{"id":100000000,"name":"main","signature":"func main()","file":"build/pause/windows/wincat/wincat.go","code":"func main() {\n\tif len(os.Args) != 3 {\n\t\tlog.Fatalln(\"usage: wincat \u003chost\u003e \u003cport\u003e\")\n\t}\n\thost := os.Args[1]\n\tport := os.Args[2]\n\n\taddr, err := net.ResolveTCPAddr(\"tcp\", fmt.Sprintf(\"%s:%s\", host, port))\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to resolve TCP addr %v %v\", host, port)\n\t}\n\n\tconn, err := net.DialTCP(\"tcp\", nil, addr)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to connect to %s:%s because %s\", host, port, err)\n\t}\n\tdefer conn.Close()\n\n\tvar wg sync.WaitGroup\n\twg.Add(2)\n\n\tgo func() {\n\t\tdefer func() {\n\t\t\tos.Stdout.Close()\n\t\t\tos.Stdin.Close()\n\t\t\tconn.CloseRead()\n\t\t\twg.Done()\n\t\t}()\n\n\t\t_, err := io.Copy(os.Stdout, conn)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error while copying stream to stdout: %v\", err)\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tdefer func() {\n\t\t\tconn.CloseWrite()\n\t\t\twg.Done()\n\t\t}()\n\n\t\t_, err := io.Copy(conn, os.Stdin)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error while copying stream from stdin: %v\", err)\n\t\t}\n\t}()\n\n\twg.Wait()\n}","line":{"from":30,"to":78}} {"id":100000001,"name":"main","signature":"func main()","file":"cluster/gce/gci/mounter/mounter.go","code":"func main() {\n\n\tif len(os.Args) \u003c 2 {\n\t\tfmt.Fprintf(os.Stderr, \"Command failed: must provide a command to run.\\n\")\n\t\treturn\n\t}\n\tpath, _ := filepath.Split(os.Args[0])\n\trootfsPath := filepath.Join(path, rootfs)\n\tif _, err := os.Stat(rootfsPath); os.IsNotExist(err) {\n\t\trootfsPath = defaultRootfs\n\t}\n\tcommand := os.Args[1]\n\tswitch command {\n\tcase mountCmd:\n\t\tmountErr := mountInChroot(rootfsPath, os.Args[2:])\n\t\tif mountErr != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Mount failed: %v\", mountErr)\n\t\t\tos.Exit(1)\n\t\t}\n\tdefault:\n\t\tfmt.Fprintf(os.Stderr, \"Unknown command, must be %s\", mountCmd)\n\t\tos.Exit(1)\n\n\t}\n}","line":{"from":37,"to":61}} {"id":100000002,"name":"mountInChroot","signature":"func mountInChroot(rootfsPath string, args []string) error","file":"cluster/gce/gci/mounter/mounter.go","code":"// MountInChroot is to run mount within chroot with the passing root directory\nfunc mountInChroot(rootfsPath string, args []string) error {\n\tif _, err := os.Stat(rootfsPath); os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"path \u003c%s\u003e does not exist\", rootfsPath)\n\t}\n\targs = append([]string{rootfsPath, mountCmd}, args...)\n\toutput, err := exec.Command(chrootCmd, args...).CombinedOutput()\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\tif !strings.EqualFold(string(output), nfsRPCBindErrMsg) {\n\t\t// Mount failed but not because of RPC bind error\n\t\treturn fmt.Errorf(\"mount failed: %v\\nMounting command: %s\\nMounting arguments: %v\\nOutput: %s\", err, chrootCmd, args, string(output))\n\t}\n\n\t// Mount failed because it is NFS V3 and we need to run rpcBind\n\toutput, err = exec.Command(chrootCmd, rootfsPath, rpcBindCmd, \"-w\").CombinedOutput()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"mount issued for NFS V3 but unable to run rpcbind:\\n Output: %s\\n Error: %v\", string(output), err)\n\t}\n\n\t// Rpcbind is running, try mounting again\n\toutput, err = exec.Command(chrootCmd, args...).CombinedOutput()\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"mount failed for NFS V3 even after running rpcBind %s, %v\", string(output), err)\n\t}\n\n\treturn nil\n}","line":{"from":63,"to":93}} {"id":100000003,"name":"registerFlags","signature":"func registerFlags(fs *pflag.FlagSet)","file":"cluster/images/etcd-version-monitor/etcd-version-monitor.go","code":"func registerFlags(fs *pflag.FlagSet) {\n\tfs.StringVar(\u0026listenAddress, \"listen-address\", \"localhost:9101\", \"Address to listen on for serving prometheus metrics\")\n\tfs.StringVar(\u0026metricsPath, \"metrics-path\", \"/metrics\", \"Path under which prometheus metrics are to be served\")\n\tfs.StringVar(\u0026etcdVersionScrapeURI, \"etcd-version-scrape-uri\", \"http://localhost:2379/version\", \"URI to scrape etcd version info\")\n\tfs.StringVar(\u0026etcdMetricsScrapeURI, \"etcd-metrics-scrape-uri\", \"http://localhost:2379/metrics\", \"URI to scrape etcd metrics\")\n\tfs.DurationVar(\u0026scrapeTimeout, \"scrape-timeout\", 15*time.Second, \"Timeout for trying to get stats from etcd\")\n}","line":{"from":46,"to":52}} {"id":100000004,"name":"Gather","signature":"func (m *monitorGatherer) Gather() ([]*dto.MetricFamily, error)","file":"cluster/images/etcd-version-monitor/etcd-version-monitor.go","code":"func (m *monitorGatherer) Gather() ([]*dto.MetricFamily, error) {\n\tetcdMetrics, err := scrapeMetrics()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\texported, err := m.rewriteExportedMetrics(etcdMetrics)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcustom, err := customMetricRegistry.Gather()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := make([]*dto.MetricFamily, 0, len(exported)+len(custom))\n\tresult = append(result, exported...)\n\tresult = append(result, custom...)\n\treturn result, nil\n}","line":{"from":153,"to":170}} {"id":100000005,"name":"rewriteExportedMetrics","signature":"func (m *monitorGatherer) rewriteExportedMetrics(metrics map[string]*dto.MetricFamily) ([]*dto.MetricFamily, error)","file":"cluster/images/etcd-version-monitor/etcd-version-monitor.go","code":"func (m *monitorGatherer) rewriteExportedMetrics(metrics map[string]*dto.MetricFamily) ([]*dto.MetricFamily, error) {\n\tresults := make([]*dto.MetricFamily, 0, len(metrics))\n\tfor n, mf := range metrics {\n\t\tif e, ok := m.exported[n]; ok {\n\t\t\t// Apply rewrite rules for metrics that have them.\n\t\t\tif e.rewriters == nil {\n\t\t\t\tresults = append(results, mf)\n\t\t\t} else {\n\t\t\t\tfor _, rewriter := range e.rewriters {\n\t\t\t\t\tnew, err := rewriter(mf)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tresults = append(results, new)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// Proxy all metrics without any rewrite rules directly.\n\t\t\tresults = append(results, mf)\n\t\t}\n\t}\n\treturn results, nil\n}","line":{"from":172,"to":194}} {"id":100000006,"name":"getVersion","signature":"func getVersion(lastSeenBinaryVersion *string) error","file":"cluster/images/etcd-version-monitor/etcd-version-monitor.go","code":"// Function for fetching etcd version info and feeding it to the prometheus metric.\nfunc getVersion(lastSeenBinaryVersion *string) error {\n\t// Create the get request for the etcd version endpoint.\n\treq, err := http.NewRequest(\"GET\", etcdVersionScrapeURI, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create GET request for etcd version: %v\", err)\n\t}\n\n\t// Send the get request and receive a response.\n\tclient := \u0026http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to receive GET response for etcd version: %v\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\t// Obtain EtcdVersion from the JSON response.\n\tvar version EtcdVersion\n\tif err := json.NewDecoder(resp.Body).Decode(\u0026version); err != nil {\n\t\treturn fmt.Errorf(\"failed to decode etcd version JSON: %v\", err)\n\t}\n\n\t// Return without updating the version if it stayed the same since last time.\n\tif *lastSeenBinaryVersion == version.BinaryVersion {\n\t\treturn nil\n\t}\n\n\t// Delete the metric for the previous version.\n\tif *lastSeenBinaryVersion != \"\" {\n\t\tdeleted := etcdVersion.Delete(metrics.Labels{\"binary_version\": *lastSeenBinaryVersion})\n\t\tif !deleted {\n\t\t\treturn errors.New(\"failed to delete previous version's metric\")\n\t\t}\n\t}\n\n\t// Record the new version in a metric.\n\tetcdVersion.With(metrics.Labels{\n\t\t\"binary_version\": version.BinaryVersion,\n\t}).Set(0)\n\t*lastSeenBinaryVersion = version.BinaryVersion\n\treturn nil\n}","line":{"from":202,"to":243}} {"id":100000007,"name":"getVersionPeriodically","signature":"func getVersionPeriodically(stopCh \u003c-chan struct{})","file":"cluster/images/etcd-version-monitor/etcd-version-monitor.go","code":"// Periodically fetches etcd version info.\nfunc getVersionPeriodically(stopCh \u003c-chan struct{}) {\n\tlastSeenBinaryVersion := \"\"\n\tfor {\n\t\tif err := getVersion(\u0026lastSeenBinaryVersion); err != nil {\n\t\t\tklog.Errorf(\"Failed to fetch etcd version: %v\", err)\n\t\t}\n\t\tselect {\n\t\tcase \u003c-stopCh:\n\t\t\treturn\n\t\tcase \u003c-time.After(scrapeTimeout):\n\t\t}\n\t}\n}","line":{"from":245,"to":258}} {"id":100000008,"name":"scrapeMetrics","signature":"func scrapeMetrics() (map[string]*dto.MetricFamily, error)","file":"cluster/images/etcd-version-monitor/etcd-version-monitor.go","code":"// scrapeMetrics scrapes the prometheus metrics from the etcd metrics URI.\nfunc scrapeMetrics() (map[string]*dto.MetricFamily, error) {\n\treq, err := http.NewRequest(\"GET\", etcdMetricsScrapeURI, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create GET request for etcd metrics: %v\", err)\n\t}\n\n\t// Send the get request and receive a response.\n\tclient := \u0026http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to receive GET response for etcd metrics: %v\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\treturn testutil.TextToMetricFamilies(resp.Body)\n}","line":{"from":260,"to":276}} {"id":100000009,"name":"renameMetric","signature":"func renameMetric(mf *dto.MetricFamily, name string)","file":"cluster/images/etcd-version-monitor/etcd-version-monitor.go","code":"func renameMetric(mf *dto.MetricFamily, name string) {\n\tmf.Name = \u0026name\n}","line":{"from":278,"to":280}} {"id":100000010,"name":"renameLabels","signature":"func renameLabels(mf *dto.MetricFamily, nameMapping map[string]string)","file":"cluster/images/etcd-version-monitor/etcd-version-monitor.go","code":"func renameLabels(mf *dto.MetricFamily, nameMapping map[string]string) {\n\tfor _, m := range mf.Metric {\n\t\tfor _, lbl := range m.Label {\n\t\t\tif alias, ok := nameMapping[*lbl.Name]; ok {\n\t\t\t\tlbl.Name = \u0026alias\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":282,"to":290}} {"id":100000011,"name":"filterMetricsByLabels","signature":"func filterMetricsByLabels(mf *dto.MetricFamily, labelValues map[string]string)","file":"cluster/images/etcd-version-monitor/etcd-version-monitor.go","code":"func filterMetricsByLabels(mf *dto.MetricFamily, labelValues map[string]string) {\n\tbuf := mf.Metric[:0]\n\tfor _, m := range mf.Metric {\n\t\tshouldRemove := false\n\t\tfor _, lbl := range m.Label {\n\t\t\tif val, ok := labelValues[*lbl.Name]; ok \u0026\u0026 val != *lbl.Value {\n\t\t\t\tshouldRemove = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !shouldRemove {\n\t\t\tbuf = append(buf, m)\n\t\t}\n\t}\n\tmf.Metric = buf\n}","line":{"from":292,"to":307}} {"id":100000012,"name":"groupCounterMetricsByLabels","signature":"func groupCounterMetricsByLabels(mf *dto.MetricFamily, names map[string]bool)","file":"cluster/images/etcd-version-monitor/etcd-version-monitor.go","code":"func groupCounterMetricsByLabels(mf *dto.MetricFamily, names map[string]bool) {\n\tbuf := mf.Metric[:0]\n\tdeleteLabels(mf, names)\n\tbyLabels := map[string]*dto.Metric{}\n\tfor _, m := range mf.Metric {\n\t\tif metric, ok := byLabels[labelsKey(m.Label)]; ok {\n\t\t\tmetric.Counter.Value = proto.Float64(*metric.Counter.Value + *m.Counter.Value)\n\t\t} else {\n\t\t\tbyLabels[labelsKey(m.Label)] = m\n\t\t\tbuf = append(buf, m)\n\t\t}\n\t}\n\tmf.Metric = buf\n}","line":{"from":309,"to":322}} {"id":100000013,"name":"labelsKey","signature":"func labelsKey(lbls []*dto.LabelPair) string","file":"cluster/images/etcd-version-monitor/etcd-version-monitor.go","code":"func labelsKey(lbls []*dto.LabelPair) string {\n\tvar buf bytes.Buffer\n\tfor i, lbl := range lbls {\n\t\tbuf.WriteString(lbl.String())\n\t\tif i \u003c len(lbls)-1 {\n\t\t\tbuf.WriteString(\",\")\n\t\t}\n\t}\n\treturn buf.String()\n}","line":{"from":324,"to":333}} {"id":100000014,"name":"deleteLabels","signature":"func deleteLabels(mf *dto.MetricFamily, names map[string]bool)","file":"cluster/images/etcd-version-monitor/etcd-version-monitor.go","code":"func deleteLabels(mf *dto.MetricFamily, names map[string]bool) {\n\tfor _, m := range mf.Metric {\n\t\tbuf := m.Label[:0]\n\t\tfor _, lbl := range m.Label {\n\t\t\tshouldRemove := names[*lbl.Name]\n\t\t\tif !shouldRemove {\n\t\t\t\tbuf = append(buf, lbl)\n\t\t\t}\n\t\t}\n\t\tm.Label = buf\n\t}\n}","line":{"from":335,"to":346}} {"id":100000015,"name":"identity","signature":"func identity(mf *dto.MetricFamily) (*dto.MetricFamily, error)","file":"cluster/images/etcd-version-monitor/etcd-version-monitor.go","code":"func identity(mf *dto.MetricFamily) (*dto.MetricFamily, error) {\n\treturn mf, nil\n}","line":{"from":348,"to":350}} {"id":100000016,"name":"deepCopyMetricFamily","signature":"func deepCopyMetricFamily(mf *dto.MetricFamily) *dto.MetricFamily","file":"cluster/images/etcd-version-monitor/etcd-version-monitor.go","code":"func deepCopyMetricFamily(mf *dto.MetricFamily) *dto.MetricFamily {\n\tr := \u0026dto.MetricFamily{}\n\tr.Name = mf.Name\n\tr.Help = mf.Help\n\tr.Type = mf.Type\n\tr.Metric = make([]*dto.Metric, len(mf.Metric))\n\tfor i, m := range mf.Metric {\n\t\tr.Metric[i] = deepCopyMetric(m)\n\t}\n\treturn r\n}","line":{"from":352,"to":362}} {"id":100000017,"name":"deepCopyMetric","signature":"func deepCopyMetric(m *dto.Metric) *dto.Metric","file":"cluster/images/etcd-version-monitor/etcd-version-monitor.go","code":"func deepCopyMetric(m *dto.Metric) *dto.Metric {\n\tr := \u0026dto.Metric{}\n\tr.Label = make([]*dto.LabelPair, len(m.Label))\n\tfor i, lp := range m.Label {\n\t\tr.Label[i] = deepCopyLabelPair(lp)\n\t}\n\tr.Gauge = m.Gauge\n\tr.Counter = m.Counter\n\tr.Summary = m.Summary\n\tr.Untyped = m.Untyped\n\tr.Histogram = m.Histogram\n\tr.TimestampMs = m.TimestampMs\n\treturn r\n}","line":{"from":364,"to":377}} {"id":100000018,"name":"deepCopyLabelPair","signature":"func deepCopyLabelPair(lp *dto.LabelPair) *dto.LabelPair","file":"cluster/images/etcd-version-monitor/etcd-version-monitor.go","code":"func deepCopyLabelPair(lp *dto.LabelPair) *dto.LabelPair {\n\tr := \u0026dto.LabelPair{}\n\tr.Name = lp.Name\n\tr.Value = lp.Value\n\treturn r\n}","line":{"from":379,"to":384}} {"id":100000019,"name":"main","signature":"func main()","file":"cluster/images/etcd-version-monitor/etcd-version-monitor.go","code":"func main() {\n\t// Register the commandline flags passed to the tool.\n\tregisterFlags(pflag.CommandLine)\n\tpflag.CommandLine.AddGoFlagSet(goflag.CommandLine)\n\tpflag.Parse()\n\n\t// Register the metrics we defined above with prometheus.\n\tcustomMetricRegistry.MustRegister(etcdVersion)\n\n\t// Spawn threads for periodically scraping etcd version metrics.\n\tstopCh := make(chan struct{})\n\tdefer close(stopCh)\n\tgo getVersionPeriodically(stopCh)\n\n\t// Serve our metrics on listenAddress/metricsPath.\n\tklog.Infof(\"Listening on: %v\", listenAddress)\n\thttp.Handle(metricsPath, metrics.HandlerFor(gatherer, metrics.HandlerOpts{}))\n\tklog.Errorf(\"Stopped listening/serving metrics: %v\", http.ListenAndServe(listenAddress, nil))\n}","line":{"from":386,"to":404}} {"id":100000020,"name":"copyFile","signature":"func copyFile(source, dest string) error","file":"cluster/images/etcd/migrate/copy_file.go","code":"func copyFile(source, dest string) error {\n\tsf, err := os.Open(source)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to open source file [%s]: %q\", source, err)\n\t}\n\tdefer sf.Close()\n\tfi, err := sf.Stat()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to stat source file [%s]: %q\", source, err)\n\t}\n\n\tdir := filepath.Dir(dest)\n\tif err := os.MkdirAll(dir, 0755); err != nil {\n\t\treturn fmt.Errorf(\"unable to create directory [%s]: %q\", dir, err)\n\t}\n\tdf, err := os.Create(dest)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to create destination file [%s]: %q\", dest, err)\n\t}\n\tdefer df.Close()\n\n\t_, err = io.Copy(df, sf)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to copy [%s] to [%s]: %q\", source, dest, err)\n\t}\n\n\tif err := os.Chmod(dest, fi.Mode()); err != nil {\n\t\treturn fmt.Errorf(\"unable to close destination file: %q\", err)\n\t}\n\treturn nil\n}","line":{"from":26,"to":56}} {"id":100000021,"name":"OpenOrCreateDataDirectory","signature":"func OpenOrCreateDataDirectory(path string) (*DataDirectory, error)","file":"cluster/images/etcd/migrate/data_dir.go","code":"// OpenOrCreateDataDirectory opens a data directory, creating the directory\n// if it doesn't not already exist.\nfunc OpenOrCreateDataDirectory(path string) (*DataDirectory, error) {\n\texists, err := exists(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\tklog.Infof(\"data directory '%s' does not exist, creating it\", path)\n\t\terr := os.MkdirAll(path, 0777)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to create data directory %s: %v\", path, err)\n\t\t}\n\t}\n\tversionFile := \u0026VersionFile{\n\t\tpath: filepath.Join(path, versionFilename),\n\t}\n\treturn \u0026DataDirectory{path, versionFile}, nil\n}","line":{"from":38,"to":56}} {"id":100000022,"name":"Initialize","signature":"func (d *DataDirectory) Initialize(target *EtcdVersionPair) error","file":"cluster/images/etcd/migrate/data_dir.go","code":"// Initialize set the version.txt to the target version if the data\n// directory is empty. If the data directory is non-empty, no\n// version.txt file will be written since the actual version of etcd\n// used to create the data is unknown.\nfunc (d *DataDirectory) Initialize(target *EtcdVersionPair) error {\n\tisEmpty, err := d.IsEmpty()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif isEmpty {\n\t\tklog.Infof(\"data directory '%s' is empty, writing target version '%s' to version.txt\", d.path, target)\n\t\terr = d.versionFile.Write(target)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to write version.txt to '%s': %v\", d.path, err)\n\t\t}\n\t\treturn nil\n\t}\n\treturn nil\n}","line":{"from":58,"to":76}} {"id":100000023,"name":"Backup","signature":"func (d *DataDirectory) Backup() error","file":"cluster/images/etcd/migrate/data_dir.go","code":"// Backup creates a backup copy of data directory.\nfunc (d *DataDirectory) Backup() error {\n\tbackupDir := fmt.Sprintf(\"%s.bak\", d.path)\n\terr := os.RemoveAll(backupDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.MkdirAll(backupDir, 0777)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = copyDirectory(d.path, backupDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":78,"to":95}} {"id":100000024,"name":"IsEmpty","signature":"func (d *DataDirectory) IsEmpty() (bool, error)","file":"cluster/images/etcd/migrate/data_dir.go","code":"// IsEmpty returns true if the data directory is entirely empty.\nfunc (d *DataDirectory) IsEmpty() (bool, error) {\n\tdir, err := os.Open(d.path)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"failed to open data directory %s: %v\", d.path, err)\n\t}\n\tdefer dir.Close()\n\t_, err = dir.Readdirnames(1)\n\tif err == io.EOF {\n\t\treturn true, nil\n\t}\n\treturn false, err\n}","line":{"from":97,"to":109}} {"id":100000025,"name":"String","signature":"func (d *DataDirectory) String() string","file":"cluster/images/etcd/migrate/data_dir.go","code":"// String returns the data directory path.\nfunc (d *DataDirectory) String() string {\n\treturn d.path\n}","line":{"from":111,"to":114}} {"id":100000026,"name":"nextPath","signature":"func (v *VersionFile) nextPath() string","file":"cluster/images/etcd/migrate/data_dir.go","code":"func (v *VersionFile) nextPath() string {\n\treturn fmt.Sprintf(\"%s-next\", v.path)\n}","line":{"from":123,"to":125}} {"id":100000027,"name":"Exists","signature":"func (v *VersionFile) Exists() (bool, error)","file":"cluster/images/etcd/migrate/data_dir.go","code":"// Exists returns true if a version.txt file exists on the file system.\nfunc (v *VersionFile) Exists() (bool, error) {\n\treturn exists(v.path)\n}","line":{"from":127,"to":130}} {"id":100000028,"name":"Read","signature":"func (v *VersionFile) Read() (*EtcdVersionPair, error)","file":"cluster/images/etcd/migrate/data_dir.go","code":"// Read parses the version.txt file and returns it's contents.\nfunc (v *VersionFile) Read() (*EtcdVersionPair, error) {\n\tdata, err := os.ReadFile(v.path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read version file %s: %v\", v.path, err)\n\t}\n\ttxt := strings.TrimSpace(string(data))\n\tvp, err := ParseEtcdVersionPair(txt)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse etcd '\u003cversion\u003e/\u003cstorage-version\u003e' string from version.txt file contents '%s': %v\", txt, err)\n\t}\n\treturn vp, nil\n}","line":{"from":132,"to":144}} {"id":100000029,"name":"equals","signature":"func (v *VersionFile) equals(vp *EtcdVersionPair) (bool, error)","file":"cluster/images/etcd/migrate/data_dir.go","code":"// equals returns true iff VersionFile exists and contains given EtcdVersionPair.\nfunc (v *VersionFile) equals(vp *EtcdVersionPair) (bool, error) {\n\texists, err := v.Exists()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif !exists {\n\t\treturn false, nil\n\t}\n\tcvp, err := v.Read()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn vp.Equals(cvp), nil\n}","line":{"from":146,"to":160}} {"id":100000030,"name":"Write","signature":"func (v *VersionFile) Write(vp *EtcdVersionPair) error","file":"cluster/images/etcd/migrate/data_dir.go","code":"// Write creates or overwrites the contents of the version.txt file with the given EtcdVersionPair.\nfunc (v *VersionFile) Write(vp *EtcdVersionPair) error {\n\t// We do write only if file content differs from given EtcdVersionPair.\n\tisUpToDate, err := v.equals(vp)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to to check if version file %s should be changed: %v\", v.path, err)\n\t}\n\tif isUpToDate {\n\t\treturn nil\n\t}\n\t// We do write + rename instead of just write to protect from version.txt\n\t// corruption under full disk condition.\n\t// See https://github.com/kubernetes/kubernetes/issues/98989.\n\terr = os.WriteFile(v.nextPath(), []byte(vp.String()), 0666)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to write new version file %s: %v\", v.nextPath(), err)\n\t}\n\treturn os.Rename(v.nextPath(), v.path)\n}","line":{"from":162,"to":180}} {"id":100000031,"name":"exists","signature":"func exists(path string) (bool, error)","file":"cluster/images/etcd/migrate/data_dir.go","code":"func exists(path string) (bool, error) {\n\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\treturn false, nil\n\t} else if err != nil {\n\t\treturn false, err\n\t}\n\treturn true, nil\n}","line":{"from":182,"to":189}} {"id":100000032,"name":"main","signature":"func main()","file":"cluster/images/etcd/migrate/migrate.go","code":"func main() {\n\tregisterFlags(migrateCmd.Flags(), \u0026opts)\n\terr := migrateCmd.Execute()\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to execute migratecmd: %s\", err)\n\t}\n}","line":{"from":47,"to":53}} {"id":100000033,"name":"runMigrate","signature":"func runMigrate()","file":"cluster/images/etcd/migrate/migrate.go","code":"// runMigrate starts the migration.\nfunc runMigrate() {\n\tif err := opts.validateAndDefault(); err != nil {\n\t\tklog.Fatalf(\"%v\", err)\n\t}\n\tcopyBinaries()\n\n\ttarget := \u0026EtcdVersionPair{\n\t\tversion: MustParseEtcdVersion(opts.targetVersion),\n\t\tstorageVersion: MustParseEtcdStorageVersion(opts.targetStorage),\n\t}\n\n\tmigrate(\n\t\topts.name, opts.port, opts.peerListenUrls, opts.peerAdvertiseUrls, opts.clientListenUrls,\n\t\topts.binDir, opts.dataDir, opts.etcdDataPrefix, opts.ttlKeysDirectory, opts.initialCluster,\n\t\ttarget, opts.supportedVersions, opts.etcdServerArgs)\n}","line":{"from":55,"to":71}} {"id":100000034,"name":"copyBinaries","signature":"func copyBinaries()","file":"cluster/images/etcd/migrate/migrate.go","code":"func copyBinaries() {\n\tif val, err := lookupEnv(\"DO_NOT_MOVE_BINARIES\"); err != nil || val != \"true\" {\n\t\tetcdVersioned := fmt.Sprintf(\"etcd-%s\", opts.targetVersion)\n\t\tetcdctlVersioned := fmt.Sprintf(\"etcdctl-%s\", opts.targetVersion)\n\t\tif err := copyFile(filepath.Join(opts.binDir, etcdVersioned), filepath.Join(opts.binDir, \"etcd\")); err != nil {\n\t\t\tklog.Fatalf(\"Failed to copy %s: %v\", etcdVersioned, err)\n\t\t}\n\t\tif err := copyFile(filepath.Join(opts.binDir, etcdctlVersioned), filepath.Join(opts.binDir, \"etcdctl\")); err != nil {\n\t\t\tklog.Fatalf(\"Failed to copy %s: %v\", etcdctlVersioned, err)\n\t\t}\n\t}\n}","line":{"from":73,"to":84}} {"id":100000035,"name":"migrate","signature":"func migrate(name string, port uint64, peerListenUrls string, peerAdvertiseUrls string, clientListenUrls string,","file":"cluster/images/etcd/migrate/migrate.go","code":"// migrate opens or initializes the etcd data directory, configures the migrator, and starts the migration.\nfunc migrate(name string, port uint64, peerListenUrls string, peerAdvertiseUrls string, clientListenUrls string,\n\tbinPath string, dataDirPath string, etcdDataPrefix string, ttlKeysDirectory string,\n\tinitialCluster string, target *EtcdVersionPair, bundledVersions SupportedVersions, etcdServerArgs string) {\n\n\tdataDir, err := OpenOrCreateDataDirectory(dataDirPath)\n\tif err != nil {\n\t\tklog.Fatalf(\"Error opening or creating data directory %s: %v\", dataDirPath, err)\n\t}\n\n\tcfg := \u0026EtcdMigrateCfg{\n\t\tbinPath: binPath,\n\t\tname: name,\n\t\tport: port,\n\t\tpeerListenUrls: peerListenUrls,\n\t\tpeerAdvertiseUrls: peerAdvertiseUrls,\n\t\tclientListenUrls: clientListenUrls,\n\t\tetcdDataPrefix: etcdDataPrefix,\n\t\tttlKeysDirectory: ttlKeysDirectory,\n\t\tinitialCluster: initialCluster,\n\t\tsupportedVersions: bundledVersions,\n\t\tdataDirectory: dataDirPath,\n\t\tetcdServerArgs: etcdServerArgs,\n\t}\n\tclient, err := NewEtcdMigrateClient(cfg)\n\tif err != nil {\n\t\tklog.Fatalf(\"Migration failed: %v\", err)\n\t}\n\tdefer client.Close()\n\n\tmigrator := \u0026Migrator{cfg, dataDir, client}\n\n\terr = migrator.MigrateIfNeeded(target)\n\tif err != nil {\n\t\tklog.Fatalf(\"Migration failed: %v\", err)\n\t}\n}","line":{"from":86,"to":122}} {"id":100000036,"name":"NewEtcdMigrateClient","signature":"func NewEtcdMigrateClient(cfg *EtcdMigrateCfg) (EtcdMigrateClient, error)","file":"cluster/images/etcd/migrate/migrate_client.go","code":"// NewEtcdMigrateClient creates a new EtcdMigrateClient from the given EtcdMigrateCfg.\nfunc NewEtcdMigrateClient(cfg *EtcdMigrateCfg) (EtcdMigrateClient, error) {\n\treturn \u0026CombinedEtcdClient{cfg}, nil\n}","line":{"from":40,"to":43}} {"id":100000037,"name":"Close","signature":"func (e *CombinedEtcdClient) Close() error","file":"cluster/images/etcd/migrate/migrate_client.go","code":"// Close closes the client and releases any resources it holds.\nfunc (e *CombinedEtcdClient) Close() error {\n\treturn nil\n}","line":{"from":45,"to":48}} {"id":100000038,"name":"SetEtcdVersionKeyValue","signature":"func (e *CombinedEtcdClient) SetEtcdVersionKeyValue(version *EtcdVersion) error","file":"cluster/images/etcd/migrate/migrate_client.go","code":"// SetEtcdVersionKeyValue writes the given version to the etcd 'etcd_version' key.\n// If no error is returned, the write was successful, indicating the etcd server is available\n// and able to perform consensus writes.\nfunc (e *CombinedEtcdClient) SetEtcdVersionKeyValue(version *EtcdVersion) error {\n\treturn e.Put(version, \"etcd_version\", version.String())\n}","line":{"from":50,"to":55}} {"id":100000039,"name":"Put","signature":"func (e *CombinedEtcdClient) Put(version *EtcdVersion, key, value string) error","file":"cluster/images/etcd/migrate/migrate_client.go","code":"// Put write a single key value pair to etcd.\nfunc (e *CombinedEtcdClient) Put(version *EtcdVersion, key, value string) error {\n\tv3client, err := e.clientV3()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer v3client.Close()\n\t_, err = v3client.KV.Put(context.Background(), key, value)\n\treturn err\n}","line":{"from":57,"to":66}} {"id":100000040,"name":"Get","signature":"func (e *CombinedEtcdClient) Get(version *EtcdVersion, key string) (string, error)","file":"cluster/images/etcd/migrate/migrate_client.go","code":"// Get reads a single value for a given key.\nfunc (e *CombinedEtcdClient) Get(version *EtcdVersion, key string) (string, error) {\n\tv3client, err := e.clientV3()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer v3client.Close()\n\tresp, err := v3client.KV.Get(context.Background(), key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tkvs := resp.Kvs\n\tif len(kvs) != 1 {\n\t\treturn \"\", fmt.Errorf(\"expected exactly one value for key %s but got %d\", key, len(kvs))\n\t}\n\n\treturn string(kvs[0].Value), nil\n}","line":{"from":68,"to":85}} {"id":100000041,"name":"clientV3","signature":"func (e *CombinedEtcdClient) clientV3() (*clientv3.Client, error)","file":"cluster/images/etcd/migrate/migrate_client.go","code":"func (e *CombinedEtcdClient) clientV3() (*clientv3.Client, error) {\n\treturn clientv3.New(clientv3.Config{\n\t\tEndpoints: []string{e.endpoint()},\n\t\tDialTimeout: 20 * time.Second,\n\t\tDialOptions: []grpc.DialOption{\n\t\t\tgrpc.WithBlock(), // block until the underlying connection is up\n\t\t},\n\t})\n}","line":{"from":87,"to":95}} {"id":100000042,"name":"Backup","signature":"func (e *CombinedEtcdClient) Backup(version *EtcdVersion, backupDir string) error","file":"cluster/images/etcd/migrate/migrate_client.go","code":"// Backup creates a backup of an etcd2 data directory at the given backupDir.\nfunc (e *CombinedEtcdClient) Backup(version *EtcdVersion, backupDir string) error {\n\t// We cannot use etcd/client (v2) to make this call. It is implemented in the etcdctl client code.\n\tif version.Major != 2 {\n\t\treturn fmt.Errorf(\"etcd 2.x required but got version '%s'\", version)\n\t}\n\treturn e.runEtcdctlCommand(version,\n\t\t\"--debug\",\n\t\t\"backup\",\n\t\t\"--data-dir\", e.cfg.dataDirectory,\n\t\t\"--backup-dir\", backupDir,\n\t)\n}","line":{"from":97,"to":109}} {"id":100000043,"name":"Snapshot","signature":"func (e *CombinedEtcdClient) Snapshot(version *EtcdVersion, snapshotFile string) error","file":"cluster/images/etcd/migrate/migrate_client.go","code":"// Snapshot captures a snapshot from a running etcd3 server and saves it to the given snapshotFile.\n// We cannot use etcd/clientv3 to make this call. It is implemented in the etcdctl client code.\nfunc (e *CombinedEtcdClient) Snapshot(version *EtcdVersion, snapshotFile string) error {\n\tif version.Major != 3 {\n\t\treturn fmt.Errorf(\"etcd 3.x required but got version '%s'\", version)\n\t}\n\treturn e.runEtcdctlCommand(version,\n\t\t\"--endpoints\", e.endpoint(),\n\t\t\"snapshot\", \"save\", snapshotFile,\n\t)\n}","line":{"from":111,"to":121}} {"id":100000044,"name":"Restore","signature":"func (e *CombinedEtcdClient) Restore(version *EtcdVersion, snapshotFile string) error","file":"cluster/images/etcd/migrate/migrate_client.go","code":"// Restore restores a given snapshotFile into the data directory specified this clients config.\nfunc (e *CombinedEtcdClient) Restore(version *EtcdVersion, snapshotFile string) error {\n\t// We cannot use etcd/clientv3 to make this call. It is implemented in the etcdctl client code.\n\tif version.Major != 3 {\n\t\treturn fmt.Errorf(\"etcd 3.x required but got version '%s'\", version)\n\t}\n\treturn e.runEtcdctlCommand(version,\n\t\t\"snapshot\", \"restore\", snapshotFile,\n\t\t\"--data-dir\", e.cfg.dataDirectory,\n\t\t\"--name\", e.cfg.name,\n\t\t\"--initial-advertise-peer-urls\", e.cfg.peerAdvertiseUrls,\n\t\t\"--initial-cluster\", e.cfg.initialCluster,\n\t)\n}","line":{"from":123,"to":136}} {"id":100000045,"name":"Migrate","signature":"func (e *CombinedEtcdClient) Migrate(version *EtcdVersion) error","file":"cluster/images/etcd/migrate/migrate_client.go","code":"// Migrate upgrades a 'etcd2' storage version data directory to a 'etcd3' storage version\n// data directory.\nfunc (e *CombinedEtcdClient) Migrate(version *EtcdVersion) error {\n\t// We cannot use etcd/clientv3 to make this call as it is implemented in etcd/etcdctl.\n\tif version.Major != 3 {\n\t\treturn fmt.Errorf(\"etcd 3.x required but got version '%s'\", version)\n\t}\n\treturn e.runEtcdctlCommand(version,\n\t\t\"migrate\",\n\t\t\"--data-dir\", e.cfg.dataDirectory,\n\t)\n}","line":{"from":138,"to":149}} {"id":100000046,"name":"runEtcdctlCommand","signature":"func (e *CombinedEtcdClient) runEtcdctlCommand(version *EtcdVersion, args ...string) error","file":"cluster/images/etcd/migrate/migrate_client.go","code":"func (e *CombinedEtcdClient) runEtcdctlCommand(version *EtcdVersion, args ...string) error {\n\tetcdctlCmd := exec.Command(filepath.Join(e.cfg.binPath, fmt.Sprintf(\"etcdctl-%s\", version)), args...)\n\tetcdctlCmd.Env = []string{fmt.Sprintf(\"ETCDCTL_API=%d\", version.Major)}\n\tetcdctlCmd.Stdout = os.Stdout\n\tetcdctlCmd.Stderr = os.Stderr\n\treturn etcdctlCmd.Run()\n}","line":{"from":151,"to":157}} {"id":100000047,"name":"AttachLease","signature":"func (e *CombinedEtcdClient) AttachLease(leaseDuration time.Duration) error","file":"cluster/images/etcd/migrate/migrate_client.go","code":"// AttachLease attaches leases of the given leaseDuration to all the etcd objects under\n// ttlKeysDirectory specified in this client's config.\nfunc (e *CombinedEtcdClient) AttachLease(leaseDuration time.Duration) error {\n\tttlKeysPrefix := e.cfg.ttlKeysDirectory\n\t// Make sure that ttlKeysPrefix is ended with \"/\" so that we only get children \"directories\".\n\tif !strings.HasSuffix(ttlKeysPrefix, \"/\") {\n\t\tttlKeysPrefix += \"/\"\n\t}\n\tctx := context.Background()\n\n\tv3client, err := e.clientV3()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer v3client.Close()\n\tobjectsResp, err := v3client.KV.Get(ctx, ttlKeysPrefix, clientv3.WithPrefix())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error while getting objects to attach to the lease\")\n\t}\n\n\tlease, err := v3client.Lease.Grant(ctx, int64(leaseDuration/time.Second))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error while creating lease: %v\", err)\n\t}\n\tklog.Infof(\"Lease with TTL: %v created\", lease.TTL)\n\n\tklog.Infof(\"Attaching lease to %d entries\", len(objectsResp.Kvs))\n\tfor _, kv := range objectsResp.Kvs {\n\t\tputResp, err := v3client.KV.Put(ctx, string(kv.Key), string(kv.Value), clientv3.WithLease(lease.ID), clientv3.WithPrevKV())\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Error while attaching lease to: %s\", string(kv.Key))\n\t\t}\n\t\tif !bytes.Equal(putResp.PrevKv.Value, kv.Value) {\n\t\t\treturn fmt.Errorf(\"concurrent access to key detected when setting lease on %s, expected previous value of %s but got %s\",\n\t\t\t\tkv.Key, kv.Value, putResp.PrevKv.Value)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":159,"to":197}} {"id":100000048,"name":"endpoint","signature":"func (e *CombinedEtcdClient) endpoint() string","file":"cluster/images/etcd/migrate/migrate_client.go","code":"func (e *CombinedEtcdClient) endpoint() string {\n\treturn fmt.Sprintf(\"http://127.0.0.1:%d\", e.cfg.port)\n}","line":{"from":199,"to":201}} {"id":100000049,"name":"NewEtcdMigrateServer","signature":"func NewEtcdMigrateServer(cfg *EtcdMigrateCfg, client EtcdMigrateClient) *EtcdMigrateServer","file":"cluster/images/etcd/migrate/migrate_server.go","code":"// NewEtcdMigrateServer creates a EtcdMigrateServer for starting and stopping a etcd server at the given version.\nfunc NewEtcdMigrateServer(cfg *EtcdMigrateCfg, client EtcdMigrateClient) *EtcdMigrateServer {\n\treturn \u0026EtcdMigrateServer{cfg: cfg, client: client}\n}","line":{"from":36,"to":39}} {"id":100000050,"name":"Start","signature":"func (r *EtcdMigrateServer) Start(version *EtcdVersion) error","file":"cluster/images/etcd/migrate/migrate_server.go","code":"// Start starts an etcd server as a separate process, waits until it has started, and returns a exec.Cmd.\n// TODO: Add support for listening to client via TLS.\nfunc (r *EtcdMigrateServer) Start(version *EtcdVersion) error {\n\tetcdCmd := exec.Command(\n\t\tfmt.Sprintf(\"%s/etcd-%s\", r.cfg.binPath, version),\n\t\t\"--name\", r.cfg.name,\n\t\t\"--initial-cluster\", r.cfg.initialCluster,\n\t\t\"--debug\",\n\t\t\"--data-dir\", r.cfg.dataDirectory,\n\t\t\"--listen-client-urls\", r.cfg.clientListenUrls,\n\t\t\"--advertise-client-urls\", fmt.Sprintf(\"http://127.0.0.1:%d\", r.cfg.port),\n\t\t\"--listen-peer-urls\", r.cfg.peerListenUrls,\n\t\t\"--initial-advertise-peer-urls\", r.cfg.peerAdvertiseUrls,\n\t)\n\tif r.cfg.etcdServerArgs != \"\" {\n\t\textraArgs := strings.Fields(r.cfg.etcdServerArgs)\n\t\tetcdCmd.Args = append(etcdCmd.Args, extraArgs...)\n\t}\n\tfmt.Printf(\"Starting server %s: %+v\\n\", r.cfg.name, etcdCmd.Args)\n\n\tetcdCmd.Stdout = os.Stdout\n\tetcdCmd.Stderr = os.Stderr\n\terr := etcdCmd.Start()\n\tif err != nil {\n\t\treturn err\n\t}\n\tinterval := time.NewTicker(time.Millisecond * 500)\n\tdefer interval.Stop()\n\tdone := make(chan bool)\n\tgo func() {\n\t\ttime.Sleep(time.Minute * 2)\n\t\tclose(done)\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase \u003c-interval.C:\n\t\t\terr := r.client.SetEtcdVersionKeyValue(version)\n\t\t\tif err != nil {\n\t\t\t\tklog.Infof(\"Still waiting for etcd to start, current error: %v\", err)\n\t\t\t\t// keep waiting\n\t\t\t} else {\n\t\t\t\tklog.Infof(\"Etcd on port %d is up.\", r.cfg.port)\n\t\t\t\tr.cmd = etcdCmd\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase \u003c-done:\n\t\t\terr = etcdCmd.Process.Kill()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error killing etcd: %v\", err)\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"timed out waiting for etcd on port %d\", r.cfg.port)\n\t\t}\n\t}\n}","line":{"from":41,"to":94}} {"id":100000051,"name":"Stop","signature":"func (r *EtcdMigrateServer) Stop() error","file":"cluster/images/etcd/migrate/migrate_server.go","code":"// Stop terminates the etcd server process. If the etcd server process has not been started\n// or is not still running, this returns an error.\nfunc (r *EtcdMigrateServer) Stop() error {\n\tif r.cmd == nil {\n\t\treturn fmt.Errorf(\"cannot stop EtcdMigrateServer that has not been started\")\n\t}\n\terr := r.cmd.Process.Signal(os.Interrupt)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error sending SIGINT to etcd for graceful shutdown: %v\", err)\n\t}\n\tgracefulWait := time.Minute * 2\n\tstopped := make(chan bool)\n\ttimedout := make(chan bool)\n\tgo func() {\n\t\ttime.Sleep(gracefulWait)\n\t\tclose(timedout)\n\t}()\n\tgo func() {\n\t\tselect {\n\t\tcase \u003c-stopped:\n\t\t\treturn\n\t\tcase \u003c-timedout:\n\t\t\tklog.Infof(\"etcd server has not terminated gracefully after %s, killing it.\", gracefulWait)\n\t\t\tr.cmd.Process.Kill()\n\t\t\treturn\n\t\t}\n\t}()\n\terr = r.cmd.Wait()\n\tclose(stopped)\n\tif exiterr, ok := err.(*exec.ExitError); ok {\n\t\tklog.Infof(\"etcd server stopped (signal: %s)\", exiterr.Error())\n\t\t// stopped\n\t} else if err != nil {\n\t\treturn fmt.Errorf(\"error waiting for etcd to stop: %v\", err)\n\t}\n\tklog.Infof(\"Stopped etcd server %s\", r.cfg.name)\n\treturn nil\n}","line":{"from":96,"to":133}} {"id":100000052,"name":"MigrateIfNeeded","signature":"func (m *Migrator) MigrateIfNeeded(target *EtcdVersionPair) error","file":"cluster/images/etcd/migrate/migrator.go","code":"// MigrateIfNeeded upgrades or downgrades the etcd data directory to the given target version.\nfunc (m *Migrator) MigrateIfNeeded(target *EtcdVersionPair) error {\n\tklog.Infof(\"Starting migration to %s\", target)\n\terr := m.dataDirectory.Initialize(target)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to initialize data directory %s: %v\", m.dataDirectory.path, err)\n\t}\n\n\tvar current *EtcdVersionPair\n\tvfExists, err := m.dataDirectory.versionFile.Exists()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif vfExists {\n\t\tcurrent, err = m.dataDirectory.versionFile.Read()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\treturn fmt.Errorf(\"existing data directory '%s' is missing version.txt file, unable to migrate\", m.dataDirectory.path)\n\t}\n\n\tfor {\n\t\tklog.Infof(\"Converging current version '%s' to target version '%s'\", current, target)\n\t\tcurrentNextMinorVersion := \u0026EtcdVersion{Version: semver.Version{Major: current.version.Major, Minor: current.version.Minor + 1}}\n\t\tswitch {\n\t\tcase current.version.MajorMinorEquals(target.version) || currentNextMinorVersion.MajorMinorEquals(target.version):\n\t\t\tklog.Infof(\"current version '%s' equals or is one minor version previous of target version '%s' - migration complete\", current, target)\n\t\t\terr = m.dataDirectory.versionFile.Write(target)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to write version.txt to '%s': %v\", m.dataDirectory.path, err)\n\t\t\t}\n\t\t\treturn nil\n\t\tcase current.storageVersion == storageEtcd2 \u0026\u0026 target.storageVersion == storageEtcd3:\n\t\t\treturn fmt.Errorf(\"upgrading from etcd2 storage to etcd3 storage is not supported\")\n\t\tcase current.version.Major == 3 \u0026\u0026 target.version.Major == 2:\n\t\t\treturn fmt.Errorf(\"downgrading from etcd 3.x to 2.x is not supported\")\n\t\tcase current.version.Major == target.version.Major \u0026\u0026 current.version.Minor \u003c target.version.Minor:\n\t\t\tstepVersion := m.cfg.supportedVersions.NextVersionPair(current)\n\t\t\tklog.Infof(\"upgrading etcd from %s to %s\", current, stepVersion)\n\t\t\tcurrent, err = m.minorVersionUpgrade(current, stepVersion)\n\t\tcase current.version.Major == 3 \u0026\u0026 target.version.Major == 3 \u0026\u0026 current.version.Minor \u003e target.version.Minor:\n\t\t\tklog.Infof(\"rolling etcd back from %s to %s\", current, target)\n\t\t\tcurrent, err = m.rollbackEtcd3MinorVersion(current, target)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}","line":{"from":64,"to":113}} {"id":100000053,"name":"rollbackEtcd3MinorVersion","signature":"func (m *Migrator) rollbackEtcd3MinorVersion(current *EtcdVersionPair, target *EtcdVersionPair) (*EtcdVersionPair, error)","file":"cluster/images/etcd/migrate/migrator.go","code":"func (m *Migrator) rollbackEtcd3MinorVersion(current *EtcdVersionPair, target *EtcdVersionPair) (*EtcdVersionPair, error) {\n\tif target.version.Minor != current.version.Minor-1 {\n\t\treturn nil, fmt.Errorf(\"rollback from %s to %s not supported, only rollbacks to the previous minor version are supported\", current.version, target.version)\n\t}\n\n\tklog.Infof(\"Performing etcd %s -\u003e %s rollback\", current.version, target.version)\n\terr := m.dataDirectory.Backup()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsnapshotFilename := fmt.Sprintf(\"%s.snapshot.db\", m.dataDirectory.path)\n\terr = os.Remove(snapshotFilename)\n\tif err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\treturn nil, fmt.Errorf(\"failed to clean snapshot file before rollback: %v\", err)\n\t}\n\n\t// Start current version of etcd.\n\trunner := m.newServer()\n\tklog.Infof(\"Starting etcd version %s to capture rollback snapshot.\", current.version)\n\terr = runner.Start(current.version)\n\tif err != nil {\n\t\tklog.Fatalf(\"Unable to automatically downgrade etcd: starting etcd version %s to capture rollback snapshot failed: %v\", current.version, err)\n\t\treturn nil, err\n\t}\n\n\tklog.Infof(\"Snapshotting etcd %s to %s\", current.version, snapshotFilename)\n\terr = m.client.Snapshot(current.version, snapshotFilename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = runner.Stop()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tklog.Info(\"Backing up data before rolling back\")\n\tbackupDir := fmt.Sprintf(\"%s.bak\", m.dataDirectory)\n\terr = os.RemoveAll(backupDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\torigInfo, err := os.Stat(m.dataDirectory.path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = os.Rename(m.dataDirectory.path, backupDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tklog.Infof(\"Restoring etcd %s from %s\", target.version, snapshotFilename)\n\terr = m.client.Restore(target.version, snapshotFilename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = os.Chmod(m.dataDirectory.path, origInfo.Mode())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn target, nil\n}","line":{"from":115,"to":178}} {"id":100000054,"name":"minorVersionUpgrade","signature":"func (m *Migrator) minorVersionUpgrade(current *EtcdVersionPair, target *EtcdVersionPair) (*EtcdVersionPair, error)","file":"cluster/images/etcd/migrate/migrator.go","code":"func (m *Migrator) minorVersionUpgrade(current *EtcdVersionPair, target *EtcdVersionPair) (*EtcdVersionPair, error) {\n\trunner := m.newServer()\n\n\t// Do the migration step, by just starting etcd in the target version.\n\terr := runner.Start(target.version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = runner.Stop()\n\treturn target, err\n}","line":{"from":180,"to":190}} {"id":100000055,"name":"newServer","signature":"func (m *Migrator) newServer() *EtcdMigrateServer","file":"cluster/images/etcd/migrate/migrator.go","code":"func (m *Migrator) newServer() *EtcdMigrateServer {\n\treturn NewEtcdMigrateServer(m.cfg, m.client)\n}","line":{"from":192,"to":194}} {"id":100000056,"name":"registerFlags","signature":"func registerFlags(flags *flag.FlagSet, opt *migrateOpts)","file":"cluster/images/etcd/migrate/options.go","code":"func registerFlags(flags *flag.FlagSet, opt *migrateOpts) {\n\tflags.StringVar(\u0026opts.name, \"name\", \"\",\n\t\t\"etcd cluster member name. If unset fallbacks to defaults to ETCD_NAME env, if unset defaults to etcd-\u003cETCD_HOSTNAME\u003e env, if unset defaults to etcd-\u003cHOSTNAME\u003e env.\")\n\tflags.Uint64Var(\u0026opts.port, \"port\", 0,\n\t\t\"etcd client port to use during migration operations. \"+\n\t\t\t\"This should be a different port than typically used by etcd to avoid clients accidentally connecting during upgrade/downgrade operations. \"+\n\t\t\t\"If unset default to 18629 or 18631 depending on \u003cdata-dir\u003e.\")\n\tflags.Uint64Var(\u0026opts.peerPort, \"peer-port\", 0,\n\t\t\"etcd peer port to use during migration operations. If unset defaults to 2380 or 2381 depending on \u003cdata-dir\u003e.\")\n\tflags.StringVar(\u0026opts.peerListenUrls, \"listen-peer-urls\", \"\",\n\t\t\"etcd --listen-peer-urls flag. If unset, fallbacks to LISTEN_PEER_URLS env and if unset defaults to http://localhost:\u003cpeer-port\u003e.\")\n\tflags.StringVar(\u0026opts.peerAdvertiseUrls, \"initial-advertise-peer-urls\", \"\",\n\t\t\"etcd --initial-advertise-peer-urls flag. If unset fallbacks to INITIAL_ADVERTISE_PEER_URLS env and if unset defaults to http://localhost:\u003cpeer-port\u003e.\")\n\tflags.StringVar(\u0026opts.clientListenUrls, \"listen-client-urls\", \"\",\n\t\t\"etcd --listen-client-urls flag. If unset, fallbacks to LISTEN_CLIENT_URLS env, and if unset defaults to http://127.0.0.1:\u003cport\u003e.\")\n\tflags.StringVar(\u0026opts.binDir, \"bin-dir\", \"/usr/local/bin\",\n\t\t\"directory of etcd and etcdctl binaries, must contain etcd-\u003cversion\u003e and etcdctl-\u003cversion\u003e for each version listed in \u003cbundled-versions\u003e.\")\n\tflags.StringVar(\u0026opts.dataDir, \"data-dir\", \"\",\n\t\t\"etcd data directory of etcd server to migrate. If unset fallbacks to DATA_DIRECTORY env.\")\n\tflags.StringSliceVar(\u0026opts.bundledVersions, \"bundled-versions\", supportedEtcdVersions,\n\t\t\"comma separated list of etcd binary versions present under the bin-dir.\")\n\tflags.StringVar(\u0026opts.etcdDataPrefix, \"etcd-data-prefix\", \"\",\n\t\t\"etcd key prefix under which all objects are kept. If unset fallbacks to ETCD_DATA_PREFIX env and if unset defaults to /registry.\")\n\tflags.StringVar(\u0026opts.ttlKeysDirectory, \"ttl-keys-directory\", \"\",\n\t\t\"etcd key prefix under which all keys with TTLs are kept. Defaults to \u003cetcd-data-prefix\u003e/events\")\n\tflags.StringVar(\u0026opts.initialCluster, \"initial-cluster\", \"\",\n\t\t\"comma separated list of name=endpoint pairs. If unset fallbacks to INITIAL_CLUSTER and if unset defaults to \u003cetcd-name\u003e=https://localhost:\u003cpeer-port\u003e.\")\n\tflags.StringVar(\u0026opts.targetVersion, \"target-version\", \"\",\n\t\t\"version of etcd to migrate to. Format must be \u003cmajor\u003e.\u003cminor\u003e.\u003cpatch\u003e. If unset fallbacks to TARGET_VERSION env.\")\n\tflags.StringVar(\u0026opts.targetStorage, \"target-storage\", \"\",\n\t\t\"storage version of etcd to migrate to, one of: etcd2, etcd3. If unset fallbacks to TARGET_STORAGE env.\")\n\tflags.StringVar(\u0026opts.etcdServerArgs, \"etcd-server-extra-args\", \"\",\n\t\t\"additional etcd server args for starting etcd servers during migration steps, need to set TLS certs flags for multi-member clusters using mTLS for communication. \"+\n\t\t\t\"If unset fallbacks to ETCD_CREDS env.\")\n}","line":{"from":74,"to":108}} {"id":100000057,"name":"lookupEnv","signature":"func lookupEnv(env string) (string, error)","file":"cluster/images/etcd/migrate/options.go","code":"func lookupEnv(env string) (string, error) {\n\tresult, ok := os.LookupEnv(env)\n\tif !ok || len(result) == 0 {\n\t\treturn result, fmt.Errorf(\"%s variable unset - expected failure\", env)\n\t}\n\treturn result, nil\n}","line":{"from":110,"to":116}} {"id":100000058,"name":"fallbackToEnv","signature":"func fallbackToEnv(flag, env string) (string, error)","file":"cluster/images/etcd/migrate/options.go","code":"func fallbackToEnv(flag, env string) (string, error) {\n\tklog.Infof(\"--%s unset - falling back to %s variable\", flag, env)\n\treturn lookupEnv(env)\n}","line":{"from":118,"to":121}} {"id":100000059,"name":"fallbackToEnvWithDefault","signature":"func fallbackToEnvWithDefault(flag, env, def string) string","file":"cluster/images/etcd/migrate/options.go","code":"func fallbackToEnvWithDefault(flag, env, def string) string {\n\tif value, err := lookupEnv(env); err == nil {\n\t\treturn value\n\t}\n\tklog.Warningf(\"%s variable for %s flag unset - defaulting to %s\", env, flag, def)\n\treturn def\n}","line":{"from":123,"to":129}} {"id":100000060,"name":"defaultName","signature":"func defaultName() (string, error)","file":"cluster/images/etcd/migrate/options.go","code":"func defaultName() (string, error) {\n\tif etcdName, err := lookupEnv(etcdNameEnv); err == nil {\n\t\treturn etcdName, nil\n\t}\n\tklog.Warningf(\"%s variable unset - falling back to etcd-%s variable\", etcdNameEnv, etcdHostnameEnv)\n\tif etcdHostname, err := lookupEnv(etcdHostnameEnv); err == nil {\n\t\treturn fmt.Sprintf(\"etcd-%s\", etcdHostname), nil\n\t}\n\tklog.Warningf(\"%s variable unset - falling back to etcd-%s variable\", etcdHostnameEnv, hostnameEnv)\n\tif hostname, err := lookupEnv(hostnameEnv); err == nil {\n\t\treturn fmt.Sprintf(\"etcd-%s\", hostname), nil\n\t}\n\treturn \"\", fmt.Errorf(\"defaulting --name failed due to all ETCD_NAME, ETCD_HOSTNAME and HOSTNAME unset\")\n}","line":{"from":131,"to":144}} {"id":100000061,"name":"validateAndDefault","signature":"func (opts *migrateOpts) validateAndDefault() error","file":"cluster/images/etcd/migrate/options.go","code":"func (opts *migrateOpts) validateAndDefault() error {\n\tvar err error\n\n\tif opts.name == \"\" {\n\t\tklog.Infof(\"--name unset - falling back to %s variable\", etcdNameEnv)\n\t\tif opts.name, err = defaultName(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif opts.dataDir == \"\" {\n\t\tif opts.dataDir, err = fallbackToEnv(\"data-dir\", dataDirEnv); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tetcdEventsRE := regexp.MustCompile(\"event\")\n\tif opts.port == 0 {\n\t\tif etcdEventsRE.MatchString(opts.dataDir) {\n\t\t\topts.port = 18631\n\t\t} else {\n\t\t\topts.port = 18629\n\t\t}\n\t\tklog.Infof(\"--port unset - defaulting to %d\", opts.port)\n\t}\n\tif opts.peerPort == 0 {\n\t\tif etcdEventsRE.MatchString(opts.dataDir) {\n\t\t\topts.peerPort = 2381\n\t\t} else {\n\t\t\topts.peerPort = 2380\n\t\t}\n\t\tklog.Infof(\"--peer-port unset - defaulting to %d\", opts.peerPort)\n\t}\n\n\tif opts.initialCluster == \"\" {\n\t\tdef := fmt.Sprintf(initialClusterFmt, opts.name, opts.peerPort)\n\t\topts.initialCluster = fallbackToEnvWithDefault(\"initial-cluster\", initialClusterEnv, def)\n\t}\n\n\tif opts.peerListenUrls == \"\" {\n\t\tdef := fmt.Sprintf(peerListenUrlsFmt, opts.peerPort)\n\t\topts.peerListenUrls = fallbackToEnvWithDefault(\"listen-peer-urls\", peerListenUrlsEnv, def)\n\t}\n\n\tif opts.peerAdvertiseUrls == \"\" {\n\t\tdef := fmt.Sprintf(peerAdvertiseUrlsFmt, opts.peerPort)\n\t\topts.peerAdvertiseUrls = fallbackToEnvWithDefault(\"initial-advertise-peer-urls\", peerAdvertiseUrlsEnv, def)\n\t}\n\n\tif opts.clientListenUrls == \"\" {\n\t\tdef := fmt.Sprintf(clientListenURLFmt, opts.port)\n\t\topts.clientListenUrls = fallbackToEnvWithDefault(\"listen-client-urls\", clientListenURLsEnv, def)\n\t}\n\n\tif opts.targetVersion == \"\" {\n\t\tif opts.targetVersion, err = fallbackToEnv(\"target-version\", targetVersionEnv); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif opts.targetStorage == \"\" {\n\t\tif opts.targetStorage, err = fallbackToEnv(\"target-storage\", targetStorageEnv); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif opts.etcdDataPrefix == \"\" {\n\t\topts.etcdDataPrefix = fallbackToEnvWithDefault(\"etcd-data-prefix\", etcdDataPrefixEnv, etcdDataPrefixDefault)\n\t}\n\n\tif opts.ttlKeysDirectory == \"\" {\n\t\topts.ttlKeysDirectory = fmt.Sprintf(ttlKeysDirectoryFmt, opts.etcdDataPrefix)\n\t\tklog.Infof(\"--ttl-keys-directory unset - defaulting to %s\", opts.ttlKeysDirectory)\n\t}\n\n\tif opts.etcdServerArgs == \"\" {\n\t\topts.etcdServerArgs = fallbackToEnvWithDefault(\"etcd-server-extra-args\", etcdServerArgsEnv, \"\")\n\t}\n\n\tif opts.supportedVersions, err = ParseSupportedVersions(opts.bundledVersions); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse --bundled-versions: %v\", err)\n\t}\n\n\tif err := validateBundledVersions(opts.supportedVersions, opts.binDir); err != nil {\n\t\treturn fmt.Errorf(\"failed to validate that 'etcd-\u003cversion\u003e' and 'etcdctl-\u003cversion\u003e' binaries exist in --bin-dir '%s' for all --bundled-versions '%s': %v\",\n\t\t\topts.binDir, strings.Join(opts.bundledVersions, \",\"), err)\n\t}\n\treturn nil\n}","line":{"from":146,"to":234}} {"id":100000062,"name":"validateBundledVersions","signature":"func validateBundledVersions(bundledVersions SupportedVersions, binDir string) error","file":"cluster/images/etcd/migrate/options.go","code":"// validateBundledVersions checks that 'etcd-\u003cversion\u003e' and 'etcdctl-\u003cversion\u003e' binaries exist in the binDir\n// for each version in the bundledVersions list.\nfunc validateBundledVersions(bundledVersions SupportedVersions, binDir string) error {\n\tfor _, v := range bundledVersions {\n\t\tfor _, binaryName := range []string{\"etcd\", \"etcdctl\"} {\n\t\t\tfn := filepath.Join(binDir, fmt.Sprintf(\"%s-%s\", binaryName, v))\n\t\t\tif _, err := os.Stat(fn); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to validate '%s' binary exists for bundled-version '%s': %v\", fn, v, err)\n\t\t\t}\n\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":236,"to":249}} {"id":100000063,"name":"copyDirectory","signature":"func copyDirectory(source string, dest string) error","file":"cluster/images/etcd/migrate/util_others.go","code":"func copyDirectory(source string, dest string) error {\n\treturn fileutils.CopyDirectory(source, dest)\n}","line":{"from":26,"to":28}} {"id":100000064,"name":"copyDirectory","signature":"func copyDirectory(source string, dest string) error","file":"cluster/images/etcd/migrate/utils_windows.go","code":"func copyDirectory(source string, dest string) error {\n\treturn fmt.Errorf(\"no support for windows\")\n}","line":{"from":24,"to":26}} {"id":100000065,"name":"ParseEtcdVersion","signature":"func ParseEtcdVersion(s string) (*EtcdVersion, error)","file":"cluster/images/etcd/migrate/versions.go","code":"// ParseEtcdVersion parses a SemVer string to an EtcdVersion.\nfunc ParseEtcdVersion(s string) (*EtcdVersion, error) {\n\tv, err := semver.Make(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026EtcdVersion{v}, nil\n}","line":{"from":31,"to":38}} {"id":100000066,"name":"MustParseEtcdVersion","signature":"func MustParseEtcdVersion(s string) *EtcdVersion","file":"cluster/images/etcd/migrate/versions.go","code":"// MustParseEtcdVersion parses a SemVer string to an EtcdVersion and panics if the parse fails.\nfunc MustParseEtcdVersion(s string) *EtcdVersion {\n\treturn \u0026EtcdVersion{semver.MustParse(s)}\n}","line":{"from":40,"to":43}} {"id":100000067,"name":"String","signature":"func (v *EtcdVersion) String() string","file":"cluster/images/etcd/migrate/versions.go","code":"// String returns the version in SemVer string format.\nfunc (v *EtcdVersion) String() string {\n\treturn v.Version.String()\n}","line":{"from":45,"to":48}} {"id":100000068,"name":"Equals","signature":"func (v *EtcdVersion) Equals(o *EtcdVersion) bool","file":"cluster/images/etcd/migrate/versions.go","code":"// Equals returns true if the versions are exactly equal.\nfunc (v *EtcdVersion) Equals(o *EtcdVersion) bool {\n\treturn v.Version.Equals(o.Version)\n}","line":{"from":50,"to":53}} {"id":100000069,"name":"MajorMinorEquals","signature":"func (v *EtcdVersion) MajorMinorEquals(o *EtcdVersion) bool","file":"cluster/images/etcd/migrate/versions.go","code":"// MajorMinorEquals returns true if the major and minor parts of the versions are equal;\n// if only patch versions differ, this returns true.\nfunc (v *EtcdVersion) MajorMinorEquals(o *EtcdVersion) bool {\n\treturn v.Major == o.Major \u0026\u0026 v.Minor == o.Minor\n}","line":{"from":55,"to":59}} {"id":100000070,"name":"ParseEtcdStorageVersion","signature":"func ParseEtcdStorageVersion(s string) (EtcdStorageVersion, error)","file":"cluster/images/etcd/migrate/versions.go","code":"// ParseEtcdStorageVersion parses an etcd storage version string to an EtcdStorageVersion.\nfunc ParseEtcdStorageVersion(s string) (EtcdStorageVersion, error) {\n\tswitch s {\n\tcase \"etcd2\":\n\t\treturn storageEtcd2, nil\n\tcase \"etcd3\":\n\t\treturn storageEtcd3, nil\n\tdefault:\n\t\treturn storageUnknown, fmt.Errorf(\"unrecognized storage version: %s\", s)\n\t}\n}","line":{"from":70,"to":80}} {"id":100000071,"name":"MustParseEtcdStorageVersion","signature":"func MustParseEtcdStorageVersion(s string) EtcdStorageVersion","file":"cluster/images/etcd/migrate/versions.go","code":"// MustParseEtcdStorageVersion parses an etcd storage version string to an EtcdStorageVersion and\n// panics if the parse fails.\nfunc MustParseEtcdStorageVersion(s string) EtcdStorageVersion {\n\tversion, err := ParseEtcdStorageVersion(s)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn version\n}","line":{"from":82,"to":90}} {"id":100000072,"name":"String","signature":"func (v EtcdStorageVersion) String() string","file":"cluster/images/etcd/migrate/versions.go","code":"// String returns the text representation of the EtcdStorageVersion, 'etcd2' or 'etcd3'.\nfunc (v EtcdStorageVersion) String() string {\n\tswitch v {\n\tcase storageEtcd2:\n\t\treturn \"etcd2\"\n\tcase storageEtcd3:\n\t\treturn \"etcd3\"\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"enum value %d missing from EtcdStorageVersion String() function\", v))\n\t}\n}","line":{"from":92,"to":102}} {"id":100000073,"name":"ParseEtcdVersionPair","signature":"func ParseEtcdVersionPair(s string) (*EtcdVersionPair, error)","file":"cluster/images/etcd/migrate/versions.go","code":"// ParseEtcdVersionPair parses a \"\u003cversion\u003e/\u003cstorage-version\u003e\" string to an EtcdVersionPair.\nfunc ParseEtcdVersionPair(s string) (*EtcdVersionPair, error) {\n\tparts := strings.Split(s, \"/\")\n\tif len(parts) != 2 {\n\t\treturn nil, fmt.Errorf(\"malformed version file, expected \u003cmajor\u003e.\u003cminor\u003e.\u003cpatch\u003e/\u003cstorage\u003e but got %s\", s)\n\t}\n\tversion, err := ParseEtcdVersion(parts[0])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstorageVersion, err := ParseEtcdStorageVersion(parts[1])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026EtcdVersionPair{version, storageVersion}, nil\n}","line":{"from":110,"to":125}} {"id":100000074,"name":"String","signature":"func (vp *EtcdVersionPair) String() string","file":"cluster/images/etcd/migrate/versions.go","code":"// String returns \"\u003cversion\u003e/\u003cstorage-version\u003e\" string of the EtcdVersionPair.\nfunc (vp *EtcdVersionPair) String() string {\n\treturn fmt.Sprintf(\"%s/%s\", vp.version, vp.storageVersion)\n}","line":{"from":127,"to":130}} {"id":100000075,"name":"Equals","signature":"func (vp *EtcdVersionPair) Equals(o *EtcdVersionPair) bool","file":"cluster/images/etcd/migrate/versions.go","code":"// Equals returns true if both the versions and storage versions are exactly equal.\nfunc (vp *EtcdVersionPair) Equals(o *EtcdVersionPair) bool {\n\treturn vp.version.Equals(o.version) \u0026\u0026 vp.storageVersion == o.storageVersion\n}","line":{"from":132,"to":135}} {"id":100000076,"name":"NextVersion","signature":"func (sv SupportedVersions) NextVersion(current *EtcdVersion) *EtcdVersion","file":"cluster/images/etcd/migrate/versions.go","code":"// NextVersion returns the next supported version after the given current version, or nil if no\n// next version exists.\nfunc (sv SupportedVersions) NextVersion(current *EtcdVersion) *EtcdVersion {\n\tvar nextVersion *EtcdVersion\n\tfor i, supportedVersion := range sv {\n\t\tif current.MajorMinorEquals(supportedVersion) \u0026\u0026 len(sv) \u003e i+1 {\n\t\t\tnextVersion = sv[i+1]\n\t\t}\n\t}\n\treturn nextVersion\n}","line":{"from":141,"to":151}} {"id":100000077,"name":"NextVersionPair","signature":"func (sv SupportedVersions) NextVersionPair(current *EtcdVersionPair) *EtcdVersionPair","file":"cluster/images/etcd/migrate/versions.go","code":"// NextVersionPair returns the next supported version after the given current version and infers\n// the storage version from the major version part of the next version.\nfunc (sv SupportedVersions) NextVersionPair(current *EtcdVersionPair) *EtcdVersionPair {\n\tnextVersion := sv.NextVersion(current.version)\n\tif nextVersion == nil {\n\t\treturn nil\n\t}\n\tstorageVersion := storageEtcd3\n\tif nextVersion.Major == 2 {\n\t\tstorageVersion = storageEtcd2\n\t}\n\treturn \u0026EtcdVersionPair{version: nextVersion, storageVersion: storageVersion}\n}","line":{"from":153,"to":165}} {"id":100000078,"name":"ParseSupportedVersions","signature":"func ParseSupportedVersions(list []string) (SupportedVersions, error)","file":"cluster/images/etcd/migrate/versions.go","code":"// ParseSupportedVersions parses a list of etcd versions.\nfunc ParseSupportedVersions(list []string) (SupportedVersions, error) {\n\tvar err error\n\tversions := make(SupportedVersions, len(list))\n\tfor i, v := range list {\n\t\tversions[i], err = ParseEtcdVersion(strings.TrimSpace(v))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn versions, nil\n}","line":{"from":167,"to":178}} {"id":100000079,"name":"main","signature":"func main()","file":"cmd/clicheck/check_cli_conventions.go","code":"func main() {\n\tvar errorCount int\n\n\tkubectl := cmd.NewKubectlCommand(cmd.KubectlOptions{IOStreams: genericclioptions.IOStreams{In: os.Stdin, Out: io.Discard, ErrOut: io.Discard}})\n\terrors := cmdsanity.RunCmdChecks(kubectl, cmdsanity.AllCmdChecks, []string{})\n\tfor _, err := range errors {\n\t\terrorCount++\n\t\tfmt.Fprintf(os.Stderr, \" %d. %s\\n\", errorCount, err)\n\t}\n\n\terrors = cmdsanity.RunGlobalChecks(cmdsanity.AllGlobalChecks)\n\tfor _, err := range errors {\n\t\terrorCount++\n\t\tfmt.Fprintf(os.Stderr, \" %d. %s\\n\", errorCount, err)\n\t}\n\n\tif errorCount \u003e 0 {\n\t\tfmt.Fprintf(os.Stdout, \"Found %d errors.\\n\", errorCount)\n\t\tos.Exit(1)\n\t}\n\n\tfmt.Fprintln(os.Stdout, \"Congrats, CLI looks good!\")\n}","line":{"from":29,"to":51}} {"id":100000080,"name":"main","signature":"func main()","file":"cmd/cloud-controller-manager/main.go","code":"func main() {\n\tccmOptions, err := options.NewCloudControllerManagerOptions()\n\tif err != nil {\n\t\tklog.Fatalf(\"unable to initialize command options: %v\", err)\n\t}\n\n\tcontrollerInitializers := app.DefaultInitFuncConstructors\n\t// Here is an example to remove the controller which is not needed.\n\t// e.g. remove the cloud-node-lifecycle controller which current cloud provider does not need.\n\t//delete(controllerInitializers, \"cloud-node-lifecycle\")\n\n\t// Here is an example to add an controller(NodeIpamController) which will be used by cloud provider\n\t// generate nodeIPAMConfig. Here is an sample code.\n\t// If you do not need additional controller, please ignore.\n\n\tnodeIpamController := nodeIPAMController{}\n\tnodeIpamController.nodeIPAMControllerOptions.NodeIPAMControllerConfiguration = \u0026nodeIpamController.nodeIPAMControllerConfiguration\n\tfss := cliflag.NamedFlagSets{}\n\tnodeIpamController.nodeIPAMControllerOptions.AddFlags(fss.FlagSet(\"nodeipam controller\"))\n\n\tcontrollerInitializers[\"nodeipam\"] = app.ControllerInitFuncConstructor{\n\t\t// \"node-controller\" is the shared identity of all node controllers, including node, node lifecycle, and node ipam.\n\t\t// See https://github.com/kubernetes/kubernetes/pull/72764#issuecomment-453300990 for more context.\n\t\tInitContext: app.ControllerInitContext{\n\t\t\tClientName: \"node-controller\",\n\t\t},\n\t\tConstructor: nodeIpamController.StartNodeIpamControllerWrapper,\n\t}\n\n\tcommand := app.NewCloudControllerManagerCommand(ccmOptions, cloudInitializer, controllerInitializers, fss, wait.NeverStop)\n\tcode := cli.Run(command)\n\tos.Exit(code)\n}","line":{"from":44,"to":76}} {"id":100000081,"name":"cloudInitializer","signature":"func cloudInitializer(config *cloudcontrollerconfig.CompletedConfig) cloudprovider.Interface","file":"cmd/cloud-controller-manager/main.go","code":"func cloudInitializer(config *cloudcontrollerconfig.CompletedConfig) cloudprovider.Interface {\n\tcloudConfig := config.ComponentConfig.KubeCloudShared.CloudProvider\n\t// initialize cloud provider with the cloud provider name and config file provided\n\tcloud, err := cloudprovider.InitCloudProvider(cloudConfig.Name, cloudConfig.CloudConfigFile)\n\tif err != nil {\n\t\tklog.Fatalf(\"Cloud provider could not be initialized: %v\", err)\n\t}\n\tif cloud == nil {\n\t\tklog.Fatalf(\"Cloud provider is nil\")\n\t}\n\n\tif !cloud.HasClusterID() {\n\t\tif config.ComponentConfig.KubeCloudShared.AllowUntaggedCloud {\n\t\t\tklog.Warning(\"detected a cluster without a ClusterID. A ClusterID will be required in the future. Please tag your cluster to avoid any future issues\")\n\t\t} else {\n\t\t\tklog.Fatalf(\"no ClusterID found. A ClusterID is required for the cloud provider to function properly. This check can be bypassed by setting the allow-untagged-cloud option\")\n\t\t}\n\t}\n\n\treturn cloud\n}","line":{"from":78,"to":98}} {"id":100000082,"name":"StartNodeIpamControllerWrapper","signature":"func (nodeIpamController *nodeIPAMController) StartNodeIpamControllerWrapper(initContext app.ControllerInitContext, completedConfig *cloudcontrollerconfig.CompletedConfig, cloud cloudprovider.Interface) app.InitFunc","file":"cmd/cloud-controller-manager/nodeipamcontroller.go","code":"func (nodeIpamController *nodeIPAMController) StartNodeIpamControllerWrapper(initContext app.ControllerInitContext, completedConfig *cloudcontrollerconfig.CompletedConfig, cloud cloudprovider.Interface) app.InitFunc {\n\tallErrors := nodeIpamController.nodeIPAMControllerOptions.Validate()\n\tif len(allErrors) \u003e 0 {\n\t\tklog.Fatal(\"NodeIPAM controller values are not properly set.\")\n\t}\n\tnodeIpamController.nodeIPAMControllerOptions.ApplyTo(\u0026nodeIpamController.nodeIPAMControllerConfiguration)\n\n\treturn func(ctx context.Context, controllerContext genericcontrollermanager.ControllerContext) (controller.Interface, bool, error) {\n\t\treturn startNodeIpamController(ctx, initContext, completedConfig, nodeIpamController.nodeIPAMControllerConfiguration, controllerContext, cloud)\n\t}\n}","line":{"from":57,"to":67}} {"id":100000083,"name":"startNodeIpamController","signature":"func startNodeIpamController(ctx context.Context, initContext app.ControllerInitContext, ccmConfig *cloudcontrollerconfig.CompletedConfig, nodeIPAMConfig nodeipamconfig.NodeIPAMControllerConfiguration, controllerCtx genericcontrollermanager.ControllerContext, cloud cloudprovider.Interface) (controller.Interface, bool, error)","file":"cmd/cloud-controller-manager/nodeipamcontroller.go","code":"func startNodeIpamController(ctx context.Context, initContext app.ControllerInitContext, ccmConfig *cloudcontrollerconfig.CompletedConfig, nodeIPAMConfig nodeipamconfig.NodeIPAMControllerConfiguration, controllerCtx genericcontrollermanager.ControllerContext, cloud cloudprovider.Interface) (controller.Interface, bool, error) {\n\tvar serviceCIDR *net.IPNet\n\tvar secondaryServiceCIDR *net.IPNet\n\n\t// should we start nodeIPAM\n\tif !ccmConfig.ComponentConfig.KubeCloudShared.AllocateNodeCIDRs {\n\t\treturn nil, false, nil\n\t}\n\n\t// Cannot run cloud ipam controller if cloud provider is nil (--cloud-provider not set or set to 'external')\n\tif cloud == nil \u0026\u0026 ccmConfig.ComponentConfig.KubeCloudShared.CIDRAllocatorType == string(ipam.CloudAllocatorType) {\n\t\treturn nil, false, errors.New(\"--cidr-allocator-type is set to 'CloudAllocator' but cloud provider is not configured\")\n\t}\n\n\t// failure: bad cidrs in config\n\tclusterCIDRs, dualStack, err := processCIDRs(ccmConfig.ComponentConfig.KubeCloudShared.ClusterCIDR)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\t// failure: more than one cidr but they are not configured as dual stack\n\tif len(clusterCIDRs) \u003e 1 \u0026\u0026 !dualStack {\n\t\treturn nil, false, fmt.Errorf(\"len of ClusterCIDRs==%v and they are not configured as dual stack (at least one from each IPFamily\", len(clusterCIDRs))\n\t}\n\n\t// failure: more than cidrs is not allowed even with dual stack\n\tif len(clusterCIDRs) \u003e 2 {\n\t\treturn nil, false, fmt.Errorf(\"len of clusters is:%v \u003e more than max allowed of 2\", len(clusterCIDRs))\n\t}\n\n\t// service cidr processing\n\tif len(strings.TrimSpace(nodeIPAMConfig.ServiceCIDR)) != 0 {\n\t\t_, serviceCIDR, err = netutils.ParseCIDRSloppy(nodeIPAMConfig.ServiceCIDR)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Unsuccessful parsing of service CIDR\", \"CIDR\", nodeIPAMConfig.ServiceCIDR)\n\t\t}\n\t}\n\n\tif len(strings.TrimSpace(nodeIPAMConfig.SecondaryServiceCIDR)) != 0 {\n\t\t_, secondaryServiceCIDR, err = netutils.ParseCIDRSloppy(nodeIPAMConfig.SecondaryServiceCIDR)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Unsuccessful parsing of service CIDR\", \"CIDR\", nodeIPAMConfig.SecondaryServiceCIDR)\n\t\t}\n\t}\n\n\t// the following checks are triggered if both serviceCIDR and secondaryServiceCIDR are provided\n\tif serviceCIDR != nil \u0026\u0026 secondaryServiceCIDR != nil {\n\t\t// should be dual stack (from different IPFamilies)\n\t\tdualstackServiceCIDR, err := netutils.IsDualStackCIDRs([]*net.IPNet{serviceCIDR, secondaryServiceCIDR})\n\t\tif err != nil {\n\t\t\treturn nil, false, fmt.Errorf(\"failed to perform dualstack check on serviceCIDR and secondaryServiceCIDR error:%v\", err)\n\t\t}\n\t\tif !dualstackServiceCIDR {\n\t\t\treturn nil, false, fmt.Errorf(\"serviceCIDR and secondaryServiceCIDR are not dualstack (from different IPfamiles)\")\n\t\t}\n\t}\n\n\tnodeCIDRMaskSizes, err := setNodeCIDRMaskSizes(nodeIPAMConfig, clusterCIDRs)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\tvar clusterCIDRInformer v1alpha1.ClusterCIDRInformer\n\tif utilfeature.DefaultFeatureGate.Enabled(features.MultiCIDRRangeAllocator) {\n\t\tclusterCIDRInformer = controllerCtx.InformerFactory.Networking().V1alpha1().ClusterCIDRs()\n\t}\n\tnodeIpamController, err := nodeipamcontroller.NewNodeIpamController(\n\t\tctx,\n\t\tcontrollerCtx.InformerFactory.Core().V1().Nodes(),\n\t\tclusterCIDRInformer,\n\t\tcloud,\n\t\tcontrollerCtx.ClientBuilder.ClientOrDie(initContext.ClientName),\n\t\tclusterCIDRs,\n\t\tserviceCIDR,\n\t\tsecondaryServiceCIDR,\n\t\tnodeCIDRMaskSizes,\n\t\tipam.CIDRAllocatorType(ccmConfig.ComponentConfig.KubeCloudShared.CIDRAllocatorType),\n\t)\n\tif err != nil {\n\t\treturn nil, true, err\n\t}\n\tgo nodeIpamController.Run(ctx)\n\treturn nil, true, nil\n}","line":{"from":69,"to":152}} {"id":100000084,"name":"processCIDRs","signature":"func processCIDRs(cidrsList string) ([]*net.IPNet, bool, error)","file":"cmd/cloud-controller-manager/nodeipamcontroller.go","code":"// processCIDRs is a helper function that works on a comma separated cidrs and returns\n// a list of typed cidrs\n// a flag if cidrs represents a dual stack\n// error if failed to parse any of the cidrs\nfunc processCIDRs(cidrsList string) ([]*net.IPNet, bool, error) {\n\tcidrsSplit := strings.Split(strings.TrimSpace(cidrsList), \",\")\n\n\tcidrs, err := netutils.ParseCIDRs(cidrsSplit)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\t// if cidrs has an error then the previous call will fail\n\t// safe to ignore error checking on next call\n\tdualstack, _ := netutils.IsDualStackCIDRs(cidrs)\n\n\treturn cidrs, dualstack, nil\n}","line":{"from":154,"to":171}} {"id":100000085,"name":"setNodeCIDRMaskSizes","signature":"func setNodeCIDRMaskSizes(cfg nodeipamconfig.NodeIPAMControllerConfiguration, clusterCIDRs []*net.IPNet) ([]int, error)","file":"cmd/cloud-controller-manager/nodeipamcontroller.go","code":"// setNodeCIDRMaskSizes returns the IPv4 and IPv6 node cidr mask sizes to the value provided\n// for --node-cidr-mask-size-ipv4 and --node-cidr-mask-size-ipv6 respectively. If value not provided,\n// then it will return default IPv4 and IPv6 cidr mask sizes.\nfunc setNodeCIDRMaskSizes(cfg nodeipamconfig.NodeIPAMControllerConfiguration, clusterCIDRs []*net.IPNet) ([]int, error) {\n\n\tsortedSizes := func(maskSizeIPv4, maskSizeIPv6 int) []int {\n\t\tnodeMaskCIDRs := make([]int, len(clusterCIDRs))\n\n\t\tfor idx, clusterCIDR := range clusterCIDRs {\n\t\t\tif netutils.IsIPv6CIDR(clusterCIDR) {\n\t\t\t\tnodeMaskCIDRs[idx] = maskSizeIPv6\n\t\t\t} else {\n\t\t\t\tnodeMaskCIDRs[idx] = maskSizeIPv4\n\t\t\t}\n\t\t}\n\t\treturn nodeMaskCIDRs\n\t}\n\n\t// --node-cidr-mask-size flag is incompatible with dual stack clusters.\n\tipv4Mask, ipv6Mask := defaultNodeMaskCIDRIPv4, defaultNodeMaskCIDRIPv6\n\tisDualstack := len(clusterCIDRs) \u003e 1\n\n\t// case one: cluster is dualstack (i.e, more than one cidr)\n\tif isDualstack {\n\t\t// if --node-cidr-mask-size then fail, user must configure the correct dual-stack mask sizes (or use default)\n\t\tif cfg.NodeCIDRMaskSize != 0 {\n\t\t\treturn nil, errors.New(\"usage of --node-cidr-mask-size is not allowed with dual-stack clusters\")\n\t\t}\n\n\t\tif cfg.NodeCIDRMaskSizeIPv4 != 0 {\n\t\t\tipv4Mask = int(cfg.NodeCIDRMaskSizeIPv4)\n\t\t}\n\t\tif cfg.NodeCIDRMaskSizeIPv6 != 0 {\n\t\t\tipv6Mask = int(cfg.NodeCIDRMaskSizeIPv6)\n\t\t}\n\t\treturn sortedSizes(ipv4Mask, ipv6Mask), nil\n\t}\n\n\tmaskConfigured := cfg.NodeCIDRMaskSize != 0\n\tmaskV4Configured := cfg.NodeCIDRMaskSizeIPv4 != 0\n\tmaskV6Configured := cfg.NodeCIDRMaskSizeIPv6 != 0\n\tisSingleStackIPv6 := netutils.IsIPv6CIDR(clusterCIDRs[0])\n\n\t// original flag is set\n\tif maskConfigured {\n\t\t// original mask flag is still the main reference.\n\t\tif maskV4Configured || maskV6Configured {\n\t\t\treturn nil, errors.New(\"usage of --node-cidr-mask-size-ipv4 and --node-cidr-mask-size-ipv6 is not allowed if --node-cidr-mask-size is set. For dual-stack clusters please unset it and use IPFamily specific flags\")\n\t\t}\n\n\t\tmask := int(cfg.NodeCIDRMaskSize)\n\t\treturn sortedSizes(mask, mask), nil\n\t}\n\n\tif maskV4Configured {\n\t\tif isSingleStackIPv6 {\n\t\t\treturn nil, errors.New(\"usage of --node-cidr-mask-size-ipv4 is not allowed for a single-stack IPv6 cluster\")\n\t\t}\n\n\t\tipv4Mask = int(cfg.NodeCIDRMaskSizeIPv4)\n\t}\n\n\t// !maskV4Configured \u0026\u0026 !maskConfigured \u0026\u0026 maskV6Configured\n\tif maskV6Configured {\n\t\tif !isSingleStackIPv6 {\n\t\t\treturn nil, errors.New(\"usage of --node-cidr-mask-size-ipv6 is not allowed for a single-stack IPv4 cluster\")\n\t\t}\n\n\t\tipv6Mask = int(cfg.NodeCIDRMaskSizeIPv6)\n\t}\n\treturn sortedSizes(ipv4Mask, ipv6Mask), nil\n}","line":{"from":173,"to":244}} {"id":100000086,"name":"main","signature":"func main()","file":"cmd/dependencycheck/dependencycheck.go","code":"func main() {\n\tflag.Parse()\n\n\targs := flag.Args()\n\n\tif len(args) != 1 {\n\t\tlog.Fatalf(\"usage: dependencycheck \u003cjson-dep-file\u003e (e.g. 'go list -mod=vendor -test -deps -json ./vendor/...')\")\n\t}\n\tif *restrict == \"\" {\n\t\tlog.Fatalf(\"Must specify restricted regex pattern\")\n\t}\n\tdepsPattern, err := regexp.Compile(*restrict)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error compiling restricted dependencies regex: %v\", err)\n\t}\n\tvar excludePattern *regexp.Regexp\n\tif *exclude != \"\" {\n\t\texcludePattern, err = regexp.Compile(*exclude)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error compiling excluded package regex: %v\", err)\n\t\t}\n\t}\n\tb, err := os.ReadFile(args[0])\n\tif err != nil {\n\t\tlog.Fatalf(\"Error reading dependencies file: %v\", err)\n\t}\n\n\tpackages := []goPackage{}\n\tdecoder := json.NewDecoder(bytes.NewBuffer(b))\n\tfor {\n\t\tpkg := goPackage{}\n\t\tif err := decoder.Decode(\u0026pkg); err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tlog.Fatalf(\"Error unmarshaling dependencies file: %v\", err)\n\t\t}\n\t\tpackages = append(packages, pkg)\n\t}\n\n\tviolations := map[string][]string{}\n\tfor _, p := range packages {\n\t\tif excludePattern != nil \u0026\u0026 excludePattern.MatchString(p.ImportPath) {\n\t\t\tcontinue\n\t\t}\n\t\timportViolations := []string{}\n\t\tallImports := []string{}\n\t\tallImports = append(allImports, p.Imports...)\n\t\tallImports = append(allImports, p.TestImports...)\n\t\tallImports = append(allImports, p.XTestImports...)\n\t\tfor _, i := range allImports {\n\t\t\tif depsPattern.MatchString(i) {\n\t\t\t\timportViolations = append(importViolations, i)\n\t\t\t}\n\t\t}\n\t\tif len(importViolations) \u003e 0 {\n\t\t\tviolations[p.ImportPath] = importViolations\n\t\t}\n\t}\n\n\tif len(violations) \u003e 0 {\n\t\tfor k, v := range violations {\n\t\t\tfmt.Printf(\"Found dependency violations in package %s:\\n\", k)\n\t\t\tfor _, a := range v {\n\t\t\t\tfmt.Println(\"--\u003e \" + a)\n\t\t\t}\n\t\t}\n\t\tlog.Fatal(\"Found restricted dependency violations in packages\")\n\t}\n}","line":{"from":46,"to":115}} {"id":100000087,"name":"runCommand","signature":"func runCommand(cmd ...string) (string, error)","file":"cmd/dependencyverifier/dependencyverifier.go","code":"// runCommand runs the cmd and returns the combined stdout and stderr, or an\n// error if the command failed.\nfunc runCommand(cmd ...string) (string, error) {\n\toutput, err := exec.Command(cmd[0], cmd[1:]...).CombinedOutput()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to run %q: %s (%s)\", strings.Join(cmd, \" \"), err, output)\n\t}\n\treturn string(output), nil\n}","line":{"from":48,"to":56}} {"id":100000088,"name":"readFile","signature":"func readFile(path string) (string, error)","file":"cmd/dependencyverifier/dependencyverifier.go","code":"func readFile(path string) (string, error) {\n\tcontent, err := os.ReadFile(path)\n\t// Convert []byte to string and print to screen\n\treturn string(content), err\n}","line":{"from":58,"to":62}} {"id":100000089,"name":"moduleInSlice","signature":"func moduleInSlice(a module, list []module, matchVersion bool) bool","file":"cmd/dependencyverifier/dependencyverifier.go","code":"func moduleInSlice(a module, list []module, matchVersion bool) bool {\n\tfor _, b := range list {\n\t\tif b == a {\n\t\t\treturn true\n\t\t}\n\t\tif !matchVersion \u0026\u0026 b.name == a.name {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":64,"to":74}} {"id":100000090,"name":"convertToMap","signature":"func convertToMap(modStr string) ([]module, map[module][]module)","file":"cmd/dependencyverifier/dependencyverifier.go","code":"// converts `go mod graph` output modStr into a map of from-\u003e[]to references and the main module\nfunc convertToMap(modStr string) ([]module, map[module][]module) {\n\tvar (\n\t\tmainModulesList = []module{}\n\t\tmainModules = map[module]bool{}\n\t)\n\tmodMap := make(map[module][]module)\n\tfor _, line := range strings.Split(modStr, \"\\n\") {\n\t\tif len(line) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tdeps := strings.Split(line, \" \")\n\t\tif len(deps) == 2 {\n\t\t\tfirst := parseModule(deps[0])\n\t\t\tsecond := parseModule(deps[1])\n\t\t\tif first.version == \"\" || first.version == \"v0.0.0\" {\n\t\t\t\tif !mainModules[first] {\n\t\t\t\t\tmainModules[first] = true\n\t\t\t\t\tmainModulesList = append(mainModulesList, first)\n\t\t\t\t}\n\t\t\t}\n\t\t\tmodMap[first] = append(modMap[first], second)\n\t\t} else {\n\t\t\t// skip invalid line\n\t\t\tlog.Printf(\"!!!invalid line in mod.graph: %s\", line)\n\t\t\tcontinue\n\t\t}\n\t}\n\treturn mainModulesList, modMap\n}","line":{"from":76,"to":105}} {"id":100000091,"name":"difference","signature":"func difference(a, b []string) ([]string, []string)","file":"cmd/dependencyverifier/dependencyverifier.go","code":"// difference returns a-b and b-a as sorted lists\nfunc difference(a, b []string) ([]string, []string) {\n\taMinusB := map[string]bool{}\n\tbMinusA := map[string]bool{}\n\tfor _, dependency := range a {\n\t\taMinusB[dependency] = true\n\t}\n\tfor _, dependency := range b {\n\t\tif _, found := aMinusB[dependency]; found {\n\t\t\tdelete(aMinusB, dependency)\n\t\t} else {\n\t\t\tbMinusA[dependency] = true\n\t\t}\n\t}\n\taMinusBList := []string{}\n\tbMinusAList := []string{}\n\tfor dependency := range aMinusB {\n\t\taMinusBList = append(aMinusBList, dependency)\n\t}\n\tfor dependency := range bMinusA {\n\t\tbMinusAList = append(bMinusAList, dependency)\n\t}\n\tsort.Strings(aMinusBList)\n\tsort.Strings(bMinusAList)\n\treturn aMinusBList, bMinusAList\n}","line":{"from":107,"to":132}} {"id":100000092,"name":"String","signature":"func (m module) String() string","file":"cmd/dependencyverifier/dependencyverifier.go","code":"func (m module) String() string {\n\tif len(m.version) == 0 {\n\t\treturn m.name\n\t}\n\treturn m.name + \"@\" + m.version\n}","line":{"from":139,"to":144}} {"id":100000093,"name":"parseModule","signature":"func parseModule(s string) module","file":"cmd/dependencyverifier/dependencyverifier.go","code":"func parseModule(s string) module {\n\tif !strings.Contains(s, \"@\") {\n\t\treturn module{name: s}\n\t}\n\tparts := strings.SplitN(s, \"@\", 2)\n\treturn module{name: parts[0], version: parts[1]}\n}","line":{"from":146,"to":152}} {"id":100000094,"name":"main","signature":"func main()","file":"cmd/dependencyverifier/dependencyverifier.go","code":"// option1: dependencyverifier dependencies.json\n// it will run `go mod graph` and check it.\n// option2: dependencyverifier dependencies.json mod.graph\n// it will check the specified mod graph result file.\nfunc main() {\n\tvar modeGraphStr string\n\tvar err error\n\tif len(os.Args) == 2 {\n\t\t// run `go mod graph`\n\t\tmodeGraphStr, err = runCommand(\"go\", \"mod\", \"graph\")\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error running 'go mod graph': %s\", err)\n\t\t}\n\t} else if len(os.Args) == 3 {\n\t\tmodGraphFile := string(os.Args[2])\n\t\tmodeGraphStr, err = readFile(modGraphFile)\n\t\t// read file, such as `mod.graph`\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error reading mod file %s: %s\", modGraphFile, err)\n\t\t}\n\t} else {\n\t\tlog.Fatalf(\"Usage: %s dependencies.json {mod.graph}\", os.Args[0])\n\t}\n\n\tdependenciesJSONPath := string(os.Args[1])\n\tdependencies, err := readFile(dependenciesJSONPath)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error reading dependencies file %s: %s\", dependencies, err)\n\t}\n\n\t// load Unwanted from json\n\tconfigFromFile := \u0026Unwanted{}\n\tdecoder := json.NewDecoder(bytes.NewBuffer([]byte(dependencies)))\n\tdecoder.DisallowUnknownFields()\n\tif err := decoder.Decode(configFromFile); err != nil {\n\t\tlog.Fatalf(\"Error reading dependencies file %s: %s\", dependenciesJSONPath, err)\n\t}\n\n\t// convert from `go mod graph` to main module and map of from-\u003e[]to references\n\tmainModules, moduleGraph := convertToMap(modeGraphStr)\n\n\t// gather the effective versions by looking at the versions required by the main modules\n\teffectiveVersions := map[string]module{}\n\tfor _, mainModule := range mainModules {\n\t\tfor _, override := range moduleGraph[mainModule] {\n\t\t\tif _, ok := effectiveVersions[override.name]; !ok {\n\t\t\t\teffectiveVersions[override.name] = override\n\t\t\t}\n\t\t}\n\t}\n\n\tunwantedToReferencers := map[string][]module{}\n\tfor _, mainModule := range mainModules {\n\t\t// visit to find unwanted modules still referenced from the main module\n\t\tvisit(func(m module, via []module) {\n\t\t\tif _, unwanted := configFromFile.Spec.UnwantedModules[m.name]; unwanted {\n\t\t\t\t// this is unwanted, store what is referencing it\n\t\t\t\treferencer := via[len(via)-1]\n\t\t\t\tif !moduleInSlice(referencer, unwantedToReferencers[m.name], false) {\n\t\t\t\t\t// // uncomment to get a detailed tree of the path that referenced the unwanted dependency\n\t\t\t\t\t//\n\t\t\t\t\t// i := 0\n\t\t\t\t\t// for _, v := range via {\n\t\t\t\t\t// \tif v.version != \"\" \u0026\u0026 v.version != \"v0.0.0\" {\n\t\t\t\t\t// \t\tfmt.Println(strings.Repeat(\" \", i), v)\n\t\t\t\t\t// \t\ti++\n\t\t\t\t\t// \t}\n\t\t\t\t\t// }\n\t\t\t\t\t// if i \u003e 0 {\n\t\t\t\t\t// \tfmt.Println(strings.Repeat(\" \", i+1), m)\n\t\t\t\t\t// \tfmt.Println()\n\t\t\t\t\t// }\n\t\t\t\t\tunwantedToReferencers[m.name] = append(unwantedToReferencers[m.name], referencer)\n\t\t\t\t}\n\t\t\t}\n\t\t}, mainModule, moduleGraph, effectiveVersions)\n\t}\n\n\tconfig := \u0026Unwanted{}\n\tconfig.Spec.UnwantedModules = configFromFile.Spec.UnwantedModules\n\tfor unwanted := range unwantedToReferencers {\n\t\tif config.Status.UnwantedReferences == nil {\n\t\t\tconfig.Status.UnwantedReferences = map[string][]string{}\n\t\t}\n\t\tsort.Slice(unwantedToReferencers[unwanted], func(i, j int) bool {\n\t\t\tri := unwantedToReferencers[unwanted][i]\n\t\t\trj := unwantedToReferencers[unwanted][j]\n\t\t\tif ri.name != rj.name {\n\t\t\t\treturn ri.name \u003c rj.name\n\t\t\t}\n\t\t\treturn ri.version \u003c rj.version\n\t\t})\n\t\tfor _, referencer := range unwantedToReferencers[unwanted] {\n\t\t\t// make sure any reference at all shows up as a non-nil status\n\t\t\tif config.Status.UnwantedReferences == nil {\n\t\t\t\tconfig.Status.UnwantedReferences[unwanted] = []string{}\n\t\t\t}\n\t\t\t// record specific names of versioned referents\n\t\t\tif referencer.version != \"\" \u0026\u0026 referencer.version != \"v0.0.0\" {\n\t\t\t\tconfig.Status.UnwantedReferences[unwanted] = append(config.Status.UnwantedReferences[unwanted], referencer.name)\n\t\t\t}\n\t\t}\n\t}\n\n\tneedUpdate := false\n\n\t// Compare unwanted list from unwanted-dependencies.json with current status from `go mod graph`\n\texpected, err := json.MarshalIndent(configFromFile.Status, \"\", \" \")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tactual, err := json.MarshalIndent(config.Status, \"\", \" \")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif !bytes.Equal(expected, actual) {\n\t\tlog.Printf(\"Expected status of\\n%s\", string(expected))\n\t\tlog.Printf(\"Got status of\\n%s\", string(actual))\n\t}\n\tfor expectedRef, expectedFrom := range configFromFile.Status.UnwantedReferences {\n\t\tactualFrom, ok := config.Status.UnwantedReferences[expectedRef]\n\t\tif !ok {\n\t\t\t// disappeared entirely\n\t\t\tlog.Printf(\"Good news! Unwanted dependency %q is no longer referenced. Remove status.unwantedReferences[%q] in %s to ensure it doesn't get reintroduced.\", expectedRef, expectedRef, dependenciesJSONPath)\n\t\t\tneedUpdate = true\n\t\t\tcontinue\n\t\t}\n\t\tremovedReferences, unwantedReferences := difference(expectedFrom, actualFrom)\n\t\tif len(removedReferences) \u003e 0 {\n\t\t\tlog.Printf(\"Good news! Unwanted module %q dropped the following dependants:\", expectedRef)\n\t\t\tfor _, reference := range removedReferences {\n\t\t\t\tlog.Printf(\" %s\", reference)\n\t\t\t}\n\t\t\tlog.Printf(\"!!! Remove those from status.unwantedReferences[%q] in %s to ensure they don't get reintroduced.\", expectedRef, dependenciesJSONPath)\n\t\t\tneedUpdate = true\n\t\t}\n\t\tif len(unwantedReferences) \u003e 0 {\n\t\t\tlog.Printf(\"Unwanted module %q marked in %s is referenced by new dependants:\", expectedRef, dependenciesJSONPath)\n\t\t\tfor _, reference := range unwantedReferences {\n\t\t\t\tlog.Printf(\" %s\", reference)\n\t\t\t}\n\t\t\tlog.Printf(\"!!! Avoid updating referencing modules to versions that reintroduce use of unwanted dependencies\\n\")\n\t\t\tneedUpdate = true\n\t\t}\n\t}\n\tfor actualRef, actualFrom := range config.Status.UnwantedReferences {\n\t\tif _, expected := configFromFile.Status.UnwantedReferences[actualRef]; expected {\n\t\t\t// expected, already ensured referencers were equal in the first loop\n\t\t\tcontinue\n\t\t}\n\t\tlog.Printf(\"Unwanted module %q marked in %s is referenced\", actualRef, dependenciesJSONPath)\n\t\tfor _, reference := range actualFrom {\n\t\t\tlog.Printf(\" %s\", reference)\n\t\t}\n\t\tlog.Printf(\"!!! Avoid updating referencing modules to versions that reintroduce use of unwanted dependencies\\n\")\n\t\tneedUpdate = true\n\t}\n\n\tif needUpdate {\n\t\tos.Exit(1)\n\t}\n}","line":{"from":154,"to":315}} {"id":100000095,"name":"visit","signature":"func visit(visitor func(m module, via []module), main module, references map[module][]module, effectiveVersions map[string]module)","file":"cmd/dependencyverifier/dependencyverifier.go","code":"func visit(visitor func(m module, via []module), main module, references map[module][]module, effectiveVersions map[string]module) {\n\tdoVisit(visitor, main, nil, map[module]bool{}, references, effectiveVersions)\n}","line":{"from":317,"to":319}} {"id":100000096,"name":"doVisit","signature":"func doVisit(visitor func(m module, via []module), from module, via []module, visited map[module]bool, references map[module][]module, effectiveVersions map[string]module)","file":"cmd/dependencyverifier/dependencyverifier.go","code":"func doVisit(visitor func(m module, via []module), from module, via []module, visited map[module]bool, references map[module][]module, effectiveVersions map[string]module) {\n\tvisitor(from, via)\n\tvia = append(via, from)\n\tif visited[from] {\n\t\treturn\n\t}\n\tfor _, to := range references[from] {\n\t\t// switch to the effective version of this dependency\n\t\tif override, ok := effectiveVersions[to.name]; ok {\n\t\t\tto = override\n\t\t}\n\t\t// recurse unless we've already visited this module in this traversal\n\t\tif !moduleInSlice(to, via, false) {\n\t\t\tdoVisit(visitor, to, via, visited, references, effectiveVersions)\n\t\t}\n\t}\n\tvisited[from] = true\n}","line":{"from":321,"to":338}} {"id":100000097,"name":"main","signature":"func main()","file":"cmd/fieldnamedocscheck/field_name_docs_check.go","code":"func main() {\n\tflag.Parse()\n\n\tif *typeSrc == \"\" {\n\t\tklog.Fatalf(\"Please define -s flag as it is the api type file\")\n\t}\n\n\tdocsForTypes := kruntime.ParseDocumentationFrom(*typeSrc)\n\trc := false\n\n\tfor _, ks := range docsForTypes {\n\t\ttypesMap := make(kubeTypesMap)\n\n\t\tfor _, p := range ks[1:] {\n\t\t\t// skip the field with no tag name\n\t\t\tif p.Name != \"\" {\n\t\t\t\ttypesMap[strings.ToLower(p.Name)] = p\n\t\t\t}\n\t\t}\n\n\t\tstructName := ks[0].Name\n\n\t\trc = checkFieldNameAndDoc(structName, \"\", ks[0].Doc, typesMap)\n\t\tfor _, p := range ks[1:] {\n\t\t\trc = checkFieldNameAndDoc(structName, p.Name, p.Doc, typesMap)\n\t\t}\n\t}\n\n\tif rc {\n\t\tos.Exit(1)\n\t}\n}","line":{"from":39,"to":70}} {"id":100000098,"name":"checkFieldNameAndDoc","signature":"func checkFieldNameAndDoc(structName, fieldName, doc string, typesMap kubeTypesMap) bool","file":"cmd/fieldnamedocscheck/field_name_docs_check.go","code":"func checkFieldNameAndDoc(structName, fieldName, doc string, typesMap kubeTypesMap) bool {\n\trc := false\n\tvisited := sets.Set[string]{}\n\n\t// The rule is:\n\t// 1. Get all back-tick quoted names in the doc\n\t// 2. Skip the name which is already found mismatched.\n\t// 3. Skip the name whose lowercase is different from the lowercase of tag names,\n\t// because some docs use back-tick to quote field value or nil\n\t// 4. Check if the name is different from its tag name\n\n\t// TODO: a manual pass adding back-ticks to the doc strings, then update the linter to\n\t// check the existence of back-ticks\n\tnameGroups := re.FindAllStringSubmatch(doc, -1)\n\tfor _, nameGroup := range nameGroups {\n\t\tname := nameGroup[1]\n\t\tif visited.Has(name) {\n\t\t\tcontinue\n\t\t}\n\t\tif p, ok := typesMap[strings.ToLower(name)]; ok \u0026\u0026 p.Name != name {\n\t\t\trc = true\n\t\t\tvisited.Insert(name)\n\n\t\t\tfmt.Fprintf(os.Stderr, \"Error: doc for %s\", structName)\n\t\t\tif fieldName != \"\" {\n\t\t\t\tfmt.Fprintf(os.Stderr, \".%s\", fieldName)\n\t\t\t}\n\n\t\t\tfmt.Fprintf(os.Stderr, \" contains: %s, which should be: %s\\n\", name, p.Name)\n\t\t}\n\t}\n\n\treturn rc\n}","line":{"from":72,"to":105}} {"id":100000099,"name":"main","signature":"func main()","file":"cmd/gendocs/gen_kubectl_docs.go","code":"func main() {\n\t// use os.Args instead of \"flags\" because \"flags\" will mess up the man pages!\n\tpath := \"docs/\"\n\tif len(os.Args) == 2 {\n\t\tpath = os.Args[1]\n\t} else if len(os.Args) \u003e 2 {\n\t\tfmt.Fprintf(os.Stderr, \"usage: %s [output directory]\\n\", os.Args[0])\n\t\tos.Exit(1)\n\t}\n\n\toutDir, err := genutils.OutDir(path)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"failed to get output directory: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\t// Set environment variables used by kubectl so the output is consistent,\n\t// regardless of where we run.\n\tos.Setenv(\"HOME\", \"/home/username\")\n\tkubectl := cmd.NewKubectlCommand(cmd.KubectlOptions{IOStreams: genericclioptions.IOStreams{In: bytes.NewReader(nil), Out: io.Discard, ErrOut: io.Discard}})\n\tdoc.GenMarkdownTree(kubectl, outDir)\n}","line":{"from":31,"to":52}} {"id":100000100,"name":"main","signature":"func main()","file":"cmd/genkubedocs/gen_kube_docs.go","code":"func main() {\n\t// use os.Args instead of \"flags\" because \"flags\" will mess up the man pages!\n\tpath := \"\"\n\tmodule := \"\"\n\tif len(os.Args) == 3 {\n\t\tpath = os.Args[1]\n\t\tmodule = os.Args[2]\n\t} else {\n\t\tfmt.Fprintf(os.Stderr, \"usage: %s [output directory] [module] \\n\", os.Args[0])\n\t\tos.Exit(1)\n\t}\n\n\toutDir, err := genutils.OutDir(path)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"failed to get output directory: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tswitch module {\n\tcase \"kube-apiserver\":\n\t\t// generate docs for kube-apiserver\n\t\tapiserver := apiservapp.NewAPIServerCommand()\n\t\tdoc.GenMarkdownTree(apiserver, outDir)\n\tcase \"kube-controller-manager\":\n\t\t// generate docs for kube-controller-manager\n\t\tcontrollermanager := cmapp.NewControllerManagerCommand()\n\t\tdoc.GenMarkdownTree(controllermanager, outDir)\n\tcase \"kube-proxy\":\n\t\t// generate docs for kube-proxy\n\t\tproxy := proxyapp.NewProxyCommand()\n\t\tdoc.GenMarkdownTree(proxy, outDir)\n\tcase \"kube-scheduler\":\n\t\t// generate docs for kube-scheduler\n\t\tscheduler := schapp.NewSchedulerCommand()\n\t\tdoc.GenMarkdownTree(scheduler, outDir)\n\tcase \"kubelet\":\n\t\t// generate docs for kubelet\n\t\tkubelet := kubeletapp.NewKubeletCommand()\n\t\tdoc.GenMarkdownTree(kubelet, outDir)\n\tcase \"kubeadm\":\n\t\t// resets global flags created by kubelet or other commands e.g.\n\t\t// --azure-container-registry-config from pkg/credentialprovider/azure\n\t\t// --version pkg/version/verflag\n\t\tpflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)\n\n\t\t// generate docs for kubeadm\n\t\tkubeadm := kubeadmapp.NewKubeadmCommand(bytes.NewReader(nil), io.Discard, io.Discard)\n\t\tdoc.GenMarkdownTree(kubeadm, outDir)\n\n\t\t// cleanup generated code for usage as include in the website\n\t\tMarkdownPostProcessing(kubeadm, outDir, cleanupForInclude)\n\tdefault:\n\t\tfmt.Fprintf(os.Stderr, \"Module %s is not supported\", module)\n\t\tos.Exit(1)\n\t}\n}","line":{"from":36,"to":91}} {"id":100000101,"name":"MarkdownPostProcessing","signature":"func MarkdownPostProcessing(cmd *cobra.Command, dir string, processor func(string) string) error","file":"cmd/genkubedocs/postprocessing.go","code":"// MarkdownPostProcessing goes though the generated files\nfunc MarkdownPostProcessing(cmd *cobra.Command, dir string, processor func(string) string) error {\n\tfor _, c := range cmd.Commands() {\n\t\tif !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {\n\t\t\tcontinue\n\t\t}\n\t\tif err := MarkdownPostProcessing(c, dir, processor); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tbasename := strings.Replace(cmd.CommandPath(), \" \", \"_\", -1) + \".md\"\n\tfilename := filepath.Join(dir, basename)\n\n\tmarkdownBytes, err := os.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprocessedMarkDown := processor(string(markdownBytes))\n\n\treturn os.WriteFile(filename, []byte(processedMarkDown), 0644)\n}","line":{"from":27,"to":49}} {"id":100000102,"name":"cleanupForInclude","signature":"func cleanupForInclude(md string) string","file":"cmd/genkubedocs/postprocessing.go","code":"// cleanupForInclude parts of markdown that will make difficult to use it as include in the website:\n// - The title of the document (this allow more flexibility for include, e.g. include in tabs)\n// - The sections see also, that assumes file will be used as a main page\nfunc cleanupForInclude(md string) string {\n\tlines := strings.Split(md, \"\\n\")\n\n\tcleanMd := \"\"\n\tfor i, line := range lines {\n\t\tif i == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif line == \"### SEE ALSO\" {\n\t\t\tbreak\n\t\t}\n\n\t\tcleanMd += line\n\t\tif i \u003c len(lines)-1 {\n\t\t\tcleanMd += \"\\n\"\n\t\t}\n\t}\n\n\treturn cleanMd\n}","line":{"from":51,"to":73}} {"id":100000103,"name":"main","signature":"func main()","file":"cmd/genman/gen_kube_man.go","code":"func main() {\n\t// use os.Args instead of \"flags\" because \"flags\" will mess up the man pages!\n\tpath := \"docs/man/man1\"\n\tmodule := \"\"\n\tif len(os.Args) == 3 {\n\t\tpath = os.Args[1]\n\t\tmodule = os.Args[2]\n\t} else {\n\t\tfmt.Fprintf(os.Stderr, \"usage: %s [output directory] [module] \\n\", os.Args[0])\n\t\tos.Exit(1)\n\t}\n\n\toutDir, err := genutils.OutDir(path)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"failed to get output directory: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\t// Set environment variables used by command so the output is consistent,\n\t// regardless of where we run.\n\tos.Setenv(\"HOME\", \"/home/username\")\n\n\tswitch module {\n\tcase \"kube-apiserver\":\n\t\t// generate manpage for kube-apiserver\n\t\tapiserver := apiservapp.NewAPIServerCommand()\n\t\tgenMarkdown(apiserver, \"\", outDir)\n\t\tfor _, c := range apiserver.Commands() {\n\t\t\tgenMarkdown(c, \"kube-apiserver\", outDir)\n\t\t}\n\tcase \"kube-controller-manager\":\n\t\t// generate manpage for kube-controller-manager\n\t\tcontrollermanager := cmapp.NewControllerManagerCommand()\n\t\tgenMarkdown(controllermanager, \"\", outDir)\n\t\tfor _, c := range controllermanager.Commands() {\n\t\t\tgenMarkdown(c, \"kube-controller-manager\", outDir)\n\t\t}\n\tcase \"kube-proxy\":\n\t\t// generate manpage for kube-proxy\n\t\tproxy := proxyapp.NewProxyCommand()\n\t\tgenMarkdown(proxy, \"\", outDir)\n\t\tfor _, c := range proxy.Commands() {\n\t\t\tgenMarkdown(c, \"kube-proxy\", outDir)\n\t\t}\n\tcase \"kube-scheduler\":\n\t\t// generate manpage for kube-scheduler\n\t\tscheduler := schapp.NewSchedulerCommand()\n\t\tgenMarkdown(scheduler, \"\", outDir)\n\t\tfor _, c := range scheduler.Commands() {\n\t\t\tgenMarkdown(c, \"kube-scheduler\", outDir)\n\t\t}\n\tcase \"kubelet\":\n\t\t// generate manpage for kubelet\n\t\tkubelet := kubeletapp.NewKubeletCommand()\n\t\tgenMarkdown(kubelet, \"\", outDir)\n\t\tfor _, c := range kubelet.Commands() {\n\t\t\tgenMarkdown(c, \"kubelet\", outDir)\n\t\t}\n\tcase \"kubectl\":\n\t\t// generate manpage for kubectl\n\t\tkubectl := kubectlcmd.NewKubectlCommand(kubectlcmd.KubectlOptions{IOStreams: genericclioptions.IOStreams{In: bytes.NewReader(nil), Out: io.Discard, ErrOut: io.Discard}})\n\t\tgenMarkdown(kubectl, \"\", outDir)\n\t\tfor _, c := range kubectl.Commands() {\n\t\t\tgenMarkdown(c, \"kubectl\", outDir)\n\t\t}\n\tcase \"kubeadm\":\n\t\t// generate manpage for kubeadm\n\t\tkubeadm := kubeadmapp.NewKubeadmCommand(bytes.NewReader(nil), io.Discard, io.Discard)\n\t\tgenMarkdown(kubeadm, \"\", outDir)\n\t\tfor _, c := range kubeadm.Commands() {\n\t\t\tgenMarkdown(c, \"kubeadm\", outDir)\n\t\t}\n\tdefault:\n\t\tfmt.Fprintf(os.Stderr, \"Module %s is not supported\", module)\n\t\tos.Exit(1)\n\t}\n}","line":{"from":40,"to":116}} {"id":100000104,"name":"preamble","signature":"func preamble(out *bytes.Buffer, name, short, long string)","file":"cmd/genman/gen_kube_man.go","code":"func preamble(out *bytes.Buffer, name, short, long string) {\n\tout.WriteString(`% KUBERNETES(1) kubernetes User Manuals\n% Eric Paris\n% Jan 2015\n# NAME\n`)\n\tfmt.Fprintf(out, \"%s \\\\- %s\\n\\n\", name, short)\n\tfmt.Fprintf(out, \"# SYNOPSIS\\n\")\n\tfmt.Fprintf(out, \"**%s** [OPTIONS]\\n\\n\", name)\n\tfmt.Fprintf(out, \"# DESCRIPTION\\n\")\n\tfmt.Fprintf(out, \"%s\\n\\n\", long)\n}","line":{"from":118,"to":129}} {"id":100000105,"name":"printFlags","signature":"func printFlags(out *bytes.Buffer, flags *pflag.FlagSet)","file":"cmd/genman/gen_kube_man.go","code":"func printFlags(out *bytes.Buffer, flags *pflag.FlagSet) {\n\tflags.VisitAll(func(flag *pflag.Flag) {\n\t\tformat := \"**--%s**=%s\\n\\t%s\\n\\n\"\n\t\tif flag.Value.Type() == \"string\" {\n\t\t\t// put quotes on the value\n\t\t\tformat = \"**--%s**=%q\\n\\t%s\\n\\n\"\n\t\t}\n\n\t\t// Todo, when we mark a shorthand is deprecated, but specify an empty message.\n\t\t// The flag.ShorthandDeprecated is empty as the shorthand is deprecated.\n\t\t// Using len(flag.ShorthandDeprecated) \u003e 0 can't handle this, others are ok.\n\t\tif !(len(flag.ShorthandDeprecated) \u003e 0) \u0026\u0026 len(flag.Shorthand) \u003e 0 {\n\t\t\tformat = \"**-%s**, \" + format\n\t\t\tfmt.Fprintf(out, format, flag.Shorthand, flag.Name, flag.DefValue, flag.Usage)\n\t\t} else {\n\t\t\tfmt.Fprintf(out, format, flag.Name, flag.DefValue, flag.Usage)\n\t\t}\n\t})\n}","line":{"from":131,"to":149}} {"id":100000106,"name":"printOptions","signature":"func printOptions(out *bytes.Buffer, command *cobra.Command)","file":"cmd/genman/gen_kube_man.go","code":"func printOptions(out *bytes.Buffer, command *cobra.Command) {\n\tflags := command.NonInheritedFlags()\n\tif flags.HasFlags() {\n\t\tfmt.Fprintf(out, \"# OPTIONS\\n\")\n\t\tprintFlags(out, flags)\n\t\tfmt.Fprintf(out, \"\\n\")\n\t}\n\tflags = command.InheritedFlags()\n\tif flags.HasFlags() {\n\t\tfmt.Fprintf(out, \"# OPTIONS INHERITED FROM PARENT COMMANDS\\n\")\n\t\tprintFlags(out, flags)\n\t\tfmt.Fprintf(out, \"\\n\")\n\t}\n}","line":{"from":151,"to":164}} {"id":100000107,"name":"genMarkdown","signature":"func genMarkdown(command *cobra.Command, parent, docsDir string)","file":"cmd/genman/gen_kube_man.go","code":"func genMarkdown(command *cobra.Command, parent, docsDir string) {\n\tdparent := strings.Replace(parent, \" \", \"-\", -1)\n\tname := command.Name()\n\tdname := name\n\tif len(parent) \u003e 0 {\n\t\tdname = dparent + \"-\" + name\n\t\tname = parent + \" \" + name\n\t}\n\n\tout := new(bytes.Buffer)\n\tshort := command.Short\n\tlong := command.Long\n\tif len(long) == 0 {\n\t\tlong = short\n\t}\n\n\tpreamble(out, name, short, long)\n\tprintOptions(out, command)\n\n\tif len(command.Example) \u003e 0 {\n\t\tfmt.Fprintf(out, \"# EXAMPLE\\n\")\n\t\tfmt.Fprintf(out, \"```\\n%s\\n```\\n\", command.Example)\n\t}\n\n\tif len(command.Commands()) \u003e 0 || len(parent) \u003e 0 {\n\t\tfmt.Fprintf(out, \"# SEE ALSO\\n\")\n\t\tif len(parent) \u003e 0 {\n\t\t\tfmt.Fprintf(out, \"**%s(1)**, \", dparent)\n\t\t}\n\t\tfor _, c := range command.Commands() {\n\t\t\tfmt.Fprintf(out, \"**%s-%s(1)**, \", dname, c.Name())\n\t\t\tgenMarkdown(c, name, docsDir)\n\t\t}\n\t\tfmt.Fprintf(out, \"\\n\")\n\t}\n\n\tout.WriteString(`\n# HISTORY\nJanuary 2015, Originally compiled by Eric Paris (eparis at redhat dot com) based on the kubernetes source material, but hopefully they have been automatically generated since!\n`)\n\n\tfinal := mangen.Render(out.Bytes())\n\n\tfilename := docsDir + dname + \".1\"\n\toutFile, err := os.Create(filename)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tdefer outFile.Close()\n\t_, err = outFile.Write(final)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n}","line":{"from":166,"to":222}} {"id":100000108,"name":"main","signature":"func main()","file":"cmd/genswaggertypedocs/swagger_type_docs.go","code":"func main() {\n\tflag.Parse()\n\n\tif *typeSrc == \"\" {\n\t\tklog.Fatalf(\"Please define -s flag as it is the source file\")\n\t}\n\n\tvar funcOut io.Writer\n\tif *functionDest == \"-\" {\n\t\tfuncOut = os.Stdout\n\t} else {\n\t\tfile, err := os.Create(*functionDest)\n\t\tif err != nil {\n\t\t\tklog.Fatalf(\"Couldn't open %v: %v\", *functionDest, err)\n\t\t}\n\t\tdefer file.Close()\n\t\tfuncOut = file\n\t}\n\n\tdocsForTypes := kruntime.ParseDocumentationFrom(*typeSrc)\n\n\tif *verify {\n\t\trc, err := kruntime.VerifySwaggerDocsExist(docsForTypes, funcOut)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error in verification process: %s\\n\", err)\n\t\t}\n\t\tos.Exit(rc)\n\t}\n\n\tif len(docsForTypes) \u003e 0 {\n\t\tif err := kruntime.WriteSwaggerDocFunc(docsForTypes, funcOut); err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error when writing swagger documentation functions: %s\\n\", err)\n\t\t\tos.Exit(-1)\n\t\t}\n\t}\n}","line":{"from":36,"to":71}} {"id":100000109,"name":"OutDir","signature":"func OutDir(path string) (string, error)","file":"cmd/genutils/genutils.go","code":"// OutDir creates the absolute path name from path and checks path exists.\n// Returns absolute path including trailing '/' or error if path does not exist.\nfunc OutDir(path string) (string, error) {\n\toutDir, err := filepath.Abs(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tstat, err := os.Stat(outDir)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif !stat.IsDir() {\n\t\treturn \"\", fmt.Errorf(\"output directory %s is not a directory\", outDir)\n\t}\n\toutDir = outDir + \"/\"\n\treturn outDir, nil\n}","line":{"from":25,"to":43}} {"id":100000110,"name":"main","signature":"func main()","file":"cmd/genyaml/gen_kubectl_yaml.go","code":"func main() {\n\tpath := \"docs/yaml/kubectl\"\n\tif len(os.Args) == 2 {\n\t\tpath = os.Args[1]\n\t} else if len(os.Args) \u003e 2 {\n\t\tfmt.Fprintf(os.Stderr, \"usage: %s [output directory]\\n\", os.Args[0])\n\t\tos.Exit(1)\n\t}\n\n\toutDir, err := genutils.OutDir(path)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"failed to get output directory: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\t// Set environment variables used by kubectl so the output is consistent,\n\t// regardless of where we run.\n\tos.Setenv(\"HOME\", \"/home/username\")\n\tkubectl := cmd.NewKubectlCommand(cmd.KubectlOptions{IOStreams: genericclioptions.IOStreams{In: bytes.NewReader(nil), Out: io.Discard, ErrOut: io.Discard}})\n\tgenYaml(kubectl, \"\", outDir)\n\tfor _, c := range kubectl.Commands() {\n\t\tgenYaml(c, \"kubectl\", outDir)\n\t}\n}","line":{"from":51,"to":74}} {"id":100000111,"name":"forceMultiLine","signature":"func forceMultiLine(s string) string","file":"cmd/genyaml/gen_kubectl_yaml.go","code":"// Temporary workaround for yaml lib generating incorrect yaml with long strings\n// that do not contain \\n.\nfunc forceMultiLine(s string) string {\n\tif len(s) \u003e 60 \u0026\u0026 !strings.Contains(s, \"\\n\") {\n\t\ts = s + \"\\n\"\n\t}\n\treturn s\n}","line":{"from":76,"to":83}} {"id":100000112,"name":"genFlagResult","signature":"func genFlagResult(flags *pflag.FlagSet) []cmdOption","file":"cmd/genyaml/gen_kubectl_yaml.go","code":"func genFlagResult(flags *pflag.FlagSet) []cmdOption {\n\tresult := []cmdOption{}\n\n\tflags.VisitAll(func(flag *pflag.Flag) {\n\t\t// Todo, when we mark a shorthand is deprecated, but specify an empty message.\n\t\t// The flag.ShorthandDeprecated is empty as the shorthand is deprecated.\n\t\t// Using len(flag.ShorthandDeprecated) \u003e 0 can't handle this, others are ok.\n\t\tif !(len(flag.ShorthandDeprecated) \u003e 0) \u0026\u0026 len(flag.Shorthand) \u003e 0 {\n\t\t\topt := cmdOption{\n\t\t\t\tflag.Name,\n\t\t\t\tflag.Shorthand,\n\t\t\t\tflag.DefValue,\n\t\t\t\tforceMultiLine(flag.Usage),\n\t\t\t}\n\t\t\tresult = append(result, opt)\n\t\t} else {\n\t\t\topt := cmdOption{\n\t\t\t\tName: flag.Name,\n\t\t\t\tDefaultValue: forceMultiLine(flag.DefValue),\n\t\t\t\tUsage: forceMultiLine(flag.Usage),\n\t\t\t}\n\t\t\tresult = append(result, opt)\n\t\t}\n\t})\n\n\treturn result\n}","line":{"from":85,"to":111}} {"id":100000113,"name":"genYaml","signature":"func genYaml(command *cobra.Command, parent, docsDir string)","file":"cmd/genyaml/gen_kubectl_yaml.go","code":"func genYaml(command *cobra.Command, parent, docsDir string) {\n\tdoc := cmdDoc{}\n\n\tdoc.Name = command.Name()\n\tdoc.Synopsis = forceMultiLine(command.Short)\n\tdoc.Description = forceMultiLine(command.Long)\n\n\tflags := command.NonInheritedFlags()\n\tif flags.HasFlags() {\n\t\tdoc.Options = genFlagResult(flags)\n\t}\n\tflags = command.InheritedFlags()\n\tif flags.HasFlags() {\n\t\tdoc.InheritedOptions = genFlagResult(flags)\n\t}\n\n\tif len(command.Example) \u003e 0 {\n\t\tdoc.Example = command.Example\n\t}\n\n\tif len(command.Commands()) \u003e 0 || len(parent) \u003e 0 {\n\t\tresult := []string{}\n\t\tif len(parent) \u003e 0 {\n\t\t\tresult = append(result, parent)\n\t\t}\n\t\tfor _, c := range command.Commands() {\n\t\t\tresult = append(result, c.Name())\n\t\t}\n\t\tdoc.SeeAlso = result\n\t}\n\n\tfinal, err := yaml.Marshal(\u0026doc)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\tvar filename string\n\n\tif parent == \"\" {\n\t\tfilename = docsDir + doc.Name + \".yaml\"\n\t} else {\n\t\tfilename = docsDir + parent + \"_\" + doc.Name + \".yaml\"\n\t}\n\n\toutFile, err := os.Create(filename)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tdefer outFile.Close()\n\t_, err = outFile.Write(final)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}","line":{"from":113,"to":169}} {"id":100000114,"name":"ForbiddenImportsFor","signature":"func (i *ImportRestriction) ForbiddenImportsFor(pkg Package) ([]string, error)","file":"cmd/importverifier/importverifier.go","code":"// ForbiddenImportsFor determines all of the forbidden\n// imports for a package given the import restrictions\nfunc (i *ImportRestriction) ForbiddenImportsFor(pkg Package) ([]string, error) {\n\tif restricted, err := i.isRestrictedDir(pkg.Dir); err != nil {\n\t\treturn []string{}, err\n\t} else if !restricted {\n\t\treturn []string{}, nil\n\t}\n\n\treturn i.forbiddenImportsFor(pkg), nil\n}","line":{"from":63,"to":73}} {"id":100000115,"name":"isRestrictedDir","signature":"func (i *ImportRestriction) isRestrictedDir(dir string) (bool, error)","file":"cmd/importverifier/importverifier.go","code":"// isRestrictedDir determines if the source directory has\n// any restrictions placed on it by this configuration.\n// A path will be restricted if:\n// - it falls under the base import path\n// - it does not fall under any of the ignored sub-trees\nfunc (i *ImportRestriction) isRestrictedDir(dir string) (bool, error) {\n\tif under, err := isPathUnder(i.BaseDir, dir); err != nil {\n\t\treturn false, err\n\t} else if !under {\n\t\treturn false, nil\n\t}\n\n\tfor _, ignored := range i.IgnoredSubTrees {\n\t\tif under, err := isPathUnder(ignored, dir); err != nil {\n\t\t\treturn false, err\n\t\t} else if under {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\treturn true, nil\n}","line":{"from":75,"to":96}} {"id":100000116,"name":"isPathUnder","signature":"func isPathUnder(base, path string) (bool, error)","file":"cmd/importverifier/importverifier.go","code":"// isPathUnder determines if path is under base\nfunc isPathUnder(base, path string) (bool, error) {\n\tabsBase, err := filepath.Abs(base)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tabsPath, err := filepath.Abs(path)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\trelPath, err := filepath.Rel(absBase, absPath)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t// if path is below base, the relative path\n\t// from base to path will not start with `../`\n\treturn !strings.HasPrefix(relPath, \"..\"), nil\n}","line":{"from":98,"to":117}} {"id":100000117,"name":"forbiddenImportsFor","signature":"func (i *ImportRestriction) forbiddenImportsFor(pkg Package) []string","file":"cmd/importverifier/importverifier.go","code":"// forbiddenImportsFor determines all of the forbidden\n// imports for a package given the import restrictions\n// and returns a deduplicated list of them\nfunc (i *ImportRestriction) forbiddenImportsFor(pkg Package) []string {\n\tforbiddenImportSet := map[string]struct{}{}\n\timports := pkg.Imports\n\tif !i.ExcludeTests {\n\t\timports = append(imports, append(pkg.TestImports, pkg.XTestImports...)...)\n\t}\n\tfor _, imp := range imports {\n\t\tpath := extractVendorPath(imp)\n\t\tif i.isForbidden(path) {\n\t\t\tforbiddenImportSet[path] = struct{}{}\n\t\t}\n\t}\n\n\tvar forbiddenImports []string\n\tfor imp := range forbiddenImportSet {\n\t\tforbiddenImports = append(forbiddenImports, imp)\n\t}\n\treturn forbiddenImports\n}","line":{"from":119,"to":140}} {"id":100000118,"name":"extractVendorPath","signature":"func extractVendorPath(path string) string","file":"cmd/importverifier/importverifier.go","code":"// extractVendorPath removes a vendor prefix if one exists\nfunc extractVendorPath(path string) string {\n\tvendorPath := \"/vendor/\"\n\tif !strings.Contains(path, vendorPath) {\n\t\treturn path\n\t}\n\n\treturn path[strings.Index(path, vendorPath)+len(vendorPath):]\n}","line":{"from":142,"to":150}} {"id":100000119,"name":"isForbidden","signature":"func (i *ImportRestriction) isForbidden(imp string) bool","file":"cmd/importverifier/importverifier.go","code":"// isForbidden determines if an import is forbidden,\n// which is true when the import is:\n// - of a package under the rootPackage\n// - is not of the base import path or a sub-package of it\n// - is not of an allowed path or a sub-package of one\nfunc (i *ImportRestriction) isForbidden(imp string) bool {\n\timportsBelowRoot := strings.HasPrefix(imp, rootPackage)\n\timportsBelowBase := strings.HasPrefix(imp, i.BaseDir)\n\timportsAllowed := false\n\tfor _, allowed := range i.AllowedImports {\n\t\texactlyImportsAllowed := imp == allowed\n\t\timportsBelowAllowed := strings.HasPrefix(imp, fmt.Sprintf(\"%s/\", allowed))\n\t\timportsAllowed = importsAllowed || (importsBelowAllowed || exactlyImportsAllowed)\n\t}\n\n\treturn importsBelowRoot \u0026\u0026 !importsBelowBase \u0026\u0026 !importsAllowed\n}","line":{"from":152,"to":168}} {"id":100000120,"name":"main","signature":"func main()","file":"cmd/importverifier/importverifier.go","code":"func main() {\n\tif len(os.Args) != 3 {\n\t\tlog.Fatalf(\"Usage: %s ROOT RESTRICTIONS.yaml\", os.Args[0])\n\t}\n\n\trootPackage = os.Args[1]\n\tconfigFile := os.Args[2]\n\timportRestrictions, err := loadImportRestrictions(configFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to load import restrictions: %v\", err)\n\t}\n\n\tfoundForbiddenImports := false\n\tfor _, restriction := range importRestrictions {\n\t\tlog.Printf(\"Inspecting imports under %s...\\n\", restriction.BaseDir)\n\t\tpackages, err := resolvePackageTree(restriction.BaseDir)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed to resolve package tree: %v\", err)\n\t\t} else if len(packages) == 0 {\n\t\t\tlog.Fatalf(\"Found no packages under tree %s\", restriction.BaseDir)\n\t\t}\n\n\t\tlog.Printf(\"- validating imports for %d packages in the tree\", len(packages))\n\t\trestrictionViolated := false\n\t\tfor _, pkg := range packages {\n\t\t\tif forbidden, err := restriction.ForbiddenImportsFor(pkg); err != nil {\n\t\t\t\tlog.Fatalf(\"-- failed to validate imports: %v\", err)\n\t\t\t} else if len(forbidden) != 0 {\n\t\t\t\tlogForbiddenPackages(pkg.ImportPath, forbidden)\n\t\t\t\trestrictionViolated = true\n\t\t\t}\n\t\t}\n\t\tif restrictionViolated {\n\t\t\tfoundForbiddenImports = true\n\t\t\tlog.Println(\"- FAIL\")\n\t\t} else {\n\t\t\tlog.Println(\"- OK\")\n\t\t}\n\t}\n\n\tif foundForbiddenImports {\n\t\tos.Exit(1)\n\t}\n}","line":{"from":172,"to":215}} {"id":100000121,"name":"loadImportRestrictions","signature":"func loadImportRestrictions(configFile string) ([]ImportRestriction, error)","file":"cmd/importverifier/importverifier.go","code":"func loadImportRestrictions(configFile string) ([]ImportRestriction, error) {\n\tconfig, err := os.ReadFile(configFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load configuration from %s: %v\", configFile, err)\n\t}\n\n\tvar importRestrictions []ImportRestriction\n\tif err := yaml.Unmarshal(config, \u0026importRestrictions); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal from %s: %v\", configFile, err)\n\t}\n\n\treturn importRestrictions, nil\n}","line":{"from":217,"to":229}} {"id":100000122,"name":"resolvePackageTree","signature":"func resolvePackageTree(treeBase string) ([]Package, error)","file":"cmd/importverifier/importverifier.go","code":"func resolvePackageTree(treeBase string) ([]Package, error) {\n\t// try resolving with $cwd\n\tpackages, err := resolvePackageTreeInDir(\"\", treeBase)\n\tif err != nil || len(packages) == 0 {\n\t\t// if that fails or finds no packages, resolve under ./vendor/$treeBase\n\t\tstagingPackages, stagingErr := resolvePackageTreeInDir(filepath.Join(\"./vendor\", treeBase), treeBase)\n\t\tif stagingErr == nil \u0026\u0026 len(stagingPackages) \u003e 0 {\n\t\t\t// if that succeeds, return\n\t\t\treturn stagingPackages, stagingErr\n\t\t}\n\t}\n\t// otherwise, return original packages and error\n\treturn packages, err\n}","line":{"from":231,"to":244}} {"id":100000123,"name":"resolvePackageTreeInDir","signature":"func resolvePackageTreeInDir(dir string, treeBase string) ([]Package, error)","file":"cmd/importverifier/importverifier.go","code":"func resolvePackageTreeInDir(dir string, treeBase string) ([]Package, error) {\n\tcmd := \"go\"\n\targs := []string{\"list\", \"-json\", fmt.Sprintf(\"%s...\", treeBase)}\n\tc := exec.Command(cmd, args...)\n\tc.Dir = dir\n\tstdout, err := c.Output()\n\tif err != nil {\n\t\tvar message string\n\t\tif ee, ok := err.(*exec.ExitError); ok {\n\t\t\tmessage = fmt.Sprintf(\"%v\\n%v\", ee, string(ee.Stderr))\n\t\t} else {\n\t\t\tmessage = fmt.Sprintf(\"%v\", err)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"failed to run `%s %s`: %v\", cmd, strings.Join(args, \" \"), message)\n\t}\n\n\tpackages, err := decodePackages(bytes.NewReader(stdout))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to decode packages: %v\", err)\n\t}\n\n\treturn packages, nil\n}","line":{"from":246,"to":268}} {"id":100000124,"name":"decodePackages","signature":"func decodePackages(r io.Reader) ([]Package, error)","file":"cmd/importverifier/importverifier.go","code":"func decodePackages(r io.Reader) ([]Package, error) {\n\t// `go list -json` concatenates package definitions\n\t// instead of emitting a single valid JSON, so we\n\t// need to stream the output to decode it into the\n\t// data we are looking for instead of just using a\n\t// simple JSON decoder on stdout\n\tvar packages []Package\n\tdecoder := json.NewDecoder(r)\n\tfor decoder.More() {\n\t\tvar pkg Package\n\t\tif err := decoder.Decode(\u0026pkg); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid package: %v\", err)\n\t\t}\n\t\tpackages = append(packages, pkg)\n\t}\n\n\treturn packages, nil\n}","line":{"from":270,"to":287}} {"id":100000125,"name":"logForbiddenPackages","signature":"func logForbiddenPackages(base string, forbidden []string)","file":"cmd/importverifier/importverifier.go","code":"func logForbiddenPackages(base string, forbidden []string) {\n\tlog.Printf(\"-- found forbidden imports for %s:\\n\", base)\n\tfor _, forbiddenPackage := range forbidden {\n\t\tlog.Printf(\"--- %s\\n\", forbiddenPackage)\n\t}\n}","line":{"from":289,"to":294}} {"id":100000126,"name":"main","signature":"func main()","file":"cmd/kube-apiserver/apiserver.go","code":"func main() {\n\tcommand := app.NewAPIServerCommand()\n\tcode := cli.Run(command)\n\tos.Exit(code)\n}","line":{"from":32,"to":36}} {"id":100000127,"name":"createAggregatorConfig","signature":"func createAggregatorConfig(","file":"cmd/kube-apiserver/app/aggregator.go","code":"func createAggregatorConfig(\n\tkubeAPIServerConfig genericapiserver.Config,\n\tcommandOptions *options.ServerRunOptions,\n\texternalInformers kubeexternalinformers.SharedInformerFactory,\n\tserviceResolver aggregatorapiserver.ServiceResolver,\n\tproxyTransport *http.Transport,\n\tpluginInitializers []admission.PluginInitializer,\n) (*aggregatorapiserver.Config, error) {\n\t// make a shallow copy to let us twiddle a few things\n\t// most of the config actually remains the same. We only need to mess with a couple items related to the particulars of the aggregator\n\tgenericConfig := kubeAPIServerConfig\n\tgenericConfig.PostStartHooks = map[string]genericapiserver.PostStartHookConfigEntry{}\n\tgenericConfig.RESTOptionsGetter = nil\n\t// prevent generic API server from installing the OpenAPI handler. Aggregator server\n\t// has its own customized OpenAPI handler.\n\tgenericConfig.SkipOpenAPIInstallation = true\n\n\tif utilfeature.DefaultFeatureGate.Enabled(genericfeatures.StorageVersionAPI) \u0026\u0026\n\t\tutilfeature.DefaultFeatureGate.Enabled(genericfeatures.APIServerIdentity) {\n\t\t// Add StorageVersionPrecondition handler to aggregator-apiserver.\n\t\t// The handler will block write requests to built-in resources until the\n\t\t// target resources' storage versions are up-to-date.\n\t\tgenericConfig.BuildHandlerChainFunc = genericapiserver.BuildHandlerChainWithStorageVersionPrecondition\n\t}\n\n\t// copy the etcd options so we don't mutate originals.\n\t// we assume that the etcd options have been completed already. avoid messing with anything outside\n\t// of changes to StorageConfig as that may lead to unexpected behavior when the options are applied.\n\tetcdOptions := *commandOptions.Etcd\n\tetcdOptions.StorageConfig.Paging = utilfeature.DefaultFeatureGate.Enabled(genericfeatures.APIListChunking)\n\tetcdOptions.StorageConfig.Codec = aggregatorscheme.Codecs.LegacyCodec(v1.SchemeGroupVersion, v1beta1.SchemeGroupVersion)\n\tetcdOptions.StorageConfig.EncodeVersioner = runtime.NewMultiGroupVersioner(v1.SchemeGroupVersion, schema.GroupKind{Group: v1beta1.GroupName})\n\tetcdOptions.SkipHealthEndpoints = true // avoid double wiring of health checks\n\tif err := etcdOptions.ApplyTo(\u0026genericConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// override MergedResourceConfig with aggregator defaults and registry\n\tif err := commandOptions.APIEnablement.ApplyTo(\n\t\t\u0026genericConfig,\n\t\taggregatorapiserver.DefaultAPIResourceConfigSource(),\n\t\taggregatorscheme.Scheme); err != nil {\n\t\treturn nil, err\n\t}\n\n\taggregatorConfig := \u0026aggregatorapiserver.Config{\n\t\tGenericConfig: \u0026genericapiserver.RecommendedConfig{\n\t\t\tConfig: genericConfig,\n\t\t\tSharedInformerFactory: externalInformers,\n\t\t},\n\t\tExtraConfig: aggregatorapiserver.ExtraConfig{\n\t\t\tProxyClientCertFile: commandOptions.ProxyClientCertFile,\n\t\t\tProxyClientKeyFile: commandOptions.ProxyClientKeyFile,\n\t\t\tServiceResolver: serviceResolver,\n\t\t\tProxyTransport: proxyTransport,\n\t\t\tRejectForwardingRedirects: commandOptions.AggregatorRejectForwardingRedirects,\n\t\t},\n\t}\n\n\t// we need to clear the poststarthooks so we don't add them multiple times to all the servers (that fails)\n\taggregatorConfig.GenericConfig.PostStartHooks = map[string]genericapiserver.PostStartHookConfigEntry{}\n\n\treturn aggregatorConfig, nil\n}","line":{"from":54,"to":117}} {"id":100000128,"name":"createAggregatorServer","signature":"func createAggregatorServer(aggregatorConfig *aggregatorapiserver.Config, delegateAPIServer genericapiserver.DelegationTarget, apiExtensionInformers apiextensionsinformers.SharedInformerFactory, crdAPIEnabled bool) (*aggregatorapiserver.APIAggregator, error)","file":"cmd/kube-apiserver/app/aggregator.go","code":"func createAggregatorServer(aggregatorConfig *aggregatorapiserver.Config, delegateAPIServer genericapiserver.DelegationTarget, apiExtensionInformers apiextensionsinformers.SharedInformerFactory, crdAPIEnabled bool) (*aggregatorapiserver.APIAggregator, error) {\n\taggregatorServer, err := aggregatorConfig.Complete().NewWithDelegate(delegateAPIServer)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create controllers for auto-registration\n\tapiRegistrationClient, err := apiregistrationclient.NewForConfig(aggregatorConfig.GenericConfig.LoopbackClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tautoRegistrationController := autoregister.NewAutoRegisterController(aggregatorServer.APIRegistrationInformers.Apiregistration().V1().APIServices(), apiRegistrationClient)\n\tapiServices := apiServicesToRegister(delegateAPIServer, autoRegistrationController)\n\tcrdRegistrationController := crdregistration.NewCRDRegistrationController(\n\t\tapiExtensionInformers.Apiextensions().V1().CustomResourceDefinitions(),\n\t\tautoRegistrationController)\n\n\t// Imbue all builtin group-priorities onto the aggregated discovery\n\tif aggregatorConfig.GenericConfig.AggregatedDiscoveryGroupManager != nil {\n\t\tfor gv, entry := range apiVersionPriorities {\n\t\t\taggregatorConfig.GenericConfig.AggregatedDiscoveryGroupManager.SetGroupVersionPriority(metav1.GroupVersion(gv), int(entry.group), int(entry.version))\n\t\t}\n\t}\n\n\terr = aggregatorServer.GenericAPIServer.AddPostStartHook(\"kube-apiserver-autoregistration\", func(context genericapiserver.PostStartHookContext) error {\n\t\tgo crdRegistrationController.Run(5, context.StopCh)\n\t\tgo func() {\n\t\t\t// let the CRD controller process the initial set of CRDs before starting the autoregistration controller.\n\t\t\t// this prevents the autoregistration controller's initial sync from deleting APIServices for CRDs that still exist.\n\t\t\t// we only need to do this if CRDs are enabled on this server. We can't use discovery because we are the source for discovery.\n\t\t\tif crdAPIEnabled {\n\t\t\t\tklog.Infof(\"waiting for initial CRD sync...\")\n\t\t\t\tcrdRegistrationController.WaitForInitialSync()\n\t\t\t\tklog.Infof(\"initial CRD sync complete...\")\n\t\t\t} else {\n\t\t\t\tklog.Infof(\"CRD API not enabled, starting APIService registration without waiting for initial CRD sync\")\n\t\t\t}\n\t\t\tautoRegistrationController.Run(5, context.StopCh)\n\t\t}()\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = aggregatorServer.GenericAPIServer.AddBootSequenceHealthChecks(\n\t\tmakeAPIServiceAvailableHealthCheck(\n\t\t\t\"autoregister-completion\",\n\t\t\tapiServices,\n\t\t\taggregatorServer.APIRegistrationInformers.Apiregistration().V1().APIServices(),\n\t\t),\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn aggregatorServer, nil\n}","line":{"from":119,"to":176}} {"id":100000129,"name":"makeAPIService","signature":"func makeAPIService(gv schema.GroupVersion) *v1.APIService","file":"cmd/kube-apiserver/app/aggregator.go","code":"func makeAPIService(gv schema.GroupVersion) *v1.APIService {\n\tapiServicePriority, ok := apiVersionPriorities[gv]\n\tif !ok {\n\t\t// if we aren't found, then we shouldn't register ourselves because it could result in a CRD group version\n\t\t// being permanently stuck in the APIServices list.\n\t\tklog.Infof(\"Skipping APIService creation for %v\", gv)\n\t\treturn nil\n\t}\n\treturn \u0026v1.APIService{\n\t\tObjectMeta: metav1.ObjectMeta{Name: gv.Version + \".\" + gv.Group},\n\t\tSpec: v1.APIServiceSpec{\n\t\t\tGroup: gv.Group,\n\t\t\tVersion: gv.Version,\n\t\t\tGroupPriorityMinimum: apiServicePriority.group,\n\t\t\tVersionPriority: apiServicePriority.version,\n\t\t},\n\t}\n}","line":{"from":178,"to":195}} {"id":100000130,"name":"makeAPIServiceAvailableHealthCheck","signature":"func makeAPIServiceAvailableHealthCheck(name string, apiServices []*v1.APIService, apiServiceInformer informers.APIServiceInformer) healthz.HealthChecker","file":"cmd/kube-apiserver/app/aggregator.go","code":"// makeAPIServiceAvailableHealthCheck returns a healthz check that returns healthy\n// once all of the specified services have been observed to be available at least once.\nfunc makeAPIServiceAvailableHealthCheck(name string, apiServices []*v1.APIService, apiServiceInformer informers.APIServiceInformer) healthz.HealthChecker {\n\t// Track the auto-registered API services that have not been observed to be available yet\n\tpendingServiceNamesLock := \u0026sync.RWMutex{}\n\tpendingServiceNames := sets.NewString()\n\tfor _, service := range apiServices {\n\t\tpendingServiceNames.Insert(service.Name)\n\t}\n\n\t// When an APIService in the list is seen as available, remove it from the pending list\n\thandleAPIServiceChange := func(service *v1.APIService) {\n\t\tpendingServiceNamesLock.Lock()\n\t\tdefer pendingServiceNamesLock.Unlock()\n\t\tif !pendingServiceNames.Has(service.Name) {\n\t\t\treturn\n\t\t}\n\t\tif v1helper.IsAPIServiceConditionTrue(service, v1.Available) {\n\t\t\tpendingServiceNames.Delete(service.Name)\n\t\t}\n\t}\n\n\t// Watch add/update events for APIServices\n\tapiServiceInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) { handleAPIServiceChange(obj.(*v1.APIService)) },\n\t\tUpdateFunc: func(old, new interface{}) { handleAPIServiceChange(new.(*v1.APIService)) },\n\t})\n\n\t// Don't return healthy until the pending list is empty\n\treturn healthz.NamedCheck(name, func(r *http.Request) error {\n\t\tpendingServiceNamesLock.RLock()\n\t\tdefer pendingServiceNamesLock.RUnlock()\n\t\tif pendingServiceNames.Len() \u003e 0 {\n\t\t\treturn fmt.Errorf(\"missing APIService: %v\", pendingServiceNames.List())\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":197,"to":234}} {"id":100000131,"name":"apiServicesToRegister","signature":"func apiServicesToRegister(delegateAPIServer genericapiserver.DelegationTarget, registration autoregister.AutoAPIServiceRegistration) []*v1.APIService","file":"cmd/kube-apiserver/app/aggregator.go","code":"func apiServicesToRegister(delegateAPIServer genericapiserver.DelegationTarget, registration autoregister.AutoAPIServiceRegistration) []*v1.APIService {\n\tapiServices := []*v1.APIService{}\n\n\tfor _, curr := range delegateAPIServer.ListedPaths() {\n\t\tif curr == \"/api/v1\" {\n\t\t\tapiService := makeAPIService(schema.GroupVersion{Group: \"\", Version: \"v1\"})\n\t\t\tregistration.AddAPIServiceToSyncOnStart(apiService)\n\t\t\tapiServices = append(apiServices, apiService)\n\t\t\tcontinue\n\t\t}\n\n\t\tif !strings.HasPrefix(curr, \"/apis/\") {\n\t\t\tcontinue\n\t\t}\n\t\t// this comes back in a list that looks like /apis/rbac.authorization.k8s.io/v1alpha1\n\t\ttokens := strings.Split(curr, \"/\")\n\t\tif len(tokens) != 4 {\n\t\t\tcontinue\n\t\t}\n\n\t\tapiService := makeAPIService(schema.GroupVersion{Group: tokens[2], Version: tokens[3]})\n\t\tif apiService == nil {\n\t\t\tcontinue\n\t\t}\n\t\tregistration.AddAPIServiceToSyncOnStart(apiService)\n\t\tapiServices = append(apiServices, apiService)\n\t}\n\n\treturn apiServices\n}","line":{"from":297,"to":326}} {"id":100000132,"name":"createAPIExtensionsConfig","signature":"func createAPIExtensionsConfig(","file":"cmd/kube-apiserver/app/apiextensions.go","code":"func createAPIExtensionsConfig(\n\tkubeAPIServerConfig genericapiserver.Config,\n\texternalInformers kubeexternalinformers.SharedInformerFactory,\n\tpluginInitializers []admission.PluginInitializer,\n\tcommandOptions *options.ServerRunOptions,\n\tmasterCount int,\n\tserviceResolver webhook.ServiceResolver,\n\tauthResolverWrapper webhook.AuthenticationInfoResolverWrapper,\n) (*apiextensionsapiserver.Config, error) {\n\t// make a shallow copy to let us twiddle a few things\n\t// most of the config actually remains the same. We only need to mess with a couple items related to the particulars of the apiextensions\n\tgenericConfig := kubeAPIServerConfig\n\tgenericConfig.PostStartHooks = map[string]genericapiserver.PostStartHookConfigEntry{}\n\tgenericConfig.RESTOptionsGetter = nil\n\n\t// copy the etcd options so we don't mutate originals.\n\t// we assume that the etcd options have been completed already. avoid messing with anything outside\n\t// of changes to StorageConfig as that may lead to unexpected behavior when the options are applied.\n\tetcdOptions := *commandOptions.Etcd\n\tetcdOptions.StorageConfig.Paging = utilfeature.DefaultFeatureGate.Enabled(features.APIListChunking)\n\t// this is where the true decodable levels come from.\n\tetcdOptions.StorageConfig.Codec = apiextensionsapiserver.Codecs.LegacyCodec(v1beta1.SchemeGroupVersion, v1.SchemeGroupVersion)\n\t// prefer the more compact serialization (v1beta1) for storage until https://issue.k8s.io/82292 is resolved for objects whose v1 serialization is too big but whose v1beta1 serialization can be stored\n\tetcdOptions.StorageConfig.EncodeVersioner = runtime.NewMultiGroupVersioner(v1beta1.SchemeGroupVersion, schema.GroupKind{Group: v1beta1.GroupName})\n\tetcdOptions.SkipHealthEndpoints = true // avoid double wiring of health checks\n\tif err := etcdOptions.ApplyTo(\u0026genericConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// override MergedResourceConfig with apiextensions defaults and registry\n\tif err := commandOptions.APIEnablement.ApplyTo(\n\t\t\u0026genericConfig,\n\t\tapiextensionsapiserver.DefaultAPIResourceConfigSource(),\n\t\tapiextensionsapiserver.Scheme); err != nil {\n\t\treturn nil, err\n\t}\n\tcrdRESTOptionsGetter, err := apiextensionsoptions.NewCRDRESTOptionsGetter(etcdOptions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tapiextensionsConfig := \u0026apiextensionsapiserver.Config{\n\t\tGenericConfig: \u0026genericapiserver.RecommendedConfig{\n\t\t\tConfig: genericConfig,\n\t\t\tSharedInformerFactory: externalInformers,\n\t\t},\n\t\tExtraConfig: apiextensionsapiserver.ExtraConfig{\n\t\t\tCRDRESTOptionsGetter: crdRESTOptionsGetter,\n\t\t\tMasterCount: masterCount,\n\t\t\tAuthResolverWrapper: authResolverWrapper,\n\t\t\tServiceResolver: serviceResolver,\n\t\t},\n\t}\n\n\t// we need to clear the poststarthooks so we don't add them multiple times to all the servers (that fails)\n\tapiextensionsConfig.GenericConfig.PostStartHooks = map[string]genericapiserver.PostStartHookConfigEntry{}\n\n\treturn apiextensionsConfig, nil\n}","line":{"from":38,"to":95}} {"id":100000133,"name":"createAPIExtensionsServer","signature":"func createAPIExtensionsServer(apiextensionsConfig *apiextensionsapiserver.Config, delegateAPIServer genericapiserver.DelegationTarget) (*apiextensionsapiserver.CustomResourceDefinitions, error)","file":"cmd/kube-apiserver/app/apiextensions.go","code":"func createAPIExtensionsServer(apiextensionsConfig *apiextensionsapiserver.Config, delegateAPIServer genericapiserver.DelegationTarget) (*apiextensionsapiserver.CustomResourceDefinitions, error) {\n\treturn apiextensionsConfig.Complete().New(delegateAPIServer)\n}","line":{"from":97,"to":99}} {"id":100000134,"name":"AddCustomGlobalFlags","signature":"func AddCustomGlobalFlags(fs *pflag.FlagSet)","file":"cmd/kube-apiserver/app/options/globalflags.go","code":"// AddCustomGlobalFlags explicitly registers flags that internal packages register\n// against the global flagsets from \"flag\". We do this in order to prevent\n// unwanted flags from leaking into the kube-apiserver's flagset.\nfunc AddCustomGlobalFlags(fs *pflag.FlagSet) {\n\t// Lookup flags in global flag set and re-register the values with our flagset.\n\n\t// Adds flags from k8s.io/kubernetes/pkg/cloudprovider/providers.\n\tregisterLegacyGlobalFlags(fs)\n\n\t// Adds flags from k8s.io/apiserver/pkg/admission.\n\tglobalflag.Register(fs, \"default-not-ready-toleration-seconds\")\n\tglobalflag.Register(fs, \"default-unreachable-toleration-seconds\")\n}","line":{"from":29,"to":41}} {"id":100000135,"name":"registerLegacyGlobalFlags","signature":"func registerLegacyGlobalFlags(fs *pflag.FlagSet)","file":"cmd/kube-apiserver/app/options/globalflags_providerless.go","code":"func registerLegacyGlobalFlags(fs *pflag.FlagSet) {\n\t// no-op when no legacy providers are compiled in\n}","line":{"from":26,"to":28}} {"id":100000136,"name":"registerLegacyGlobalFlags","signature":"func registerLegacyGlobalFlags(fs *pflag.FlagSet)","file":"cmd/kube-apiserver/app/options/globalflags_providers.go","code":"func registerLegacyGlobalFlags(fs *pflag.FlagSet) {\n\tglobalflag.Register(fs, \"cloud-provider-gce-lb-src-cidrs\")\n\tglobalflag.Register(fs, \"cloud-provider-gce-l7lb-src-cidrs\")\n\tfs.MarkDeprecated(\"cloud-provider-gce-lb-src-cidrs\", \"This flag will be removed once the GCE Cloud Provider is removed from kube-apiserver\")\n}","line":{"from":28,"to":32}} {"id":100000137,"name":"NewServerRunOptions","signature":"func NewServerRunOptions() *ServerRunOptions","file":"cmd/kube-apiserver/app/options/options.go","code":"// NewServerRunOptions creates a new ServerRunOptions object with default parameters\nfunc NewServerRunOptions() *ServerRunOptions {\n\ts := ServerRunOptions{\n\t\tGenericServerRunOptions: genericoptions.NewServerRunOptions(),\n\t\tEtcd: genericoptions.NewEtcdOptions(storagebackend.NewDefaultConfig(kubeoptions.DefaultEtcdPathPrefix, nil)),\n\t\tSecureServing: kubeoptions.NewSecureServingOptions(),\n\t\tAudit: genericoptions.NewAuditOptions(),\n\t\tFeatures: genericoptions.NewFeatureOptions(),\n\t\tAdmission: kubeoptions.NewAdmissionOptions(),\n\t\tAuthentication: kubeoptions.NewBuiltInAuthenticationOptions().WithAll(),\n\t\tAuthorization: kubeoptions.NewBuiltInAuthorizationOptions(),\n\t\tCloudProvider: kubeoptions.NewCloudProviderOptions(),\n\t\tAPIEnablement: genericoptions.NewAPIEnablementOptions(),\n\t\tEgressSelector: genericoptions.NewEgressSelectorOptions(),\n\t\tMetrics: metrics.NewOptions(),\n\t\tLogs: logs.NewOptions(),\n\t\tTraces: genericoptions.NewTracingOptions(),\n\n\t\tEnableLogsHandler: true,\n\t\tEventTTL: 1 * time.Hour,\n\t\tMasterCount: 1,\n\t\tEndpointReconcilerType: string(reconcilers.LeaseEndpointReconcilerType),\n\t\tKubeletConfig: kubeletclient.KubeletClientConfig{\n\t\t\tPort: ports.KubeletPort,\n\t\t\tReadOnlyPort: ports.KubeletReadOnlyPort,\n\t\t\tPreferredAddressTypes: []string{\n\t\t\t\t// --override-hostname\n\t\t\t\tstring(api.NodeHostName),\n\n\t\t\t\t// internal, preferring DNS if reported\n\t\t\t\tstring(api.NodeInternalDNS),\n\t\t\t\tstring(api.NodeInternalIP),\n\n\t\t\t\t// external, preferring DNS if reported\n\t\t\t\tstring(api.NodeExternalDNS),\n\t\t\t\tstring(api.NodeExternalIP),\n\t\t\t},\n\t\t\tHTTPTimeout: time.Duration(5) * time.Second,\n\t\t},\n\t\tServiceNodePortRange: kubeoptions.DefaultServiceNodePortRange,\n\t\tAggregatorRejectForwardingRedirects: true,\n\t}\n\n\t// Overwrite the default for storage data format.\n\ts.Etcd.DefaultStorageMediaType = \"application/vnd.kubernetes.protobuf\"\n\n\treturn \u0026s\n}","line":{"from":92,"to":139}} {"id":100000138,"name":"Flags","signature":"func (s *ServerRunOptions) Flags() (fss cliflag.NamedFlagSets)","file":"cmd/kube-apiserver/app/options/options.go","code":"// Flags returns flags for a specific APIServer by section name\nfunc (s *ServerRunOptions) Flags() (fss cliflag.NamedFlagSets) {\n\t// Add the generic flags.\n\ts.GenericServerRunOptions.AddUniversalFlags(fss.FlagSet(\"generic\"))\n\ts.Etcd.AddFlags(fss.FlagSet(\"etcd\"))\n\ts.SecureServing.AddFlags(fss.FlagSet(\"secure serving\"))\n\ts.Audit.AddFlags(fss.FlagSet(\"auditing\"))\n\ts.Features.AddFlags(fss.FlagSet(\"features\"))\n\ts.Authentication.AddFlags(fss.FlagSet(\"authentication\"))\n\ts.Authorization.AddFlags(fss.FlagSet(\"authorization\"))\n\ts.CloudProvider.AddFlags(fss.FlagSet(\"cloud provider\"))\n\ts.APIEnablement.AddFlags(fss.FlagSet(\"API enablement\"))\n\ts.EgressSelector.AddFlags(fss.FlagSet(\"egress selector\"))\n\ts.Admission.AddFlags(fss.FlagSet(\"admission\"))\n\ts.Metrics.AddFlags(fss.FlagSet(\"metrics\"))\n\tlogsapi.AddFlags(s.Logs, fss.FlagSet(\"logs\"))\n\ts.Traces.AddFlags(fss.FlagSet(\"traces\"))\n\n\t// Note: the weird \"\"+ in below lines seems to be the only way to get gofmt to\n\t// arrange these text blocks sensibly. Grrr.\n\tfs := fss.FlagSet(\"misc\")\n\tfs.DurationVar(\u0026s.EventTTL, \"event-ttl\", s.EventTTL,\n\t\t\"Amount of time to retain events.\")\n\n\tfs.BoolVar(\u0026s.AllowPrivileged, \"allow-privileged\", s.AllowPrivileged,\n\t\t\"If true, allow privileged containers. [default=false]\")\n\n\tfs.BoolVar(\u0026s.EnableLogsHandler, \"enable-logs-handler\", s.EnableLogsHandler,\n\t\t\"If true, install a /logs handler for the apiserver logs.\")\n\tfs.MarkDeprecated(\"enable-logs-handler\", \"This flag will be removed in v1.19\")\n\n\tfs.Int64Var(\u0026s.MaxConnectionBytesPerSec, \"max-connection-bytes-per-sec\", s.MaxConnectionBytesPerSec, \"\"+\n\t\t\"If non-zero, throttle each user connection to this number of bytes/sec. \"+\n\t\t\"Currently only applies to long-running requests.\")\n\n\tfs.IntVar(\u0026s.MasterCount, \"apiserver-count\", s.MasterCount,\n\t\t\"The number of apiservers running in the cluster, must be a positive number. (In use when --endpoint-reconciler-type=master-count is enabled.)\")\n\tfs.MarkDeprecated(\"apiserver-count\", \"apiserver-count is deprecated and will be removed in a future version.\")\n\n\tfs.StringVar(\u0026s.EndpointReconcilerType, \"endpoint-reconciler-type\", s.EndpointReconcilerType,\n\t\t\"Use an endpoint reconciler (\"+strings.Join(reconcilers.AllTypes.Names(), \", \")+\") master-count is deprecated, and will be removed in a future version.\")\n\n\t// See #14282 for details on how to test/try this option out.\n\t// TODO: remove this comment once this option is tested in CI.\n\tfs.IntVar(\u0026s.KubernetesServiceNodePort, \"kubernetes-service-node-port\", s.KubernetesServiceNodePort, \"\"+\n\t\t\"If non-zero, the Kubernetes master service (which apiserver creates/maintains) will be \"+\n\t\t\"of type NodePort, using this as the value of the port. If zero, the Kubernetes master \"+\n\t\t\"service will be of type ClusterIP.\")\n\n\tfs.StringVar(\u0026s.ServiceClusterIPRanges, \"service-cluster-ip-range\", s.ServiceClusterIPRanges, \"\"+\n\t\t\"A CIDR notation IP range from which to assign service cluster IPs. This must not \"+\n\t\t\"overlap with any IP ranges assigned to nodes or pods. Max of two dual-stack CIDRs is allowed.\")\n\n\tfs.Var(\u0026s.ServiceNodePortRange, \"service-node-port-range\", \"\"+\n\t\t\"A port range to reserve for services with NodePort visibility. This must not overlap with the ephemeral port range on nodes. \"+\n\t\t\"Example: '30000-32767'. Inclusive at both ends of the range.\")\n\n\t// Kubelet related flags:\n\tfs.StringSliceVar(\u0026s.KubeletConfig.PreferredAddressTypes, \"kubelet-preferred-address-types\", s.KubeletConfig.PreferredAddressTypes,\n\t\t\"List of the preferred NodeAddressTypes to use for kubelet connections.\")\n\n\tfs.UintVar(\u0026s.KubeletConfig.Port, \"kubelet-port\", s.KubeletConfig.Port,\n\t\t\"DEPRECATED: kubelet port.\")\n\tfs.MarkDeprecated(\"kubelet-port\", \"kubelet-port is deprecated and will be removed.\")\n\n\tfs.UintVar(\u0026s.KubeletConfig.ReadOnlyPort, \"kubelet-read-only-port\", s.KubeletConfig.ReadOnlyPort,\n\t\t\"DEPRECATED: kubelet read only port.\")\n\tfs.MarkDeprecated(\"kubelet-read-only-port\", \"kubelet-read-only-port is deprecated and will be removed.\")\n\n\tfs.DurationVar(\u0026s.KubeletConfig.HTTPTimeout, \"kubelet-timeout\", s.KubeletConfig.HTTPTimeout,\n\t\t\"Timeout for kubelet operations.\")\n\n\tfs.StringVar(\u0026s.KubeletConfig.TLSClientConfig.CertFile, \"kubelet-client-certificate\", s.KubeletConfig.TLSClientConfig.CertFile,\n\t\t\"Path to a client cert file for TLS.\")\n\n\tfs.StringVar(\u0026s.KubeletConfig.TLSClientConfig.KeyFile, \"kubelet-client-key\", s.KubeletConfig.TLSClientConfig.KeyFile,\n\t\t\"Path to a client key file for TLS.\")\n\n\tfs.StringVar(\u0026s.KubeletConfig.TLSClientConfig.CAFile, \"kubelet-certificate-authority\", s.KubeletConfig.TLSClientConfig.CAFile,\n\t\t\"Path to a cert file for the certificate authority.\")\n\n\tfs.StringVar(\u0026s.ProxyClientCertFile, \"proxy-client-cert-file\", s.ProxyClientCertFile, \"\"+\n\t\t\"Client certificate used to prove the identity of the aggregator or kube-apiserver \"+\n\t\t\"when it must call out during a request. This includes proxying requests to a user \"+\n\t\t\"api-server and calling out to webhook admission plugins. It is expected that this \"+\n\t\t\"cert includes a signature from the CA in the --requestheader-client-ca-file flag. \"+\n\t\t\"That CA is published in the 'extension-apiserver-authentication' configmap in \"+\n\t\t\"the kube-system namespace. Components receiving calls from kube-aggregator should \"+\n\t\t\"use that CA to perform their half of the mutual TLS verification.\")\n\tfs.StringVar(\u0026s.ProxyClientKeyFile, \"proxy-client-key-file\", s.ProxyClientKeyFile, \"\"+\n\t\t\"Private key for the client certificate used to prove the identity of the aggregator or kube-apiserver \"+\n\t\t\"when it must call out during a request. This includes proxying requests to a user \"+\n\t\t\"api-server and calling out to webhook admission plugins.\")\n\n\tfs.BoolVar(\u0026s.EnableAggregatorRouting, \"enable-aggregator-routing\", s.EnableAggregatorRouting,\n\t\t\"Turns on aggregator routing requests to endpoints IP rather than cluster IP.\")\n\n\tfs.BoolVar(\u0026s.AggregatorRejectForwardingRedirects, \"aggregator-reject-forwarding-redirect\", s.AggregatorRejectForwardingRedirects,\n\t\t\"Aggregator reject forwarding redirect response back to client.\")\n\n\tfs.StringVar(\u0026s.ServiceAccountSigningKeyFile, \"service-account-signing-key-file\", s.ServiceAccountSigningKeyFile, \"\"+\n\t\t\"Path to the file that contains the current private key of the service account token issuer. The issuer will sign issued ID tokens with this private key.\")\n\n\treturn fss\n}","line":{"from":141,"to":245}} {"id":100000139,"name":"validateClusterIPFlags","signature":"func validateClusterIPFlags(options *ServerRunOptions) []error","file":"cmd/kube-apiserver/app/options/validation.go","code":"// TODO: Longer term we should read this from some config store, rather than a flag.\n// validateClusterIPFlags is expected to be called after Complete()\nfunc validateClusterIPFlags(options *ServerRunOptions) []error {\n\tvar errs []error\n\t// maxCIDRBits is used to define the maximum CIDR size for the cluster ip(s)\n\tmaxCIDRBits := 20\n\tif utilfeature.DefaultFeatureGate.Enabled(features.MultiCIDRServiceAllocator) {\n\t\tmaxCIDRBits = 64\n\t}\n\n\t// validate that primary has been processed by user provided values or it has been defaulted\n\tif options.PrimaryServiceClusterIPRange.IP == nil {\n\t\terrs = append(errs, errors.New(\"--service-cluster-ip-range must contain at least one valid cidr\"))\n\t}\n\n\tserviceClusterIPRangeList := strings.Split(options.ServiceClusterIPRanges, \",\")\n\tif len(serviceClusterIPRangeList) \u003e 2 {\n\t\terrs = append(errs, errors.New(\"--service-cluster-ip-range must not contain more than two entries\"))\n\t}\n\n\t// Complete() expected to have set Primary* and Secondary*\n\t// primary CIDR validation\n\tif err := validateMaxCIDRRange(options.PrimaryServiceClusterIPRange, maxCIDRBits, \"--service-cluster-ip-range\"); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\tsecondaryServiceClusterIPRangeUsed := (options.SecondaryServiceClusterIPRange.IP != nil)\n\t// note: While the cluster might be dualstack (i.e. pods with multiple IPs), the user may choose\n\t// to only ingress traffic within and into the cluster on one IP family only. this family is decided\n\t// by the range set on --service-cluster-ip-range. If/when the user decides to use dual stack services\n\t// the Secondary* must be of different IPFamily than --service-cluster-ip-range\n\tif secondaryServiceClusterIPRangeUsed {\n\t\t// Should be dualstack IPFamily(PrimaryServiceClusterIPRange) != IPFamily(SecondaryServiceClusterIPRange)\n\t\tdualstack, err := netutils.IsDualStackCIDRs([]*net.IPNet{\u0026options.PrimaryServiceClusterIPRange, \u0026options.SecondaryServiceClusterIPRange})\n\t\tif err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"error attempting to validate dualstack for --service-cluster-ip-range value error:%v\", err))\n\t\t}\n\n\t\tif !dualstack {\n\t\t\terrs = append(errs, errors.New(\"--service-cluster-ip-range[0] and --service-cluster-ip-range[1] must be of different IP family\"))\n\t\t}\n\n\t\tif err := validateMaxCIDRRange(options.SecondaryServiceClusterIPRange, maxCIDRBits, \"--service-cluster-ip-range[1]\"); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\treturn errs\n}","line":{"from":34,"to":82}} {"id":100000140,"name":"validateMaxCIDRRange","signature":"func validateMaxCIDRRange(cidr net.IPNet, maxCIDRBits int, cidrFlag string) error","file":"cmd/kube-apiserver/app/options/validation.go","code":"func validateMaxCIDRRange(cidr net.IPNet, maxCIDRBits int, cidrFlag string) error {\n\t// Should be smallish sized cidr, this thing is kept in etcd\n\t// bigger cidr (specially those offered by IPv6) will add no value\n\t// significantly increase snapshotting time.\n\tvar ones, bits = cidr.Mask.Size()\n\tif bits-ones \u003e maxCIDRBits {\n\t\treturn fmt.Errorf(\"specified %s is too large; for %d-bit addresses, the mask must be \u003e= %d\", cidrFlag, bits, bits-maxCIDRBits)\n\t}\n\n\treturn nil\n}","line":{"from":84,"to":94}} {"id":100000141,"name":"validateServiceNodePort","signature":"func validateServiceNodePort(options *ServerRunOptions) []error","file":"cmd/kube-apiserver/app/options/validation.go","code":"func validateServiceNodePort(options *ServerRunOptions) []error {\n\tvar errs []error\n\n\tif options.KubernetesServiceNodePort \u003c 0 || options.KubernetesServiceNodePort \u003e 65535 {\n\t\terrs = append(errs, fmt.Errorf(\"--kubernetes-service-node-port %v must be between 0 and 65535, inclusive. If 0, the Kubernetes master service will be of type ClusterIP\", options.KubernetesServiceNodePort))\n\t}\n\n\tif options.KubernetesServiceNodePort \u003e 0 \u0026\u0026 !options.ServiceNodePortRange.Contains(options.KubernetesServiceNodePort) {\n\t\terrs = append(errs, fmt.Errorf(\"kubernetes service node port range %v doesn't contain %v\", options.ServiceNodePortRange, options.KubernetesServiceNodePort))\n\t}\n\treturn errs\n}","line":{"from":96,"to":107}} {"id":100000142,"name":"validateTokenRequest","signature":"func validateTokenRequest(options *ServerRunOptions) []error","file":"cmd/kube-apiserver/app/options/validation.go","code":"func validateTokenRequest(options *ServerRunOptions) []error {\n\tvar errs []error\n\n\tenableAttempted := options.ServiceAccountSigningKeyFile != \"\" ||\n\t\t(len(options.Authentication.ServiceAccounts.Issuers) != 0 \u0026\u0026 options.Authentication.ServiceAccounts.Issuers[0] != \"\") ||\n\t\tlen(options.Authentication.APIAudiences) != 0\n\n\tenableSucceeded := options.ServiceAccountIssuer != nil\n\n\tif !enableAttempted {\n\t\terrs = append(errs, errors.New(\"--service-account-signing-key-file and --service-account-issuer are required flags\"))\n\t}\n\n\tif enableAttempted \u0026\u0026 !enableSucceeded {\n\t\terrs = append(errs, errors.New(\"--service-account-signing-key-file, --service-account-issuer, and --api-audiences should be specified together\"))\n\t}\n\n\treturn errs\n}","line":{"from":109,"to":127}} {"id":100000143,"name":"validateAPIPriorityAndFairness","signature":"func validateAPIPriorityAndFairness(options *ServerRunOptions) []error","file":"cmd/kube-apiserver/app/options/validation.go","code":"func validateAPIPriorityAndFairness(options *ServerRunOptions) []error {\n\tif utilfeature.DefaultFeatureGate.Enabled(genericfeatures.APIPriorityAndFairness) \u0026\u0026 options.GenericServerRunOptions.EnablePriorityAndFairness {\n\t\t// If none of the following runtime config options are specified,\n\t\t// APF is assumed to be turned on. The internal APF controller uses\n\t\t// v1beta3 so it should be enabled.\n\t\tenabledAPIString := options.APIEnablement.RuntimeConfig.String()\n\t\ttestConfigs := []string{\"flowcontrol.apiserver.k8s.io/v1beta3\", \"api/beta\", \"api/all\"} // in the order of precedence\n\t\tfor _, testConfig := range testConfigs {\n\t\t\tif strings.Contains(enabledAPIString, fmt.Sprintf(\"%s=false\", testConfig)) {\n\t\t\t\treturn []error{fmt.Errorf(\"--runtime-config=%s=false conflicts with --enable-priority-and-fairness=true and --feature-gates=APIPriorityAndFairness=true\", testConfig)}\n\t\t\t}\n\t\t\tif strings.Contains(enabledAPIString, fmt.Sprintf(\"%s=true\", testConfig)) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":129,"to":147}} {"id":100000144,"name":"Validate","signature":"func (s *ServerRunOptions) Validate() []error","file":"cmd/kube-apiserver/app/options/validation.go","code":"// Validate checks ServerRunOptions and return a slice of found errs.\nfunc (s *ServerRunOptions) Validate() []error {\n\tvar errs []error\n\tif s.MasterCount \u003c= 0 {\n\t\terrs = append(errs, fmt.Errorf(\"--apiserver-count should be a positive number, but value '%d' provided\", s.MasterCount))\n\t}\n\terrs = append(errs, s.Etcd.Validate()...)\n\terrs = append(errs, validateClusterIPFlags(s)...)\n\terrs = append(errs, validateServiceNodePort(s)...)\n\terrs = append(errs, validateAPIPriorityAndFairness(s)...)\n\terrs = append(errs, s.SecureServing.Validate()...)\n\terrs = append(errs, s.Authentication.Validate()...)\n\terrs = append(errs, s.Authorization.Validate()...)\n\terrs = append(errs, s.Audit.Validate()...)\n\terrs = append(errs, s.Admission.Validate()...)\n\terrs = append(errs, s.APIEnablement.Validate(legacyscheme.Scheme, apiextensionsapiserver.Scheme, aggregatorscheme.Scheme)...)\n\terrs = append(errs, validateTokenRequest(s)...)\n\terrs = append(errs, s.Metrics.Validate()...)\n\n\treturn errs\n}","line":{"from":149,"to":169}} {"id":100000145,"name":"init","signature":"func init()","file":"cmd/kube-apiserver/app/server.go","code":"func init() {\n\tutilruntime.Must(logsapi.AddFeatureGates(utilfeature.DefaultMutableFeatureGate))\n}","line":{"from":91,"to":93}} {"id":100000146,"name":"NewAPIServerCommand","signature":"func NewAPIServerCommand() *cobra.Command","file":"cmd/kube-apiserver/app/server.go","code":"// NewAPIServerCommand creates a *cobra.Command object with default parameters\nfunc NewAPIServerCommand() *cobra.Command {\n\ts := options.NewServerRunOptions()\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"kube-apiserver\",\n\t\tLong: `The Kubernetes API server validates and configures data\nfor the api objects which include pods, services, replicationcontrollers, and\nothers. The API Server services REST operations and provides the frontend to the\ncluster's shared state through which all other components interact.`,\n\n\t\t// stop printing usage when the command errors\n\t\tSilenceUsage: true,\n\t\tPersistentPreRunE: func(*cobra.Command, []string) error {\n\t\t\t// silence client-go warnings.\n\t\t\t// kube-apiserver loopback clients should not log self-issued warnings.\n\t\t\trest.SetDefaultWarningHandler(rest.NoWarnings{})\n\t\t\treturn nil\n\t\t},\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tverflag.PrintAndExitIfRequested()\n\t\t\tfs := cmd.Flags()\n\n\t\t\t// Activate logging as soon as possible, after that\n\t\t\t// show flags with the final logging configuration.\n\t\t\tif err := logsapi.ValidateAndApply(s.Logs, utilfeature.DefaultFeatureGate); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcliflag.PrintFlags(fs)\n\n\t\t\t// set default options\n\t\t\tcompletedOptions, err := Complete(s)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// validate options\n\t\t\tif errs := completedOptions.Validate(); len(errs) != 0 {\n\t\t\t\treturn utilerrors.NewAggregate(errs)\n\t\t\t}\n\t\t\t// add feature enablement metrics\n\t\t\tutilfeature.DefaultMutableFeatureGate.AddMetrics()\n\t\t\treturn Run(completedOptions, genericapiserver.SetupSignalHandler())\n\t\t},\n\t\tArgs: func(cmd *cobra.Command, args []string) error {\n\t\t\tfor _, arg := range args {\n\t\t\t\tif len(arg) \u003e 0 {\n\t\t\t\t\treturn fmt.Errorf(\"%q does not take any arguments, got %q\", cmd.CommandPath(), args)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tfs := cmd.Flags()\n\tnamedFlagSets := s.Flags()\n\tverflag.AddFlags(namedFlagSets.FlagSet(\"global\"))\n\tglobalflag.AddGlobalFlags(namedFlagSets.FlagSet(\"global\"), cmd.Name(), logs.SkipLoggingConfigurationFlags())\n\toptions.AddCustomGlobalFlags(namedFlagSets.FlagSet(\"generic\"))\n\tfor _, f := range namedFlagSets.FlagSets {\n\t\tfs.AddFlagSet(f)\n\t}\n\n\tcols, _, _ := term.TerminalSize(cmd.OutOrStdout())\n\tcliflag.SetUsageAndHelpFunc(cmd, namedFlagSets, cols)\n\n\treturn cmd\n}","line":{"from":95,"to":161}} {"id":100000147,"name":"Run","signature":"func Run(completeOptions completedServerRunOptions, stopCh \u003c-chan struct{}) error","file":"cmd/kube-apiserver/app/server.go","code":"// Run runs the specified APIServer. This should never exit.\nfunc Run(completeOptions completedServerRunOptions, stopCh \u003c-chan struct{}) error {\n\t// To help debugging, immediately log version\n\tklog.Infof(\"Version: %+v\", version.Get())\n\n\tklog.InfoS(\"Golang settings\", \"GOGC\", os.Getenv(\"GOGC\"), \"GOMAXPROCS\", os.Getenv(\"GOMAXPROCS\"), \"GOTRACEBACK\", os.Getenv(\"GOTRACEBACK\"))\n\n\tserver, err := CreateServerChain(completeOptions)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprepared, err := server.PrepareRun()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn prepared.Run(stopCh)\n}","line":{"from":163,"to":181}} {"id":100000148,"name":"CreateServerChain","signature":"func CreateServerChain(completedOptions completedServerRunOptions) (*aggregatorapiserver.APIAggregator, error)","file":"cmd/kube-apiserver/app/server.go","code":"// CreateServerChain creates the apiservers connected via delegation.\nfunc CreateServerChain(completedOptions completedServerRunOptions) (*aggregatorapiserver.APIAggregator, error) {\n\tkubeAPIServerConfig, serviceResolver, pluginInitializer, err := CreateKubeAPIServerConfig(completedOptions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// If additional API servers are added, they should be gated.\n\tapiExtensionsConfig, err := createAPIExtensionsConfig(*kubeAPIServerConfig.GenericConfig, kubeAPIServerConfig.ExtraConfig.VersionedInformers, pluginInitializer, completedOptions.ServerRunOptions, completedOptions.MasterCount,\n\t\tserviceResolver, webhook.NewDefaultAuthenticationInfoResolverWrapper(kubeAPIServerConfig.ExtraConfig.ProxyTransport, kubeAPIServerConfig.GenericConfig.EgressSelector, kubeAPIServerConfig.GenericConfig.LoopbackClientConfig, kubeAPIServerConfig.GenericConfig.TracerProvider))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcrdAPIEnabled := apiExtensionsConfig.GenericConfig.MergedResourceConfig.ResourceEnabled(apiextensionsv1.SchemeGroupVersion.WithResource(\"customresourcedefinitions\"))\n\n\tnotFoundHandler := notfoundhandler.New(kubeAPIServerConfig.GenericConfig.Serializer, genericapifilters.NoMuxAndDiscoveryIncompleteKey)\n\tapiExtensionsServer, err := createAPIExtensionsServer(apiExtensionsConfig, genericapiserver.NewEmptyDelegateWithCustomHandler(notFoundHandler))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkubeAPIServer, err := CreateKubeAPIServer(kubeAPIServerConfig, apiExtensionsServer.GenericAPIServer)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// aggregator comes last in the chain\n\taggregatorConfig, err := createAggregatorConfig(*kubeAPIServerConfig.GenericConfig, completedOptions.ServerRunOptions, kubeAPIServerConfig.ExtraConfig.VersionedInformers, serviceResolver, kubeAPIServerConfig.ExtraConfig.ProxyTransport, pluginInitializer)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taggregatorServer, err := createAggregatorServer(aggregatorConfig, kubeAPIServer.GenericAPIServer, apiExtensionsServer.Informers, crdAPIEnabled)\n\tif err != nil {\n\t\t// we don't need special handling for innerStopCh because the aggregator server doesn't create any go routines\n\t\treturn nil, err\n\t}\n\n\treturn aggregatorServer, nil\n}","line":{"from":183,"to":221}} {"id":100000149,"name":"CreateKubeAPIServer","signature":"func CreateKubeAPIServer(kubeAPIServerConfig *controlplane.Config, delegateAPIServer genericapiserver.DelegationTarget) (*controlplane.Instance, error)","file":"cmd/kube-apiserver/app/server.go","code":"// CreateKubeAPIServer creates and wires a workable kube-apiserver\nfunc CreateKubeAPIServer(kubeAPIServerConfig *controlplane.Config, delegateAPIServer genericapiserver.DelegationTarget) (*controlplane.Instance, error) {\n\treturn kubeAPIServerConfig.Complete().New(delegateAPIServer)\n}","line":{"from":223,"to":226}} {"id":100000150,"name":"CreateProxyTransport","signature":"func CreateProxyTransport() *http.Transport","file":"cmd/kube-apiserver/app/server.go","code":"// CreateProxyTransport creates the dialer infrastructure to connect to the nodes.\nfunc CreateProxyTransport() *http.Transport {\n\tvar proxyDialerFn utilnet.DialFunc\n\t// Proxying to pods and services is IP-based... don't expect to be able to verify the hostname\n\tproxyTLSClientConfig := \u0026tls.Config{InsecureSkipVerify: true}\n\tproxyTransport := utilnet.SetTransportDefaults(\u0026http.Transport{\n\t\tDialContext: proxyDialerFn,\n\t\tTLSClientConfig: proxyTLSClientConfig,\n\t})\n\treturn proxyTransport\n}","line":{"from":228,"to":238}} {"id":100000151,"name":"CreateKubeAPIServerConfig","signature":"func CreateKubeAPIServerConfig(s completedServerRunOptions) (","file":"cmd/kube-apiserver/app/server.go","code":"// CreateKubeAPIServerConfig creates all the resources for running the API server, but runs none of them\nfunc CreateKubeAPIServerConfig(s completedServerRunOptions) (\n\t*controlplane.Config,\n\taggregatorapiserver.ServiceResolver,\n\t[]admission.PluginInitializer,\n\terror,\n) {\n\tproxyTransport := CreateProxyTransport()\n\n\tgenericConfig, versionedInformers, serviceResolver, pluginInitializers, admissionPostStartHook, storageFactory, err := buildGenericConfig(s.ServerRunOptions, proxyTransport)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tcapabilities.Setup(s.AllowPrivileged, s.MaxConnectionBytesPerSec)\n\n\ts.Metrics.Apply()\n\tserviceaccount.RegisterMetrics()\n\n\tconfig := \u0026controlplane.Config{\n\t\tGenericConfig: genericConfig,\n\t\tExtraConfig: controlplane.ExtraConfig{\n\t\t\tAPIResourceConfigSource: storageFactory.APIResourceConfigSource,\n\t\t\tStorageFactory: storageFactory,\n\t\t\tEventTTL: s.EventTTL,\n\t\t\tKubeletClientConfig: s.KubeletConfig,\n\t\t\tEnableLogsSupport: s.EnableLogsHandler,\n\t\t\tProxyTransport: proxyTransport,\n\n\t\t\tServiceIPRange: s.PrimaryServiceClusterIPRange,\n\t\t\tAPIServerServiceIP: s.APIServerServiceIP,\n\t\t\tSecondaryServiceIPRange: s.SecondaryServiceClusterIPRange,\n\n\t\t\tAPIServerServicePort: 443,\n\n\t\t\tServiceNodePortRange: s.ServiceNodePortRange,\n\t\t\tKubernetesServiceNodePort: s.KubernetesServiceNodePort,\n\n\t\t\tEndpointReconcilerType: reconcilers.Type(s.EndpointReconcilerType),\n\t\t\tMasterCount: s.MasterCount,\n\n\t\t\tServiceAccountIssuer: s.ServiceAccountIssuer,\n\t\t\tServiceAccountMaxExpiration: s.ServiceAccountTokenMaxExpiration,\n\t\t\tExtendExpiration: s.Authentication.ServiceAccounts.ExtendExpiration,\n\n\t\t\tVersionedInformers: versionedInformers,\n\t\t},\n\t}\n\n\tclientCAProvider, err := s.Authentication.ClientCert.GetClientCAContentProvider()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tconfig.ExtraConfig.ClusterAuthenticationInfo.ClientCA = clientCAProvider\n\n\trequestHeaderConfig, err := s.Authentication.RequestHeader.ToAuthenticationRequestHeaderConfig()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tif requestHeaderConfig != nil {\n\t\tconfig.ExtraConfig.ClusterAuthenticationInfo.RequestHeaderCA = requestHeaderConfig.CAContentProvider\n\t\tconfig.ExtraConfig.ClusterAuthenticationInfo.RequestHeaderAllowedNames = requestHeaderConfig.AllowedClientNames\n\t\tconfig.ExtraConfig.ClusterAuthenticationInfo.RequestHeaderExtraHeaderPrefixes = requestHeaderConfig.ExtraHeaderPrefixes\n\t\tconfig.ExtraConfig.ClusterAuthenticationInfo.RequestHeaderGroupHeaders = requestHeaderConfig.GroupHeaders\n\t\tconfig.ExtraConfig.ClusterAuthenticationInfo.RequestHeaderUsernameHeaders = requestHeaderConfig.UsernameHeaders\n\t}\n\n\tif err := config.GenericConfig.AddPostStartHook(\"start-kube-apiserver-admission-initializer\", admissionPostStartHook); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tif config.GenericConfig.EgressSelector != nil {\n\t\t// Use the config.GenericConfig.EgressSelector lookup to find the dialer to connect to the kubelet\n\t\tconfig.ExtraConfig.KubeletClientConfig.Lookup = config.GenericConfig.EgressSelector.Lookup\n\n\t\t// Use the config.GenericConfig.EgressSelector lookup as the transport used by the \"proxy\" subresources.\n\t\tnetworkContext := egressselector.Cluster.AsNetworkContext()\n\t\tdialer, err := config.GenericConfig.EgressSelector.Lookup(networkContext)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t\tc := proxyTransport.Clone()\n\t\tc.DialContext = dialer\n\t\tconfig.ExtraConfig.ProxyTransport = c\n\t}\n\n\t// Load the public keys.\n\tvar pubKeys []interface{}\n\tfor _, f := range s.Authentication.ServiceAccounts.KeyFiles {\n\t\tkeys, err := keyutil.PublicKeysFromFile(f)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, fmt.Errorf(\"failed to parse key file %q: %v\", f, err)\n\t\t}\n\t\tpubKeys = append(pubKeys, keys...)\n\t}\n\t// Plumb the required metadata through ExtraConfig.\n\tconfig.ExtraConfig.ServiceAccountIssuerURL = s.Authentication.ServiceAccounts.Issuers[0]\n\tconfig.ExtraConfig.ServiceAccountJWKSURI = s.Authentication.ServiceAccounts.JWKSURI\n\tconfig.ExtraConfig.ServiceAccountPublicKeys = pubKeys\n\n\treturn config, serviceResolver, pluginInitializers, nil\n}","line":{"from":240,"to":341}} {"id":100000152,"name":"buildGenericConfig","signature":"func buildGenericConfig(","file":"cmd/kube-apiserver/app/server.go","code":"// BuildGenericConfig takes the master server options and produces the genericapiserver.Config associated with it\nfunc buildGenericConfig(\n\ts *options.ServerRunOptions,\n\tproxyTransport *http.Transport,\n) (\n\tgenericConfig *genericapiserver.Config,\n\tversionedInformers clientgoinformers.SharedInformerFactory,\n\tserviceResolver aggregatorapiserver.ServiceResolver,\n\tpluginInitializers []admission.PluginInitializer,\n\tadmissionPostStartHook genericapiserver.PostStartHookFunc,\n\tstorageFactory *serverstorage.DefaultStorageFactory,\n\tlastErr error,\n) {\n\tgenericConfig = genericapiserver.NewConfig(legacyscheme.Codecs)\n\tgenericConfig.MergedResourceConfig = controlplane.DefaultAPIResourceConfigSource()\n\n\tif lastErr = s.GenericServerRunOptions.ApplyTo(genericConfig); lastErr != nil {\n\t\treturn\n\t}\n\n\tif lastErr = s.SecureServing.ApplyTo(\u0026genericConfig.SecureServing, \u0026genericConfig.LoopbackClientConfig); lastErr != nil {\n\t\treturn\n\t}\n\tif lastErr = s.Features.ApplyTo(genericConfig); lastErr != nil {\n\t\treturn\n\t}\n\tif lastErr = s.APIEnablement.ApplyTo(genericConfig, controlplane.DefaultAPIResourceConfigSource(), legacyscheme.Scheme); lastErr != nil {\n\t\treturn\n\t}\n\tif lastErr = s.EgressSelector.ApplyTo(genericConfig); lastErr != nil {\n\t\treturn\n\t}\n\tif utilfeature.DefaultFeatureGate.Enabled(genericfeatures.APIServerTracing) {\n\t\tif lastErr = s.Traces.ApplyTo(genericConfig.EgressSelector, genericConfig); lastErr != nil {\n\t\t\treturn\n\t\t}\n\t}\n\t// wrap the definitions to revert any changes from disabled features\n\tgetOpenAPIDefinitions := openapi.GetOpenAPIDefinitionsWithoutDisabledFeatures(generatedopenapi.GetOpenAPIDefinitions)\n\tgenericConfig.OpenAPIConfig = genericapiserver.DefaultOpenAPIConfig(getOpenAPIDefinitions, openapinamer.NewDefinitionNamer(legacyscheme.Scheme, extensionsapiserver.Scheme, aggregatorscheme.Scheme))\n\tgenericConfig.OpenAPIConfig.Info.Title = \"Kubernetes\"\n\tgenericConfig.OpenAPIV3Config = genericapiserver.DefaultOpenAPIV3Config(getOpenAPIDefinitions, openapinamer.NewDefinitionNamer(legacyscheme.Scheme, extensionsapiserver.Scheme, aggregatorscheme.Scheme))\n\tgenericConfig.OpenAPIV3Config.Info.Title = \"Kubernetes\"\n\n\tgenericConfig.LongRunningFunc = filters.BasicLongRunningRequestCheck(\n\t\tsets.NewString(\"watch\", \"proxy\"),\n\t\tsets.NewString(\"attach\", \"exec\", \"proxy\", \"log\", \"portforward\"),\n\t)\n\n\tkubeVersion := version.Get()\n\tgenericConfig.Version = \u0026kubeVersion\n\n\tif genericConfig.EgressSelector != nil {\n\t\ts.Etcd.StorageConfig.Transport.EgressLookup = genericConfig.EgressSelector.Lookup\n\t}\n\tif utilfeature.DefaultFeatureGate.Enabled(genericfeatures.APIServerTracing) {\n\t\ts.Etcd.StorageConfig.Transport.TracerProvider = genericConfig.TracerProvider\n\t} else {\n\t\ts.Etcd.StorageConfig.Transport.TracerProvider = oteltrace.NewNoopTracerProvider()\n\t}\n\tif lastErr = s.Etcd.Complete(genericConfig.StorageObjectCountTracker, genericConfig.DrainedNotify(), genericConfig.AddPostStartHook); lastErr != nil {\n\t\treturn\n\t}\n\n\tstorageFactoryConfig := kubeapiserver.NewStorageFactoryConfig()\n\tstorageFactoryConfig.APIResourceConfig = genericConfig.MergedResourceConfig\n\tstorageFactory, lastErr = storageFactoryConfig.Complete(s.Etcd).New()\n\tif lastErr != nil {\n\t\treturn\n\t}\n\tif lastErr = s.Etcd.ApplyWithStorageFactoryTo(storageFactory, genericConfig); lastErr != nil {\n\t\treturn\n\t}\n\n\t// Use protobufs for self-communication.\n\t// Since not every generic apiserver has to support protobufs, we\n\t// cannot default to it in generic apiserver and need to explicitly\n\t// set it in kube-apiserver.\n\tgenericConfig.LoopbackClientConfig.ContentConfig.ContentType = \"application/vnd.kubernetes.protobuf\"\n\t// Disable compression for self-communication, since we are going to be\n\t// on a fast local network\n\tgenericConfig.LoopbackClientConfig.DisableCompression = true\n\n\tkubeClientConfig := genericConfig.LoopbackClientConfig\n\tclientgoExternalClient, err := clientgoclientset.NewForConfig(kubeClientConfig)\n\tif err != nil {\n\t\tlastErr = fmt.Errorf(\"failed to create real external clientset: %v\", err)\n\t\treturn\n\t}\n\tversionedInformers = clientgoinformers.NewSharedInformerFactory(clientgoExternalClient, 10*time.Minute)\n\n\t// Authentication.ApplyTo requires already applied OpenAPIConfig and EgressSelector if present\n\tif lastErr = s.Authentication.ApplyTo(\u0026genericConfig.Authentication, genericConfig.SecureServing, genericConfig.EgressSelector, genericConfig.OpenAPIConfig, genericConfig.OpenAPIV3Config, clientgoExternalClient, versionedInformers); lastErr != nil {\n\t\treturn\n\t}\n\n\tgenericConfig.Authorization.Authorizer, genericConfig.RuleResolver, err = BuildAuthorizer(s, genericConfig.EgressSelector, versionedInformers)\n\tif err != nil {\n\t\tlastErr = fmt.Errorf(\"invalid authorization config: %v\", err)\n\t\treturn\n\t}\n\tif !sets.NewString(s.Authorization.Modes...).Has(modes.ModeRBAC) {\n\t\tgenericConfig.DisabledPostStartHooks.Insert(rbacrest.PostStartHookName)\n\t}\n\n\tlastErr = s.Audit.ApplyTo(genericConfig)\n\tif lastErr != nil {\n\t\treturn\n\t}\n\n\tadmissionConfig := \u0026kubeapiserveradmission.Config{\n\t\tExternalInformers: versionedInformers,\n\t\tLoopbackClientConfig: genericConfig.LoopbackClientConfig,\n\t\tCloudConfigFile: s.CloudProvider.CloudConfigFile,\n\t}\n\tserviceResolver = buildServiceResolver(s.EnableAggregatorRouting, genericConfig.LoopbackClientConfig.Host, versionedInformers)\n\tschemaResolver := resolver.NewDefinitionsSchemaResolver(k8sscheme.Scheme, genericConfig.OpenAPIConfig.GetDefinitions)\n\tpluginInitializers, admissionPostStartHook, err = admissionConfig.New(proxyTransport, genericConfig.EgressSelector, serviceResolver, genericConfig.TracerProvider, schemaResolver)\n\tif err != nil {\n\t\tlastErr = fmt.Errorf(\"failed to create admission plugin initializer: %v\", err)\n\t\treturn\n\t}\n\n\terr = s.Admission.ApplyTo(\n\t\tgenericConfig,\n\t\tversionedInformers,\n\t\tkubeClientConfig,\n\t\tutilfeature.DefaultFeatureGate,\n\t\tpluginInitializers...)\n\tif err != nil {\n\t\tlastErr = fmt.Errorf(\"failed to initialize admission: %v\", err)\n\t\treturn\n\t}\n\n\tif utilfeature.DefaultFeatureGate.Enabled(genericfeatures.APIPriorityAndFairness) \u0026\u0026 s.GenericServerRunOptions.EnablePriorityAndFairness {\n\t\tgenericConfig.FlowControl, lastErr = BuildPriorityAndFairness(s, clientgoExternalClient, versionedInformers)\n\t}\n\tif utilfeature.DefaultFeatureGate.Enabled(genericfeatures.AggregatedDiscoveryEndpoint) {\n\t\tgenericConfig.AggregatedDiscoveryGroupManager = aggregated.NewResourceManager(\"apis\")\n\t}\n\n\treturn\n}","line":{"from":343,"to":485}} {"id":100000153,"name":"BuildAuthorizer","signature":"func BuildAuthorizer(s *options.ServerRunOptions, EgressSelector *egressselector.EgressSelector, versionedInformers clientgoinformers.SharedInformerFactory) (authorizer.Authorizer, authorizer.RuleResolver, error)","file":"cmd/kube-apiserver/app/server.go","code":"// BuildAuthorizer constructs the authorizer\nfunc BuildAuthorizer(s *options.ServerRunOptions, EgressSelector *egressselector.EgressSelector, versionedInformers clientgoinformers.SharedInformerFactory) (authorizer.Authorizer, authorizer.RuleResolver, error) {\n\tauthorizationConfig := s.Authorization.ToAuthorizationConfig(versionedInformers)\n\n\tif EgressSelector != nil {\n\t\tegressDialer, err := EgressSelector.Lookup(egressselector.ControlPlane.AsNetworkContext())\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tauthorizationConfig.CustomDial = egressDialer\n\t}\n\n\treturn authorizationConfig.New()\n}","line":{"from":487,"to":500}} {"id":100000154,"name":"BuildPriorityAndFairness","signature":"func BuildPriorityAndFairness(s *options.ServerRunOptions, extclient clientgoclientset.Interface, versionedInformer clientgoinformers.SharedInformerFactory) (utilflowcontrol.Interface, error)","file":"cmd/kube-apiserver/app/server.go","code":"// BuildPriorityAndFairness constructs the guts of the API Priority and Fairness filter\nfunc BuildPriorityAndFairness(s *options.ServerRunOptions, extclient clientgoclientset.Interface, versionedInformer clientgoinformers.SharedInformerFactory) (utilflowcontrol.Interface, error) {\n\tif s.GenericServerRunOptions.MaxRequestsInFlight+s.GenericServerRunOptions.MaxMutatingRequestsInFlight \u003c= 0 {\n\t\treturn nil, fmt.Errorf(\"invalid configuration: MaxRequestsInFlight=%d and MaxMutatingRequestsInFlight=%d; they must add up to something positive\", s.GenericServerRunOptions.MaxRequestsInFlight, s.GenericServerRunOptions.MaxMutatingRequestsInFlight)\n\t}\n\treturn utilflowcontrol.New(\n\t\tversionedInformer,\n\t\textclient.FlowcontrolV1beta3(),\n\t\ts.GenericServerRunOptions.MaxRequestsInFlight+s.GenericServerRunOptions.MaxMutatingRequestsInFlight,\n\t\ts.GenericServerRunOptions.RequestTimeout/4,\n\t), nil\n}","line":{"from":502,"to":513}} {"id":100000155,"name":"Complete","signature":"func Complete(s *options.ServerRunOptions) (completedServerRunOptions, error)","file":"cmd/kube-apiserver/app/server.go","code":"// Complete set default ServerRunOptions.\n// Should be called after kube-apiserver flags parsed.\nfunc Complete(s *options.ServerRunOptions) (completedServerRunOptions, error) {\n\tvar options completedServerRunOptions\n\t// set defaults\n\tif err := s.GenericServerRunOptions.DefaultAdvertiseAddress(s.SecureServing.SecureServingOptions); err != nil {\n\t\treturn options, err\n\t}\n\n\t// process s.ServiceClusterIPRange from list to Primary and Secondary\n\t// we process secondary only if provided by user\n\tapiServerServiceIP, primaryServiceIPRange, secondaryServiceIPRange, err := getServiceIPAndRanges(s.ServiceClusterIPRanges)\n\tif err != nil {\n\t\treturn options, err\n\t}\n\ts.PrimaryServiceClusterIPRange = primaryServiceIPRange\n\ts.SecondaryServiceClusterIPRange = secondaryServiceIPRange\n\ts.APIServerServiceIP = apiServerServiceIP\n\n\tif err := s.SecureServing.MaybeDefaultWithSelfSignedCerts(s.GenericServerRunOptions.AdvertiseAddress.String(), []string{\"kubernetes.default.svc\", \"kubernetes.default\", \"kubernetes\"}, []net.IP{apiServerServiceIP}); err != nil {\n\t\treturn options, fmt.Errorf(\"error creating self-signed certificates: %v\", err)\n\t}\n\n\tif len(s.GenericServerRunOptions.ExternalHost) == 0 {\n\t\tif len(s.GenericServerRunOptions.AdvertiseAddress) \u003e 0 {\n\t\t\ts.GenericServerRunOptions.ExternalHost = s.GenericServerRunOptions.AdvertiseAddress.String()\n\t\t} else {\n\t\t\thostname, err := os.Hostname()\n\t\t\tif err != nil {\n\t\t\t\treturn options, fmt.Errorf(\"error finding host name: %v\", err)\n\t\t\t}\n\t\t\ts.GenericServerRunOptions.ExternalHost = hostname\n\t\t}\n\t\tklog.Infof(\"external host was not specified, using %v\", s.GenericServerRunOptions.ExternalHost)\n\t}\n\n\ts.Authentication.ApplyAuthorization(s.Authorization)\n\n\t// Use (ServiceAccountSigningKeyFile != \"\") as a proxy to the user enabling\n\t// TokenRequest functionality. This defaulting was convenient, but messed up\n\t// a lot of people when they rotated their serving cert with no idea it was\n\t// connected to their service account keys. We are taking this opportunity to\n\t// remove this problematic defaulting.\n\tif s.ServiceAccountSigningKeyFile == \"\" {\n\t\t// Default to the private server key for service account token signing\n\t\tif len(s.Authentication.ServiceAccounts.KeyFiles) == 0 \u0026\u0026 s.SecureServing.ServerCert.CertKey.KeyFile != \"\" {\n\t\t\tif kubeauthenticator.IsValidServiceAccountKeyFile(s.SecureServing.ServerCert.CertKey.KeyFile) {\n\t\t\t\ts.Authentication.ServiceAccounts.KeyFiles = []string{s.SecureServing.ServerCert.CertKey.KeyFile}\n\t\t\t} else {\n\t\t\t\tklog.Warning(\"No TLS key provided, service account token authentication disabled\")\n\t\t\t}\n\t\t}\n\t}\n\n\tif s.ServiceAccountSigningKeyFile != \"\" \u0026\u0026 len(s.Authentication.ServiceAccounts.Issuers) != 0 \u0026\u0026 s.Authentication.ServiceAccounts.Issuers[0] != \"\" {\n\t\tsk, err := keyutil.PrivateKeyFromFile(s.ServiceAccountSigningKeyFile)\n\t\tif err != nil {\n\t\t\treturn options, fmt.Errorf(\"failed to parse service-account-issuer-key-file: %v\", err)\n\t\t}\n\t\tif s.Authentication.ServiceAccounts.MaxExpiration != 0 {\n\t\t\tlowBound := time.Hour\n\t\t\tupBound := time.Duration(1\u003c\u003c32) * time.Second\n\t\t\tif s.Authentication.ServiceAccounts.MaxExpiration \u003c lowBound ||\n\t\t\t\ts.Authentication.ServiceAccounts.MaxExpiration \u003e upBound {\n\t\t\t\treturn options, fmt.Errorf(\"the service-account-max-token-expiration must be between 1 hour and 2^32 seconds\")\n\t\t\t}\n\t\t\tif s.Authentication.ServiceAccounts.ExtendExpiration {\n\t\t\t\tif s.Authentication.ServiceAccounts.MaxExpiration \u003c serviceaccount.WarnOnlyBoundTokenExpirationSeconds*time.Second {\n\t\t\t\t\tklog.Warningf(\"service-account-extend-token-expiration is true, in order to correctly trigger safe transition logic, service-account-max-token-expiration must be set longer than %d seconds (currently %s)\", serviceaccount.WarnOnlyBoundTokenExpirationSeconds, s.Authentication.ServiceAccounts.MaxExpiration)\n\t\t\t\t}\n\t\t\t\tif s.Authentication.ServiceAccounts.MaxExpiration \u003c serviceaccount.ExpirationExtensionSeconds*time.Second {\n\t\t\t\t\tklog.Warningf(\"service-account-extend-token-expiration is true, enabling tokens valid up to %d seconds, which is longer than service-account-max-token-expiration set to %s seconds\", serviceaccount.ExpirationExtensionSeconds, s.Authentication.ServiceAccounts.MaxExpiration)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\ts.ServiceAccountIssuer, err = serviceaccount.JWTTokenGenerator(s.Authentication.ServiceAccounts.Issuers[0], sk)\n\t\tif err != nil {\n\t\t\treturn options, fmt.Errorf(\"failed to build token generator: %v\", err)\n\t\t}\n\t\ts.ServiceAccountTokenMaxExpiration = s.Authentication.ServiceAccounts.MaxExpiration\n\t}\n\n\tif s.Etcd.EnableWatchCache {\n\t\tsizes := kubeapiserver.DefaultWatchCacheSizes()\n\t\t// Ensure that overrides parse correctly.\n\t\tuserSpecified, err := serveroptions.ParseWatchCacheSizes(s.Etcd.WatchCacheSizes)\n\t\tif err != nil {\n\t\t\treturn options, err\n\t\t}\n\t\tfor resource, size := range userSpecified {\n\t\t\tsizes[resource] = size\n\t\t}\n\t\ts.Etcd.WatchCacheSizes, err = serveroptions.WriteWatchCacheSizes(sizes)\n\t\tif err != nil {\n\t\t\treturn options, err\n\t\t}\n\t}\n\n\tfor key, value := range s.APIEnablement.RuntimeConfig {\n\t\tif key == \"v1\" || strings.HasPrefix(key, \"v1/\") ||\n\t\t\tkey == \"api/v1\" || strings.HasPrefix(key, \"api/v1/\") {\n\t\t\tdelete(s.APIEnablement.RuntimeConfig, key)\n\t\t\ts.APIEnablement.RuntimeConfig[\"/v1\"] = value\n\t\t}\n\t\tif key == \"api/legacy\" {\n\t\t\tdelete(s.APIEnablement.RuntimeConfig, key)\n\t\t}\n\t}\n\n\toptions.ServerRunOptions = s\n\treturn options, nil\n}","line":{"from":520,"to":632}} {"id":100000156,"name":"SetServiceResolverForTests","signature":"func SetServiceResolverForTests(resolver webhook.ServiceResolver) func()","file":"cmd/kube-apiserver/app/server.go","code":"// SetServiceResolverForTests allows the service resolver to be overridden during tests.\n// Tests using this function must run serially as this function is not safe to call concurrently with server start.\nfunc SetServiceResolverForTests(resolver webhook.ServiceResolver) func() {\n\tif testServiceResolver != nil {\n\t\tpanic(\"test service resolver is set: tests are either running concurrently or clean up was skipped\")\n\t}\n\n\ttestServiceResolver = resolver\n\n\treturn func() {\n\t\ttestServiceResolver = nil\n\t}\n}","line":{"from":636,"to":648}} {"id":100000157,"name":"buildServiceResolver","signature":"func buildServiceResolver(enabledAggregatorRouting bool, hostname string, informer clientgoinformers.SharedInformerFactory) webhook.ServiceResolver","file":"cmd/kube-apiserver/app/server.go","code":"func buildServiceResolver(enabledAggregatorRouting bool, hostname string, informer clientgoinformers.SharedInformerFactory) webhook.ServiceResolver {\n\tif testServiceResolver != nil {\n\t\treturn testServiceResolver\n\t}\n\n\tvar serviceResolver webhook.ServiceResolver\n\tif enabledAggregatorRouting {\n\t\tserviceResolver = aggregatorapiserver.NewEndpointServiceResolver(\n\t\t\tinformer.Core().V1().Services().Lister(),\n\t\t\tinformer.Core().V1().Endpoints().Lister(),\n\t\t)\n\t} else {\n\t\tserviceResolver = aggregatorapiserver.NewClusterIPServiceResolver(\n\t\t\tinformer.Core().V1().Services().Lister(),\n\t\t)\n\t}\n\t// resolve kubernetes.default.svc locally\n\tif localHost, err := url.Parse(hostname); err == nil {\n\t\tserviceResolver = aggregatorapiserver.NewLoopbackServiceResolver(serviceResolver, localHost)\n\t}\n\treturn serviceResolver\n}","line":{"from":650,"to":671}} {"id":100000158,"name":"getServiceIPAndRanges","signature":"func getServiceIPAndRanges(serviceClusterIPRanges string) (net.IP, net.IPNet, net.IPNet, error)","file":"cmd/kube-apiserver/app/server.go","code":"func getServiceIPAndRanges(serviceClusterIPRanges string) (net.IP, net.IPNet, net.IPNet, error) {\n\tserviceClusterIPRangeList := []string{}\n\tif serviceClusterIPRanges != \"\" {\n\t\tserviceClusterIPRangeList = strings.Split(serviceClusterIPRanges, \",\")\n\t}\n\n\tvar apiServerServiceIP net.IP\n\tvar primaryServiceIPRange net.IPNet\n\tvar secondaryServiceIPRange net.IPNet\n\tvar err error\n\t// nothing provided by user, use default range (only applies to the Primary)\n\tif len(serviceClusterIPRangeList) == 0 {\n\t\tvar primaryServiceClusterCIDR net.IPNet\n\t\tprimaryServiceIPRange, apiServerServiceIP, err = controlplane.ServiceIPRange(primaryServiceClusterCIDR)\n\t\tif err != nil {\n\t\t\treturn net.IP{}, net.IPNet{}, net.IPNet{}, fmt.Errorf(\"error determining service IP ranges: %v\", err)\n\t\t}\n\t\treturn apiServerServiceIP, primaryServiceIPRange, net.IPNet{}, nil\n\t}\n\n\t_, primaryServiceClusterCIDR, err := netutils.ParseCIDRSloppy(serviceClusterIPRangeList[0])\n\tif err != nil {\n\t\treturn net.IP{}, net.IPNet{}, net.IPNet{}, fmt.Errorf(\"service-cluster-ip-range[0] is not a valid cidr\")\n\t}\n\n\tprimaryServiceIPRange, apiServerServiceIP, err = controlplane.ServiceIPRange(*primaryServiceClusterCIDR)\n\tif err != nil {\n\t\treturn net.IP{}, net.IPNet{}, net.IPNet{}, fmt.Errorf(\"error determining service IP ranges for primary service cidr: %v\", err)\n\t}\n\n\t// user provided at least two entries\n\t// note: validation asserts that the list is max of two dual stack entries\n\tif len(serviceClusterIPRangeList) \u003e 1 {\n\t\t_, secondaryServiceClusterCIDR, err := netutils.ParseCIDRSloppy(serviceClusterIPRangeList[1])\n\t\tif err != nil {\n\t\t\treturn net.IP{}, net.IPNet{}, net.IPNet{}, fmt.Errorf(\"service-cluster-ip-range[1] is not an ip net\")\n\t\t}\n\t\tsecondaryServiceIPRange = *secondaryServiceClusterCIDR\n\t}\n\treturn apiServerServiceIP, primaryServiceIPRange, secondaryServiceIPRange, nil\n}","line":{"from":673,"to":713}} {"id":100000159,"name":"startDaemonSetController","signature":"func startDaemonSetController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/apps.go","code":"func startDaemonSetController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tdsc, err := daemon.NewDaemonSetsController(\n\t\tctx,\n\t\tcontrollerContext.InformerFactory.Apps().V1().DaemonSets(),\n\t\tcontrollerContext.InformerFactory.Apps().V1().ControllerRevisions(),\n\t\tcontrollerContext.InformerFactory.Core().V1().Pods(),\n\t\tcontrollerContext.InformerFactory.Core().V1().Nodes(),\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"daemon-set-controller\"),\n\t\tflowcontrol.NewBackOff(1*time.Second, 15*time.Minute),\n\t)\n\tif err != nil {\n\t\treturn nil, true, fmt.Errorf(\"error creating DaemonSets controller: %v\", err)\n\t}\n\tgo dsc.Run(ctx, int(controllerContext.ComponentConfig.DaemonSetController.ConcurrentDaemonSetSyncs))\n\treturn nil, true, nil\n}","line":{"from":36,"to":51}} {"id":100000160,"name":"startStatefulSetController","signature":"func startStatefulSetController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/apps.go","code":"func startStatefulSetController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tgo statefulset.NewStatefulSetController(\n\t\tctx,\n\t\tcontrollerContext.InformerFactory.Core().V1().Pods(),\n\t\tcontrollerContext.InformerFactory.Apps().V1().StatefulSets(),\n\t\tcontrollerContext.InformerFactory.Core().V1().PersistentVolumeClaims(),\n\t\tcontrollerContext.InformerFactory.Apps().V1().ControllerRevisions(),\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"statefulset-controller\"),\n\t).Run(ctx, int(controllerContext.ComponentConfig.StatefulSetController.ConcurrentStatefulSetSyncs))\n\treturn nil, true, nil\n}","line":{"from":53,"to":63}} {"id":100000161,"name":"startReplicaSetController","signature":"func startReplicaSetController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/apps.go","code":"func startReplicaSetController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tgo replicaset.NewReplicaSetController(\n\t\tklog.FromContext(ctx),\n\t\tcontrollerContext.InformerFactory.Apps().V1().ReplicaSets(),\n\t\tcontrollerContext.InformerFactory.Core().V1().Pods(),\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"replicaset-controller\"),\n\t\treplicaset.BurstReplicas,\n\t).Run(ctx, int(controllerContext.ComponentConfig.ReplicaSetController.ConcurrentRSSyncs))\n\treturn nil, true, nil\n}","line":{"from":65,"to":74}} {"id":100000162,"name":"startDeploymentController","signature":"func startDeploymentController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/apps.go","code":"func startDeploymentController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tdc, err := deployment.NewDeploymentController(\n\t\tctx,\n\t\tcontrollerContext.InformerFactory.Apps().V1().Deployments(),\n\t\tcontrollerContext.InformerFactory.Apps().V1().ReplicaSets(),\n\t\tcontrollerContext.InformerFactory.Core().V1().Pods(),\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"deployment-controller\"),\n\t)\n\tif err != nil {\n\t\treturn nil, true, fmt.Errorf(\"error creating Deployment controller: %v\", err)\n\t}\n\tgo dc.Run(ctx, int(controllerContext.ComponentConfig.DeploymentController.ConcurrentDeploymentSyncs))\n\treturn nil, true, nil\n}","line":{"from":76,"to":89}} {"id":100000163,"name":"startHPAController","signature":"func startHPAController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/autoscaling.go","code":"func startHPAController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tif !controllerContext.AvailableResources[schema.GroupVersionResource{Group: \"autoscaling\", Version: \"v1\", Resource: \"horizontalpodautoscalers\"}] {\n\t\treturn nil, false, nil\n\t}\n\n\treturn startHPAControllerWithRESTClient(ctx, controllerContext)\n}","line":{"from":39,"to":45}} {"id":100000164,"name":"startHPAControllerWithRESTClient","signature":"func startHPAControllerWithRESTClient(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/autoscaling.go","code":"func startHPAControllerWithRESTClient(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\n\tclientConfig := controllerContext.ClientBuilder.ConfigOrDie(\"horizontal-pod-autoscaler\")\n\thpaClient := controllerContext.ClientBuilder.ClientOrDie(\"horizontal-pod-autoscaler\")\n\n\tapiVersionsGetter := custom_metrics.NewAvailableAPIsGetter(hpaClient.Discovery())\n\t// invalidate the discovery information roughly once per resync interval our API\n\t// information is *at most* two resync intervals old.\n\tgo custom_metrics.PeriodicallyInvalidate(\n\t\tapiVersionsGetter,\n\t\tcontrollerContext.ComponentConfig.HPAController.HorizontalPodAutoscalerSyncPeriod.Duration,\n\t\tctx.Done())\n\n\tmetricsClient := metrics.NewRESTMetricsClient(\n\t\tresourceclient.NewForConfigOrDie(clientConfig),\n\t\tcustom_metrics.NewForConfig(clientConfig, controllerContext.RESTMapper, apiVersionsGetter),\n\t\texternal_metrics.NewForConfigOrDie(clientConfig),\n\t)\n\treturn startHPAControllerWithMetricsClient(ctx, controllerContext, metricsClient)\n}","line":{"from":47,"to":66}} {"id":100000165,"name":"startHPAControllerWithMetricsClient","signature":"func startHPAControllerWithMetricsClient(ctx context.Context, controllerContext ControllerContext, metricsClient metrics.MetricsClient) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/autoscaling.go","code":"func startHPAControllerWithMetricsClient(ctx context.Context, controllerContext ControllerContext, metricsClient metrics.MetricsClient) (controller.Interface, bool, error) {\n\n\thpaClient := controllerContext.ClientBuilder.ClientOrDie(\"horizontal-pod-autoscaler\")\n\thpaClientConfig := controllerContext.ClientBuilder.ConfigOrDie(\"horizontal-pod-autoscaler\")\n\n\t// we don't use cached discovery because DiscoveryScaleKindResolver does its own caching,\n\t// so we want to re-fetch every time when we actually ask for it\n\tscaleKindResolver := scale.NewDiscoveryScaleKindResolver(hpaClient.Discovery())\n\tscaleClient, err := scale.NewForConfig(hpaClientConfig, controllerContext.RESTMapper, dynamic.LegacyAPIPathResolverFunc, scaleKindResolver)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\tgo podautoscaler.NewHorizontalController(\n\t\thpaClient.CoreV1(),\n\t\tscaleClient,\n\t\thpaClient.AutoscalingV2(),\n\t\tcontrollerContext.RESTMapper,\n\t\tmetricsClient,\n\t\tcontrollerContext.InformerFactory.Autoscaling().V2().HorizontalPodAutoscalers(),\n\t\tcontrollerContext.InformerFactory.Core().V1().Pods(),\n\t\tcontrollerContext.ComponentConfig.HPAController.HorizontalPodAutoscalerSyncPeriod.Duration,\n\t\tcontrollerContext.ComponentConfig.HPAController.HorizontalPodAutoscalerDownscaleStabilizationWindow.Duration,\n\t\tcontrollerContext.ComponentConfig.HPAController.HorizontalPodAutoscalerTolerance,\n\t\tcontrollerContext.ComponentConfig.HPAController.HorizontalPodAutoscalerCPUInitializationPeriod.Duration,\n\t\tcontrollerContext.ComponentConfig.HPAController.HorizontalPodAutoscalerInitialReadinessDelay.Duration,\n\t\tfeature.DefaultFeatureGate.Enabled(features.HPAContainerMetrics),\n\t).Run(ctx, int(controllerContext.ComponentConfig.HPAController.ConcurrentHorizontalPodAutoscalerSyncs))\n\treturn nil, true, nil\n}","line":{"from":68,"to":97}} {"id":100000166,"name":"startJobController","signature":"func startJobController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/batch.go","code":"func startJobController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tgo job.NewController(\n\t\tcontrollerContext.InformerFactory.Core().V1().Pods(),\n\t\tcontrollerContext.InformerFactory.Batch().V1().Jobs(),\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"job-controller\"),\n\t).Run(ctx, int(controllerContext.ComponentConfig.JobController.ConcurrentJobSyncs))\n\treturn nil, true, nil\n}","line":{"from":31,"to":38}} {"id":100000167,"name":"startCronJobController","signature":"func startCronJobController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/batch.go","code":"func startCronJobController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tcj2c, err := cronjob.NewControllerV2(ctx, controllerContext.InformerFactory.Batch().V1().Jobs(),\n\t\tcontrollerContext.InformerFactory.Batch().V1().CronJobs(),\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"cronjob-controller\"),\n\t)\n\tif err != nil {\n\t\treturn nil, true, fmt.Errorf(\"error creating CronJob controller V2: %v\", err)\n\t}\n\n\tgo cj2c.Run(ctx, int(controllerContext.ComponentConfig.CronJobController.ConcurrentCronJobSyncs))\n\treturn nil, true, nil\n}","line":{"from":40,"to":51}} {"id":100000168,"name":"startBootstrapSignerController","signature":"func startBootstrapSignerController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/bootstrap.go","code":"func startBootstrapSignerController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tbsc, err := bootstrap.NewSigner(\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"bootstrap-signer\"),\n\t\tcontrollerContext.InformerFactory.Core().V1().Secrets(),\n\t\tcontrollerContext.InformerFactory.Core().V1().ConfigMaps(),\n\t\tbootstrap.DefaultSignerOptions(),\n\t)\n\tif err != nil {\n\t\treturn nil, true, fmt.Errorf(\"error creating BootstrapSigner controller: %v\", err)\n\t}\n\tgo bsc.Run(ctx)\n\treturn nil, true, nil\n}","line":{"from":27,"to":39}} {"id":100000169,"name":"startTokenCleanerController","signature":"func startTokenCleanerController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/bootstrap.go","code":"func startTokenCleanerController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\ttcc, err := bootstrap.NewTokenCleaner(\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"token-cleaner\"),\n\t\tcontrollerContext.InformerFactory.Core().V1().Secrets(),\n\t\tbootstrap.DefaultTokenCleanerOptions(),\n\t)\n\tif err != nil {\n\t\treturn nil, true, fmt.Errorf(\"error creating TokenCleaner controller: %v\", err)\n\t}\n\tgo tcc.Run(ctx)\n\treturn nil, true, nil\n}","line":{"from":41,"to":52}} {"id":100000170,"name":"startCSRSigningController","signature":"func startCSRSigningController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/certificates.go","code":"func startCSRSigningController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tlogger := klog.FromContext(ctx)\n\tmissingSingleSigningFile := controllerContext.ComponentConfig.CSRSigningController.ClusterSigningCertFile == \"\" || controllerContext.ComponentConfig.CSRSigningController.ClusterSigningKeyFile == \"\"\n\tif missingSingleSigningFile \u0026\u0026 !anySpecificFilesSet(controllerContext.ComponentConfig.CSRSigningController) {\n\t\tlogger.Info(\"Skipping CSR signer controller because no csr cert/key was specified\")\n\t\treturn nil, false, nil\n\t}\n\tif !missingSingleSigningFile \u0026\u0026 anySpecificFilesSet(controllerContext.ComponentConfig.CSRSigningController) {\n\t\treturn nil, false, fmt.Errorf(\"cannot specify default and per controller certs at the same time\")\n\t}\n\n\tc := controllerContext.ClientBuilder.ClientOrDie(\"certificate-controller\")\n\tcsrInformer := controllerContext.InformerFactory.Certificates().V1().CertificateSigningRequests()\n\tcertTTL := controllerContext.ComponentConfig.CSRSigningController.ClusterSigningDuration.Duration\n\n\tif kubeletServingSignerCertFile, kubeletServingSignerKeyFile := getKubeletServingSignerFiles(controllerContext.ComponentConfig.CSRSigningController); len(kubeletServingSignerCertFile) \u003e 0 || len(kubeletServingSignerKeyFile) \u003e 0 {\n\t\tkubeletServingSigner, err := signer.NewKubeletServingCSRSigningController(c, csrInformer, kubeletServingSignerCertFile, kubeletServingSignerKeyFile, certTTL)\n\t\tif err != nil {\n\t\t\treturn nil, false, fmt.Errorf(\"failed to start kubernetes.io/kubelet-serving certificate controller: %v\", err)\n\t\t}\n\t\tgo kubeletServingSigner.Run(ctx, 5)\n\t} else {\n\t\tlogger.Info(\"Skipping CSR signer controller because specific files were specified for other signers and not this one\", \"controller\", \"kubernetes.io/kubelet-serving\")\n\t}\n\n\tif kubeletClientSignerCertFile, kubeletClientSignerKeyFile := getKubeletClientSignerFiles(controllerContext.ComponentConfig.CSRSigningController); len(kubeletClientSignerCertFile) \u003e 0 || len(kubeletClientSignerKeyFile) \u003e 0 {\n\t\tkubeletClientSigner, err := signer.NewKubeletClientCSRSigningController(c, csrInformer, kubeletClientSignerCertFile, kubeletClientSignerKeyFile, certTTL)\n\t\tif err != nil {\n\t\t\treturn nil, false, fmt.Errorf(\"failed to start kubernetes.io/kube-apiserver-client-kubelet certificate controller: %v\", err)\n\t\t}\n\t\tgo kubeletClientSigner.Run(ctx, 5)\n\t} else {\n\t\tlogger.Info(\"Skipping CSR signer controller because specific files were specified for other signers and not this one\", \"controller\", \"kubernetes.io/kube-apiserver-client-kubelet\")\n\t}\n\n\tif kubeAPIServerSignerCertFile, kubeAPIServerSignerKeyFile := getKubeAPIServerClientSignerFiles(controllerContext.ComponentConfig.CSRSigningController); len(kubeAPIServerSignerCertFile) \u003e 0 || len(kubeAPIServerSignerKeyFile) \u003e 0 {\n\t\tkubeAPIServerClientSigner, err := signer.NewKubeAPIServerClientCSRSigningController(c, csrInformer, kubeAPIServerSignerCertFile, kubeAPIServerSignerKeyFile, certTTL)\n\t\tif err != nil {\n\t\t\treturn nil, false, fmt.Errorf(\"failed to start kubernetes.io/kube-apiserver-client certificate controller: %v\", err)\n\t\t}\n\t\tgo kubeAPIServerClientSigner.Run(ctx, 5)\n\t} else {\n\t\tlogger.Info(\"Skipping CSR signer controller because specific files were specified for other signers and not this one\", \"controller\", \"kubernetes.io/kube-apiserver-client\")\n\t}\n\n\tif legacyUnknownSignerCertFile, legacyUnknownSignerKeyFile := getLegacyUnknownSignerFiles(controllerContext.ComponentConfig.CSRSigningController); len(legacyUnknownSignerCertFile) \u003e 0 || len(legacyUnknownSignerKeyFile) \u003e 0 {\n\t\tlegacyUnknownSigner, err := signer.NewLegacyUnknownCSRSigningController(c, csrInformer, legacyUnknownSignerCertFile, legacyUnknownSignerKeyFile, certTTL)\n\t\tif err != nil {\n\t\t\treturn nil, false, fmt.Errorf(\"failed to start kubernetes.io/legacy-unknown certificate controller: %v\", err)\n\t\t}\n\t\tgo legacyUnknownSigner.Run(ctx, 5)\n\t} else {\n\t\tlogger.Info(\"Skipping CSR signer controller because specific files were specified for other signers and not this one\", \"controller\", \"kubernetes.io/legacy-unknown\")\n\t}\n\n\treturn nil, true, nil\n}","line":{"from":35,"to":91}} {"id":100000171,"name":"areKubeletServingSignerFilesSpecified","signature":"func areKubeletServingSignerFilesSpecified(config csrsigningconfig.CSRSigningControllerConfiguration) bool","file":"cmd/kube-controller-manager/app/certificates.go","code":"func areKubeletServingSignerFilesSpecified(config csrsigningconfig.CSRSigningControllerConfiguration) bool {\n\t// if only one is specified, it will error later during construction\n\treturn len(config.KubeletServingSignerConfiguration.CertFile) \u003e 0 || len(config.KubeletServingSignerConfiguration.KeyFile) \u003e 0\n}","line":{"from":93,"to":96}} {"id":100000172,"name":"areKubeletClientSignerFilesSpecified","signature":"func areKubeletClientSignerFilesSpecified(config csrsigningconfig.CSRSigningControllerConfiguration) bool","file":"cmd/kube-controller-manager/app/certificates.go","code":"func areKubeletClientSignerFilesSpecified(config csrsigningconfig.CSRSigningControllerConfiguration) bool {\n\t// if only one is specified, it will error later during construction\n\treturn len(config.KubeletClientSignerConfiguration.CertFile) \u003e 0 || len(config.KubeletClientSignerConfiguration.KeyFile) \u003e 0\n}","line":{"from":97,"to":100}} {"id":100000173,"name":"areKubeAPIServerClientSignerFilesSpecified","signature":"func areKubeAPIServerClientSignerFilesSpecified(config csrsigningconfig.CSRSigningControllerConfiguration) bool","file":"cmd/kube-controller-manager/app/certificates.go","code":"func areKubeAPIServerClientSignerFilesSpecified(config csrsigningconfig.CSRSigningControllerConfiguration) bool {\n\t// if only one is specified, it will error later during construction\n\treturn len(config.KubeAPIServerClientSignerConfiguration.CertFile) \u003e 0 || len(config.KubeAPIServerClientSignerConfiguration.KeyFile) \u003e 0\n}","line":{"from":102,"to":105}} {"id":100000174,"name":"areLegacyUnknownSignerFilesSpecified","signature":"func areLegacyUnknownSignerFilesSpecified(config csrsigningconfig.CSRSigningControllerConfiguration) bool","file":"cmd/kube-controller-manager/app/certificates.go","code":"func areLegacyUnknownSignerFilesSpecified(config csrsigningconfig.CSRSigningControllerConfiguration) bool {\n\t// if only one is specified, it will error later during construction\n\treturn len(config.LegacyUnknownSignerConfiguration.CertFile) \u003e 0 || len(config.LegacyUnknownSignerConfiguration.KeyFile) \u003e 0\n}","line":{"from":107,"to":110}} {"id":100000175,"name":"anySpecificFilesSet","signature":"func anySpecificFilesSet(config csrsigningconfig.CSRSigningControllerConfiguration) bool","file":"cmd/kube-controller-manager/app/certificates.go","code":"func anySpecificFilesSet(config csrsigningconfig.CSRSigningControllerConfiguration) bool {\n\treturn areKubeletServingSignerFilesSpecified(config) ||\n\t\tareKubeletClientSignerFilesSpecified(config) ||\n\t\tareKubeAPIServerClientSignerFilesSpecified(config) ||\n\t\tareLegacyUnknownSignerFilesSpecified(config)\n}","line":{"from":112,"to":117}} {"id":100000176,"name":"getKubeletServingSignerFiles","signature":"func getKubeletServingSignerFiles(config csrsigningconfig.CSRSigningControllerConfiguration) (string, string)","file":"cmd/kube-controller-manager/app/certificates.go","code":"func getKubeletServingSignerFiles(config csrsigningconfig.CSRSigningControllerConfiguration) (string, string) {\n\t// if any cert/key is set for specific CSR signing loops, then the --cluster-signing-{cert,key}-file are not used for any CSR signing loop.\n\tif anySpecificFilesSet(config) {\n\t\treturn config.KubeletServingSignerConfiguration.CertFile, config.KubeletServingSignerConfiguration.KeyFile\n\t}\n\treturn config.ClusterSigningCertFile, config.ClusterSigningKeyFile\n}","line":{"from":119,"to":125}} {"id":100000177,"name":"getKubeletClientSignerFiles","signature":"func getKubeletClientSignerFiles(config csrsigningconfig.CSRSigningControllerConfiguration) (string, string)","file":"cmd/kube-controller-manager/app/certificates.go","code":"func getKubeletClientSignerFiles(config csrsigningconfig.CSRSigningControllerConfiguration) (string, string) {\n\t// if any cert/key is set for specific CSR signing loops, then the --cluster-signing-{cert,key}-file are not used for any CSR signing loop.\n\tif anySpecificFilesSet(config) {\n\t\treturn config.KubeletClientSignerConfiguration.CertFile, config.KubeletClientSignerConfiguration.KeyFile\n\t}\n\treturn config.ClusterSigningCertFile, config.ClusterSigningKeyFile\n}","line":{"from":127,"to":133}} {"id":100000178,"name":"getKubeAPIServerClientSignerFiles","signature":"func getKubeAPIServerClientSignerFiles(config csrsigningconfig.CSRSigningControllerConfiguration) (string, string)","file":"cmd/kube-controller-manager/app/certificates.go","code":"func getKubeAPIServerClientSignerFiles(config csrsigningconfig.CSRSigningControllerConfiguration) (string, string) {\n\t// if any cert/key is set for specific CSR signing loops, then the --cluster-signing-{cert,key}-file are not used for any CSR signing loop.\n\tif anySpecificFilesSet(config) {\n\t\treturn config.KubeAPIServerClientSignerConfiguration.CertFile, config.KubeAPIServerClientSignerConfiguration.KeyFile\n\t}\n\treturn config.ClusterSigningCertFile, config.ClusterSigningKeyFile\n}","line":{"from":135,"to":141}} {"id":100000179,"name":"getLegacyUnknownSignerFiles","signature":"func getLegacyUnknownSignerFiles(config csrsigningconfig.CSRSigningControllerConfiguration) (string, string)","file":"cmd/kube-controller-manager/app/certificates.go","code":"func getLegacyUnknownSignerFiles(config csrsigningconfig.CSRSigningControllerConfiguration) (string, string) {\n\t// if any cert/key is set for specific CSR signing loops, then the --cluster-signing-{cert,key}-file are not used for any CSR signing loop.\n\tif anySpecificFilesSet(config) {\n\t\treturn config.LegacyUnknownSignerConfiguration.CertFile, config.LegacyUnknownSignerConfiguration.KeyFile\n\t}\n\treturn config.ClusterSigningCertFile, config.ClusterSigningKeyFile\n}","line":{"from":143,"to":149}} {"id":100000180,"name":"startCSRApprovingController","signature":"func startCSRApprovingController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/certificates.go","code":"func startCSRApprovingController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tapprover := approver.NewCSRApprovingController(\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"certificate-controller\"),\n\t\tcontrollerContext.InformerFactory.Certificates().V1().CertificateSigningRequests(),\n\t)\n\tgo approver.Run(ctx, 5)\n\n\treturn nil, true, nil\n}","line":{"from":151,"to":159}} {"id":100000181,"name":"startCSRCleanerController","signature":"func startCSRCleanerController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/certificates.go","code":"func startCSRCleanerController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tcleaner := cleaner.NewCSRCleanerController(\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"certificate-controller\").CertificatesV1().CertificateSigningRequests(),\n\t\tcontrollerContext.InformerFactory.Certificates().V1().CertificateSigningRequests(),\n\t)\n\tgo cleaner.Run(ctx, 1)\n\treturn nil, true, nil\n}","line":{"from":161,"to":168}} {"id":100000182,"name":"startRootCACertPublisher","signature":"func startRootCACertPublisher(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/certificates.go","code":"func startRootCACertPublisher(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tvar (\n\t\trootCA []byte\n\t\terr error\n\t)\n\tif controllerContext.ComponentConfig.SAController.RootCAFile != \"\" {\n\t\tif rootCA, err = readCA(controllerContext.ComponentConfig.SAController.RootCAFile); err != nil {\n\t\t\treturn nil, true, fmt.Errorf(\"error parsing root-ca-file at %s: %v\", controllerContext.ComponentConfig.SAController.RootCAFile, err)\n\t\t}\n\t} else {\n\t\trootCA = controllerContext.ClientBuilder.ConfigOrDie(\"root-ca-cert-publisher\").CAData\n\t}\n\n\tsac, err := rootcacertpublisher.NewPublisher(\n\t\tcontrollerContext.InformerFactory.Core().V1().ConfigMaps(),\n\t\tcontrollerContext.InformerFactory.Core().V1().Namespaces(),\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"root-ca-cert-publisher\"),\n\t\trootCA,\n\t)\n\tif err != nil {\n\t\treturn nil, true, fmt.Errorf(\"error creating root CA certificate publisher: %v\", err)\n\t}\n\tgo sac.Run(ctx, 1)\n\treturn nil, true, nil\n}","line":{"from":170,"to":194}} {"id":100000183,"name":"createCloudProvider","signature":"func createCloudProvider(logger klog.Logger, cloudProvider string, externalCloudVolumePlugin string, cloudConfigFile string,","file":"cmd/kube-controller-manager/app/cloudproviders.go","code":"// createCloudProvider helps consolidate what is needed for cloud providers, we explicitly list the things\n// that the cloud providers need as parameters, so we can control\nfunc createCloudProvider(logger klog.Logger, cloudProvider string, externalCloudVolumePlugin string, cloudConfigFile string,\n\tallowUntaggedCloud bool, sharedInformers informers.SharedInformerFactory) (cloudprovider.Interface, ControllerLoopMode, error) {\n\tvar cloud cloudprovider.Interface\n\tvar loopMode ControllerLoopMode\n\tvar err error\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.DisableCloudProviders) \u0026\u0026 cloudprovider.IsDeprecatedInternal(cloudProvider) {\n\t\tcloudprovider.DisableWarningForProvider(cloudProvider)\n\t\treturn nil, ExternalLoops, fmt.Errorf(\n\t\t\t\"cloud provider %q was specified, but built-in cloud providers are disabled. Please set --cloud-provider=external and migrate to an external cloud provider\",\n\t\t\tcloudProvider)\n\t}\n\n\tif cloudprovider.IsExternal(cloudProvider) {\n\t\tloopMode = ExternalLoops\n\t\tif externalCloudVolumePlugin == \"\" {\n\t\t\t// externalCloudVolumePlugin is temporary until we split all cloud providers out.\n\t\t\t// So we just tell the caller that we need to run ExternalLoops without any cloud provider.\n\t\t\treturn nil, loopMode, nil\n\t\t}\n\t\tcloud, err = cloudprovider.InitCloudProvider(externalCloudVolumePlugin, cloudConfigFile)\n\t} else {\n\t\tcloudprovider.DeprecationWarningForProvider(cloudProvider)\n\n\t\tloopMode = IncludeCloudLoops\n\t\tcloud, err = cloudprovider.InitCloudProvider(cloudProvider, cloudConfigFile)\n\t}\n\tif err != nil {\n\t\treturn nil, loopMode, fmt.Errorf(\"cloud provider could not be initialized: %v\", err)\n\t}\n\n\tif cloud != nil \u0026\u0026 !cloud.HasClusterID() {\n\t\tif allowUntaggedCloud {\n\t\t\tlogger.Info(\"Warning: detected a cluster without a ClusterID. A ClusterID will be required in the future. Please tag your cluster to avoid any future issues\")\n\t\t} else {\n\t\t\treturn nil, loopMode, fmt.Errorf(\"no ClusterID Found. A ClusterID is required for the cloud provider to function properly. This check can be bypassed by setting the allow-untagged-cloud option\")\n\t\t}\n\t}\n\n\tif informerUserCloud, ok := cloud.(cloudprovider.InformerUser); ok {\n\t\tinformerUserCloud.SetInformers(sharedInformers)\n\t}\n\treturn cloud, loopMode, err\n}","line":{"from":30,"to":75}} {"id":100000184,"name":"Complete","signature":"func (c *Config) Complete() *CompletedConfig","file":"cmd/kube-controller-manager/app/config/config.go","code":"// Complete fills in any fields not set that are required to have valid data. It's mutating the receiver.\nfunc (c *Config) Complete() *CompletedConfig {\n\tcc := completedConfig{c}\n\n\tapiserver.AuthorizeClientBearerToken(c.LoopbackClientConfig, \u0026c.Authentication, \u0026c.Authorization)\n\n\treturn \u0026CompletedConfig{\u0026cc}\n}","line":{"from":58,"to":65}} {"id":100000185,"name":"init","signature":"func init()","file":"cmd/kube-controller-manager/app/controllermanager.go","code":"func init() {\n\tutilruntime.Must(logsapi.AddFeatureGates(utilfeature.DefaultMutableFeatureGate))\n\tutilruntime.Must(features.AddFeatureGates(utilfeature.DefaultMutableFeatureGate))\n}","line":{"from":81,"to":84}} {"id":100000186,"name":"NewControllerManagerCommand","signature":"func NewControllerManagerCommand() *cobra.Command","file":"cmd/kube-controller-manager/app/controllermanager.go","code":"// NewControllerManagerCommand creates a *cobra.Command object with default parameters\nfunc NewControllerManagerCommand() *cobra.Command {\n\ts, err := options.NewKubeControllerManagerOptions()\n\tif err != nil {\n\t\tklog.Background().Error(err, \"Unable to initialize command options\")\n\t\tklog.FlushAndExit(klog.ExitFlushTimeout, 1)\n\t}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"kube-controller-manager\",\n\t\tLong: `The Kubernetes controller manager is a daemon that embeds\nthe core control loops shipped with Kubernetes. In applications of robotics and\nautomation, a control loop is a non-terminating loop that regulates the state of\nthe system. In Kubernetes, a controller is a control loop that watches the shared\nstate of the cluster through the apiserver and makes changes attempting to move the\ncurrent state towards the desired state. Examples of controllers that ship with\nKubernetes today are the replication controller, endpoints controller, namespace\ncontroller, and serviceaccounts controller.`,\n\t\tPersistentPreRunE: func(*cobra.Command, []string) error {\n\t\t\t// silence client-go warnings.\n\t\t\t// kube-controller-manager generically watches APIs (including deprecated ones),\n\t\t\t// and CI ensures it works properly against matching kube-apiserver versions.\n\t\t\trestclient.SetDefaultWarningHandler(restclient.NoWarnings{})\n\t\t\treturn nil\n\t\t},\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tverflag.PrintAndExitIfRequested()\n\n\t\t\t// Activate logging as soon as possible, after that\n\t\t\t// show flags with the final logging configuration.\n\t\t\tif err := logsapi.ValidateAndApply(s.Logs, utilfeature.DefaultFeatureGate); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcliflag.PrintFlags(cmd.Flags())\n\n\t\t\tc, err := s.Config(KnownControllers(), ControllersDisabledByDefault.List())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// add feature enablement metrics\n\t\t\tutilfeature.DefaultMutableFeatureGate.AddMetrics()\n\t\t\treturn Run(context.Background(), c.Complete())\n\t\t},\n\t\tArgs: func(cmd *cobra.Command, args []string) error {\n\t\t\tfor _, arg := range args {\n\t\t\t\tif len(arg) \u003e 0 {\n\t\t\t\t\treturn fmt.Errorf(\"%q does not take any arguments, got %q\", cmd.CommandPath(), args)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tfs := cmd.Flags()\n\tnamedFlagSets := s.Flags(KnownControllers(), ControllersDisabledByDefault.List())\n\tverflag.AddFlags(namedFlagSets.FlagSet(\"global\"))\n\tglobalflag.AddGlobalFlags(namedFlagSets.FlagSet(\"global\"), cmd.Name(), logs.SkipLoggingConfigurationFlags())\n\tregisterLegacyGlobalFlags(namedFlagSets)\n\tfor _, f := range namedFlagSets.FlagSets {\n\t\tfs.AddFlagSet(f)\n\t}\n\n\tcols, _, _ := term.TerminalSize(cmd.OutOrStdout())\n\tcliflag.SetUsageAndHelpFunc(cmd, namedFlagSets, cols)\n\n\treturn cmd\n}","line":{"from":103,"to":169}} {"id":100000187,"name":"ResyncPeriod","signature":"func ResyncPeriod(c *config.CompletedConfig) func() time.Duration","file":"cmd/kube-controller-manager/app/controllermanager.go","code":"// ResyncPeriod returns a function which generates a duration each time it is\n// invoked; this is so that multiple controllers don't get into lock-step and all\n// hammer the apiserver with list requests simultaneously.\nfunc ResyncPeriod(c *config.CompletedConfig) func() time.Duration {\n\treturn func() time.Duration {\n\t\tfactor := rand.Float64() + 1\n\t\treturn time.Duration(float64(c.ComponentConfig.Generic.MinResyncPeriod.Nanoseconds()) * factor)\n\t}\n}","line":{"from":171,"to":179}} {"id":100000188,"name":"Run","signature":"func Run(ctx context.Context, c *config.CompletedConfig) error","file":"cmd/kube-controller-manager/app/controllermanager.go","code":"// Run runs the KubeControllerManagerOptions.\nfunc Run(ctx context.Context, c *config.CompletedConfig) error {\n\tlogger := klog.FromContext(ctx)\n\tstopCh := ctx.Done()\n\n\t// To help debugging, immediately log version\n\tlogger.Info(\"Starting\", \"version\", version.Get())\n\n\tlogger.Info(\"Golang settings\", \"GOGC\", os.Getenv(\"GOGC\"), \"GOMAXPROCS\", os.Getenv(\"GOMAXPROCS\"), \"GOTRACEBACK\", os.Getenv(\"GOTRACEBACK\"))\n\n\t// Start events processing pipeline.\n\tc.EventBroadcaster.StartStructuredLogging(0)\n\tc.EventBroadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: c.Client.CoreV1().Events(\"\")})\n\tdefer c.EventBroadcaster.Shutdown()\n\n\tif cfgz, err := configz.New(ConfigzName); err == nil {\n\t\tcfgz.Set(c.ComponentConfig)\n\t} else {\n\t\tlogger.Error(err, \"Unable to register configz\")\n\t}\n\n\t// Setup any healthz checks we will want to use.\n\tvar checks []healthz.HealthChecker\n\tvar electionChecker *leaderelection.HealthzAdaptor\n\tif c.ComponentConfig.Generic.LeaderElection.LeaderElect {\n\t\telectionChecker = leaderelection.NewLeaderHealthzAdaptor(time.Second * 20)\n\t\tchecks = append(checks, electionChecker)\n\t}\n\thealthzHandler := controllerhealthz.NewMutableHealthzHandler(checks...)\n\n\t// Start the controller manager HTTP server\n\t// unsecuredMux is the handler for these controller *after* authn/authz filters have been applied\n\tvar unsecuredMux *mux.PathRecorderMux\n\tif c.SecureServing != nil {\n\t\tunsecuredMux = genericcontrollermanager.NewBaseHandler(\u0026c.ComponentConfig.Generic.Debugging, healthzHandler)\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.ComponentSLIs) {\n\t\t\tslis.SLIMetricsWithReset{}.Install(unsecuredMux)\n\t\t}\n\t\thandler := genericcontrollermanager.BuildHandlerChain(unsecuredMux, \u0026c.Authorization, \u0026c.Authentication)\n\t\t// TODO: handle stoppedCh and listenerStoppedCh returned by c.SecureServing.Serve\n\t\tif _, _, err := c.SecureServing.Serve(handler, 0, stopCh); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tclientBuilder, rootClientBuilder := createClientBuilders(logger, c)\n\n\tsaTokenControllerInitFunc := serviceAccountTokenControllerStarter{rootClientBuilder: rootClientBuilder}.startServiceAccountTokenController\n\n\trun := func(ctx context.Context, startSATokenController InitFunc, initializersFunc ControllerInitializersFunc) {\n\t\tcontrollerContext, err := CreateControllerContext(logger, c, rootClientBuilder, clientBuilder, ctx.Done())\n\t\tif err != nil {\n\t\t\tlogger.Error(err, \"Error building controller context\")\n\t\t\tklog.FlushAndExit(klog.ExitFlushTimeout, 1)\n\t\t}\n\t\tcontrollerInitializers := initializersFunc(controllerContext.LoopMode)\n\t\tif err := StartControllers(ctx, controllerContext, startSATokenController, controllerInitializers, unsecuredMux, healthzHandler); err != nil {\n\t\t\tlogger.Error(err, \"Error starting controllers\")\n\t\t\tklog.FlushAndExit(klog.ExitFlushTimeout, 1)\n\t\t}\n\n\t\tcontrollerContext.InformerFactory.Start(stopCh)\n\t\tcontrollerContext.ObjectOrMetadataInformerFactory.Start(stopCh)\n\t\tclose(controllerContext.InformersStarted)\n\n\t\t\u003c-ctx.Done()\n\t}\n\n\t// No leader election, run directly\n\tif !c.ComponentConfig.Generic.LeaderElection.LeaderElect {\n\t\trun(ctx, saTokenControllerInitFunc, NewControllerInitializers)\n\t\treturn nil\n\t}\n\n\tid, err := os.Hostname()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// add a uniquifier so that two processes on the same host don't accidentally both become active\n\tid = id + \"_\" + string(uuid.NewUUID())\n\n\t// leaderMigrator will be non-nil if and only if Leader Migration is enabled.\n\tvar leaderMigrator *leadermigration.LeaderMigrator = nil\n\n\t// startSATokenController will be original saTokenControllerInitFunc if leader migration is not enabled.\n\tstartSATokenController := saTokenControllerInitFunc\n\n\t// If leader migration is enabled, create the LeaderMigrator and prepare for migration\n\tif leadermigration.Enabled(\u0026c.ComponentConfig.Generic) {\n\t\tlogger.Info(\"starting leader migration\")\n\n\t\tleaderMigrator = leadermigration.NewLeaderMigrator(\u0026c.ComponentConfig.Generic.LeaderMigration,\n\t\t\t\"kube-controller-manager\")\n\n\t\t// Wrap saTokenControllerInitFunc to signal readiness for migration after starting\n\t\t// the controller.\n\t\tstartSATokenController = func(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\t\t\tdefer close(leaderMigrator.MigrationReady)\n\t\t\treturn saTokenControllerInitFunc(ctx, controllerContext)\n\t\t}\n\t}\n\n\t// Start the main lock\n\tgo leaderElectAndRun(ctx, c, id, electionChecker,\n\t\tc.ComponentConfig.Generic.LeaderElection.ResourceLock,\n\t\tc.ComponentConfig.Generic.LeaderElection.ResourceName,\n\t\tleaderelection.LeaderCallbacks{\n\t\t\tOnStartedLeading: func(ctx context.Context) {\n\t\t\t\tinitializersFunc := NewControllerInitializers\n\t\t\t\tif leaderMigrator != nil {\n\t\t\t\t\t// If leader migration is enabled, we should start only non-migrated controllers\n\t\t\t\t\t// for the main lock.\n\t\t\t\t\tinitializersFunc = createInitializersFunc(leaderMigrator.FilterFunc, leadermigration.ControllerNonMigrated)\n\t\t\t\t\tlogger.Info(\"leader migration: starting main controllers.\")\n\t\t\t\t}\n\t\t\t\trun(ctx, startSATokenController, initializersFunc)\n\t\t\t},\n\t\t\tOnStoppedLeading: func() {\n\t\t\t\tlogger.Error(nil, \"leaderelection lost\")\n\t\t\t\tklog.FlushAndExit(klog.ExitFlushTimeout, 1)\n\t\t\t},\n\t\t})\n\n\t// If Leader Migration is enabled, proceed to attempt the migration lock.\n\tif leaderMigrator != nil {\n\t\t// Wait for Service Account Token Controller to start before acquiring the migration lock.\n\t\t// At this point, the main lock must have already been acquired, or the KCM process already exited.\n\t\t// We wait for the main lock before acquiring the migration lock to prevent the situation\n\t\t// where KCM instance A holds the main lock while KCM instance B holds the migration lock.\n\t\t\u003c-leaderMigrator.MigrationReady\n\n\t\t// Start the migration lock.\n\t\tgo leaderElectAndRun(ctx, c, id, electionChecker,\n\t\t\tc.ComponentConfig.Generic.LeaderMigration.ResourceLock,\n\t\t\tc.ComponentConfig.Generic.LeaderMigration.LeaderName,\n\t\t\tleaderelection.LeaderCallbacks{\n\t\t\t\tOnStartedLeading: func(ctx context.Context) {\n\t\t\t\t\tlogger.Info(\"leader migration: starting migrated controllers.\")\n\t\t\t\t\t// DO NOT start saTokenController under migration lock\n\t\t\t\t\trun(ctx, nil, createInitializersFunc(leaderMigrator.FilterFunc, leadermigration.ControllerMigrated))\n\t\t\t\t},\n\t\t\t\tOnStoppedLeading: func() {\n\t\t\t\t\tlogger.Error(nil, \"migration leaderelection lost\")\n\t\t\t\t\tklog.FlushAndExit(klog.ExitFlushTimeout, 1)\n\t\t\t\t},\n\t\t\t})\n\t}\n\n\t\u003c-stopCh\n\treturn nil\n}","line":{"from":181,"to":332}} {"id":100000189,"name":"IsControllerEnabled","signature":"func (c ControllerContext) IsControllerEnabled(name string) bool","file":"cmd/kube-controller-manager/app/controllermanager.go","code":"// IsControllerEnabled checks if the context's controllers enabled or not\nfunc (c ControllerContext) IsControllerEnabled(name string) bool {\n\treturn genericcontrollermanager.IsControllerEnabled(name, ControllersDisabledByDefault, c.ComponentConfig.Generic.Controllers)\n}","line":{"from":381,"to":384}} {"id":100000190,"name":"KnownControllers","signature":"func KnownControllers() []string","file":"cmd/kube-controller-manager/app/controllermanager.go","code":"// KnownControllers returns all known controllers's name\nfunc KnownControllers() []string {\n\tret := sets.StringKeySet(NewControllerInitializers(IncludeCloudLoops))\n\n\t// add \"special\" controllers that aren't initialized normally. These controllers cannot be initialized\n\t// using a normal function. The only known special case is the SA token controller which *must* be started\n\t// first to ensure that the SA tokens for future controllers will exist. Think very carefully before adding\n\t// to this list.\n\tret.Insert(\n\t\tsaTokenControllerName,\n\t)\n\n\treturn ret.List()\n}","line":{"from":401,"to":414}} {"id":100000191,"name":"NewControllerInitializers","signature":"func NewControllerInitializers(loopMode ControllerLoopMode) map[string]InitFunc","file":"cmd/kube-controller-manager/app/controllermanager.go","code":"// NewControllerInitializers is a public map of named controller groups (you can start more than one in an init func)\n// paired to their InitFunc. This allows for structured downstream composition and subdivision.\nfunc NewControllerInitializers(loopMode ControllerLoopMode) map[string]InitFunc {\n\tcontrollers := map[string]InitFunc{}\n\n\t// All of the controllers must have unique names, or else we will explode.\n\tregister := func(name string, fn InitFunc) {\n\t\tif _, found := controllers[name]; found {\n\t\t\tpanic(fmt.Sprintf(\"controller name %q was registered twice\", name))\n\t\t}\n\t\tcontrollers[name] = fn\n\t}\n\n\tregister(\"endpoint\", startEndpointController)\n\tregister(\"endpointslice\", startEndpointSliceController)\n\tregister(\"endpointslicemirroring\", startEndpointSliceMirroringController)\n\tregister(\"replicationcontroller\", startReplicationController)\n\tregister(\"podgc\", startPodGCController)\n\tregister(\"resourcequota\", startResourceQuotaController)\n\tregister(\"namespace\", startNamespaceController)\n\tregister(\"serviceaccount\", startServiceAccountController)\n\tregister(\"garbagecollector\", startGarbageCollectorController)\n\tregister(\"daemonset\", startDaemonSetController)\n\tregister(\"job\", startJobController)\n\tregister(\"deployment\", startDeploymentController)\n\tregister(\"replicaset\", startReplicaSetController)\n\tregister(\"horizontalpodautoscaling\", startHPAController)\n\tregister(\"disruption\", startDisruptionController)\n\tregister(\"statefulset\", startStatefulSetController)\n\tregister(\"cronjob\", startCronJobController)\n\tregister(\"csrsigning\", startCSRSigningController)\n\tregister(\"csrapproving\", startCSRApprovingController)\n\tregister(\"csrcleaner\", startCSRCleanerController)\n\tregister(\"ttl\", startTTLController)\n\tregister(\"bootstrapsigner\", startBootstrapSignerController)\n\tregister(\"tokencleaner\", startTokenCleanerController)\n\tregister(\"nodeipam\", startNodeIpamController)\n\tregister(\"nodelifecycle\", startNodeLifecycleController)\n\tif loopMode == IncludeCloudLoops {\n\t\tregister(\"service\", startServiceController)\n\t\tregister(\"route\", startRouteController)\n\t\tregister(\"cloud-node-lifecycle\", startCloudNodeLifecycleController)\n\t\t// TODO: volume controller into the IncludeCloudLoops only set.\n\t}\n\tregister(\"persistentvolume-binder\", startPersistentVolumeBinderController)\n\tregister(\"attachdetach\", startAttachDetachController)\n\tregister(\"persistentvolume-expander\", startVolumeExpandController)\n\tregister(\"clusterrole-aggregation\", startClusterRoleAggregrationController)\n\tregister(\"pvc-protection\", startPVCProtectionController)\n\tregister(\"pv-protection\", startPVProtectionController)\n\tregister(\"ttl-after-finished\", startTTLAfterFinishedController)\n\tregister(\"root-ca-cert-publisher\", startRootCACertPublisher)\n\tregister(\"ephemeral-volume\", startEphemeralVolumeController)\n\tif utilfeature.DefaultFeatureGate.Enabled(genericfeatures.APIServerIdentity) \u0026\u0026\n\t\tutilfeature.DefaultFeatureGate.Enabled(genericfeatures.StorageVersionAPI) {\n\t\tregister(\"storage-version-gc\", startStorageVersionGCController)\n\t}\n\tif utilfeature.DefaultFeatureGate.Enabled(kubefeatures.DynamicResourceAllocation) {\n\t\tregister(\"resource-claim-controller\", startResourceClaimController)\n\t}\n\n\treturn controllers\n}","line":{"from":426,"to":488}} {"id":100000192,"name":"GetAvailableResources","signature":"func GetAvailableResources(clientBuilder clientbuilder.ControllerClientBuilder) (map[schema.GroupVersionResource]bool, error)","file":"cmd/kube-controller-manager/app/controllermanager.go","code":"// GetAvailableResources gets the map which contains all available resources of the apiserver\n// TODO: In general, any controller checking this needs to be dynamic so\n// users don't have to restart their controller manager if they change the apiserver.\n// Until we get there, the structure here needs to be exposed for the construction of a proper ControllerContext.\nfunc GetAvailableResources(clientBuilder clientbuilder.ControllerClientBuilder) (map[schema.GroupVersionResource]bool, error) {\n\tclient := clientBuilder.ClientOrDie(\"controller-discovery\")\n\tdiscoveryClient := client.Discovery()\n\t_, resourceMap, err := discoveryClient.ServerGroupsAndResources()\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unable to get all supported resources from server: %v\", err))\n\t}\n\tif len(resourceMap) == 0 {\n\t\treturn nil, fmt.Errorf(\"unable to get any supported resources from server\")\n\t}\n\n\tallResources := map[schema.GroupVersionResource]bool{}\n\tfor _, apiResourceList := range resourceMap {\n\t\tversion, err := schema.ParseGroupVersion(apiResourceList.GroupVersion)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, apiResource := range apiResourceList.APIResources {\n\t\t\tallResources[version.WithResource(apiResource.Name)] = true\n\t\t}\n\t}\n\n\treturn allResources, nil\n}","line":{"from":490,"to":517}} {"id":100000193,"name":"CreateControllerContext","signature":"func CreateControllerContext(logger klog.Logger, s *config.CompletedConfig, rootClientBuilder, clientBuilder clientbuilder.ControllerClientBuilder, stop \u003c-chan struct{}) (ControllerContext, error)","file":"cmd/kube-controller-manager/app/controllermanager.go","code":"// CreateControllerContext creates a context struct containing references to resources needed by the\n// controllers such as the cloud provider and clientBuilder. rootClientBuilder is only used for\n// the shared-informers client and token controller.\nfunc CreateControllerContext(logger klog.Logger, s *config.CompletedConfig, rootClientBuilder, clientBuilder clientbuilder.ControllerClientBuilder, stop \u003c-chan struct{}) (ControllerContext, error) {\n\tversionedClient := rootClientBuilder.ClientOrDie(\"shared-informers\")\n\tsharedInformers := informers.NewSharedInformerFactory(versionedClient, ResyncPeriod(s)())\n\n\tmetadataClient := metadata.NewForConfigOrDie(rootClientBuilder.ConfigOrDie(\"metadata-informers\"))\n\tmetadataInformers := metadatainformer.NewSharedInformerFactory(metadataClient, ResyncPeriod(s)())\n\n\t// If apiserver is not running we should wait for some time and fail only then. This is particularly\n\t// important when we start apiserver and controller manager at the same time.\n\tif err := genericcontrollermanager.WaitForAPIServer(versionedClient, 10*time.Second); err != nil {\n\t\treturn ControllerContext{}, fmt.Errorf(\"failed to wait for apiserver being healthy: %v\", err)\n\t}\n\n\t// Use a discovery client capable of being refreshed.\n\tdiscoveryClient := rootClientBuilder.DiscoveryClientOrDie(\"controller-discovery\")\n\tcachedClient := cacheddiscovery.NewMemCacheClient(discoveryClient)\n\trestMapper := restmapper.NewDeferredDiscoveryRESTMapper(cachedClient)\n\tgo wait.Until(func() {\n\t\trestMapper.Reset()\n\t}, 30*time.Second, stop)\n\n\tavailableResources, err := GetAvailableResources(rootClientBuilder)\n\tif err != nil {\n\t\treturn ControllerContext{}, err\n\t}\n\n\tcloud, loopMode, err := createCloudProvider(logger, s.ComponentConfig.KubeCloudShared.CloudProvider.Name, s.ComponentConfig.KubeCloudShared.ExternalCloudVolumePlugin,\n\t\ts.ComponentConfig.KubeCloudShared.CloudProvider.CloudConfigFile, s.ComponentConfig.KubeCloudShared.AllowUntaggedCloud, sharedInformers)\n\tif err != nil {\n\t\treturn ControllerContext{}, err\n\t}\n\n\tctx := ControllerContext{\n\t\tClientBuilder: clientBuilder,\n\t\tInformerFactory: sharedInformers,\n\t\tObjectOrMetadataInformerFactory: informerfactory.NewInformerFactory(sharedInformers, metadataInformers),\n\t\tComponentConfig: s.ComponentConfig,\n\t\tRESTMapper: restMapper,\n\t\tAvailableResources: availableResources,\n\t\tCloud: cloud,\n\t\tLoopMode: loopMode,\n\t\tInformersStarted: make(chan struct{}),\n\t\tResyncPeriod: ResyncPeriod(s),\n\t\tControllerManagerMetrics: controllersmetrics.NewControllerManagerMetrics(\"kube-controller-manager\"),\n\t}\n\tcontrollersmetrics.Register()\n\treturn ctx, nil\n}","line":{"from":519,"to":569}} {"id":100000194,"name":"StartControllers","signature":"func StartControllers(ctx context.Context, controllerCtx ControllerContext, startSATokenController InitFunc, controllers map[string]InitFunc,","file":"cmd/kube-controller-manager/app/controllermanager.go","code":"// StartControllers starts a set of controllers with a specified ControllerContext\nfunc StartControllers(ctx context.Context, controllerCtx ControllerContext, startSATokenController InitFunc, controllers map[string]InitFunc,\n\tunsecuredMux *mux.PathRecorderMux, healthzHandler *controllerhealthz.MutableHealthzHandler) error {\n\tlogger := klog.FromContext(ctx)\n\n\t// Always start the SA token controller first using a full-power client, since it needs to mint tokens for the rest\n\t// If this fails, just return here and fail since other controllers won't be able to get credentials.\n\tif startSATokenController != nil {\n\t\tif _, _, err := startSATokenController(ctx, controllerCtx); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Initialize the cloud provider with a reference to the clientBuilder only after token controller\n\t// has started in case the cloud provider uses the client builder.\n\tif controllerCtx.Cloud != nil {\n\t\tcontrollerCtx.Cloud.Initialize(controllerCtx.ClientBuilder, ctx.Done())\n\t}\n\n\tvar controllerChecks []healthz.HealthChecker\n\n\t// Each controller is passed a context where the logger has the name of\n\t// the controller set through WithName. That name then becomes the prefix of\n\t// of all log messages emitted by that controller.\n\t//\n\t// In this loop, an explicit \"controller\" key is used instead, for two reasons:\n\t// - while contextual logging is alpha, klog.LoggerWithName is still a no-op,\n\t// so we cannot rely on it yet to add the name\n\t// - it allows distinguishing between log entries emitted by the controller\n\t// and those emitted for it - this is a bit debatable and could be revised.\n\tfor controllerName, initFn := range controllers {\n\t\tif !controllerCtx.IsControllerEnabled(controllerName) {\n\t\t\tlogger.Info(\"Warning: controller is disabled\", \"controller\", controllerName)\n\t\t\tcontinue\n\t\t}\n\n\t\ttime.Sleep(wait.Jitter(controllerCtx.ComponentConfig.Generic.ControllerStartInterval.Duration, ControllerStartJitter))\n\n\t\tlogger.V(1).Info(\"Starting controller\", \"controller\", controllerName)\n\t\tctrl, started, err := initFn(klog.NewContext(ctx, klog.LoggerWithName(logger, controllerName)), controllerCtx)\n\t\tif err != nil {\n\t\t\tlogger.Error(err, \"Error starting controller\", \"controller\", controllerName)\n\t\t\treturn err\n\t\t}\n\t\tif !started {\n\t\t\tlogger.Info(\"Warning: skipping controller\", \"controller\", controllerName)\n\t\t\tcontinue\n\t\t}\n\t\tcheck := controllerhealthz.NamedPingChecker(controllerName)\n\t\tif ctrl != nil {\n\t\t\t// check if the controller supports and requests a debugHandler\n\t\t\t// and it needs the unsecuredMux to mount the handler onto.\n\t\t\tif debuggable, ok := ctrl.(controller.Debuggable); ok \u0026\u0026 unsecuredMux != nil {\n\t\t\t\tif debugHandler := debuggable.DebuggingHandler(); debugHandler != nil {\n\t\t\t\t\tbasePath := \"/debug/controllers/\" + controllerName\n\t\t\t\t\tunsecuredMux.UnlistedHandle(basePath, http.StripPrefix(basePath, debugHandler))\n\t\t\t\t\tunsecuredMux.UnlistedHandlePrefix(basePath+\"/\", http.StripPrefix(basePath, debugHandler))\n\t\t\t\t}\n\t\t\t}\n\t\t\tif healthCheckable, ok := ctrl.(controller.HealthCheckable); ok {\n\t\t\t\tif realCheck := healthCheckable.HealthChecker(); realCheck != nil {\n\t\t\t\t\tcheck = controllerhealthz.NamedHealthChecker(controllerName, realCheck)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcontrollerChecks = append(controllerChecks, check)\n\n\t\tlogger.Info(\"Started controller\", \"controller\", controllerName)\n\t}\n\n\thealthzHandler.AddHealthChecker(controllerChecks...)\n\n\treturn nil\n}","line":{"from":571,"to":644}} {"id":100000195,"name":"startServiceAccountTokenController","signature":"func (c serviceAccountTokenControllerStarter) startServiceAccountTokenController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/controllermanager.go","code":"func (c serviceAccountTokenControllerStarter) startServiceAccountTokenController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tlogger := klog.FromContext(ctx)\n\tif !controllerContext.IsControllerEnabled(saTokenControllerName) {\n\t\tlogger.Info(\"Warning: controller is disabled\", \"controller\", saTokenControllerName)\n\t\treturn nil, false, nil\n\t}\n\n\tif len(controllerContext.ComponentConfig.SAController.ServiceAccountKeyFile) == 0 {\n\t\tlogger.Info(\"Controller is disabled because there is no private key\", \"controller\", saTokenControllerName)\n\t\treturn nil, false, nil\n\t}\n\tprivateKey, err := keyutil.PrivateKeyFromFile(controllerContext.ComponentConfig.SAController.ServiceAccountKeyFile)\n\tif err != nil {\n\t\treturn nil, true, fmt.Errorf(\"error reading key for service account token controller: %v\", err)\n\t}\n\n\tvar rootCA []byte\n\tif controllerContext.ComponentConfig.SAController.RootCAFile != \"\" {\n\t\tif rootCA, err = readCA(controllerContext.ComponentConfig.SAController.RootCAFile); err != nil {\n\t\t\treturn nil, true, fmt.Errorf(\"error parsing root-ca-file at %s: %v\", controllerContext.ComponentConfig.SAController.RootCAFile, err)\n\t\t}\n\t} else {\n\t\trootCA = c.rootClientBuilder.ConfigOrDie(\"tokens-controller\").CAData\n\t}\n\n\ttokenGenerator, err := serviceaccount.JWTTokenGenerator(serviceaccount.LegacyIssuer, privateKey)\n\tif err != nil {\n\t\treturn nil, false, fmt.Errorf(\"failed to build token generator: %v\", err)\n\t}\n\tcontroller, err := serviceaccountcontroller.NewTokensController(\n\t\tcontrollerContext.InformerFactory.Core().V1().ServiceAccounts(),\n\t\tcontrollerContext.InformerFactory.Core().V1().Secrets(),\n\t\tc.rootClientBuilder.ClientOrDie(\"tokens-controller\"),\n\t\tserviceaccountcontroller.TokensControllerOptions{\n\t\t\tTokenGenerator: tokenGenerator,\n\t\t\tRootCA: rootCA,\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, true, fmt.Errorf(\"error creating Tokens controller: %v\", err)\n\t}\n\tgo controller.Run(ctx, int(controllerContext.ComponentConfig.SAController.ConcurrentSATokenSyncs))\n\n\t// start the first set of informers now so that other controllers can start\n\tcontrollerContext.InformerFactory.Start(ctx.Done())\n\n\treturn nil, true, nil\n}","line":{"from":653,"to":700}} {"id":100000196,"name":"readCA","signature":"func readCA(file string) ([]byte, error)","file":"cmd/kube-controller-manager/app/controllermanager.go","code":"func readCA(file string) ([]byte, error) {\n\trootCA, err := os.ReadFile(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif _, err := certutil.ParseCertsPEM(rootCA); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn rootCA, err\n}","line":{"from":702,"to":712}} {"id":100000197,"name":"createClientBuilders","signature":"func createClientBuilders(logger klog.Logger, c *config.CompletedConfig) (clientBuilder clientbuilder.ControllerClientBuilder, rootClientBuilder clientbuilder.ControllerClientBuilder)","file":"cmd/kube-controller-manager/app/controllermanager.go","code":"// createClientBuilders creates clientBuilder and rootClientBuilder from the given configuration\nfunc createClientBuilders(logger klog.Logger, c *config.CompletedConfig) (clientBuilder clientbuilder.ControllerClientBuilder, rootClientBuilder clientbuilder.ControllerClientBuilder) {\n\trootClientBuilder = clientbuilder.SimpleControllerClientBuilder{\n\t\tClientConfig: c.Kubeconfig,\n\t}\n\tif c.ComponentConfig.KubeCloudShared.UseServiceAccountCredentials {\n\t\tif len(c.ComponentConfig.SAController.ServiceAccountKeyFile) == 0 {\n\t\t\t// It's possible another controller process is creating the tokens for us.\n\t\t\t// If one isn't, we'll timeout and exit when our client builder is unable to create the tokens.\n\t\t\tlogger.Info(\"Warning: --use-service-account-credentials was specified without providing a --service-account-private-key-file\")\n\t\t}\n\n\t\tclientBuilder = clientbuilder.NewDynamicClientBuilder(\n\t\t\trestclient.AnonymousClientConfig(c.Kubeconfig),\n\t\t\tc.Client.CoreV1(),\n\t\t\tmetav1.NamespaceSystem)\n\t} else {\n\t\tclientBuilder = rootClientBuilder\n\t}\n\treturn\n}","line":{"from":714,"to":734}} {"id":100000198,"name":"leaderElectAndRun","signature":"func leaderElectAndRun(ctx context.Context, c *config.CompletedConfig, lockIdentity string, electionChecker *leaderelection.HealthzAdaptor, resourceLock string, leaseName string, callbacks leaderelection.LeaderCallbacks)","file":"cmd/kube-controller-manager/app/controllermanager.go","code":"// leaderElectAndRun runs the leader election, and runs the callbacks once the leader lease is acquired.\n// TODO: extract this function into staging/controller-manager\nfunc leaderElectAndRun(ctx context.Context, c *config.CompletedConfig, lockIdentity string, electionChecker *leaderelection.HealthzAdaptor, resourceLock string, leaseName string, callbacks leaderelection.LeaderCallbacks) {\n\tlogger := klog.FromContext(ctx)\n\trl, err := resourcelock.NewFromKubeconfig(resourceLock,\n\t\tc.ComponentConfig.Generic.LeaderElection.ResourceNamespace,\n\t\tleaseName,\n\t\tresourcelock.ResourceLockConfig{\n\t\t\tIdentity: lockIdentity,\n\t\t\tEventRecorder: c.EventRecorder,\n\t\t},\n\t\tc.Kubeconfig,\n\t\tc.ComponentConfig.Generic.LeaderElection.RenewDeadline.Duration)\n\tif err != nil {\n\t\tlogger.Error(err, \"Error creating lock\")\n\t\tklog.FlushAndExit(klog.ExitFlushTimeout, 1)\n\t}\n\n\tleaderelection.RunOrDie(ctx, leaderelection.LeaderElectionConfig{\n\t\tLock: rl,\n\t\tLeaseDuration: c.ComponentConfig.Generic.LeaderElection.LeaseDuration.Duration,\n\t\tRenewDeadline: c.ComponentConfig.Generic.LeaderElection.RenewDeadline.Duration,\n\t\tRetryPeriod: c.ComponentConfig.Generic.LeaderElection.RetryPeriod.Duration,\n\t\tCallbacks: callbacks,\n\t\tWatchDog: electionChecker,\n\t\tName: leaseName,\n\t})\n\n\tpanic(\"unreachable\")\n}","line":{"from":736,"to":765}} {"id":100000199,"name":"createInitializersFunc","signature":"func createInitializersFunc(filterFunc leadermigration.FilterFunc, expected leadermigration.FilterResult) ControllerInitializersFunc","file":"cmd/kube-controller-manager/app/controllermanager.go","code":"// createInitializersFunc creates a initializersFunc that returns all initializer\n// with expected as the result after filtering through filterFunc.\nfunc createInitializersFunc(filterFunc leadermigration.FilterFunc, expected leadermigration.FilterResult) ControllerInitializersFunc {\n\treturn func(loopMode ControllerLoopMode) map[string]InitFunc {\n\t\tinitializers := make(map[string]InitFunc)\n\t\tfor name, initializer := range NewControllerInitializers(loopMode) {\n\t\t\tif filterFunc(name) == expected {\n\t\t\t\tinitializers[name] = initializer\n\t\t\t}\n\t\t}\n\t\treturn initializers\n\t}\n}","line":{"from":767,"to":779}} {"id":100000200,"name":"startServiceController","signature":"func startServiceController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/core.go","code":"func startServiceController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tserviceController, err := servicecontroller.New(\n\t\tcontrollerContext.Cloud,\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"service-controller\"),\n\t\tcontrollerContext.InformerFactory.Core().V1().Services(),\n\t\tcontrollerContext.InformerFactory.Core().V1().Nodes(),\n\t\tcontrollerContext.ComponentConfig.KubeCloudShared.ClusterName,\n\t\tutilfeature.DefaultFeatureGate,\n\t)\n\tif err != nil {\n\t\t// This error shouldn't fail. It lives like this as a legacy.\n\t\tklog.FromContext(ctx).Error(err, \"Failed to start service controller\")\n\t\treturn nil, false, nil\n\t}\n\tgo serviceController.Run(ctx, int(controllerContext.ComponentConfig.ServiceController.ConcurrentServiceSyncs), controllerContext.ControllerManagerMetrics)\n\treturn nil, true, nil\n}","line":{"from":81,"to":97}} {"id":100000201,"name":"startNodeIpamController","signature":"func startNodeIpamController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/core.go","code":"func startNodeIpamController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tvar serviceCIDR *net.IPNet\n\tvar secondaryServiceCIDR *net.IPNet\n\tlogger := klog.FromContext(ctx)\n\n\t// should we start nodeIPAM\n\tif !controllerContext.ComponentConfig.KubeCloudShared.AllocateNodeCIDRs {\n\t\treturn nil, false, nil\n\t}\n\n\t// Cannot run cloud ipam controller if cloud provider is nil (--cloud-provider not set or set to 'external')\n\tif controllerContext.Cloud == nil \u0026\u0026 controllerContext.ComponentConfig.KubeCloudShared.CIDRAllocatorType == string(ipam.CloudAllocatorType) {\n\t\treturn nil, false, errors.New(\"--cidr-allocator-type is set to 'CloudAllocator' but cloud provider is not configured\")\n\t}\n\n\tclusterCIDRs, err := validateCIDRs(controllerContext.ComponentConfig.KubeCloudShared.ClusterCIDR)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\t// service cidr processing\n\tif len(strings.TrimSpace(controllerContext.ComponentConfig.NodeIPAMController.ServiceCIDR)) != 0 {\n\t\t_, serviceCIDR, err = netutils.ParseCIDRSloppy(controllerContext.ComponentConfig.NodeIPAMController.ServiceCIDR)\n\t\tif err != nil {\n\t\t\tlogger.Info(\"Warning: unsuccessful parsing of service CIDR\", \"CIDR\", controllerContext.ComponentConfig.NodeIPAMController.ServiceCIDR, \"err\", err)\n\t\t}\n\t}\n\n\tif len(strings.TrimSpace(controllerContext.ComponentConfig.NodeIPAMController.SecondaryServiceCIDR)) != 0 {\n\t\t_, secondaryServiceCIDR, err = netutils.ParseCIDRSloppy(controllerContext.ComponentConfig.NodeIPAMController.SecondaryServiceCIDR)\n\t\tif err != nil {\n\t\t\tlogger.Info(\"Warning: unsuccessful parsing of service CIDR\", \"CIDR\", controllerContext.ComponentConfig.NodeIPAMController.SecondaryServiceCIDR, \"err\", err)\n\t\t}\n\t}\n\n\t// the following checks are triggered if both serviceCIDR and secondaryServiceCIDR are provided\n\tif serviceCIDR != nil \u0026\u0026 secondaryServiceCIDR != nil {\n\t\t// should be dual stack (from different IPFamilies)\n\t\tdualstackServiceCIDR, err := netutils.IsDualStackCIDRs([]*net.IPNet{serviceCIDR, secondaryServiceCIDR})\n\t\tif err != nil {\n\t\t\treturn nil, false, fmt.Errorf(\"failed to perform dualstack check on serviceCIDR and secondaryServiceCIDR error:%v\", err)\n\t\t}\n\t\tif !dualstackServiceCIDR {\n\t\t\treturn nil, false, fmt.Errorf(\"serviceCIDR and secondaryServiceCIDR are not dualstack (from different IPfamiles)\")\n\t\t}\n\t}\n\n\t// only --node-cidr-mask-size-ipv4 and --node-cidr-mask-size-ipv6 supported with dual stack clusters.\n\t// --node-cidr-mask-size flag is incompatible with dual stack clusters.\n\tnodeCIDRMaskSizes, err := setNodeCIDRMaskSizes(controllerContext.ComponentConfig.NodeIPAMController, clusterCIDRs)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\tvar clusterCIDRInformer v1alpha1.ClusterCIDRInformer\n\tif utilfeature.DefaultFeatureGate.Enabled(features.MultiCIDRRangeAllocator) {\n\t\tclusterCIDRInformer = controllerContext.InformerFactory.Networking().V1alpha1().ClusterCIDRs()\n\t}\n\n\tnodeIpamController, err := nodeipamcontroller.NewNodeIpamController(\n\t\tctx,\n\t\tcontrollerContext.InformerFactory.Core().V1().Nodes(),\n\t\tclusterCIDRInformer,\n\t\tcontrollerContext.Cloud,\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"node-controller\"),\n\t\tclusterCIDRs,\n\t\tserviceCIDR,\n\t\tsecondaryServiceCIDR,\n\t\tnodeCIDRMaskSizes,\n\t\tipam.CIDRAllocatorType(controllerContext.ComponentConfig.KubeCloudShared.CIDRAllocatorType),\n\t)\n\tif err != nil {\n\t\treturn nil, true, err\n\t}\n\tgo nodeIpamController.RunWithMetrics(ctx, controllerContext.ControllerManagerMetrics)\n\treturn nil, true, nil\n}","line":{"from":99,"to":175}} {"id":100000202,"name":"startNodeLifecycleController","signature":"func startNodeLifecycleController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/core.go","code":"func startNodeLifecycleController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tlifecycleController, err := lifecyclecontroller.NewNodeLifecycleController(\n\t\tctx,\n\t\tcontrollerContext.InformerFactory.Coordination().V1().Leases(),\n\t\tcontrollerContext.InformerFactory.Core().V1().Pods(),\n\t\tcontrollerContext.InformerFactory.Core().V1().Nodes(),\n\t\tcontrollerContext.InformerFactory.Apps().V1().DaemonSets(),\n\t\t// node lifecycle controller uses existing cluster role from node-controller\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"node-controller\"),\n\t\tcontrollerContext.ComponentConfig.KubeCloudShared.NodeMonitorPeriod.Duration,\n\t\tcontrollerContext.ComponentConfig.NodeLifecycleController.NodeStartupGracePeriod.Duration,\n\t\tcontrollerContext.ComponentConfig.NodeLifecycleController.NodeMonitorGracePeriod.Duration,\n\t\tcontrollerContext.ComponentConfig.NodeLifecycleController.NodeEvictionRate,\n\t\tcontrollerContext.ComponentConfig.NodeLifecycleController.SecondaryNodeEvictionRate,\n\t\tcontrollerContext.ComponentConfig.NodeLifecycleController.LargeClusterSizeThreshold,\n\t\tcontrollerContext.ComponentConfig.NodeLifecycleController.UnhealthyZoneThreshold,\n\t)\n\tif err != nil {\n\t\treturn nil, true, err\n\t}\n\tgo lifecycleController.Run(ctx)\n\treturn nil, true, nil\n}","line":{"from":177,"to":199}} {"id":100000203,"name":"startCloudNodeLifecycleController","signature":"func startCloudNodeLifecycleController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/core.go","code":"func startCloudNodeLifecycleController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tlogger := klog.FromContext(ctx)\n\tcloudNodeLifecycleController, err := cloudnodelifecyclecontroller.NewCloudNodeLifecycleController(\n\t\tcontrollerContext.InformerFactory.Core().V1().Nodes(),\n\t\t// cloud node lifecycle controller uses existing cluster role from node-controller\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"node-controller\"),\n\t\tcontrollerContext.Cloud,\n\t\tcontrollerContext.ComponentConfig.KubeCloudShared.NodeMonitorPeriod.Duration,\n\t)\n\tif err != nil {\n\t\t// the controller manager should continue to run if the \"Instances\" interface is not\n\t\t// supported, though it's unlikely for a cloud provider to not support it\n\t\tlogger.Error(err, \"Failed to start cloud node lifecycle controller\")\n\t\treturn nil, false, nil\n\t}\n\n\tgo cloudNodeLifecycleController.Run(ctx, controllerContext.ControllerManagerMetrics)\n\treturn nil, true, nil\n}","line":{"from":201,"to":219}} {"id":100000204,"name":"startRouteController","signature":"func startRouteController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/core.go","code":"func startRouteController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tlogger := klog.FromContext(ctx)\n\tif !controllerContext.ComponentConfig.KubeCloudShared.AllocateNodeCIDRs || !controllerContext.ComponentConfig.KubeCloudShared.ConfigureCloudRoutes {\n\t\tlogger.Info(\"Will not configure cloud provider routes for allocate-node-cidrs\", \"CIDRs\", controllerContext.ComponentConfig.KubeCloudShared.AllocateNodeCIDRs, \"routes\", controllerContext.ComponentConfig.KubeCloudShared.ConfigureCloudRoutes)\n\t\treturn nil, false, nil\n\t}\n\tif controllerContext.Cloud == nil {\n\t\tlogger.Info(\"Warning: configure-cloud-routes is set, but no cloud provider specified. Will not configure cloud provider routes.\")\n\t\treturn nil, false, nil\n\t}\n\troutes, ok := controllerContext.Cloud.Routes()\n\tif !ok {\n\t\tlogger.Info(\"Warning: configure-cloud-routes is set, but cloud provider does not support routes. Will not configure cloud provider routes.\")\n\t\treturn nil, false, nil\n\t}\n\n\tclusterCIDRs, err := validateCIDRs(controllerContext.ComponentConfig.KubeCloudShared.ClusterCIDR)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\trouteController := routecontroller.New(routes,\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"route-controller\"),\n\t\tcontrollerContext.InformerFactory.Core().V1().Nodes(),\n\t\tcontrollerContext.ComponentConfig.KubeCloudShared.ClusterName,\n\t\tclusterCIDRs)\n\tgo routeController.Run(ctx, controllerContext.ComponentConfig.KubeCloudShared.RouteReconciliationPeriod.Duration, controllerContext.ControllerManagerMetrics)\n\treturn nil, true, nil\n}","line":{"from":221,"to":249}} {"id":100000205,"name":"startPersistentVolumeBinderController","signature":"func startPersistentVolumeBinderController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/core.go","code":"func startPersistentVolumeBinderController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tlogger := klog.FromContext(ctx)\n\tplugins, err := ProbeControllerVolumePlugins(logger, controllerContext.Cloud, controllerContext.ComponentConfig.PersistentVolumeBinderController.VolumeConfiguration)\n\tif err != nil {\n\t\treturn nil, true, fmt.Errorf(\"failed to probe volume plugins when starting persistentvolume controller: %v\", err)\n\t}\n\tfilteredDialOptions, err := options.ParseVolumeHostFilters(\n\t\tcontrollerContext.ComponentConfig.PersistentVolumeBinderController.VolumeHostCIDRDenylist,\n\t\tcontrollerContext.ComponentConfig.PersistentVolumeBinderController.VolumeHostAllowLocalLoopback)\n\tif err != nil {\n\t\treturn nil, true, err\n\t}\n\tparams := persistentvolumecontroller.ControllerParameters{\n\t\tKubeClient: controllerContext.ClientBuilder.ClientOrDie(\"persistent-volume-binder\"),\n\t\tSyncPeriod: controllerContext.ComponentConfig.PersistentVolumeBinderController.PVClaimBinderSyncPeriod.Duration,\n\t\tVolumePlugins: plugins,\n\t\tCloud: controllerContext.Cloud,\n\t\tClusterName: controllerContext.ComponentConfig.KubeCloudShared.ClusterName,\n\t\tVolumeInformer: controllerContext.InformerFactory.Core().V1().PersistentVolumes(),\n\t\tClaimInformer: controllerContext.InformerFactory.Core().V1().PersistentVolumeClaims(),\n\t\tClassInformer: controllerContext.InformerFactory.Storage().V1().StorageClasses(),\n\t\tPodInformer: controllerContext.InformerFactory.Core().V1().Pods(),\n\t\tNodeInformer: controllerContext.InformerFactory.Core().V1().Nodes(),\n\t\tEnableDynamicProvisioning: controllerContext.ComponentConfig.PersistentVolumeBinderController.VolumeConfiguration.EnableDynamicProvisioning,\n\t\tFilteredDialOptions: filteredDialOptions,\n\t}\n\tvolumeController, volumeControllerErr := persistentvolumecontroller.NewController(ctx, params)\n\tif volumeControllerErr != nil {\n\t\treturn nil, true, fmt.Errorf(\"failed to construct persistentvolume controller: %v\", volumeControllerErr)\n\t}\n\tgo volumeController.Run(ctx)\n\treturn nil, true, nil\n}","line":{"from":251,"to":283}} {"id":100000206,"name":"startAttachDetachController","signature":"func startAttachDetachController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/core.go","code":"func startAttachDetachController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tlogger := klog.FromContext(ctx)\n\tcsiNodeInformer := controllerContext.InformerFactory.Storage().V1().CSINodes()\n\tcsiDriverInformer := controllerContext.InformerFactory.Storage().V1().CSIDrivers()\n\n\tplugins, err := ProbeAttachableVolumePlugins(logger)\n\tif err != nil {\n\t\treturn nil, true, fmt.Errorf(\"failed to probe volume plugins when starting attach/detach controller: %v\", err)\n\t}\n\n\tfilteredDialOptions, err := options.ParseVolumeHostFilters(\n\t\tcontrollerContext.ComponentConfig.PersistentVolumeBinderController.VolumeHostCIDRDenylist,\n\t\tcontrollerContext.ComponentConfig.PersistentVolumeBinderController.VolumeHostAllowLocalLoopback)\n\tif err != nil {\n\t\treturn nil, true, err\n\t}\n\n\tctx = klog.NewContext(ctx, logger)\n\tattachDetachController, attachDetachControllerErr :=\n\t\tattachdetach.NewAttachDetachController(\n\t\t\tlogger,\n\t\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"attachdetach-controller\"),\n\t\t\tcontrollerContext.InformerFactory.Core().V1().Pods(),\n\t\t\tcontrollerContext.InformerFactory.Core().V1().Nodes(),\n\t\t\tcontrollerContext.InformerFactory.Core().V1().PersistentVolumeClaims(),\n\t\t\tcontrollerContext.InformerFactory.Core().V1().PersistentVolumes(),\n\t\t\tcsiNodeInformer,\n\t\t\tcsiDriverInformer,\n\t\t\tcontrollerContext.InformerFactory.Storage().V1().VolumeAttachments(),\n\t\t\tcontrollerContext.Cloud,\n\t\t\tplugins,\n\t\t\tGetDynamicPluginProber(controllerContext.ComponentConfig.PersistentVolumeBinderController.VolumeConfiguration),\n\t\t\tcontrollerContext.ComponentConfig.AttachDetachController.DisableAttachDetachReconcilerSync,\n\t\t\tcontrollerContext.ComponentConfig.AttachDetachController.ReconcilerSyncLoopPeriod.Duration,\n\t\t\tattachdetach.DefaultTimerConfig,\n\t\t\tfilteredDialOptions,\n\t\t)\n\tif attachDetachControllerErr != nil {\n\t\treturn nil, true, fmt.Errorf(\"failed to start attach/detach controller: %v\", attachDetachControllerErr)\n\t}\n\tgo attachDetachController.Run(ctx)\n\treturn nil, true, nil\n}","line":{"from":285,"to":327}} {"id":100000207,"name":"startVolumeExpandController","signature":"func startVolumeExpandController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/core.go","code":"func startVolumeExpandController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tlogger := klog.FromContext(ctx)\n\tplugins, err := ProbeExpandableVolumePlugins(logger, controllerContext.ComponentConfig.PersistentVolumeBinderController.VolumeConfiguration)\n\tif err != nil {\n\t\treturn nil, true, fmt.Errorf(\"failed to probe volume plugins when starting volume expand controller: %v\", err)\n\t}\n\tcsiTranslator := csitrans.New()\n\tfilteredDialOptions, err := options.ParseVolumeHostFilters(\n\t\tcontrollerContext.ComponentConfig.PersistentVolumeBinderController.VolumeHostCIDRDenylist,\n\t\tcontrollerContext.ComponentConfig.PersistentVolumeBinderController.VolumeHostAllowLocalLoopback)\n\tif err != nil {\n\t\treturn nil, true, err\n\t}\n\texpandController, expandControllerErr := expand.NewExpandController(\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"expand-controller\"),\n\t\tcontrollerContext.InformerFactory.Core().V1().PersistentVolumeClaims(),\n\t\tcontrollerContext.InformerFactory.Core().V1().PersistentVolumes(),\n\t\tcontrollerContext.Cloud,\n\t\tplugins,\n\t\tcsiTranslator,\n\t\tcsimigration.NewPluginManager(csiTranslator, utilfeature.DefaultFeatureGate),\n\t\tfilteredDialOptions,\n\t)\n\n\tif expandControllerErr != nil {\n\t\treturn nil, true, fmt.Errorf(\"failed to start volume expand controller: %v\", expandControllerErr)\n\t}\n\tgo expandController.Run(ctx)\n\treturn nil, true, nil\n\n}","line":{"from":329,"to":359}} {"id":100000208,"name":"startEphemeralVolumeController","signature":"func startEphemeralVolumeController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/core.go","code":"func startEphemeralVolumeController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tephemeralController, err := ephemeral.NewController(\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"ephemeral-volume-controller\"),\n\t\tcontrollerContext.InformerFactory.Core().V1().Pods(),\n\t\tcontrollerContext.InformerFactory.Core().V1().PersistentVolumeClaims())\n\tif err != nil {\n\t\treturn nil, true, fmt.Errorf(\"failed to start ephemeral volume controller: %v\", err)\n\t}\n\tgo ephemeralController.Run(ctx, int(controllerContext.ComponentConfig.EphemeralVolumeController.ConcurrentEphemeralVolumeSyncs))\n\treturn nil, true, nil\n}","line":{"from":361,"to":371}} {"id":100000209,"name":"startResourceClaimController","signature":"func startResourceClaimController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/core.go","code":"func startResourceClaimController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tephemeralController, err := resourceclaim.NewController(\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"resource-claim-controller\"),\n\t\tcontrollerContext.InformerFactory.Core().V1().Pods(),\n\t\tcontrollerContext.InformerFactory.Resource().V1alpha2().ResourceClaims(),\n\t\tcontrollerContext.InformerFactory.Resource().V1alpha2().ResourceClaimTemplates())\n\tif err != nil {\n\t\treturn nil, true, fmt.Errorf(\"failed to start ephemeral volume controller: %v\", err)\n\t}\n\tgo ephemeralController.Run(ctx, defaultResourceClaimControllerWorkers)\n\treturn nil, true, nil\n}","line":{"from":375,"to":386}} {"id":100000210,"name":"startEndpointController","signature":"func startEndpointController(ctx context.Context, controllerCtx ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/core.go","code":"func startEndpointController(ctx context.Context, controllerCtx ControllerContext) (controller.Interface, bool, error) {\n\tgo endpointcontroller.NewEndpointController(\n\t\tcontrollerCtx.InformerFactory.Core().V1().Pods(),\n\t\tcontrollerCtx.InformerFactory.Core().V1().Services(),\n\t\tcontrollerCtx.InformerFactory.Core().V1().Endpoints(),\n\t\tcontrollerCtx.ClientBuilder.ClientOrDie(\"endpoint-controller\"),\n\t\tcontrollerCtx.ComponentConfig.EndpointController.EndpointUpdatesBatchPeriod.Duration,\n\t).Run(ctx, int(controllerCtx.ComponentConfig.EndpointController.ConcurrentEndpointSyncs))\n\treturn nil, true, nil\n}","line":{"from":388,"to":397}} {"id":100000211,"name":"startReplicationController","signature":"func startReplicationController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/core.go","code":"func startReplicationController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tgo replicationcontroller.NewReplicationManager(\n\t\tcontrollerContext.InformerFactory.Core().V1().Pods(),\n\t\tcontrollerContext.InformerFactory.Core().V1().ReplicationControllers(),\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"replication-controller\"),\n\t\treplicationcontroller.BurstReplicas,\n\t).Run(ctx, int(controllerContext.ComponentConfig.ReplicationController.ConcurrentRCSyncs))\n\treturn nil, true, nil\n}","line":{"from":399,"to":407}} {"id":100000212,"name":"startPodGCController","signature":"func startPodGCController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/core.go","code":"func startPodGCController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tgo podgc.NewPodGC(\n\t\tctx,\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"pod-garbage-collector\"),\n\t\tcontrollerContext.InformerFactory.Core().V1().Pods(),\n\t\tcontrollerContext.InformerFactory.Core().V1().Nodes(),\n\t\tint(controllerContext.ComponentConfig.PodGCController.TerminatedPodGCThreshold),\n\t).Run(ctx)\n\treturn nil, true, nil\n}","line":{"from":409,"to":418}} {"id":100000213,"name":"startResourceQuotaController","signature":"func startResourceQuotaController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/core.go","code":"func startResourceQuotaController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tresourceQuotaControllerClient := controllerContext.ClientBuilder.ClientOrDie(\"resourcequota-controller\")\n\tresourceQuotaControllerDiscoveryClient := controllerContext.ClientBuilder.DiscoveryClientOrDie(\"resourcequota-controller\")\n\tdiscoveryFunc := resourceQuotaControllerDiscoveryClient.ServerPreferredNamespacedResources\n\tlisterFuncForResource := generic.ListerFuncForResourceFunc(controllerContext.InformerFactory.ForResource)\n\tquotaConfiguration := quotainstall.NewQuotaConfigurationForControllers(listerFuncForResource)\n\n\tresourceQuotaControllerOptions := \u0026resourcequotacontroller.ControllerOptions{\n\t\tQuotaClient: resourceQuotaControllerClient.CoreV1(),\n\t\tResourceQuotaInformer: controllerContext.InformerFactory.Core().V1().ResourceQuotas(),\n\t\tResyncPeriod: pkgcontroller.StaticResyncPeriodFunc(controllerContext.ComponentConfig.ResourceQuotaController.ResourceQuotaSyncPeriod.Duration),\n\t\tInformerFactory: controllerContext.ObjectOrMetadataInformerFactory,\n\t\tReplenishmentResyncPeriod: controllerContext.ResyncPeriod,\n\t\tDiscoveryFunc: discoveryFunc,\n\t\tIgnoredResourcesFunc: quotaConfiguration.IgnoredResources,\n\t\tInformersStarted: controllerContext.InformersStarted,\n\t\tRegistry: generic.NewRegistry(quotaConfiguration.Evaluators()),\n\t\tUpdateFilter: quotainstall.DefaultUpdateFilter(),\n\t}\n\tresourceQuotaController, err := resourcequotacontroller.NewController(ctx, resourceQuotaControllerOptions)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\tgo resourceQuotaController.Run(ctx, int(controllerContext.ComponentConfig.ResourceQuotaController.ConcurrentResourceQuotaSyncs))\n\n\t// Periodically the quota controller to detect new resource types\n\tgo resourceQuotaController.Sync(ctx, discoveryFunc, 30*time.Second)\n\n\treturn nil, true, nil\n}","line":{"from":420,"to":449}} {"id":100000214,"name":"startNamespaceController","signature":"func startNamespaceController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/core.go","code":"func startNamespaceController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\t// the namespace cleanup controller is very chatty. It makes lots of discovery calls and then it makes lots of delete calls\n\t// the ratelimiter negatively affects its speed. Deleting 100 total items in a namespace (that's only a few of each resource\n\t// including events), takes ~10 seconds by default.\n\tnsKubeconfig := controllerContext.ClientBuilder.ConfigOrDie(\"namespace-controller\")\n\tnsKubeconfig.QPS *= 20\n\tnsKubeconfig.Burst *= 100\n\tnamespaceKubeClient := clientset.NewForConfigOrDie(nsKubeconfig)\n\treturn startModifiedNamespaceController(ctx, controllerContext, namespaceKubeClient, nsKubeconfig)\n}","line":{"from":451,"to":460}} {"id":100000215,"name":"startModifiedNamespaceController","signature":"func startModifiedNamespaceController(ctx context.Context, controllerContext ControllerContext, namespaceKubeClient clientset.Interface, nsKubeconfig *restclient.Config) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/core.go","code":"func startModifiedNamespaceController(ctx context.Context, controllerContext ControllerContext, namespaceKubeClient clientset.Interface, nsKubeconfig *restclient.Config) (controller.Interface, bool, error) {\n\n\tmetadataClient, err := metadata.NewForConfig(nsKubeconfig)\n\tif err != nil {\n\t\treturn nil, true, err\n\t}\n\n\tdiscoverResourcesFn := namespaceKubeClient.Discovery().ServerPreferredNamespacedResources\n\n\tnamespaceController := namespacecontroller.NewNamespaceController(\n\t\tctx,\n\t\tnamespaceKubeClient,\n\t\tmetadataClient,\n\t\tdiscoverResourcesFn,\n\t\tcontrollerContext.InformerFactory.Core().V1().Namespaces(),\n\t\tcontrollerContext.ComponentConfig.NamespaceController.NamespaceSyncPeriod.Duration,\n\t\tv1.FinalizerKubernetes,\n\t)\n\tgo namespaceController.Run(ctx, int(controllerContext.ComponentConfig.NamespaceController.ConcurrentNamespaceSyncs))\n\n\treturn nil, true, nil\n}","line":{"from":462,"to":483}} {"id":100000216,"name":"startServiceAccountController","signature":"func startServiceAccountController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/core.go","code":"func startServiceAccountController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tsac, err := serviceaccountcontroller.NewServiceAccountsController(\n\t\tcontrollerContext.InformerFactory.Core().V1().ServiceAccounts(),\n\t\tcontrollerContext.InformerFactory.Core().V1().Namespaces(),\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"service-account-controller\"),\n\t\tserviceaccountcontroller.DefaultServiceAccountsControllerOptions(),\n\t)\n\tif err != nil {\n\t\treturn nil, true, fmt.Errorf(\"error creating ServiceAccount controller: %v\", err)\n\t}\n\tgo sac.Run(ctx, 1)\n\treturn nil, true, nil\n}","line":{"from":485,"to":497}} {"id":100000217,"name":"startTTLController","signature":"func startTTLController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/core.go","code":"func startTTLController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tgo ttlcontroller.NewTTLController(\n\t\tctx,\n\t\tcontrollerContext.InformerFactory.Core().V1().Nodes(),\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"ttl-controller\"),\n\t).Run(ctx, 5)\n\treturn nil, true, nil\n}","line":{"from":499,"to":506}} {"id":100000218,"name":"startGarbageCollectorController","signature":"func startGarbageCollectorController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/core.go","code":"func startGarbageCollectorController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tif !controllerContext.ComponentConfig.GarbageCollectorController.EnableGarbageCollector {\n\t\treturn nil, false, nil\n\t}\n\n\tgcClientset := controllerContext.ClientBuilder.ClientOrDie(\"generic-garbage-collector\")\n\tdiscoveryClient := controllerContext.ClientBuilder.DiscoveryClientOrDie(\"generic-garbage-collector\")\n\n\tconfig := controllerContext.ClientBuilder.ConfigOrDie(\"generic-garbage-collector\")\n\t// Increase garbage collector controller's throughput: each object deletion takes two API calls,\n\t// so to get |config.QPS| deletion rate we need to allow 2x more requests for this controller.\n\tconfig.QPS *= 2\n\tmetadataClient, err := metadata.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, true, err\n\t}\n\n\tignoredResources := make(map[schema.GroupResource]struct{})\n\tfor _, r := range controllerContext.ComponentConfig.GarbageCollectorController.GCIgnoredResources {\n\t\tignoredResources[schema.GroupResource{Group: r.Group, Resource: r.Resource}] = struct{}{}\n\t}\n\tgarbageCollector, err := garbagecollector.NewGarbageCollector(\n\t\tgcClientset,\n\t\tmetadataClient,\n\t\tcontrollerContext.RESTMapper,\n\t\tignoredResources,\n\t\tcontrollerContext.ObjectOrMetadataInformerFactory,\n\t\tcontrollerContext.InformersStarted,\n\t)\n\tif err != nil {\n\t\treturn nil, true, fmt.Errorf(\"failed to start the generic garbage collector: %v\", err)\n\t}\n\n\t// Start the garbage collector.\n\tworkers := int(controllerContext.ComponentConfig.GarbageCollectorController.ConcurrentGCSyncs)\n\tgo garbageCollector.Run(ctx, workers)\n\n\t// Periodically refresh the RESTMapper with new discovery information and sync\n\t// the garbage collector.\n\tgo garbageCollector.Sync(ctx, discoveryClient, 30*time.Second)\n\n\treturn garbageCollector, true, nil\n}","line":{"from":508,"to":550}} {"id":100000219,"name":"startPVCProtectionController","signature":"func startPVCProtectionController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/core.go","code":"func startPVCProtectionController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tpvcProtectionController, err := pvcprotection.NewPVCProtectionController(\n\t\tklog.FromContext(ctx),\n\t\tcontrollerContext.InformerFactory.Core().V1().PersistentVolumeClaims(),\n\t\tcontrollerContext.InformerFactory.Core().V1().Pods(),\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"pvc-protection-controller\"),\n\t)\n\tif err != nil {\n\t\treturn nil, true, fmt.Errorf(\"failed to start the pvc protection controller: %v\", err)\n\t}\n\tgo pvcProtectionController.Run(ctx, 1)\n\treturn nil, true, nil\n}","line":{"from":552,"to":564}} {"id":100000220,"name":"startPVProtectionController","signature":"func startPVProtectionController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/core.go","code":"func startPVProtectionController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tgo pvprotection.NewPVProtectionController(\n\t\tklog.FromContext(ctx),\n\t\tcontrollerContext.InformerFactory.Core().V1().PersistentVolumes(),\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"pv-protection-controller\"),\n\t).Run(ctx, 1)\n\treturn nil, true, nil\n}","line":{"from":566,"to":573}} {"id":100000221,"name":"startTTLAfterFinishedController","signature":"func startTTLAfterFinishedController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/core.go","code":"func startTTLAfterFinishedController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tgo ttlafterfinished.New(\n\t\tctx,\n\t\tcontrollerContext.InformerFactory.Batch().V1().Jobs(),\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"ttl-after-finished-controller\"),\n\t).Run(ctx, int(controllerContext.ComponentConfig.TTLAfterFinishedController.ConcurrentTTLSyncs))\n\treturn nil, true, nil\n}","line":{"from":575,"to":582}} {"id":100000222,"name":"validateCIDRs","signature":"func validateCIDRs(cidrsList string) ([]*net.IPNet, error)","file":"cmd/kube-controller-manager/app/core.go","code":"// processCIDRs is a helper function that works on a comma separated cidrs and returns\n// a list of typed cidrs\n// error if failed to parse any of the cidrs or invalid length of cidrs\nfunc validateCIDRs(cidrsList string) ([]*net.IPNet, error) {\n\t// failure: bad cidrs in config\n\tclusterCIDRs, dualStack, err := processCIDRs(cidrsList)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// failure: more than one cidr but they are not configured as dual stack\n\tif len(clusterCIDRs) \u003e 1 \u0026\u0026 !dualStack {\n\t\treturn nil, fmt.Errorf(\"len of ClusterCIDRs==%v and they are not configured as dual stack (at least one from each IPFamily\", len(clusterCIDRs))\n\t}\n\n\t// failure: more than cidrs is not allowed even with dual stack\n\tif len(clusterCIDRs) \u003e 2 {\n\t\treturn nil, fmt.Errorf(\"length of clusterCIDRs is:%v more than max allowed of 2\", len(clusterCIDRs))\n\t}\n\n\treturn clusterCIDRs, nil\n}","line":{"from":584,"to":605}} {"id":100000223,"name":"processCIDRs","signature":"func processCIDRs(cidrsList string) ([]*net.IPNet, bool, error)","file":"cmd/kube-controller-manager/app/core.go","code":"// processCIDRs is a helper function that works on a comma separated cidrs and returns\n// a list of typed cidrs\n// a flag if cidrs represents a dual stack\n// error if failed to parse any of the cidrs\nfunc processCIDRs(cidrsList string) ([]*net.IPNet, bool, error) {\n\tcidrsSplit := strings.Split(strings.TrimSpace(cidrsList), \",\")\n\n\tcidrs, err := netutils.ParseCIDRs(cidrsSplit)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\t// if cidrs has an error then the previous call will fail\n\t// safe to ignore error checking on next call\n\tdualstack, _ := netutils.IsDualStackCIDRs(cidrs)\n\n\treturn cidrs, dualstack, nil\n}","line":{"from":607,"to":624}} {"id":100000224,"name":"setNodeCIDRMaskSizes","signature":"func setNodeCIDRMaskSizes(cfg nodeipamconfig.NodeIPAMControllerConfiguration, clusterCIDRs []*net.IPNet) ([]int, error)","file":"cmd/kube-controller-manager/app/core.go","code":"// setNodeCIDRMaskSizes returns the IPv4 and IPv6 node cidr mask sizes to the value provided\n// for --node-cidr-mask-size-ipv4 and --node-cidr-mask-size-ipv6 respectively. If value not provided,\n// then it will return default IPv4 and IPv6 cidr mask sizes.\nfunc setNodeCIDRMaskSizes(cfg nodeipamconfig.NodeIPAMControllerConfiguration, clusterCIDRs []*net.IPNet) ([]int, error) {\n\n\tsortedSizes := func(maskSizeIPv4, maskSizeIPv6 int) []int {\n\t\tnodeMaskCIDRs := make([]int, len(clusterCIDRs))\n\n\t\tfor idx, clusterCIDR := range clusterCIDRs {\n\t\t\tif netutils.IsIPv6CIDR(clusterCIDR) {\n\t\t\t\tnodeMaskCIDRs[idx] = maskSizeIPv6\n\t\t\t} else {\n\t\t\t\tnodeMaskCIDRs[idx] = maskSizeIPv4\n\t\t\t}\n\t\t}\n\t\treturn nodeMaskCIDRs\n\t}\n\n\t// --node-cidr-mask-size flag is incompatible with dual stack clusters.\n\tipv4Mask, ipv6Mask := defaultNodeMaskCIDRIPv4, defaultNodeMaskCIDRIPv6\n\tisDualstack := len(clusterCIDRs) \u003e 1\n\n\t// case one: cluster is dualstack (i.e, more than one cidr)\n\tif isDualstack {\n\t\t// if --node-cidr-mask-size then fail, user must configure the correct dual-stack mask sizes (or use default)\n\t\tif cfg.NodeCIDRMaskSize != 0 {\n\t\t\treturn nil, errors.New(\"usage of --node-cidr-mask-size is not allowed with dual-stack clusters\")\n\n\t\t}\n\n\t\tif cfg.NodeCIDRMaskSizeIPv4 != 0 {\n\t\t\tipv4Mask = int(cfg.NodeCIDRMaskSizeIPv4)\n\t\t}\n\t\tif cfg.NodeCIDRMaskSizeIPv6 != 0 {\n\t\t\tipv6Mask = int(cfg.NodeCIDRMaskSizeIPv6)\n\t\t}\n\t\treturn sortedSizes(ipv4Mask, ipv6Mask), nil\n\t}\n\n\tmaskConfigured := cfg.NodeCIDRMaskSize != 0\n\tmaskV4Configured := cfg.NodeCIDRMaskSizeIPv4 != 0\n\tmaskV6Configured := cfg.NodeCIDRMaskSizeIPv6 != 0\n\tisSingleStackIPv6 := netutils.IsIPv6CIDR(clusterCIDRs[0])\n\n\t// original flag is set\n\tif maskConfigured {\n\t\t// original mask flag is still the main reference.\n\t\tif maskV4Configured || maskV6Configured {\n\t\t\treturn nil, errors.New(\"usage of --node-cidr-mask-size-ipv4 and --node-cidr-mask-size-ipv6 is not allowed if --node-cidr-mask-size is set. For dual-stack clusters please unset it and use IPFamily specific flags\")\n\t\t}\n\n\t\tmask := int(cfg.NodeCIDRMaskSize)\n\t\treturn sortedSizes(mask, mask), nil\n\t}\n\n\tif maskV4Configured {\n\t\tif isSingleStackIPv6 {\n\t\t\treturn nil, errors.New(\"usage of --node-cidr-mask-size-ipv4 is not allowed for a single-stack IPv6 cluster\")\n\t\t}\n\n\t\tipv4Mask = int(cfg.NodeCIDRMaskSizeIPv4)\n\t}\n\n\t// !maskV4Configured \u0026\u0026 !maskConfigured \u0026\u0026 maskV6Configured\n\tif maskV6Configured {\n\t\tif !isSingleStackIPv6 {\n\t\t\treturn nil, errors.New(\"usage of --node-cidr-mask-size-ipv6 is not allowed for a single-stack IPv4 cluster\")\n\t\t}\n\n\t\tipv6Mask = int(cfg.NodeCIDRMaskSizeIPv6)\n\t}\n\treturn sortedSizes(ipv4Mask, ipv6Mask), nil\n}","line":{"from":626,"to":698}} {"id":100000225,"name":"startStorageVersionGCController","signature":"func startStorageVersionGCController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/core.go","code":"func startStorageVersionGCController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tgo storageversiongc.NewStorageVersionGC(\n\t\tctx,\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"storage-version-garbage-collector\"),\n\t\tcontrollerContext.InformerFactory.Coordination().V1().Leases(),\n\t\tcontrollerContext.InformerFactory.Internal().V1alpha1().StorageVersions(),\n\t).Run(ctx)\n\treturn nil, true, nil\n}","line":{"from":700,"to":708}} {"id":100000226,"name":"startEndpointSliceController","signature":"func startEndpointSliceController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/discovery.go","code":"func startEndpointSliceController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tgo endpointslicecontroller.NewController(\n\t\tcontrollerContext.InformerFactory.Core().V1().Pods(),\n\t\tcontrollerContext.InformerFactory.Core().V1().Services(),\n\t\tcontrollerContext.InformerFactory.Core().V1().Nodes(),\n\t\tcontrollerContext.InformerFactory.Discovery().V1().EndpointSlices(),\n\t\tcontrollerContext.ComponentConfig.EndpointSliceController.MaxEndpointsPerSlice,\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"endpointslice-controller\"),\n\t\tcontrollerContext.ComponentConfig.EndpointSliceController.EndpointUpdatesBatchPeriod.Duration,\n\t).Run(int(controllerContext.ComponentConfig.EndpointSliceController.ConcurrentServiceEndpointSyncs), ctx.Done())\n\treturn nil, true, nil\n}","line":{"from":30,"to":41}} {"id":100000227,"name":"startEndpointSliceMirroringController","signature":"func startEndpointSliceMirroringController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/discovery.go","code":"func startEndpointSliceMirroringController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tgo endpointslicemirroringcontroller.NewController(\n\t\tcontrollerContext.InformerFactory.Core().V1().Endpoints(),\n\t\tcontrollerContext.InformerFactory.Discovery().V1().EndpointSlices(),\n\t\tcontrollerContext.InformerFactory.Core().V1().Services(),\n\t\tcontrollerContext.ComponentConfig.EndpointSliceMirroringController.MirroringMaxEndpointsPerSubset,\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"endpointslicemirroring-controller\"),\n\t\tcontrollerContext.ComponentConfig.EndpointSliceMirroringController.MirroringEndpointUpdatesBatchPeriod.Duration,\n\t).Run(int(controllerContext.ComponentConfig.EndpointSliceMirroringController.MirroringConcurrentServiceEndpointSyncs), ctx.Done())\n\treturn nil, true, nil\n}","line":{"from":43,"to":53}} {"id":100000228,"name":"registerLegacyGlobalFlags","signature":"func registerLegacyGlobalFlags(namedFlagSets cliflag.NamedFlagSets)","file":"cmd/kube-controller-manager/app/flags_providerless.go","code":"func registerLegacyGlobalFlags(namedFlagSets cliflag.NamedFlagSets) {\n\t// no-op when legacy cloud providers are not compiled\n}","line":{"from":26,"to":28}} {"id":100000229,"name":"registerLegacyGlobalFlags","signature":"func registerLegacyGlobalFlags(namedFlagSets cliflag.NamedFlagSets)","file":"cmd/kube-controller-manager/app/flags_providers.go","code":"func registerLegacyGlobalFlags(namedFlagSets cliflag.NamedFlagSets) {\n\t// hoist this flag from the global flagset to preserve the commandline until\n\t// the gce cloudprovider is removed.\n\tglobalflag.Register(namedFlagSets.FlagSet(\"generic\"), \"cloud-provider-gce-lb-src-cidrs\")\n\tnamedFlagSets.FlagSet(\"generic\").MarkDeprecated(\"cloud-provider-gce-lb-src-cidrs\", \"This flag will be removed once the GCE Cloud Provider is removed from kube-controller-manager\")\n}","line":{"from":27,"to":32}} {"id":100000230,"name":"AddFlags","signature":"func (o *AttachDetachControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"cmd/kube-controller-manager/app/options/attachdetachcontroller.go","code":"// AddFlags adds flags related to AttachDetachController for controller manager to the specified FlagSet.\nfunc (o *AttachDetachControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.BoolVar(\u0026o.DisableAttachDetachReconcilerSync, \"disable-attach-detach-reconcile-sync\", false, \"Disable volume attach detach reconciler sync. Disabling this may cause volumes to be mismatched with pods. Use wisely.\")\n\tfs.DurationVar(\u0026o.ReconcilerSyncLoopPeriod.Duration, \"attach-detach-reconcile-sync-period\", o.ReconcilerSyncLoopPeriod.Duration, \"The reconciler sync wait time between volume attach detach. This duration must be larger than one second, and increasing this value from the default may allow for volumes to be mismatched with pods.\")\n}","line":{"from":32,"to":40}} {"id":100000231,"name":"ApplyTo","signature":"func (o *AttachDetachControllerOptions) ApplyTo(cfg *attachdetachconfig.AttachDetachControllerConfiguration) error","file":"cmd/kube-controller-manager/app/options/attachdetachcontroller.go","code":"// ApplyTo fills up AttachDetachController config with options.\nfunc (o *AttachDetachControllerOptions) ApplyTo(cfg *attachdetachconfig.AttachDetachControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.DisableAttachDetachReconcilerSync = o.DisableAttachDetachReconcilerSync\n\tcfg.ReconcilerSyncLoopPeriod = o.ReconcilerSyncLoopPeriod\n\n\treturn nil\n}","line":{"from":42,"to":52}} {"id":100000232,"name":"Validate","signature":"func (o *AttachDetachControllerOptions) Validate() []error","file":"cmd/kube-controller-manager/app/options/attachdetachcontroller.go","code":"// Validate checks validation of AttachDetachControllerOptions.\nfunc (o *AttachDetachControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\n\tif o.ReconcilerSyncLoopPeriod.Duration \u003c time.Second {\n\t\terrs = append(errs, fmt.Errorf(\"duration time must be greater than one second as set via command line option reconcile-sync-loop-period\"))\n\t}\n\n\treturn errs\n}","line":{"from":54,"to":67}} {"id":100000233,"name":"AddFlags","signature":"func (o *CronJobControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"cmd/kube-controller-manager/app/options/cronjobcontroller.go","code":"// AddFlags adds flags related to JobController for controller manager to the specified FlagSet.\nfunc (o *CronJobControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n}","line":{"from":30,"to":35}} {"id":100000234,"name":"ApplyTo","signature":"func (o *CronJobControllerOptions) ApplyTo(cfg *cronjobconfig.CronJobControllerConfiguration) error","file":"cmd/kube-controller-manager/app/options/cronjobcontroller.go","code":"// ApplyTo fills up JobController config with options.\nfunc (o *CronJobControllerOptions) ApplyTo(cfg *cronjobconfig.CronJobControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ConcurrentCronJobSyncs = o.ConcurrentCronJobSyncs\n\n\treturn nil\n}","line":{"from":37,"to":46}} {"id":100000235,"name":"Validate","signature":"func (o *CronJobControllerOptions) Validate() []error","file":"cmd/kube-controller-manager/app/options/cronjobcontroller.go","code":"// Validate checks validation of CronJobControllerOptions.\nfunc (o *CronJobControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\treturn errs\n}","line":{"from":48,"to":56}} {"id":100000236,"name":"AddFlags","signature":"func (o *CSRSigningControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"cmd/kube-controller-manager/app/options/csrsigningcontroller.go","code":"// AddFlags adds flags related to CSRSigningController for controller manager to the specified FlagSet.\nfunc (o *CSRSigningControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.StringVar(\u0026o.ClusterSigningCertFile, \"cluster-signing-cert-file\", o.ClusterSigningCertFile, \"Filename containing a PEM-encoded X509 CA certificate used to issue cluster-scoped certificates. If specified, no more specific --cluster-signing-* flag may be specified.\")\n\tfs.StringVar(\u0026o.ClusterSigningKeyFile, \"cluster-signing-key-file\", o.ClusterSigningKeyFile, \"Filename containing a PEM-encoded RSA or ECDSA private key used to sign cluster-scoped certificates. If specified, no more specific --cluster-signing-* flag may be specified.\")\n\tfs.StringVar(\u0026o.KubeletServingSignerConfiguration.CertFile, \"cluster-signing-kubelet-serving-cert-file\", o.KubeletServingSignerConfiguration.CertFile, \"Filename containing a PEM-encoded X509 CA certificate used to issue certificates for the kubernetes.io/kubelet-serving signer. If specified, --cluster-signing-{cert,key}-file must not be set.\")\n\tfs.StringVar(\u0026o.KubeletServingSignerConfiguration.KeyFile, \"cluster-signing-kubelet-serving-key-file\", o.KubeletServingSignerConfiguration.KeyFile, \"Filename containing a PEM-encoded RSA or ECDSA private key used to sign certificates for the kubernetes.io/kubelet-serving signer. If specified, --cluster-signing-{cert,key}-file must not be set.\")\n\tfs.StringVar(\u0026o.KubeletClientSignerConfiguration.CertFile, \"cluster-signing-kubelet-client-cert-file\", o.KubeletClientSignerConfiguration.CertFile, \"Filename containing a PEM-encoded X509 CA certificate used to issue certificates for the kubernetes.io/kube-apiserver-client-kubelet signer. If specified, --cluster-signing-{cert,key}-file must not be set.\")\n\tfs.StringVar(\u0026o.KubeletClientSignerConfiguration.KeyFile, \"cluster-signing-kubelet-client-key-file\", o.KubeletClientSignerConfiguration.KeyFile, \"Filename containing a PEM-encoded RSA or ECDSA private key used to sign certificates for the kubernetes.io/kube-apiserver-client-kubelet signer. If specified, --cluster-signing-{cert,key}-file must not be set.\")\n\tfs.StringVar(\u0026o.KubeAPIServerClientSignerConfiguration.CertFile, \"cluster-signing-kube-apiserver-client-cert-file\", o.KubeAPIServerClientSignerConfiguration.CertFile, \"Filename containing a PEM-encoded X509 CA certificate used to issue certificates for the kubernetes.io/kube-apiserver-client signer. If specified, --cluster-signing-{cert,key}-file must not be set.\")\n\tfs.StringVar(\u0026o.KubeAPIServerClientSignerConfiguration.KeyFile, \"cluster-signing-kube-apiserver-client-key-file\", o.KubeAPIServerClientSignerConfiguration.KeyFile, \"Filename containing a PEM-encoded RSA or ECDSA private key used to sign certificates for the kubernetes.io/kube-apiserver-client signer. If specified, --cluster-signing-{cert,key}-file must not be set.\")\n\tfs.StringVar(\u0026o.LegacyUnknownSignerConfiguration.CertFile, \"cluster-signing-legacy-unknown-cert-file\", o.LegacyUnknownSignerConfiguration.CertFile, \"Filename containing a PEM-encoded X509 CA certificate used to issue certificates for the kubernetes.io/legacy-unknown signer. If specified, --cluster-signing-{cert,key}-file must not be set.\")\n\tfs.StringVar(\u0026o.LegacyUnknownSignerConfiguration.KeyFile, \"cluster-signing-legacy-unknown-key-file\", o.LegacyUnknownSignerConfiguration.KeyFile, \"Filename containing a PEM-encoded RSA or ECDSA private key used to sign certificates for the kubernetes.io/legacy-unknown signer. If specified, --cluster-signing-{cert,key}-file must not be set.\")\n\tfs.DurationVar(\u0026o.ClusterSigningDuration.Duration, \"cluster-signing-duration\", o.ClusterSigningDuration.Duration, \"The max length of duration signed certificates will be given. Individual CSRs may request shorter certs by setting spec.expirationSeconds.\")\n}","line":{"from":32,"to":49}} {"id":100000237,"name":"ApplyTo","signature":"func (o *CSRSigningControllerOptions) ApplyTo(cfg *csrsigningconfig.CSRSigningControllerConfiguration) error","file":"cmd/kube-controller-manager/app/options/csrsigningcontroller.go","code":"// ApplyTo fills up CSRSigningController config with options.\nfunc (o *CSRSigningControllerOptions) ApplyTo(cfg *csrsigningconfig.CSRSigningControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ClusterSigningCertFile = o.ClusterSigningCertFile\n\tcfg.ClusterSigningKeyFile = o.ClusterSigningKeyFile\n\tcfg.KubeletServingSignerConfiguration = o.KubeletServingSignerConfiguration\n\tcfg.KubeletClientSignerConfiguration = o.KubeletClientSignerConfiguration\n\tcfg.KubeAPIServerClientSignerConfiguration = o.KubeAPIServerClientSignerConfiguration\n\tcfg.LegacyUnknownSignerConfiguration = o.LegacyUnknownSignerConfiguration\n\tcfg.ClusterSigningDuration = o.ClusterSigningDuration\n\n\treturn nil\n}","line":{"from":51,"to":66}} {"id":100000238,"name":"Validate","signature":"func (o *CSRSigningControllerOptions) Validate() []error","file":"cmd/kube-controller-manager/app/options/csrsigningcontroller.go","code":"// Validate checks validation of CSRSigningControllerOptions.\nfunc (o *CSRSigningControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\tif err := csrSigningFilesValid(o.KubeletServingSignerConfiguration); err != nil {\n\t\terrs = append(errs, fmt.Errorf(\"%q: %v\", \"cluster-signing-kubelet-serving\", err))\n\t}\n\tif err := csrSigningFilesValid(o.KubeletClientSignerConfiguration); err != nil {\n\t\terrs = append(errs, fmt.Errorf(\"%q: %v\", \"cluster-signing-kube-apiserver-client\", err))\n\t}\n\tif err := csrSigningFilesValid(o.KubeAPIServerClientSignerConfiguration); err != nil {\n\t\terrs = append(errs, fmt.Errorf(\"%q: %v\", \"cluster-signing-kube-apiserver\", err))\n\t}\n\tif err := csrSigningFilesValid(o.LegacyUnknownSignerConfiguration); err != nil {\n\t\terrs = append(errs, fmt.Errorf(\"%q: %v\", \"cluster-signing-legacy-unknown\", err))\n\t}\n\n\tsingleSigningFile := len(o.ClusterSigningCertFile) \u003e 0 || len(o.ClusterSigningKeyFile) \u003e 0\n\tanySpecificFilesSet := len(o.KubeletServingSignerConfiguration.CertFile) \u003e 0 || len(o.KubeletServingSignerConfiguration.KeyFile) \u003e 0 ||\n\t\tlen(o.KubeletClientSignerConfiguration.CertFile) \u003e 0 || len(o.KubeletClientSignerConfiguration.KeyFile) \u003e 0 ||\n\t\tlen(o.KubeAPIServerClientSignerConfiguration.CertFile) \u003e 0 || len(o.KubeAPIServerClientSignerConfiguration.KeyFile) \u003e 0 ||\n\t\tlen(o.LegacyUnknownSignerConfiguration.CertFile) \u003e 0 || len(o.LegacyUnknownSignerConfiguration.KeyFile) \u003e 0\n\tif singleSigningFile \u0026\u0026 anySpecificFilesSet {\n\t\terrs = append(errs, fmt.Errorf(\"cannot specify --cluster-signing-{cert,key}-file and other --cluster-signing-*-file flags at the same time\"))\n\t}\n\n\treturn errs\n}","line":{"from":68,"to":98}} {"id":100000239,"name":"csrSigningFilesValid","signature":"func csrSigningFilesValid(config csrsigningconfig.CSRSigningConfiguration) error","file":"cmd/kube-controller-manager/app/options/csrsigningcontroller.go","code":"// both must be specified or both must be empty\nfunc csrSigningFilesValid(config csrsigningconfig.CSRSigningConfiguration) error {\n\tswitch {\n\tcase (len(config.CertFile) == 0) \u0026\u0026 (len(config.KeyFile) == 0):\n\t\treturn nil\n\tcase (len(config.CertFile) != 0) \u0026\u0026 (len(config.KeyFile) != 0):\n\t\treturn nil\n\tcase (len(config.CertFile) == 0) \u0026\u0026 (len(config.KeyFile) != 0):\n\t\treturn fmt.Errorf(\"cannot specify key without cert\")\n\tcase (len(config.CertFile) != 0) \u0026\u0026 (len(config.KeyFile) == 0):\n\t\treturn fmt.Errorf(\"cannot specify cert without key\")\n\t}\n\n\treturn fmt.Errorf(\"math broke\")\n}","line":{"from":100,"to":114}} {"id":100000240,"name":"AddFlags","signature":"func (o *DaemonSetControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"cmd/kube-controller-manager/app/options/daemonsetcontroller.go","code":"// AddFlags adds flags related to DaemonSetController for controller manager to the specified FlagSet.\nfunc (o *DaemonSetControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n}","line":{"from":30,"to":35}} {"id":100000241,"name":"ApplyTo","signature":"func (o *DaemonSetControllerOptions) ApplyTo(cfg *daemonconfig.DaemonSetControllerConfiguration) error","file":"cmd/kube-controller-manager/app/options/daemonsetcontroller.go","code":"// ApplyTo fills up DaemonSetController config with options.\nfunc (o *DaemonSetControllerOptions) ApplyTo(cfg *daemonconfig.DaemonSetControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ConcurrentDaemonSetSyncs = o.ConcurrentDaemonSetSyncs\n\n\treturn nil\n}","line":{"from":37,"to":46}} {"id":100000242,"name":"Validate","signature":"func (o *DaemonSetControllerOptions) Validate() []error","file":"cmd/kube-controller-manager/app/options/daemonsetcontroller.go","code":"// Validate checks validation of DaemonSetControllerOptions.\nfunc (o *DaemonSetControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\treturn errs\n}","line":{"from":48,"to":56}} {"id":100000243,"name":"AddFlags","signature":"func (o *DeploymentControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"cmd/kube-controller-manager/app/options/deploymentcontroller.go","code":"// AddFlags adds flags related to DeploymentController for controller manager to the specified FlagSet.\nfunc (o *DeploymentControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.Int32Var(\u0026o.ConcurrentDeploymentSyncs, \"concurrent-deployment-syncs\", o.ConcurrentDeploymentSyncs, \"The number of deployment objects that are allowed to sync concurrently. Larger number = more responsive deployments, but more CPU (and network) load\")\n}","line":{"from":30,"to":37}} {"id":100000244,"name":"ApplyTo","signature":"func (o *DeploymentControllerOptions) ApplyTo(cfg *deploymentconfig.DeploymentControllerConfiguration) error","file":"cmd/kube-controller-manager/app/options/deploymentcontroller.go","code":"// ApplyTo fills up DeploymentController config with options.\nfunc (o *DeploymentControllerOptions) ApplyTo(cfg *deploymentconfig.DeploymentControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ConcurrentDeploymentSyncs = o.ConcurrentDeploymentSyncs\n\n\treturn nil\n}","line":{"from":39,"to":48}} {"id":100000245,"name":"Validate","signature":"func (o *DeploymentControllerOptions) Validate() []error","file":"cmd/kube-controller-manager/app/options/deploymentcontroller.go","code":"// Validate checks validation of DeploymentControllerOptions.\nfunc (o *DeploymentControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\treturn errs\n}","line":{"from":50,"to":58}} {"id":100000246,"name":"AddFlags","signature":"func (o *DeprecatedControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"cmd/kube-controller-manager/app/options/deprecatedcontroller.go","code":"// AddFlags adds flags related to DeprecatedController for controller manager to the specified FlagSet.\nfunc (o *DeprecatedControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n}","line":{"from":31,"to":36}} {"id":100000247,"name":"ApplyTo","signature":"func (o *DeprecatedControllerOptions) ApplyTo(cfg *kubectrlmgrconfig.DeprecatedControllerConfiguration) error","file":"cmd/kube-controller-manager/app/options/deprecatedcontroller.go","code":"// ApplyTo fills up DeprecatedController config with options.\nfunc (o *DeprecatedControllerOptions) ApplyTo(cfg *kubectrlmgrconfig.DeprecatedControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\treturn nil\n}","line":{"from":38,"to":45}} {"id":100000248,"name":"Validate","signature":"func (o *DeprecatedControllerOptions) Validate() []error","file":"cmd/kube-controller-manager/app/options/deprecatedcontroller.go","code":"// Validate checks validation of DeprecatedControllerOptions.\nfunc (o *DeprecatedControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\treturn errs\n}","line":{"from":47,"to":55}} {"id":100000249,"name":"AddFlags","signature":"func (o *EndpointControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"cmd/kube-controller-manager/app/options/endpointcontroller.go","code":"// AddFlags adds flags related to EndPointController for controller manager to the specified FlagSet.\nfunc (o *EndpointControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.Int32Var(\u0026o.ConcurrentEndpointSyncs, \"concurrent-endpoint-syncs\", o.ConcurrentEndpointSyncs, \"The number of endpoint syncing operations that will be done concurrently. Larger number = faster endpoint updating, but more CPU (and network) load\")\n\tfs.DurationVar(\u0026o.EndpointUpdatesBatchPeriod.Duration, \"endpoint-updates-batch-period\", o.EndpointUpdatesBatchPeriod.Duration, \"The length of endpoint updates batching period. Processing of pod changes will be delayed by this duration to join them with potential upcoming updates and reduce the overall number of endpoints updates. Larger number = higher endpoint programming latency, but lower number of endpoints revision generated\")\n}","line":{"from":30,"to":38}} {"id":100000250,"name":"ApplyTo","signature":"func (o *EndpointControllerOptions) ApplyTo(cfg *endpointconfig.EndpointControllerConfiguration) error","file":"cmd/kube-controller-manager/app/options/endpointcontroller.go","code":"// ApplyTo fills up EndPointController config with options.\nfunc (o *EndpointControllerOptions) ApplyTo(cfg *endpointconfig.EndpointControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ConcurrentEndpointSyncs = o.ConcurrentEndpointSyncs\n\tcfg.EndpointUpdatesBatchPeriod = o.EndpointUpdatesBatchPeriod\n\n\treturn nil\n}","line":{"from":40,"to":50}} {"id":100000251,"name":"Validate","signature":"func (o *EndpointControllerOptions) Validate() []error","file":"cmd/kube-controller-manager/app/options/endpointcontroller.go","code":"// Validate checks validation of EndpointControllerOptions.\nfunc (o *EndpointControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\treturn errs\n}","line":{"from":52,"to":60}} {"id":100000252,"name":"AddFlags","signature":"func (o *EndpointSliceControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"cmd/kube-controller-manager/app/options/endpointslicecontroller.go","code":"// AddFlags adds flags related to EndpointSliceController for controller manager to the specified FlagSet.\nfunc (o *EndpointSliceControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.Int32Var(\u0026o.ConcurrentServiceEndpointSyncs, \"concurrent-service-endpoint-syncs\", o.ConcurrentServiceEndpointSyncs, \"The number of service endpoint syncing operations that will be done concurrently. Larger number = faster endpoint slice updating, but more CPU (and network) load. Defaults to 5.\")\n\tfs.Int32Var(\u0026o.MaxEndpointsPerSlice, \"max-endpoints-per-slice\", o.MaxEndpointsPerSlice, \"The maximum number of endpoints that will be added to an EndpointSlice. More endpoints per slice will result in less endpoint slices, but larger resources. Defaults to 100.\")\n\tfs.DurationVar(\u0026o.EndpointUpdatesBatchPeriod.Duration, \"endpointslice-updates-batch-period\", o.EndpointUpdatesBatchPeriod.Duration, \"The length of endpoint slice updates batching period. Processing of pod changes will be delayed by this duration to join them with potential upcoming updates and reduce the overall number of endpoints updates. Larger number = higher endpoint programming latency, but lower number of endpoints revision generated\")\n}","line":{"from":39,"to":48}} {"id":100000253,"name":"ApplyTo","signature":"func (o *EndpointSliceControllerOptions) ApplyTo(cfg *endpointsliceconfig.EndpointSliceControllerConfiguration) error","file":"cmd/kube-controller-manager/app/options/endpointslicecontroller.go","code":"// ApplyTo fills up EndpointSliceController config with options.\nfunc (o *EndpointSliceControllerOptions) ApplyTo(cfg *endpointsliceconfig.EndpointSliceControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ConcurrentServiceEndpointSyncs = o.ConcurrentServiceEndpointSyncs\n\tcfg.MaxEndpointsPerSlice = o.MaxEndpointsPerSlice\n\tcfg.EndpointUpdatesBatchPeriod = o.EndpointUpdatesBatchPeriod\n\n\treturn nil\n}","line":{"from":50,"to":61}} {"id":100000254,"name":"Validate","signature":"func (o *EndpointSliceControllerOptions) Validate() []error","file":"cmd/kube-controller-manager/app/options/endpointslicecontroller.go","code":"// Validate checks validation of EndpointSliceControllerOptions.\nfunc (o *EndpointSliceControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\n\tif o.ConcurrentServiceEndpointSyncs \u003c minConcurrentServiceEndpointSyncs {\n\t\terrs = append(errs, fmt.Errorf(\"concurrent-service-endpoint-syncs must not be less than %d, but got %d\", minConcurrentServiceEndpointSyncs, o.ConcurrentServiceEndpointSyncs))\n\t} else if o.ConcurrentServiceEndpointSyncs \u003e maxConcurrentServiceEndpointSyncs {\n\t\terrs = append(errs, fmt.Errorf(\"concurrent-service-endpoint-syncs must not be more than %d, but got %d\", maxConcurrentServiceEndpointSyncs, o.ConcurrentServiceEndpointSyncs))\n\t}\n\n\tif o.MaxEndpointsPerSlice \u003c minMaxEndpointsPerSlice {\n\t\terrs = append(errs, fmt.Errorf(\"max-endpoints-per-slice must not be less than %d, but got %d\", minMaxEndpointsPerSlice, o.MaxEndpointsPerSlice))\n\t} else if o.MaxEndpointsPerSlice \u003e maxMaxEndpointsPerSlice {\n\t\terrs = append(errs, fmt.Errorf(\"max-endpoints-per-slice must not be more than %d, but got %d\", maxMaxEndpointsPerSlice, o.MaxEndpointsPerSlice))\n\t}\n\n\treturn errs\n}","line":{"from":63,"to":84}} {"id":100000255,"name":"AddFlags","signature":"func (o *EndpointSliceMirroringControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"cmd/kube-controller-manager/app/options/endpointslicemirroringcontroller.go","code":"// AddFlags adds flags related to EndpointSliceMirroringController for\n// controller manager to the specified FlagSet.\nfunc (o *EndpointSliceMirroringControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.Int32Var(\u0026o.MirroringConcurrentServiceEndpointSyncs, \"mirroring-concurrent-service-endpoint-syncs\", o.MirroringConcurrentServiceEndpointSyncs, \"The number of service endpoint syncing operations that will be done concurrently by the EndpointSliceMirroring controller. Larger number = faster endpoint slice updating, but more CPU (and network) load. Defaults to 5.\")\n\tfs.Int32Var(\u0026o.MirroringMaxEndpointsPerSubset, \"mirroring-max-endpoints-per-subset\", o.MirroringMaxEndpointsPerSubset, \"The maximum number of endpoints that will be added to an EndpointSlice by the EndpointSliceMirroring controller. More endpoints per slice will result in less endpoint slices, but larger resources. Defaults to 100.\")\n\tfs.DurationVar(\u0026o.MirroringEndpointUpdatesBatchPeriod.Duration, \"mirroring-endpointslice-updates-batch-period\", o.MirroringEndpointUpdatesBatchPeriod.Duration, \"The length of EndpointSlice updates batching period for EndpointSliceMirroring controller. Processing of EndpointSlice changes will be delayed by this duration to join them with potential upcoming updates and reduce the overall number of EndpointSlice updates. Larger number = higher endpoint programming latency, but lower number of endpoints revision generated\")\n}","line":{"from":40,"to":50}} {"id":100000256,"name":"ApplyTo","signature":"func (o *EndpointSliceMirroringControllerOptions) ApplyTo(cfg *endpointslicemirroringconfig.EndpointSliceMirroringControllerConfiguration) error","file":"cmd/kube-controller-manager/app/options/endpointslicemirroringcontroller.go","code":"// ApplyTo fills up EndpointSliceMirroringController config with options.\nfunc (o *EndpointSliceMirroringControllerOptions) ApplyTo(cfg *endpointslicemirroringconfig.EndpointSliceMirroringControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.MirroringConcurrentServiceEndpointSyncs = o.MirroringConcurrentServiceEndpointSyncs\n\tcfg.MirroringMaxEndpointsPerSubset = o.MirroringMaxEndpointsPerSubset\n\tcfg.MirroringEndpointUpdatesBatchPeriod = o.MirroringEndpointUpdatesBatchPeriod\n\n\treturn nil\n}","line":{"from":52,"to":63}} {"id":100000257,"name":"Validate","signature":"func (o *EndpointSliceMirroringControllerOptions) Validate() []error","file":"cmd/kube-controller-manager/app/options/endpointslicemirroringcontroller.go","code":"// Validate checks validation of EndpointSliceMirroringControllerOptions.\nfunc (o *EndpointSliceMirroringControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\n\tif o.MirroringConcurrentServiceEndpointSyncs \u003c mirroringMinConcurrentServiceEndpointSyncs {\n\t\terrs = append(errs, fmt.Errorf(\"mirroring-concurrent-service-endpoint-syncs must not be less than %d, but got %d\", mirroringMinConcurrentServiceEndpointSyncs, o.MirroringConcurrentServiceEndpointSyncs))\n\t} else if o.MirroringConcurrentServiceEndpointSyncs \u003e mirroringMaxConcurrentServiceEndpointSyncs {\n\t\terrs = append(errs, fmt.Errorf(\"mirroring-concurrent-service-endpoint-syncs must not be more than %d, but got %d\", mirroringMaxConcurrentServiceEndpointSyncs, o.MirroringConcurrentServiceEndpointSyncs))\n\t}\n\n\tif o.MirroringMaxEndpointsPerSubset \u003c mirroringMinMaxEndpointsPerSubset {\n\t\terrs = append(errs, fmt.Errorf(\"mirroring-max-endpoints-per-subset must not be less than %d, but got %d\", mirroringMinMaxEndpointsPerSubset, o.MirroringMaxEndpointsPerSubset))\n\t} else if o.MirroringMaxEndpointsPerSubset \u003e mirroringMaxMaxEndpointsPerSubset {\n\t\terrs = append(errs, fmt.Errorf(\"mirroring-max-endpoints-per-subset must not be more than %d, but got %d\", mirroringMaxMaxEndpointsPerSubset, o.MirroringMaxEndpointsPerSubset))\n\t}\n\n\treturn errs\n}","line":{"from":65,"to":86}} {"id":100000258,"name":"AddFlags","signature":"func (o *EphemeralVolumeControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"cmd/kube-controller-manager/app/options/ephemeralcontroller.go","code":"// AddFlags adds flags related to EphemeralVolumeController for controller manager to the specified FlagSet.\nfunc (o *EphemeralVolumeControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.Int32Var(\u0026o.ConcurrentEphemeralVolumeSyncs, \"concurrent-ephemeralvolume-syncs\", o.ConcurrentEphemeralVolumeSyncs, \"The number of ephemeral volume syncing operations that will be done concurrently. Larger number = faster ephemeral volume updating, but more CPU (and network) load\")\n}","line":{"from":32,"to":39}} {"id":100000259,"name":"ApplyTo","signature":"func (o *EphemeralVolumeControllerOptions) ApplyTo(cfg *ephemeralvolumeconfig.EphemeralVolumeControllerConfiguration) error","file":"cmd/kube-controller-manager/app/options/ephemeralcontroller.go","code":"// ApplyTo fills up EphemeralVolumeController config with options.\nfunc (o *EphemeralVolumeControllerOptions) ApplyTo(cfg *ephemeralvolumeconfig.EphemeralVolumeControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ConcurrentEphemeralVolumeSyncs = o.ConcurrentEphemeralVolumeSyncs\n\n\treturn nil\n}","line":{"from":41,"to":50}} {"id":100000260,"name":"Validate","signature":"func (o *EphemeralVolumeControllerOptions) Validate() []error","file":"cmd/kube-controller-manager/app/options/ephemeralcontroller.go","code":"// Validate checks validation of EphemeralVolumeControllerOptions.\nfunc (o *EphemeralVolumeControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\tif o.ConcurrentEphemeralVolumeSyncs \u003c 1 {\n\t\terrs = append(errs, fmt.Errorf(\"concurrent-ephemeralvolume-syncs must be greater than 0, but got %d\", o.ConcurrentEphemeralVolumeSyncs))\n\t}\n\treturn errs\n}","line":{"from":52,"to":63}} {"id":100000261,"name":"AddFlags","signature":"func (o *GarbageCollectorControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"cmd/kube-controller-manager/app/options/garbagecollectorcontroller.go","code":"// AddFlags adds flags related to GarbageCollectorController for controller manager to the specified FlagSet.\nfunc (o *GarbageCollectorControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.Int32Var(\u0026o.ConcurrentGCSyncs, \"concurrent-gc-syncs\", o.ConcurrentGCSyncs, \"The number of garbage collector workers that are allowed to sync concurrently.\")\n\tfs.BoolVar(\u0026o.EnableGarbageCollector, \"enable-garbage-collector\", o.EnableGarbageCollector, \"Enables the generic garbage collector. MUST be synced with the corresponding flag of the kube-apiserver.\")\n}","line":{"from":30,"to":38}} {"id":100000262,"name":"ApplyTo","signature":"func (o *GarbageCollectorControllerOptions) ApplyTo(cfg *garbagecollectorconfig.GarbageCollectorControllerConfiguration) error","file":"cmd/kube-controller-manager/app/options/garbagecollectorcontroller.go","code":"// ApplyTo fills up GarbageCollectorController config with options.\nfunc (o *GarbageCollectorControllerOptions) ApplyTo(cfg *garbagecollectorconfig.GarbageCollectorControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ConcurrentGCSyncs = o.ConcurrentGCSyncs\n\tcfg.GCIgnoredResources = o.GCIgnoredResources\n\tcfg.EnableGarbageCollector = o.EnableGarbageCollector\n\n\treturn nil\n}","line":{"from":40,"to":51}} {"id":100000263,"name":"Validate","signature":"func (o *GarbageCollectorControllerOptions) Validate() []error","file":"cmd/kube-controller-manager/app/options/garbagecollectorcontroller.go","code":"// Validate checks validation of GarbageCollectorController.\nfunc (o *GarbageCollectorControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\treturn errs\n}","line":{"from":53,"to":61}} {"id":100000264,"name":"AddFlags","signature":"func (o *HPAControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"cmd/kube-controller-manager/app/options/hpacontroller.go","code":"// AddFlags adds flags related to HPAController for controller manager to the specified FlagSet.\nfunc (o *HPAControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.Int32Var(\u0026o.ConcurrentHorizontalPodAutoscalerSyncs, \"concurrent-horizontal-pod-autoscaler-syncs\", o.ConcurrentHorizontalPodAutoscalerSyncs, \"The number of horizontal pod autoscaler objects that are allowed to sync concurrently. Larger number = more responsive horizontal pod autoscaler objects processing, but more CPU (and network) load.\")\n\tfs.DurationVar(\u0026o.HorizontalPodAutoscalerSyncPeriod.Duration, \"horizontal-pod-autoscaler-sync-period\", o.HorizontalPodAutoscalerSyncPeriod.Duration, \"The period for syncing the number of pods in horizontal pod autoscaler.\")\n\tfs.DurationVar(\u0026o.HorizontalPodAutoscalerUpscaleForbiddenWindow.Duration, \"horizontal-pod-autoscaler-upscale-delay\", o.HorizontalPodAutoscalerUpscaleForbiddenWindow.Duration, \"The period since last upscale, before another upscale can be performed in horizontal pod autoscaler.\")\n\tfs.MarkDeprecated(\"horizontal-pod-autoscaler-upscale-delay\", \"This flag is currently no-op and will be deleted.\")\n\tfs.DurationVar(\u0026o.HorizontalPodAutoscalerDownscaleStabilizationWindow.Duration, \"horizontal-pod-autoscaler-downscale-stabilization\", o.HorizontalPodAutoscalerDownscaleStabilizationWindow.Duration, \"The period for which autoscaler will look backwards and not scale down below any recommendation it made during that period.\")\n\tfs.DurationVar(\u0026o.HorizontalPodAutoscalerDownscaleForbiddenWindow.Duration, \"horizontal-pod-autoscaler-downscale-delay\", o.HorizontalPodAutoscalerDownscaleForbiddenWindow.Duration, \"The period since last downscale, before another downscale can be performed in horizontal pod autoscaler.\")\n\tfs.MarkDeprecated(\"horizontal-pod-autoscaler-downscale-delay\", \"This flag is currently no-op and will be deleted.\")\n\tfs.Float64Var(\u0026o.HorizontalPodAutoscalerTolerance, \"horizontal-pod-autoscaler-tolerance\", o.HorizontalPodAutoscalerTolerance, \"The minimum change (from 1.0) in the desired-to-actual metrics ratio for the horizontal pod autoscaler to consider scaling.\")\n\tfs.DurationVar(\u0026o.HorizontalPodAutoscalerCPUInitializationPeriod.Duration, \"horizontal-pod-autoscaler-cpu-initialization-period\", o.HorizontalPodAutoscalerCPUInitializationPeriod.Duration, \"The period after pod start when CPU samples might be skipped.\")\n\tfs.DurationVar(\u0026o.HorizontalPodAutoscalerInitialReadinessDelay.Duration, \"horizontal-pod-autoscaler-initial-readiness-delay\", o.HorizontalPodAutoscalerInitialReadinessDelay.Duration, \"The period after pod start during which readiness changes will be treated as initial readiness.\")\n}","line":{"from":32,"to":48}} {"id":100000265,"name":"ApplyTo","signature":"func (o *HPAControllerOptions) ApplyTo(cfg *poautosclerconfig.HPAControllerConfiguration) error","file":"cmd/kube-controller-manager/app/options/hpacontroller.go","code":"// ApplyTo fills up HPAController config with options.\nfunc (o *HPAControllerOptions) ApplyTo(cfg *poautosclerconfig.HPAControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ConcurrentHorizontalPodAutoscalerSyncs = o.ConcurrentHorizontalPodAutoscalerSyncs\n\tcfg.HorizontalPodAutoscalerSyncPeriod = o.HorizontalPodAutoscalerSyncPeriod\n\tcfg.HorizontalPodAutoscalerDownscaleStabilizationWindow = o.HorizontalPodAutoscalerDownscaleStabilizationWindow\n\tcfg.HorizontalPodAutoscalerTolerance = o.HorizontalPodAutoscalerTolerance\n\tcfg.HorizontalPodAutoscalerCPUInitializationPeriod = o.HorizontalPodAutoscalerCPUInitializationPeriod\n\tcfg.HorizontalPodAutoscalerInitialReadinessDelay = o.HorizontalPodAutoscalerInitialReadinessDelay\n\tcfg.HorizontalPodAutoscalerUpscaleForbiddenWindow = o.HorizontalPodAutoscalerUpscaleForbiddenWindow\n\tcfg.HorizontalPodAutoscalerDownscaleForbiddenWindow = o.HorizontalPodAutoscalerDownscaleForbiddenWindow\n\n\treturn nil\n}","line":{"from":50,"to":66}} {"id":100000266,"name":"Validate","signature":"func (o *HPAControllerOptions) Validate() []error","file":"cmd/kube-controller-manager/app/options/hpacontroller.go","code":"// Validate checks validation of HPAControllerOptions.\nfunc (o *HPAControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\tif o.ConcurrentHorizontalPodAutoscalerSyncs \u003c 1 {\n\t\terrs = append(errs, fmt.Errorf(\"concurrent-horizontal-pod-autoscaler-syncs must be greater than 0, but got %d\", o.ConcurrentHorizontalPodAutoscalerSyncs))\n\t}\n\treturn errs\n}","line":{"from":68,"to":79}} {"id":100000267,"name":"AddFlags","signature":"func (o *JobControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"cmd/kube-controller-manager/app/options/jobcontroller.go","code":"// AddFlags adds flags related to JobController for controller manager to the specified FlagSet.\nfunc (o *JobControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n}","line":{"from":30,"to":35}} {"id":100000268,"name":"ApplyTo","signature":"func (o *JobControllerOptions) ApplyTo(cfg *jobconfig.JobControllerConfiguration) error","file":"cmd/kube-controller-manager/app/options/jobcontroller.go","code":"// ApplyTo fills up JobController config with options.\nfunc (o *JobControllerOptions) ApplyTo(cfg *jobconfig.JobControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ConcurrentJobSyncs = o.ConcurrentJobSyncs\n\n\treturn nil\n}","line":{"from":37,"to":46}} {"id":100000269,"name":"Validate","signature":"func (o *JobControllerOptions) Validate() []error","file":"cmd/kube-controller-manager/app/options/jobcontroller.go","code":"// Validate checks validation of JobControllerOptions.\nfunc (o *JobControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\treturn errs\n}","line":{"from":48,"to":56}} {"id":100000270,"name":"AddFlags","signature":"func (o *NamespaceControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"cmd/kube-controller-manager/app/options/namespacecontroller.go","code":"// AddFlags adds flags related to NamespaceController for controller manager to the specified FlagSet.\nfunc (o *NamespaceControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.DurationVar(\u0026o.NamespaceSyncPeriod.Duration, \"namespace-sync-period\", o.NamespaceSyncPeriod.Duration, \"The period for syncing namespace life-cycle updates\")\n\tfs.Int32Var(\u0026o.ConcurrentNamespaceSyncs, \"concurrent-namespace-syncs\", o.ConcurrentNamespaceSyncs, \"The number of namespace objects that are allowed to sync concurrently. Larger number = more responsive namespace termination, but more CPU (and network) load\")\n}","line":{"from":30,"to":38}} {"id":100000271,"name":"ApplyTo","signature":"func (o *NamespaceControllerOptions) ApplyTo(cfg *namespaceconfig.NamespaceControllerConfiguration) error","file":"cmd/kube-controller-manager/app/options/namespacecontroller.go","code":"// ApplyTo fills up NamespaceController config with options.\nfunc (o *NamespaceControllerOptions) ApplyTo(cfg *namespaceconfig.NamespaceControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.NamespaceSyncPeriod = o.NamespaceSyncPeriod\n\tcfg.ConcurrentNamespaceSyncs = o.ConcurrentNamespaceSyncs\n\n\treturn nil\n}","line":{"from":40,"to":50}} {"id":100000272,"name":"Validate","signature":"func (o *NamespaceControllerOptions) Validate() []error","file":"cmd/kube-controller-manager/app/options/namespacecontroller.go","code":"// Validate checks validation of NamespaceControllerOptions.\nfunc (o *NamespaceControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\treturn errs\n}","line":{"from":52,"to":60}} {"id":100000273,"name":"AddFlags","signature":"func (o *NodeIPAMControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"cmd/kube-controller-manager/app/options/nodeipamcontroller.go","code":"// AddFlags adds flags related to NodeIpamController for controller manager to the specified FlagSet.\nfunc (o *NodeIPAMControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\tfs.StringVar(\u0026o.ServiceCIDR, \"service-cluster-ip-range\", o.ServiceCIDR, \"CIDR Range for Services in cluster. Requires --allocate-node-cidrs to be true\")\n\tfs.Int32Var(\u0026o.NodeCIDRMaskSize, \"node-cidr-mask-size\", o.NodeCIDRMaskSize, \"Mask size for node cidr in cluster. Default is 24 for IPv4 and 64 for IPv6.\")\n\tfs.Int32Var(\u0026o.NodeCIDRMaskSizeIPv4, \"node-cidr-mask-size-ipv4\", o.NodeCIDRMaskSizeIPv4, \"Mask size for IPv4 node cidr in dual-stack cluster. Default is 24.\")\n\tfs.Int32Var(\u0026o.NodeCIDRMaskSizeIPv6, \"node-cidr-mask-size-ipv6\", o.NodeCIDRMaskSizeIPv6, \"Mask size for IPv6 node cidr in dual-stack cluster. Default is 64.\")\n}","line":{"from":33,"to":42}} {"id":100000274,"name":"ApplyTo","signature":"func (o *NodeIPAMControllerOptions) ApplyTo(cfg *nodeipamconfig.NodeIPAMControllerConfiguration) error","file":"cmd/kube-controller-manager/app/options/nodeipamcontroller.go","code":"// ApplyTo fills up NodeIpamController config with options.\nfunc (o *NodeIPAMControllerOptions) ApplyTo(cfg *nodeipamconfig.NodeIPAMControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\t// split the cidrs list and assign primary and secondary\n\tserviceCIDRList := strings.Split(o.ServiceCIDR, \",\")\n\tif len(serviceCIDRList) \u003e 0 {\n\t\tcfg.ServiceCIDR = serviceCIDRList[0]\n\t}\n\tif len(serviceCIDRList) \u003e 1 {\n\t\tcfg.SecondaryServiceCIDR = serviceCIDRList[1]\n\t}\n\n\tcfg.NodeCIDRMaskSize = o.NodeCIDRMaskSize\n\tcfg.NodeCIDRMaskSizeIPv4 = o.NodeCIDRMaskSizeIPv4\n\tcfg.NodeCIDRMaskSizeIPv6 = o.NodeCIDRMaskSizeIPv6\n\n\treturn nil\n}","line":{"from":44,"to":64}} {"id":100000275,"name":"Validate","signature":"func (o *NodeIPAMControllerOptions) Validate() []error","file":"cmd/kube-controller-manager/app/options/nodeipamcontroller.go","code":"// Validate checks validation of NodeIPAMControllerOptions.\nfunc (o *NodeIPAMControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\terrs := make([]error, 0)\n\n\tserviceCIDRList := strings.Split(o.ServiceCIDR, \",\")\n\tif len(serviceCIDRList) \u003e 2 {\n\t\terrs = append(errs, fmt.Errorf(\"--service-cluster-ip-range can not contain more than two entries\"))\n\t}\n\n\treturn errs\n}","line":{"from":66,"to":79}} {"id":100000276,"name":"AddFlags","signature":"func (o *NodeLifecycleControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"cmd/kube-controller-manager/app/options/nodelifecyclecontroller.go","code":"// AddFlags adds flags related to NodeLifecycleController for controller manager to the specified FlagSet.\nfunc (o *NodeLifecycleControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.DurationVar(\u0026o.NodeStartupGracePeriod.Duration, \"node-startup-grace-period\", o.NodeStartupGracePeriod.Duration,\n\t\t\"Amount of time which we allow starting Node to be unresponsive before marking it unhealthy.\")\n\tfs.DurationVar(\u0026o.NodeMonitorGracePeriod.Duration, \"node-monitor-grace-period\", o.NodeMonitorGracePeriod.Duration,\n\t\t\"Amount of time which we allow running Node to be unresponsive before marking it unhealthy. \"+\n\t\t\t\"Must be N times more than kubelet's nodeStatusUpdateFrequency, \"+\n\t\t\t\"where N means number of retries allowed for kubelet to post node status.\")\n\tfs.Float32Var(\u0026o.NodeEvictionRate, \"node-eviction-rate\", 0.1, \"Number of nodes per second on which pods are deleted in case of node failure when a zone is healthy (see --unhealthy-zone-threshold for definition of healthy/unhealthy). Zone refers to entire cluster in non-multizone clusters.\")\n\tfs.Float32Var(\u0026o.SecondaryNodeEvictionRate, \"secondary-node-eviction-rate\", 0.01, \"Number of nodes per second on which pods are deleted in case of node failure when a zone is unhealthy (see --unhealthy-zone-threshold for definition of healthy/unhealthy). Zone refers to entire cluster in non-multizone clusters. This value is implicitly overridden to 0 if the cluster size is smaller than --large-cluster-size-threshold.\")\n\tfs.Int32Var(\u0026o.LargeClusterSizeThreshold, \"large-cluster-size-threshold\", 50, \"Number of nodes from which NodeController treats the cluster as large for the eviction logic purposes. --secondary-node-eviction-rate is implicitly overridden to 0 for clusters this size or smaller.\")\n\tfs.Float32Var(\u0026o.UnhealthyZoneThreshold, \"unhealthy-zone-threshold\", 0.55, \"Fraction of Nodes in a zone which needs to be not Ready (minimum 3) for zone to be treated as unhealthy. \")\n}","line":{"from":30,"to":46}} {"id":100000277,"name":"ApplyTo","signature":"func (o *NodeLifecycleControllerOptions) ApplyTo(cfg *nodelifecycleconfig.NodeLifecycleControllerConfiguration) error","file":"cmd/kube-controller-manager/app/options/nodelifecyclecontroller.go","code":"// ApplyTo fills up NodeLifecycleController config with options.\nfunc (o *NodeLifecycleControllerOptions) ApplyTo(cfg *nodelifecycleconfig.NodeLifecycleControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.NodeStartupGracePeriod = o.NodeStartupGracePeriod\n\tcfg.NodeMonitorGracePeriod = o.NodeMonitorGracePeriod\n\tcfg.NodeEvictionRate = o.NodeEvictionRate\n\tcfg.SecondaryNodeEvictionRate = o.SecondaryNodeEvictionRate\n\tcfg.LargeClusterSizeThreshold = o.LargeClusterSizeThreshold\n\tcfg.UnhealthyZoneThreshold = o.UnhealthyZoneThreshold\n\n\treturn nil\n}","line":{"from":48,"to":62}} {"id":100000278,"name":"Validate","signature":"func (o *NodeLifecycleControllerOptions) Validate() []error","file":"cmd/kube-controller-manager/app/options/nodelifecyclecontroller.go","code":"// Validate checks validation of NodeLifecycleControllerOptions.\nfunc (o *NodeLifecycleControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\treturn errs\n}","line":{"from":64,"to":72}} {"id":100000279,"name":"NewKubeControllerManagerOptions","signature":"func NewKubeControllerManagerOptions() (*KubeControllerManagerOptions, error)","file":"cmd/kube-controller-manager/app/options/options.go","code":"// NewKubeControllerManagerOptions creates a new KubeControllerManagerOptions with a default config.\nfunc NewKubeControllerManagerOptions() (*KubeControllerManagerOptions, error) {\n\tcomponentConfig, err := NewDefaultComponentConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts := KubeControllerManagerOptions{\n\t\tGeneric: cmoptions.NewGenericControllerManagerConfigurationOptions(\u0026componentConfig.Generic),\n\t\tKubeCloudShared: cpoptions.NewKubeCloudSharedOptions(\u0026componentConfig.KubeCloudShared),\n\t\tServiceController: \u0026cpoptions.ServiceControllerOptions{\n\t\t\tServiceControllerConfiguration: \u0026componentConfig.ServiceController,\n\t\t},\n\t\tAttachDetachController: \u0026AttachDetachControllerOptions{\n\t\t\t\u0026componentConfig.AttachDetachController,\n\t\t},\n\t\tCSRSigningController: \u0026CSRSigningControllerOptions{\n\t\t\t\u0026componentConfig.CSRSigningController,\n\t\t},\n\t\tDaemonSetController: \u0026DaemonSetControllerOptions{\n\t\t\t\u0026componentConfig.DaemonSetController,\n\t\t},\n\t\tDeploymentController: \u0026DeploymentControllerOptions{\n\t\t\t\u0026componentConfig.DeploymentController,\n\t\t},\n\t\tStatefulSetController: \u0026StatefulSetControllerOptions{\n\t\t\t\u0026componentConfig.StatefulSetController,\n\t\t},\n\t\tDeprecatedFlags: \u0026DeprecatedControllerOptions{\n\t\t\t\u0026componentConfig.DeprecatedController,\n\t\t},\n\t\tEndpointController: \u0026EndpointControllerOptions{\n\t\t\t\u0026componentConfig.EndpointController,\n\t\t},\n\t\tEndpointSliceController: \u0026EndpointSliceControllerOptions{\n\t\t\t\u0026componentConfig.EndpointSliceController,\n\t\t},\n\t\tEndpointSliceMirroringController: \u0026EndpointSliceMirroringControllerOptions{\n\t\t\t\u0026componentConfig.EndpointSliceMirroringController,\n\t\t},\n\t\tEphemeralVolumeController: \u0026EphemeralVolumeControllerOptions{\n\t\t\t\u0026componentConfig.EphemeralVolumeController,\n\t\t},\n\t\tGarbageCollectorController: \u0026GarbageCollectorControllerOptions{\n\t\t\t\u0026componentConfig.GarbageCollectorController,\n\t\t},\n\t\tHPAController: \u0026HPAControllerOptions{\n\t\t\t\u0026componentConfig.HPAController,\n\t\t},\n\t\tJobController: \u0026JobControllerOptions{\n\t\t\t\u0026componentConfig.JobController,\n\t\t},\n\t\tCronJobController: \u0026CronJobControllerOptions{\n\t\t\t\u0026componentConfig.CronJobController,\n\t\t},\n\t\tNamespaceController: \u0026NamespaceControllerOptions{\n\t\t\t\u0026componentConfig.NamespaceController,\n\t\t},\n\t\tNodeIPAMController: \u0026NodeIPAMControllerOptions{\n\t\t\t\u0026componentConfig.NodeIPAMController,\n\t\t},\n\t\tNodeLifecycleController: \u0026NodeLifecycleControllerOptions{\n\t\t\t\u0026componentConfig.NodeLifecycleController,\n\t\t},\n\t\tPersistentVolumeBinderController: \u0026PersistentVolumeBinderControllerOptions{\n\t\t\t\u0026componentConfig.PersistentVolumeBinderController,\n\t\t},\n\t\tPodGCController: \u0026PodGCControllerOptions{\n\t\t\t\u0026componentConfig.PodGCController,\n\t\t},\n\t\tReplicaSetController: \u0026ReplicaSetControllerOptions{\n\t\t\t\u0026componentConfig.ReplicaSetController,\n\t\t},\n\t\tReplicationController: \u0026ReplicationControllerOptions{\n\t\t\t\u0026componentConfig.ReplicationController,\n\t\t},\n\t\tResourceQuotaController: \u0026ResourceQuotaControllerOptions{\n\t\t\t\u0026componentConfig.ResourceQuotaController,\n\t\t},\n\t\tSAController: \u0026SAControllerOptions{\n\t\t\t\u0026componentConfig.SAController,\n\t\t},\n\t\tTTLAfterFinishedController: \u0026TTLAfterFinishedControllerOptions{\n\t\t\t\u0026componentConfig.TTLAfterFinishedController,\n\t\t},\n\t\tSecureServing: apiserveroptions.NewSecureServingOptions().WithLoopback(),\n\t\tAuthentication: apiserveroptions.NewDelegatingAuthenticationOptions(),\n\t\tAuthorization: apiserveroptions.NewDelegatingAuthorizationOptions(),\n\t\tMetrics: metrics.NewOptions(),\n\t\tLogs: logs.NewOptions(),\n\t}\n\n\ts.Authentication.RemoteKubeConfigFileOptional = true\n\ts.Authorization.RemoteKubeConfigFileOptional = true\n\n\t// Set the PairName but leave certificate directory blank to generate in-memory by default\n\ts.SecureServing.ServerCert.CertDirectory = \"\"\n\ts.SecureServing.ServerCert.PairName = \"kube-controller-manager\"\n\ts.SecureServing.BindPort = ports.KubeControllerManagerPort\n\n\tgcIgnoredResources := make([]garbagecollectorconfig.GroupResource, 0, len(garbagecollector.DefaultIgnoredResources()))\n\tfor r := range garbagecollector.DefaultIgnoredResources() {\n\t\tgcIgnoredResources = append(gcIgnoredResources, garbagecollectorconfig.GroupResource{Group: r.Group, Resource: r.Resource})\n\t}\n\n\ts.GarbageCollectorController.GCIgnoredResources = gcIgnoredResources\n\ts.Generic.LeaderElection.ResourceName = \"kube-controller-manager\"\n\ts.Generic.LeaderElection.ResourceNamespace = \"kube-system\"\n\n\treturn \u0026s, nil\n}","line":{"from":98,"to":208}} {"id":100000280,"name":"NewDefaultComponentConfig","signature":"func NewDefaultComponentConfig() (kubectrlmgrconfig.KubeControllerManagerConfiguration, error)","file":"cmd/kube-controller-manager/app/options/options.go","code":"// NewDefaultComponentConfig returns kube-controller manager configuration object.\nfunc NewDefaultComponentConfig() (kubectrlmgrconfig.KubeControllerManagerConfiguration, error) {\n\tversioned := kubectrlmgrconfigv1alpha1.KubeControllerManagerConfiguration{}\n\tkubectrlmgrconfigscheme.Scheme.Default(\u0026versioned)\n\n\tinternal := kubectrlmgrconfig.KubeControllerManagerConfiguration{}\n\tif err := kubectrlmgrconfigscheme.Scheme.Convert(\u0026versioned, \u0026internal, nil); err != nil {\n\t\treturn internal, err\n\t}\n\treturn internal, nil\n}","line":{"from":210,"to":220}} {"id":100000281,"name":"Flags","signature":"func (s *KubeControllerManagerOptions) Flags(allControllers []string, disabledByDefaultControllers []string) cliflag.NamedFlagSets","file":"cmd/kube-controller-manager/app/options/options.go","code":"// Flags returns flags for a specific KubeController by section name\nfunc (s *KubeControllerManagerOptions) Flags(allControllers []string, disabledByDefaultControllers []string) cliflag.NamedFlagSets {\n\tfss := cliflag.NamedFlagSets{}\n\ts.Generic.AddFlags(\u0026fss, allControllers, disabledByDefaultControllers)\n\ts.KubeCloudShared.AddFlags(fss.FlagSet(\"generic\"))\n\ts.ServiceController.AddFlags(fss.FlagSet(\"service controller\"))\n\n\ts.SecureServing.AddFlags(fss.FlagSet(\"secure serving\"))\n\ts.Authentication.AddFlags(fss.FlagSet(\"authentication\"))\n\ts.Authorization.AddFlags(fss.FlagSet(\"authorization\"))\n\n\ts.AttachDetachController.AddFlags(fss.FlagSet(\"attachdetach controller\"))\n\ts.CSRSigningController.AddFlags(fss.FlagSet(\"csrsigning controller\"))\n\ts.DeploymentController.AddFlags(fss.FlagSet(\"deployment controller\"))\n\ts.StatefulSetController.AddFlags(fss.FlagSet(\"statefulset controller\"))\n\ts.DaemonSetController.AddFlags(fss.FlagSet(\"daemonset controller\"))\n\ts.DeprecatedFlags.AddFlags(fss.FlagSet(\"deprecated\"))\n\ts.EndpointController.AddFlags(fss.FlagSet(\"endpoint controller\"))\n\ts.EndpointSliceController.AddFlags(fss.FlagSet(\"endpointslice controller\"))\n\ts.EndpointSliceMirroringController.AddFlags(fss.FlagSet(\"endpointslicemirroring controller\"))\n\ts.EphemeralVolumeController.AddFlags(fss.FlagSet(\"ephemeralvolume controller\"))\n\ts.GarbageCollectorController.AddFlags(fss.FlagSet(\"garbagecollector controller\"))\n\ts.HPAController.AddFlags(fss.FlagSet(\"horizontalpodautoscaling controller\"))\n\ts.JobController.AddFlags(fss.FlagSet(\"job controller\"))\n\ts.CronJobController.AddFlags(fss.FlagSet(\"cronjob controller\"))\n\ts.NamespaceController.AddFlags(fss.FlagSet(\"namespace controller\"))\n\ts.NodeIPAMController.AddFlags(fss.FlagSet(\"nodeipam controller\"))\n\ts.NodeLifecycleController.AddFlags(fss.FlagSet(\"nodelifecycle controller\"))\n\ts.PersistentVolumeBinderController.AddFlags(fss.FlagSet(\"persistentvolume-binder controller\"))\n\ts.PodGCController.AddFlags(fss.FlagSet(\"podgc controller\"))\n\ts.ReplicaSetController.AddFlags(fss.FlagSet(\"replicaset controller\"))\n\ts.ReplicationController.AddFlags(fss.FlagSet(\"replicationcontroller\"))\n\ts.ResourceQuotaController.AddFlags(fss.FlagSet(\"resourcequota controller\"))\n\ts.SAController.AddFlags(fss.FlagSet(\"serviceaccount controller\"))\n\ts.TTLAfterFinishedController.AddFlags(fss.FlagSet(\"ttl-after-finished controller\"))\n\ts.Metrics.AddFlags(fss.FlagSet(\"metrics\"))\n\tlogsapi.AddFlags(s.Logs, fss.FlagSet(\"logs\"))\n\n\tfs := fss.FlagSet(\"misc\")\n\tfs.StringVar(\u0026s.Master, \"master\", s.Master, \"The address of the Kubernetes API server (overrides any value in kubeconfig).\")\n\tfs.StringVar(\u0026s.Generic.ClientConnection.Kubeconfig, \"kubeconfig\", s.Generic.ClientConnection.Kubeconfig, \"Path to kubeconfig file with authorization and master location information (the master location can be overridden by the master flag).\")\n\tutilfeature.DefaultMutableFeatureGate.AddFlag(fss.FlagSet(\"generic\"))\n\n\treturn fss\n}","line":{"from":222,"to":266}} {"id":100000282,"name":"ApplyTo","signature":"func (s *KubeControllerManagerOptions) ApplyTo(c *kubecontrollerconfig.Config) error","file":"cmd/kube-controller-manager/app/options/options.go","code":"// ApplyTo fills up controller manager config with options.\nfunc (s *KubeControllerManagerOptions) ApplyTo(c *kubecontrollerconfig.Config) error {\n\tif err := s.Generic.ApplyTo(\u0026c.ComponentConfig.Generic); err != nil {\n\t\treturn err\n\t}\n\tif err := s.KubeCloudShared.ApplyTo(\u0026c.ComponentConfig.KubeCloudShared); err != nil {\n\t\treturn err\n\t}\n\tif err := s.AttachDetachController.ApplyTo(\u0026c.ComponentConfig.AttachDetachController); err != nil {\n\t\treturn err\n\t}\n\tif err := s.CSRSigningController.ApplyTo(\u0026c.ComponentConfig.CSRSigningController); err != nil {\n\t\treturn err\n\t}\n\tif err := s.DaemonSetController.ApplyTo(\u0026c.ComponentConfig.DaemonSetController); err != nil {\n\t\treturn err\n\t}\n\tif err := s.DeploymentController.ApplyTo(\u0026c.ComponentConfig.DeploymentController); err != nil {\n\t\treturn err\n\t}\n\tif err := s.StatefulSetController.ApplyTo(\u0026c.ComponentConfig.StatefulSetController); err != nil {\n\t\treturn err\n\t}\n\tif err := s.DeprecatedFlags.ApplyTo(\u0026c.ComponentConfig.DeprecatedController); err != nil {\n\t\treturn err\n\t}\n\tif err := s.EndpointController.ApplyTo(\u0026c.ComponentConfig.EndpointController); err != nil {\n\t\treturn err\n\t}\n\tif err := s.EndpointSliceController.ApplyTo(\u0026c.ComponentConfig.EndpointSliceController); err != nil {\n\t\treturn err\n\t}\n\tif err := s.EndpointSliceMirroringController.ApplyTo(\u0026c.ComponentConfig.EndpointSliceMirroringController); err != nil {\n\t\treturn err\n\t}\n\tif err := s.EphemeralVolumeController.ApplyTo(\u0026c.ComponentConfig.EphemeralVolumeController); err != nil {\n\t\treturn err\n\t}\n\tif err := s.GarbageCollectorController.ApplyTo(\u0026c.ComponentConfig.GarbageCollectorController); err != nil {\n\t\treturn err\n\t}\n\tif err := s.HPAController.ApplyTo(\u0026c.ComponentConfig.HPAController); err != nil {\n\t\treturn err\n\t}\n\tif err := s.JobController.ApplyTo(\u0026c.ComponentConfig.JobController); err != nil {\n\t\treturn err\n\t}\n\tif err := s.CronJobController.ApplyTo(\u0026c.ComponentConfig.CronJobController); err != nil {\n\t\treturn err\n\t}\n\tif err := s.NamespaceController.ApplyTo(\u0026c.ComponentConfig.NamespaceController); err != nil {\n\t\treturn err\n\t}\n\tif err := s.NodeIPAMController.ApplyTo(\u0026c.ComponentConfig.NodeIPAMController); err != nil {\n\t\treturn err\n\t}\n\tif err := s.NodeLifecycleController.ApplyTo(\u0026c.ComponentConfig.NodeLifecycleController); err != nil {\n\t\treturn err\n\t}\n\tif err := s.PersistentVolumeBinderController.ApplyTo(\u0026c.ComponentConfig.PersistentVolumeBinderController); err != nil {\n\t\treturn err\n\t}\n\tif err := s.PodGCController.ApplyTo(\u0026c.ComponentConfig.PodGCController); err != nil {\n\t\treturn err\n\t}\n\tif err := s.ReplicaSetController.ApplyTo(\u0026c.ComponentConfig.ReplicaSetController); err != nil {\n\t\treturn err\n\t}\n\tif err := s.ReplicationController.ApplyTo(\u0026c.ComponentConfig.ReplicationController); err != nil {\n\t\treturn err\n\t}\n\tif err := s.ResourceQuotaController.ApplyTo(\u0026c.ComponentConfig.ResourceQuotaController); err != nil {\n\t\treturn err\n\t}\n\tif err := s.SAController.ApplyTo(\u0026c.ComponentConfig.SAController); err != nil {\n\t\treturn err\n\t}\n\tif err := s.ServiceController.ApplyTo(\u0026c.ComponentConfig.ServiceController); err != nil {\n\t\treturn err\n\t}\n\tif err := s.TTLAfterFinishedController.ApplyTo(\u0026c.ComponentConfig.TTLAfterFinishedController); err != nil {\n\t\treturn err\n\t}\n\tif err := s.SecureServing.ApplyTo(\u0026c.SecureServing, \u0026c.LoopbackClientConfig); err != nil {\n\t\treturn err\n\t}\n\tif s.SecureServing.BindPort != 0 || s.SecureServing.Listener != nil {\n\t\tif err := s.Authentication.ApplyTo(\u0026c.Authentication, c.SecureServing, nil); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := s.Authorization.ApplyTo(\u0026c.Authorization); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":268,"to":363}} {"id":100000283,"name":"Validate","signature":"func (s *KubeControllerManagerOptions) Validate(allControllers []string, disabledByDefaultControllers []string) error","file":"cmd/kube-controller-manager/app/options/options.go","code":"// Validate is used to validate the options and config before launching the controller manager\nfunc (s *KubeControllerManagerOptions) Validate(allControllers []string, disabledByDefaultControllers []string) error {\n\tvar errs []error\n\n\terrs = append(errs, s.Generic.Validate(allControllers, disabledByDefaultControllers)...)\n\terrs = append(errs, s.KubeCloudShared.Validate()...)\n\terrs = append(errs, s.AttachDetachController.Validate()...)\n\terrs = append(errs, s.CSRSigningController.Validate()...)\n\terrs = append(errs, s.DaemonSetController.Validate()...)\n\terrs = append(errs, s.DeploymentController.Validate()...)\n\terrs = append(errs, s.StatefulSetController.Validate()...)\n\terrs = append(errs, s.DeprecatedFlags.Validate()...)\n\terrs = append(errs, s.EndpointController.Validate()...)\n\terrs = append(errs, s.EndpointSliceController.Validate()...)\n\terrs = append(errs, s.EndpointSliceMirroringController.Validate()...)\n\terrs = append(errs, s.EphemeralVolumeController.Validate()...)\n\terrs = append(errs, s.GarbageCollectorController.Validate()...)\n\terrs = append(errs, s.HPAController.Validate()...)\n\terrs = append(errs, s.JobController.Validate()...)\n\terrs = append(errs, s.CronJobController.Validate()...)\n\terrs = append(errs, s.NamespaceController.Validate()...)\n\terrs = append(errs, s.NodeIPAMController.Validate()...)\n\terrs = append(errs, s.NodeLifecycleController.Validate()...)\n\terrs = append(errs, s.PersistentVolumeBinderController.Validate()...)\n\terrs = append(errs, s.PodGCController.Validate()...)\n\terrs = append(errs, s.ReplicaSetController.Validate()...)\n\terrs = append(errs, s.ReplicationController.Validate()...)\n\terrs = append(errs, s.ResourceQuotaController.Validate()...)\n\terrs = append(errs, s.SAController.Validate()...)\n\terrs = append(errs, s.ServiceController.Validate()...)\n\terrs = append(errs, s.TTLAfterFinishedController.Validate()...)\n\terrs = append(errs, s.SecureServing.Validate()...)\n\terrs = append(errs, s.Authentication.Validate()...)\n\terrs = append(errs, s.Authorization.Validate()...)\n\terrs = append(errs, s.Metrics.Validate()...)\n\n\t// TODO: validate component config, master and kubeconfig\n\n\treturn utilerrors.NewAggregate(errs)\n}","line":{"from":365,"to":404}} {"id":100000284,"name":"Config","signature":"func (s KubeControllerManagerOptions) Config(allControllers []string, disabledByDefaultControllers []string) (*kubecontrollerconfig.Config, error)","file":"cmd/kube-controller-manager/app/options/options.go","code":"// Config return a controller manager config objective\nfunc (s KubeControllerManagerOptions) Config(allControllers []string, disabledByDefaultControllers []string) (*kubecontrollerconfig.Config, error) {\n\tif err := s.Validate(allControllers, disabledByDefaultControllers); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := s.SecureServing.MaybeDefaultWithSelfSignedCerts(\"localhost\", nil, []net.IP{netutils.ParseIPSloppy(\"127.0.0.1\")}); err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating self-signed certificates: %v\", err)\n\t}\n\n\tkubeconfig, err := clientcmd.BuildConfigFromFlags(s.Master, s.Generic.ClientConnection.Kubeconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkubeconfig.DisableCompression = true\n\tkubeconfig.ContentConfig.AcceptContentTypes = s.Generic.ClientConnection.AcceptContentTypes\n\tkubeconfig.ContentConfig.ContentType = s.Generic.ClientConnection.ContentType\n\tkubeconfig.QPS = s.Generic.ClientConnection.QPS\n\tkubeconfig.Burst = int(s.Generic.ClientConnection.Burst)\n\n\tclient, err := clientset.NewForConfig(restclient.AddUserAgent(kubeconfig, KubeControllerManagerUserAgent))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\teventBroadcaster := record.NewBroadcaster()\n\teventRecorder := eventBroadcaster.NewRecorder(clientgokubescheme.Scheme, v1.EventSource{Component: KubeControllerManagerUserAgent})\n\n\tc := \u0026kubecontrollerconfig.Config{\n\t\tClient: client,\n\t\tKubeconfig: kubeconfig,\n\t\tEventBroadcaster: eventBroadcaster,\n\t\tEventRecorder: eventRecorder,\n\t}\n\tif err := s.ApplyTo(c); err != nil {\n\t\treturn nil, err\n\t}\n\ts.Metrics.Apply()\n\n\treturn c, nil\n}","line":{"from":406,"to":446}} {"id":100000285,"name":"AddFlags","signature":"func (o *PersistentVolumeBinderControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"cmd/kube-controller-manager/app/options/persistentvolumebindercontroller.go","code":"// AddFlags adds flags related to PersistentVolumeBinderController for controller manager to the specified FlagSet.\nfunc (o *PersistentVolumeBinderControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.DurationVar(\u0026o.PVClaimBinderSyncPeriod.Duration, \"pvclaimbinder-sync-period\", o.PVClaimBinderSyncPeriod.Duration, \"The period for syncing persistent volumes and persistent volume claims\")\n\tfs.StringVar(\u0026o.VolumeConfiguration.PersistentVolumeRecyclerConfiguration.PodTemplateFilePathNFS, \"pv-recycler-pod-template-filepath-nfs\", o.VolumeConfiguration.PersistentVolumeRecyclerConfiguration.PodTemplateFilePathNFS, \"The file path to a pod definition used as a template for NFS persistent volume recycling\")\n\tfs.Int32Var(\u0026o.VolumeConfiguration.PersistentVolumeRecyclerConfiguration.MinimumTimeoutNFS, \"pv-recycler-minimum-timeout-nfs\", o.VolumeConfiguration.PersistentVolumeRecyclerConfiguration.MinimumTimeoutNFS, \"The minimum ActiveDeadlineSeconds to use for an NFS Recycler pod\")\n\tfs.Int32Var(\u0026o.VolumeConfiguration.PersistentVolumeRecyclerConfiguration.IncrementTimeoutNFS, \"pv-recycler-increment-timeout-nfs\", o.VolumeConfiguration.PersistentVolumeRecyclerConfiguration.IncrementTimeoutNFS, \"the increment of time added per Gi to ActiveDeadlineSeconds for an NFS scrubber pod\")\n\tfs.StringVar(\u0026o.VolumeConfiguration.PersistentVolumeRecyclerConfiguration.PodTemplateFilePathHostPath, \"pv-recycler-pod-template-filepath-hostpath\", o.VolumeConfiguration.PersistentVolumeRecyclerConfiguration.PodTemplateFilePathHostPath, \"The file path to a pod definition used as a template for HostPath persistent volume recycling. This is for development and testing only and will not work in a multi-node cluster.\")\n\tfs.Int32Var(\u0026o.VolumeConfiguration.PersistentVolumeRecyclerConfiguration.MinimumTimeoutHostPath, \"pv-recycler-minimum-timeout-hostpath\", o.VolumeConfiguration.PersistentVolumeRecyclerConfiguration.MinimumTimeoutHostPath, \"The minimum ActiveDeadlineSeconds to use for a HostPath Recycler pod. This is for development and testing only and will not work in a multi-node cluster.\")\n\tfs.Int32Var(\u0026o.VolumeConfiguration.PersistentVolumeRecyclerConfiguration.IncrementTimeoutHostPath, \"pv-recycler-timeout-increment-hostpath\", o.VolumeConfiguration.PersistentVolumeRecyclerConfiguration.IncrementTimeoutHostPath, \"the increment of time added per Gi to ActiveDeadlineSeconds for a HostPath scrubber pod. This is for development and testing only and will not work in a multi-node cluster.\")\n\tfs.BoolVar(\u0026o.VolumeConfiguration.EnableHostPathProvisioning, \"enable-hostpath-provisioner\", o.VolumeConfiguration.EnableHostPathProvisioning, \"Enable HostPath PV provisioning when running without a cloud provider. This allows testing and development of provisioning features. HostPath provisioning is not supported in any way, won't work in a multi-node cluster, and should not be used for anything other than testing or development.\")\n\tfs.BoolVar(\u0026o.VolumeConfiguration.EnableDynamicProvisioning, \"enable-dynamic-provisioning\", o.VolumeConfiguration.EnableDynamicProvisioning, \"Enable dynamic provisioning for environments that support it.\")\n\tfs.StringVar(\u0026o.VolumeConfiguration.FlexVolumePluginDir, \"flex-volume-plugin-dir\", o.VolumeConfiguration.FlexVolumePluginDir, \"Full path of the directory in which the flex volume plugin should search for additional third party volume plugins.\")\n\tfs.StringSliceVar(\u0026o.VolumeHostCIDRDenylist, \"volume-host-cidr-denylist\", o.VolumeHostCIDRDenylist, \"A comma-separated list of CIDR ranges to avoid from volume plugins.\")\n\tfs.BoolVar(\u0026o.VolumeHostAllowLocalLoopback, \"volume-host-allow-local-loopback\", o.VolumeHostAllowLocalLoopback, \"If false, deny local loopback IPs in addition to any CIDR ranges in --volume-host-cidr-denylist\")\n}","line":{"from":34,"to":52}} {"id":100000286,"name":"ApplyTo","signature":"func (o *PersistentVolumeBinderControllerOptions) ApplyTo(cfg *persistentvolumeconfig.PersistentVolumeBinderControllerConfiguration) error","file":"cmd/kube-controller-manager/app/options/persistentvolumebindercontroller.go","code":"// ApplyTo fills up PersistentVolumeBinderController config with options.\nfunc (o *PersistentVolumeBinderControllerOptions) ApplyTo(cfg *persistentvolumeconfig.PersistentVolumeBinderControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.PVClaimBinderSyncPeriod = o.PVClaimBinderSyncPeriod\n\tcfg.VolumeConfiguration = o.VolumeConfiguration\n\tcfg.VolumeHostCIDRDenylist = o.VolumeHostCIDRDenylist\n\tcfg.VolumeHostAllowLocalLoopback = o.VolumeHostAllowLocalLoopback\n\n\treturn nil\n}","line":{"from":54,"to":66}} {"id":100000287,"name":"Validate","signature":"func (o *PersistentVolumeBinderControllerOptions) Validate() []error","file":"cmd/kube-controller-manager/app/options/persistentvolumebindercontroller.go","code":"// Validate checks validation of PersistentVolumeBinderControllerOptions.\nfunc (o *PersistentVolumeBinderControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\tif _, err := ParseVolumeHostFilters(o.VolumeHostCIDRDenylist, o.VolumeHostAllowLocalLoopback); err != nil {\n\t\terrs = append(errs, fmt.Errorf(\"bad --volume-host-ip-denylist/--volume-host-allow-local-loopback %w\", err))\n\t}\n\treturn errs\n}","line":{"from":68,"to":79}} {"id":100000288,"name":"ParseVolumeHostFilters","signature":"func ParseVolumeHostFilters(denylist []string, allowLocalLoopback bool) (*proxyutil.FilteredDialOptions, error)","file":"cmd/kube-controller-manager/app/options/persistentvolumebindercontroller.go","code":"// ParseVolumeHostFilters process the --volume-host-ip-denylist and --volume-host-allow-local-loopback flags.\nfunc ParseVolumeHostFilters(denylist []string, allowLocalLoopback bool) (*proxyutil.FilteredDialOptions, error) {\n\tdenyCIDRs, err := netutils.ParseCIDRs(denylist)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026proxyutil.FilteredDialOptions{DialHostCIDRDenylist: denyCIDRs, AllowLocalLoopback: allowLocalLoopback}, nil\n}","line":{"from":81,"to":88}} {"id":100000289,"name":"AddFlags","signature":"func (o *PodGCControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"cmd/kube-controller-manager/app/options/podgccontroller.go","code":"// AddFlags adds flags related to PodGCController for controller manager to the specified FlagSet.\nfunc (o *PodGCControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.Int32Var(\u0026o.TerminatedPodGCThreshold, \"terminated-pod-gc-threshold\", o.TerminatedPodGCThreshold, \"Number of terminated pods that can exist before the terminated pod garbage collector starts deleting terminated pods. If \u003c= 0, the terminated pod garbage collector is disabled.\")\n}","line":{"from":30,"to":37}} {"id":100000290,"name":"ApplyTo","signature":"func (o *PodGCControllerOptions) ApplyTo(cfg *podgcconfig.PodGCControllerConfiguration) error","file":"cmd/kube-controller-manager/app/options/podgccontroller.go","code":"// ApplyTo fills up PodGCController config with options.\nfunc (o *PodGCControllerOptions) ApplyTo(cfg *podgcconfig.PodGCControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.TerminatedPodGCThreshold = o.TerminatedPodGCThreshold\n\n\treturn nil\n}","line":{"from":39,"to":48}} {"id":100000291,"name":"Validate","signature":"func (o *PodGCControllerOptions) Validate() []error","file":"cmd/kube-controller-manager/app/options/podgccontroller.go","code":"// Validate checks validation of PodGCControllerOptions.\nfunc (o *PodGCControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\treturn errs\n}","line":{"from":50,"to":58}} {"id":100000292,"name":"AddFlags","signature":"func (o *ReplicaSetControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"cmd/kube-controller-manager/app/options/replicasetcontroller.go","code":"// AddFlags adds flags related to ReplicaSetController for controller manager to the specified FlagSet.\nfunc (o *ReplicaSetControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.Int32Var(\u0026o.ConcurrentRSSyncs, \"concurrent-replicaset-syncs\", o.ConcurrentRSSyncs, \"The number of replica sets that are allowed to sync concurrently. Larger number = more responsive replica management, but more CPU (and network) load\")\n}","line":{"from":30,"to":37}} {"id":100000293,"name":"ApplyTo","signature":"func (o *ReplicaSetControllerOptions) ApplyTo(cfg *replicasetconfig.ReplicaSetControllerConfiguration) error","file":"cmd/kube-controller-manager/app/options/replicasetcontroller.go","code":"// ApplyTo fills up ReplicaSetController config with options.\nfunc (o *ReplicaSetControllerOptions) ApplyTo(cfg *replicasetconfig.ReplicaSetControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ConcurrentRSSyncs = o.ConcurrentRSSyncs\n\n\treturn nil\n}","line":{"from":39,"to":48}} {"id":100000294,"name":"Validate","signature":"func (o *ReplicaSetControllerOptions) Validate() []error","file":"cmd/kube-controller-manager/app/options/replicasetcontroller.go","code":"// Validate checks validation of ReplicaSetControllerOptions.\nfunc (o *ReplicaSetControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\treturn errs\n}","line":{"from":50,"to":58}} {"id":100000295,"name":"AddFlags","signature":"func (o *ReplicationControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"cmd/kube-controller-manager/app/options/replicationcontroller.go","code":"// AddFlags adds flags related to ReplicationController for controller manager to the specified FlagSet.\nfunc (o *ReplicationControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.Int32Var(\u0026o.ConcurrentRCSyncs, \"concurrent_rc_syncs\", o.ConcurrentRCSyncs, \"The number of replication controllers that are allowed to sync concurrently. Larger number = more responsive replica management, but more CPU (and network) load\")\n}","line":{"from":30,"to":37}} {"id":100000296,"name":"ApplyTo","signature":"func (o *ReplicationControllerOptions) ApplyTo(cfg *replicationconfig.ReplicationControllerConfiguration) error","file":"cmd/kube-controller-manager/app/options/replicationcontroller.go","code":"// ApplyTo fills up ReplicationController config with options.\nfunc (o *ReplicationControllerOptions) ApplyTo(cfg *replicationconfig.ReplicationControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ConcurrentRCSyncs = o.ConcurrentRCSyncs\n\n\treturn nil\n}","line":{"from":39,"to":48}} {"id":100000297,"name":"Validate","signature":"func (o *ReplicationControllerOptions) Validate() []error","file":"cmd/kube-controller-manager/app/options/replicationcontroller.go","code":"// Validate checks validation of ReplicationControllerOptions.\nfunc (o *ReplicationControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\treturn errs\n}","line":{"from":50,"to":58}} {"id":100000298,"name":"AddFlags","signature":"func (o *ResourceQuotaControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"cmd/kube-controller-manager/app/options/resourcequotacontroller.go","code":"// AddFlags adds flags related to ResourceQuotaController for controller manager to the specified FlagSet.\nfunc (o *ResourceQuotaControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.DurationVar(\u0026o.ResourceQuotaSyncPeriod.Duration, \"resource-quota-sync-period\", o.ResourceQuotaSyncPeriod.Duration, \"The period for syncing quota usage status in the system\")\n\tfs.Int32Var(\u0026o.ConcurrentResourceQuotaSyncs, \"concurrent-resource-quota-syncs\", o.ConcurrentResourceQuotaSyncs, \"The number of resource quotas that are allowed to sync concurrently. Larger number = more responsive quota management, but more CPU (and network) load\")\n}","line":{"from":30,"to":38}} {"id":100000299,"name":"ApplyTo","signature":"func (o *ResourceQuotaControllerOptions) ApplyTo(cfg *resourcequotaconfig.ResourceQuotaControllerConfiguration) error","file":"cmd/kube-controller-manager/app/options/resourcequotacontroller.go","code":"// ApplyTo fills up ResourceQuotaController config with options.\nfunc (o *ResourceQuotaControllerOptions) ApplyTo(cfg *resourcequotaconfig.ResourceQuotaControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ResourceQuotaSyncPeriod = o.ResourceQuotaSyncPeriod\n\tcfg.ConcurrentResourceQuotaSyncs = o.ConcurrentResourceQuotaSyncs\n\n\treturn nil\n}","line":{"from":40,"to":50}} {"id":100000300,"name":"Validate","signature":"func (o *ResourceQuotaControllerOptions) Validate() []error","file":"cmd/kube-controller-manager/app/options/resourcequotacontroller.go","code":"// Validate checks validation of ResourceQuotaControllerOptions.\nfunc (o *ResourceQuotaControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\treturn errs\n}","line":{"from":52,"to":60}} {"id":100000301,"name":"AddFlags","signature":"func (o *SAControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"cmd/kube-controller-manager/app/options/serviceaccountcontroller.go","code":"// AddFlags adds flags related to ServiceAccountController for controller manager to the specified FlagSet\nfunc (o *SAControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.StringVar(\u0026o.ServiceAccountKeyFile, \"service-account-private-key-file\", o.ServiceAccountKeyFile, \"Filename containing a PEM-encoded private RSA or ECDSA key used to sign service account tokens.\")\n\tfs.Int32Var(\u0026o.ConcurrentSATokenSyncs, \"concurrent-serviceaccount-token-syncs\", o.ConcurrentSATokenSyncs, \"The number of service account token objects that are allowed to sync concurrently. Larger number = more responsive token generation, but more CPU (and network) load\")\n\tfs.StringVar(\u0026o.RootCAFile, \"root-ca-file\", o.RootCAFile, \"If set, this root certificate authority will be included in service account's token secret. This must be a valid PEM-encoded CA bundle.\")\n}","line":{"from":30,"to":39}} {"id":100000302,"name":"ApplyTo","signature":"func (o *SAControllerOptions) ApplyTo(cfg *serviceaccountconfig.SAControllerConfiguration) error","file":"cmd/kube-controller-manager/app/options/serviceaccountcontroller.go","code":"// ApplyTo fills up ServiceAccountController config with options.\nfunc (o *SAControllerOptions) ApplyTo(cfg *serviceaccountconfig.SAControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ServiceAccountKeyFile = o.ServiceAccountKeyFile\n\tcfg.ConcurrentSATokenSyncs = o.ConcurrentSATokenSyncs\n\tcfg.RootCAFile = o.RootCAFile\n\n\treturn nil\n}","line":{"from":41,"to":52}} {"id":100000303,"name":"Validate","signature":"func (o *SAControllerOptions) Validate() []error","file":"cmd/kube-controller-manager/app/options/serviceaccountcontroller.go","code":"// Validate checks validation of ServiceAccountControllerOptions.\nfunc (o *SAControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\treturn errs\n}","line":{"from":54,"to":62}} {"id":100000304,"name":"AddFlags","signature":"func (o *StatefulSetControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"cmd/kube-controller-manager/app/options/statefulsetcontroller.go","code":"// AddFlags adds flags related to StatefulSetController for controller manager to the specified FlagSet.\nfunc (o *StatefulSetControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.Int32Var(\u0026o.ConcurrentStatefulSetSyncs, \"concurrent-statefulset-syncs\", o.ConcurrentStatefulSetSyncs, \"The number of statefulset objects that are allowed to sync concurrently. Larger number = more responsive statefulsets, but more CPU (and network) load\")\n}","line":{"from":32,"to":39}} {"id":100000305,"name":"ApplyTo","signature":"func (o *StatefulSetControllerOptions) ApplyTo(cfg *statefulsetconfig.StatefulSetControllerConfiguration) error","file":"cmd/kube-controller-manager/app/options/statefulsetcontroller.go","code":"// ApplyTo fills up StatefulSetController config with options.\nfunc (o *StatefulSetControllerOptions) ApplyTo(cfg *statefulsetconfig.StatefulSetControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ConcurrentStatefulSetSyncs = o.ConcurrentStatefulSetSyncs\n\n\treturn nil\n}","line":{"from":41,"to":50}} {"id":100000306,"name":"Validate","signature":"func (o *StatefulSetControllerOptions) Validate() []error","file":"cmd/kube-controller-manager/app/options/statefulsetcontroller.go","code":"// Validate checks validation of StatefulSetControllerOptions.\nfunc (o *StatefulSetControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\tif o.ConcurrentStatefulSetSyncs \u003c 1 {\n\t\terrs = append(errs, fmt.Errorf(\"concurrent-statefulset-syncs must be greater than 0, but got %d\", o.ConcurrentStatefulSetSyncs))\n\t}\n\treturn errs\n}","line":{"from":52,"to":63}} {"id":100000307,"name":"AddFlags","signature":"func (o *TTLAfterFinishedControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"cmd/kube-controller-manager/app/options/ttlafterfinishedcontroller.go","code":"// AddFlags adds flags related to TTLAfterFinishedController for controller manager to the specified FlagSet.\nfunc (o *TTLAfterFinishedControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.Int32Var(\u0026o.ConcurrentTTLSyncs, \"concurrent-ttl-after-finished-syncs\", o.ConcurrentTTLSyncs, \"The number of TTL-after-finished controller workers that are allowed to sync concurrently.\")\n}","line":{"from":30,"to":37}} {"id":100000308,"name":"ApplyTo","signature":"func (o *TTLAfterFinishedControllerOptions) ApplyTo(cfg *ttlafterfinishedconfig.TTLAfterFinishedControllerConfiguration) error","file":"cmd/kube-controller-manager/app/options/ttlafterfinishedcontroller.go","code":"// ApplyTo fills up TTLAfterFinishedController config with options.\nfunc (o *TTLAfterFinishedControllerOptions) ApplyTo(cfg *ttlafterfinishedconfig.TTLAfterFinishedControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ConcurrentTTLSyncs = o.ConcurrentTTLSyncs\n\n\treturn nil\n}","line":{"from":39,"to":48}} {"id":100000309,"name":"Validate","signature":"func (o *TTLAfterFinishedControllerOptions) Validate() []error","file":"cmd/kube-controller-manager/app/options/ttlafterfinishedcontroller.go","code":"// Validate checks validation of TTLAfterFinishedControllerOptions.\nfunc (o *TTLAfterFinishedControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\treturn errs\n}","line":{"from":50,"to":58}} {"id":100000310,"name":"ProbeAttachableVolumePlugins","signature":"func ProbeAttachableVolumePlugins(logger klog.Logger) ([]volume.VolumePlugin, error)","file":"cmd/kube-controller-manager/app/plugins.go","code":"// ProbeAttachableVolumePlugins collects all volume plugins for the attach/\n// detach controller.\n// The list of plugins is manually compiled. This code and the plugin\n// initialization code for kubelet really, really need a through refactor.\nfunc ProbeAttachableVolumePlugins(logger klog.Logger) ([]volume.VolumePlugin, error) {\n\tvar err error\n\tallPlugins := []volume.VolumePlugin{}\n\tallPlugins, err = appendAttachableLegacyProviderVolumes(logger, allPlugins, utilfeature.DefaultFeatureGate)\n\tif err != nil {\n\t\treturn allPlugins, err\n\t}\n\tallPlugins = append(allPlugins, fc.ProbeVolumePlugins()...)\n\tallPlugins = append(allPlugins, iscsi.ProbeVolumePlugins()...)\n\tallPlugins = append(allPlugins, csi.ProbeVolumePlugins()...)\n\treturn allPlugins, nil\n}","line":{"from":48,"to":63}} {"id":100000311,"name":"GetDynamicPluginProber","signature":"func GetDynamicPluginProber(config persistentvolumeconfig.VolumeConfiguration) volume.DynamicPluginProber","file":"cmd/kube-controller-manager/app/plugins.go","code":"// GetDynamicPluginProber gets the probers of dynamically discoverable plugins\n// for the attach/detach controller.\n// Currently only Flexvolume plugins are dynamically discoverable.\nfunc GetDynamicPluginProber(config persistentvolumeconfig.VolumeConfiguration) volume.DynamicPluginProber {\n\treturn flexvolume.GetDynamicPluginProber(config.FlexVolumePluginDir, exec.New() /*exec.Interface*/)\n}","line":{"from":65,"to":70}} {"id":100000312,"name":"ProbeExpandableVolumePlugins","signature":"func ProbeExpandableVolumePlugins(logger klog.Logger, config persistentvolumeconfig.VolumeConfiguration) ([]volume.VolumePlugin, error)","file":"cmd/kube-controller-manager/app/plugins.go","code":"// ProbeExpandableVolumePlugins returns volume plugins which are expandable\nfunc ProbeExpandableVolumePlugins(logger klog.Logger, config persistentvolumeconfig.VolumeConfiguration) ([]volume.VolumePlugin, error) {\n\tvar err error\n\tallPlugins := []volume.VolumePlugin{}\n\tallPlugins, err = appendExpandableLegacyProviderVolumes(logger, allPlugins, utilfeature.DefaultFeatureGate)\n\tif err != nil {\n\t\treturn allPlugins, err\n\t}\n\tallPlugins = append(allPlugins, fc.ProbeVolumePlugins()...)\n\treturn allPlugins, nil\n}","line":{"from":72,"to":82}} {"id":100000313,"name":"ProbeControllerVolumePlugins","signature":"func ProbeControllerVolumePlugins(logger klog.Logger, cloud cloudprovider.Interface, config persistentvolumeconfig.VolumeConfiguration) ([]volume.VolumePlugin, error)","file":"cmd/kube-controller-manager/app/plugins.go","code":"// ProbeControllerVolumePlugins collects all persistent volume plugins into an\n// easy to use list. Only volume plugins that implement any of\n// provisioner/recycler/deleter interface should be returned.\nfunc ProbeControllerVolumePlugins(logger klog.Logger, cloud cloudprovider.Interface, config persistentvolumeconfig.VolumeConfiguration) ([]volume.VolumePlugin, error) {\n\tallPlugins := []volume.VolumePlugin{}\n\n\t// The list of plugins to probe is decided by this binary, not\n\t// by dynamic linking or other \"magic\". Plugins will be analyzed and\n\t// initialized later.\n\n\t// Each plugin can make use of VolumeConfig. The single arg to this func contains *all* enumerated\n\t// options meant to configure volume plugins. From that single config, create an instance of volume.VolumeConfig\n\t// for a specific plugin and pass that instance to the plugin's ProbeVolumePlugins(config) func.\n\n\t// HostPath recycling is for testing and development purposes only!\n\thostPathConfig := volume.VolumeConfig{\n\t\tRecyclerMinimumTimeout: int(config.PersistentVolumeRecyclerConfiguration.MinimumTimeoutHostPath),\n\t\tRecyclerTimeoutIncrement: int(config.PersistentVolumeRecyclerConfiguration.IncrementTimeoutHostPath),\n\t\tRecyclerPodTemplate: volume.NewPersistentVolumeRecyclerPodTemplate(),\n\t\tProvisioningEnabled: config.EnableHostPathProvisioning,\n\t}\n\tif err := AttemptToLoadRecycler(config.PersistentVolumeRecyclerConfiguration.PodTemplateFilePathHostPath, \u0026hostPathConfig); err != nil {\n\t\tlogger.Error(err, \"Could not create hostpath recycler pod from file\", \"path\", config.PersistentVolumeRecyclerConfiguration.PodTemplateFilePathHostPath)\n\t\tklog.FlushAndExit(klog.ExitFlushTimeout, 1)\n\t}\n\tallPlugins = append(allPlugins, hostpath.ProbeVolumePlugins(hostPathConfig)...)\n\n\tnfsConfig := volume.VolumeConfig{\n\t\tRecyclerMinimumTimeout: int(config.PersistentVolumeRecyclerConfiguration.MinimumTimeoutNFS),\n\t\tRecyclerTimeoutIncrement: int(config.PersistentVolumeRecyclerConfiguration.IncrementTimeoutNFS),\n\t\tRecyclerPodTemplate: volume.NewPersistentVolumeRecyclerPodTemplate(),\n\t}\n\tif err := AttemptToLoadRecycler(config.PersistentVolumeRecyclerConfiguration.PodTemplateFilePathNFS, \u0026nfsConfig); err != nil {\n\t\tlogger.Error(err, \"Could not create NFS recycler pod from file\", \"path\", config.PersistentVolumeRecyclerConfiguration.PodTemplateFilePathNFS)\n\t\tklog.FlushAndExit(klog.ExitFlushTimeout, 1)\n\t}\n\tallPlugins = append(allPlugins, nfs.ProbeVolumePlugins(nfsConfig)...)\n\n\tvar err error\n\tallPlugins, err = appendExpandableLegacyProviderVolumes(logger, allPlugins, utilfeature.DefaultFeatureGate)\n\tif err != nil {\n\t\treturn allPlugins, err\n\t}\n\n\tallPlugins = append(allPlugins, local.ProbeVolumePlugins()...)\n\tallPlugins = append(allPlugins, csi.ProbeVolumePlugins()...)\n\n\treturn allPlugins, nil\n}","line":{"from":84,"to":132}} {"id":100000314,"name":"AttemptToLoadRecycler","signature":"func AttemptToLoadRecycler(path string, config *volume.VolumeConfig) error","file":"cmd/kube-controller-manager/app/plugins.go","code":"// AttemptToLoadRecycler tries decoding a pod from a filepath for use as a recycler for a volume.\n// If successful, this method will set the recycler on the config.\n// If unsuccessful, an error is returned. Function is exported for reuse downstream.\nfunc AttemptToLoadRecycler(path string, config *volume.VolumeConfig) error {\n\tif path != \"\" {\n\t\trecyclerPod, err := volumeutil.LoadPodFromFile(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err = volume.ValidateRecyclerPodTemplate(recyclerPod); err != nil {\n\t\t\treturn fmt.Errorf(\"pod specification (%v): %v\", path, err)\n\t\t}\n\t\tconfig.RecyclerPodTemplate = recyclerPod\n\t}\n\treturn nil\n}","line":{"from":134,"to":149}} {"id":100000315,"name":"appendAttachableLegacyProviderVolumes","signature":"func appendAttachableLegacyProviderVolumes(logger klog.Logger, allPlugins []volume.VolumePlugin, featureGate featuregate.FeatureGate) ([]volume.VolumePlugin, error)","file":"cmd/kube-controller-manager/app/plugins_providerless.go","code":"func appendAttachableLegacyProviderVolumes(logger klog.Logger, allPlugins []volume.VolumePlugin, featureGate featuregate.FeatureGate) ([]volume.VolumePlugin, error) {\n\t// no-op when compiled without legacy cloud providers\n\treturn allPlugins, nil\n}","line":{"from":29,"to":32}} {"id":100000316,"name":"appendExpandableLegacyProviderVolumes","signature":"func appendExpandableLegacyProviderVolumes(logger klog.Logger, allPlugins []volume.VolumePlugin, featureGate featuregate.FeatureGate) ([]volume.VolumePlugin, error)","file":"cmd/kube-controller-manager/app/plugins_providerless.go","code":"func appendExpandableLegacyProviderVolumes(logger klog.Logger, allPlugins []volume.VolumePlugin, featureGate featuregate.FeatureGate) ([]volume.VolumePlugin, error) {\n\t// no-op when compiled without legacy cloud providers\n\treturn allPlugins, nil\n}","line":{"from":34,"to":37}} {"id":100000317,"name":"appendLegacyProviderVolumes","signature":"func appendLegacyProviderVolumes(logger klog.Logger, allPlugins []volume.VolumePlugin, featureGate featuregate.FeatureGate) ([]volume.VolumePlugin, error)","file":"cmd/kube-controller-manager/app/plugins_providerless.go","code":"func appendLegacyProviderVolumes(logger klog.Logger, allPlugins []volume.VolumePlugin, featureGate featuregate.FeatureGate) ([]volume.VolumePlugin, error) {\n\t// no-op when compiled without legacy cloud providers\n\treturn allPlugins, nil\n}","line":{"from":39,"to":42}} {"id":100000318,"name":"appendPluginBasedOnFeatureFlags","signature":"func appendPluginBasedOnFeatureFlags(logger klog.Logger, plugins []volume.VolumePlugin, inTreePluginName string, featureGate featuregate.FeatureGate, pluginInfo pluginInfo) ([]volume.VolumePlugin, error)","file":"cmd/kube-controller-manager/app/plugins_providers.go","code":"func appendPluginBasedOnFeatureFlags(logger klog.Logger, plugins []volume.VolumePlugin, inTreePluginName string, featureGate featuregate.FeatureGate, pluginInfo pluginInfo) ([]volume.VolumePlugin, error) {\n\n\t_, err := csimigration.CheckMigrationFeatureFlags(featureGate, pluginInfo.pluginMigrationFeature, pluginInfo.pluginUnregisterFeature)\n\tif err != nil {\n\t\tlogger.Error(err, \"Unexpected CSI Migration Feature Flags combination detected. CSI Migration may not take effect\")\n\t\tklog.FlushAndExit(klog.ExitFlushTimeout, 1)\n\t\t// TODO: fail and return here once alpha only tests can set the feature flags for a plugin correctly\n\t}\n\n\t// Skip appending the in-tree plugin to the list of plugins to be probed/initialized\n\t// if the plugin unregister feature flag is set\n\tif featureGate.Enabled(pluginInfo.pluginUnregisterFeature) {\n\t\tlogger.Info(\"Skip registration of plugin since feature flag is enabled\", \"plugin\", inTreePluginName, \"feature\", pluginInfo.pluginUnregisterFeature)\n\t\treturn plugins, nil\n\t}\n\tplugins = append(plugins, pluginInfo.pluginProbeFunction()...)\n\treturn plugins, nil\n}","line":{"from":38,"to":55}} {"id":100000319,"name":"appendAttachableLegacyProviderVolumes","signature":"func appendAttachableLegacyProviderVolumes(logger klog.Logger, allPlugins []volume.VolumePlugin, featureGate featuregate.FeatureGate) ([]volume.VolumePlugin, error)","file":"cmd/kube-controller-manager/app/plugins_providers.go","code":"func appendAttachableLegacyProviderVolumes(logger klog.Logger, allPlugins []volume.VolumePlugin, featureGate featuregate.FeatureGate) ([]volume.VolumePlugin, error) {\n\tpluginMigrationStatus := make(map[string]pluginInfo)\n\tpluginMigrationStatus[plugins.GCEPDInTreePluginName] = pluginInfo{pluginMigrationFeature: features.CSIMigrationGCE, pluginUnregisterFeature: features.InTreePluginGCEUnregister, pluginProbeFunction: gcepd.ProbeVolumePlugins}\n\tpluginMigrationStatus[plugins.VSphereInTreePluginName] = pluginInfo{pluginMigrationFeature: features.CSIMigrationvSphere, pluginUnregisterFeature: features.InTreePluginvSphereUnregister, pluginProbeFunction: vsphere_volume.ProbeVolumePlugins}\n\tpluginMigrationStatus[plugins.PortworxVolumePluginName] = pluginInfo{pluginMigrationFeature: features.CSIMigrationPortworx, pluginUnregisterFeature: features.InTreePluginPortworxUnregister, pluginProbeFunction: portworx.ProbeVolumePlugins}\n\tpluginMigrationStatus[plugins.RBDVolumePluginName] = pluginInfo{pluginMigrationFeature: features.CSIMigrationRBD, pluginUnregisterFeature: features.InTreePluginRBDUnregister, pluginProbeFunction: rbd.ProbeVolumePlugins}\n\tvar err error\n\tfor pluginName, pluginInfo := range pluginMigrationStatus {\n\t\tallPlugins, err = appendPluginBasedOnFeatureFlags(logger, allPlugins, pluginName, featureGate, pluginInfo)\n\t\tif err != nil {\n\t\t\treturn allPlugins, err\n\t\t}\n\t}\n\treturn allPlugins, nil\n}","line":{"from":63,"to":77}} {"id":100000320,"name":"appendExpandableLegacyProviderVolumes","signature":"func appendExpandableLegacyProviderVolumes(logger klog.Logger, allPlugins []volume.VolumePlugin, featureGate featuregate.FeatureGate) ([]volume.VolumePlugin, error)","file":"cmd/kube-controller-manager/app/plugins_providers.go","code":"func appendExpandableLegacyProviderVolumes(logger klog.Logger, allPlugins []volume.VolumePlugin, featureGate featuregate.FeatureGate) ([]volume.VolumePlugin, error) {\n\treturn appendLegacyProviderVolumes(logger, allPlugins, featureGate)\n}","line":{"from":79,"to":81}} {"id":100000321,"name":"appendLegacyProviderVolumes","signature":"func appendLegacyProviderVolumes(logger klog.Logger, allPlugins []volume.VolumePlugin, featureGate featuregate.FeatureGate) ([]volume.VolumePlugin, error)","file":"cmd/kube-controller-manager/app/plugins_providers.go","code":"func appendLegacyProviderVolumes(logger klog.Logger, allPlugins []volume.VolumePlugin, featureGate featuregate.FeatureGate) ([]volume.VolumePlugin, error) {\n\tvar err error\n\t// First append attachable volumes\n\tallPlugins, err = appendAttachableLegacyProviderVolumes(logger, allPlugins, featureGate)\n\tif err != nil {\n\t\treturn allPlugins, err\n\t}\n\n\t// Then append non-attachable volumes\n\tpluginName := plugins.AzureFileInTreePluginName\n\tpluginInfo := pluginInfo{\n\t\tpluginMigrationFeature: features.CSIMigrationAzureFile,\n\t\tpluginUnregisterFeature: features.InTreePluginAzureFileUnregister,\n\t\tpluginProbeFunction: azure_file.ProbeVolumePlugins,\n\t}\n\tallPlugins, err = appendPluginBasedOnFeatureFlags(logger, allPlugins, pluginName, featureGate, pluginInfo)\n\tif err != nil {\n\t\treturn allPlugins, err\n\t}\n\n\treturn allPlugins, nil\n}","line":{"from":83,"to":104}} {"id":100000322,"name":"startDisruptionController","signature":"func startDisruptionController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/policy.go","code":"func startDisruptionController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tclient := controllerContext.ClientBuilder.ClientOrDie(\"disruption-controller\")\n\tconfig := controllerContext.ClientBuilder.ConfigOrDie(\"disruption-controller\")\n\tscaleKindResolver := scale.NewDiscoveryScaleKindResolver(client.Discovery())\n\tscaleClient, err := scale.NewForConfig(config, controllerContext.RESTMapper, dynamic.LegacyAPIPathResolverFunc, scaleKindResolver)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\tgo disruption.NewDisruptionController(\n\t\tcontrollerContext.InformerFactory.Core().V1().Pods(),\n\t\tcontrollerContext.InformerFactory.Policy().V1().PodDisruptionBudgets(),\n\t\tcontrollerContext.InformerFactory.Core().V1().ReplicationControllers(),\n\t\tcontrollerContext.InformerFactory.Apps().V1().ReplicaSets(),\n\t\tcontrollerContext.InformerFactory.Apps().V1().Deployments(),\n\t\tcontrollerContext.InformerFactory.Apps().V1().StatefulSets(),\n\t\tclient,\n\t\tcontrollerContext.RESTMapper,\n\t\tscaleClient,\n\t\tclient.Discovery(),\n\t).Run(ctx)\n\treturn nil, true, nil\n}","line":{"from":31,"to":53}} {"id":100000323,"name":"startClusterRoleAggregrationController","signature":"func startClusterRoleAggregrationController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error)","file":"cmd/kube-controller-manager/app/rbac.go","code":"func startClusterRoleAggregrationController(ctx context.Context, controllerContext ControllerContext) (controller.Interface, bool, error) {\n\tif !controllerContext.AvailableResources[schema.GroupVersionResource{Group: \"rbac.authorization.k8s.io\", Version: \"v1\", Resource: \"clusterroles\"}] {\n\t\treturn nil, false, nil\n\t}\n\tgo clusterroleaggregation.NewClusterRoleAggregation(\n\t\tcontrollerContext.InformerFactory.Rbac().V1().ClusterRoles(),\n\t\tcontrollerContext.ClientBuilder.ClientOrDie(\"clusterrole-aggregation-controller\").RbacV1(),\n\t).Run(ctx, 5)\n\treturn nil, true, nil\n}","line":{"from":27,"to":36}} {"id":100000324,"name":"main","signature":"func main()","file":"cmd/kube-controller-manager/controller-manager.go","code":"func main() {\n\tcommand := app.NewControllerManagerCommand()\n\tcode := cli.Run(command)\n\tos.Exit(code)\n}","line":{"from":34,"to":38}} {"id":100000325,"name":"SetMax","signature":"func (rct realConntracker) SetMax(max int) error","file":"cmd/kube-proxy/app/conntrack.go","code":"func (rct realConntracker) SetMax(max int) error {\n\tif err := rct.setIntSysCtl(\"nf_conntrack_max\", max); err != nil {\n\t\treturn err\n\t}\n\tklog.InfoS(\"Setting nf_conntrack_max\", \"nfConntrackMax\", max)\n\n\t// Linux does not support writing to /sys/module/nf_conntrack/parameters/hashsize\n\t// when the writer process is not in the initial network namespace\n\t// (https://github.com/torvalds/linux/blob/v4.10/net/netfilter/nf_conntrack_core.c#L1795-L1796).\n\t// Usually that's fine. But in some configurations such as with github.com/kinvolk/kubeadm-nspawn,\n\t// kube-proxy is in another netns.\n\t// Therefore, check if writing in hashsize is necessary and skip the writing if not.\n\thashsize, err := readIntStringFile(\"/sys/module/nf_conntrack/parameters/hashsize\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tif hashsize \u003e= (max / 4) {\n\t\treturn nil\n\t}\n\n\t// sysfs is expected to be mounted as 'rw'. However, it may be\n\t// unexpectedly mounted as 'ro' by docker because of a known docker\n\t// issue (https://github.com/docker/docker/issues/24000). Setting\n\t// conntrack will fail when sysfs is readonly. When that happens, we\n\t// don't set conntrack hashsize and return a special error\n\t// errReadOnlySysFS here. The caller should deal with\n\t// errReadOnlySysFS differently.\n\twritable, err := isSysFSWritable()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !writable {\n\t\treturn errReadOnlySysFS\n\t}\n\t// TODO: generify this and sysctl to a new sysfs.WriteInt()\n\tklog.InfoS(\"Setting conntrack hashsize\", \"conntrackHashsize\", max/4)\n\treturn writeIntStringFile(\"/sys/module/nf_conntrack/parameters/hashsize\", max/4)\n}","line":{"from":48,"to":85}} {"id":100000326,"name":"SetTCPEstablishedTimeout","signature":"func (rct realConntracker) SetTCPEstablishedTimeout(seconds int) error","file":"cmd/kube-proxy/app/conntrack.go","code":"func (rct realConntracker) SetTCPEstablishedTimeout(seconds int) error {\n\treturn rct.setIntSysCtl(\"nf_conntrack_tcp_timeout_established\", seconds)\n}","line":{"from":87,"to":89}} {"id":100000327,"name":"SetTCPCloseWaitTimeout","signature":"func (rct realConntracker) SetTCPCloseWaitTimeout(seconds int) error","file":"cmd/kube-proxy/app/conntrack.go","code":"func (rct realConntracker) SetTCPCloseWaitTimeout(seconds int) error {\n\treturn rct.setIntSysCtl(\"nf_conntrack_tcp_timeout_close_wait\", seconds)\n}","line":{"from":91,"to":93}} {"id":100000328,"name":"setIntSysCtl","signature":"func (realConntracker) setIntSysCtl(name string, value int) error","file":"cmd/kube-proxy/app/conntrack.go","code":"func (realConntracker) setIntSysCtl(name string, value int) error {\n\tentry := \"net/netfilter/\" + name\n\n\tsys := sysctl.New()\n\tif val, _ := sys.GetSysctl(entry); val != value \u0026\u0026 val \u003c value {\n\t\tklog.InfoS(\"Set sysctl\", \"entry\", entry, \"value\", value)\n\t\tif err := sys.SetSysctl(entry, value); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":95,"to":106}} {"id":100000329,"name":"isSysFSWritable","signature":"func isSysFSWritable() (bool, error)","file":"cmd/kube-proxy/app/conntrack.go","code":"// isSysFSWritable checks /proc/mounts to see whether sysfs is 'rw' or not.\nfunc isSysFSWritable() (bool, error) {\n\tconst permWritable = \"rw\"\n\tconst sysfsDevice = \"sysfs\"\n\tm := mount.New(\"\" /* default mount path */)\n\tmountPoints, err := m.List()\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to list mount points\")\n\t\treturn false, err\n\t}\n\n\tfor _, mountPoint := range mountPoints {\n\t\tif mountPoint.Type != sysfsDevice {\n\t\t\tcontinue\n\t\t}\n\t\t// Check whether sysfs is 'rw'\n\t\tif len(mountPoint.Opts) \u003e 0 \u0026\u0026 mountPoint.Opts[0] == permWritable {\n\t\t\treturn true, nil\n\t\t}\n\t\tklog.ErrorS(nil, \"Sysfs is not writable\", \"mountPoint\", mountPoint, \"mountOptions\", mountPoint.Opts)\n\t\treturn false, errReadOnlySysFS\n\t}\n\n\treturn false, errors.New(\"no sysfs mounted\")\n}","line":{"from":108,"to":132}} {"id":100000330,"name":"readIntStringFile","signature":"func readIntStringFile(filename string) (int, error)","file":"cmd/kube-proxy/app/conntrack.go","code":"func readIntStringFile(filename string) (int, error) {\n\tb, err := os.ReadFile(filename)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\treturn strconv.Atoi(strings.TrimSpace(string(b)))\n}","line":{"from":134,"to":140}} {"id":100000331,"name":"writeIntStringFile","signature":"func writeIntStringFile(filename string, value int) error","file":"cmd/kube-proxy/app/conntrack.go","code":"func writeIntStringFile(filename string, value int) error {\n\treturn os.WriteFile(filename, []byte(strconv.Itoa(value)), 0640)\n}","line":{"from":142,"to":144}} {"id":100000332,"name":"initForOS","signature":"func initForOS(service bool) error","file":"cmd/kube-proxy/app/init_others.go","code":"func initForOS(service bool) error {\n\treturn nil\n}","line":{"from":26,"to":28}} {"id":100000333,"name":"addOSFlags","signature":"func (o *Options) addOSFlags(fs *pflag.FlagSet)","file":"cmd/kube-proxy/app/init_others.go","code":"func (o *Options) addOSFlags(fs *pflag.FlagSet) {\n}","line":{"from":30,"to":31}} {"id":100000334,"name":"initForOS","signature":"func initForOS(windowsService bool) error","file":"cmd/kube-proxy/app/init_windows.go","code":"func initForOS(windowsService bool) error {\n\tif windowsService {\n\t\treturn service.InitService(serviceName)\n\t}\n\treturn nil\n}","line":{"from":32,"to":37}} {"id":100000335,"name":"addOSFlags","signature":"func (o *Options) addOSFlags(fs *pflag.FlagSet)","file":"cmd/kube-proxy/app/init_windows.go","code":"func (o *Options) addOSFlags(fs *pflag.FlagSet) {\n\tfs.BoolVar(\u0026o.WindowsService, \"windows-service\", o.WindowsService, \"Enable Windows Service Control Manager API integration\")\n\tfs.StringVar(\u0026o.config.Winkernel.SourceVip, \"source-vip\", o.config.Winkernel.SourceVip, \"The IP address of the source VIP for non-DSR.\")\n\tfs.StringVar(\u0026o.config.Winkernel.NetworkName, \"network-name\", o.config.Winkernel.NetworkName, \"The name of the cluster network.\")\n\tfs.BoolVar(\u0026o.config.Winkernel.EnableDSR, \"enable-dsr\", o.config.Winkernel.EnableDSR, \"If true make kube-proxy apply DSR policies for service VIP\")\n\tfs.StringVar(\u0026o.config.Winkernel.RootHnsEndpointName, \"root-hnsendpoint-name\", \"cbr0\", \"The name of the hns endpoint name for root namespace attached to l2bridge\")\n\tfs.BoolVar(\u0026o.config.Winkernel.ForwardHealthCheckVip, \"forward-healthcheck-vip\", o.config.Winkernel.ForwardHealthCheckVip, \"If true forward service VIP for health check port\")\n}","line":{"from":39,"to":46}} {"id":100000336,"name":"init","signature":"func init()","file":"cmd/kube-proxy/app/server.go","code":"func init() {\n\tutilruntime.Must(metricsfeatures.AddFeatureGates(utilfeature.DefaultMutableFeatureGate))\n\tlogsapi.AddFeatureGates(utilfeature.DefaultMutableFeatureGate)\n}","line":{"from":91,"to":94}} {"id":100000337,"name":"AddFlags","signature":"func (o *Options) AddFlags(fs *pflag.FlagSet)","file":"cmd/kube-proxy/app/server.go","code":"// AddFlags adds flags to fs and binds them to options.\nfunc (o *Options) AddFlags(fs *pflag.FlagSet) {\n\to.addOSFlags(fs)\n\n\tfs.StringVar(\u0026o.ConfigFile, \"config\", o.ConfigFile, \"The path to the configuration file.\")\n\tfs.StringVar(\u0026o.WriteConfigTo, \"write-config-to\", o.WriteConfigTo, \"If set, write the default configuration values to this file and exit.\")\n\tfs.StringVar(\u0026o.config.ClientConnection.Kubeconfig, \"kubeconfig\", o.config.ClientConnection.Kubeconfig, \"Path to kubeconfig file with authorization information (the master location can be overridden by the master flag).\")\n\tfs.StringVar(\u0026o.config.ClusterCIDR, \"cluster-cidr\", o.config.ClusterCIDR, \"The CIDR range of pods in the cluster. When configured, traffic sent to a Service cluster IP from outside this range will be masqueraded and traffic sent from pods to an external LoadBalancer IP will be directed to the respective cluster IP instead. \"+\n\t\t\"For dual-stack clusters, a comma-separated list is accepted with at least one CIDR per IP family (IPv4 and IPv6). \"+\n\t\t\"This parameter is ignored if a config file is specified by --config.\")\n\tfs.StringVar(\u0026o.config.ClientConnection.ContentType, \"kube-api-content-type\", o.config.ClientConnection.ContentType, \"Content type of requests sent to apiserver.\")\n\tfs.StringVar(\u0026o.master, \"master\", o.master, \"The address of the Kubernetes API server (overrides any value in kubeconfig)\")\n\tfs.StringVar(\u0026o.hostnameOverride, \"hostname-override\", o.hostnameOverride, \"If non-empty, will use this string as identification instead of the actual hostname.\")\n\tfs.StringVar(\u0026o.config.IPVS.Scheduler, \"ipvs-scheduler\", o.config.IPVS.Scheduler, \"The ipvs scheduler type when proxy mode is ipvs\")\n\tfs.StringVar(\u0026o.config.ShowHiddenMetricsForVersion, \"show-hidden-metrics-for-version\", o.config.ShowHiddenMetricsForVersion,\n\t\t\"The previous version for which you want to show hidden metrics. \"+\n\t\t\t\"Only the previous minor version is meaningful, other values will not be allowed. \"+\n\t\t\t\"The format is \u003cmajor\u003e.\u003cminor\u003e, e.g.: '1.16'. \"+\n\t\t\t\"The purpose of this format is make sure you have the opportunity to notice if the next release hides additional metrics, \"+\n\t\t\t\"rather than being surprised when they are permanently removed in the release after that. \"+\n\t\t\t\"This parameter is ignored if a config file is specified by --config.\")\n\n\tfs.StringSliceVar(\u0026o.config.IPVS.ExcludeCIDRs, \"ipvs-exclude-cidrs\", o.config.IPVS.ExcludeCIDRs, \"A comma-separated list of CIDR's which the ipvs proxier should not touch when cleaning up IPVS rules.\")\n\tfs.StringSliceVar(\u0026o.config.NodePortAddresses, \"nodeport-addresses\", o.config.NodePortAddresses,\n\t\t\"A string slice of values which specify the addresses to use for NodePorts. Values may be valid IP blocks (e.g. 1.2.3.0/24, 1.2.3.4/32). The default empty string slice ([]) means to use all local addresses. This parameter is ignored if a config file is specified by --config.\")\n\n\tfs.BoolVar(\u0026o.CleanupAndExit, \"cleanup\", o.CleanupAndExit, \"If true cleanup iptables and ipvs rules and exit.\")\n\n\tfs.Var(\u0026utilflag.IPVar{Val: \u0026o.config.BindAddress}, \"bind-address\", \"The IP address for the proxy server to serve on (set to '0.0.0.0' for all IPv4 interfaces and '::' for all IPv6 interfaces). This parameter is ignored if a config file is specified by --config.\")\n\tfs.Var(\u0026utilflag.IPPortVar{Val: \u0026o.config.HealthzBindAddress}, \"healthz-bind-address\", \"The IP address with port for the health check server to serve on (set to '0.0.0.0:10256' for all IPv4 interfaces and '[::]:10256' for all IPv6 interfaces). Set empty to disable. This parameter is ignored if a config file is specified by --config.\")\n\tfs.Var(\u0026utilflag.IPPortVar{Val: \u0026o.config.MetricsBindAddress}, \"metrics-bind-address\", \"The IP address with port for the metrics server to serve on (set to '0.0.0.0:10249' for all IPv4 interfaces and '[::]:10249' for all IPv6 interfaces). Set empty to disable. This parameter is ignored if a config file is specified by --config.\")\n\tfs.BoolVar(\u0026o.config.BindAddressHardFail, \"bind-address-hard-fail\", o.config.BindAddressHardFail, \"If true kube-proxy will treat failure to bind to a port as fatal and exit\")\n\tfs.Var(utilflag.PortRangeVar{Val: \u0026o.config.PortRange}, \"proxy-port-range\", \"Range of host ports (beginPort-endPort, single port or beginPort+offset, inclusive) that may be consumed in order to proxy service traffic. If (unspecified, 0, or 0-0) then ports will be randomly chosen.\")\n\tfs.Var(\u0026o.config.Mode, \"proxy-mode\", \"Which proxy mode to use: on Linux this can be 'iptables' (default) or 'ipvs'. On Windows the only supported value is 'kernelspace'.\"+\n\t\t\"This parameter is ignored if a config file is specified by --config.\")\n\tfs.Var(cliflag.NewMapStringBool(\u0026o.config.FeatureGates), \"feature-gates\", \"A set of key=value pairs that describe feature gates for alpha/experimental features. \"+\n\t\t\"Options are:\\n\"+strings.Join(utilfeature.DefaultFeatureGate.KnownFeatures(), \"\\n\")+\"\\n\"+\n\t\t\"This parameter is ignored if a config file is specified by --config.\")\n\n\tfs.Int32Var(\u0026o.healthzPort, \"healthz-port\", o.healthzPort, \"The port to bind the health check server. Use 0 to disable.\")\n\tfs.MarkDeprecated(\"healthz-port\", \"This flag is deprecated and will be removed in a future release. Please use --healthz-bind-address instead.\")\n\tfs.Int32Var(\u0026o.metricsPort, \"metrics-port\", o.metricsPort, \"The port to bind the metrics server. Use 0 to disable.\")\n\tfs.MarkDeprecated(\"metrics-port\", \"This flag is deprecated and will be removed in a future release. Please use --metrics-bind-address instead.\")\n\tfs.Int32Var(o.config.OOMScoreAdj, \"oom-score-adj\", pointer.Int32Deref(o.config.OOMScoreAdj, int32(qos.KubeProxyOOMScoreAdj)), \"The oom-score-adj value for kube-proxy process. Values must be within the range [-1000, 1000]. This parameter is ignored if a config file is specified by --config.\")\n\tfs.Int32Var(o.config.IPTables.MasqueradeBit, \"iptables-masquerade-bit\", pointer.Int32Deref(o.config.IPTables.MasqueradeBit, 14), \"If using the pure iptables proxy, the bit of the fwmark space to mark packets requiring SNAT with. Must be within the range [0, 31].\")\n\tfs.Int32Var(o.config.Conntrack.MaxPerCore, \"conntrack-max-per-core\", *o.config.Conntrack.MaxPerCore,\n\t\t\"Maximum number of NAT connections to track per CPU core (0 to leave the limit as-is and ignore conntrack-min).\")\n\tfs.Int32Var(o.config.Conntrack.Min, \"conntrack-min\", *o.config.Conntrack.Min,\n\t\t\"Minimum number of conntrack entries to allocate, regardless of conntrack-max-per-core (set conntrack-max-per-core=0 to leave the limit as-is).\")\n\tfs.Int32Var(\u0026o.config.ClientConnection.Burst, \"kube-api-burst\", o.config.ClientConnection.Burst, \"Burst to use while talking with kubernetes apiserver\")\n\n\tfs.DurationVar(\u0026o.config.IPTables.SyncPeriod.Duration, \"iptables-sync-period\", o.config.IPTables.SyncPeriod.Duration, \"The maximum interval of how often iptables rules are refreshed (e.g. '5s', '1m', '2h22m'). Must be greater than 0.\")\n\tfs.DurationVar(\u0026o.config.IPTables.MinSyncPeriod.Duration, \"iptables-min-sync-period\", o.config.IPTables.MinSyncPeriod.Duration, \"The minimum interval of how often the iptables rules can be refreshed as endpoints and services change (e.g. '5s', '1m', '2h22m').\")\n\tfs.DurationVar(\u0026o.config.IPVS.SyncPeriod.Duration, \"ipvs-sync-period\", o.config.IPVS.SyncPeriod.Duration, \"The maximum interval of how often ipvs rules are refreshed (e.g. '5s', '1m', '2h22m'). Must be greater than 0.\")\n\tfs.DurationVar(\u0026o.config.IPVS.MinSyncPeriod.Duration, \"ipvs-min-sync-period\", o.config.IPVS.MinSyncPeriod.Duration, \"The minimum interval of how often the ipvs rules can be refreshed as endpoints and services change (e.g. '5s', '1m', '2h22m').\")\n\tfs.DurationVar(\u0026o.config.IPVS.TCPTimeout.Duration, \"ipvs-tcp-timeout\", o.config.IPVS.TCPTimeout.Duration, \"The timeout for idle IPVS TCP connections, 0 to leave as-is. (e.g. '5s', '1m', '2h22m').\")\n\tfs.DurationVar(\u0026o.config.IPVS.TCPFinTimeout.Duration, \"ipvs-tcpfin-timeout\", o.config.IPVS.TCPFinTimeout.Duration, \"The timeout for IPVS TCP connections after receiving a FIN packet, 0 to leave as-is. (e.g. '5s', '1m', '2h22m').\")\n\tfs.DurationVar(\u0026o.config.IPVS.UDPTimeout.Duration, \"ipvs-udp-timeout\", o.config.IPVS.UDPTimeout.Duration, \"The timeout for IPVS UDP packets, 0 to leave as-is. (e.g. '5s', '1m', '2h22m').\")\n\tfs.DurationVar(\u0026o.config.Conntrack.TCPEstablishedTimeout.Duration, \"conntrack-tcp-timeout-established\", o.config.Conntrack.TCPEstablishedTimeout.Duration, \"Idle timeout for established TCP connections (0 to leave as-is)\")\n\tfs.DurationVar(\n\t\t\u0026o.config.Conntrack.TCPCloseWaitTimeout.Duration, \"conntrack-tcp-timeout-close-wait\",\n\t\to.config.Conntrack.TCPCloseWaitTimeout.Duration,\n\t\t\"NAT timeout for TCP connections in the CLOSE_WAIT state\")\n\tfs.DurationVar(\u0026o.config.ConfigSyncPeriod.Duration, \"config-sync-period\", o.config.ConfigSyncPeriod.Duration, \"How often configuration from the apiserver is refreshed. Must be greater than 0.\")\n\n\tfs.BoolVar(\u0026o.config.IPVS.StrictARP, \"ipvs-strict-arp\", o.config.IPVS.StrictARP, \"Enable strict ARP by setting arp_ignore to 1 and arp_announce to 2\")\n\tfs.BoolVar(\u0026o.config.IPTables.MasqueradeAll, \"masquerade-all\", o.config.IPTables.MasqueradeAll, \"If using the pure iptables proxy, SNAT all traffic sent via Service cluster IPs (this not commonly needed)\")\n\tfs.BoolVar(o.config.IPTables.LocalhostNodePorts, \"iptables-localhost-nodeports\", pointer.BoolDeref(o.config.IPTables.LocalhostNodePorts, true), \"If false Kube-proxy will disable the legacy behavior of allowing NodePort services to be accessed via localhost, This only applies to iptables mode and ipv4.\")\n\tfs.BoolVar(\u0026o.config.EnableProfiling, \"profiling\", o.config.EnableProfiling, \"If true enables profiling via web interface on /debug/pprof handler. This parameter is ignored if a config file is specified by --config.\")\n\n\tfs.Float32Var(\u0026o.config.ClientConnection.QPS, \"kube-api-qps\", o.config.ClientConnection.QPS, \"QPS to use while talking with kubernetes apiserver\")\n\tfs.Var(\u0026o.config.DetectLocalMode, \"detect-local-mode\", \"Mode to use to detect local traffic. This parameter is ignored if a config file is specified by --config.\")\n\tfs.StringVar(\u0026o.config.DetectLocal.BridgeInterface, \"pod-bridge-interface\", o.config.DetectLocal.BridgeInterface, \"A bridge interface name in the cluster. Kube-proxy considers traffic as local if originating from an interface which matches the value. This argument should be set if DetectLocalMode is set to BridgeInterface.\")\n\tfs.StringVar(\u0026o.config.DetectLocal.InterfaceNamePrefix, \"pod-interface-name-prefix\", o.config.DetectLocal.InterfaceNamePrefix, \"An interface prefix in the cluster. Kube-proxy considers traffic as local if originating from interfaces that match the given prefix. This argument should be set if DetectLocalMode is set to InterfaceNamePrefix.\")\n}","line":{"from":137,"to":211}} {"id":100000338,"name":"NewOptions","signature":"func NewOptions() *Options","file":"cmd/kube-proxy/app/server.go","code":"// NewOptions returns initialized Options\nfunc NewOptions() *Options {\n\treturn \u0026Options{\n\t\tconfig: new(kubeproxyconfig.KubeProxyConfiguration),\n\t\thealthzPort: ports.ProxyHealthzPort,\n\t\tmetricsPort: ports.ProxyStatusPort,\n\t\terrCh: make(chan error),\n\t}\n}","line":{"from":213,"to":221}} {"id":100000339,"name":"Complete","signature":"func (o *Options) Complete() error","file":"cmd/kube-proxy/app/server.go","code":"// Complete completes all the required options.\nfunc (o *Options) Complete() error {\n\tif len(o.ConfigFile) == 0 \u0026\u0026 len(o.WriteConfigTo) == 0 {\n\t\tklog.InfoS(\"Warning, all flags other than --config, --write-config-to, and --cleanup are deprecated, please begin using a config file ASAP\")\n\t\to.config.HealthzBindAddress = addressFromDeprecatedFlags(o.config.HealthzBindAddress, o.healthzPort)\n\t\to.config.MetricsBindAddress = addressFromDeprecatedFlags(o.config.MetricsBindAddress, o.metricsPort)\n\t}\n\n\t// Load the config file here in Complete, so that Validate validates the fully-resolved config.\n\tif len(o.ConfigFile) \u003e 0 {\n\t\tc, err := o.loadConfigFromFile(o.ConfigFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\to.config = c\n\n\t\tif err := o.initWatcher(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := o.processHostnameOverrideFlag(); err != nil {\n\t\treturn err\n\t}\n\n\treturn utilfeature.DefaultMutableFeatureGate.SetFromMap(o.config.FeatureGates)\n}","line":{"from":223,"to":249}} {"id":100000340,"name":"initWatcher","signature":"func (o *Options) initWatcher() error","file":"cmd/kube-proxy/app/server.go","code":"// Creates a new filesystem watcher and adds watches for the config file.\nfunc (o *Options) initWatcher() error {\n\tfswatcher := filesystem.NewFsnotifyWatcher()\n\terr := fswatcher.Init(o.eventHandler, o.errorHandler)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = fswatcher.AddWatch(o.ConfigFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\to.watcher = fswatcher\n\treturn nil\n}","line":{"from":251,"to":264}} {"id":100000341,"name":"eventHandler","signature":"func (o *Options) eventHandler(ent fsnotify.Event)","file":"cmd/kube-proxy/app/server.go","code":"func (o *Options) eventHandler(ent fsnotify.Event) {\n\tif ent.Has(fsnotify.Write) || ent.Has(fsnotify.Rename) {\n\t\t// error out when ConfigFile is updated\n\t\to.errCh \u003c- fmt.Errorf(\"content of the proxy server's configuration file was updated\")\n\t\treturn\n\t}\n\to.errCh \u003c- nil\n}","line":{"from":266,"to":273}} {"id":100000342,"name":"errorHandler","signature":"func (o *Options) errorHandler(err error)","file":"cmd/kube-proxy/app/server.go","code":"func (o *Options) errorHandler(err error) {\n\to.errCh \u003c- err\n}","line":{"from":275,"to":277}} {"id":100000343,"name":"processHostnameOverrideFlag","signature":"func (o *Options) processHostnameOverrideFlag() error","file":"cmd/kube-proxy/app/server.go","code":"// processHostnameOverrideFlag processes hostname-override flag\nfunc (o *Options) processHostnameOverrideFlag() error {\n\t// Check if hostname-override flag is set and use value since configFile always overrides\n\tif len(o.hostnameOverride) \u003e 0 {\n\t\thostName := strings.TrimSpace(o.hostnameOverride)\n\t\tif len(hostName) == 0 {\n\t\t\treturn fmt.Errorf(\"empty hostname-override is invalid\")\n\t\t}\n\t\to.config.HostnameOverride = strings.ToLower(hostName)\n\t}\n\n\treturn nil\n}","line":{"from":279,"to":291}} {"id":100000344,"name":"Validate","signature":"func (o *Options) Validate() error","file":"cmd/kube-proxy/app/server.go","code":"// Validate validates all the required options.\nfunc (o *Options) Validate() error {\n\tif errs := validation.Validate(o.config); len(errs) != 0 {\n\t\treturn errs.ToAggregate()\n\t}\n\n\treturn nil\n}","line":{"from":293,"to":300}} {"id":100000345,"name":"Run","signature":"func (o *Options) Run() error","file":"cmd/kube-proxy/app/server.go","code":"// Run runs the specified ProxyServer.\nfunc (o *Options) Run() error {\n\tdefer close(o.errCh)\n\tif len(o.WriteConfigTo) \u003e 0 {\n\t\treturn o.writeConfigFile()\n\t}\n\n\tif o.CleanupAndExit {\n\t\treturn cleanupAndExit()\n\t}\n\n\tproxyServer, err := NewProxyServer(o)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.proxyServer = proxyServer\n\treturn o.runLoop()\n}","line":{"from":302,"to":320}} {"id":100000346,"name":"runLoop","signature":"func (o *Options) runLoop() error","file":"cmd/kube-proxy/app/server.go","code":"// runLoop will watch on the update change of the proxy server's configuration file.\n// Return an error when updated\nfunc (o *Options) runLoop() error {\n\tif o.watcher != nil {\n\t\to.watcher.Run()\n\t}\n\n\t// run the proxy in goroutine\n\tgo func() {\n\t\terr := o.proxyServer.Run()\n\t\to.errCh \u003c- err\n\t}()\n\n\tfor {\n\t\terr := \u003c-o.errCh\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}","line":{"from":322,"to":341}} {"id":100000347,"name":"writeConfigFile","signature":"func (o *Options) writeConfigFile() (err error)","file":"cmd/kube-proxy/app/server.go","code":"func (o *Options) writeConfigFile() (err error) {\n\tconst mediaType = runtime.ContentTypeYAML\n\tinfo, ok := runtime.SerializerInfoForMediaType(proxyconfigscheme.Codecs.SupportedMediaTypes(), mediaType)\n\tif !ok {\n\t\treturn fmt.Errorf(\"unable to locate encoder -- %q is not a supported media type\", mediaType)\n\t}\n\n\tencoder := proxyconfigscheme.Codecs.EncoderForVersion(info.Serializer, v1alpha1.SchemeGroupVersion)\n\n\tconfigFile, err := os.Create(o.WriteConfigTo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\tferr := configFile.Close()\n\t\tif ferr != nil \u0026\u0026 err == nil {\n\t\t\terr = ferr\n\t\t}\n\t}()\n\n\tif err = encoder.Encode(o.config, configFile); err != nil {\n\t\treturn err\n\t}\n\n\tklog.InfoS(\"Wrote configuration\", \"file\", o.WriteConfigTo)\n\n\treturn nil\n}","line":{"from":343,"to":371}} {"id":100000348,"name":"addressFromDeprecatedFlags","signature":"func addressFromDeprecatedFlags(addr string, port int32) string","file":"cmd/kube-proxy/app/server.go","code":"// addressFromDeprecatedFlags returns server address from flags\n// passed on the command line based on the following rules:\n// 1. If port is 0, disable the server (e.g. set address to empty).\n// 2. Otherwise, set the port portion of the config accordingly.\nfunc addressFromDeprecatedFlags(addr string, port int32) string {\n\tif port == 0 {\n\t\treturn \"\"\n\t}\n\treturn proxyutil.AppendPortIfNeeded(addr, port)\n}","line":{"from":373,"to":382}} {"id":100000349,"name":"newLenientSchemeAndCodecs","signature":"func newLenientSchemeAndCodecs() (*runtime.Scheme, *serializer.CodecFactory, error)","file":"cmd/kube-proxy/app/server.go","code":"// newLenientSchemeAndCodecs returns a scheme that has only v1alpha1 registered into\n// it and a CodecFactory with strict decoding disabled.\nfunc newLenientSchemeAndCodecs() (*runtime.Scheme, *serializer.CodecFactory, error) {\n\tlenientScheme := runtime.NewScheme()\n\tif err := kubeproxyconfig.AddToScheme(lenientScheme); err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to add kube-proxy config API to lenient scheme: %v\", err)\n\t}\n\tif err := kubeproxyconfigv1alpha1.AddToScheme(lenientScheme); err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to add kube-proxy config v1alpha1 API to lenient scheme: %v\", err)\n\t}\n\tlenientCodecs := serializer.NewCodecFactory(lenientScheme, serializer.DisableStrict)\n\treturn lenientScheme, \u0026lenientCodecs, nil\n}","line":{"from":384,"to":396}} {"id":100000350,"name":"loadConfigFromFile","signature":"func (o *Options) loadConfigFromFile(file string) (*kubeproxyconfig.KubeProxyConfiguration, error)","file":"cmd/kube-proxy/app/server.go","code":"// loadConfigFromFile loads the contents of file and decodes it as a\n// KubeProxyConfiguration object.\nfunc (o *Options) loadConfigFromFile(file string) (*kubeproxyconfig.KubeProxyConfiguration, error) {\n\tdata, err := os.ReadFile(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn o.loadConfig(data)\n}","line":{"from":398,"to":407}} {"id":100000351,"name":"loadConfig","signature":"func (o *Options) loadConfig(data []byte) (*kubeproxyconfig.KubeProxyConfiguration, error)","file":"cmd/kube-proxy/app/server.go","code":"// loadConfig decodes a serialized KubeProxyConfiguration to the internal type.\nfunc (o *Options) loadConfig(data []byte) (*kubeproxyconfig.KubeProxyConfiguration, error) {\n\n\tconfigObj, gvk, err := proxyconfigscheme.Codecs.UniversalDecoder().Decode(data, nil, nil)\n\tif err != nil {\n\t\t// Try strict decoding first. If that fails decode with a lenient\n\t\t// decoder, which has only v1alpha1 registered, and log a warning.\n\t\t// The lenient path is to be dropped when support for v1alpha1 is dropped.\n\t\tif !runtime.IsStrictDecodingError(err) {\n\t\t\treturn nil, fmt.Errorf(\"failed to decode: %w\", err)\n\t\t}\n\n\t\t_, lenientCodecs, lenientErr := newLenientSchemeAndCodecs()\n\t\tif lenientErr != nil {\n\t\t\treturn nil, lenientErr\n\t\t}\n\n\t\tconfigObj, gvk, lenientErr = lenientCodecs.UniversalDecoder().Decode(data, nil, nil)\n\t\tif lenientErr != nil {\n\t\t\t// Lenient decoding failed with the current version, return the\n\t\t\t// original strict error.\n\t\t\treturn nil, fmt.Errorf(\"failed lenient decoding: %v\", err)\n\t\t}\n\n\t\t// Continue with the v1alpha1 object that was decoded leniently, but emit a warning.\n\t\tklog.InfoS(\"Using lenient decoding as strict decoding failed\", \"err\", err)\n\t}\n\n\tproxyConfig, ok := configObj.(*kubeproxyconfig.KubeProxyConfiguration)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"got unexpected config type: %v\", gvk)\n\t}\n\treturn proxyConfig, nil\n}","line":{"from":409,"to":442}} {"id":100000352,"name":"ApplyDefaults","signature":"func (o *Options) ApplyDefaults(in *kubeproxyconfig.KubeProxyConfiguration) (*kubeproxyconfig.KubeProxyConfiguration, error)","file":"cmd/kube-proxy/app/server.go","code":"// ApplyDefaults applies the default values to Options.\nfunc (o *Options) ApplyDefaults(in *kubeproxyconfig.KubeProxyConfiguration) (*kubeproxyconfig.KubeProxyConfiguration, error) {\n\texternal, err := proxyconfigscheme.Scheme.ConvertToVersion(in, v1alpha1.SchemeGroupVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tproxyconfigscheme.Scheme.Default(external)\n\n\tinternal, err := proxyconfigscheme.Scheme.ConvertToVersion(external, kubeproxyconfig.SchemeGroupVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := internal.(*kubeproxyconfig.KubeProxyConfiguration)\n\n\treturn out, nil\n}","line":{"from":444,"to":461}} {"id":100000353,"name":"NewProxyCommand","signature":"func NewProxyCommand() *cobra.Command","file":"cmd/kube-proxy/app/server.go","code":"// NewProxyCommand creates a *cobra.Command object with default parameters\nfunc NewProxyCommand() *cobra.Command {\n\topts := NewOptions()\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"kube-proxy\",\n\t\tLong: `The Kubernetes network proxy runs on each node. This\nreflects services as defined in the Kubernetes API on each node and can do simple\nTCP, UDP, and SCTP stream forwarding or round robin TCP, UDP, and SCTP forwarding across a set of backends.\nService cluster IPs and ports are currently found through Docker-links-compatible\nenvironment variables specifying ports opened by the service proxy. There is an optional\naddon that provides cluster DNS for these cluster IPs. The user must create a service\nwith the apiserver API to configure the proxy.`,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tverflag.PrintAndExitIfRequested()\n\t\t\tcliflag.PrintFlags(cmd.Flags())\n\n\t\t\tif err := initForOS(opts.WindowsService); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed os init: %w\", err)\n\t\t\t}\n\n\t\t\tif err := opts.Complete(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed complete: %w\", err)\n\t\t\t}\n\n\t\t\tif err := opts.Validate(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed validate: %w\", err)\n\t\t\t}\n\t\t\t// add feature enablement metrics\n\t\t\tutilfeature.DefaultMutableFeatureGate.AddMetrics()\n\t\t\tif err := opts.Run(); err != nil {\n\t\t\t\tklog.ErrorS(err, \"Error running ProxyServer\")\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t\tArgs: func(cmd *cobra.Command, args []string) error {\n\t\t\tfor _, arg := range args {\n\t\t\t\tif len(arg) \u003e 0 {\n\t\t\t\t\treturn fmt.Errorf(\"%q does not take any arguments, got %q\", cmd.CommandPath(), args)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tvar err error\n\topts.config, err = opts.ApplyDefaults(opts.config)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Unable to create flag defaults\")\n\t\t// ACTION REQUIRED: Exit code changed from 255 to 1\n\t\tos.Exit(1)\n\t}\n\n\tfs := cmd.Flags()\n\topts.AddFlags(fs)\n\tfs.AddGoFlagSet(goflag.CommandLine) // for --boot-id-file and --machine-id-file\n\n\t_ = cmd.MarkFlagFilename(\"config\", \"yaml\", \"yml\", \"json\")\n\n\treturn cmd\n}","line":{"from":463,"to":525}} {"id":100000354,"name":"createClients","signature":"func createClients(config componentbaseconfig.ClientConnectionConfiguration, masterOverride string) (clientset.Interface, v1core.EventsGetter, error)","file":"cmd/kube-proxy/app/server.go","code":"// createClients creates a kube client and an event client from the given config and masterOverride.\n// TODO remove masterOverride when CLI flags are removed.\nfunc createClients(config componentbaseconfig.ClientConnectionConfiguration, masterOverride string) (clientset.Interface, v1core.EventsGetter, error) {\n\tvar kubeConfig *rest.Config\n\tvar err error\n\n\tif len(config.Kubeconfig) == 0 \u0026\u0026 len(masterOverride) == 0 {\n\t\tklog.InfoS(\"Neither kubeconfig file nor master URL was specified, falling back to in-cluster config\")\n\t\tkubeConfig, err = rest.InClusterConfig()\n\t} else {\n\t\t// This creates a client, first loading any specified kubeconfig\n\t\t// file, and then overriding the Master flag, if non-empty.\n\t\tkubeConfig, err = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(\n\t\t\t\u0026clientcmd.ClientConfigLoadingRules{ExplicitPath: config.Kubeconfig},\n\t\t\t\u0026clientcmd.ConfigOverrides{ClusterInfo: clientcmdapi.Cluster{Server: masterOverride}}).ClientConfig()\n\t}\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tkubeConfig.AcceptContentTypes = config.AcceptContentTypes\n\tkubeConfig.ContentType = config.ContentType\n\tkubeConfig.QPS = config.QPS\n\tkubeConfig.Burst = int(config.Burst)\n\n\tclient, err := clientset.NewForConfig(kubeConfig)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\teventClient, err := clientset.NewForConfig(kubeConfig)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn client, eventClient.CoreV1(), nil\n}","line":{"from":553,"to":589}} {"id":100000355,"name":"serveHealthz","signature":"func serveHealthz(hz healthcheck.ProxierHealthUpdater, errCh chan error)","file":"cmd/kube-proxy/app/server.go","code":"func serveHealthz(hz healthcheck.ProxierHealthUpdater, errCh chan error) {\n\tif hz == nil {\n\t\treturn\n\t}\n\n\tfn := func() {\n\t\terr := hz.Run()\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Healthz server failed\")\n\t\t\tif errCh != nil {\n\t\t\t\terrCh \u003c- fmt.Errorf(\"healthz server failed: %v\", err)\n\t\t\t\t// if in hardfail mode, never retry again\n\t\t\t\tblockCh := make(chan error)\n\t\t\t\t\u003c-blockCh\n\t\t\t}\n\t\t} else {\n\t\t\tklog.ErrorS(nil, \"Healthz server returned without error\")\n\t\t}\n\t}\n\tgo wait.Until(fn, 5*time.Second, wait.NeverStop)\n}","line":{"from":591,"to":611}} {"id":100000356,"name":"serveMetrics","signature":"func serveMetrics(bindAddress string, proxyMode kubeproxyconfig.ProxyMode, enableProfiling bool, errCh chan error)","file":"cmd/kube-proxy/app/server.go","code":"func serveMetrics(bindAddress string, proxyMode kubeproxyconfig.ProxyMode, enableProfiling bool, errCh chan error) {\n\tif len(bindAddress) == 0 {\n\t\treturn\n\t}\n\n\tproxyMux := mux.NewPathRecorderMux(\"kube-proxy\")\n\thealthz.InstallHandler(proxyMux)\n\tif utilfeature.DefaultFeatureGate.Enabled(metricsfeatures.ComponentSLIs) {\n\t\tslis.SLIMetricsWithReset{}.Install(proxyMux)\n\t}\n\tproxyMux.HandleFunc(\"/proxyMode\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"text/plain; charset=utf-8\")\n\t\tw.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\t\tfmt.Fprintf(w, \"%s\", proxyMode)\n\t})\n\n\tproxyMux.Handle(\"/metrics\", legacyregistry.Handler())\n\n\tif enableProfiling {\n\t\troutes.Profiling{}.Install(proxyMux)\n\t\troutes.DebugFlags{}.Install(proxyMux, \"v\", routes.StringFlagPutHandler(logs.GlogSetter))\n\t}\n\n\tconfigz.InstallHandler(proxyMux)\n\n\tfn := func() {\n\t\terr := http.ListenAndServe(bindAddress, proxyMux)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"starting metrics server failed: %v\", err)\n\t\t\tutilruntime.HandleError(err)\n\t\t\tif errCh != nil {\n\t\t\t\terrCh \u003c- err\n\t\t\t\t// if in hardfail mode, never retry again\n\t\t\t\tblockCh := make(chan error)\n\t\t\t\t\u003c-blockCh\n\t\t\t}\n\t\t}\n\t}\n\tgo wait.Until(fn, 5*time.Second, wait.NeverStop)\n}","line":{"from":613,"to":652}} {"id":100000357,"name":"Run","signature":"func (s *ProxyServer) Run() error","file":"cmd/kube-proxy/app/server.go","code":"// Run runs the specified ProxyServer. This should never exit (unless CleanupAndExit is set).\n// TODO: At the moment, Run() cannot return a nil error, otherwise it's caller will never exit. Update callers of Run to handle nil errors.\nfunc (s *ProxyServer) Run() error {\n\t// To help debugging, immediately log version\n\tklog.InfoS(\"Version info\", \"version\", version.Get())\n\n\tklog.InfoS(\"Golang settings\", \"GOGC\", os.Getenv(\"GOGC\"), \"GOMAXPROCS\", os.Getenv(\"GOMAXPROCS\"), \"GOTRACEBACK\", os.Getenv(\"GOTRACEBACK\"))\n\n\t// TODO(vmarmol): Use container config for this.\n\tvar oomAdjuster *oom.OOMAdjuster\n\tif s.OOMScoreAdj != nil {\n\t\toomAdjuster = oom.NewOOMAdjuster()\n\t\tif err := oomAdjuster.ApplyOOMScoreAdj(0, int(*s.OOMScoreAdj)); err != nil {\n\t\t\tklog.V(2).InfoS(\"Failed to apply OOMScore\", \"err\", err)\n\t\t}\n\t}\n\n\tif s.Broadcaster != nil \u0026\u0026 s.EventClient != nil {\n\t\tstopCh := make(chan struct{})\n\t\ts.Broadcaster.StartRecordingToSink(stopCh)\n\t}\n\n\t// TODO(thockin): make it possible for healthz and metrics to be on the same port.\n\n\tvar errCh chan error\n\tif s.BindAddressHardFail {\n\t\terrCh = make(chan error)\n\t}\n\n\t// Start up a healthz server if requested\n\tserveHealthz(s.HealthzServer, errCh)\n\n\t// Start up a metrics server if requested\n\tserveMetrics(s.MetricsBindAddress, s.ProxyMode, s.EnableProfiling, errCh)\n\n\t// Tune conntrack, if requested\n\t// Conntracker is always nil for windows\n\tif s.Conntracker != nil {\n\t\tmax, err := getConntrackMax(s.ConntrackConfiguration)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif max \u003e 0 {\n\t\t\terr := s.Conntracker.SetMax(max)\n\t\t\tif err != nil {\n\t\t\t\tif err != errReadOnlySysFS {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t// errReadOnlySysFS is caused by a known docker issue (https://github.com/docker/docker/issues/24000),\n\t\t\t\t// the only remediation we know is to restart the docker daemon.\n\t\t\t\t// Here we'll send an node event with specific reason and message, the\n\t\t\t\t// administrator should decide whether and how to handle this issue,\n\t\t\t\t// whether to drain the node and restart docker. Occurs in other container runtimes\n\t\t\t\t// as well.\n\t\t\t\t// TODO(random-liu): Remove this when the docker bug is fixed.\n\t\t\t\tconst message = \"CRI error: /sys is read-only: \" +\n\t\t\t\t\t\"cannot modify conntrack limits, problems may arise later (If running Docker, see docker issue #24000)\"\n\t\t\t\ts.Recorder.Eventf(s.NodeRef, nil, api.EventTypeWarning, err.Error(), \"StartKubeProxy\", message)\n\t\t\t}\n\t\t}\n\n\t\tif s.ConntrackConfiguration.TCPEstablishedTimeout != nil \u0026\u0026 s.ConntrackConfiguration.TCPEstablishedTimeout.Duration \u003e 0 {\n\t\t\ttimeout := int(s.ConntrackConfiguration.TCPEstablishedTimeout.Duration / time.Second)\n\t\t\tif err := s.Conntracker.SetTCPEstablishedTimeout(timeout); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tif s.ConntrackConfiguration.TCPCloseWaitTimeout != nil \u0026\u0026 s.ConntrackConfiguration.TCPCloseWaitTimeout.Duration \u003e 0 {\n\t\t\ttimeout := int(s.ConntrackConfiguration.TCPCloseWaitTimeout.Duration / time.Second)\n\t\t\tif err := s.Conntracker.SetTCPCloseWaitTimeout(timeout); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tnoProxyName, err := labels.NewRequirement(apis.LabelServiceProxyName, selection.DoesNotExist, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnoHeadlessEndpoints, err := labels.NewRequirement(v1.IsHeadlessService, selection.DoesNotExist, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlabelSelector := labels.NewSelector()\n\tlabelSelector = labelSelector.Add(*noProxyName, *noHeadlessEndpoints)\n\n\t// Make informers that filter out objects that want a non-default service proxy.\n\tinformerFactory := informers.NewSharedInformerFactoryWithOptions(s.Client, s.ConfigSyncPeriod,\n\t\tinformers.WithTweakListOptions(func(options *metav1.ListOptions) {\n\t\t\toptions.LabelSelector = labelSelector.String()\n\t\t}))\n\n\t// Create configs (i.e. Watches for Services and EndpointSlices)\n\t// Note: RegisterHandler() calls need to happen before creation of Sources because sources\n\t// only notify on changes, and the initial update (on process start) may be lost if no handlers\n\t// are registered yet.\n\tserviceConfig := config.NewServiceConfig(informerFactory.Core().V1().Services(), s.ConfigSyncPeriod)\n\tserviceConfig.RegisterEventHandler(s.Proxier)\n\tgo serviceConfig.Run(wait.NeverStop)\n\n\tendpointSliceConfig := config.NewEndpointSliceConfig(informerFactory.Discovery().V1().EndpointSlices(), s.ConfigSyncPeriod)\n\tendpointSliceConfig.RegisterEventHandler(s.Proxier)\n\tgo endpointSliceConfig.Run(wait.NeverStop)\n\n\t// This has to start after the calls to NewServiceConfig because that\n\t// function must configure its shared informer event handlers first.\n\tinformerFactory.Start(wait.NeverStop)\n\n\t// Make an informer that selects for our nodename.\n\tcurrentNodeInformerFactory := informers.NewSharedInformerFactoryWithOptions(s.Client, s.ConfigSyncPeriod,\n\t\tinformers.WithTweakListOptions(func(options *metav1.ListOptions) {\n\t\t\toptions.FieldSelector = fields.OneTermEqualSelector(\"metadata.name\", s.NodeRef.Name).String()\n\t\t}))\n\tnodeConfig := config.NewNodeConfig(currentNodeInformerFactory.Core().V1().Nodes(), s.ConfigSyncPeriod)\n\t// https://issues.k8s.io/111321\n\tif s.localDetectorMode == kubeproxyconfig.LocalModeNodeCIDR {\n\t\tnodeConfig.RegisterEventHandler(proxy.NewNodePodCIDRHandler(s.podCIDRs))\n\t}\n\tnodeConfig.RegisterEventHandler(s.Proxier)\n\n\tgo nodeConfig.Run(wait.NeverStop)\n\n\t// This has to start after the calls to NewNodeConfig because that must\n\t// configure the shared informer event handler first.\n\tcurrentNodeInformerFactory.Start(wait.NeverStop)\n\n\t// Birth Cry after the birth is successful\n\ts.birthCry()\n\n\tgo s.Proxier.SyncLoop()\n\n\treturn \u003c-errCh\n}","line":{"from":654,"to":789}} {"id":100000358,"name":"birthCry","signature":"func (s *ProxyServer) birthCry()","file":"cmd/kube-proxy/app/server.go","code":"func (s *ProxyServer) birthCry() {\n\ts.Recorder.Eventf(s.NodeRef, nil, api.EventTypeNormal, \"Starting\", \"StartKubeProxy\", \"\")\n}","line":{"from":791,"to":793}} {"id":100000359,"name":"getConntrackMax","signature":"func getConntrackMax(config kubeproxyconfig.KubeProxyConntrackConfiguration) (int, error)","file":"cmd/kube-proxy/app/server.go","code":"func getConntrackMax(config kubeproxyconfig.KubeProxyConntrackConfiguration) (int, error) {\n\tif config.MaxPerCore != nil \u0026\u0026 *config.MaxPerCore \u003e 0 {\n\t\tfloor := 0\n\t\tif config.Min != nil {\n\t\t\tfloor = int(*config.Min)\n\t\t}\n\t\tscaled := int(*config.MaxPerCore) * detectNumCPU()\n\t\tif scaled \u003e floor {\n\t\t\tklog.V(3).InfoS(\"GetConntrackMax: using scaled conntrack-max-per-core\")\n\t\t\treturn scaled, nil\n\t\t}\n\t\tklog.V(3).InfoS(\"GetConntrackMax: using conntrack-min\")\n\t\treturn floor, nil\n\t}\n\treturn 0, nil\n}","line":{"from":795,"to":810}} {"id":100000360,"name":"detectNodeIP","signature":"func detectNodeIP(client clientset.Interface, hostname, bindAddress string) net.IP","file":"cmd/kube-proxy/app/server.go","code":"// detectNodeIP returns the nodeIP used by the proxier\n// The order of precedence is:\n// 1. config.bindAddress if bindAddress is not 0.0.0.0 or ::\n// 2. the primary IP from the Node object, if set\n// 3. if no IP is found it defaults to 127.0.0.1 and IPv4\nfunc detectNodeIP(client clientset.Interface, hostname, bindAddress string) net.IP {\n\tnodeIP := netutils.ParseIPSloppy(bindAddress)\n\tif nodeIP.IsUnspecified() {\n\t\tnodeIP = utilnode.GetNodeIP(client, hostname)\n\t}\n\tif nodeIP == nil {\n\t\tklog.InfoS(\"Can't determine this node's IP, assuming 127.0.0.1; if this is incorrect, please set the --bind-address flag\")\n\t\tnodeIP = netutils.ParseIPSloppy(\"127.0.0.1\")\n\t}\n\treturn nodeIP\n}","line":{"from":812,"to":827}} {"id":100000361,"name":"nodeIPTuple","signature":"func nodeIPTuple(bindAddress string) [2]net.IP","file":"cmd/kube-proxy/app/server.go","code":"// nodeIPTuple takes an addresses and return a tuple (ipv4,ipv6)\n// The returned tuple is guaranteed to have the order (ipv4,ipv6). The address NOT of the passed address\n// will have \"any\" address (0.0.0.0 or ::) inserted.\nfunc nodeIPTuple(bindAddress string) [2]net.IP {\n\tnodes := [2]net.IP{net.IPv4zero, net.IPv6zero}\n\n\tadr := netutils.ParseIPSloppy(bindAddress)\n\tif netutils.IsIPv6(adr) {\n\t\tnodes[1] = adr\n\t} else {\n\t\tnodes[0] = adr\n\t}\n\n\treturn nodes\n}","line":{"from":829,"to":843}} {"id":100000362,"name":"NewProxyServer","signature":"func NewProxyServer(o *Options) (*ProxyServer, error)","file":"cmd/kube-proxy/app/server_others.go","code":"// NewProxyServer returns a new ProxyServer.\nfunc NewProxyServer(o *Options) (*ProxyServer, error) {\n\treturn newProxyServer(o.config, o.master)\n}","line":{"from":73,"to":76}} {"id":100000363,"name":"newProxyServer","signature":"func newProxyServer(","file":"cmd/kube-proxy/app/server_others.go","code":"func newProxyServer(\n\tconfig *proxyconfigapi.KubeProxyConfiguration,\n\tmaster string) (*ProxyServer, error) {\n\n\tif config == nil {\n\t\treturn nil, errors.New(\"config is required\")\n\t}\n\n\tif c, err := configz.New(proxyconfigapi.GroupName); err == nil {\n\t\tc.Set(config)\n\t} else {\n\t\treturn nil, fmt.Errorf(\"unable to register configz: %s\", err)\n\t}\n\n\tvar ipvsInterface utilipvs.Interface\n\tvar ipsetInterface utilipset.Interface\n\n\tif len(config.ShowHiddenMetricsForVersion) \u003e 0 {\n\t\tmetrics.SetShowHidden()\n\t}\n\n\thostname, err := nodeutil.GetHostname(config.HostnameOverride)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient, eventClient, err := createClients(config.ClientConnection, master)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnodeIP := detectNodeIP(client, hostname, config.BindAddress)\n\tklog.InfoS(\"Detected node IP\", \"address\", nodeIP.String())\n\n\t// Create event recorder\n\teventBroadcaster := events.NewBroadcaster(\u0026events.EventSinkImpl{Interface: client.EventsV1()})\n\trecorder := eventBroadcaster.NewRecorder(scheme.Scheme, \"kube-proxy\")\n\n\tnodeRef := \u0026v1.ObjectReference{\n\t\tKind: \"Node\",\n\t\tName: hostname,\n\t\tUID: types.UID(hostname),\n\t\tNamespace: \"\",\n\t}\n\n\tvar healthzServer healthcheck.ProxierHealthUpdater\n\tif len(config.HealthzBindAddress) \u003e 0 {\n\t\thealthzServer = healthcheck.NewProxierHealthServer(config.HealthzBindAddress, 2*config.IPTables.SyncPeriod.Duration, recorder, nodeRef)\n\t}\n\n\tvar proxier proxy.Provider\n\tvar detectLocalMode proxyconfigapi.LocalMode\n\n\tproxyMode := getProxyMode(config.Mode)\n\tdetectLocalMode, err = getDetectLocalMode(config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot determine detect-local-mode: %v\", err)\n\t}\n\n\tvar nodeInfo *v1.Node\n\tpodCIDRs := []string{}\n\tif detectLocalMode == proxyconfigapi.LocalModeNodeCIDR {\n\t\tklog.InfoS(\"Watching for node, awaiting podCIDR allocation\", \"hostname\", hostname)\n\t\tnodeInfo, err = waitForPodCIDR(client, hostname)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpodCIDRs = nodeInfo.Spec.PodCIDRs\n\t\tklog.InfoS(\"NodeInfo\", \"podCIDR\", nodeInfo.Spec.PodCIDR, \"podCIDRs\", nodeInfo.Spec.PodCIDRs)\n\t}\n\n\tklog.V(2).InfoS(\"DetectLocalMode\", \"localMode\", string(detectLocalMode))\n\n\tprimaryFamily := v1.IPv4Protocol\n\tprimaryProtocol := utiliptables.ProtocolIPv4\n\tif netutils.IsIPv6(nodeIP) {\n\t\tprimaryFamily = v1.IPv6Protocol\n\t\tprimaryProtocol = utiliptables.ProtocolIPv6\n\t}\n\texecer := exec.New()\n\tiptInterface := utiliptables.New(execer, primaryProtocol)\n\n\tvar ipt [2]utiliptables.Interface\n\tdualStack := true // While we assume that node supports, we do further checks below\n\n\t// Create iptables handlers for both families, one is already created\n\t// Always ordered as IPv4, IPv6\n\tif primaryProtocol == utiliptables.ProtocolIPv4 {\n\t\tipt[0] = iptInterface\n\t\tipt[1] = utiliptables.New(execer, utiliptables.ProtocolIPv6)\n\t} else {\n\t\tipt[0] = utiliptables.New(execer, utiliptables.ProtocolIPv4)\n\t\tipt[1] = iptInterface\n\t}\n\n\tnodePortAddresses := config.NodePortAddresses\n\n\tif !ipt[0].Present() {\n\t\treturn nil, fmt.Errorf(\"iptables is not supported for primary IP family %q\", primaryProtocol)\n\t} else if !ipt[1].Present() {\n\t\tklog.InfoS(\"kube-proxy running in single-stack mode: secondary ipFamily is not supported\", \"ipFamily\", ipt[1].Protocol())\n\t\tdualStack = false\n\n\t\t// Validate NodePortAddresses is single-stack\n\t\tnpaByFamily := proxyutil.MapCIDRsByIPFamily(config.NodePortAddresses)\n\t\tsecondaryFamily := proxyutil.OtherIPFamily(primaryFamily)\n\t\tbadAddrs := npaByFamily[secondaryFamily]\n\t\tif len(badAddrs) \u003e 0 {\n\t\t\tklog.InfoS(\"Ignoring --nodeport-addresses of the wrong family\", \"ipFamily\", secondaryFamily, \"addresses\", badAddrs)\n\t\t\tnodePortAddresses = npaByFamily[primaryFamily]\n\t\t}\n\t}\n\n\tif proxyMode == proxyconfigapi.ProxyModeIPTables {\n\t\tklog.InfoS(\"Using iptables Proxier\")\n\t\tif config.IPTables.MasqueradeBit == nil {\n\t\t\t// MasqueradeBit must be specified or defaulted.\n\t\t\treturn nil, fmt.Errorf(\"unable to read IPTables MasqueradeBit from config\")\n\t\t}\n\n\t\tif dualStack {\n\t\t\tklog.InfoS(\"kube-proxy running in dual-stack mode\", \"ipFamily\", iptInterface.Protocol())\n\t\t\tklog.InfoS(\"Creating dualStackProxier for iptables\")\n\t\t\t// Always ordered to match []ipt\n\t\t\tvar localDetectors [2]proxyutiliptables.LocalTrafficDetector\n\t\t\tlocalDetectors, err = getDualStackLocalDetectorTuple(detectLocalMode, config, ipt, nodeInfo)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"unable to create proxier: %v\", err)\n\t\t\t}\n\n\t\t\t// TODO this has side effects that should only happen when Run() is invoked.\n\t\t\tproxier, err = iptables.NewDualStackProxier(\n\t\t\t\tipt,\n\t\t\t\tutilsysctl.New(),\n\t\t\t\texecer,\n\t\t\t\tconfig.IPTables.SyncPeriod.Duration,\n\t\t\t\tconfig.IPTables.MinSyncPeriod.Duration,\n\t\t\t\tconfig.IPTables.MasqueradeAll,\n\t\t\t\t*config.IPTables.LocalhostNodePorts,\n\t\t\t\tint(*config.IPTables.MasqueradeBit),\n\t\t\t\tlocalDetectors,\n\t\t\t\thostname,\n\t\t\t\tnodeIPTuple(config.BindAddress),\n\t\t\t\trecorder,\n\t\t\t\thealthzServer,\n\t\t\t\tnodePortAddresses,\n\t\t\t)\n\t\t} else {\n\t\t\t// Create a single-stack proxier if and only if the node does not support dual-stack (i.e, no iptables support).\n\t\t\tvar localDetector proxyutiliptables.LocalTrafficDetector\n\t\t\tlocalDetector, err = getLocalDetector(detectLocalMode, config, iptInterface, nodeInfo)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"unable to create proxier: %v\", err)\n\t\t\t}\n\n\t\t\t// TODO this has side effects that should only happen when Run() is invoked.\n\t\t\tproxier, err = iptables.NewProxier(\n\t\t\t\tprimaryFamily,\n\t\t\t\tiptInterface,\n\t\t\t\tutilsysctl.New(),\n\t\t\t\texecer,\n\t\t\t\tconfig.IPTables.SyncPeriod.Duration,\n\t\t\t\tconfig.IPTables.MinSyncPeriod.Duration,\n\t\t\t\tconfig.IPTables.MasqueradeAll,\n\t\t\t\t*config.IPTables.LocalhostNodePorts,\n\t\t\t\tint(*config.IPTables.MasqueradeBit),\n\t\t\t\tlocalDetector,\n\t\t\t\thostname,\n\t\t\t\tnodeIP,\n\t\t\t\trecorder,\n\t\t\t\thealthzServer,\n\t\t\t\tnodePortAddresses,\n\t\t\t)\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to create proxier: %v\", err)\n\t\t}\n\t\tproxymetrics.RegisterMetrics()\n\t} else if proxyMode == proxyconfigapi.ProxyModeIPVS {\n\t\tkernelHandler := ipvs.NewLinuxKernelHandler()\n\t\tipsetInterface = utilipset.New(execer)\n\t\tipvsInterface = utilipvs.New()\n\t\tif err := ipvs.CanUseIPVSProxier(ipvsInterface, ipsetInterface, config.IPVS.Scheduler); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"can't use the IPVS proxier: %v\", err)\n\t\t}\n\n\t\tklog.InfoS(\"Using ipvs Proxier\")\n\t\tif dualStack {\n\t\t\tklog.InfoS(\"Creating dualStackProxier for ipvs\")\n\n\t\t\tnodeIPs := nodeIPTuple(config.BindAddress)\n\n\t\t\t// Always ordered to match []ipt\n\t\t\tvar localDetectors [2]proxyutiliptables.LocalTrafficDetector\n\t\t\tlocalDetectors, err = getDualStackLocalDetectorTuple(detectLocalMode, config, ipt, nodeInfo)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"unable to create proxier: %v\", err)\n\t\t\t}\n\n\t\t\tproxier, err = ipvs.NewDualStackProxier(\n\t\t\t\tipt,\n\t\t\t\tipvsInterface,\n\t\t\t\tipsetInterface,\n\t\t\t\tutilsysctl.New(),\n\t\t\t\texecer,\n\t\t\t\tconfig.IPVS.SyncPeriod.Duration,\n\t\t\t\tconfig.IPVS.MinSyncPeriod.Duration,\n\t\t\t\tconfig.IPVS.ExcludeCIDRs,\n\t\t\t\tconfig.IPVS.StrictARP,\n\t\t\t\tconfig.IPVS.TCPTimeout.Duration,\n\t\t\t\tconfig.IPVS.TCPFinTimeout.Duration,\n\t\t\t\tconfig.IPVS.UDPTimeout.Duration,\n\t\t\t\tconfig.IPTables.MasqueradeAll,\n\t\t\t\tint(*config.IPTables.MasqueradeBit),\n\t\t\t\tlocalDetectors,\n\t\t\t\thostname,\n\t\t\t\tnodeIPs,\n\t\t\t\trecorder,\n\t\t\t\thealthzServer,\n\t\t\t\tconfig.IPVS.Scheduler,\n\t\t\t\tnodePortAddresses,\n\t\t\t\tkernelHandler,\n\t\t\t)\n\t\t} else {\n\t\t\tvar localDetector proxyutiliptables.LocalTrafficDetector\n\t\t\tlocalDetector, err = getLocalDetector(detectLocalMode, config, iptInterface, nodeInfo)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"unable to create proxier: %v\", err)\n\t\t\t}\n\n\t\t\tproxier, err = ipvs.NewProxier(\n\t\t\t\tprimaryFamily,\n\t\t\t\tiptInterface,\n\t\t\t\tipvsInterface,\n\t\t\t\tipsetInterface,\n\t\t\t\tutilsysctl.New(),\n\t\t\t\texecer,\n\t\t\t\tconfig.IPVS.SyncPeriod.Duration,\n\t\t\t\tconfig.IPVS.MinSyncPeriod.Duration,\n\t\t\t\tconfig.IPVS.ExcludeCIDRs,\n\t\t\t\tconfig.IPVS.StrictARP,\n\t\t\t\tconfig.IPVS.TCPTimeout.Duration,\n\t\t\t\tconfig.IPVS.TCPFinTimeout.Duration,\n\t\t\t\tconfig.IPVS.UDPTimeout.Duration,\n\t\t\t\tconfig.IPTables.MasqueradeAll,\n\t\t\t\tint(*config.IPTables.MasqueradeBit),\n\t\t\t\tlocalDetector,\n\t\t\t\thostname,\n\t\t\t\tnodeIP,\n\t\t\t\trecorder,\n\t\t\t\thealthzServer,\n\t\t\t\tconfig.IPVS.Scheduler,\n\t\t\t\tnodePortAddresses,\n\t\t\t\tkernelHandler,\n\t\t\t)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to create proxier: %v\", err)\n\t\t}\n\t\tproxymetrics.RegisterMetrics()\n\t}\n\n\treturn \u0026ProxyServer{\n\t\tClient: client,\n\t\tEventClient: eventClient,\n\t\tIptInterface: iptInterface,\n\t\tIpvsInterface: ipvsInterface,\n\t\tIpsetInterface: ipsetInterface,\n\t\texecer: execer,\n\t\tProxier: proxier,\n\t\tBroadcaster: eventBroadcaster,\n\t\tRecorder: recorder,\n\t\tConntrackConfiguration: config.Conntrack,\n\t\tConntracker: \u0026realConntracker{},\n\t\tProxyMode: proxyMode,\n\t\tNodeRef: nodeRef,\n\t\tMetricsBindAddress: config.MetricsBindAddress,\n\t\tBindAddressHardFail: config.BindAddressHardFail,\n\t\tEnableProfiling: config.EnableProfiling,\n\t\tOOMScoreAdj: config.OOMScoreAdj,\n\t\tConfigSyncPeriod: config.ConfigSyncPeriod.Duration,\n\t\tHealthzServer: healthzServer,\n\t\tlocalDetectorMode: detectLocalMode,\n\t\tpodCIDRs: podCIDRs,\n\t}, nil\n}","line":{"from":78,"to":364}} {"id":100000364,"name":"waitForPodCIDR","signature":"func waitForPodCIDR(client clientset.Interface, nodeName string) (*v1.Node, error)","file":"cmd/kube-proxy/app/server_others.go","code":"func waitForPodCIDR(client clientset.Interface, nodeName string) (*v1.Node, error) {\n\t// since allocators can assign the podCIDR after the node registers, we do a watch here to wait\n\t// for podCIDR to be assigned, instead of assuming that the Get() on startup will have it.\n\tctx, cancelFunc := context.WithTimeout(context.TODO(), timeoutForNodePodCIDR)\n\tdefer cancelFunc()\n\n\tfieldSelector := fields.OneTermEqualSelector(\"metadata.name\", nodeName).String()\n\tlw := \u0026cache.ListWatch{\n\t\tListFunc: func(options metav1.ListOptions) (object runtime.Object, e error) {\n\t\t\toptions.FieldSelector = fieldSelector\n\t\t\treturn client.CoreV1().Nodes().List(ctx, options)\n\t\t},\n\t\tWatchFunc: func(options metav1.ListOptions) (i watch.Interface, e error) {\n\t\t\toptions.FieldSelector = fieldSelector\n\t\t\treturn client.CoreV1().Nodes().Watch(ctx, options)\n\t\t},\n\t}\n\tcondition := func(event watch.Event) (bool, error) {\n\t\t// don't process delete events\n\t\tif event.Type != watch.Modified \u0026\u0026 event.Type != watch.Added {\n\t\t\treturn false, nil\n\t\t}\n\n\t\tn, ok := event.Object.(*v1.Node)\n\t\tif !ok {\n\t\t\treturn false, fmt.Errorf(\"event object not of type Node\")\n\t\t}\n\t\t// don't consider the node if is going to be deleted and keep waiting\n\t\tif !n.DeletionTimestamp.IsZero() {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn n.Spec.PodCIDR != \"\" \u0026\u0026 len(n.Spec.PodCIDRs) \u003e 0, nil\n\t}\n\n\tevt, err := toolswatch.UntilWithSync(ctx, lw, \u0026v1.Node{}, nil, condition)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"timeout waiting for PodCIDR allocation to configure detect-local-mode %v: %v\", proxyconfigapi.LocalModeNodeCIDR, err)\n\t}\n\tif n, ok := evt.Object.(*v1.Node); ok {\n\t\treturn n, nil\n\t}\n\treturn nil, fmt.Errorf(\"event object not of type node\")\n}","line":{"from":366,"to":408}} {"id":100000365,"name":"detectNumCPU","signature":"func detectNumCPU() int","file":"cmd/kube-proxy/app/server_others.go","code":"func detectNumCPU() int {\n\t// try get numCPU from /sys firstly due to a known issue (https://github.com/kubernetes/kubernetes/issues/99225)\n\t_, numCPU, err := machine.GetTopology(sysfs.NewRealSysFs())\n\tif err != nil || numCPU \u003c 1 {\n\t\treturn goruntime.NumCPU()\n\t}\n\treturn numCPU\n}","line":{"from":410,"to":417}} {"id":100000366,"name":"getDetectLocalMode","signature":"func getDetectLocalMode(config *proxyconfigapi.KubeProxyConfiguration) (proxyconfigapi.LocalMode, error)","file":"cmd/kube-proxy/app/server_others.go","code":"func getDetectLocalMode(config *proxyconfigapi.KubeProxyConfiguration) (proxyconfigapi.LocalMode, error) {\n\tmode := config.DetectLocalMode\n\tswitch mode {\n\tcase proxyconfigapi.LocalModeClusterCIDR, proxyconfigapi.LocalModeNodeCIDR, proxyconfigapi.LocalModeBridgeInterface, proxyconfigapi.LocalModeInterfaceNamePrefix:\n\t\treturn mode, nil\n\tdefault:\n\t\tif strings.TrimSpace(mode.String()) != \"\" {\n\t\t\treturn mode, fmt.Errorf(\"unknown detect-local-mode: %v\", mode)\n\t\t}\n\t\tklog.V(4).InfoS(\"Defaulting detect-local-mode\", \"localModeClusterCIDR\", string(proxyconfigapi.LocalModeClusterCIDR))\n\t\treturn proxyconfigapi.LocalModeClusterCIDR, nil\n\t}\n}","line":{"from":419,"to":431}} {"id":100000367,"name":"getLocalDetector","signature":"func getLocalDetector(mode proxyconfigapi.LocalMode, config *proxyconfigapi.KubeProxyConfiguration, ipt utiliptables.Interface, nodeInfo *v1.Node) (proxyutiliptables.LocalTrafficDetector, error)","file":"cmd/kube-proxy/app/server_others.go","code":"func getLocalDetector(mode proxyconfigapi.LocalMode, config *proxyconfigapi.KubeProxyConfiguration, ipt utiliptables.Interface, nodeInfo *v1.Node) (proxyutiliptables.LocalTrafficDetector, error) {\n\tswitch mode {\n\tcase proxyconfigapi.LocalModeClusterCIDR:\n\t\tif len(strings.TrimSpace(config.ClusterCIDR)) == 0 {\n\t\t\tklog.InfoS(\"Detect-local-mode set to ClusterCIDR, but no cluster CIDR defined\")\n\t\t\tbreak\n\t\t}\n\t\treturn proxyutiliptables.NewDetectLocalByCIDR(config.ClusterCIDR, ipt)\n\tcase proxyconfigapi.LocalModeNodeCIDR:\n\t\tif len(strings.TrimSpace(nodeInfo.Spec.PodCIDR)) == 0 {\n\t\t\tklog.InfoS(\"Detect-local-mode set to NodeCIDR, but no PodCIDR defined at node\")\n\t\t\tbreak\n\t\t}\n\t\treturn proxyutiliptables.NewDetectLocalByCIDR(nodeInfo.Spec.PodCIDR, ipt)\n\tcase proxyconfigapi.LocalModeBridgeInterface:\n\t\tif len(strings.TrimSpace(config.DetectLocal.BridgeInterface)) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"Detect-local-mode set to BridgeInterface, but no bridge-interface-name %s is defined\", config.DetectLocal.BridgeInterface)\n\t\t}\n\t\treturn proxyutiliptables.NewDetectLocalByBridgeInterface(config.DetectLocal.BridgeInterface)\n\tcase proxyconfigapi.LocalModeInterfaceNamePrefix:\n\t\tif len(strings.TrimSpace(config.DetectLocal.InterfaceNamePrefix)) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"Detect-local-mode set to InterfaceNamePrefix, but no interface-prefix %s is defined\", config.DetectLocal.InterfaceNamePrefix)\n\t\t}\n\t\treturn proxyutiliptables.NewDetectLocalByInterfaceNamePrefix(config.DetectLocal.InterfaceNamePrefix)\n\t}\n\tklog.InfoS(\"Defaulting to no-op detect-local\", \"detectLocalMode\", string(mode))\n\treturn proxyutiliptables.NewNoOpLocalDetector(), nil\n}","line":{"from":433,"to":460}} {"id":100000368,"name":"getDualStackLocalDetectorTuple","signature":"func getDualStackLocalDetectorTuple(mode proxyconfigapi.LocalMode, config *proxyconfigapi.KubeProxyConfiguration, ipt [2]utiliptables.Interface, nodeInfo *v1.Node) ([2]proxyutiliptables.LocalTrafficDetector, error)","file":"cmd/kube-proxy/app/server_others.go","code":"func getDualStackLocalDetectorTuple(mode proxyconfigapi.LocalMode, config *proxyconfigapi.KubeProxyConfiguration, ipt [2]utiliptables.Interface, nodeInfo *v1.Node) ([2]proxyutiliptables.LocalTrafficDetector, error) {\n\tvar err error\n\tlocalDetectors := [2]proxyutiliptables.LocalTrafficDetector{proxyutiliptables.NewNoOpLocalDetector(), proxyutiliptables.NewNoOpLocalDetector()}\n\tswitch mode {\n\tcase proxyconfigapi.LocalModeClusterCIDR:\n\t\tif len(strings.TrimSpace(config.ClusterCIDR)) == 0 {\n\t\t\tklog.InfoS(\"Detect-local-mode set to ClusterCIDR, but no cluster CIDR defined\")\n\t\t\tbreak\n\t\t}\n\n\t\tclusterCIDRs := cidrTuple(config.ClusterCIDR)\n\n\t\tif len(strings.TrimSpace(clusterCIDRs[0])) == 0 {\n\t\t\tklog.InfoS(\"Detect-local-mode set to ClusterCIDR, but no IPv4 cluster CIDR defined, defaulting to no-op detect-local for IPv4\")\n\t\t} else {\n\t\t\tlocalDetectors[0], err = proxyutiliptables.NewDetectLocalByCIDR(clusterCIDRs[0], ipt[0])\n\t\t\tif err != nil { // don't loose the original error\n\t\t\t\treturn localDetectors, err\n\t\t\t}\n\t\t}\n\n\t\tif len(strings.TrimSpace(clusterCIDRs[1])) == 0 {\n\t\t\tklog.InfoS(\"Detect-local-mode set to ClusterCIDR, but no IPv6 cluster CIDR defined, defaulting to no-op detect-local for IPv6\")\n\t\t} else {\n\t\t\tlocalDetectors[1], err = proxyutiliptables.NewDetectLocalByCIDR(clusterCIDRs[1], ipt[1])\n\t\t}\n\t\treturn localDetectors, err\n\tcase proxyconfigapi.LocalModeNodeCIDR:\n\t\tif nodeInfo == nil || len(strings.TrimSpace(nodeInfo.Spec.PodCIDR)) == 0 {\n\t\t\tklog.InfoS(\"No node info available to configure detect-local-mode NodeCIDR\")\n\t\t\tbreak\n\t\t}\n\t\t// localDetectors, like ipt, need to be of the order [IPv4, IPv6], but PodCIDRs is setup so that PodCIDRs[0] == PodCIDR.\n\t\t// so have to handle the case where PodCIDR can be IPv6 and set that to localDetectors[1]\n\t\tif netutils.IsIPv6CIDRString(nodeInfo.Spec.PodCIDR) {\n\t\t\tlocalDetectors[1], err = proxyutiliptables.NewDetectLocalByCIDR(nodeInfo.Spec.PodCIDR, ipt[1])\n\t\t\tif err != nil {\n\t\t\t\treturn localDetectors, err\n\t\t\t}\n\t\t\tif len(nodeInfo.Spec.PodCIDRs) \u003e 1 {\n\t\t\t\tlocalDetectors[0], err = proxyutiliptables.NewDetectLocalByCIDR(nodeInfo.Spec.PodCIDRs[1], ipt[0])\n\t\t\t}\n\t\t} else {\n\t\t\tlocalDetectors[0], err = proxyutiliptables.NewDetectLocalByCIDR(nodeInfo.Spec.PodCIDR, ipt[0])\n\t\t\tif err != nil {\n\t\t\t\treturn localDetectors, err\n\t\t\t}\n\t\t\tif len(nodeInfo.Spec.PodCIDRs) \u003e 1 {\n\t\t\t\tlocalDetectors[1], err = proxyutiliptables.NewDetectLocalByCIDR(nodeInfo.Spec.PodCIDRs[1], ipt[1])\n\t\t\t}\n\t\t}\n\t\treturn localDetectors, err\n\tcase proxyconfigapi.LocalModeBridgeInterface, proxyconfigapi.LocalModeInterfaceNamePrefix:\n\t\tlocalDetector, err := getLocalDetector(mode, config, ipt[0], nodeInfo)\n\t\tif err == nil {\n\t\t\tlocalDetectors[0] = localDetector\n\t\t\tlocalDetectors[1] = localDetector\n\t\t}\n\t\treturn localDetectors, err\n\tdefault:\n\t\tklog.InfoS(\"Unknown detect-local-mode\", \"detectLocalMode\", mode)\n\t}\n\tklog.InfoS(\"Defaulting to no-op detect-local\", \"detectLocalMode\", string(mode))\n\treturn localDetectors, nil\n}","line":{"from":462,"to":526}} {"id":100000369,"name":"cidrTuple","signature":"func cidrTuple(cidrList string) [2]string","file":"cmd/kube-proxy/app/server_others.go","code":"// cidrTuple takes a comma separated list of CIDRs and return a tuple (ipv4cidr,ipv6cidr)\n// The returned tuple is guaranteed to have the order (ipv4,ipv6) and if no cidr from a family is found an\n// empty string \"\" is inserted.\nfunc cidrTuple(cidrList string) [2]string {\n\tcidrs := [2]string{\"\", \"\"}\n\tfoundIPv4 := false\n\tfoundIPv6 := false\n\n\tfor _, cidr := range strings.Split(cidrList, \",\") {\n\t\tif netutils.IsIPv6CIDRString(cidr) \u0026\u0026 !foundIPv6 {\n\t\t\tcidrs[1] = cidr\n\t\t\tfoundIPv6 = true\n\t\t} else if !foundIPv4 {\n\t\t\tcidrs[0] = cidr\n\t\t\tfoundIPv4 = true\n\t\t}\n\t\tif foundIPv6 \u0026\u0026 foundIPv4 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn cidrs\n}","line":{"from":528,"to":550}} {"id":100000370,"name":"getProxyMode","signature":"func getProxyMode(proxyMode proxyconfigapi.ProxyMode) proxyconfigapi.ProxyMode","file":"cmd/kube-proxy/app/server_others.go","code":"func getProxyMode(proxyMode proxyconfigapi.ProxyMode) proxyconfigapi.ProxyMode {\n\tif proxyMode == \"\" {\n\t\tklog.InfoS(\"Using iptables proxy\")\n\t\treturn proxyconfigapi.ProxyModeIPTables\n\t} else {\n\t\treturn proxyMode\n\t}\n}","line":{"from":552,"to":559}} {"id":100000371,"name":"cleanupAndExit","signature":"func cleanupAndExit() error","file":"cmd/kube-proxy/app/server_others.go","code":"// cleanupAndExit remove iptables rules and ipset/ipvs rules\nfunc cleanupAndExit() error {\n\texecer := exec.New()\n\n\t// cleanup IPv6 and IPv4 iptables rules, regardless of current configuration\n\tipts := []utiliptables.Interface{\n\t\tutiliptables.New(execer, utiliptables.ProtocolIPv4),\n\t\tutiliptables.New(execer, utiliptables.ProtocolIPv6),\n\t}\n\n\tipsetInterface := utilipset.New(execer)\n\tipvsInterface := utilipvs.New()\n\n\tvar encounteredError bool\n\tfor _, ipt := range ipts {\n\t\tencounteredError = iptables.CleanupLeftovers(ipt) || encounteredError\n\t\tencounteredError = ipvs.CleanupLeftovers(ipvsInterface, ipt, ipsetInterface) || encounteredError\n\t}\n\tif encounteredError {\n\t\treturn errors.New(\"encountered an error while tearing down rules\")\n\t}\n\n\treturn nil\n}","line":{"from":561,"to":584}} {"id":100000372,"name":"NewProxyServer","signature":"func NewProxyServer(o *Options) (*ProxyServer, error)","file":"cmd/kube-proxy/app/server_windows.go","code":"// NewProxyServer returns a new ProxyServer.\nfunc NewProxyServer(o *Options) (*ProxyServer, error) {\n\treturn newProxyServer(o.config, o.master)\n}","line":{"from":48,"to":51}} {"id":100000373,"name":"newProxyServer","signature":"func newProxyServer(config *proxyconfigapi.KubeProxyConfiguration, master string) (*ProxyServer, error)","file":"cmd/kube-proxy/app/server_windows.go","code":"func newProxyServer(config *proxyconfigapi.KubeProxyConfiguration, master string) (*ProxyServer, error) {\n\tif config == nil {\n\t\treturn nil, errors.New(\"config is required\")\n\t}\n\n\tif c, err := configz.New(proxyconfigapi.GroupName); err == nil {\n\t\tc.Set(config)\n\t} else {\n\t\treturn nil, fmt.Errorf(\"unable to register configz: %s\", err)\n\t}\n\n\tif len(config.ShowHiddenMetricsForVersion) \u003e 0 {\n\t\tmetrics.SetShowHidden()\n\t}\n\n\tclient, eventClient, err := createClients(config.ClientConnection, master)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create event recorder\n\thostname, err := nodeutil.GetHostname(config.HostnameOverride)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnodeIP := detectNodeIP(client, hostname, config.BindAddress)\n\tklog.InfoS(\"Detected node IP\", \"IP\", nodeIP.String())\n\n\teventBroadcaster := events.NewBroadcaster(\u0026events.EventSinkImpl{Interface: client.EventsV1()})\n\trecorder := eventBroadcaster.NewRecorder(proxyconfigscheme.Scheme, \"kube-proxy\")\n\n\tnodeRef := \u0026v1.ObjectReference{\n\t\tKind: \"Node\",\n\t\tName: hostname,\n\t\tUID: types.UID(hostname),\n\t\tNamespace: \"\",\n\t}\n\n\tvar healthzServer healthcheck.ProxierHealthUpdater\n\tvar healthzPort int\n\tif len(config.HealthzBindAddress) \u003e 0 {\n\t\thealthzServer = healthcheck.NewProxierHealthServer(config.HealthzBindAddress, 2*config.IPTables.SyncPeriod.Duration, recorder, nodeRef)\n\t\t_, port, _ := net.SplitHostPort(config.HealthzBindAddress)\n\t\thealthzPort, _ = strconv.Atoi(port)\n\t}\n\n\t// Check if Kernel Space can be used.\n\tcanUseWinKernelProxy, err := winkernel.CanUseWinKernelProxier(winkernel.WindowsKernelCompatTester{})\n\tif !canUseWinKernelProxy \u0026\u0026 err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar proxier proxy.Provider\n\tproxyMode := proxyconfigapi.ProxyModeKernelspace\n\tdualStackMode := getDualStackMode(config.Winkernel.NetworkName, winkernel.DualStackCompatTester{})\n\tif dualStackMode {\n\t\tklog.InfoS(\"Creating dualStackProxier for Windows kernel.\")\n\n\t\tproxier, err = winkernel.NewDualStackProxier(\n\t\t\tconfig.IPTables.SyncPeriod.Duration,\n\t\t\tconfig.IPTables.MinSyncPeriod.Duration,\n\t\t\tconfig.IPTables.MasqueradeAll,\n\t\t\tint(*config.IPTables.MasqueradeBit),\n\t\t\tconfig.ClusterCIDR,\n\t\t\thostname,\n\t\t\tnodeIPTuple(config.BindAddress),\n\t\t\trecorder,\n\t\t\thealthzServer,\n\t\t\tconfig.Winkernel,\n\t\t\thealthzPort,\n\t\t)\n\t} else {\n\t\tproxier, err = winkernel.NewProxier(\n\t\t\tconfig.IPTables.SyncPeriod.Duration,\n\t\t\tconfig.IPTables.MinSyncPeriod.Duration,\n\t\t\tconfig.IPTables.MasqueradeAll,\n\t\t\tint(*config.IPTables.MasqueradeBit),\n\t\t\tconfig.ClusterCIDR,\n\t\t\thostname,\n\t\t\tnodeIP,\n\t\t\trecorder,\n\t\t\thealthzServer,\n\t\t\tconfig.Winkernel,\n\t\t\thealthzPort,\n\t\t)\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create proxier: %v\", err)\n\t}\n\twinkernel.RegisterMetrics()\n\n\treturn \u0026ProxyServer{\n\t\tClient: client,\n\t\tEventClient: eventClient,\n\t\tProxier: proxier,\n\t\tBroadcaster: eventBroadcaster,\n\t\tRecorder: recorder,\n\t\tProxyMode: proxyMode,\n\t\tNodeRef: nodeRef,\n\t\tMetricsBindAddress: config.MetricsBindAddress,\n\t\tBindAddressHardFail: config.BindAddressHardFail,\n\t\tEnableProfiling: config.EnableProfiling,\n\t\tOOMScoreAdj: config.OOMScoreAdj,\n\t\tConfigSyncPeriod: config.ConfigSyncPeriod.Duration,\n\t\tHealthzServer: healthzServer,\n\t}, nil\n}","line":{"from":53,"to":159}} {"id":100000374,"name":"getDualStackMode","signature":"func getDualStackMode(networkname string, compatTester winkernel.StackCompatTester) bool","file":"cmd/kube-proxy/app/server_windows.go","code":"func getDualStackMode(networkname string, compatTester winkernel.StackCompatTester) bool {\n\treturn compatTester.DualStackCompatible(networkname)\n}","line":{"from":161,"to":163}} {"id":100000375,"name":"detectNumCPU","signature":"func detectNumCPU() int","file":"cmd/kube-proxy/app/server_windows.go","code":"func detectNumCPU() int {\n\treturn goruntime.NumCPU()\n}","line":{"from":165,"to":167}} {"id":100000376,"name":"cleanupAndExit","signature":"func cleanupAndExit() error","file":"cmd/kube-proxy/app/server_windows.go","code":"// cleanupAndExit cleans up after a previous proxy run\nfunc cleanupAndExit() error {\n\treturn errors.New(\"--cleanup-and-exit is not implemented on Windows\")\n}","line":{"from":169,"to":172}} {"id":100000377,"name":"main","signature":"func main()","file":"cmd/kube-proxy/proxy.go","code":"func main() {\n\tcommand := app.NewProxyCommand()\n\tcode := cli.Run(command)\n\tos.Exit(code)\n}","line":{"from":28,"to":32}} {"id":100000378,"name":"Complete","signature":"func (c *Config) Complete() CompletedConfig","file":"cmd/kube-scheduler/app/config/config.go","code":"// Complete fills in any fields not set that are required to have valid data. It's mutating the receiver.\nfunc (c *Config) Complete() CompletedConfig {\n\tcc := completedConfig{c}\n\n\tapiserver.AuthorizeClientBearerToken(c.LoopbackClientConfig, \u0026c.Authentication, \u0026c.Authorization)\n\n\treturn CompletedConfig{\u0026cc}\n}","line":{"from":72,"to":79}} {"id":100000379,"name":"loadConfigFromFile","signature":"func loadConfigFromFile(logger klog.Logger, file string) (*config.KubeSchedulerConfiguration, error)","file":"cmd/kube-scheduler/app/options/configfile.go","code":"func loadConfigFromFile(logger klog.Logger, file string) (*config.KubeSchedulerConfiguration, error) {\n\tdata, err := os.ReadFile(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn loadConfig(logger, data)\n}","line":{"from":34,"to":41}} {"id":100000380,"name":"loadConfig","signature":"func loadConfig(logger klog.Logger, data []byte) (*config.KubeSchedulerConfiguration, error)","file":"cmd/kube-scheduler/app/options/configfile.go","code":"func loadConfig(logger klog.Logger, data []byte) (*config.KubeSchedulerConfiguration, error) {\n\t// The UniversalDecoder runs defaulting and returns the internal type by default.\n\tobj, gvk, err := scheme.Codecs.UniversalDecoder().Decode(data, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif cfgObj, ok := obj.(*config.KubeSchedulerConfiguration); ok {\n\t\t// We don't set this field in pkg/scheduler/apis/config/{version}/conversion.go\n\t\t// because the field will be cleared later by API machinery during\n\t\t// conversion. See KubeSchedulerConfiguration internal type definition for\n\t\t// more details.\n\t\tcfgObj.TypeMeta.APIVersion = gvk.GroupVersion().String()\n\t\tswitch cfgObj.TypeMeta.APIVersion {\n\t\tcase configv1beta2.SchemeGroupVersion.String():\n\t\t\tlogger.Info(\"KubeSchedulerConfiguration v1beta2 is deprecated in v1.25, will be removed in v1.28\")\n\t\tcase configv1beta3.SchemeGroupVersion.String():\n\t\t\tlogger.Info(\"KubeSchedulerConfiguration v1beta3 is deprecated in v1.26, will be removed in v1.29\")\n\t\t}\n\t\treturn cfgObj, nil\n\t}\n\treturn nil, fmt.Errorf(\"couldn't decode as KubeSchedulerConfiguration, got %s: \", gvk)\n}","line":{"from":43,"to":64}} {"id":100000381,"name":"encodeConfig","signature":"func encodeConfig(cfg *config.KubeSchedulerConfiguration) (*bytes.Buffer, error)","file":"cmd/kube-scheduler/app/options/configfile.go","code":"func encodeConfig(cfg *config.KubeSchedulerConfiguration) (*bytes.Buffer, error) {\n\tbuf := new(bytes.Buffer)\n\tconst mediaType = runtime.ContentTypeYAML\n\tinfo, ok := runtime.SerializerInfoForMediaType(scheme.Codecs.SupportedMediaTypes(), mediaType)\n\tif !ok {\n\t\treturn buf, fmt.Errorf(\"unable to locate encoder -- %q is not a supported media type\", mediaType)\n\t}\n\n\tvar encoder runtime.Encoder\n\tswitch cfg.TypeMeta.APIVersion {\n\tcase configv1beta2.SchemeGroupVersion.String():\n\t\tencoder = scheme.Codecs.EncoderForVersion(info.Serializer, configv1beta2.SchemeGroupVersion)\n\tcase configv1beta3.SchemeGroupVersion.String():\n\t\tencoder = scheme.Codecs.EncoderForVersion(info.Serializer, configv1beta3.SchemeGroupVersion)\n\tcase configv1.SchemeGroupVersion.String():\n\t\tencoder = scheme.Codecs.EncoderForVersion(info.Serializer, configv1.SchemeGroupVersion)\n\tdefault:\n\t\tencoder = scheme.Codecs.EncoderForVersion(info.Serializer, configv1.SchemeGroupVersion)\n\t}\n\tif err := encoder.Encode(cfg, buf); err != nil {\n\t\treturn buf, err\n\t}\n\treturn buf, nil\n}","line":{"from":66,"to":89}} {"id":100000382,"name":"LogOrWriteConfig","signature":"func LogOrWriteConfig(logger klog.Logger, fileName string, cfg *config.KubeSchedulerConfiguration, completedProfiles []config.KubeSchedulerProfile) error","file":"cmd/kube-scheduler/app/options/configfile.go","code":"// LogOrWriteConfig logs the completed component config and writes it into the given file name as YAML, if either is enabled\nfunc LogOrWriteConfig(logger klog.Logger, fileName string, cfg *config.KubeSchedulerConfiguration, completedProfiles []config.KubeSchedulerProfile) error {\n\tloggerV := logger.V(2)\n\tif !loggerV.Enabled() \u0026\u0026 len(fileName) == 0 {\n\t\treturn nil\n\t}\n\tcfg.Profiles = completedProfiles\n\n\tbuf, err := encodeConfig(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif loggerV.Enabled() {\n\t\tloggerV.Info(\"Using component config\", \"config\", buf.String())\n\t}\n\n\tif len(fileName) \u003e 0 {\n\t\tconfigFile, err := os.Create(fileName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer configFile.Close()\n\t\tif _, err := io.Copy(configFile, buf); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlogger.Info(\"Wrote configuration\", \"file\", fileName)\n\t\tos.Exit(0)\n\t}\n\treturn nil\n}","line":{"from":91,"to":121}} {"id":100000383,"name":"AddFlags","signature":"func (o *DeprecatedOptions) AddFlags(fs *pflag.FlagSet)","file":"cmd/kube-scheduler/app/options/deprecated.go","code":"// AddFlags adds flags for the deprecated options.\nfunc (o *DeprecatedOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.BoolVar(\u0026o.EnableProfiling, \"profiling\", true, \"DEPRECATED: enable profiling via web interface host:port/debug/pprof/. This parameter is ignored if a config file is specified in --config.\")\n\tfs.BoolVar(\u0026o.EnableContentionProfiling, \"contention-profiling\", true, \"DEPRECATED: enable block profiling, if profiling is enabled. This parameter is ignored if a config file is specified in --config.\")\n\tfs.StringVar(\u0026o.Kubeconfig, \"kubeconfig\", \"\", \"DEPRECATED: path to kubeconfig file with authorization and master location information. This parameter is ignored if a config file is specified in --config.\")\n\tfs.StringVar(\u0026o.ContentType, \"kube-api-content-type\", \"application/vnd.kubernetes.protobuf\", \"DEPRECATED: content type of requests sent to apiserver. This parameter is ignored if a config file is specified in --config.\")\n\tfs.Float32Var(\u0026o.QPS, \"kube-api-qps\", 50.0, \"DEPRECATED: QPS to use while talking with kubernetes apiserver. This parameter is ignored if a config file is specified in --config.\")\n\tfs.Int32Var(\u0026o.Burst, \"kube-api-burst\", 100, \"DEPRECATED: burst to use while talking with kubernetes apiserver. This parameter is ignored if a config file is specified in --config.\")\n\tfs.StringVar(\u0026o.ResourceNamespace, \"lock-object-namespace\", \"kube-system\", \"DEPRECATED: define the namespace of the lock object. Will be removed in favor of leader-elect-resource-namespace. This parameter is ignored if a config file is specified in --config.\")\n\tfs.StringVar(\u0026o.ResourceName, \"lock-object-name\", \"kube-scheduler\", \"DEPRECATED: define the name of the lock object. Will be removed in favor of leader-elect-resource-name. This parameter is ignored if a config file is specified in --config.\")\n\tfs.DurationVar(\u0026o.PodMaxInUnschedulablePodsDuration, \"pod-max-in-unschedulable-pods-duration\", 5*time.Minute, \"DEPRECATED: the maximum time a pod can stay in unschedulablePods. If a pod stays in unschedulablePods for longer than this value, the pod will be moved from unschedulablePods to backoffQ or activeQ. This flag is deprecated and will be removed in 1.26\")\n}","line":{"from":40,"to":55}} {"id":100000384,"name":"NewOptions","signature":"func NewOptions() *Options","file":"cmd/kube-scheduler/app/options/options.go","code":"// NewOptions returns default scheduler app options.\nfunc NewOptions() *Options {\n\to := \u0026Options{\n\t\tSecureServing: apiserveroptions.NewSecureServingOptions().WithLoopback(),\n\t\tAuthentication: apiserveroptions.NewDelegatingAuthenticationOptions(),\n\t\tAuthorization: apiserveroptions.NewDelegatingAuthorizationOptions(),\n\t\tDeprecated: \u0026DeprecatedOptions{\n\t\t\tPodMaxInUnschedulablePodsDuration: 5 * time.Minute,\n\t\t},\n\t\tLeaderElection: \u0026componentbaseconfig.LeaderElectionConfiguration{\n\t\t\tLeaderElect: true,\n\t\t\tLeaseDuration: metav1.Duration{Duration: 15 * time.Second},\n\t\t\tRenewDeadline: metav1.Duration{Duration: 10 * time.Second},\n\t\t\tRetryPeriod: metav1.Duration{Duration: 2 * time.Second},\n\t\t\tResourceLock: \"leases\",\n\t\t\tResourceName: \"kube-scheduler\",\n\t\t\tResourceNamespace: \"kube-system\",\n\t\t},\n\t\tMetrics: metrics.NewOptions(),\n\t\tLogs: logs.NewOptions(),\n\t}\n\n\to.Authentication.TolerateInClusterLookupFailure = true\n\to.Authentication.RemoteKubeConfigFileOptional = true\n\to.Authorization.RemoteKubeConfigFileOptional = true\n\n\t// Set the PairName but leave certificate directory blank to generate in-memory by default\n\to.SecureServing.ServerCert.CertDirectory = \"\"\n\to.SecureServing.ServerCert.PairName = \"kube-scheduler\"\n\to.SecureServing.BindPort = kubeschedulerconfig.DefaultKubeSchedulerPort\n\n\to.initFlags()\n\n\treturn o\n}","line":{"from":79,"to":113}} {"id":100000385,"name":"ApplyDeprecated","signature":"func (o *Options) ApplyDeprecated()","file":"cmd/kube-scheduler/app/options/options.go","code":"// ApplyDeprecated obtains the deprecated CLI args and set them to `o.ComponentConfig` if specified.\nfunc (o *Options) ApplyDeprecated() {\n\tif o.Flags == nil {\n\t\treturn\n\t}\n\t// Obtain deprecated CLI args. Set them to cfg if specified in command line.\n\tdeprecated := o.Flags.FlagSet(\"deprecated\")\n\tif deprecated.Changed(\"profiling\") {\n\t\to.ComponentConfig.EnableProfiling = o.Deprecated.EnableProfiling\n\t}\n\tif deprecated.Changed(\"contention-profiling\") {\n\t\to.ComponentConfig.EnableContentionProfiling = o.Deprecated.EnableContentionProfiling\n\t}\n\tif deprecated.Changed(\"kubeconfig\") {\n\t\to.ComponentConfig.ClientConnection.Kubeconfig = o.Deprecated.Kubeconfig\n\t}\n\tif deprecated.Changed(\"kube-api-content-type\") {\n\t\to.ComponentConfig.ClientConnection.ContentType = o.Deprecated.ContentType\n\t}\n\tif deprecated.Changed(\"kube-api-qps\") {\n\t\to.ComponentConfig.ClientConnection.QPS = o.Deprecated.QPS\n\t}\n\tif deprecated.Changed(\"kube-api-burst\") {\n\t\to.ComponentConfig.ClientConnection.Burst = o.Deprecated.Burst\n\t}\n\tif deprecated.Changed(\"lock-object-namespace\") {\n\t\to.ComponentConfig.LeaderElection.ResourceNamespace = o.Deprecated.ResourceNamespace\n\t}\n\tif deprecated.Changed(\"lock-object-name\") {\n\t\to.ComponentConfig.LeaderElection.ResourceName = o.Deprecated.ResourceName\n\t}\n}","line":{"from":115,"to":146}} {"id":100000386,"name":"ApplyLeaderElectionTo","signature":"func (o *Options) ApplyLeaderElectionTo(cfg *kubeschedulerconfig.KubeSchedulerConfiguration)","file":"cmd/kube-scheduler/app/options/options.go","code":"// ApplyLeaderElectionTo obtains the CLI args related with leaderelection, and override the values in `cfg`.\n// Then the `cfg` object is injected into the `options` object.\nfunc (o *Options) ApplyLeaderElectionTo(cfg *kubeschedulerconfig.KubeSchedulerConfiguration) {\n\tif o.Flags == nil {\n\t\treturn\n\t}\n\t// Obtain CLI args related with leaderelection. Set them to `cfg` if specified in command line.\n\tleaderelection := o.Flags.FlagSet(\"leader election\")\n\tif leaderelection.Changed(\"leader-elect\") {\n\t\tcfg.LeaderElection.LeaderElect = o.LeaderElection.LeaderElect\n\t}\n\tif leaderelection.Changed(\"leader-elect-lease-duration\") {\n\t\tcfg.LeaderElection.LeaseDuration = o.LeaderElection.LeaseDuration\n\t}\n\tif leaderelection.Changed(\"leader-elect-renew-deadline\") {\n\t\tcfg.LeaderElection.RenewDeadline = o.LeaderElection.RenewDeadline\n\t}\n\tif leaderelection.Changed(\"leader-elect-retry-period\") {\n\t\tcfg.LeaderElection.RetryPeriod = o.LeaderElection.RetryPeriod\n\t}\n\tif leaderelection.Changed(\"leader-elect-resource-lock\") {\n\t\tcfg.LeaderElection.ResourceLock = o.LeaderElection.ResourceLock\n\t}\n\tif leaderelection.Changed(\"leader-elect-resource-name\") {\n\t\tcfg.LeaderElection.ResourceName = o.LeaderElection.ResourceName\n\t}\n\tif leaderelection.Changed(\"leader-elect-resource-namespace\") {\n\t\tcfg.LeaderElection.ResourceNamespace = o.LeaderElection.ResourceNamespace\n\t}\n\n\to.ComponentConfig = cfg\n}","line":{"from":148,"to":179}} {"id":100000387,"name":"initFlags","signature":"func (o *Options) initFlags()","file":"cmd/kube-scheduler/app/options/options.go","code":"// initFlags initializes flags by section name.\nfunc (o *Options) initFlags() {\n\tif o.Flags != nil {\n\t\treturn\n\t}\n\n\tnfs := cliflag.NamedFlagSets{}\n\tfs := nfs.FlagSet(\"misc\")\n\tfs.StringVar(\u0026o.ConfigFile, \"config\", o.ConfigFile, \"The path to the configuration file.\")\n\tfs.StringVar(\u0026o.WriteConfigTo, \"write-config-to\", o.WriteConfigTo, \"If set, write the configuration values to this file and exit.\")\n\tfs.StringVar(\u0026o.Master, \"master\", o.Master, \"The address of the Kubernetes API server (overrides any value in kubeconfig)\")\n\n\to.SecureServing.AddFlags(nfs.FlagSet(\"secure serving\"))\n\to.Authentication.AddFlags(nfs.FlagSet(\"authentication\"))\n\to.Authorization.AddFlags(nfs.FlagSet(\"authorization\"))\n\to.Deprecated.AddFlags(nfs.FlagSet(\"deprecated\"))\n\toptions.BindLeaderElectionFlags(o.LeaderElection, nfs.FlagSet(\"leader election\"))\n\tutilfeature.DefaultMutableFeatureGate.AddFlag(nfs.FlagSet(\"feature gate\"))\n\to.Metrics.AddFlags(nfs.FlagSet(\"metrics\"))\n\tlogsapi.AddFlags(o.Logs, nfs.FlagSet(\"logs\"))\n\n\to.Flags = \u0026nfs\n}","line":{"from":181,"to":203}} {"id":100000388,"name":"ApplyTo","signature":"func (o *Options) ApplyTo(logger klog.Logger, c *schedulerappconfig.Config) error","file":"cmd/kube-scheduler/app/options/options.go","code":"// ApplyTo applies the scheduler options to the given scheduler app configuration.\nfunc (o *Options) ApplyTo(logger klog.Logger, c *schedulerappconfig.Config) error {\n\tif len(o.ConfigFile) == 0 {\n\t\t// If the --config arg is not specified, honor the deprecated as well as leader election CLI args.\n\t\to.ApplyDeprecated()\n\t\to.ApplyLeaderElectionTo(o.ComponentConfig)\n\t\tc.ComponentConfig = *o.ComponentConfig\n\t} else {\n\t\tcfg, err := loadConfigFromFile(logger, o.ConfigFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// If the --config arg is specified, honor the leader election CLI args only.\n\t\to.ApplyLeaderElectionTo(cfg)\n\n\t\tif err := validation.ValidateKubeSchedulerConfiguration(cfg); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.ComponentConfig = *cfg\n\t}\n\n\t// Build kubeconfig first to so that if it fails, it doesn't cause leaking\n\t// goroutines (started from initializing secure serving - which underneath\n\t// creates a queue which in its constructor starts a goroutine).\n\tkubeConfig, err := createKubeConfig(c.ComponentConfig.ClientConnection, o.Master)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.KubeConfig = kubeConfig\n\n\tif err := o.SecureServing.ApplyTo(\u0026c.SecureServing, \u0026c.LoopbackClientConfig); err != nil {\n\t\treturn err\n\t}\n\tif o.SecureServing != nil \u0026\u0026 (o.SecureServing.BindPort != 0 || o.SecureServing.Listener != nil) {\n\t\tif err := o.Authentication.ApplyTo(\u0026c.Authentication, c.SecureServing, nil); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := o.Authorization.ApplyTo(\u0026c.Authorization); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\to.Metrics.Apply()\n\n\t// Apply value independently instead of using ApplyDeprecated() because it can't be configured via ComponentConfig.\n\tif o.Deprecated != nil {\n\t\tc.PodMaxInUnschedulablePodsDuration = o.Deprecated.PodMaxInUnschedulablePodsDuration\n\t}\n\n\treturn nil\n}","line":{"from":205,"to":255}} {"id":100000389,"name":"Validate","signature":"func (o *Options) Validate() []error","file":"cmd/kube-scheduler/app/options/options.go","code":"// Validate validates all the required options.\nfunc (o *Options) Validate() []error {\n\tvar errs []error\n\n\tif err := validation.ValidateKubeSchedulerConfiguration(o.ComponentConfig); err != nil {\n\t\terrs = append(errs, err.Errors()...)\n\t}\n\terrs = append(errs, o.SecureServing.Validate()...)\n\terrs = append(errs, o.Authentication.Validate()...)\n\terrs = append(errs, o.Authorization.Validate()...)\n\terrs = append(errs, o.Metrics.Validate()...)\n\n\treturn errs\n}","line":{"from":257,"to":270}} {"id":100000390,"name":"Config","signature":"func (o *Options) Config(ctx context.Context) (*schedulerappconfig.Config, error)","file":"cmd/kube-scheduler/app/options/options.go","code":"// Config return a scheduler config object\nfunc (o *Options) Config(ctx context.Context) (*schedulerappconfig.Config, error) {\n\tlogger := klog.FromContext(ctx)\n\tif o.SecureServing != nil {\n\t\tif err := o.SecureServing.MaybeDefaultWithSelfSignedCerts(\"localhost\", nil, []net.IP{netutils.ParseIPSloppy(\"127.0.0.1\")}); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error creating self-signed certificates: %v\", err)\n\t\t}\n\t}\n\n\tc := \u0026schedulerappconfig.Config{}\n\tif err := o.ApplyTo(logger, c); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Prepare kube clients.\n\tclient, eventClient, err := createClients(c.KubeConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.EventBroadcaster = events.NewEventBroadcasterAdapter(eventClient)\n\n\t// Set up leader election if enabled.\n\tvar leaderElectionConfig *leaderelection.LeaderElectionConfig\n\tif c.ComponentConfig.LeaderElection.LeaderElect {\n\t\t// Use the scheduler name in the first profile to record leader election.\n\t\tschedulerName := corev1.DefaultSchedulerName\n\t\tif len(c.ComponentConfig.Profiles) != 0 {\n\t\t\tschedulerName = c.ComponentConfig.Profiles[0].SchedulerName\n\t\t}\n\t\tcoreRecorder := c.EventBroadcaster.DeprecatedNewLegacyRecorder(schedulerName)\n\t\tleaderElectionConfig, err = makeLeaderElectionConfig(c.ComponentConfig.LeaderElection, c.KubeConfig, coreRecorder)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tc.Client = client\n\tc.InformerFactory = scheduler.NewInformerFactory(client, 0)\n\tdynClient := dynamic.NewForConfigOrDie(c.KubeConfig)\n\tc.DynInformerFactory = dynamicinformer.NewFilteredDynamicSharedInformerFactory(dynClient, 0, corev1.NamespaceAll, nil)\n\tc.LeaderElection = leaderElectionConfig\n\n\treturn c, nil\n}","line":{"from":272,"to":316}} {"id":100000391,"name":"makeLeaderElectionConfig","signature":"func makeLeaderElectionConfig(config componentbaseconfig.LeaderElectionConfiguration, kubeConfig *restclient.Config, recorder record.EventRecorder) (*leaderelection.LeaderElectionConfig, error)","file":"cmd/kube-scheduler/app/options/options.go","code":"// makeLeaderElectionConfig builds a leader election configuration. It will\n// create a new resource lock associated with the configuration.\nfunc makeLeaderElectionConfig(config componentbaseconfig.LeaderElectionConfiguration, kubeConfig *restclient.Config, recorder record.EventRecorder) (*leaderelection.LeaderElectionConfig, error) {\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to get hostname: %v\", err)\n\t}\n\t// add a uniquifier so that two processes on the same host don't accidentally both become active\n\tid := hostname + \"_\" + string(uuid.NewUUID())\n\n\trl, err := resourcelock.NewFromKubeconfig(config.ResourceLock,\n\t\tconfig.ResourceNamespace,\n\t\tconfig.ResourceName,\n\t\tresourcelock.ResourceLockConfig{\n\t\t\tIdentity: id,\n\t\t\tEventRecorder: recorder,\n\t\t},\n\t\tkubeConfig,\n\t\tconfig.RenewDeadline.Duration)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"couldn't create resource lock: %v\", err)\n\t}\n\n\treturn \u0026leaderelection.LeaderElectionConfig{\n\t\tLock: rl,\n\t\tLeaseDuration: config.LeaseDuration.Duration,\n\t\tRenewDeadline: config.RenewDeadline.Duration,\n\t\tRetryPeriod: config.RetryPeriod.Duration,\n\t\tWatchDog: leaderelection.NewLeaderHealthzAdaptor(time.Second * 20),\n\t\tName: \"kube-scheduler\",\n\t\tReleaseOnCancel: true,\n\t}, nil\n}","line":{"from":318,"to":350}} {"id":100000392,"name":"createKubeConfig","signature":"func createKubeConfig(config componentbaseconfig.ClientConnectionConfiguration, masterOverride string) (*restclient.Config, error)","file":"cmd/kube-scheduler/app/options/options.go","code":"// createKubeConfig creates a kubeConfig from the given config and masterOverride.\n// TODO remove masterOverride when CLI flags are removed.\nfunc createKubeConfig(config componentbaseconfig.ClientConnectionConfiguration, masterOverride string) (*restclient.Config, error) {\n\tkubeConfig, err := clientcmd.BuildConfigFromFlags(masterOverride, config.Kubeconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkubeConfig.DisableCompression = true\n\tkubeConfig.AcceptContentTypes = config.AcceptContentTypes\n\tkubeConfig.ContentType = config.ContentType\n\tkubeConfig.QPS = config.QPS\n\tkubeConfig.Burst = int(config.Burst)\n\n\treturn kubeConfig, nil\n}","line":{"from":352,"to":367}} {"id":100000393,"name":"createClients","signature":"func createClients(kubeConfig *restclient.Config) (clientset.Interface, clientset.Interface, error)","file":"cmd/kube-scheduler/app/options/options.go","code":"// createClients creates a kube client and an event client from the given kubeConfig\nfunc createClients(kubeConfig *restclient.Config) (clientset.Interface, clientset.Interface, error) {\n\tclient, err := clientset.NewForConfig(restclient.AddUserAgent(kubeConfig, \"scheduler\"))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\teventClient, err := clientset.NewForConfig(kubeConfig)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn client, eventClient, nil\n}","line":{"from":369,"to":382}} {"id":100000394,"name":"init","signature":"func init()","file":"cmd/kube-scheduler/app/server.go","code":"func init() {\n\tutilruntime.Must(logsapi.AddFeatureGates(utilfeature.DefaultMutableFeatureGate))\n\tutilruntime.Must(features.AddFeatureGates(utilfeature.DefaultMutableFeatureGate))\n}","line":{"from":67,"to":70}} {"id":100000395,"name":"NewSchedulerCommand","signature":"func NewSchedulerCommand(registryOptions ...Option) *cobra.Command","file":"cmd/kube-scheduler/app/server.go","code":"// NewSchedulerCommand creates a *cobra.Command object with default parameters and registryOptions\nfunc NewSchedulerCommand(registryOptions ...Option) *cobra.Command {\n\topts := options.NewOptions()\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"kube-scheduler\",\n\t\tLong: `The Kubernetes scheduler is a control plane process which assigns\nPods to Nodes. The scheduler determines which Nodes are valid placements for\neach Pod in the scheduling queue according to constraints and available\nresources. The scheduler then ranks each valid Node and binds the Pod to a\nsuitable Node. Multiple different schedulers may be used within a cluster;\nkube-scheduler is the reference implementation.\nSee [scheduling](https://kubernetes.io/docs/concepts/scheduling-eviction/)\nfor more information about scheduling and the kube-scheduler component.`,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn runCommand(cmd, opts, registryOptions...)\n\t\t},\n\t\tArgs: func(cmd *cobra.Command, args []string) error {\n\t\t\tfor _, arg := range args {\n\t\t\t\tif len(arg) \u003e 0 {\n\t\t\t\t\treturn fmt.Errorf(\"%q does not take any arguments, got %q\", cmd.CommandPath(), args)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tnfs := opts.Flags\n\tverflag.AddFlags(nfs.FlagSet(\"global\"))\n\tglobalflag.AddGlobalFlags(nfs.FlagSet(\"global\"), cmd.Name(), logs.SkipLoggingConfigurationFlags())\n\tfs := cmd.Flags()\n\tfor _, f := range nfs.FlagSets {\n\t\tfs.AddFlagSet(f)\n\t}\n\n\tcols, _, _ := term.TerminalSize(cmd.OutOrStdout())\n\tcliflag.SetUsageAndHelpFunc(cmd, *nfs, cols)\n\n\tif err := cmd.MarkFlagFilename(\"config\", \"yaml\", \"yml\", \"json\"); err != nil {\n\t\tklog.Background().Error(err, \"Failed to mark flag filename\")\n\t}\n\n\treturn cmd\n}","line":{"from":75,"to":118}} {"id":100000396,"name":"runCommand","signature":"func runCommand(cmd *cobra.Command, opts *options.Options, registryOptions ...Option) error","file":"cmd/kube-scheduler/app/server.go","code":"// runCommand runs the scheduler.\nfunc runCommand(cmd *cobra.Command, opts *options.Options, registryOptions ...Option) error {\n\tverflag.PrintAndExitIfRequested()\n\n\t// Activate logging as soon as possible, after that\n\t// show flags with the final logging configuration.\n\tif err := logsapi.ValidateAndApply(opts.Logs, utilfeature.DefaultFeatureGate); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tcliflag.PrintFlags(cmd.Flags())\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tgo func() {\n\t\tstopCh := server.SetupSignalHandler()\n\t\t\u003c-stopCh\n\t\tcancel()\n\t}()\n\n\tcc, sched, err := Setup(ctx, opts, registryOptions...)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// add feature enablement metrics\n\tutilfeature.DefaultMutableFeatureGate.AddMetrics()\n\treturn Run(ctx, cc, sched)\n}","line":{"from":120,"to":147}} {"id":100000397,"name":"Run","signature":"func Run(ctx context.Context, cc *schedulerserverconfig.CompletedConfig, sched *scheduler.Scheduler) error","file":"cmd/kube-scheduler/app/server.go","code":"// Run executes the scheduler based on the given configuration. It only returns on error or when context is done.\nfunc Run(ctx context.Context, cc *schedulerserverconfig.CompletedConfig, sched *scheduler.Scheduler) error {\n\tlogger := klog.FromContext(ctx)\n\n\t// To help debugging, immediately log version\n\tlogger.Info(\"Starting Kubernetes Scheduler\", \"version\", version.Get())\n\n\tlogger.Info(\"Golang settings\", \"GOGC\", os.Getenv(\"GOGC\"), \"GOMAXPROCS\", os.Getenv(\"GOMAXPROCS\"), \"GOTRACEBACK\", os.Getenv(\"GOTRACEBACK\"))\n\n\t// Configz registration.\n\tif cz, err := configz.New(\"componentconfig\"); err == nil {\n\t\tcz.Set(cc.ComponentConfig)\n\t} else {\n\t\treturn fmt.Errorf(\"unable to register configz: %s\", err)\n\t}\n\n\t// Start events processing pipeline.\n\tcc.EventBroadcaster.StartRecordingToSink(ctx.Done())\n\tdefer cc.EventBroadcaster.Shutdown()\n\n\t// Setup healthz checks.\n\tvar checks []healthz.HealthChecker\n\tif cc.ComponentConfig.LeaderElection.LeaderElect {\n\t\tchecks = append(checks, cc.LeaderElection.WatchDog)\n\t}\n\n\twaitingForLeader := make(chan struct{})\n\tisLeader := func() bool {\n\t\tselect {\n\t\tcase _, ok := \u003c-waitingForLeader:\n\t\t\t// if channel is closed, we are leading\n\t\t\treturn !ok\n\t\tdefault:\n\t\t\t// channel is open, we are waiting for a leader\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// Start up the healthz server.\n\tif cc.SecureServing != nil {\n\t\thandler := buildHandlerChain(newHealthzAndMetricsHandler(\u0026cc.ComponentConfig, cc.InformerFactory, isLeader, checks...), cc.Authentication.Authenticator, cc.Authorization.Authorizer)\n\t\t// TODO: handle stoppedCh and listenerStoppedCh returned by c.SecureServing.Serve\n\t\tif _, _, err := cc.SecureServing.Serve(handler, 0, ctx.Done()); err != nil {\n\t\t\t// fail early for secure handlers, removing the old error loop from above\n\t\t\treturn fmt.Errorf(\"failed to start secure server: %v\", err)\n\t\t}\n\t}\n\n\t// Start all informers.\n\tcc.InformerFactory.Start(ctx.Done())\n\t// DynInformerFactory can be nil in tests.\n\tif cc.DynInformerFactory != nil {\n\t\tcc.DynInformerFactory.Start(ctx.Done())\n\t}\n\n\t// Wait for all caches to sync before scheduling.\n\tcc.InformerFactory.WaitForCacheSync(ctx.Done())\n\t// DynInformerFactory can be nil in tests.\n\tif cc.DynInformerFactory != nil {\n\t\tcc.DynInformerFactory.WaitForCacheSync(ctx.Done())\n\t}\n\n\t// If leader election is enabled, runCommand via LeaderElector until done and exit.\n\tif cc.LeaderElection != nil {\n\t\tcc.LeaderElection.Callbacks = leaderelection.LeaderCallbacks{\n\t\t\tOnStartedLeading: func(ctx context.Context) {\n\t\t\t\tclose(waitingForLeader)\n\t\t\t\tsched.Run(ctx)\n\t\t\t},\n\t\t\tOnStoppedLeading: func() {\n\t\t\t\tselect {\n\t\t\t\tcase \u003c-ctx.Done():\n\t\t\t\t\t// We were asked to terminate. Exit 0.\n\t\t\t\t\tlogger.Info(\"Requested to terminate, exiting\")\n\t\t\t\t\tos.Exit(0)\n\t\t\t\tdefault:\n\t\t\t\t\t// We lost the lock.\n\t\t\t\t\tlogger.Error(nil, \"Leaderelection lost\")\n\t\t\t\t\tklog.FlushAndExit(klog.ExitFlushTimeout, 1)\n\t\t\t\t}\n\t\t\t},\n\t\t}\n\t\tleaderElector, err := leaderelection.NewLeaderElector(*cc.LeaderElection)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't create leader elector: %v\", err)\n\t\t}\n\n\t\tleaderElector.Run(ctx)\n\n\t\treturn fmt.Errorf(\"lost lease\")\n\t}\n\n\t// Leader election is disabled, so runCommand inline until done.\n\tclose(waitingForLeader)\n\tsched.Run(ctx)\n\treturn fmt.Errorf(\"finished without leader elect\")\n}","line":{"from":149,"to":245}} {"id":100000398,"name":"buildHandlerChain","signature":"func buildHandlerChain(handler http.Handler, authn authenticator.Request, authz authorizer.Authorizer) http.Handler","file":"cmd/kube-scheduler/app/server.go","code":"// buildHandlerChain wraps the given handler with the standard filters.\nfunc buildHandlerChain(handler http.Handler, authn authenticator.Request, authz authorizer.Authorizer) http.Handler {\n\trequestInfoResolver := \u0026apirequest.RequestInfoFactory{}\n\tfailedHandler := genericapifilters.Unauthorized(scheme.Codecs)\n\n\thandler = genericapifilters.WithAuthorization(handler, authz, scheme.Codecs)\n\thandler = genericapifilters.WithAuthentication(handler, authn, failedHandler, nil, nil)\n\thandler = genericapifilters.WithRequestInfo(handler, requestInfoResolver)\n\thandler = genericapifilters.WithCacheControl(handler)\n\thandler = genericfilters.WithHTTPLogging(handler)\n\thandler = genericfilters.WithPanicRecovery(handler, requestInfoResolver)\n\n\treturn handler\n}","line":{"from":247,"to":260}} {"id":100000399,"name":"installMetricHandler","signature":"func installMetricHandler(pathRecorderMux *mux.PathRecorderMux, informers informers.SharedInformerFactory, isLeader func() bool)","file":"cmd/kube-scheduler/app/server.go","code":"func installMetricHandler(pathRecorderMux *mux.PathRecorderMux, informers informers.SharedInformerFactory, isLeader func() bool) {\n\tconfigz.InstallHandler(pathRecorderMux)\n\tpathRecorderMux.Handle(\"/metrics\", legacyregistry.HandlerWithReset())\n\n\tresourceMetricsHandler := resources.Handler(informers.Core().V1().Pods().Lister())\n\tpathRecorderMux.HandleFunc(\"/metrics/resources\", func(w http.ResponseWriter, req *http.Request) {\n\t\tif !isLeader() {\n\t\t\treturn\n\t\t}\n\t\tresourceMetricsHandler.ServeHTTP(w, req)\n\t})\n}","line":{"from":262,"to":273}} {"id":100000400,"name":"newHealthzAndMetricsHandler","signature":"func newHealthzAndMetricsHandler(config *kubeschedulerconfig.KubeSchedulerConfiguration, informers informers.SharedInformerFactory, isLeader func() bool, checks ...healthz.HealthChecker) http.Handler","file":"cmd/kube-scheduler/app/server.go","code":"// newHealthzAndMetricsHandler creates a healthz server from the config, and will also\n// embed the metrics handler.\nfunc newHealthzAndMetricsHandler(config *kubeschedulerconfig.KubeSchedulerConfiguration, informers informers.SharedInformerFactory, isLeader func() bool, checks ...healthz.HealthChecker) http.Handler {\n\tpathRecorderMux := mux.NewPathRecorderMux(\"kube-scheduler\")\n\thealthz.InstallHandler(pathRecorderMux, checks...)\n\tinstallMetricHandler(pathRecorderMux, informers, isLeader)\n\tif utilfeature.DefaultFeatureGate.Enabled(features.ComponentSLIs) {\n\t\tslis.SLIMetricsWithReset{}.Install(pathRecorderMux)\n\t}\n\tif config.EnableProfiling {\n\t\troutes.Profiling{}.Install(pathRecorderMux)\n\t\tif config.EnableContentionProfiling {\n\t\t\tgoruntime.SetBlockProfileRate(1)\n\t\t}\n\t\troutes.DebugFlags{}.Install(pathRecorderMux, \"v\", routes.StringFlagPutHandler(logs.GlogSetter))\n\t}\n\treturn pathRecorderMux\n}","line":{"from":275,"to":292}} {"id":100000401,"name":"getRecorderFactory","signature":"func getRecorderFactory(cc *schedulerserverconfig.CompletedConfig) profile.RecorderFactory","file":"cmd/kube-scheduler/app/server.go","code":"func getRecorderFactory(cc *schedulerserverconfig.CompletedConfig) profile.RecorderFactory {\n\treturn func(name string) events.EventRecorder {\n\t\treturn cc.EventBroadcaster.NewRecorder(name)\n\t}\n}","line":{"from":294,"to":298}} {"id":100000402,"name":"WithPlugin","signature":"func WithPlugin(name string, factory runtime.PluginFactory) Option","file":"cmd/kube-scheduler/app/server.go","code":"// WithPlugin creates an Option based on plugin name and factory. Please don't remove this function: it is used to register out-of-tree plugins,\n// hence there are no references to it from the kubernetes scheduler code base.\nfunc WithPlugin(name string, factory runtime.PluginFactory) Option {\n\treturn func(registry runtime.Registry) error {\n\t\treturn registry.Register(name, factory)\n\t}\n}","line":{"from":300,"to":306}} {"id":100000403,"name":"Setup","signature":"func Setup(ctx context.Context, opts *options.Options, outOfTreeRegistryOptions ...Option) (*schedulerserverconfig.CompletedConfig, *scheduler.Scheduler, error)","file":"cmd/kube-scheduler/app/server.go","code":"// Setup creates a completed config and a scheduler based on the command args and options\nfunc Setup(ctx context.Context, opts *options.Options, outOfTreeRegistryOptions ...Option) (*schedulerserverconfig.CompletedConfig, *scheduler.Scheduler, error) {\n\tif cfg, err := latest.Default(); err != nil {\n\t\treturn nil, nil, err\n\t} else {\n\t\topts.ComponentConfig = cfg\n\t}\n\n\tif errs := opts.Validate(); len(errs) \u003e 0 {\n\t\treturn nil, nil, utilerrors.NewAggregate(errs)\n\t}\n\n\tc, err := opts.Config(ctx)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Get the completed config\n\tcc := c.Complete()\n\n\toutOfTreeRegistry := make(runtime.Registry)\n\tfor _, option := range outOfTreeRegistryOptions {\n\t\tif err := option(outOfTreeRegistry); err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\trecorderFactory := getRecorderFactory(\u0026cc)\n\tcompletedProfiles := make([]kubeschedulerconfig.KubeSchedulerProfile, 0)\n\t// Create the scheduler.\n\tsched, err := scheduler.New(cc.Client,\n\t\tcc.InformerFactory,\n\t\tcc.DynInformerFactory,\n\t\trecorderFactory,\n\t\tctx.Done(),\n\t\tscheduler.WithComponentConfigVersion(cc.ComponentConfig.TypeMeta.APIVersion),\n\t\tscheduler.WithKubeConfig(cc.KubeConfig),\n\t\tscheduler.WithProfiles(cc.ComponentConfig.Profiles...),\n\t\tscheduler.WithPercentageOfNodesToScore(cc.ComponentConfig.PercentageOfNodesToScore),\n\t\tscheduler.WithFrameworkOutOfTreeRegistry(outOfTreeRegistry),\n\t\tscheduler.WithPodMaxBackoffSeconds(cc.ComponentConfig.PodMaxBackoffSeconds),\n\t\tscheduler.WithPodInitialBackoffSeconds(cc.ComponentConfig.PodInitialBackoffSeconds),\n\t\tscheduler.WithPodMaxInUnschedulablePodsDuration(cc.PodMaxInUnschedulablePodsDuration),\n\t\tscheduler.WithExtenders(cc.ComponentConfig.Extenders...),\n\t\tscheduler.WithParallelism(cc.ComponentConfig.Parallelism),\n\t\tscheduler.WithBuildFrameworkCapturer(func(profile kubeschedulerconfig.KubeSchedulerProfile) {\n\t\t\t// Profiles are processed during Framework instantiation to set default plugins and configurations. Capturing them for logging\n\t\t\tcompletedProfiles = append(completedProfiles, profile)\n\t\t}),\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif err := options.LogOrWriteConfig(klog.FromContext(ctx), opts.WriteConfigTo, \u0026cc.ComponentConfig, completedProfiles); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn \u0026cc, sched, nil\n}","line":{"from":308,"to":366}} {"id":100000404,"name":"main","signature":"func main()","file":"cmd/kube-scheduler/scheduler.go","code":"func main() {\n\tcommand := app.NewSchedulerCommand()\n\tcode := cli.Run(command)\n\tos.Exit(code)\n}","line":{"from":29,"to":33}} {"id":100000405,"name":"MarshalJSON","signature":"func (bts BootstrapTokenString) MarshalJSON() ([]byte, error)","file":"cmd/kubeadm/app/apis/bootstraptoken/v1/utils.go","code":"// MarshalJSON implements the json.Marshaler interface.\nfunc (bts BootstrapTokenString) MarshalJSON() ([]byte, error) {\n\treturn []byte(fmt.Sprintf(`\"%s\"`, bts.String())), nil\n}","line":{"from":46,"to":49}} {"id":100000406,"name":"UnmarshalJSON","signature":"func (bts *BootstrapTokenString) UnmarshalJSON(b []byte) error","file":"cmd/kubeadm/app/apis/bootstraptoken/v1/utils.go","code":"// UnmarshalJSON implements the json.Unmarshaller interface.\nfunc (bts *BootstrapTokenString) UnmarshalJSON(b []byte) error {\n\t// If the token is represented as \"\", just return quickly without an error\n\tif len(b) == 0 {\n\t\treturn nil\n\t}\n\n\t// Remove unnecessary \" characters coming from the JSON parser\n\ttoken := strings.Replace(string(b), `\"`, ``, -1)\n\t// Convert the string Token to a BootstrapTokenString object\n\tnewbts, err := NewBootstrapTokenString(token)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbts.ID = newbts.ID\n\tbts.Secret = newbts.Secret\n\treturn nil\n}","line":{"from":51,"to":68}} {"id":100000407,"name":"String","signature":"func (bts BootstrapTokenString) String() string","file":"cmd/kubeadm/app/apis/bootstraptoken/v1/utils.go","code":"// String returns the string representation of the BootstrapTokenString\nfunc (bts BootstrapTokenString) String() string {\n\tif len(bts.ID) \u003e 0 \u0026\u0026 len(bts.Secret) \u003e 0 {\n\t\treturn bootstraputil.TokenFromIDAndSecret(bts.ID, bts.Secret)\n\t}\n\treturn \"\"\n}","line":{"from":70,"to":76}} {"id":100000408,"name":"NewBootstrapTokenString","signature":"func NewBootstrapTokenString(token string) (*BootstrapTokenString, error)","file":"cmd/kubeadm/app/apis/bootstraptoken/v1/utils.go","code":"// NewBootstrapTokenString converts the given Bootstrap Token as a string\n// to the BootstrapTokenString object used for serialization/deserialization\n// and internal usage. It also automatically validates that the given token\n// is of the right format\nfunc NewBootstrapTokenString(token string) (*BootstrapTokenString, error) {\n\tsubstrs := bootstraputil.BootstrapTokenRegexp.FindStringSubmatch(token)\n\tif len(substrs) != validatedSubstringsSize {\n\t\treturn nil, errors.Errorf(\"the bootstrap token %q was not of the form %q\", token, bootstrapapi.BootstrapTokenPattern)\n\t}\n\n\treturn \u0026BootstrapTokenString{ID: substrs[1], Secret: substrs[2]}, nil\n}","line":{"from":78,"to":89}} {"id":100000409,"name":"NewBootstrapTokenStringFromIDAndSecret","signature":"func NewBootstrapTokenStringFromIDAndSecret(id, secret string) (*BootstrapTokenString, error)","file":"cmd/kubeadm/app/apis/bootstraptoken/v1/utils.go","code":"// NewBootstrapTokenStringFromIDAndSecret is a wrapper around NewBootstrapTokenString\n// that allows the caller to specify the ID and Secret separately\nfunc NewBootstrapTokenStringFromIDAndSecret(id, secret string) (*BootstrapTokenString, error) {\n\treturn NewBootstrapTokenString(bootstraputil.TokenFromIDAndSecret(id, secret))\n}","line":{"from":91,"to":95}} {"id":100000410,"name":"BootstrapTokenToSecret","signature":"func BootstrapTokenToSecret(bt *BootstrapToken) *v1.Secret","file":"cmd/kubeadm/app/apis/bootstraptoken/v1/utils.go","code":"// BootstrapTokenToSecret converts the given BootstrapToken object to its Secret representation that\n// may be submitted to the API Server in order to be stored.\nfunc BootstrapTokenToSecret(bt *BootstrapToken) *v1.Secret {\n\treturn \u0026v1.Secret{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: bootstraputil.BootstrapTokenSecretName(bt.Token.ID),\n\t\t\tNamespace: metav1.NamespaceSystem,\n\t\t},\n\t\tType: v1.SecretType(bootstrapapi.SecretTypeBootstrapToken),\n\t\tData: encodeTokenSecretData(bt, time.Now()),\n\t}\n}","line":{"from":97,"to":108}} {"id":100000411,"name":"encodeTokenSecretData","signature":"func encodeTokenSecretData(token *BootstrapToken, now time.Time) map[string][]byte","file":"cmd/kubeadm/app/apis/bootstraptoken/v1/utils.go","code":"// encodeTokenSecretData takes the token discovery object and an optional duration and returns the .Data for the Secret\n// now is passed in order to be able to used in unit testing\nfunc encodeTokenSecretData(token *BootstrapToken, now time.Time) map[string][]byte {\n\tdata := map[string][]byte{\n\t\tbootstrapapi.BootstrapTokenIDKey: []byte(token.Token.ID),\n\t\tbootstrapapi.BootstrapTokenSecretKey: []byte(token.Token.Secret),\n\t}\n\n\tif len(token.Description) \u003e 0 {\n\t\tdata[bootstrapapi.BootstrapTokenDescriptionKey] = []byte(token.Description)\n\t}\n\n\t// If for some strange reason both token.TTL and token.Expires would be set\n\t// (they are mutually exclusive in validation so this shouldn't be the case),\n\t// token.Expires has higher priority, as can be seen in the logic here.\n\tif token.Expires != nil {\n\t\t// Format the expiration date accordingly\n\t\t// TODO: This maybe should be a helper function in bootstraputil?\n\t\texpirationString := token.Expires.Time.UTC().Format(time.RFC3339)\n\t\tdata[bootstrapapi.BootstrapTokenExpirationKey] = []byte(expirationString)\n\n\t} else if token.TTL != nil \u0026\u0026 token.TTL.Duration \u003e 0 {\n\t\t// Only if .Expires is unset, TTL might have an effect\n\t\t// Get the current time, add the specified duration, and format it accordingly\n\t\texpirationString := now.Add(token.TTL.Duration).UTC().Format(time.RFC3339)\n\t\tdata[bootstrapapi.BootstrapTokenExpirationKey] = []byte(expirationString)\n\t}\n\n\tfor _, usage := range token.Usages {\n\t\tdata[bootstrapapi.BootstrapTokenUsagePrefix+usage] = []byte(\"true\")\n\t}\n\n\tif len(token.Groups) \u003e 0 {\n\t\tdata[bootstrapapi.BootstrapTokenExtraGroupsKey] = []byte(strings.Join(token.Groups, \",\"))\n\t}\n\treturn data\n}","line":{"from":110,"to":146}} {"id":100000412,"name":"BootstrapTokenFromSecret","signature":"func BootstrapTokenFromSecret(secret *v1.Secret) (*BootstrapToken, error)","file":"cmd/kubeadm/app/apis/bootstraptoken/v1/utils.go","code":"// BootstrapTokenFromSecret returns a BootstrapToken object from the given Secret\nfunc BootstrapTokenFromSecret(secret *v1.Secret) (*BootstrapToken, error) {\n\t// Get the Token ID field from the Secret data\n\ttokenID := bootstrapsecretutil.GetData(secret, bootstrapapi.BootstrapTokenIDKey)\n\tif len(tokenID) == 0 {\n\t\treturn nil, errors.Errorf(\"bootstrap Token Secret has no token-id data: %s\", secret.Name)\n\t}\n\n\t// Enforce the right naming convention\n\tif secret.Name != bootstraputil.BootstrapTokenSecretName(tokenID) {\n\t\treturn nil, errors.Errorf(\"bootstrap token name is not of the form '%s(token-id)'. Actual: %q. Expected: %q\",\n\t\t\tbootstrapapi.BootstrapTokenSecretPrefix, secret.Name, bootstraputil.BootstrapTokenSecretName(tokenID))\n\t}\n\n\ttokenSecret := bootstrapsecretutil.GetData(secret, bootstrapapi.BootstrapTokenSecretKey)\n\tif len(tokenSecret) == 0 {\n\t\treturn nil, errors.Errorf(\"bootstrap Token Secret has no token-secret data: %s\", secret.Name)\n\t}\n\n\t// Create the BootstrapTokenString object based on the ID and Secret\n\tbts, err := NewBootstrapTokenStringFromIDAndSecret(tokenID, tokenSecret)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"bootstrap Token Secret is invalid and couldn't be parsed\")\n\t}\n\n\t// Get the description (if any) from the Secret\n\tdescription := bootstrapsecretutil.GetData(secret, bootstrapapi.BootstrapTokenDescriptionKey)\n\n\t// Expiration time is optional, if not specified this implies the token\n\t// never expires.\n\tsecretExpiration := bootstrapsecretutil.GetData(secret, bootstrapapi.BootstrapTokenExpirationKey)\n\tvar expires *metav1.Time\n\tif len(secretExpiration) \u003e 0 {\n\t\texpTime, err := time.Parse(time.RFC3339, secretExpiration)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"can't parse expiration time of bootstrap token %q\", secret.Name)\n\t\t}\n\t\texpires = \u0026metav1.Time{Time: expTime}\n\t}\n\n\t// Build an usages string slice from the Secret data\n\tvar usages []string\n\tfor k, v := range secret.Data {\n\t\t// Skip all fields that don't include this prefix\n\t\tif !strings.HasPrefix(k, bootstrapapi.BootstrapTokenUsagePrefix) {\n\t\t\tcontinue\n\t\t}\n\t\t// Skip those that don't have this usage set to true\n\t\tif string(v) != \"true\" {\n\t\t\tcontinue\n\t\t}\n\t\tusages = append(usages, strings.TrimPrefix(k, bootstrapapi.BootstrapTokenUsagePrefix))\n\t}\n\t// Only sort the slice if defined\n\tif usages != nil {\n\t\tsort.Strings(usages)\n\t}\n\n\t// Get the extra groups information from the Secret\n\t// It's done this way to make .Groups be nil in case there is no items, rather than an\n\t// empty slice or an empty slice with a \"\" string only\n\tvar groups []string\n\tgroupsString := bootstrapsecretutil.GetData(secret, bootstrapapi.BootstrapTokenExtraGroupsKey)\n\tg := strings.Split(groupsString, \",\")\n\tif len(g) \u003e 0 \u0026\u0026 len(g[0]) \u003e 0 {\n\t\tgroups = g\n\t}\n\n\treturn \u0026BootstrapToken{\n\t\tToken: bts,\n\t\tDescription: description,\n\t\tExpires: expires,\n\t\tUsages: usages,\n\t\tGroups: groups,\n\t}, nil\n}","line":{"from":148,"to":223}} {"id":100000413,"name":"APIEndpointFromString","signature":"func APIEndpointFromString(apiEndpoint string) (APIEndpoint, error)","file":"cmd/kubeadm/app/apis/kubeadm/apiendpoint.go","code":"// APIEndpointFromString returns an APIEndpoint struct based on a \"host:port\" raw string.\nfunc APIEndpointFromString(apiEndpoint string) (APIEndpoint, error) {\n\tapiEndpointHost, apiEndpointPortStr, err := net.SplitHostPort(apiEndpoint)\n\tif err != nil {\n\t\treturn APIEndpoint{}, errors.Wrapf(err, \"invalid advertise address endpoint: %s\", apiEndpoint)\n\t}\n\tif netutils.ParseIPSloppy(apiEndpointHost) == nil {\n\t\treturn APIEndpoint{}, errors.Errorf(\"invalid API endpoint IP: %s\", apiEndpointHost)\n\t}\n\tapiEndpointPort, err := net.LookupPort(\"tcp\", apiEndpointPortStr)\n\tif err != nil {\n\t\treturn APIEndpoint{}, errors.Wrapf(err, \"invalid advertise address endpoint port: %s\", apiEndpointPortStr)\n\t}\n\treturn APIEndpoint{\n\t\tAdvertiseAddress: apiEndpointHost,\n\t\tBindPort: int32(apiEndpointPort),\n\t}, nil\n}","line":{"from":28,"to":45}} {"id":100000414,"name":"String","signature":"func (endpoint *APIEndpoint) String() string","file":"cmd/kubeadm/app/apis/kubeadm/apiendpoint.go","code":"func (endpoint *APIEndpoint) String() string {\n\treturn net.JoinHostPort(endpoint.AdvertiseAddress, strconv.FormatInt(int64(endpoint.BindPort), 10))\n}","line":{"from":47,"to":49}} {"id":100000415,"name":"Funcs","signature":"func Funcs(codecs runtimeserializer.CodecFactory) []interface{}","file":"cmd/kubeadm/app/apis/kubeadm/fuzzer/fuzzer.go","code":"// Funcs returns the fuzzer functions for the kubeadm apis.\nfunc Funcs(codecs runtimeserializer.CodecFactory) []interface{} {\n\treturn []interface{}{\n\t\tfuzzInitConfiguration,\n\t\tfuzzClusterConfiguration,\n\t\tfuzzComponentConfigMap,\n\t\tfuzzDNS,\n\t\tfuzzNodeRegistration,\n\t\tfuzzLocalEtcd,\n\t\tfuzzNetworking,\n\t\tfuzzJoinConfiguration,\n\t\tfuzzJoinControlPlane,\n\t}\n}","line":{"from":31,"to":44}} {"id":100000416,"name":"fuzzInitConfiguration","signature":"func fuzzInitConfiguration(obj *kubeadm.InitConfiguration, c fuzz.Continue)","file":"cmd/kubeadm/app/apis/kubeadm/fuzzer/fuzzer.go","code":"func fuzzInitConfiguration(obj *kubeadm.InitConfiguration, c fuzz.Continue) {\n\tc.FuzzNoCustom(obj)\n\n\t// Pinning values for fields that get defaults if fuzz value is empty string or nil (thus making the round trip test fail)\n\n\t// Avoid round tripping the ClusterConfiguration embedded in the InitConfiguration, since it is\n\t// only present in the internal version and not in public versions\n\tobj.ClusterConfiguration = kubeadm.ClusterConfiguration{}\n\n\t// Adds the default bootstrap token to get the round trip working\n\tobj.BootstrapTokens = []bootstraptokenv1.BootstrapToken{\n\t\t{\n\t\t\tGroups: []string{\"foo\"},\n\t\t\tUsages: []string{\"foo\"},\n\t\t\tTTL: \u0026metav1.Duration{Duration: 1234},\n\t\t},\n\t}\n\tobj.SkipPhases = nil\n\tobj.NodeRegistration.ImagePullPolicy = corev1.PullIfNotPresent\n\tobj.Patches = nil\n}","line":{"from":46,"to":66}} {"id":100000417,"name":"fuzzNodeRegistration","signature":"func fuzzNodeRegistration(obj *kubeadm.NodeRegistrationOptions, c fuzz.Continue)","file":"cmd/kubeadm/app/apis/kubeadm/fuzzer/fuzzer.go","code":"func fuzzNodeRegistration(obj *kubeadm.NodeRegistrationOptions, c fuzz.Continue) {\n\tc.FuzzNoCustom(obj)\n\n\t// Pinning values for fields that get defaults if fuzz value is empty string or nil (thus making the round trip test fail)\n\tobj.IgnorePreflightErrors = nil\n}","line":{"from":68,"to":73}} {"id":100000418,"name":"fuzzClusterConfiguration","signature":"func fuzzClusterConfiguration(obj *kubeadm.ClusterConfiguration, c fuzz.Continue)","file":"cmd/kubeadm/app/apis/kubeadm/fuzzer/fuzzer.go","code":"func fuzzClusterConfiguration(obj *kubeadm.ClusterConfiguration, c fuzz.Continue) {\n\tc.FuzzNoCustom(obj)\n\n\t// Pinning values for fields that get defaults if fuzz value is empty string or nil (thus making the round trip test fail)\n\tobj.CertificatesDir = \"foo\"\n\tobj.ClusterName = \"bar\"\n\tobj.ImageRepository = \"baz\"\n\tobj.CIImageRepository = \"\" // This fields doesn't exists in public API \u003e\u003e using default to get the roundtrip test pass\n\tobj.KubernetesVersion = \"qux\"\n\tobj.CIKubernetesVersion = \"\" // This fields doesn't exists in public API \u003e\u003e using default to get the roundtrip test pass\n\tobj.APIServer.TimeoutForControlPlane = \u0026metav1.Duration{\n\t\tDuration: constants.DefaultControlPlaneTimeout,\n\t}\n}","line":{"from":75,"to":88}} {"id":100000419,"name":"fuzzDNS","signature":"func fuzzDNS(obj *kubeadm.DNS, c fuzz.Continue)","file":"cmd/kubeadm/app/apis/kubeadm/fuzzer/fuzzer.go","code":"func fuzzDNS(obj *kubeadm.DNS, c fuzz.Continue) {\n\tc.FuzzNoCustom(obj)\n}","line":{"from":90,"to":92}} {"id":100000420,"name":"fuzzComponentConfigMap","signature":"func fuzzComponentConfigMap(obj *kubeadm.ComponentConfigMap, c fuzz.Continue)","file":"cmd/kubeadm/app/apis/kubeadm/fuzzer/fuzzer.go","code":"func fuzzComponentConfigMap(obj *kubeadm.ComponentConfigMap, c fuzz.Continue) {\n\t// This is intentionally empty because component config does not exists in the public api\n\t// (empty mean all ComponentConfigs fields nil, and this is necessary for getting roundtrip passing)\n}","line":{"from":94,"to":97}} {"id":100000421,"name":"fuzzLocalEtcd","signature":"func fuzzLocalEtcd(obj *kubeadm.LocalEtcd, c fuzz.Continue)","file":"cmd/kubeadm/app/apis/kubeadm/fuzzer/fuzzer.go","code":"func fuzzLocalEtcd(obj *kubeadm.LocalEtcd, c fuzz.Continue) {\n\tc.FuzzNoCustom(obj)\n\n\t// Pinning values for fields that get defaults if fuzz value is empty string or nil (thus making the round trip test fail)\n\tobj.DataDir = \"foo\"\n}","line":{"from":99,"to":104}} {"id":100000422,"name":"fuzzNetworking","signature":"func fuzzNetworking(obj *kubeadm.Networking, c fuzz.Continue)","file":"cmd/kubeadm/app/apis/kubeadm/fuzzer/fuzzer.go","code":"func fuzzNetworking(obj *kubeadm.Networking, c fuzz.Continue) {\n\tc.FuzzNoCustom(obj)\n\n\t// Pinning values for fields that get defaults if fuzz value is empty string or nil (thus making the round trip test fail)\n\tobj.DNSDomain = \"foo\"\n\tobj.ServiceSubnet = \"bar\"\n}","line":{"from":106,"to":112}} {"id":100000423,"name":"fuzzJoinConfiguration","signature":"func fuzzJoinConfiguration(obj *kubeadm.JoinConfiguration, c fuzz.Continue)","file":"cmd/kubeadm/app/apis/kubeadm/fuzzer/fuzzer.go","code":"func fuzzJoinConfiguration(obj *kubeadm.JoinConfiguration, c fuzz.Continue) {\n\tc.FuzzNoCustom(obj)\n\n\t// Pinning values for fields that get defaults if fuzz value is empty string or nil (thus making the round trip test fail)\n\tobj.CACertPath = \"foo\"\n\tobj.Discovery = kubeadm.Discovery{\n\t\tBootstrapToken: \u0026kubeadm.BootstrapTokenDiscovery{Token: \"baz\"},\n\t\tTLSBootstrapToken: \"qux\",\n\t\tTimeout: \u0026metav1.Duration{Duration: 1234},\n\t}\n\tobj.SkipPhases = nil\n\tobj.NodeRegistration.ImagePullPolicy = corev1.PullIfNotPresent\n\tobj.Patches = nil\n}","line":{"from":114,"to":127}} {"id":100000424,"name":"fuzzJoinControlPlane","signature":"func fuzzJoinControlPlane(obj *kubeadm.JoinControlPlane, c fuzz.Continue)","file":"cmd/kubeadm/app/apis/kubeadm/fuzzer/fuzzer.go","code":"func fuzzJoinControlPlane(obj *kubeadm.JoinControlPlane, c fuzz.Continue) {\n\tc.FuzzNoCustom(obj)\n}","line":{"from":129,"to":131}} {"id":100000425,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"cmd/kubeadm/app/apis/kubeadm/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":37,"to":40}} {"id":100000426,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"cmd/kubeadm/app/apis/kubeadm/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":42,"to":45}} {"id":100000427,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"cmd/kubeadm/app/apis/kubeadm/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026InitConfiguration{},\n\t\t\u0026ClusterConfiguration{},\n\t\t\u0026JoinConfiguration{},\n\t)\n\treturn nil\n}","line":{"from":47,"to":54}} {"id":100000428,"name":"init","signature":"func init()","file":"cmd/kubeadm/app/apis/kubeadm/scheme/scheme.go","code":"func init() {\n\tmetav1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: \"v1\"})\n\tAddToScheme(Scheme)\n}","line":{"from":36,"to":39}} {"id":100000429,"name":"AddToScheme","signature":"func AddToScheme(scheme *runtime.Scheme)","file":"cmd/kubeadm/app/apis/kubeadm/scheme/scheme.go","code":"// AddToScheme builds the kubeadm scheme using all known versions of the kubeadm api.\nfunc AddToScheme(scheme *runtime.Scheme) {\n\tutilruntime.Must(kubeadm.AddToScheme(scheme))\n\tutilruntime.Must(v1beta3.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1beta3.SchemeGroupVersion))\n}","line":{"from":41,"to":46}} {"id":100000430,"name":"GetControlPlaneImageRepository","signature":"func (cfg *ClusterConfiguration) GetControlPlaneImageRepository() string","file":"cmd/kubeadm/app/apis/kubeadm/types.go","code":"// GetControlPlaneImageRepository returns name of image repository\n// for control plane images (API,Controller Manager,Scheduler and Proxy)\n// It will override location with CI registry name in case user requests special\n// Kubernetes version from CI build area.\n// (See: kubeadmconstants.DefaultCIImageRepository)\nfunc (cfg *ClusterConfiguration) GetControlPlaneImageRepository() string {\n\tif cfg.CIImageRepository != \"\" {\n\t\treturn cfg.CIImageRepository\n\t}\n\treturn cfg.ImageRepository\n}","line":{"from":375,"to":385}} {"id":100000431,"name":"PublicKeyAlgorithm","signature":"func (cfg *ClusterConfiguration) PublicKeyAlgorithm() x509.PublicKeyAlgorithm","file":"cmd/kubeadm/app/apis/kubeadm/types.go","code":"// PublicKeyAlgorithm returns the type of encryption keys used in the cluster.\nfunc (cfg *ClusterConfiguration) PublicKeyAlgorithm() x509.PublicKeyAlgorithm {\n\tif features.Enabled(cfg.FeatureGates, features.PublicKeysECDSA) {\n\t\treturn x509.ECDSA\n\t}\n\n\treturn x509.RSA\n}","line":{"from":387,"to":394}} {"id":100000432,"name":"Convert_kubeadm_InitConfiguration_To_v1beta3_InitConfiguration","signature":"func Convert_kubeadm_InitConfiguration_To_v1beta3_InitConfiguration(in *kubeadm.InitConfiguration, out *InitConfiguration, s conversion.Scope) error","file":"cmd/kubeadm/app/apis/kubeadm/v1beta3/conversion.go","code":"func Convert_kubeadm_InitConfiguration_To_v1beta3_InitConfiguration(in *kubeadm.InitConfiguration, out *InitConfiguration, s conversion.Scope) error {\n\treturn autoConvert_kubeadm_InitConfiguration_To_v1beta3_InitConfiguration(in, out, s)\n}","line":{"from":25,"to":27}} {"id":100000433,"name":"Convert_v1beta3_InitConfiguration_To_kubeadm_InitConfiguration","signature":"func Convert_v1beta3_InitConfiguration_To_kubeadm_InitConfiguration(in *InitConfiguration, out *kubeadm.InitConfiguration, s conversion.Scope) error","file":"cmd/kubeadm/app/apis/kubeadm/v1beta3/conversion.go","code":"func Convert_v1beta3_InitConfiguration_To_kubeadm_InitConfiguration(in *InitConfiguration, out *kubeadm.InitConfiguration, s conversion.Scope) error {\n\terr := autoConvert_v1beta3_InitConfiguration_To_kubeadm_InitConfiguration(in, out, s)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = Convert_v1beta3_ClusterConfiguration_To_kubeadm_ClusterConfiguration(\u0026ClusterConfiguration{}, \u0026out.ClusterConfiguration, s)\n\treturn err\n}","line":{"from":29,"to":36}} {"id":100000434,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"cmd/kubeadm/app/apis/kubeadm/v1beta3/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":65,"to":67}} {"id":100000435,"name":"SetDefaults_InitConfiguration","signature":"func SetDefaults_InitConfiguration(obj *InitConfiguration)","file":"cmd/kubeadm/app/apis/kubeadm/v1beta3/defaults.go","code":"// SetDefaults_InitConfiguration assigns default values for the InitConfiguration\nfunc SetDefaults_InitConfiguration(obj *InitConfiguration) {\n\tSetDefaults_BootstrapTokens(obj)\n\tSetDefaults_APIEndpoint(\u0026obj.LocalAPIEndpoint)\n\tSetDefaults_NodeRegistration(\u0026obj.NodeRegistration)\n}","line":{"from":69,"to":74}} {"id":100000436,"name":"SetDefaults_ClusterConfiguration","signature":"func SetDefaults_ClusterConfiguration(obj *ClusterConfiguration)","file":"cmd/kubeadm/app/apis/kubeadm/v1beta3/defaults.go","code":"// SetDefaults_ClusterConfiguration assigns default values for the ClusterConfiguration\nfunc SetDefaults_ClusterConfiguration(obj *ClusterConfiguration) {\n\tif obj.KubernetesVersion == \"\" {\n\t\tobj.KubernetesVersion = DefaultKubernetesVersion\n\t}\n\n\tif obj.Networking.ServiceSubnet == \"\" {\n\t\tobj.Networking.ServiceSubnet = DefaultServicesSubnet\n\t}\n\n\tif obj.Networking.DNSDomain == \"\" {\n\t\tobj.Networking.DNSDomain = DefaultServiceDNSDomain\n\t}\n\n\tif obj.CertificatesDir == \"\" {\n\t\tobj.CertificatesDir = DefaultCertificatesDir\n\t}\n\n\tif obj.ImageRepository == \"\" {\n\t\tobj.ImageRepository = DefaultImageRepository\n\t}\n\n\tif obj.ClusterName == \"\" {\n\t\tobj.ClusterName = DefaultClusterName\n\t}\n\n\tSetDefaults_Etcd(obj)\n\tSetDefaults_APIServer(\u0026obj.APIServer)\n}","line":{"from":76,"to":104}} {"id":100000437,"name":"SetDefaults_APIServer","signature":"func SetDefaults_APIServer(obj *APIServer)","file":"cmd/kubeadm/app/apis/kubeadm/v1beta3/defaults.go","code":"// SetDefaults_APIServer assigns default values for the API Server\nfunc SetDefaults_APIServer(obj *APIServer) {\n\tif obj.TimeoutForControlPlane == nil {\n\t\tobj.TimeoutForControlPlane = \u0026metav1.Duration{\n\t\t\tDuration: constants.DefaultControlPlaneTimeout,\n\t\t}\n\t}\n}","line":{"from":106,"to":113}} {"id":100000438,"name":"SetDefaults_Etcd","signature":"func SetDefaults_Etcd(obj *ClusterConfiguration)","file":"cmd/kubeadm/app/apis/kubeadm/v1beta3/defaults.go","code":"// SetDefaults_Etcd assigns default values for the proxy\nfunc SetDefaults_Etcd(obj *ClusterConfiguration) {\n\tif obj.Etcd.External == nil \u0026\u0026 obj.Etcd.Local == nil {\n\t\tobj.Etcd.Local = \u0026LocalEtcd{}\n\t}\n\tif obj.Etcd.Local != nil {\n\t\tif obj.Etcd.Local.DataDir == \"\" {\n\t\t\tobj.Etcd.Local.DataDir = DefaultEtcdDataDir\n\t\t}\n\t}\n}","line":{"from":115,"to":125}} {"id":100000439,"name":"SetDefaults_JoinConfiguration","signature":"func SetDefaults_JoinConfiguration(obj *JoinConfiguration)","file":"cmd/kubeadm/app/apis/kubeadm/v1beta3/defaults.go","code":"// SetDefaults_JoinConfiguration assigns default values to a regular node\nfunc SetDefaults_JoinConfiguration(obj *JoinConfiguration) {\n\tif obj.CACertPath == \"\" {\n\t\tobj.CACertPath = DefaultCACertPath\n\t}\n\n\tSetDefaults_JoinControlPlane(obj.ControlPlane)\n\tSetDefaults_Discovery(\u0026obj.Discovery)\n\tSetDefaults_NodeRegistration(\u0026obj.NodeRegistration)\n}","line":{"from":127,"to":136}} {"id":100000440,"name":"SetDefaults_JoinControlPlane","signature":"func SetDefaults_JoinControlPlane(obj *JoinControlPlane)","file":"cmd/kubeadm/app/apis/kubeadm/v1beta3/defaults.go","code":"func SetDefaults_JoinControlPlane(obj *JoinControlPlane) {\n\tif obj != nil {\n\t\tSetDefaults_APIEndpoint(\u0026obj.LocalAPIEndpoint)\n\t}\n}","line":{"from":138,"to":142}} {"id":100000441,"name":"SetDefaults_Discovery","signature":"func SetDefaults_Discovery(obj *Discovery)","file":"cmd/kubeadm/app/apis/kubeadm/v1beta3/defaults.go","code":"// SetDefaults_Discovery assigns default values for the discovery process\nfunc SetDefaults_Discovery(obj *Discovery) {\n\tif len(obj.TLSBootstrapToken) == 0 \u0026\u0026 obj.BootstrapToken != nil {\n\t\tobj.TLSBootstrapToken = obj.BootstrapToken.Token\n\t}\n\n\tif obj.Timeout == nil {\n\t\tobj.Timeout = \u0026metav1.Duration{\n\t\t\tDuration: DefaultDiscoveryTimeout,\n\t\t}\n\t}\n\n\tif obj.File != nil {\n\t\tSetDefaults_FileDiscovery(obj.File)\n\t}\n}","line":{"from":144,"to":159}} {"id":100000442,"name":"SetDefaults_FileDiscovery","signature":"func SetDefaults_FileDiscovery(obj *FileDiscovery)","file":"cmd/kubeadm/app/apis/kubeadm/v1beta3/defaults.go","code":"// SetDefaults_FileDiscovery assigns default values for file based discovery\nfunc SetDefaults_FileDiscovery(obj *FileDiscovery) {\n\t// Make sure file URL becomes path\n\tif len(obj.KubeConfigPath) != 0 {\n\t\tu, err := url.Parse(obj.KubeConfigPath)\n\t\tif err == nil \u0026\u0026 u.Scheme == \"file\" {\n\t\t\tobj.KubeConfigPath = u.Path\n\t\t}\n\t}\n}","line":{"from":161,"to":170}} {"id":100000443,"name":"SetDefaults_BootstrapTokens","signature":"func SetDefaults_BootstrapTokens(obj *InitConfiguration)","file":"cmd/kubeadm/app/apis/kubeadm/v1beta3/defaults.go","code":"// SetDefaults_BootstrapTokens sets the defaults for the .BootstrapTokens field\n// If the slice is empty, it's defaulted with one token. Otherwise it just loops\n// through the slice and sets the defaults for the omitempty fields that are TTL,\n// Usages and Groups. Token is NOT defaulted with a random one in the API defaulting\n// layer, but set to a random value later at runtime if not set before.\nfunc SetDefaults_BootstrapTokens(obj *InitConfiguration) {\n\n\tif obj.BootstrapTokens == nil || len(obj.BootstrapTokens) == 0 {\n\t\tobj.BootstrapTokens = []bootstraptokenv1.BootstrapToken{{}}\n\t}\n\n\tfor i := range obj.BootstrapTokens {\n\t\tSetDefaults_BootstrapToken(\u0026obj.BootstrapTokens[i])\n\t}\n}","line":{"from":172,"to":186}} {"id":100000444,"name":"SetDefaults_BootstrapToken","signature":"func SetDefaults_BootstrapToken(bt *bootstraptokenv1.BootstrapToken)","file":"cmd/kubeadm/app/apis/kubeadm/v1beta3/defaults.go","code":"// SetDefaults_BootstrapToken sets the defaults for an individual Bootstrap Token\nfunc SetDefaults_BootstrapToken(bt *bootstraptokenv1.BootstrapToken) {\n\tif bt.TTL == nil {\n\t\tbt.TTL = \u0026metav1.Duration{\n\t\t\tDuration: constants.DefaultTokenDuration,\n\t\t}\n\t}\n\tif len(bt.Usages) == 0 {\n\t\tbt.Usages = constants.DefaultTokenUsages\n\t}\n\n\tif len(bt.Groups) == 0 {\n\t\tbt.Groups = constants.DefaultTokenGroups\n\t}\n}","line":{"from":188,"to":202}} {"id":100000445,"name":"SetDefaults_APIEndpoint","signature":"func SetDefaults_APIEndpoint(obj *APIEndpoint)","file":"cmd/kubeadm/app/apis/kubeadm/v1beta3/defaults.go","code":"// SetDefaults_APIEndpoint sets the defaults for the API server instance deployed on a node.\nfunc SetDefaults_APIEndpoint(obj *APIEndpoint) {\n\tif obj.BindPort == 0 {\n\t\tobj.BindPort = DefaultAPIBindPort\n\t}\n}","line":{"from":204,"to":209}} {"id":100000446,"name":"SetDefaults_NodeRegistration","signature":"func SetDefaults_NodeRegistration(obj *NodeRegistrationOptions)","file":"cmd/kubeadm/app/apis/kubeadm/v1beta3/defaults.go","code":"// SetDefaults_NodeRegistration sets the defaults for the NodeRegistrationOptions object\nfunc SetDefaults_NodeRegistration(obj *NodeRegistrationOptions) {\n\tif len(obj.ImagePullPolicy) == 0 {\n\t\tobj.ImagePullPolicy = DefaultImagePullPolicy\n\t}\n}","line":{"from":211,"to":216}} {"id":100000447,"name":"init","signature":"func init()","file":"cmd/kubeadm/app/apis/kubeadm/v1beta3/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addKnownTypes, addDefaultingFuncs)\n}","line":{"from":39,"to":44}} {"id":100000448,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"cmd/kubeadm/app/apis/kubeadm/v1beta3/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":46,"to":49}} {"id":100000449,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"cmd/kubeadm/app/apis/kubeadm/v1beta3/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":51,"to":54}} {"id":100000450,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"cmd/kubeadm/app/apis/kubeadm/v1beta3/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026InitConfiguration{},\n\t\t\u0026ClusterConfiguration{},\n\t\t\u0026JoinConfiguration{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":56,"to":64}} {"id":100000451,"name":"isAbs","signature":"func isAbs(path string) bool","file":"cmd/kubeadm/app/apis/kubeadm/validation/util_unix.go","code":"func isAbs(path string) bool {\n\treturn filepath.IsAbs(path)\n}","line":{"from":26,"to":28}} {"id":100000452,"name":"isAbs","signature":"func isAbs(path string) bool","file":"cmd/kubeadm/app/apis/kubeadm/validation/util_windows.go","code":"func isAbs(path string) bool {\n\t// on Windows, filepath.IsAbs will not return True for paths prefixed with a slash, even\n\t// though they can be used as absolute paths (https://docs.microsoft.com/en-us/dotnet/standard/io/file-path-formats).\n\treturn filepath.IsAbs(path) || (len(path) \u003e 0 \u0026\u0026 (path[0] == '\\\\' || path[0] == '/'))\n}","line":{"from":26,"to":30}} {"id":100000453,"name":"ValidateInitConfiguration","signature":"func ValidateInitConfiguration(c *kubeadm.InitConfiguration) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateInitConfiguration validates an InitConfiguration object and collects all encountered errors\nfunc ValidateInitConfiguration(c *kubeadm.InitConfiguration) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, ValidateNodeRegistrationOptions(\u0026c.NodeRegistration, field.NewPath(\"nodeRegistration\"))...)\n\tallErrs = append(allErrs, ValidateBootstrapTokens(c.BootstrapTokens, field.NewPath(\"bootstrapTokens\"))...)\n\tallErrs = append(allErrs, ValidateClusterConfiguration(\u0026c.ClusterConfiguration)...)\n\t// TODO(Arvinderpal): update advertiseAddress validation for dual-stack once it's implemented.\n\tallErrs = append(allErrs, ValidateAPIEndpoint(\u0026c.LocalAPIEndpoint, field.NewPath(\"localAPIEndpoint\"))...)\n\t// TODO: Maybe validate that .CertificateKey is a valid hex encoded AES key\n\treturn allErrs\n}","line":{"from":49,"to":59}} {"id":100000454,"name":"ValidateClusterConfiguration","signature":"func ValidateClusterConfiguration(c *kubeadm.ClusterConfiguration) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateClusterConfiguration validates an ClusterConfiguration object and collects all encountered errors\nfunc ValidateClusterConfiguration(c *kubeadm.ClusterConfiguration) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, ValidateDNS(\u0026c.DNS, field.NewPath(\"dns\"))...)\n\tallErrs = append(allErrs, ValidateNetworking(c, field.NewPath(\"networking\"))...)\n\tallErrs = append(allErrs, ValidateAPIServer(\u0026c.APIServer, field.NewPath(\"apiServer\"))...)\n\tallErrs = append(allErrs, ValidateAbsolutePath(c.CertificatesDir, field.NewPath(\"certificatesDir\"))...)\n\tallErrs = append(allErrs, ValidateFeatureGates(c.FeatureGates, field.NewPath(\"featureGates\"))...)\n\tallErrs = append(allErrs, ValidateHostPort(c.ControlPlaneEndpoint, field.NewPath(\"controlPlaneEndpoint\"))...)\n\tallErrs = append(allErrs, ValidateImageRepository(c.ImageRepository, field.NewPath(\"imageRepository\"))...)\n\tallErrs = append(allErrs, ValidateEtcd(\u0026c.Etcd, field.NewPath(\"etcd\"))...)\n\tallErrs = append(allErrs, componentconfigs.Validate(c)...)\n\treturn allErrs\n}","line":{"from":61,"to":74}} {"id":100000455,"name":"ValidateAPIServer","signature":"func ValidateAPIServer(a *kubeadm.APIServer, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateAPIServer validates a APIServer object and collects all encountered errors\nfunc ValidateAPIServer(a *kubeadm.APIServer, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, ValidateCertSANs(a.CertSANs, fldPath.Child(\"certSANs\"))...)\n\treturn allErrs\n}","line":{"from":76,"to":81}} {"id":100000456,"name":"ValidateJoinConfiguration","signature":"func ValidateJoinConfiguration(c *kubeadm.JoinConfiguration) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateJoinConfiguration validates node configuration and collects all encountered errors\nfunc ValidateJoinConfiguration(c *kubeadm.JoinConfiguration) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, ValidateDiscovery(\u0026c.Discovery, field.NewPath(\"discovery\"))...)\n\tallErrs = append(allErrs, ValidateNodeRegistrationOptions(\u0026c.NodeRegistration, field.NewPath(\"nodeRegistration\"))...)\n\tallErrs = append(allErrs, ValidateJoinControlPlane(c.ControlPlane, field.NewPath(\"controlPlane\"))...)\n\n\tif !isAbs(c.CACertPath) || !strings.HasSuffix(c.CACertPath, \".crt\") {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"caCertPath\"), c.CACertPath, \"the ca certificate path must be an absolute path\"))\n\t}\n\treturn allErrs\n}","line":{"from":83,"to":94}} {"id":100000457,"name":"ValidateJoinControlPlane","signature":"func ValidateJoinControlPlane(c *kubeadm.JoinControlPlane, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateJoinControlPlane validates joining control plane configuration and collects all encountered errors\nfunc ValidateJoinControlPlane(c *kubeadm.JoinControlPlane, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif c != nil {\n\t\tallErrs = append(allErrs, ValidateAPIEndpoint(\u0026c.LocalAPIEndpoint, fldPath.Child(\"localAPIEndpoint\"))...)\n\t\t// TODO: Maybe validate that .CertificateKey is a valid hex encoded AES key\n\t}\n\treturn allErrs\n}","line":{"from":96,"to":104}} {"id":100000458,"name":"ValidateNodeRegistrationOptions","signature":"func ValidateNodeRegistrationOptions(nro *kubeadm.NodeRegistrationOptions, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateNodeRegistrationOptions validates the NodeRegistrationOptions object\nfunc ValidateNodeRegistrationOptions(nro *kubeadm.NodeRegistrationOptions, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(nro.Name) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath, \"--node-name or .nodeRegistration.name in the config file is a required value. It seems like this value couldn't be automatically detected in your environment, please specify the desired value using the CLI or config file.\"))\n\t} else {\n\t\tnameFldPath := fldPath.Child(\"name\")\n\t\tfor _, err := range validation.IsDNS1123Subdomain(nro.Name) {\n\t\t\tallErrs = append(allErrs, field.Invalid(nameFldPath, nro.Name, err))\n\t\t}\n\t}\n\tallErrs = append(allErrs, ValidateSocketPath(nro.CRISocket, fldPath.Child(\"criSocket\"))...)\n\t// TODO: Maybe validate .Taints as well in the future using something like validateNodeTaints() in pkg/apis/core/validation\n\treturn allErrs\n}","line":{"from":106,"to":120}} {"id":100000459,"name":"ValidateDiscovery","signature":"func ValidateDiscovery(d *kubeadm.Discovery, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateDiscovery validates discovery related configuration and collects all encountered errors\nfunc ValidateDiscovery(d *kubeadm.Discovery, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif d.BootstrapToken == nil \u0026\u0026 d.File == nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, \"\", \"bootstrapToken or file must be set\"))\n\t}\n\n\tif d.BootstrapToken != nil \u0026\u0026 d.File != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, \"\", \"bootstrapToken and file cannot both be set\"))\n\t}\n\n\tif d.BootstrapToken != nil {\n\t\tallErrs = append(allErrs, ValidateDiscoveryBootstrapToken(d.BootstrapToken, fldPath.Child(\"bootstrapToken\"))...)\n\t\tallErrs = append(allErrs, ValidateToken(d.TLSBootstrapToken, fldPath.Child(\"tlsBootstrapToken\"))...)\n\t}\n\n\tif d.File != nil {\n\t\tallErrs = append(allErrs, ValidateDiscoveryFile(d.File, fldPath.Child(\"file\"))...)\n\t\tif len(d.TLSBootstrapToken) != 0 {\n\t\t\tallErrs = append(allErrs, ValidateToken(d.TLSBootstrapToken, fldPath.Child(\"tlsBootstrapToken\"))...)\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":122,"to":147}} {"id":100000460,"name":"ValidateDiscoveryBootstrapToken","signature":"func ValidateDiscoveryBootstrapToken(b *kubeadm.BootstrapTokenDiscovery, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateDiscoveryBootstrapToken validates bootstrap token discovery configuration\nfunc ValidateDiscoveryBootstrapToken(b *kubeadm.BootstrapTokenDiscovery, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(b.APIServerEndpoint) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath, \"APIServerEndpoint is not set\"))\n\t}\n\n\tif len(b.CACertHashes) == 0 \u0026\u0026 !b.UnsafeSkipCAVerification {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"caCertHashes\"), \"\", \"using token-based discovery without caCertHashes can be unsafe. Set unsafeSkipCAVerification as true in your kubeadm config file or pass --discovery-token-unsafe-skip-ca-verification flag to continue\"))\n\t}\n\n\tallErrs = append(allErrs, ValidateToken(b.Token, fldPath.Child(kubeadmcmdoptions.TokenStr))...)\n\tallErrs = append(allErrs, ValidateDiscoveryTokenAPIServer(b.APIServerEndpoint, fldPath.Child(\"apiServerEndpoint\"))...)\n\n\treturn allErrs\n}","line":{"from":149,"to":165}} {"id":100000461,"name":"ValidateDiscoveryFile","signature":"func ValidateDiscoveryFile(f *kubeadm.FileDiscovery, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateDiscoveryFile validates file discovery configuration\nfunc ValidateDiscoveryFile(f *kubeadm.FileDiscovery, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tallErrs = append(allErrs, ValidateDiscoveryKubeConfigPath(f.KubeConfigPath, fldPath.Child(\"kubeConfigPath\"))...)\n\n\treturn allErrs\n}","line":{"from":167,"to":174}} {"id":100000462,"name":"ValidateDiscoveryTokenAPIServer","signature":"func ValidateDiscoveryTokenAPIServer(apiServer string, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateDiscoveryTokenAPIServer validates discovery token for API server\nfunc ValidateDiscoveryTokenAPIServer(apiServer string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\t_, _, err := net.SplitHostPort(apiServer)\n\tif err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, apiServer, err.Error()))\n\t}\n\treturn allErrs\n}","line":{"from":176,"to":184}} {"id":100000463,"name":"ValidateDiscoveryKubeConfigPath","signature":"func ValidateDiscoveryKubeConfigPath(discoveryFile string, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateDiscoveryKubeConfigPath validates location of a discovery file\nfunc ValidateDiscoveryKubeConfigPath(discoveryFile string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tu, err := url.Parse(discoveryFile)\n\tif err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, discoveryFile, \"not a valid HTTPS URL or a file on disk\"))\n\t\treturn allErrs\n\t}\n\n\tif u.Scheme == \"\" {\n\t\t// URIs with no scheme should be treated as files\n\t\tif _, err := os.Stat(discoveryFile); os.IsNotExist(err) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, discoveryFile, \"not a valid HTTPS URL or a file on disk\"))\n\t\t}\n\t\treturn allErrs\n\t}\n\n\tif u.Scheme != \"https\" {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, discoveryFile, \"if a URL is used, the scheme must be https\"))\n\t}\n\treturn allErrs\n}","line":{"from":186,"to":207}} {"id":100000464,"name":"ValidateBootstrapTokens","signature":"func ValidateBootstrapTokens(bts []bootstraptokenv1.BootstrapToken, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateBootstrapTokens validates a slice of BootstrapToken objects\nfunc ValidateBootstrapTokens(bts []bootstraptokenv1.BootstrapToken, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor i, bt := range bts {\n\t\tbtPath := fldPath.Child(fmt.Sprintf(\"%d\", i))\n\t\tallErrs = append(allErrs, ValidateToken(bt.Token.String(), btPath.Child(kubeadmcmdoptions.TokenStr))...)\n\t\tallErrs = append(allErrs, ValidateTokenUsages(bt.Usages, btPath.Child(kubeadmcmdoptions.TokenUsages))...)\n\t\tallErrs = append(allErrs, ValidateTokenGroups(bt.Usages, bt.Groups, btPath.Child(kubeadmcmdoptions.TokenGroups))...)\n\n\t\tif bt.Expires != nil \u0026\u0026 bt.TTL != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(btPath, \"\", \"the BootstrapToken .TTL and .Expires fields are mutually exclusive\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":209,"to":223}} {"id":100000465,"name":"ValidateToken","signature":"func ValidateToken(token string, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateToken validates a Bootstrap Token\nfunc ValidateToken(token string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif !bootstraputil.IsValidBootstrapToken(token) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, token, \"the bootstrap token is invalid\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":225,"to":234}} {"id":100000466,"name":"ValidateTokenGroups","signature":"func ValidateTokenGroups(usages []string, groups []string, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateTokenGroups validates token groups\nfunc ValidateTokenGroups(usages []string, groups []string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\t// adding groups only makes sense for authentication\n\tusagesSet := sets.New(usages...)\n\tusageAuthentication := strings.TrimPrefix(bootstrapapi.BootstrapTokenUsageAuthentication, bootstrapapi.BootstrapTokenUsagePrefix)\n\tif len(groups) \u003e 0 \u0026\u0026 !usagesSet.Has(usageAuthentication) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, groups, fmt.Sprintf(\"token groups cannot be specified unless --usages includes %q\", usageAuthentication)))\n\t}\n\n\t// validate any extra group names\n\tfor _, group := range groups {\n\t\tif err := bootstraputil.ValidateBootstrapGroupName(group); err != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, groups, err.Error()))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":236,"to":255}} {"id":100000467,"name":"ValidateTokenUsages","signature":"func ValidateTokenUsages(usages []string, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateTokenUsages validates token usages\nfunc ValidateTokenUsages(usages []string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\t// validate usages\n\tif err := bootstraputil.ValidateUsages(usages); err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, usages, err.Error()))\n\t}\n\n\treturn allErrs\n}","line":{"from":257,"to":267}} {"id":100000468,"name":"ValidateEtcd","signature":"func ValidateEtcd(e *kubeadm.Etcd, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateEtcd validates the .Etcd sub-struct.\nfunc ValidateEtcd(e *kubeadm.Etcd, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tlocalPath := fldPath.Child(\"local\")\n\texternalPath := fldPath.Child(\"external\")\n\n\tif e.Local == nil \u0026\u0026 e.External == nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, \"\", \"either .Etcd.Local or .Etcd.External is required\"))\n\t\treturn allErrs\n\t}\n\tif e.Local != nil \u0026\u0026 e.External != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, \"\", \".Etcd.Local and .Etcd.External are mutually exclusive\"))\n\t\treturn allErrs\n\t}\n\tif e.Local != nil {\n\t\tallErrs = append(allErrs, ValidateAbsolutePath(e.Local.DataDir, localPath.Child(\"dataDir\"))...)\n\t\tallErrs = append(allErrs, ValidateCertSANs(e.Local.ServerCertSANs, localPath.Child(\"serverCertSANs\"))...)\n\t\tallErrs = append(allErrs, ValidateCertSANs(e.Local.PeerCertSANs, localPath.Child(\"peerCertSANs\"))...)\n\t\tif len(e.Local.ImageRepository) \u003e 0 {\n\t\t\tallErrs = append(allErrs, ValidateImageRepository(e.Local.ImageRepository, localPath.Child(\"imageRepository\"))...)\n\t\t}\n\t}\n\tif e.External != nil {\n\t\trequireHTTPS := true\n\t\t// Only allow the http scheme if no certs/keys are passed\n\t\tif e.External.CAFile == \"\" \u0026\u0026 e.External.CertFile == \"\" \u0026\u0026 e.External.KeyFile == \"\" {\n\t\t\trequireHTTPS = false\n\t\t}\n\t\t// Require either none or both of the cert/key pair\n\t\tif (e.External.CertFile == \"\" \u0026\u0026 e.External.KeyFile != \"\") || (e.External.CertFile != \"\" \u0026\u0026 e.External.KeyFile == \"\") {\n\t\t\tallErrs = append(allErrs, field.Invalid(externalPath, \"\", \"either both or none of .Etcd.External.CertFile and .Etcd.External.KeyFile must be set\"))\n\t\t}\n\t\t// If the cert and key are specified, require the CA as well\n\t\tif e.External.CertFile != \"\" \u0026\u0026 e.External.KeyFile != \"\" \u0026\u0026 e.External.CAFile == \"\" {\n\t\t\tallErrs = append(allErrs, field.Invalid(externalPath, \"\", \"setting .Etcd.External.CertFile and .Etcd.External.KeyFile requires .Etcd.External.CAFile\"))\n\t\t}\n\n\t\tallErrs = append(allErrs, ValidateURLs(e.External.Endpoints, requireHTTPS, externalPath.Child(\"endpoints\"))...)\n\t\tif e.External.CAFile != \"\" {\n\t\t\tallErrs = append(allErrs, ValidateAbsolutePath(e.External.CAFile, externalPath.Child(\"caFile\"))...)\n\t\t}\n\t\tif e.External.CertFile != \"\" {\n\t\t\tallErrs = append(allErrs, ValidateAbsolutePath(e.External.CertFile, externalPath.Child(\"certFile\"))...)\n\t\t}\n\t\tif e.External.KeyFile != \"\" {\n\t\t\tallErrs = append(allErrs, ValidateAbsolutePath(e.External.KeyFile, externalPath.Child(\"keyFile\"))...)\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":269,"to":318}} {"id":100000469,"name":"ValidateCertSANs","signature":"func ValidateCertSANs(altnames []string, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateCertSANs validates alternative names\nfunc ValidateCertSANs(altnames []string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor _, altname := range altnames {\n\t\tif errs := validation.IsDNS1123Subdomain(altname); len(errs) != 0 {\n\t\t\tif errs2 := validation.IsWildcardDNS1123Subdomain(altname); len(errs2) != 0 {\n\t\t\t\tif netutils.ParseIPSloppy(altname) == nil {\n\t\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, altname, fmt.Sprintf(\"altname is not a valid IP address, DNS label or a DNS label with subdomain wildcards: %s; %s\", strings.Join(errs, \"; \"), strings.Join(errs2, \"; \"))))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":320,"to":333}} {"id":100000470,"name":"ValidateURLs","signature":"func ValidateURLs(urls []string, requireHTTPS bool, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateURLs validates the URLs given in the string slice, makes sure they are parsable. Optionally, it can enforces HTTPS usage.\nfunc ValidateURLs(urls []string, requireHTTPS bool, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor _, urlstr := range urls {\n\t\tu, err := url.Parse(urlstr)\n\t\tif err != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, urlstr, fmt.Sprintf(\"URL parse error: %v\", err)))\n\t\t\tcontinue\n\t\t}\n\t\tif requireHTTPS \u0026\u0026 u.Scheme != \"https\" {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, urlstr, \"the URL must be using the HTTPS scheme\"))\n\t\t}\n\t\tif u.Scheme == \"\" {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, urlstr, \"the URL without scheme is not allowed\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":335,"to":352}} {"id":100000471,"name":"ValidateIPFromString","signature":"func ValidateIPFromString(ipaddr string, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateIPFromString validates ip address\nfunc ValidateIPFromString(ipaddr string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif netutils.ParseIPSloppy(ipaddr) == nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, ipaddr, \"ip address is not valid\"))\n\t}\n\treturn allErrs\n}","line":{"from":354,"to":361}} {"id":100000472,"name":"ValidatePort","signature":"func ValidatePort(port int32, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidatePort validates port numbers\nfunc ValidatePort(port int32, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif _, err := kubeadmutil.ParsePort(strconv.Itoa(int(port))); err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, port, \"port number is not valid\"))\n\t}\n\treturn allErrs\n}","line":{"from":363,"to":370}} {"id":100000473,"name":"ValidateHostPort","signature":"func ValidateHostPort(endpoint string, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateHostPort validates host[:port] endpoints\nfunc ValidateHostPort(endpoint string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif _, _, err := kubeadmutil.ParseHostPort(endpoint); endpoint != \"\" \u0026\u0026 err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, endpoint, \"endpoint is not valid\"))\n\t}\n\treturn allErrs\n}","line":{"from":372,"to":379}} {"id":100000474,"name":"ValidateIPNetFromString","signature":"func ValidateIPNetFromString(subnetStr string, minAddrs int64, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateIPNetFromString validates network portion of ip address\nfunc ValidateIPNetFromString(subnetStr string, minAddrs int64, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tsubnets, err := netutils.ParseCIDRs(strings.Split(subnetStr, \",\"))\n\tif err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, subnetStr, \"couldn't parse subnet\"))\n\t\treturn allErrs\n\t}\n\tswitch {\n\t// if DualStack only 2 CIDRs allowed\n\tcase len(subnets) \u003e 2:\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, subnetStr, \"expected one (IPv4 or IPv6) CIDR or two CIDRs from each family for dual-stack networking\"))\n\t// if DualStack and there are 2 CIDRs validate if there is at least one of each IP family\n\tcase len(subnets) == 2:\n\t\tareDualStackCIDRs, err := netutils.IsDualStackCIDRs(subnets)\n\t\tif err != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, subnetStr, err.Error()))\n\t\t} else if !areDualStackCIDRs {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, subnetStr, \"expected one (IPv4 or IPv6) CIDR or two CIDRs from each family for dual-stack networking\"))\n\t\t}\n\t}\n\t// validate the subnet/s\n\tfor _, s := range subnets {\n\t\tnumAddresses := netutils.RangeSize(s)\n\t\tif numAddresses \u003c minAddrs {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, s.String(), fmt.Sprintf(\"subnet with %d address(es) is too small, the minimum is %d\", numAddresses, minAddrs)))\n\t\t}\n\n\t\t// Warn when the subnet is in site-local range - i.e. contains addresses that belong to fec0::/10\n\t\t_, siteLocalNet, _ := netutils.ParseCIDRSloppy(\"fec0::/10\")\n\t\tif siteLocalNet.Contains(s.IP) || s.Contains(siteLocalNet.IP) {\n\t\t\tklog.Warningf(\"the subnet %v contains IPv6 site-local addresses that belong to fec0::/10 which has been deprecated by rfc3879\", s)\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":381,"to":416}} {"id":100000475,"name":"ValidateServiceSubnetSize","signature":"func ValidateServiceSubnetSize(subnetStr string, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateServiceSubnetSize validates that the maximum subnet size is not exceeded\n// Should be a small cidr due to how it is stored in etcd.\n// bigger cidr (specially those offered by IPv6) will add no value\n// and significantly increase snapshotting time.\n// NOTE: This is identical to validation performed in the apiserver.\nfunc ValidateServiceSubnetSize(subnetStr string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\t// subnets were already validated\n\tsubnets, _ := netutils.ParseCIDRs(strings.Split(subnetStr, \",\"))\n\tfor _, serviceSubnet := range subnets {\n\t\tones, bits := serviceSubnet.Mask.Size()\n\t\tif bits-ones \u003e constants.MaximumBitsForServiceSubnet {\n\t\t\terrMsg := fmt.Sprintf(\"specified service subnet is too large; for %d-bit addresses, the mask must be \u003e= %d\", bits, bits-constants.MaximumBitsForServiceSubnet)\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, serviceSubnet.String(), errMsg))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":418,"to":435}} {"id":100000476,"name":"ValidatePodSubnetNodeMask","signature":"func ValidatePodSubnetNodeMask(subnetStr string, c *kubeadm.ClusterConfiguration, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidatePodSubnetNodeMask validates that the relation between podSubnet and node-masks is correct\nfunc ValidatePodSubnetNodeMask(subnetStr string, c *kubeadm.ClusterConfiguration, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\t// subnets were already validated\n\tsubnets, _ := netutils.ParseCIDRs(strings.Split(subnetStr, \",\"))\n\tfor _, podSubnet := range subnets {\n\t\t// obtain podSubnet mask\n\t\tmask := podSubnet.Mask\n\t\tmaskSize, _ := mask.Size()\n\t\t// obtain node-cidr-mask\n\t\tnodeMask, err := getClusterNodeMask(c, netutils.IsIPv6(podSubnet.IP))\n\t\tif err != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, podSubnet.String(), err.Error()))\n\t\t\tcontinue\n\t\t}\n\t\t// the pod subnet mask needs to allow one or multiple node-masks\n\t\t// i.e. if it has a /24 the node mask must be between 24 and 32 for ipv4\n\t\tif maskSize \u003e nodeMask {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, podSubnet.String(), fmt.Sprintf(\"the size of pod subnet with mask %d is smaller than the size of node subnet with mask %d\", maskSize, nodeMask)))\n\t\t} else if (nodeMask - maskSize) \u003e constants.PodSubnetNodeMaskMaxDiff {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, podSubnet.String(), fmt.Sprintf(\"pod subnet mask (%d) and node-mask (%d) difference is greater than %d\", maskSize, nodeMask, constants.PodSubnetNodeMaskMaxDiff)))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":437,"to":461}} {"id":100000477,"name":"getClusterNodeMask","signature":"func getClusterNodeMask(c *kubeadm.ClusterConfiguration, isIPv6 bool) (int, error)","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// getClusterNodeMask returns the corresponding node-cidr-mask\n// based on the Cluster configuration and the IP family\n// Default is 24 for IPv4 and 64 for IPv6\nfunc getClusterNodeMask(c *kubeadm.ClusterConfiguration, isIPv6 bool) (int, error) {\n\t// defaultNodeMaskCIDRIPv4 is default mask size for IPv4 node cidr for use by the controller manager\n\tconst defaultNodeMaskCIDRIPv4 = 24\n\t// defaultNodeMaskCIDRIPv6 is default mask size for IPv6 node cidr for use by the controller manager\n\tconst defaultNodeMaskCIDRIPv6 = 64\n\tvar maskSize int\n\tvar maskArg string\n\tvar err error\n\n\tif isIPv6 {\n\t\tmaskArg = \"node-cidr-mask-size-ipv6\"\n\t} else {\n\t\tmaskArg = \"node-cidr-mask-size-ipv4\"\n\t}\n\n\tif v, ok := c.ControllerManager.ExtraArgs[maskArg]; ok \u0026\u0026 v != \"\" {\n\t\t// assume it is an integer, if not it will fail later\n\t\tmaskSize, err = strconv.Atoi(v)\n\t\tif err != nil {\n\t\t\treturn 0, errors.Wrapf(err, \"could not parse the value of the kube-controller-manager flag %s as an integer\", maskArg)\n\t\t}\n\t} else if isIPv6 {\n\t\tmaskSize = defaultNodeMaskCIDRIPv6\n\t} else {\n\t\tmaskSize = defaultNodeMaskCIDRIPv4\n\t}\n\treturn maskSize, nil\n}","line":{"from":463,"to":493}} {"id":100000478,"name":"ValidateDNS","signature":"func ValidateDNS(dns *kubeadm.DNS, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateDNS validates the DNS object and collects all encountered errors\nfunc ValidateDNS(dns *kubeadm.DNS, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(dns.ImageRepository) \u003e 0 {\n\t\tallErrs = append(allErrs, ValidateImageRepository(dns.ImageRepository, fldPath.Child(\"imageRepository\"))...)\n\t}\n\n\treturn allErrs\n}","line":{"from":495,"to":504}} {"id":100000479,"name":"ValidateNetworking","signature":"func ValidateNetworking(c *kubeadm.ClusterConfiguration, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateNetworking validates networking configuration\nfunc ValidateNetworking(c *kubeadm.ClusterConfiguration, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tdnsDomainFldPath := fldPath.Child(\"dnsDomain\")\n\tfor _, err := range validation.IsDNS1123Subdomain(c.Networking.DNSDomain) {\n\t\tallErrs = append(allErrs, field.Invalid(dnsDomainFldPath, c.Networking.DNSDomain, err))\n\t}\n\n\tif len(c.Networking.ServiceSubnet) != 0 {\n\t\tallErrs = append(allErrs, ValidateIPNetFromString(c.Networking.ServiceSubnet, constants.MinimumAddressesInServiceSubnet, fldPath.Child(\"serviceSubnet\"))...)\n\t\t// Service subnet was already validated, we need to validate now the subnet size\n\t\tallErrs = append(allErrs, ValidateServiceSubnetSize(c.Networking.ServiceSubnet, fldPath.Child(\"serviceSubnet\"))...)\n\t}\n\tif len(c.Networking.PodSubnet) != 0 {\n\t\tallErrs = append(allErrs, ValidateIPNetFromString(c.Networking.PodSubnet, constants.MinimumAddressesInPodSubnet, fldPath.Child(\"podSubnet\"))...)\n\t\tif c.ControllerManager.ExtraArgs[\"allocate-node-cidrs\"] != \"false\" {\n\t\t\t// Pod subnet was already validated, we need to validate now against the node-mask\n\t\t\tallErrs = append(allErrs, ValidatePodSubnetNodeMask(c.Networking.PodSubnet, c, fldPath.Child(\"podSubnet\"))...)\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":506,"to":527}} {"id":100000480,"name":"ValidateAbsolutePath","signature":"func ValidateAbsolutePath(path string, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateAbsolutePath validates whether provided path is absolute or not\nfunc ValidateAbsolutePath(path string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif !isAbs(path) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, path, \"path is not absolute\"))\n\t}\n\treturn allErrs\n}","line":{"from":529,"to":536}} {"id":100000481,"name":"ValidateMixedArguments","signature":"func ValidateMixedArguments(flag *pflag.FlagSet) error","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateMixedArguments validates passed arguments\nfunc ValidateMixedArguments(flag *pflag.FlagSet) error {\n\t// If --config isn't set, we have nothing to validate\n\tif !flag.Changed(\"config\") {\n\t\treturn nil\n\t}\n\n\tmixedInvalidFlags := []string{}\n\tflag.Visit(func(f *pflag.Flag) {\n\t\tif isAllowedFlag(f.Name) {\n\t\t\t// \"--skip-*\" flags or other allowed flags can be set with --config\n\t\t\treturn\n\t\t}\n\t\tmixedInvalidFlags = append(mixedInvalidFlags, f.Name)\n\t})\n\n\tif len(mixedInvalidFlags) != 0 {\n\t\treturn errors.Errorf(\"can not mix '--config' with arguments %v\", mixedInvalidFlags)\n\t}\n\treturn nil\n}","line":{"from":538,"to":558}} {"id":100000482,"name":"isAllowedFlag","signature":"func isAllowedFlag(flagName string) bool","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"func isAllowedFlag(flagName string) bool {\n\tallowedFlags := sets.New(kubeadmcmdoptions.CfgPath,\n\t\tkubeadmcmdoptions.IgnorePreflightErrors,\n\t\tkubeadmcmdoptions.DryRun,\n\t\tkubeadmcmdoptions.KubeconfigPath,\n\t\tkubeadmcmdoptions.NodeName,\n\t\tkubeadmcmdoptions.KubeconfigDir,\n\t\tkubeadmcmdoptions.UploadCerts,\n\t\t\"print-join-command\", \"rootfs\", \"v\", \"log-file\")\n\tif allowedFlags.Has(flagName) {\n\t\treturn true\n\t}\n\treturn strings.HasPrefix(flagName, \"skip-\")\n}","line":{"from":560,"to":573}} {"id":100000483,"name":"ValidateFeatureGates","signature":"func ValidateFeatureGates(featureGates map[string]bool, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateFeatureGates validates provided feature gates\nfunc ValidateFeatureGates(featureGates map[string]bool, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\t// check valid feature names are provided\n\tfor k := range featureGates {\n\t\tif !features.Supports(features.InitFeatureGates, k) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, featureGates,\n\t\t\t\tfmt.Sprintf(\"%s is not a valid feature name.\", k)))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":575,"to":587}} {"id":100000484,"name":"ValidateAPIEndpoint","signature":"func ValidateAPIEndpoint(c *kubeadm.APIEndpoint, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateAPIEndpoint validates API server's endpoint\nfunc ValidateAPIEndpoint(c *kubeadm.APIEndpoint, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, ValidateIPFromString(c.AdvertiseAddress, fldPath.Child(\"advertiseAddress\"))...)\n\tallErrs = append(allErrs, ValidatePort(c.BindPort, fldPath.Child(\"bindPort\"))...)\n\treturn allErrs\n}","line":{"from":589,"to":595}} {"id":100000485,"name":"ValidateIgnorePreflightErrors","signature":"func ValidateIgnorePreflightErrors(ignorePreflightErrorsFromCLI, ignorePreflightErrorsFromConfigFile []string) (sets.Set[string], error)","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateIgnorePreflightErrors validates duplicates in:\n// - ignore-preflight-errors flag and\n// - ignorePreflightErrors field in {Init,Join}Configuration files.\nfunc ValidateIgnorePreflightErrors(ignorePreflightErrorsFromCLI, ignorePreflightErrorsFromConfigFile []string) (sets.Set[string], error) {\n\tignoreErrors := sets.New[string]()\n\tallErrs := field.ErrorList{}\n\n\tfor _, item := range ignorePreflightErrorsFromConfigFile {\n\t\tignoreErrors.Insert(strings.ToLower(item)) // parameters are case insensitive\n\t}\n\n\tif ignoreErrors.Has(\"all\") {\n\t\t// \"all\" is forbidden in config files. Administrators should use an\n\t\t// explicit list of errors they want to ignore, as it can be risky to\n\t\t// mask all errors in such a way. Hence, we return an error:\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"ignorePreflightErrors\"), \"all\", \"'all' cannot be used in configuration file\"))\n\t}\n\n\tfor _, item := range ignorePreflightErrorsFromCLI {\n\t\tignoreErrors.Insert(strings.ToLower(item)) // parameters are case insensitive\n\t}\n\n\tif ignoreErrors.Has(\"all\") \u0026\u0026 ignoreErrors.Len() \u003e 1 {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"ignore-preflight-errors\"), strings.Join(sets.List(ignoreErrors), \",\"), \"don't specify individual checks if 'all' is used\"))\n\t}\n\n\treturn ignoreErrors, allErrs.ToAggregate()\n}","line":{"from":597,"to":624}} {"id":100000486,"name":"ValidateSocketPath","signature":"func ValidateSocketPath(socket string, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateSocketPath validates format of socket path or url\nfunc ValidateSocketPath(socket string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(socket) == 0 { // static and dynamic defaulting should have added a value to the field already\n\t\treturn append(allErrs, field.Invalid(fldPath, socket, \"empty CRI socket\"))\n\t}\n\n\tu, err := url.Parse(socket)\n\tif err != nil {\n\t\treturn append(allErrs, field.Invalid(fldPath, socket, fmt.Sprintf(\"URL parsing error: %v\", err)))\n\t}\n\n\t// static and dynamic defaulting should have ensured that an URL scheme is used\n\tif u.Scheme != kubeadmapiv1.DefaultContainerRuntimeURLScheme {\n\t\treturn append(allErrs, field.Invalid(fldPath, socket, fmt.Sprintf(\"only URL scheme %q is supported, got %q\", kubeadmapiv1.DefaultContainerRuntimeURLScheme, u.Scheme)))\n\t}\n\n\treturn allErrs\n}","line":{"from":626,"to":645}} {"id":100000487,"name":"ValidateImageRepository","signature":"func ValidateImageRepository(imageRepository string, fldPath *field.Path) field.ErrorList","file":"cmd/kubeadm/app/apis/kubeadm/validation/validation.go","code":"// ValidateImageRepository validates the image repository format\nfunc ValidateImageRepository(imageRepository string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\timage := fmt.Sprintf(\"%s/%s:%s\", imageRepository, \"name\", \"tag\")\n\tif !reference.ReferenceRegexp.MatchString(image) {\n\t\treturn append(allErrs, field.Invalid(fldPath, imageRepository, \"invalid image repository format\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":647,"to":657}} {"id":100000488,"name":"Funcs","signature":"func Funcs(codecs runtimeserializer.CodecFactory) []interface{}","file":"cmd/kubeadm/app/apis/output/fuzzer/fuzzer.go","code":"// Funcs returns the fuzzer functions for the kubeadm apis.\nfunc Funcs(codecs runtimeserializer.CodecFactory) []interface{} {\n\treturn []interface{}{\n\t\tfuzzBootstrapToken,\n\t}\n}","line":{"from":32,"to":37}} {"id":100000489,"name":"fuzzBootstrapToken","signature":"func fuzzBootstrapToken(obj *output.BootstrapToken, c fuzz.Continue)","file":"cmd/kubeadm/app/apis/output/fuzzer/fuzzer.go","code":"func fuzzBootstrapToken(obj *output.BootstrapToken, c fuzz.Continue) {\n\tc.FuzzNoCustom(obj)\n\n\tobj.Token = \u0026bootstraptokenv1.BootstrapTokenString{ID: \"uvxdac\", Secret: \"fq35fuyue3kd4gda\"}\n\tobj.Description = \"\"\n\tobj.TTL = \u0026metav1.Duration{Duration: time.Hour * 24}\n\tobj.Usages = []string{\"authentication\", \"signing\"}\n\tobj.Groups = []string{constants.NodeBootstrapTokenAuthGroup}\n}","line":{"from":39,"to":47}} {"id":100000490,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"cmd/kubeadm/app/apis/output/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":37,"to":40}} {"id":100000491,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"cmd/kubeadm/app/apis/output/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":42,"to":45}} {"id":100000492,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"cmd/kubeadm/app/apis/output/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026BootstrapToken{},\n\t\t\u0026Images{},\n\t\t\u0026UpgradePlan{},\n\t)\n\treturn nil\n}","line":{"from":47,"to":54}} {"id":100000493,"name":"init","signature":"func init()","file":"cmd/kubeadm/app/apis/output/scheme/scheme.go","code":"func init() {\n\tmetav1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: \"v1\"})\n\tAddToScheme(Scheme)\n}","line":{"from":36,"to":39}} {"id":100000494,"name":"AddToScheme","signature":"func AddToScheme(scheme *runtime.Scheme)","file":"cmd/kubeadm/app/apis/output/scheme/scheme.go","code":"// AddToScheme builds the kubeadm scheme using all known versions of the kubeadm api.\nfunc AddToScheme(scheme *runtime.Scheme) {\n\tutilruntime.Must(output.AddToScheme(scheme))\n\tutilruntime.Must(v1alpha2.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1alpha2.SchemeGroupVersion))\n}","line":{"from":41,"to":46}} {"id":100000495,"name":"init","signature":"func init()","file":"cmd/kubeadm/app/apis/output/v1alpha2/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addKnownTypes)\n}","line":{"from":39,"to":44}} {"id":100000496,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"cmd/kubeadm/app/apis/output/v1alpha2/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":46,"to":49}} {"id":100000497,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"cmd/kubeadm/app/apis/output/v1alpha2/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":51,"to":54}} {"id":100000498,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"cmd/kubeadm/app/apis/output/v1alpha2/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026BootstrapToken{},\n\t\t\u0026Images{},\n\t\t\u0026UpgradePlan{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":56,"to":64}} {"id":100000499,"name":"NewCmdAlpha","signature":"func NewCmdAlpha() *cobra.Command","file":"cmd/kubeadm/app/cmd/alpha/alpha.go","code":"// NewCmdAlpha returns \"kubeadm alpha\" command.\nfunc NewCmdAlpha() *cobra.Command {\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"alpha\",\n\t\tShort: \"Kubeadm experimental sub-commands\",\n\t}\n\n\treturn cmd\n}","line":{"from":23,"to":31}} {"id":100000500,"name":"newCmdCertsUtility","signature":"func newCmdCertsUtility(out io.Writer) *cobra.Command","file":"cmd/kubeadm/app/cmd/certs.go","code":"// newCmdCertsUtility returns main command for certs phase\nfunc newCmdCertsUtility(out io.Writer) *cobra.Command {\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"certs\",\n\t\tAliases: []string{\"certificates\"},\n\t\tShort: \"Commands related to handling kubernetes certificates\",\n\t\tRun: cmdutil.SubCmdRun(),\n\t}\n\n\tcmd.AddCommand(newCmdCertsRenewal(out))\n\tcmd.AddCommand(newCmdCertsExpiration(out, kubeadmconstants.KubernetesDir))\n\tcmd.AddCommand(newCmdCertificateKey())\n\tcmd.AddCommand(newCmdGenCSR(out))\n\treturn cmd\n}","line":{"from":93,"to":107}} {"id":100000501,"name":"newGenCSRConfig","signature":"func newGenCSRConfig() *genCSRConfig","file":"cmd/kubeadm/app/cmd/certs.go","code":"func newGenCSRConfig() *genCSRConfig {\n\treturn \u0026genCSRConfig{\n\t\tkubeConfigDir: kubeadmconstants.KubernetesDir,\n\t}\n}","line":{"from":117,"to":121}} {"id":100000502,"name":"addFlagSet","signature":"func (o *genCSRConfig) addFlagSet(flagSet *pflag.FlagSet)","file":"cmd/kubeadm/app/cmd/certs.go","code":"func (o *genCSRConfig) addFlagSet(flagSet *pflag.FlagSet) {\n\toptions.AddConfigFlag(flagSet, \u0026o.kubeadmConfigPath)\n\toptions.AddCertificateDirFlag(flagSet, \u0026o.certDir)\n\toptions.AddKubeConfigDirFlag(flagSet, \u0026o.kubeConfigDir)\n}","line":{"from":123,"to":127}} {"id":100000503,"name":"load","signature":"func (o *genCSRConfig) load() (err error)","file":"cmd/kubeadm/app/cmd/certs.go","code":"// load merges command line flag values into kubeadm's config.\n// Reads Kubeadm config from a file (if present)\n// else use dynamically generated default config.\n// This configuration contains the DNS names and IP addresses which\n// are encoded in the control-plane CSRs.\nfunc (o *genCSRConfig) load() (err error) {\n\to.kubeadmConfig, err = configutil.LoadOrDefaultInitConfiguration(\n\t\to.kubeadmConfigPath,\n\t\tcmdutil.DefaultInitConfiguration(),\n\t\t\u0026kubeadmapiv1.ClusterConfiguration{},\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// --cert-dir takes priority over kubeadm config if set.\n\tif o.certDir != \"\" {\n\t\to.kubeadmConfig.CertificatesDir = o.certDir\n\t}\n\treturn nil\n}","line":{"from":129,"to":148}} {"id":100000504,"name":"newCmdGenCSR","signature":"func newCmdGenCSR(out io.Writer) *cobra.Command","file":"cmd/kubeadm/app/cmd/certs.go","code":"// newCmdGenCSR returns cobra.Command for generating keys and CSRs\nfunc newCmdGenCSR(out io.Writer) *cobra.Command {\n\tconfig := newGenCSRConfig()\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"generate-csr\",\n\t\tShort: \"Generate keys and certificate signing requests\",\n\t\tLong: generateCSRLongDesc,\n\t\tExample: generateCSRExample,\n\t\tArgs: cobra.NoArgs,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tif err := config.load(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn runGenCSR(out, config)\n\t\t},\n\t}\n\tconfig.addFlagSet(cmd.Flags())\n\treturn cmd\n}","line":{"from":150,"to":169}} {"id":100000505,"name":"runGenCSR","signature":"func runGenCSR(out io.Writer, config *genCSRConfig) error","file":"cmd/kubeadm/app/cmd/certs.go","code":"// runGenCSR contains the logic of the generate-csr sub-command.\nfunc runGenCSR(out io.Writer, config *genCSRConfig) error {\n\tif err := certsphase.CreateDefaultKeysAndCSRFiles(out, config.kubeadmConfig); err != nil {\n\t\treturn err\n\t}\n\tif err := kubeconfigphase.CreateDefaultKubeConfigsAndCSRFiles(out, config.kubeConfigDir, config.kubeadmConfig); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":171,"to":180}} {"id":100000506,"name":"newCmdCertificateKey","signature":"func newCmdCertificateKey() *cobra.Command","file":"cmd/kubeadm/app/cmd/certs.go","code":"// newCmdCertificateKey returns cobra.Command for certificate key generate\nfunc newCmdCertificateKey() *cobra.Command {\n\treturn \u0026cobra.Command{\n\t\tUse: \"certificate-key\",\n\t\tShort: \"Generate certificate keys\",\n\t\tLong: certificateKeyLongDesc,\n\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tkey, err := copycerts.CreateCertificateKey()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfmt.Println(key)\n\t\t\treturn nil\n\t\t},\n\t\tArgs: cobra.NoArgs,\n\t}\n}","line":{"from":182,"to":199}} {"id":100000507,"name":"newCmdCertsRenewal","signature":"func newCmdCertsRenewal(out io.Writer) *cobra.Command","file":"cmd/kubeadm/app/cmd/certs.go","code":"// newCmdCertsRenewal creates a new `cert renew` command.\nfunc newCmdCertsRenewal(out io.Writer) *cobra.Command {\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"renew\",\n\t\tShort: \"Renew certificates for a Kubernetes cluster\",\n\t\tLong: cmdutil.MacroCommandLongDescription,\n\t\tRun: cmdutil.SubCmdRun(),\n\t}\n\n\tcmd.AddCommand(getRenewSubCommands(out, kubeadmconstants.KubernetesDir)...)\n\n\treturn cmd\n}","line":{"from":201,"to":213}} {"id":100000508,"name":"getRenewSubCommands","signature":"func getRenewSubCommands(out io.Writer, kdir string) []*cobra.Command","file":"cmd/kubeadm/app/cmd/certs.go","code":"func getRenewSubCommands(out io.Writer, kdir string) []*cobra.Command {\n\tflags := \u0026renewFlags{\n\t\tcfg: kubeadmapiv1.ClusterConfiguration{\n\t\t\t// Setting kubernetes version to a default value in order to allow a not necessary internet lookup\n\t\t\tKubernetesVersion: kubeadmconstants.CurrentKubernetesVersion.String(),\n\t\t},\n\t\tkubeconfigPath: kubeadmconstants.GetAdminKubeConfigPath(),\n\t}\n\t// Default values for the cobra help text\n\tkubeadmscheme.Scheme.Default(\u0026flags.cfg)\n\n\t// Get a renewal manager for a generic Cluster configuration, that is used only for getting\n\t// the list of certificates for building subcommands\n\trm, err := renewal.NewManager(\u0026kubeadmapi.ClusterConfiguration{}, \"\")\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tcmdList := []*cobra.Command{}\n\tfor _, handler := range rm.Certificates() {\n\t\t// get the cobra.Command skeleton for this command\n\t\tcmd := \u0026cobra.Command{\n\t\t\tUse: handler.Name,\n\t\t\tShort: fmt.Sprintf(\"Renew the %s\", handler.LongName),\n\t\t\tLong: fmt.Sprintf(genericCertRenewLongDesc, handler.LongName),\n\t\t}\n\t\taddRenewFlags(cmd, flags)\n\t\t// get the implementation of renewing this certificate\n\t\trenewalFunc := func(handler *renewal.CertificateRenewHandler) func() error {\n\t\t\treturn func() error {\n\t\t\t\t// Get cluster configuration (from --config, kubeadm-config ConfigMap, or default as a fallback)\n\t\t\t\tinternalcfg, err := getInternalCfg(flags.cfgPath, flags.kubeconfigPath, flags.cfg, out, \"renew\")\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\treturn renewCert(kdir, internalcfg, handler)\n\t\t\t}\n\t\t}(handler)\n\t\t// install the implementation into the command\n\t\tcmd.RunE = func(*cobra.Command, []string) error { return renewalFunc() }\n\t\tcmd.Args = cobra.NoArgs\n\t\tcmdList = append(cmdList, cmd)\n\t}\n\n\tallCmd := \u0026cobra.Command{\n\t\tUse: \"all\",\n\t\tShort: \"Renew all available certificates\",\n\t\tLong: allLongDesc,\n\t\tRunE: func(*cobra.Command, []string) error {\n\t\t\t// Get cluster configuration (from --config, kubeadm-config ConfigMap, or default as a fallback)\n\t\t\tinternalcfg, err := getInternalCfg(flags.cfgPath, flags.kubeconfigPath, flags.cfg, out, \"renew\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Get a renewal manager for an actual Cluster configuration\n\t\t\trm, err := renewal.NewManager(\u0026internalcfg.ClusterConfiguration, kdir)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Renew certificates\n\t\t\tfor _, handler := range rm.Certificates() {\n\t\t\t\tif err := renewCert(kdir, internalcfg, handler); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\tfmt.Printf(\"\\nDone renewing certificates. You must restart the kube-apiserver, kube-controller-manager, kube-scheduler and etcd, so that they can use the new certificates.\\n\")\n\t\t\treturn nil\n\t\t},\n\t\tArgs: cobra.NoArgs,\n\t}\n\taddRenewFlags(allCmd, flags)\n\n\tcmdList = append(cmdList, allCmd)\n\treturn cmdList\n}","line":{"from":221,"to":298}} {"id":100000509,"name":"addRenewFlags","signature":"func addRenewFlags(cmd *cobra.Command, flags *renewFlags)","file":"cmd/kubeadm/app/cmd/certs.go","code":"func addRenewFlags(cmd *cobra.Command, flags *renewFlags) {\n\toptions.AddConfigFlag(cmd.Flags(), \u0026flags.cfgPath)\n\toptions.AddCertificateDirFlag(cmd.Flags(), \u0026flags.cfg.CertificatesDir)\n\toptions.AddKubeConfigFlag(cmd.Flags(), \u0026flags.kubeconfigPath)\n}","line":{"from":300,"to":304}} {"id":100000510,"name":"renewCert","signature":"func renewCert(kdir string, internalcfg *kubeadmapi.InitConfiguration, handler *renewal.CertificateRenewHandler) error","file":"cmd/kubeadm/app/cmd/certs.go","code":"func renewCert(kdir string, internalcfg *kubeadmapi.InitConfiguration, handler *renewal.CertificateRenewHandler) error {\n\t// Get a renewal manager for the given cluster configuration\n\trm, err := renewal.NewManager(\u0026internalcfg.ClusterConfiguration, kdir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif ok, _ := rm.CertificateExists(handler.Name); !ok {\n\t\tfmt.Printf(\"MISSING! %s\\n\", handler.LongName)\n\t\treturn nil\n\t}\n\n\t// renew using local certificate authorities.\n\t// this operation can't complete in case the certificate key is not provided (external CA)\n\trenewed, err := rm.RenewUsingLocalCA(handler.Name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !renewed {\n\t\tfmt.Printf(\"Detected external %s, %s can't be renewed\\n\", handler.CABaseName, handler.LongName)\n\t\treturn nil\n\t}\n\tfmt.Printf(\"%s renewed\\n\", handler.LongName)\n\treturn nil\n}","line":{"from":306,"to":330}} {"id":100000511,"name":"getInternalCfg","signature":"func getInternalCfg(cfgPath string, kubeconfigPath string, cfg kubeadmapiv1.ClusterConfiguration, out io.Writer, logPrefix string) (*kubeadmapi.InitConfiguration, error)","file":"cmd/kubeadm/app/cmd/certs.go","code":"func getInternalCfg(cfgPath string, kubeconfigPath string, cfg kubeadmapiv1.ClusterConfiguration, out io.Writer, logPrefix string) (*kubeadmapi.InitConfiguration, error) {\n\t// In case the user is not providing a custom config, try to get current config from the cluster.\n\t// NB. this operation should not block, because we want to allow certificate renewal also in case of not-working clusters\n\tif cfgPath == \"\" {\n\t\tclient, err := kubeconfigutil.ClientSetFromFile(kubeconfigPath)\n\t\tif err == nil {\n\t\t\tinternalcfg, err := configutil.FetchInitConfigurationFromCluster(client, nil, logPrefix, false, false)\n\t\t\tif err == nil {\n\t\t\t\tfmt.Println() // add empty line to separate the FetchInitConfigurationFromCluster output from the command output\n\t\t\t\t// certificate renewal or expiration checking doesn't depend on a running cluster, which means the CertificatesDir\n\t\t\t\t// could be set to a value other than the default value or the value fetched from the cluster.\n\t\t\t\t// cfg.CertificatesDir could be empty if the default value is set to empty (not true today).\n\t\t\t\tif len(cfg.CertificatesDir) != 0 {\n\t\t\t\t\tklog.V(1).Infof(\"Overriding the cluster certificate directory with the value from command line flag --%s: %s\", options.CertificatesDir, cfg.CertificatesDir)\n\t\t\t\t\tinternalcfg.ClusterConfiguration.CertificatesDir = cfg.CertificatesDir\n\t\t\t\t}\n\n\t\t\t\treturn internalcfg, nil\n\t\t\t}\n\t\t\tfmt.Printf(\"[%s] Error reading configuration from the Cluster. Falling back to default configuration\\n\\n\", logPrefix)\n\t\t}\n\t}\n\n\t// Read config from --config if provided. Otherwise, use the default configuration\n\treturn configutil.LoadOrDefaultInitConfiguration(cfgPath, cmdutil.DefaultInitConfiguration(), \u0026cfg)\n}","line":{"from":332,"to":357}} {"id":100000512,"name":"newCmdCertsExpiration","signature":"func newCmdCertsExpiration(out io.Writer, kdir string) *cobra.Command","file":"cmd/kubeadm/app/cmd/certs.go","code":"// newCmdCertsExpiration creates a new `cert check-expiration` command.\nfunc newCmdCertsExpiration(out io.Writer, kdir string) *cobra.Command {\n\tflags := \u0026expirationFlags{\n\t\tcfg: kubeadmapiv1.ClusterConfiguration{\n\t\t\t// Setting kubernetes version to a default value in order to allow a not necessary internet lookup\n\t\t\tKubernetesVersion: kubeadmconstants.CurrentKubernetesVersion.String(),\n\t\t},\n\t\tkubeconfigPath: kubeadmconstants.GetAdminKubeConfigPath(),\n\t}\n\t// Default values for the cobra help text\n\tkubeadmscheme.Scheme.Default(\u0026flags.cfg)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"check-expiration\",\n\t\tShort: \"Check certificates expiration for a Kubernetes cluster\",\n\t\tLong: expirationLongDesc,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\t// Get cluster configuration (from --config, kubeadm-config ConfigMap, or default as a fallback)\n\t\t\tinternalcfg, err := getInternalCfg(flags.cfgPath, flags.kubeconfigPath, flags.cfg, out, \"check-expiration\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Get a renewal manager for the given cluster configuration\n\t\t\trm, err := renewal.NewManager(\u0026internalcfg.ClusterConfiguration, kdir)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Get all the certificate expiration info\n\t\t\tyesNo := func(b bool) string {\n\t\t\t\tif b {\n\t\t\t\t\treturn \"yes\"\n\t\t\t\t}\n\t\t\t\treturn \"no\"\n\t\t\t}\n\t\t\tw := tabwriter.NewWriter(out, 10, 4, 3, ' ', 0)\n\t\t\tfmt.Fprintln(w, \"CERTIFICATE\\tEXPIRES\\tRESIDUAL TIME\\tCERTIFICATE AUTHORITY\\tEXTERNALLY MANAGED\")\n\t\t\tfor _, handler := range rm.Certificates() {\n\t\t\t\tif ok, _ := rm.CertificateExists(handler.Name); ok {\n\t\t\t\t\te, err := rm.GetCertificateExpirationInfo(handler.Name)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\n\t\t\t\t\ts := fmt.Sprintf(\"%s\\t%s\\t%s\\t%s\\t%-8v\",\n\t\t\t\t\t\te.Name,\n\t\t\t\t\t\te.ExpirationDate.Format(\"Jan 02, 2006 15:04 MST\"),\n\t\t\t\t\t\tduration.ShortHumanDuration(e.ResidualTime()),\n\t\t\t\t\t\thandler.CAName,\n\t\t\t\t\t\tyesNo(e.ExternallyManaged),\n\t\t\t\t\t)\n\n\t\t\t\t\tfmt.Fprintln(w, s)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// the certificate does not exist (for any reason)\n\t\t\t\ts := fmt.Sprintf(\"!MISSING! %s\\t\\t\\t\\t\",\n\t\t\t\t\thandler.Name,\n\t\t\t\t)\n\t\t\t\tfmt.Fprintln(w, s)\n\t\t\t}\n\t\t\tfmt.Fprintln(w)\n\t\t\tfmt.Fprintln(w, \"CERTIFICATE AUTHORITY\\tEXPIRES\\tRESIDUAL TIME\\tEXTERNALLY MANAGED\")\n\t\t\tfor _, handler := range rm.CAs() {\n\t\t\t\tif ok, _ := rm.CAExists(handler.Name); ok {\n\t\t\t\t\te, err := rm.GetCAExpirationInfo(handler.Name)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\n\t\t\t\t\ts := fmt.Sprintf(\"%s\\t%s\\t%s\\t%-8v\",\n\t\t\t\t\t\te.Name,\n\t\t\t\t\t\te.ExpirationDate.Format(\"Jan 02, 2006 15:04 MST\"),\n\t\t\t\t\t\tduration.ShortHumanDuration(e.ResidualTime()),\n\t\t\t\t\t\tyesNo(e.ExternallyManaged),\n\t\t\t\t\t)\n\n\t\t\t\t\tfmt.Fprintln(w, s)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// the CA does not exist (for any reason)\n\t\t\t\ts := fmt.Sprintf(\"!MISSING! %s\\t\\t\\t\",\n\t\t\t\t\thandler.Name,\n\t\t\t\t)\n\t\t\t\tfmt.Fprintln(w, s)\n\t\t\t}\n\t\t\tw.Flush()\n\t\t\treturn nil\n\t\t},\n\t\tArgs: cobra.NoArgs,\n\t}\n\taddExpirationFlags(cmd, flags)\n\n\treturn cmd\n}","line":{"from":359,"to":456}} {"id":100000513,"name":"addExpirationFlags","signature":"func addExpirationFlags(cmd *cobra.Command, flags *expirationFlags)","file":"cmd/kubeadm/app/cmd/certs.go","code":"func addExpirationFlags(cmd *cobra.Command, flags *expirationFlags) {\n\toptions.AddConfigFlag(cmd.Flags(), \u0026flags.cfgPath)\n\toptions.AddCertificateDirFlag(cmd.Flags(), \u0026flags.cfg.CertificatesDir)\n\toptions.AddKubeConfigFlag(cmd.Flags(), \u0026flags.kubeconfigPath)\n}","line":{"from":464,"to":468}} {"id":100000514,"name":"NewKubeadmCommand","signature":"func NewKubeadmCommand(in io.Reader, out, err io.Writer) *cobra.Command","file":"cmd/kubeadm/app/cmd/cmd.go","code":"// NewKubeadmCommand returns cobra.Command to run kubeadm command\nfunc NewKubeadmCommand(in io.Reader, out, err io.Writer) *cobra.Command {\n\tvar rootfsPath string\n\n\tcmds := \u0026cobra.Command{\n\t\tUse: \"kubeadm\",\n\t\tShort: \"kubeadm: easily bootstrap a secure Kubernetes cluster\",\n\t\tLong: dedent.Dedent(`\n\n\t\t\t ┌──────────────────────────────────────────────────────────┐\n\t\t\t │ KUBEADM │\n\t\t\t │ Easily bootstrap a secure Kubernetes cluster │\n\t\t\t │ │\n\t\t\t │ Please give us feedback at: │\n\t\t\t │ https://github.com/kubernetes/kubeadm/issues │\n\t\t\t └──────────────────────────────────────────────────────────┘\n\n\t\t\tExample usage:\n\n\t\t\t Create a two-machine cluster with one control-plane node\n\t\t\t (which controls the cluster), and one worker node\n\t\t\t (where your workloads, like Pods and Deployments run).\n\n\t\t\t ┌──────────────────────────────────────────────────────────┐\n\t\t\t │ On the first machine: │\n\t\t\t ├──────────────────────────────────────────────────────────┤\n\t\t\t │ control-plane# kubeadm init │\n\t\t\t └──────────────────────────────────────────────────────────┘\n\n\t\t\t ┌──────────────────────────────────────────────────────────┐\n\t\t\t │ On the second machine: │\n\t\t\t ├──────────────────────────────────────────────────────────┤\n\t\t\t │ worker# kubeadm join \u003carguments-returned-from-init\u003e │\n\t\t\t └──────────────────────────────────────────────────────────┘\n\n\t\t\t You can then repeat the second step on as many other machines as you like.\n\n\t\t`),\n\t\tSilenceErrors: true,\n\t\tSilenceUsage: true,\n\t\tPersistentPreRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tif rootfsPath != \"\" {\n\t\t\t\tif err := kubeadmutil.Chroot(rootfsPath); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tcmds.ResetFlags()\n\n\tcmds.AddCommand(newCmdCertsUtility(out))\n\tcmds.AddCommand(newCmdCompletion(out, \"\"))\n\tcmds.AddCommand(newCmdConfig(out))\n\tcmds.AddCommand(newCmdInit(out, nil))\n\tcmds.AddCommand(newCmdJoin(out, nil))\n\tcmds.AddCommand(newCmdReset(in, out, nil))\n\tcmds.AddCommand(newCmdVersion(out))\n\tcmds.AddCommand(newCmdToken(out, err))\n\tcmds.AddCommand(upgrade.NewCmdUpgrade(out))\n\tcmds.AddCommand(alpha.NewCmdAlpha())\n\toptions.AddKubeadmOtherFlags(cmds.PersistentFlags(), \u0026rootfsPath)\n\tcmds.AddCommand(newCmdKubeConfigUtility(out))\n\n\treturn cmds\n}","line":{"from":31,"to":97}} {"id":100000515,"name":"GetSupportedShells","signature":"func GetSupportedShells() []string","file":"cmd/kubeadm/app/cmd/completion.go","code":"// GetSupportedShells returns a list of supported shells\nfunc GetSupportedShells() []string {\n\tshells := []string{}\n\tfor s := range completionShells {\n\t\tshells = append(shells, s)\n\t}\n\treturn shells\n}","line":{"from":91,"to":98}} {"id":100000516,"name":"newCmdCompletion","signature":"func newCmdCompletion(out io.Writer, boilerPlate string) *cobra.Command","file":"cmd/kubeadm/app/cmd/completion.go","code":"// newCmdCompletion returns the \"kubeadm completion\" command\nfunc newCmdCompletion(out io.Writer, boilerPlate string) *cobra.Command {\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"completion SHELL\",\n\t\tShort: \"Output shell completion code for the specified shell (bash or zsh)\",\n\t\tLong: completionLong,\n\t\tExample: completionExample,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn RunCompletion(out, boilerPlate, cmd, args)\n\t\t},\n\t\tValidArgs: GetSupportedShells(),\n\t}\n\n\treturn cmd\n}","line":{"from":100,"to":114}} {"id":100000517,"name":"RunCompletion","signature":"func RunCompletion(out io.Writer, boilerPlate string, cmd *cobra.Command, args []string) error","file":"cmd/kubeadm/app/cmd/completion.go","code":"// RunCompletion checks given arguments and executes command\nfunc RunCompletion(out io.Writer, boilerPlate string, cmd *cobra.Command, args []string) error {\n\tif length := len(args); length == 0 {\n\t\treturn errors.New(\"shell not specified\")\n\t} else if length \u003e 1 {\n\t\treturn errors.New(\"too many arguments. expected only the shell type\")\n\t}\n\trun, found := completionShells[args[0]]\n\tif !found {\n\t\treturn errors.Errorf(\"unsupported shell type %q\", args[0])\n\t}\n\n\tif len(boilerPlate) == 0 {\n\t\tboilerPlate = defaultBoilerPlate\n\t}\n\tif _, err := out.Write([]byte(boilerPlate)); err != nil {\n\t\treturn err\n\t}\n\treturn run(out, cmd.Parent())\n}","line":{"from":116,"to":135}} {"id":100000518,"name":"runCompletionBash","signature":"func runCompletionBash(out io.Writer, kubeadm *cobra.Command) error","file":"cmd/kubeadm/app/cmd/completion.go","code":"func runCompletionBash(out io.Writer, kubeadm *cobra.Command) error {\n\tklog.V(1).Infoln(\"[completion] writing completion code for Bash\")\n\treturn kubeadm.GenBashCompletion(out)\n}","line":{"from":137,"to":140}} {"id":100000519,"name":"runCompletionZsh","signature":"func runCompletionZsh(out io.Writer, kubeadm *cobra.Command) error","file":"cmd/kubeadm/app/cmd/completion.go","code":"func runCompletionZsh(out io.Writer, kubeadm *cobra.Command) error {\n\tzshInitialization := `\n__kubeadm_bash_source() {\n\talias shopt=':'\n\talias _expand=_bash_expand\n\talias _complete=_bash_comp\n\temulate -L sh\n\tsetopt kshglob noshglob braceexpand\n\n\tsource \"$@\"\n}\n\n__kubeadm_type() {\n\t# -t is not supported by zsh\n\tif [ \"$1\" == \"-t\" ]; then\n\t\tshift\n\n\t\t# fake Bash 4 to disable \"complete -o nospace\". Instead\n\t\t# \"compopt +-o nospace\" is used in the code to toggle trailing\n\t\t# spaces. We don't support that, but leave trailing spaces on\n\t\t# all the time\n\t\tif [ \"$1\" = \"__kubeadm_compopt\" ]; then\n\t\t\techo builtin\n\t\t\treturn 0\n\t\tfi\n\tfi\n\ttype \"$@\"\n}\n\n__kubeadm_compgen() {\n\tlocal completions w\n\tcompletions=( $(compgen \"$@\") ) || return $?\n\n\t# filter by given word as prefix\n\twhile [[ \"$1\" = -* \u0026\u0026 \"$1\" != -- ]]; do\n\t\tshift\n\t\tshift\n\tdone\n\tif [[ \"$1\" == -- ]]; then\n\t\tshift\n\tfi\n\tfor w in \"${completions[@]}\"; do\n\t\tif [[ \"${w}\" = \"$1\"* ]]; then\n\t\t\techo \"${w}\"\n\t\tfi\n\tdone\n}\n\n__kubeadm_compopt() {\n\ttrue # don't do anything. Not supported by bashcompinit in zsh\n}\n\n__kubeadm_ltrim_colon_completions()\n{\n\tif [[ \"$1\" == *:* \u0026\u0026 \"$COMP_WORDBREAKS\" == *:* ]]; then\n\t\t# Remove colon-word prefix from COMPREPLY items\n\t\tlocal colon_word=${1%${1##*:}}\n\t\tlocal i=${#COMPREPLY[*]}\n\t\twhile [[ $((--i)) -ge 0 ]]; do\n\t\t\tCOMPREPLY[$i]=${COMPREPLY[$i]#\"$colon_word\"}\n\t\tdone\n\tfi\n}\n\n__kubeadm_get_comp_words_by_ref() {\n\tcur=\"${COMP_WORDS[COMP_CWORD]}\"\n\tprev=\"${COMP_WORDS[${COMP_CWORD}-1]}\"\n\twords=(\"${COMP_WORDS[@]}\")\n\tcword=(\"${COMP_CWORD[@]}\")\n}\n\n__kubeadm_filedir() {\n\tlocal RET OLD_IFS w qw\n\n\t__kubectl_debug \"_filedir $@ cur=$cur\"\n\tif [[ \"$1\" = \\~* ]]; then\n\t\t# somehow does not work. Maybe, zsh does not call this at all\n\t\teval echo \"$1\"\n\t\treturn 0\n\tfi\n\n\tOLD_IFS=\"$IFS\"\n\tIFS=$'\\n'\n\tif [ \"$1\" = \"-d\" ]; then\n\t\tshift\n\t\tRET=( $(compgen -d) )\n\telse\n\t\tRET=( $(compgen -f) )\n\tfi\n\tIFS=\"$OLD_IFS\"\n\n\tIFS=\",\" __kubectl_debug \"RET=${RET[@]} len=${#RET[@]}\"\n\n\tfor w in ${RET[@]}; do\n\t\tif [[ ! \"${w}\" = \"${cur}\"* ]]; then\n\t\t\tcontinue\n\t\tfi\n\t\tif eval \"[[ \\\"\\${w}\\\" = *.$1 || -d \\\"\\${w}\\\" ]]\"; then\n\t\t\tqw=\"$(__kubeadm_quote \"${w}\")\"\n\t\t\tif [ -d \"${w}\" ]; then\n\t\t\t\tCOMPREPLY+=(\"${qw}/\")\n\t\t\telse\n\t\t\t\tCOMPREPLY+=(\"${qw}\")\n\t\t\tfi\n\t\tfi\n\tdone\n}\n\n__kubeadm_quote() {\n if [[ $1 == \\'* || $1 == \\\"* ]]; then\n # Leave out first character\n printf %q \"${1:1}\"\n else\n \tprintf %q \"$1\"\n fi\n}\n\nautoload -U +X bashcompinit \u0026\u0026 bashcompinit\n\n# use word boundary patterns for BSD or GNU sed\nLWORD='[[:\u003c:]]'\nRWORD='[[:\u003e:]]'\nif sed --version 2\u003e\u00261 | grep -q GNU; then\n\tLWORD='\\\u003c'\n\tRWORD='\\\u003e'\nfi\n\n__kubeadm_convert_bash_to_zsh() {\n\tsed \\\n\t-e 's/declare -F/whence -w/' \\\n\t-e 's/local \\([a-zA-Z0-9_]*\\)=/local \\1; \\1=/' \\\n\t-e 's/flags+=(\"\\(--.*\\)=\")/flags+=(\"\\1\"); two_word_flags+=(\"\\1\")/' \\\n\t-e 's/must_have_one_flag+=(\"\\(--.*\\)=\")/must_have_one_flag+=(\"\\1\")/' \\\n\t-e \"s/${LWORD}_filedir${RWORD}/__kubeadm_filedir/g\" \\\n\t-e \"s/${LWORD}_get_comp_words_by_ref${RWORD}/__kubeadm_get_comp_words_by_ref/g\" \\\n\t-e \"s/${LWORD}__ltrim_colon_completions${RWORD}/__kubeadm_ltrim_colon_completions/g\" \\\n\t-e \"s/${LWORD}compgen${RWORD}/__kubeadm_compgen/g\" \\\n\t-e \"s/${LWORD}compopt${RWORD}/__kubeadm_compopt/g\" \\\n\t-e \"s/${LWORD}declare${RWORD}/builtin declare/g\" \\\n\t-e \"s/\\\\\\$(type${RWORD}/\\$(__kubeadm_type/g\" \\\n\t\u003c\u003c'BASH_COMPLETION_EOF'\n`\n\tklog.V(1).Infoln(\"[completion] writing completion code for Zsh\")\n\tout.Write([]byte(zshInitialization))\n\n\tbuf := new(bytes.Buffer)\n\tkubeadm.GenBashCompletion(buf)\n\tklog.V(1).Infoln(\"[completion] writing completion code for Bash\")\n\tout.Write(buf.Bytes())\n\n\tzshTail := `\nBASH_COMPLETION_EOF\n}\n\n__kubeadm_bash_source \u003c(__kubeadm_convert_bash_to_zsh)\n`\n\tout.Write([]byte(zshTail))\n\treturn nil\n}","line":{"from":142,"to":300}} {"id":100000520,"name":"newCmdConfig","signature":"func newCmdConfig(out io.Writer) *cobra.Command","file":"cmd/kubeadm/app/cmd/config.go","code":"// newCmdConfig returns cobra.Command for \"kubeadm config\" command\nfunc newCmdConfig(out io.Writer) *cobra.Command {\n\tvar kubeConfigFile string\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"config\",\n\t\tShort: \"Manage configuration for a kubeadm cluster persisted in a ConfigMap in the cluster\",\n\t\tLong: fmt.Sprintf(dedent.Dedent(`\n\t\t\tThere is a ConfigMap in the %s namespace called %q that kubeadm uses to store internal configuration about the\n\t\t\tcluster. kubeadm CLI v1.8.0+ automatically creates this ConfigMap with the config used with 'kubeadm init', but if you\n\t\t\tinitialized your cluster using kubeadm v1.7.x or lower, you must use the 'config upload' command to create this\n\t\t\tConfigMap. This is required so that 'kubeadm upgrade' can configure your upgraded cluster correctly.\n\t\t`), metav1.NamespaceSystem, constants.KubeadmConfigConfigMap),\n\t\t// Without this callback, if a user runs just the \"upload\"\n\t\t// command without a subcommand, or with an invalid subcommand,\n\t\t// cobra will print usage information, but still exit cleanly.\n\t\t// We want to return an error code in these cases so that the\n\t\t// user knows that their command was invalid.\n\t\tRun: cmdutil.SubCmdRun(),\n\t}\n\n\toptions.AddKubeConfigFlag(cmd.PersistentFlags(), \u0026kubeConfigFile)\n\n\tkubeConfigFile = cmdutil.GetKubeConfigPath(kubeConfigFile)\n\tcmd.AddCommand(newCmdConfigPrint(out))\n\tcmd.AddCommand(newCmdConfigMigrate(out))\n\tcmd.AddCommand(newCmdConfigImages(out))\n\treturn cmd\n}","line":{"from":53,"to":81}} {"id":100000521,"name":"newCmdConfigPrint","signature":"func newCmdConfigPrint(out io.Writer) *cobra.Command","file":"cmd/kubeadm/app/cmd/config.go","code":"// newCmdConfigPrint returns cobra.Command for \"kubeadm config print\" command\nfunc newCmdConfigPrint(out io.Writer) *cobra.Command {\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"print\",\n\t\tShort: \"Print configuration\",\n\t\tLong: dedent.Dedent(`\n\t\t\tThis command prints configurations for subcommands provided.\n\t\t\tFor details, see: https://pkg.go.dev/k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm#section-directories`),\n\t\tRun: cmdutil.SubCmdRun(),\n\t}\n\tcmd.AddCommand(newCmdConfigPrintInitDefaults(out))\n\tcmd.AddCommand(newCmdConfigPrintJoinDefaults(out))\n\treturn cmd\n}","line":{"from":83,"to":96}} {"id":100000522,"name":"newCmdConfigPrintInitDefaults","signature":"func newCmdConfigPrintInitDefaults(out io.Writer) *cobra.Command","file":"cmd/kubeadm/app/cmd/config.go","code":"// newCmdConfigPrintInitDefaults returns cobra.Command for \"kubeadm config print init-defaults\" command\nfunc newCmdConfigPrintInitDefaults(out io.Writer) *cobra.Command {\n\treturn newCmdConfigPrintActionDefaults(out, \"init\", getDefaultInitConfigBytes)\n}","line":{"from":98,"to":101}} {"id":100000523,"name":"newCmdConfigPrintJoinDefaults","signature":"func newCmdConfigPrintJoinDefaults(out io.Writer) *cobra.Command","file":"cmd/kubeadm/app/cmd/config.go","code":"// newCmdConfigPrintJoinDefaults returns cobra.Command for \"kubeadm config print join-defaults\" command\nfunc newCmdConfigPrintJoinDefaults(out io.Writer) *cobra.Command {\n\treturn newCmdConfigPrintActionDefaults(out, \"join\", getDefaultNodeConfigBytes)\n}","line":{"from":103,"to":106}} {"id":100000524,"name":"newCmdConfigPrintActionDefaults","signature":"func newCmdConfigPrintActionDefaults(out io.Writer, action string, configBytesProc func() ([]byte, error)) *cobra.Command","file":"cmd/kubeadm/app/cmd/config.go","code":"func newCmdConfigPrintActionDefaults(out io.Writer, action string, configBytesProc func() ([]byte, error)) *cobra.Command {\n\tkinds := []string{}\n\tcmd := \u0026cobra.Command{\n\t\tUse: fmt.Sprintf(\"%s-defaults\", action),\n\t\tShort: fmt.Sprintf(\"Print default %s configuration, that can be used for 'kubeadm %s'\", action, action),\n\t\tLong: fmt.Sprintf(dedent.Dedent(`\n\t\t\tThis command prints objects such as the default %s configuration that is used for 'kubeadm %s'.\n\n\t\t\tNote that sensitive values like the Bootstrap Token fields are replaced with placeholder values like %q in order to pass validation but\n\t\t\tnot perform the real computation for creating a token.\n\t\t`), action, action, configutil.PlaceholderToken.Token.String()),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tgroups, err := mapLegacyKindsToGroups(kinds)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn runConfigPrintActionDefaults(out, groups, configBytesProc)\n\t\t},\n\t\tArgs: cobra.NoArgs,\n\t}\n\tcmd.Flags().StringSliceVar(\u0026kinds, \"component-configs\", kinds,\n\t\tfmt.Sprintf(\"A comma-separated list for component config API objects to print the default values for. Available values: %v. If this flag is not set, no component configs will be printed.\", getSupportedComponentConfigKinds()))\n\treturn cmd\n}","line":{"from":108,"to":131}} {"id":100000525,"name":"runConfigPrintActionDefaults","signature":"func runConfigPrintActionDefaults(out io.Writer, componentConfigs []string, configBytesProc func() ([]byte, error)) error","file":"cmd/kubeadm/app/cmd/config.go","code":"func runConfigPrintActionDefaults(out io.Writer, componentConfigs []string, configBytesProc func() ([]byte, error)) error {\n\tinitialConfig, err := configBytesProc()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tallBytes := [][]byte{initialConfig}\n\tfor _, componentConfig := range componentConfigs {\n\t\tcfgBytes, err := getDefaultComponentConfigBytes(componentConfig)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tallBytes = append(allBytes, cfgBytes)\n\t}\n\n\tfmt.Fprint(out, string(bytes.Join(allBytes, []byte(constants.YAMLDocumentSeparator))))\n\treturn nil\n}","line":{"from":133,"to":150}} {"id":100000526,"name":"getDefaultComponentConfigBytes","signature":"func getDefaultComponentConfigBytes(group string) ([]byte, error)","file":"cmd/kubeadm/app/cmd/config.go","code":"func getDefaultComponentConfigBytes(group string) ([]byte, error) {\n\tdefaultedInitConfig, err := configutil.DefaultedStaticInitConfiguration()\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\tcomponentCfg, ok := defaultedInitConfig.ComponentConfigs[group]\n\tif !ok {\n\t\treturn []byte{}, errors.Errorf(\"cannot get defaulted config for component group %q\", group)\n\t}\n\n\treturn componentCfg.Marshal()\n}","line":{"from":152,"to":164}} {"id":100000527,"name":"getSupportedComponentConfigKinds","signature":"func getSupportedComponentConfigKinds() []string","file":"cmd/kubeadm/app/cmd/config.go","code":"// getSupportedComponentConfigKinds returns all currently supported component config API object names\nfunc getSupportedComponentConfigKinds() []string {\n\tobjects := []string{}\n\tfor componentType := range legacyKindToGroupMap {\n\t\tobjects = append(objects, string(componentType))\n\t}\n\tsort.Strings(objects)\n\treturn objects\n}","line":{"from":172,"to":180}} {"id":100000528,"name":"mapLegacyKindsToGroups","signature":"func mapLegacyKindsToGroups(kinds []string) ([]string, error)","file":"cmd/kubeadm/app/cmd/config.go","code":"func mapLegacyKindsToGroups(kinds []string) ([]string, error) {\n\tgroups := []string{}\n\tfor _, kind := range kinds {\n\t\tgroup, ok := legacyKindToGroupMap[kind]\n\t\tif ok {\n\t\t\tgroups = append(groups, group)\n\t\t} else {\n\t\t\treturn nil, errors.Errorf(\"--component-configs needs to contain some of %v\", getSupportedComponentConfigKinds())\n\t\t}\n\t}\n\treturn groups, nil\n}","line":{"from":182,"to":193}} {"id":100000529,"name":"getDefaultInitConfigBytes","signature":"func getDefaultInitConfigBytes() ([]byte, error)","file":"cmd/kubeadm/app/cmd/config.go","code":"func getDefaultInitConfigBytes() ([]byte, error) {\n\tinternalcfg, err := configutil.DefaultedStaticInitConfiguration()\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\treturn configutil.MarshalKubeadmConfigObject(internalcfg)\n}","line":{"from":195,"to":202}} {"id":100000530,"name":"getDefaultNodeConfigBytes","signature":"func getDefaultNodeConfigBytes() ([]byte, error)","file":"cmd/kubeadm/app/cmd/config.go","code":"func getDefaultNodeConfigBytes() ([]byte, error) {\n\tinternalcfg, err := configutil.DefaultedJoinConfiguration(\u0026kubeadmapiv1.JoinConfiguration{\n\t\tDiscovery: kubeadmapiv1.Discovery{\n\t\t\tBootstrapToken: \u0026kubeadmapiv1.BootstrapTokenDiscovery{\n\t\t\t\tToken: configutil.PlaceholderToken.Token.String(),\n\t\t\t\tAPIServerEndpoint: \"kube-apiserver:6443\",\n\t\t\t\tUnsafeSkipCAVerification: true, // TODO: UnsafeSkipCAVerification: true needs to be set for validation to pass, but shouldn't be recommended as the default\n\t\t\t},\n\t\t},\n\t\tNodeRegistration: kubeadmapiv1.NodeRegistrationOptions{\n\t\t\tCRISocket: constants.DefaultCRISocket, // avoid CRI detection\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\treturn configutil.MarshalKubeadmConfigObject(internalcfg)\n}","line":{"from":204,"to":222}} {"id":100000531,"name":"newCmdConfigMigrate","signature":"func newCmdConfigMigrate(out io.Writer) *cobra.Command","file":"cmd/kubeadm/app/cmd/config.go","code":"// newCmdConfigMigrate returns cobra.Command for \"kubeadm config migrate\" command\nfunc newCmdConfigMigrate(out io.Writer) *cobra.Command {\n\tvar oldCfgPath, newCfgPath string\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"migrate\",\n\t\tShort: \"Read an older version of the kubeadm configuration API types from a file, and output the similar config object for the newer version\",\n\t\tLong: fmt.Sprintf(dedent.Dedent(`\n\t\t\tThis command lets you convert configuration objects of older versions to the latest supported version,\n\t\t\tlocally in the CLI tool without ever touching anything in the cluster.\n\t\t\tIn this version of kubeadm, the following API versions are supported:\n\t\t\t- %s\n\n\t\t\tFurther, kubeadm can only write out config of version %q, but read both types.\n\t\t\tSo regardless of what version you pass to the --old-config parameter here, the API object will be\n\t\t\tread, deserialized, defaulted, converted, validated, and re-serialized when written to stdout or\n\t\t\t--new-config if specified.\n\n\t\t\tIn other words, the output of this command is what kubeadm actually would read internally if you\n\t\t\tsubmitted this file to \"kubeadm init\"\n\t\t`), kubeadmapiv1.SchemeGroupVersion, kubeadmapiv1.SchemeGroupVersion),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tif len(oldCfgPath) == 0 {\n\t\t\t\treturn errors.New(\"the --old-config flag is mandatory\")\n\t\t\t}\n\n\t\t\toldCfgBytes, err := os.ReadFile(oldCfgPath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\toutputBytes, err := configutil.MigrateOldConfig(oldCfgBytes)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif newCfgPath == \"\" {\n\t\t\t\tfmt.Fprint(out, string(outputBytes))\n\t\t\t} else {\n\t\t\t\tif err := os.WriteFile(newCfgPath, outputBytes, 0644); err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"failed to write the new configuration to the file %q\", newCfgPath)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t\tArgs: cobra.NoArgs,\n\t}\n\tcmd.Flags().StringVar(\u0026oldCfgPath, \"old-config\", \"\", \"Path to the kubeadm config file that is using an old API version and should be converted. This flag is mandatory.\")\n\tcmd.Flags().StringVar(\u0026newCfgPath, \"new-config\", \"\", \"Path to the resulting equivalent kubeadm config file using the new API version. Optional, if not specified output will be sent to STDOUT.\")\n\treturn cmd\n}","line":{"from":224,"to":273}} {"id":100000532,"name":"newCmdConfigImages","signature":"func newCmdConfigImages(out io.Writer) *cobra.Command","file":"cmd/kubeadm/app/cmd/config.go","code":"// newCmdConfigImages returns the \"kubeadm config images\" command\nfunc newCmdConfigImages(out io.Writer) *cobra.Command {\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"images\",\n\t\tShort: \"Interact with container images used by kubeadm\",\n\t\tRun: cmdutil.SubCmdRun(),\n\t}\n\tcmd.AddCommand(newCmdConfigImagesList(out, nil))\n\tcmd.AddCommand(newCmdConfigImagesPull())\n\treturn cmd\n}","line":{"from":275,"to":285}} {"id":100000533,"name":"newCmdConfigImagesPull","signature":"func newCmdConfigImagesPull() *cobra.Command","file":"cmd/kubeadm/app/cmd/config.go","code":"// newCmdConfigImagesPull returns the `kubeadm config images pull` command\nfunc newCmdConfigImagesPull() *cobra.Command {\n\texternalClusterCfg := \u0026kubeadmapiv1.ClusterConfiguration{}\n\tkubeadmscheme.Scheme.Default(externalClusterCfg)\n\texternalInitCfg := \u0026kubeadmapiv1.InitConfiguration{}\n\tkubeadmscheme.Scheme.Default(externalInitCfg)\n\tvar cfgPath, featureGatesString string\n\tvar err error\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"pull\",\n\t\tShort: \"Pull images used by kubeadm\",\n\t\tRunE: func(_ *cobra.Command, _ []string) error {\n\t\t\texternalClusterCfg.FeatureGates, err = features.NewFeatureGate(\u0026features.InitFeatureGates, featureGatesString)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tinternalcfg, err := configutil.LoadOrDefaultInitConfiguration(cfgPath, externalInitCfg, externalClusterCfg)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontainerRuntime, err := utilruntime.NewContainerRuntime(utilsexec.New(), internalcfg.NodeRegistration.CRISocket)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn PullControlPlaneImages(containerRuntime, \u0026internalcfg.ClusterConfiguration)\n\t\t},\n\t\tArgs: cobra.NoArgs,\n\t}\n\tAddImagesCommonConfigFlags(cmd.PersistentFlags(), externalClusterCfg, \u0026cfgPath, \u0026featureGatesString)\n\tcmdutil.AddCRISocketFlag(cmd.PersistentFlags(), \u0026externalInitCfg.NodeRegistration.CRISocket)\n\n\treturn cmd\n}","line":{"from":287,"to":320}} {"id":100000534,"name":"PullControlPlaneImages","signature":"func PullControlPlaneImages(runtime utilruntime.ContainerRuntime, cfg *kubeadmapi.ClusterConfiguration) error","file":"cmd/kubeadm/app/cmd/config.go","code":"// PullControlPlaneImages pulls all images that the ImagesPull knows about\nfunc PullControlPlaneImages(runtime utilruntime.ContainerRuntime, cfg *kubeadmapi.ClusterConfiguration) error {\n\timages := images.GetControlPlaneImages(cfg)\n\tfor _, image := range images {\n\t\tif err := runtime.PullImage(image); err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to pull image %q\", image)\n\t\t}\n\t\tfmt.Printf(\"[config/images] Pulled %s\\n\", image)\n\t}\n\treturn nil\n}","line":{"from":322,"to":332}} {"id":100000535,"name":"newCmdConfigImagesList","signature":"func newCmdConfigImagesList(out io.Writer, mockK8sVersion *string) *cobra.Command","file":"cmd/kubeadm/app/cmd/config.go","code":"// newCmdConfigImagesList returns the \"kubeadm config images list\" command\nfunc newCmdConfigImagesList(out io.Writer, mockK8sVersion *string) *cobra.Command {\n\texternalcfg := \u0026kubeadmapiv1.ClusterConfiguration{}\n\tkubeadmscheme.Scheme.Default(externalcfg)\n\tvar cfgPath, featureGatesString string\n\tvar err error\n\n\t// This just sets the Kubernetes version for unit testing so kubeadm won't try to\n\t// lookup the latest release from the internet.\n\tif mockK8sVersion != nil {\n\t\texternalcfg.KubernetesVersion = *mockK8sVersion\n\t}\n\n\toutputFlags := output.NewOutputFlags(\u0026imageTextPrintFlags{}).WithTypeSetter(outputapischeme.Scheme).WithDefaultOutput(output.TextOutput)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"Print a list of images kubeadm will use. The configuration file is used in case any images or image repositories are customized\",\n\t\tRunE: func(_ *cobra.Command, _ []string) error {\n\t\t\texternalcfg.FeatureGates, err = features.NewFeatureGate(\u0026features.InitFeatureGates, featureGatesString)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tprinter, err := outputFlags.ToPrinter()\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"could not construct output printer\")\n\t\t\t}\n\n\t\t\timagesList, err := NewImagesList(cfgPath, externalcfg)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn imagesList.Run(out, printer)\n\t\t},\n\t\tArgs: cobra.NoArgs,\n\t}\n\toutputFlags.AddFlags(cmd)\n\tAddImagesCommonConfigFlags(cmd.PersistentFlags(), externalcfg, \u0026cfgPath, \u0026featureGatesString)\n\treturn cmd\n}","line":{"from":334,"to":375}} {"id":100000536,"name":"NewImagesList","signature":"func NewImagesList(cfgPath string, cfg *kubeadmapiv1.ClusterConfiguration) (*ImagesList, error)","file":"cmd/kubeadm/app/cmd/config.go","code":"// NewImagesList returns the underlying struct for the \"kubeadm config images list\" command\nfunc NewImagesList(cfgPath string, cfg *kubeadmapiv1.ClusterConfiguration) (*ImagesList, error) {\n\tinitcfg, err := configutil.LoadOrDefaultInitConfiguration(cfgPath, cmdutil.DefaultInitConfiguration(), cfg)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not convert cfg to an internal cfg\")\n\t}\n\n\treturn \u0026ImagesList{\n\t\tcfg: initcfg,\n\t}, nil\n}","line":{"from":377,"to":387}} {"id":100000537,"name":"PrintObj","signature":"func (itp *imageTextPrinter) PrintObj(obj runtime.Object, writer io.Writer) error","file":"cmd/kubeadm/app/cmd/config.go","code":"// PrintObj is an implementation of ResourcePrinter.PrintObj for plain text output\nfunc (itp *imageTextPrinter) PrintObj(obj runtime.Object, writer io.Writer) error {\n\tvar err error\n\tif imgs, ok := obj.(*outputapiv1alpha2.Images); ok {\n\t\t_, err = fmt.Fprintln(writer, strings.Join(imgs.Images, \"\\n\"))\n\t} else {\n\t\terr = errors.New(\"unexpected object type\")\n\t}\n\treturn err\n}","line":{"from":399,"to":408}} {"id":100000538,"name":"ToPrinter","signature":"func (ipf *imageTextPrintFlags) ToPrinter(outputFormat string) (output.Printer, error)","file":"cmd/kubeadm/app/cmd/config.go","code":"// ToPrinter returns a kubeadm printer for the text output format\nfunc (ipf *imageTextPrintFlags) ToPrinter(outputFormat string) (output.Printer, error) {\n\tif outputFormat == output.TextOutput {\n\t\treturn \u0026imageTextPrinter{}, nil\n\t}\n\treturn nil, genericclioptions.NoCompatiblePrinterError{OutputFormat: \u0026outputFormat, AllowedFormats: []string{output.TextOutput}}\n}","line":{"from":413,"to":419}} {"id":100000539,"name":"Run","signature":"func (i *ImagesList) Run(out io.Writer, printer output.Printer) error","file":"cmd/kubeadm/app/cmd/config.go","code":"// Run runs the images command and writes the result to the io.Writer passed in\nfunc (i *ImagesList) Run(out io.Writer, printer output.Printer) error {\n\timgs := images.GetControlPlaneImages(\u0026i.cfg.ClusterConfiguration)\n\n\tif err := printer.PrintObj(\u0026outputapiv1alpha2.Images{Images: imgs}, out); err != nil {\n\t\treturn errors.Wrap(err, \"unable to print images\")\n\t}\n\n\treturn nil\n}","line":{"from":421,"to":430}} {"id":100000540,"name":"AddImagesCommonConfigFlags","signature":"func AddImagesCommonConfigFlags(flagSet *flag.FlagSet, cfg *kubeadmapiv1.ClusterConfiguration, cfgPath *string, featureGatesString *string)","file":"cmd/kubeadm/app/cmd/config.go","code":"// AddImagesCommonConfigFlags adds the flags that configure kubeadm (and affect the images kubeadm will use)\nfunc AddImagesCommonConfigFlags(flagSet *flag.FlagSet, cfg *kubeadmapiv1.ClusterConfiguration, cfgPath *string, featureGatesString *string) {\n\toptions.AddKubernetesVersionFlag(flagSet, \u0026cfg.KubernetesVersion)\n\toptions.AddFeatureGatesStringFlag(flagSet, featureGatesString)\n\toptions.AddImageMetaFlags(flagSet, \u0026cfg.ImageRepository)\n\toptions.AddConfigFlag(flagSet, cfgPath)\n}","line":{"from":432,"to":438}} {"id":100000541,"name":"newCmdInit","signature":"func newCmdInit(out io.Writer, initOptions *initOptions) *cobra.Command","file":"cmd/kubeadm/app/cmd/init.go","code":"// newCmdInit returns \"kubeadm init\" command.\n// NB. initOptions is exposed as parameter for allowing unit testing of\n// the newInitOptions method, that implements all the command options validation logic\nfunc newCmdInit(out io.Writer, initOptions *initOptions) *cobra.Command {\n\tif initOptions == nil {\n\t\tinitOptions = newInitOptions()\n\t}\n\tinitRunner := workflow.NewRunner()\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"init\",\n\t\tShort: \"Run this command in order to set up the Kubernetes control plane\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tc, err := initRunner.InitData(args)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tdata := c.(*initData)\n\t\t\tfmt.Printf(\"[init] Using Kubernetes version: %s\\n\", data.cfg.KubernetesVersion)\n\n\t\t\treturn initRunner.Run(args)\n\t\t},\n\t\tArgs: cobra.NoArgs,\n\t}\n\n\t// add flags to the init command.\n\t// init command local flags could be eventually inherited by the sub-commands automatically generated for phases\n\tAddInitConfigFlags(cmd.Flags(), initOptions.externalInitCfg)\n\tAddClusterConfigFlags(cmd.Flags(), initOptions.externalClusterCfg, \u0026initOptions.featureGatesString)\n\tAddInitOtherFlags(cmd.Flags(), initOptions)\n\tinitOptions.bto.AddTokenFlag(cmd.Flags())\n\tinitOptions.bto.AddTTLFlag(cmd.Flags())\n\toptions.AddImageMetaFlags(cmd.Flags(), \u0026initOptions.externalClusterCfg.ImageRepository)\n\n\t// defines additional flag that are not used by the init command but that could be eventually used\n\t// by the sub-commands automatically generated for phases\n\tinitRunner.SetAdditionalFlags(func(flags *flag.FlagSet) {\n\t\toptions.AddKubeConfigFlag(flags, \u0026initOptions.kubeconfigPath)\n\t\toptions.AddKubeConfigDirFlag(flags, \u0026initOptions.kubeconfigDir)\n\t\toptions.AddControlPlanExtraArgsFlags(flags, \u0026initOptions.externalClusterCfg.APIServer.ExtraArgs, \u0026initOptions.externalClusterCfg.ControllerManager.ExtraArgs, \u0026initOptions.externalClusterCfg.Scheduler.ExtraArgs)\n\t})\n\n\t// initialize the workflow runner with the list of phases\n\tinitRunner.AppendPhase(phases.NewPreflightPhase())\n\tinitRunner.AppendPhase(phases.NewCertsPhase())\n\tinitRunner.AppendPhase(phases.NewKubeConfigPhase())\n\tinitRunner.AppendPhase(phases.NewKubeletStartPhase())\n\tinitRunner.AppendPhase(phases.NewControlPlanePhase())\n\tinitRunner.AppendPhase(phases.NewEtcdPhase())\n\tinitRunner.AppendPhase(phases.NewWaitControlPlanePhase())\n\tinitRunner.AppendPhase(phases.NewUploadConfigPhase())\n\tinitRunner.AppendPhase(phases.NewUploadCertsPhase())\n\tinitRunner.AppendPhase(phases.NewMarkControlPlanePhase())\n\tinitRunner.AppendPhase(phases.NewBootstrapTokenPhase())\n\tinitRunner.AppendPhase(phases.NewKubeletFinalizePhase())\n\tinitRunner.AppendPhase(phases.NewAddonPhase())\n\tinitRunner.AppendPhase(phases.NewShowJoinCommandPhase())\n\n\t// sets the data builder function, that will be used by the runner\n\t// both when running the entire workflow or single phases\n\tinitRunner.SetDataInitializer(func(cmd *cobra.Command, args []string) (workflow.RunData, error) {\n\t\tif cmd.Flags().Lookup(options.NodeCRISocket) == nil {\n\t\t\t// avoid CRI detection\n\t\t\t// assume that the command execution does not depend on CRISocket when --cri-socket flag is not set\n\t\t\tinitOptions.externalInitCfg.NodeRegistration.CRISocket = kubeadmconstants.UnknownCRISocket\n\t\t}\n\t\tdata, err := newInitData(cmd, args, initOptions, out)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// If the flag for skipping phases was empty, use the values from config\n\t\tif len(initRunner.Options.SkipPhases) == 0 {\n\t\t\tinitRunner.Options.SkipPhases = data.cfg.SkipPhases\n\t\t}\n\t\treturn data, nil\n\t})\n\n\t// binds the Runner to kubeadm init command by altering\n\t// command help, adding --skip-phases flag and by adding phases subcommands\n\tinitRunner.BindToCommand(cmd)\n\n\treturn cmd\n}","line":{"from":90,"to":173}} {"id":100000542,"name":"AddInitConfigFlags","signature":"func AddInitConfigFlags(flagSet *flag.FlagSet, cfg *kubeadmapiv1.InitConfiguration)","file":"cmd/kubeadm/app/cmd/init.go","code":"// AddInitConfigFlags adds init flags bound to the config to the specified flagset\nfunc AddInitConfigFlags(flagSet *flag.FlagSet, cfg *kubeadmapiv1.InitConfiguration) {\n\tflagSet.StringVar(\n\t\t\u0026cfg.LocalAPIEndpoint.AdvertiseAddress, options.APIServerAdvertiseAddress, cfg.LocalAPIEndpoint.AdvertiseAddress,\n\t\t\"The IP address the API Server will advertise it's listening on. If not set the default network interface will be used.\",\n\t)\n\tflagSet.Int32Var(\n\t\t\u0026cfg.LocalAPIEndpoint.BindPort, options.APIServerBindPort, cfg.LocalAPIEndpoint.BindPort,\n\t\t\"Port for the API Server to bind to.\",\n\t)\n\tflagSet.StringVar(\n\t\t\u0026cfg.NodeRegistration.Name, options.NodeName, cfg.NodeRegistration.Name,\n\t\t`Specify the node name.`,\n\t)\n\tflagSet.StringVar(\n\t\t\u0026cfg.CertificateKey, options.CertificateKey, \"\",\n\t\t\"Key used to encrypt the control-plane certificates in the kubeadm-certs Secret.\",\n\t)\n\tcmdutil.AddCRISocketFlag(flagSet, \u0026cfg.NodeRegistration.CRISocket)\n}","line":{"from":175,"to":194}} {"id":100000543,"name":"AddClusterConfigFlags","signature":"func AddClusterConfigFlags(flagSet *flag.FlagSet, cfg *kubeadmapiv1.ClusterConfiguration, featureGatesString *string)","file":"cmd/kubeadm/app/cmd/init.go","code":"// AddClusterConfigFlags adds cluster flags bound to the config to the specified flagset\nfunc AddClusterConfigFlags(flagSet *flag.FlagSet, cfg *kubeadmapiv1.ClusterConfiguration, featureGatesString *string) {\n\tflagSet.StringVar(\n\t\t\u0026cfg.Networking.ServiceSubnet, options.NetworkingServiceSubnet, cfg.Networking.ServiceSubnet,\n\t\t\"Use alternative range of IP address for service VIPs.\",\n\t)\n\tflagSet.StringVar(\n\t\t\u0026cfg.Networking.PodSubnet, options.NetworkingPodSubnet, cfg.Networking.PodSubnet,\n\t\t\"Specify range of IP addresses for the pod network. If set, the control plane will automatically allocate CIDRs for every node.\",\n\t)\n\tflagSet.StringVar(\n\t\t\u0026cfg.Networking.DNSDomain, options.NetworkingDNSDomain, cfg.Networking.DNSDomain,\n\t\t`Use alternative domain for services, e.g. \"myorg.internal\".`,\n\t)\n\n\tflagSet.StringVar(\n\t\t\u0026cfg.ControlPlaneEndpoint, options.ControlPlaneEndpoint, cfg.ControlPlaneEndpoint,\n\t\t`Specify a stable IP address or DNS name for the control plane.`,\n\t)\n\n\toptions.AddKubernetesVersionFlag(flagSet, \u0026cfg.KubernetesVersion)\n\n\tflagSet.StringVar(\n\t\t\u0026cfg.CertificatesDir, options.CertificatesDir, cfg.CertificatesDir,\n\t\t`The path where to save and store the certificates.`,\n\t)\n\tflagSet.StringSliceVar(\n\t\t\u0026cfg.APIServer.CertSANs, options.APIServerCertSANs, cfg.APIServer.CertSANs,\n\t\t`Optional extra Subject Alternative Names (SANs) to use for the API Server serving certificate. Can be both IP addresses and DNS names.`,\n\t)\n\toptions.AddFeatureGatesStringFlag(flagSet, featureGatesString)\n}","line":{"from":196,"to":227}} {"id":100000544,"name":"AddInitOtherFlags","signature":"func AddInitOtherFlags(flagSet *flag.FlagSet, initOptions *initOptions)","file":"cmd/kubeadm/app/cmd/init.go","code":"// AddInitOtherFlags adds init flags that are not bound to a configuration file to the given flagset\n// Note: All flags that are not bound to the cfg object should be allowed in cmd/kubeadm/app/apis/kubeadm/validation/validation.go\nfunc AddInitOtherFlags(flagSet *flag.FlagSet, initOptions *initOptions) {\n\toptions.AddConfigFlag(flagSet, \u0026initOptions.cfgPath)\n\tflagSet.StringSliceVar(\n\t\t\u0026initOptions.ignorePreflightErrors, options.IgnorePreflightErrors, initOptions.ignorePreflightErrors,\n\t\t\"A list of checks whose errors will be shown as warnings. Example: 'IsPrivilegedUser,Swap'. Value 'all' ignores errors from all checks.\",\n\t)\n\tflagSet.BoolVar(\n\t\t\u0026initOptions.skipTokenPrint, options.SkipTokenPrint, initOptions.skipTokenPrint,\n\t\t\"Skip printing of the default bootstrap token generated by 'kubeadm init'.\",\n\t)\n\tflagSet.BoolVar(\n\t\t\u0026initOptions.dryRun, options.DryRun, initOptions.dryRun,\n\t\t\"Don't apply any changes; just output what would be done.\",\n\t)\n\tflagSet.BoolVar(\n\t\t\u0026initOptions.uploadCerts, options.UploadCerts, initOptions.uploadCerts,\n\t\t\"Upload control-plane certificates to the kubeadm-certs Secret.\",\n\t)\n\tflagSet.BoolVar(\n\t\t\u0026initOptions.skipCertificateKeyPrint, options.SkipCertificateKeyPrint, initOptions.skipCertificateKeyPrint,\n\t\t\"Don't print the key used to encrypt the control-plane certificates.\",\n\t)\n\toptions.AddPatchesFlag(flagSet, \u0026initOptions.patchesDir)\n}","line":{"from":229,"to":254}} {"id":100000545,"name":"newInitOptions","signature":"func newInitOptions() *initOptions","file":"cmd/kubeadm/app/cmd/init.go","code":"// newInitOptions returns a struct ready for being used for creating cmd init flags.\nfunc newInitOptions() *initOptions {\n\t// initialize the public kubeadm config API by applying defaults\n\texternalInitCfg := \u0026kubeadmapiv1.InitConfiguration{}\n\tkubeadmscheme.Scheme.Default(externalInitCfg)\n\n\texternalClusterCfg := \u0026kubeadmapiv1.ClusterConfiguration{}\n\tkubeadmscheme.Scheme.Default(externalClusterCfg)\n\n\t// Create the options object for the bootstrap token-related flags, and override the default value for .Description\n\tbto := options.NewBootstrapTokenOptions()\n\tbto.Description = \"The default bootstrap token generated by 'kubeadm init'.\"\n\n\treturn \u0026initOptions{\n\t\texternalInitCfg: externalInitCfg,\n\t\texternalClusterCfg: externalClusterCfg,\n\t\tbto: bto,\n\t\tkubeconfigDir: kubeadmconstants.KubernetesDir,\n\t\tkubeconfigPath: kubeadmconstants.GetAdminKubeConfigPath(),\n\t\tuploadCerts: false,\n\t}\n}","line":{"from":256,"to":277}} {"id":100000546,"name":"newInitData","signature":"func newInitData(cmd *cobra.Command, args []string, options *initOptions, out io.Writer) (*initData, error)","file":"cmd/kubeadm/app/cmd/init.go","code":"// newInitData returns a new initData struct to be used for the execution of the kubeadm init workflow.\n// This func takes care of validating initOptions passed to the command, and then it converts\n// options into the internal InitConfiguration type that is used as input all the phases in the kubeadm init workflow\nfunc newInitData(cmd *cobra.Command, args []string, options *initOptions, out io.Writer) (*initData, error) {\n\t// Re-apply defaults to the public kubeadm API (this will set only values not exposed/not set as a flags)\n\tkubeadmscheme.Scheme.Default(options.externalInitCfg)\n\tkubeadmscheme.Scheme.Default(options.externalClusterCfg)\n\n\t// Validate standalone flags values and/or combination of flags and then assigns\n\t// validated values to the public kubeadm config API when applicable\n\tvar err error\n\tif options.externalClusterCfg.FeatureGates, err = features.NewFeatureGate(\u0026features.InitFeatureGates, options.featureGatesString); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = validation.ValidateMixedArguments(cmd.Flags()); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = options.bto.ApplyTo(options.externalInitCfg); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Either use the config file if specified, or convert public kubeadm API to the internal InitConfiguration\n\t// and validates InitConfiguration\n\tcfg, err := configutil.LoadOrDefaultInitConfiguration(options.cfgPath, options.externalInitCfg, options.externalClusterCfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tignorePreflightErrorsSet, err := validation.ValidateIgnorePreflightErrors(options.ignorePreflightErrors, cfg.NodeRegistration.IgnorePreflightErrors)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Also set the union of pre-flight errors to InitConfiguration, to provide a consistent view of the runtime configuration:\n\tcfg.NodeRegistration.IgnorePreflightErrors = sets.List(ignorePreflightErrorsSet)\n\n\t// override node name from the command line option\n\tif options.externalInitCfg.NodeRegistration.Name != \"\" {\n\t\tcfg.NodeRegistration.Name = options.externalInitCfg.NodeRegistration.Name\n\t}\n\n\tif err := configutil.VerifyAPIServerBindAddress(cfg.LocalAPIEndpoint.AdvertiseAddress); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := features.ValidateVersion(features.InitFeatureGates, cfg.FeatureGates, cfg.KubernetesVersion); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// if dry running creates a temporary folder for saving kubeadm generated files\n\tdryRunDir := \"\"\n\tif options.dryRun {\n\t\t// the KUBEADM_INIT_DRYRUN_DIR environment variable allows overriding the dry-run temporary\n\t\t// directory from the command line. This makes it possible to run \"kubeadm init\" integration\n\t\t// tests without root.\n\t\tif dryRunDir, err = kubeadmconstants.CreateTempDirForKubeadm(os.Getenv(\"KUBEADM_INIT_DRYRUN_DIR\"), \"kubeadm-init-dryrun\"); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"couldn't create a temporary directory\")\n\t\t}\n\t}\n\n\t// Checks if an external CA is provided by the user (when the CA Cert is present but the CA Key is not)\n\texternalCA, err := certsphase.UsingExternalCA(\u0026cfg.ClusterConfiguration)\n\tif externalCA {\n\t\t// In case the certificates signed by CA (that should be provided by the user) are missing or invalid,\n\t\t// returns, because kubeadm can't regenerate them without the CA Key\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"invalid or incomplete external CA\")\n\t\t}\n\n\t\t// Validate that also the required kubeconfig files exists and are invalid, because\n\t\t// kubeadm can't regenerate them without the CA Key\n\t\tkubeconfigDir := options.kubeconfigDir\n\t\tif err := kubeconfigphase.ValidateKubeconfigsForExternalCA(kubeconfigDir, cfg); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Checks if an external Front-Proxy CA is provided by the user (when the Front-Proxy CA Cert is present but the Front-Proxy CA Key is not)\n\texternalFrontProxyCA, err := certsphase.UsingExternalFrontProxyCA(\u0026cfg.ClusterConfiguration)\n\tif externalFrontProxyCA {\n\t\t// In case the certificates signed by Front-Proxy CA (that should be provided by the user) are missing or invalid,\n\t\t// returns, because kubeadm can't regenerate them without the Front-Proxy CA Key\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"invalid or incomplete external front-proxy CA\")\n\t\t}\n\t}\n\n\tif options.uploadCerts \u0026\u0026 (externalCA || externalFrontProxyCA) {\n\t\treturn nil, errors.New(\"can't use upload-certs with an external CA or an external front-proxy CA\")\n\t}\n\n\treturn \u0026initData{\n\t\tcfg: cfg,\n\t\tcertificatesDir: cfg.CertificatesDir,\n\t\tskipTokenPrint: options.skipTokenPrint,\n\t\tdryRun: options.dryRun,\n\t\tdryRunDir: dryRunDir,\n\t\tkubeconfigDir: options.kubeconfigDir,\n\t\tkubeconfigPath: options.kubeconfigPath,\n\t\tignorePreflightErrors: ignorePreflightErrorsSet,\n\t\texternalCA: externalCA,\n\t\toutputWriter: out,\n\t\tuploadCerts: options.uploadCerts,\n\t\tskipCertificateKeyPrint: options.skipCertificateKeyPrint,\n\t\tpatchesDir: options.patchesDir,\n\t}, nil\n}","line":{"from":279,"to":385}} {"id":100000547,"name":"UploadCerts","signature":"func (d *initData) UploadCerts() bool","file":"cmd/kubeadm/app/cmd/init.go","code":"// UploadCerts returns Uploadcerts flag.\nfunc (d *initData) UploadCerts() bool {\n\treturn d.uploadCerts\n}","line":{"from":387,"to":390}} {"id":100000548,"name":"CertificateKey","signature":"func (d *initData) CertificateKey() string","file":"cmd/kubeadm/app/cmd/init.go","code":"// CertificateKey returns the key used to encrypt the certs.\nfunc (d *initData) CertificateKey() string {\n\treturn d.cfg.CertificateKey\n}","line":{"from":392,"to":395}} {"id":100000549,"name":"SetCertificateKey","signature":"func (d *initData) SetCertificateKey(key string)","file":"cmd/kubeadm/app/cmd/init.go","code":"// SetCertificateKey set the key used to encrypt the certs.\nfunc (d *initData) SetCertificateKey(key string) {\n\td.cfg.CertificateKey = key\n}","line":{"from":397,"to":400}} {"id":100000550,"name":"SkipCertificateKeyPrint","signature":"func (d *initData) SkipCertificateKeyPrint() bool","file":"cmd/kubeadm/app/cmd/init.go","code":"// SkipCertificateKeyPrint returns the skipCertificateKeyPrint flag.\nfunc (d *initData) SkipCertificateKeyPrint() bool {\n\treturn d.skipCertificateKeyPrint\n}","line":{"from":402,"to":405}} {"id":100000551,"name":"Cfg","signature":"func (d *initData) Cfg() *kubeadmapi.InitConfiguration","file":"cmd/kubeadm/app/cmd/init.go","code":"// Cfg returns initConfiguration.\nfunc (d *initData) Cfg() *kubeadmapi.InitConfiguration {\n\treturn d.cfg\n}","line":{"from":407,"to":410}} {"id":100000552,"name":"DryRun","signature":"func (d *initData) DryRun() bool","file":"cmd/kubeadm/app/cmd/init.go","code":"// DryRun returns the DryRun flag.\nfunc (d *initData) DryRun() bool {\n\treturn d.dryRun\n}","line":{"from":412,"to":415}} {"id":100000553,"name":"SkipTokenPrint","signature":"func (d *initData) SkipTokenPrint() bool","file":"cmd/kubeadm/app/cmd/init.go","code":"// SkipTokenPrint returns the SkipTokenPrint flag.\nfunc (d *initData) SkipTokenPrint() bool {\n\treturn d.skipTokenPrint\n}","line":{"from":417,"to":420}} {"id":100000554,"name":"IgnorePreflightErrors","signature":"func (d *initData) IgnorePreflightErrors() sets.Set[string]","file":"cmd/kubeadm/app/cmd/init.go","code":"// IgnorePreflightErrors returns the IgnorePreflightErrors flag.\nfunc (d *initData) IgnorePreflightErrors() sets.Set[string] {\n\treturn d.ignorePreflightErrors\n}","line":{"from":422,"to":425}} {"id":100000555,"name":"CertificateWriteDir","signature":"func (d *initData) CertificateWriteDir() string","file":"cmd/kubeadm/app/cmd/init.go","code":"// CertificateWriteDir returns the path to the certificate folder or the temporary folder path in case of DryRun.\nfunc (d *initData) CertificateWriteDir() string {\n\tif d.dryRun {\n\t\treturn d.dryRunDir\n\t}\n\treturn d.certificatesDir\n}","line":{"from":427,"to":433}} {"id":100000556,"name":"CertificateDir","signature":"func (d *initData) CertificateDir() string","file":"cmd/kubeadm/app/cmd/init.go","code":"// CertificateDir returns the CertificateDir as originally specified by the user.\nfunc (d *initData) CertificateDir() string {\n\treturn d.certificatesDir\n}","line":{"from":435,"to":438}} {"id":100000557,"name":"KubeConfigDir","signature":"func (d *initData) KubeConfigDir() string","file":"cmd/kubeadm/app/cmd/init.go","code":"// KubeConfigDir returns the path of the Kubernetes configuration folder or the temporary folder path in case of DryRun.\nfunc (d *initData) KubeConfigDir() string {\n\tif d.dryRun {\n\t\treturn d.dryRunDir\n\t}\n\treturn d.kubeconfigDir\n}","line":{"from":440,"to":446}} {"id":100000558,"name":"KubeConfigPath","signature":"func (d *initData) KubeConfigPath() string","file":"cmd/kubeadm/app/cmd/init.go","code":"// KubeConfigPath returns the path to the kubeconfig file to use for connecting to Kubernetes\nfunc (d *initData) KubeConfigPath() string {\n\tif d.dryRun {\n\t\td.kubeconfigPath = filepath.Join(d.dryRunDir, kubeadmconstants.AdminKubeConfigFileName)\n\t}\n\treturn d.kubeconfigPath\n}","line":{"from":448,"to":454}} {"id":100000559,"name":"ManifestDir","signature":"func (d *initData) ManifestDir() string","file":"cmd/kubeadm/app/cmd/init.go","code":"// ManifestDir returns the path where manifest should be stored or the temporary folder path in case of DryRun.\nfunc (d *initData) ManifestDir() string {\n\tif d.dryRun {\n\t\treturn d.dryRunDir\n\t}\n\treturn kubeadmconstants.GetStaticPodDirectory()\n}","line":{"from":456,"to":462}} {"id":100000560,"name":"KubeletDir","signature":"func (d *initData) KubeletDir() string","file":"cmd/kubeadm/app/cmd/init.go","code":"// KubeletDir returns path of the kubelet configuration folder or the temporary folder in case of DryRun.\nfunc (d *initData) KubeletDir() string {\n\tif d.dryRun {\n\t\treturn d.dryRunDir\n\t}\n\treturn kubeadmconstants.KubeletRunDirectory\n}","line":{"from":464,"to":470}} {"id":100000561,"name":"ExternalCA","signature":"func (d *initData) ExternalCA() bool","file":"cmd/kubeadm/app/cmd/init.go","code":"// ExternalCA returns true if an external CA is provided by the user.\nfunc (d *initData) ExternalCA() bool {\n\treturn d.externalCA\n}","line":{"from":472,"to":475}} {"id":100000562,"name":"OutputWriter","signature":"func (d *initData) OutputWriter() io.Writer","file":"cmd/kubeadm/app/cmd/init.go","code":"// OutputWriter returns the io.Writer used to write output to by this command.\nfunc (d *initData) OutputWriter() io.Writer {\n\treturn d.outputWriter\n}","line":{"from":477,"to":480}} {"id":100000563,"name":"Client","signature":"func (d *initData) Client() (clientset.Interface, error)","file":"cmd/kubeadm/app/cmd/init.go","code":"// Client returns a Kubernetes client to be used by kubeadm.\n// This function is implemented as a singleton, thus avoiding to recreate the client when it is used by different phases.\n// Important. This function must be called after the admin.conf kubeconfig file is created.\nfunc (d *initData) Client() (clientset.Interface, error) {\n\tif d.client == nil {\n\t\tif d.dryRun {\n\t\t\tsvcSubnetCIDR, err := kubeadmconstants.GetKubernetesServiceCIDR(d.cfg.Networking.ServiceSubnet)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrapf(err, \"unable to get internal Kubernetes Service IP from the given service CIDR (%s)\", d.cfg.Networking.ServiceSubnet)\n\t\t\t}\n\t\t\t// If we're dry-running, we should create a faked client that answers some GETs in order to be able to do the full init flow and just logs the rest of requests\n\t\t\tdryRunGetter := apiclient.NewInitDryRunGetter(d.cfg.NodeRegistration.Name, svcSubnetCIDR.String())\n\t\t\td.client = apiclient.NewDryRunClient(dryRunGetter, os.Stdout)\n\t\t} else {\n\t\t\t// If we're acting for real, we should create a connection to the API server and wait for it to come up\n\t\t\tvar err error\n\t\t\td.client, err = kubeconfigutil.ClientSetFromFile(d.KubeConfigPath())\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\treturn d.client, nil\n}","line":{"from":482,"to":505}} {"id":100000564,"name":"Tokens","signature":"func (d *initData) Tokens() []string","file":"cmd/kubeadm/app/cmd/init.go","code":"// Tokens returns an array of token strings.\nfunc (d *initData) Tokens() []string {\n\ttokens := []string{}\n\tfor _, bt := range d.cfg.BootstrapTokens {\n\t\ttokens = append(tokens, bt.Token.String())\n\t}\n\treturn tokens\n}","line":{"from":507,"to":514}} {"id":100000565,"name":"PatchesDir","signature":"func (d *initData) PatchesDir() string","file":"cmd/kubeadm/app/cmd/init.go","code":"// PatchesDir returns the folder where patches for components are stored\nfunc (d *initData) PatchesDir() string {\n\t// If provided, make the flag value override the one in config.\n\tif len(d.patchesDir) \u003e 0 {\n\t\treturn d.patchesDir\n\t}\n\tif d.cfg.Patches != nil {\n\t\treturn d.cfg.Patches.Directory\n\t}\n\treturn \"\"\n}","line":{"from":516,"to":526}} {"id":100000566,"name":"newCmdJoin","signature":"func newCmdJoin(out io.Writer, joinOptions *joinOptions) *cobra.Command","file":"cmd/kubeadm/app/cmd/join.go","code":"// newCmdJoin returns \"kubeadm join\" command.\n// NB. joinOptions is exposed as parameter for allowing unit testing of\n// the newJoinData method, that implements all the command options validation logic\nfunc newCmdJoin(out io.Writer, joinOptions *joinOptions) *cobra.Command {\n\tif joinOptions == nil {\n\t\tjoinOptions = newJoinOptions()\n\t}\n\tjoinRunner := workflow.NewRunner()\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"join [api-server-endpoint]\",\n\t\tShort: \"Run this on any machine you wish to join an existing cluster\",\n\t\tLong: joinLongDescription,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\n\t\t\tc, err := joinRunner.InitData(args)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tdata := c.(*joinData)\n\n\t\t\tif err := joinRunner.Run(args); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// if the node is hosting a new control plane instance\n\t\t\tif data.cfg.ControlPlane != nil {\n\t\t\t\t// outputs the join control plane done message and exit\n\t\t\t\tetcdMessage := \"\"\n\t\t\t\tif data.initCfg.Etcd.External == nil {\n\t\t\t\t\tetcdMessage = \"* A new etcd member was added to the local/stacked etcd cluster.\"\n\t\t\t\t}\n\n\t\t\t\tctx := map[string]string{\n\t\t\t\t\t\"KubeConfigPath\": kubeadmconstants.GetAdminKubeConfigPath(),\n\t\t\t\t\t\"etcdMessage\": etcdMessage,\n\t\t\t\t}\n\t\t\t\tif err := joinControPlaneDoneTemp.Execute(data.outputWriter, ctx); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\t// otherwise, if the node joined as a worker node;\n\t\t\t\t// outputs the join done message and exit\n\t\t\t\tfmt.Fprint(data.outputWriter, joinWorkerNodeDoneMsg)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t\t// We accept the control-plane location as an optional positional argument\n\t\tArgs: cobra.MaximumNArgs(1),\n\t}\n\n\taddJoinConfigFlags(cmd.Flags(), joinOptions.externalcfg)\n\taddJoinOtherFlags(cmd.Flags(), joinOptions)\n\n\tjoinRunner.AppendPhase(phases.NewPreflightPhase())\n\tjoinRunner.AppendPhase(phases.NewControlPlanePreparePhase())\n\tjoinRunner.AppendPhase(phases.NewCheckEtcdPhase())\n\tjoinRunner.AppendPhase(phases.NewKubeletStartPhase())\n\tjoinRunner.AppendPhase(phases.NewControlPlaneJoinPhase())\n\n\t// sets the data builder function, that will be used by the runner\n\t// both when running the entire workflow or single phases\n\tjoinRunner.SetDataInitializer(func(cmd *cobra.Command, args []string) (workflow.RunData, error) {\n\t\tif cmd.Flags().Lookup(options.NodeCRISocket) == nil {\n\t\t\t// avoid CRI detection\n\t\t\t// assume that the command execution does not depend on CRISocket when --cri-socket flag is not set\n\t\t\tjoinOptions.externalcfg.NodeRegistration.CRISocket = kubeadmconstants.UnknownCRISocket\n\t\t}\n\t\tdata, err := newJoinData(cmd, args, joinOptions, out, kubeadmconstants.GetAdminKubeConfigPath())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// If the flag for skipping phases was empty, use the values from config\n\t\tif len(joinRunner.Options.SkipPhases) == 0 {\n\t\t\tjoinRunner.Options.SkipPhases = data.cfg.SkipPhases\n\t\t}\n\t\treturn data, nil\n\t})\n\n\t// binds the Runner to kubeadm join command by altering\n\t// command help, adding --skip-phases flag and by adding phases subcommands\n\tjoinRunner.BindToCommand(cmd)\n\n\treturn cmd\n}","line":{"from":157,"to":244}} {"id":100000567,"name":"addJoinConfigFlags","signature":"func addJoinConfigFlags(flagSet *flag.FlagSet, cfg *kubeadmapiv1.JoinConfiguration)","file":"cmd/kubeadm/app/cmd/join.go","code":"// addJoinConfigFlags adds join flags bound to the config to the specified flagset\nfunc addJoinConfigFlags(flagSet *flag.FlagSet, cfg *kubeadmapiv1.JoinConfiguration) {\n\tflagSet.StringVar(\n\t\t\u0026cfg.NodeRegistration.Name, options.NodeName, cfg.NodeRegistration.Name,\n\t\t`Specify the node name.`,\n\t)\n\tflagSet.StringVar(\n\t\t\u0026cfg.ControlPlane.CertificateKey, options.CertificateKey, cfg.ControlPlane.CertificateKey,\n\t\t\"Use this key to decrypt the certificate secrets uploaded by init.\",\n\t)\n\t// add control plane endpoint flags to the specified flagset\n\tflagSet.StringVar(\n\t\t\u0026cfg.ControlPlane.LocalAPIEndpoint.AdvertiseAddress, options.APIServerAdvertiseAddress, cfg.ControlPlane.LocalAPIEndpoint.AdvertiseAddress,\n\t\t\"If the node should host a new control plane instance, the IP address the API Server will advertise it's listening on. If not set the default network interface will be used.\",\n\t)\n\tflagSet.Int32Var(\n\t\t\u0026cfg.ControlPlane.LocalAPIEndpoint.BindPort, options.APIServerBindPort, cfg.ControlPlane.LocalAPIEndpoint.BindPort,\n\t\t\"If the node should host a new control plane instance, the port for the API Server to bind to.\",\n\t)\n\t// adds bootstrap token specific discovery flags to the specified flagset\n\tflagSet.StringVar(\n\t\t\u0026cfg.Discovery.BootstrapToken.Token, options.TokenDiscovery, \"\",\n\t\t\"For token-based discovery, the token used to validate cluster information fetched from the API server.\",\n\t)\n\tflagSet.StringSliceVar(\n\t\t\u0026cfg.Discovery.BootstrapToken.CACertHashes, options.TokenDiscoveryCAHash, []string{},\n\t\t\"For token-based discovery, validate that the root CA public key matches this hash (format: \\\"\u003ctype\u003e:\u003cvalue\u003e\\\").\",\n\t)\n\tflagSet.BoolVar(\n\t\t\u0026cfg.Discovery.BootstrapToken.UnsafeSkipCAVerification, options.TokenDiscoverySkipCAHash, false,\n\t\t\"For token-based discovery, allow joining without --discovery-token-ca-cert-hash pinning.\",\n\t)\n\t//\tdiscovery via kube config file flag\n\tflagSet.StringVar(\n\t\t\u0026cfg.Discovery.File.KubeConfigPath, options.FileDiscovery, \"\",\n\t\t\"For file-based discovery, a file or URL from which to load cluster information.\",\n\t)\n\tflagSet.StringVar(\n\t\t\u0026cfg.Discovery.TLSBootstrapToken, options.TLSBootstrapToken, cfg.Discovery.TLSBootstrapToken,\n\t\t`Specify the token used to temporarily authenticate with the Kubernetes Control Plane while joining the node.`,\n\t)\n\tcmdutil.AddCRISocketFlag(flagSet, \u0026cfg.NodeRegistration.CRISocket)\n}","line":{"from":246,"to":288}} {"id":100000568,"name":"addJoinOtherFlags","signature":"func addJoinOtherFlags(flagSet *flag.FlagSet, joinOptions *joinOptions)","file":"cmd/kubeadm/app/cmd/join.go","code":"// addJoinOtherFlags adds join flags that are not bound to a configuration file to the given flagset\nfunc addJoinOtherFlags(flagSet *flag.FlagSet, joinOptions *joinOptions) {\n\toptions.AddConfigFlag(flagSet, \u0026joinOptions.cfgPath)\n\tflagSet.StringSliceVar(\n\t\t\u0026joinOptions.ignorePreflightErrors, options.IgnorePreflightErrors, joinOptions.ignorePreflightErrors,\n\t\t\"A list of checks whose errors will be shown as warnings. Example: 'IsPrivilegedUser,Swap'. Value 'all' ignores errors from all checks.\",\n\t)\n\tflagSet.StringVar(\n\t\t\u0026joinOptions.token, options.TokenStr, \"\",\n\t\t\"Use this token for both discovery-token and tls-bootstrap-token when those values are not provided.\",\n\t)\n\tflagSet.BoolVar(\n\t\t\u0026joinOptions.controlPlane, options.ControlPlane, joinOptions.controlPlane,\n\t\t\"Create a new control plane instance on this node\",\n\t)\n\tflagSet.BoolVar(\n\t\t\u0026joinOptions.dryRun, options.DryRun, joinOptions.dryRun,\n\t\t\"Don't apply any changes; just output what would be done.\",\n\t)\n\toptions.AddPatchesFlag(flagSet, \u0026joinOptions.patchesDir)\n}","line":{"from":290,"to":310}} {"id":100000569,"name":"newJoinOptions","signature":"func newJoinOptions() *joinOptions","file":"cmd/kubeadm/app/cmd/join.go","code":"// newJoinOptions returns a struct ready for being used for creating cmd join flags.\nfunc newJoinOptions() *joinOptions {\n\t// initialize the public kubeadm config API by applying defaults\n\texternalcfg := \u0026kubeadmapiv1.JoinConfiguration{}\n\n\t// Add optional config objects to host flags.\n\t// un-set objects will be cleaned up afterwards (into newJoinData func)\n\texternalcfg.Discovery.File = \u0026kubeadmapiv1.FileDiscovery{}\n\texternalcfg.Discovery.BootstrapToken = \u0026kubeadmapiv1.BootstrapTokenDiscovery{}\n\texternalcfg.ControlPlane = \u0026kubeadmapiv1.JoinControlPlane{}\n\n\t// This object is used for storage of control-plane flags.\n\tjoinControlPlane := \u0026kubeadmapiv1.JoinControlPlane{}\n\n\t// Apply defaults\n\tkubeadmscheme.Scheme.Default(externalcfg)\n\tkubeadmapiv1.SetDefaults_JoinControlPlane(joinControlPlane)\n\n\treturn \u0026joinOptions{\n\t\texternalcfg: externalcfg,\n\t}\n}","line":{"from":312,"to":333}} {"id":100000570,"name":"newJoinData","signature":"func newJoinData(cmd *cobra.Command, args []string, opt *joinOptions, out io.Writer, adminKubeConfigPath string) (*joinData, error)","file":"cmd/kubeadm/app/cmd/join.go","code":"// newJoinData returns a new joinData struct to be used for the execution of the kubeadm join workflow.\n// This func takes care of validating joinOptions passed to the command, and then it converts\n// options into the internal JoinConfiguration type that is used as input all the phases in the kubeadm join workflow\nfunc newJoinData(cmd *cobra.Command, args []string, opt *joinOptions, out io.Writer, adminKubeConfigPath string) (*joinData, error) {\n\n\t// Validate the mixed arguments with --config and return early on errors\n\tif err := validation.ValidateMixedArguments(cmd.Flags()); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Re-apply defaults to the public kubeadm API (this will set only values not exposed/not set as a flags)\n\tkubeadmscheme.Scheme.Default(opt.externalcfg)\n\n\t// Validate standalone flags values and/or combination of flags and then assigns\n\t// validated values to the public kubeadm config API when applicable\n\n\t// if a token is provided, use this value for both discovery-token and tls-bootstrap-token when those values are not provided\n\tif len(opt.token) \u003e 0 {\n\t\tif len(opt.externalcfg.Discovery.TLSBootstrapToken) == 0 {\n\t\t\topt.externalcfg.Discovery.TLSBootstrapToken = opt.token\n\t\t}\n\t\tif len(opt.externalcfg.Discovery.BootstrapToken.Token) == 0 {\n\t\t\topt.externalcfg.Discovery.BootstrapToken.Token = opt.token\n\t\t}\n\t}\n\n\t// if a file or URL from which to load cluster information was not provided, unset the Discovery.File object\n\tif len(opt.externalcfg.Discovery.File.KubeConfigPath) == 0 {\n\t\topt.externalcfg.Discovery.File = nil\n\t}\n\n\t// if an APIServerEndpoint from which to retrieve cluster information was not provided, unset the Discovery.BootstrapToken object\n\tif len(args) == 0 {\n\t\topt.externalcfg.Discovery.BootstrapToken = nil\n\t} else {\n\t\tif len(opt.cfgPath) == 0 \u0026\u0026 len(args) \u003e 1 {\n\t\t\tklog.Warningf(\"[preflight] WARNING: More than one API server endpoint supplied on command line %v. Using the first one.\", args)\n\t\t}\n\t\topt.externalcfg.Discovery.BootstrapToken.APIServerEndpoint = args[0]\n\t}\n\n\t// If not passing --control-plane, unset the ControlPlane object\n\tif !opt.controlPlane {\n\t\t// Use a defaulted JoinControlPlane object to detect if the user has passed\n\t\t// other control-plane related flags.\n\t\tdefaultJCP := \u0026kubeadmapiv1.JoinControlPlane{}\n\t\tkubeadmapiv1.SetDefaults_JoinControlPlane(defaultJCP)\n\n\t\t// This list must match the JCP flags in addJoinConfigFlags()\n\t\tjoinControlPlaneFlags := []string{\n\t\t\toptions.CertificateKey,\n\t\t\toptions.APIServerAdvertiseAddress,\n\t\t\toptions.APIServerBindPort,\n\t\t}\n\n\t\tif *opt.externalcfg.ControlPlane != *defaultJCP {\n\t\t\tklog.Warningf(\"[preflight] WARNING: --%s is also required when passing control-plane \"+\n\t\t\t\t\"related flags such as [%s]\", options.ControlPlane, strings.Join(joinControlPlaneFlags, \", \"))\n\t\t}\n\t\topt.externalcfg.ControlPlane = nil\n\t}\n\n\t// if the admin.conf file already exists, use it for skipping the discovery process.\n\t// NB. this case can happen when we are joining a control-plane node only (and phases are invoked atomically)\n\tvar tlsBootstrapCfg *clientcmdapi.Config\n\tif _, err := os.Stat(adminKubeConfigPath); err == nil \u0026\u0026 opt.controlPlane {\n\t\t// use the admin.conf as tlsBootstrapCfg, that is the kubeconfig file used for reading the kubeadm-config during discovery\n\t\tklog.V(1).Infof(\"[preflight] found %s. Use it for skipping discovery\", adminKubeConfigPath)\n\t\ttlsBootstrapCfg, err = clientcmd.LoadFromFile(adminKubeConfigPath)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"Error loading %s\", adminKubeConfigPath)\n\t\t}\n\t}\n\n\t// Either use the config file if specified, or convert public kubeadm API to the internal JoinConfiguration\n\t// and validates JoinConfiguration\n\tif opt.externalcfg.NodeRegistration.Name == \"\" {\n\t\tklog.V(1).Infoln(\"[preflight] found NodeName empty; using OS hostname as NodeName\")\n\t}\n\n\tif opt.externalcfg.ControlPlane != nil \u0026\u0026 opt.externalcfg.ControlPlane.LocalAPIEndpoint.AdvertiseAddress == \"\" {\n\t\tklog.V(1).Infoln(\"[preflight] found advertiseAddress empty; using default interface's IP address as advertiseAddress\")\n\t}\n\n\t// in case the command doesn't have flags for discovery, makes the join cfg validation pass checks on discovery\n\tif cmd.Flags().Lookup(options.FileDiscovery) == nil {\n\t\tif _, err := os.Stat(adminKubeConfigPath); os.IsNotExist(err) {\n\t\t\treturn nil, errors.Errorf(\"File %s does not exists. Please use 'kubeadm join phase control-plane-prepare' subcommands to generate it.\", adminKubeConfigPath)\n\t\t}\n\t\tklog.V(1).Infof(\"[preflight] found discovery flags missing for this command. using FileDiscovery: %s\", adminKubeConfigPath)\n\t\topt.externalcfg.Discovery.File = \u0026kubeadmapiv1.FileDiscovery{KubeConfigPath: adminKubeConfigPath}\n\t\topt.externalcfg.Discovery.BootstrapToken = nil //NB. this could be removed when we get better control on args (e.g. phases without discovery should have NoArgs )\n\t}\n\n\tcfg, err := configutil.LoadOrDefaultJoinConfiguration(opt.cfgPath, opt.externalcfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tignorePreflightErrorsSet, err := validation.ValidateIgnorePreflightErrors(opt.ignorePreflightErrors, cfg.NodeRegistration.IgnorePreflightErrors)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Also set the union of pre-flight errors to JoinConfiguration, to provide a consistent view of the runtime configuration:\n\tcfg.NodeRegistration.IgnorePreflightErrors = sets.List(ignorePreflightErrorsSet)\n\n\t// override node name and CRI socket from the command line opt\n\tif opt.externalcfg.NodeRegistration.Name != \"\" {\n\t\tcfg.NodeRegistration.Name = opt.externalcfg.NodeRegistration.Name\n\t}\n\tif opt.externalcfg.NodeRegistration.CRISocket != \"\" {\n\t\tcfg.NodeRegistration.CRISocket = opt.externalcfg.NodeRegistration.CRISocket\n\t}\n\n\tif cfg.ControlPlane != nil {\n\t\tif err := configutil.VerifyAPIServerBindAddress(cfg.ControlPlane.LocalAPIEndpoint.AdvertiseAddress); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// if dry running, creates a temporary folder to save kubeadm generated files\n\tdryRunDir := \"\"\n\tif opt.dryRun {\n\t\tif dryRunDir, err = kubeadmconstants.CreateTempDirForKubeadm(\"\", \"kubeadm-join-dryrun\"); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"couldn't create a temporary directory on dryrun\")\n\t\t}\n\t}\n\n\treturn \u0026joinData{\n\t\tcfg: cfg,\n\t\ttlsBootstrapCfg: tlsBootstrapCfg,\n\t\tignorePreflightErrors: ignorePreflightErrorsSet,\n\t\toutputWriter: out,\n\t\tpatchesDir: opt.patchesDir,\n\t\tdryRun: opt.dryRun,\n\t\tdryRunDir: dryRunDir,\n\t}, nil\n}","line":{"from":335,"to":472}} {"id":100000571,"name":"CertificateKey","signature":"func (j *joinData) CertificateKey() string","file":"cmd/kubeadm/app/cmd/join.go","code":"// CertificateKey returns the key used to encrypt the certs.\nfunc (j *joinData) CertificateKey() string {\n\tif j.cfg.ControlPlane != nil {\n\t\treturn j.cfg.ControlPlane.CertificateKey\n\t}\n\treturn \"\"\n}","line":{"from":474,"to":480}} {"id":100000572,"name":"Cfg","signature":"func (j *joinData) Cfg() *kubeadmapi.JoinConfiguration","file":"cmd/kubeadm/app/cmd/join.go","code":"// Cfg returns the JoinConfiguration.\nfunc (j *joinData) Cfg() *kubeadmapi.JoinConfiguration {\n\treturn j.cfg\n}","line":{"from":482,"to":485}} {"id":100000573,"name":"DryRun","signature":"func (j *joinData) DryRun() bool","file":"cmd/kubeadm/app/cmd/join.go","code":"// DryRun returns the DryRun flag.\nfunc (j *joinData) DryRun() bool {\n\treturn j.dryRun\n}","line":{"from":487,"to":490}} {"id":100000574,"name":"KubeConfigDir","signature":"func (j *joinData) KubeConfigDir() string","file":"cmd/kubeadm/app/cmd/join.go","code":"// KubeConfigDir returns the path of the Kubernetes configuration folder or the temporary folder path in case of DryRun.\nfunc (j *joinData) KubeConfigDir() string {\n\tif j.dryRun {\n\t\treturn j.dryRunDir\n\t}\n\treturn kubeadmconstants.KubernetesDir\n}","line":{"from":492,"to":498}} {"id":100000575,"name":"KubeletDir","signature":"func (j *joinData) KubeletDir() string","file":"cmd/kubeadm/app/cmd/join.go","code":"// KubeletDir returns the path of the kubelet configuration folder or the temporary folder in case of DryRun.\nfunc (j *joinData) KubeletDir() string {\n\tif j.dryRun {\n\t\treturn j.dryRunDir\n\t}\n\treturn kubeadmconstants.KubeletRunDirectory\n}","line":{"from":500,"to":506}} {"id":100000576,"name":"ManifestDir","signature":"func (j *joinData) ManifestDir() string","file":"cmd/kubeadm/app/cmd/join.go","code":"// ManifestDir returns the path where manifest should be stored or the temporary folder path in case of DryRun.\nfunc (j *joinData) ManifestDir() string {\n\tif j.dryRun {\n\t\treturn j.dryRunDir\n\t}\n\treturn kubeadmconstants.GetStaticPodDirectory()\n}","line":{"from":508,"to":514}} {"id":100000577,"name":"CertificateWriteDir","signature":"func (j *joinData) CertificateWriteDir() string","file":"cmd/kubeadm/app/cmd/join.go","code":"// CertificateWriteDir returns the path where certs should be stored or the temporary folder path in case of DryRun.\nfunc (j *joinData) CertificateWriteDir() string {\n\tif j.dryRun {\n\t\treturn j.dryRunDir\n\t}\n\treturn j.initCfg.CertificatesDir\n}","line":{"from":516,"to":522}} {"id":100000578,"name":"TLSBootstrapCfg","signature":"func (j *joinData) TLSBootstrapCfg() (*clientcmdapi.Config, error)","file":"cmd/kubeadm/app/cmd/join.go","code":"// TLSBootstrapCfg returns the cluster-info (kubeconfig).\nfunc (j *joinData) TLSBootstrapCfg() (*clientcmdapi.Config, error) {\n\tif j.tlsBootstrapCfg != nil {\n\t\treturn j.tlsBootstrapCfg, nil\n\t}\n\tklog.V(1).Infoln(\"[preflight] Discovering cluster-info\")\n\ttlsBootstrapCfg, err := discovery.For(j.cfg)\n\tj.tlsBootstrapCfg = tlsBootstrapCfg\n\treturn tlsBootstrapCfg, err\n}","line":{"from":524,"to":533}} {"id":100000579,"name":"InitCfg","signature":"func (j *joinData) InitCfg() (*kubeadmapi.InitConfiguration, error)","file":"cmd/kubeadm/app/cmd/join.go","code":"// InitCfg returns the InitConfiguration.\nfunc (j *joinData) InitCfg() (*kubeadmapi.InitConfiguration, error) {\n\tif j.initCfg != nil {\n\t\treturn j.initCfg, nil\n\t}\n\tif _, err := j.TLSBootstrapCfg(); err != nil {\n\t\treturn nil, err\n\t}\n\tklog.V(1).Infoln(\"[preflight] Fetching init configuration\")\n\tinitCfg, err := fetchInitConfigurationFromJoinConfiguration(j.cfg, j.tlsBootstrapCfg)\n\tj.initCfg = initCfg\n\treturn initCfg, err\n}","line":{"from":535,"to":547}} {"id":100000580,"name":"Client","signature":"func (j *joinData) Client() (clientset.Interface, error)","file":"cmd/kubeadm/app/cmd/join.go","code":"// Client returns the Client for accessing the cluster with the identity defined in admin.conf.\nfunc (j *joinData) Client() (clientset.Interface, error) {\n\tif j.client != nil {\n\t\treturn j.client, nil\n\t}\n\tpath := filepath.Join(j.KubeConfigDir(), kubeadmconstants.AdminKubeConfigFileName)\n\n\tclient, err := kubeconfigutil.ClientSetFromFile(path)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"[preflight] couldn't create Kubernetes client\")\n\t}\n\tj.client = client\n\treturn client, nil\n}","line":{"from":549,"to":562}} {"id":100000581,"name":"IgnorePreflightErrors","signature":"func (j *joinData) IgnorePreflightErrors() sets.Set[string]","file":"cmd/kubeadm/app/cmd/join.go","code":"// IgnorePreflightErrors returns the list of preflight errors to ignore.\nfunc (j *joinData) IgnorePreflightErrors() sets.Set[string] {\n\treturn j.ignorePreflightErrors\n}","line":{"from":564,"to":567}} {"id":100000582,"name":"OutputWriter","signature":"func (j *joinData) OutputWriter() io.Writer","file":"cmd/kubeadm/app/cmd/join.go","code":"// OutputWriter returns the io.Writer used to write messages such as the \"join done\" message.\nfunc (j *joinData) OutputWriter() io.Writer {\n\treturn j.outputWriter\n}","line":{"from":569,"to":572}} {"id":100000583,"name":"PatchesDir","signature":"func (j *joinData) PatchesDir() string","file":"cmd/kubeadm/app/cmd/join.go","code":"// PatchesDir returns the folder where patches for components are stored\nfunc (j *joinData) PatchesDir() string {\n\t// If provided, make the flag value override the one in config.\n\tif len(j.patchesDir) \u003e 0 {\n\t\treturn j.patchesDir\n\t}\n\tif j.cfg.Patches != nil {\n\t\treturn j.cfg.Patches.Directory\n\t}\n\treturn \"\"\n}","line":{"from":574,"to":584}} {"id":100000584,"name":"fetchInitConfigurationFromJoinConfiguration","signature":"func fetchInitConfigurationFromJoinConfiguration(cfg *kubeadmapi.JoinConfiguration, tlsBootstrapCfg *clientcmdapi.Config) (*kubeadmapi.InitConfiguration, error)","file":"cmd/kubeadm/app/cmd/join.go","code":"// fetchInitConfigurationFromJoinConfiguration retrieves the init configuration from a join configuration, performing the discovery\nfunc fetchInitConfigurationFromJoinConfiguration(cfg *kubeadmapi.JoinConfiguration, tlsBootstrapCfg *clientcmdapi.Config) (*kubeadmapi.InitConfiguration, error) {\n\t// Retrieves the kubeadm configuration\n\tklog.V(1).Infoln(\"[preflight] Retrieving KubeConfig objects\")\n\tinitConfiguration, err := fetchInitConfiguration(tlsBootstrapCfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create the final KubeConfig file with the cluster name discovered after fetching the cluster configuration\n\t_, clusterinfo := kubeconfigutil.GetClusterFromKubeConfig(tlsBootstrapCfg)\n\ttlsBootstrapCfg.Clusters = map[string]*clientcmdapi.Cluster{\n\t\tinitConfiguration.ClusterName: clusterinfo,\n\t}\n\ttlsBootstrapCfg.Contexts[tlsBootstrapCfg.CurrentContext].Cluster = initConfiguration.ClusterName\n\n\t// injects into the kubeadm configuration the information about the joining node\n\tinitConfiguration.NodeRegistration = cfg.NodeRegistration\n\tif cfg.ControlPlane != nil {\n\t\tinitConfiguration.LocalAPIEndpoint = cfg.ControlPlane.LocalAPIEndpoint\n\t}\n\n\treturn initConfiguration, nil\n}","line":{"from":586,"to":609}} {"id":100000585,"name":"fetchInitConfiguration","signature":"func fetchInitConfiguration(tlsBootstrapCfg *clientcmdapi.Config) (*kubeadmapi.InitConfiguration, error)","file":"cmd/kubeadm/app/cmd/join.go","code":"// fetchInitConfiguration reads the cluster configuration from the kubeadm-admin configMap\nfunc fetchInitConfiguration(tlsBootstrapCfg *clientcmdapi.Config) (*kubeadmapi.InitConfiguration, error) {\n\t// creates a client to access the cluster using the bootstrap token identity\n\ttlsClient, err := kubeconfigutil.ToClientSet(tlsBootstrapCfg)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to access the cluster\")\n\t}\n\n\t// Fetches the init configuration\n\tinitConfiguration, err := configutil.FetchInitConfigurationFromCluster(tlsClient, nil, \"preflight\", true, false)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to fetch the kubeadm-config ConfigMap\")\n\t}\n\n\treturn initConfiguration, nil\n}","line":{"from":611,"to":626}} {"id":100000586,"name":"newCmdKubeConfigUtility","signature":"func newCmdKubeConfigUtility(out io.Writer) *cobra.Command","file":"cmd/kubeadm/app/cmd/kubeconfig.go","code":"// newCmdKubeConfigUtility returns main command for kubeconfig phase\nfunc newCmdKubeConfigUtility(out io.Writer) *cobra.Command {\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"kubeconfig\",\n\t\tShort: \"Kubeconfig file utilities\",\n\t\tLong: kubeconfigLongDesc,\n\t}\n\n\tcmd.AddCommand(newCmdUserKubeConfig(out))\n\treturn cmd\n}","line":{"from":53,"to":63}} {"id":100000587,"name":"newCmdUserKubeConfig","signature":"func newCmdUserKubeConfig(out io.Writer) *cobra.Command","file":"cmd/kubeadm/app/cmd/kubeconfig.go","code":"// newCmdUserKubeConfig returns sub commands for kubeconfig phase\nfunc newCmdUserKubeConfig(out io.Writer) *cobra.Command {\n\n\tinitCfg := cmdutil.DefaultInitConfiguration()\n\tclusterCfg := \u0026kubeadmapiv1.ClusterConfiguration{}\n\n\tvar (\n\t\ttoken, clientName, cfgPath string\n\t\torganizations []string\n\t\tvalidityPeriod time.Duration\n\t)\n\n\t// Creates the UX Command\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"user\",\n\t\tShort: \"Output a kubeconfig file for an additional user\",\n\t\tLong: userKubeconfigLongDesc,\n\t\tExample: userKubeconfigExample,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\t// This call returns the ready-to-use configuration based on the defaults populated by flags\n\t\t\tinternalCfg, err := configutil.LoadOrDefaultInitConfiguration(cfgPath, initCfg, clusterCfg)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif validityPeriod \u003e kubeadmconstants.CertificateValidity {\n\t\t\t\tklog.Warningf(\"WARNING: the specified certificate validity period %v is longer than the default duration %v, this may increase security risks.\",\n\t\t\t\t\tvalidityPeriod, kubeadmconstants.CertificateValidity)\n\t\t\t}\n\n\t\t\tnotAfter := time.Now().Add(validityPeriod).UTC()\n\n\t\t\t// if the kubeconfig file for an additional user has to use a token, use it\n\t\t\tif token != \"\" {\n\t\t\t\treturn kubeconfigphase.WriteKubeConfigWithToken(out, internalCfg, clientName, token, \u0026notAfter)\n\t\t\t}\n\n\t\t\t// Otherwise, write a kubeconfig file with a generate client cert\n\t\t\treturn kubeconfigphase.WriteKubeConfigWithClientCert(out, internalCfg, clientName, organizations, \u0026notAfter)\n\t\t},\n\t\tArgs: cobra.NoArgs,\n\t}\n\n\toptions.AddConfigFlag(cmd.Flags(), \u0026cfgPath)\n\n\t// Add command specific flags\n\tcmd.Flags().StringVar(\u0026token, options.TokenStr, token, \"The token that should be used as the authentication mechanism for this kubeconfig, instead of client certificates\")\n\tcmd.Flags().StringVar(\u0026clientName, \"client-name\", clientName, \"The name of user. It will be used as the CN if client certificates are created\")\n\tcmd.Flags().StringSliceVar(\u0026organizations, \"org\", organizations, \"The organizations of the client certificate. It will be used as the O if client certificates are created\")\n\tcmd.Flags().DurationVar(\u0026validityPeriod, \"validity-period\", kubeadmconstants.CertificateValidity, \"The validity period of the client certificate. It is an offset from the current time.\")\n\n\tcmd.MarkFlagRequired(\"client-name\")\n\treturn cmd\n}","line":{"from":65,"to":118}} {"id":100000588,"name":"AddCertificateDirFlag","signature":"func AddCertificateDirFlag(fs *pflag.FlagSet, certsDir *string)","file":"cmd/kubeadm/app/cmd/options/certs.go","code":"// AddCertificateDirFlag adds the --certs-dir flag to the given flagset\nfunc AddCertificateDirFlag(fs *pflag.FlagSet, certsDir *string) {\n\tfs.StringVar(certsDir, CertificatesDir, *certsDir, \"The path where to save the certificates\")\n}","line":{"from":21,"to":24}} {"id":100000589,"name":"AddKubeConfigFlag","signature":"func AddKubeConfigFlag(fs *pflag.FlagSet, kubeConfigFile *string)","file":"cmd/kubeadm/app/cmd/options/generic.go","code":"// AddKubeConfigFlag adds the --kubeconfig flag to the given flagset\nfunc AddKubeConfigFlag(fs *pflag.FlagSet, kubeConfigFile *string) {\n\tfs.StringVar(kubeConfigFile, KubeconfigPath, *kubeConfigFile, \"The kubeconfig file to use when talking to the cluster. If the flag is not set, a set of standard locations can be searched for an existing kubeconfig file.\")\n\t// Note that DefValue is the text shown in the terminal and not the default value assigned to the flag\n\tfs.Lookup(KubeconfigPath).DefValue = constants.GetAdminKubeConfigPath()\n}","line":{"from":30,"to":35}} {"id":100000590,"name":"AddKubeConfigDirFlag","signature":"func AddKubeConfigDirFlag(fs *pflag.FlagSet, kubeConfigDir *string)","file":"cmd/kubeadm/app/cmd/options/generic.go","code":"// AddKubeConfigDirFlag adds the --kubeconfig-dir flag to the given flagset\nfunc AddKubeConfigDirFlag(fs *pflag.FlagSet, kubeConfigDir *string) {\n\tfs.StringVar(kubeConfigDir, KubeconfigDir, *kubeConfigDir, \"The path where to save the kubeconfig file.\")\n}","line":{"from":37,"to":40}} {"id":100000591,"name":"AddConfigFlag","signature":"func AddConfigFlag(fs *pflag.FlagSet, cfgPath *string)","file":"cmd/kubeadm/app/cmd/options/generic.go","code":"// AddConfigFlag adds the --config flag to the given flagset\nfunc AddConfigFlag(fs *pflag.FlagSet, cfgPath *string) {\n\tfs.StringVar(cfgPath, CfgPath, *cfgPath, \"Path to a kubeadm configuration file.\")\n}","line":{"from":42,"to":45}} {"id":100000592,"name":"AddIgnorePreflightErrorsFlag","signature":"func AddIgnorePreflightErrorsFlag(fs *pflag.FlagSet, ignorePreflightErrors *[]string)","file":"cmd/kubeadm/app/cmd/options/generic.go","code":"// AddIgnorePreflightErrorsFlag adds the --ignore-preflight-errors flag to the given flagset\nfunc AddIgnorePreflightErrorsFlag(fs *pflag.FlagSet, ignorePreflightErrors *[]string) {\n\tfs.StringSliceVar(\n\t\tignorePreflightErrors, IgnorePreflightErrors, *ignorePreflightErrors,\n\t\t\"A list of checks whose errors will be shown as warnings. Example: 'IsPrivilegedUser,Swap'. Value 'all' ignores errors from all checks.\",\n\t)\n}","line":{"from":47,"to":53}} {"id":100000593,"name":"AddControlPlanExtraArgsFlags","signature":"func AddControlPlanExtraArgsFlags(fs *pflag.FlagSet, apiServerExtraArgs, controllerManagerExtraArgs, schedulerExtraArgs *map[string]string)","file":"cmd/kubeadm/app/cmd/options/generic.go","code":"// AddControlPlanExtraArgsFlags adds the ExtraArgs flags for control plane components\nfunc AddControlPlanExtraArgsFlags(fs *pflag.FlagSet, apiServerExtraArgs, controllerManagerExtraArgs, schedulerExtraArgs *map[string]string) {\n\tfs.Var(cliflag.NewMapStringString(apiServerExtraArgs), APIServerExtraArgs, \"A set of extra flags to pass to the API Server or override default ones in form of \u003cflagname\u003e=\u003cvalue\u003e\")\n\tfs.Var(cliflag.NewMapStringString(controllerManagerExtraArgs), ControllerManagerExtraArgs, \"A set of extra flags to pass to the Controller Manager or override default ones in form of \u003cflagname\u003e=\u003cvalue\u003e\")\n\tfs.Var(cliflag.NewMapStringString(schedulerExtraArgs), SchedulerExtraArgs, \"A set of extra flags to pass to the Scheduler or override default ones in form of \u003cflagname\u003e=\u003cvalue\u003e\")\n}","line":{"from":55,"to":60}} {"id":100000594,"name":"AddImageMetaFlags","signature":"func AddImageMetaFlags(fs *pflag.FlagSet, imageRepository *string)","file":"cmd/kubeadm/app/cmd/options/generic.go","code":"// AddImageMetaFlags adds the --image-repository flag to the given flagset\nfunc AddImageMetaFlags(fs *pflag.FlagSet, imageRepository *string) {\n\tfs.StringVar(imageRepository, ImageRepository, *imageRepository, \"Choose a container registry to pull control plane images from\")\n}","line":{"from":62,"to":65}} {"id":100000595,"name":"AddFeatureGatesStringFlag","signature":"func AddFeatureGatesStringFlag(fs *pflag.FlagSet, featureGatesString *string)","file":"cmd/kubeadm/app/cmd/options/generic.go","code":"// AddFeatureGatesStringFlag adds the --feature-gates flag to the given flagset\nfunc AddFeatureGatesStringFlag(fs *pflag.FlagSet, featureGatesString *string) {\n\tif knownFeatures := features.KnownFeatures(\u0026features.InitFeatureGates); len(knownFeatures) \u003e 0 {\n\t\tfs.StringVar(featureGatesString, FeatureGatesString, *featureGatesString, \"A set of key=value pairs that describe feature gates for various features. \"+\n\t\t\t\"Options are:\\n\"+strings.Join(knownFeatures, \"\\n\"))\n\t} else {\n\t\tfs.StringVar(featureGatesString, FeatureGatesString, *featureGatesString, \"A set of key=value pairs that describe feature gates for various features. \"+\n\t\t\t\"No feature gates are available in this release.\")\n\t}\n}","line":{"from":67,"to":76}} {"id":100000596,"name":"AddKubernetesVersionFlag","signature":"func AddKubernetesVersionFlag(fs *pflag.FlagSet, kubernetesVersion *string)","file":"cmd/kubeadm/app/cmd/options/generic.go","code":"// AddKubernetesVersionFlag adds the --kubernetes-version flag to the given flagset\nfunc AddKubernetesVersionFlag(fs *pflag.FlagSet, kubernetesVersion *string) {\n\tfs.StringVar(\n\t\tkubernetesVersion, KubernetesVersion, *kubernetesVersion,\n\t\t`Choose a specific Kubernetes version for the control plane.`,\n\t)\n}","line":{"from":78,"to":84}} {"id":100000597,"name":"AddKubeadmOtherFlags","signature":"func AddKubeadmOtherFlags(flagSet *pflag.FlagSet, rootfsPath *string)","file":"cmd/kubeadm/app/cmd/options/generic.go","code":"// AddKubeadmOtherFlags adds flags that are not bound to a configuration file to the given flagset\nfunc AddKubeadmOtherFlags(flagSet *pflag.FlagSet, rootfsPath *string) {\n\tflagSet.StringVar(\n\t\trootfsPath, \"rootfs\", *rootfsPath,\n\t\t\"[EXPERIMENTAL] The path to the 'real' host root filesystem.\",\n\t)\n}","line":{"from":86,"to":92}} {"id":100000598,"name":"AddPatchesFlag","signature":"func AddPatchesFlag(fs *pflag.FlagSet, patchesDir *string)","file":"cmd/kubeadm/app/cmd/options/generic.go","code":"// AddPatchesFlag adds the --patches flag to the given flagset\nfunc AddPatchesFlag(fs *pflag.FlagSet, patchesDir *string) {\n\tconst usage = `Path to a directory that contains files named ` +\n\t\t`\"target[suffix][+patchtype].extension\". For example, ` +\n\t\t`\"kube-apiserver0+merge.yaml\" or just \"etcd.json\". ` +\n\t\t`\"target\" can be one of \"kube-apiserver\", \"kube-controller-manager\", \"kube-scheduler\", \"etcd\", \"kubeletconfiguration\". ` +\n\t\t`\"patchtype\" can be one of \"strategic\", \"merge\" or \"json\" and they match the patch formats ` +\n\t\t`supported by kubectl. The default \"patchtype\" is \"strategic\". \"extension\" must be either ` +\n\t\t`\"json\" or \"yaml\". \"suffix\" is an optional string that can be used to determine ` +\n\t\t`which patches are applied first alpha-numerically.`\n\tfs.StringVar(patchesDir, Patches, *patchesDir, usage)\n}","line":{"from":94,"to":105}} {"id":100000599,"name":"NewBootstrapTokenOptions","signature":"func NewBootstrapTokenOptions() *BootstrapTokenOptions","file":"cmd/kubeadm/app/cmd/options/token.go","code":"// NewBootstrapTokenOptions creates a new BootstrapTokenOptions object with the default values\nfunc NewBootstrapTokenOptions() *BootstrapTokenOptions {\n\tbto := \u0026BootstrapTokenOptions{\u0026bootstraptokenv1.BootstrapToken{}, \"\"}\n\tkubeadmapiv1.SetDefaults_BootstrapToken(bto.BootstrapToken)\n\treturn bto\n}","line":{"from":32,"to":37}} {"id":100000600,"name":"AddTokenFlag","signature":"func (bto *BootstrapTokenOptions) AddTokenFlag(fs *pflag.FlagSet)","file":"cmd/kubeadm/app/cmd/options/token.go","code":"// AddTokenFlag adds the --token flag to the given flagset\nfunc (bto *BootstrapTokenOptions) AddTokenFlag(fs *pflag.FlagSet) {\n\tfs.StringVar(\n\t\t\u0026bto.TokenStr, TokenStr, \"\",\n\t\t\"The token to use for establishing bidirectional trust between nodes and control-plane nodes. The format is [a-z0-9]{6}\\\\.[a-z0-9]{16} - e.g. abcdef.0123456789abcdef\",\n\t)\n}","line":{"from":47,"to":53}} {"id":100000601,"name":"AddTTLFlag","signature":"func (bto *BootstrapTokenOptions) AddTTLFlag(fs *pflag.FlagSet)","file":"cmd/kubeadm/app/cmd/options/token.go","code":"// AddTTLFlag adds the --token-ttl flag to the given flagset\nfunc (bto *BootstrapTokenOptions) AddTTLFlag(fs *pflag.FlagSet) {\n\tbto.AddTTLFlagWithName(fs, TokenTTL)\n}","line":{"from":55,"to":58}} {"id":100000602,"name":"AddTTLFlagWithName","signature":"func (bto *BootstrapTokenOptions) AddTTLFlagWithName(fs *pflag.FlagSet, flagName string)","file":"cmd/kubeadm/app/cmd/options/token.go","code":"// AddTTLFlagWithName adds the --token-ttl flag with a custom flag name given flagset\nfunc (bto *BootstrapTokenOptions) AddTTLFlagWithName(fs *pflag.FlagSet, flagName string) {\n\tfs.DurationVar(\n\t\t\u0026bto.TTL.Duration, flagName, bto.TTL.Duration,\n\t\t\"The duration before the token is automatically deleted (e.g. 1s, 2m, 3h). If set to '0', the token will never expire\",\n\t)\n}","line":{"from":60,"to":66}} {"id":100000603,"name":"AddUsagesFlag","signature":"func (bto *BootstrapTokenOptions) AddUsagesFlag(fs *pflag.FlagSet)","file":"cmd/kubeadm/app/cmd/options/token.go","code":"// AddUsagesFlag adds the --usages flag to the given flagset\nfunc (bto *BootstrapTokenOptions) AddUsagesFlag(fs *pflag.FlagSet) {\n\tfs.StringSliceVar(\n\t\t\u0026bto.Usages, TokenUsages, bto.Usages,\n\t\tfmt.Sprintf(\"Describes the ways in which this token can be used. You can pass --usages multiple times or provide a comma separated list of options. Valid options: [%s]\", strings.Join(kubeadmconstants.DefaultTokenUsages, \",\")),\n\t)\n}","line":{"from":68,"to":74}} {"id":100000604,"name":"AddGroupsFlag","signature":"func (bto *BootstrapTokenOptions) AddGroupsFlag(fs *pflag.FlagSet)","file":"cmd/kubeadm/app/cmd/options/token.go","code":"// AddGroupsFlag adds the --groups flag to the given flagset\nfunc (bto *BootstrapTokenOptions) AddGroupsFlag(fs *pflag.FlagSet) {\n\tfs.StringSliceVar(\n\t\t\u0026bto.Groups, TokenGroups, bto.Groups,\n\t\tfmt.Sprintf(\"Extra groups that this token will authenticate as when used for authentication. Must match %q\", bootstrapapi.BootstrapGroupPattern),\n\t)\n}","line":{"from":76,"to":82}} {"id":100000605,"name":"AddDescriptionFlag","signature":"func (bto *BootstrapTokenOptions) AddDescriptionFlag(fs *pflag.FlagSet)","file":"cmd/kubeadm/app/cmd/options/token.go","code":"// AddDescriptionFlag adds the --description flag to the given flagset\nfunc (bto *BootstrapTokenOptions) AddDescriptionFlag(fs *pflag.FlagSet) {\n\tfs.StringVar(\n\t\t\u0026bto.Description, TokenDescription, bto.Description,\n\t\t\"A human friendly description of how this token is used.\",\n\t)\n}","line":{"from":84,"to":90}} {"id":100000606,"name":"ApplyTo","signature":"func (bto *BootstrapTokenOptions) ApplyTo(cfg *kubeadmapiv1.InitConfiguration) error","file":"cmd/kubeadm/app/cmd/options/token.go","code":"// ApplyTo applies the values set internally in the BootstrapTokenOptions object to a InitConfiguration object at runtime\n// If --token was specified in the CLI (as a string), it's parsed and validated before it's added to the BootstrapToken object.\nfunc (bto *BootstrapTokenOptions) ApplyTo(cfg *kubeadmapiv1.InitConfiguration) error {\n\tif len(bto.TokenStr) \u003e 0 {\n\t\tvar err error\n\t\tbto.Token, err = bootstraptokenv1.NewBootstrapTokenString(bto.TokenStr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Set the token specified by the flags as the first and only token to create in case --config is not specified\n\tcfg.BootstrapTokens = []bootstraptokenv1.BootstrapToken{*bto.BootstrapToken}\n\treturn nil\n}","line":{"from":92,"to":106}} {"id":100000607,"name":"NewAddonPhase","signature":"func NewAddonPhase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/init/addons.go","code":"// NewAddonPhase returns the addon Cobra command\nfunc NewAddonPhase() workflow.Phase {\n\tdnsLocalFlags := pflag.NewFlagSet(options.PrintManifest, pflag.ContinueOnError)\n\tdnsLocalFlags.BoolVar(\u0026printManifest, options.PrintManifest, printManifest, \"Print the addon manifests to STDOUT instead of installing them\")\n\n\tproxyLocalFlags := pflag.NewFlagSet(options.PrintManifest, pflag.ContinueOnError)\n\tproxyLocalFlags.BoolVar(\u0026printManifest, options.PrintManifest, printManifest, \"Print the addon manifests to STDOUT instead of installing them\")\n\n\treturn workflow.Phase{\n\t\tName: \"addon\",\n\t\tShort: \"Install required addons for passing conformance tests\",\n\t\tLong: cmdutil.MacroCommandLongDescription,\n\t\tPhases: []workflow.Phase{\n\t\t\t{\n\t\t\t\tName: \"all\",\n\t\t\t\tShort: \"Install all the addons\",\n\t\t\t\tInheritFlags: getAddonPhaseFlags(\"all\"),\n\t\t\t\tRunAllSiblings: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"coredns\",\n\t\t\t\tShort: \"Install the CoreDNS addon to a Kubernetes cluster\",\n\t\t\t\tLong: coreDNSAddonLongDesc,\n\t\t\t\tInheritFlags: getAddonPhaseFlags(\"coredns\"),\n\t\t\t\tRun: runCoreDNSAddon,\n\t\t\t\tLocalFlags: dnsLocalFlags,\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"kube-proxy\",\n\t\t\t\tShort: \"Install the kube-proxy addon to a Kubernetes cluster\",\n\t\t\t\tLong: kubeProxyAddonLongDesc,\n\t\t\t\tInheritFlags: getAddonPhaseFlags(\"kube-proxy\"),\n\t\t\t\tRun: runKubeProxyAddon,\n\t\t\t\tLocalFlags: proxyLocalFlags,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":48,"to":85}} {"id":100000608,"name":"getInitData","signature":"func getInitData(c workflow.RunData) (*kubeadmapi.InitConfiguration, clientset.Interface, io.Writer, error)","file":"cmd/kubeadm/app/cmd/phases/init/addons.go","code":"func getInitData(c workflow.RunData) (*kubeadmapi.InitConfiguration, clientset.Interface, io.Writer, error) {\n\tdata, ok := c.(InitData)\n\tif !ok {\n\t\treturn nil, nil, nil, errors.New(\"addon phase invoked with an invalid data struct\")\n\t}\n\tcfg := data.Cfg()\n\tvar client clientset.Interface\n\tvar err error\n\tif !printManifest {\n\t\tclient, err = data.Client()\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t}\n\n\tout := data.OutputWriter()\n\treturn cfg, client, out, err\n}","line":{"from":87,"to":104}} {"id":100000609,"name":"runCoreDNSAddon","signature":"func runCoreDNSAddon(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/init/addons.go","code":"// runCoreDNSAddon installs CoreDNS addon to a Kubernetes cluster\nfunc runCoreDNSAddon(c workflow.RunData) error {\n\tcfg, client, out, err := getInitData(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn dnsaddon.EnsureDNSAddon(\u0026cfg.ClusterConfiguration, client, out, printManifest)\n}","line":{"from":106,"to":113}} {"id":100000610,"name":"runKubeProxyAddon","signature":"func runKubeProxyAddon(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/init/addons.go","code":"// runKubeProxyAddon installs KubeProxy addon to a Kubernetes cluster\nfunc runKubeProxyAddon(c workflow.RunData) error {\n\tcfg, client, out, err := getInitData(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn proxyaddon.EnsureProxyAddon(\u0026cfg.ClusterConfiguration, \u0026cfg.LocalAPIEndpoint, client, out, printManifest)\n}","line":{"from":115,"to":122}} {"id":100000611,"name":"getAddonPhaseFlags","signature":"func getAddonPhaseFlags(name string) []string","file":"cmd/kubeadm/app/cmd/phases/init/addons.go","code":"func getAddonPhaseFlags(name string) []string {\n\tflags := []string{\n\t\toptions.CfgPath,\n\t\toptions.KubeconfigPath,\n\t\toptions.KubernetesVersion,\n\t\toptions.ImageRepository,\n\t\toptions.DryRun,\n\t}\n\tif name == \"all\" || name == \"kube-proxy\" {\n\t\tflags = append(flags,\n\t\t\toptions.APIServerAdvertiseAddress,\n\t\t\toptions.ControlPlaneEndpoint,\n\t\t\toptions.APIServerBindPort,\n\t\t\toptions.NetworkingPodSubnet,\n\t\t)\n\t}\n\tif name == \"all\" || name == \"coredns\" {\n\t\tflags = append(flags,\n\t\t\toptions.FeatureGatesString,\n\t\t\toptions.NetworkingDNSDomain,\n\t\t\toptions.NetworkingServiceSubnet,\n\t\t)\n\t}\n\treturn flags\n}","line":{"from":124,"to":148}} {"id":100000612,"name":"NewBootstrapTokenPhase","signature":"func NewBootstrapTokenPhase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/init/bootstraptoken.go","code":"// NewBootstrapTokenPhase returns the phase to bootstrapToken\nfunc NewBootstrapTokenPhase() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"bootstrap-token\",\n\t\tAliases: []string{\"bootstraptoken\"},\n\t\tShort: \"Generates bootstrap tokens used to join a node to a cluster\",\n\t\tExample: bootstrapTokenExamples,\n\t\tLong: bootstrapTokenLongDesc,\n\t\tInheritFlags: []string{\n\t\t\toptions.CfgPath,\n\t\t\toptions.KubeconfigPath,\n\t\t\toptions.SkipTokenPrint,\n\t\t\toptions.DryRun,\n\t\t},\n\t\tRun: runBootstrapToken,\n\t}\n}","line":{"from":47,"to":63}} {"id":100000613,"name":"runBootstrapToken","signature":"func runBootstrapToken(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/init/bootstraptoken.go","code":"func runBootstrapToken(c workflow.RunData) error {\n\tdata, ok := c.(InitData)\n\tif !ok {\n\t\treturn errors.New(\"bootstrap-token phase invoked with an invalid data struct\")\n\t}\n\n\tclient, err := data.Client()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !data.SkipTokenPrint() {\n\t\ttokens := data.Tokens()\n\t\tif len(tokens) == 1 {\n\t\t\tfmt.Printf(\"[bootstrap-token] Using token: %s\\n\", tokens[0])\n\t\t} else if len(tokens) \u003e 1 {\n\t\t\tfmt.Printf(\"[bootstrap-token] Using tokens: %v\\n\", tokens)\n\t\t}\n\t}\n\n\tfmt.Println(\"[bootstrap-token] Configuring bootstrap tokens, cluster-info ConfigMap, RBAC Roles\")\n\t// Create the default node bootstrap token\n\tif err := nodebootstraptokenphase.UpdateOrCreateTokens(client, false, data.Cfg().BootstrapTokens); err != nil {\n\t\treturn errors.Wrap(err, \"error updating or creating token\")\n\t}\n\t// Create RBAC rules that makes the bootstrap tokens able to get nodes\n\tif err := nodebootstraptokenphase.AllowBoostrapTokensToGetNodes(client); err != nil {\n\t\treturn errors.Wrap(err, \"error allowing bootstrap tokens to get Nodes\")\n\t}\n\t// Create RBAC rules that makes the bootstrap tokens able to post CSRs\n\tif err := nodebootstraptokenphase.AllowBootstrapTokensToPostCSRs(client); err != nil {\n\t\treturn errors.Wrap(err, \"error allowing bootstrap tokens to post CSRs\")\n\t}\n\t// Create RBAC rules that makes the bootstrap tokens able to get their CSRs approved automatically\n\tif err := nodebootstraptokenphase.AutoApproveNodeBootstrapTokens(client); err != nil {\n\t\treturn errors.Wrap(err, \"error auto-approving node bootstrap tokens\")\n\t}\n\n\t// Create/update RBAC rules that makes the nodes to rotate certificates and get their CSRs approved automatically\n\tif err := nodebootstraptokenphase.AutoApproveNodeCertificateRotation(client); err != nil {\n\t\treturn err\n\t}\n\n\t// Create the cluster-info ConfigMap with the associated RBAC rules\n\tif err := clusterinfophase.CreateBootstrapConfigMapIfNotExists(client, data.KubeConfigPath()); err != nil {\n\t\treturn errors.Wrap(err, \"error creating bootstrap ConfigMap\")\n\t}\n\tif err := clusterinfophase.CreateClusterInfoRBACRules(client); err != nil {\n\t\treturn errors.Wrap(err, \"error creating clusterinfo RBAC rules\")\n\t}\n\treturn nil\n}","line":{"from":65,"to":116}} {"id":100000614,"name":"NewCertsPhase","signature":"func NewCertsPhase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/init/certs.go","code":"// NewCertsPhase returns the phase for the certs\nfunc NewCertsPhase() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"certs\",\n\t\tShort: \"Certificate generation\",\n\t\tPhases: newCertSubPhases(),\n\t\tRun: runCerts,\n\t\tLong: cmdutil.MacroCommandLongDescription,\n\t}\n}","line":{"from":52,"to":61}} {"id":100000615,"name":"newCertSubPhases","signature":"func newCertSubPhases() []workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/init/certs.go","code":"// newCertSubPhases returns sub phases for certs phase\nfunc newCertSubPhases() []workflow.Phase {\n\tsubPhases := []workflow.Phase{}\n\n\t// All subphase\n\tallPhase := workflow.Phase{\n\t\tName: \"all\",\n\t\tShort: \"Generate all certificates\",\n\t\tInheritFlags: getCertPhaseFlags(\"all\"),\n\t\tRunAllSiblings: true,\n\t}\n\n\tsubPhases = append(subPhases, allPhase)\n\n\t// This loop assumes that GetDefaultCertList() always returns a list of\n\t// certificate that is preceded by the CAs that sign them.\n\tvar lastCACert *certsphase.KubeadmCert\n\tfor _, cert := range certsphase.GetDefaultCertList() {\n\t\tvar phase workflow.Phase\n\t\tif cert.CAName == \"\" {\n\t\t\tphase = newCertSubPhase(cert, runCAPhase(cert))\n\t\t\tlastCACert = cert\n\t\t} else {\n\t\t\tphase = newCertSubPhase(cert, runCertPhase(cert, lastCACert))\n\t\t}\n\t\tsubPhases = append(subPhases, phase)\n\t}\n\n\t// SA creates the private/public key pair, which doesn't use x509 at all\n\tsaPhase := workflow.Phase{\n\t\tName: \"sa\",\n\t\tShort: \"Generate a private key for signing service account tokens along with its public key\",\n\t\tLong: saKeyLongDesc,\n\t\tRun: runCertsSa,\n\t\tInheritFlags: []string{options.CertificatesDir},\n\t}\n\n\tsubPhases = append(subPhases, saPhase)\n\n\treturn subPhases\n}","line":{"from":63,"to":103}} {"id":100000616,"name":"newCertSubPhase","signature":"func newCertSubPhase(certSpec *certsphase.KubeadmCert, run func(c workflow.RunData) error) workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/init/certs.go","code":"func newCertSubPhase(certSpec *certsphase.KubeadmCert, run func(c workflow.RunData) error) workflow.Phase {\n\tphase := workflow.Phase{\n\t\tName: certSpec.Name,\n\t\tShort: fmt.Sprintf(\"Generate the %s\", certSpec.LongName),\n\t\tLong: fmt.Sprintf(\n\t\t\tgenericLongDesc,\n\t\t\tcertSpec.LongName,\n\t\t\tcertSpec.BaseName,\n\t\t\tgetSANDescription(certSpec),\n\t\t),\n\t\tRun: run,\n\t\tInheritFlags: getCertPhaseFlags(certSpec.Name),\n\t}\n\treturn phase\n}","line":{"from":105,"to":119}} {"id":100000617,"name":"getCertPhaseFlags","signature":"func getCertPhaseFlags(name string) []string","file":"cmd/kubeadm/app/cmd/phases/init/certs.go","code":"func getCertPhaseFlags(name string) []string {\n\tflags := []string{\n\t\toptions.CertificatesDir,\n\t\toptions.CfgPath,\n\t\toptions.KubernetesVersion,\n\t\toptions.DryRun,\n\t}\n\tif name == \"all\" || name == \"apiserver\" {\n\t\tflags = append(flags,\n\t\t\toptions.APIServerAdvertiseAddress,\n\t\t\toptions.ControlPlaneEndpoint,\n\t\t\toptions.APIServerCertSANs,\n\t\t\toptions.NetworkingDNSDomain,\n\t\t\toptions.NetworkingServiceSubnet,\n\t\t)\n\t}\n\treturn flags\n}","line":{"from":121,"to":138}} {"id":100000618,"name":"getSANDescription","signature":"func getSANDescription(certSpec *certsphase.KubeadmCert) string","file":"cmd/kubeadm/app/cmd/phases/init/certs.go","code":"func getSANDescription(certSpec *certsphase.KubeadmCert) string {\n\t//Defaulted config we will use to get SAN certs\n\tdefaultConfig := cmdutil.DefaultInitConfiguration()\n\t// GetAPIServerAltNames errors without an AdvertiseAddress; this is as good as any.\n\tdefaultConfig.LocalAPIEndpoint = kubeadmapiv1.APIEndpoint{\n\t\tAdvertiseAddress: \"127.0.0.1\",\n\t}\n\n\tdefaultInternalConfig := \u0026kubeadmapi.InitConfiguration{}\n\n\tkubeadmscheme.Scheme.Default(defaultConfig)\n\tif err := kubeadmscheme.Scheme.Convert(defaultConfig, defaultInternalConfig, nil); err != nil {\n\t\treturn \"\"\n\t}\n\n\tcertConfig, err := certSpec.GetConfig(defaultInternalConfig)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\tif len(certConfig.AltNames.DNSNames) == 0 \u0026\u0026 len(certConfig.AltNames.IPs) == 0 {\n\t\treturn \"\"\n\t}\n\t// This mutates the certConfig, but we're throwing it after we construct the command anyway\n\tsans := []string{}\n\n\tfor _, dnsName := range certConfig.AltNames.DNSNames {\n\t\tif dnsName != \"\" {\n\t\t\tsans = append(sans, dnsName)\n\t\t}\n\t}\n\n\tfor _, ip := range certConfig.AltNames.IPs {\n\t\tsans = append(sans, ip.String())\n\t}\n\treturn fmt.Sprintf(\"\\n\\nDefault SANs are %s\", strings.Join(sans, \", \"))\n}","line":{"from":140,"to":176}} {"id":100000619,"name":"runCertsSa","signature":"func runCertsSa(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/init/certs.go","code":"func runCertsSa(c workflow.RunData) error {\n\tdata, ok := c.(InitData)\n\tif !ok {\n\t\treturn errors.New(\"certs phase invoked with an invalid data struct\")\n\t}\n\n\t// if external CA mode, skip service account key generation\n\tif data.ExternalCA() {\n\t\tfmt.Printf(\"[certs] Using existing sa keys\\n\")\n\t\treturn nil\n\t}\n\n\t// create the new service account key (or use existing)\n\treturn certsphase.CreateServiceAccountKeyAndPublicKeyFiles(data.CertificateWriteDir(), data.Cfg().ClusterConfiguration.PublicKeyAlgorithm())\n}","line":{"from":178,"to":192}} {"id":100000620,"name":"runCerts","signature":"func runCerts(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/init/certs.go","code":"func runCerts(c workflow.RunData) error {\n\tdata, ok := c.(InitData)\n\tif !ok {\n\t\treturn errors.New(\"certs phase invoked with an invalid data struct\")\n\t}\n\n\tfmt.Printf(\"[certs] Using certificateDir folder %q\\n\", data.CertificateWriteDir())\n\treturn nil\n}","line":{"from":194,"to":202}} {"id":100000621,"name":"runCAPhase","signature":"func runCAPhase(ca *certsphase.KubeadmCert) func(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/init/certs.go","code":"func runCAPhase(ca *certsphase.KubeadmCert) func(c workflow.RunData) error {\n\treturn func(c workflow.RunData) error {\n\t\tdata, ok := c.(InitData)\n\t\tif !ok {\n\t\t\treturn errors.New(\"certs phase invoked with an invalid data struct\")\n\t\t}\n\n\t\t// if using external etcd, skips etcd certificate authority generation\n\t\tif data.Cfg().Etcd.External != nil \u0026\u0026 ca.Name == \"etcd-ca\" {\n\t\t\tfmt.Printf(\"[certs] External etcd mode: Skipping %s certificate authority generation\\n\", ca.BaseName)\n\t\t\treturn nil\n\t\t}\n\n\t\tif cert, err := pkiutil.TryLoadCertFromDisk(data.CertificateDir(), ca.BaseName); err == nil {\n\t\t\tcertsphase.CheckCertificatePeriodValidity(ca.BaseName, cert)\n\n\t\t\t// If CA Cert existed while dryrun, copy CA Cert to dryrun dir for later use\n\t\t\tif data.DryRun() {\n\t\t\t\terr := kubeadmutil.CopyFile(filepath.Join(data.CertificateDir(), kubeadmconstants.CACertName), filepath.Join(data.CertificateWriteDir(), kubeadmconstants.CACertName))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"could not copy %s to dry run directory %s\", kubeadmconstants.CACertName, data.CertificateWriteDir())\n\t\t\t\t}\n\t\t\t}\n\t\t\tif _, err := pkiutil.TryLoadKeyFromDisk(data.CertificateDir(), ca.BaseName); err == nil {\n\t\t\t\t// If CA Key existed while dryrun, copy CA Key to dryrun dir for later use\n\t\t\t\tif data.DryRun() {\n\t\t\t\t\terr := kubeadmutil.CopyFile(filepath.Join(data.CertificateDir(), kubeadmconstants.CAKeyName), filepath.Join(data.CertificateWriteDir(), kubeadmconstants.CAKeyName))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn errors.Wrapf(err, \"could not copy %s to dry run directory %s\", kubeadmconstants.CAKeyName, data.CertificateWriteDir())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\"[certs] Using existing %s certificate authority\\n\", ca.BaseName)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tfmt.Printf(\"[certs] Using existing %s keyless certificate authority\\n\", ca.BaseName)\n\t\t\treturn nil\n\t\t}\n\n\t\t// if dryrunning, write certificates authority to a temporary folder (and defer restore to the path originally specified by the user)\n\t\tcfg := data.Cfg()\n\t\tcfg.CertificatesDir = data.CertificateWriteDir()\n\t\tdefer func() { cfg.CertificatesDir = data.CertificateDir() }()\n\n\t\t// create the new certificate authority (or use existing)\n\t\treturn certsphase.CreateCACertAndKeyFiles(ca, cfg)\n\t}\n}","line":{"from":204,"to":250}} {"id":100000622,"name":"runCertPhase","signature":"func runCertPhase(cert *certsphase.KubeadmCert, caCert *certsphase.KubeadmCert) func(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/init/certs.go","code":"func runCertPhase(cert *certsphase.KubeadmCert, caCert *certsphase.KubeadmCert) func(c workflow.RunData) error {\n\treturn func(c workflow.RunData) error {\n\t\tdata, ok := c.(InitData)\n\t\tif !ok {\n\t\t\treturn errors.New(\"certs phase invoked with an invalid data struct\")\n\t\t}\n\n\t\t// if using external etcd, skips etcd certificates generation\n\t\tif data.Cfg().Etcd.External != nil \u0026\u0026 cert.CAName == \"etcd-ca\" {\n\t\t\tfmt.Printf(\"[certs] External etcd mode: Skipping %s certificate generation\\n\", cert.BaseName)\n\t\t\treturn nil\n\t\t}\n\n\t\tif certData, intermediates, err := pkiutil.TryLoadCertChainFromDisk(data.CertificateDir(), cert.BaseName); err == nil {\n\t\t\tcertsphase.CheckCertificatePeriodValidity(cert.BaseName, certData)\n\n\t\t\tcaCertData, err := pkiutil.TryLoadCertFromDisk(data.CertificateDir(), caCert.BaseName)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"couldn't load CA certificate %s\", caCert.Name)\n\t\t\t}\n\n\t\t\tcertsphase.CheckCertificatePeriodValidity(caCert.BaseName, caCertData)\n\n\t\t\tif err := pkiutil.VerifyCertChain(certData, intermediates, caCertData); err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"[certs] certificate %s not signed by CA certificate %s\", cert.BaseName, caCert.BaseName)\n\t\t\t}\n\n\t\t\tfmt.Printf(\"[certs] Using existing %s certificate and key on disk\\n\", cert.BaseName)\n\t\t\treturn nil\n\t\t}\n\n\t\t// if dryrunning, write certificates to a temporary folder (and defer restore to the path originally specified by the user)\n\t\tcfg := data.Cfg()\n\t\tcfg.CertificatesDir = data.CertificateWriteDir()\n\t\tdefer func() { cfg.CertificatesDir = data.CertificateDir() }()\n\n\t\t// create the new certificate (or use existing)\n\t\treturn certsphase.CreateCertAndKeyFilesWithCA(cert, caCert, cfg)\n\t}\n}","line":{"from":252,"to":291}} {"id":100000623,"name":"getPhaseDescription","signature":"func getPhaseDescription(component string) string","file":"cmd/kubeadm/app/cmd/phases/init/controlplane.go","code":"func getPhaseDescription(component string) string {\n\treturn fmt.Sprintf(\"Generates the %s static Pod manifest\", component)\n}","line":{"from":60,"to":62}} {"id":100000624,"name":"NewControlPlanePhase","signature":"func NewControlPlanePhase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/init/controlplane.go","code":"// NewControlPlanePhase creates a kubeadm workflow phase that implements bootstrapping the control plane.\nfunc NewControlPlanePhase() workflow.Phase {\n\tphase := workflow.Phase{\n\t\tName: \"control-plane\",\n\t\tShort: \"Generate all static Pod manifest files necessary to establish the control plane\",\n\t\tLong: cmdutil.MacroCommandLongDescription,\n\t\tPhases: []workflow.Phase{\n\t\t\t{\n\t\t\t\tName: \"all\",\n\t\t\t\tShort: \"Generate all static Pod manifest files\",\n\t\t\t\tInheritFlags: getControlPlanePhaseFlags(\"all\"),\n\t\t\t\tExample: controlPlaneExample,\n\t\t\t\tRunAllSiblings: true,\n\t\t\t},\n\t\t\tnewControlPlaneSubphase(kubeadmconstants.KubeAPIServer),\n\t\t\tnewControlPlaneSubphase(kubeadmconstants.KubeControllerManager),\n\t\t\tnewControlPlaneSubphase(kubeadmconstants.KubeScheduler),\n\t\t},\n\t\tRun: runControlPlanePhase,\n\t}\n\treturn phase\n}","line":{"from":64,"to":85}} {"id":100000625,"name":"newControlPlaneSubphase","signature":"func newControlPlaneSubphase(component string) workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/init/controlplane.go","code":"func newControlPlaneSubphase(component string) workflow.Phase {\n\tphase := workflow.Phase{\n\t\tName: controlPlanePhaseProperties[component].name,\n\t\tShort: controlPlanePhaseProperties[component].short,\n\t\tRun: runControlPlaneSubphase(component),\n\t\tInheritFlags: getControlPlanePhaseFlags(component),\n\t}\n\treturn phase\n}","line":{"from":87,"to":95}} {"id":100000626,"name":"getControlPlanePhaseFlags","signature":"func getControlPlanePhaseFlags(name string) []string","file":"cmd/kubeadm/app/cmd/phases/init/controlplane.go","code":"func getControlPlanePhaseFlags(name string) []string {\n\tflags := []string{\n\t\toptions.CfgPath,\n\t\toptions.CertificatesDir,\n\t\toptions.KubernetesVersion,\n\t\toptions.ImageRepository,\n\t\toptions.Patches,\n\t\toptions.DryRun,\n\t}\n\tif name == \"all\" || name == kubeadmconstants.KubeAPIServer {\n\t\tflags = append(flags,\n\t\t\toptions.APIServerAdvertiseAddress,\n\t\t\toptions.ControlPlaneEndpoint,\n\t\t\toptions.APIServerBindPort,\n\t\t\toptions.APIServerExtraArgs,\n\t\t\toptions.FeatureGatesString,\n\t\t\toptions.NetworkingServiceSubnet,\n\t\t)\n\t}\n\tif name == \"all\" || name == kubeadmconstants.KubeControllerManager {\n\t\tflags = append(flags,\n\t\t\toptions.ControllerManagerExtraArgs,\n\t\t\toptions.NetworkingPodSubnet,\n\t\t)\n\t}\n\tif name == \"all\" || name == kubeadmconstants.KubeScheduler {\n\t\tflags = append(flags,\n\t\t\toptions.SchedulerExtraArgs,\n\t\t)\n\t}\n\treturn flags\n}","line":{"from":97,"to":128}} {"id":100000627,"name":"runControlPlanePhase","signature":"func runControlPlanePhase(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/init/controlplane.go","code":"func runControlPlanePhase(c workflow.RunData) error {\n\tdata, ok := c.(InitData)\n\tif !ok {\n\t\treturn errors.New(\"control-plane phase invoked with an invalid data struct\")\n\t}\n\n\tfmt.Printf(\"[control-plane] Using manifest folder %q\\n\", data.ManifestDir())\n\treturn nil\n}","line":{"from":130,"to":138}} {"id":100000628,"name":"runControlPlaneSubphase","signature":"func runControlPlaneSubphase(component string) func(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/init/controlplane.go","code":"func runControlPlaneSubphase(component string) func(c workflow.RunData) error {\n\treturn func(c workflow.RunData) error {\n\t\tdata, ok := c.(InitData)\n\t\tif !ok {\n\t\t\treturn errors.New(\"control-plane phase invoked with an invalid data struct\")\n\t\t}\n\t\tcfg := data.Cfg()\n\n\t\tfmt.Printf(\"[control-plane] Creating static Pod manifest for %q\\n\", component)\n\t\treturn controlplane.CreateStaticPodFiles(data.ManifestDir(), data.PatchesDir(), \u0026cfg.ClusterConfiguration, \u0026cfg.LocalAPIEndpoint, data.DryRun(), component)\n\t}\n}","line":{"from":140,"to":151}} {"id":100000629,"name":"NewEtcdPhase","signature":"func NewEtcdPhase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/init/etcd.go","code":"// NewEtcdPhase creates a kubeadm workflow phase that implements handling of etcd.\nfunc NewEtcdPhase() workflow.Phase {\n\tphase := workflow.Phase{\n\t\tName: \"etcd\",\n\t\tShort: \"Generate static Pod manifest file for local etcd\",\n\t\tLong: cmdutil.MacroCommandLongDescription,\n\t\tPhases: []workflow.Phase{\n\t\t\tnewEtcdLocalSubPhase(),\n\t\t},\n\t}\n\treturn phase\n}","line":{"from":45,"to":56}} {"id":100000630,"name":"newEtcdLocalSubPhase","signature":"func newEtcdLocalSubPhase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/init/etcd.go","code":"func newEtcdLocalSubPhase() workflow.Phase {\n\tphase := workflow.Phase{\n\t\tName: \"local\",\n\t\tShort: \"Generate the static Pod manifest file for a local, single-node local etcd instance\",\n\t\tExample: etcdLocalExample,\n\t\tRun: runEtcdPhaseLocal(),\n\t\tInheritFlags: getEtcdPhaseFlags(),\n\t}\n\treturn phase\n}","line":{"from":58,"to":67}} {"id":100000631,"name":"getEtcdPhaseFlags","signature":"func getEtcdPhaseFlags() []string","file":"cmd/kubeadm/app/cmd/phases/init/etcd.go","code":"func getEtcdPhaseFlags() []string {\n\tflags := []string{\n\t\toptions.CertificatesDir,\n\t\toptions.CfgPath,\n\t\toptions.ImageRepository,\n\t\toptions.Patches,\n\t\toptions.DryRun,\n\t}\n\treturn flags\n}","line":{"from":69,"to":78}} {"id":100000632,"name":"runEtcdPhaseLocal","signature":"func runEtcdPhaseLocal() func(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/init/etcd.go","code":"func runEtcdPhaseLocal() func(c workflow.RunData) error {\n\treturn func(c workflow.RunData) error {\n\t\tdata, ok := c.(InitData)\n\t\tif !ok {\n\t\t\treturn errors.New(\"etcd phase invoked with an invalid data struct\")\n\t\t}\n\t\tcfg := data.Cfg()\n\n\t\t// Add etcd static pod spec only if external etcd is not configured\n\t\tif cfg.Etcd.External == nil {\n\t\t\t// creates target folder if doesn't exist already\n\t\t\tif !data.DryRun() {\n\t\t\t\t// Create the etcd data directory\n\t\t\t\tif err := etcdutil.CreateDataDirectory(cfg.Etcd.Local.DataDir); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"[etcd] Would ensure that %q directory is present\\n\", cfg.Etcd.Local.DataDir)\n\t\t\t}\n\t\t\tfmt.Printf(\"[etcd] Creating static Pod manifest for local etcd in %q\\n\", data.ManifestDir())\n\t\t\tif err := etcdphase.CreateLocalEtcdStaticPodManifestFile(data.ManifestDir(), data.PatchesDir(), cfg.NodeRegistration.Name, \u0026cfg.ClusterConfiguration, \u0026cfg.LocalAPIEndpoint, data.DryRun()); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"error creating local etcd static pod manifest file\")\n\t\t\t}\n\t\t} else {\n\t\t\tklog.V(1).Infoln(\"[etcd] External etcd mode. Skipping the creation of a manifest for local etcd\")\n\t\t}\n\t\treturn nil\n\t}\n}","line":{"from":80,"to":108}} {"id":100000633,"name":"NewKubeConfigPhase","signature":"func NewKubeConfigPhase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/init/kubeconfig.go","code":"// NewKubeConfigPhase creates a kubeadm workflow phase that creates all kubeconfig files necessary to establish the control plane and the admin kubeconfig file.\nfunc NewKubeConfigPhase() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"kubeconfig\",\n\t\tShort: \"Generate all kubeconfig files necessary to establish the control plane and the admin kubeconfig file\",\n\t\tLong: cmdutil.MacroCommandLongDescription,\n\t\tPhases: []workflow.Phase{\n\t\t\t{\n\t\t\t\tName: \"all\",\n\t\t\t\tShort: \"Generate all kubeconfig files\",\n\t\t\t\tInheritFlags: getKubeConfigPhaseFlags(\"all\"),\n\t\t\t\tRunAllSiblings: true,\n\t\t\t},\n\t\t\tNewKubeConfigFilePhase(kubeadmconstants.AdminKubeConfigFileName),\n\t\t\tNewKubeConfigFilePhase(kubeadmconstants.KubeletKubeConfigFileName),\n\t\t\tNewKubeConfigFilePhase(kubeadmconstants.ControllerManagerKubeConfigFileName),\n\t\t\tNewKubeConfigFilePhase(kubeadmconstants.SchedulerKubeConfigFileName),\n\t\t},\n\t\tRun: runKubeConfig,\n\t}\n}","line":{"from":66,"to":86}} {"id":100000634,"name":"NewKubeConfigFilePhase","signature":"func NewKubeConfigFilePhase(kubeConfigFileName string) workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/init/kubeconfig.go","code":"// NewKubeConfigFilePhase creates a kubeadm workflow phase that creates a kubeconfig file.\nfunc NewKubeConfigFilePhase(kubeConfigFileName string) workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: kubeconfigFilePhaseProperties[kubeConfigFileName].name,\n\t\tShort: kubeconfigFilePhaseProperties[kubeConfigFileName].short,\n\t\tLong: fmt.Sprintf(kubeconfigFilePhaseProperties[kubeConfigFileName].long, kubeConfigFileName),\n\t\tRun: runKubeConfigFile(kubeConfigFileName),\n\t\tInheritFlags: getKubeConfigPhaseFlags(kubeConfigFileName),\n\t}\n}","line":{"from":88,"to":97}} {"id":100000635,"name":"getKubeConfigPhaseFlags","signature":"func getKubeConfigPhaseFlags(name string) []string","file":"cmd/kubeadm/app/cmd/phases/init/kubeconfig.go","code":"func getKubeConfigPhaseFlags(name string) []string {\n\tflags := []string{\n\t\toptions.APIServerAdvertiseAddress,\n\t\toptions.ControlPlaneEndpoint,\n\t\toptions.APIServerBindPort,\n\t\toptions.CertificatesDir,\n\t\toptions.CfgPath,\n\t\toptions.KubeconfigDir,\n\t\toptions.KubernetesVersion,\n\t\toptions.DryRun,\n\t}\n\tif name == \"all\" || name == kubeadmconstants.KubeletKubeConfigFileName {\n\t\tflags = append(flags,\n\t\t\toptions.NodeName,\n\t\t)\n\t}\n\treturn flags\n}","line":{"from":99,"to":116}} {"id":100000636,"name":"runKubeConfig","signature":"func runKubeConfig(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/init/kubeconfig.go","code":"func runKubeConfig(c workflow.RunData) error {\n\tdata, ok := c.(InitData)\n\tif !ok {\n\t\treturn errors.New(\"kubeconfig phase invoked with an invalid data struct\")\n\t}\n\n\tfmt.Printf(\"[kubeconfig] Using kubeconfig folder %q\\n\", data.KubeConfigDir())\n\treturn nil\n}","line":{"from":118,"to":126}} {"id":100000637,"name":"runKubeConfigFile","signature":"func runKubeConfigFile(kubeConfigFileName string) func(workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/init/kubeconfig.go","code":"// runKubeConfigFile executes kubeconfig creation logic.\nfunc runKubeConfigFile(kubeConfigFileName string) func(workflow.RunData) error {\n\treturn func(c workflow.RunData) error {\n\t\tdata, ok := c.(InitData)\n\t\tif !ok {\n\t\t\treturn errors.New(\"kubeconfig phase invoked with an invalid data struct\")\n\t\t}\n\n\t\t// if external CA mode, skip certificate authority generation\n\t\tif data.ExternalCA() {\n\t\t\tfmt.Printf(\"[kubeconfig] External CA mode: Using user provided %s\\n\", kubeConfigFileName)\n\t\t\t// If using an external CA while dryrun, copy kubeconfig files to dryrun dir for later use\n\t\t\tif data.DryRun() {\n\t\t\t\terr := kubeadmutil.CopyFile(filepath.Join(kubeadmconstants.KubernetesDir, kubeConfigFileName), filepath.Join(data.KubeConfigDir(), kubeConfigFileName))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"could not copy %s to dry run directory %s\", kubeConfigFileName, data.KubeConfigDir())\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\t// if dryrunning, reads certificates from a temporary folder (and defer restore to the path originally specified by the user)\n\t\tcfg := data.Cfg()\n\t\tcfg.CertificatesDir = data.CertificateWriteDir()\n\t\tdefer func() { cfg.CertificatesDir = data.CertificateDir() }()\n\n\t\t// creates the KubeConfig file (or use existing)\n\t\treturn kubeconfigphase.CreateKubeConfigFile(kubeConfigFileName, data.KubeConfigDir(), data.Cfg())\n\t}\n}","line":{"from":128,"to":157}} {"id":100000638,"name":"NewKubeletStartPhase","signature":"func NewKubeletStartPhase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/init/kubelet.go","code":"// NewKubeletStartPhase creates a kubeadm workflow phase that start kubelet on a node.\nfunc NewKubeletStartPhase() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"kubelet-start\",\n\t\tShort: \"Write kubelet settings and (re)start the kubelet\",\n\t\tLong: \"Write a file with KubeletConfiguration and an environment file with node specific kubelet settings, and then (re)start kubelet.\",\n\t\tExample: kubeletStartPhaseExample,\n\t\tRun: runKubeletStart,\n\t\tInheritFlags: []string{\n\t\t\toptions.CfgPath,\n\t\t\toptions.NodeCRISocket,\n\t\t\toptions.NodeName,\n\t\t\toptions.Patches,\n\t\t\toptions.DryRun,\n\t\t},\n\t}\n}","line":{"from":39,"to":55}} {"id":100000639,"name":"runKubeletStart","signature":"func runKubeletStart(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/init/kubelet.go","code":"// runKubeletStart executes kubelet start logic.\nfunc runKubeletStart(c workflow.RunData) error {\n\tdata, ok := c.(InitData)\n\tif !ok {\n\t\treturn errors.New(\"kubelet-start phase invoked with an invalid data struct\")\n\t}\n\n\t// First off, configure the kubelet. In this short timeframe, kubeadm is trying to stop/restart the kubelet\n\t// Try to stop the kubelet service so no race conditions occur when configuring it\n\tif !data.DryRun() {\n\t\tklog.V(1).Infoln(\"Stopping the kubelet\")\n\t\tkubeletphase.TryStopKubelet()\n\t}\n\n\t// Write env file with flags for the kubelet to use. We do not need to write the --register-with-taints for the control-plane,\n\t// as we handle that ourselves in the mark-control-plane phase\n\t// TODO: Maybe we want to do that some time in the future, in order to remove some logic from the mark-control-plane phase?\n\tif err := kubeletphase.WriteKubeletDynamicEnvFile(\u0026data.Cfg().ClusterConfiguration, \u0026data.Cfg().NodeRegistration, false, data.KubeletDir()); err != nil {\n\t\treturn errors.Wrap(err, \"error writing a dynamic environment file for the kubelet\")\n\t}\n\n\t// Write the kubelet configuration file to disk.\n\tif err := kubeletphase.WriteConfigToDisk(\u0026data.Cfg().ClusterConfiguration, data.KubeletDir(), data.PatchesDir(), data.OutputWriter()); err != nil {\n\t\treturn errors.Wrap(err, \"error writing kubelet configuration to disk\")\n\t}\n\n\t// Try to start the kubelet service in case it's inactive\n\tif !data.DryRun() {\n\t\tfmt.Println(\"[kubelet-start] Starting the kubelet\")\n\t\tkubeletphase.TryStartKubelet()\n\t}\n\n\treturn nil\n}","line":{"from":57,"to":90}} {"id":100000640,"name":"NewKubeletFinalizePhase","signature":"func NewKubeletFinalizePhase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/init/kubeletfinalize.go","code":"// NewKubeletFinalizePhase creates a kubeadm workflow phase that updates settings\n// relevant to the kubelet after TLS bootstrap.\nfunc NewKubeletFinalizePhase() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"kubelet-finalize\",\n\t\tShort: \"Updates settings relevant to the kubelet after TLS bootstrap\",\n\t\tExample: kubeletFinalizePhaseExample,\n\t\tPhases: []workflow.Phase{\n\t\t\t{\n\t\t\t\tName: \"all\",\n\t\t\t\tShort: \"Run all kubelet-finalize phases\",\n\t\t\t\tInheritFlags: []string{options.CfgPath, options.CertificatesDir, options.DryRun},\n\t\t\t\tExample: kubeletFinalizePhaseExample,\n\t\t\t\tRunAllSiblings: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"experimental-cert-rotation\",\n\t\t\t\tShort: \"Enable kubelet client certificate rotation\",\n\t\t\t\tInheritFlags: []string{options.CfgPath, options.CertificatesDir, options.DryRun},\n\t\t\t\tRun: runKubeletFinalizeCertRotation,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":43,"to":66}} {"id":100000641,"name":"runKubeletFinalizeCertRotation","signature":"func runKubeletFinalizeCertRotation(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/init/kubeletfinalize.go","code":"// runKubeletFinalizeCertRotation detects if the kubelet certificate rotation is enabled\n// and updates the kubelet.conf file to point to a rotatable certificate and key for the\n// Node user.\nfunc runKubeletFinalizeCertRotation(c workflow.RunData) error {\n\tdata, ok := c.(InitData)\n\tif !ok {\n\t\treturn errors.New(\"kubelet-finalize phase invoked with an invalid data struct\")\n\t}\n\n\t// Check if the user has added the kubelet --cert-dir flag.\n\t// If yes, use that path, else use the kubeadm provided value.\n\tcfg := data.Cfg()\n\tpkiPath := filepath.Join(data.KubeletDir(), \"pki\")\n\tval, ok := cfg.NodeRegistration.KubeletExtraArgs[\"cert-dir\"]\n\tif ok {\n\t\tpkiPath = val\n\t}\n\n\t// Check for the existence of the kubelet-client-current.pem file in the kubelet certificate directory.\n\trotate := false\n\tpemPath := filepath.Join(pkiPath, \"kubelet-client-current.pem\")\n\tif _, err := os.Stat(pemPath); err == nil {\n\t\tklog.V(1).Infof(\"[kubelet-finalize] Assuming that kubelet client certificate rotation is enabled: found %q\", pemPath)\n\t\trotate = true\n\t} else {\n\t\tklog.V(1).Infof(\"[kubelet-finalize] Assuming that kubelet client certificate rotation is disabled: %v\", err)\n\t}\n\n\t// Exit early if rotation is disabled.\n\tif !rotate {\n\t\treturn nil\n\t}\n\n\tkubeconfigPath := filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.KubeletKubeConfigFileName)\n\tfmt.Printf(\"[kubelet-finalize] Updating %q to point to a rotatable kubelet client certificate and key\\n\", kubeconfigPath)\n\n\t// Exit early if dry-running is enabled.\n\tif data.DryRun() {\n\t\treturn nil\n\t}\n\n\t// Load the kubeconfig from disk.\n\tkubeconfig, err := clientcmd.LoadFromFile(kubeconfigPath)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"could not load %q\", kubeconfigPath)\n\t}\n\n\t// Perform basic validation. The errors here can only happen if the kubelet.conf was corrupted.\n\tuserName := fmt.Sprintf(\"%s%s\", kubeadmconstants.NodesUserPrefix, cfg.NodeRegistration.Name)\n\tinfo, ok := kubeconfig.AuthInfos[userName]\n\tif !ok {\n\t\treturn errors.Errorf(\"the file %q does not contain authentication for user %q\", kubeconfigPath, cfg.NodeRegistration.Name)\n\t}\n\n\t// Update the client certificate and key of the node authorizer to point to the PEM symbolic link.\n\tinfo.ClientKeyData = []byte{}\n\tinfo.ClientCertificateData = []byte{}\n\tinfo.ClientKey = pemPath\n\tinfo.ClientCertificate = pemPath\n\n\t// Writes the kubeconfig back to disk.\n\tif err = clientcmd.WriteToFile(*kubeconfig, kubeconfigPath); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to serialize %q\", kubeconfigPath)\n\t}\n\n\t// Restart the kubelet.\n\tklog.V(1).Info(\"[kubelet-finalize] Restarting the kubelet to enable client certificate rotation\")\n\tkubeletphase.TryRestartKubelet()\n\n\treturn nil\n}","line":{"from":68,"to":138}} {"id":100000642,"name":"NewMarkControlPlanePhase","signature":"func NewMarkControlPlanePhase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/init/markcontrolplane.go","code":"// NewMarkControlPlanePhase creates a kubeadm workflow phase that implements mark-controlplane checks.\nfunc NewMarkControlPlanePhase() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"mark-control-plane\",\n\t\tShort: \"Mark a node as a control-plane\",\n\t\tExample: markControlPlaneExample,\n\t\tInheritFlags: []string{\n\t\t\toptions.NodeName,\n\t\t\toptions.CfgPath,\n\t\t\toptions.DryRun,\n\t\t},\n\t\tRun: runMarkControlPlane,\n\t}\n}","line":{"from":38,"to":51}} {"id":100000643,"name":"runMarkControlPlane","signature":"func runMarkControlPlane(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/init/markcontrolplane.go","code":"// runMarkControlPlane executes mark-control-plane checks logic.\nfunc runMarkControlPlane(c workflow.RunData) error {\n\tdata, ok := c.(InitData)\n\tif !ok {\n\t\treturn errors.New(\"mark-control-plane phase invoked with an invalid data struct\")\n\t}\n\n\tclient, err := data.Client()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnodeRegistration := data.Cfg().NodeRegistration\n\treturn markcontrolplanephase.MarkControlPlane(client, nodeRegistration.Name, nodeRegistration.Taints)\n}","line":{"from":53,"to":67}} {"id":100000644,"name":"NewPreflightPhase","signature":"func NewPreflightPhase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/init/preflight.go","code":"// NewPreflightPhase creates a kubeadm workflow phase that implements preflight checks for a new control-plane node.\nfunc NewPreflightPhase() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"preflight\",\n\t\tShort: \"Run pre-flight checks\",\n\t\tLong: \"Run pre-flight checks for kubeadm init.\",\n\t\tExample: preflightExample,\n\t\tRun: runPreflight,\n\t\tInheritFlags: []string{\n\t\t\toptions.CfgPath,\n\t\t\toptions.NodeCRISocket,\n\t\t\toptions.IgnorePreflightErrors,\n\t\t\toptions.DryRun,\n\t\t},\n\t}\n}","line":{"from":39,"to":54}} {"id":100000645,"name":"runPreflight","signature":"func runPreflight(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/init/preflight.go","code":"// runPreflight executes preflight checks logic.\nfunc runPreflight(c workflow.RunData) error {\n\tdata, ok := c.(InitData)\n\tif !ok {\n\t\treturn errors.New(\"preflight phase invoked with an invalid data struct\")\n\t}\n\n\tfmt.Println(\"[preflight] Running pre-flight checks\")\n\tif err := preflight.RunInitNodeChecks(utilsexec.New(), data.Cfg(), data.IgnorePreflightErrors(), false, false); err != nil {\n\t\treturn err\n\t}\n\n\tif data.DryRun() {\n\t\tfmt.Println(\"[preflight] Would pull the required images (like 'kubeadm config images pull')\")\n\t\treturn nil\n\t}\n\n\tfmt.Println(\"[preflight] Pulling images required for setting up a Kubernetes cluster\")\n\tfmt.Println(\"[preflight] This might take a minute or two, depending on the speed of your internet connection\")\n\tfmt.Println(\"[preflight] You can also perform this action in beforehand using 'kubeadm config images pull'\")\n\treturn preflight.RunPullImagesCheck(utilsexec.New(), data.Cfg(), data.IgnorePreflightErrors())\n}","line":{"from":56,"to":77}} {"id":100000646,"name":"NewShowJoinCommandPhase","signature":"func NewShowJoinCommandPhase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/init/showjoincommand.go","code":"// NewShowJoinCommandPhase creates a kubeadm workflow phase that implements showing the join command.\nfunc NewShowJoinCommandPhase() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"show-join-command\",\n\t\tShort: \"Show the join command for control-plane and worker node\",\n\t\tRun: showJoinCommand,\n\t\tDependencies: []string{\"bootstrap-token\", \"upload-certs\"},\n\t}\n}","line":{"from":70,"to":78}} {"id":100000647,"name":"showJoinCommand","signature":"func showJoinCommand(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/init/showjoincommand.go","code":"// showJoinCommand prints the join command after all the phases in init have finished\nfunc showJoinCommand(c workflow.RunData) error {\n\tdata, ok := c.(InitData)\n\tif !ok {\n\t\treturn errors.New(\"show-join-command phase invoked with an invalid data struct\")\n\t}\n\n\tadminKubeConfigPath := data.KubeConfigPath()\n\n\t// Prints the join command, multiple times in case the user has multiple tokens\n\tfor _, token := range data.Tokens() {\n\t\tif err := printJoinCommand(data.OutputWriter(), adminKubeConfigPath, token, data); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to print join command\")\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":80,"to":97}} {"id":100000648,"name":"printJoinCommand","signature":"func printJoinCommand(out io.Writer, adminKubeConfigPath, token string, i InitData) error","file":"cmd/kubeadm/app/cmd/phases/init/showjoincommand.go","code":"func printJoinCommand(out io.Writer, adminKubeConfigPath, token string, i InitData) error {\n\tjoinControlPlaneCommand, err := cmdutil.GetJoinControlPlaneCommand(adminKubeConfigPath, token, i.CertificateKey(), i.SkipTokenPrint(), i.SkipCertificateKeyPrint())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tjoinWorkerCommand, err := cmdutil.GetJoinWorkerCommand(adminKubeConfigPath, token, i.SkipTokenPrint())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tctx := map[string]interface{}{\n\t\t\"KubeConfigPath\": adminKubeConfigPath,\n\t\t\"ControlPlaneEndpoint\": i.Cfg().ControlPlaneEndpoint,\n\t\t\"UploadCerts\": i.UploadCerts(),\n\t\t\"joinControlPlaneCommand\": joinControlPlaneCommand,\n\t\t\"joinWorkerCommand\": joinWorkerCommand,\n\t}\n\n\treturn initDoneTempl.Execute(out, ctx)\n}","line":{"from":99,"to":119}} {"id":100000649,"name":"NewUploadCertsPhase","signature":"func NewUploadCertsPhase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/init/uploadcerts.go","code":"// NewUploadCertsPhase returns the uploadCerts phase\nfunc NewUploadCertsPhase() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"upload-certs\",\n\t\tShort: fmt.Sprintf(\"Upload certificates to %s\", kubeadmconstants.KubeadmCertsSecret),\n\t\tLong: fmt.Sprintf(\"Upload control plane certificates to the %s Secret\", kubeadmconstants.KubeadmCertsSecret),\n\t\tRun: runUploadCerts,\n\t\tInheritFlags: []string{\n\t\t\toptions.CfgPath,\n\t\t\toptions.KubeconfigPath,\n\t\t\toptions.UploadCerts,\n\t\t\toptions.CertificateKey,\n\t\t\toptions.SkipCertificateKeyPrint,\n\t\t\toptions.DryRun,\n\t\t},\n\t}\n}","line":{"from":30,"to":46}} {"id":100000650,"name":"runUploadCerts","signature":"func runUploadCerts(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/init/uploadcerts.go","code":"func runUploadCerts(c workflow.RunData) error {\n\tdata, ok := c.(InitData)\n\tif !ok {\n\t\treturn errors.New(\"upload-certs phase invoked with an invalid data struct\")\n\t}\n\n\tif !data.UploadCerts() {\n\t\tfmt.Printf(\"[upload-certs] Skipping phase. Please see --%s\\n\", options.UploadCerts)\n\t\treturn nil\n\t}\n\tclient, err := data.Client()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(data.CertificateKey()) == 0 {\n\t\tcertificateKey, err := copycerts.CreateCertificateKey()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdata.SetCertificateKey(certificateKey)\n\t}\n\n\tif err := copycerts.UploadCerts(client, data.Cfg(), data.CertificateKey()); err != nil {\n\t\treturn errors.Wrap(err, \"error uploading certs\")\n\t}\n\tif !data.SkipCertificateKeyPrint() {\n\t\tfmt.Printf(\"[upload-certs] Using certificate key:\\n%s\\n\", data.CertificateKey())\n\t}\n\treturn nil\n}","line":{"from":48,"to":78}} {"id":100000651,"name":"NewUploadConfigPhase","signature":"func NewUploadConfigPhase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/init/uploadconfig.go","code":"// NewUploadConfigPhase returns the phase to uploadConfig\nfunc NewUploadConfigPhase() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"upload-config\",\n\t\tAliases: []string{\"uploadconfig\"},\n\t\tShort: \"Upload the kubeadm and kubelet configuration to a ConfigMap\",\n\t\tLong: cmdutil.MacroCommandLongDescription,\n\t\tPhases: []workflow.Phase{\n\t\t\t{\n\t\t\t\tName: \"all\",\n\t\t\t\tShort: \"Upload all configuration to a config map\",\n\t\t\t\tRunAllSiblings: true,\n\t\t\t\tInheritFlags: getUploadConfigPhaseFlags(),\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"kubeadm\",\n\t\t\t\tShort: \"Upload the kubeadm ClusterConfiguration to a ConfigMap\",\n\t\t\t\tLong: uploadKubeadmConfigLongDesc,\n\t\t\t\tExample: uploadKubeadmConfigExample,\n\t\t\t\tRun: runUploadKubeadmConfig,\n\t\t\t\tInheritFlags: getUploadConfigPhaseFlags(),\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"kubelet\",\n\t\t\t\tShort: \"Upload the kubelet component config to a ConfigMap\",\n\t\t\t\tLong: uploadKubeletConfigLongDesc,\n\t\t\t\tExample: uploadKubeletConfigExample,\n\t\t\t\tRun: runUploadKubeletConfig,\n\t\t\t\tInheritFlags: getUploadConfigPhaseFlags(),\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":62,"to":94}} {"id":100000652,"name":"getUploadConfigPhaseFlags","signature":"func getUploadConfigPhaseFlags() []string","file":"cmd/kubeadm/app/cmd/phases/init/uploadconfig.go","code":"func getUploadConfigPhaseFlags() []string {\n\treturn []string{\n\t\toptions.CfgPath,\n\t\toptions.NodeCRISocket,\n\t\toptions.KubeconfigPath,\n\t\toptions.DryRun,\n\t}\n}","line":{"from":96,"to":103}} {"id":100000653,"name":"runUploadKubeadmConfig","signature":"func runUploadKubeadmConfig(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/init/uploadconfig.go","code":"// runUploadKubeadmConfig uploads the kubeadm configuration to a ConfigMap\nfunc runUploadKubeadmConfig(c workflow.RunData) error {\n\tcfg, client, _, err := getUploadConfigData(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tklog.V(1).Infoln(\"[upload-config] Uploading the kubeadm ClusterConfiguration to a ConfigMap\")\n\tif err := uploadconfig.UploadConfiguration(cfg, client); err != nil {\n\t\treturn errors.Wrap(err, \"error uploading the kubeadm ClusterConfiguration\")\n\t}\n\treturn nil\n}","line":{"from":105,"to":117}} {"id":100000654,"name":"runUploadKubeletConfig","signature":"func runUploadKubeletConfig(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/init/uploadconfig.go","code":"// runUploadKubeletConfig uploads the kubelet configuration to a ConfigMap\nfunc runUploadKubeletConfig(c workflow.RunData) error {\n\tcfg, client, patchesDir, err := getUploadConfigData(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tklog.V(1).Infoln(\"[upload-config] Uploading the kubelet component config to a ConfigMap\")\n\tif err = kubeletphase.CreateConfigMap(\u0026cfg.ClusterConfiguration, patchesDir, client); err != nil {\n\t\treturn errors.Wrap(err, \"error creating kubelet configuration ConfigMap\")\n\t}\n\n\tklog.V(1).Infoln(\"[upload-config] Preserving the CRISocket information for the control-plane node\")\n\tif err := patchnodephase.AnnotateCRISocket(client, cfg.NodeRegistration.Name, cfg.NodeRegistration.CRISocket); err != nil {\n\t\treturn errors.Wrap(err, \"Error writing Crisocket information for the control-plane node\")\n\t}\n\treturn nil\n}","line":{"from":119,"to":136}} {"id":100000655,"name":"getUploadConfigData","signature":"func getUploadConfigData(c workflow.RunData) (*kubeadmapi.InitConfiguration, clientset.Interface, string, error)","file":"cmd/kubeadm/app/cmd/phases/init/uploadconfig.go","code":"func getUploadConfigData(c workflow.RunData) (*kubeadmapi.InitConfiguration, clientset.Interface, string, error) {\n\tdata, ok := c.(InitData)\n\tif !ok {\n\t\treturn nil, nil, \"\", errors.New(\"upload-config phase invoked with an invalid data struct\")\n\t}\n\tcfg := data.Cfg()\n\tclient, err := data.Client()\n\tif err != nil {\n\t\treturn nil, nil, \"\", err\n\t}\n\treturn cfg, client, data.PatchesDir(), err\n}","line":{"from":138,"to":149}} {"id":100000656,"name":"NewWaitControlPlanePhase","signature":"func NewWaitControlPlanePhase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/init/waitcontrolplane.go","code":"// NewWaitControlPlanePhase is a hidden phase that runs after the control-plane and etcd phases\nfunc NewWaitControlPlanePhase() workflow.Phase {\n\tphase := workflow.Phase{\n\t\tName: \"wait-control-plane\",\n\t\tRun: runWaitControlPlanePhase,\n\t\tHidden: true,\n\t}\n\treturn phase\n}","line":{"from":58,"to":66}} {"id":100000657,"name":"runWaitControlPlanePhase","signature":"func runWaitControlPlanePhase(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/init/waitcontrolplane.go","code":"func runWaitControlPlanePhase(c workflow.RunData) error {\n\tdata, ok := c.(InitData)\n\tif !ok {\n\t\treturn errors.New(\"wait-control-plane phase invoked with an invalid data struct\")\n\t}\n\n\t// If we're dry-running, print the generated manifests.\n\t// TODO: think of a better place to move this call - e.g. a hidden phase.\n\tif data.DryRun() {\n\t\tif err := dryrunutil.PrintFilesIfDryRunning(true /* needPrintManifest */, data.ManifestDir(), data.OutputWriter()); err != nil {\n\t\t\treturn errors.Wrap(err, \"error printing files on dryrun\")\n\t\t}\n\t}\n\n\t// waiter holds the apiclient.Waiter implementation of choice, responsible for querying the API server in various ways and waiting for conditions to be fulfilled\n\tklog.V(1).Infoln(\"[wait-control-plane] Waiting for the API server to be healthy\")\n\n\tclient, err := data.Client()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"cannot obtain client\")\n\t}\n\n\ttimeout := data.Cfg().ClusterConfiguration.APIServer.TimeoutForControlPlane.Duration\n\twaiter, err := newControlPlaneWaiter(data.DryRun(), timeout, client, data.OutputWriter())\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error creating waiter\")\n\t}\n\n\tfmt.Printf(\"[wait-control-plane] Waiting for the kubelet to boot up the control plane as static Pods from directory %q. This can take up to %v\\n\", data.ManifestDir(), timeout)\n\n\tif err := waiter.WaitForKubeletAndFunc(waiter.WaitForAPI); err != nil {\n\t\tcontext := struct {\n\t\t\tError string\n\t\t\tSocket string\n\t\t}{\n\t\t\tError: fmt.Sprintf(\"%v\", err),\n\t\t\tSocket: data.Cfg().NodeRegistration.CRISocket,\n\t\t}\n\n\t\tkubeletFailTempl.Execute(data.OutputWriter(), context)\n\t\treturn errors.New(\"couldn't initialize a Kubernetes cluster\")\n\t}\n\n\treturn nil\n}","line":{"from":68,"to":112}} {"id":100000658,"name":"newControlPlaneWaiter","signature":"func newControlPlaneWaiter(dryRun bool, timeout time.Duration, client clientset.Interface, out io.Writer) (apiclient.Waiter, error)","file":"cmd/kubeadm/app/cmd/phases/init/waitcontrolplane.go","code":"// newControlPlaneWaiter returns a new waiter that is used to wait on the control plane to boot up.\nfunc newControlPlaneWaiter(dryRun bool, timeout time.Duration, client clientset.Interface, out io.Writer) (apiclient.Waiter, error) {\n\tif dryRun {\n\t\treturn dryrunutil.NewWaiter(), nil\n\t}\n\n\treturn apiclient.NewKubeWaiter(client, timeout, out), nil\n}","line":{"from":114,"to":121}} {"id":100000659,"name":"NewCheckEtcdPhase","signature":"func NewCheckEtcdPhase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/join/checketcd.go","code":"// NewCheckEtcdPhase is a hidden phase that runs after the control-plane-prepare and\n// before the bootstrap-kubelet phase that ensures etcd is healthy\nfunc NewCheckEtcdPhase() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"check-etcd\",\n\t\tRun: runCheckEtcdPhase,\n\t\tHidden: true,\n\t}\n}","line":{"from":28,"to":36}} {"id":100000660,"name":"runCheckEtcdPhase","signature":"func runCheckEtcdPhase(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/join/checketcd.go","code":"func runCheckEtcdPhase(c workflow.RunData) error {\n\tdata, ok := c.(JoinData)\n\tif !ok {\n\t\treturn errors.New(\"check-etcd phase invoked with an invalid data struct\")\n\t}\n\n\t// Skip if this is not a control plane\n\tif data.Cfg().ControlPlane == nil {\n\t\treturn nil\n\t}\n\n\tcfg, err := data.InitCfg()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif cfg.Etcd.External != nil {\n\t\tfmt.Println(\"[check-etcd] Skipping etcd check in external mode\")\n\t\treturn nil\n\t}\n\n\tfmt.Println(\"[check-etcd] Checking that the etcd cluster is healthy\")\n\n\t// Checks that the etcd cluster is healthy\n\t// NB. this check cannot be implemented before because it requires the admin.conf and all the certificates\n\t// for connecting to etcd already in place\n\tclient, err := data.Client()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn etcdphase.CheckLocalEtcdClusterStatus(client, data.CertificateWriteDir())\n}","line":{"from":38,"to":70}} {"id":100000661,"name":"getControlPlaneJoinPhaseFlags","signature":"func getControlPlaneJoinPhaseFlags(name string) []string","file":"cmd/kubeadm/app/cmd/phases/join/controlplanejoin.go","code":"func getControlPlaneJoinPhaseFlags(name string) []string {\n\tflags := []string{\n\t\toptions.CfgPath,\n\t\toptions.ControlPlane,\n\t\toptions.NodeName,\n\t}\n\tif name == \"etcd\" || name == \"all\" {\n\t\tflags = append(flags, options.Patches)\n\t}\n\tif name != \"mark-control-plane\" {\n\t\tflags = append(flags, options.APIServerAdvertiseAddress)\n\t}\n\tif name != \"update-status\" {\n\t\tflags = append(flags, options.DryRun)\n\t}\n\treturn flags\n}","line":{"from":39,"to":55}} {"id":100000662,"name":"NewControlPlaneJoinPhase","signature":"func NewControlPlaneJoinPhase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/join/controlplanejoin.go","code":"// NewControlPlaneJoinPhase creates a kubeadm workflow phase that implements joining a machine as a control plane instance\nfunc NewControlPlaneJoinPhase() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"control-plane-join\",\n\t\tShort: \"Join a machine as a control plane instance\",\n\t\tExample: controlPlaneJoinExample,\n\t\tPhases: []workflow.Phase{\n\t\t\t{\n\t\t\t\tName: \"all\",\n\t\t\t\tShort: \"Join a machine as a control plane instance\",\n\t\t\t\tInheritFlags: getControlPlaneJoinPhaseFlags(\"all\"),\n\t\t\t\tRunAllSiblings: true,\n\t\t\t\tArgsValidator: cobra.NoArgs,\n\t\t\t},\n\t\t\tnewEtcdLocalSubphase(),\n\t\t\tnewUpdateStatusSubphase(),\n\t\t\tnewMarkControlPlaneSubphase(),\n\t\t},\n\t}\n}","line":{"from":57,"to":76}} {"id":100000663,"name":"newEtcdLocalSubphase","signature":"func newEtcdLocalSubphase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/join/controlplanejoin.go","code":"func newEtcdLocalSubphase() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"etcd\",\n\t\tShort: \"Add a new local etcd member\",\n\t\tRun: runEtcdPhase,\n\t\tInheritFlags: getControlPlaneJoinPhaseFlags(\"etcd\"),\n\t\tArgsValidator: cobra.NoArgs,\n\t}\n}","line":{"from":78,"to":86}} {"id":100000664,"name":"newUpdateStatusSubphase","signature":"func newUpdateStatusSubphase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/join/controlplanejoin.go","code":"func newUpdateStatusSubphase() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"update-status\",\n\t\tShort: fmt.Sprintf(\n\t\t\t\"Register the new control-plane node into the ClusterStatus maintained in the %s ConfigMap (DEPRECATED)\",\n\t\t\tkubeadmconstants.KubeadmConfigConfigMap,\n\t\t),\n\t\tRun: runUpdateStatusPhase,\n\t\tInheritFlags: getControlPlaneJoinPhaseFlags(\"update-status\"),\n\t\tArgsValidator: cobra.NoArgs,\n\t}\n}","line":{"from":88,"to":99}} {"id":100000665,"name":"newMarkControlPlaneSubphase","signature":"func newMarkControlPlaneSubphase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/join/controlplanejoin.go","code":"func newMarkControlPlaneSubphase() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"mark-control-plane\",\n\t\tShort: \"Mark a node as a control-plane\",\n\t\tRun: runMarkControlPlanePhase,\n\t\tInheritFlags: getControlPlaneJoinPhaseFlags(\"mark-control-plane\"),\n\t\tArgsValidator: cobra.NoArgs,\n\t}\n}","line":{"from":101,"to":109}} {"id":100000666,"name":"runEtcdPhase","signature":"func runEtcdPhase(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/join/controlplanejoin.go","code":"func runEtcdPhase(c workflow.RunData) error {\n\tdata, ok := c.(JoinData)\n\tif !ok {\n\t\treturn errors.New(\"control-plane-join phase invoked with an invalid data struct\")\n\t}\n\n\tif data.Cfg().ControlPlane == nil {\n\t\treturn nil\n\t}\n\n\t// gets access to the cluster using the identity defined in admin.conf\n\tclient, err := data.Client()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"couldn't create Kubernetes client\")\n\t}\n\tcfg, err := data.InitCfg()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// in case of local etcd\n\tif cfg.Etcd.External != nil {\n\t\tfmt.Println(\"[control-plane-join] Using external etcd - no local stacked instance added\")\n\t\treturn nil\n\t}\n\n\tif !data.DryRun() {\n\t\t// Create the etcd data directory\n\t\tif err := etcdutil.CreateDataDirectory(cfg.Etcd.Local.DataDir); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"[control-plane-join] Would ensure that %q directory is present\\n\", cfg.Etcd.Local.DataDir)\n\t}\n\n\t// Adds a new etcd instance; in order to do this the new etcd instance should be \"announced\" to\n\t// the existing etcd members before being created.\n\t// This operation must be executed after kubelet is already started in order to minimize the time\n\t// between the new etcd member is announced and the start of the static pod running the new etcd member, because during\n\t// this time frame etcd gets temporary not available (only when moving from 1 to 2 members in the etcd cluster).\n\t// From https://coreos.com/etcd/docs/latest/v2/runtime-configuration.html\n\t// \"If you add a new member to a 1-node cluster, the cluster cannot make progress before the new member starts\n\t// because it needs two members as majority to agree on the consensus. You will only see this behavior between the time\n\t// etcdctl member add informs the cluster about the new member and the new member successfully establishing a connection to the\n\t// existing one.\"\n\tif err := etcdphase.CreateStackedEtcdStaticPodManifestFile(client, data.ManifestDir(), data.PatchesDir(), cfg.NodeRegistration.Name, \u0026cfg.ClusterConfiguration, \u0026cfg.LocalAPIEndpoint, data.DryRun(), data.CertificateWriteDir()); err != nil {\n\t\treturn errors.Wrap(err, \"error creating local etcd static pod manifest file\")\n\t}\n\n\treturn nil\n}","line":{"from":111,"to":160}} {"id":100000667,"name":"runUpdateStatusPhase","signature":"func runUpdateStatusPhase(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/join/controlplanejoin.go","code":"func runUpdateStatusPhase(c workflow.RunData) error {\n\tdata, ok := c.(JoinData)\n\tif !ok {\n\t\treturn errors.New(\"control-plane-join phase invoked with an invalid data struct\")\n\t}\n\n\tif data.Cfg().ControlPlane != nil {\n\t\tfmt.Println(\"The 'update-status' phase is deprecated and will be removed in a future release. \" +\n\t\t\t\"Currently it performs no operation\")\n\t}\n\treturn nil\n}","line":{"from":162,"to":173}} {"id":100000668,"name":"runMarkControlPlanePhase","signature":"func runMarkControlPlanePhase(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/join/controlplanejoin.go","code":"func runMarkControlPlanePhase(c workflow.RunData) error {\n\tdata, ok := c.(JoinData)\n\tif !ok {\n\t\treturn errors.New(\"control-plane-join phase invoked with an invalid data struct\")\n\t}\n\n\tif data.Cfg().ControlPlane == nil {\n\t\treturn nil\n\t}\n\n\t// gets access to the cluster using the identity defined in admin.conf\n\tclient, err := data.Client()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"couldn't create Kubernetes client\")\n\t}\n\tcfg, err := data.InitCfg()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !data.DryRun() {\n\t\tif err := markcontrolplanephase.MarkControlPlane(client, cfg.NodeRegistration.Name, cfg.NodeRegistration.Taints); err != nil {\n\t\t\treturn errors.Wrap(err, \"error applying control-plane label and taints\")\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"[control-plane-join] Would mark node %s as a control-plane\\n\", cfg.NodeRegistration.Name)\n\t}\n\n\treturn nil\n}","line":{"from":175,"to":204}} {"id":100000669,"name":"NewControlPlanePreparePhase","signature":"func NewControlPlanePreparePhase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/join/controlplaneprepare.go","code":"// NewControlPlanePreparePhase creates a kubeadm workflow phase that implements the preparation of the node to serve a control plane\nfunc NewControlPlanePreparePhase() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"control-plane-prepare\",\n\t\tShort: \"Prepare the machine for serving a control plane\",\n\t\tExample: controlPlanePrepareExample,\n\t\tPhases: []workflow.Phase{\n\t\t\t{\n\t\t\t\tName: \"all [api-server-endpoint]\",\n\t\t\t\tShort: \"Prepare the machine for serving a control plane\",\n\t\t\t\tInheritFlags: getControlPlanePreparePhaseFlags(\"all\"),\n\t\t\t\tRunAllSiblings: true,\n\t\t\t},\n\t\t\tnewControlPlanePrepareDownloadCertsSubphase(),\n\t\t\tnewControlPlanePrepareCertsSubphase(),\n\t\t\tnewControlPlanePrepareKubeconfigSubphase(),\n\t\t\tnewControlPlanePrepareControlPlaneSubphase(),\n\t\t},\n\t}\n}","line":{"from":45,"to":64}} {"id":100000670,"name":"getControlPlanePreparePhaseFlags","signature":"func getControlPlanePreparePhaseFlags(name string) []string","file":"cmd/kubeadm/app/cmd/phases/join/controlplaneprepare.go","code":"func getControlPlanePreparePhaseFlags(name string) []string {\n\tvar flags []string\n\tswitch name {\n\tcase \"all\":\n\t\tflags = []string{\n\t\t\toptions.APIServerAdvertiseAddress,\n\t\t\toptions.APIServerBindPort,\n\t\t\toptions.CfgPath,\n\t\t\toptions.ControlPlane,\n\t\t\toptions.NodeName,\n\t\t\toptions.FileDiscovery,\n\t\t\toptions.TokenDiscovery,\n\t\t\toptions.TokenDiscoveryCAHash,\n\t\t\toptions.TokenDiscoverySkipCAHash,\n\t\t\toptions.TLSBootstrapToken,\n\t\t\toptions.TokenStr,\n\t\t\toptions.CertificateKey,\n\t\t\toptions.Patches,\n\t\t\toptions.DryRun,\n\t\t}\n\tcase \"download-certs\":\n\t\tflags = []string{\n\t\t\toptions.CfgPath,\n\t\t\toptions.ControlPlane,\n\t\t\toptions.FileDiscovery,\n\t\t\toptions.TokenDiscovery,\n\t\t\toptions.TokenDiscoveryCAHash,\n\t\t\toptions.TokenDiscoverySkipCAHash,\n\t\t\toptions.TLSBootstrapToken,\n\t\t\toptions.TokenStr,\n\t\t\toptions.CertificateKey,\n\t\t\toptions.DryRun,\n\t\t}\n\tcase \"certs\":\n\t\tflags = []string{\n\t\t\toptions.APIServerAdvertiseAddress,\n\t\t\toptions.CfgPath,\n\t\t\toptions.ControlPlane,\n\t\t\toptions.NodeName,\n\t\t\toptions.FileDiscovery,\n\t\t\toptions.TokenDiscovery,\n\t\t\toptions.TokenDiscoveryCAHash,\n\t\t\toptions.TokenDiscoverySkipCAHash,\n\t\t\toptions.TLSBootstrapToken,\n\t\t\toptions.TokenStr,\n\t\t\toptions.DryRun,\n\t\t}\n\tcase \"kubeconfig\":\n\t\tflags = []string{\n\t\t\toptions.CfgPath,\n\t\t\toptions.ControlPlane,\n\t\t\toptions.FileDiscovery,\n\t\t\toptions.TokenDiscovery,\n\t\t\toptions.TokenDiscoveryCAHash,\n\t\t\toptions.TokenDiscoverySkipCAHash,\n\t\t\toptions.TLSBootstrapToken,\n\t\t\toptions.TokenStr,\n\t\t\toptions.CertificateKey,\n\t\t\toptions.DryRun,\n\t\t}\n\tcase \"control-plane\":\n\t\tflags = []string{\n\t\t\toptions.APIServerAdvertiseAddress,\n\t\t\toptions.APIServerBindPort,\n\t\t\toptions.CfgPath,\n\t\t\toptions.ControlPlane,\n\t\t\toptions.Patches,\n\t\t\toptions.DryRun,\n\t\t}\n\tdefault:\n\t\tflags = []string{}\n\t}\n\treturn flags\n}","line":{"from":66,"to":139}} {"id":100000671,"name":"newControlPlanePrepareDownloadCertsSubphase","signature":"func newControlPlanePrepareDownloadCertsSubphase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/join/controlplaneprepare.go","code":"func newControlPlanePrepareDownloadCertsSubphase() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"download-certs [api-server-endpoint]\",\n\t\tShort: fmt.Sprintf(\"[EXPERIMENTAL] Download certificates shared among control-plane nodes from the %s Secret\", kubeadmconstants.KubeadmCertsSecret),\n\t\tRun: runControlPlanePrepareDownloadCertsPhaseLocal,\n\t\tInheritFlags: getControlPlanePreparePhaseFlags(\"download-certs\"),\n\t}\n}","line":{"from":141,"to":148}} {"id":100000672,"name":"newControlPlanePrepareCertsSubphase","signature":"func newControlPlanePrepareCertsSubphase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/join/controlplaneprepare.go","code":"func newControlPlanePrepareCertsSubphase() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"certs [api-server-endpoint]\",\n\t\tShort: \"Generate the certificates for the new control plane components\",\n\t\tRun: runControlPlanePrepareCertsPhaseLocal, //NB. eventually in future we would like to break down this in sub phases for each cert or add the --csr option\n\t\tInheritFlags: getControlPlanePreparePhaseFlags(\"certs\"),\n\t}\n}","line":{"from":150,"to":157}} {"id":100000673,"name":"newControlPlanePrepareKubeconfigSubphase","signature":"func newControlPlanePrepareKubeconfigSubphase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/join/controlplaneprepare.go","code":"func newControlPlanePrepareKubeconfigSubphase() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"kubeconfig [api-server-endpoint]\",\n\t\tShort: \"Generate the kubeconfig for the new control plane components\",\n\t\tRun: runControlPlanePrepareKubeconfigPhaseLocal, //NB. eventually in future we would like to break down this in sub phases for each kubeconfig\n\t\tInheritFlags: getControlPlanePreparePhaseFlags(\"kubeconfig\"),\n\t}\n}","line":{"from":159,"to":166}} {"id":100000674,"name":"newControlPlanePrepareControlPlaneSubphase","signature":"func newControlPlanePrepareControlPlaneSubphase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/join/controlplaneprepare.go","code":"func newControlPlanePrepareControlPlaneSubphase() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"control-plane\",\n\t\tShort: \"Generate the manifests for the new control plane components\",\n\t\tRun: runControlPlanePrepareControlPlaneSubphase, //NB. eventually in future we would like to break down this in sub phases for each component\n\t\tInheritFlags: getControlPlanePreparePhaseFlags(\"control-plane\"),\n\t\tArgsValidator: cobra.NoArgs,\n\t}\n}","line":{"from":168,"to":176}} {"id":100000675,"name":"runControlPlanePrepareControlPlaneSubphase","signature":"func runControlPlanePrepareControlPlaneSubphase(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/join/controlplaneprepare.go","code":"func runControlPlanePrepareControlPlaneSubphase(c workflow.RunData) error {\n\tdata, ok := c.(JoinData)\n\tif !ok {\n\t\treturn errors.New(\"control-plane-prepare phase invoked with an invalid data struct\")\n\t}\n\n\t// Skip if this is not a control plane\n\tif data.Cfg().ControlPlane == nil {\n\t\treturn nil\n\t}\n\n\tcfg, err := data.InitCfg()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"[control-plane] Using manifest folder %q\\n\", data.ManifestDir())\n\n\t// If we're dry-running, set CertificatesDir to default value to get the right cert path in static pod yaml\n\tif data.DryRun() {\n\t\tcfg.CertificatesDir = filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.DefaultCertificateDir)\n\t}\n\n\tfor _, component := range kubeadmconstants.ControlPlaneComponents {\n\t\tfmt.Printf(\"[control-plane] Creating static Pod manifest for %q\\n\", component)\n\t\terr := controlplane.CreateStaticPodFiles(\n\t\t\tdata.ManifestDir(),\n\t\t\tdata.PatchesDir(),\n\t\t\t\u0026cfg.ClusterConfiguration,\n\t\t\t\u0026cfg.LocalAPIEndpoint,\n\t\t\tdata.DryRun(),\n\t\t\tcomponent,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":178,"to":216}} {"id":100000676,"name":"runControlPlanePrepareDownloadCertsPhaseLocal","signature":"func runControlPlanePrepareDownloadCertsPhaseLocal(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/join/controlplaneprepare.go","code":"func runControlPlanePrepareDownloadCertsPhaseLocal(c workflow.RunData) error {\n\tdata, ok := c.(JoinData)\n\tif !ok {\n\t\treturn errors.New(\"download-certs phase invoked with an invalid data struct\")\n\t}\n\n\tif data.Cfg().ControlPlane == nil || len(data.CertificateKey()) == 0 {\n\t\tklog.V(1).Infoln(\"[download-certs] Skipping certs download\")\n\t\treturn nil\n\t}\n\n\tcfg, err := data.InitCfg()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// If we're dry-running, download certs to tmp dir, and defer to restore to the path originally specified by the user\n\tcertsDir := cfg.CertificatesDir\n\tcfg.CertificatesDir = data.CertificateWriteDir()\n\tdefer func() { cfg.CertificatesDir = certsDir }()\n\n\tclient, err := bootstrapClient(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := copycerts.DownloadCerts(client, cfg, data.CertificateKey()); err != nil {\n\t\treturn errors.Wrap(err, \"error downloading certs\")\n\t}\n\treturn nil\n}","line":{"from":218,"to":248}} {"id":100000677,"name":"runControlPlanePrepareCertsPhaseLocal","signature":"func runControlPlanePrepareCertsPhaseLocal(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/join/controlplaneprepare.go","code":"func runControlPlanePrepareCertsPhaseLocal(c workflow.RunData) error {\n\tdata, ok := c.(JoinData)\n\tif !ok {\n\t\treturn errors.New(\"control-plane-prepare phase invoked with an invalid data struct\")\n\t}\n\n\t// Skip if this is not a control plane\n\tif data.Cfg().ControlPlane == nil {\n\t\treturn nil\n\t}\n\n\tcfg, err := data.InitCfg()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"[certs] Using certificateDir folder %q\\n\", cfg.CertificatesDir)\n\n\t// if dryrunning, write certificates files to a temporary folder (and defer restore to the path originally specified by the user)\n\tcertsDir := cfg.CertificatesDir\n\tcfg.CertificatesDir = data.CertificateWriteDir()\n\tdefer func() { cfg.CertificatesDir = certsDir }()\n\t// Generate missing certificates (if any)\n\treturn certsphase.CreatePKIAssets(cfg)\n}","line":{"from":250,"to":274}} {"id":100000678,"name":"runControlPlanePrepareKubeconfigPhaseLocal","signature":"func runControlPlanePrepareKubeconfigPhaseLocal(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/join/controlplaneprepare.go","code":"func runControlPlanePrepareKubeconfigPhaseLocal(c workflow.RunData) error {\n\tdata, ok := c.(JoinData)\n\tif !ok {\n\t\treturn errors.New(\"control-plane-prepare phase invoked with an invalid data struct\")\n\t}\n\n\t// Skip if this is not a control plane\n\tif data.Cfg().ControlPlane == nil {\n\t\treturn nil\n\t}\n\n\tcfg, err := data.InitCfg()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"[kubeconfig] Generating kubeconfig files\")\n\tfmt.Printf(\"[kubeconfig] Using kubeconfig folder %q\\n\", data.KubeConfigDir())\n\n\t// Generate kubeconfig files for controller manager, scheduler and for the admin/kubeadm itself\n\t// NB. The kubeconfig file for kubelet will be generated by the TLS bootstrap process in\n\t// following steps of the join --control-plane workflow\n\tif err := kubeconfigphase.CreateJoinControlPlaneKubeConfigFiles(data.KubeConfigDir(), cfg); err != nil {\n\t\treturn errors.Wrap(err, \"error generating kubeconfig files\")\n\t}\n\n\treturn nil\n}","line":{"from":276,"to":303}} {"id":100000679,"name":"bootstrapClient","signature":"func bootstrapClient(data JoinData) (clientset.Interface, error)","file":"cmd/kubeadm/app/cmd/phases/join/controlplaneprepare.go","code":"func bootstrapClient(data JoinData) (clientset.Interface, error) {\n\ttlsBootstrapCfg, err := data.TLSBootstrapCfg()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to access the cluster\")\n\t}\n\tclient, err := kubeconfigutil.ToClientSet(tlsBootstrapCfg)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to access the cluster\")\n\t}\n\treturn client, nil\n}","line":{"from":305,"to":315}} {"id":100000680,"name":"NewKubeletStartPhase","signature":"func NewKubeletStartPhase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/join/kubelet.go","code":"// NewKubeletStartPhase creates a kubeadm workflow phase that start kubelet on a node.\nfunc NewKubeletStartPhase() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"kubelet-start [api-server-endpoint]\",\n\t\tShort: \"Write kubelet settings, certificates and (re)start the kubelet\",\n\t\tLong: \"Write a file with KubeletConfiguration and an environment file with node specific kubelet settings, and then (re)start kubelet.\",\n\t\tRun: runKubeletStartJoinPhase,\n\t\tInheritFlags: []string{\n\t\t\toptions.CfgPath,\n\t\t\toptions.NodeCRISocket,\n\t\t\toptions.NodeName,\n\t\t\toptions.FileDiscovery,\n\t\t\toptions.TokenDiscovery,\n\t\t\toptions.TokenDiscoveryCAHash,\n\t\t\toptions.TokenDiscoverySkipCAHash,\n\t\t\toptions.TLSBootstrapToken,\n\t\t\toptions.TokenStr,\n\t\t\toptions.Patches,\n\t\t\toptions.DryRun,\n\t\t},\n\t}\n}","line":{"from":62,"to":83}} {"id":100000681,"name":"getKubeletStartJoinData","signature":"func getKubeletStartJoinData(c workflow.RunData) (*kubeadmapi.JoinConfiguration, *kubeadmapi.InitConfiguration, *clientcmdapi.Config, error)","file":"cmd/kubeadm/app/cmd/phases/join/kubelet.go","code":"func getKubeletStartJoinData(c workflow.RunData) (*kubeadmapi.JoinConfiguration, *kubeadmapi.InitConfiguration, *clientcmdapi.Config, error) {\n\tdata, ok := c.(JoinData)\n\tif !ok {\n\t\treturn nil, nil, nil, errors.New(\"kubelet-start phase invoked with an invalid data struct\")\n\t}\n\tcfg := data.Cfg()\n\tinitCfg, err := data.InitCfg()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\ttlsBootstrapCfg, err := data.TLSBootstrapCfg()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\treturn cfg, initCfg, tlsBootstrapCfg, nil\n}","line":{"from":85,"to":100}} {"id":100000682,"name":"runKubeletStartJoinPhase","signature":"func runKubeletStartJoinPhase(c workflow.RunData) (returnErr error)","file":"cmd/kubeadm/app/cmd/phases/join/kubelet.go","code":"// runKubeletStartJoinPhase executes the kubelet TLS bootstrap process.\n// This process is executed by the kubelet and completes with the node joining the cluster\n// with a dedicates set of credentials as required by the node authorizer\nfunc runKubeletStartJoinPhase(c workflow.RunData) (returnErr error) {\n\tcfg, initCfg, tlsBootstrapCfg, err := getKubeletStartJoinData(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdata, ok := c.(JoinData)\n\tif !ok {\n\t\treturn errors.New(\"kubelet-start phase invoked with an invalid data struct\")\n\t}\n\tbootstrapKubeConfigFile := filepath.Join(data.KubeConfigDir(), kubeadmconstants.KubeletBootstrapKubeConfigFileName)\n\n\t// Deletes the bootstrapKubeConfigFile, so the credential used for TLS bootstrap is removed from disk\n\tdefer os.Remove(bootstrapKubeConfigFile)\n\n\t// Write the bootstrap kubelet config file or the TLS-Bootstrapped kubelet config file down to disk\n\tklog.V(1).Infof(\"[kubelet-start] writing bootstrap kubelet config file at %s\", bootstrapKubeConfigFile)\n\tif err := kubeconfigutil.WriteToDisk(bootstrapKubeConfigFile, tlsBootstrapCfg); err != nil {\n\t\treturn errors.Wrap(err, \"couldn't save bootstrap-kubelet.conf to disk\")\n\t}\n\n\t// Write the ca certificate to disk so kubelet can use it for authentication\n\tcluster := tlsBootstrapCfg.Contexts[tlsBootstrapCfg.CurrentContext].Cluster\n\n\t// If we're dry-running, write ca cert in tmp\n\tcaPath := cfg.CACertPath\n\tif data.DryRun() {\n\t\tcaPath = filepath.Join(data.CertificateWriteDir(), kubeadmconstants.CACertName)\n\t}\n\n\tif _, err := os.Stat(caPath); os.IsNotExist(err) {\n\t\tklog.V(1).Infof(\"[kubelet-start] writing CA certificate at %s\", caPath)\n\t\tif err := certutil.WriteCert(caPath, tlsBootstrapCfg.Clusters[cluster].CertificateAuthorityData); err != nil {\n\t\t\treturn errors.Wrap(err, \"couldn't save the CA certificate to disk\")\n\t\t}\n\t}\n\n\tbootstrapClient, err := kubeconfigutil.ClientSetFromFile(bootstrapKubeConfigFile)\n\tif err != nil {\n\t\treturn errors.Errorf(\"couldn't create client from kubeconfig file %q\", bootstrapKubeConfigFile)\n\t}\n\n\t// Obtain the name of this Node.\n\tnodeName, _, err := kubeletphase.GetNodeNameAndHostname(\u0026cfg.NodeRegistration)\n\tif err != nil {\n\t\tklog.Warning(err)\n\t}\n\n\t// Make sure to exit before TLS bootstrap if a Node with the same name exist in the cluster\n\t// and it has the \"Ready\" status.\n\t// A new Node with the same name as an existing control-plane Node can cause undefined\n\t// behavior and ultimately control-plane failure.\n\tklog.V(1).Infof(\"[kubelet-start] Checking for an existing Node in the cluster with name %q and status %q\", nodeName, v1.NodeReady)\n\tnode, err := bootstrapClient.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{})\n\tif err != nil \u0026\u0026 !apierrors.IsNotFound(err) {\n\t\treturn errors.Wrapf(err, \"cannot get Node %q\", nodeName)\n\t}\n\tfor _, cond := range node.Status.Conditions {\n\t\tif cond.Type == v1.NodeReady \u0026\u0026 cond.Status == v1.ConditionTrue {\n\t\t\treturn errors.Errorf(\"a Node with name %q and status %q already exists in the cluster. \"+\n\t\t\t\t\"You must delete the existing Node or change the name of this new joining Node\", nodeName, v1.NodeReady)\n\t\t}\n\t}\n\n\t// Configure the kubelet. In this short timeframe, kubeadm is trying to stop/restart the kubelet\n\t// Try to stop the kubelet service so no race conditions occur when configuring it\n\tif !data.DryRun() {\n\t\tklog.V(1).Infoln(\"[kubelet-start] Stopping the kubelet\")\n\t\tkubeletphase.TryStopKubelet()\n\t} else {\n\t\tfmt.Println(\"[kubelet-start] Would stop the kubelet\")\n\t}\n\n\t// Write the configuration for the kubelet (using the bootstrap token credentials) to disk so the kubelet can start\n\tif err := kubeletphase.WriteConfigToDisk(\u0026initCfg.ClusterConfiguration, data.KubeletDir(), data.PatchesDir(), data.OutputWriter()); err != nil {\n\t\treturn err\n\t}\n\n\t// Write env file with flags for the kubelet to use. We only want to\n\t// register the joining node with the specified taints if the node\n\t// is not a control-plane. The mark-control-plane phase will register the taints otherwise.\n\tregisterTaintsUsingFlags := cfg.ControlPlane == nil\n\tif err := kubeletphase.WriteKubeletDynamicEnvFile(\u0026initCfg.ClusterConfiguration, \u0026initCfg.NodeRegistration, registerTaintsUsingFlags, data.KubeletDir()); err != nil {\n\t\treturn err\n\t}\n\n\tif data.DryRun() {\n\t\tfmt.Println(\"[kubelet-start] Would start the kubelet\")\n\t\t// If we're dry-running, print the kubelet config manifests and print static pod manifests if joining a control plane.\n\t\t// TODO: think of a better place to move this call - e.g. a hidden phase.\n\t\tif err := dryrunutil.PrintFilesIfDryRunning(cfg.ControlPlane != nil, data.ManifestDir(), data.OutputWriter()); err != nil {\n\t\t\treturn errors.Wrap(err, \"error printing files on dryrun\")\n\t\t}\n\t\treturn nil\n\t}\n\n\t// Try to start the kubelet service in case it's inactive\n\tfmt.Println(\"[kubelet-start] Starting the kubelet\")\n\tkubeletphase.TryStartKubelet()\n\n\t// Now the kubelet will perform the TLS Bootstrap, transforming /etc/kubernetes/bootstrap-kubelet.conf to /etc/kubernetes/kubelet.conf\n\t// Wait for the kubelet to create the /etc/kubernetes/kubelet.conf kubeconfig file. If this process\n\t// times out, display a somewhat user-friendly message.\n\twaiter := apiclient.NewKubeWaiter(nil, kubeadmconstants.TLSBootstrapTimeout, os.Stdout)\n\tif err := waiter.WaitForKubeletAndFunc(waitForTLSBootstrappedClient); err != nil {\n\t\tfmt.Printf(kubeadmJoinFailMsg, err)\n\t\treturn err\n\t}\n\n\t// When we know the /etc/kubernetes/kubelet.conf file is available, get the client\n\tclient, err := kubeconfigutil.ClientSetFromFile(kubeadmconstants.GetKubeletKubeConfigPath())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tklog.V(1).Infoln(\"[kubelet-start] preserving the crisocket information for the node\")\n\tif err := patchnodephase.AnnotateCRISocket(client, cfg.NodeRegistration.Name, cfg.NodeRegistration.CRISocket); err != nil {\n\t\treturn errors.Wrap(err, \"error uploading crisocket\")\n\t}\n\n\treturn nil\n}","line":{"from":102,"to":226}} {"id":100000683,"name":"waitForTLSBootstrappedClient","signature":"func waitForTLSBootstrappedClient() error","file":"cmd/kubeadm/app/cmd/phases/join/kubelet.go","code":"// waitForTLSBootstrappedClient waits for the /etc/kubernetes/kubelet.conf file to be available\nfunc waitForTLSBootstrappedClient() error {\n\tfmt.Println(\"[kubelet-start] Waiting for the kubelet to perform the TLS Bootstrap...\")\n\n\t// Loop on every falsy return. Return with an error if raised. Exit successfully if true is returned.\n\treturn wait.PollImmediate(kubeadmconstants.TLSBootstrapRetryInterval, kubeadmconstants.TLSBootstrapTimeout, func() (bool, error) {\n\t\t// Check that we can create a client set out of the kubelet kubeconfig. This ensures not\n\t\t// only that the kubeconfig file exists, but that other files required by it also exist (like\n\t\t// client certificate and key)\n\t\t_, err := kubeconfigutil.ClientSetFromFile(kubeadmconstants.GetKubeletKubeConfigPath())\n\t\treturn (err == nil), nil\n\t})\n}","line":{"from":228,"to":240}} {"id":100000684,"name":"NewPreflightPhase","signature":"func NewPreflightPhase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/join/preflight.go","code":"// NewPreflightPhase creates a kubeadm workflow phase that implements preflight checks for a new node join\nfunc NewPreflightPhase() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"preflight [api-server-endpoint]\",\n\t\tShort: \"Run join pre-flight checks\",\n\t\tLong: \"Run pre-flight checks for kubeadm join.\",\n\t\tExample: preflightExample,\n\t\tRun: runPreflight,\n\t\tInheritFlags: []string{\n\t\t\toptions.CfgPath,\n\t\t\toptions.IgnorePreflightErrors,\n\t\t\toptions.TLSBootstrapToken,\n\t\t\toptions.TokenStr,\n\t\t\toptions.ControlPlane,\n\t\t\toptions.APIServerAdvertiseAddress,\n\t\t\toptions.APIServerBindPort,\n\t\t\toptions.NodeCRISocket,\n\t\t\toptions.NodeName,\n\t\t\toptions.FileDiscovery,\n\t\t\toptions.TokenDiscovery,\n\t\t\toptions.TokenDiscoveryCAHash,\n\t\t\toptions.TokenDiscoverySkipCAHash,\n\t\t\toptions.CertificateKey,\n\t\t\toptions.DryRun,\n\t\t},\n\t}\n}","line":{"from":56,"to":82}} {"id":100000685,"name":"runPreflight","signature":"func runPreflight(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/join/preflight.go","code":"// runPreflight executes preflight checks logic.\nfunc runPreflight(c workflow.RunData) error {\n\tj, ok := c.(JoinData)\n\tif !ok {\n\t\treturn errors.New(\"preflight phase invoked with an invalid data struct\")\n\t}\n\tfmt.Println(\"[preflight] Running pre-flight checks\")\n\n\t// Start with general checks\n\tklog.V(1).Infoln(\"[preflight] Running general checks\")\n\tif err := preflight.RunJoinNodeChecks(utilsexec.New(), j.Cfg(), j.IgnorePreflightErrors()); err != nil {\n\t\treturn err\n\t}\n\n\tinitCfg, err := j.InitCfg()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Continue with more specific checks based on the init configuration\n\tklog.V(1).Infoln(\"[preflight] Running configuration dependant checks\")\n\tif j.Cfg().ControlPlane != nil {\n\t\t// Checks if the cluster configuration supports\n\t\t// joining a new control plane instance and if all the necessary certificates are provided\n\t\thasCertificateKey := len(j.CertificateKey()) \u003e 0\n\t\tif err := checkIfReadyForAdditionalControlPlane(\u0026initCfg.ClusterConfiguration, hasCertificateKey); err != nil {\n\t\t\t// outputs the not ready for hosting a new control plane instance message\n\t\t\tctx := map[string]string{\n\t\t\t\t\"Error\": err.Error(),\n\t\t\t}\n\n\t\t\tvar msg bytes.Buffer\n\t\t\tnotReadyToJoinControlPlaneTemp.Execute(\u0026msg, ctx)\n\t\t\treturn errors.New(msg.String())\n\t\t}\n\n\t\t// run kubeadm init preflight checks for checking all the prerequisites\n\t\tfmt.Println(\"[preflight] Running pre-flight checks before initializing the new control plane instance\")\n\n\t\tif err := preflight.RunInitNodeChecks(utilsexec.New(), initCfg, j.IgnorePreflightErrors(), true, hasCertificateKey); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif j.DryRun() {\n\t\t\tfmt.Println(\"[preflight] Would pull the required images (like 'kubeadm config images pull')\")\n\t\t\treturn nil\n\t\t}\n\n\t\tfmt.Println(\"[preflight] Pulling images required for setting up a Kubernetes cluster\")\n\t\tfmt.Println(\"[preflight] This might take a minute or two, depending on the speed of your internet connection\")\n\t\tfmt.Println(\"[preflight] You can also perform this action in beforehand using 'kubeadm config images pull'\")\n\t\tif err := preflight.RunPullImagesCheck(utilsexec.New(), initCfg, j.IgnorePreflightErrors()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":84,"to":140}} {"id":100000686,"name":"checkIfReadyForAdditionalControlPlane","signature":"func checkIfReadyForAdditionalControlPlane(initConfiguration *kubeadmapi.ClusterConfiguration, hasCertificateKey bool) error","file":"cmd/kubeadm/app/cmd/phases/join/preflight.go","code":"// checkIfReadyForAdditionalControlPlane ensures that the cluster is in a state that supports\n// joining an additional control plane instance and if the node is ready to preflight\nfunc checkIfReadyForAdditionalControlPlane(initConfiguration *kubeadmapi.ClusterConfiguration, hasCertificateKey bool) error {\n\t// blocks if the cluster was created without a stable control plane endpoint\n\tif initConfiguration.ControlPlaneEndpoint == \"\" {\n\t\treturn errors.New(\"unable to add a new control plane instance to a cluster that doesn't have a stable controlPlaneEndpoint address\")\n\t}\n\n\tif !hasCertificateKey {\n\t\t// checks if the certificates are provided and are still valid, not expired yet.\n\t\tif ret, err := certs.SharedCertificateExists(initConfiguration); !ret {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":142,"to":158}} {"id":100000687,"name":"NewCleanupNodePhase","signature":"func NewCleanupNodePhase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/reset/cleanupnode.go","code":"// NewCleanupNodePhase creates a kubeadm workflow phase that cleanup the node\nfunc NewCleanupNodePhase() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"cleanup-node\",\n\t\tAliases: []string{\"cleanupnode\"},\n\t\tShort: \"Run cleanup node.\",\n\t\tRun: runCleanupNode,\n\t\tInheritFlags: []string{\n\t\t\toptions.CertificatesDir,\n\t\t\toptions.NodeCRISocket,\n\t\t\toptions.CleanupTmpDir,\n\t\t\toptions.DryRun,\n\t\t},\n\t}\n}","line":{"from":41,"to":55}} {"id":100000688,"name":"runCleanupNode","signature":"func runCleanupNode(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/reset/cleanupnode.go","code":"func runCleanupNode(c workflow.RunData) error {\n\tdirsToClean := []string{filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.ManifestsSubDirName)}\n\tr, ok := c.(resetData)\n\tif !ok {\n\t\treturn errors.New(\"cleanup-node phase invoked with an invalid data struct\")\n\t}\n\tcertsDir := r.CertificatesDir()\n\n\t// Try to stop the kubelet service\n\tklog.V(1).Infoln(\"[reset] Getting init system\")\n\tinitSystem, err := initsystem.GetInitSystem()\n\tif err != nil {\n\t\tklog.Warningln(\"[reset] The kubelet service could not be stopped by kubeadm. Unable to detect a supported init system!\")\n\t\tklog.Warningln(\"[reset] Please ensure kubelet is stopped manually\")\n\t} else {\n\t\tif !r.DryRun() {\n\t\t\tfmt.Println(\"[reset] Stopping the kubelet service\")\n\t\t\tif err := initSystem.ServiceStop(\"kubelet\"); err != nil {\n\t\t\t\tklog.Warningf(\"[reset] The kubelet service could not be stopped by kubeadm: [%v]\\n\", err)\n\t\t\t\tklog.Warningln(\"[reset] Please ensure kubelet is stopped manually\")\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Println(\"[reset] Would stop the kubelet service\")\n\t\t}\n\t}\n\n\tif !r.DryRun() {\n\t\t// Try to unmount mounted directories under kubeadmconstants.KubeletRunDirectory in order to be able to remove the kubeadmconstants.KubeletRunDirectory directory later\n\t\tfmt.Printf(\"[reset] Unmounting mounted directories in %q\\n\", kubeadmconstants.KubeletRunDirectory)\n\t\t// In case KubeletRunDirectory holds a symbolic link, evaluate it\n\t\tkubeletRunDir, err := absoluteKubeletRunDirectory()\n\t\tif err == nil {\n\t\t\t// Only clean absoluteKubeletRunDirectory if umountDirsCmd passed without error\n\t\t\tdirsToClean = append(dirsToClean, kubeletRunDir)\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"[reset] Would unmount mounted directories in %q\\n\", kubeadmconstants.KubeletRunDirectory)\n\t}\n\n\tif !r.DryRun() {\n\t\tklog.V(1).Info(\"[reset] Removing Kubernetes-managed containers\")\n\t\tif err := removeContainers(utilsexec.New(), r.CRISocketPath()); err != nil {\n\t\t\tklog.Warningf(\"[reset] Failed to remove containers: %v\\n\", err)\n\t\t}\n\t} else {\n\t\tfmt.Println(\"[reset] Would remove Kubernetes-managed containers\")\n\t}\n\n\t// Remove contents from the config and pki directories\n\tif certsDir != kubeadmapiv1.DefaultCertificatesDir {\n\t\tklog.Warningf(\"[reset] WARNING: Cleaning a non-default certificates directory: %q\\n\", certsDir)\n\t}\n\n\tdirsToClean = append(dirsToClean, certsDir)\n\tif r.CleanupTmpDir() {\n\t\ttempDir := path.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.TempDirForKubeadm)\n\t\tdirsToClean = append(dirsToClean, tempDir)\n\t}\n\tresetConfigDir(kubeadmconstants.KubernetesDir, dirsToClean, r.DryRun())\n\n\tif r.Cfg() != nil \u0026\u0026 features.Enabled(r.Cfg().FeatureGates, features.RootlessControlPlane) {\n\t\tif !r.DryRun() {\n\t\t\tklog.V(1).Infoln(\"[reset] Removing users and groups created for rootless control-plane\")\n\t\t\tif err := users.RemoveUsersAndGroups(); err != nil {\n\t\t\t\tklog.Warningf(\"[reset] Failed to remove users and groups: %v\\n\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Println(\"[reset] Would remove users and groups created for rootless control-plane\")\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":57,"to":129}} {"id":100000689,"name":"absoluteKubeletRunDirectory","signature":"func absoluteKubeletRunDirectory() (string, error)","file":"cmd/kubeadm/app/cmd/phases/reset/cleanupnode.go","code":"func absoluteKubeletRunDirectory() (string, error) {\n\tabsoluteKubeletRunDirectory, err := filepath.EvalSymlinks(kubeadmconstants.KubeletRunDirectory)\n\tif err != nil {\n\t\tklog.Warningf(\"[reset] Failed to evaluate the %q directory. Skipping its unmount and cleanup: %v\\n\", kubeadmconstants.KubeletRunDirectory, err)\n\t\treturn \"\", err\n\t}\n\terr = unmountKubeletDirectory(absoluteKubeletRunDirectory)\n\tif err != nil {\n\t\tklog.Warningf(\"[reset] Failed to unmount mounted directories in %s \\n\", kubeadmconstants.KubeletRunDirectory)\n\t\treturn \"\", err\n\t}\n\treturn absoluteKubeletRunDirectory, nil\n}","line":{"from":131,"to":143}} {"id":100000690,"name":"removeContainers","signature":"func removeContainers(execer utilsexec.Interface, criSocketPath string) error","file":"cmd/kubeadm/app/cmd/phases/reset/cleanupnode.go","code":"func removeContainers(execer utilsexec.Interface, criSocketPath string) error {\n\tcontainerRuntime, err := utilruntime.NewContainerRuntime(execer, criSocketPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcontainers, err := containerRuntime.ListKubeContainers()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn containerRuntime.RemoveContainers(containers)\n}","line":{"from":145,"to":155}} {"id":100000691,"name":"resetConfigDir","signature":"func resetConfigDir(configPathDir string, dirsToClean []string, isDryRun bool)","file":"cmd/kubeadm/app/cmd/phases/reset/cleanupnode.go","code":"// resetConfigDir is used to cleanup the files in the folder defined in dirsToClean.\nfunc resetConfigDir(configPathDir string, dirsToClean []string, isDryRun bool) {\n\tif !isDryRun {\n\t\tfmt.Printf(\"[reset] Deleting contents of directories: %v\\n\", dirsToClean)\n\t\tfor _, dir := range dirsToClean {\n\t\t\tif err := CleanDir(dir); err != nil {\n\t\t\t\tklog.Warningf(\"[reset] Failed to delete contents of %q directory: %v\", dir, err)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"[reset] Would delete contents of directories: %v\\n\", dirsToClean)\n\t}\n\n\tfilesToClean := []string{\n\t\tfilepath.Join(configPathDir, kubeadmconstants.AdminKubeConfigFileName),\n\t\tfilepath.Join(configPathDir, kubeadmconstants.KubeletKubeConfigFileName),\n\t\tfilepath.Join(configPathDir, kubeadmconstants.KubeletBootstrapKubeConfigFileName),\n\t\tfilepath.Join(configPathDir, kubeadmconstants.ControllerManagerKubeConfigFileName),\n\t\tfilepath.Join(configPathDir, kubeadmconstants.SchedulerKubeConfigFileName),\n\t}\n\n\tif !isDryRun {\n\t\tfmt.Printf(\"[reset] Deleting files: %v\\n\", filesToClean)\n\t\tfor _, path := range filesToClean {\n\t\t\tif err := os.RemoveAll(path); err != nil {\n\t\t\t\tklog.Warningf(\"[reset] Failed to remove file: %q [%v]\\n\", path, err)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"[reset] Would delete files: %v\\n\", filesToClean)\n\t}\n}","line":{"from":157,"to":188}} {"id":100000692,"name":"CleanDir","signature":"func CleanDir(filePath string) error","file":"cmd/kubeadm/app/cmd/phases/reset/cleanupnode.go","code":"// CleanDir removes everything in a directory, but not the directory itself\nfunc CleanDir(filePath string) error {\n\t// If the directory doesn't even exist there's nothing to do, and we do\n\t// not consider this an error\n\tif _, err := os.Stat(filePath); os.IsNotExist(err) {\n\t\treturn nil\n\t}\n\n\td, err := os.Open(filePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer d.Close()\n\tnames, err := d.Readdirnames(-1)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, name := range names {\n\t\tif err = os.RemoveAll(filepath.Join(filePath, name)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":190,"to":213}} {"id":100000693,"name":"IsDirEmpty","signature":"func IsDirEmpty(dir string) (bool, error)","file":"cmd/kubeadm/app/cmd/phases/reset/cleanupnode.go","code":"func IsDirEmpty(dir string) (bool, error) {\n\td, err := os.Open(dir)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer d.Close()\n\t_, err = d.Readdirnames(1)\n\tif err == io.EOF {\n\t\treturn true, nil\n\t}\n\treturn false, nil\n}","line":{"from":215,"to":226}} {"id":100000694,"name":"NewPreflightPhase","signature":"func NewPreflightPhase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/reset/preflight.go","code":"// NewPreflightPhase creates a kubeadm workflow phase implements preflight checks for reset\nfunc NewPreflightPhase() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"preflight\",\n\t\tAliases: []string{\"pre-flight\"},\n\t\tShort: \"Run reset pre-flight checks\",\n\t\tLong: \"Run pre-flight checks for kubeadm reset.\",\n\t\tRun: runPreflight,\n\t\tInheritFlags: []string{\n\t\t\toptions.IgnorePreflightErrors,\n\t\t\toptions.ForceReset,\n\t\t\toptions.DryRun,\n\t\t},\n\t}\n}","line":{"from":32,"to":46}} {"id":100000695,"name":"runPreflight","signature":"func runPreflight(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/reset/preflight.go","code":"// runPreflight executes preflight checks logic.\nfunc runPreflight(c workflow.RunData) error {\n\tr, ok := c.(resetData)\n\tif !ok {\n\t\treturn errors.New(\"preflight phase invoked with an invalid data struct\")\n\t}\n\n\tif !r.ForceReset() \u0026\u0026 !r.DryRun() {\n\t\tklog.Warning(\"[reset] WARNING: Changes made to this host by 'kubeadm init' or 'kubeadm join' will be reverted.\")\n\t\tif err := util.InteractivelyConfirmAction(\"reset\", \"Are you sure you want to proceed?\", r.InputReader()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfmt.Println(\"[preflight] Running pre-flight checks\")\n\treturn preflight.RunRootCheckOnly(r.IgnorePreflightErrors())\n}","line":{"from":48,"to":64}} {"id":100000696,"name":"NewRemoveETCDMemberPhase","signature":"func NewRemoveETCDMemberPhase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/reset/removeetcdmember.go","code":"// NewRemoveETCDMemberPhase creates a kubeadm workflow phase for remove-etcd-member\nfunc NewRemoveETCDMemberPhase() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"remove-etcd-member\",\n\t\tShort: \"Remove a local etcd member.\",\n\t\tLong: \"Remove a local etcd member for a control plane node.\",\n\t\tRun: runRemoveETCDMemberPhase,\n\t\tInheritFlags: []string{\n\t\t\toptions.KubeconfigPath,\n\t\t\toptions.DryRun,\n\t\t},\n\t}\n}","line":{"from":38,"to":50}} {"id":100000697,"name":"runRemoveETCDMemberPhase","signature":"func runRemoveETCDMemberPhase(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/reset/removeetcdmember.go","code":"func runRemoveETCDMemberPhase(c workflow.RunData) error {\n\tr, ok := c.(resetData)\n\tif !ok {\n\t\treturn errors.New(\"remove-etcd-member-phase phase invoked with an invalid data struct\")\n\t}\n\tcfg := r.Cfg()\n\n\t// Only clear etcd data when using local etcd.\n\tklog.V(1).Infoln(\"[reset] Checking for etcd config\")\n\tetcdManifestPath := filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.ManifestsSubDirName, \"etcd.yaml\")\n\tetcdDataDir, err := getEtcdDataDir(etcdManifestPath, cfg)\n\tif err == nil {\n\t\tif cfg != nil {\n\t\t\tif !r.DryRun() {\n\t\t\t\terr := etcdphase.RemoveStackedEtcdMemberFromCluster(r.Client(), cfg)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Warningf(\"[reset] Failed to remove etcd member: %v, please manually remove this etcd member using etcdctl\", err)\n\t\t\t\t} else {\n\t\t\t\t\tif err := CleanDir(etcdDataDir); err != nil {\n\t\t\t\t\t\tklog.Warningf(\"[reset] Failed to delete contents of the etcd directory: %q, error: %v\", etcdDataDir, err)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfmt.Printf(\"[reset] Deleted contents of the etcd data directory: %v\\n\", etcdDataDir)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"[reset] Would remove the etcd member on this node from the etcd cluster\")\n\t\t\t\tfmt.Printf(\"[reset] Would delete contents of the etcd data directory: %v\\n\", etcdDataDir)\n\t\t\t}\n\t\t}\n\t\t// This could happen if the phase `cleanup-node` is run before the `remove-etcd-member`.\n\t\t// Cleanup the data in the etcd data dir to avoid some stale files which might cause the failure to build cluster in the next time.\n\t\tempty, _ := IsDirEmpty(etcdDataDir)\n\t\tif !empty \u0026\u0026 !r.DryRun() {\n\t\t\tif err := CleanDir(etcdDataDir); err != nil {\n\t\t\t\tklog.Warningf(\"[reset] Failed to delete contents of the etcd directory: %q, error: %v\", etcdDataDir, err)\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"[reset] Deleted contents of the etcd data directory: %v\\n\", etcdDataDir)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfmt.Println(\"[reset] No etcd config found. Assuming external etcd\")\n\t\tfmt.Println(\"[reset] Please, manually reset etcd to prevent further issues\")\n\t}\n\n\treturn nil\n}","line":{"from":52,"to":97}} {"id":100000698,"name":"getEtcdDataDir","signature":"func getEtcdDataDir(manifestPath string, cfg *kubeadmapi.InitConfiguration) (string, error)","file":"cmd/kubeadm/app/cmd/phases/reset/removeetcdmember.go","code":"func getEtcdDataDir(manifestPath string, cfg *kubeadmapi.InitConfiguration) (string, error) {\n\tconst etcdVolumeName = \"etcd-data\"\n\tvar dataDir string\n\n\tif cfg != nil \u0026\u0026 cfg.Etcd.Local != nil {\n\t\treturn cfg.Etcd.Local.DataDir, nil\n\t}\n\tklog.Warningln(\"[reset] No kubeadm config, using etcd pod spec to get data directory\")\n\n\tif _, err := os.Stat(manifestPath); os.IsNotExist(err) {\n\t\t// Fall back to use the default cluster config if etcd.yaml doesn't exist, this could happen that\n\t\t// etcd.yaml is removed by other reset phases, e.g. cleanup-node.\n\t\tcfg := \u0026v1beta3.ClusterConfiguration{}\n\t\tscheme.Scheme.Default(cfg)\n\t\treturn cfg.Etcd.Local.DataDir, nil\n\t}\n\tetcdPod, err := utilstaticpod.ReadStaticPodFromDisk(manifestPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfor _, volumeMount := range etcdPod.Spec.Volumes {\n\t\tif volumeMount.Name == etcdVolumeName {\n\t\t\tdataDir = volumeMount.HostPath.Path\n\t\t\tbreak\n\t\t}\n\t}\n\tif dataDir == \"\" {\n\t\treturn dataDir, errors.New(\"invalid etcd pod manifest\")\n\t}\n\treturn dataDir, nil\n}","line":{"from":99,"to":129}} {"id":100000699,"name":"unmountKubeletDirectory","signature":"func unmountKubeletDirectory(absoluteKubeletRunDirectory string) error","file":"cmd/kubeadm/app/cmd/phases/reset/unmount.go","code":"// unmountKubeletDirectory is a NOOP on all but linux.\nfunc unmountKubeletDirectory(absoluteKubeletRunDirectory string) error {\n\tklog.Warning(\"Cannot unmount filesystems on current OS, all mounted file systems will need to be manually unmounted\")\n\treturn nil\n}","line":{"from":26,"to":30}} {"id":100000700,"name":"unmountKubeletDirectory","signature":"func unmountKubeletDirectory(absoluteKubeletRunDirectory string) error","file":"cmd/kubeadm/app/cmd/phases/reset/unmount_linux.go","code":"// unmountKubeletDirectory unmounts all paths that contain KubeletRunDirectory\nfunc unmountKubeletDirectory(absoluteKubeletRunDirectory string) error {\n\traw, err := os.ReadFile(\"/proc/mounts\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !strings.HasSuffix(absoluteKubeletRunDirectory, \"/\") {\n\t\t// trailing \"/\" is needed to ensure that possibly mounted /var/lib/kubelet is skipped\n\t\tabsoluteKubeletRunDirectory += \"/\"\n\t}\n\n\tmounts := strings.Split(string(raw), \"\\n\")\n\tfor _, mount := range mounts {\n\t\tm := strings.Split(mount, \" \")\n\t\tif len(m) \u003c 2 || !strings.HasPrefix(m[1], absoluteKubeletRunDirectory) {\n\t\t\tcontinue\n\t\t}\n\t\tif err := syscall.Unmount(m[1], 0); err != nil {\n\t\t\tklog.Warningf(\"[reset] Failed to unmount mounted directory in %s: %s\", absoluteKubeletRunDirectory, m[1])\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":30,"to":53}} {"id":100000701,"name":"NewControlPlane","signature":"func NewControlPlane() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/upgrade/node/controlplane.go","code":"// NewControlPlane creates a kubeadm workflow phase that implements handling of control-plane upgrade.\nfunc NewControlPlane() workflow.Phase {\n\tphase := workflow.Phase{\n\t\tName: \"control-plane\",\n\t\tShort: \"Upgrade the control plane instance deployed on this node, if any\",\n\t\tRun: runControlPlane(),\n\t\tInheritFlags: []string{\n\t\t\toptions.DryRun,\n\t\t\toptions.KubeconfigPath,\n\t\t\toptions.CertificateRenewal,\n\t\t\toptions.EtcdUpgrade,\n\t\t\toptions.Patches,\n\t\t},\n\t}\n\treturn phase\n}","line":{"from":31,"to":46}} {"id":100000702,"name":"runControlPlane","signature":"func runControlPlane() func(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/upgrade/node/controlplane.go","code":"func runControlPlane() func(c workflow.RunData) error {\n\treturn func(c workflow.RunData) error {\n\t\tdata, ok := c.(Data)\n\t\tif !ok {\n\t\t\treturn errors.New(\"control-plane phase invoked with an invalid data struct\")\n\t\t}\n\n\t\t// if this is not a control-plane node, this phase should not be executed\n\t\tif !data.IsControlPlaneNode() {\n\t\t\tfmt.Println(\"[upgrade] Skipping phase. Not a control plane node.\")\n\t\t\treturn nil\n\t\t}\n\n\t\t// otherwise, retrieve all the info required for control plane upgrade\n\t\tcfg := data.Cfg()\n\t\tclient := data.Client()\n\t\tdryRun := data.DryRun()\n\t\tetcdUpgrade := data.EtcdUpgrade()\n\t\trenewCerts := data.RenewCerts()\n\t\tpatchesDir := data.PatchesDir()\n\n\t\t// Upgrade the control plane and etcd if installed on this node\n\t\tfmt.Printf(\"[upgrade] Upgrading your Static Pod-hosted control plane instance to version %q...\\n\", cfg.KubernetesVersion)\n\t\tif dryRun {\n\t\t\treturn upgrade.DryRunStaticPodUpgrade(patchesDir, cfg)\n\t\t}\n\n\t\twaiter := apiclient.NewKubeWaiter(data.Client(), upgrade.UpgradeManifestTimeout, os.Stdout)\n\n\t\tif err := upgrade.PerformStaticPodUpgrade(client, waiter, cfg, etcdUpgrade, renewCerts, patchesDir); err != nil {\n\t\t\treturn errors.Wrap(err, \"couldn't complete the static pod upgrade\")\n\t\t}\n\n\t\tfmt.Println(\"[upgrade] The control plane instance for this node was successfully updated!\")\n\n\t\treturn nil\n\t}\n}","line":{"from":48,"to":85}} {"id":100000703,"name":"NewKubeletConfigPhase","signature":"func NewKubeletConfigPhase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/upgrade/node/kubeletconfig.go","code":"// NewKubeletConfigPhase creates a kubeadm workflow phase that implements handling of kubelet-config upgrade.\nfunc NewKubeletConfigPhase() workflow.Phase {\n\tphase := workflow.Phase{\n\t\tName: \"kubelet-config\",\n\t\tShort: \"Upgrade the kubelet configuration for this node\",\n\t\tLong: kubeletConfigLongDesc,\n\t\tRun: runKubeletConfigPhase(),\n\t\tInheritFlags: []string{\n\t\t\toptions.DryRun,\n\t\t\toptions.KubeconfigPath,\n\t\t\toptions.Patches,\n\t\t},\n\t}\n\treturn phase\n}","line":{"from":36,"to":50}} {"id":100000704,"name":"runKubeletConfigPhase","signature":"func runKubeletConfigPhase() func(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/upgrade/node/kubeletconfig.go","code":"func runKubeletConfigPhase() func(c workflow.RunData) error {\n\treturn func(c workflow.RunData) error {\n\t\tdata, ok := c.(Data)\n\t\tif !ok {\n\t\t\treturn errors.New(\"kubelet-config phase invoked with an invalid data struct\")\n\t\t}\n\n\t\t// otherwise, retrieve all the info required for kubelet config upgrade\n\t\tcfg := data.Cfg()\n\t\tdryRun := data.DryRun()\n\n\t\t// Write the configuration for the kubelet down to disk and print the generated manifests instead if dry-running.\n\t\t// If not dry-running, the kubelet config file will be backed up to /etc/kubernetes/tmp/ dir, so that it could be\n\t\t// recovered if there is anything goes wrong.\n\t\terr := upgrade.WriteKubeletConfigFiles(cfg, data.PatchesDir(), dryRun, data.OutputWriter())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Println(\"[upgrade] The configuration for this node was successfully updated!\")\n\t\tfmt.Println(\"[upgrade] Now you should go ahead and upgrade the kubelet package using your package manager.\")\n\t\treturn nil\n\t}\n}","line":{"from":52,"to":75}} {"id":100000705,"name":"NewPreflightPhase","signature":"func NewPreflightPhase() workflow.Phase","file":"cmd/kubeadm/app/cmd/phases/upgrade/node/preflight.go","code":"// NewPreflightPhase creates a kubeadm workflow phase that implements preflight checks for a new node join\nfunc NewPreflightPhase() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"preflight\",\n\t\tShort: \"Run upgrade node pre-flight checks\",\n\t\tLong: \"Run pre-flight checks for kubeadm upgrade node.\",\n\t\tRun: runPreflight,\n\t\tInheritFlags: []string{\n\t\t\toptions.IgnorePreflightErrors,\n\t\t},\n\t}\n}","line":{"from":31,"to":42}} {"id":100000706,"name":"runPreflight","signature":"func runPreflight(c workflow.RunData) error","file":"cmd/kubeadm/app/cmd/phases/upgrade/node/preflight.go","code":"// runPreflight executes preflight checks logic.\nfunc runPreflight(c workflow.RunData) error {\n\tdata, ok := c.(Data)\n\tif !ok {\n\t\treturn errors.New(\"preflight phase invoked with an invalid data struct\")\n\t}\n\tfmt.Println(\"[preflight] Running pre-flight checks\")\n\n\t// First, check if we're root separately from the other preflight checks and fail fast\n\tif err := preflight.RunRootCheckOnly(data.IgnorePreflightErrors()); err != nil {\n\t\treturn err\n\t}\n\n\t// if this is a control-plane node, pull the basic images\n\tif data.IsControlPlaneNode() {\n\t\tif !data.DryRun() {\n\t\t\tfmt.Println(\"[preflight] Pulling images required for setting up a Kubernetes cluster\")\n\t\t\tfmt.Println(\"[preflight] This might take a minute or two, depending on the speed of your internet connection\")\n\t\t\tfmt.Println(\"[preflight] You can also perform this action in beforehand using 'kubeadm config images pull'\")\n\t\t\tif err := preflight.RunPullImagesCheck(utilsexec.New(), data.Cfg(), data.IgnorePreflightErrors()); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Println(\"[preflight] Would pull the required images (like 'kubeadm config images pull')\")\n\t\t}\n\t} else {\n\t\tfmt.Println(\"[preflight] Skipping prepull. Not a control plane node.\")\n\t\treturn nil\n\t}\n\n\treturn nil\n}","line":{"from":44,"to":75}} {"id":100000707,"name":"SetKubernetesVersion","signature":"func SetKubernetesVersion(cfg *kubeadmapiv1.ClusterConfiguration)","file":"cmd/kubeadm/app/cmd/phases/util.go","code":"// SetKubernetesVersion gets the current Kubeadm version and sets it as KubeadmVersion in the config,\n// unless it's already set to a value different from the default.\nfunc SetKubernetesVersion(cfg *kubeadmapiv1.ClusterConfiguration) {\n\n\tif cfg.KubernetesVersion != kubeadmapiv1.DefaultKubernetesVersion \u0026\u0026 cfg.KubernetesVersion != \"\" {\n\t\treturn\n\t}\n\tcfg.KubernetesVersion = version.Get().String()\n}","line":{"from":25,"to":33}} {"id":100000708,"name":"AppendPhase","signature":"func (t *Phase) AppendPhase(phase Phase)","file":"cmd/kubeadm/app/cmd/phases/workflow/phase.go","code":"// AppendPhase adds the given phase to the nested, ordered sequence of phases.\nfunc (t *Phase) AppendPhase(phase Phase) {\n\tt.Phases = append(t.Phases, phase)\n}","line":{"from":86,"to":89}} {"id":100000709,"name":"NewRunner","signature":"func NewRunner() *Runner","file":"cmd/kubeadm/app/cmd/phases/workflow/runner.go","code":"// NewRunner return a new runner for composable kubeadm workflows.\nfunc NewRunner() *Runner {\n\treturn \u0026Runner{\n\t\tPhases: []Phase{},\n\t}\n}","line":{"from":103,"to":108}} {"id":100000710,"name":"AppendPhase","signature":"func (e *Runner) AppendPhase(t Phase)","file":"cmd/kubeadm/app/cmd/phases/workflow/runner.go","code":"// AppendPhase adds the given phase to the ordered sequence of phases managed by the runner.\nfunc (e *Runner) AppendPhase(t Phase) {\n\te.Phases = append(e.Phases, t)\n}","line":{"from":110,"to":113}} {"id":100000711,"name":"computePhaseRunFlags","signature":"func (e *Runner) computePhaseRunFlags() (map[string]bool, error)","file":"cmd/kubeadm/app/cmd/phases/workflow/runner.go","code":"// computePhaseRunFlags return a map defining which phase should be run and which not.\n// PhaseRunFlags are computed according to RunnerOptions.\nfunc (e *Runner) computePhaseRunFlags() (map[string]bool, error) {\n\t// Initialize support data structure\n\tphaseRunFlags := map[string]bool{}\n\tphaseHierarchy := map[string][]string{}\n\te.visitAll(func(p *phaseRunner) error {\n\t\t// Initialize phaseRunFlags assuming that all the phases should be run.\n\t\tphaseRunFlags[p.generatedName] = true\n\n\t\t// Initialize phaseHierarchy for the current phase (the list of phases\n\t\t// depending on the current phase\n\t\tphaseHierarchy[p.generatedName] = []string{}\n\n\t\t// Register current phase as part of its own parent hierarchy\n\t\tparent := p.parent\n\t\tfor parent != nil {\n\t\t\tphaseHierarchy[parent.generatedName] = append(phaseHierarchy[parent.generatedName], p.generatedName)\n\t\t\tparent = parent.parent\n\t\t}\n\t\treturn nil\n\t})\n\n\t// If a filter option is specified, set all phaseRunFlags to false except for\n\t// the phases included in the filter and their hierarchy of nested phases.\n\tif len(e.Options.FilterPhases) \u003e 0 {\n\t\tfor i := range phaseRunFlags {\n\t\t\tphaseRunFlags[i] = false\n\t\t}\n\t\tfor _, f := range e.Options.FilterPhases {\n\t\t\tif _, ok := phaseRunFlags[f]; !ok {\n\t\t\t\treturn phaseRunFlags, errors.Errorf(\"invalid phase name: %s\", f)\n\t\t\t}\n\t\t\tphaseRunFlags[f] = true\n\t\t\tfor _, c := range phaseHierarchy[f] {\n\t\t\t\tphaseRunFlags[c] = true\n\t\t\t}\n\t\t}\n\t}\n\n\t// If a phase skip option is specified, set the corresponding phaseRunFlags\n\t// to false and apply the same change to the underlying hierarchy\n\tfor _, f := range e.Options.SkipPhases {\n\t\tif _, ok := phaseRunFlags[f]; !ok {\n\t\t\treturn phaseRunFlags, errors.Errorf(\"invalid phase name: %s\", f)\n\t\t}\n\t\tphaseRunFlags[f] = false\n\t\tfor _, c := range phaseHierarchy[f] {\n\t\t\tphaseRunFlags[c] = false\n\t\t}\n\t}\n\n\treturn phaseRunFlags, nil\n}","line":{"from":115,"to":168}} {"id":100000712,"name":"SetDataInitializer","signature":"func (e *Runner) SetDataInitializer(builder func(cmd *cobra.Command, args []string) (RunData, error))","file":"cmd/kubeadm/app/cmd/phases/workflow/runner.go","code":"// SetDataInitializer allows to setup a function that initialize the runtime data shared\n// among all the phases included in the workflow.\n// The method will receive in input the cmd that triggers the Runner (only if the runner is BindToCommand)\nfunc (e *Runner) SetDataInitializer(builder func(cmd *cobra.Command, args []string) (RunData, error)) {\n\te.runDataInitializer = builder\n}","line":{"from":170,"to":175}} {"id":100000713,"name":"InitData","signature":"func (e *Runner) InitData(args []string) (RunData, error)","file":"cmd/kubeadm/app/cmd/phases/workflow/runner.go","code":"// InitData triggers the creation of runtime data shared among all the phases included in the workflow.\n// This action can be executed explicitly out, when it is necessary to get the RunData\n// before actually executing Run, or implicitly when invoking Run.\nfunc (e *Runner) InitData(args []string) (RunData, error) {\n\tif e.runData == nil \u0026\u0026 e.runDataInitializer != nil {\n\t\tvar err error\n\t\tif e.runData, err = e.runDataInitializer(e.runCmd, args); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn e.runData, nil\n}","line":{"from":177,"to":189}} {"id":100000714,"name":"Run","signature":"func (e *Runner) Run(args []string) error","file":"cmd/kubeadm/app/cmd/phases/workflow/runner.go","code":"// Run the kubeadm composable kubeadm workflows.\nfunc (e *Runner) Run(args []string) error {\n\te.prepareForExecution()\n\n\t// determine which phase should be run according to RunnerOptions\n\tphaseRunFlags, err := e.computePhaseRunFlags()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// precheck phase dependencies before actual execution\n\tmissedDeps := make(map[string][]string)\n\tvisited := make(map[string]struct{})\n\tfor _, p := range e.phaseRunners {\n\t\tif run, ok := phaseRunFlags[p.generatedName]; !run || !ok {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, dep := range p.Phase.Dependencies {\n\t\t\tif _, ok := visited[dep]; !ok {\n\t\t\t\tmissedDeps[p.Phase.Name] = append(missedDeps[p.Phase.Name], dep)\n\t\t\t}\n\t\t}\n\t\tvisited[p.Phase.Name] = struct{}{}\n\t}\n\tif len(missedDeps) \u003e 0 {\n\t\tvar msg strings.Builder\n\t\tmsg.WriteString(\"unresolved dependencies:\")\n\t\tfor phase, missedPhases := range missedDeps {\n\t\t\tmsg.WriteString(fmt.Sprintf(\"\\n\\tmissing %v phase(s) needed by %q phase\", missedPhases, phase))\n\t\t}\n\t\treturn errors.New(msg.String())\n\t}\n\n\t// builds the runner data if the runtime data is not initialized\n\tdata := e.runData\n\tif data == nil {\n\t\tif data, err = e.InitData(args); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = e.visitAll(func(p *phaseRunner) error {\n\t\t// if the phase should not be run, skip the phase.\n\t\tif run, ok := phaseRunFlags[p.generatedName]; !run || !ok {\n\t\t\treturn nil\n\t\t}\n\n\t\t// Errors if phases that are meant to create special subcommands only\n\t\t// are wrongly assigned Run Methods\n\t\tif p.RunAllSiblings \u0026\u0026 (p.RunIf != nil || p.Run != nil) {\n\t\t\treturn errors.Errorf(\"phase marked as RunAllSiblings can not have Run functions %s\", p.generatedName)\n\t\t}\n\n\t\t// If the phase defines a condition to be checked before executing the phase action.\n\t\tif p.RunIf != nil {\n\t\t\t// Check the condition and returns if the condition isn't satisfied (or fails)\n\t\t\tok, err := p.RunIf(data)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"error execution run condition for phase %s\", p.generatedName)\n\t\t\t}\n\n\t\t\tif !ok {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\t// Runs the phase action (if defined)\n\t\tif p.Run != nil {\n\t\t\tif err := p.Run(data); err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"error execution phase %s\", p.generatedName)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\n\treturn err\n}","line":{"from":191,"to":268}} {"id":100000715,"name":"Help","signature":"func (e *Runner) Help(cmdUse string) string","file":"cmd/kubeadm/app/cmd/phases/workflow/runner.go","code":"// Help returns text with the list of phases included in the workflow.\nfunc (e *Runner) Help(cmdUse string) string {\n\te.prepareForExecution()\n\n\t// computes the max length of for each phase use line\n\tmaxLength := 0\n\te.visitAll(func(p *phaseRunner) error {\n\t\tif !p.Hidden \u0026\u0026 !p.RunAllSiblings {\n\t\t\tlength := len(p.use)\n\t\t\tif maxLength \u003c length {\n\t\t\t\tmaxLength = length\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\n\t// prints the list of phases indented by level and formatted using the maxlength\n\t// the list is enclosed in a mardown code block for ensuring better readability in the public web site\n\tline := fmt.Sprintf(\"The %q command executes the following phases:\\n\", cmdUse)\n\tline += \"```\\n\"\n\toffset := 2\n\te.visitAll(func(p *phaseRunner) error {\n\t\tif !p.Hidden \u0026\u0026 !p.RunAllSiblings {\n\t\t\tpadding := maxLength - len(p.use) + offset\n\t\t\tline += strings.Repeat(\" \", offset*p.level) // indentation\n\t\t\tline += p.use // name + aliases\n\t\t\tline += strings.Repeat(\" \", padding) // padding right up to max length (+ offset for spacing)\n\t\t\tline += p.Short // phase short description\n\t\t\tline += \"\\n\"\n\t\t}\n\n\t\treturn nil\n\t})\n\tline += \"```\"\n\treturn line\n}","line":{"from":270,"to":305}} {"id":100000716,"name":"SetAdditionalFlags","signature":"func (e *Runner) SetAdditionalFlags(fn func(*pflag.FlagSet))","file":"cmd/kubeadm/app/cmd/phases/workflow/runner.go","code":"// SetAdditionalFlags allows to define flags to be added\n// to the subcommands generated for each phase (but not existing in the parent command).\n// Please note that this command needs to be done before BindToCommand.\n// Nb. if a flag is used only by one phase, please consider using phase LocalFlags.\nfunc (e *Runner) SetAdditionalFlags(fn func(*pflag.FlagSet)) {\n\t// creates a new NewFlagSet\n\te.cmdAdditionalFlags = pflag.NewFlagSet(\"phaseAdditionalFlags\", pflag.ContinueOnError)\n\t// invokes the function that sets additional flags\n\tfn(e.cmdAdditionalFlags)\n}","line":{"from":307,"to":316}} {"id":100000717,"name":"BindToCommand","signature":"func (e *Runner) BindToCommand(cmd *cobra.Command)","file":"cmd/kubeadm/app/cmd/phases/workflow/runner.go","code":"// BindToCommand bind the Runner to a cobra command by altering\n// command help, adding phase related flags and by adding phases subcommands\n// Please note that this command needs to be done once all the phases are added to the Runner.\nfunc (e *Runner) BindToCommand(cmd *cobra.Command) {\n\t// keep track of the command triggering the runner\n\te.runCmd = cmd\n\n\t// return early if no phases were added\n\tif len(e.Phases) == 0 {\n\t\treturn\n\t}\n\n\te.prepareForExecution()\n\n\t// adds the phases subcommand\n\tphaseCommand := \u0026cobra.Command{\n\t\tUse: \"phase\",\n\t\tShort: fmt.Sprintf(\"Use this command to invoke single phase of the %s workflow\", cmd.Name()),\n\t}\n\n\tcmd.AddCommand(phaseCommand)\n\n\t// generate all the nested subcommands for invoking single phases\n\tsubcommands := map[string]*cobra.Command{}\n\te.visitAll(func(p *phaseRunner) error {\n\t\t// skip hidden phases\n\t\tif p.Hidden {\n\t\t\treturn nil\n\t\t}\n\n\t\t// initialize phase selector\n\t\tphaseSelector := p.generatedName\n\n\t\t// if requested, set the phase to run all the sibling phases\n\t\tif p.RunAllSiblings {\n\t\t\tphaseSelector = p.parent.generatedName\n\t\t}\n\n\t\t// creates phase subcommand\n\t\tphaseCmd := \u0026cobra.Command{\n\t\t\tUse: strings.ToLower(p.Name),\n\t\t\tShort: p.Short,\n\t\t\tLong: p.Long,\n\t\t\tExample: p.Example,\n\t\t\tAliases: p.Aliases,\n\t\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\t\t// if the phase has subphases, print the help and exits\n\t\t\t\tif len(p.Phases) \u003e 0 {\n\t\t\t\t\treturn cmd.Help()\n\t\t\t\t}\n\n\t\t\t\t// overrides the command triggering the Runner using the phaseCmd\n\t\t\t\te.runCmd = cmd\n\t\t\t\te.Options.FilterPhases = []string{phaseSelector}\n\t\t\t\treturn e.Run(args)\n\t\t\t},\n\t\t}\n\n\t\t// makes the new command inherits local flags from the parent command\n\t\t// Nb. global flags will be inherited automatically\n\t\tinheritsFlags(cmd.Flags(), phaseCmd.Flags(), p.InheritFlags)\n\n\t\t// makes the new command inherits additional flags for phases\n\t\tif e.cmdAdditionalFlags != nil {\n\t\t\tinheritsFlags(e.cmdAdditionalFlags, phaseCmd.Flags(), p.InheritFlags)\n\t\t}\n\n\t\t// If defined, added phase local flags\n\t\tif p.LocalFlags != nil {\n\t\t\tp.LocalFlags.VisitAll(func(f *pflag.Flag) {\n\t\t\t\tphaseCmd.Flags().AddFlag(f)\n\t\t\t})\n\t\t}\n\n\t\t// if this phase has children (not a leaf) it doesn't accept any args\n\t\tif len(p.Phases) \u003e 0 {\n\t\t\tphaseCmd.Args = cobra.NoArgs\n\t\t} else {\n\t\t\tif p.ArgsValidator == nil {\n\t\t\t\tphaseCmd.Args = cmd.Args\n\t\t\t} else {\n\t\t\t\tphaseCmd.Args = p.ArgsValidator\n\t\t\t}\n\t\t}\n\n\t\t// adds the command to parent\n\t\tif p.level == 0 {\n\t\t\tphaseCommand.AddCommand(phaseCmd)\n\t\t} else {\n\t\t\tsubcommands[p.parent.generatedName].AddCommand(phaseCmd)\n\t\t}\n\n\t\tsubcommands[p.generatedName] = phaseCmd\n\t\treturn nil\n\t})\n\n\t// alters the command description to show available phases\n\tif cmd.Long != \"\" {\n\t\tcmd.Long = fmt.Sprintf(\"%s\\n\\n%s\\n\", cmd.Long, e.Help(cmd.Use))\n\t} else {\n\t\tcmd.Long = fmt.Sprintf(\"%s\\n\\n%s\\n\", cmd.Short, e.Help(cmd.Use))\n\t}\n\n\t// adds phase related flags to the main command\n\tcmd.Flags().StringSliceVar(\u0026e.Options.SkipPhases, \"skip-phases\", nil, \"List of phases to be skipped\")\n}","line":{"from":318,"to":423}} {"id":100000718,"name":"inheritsFlags","signature":"func inheritsFlags(sourceFlags, targetFlags *pflag.FlagSet, cmdFlags []string)","file":"cmd/kubeadm/app/cmd/phases/workflow/runner.go","code":"func inheritsFlags(sourceFlags, targetFlags *pflag.FlagSet, cmdFlags []string) {\n\t// If the list of flag to be inherited from the parent command is not defined, no flag is added\n\tif cmdFlags == nil {\n\t\treturn\n\t}\n\n\t// add all the flags to be inherited to the target flagSet\n\tsourceFlags.VisitAll(func(f *pflag.Flag) {\n\t\tfor _, c := range cmdFlags {\n\t\t\tif f.Name == c {\n\t\t\t\ttargetFlags.AddFlag(f)\n\t\t\t}\n\t\t}\n\t})\n}","line":{"from":425,"to":439}} {"id":100000719,"name":"visitAll","signature":"func (e *Runner) visitAll(fn func(*phaseRunner) error) error","file":"cmd/kubeadm/app/cmd/phases/workflow/runner.go","code":"// visitAll provides a utility method for visiting all the phases in the workflow\n// in the execution order and executing a func on each phase.\n// Nested phase are visited immediately after their parent phase.\nfunc (e *Runner) visitAll(fn func(*phaseRunner) error) error {\n\tfor _, currentRunner := range e.phaseRunners {\n\t\tif err := fn(currentRunner); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":441,"to":451}} {"id":100000720,"name":"prepareForExecution","signature":"func (e *Runner) prepareForExecution()","file":"cmd/kubeadm/app/cmd/phases/workflow/runner.go","code":"// prepareForExecution initialize the internal state of the Runner (the list of phaseRunner).\nfunc (e *Runner) prepareForExecution() {\n\te.phaseRunners = []*phaseRunner{}\n\tvar parentRunner *phaseRunner\n\tfor _, phase := range e.Phases {\n\t\t// skips phases that are meant to create special subcommands only\n\t\tif phase.RunAllSiblings {\n\t\t\tcontinue\n\t\t}\n\n\t\t// add phases to the execution list\n\t\taddPhaseRunner(e, parentRunner, phase)\n\t}\n}","line":{"from":453,"to":466}} {"id":100000721,"name":"addPhaseRunner","signature":"func addPhaseRunner(e *Runner, parentRunner *phaseRunner, phase Phase)","file":"cmd/kubeadm/app/cmd/phases/workflow/runner.go","code":"// addPhaseRunner adds the phaseRunner for a given phase to the phaseRunners list\nfunc addPhaseRunner(e *Runner, parentRunner *phaseRunner, phase Phase) {\n\t// computes contextual information derived by the workflow managed by the Runner.\n\tuse := cleanName(phase.Name)\n\tgeneratedName := use\n\tselfPath := []string{generatedName}\n\n\tif parentRunner != nil {\n\t\tgeneratedName = strings.Join([]string{parentRunner.generatedName, generatedName}, phaseSeparator)\n\t\tuse = fmt.Sprintf(\"%s%s\", phaseSeparator, use)\n\t\tselfPath = append(parentRunner.selfPath, selfPath...)\n\t}\n\n\t// creates the phaseRunner\n\tcurrentRunner := \u0026phaseRunner{\n\t\tPhase: phase,\n\t\tparent: parentRunner,\n\t\tlevel: len(selfPath) - 1,\n\t\tselfPath: selfPath,\n\t\tgeneratedName: generatedName,\n\t\tuse: use,\n\t}\n\n\t// adds to the phaseRunners list\n\te.phaseRunners = append(e.phaseRunners, currentRunner)\n\n\t// iterate for the nested, ordered list of phases, thus storing\n\t// phases in the expected executing order (child phase are stored immediately after their parent phase).\n\tfor _, childPhase := range phase.Phases {\n\t\taddPhaseRunner(e, currentRunner, childPhase)\n\t}\n}","line":{"from":468,"to":499}} {"id":100000722,"name":"cleanName","signature":"func cleanName(name string) string","file":"cmd/kubeadm/app/cmd/phases/workflow/runner.go","code":"// cleanName makes phase name suitable for the runner help, by lowercasing the name\n// and removing args descriptors, if any\nfunc cleanName(name string) string {\n\tret := strings.ToLower(name)\n\tif pos := strings.Index(ret, \" \"); pos != -1 {\n\t\tret = ret[:pos]\n\t}\n\treturn ret\n}","line":{"from":501,"to":509}} {"id":100000723,"name":"newResetOptions","signature":"func newResetOptions() *resetOptions","file":"cmd/kubeadm/app/cmd/reset.go","code":"// newResetOptions returns a struct ready for being used for creating cmd join flags.\nfunc newResetOptions() *resetOptions {\n\treturn \u0026resetOptions{\n\t\tcertificatesDir: kubeadmapiv1.DefaultCertificatesDir,\n\t\tforceReset: false,\n\t\tkubeconfigPath: kubeadmconstants.GetAdminKubeConfigPath(),\n\t\tcleanupTmpDir: false,\n\t}\n}","line":{"from":87,"to":95}} {"id":100000724,"name":"newResetData","signature":"func newResetData(cmd *cobra.Command, options *resetOptions, in io.Reader, out io.Writer) (*resetData, error)","file":"cmd/kubeadm/app/cmd/reset.go","code":"// newResetData returns a new resetData struct to be used for the execution of the kubeadm reset workflow.\nfunc newResetData(cmd *cobra.Command, options *resetOptions, in io.Reader, out io.Writer) (*resetData, error) {\n\tvar cfg *kubeadmapi.InitConfiguration\n\n\tclient, err := cmdutil.GetClientSet(options.kubeconfigPath, false)\n\tif err == nil {\n\t\tklog.V(1).Infof(\"[reset] Loaded client set from kubeconfig file: %s\", options.kubeconfigPath)\n\t\tcfg, err = configutil.FetchInitConfigurationFromCluster(client, nil, \"reset\", false, false)\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"[reset] Unable to fetch the kubeadm-config ConfigMap from cluster: %v\", err)\n\t\t}\n\t} else {\n\t\tklog.V(1).Infof(\"[reset] Could not obtain a client set from the kubeconfig file: %s\", options.kubeconfigPath)\n\t}\n\n\tignorePreflightErrorsFromCfg := []string{}\n\tignorePreflightErrorsSet, err := validation.ValidateIgnorePreflightErrors(options.ignorePreflightErrors, ignorePreflightErrorsFromCfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif cfg != nil {\n\t\t// Also set the union of pre-flight errors to InitConfiguration, to provide a consistent view of the runtime configuration:\n\t\tcfg.NodeRegistration.IgnorePreflightErrors = sets.List(ignorePreflightErrorsSet)\n\t}\n\n\tvar criSocketPath string\n\tif options.criSocketPath == \"\" {\n\t\tcriSocketPath, err = resetDetectCRISocket(cfg)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tklog.V(1).Infof(\"[reset] Detected and using CRI socket: %s\", criSocketPath)\n\t} else {\n\t\tcriSocketPath = options.criSocketPath\n\t\tklog.V(1).Infof(\"[reset] Using specified CRI socket: %s\", criSocketPath)\n\t}\n\n\treturn \u0026resetData{\n\t\tcertificatesDir: options.certificatesDir,\n\t\tclient: client,\n\t\tcriSocketPath: criSocketPath,\n\t\tforceReset: options.forceReset,\n\t\tignorePreflightErrors: ignorePreflightErrorsSet,\n\t\tinputReader: in,\n\t\toutputWriter: out,\n\t\tcfg: cfg,\n\t\tdryRun: options.dryRun,\n\t\tcleanupTmpDir: options.cleanupTmpDir,\n\t}, nil\n}","line":{"from":97,"to":146}} {"id":100000725,"name":"AddResetFlags","signature":"func AddResetFlags(flagSet *flag.FlagSet, resetOptions *resetOptions)","file":"cmd/kubeadm/app/cmd/reset.go","code":"// AddResetFlags adds reset flags\nfunc AddResetFlags(flagSet *flag.FlagSet, resetOptions *resetOptions) {\n\tflagSet.StringVar(\n\t\t\u0026resetOptions.certificatesDir, options.CertificatesDir, resetOptions.certificatesDir,\n\t\t`The path to the directory where the certificates are stored. If specified, clean this directory.`,\n\t)\n\tflagSet.BoolVarP(\n\t\t\u0026resetOptions.forceReset, options.ForceReset, \"f\", false,\n\t\t\"Reset the node without prompting for confirmation.\",\n\t)\n\tflagSet.BoolVar(\n\t\t\u0026resetOptions.dryRun, options.DryRun, resetOptions.dryRun,\n\t\t\"Don't apply any changes; just output what would be done.\",\n\t)\n\tflagSet.BoolVar(\n\t\t\u0026resetOptions.cleanupTmpDir, options.CleanupTmpDir, resetOptions.cleanupTmpDir,\n\t\tfmt.Sprintf(\"Cleanup the %q directory\", path.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.TempDirForKubeadm)),\n\t)\n\n\toptions.AddKubeConfigFlag(flagSet, \u0026resetOptions.kubeconfigPath)\n\toptions.AddIgnorePreflightErrorsFlag(flagSet, \u0026resetOptions.ignorePreflightErrors)\n\tcmdutil.AddCRISocketFlag(flagSet, \u0026resetOptions.criSocketPath)\n}","line":{"from":148,"to":170}} {"id":100000726,"name":"newCmdReset","signature":"func newCmdReset(in io.Reader, out io.Writer, resetOptions *resetOptions) *cobra.Command","file":"cmd/kubeadm/app/cmd/reset.go","code":"// newCmdReset returns the \"kubeadm reset\" command\nfunc newCmdReset(in io.Reader, out io.Writer, resetOptions *resetOptions) *cobra.Command {\n\tif resetOptions == nil {\n\t\tresetOptions = newResetOptions()\n\t}\n\tresetRunner := workflow.NewRunner()\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"reset\",\n\t\tShort: \"Performs a best effort revert of changes made to this host by 'kubeadm init' or 'kubeadm join'\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\terr := resetRunner.Run(args)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// output help text instructing user how to remove cni folders\n\t\t\tfmt.Print(cniCleanupInstructions)\n\t\t\t// Output help text instructing user how to remove iptables rules\n\t\t\tfmt.Print(iptablesCleanupInstructions)\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tAddResetFlags(cmd.Flags(), resetOptions)\n\n\t// initialize the workflow runner with the list of phases\n\tresetRunner.AppendPhase(phases.NewPreflightPhase())\n\tresetRunner.AppendPhase(phases.NewRemoveETCDMemberPhase())\n\tresetRunner.AppendPhase(phases.NewCleanupNodePhase())\n\n\t// sets the data builder function, that will be used by the runner\n\t// both when running the entire workflow or single phases\n\tresetRunner.SetDataInitializer(func(cmd *cobra.Command, args []string) (workflow.RunData, error) {\n\t\tif cmd.Flags().Lookup(options.NodeCRISocket) == nil {\n\t\t\t// avoid CRI detection\n\t\t\t// assume that the command execution does not depend on CRISocket when --cri-socket flag is not set\n\t\t\tresetOptions.criSocketPath = kubeadmconstants.UnknownCRISocket\n\t\t}\n\t\treturn newResetData(cmd, resetOptions, in, out)\n\t})\n\n\t// binds the Runner to kubeadm reset command by altering\n\t// command help, adding --skip-phases flag and by adding phases subcommands\n\tresetRunner.BindToCommand(cmd)\n\n\treturn cmd\n}","line":{"from":172,"to":219}} {"id":100000727,"name":"Cfg","signature":"func (r *resetData) Cfg() *kubeadmapi.InitConfiguration","file":"cmd/kubeadm/app/cmd/reset.go","code":"// Cfg returns the InitConfiguration.\nfunc (r *resetData) Cfg() *kubeadmapi.InitConfiguration {\n\treturn r.cfg\n}","line":{"from":221,"to":224}} {"id":100000728,"name":"DryRun","signature":"func (r *resetData) DryRun() bool","file":"cmd/kubeadm/app/cmd/reset.go","code":"// DryRun returns the dryRun flag.\nfunc (r *resetData) DryRun() bool {\n\treturn r.dryRun\n}","line":{"from":226,"to":229}} {"id":100000729,"name":"CleanupTmpDir","signature":"func (r *resetData) CleanupTmpDir() bool","file":"cmd/kubeadm/app/cmd/reset.go","code":"// CleanupTmpDir returns the cleanupTmpDir flag.\nfunc (r *resetData) CleanupTmpDir() bool {\n\treturn r.cleanupTmpDir\n}","line":{"from":231,"to":234}} {"id":100000730,"name":"CertificatesDir","signature":"func (r *resetData) CertificatesDir() string","file":"cmd/kubeadm/app/cmd/reset.go","code":"// CertificatesDir returns the CertificatesDir.\nfunc (r *resetData) CertificatesDir() string {\n\treturn r.certificatesDir\n}","line":{"from":236,"to":239}} {"id":100000731,"name":"Client","signature":"func (r *resetData) Client() clientset.Interface","file":"cmd/kubeadm/app/cmd/reset.go","code":"// Client returns the Client for accessing the cluster.\nfunc (r *resetData) Client() clientset.Interface {\n\treturn r.client\n}","line":{"from":241,"to":244}} {"id":100000732,"name":"ForceReset","signature":"func (r *resetData) ForceReset() bool","file":"cmd/kubeadm/app/cmd/reset.go","code":"// ForceReset returns the forceReset flag.\nfunc (r *resetData) ForceReset() bool {\n\treturn r.forceReset\n}","line":{"from":246,"to":249}} {"id":100000733,"name":"InputReader","signature":"func (r *resetData) InputReader() io.Reader","file":"cmd/kubeadm/app/cmd/reset.go","code":"// InputReader returns the io.reader used to read messages.\nfunc (r *resetData) InputReader() io.Reader {\n\treturn r.inputReader\n}","line":{"from":251,"to":254}} {"id":100000734,"name":"IgnorePreflightErrors","signature":"func (r *resetData) IgnorePreflightErrors() sets.Set[string]","file":"cmd/kubeadm/app/cmd/reset.go","code":"// IgnorePreflightErrors returns the list of preflight errors to ignore.\nfunc (r *resetData) IgnorePreflightErrors() sets.Set[string] {\n\treturn r.ignorePreflightErrors\n}","line":{"from":256,"to":259}} {"id":100000735,"name":"CRISocketPath","signature":"func (r *resetData) CRISocketPath() string","file":"cmd/kubeadm/app/cmd/reset.go","code":"// CRISocketPath returns the criSocketPath.\nfunc (r *resetData) CRISocketPath() string {\n\treturn r.criSocketPath\n}","line":{"from":261,"to":264}} {"id":100000736,"name":"resetDetectCRISocket","signature":"func resetDetectCRISocket(cfg *kubeadmapi.InitConfiguration) (string, error)","file":"cmd/kubeadm/app/cmd/reset.go","code":"func resetDetectCRISocket(cfg *kubeadmapi.InitConfiguration) (string, error) {\n\tif cfg != nil {\n\t\t// first try to get the CRI socket from the cluster configuration\n\t\treturn cfg.NodeRegistration.CRISocket, nil\n\t}\n\n\t// if this fails, try to detect it\n\treturn utilruntime.DetectCRISocket()\n}","line":{"from":266,"to":274}} {"id":100000737,"name":"newCmdToken","signature":"func newCmdToken(out io.Writer, errW io.Writer) *cobra.Command","file":"cmd/kubeadm/app/cmd/token.go","code":"// newCmdToken returns cobra.Command for token management\nfunc newCmdToken(out io.Writer, errW io.Writer) *cobra.Command {\n\tvar kubeConfigFile string\n\tvar dryRun bool\n\ttokenCmd := \u0026cobra.Command{\n\t\tUse: \"token\",\n\t\tShort: \"Manage bootstrap tokens\",\n\t\tLong: dedent.Dedent(`\n\t\t\tThis command manages bootstrap tokens. It is optional and needed only for advanced use cases.\n\n\t\t\tIn short, bootstrap tokens are used for establishing bidirectional trust between a client and a server.\n\t\t\tA bootstrap token can be used when a client (for example a node that is about to join the cluster) needs\n\t\t\tto trust the server it is talking to. Then a bootstrap token with the \"signing\" usage can be used.\n\t\t\tbootstrap tokens can also function as a way to allow short-lived authentication to the API Server\n\t\t\t(the token serves as a way for the API Server to trust the client), for example for doing the TLS Bootstrap.\n\n\t\t\tWhat is a bootstrap token more exactly?\n\t\t\t - It is a Secret in the kube-system namespace of type \"bootstrap.kubernetes.io/token\".\n\t\t\t - A bootstrap token must be of the form \"[a-z0-9]{6}.[a-z0-9]{16}\". The former part is the public token ID,\n\t\t\t while the latter is the Token Secret and it must be kept private at all circumstances!\n\t\t\t - The name of the Secret must be named \"bootstrap-token-(token-id)\".\n\n\t\t\tYou can read more about bootstrap tokens here:\n\t\t\t https://kubernetes.io/docs/admin/bootstrap-tokens/\n\t\t`),\n\n\t\t// Without this callback, if a user runs just the \"token\"\n\t\t// command without a subcommand, or with an invalid subcommand,\n\t\t// cobra will print usage information, but still exit cleanly.\n\t\t// We want to return an error code in these cases so that the\n\t\t// user knows that their command was invalid.\n\t\tRun: cmdutil.SubCmdRun(),\n\t}\n\n\toptions.AddKubeConfigFlag(tokenCmd.PersistentFlags(), \u0026kubeConfigFile)\n\ttokenCmd.PersistentFlags().BoolVar(\u0026dryRun,\n\t\toptions.DryRun, dryRun, \"Whether to enable dry-run mode or not\")\n\n\tcfg := cmdutil.DefaultInitConfiguration()\n\n\t// Default values for the cobra help text\n\tkubeadmscheme.Scheme.Default(cfg)\n\n\tvar cfgPath string\n\tvar printJoinCommand bool\n\tvar certificateKey string\n\tbto := options.NewBootstrapTokenOptions()\n\n\tcreateCmd := \u0026cobra.Command{\n\t\tUse: \"create [token]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: \"Create bootstrap tokens on the server\",\n\t\tLong: dedent.Dedent(`\n\t\t\tThis command will create a bootstrap token for you.\n\t\t\tYou can specify the usages for this token, the \"time to live\" and an optional human friendly description.\n\n\t\t\tThe [token] is the actual token to write.\n\t\t\tThis should be a securely generated random token of the form \"[a-z0-9]{6}.[a-z0-9]{16}\".\n\t\t\tIf no [token] is given, kubeadm will generate a random token instead.\n\t\t`),\n\t\tRunE: func(tokenCmd *cobra.Command, args []string) error {\n\t\t\tif len(args) \u003e 0 {\n\t\t\t\tbto.TokenStr = args[0]\n\t\t\t}\n\t\t\tklog.V(1).Infoln(\"[token] validating mixed arguments\")\n\t\t\tif err := validation.ValidateMixedArguments(tokenCmd.Flags()); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := bto.ApplyTo(cfg); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tklog.V(1).Infoln(\"[token] getting Clientsets from kubeconfig file\")\n\t\t\tkubeConfigFile = cmdutil.GetKubeConfigPath(kubeConfigFile)\n\t\t\tclient, err := cmdutil.GetClientSet(kubeConfigFile, dryRun)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn RunCreateToken(out, client, cfgPath, cfg, printJoinCommand, certificateKey, kubeConfigFile)\n\t\t},\n\t}\n\n\toptions.AddConfigFlag(createCmd.Flags(), \u0026cfgPath)\n\tcreateCmd.Flags().BoolVar(\u0026printJoinCommand,\n\t\t\"print-join-command\", false, \"Instead of printing only the token, print the full 'kubeadm join' flag needed to join the cluster using the token.\")\n\tcreateCmd.Flags().StringVar(\u0026certificateKey,\n\t\toptions.CertificateKey, \"\", \"When used together with '--print-join-command', print the full 'kubeadm join' flag needed to join the cluster as a control-plane. To create a new certificate key you must use 'kubeadm init phase upload-certs --upload-certs'.\")\n\tbto.AddTTLFlagWithName(createCmd.Flags(), \"ttl\")\n\tbto.AddUsagesFlag(createCmd.Flags())\n\tbto.AddGroupsFlag(createCmd.Flags())\n\tbto.AddDescriptionFlag(createCmd.Flags())\n\n\ttokenCmd.AddCommand(createCmd)\n\ttokenCmd.AddCommand(newCmdTokenGenerate(out))\n\n\toutputFlags := output.NewOutputFlags(\u0026tokenTextPrintFlags{}).WithTypeSetter(outputapischeme.Scheme).WithDefaultOutput(output.TextOutput)\n\n\tlistCmd := \u0026cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List bootstrap tokens on the server\",\n\t\tLong: dedent.Dedent(`\n\t\t\tThis command will list all bootstrap tokens for you.\n\t\t`),\n\t\tRunE: func(tokenCmd *cobra.Command, args []string) error {\n\t\t\tkubeConfigFile = cmdutil.GetKubeConfigPath(kubeConfigFile)\n\t\t\tclient, err := cmdutil.GetClientSet(kubeConfigFile, dryRun)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tprinter, err := outputFlags.ToPrinter()\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"could not construct output printer\")\n\t\t\t}\n\n\t\t\treturn RunListTokens(out, errW, client, printer)\n\t\t},\n\t\tArgs: cobra.NoArgs,\n\t}\n\n\toutputFlags.AddFlags(listCmd)\n\n\ttokenCmd.AddCommand(listCmd)\n\n\tdeleteCmd := \u0026cobra.Command{\n\t\tUse: \"delete [token-value] ...\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: \"Delete bootstrap tokens on the server\",\n\t\tLong: dedent.Dedent(`\n\t\t\tThis command will delete a list of bootstrap tokens for you.\n\n\t\t\tThe [token-value] is the full Token of the form \"[a-z0-9]{6}.[a-z0-9]{16}\" or the\n\t\t\tToken ID of the form \"[a-z0-9]{6}\" to delete.\n\t\t`),\n\t\tRunE: func(tokenCmd *cobra.Command, args []string) error {\n\t\t\tif len(args) \u003c 1 {\n\t\t\t\treturn errors.Errorf(\"missing argument; 'token delete' is missing token of form %q or %q\", bootstrapapi.BootstrapTokenPattern, bootstrapapi.BootstrapTokenIDPattern)\n\t\t\t}\n\t\t\tkubeConfigFile = cmdutil.GetKubeConfigPath(kubeConfigFile)\n\t\t\tclient, err := cmdutil.GetClientSet(kubeConfigFile, dryRun)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn RunDeleteTokens(out, client, args)\n\t\t},\n\t}\n\ttokenCmd.AddCommand(deleteCmd)\n\n\treturn tokenCmd\n}","line":{"from":55,"to":207}} {"id":100000738,"name":"newCmdTokenGenerate","signature":"func newCmdTokenGenerate(out io.Writer) *cobra.Command","file":"cmd/kubeadm/app/cmd/token.go","code":"// newCmdTokenGenerate returns cobra.Command to generate new token\nfunc newCmdTokenGenerate(out io.Writer) *cobra.Command {\n\treturn \u0026cobra.Command{\n\t\tUse: \"generate\",\n\t\tShort: \"Generate and print a bootstrap token, but do not create it on the server\",\n\t\tLong: dedent.Dedent(`\n\t\t\tThis command will print out a randomly-generated bootstrap token that can be used with\n\t\t\tthe \"init\" and \"join\" commands.\n\n\t\t\tYou don't have to use this command in order to generate a token. You can do so\n\t\t\tyourself as long as it is in the format \"[a-z0-9]{6}.[a-z0-9]{16}\". This\n\t\t\tcommand is provided for convenience to generate tokens in the given format.\n\n\t\t\tYou can also use \"kubeadm init\" without specifying a token and it will\n\t\t\tgenerate and print one for you.\n\t\t`),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn RunGenerateToken(out)\n\t\t},\n\t\tArgs: cobra.NoArgs,\n\t}\n}","line":{"from":209,"to":230}} {"id":100000739,"name":"RunCreateToken","signature":"func RunCreateToken(out io.Writer, client clientset.Interface, cfgPath string, initCfg *kubeadmapiv1.InitConfiguration, printJoinCommand bool, certificateKey string, kubeConfigFile string) error","file":"cmd/kubeadm/app/cmd/token.go","code":"// RunCreateToken generates a new bootstrap token and stores it as a secret on the server.\nfunc RunCreateToken(out io.Writer, client clientset.Interface, cfgPath string, initCfg *kubeadmapiv1.InitConfiguration, printJoinCommand bool, certificateKey string, kubeConfigFile string) error {\n\t// ClusterConfiguration is needed just for the call to LoadOrDefaultInitConfiguration\n\tclusterCfg := \u0026kubeadmapiv1.ClusterConfiguration{\n\t\t// KubernetesVersion is not used, but we set this explicitly to avoid\n\t\t// the lookup of the version from the internet when executing LoadOrDefaultInitConfiguration\n\t\tKubernetesVersion: kubeadmconstants.CurrentKubernetesVersion.String(),\n\t}\n\tkubeadmscheme.Scheme.Default(clusterCfg)\n\n\t// This call returns the ready-to-use configuration based on the configuration file that might or might not exist and the default cfg populated by flags\n\tklog.V(1).Infoln(\"[token] loading configurations\")\n\n\tinternalcfg, err := configutil.LoadOrDefaultInitConfiguration(cfgPath, initCfg, clusterCfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tklog.V(1).Infoln(\"[token] creating token\")\n\tif err := tokenphase.CreateNewTokens(client, internalcfg.BootstrapTokens); err != nil {\n\t\treturn err\n\t}\n\n\t// if --print-join-command was specified, print a machine-readable full `kubeadm join` command\n\t// otherwise, just print the token\n\tif printJoinCommand {\n\t\tskipTokenPrint := false\n\t\tif certificateKey != \"\" {\n\t\t\tskipCertificateKeyPrint := false\n\t\t\tjoinCommand, err := cmdutil.GetJoinControlPlaneCommand(kubeConfigFile, internalcfg.BootstrapTokens[0].Token.String(), certificateKey, skipTokenPrint, skipCertificateKeyPrint)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"failed to get join command\")\n\t\t\t}\n\t\t\tjoinCommand = strings.ReplaceAll(joinCommand, \"\\\\\\n\", \"\")\n\t\t\tjoinCommand = strings.ReplaceAll(joinCommand, \"\\t\", \"\")\n\t\t\tfmt.Fprintln(out, joinCommand)\n\t\t} else {\n\t\t\tjoinCommand, err := cmdutil.GetJoinWorkerCommand(kubeConfigFile, internalcfg.BootstrapTokens[0].Token.String(), skipTokenPrint)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"failed to get join command\")\n\t\t\t}\n\t\t\tjoinCommand = strings.ReplaceAll(joinCommand, \"\\\\\\n\", \"\")\n\t\t\tjoinCommand = strings.ReplaceAll(joinCommand, \"\\t\", \"\")\n\t\t\tfmt.Fprintln(out, joinCommand)\n\t\t}\n\t} else {\n\t\tif certificateKey != \"\" {\n\t\t\treturn errors.New(\"cannot use --certificate-key without --print-join-command\")\n\t\t}\n\t\tfmt.Fprintln(out, internalcfg.BootstrapTokens[0].Token.String())\n\t}\n\n\treturn nil\n}","line":{"from":232,"to":285}} {"id":100000740,"name":"RunGenerateToken","signature":"func RunGenerateToken(out io.Writer) error","file":"cmd/kubeadm/app/cmd/token.go","code":"// RunGenerateToken just generates a random token for the user\nfunc RunGenerateToken(out io.Writer) error {\n\tklog.V(1).Infoln(\"[token] generating random token\")\n\ttoken, err := bootstraputil.GenerateBootstrapToken()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Fprintln(out, token)\n\treturn nil\n}","line":{"from":287,"to":297}} {"id":100000741,"name":"formatBootstrapToken","signature":"func formatBootstrapToken(obj *outputapiv1alpha2.BootstrapToken) string","file":"cmd/kubeadm/app/cmd/token.go","code":"func formatBootstrapToken(obj *outputapiv1alpha2.BootstrapToken) string {\n\tttl := \"\u003cforever\u003e\"\n\texpires := \"\u003cnever\u003e\"\n\tif obj.Expires != nil {\n\t\tttl = duration.ShortHumanDuration(time.Until(obj.Expires.Time))\n\t\texpires = obj.Expires.Format(time.RFC3339)\n\t}\n\tttl = fmt.Sprintf(\"%-9s\", ttl)\n\n\tusages := strings.Join(obj.Usages, \",\")\n\tif len(usages) == 0 {\n\t\tusages = \"\u003cnone\u003e\"\n\t}\n\tusages = fmt.Sprintf(\"%-22s\", usages)\n\n\tdescription := obj.Description\n\tif len(description) == 0 {\n\t\tdescription = \"\u003cnone\u003e\"\n\t}\n\tdescription = fmt.Sprintf(\"%-56s\", description)\n\n\tgroups := strings.Join(obj.Groups, \",\")\n\tif len(groups) == 0 {\n\t\tgroups = \"\u003cnone\u003e\"\n\t}\n\n\treturn fmt.Sprintf(\"%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n\", obj.Token, ttl, expires, usages, description, groups)\n}","line":{"from":299,"to":326}} {"id":100000742,"name":"PrintObj","signature":"func (ttp *tokenTextPrinter) PrintObj(obj runtime.Object, writer io.Writer) error","file":"cmd/kubeadm/app/cmd/token.go","code":"// PrintObj is an implementation of ResourcePrinter.PrintObj for plain text output\nfunc (ttp *tokenTextPrinter) PrintObj(obj runtime.Object, writer io.Writer) error {\n\ttabw := tabwriter.NewWriter(writer, 10, 4, 3, ' ', 0)\n\n\t// Print header\n\tif !ttp.headerIsPrinted {\n\t\tfmt.Fprintln(tabw, strings.Join(ttp.columns, \"\\t\"))\n\t\tttp.headerIsPrinted = true\n\t}\n\n\t// Print token\n\tfmt.Fprint(tabw, formatBootstrapToken(obj.(*outputapiv1alpha2.BootstrapToken)))\n\n\treturn tabw.Flush()\n}","line":{"from":335,"to":349}} {"id":100000743,"name":"ToPrinter","signature":"func (tpf *tokenTextPrintFlags) ToPrinter(outputFormat string) (output.Printer, error)","file":"cmd/kubeadm/app/cmd/token.go","code":"// ToPrinter returns a kubeadm printer for the text output format\nfunc (tpf *tokenTextPrintFlags) ToPrinter(outputFormat string) (output.Printer, error) {\n\tif outputFormat == output.TextOutput {\n\t\treturn \u0026tokenTextPrinter{columns: []string{\"TOKEN\", \"TTL\", \"EXPIRES\", \"USAGES\", \"DESCRIPTION\", \"EXTRA GROUPS\"}}, nil\n\t}\n\treturn nil, genericclioptions.NoCompatiblePrinterError{OutputFormat: \u0026outputFormat, AllowedFormats: []string{output.TextOutput}}\n}","line":{"from":354,"to":360}} {"id":100000744,"name":"RunListTokens","signature":"func RunListTokens(out io.Writer, errW io.Writer, client clientset.Interface, printer output.Printer) error","file":"cmd/kubeadm/app/cmd/token.go","code":"// RunListTokens lists details on all existing bootstrap tokens on the server.\nfunc RunListTokens(out io.Writer, errW io.Writer, client clientset.Interface, printer output.Printer) error {\n\t// First, build our selector for bootstrap tokens only\n\tklog.V(1).Infoln(\"[token] preparing selector for bootstrap token\")\n\ttokenSelector := fields.SelectorFromSet(\n\t\tmap[string]string{\n\t\t\t\"type\": string(bootstrapapi.SecretTypeBootstrapToken),\n\t\t},\n\t)\n\tlistOptions := metav1.ListOptions{\n\t\tFieldSelector: tokenSelector.String(),\n\t}\n\n\tklog.V(1).Info(\"[token] retrieving list of bootstrap tokens\")\n\tsecrets, err := client.CoreV1().Secrets(metav1.NamespaceSystem).List(context.TODO(), listOptions)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to list bootstrap tokens\")\n\t}\n\n\tfor _, secret := range secrets.Items {\n\t\t// Get the BootstrapToken struct representation from the Secret object\n\t\ttoken, err := bootstraptokenv1.BootstrapTokenFromSecret(\u0026secret)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(errW, \"%v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Convert token into versioned output structure\n\t\toutputToken := outputapiv1alpha2.BootstrapToken{\n\t\t\tBootstrapToken: bootstraptokenv1.BootstrapToken{\n\t\t\t\tToken: \u0026bootstraptokenv1.BootstrapTokenString{ID: token.Token.ID, Secret: token.Token.Secret},\n\t\t\t\tDescription: token.Description,\n\t\t\t\tTTL: token.TTL,\n\t\t\t\tExpires: token.Expires,\n\t\t\t\tUsages: token.Usages,\n\t\t\t\tGroups: token.Groups,\n\t\t\t},\n\t\t}\n\n\t\tif err := printer.PrintObj(\u0026outputToken, out); err != nil {\n\t\t\treturn errors.Wrapf(err, \"unable to print token %s\", token.Token)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":362,"to":406}} {"id":100000745,"name":"RunDeleteTokens","signature":"func RunDeleteTokens(out io.Writer, client clientset.Interface, tokenIDsOrTokens []string) error","file":"cmd/kubeadm/app/cmd/token.go","code":"// RunDeleteTokens removes a bootstrap tokens from the server.\nfunc RunDeleteTokens(out io.Writer, client clientset.Interface, tokenIDsOrTokens []string) error {\n\tfor _, tokenIDOrToken := range tokenIDsOrTokens {\n\t\t// Assume this is a token id and try to parse it\n\t\ttokenID := tokenIDOrToken\n\t\tklog.V(1).Info(\"[token] parsing token\")\n\t\tif !bootstraputil.IsValidBootstrapTokenID(tokenIDOrToken) {\n\t\t\t// Okay, the full token with both id and secret was probably passed. Parse it and extract the ID only\n\t\t\tbts, err := bootstraptokenv1.NewBootstrapTokenString(tokenIDOrToken)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Errorf(\"given token didn't match pattern %q or %q\",\n\t\t\t\t\tbootstrapapi.BootstrapTokenPattern, bootstrapapi.BootstrapTokenIDPattern)\n\t\t\t}\n\t\t\ttokenID = bts.ID\n\t\t}\n\n\t\ttokenSecretName := bootstraputil.BootstrapTokenSecretName(tokenID)\n\t\tklog.V(1).Infof(\"[token] deleting token %q\", tokenID)\n\t\tif err := client.CoreV1().Secrets(metav1.NamespaceSystem).Delete(context.TODO(), tokenSecretName, metav1.DeleteOptions{}); err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to delete bootstrap token %q\", tokenID)\n\t\t}\n\t\tfmt.Fprintf(out, \"bootstrap token %q deleted\\n\", tokenID)\n\t}\n\treturn nil\n}","line":{"from":408,"to":432}} {"id":100000746,"name":"sessionIsInteractive","signature":"func (f *applyFlags) sessionIsInteractive() bool","file":"cmd/kubeadm/app/cmd/upgrade/apply.go","code":"// sessionIsInteractive returns true if the session is of an interactive type (the default, can be opted out of with -y, -f or --dry-run)\nfunc (f *applyFlags) sessionIsInteractive() bool {\n\treturn !(f.nonInteractiveMode || f.dryRun || f.force)\n}","line":{"from":56,"to":59}} {"id":100000747,"name":"newCmdApply","signature":"func newCmdApply(apf *applyPlanFlags) *cobra.Command","file":"cmd/kubeadm/app/cmd/upgrade/apply.go","code":"// newCmdApply returns the cobra command for `kubeadm upgrade apply`\nfunc newCmdApply(apf *applyPlanFlags) *cobra.Command {\n\tflags := \u0026applyFlags{\n\t\tapplyPlanFlags: apf,\n\t\tetcdUpgrade: true,\n\t\trenewCerts: true,\n\t}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"apply [version]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: \"Upgrade your Kubernetes cluster to the specified version\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn runApply(flags, args)\n\t\t},\n\t}\n\n\t// Register the common flags for apply and plan\n\taddApplyPlanFlags(cmd.Flags(), flags.applyPlanFlags)\n\t// Specify the valid flags specific for apply\n\tcmd.Flags().BoolVarP(\u0026flags.nonInteractiveMode, \"yes\", \"y\", flags.nonInteractiveMode, \"Perform the upgrade and do not prompt for confirmation (non-interactive mode).\")\n\tcmd.Flags().BoolVarP(\u0026flags.force, \"force\", \"f\", flags.force, \"Force upgrading although some requirements might not be met. This also implies non-interactive mode.\")\n\tcmd.Flags().BoolVar(\u0026flags.dryRun, options.DryRun, flags.dryRun, \"Do not change any state, just output what actions would be performed.\")\n\tcmd.Flags().BoolVar(\u0026flags.etcdUpgrade, \"etcd-upgrade\", flags.etcdUpgrade, \"Perform the upgrade of etcd.\")\n\tcmd.Flags().BoolVar(\u0026flags.renewCerts, options.CertificateRenewal, flags.renewCerts, \"Perform the renewal of certificates used by component changed during upgrades.\")\n\toptions.AddPatchesFlag(cmd.Flags(), \u0026flags.patchesDir)\n\n\treturn cmd\n}","line":{"from":61,"to":89}} {"id":100000748,"name":"runApply","signature":"func runApply(flags *applyFlags, args []string) error","file":"cmd/kubeadm/app/cmd/upgrade/apply.go","code":"// runApply takes care of the actual upgrade functionality\n// It does the following things:\n// - Checks if the cluster is healthy\n// - Gets the configuration from the kubeadm-config ConfigMap in the cluster\n// - Enforces all version skew policies\n// - Asks the user if they really want to upgrade\n// - Makes sure the control plane images are available locally on the control-plane(s)\n// - Upgrades the control plane components\n// - Applies the other resources that'd be created with kubeadm init as well, like\n// - Creating the RBAC rules for the bootstrap tokens and the cluster-info ConfigMap\n// - Applying new CorDNS and kube-proxy manifests\n// - Uploads the newly used configuration to the cluster ConfigMap\nfunc runApply(flags *applyFlags, args []string) error {\n\n\t// Start with the basics, verify that the cluster is healthy and get the configuration from the cluster (using the ConfigMap)\n\tklog.V(1).Infoln(\"[upgrade/apply] verifying health of cluster\")\n\tklog.V(1).Infoln(\"[upgrade/apply] retrieving configuration from cluster\")\n\tclient, versionGetter, cfg, err := enforceRequirements(flags.applyPlanFlags, args, flags.dryRun, true, \u0026output.TextPrinter{}, loadConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Validate requested and validate actual version\n\tklog.V(1).Infoln(\"[upgrade/apply] validating requested and actual version\")\n\tif err := configutil.NormalizeKubernetesVersion(\u0026cfg.ClusterConfiguration); err != nil {\n\t\treturn err\n\t}\n\n\t// Use normalized version string in all following code.\n\tnewK8sVersion, err := version.ParseSemantic(cfg.KubernetesVersion)\n\tif err != nil {\n\t\treturn errors.Errorf(\"unable to parse normalized version %q as a semantic version\", cfg.KubernetesVersion)\n\t}\n\n\tif err := features.ValidateVersion(features.InitFeatureGates, cfg.FeatureGates, cfg.KubernetesVersion); err != nil {\n\t\treturn err\n\t}\n\n\t// Enforce the version skew policies\n\tklog.V(1).Infoln(\"[upgrade/version] enforcing version skew policies\")\n\tif err := EnforceVersionPolicies(cfg.KubernetesVersion, newK8sVersion, flags, versionGetter); err != nil {\n\t\treturn errors.Wrap(err, \"[upgrade/version] FATAL\")\n\t}\n\n\t// If the current session is interactive, ask the user whether they really want to upgrade.\n\tif flags.sessionIsInteractive() {\n\t\tif err := cmdutil.InteractivelyConfirmAction(\"upgrade\", \"Are you sure you want to proceed?\", os.Stdin); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !flags.dryRun {\n\t\tfmt.Println(\"[upgrade/prepull] Pulling images required for setting up a Kubernetes cluster\")\n\t\tfmt.Println(\"[upgrade/prepull] This might take a minute or two, depending on the speed of your internet connection\")\n\t\tfmt.Println(\"[upgrade/prepull] You can also perform this action in beforehand using 'kubeadm config images pull'\")\n\t\tif err := preflight.RunPullImagesCheck(utilsexec.New(), cfg, sets.New(cfg.NodeRegistration.IgnorePreflightErrors...)); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tfmt.Println(\"[upgrade/prepull] Would pull the required images (like 'kubeadm config images pull')\")\n\t}\n\n\twaiter := getWaiter(flags.dryRun, client, upgrade.UpgradeManifestTimeout)\n\n\t// Now; perform the upgrade procedure\n\tif err := PerformControlPlaneUpgrade(flags, client, waiter, cfg); err != nil {\n\t\treturn errors.Wrap(err, \"[upgrade/apply] FATAL\")\n\t}\n\n\t// Upgrade RBAC rules and addons.\n\tklog.V(1).Infoln(\"[upgrade/postupgrade] upgrading RBAC rules and addons\")\n\tif err := upgrade.PerformPostUpgradeTasks(client, cfg, flags.patchesDir, flags.dryRun, flags.applyPlanFlags.out); err != nil {\n\t\treturn errors.Wrap(err, \"[upgrade/postupgrade] FATAL post-upgrade error\")\n\t}\n\n\tif flags.dryRun {\n\t\tfmt.Println(\"[upgrade/successful] Finished dryrunning successfully!\")\n\t\treturn nil\n\t}\n\n\tfmt.Println(\"\")\n\tfmt.Printf(\"[upgrade/successful] SUCCESS! Your cluster was upgraded to %q. Enjoy!\\n\", cfg.KubernetesVersion)\n\tfmt.Println(\"\")\n\tfmt.Println(\"[upgrade/kubelet] Now that your control plane is upgraded, please proceed with upgrading your kubelets if you haven't already done so.\")\n\n\treturn nil\n}","line":{"from":91,"to":177}} {"id":100000749,"name":"EnforceVersionPolicies","signature":"func EnforceVersionPolicies(newK8sVersionStr string, newK8sVersion *version.Version, flags *applyFlags, versionGetter upgrade.VersionGetter) error","file":"cmd/kubeadm/app/cmd/upgrade/apply.go","code":"// EnforceVersionPolicies makes sure that the version the user specified is valid to upgrade to\n// There are both fatal and skippable (with --force) errors\nfunc EnforceVersionPolicies(newK8sVersionStr string, newK8sVersion *version.Version, flags *applyFlags, versionGetter upgrade.VersionGetter) error {\n\tfmt.Printf(\"[upgrade/version] You have chosen to change the cluster version to %q\\n\", newK8sVersionStr)\n\n\tversionSkewErrs := upgrade.EnforceVersionPolicies(versionGetter, newK8sVersionStr, newK8sVersion, flags.allowExperimentalUpgrades, flags.allowRCUpgrades)\n\tif versionSkewErrs != nil {\n\n\t\tif len(versionSkewErrs.Mandatory) \u003e 0 {\n\t\t\treturn errors.Errorf(\"the --version argument is invalid due to these fatal errors:\\n\\n%v\\nPlease fix the misalignments highlighted above and try upgrading again\",\n\t\t\t\tkubeadmutil.FormatErrMsg(versionSkewErrs.Mandatory))\n\t\t}\n\n\t\tif len(versionSkewErrs.Skippable) \u003e 0 {\n\t\t\t// Return the error if the user hasn't specified the --force flag\n\t\t\tif !flags.force {\n\t\t\t\treturn errors.Errorf(\"the --version argument is invalid due to these errors:\\n\\n%v\\nCan be bypassed if you pass the --force flag\",\n\t\t\t\t\tkubeadmutil.FormatErrMsg(versionSkewErrs.Skippable))\n\t\t\t}\n\t\t\t// Soft errors found, but --force was specified\n\t\t\tfmt.Printf(\"[upgrade/version] Found %d potential version compatibility errors but skipping since the --force flag is set: \\n\\n%v\", len(versionSkewErrs.Skippable), kubeadmutil.FormatErrMsg(versionSkewErrs.Skippable))\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":179,"to":203}} {"id":100000750,"name":"PerformControlPlaneUpgrade","signature":"func PerformControlPlaneUpgrade(flags *applyFlags, client clientset.Interface, waiter apiclient.Waiter, internalcfg *kubeadmapi.InitConfiguration) error","file":"cmd/kubeadm/app/cmd/upgrade/apply.go","code":"// PerformControlPlaneUpgrade actually performs the upgrade procedure for the cluster of your type (self-hosted or static-pod-hosted)\nfunc PerformControlPlaneUpgrade(flags *applyFlags, client clientset.Interface, waiter apiclient.Waiter, internalcfg *kubeadmapi.InitConfiguration) error {\n\n\t// OK, the cluster is hosted using static pods. Upgrade a static-pod hosted cluster\n\tfmt.Printf(\"[upgrade/apply] Upgrading your Static Pod-hosted control plane to version %q (timeout: %v)...\\n\",\n\t\tinternalcfg.KubernetesVersion, upgrade.UpgradeManifestTimeout)\n\n\tif flags.dryRun {\n\t\treturn upgrade.DryRunStaticPodUpgrade(flags.patchesDir, internalcfg)\n\t}\n\n\treturn upgrade.PerformStaticPodUpgrade(client, waiter, internalcfg, flags.etcdUpgrade, flags.renewCerts, flags.patchesDir)\n}","line":{"from":205,"to":217}} {"id":100000751,"name":"isKubeadmConfigPresent","signature":"func isKubeadmConfigPresent(docmap kubeadmapi.DocumentMap) bool","file":"cmd/kubeadm/app/cmd/upgrade/common.go","code":"// isKubeadmConfigPresent checks if a kubeadm config type is found in the provided document map\nfunc isKubeadmConfigPresent(docmap kubeadmapi.DocumentMap) bool {\n\tfor gvk := range docmap {\n\t\tif gvk.Group == kubeadmapi.GroupName {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":51,"to":59}} {"id":100000752,"name":"loadConfig","signature":"func loadConfig(cfgPath string, client clientset.Interface, skipComponentConfigs bool, printer output.Printer) (*kubeadmapi.InitConfiguration, bool, error)","file":"cmd/kubeadm/app/cmd/upgrade/common.go","code":"// loadConfig loads configuration from a file and/or the cluster. InitConfiguration, ClusterConfiguration and (optionally) component configs\n// are loaded. This function allows the component configs to be loaded from a file that contains only them. If the file contains any kubeadm types\n// in it (API group \"kubeadm.kubernetes.io\" present), then the supplied file is treaded as a legacy reconfiguration style \"--config\" use and the\n// returned bool value is set to true (the only case to be done so).\nfunc loadConfig(cfgPath string, client clientset.Interface, skipComponentConfigs bool, printer output.Printer) (*kubeadmapi.InitConfiguration, bool, error) {\n\t// Used for info logs here\n\tconst logPrefix = \"upgrade/config\"\n\n\t// The usual case here is to not have a config file, but rather load the config from the cluster.\n\t// This is probably 90% of the time. So we handle it first.\n\tif cfgPath == \"\" {\n\t\tcfg, err := configutil.FetchInitConfigurationFromCluster(client, printer, logPrefix, false, skipComponentConfigs)\n\t\treturn cfg, false, err\n\t}\n\n\t// Otherwise, we have a config file. Let's load it.\n\tconfigBytes, err := os.ReadFile(cfgPath)\n\tif err != nil {\n\t\treturn nil, false, errors.Wrapf(err, \"unable to load config from file %q\", cfgPath)\n\t}\n\n\t// Split the YAML documents in the file into a DocumentMap\n\tdocmap, err := kubeadmutil.SplitYAMLDocuments(configBytes)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\t// If there are kubeadm types (API group kubeadm.kubernetes.io) present, we need to keep the existing behavior\n\t// here. Basically, we have to load all of the configs from the file and none from the cluster. Configs that are\n\t// missing from the file will be automatically regenerated by kubeadm even if they are present in the cluster.\n\t// The resulting configs overwrite the existing cluster ones at the end of a successful upgrade apply operation.\n\tif isKubeadmConfigPresent(docmap) {\n\t\tklog.Warning(\"WARNING: Usage of the --config flag with kubeadm config types for reconfiguring the cluster during upgrade is not recommended!\")\n\t\tcfg, err := configutil.BytesToInitConfiguration(configBytes)\n\t\treturn cfg, true, err\n\t}\n\n\t// If no kubeadm config types are present, we assume that there are manually upgraded component configs in the file.\n\t// Hence, we load the kubeadm types from the cluster.\n\tinitCfg, err := configutil.FetchInitConfigurationFromCluster(client, printer, logPrefix, false, true)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\t// Stop here if the caller does not want us to load the component configs\n\tif !skipComponentConfigs {\n\t\t// Load the component configs with upgrades\n\t\tif err := componentconfigs.FetchFromClusterWithLocalOverwrites(\u0026initCfg.ClusterConfiguration, client, docmap); err != nil {\n\t\t\treturn nil, false, err\n\t\t}\n\n\t\t// Now default and validate the configs\n\t\tcomponentconfigs.Default(\u0026initCfg.ClusterConfiguration, \u0026initCfg.LocalAPIEndpoint, \u0026initCfg.NodeRegistration)\n\t\tif errs := componentconfigs.Validate(\u0026initCfg.ClusterConfiguration); len(errs) != 0 {\n\t\t\treturn nil, false, errs.ToAggregate()\n\t\t}\n\t}\n\n\treturn initCfg, false, nil\n}","line":{"from":61,"to":120}} {"id":100000753,"name":"enforceRequirements","signature":"func enforceRequirements(flags *applyPlanFlags, args []string, dryRun bool, upgradeApply bool, printer output.Printer, loadConfig LoadConfigFunc) (clientset.Interface, upgrade.VersionGetter, *kubeadmapi.InitConfiguration, error)","file":"cmd/kubeadm/app/cmd/upgrade/common.go","code":"// enforceRequirements verifies that it's okay to upgrade and then returns the variables needed for the rest of the procedure\nfunc enforceRequirements(flags *applyPlanFlags, args []string, dryRun bool, upgradeApply bool, printer output.Printer, loadConfig LoadConfigFunc) (clientset.Interface, upgrade.VersionGetter, *kubeadmapi.InitConfiguration, error) {\n\tclient, err := getClient(flags.kubeConfigPath, dryRun)\n\tif err != nil {\n\t\treturn nil, nil, nil, errors.Wrapf(err, \"couldn't create a Kubernetes client from file %q\", flags.kubeConfigPath)\n\t}\n\n\t// Fetch the configuration from a file or ConfigMap and validate it\n\tprinter.Printf(\"[upgrade/config] Making sure the configuration is correct:\\n\")\n\n\tvar newK8sVersion string\n\tcfg, legacyReconfigure, err := loadConfig(flags.cfgPath, client, !upgradeApply, printer)\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\tprinter.Printf(\"[upgrade/config] In order to upgrade, a ConfigMap called %q in the %s namespace must exist.\\n\", constants.KubeadmConfigConfigMap, metav1.NamespaceSystem)\n\t\t\tprinter.Printf(\"[upgrade/config] Without this information, 'kubeadm upgrade' won't know how to configure your upgraded cluster.\\n\")\n\t\t\tprinter.Println()\n\t\t\tprinter.Printf(\"[upgrade/config] Next steps:\\n\")\n\t\t\tprinter.Printf(\"\\t- OPTION 1: Run 'kubeadm config upload from-flags' and specify the same CLI arguments you passed to 'kubeadm init' when you created your control-plane.\\n\")\n\t\t\tprinter.Printf(\"\\t- OPTION 2: Run 'kubeadm config upload from-file' and specify the same config file you passed to 'kubeadm init' when you created your control-plane.\\n\")\n\t\t\tprinter.Printf(\"\\t- OPTION 3: Pass a config file to 'kubeadm upgrade' using the --config flag.\\n\")\n\t\t\tprinter.Println()\n\t\t\terr = errors.Errorf(\"the ConfigMap %q in the %s namespace used for getting configuration information was not found\", constants.KubeadmConfigConfigMap, metav1.NamespaceSystem)\n\t\t}\n\t\treturn nil, nil, nil, errors.Wrap(err, \"[upgrade/config] FATAL\")\n\t} else if legacyReconfigure {\n\t\t// Set the newK8sVersion to the value in the ClusterConfiguration. This is done, so that users who use the --config option\n\t\t// to supply a new ClusterConfiguration don't have to specify the Kubernetes version twice,\n\t\t// if they don't want to upgrade but just change a setting.\n\t\tnewK8sVersion = cfg.KubernetesVersion\n\t}\n\n\t// The version arg is mandatory, during upgrade apply, unless it's specified in the config file\n\tif upgradeApply \u0026\u0026 newK8sVersion == \"\" {\n\t\tif err := cmdutil.ValidateExactArgNumber(args, []string{\"version\"}); err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t}\n\n\t// If option was specified in both args and config file, args will overwrite the config file.\n\tif len(args) == 1 {\n\t\tnewK8sVersion = args[0]\n\t\tif upgradeApply {\n\t\t\t// The `upgrade apply` version always overwrites the KubernetesVersion in the returned cfg with the target\n\t\t\t// version. While this is not the same for `upgrade plan` where the KubernetesVersion should be the old\n\t\t\t// one (because the call to getComponentConfigVersionStates requires the currently installed version).\n\t\t\t// This also makes the KubernetesVersion value returned for `upgrade plan` consistent as that command\n\t\t\t// allows to not specify a target version in which case KubernetesVersion will always hold the currently\n\t\t\t// installed one.\n\t\t\tcfg.KubernetesVersion = newK8sVersion\n\t\t}\n\t}\n\n\tignorePreflightErrorsSet, err := validation.ValidateIgnorePreflightErrors(flags.ignorePreflightErrors, cfg.NodeRegistration.IgnorePreflightErrors)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\t// Also set the union of pre-flight errors to InitConfiguration, to provide a consistent view of the runtime configuration:\n\tcfg.NodeRegistration.IgnorePreflightErrors = sets.List(ignorePreflightErrorsSet)\n\n\t// Ensure the user is root\n\tklog.V(1).Info(\"running preflight checks\")\n\tif err := runPreflightChecks(client, ignorePreflightErrorsSet, \u0026cfg.ClusterConfiguration, printer); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// Run healthchecks against the cluster\n\tif err := upgrade.CheckClusterHealth(client, \u0026cfg.ClusterConfiguration, ignorePreflightErrorsSet); err != nil {\n\t\treturn nil, nil, nil, errors.Wrap(err, \"[upgrade/health] FATAL\")\n\t}\n\n\t// If features gates are passed to the command line, use it (otherwise use featureGates from configuration)\n\tif flags.featureGatesString != \"\" {\n\t\tcfg.FeatureGates, err = features.NewFeatureGate(\u0026features.InitFeatureGates, flags.featureGatesString)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, errors.Wrap(err, \"[upgrade/config] FATAL\")\n\t\t}\n\t}\n\n\t// Check if feature gate flags used in the cluster are consistent with the set of features currently supported by kubeadm\n\tif msg := features.CheckDeprecatedFlags(\u0026features.InitFeatureGates, cfg.FeatureGates); len(msg) \u003e 0 {\n\t\tfor _, m := range msg {\n\t\t\tprinter.Printf(\"[upgrade/config] %s\\n\", m)\n\t\t}\n\t\treturn nil, nil, nil, errors.New(\"[upgrade/config] FATAL. Unable to upgrade a cluster using deprecated feature-gate flags. Please see the release notes\")\n\t}\n\n\t// If the user told us to print this information out; do it!\n\tif flags.printConfig {\n\t\tprintConfiguration(\u0026cfg.ClusterConfiguration, os.Stdout, printer)\n\t}\n\n\t// Use a real version getter interface that queries the API server, the kubeadm client and the Kubernetes CI system for latest versions\n\treturn client, upgrade.NewOfflineVersionGetter(upgrade.NewKubeVersionGetter(client), newK8sVersion), cfg, nil\n}","line":{"from":124,"to":218}} {"id":100000754,"name":"printConfiguration","signature":"func printConfiguration(clustercfg *kubeadmapi.ClusterConfiguration, w io.Writer, printer output.Printer)","file":"cmd/kubeadm/app/cmd/upgrade/common.go","code":"// printConfiguration prints the external version of the API to yaml\nfunc printConfiguration(clustercfg *kubeadmapi.ClusterConfiguration, w io.Writer, printer output.Printer) {\n\t// Short-circuit if cfg is nil, so we can safely get the value of the pointer below\n\tif clustercfg == nil {\n\t\treturn\n\t}\n\n\tcfgYaml, err := configutil.MarshalKubeadmConfigObject(clustercfg)\n\tif err == nil {\n\t\tprinter.Fprintln(w, \"[upgrade/config] Configuration used:\")\n\n\t\tscanner := bufio.NewScanner(bytes.NewReader(cfgYaml))\n\t\tfor scanner.Scan() {\n\t\t\tprinter.Fprintf(w, \"\\t%s\\n\", scanner.Text())\n\t\t}\n\t}\n}","line":{"from":220,"to":236}} {"id":100000755,"name":"runPreflightChecks","signature":"func runPreflightChecks(client clientset.Interface, ignorePreflightErrors sets.Set[string], cfg *kubeadmapi.ClusterConfiguration, printer output.Printer) error","file":"cmd/kubeadm/app/cmd/upgrade/common.go","code":"// runPreflightChecks runs the root preflight check\nfunc runPreflightChecks(client clientset.Interface, ignorePreflightErrors sets.Set[string], cfg *kubeadmapi.ClusterConfiguration, printer output.Printer) error {\n\tprinter.Printf(\"[preflight] Running pre-flight checks.\\n\")\n\terr := preflight.RunRootCheckOnly(ignorePreflightErrors)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn upgrade.RunCoreDNSMigrationCheck(client, ignorePreflightErrors)\n}","line":{"from":238,"to":246}} {"id":100000756,"name":"getClient","signature":"func getClient(file string, dryRun bool) (clientset.Interface, error)","file":"cmd/kubeadm/app/cmd/upgrade/common.go","code":"// getClient gets a real or fake client depending on whether the user is dry-running or not\nfunc getClient(file string, dryRun bool) (clientset.Interface, error) {\n\tif dryRun {\n\t\tdryRunGetter, err := apiclient.NewClientBackedDryRunGetterFromKubeconfig(file)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// In order for fakeclient.Discovery().ServerVersion() to return the backing API Server's\n\t\t// real version; we have to do some clever API machinery tricks. First, we get the real\n\t\t// API Server's version\n\t\trealServerVersion, err := dryRunGetter.Client().Discovery().ServerVersion()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to get server version\")\n\t\t}\n\n\t\t// Get the fake clientset\n\t\tdryRunOpts := apiclient.GetDefaultDryRunClientOptions(dryRunGetter, os.Stdout)\n\t\t// Print GET and LIST requests\n\t\tdryRunOpts.PrintGETAndLIST = true\n\t\tfakeclient := apiclient.NewDryRunClientWithOpts(dryRunOpts)\n\t\t// As we know the return of Discovery() of the fake clientset is of type *fakediscovery.FakeDiscovery\n\t\t// we can convert it to that struct.\n\t\tfakeclientDiscovery, ok := fakeclient.Discovery().(*fakediscovery.FakeDiscovery)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"couldn't set fake discovery's server version\")\n\t\t}\n\t\t// Lastly, set the right server version to be used\n\t\tfakeclientDiscovery.FakedServerVersion = realServerVersion\n\t\t// return the fake clientset used for dry-running\n\t\treturn fakeclient, nil\n\t}\n\treturn kubeconfigutil.ClientSetFromFile(file)\n}","line":{"from":248,"to":281}} {"id":100000757,"name":"getWaiter","signature":"func getWaiter(dryRun bool, client clientset.Interface, timeout time.Duration) apiclient.Waiter","file":"cmd/kubeadm/app/cmd/upgrade/common.go","code":"// getWaiter gets the right waiter implementation\nfunc getWaiter(dryRun bool, client clientset.Interface, timeout time.Duration) apiclient.Waiter {\n\tif dryRun {\n\t\treturn dryrunutil.NewWaiter()\n\t}\n\treturn apiclient.NewKubeWaiter(client, timeout, os.Stdout)\n}","line":{"from":283,"to":289}} {"id":100000758,"name":"newCmdDiff","signature":"func newCmdDiff(out io.Writer) *cobra.Command","file":"cmd/kubeadm/app/cmd/upgrade/diff.go","code":"// newCmdDiff returns the cobra command for `kubeadm upgrade diff`\nfunc newCmdDiff(out io.Writer) *cobra.Command {\n\tflags := \u0026diffFlags{\n\t\tkubeConfigPath: constants.GetAdminKubeConfigPath(),\n\t\tout: out,\n\t}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"diff [version]\",\n\t\tShort: \"Show what differences would be applied to existing static pod manifests. See also: kubeadm upgrade apply --dry-run\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\t// Run preflight checks for diff to check that the manifests already exist.\n\t\t\tif err := validateManifestsPath(\n\t\t\t\tflags.apiServerManifestPath,\n\t\t\t\tflags.controllerManagerManifestPath,\n\t\t\t\tflags.schedulerManifestPath); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn runDiff(flags, args)\n\t\t},\n\t}\n\n\toptions.AddKubeConfigFlag(cmd.Flags(), \u0026flags.kubeConfigPath)\n\toptions.AddConfigFlag(cmd.Flags(), \u0026flags.cfgPath)\n\tcmd.Flags().StringVar(\u0026flags.apiServerManifestPath, \"api-server-manifest\", defaultAPIServerManifestPath, \"path to API server manifest\")\n\tcmd.Flags().StringVar(\u0026flags.controllerManagerManifestPath, \"controller-manager-manifest\", defaultControllerManagerManifestPath, \"path to controller manifest\")\n\tcmd.Flags().StringVar(\u0026flags.schedulerManifestPath, \"scheduler-manifest\", defaultSchedulerManifestPath, \"path to scheduler manifest\")\n\tcmd.Flags().IntVarP(\u0026flags.contextLines, \"context-lines\", \"c\", 3, \"How many lines of context in the diff\")\n\n\treturn cmd\n}","line":{"from":59,"to":89}} {"id":100000759,"name":"validateManifestsPath","signature":"func validateManifestsPath(manifests ...string) (err error)","file":"cmd/kubeadm/app/cmd/upgrade/diff.go","code":"func validateManifestsPath(manifests ...string) (err error) {\n\tfor _, manifestPath := range manifests {\n\t\tif len(manifestPath) == 0 {\n\t\t\treturn errors.New(\"empty manifest path\")\n\t\t}\n\t\ts, err := os.Stat(manifestPath)\n\t\tif err != nil {\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\treturn errors.Wrapf(err, \"the manifest file %q does not exist\", manifestPath)\n\t\t\t}\n\t\t\treturn errors.Wrapf(err, \"error obtaining stats for manifest file %q\", manifestPath)\n\t\t}\n\t\tif s.IsDir() {\n\t\t\treturn errors.Errorf(\"%q is a directory\", manifestPath)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":91,"to":108}} {"id":100000760,"name":"runDiff","signature":"func runDiff(flags *diffFlags, args []string) error","file":"cmd/kubeadm/app/cmd/upgrade/diff.go","code":"func runDiff(flags *diffFlags, args []string) error {\n\tvar err error\n\tvar cfg *kubeadmapi.InitConfiguration\n\tif flags.cfgPath != \"\" {\n\t\tcfg, err = configutil.LoadInitConfigurationFromFile(flags.cfgPath)\n\t} else {\n\t\tvar client *client.Clientset\n\t\tclient, err = kubeconfigutil.ClientSetFromFile(flags.kubeConfigPath)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"couldn't create a Kubernetes client from file %q\", flags.kubeConfigPath)\n\t\t}\n\t\tcfg, err = configutil.FetchInitConfigurationFromCluster(client, nil, \"upgrade/diff\", false, false)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// If the version is specified in config file, pick up that value.\n\tif cfg.KubernetesVersion != \"\" {\n\t\tflags.newK8sVersionStr = cfg.KubernetesVersion\n\t}\n\n\t// If the new version is already specified in config file, version arg is optional.\n\tif flags.newK8sVersionStr == \"\" {\n\t\tif err := cmdutil.ValidateExactArgNumber(args, []string{\"version\"}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// If option was specified in both args and config file, args will overwrite the config file.\n\tif len(args) == 1 {\n\t\tflags.newK8sVersionStr = args[0]\n\t}\n\n\t_, err = version.ParseSemantic(flags.newK8sVersionStr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcfg.ClusterConfiguration.KubernetesVersion = flags.newK8sVersionStr\n\n\tspecs := controlplane.GetStaticPodSpecs(\u0026cfg.ClusterConfiguration, \u0026cfg.LocalAPIEndpoint)\n\tfor spec, pod := range specs {\n\t\tvar path string\n\t\tswitch spec {\n\t\tcase constants.KubeAPIServer:\n\t\t\tpath = flags.apiServerManifestPath\n\t\tcase constants.KubeControllerManager:\n\t\t\tpath = flags.controllerManagerManifestPath\n\t\tcase constants.KubeScheduler:\n\t\t\tpath = flags.schedulerManifestPath\n\t\tdefault:\n\t\t\tklog.Errorf(\"[diff] unknown spec %v\", spec)\n\t\t\tcontinue\n\t\t}\n\n\t\tnewManifest, err := kubeadmutil.MarshalToYaml(\u0026pod, corev1.SchemeGroupVersion)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif path == \"\" {\n\t\t\treturn errors.New(\"empty manifest path\")\n\t\t}\n\t\texistingManifest, err := os.ReadFile(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Populated and write out the diff\n\t\tdiff := difflib.UnifiedDiff{\n\t\t\tA: difflib.SplitLines(string(existingManifest)),\n\t\t\tB: difflib.SplitLines(string(newManifest)),\n\t\t\tFromFile: path,\n\t\t\tToFile: \"new manifest\",\n\t\t\tContext: flags.contextLines,\n\t\t}\n\n\t\tdifflib.WriteUnifiedDiff(flags.out, diff)\n\t}\n\treturn nil\n}","line":{"from":110,"to":190}} {"id":100000761,"name":"newCmdNode","signature":"func newCmdNode(out io.Writer) *cobra.Command","file":"cmd/kubeadm/app/cmd/upgrade/node.go","code":"// newCmdNode returns the cobra command for `kubeadm upgrade node`\nfunc newCmdNode(out io.Writer) *cobra.Command {\n\tnodeOptions := newNodeOptions()\n\tnodeRunner := workflow.NewRunner()\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"node\",\n\t\tShort: \"Upgrade commands for a node in the cluster\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn nodeRunner.Run(args)\n\t\t},\n\t\tArgs: cobra.NoArgs,\n\t}\n\n\t// adds flags to the node command\n\t// flags could be eventually inherited by the sub-commands automatically generated for phases\n\taddUpgradeNodeFlags(cmd.Flags(), nodeOptions)\n\toptions.AddPatchesFlag(cmd.Flags(), \u0026nodeOptions.patchesDir)\n\n\t// initialize the workflow runner with the list of phases\n\tnodeRunner.AppendPhase(phases.NewPreflightPhase())\n\tnodeRunner.AppendPhase(phases.NewControlPlane())\n\tnodeRunner.AppendPhase(phases.NewKubeletConfigPhase())\n\n\t// sets the data builder function, that will be used by the runner\n\t// both when running the entire workflow or single phases\n\tnodeRunner.SetDataInitializer(func(cmd *cobra.Command, args []string) (workflow.RunData, error) {\n\t\treturn newNodeData(cmd, args, nodeOptions, out)\n\t})\n\n\t// binds the Runner to kubeadm upgrade node command by altering\n\t// command help, adding --skip-phases flag and by adding phases subcommands\n\tnodeRunner.BindToCommand(cmd)\n\n\treturn cmd\n}","line":{"from":69,"to":104}} {"id":100000762,"name":"newNodeOptions","signature":"func newNodeOptions() *nodeOptions","file":"cmd/kubeadm/app/cmd/upgrade/node.go","code":"// newNodeOptions returns a struct ready for being used for creating cmd kubeadm upgrade node flags.\nfunc newNodeOptions() *nodeOptions {\n\treturn \u0026nodeOptions{\n\t\tkubeConfigPath: constants.GetKubeletKubeConfigPath(),\n\t\tdryRun: false,\n\t\trenewCerts: true,\n\t\tetcdUpgrade: true,\n\t}\n}","line":{"from":106,"to":114}} {"id":100000763,"name":"addUpgradeNodeFlags","signature":"func addUpgradeNodeFlags(flagSet *flag.FlagSet, nodeOptions *nodeOptions)","file":"cmd/kubeadm/app/cmd/upgrade/node.go","code":"func addUpgradeNodeFlags(flagSet *flag.FlagSet, nodeOptions *nodeOptions) {\n\toptions.AddKubeConfigFlag(flagSet, \u0026nodeOptions.kubeConfigPath)\n\tflagSet.BoolVar(\u0026nodeOptions.dryRun, options.DryRun, nodeOptions.dryRun, \"Do not change any state, just output the actions that would be performed.\")\n\tflagSet.BoolVar(\u0026nodeOptions.renewCerts, options.CertificateRenewal, nodeOptions.renewCerts, \"Perform the renewal of certificates used by component changed during upgrades.\")\n\tflagSet.BoolVar(\u0026nodeOptions.etcdUpgrade, options.EtcdUpgrade, nodeOptions.etcdUpgrade, \"Perform the upgrade of etcd.\")\n\tflagSet.StringSliceVar(\u0026nodeOptions.ignorePreflightErrors, options.IgnorePreflightErrors, nodeOptions.ignorePreflightErrors, \"A list of checks whose errors will be shown as warnings. Example: 'IsPrivilegedUser,Swap'. Value 'all' ignores errors from all checks.\")\n}","line":{"from":116,"to":122}} {"id":100000764,"name":"newNodeData","signature":"func newNodeData(cmd *cobra.Command, args []string, options *nodeOptions, out io.Writer) (*nodeData, error)","file":"cmd/kubeadm/app/cmd/upgrade/node.go","code":"// newNodeData returns a new nodeData struct to be used for the execution of the kubeadm upgrade node workflow.\n// This func takes care of validating nodeOptions passed to the command, and then it converts\n// options into the internal InitConfiguration type that is used as input all the phases in the kubeadm upgrade node workflow\nfunc newNodeData(cmd *cobra.Command, args []string, options *nodeOptions, out io.Writer) (*nodeData, error) {\n\tclient, err := getClient(options.kubeConfigPath, options.dryRun)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"couldn't create a Kubernetes client from file %q\", options.kubeConfigPath)\n\t}\n\n\t// isControlPlane checks if a node is a control-plane node by looking up\n\t// the kube-apiserver manifest file\n\tisControlPlaneNode := true\n\tfilepath := constants.GetStaticPodFilepath(constants.KubeAPIServer, constants.GetStaticPodDirectory())\n\tif _, err := os.Stat(filepath); os.IsNotExist(err) {\n\t\tisControlPlaneNode = false\n\t}\n\n\t// Fetches the cluster configuration\n\t// NB in case of control-plane node, we are reading all the info for the node; in case of NOT control-plane node\n\t// (worker node), we are not reading local API address and the CRI socket from the node object\n\tcfg, err := configutil.FetchInitConfigurationFromCluster(client, nil, \"upgrade\", !isControlPlaneNode, false)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to fetch the kubeadm-config ConfigMap\")\n\t}\n\n\tignorePreflightErrorsSet, err := validation.ValidateIgnorePreflightErrors(options.ignorePreflightErrors, cfg.NodeRegistration.IgnorePreflightErrors)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Also set the union of pre-flight errors to JoinConfiguration, to provide a consistent view of the runtime configuration:\n\tcfg.NodeRegistration.IgnorePreflightErrors = sets.List(ignorePreflightErrorsSet)\n\treturn \u0026nodeData{\n\t\tetcdUpgrade: options.etcdUpgrade,\n\t\trenewCerts: options.renewCerts,\n\t\tdryRun: options.dryRun,\n\t\tcfg: cfg,\n\t\tclient: client,\n\t\tisControlPlaneNode: isControlPlaneNode,\n\t\tpatchesDir: options.patchesDir,\n\t\tignorePreflightErrors: ignorePreflightErrorsSet,\n\t\tkubeConfigPath: options.kubeConfigPath,\n\t\toutputWriter: out,\n\t}, nil\n}","line":{"from":124,"to":167}} {"id":100000765,"name":"DryRun","signature":"func (d *nodeData) DryRun() bool","file":"cmd/kubeadm/app/cmd/upgrade/node.go","code":"// DryRun returns the dryRun flag.\nfunc (d *nodeData) DryRun() bool {\n\treturn d.dryRun\n}","line":{"from":169,"to":172}} {"id":100000766,"name":"EtcdUpgrade","signature":"func (d *nodeData) EtcdUpgrade() bool","file":"cmd/kubeadm/app/cmd/upgrade/node.go","code":"// EtcdUpgrade returns the etcdUpgrade flag.\nfunc (d *nodeData) EtcdUpgrade() bool {\n\treturn d.etcdUpgrade\n}","line":{"from":174,"to":177}} {"id":100000767,"name":"RenewCerts","signature":"func (d *nodeData) RenewCerts() bool","file":"cmd/kubeadm/app/cmd/upgrade/node.go","code":"// RenewCerts returns the renewCerts flag.\nfunc (d *nodeData) RenewCerts() bool {\n\treturn d.renewCerts\n}","line":{"from":179,"to":182}} {"id":100000768,"name":"Cfg","signature":"func (d *nodeData) Cfg() *kubeadmapi.InitConfiguration","file":"cmd/kubeadm/app/cmd/upgrade/node.go","code":"// Cfg returns initConfiguration.\nfunc (d *nodeData) Cfg() *kubeadmapi.InitConfiguration {\n\treturn d.cfg\n}","line":{"from":184,"to":187}} {"id":100000769,"name":"IsControlPlaneNode","signature":"func (d *nodeData) IsControlPlaneNode() bool","file":"cmd/kubeadm/app/cmd/upgrade/node.go","code":"// IsControlPlaneNode returns the isControlPlaneNode flag.\nfunc (d *nodeData) IsControlPlaneNode() bool {\n\treturn d.isControlPlaneNode\n}","line":{"from":189,"to":192}} {"id":100000770,"name":"Client","signature":"func (d *nodeData) Client() clientset.Interface","file":"cmd/kubeadm/app/cmd/upgrade/node.go","code":"// Client returns a Kubernetes client to be used by kubeadm.\nfunc (d *nodeData) Client() clientset.Interface {\n\treturn d.client\n}","line":{"from":194,"to":197}} {"id":100000771,"name":"PatchesDir","signature":"func (d *nodeData) PatchesDir() string","file":"cmd/kubeadm/app/cmd/upgrade/node.go","code":"// PatchesDir returns the folder where patches for components are stored\nfunc (d *nodeData) PatchesDir() string {\n\treturn d.patchesDir\n}","line":{"from":199,"to":202}} {"id":100000772,"name":"IgnorePreflightErrors","signature":"func (d *nodeData) IgnorePreflightErrors() sets.Set[string]","file":"cmd/kubeadm/app/cmd/upgrade/node.go","code":"// IgnorePreflightErrors returns the list of preflight errors to ignore.\nfunc (d *nodeData) IgnorePreflightErrors() sets.Set[string] {\n\treturn d.ignorePreflightErrors\n}","line":{"from":204,"to":207}} {"id":100000773,"name":"KubeConfigPath","signature":"func (d *nodeData) KubeConfigPath() string","file":"cmd/kubeadm/app/cmd/upgrade/node.go","code":"// KubeconfigPath returns the path to the user kubeconfig file.\nfunc (d *nodeData) KubeConfigPath() string {\n\treturn d.kubeConfigPath\n}","line":{"from":209,"to":212}} {"id":100000774,"name":"OutputWriter","signature":"func (d *nodeData) OutputWriter() io.Writer","file":"cmd/kubeadm/app/cmd/upgrade/node.go","code":"func (d *nodeData) OutputWriter() io.Writer {\n\treturn d.outputWriter\n}","line":{"from":214,"to":216}} {"id":100000775,"name":"newCmdPlan","signature":"func newCmdPlan(apf *applyPlanFlags) *cobra.Command","file":"cmd/kubeadm/app/cmd/upgrade/plan.go","code":"// newCmdPlan returns the cobra command for `kubeadm upgrade plan`\nfunc newCmdPlan(apf *applyPlanFlags) *cobra.Command {\n\tflags := \u0026planFlags{\n\t\tapplyPlanFlags: apf,\n\t}\n\n\toutputFlags := newUpgradePlanPrintFlags(output.TextOutput)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"plan [version] [flags]\",\n\t\tShort: \"Check which versions are available to upgrade to and validate whether your current cluster is upgradeable. To skip the internet check, pass in the optional [version] parameter\",\n\t\tRunE: func(_ *cobra.Command, args []string) error {\n\t\t\tprinter, err := outputFlags.ToPrinter()\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"could not construct output printer\")\n\t\t\t}\n\n\t\t\treturn runPlan(flags, args, printer)\n\t\t},\n\t}\n\n\toutputFlags.AddFlags(cmd)\n\n\t// Register the common flags for apply and plan\n\taddApplyPlanFlags(cmd.Flags(), flags.applyPlanFlags)\n\treturn cmd\n}","line":{"from":52,"to":78}} {"id":100000776,"name":"newComponentUpgradePlan","signature":"func newComponentUpgradePlan(name, currentVersion, newVersion string) outputapiv1alpha2.ComponentUpgradePlan","file":"cmd/kubeadm/app/cmd/upgrade/plan.go","code":"// newComponentUpgradePlan helper creates outputapiv1alpha2.ComponentUpgradePlan object\nfunc newComponentUpgradePlan(name, currentVersion, newVersion string) outputapiv1alpha2.ComponentUpgradePlan {\n\treturn outputapiv1alpha2.ComponentUpgradePlan{\n\t\tName: name,\n\t\tCurrentVersion: currentVersion,\n\t\tNewVersion: newVersion,\n\t}\n}","line":{"from":80,"to":87}} {"id":100000777,"name":"newUpgradePlanPrintFlags","signature":"func newUpgradePlanPrintFlags(outputFormat string) *upgradePlanPrintFlags","file":"cmd/kubeadm/app/cmd/upgrade/plan.go","code":"func newUpgradePlanPrintFlags(outputFormat string) *upgradePlanPrintFlags {\n\treturn \u0026upgradePlanPrintFlags{\n\t\tJSONYamlPrintFlags: \u0026upgradePlanJSONYamlPrintFlags{},\n\t\tTextPrintFlags: \u0026upgradePlanTextPrintFlags{},\n\t\tTypeSetterPrinter: printers.NewTypeSetter(outputapischeme.Scheme),\n\t\tOutputFormat: strings.ToLower(outputFormat),\n\t}\n}","line":{"from":103,"to":110}} {"id":100000778,"name":"AllowedFormats","signature":"func (pf *upgradePlanPrintFlags) AllowedFormats() []string","file":"cmd/kubeadm/app/cmd/upgrade/plan.go","code":"// AllowedFormats returns a list of allowed output formats\nfunc (pf *upgradePlanPrintFlags) AllowedFormats() []string {\n\tret := pf.TextPrintFlags.AllowedFormats()\n\treturn append(ret, pf.JSONYamlPrintFlags.AllowedFormats()...)\n}","line":{"from":112,"to":116}} {"id":100000779,"name":"AddFlags","signature":"func (pf *upgradePlanPrintFlags) AddFlags(cmd *cobra.Command)","file":"cmd/kubeadm/app/cmd/upgrade/plan.go","code":"// AddFlags receives a *cobra.Command reference and binds\n// flags related to Kubeadm printing to it\nfunc (pf *upgradePlanPrintFlags) AddFlags(cmd *cobra.Command) {\n\tpf.TextPrintFlags.AddFlags(cmd)\n\tpf.JSONYamlPrintFlags.AddFlags(cmd)\n\t// TODO: once we are confident the feature is graduated we should remove the EXPERIMENTAL text below:\n\t// https://github.com/kubernetes/kubeadm/issues/494\n\tcmd.Flags().StringVarP(\u0026pf.OutputFormat, \"output\", \"o\", pf.OutputFormat, fmt.Sprintf(\"EXPERIMENTAL: Output format. One of: %s.\", strings.Join(pf.AllowedFormats(), \"|\")))\n}","line":{"from":118,"to":126}} {"id":100000780,"name":"ToPrinter","signature":"func (pf *upgradePlanPrintFlags) ToPrinter() (output.Printer, error)","file":"cmd/kubeadm/app/cmd/upgrade/plan.go","code":"// ToPrinter receives an outputFormat and returns a printer capable of\n// handling format printing.\n// Returns error if the specified outputFormat does not match supported formats.\nfunc (pf *upgradePlanPrintFlags) ToPrinter() (output.Printer, error) {\n\tswitch pf.OutputFormat {\n\tcase output.TextOutput:\n\t\treturn pf.TextPrintFlags.ToPrinter(pf.OutputFormat)\n\tcase output.JSONOutput:\n\t\treturn newUpgradePlanJSONYAMLPrinter(pf.TypeSetterPrinter.WrapToPrinter(pf.JSONYamlPrintFlags.ToPrinter(output.JSONOutput)))\n\tcase output.YAMLOutput:\n\t\treturn newUpgradePlanJSONYAMLPrinter(pf.TypeSetterPrinter.WrapToPrinter(pf.JSONYamlPrintFlags.ToPrinter(output.YAMLOutput)))\n\tdefault:\n\t\treturn nil, genericclioptions.NoCompatiblePrinterError{OutputFormat: \u0026pf.OutputFormat, AllowedFormats: pf.AllowedFormats()}\n\t}\n}","line":{"from":128,"to":142}} {"id":100000781,"name":"AllowedFormats","signature":"func (pf *upgradePlanJSONYamlPrintFlags) AllowedFormats() []string","file":"cmd/kubeadm/app/cmd/upgrade/plan.go","code":"// AllowedFormats returns a list of allowed output formats\nfunc (pf *upgradePlanJSONYamlPrintFlags) AllowedFormats() []string {\n\treturn []string{output.JSONOutput, output.YAMLOutput}\n}","line":{"from":148,"to":151}} {"id":100000782,"name":"newUpgradePlanJSONYAMLPrinter","signature":"func newUpgradePlanJSONYAMLPrinter(resourcePrinter printers.ResourcePrinter, err error) (output.Printer, error)","file":"cmd/kubeadm/app/cmd/upgrade/plan.go","code":"// newUpgradePlanJSONYAMLPrinter creates a new upgradePlanJSONYAMLPrinter object\nfunc newUpgradePlanJSONYAMLPrinter(resourcePrinter printers.ResourcePrinter, err error) (output.Printer, error) {\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026upgradePlanJSONYAMLPrinter{ResourcePrinterWrapper: output.ResourcePrinterWrapper{Printer: resourcePrinter}}, nil\n}","line":{"from":159,"to":165}} {"id":100000783,"name":"PrintObj","signature":"func (p *upgradePlanJSONYAMLPrinter) PrintObj(obj runtime.Object, writer io.Writer) error","file":"cmd/kubeadm/app/cmd/upgrade/plan.go","code":"// PrintObj is an implementation of ResourcePrinter.PrintObj that adds object to the buffer\nfunc (p *upgradePlanJSONYAMLPrinter) PrintObj(obj runtime.Object, writer io.Writer) error {\n\titem, ok := obj.(*outputapiv1alpha2.ComponentUpgradePlan)\n\tif !ok {\n\t\treturn errors.Errorf(\"expected ComponentUpgradePlan, but got %+v\", obj)\n\t}\n\tp.Buffer = append(p.Buffer, *item)\n\treturn nil\n}","line":{"from":167,"to":175}} {"id":100000784,"name":"Flush","signature":"func (p *upgradePlanJSONYAMLPrinter) Flush(writer io.Writer, last bool)","file":"cmd/kubeadm/app/cmd/upgrade/plan.go","code":"// Flush writes any buffered data once last object is added\nfunc (p *upgradePlanJSONYAMLPrinter) Flush(writer io.Writer, last bool) {\n\tif !last {\n\t\treturn\n\t}\n\tif len(p.Buffer) == 0 {\n\t\treturn\n\t}\n\tplan := \u0026outputapiv1alpha2.UpgradePlan{Components: p.Buffer}\n\tif err := p.Printer.PrintObj(plan, writer); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"could not flush output buffer: %v\\n\", err)\n\t}\n}","line":{"from":177,"to":189}} {"id":100000785,"name":"Close","signature":"func (p *upgradePlanJSONYAMLPrinter) Close(writer io.Writer)","file":"cmd/kubeadm/app/cmd/upgrade/plan.go","code":"// Close empties the list of buffered components\nfunc (p *upgradePlanJSONYAMLPrinter) Close(writer io.Writer) {\n\tp.Buffer = p.Buffer[:0]\n}","line":{"from":191,"to":194}} {"id":100000786,"name":"Flush","signature":"func (p *upgradePlanTextPrinter) Flush(writer io.Writer, last bool)","file":"cmd/kubeadm/app/cmd/upgrade/plan.go","code":"// Flush writes any buffered data\nfunc (p *upgradePlanTextPrinter) Flush(writer io.Writer, last bool) {\n\tif p.tabwriter != nil {\n\t\tp.tabwriter.Flush()\n\t\tp.tabwriter = nil\n\t\tp.Fprintln(writer, \"\")\n\t}\n}","line":{"from":203,"to":210}} {"id":100000787,"name":"PrintObj","signature":"func (p *upgradePlanTextPrinter) PrintObj(obj runtime.Object, writer io.Writer) error","file":"cmd/kubeadm/app/cmd/upgrade/plan.go","code":"// PrintObj is an implementation of ResourcePrinter.PrintObj for upgrade plan plain text output\nfunc (p *upgradePlanTextPrinter) PrintObj(obj runtime.Object, writer io.Writer) error {\n\tif p.tabwriter == nil {\n\t\tp.tabwriter = tabwriter.NewWriter(writer, 10, 4, 3, ' ', 0)\n\t\t// Print header\n\t\tfmt.Fprintln(p.tabwriter, strings.Join(p.columns, \"\\t\"))\n\t}\n\n\titem, ok := obj.(*outputapiv1alpha2.ComponentUpgradePlan)\n\tif !ok {\n\t\treturn errors.Errorf(\"expected ComponentUpgradePlan, but got %+v\", obj)\n\t}\n\n\t// Print item\n\tfmt.Fprintf(p.tabwriter, \"%s\\t%s\\t%s\\n\", item.Name, item.CurrentVersion, item.NewVersion)\n\treturn nil\n}","line":{"from":212,"to":228}} {"id":100000788,"name":"AddFlags","signature":"func (pf *upgradePlanTextPrintFlags) AddFlags(cmd *cobra.Command) {}","file":"cmd/kubeadm/app/cmd/upgrade/plan.go","code":"func (pf *upgradePlanTextPrintFlags) AddFlags(cmd *cobra.Command) {}","line":{"from":233,"to":233}} {"id":100000789,"name":"AllowedFormats","signature":"func (pf *upgradePlanTextPrintFlags) AllowedFormats() []string","file":"cmd/kubeadm/app/cmd/upgrade/plan.go","code":"// AllowedFormats returns a list of allowed output formats\nfunc (pf *upgradePlanTextPrintFlags) AllowedFormats() []string {\n\treturn []string{output.TextOutput}\n}","line":{"from":235,"to":238}} {"id":100000790,"name":"ToPrinter","signature":"func (pf *upgradePlanTextPrintFlags) ToPrinter(outputFormat string) (output.Printer, error)","file":"cmd/kubeadm/app/cmd/upgrade/plan.go","code":"// ToPrinter returns a kubeadm printer for the text output format\nfunc (pf *upgradePlanTextPrintFlags) ToPrinter(outputFormat string) (output.Printer, error) {\n\tif outputFormat == output.TextOutput {\n\t\treturn \u0026upgradePlanTextPrinter{columns: []string{\"COMPONENT\", \"CURRENT\", \"TARGET\"}}, nil\n\t}\n\treturn nil, genericclioptions.NoCompatiblePrinterError{OutputFormat: \u0026outputFormat, AllowedFormats: []string{output.JSONOutput, output.YAMLOutput, output.TextOutput}}\n}","line":{"from":240,"to":246}} {"id":100000791,"name":"runPlan","signature":"func runPlan(flags *planFlags, args []string, printer output.Printer) error","file":"cmd/kubeadm/app/cmd/upgrade/plan.go","code":"// runPlan takes care of outputting available versions to upgrade to for the user\nfunc runPlan(flags *planFlags, args []string, printer output.Printer) error {\n\t// Start with the basics, verify that the cluster is healthy, build a client and a versionGetter. Never dry-run when planning.\n\tklog.V(1).Infoln(\"[upgrade/plan] verifying health of cluster\")\n\tklog.V(1).Infoln(\"[upgrade/plan] retrieving configuration from cluster\")\n\tclient, versionGetter, cfg, err := enforceRequirements(flags.applyPlanFlags, args, false, false, printer, loadConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Currently this is the only method we have for distinguishing\n\t// external etcd vs static pod etcd\n\tisExternalEtcd := cfg.Etcd.External != nil\n\n\t// Compute which upgrade possibilities there are\n\tklog.V(1).Infoln(\"[upgrade/plan] computing upgrade possibilities\")\n\tavailUpgrades, err := upgrade.GetAvailableUpgrades(versionGetter, flags.allowExperimentalUpgrades, flags.allowRCUpgrades, isExternalEtcd, client, constants.GetStaticPodDirectory(), printer)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"[upgrade/versions] FATAL\")\n\t}\n\n\t// Fetch the current state of the component configs\n\tklog.V(1).Infoln(\"[upgrade/plan] analysing component config version states\")\n\tconfigVersionStates, err := getComponentConfigVersionStates(\u0026cfg.ClusterConfiguration, client, flags.cfgPath)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"[upgrade/versions] FATAL\")\n\t}\n\n\t// No upgrades available\n\tif len(availUpgrades) == 0 {\n\t\tklog.V(1).Infoln(\"[upgrade/plan] Awesome, you're up-to-date! Enjoy!\")\n\t\treturn nil\n\t}\n\n\t// Generate and print upgrade plans\n\tfor _, up := range availUpgrades {\n\t\tplan, unstableVersionFlag, err := genUpgradePlan(\u0026up, isExternalEtcd)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Actually, this is needed for machine-readable output only.\n\t\t// printUpgradePlan won't output the configVersionStates as it will simply print the same table several times\n\t\t// in the human-readable output if it did so\n\t\tplan.ConfigVersions = configVersionStates\n\n\t\tprintUpgradePlan(\u0026up, plan, unstableVersionFlag, isExternalEtcd, os.Stdout, printer)\n\t}\n\n\t// Finally, print the component config state table\n\tprintComponentConfigVersionStates(configVersionStates, os.Stdout, printer)\n\treturn nil\n}","line":{"from":248,"to":300}} {"id":100000792,"name":"appendDNSComponent","signature":"func appendDNSComponent(components []outputapiv1alpha2.ComponentUpgradePlan, up *upgrade.Upgrade, name string) []outputapiv1alpha2.ComponentUpgradePlan","file":"cmd/kubeadm/app/cmd/upgrade/plan.go","code":"// TODO There is currently no way to cleanly output upgrades that involve adding, removing, or changing components\n// https://github.com/kubernetes/kubeadm/issues/810 was created to track addressing this.\nfunc appendDNSComponent(components []outputapiv1alpha2.ComponentUpgradePlan, up *upgrade.Upgrade, name string) []outputapiv1alpha2.ComponentUpgradePlan {\n\tbeforeVersion := up.Before.DNSVersion\n\tafterVersion := up.After.DNSVersion\n\n\tif beforeVersion != \"\" || afterVersion != \"\" {\n\t\tcomponents = append(components, newComponentUpgradePlan(name, beforeVersion, afterVersion))\n\t}\n\treturn components\n}","line":{"from":302,"to":312}} {"id":100000793,"name":"genUpgradePlan","signature":"func genUpgradePlan(up *upgrade.Upgrade, isExternalEtcd bool) (*outputapiv1alpha2.UpgradePlan, string, error)","file":"cmd/kubeadm/app/cmd/upgrade/plan.go","code":"// genUpgradePlan generates output-friendly upgrade plan out of upgrade.Upgrade structure\nfunc genUpgradePlan(up *upgrade.Upgrade, isExternalEtcd bool) (*outputapiv1alpha2.UpgradePlan, string, error) {\n\tnewK8sVersion, err := version.ParseSemantic(up.After.KubeVersion)\n\tif err != nil {\n\t\treturn nil, \"\", errors.Wrapf(err, \"Unable to parse normalized version %q as a semantic version\", up.After.KubeVersion)\n\t}\n\n\tunstableVersionFlag := \"\"\n\tif len(newK8sVersion.PreRelease()) != 0 {\n\t\tif strings.HasPrefix(newK8sVersion.PreRelease(), \"rc\") {\n\t\t\tunstableVersionFlag = \" --allow-release-candidate-upgrades\"\n\t\t} else {\n\t\t\tunstableVersionFlag = \" --allow-experimental-upgrades\"\n\t\t}\n\t}\n\n\tcomponents := []outputapiv1alpha2.ComponentUpgradePlan{}\n\n\tif up.CanUpgradeKubelets() {\n\t\t// The map is of the form \u003cold-version\u003e:\u003cnode-count\u003e. Here all the keys are put into a slice and sorted\n\t\t// in order to always get the right order. Then the map value is extracted separately\n\t\tfor _, oldVersion := range sortedSliceFromStringIntMap(up.Before.KubeletVersions) {\n\t\t\tnodeCount := up.Before.KubeletVersions[oldVersion]\n\t\t\tcomponents = append(components, newComponentUpgradePlan(constants.Kubelet, fmt.Sprintf(\"%d x %s\", nodeCount, oldVersion), up.After.KubeVersion))\n\t\t}\n\t}\n\n\tcomponents = append(components, newComponentUpgradePlan(constants.KubeAPIServer, up.Before.KubeVersion, up.After.KubeVersion))\n\tcomponents = append(components, newComponentUpgradePlan(constants.KubeControllerManager, up.Before.KubeVersion, up.After.KubeVersion))\n\tcomponents = append(components, newComponentUpgradePlan(constants.KubeScheduler, up.Before.KubeVersion, up.After.KubeVersion))\n\tcomponents = append(components, newComponentUpgradePlan(constants.KubeProxy, up.Before.KubeVersion, up.After.KubeVersion))\n\n\tcomponents = appendDNSComponent(components, up, constants.CoreDNS)\n\n\tif !isExternalEtcd {\n\t\tcomponents = append(components, newComponentUpgradePlan(constants.Etcd, up.Before.EtcdVersion, up.After.EtcdVersion))\n\t}\n\n\treturn \u0026outputapiv1alpha2.UpgradePlan{Components: components}, unstableVersionFlag, nil\n}","line":{"from":314,"to":353}} {"id":100000794,"name":"getComponentConfigVersionStates","signature":"func getComponentConfigVersionStates(cfg *kubeadmapi.ClusterConfiguration, client clientset.Interface, cfgPath string) ([]outputapiv1alpha2.ComponentConfigVersionState, error)","file":"cmd/kubeadm/app/cmd/upgrade/plan.go","code":"func getComponentConfigVersionStates(cfg *kubeadmapi.ClusterConfiguration, client clientset.Interface, cfgPath string) ([]outputapiv1alpha2.ComponentConfigVersionState, error) {\n\tdocmap := kubeadmapi.DocumentMap{}\n\n\tif cfgPath != \"\" {\n\t\tbytes, err := os.ReadFile(cfgPath)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"unable to read config file %q\", cfgPath)\n\t\t}\n\n\t\tdocmap, err = kubeadmutil.SplitYAMLDocuments(bytes)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn componentconfigs.GetVersionStates(cfg, client, docmap)\n}","line":{"from":355,"to":371}} {"id":100000795,"name":"printUpgradePlan","signature":"func printUpgradePlan(up *upgrade.Upgrade, plan *outputapiv1alpha2.UpgradePlan, unstableVersionFlag string, isExternalEtcd bool, writer io.Writer, printer output.Printer)","file":"cmd/kubeadm/app/cmd/upgrade/plan.go","code":"// printUpgradePlan prints a UX-friendly overview of what versions are available to upgrade to\nfunc printUpgradePlan(up *upgrade.Upgrade, plan *outputapiv1alpha2.UpgradePlan, unstableVersionFlag string, isExternalEtcd bool, writer io.Writer, printer output.Printer) {\n\tprintHeader := true\n\tprintManualUpgradeHeader := true\n\tfor _, component := range plan.Components {\n\t\tif isExternalEtcd \u0026\u0026 component.Name == constants.Etcd {\n\t\t\t// Don't print etcd if it's external\n\t\t\tcontinue\n\t\t} else if component.Name == constants.Kubelet {\n\t\t\tif printManualUpgradeHeader {\n\t\t\t\tprinter.Fprintln(writer, \"Components that must be upgraded manually after you have upgraded the control plane with 'kubeadm upgrade apply':\")\n\t\t\t\tplan := newComponentUpgradePlan(component.Name, component.CurrentVersion, component.NewVersion)\n\t\t\t\tprinter.PrintObj(\u0026plan, writer)\n\t\t\t\tprintManualUpgradeHeader = false\n\t\t\t} else {\n\t\t\t\tplan := newComponentUpgradePlan(\"\", component.CurrentVersion, component.NewVersion)\n\t\t\t\tprinter.PrintObj(\u0026plan, writer)\n\t\t\t}\n\t\t} else {\n\t\t\tif printHeader {\n\t\t\t\t// End of manual upgrades table\n\t\t\t\tprinter.Flush(writer, false)\n\t\t\t\tprinter.Fprintf(writer, \"Upgrade to the latest %s:\\n\", up.Description)\n\t\t\t\tprinter.Fprintln(writer, \"\")\n\t\t\t\tprintHeader = false\n\t\t\t}\n\t\t\tplan := newComponentUpgradePlan(component.Name, component.CurrentVersion, component.NewVersion)\n\t\t\tprinter.PrintObj(\u0026plan, writer)\n\t\t}\n\t}\n\tprinter.Flush(writer, true)\n\n\tprinter.Fprintln(writer, \"You can now apply the upgrade by executing the following command:\")\n\tprinter.Fprintln(writer, \"\")\n\tprinter.Fprintf(writer, \"\\tkubeadm upgrade apply %s%s\\n\", up.After.KubeVersion, unstableVersionFlag)\n\tprinter.Fprintln(writer, \"\")\n\n\tif up.Before.KubeadmVersion != up.After.KubeadmVersion {\n\t\tprinter.Fprintf(writer, \"Note: Before you can perform this upgrade, you have to update kubeadm to %s.\\n\", up.After.KubeadmVersion)\n\t\tprinter.Fprintln(writer, \"\")\n\t}\n\n\tprintLineSeparator(writer, printer)\n\tprinter.Close(writer)\n}","line":{"from":373,"to":417}} {"id":100000796,"name":"sortedSliceFromStringIntMap","signature":"func sortedSliceFromStringIntMap(strMap map[string]uint16) []string","file":"cmd/kubeadm/app/cmd/upgrade/plan.go","code":"// sortedSliceFromStringIntMap returns a slice of the keys in the map sorted alphabetically\nfunc sortedSliceFromStringIntMap(strMap map[string]uint16) []string {\n\tstrSlice := []string{}\n\tfor k := range strMap {\n\t\tstrSlice = append(strSlice, k)\n\t}\n\tsort.Strings(strSlice)\n\treturn strSlice\n}","line":{"from":419,"to":427}} {"id":100000797,"name":"strOrDash","signature":"func strOrDash(s string) string","file":"cmd/kubeadm/app/cmd/upgrade/plan.go","code":"func strOrDash(s string) string {\n\tif s != \"\" {\n\t\treturn s\n\t}\n\treturn \"-\"\n}","line":{"from":429,"to":434}} {"id":100000798,"name":"yesOrNo","signature":"func yesOrNo(b bool) string","file":"cmd/kubeadm/app/cmd/upgrade/plan.go","code":"func yesOrNo(b bool) string {\n\tif b {\n\t\treturn \"yes\"\n\t}\n\treturn \"no\"\n}","line":{"from":436,"to":441}} {"id":100000799,"name":"printLineSeparator","signature":"func printLineSeparator(w io.Writer, printer output.Printer)","file":"cmd/kubeadm/app/cmd/upgrade/plan.go","code":"func printLineSeparator(w io.Writer, printer output.Printer) {\n\tprinter.Fprintf(w, \"_____________________________________________________________________\\n\\n\")\n}","line":{"from":443,"to":445}} {"id":100000800,"name":"printComponentConfigVersionStates","signature":"func printComponentConfigVersionStates(versionStates []outputapiv1alpha2.ComponentConfigVersionState, w io.Writer, printer output.Printer)","file":"cmd/kubeadm/app/cmd/upgrade/plan.go","code":"func printComponentConfigVersionStates(versionStates []outputapiv1alpha2.ComponentConfigVersionState, w io.Writer, printer output.Printer) {\n\tif len(versionStates) == 0 {\n\t\tprinter.Fprintln(w, \"No information available on component configs.\")\n\t\treturn\n\t}\n\n\tprinter.Fprintln(w, dedent.Dedent(`\n\t\tThe table below shows the current state of component configs as understood by this version of kubeadm.\n\t\tConfigs that have a \"yes\" mark in the \"MANUAL UPGRADE REQUIRED\" column require manual config upgrade or\n\t\tresetting to kubeadm defaults before a successful upgrade can be performed. The version to manually\n\t\tupgrade to is denoted in the \"PREFERRED VERSION\" column.\n\t`))\n\n\ttabw := tabwriter.NewWriter(w, 10, 4, 3, ' ', 0)\n\tprinter.Fprintln(tabw, \"API GROUP\\tCURRENT VERSION\\tPREFERRED VERSION\\tMANUAL UPGRADE REQUIRED\")\n\n\tfor _, state := range versionStates {\n\t\tprinter.Fprintf(tabw,\n\t\t\t\"%s\\t%s\\t%s\\t%s\\n\",\n\t\t\tstate.Group,\n\t\t\tstrOrDash(state.CurrentVersion),\n\t\t\tstrOrDash(state.PreferredVersion),\n\t\t\tyesOrNo(state.ManualUpgradeRequired),\n\t\t)\n\t}\n\n\ttabw.Flush()\n\tprintLineSeparator(w, printer)\n}","line":{"from":447,"to":475}} {"id":100000801,"name":"NewCmdUpgrade","signature":"func NewCmdUpgrade(out io.Writer) *cobra.Command","file":"cmd/kubeadm/app/cmd/upgrade/upgrade.go","code":"// NewCmdUpgrade returns the cobra command for `kubeadm upgrade`\nfunc NewCmdUpgrade(out io.Writer) *cobra.Command {\n\tflags := \u0026applyPlanFlags{\n\t\tkubeConfigPath: kubeadmconstants.GetAdminKubeConfigPath(),\n\t\tcfgPath: \"\",\n\t\tfeatureGatesString: \"\",\n\t\tallowExperimentalUpgrades: false,\n\t\tallowRCUpgrades: false,\n\t\tprintConfig: false,\n\t\tout: out,\n\t}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"upgrade\",\n\t\tShort: \"Upgrade your cluster smoothly to a newer version with this command\",\n\t\tRun: cmdutil.SubCmdRun(),\n\t}\n\n\tcmd.AddCommand(newCmdApply(flags))\n\tcmd.AddCommand(newCmdPlan(flags))\n\tcmd.AddCommand(newCmdDiff(out))\n\tcmd.AddCommand(newCmdNode(out))\n\treturn cmd\n}","line":{"from":42,"to":65}} {"id":100000802,"name":"addApplyPlanFlags","signature":"func addApplyPlanFlags(fs *pflag.FlagSet, flags *applyPlanFlags)","file":"cmd/kubeadm/app/cmd/upgrade/upgrade.go","code":"func addApplyPlanFlags(fs *pflag.FlagSet, flags *applyPlanFlags) {\n\toptions.AddKubeConfigFlag(fs, \u0026flags.kubeConfigPath)\n\toptions.AddConfigFlag(fs, \u0026flags.cfgPath)\n\n\tfs.BoolVar(\u0026flags.allowExperimentalUpgrades, \"allow-experimental-upgrades\", flags.allowExperimentalUpgrades, \"Show unstable versions of Kubernetes as an upgrade alternative and allow upgrading to an alpha/beta/release candidate versions of Kubernetes.\")\n\tfs.BoolVar(\u0026flags.allowRCUpgrades, \"allow-release-candidate-upgrades\", flags.allowRCUpgrades, \"Show release candidate versions of Kubernetes as an upgrade alternative and allow upgrading to a release candidate versions of Kubernetes.\")\n\tfs.BoolVar(\u0026flags.printConfig, \"print-config\", flags.printConfig, \"Specifies whether the configuration file that will be used in the upgrade should be printed or not.\")\n\toptions.AddFeatureGatesStringFlag(fs, \u0026flags.featureGatesString)\n\toptions.AddIgnorePreflightErrorsFlag(fs, \u0026flags.ignorePreflightErrors)\n}","line":{"from":67,"to":76}} {"id":100000803,"name":"SubCmdRun","signature":"func SubCmdRun() func(c *cobra.Command, args []string)","file":"cmd/kubeadm/app/cmd/util/cmdutil.go","code":"// SubCmdRun returns a function that handles a case where a subcommand must be specified\n// Without this callback, if a user runs just the command without a subcommand,\n// or with an invalid subcommand, cobra will print usage information, but still exit cleanly.\nfunc SubCmdRun() func(c *cobra.Command, args []string) {\n\treturn func(c *cobra.Command, args []string) {\n\t\tif len(args) \u003e 0 {\n\t\t\tkubeadmutil.CheckErr(usageErrorf(c, \"invalid subcommand %q\", strings.Join(args, \" \")))\n\t\t}\n\t\tc.Help()\n\t\tkubeadmutil.CheckErr(kubeadmutil.ErrExit)\n\t}\n}","line":{"from":42,"to":53}} {"id":100000804,"name":"usageErrorf","signature":"func usageErrorf(c *cobra.Command, format string, args ...interface{}) error","file":"cmd/kubeadm/app/cmd/util/cmdutil.go","code":"func usageErrorf(c *cobra.Command, format string, args ...interface{}) error {\n\tmsg := fmt.Sprintf(format, args...)\n\treturn errors.Errorf(\"%s\\nSee '%s -h' for help and examples\", msg, c.CommandPath())\n}","line":{"from":55,"to":58}} {"id":100000805,"name":"ValidateExactArgNumber","signature":"func ValidateExactArgNumber(args []string, supportedArgs []string) error","file":"cmd/kubeadm/app/cmd/util/cmdutil.go","code":"// ValidateExactArgNumber validates that the required top-level arguments are specified\nfunc ValidateExactArgNumber(args []string, supportedArgs []string) error {\n\tlenSupported := len(supportedArgs)\n\tvalidArgs := 0\n\t// Disregard possible \"\" arguments; they are invalid\n\tfor _, arg := range args {\n\t\tif len(arg) \u003e 0 {\n\t\t\tvalidArgs++\n\t\t}\n\t\t// break early for too many arguments\n\t\tif validArgs \u003e lenSupported {\n\t\t\treturn errors.Errorf(\"too many arguments. Required arguments: %v\", supportedArgs)\n\t\t}\n\t}\n\n\tif validArgs \u003c lenSupported {\n\t\treturn errors.Errorf(\"missing one or more required arguments. Required arguments: %v\", supportedArgs)\n\t}\n\treturn nil\n}","line":{"from":60,"to":79}} {"id":100000806,"name":"GetKubeConfigPath","signature":"func GetKubeConfigPath(file string) string","file":"cmd/kubeadm/app/cmd/util/cmdutil.go","code":"// GetKubeConfigPath can be used to search for a kubeconfig in standard locations\n// if and empty string is passed to the function. If a non-empty string is passed\n// the function returns the same string.\nfunc GetKubeConfigPath(file string) string {\n\t// If a value is provided respect that.\n\tif file != \"\" {\n\t\treturn file\n\t}\n\t// Find a config in the standard locations using DefaultClientConfigLoadingRules,\n\t// but also consider the default config path.\n\trules := clientcmd.NewDefaultClientConfigLoadingRules()\n\trules.Precedence = append(rules.Precedence, kubeadmconstants.GetAdminKubeConfigPath())\n\tfile = rules.GetDefaultFilename()\n\tklog.V(1).Infof(\"Using kubeconfig file: %s\", file)\n\treturn file\n}","line":{"from":81,"to":96}} {"id":100000807,"name":"AddCRISocketFlag","signature":"func AddCRISocketFlag(flagSet *pflag.FlagSet, criSocket *string)","file":"cmd/kubeadm/app/cmd/util/cmdutil.go","code":"// AddCRISocketFlag adds the cri-socket flag to the supplied flagSet\nfunc AddCRISocketFlag(flagSet *pflag.FlagSet, criSocket *string) {\n\tflagSet.StringVar(\n\t\tcriSocket, options.NodeCRISocket, *criSocket,\n\t\t\"Path to the CRI socket to connect. If empty kubeadm will try to auto-detect this value; use this option only if you have more than one CRI installed or if you have non-standard CRI socket.\",\n\t)\n}","line":{"from":98,"to":104}} {"id":100000808,"name":"DefaultInitConfiguration","signature":"func DefaultInitConfiguration() *kubeadmapiv1.InitConfiguration","file":"cmd/kubeadm/app/cmd/util/cmdutil.go","code":"// DefaultInitConfiguration return default InitConfiguration. Avoid running the CRI auto-detection\n// code as we don't need it.\nfunc DefaultInitConfiguration() *kubeadmapiv1.InitConfiguration {\n\tinitCfg := \u0026kubeadmapiv1.InitConfiguration{\n\t\tNodeRegistration: kubeadmapiv1.NodeRegistrationOptions{\n\t\t\tCRISocket: kubeadmconstants.UnknownCRISocket, // avoid CRI detection\n\t\t},\n\t}\n\treturn initCfg\n}","line":{"from":106,"to":115}} {"id":100000809,"name":"InteractivelyConfirmAction","signature":"func InteractivelyConfirmAction(action, question string, r io.Reader) error","file":"cmd/kubeadm/app/cmd/util/cmdutil.go","code":"// InteractivelyConfirmAction asks the user whether they _really_ want to take the action.\nfunc InteractivelyConfirmAction(action, question string, r io.Reader) error {\n\tfmt.Printf(\"[%s] %s [y/N]: \", action, question)\n\tscanner := bufio.NewScanner(r)\n\tscanner.Scan()\n\tif err := scanner.Err(); err != nil {\n\t\treturn errors.Wrap(err, \"couldn't read from standard input\")\n\t}\n\tanswer := scanner.Text()\n\tif strings.EqualFold(answer, \"y\") || strings.EqualFold(answer, \"yes\") {\n\t\treturn nil\n\t}\n\n\treturn errors.New(\"won't proceed; the user didn't answer (Y|y) in order to continue\")\n}","line":{"from":117,"to":131}} {"id":100000810,"name":"GetClientSet","signature":"func GetClientSet(file string, dryRun bool) (clientset.Interface, error)","file":"cmd/kubeadm/app/cmd/util/cmdutil.go","code":"// GetClientSet gets a real or fake client depending on whether the user is dry-running or not\nfunc GetClientSet(file string, dryRun bool) (clientset.Interface, error) {\n\tif dryRun {\n\t\tdryRunGetter, err := apiclient.NewClientBackedDryRunGetterFromKubeconfig(file)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn apiclient.NewDryRunClient(dryRunGetter, os.Stdout), nil\n\t}\n\treturn kubeconfigutil.ClientSetFromFile(file)\n}","line":{"from":133,"to":143}} {"id":100000811,"name":"LongDesc","signature":"func LongDesc(s string) string","file":"cmd/kubeadm/app/cmd/util/documentation.go","code":"// LongDesc is designed to help with producing better long command line descriptions in code.\n// Its behavior is somewhat inspired by the same function of kubectl, which uses Markdown for the input message.\n// This one is not Markdown compliant, but it covers the needs of kubeadm. In particular:\n// - Beginning and trailing space characters (including empty lines), are stripped from the output.\n// - Consecutive non-empty lines of text are joined with spaces to form paragraphs.\n// - Paragraphs are blocks of text divided by one or more empty lines or lines consisting only of \"space\" characters.\n// - Paragraphs are spaced by precisely one empty line in the output.\n// - A line break can be forced by adding a couple of empty spaces at the end of a text line.\n// - All indentation is removed. The resulting output is not indented.\nfunc LongDesc(s string) string {\n\t// Strip beginning and trailing space characters (including empty lines) and split the lines into a slice\n\tlines := strings.Split(strings.TrimSpace(s), \"\\n\")\n\n\toutput := []string{}\n\tparagraph := []string{}\n\n\tfor _, line := range lines {\n\t\t// Remove indentation and trailing spaces from the current line\n\t\ttrimmedLine := strings.TrimSpace(line)\n\t\tif trimmedLine == \"\" {\n\t\t\tif len(paragraph) \u003e 0 {\n\t\t\t\t// If the line is empty and the current paragraph is not, we have reached a paragraph end.\n\t\t\t\t// (if the paragraph and the line are empty, then this is non-first empty line in between paragraphs and needs to be ignored)\n\t\t\t\t// In that case we join all of the paragraph lines with a single space,\n\t\t\t\t// add a trailing newline character (to ensure an empty line after the paragraph),\n\t\t\t\t// append the paragraph text to the output and clear everything in the current paragraph slice.\n\t\t\t\toutput = append(output, strings.Join(paragraph, \" \")+\"\\n\")\n\t\t\t\tparagraph = []string{}\n\t\t\t}\n\t\t} else {\n\t\t\t// Non-empty text line, append it to the current paragraph\n\t\t\tparagraph = append(paragraph, trimmedLine)\n\t\t\tif strings.HasSuffix(line, \" \") {\n\t\t\t\t// If the original line has a suffix of couple of spaces, then we add a line break.\n\t\t\t\t// This is achieved by flushing out the current paragraph and starting a new one.\n\t\t\t\t// No trailing space is added to the flushed paragraph,\n\t\t\t\t// so that no empty line is placed between the old and the new paragraphs (a simple line break)\n\t\t\t\toutput = append(output, strings.Join(paragraph, \" \"))\n\t\t\t\tparagraph = []string{}\n\t\t\t}\n\t\t}\n\t}\n\n\t// The last paragraph is always unflushed, so flush it.\n\t// We don't add a trailing newline character, so that we won't have to strip the output.\n\toutput = append(output, strings.Join(paragraph, \" \"))\n\n\t// Join all the paragraphs together with new lines in between them.\n\treturn strings.Join(output, \"\\n\")\n}","line":{"from":35,"to":84}} {"id":100000812,"name":"Examples","signature":"func Examples(s string) string","file":"cmd/kubeadm/app/cmd/util/documentation.go","code":"// Examples is designed to help with producing examples for command line usage.\n// Its behavior is mimicking a similar kubectl function in the following ways:\n// - Beginning and trailing space characters (including empty lines), are stripped from the output.\n// - All lines of text are stripped of beginning and trailing spaces (thus loosing indentation) and are then double-space indented.\nfunc Examples(s string) string {\n\ttrimmedText := strings.TrimSpace(s)\n\tif trimmedText == \"\" {\n\t\treturn \"\"\n\t}\n\n\tconst indent = ` `\n\tinLines := strings.Split(trimmedText, \"\\n\")\n\toutLines := make([]string, 0, len(inLines))\n\n\tfor _, line := range inLines {\n\t\toutLines = append(outLines, indent+strings.TrimSpace(line))\n\t}\n\n\treturn strings.Join(outLines, \"\\n\")\n}","line":{"from":86,"to":105}} {"id":100000813,"name":"GetJoinWorkerCommand","signature":"func GetJoinWorkerCommand(kubeConfigFile, token string, skipTokenPrint bool) (string, error)","file":"cmd/kubeadm/app/cmd/util/join.go","code":"// GetJoinWorkerCommand returns the kubeadm join command for a given token and\n// Kubernetes cluster (the current cluster in the kubeconfig file)\nfunc GetJoinWorkerCommand(kubeConfigFile, token string, skipTokenPrint bool) (string, error) {\n\treturn getJoinCommand(kubeConfigFile, token, \"\", false, skipTokenPrint, false)\n}","line":{"from":40,"to":44}} {"id":100000814,"name":"GetJoinControlPlaneCommand","signature":"func GetJoinControlPlaneCommand(kubeConfigFile, token, key string, skipTokenPrint, skipCertificateKeyPrint bool) (string, error)","file":"cmd/kubeadm/app/cmd/util/join.go","code":"// GetJoinControlPlaneCommand returns the kubeadm join command for a given token and\n// Kubernetes cluster (the current cluster in the kubeconfig file)\nfunc GetJoinControlPlaneCommand(kubeConfigFile, token, key string, skipTokenPrint, skipCertificateKeyPrint bool) (string, error) {\n\treturn getJoinCommand(kubeConfigFile, token, key, true, skipTokenPrint, skipCertificateKeyPrint)\n}","line":{"from":46,"to":50}} {"id":100000815,"name":"getJoinCommand","signature":"func getJoinCommand(kubeConfigFile, token, key string, controlPlane, skipTokenPrint, skipCertificateKeyPrint bool) (string, error)","file":"cmd/kubeadm/app/cmd/util/join.go","code":"func getJoinCommand(kubeConfigFile, token, key string, controlPlane, skipTokenPrint, skipCertificateKeyPrint bool) (string, error) {\n\t// load the kubeconfig file to get the CA certificate and endpoint\n\tconfig, err := clientcmd.LoadFromFile(kubeConfigFile)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to load kubeconfig\")\n\t}\n\n\t// load the default cluster config\n\t_, clusterConfig := kubeconfigutil.GetClusterFromKubeConfig(config)\n\tif clusterConfig == nil {\n\t\treturn \"\", errors.New(\"failed to get default cluster config\")\n\t}\n\n\t// load CA certificates from the kubeconfig (either from PEM data or by file path)\n\tvar caCerts []*x509.Certificate\n\tif clusterConfig.CertificateAuthorityData != nil {\n\t\tcaCerts, err = clientcertutil.ParseCertsPEM(clusterConfig.CertificateAuthorityData)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"failed to parse CA certificate from kubeconfig\")\n\t\t}\n\t} else if clusterConfig.CertificateAuthority != \"\" {\n\t\tcaCerts, err = clientcertutil.CertsFromFile(clusterConfig.CertificateAuthority)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"failed to load CA certificate referenced by kubeconfig\")\n\t\t}\n\t} else {\n\t\treturn \"\", errors.New(\"no CA certificates found in kubeconfig\")\n\t}\n\n\t// hash all the CA certs and include their public key pins as trusted values\n\tpublicKeyPins := make([]string, 0, len(caCerts))\n\tfor _, caCert := range caCerts {\n\t\tpublicKeyPins = append(publicKeyPins, pubkeypin.Hash(caCert))\n\t}\n\n\tctx := map[string]interface{}{\n\t\t\"Token\": token,\n\t\t\"CAPubKeyPins\": publicKeyPins,\n\t\t\"ControlPlaneHostPort\": strings.Replace(clusterConfig.Server, \"https://\", \"\", -1),\n\t\t\"CertificateKey\": key,\n\t\t\"ControlPlane\": controlPlane,\n\t}\n\n\tif skipTokenPrint {\n\t\tctx[\"Token\"] = template.HTML(\"\u003cvalue withheld\u003e\")\n\t}\n\tif skipCertificateKeyPrint {\n\t\tctx[\"CertificateKey\"] = template.HTML(\"\u003cvalue withheld\u003e\")\n\t}\n\n\tvar out bytes.Buffer\n\terr = joinCommandTemplate.Execute(\u0026out, ctx)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to render join command template\")\n\t}\n\treturn out.String(), nil\n}","line":{"from":52,"to":108}} {"id":100000816,"name":"newCmdVersion","signature":"func newCmdVersion(out io.Writer) *cobra.Command","file":"cmd/kubeadm/app/cmd/version.go","code":"// newCmdVersion provides the version information of kubeadm.\nfunc newCmdVersion(out io.Writer) *cobra.Command {\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"version\",\n\t\tShort: \"Print the version of kubeadm\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn RunVersion(out, cmd)\n\t\t},\n\t\tArgs: cobra.NoArgs,\n\t}\n\tcmd.Flags().StringP(\"output\", \"o\", \"\", \"Output format; available options are 'yaml', 'json' and 'short'\")\n\treturn cmd\n}","line":{"from":38,"to":50}} {"id":100000817,"name":"RunVersion","signature":"func RunVersion(out io.Writer, cmd *cobra.Command) error","file":"cmd/kubeadm/app/cmd/version.go","code":"// RunVersion provides the version information of kubeadm in format depending on arguments\n// specified in cobra.Command.\nfunc RunVersion(out io.Writer, cmd *cobra.Command) error {\n\tklog.V(1).Infoln(\"[version] retrieving version info\")\n\tclientVersion := version.Get()\n\tv := Version{\n\t\tClientVersion: \u0026clientVersion,\n\t}\n\n\tconst flag = \"output\"\n\tof, err := cmd.Flags().GetString(flag)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"error accessing flag %s for command %s\", flag, cmd.Name())\n\t}\n\n\tswitch of {\n\tcase \"\":\n\t\tfmt.Fprintf(out, \"kubeadm version: %#v\\n\", v.ClientVersion)\n\tcase \"short\":\n\t\tfmt.Fprintf(out, \"%s\\n\", v.ClientVersion.GitVersion)\n\tcase \"yaml\":\n\t\ty, err := yaml.Marshal(\u0026v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Fprintln(out, string(y))\n\tcase \"json\":\n\t\ty, err := json.MarshalIndent(\u0026v, \"\", \" \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Fprintln(out, string(y))\n\tdefault:\n\t\treturn errors.Errorf(\"invalid output format: %s\", of)\n\t}\n\n\treturn nil\n}","line":{"from":52,"to":89}} {"id":100000818,"name":"ChecksumForConfigMap","signature":"func ChecksumForConfigMap(cm *v1.ConfigMap) string","file":"cmd/kubeadm/app/componentconfigs/checksums.go","code":"// ChecksumForConfigMap calculates a checksum for the supplied config map. The exact algorithm depends on hash and prefix parameters\nfunc ChecksumForConfigMap(cm *v1.ConfigMap) string {\n\thash := sha256.New()\n\n\t// Since maps are not ordered we need to make sure we order them somehow so we'll always get the same checksums\n\t// for the same config maps. The solution here is to extract the keys into a slice and sort them.\n\t// Then iterate over that slice to fetch the values to be hashed.\n\tkeys := []string{}\n\tfor key := range cm.Data {\n\t\tkeys = append(keys, key)\n\t}\n\tsort.Strings(keys)\n\n\tfor _, key := range keys {\n\t\thash.Write([]byte(cm.Data[key]))\n\t}\n\n\t// Do the same as above, but for binaryData this time.\n\tkeys = []string{}\n\tfor key := range cm.BinaryData {\n\t\tkeys = append(keys, key)\n\t}\n\tsort.Strings(keys)\n\n\tfor _, key := range keys {\n\t\thash.Write(cm.BinaryData[key])\n\t}\n\n\treturn fmt.Sprintf(\"sha256:%x\", hash.Sum(nil))\n}","line":{"from":29,"to":58}} {"id":100000819,"name":"SignConfigMap","signature":"func SignConfigMap(cm *v1.ConfigMap)","file":"cmd/kubeadm/app/componentconfigs/checksums.go","code":"// SignConfigMap calculates the supplied config map checksum and annotates it with it\nfunc SignConfigMap(cm *v1.ConfigMap) {\n\tif cm.Annotations == nil {\n\t\tcm.Annotations = map[string]string{}\n\t}\n\tcm.Annotations[constants.ComponentConfigHashAnnotationKey] = ChecksumForConfigMap(cm)\n}","line":{"from":60,"to":66}} {"id":100000820,"name":"VerifyConfigMapSignature","signature":"func VerifyConfigMapSignature(cm *v1.ConfigMap) bool","file":"cmd/kubeadm/app/componentconfigs/checksums.go","code":"// VerifyConfigMapSignature returns true if the config map has checksum annotation and it matches; false otherwise\nfunc VerifyConfigMapSignature(cm *v1.ConfigMap) bool {\n\tsignature, ok := cm.Annotations[constants.ComponentConfigHashAnnotationKey]\n\tif !ok {\n\t\treturn false\n\t}\n\treturn signature == ChecksumForConfigMap(cm)\n}","line":{"from":68,"to":75}} {"id":100000821,"name":"FromDocumentMap","signature":"func (h *handler) FromDocumentMap(docmap kubeadmapi.DocumentMap) (kubeadmapi.ComponentConfig, error)","file":"cmd/kubeadm/app/componentconfigs/configset.go","code":"// FromDocumentMap looks in the document map for documents with this handler's group.\n// If such are found a new component config is instantiated and the documents are loaded into it.\n// No error is returned if no documents are found.\nfunc (h *handler) FromDocumentMap(docmap kubeadmapi.DocumentMap) (kubeadmapi.ComponentConfig, error) {\n\tfor gvk := range docmap {\n\t\tif gvk.Group == h.GroupVersion.Group {\n\t\t\tcfg := h.CreateEmpty()\n\t\t\tif err := cfg.Unmarshal(docmap); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\t// consider all successfully loaded configs from a document map as user supplied\n\t\t\tcfg.SetUserSupplied(true)\n\t\t\treturn cfg, nil\n\t\t}\n\t}\n\treturn nil, nil\n}","line":{"from":54,"to":70}} {"id":100000822,"name":"fromConfigMap","signature":"func (h *handler) fromConfigMap(client clientset.Interface, cmName, cmKey string, mustExist bool) (kubeadmapi.ComponentConfig, error)","file":"cmd/kubeadm/app/componentconfigs/configset.go","code":"// fromConfigMap is an utility function, which will load the value of a key of a config map and use h.FromDocumentMap() to perform the parsing\n// This is an utility func. Used by the component config support implementations. Don't use it outside of that context.\nfunc (h *handler) fromConfigMap(client clientset.Interface, cmName, cmKey string, mustExist bool) (kubeadmapi.ComponentConfig, error) {\n\tconfigMap, err := apiclient.GetConfigMapWithRetry(client, metav1.NamespaceSystem, cmName)\n\tif err != nil {\n\t\tif !mustExist \u0026\u0026 (apierrors.IsNotFound(err) || apierrors.IsForbidden(err)) {\n\t\t\tklog.Warningf(\"Warning: No %s config is loaded. Continuing without it: %v\", h.GroupVersion, err)\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tconfigData, ok := configMap.Data[cmKey]\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"unexpected error when reading %s ConfigMap: %s key value pair missing\", cmName, cmKey)\n\t}\n\n\tgvkmap, err := kubeadmutil.SplitYAMLDocuments([]byte(configData))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// If the checksum comes up neatly we assume the config was generated\n\tgeneratedConfig := VerifyConfigMapSignature(configMap)\n\n\tcomponentCfg, err := h.FromDocumentMap(gvkmap)\n\tif err != nil {\n\t\t// If the config was generated and we get UnsupportedConfigVersionError, we skip loading it.\n\t\t// This will force us to use the generated default current version (effectively regenerating the config with the current version).\n\t\tif _, ok := err.(*UnsupportedConfigVersionError); ok \u0026\u0026 generatedConfig {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tif componentCfg != nil {\n\t\tcomponentCfg.SetUserSupplied(!generatedConfig)\n\t}\n\n\treturn componentCfg, nil\n}","line":{"from":72,"to":112}} {"id":100000823,"name":"FromCluster","signature":"func (h *handler) FromCluster(clientset clientset.Interface, clusterCfg *kubeadmapi.ClusterConfiguration) (kubeadmapi.ComponentConfig, error)","file":"cmd/kubeadm/app/componentconfigs/configset.go","code":"// FromCluster loads a component from a config map in the cluster\nfunc (h *handler) FromCluster(clientset clientset.Interface, clusterCfg *kubeadmapi.ClusterConfiguration) (kubeadmapi.ComponentConfig, error) {\n\treturn h.fromCluster(h, clientset, clusterCfg)\n}","line":{"from":114,"to":117}} {"id":100000824,"name":"IsUserSupplied","signature":"func (cb *configBase) IsUserSupplied() bool","file":"cmd/kubeadm/app/componentconfigs/configset.go","code":"func (cb *configBase) IsUserSupplied() bool {\n\treturn cb.userSupplied\n}","line":{"from":134,"to":136}} {"id":100000825,"name":"SetUserSupplied","signature":"func (cb *configBase) SetUserSupplied(userSupplied bool)","file":"cmd/kubeadm/app/componentconfigs/configset.go","code":"func (cb *configBase) SetUserSupplied(userSupplied bool) {\n\tcb.userSupplied = userSupplied\n}","line":{"from":138,"to":140}} {"id":100000826,"name":"DeepCopyInto","signature":"func (cb *configBase) DeepCopyInto(other *configBase)","file":"cmd/kubeadm/app/componentconfigs/configset.go","code":"func (cb *configBase) DeepCopyInto(other *configBase) {\n\t*other = *cb\n}","line":{"from":142,"to":144}} {"id":100000827,"name":"cloneBytes","signature":"func cloneBytes(in []byte) []byte","file":"cmd/kubeadm/app/componentconfigs/configset.go","code":"func cloneBytes(in []byte) []byte {\n\tout := make([]byte, len(in))\n\tcopy(out, in)\n\treturn out\n}","line":{"from":146,"to":150}} {"id":100000828,"name":"Marshal","signature":"func (cb *configBase) Marshal(object runtime.Object) ([]byte, error)","file":"cmd/kubeadm/app/componentconfigs/configset.go","code":"// Marshal is an utility function, used by the component config support implementations to marshal a runtime.Object to YAML with the\n// correct group and version\nfunc (cb *configBase) Marshal(object runtime.Object) ([]byte, error) {\n\treturn kubeadmutil.MarshalToYamlForCodecs(object, cb.GroupVersion, Codecs)\n}","line":{"from":152,"to":156}} {"id":100000829,"name":"Unmarshal","signature":"func (cb *configBase) Unmarshal(from kubeadmapi.DocumentMap, into runtime.Object) error","file":"cmd/kubeadm/app/componentconfigs/configset.go","code":"// Unmarshal attempts to unmarshal a runtime.Object from a document map. If no object is found, no error is returned.\n// If a matching group is found, but no matching version an error is returned indicating that users should do manual conversion.\nfunc (cb *configBase) Unmarshal(from kubeadmapi.DocumentMap, into runtime.Object) error {\n\tfor gvk, yaml := range from {\n\t\t// If this is a different group, we ignore it\n\t\tif gvk.Group != cb.GroupVersion.Group {\n\t\t\tcontinue\n\t\t}\n\n\t\tif gvk.Version != cb.GroupVersion.Version {\n\t\t\treturn \u0026UnsupportedConfigVersionError{\n\t\t\t\tOldVersion: gvk.GroupVersion(),\n\t\t\t\tCurrentVersion: cb.GroupVersion,\n\t\t\t\tDocument: cloneBytes(yaml),\n\t\t\t}\n\t\t}\n\n\t\t// Print warnings for strict errors\n\t\tif err := strict.VerifyUnmarshalStrict([]*runtime.Scheme{Scheme}, gvk, yaml); err != nil {\n\t\t\tklog.Warning(err.Error())\n\t\t}\n\n\t\t// As long as we support only component configs with a single kind, this is allowed\n\t\treturn runtime.DecodeInto(Codecs.UniversalDecoder(), yaml, into)\n\t}\n\n\treturn nil\n}","line":{"from":158,"to":185}} {"id":100000830,"name":"ensureInitializedComponentConfigs","signature":"func ensureInitializedComponentConfigs(clusterCfg *kubeadmapi.ClusterConfiguration)","file":"cmd/kubeadm/app/componentconfigs/configset.go","code":"// ensureInitializedComponentConfigs is an utility func to initialize the ComponentConfigMap in ClusterConfiguration prior to possible writes to it\nfunc ensureInitializedComponentConfigs(clusterCfg *kubeadmapi.ClusterConfiguration) {\n\tif clusterCfg.ComponentConfigs == nil {\n\t\tclusterCfg.ComponentConfigs = kubeadmapi.ComponentConfigMap{}\n\t}\n}","line":{"from":187,"to":192}} {"id":100000831,"name":"Default","signature":"func Default(clusterCfg *kubeadmapi.ClusterConfiguration, localAPIEndpoint *kubeadmapi.APIEndpoint, nodeRegOpts *kubeadmapi.NodeRegistrationOptions)","file":"cmd/kubeadm/app/componentconfigs/configset.go","code":"// Default sets up defaulted component configs in the supplied ClusterConfiguration\nfunc Default(clusterCfg *kubeadmapi.ClusterConfiguration, localAPIEndpoint *kubeadmapi.APIEndpoint, nodeRegOpts *kubeadmapi.NodeRegistrationOptions) {\n\tensureInitializedComponentConfigs(clusterCfg)\n\n\tfor _, handler := range known {\n\t\t// If the component config exists, simply default it. Otherwise, create it before defaulting.\n\t\tgroup := handler.GroupVersion.Group\n\t\tif componentCfg, ok := clusterCfg.ComponentConfigs[group]; ok {\n\t\t\tcomponentCfg.Default(clusterCfg, localAPIEndpoint, nodeRegOpts)\n\t\t} else {\n\t\t\tcomponentCfg := handler.CreateEmpty()\n\t\t\tcomponentCfg.Default(clusterCfg, localAPIEndpoint, nodeRegOpts)\n\t\t\tclusterCfg.ComponentConfigs[group] = componentCfg\n\t\t}\n\t}\n}","line":{"from":194,"to":209}} {"id":100000832,"name":"FetchFromCluster","signature":"func FetchFromCluster(clusterCfg *kubeadmapi.ClusterConfiguration, client clientset.Interface) error","file":"cmd/kubeadm/app/componentconfigs/configset.go","code":"// FetchFromCluster attempts to fetch all known component configs from their config maps and store them in the supplied ClusterConfiguration\nfunc FetchFromCluster(clusterCfg *kubeadmapi.ClusterConfiguration, client clientset.Interface) error {\n\tensureInitializedComponentConfigs(clusterCfg)\n\n\tfor _, handler := range known {\n\t\tcomponentCfg, err := handler.FromCluster(client, clusterCfg)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif componentCfg != nil {\n\t\t\tclusterCfg.ComponentConfigs[handler.GroupVersion.Group] = componentCfg\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":211,"to":227}} {"id":100000833,"name":"FetchFromDocumentMap","signature":"func FetchFromDocumentMap(clusterCfg *kubeadmapi.ClusterConfiguration, docmap kubeadmapi.DocumentMap) error","file":"cmd/kubeadm/app/componentconfigs/configset.go","code":"// FetchFromDocumentMap attempts to load all known component configs from a document map into the supplied ClusterConfiguration\nfunc FetchFromDocumentMap(clusterCfg *kubeadmapi.ClusterConfiguration, docmap kubeadmapi.DocumentMap) error {\n\tensureInitializedComponentConfigs(clusterCfg)\n\n\tfor _, handler := range known {\n\t\tcomponentCfg, err := handler.FromDocumentMap(docmap)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif componentCfg != nil {\n\t\t\tclusterCfg.ComponentConfigs[handler.GroupVersion.Group] = componentCfg\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":229,"to":245}} {"id":100000834,"name":"FetchFromClusterWithLocalOverwrites","signature":"func FetchFromClusterWithLocalOverwrites(clusterCfg *kubeadmapi.ClusterConfiguration, client clientset.Interface, docmap kubeadmapi.DocumentMap) error","file":"cmd/kubeadm/app/componentconfigs/configset.go","code":"// FetchFromClusterWithLocalOverwrites fetches component configs from a cluster and overwrites them locally with\n// the ones present in the supplied document map. If any UnsupportedConfigVersionError are not handled by the configs\n// in the document map, the function returns them all as a single UnsupportedConfigVersionsErrorMap.\n// This function is normally called only in some specific cases during upgrade.\nfunc FetchFromClusterWithLocalOverwrites(clusterCfg *kubeadmapi.ClusterConfiguration, client clientset.Interface, docmap kubeadmapi.DocumentMap) error {\n\tensureInitializedComponentConfigs(clusterCfg)\n\n\toldVersionErrs := UnsupportedConfigVersionsErrorMap{}\n\n\tfor _, handler := range known {\n\t\tcomponentCfg, err := handler.FromCluster(client, clusterCfg)\n\t\tif err != nil {\n\t\t\tif vererr, ok := err.(*UnsupportedConfigVersionError); ok {\n\t\t\t\toldVersionErrs[handler.GroupVersion.Group] = vererr\n\t\t\t} else {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else if componentCfg != nil {\n\t\t\tclusterCfg.ComponentConfigs[handler.GroupVersion.Group] = componentCfg\n\t\t}\n\t}\n\n\tfor _, handler := range known {\n\t\tcomponentCfg, err := handler.FromDocumentMap(docmap)\n\t\tif err != nil {\n\t\t\tif vererr, ok := err.(*UnsupportedConfigVersionError); ok {\n\t\t\t\toldVersionErrs[handler.GroupVersion.Group] = vererr\n\t\t\t} else {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else if componentCfg != nil {\n\t\t\tclusterCfg.ComponentConfigs[handler.GroupVersion.Group] = componentCfg\n\t\t\tdelete(oldVersionErrs, handler.GroupVersion.Group)\n\t\t}\n\t}\n\n\tif len(oldVersionErrs) != 0 {\n\t\treturn oldVersionErrs\n\t}\n\n\treturn nil\n}","line":{"from":247,"to":288}} {"id":100000835,"name":"GetVersionStates","signature":"func GetVersionStates(clusterCfg *kubeadmapi.ClusterConfiguration, client clientset.Interface, docmap kubeadmapi.DocumentMap) ([]outputapiv1alpha2.ComponentConfigVersionState, error)","file":"cmd/kubeadm/app/componentconfigs/configset.go","code":"// GetVersionStates returns a slice of ComponentConfigVersionState structs\n// describing all supported component config groups that were identified on the cluster\nfunc GetVersionStates(clusterCfg *kubeadmapi.ClusterConfiguration, client clientset.Interface, docmap kubeadmapi.DocumentMap) ([]outputapiv1alpha2.ComponentConfigVersionState, error) {\n\t// We don't want to modify clusterCfg so we make a working deep copy of it.\n\t// Also, we don't want the defaulted component configs so we get rid of them.\n\tscratchClusterCfg := clusterCfg.DeepCopy()\n\tscratchClusterCfg.ComponentConfigs = kubeadmapi.ComponentConfigMap{}\n\n\t// Call FetchFromClusterWithLocalOverwrites. This will populate the configs it can load and will return all\n\t// UnsupportedConfigVersionError(s) in a sinle instance of a MultipleUnsupportedConfigVersionsError.\n\tvar multipleVerErrs UnsupportedConfigVersionsErrorMap\n\terr := FetchFromClusterWithLocalOverwrites(scratchClusterCfg, client, docmap)\n\tif err != nil {\n\t\tif vererrs, ok := err.(UnsupportedConfigVersionsErrorMap); ok {\n\t\t\tmultipleVerErrs = vererrs\n\t\t} else {\n\t\t\t// This seems to be a genuine error so we end here\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tresults := []outputapiv1alpha2.ComponentConfigVersionState{}\n\tfor _, handler := range known {\n\t\tgroup := handler.GroupVersion.Group\n\t\tif vererr, ok := multipleVerErrs[group]; ok {\n\t\t\t// If there is an UnsupportedConfigVersionError then we are dealing with a case where the config was user\n\t\t\t// supplied and requires manual upgrade\n\t\t\tresults = append(results, outputapiv1alpha2.ComponentConfigVersionState{\n\t\t\t\tGroup: group,\n\t\t\t\tCurrentVersion: vererr.OldVersion.Version,\n\t\t\t\tPreferredVersion: vererr.CurrentVersion.Version,\n\t\t\t\tManualUpgradeRequired: true,\n\t\t\t})\n\t\t} else if _, ok := scratchClusterCfg.ComponentConfigs[group]; ok {\n\t\t\t// Normally loaded component config. No manual upgrade required on behalf of users.\n\t\t\tresults = append(results, outputapiv1alpha2.ComponentConfigVersionState{\n\t\t\t\tGroup: group,\n\t\t\t\tCurrentVersion: handler.GroupVersion.Version, // Currently kubeadm supports only one version per API\n\t\t\t\tPreferredVersion: handler.GroupVersion.Version, // group so we can get away with these being the same\n\t\t\t})\n\t\t} else {\n\t\t\t// This config was either not present (user did not install an addon) or the config was unsupported kubeadm\n\t\t\t// generated one and is therefore skipped so we can automatically re-generate it (no action required on\n\t\t\t// behalf of the user).\n\t\t\tresults = append(results, outputapiv1alpha2.ComponentConfigVersionState{\n\t\t\t\tGroup: group,\n\t\t\t\tPreferredVersion: handler.GroupVersion.Version,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn results, nil\n}","line":{"from":290,"to":342}} {"id":100000836,"name":"Validate","signature":"func Validate(clusterCfg *kubeadmapi.ClusterConfiguration) field.ErrorList","file":"cmd/kubeadm/app/componentconfigs/configset.go","code":"// Validate is a placeholder for performing a validation on an already loaded component configs in a ClusterConfiguration\n// TODO: investigate if the function can be repurposed for validating component config via CLI\nfunc Validate(clusterCfg *kubeadmapi.ClusterConfiguration) field.ErrorList {\n\treturn field.ErrorList{}\n}","line":{"from":344,"to":348}} {"id":100000837,"name":"kubeletConfigFromCluster","signature":"func kubeletConfigFromCluster(h *handler, clientset clientset.Interface, clusterCfg *kubeadmapi.ClusterConfiguration) (kubeadmapi.ComponentConfig, error)","file":"cmd/kubeadm/app/componentconfigs/kubelet.go","code":"func kubeletConfigFromCluster(h *handler, clientset clientset.Interface, clusterCfg *kubeadmapi.ClusterConfiguration) (kubeadmapi.ComponentConfig, error) {\n\tconfigMapName := constants.KubeletBaseConfigurationConfigMap\n\tklog.V(1).Infof(\"attempting to download the KubeletConfiguration from ConfigMap %q\", configMapName)\n\tcm, err := h.fromConfigMap(clientset, configMapName, constants.KubeletBaseConfigurationConfigMapKey, true)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"could not download the kubelet configuration from ConfigMap %q\",\n\t\t\tconfigMapName)\n\t}\n\treturn cm, nil\n}","line":{"from":72,"to":81}} {"id":100000838,"name":"DeepCopy","signature":"func (kc *kubeletConfig) DeepCopy() kubeadmapi.ComponentConfig","file":"cmd/kubeadm/app/componentconfigs/kubelet.go","code":"func (kc *kubeletConfig) DeepCopy() kubeadmapi.ComponentConfig {\n\tresult := \u0026kubeletConfig{}\n\tkc.configBase.DeepCopyInto(\u0026result.configBase)\n\tkc.config.DeepCopyInto(\u0026result.config)\n\treturn result\n}","line":{"from":89,"to":94}} {"id":100000839,"name":"Marshal","signature":"func (kc *kubeletConfig) Marshal() ([]byte, error)","file":"cmd/kubeadm/app/componentconfigs/kubelet.go","code":"func (kc *kubeletConfig) Marshal() ([]byte, error) {\n\treturn kc.configBase.Marshal(\u0026kc.config)\n}","line":{"from":96,"to":98}} {"id":100000840,"name":"Unmarshal","signature":"func (kc *kubeletConfig) Unmarshal(docmap kubeadmapi.DocumentMap) error","file":"cmd/kubeadm/app/componentconfigs/kubelet.go","code":"func (kc *kubeletConfig) Unmarshal(docmap kubeadmapi.DocumentMap) error {\n\treturn kc.configBase.Unmarshal(docmap, \u0026kc.config)\n}","line":{"from":100,"to":102}} {"id":100000841,"name":"Get","signature":"func (kc *kubeletConfig) Get() interface{}","file":"cmd/kubeadm/app/componentconfigs/kubelet.go","code":"func (kc *kubeletConfig) Get() interface{} {\n\treturn \u0026kc.config\n}","line":{"from":104,"to":106}} {"id":100000842,"name":"Set","signature":"func (kc *kubeletConfig) Set(cfg interface{})","file":"cmd/kubeadm/app/componentconfigs/kubelet.go","code":"func (kc *kubeletConfig) Set(cfg interface{}) {\n\tkc.config = *cfg.(*kubeletconfig.KubeletConfiguration)\n}","line":{"from":108,"to":110}} {"id":100000843,"name":"Default","signature":"func (kc *kubeletConfig) Default(cfg *kubeadmapi.ClusterConfiguration, _ *kubeadmapi.APIEndpoint, nodeRegOpts *kubeadmapi.NodeRegistrationOptions)","file":"cmd/kubeadm/app/componentconfigs/kubelet.go","code":"func (kc *kubeletConfig) Default(cfg *kubeadmapi.ClusterConfiguration, _ *kubeadmapi.APIEndpoint, nodeRegOpts *kubeadmapi.NodeRegistrationOptions) {\n\tconst kind = \"KubeletConfiguration\"\n\n\tif kc.config.FeatureGates == nil {\n\t\tkc.config.FeatureGates = map[string]bool{}\n\t}\n\n\tif kc.config.StaticPodPath == \"\" {\n\t\tkc.config.StaticPodPath = kubeadmapiv1.DefaultManifestsDir\n\t} else if kc.config.StaticPodPath != kubeadmapiv1.DefaultManifestsDir {\n\t\twarnDefaultComponentConfigValue(kind, \"staticPodPath\", kubeadmapiv1.DefaultManifestsDir, kc.config.StaticPodPath)\n\t}\n\n\tclusterDNS := \"\"\n\tdnsIP, err := constants.GetDNSIP(cfg.Networking.ServiceSubnet)\n\tif err != nil {\n\t\tclusterDNS = kubeadmapiv1.DefaultClusterDNSIP\n\t} else {\n\t\tclusterDNS = dnsIP.String()\n\t}\n\n\tif kc.config.ClusterDNS == nil {\n\t\tkc.config.ClusterDNS = []string{clusterDNS}\n\t} else if len(kc.config.ClusterDNS) != 1 || kc.config.ClusterDNS[0] != clusterDNS {\n\t\twarnDefaultComponentConfigValue(kind, \"clusterDNS\", []string{clusterDNS}, kc.config.ClusterDNS)\n\t}\n\n\tif kc.config.ClusterDomain == \"\" {\n\t\tkc.config.ClusterDomain = cfg.Networking.DNSDomain\n\t} else if cfg.Networking.DNSDomain != \"\" \u0026\u0026 kc.config.ClusterDomain != cfg.Networking.DNSDomain {\n\t\twarnDefaultComponentConfigValue(kind, \"clusterDomain\", cfg.Networking.DNSDomain, kc.config.ClusterDomain)\n\t}\n\n\t// Require all clients to the kubelet API to have client certs signed by the cluster CA\n\tclientCAFile := filepath.Join(cfg.CertificatesDir, constants.CACertName)\n\tif kc.config.Authentication.X509.ClientCAFile == \"\" {\n\t\tkc.config.Authentication.X509.ClientCAFile = clientCAFile\n\t} else if kc.config.Authentication.X509.ClientCAFile != clientCAFile {\n\t\twarnDefaultComponentConfigValue(kind, \"authentication.x509.clientCAFile\", clientCAFile, kc.config.Authentication.X509.ClientCAFile)\n\t}\n\n\tif kc.config.Authentication.Anonymous.Enabled == nil {\n\t\tkc.config.Authentication.Anonymous.Enabled = pointer.Bool(kubeletAuthenticationAnonymousEnabled)\n\t} else if *kc.config.Authentication.Anonymous.Enabled {\n\t\twarnDefaultComponentConfigValue(kind, \"authentication.anonymous.enabled\", kubeletAuthenticationAnonymousEnabled, *kc.config.Authentication.Anonymous.Enabled)\n\t}\n\n\t// On every client request to the kubelet API, execute a webhook (SubjectAccessReview request) to the API server\n\t// and ask it whether the client is authorized to access the kubelet API\n\tif kc.config.Authorization.Mode == \"\" {\n\t\tkc.config.Authorization.Mode = kubeletconfig.KubeletAuthorizationModeWebhook\n\t} else if kc.config.Authorization.Mode != kubeletconfig.KubeletAuthorizationModeWebhook {\n\t\twarnDefaultComponentConfigValue(kind, \"authorization.mode\", kubeletconfig.KubeletAuthorizationModeWebhook, kc.config.Authorization.Mode)\n\t}\n\n\t// Let clients using other authentication methods like ServiceAccount tokens also access the kubelet API\n\tif kc.config.Authentication.Webhook.Enabled == nil {\n\t\tkc.config.Authentication.Webhook.Enabled = pointer.Bool(kubeletAuthenticationWebhookEnabled)\n\t} else if !*kc.config.Authentication.Webhook.Enabled {\n\t\twarnDefaultComponentConfigValue(kind, \"authentication.webhook.enabled\", kubeletAuthenticationWebhookEnabled, *kc.config.Authentication.Webhook.Enabled)\n\t}\n\n\t// Serve a /healthz webserver on localhost:10248 that kubeadm can talk to\n\tif kc.config.HealthzBindAddress == \"\" {\n\t\tkc.config.HealthzBindAddress = kubeletHealthzBindAddress\n\t} else if kc.config.HealthzBindAddress != kubeletHealthzBindAddress {\n\t\twarnDefaultComponentConfigValue(kind, \"healthzBindAddress\", kubeletHealthzBindAddress, kc.config.HealthzBindAddress)\n\t}\n\n\tif kc.config.HealthzPort == nil {\n\t\tkc.config.HealthzPort = pointer.Int32(constants.KubeletHealthzPort)\n\t} else if *kc.config.HealthzPort != constants.KubeletHealthzPort {\n\t\twarnDefaultComponentConfigValue(kind, \"healthzPort\", constants.KubeletHealthzPort, *kc.config.HealthzPort)\n\t}\n\n\tif kc.config.ReadOnlyPort != kubeletReadOnlyPort {\n\t\twarnDefaultComponentConfigValue(kind, \"readOnlyPort\", kubeletReadOnlyPort, kc.config.ReadOnlyPort)\n\t}\n\n\t// We cannot show a warning for RotateCertificates==false and we must hardcode it to true.\n\t// There is no way to determine if the user has set this or not, given the field is a non-pointer.\n\tkc.config.RotateCertificates = kubeletRotateCertificates\n\n\tif len(kc.config.CgroupDriver) == 0 {\n\t\tklog.V(1).Infof(\"the value of KubeletConfiguration.cgroupDriver is empty; setting it to %q\", constants.CgroupDriverSystemd)\n\t\tkc.config.CgroupDriver = constants.CgroupDriverSystemd\n\t}\n\n\tok, err := isServiceActive(\"systemd-resolved\")\n\tif err != nil {\n\t\tklog.Warningf(\"cannot determine if systemd-resolved is active: %v\", err)\n\t}\n\tif ok {\n\t\tif kc.config.ResolverConfig == nil {\n\t\t\tkc.config.ResolverConfig = pointer.String(kubeletSystemdResolverConfig)\n\t\t} else {\n\t\t\tif *kc.config.ResolverConfig != kubeletSystemdResolverConfig {\n\t\t\t\twarnDefaultComponentConfigValue(kind, \"resolvConf\", kubeletSystemdResolverConfig, *kc.config.ResolverConfig)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":112,"to":213}} {"id":100000844,"name":"isServiceActive","signature":"func isServiceActive(name string) (bool, error)","file":"cmd/kubeadm/app/componentconfigs/kubelet.go","code":"// isServiceActive checks whether the given service exists and is running\nfunc isServiceActive(name string) (bool, error) {\n\tinitSystem, err := initsystem.GetInitSystem()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn initSystem.ServiceIsActive(name), nil\n}","line":{"from":215,"to":222}} {"id":100000845,"name":"Mutate","signature":"func (kc *kubeletConfig) Mutate() error","file":"cmd/kubeadm/app/componentconfigs/kubelet_unix.go","code":"// Mutate allows applying pre-defined modifications to the config before it's marshaled.\nfunc (kc *kubeletConfig) Mutate() error {\n\treturn nil\n}","line":{"from":22,"to":25}} {"id":100000846,"name":"Mutate","signature":"func (kc *kubeletConfig) Mutate() error","file":"cmd/kubeadm/app/componentconfigs/kubelet_windows.go","code":"// Mutate modifies absolute path fields in the KubeletConfiguration to be Windows compatible absolute paths.\nfunc (kc *kubeletConfig) Mutate() error {\n\t// When \"kubeadm join\" downloads the KubeletConfiguration from the cluster on Windows\n\t// nodes, it would contain absolute paths that may lack drive letters, since the config\n\t// could have been generated on a Linux control-plane node. On Windows the\n\t// Golang path.IsAbs() function returns false unless the path contains a drive letter.\n\t// This trips client-go and the kubelet, creating problems on Windows nodes.\n\t// Fixing it in client-go or the kubelet is a breaking change to existing Windows\n\t// users that rely on relative paths:\n\t// https://github.com/kubernetes/kubernetes/pull/77710#issuecomment-491989621\n\t//\n\t// Thus, a workaround here is to adapt the KubeletConfiguration paths for Windows.\n\t// Note this is currently bound to KubeletConfiguration v1beta1.\n\tklog.V(2).Infoln(\"[componentconfig] Adapting the paths in the KubeletConfiguration for Windows...\")\n\n\t// Get the drive from where the kubeadm binary was called.\n\texe, err := os.Executable()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"could not obtain information about the kubeadm executable\")\n\t}\n\tdrive := filepath.VolumeName(filepath.Dir(exe))\n\tklog.V(2).Infof(\"[componentconfig] Assuming Windows drive %q\", drive)\n\n\t// Mutate the paths in the config.\n\tmutatePaths(\u0026kc.config, drive)\n\treturn nil\n}","line":{"from":30,"to":56}} {"id":100000847,"name":"mutatePaths","signature":"func mutatePaths(cfg *kubeletconfig.KubeletConfiguration, drive string)","file":"cmd/kubeadm/app/componentconfigs/kubelet_windows.go","code":"func mutatePaths(cfg *kubeletconfig.KubeletConfiguration, drive string) {\n\tmutateStringField := func(name string, field *string) {\n\t\t// path.IsAbs() is not reliable here in the Windows runtime, so check if the\n\t\t// path starts with \"/\" instead. This means the path originated from a Unix node and\n\t\t// is an absolute path.\n\t\tif !strings.HasPrefix(*field, \"/\") {\n\t\t\treturn\n\t\t}\n\t\t// Prepend the drive letter to the path and update the field.\n\t\t*field = filepath.Join(drive, *field)\n\t\tklog.V(2).Infof(\"[componentconfig] kubelet/Windows: adapted path for field %q to %q\", name, *field)\n\t}\n\n\t// Mutate the fields we care about.\n\tklog.V(2).Infof(\"[componentconfig] kubelet/Windows: changing field \\\"resolverConfig\\\" to empty\")\n\tcfg.ResolverConfig = utilpointer.String(\"\")\n\tmutateStringField(\"staticPodPath\", \u0026cfg.StaticPodPath)\n\tmutateStringField(\"authentication.x509.clientCAFile\", \u0026cfg.Authentication.X509.ClientCAFile)\n}","line":{"from":58,"to":76}} {"id":100000848,"name":"kubeProxyConfigFromCluster","signature":"func kubeProxyConfigFromCluster(h *handler, clientset clientset.Interface, _ *kubeadmapi.ClusterConfiguration) (kubeadmapi.ComponentConfig, error)","file":"cmd/kubeadm/app/componentconfigs/kubeproxy.go","code":"func kubeProxyConfigFromCluster(h *handler, clientset clientset.Interface, _ *kubeadmapi.ClusterConfiguration) (kubeadmapi.ComponentConfig, error) {\n\treturn h.fromConfigMap(clientset, kubeadmconstants.KubeProxyConfigMap, kubeadmconstants.KubeProxyConfigMapKey, false)\n}","line":{"from":51,"to":53}} {"id":100000849,"name":"DeepCopy","signature":"func (kp *kubeProxyConfig) DeepCopy() kubeadmapi.ComponentConfig","file":"cmd/kubeadm/app/componentconfigs/kubeproxy.go","code":"func (kp *kubeProxyConfig) DeepCopy() kubeadmapi.ComponentConfig {\n\tresult := \u0026kubeProxyConfig{}\n\tkp.configBase.DeepCopyInto(\u0026result.configBase)\n\tkp.config.DeepCopyInto(\u0026result.config)\n\treturn result\n}","line":{"from":61,"to":66}} {"id":100000850,"name":"Marshal","signature":"func (kp *kubeProxyConfig) Marshal() ([]byte, error)","file":"cmd/kubeadm/app/componentconfigs/kubeproxy.go","code":"func (kp *kubeProxyConfig) Marshal() ([]byte, error) {\n\treturn kp.configBase.Marshal(\u0026kp.config)\n}","line":{"from":68,"to":70}} {"id":100000851,"name":"Unmarshal","signature":"func (kp *kubeProxyConfig) Unmarshal(docmap kubeadmapi.DocumentMap) error","file":"cmd/kubeadm/app/componentconfigs/kubeproxy.go","code":"func (kp *kubeProxyConfig) Unmarshal(docmap kubeadmapi.DocumentMap) error {\n\treturn kp.configBase.Unmarshal(docmap, \u0026kp.config)\n}","line":{"from":72,"to":74}} {"id":100000852,"name":"kubeProxyDefaultBindAddress","signature":"func kubeProxyDefaultBindAddress(localAdvertiseAddress string) string","file":"cmd/kubeadm/app/componentconfigs/kubeproxy.go","code":"func kubeProxyDefaultBindAddress(localAdvertiseAddress string) string {\n\tip := netutils.ParseIPSloppy(localAdvertiseAddress)\n\tif ip.To4() != nil {\n\t\treturn kubeadmapiv1.DefaultProxyBindAddressv4\n\t}\n\treturn kubeadmapiv1.DefaultProxyBindAddressv6\n}","line":{"from":76,"to":82}} {"id":100000853,"name":"Get","signature":"func (kp *kubeProxyConfig) Get() interface{}","file":"cmd/kubeadm/app/componentconfigs/kubeproxy.go","code":"func (kp *kubeProxyConfig) Get() interface{} {\n\treturn \u0026kp.config\n}","line":{"from":84,"to":86}} {"id":100000854,"name":"Set","signature":"func (kp *kubeProxyConfig) Set(cfg interface{})","file":"cmd/kubeadm/app/componentconfigs/kubeproxy.go","code":"func (kp *kubeProxyConfig) Set(cfg interface{}) {\n\tkp.config = *cfg.(*kubeproxyconfig.KubeProxyConfiguration)\n}","line":{"from":88,"to":90}} {"id":100000855,"name":"Default","signature":"func (kp *kubeProxyConfig) Default(cfg *kubeadmapi.ClusterConfiguration, localAPIEndpoint *kubeadmapi.APIEndpoint, _ *kubeadmapi.NodeRegistrationOptions)","file":"cmd/kubeadm/app/componentconfigs/kubeproxy.go","code":"func (kp *kubeProxyConfig) Default(cfg *kubeadmapi.ClusterConfiguration, localAPIEndpoint *kubeadmapi.APIEndpoint, _ *kubeadmapi.NodeRegistrationOptions) {\n\tconst kind = \"KubeProxyConfiguration\"\n\n\t// The below code is necessary because while KubeProxy may be defined, the user may not\n\t// have defined any feature-gates, thus FeatureGates will be nil and the later insertion\n\t// of any feature-gates will cause a panic.\n\tif kp.config.FeatureGates == nil {\n\t\tkp.config.FeatureGates = map[string]bool{}\n\t}\n\n\tdefaultBindAddress := kubeProxyDefaultBindAddress(localAPIEndpoint.AdvertiseAddress)\n\tif kp.config.BindAddress == \"\" {\n\t\tkp.config.BindAddress = defaultBindAddress\n\t} else if kp.config.BindAddress != defaultBindAddress {\n\t\twarnDefaultComponentConfigValue(kind, \"bindAddress\", defaultBindAddress, kp.config.BindAddress)\n\t}\n\n\tif kp.config.ClusterCIDR == \"\" \u0026\u0026 cfg.Networking.PodSubnet != \"\" {\n\t\tkp.config.ClusterCIDR = cfg.Networking.PodSubnet\n\t} else if cfg.Networking.PodSubnet != \"\" \u0026\u0026 kp.config.ClusterCIDR != cfg.Networking.PodSubnet {\n\t\twarnDefaultComponentConfigValue(kind, \"clusterCIDR\", cfg.Networking.PodSubnet, kp.config.ClusterCIDR)\n\t}\n\n\tif kp.config.ClientConnection.Kubeconfig == \"\" {\n\t\tkp.config.ClientConnection.Kubeconfig = kubeproxyKubeConfigFileName\n\t} else if kp.config.ClientConnection.Kubeconfig != kubeproxyKubeConfigFileName {\n\t\twarnDefaultComponentConfigValue(kind, \"clientConnection.kubeconfig\", kubeproxyKubeConfigFileName, kp.config.ClientConnection.Kubeconfig)\n\t}\n}","line":{"from":92,"to":120}} {"id":100000856,"name":"Mutate","signature":"func (kp *kubeProxyConfig) Mutate() error","file":"cmd/kubeadm/app/componentconfigs/kubeproxy.go","code":"// Mutate is NOP for the kube-proxy config\nfunc (kp *kubeProxyConfig) Mutate() error {\n\treturn nil\n}","line":{"from":122,"to":125}} {"id":100000857,"name":"init","signature":"func init()","file":"cmd/kubeadm/app/componentconfigs/scheme.go","code":"func init() {\n\tmetav1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: \"v1\"})\n\tAddToScheme(Scheme)\n}","line":{"from":33,"to":36}} {"id":100000858,"name":"AddToScheme","signature":"func AddToScheme(scheme *runtime.Scheme)","file":"cmd/kubeadm/app/componentconfigs/scheme.go","code":"// AddToScheme builds the kubeadm ComponentConfig scheme using all known ComponentConfig versions.\nfunc AddToScheme(scheme *runtime.Scheme) {\n\tfor _, handler := range known {\n\t\tutilruntime.Must(handler.AddToScheme(scheme))\n\t}\n}","line":{"from":38,"to":43}} {"id":100000859,"name":"Error","signature":"func (err *UnsupportedConfigVersionError) Error() string","file":"cmd/kubeadm/app/componentconfigs/utils.go","code":"// Error implements the standard Golang error interface for UnsupportedConfigVersionError\nfunc (err *UnsupportedConfigVersionError) Error() string {\n\treturn fmt.Sprintf(\"unsupported apiVersion %q, you may have to do manual conversion to %q and run kubeadm again\", err.OldVersion, err.CurrentVersion)\n}","line":{"from":40,"to":43}} {"id":100000860,"name":"Error","signature":"func (errs UnsupportedConfigVersionsErrorMap) Error() string","file":"cmd/kubeadm/app/componentconfigs/utils.go","code":"// Error implements the standard Golang error interface for UnsupportedConfigVersionsErrorMap\nfunc (errs UnsupportedConfigVersionsErrorMap) Error() string {\n\t// Make sure the error messages we print are predictable by sorting them by the group names involved\n\tgroups := make([]string, 0, len(errs))\n\tfor group := range errs {\n\t\tgroups = append(groups, group)\n\t}\n\tsort.Strings(groups)\n\n\tmsgs := make([]string, 1, 1+len(errs))\n\tmsgs[0] = \"multiple unsupported config version errors encountered:\"\n\tfor _, group := range groups {\n\t\tmsgs = append(msgs, errs[group].Error())\n\t}\n\n\treturn strings.Join(msgs, \"\\n\\t- \")\n}","line":{"from":48,"to":64}} {"id":100000861,"name":"warnDefaultComponentConfigValue","signature":"func warnDefaultComponentConfigValue(componentConfigKind, paramName string, defaultValue, userValue interface{})","file":"cmd/kubeadm/app/componentconfigs/utils.go","code":"// warnDefaultComponentConfigValue prints a warning if the user modified a field in a certain\n// ComponentConfig from the default recommended value in kubeadm.\nfunc warnDefaultComponentConfigValue(componentConfigKind, paramName string, defaultValue, userValue interface{}) {\n\tklog.Warningf(\"The recommended value for %q in %q is: %v; the provided value is: %v\",\n\t\tparamName, componentConfigKind, defaultValue, userValue)\n}","line":{"from":66,"to":71}} {"id":100000862,"name":"getSkewedKubernetesVersion","signature":"func getSkewedKubernetesVersion(n int) *version.Version","file":"cmd/kubeadm/app/constants/constants.go","code":"// getSkewedKubernetesVersion returns the current MAJOR.(MINOR+n).0 Kubernetes version with a skew of 'n'\n// It uses the kubeadm version provided by the 'component-base/version' package. This version must be populated\n// by passing linker flags during the kubeadm build process. If the version is empty, assume that kubeadm\n// was either build incorrectly or this code is running in unit tests.\nfunc getSkewedKubernetesVersion(n int) *version.Version {\n\tversionInfo := componentversion.Get()\n\treturn getSkewedKubernetesVersionImpl(\u0026versionInfo, n)\n}","line":{"from":505,"to":512}} {"id":100000863,"name":"getSkewedKubernetesVersionImpl","signature":"func getSkewedKubernetesVersionImpl(versionInfo *apimachineryversion.Info, n int) *version.Version","file":"cmd/kubeadm/app/constants/constants.go","code":"func getSkewedKubernetesVersionImpl(versionInfo *apimachineryversion.Info, n int) *version.Version {\n\t// TODO: update if the kubeadm version gets decoupled from the Kubernetes version.\n\t// This would require keeping track of the supported skew in a table.\n\t// More changes would be required if the kubelet version one day decouples from that of Kubernetes.\n\tvar ver *version.Version\n\tif len(versionInfo.Major) == 0 {\n\t\treturn defaultKubernetesPlaceholderVersion\n\t}\n\tver = version.MustParseSemantic(versionInfo.GitVersion)\n\t// Append the MINOR version skew.\n\t// TODO: handle the case of Kubernetes moving to v2.0 or having MAJOR version updates in the future.\n\t// This would require keeping track (in a table) of the last MINOR for a particular MAJOR.\n\tminor := uint(int(ver.Minor()) + n)\n\treturn version.MustParseSemantic(fmt.Sprintf(\"v%d.%d.0\", ver.Major(), minor))\n}","line":{"from":514,"to":528}} {"id":100000864,"name":"EtcdSupportedVersion","signature":"func EtcdSupportedVersion(supportedEtcdVersion map[uint8]string, versionString string) (etcdVersion *version.Version, warning, err error)","file":"cmd/kubeadm/app/constants/constants.go","code":"// EtcdSupportedVersion returns officially supported version of etcd for a specific Kubernetes release\n// If passed version is not in the given list, the function returns the nearest version with a warning\nfunc EtcdSupportedVersion(supportedEtcdVersion map[uint8]string, versionString string) (etcdVersion *version.Version, warning, err error) {\n\tkubernetesVersion, err := version.ParseSemantic(versionString)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdesiredVersion, etcdStringVersion := uint8(kubernetesVersion.Minor()), \"\"\n\n\tmin, max := ^uint8(0), uint8(0)\n\tfor k, v := range supportedEtcdVersion {\n\t\tif desiredVersion == k {\n\t\t\tetcdStringVersion = v\n\t\t\tbreak\n\t\t}\n\t\tif k \u003c min {\n\t\t\tmin = k\n\t\t}\n\t\tif k \u003e max {\n\t\t\tmax = k\n\t\t}\n\t}\n\n\tif len(etcdStringVersion) == 0 {\n\t\tif desiredVersion \u003c min {\n\t\t\tetcdStringVersion = supportedEtcdVersion[min]\n\t\t}\n\t\tif desiredVersion \u003e max {\n\t\t\tetcdStringVersion = supportedEtcdVersion[max]\n\t\t}\n\t\twarning = errors.Errorf(\"could not find officially supported version of etcd for Kubernetes %s, falling back to the nearest etcd version (%s)\",\n\t\t\tversionString, etcdStringVersion)\n\t}\n\n\tetcdVersion, err = version.ParseSemantic(etcdStringVersion)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn etcdVersion, warning, nil\n}","line":{"from":530,"to":570}} {"id":100000865,"name":"GetStaticPodDirectory","signature":"func GetStaticPodDirectory() string","file":"cmd/kubeadm/app/constants/constants.go","code":"// GetStaticPodDirectory returns the location on the disk where the Static Pod should be present\nfunc GetStaticPodDirectory() string {\n\treturn filepath.Join(KubernetesDir, ManifestsSubDirName)\n}","line":{"from":572,"to":575}} {"id":100000866,"name":"GetStaticPodFilepath","signature":"func GetStaticPodFilepath(componentName, manifestsDir string) string","file":"cmd/kubeadm/app/constants/constants.go","code":"// GetStaticPodFilepath returns the location on the disk where the Static Pod should be present\nfunc GetStaticPodFilepath(componentName, manifestsDir string) string {\n\treturn filepath.Join(manifestsDir, componentName+\".yaml\")\n}","line":{"from":577,"to":580}} {"id":100000867,"name":"GetAdminKubeConfigPath","signature":"func GetAdminKubeConfigPath() string","file":"cmd/kubeadm/app/constants/constants.go","code":"// GetAdminKubeConfigPath returns the location on the disk where admin kubeconfig is located by default\nfunc GetAdminKubeConfigPath() string {\n\treturn filepath.Join(KubernetesDir, AdminKubeConfigFileName)\n}","line":{"from":582,"to":585}} {"id":100000868,"name":"GetBootstrapKubeletKubeConfigPath","signature":"func GetBootstrapKubeletKubeConfigPath() string","file":"cmd/kubeadm/app/constants/constants.go","code":"// GetBootstrapKubeletKubeConfigPath returns the location on the disk where bootstrap kubelet kubeconfig is located by default\nfunc GetBootstrapKubeletKubeConfigPath() string {\n\treturn filepath.Join(KubernetesDir, KubeletBootstrapKubeConfigFileName)\n}","line":{"from":587,"to":590}} {"id":100000869,"name":"GetKubeletKubeConfigPath","signature":"func GetKubeletKubeConfigPath() string","file":"cmd/kubeadm/app/constants/constants.go","code":"// GetKubeletKubeConfigPath returns the location on the disk where kubelet kubeconfig is located by default\nfunc GetKubeletKubeConfigPath() string {\n\treturn filepath.Join(KubernetesDir, KubeletKubeConfigFileName)\n}","line":{"from":592,"to":595}} {"id":100000870,"name":"CreateTempDirForKubeadm","signature":"func CreateTempDirForKubeadm(kubernetesDir, dirName string) (string, error)","file":"cmd/kubeadm/app/constants/constants.go","code":"// CreateTempDirForKubeadm is a function that creates a temporary directory under /etc/kubernetes/tmp (not using /tmp as that would potentially be dangerous)\nfunc CreateTempDirForKubeadm(kubernetesDir, dirName string) (string, error) {\n\ttempDir := path.Join(KubernetesDir, TempDirForKubeadm)\n\tif len(kubernetesDir) != 0 {\n\t\ttempDir = path.Join(kubernetesDir, TempDirForKubeadm)\n\t}\n\n\t// creates target folder if not already exists\n\tif err := os.MkdirAll(tempDir, 0700); err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"failed to create directory %q\", tempDir)\n\t}\n\n\ttempDir, err := os.MkdirTemp(tempDir, dirName)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"couldn't create a temporary directory\")\n\t}\n\treturn tempDir, nil\n}","line":{"from":597,"to":614}} {"id":100000871,"name":"CreateTimestampDirForKubeadm","signature":"func CreateTimestampDirForKubeadm(kubernetesDir, dirName string) (string, error)","file":"cmd/kubeadm/app/constants/constants.go","code":"// CreateTimestampDirForKubeadm is a function that creates a temporary directory under /etc/kubernetes/tmp formatted with the current date\nfunc CreateTimestampDirForKubeadm(kubernetesDir, dirName string) (string, error) {\n\ttempDir := path.Join(KubernetesDir, TempDirForKubeadm)\n\tif len(kubernetesDir) != 0 {\n\t\ttempDir = path.Join(kubernetesDir, TempDirForKubeadm)\n\t}\n\n\t// creates target folder if not already exists\n\tif err := os.MkdirAll(tempDir, 0700); err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"failed to create directory %q\", tempDir)\n\t}\n\n\ttimestampDirName := fmt.Sprintf(\"%s-%s\", dirName, time.Now().Format(\"2006-01-02-15-04-05\"))\n\ttimestampDir := path.Join(tempDir, timestampDirName)\n\tif err := os.Mkdir(timestampDir, 0700); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"could not create timestamp directory\")\n\t}\n\n\treturn timestampDir, nil\n}","line":{"from":616,"to":635}} {"id":100000872,"name":"GetDNSIP","signature":"func GetDNSIP(svcSubnetList string) (net.IP, error)","file":"cmd/kubeadm/app/constants/constants.go","code":"// GetDNSIP returns a dnsIP, which is 10th IP in svcSubnet CIDR range\nfunc GetDNSIP(svcSubnetList string) (net.IP, error) {\n\t// Get the service subnet CIDR\n\tsvcSubnetCIDR, err := GetKubernetesServiceCIDR(svcSubnetList)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get internal Kubernetes Service IP from the given service CIDR (%s)\", svcSubnetList)\n\t}\n\n\t// Selects the 10th IP in service subnet CIDR range as dnsIP\n\tdnsIP, err := netutils.GetIndexedIP(svcSubnetCIDR, 10)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to get internal Kubernetes Service IP from the given service CIDR\")\n\t}\n\n\treturn dnsIP, nil\n}","line":{"from":637,"to":652}} {"id":100000873,"name":"GetKubernetesServiceCIDR","signature":"func GetKubernetesServiceCIDR(svcSubnetList string) (*net.IPNet, error)","file":"cmd/kubeadm/app/constants/constants.go","code":"// GetKubernetesServiceCIDR returns the default Service CIDR for the Kubernetes internal service\nfunc GetKubernetesServiceCIDR(svcSubnetList string) (*net.IPNet, error) {\n\t// The default service address family for the cluster is the address family of the first\n\t// service cluster IP range configured via the `--service-cluster-ip-range` flag\n\t// of the kube-controller-manager and kube-apiserver.\n\tsvcSubnets, err := netutils.ParseCIDRs(strings.Split(svcSubnetList, \",\"))\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to parse ServiceSubnet %v\", svcSubnetList)\n\t}\n\tif len(svcSubnets) == 0 {\n\t\treturn nil, errors.New(\"received empty ServiceSubnet\")\n\t}\n\treturn svcSubnets[0], nil\n}","line":{"from":654,"to":667}} {"id":100000874,"name":"GetAPIServerVirtualIP","signature":"func GetAPIServerVirtualIP(svcSubnetList string) (net.IP, error)","file":"cmd/kubeadm/app/constants/constants.go","code":"// GetAPIServerVirtualIP returns the IP of the internal Kubernetes API service\nfunc GetAPIServerVirtualIP(svcSubnetList string) (net.IP, error) {\n\tsvcSubnet, err := GetKubernetesServiceCIDR(svcSubnetList)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to get internal Kubernetes Service IP from the given service CIDR\")\n\t}\n\tinternalAPIServerVirtualIP, err := netutils.GetIndexedIP(svcSubnet, 1)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get the first IP address from the given CIDR: %s\", svcSubnet.String())\n\t}\n\treturn internalAPIServerVirtualIP, nil\n}","line":{"from":669,"to":680}} {"id":100000875,"name":"For","signature":"func For(cfg *kubeadmapi.JoinConfiguration) (*clientcmdapi.Config, error)","file":"cmd/kubeadm/app/discovery/discovery.go","code":"// For returns a kubeconfig object that can be used for doing the TLS Bootstrap with the right credentials\n// Also, before returning anything, it makes sure it can trust the API Server\nfunc For(cfg *kubeadmapi.JoinConfiguration) (*clientcmdapi.Config, error) {\n\t// TODO: Print summary info about the CA certificate, along with the checksum signature\n\t// we also need an ability for the user to configure the client to validate received CA cert against a checksum\n\tconfig, err := DiscoverValidatedKubeConfig(cfg)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"couldn't validate the identity of the API Server\")\n\t}\n\n\t// If the users has provided a TLSBootstrapToken use it for the join process.\n\t// This is usually the case of Token discovery, but it can also be used with a discovery file\n\t// without embedded authentication credentials.\n\tif len(cfg.Discovery.TLSBootstrapToken) != 0 {\n\t\tklog.V(1).Info(\"[discovery] Using provided TLSBootstrapToken as authentication credentials for the join process\")\n\n\t\t_, clusterinfo := kubeconfigutil.GetClusterFromKubeConfig(config)\n\t\treturn kubeconfigutil.CreateWithToken(\n\t\t\tclusterinfo.Server,\n\t\t\tkubeadmapiv1.DefaultClusterName,\n\t\t\tTokenUser,\n\t\t\tclusterinfo.CertificateAuthorityData,\n\t\t\tcfg.Discovery.TLSBootstrapToken,\n\t\t), nil\n\t}\n\n\t// if the config returned from discovery has authentication credentials, proceed with the TLS boostrap process\n\tif kubeconfigutil.HasAuthenticationCredentials(config) {\n\t\treturn config, nil\n\t}\n\n\t// if there are no authentication credentials (nor in the config returned from discovery, nor in the TLSBootstrapToken), fail\n\treturn nil, errors.New(\"couldn't find authentication credentials for the TLS boostrap process. Please use Token discovery, a discovery file with embedded authentication credentials or a discovery file without authentication credentials but with the TLSBootstrapToken flag\")\n}","line":{"from":38,"to":71}} {"id":100000876,"name":"DiscoverValidatedKubeConfig","signature":"func DiscoverValidatedKubeConfig(cfg *kubeadmapi.JoinConfiguration) (*clientcmdapi.Config, error)","file":"cmd/kubeadm/app/discovery/discovery.go","code":"// DiscoverValidatedKubeConfig returns a validated Config object that specifies where the cluster is and the CA cert to trust\nfunc DiscoverValidatedKubeConfig(cfg *kubeadmapi.JoinConfiguration) (*clientcmdapi.Config, error) {\n\tswitch {\n\tcase cfg.Discovery.File != nil:\n\t\tkubeConfigPath := cfg.Discovery.File.KubeConfigPath\n\t\tif isHTTPSURL(kubeConfigPath) {\n\t\t\treturn https.RetrieveValidatedConfigInfo(kubeConfigPath, cfg.Discovery.Timeout.Duration)\n\t\t}\n\t\treturn file.RetrieveValidatedConfigInfo(kubeConfigPath, cfg.Discovery.Timeout.Duration)\n\tcase cfg.Discovery.BootstrapToken != nil:\n\t\treturn token.RetrieveValidatedConfigInfo(\u0026cfg.Discovery)\n\tdefault:\n\t\treturn nil, errors.New(\"couldn't find a valid discovery configuration\")\n\t}\n}","line":{"from":73,"to":87}} {"id":100000877,"name":"isHTTPSURL","signature":"func isHTTPSURL(s string) bool","file":"cmd/kubeadm/app/discovery/discovery.go","code":"// isHTTPSURL checks whether the string is parsable as a URL and whether the Scheme is https\nfunc isHTTPSURL(s string) bool {\n\tu, err := url.Parse(s)\n\treturn err == nil \u0026\u0026 u.Scheme == \"https\"\n}","line":{"from":89,"to":93}} {"id":100000878,"name":"RetrieveValidatedConfigInfo","signature":"func RetrieveValidatedConfigInfo(filepath string, discoveryTimeout time.Duration) (*clientcmdapi.Config, error)","file":"cmd/kubeadm/app/discovery/file/file.go","code":"// RetrieveValidatedConfigInfo connects to the API Server and makes sure it can talk\n// securely to the API Server using the provided CA cert and\n// optionally refreshes the cluster-info information from the cluster-info ConfigMap\nfunc RetrieveValidatedConfigInfo(filepath string, discoveryTimeout time.Duration) (*clientcmdapi.Config, error) {\n\tconfig, err := clientcmd.LoadFromFile(filepath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ValidateConfigInfo(config, discoveryTimeout)\n}","line":{"from":38,"to":47}} {"id":100000879,"name":"ValidateConfigInfo","signature":"func ValidateConfigInfo(config *clientcmdapi.Config, discoveryTimeout time.Duration) (*clientcmdapi.Config, error)","file":"cmd/kubeadm/app/discovery/file/file.go","code":"// ValidateConfigInfo connects to the API Server and makes sure it can talk\n// securely to the API Server using the provided CA cert/client certificates and\n// optionally refreshes the cluster-info information from the cluster-info ConfigMap\nfunc ValidateConfigInfo(config *clientcmdapi.Config, discoveryTimeout time.Duration) (*clientcmdapi.Config, error) {\n\tif len(config.Clusters) \u003c 1 {\n\t\treturn nil, errors.New(\"the provided kubeconfig file must have at least one Cluster defined\")\n\t}\n\tcurrentClusterName, currentCluster := kubeconfigutil.GetClusterFromKubeConfig(config)\n\tif currentCluster == nil {\n\t\treturn nil, errors.New(\"the provided kubeconfig file must have a unnamed Cluster or a CurrentContext that specifies a non-nil Cluster\")\n\t}\n\tif err := clientcmd.Validate(*config); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// If the kubeconfig points to a file for the CA, make sure the CA file contents are embedded\n\tif err := kubeconfigutil.EnsureCertificateAuthorityIsEmbedded(currentCluster); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// If the discovery file config contains authentication credentials\n\tif kubeconfigutil.HasAuthenticationCredentials(config) {\n\t\tklog.V(1).Info(\"[discovery] Using authentication credentials from the discovery file for validating TLS connection\")\n\n\t\t// We should ensure that all the authentication info is embedded in config file, so everything will work also when\n\t\t// the kubeconfig file will be stored in /etc/kubernetes/boostrap-kubelet.conf\n\t\tif err := kubeconfigutil.EnsureAuthenticationInfoAreEmbedded(config); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\t// If the discovery file config does not contains authentication credentials\n\t\tklog.V(1).Info(\"[discovery] Discovery file does not contains authentication credentials, using unauthenticated request for validating TLS connection\")\n\t}\n\n\t// Try to read the cluster-info config map; this step was required by the original design in order\n\t// to validate the TLS connection to the server early in the process\n\tclient, err := kubeconfigutil.ToClientSet(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tklog.V(1).Infof(\"[discovery] Created cluster-info discovery client, requesting info from %q\\n\", currentCluster.Server)\n\n\tvar clusterinfoCM *v1.ConfigMap\n\n\terr = wait.Poll(constants.DiscoveryRetryInterval, discoveryTimeout, func() (bool, error) {\n\t\tvar err error\n\t\tclusterinfoCM, err = client.CoreV1().ConfigMaps(metav1.NamespacePublic).Get(context.TODO(), bootstrapapi.ConfigMapClusterInfo, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\tif apierrors.IsForbidden(err) {\n\t\t\t\t// If the request is unauthorized, the cluster admin has not granted access to the cluster info configmap for unauthenticated users\n\t\t\t\t// In that case, trust the cluster admin and do not refresh the cluster-info data\n\t\t\t\tklog.Warningf(\"[discovery] Could not access the %s ConfigMap for refreshing the cluster-info information, but the TLS cert is valid so proceeding...\\n\", bootstrapapi.ConfigMapClusterInfo)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\tklog.V(1).Infof(\"[discovery] Error reading the %s ConfigMap, will try again: %v\\n\", bootstrapapi.ConfigMapClusterInfo, err)\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\tif err == wait.ErrWaitTimeout {\n\t\treturn nil, errors.Errorf(\"Abort reading the %s ConfigMap after timeout of %v\", bootstrapapi.ConfigMapClusterInfo, discoveryTimeout)\n\t}\n\n\t// If we couldn't fetch the cluster-info ConfigMap, just return the cluster-info object the user provided\n\tif clusterinfoCM == nil {\n\t\treturn config, nil\n\t}\n\n\t// We somehow got hold of the ConfigMap, try to read some data from it. If we can't, fallback on the user-provided file\n\trefreshedBaseKubeConfig, err := tryParseClusterInfoFromConfigMap(clusterinfoCM)\n\tif err != nil {\n\t\tklog.V(1).Infof(\"[discovery] The %s ConfigMap isn't set up properly (%v), but the TLS cert is valid so proceeding...\\n\", bootstrapapi.ConfigMapClusterInfo, err)\n\t\treturn config, nil\n\t}\n\n\t_, refreshedCluster := kubeconfigutil.GetClusterFromKubeConfig(refreshedBaseKubeConfig)\n\tif currentCluster.Server != refreshedCluster.Server {\n\t\tklog.Warningf(\"[discovery] the API Server endpoint %q in use is different from the endpoint %q which defined in the %s ConfigMap\", currentCluster.Server, refreshedCluster.Server, bootstrapapi.ConfigMapClusterInfo)\n\t}\n\n\tif len(currentCluster.CertificateAuthorityData) == 0 \u0026\u0026 len(refreshedCluster.CertificateAuthorityData) \u003e 0 {\n\t\tconfig.Clusters[currentClusterName].CertificateAuthorityData = refreshedCluster.CertificateAuthorityData\n\t\tklog.V(1).Infof(\"[discovery] Synced CertificateAuthorityData from the %s ConfigMap\", bootstrapapi.ConfigMapClusterInfo)\n\t}\n\n\treturn config, nil\n}","line":{"from":49,"to":136}} {"id":100000880,"name":"tryParseClusterInfoFromConfigMap","signature":"func tryParseClusterInfoFromConfigMap(cm *v1.ConfigMap) (*clientcmdapi.Config, error)","file":"cmd/kubeadm/app/discovery/file/file.go","code":"// tryParseClusterInfoFromConfigMap tries to parse a kubeconfig file from a ConfigMap key\nfunc tryParseClusterInfoFromConfigMap(cm *v1.ConfigMap) (*clientcmdapi.Config, error) {\n\tkubeConfigString, ok := cm.Data[bootstrapapi.KubeConfigKey]\n\tif !ok || len(kubeConfigString) == 0 {\n\t\treturn nil, errors.Errorf(\"no %s key in ConfigMap\", bootstrapapi.KubeConfigKey)\n\t}\n\tparsedKubeConfig, err := clientcmd.Load([]byte(kubeConfigString))\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"couldn't parse the kubeconfig file in the %s ConfigMap\", bootstrapapi.ConfigMapClusterInfo)\n\t}\n\treturn parsedKubeConfig, nil\n}","line":{"from":138,"to":149}} {"id":100000881,"name":"RetrieveValidatedConfigInfo","signature":"func RetrieveValidatedConfigInfo(httpsURL string, discoveryTimeout time.Duration) (*clientcmdapi.Config, error)","file":"cmd/kubeadm/app/discovery/https/https.go","code":"// RetrieveValidatedConfigInfo connects to the API Server and makes sure it can talk\n// securely to the API Server using the provided CA cert and\n// optionally refreshes the cluster-info information from the cluster-info ConfigMap\nfunc RetrieveValidatedConfigInfo(httpsURL string, discoveryTimeout time.Duration) (*clientcmdapi.Config, error) {\n\tclient := \u0026http.Client{Transport: netutil.SetOldTransportDefaults(\u0026http.Transport{})}\n\tresponse, err := client.Get(httpsURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer response.Body.Close()\n\n\tkubeconfig, err := io.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig, err := clientcmd.Load(kubeconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn file.ValidateConfigInfo(config, discoveryTimeout)\n}","line":{"from":31,"to":52}} {"id":100000882,"name":"RetrieveValidatedConfigInfo","signature":"func RetrieveValidatedConfigInfo(cfg *kubeadmapi.Discovery) (*clientcmdapi.Config, error)","file":"cmd/kubeadm/app/discovery/token/token.go","code":"// RetrieveValidatedConfigInfo connects to the API Server and tries to fetch the cluster-info ConfigMap\n// It then makes sure it can trust the API Server by looking at the JWS-signed tokens and (if CACertHashes is not empty)\n// validating the cluster CA against a set of pinned public keys\nfunc RetrieveValidatedConfigInfo(cfg *kubeadmapi.Discovery) (*clientcmdapi.Config, error) {\n\treturn retrieveValidatedConfigInfo(nil, cfg, constants.DiscoveryRetryInterval)\n}","line":{"from":49,"to":54}} {"id":100000883,"name":"retrieveValidatedConfigInfo","signature":"func retrieveValidatedConfigInfo(client clientset.Interface, cfg *kubeadmapi.Discovery, interval time.Duration) (*clientcmdapi.Config, error)","file":"cmd/kubeadm/app/discovery/token/token.go","code":"// retrieveValidatedConfigInfo is a private implementation of RetrieveValidatedConfigInfo.\n// It accepts an optional clientset that can be used for testing purposes.\nfunc retrieveValidatedConfigInfo(client clientset.Interface, cfg *kubeadmapi.Discovery, interval time.Duration) (*clientcmdapi.Config, error) {\n\ttoken, err := bootstraptokenv1.NewBootstrapTokenString(cfg.BootstrapToken.Token)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Load the CACertHashes into a pubkeypin.Set\n\tpubKeyPins := pubkeypin.NewSet()\n\tif err = pubKeyPins.Allow(cfg.BootstrapToken.CACertHashes...); err != nil {\n\t\treturn nil, errors.Wrap(err, \"invalid discovery token CA certificate hash\")\n\t}\n\n\tduration := cfg.Timeout.Duration\n\t// Make sure the interval is not bigger than the duration\n\tif interval \u003e duration {\n\t\tinterval = duration\n\t}\n\n\tendpoint := cfg.BootstrapToken.APIServerEndpoint\n\tinsecureBootstrapConfig := buildInsecureBootstrapKubeConfig(endpoint, kubeadmapiv1.DefaultClusterName)\n\tclusterName := insecureBootstrapConfig.Contexts[insecureBootstrapConfig.CurrentContext].Cluster\n\n\tklog.V(1).Infof(\"[discovery] Created cluster-info discovery client, requesting info from %q\", endpoint)\n\tinsecureClusterInfo, err := getClusterInfo(client, insecureBootstrapConfig, token, interval, duration)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Validate the token in the cluster info\n\tinsecureKubeconfigBytes, err := validateClusterInfoToken(insecureClusterInfo, token)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Load the insecure config\n\tinsecureConfig, err := clientcmd.Load(insecureKubeconfigBytes)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"couldn't parse the kubeconfig file in the %s ConfigMap\", bootstrapapi.ConfigMapClusterInfo)\n\t}\n\n\t// The ConfigMap should contain a single cluster\n\tif len(insecureConfig.Clusters) != 1 {\n\t\treturn nil, errors.Errorf(\"expected the kubeconfig file in the %s ConfigMap to have a single cluster, but it had %d\", bootstrapapi.ConfigMapClusterInfo, len(insecureConfig.Clusters))\n\t}\n\n\t// If no TLS root CA pinning was specified, we're done\n\tif pubKeyPins.Empty() {\n\t\tklog.V(1).Infof(\"[discovery] Cluster info signature and contents are valid and no TLS pinning was specified, will use API Server %q\", endpoint)\n\t\treturn insecureConfig, nil\n\t}\n\n\t// Load and validate the cluster CA from the insecure kubeconfig\n\tclusterCABytes, err := validateClusterCA(insecureConfig, pubKeyPins)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Now that we know the cluster CA, connect back a second time validating with that CA\n\tsecureBootstrapConfig := buildSecureBootstrapKubeConfig(endpoint, clusterCABytes, clusterName)\n\n\tklog.V(1).Infof(\"[discovery] Requesting info from %q again to validate TLS against the pinned public key\", endpoint)\n\tsecureClusterInfo, err := getClusterInfo(client, secureBootstrapConfig, token, interval, duration)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Pull the kubeconfig from the securely-obtained ConfigMap and validate that it's the same as what we found the first time\n\tsecureKubeconfigBytes := []byte(secureClusterInfo.Data[bootstrapapi.KubeConfigKey])\n\tif !bytes.Equal(secureKubeconfigBytes, insecureKubeconfigBytes) {\n\t\treturn nil, errors.Errorf(\"the second kubeconfig from the %s ConfigMap (using validated TLS) was different from the first\", bootstrapapi.ConfigMapClusterInfo)\n\t}\n\n\tsecureKubeconfig, err := clientcmd.Load(secureKubeconfigBytes)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"couldn't parse the kubeconfig file in the %s ConfigMap\", bootstrapapi.ConfigMapClusterInfo)\n\t}\n\n\tklog.V(1).Infof(\"[discovery] Cluster info signature and contents are valid and TLS certificate validates against pinned roots, will use API Server %q\", endpoint)\n\n\treturn secureKubeconfig, nil\n}","line":{"from":56,"to":138}} {"id":100000884,"name":"buildInsecureBootstrapKubeConfig","signature":"func buildInsecureBootstrapKubeConfig(endpoint, clustername string) *clientcmdapi.Config","file":"cmd/kubeadm/app/discovery/token/token.go","code":"// buildInsecureBootstrapKubeConfig makes a kubeconfig object that connects insecurely to the API Server for bootstrapping purposes\nfunc buildInsecureBootstrapKubeConfig(endpoint, clustername string) *clientcmdapi.Config {\n\tcontrolPlaneEndpoint := fmt.Sprintf(\"https://%s\", endpoint)\n\tbootstrapConfig := kubeconfigutil.CreateBasic(controlPlaneEndpoint, clustername, BootstrapUser, []byte{})\n\tbootstrapConfig.Clusters[clustername].InsecureSkipTLSVerify = true\n\treturn bootstrapConfig\n}","line":{"from":140,"to":146}} {"id":100000885,"name":"buildSecureBootstrapKubeConfig","signature":"func buildSecureBootstrapKubeConfig(endpoint string, caCert []byte, clustername string) *clientcmdapi.Config","file":"cmd/kubeadm/app/discovery/token/token.go","code":"// buildSecureBootstrapKubeConfig makes a kubeconfig object that connects securely to the API Server for bootstrapping purposes (validating with the specified CA)\nfunc buildSecureBootstrapKubeConfig(endpoint string, caCert []byte, clustername string) *clientcmdapi.Config {\n\tcontrolPlaneEndpoint := fmt.Sprintf(\"https://%s\", endpoint)\n\tbootstrapConfig := kubeconfigutil.CreateBasic(controlPlaneEndpoint, clustername, BootstrapUser, caCert)\n\treturn bootstrapConfig\n}","line":{"from":148,"to":153}} {"id":100000886,"name":"validateClusterInfoToken","signature":"func validateClusterInfoToken(insecureClusterInfo *v1.ConfigMap, token *bootstraptokenv1.BootstrapTokenString) ([]byte, error)","file":"cmd/kubeadm/app/discovery/token/token.go","code":"// validateClusterInfoToken validates that the JWS token present in the cluster info ConfigMap is valid\nfunc validateClusterInfoToken(insecureClusterInfo *v1.ConfigMap, token *bootstraptokenv1.BootstrapTokenString) ([]byte, error) {\n\tinsecureKubeconfigString, ok := insecureClusterInfo.Data[bootstrapapi.KubeConfigKey]\n\tif !ok || len(insecureKubeconfigString) == 0 {\n\t\treturn nil, errors.Errorf(\"there is no %s key in the %s ConfigMap. This API Server isn't set up for token bootstrapping, can't connect\",\n\t\t\tbootstrapapi.KubeConfigKey, bootstrapapi.ConfigMapClusterInfo)\n\t}\n\n\tdetachedJWSToken, ok := insecureClusterInfo.Data[bootstrapapi.JWSSignatureKeyPrefix+token.ID]\n\tif !ok || len(detachedJWSToken) == 0 {\n\t\treturn nil, errors.Errorf(\"token id %q is invalid for this cluster or it has expired. Use \\\"kubeadm token create\\\" on the control-plane node to create a new valid token\", token.ID)\n\t}\n\n\tif !bootstrap.DetachedTokenIsValid(detachedJWSToken, insecureKubeconfigString, token.ID, token.Secret) {\n\t\treturn nil, errors.New(\"failed to verify JWS signature of received cluster info object, can't trust this API Server\")\n\t}\n\n\treturn []byte(insecureKubeconfigString), nil\n}","line":{"from":155,"to":173}} {"id":100000887,"name":"validateClusterCA","signature":"func validateClusterCA(insecureConfig *clientcmdapi.Config, pubKeyPins *pubkeypin.Set) ([]byte, error)","file":"cmd/kubeadm/app/discovery/token/token.go","code":"// validateClusterCA validates the cluster CA found in the insecure kubeconfig\nfunc validateClusterCA(insecureConfig *clientcmdapi.Config, pubKeyPins *pubkeypin.Set) ([]byte, error) {\n\tvar clusterCABytes []byte\n\tfor _, cluster := range insecureConfig.Clusters {\n\t\tclusterCABytes = cluster.CertificateAuthorityData\n\t}\n\n\tclusterCAs, err := certutil.ParseCertsPEM(clusterCABytes)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to parse cluster CA from the %s ConfigMap\", bootstrapapi.ConfigMapClusterInfo)\n\t}\n\n\t// Validate the cluster CA public key against the pinned set\n\terr = pubKeyPins.CheckAny(clusterCAs)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"cluster CA found in %s ConfigMap is invalid\", bootstrapapi.ConfigMapClusterInfo)\n\t}\n\n\treturn clusterCABytes, nil\n}","line":{"from":175,"to":194}} {"id":100000888,"name":"getClusterInfo","signature":"func getClusterInfo(client clientset.Interface, kubeconfig *clientcmdapi.Config, token *bootstraptokenv1.BootstrapTokenString, interval, duration time.Duration) (*v1.ConfigMap, error)","file":"cmd/kubeadm/app/discovery/token/token.go","code":"// getClusterInfo creates a client from the given kubeconfig if the given client is nil,\n// and requests the cluster info ConfigMap using PollImmediate.\n// If a client is provided it will be used instead.\nfunc getClusterInfo(client clientset.Interface, kubeconfig *clientcmdapi.Config, token *bootstraptokenv1.BootstrapTokenString, interval, duration time.Duration) (*v1.ConfigMap, error) {\n\tvar cm *v1.ConfigMap\n\tvar err error\n\n\t// Create client from kubeconfig\n\tif client == nil {\n\t\tclient, err = kubeconfigutil.ToClientSet(kubeconfig)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tctx, cancel := context.WithTimeout(context.TODO(), duration)\n\tdefer cancel()\n\n\twait.JitterUntil(func() {\n\t\tcm, err = client.CoreV1().ConfigMaps(metav1.NamespacePublic).Get(context.TODO(), bootstrapapi.ConfigMapClusterInfo, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\tklog.V(1).Infof(\"[discovery] Failed to request cluster-info, will try again: %v\", err)\n\t\t\treturn\n\t\t}\n\t\t// Even if the ConfigMap is available the JWS signature is patched-in a bit later.\n\t\t// Make sure we retry util then.\n\t\tif _, ok := cm.Data[bootstrapapi.JWSSignatureKeyPrefix+token.ID]; !ok {\n\t\t\tklog.V(1).Infof(\"[discovery] The cluster-info ConfigMap does not yet contain a JWS signature for token ID %q, will try again\", token.ID)\n\t\t\terr = errors.Errorf(\"could not find a JWS signature in the cluster-info ConfigMap for token ID %q\", token.ID)\n\t\t\treturn\n\t\t}\n\t\t// Cancel the context on success\n\t\tcancel()\n\t}, interval, 0.3, true, ctx.Done())\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cm, nil\n}","line":{"from":196,"to":236}} {"id":100000889,"name":"ValidateVersion","signature":"func ValidateVersion(allFeatures FeatureList, requestedFeatures map[string]bool, requestedVersion string) error","file":"cmd/kubeadm/app/features/features.go","code":"// ValidateVersion ensures that a feature gate list is compatible with the chosen Kubernetes version\nfunc ValidateVersion(allFeatures FeatureList, requestedFeatures map[string]bool, requestedVersion string) error {\n\tif requestedVersion == \"\" {\n\t\treturn nil\n\t}\n\tparsedExpVersion, err := version.ParseSemantic(requestedVersion)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"error parsing version %s\", requestedVersion)\n\t}\n\tfor k := range requestedFeatures {\n\t\tif minVersion := allFeatures[k].MinimumVersion; minVersion != nil {\n\t\t\tif !parsedExpVersion.AtLeast(minVersion) {\n\t\t\t\treturn errors.Errorf(\n\t\t\t\t\t\"the requested Kubernetes version (%s) is incompatible with the %s feature gate, which needs %s as a minimum\",\n\t\t\t\t\trequestedVersion, k, minVersion)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":58,"to":77}} {"id":100000890,"name":"Enabled","signature":"func Enabled(featureList map[string]bool, featureName string) bool","file":"cmd/kubeadm/app/features/features.go","code":"// Enabled indicates whether a feature name has been enabled\nfunc Enabled(featureList map[string]bool, featureName string) bool {\n\tif enabled, ok := featureList[string(featureName)]; ok {\n\t\treturn enabled\n\t}\n\treturn InitFeatureGates[string(featureName)].Default\n}","line":{"from":79,"to":85}} {"id":100000891,"name":"Supports","signature":"func Supports(featureList FeatureList, featureName string) bool","file":"cmd/kubeadm/app/features/features.go","code":"// Supports indicates whether a feature name is supported on the given\n// feature set\nfunc Supports(featureList FeatureList, featureName string) bool {\n\tfor k, v := range featureList {\n\t\tif featureName == string(k) {\n\t\t\treturn v.PreRelease != featuregate.Deprecated\n\t\t}\n\t}\n\treturn false\n}","line":{"from":87,"to":96}} {"id":100000892,"name":"Keys","signature":"func Keys(featureList FeatureList) []string","file":"cmd/kubeadm/app/features/features.go","code":"// Keys returns a slice of feature names for a given feature set\nfunc Keys(featureList FeatureList) []string {\n\tvar list []string\n\tfor k := range featureList {\n\t\tlist = append(list, string(k))\n\t}\n\treturn list\n}","line":{"from":98,"to":105}} {"id":100000893,"name":"KnownFeatures","signature":"func KnownFeatures(f *FeatureList) []string","file":"cmd/kubeadm/app/features/features.go","code":"// KnownFeatures returns a slice of strings describing the FeatureList features.\nfunc KnownFeatures(f *FeatureList) []string {\n\tvar known []string\n\tfor k, v := range *f {\n\t\tif v.HiddenInHelpText {\n\t\t\tcontinue\n\t\t}\n\n\t\tpre := \"\"\n\t\tif v.PreRelease != featuregate.GA {\n\t\t\tpre = fmt.Sprintf(\"%s - \", v.PreRelease)\n\t\t}\n\t\tknown = append(known, fmt.Sprintf(\"%s=true|false (%sdefault=%t)\", k, pre, v.Default))\n\t}\n\tsort.Strings(known)\n\treturn known\n}","line":{"from":107,"to":123}} {"id":100000894,"name":"NewFeatureGate","signature":"func NewFeatureGate(f *FeatureList, value string) (map[string]bool, error)","file":"cmd/kubeadm/app/features/features.go","code":"// NewFeatureGate parses a string of the form \"key1=value1,key2=value2,...\" into a\n// map[string]bool of known keys or returns an error.\nfunc NewFeatureGate(f *FeatureList, value string) (map[string]bool, error) {\n\tfeatureGate := map[string]bool{}\n\tfor _, s := range strings.Split(value, \",\") {\n\t\tif len(s) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tarr := strings.SplitN(s, \"=\", 2)\n\t\tif len(arr) != 2 {\n\t\t\treturn nil, errors.Errorf(\"missing bool value for feature-gate key:%s\", s)\n\t\t}\n\n\t\tk := strings.TrimSpace(arr[0])\n\t\tv := strings.TrimSpace(arr[1])\n\n\t\tfeatureSpec, ok := (*f)[k]\n\t\tif !ok {\n\t\t\treturn nil, errors.Errorf(\"unrecognized feature-gate key: %s\", k)\n\t\t}\n\n\t\tif featureSpec.PreRelease == featuregate.Deprecated {\n\t\t\treturn nil, errors.Errorf(\"feature-gate key is deprecated: %s\", k)\n\t\t}\n\n\t\tboolValue, err := strconv.ParseBool(v)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Errorf(\"invalid value %v for feature-gate key: %s, use true|false instead\", v, k)\n\t\t}\n\t\tfeatureGate[k] = boolValue\n\t}\n\n\treturn featureGate, nil\n}","line":{"from":125,"to":159}} {"id":100000895,"name":"CheckDeprecatedFlags","signature":"func CheckDeprecatedFlags(f *FeatureList, features map[string]bool) map[string]string","file":"cmd/kubeadm/app/features/features.go","code":"// CheckDeprecatedFlags takes a list of existing feature gate flags and validates against the current feature flag set.\n// It used during upgrades for ensuring consistency of feature gates used in an existing cluster, that might\n// be created with a previous version of kubeadm, with the set of features currently supported by kubeadm\nfunc CheckDeprecatedFlags(f *FeatureList, features map[string]bool) map[string]string {\n\tdeprecatedMsg := map[string]string{}\n\tfor k := range features {\n\t\tfeatureSpec, ok := (*f)[k]\n\t\tif !ok {\n\t\t\t// This case should never happen, it is implemented only as a sentinel\n\t\t\t// for removal of flags executed when flags are still in use (always before deprecate, then after one cycle remove)\n\t\t\tdeprecatedMsg[k] = fmt.Sprintf(\"Unknown feature gate flag: %s\", k)\n\t\t}\n\n\t\tif featureSpec.PreRelease == featuregate.Deprecated {\n\t\t\tif _, ok := deprecatedMsg[k]; !ok {\n\t\t\t\tdeprecatedMsg[k] = featureSpec.DeprecationMessage\n\t\t\t}\n\t\t}\n\t}\n\n\treturn deprecatedMsg\n}","line":{"from":161,"to":182}} {"id":100000896,"name":"GetGenericImage","signature":"func GetGenericImage(prefix, image, tag string) string","file":"cmd/kubeadm/app/images/images.go","code":"// GetGenericImage generates and returns a platform agnostic image (backed by manifest list)\nfunc GetGenericImage(prefix, image, tag string) string {\n\treturn fmt.Sprintf(\"%s/%s:%s\", prefix, image, tag)\n}","line":{"from":30,"to":33}} {"id":100000897,"name":"GetKubernetesImage","signature":"func GetKubernetesImage(image string, cfg *kubeadmapi.ClusterConfiguration) string","file":"cmd/kubeadm/app/images/images.go","code":"// GetKubernetesImage generates and returns the image for the components managed in the Kubernetes main repository,\n// including the control-plane components and kube-proxy.\nfunc GetKubernetesImage(image string, cfg *kubeadmapi.ClusterConfiguration) string {\n\trepoPrefix := cfg.GetControlPlaneImageRepository()\n\tkubernetesImageTag := kubeadmutil.KubernetesVersionToImageTag(cfg.KubernetesVersion)\n\treturn GetGenericImage(repoPrefix, image, kubernetesImageTag)\n}","line":{"from":35,"to":41}} {"id":100000898,"name":"GetDNSImage","signature":"func GetDNSImage(cfg *kubeadmapi.ClusterConfiguration) string","file":"cmd/kubeadm/app/images/images.go","code":"// GetDNSImage generates and returns the image for CoreDNS.\nfunc GetDNSImage(cfg *kubeadmapi.ClusterConfiguration) string {\n\t// DNS uses default image repository by default\n\tdnsImageRepository := cfg.ImageRepository\n\t// unless an override is specified\n\tif cfg.DNS.ImageRepository != \"\" {\n\t\tdnsImageRepository = cfg.DNS.ImageRepository\n\t}\n\t// Handle the renaming of the official image from \"registry.k8s.io/coredns\" to \"registry.k8s.io/coredns/coredns\n\tif dnsImageRepository == kubeadmapiv1beta3.DefaultImageRepository {\n\t\tdnsImageRepository = fmt.Sprintf(\"%s/coredns\", dnsImageRepository)\n\t}\n\t// DNS uses an imageTag that corresponds to the DNS version matching the Kubernetes version\n\tdnsImageTag := constants.CoreDNSVersion\n\n\t// unless an override is specified\n\tif cfg.DNS.ImageTag != \"\" {\n\t\tdnsImageTag = cfg.DNS.ImageTag\n\t}\n\treturn GetGenericImage(dnsImageRepository, constants.CoreDNSImageName, dnsImageTag)\n}","line":{"from":43,"to":63}} {"id":100000899,"name":"GetEtcdImage","signature":"func GetEtcdImage(cfg *kubeadmapi.ClusterConfiguration) string","file":"cmd/kubeadm/app/images/images.go","code":"// GetEtcdImage generates and returns the image for etcd\nfunc GetEtcdImage(cfg *kubeadmapi.ClusterConfiguration) string {\n\t// Etcd uses default image repository by default\n\tetcdImageRepository := cfg.ImageRepository\n\t// unless an override is specified\n\tif cfg.Etcd.Local != nil \u0026\u0026 cfg.Etcd.Local.ImageRepository != \"\" {\n\t\tetcdImageRepository = cfg.Etcd.Local.ImageRepository\n\t}\n\t// Etcd uses an imageTag that corresponds to the etcd version matching the Kubernetes version\n\tetcdImageTag := constants.DefaultEtcdVersion\n\tetcdVersion, warning, err := constants.EtcdSupportedVersion(constants.SupportedEtcdVersion, cfg.KubernetesVersion)\n\tif err == nil {\n\t\tetcdImageTag = etcdVersion.String()\n\t}\n\tif warning != nil {\n\t\tklog.Warningln(warning)\n\t}\n\t// unless an override is specified\n\tif cfg.Etcd.Local != nil \u0026\u0026 cfg.Etcd.Local.ImageTag != \"\" {\n\t\tetcdImageTag = cfg.Etcd.Local.ImageTag\n\t}\n\treturn GetGenericImage(etcdImageRepository, constants.Etcd, etcdImageTag)\n}","line":{"from":65,"to":87}} {"id":100000900,"name":"GetControlPlaneImages","signature":"func GetControlPlaneImages(cfg *kubeadmapi.ClusterConfiguration) []string","file":"cmd/kubeadm/app/images/images.go","code":"// GetControlPlaneImages returns a list of container images kubeadm expects to use on a control plane node\nfunc GetControlPlaneImages(cfg *kubeadmapi.ClusterConfiguration) []string {\n\timages := make([]string, 0)\n\n\t// start with core kubernetes images\n\timages = append(images, GetKubernetesImage(constants.KubeAPIServer, cfg))\n\timages = append(images, GetKubernetesImage(constants.KubeControllerManager, cfg))\n\timages = append(images, GetKubernetesImage(constants.KubeScheduler, cfg))\n\timages = append(images, GetKubernetesImage(constants.KubeProxy, cfg))\n\n\t// pause is not available on the ci image repository so use the default image repository.\n\timages = append(images, GetPauseImage(cfg))\n\n\t// if etcd is not external then add the image as it will be required\n\tif cfg.Etcd.Local != nil {\n\t\timages = append(images, GetEtcdImage(cfg))\n\t}\n\n\t// Append the appropriate DNS images\n\timages = append(images, GetDNSImage(cfg))\n\n\treturn images\n}","line":{"from":89,"to":111}} {"id":100000901,"name":"GetPauseImage","signature":"func GetPauseImage(cfg *kubeadmapi.ClusterConfiguration) string","file":"cmd/kubeadm/app/images/images.go","code":"// GetPauseImage returns the image for the \"pause\" container\nfunc GetPauseImage(cfg *kubeadmapi.ClusterConfiguration) string {\n\treturn GetGenericImage(cfg.ImageRepository, \"pause\", constants.PauseVersion)\n}","line":{"from":113,"to":116}} {"id":100000902,"name":"Run","signature":"func Run() error","file":"cmd/kubeadm/app/kubeadm.go","code":"// Run creates and executes new kubeadm command\nfunc Run() error {\n\tklog.InitFlags(nil)\n\tpflag.CommandLine.SetNormalizeFunc(cliflag.WordSepNormalizeFunc)\n\tpflag.CommandLine.AddGoFlagSet(flag.CommandLine)\n\n\tpflag.Set(\"logtostderr\", \"true\")\n\t// We do not want these flags to show up in --help\n\t// These MarkHidden calls must be after the lines above\n\tpflag.CommandLine.MarkHidden(\"version\")\n\tpflag.CommandLine.MarkHidden(\"log-flush-frequency\")\n\tpflag.CommandLine.MarkHidden(\"alsologtostderr\")\n\tpflag.CommandLine.MarkHidden(\"log-backtrace-at\")\n\tpflag.CommandLine.MarkHidden(\"log-dir\")\n\tpflag.CommandLine.MarkHidden(\"logtostderr\")\n\tpflag.CommandLine.MarkHidden(\"stderrthreshold\")\n\tpflag.CommandLine.MarkHidden(\"vmodule\")\n\n\tcmd := cmd.NewKubeadmCommand(os.Stdin, os.Stdout, os.Stderr)\n\treturn cmd.Execute()\n}","line":{"from":31,"to":51}} {"id":100000903,"name":"DeployedDNSAddon","signature":"func DeployedDNSAddon(client clientset.Interface) (string, error)","file":"cmd/kubeadm/app/phases/addons/dns/dns.go","code":"// DeployedDNSAddon returns the type of DNS addon currently deployed\nfunc DeployedDNSAddon(client clientset.Interface) (string, error) {\n\tdeploymentsClient := client.AppsV1().Deployments(metav1.NamespaceSystem)\n\tdeployments, err := deploymentsClient.List(context.TODO(), metav1.ListOptions{LabelSelector: \"k8s-app=kube-dns\"})\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"couldn't retrieve DNS addon deployments\")\n\t}\n\n\tswitch len(deployments.Items) {\n\tcase 0:\n\t\treturn \"\", nil\n\tcase 1:\n\t\taddonImage := deployments.Items[0].Spec.Template.Spec.Containers[0].Image\n\t\taddonImageParts := strings.Split(addonImage, \":\")\n\t\taddonVersion := addonImageParts[len(addonImageParts)-1]\n\t\treturn addonVersion, nil\n\tdefault:\n\t\treturn \"\", errors.Errorf(\"multiple DNS addon deployments found: %v\", deployments.Items)\n\t}\n}","line":{"from":51,"to":70}} {"id":100000904,"name":"deployedDNSReplicas","signature":"func deployedDNSReplicas(client clientset.Interface, replicas int32) (*int32, error)","file":"cmd/kubeadm/app/phases/addons/dns/dns.go","code":"// deployedDNSReplicas returns the replica count for the current DNS deployment\nfunc deployedDNSReplicas(client clientset.Interface, replicas int32) (*int32, error) {\n\tdeploymentsClient := client.AppsV1().Deployments(metav1.NamespaceSystem)\n\tdeployments, err := deploymentsClient.List(context.TODO(), metav1.ListOptions{LabelSelector: \"k8s-app=kube-dns\"})\n\tif err != nil {\n\t\treturn \u0026replicas, errors.Wrap(err, \"couldn't retrieve DNS addon deployments\")\n\t}\n\tswitch len(deployments.Items) {\n\tcase 0:\n\t\treturn \u0026replicas, nil\n\tcase 1:\n\t\treturn deployments.Items[0].Spec.Replicas, nil\n\tdefault:\n\t\treturn \u0026replicas, errors.Errorf(\"multiple DNS addon deployments found: %v\", deployments.Items)\n\t}\n}","line":{"from":72,"to":87}} {"id":100000905,"name":"EnsureDNSAddon","signature":"func EnsureDNSAddon(cfg *kubeadmapi.ClusterConfiguration, client clientset.Interface, out io.Writer, printManifest bool) error","file":"cmd/kubeadm/app/phases/addons/dns/dns.go","code":"// EnsureDNSAddon creates the CoreDNS addon\nfunc EnsureDNSAddon(cfg *kubeadmapi.ClusterConfiguration, client clientset.Interface, out io.Writer, printManifest bool) error {\n\tvar replicas *int32\n\tvar err error\n\tif !printManifest {\n\t\treplicas, err = deployedDNSReplicas(client, coreDNSReplicas)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tvar defaultReplicas int32 = coreDNSReplicas\n\t\treplicas = \u0026defaultReplicas\n\t}\n\treturn coreDNSAddon(cfg, client, replicas, out, printManifest)\n}","line":{"from":89,"to":103}} {"id":100000906,"name":"coreDNSAddon","signature":"func coreDNSAddon(cfg *kubeadmapi.ClusterConfiguration, client clientset.Interface, replicas *int32, out io.Writer, printManifest bool) error","file":"cmd/kubeadm/app/phases/addons/dns/dns.go","code":"func coreDNSAddon(cfg *kubeadmapi.ClusterConfiguration, client clientset.Interface, replicas *int32, out io.Writer, printManifest bool) error {\n\t// Get the YAML manifest\n\tcoreDNSDeploymentBytes, err := kubeadmutil.ParseTemplate(CoreDNSDeployment, struct {\n\t\tDeploymentName, Image, ControlPlaneTaintKey string\n\t\tReplicas *int32\n\t}{\n\t\tDeploymentName: kubeadmconstants.CoreDNSDeploymentName,\n\t\tImage: images.GetDNSImage(cfg),\n\t\tControlPlaneTaintKey: kubeadmconstants.LabelNodeRoleControlPlane,\n\t\tReplicas: replicas,\n\t})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error when parsing CoreDNS deployment template\")\n\t}\n\n\t// Get the config file for CoreDNS\n\tcoreDNSConfigMapBytes, err := kubeadmutil.ParseTemplate(CoreDNSConfigMap, struct{ DNSDomain, UpstreamNameserver, StubDomain string }{\n\t\tDNSDomain: cfg.Networking.DNSDomain,\n\t})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error when parsing CoreDNS configMap template\")\n\t}\n\n\tdnsip, err := kubeadmconstants.GetDNSIP(cfg.Networking.ServiceSubnet)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcoreDNSServiceBytes, err := kubeadmutil.ParseTemplate(CoreDNSService, struct{ DNSIP string }{\n\t\tDNSIP: dnsip.String(),\n\t})\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error when parsing CoreDNS service template\")\n\t}\n\n\tif printManifest {\n\t\tfmt.Fprint(out, \"---\")\n\t\tfmt.Fprintf(out, \"%s\", coreDNSDeploymentBytes)\n\t\tfmt.Fprint(out, \"---\")\n\t\tfmt.Fprintf(out, \"%s\", coreDNSConfigMapBytes)\n\t\tfmt.Fprint(out, \"---\")\n\t\tfmt.Fprintf(out, \"%s\", coreDNSServiceBytes)\n\t\tfmt.Fprint(out, \"---\")\n\t\tfmt.Fprintf(out, \"%s\", []byte(CoreDNSClusterRole))\n\t\tfmt.Fprint(out, \"---\")\n\t\tfmt.Fprintf(out, \"%s\", []byte(CoreDNSClusterRoleBinding))\n\t\tfmt.Fprint(out, \"---\")\n\t\tfmt.Fprintf(out, \"%s\", []byte(CoreDNSServiceAccount))\n\t\treturn nil\n\t}\n\n\tif err := createCoreDNSAddon(coreDNSDeploymentBytes, coreDNSServiceBytes, coreDNSConfigMapBytes, client); err != nil {\n\t\treturn err\n\t}\n\tfmt.Fprintln(out, \"[addons] Applied essential addon: CoreDNS\")\n\treturn nil\n}","line":{"from":105,"to":162}} {"id":100000907,"name":"createCoreDNSAddon","signature":"func createCoreDNSAddon(deploymentBytes, serviceBytes, configBytes []byte, client clientset.Interface) error","file":"cmd/kubeadm/app/phases/addons/dns/dns.go","code":"func createCoreDNSAddon(deploymentBytes, serviceBytes, configBytes []byte, client clientset.Interface) error {\n\tcoreDNSConfigMap := \u0026v1.ConfigMap{}\n\tif err := kuberuntime.DecodeInto(clientsetscheme.Codecs.UniversalDecoder(), configBytes, coreDNSConfigMap); err != nil {\n\t\treturn errors.Wrapf(err, \"%s ConfigMap\", unableToDecodeCoreDNS)\n\t}\n\n\t// Create the ConfigMap for CoreDNS or update/migrate it in case it already exists\n\t_, corefile, currentInstalledCoreDNSVersion, err := GetCoreDNSInfo(client)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"unable to fetch CoreDNS current installed version and ConfigMap.\")\n\t}\n\n\tcorefileMigrationRequired, err := isCoreDNSConfigMapMigrationRequired(corefile, currentInstalledCoreDNSVersion)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Assume that migration is always possible, rely on migrateCoreDNSCorefile() to fail if not.\n\tcanMigrateCorefile := true\n\n\tif corefile == \"\" || migration.Default(\"\", corefile) {\n\t\t// If the Corefile is empty or default, the latest default Corefile will be applied\n\t\tif err := apiclient.CreateOrUpdateConfigMap(client, coreDNSConfigMap); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else if corefileMigrationRequired {\n\t\t// If migration is required, try and migrate the Corefile\n\t\tif err := migrateCoreDNSCorefile(client, coreDNSConfigMap, corefile, currentInstalledCoreDNSVersion); err != nil {\n\t\t\t// Errors in Corefile Migration is verified during preflight checks. This part will be executed when a user has chosen\n\t\t\t// to ignore preflight check errors.\n\t\t\tcanMigrateCorefile = false\n\t\t\tklog.Warningf(\"the CoreDNS Configuration was not migrated: %v. The existing CoreDNS Corefile configuration has been retained.\", err)\n\t\t\tif err := apiclient.CreateOrRetainConfigMap(client, coreDNSConfigMap, kubeadmconstants.CoreDNSConfigMap); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// If the Corefile is modified and doesn't require any migration, it'll be retained for the benefit of the user\n\t\tif err := apiclient.CreateOrRetainConfigMap(client, coreDNSConfigMap, kubeadmconstants.CoreDNSConfigMap); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tcoreDNSClusterRoles := \u0026rbac.ClusterRole{}\n\tif err := kuberuntime.DecodeInto(clientsetscheme.Codecs.UniversalDecoder(), []byte(CoreDNSClusterRole), coreDNSClusterRoles); err != nil {\n\t\treturn errors.Wrapf(err, \"%s ClusterRole\", unableToDecodeCoreDNS)\n\t}\n\n\t// Create the Clusterroles for CoreDNS or update it in case it already exists\n\tif err := apiclient.CreateOrUpdateClusterRole(client, coreDNSClusterRoles); err != nil {\n\t\treturn err\n\t}\n\n\tcoreDNSClusterRolesBinding := \u0026rbac.ClusterRoleBinding{}\n\tif err := kuberuntime.DecodeInto(clientsetscheme.Codecs.UniversalDecoder(), []byte(CoreDNSClusterRoleBinding), coreDNSClusterRolesBinding); err != nil {\n\t\treturn errors.Wrapf(err, \"%s ClusterRoleBinding\", unableToDecodeCoreDNS)\n\t}\n\n\t// Create the Clusterrolebindings for CoreDNS or update it in case it already exists\n\tif err := apiclient.CreateOrUpdateClusterRoleBinding(client, coreDNSClusterRolesBinding); err != nil {\n\t\treturn err\n\t}\n\n\tcoreDNSServiceAccount := \u0026v1.ServiceAccount{}\n\tif err := kuberuntime.DecodeInto(clientsetscheme.Codecs.UniversalDecoder(), []byte(CoreDNSServiceAccount), coreDNSServiceAccount); err != nil {\n\t\treturn errors.Wrapf(err, \"%s ServiceAccount\", unableToDecodeCoreDNS)\n\t}\n\n\t// Create the ConfigMap for CoreDNS or update it in case it already exists\n\tif err := apiclient.CreateOrUpdateServiceAccount(client, coreDNSServiceAccount); err != nil {\n\t\treturn err\n\t}\n\n\tcoreDNSDeployment := \u0026apps.Deployment{}\n\tif err := kuberuntime.DecodeInto(clientsetscheme.Codecs.UniversalDecoder(), deploymentBytes, coreDNSDeployment); err != nil {\n\t\treturn errors.Wrapf(err, \"%s Deployment\", unableToDecodeCoreDNS)\n\t}\n\n\t// Create the deployment for CoreDNS or retain it in case the CoreDNS migration has failed during upgrade\n\tif !canMigrateCorefile {\n\t\tif err := apiclient.CreateOrRetainDeployment(client, coreDNSDeployment, kubeadmconstants.CoreDNSDeploymentName); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t// Create the Deployment for CoreDNS or update it in case it already exists\n\t\tif err := apiclient.CreateOrUpdateDeployment(client, coreDNSDeployment); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tcoreDNSService := \u0026v1.Service{}\n\treturn createDNSService(coreDNSService, serviceBytes, client)\n}","line":{"from":164,"to":256}} {"id":100000908,"name":"createDNSService","signature":"func createDNSService(dnsService *v1.Service, serviceBytes []byte, client clientset.Interface) error","file":"cmd/kubeadm/app/phases/addons/dns/dns.go","code":"func createDNSService(dnsService *v1.Service, serviceBytes []byte, client clientset.Interface) error {\n\tif err := kuberuntime.DecodeInto(clientsetscheme.Codecs.UniversalDecoder(), serviceBytes, dnsService); err != nil {\n\t\treturn errors.Wrap(err, \"unable to decode the DNS service\")\n\t}\n\n\t// Can't use a generic apiclient helper func here as we have to tolerate more than AlreadyExists.\n\tif _, err := client.CoreV1().Services(metav1.NamespaceSystem).Create(context.TODO(), dnsService, metav1.CreateOptions{}); err != nil {\n\t\t// Ignore if the Service is invalid with this error message:\n\t\t// \tService \"kube-dns\" is invalid: spec.clusterIP: Invalid value: \"10.96.0.10\": provided IP is already allocated\n\n\t\tif !apierrors.IsAlreadyExists(err) \u0026\u0026 !apierrors.IsInvalid(err) {\n\t\t\treturn errors.Wrap(err, \"unable to create a new DNS service\")\n\t\t}\n\n\t\tif _, err := client.CoreV1().Services(metav1.NamespaceSystem).Update(context.TODO(), dnsService, metav1.UpdateOptions{}); err != nil {\n\t\t\treturn errors.Wrap(err, \"unable to create/update the DNS service\")\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":258,"to":277}} {"id":100000909,"name":"isCoreDNSConfigMapMigrationRequired","signature":"func isCoreDNSConfigMapMigrationRequired(corefile, currentInstalledCoreDNSVersion string) (bool, error)","file":"cmd/kubeadm/app/phases/addons/dns/dns.go","code":"// isCoreDNSConfigMapMigrationRequired checks if a migration of the CoreDNS ConfigMap is required.\nfunc isCoreDNSConfigMapMigrationRequired(corefile, currentInstalledCoreDNSVersion string) (bool, error) {\n\tvar isMigrationRequired bool\n\n\t// Current installed version is expected to be empty for init\n\tif currentInstalledCoreDNSVersion == \"\" {\n\t\treturn isMigrationRequired, nil\n\t}\n\tcurrentInstalledCoreDNSVersion = strings.TrimLeft(currentInstalledCoreDNSVersion, \"v\")\n\ttargetCoreDNSVersion := strings.TrimLeft(kubeadmconstants.CoreDNSVersion, \"v\")\n\tif currentInstalledCoreDNSVersion == targetCoreDNSVersion {\n\t\treturn isMigrationRequired, nil\n\t}\n\tdeprecated, err := migration.Deprecated(currentInstalledCoreDNSVersion, targetCoreDNSVersion, corefile)\n\tif err != nil {\n\t\treturn isMigrationRequired, errors.Wrap(err, \"unable to get list of changes to the configuration.\")\n\t}\n\n\t// Check if there are any plugins/options which needs to be removed or is a new default\n\tfor _, dep := range deprecated {\n\t\tif dep.Severity == \"removed\" || dep.Severity == \"newdefault\" {\n\t\t\tisMigrationRequired = true\n\t\t}\n\t}\n\n\treturn isMigrationRequired, nil\n}","line":{"from":279,"to":305}} {"id":100000910,"name":"migrateCoreDNSCorefile","signature":"func migrateCoreDNSCorefile(client clientset.Interface, cm *v1.ConfigMap, corefile, currentInstalledCoreDNSVersion string) error","file":"cmd/kubeadm/app/phases/addons/dns/dns.go","code":"func migrateCoreDNSCorefile(client clientset.Interface, cm *v1.ConfigMap, corefile, currentInstalledCoreDNSVersion string) error {\n\t// Since the current configuration present is not the default version, try and migrate it.\n\tupdatedCorefile, err := migration.Migrate(currentInstalledCoreDNSVersion, strings.TrimLeft(kubeadmconstants.CoreDNSVersion, \"v\"), corefile, false)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"unable to migrate CoreDNS ConfigMap\")\n\t}\n\n\t// Take a copy of the existing Corefile data as `Corefile-backup` and update the ConfigMap\n\tif _, err := client.CoreV1().ConfigMaps(cm.ObjectMeta.Namespace).Update(context.TODO(), \u0026v1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: kubeadmconstants.CoreDNSConfigMap,\n\t\t\tNamespace: metav1.NamespaceSystem,\n\t\t},\n\t\tData: map[string]string{\n\t\t\t\"Corefile\": updatedCorefile,\n\t\t\t\"Corefile-backup\": corefile,\n\t\t},\n\t}, metav1.UpdateOptions{}); err != nil {\n\t\treturn errors.Wrap(err, \"unable to update the CoreDNS ConfigMap\")\n\t}\n\n\t// Point the CoreDNS deployment to the `Corefile-backup` data.\n\tif err := setCorefile(client, \"Corefile-backup\"); err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"[addons] Migrating CoreDNS Corefile\")\n\tchanges, err := migration.Deprecated(currentInstalledCoreDNSVersion, strings.TrimLeft(kubeadmconstants.CoreDNSVersion, \"v\"), corefile)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"unable to get list of changes to the configuration.\")\n\t}\n\t// show the migration changes\n\tklog.V(2).Infof(\"the CoreDNS configuration has been migrated and applied: %v.\", updatedCorefile)\n\tklog.V(2).Infoln(\"the old migration has been saved in the CoreDNS ConfigMap under the name [Corefile-backup]\")\n\tklog.V(2).Infoln(\"The changes in the new CoreDNS Configuration are as follows:\")\n\tfor _, change := range changes {\n\t\tklog.V(2).Infof(\"%v\", change.ToString())\n\t}\n\treturn nil\n}","line":{"from":307,"to":346}} {"id":100000911,"name":"GetCoreDNSInfo","signature":"func GetCoreDNSInfo(client clientset.Interface) (*v1.ConfigMap, string, string, error)","file":"cmd/kubeadm/app/phases/addons/dns/dns.go","code":"// GetCoreDNSInfo gets the current CoreDNS installed and the current Corefile Configuration of CoreDNS.\nfunc GetCoreDNSInfo(client clientset.Interface) (*v1.ConfigMap, string, string, error) {\n\tcoreDNSConfigMap, err := client.CoreV1().ConfigMaps(metav1.NamespaceSystem).Get(context.TODO(), kubeadmconstants.CoreDNSConfigMap, metav1.GetOptions{})\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\treturn nil, \"\", \"\", nil\n\t\t}\n\t\treturn nil, \"\", \"\", err\n\t}\n\tcorefile, ok := coreDNSConfigMap.Data[\"Corefile\"]\n\tif !ok {\n\t\treturn nil, \"\", \"\", errors.New(\"unable to find the CoreDNS Corefile data\")\n\t}\n\n\tcurrentCoreDNSversion, err := DeployedDNSAddon(client)\n\tif err != nil {\n\t\treturn nil, \"\", \"\", err\n\t}\n\n\treturn coreDNSConfigMap, corefile, currentCoreDNSversion, nil\n}","line":{"from":348,"to":368}} {"id":100000912,"name":"setCorefile","signature":"func setCorefile(client clientset.Interface, coreDNSCorefileName string) error","file":"cmd/kubeadm/app/phases/addons/dns/dns.go","code":"func setCorefile(client clientset.Interface, coreDNSCorefileName string) error {\n\tdnsDeployment, err := client.AppsV1().Deployments(metav1.NamespaceSystem).Get(context.TODO(), kubeadmconstants.CoreDNSDeploymentName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\tpatch := fmt.Sprintf(`{\"spec\":{\"template\":{\"spec\":{\"volumes\":[{\"name\": \"config-volume\", \"configMap\":{\"name\": \"coredns\", \"items\":[{\"key\": \"%s\", \"path\": \"Corefile\"}]}}]}}}}`, coreDNSCorefileName)\n\n\tif _, err := client.AppsV1().Deployments(dnsDeployment.ObjectMeta.Namespace).Patch(context.TODO(), dnsDeployment.Name, types.StrategicMergePatchType, []byte(patch), metav1.PatchOptions{}); err != nil {\n\t\treturn errors.Wrap(err, \"unable to patch the CoreDNS deployment\")\n\t}\n\treturn nil\n}","line":{"from":370,"to":381}} {"id":100000913,"name":"EnsureProxyAddon","signature":"func EnsureProxyAddon(cfg *kubeadmapi.ClusterConfiguration, localEndpoint *kubeadmapi.APIEndpoint, client clientset.Interface, out io.Writer, printManifest bool) error","file":"cmd/kubeadm/app/phases/addons/proxy/proxy.go","code":"// EnsureProxyAddon creates the kube-proxy addons\nfunc EnsureProxyAddon(cfg *kubeadmapi.ClusterConfiguration, localEndpoint *kubeadmapi.APIEndpoint, client clientset.Interface, out io.Writer, printManifest bool) error {\n\tcmByte, err := createKubeProxyConfigMap(cfg, localEndpoint, client, printManifest)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdsByte, err := createKubeProxyAddon(cfg, client, printManifest)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := printOrCreateKubeProxyObjects(cmByte, dsByte, client, out, printManifest); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":51,"to":68}} {"id":100000914,"name":"printOrCreateKubeProxyObjects","signature":"func printOrCreateKubeProxyObjects(cmByte []byte, dsByte []byte, client clientset.Interface, out io.Writer, printManifest bool) error","file":"cmd/kubeadm/app/phases/addons/proxy/proxy.go","code":"// Create SA, RBACRules or print manifests of them to out if printManifest is true\nfunc printOrCreateKubeProxyObjects(cmByte []byte, dsByte []byte, client clientset.Interface, out io.Writer, printManifest bool) error {\n\tvar saBytes, crbBytes, roleBytes, roleBindingBytes []byte\n\tvar err error\n\n\tsa := \u0026v1.ServiceAccount{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: KubeProxyServiceAccountName,\n\t\t\tNamespace: metav1.NamespaceSystem,\n\t\t},\n\t}\n\n\tcrb := \u0026rbac.ClusterRoleBinding{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: constants.KubeProxyClusterRoleBindingName,\n\t\t},\n\t\tRoleRef: rbac.RoleRef{\n\t\t\tAPIGroup: rbac.GroupName,\n\t\t\tKind: \"ClusterRole\",\n\t\t\tName: constants.KubeProxyClusterRoleName,\n\t\t},\n\t\tSubjects: []rbac.Subject{\n\t\t\t{\n\t\t\t\tKind: rbac.ServiceAccountKind,\n\t\t\t\tName: KubeProxyServiceAccountName,\n\t\t\t\tNamespace: metav1.NamespaceSystem,\n\t\t\t},\n\t\t},\n\t}\n\n\trole := \u0026rbac.Role{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: KubeProxyConfigMapRoleName,\n\t\t\tNamespace: metav1.NamespaceSystem,\n\t\t},\n\t\tRules: []rbac.PolicyRule{\n\t\t\t{\n\t\t\t\tVerbs: []string{\"get\"},\n\t\t\t\tAPIGroups: []string{\"\"},\n\t\t\t\tResources: []string{\"configmaps\"},\n\t\t\t\tResourceNames: []string{constants.KubeProxyConfigMap},\n\t\t\t},\n\t\t},\n\t}\n\n\trb := \u0026rbac.RoleBinding{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: KubeProxyConfigMapRoleName,\n\t\t\tNamespace: metav1.NamespaceSystem,\n\t\t},\n\t\tRoleRef: rbac.RoleRef{\n\t\t\tAPIGroup: rbac.GroupName,\n\t\t\tKind: \"Role\",\n\t\t\tName: KubeProxyConfigMapRoleName,\n\t\t},\n\t\tSubjects: []rbac.Subject{\n\t\t\t{\n\t\t\t\tKind: rbac.GroupKind,\n\t\t\t\tName: constants.NodeBootstrapTokenAuthGroup,\n\t\t\t},\n\t\t},\n\t}\n\n\t// Create the objects if printManifest is false\n\tif !printManifest {\n\t\tif err := apiclient.CreateOrUpdateServiceAccount(client, sa); err != nil {\n\t\t\treturn errors.Wrap(err, \"error when creating kube-proxy service account\")\n\t\t}\n\n\t\tif err := apiclient.CreateOrUpdateClusterRoleBinding(client, crb); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := apiclient.CreateOrUpdateRole(client, role); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := apiclient.CreateOrUpdateRoleBinding(client, rb); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Fprintln(out, \"[addons] Applied essential addon: kube-proxy\")\n\n\t\treturn nil\n\n\t}\n\n\tgv := schema.GroupVersion{Group: \"\", Version: \"v1\"}\n\tif saBytes, err = kubeadmutil.MarshalToYaml(sa, gv); err != nil {\n\t\treturn err\n\t}\n\n\tgv = schema.GroupVersion{Group: \"rbac.authorization.k8s.io\", Version: \"v1\"}\n\tif crbBytes, err = kubeadmutil.MarshalToYaml(crb, gv); err != nil {\n\t\treturn err\n\t}\n\n\tif roleBytes, err = kubeadmutil.MarshalToYaml(role, gv); err != nil {\n\t\treturn err\n\t}\n\n\tif roleBindingBytes, err = kubeadmutil.MarshalToYaml(rb, gv); err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Fprintln(out, \"---\")\n\tfmt.Fprintf(out, \"%s\", saBytes)\n\tfmt.Fprintln(out, \"---\")\n\tfmt.Fprintf(out, \"%s\", crbBytes)\n\tfmt.Fprintln(out, \"---\")\n\tfmt.Fprintf(out, \"%s\", roleBytes)\n\tfmt.Fprintln(out, \"---\")\n\tfmt.Fprintf(out, \"%s\", roleBindingBytes)\n\tfmt.Fprint(out, \"---\")\n\tfmt.Fprintf(out, \"%s\", cmByte)\n\tfmt.Fprint(out, \"---\")\n\tfmt.Fprintf(out, \"%s\", dsByte)\n\n\treturn nil\n}","line":{"from":70,"to":189}} {"id":100000915,"name":"createKubeProxyConfigMap","signature":"func createKubeProxyConfigMap(cfg *kubeadmapi.ClusterConfiguration, localEndpoint *kubeadmapi.APIEndpoint, client clientset.Interface, printManifest bool) ([]byte, error)","file":"cmd/kubeadm/app/phases/addons/proxy/proxy.go","code":"func createKubeProxyConfigMap(cfg *kubeadmapi.ClusterConfiguration, localEndpoint *kubeadmapi.APIEndpoint, client clientset.Interface, printManifest bool) ([]byte, error) {\n\t// Generate ControlPlane Enpoint kubeconfig file\n\tcontrolPlaneEndpoint, err := kubeadmutil.GetControlPlaneEndpoint(cfg.ControlPlaneEndpoint, localEndpoint)\n\tif err != nil {\n\t\treturn []byte(\"\"), err\n\t}\n\n\tkubeProxyCfg, ok := cfg.ComponentConfigs[componentconfigs.KubeProxyGroup]\n\tif !ok {\n\t\treturn []byte(\"\"), errors.New(\"no kube-proxy component config found in the active component config set\")\n\t}\n\n\tproxyBytes, err := kubeProxyCfg.Marshal()\n\tif err != nil {\n\t\treturn []byte(\"\"), errors.Wrap(err, \"error when marshaling\")\n\t}\n\tvar prefixBytes bytes.Buffer\n\tapiclient.PrintBytesWithLinePrefix(\u0026prefixBytes, proxyBytes, \" \")\n\tconfigMapBytes, err := kubeadmutil.ParseTemplate(KubeProxyConfigMap19,\n\t\tstruct {\n\t\t\tControlPlaneEndpoint string\n\t\t\tProxyConfig string\n\t\t\tProxyConfigMap string\n\t\t\tProxyConfigMapKey string\n\t\t}{\n\t\t\tControlPlaneEndpoint: controlPlaneEndpoint,\n\t\t\tProxyConfig: prefixBytes.String(),\n\t\t\tProxyConfigMap: constants.KubeProxyConfigMap,\n\t\t\tProxyConfigMapKey: constants.KubeProxyConfigMapKey,\n\t\t})\n\tif err != nil {\n\t\treturn []byte(\"\"), errors.Wrap(err, \"error when parsing kube-proxy configmap template\")\n\t}\n\n\tif printManifest {\n\t\treturn configMapBytes, nil\n\t}\n\n\tkubeproxyConfigMap := \u0026v1.ConfigMap{}\n\tif err := kuberuntime.DecodeInto(clientsetscheme.Codecs.UniversalDecoder(), configMapBytes, kubeproxyConfigMap); err != nil {\n\t\treturn []byte(\"\"), errors.Wrap(err, \"unable to decode kube-proxy configmap\")\n\t}\n\n\tif !kubeProxyCfg.IsUserSupplied() {\n\t\tcomponentconfigs.SignConfigMap(kubeproxyConfigMap)\n\t}\n\n\t// Create the ConfigMap for kube-proxy or update it in case it already exists\n\treturn []byte(\"\"), apiclient.CreateOrUpdateConfigMap(client, kubeproxyConfigMap)\n}","line":{"from":191,"to":240}} {"id":100000916,"name":"createKubeProxyAddon","signature":"func createKubeProxyAddon(cfg *kubeadmapi.ClusterConfiguration, client clientset.Interface, printManifest bool) ([]byte, error)","file":"cmd/kubeadm/app/phases/addons/proxy/proxy.go","code":"func createKubeProxyAddon(cfg *kubeadmapi.ClusterConfiguration, client clientset.Interface, printManifest bool) ([]byte, error) {\n\tdaemonSetbytes, err := kubeadmutil.ParseTemplate(KubeProxyDaemonSet19, struct{ Image, ProxyConfigMap, ProxyConfigMapKey string }{\n\t\tImage: images.GetKubernetesImage(constants.KubeProxy, cfg),\n\t\tProxyConfigMap: constants.KubeProxyConfigMap,\n\t\tProxyConfigMapKey: constants.KubeProxyConfigMapKey,\n\t})\n\tif err != nil {\n\t\treturn []byte(\"\"), errors.Wrap(err, \"error when parsing kube-proxy daemonset template\")\n\t}\n\n\tif printManifest {\n\t\treturn daemonSetbytes, nil\n\t}\n\n\tkubeproxyDaemonSet := \u0026apps.DaemonSet{}\n\tif err := kuberuntime.DecodeInto(clientsetscheme.Codecs.UniversalDecoder(), daemonSetbytes, kubeproxyDaemonSet); err != nil {\n\t\treturn []byte(\"\"), errors.Wrap(err, \"unable to decode kube-proxy daemonset\")\n\t}\n\t// Propagate the http/https proxy host environment variables to the container\n\tenv := \u0026kubeproxyDaemonSet.Spec.Template.Spec.Containers[0].Env\n\t*env = append(*env, kubeadmutil.GetProxyEnvVars()...)\n\n\t// Create the DaemonSet for kube-proxy or update it in case it already exists\n\treturn []byte(\"\"), apiclient.CreateOrUpdateDaemonSet(client, kubeproxyDaemonSet)\n}","line":{"from":242,"to":266}} {"id":100000917,"name":"CreateBootstrapConfigMapIfNotExists","signature":"func CreateBootstrapConfigMapIfNotExists(client clientset.Interface, file string) error","file":"cmd/kubeadm/app/phases/bootstraptoken/clusterinfo/clusterinfo.go","code":"// CreateBootstrapConfigMapIfNotExists creates the kube-public ConfigMap if it doesn't exist already\nfunc CreateBootstrapConfigMapIfNotExists(client clientset.Interface, file string) error {\n\n\tfmt.Printf(\"[bootstrap-token] Creating the %q ConfigMap in the %q namespace\\n\", bootstrapapi.ConfigMapClusterInfo, metav1.NamespacePublic)\n\n\tklog.V(1).Infoln(\"[bootstrap-token] loading admin kubeconfig\")\n\tadminConfig, err := clientcmd.LoadFromFile(file)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to load admin kubeconfig\")\n\t}\n\tif err = clientcmdapi.FlattenConfig(adminConfig); err != nil {\n\t\treturn err\n\t}\n\n\tadminCluster := adminConfig.Contexts[adminConfig.CurrentContext].Cluster\n\t// Copy the cluster from admin.conf to the bootstrap kubeconfig, contains the CA cert and the server URL\n\tklog.V(1).Infoln(\"[bootstrap-token] copying the cluster from admin.conf to the bootstrap kubeconfig\")\n\tbootstrapConfig := \u0026clientcmdapi.Config{\n\t\tClusters: map[string]*clientcmdapi.Cluster{\n\t\t\t\"\": adminConfig.Clusters[adminCluster],\n\t\t},\n\t}\n\tbootstrapBytes, err := clientcmd.Write(*bootstrapConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Create or update the ConfigMap in the kube-public namespace\n\tklog.V(1).Infoln(\"[bootstrap-token] creating/updating ConfigMap in kube-public namespace\")\n\treturn apiclient.CreateOrUpdateConfigMap(client, \u0026v1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: bootstrapapi.ConfigMapClusterInfo,\n\t\t\tNamespace: metav1.NamespacePublic,\n\t\t},\n\t\tData: map[string]string{\n\t\t\tbootstrapapi.KubeConfigKey: string(bootstrapBytes),\n\t\t},\n\t})\n}","line":{"from":42,"to":80}} {"id":100000918,"name":"CreateClusterInfoRBACRules","signature":"func CreateClusterInfoRBACRules(client clientset.Interface) error","file":"cmd/kubeadm/app/phases/bootstraptoken/clusterinfo/clusterinfo.go","code":"// CreateClusterInfoRBACRules creates the RBAC rules for exposing the cluster-info ConfigMap in the kube-public namespace to unauthenticated users\nfunc CreateClusterInfoRBACRules(client clientset.Interface) error {\n\tklog.V(1).Infoln(\"creating the RBAC rules for exposing the cluster-info ConfigMap in the kube-public namespace\")\n\terr := apiclient.CreateOrUpdateRole(client, \u0026rbac.Role{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: BootstrapSignerClusterRoleName,\n\t\t\tNamespace: metav1.NamespacePublic,\n\t\t},\n\t\tRules: []rbac.PolicyRule{\n\t\t\t{\n\t\t\t\tVerbs: []string{\"get\"},\n\t\t\t\tAPIGroups: []string{\"\"},\n\t\t\t\tResources: []string{\"configmaps\"},\n\t\t\t\tResourceNames: []string{bootstrapapi.ConfigMapClusterInfo},\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn apiclient.CreateOrUpdateRoleBinding(client, \u0026rbac.RoleBinding{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: BootstrapSignerClusterRoleName,\n\t\t\tNamespace: metav1.NamespacePublic,\n\t\t},\n\t\tRoleRef: rbac.RoleRef{\n\t\t\tAPIGroup: rbac.GroupName,\n\t\t\tKind: \"Role\",\n\t\t\tName: BootstrapSignerClusterRoleName,\n\t\t},\n\t\tSubjects: []rbac.Subject{\n\t\t\t{\n\t\t\t\tKind: rbac.UserKind,\n\t\t\t\tName: user.Anonymous,\n\t\t\t},\n\t\t},\n\t})\n}","line":{"from":82,"to":120}} {"id":100000919,"name":"AllowBootstrapTokensToPostCSRs","signature":"func AllowBootstrapTokensToPostCSRs(client clientset.Interface) error","file":"cmd/kubeadm/app/phases/bootstraptoken/node/tlsbootstrap.go","code":"// AllowBootstrapTokensToPostCSRs creates RBAC rules in a way the makes Node Bootstrap Tokens able to post CSRs\nfunc AllowBootstrapTokensToPostCSRs(client clientset.Interface) error {\n\tfmt.Println(\"[bootstrap-token] Configured RBAC rules to allow Node Bootstrap tokens to post CSRs in order for nodes to get long term certificate credentials\")\n\n\treturn apiclient.CreateOrUpdateClusterRoleBinding(client, \u0026rbac.ClusterRoleBinding{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: constants.NodeKubeletBootstrap,\n\t\t},\n\t\tRoleRef: rbac.RoleRef{\n\t\t\tAPIGroup: rbac.GroupName,\n\t\t\tKind: \"ClusterRole\",\n\t\t\tName: constants.NodeBootstrapperClusterRoleName,\n\t\t},\n\t\tSubjects: []rbac.Subject{\n\t\t\t{\n\t\t\t\tKind: rbac.GroupKind,\n\t\t\t\tName: constants.NodeBootstrapTokenAuthGroup,\n\t\t\t},\n\t\t},\n\t})\n}","line":{"from":30,"to":50}} {"id":100000920,"name":"AllowBoostrapTokensToGetNodes","signature":"func AllowBoostrapTokensToGetNodes(client clientset.Interface) error","file":"cmd/kubeadm/app/phases/bootstraptoken/node/tlsbootstrap.go","code":"// AllowBoostrapTokensToGetNodes creates RBAC rules to allow Node Bootstrap Tokens to list nodes\nfunc AllowBoostrapTokensToGetNodes(client clientset.Interface) error {\n\tfmt.Println(\"[bootstrap-token] Configured RBAC rules to allow Node Bootstrap tokens to get nodes\")\n\n\tif err := apiclient.CreateOrUpdateClusterRole(client, \u0026rbac.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: constants.GetNodesClusterRoleName,\n\t\t\tNamespace: metav1.NamespaceSystem,\n\t\t},\n\t\tRules: []rbac.PolicyRule{\n\t\t\t{\n\t\t\t\tVerbs: []string{\"get\"},\n\t\t\t\tAPIGroups: []string{\"\"},\n\t\t\t\tResources: []string{\"nodes\"},\n\t\t\t},\n\t\t},\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\treturn apiclient.CreateOrUpdateClusterRoleBinding(client, \u0026rbac.ClusterRoleBinding{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: constants.GetNodesClusterRoleName,\n\t\t\tNamespace: metav1.NamespaceSystem,\n\t\t},\n\t\tRoleRef: rbac.RoleRef{\n\t\t\tAPIGroup: rbac.GroupName,\n\t\t\tKind: \"ClusterRole\",\n\t\t\tName: constants.GetNodesClusterRoleName,\n\t\t},\n\t\tSubjects: []rbac.Subject{\n\t\t\t{\n\t\t\t\tKind: rbac.GroupKind,\n\t\t\t\tName: constants.NodeBootstrapTokenAuthGroup,\n\t\t\t},\n\t\t},\n\t})\n}","line":{"from":52,"to":89}} {"id":100000921,"name":"AutoApproveNodeBootstrapTokens","signature":"func AutoApproveNodeBootstrapTokens(client clientset.Interface) error","file":"cmd/kubeadm/app/phases/bootstraptoken/node/tlsbootstrap.go","code":"// AutoApproveNodeBootstrapTokens creates RBAC rules in a way that makes Node Bootstrap Tokens' CSR auto-approved by the csrapprover controller\nfunc AutoApproveNodeBootstrapTokens(client clientset.Interface) error {\n\tfmt.Println(\"[bootstrap-token] Configured RBAC rules to allow the csrapprover controller automatically approve CSRs from a Node Bootstrap Token\")\n\n\t// Always create this kubeadm-specific binding though\n\treturn apiclient.CreateOrUpdateClusterRoleBinding(client, \u0026rbac.ClusterRoleBinding{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: constants.NodeAutoApproveBootstrapClusterRoleBinding,\n\t\t},\n\t\tRoleRef: rbac.RoleRef{\n\t\t\tAPIGroup: rbac.GroupName,\n\t\t\tKind: \"ClusterRole\",\n\t\t\tName: constants.CSRAutoApprovalClusterRoleName,\n\t\t},\n\t\tSubjects: []rbac.Subject{\n\t\t\t{\n\t\t\t\tKind: rbac.GroupKind,\n\t\t\t\tName: constants.NodeBootstrapTokenAuthGroup,\n\t\t\t},\n\t\t},\n\t})\n}","line":{"from":91,"to":112}} {"id":100000922,"name":"AutoApproveNodeCertificateRotation","signature":"func AutoApproveNodeCertificateRotation(client clientset.Interface) error","file":"cmd/kubeadm/app/phases/bootstraptoken/node/tlsbootstrap.go","code":"// AutoApproveNodeCertificateRotation creates RBAC rules in a way that makes Node certificate rotation CSR auto-approved by the csrapprover controller\nfunc AutoApproveNodeCertificateRotation(client clientset.Interface) error {\n\tfmt.Println(\"[bootstrap-token] Configured RBAC rules to allow certificate rotation for all node client certificates in the cluster\")\n\n\treturn apiclient.CreateOrUpdateClusterRoleBinding(client, \u0026rbac.ClusterRoleBinding{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: constants.NodeAutoApproveCertificateRotationClusterRoleBinding,\n\t\t},\n\t\tRoleRef: rbac.RoleRef{\n\t\t\tAPIGroup: rbac.GroupName,\n\t\t\tKind: \"ClusterRole\",\n\t\t\tName: constants.NodeSelfCSRAutoApprovalClusterRoleName,\n\t\t},\n\t\tSubjects: []rbac.Subject{\n\t\t\t{\n\t\t\t\tKind: rbac.GroupKind,\n\t\t\t\tName: constants.NodesGroup,\n\t\t\t},\n\t\t},\n\t})\n}","line":{"from":114,"to":134}} {"id":100000923,"name":"CreateNewTokens","signature":"func CreateNewTokens(client clientset.Interface, tokens []bootstraptokenv1.BootstrapToken) error","file":"cmd/kubeadm/app/phases/bootstraptoken/node/token.go","code":"// CreateNewTokens tries to create a token and fails if one with the same ID already exists\nfunc CreateNewTokens(client clientset.Interface, tokens []bootstraptokenv1.BootstrapToken) error {\n\treturn UpdateOrCreateTokens(client, true, tokens)\n}","line":{"from":32,"to":35}} {"id":100000924,"name":"UpdateOrCreateTokens","signature":"func UpdateOrCreateTokens(client clientset.Interface, failIfExists bool, tokens []bootstraptokenv1.BootstrapToken) error","file":"cmd/kubeadm/app/phases/bootstraptoken/node/token.go","code":"// UpdateOrCreateTokens attempts to update a token with the given ID, or create if it does not already exist.\nfunc UpdateOrCreateTokens(client clientset.Interface, failIfExists bool, tokens []bootstraptokenv1.BootstrapToken) error {\n\n\tfor _, token := range tokens {\n\n\t\tsecretName := bootstraputil.BootstrapTokenSecretName(token.Token.ID)\n\t\tsecret, err := client.CoreV1().Secrets(metav1.NamespaceSystem).Get(context.TODO(), secretName, metav1.GetOptions{})\n\t\tif secret != nil \u0026\u0026 err == nil \u0026\u0026 failIfExists {\n\t\t\treturn errors.Errorf(\"a token with id %q already exists\", token.Token.ID)\n\t\t}\n\n\t\tupdatedOrNewSecret := bootstraptokenv1.BootstrapTokenToSecret(\u0026token)\n\t\t// Try to create or update the token with an exponential backoff\n\t\terr = apiclient.TryRunCommand(func() error {\n\t\t\tif err := apiclient.CreateOrUpdateSecret(client, updatedOrNewSecret); err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"failed to create or update bootstrap token with name %s\", secretName)\n\t\t\t}\n\t\t\treturn nil\n\t\t}, 5)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":37,"to":61}} {"id":100000925,"name":"GetConfig","signature":"func (k *KubeadmCert) GetConfig(ic *kubeadmapi.InitConfiguration) (*pkiutil.CertConfig, error)","file":"cmd/kubeadm/app/phases/certs/certlist.go","code":"// GetConfig returns the definition for the given cert given the provided InitConfiguration\nfunc (k *KubeadmCert) GetConfig(ic *kubeadmapi.InitConfiguration) (*pkiutil.CertConfig, error) {\n\tfor _, f := range k.configMutators {\n\t\tif err := f(ic, \u0026k.config); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tk.config.PublicKeyAlgorithm = ic.ClusterConfiguration.PublicKeyAlgorithm()\n\treturn \u0026k.config, nil\n}","line":{"from":55,"to":65}} {"id":100000926,"name":"CreateFromCA","signature":"func (k *KubeadmCert) CreateFromCA(ic *kubeadmapi.InitConfiguration, caCert *x509.Certificate, caKey crypto.Signer) error","file":"cmd/kubeadm/app/phases/certs/certlist.go","code":"// CreateFromCA makes and writes a certificate using the given CA cert and key.\nfunc (k *KubeadmCert) CreateFromCA(ic *kubeadmapi.InitConfiguration, caCert *x509.Certificate, caKey crypto.Signer) error {\n\tcfg, err := k.GetConfig(ic)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"couldn't create %q certificate\", k.Name)\n\t}\n\tcert, key, err := pkiutil.NewCertAndKey(caCert, caKey, cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = writeCertificateFilesIfNotExist(\n\t\tic.CertificatesDir,\n\t\tk.BaseName,\n\t\tcaCert,\n\t\tcert,\n\t\tkey,\n\t\tcfg,\n\t)\n\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to write or validate certificate %q\", k.Name)\n\t}\n\n\treturn nil\n}","line":{"from":67,"to":91}} {"id":100000927,"name":"CreateAsCA","signature":"func (k *KubeadmCert) CreateAsCA(ic *kubeadmapi.InitConfiguration) (*x509.Certificate, crypto.Signer, error)","file":"cmd/kubeadm/app/phases/certs/certlist.go","code":"// CreateAsCA creates a certificate authority, writing the files to disk and also returning the created CA so it can be used to sign child certs.\nfunc (k *KubeadmCert) CreateAsCA(ic *kubeadmapi.InitConfiguration) (*x509.Certificate, crypto.Signer, error) {\n\tcfg, err := k.GetConfig(ic)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrapf(err, \"couldn't get configuration for %q CA certificate\", k.Name)\n\t}\n\tcaCert, caKey, err := pkiutil.NewCertificateAuthority(cfg)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrapf(err, \"couldn't generate %q CA certificate\", k.Name)\n\t}\n\n\terr = writeCertificateAuthorityFilesIfNotExist(\n\t\tic.CertificatesDir,\n\t\tk.BaseName,\n\t\tcaCert,\n\t\tcaKey,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrapf(err, \"couldn't write out %q CA certificate\", k.Name)\n\t}\n\n\treturn caCert, caKey, nil\n}","line":{"from":93,"to":115}} {"id":100000928,"name":"CreateTree","signature":"func (t CertificateTree) CreateTree(ic *kubeadmapi.InitConfiguration) error","file":"cmd/kubeadm/app/phases/certs/certlist.go","code":"// CreateTree creates the CAs, certs signed by the CAs, and writes them all to disk.\nfunc (t CertificateTree) CreateTree(ic *kubeadmapi.InitConfiguration) error {\n\tfor ca, leaves := range t {\n\t\tcfg, err := ca.GetConfig(ic)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar caKey crypto.Signer\n\n\t\tcaCert, err := pkiutil.TryLoadCertFromDisk(ic.CertificatesDir, ca.BaseName)\n\t\tif err == nil {\n\t\t\t// Validate period\n\t\t\tCheckCertificatePeriodValidity(ca.BaseName, caCert)\n\n\t\t\t// Cert exists already, make sure it's valid\n\t\t\tif !caCert.IsCA {\n\t\t\t\treturn errors.Errorf(\"certificate %q is not a CA\", ca.Name)\n\t\t\t}\n\t\t\t// Try and load a CA Key\n\t\t\tcaKey, err = pkiutil.TryLoadKeyFromDisk(ic.CertificatesDir, ca.BaseName)\n\t\t\tif err != nil {\n\t\t\t\t// If there's no CA key, make sure every certificate exists.\n\t\t\t\tfor _, leaf := range leaves {\n\t\t\t\t\tcl := certKeyLocation{\n\t\t\t\t\t\tpkiDir: ic.CertificatesDir,\n\t\t\t\t\t\tbaseName: leaf.BaseName,\n\t\t\t\t\t\tuxName: leaf.Name,\n\t\t\t\t\t}\n\t\t\t\t\tif err := validateSignedCertWithCA(cl, caCert); err != nil {\n\t\t\t\t\t\treturn errors.Wrapf(err, \"could not load expected certificate %q or validate the existence of key %q for it\", leaf.Name, ca.Name)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// CA key exists; just use that to create new certificates.\n\t\t\tklog.V(1).Infof(\"[certs] Using the existing CA certificate %q and key %q\\n\", filepath.Join(ic.CertificatesDir, fmt.Sprintf(\"%s.crt\", ca.BaseName)), filepath.Join(ic.CertificatesDir, fmt.Sprintf(\"%s.key\", ca.BaseName)))\n\t\t} else {\n\t\t\t// CACert doesn't already exist, create a new cert and key.\n\t\t\tcaCert, caKey, err = pkiutil.NewCertificateAuthority(cfg)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\terr = writeCertificateAuthorityFilesIfNotExist(\n\t\t\t\tic.CertificatesDir,\n\t\t\t\tca.BaseName,\n\t\t\t\tcaCert,\n\t\t\t\tcaKey,\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tfor _, leaf := range leaves {\n\t\t\tif err := leaf.CreateFromCA(ic, caCert, caKey); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":120,"to":182}} {"id":100000929,"name":"CertTree","signature":"func (m CertificateMap) CertTree() (CertificateTree, error)","file":"cmd/kubeadm/app/phases/certs/certlist.go","code":"// CertTree returns a one-level-deep tree, mapping a CA cert to an array of certificates that should be signed by it.\nfunc (m CertificateMap) CertTree() (CertificateTree, error) {\n\tcaMap := make(CertificateTree)\n\n\tfor _, cert := range m {\n\t\tif cert.CAName == \"\" {\n\t\t\tif _, ok := caMap[cert]; !ok {\n\t\t\t\tcaMap[cert] = []*KubeadmCert{}\n\t\t\t}\n\t\t} else {\n\t\t\tca, ok := m[cert.CAName]\n\t\t\tif !ok {\n\t\t\t\treturn nil, errors.Errorf(\"certificate %q references unknown CA %q\", cert.Name, cert.CAName)\n\t\t\t}\n\t\t\tcaMap[ca] = append(caMap[ca], cert)\n\t\t}\n\t}\n\n\treturn caMap, nil\n}","line":{"from":187,"to":206}} {"id":100000930,"name":"AsMap","signature":"func (c Certificates) AsMap() CertificateMap","file":"cmd/kubeadm/app/phases/certs/certlist.go","code":"// AsMap returns the list of certificates as a map, keyed by name.\nfunc (c Certificates) AsMap() CertificateMap {\n\tcertMap := make(map[string]*KubeadmCert)\n\tfor _, cert := range c {\n\t\tcertMap[cert.Name] = cert\n\t}\n\n\treturn certMap\n}","line":{"from":211,"to":219}} {"id":100000931,"name":"GetDefaultCertList","signature":"func GetDefaultCertList() Certificates","file":"cmd/kubeadm/app/phases/certs/certlist.go","code":"// GetDefaultCertList returns all of the certificates kubeadm requires to function.\nfunc GetDefaultCertList() Certificates {\n\treturn Certificates{\n\t\tKubeadmCertRootCA(),\n\t\tKubeadmCertAPIServer(),\n\t\tKubeadmCertKubeletClient(),\n\t\t// Front Proxy certs\n\t\tKubeadmCertFrontProxyCA(),\n\t\tKubeadmCertFrontProxyClient(),\n\t\t// etcd certs\n\t\tKubeadmCertEtcdCA(),\n\t\tKubeadmCertEtcdServer(),\n\t\tKubeadmCertEtcdPeer(),\n\t\tKubeadmCertEtcdHealthcheck(),\n\t\tKubeadmCertEtcdAPIClient(),\n\t}\n}","line":{"from":221,"to":237}} {"id":100000932,"name":"GetCertsWithoutEtcd","signature":"func GetCertsWithoutEtcd() Certificates","file":"cmd/kubeadm/app/phases/certs/certlist.go","code":"// GetCertsWithoutEtcd returns all of the certificates kubeadm needs when etcd is hosted externally.\nfunc GetCertsWithoutEtcd() Certificates {\n\treturn Certificates{\n\t\tKubeadmCertRootCA(),\n\t\tKubeadmCertAPIServer(),\n\t\tKubeadmCertKubeletClient(),\n\t\t// Front Proxy certs\n\t\tKubeadmCertFrontProxyCA(),\n\t\tKubeadmCertFrontProxyClient(),\n\t}\n}","line":{"from":239,"to":249}} {"id":100000933,"name":"KubeadmCertRootCA","signature":"func KubeadmCertRootCA() *KubeadmCert","file":"cmd/kubeadm/app/phases/certs/certlist.go","code":"// KubeadmCertRootCA is the definition of the Kubernetes Root CA for the API Server and kubelet.\nfunc KubeadmCertRootCA() *KubeadmCert {\n\treturn \u0026KubeadmCert{\n\t\tName: \"ca\",\n\t\tLongName: \"self-signed Kubernetes CA to provision identities for other Kubernetes components\",\n\t\tBaseName: kubeadmconstants.CACertAndKeyBaseName,\n\t\tconfig: pkiutil.CertConfig{\n\t\t\tConfig: certutil.Config{\n\t\t\t\tCommonName: \"kubernetes\",\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":251,"to":263}} {"id":100000934,"name":"KubeadmCertAPIServer","signature":"func KubeadmCertAPIServer() *KubeadmCert","file":"cmd/kubeadm/app/phases/certs/certlist.go","code":"// KubeadmCertAPIServer is the definition of the cert used to serve the Kubernetes API.\nfunc KubeadmCertAPIServer() *KubeadmCert {\n\treturn \u0026KubeadmCert{\n\t\tName: \"apiserver\",\n\t\tLongName: \"certificate for serving the Kubernetes API\",\n\t\tBaseName: kubeadmconstants.APIServerCertAndKeyBaseName,\n\t\tCAName: \"ca\",\n\t\tconfig: pkiutil.CertConfig{\n\t\t\tConfig: certutil.Config{\n\t\t\t\tCommonName: kubeadmconstants.APIServerCertCommonName,\n\t\t\t\tUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},\n\t\t\t},\n\t\t},\n\t\tconfigMutators: []configMutatorsFunc{\n\t\t\tmakeAltNamesMutator(pkiutil.GetAPIServerAltNames),\n\t\t},\n\t}\n}","line":{"from":265,"to":282}} {"id":100000935,"name":"KubeadmCertKubeletClient","signature":"func KubeadmCertKubeletClient() *KubeadmCert","file":"cmd/kubeadm/app/phases/certs/certlist.go","code":"// KubeadmCertKubeletClient is the definition of the cert used by the API server to access the kubelet.\nfunc KubeadmCertKubeletClient() *KubeadmCert {\n\treturn \u0026KubeadmCert{\n\t\tName: \"apiserver-kubelet-client\",\n\t\tLongName: \"certificate for the API server to connect to kubelet\",\n\t\tBaseName: kubeadmconstants.APIServerKubeletClientCertAndKeyBaseName,\n\t\tCAName: \"ca\",\n\t\tconfig: pkiutil.CertConfig{\n\t\t\tConfig: certutil.Config{\n\t\t\t\tCommonName: kubeadmconstants.APIServerKubeletClientCertCommonName,\n\t\t\t\tOrganization: []string{kubeadmconstants.SystemPrivilegedGroup},\n\t\t\t\tUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":284,"to":299}} {"id":100000936,"name":"KubeadmCertFrontProxyCA","signature":"func KubeadmCertFrontProxyCA() *KubeadmCert","file":"cmd/kubeadm/app/phases/certs/certlist.go","code":"// KubeadmCertFrontProxyCA is the definition of the CA used for the front end proxy.\nfunc KubeadmCertFrontProxyCA() *KubeadmCert {\n\treturn \u0026KubeadmCert{\n\t\tName: \"front-proxy-ca\",\n\t\tLongName: \"self-signed CA to provision identities for front proxy\",\n\t\tBaseName: kubeadmconstants.FrontProxyCACertAndKeyBaseName,\n\t\tconfig: pkiutil.CertConfig{\n\t\t\tConfig: certutil.Config{\n\t\t\t\tCommonName: \"front-proxy-ca\",\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":301,"to":313}} {"id":100000937,"name":"KubeadmCertFrontProxyClient","signature":"func KubeadmCertFrontProxyClient() *KubeadmCert","file":"cmd/kubeadm/app/phases/certs/certlist.go","code":"// KubeadmCertFrontProxyClient is the definition of the cert used by the API server to access the front proxy.\nfunc KubeadmCertFrontProxyClient() *KubeadmCert {\n\treturn \u0026KubeadmCert{\n\t\tName: \"front-proxy-client\",\n\t\tBaseName: kubeadmconstants.FrontProxyClientCertAndKeyBaseName,\n\t\tLongName: \"certificate for the front proxy client\",\n\t\tCAName: \"front-proxy-ca\",\n\t\tconfig: pkiutil.CertConfig{\n\t\t\tConfig: certutil.Config{\n\t\t\t\tCommonName: kubeadmconstants.FrontProxyClientCertCommonName,\n\t\t\t\tUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":315,"to":329}} {"id":100000938,"name":"KubeadmCertEtcdCA","signature":"func KubeadmCertEtcdCA() *KubeadmCert","file":"cmd/kubeadm/app/phases/certs/certlist.go","code":"// KubeadmCertEtcdCA is the definition of the root CA used by the hosted etcd server.\nfunc KubeadmCertEtcdCA() *KubeadmCert {\n\treturn \u0026KubeadmCert{\n\t\tName: \"etcd-ca\",\n\t\tLongName: \"self-signed CA to provision identities for etcd\",\n\t\tBaseName: kubeadmconstants.EtcdCACertAndKeyBaseName,\n\t\tconfig: pkiutil.CertConfig{\n\t\t\tConfig: certutil.Config{\n\t\t\t\tCommonName: \"etcd-ca\",\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":331,"to":343}} {"id":100000939,"name":"KubeadmCertEtcdServer","signature":"func KubeadmCertEtcdServer() *KubeadmCert","file":"cmd/kubeadm/app/phases/certs/certlist.go","code":"// KubeadmCertEtcdServer is the definition of the cert used to serve etcd to clients.\nfunc KubeadmCertEtcdServer() *KubeadmCert {\n\treturn \u0026KubeadmCert{\n\t\tName: \"etcd-server\",\n\t\tLongName: \"certificate for serving etcd\",\n\t\tBaseName: kubeadmconstants.EtcdServerCertAndKeyBaseName,\n\t\tCAName: \"etcd-ca\",\n\t\tconfig: pkiutil.CertConfig{\n\t\t\tConfig: certutil.Config{\n\t\t\t\t// TODO: etcd 3.2 introduced an undocumented requirement for ClientAuth usage on the\n\t\t\t\t// server cert: https://github.com/coreos/etcd/issues/9785#issuecomment-396715692\n\t\t\t\t// Once the upstream issue is resolved, this should be returned to only allowing\n\t\t\t\t// ServerAuth usage.\n\t\t\t\tUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},\n\t\t\t},\n\t\t},\n\t\tconfigMutators: []configMutatorsFunc{\n\t\t\tmakeAltNamesMutator(pkiutil.GetEtcdAltNames),\n\t\t\tsetCommonNameToNodeName(),\n\t\t},\n\t}\n}","line":{"from":345,"to":366}} {"id":100000940,"name":"KubeadmCertEtcdPeer","signature":"func KubeadmCertEtcdPeer() *KubeadmCert","file":"cmd/kubeadm/app/phases/certs/certlist.go","code":"// KubeadmCertEtcdPeer is the definition of the cert used by etcd peers to access each other.\nfunc KubeadmCertEtcdPeer() *KubeadmCert {\n\treturn \u0026KubeadmCert{\n\t\tName: \"etcd-peer\",\n\t\tLongName: \"certificate for etcd nodes to communicate with each other\",\n\t\tBaseName: kubeadmconstants.EtcdPeerCertAndKeyBaseName,\n\t\tCAName: \"etcd-ca\",\n\t\tconfig: pkiutil.CertConfig{\n\t\t\tConfig: certutil.Config{\n\t\t\t\tUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},\n\t\t\t},\n\t\t},\n\t\tconfigMutators: []configMutatorsFunc{\n\t\t\tmakeAltNamesMutator(pkiutil.GetEtcdPeerAltNames),\n\t\t\tsetCommonNameToNodeName(),\n\t\t},\n\t}\n}","line":{"from":368,"to":385}} {"id":100000941,"name":"KubeadmCertEtcdHealthcheck","signature":"func KubeadmCertEtcdHealthcheck() *KubeadmCert","file":"cmd/kubeadm/app/phases/certs/certlist.go","code":"// KubeadmCertEtcdHealthcheck is the definition of the cert used by Kubernetes to check the health of the etcd server.\nfunc KubeadmCertEtcdHealthcheck() *KubeadmCert {\n\treturn \u0026KubeadmCert{\n\t\tName: \"etcd-healthcheck-client\",\n\t\tLongName: \"certificate for liveness probes to healthcheck etcd\",\n\t\tBaseName: kubeadmconstants.EtcdHealthcheckClientCertAndKeyBaseName,\n\t\tCAName: \"etcd-ca\",\n\t\tconfig: pkiutil.CertConfig{\n\t\t\tConfig: certutil.Config{\n\t\t\t\tCommonName: kubeadmconstants.EtcdHealthcheckClientCertCommonName,\n\t\t\t\tOrganization: []string{kubeadmconstants.SystemPrivilegedGroup},\n\t\t\t\tUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":387,"to":402}} {"id":100000942,"name":"KubeadmCertEtcdAPIClient","signature":"func KubeadmCertEtcdAPIClient() *KubeadmCert","file":"cmd/kubeadm/app/phases/certs/certlist.go","code":"// KubeadmCertEtcdAPIClient is the definition of the cert used by the API server to access etcd.\nfunc KubeadmCertEtcdAPIClient() *KubeadmCert {\n\treturn \u0026KubeadmCert{\n\t\tName: \"apiserver-etcd-client\",\n\t\tLongName: \"certificate the apiserver uses to access etcd\",\n\t\tBaseName: kubeadmconstants.APIServerEtcdClientCertAndKeyBaseName,\n\t\tCAName: \"etcd-ca\",\n\t\tconfig: pkiutil.CertConfig{\n\t\t\tConfig: certutil.Config{\n\t\t\t\tCommonName: kubeadmconstants.APIServerEtcdClientCertCommonName,\n\t\t\t\tOrganization: []string{kubeadmconstants.SystemPrivilegedGroup},\n\t\t\t\tUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":404,"to":419}} {"id":100000943,"name":"makeAltNamesMutator","signature":"func makeAltNamesMutator(f func(*kubeadmapi.InitConfiguration) (*certutil.AltNames, error)) configMutatorsFunc","file":"cmd/kubeadm/app/phases/certs/certlist.go","code":"func makeAltNamesMutator(f func(*kubeadmapi.InitConfiguration) (*certutil.AltNames, error)) configMutatorsFunc {\n\treturn func(mc *kubeadmapi.InitConfiguration, cc *pkiutil.CertConfig) error {\n\t\taltNames, err := f(mc)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcc.AltNames = *altNames\n\t\treturn nil\n\t}\n}","line":{"from":421,"to":430}} {"id":100000944,"name":"setCommonNameToNodeName","signature":"func setCommonNameToNodeName() configMutatorsFunc","file":"cmd/kubeadm/app/phases/certs/certlist.go","code":"func setCommonNameToNodeName() configMutatorsFunc {\n\treturn func(mc *kubeadmapi.InitConfiguration, cc *pkiutil.CertConfig) error {\n\t\tcc.CommonName = mc.NodeRegistration.Name\n\t\treturn nil\n\t}\n}","line":{"from":432,"to":437}} {"id":100000945,"name":"leafCertificates","signature":"func leafCertificates(c Certificates) (Certificates, error)","file":"cmd/kubeadm/app/phases/certs/certlist.go","code":"// leafCertificates returns non-CA certificates from the supplied Certificates.\nfunc leafCertificates(c Certificates) (Certificates, error) {\n\tcertTree, err := c.AsMap().CertTree()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar out Certificates\n\tfor _, leafCertificates := range certTree {\n\t\tout = append(out, leafCertificates...)\n\t}\n\treturn out, nil\n}","line":{"from":439,"to":451}} {"id":100000946,"name":"createKeyAndCSR","signature":"func createKeyAndCSR(kubeadmConfig *kubeadmapi.InitConfiguration, cert *KubeadmCert) error","file":"cmd/kubeadm/app/phases/certs/certlist.go","code":"func createKeyAndCSR(kubeadmConfig *kubeadmapi.InitConfiguration, cert *KubeadmCert) error {\n\tif kubeadmConfig == nil {\n\t\treturn errors.Errorf(\"%s: kubeadmConfig was nil\", errInvalid)\n\t}\n\tif cert == nil {\n\t\treturn errors.Errorf(\"%s: cert was nil\", errInvalid)\n\t}\n\tcertDir := kubeadmConfig.CertificatesDir\n\tname := cert.BaseName\n\tif pkiutil.CSROrKeyExist(certDir, name) {\n\t\treturn errors.Errorf(\"%s: key or CSR %s/%s\", errExist, certDir, name)\n\t}\n\tcfg, err := cert.GetConfig(kubeadmConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcsr, key, err := pkiutil.NewCSRAndKey(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = pkiutil.WriteKey(certDir, name, key)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn pkiutil.WriteCSR(certDir, name, csr)\n}","line":{"from":453,"to":478}} {"id":100000947,"name":"CreateDefaultKeysAndCSRFiles","signature":"func CreateDefaultKeysAndCSRFiles(out io.Writer, config *kubeadmapi.InitConfiguration) error","file":"cmd/kubeadm/app/phases/certs/certlist.go","code":"// CreateDefaultKeysAndCSRFiles is used in ExternalCA mode to create key files\n// and adjacent CSR files.\nfunc CreateDefaultKeysAndCSRFiles(out io.Writer, config *kubeadmapi.InitConfiguration) error {\n\tcertificates, err := leafCertificates(GetDefaultCertList())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif out != nil {\n\t\tfmt.Fprintf(out, \"generating keys and CSRs in %s\\n\", config.CertificatesDir)\n\t}\n\tfor _, cert := range certificates {\n\t\tif err := createKeyAndCSR(config, cert); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif out != nil {\n\t\t\tfmt.Fprintf(out, \" %s\\n\", cert.BaseName)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":480,"to":499}} {"id":100000948,"name":"CreatePKIAssets","signature":"func CreatePKIAssets(cfg *kubeadmapi.InitConfiguration) error","file":"cmd/kubeadm/app/phases/certs/certs.go","code":"// CreatePKIAssets will create and write to disk all PKI assets necessary to establish the control plane.\n// If the PKI assets already exists in the target folder, they are used only if evaluated equal; otherwise an error is returned.\nfunc CreatePKIAssets(cfg *kubeadmapi.InitConfiguration) error {\n\tklog.V(1).Infoln(\"creating PKI assets\")\n\n\t// This structure cannot handle multilevel CA hierarchies.\n\t// This isn't a problem right now, but may become one in the future.\n\n\tvar certList Certificates\n\n\tif cfg.Etcd.Local == nil {\n\t\tcertList = GetCertsWithoutEtcd()\n\t} else {\n\t\tcertList = GetDefaultCertList()\n\t}\n\n\tcertTree, err := certList.AsMap().CertTree()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := certTree.CreateTree(cfg); err != nil {\n\t\treturn errors.Wrap(err, \"error creating PKI assets\")\n\t}\n\n\tfmt.Printf(\"[certs] Valid certificates and keys now exist in %q\\n\", cfg.CertificatesDir)\n\n\t// Service accounts are not x509 certs, so handled separately\n\treturn CreateServiceAccountKeyAndPublicKeyFiles(cfg.CertificatesDir, cfg.ClusterConfiguration.PublicKeyAlgorithm())\n}","line":{"from":44,"to":73}} {"id":100000949,"name":"CreateServiceAccountKeyAndPublicKeyFiles","signature":"func CreateServiceAccountKeyAndPublicKeyFiles(certsDir string, keyType x509.PublicKeyAlgorithm) error","file":"cmd/kubeadm/app/phases/certs/certs.go","code":"// CreateServiceAccountKeyAndPublicKeyFiles creates new public/private key files for signing service account users.\n// If the sa public/private key files already exist in the target folder, they are used only if evaluated equals; otherwise an error is returned.\nfunc CreateServiceAccountKeyAndPublicKeyFiles(certsDir string, keyType x509.PublicKeyAlgorithm) error {\n\tklog.V(1).Infoln(\"creating new public/private key files for signing service account users\")\n\t_, err := keyutil.PrivateKeyFromFile(filepath.Join(certsDir, kubeadmconstants.ServiceAccountPrivateKeyName))\n\tif err == nil {\n\t\t// kubeadm doesn't validate the existing certificate key more than this;\n\t\t// Basically, if we find a key file with the same path kubeadm thinks those files\n\t\t// are equal and doesn't bother writing a new file\n\t\tfmt.Printf(\"[certs] Using the existing %q key\\n\", kubeadmconstants.ServiceAccountKeyBaseName)\n\t\treturn nil\n\t} else if !os.IsNotExist(err) {\n\t\treturn errors.Wrapf(err, \"file %s existed but it could not be loaded properly\", kubeadmconstants.ServiceAccountPrivateKeyName)\n\t}\n\n\t// The key does NOT exist, let's generate it now\n\tkey, err := pkiutil.NewPrivateKey(keyType)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Write .key and .pub files to disk\n\tfmt.Printf(\"[certs] Generating %q key and public key\\n\", kubeadmconstants.ServiceAccountKeyBaseName)\n\n\tif err := pkiutil.WriteKey(certsDir, kubeadmconstants.ServiceAccountKeyBaseName, key); err != nil {\n\t\treturn err\n\t}\n\n\treturn pkiutil.WritePublicKey(certsDir, kubeadmconstants.ServiceAccountKeyBaseName, key.Public())\n}","line":{"from":75,"to":104}} {"id":100000950,"name":"CreateCACertAndKeyFiles","signature":"func CreateCACertAndKeyFiles(certSpec *KubeadmCert, cfg *kubeadmapi.InitConfiguration) error","file":"cmd/kubeadm/app/phases/certs/certs.go","code":"// CreateCACertAndKeyFiles generates and writes out a given certificate authority.\n// The certSpec should be one of the variables from this package.\nfunc CreateCACertAndKeyFiles(certSpec *KubeadmCert, cfg *kubeadmapi.InitConfiguration) error {\n\tif certSpec.CAName != \"\" {\n\t\treturn errors.Errorf(\"this function should only be used for CAs, but cert %s has CA %s\", certSpec.Name, certSpec.CAName)\n\t}\n\tklog.V(1).Infof(\"creating a new certificate authority for %s\", certSpec.Name)\n\n\tcertConfig, err := certSpec.GetConfig(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcaCert, caKey, err := pkiutil.NewCertificateAuthority(certConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn writeCertificateAuthorityFilesIfNotExist(\n\t\tcfg.CertificatesDir,\n\t\tcertSpec.BaseName,\n\t\tcaCert,\n\t\tcaKey,\n\t)\n}","line":{"from":106,"to":130}} {"id":100000951,"name":"NewCSR","signature":"func NewCSR(certSpec *KubeadmCert, cfg *kubeadmapi.InitConfiguration) (*x509.CertificateRequest, crypto.Signer, error)","file":"cmd/kubeadm/app/phases/certs/certs.go","code":"// NewCSR will generate a new CSR and accompanying key\nfunc NewCSR(certSpec *KubeadmCert, cfg *kubeadmapi.InitConfiguration) (*x509.CertificateRequest, crypto.Signer, error) {\n\tcertConfig, err := certSpec.GetConfig(cfg)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"failed to retrieve cert configuration\")\n\t}\n\n\treturn pkiutil.NewCSRAndKey(certConfig)\n}","line":{"from":132,"to":140}} {"id":100000952,"name":"CreateCSR","signature":"func CreateCSR(certSpec *KubeadmCert, cfg *kubeadmapi.InitConfiguration, path string) error","file":"cmd/kubeadm/app/phases/certs/certs.go","code":"// CreateCSR creates a certificate signing request\nfunc CreateCSR(certSpec *KubeadmCert, cfg *kubeadmapi.InitConfiguration, path string) error {\n\tcsr, key, err := NewCSR(certSpec, cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn writeCSRFilesIfNotExist(path, certSpec.BaseName, csr, key)\n}","line":{"from":142,"to":149}} {"id":100000953,"name":"CreateCertAndKeyFilesWithCA","signature":"func CreateCertAndKeyFilesWithCA(certSpec *KubeadmCert, caCertSpec *KubeadmCert, cfg *kubeadmapi.InitConfiguration) error","file":"cmd/kubeadm/app/phases/certs/certs.go","code":"// CreateCertAndKeyFilesWithCA loads the given certificate authority from disk, then generates and writes out the given certificate and key.\n// The certSpec and caCertSpec should both be one of the variables from this package.\nfunc CreateCertAndKeyFilesWithCA(certSpec *KubeadmCert, caCertSpec *KubeadmCert, cfg *kubeadmapi.InitConfiguration) error {\n\tif certSpec.CAName != caCertSpec.Name {\n\t\treturn errors.Errorf(\"expected CAname for %s to be %q, but was %s\", certSpec.Name, certSpec.CAName, caCertSpec.Name)\n\t}\n\n\tcaCert, caKey, err := LoadCertificateAuthority(cfg.CertificatesDir, caCertSpec.BaseName)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"couldn't load CA certificate %s\", caCertSpec.Name)\n\t}\n\n\treturn certSpec.CreateFromCA(cfg, caCert, caKey)\n}","line":{"from":151,"to":164}} {"id":100000954,"name":"LoadCertificateAuthority","signature":"func LoadCertificateAuthority(pkiDir string, baseName string) (*x509.Certificate, crypto.Signer, error)","file":"cmd/kubeadm/app/phases/certs/certs.go","code":"// LoadCertificateAuthority tries to load a CA in the given directory with the given name.\nfunc LoadCertificateAuthority(pkiDir string, baseName string) (*x509.Certificate, crypto.Signer, error) {\n\t// Checks if certificate authority exists in the PKI directory\n\tif !pkiutil.CertOrKeyExist(pkiDir, baseName) {\n\t\treturn nil, nil, errors.Errorf(\"couldn't load %s certificate authority from %s\", baseName, pkiDir)\n\t}\n\n\t// Try to load certificate authority .crt and .key from the PKI directory\n\tcaCert, caKey, err := pkiutil.TryLoadCertAndKeyFromDisk(pkiDir, baseName)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrapf(err, \"failure loading %s certificate authority\", baseName)\n\t}\n\t// Validate period\n\tCheckCertificatePeriodValidity(baseName, caCert)\n\n\t// Make sure the loaded CA cert actually is a CA\n\tif !caCert.IsCA {\n\t\treturn nil, nil, errors.Errorf(\"%s certificate is not a certificate authority\", baseName)\n\t}\n\n\treturn caCert, caKey, nil\n}","line":{"from":166,"to":187}} {"id":100000955,"name":"writeCertificateAuthorityFilesIfNotExist","signature":"func writeCertificateAuthorityFilesIfNotExist(pkiDir string, baseName string, caCert *x509.Certificate, caKey crypto.Signer) error","file":"cmd/kubeadm/app/phases/certs/certs.go","code":"// writeCertificateAuthorityFilesIfNotExist write a new certificate Authority to the given path.\n// If there already is a certificate file at the given path; kubeadm tries to load it and check if the values in the\n// existing and the expected certificate equals. If they do; kubeadm will just skip writing the file as it's up-to-date,\n// otherwise this function returns an error.\nfunc writeCertificateAuthorityFilesIfNotExist(pkiDir string, baseName string, caCert *x509.Certificate, caKey crypto.Signer) error {\n\n\t// If cert or key exists, we should try to load them\n\tif pkiutil.CertOrKeyExist(pkiDir, baseName) {\n\n\t\t// Try to load .crt and .key from the PKI directory\n\t\tcaCert, _, err := pkiutil.TryLoadCertAndKeyFromDisk(pkiDir, baseName)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"failure loading %s certificate\", baseName)\n\t\t}\n\t\t// Validate period\n\t\tCheckCertificatePeriodValidity(baseName, caCert)\n\n\t\t// Check if the existing cert is a CA\n\t\tif !caCert.IsCA {\n\t\t\treturn errors.Errorf(\"certificate %s is not a CA\", baseName)\n\t\t}\n\n\t\t// kubeadm doesn't validate the existing certificate Authority more than this;\n\t\t// Basically, if we find a certificate file with the same path; and it is a CA\n\t\t// kubeadm thinks those files are equal and doesn't bother writing a new file\n\t\tfmt.Printf(\"[certs] Using the existing %q certificate and key\\n\", baseName)\n\t} else {\n\t\t// Write .crt and .key files to disk\n\t\tfmt.Printf(\"[certs] Generating %q certificate and key\\n\", baseName)\n\n\t\tif err := pkiutil.WriteCertAndKey(pkiDir, baseName, caCert, caKey); err != nil {\n\t\t\treturn errors.Wrapf(err, \"failure while saving %s certificate and key\", baseName)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":189,"to":224}} {"id":100000956,"name":"writeCertificateFilesIfNotExist","signature":"func writeCertificateFilesIfNotExist(pkiDir string, baseName string, signingCert *x509.Certificate, cert *x509.Certificate, key crypto.Signer, cfg *pkiutil.CertConfig) error","file":"cmd/kubeadm/app/phases/certs/certs.go","code":"// writeCertificateFilesIfNotExist write a new certificate to the given path.\n// If there already is a certificate file at the given path; kubeadm tries to load it and check if the values in the\n// existing and the expected certificate equals. If they do; kubeadm will just skip writing the file as it's up-to-date,\n// otherwise this function returns an error.\nfunc writeCertificateFilesIfNotExist(pkiDir string, baseName string, signingCert *x509.Certificate, cert *x509.Certificate, key crypto.Signer, cfg *pkiutil.CertConfig) error {\n\n\t// Checks if the signed certificate exists in the PKI directory\n\tif pkiutil.CertOrKeyExist(pkiDir, baseName) {\n\t\t// Try to load key from the PKI directory\n\t\t_, err := pkiutil.TryLoadKeyFromDisk(pkiDir, baseName)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"failure loading %s key\", baseName)\n\t\t}\n\n\t\t// Try to load certificate from the PKI directory\n\t\tsignedCert, intermediates, err := pkiutil.TryLoadCertChainFromDisk(pkiDir, baseName)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"failure loading %s certificate\", baseName)\n\t\t}\n\t\t// Validate period\n\t\tCheckCertificatePeriodValidity(baseName, signedCert)\n\n\t\t// Check if the existing cert is signed by the given CA\n\t\tif err := pkiutil.VerifyCertChain(signedCert, intermediates, signingCert); err != nil {\n\t\t\treturn errors.Errorf(\"certificate %s is not signed by corresponding CA\", baseName)\n\t\t}\n\n\t\t// Check if the certificate has the correct attributes\n\t\tif err := validateCertificateWithConfig(signedCert, baseName, cfg); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Printf(\"[certs] Using the existing %q certificate and key\\n\", baseName)\n\t} else {\n\t\t// Write .crt and .key files to disk\n\t\tfmt.Printf(\"[certs] Generating %q certificate and key\\n\", baseName)\n\n\t\tif err := pkiutil.WriteCertAndKey(pkiDir, baseName, cert, key); err != nil {\n\t\t\treturn errors.Wrapf(err, \"failure while saving %s certificate and key\", baseName)\n\t\t}\n\t\tif pkiutil.HasServerAuth(cert) {\n\t\t\tfmt.Printf(\"[certs] %s serving cert is signed for DNS names %v and IPs %v\\n\", baseName, cert.DNSNames, cert.IPAddresses)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":226,"to":272}} {"id":100000957,"name":"writeCSRFilesIfNotExist","signature":"func writeCSRFilesIfNotExist(csrDir string, baseName string, csr *x509.CertificateRequest, key crypto.Signer) error","file":"cmd/kubeadm/app/phases/certs/certs.go","code":"// writeCSRFilesIfNotExist writes a new CSR to the given path.\n// If there already is a CSR file at the given path; kubeadm tries to load it and check if it's a valid certificate.\n// otherwise this function returns an error.\nfunc writeCSRFilesIfNotExist(csrDir string, baseName string, csr *x509.CertificateRequest, key crypto.Signer) error {\n\tif pkiutil.CSROrKeyExist(csrDir, baseName) {\n\t\t_, _, err := pkiutil.TryLoadCSRAndKeyFromDisk(csrDir, baseName)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"%s CSR existed but it could not be loaded properly\", baseName)\n\t\t}\n\n\t\tfmt.Printf(\"[certs] Using the existing %q CSR\\n\", baseName)\n\t} else {\n\t\t// Write .key and .csr files to disk\n\t\tfmt.Printf(\"[certs] Generating %q key and CSR\\n\", baseName)\n\n\t\tif err := pkiutil.WriteKey(csrDir, baseName, key); err != nil {\n\t\t\treturn errors.Wrapf(err, \"failure while saving %s key\", baseName)\n\t\t}\n\n\t\tif err := pkiutil.WriteCSR(csrDir, baseName, csr); err != nil {\n\t\t\treturn errors.Wrapf(err, \"failure while saving %s CSR\", baseName)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":274,"to":299}} {"id":100000958,"name":"SharedCertificateExists","signature":"func SharedCertificateExists(cfg *kubeadmapi.ClusterConfiguration) (bool, error)","file":"cmd/kubeadm/app/phases/certs/certs.go","code":"// SharedCertificateExists verifies if the shared certificates exist and are still valid - the certificates must be\n// equal across control-plane nodes: ca.key, ca.crt, sa.key, sa.pub, front-proxy-ca.key, front-proxy-ca.crt and etcd/ca.key, etcd/ca.crt if local/stacked etcd\n// Missing private keys of CA are non-fatal and produce warnings.\nfunc SharedCertificateExists(cfg *kubeadmapi.ClusterConfiguration) (bool, error) {\n\tvar errs []error\n\tif err := validateCACertAndKey(certKeyLocation{cfg.CertificatesDir, kubeadmconstants.CACertAndKeyBaseName, \"\", \"CA\"}); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\tif err := validatePrivatePublicKey(certKeyLocation{cfg.CertificatesDir, \"\", kubeadmconstants.ServiceAccountKeyBaseName, \"service account\"}); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\tif err := validateCACertAndKey(certKeyLocation{cfg.CertificatesDir, kubeadmconstants.FrontProxyCACertAndKeyBaseName, \"\", \"front-proxy CA\"}); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\t// in case of local/stacked etcd\n\tif cfg.Etcd.External == nil {\n\t\tif err := validateCACertAndKey(certKeyLocation{cfg.CertificatesDir, kubeadmconstants.EtcdCACertAndKeyBaseName, \"\", \"etcd CA\"}); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\tif len(errs) != 0 {\n\t\treturn false, utilerrors.NewAggregate(errs)\n\t}\n\treturn true, nil\n}","line":{"from":308,"to":335}} {"id":100000959,"name":"UsingExternalCA","signature":"func UsingExternalCA(cfg *kubeadmapi.ClusterConfiguration) (bool, error)","file":"cmd/kubeadm/app/phases/certs/certs.go","code":"// UsingExternalCA determines whether the user is relying on an external CA. We currently implicitly determine this is the case\n// when the CA Cert is present but the CA Key is not.\n// This allows us to, e.g., skip generating certs or not start the csr signing controller.\n// In case we are using an external front-proxy CA, the function validates the certificates signed by front-proxy CA that should be provided by the user.\nfunc UsingExternalCA(cfg *kubeadmapi.ClusterConfiguration) (bool, error) {\n\n\tif err := validateCACert(certKeyLocation{cfg.CertificatesDir, kubeadmconstants.CACertAndKeyBaseName, \"\", \"CA\"}); err != nil {\n\t\treturn false, err\n\t}\n\n\tcaKeyPath := filepath.Join(cfg.CertificatesDir, kubeadmconstants.CAKeyName)\n\tif _, err := os.Stat(caKeyPath); !os.IsNotExist(err) {\n\t\treturn false, nil\n\t}\n\n\tif err := validateSignedCert(certKeyLocation{cfg.CertificatesDir, kubeadmconstants.CACertAndKeyBaseName, kubeadmconstants.APIServerCertAndKeyBaseName, \"API server\"}); err != nil {\n\t\treturn true, err\n\t}\n\n\tif err := validateSignedCert(certKeyLocation{cfg.CertificatesDir, kubeadmconstants.CACertAndKeyBaseName, kubeadmconstants.APIServerKubeletClientCertAndKeyBaseName, \"API server kubelet client\"}); err != nil {\n\t\treturn true, err\n\t}\n\n\treturn true, nil\n}","line":{"from":337,"to":361}} {"id":100000960,"name":"UsingExternalFrontProxyCA","signature":"func UsingExternalFrontProxyCA(cfg *kubeadmapi.ClusterConfiguration) (bool, error)","file":"cmd/kubeadm/app/phases/certs/certs.go","code":"// UsingExternalFrontProxyCA determines whether the user is relying on an external front-proxy CA. We currently implicitly determine this is the case\n// when the front proxy CA Cert is present but the front proxy CA Key is not.\n// In case we are using an external front-proxy CA, the function validates the certificates signed by front-proxy CA that should be provided by the user.\nfunc UsingExternalFrontProxyCA(cfg *kubeadmapi.ClusterConfiguration) (bool, error) {\n\n\tif err := validateCACert(certKeyLocation{cfg.CertificatesDir, kubeadmconstants.FrontProxyCACertAndKeyBaseName, \"\", \"front-proxy CA\"}); err != nil {\n\t\treturn false, err\n\t}\n\n\tfrontProxyCAKeyPath := filepath.Join(cfg.CertificatesDir, kubeadmconstants.FrontProxyCAKeyName)\n\tif _, err := os.Stat(frontProxyCAKeyPath); !os.IsNotExist(err) {\n\t\treturn false, nil\n\t}\n\n\tif err := validateSignedCert(certKeyLocation{cfg.CertificatesDir, kubeadmconstants.FrontProxyCACertAndKeyBaseName, kubeadmconstants.FrontProxyClientCertAndKeyBaseName, \"front-proxy client\"}); err != nil {\n\t\treturn true, err\n\t}\n\n\treturn true, nil\n}","line":{"from":363,"to":382}} {"id":100000961,"name":"UsingExternalEtcdCA","signature":"func UsingExternalEtcdCA(cfg *kubeadmapi.ClusterConfiguration) (bool, error)","file":"cmd/kubeadm/app/phases/certs/certs.go","code":"// UsingExternalEtcdCA determines whether the user is relying on an external etcd CA. We currently implicitly determine this is the case\n// when the etcd CA Cert is present but the etcd CA Key is not.\n// In case we are using an external etcd CA, the function validates the certificates signed by etcd CA that should be provided by the user.\nfunc UsingExternalEtcdCA(cfg *kubeadmapi.ClusterConfiguration) (bool, error) {\n\tif err := validateCACert(certKeyLocation{cfg.CertificatesDir, kubeadmconstants.EtcdCACertAndKeyBaseName, \"\", \"etcd CA\"}); err != nil {\n\t\treturn false, err\n\t}\n\n\tpath := filepath.Join(cfg.CertificatesDir, kubeadmconstants.EtcdCAKeyName)\n\tif _, err := os.Stat(path); !os.IsNotExist(err) {\n\t\treturn false, nil\n\t}\n\n\tif err := validateSignedCert(certKeyLocation{cfg.CertificatesDir, kubeadmconstants.EtcdCACertAndKeyBaseName, kubeadmconstants.APIServerEtcdClientCertAndKeyBaseName, \"apiserver etcd client\"}); err != nil {\n\t\treturn true, err\n\t}\n\n\tif err := validateSignedCert(certKeyLocation{cfg.CertificatesDir, kubeadmconstants.EtcdCACertAndKeyBaseName, kubeadmconstants.EtcdServerCertAndKeyBaseName, \"etcd server\"}); err != nil {\n\t\treturn true, err\n\t}\n\n\tif err := validateSignedCert(certKeyLocation{cfg.CertificatesDir, kubeadmconstants.EtcdCACertAndKeyBaseName, kubeadmconstants.EtcdPeerCertAndKeyBaseName, \"etcd peer\"}); err != nil {\n\t\treturn true, err\n\t}\n\n\tif err := validateSignedCert(certKeyLocation{cfg.CertificatesDir, kubeadmconstants.EtcdCACertAndKeyBaseName, kubeadmconstants.EtcdHealthcheckClientCertAndKeyBaseName, \"etcd health-check client\"}); err != nil {\n\t\treturn true, err\n\t}\n\n\treturn true, nil\n}","line":{"from":384,"to":414}} {"id":100000962,"name":"validateCACert","signature":"func validateCACert(l certKeyLocation) error","file":"cmd/kubeadm/app/phases/certs/certs.go","code":"// validateCACert tries to load a x509 certificate from pkiDir and validates that it is a CA\nfunc validateCACert(l certKeyLocation) error {\n\t// Check CA Cert\n\tcaCert, err := pkiutil.TryLoadCertFromDisk(l.pkiDir, l.caBaseName)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failure loading certificate for %s\", l.uxName)\n\t}\n\t// Validate period\n\tCheckCertificatePeriodValidity(l.uxName, caCert)\n\n\t// Check if cert is a CA\n\tif !caCert.IsCA {\n\t\treturn errors.Errorf(\"certificate %s is not a CA\", l.uxName)\n\t}\n\treturn nil\n}","line":{"from":416,"to":431}} {"id":100000963,"name":"validateCACertAndKey","signature":"func validateCACertAndKey(l certKeyLocation) error","file":"cmd/kubeadm/app/phases/certs/certs.go","code":"// validateCACertAndKey tries to load a x509 certificate and private key from pkiDir,\n// and validates that the cert is a CA. Failure to load the key produces a warning.\nfunc validateCACertAndKey(l certKeyLocation) error {\n\tif err := validateCACert(l); err != nil {\n\t\treturn err\n\t}\n\n\t_, err := pkiutil.TryLoadKeyFromDisk(l.pkiDir, l.caBaseName)\n\tif err != nil {\n\t\tklog.Warningf(\"assuming external key for %s: %v\", l.uxName, err)\n\t}\n\treturn nil\n}","line":{"from":433,"to":445}} {"id":100000964,"name":"validateSignedCert","signature":"func validateSignedCert(l certKeyLocation) error","file":"cmd/kubeadm/app/phases/certs/certs.go","code":"// validateSignedCert tries to load a x509 certificate and private key from pkiDir and validates\n// that the cert is signed by a given CA\nfunc validateSignedCert(l certKeyLocation) error {\n\t// Try to load CA\n\tcaCert, err := pkiutil.TryLoadCertFromDisk(l.pkiDir, l.caBaseName)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failure loading certificate authority for %s\", l.uxName)\n\t}\n\t// Validate period\n\tCheckCertificatePeriodValidity(l.uxName, caCert)\n\n\treturn validateSignedCertWithCA(l, caCert)\n}","line":{"from":447,"to":459}} {"id":100000965,"name":"validateSignedCertWithCA","signature":"func validateSignedCertWithCA(l certKeyLocation, caCert *x509.Certificate) error","file":"cmd/kubeadm/app/phases/certs/certs.go","code":"// validateSignedCertWithCA tries to load a certificate and private key and\n// validates that the cert is signed by the given caCert\nfunc validateSignedCertWithCA(l certKeyLocation, caCert *x509.Certificate) error {\n\t// Try to load key from the PKI directory\n\t_, err := pkiutil.TryLoadKeyFromDisk(l.pkiDir, l.baseName)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failure loading key for %s\", l.baseName)\n\t}\n\n\t// Try to load certificate from the PKI directory\n\tsignedCert, intermediates, err := pkiutil.TryLoadCertChainFromDisk(l.pkiDir, l.baseName)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failure loading certificate for %s\", l.uxName)\n\t}\n\t// Validate period\n\tCheckCertificatePeriodValidity(l.uxName, signedCert)\n\n\t// Check if the cert is signed by the CA\n\tif err := pkiutil.VerifyCertChain(signedCert, intermediates, caCert); err != nil {\n\t\treturn errors.Wrapf(err, \"certificate %s is not signed by corresponding CA\", l.uxName)\n\t}\n\treturn nil\n}","line":{"from":461,"to":483}} {"id":100000966,"name":"validatePrivatePublicKey","signature":"func validatePrivatePublicKey(l certKeyLocation) error","file":"cmd/kubeadm/app/phases/certs/certs.go","code":"// validatePrivatePublicKey tries to load a private key from pkiDir\nfunc validatePrivatePublicKey(l certKeyLocation) error {\n\t// Try to load key\n\t_, _, err := pkiutil.TryLoadPrivatePublicKeyFromDisk(l.pkiDir, l.baseName)\n\treturn errors.Wrapf(err, \"failure loading key for %s\", l.uxName)\n}","line":{"from":485,"to":490}} {"id":100000967,"name":"validateCertificateWithConfig","signature":"func validateCertificateWithConfig(cert *x509.Certificate, baseName string, cfg *pkiutil.CertConfig) error","file":"cmd/kubeadm/app/phases/certs/certs.go","code":"// validateCertificateWithConfig makes sure that a given certificate is valid at\n// least for the SANs defined in the configuration.\nfunc validateCertificateWithConfig(cert *x509.Certificate, baseName string, cfg *pkiutil.CertConfig) error {\n\tfor _, dnsName := range cfg.AltNames.DNSNames {\n\t\tif err := cert.VerifyHostname(dnsName); err != nil {\n\t\t\treturn errors.Wrapf(err, \"certificate %s is invalid\", baseName)\n\t\t}\n\t}\n\tfor _, ipAddress := range cfg.AltNames.IPs {\n\t\tif err := cert.VerifyHostname(ipAddress.String()); err != nil {\n\t\t\treturn errors.Wrapf(err, \"certificate %s is invalid\", baseName)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":492,"to":506}} {"id":100000968,"name":"CheckCertificatePeriodValidity","signature":"func CheckCertificatePeriodValidity(baseName string, cert *x509.Certificate)","file":"cmd/kubeadm/app/phases/certs/certs.go","code":"// CheckCertificatePeriodValidity takes a certificate and prints a warning if its period\n// is not valid related to the current time. It does so only if the certificate was not validated already\n// by keeping track with a cache.\nfunc CheckCertificatePeriodValidity(baseName string, cert *x509.Certificate) {\n\tcertPeriodValidationMutex.Lock()\n\tdefer certPeriodValidationMutex.Unlock()\n\tif _, exists := certPeriodValidation[baseName]; exists {\n\t\treturn\n\t}\n\tcertPeriodValidation[baseName] = struct{}{}\n\n\tklog.V(5).Infof(\"validating certificate period for %s certificate\", baseName)\n\tif err := pkiutil.ValidateCertPeriod(cert, 0); err != nil {\n\t\tklog.Warningf(\"WARNING: could not validate bounds for certificate %s: %v\", baseName, err)\n\t}\n}","line":{"from":508,"to":523}} {"id":100000969,"name":"newExpirationInfo","signature":"func newExpirationInfo(name string, cert *x509.Certificate, externallyManaged bool) *ExpirationInfo","file":"cmd/kubeadm/app/phases/certs/renewal/expiration.go","code":"// newExpirationInfo returns a new ExpirationInfo\nfunc newExpirationInfo(name string, cert *x509.Certificate, externallyManaged bool) *ExpirationInfo {\n\treturn \u0026ExpirationInfo{\n\t\tName: name,\n\t\tExpirationDate: cert.NotAfter,\n\t\tExternallyManaged: externallyManaged,\n\t}\n}","line":{"from":40,"to":47}} {"id":100000970,"name":"ResidualTime","signature":"func (e *ExpirationInfo) ResidualTime() time.Duration","file":"cmd/kubeadm/app/phases/certs/renewal/expiration.go","code":"// ResidualTime returns the time missing to expiration\nfunc (e *ExpirationInfo) ResidualTime() time.Duration {\n\treturn time.Until(e.ExpirationDate)\n}","line":{"from":49,"to":52}} {"id":100000971,"name":"NewFileRenewer","signature":"func NewFileRenewer(caCert *x509.Certificate, caKey crypto.Signer) *FileRenewer","file":"cmd/kubeadm/app/phases/certs/renewal/filerenewer.go","code":"// NewFileRenewer returns a new certificate renewer that uses given CA cert and key for generating new certificates\nfunc NewFileRenewer(caCert *x509.Certificate, caKey crypto.Signer) *FileRenewer {\n\treturn \u0026FileRenewer{\n\t\tcaCert: caCert,\n\t\tcaKey: caKey,\n\t}\n}","line":{"from":32,"to":38}} {"id":100000972,"name":"Renew","signature":"func (r *FileRenewer) Renew(cfg *pkiutil.CertConfig) (*x509.Certificate, crypto.Signer, error)","file":"cmd/kubeadm/app/phases/certs/renewal/filerenewer.go","code":"// Renew a certificate using a given CA cert and key\nfunc (r *FileRenewer) Renew(cfg *pkiutil.CertConfig) (*x509.Certificate, crypto.Signer, error) {\n\treturn pkiutil.NewCertAndKey(r.caCert, r.caKey, cfg)\n}","line":{"from":40,"to":43}} {"id":100000973,"name":"NewManager","signature":"func NewManager(cfg *kubeadmapi.ClusterConfiguration, kubernetesDir string) (*Manager, error)","file":"cmd/kubeadm/app/phases/certs/renewal/manager.go","code":"// NewManager return a new certificate renewal manager ready for handling certificates in the cluster\nfunc NewManager(cfg *kubeadmapi.ClusterConfiguration, kubernetesDir string) (*Manager, error) {\n\trm := \u0026Manager{\n\t\tcfg: cfg,\n\t\tkubernetesDir: kubernetesDir,\n\t\tcertificates: map[string]*CertificateRenewHandler{},\n\t\tcas: map[string]*CAExpirationHandler{},\n\t}\n\n\t// gets the list of certificates that are expected according to the current cluster configuration\n\tcertListFunc := certsphase.GetDefaultCertList\n\tif cfg.Etcd.External != nil {\n\t\tcertListFunc = certsphase.GetCertsWithoutEtcd\n\t}\n\tcertTree, err := certListFunc().AsMap().CertTree()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create a CertificateRenewHandler for each signed certificate in the certificate tree;\n\t// NB. we are not offering support for renewing CAs; this would cause serious consequences\n\tfor ca, certs := range certTree {\n\t\tfor _, cert := range certs {\n\t\t\t// create a ReadWriter for certificates stored in the K8s local PKI\n\t\t\tpkiReadWriter := newPKICertificateReadWriter(rm.cfg.CertificatesDir, cert.BaseName)\n\n\t\t\t// adds the certificateRenewHandler.\n\t\t\t// PKI certificates are indexed by name, that is a well know constant defined\n\t\t\t// in the certsphase package and that can be reused across all the kubeadm codebase\n\t\t\trm.certificates[cert.Name] = \u0026CertificateRenewHandler{\n\t\t\t\tName: cert.Name,\n\t\t\t\tLongName: cert.LongName,\n\t\t\t\tFileName: cert.BaseName,\n\t\t\t\tCAName: ca.Name,\n\t\t\t\tCABaseName: ca.BaseName, //Nb. this is a path for etcd certs (they are stored in a subfolder)\n\t\t\t\treadwriter: pkiReadWriter,\n\t\t\t}\n\t\t}\n\n\t\tpkiReadWriter := newPKICertificateReadWriter(rm.cfg.CertificatesDir, ca.BaseName)\n\t\trm.cas[ca.Name] = \u0026CAExpirationHandler{\n\t\t\tName: ca.Name,\n\t\t\tLongName: ca.LongName,\n\t\t\tFileName: ca.BaseName,\n\t\t\treadwriter: pkiReadWriter,\n\t\t}\n\t}\n\n\t// gets the list of certificates that should be considered for renewal\n\tkubeConfigs := []struct {\n\t\tlongName string\n\t\tfileName string\n\t}{\n\t\t{\n\t\t\tlongName: \"certificate embedded in the kubeconfig file for the admin to use and for kubeadm itself\",\n\t\t\tfileName: kubeadmconstants.AdminKubeConfigFileName,\n\t\t},\n\t\t{\n\t\t\tlongName: \"certificate embedded in the kubeconfig file for the controller manager to use\",\n\t\t\tfileName: kubeadmconstants.ControllerManagerKubeConfigFileName,\n\t\t},\n\t\t{\n\t\t\tlongName: \"certificate embedded in the kubeconfig file for the scheduler manager to use\",\n\t\t\tfileName: kubeadmconstants.SchedulerKubeConfigFileName,\n\t\t},\n\t\t//NB. we are excluding KubeletKubeConfig from renewal because management of this certificate is delegated to kubelet\n\t}\n\n\t// create a CertificateRenewHandler for each kubeConfig file\n\tfor _, kubeConfig := range kubeConfigs {\n\t\t// create a ReadWriter for certificates embedded in kubeConfig files\n\t\tkubeConfigReadWriter := newKubeconfigReadWriter(kubernetesDir, kubeConfig.fileName,\n\t\t\trm.cfg.CertificatesDir, kubeadmconstants.CACertAndKeyBaseName)\n\n\t\t// adds the certificateRenewHandler.\n\t\t// Certificates embedded kubeConfig files in are indexed by fileName, that is a well know constant defined\n\t\t// in the kubeadm constants package and that can be reused across all the kubeadm codebase\n\t\trm.certificates[kubeConfig.fileName] = \u0026CertificateRenewHandler{\n\t\t\tName: kubeConfig.fileName, // we are using fileName as name, because there is nothing similar outside\n\t\t\tLongName: kubeConfig.longName,\n\t\t\tFileName: kubeConfig.fileName,\n\t\t\tCABaseName: kubeadmconstants.CACertAndKeyBaseName, // all certificates in kubeConfig files are signed by the Kubernetes CA\n\t\t\tCAName: kubeadmconstants.CACertAndKeyBaseName,\n\t\t\treadwriter: kubeConfigReadWriter,\n\t\t}\n\t}\n\n\treturn rm, nil\n}","line":{"from":87,"to":175}} {"id":100000974,"name":"Certificates","signature":"func (rm *Manager) Certificates() []*CertificateRenewHandler","file":"cmd/kubeadm/app/phases/certs/renewal/manager.go","code":"// Certificates returns the list of certificates controlled by this Manager\nfunc (rm *Manager) Certificates() []*CertificateRenewHandler {\n\tcertificates := []*CertificateRenewHandler{}\n\tfor _, h := range rm.certificates {\n\t\tcertificates = append(certificates, h)\n\t}\n\n\tsort.Slice(certificates, func(i, j int) bool { return certificates[i].Name \u003c certificates[j].Name })\n\n\treturn certificates\n}","line":{"from":177,"to":187}} {"id":100000975,"name":"CAs","signature":"func (rm *Manager) CAs() []*CAExpirationHandler","file":"cmd/kubeadm/app/phases/certs/renewal/manager.go","code":"// CAs returns the list of CAs related to the certificates that are controlled by this manager\nfunc (rm *Manager) CAs() []*CAExpirationHandler {\n\tcas := []*CAExpirationHandler{}\n\tfor _, h := range rm.cas {\n\t\tcas = append(cas, h)\n\t}\n\n\tsort.Slice(cas, func(i, j int) bool { return cas[i].Name \u003c cas[j].Name })\n\n\treturn cas\n}","line":{"from":189,"to":199}} {"id":100000976,"name":"RenewUsingLocalCA","signature":"func (rm *Manager) RenewUsingLocalCA(name string) (bool, error)","file":"cmd/kubeadm/app/phases/certs/renewal/manager.go","code":"// RenewUsingLocalCA executes certificate renewal using local certificate authorities for generating new certs.\n// For PKI certificates, use the name defined in the certsphase package, while for certificates\n// embedded in the kubeConfig files, use the kubeConfig file name defined in the kubeadm constants package.\n// If you use the CertificateRenewHandler returned by Certificates func, handler.Name already contains the right value.\nfunc (rm *Manager) RenewUsingLocalCA(name string) (bool, error) {\n\thandler, ok := rm.certificates[name]\n\tif !ok {\n\t\treturn false, errors.Errorf(\"%s is not a valid certificate for this cluster\", name)\n\t}\n\n\t// checks if the certificate is externally managed (CA certificate provided without the certificate key)\n\texternallyManaged, err := rm.IsExternallyManaged(handler.CABaseName)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t// in case of external CA it is not possible to renew certificates, then return early\n\tif externallyManaged {\n\t\treturn false, nil\n\t}\n\n\t// reads the current certificate\n\tcert, err := handler.readwriter.Read()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t// extract the certificate config\n\tcfg := \u0026pkiutil.CertConfig{\n\t\tConfig: certToConfig(cert),\n\t\tPublicKeyAlgorithm: rm.cfg.PublicKeyAlgorithm(),\n\t}\n\n\t// reads the CA\n\tcaCert, caKey, err := certsphase.LoadCertificateAuthority(rm.cfg.CertificatesDir, handler.CABaseName)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t// create a new certificate with the same config\n\tnewCert, newKey, err := NewFileRenewer(caCert, caKey).Renew(cfg)\n\tif err != nil {\n\t\treturn false, errors.Wrapf(err, \"failed to renew certificate %s\", name)\n\t}\n\n\t// writes the new certificate to disk\n\terr = handler.readwriter.Write(newCert, newKey)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn true, nil\n}","line":{"from":201,"to":253}} {"id":100000977,"name":"CreateRenewCSR","signature":"func (rm *Manager) CreateRenewCSR(name, outdir string) error","file":"cmd/kubeadm/app/phases/certs/renewal/manager.go","code":"// CreateRenewCSR generates CSR request for certificate renewal.\n// For PKI certificates, use the name defined in the certsphase package, while for certificates\n// embedded in the kubeConfig files, use the kubeConfig file name defined in the kubeadm constants package.\n// If you use the CertificateRenewHandler returned by Certificates func, handler.Name already contains the right value.\nfunc (rm *Manager) CreateRenewCSR(name, outdir string) error {\n\thandler, ok := rm.certificates[name]\n\tif !ok {\n\t\treturn errors.Errorf(\"%s is not a known certificate\", name)\n\t}\n\n\t// reads the current certificate\n\tcert, err := handler.readwriter.Read()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// extracts the certificate config\n\tcfg := \u0026pkiutil.CertConfig{\n\t\tConfig: certToConfig(cert),\n\t\tPublicKeyAlgorithm: rm.cfg.PublicKeyAlgorithm(),\n\t}\n\n\t// generates the CSR request and save it\n\tcsr, key, err := pkiutil.NewCSRAndKey(cfg)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failure while generating %s CSR and key\", name)\n\t}\n\tif err := pkiutil.WriteKey(outdir, name, key); err != nil {\n\t\treturn errors.Wrapf(err, \"failure while saving %s key\", name)\n\t}\n\n\tif err := pkiutil.WriteCSR(outdir, name, csr); err != nil {\n\t\treturn errors.Wrapf(err, \"failure while saving %s CSR\", name)\n\t}\n\n\treturn nil\n}","line":{"from":255,"to":291}} {"id":100000978,"name":"CertificateExists","signature":"func (rm *Manager) CertificateExists(name string) (bool, error)","file":"cmd/kubeadm/app/phases/certs/renewal/manager.go","code":"// CertificateExists returns true if a certificate exists.\nfunc (rm *Manager) CertificateExists(name string) (bool, error) {\n\thandler, ok := rm.certificates[name]\n\tif !ok {\n\t\treturn false, errors.Errorf(\"%s is not a known certificate\", name)\n\t}\n\n\treturn handler.readwriter.Exists(), nil\n}","line":{"from":293,"to":301}} {"id":100000979,"name":"GetCertificateExpirationInfo","signature":"func (rm *Manager) GetCertificateExpirationInfo(name string) (*ExpirationInfo, error)","file":"cmd/kubeadm/app/phases/certs/renewal/manager.go","code":"// GetCertificateExpirationInfo returns certificate expiration info.\n// For PKI certificates, use the name defined in the certsphase package, while for certificates\n// embedded in the kubeConfig files, use the kubeConfig file name defined in the kubeadm constants package.\n// If you use the CertificateRenewHandler returned by Certificates func, handler.Name already contains the right value.\nfunc (rm *Manager) GetCertificateExpirationInfo(name string) (*ExpirationInfo, error) {\n\thandler, ok := rm.certificates[name]\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"%s is not a known certificate\", name)\n\t}\n\n\t// checks if the certificate is externally managed (CA certificate provided without the certificate key)\n\texternallyManaged, err := rm.IsExternallyManaged(handler.CABaseName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// reads the current certificate\n\tcert, err := handler.readwriter.Read()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// returns the certificate expiration info\n\treturn newExpirationInfo(name, cert, externallyManaged), nil\n}","line":{"from":303,"to":327}} {"id":100000980,"name":"CAExists","signature":"func (rm *Manager) CAExists(name string) (bool, error)","file":"cmd/kubeadm/app/phases/certs/renewal/manager.go","code":"// CAExists returns true if a certificate authority exists.\nfunc (rm *Manager) CAExists(name string) (bool, error) {\n\thandler, ok := rm.cas[name]\n\tif !ok {\n\t\treturn false, errors.Errorf(\"%s is not a known certificate\", name)\n\t}\n\n\treturn handler.readwriter.Exists(), nil\n}","line":{"from":329,"to":337}} {"id":100000981,"name":"GetCAExpirationInfo","signature":"func (rm *Manager) GetCAExpirationInfo(name string) (*ExpirationInfo, error)","file":"cmd/kubeadm/app/phases/certs/renewal/manager.go","code":"// GetCAExpirationInfo returns CA expiration info.\nfunc (rm *Manager) GetCAExpirationInfo(name string) (*ExpirationInfo, error) {\n\thandler, ok := rm.cas[name]\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"%s is not a known CA\", name)\n\t}\n\n\t// checks if the CA is externally managed (CA certificate provided without the certificate key)\n\texternallyManaged, err := rm.IsExternallyManaged(handler.FileName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// reads the current CA\n\tca, err := handler.readwriter.Read()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// returns the CA expiration info\n\treturn newExpirationInfo(name, ca, externallyManaged), nil\n}","line":{"from":339,"to":360}} {"id":100000982,"name":"IsExternallyManaged","signature":"func (rm *Manager) IsExternallyManaged(caBaseName string) (bool, error)","file":"cmd/kubeadm/app/phases/certs/renewal/manager.go","code":"// IsExternallyManaged checks if we are in the external CA case (CA certificate provided without the certificate key)\nfunc (rm *Manager) IsExternallyManaged(caBaseName string) (bool, error) {\n\tswitch caBaseName {\n\tcase kubeadmconstants.CACertAndKeyBaseName:\n\t\texternallyManaged, err := certsphase.UsingExternalCA(rm.cfg)\n\t\tif err != nil {\n\t\t\treturn false, errors.Wrapf(err, \"Error checking external CA condition for %s certificate authority\", caBaseName)\n\t\t}\n\t\treturn externallyManaged, nil\n\tcase kubeadmconstants.FrontProxyCACertAndKeyBaseName:\n\t\texternallyManaged, err := certsphase.UsingExternalFrontProxyCA(rm.cfg)\n\t\tif err != nil {\n\t\t\treturn false, errors.Wrapf(err, \"Error checking external CA condition for %s certificate authority\", caBaseName)\n\t\t}\n\t\treturn externallyManaged, nil\n\tcase kubeadmconstants.EtcdCACertAndKeyBaseName:\n\t\texternallyManaged, err := certsphase.UsingExternalEtcdCA(rm.cfg)\n\t\tif err != nil {\n\t\t\treturn false, errors.Wrapf(err, \"Error checking external CA condition for %s certificate authority\", caBaseName)\n\t\t}\n\t\treturn externallyManaged, nil\n\tdefault:\n\t\treturn false, errors.Errorf(\"unknown certificate authority %s\", caBaseName)\n\t}\n}","line":{"from":362,"to":386}} {"id":100000983,"name":"certToConfig","signature":"func certToConfig(cert *x509.Certificate) certutil.Config","file":"cmd/kubeadm/app/phases/certs/renewal/manager.go","code":"func certToConfig(cert *x509.Certificate) certutil.Config {\n\treturn certutil.Config{\n\t\tCommonName: cert.Subject.CommonName,\n\t\tOrganization: cert.Subject.Organization,\n\t\tAltNames: certutil.AltNames{\n\t\t\tIPs: cert.IPAddresses,\n\t\t\tDNSNames: cert.DNSNames,\n\t\t},\n\t\tUsages: cert.ExtKeyUsage,\n\t}\n}","line":{"from":388,"to":398}} {"id":100000984,"name":"newPKICertificateReadWriter","signature":"func newPKICertificateReadWriter(certificateDir string, baseName string) *pkiCertificateReadWriter","file":"cmd/kubeadm/app/phases/certs/renewal/readwriter.go","code":"// newPKICertificateReadWriter return a new pkiCertificateReadWriter\nfunc newPKICertificateReadWriter(certificateDir string, baseName string) *pkiCertificateReadWriter {\n\treturn \u0026pkiCertificateReadWriter{\n\t\tbaseName: baseName,\n\t\tcertificateDir: certificateDir,\n\t}\n}","line":{"from":55,"to":61}} {"id":100000985,"name":"Exists","signature":"func (rw *pkiCertificateReadWriter) Exists() bool","file":"cmd/kubeadm/app/phases/certs/renewal/readwriter.go","code":"// Exists checks if a certificate exist\nfunc (rw *pkiCertificateReadWriter) Exists() bool {\n\tcertificatePath, _ := pkiutil.PathsForCertAndKey(rw.certificateDir, rw.baseName)\n\treturn fileExists(certificatePath)\n}","line":{"from":63,"to":67}} {"id":100000986,"name":"fileExists","signature":"func fileExists(filename string) bool","file":"cmd/kubeadm/app/phases/certs/renewal/readwriter.go","code":"func fileExists(filename string) bool {\n\tinfo, err := os.Stat(filename)\n\tif os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn !info.IsDir()\n}","line":{"from":69,"to":75}} {"id":100000987,"name":"Read","signature":"func (rw *pkiCertificateReadWriter) Read() (*x509.Certificate, error)","file":"cmd/kubeadm/app/phases/certs/renewal/readwriter.go","code":"// Read a certificate from a file the K8s pki managed by kubeadm\nfunc (rw *pkiCertificateReadWriter) Read() (*x509.Certificate, error) {\n\tcertificatePath, _ := pkiutil.PathsForCertAndKey(rw.certificateDir, rw.baseName)\n\tcerts, err := certutil.CertsFromFile(certificatePath)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to load existing certificate %s\", rw.baseName)\n\t}\n\n\t// Safely pick the first one because the sender's certificate must come first in the list.\n\t// For details, see: https://www.rfc-editor.org/rfc/rfc4346#section-7.4.2\n\treturn certs[0], nil\n}","line":{"from":77,"to":88}} {"id":100000988,"name":"Write","signature":"func (rw *pkiCertificateReadWriter) Write(newCert *x509.Certificate, newKey crypto.Signer) error","file":"cmd/kubeadm/app/phases/certs/renewal/readwriter.go","code":"// Write a certificate to files in the K8s pki managed by kubeadm\nfunc (rw *pkiCertificateReadWriter) Write(newCert *x509.Certificate, newKey crypto.Signer) error {\n\tif err := pkiutil.WriteCertAndKey(rw.certificateDir, rw.baseName, newCert, newKey); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to write new certificate %s\", rw.baseName)\n\t}\n\treturn nil\n}","line":{"from":90,"to":96}} {"id":100000989,"name":"newKubeconfigReadWriter","signature":"func newKubeconfigReadWriter(kubernetesDir string, kubeConfigFileName string, certificateDir, baseName string) *kubeConfigReadWriter","file":"cmd/kubeadm/app/phases/certs/renewal/readwriter.go","code":"// newKubeconfigReadWriter return a new kubeConfigReadWriter\nfunc newKubeconfigReadWriter(kubernetesDir string, kubeConfigFileName string, certificateDir, baseName string) *kubeConfigReadWriter {\n\treturn \u0026kubeConfigReadWriter{\n\t\tkubernetesDir: kubernetesDir,\n\t\tkubeConfigFileName: kubeConfigFileName,\n\t\tkubeConfigFilePath: filepath.Join(kubernetesDir, kubeConfigFileName),\n\t\tcertificateDir: certificateDir,\n\t\tbaseName: baseName,\n\t}\n}","line":{"from":111,"to":120}} {"id":100000990,"name":"Exists","signature":"func (rw *kubeConfigReadWriter) Exists() bool","file":"cmd/kubeadm/app/phases/certs/renewal/readwriter.go","code":"// Exists checks if a certificate embedded in kubeConfig file exists\nfunc (rw *kubeConfigReadWriter) Exists() bool {\n\treturn fileExists(rw.kubeConfigFilePath)\n}","line":{"from":122,"to":125}} {"id":100000991,"name":"Read","signature":"func (rw *kubeConfigReadWriter) Read() (*x509.Certificate, error)","file":"cmd/kubeadm/app/phases/certs/renewal/readwriter.go","code":"// Read a certificate embedded in kubeConfig file managed by kubeadm.\n// Please note that the kubeConfig file itself is kept in the ReadWriter state thus allowing\n// to preserve the attributes (Context, Servers, AuthInfo etc.)\nfunc (rw *kubeConfigReadWriter) Read() (*x509.Certificate, error) {\n\t// try to load the kubeConfig file\n\tkubeConfig, err := clientcmd.LoadFromFile(rw.kubeConfigFilePath)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to load kubeConfig file %s\", rw.kubeConfigFilePath)\n\t}\n\n\t// The CA cert is required for updating kubeconfig files.\n\t// For local CA renewal, the local CA on disk could have changed, thus a reload is needed.\n\t// For CSR renewal we assume the same CA on disk is mounted for usage with KCM's\n\t// '--cluster-signing-cert-file' flag.\n\tcertificatePath, _ := pkiutil.PathsForCertAndKey(rw.certificateDir, rw.baseName)\n\tcaCerts, err := certutil.CertsFromFile(certificatePath)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to load existing certificate %s\", rw.baseName)\n\t}\n\n\t// Safely pick the first one because the sender's certificate must come first in the list.\n\t// For details, see: https://www.rfc-editor.org/rfc/rfc4346#section-7.4.2\n\trw.caCert = caCerts[0]\n\n\t// get current context\n\tif _, ok := kubeConfig.Contexts[kubeConfig.CurrentContext]; !ok {\n\t\treturn nil, errors.Errorf(\"invalid kubeConfig file %s: missing context %s\", rw.kubeConfigFilePath, kubeConfig.CurrentContext)\n\t}\n\n\t// get cluster info for current context and ensure a server certificate is embedded in it\n\tclusterName := kubeConfig.Contexts[kubeConfig.CurrentContext].Cluster\n\tif _, ok := kubeConfig.Clusters[clusterName]; !ok {\n\t\treturn nil, errors.Errorf(\"invalid kubeConfig file %s: missing cluster %s\", rw.kubeConfigFilePath, clusterName)\n\t}\n\n\tcluster := kubeConfig.Clusters[clusterName]\n\tif len(cluster.CertificateAuthorityData) == 0 {\n\t\treturn nil, errors.Errorf(\"kubeConfig file %s does not have an embedded server certificate\", rw.kubeConfigFilePath)\n\t}\n\n\t// get auth info for current context and ensure a client certificate is embedded in it\n\tauthInfoName := kubeConfig.Contexts[kubeConfig.CurrentContext].AuthInfo\n\tif _, ok := kubeConfig.AuthInfos[authInfoName]; !ok {\n\t\treturn nil, errors.Errorf(\"invalid kubeConfig file %s: missing authInfo %s\", rw.kubeConfigFilePath, authInfoName)\n\t}\n\n\tauthInfo := kubeConfig.AuthInfos[authInfoName]\n\tif len(authInfo.ClientCertificateData) == 0 {\n\t\treturn nil, errors.Errorf(\"kubeConfig file %s does not have an embedded client certificate\", rw.kubeConfigFilePath)\n\t}\n\n\t// parse the client certificate, retrieve the cert config and then renew it\n\tcerts, err := certutil.ParseCertsPEM(authInfo.ClientCertificateData)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"kubeConfig file %s does not contain a valid client certificate\", rw.kubeConfigFilePath)\n\t}\n\n\trw.kubeConfig = kubeConfig\n\n\treturn certs[0], nil\n}","line":{"from":127,"to":187}} {"id":100000992,"name":"Write","signature":"func (rw *kubeConfigReadWriter) Write(newCert *x509.Certificate, newKey crypto.Signer) error","file":"cmd/kubeadm/app/phases/certs/renewal/readwriter.go","code":"// Write a certificate embedded in kubeConfig file managed by kubeadm\n// Please note that all the other attribute of the kubeConfig file are preserved, but this\n// requires to call Read before Write\nfunc (rw *kubeConfigReadWriter) Write(newCert *x509.Certificate, newKey crypto.Signer) error {\n\t// check if Read was called before Write\n\tif rw.kubeConfig == nil {\n\t\treturn errors.Errorf(\"failed to Write kubeConfig file with renewed certs. It is necessary to call Read before Write\")\n\t}\n\n\t// encodes the new key\n\tencodedClientKey, err := keyutil.MarshalPrivateKeyToPEM(newKey)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to marshal private key to PEM\")\n\t}\n\n\t// Update the embedded CA in the kubeconfig file.\n\t// This assumes that the user has kept the current context to the desired one.\n\tclusterName := rw.kubeConfig.Contexts[rw.kubeConfig.CurrentContext].Cluster\n\tcluster := rw.kubeConfig.Clusters[clusterName]\n\tcluster.CertificateAuthorityData = pkiutil.EncodeCertPEM(rw.caCert)\n\n\t// get auth info for current context and ensure a client certificate is embedded in it\n\tauthInfoName := rw.kubeConfig.Contexts[rw.kubeConfig.CurrentContext].AuthInfo\n\n\t// create a kubeConfig copy with the new client certs\n\tnewConfig := rw.kubeConfig.DeepCopy()\n\tnewConfig.AuthInfos[authInfoName].ClientKeyData = encodedClientKey\n\tnewConfig.AuthInfos[authInfoName].ClientCertificateData = pkiutil.EncodeCertPEM(newCert)\n\n\t// writes the kubeConfig to disk\n\treturn clientcmd.WriteToFile(*newConfig, rw.kubeConfigFilePath)\n}","line":{"from":189,"to":220}} {"id":100000993,"name":"CreateInitStaticPodManifestFiles","signature":"func CreateInitStaticPodManifestFiles(manifestDir, patchesDir string, cfg *kubeadmapi.InitConfiguration, isDryRun bool) error","file":"cmd/kubeadm/app/phases/controlplane/manifests.go","code":"// CreateInitStaticPodManifestFiles will write all static pod manifest files needed to bring up the control plane.\nfunc CreateInitStaticPodManifestFiles(manifestDir, patchesDir string, cfg *kubeadmapi.InitConfiguration, isDryRun bool) error {\n\tklog.V(1).Infoln(\"[control-plane] creating static Pod files\")\n\treturn CreateStaticPodFiles(manifestDir, patchesDir, \u0026cfg.ClusterConfiguration, \u0026cfg.LocalAPIEndpoint, isDryRun, kubeadmconstants.KubeAPIServer, kubeadmconstants.KubeControllerManager, kubeadmconstants.KubeScheduler)\n}","line":{"from":43,"to":47}} {"id":100000994,"name":"GetStaticPodSpecs","signature":"func GetStaticPodSpecs(cfg *kubeadmapi.ClusterConfiguration, endpoint *kubeadmapi.APIEndpoint) map[string]v1.Pod","file":"cmd/kubeadm/app/phases/controlplane/manifests.go","code":"// GetStaticPodSpecs returns all staticPodSpecs actualized to the context of the current configuration\n// NB. this method holds the information about how kubeadm creates static pod manifests.\nfunc GetStaticPodSpecs(cfg *kubeadmapi.ClusterConfiguration, endpoint *kubeadmapi.APIEndpoint) map[string]v1.Pod {\n\t// Get the required hostpath mounts\n\tmounts := getHostPathVolumesForTheControlPlane(cfg)\n\n\t// Prepare static pod specs\n\tstaticPodSpecs := map[string]v1.Pod{\n\t\tkubeadmconstants.KubeAPIServer: staticpodutil.ComponentPod(v1.Container{\n\t\t\tName: kubeadmconstants.KubeAPIServer,\n\t\t\tImage: images.GetKubernetesImage(kubeadmconstants.KubeAPIServer, cfg),\n\t\t\tImagePullPolicy: v1.PullIfNotPresent,\n\t\t\tCommand: getAPIServerCommand(cfg, endpoint),\n\t\t\tVolumeMounts: staticpodutil.VolumeMountMapToSlice(mounts.GetVolumeMounts(kubeadmconstants.KubeAPIServer)),\n\t\t\tLivenessProbe: staticpodutil.LivenessProbe(staticpodutil.GetAPIServerProbeAddress(endpoint), \"/livez\", int(endpoint.BindPort), v1.URISchemeHTTPS),\n\t\t\tReadinessProbe: staticpodutil.ReadinessProbe(staticpodutil.GetAPIServerProbeAddress(endpoint), \"/readyz\", int(endpoint.BindPort), v1.URISchemeHTTPS),\n\t\t\tStartupProbe: staticpodutil.StartupProbe(staticpodutil.GetAPIServerProbeAddress(endpoint), \"/livez\", int(endpoint.BindPort), v1.URISchemeHTTPS, cfg.APIServer.TimeoutForControlPlane),\n\t\t\tResources: staticpodutil.ComponentResources(\"250m\"),\n\t\t\tEnv: kubeadmutil.GetProxyEnvVars(),\n\t\t}, mounts.GetVolumes(kubeadmconstants.KubeAPIServer),\n\t\t\tmap[string]string{kubeadmconstants.KubeAPIServerAdvertiseAddressEndpointAnnotationKey: endpoint.String()}),\n\t\tkubeadmconstants.KubeControllerManager: staticpodutil.ComponentPod(v1.Container{\n\t\t\tName: kubeadmconstants.KubeControllerManager,\n\t\t\tImage: images.GetKubernetesImage(kubeadmconstants.KubeControllerManager, cfg),\n\t\t\tImagePullPolicy: v1.PullIfNotPresent,\n\t\t\tCommand: getControllerManagerCommand(cfg),\n\t\t\tVolumeMounts: staticpodutil.VolumeMountMapToSlice(mounts.GetVolumeMounts(kubeadmconstants.KubeControllerManager)),\n\t\t\tLivenessProbe: staticpodutil.LivenessProbe(staticpodutil.GetControllerManagerProbeAddress(cfg), \"/healthz\", kubeadmconstants.KubeControllerManagerPort, v1.URISchemeHTTPS),\n\t\t\tStartupProbe: staticpodutil.StartupProbe(staticpodutil.GetControllerManagerProbeAddress(cfg), \"/healthz\", kubeadmconstants.KubeControllerManagerPort, v1.URISchemeHTTPS, cfg.APIServer.TimeoutForControlPlane),\n\t\t\tResources: staticpodutil.ComponentResources(\"200m\"),\n\t\t\tEnv: kubeadmutil.GetProxyEnvVars(),\n\t\t}, mounts.GetVolumes(kubeadmconstants.KubeControllerManager), nil),\n\t\tkubeadmconstants.KubeScheduler: staticpodutil.ComponentPod(v1.Container{\n\t\t\tName: kubeadmconstants.KubeScheduler,\n\t\t\tImage: images.GetKubernetesImage(kubeadmconstants.KubeScheduler, cfg),\n\t\t\tImagePullPolicy: v1.PullIfNotPresent,\n\t\t\tCommand: getSchedulerCommand(cfg),\n\t\t\tVolumeMounts: staticpodutil.VolumeMountMapToSlice(mounts.GetVolumeMounts(kubeadmconstants.KubeScheduler)),\n\t\t\tLivenessProbe: staticpodutil.LivenessProbe(staticpodutil.GetSchedulerProbeAddress(cfg), \"/healthz\", kubeadmconstants.KubeSchedulerPort, v1.URISchemeHTTPS),\n\t\t\tStartupProbe: staticpodutil.StartupProbe(staticpodutil.GetSchedulerProbeAddress(cfg), \"/healthz\", kubeadmconstants.KubeSchedulerPort, v1.URISchemeHTTPS, cfg.APIServer.TimeoutForControlPlane),\n\t\t\tResources: staticpodutil.ComponentResources(\"100m\"),\n\t\t\tEnv: kubeadmutil.GetProxyEnvVars(),\n\t\t}, mounts.GetVolumes(kubeadmconstants.KubeScheduler), nil),\n\t}\n\treturn staticPodSpecs\n}","line":{"from":49,"to":94}} {"id":100000995,"name":"CreateStaticPodFiles","signature":"func CreateStaticPodFiles(manifestDir, patchesDir string, cfg *kubeadmapi.ClusterConfiguration, endpoint *kubeadmapi.APIEndpoint, isDryRun bool, componentNames ...string) error","file":"cmd/kubeadm/app/phases/controlplane/manifests.go","code":"// CreateStaticPodFiles creates all the requested static pod files.\nfunc CreateStaticPodFiles(manifestDir, patchesDir string, cfg *kubeadmapi.ClusterConfiguration, endpoint *kubeadmapi.APIEndpoint, isDryRun bool, componentNames ...string) error {\n\t// gets the StaticPodSpecs, actualized for the current ClusterConfiguration\n\tklog.V(1).Infoln(\"[control-plane] getting StaticPodSpecs\")\n\tspecs := GetStaticPodSpecs(cfg, endpoint)\n\n\tvar usersAndGroups *users.UsersAndGroups\n\tvar err error\n\tif features.Enabled(cfg.FeatureGates, features.RootlessControlPlane) {\n\t\tif isDryRun {\n\t\t\tfmt.Printf(\"[control-plane] Would create users and groups for %+v to run as non-root\\n\", componentNames)\n\t\t} else {\n\t\t\tusersAndGroups, err = staticpodutil.GetUsersAndGroups()\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"failed to create users and groups\")\n\t\t\t}\n\t\t}\n\t}\n\n\t// creates required static pod specs\n\tfor _, componentName := range componentNames {\n\t\t// retrieves the StaticPodSpec for given component\n\t\tspec, exists := specs[componentName]\n\t\tif !exists {\n\t\t\treturn errors.Errorf(\"couldn't retrieve StaticPodSpec for %q\", componentName)\n\t\t}\n\n\t\t// print all volumes that are mounted\n\t\tfor _, v := range spec.Spec.Volumes {\n\t\t\tklog.V(2).Infof(\"[control-plane] adding volume %q for component %q\", v.Name, componentName)\n\t\t}\n\n\t\tif features.Enabled(cfg.FeatureGates, features.RootlessControlPlane) {\n\t\t\tif isDryRun {\n\t\t\t\tfmt.Printf(\"[control-plane] Would update static pod manifest for %q to run run as non-root\\n\", componentName)\n\t\t\t} else {\n\t\t\t\tif usersAndGroups != nil {\n\t\t\t\t\tif err := staticpodutil.RunComponentAsNonRoot(componentName, \u0026spec, usersAndGroups, cfg); err != nil {\n\t\t\t\t\t\treturn errors.Wrapf(err, \"failed to run component %q as non-root\", componentName)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// if patchesDir is defined, patch the static Pod manifest\n\t\tif patchesDir != \"\" {\n\t\t\tpatchedSpec, err := staticpodutil.PatchStaticPod(\u0026spec, patchesDir, os.Stdout)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"failed to patch static Pod manifest file for %q\", componentName)\n\t\t\t}\n\t\t\tspec = *patchedSpec\n\t\t}\n\n\t\t// writes the StaticPodSpec to disk\n\t\tif err := staticpodutil.WriteStaticPodToDisk(componentName, manifestDir, spec); err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to create static pod manifest file for %q\", componentName)\n\t\t}\n\n\t\tklog.V(1).Infof(\"[control-plane] wrote static Pod manifest for component %q to %q\\n\", componentName, kubeadmconstants.GetStaticPodFilepath(componentName, manifestDir))\n\t}\n\n\treturn nil\n}","line":{"from":96,"to":158}} {"id":100000996,"name":"getAPIServerCommand","signature":"func getAPIServerCommand(cfg *kubeadmapi.ClusterConfiguration, localAPIEndpoint *kubeadmapi.APIEndpoint) []string","file":"cmd/kubeadm/app/phases/controlplane/manifests.go","code":"// getAPIServerCommand builds the right API server command from the given config object and version\nfunc getAPIServerCommand(cfg *kubeadmapi.ClusterConfiguration, localAPIEndpoint *kubeadmapi.APIEndpoint) []string {\n\tdefaultArguments := map[string]string{\n\t\t\"advertise-address\": localAPIEndpoint.AdvertiseAddress,\n\t\t\"enable-admission-plugins\": \"NodeRestriction\",\n\t\t\"service-cluster-ip-range\": cfg.Networking.ServiceSubnet,\n\t\t\"service-account-key-file\": filepath.Join(cfg.CertificatesDir, kubeadmconstants.ServiceAccountPublicKeyName),\n\t\t\"service-account-signing-key-file\": filepath.Join(cfg.CertificatesDir, kubeadmconstants.ServiceAccountPrivateKeyName),\n\t\t\"service-account-issuer\": fmt.Sprintf(\"https://kubernetes.default.svc.%s\", cfg.Networking.DNSDomain),\n\t\t\"client-ca-file\": filepath.Join(cfg.CertificatesDir, kubeadmconstants.CACertName),\n\t\t\"tls-cert-file\": filepath.Join(cfg.CertificatesDir, kubeadmconstants.APIServerCertName),\n\t\t\"tls-private-key-file\": filepath.Join(cfg.CertificatesDir, kubeadmconstants.APIServerKeyName),\n\t\t\"kubelet-client-certificate\": filepath.Join(cfg.CertificatesDir, kubeadmconstants.APIServerKubeletClientCertName),\n\t\t\"kubelet-client-key\": filepath.Join(cfg.CertificatesDir, kubeadmconstants.APIServerKubeletClientKeyName),\n\t\t\"enable-bootstrap-token-auth\": \"true\",\n\t\t\"secure-port\": fmt.Sprintf(\"%d\", localAPIEndpoint.BindPort),\n\t\t\"allow-privileged\": \"true\",\n\t\t\"kubelet-preferred-address-types\": \"InternalIP,ExternalIP,Hostname\",\n\t\t// add options to configure the front proxy. Without the generated client cert, this will never be useable\n\t\t// so add it unconditionally with recommended values\n\t\t\"requestheader-username-headers\": \"X-Remote-User\",\n\t\t\"requestheader-group-headers\": \"X-Remote-Group\",\n\t\t\"requestheader-extra-headers-prefix\": \"X-Remote-Extra-\",\n\t\t\"requestheader-client-ca-file\": filepath.Join(cfg.CertificatesDir, kubeadmconstants.FrontProxyCACertName),\n\t\t\"requestheader-allowed-names\": \"front-proxy-client\",\n\t\t\"proxy-client-cert-file\": filepath.Join(cfg.CertificatesDir, kubeadmconstants.FrontProxyClientCertName),\n\t\t\"proxy-client-key-file\": filepath.Join(cfg.CertificatesDir, kubeadmconstants.FrontProxyClientKeyName),\n\t}\n\n\tcommand := []string{\"kube-apiserver\"}\n\n\t// If the user set endpoints for an external etcd cluster\n\tif cfg.Etcd.External != nil {\n\t\tdefaultArguments[\"etcd-servers\"] = strings.Join(cfg.Etcd.External.Endpoints, \",\")\n\n\t\t// Use any user supplied etcd certificates\n\t\tif cfg.Etcd.External.CAFile != \"\" {\n\t\t\tdefaultArguments[\"etcd-cafile\"] = cfg.Etcd.External.CAFile\n\t\t}\n\t\tif cfg.Etcd.External.CertFile != \"\" \u0026\u0026 cfg.Etcd.External.KeyFile != \"\" {\n\t\t\tdefaultArguments[\"etcd-certfile\"] = cfg.Etcd.External.CertFile\n\t\t\tdefaultArguments[\"etcd-keyfile\"] = cfg.Etcd.External.KeyFile\n\t\t}\n\t} else {\n\t\t// Default to etcd static pod on localhost\n\t\t// localhost IP family should be the same that the AdvertiseAddress\n\t\tetcdLocalhostAddress := \"127.0.0.1\"\n\t\tif utilsnet.IsIPv6String(localAPIEndpoint.AdvertiseAddress) {\n\t\t\tetcdLocalhostAddress = \"::1\"\n\t\t}\n\t\tdefaultArguments[\"etcd-servers\"] = fmt.Sprintf(\"https://%s\", net.JoinHostPort(etcdLocalhostAddress, strconv.Itoa(kubeadmconstants.EtcdListenClientPort)))\n\t\tdefaultArguments[\"etcd-cafile\"] = filepath.Join(cfg.CertificatesDir, kubeadmconstants.EtcdCACertName)\n\t\tdefaultArguments[\"etcd-certfile\"] = filepath.Join(cfg.CertificatesDir, kubeadmconstants.APIServerEtcdClientCertName)\n\t\tdefaultArguments[\"etcd-keyfile\"] = filepath.Join(cfg.CertificatesDir, kubeadmconstants.APIServerEtcdClientKeyName)\n\n\t\t// Apply user configurations for local etcd\n\t\tif cfg.Etcd.Local != nil {\n\t\t\tif value, ok := cfg.Etcd.Local.ExtraArgs[\"advertise-client-urls\"]; ok {\n\t\t\t\tdefaultArguments[\"etcd-servers\"] = value\n\t\t\t}\n\t\t}\n\t}\n\n\tif cfg.APIServer.ExtraArgs == nil {\n\t\tcfg.APIServer.ExtraArgs = map[string]string{}\n\t}\n\tcfg.APIServer.ExtraArgs[\"authorization-mode\"] = getAuthzModes(cfg.APIServer.ExtraArgs[\"authorization-mode\"])\n\tcommand = append(command, kubeadmutil.BuildArgumentListFromMap(defaultArguments, cfg.APIServer.ExtraArgs)...)\n\n\treturn command\n}","line":{"from":160,"to":230}} {"id":100000997,"name":"getAuthzModes","signature":"func getAuthzModes(authzModeExtraArgs string) string","file":"cmd/kubeadm/app/phases/controlplane/manifests.go","code":"// getAuthzModes gets the authorization-related parameters to the api server\n// Node,RBAC is the default mode if nothing is passed to kubeadm. User provided modes override\n// the default.\nfunc getAuthzModes(authzModeExtraArgs string) string {\n\tdefaultMode := []string{\n\t\tkubeadmconstants.ModeNode,\n\t\tkubeadmconstants.ModeRBAC,\n\t}\n\n\tif len(authzModeExtraArgs) \u003e 0 {\n\t\tmode := []string{}\n\t\tfor _, requested := range strings.Split(authzModeExtraArgs, \",\") {\n\t\t\tif isValidAuthzMode(requested) {\n\t\t\t\tmode = append(mode, requested)\n\t\t\t} else {\n\t\t\t\tklog.Warningf(\"ignoring unknown kube-apiserver authorization-mode %q\", requested)\n\t\t\t}\n\t\t}\n\n\t\t// only return the user provided mode if at least one was valid\n\t\tif len(mode) \u003e 0 {\n\t\t\tif !compareAuthzModes(defaultMode, mode) {\n\t\t\t\tklog.Warningf(\"the default kube-apiserver authorization-mode is %q; using %q\",\n\t\t\t\t\tstrings.Join(defaultMode, \",\"),\n\t\t\t\t\tstrings.Join(mode, \",\"),\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn strings.Join(mode, \",\")\n\t\t}\n\t}\n\treturn strings.Join(defaultMode, \",\")\n}","line":{"from":232,"to":263}} {"id":100000998,"name":"compareAuthzModes","signature":"func compareAuthzModes(a, b []string) bool","file":"cmd/kubeadm/app/phases/controlplane/manifests.go","code":"// compareAuthzModes compares two given authz modes and returns false if they do not match\nfunc compareAuthzModes(a, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i, m := range a {\n\t\tif m != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":265,"to":276}} {"id":100000999,"name":"isValidAuthzMode","signature":"func isValidAuthzMode(authzMode string) bool","file":"cmd/kubeadm/app/phases/controlplane/manifests.go","code":"func isValidAuthzMode(authzMode string) bool {\n\tallModes := []string{\n\t\tkubeadmconstants.ModeNode,\n\t\tkubeadmconstants.ModeRBAC,\n\t\tkubeadmconstants.ModeWebhook,\n\t\tkubeadmconstants.ModeABAC,\n\t\tkubeadmconstants.ModeAlwaysAllow,\n\t\tkubeadmconstants.ModeAlwaysDeny,\n\t}\n\n\tfor _, mode := range allModes {\n\t\tif authzMode == mode {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":278,"to":294}} {"id":100001000,"name":"getControllerManagerCommand","signature":"func getControllerManagerCommand(cfg *kubeadmapi.ClusterConfiguration) []string","file":"cmd/kubeadm/app/phases/controlplane/manifests.go","code":"// getControllerManagerCommand builds the right controller manager command from the given config object and version\nfunc getControllerManagerCommand(cfg *kubeadmapi.ClusterConfiguration) []string {\n\n\tkubeconfigFile := filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.ControllerManagerKubeConfigFileName)\n\tcaFile := filepath.Join(cfg.CertificatesDir, kubeadmconstants.CACertName)\n\n\tdefaultArguments := map[string]string{\n\t\t\"bind-address\": \"127.0.0.1\",\n\t\t\"leader-elect\": \"true\",\n\t\t\"kubeconfig\": kubeconfigFile,\n\t\t\"authentication-kubeconfig\": kubeconfigFile,\n\t\t\"authorization-kubeconfig\": kubeconfigFile,\n\t\t\"client-ca-file\": caFile,\n\t\t\"requestheader-client-ca-file\": filepath.Join(cfg.CertificatesDir, kubeadmconstants.FrontProxyCACertName),\n\t\t\"root-ca-file\": caFile,\n\t\t\"service-account-private-key-file\": filepath.Join(cfg.CertificatesDir, kubeadmconstants.ServiceAccountPrivateKeyName),\n\t\t\"cluster-signing-cert-file\": caFile,\n\t\t\"cluster-signing-key-file\": filepath.Join(cfg.CertificatesDir, kubeadmconstants.CAKeyName),\n\t\t\"use-service-account-credentials\": \"true\",\n\t\t\"controllers\": \"*,bootstrapsigner,tokencleaner\",\n\t}\n\n\t// If using external CA, pass empty string to controller manager instead of ca.key/ca.crt path,\n\t// so that the csrsigning controller fails to start\n\tif res, _ := certphase.UsingExternalCA(cfg); res {\n\t\tdefaultArguments[\"cluster-signing-key-file\"] = \"\"\n\t\tdefaultArguments[\"cluster-signing-cert-file\"] = \"\"\n\t}\n\n\t// Let the controller-manager allocate Node CIDRs for the Pod network.\n\t// Each node will get a subspace of the address CIDR provided with --pod-network-cidr.\n\tif cfg.Networking.PodSubnet != \"\" {\n\t\tdefaultArguments[\"allocate-node-cidrs\"] = \"true\"\n\t\tdefaultArguments[\"cluster-cidr\"] = cfg.Networking.PodSubnet\n\t\tif cfg.Networking.ServiceSubnet != \"\" {\n\t\t\tdefaultArguments[\"service-cluster-ip-range\"] = cfg.Networking.ServiceSubnet\n\t\t}\n\t}\n\n\t// Set cluster name\n\tif cfg.ClusterName != \"\" {\n\t\tdefaultArguments[\"cluster-name\"] = cfg.ClusterName\n\t}\n\n\tcommand := []string{\"kube-controller-manager\"}\n\tcommand = append(command, kubeadmutil.BuildArgumentListFromMap(defaultArguments, cfg.ControllerManager.ExtraArgs)...)\n\n\treturn command\n}","line":{"from":296,"to":344}} {"id":100001001,"name":"getSchedulerCommand","signature":"func getSchedulerCommand(cfg *kubeadmapi.ClusterConfiguration) []string","file":"cmd/kubeadm/app/phases/controlplane/manifests.go","code":"// getSchedulerCommand builds the right scheduler command from the given config object and version\nfunc getSchedulerCommand(cfg *kubeadmapi.ClusterConfiguration) []string {\n\tkubeconfigFile := filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.SchedulerKubeConfigFileName)\n\tdefaultArguments := map[string]string{\n\t\t\"bind-address\": \"127.0.0.1\",\n\t\t\"leader-elect\": \"true\",\n\t\t\"kubeconfig\": kubeconfigFile,\n\t\t\"authentication-kubeconfig\": kubeconfigFile,\n\t\t\"authorization-kubeconfig\": kubeconfigFile,\n\t}\n\n\tcommand := []string{\"kube-scheduler\"}\n\tcommand = append(command, kubeadmutil.BuildArgumentListFromMap(defaultArguments, cfg.Scheduler.ExtraArgs)...)\n\treturn command\n}","line":{"from":346,"to":360}} {"id":100001002,"name":"getHostPathVolumesForTheControlPlane","signature":"func getHostPathVolumesForTheControlPlane(cfg *kubeadmapi.ClusterConfiguration) controlPlaneHostPathMounts","file":"cmd/kubeadm/app/phases/controlplane/volumes.go","code":"// getHostPathVolumesForTheControlPlane gets the required hostPath volumes and mounts for the control plane\nfunc getHostPathVolumesForTheControlPlane(cfg *kubeadmapi.ClusterConfiguration) controlPlaneHostPathMounts {\n\thostPathDirectoryOrCreate := v1.HostPathDirectoryOrCreate\n\thostPathFileOrCreate := v1.HostPathFileOrCreate\n\tmounts := newControlPlaneHostPathMounts()\n\n\t// HostPath volumes for the API Server\n\t// Read-only mount for the certificates directory\n\t// TODO: Always mount the K8s Certificates directory to a static path inside of the container\n\tmounts.NewHostPathMount(kubeadmconstants.KubeAPIServer, kubeadmconstants.KubeCertificatesVolumeName, cfg.CertificatesDir, cfg.CertificatesDir, true, \u0026hostPathDirectoryOrCreate)\n\t// Read-only mount for the ca certs (/etc/ssl/certs) directory\n\tmounts.NewHostPathMount(kubeadmconstants.KubeAPIServer, caCertsVolumeName, caCertsVolumePath, caCertsVolumePath, true, \u0026hostPathDirectoryOrCreate)\n\n\t// If external etcd is specified, mount the directories needed for accessing the CA/serving certs and the private key\n\tif cfg.Etcd.External != nil {\n\t\tetcdVols, etcdVolMounts := getEtcdCertVolumes(cfg.Etcd.External, cfg.CertificatesDir)\n\t\tmounts.AddHostPathMounts(kubeadmconstants.KubeAPIServer, etcdVols, etcdVolMounts)\n\t}\n\n\t// HostPath volumes for the controller manager\n\t// Read-only mount for the certificates directory\n\t// TODO: Always mount the K8s Certificates directory to a static path inside of the container\n\tmounts.NewHostPathMount(kubeadmconstants.KubeControllerManager, kubeadmconstants.KubeCertificatesVolumeName, cfg.CertificatesDir, cfg.CertificatesDir, true, \u0026hostPathDirectoryOrCreate)\n\t// Read-only mount for the ca certs (/etc/ssl/certs) directory\n\tmounts.NewHostPathMount(kubeadmconstants.KubeControllerManager, caCertsVolumeName, caCertsVolumePath, caCertsVolumePath, true, \u0026hostPathDirectoryOrCreate)\n\t// Read-only mount for the controller manager kubeconfig file\n\tcontrollerManagerKubeConfigFile := filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.ControllerManagerKubeConfigFileName)\n\tmounts.NewHostPathMount(kubeadmconstants.KubeControllerManager, kubeadmconstants.KubeConfigVolumeName, controllerManagerKubeConfigFile, controllerManagerKubeConfigFile, true, \u0026hostPathFileOrCreate)\n\t// Mount for the flexvolume directory (/usr/libexec/kubernetes/kubelet-plugins/volume/exec by default)\n\t// Flexvolume dir must NOT be readonly as it is used for third-party plugins to integrate with their storage backends via unix domain socket.\n\tflexvolumeDirVolumePath, ok := cfg.ControllerManager.ExtraArgs[\"flex-volume-plugin-dir\"]\n\tif !ok {\n\t\tflexvolumeDirVolumePath = defaultFlexvolumeDirVolumePath\n\t}\n\tmounts.NewHostPathMount(kubeadmconstants.KubeControllerManager, flexvolumeDirVolumeName, flexvolumeDirVolumePath, flexvolumeDirVolumePath, false, \u0026hostPathDirectoryOrCreate)\n\n\t// HostPath volumes for the scheduler\n\t// Read-only mount for the scheduler kubeconfig file\n\tschedulerKubeConfigFile := filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.SchedulerKubeConfigFileName)\n\tmounts.NewHostPathMount(kubeadmconstants.KubeScheduler, kubeadmconstants.KubeConfigVolumeName, schedulerKubeConfigFile, schedulerKubeConfigFile, true, \u0026hostPathFileOrCreate)\n\n\t// On some systems were we host-mount /etc/ssl/certs, it is also required to mount additional directories.\n\t// This is needed due to symlinks pointing from files in /etc/ssl/certs to these directories.\n\tfor _, caCertsExtraVolumePath := range caCertsExtraVolumePaths {\n\t\tif isExtraVolumeMountNeeded(caCertsExtraVolumePath) {\n\t\t\tcaCertsExtraVolumeName := strings.Replace(caCertsExtraVolumePath, \"/\", \"-\", -1)[1:]\n\t\t\tmounts.NewHostPathMount(kubeadmconstants.KubeAPIServer, caCertsExtraVolumeName, caCertsExtraVolumePath, caCertsExtraVolumePath, true, \u0026hostPathDirectoryOrCreate)\n\t\t\tmounts.NewHostPathMount(kubeadmconstants.KubeControllerManager, caCertsExtraVolumeName, caCertsExtraVolumePath, caCertsExtraVolumePath, true, \u0026hostPathDirectoryOrCreate)\n\t\t}\n\t}\n\n\t// Merge user defined mounts and ensure unique volume and volume mount\n\t// names\n\tmounts.AddExtraHostPathMounts(kubeadmconstants.KubeAPIServer, cfg.APIServer.ExtraVolumes)\n\tmounts.AddExtraHostPathMounts(kubeadmconstants.KubeControllerManager, cfg.ControllerManager.ExtraVolumes)\n\tmounts.AddExtraHostPathMounts(kubeadmconstants.KubeScheduler, cfg.Scheduler.ExtraVolumes)\n\n\treturn mounts\n}","line":{"from":45,"to":103}} {"id":100001003,"name":"newControlPlaneHostPathMounts","signature":"func newControlPlaneHostPathMounts() controlPlaneHostPathMounts","file":"cmd/kubeadm/app/phases/controlplane/volumes.go","code":"func newControlPlaneHostPathMounts() controlPlaneHostPathMounts {\n\treturn controlPlaneHostPathMounts{\n\t\tvolumes: map[string]map[string]v1.Volume{},\n\t\tvolumeMounts: map[string]map[string]v1.VolumeMount{},\n\t}\n}","line":{"from":121,"to":126}} {"id":100001004,"name":"NewHostPathMount","signature":"func (c *controlPlaneHostPathMounts) NewHostPathMount(component, mountName, hostPath, containerPath string, readOnly bool, hostPathType *v1.HostPathType)","file":"cmd/kubeadm/app/phases/controlplane/volumes.go","code":"func (c *controlPlaneHostPathMounts) NewHostPathMount(component, mountName, hostPath, containerPath string, readOnly bool, hostPathType *v1.HostPathType) {\n\tvol := staticpodutil.NewVolume(mountName, hostPath, hostPathType)\n\tc.addComponentVolume(component, vol)\n\tvolMount := staticpodutil.NewVolumeMount(mountName, containerPath, readOnly)\n\tc.addComponentVolumeMount(component, volMount)\n}","line":{"from":128,"to":133}} {"id":100001005,"name":"AddHostPathMounts","signature":"func (c *controlPlaneHostPathMounts) AddHostPathMounts(component string, vols []v1.Volume, volMounts []v1.VolumeMount)","file":"cmd/kubeadm/app/phases/controlplane/volumes.go","code":"func (c *controlPlaneHostPathMounts) AddHostPathMounts(component string, vols []v1.Volume, volMounts []v1.VolumeMount) {\n\tfor _, v := range vols {\n\t\tc.addComponentVolume(component, v)\n\t}\n\tfor _, v := range volMounts {\n\t\tc.addComponentVolumeMount(component, v)\n\t}\n}","line":{"from":135,"to":142}} {"id":100001006,"name":"AddExtraHostPathMounts","signature":"func (c *controlPlaneHostPathMounts) AddExtraHostPathMounts(component string, extraVols []kubeadmapi.HostPathMount)","file":"cmd/kubeadm/app/phases/controlplane/volumes.go","code":"// AddExtraHostPathMounts adds host path mounts and overwrites the default\n// paths in the case that a user specifies the same volume/volume mount name.\nfunc (c *controlPlaneHostPathMounts) AddExtraHostPathMounts(component string, extraVols []kubeadmapi.HostPathMount) {\n\tfor _, extraVol := range extraVols {\n\t\thostPathType := extraVol.PathType\n\t\tc.NewHostPathMount(component, extraVol.Name, extraVol.HostPath, extraVol.MountPath, extraVol.ReadOnly, \u0026hostPathType)\n\t}\n}","line":{"from":144,"to":151}} {"id":100001007,"name":"GetVolumes","signature":"func (c *controlPlaneHostPathMounts) GetVolumes(component string) map[string]v1.Volume","file":"cmd/kubeadm/app/phases/controlplane/volumes.go","code":"func (c *controlPlaneHostPathMounts) GetVolumes(component string) map[string]v1.Volume {\n\treturn c.volumes[component]\n}","line":{"from":153,"to":155}} {"id":100001008,"name":"GetVolumeMounts","signature":"func (c *controlPlaneHostPathMounts) GetVolumeMounts(component string) map[string]v1.VolumeMount","file":"cmd/kubeadm/app/phases/controlplane/volumes.go","code":"func (c *controlPlaneHostPathMounts) GetVolumeMounts(component string) map[string]v1.VolumeMount {\n\treturn c.volumeMounts[component]\n}","line":{"from":157,"to":159}} {"id":100001009,"name":"addComponentVolume","signature":"func (c *controlPlaneHostPathMounts) addComponentVolume(component string, vol v1.Volume)","file":"cmd/kubeadm/app/phases/controlplane/volumes.go","code":"func (c *controlPlaneHostPathMounts) addComponentVolume(component string, vol v1.Volume) {\n\tif _, ok := c.volumes[component]; !ok {\n\t\tc.volumes[component] = map[string]v1.Volume{}\n\t}\n\tc.volumes[component][vol.Name] = vol\n}","line":{"from":161,"to":166}} {"id":100001010,"name":"addComponentVolumeMount","signature":"func (c *controlPlaneHostPathMounts) addComponentVolumeMount(component string, volMount v1.VolumeMount)","file":"cmd/kubeadm/app/phases/controlplane/volumes.go","code":"func (c *controlPlaneHostPathMounts) addComponentVolumeMount(component string, volMount v1.VolumeMount) {\n\tif _, ok := c.volumeMounts[component]; !ok {\n\t\tc.volumeMounts[component] = map[string]v1.VolumeMount{}\n\t}\n\tc.volumeMounts[component][volMount.Name] = volMount\n}","line":{"from":168,"to":173}} {"id":100001011,"name":"getEtcdCertVolumes","signature":"func getEtcdCertVolumes(etcdCfg *kubeadmapi.ExternalEtcd, k8sCertificatesDir string) ([]v1.Volume, []v1.VolumeMount)","file":"cmd/kubeadm/app/phases/controlplane/volumes.go","code":"// getEtcdCertVolumes returns the volumes/volumemounts needed for talking to an external etcd cluster\nfunc getEtcdCertVolumes(etcdCfg *kubeadmapi.ExternalEtcd, k8sCertificatesDir string) ([]v1.Volume, []v1.VolumeMount) {\n\tcertPaths := []string{etcdCfg.CAFile, etcdCfg.CertFile, etcdCfg.KeyFile}\n\tcertDirs := sets.New[string]()\n\tfor _, certPath := range certPaths {\n\t\tcertDir := filepath.ToSlash(filepath.Dir(certPath))\n\t\t// Ignore \".\", which is the result of passing an empty path.\n\t\t// Also ignore the cert directories that already may be mounted; /etc/ssl/certs, /etc/pki or Kubernetes CertificatesDir\n\t\t// If the etcd certs are in there, it's okay, we don't have to do anything\n\t\textraVolumePath := false\n\t\tfor _, caCertsExtraVolumePath := range caCertsExtraVolumePaths {\n\t\t\tif strings.HasPrefix(certDir, caCertsExtraVolumePath) {\n\t\t\t\textraVolumePath = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif certDir == \".\" || extraVolumePath || strings.HasPrefix(certDir, caCertsVolumePath) || strings.HasPrefix(certDir, k8sCertificatesDir) {\n\t\t\tcontinue\n\t\t}\n\t\t// Filter out any existing hostpath mounts in the list that contains a subset of the path\n\t\talreadyExists := false\n\t\tfor _, existingCertDir := range sets.List(certDirs) {\n\t\t\t// If the current directory is a parent of an existing one, remove the already existing one\n\t\t\tif strings.HasPrefix(existingCertDir, certDir) {\n\t\t\t\tcertDirs.Delete(existingCertDir)\n\t\t\t} else if strings.HasPrefix(certDir, existingCertDir) {\n\t\t\t\t// If an existing directory is a parent of the current one, don't add the current one\n\t\t\t\talreadyExists = true\n\t\t\t}\n\t\t}\n\t\tif alreadyExists {\n\t\t\tcontinue\n\t\t}\n\t\tcertDirs.Insert(certDir)\n\t}\n\n\tvolumes := []v1.Volume{}\n\tvolumeMounts := []v1.VolumeMount{}\n\tpathType := v1.HostPathDirectoryOrCreate\n\tfor i, certDir := range sets.List(certDirs) {\n\t\tname := fmt.Sprintf(\"etcd-certs-%d\", i)\n\t\tvolumes = append(volumes, staticpodutil.NewVolume(name, certDir, \u0026pathType))\n\t\tvolumeMounts = append(volumeMounts, staticpodutil.NewVolumeMount(name, certDir, true))\n\t}\n\treturn volumes, volumeMounts\n}","line":{"from":175,"to":220}} {"id":100001012,"name":"isExtraVolumeMountNeeded","signature":"func isExtraVolumeMountNeeded(caCertsExtraVolumePath string) bool","file":"cmd/kubeadm/app/phases/controlplane/volumes.go","code":"// isExtraVolumeMountNeeded specifies whether /etc/pki should be host-mounted into the containers\n// On some systems were we host-mount /etc/ssl/certs, it is also required to mount /etc/pki. This is needed\n// due to symlinks pointing from files in /etc/ssl/certs into /etc/pki/\nfunc isExtraVolumeMountNeeded(caCertsExtraVolumePath string) bool {\n\tif _, err := os.Stat(caCertsExtraVolumePath); err == nil {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":222,"to":230}} {"id":100001013,"name":"createShortLivedBootstrapToken","signature":"func createShortLivedBootstrapToken(client clientset.Interface) (string, error)","file":"cmd/kubeadm/app/phases/copycerts/copycerts.go","code":"// createShortLivedBootstrapToken creates the token used to manager kubeadm-certs\n// and return the tokenID\nfunc createShortLivedBootstrapToken(client clientset.Interface) (string, error) {\n\ttokenStr, err := bootstraputil.GenerateBootstrapToken()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"error generating token to upload certs\")\n\t}\n\ttoken, err := bootstraptokenv1.NewBootstrapTokenString(tokenStr)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"error creating upload certs token\")\n\t}\n\ttokens := []bootstraptokenv1.BootstrapToken{{\n\t\tToken: token,\n\t\tDescription: \"Proxy for managing TTL for the kubeadm-certs secret\",\n\t\tTTL: \u0026metav1.Duration{\n\t\t\tDuration: kubeadmconstants.DefaultCertTokenDuration,\n\t\t},\n\t}}\n\n\tif err := nodebootstraptokenphase.CreateNewTokens(client, tokens); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"error creating token\")\n\t}\n\treturn tokens[0].Token.ID, nil\n}","line":{"from":54,"to":77}} {"id":100001014,"name":"CreateCertificateKey","signature":"func CreateCertificateKey() (string, error)","file":"cmd/kubeadm/app/phases/copycerts/copycerts.go","code":"// CreateCertificateKey returns a cryptographically secure random key\nfunc CreateCertificateKey() (string, error) {\n\trandBytes, err := cryptoutil.CreateRandBytes(kubeadmconstants.CertificateKeySize)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn hex.EncodeToString(randBytes), nil\n}","line":{"from":79,"to":86}} {"id":100001015,"name":"UploadCerts","signature":"func UploadCerts(client clientset.Interface, cfg *kubeadmapi.InitConfiguration, key string) error","file":"cmd/kubeadm/app/phases/copycerts/copycerts.go","code":"// UploadCerts save certs needs to join a new control-plane on kubeadm-certs sercret.\nfunc UploadCerts(client clientset.Interface, cfg *kubeadmapi.InitConfiguration, key string) error {\n\tfmt.Printf(\"[upload-certs] Storing the certificates in Secret %q in the %q Namespace\\n\", kubeadmconstants.KubeadmCertsSecret, metav1.NamespaceSystem)\n\tdecodedKey, err := hex.DecodeString(key)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error decoding certificate key\")\n\t}\n\ttokenID, err := createShortLivedBootstrapToken(client)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsecretData, err := getDataFromDisk(cfg, decodedKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\tref, err := getSecretOwnerRef(client, tokenID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = apiclient.CreateOrUpdateSecret(client, \u0026v1.Secret{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: kubeadmconstants.KubeadmCertsSecret,\n\t\t\tNamespace: metav1.NamespaceSystem,\n\t\t\tOwnerReferences: ref,\n\t\t},\n\t\tData: secretData,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn createRBAC(client)\n}","line":{"from":88,"to":122}} {"id":100001016,"name":"createRBAC","signature":"func createRBAC(client clientset.Interface) error","file":"cmd/kubeadm/app/phases/copycerts/copycerts.go","code":"func createRBAC(client clientset.Interface) error {\n\terr := apiclient.CreateOrUpdateRole(client, \u0026rbac.Role{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: kubeadmconstants.KubeadmCertsClusterRoleName,\n\t\t\tNamespace: metav1.NamespaceSystem,\n\t\t},\n\t\tRules: []rbac.PolicyRule{\n\t\t\t{\n\t\t\t\tVerbs: []string{\"get\"},\n\t\t\t\tAPIGroups: []string{\"\"},\n\t\t\t\tResources: []string{\"secrets\"},\n\t\t\t\tResourceNames: []string{kubeadmconstants.KubeadmCertsSecret},\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn apiclient.CreateOrUpdateRoleBinding(client, \u0026rbac.RoleBinding{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: kubeadmconstants.KubeadmCertsClusterRoleName,\n\t\t\tNamespace: metav1.NamespaceSystem,\n\t\t},\n\t\tRoleRef: rbac.RoleRef{\n\t\t\tAPIGroup: rbac.GroupName,\n\t\t\tKind: \"Role\",\n\t\t\tName: kubeadmconstants.KubeadmCertsClusterRoleName,\n\t\t},\n\t\tSubjects: []rbac.Subject{\n\t\t\t{\n\t\t\t\tKind: rbac.GroupKind,\n\t\t\t\tName: kubeadmconstants.NodeBootstrapTokenAuthGroup,\n\t\t\t},\n\t\t},\n\t})\n}","line":{"from":124,"to":160}} {"id":100001017,"name":"getSecretOwnerRef","signature":"func getSecretOwnerRef(client clientset.Interface, tokenID string) ([]metav1.OwnerReference, error)","file":"cmd/kubeadm/app/phases/copycerts/copycerts.go","code":"func getSecretOwnerRef(client clientset.Interface, tokenID string) ([]metav1.OwnerReference, error) {\n\tsecretName := bootstraputil.BootstrapTokenSecretName(tokenID)\n\tsecret, err := client.CoreV1().Secrets(metav1.NamespaceSystem).Get(context.TODO(), secretName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error to get token reference\")\n\t}\n\n\tgvk := schema.GroupVersionKind{Version: \"v1\", Kind: \"Secret\"}\n\tref := metav1.NewControllerRef(secret, gvk)\n\treturn []metav1.OwnerReference{*ref}, nil\n}","line":{"from":162,"to":172}} {"id":100001018,"name":"loadAndEncryptCert","signature":"func loadAndEncryptCert(certPath string, key []byte) ([]byte, error)","file":"cmd/kubeadm/app/phases/copycerts/copycerts.go","code":"func loadAndEncryptCert(certPath string, key []byte) ([]byte, error) {\n\tcert, err := os.ReadFile(certPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cryptoutil.EncryptBytes(cert, key)\n}","line":{"from":174,"to":180}} {"id":100001019,"name":"certsToTransfer","signature":"func certsToTransfer(cfg *kubeadmapi.InitConfiguration) map[string]string","file":"cmd/kubeadm/app/phases/copycerts/copycerts.go","code":"func certsToTransfer(cfg *kubeadmapi.InitConfiguration) map[string]string {\n\tcertsDir := cfg.CertificatesDir\n\tcerts := map[string]string{\n\t\tkubeadmconstants.CACertName: path.Join(certsDir, kubeadmconstants.CACertName),\n\t\tkubeadmconstants.CAKeyName: path.Join(certsDir, kubeadmconstants.CAKeyName),\n\t\tkubeadmconstants.FrontProxyCACertName: path.Join(certsDir, kubeadmconstants.FrontProxyCACertName),\n\t\tkubeadmconstants.FrontProxyCAKeyName: path.Join(certsDir, kubeadmconstants.FrontProxyCAKeyName),\n\t\tkubeadmconstants.ServiceAccountPublicKeyName: path.Join(certsDir, kubeadmconstants.ServiceAccountPublicKeyName),\n\t\tkubeadmconstants.ServiceAccountPrivateKeyName: path.Join(certsDir, kubeadmconstants.ServiceAccountPrivateKeyName),\n\t}\n\n\tif cfg.Etcd.External == nil {\n\t\tcerts[kubeadmconstants.EtcdCACertName] = path.Join(certsDir, kubeadmconstants.EtcdCACertName)\n\t\tcerts[kubeadmconstants.EtcdCAKeyName] = path.Join(certsDir, kubeadmconstants.EtcdCAKeyName)\n\t} else {\n\t\tcerts[externalEtcdCA] = cfg.Etcd.External.CAFile\n\t\tcerts[externalEtcdCert] = cfg.Etcd.External.CertFile\n\t\tcerts[externalEtcdKey] = cfg.Etcd.External.KeyFile\n\t}\n\n\treturn certs\n}","line":{"from":182,"to":203}} {"id":100001020,"name":"getDataFromDisk","signature":"func getDataFromDisk(cfg *kubeadmapi.InitConfiguration, key []byte) (map[string][]byte, error)","file":"cmd/kubeadm/app/phases/copycerts/copycerts.go","code":"func getDataFromDisk(cfg *kubeadmapi.InitConfiguration, key []byte) (map[string][]byte, error) {\n\tsecretData := map[string][]byte{}\n\tfor certName, certPath := range certsToTransfer(cfg) {\n\t\tcert, err := loadAndEncryptCert(certPath, key)\n\t\tif err == nil || os.IsNotExist(err) {\n\t\t\tsecretData[certOrKeyNameToSecretName(certName)] = cert\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn secretData, nil\n}","line":{"from":205,"to":216}} {"id":100001021,"name":"DownloadCerts","signature":"func DownloadCerts(client clientset.Interface, cfg *kubeadmapi.InitConfiguration, key string) error","file":"cmd/kubeadm/app/phases/copycerts/copycerts.go","code":"// DownloadCerts downloads the certificates needed to join a new control plane.\nfunc DownloadCerts(client clientset.Interface, cfg *kubeadmapi.InitConfiguration, key string) error {\n\tfmt.Printf(\"[download-certs] Downloading the certificates in Secret %q in the %q Namespace\\n\", kubeadmconstants.KubeadmCertsSecret, metav1.NamespaceSystem)\n\n\tdecodedKey, err := hex.DecodeString(key)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error decoding certificate key\")\n\t}\n\n\tsecret, err := getSecret(client)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error downloading the secret\")\n\t}\n\n\tsecretData, err := getDataFromSecret(secret, decodedKey)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error decoding secret data with provided key\")\n\t}\n\n\tfmt.Printf(\"[download-certs] Saving the certificates to the folder: %q\\n\", cfg.CertificatesDir)\n\n\tfor certOrKeyName, certOrKeyPath := range certsToTransfer(cfg) {\n\t\tcertOrKeyData, found := secretData[certOrKeyNameToSecretName(certOrKeyName)]\n\t\tif !found {\n\t\t\treturn errors.Errorf(\"the Secret does not include the required certificate or key - name: %s, path: %s\", certOrKeyName, certOrKeyPath)\n\t\t}\n\t\tif len(certOrKeyData) == 0 {\n\t\t\tklog.V(1).Infof(\"[download-certs] Not saving %q to disk, since it is empty in the %q Secret\\n\", certOrKeyName, kubeadmconstants.KubeadmCertsSecret)\n\t\t\tcontinue\n\t\t}\n\t\tif err := writeCertOrKey(certOrKeyPath, certOrKeyData); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":218,"to":254}} {"id":100001022,"name":"writeCertOrKey","signature":"func writeCertOrKey(certOrKeyPath string, certOrKeyData []byte) error","file":"cmd/kubeadm/app/phases/copycerts/copycerts.go","code":"func writeCertOrKey(certOrKeyPath string, certOrKeyData []byte) error {\n\tif _, err := keyutil.ParsePrivateKeyPEM(certOrKeyData); err == nil {\n\t\treturn keyutil.WriteKey(certOrKeyPath, certOrKeyData)\n\t} else if _, err := keyutil.ParsePublicKeysPEM(certOrKeyData); err == nil {\n\t\treturn certutil.WriteCert(certOrKeyPath, certOrKeyData)\n\t}\n\treturn errors.New(\"unknown data found in Secret entry\")\n}","line":{"from":256,"to":263}} {"id":100001023,"name":"getSecret","signature":"func getSecret(client clientset.Interface) (*v1.Secret, error)","file":"cmd/kubeadm/app/phases/copycerts/copycerts.go","code":"func getSecret(client clientset.Interface) (*v1.Secret, error) {\n\tsecret, err := client.CoreV1().Secrets(metav1.NamespaceSystem).Get(context.TODO(), kubeadmconstants.KubeadmCertsSecret, metav1.GetOptions{})\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\treturn nil, errors.Errorf(\"Secret %q was not found in the %q Namespace. This Secret might have expired. Please, run `kubeadm init phase upload-certs --upload-certs` on a control plane to generate a new one\", kubeadmconstants.KubeadmCertsSecret, metav1.NamespaceSystem)\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn secret, nil\n}","line":{"from":265,"to":274}} {"id":100001024,"name":"getDataFromSecret","signature":"func getDataFromSecret(secret *v1.Secret, key []byte) (map[string][]byte, error)","file":"cmd/kubeadm/app/phases/copycerts/copycerts.go","code":"func getDataFromSecret(secret *v1.Secret, key []byte) (map[string][]byte, error) {\n\tsecretData := map[string][]byte{}\n\tfor secretName, encryptedSecret := range secret.Data {\n\t\t// In some cases the secret might have empty data if the secrets were not present on disk\n\t\t// when uploading. This can specially happen with external insecure etcd (no certs)\n\t\tif len(encryptedSecret) \u003e 0 {\n\t\t\tcert, err := cryptoutil.DecryptBytes(encryptedSecret, key)\n\t\t\tif err != nil {\n\t\t\t\t// If any of the decrypt operations fail do not return a partial result,\n\t\t\t\t// return an empty result immediately\n\t\t\t\treturn map[string][]byte{}, err\n\t\t\t}\n\t\t\tsecretData[secretName] = cert\n\t\t} else {\n\t\t\tsecretData[secretName] = []byte{}\n\t\t}\n\t}\n\treturn secretData, nil\n}","line":{"from":276,"to":294}} {"id":100001025,"name":"certOrKeyNameToSecretName","signature":"func certOrKeyNameToSecretName(certOrKeyName string) string","file":"cmd/kubeadm/app/phases/copycerts/copycerts.go","code":"func certOrKeyNameToSecretName(certOrKeyName string) string {\n\treturn strings.Replace(certOrKeyName, \"/\", \"-\", -1)\n}","line":{"from":296,"to":298}} {"id":100001026,"name":"CreateLocalEtcdStaticPodManifestFile","signature":"func CreateLocalEtcdStaticPodManifestFile(manifestDir, patchesDir string, nodeName string, cfg *kubeadmapi.ClusterConfiguration, endpoint *kubeadmapi.APIEndpoint, isDryRun bool) error","file":"cmd/kubeadm/app/phases/etcd/local.go","code":"// CreateLocalEtcdStaticPodManifestFile will write local etcd static pod manifest file.\n// This function is used by init - when the etcd cluster is empty - or by kubeadm\n// upgrade - when the etcd cluster is already up and running (and the --initial-cluster flag have no impact)\nfunc CreateLocalEtcdStaticPodManifestFile(manifestDir, patchesDir string, nodeName string, cfg *kubeadmapi.ClusterConfiguration, endpoint *kubeadmapi.APIEndpoint, isDryRun bool) error {\n\tif cfg.Etcd.External != nil {\n\t\treturn errors.New(\"etcd static pod manifest cannot be generated for cluster using external etcd\")\n\t}\n\n\tif err := prepareAndWriteEtcdStaticPod(manifestDir, patchesDir, cfg, endpoint, nodeName, []etcdutil.Member{}, isDryRun); err != nil {\n\t\treturn err\n\t}\n\n\tklog.V(1).Infof(\"[etcd] wrote Static Pod manifest for a local etcd member to %q\\n\", kubeadmconstants.GetStaticPodFilepath(kubeadmconstants.Etcd, manifestDir))\n\treturn nil\n}","line":{"from":53,"to":67}} {"id":100001027,"name":"CheckLocalEtcdClusterStatus","signature":"func CheckLocalEtcdClusterStatus(client clientset.Interface, certificatesDir string) error","file":"cmd/kubeadm/app/phases/etcd/local.go","code":"// CheckLocalEtcdClusterStatus verifies health state of local/stacked etcd cluster before installing a new etcd member\nfunc CheckLocalEtcdClusterStatus(client clientset.Interface, certificatesDir string) error {\n\tklog.V(1).Info(\"[etcd] Checking etcd cluster health\")\n\n\t// creates an etcd client that connects to all the local/stacked etcd members\n\tklog.V(1).Info(\"creating etcd client that connects to etcd pods\")\n\tetcdClient, err := etcdutil.NewFromCluster(client, certificatesDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Checking health state\n\terr = etcdClient.CheckClusterHealth()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"etcd cluster is not healthy\")\n\t}\n\n\treturn nil\n}","line":{"from":69,"to":87}} {"id":100001028,"name":"RemoveStackedEtcdMemberFromCluster","signature":"func RemoveStackedEtcdMemberFromCluster(client clientset.Interface, cfg *kubeadmapi.InitConfiguration) error","file":"cmd/kubeadm/app/phases/etcd/local.go","code":"// RemoveStackedEtcdMemberFromCluster will remove a local etcd member from etcd cluster,\n// when reset the control plane node.\nfunc RemoveStackedEtcdMemberFromCluster(client clientset.Interface, cfg *kubeadmapi.InitConfiguration) error {\n\t// creates an etcd client that connects to all the local/stacked etcd members\n\tklog.V(1).Info(\"[etcd] creating etcd client that connects to etcd pods\")\n\tetcdClient, err := etcdutil.NewFromCluster(client, cfg.CertificatesDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmembers, err := etcdClient.ListMembers()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// If this is the only remaining stacked etcd member in the cluster, calling RemoveMember()\n\t// is not needed.\n\tif len(members) == 1 {\n\t\tetcdClientAddress := etcdutil.GetClientURL(\u0026cfg.LocalAPIEndpoint)\n\t\tfor _, endpoint := range etcdClient.Endpoints {\n\t\t\tif endpoint == etcdClientAddress {\n\t\t\t\tklog.V(1).Info(\"[etcd] This is the only remaining etcd member in the etcd cluster, skip removing it\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// notifies the other members of the etcd cluster about the removing member\n\tetcdPeerAddress := etcdutil.GetPeerURL(\u0026cfg.LocalAPIEndpoint)\n\n\tklog.V(2).Infof(\"[etcd] get the member id from peer: %s\", etcdPeerAddress)\n\tid, err := etcdClient.GetMemberID(etcdPeerAddress)\n\tif err != nil {\n\t\tif errors.Is(etcdutil.ErrNoMemberIDForPeerURL, err) {\n\t\t\tklog.V(5).Infof(\"[etcd] member was already removed, because no member id exists for peer %s\", etcdPeerAddress)\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\tklog.V(1).Infof(\"[etcd] removing etcd member: %s, id: %d\", etcdPeerAddress, id)\n\tmembers, err = etcdClient.RemoveMember(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\tklog.V(1).Infof(\"[etcd] Updated etcd member list: %v\", members)\n\n\treturn nil\n}","line":{"from":89,"to":136}} {"id":100001029,"name":"CreateStackedEtcdStaticPodManifestFile","signature":"func CreateStackedEtcdStaticPodManifestFile(client clientset.Interface, manifestDir, patchesDir string, nodeName string, cfg *kubeadmapi.ClusterConfiguration, endpoint *kubeadmapi.APIEndpoint, isDryRun bool, certificatesDir string) error","file":"cmd/kubeadm/app/phases/etcd/local.go","code":"// CreateStackedEtcdStaticPodManifestFile will write local etcd static pod manifest file\n// for an additional etcd member that is joining an existing local/stacked etcd cluster.\n// Other members of the etcd cluster will be notified of the joining node in beforehand as well.\nfunc CreateStackedEtcdStaticPodManifestFile(client clientset.Interface, manifestDir, patchesDir string, nodeName string, cfg *kubeadmapi.ClusterConfiguration, endpoint *kubeadmapi.APIEndpoint, isDryRun bool, certificatesDir string) error {\n\t// creates an etcd client that connects to all the local/stacked etcd members\n\tklog.V(1).Info(\"creating etcd client that connects to etcd pods\")\n\tetcdClient, err := etcdutil.NewFromCluster(client, certificatesDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tetcdPeerAddress := etcdutil.GetPeerURL(endpoint)\n\n\tvar cluster []etcdutil.Member\n\tif isDryRun {\n\t\tfmt.Printf(\"[etcd] Would add etcd member: %s\\n\", etcdPeerAddress)\n\t} else {\n\t\tklog.V(1).Infof(\"[etcd] Adding etcd member: %s\", etcdPeerAddress)\n\t\tif features.Enabled(cfg.FeatureGates, features.EtcdLearnerMode) {\n\t\t\tcluster, err = etcdClient.AddMemberAsLearner(nodeName, etcdPeerAddress)\n\t\t} else {\n\t\t\tcluster, err = etcdClient.AddMember(nodeName, etcdPeerAddress)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Println(\"[etcd] Announced new etcd member joining to the existing etcd cluster\")\n\t\tklog.V(1).Infof(\"Updated etcd member list: %v\", cluster)\n\t}\n\n\tfmt.Printf(\"[etcd] Creating static Pod manifest for %q\\n\", kubeadmconstants.Etcd)\n\n\tif err := prepareAndWriteEtcdStaticPod(manifestDir, patchesDir, cfg, endpoint, nodeName, cluster, isDryRun); err != nil {\n\t\treturn err\n\t}\n\n\tif isDryRun {\n\t\tfmt.Println(\"[etcd] Would wait for the new etcd member to join the cluster\")\n\t\treturn nil\n\t}\n\n\tif features.Enabled(cfg.FeatureGates, features.EtcdLearnerMode) {\n\t\tlearnerID, err := etcdClient.GetMemberID(etcdPeerAddress)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = etcdClient.MemberPromote(learnerID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfmt.Printf(\"[etcd] Waiting for the new etcd member to join the cluster. This can take up to %v\\n\", etcdHealthyCheckInterval*etcdHealthyCheckRetries)\n\tif _, err := etcdClient.WaitForClusterAvailable(etcdHealthyCheckRetries, etcdHealthyCheckInterval); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":138,"to":196}} {"id":100001030,"name":"GetEtcdPodSpec","signature":"func GetEtcdPodSpec(cfg *kubeadmapi.ClusterConfiguration, endpoint *kubeadmapi.APIEndpoint, nodeName string, initialCluster []etcdutil.Member) v1.Pod","file":"cmd/kubeadm/app/phases/etcd/local.go","code":"// GetEtcdPodSpec returns the etcd static Pod actualized to the context of the current configuration\n// NB. GetEtcdPodSpec methods holds the information about how kubeadm creates etcd static pod manifests.\nfunc GetEtcdPodSpec(cfg *kubeadmapi.ClusterConfiguration, endpoint *kubeadmapi.APIEndpoint, nodeName string, initialCluster []etcdutil.Member) v1.Pod {\n\tpathType := v1.HostPathDirectoryOrCreate\n\tetcdMounts := map[string]v1.Volume{\n\t\tetcdVolumeName: staticpodutil.NewVolume(etcdVolumeName, cfg.Etcd.Local.DataDir, \u0026pathType),\n\t\tcertsVolumeName: staticpodutil.NewVolume(certsVolumeName, cfg.CertificatesDir+\"/etcd\", \u0026pathType),\n\t}\n\t// probeHostname returns the correct localhost IP address family based on the endpoint AdvertiseAddress\n\tprobeHostname, probePort, probeScheme := staticpodutil.GetEtcdProbeEndpoint(\u0026cfg.Etcd, utilsnet.IsIPv6String(endpoint.AdvertiseAddress))\n\treturn staticpodutil.ComponentPod(\n\t\tv1.Container{\n\t\t\tName: kubeadmconstants.Etcd,\n\t\t\tCommand: getEtcdCommand(cfg, endpoint, nodeName, initialCluster),\n\t\t\tImage: images.GetEtcdImage(cfg),\n\t\t\tImagePullPolicy: v1.PullIfNotPresent,\n\t\t\t// Mount the etcd datadir path read-write so etcd can store data in a more persistent manner\n\t\t\tVolumeMounts: []v1.VolumeMount{\n\t\t\t\tstaticpodutil.NewVolumeMount(etcdVolumeName, cfg.Etcd.Local.DataDir, false),\n\t\t\t\tstaticpodutil.NewVolumeMount(certsVolumeName, cfg.CertificatesDir+\"/etcd\", false),\n\t\t\t},\n\t\t\tResources: v1.ResourceRequirements{\n\t\t\t\tRequests: v1.ResourceList{\n\t\t\t\t\tv1.ResourceCPU: resource.MustParse(\"100m\"),\n\t\t\t\t\tv1.ResourceMemory: resource.MustParse(\"100Mi\"),\n\t\t\t\t},\n\t\t\t},\n\t\t\tLivenessProbe: staticpodutil.LivenessProbe(probeHostname, \"/health?exclude=NOSPACE\u0026serializable=true\", probePort, probeScheme),\n\t\t\tStartupProbe: staticpodutil.StartupProbe(probeHostname, \"/health?serializable=false\", probePort, probeScheme, cfg.APIServer.TimeoutForControlPlane),\n\t\t},\n\t\tetcdMounts,\n\t\t// etcd will listen on the advertise address of the API server, in a different port (2379)\n\t\tmap[string]string{kubeadmconstants.EtcdAdvertiseClientUrlsAnnotationKey: etcdutil.GetClientURL(endpoint)},\n\t)\n}","line":{"from":198,"to":232}} {"id":100001031,"name":"getEtcdCommand","signature":"func getEtcdCommand(cfg *kubeadmapi.ClusterConfiguration, endpoint *kubeadmapi.APIEndpoint, nodeName string, initialCluster []etcdutil.Member) []string","file":"cmd/kubeadm/app/phases/etcd/local.go","code":"// getEtcdCommand builds the right etcd command from the given config object\nfunc getEtcdCommand(cfg *kubeadmapi.ClusterConfiguration, endpoint *kubeadmapi.APIEndpoint, nodeName string, initialCluster []etcdutil.Member) []string {\n\t// localhost IP family should be the same that the AdvertiseAddress\n\tetcdLocalhostAddress := \"127.0.0.1\"\n\tif utilsnet.IsIPv6String(endpoint.AdvertiseAddress) {\n\t\tetcdLocalhostAddress = \"::1\"\n\t}\n\tdefaultArguments := map[string]string{\n\t\t\"name\": nodeName,\n\t\t// TODO: start using --initial-corrupt-check once the graduated flag is available:\n\t\t// https://github.com/kubernetes/kubeadm/issues/2676\n\t\t\"experimental-initial-corrupt-check\": \"true\",\n\t\t\"listen-client-urls\": fmt.Sprintf(\"%s,%s\", etcdutil.GetClientURLByIP(etcdLocalhostAddress), etcdutil.GetClientURL(endpoint)),\n\t\t\"advertise-client-urls\": etcdutil.GetClientURL(endpoint),\n\t\t\"listen-peer-urls\": etcdutil.GetPeerURL(endpoint),\n\t\t\"initial-advertise-peer-urls\": etcdutil.GetPeerURL(endpoint),\n\t\t\"data-dir\": cfg.Etcd.Local.DataDir,\n\t\t\"cert-file\": filepath.Join(cfg.CertificatesDir, kubeadmconstants.EtcdServerCertName),\n\t\t\"key-file\": filepath.Join(cfg.CertificatesDir, kubeadmconstants.EtcdServerKeyName),\n\t\t\"trusted-ca-file\": filepath.Join(cfg.CertificatesDir, kubeadmconstants.EtcdCACertName),\n\t\t\"client-cert-auth\": \"true\",\n\t\t\"peer-cert-file\": filepath.Join(cfg.CertificatesDir, kubeadmconstants.EtcdPeerCertName),\n\t\t\"peer-key-file\": filepath.Join(cfg.CertificatesDir, kubeadmconstants.EtcdPeerKeyName),\n\t\t\"peer-trusted-ca-file\": filepath.Join(cfg.CertificatesDir, kubeadmconstants.EtcdCACertName),\n\t\t\"peer-client-cert-auth\": \"true\",\n\t\t\"snapshot-count\": \"10000\",\n\t\t\"listen-metrics-urls\": fmt.Sprintf(\"http://%s\", net.JoinHostPort(etcdLocalhostAddress, strconv.Itoa(kubeadmconstants.EtcdMetricsPort))),\n\t\t\"experimental-watch-progress-notify-interval\": \"5s\",\n\t}\n\n\tif len(initialCluster) == 0 {\n\t\tdefaultArguments[\"initial-cluster\"] = fmt.Sprintf(\"%s=%s\", nodeName, etcdutil.GetPeerURL(endpoint))\n\t} else {\n\t\t// NB. the joining etcd member should be part of the initialCluster list\n\t\tendpoints := []string{}\n\t\tfor _, member := range initialCluster {\n\t\t\tendpoints = append(endpoints, fmt.Sprintf(\"%s=%s\", member.Name, member.PeerURL))\n\t\t}\n\n\t\tdefaultArguments[\"initial-cluster\"] = strings.Join(endpoints, \",\")\n\t\tdefaultArguments[\"initial-cluster-state\"] = \"existing\"\n\t}\n\n\tcommand := []string{\"etcd\"}\n\tcommand = append(command, kubeadmutil.BuildArgumentListFromMap(defaultArguments, cfg.Etcd.Local.ExtraArgs)...)\n\treturn command\n}","line":{"from":234,"to":280}} {"id":100001032,"name":"prepareAndWriteEtcdStaticPod","signature":"func prepareAndWriteEtcdStaticPod(manifestDir string, patchesDir string, cfg *kubeadmapi.ClusterConfiguration, endpoint *kubeadmapi.APIEndpoint, nodeName string, initialCluster []etcdutil.Member, isDryRun bool) error","file":"cmd/kubeadm/app/phases/etcd/local.go","code":"func prepareAndWriteEtcdStaticPod(manifestDir string, patchesDir string, cfg *kubeadmapi.ClusterConfiguration, endpoint *kubeadmapi.APIEndpoint, nodeName string, initialCluster []etcdutil.Member, isDryRun bool) error {\n\t// gets etcd StaticPodSpec, actualized for the current ClusterConfiguration and the new list of etcd members\n\tspec := GetEtcdPodSpec(cfg, endpoint, nodeName, initialCluster)\n\n\tvar usersAndGroups *users.UsersAndGroups\n\tvar err error\n\tif features.Enabled(cfg.FeatureGates, features.RootlessControlPlane) {\n\t\tif isDryRun {\n\t\t\tfmt.Printf(\"[etcd] Would create users and groups for %q to run as non-root\\n\", kubeadmconstants.Etcd)\n\t\t\tfmt.Printf(\"[etcd] Would update static pod manifest for %q to run run as non-root\\n\", kubeadmconstants.Etcd)\n\t\t} else {\n\t\t\tusersAndGroups, err = staticpodutil.GetUsersAndGroups()\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"failed to create users and groups\")\n\t\t\t}\n\t\t\t// usersAndGroups is nil on non-linux.\n\t\t\tif usersAndGroups != nil {\n\t\t\t\tif err := staticpodutil.RunComponentAsNonRoot(kubeadmconstants.Etcd, \u0026spec, usersAndGroups, cfg); err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"failed to run component %q as non-root\", kubeadmconstants.Etcd)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// if patchesDir is defined, patch the static Pod manifest\n\tif patchesDir != \"\" {\n\t\tpatchedSpec, err := staticpodutil.PatchStaticPod(\u0026spec, patchesDir, os.Stdout)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to patch static Pod manifest file for %q\", kubeadmconstants.Etcd)\n\t\t}\n\t\tspec = *patchedSpec\n\t}\n\n\t// writes etcd StaticPod to disk\n\tif err := staticpodutil.WriteStaticPodToDisk(kubeadmconstants.Etcd, manifestDir, spec); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":282,"to":321}} {"id":100001033,"name":"CreateJoinControlPlaneKubeConfigFiles","signature":"func CreateJoinControlPlaneKubeConfigFiles(outDir string, cfg *kubeadmapi.InitConfiguration) error","file":"cmd/kubeadm/app/phases/kubeconfig/kubeconfig.go","code":"// CreateJoinControlPlaneKubeConfigFiles will create and write to disk the kubeconfig files required by kubeadm\n// join --control-plane workflow, plus the admin kubeconfig file used by the administrator and kubeadm itself; the\n// kubelet.conf file must not be created because it will be created and signed by the kubelet TLS bootstrap process.\n// When not using external CA mode, if a kubeconfig file already exists it is used only if evaluated equal,\n// otherwise an error is returned. For external CA mode, the creation of kubeconfig files is skipped.\nfunc CreateJoinControlPlaneKubeConfigFiles(outDir string, cfg *kubeadmapi.InitConfiguration) error {\n\tvar externaCA bool\n\tcaKeyPath := filepath.Join(cfg.CertificatesDir, kubeadmconstants.CAKeyName)\n\tif _, err := os.Stat(caKeyPath); os.IsNotExist(err) {\n\t\texternaCA = true\n\t}\n\n\tfiles := []string{\n\t\tkubeadmconstants.AdminKubeConfigFileName,\n\t\tkubeadmconstants.ControllerManagerKubeConfigFileName,\n\t\tkubeadmconstants.SchedulerKubeConfigFileName,\n\t}\n\n\tfor _, file := range files {\n\t\tif externaCA {\n\t\t\tfmt.Printf(\"[kubeconfig] External CA mode: Using user provided %s\\n\", file)\n\t\t\tcontinue\n\t\t}\n\t\tif err := createKubeConfigFiles(outDir, cfg, file); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":70,"to":98}} {"id":100001034,"name":"CreateKubeConfigFile","signature":"func CreateKubeConfigFile(kubeConfigFileName string, outDir string, cfg *kubeadmapi.InitConfiguration) error","file":"cmd/kubeadm/app/phases/kubeconfig/kubeconfig.go","code":"// CreateKubeConfigFile creates a kubeconfig file.\n// If the kubeconfig file already exists, it is used only if evaluated equal; otherwise an error is returned.\nfunc CreateKubeConfigFile(kubeConfigFileName string, outDir string, cfg *kubeadmapi.InitConfiguration) error {\n\tklog.V(1).Infof(\"creating kubeconfig file for %s\", kubeConfigFileName)\n\treturn createKubeConfigFiles(outDir, cfg, kubeConfigFileName)\n}","line":{"from":100,"to":105}} {"id":100001035,"name":"createKubeConfigFiles","signature":"func createKubeConfigFiles(outDir string, cfg *kubeadmapi.InitConfiguration, kubeConfigFileNames ...string) error","file":"cmd/kubeadm/app/phases/kubeconfig/kubeconfig.go","code":"// createKubeConfigFiles creates all the requested kubeconfig files.\n// If kubeconfig files already exists, they are used only if evaluated equal; otherwise an error is returned.\nfunc createKubeConfigFiles(outDir string, cfg *kubeadmapi.InitConfiguration, kubeConfigFileNames ...string) error {\n\n\t// gets the KubeConfigSpecs, actualized for the current InitConfiguration\n\tspecs, err := getKubeConfigSpecs(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, kubeConfigFileName := range kubeConfigFileNames {\n\t\t// retrieves the KubeConfigSpec for given kubeConfigFileName\n\t\tspec, exists := specs[kubeConfigFileName]\n\t\tif !exists {\n\t\t\treturn errors.Errorf(\"couldn't retrieve KubeConfigSpec for %s\", kubeConfigFileName)\n\t\t}\n\n\t\t// builds the KubeConfig object\n\t\tconfig, err := buildKubeConfigFromSpec(spec, cfg.ClusterName, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// writes the kubeconfig to disk if it does not exist\n\t\tif err = createKubeConfigFileIfNotExists(outDir, kubeConfigFileName, config); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":107,"to":137}} {"id":100001036,"name":"getKubeConfigSpecs","signature":"func getKubeConfigSpecs(cfg *kubeadmapi.InitConfiguration) (map[string]*kubeConfigSpec, error)","file":"cmd/kubeadm/app/phases/kubeconfig/kubeconfig.go","code":"// getKubeConfigSpecs returns all KubeConfigSpecs actualized to the context of the current InitConfiguration\n// NB. this method holds the information about how kubeadm creates kubeconfig files.\nfunc getKubeConfigSpecs(cfg *kubeadmapi.InitConfiguration) (map[string]*kubeConfigSpec, error) {\n\tcaCert, caKey, err := pkiutil.TryLoadCertAndKeyFromDisk(cfg.CertificatesDir, kubeadmconstants.CACertAndKeyBaseName)\n\tif os.IsNotExist(errors.Cause(err)) {\n\t\treturn nil, errors.Wrap(err, \"the CA files do not exist, please run `kubeadm init phase certs ca` to generate it\")\n\t}\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"couldn't create a kubeconfig; the CA files couldn't be loaded\")\n\t}\n\t// Validate period\n\tcertsphase.CheckCertificatePeriodValidity(kubeadmconstants.CACertAndKeyBaseName, caCert)\n\n\tconfigs, err := getKubeConfigSpecsBase(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, spec := range configs {\n\t\tspec.CACert = caCert\n\t\tspec.ClientCertAuth.CAKey = caKey\n\t}\n\treturn configs, nil\n}","line":{"from":139,"to":161}} {"id":100001037,"name":"buildKubeConfigFromSpec","signature":"func buildKubeConfigFromSpec(spec *kubeConfigSpec, clustername string, notAfter *time.Time) (*clientcmdapi.Config, error)","file":"cmd/kubeadm/app/phases/kubeconfig/kubeconfig.go","code":"// buildKubeConfigFromSpec creates a kubeconfig object for the given kubeConfigSpec\nfunc buildKubeConfigFromSpec(spec *kubeConfigSpec, clustername string, notAfter *time.Time) (*clientcmdapi.Config, error) {\n\n\t// If this kubeconfig should use token\n\tif spec.TokenAuth != nil {\n\t\t// create a kubeconfig with a token\n\t\treturn kubeconfigutil.CreateWithToken(\n\t\t\tspec.APIServer,\n\t\t\tclustername,\n\t\t\tspec.ClientName,\n\t\t\tpkiutil.EncodeCertPEM(spec.CACert),\n\t\t\tspec.TokenAuth.Token,\n\t\t), nil\n\t}\n\n\t// otherwise, create a client certs\n\tclientCertConfig := newClientCertConfigFromKubeConfigSpec(spec, notAfter)\n\n\tclientCert, clientKey, err := pkiutil.NewCertAndKey(spec.CACert, spec.ClientCertAuth.CAKey, \u0026clientCertConfig)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failure while creating %s client certificate\", spec.ClientName)\n\t}\n\n\tencodedClientKey, err := keyutil.MarshalPrivateKeyToPEM(clientKey)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to marshal private key to PEM\")\n\t}\n\t// create a kubeconfig with the client certs\n\treturn kubeconfigutil.CreateWithCerts(\n\t\tspec.APIServer,\n\t\tclustername,\n\t\tspec.ClientName,\n\t\tpkiutil.EncodeCertPEM(spec.CACert),\n\t\tencodedClientKey,\n\t\tpkiutil.EncodeCertPEM(clientCert),\n\t), nil\n}","line":{"from":163,"to":199}} {"id":100001038,"name":"newClientCertConfigFromKubeConfigSpec","signature":"func newClientCertConfigFromKubeConfigSpec(spec *kubeConfigSpec, notAfter *time.Time) pkiutil.CertConfig","file":"cmd/kubeadm/app/phases/kubeconfig/kubeconfig.go","code":"func newClientCertConfigFromKubeConfigSpec(spec *kubeConfigSpec, notAfter *time.Time) pkiutil.CertConfig {\n\treturn pkiutil.CertConfig{\n\t\tConfig: certutil.Config{\n\t\t\tCommonName: spec.ClientName,\n\t\t\tOrganization: spec.ClientCertAuth.Organizations,\n\t\t\tUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},\n\t\t},\n\t\tNotAfter: notAfter,\n\t}\n}","line":{"from":201,"to":210}} {"id":100001039,"name":"validateKubeConfig","signature":"func validateKubeConfig(outDir, filename string, config *clientcmdapi.Config) error","file":"cmd/kubeadm/app/phases/kubeconfig/kubeconfig.go","code":"// validateKubeConfig check if the kubeconfig file exist and has the expected CA and server URL\nfunc validateKubeConfig(outDir, filename string, config *clientcmdapi.Config) error {\n\tkubeConfigFilePath := filepath.Join(outDir, filename)\n\n\tif _, err := os.Stat(kubeConfigFilePath); err != nil {\n\t\treturn err\n\t}\n\n\t// The kubeconfig already exists, let's check if it has got the same CA and server URL\n\tcurrentConfig, err := clientcmd.LoadFromFile(kubeConfigFilePath)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to load kubeconfig file %s that already exists on disk\", kubeConfigFilePath)\n\t}\n\n\texpectedCtx, exists := config.Contexts[config.CurrentContext]\n\tif !exists {\n\t\treturn errors.Errorf(\"failed to find expected context %s\", config.CurrentContext)\n\t}\n\texpectedCluster := expectedCtx.Cluster\n\tcurrentCtx, exists := currentConfig.Contexts[currentConfig.CurrentContext]\n\tif !exists {\n\t\treturn errors.Errorf(\"failed to find CurrentContext in Contexts of the kubeconfig file %s\", kubeConfigFilePath)\n\t}\n\tcurrentCluster := currentCtx.Cluster\n\tif currentConfig.Clusters[currentCluster] == nil {\n\t\treturn errors.Errorf(\"failed to find the given CurrentContext Cluster in Clusters of the kubeconfig file %s\", kubeConfigFilePath)\n\t}\n\n\t// Make sure the compared CAs are whitespace-trimmed. The function clientcmd.LoadFromFile() just decodes\n\t// the base64 CA and places it raw in the v1.Config object. In case the user has extra whitespace\n\t// in the CA they used to create a kubeconfig this comparison to a generated v1.Config will otherwise fail.\n\tcaCurrent := bytes.TrimSpace(currentConfig.Clusters[currentCluster].CertificateAuthorityData)\n\tif len(caCurrent) == 0 {\n\t\t// fallback to load CA cert data from external CA file\n\t\tclusterCAFilePath := currentConfig.Clusters[currentCluster].CertificateAuthority\n\t\tif len(clusterCAFilePath) \u003e 0 {\n\t\t\tclusterCABytes, err := os.ReadFile(clusterCAFilePath)\n\t\t\tif err != nil {\n\t\t\t\tklog.Warningf(\"failed to load CA cert from %q for kubeconfig %q, %v\", clusterCAFilePath, kubeConfigFilePath, err)\n\t\t\t} else {\n\t\t\t\tcaCurrent = bytes.TrimSpace(clusterCABytes)\n\t\t\t}\n\t\t}\n\t}\n\tcaExpected := bytes.TrimSpace(config.Clusters[expectedCluster].CertificateAuthorityData)\n\n\t// If the current CA cert on disk doesn't match the expected CA cert, error out because we have a file, but it's stale\n\tif !bytes.Equal(caCurrent, caExpected) {\n\t\treturn errors.Errorf(\"a kubeconfig file %q exists already but has got the wrong CA cert\", kubeConfigFilePath)\n\t}\n\t// If the current API Server location on disk doesn't match the expected API server, show a warning\n\tif currentConfig.Clusters[currentCluster].Server != config.Clusters[expectedCluster].Server {\n\t\tklog.Warningf(\"a kubeconfig file %q exists already but has an unexpected API Server URL: expected: %s, got: %s\",\n\t\t\tkubeConfigFilePath, config.Clusters[expectedCluster].Server, currentConfig.Clusters[currentCluster].Server)\n\t}\n\n\treturn nil\n}","line":{"from":212,"to":269}} {"id":100001040,"name":"createKubeConfigFileIfNotExists","signature":"func createKubeConfigFileIfNotExists(outDir, filename string, config *clientcmdapi.Config) error","file":"cmd/kubeadm/app/phases/kubeconfig/kubeconfig.go","code":"// createKubeConfigFileIfNotExists saves the KubeConfig object into a file if there isn't any file at the given path.\n// If there already is a kubeconfig file at the given path; kubeadm tries to load it and check if the values in the\n// existing and the expected config equals. If they do; kubeadm will just skip writing the file as it's up-to-date,\n// but if a file exists but has old content or isn't a kubeconfig file, this function returns an error.\nfunc createKubeConfigFileIfNotExists(outDir, filename string, config *clientcmdapi.Config) error {\n\tkubeConfigFilePath := filepath.Join(outDir, filename)\n\n\terr := validateKubeConfig(outDir, filename, config)\n\tif err != nil {\n\t\t// Check if the file exist, and if it doesn't, just write it to disk\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Printf(\"[kubeconfig] Writing %q kubeconfig file\\n\", filename)\n\t\terr = kubeconfigutil.WriteToDisk(kubeConfigFilePath, config)\n\t\treturn errors.Wrapf(err, \"failed to save kubeconfig file %q on disk\", kubeConfigFilePath)\n\t}\n\t// kubeadm doesn't validate the existing kubeconfig file more than this (kubeadm trusts the client certs to be valid)\n\t// Basically, if we find a kubeconfig file with the same path; the same CA cert and the same server URL;\n\t// kubeadm thinks those files are equal and doesn't bother writing a new file\n\tfmt.Printf(\"[kubeconfig] Using existing kubeconfig file: %q\\n\", kubeConfigFilePath)\n\n\treturn nil\n}","line":{"from":271,"to":294}} {"id":100001041,"name":"WriteKubeConfigWithClientCert","signature":"func WriteKubeConfigWithClientCert(out io.Writer, cfg *kubeadmapi.InitConfiguration, clientName string, organizations []string, notAfter *time.Time) error","file":"cmd/kubeadm/app/phases/kubeconfig/kubeconfig.go","code":"// WriteKubeConfigWithClientCert writes a kubeconfig file - with a client certificate as authentication info - to the given writer.\nfunc WriteKubeConfigWithClientCert(out io.Writer, cfg *kubeadmapi.InitConfiguration, clientName string, organizations []string, notAfter *time.Time) error {\n\n\t// creates the KubeConfigSpecs, actualized for the current InitConfiguration\n\tcaCert, caKey, err := pkiutil.TryLoadCertAndKeyFromDisk(cfg.CertificatesDir, kubeadmconstants.CACertAndKeyBaseName)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"couldn't create a kubeconfig; the CA files couldn't be loaded\")\n\t}\n\t// Validate period\n\tcertsphase.CheckCertificatePeriodValidity(kubeadmconstants.CACertAndKeyBaseName, caCert)\n\n\tcontrolPlaneEndpoint, err := kubeadmutil.GetControlPlaneEndpoint(cfg.ControlPlaneEndpoint, \u0026cfg.LocalAPIEndpoint)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tspec := \u0026kubeConfigSpec{\n\t\tClientName: clientName,\n\t\tAPIServer: controlPlaneEndpoint,\n\t\tCACert: caCert,\n\t\tClientCertAuth: \u0026clientCertAuth{\n\t\t\tCAKey: caKey,\n\t\t\tOrganizations: organizations,\n\t\t},\n\t}\n\n\treturn writeKubeConfigFromSpec(out, spec, cfg.ClusterName, notAfter)\n}","line":{"from":296,"to":323}} {"id":100001042,"name":"WriteKubeConfigWithToken","signature":"func WriteKubeConfigWithToken(out io.Writer, cfg *kubeadmapi.InitConfiguration, clientName, token string, notAfter *time.Time) error","file":"cmd/kubeadm/app/phases/kubeconfig/kubeconfig.go","code":"// WriteKubeConfigWithToken writes a kubeconfig file - with a token as client authentication info - to the given writer.\nfunc WriteKubeConfigWithToken(out io.Writer, cfg *kubeadmapi.InitConfiguration, clientName, token string, notAfter *time.Time) error {\n\n\t// creates the KubeConfigSpecs, actualized for the current InitConfiguration\n\tcaCert, _, err := pkiutil.TryLoadCertAndKeyFromDisk(cfg.CertificatesDir, kubeadmconstants.CACertAndKeyBaseName)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"couldn't create a kubeconfig; the CA files couldn't be loaded\")\n\t}\n\t// Validate period\n\tcertsphase.CheckCertificatePeriodValidity(kubeadmconstants.CACertAndKeyBaseName, caCert)\n\n\tcontrolPlaneEndpoint, err := kubeadmutil.GetControlPlaneEndpoint(cfg.ControlPlaneEndpoint, \u0026cfg.LocalAPIEndpoint)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tspec := \u0026kubeConfigSpec{\n\t\tClientName: clientName,\n\t\tAPIServer: controlPlaneEndpoint,\n\t\tCACert: caCert,\n\t\tTokenAuth: \u0026tokenAuth{\n\t\t\tToken: token,\n\t\t},\n\t}\n\n\treturn writeKubeConfigFromSpec(out, spec, cfg.ClusterName, notAfter)\n}","line":{"from":325,"to":351}} {"id":100001043,"name":"writeKubeConfigFromSpec","signature":"func writeKubeConfigFromSpec(out io.Writer, spec *kubeConfigSpec, clustername string, notAfter *time.Time) error","file":"cmd/kubeadm/app/phases/kubeconfig/kubeconfig.go","code":"// writeKubeConfigFromSpec creates a kubeconfig object from a kubeConfigSpec and writes it to the given writer.\nfunc writeKubeConfigFromSpec(out io.Writer, spec *kubeConfigSpec, clustername string, notAfter *time.Time) error {\n\n\t// builds the KubeConfig object\n\tconfig, err := buildKubeConfigFromSpec(spec, clustername, notAfter)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// writes the kubeconfig to disk if it not exists\n\tconfigBytes, err := clientcmd.Write(*config)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failure while serializing admin kubeconfig\")\n\t}\n\n\tfmt.Fprintln(out, string(configBytes))\n\treturn nil\n}","line":{"from":353,"to":370}} {"id":100001044,"name":"ValidateKubeconfigsForExternalCA","signature":"func ValidateKubeconfigsForExternalCA(outDir string, cfg *kubeadmapi.InitConfiguration) error","file":"cmd/kubeadm/app/phases/kubeconfig/kubeconfig.go","code":"// ValidateKubeconfigsForExternalCA check if the kubeconfig file exist and has the expected CA and server URL using kubeadmapi.InitConfiguration.\nfunc ValidateKubeconfigsForExternalCA(outDir string, cfg *kubeadmapi.InitConfiguration) error {\n\t// Creates a kubeconfig file with the target CA and server URL\n\t// to be used as a input for validating user provided kubeconfig files\n\tcaCert, err := pkiutil.TryLoadCertFromDisk(cfg.CertificatesDir, kubeadmconstants.CACertAndKeyBaseName)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"the CA file couldn't be loaded\")\n\t}\n\t// Validate period\n\tcertsphase.CheckCertificatePeriodValidity(kubeadmconstants.CACertAndKeyBaseName, caCert)\n\n\t// validate user provided kubeconfig files for the scheduler and controller-manager\n\tlocalAPIEndpoint, err := kubeadmutil.GetLocalAPIEndpoint(\u0026cfg.LocalAPIEndpoint)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvalidationConfigLocal := kubeconfigutil.CreateBasic(localAPIEndpoint, \"dummy\", \"dummy\", pkiutil.EncodeCertPEM(caCert))\n\tkubeConfigFileNamesLocal := []string{\n\t\tkubeadmconstants.ControllerManagerKubeConfigFileName,\n\t\tkubeadmconstants.SchedulerKubeConfigFileName,\n\t}\n\n\tfor _, kubeConfigFileName := range kubeConfigFileNamesLocal {\n\t\tif err = validateKubeConfig(outDir, kubeConfigFileName, validationConfigLocal); err != nil {\n\t\t\treturn errors.Wrapf(err, \"the %s file does not exists or it is not valid\", kubeConfigFileName)\n\t\t}\n\t}\n\n\t// validate user provided kubeconfig files for the kubelet and admin\n\tcontrolPlaneEndpoint, err := kubeadmutil.GetControlPlaneEndpoint(cfg.ControlPlaneEndpoint, \u0026cfg.LocalAPIEndpoint)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvalidationConfigCPE := kubeconfigutil.CreateBasic(controlPlaneEndpoint, \"dummy\", \"dummy\", pkiutil.EncodeCertPEM(caCert))\n\tkubeConfigFileNamesCPE := []string{\n\t\tkubeadmconstants.AdminKubeConfigFileName,\n\t\tkubeadmconstants.KubeletKubeConfigFileName,\n\t}\n\n\tfor _, kubeConfigFileName := range kubeConfigFileNamesCPE {\n\t\tif err = validateKubeConfig(outDir, kubeConfigFileName, validationConfigCPE); err != nil {\n\t\t\treturn errors.Wrapf(err, \"the %s file does not exists or it is not valid\", kubeConfigFileName)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":372,"to":420}} {"id":100001045,"name":"getKubeConfigSpecsBase","signature":"func getKubeConfigSpecsBase(cfg *kubeadmapi.InitConfiguration) (map[string]*kubeConfigSpec, error)","file":"cmd/kubeadm/app/phases/kubeconfig/kubeconfig.go","code":"func getKubeConfigSpecsBase(cfg *kubeadmapi.InitConfiguration) (map[string]*kubeConfigSpec, error) {\n\tcontrolPlaneEndpoint, err := kubeadmutil.GetControlPlaneEndpoint(cfg.ControlPlaneEndpoint, \u0026cfg.LocalAPIEndpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlocalAPIEndpoint, err := kubeadmutil.GetLocalAPIEndpoint(\u0026cfg.LocalAPIEndpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn map[string]*kubeConfigSpec{\n\t\tkubeadmconstants.AdminKubeConfigFileName: {\n\t\t\tAPIServer: controlPlaneEndpoint,\n\t\t\tClientName: \"kubernetes-admin\",\n\t\t\tClientCertAuth: \u0026clientCertAuth{\n\t\t\t\tOrganizations: []string{kubeadmconstants.SystemPrivilegedGroup},\n\t\t\t},\n\t\t},\n\t\tkubeadmconstants.KubeletKubeConfigFileName: {\n\t\t\tAPIServer: controlPlaneEndpoint,\n\t\t\tClientName: fmt.Sprintf(\"%s%s\", kubeadmconstants.NodesUserPrefix, cfg.NodeRegistration.Name),\n\t\t\tClientCertAuth: \u0026clientCertAuth{\n\t\t\t\tOrganizations: []string{kubeadmconstants.NodesGroup},\n\t\t\t},\n\t\t},\n\t\tkubeadmconstants.ControllerManagerKubeConfigFileName: {\n\t\t\tAPIServer: localAPIEndpoint,\n\t\t\tClientName: kubeadmconstants.ControllerManagerUser,\n\t\t\tClientCertAuth: \u0026clientCertAuth{},\n\t\t},\n\t\tkubeadmconstants.SchedulerKubeConfigFileName: {\n\t\t\tAPIServer: localAPIEndpoint,\n\t\t\tClientName: kubeadmconstants.SchedulerUser,\n\t\t\tClientCertAuth: \u0026clientCertAuth{},\n\t\t},\n\t}, nil\n}","line":{"from":422,"to":458}} {"id":100001046,"name":"createKubeConfigAndCSR","signature":"func createKubeConfigAndCSR(kubeConfigDir string, kubeadmConfig *kubeadmapi.InitConfiguration, name string, spec *kubeConfigSpec) error","file":"cmd/kubeadm/app/phases/kubeconfig/kubeconfig.go","code":"func createKubeConfigAndCSR(kubeConfigDir string, kubeadmConfig *kubeadmapi.InitConfiguration, name string, spec *kubeConfigSpec) error {\n\tif kubeConfigDir == \"\" {\n\t\treturn errors.Errorf(\"%s: kubeConfigDir was empty\", errInvalid)\n\t}\n\tif kubeadmConfig == nil {\n\t\treturn errors.Errorf(\"%s: kubeadmConfig was nil\", errInvalid)\n\t}\n\tif name == \"\" {\n\t\treturn errors.Errorf(\"%s: name was empty\", errInvalid)\n\t}\n\tif spec == nil {\n\t\treturn errors.Errorf(\"%s: spec was nil\", errInvalid)\n\t}\n\tkubeConfigPath := filepath.Join(kubeConfigDir, name)\n\tif _, err := os.Stat(kubeConfigPath); err == nil {\n\t\treturn errors.Errorf(\"%s: kube config: %s\", errExist, kubeConfigPath)\n\t} else if !os.IsNotExist(err) {\n\t\treturn errors.Wrapf(err, \"unexpected error while checking if file exists: %s\", kubeConfigPath)\n\t}\n\tif pkiutil.CSROrKeyExist(kubeConfigDir, name) {\n\t\treturn errors.Errorf(\"%s: csr: %s\", errExist, kubeConfigPath)\n\t}\n\n\tclientCertConfig := newClientCertConfigFromKubeConfigSpec(spec, nil)\n\n\tclientKey, err := pkiutil.NewPrivateKey(clientCertConfig.PublicKeyAlgorithm)\n\tif err != nil {\n\t\treturn err\n\t}\n\tclientCSR, err := pkiutil.NewCSR(clientCertConfig, clientKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tencodedClientKey, err := keyutil.MarshalPrivateKeyToPEM(clientKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar (\n\t\temptyCACert []byte\n\t\temptyClientCert []byte\n\t)\n\n\t// create a kubeconfig with the client certs\n\tconfig := kubeconfigutil.CreateWithCerts(\n\t\tspec.APIServer,\n\t\tkubeadmConfig.ClusterName,\n\t\tspec.ClientName,\n\t\temptyCACert,\n\t\tencodedClientKey,\n\t\temptyClientCert,\n\t)\n\n\tif err := kubeconfigutil.WriteToDisk(kubeConfigPath, config); err != nil {\n\t\treturn err\n\t}\n\t// Write CSR to disk\n\tif err := pkiutil.WriteCSR(kubeConfigDir, name, clientCSR); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":460,"to":522}} {"id":100001047,"name":"CreateDefaultKubeConfigsAndCSRFiles","signature":"func CreateDefaultKubeConfigsAndCSRFiles(out io.Writer, kubeConfigDir string, kubeadmConfig *kubeadmapi.InitConfiguration) error","file":"cmd/kubeadm/app/phases/kubeconfig/kubeconfig.go","code":"// CreateDefaultKubeConfigsAndCSRFiles is used in ExternalCA mode to create\n// kubeconfig files and adjacent CSR files.\nfunc CreateDefaultKubeConfigsAndCSRFiles(out io.Writer, kubeConfigDir string, kubeadmConfig *kubeadmapi.InitConfiguration) error {\n\tkubeConfigs, err := getKubeConfigSpecsBase(kubeadmConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif out != nil {\n\t\tfmt.Fprintf(out, \"generating keys and CSRs in %s\\n\", kubeConfigDir)\n\t}\n\tfor name, spec := range kubeConfigs {\n\t\tif err := createKubeConfigAndCSR(kubeConfigDir, kubeadmConfig, name, spec); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif out != nil {\n\t\t\tfmt.Fprintf(out, \" %s\\n\", name)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":524,"to":543}} {"id":100001048,"name":"WriteConfigToDisk","signature":"func WriteConfigToDisk(cfg *kubeadmapi.ClusterConfiguration, kubeletDir, patchesDir string, output io.Writer) error","file":"cmd/kubeadm/app/phases/kubelet/config.go","code":"// WriteConfigToDisk writes the kubelet config object down to a file\n// Used at \"kubeadm init\" and \"kubeadm upgrade\" time\nfunc WriteConfigToDisk(cfg *kubeadmapi.ClusterConfiguration, kubeletDir, patchesDir string, output io.Writer) error {\n\tkubeletCfg, ok := cfg.ComponentConfigs[componentconfigs.KubeletGroup]\n\tif !ok {\n\t\treturn errors.New(\"no kubelet component config found\")\n\t}\n\n\tif err := kubeletCfg.Mutate(); err != nil {\n\t\treturn err\n\t}\n\n\tkubeletBytes, err := kubeletCfg.Marshal()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Apply patches to the KubeletConfiguration\n\tif len(patchesDir) != 0 {\n\t\tkubeletBytes, err = applyKubeletConfigPatches(kubeletBytes, patchesDir, output)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"could not apply patches to the KubeletConfiguration\")\n\t\t}\n\t}\n\n\treturn writeConfigBytesToDisk(kubeletBytes, kubeletDir)\n}","line":{"from":41,"to":67}} {"id":100001049,"name":"CreateConfigMap","signature":"func CreateConfigMap(cfg *kubeadmapi.ClusterConfiguration, patchesDir string, client clientset.Interface) error","file":"cmd/kubeadm/app/phases/kubelet/config.go","code":"// CreateConfigMap creates a ConfigMap with the generic kubelet configuration.\n// Used at \"kubeadm init\" and \"kubeadm upgrade\" time\nfunc CreateConfigMap(cfg *kubeadmapi.ClusterConfiguration, patchesDir string, client clientset.Interface) error {\n\tkubeletCfg, ok := cfg.ComponentConfigs[componentconfigs.KubeletGroup]\n\tif !ok {\n\t\treturn errors.New(\"no kubelet component config found in the active component config set\")\n\t}\n\n\tkubeletBytes, err := kubeletCfg.Marshal()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Apply patches to the KubeletConfiguration\n\tif len(patchesDir) != 0 {\n\t\tkubeletBytes, err = applyKubeletConfigPatches(kubeletBytes, patchesDir, os.Stdout)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"could not apply patches to the KubeletConfiguration\")\n\t\t}\n\t}\n\n\tconfigMapName := kubeadmconstants.KubeletBaseConfigurationConfigMap\n\tfmt.Printf(\"[kubelet] Creating a ConfigMap %q in namespace %s with the configuration for the kubelets in the cluster\\n\", configMapName, metav1.NamespaceSystem)\n\n\tconfigMap := \u0026v1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: configMapName,\n\t\t\tNamespace: metav1.NamespaceSystem,\n\t\t},\n\t\tData: map[string]string{\n\t\t\tkubeadmconstants.KubeletBaseConfigurationConfigMapKey: string(kubeletBytes),\n\t\t},\n\t}\n\n\tif !kubeletCfg.IsUserSupplied() {\n\t\tcomponentconfigs.SignConfigMap(configMap)\n\t}\n\n\tif err := apiclient.CreateOrUpdateConfigMap(client, configMap); err != nil {\n\t\treturn err\n\t}\n\n\tif err := createConfigMapRBACRules(client); err != nil {\n\t\treturn errors.Wrap(err, \"error creating kubelet configuration configmap RBAC rules\")\n\t}\n\treturn nil\n}","line":{"from":69,"to":115}} {"id":100001050,"name":"createConfigMapRBACRules","signature":"func createConfigMapRBACRules(client clientset.Interface) error","file":"cmd/kubeadm/app/phases/kubelet/config.go","code":"// createConfigMapRBACRules creates the RBAC rules for exposing the base kubelet ConfigMap in the kube-system namespace to unauthenticated users\nfunc createConfigMapRBACRules(client clientset.Interface) error {\n\tif err := apiclient.CreateOrUpdateRole(client, \u0026rbac.Role{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: kubeadmconstants.KubeletBaseConfigMapRole,\n\t\t\tNamespace: metav1.NamespaceSystem,\n\t\t},\n\t\tRules: []rbac.PolicyRule{\n\t\t\t{\n\t\t\t\tVerbs: []string{\"get\"},\n\t\t\t\tAPIGroups: []string{\"\"},\n\t\t\t\tResources: []string{\"configmaps\"},\n\t\t\t\tResourceNames: []string{kubeadmconstants.KubeletBaseConfigurationConfigMap},\n\t\t\t},\n\t\t},\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\treturn apiclient.CreateOrUpdateRoleBinding(client, \u0026rbac.RoleBinding{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: kubeadmconstants.KubeletBaseConfigMapRole,\n\t\t\tNamespace: metav1.NamespaceSystem,\n\t\t},\n\t\tRoleRef: rbac.RoleRef{\n\t\t\tAPIGroup: rbac.GroupName,\n\t\t\tKind: \"Role\",\n\t\t\tName: kubeadmconstants.KubeletBaseConfigMapRole,\n\t\t},\n\t\tSubjects: []rbac.Subject{\n\t\t\t{\n\t\t\t\tKind: rbac.GroupKind,\n\t\t\t\tName: kubeadmconstants.NodesGroup,\n\t\t\t},\n\t\t\t{\n\t\t\t\tKind: rbac.GroupKind,\n\t\t\t\tName: kubeadmconstants.NodeBootstrapTokenAuthGroup,\n\t\t\t},\n\t\t},\n\t})\n}","line":{"from":117,"to":157}} {"id":100001051,"name":"writeConfigBytesToDisk","signature":"func writeConfigBytesToDisk(b []byte, kubeletDir string) error","file":"cmd/kubeadm/app/phases/kubelet/config.go","code":"// writeConfigBytesToDisk writes a byte slice down to disk at the specific location of the kubelet config file\nfunc writeConfigBytesToDisk(b []byte, kubeletDir string) error {\n\tconfigFile := filepath.Join(kubeletDir, kubeadmconstants.KubeletConfigurationFileName)\n\tfmt.Printf(\"[kubelet-start] Writing kubelet configuration to file %q\\n\", configFile)\n\n\t// creates target folder if not already exists\n\tif err := os.MkdirAll(kubeletDir, 0700); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to create directory %q\", kubeletDir)\n\t}\n\n\tif err := os.WriteFile(configFile, b, 0644); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to write kubelet configuration to the file %q\", configFile)\n\t}\n\treturn nil\n}","line":{"from":159,"to":173}} {"id":100001052,"name":"applyKubeletConfigPatches","signature":"func applyKubeletConfigPatches(kubeletBytes []byte, patchesDir string, output io.Writer) ([]byte, error)","file":"cmd/kubeadm/app/phases/kubelet/config.go","code":"// applyKubeletConfigPatches reads patches from a directory and applies them over the input kubeletBytes\nfunc applyKubeletConfigPatches(kubeletBytes []byte, patchesDir string, output io.Writer) ([]byte, error) {\n\tpatchManager, err := patches.GetPatchManagerForPath(patchesDir, patches.KnownTargets(), output)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpatchTarget := \u0026patches.PatchTarget{\n\t\tName: patches.KubeletConfiguration,\n\t\tStrategicMergePatchObject: kubeletconfig.KubeletConfiguration{},\n\t\tData: kubeletBytes,\n\t}\n\tif err := patchManager.ApplyPatchesToTarget(patchTarget); err != nil {\n\t\treturn nil, err\n\t}\n\n\tkubeletBytes, err = yaml.JSONToYAML(patchTarget.Data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn kubeletBytes, nil\n}","line":{"from":175,"to":196}} {"id":100001053,"name":"GetNodeNameAndHostname","signature":"func GetNodeNameAndHostname(cfg *kubeadmapi.NodeRegistrationOptions) (string, string, error)","file":"cmd/kubeadm/app/phases/kubelet/flags.go","code":"// GetNodeNameAndHostname obtains the name for this Node using the following precedence\n// (from lower to higher):\n// - actual hostname\n// - NodeRegistrationOptions.Name (same as \"--node-name\" passed to \"kubeadm init/join\")\n// - \"hostname-override\" flag in NodeRegistrationOptions.KubeletExtraArgs\n// It also returns the hostname or an error if getting the hostname failed.\nfunc GetNodeNameAndHostname(cfg *kubeadmapi.NodeRegistrationOptions) (string, string, error) {\n\thostname, err := nodeutil.GetHostname(\"\")\n\tnodeName := hostname\n\tif cfg.Name != \"\" {\n\t\tnodeName = cfg.Name\n\t}\n\tif name, ok := cfg.KubeletExtraArgs[\"hostname-override\"]; ok {\n\t\tnodeName = name\n\t}\n\treturn nodeName, hostname, err\n}","line":{"from":42,"to":58}} {"id":100001054,"name":"WriteKubeletDynamicEnvFile","signature":"func WriteKubeletDynamicEnvFile(cfg *kubeadmapi.ClusterConfiguration, nodeReg *kubeadmapi.NodeRegistrationOptions, registerTaintsUsingFlags bool, kubeletDir string) error","file":"cmd/kubeadm/app/phases/kubelet/flags.go","code":"// WriteKubeletDynamicEnvFile writes an environment file with dynamic flags to the kubelet.\n// Used at \"kubeadm init\" and \"kubeadm join\" time.\nfunc WriteKubeletDynamicEnvFile(cfg *kubeadmapi.ClusterConfiguration, nodeReg *kubeadmapi.NodeRegistrationOptions, registerTaintsUsingFlags bool, kubeletDir string) error {\n\tflagOpts := kubeletFlagsOpts{\n\t\tnodeRegOpts: nodeReg,\n\t\tpauseImage: images.GetPauseImage(cfg),\n\t\tregisterTaintsUsingFlags: registerTaintsUsingFlags,\n\t}\n\tstringMap := buildKubeletArgMap(flagOpts)\n\targList := kubeadmutil.BuildArgumentListFromMap(stringMap, nodeReg.KubeletExtraArgs)\n\tenvFileContent := fmt.Sprintf(\"%s=%q\\n\", constants.KubeletEnvFileVariableName, strings.Join(argList, \" \"))\n\n\treturn writeKubeletFlagBytesToDisk([]byte(envFileContent), kubeletDir)\n}","line":{"from":60,"to":73}} {"id":100001055,"name":"buildKubeletArgMapCommon","signature":"func buildKubeletArgMapCommon(opts kubeletFlagsOpts) map[string]string","file":"cmd/kubeadm/app/phases/kubelet/flags.go","code":"// buildKubeletArgMapCommon takes a kubeletFlagsOpts object and builds based on that a string-string map with flags\n// that are common to both Linux and Windows\nfunc buildKubeletArgMapCommon(opts kubeletFlagsOpts) map[string]string {\n\tkubeletFlags := map[string]string{}\n\tkubeletFlags[\"container-runtime-endpoint\"] = opts.nodeRegOpts.CRISocket\n\n\t// This flag passes the pod infra container image (e.g. \"pause\" image) to the kubelet\n\t// and prevents its garbage collection\n\tif opts.pauseImage != \"\" {\n\t\tkubeletFlags[\"pod-infra-container-image\"] = opts.pauseImage\n\t}\n\n\tif opts.registerTaintsUsingFlags \u0026\u0026 opts.nodeRegOpts.Taints != nil \u0026\u0026 len(opts.nodeRegOpts.Taints) \u003e 0 {\n\t\ttaintStrs := []string{}\n\t\tfor _, taint := range opts.nodeRegOpts.Taints {\n\t\t\ttaintStrs = append(taintStrs, taint.ToString())\n\t\t}\n\n\t\tkubeletFlags[\"register-with-taints\"] = strings.Join(taintStrs, \",\")\n\t}\n\n\t// Pass the \"--hostname-override\" flag to the kubelet only if it's different from the hostname\n\tnodeName, hostname, err := GetNodeNameAndHostname(opts.nodeRegOpts)\n\tif err != nil {\n\t\tklog.Warning(err)\n\t}\n\tif nodeName != hostname {\n\t\tklog.V(1).Infof(\"setting kubelet hostname-override to %q\", nodeName)\n\t\tkubeletFlags[\"hostname-override\"] = nodeName\n\t}\n\n\treturn kubeletFlags\n}","line":{"from":75,"to":107}} {"id":100001056,"name":"writeKubeletFlagBytesToDisk","signature":"func writeKubeletFlagBytesToDisk(b []byte, kubeletDir string) error","file":"cmd/kubeadm/app/phases/kubelet/flags.go","code":"// writeKubeletFlagBytesToDisk writes a byte slice down to disk at the specific location of the kubelet flag overrides file\nfunc writeKubeletFlagBytesToDisk(b []byte, kubeletDir string) error {\n\tkubeletEnvFilePath := filepath.Join(kubeletDir, constants.KubeletEnvFileName)\n\tfmt.Printf(\"[kubelet-start] Writing kubelet environment file with flags to file %q\\n\", kubeletEnvFilePath)\n\n\t// creates target folder if not already exists\n\tif err := os.MkdirAll(kubeletDir, 0700); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to create directory %q\", kubeletDir)\n\t}\n\tif err := os.WriteFile(kubeletEnvFilePath, b, 0644); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to write kubelet configuration to the file %q\", kubeletEnvFilePath)\n\t}\n\treturn nil\n}","line":{"from":109,"to":122}} {"id":100001057,"name":"buildKubeletArgMap","signature":"func buildKubeletArgMap(opts kubeletFlagsOpts) map[string]string","file":"cmd/kubeadm/app/phases/kubelet/flags.go","code":"// buildKubeletArgMap takes a kubeletFlagsOpts object and builds based on that a string-string map with flags\n// that should be given to the local kubelet daemon.\nfunc buildKubeletArgMap(opts kubeletFlagsOpts) map[string]string {\n\treturn buildKubeletArgMapCommon(opts)\n}","line":{"from":124,"to":128}} {"id":100001058,"name":"TryStartKubelet","signature":"func TryStartKubelet()","file":"cmd/kubeadm/app/phases/kubelet/kubelet.go","code":"// TryStartKubelet attempts to bring up kubelet service\nfunc TryStartKubelet() {\n\t// If we notice that the kubelet service is inactive, try to start it\n\tinitSystem, err := initsystem.GetInitSystem()\n\tif err != nil {\n\t\tfmt.Println(\"[kubelet-start] No supported init system detected, won't make sure the kubelet is running properly.\")\n\t\treturn\n\t}\n\n\tif !initSystem.ServiceExists(kubeadmconstants.Kubelet) {\n\t\tfmt.Println(\"[kubelet-start] Couldn't detect a kubelet service, can't make sure the kubelet is running properly.\")\n\t}\n\n\t// This runs \"systemctl daemon-reload \u0026\u0026 systemctl restart kubelet\"\n\tif err := initSystem.ServiceRestart(kubeadmconstants.Kubelet); err != nil {\n\t\tklog.Warningf(\"[kubelet-start] WARNING: unable to start the kubelet service: [%v]\\n\", err)\n\t\tfmt.Printf(\"[kubelet-start] Please ensure kubelet is reloaded and running manually.\\n\")\n\t}\n}","line":{"from":28,"to":46}} {"id":100001059,"name":"TryStopKubelet","signature":"func TryStopKubelet()","file":"cmd/kubeadm/app/phases/kubelet/kubelet.go","code":"// TryStopKubelet attempts to bring down the kubelet service momentarily\nfunc TryStopKubelet() {\n\t// If we notice that the kubelet service is inactive, try to start it\n\tinitSystem, err := initsystem.GetInitSystem()\n\tif err != nil {\n\t\tfmt.Println(\"[kubelet-start] No supported init system detected, won't make sure the kubelet not running for a short period of time while setting up configuration for it.\")\n\t\treturn\n\t}\n\n\tif !initSystem.ServiceExists(kubeadmconstants.Kubelet) {\n\t\tfmt.Println(\"[kubelet-start] Couldn't detect a kubelet service, can't make sure the kubelet not running for a short period of time while setting up configuration for it.\")\n\t}\n\n\t// This runs \"systemctl daemon-reload \u0026\u0026 systemctl stop kubelet\"\n\tif err := initSystem.ServiceStop(kubeadmconstants.Kubelet); err != nil {\n\t\tklog.Warningf(\"[kubelet-start] WARNING: unable to stop the kubelet service momentarily: [%v]\\n\", err)\n\t}\n}","line":{"from":48,"to":65}} {"id":100001060,"name":"TryRestartKubelet","signature":"func TryRestartKubelet()","file":"cmd/kubeadm/app/phases/kubelet/kubelet.go","code":"// TryRestartKubelet attempts to restart the kubelet service\nfunc TryRestartKubelet() {\n\t// If we notice that the kubelet service is inactive, try to start it\n\tinitSystem, err := initsystem.GetInitSystem()\n\tif err != nil {\n\t\tfmt.Println(\"[kubelet-start] No supported init system detected, won't make sure the kubelet not running for a short period of time while setting up configuration for it.\")\n\t\treturn\n\t}\n\n\tif !initSystem.ServiceExists(kubeadmconstants.Kubelet) {\n\t\tfmt.Println(\"[kubelet-start] Couldn't detect a kubelet service, can't make sure the kubelet not running for a short period of time while setting up configuration for it.\")\n\t}\n\n\t// This runs \"systemctl daemon-reload \u0026\u0026 systemctl stop kubelet\"\n\tif err := initSystem.ServiceRestart(kubeadmconstants.Kubelet); err != nil {\n\t\tklog.Warningf(\"[kubelet-start] WARNING: unable to restart the kubelet service momentarily: [%v]\\n\", err)\n\t}\n}","line":{"from":67,"to":84}} {"id":100001061,"name":"MarkControlPlane","signature":"func MarkControlPlane(client clientset.Interface, controlPlaneName string, taints []v1.Taint) error","file":"cmd/kubeadm/app/phases/markcontrolplane/markcontrolplane.go","code":"// MarkControlPlane taints the control-plane and sets the control-plane label\nfunc MarkControlPlane(client clientset.Interface, controlPlaneName string, taints []v1.Taint) error {\n\tfmt.Printf(\"[mark-control-plane] Marking the node %s as control-plane by adding the labels: %v\\n\",\n\t\tcontrolPlaneName, labelsToAdd)\n\n\tif len(taints) \u003e 0 {\n\t\ttaintStrs := []string{}\n\t\tfor _, taint := range taints {\n\t\t\ttaintStrs = append(taintStrs, taint.ToString())\n\t\t}\n\t\tfmt.Printf(\"[mark-control-plane] Marking the node %s as control-plane by adding the taints %v\\n\", controlPlaneName, taintStrs)\n\t}\n\n\treturn apiclient.PatchNode(client, controlPlaneName, func(n *v1.Node) {\n\t\tmarkControlPlaneNode(n, taints)\n\t})\n}","line":{"from":35,"to":51}} {"id":100001062,"name":"taintExists","signature":"func taintExists(taint v1.Taint, taints []v1.Taint) bool","file":"cmd/kubeadm/app/phases/markcontrolplane/markcontrolplane.go","code":"func taintExists(taint v1.Taint, taints []v1.Taint) bool {\n\tfor _, t := range taints {\n\t\tif t == taint {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":53,"to":61}} {"id":100001063,"name":"markControlPlaneNode","signature":"func markControlPlaneNode(n *v1.Node, taints []v1.Taint)","file":"cmd/kubeadm/app/phases/markcontrolplane/markcontrolplane.go","code":"func markControlPlaneNode(n *v1.Node, taints []v1.Taint) {\n\tfor _, label := range labelsToAdd {\n\t\tn.ObjectMeta.Labels[label] = \"\"\n\t}\n\n\tfor _, nt := range n.Spec.Taints {\n\t\tif !taintExists(nt, taints) {\n\t\t\ttaints = append(taints, nt)\n\t\t}\n\t}\n\n\tn.Spec.Taints = taints\n}","line":{"from":63,"to":75}} {"id":100001064,"name":"AnnotateCRISocket","signature":"func AnnotateCRISocket(client clientset.Interface, nodeName string, criSocket string) error","file":"cmd/kubeadm/app/phases/patchnode/patchnode.go","code":"// AnnotateCRISocket annotates the node with the given crisocket\nfunc AnnotateCRISocket(client clientset.Interface, nodeName string, criSocket string) error {\n\n\tklog.V(1).Infof(\"[patchnode] Uploading the CRI Socket information %q to the Node API object %q as an annotation\\n\", criSocket, nodeName)\n\n\treturn apiclient.PatchNode(client, nodeName, func(n *v1.Node) {\n\t\tannotateNodeWithCRISocket(n, criSocket)\n\t})\n}","line":{"from":28,"to":36}} {"id":100001065,"name":"annotateNodeWithCRISocket","signature":"func annotateNodeWithCRISocket(n *v1.Node, criSocket string)","file":"cmd/kubeadm/app/phases/patchnode/patchnode.go","code":"func annotateNodeWithCRISocket(n *v1.Node, criSocket string) {\n\tif n.ObjectMeta.Annotations == nil {\n\t\tn.ObjectMeta.Annotations = make(map[string]string)\n\t}\n\tn.ObjectMeta.Annotations[constants.AnnotationKubeadmCRISocket] = criSocket\n}","line":{"from":38,"to":43}} {"id":100001066,"name":"CanUpgradeKubelets","signature":"func (u *Upgrade) CanUpgradeKubelets() bool","file":"cmd/kubeadm/app/phases/upgrade/compute.go","code":"// CanUpgradeKubelets returns whether an upgrade of any kubelet in the cluster is possible\nfunc (u *Upgrade) CanUpgradeKubelets() bool {\n\t// If there are multiple different versions now, an upgrade is possible (even if only for a subset of the nodes)\n\tif len(u.Before.KubeletVersions) \u003e 1 {\n\t\treturn true\n\t}\n\t// Don't report something available for upgrade if we don't know the current state\n\tif len(u.Before.KubeletVersions) == 0 {\n\t\treturn false\n\t}\n\n\t// if the same version number existed both before and after, we don't have to upgrade it\n\t_, sameVersionFound := u.Before.KubeletVersions[u.After.KubeVersion]\n\treturn !sameVersionFound\n}","line":{"from":39,"to":53}} {"id":100001067,"name":"CanUpgradeEtcd","signature":"func (u *Upgrade) CanUpgradeEtcd() bool","file":"cmd/kubeadm/app/phases/upgrade/compute.go","code":"// CanUpgradeEtcd returns whether an upgrade of etcd is possible\nfunc (u *Upgrade) CanUpgradeEtcd() bool {\n\treturn u.Before.EtcdVersion != u.After.EtcdVersion\n}","line":{"from":55,"to":58}} {"id":100001068,"name":"GetAvailableUpgrades","signature":"func GetAvailableUpgrades(versionGetterImpl VersionGetter, experimentalUpgradesAllowed, rcUpgradesAllowed, externalEtcd bool, client clientset.Interface, manifestsDir string, printer output.Printer) ([]Upgrade, error)","file":"cmd/kubeadm/app/phases/upgrade/compute.go","code":"// GetAvailableUpgrades fetches all versions from the specified VersionGetter and computes which\n// kinds of upgrades can be performed\nfunc GetAvailableUpgrades(versionGetterImpl VersionGetter, experimentalUpgradesAllowed, rcUpgradesAllowed, externalEtcd bool, client clientset.Interface, manifestsDir string, printer output.Printer) ([]Upgrade, error) {\n\tprinter.Printf(\"[upgrade] Fetching available versions to upgrade to\\n\")\n\n\t// Collect the upgrades kubeadm can do in this list\n\tvar upgrades []Upgrade\n\n\t// Get the cluster version\n\tclusterVersionStr, clusterVersion, err := versionGetterImpl.ClusterVersion()\n\tif err != nil {\n\t\treturn upgrades, err\n\t}\n\tprinter.Printf(\"[upgrade/versions] Cluster version: %s\\n\", clusterVersionStr)\n\n\t// Get current kubeadm CLI version\n\tkubeadmVersionStr, kubeadmVersion, err := versionGetterImpl.KubeadmVersion()\n\tif err != nil {\n\t\treturn upgrades, err\n\t}\n\tprinter.Printf(\"[upgrade/versions] kubeadm version: %s\\n\", kubeadmVersionStr)\n\n\t// Get and output the current latest stable version\n\tstableVersionStr, stableVersion, err := versionGetterImpl.VersionFromCILabel(\"stable\", \"stable version\")\n\tif err != nil {\n\t\tklog.Warningf(\"[upgrade/versions] WARNING: %v\\n\", err)\n\t\tklog.Warningf(\"[upgrade/versions] WARNING: Falling back to current kubeadm version as latest stable version\")\n\t\tstableVersionStr, stableVersion = kubeadmVersionStr, kubeadmVersion\n\t} else {\n\t\tprinter.Printf(\"[upgrade/versions] Target version: %s\\n\", stableVersionStr)\n\t}\n\n\t// Get the kubelet versions in the cluster\n\tkubeletVersions, err := versionGetterImpl.KubeletVersions()\n\tif err != nil {\n\t\treturn upgrades, err\n\t}\n\n\t// Get current stacked etcd version on the local node\n\tvar etcdVersion string\n\tif !externalEtcd {\n\t\tetcdVersion, err = GetEtcdImageTagFromStaticPod(manifestsDir)\n\t\tif err != nil {\n\t\t\treturn upgrades, err\n\t\t}\n\t}\n\n\tdnsVersion, err := dns.DeployedDNSAddon(client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Construct a descriptor for the current state of the world\n\tbeforeState := ClusterState{\n\t\tKubeVersion: clusterVersionStr,\n\t\tDNSVersion: dnsVersion,\n\t\tKubeadmVersion: kubeadmVersionStr,\n\t\tKubeletVersions: kubeletVersions,\n\t\tEtcdVersion: etcdVersion,\n\t}\n\n\t// Do a \"dumb guess\" that a new minor upgrade is available just because the latest stable version is higher than the cluster version\n\t// This guess will be corrected once we know if there is a patch version available\n\tcanDoMinorUpgrade := clusterVersion.LessThan(stableVersion)\n\n\t// A patch version doesn't exist if the cluster version is higher than or equal to the current stable version\n\t// in the case that a user is trying to upgrade from, let's say, v1.8.0-beta.2 to v1.8.0-rc.1 (given we support such upgrades experimentally)\n\t// a stable-1.8 branch doesn't exist yet. Hence this check.\n\tif patchVersionBranchExists(clusterVersion, stableVersion) {\n\t\tcurrentBranch := getBranchFromVersion(clusterVersionStr)\n\t\tversionLabel := fmt.Sprintf(\"stable-%s\", currentBranch)\n\t\tdescription := fmt.Sprintf(\"version in the v%s series\", currentBranch)\n\n\t\t// Get and output the latest patch version for the cluster branch\n\t\tpatchVersionStr, patchVersion, err := versionGetterImpl.VersionFromCILabel(versionLabel, description)\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"[upgrade/versions] WARNING: %v\\n\", err)\n\t\t} else {\n\t\t\tprinter.Printf(\"[upgrade/versions] Latest %s: %s\\n\", description, patchVersionStr)\n\n\t\t\t// Check if a minor version upgrade is possible when a patch release exists\n\t\t\t// It's only possible if the latest patch version is higher than the current patch version\n\t\t\t// If that's the case, they must be on different branches =\u003e a newer minor version can be upgraded to\n\t\t\tcanDoMinorUpgrade = minorUpgradePossibleWithPatchRelease(stableVersion, patchVersion)\n\n\t\t\t// If the cluster version is lower than the newest patch version, we should inform about the possible upgrade\n\t\t\tif patchUpgradePossible(clusterVersion, patchVersion) {\n\n\t\t\t\t// The kubeadm version has to be upgraded to the latest patch version\n\t\t\t\tnewKubeadmVer := patchVersionStr\n\t\t\t\tif kubeadmVersion.AtLeast(patchVersion) {\n\t\t\t\t\t// In this case, the kubeadm CLI version is new enough. Don't display an update suggestion for kubeadm by making .NewKubeadmVersion equal .CurrentKubeadmVersion\n\t\t\t\t\tnewKubeadmVer = kubeadmVersionStr\n\t\t\t\t}\n\n\t\t\t\tupgrades = append(upgrades, Upgrade{\n\t\t\t\t\tDescription: description,\n\t\t\t\t\tBefore: beforeState,\n\t\t\t\t\tAfter: ClusterState{\n\t\t\t\t\t\tKubeVersion: patchVersionStr,\n\t\t\t\t\t\tDNSVersion: kubeadmconstants.CoreDNSVersion,\n\t\t\t\t\t\tKubeadmVersion: newKubeadmVer,\n\t\t\t\t\t\tEtcdVersion: getSuggestedEtcdVersion(externalEtcd, patchVersionStr),\n\t\t\t\t\t\t// KubeletVersions is unset here as it is not used anywhere in .After\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\tif canDoMinorUpgrade {\n\t\tupgrades = append(upgrades, Upgrade{\n\t\t\tDescription: \"stable version\",\n\t\t\tBefore: beforeState,\n\t\t\tAfter: ClusterState{\n\t\t\t\tKubeVersion: stableVersionStr,\n\t\t\t\tDNSVersion: kubeadmconstants.CoreDNSVersion,\n\t\t\t\tKubeadmVersion: stableVersionStr,\n\t\t\t\tEtcdVersion: getSuggestedEtcdVersion(externalEtcd, stableVersionStr),\n\t\t\t\t// KubeletVersions is unset here as it is not used anywhere in .After\n\t\t\t},\n\t\t})\n\t}\n\n\tif experimentalUpgradesAllowed || rcUpgradesAllowed {\n\t\t// dl.k8s.io/release/latest.txt is ALWAYS an alpha.X version\n\t\t// dl.k8s.io/release/latest-1.X.txt is first v1.X.0-alpha.0 -\u003e v1.X.0-alpha.Y, then v1.X.0-beta.0 to v1.X.0-beta.Z, then v1.X.0-rc.1 to v1.X.0-rc.W.\n\t\t// After the v1.X.0 release, latest-1.X.txt is always a beta.0 version. Let's say the latest stable version on the v1.7 branch is v1.7.3, then the\n\t\t// latest-1.7 version is v1.7.4-beta.0\n\n\t\t// Worth noticing is that when the release-1.X branch is cut; there are two versions tagged: v1.X.0-beta.0 AND v1.(X+1).alpha.0\n\t\t// The v1.(X+1).alpha.0 is pretty much useless and should just be ignored, as more betas may be released that have more features than the initial v1.(X+1).alpha.0\n\n\t\t// So what we do below is getting the latest overall version, always an v1.X.0-alpha.Y version. Then we get latest-1.(X-1) version. This version may be anything\n\t\t// between v1.(X-1).0-beta.0 and v1.(X-1).Z-beta.0. At some point in time, latest-1.(X-1) will point to v1.(X-1).0-rc.1. Then we should show it.\n\n\t\t// The flow looks like this (with time on the X axis):\n\t\t// v1.8.0-alpha.1 -\u003e v1.8.0-alpha.2 -\u003e v1.8.0-alpha.3 | release-1.8 branch | v1.8.0-beta.0 -\u003e v1.8.0-beta.1 -\u003e v1.8.0-beta.2 -\u003e v1.8.0-rc.1 -\u003e v1.8.0 -\u003e v1.8.1\n\t\t// v1.9.0-alpha.0 -\u003e v1.9.0-alpha.1 -\u003e v1.9.0-alpha.2\n\n\t\t// Get and output the current latest unstable version\n\t\tlatestVersionStr, latestVersion, err := versionGetterImpl.VersionFromCILabel(\"latest\", \"experimental version\")\n\t\tif err != nil {\n\t\t\treturn upgrades, err\n\t\t}\n\t\tfmt.Printf(\"[upgrade/versions] Latest %s: %s\\n\", \"experimental version\", latestVersionStr)\n\n\t\tminorUnstable := latestVersion.Components()[1]\n\t\t// Get and output the current latest unstable version\n\t\tpreviousBranch := fmt.Sprintf(\"latest-1.%d\", minorUnstable-1)\n\t\tpreviousBranchLatestVersionStr, previousBranchLatestVersion, err := versionGetterImpl.VersionFromCILabel(previousBranch, \"previous version\")\n\t\tif err != nil {\n\t\t\treturn upgrades, err\n\t\t}\n\t\tfmt.Printf(\"[upgrade/versions] Latest %s: %s\\n\", \"previous version\", previousBranchLatestVersionStr)\n\n\t\t// If that previous latest version is an RC, RCs are allowed and the cluster version is lower than the RC version, show the upgrade\n\t\tif rcUpgradesAllowed \u0026\u0026 rcUpgradePossible(clusterVersion, previousBranchLatestVersion) {\n\t\t\tupgrades = append(upgrades, Upgrade{\n\t\t\t\tDescription: \"release candidate version\",\n\t\t\t\tBefore: beforeState,\n\t\t\t\tAfter: ClusterState{\n\t\t\t\t\tKubeVersion: previousBranchLatestVersionStr,\n\t\t\t\t\tDNSVersion: kubeadmconstants.CoreDNSVersion,\n\t\t\t\t\tKubeadmVersion: previousBranchLatestVersionStr,\n\t\t\t\t\tEtcdVersion: getSuggestedEtcdVersion(externalEtcd, previousBranchLatestVersionStr),\n\t\t\t\t\t// KubeletVersions is unset here as it is not used anywhere in .After\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\n\t\t// Show the possibility if experimental upgrades are allowed\n\t\tif experimentalUpgradesAllowed \u0026\u0026 clusterVersion.LessThan(latestVersion) {\n\n\t\t\t// Default to assume that the experimental version to show is the unstable one\n\t\t\tunstableKubeVersion := latestVersionStr\n\n\t\t\t// Ẃe should not display alpha.0. The previous branch's beta/rc versions are more relevant due how the kube branching process works.\n\t\t\tif latestVersion.PreRelease() == \"alpha.0\" {\n\t\t\t\tunstableKubeVersion = previousBranchLatestVersionStr\n\t\t\t}\n\n\t\t\tupgrades = append(upgrades, Upgrade{\n\t\t\t\tDescription: \"experimental version\",\n\t\t\t\tBefore: beforeState,\n\t\t\t\tAfter: ClusterState{\n\t\t\t\t\tKubeVersion: unstableKubeVersion,\n\t\t\t\t\tDNSVersion: kubeadmconstants.CoreDNSVersion,\n\t\t\t\t\tKubeadmVersion: unstableKubeVersion,\n\t\t\t\t\tEtcdVersion: getSuggestedEtcdVersion(externalEtcd, unstableKubeVersion),\n\t\t\t\t\t// KubeletVersions is unset here as it is not used anywhere in .After\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t}\n\n\t// Add a newline in the end of this output to leave some space to the next output section\n\tprinter.Println()\n\n\treturn upgrades, nil\n}","line":{"from":74,"to":274}} {"id":100001069,"name":"getBranchFromVersion","signature":"func getBranchFromVersion(version string) string","file":"cmd/kubeadm/app/phases/upgrade/compute.go","code":"func getBranchFromVersion(version string) string {\n\tv := versionutil.MustParseGeneric(version)\n\treturn fmt.Sprintf(\"%d.%d\", v.Major(), v.Minor())\n}","line":{"from":276,"to":279}} {"id":100001070,"name":"patchVersionBranchExists","signature":"func patchVersionBranchExists(clusterVersion, stableVersion *versionutil.Version) bool","file":"cmd/kubeadm/app/phases/upgrade/compute.go","code":"func patchVersionBranchExists(clusterVersion, stableVersion *versionutil.Version) bool {\n\treturn stableVersion.AtLeast(clusterVersion)\n}","line":{"from":281,"to":283}} {"id":100001071,"name":"patchUpgradePossible","signature":"func patchUpgradePossible(clusterVersion, patchVersion *versionutil.Version) bool","file":"cmd/kubeadm/app/phases/upgrade/compute.go","code":"func patchUpgradePossible(clusterVersion, patchVersion *versionutil.Version) bool {\n\treturn clusterVersion.LessThan(patchVersion)\n}","line":{"from":285,"to":287}} {"id":100001072,"name":"rcUpgradePossible","signature":"func rcUpgradePossible(clusterVersion, previousBranchLatestVersion *versionutil.Version) bool","file":"cmd/kubeadm/app/phases/upgrade/compute.go","code":"func rcUpgradePossible(clusterVersion, previousBranchLatestVersion *versionutil.Version) bool {\n\treturn strings.HasPrefix(previousBranchLatestVersion.PreRelease(), \"rc\") \u0026\u0026 clusterVersion.LessThan(previousBranchLatestVersion)\n}","line":{"from":289,"to":291}} {"id":100001073,"name":"minorUpgradePossibleWithPatchRelease","signature":"func minorUpgradePossibleWithPatchRelease(stableVersion, patchVersion *versionutil.Version) bool","file":"cmd/kubeadm/app/phases/upgrade/compute.go","code":"func minorUpgradePossibleWithPatchRelease(stableVersion, patchVersion *versionutil.Version) bool {\n\treturn patchVersion.LessThan(stableVersion)\n}","line":{"from":293,"to":295}} {"id":100001074,"name":"getSuggestedEtcdVersion","signature":"func getSuggestedEtcdVersion(externalEtcd bool, kubernetesVersion string) string","file":"cmd/kubeadm/app/phases/upgrade/compute.go","code":"func getSuggestedEtcdVersion(externalEtcd bool, kubernetesVersion string) string {\n\tif externalEtcd {\n\t\treturn \"\"\n\t}\n\tetcdVersion, warning, err := kubeadmconstants.EtcdSupportedVersion(kubeadmconstants.SupportedEtcdVersion, kubernetesVersion)\n\tif err != nil {\n\t\tklog.Warningf(\"[upgrade/versions] could not retrieve an etcd version for the target Kubernetes version: %v\", err)\n\t\treturn \"N/A\"\n\t}\n\tif warning != nil {\n\t\tklog.Warningf(\"[upgrade/versions] %v\", warning)\n\t}\n\treturn etcdVersion.String()\n}","line":{"from":297,"to":310}} {"id":100001075,"name":"Check","signature":"func (c *healthCheck) Check() (warnings, errors []error)","file":"cmd/kubeadm/app/phases/upgrade/health.go","code":"// Check is part of the preflight.Checker interface\nfunc (c *healthCheck) Check() (warnings, errors []error) {\n\tif err := c.f(c.client, c.cfg); err != nil {\n\t\treturn nil, []error{err}\n\t}\n\treturn nil, nil\n}","line":{"from":52,"to":58}} {"id":100001076,"name":"Name","signature":"func (c *healthCheck) Name() string","file":"cmd/kubeadm/app/phases/upgrade/health.go","code":"// Name is part of the preflight.Checker interface\nfunc (c *healthCheck) Name() string {\n\treturn c.name\n}","line":{"from":60,"to":63}} {"id":100001077,"name":"CheckClusterHealth","signature":"func CheckClusterHealth(client clientset.Interface, cfg *kubeadmapi.ClusterConfiguration, ignoreChecksErrors sets.Set[string]) error","file":"cmd/kubeadm/app/phases/upgrade/health.go","code":"// CheckClusterHealth makes sure:\n// - the API /healthz endpoint is healthy\n// - all control-plane Nodes are Ready\n// - (if static pod-hosted) that all required Static Pod manifests exist on disk\nfunc CheckClusterHealth(client clientset.Interface, cfg *kubeadmapi.ClusterConfiguration, ignoreChecksErrors sets.Set[string]) error {\n\tfmt.Println(\"[upgrade] Running cluster health checks\")\n\n\thealthChecks := []preflight.Checker{\n\t\t\u0026healthCheck{\n\t\t\tname: \"CreateJob\",\n\t\t\tclient: client,\n\t\t\tcfg: cfg,\n\t\t\tf: createJob,\n\t\t},\n\t\t\u0026healthCheck{\n\t\t\tname: \"ControlPlaneNodesReady\",\n\t\t\tclient: client,\n\t\t\tf: controlPlaneNodesReady,\n\t\t},\n\t\t\u0026healthCheck{\n\t\t\tname: \"StaticPodManifest\",\n\t\t\tclient: client,\n\t\t\tcfg: cfg,\n\t\t\tf: staticPodManifestHealth,\n\t\t},\n\t}\n\n\treturn preflight.RunChecks(healthChecks, os.Stderr, ignoreChecksErrors)\n}","line":{"from":65,"to":93}} {"id":100001078,"name":"createJob","signature":"func createJob(client clientset.Interface, cfg *kubeadmapi.ClusterConfiguration) (lastError error)","file":"cmd/kubeadm/app/phases/upgrade/health.go","code":"// CreateJob is a check that verifies that a Job can be created in the cluster\nfunc createJob(client clientset.Interface, cfg *kubeadmapi.ClusterConfiguration) (lastError error) {\n\tconst (\n\t\tjobName = \"upgrade-health-check\"\n\t\tns = metav1.NamespaceSystem\n\t\ttimeout = 15 * time.Second\n\t)\n\n\t// If client.Discovery().RESTClient() is nil, the fake client is used.\n\t// Return early because the kubeadm dryrun dynamic client only handles the core/v1 GroupVersion.\n\tif client.Discovery().RESTClient() == nil {\n\t\tfmt.Printf(\"[upgrade/health] Would create the Job %q in namespace %q and wait until it completes\\n\", jobName, ns)\n\t\treturn nil\n\t}\n\n\t// Prepare Job\n\tjob := \u0026batchv1.Job{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: jobName,\n\t\t\tNamespace: ns,\n\t\t},\n\t\tSpec: batchv1.JobSpec{\n\t\t\tBackoffLimit: pointer.Int32(0),\n\t\t\tTemplate: v1.PodTemplateSpec{\n\t\t\t\tSpec: v1.PodSpec{\n\t\t\t\t\tRestartPolicy: v1.RestartPolicyNever,\n\t\t\t\t\tSecurityContext: \u0026v1.PodSecurityContext{\n\t\t\t\t\t\tRunAsUser: pointer.Int64(999),\n\t\t\t\t\t\tRunAsGroup: pointer.Int64(999),\n\t\t\t\t\t\tRunAsNonRoot: pointer.Bool(true),\n\t\t\t\t\t},\n\t\t\t\t\tTolerations: []v1.Toleration{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tKey: constants.LabelNodeRoleControlPlane,\n\t\t\t\t\t\t\tEffect: v1.TaintEffectNoSchedule,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tContainers: []v1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: jobName,\n\t\t\t\t\t\t\tImage: images.GetPauseImage(cfg),\n\t\t\t\t\t\t\tArgs: []string{\"-v\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// Check if the Job already exists and delete it\n\tif _, err := client.BatchV1().Jobs(ns).Get(context.TODO(), jobName, metav1.GetOptions{}); err == nil {\n\t\tif err = deleteHealthCheckJob(client, ns, jobName); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Cleanup the Job on exit\n\tdefer func() {\n\t\tlastError = deleteHealthCheckJob(client, ns, jobName)\n\t}()\n\n\t// Create the Job, but retry in case it is being currently deleted\n\tklog.V(2).Infof(\"Creating Job %q in the namespace %q\", jobName, ns)\n\terr := wait.PollImmediate(time.Second*1, timeout, func() (bool, error) {\n\t\tif _, err := client.BatchV1().Jobs(ns).Create(context.TODO(), job, metav1.CreateOptions{}); err != nil {\n\t\t\tklog.V(2).Infof(\"Could not create Job %q in the namespace %q, retrying: %v\", jobName, ns, err)\n\t\t\tlastError = err\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\tif err != nil {\n\t\treturn errors.Wrapf(lastError, \"could not create Job %q in the namespace %q\", jobName, ns)\n\t}\n\n\t// Waiting and manually deleting the Job is a workaround to not enabling the TTL controller.\n\t// TODO: refactor this if the TTL controller is enabled in kubeadm once it goes Beta.\n\n\t// Wait for the Job to complete\n\terr = wait.PollImmediate(time.Second*1, timeout, func() (bool, error) {\n\t\tjob, err := client.BatchV1().Jobs(ns).Get(context.TODO(), jobName, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\tlastError = err\n\t\t\tklog.V(2).Infof(\"could not get Job %q in the namespace %q, retrying: %v\", jobName, ns, err)\n\t\t\treturn false, nil\n\t\t}\n\t\tfor _, cond := range job.Status.Conditions {\n\t\t\tif cond.Type == batchv1.JobComplete {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\t\tlastError = errors.Errorf(\"no condition of type %v\", batchv1.JobComplete)\n\t\tklog.V(2).Infof(\"Job %q in the namespace %q is not yet complete, retrying\", jobName, ns)\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\treturn errors.Wrapf(lastError, \"Job %q in the namespace %q did not complete in %v\", jobName, ns, timeout)\n\t}\n\n\tklog.V(2).Infof(\"Job %q in the namespace %q completed\", jobName, ns)\n\n\treturn nil\n}","line":{"from":95,"to":197}} {"id":100001079,"name":"deleteHealthCheckJob","signature":"func deleteHealthCheckJob(client clientset.Interface, ns, jobName string) error","file":"cmd/kubeadm/app/phases/upgrade/health.go","code":"func deleteHealthCheckJob(client clientset.Interface, ns, jobName string) error {\n\tklog.V(2).Infof(\"Deleting Job %q in the namespace %q\", jobName, ns)\n\tpropagation := metav1.DeletePropagationForeground\n\tif err := client.BatchV1().Jobs(ns).Delete(context.TODO(), jobName, metav1.DeleteOptions{PropagationPolicy: \u0026propagation}); err != nil {\n\t\treturn errors.Wrapf(err, \"could not delete Job %q in the namespace %q\", jobName, ns)\n\t}\n\treturn nil\n}","line":{"from":199,"to":206}} {"id":100001080,"name":"controlPlaneNodesReady","signature":"func controlPlaneNodesReady(client clientset.Interface, _ *kubeadmapi.ClusterConfiguration) error","file":"cmd/kubeadm/app/phases/upgrade/health.go","code":"// controlPlaneNodesReady checks whether all control-plane Nodes in the cluster are in the Running state\nfunc controlPlaneNodesReady(client clientset.Interface, _ *kubeadmapi.ClusterConfiguration) error {\n\tselectorControlPlane := labels.SelectorFromSet(labels.Set(map[string]string{\n\t\tconstants.LabelNodeRoleControlPlane: \"\",\n\t}))\n\tnodes, err := client.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{\n\t\tLabelSelector: selectorControlPlane.String(),\n\t})\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"could not list nodes labeled with %q\", constants.LabelNodeRoleControlPlane)\n\t}\n\n\tnotReadyControlPlanes := getNotReadyNodes(nodes.Items)\n\tif len(notReadyControlPlanes) != 0 {\n\t\treturn errors.Errorf(\"there are NotReady control-planes in the cluster: %v\", notReadyControlPlanes)\n\t}\n\treturn nil\n}","line":{"from":208,"to":225}} {"id":100001081,"name":"staticPodManifestHealth","signature":"func staticPodManifestHealth(_ clientset.Interface, _ *kubeadmapi.ClusterConfiguration) error","file":"cmd/kubeadm/app/phases/upgrade/health.go","code":"// staticPodManifestHealth makes sure the required static pods are presents\nfunc staticPodManifestHealth(_ clientset.Interface, _ *kubeadmapi.ClusterConfiguration) error {\n\tvar nonExistentManifests []string\n\tfor _, component := range constants.ControlPlaneComponents {\n\t\tmanifestFile := constants.GetStaticPodFilepath(component, constants.GetStaticPodDirectory())\n\t\tif _, err := os.Stat(manifestFile); os.IsNotExist(err) {\n\t\t\tnonExistentManifests = append(nonExistentManifests, manifestFile)\n\t\t}\n\t}\n\tif len(nonExistentManifests) == 0 {\n\t\treturn nil\n\t}\n\treturn errors.Errorf(\"The control plane seems to be Static Pod-hosted, but some of the manifests don't seem to exist on disk. This probably means you're running 'kubeadm upgrade' on a remote machine, which is not supported for a Static Pod-hosted cluster. Manifest files not found: %v\", nonExistentManifests)\n}","line":{"from":227,"to":240}} {"id":100001082,"name":"getNotReadyNodes","signature":"func getNotReadyNodes(nodes []v1.Node) []string","file":"cmd/kubeadm/app/phases/upgrade/health.go","code":"// getNotReadyNodes returns a string slice of nodes in the cluster that are NotReady\nfunc getNotReadyNodes(nodes []v1.Node) []string {\n\tvar notReadyNodes []string\n\tfor _, node := range nodes {\n\t\tfor _, condition := range node.Status.Conditions {\n\t\t\tif condition.Type == v1.NodeReady \u0026\u0026 condition.Status != v1.ConditionTrue {\n\t\t\t\tnotReadyNodes = append(notReadyNodes, node.ObjectMeta.Name)\n\t\t\t}\n\t\t}\n\t}\n\treturn notReadyNodes\n}","line":{"from":242,"to":253}} {"id":100001083,"name":"EnforceVersionPolicies","signature":"func EnforceVersionPolicies(versionGetter VersionGetter, newK8sVersionStr string, newK8sVersion *version.Version, allowExperimentalUpgrades, allowRCUpgrades bool) *VersionSkewPolicyErrors","file":"cmd/kubeadm/app/phases/upgrade/policy.go","code":"// EnforceVersionPolicies enforces that the proposed new version is compatible with all the different version skew policies\nfunc EnforceVersionPolicies(versionGetter VersionGetter, newK8sVersionStr string, newK8sVersion *version.Version, allowExperimentalUpgrades, allowRCUpgrades bool) *VersionSkewPolicyErrors {\n\n\tskewErrors := \u0026VersionSkewPolicyErrors{\n\t\tMandatory: []error{},\n\t\tSkippable: []error{},\n\t}\n\n\tclusterVersionStr, clusterVersion, err := versionGetter.ClusterVersion()\n\tif err != nil {\n\t\t// This case can't be forced: kubeadm has to be able to lookup cluster version for upgrades to work\n\t\tskewErrors.Mandatory = append(skewErrors.Mandatory, errors.Wrap(err, \"Unable to fetch cluster version\"))\n\t\treturn skewErrors\n\t}\n\tfmt.Printf(\"[upgrade/versions] Cluster version: %s\\n\", clusterVersionStr)\n\n\tkubeadmVersionStr, kubeadmVersion, err := versionGetter.KubeadmVersion()\n\tif err != nil {\n\t\t// This case can't be forced: kubeadm has to be able to lookup its version for upgrades to work\n\t\tskewErrors.Mandatory = append(skewErrors.Mandatory, errors.Wrap(err, \"Unable to fetch kubeadm version\"))\n\t\treturn skewErrors\n\t}\n\tfmt.Printf(\"[upgrade/versions] kubeadm version: %s\\n\", kubeadmVersionStr)\n\n\tkubeletVersions, err := versionGetter.KubeletVersions()\n\tif err != nil {\n\t\t// This is a non-critical error; continue although kubeadm couldn't look this up\n\t\tskewErrors.Skippable = append(skewErrors.Skippable, errors.Wrap(err, \"Unable to fetch kubelet version\"))\n\t}\n\n\t// Make sure the new version is a supported version (higher than the minimum one supported)\n\tif !newK8sVersion.AtLeast(constants.MinimumControlPlaneVersion) {\n\t\t// This must not happen, kubeadm always supports a minimum version; and we can't go below that\n\t\tskewErrors.Mandatory = append(skewErrors.Mandatory, errors.Errorf(\"Specified version to upgrade to %q is equal to or lower than the minimum supported version %q. Please specify a higher version to upgrade to\", newK8sVersionStr, clusterVersionStr))\n\t}\n\n\t// kubeadm doesn't support upgrades between two minor versions; e.g. a v1.7 -\u003e v1.9 upgrade is not supported right away\n\tif newK8sVersion.Minor() \u003e clusterVersion.Minor()+MaximumAllowedMinorVersionUpgradeSkew {\n\t\ttooLargeUpgradeSkewErr := errors.Errorf(\"Specified version to upgrade to %q is too high; kubeadm can upgrade only %d minor version at a time\", newK8sVersionStr, MaximumAllowedMinorVersionUpgradeSkew)\n\t\t// If the version that we're about to upgrade to is a released version, we should fully enforce this policy\n\t\t// If the version is a CI/dev/experimental version, it's okay to jump two minor version steps, but then require the -f flag\n\t\tif len(newK8sVersion.PreRelease()) == 0 {\n\t\t\tskewErrors.Mandatory = append(skewErrors.Mandatory, tooLargeUpgradeSkewErr)\n\t\t} else {\n\t\t\tskewErrors.Skippable = append(skewErrors.Skippable, tooLargeUpgradeSkewErr)\n\t\t}\n\t}\n\n\t// kubeadm doesn't support downgrades between two minor versions; e.g. a v1.9 -\u003e v1.7 downgrade is not supported right away\n\tif newK8sVersion.Minor() \u003c clusterVersion.Minor()-MaximumAllowedMinorVersionDowngradeSkew {\n\t\ttooLargeDowngradeSkewErr := errors.Errorf(\"Specified version to downgrade to %q is too low; kubeadm can downgrade only %d minor version at a time\", newK8sVersionStr, MaximumAllowedMinorVersionDowngradeSkew)\n\t\t// If the version that we're about to downgrade to is a released version, we should fully enforce this policy\n\t\t// If the version is a CI/dev/experimental version, it's okay to jump two minor version steps, but then require the -f flag\n\t\tif len(newK8sVersion.PreRelease()) == 0 {\n\t\t\tskewErrors.Mandatory = append(skewErrors.Mandatory, tooLargeDowngradeSkewErr)\n\t\t} else {\n\t\t\tskewErrors.Skippable = append(skewErrors.Skippable, tooLargeDowngradeSkewErr)\n\t\t}\n\t}\n\n\t// If the kubeadm version is lower than what we want to upgrade to; error\n\tif kubeadmVersion.LessThan(newK8sVersion) {\n\t\tif newK8sVersion.Minor() \u003e kubeadmVersion.Minor() {\n\t\t\ttooLargeKubeadmSkew := errors.Errorf(\"Specified version to upgrade to %q is at least one minor release higher than the kubeadm minor release (%d \u003e %d). Such an upgrade is not supported\", newK8sVersionStr, newK8sVersion.Minor(), kubeadmVersion.Minor())\n\t\t\t// This is unsupported; kubeadm has no idea how it should handle a newer minor release than itself\n\t\t\t// If the version is a CI/dev/experimental version though, lower the severity of this check, but then require the -f flag\n\t\t\tif len(newK8sVersion.PreRelease()) == 0 {\n\t\t\t\tskewErrors.Mandatory = append(skewErrors.Mandatory, tooLargeKubeadmSkew)\n\t\t\t} else {\n\t\t\t\tskewErrors.Skippable = append(skewErrors.Skippable, tooLargeKubeadmSkew)\n\t\t\t}\n\t\t} else {\n\t\t\t// Upgrading to a higher patch version than kubeadm is ok if the user specifies --force. Not recommended, but possible.\n\t\t\tskewErrors.Skippable = append(skewErrors.Skippable, errors.Errorf(\"Specified version to upgrade to %q is higher than the kubeadm version %q. Upgrade kubeadm first using the tool you used to install kubeadm\", newK8sVersionStr, kubeadmVersionStr))\n\t\t}\n\t}\n\n\tif kubeadmVersion.Major() \u003e newK8sVersion.Major() ||\n\t\tkubeadmVersion.Minor() \u003e newK8sVersion.Minor() {\n\t\tskewErrors.Skippable = append(skewErrors.Skippable, errors.Errorf(\"Kubeadm version %s can only be used to upgrade to Kubernetes version %d.%d\", kubeadmVersionStr, kubeadmVersion.Major(), kubeadmVersion.Minor()))\n\t}\n\n\t// Detect if the version is unstable and the user didn't allow that\n\tif err = detectUnstableVersionError(newK8sVersion, newK8sVersionStr, allowExperimentalUpgrades, allowRCUpgrades); err != nil {\n\t\tskewErrors.Skippable = append(skewErrors.Skippable, err)\n\t}\n\n\t// Detect if there are too old kubelets in the cluster\n\t// Check for nil here since this is the only case where kubeletVersions can be nil; if KubeletVersions() returned an error\n\t// However, it's okay to skip that check\n\tif kubeletVersions != nil {\n\t\tif err = detectTooOldKubelets(newK8sVersion, kubeletVersions); err != nil {\n\t\t\tskewErrors.Skippable = append(skewErrors.Skippable, err)\n\t\t}\n\t}\n\n\t// If we did not see any errors, return nil\n\tif len(skewErrors.Skippable) == 0 \u0026\u0026 len(skewErrors.Mandatory) == 0 {\n\t\treturn nil\n\t}\n\n\t// Uh oh, we encountered one or more errors, return them\n\treturn skewErrors\n}","line":{"from":47,"to":150}} {"id":100001084,"name":"detectUnstableVersionError","signature":"func detectUnstableVersionError(newK8sVersion *version.Version, newK8sVersionStr string, allowExperimentalUpgrades, allowRCUpgrades bool) error","file":"cmd/kubeadm/app/phases/upgrade/policy.go","code":"// detectUnstableVersionError is a helper function for detecting if the unstable version (if specified) is allowed to be used\nfunc detectUnstableVersionError(newK8sVersion *version.Version, newK8sVersionStr string, allowExperimentalUpgrades, allowRCUpgrades bool) error {\n\t// Short-circuit quickly if this is not an unstable version\n\tif len(newK8sVersion.PreRelease()) == 0 {\n\t\treturn nil\n\t}\n\t// If the user has specified that unstable versions are fine, then no error should be returned\n\tif allowExperimentalUpgrades {\n\t\treturn nil\n\t}\n\t// If this is a release candidate and we allow such ones, everything's fine\n\tif strings.HasPrefix(newK8sVersion.PreRelease(), \"rc\") \u0026\u0026 allowRCUpgrades {\n\t\treturn nil\n\t}\n\n\treturn errors.Errorf(\"Specified version to upgrade to %q is an unstable version and such upgrades weren't allowed via setting the --allow-*-upgrades flags\", newK8sVersionStr)\n}","line":{"from":152,"to":168}} {"id":100001085,"name":"detectTooOldKubelets","signature":"func detectTooOldKubelets(newK8sVersion *version.Version, kubeletVersions map[string]uint16) error","file":"cmd/kubeadm/app/phases/upgrade/policy.go","code":"// detectTooOldKubelets errors out if the kubelet versions are so old that an unsupported skew would happen if the cluster was upgraded\nfunc detectTooOldKubelets(newK8sVersion *version.Version, kubeletVersions map[string]uint16) error {\n\tvar tooOldKubeletVersions []string\n\tfor versionStr := range kubeletVersions {\n\n\t\tkubeletVersion, err := version.ParseSemantic(versionStr)\n\t\tif err != nil {\n\t\t\treturn errors.Errorf(\"couldn't parse kubelet version %s\", versionStr)\n\t\t}\n\n\t\tif newK8sVersion.Minor() \u003e kubeletVersion.Minor()+MaximumAllowedMinorVersionKubeletSkew {\n\t\t\ttooOldKubeletVersions = append(tooOldKubeletVersions, versionStr)\n\t\t}\n\t}\n\tif len(tooOldKubeletVersions) == 0 {\n\t\treturn nil\n\t}\n\n\treturn errors.Errorf(\"There are kubelets in this cluster that are too old that have these versions %v\", tooOldKubeletVersions)\n}","line":{"from":170,"to":189}} {"id":100001086,"name":"PerformPostUpgradeTasks","signature":"func PerformPostUpgradeTasks(client clientset.Interface, cfg *kubeadmapi.InitConfiguration, patchesDir string, dryRun bool, out io.Writer) error","file":"cmd/kubeadm/app/phases/upgrade/postupgrade.go","code":"// PerformPostUpgradeTasks runs nearly the same functions as 'kubeadm init' would do\n// Note that the mark-control-plane phase is left out, not needed, and no token is created as that doesn't belong to the upgrade\nfunc PerformPostUpgradeTasks(client clientset.Interface, cfg *kubeadmapi.InitConfiguration, patchesDir string, dryRun bool, out io.Writer) error {\n\tvar errs []error\n\n\t// Upload currently used configuration to the cluster\n\t// Note: This is done right in the beginning of cluster initialization; as we might want to make other phases\n\t// depend on centralized information from this source in the future\n\tif err := uploadconfig.UploadConfiguration(cfg, client); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\t// Create the new, version-branched kubelet ComponentConfig ConfigMap\n\tif err := kubeletphase.CreateConfigMap(\u0026cfg.ClusterConfiguration, patchesDir, client); err != nil {\n\t\terrs = append(errs, errors.Wrap(err, \"error creating kubelet configuration ConfigMap\"))\n\t}\n\n\t// Write the new kubelet config down to disk and the env file if needed\n\tif err := WriteKubeletConfigFiles(cfg, patchesDir, dryRun, out); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\t// Annotate the node with the crisocket information, sourced either from the InitConfiguration struct or\n\t// --cri-socket.\n\t// TODO: In the future we want to use something more official like NodeStatus or similar for detecting this properly\n\tif err := patchnodephase.AnnotateCRISocket(client, cfg.NodeRegistration.Name, cfg.NodeRegistration.CRISocket); err != nil {\n\t\terrs = append(errs, errors.Wrap(err, \"error uploading crisocket\"))\n\t}\n\n\t// Create RBAC rules that makes the bootstrap tokens able to get nodes\n\tif err := nodebootstraptoken.AllowBoostrapTokensToGetNodes(client); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\t// Create/update RBAC rules that makes the bootstrap tokens able to post CSRs\n\tif err := nodebootstraptoken.AllowBootstrapTokensToPostCSRs(client); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\t// Create/update RBAC rules that makes the bootstrap tokens able to get their CSRs approved automatically\n\tif err := nodebootstraptoken.AutoApproveNodeBootstrapTokens(client); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\t// Create/update RBAC rules that makes the nodes to rotate certificates and get their CSRs approved automatically\n\tif err := nodebootstraptoken.AutoApproveNodeCertificateRotation(client); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\t// TODO: Is this needed to do here? I think that updating cluster info should probably be separate from a normal upgrade\n\t// Create the cluster-info ConfigMap with the associated RBAC rules\n\t// if err := clusterinfo.CreateBootstrapConfigMapIfNotExists(client, kubeadmconstants.GetAdminKubeConfigPath()); err != nil {\n\t// \treturn err\n\t//}\n\t// Create/update RBAC rules that makes the cluster-info ConfigMap reachable\n\tif err := clusterinfo.CreateClusterInfoRBACRules(client); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\t// If the coredns ConfigMap is missing, show a warning and assume that the\n\t// DNS addon was skipped during \"kubeadm init\", and that its redeployment on upgrade is not desired.\n\t//\n\t// TODO: remove this once \"kubeadm upgrade apply\" phases are supported:\n\t// https://github.com/kubernetes/kubeadm/issues/1318\n\tvar missingCoreDNSConfigMap bool\n\tif _, err := client.CoreV1().ConfigMaps(metav1.NamespaceSystem).Get(\n\t\tcontext.TODO(),\n\t\tkubeadmconstants.CoreDNSConfigMap,\n\t\tmetav1.GetOptions{},\n\t); err != nil \u0026\u0026 apierrors.IsNotFound(err) {\n\t\tmissingCoreDNSConfigMap = true\n\t}\n\tif missingCoreDNSConfigMap {\n\t\tklog.Warningf(\"the ConfigMaps %q in the namespace %q were not found. \"+\n\t\t\t\"Assuming that a DNS server was not deployed for this cluster. \"+\n\t\t\t\"Note that once 'kubeadm upgrade apply' supports phases you \"+\n\t\t\t\"will have to skip the DNS upgrade manually\",\n\t\t\tkubeadmconstants.CoreDNSConfigMap,\n\t\t\tmetav1.NamespaceSystem)\n\t} else {\n\t\t// Upgrade CoreDNS\n\t\tif err := dns.EnsureDNSAddon(\u0026cfg.ClusterConfiguration, client, out, false); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\t// If the kube-proxy ConfigMap is missing, show a warning and assume that kube-proxy\n\t// was skipped during \"kubeadm init\", and that its redeployment on upgrade is not desired.\n\t//\n\t// TODO: remove this once \"kubeadm upgrade apply\" phases are supported:\n\t// https://github.com/kubernetes/kubeadm/issues/1318\n\tif _, err := client.CoreV1().ConfigMaps(metav1.NamespaceSystem).Get(\n\t\tcontext.TODO(),\n\t\tkubeadmconstants.KubeProxyConfigMap,\n\t\tmetav1.GetOptions{},\n\t); err != nil \u0026\u0026 apierrors.IsNotFound(err) {\n\t\tklog.Warningf(\"the ConfigMap %q in the namespace %q was not found. \"+\n\t\t\t\"Assuming that kube-proxy was not deployed for this cluster. \"+\n\t\t\t\"Note that once 'kubeadm upgrade apply' supports phases you \"+\n\t\t\t\"will have to skip the kube-proxy upgrade manually\",\n\t\t\tkubeadmconstants.KubeProxyConfigMap,\n\t\t\tmetav1.NamespaceSystem)\n\t} else {\n\t\t// Upgrade kube-proxy\n\t\tif err := proxy.EnsureProxyAddon(\u0026cfg.ClusterConfiguration, \u0026cfg.LocalAPIEndpoint, client, out, false); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\treturn errorsutil.NewAggregate(errs)\n}","line":{"from":47,"to":157}} {"id":100001087,"name":"WriteKubeletConfigFiles","signature":"func WriteKubeletConfigFiles(cfg *kubeadmapi.InitConfiguration, patchesDir string, dryRun bool, out io.Writer) error","file":"cmd/kubeadm/app/phases/upgrade/postupgrade.go","code":"func WriteKubeletConfigFiles(cfg *kubeadmapi.InitConfiguration, patchesDir string, dryRun bool, out io.Writer) error {\n\t// Set up the kubelet directory to use. If dry-running, this will return a fake directory\n\tkubeletDir, err := GetKubeletDir(dryRun)\n\tif err != nil {\n\t\t// The error here should never occur in reality, would only be thrown if /tmp doesn't exist on the machine.\n\t\treturn err\n\t}\n\n\t// Create a copy of the kubelet config file in the /etc/kubernetes/tmp/ folder.\n\tbackupDir, err := kubeadmconstants.CreateTempDirForKubeadm(kubeadmconstants.KubernetesDir, \"kubeadm-kubelet-config\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tsrc := filepath.Join(kubeletDir, kubeadmconstants.KubeletConfigurationFileName)\n\tdest := filepath.Join(backupDir, kubeadmconstants.KubeletConfigurationFileName)\n\n\tif !dryRun {\n\t\tfmt.Printf(\"[upgrade] Backing up kubelet config file to %s\\n\", dest)\n\t\terr := kubeadmutil.CopyFile(src, dest)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"error backing up the kubelet config file\")\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"[dryrun] Would back up kubelet config file to %s\\n\", dest)\n\t}\n\n\terrs := []error{}\n\t// Write the configuration for the kubelet down to disk so the upgraded kubelet can start with fresh config\n\tif err := kubeletphase.WriteConfigToDisk(\u0026cfg.ClusterConfiguration, kubeletDir, patchesDir, out); err != nil {\n\t\terrs = append(errs, errors.Wrap(err, \"error writing kubelet configuration to file\"))\n\t}\n\n\tif dryRun { // Print what contents would be written\n\t\terr := dryrunutil.PrintDryRunFile(kubeadmconstants.KubeletConfigurationFileName, kubeletDir, kubeadmconstants.KubeletRunDirectory, os.Stdout)\n\t\tif err != nil {\n\t\t\terrs = append(errs, errors.Wrap(err, \"error printing files on dryrun\"))\n\t\t}\n\t}\n\treturn errorsutil.NewAggregate(errs)\n}","line":{"from":159,"to":198}} {"id":100001088,"name":"GetKubeletDir","signature":"func GetKubeletDir(dryRun bool) (string, error)","file":"cmd/kubeadm/app/phases/upgrade/postupgrade.go","code":"// GetKubeletDir gets the kubelet directory based on whether the user is dry-running this command or not.\nfunc GetKubeletDir(dryRun bool) (string, error) {\n\tif dryRun {\n\t\treturn kubeadmconstants.CreateTempDirForKubeadm(\"\", \"kubeadm-upgrade-dryrun\")\n\t}\n\treturn kubeadmconstants.KubeletRunDirectory, nil\n}","line":{"from":200,"to":206}} {"id":100001089,"name":"moveFiles","signature":"func moveFiles(files map[string]string) error","file":"cmd/kubeadm/app/phases/upgrade/postupgrade.go","code":"// moveFiles moves files from one directory to another.\nfunc moveFiles(files map[string]string) error {\n\tfilesToRecover := make(map[string]string, len(files))\n\tfor from, to := range files {\n\t\tif err := os.Rename(from, to); err != nil {\n\t\t\treturn rollbackFiles(filesToRecover, err)\n\t\t}\n\t\tfilesToRecover[to] = from\n\t}\n\treturn nil\n}","line":{"from":208,"to":218}} {"id":100001090,"name":"rollbackFiles","signature":"func rollbackFiles(files map[string]string, originalErr error) error","file":"cmd/kubeadm/app/phases/upgrade/postupgrade.go","code":"// rollbackFiles moves the files back to the original directory.\nfunc rollbackFiles(files map[string]string, originalErr error) error {\n\terrs := []error{originalErr}\n\tfor from, to := range files {\n\t\tif err := os.Rename(from, to); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\treturn errors.Errorf(\"couldn't move these files: %v. Got errors: %v\", files, errorsutil.NewAggregate(errs))\n}","line":{"from":220,"to":229}} {"id":100001091,"name":"Name","signature":"func (c CoreDNSCheck) Name() string","file":"cmd/kubeadm/app/phases/upgrade/preflight.go","code":"// Name is part of the preflight.Checker interface\nfunc (c CoreDNSCheck) Name() string {\n\treturn c.name\n}","line":{"from":43,"to":46}} {"id":100001092,"name":"Check","signature":"func (c CoreDNSCheck) Check() (warnings, errors []error)","file":"cmd/kubeadm/app/phases/upgrade/preflight.go","code":"// Check is part of the preflight.Checker interface\nfunc (c CoreDNSCheck) Check() (warnings, errors []error) {\n\tif err := c.f(c.client); err != nil {\n\t\treturn nil, []error{err}\n\t}\n\treturn nil, nil\n}","line":{"from":48,"to":54}} {"id":100001093,"name":"RunCoreDNSMigrationCheck","signature":"func RunCoreDNSMigrationCheck(client clientset.Interface, ignorePreflightErrors sets.Set[string]) error","file":"cmd/kubeadm/app/phases/upgrade/preflight.go","code":"// RunCoreDNSMigrationCheck initializes checks related to CoreDNS migration.\nfunc RunCoreDNSMigrationCheck(client clientset.Interface, ignorePreflightErrors sets.Set[string]) error {\n\tmigrationChecks := []preflight.Checker{\n\t\t\u0026CoreDNSCheck{\n\t\t\tname: \"CoreDNSUnsupportedPlugins\",\n\t\t\tclient: client,\n\t\t\tf: checkUnsupportedPlugins,\n\t\t},\n\t\t\u0026CoreDNSCheck{\n\t\t\tname: \"CoreDNSMigration\",\n\t\t\tclient: client,\n\t\t\tf: checkMigration,\n\t\t},\n\t}\n\n\treturn preflight.RunChecks(migrationChecks, os.Stderr, ignorePreflightErrors)\n}","line":{"from":56,"to":72}} {"id":100001094,"name":"checkUnsupportedPlugins","signature":"func checkUnsupportedPlugins(client clientset.Interface) error","file":"cmd/kubeadm/app/phases/upgrade/preflight.go","code":"// checkUnsupportedPlugins checks if there are any plugins included in the current configuration\n// that are unsupported for migration.\nfunc checkUnsupportedPlugins(client clientset.Interface) error {\n\tklog.V(1).Infoln(\"validating if there are any unsupported CoreDNS plugins in the Corefile\")\n\t_, corefile, currentInstalledCoreDNSversion, err := dns.GetCoreDNSInfo(client)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcurrentInstalledCoreDNSversion = strings.TrimLeft(currentInstalledCoreDNSversion, \"v\")\n\ttargetCoreDNSVersion := strings.TrimLeft(kubeadmconstants.CoreDNSVersion, \"v\")\n\tif currentInstalledCoreDNSversion == targetCoreDNSVersion {\n\t\treturn nil\n\t}\n\tunsupportedCoreDNS, err := migration.Unsupported(currentInstalledCoreDNSversion, targetCoreDNSVersion, corefile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(unsupportedCoreDNS) != 0 {\n\t\tvar UnsupportedPlugins []string\n\t\tfor _, unsup := range unsupportedCoreDNS {\n\t\t\tUnsupportedPlugins = append(UnsupportedPlugins, unsup.ToString())\n\t\t}\n\t\tfmt.Println(\"[preflight] The corefile contains plugins that kubeadm/CoreDNS does not know how to migrate. \" +\n\t\t\t\"Each plugin listed should be manually verified for compatibility with the newer version of CoreDNS. \" +\n\t\t\t\"Once ready, the upgrade can be initiated by skipping the preflight check. During the upgrade, \" +\n\t\t\t\"kubeadm will migrate the configuration while leaving the listed plugin configs untouched, \" +\n\t\t\t\"but cannot guarantee that they will work with the newer version of CoreDNS.\")\n\t\treturn errors.Errorf(\"CoreDNS cannot migrate the following plugins:\\n%s\", UnsupportedPlugins)\n\t}\n\treturn nil\n}","line":{"from":74,"to":105}} {"id":100001095,"name":"checkMigration","signature":"func checkMigration(client clientset.Interface) error","file":"cmd/kubeadm/app/phases/upgrade/preflight.go","code":"// checkMigration validates if migration of the current CoreDNS ConfigMap is possible.\nfunc checkMigration(client clientset.Interface) error {\n\tklog.V(1).Infoln(\"validating if migration can be done for the current CoreDNS release.\")\n\t_, corefile, currentInstalledCoreDNSversion, err := dns.GetCoreDNSInfo(client)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcurrentInstalledCoreDNSversion = strings.TrimLeft(currentInstalledCoreDNSversion, \"v\")\n\t_, err = migration.Migrate(currentInstalledCoreDNSversion, strings.TrimLeft(kubeadmconstants.CoreDNSVersion, \"v\"), corefile, false)\n\treturn errors.Wrap(err, \"CoreDNS will not be upgraded\")\n}","line":{"from":107,"to":118}} {"id":100001096,"name":"NewKubeStaticPodPathManager","signature":"func NewKubeStaticPodPathManager(kubernetesDir, patchesDir, tempDir, backupDir, backupEtcdDir string, keepManifestDir, keepEtcdDir bool) StaticPodPathManager","file":"cmd/kubeadm/app/phases/upgrade/staticpods.go","code":"// NewKubeStaticPodPathManager creates a new instance of KubeStaticPodPathManager\nfunc NewKubeStaticPodPathManager(kubernetesDir, patchesDir, tempDir, backupDir, backupEtcdDir string, keepManifestDir, keepEtcdDir bool) StaticPodPathManager {\n\treturn \u0026KubeStaticPodPathManager{\n\t\tkubernetesDir: kubernetesDir,\n\t\tpatchesDir: patchesDir,\n\t\trealManifestDir: filepath.Join(kubernetesDir, constants.ManifestsSubDirName),\n\t\ttempManifestDir: tempDir,\n\t\tbackupManifestDir: backupDir,\n\t\tbackupEtcdDir: backupEtcdDir,\n\t\tkeepManifestDir: keepManifestDir,\n\t\tkeepEtcdDir: keepEtcdDir,\n\t}\n}","line":{"from":91,"to":103}} {"id":100001097,"name":"NewKubeStaticPodPathManagerUsingTempDirs","signature":"func NewKubeStaticPodPathManagerUsingTempDirs(kubernetesDir, patchesDir string, saveManifestsDir, saveEtcdDir bool) (StaticPodPathManager, error)","file":"cmd/kubeadm/app/phases/upgrade/staticpods.go","code":"// NewKubeStaticPodPathManagerUsingTempDirs creates a new instance of KubeStaticPodPathManager with temporary directories backing it\nfunc NewKubeStaticPodPathManagerUsingTempDirs(kubernetesDir, patchesDir string, saveManifestsDir, saveEtcdDir bool) (StaticPodPathManager, error) {\n\n\tupgradedManifestsDir, err := constants.CreateTempDirForKubeadm(kubernetesDir, \"kubeadm-upgraded-manifests\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbackupManifestsDir, err := constants.CreateTimestampDirForKubeadm(kubernetesDir, \"kubeadm-backup-manifests\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbackupEtcdDir, err := constants.CreateTimestampDirForKubeadm(kubernetesDir, \"kubeadm-backup-etcd\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewKubeStaticPodPathManager(kubernetesDir, patchesDir, upgradedManifestsDir, backupManifestsDir, backupEtcdDir, saveManifestsDir, saveEtcdDir), nil\n}","line":{"from":105,"to":122}} {"id":100001098,"name":"MoveFile","signature":"func (spm *KubeStaticPodPathManager) MoveFile(oldPath, newPath string) error","file":"cmd/kubeadm/app/phases/upgrade/staticpods.go","code":"// MoveFile should move a file from oldPath to newPath\nfunc (spm *KubeStaticPodPathManager) MoveFile(oldPath, newPath string) error {\n\treturn os.Rename(oldPath, newPath)\n}","line":{"from":124,"to":127}} {"id":100001099,"name":"KubernetesDir","signature":"func (spm *KubeStaticPodPathManager) KubernetesDir() string","file":"cmd/kubeadm/app/phases/upgrade/staticpods.go","code":"// KubernetesDir should point to the directory Kubernetes owns for storing various configuration files\nfunc (spm *KubeStaticPodPathManager) KubernetesDir() string {\n\treturn spm.kubernetesDir\n}","line":{"from":129,"to":132}} {"id":100001100,"name":"PatchesDir","signature":"func (spm *KubeStaticPodPathManager) PatchesDir() string","file":"cmd/kubeadm/app/phases/upgrade/staticpods.go","code":"// PatchesDir should point to the folder where patches for components are stored\nfunc (spm *KubeStaticPodPathManager) PatchesDir() string {\n\treturn spm.patchesDir\n}","line":{"from":134,"to":137}} {"id":100001101,"name":"RealManifestPath","signature":"func (spm *KubeStaticPodPathManager) RealManifestPath(component string) string","file":"cmd/kubeadm/app/phases/upgrade/staticpods.go","code":"// RealManifestPath gets the file path for the component in the \"real\" static pod manifest directory used by the kubelet\nfunc (spm *KubeStaticPodPathManager) RealManifestPath(component string) string {\n\treturn constants.GetStaticPodFilepath(component, spm.realManifestDir)\n}","line":{"from":139,"to":142}} {"id":100001102,"name":"RealManifestDir","signature":"func (spm *KubeStaticPodPathManager) RealManifestDir() string","file":"cmd/kubeadm/app/phases/upgrade/staticpods.go","code":"// RealManifestDir should point to the static pod manifest directory used by the kubelet\nfunc (spm *KubeStaticPodPathManager) RealManifestDir() string {\n\treturn spm.realManifestDir\n}","line":{"from":144,"to":147}} {"id":100001103,"name":"TempManifestPath","signature":"func (spm *KubeStaticPodPathManager) TempManifestPath(component string) string","file":"cmd/kubeadm/app/phases/upgrade/staticpods.go","code":"// TempManifestPath gets the file path for the component in the temporary directory created for generating new manifests for the upgrade\nfunc (spm *KubeStaticPodPathManager) TempManifestPath(component string) string {\n\treturn constants.GetStaticPodFilepath(component, spm.tempManifestDir)\n}","line":{"from":149,"to":152}} {"id":100001104,"name":"TempManifestDir","signature":"func (spm *KubeStaticPodPathManager) TempManifestDir() string","file":"cmd/kubeadm/app/phases/upgrade/staticpods.go","code":"// TempManifestDir should point to the temporary directory created for generating new manifests for the upgrade\nfunc (spm *KubeStaticPodPathManager) TempManifestDir() string {\n\treturn spm.tempManifestDir\n}","line":{"from":154,"to":157}} {"id":100001105,"name":"BackupManifestPath","signature":"func (spm *KubeStaticPodPathManager) BackupManifestPath(component string) string","file":"cmd/kubeadm/app/phases/upgrade/staticpods.go","code":"// BackupManifestPath gets the file path for the component in the backup directory used for backuping manifests during the transition\nfunc (spm *KubeStaticPodPathManager) BackupManifestPath(component string) string {\n\treturn constants.GetStaticPodFilepath(component, spm.backupManifestDir)\n}","line":{"from":159,"to":162}} {"id":100001106,"name":"BackupManifestDir","signature":"func (spm *KubeStaticPodPathManager) BackupManifestDir() string","file":"cmd/kubeadm/app/phases/upgrade/staticpods.go","code":"// BackupManifestDir should point to the backup directory used for backuping manifests during the transition\nfunc (spm *KubeStaticPodPathManager) BackupManifestDir() string {\n\treturn spm.backupManifestDir\n}","line":{"from":164,"to":167}} {"id":100001107,"name":"BackupEtcdDir","signature":"func (spm *KubeStaticPodPathManager) BackupEtcdDir() string","file":"cmd/kubeadm/app/phases/upgrade/staticpods.go","code":"// BackupEtcdDir should point to the backup directory used for backuping manifests during the transition\nfunc (spm *KubeStaticPodPathManager) BackupEtcdDir() string {\n\treturn spm.backupEtcdDir\n}","line":{"from":169,"to":172}} {"id":100001108,"name":"CleanupDirs","signature":"func (spm *KubeStaticPodPathManager) CleanupDirs() error","file":"cmd/kubeadm/app/phases/upgrade/staticpods.go","code":"// CleanupDirs cleans up all temporary directories except those the user has requested to keep around\nfunc (spm *KubeStaticPodPathManager) CleanupDirs() error {\n\tvar errlist []error\n\tif err := os.RemoveAll(spm.TempManifestDir()); err != nil {\n\t\terrlist = append(errlist, err)\n\t}\n\tif !spm.keepManifestDir {\n\t\tif err := os.RemoveAll(spm.BackupManifestDir()); err != nil {\n\t\t\terrlist = append(errlist, err)\n\t\t}\n\t}\n\n\tif !spm.keepEtcdDir {\n\t\tif err := os.RemoveAll(spm.BackupEtcdDir()); err != nil {\n\t\t\terrlist = append(errlist, err)\n\t\t}\n\t}\n\n\treturn utilerrors.NewAggregate(errlist)\n}","line":{"from":174,"to":193}} {"id":100001109,"name":"upgradeComponent","signature":"func upgradeComponent(component string, certsRenewMgr *renewal.Manager, waiter apiclient.Waiter, pathMgr StaticPodPathManager, cfg *kubeadmapi.InitConfiguration, beforePodHash string, recoverManifests map[string]string) error","file":"cmd/kubeadm/app/phases/upgrade/staticpods.go","code":"func upgradeComponent(component string, certsRenewMgr *renewal.Manager, waiter apiclient.Waiter, pathMgr StaticPodPathManager, cfg *kubeadmapi.InitConfiguration, beforePodHash string, recoverManifests map[string]string) error {\n\t// Special treatment is required for etcd case, when rollbackOldManifests should roll back etcd\n\t// manifests only for the case when component is Etcd\n\trecoverEtcd := false\n\tif component == constants.Etcd {\n\t\trecoverEtcd = true\n\t}\n\n\tfmt.Printf(\"[upgrade/staticpods] Preparing for %q upgrade\\n\", component)\n\n\t// The old manifest is here; in the /etc/kubernetes/manifests/\n\tcurrentManifestPath := pathMgr.RealManifestPath(component)\n\t// The new, upgraded manifest will be written here\n\tnewManifestPath := pathMgr.TempManifestPath(component)\n\t// The old manifest will be moved here; into a subfolder of the temporary directory\n\t// If a rollback is needed, these manifests will be put back to where they where initially\n\tbackupManifestPath := pathMgr.BackupManifestPath(component)\n\n\t// Store the backup path in the recover list. If something goes wrong now, this component will be rolled back.\n\trecoverManifests[component] = backupManifestPath\n\n\t// Skip upgrade if current and new manifests are equal\n\tequal, err := staticpod.ManifestFilesAreEqual(currentManifestPath, newManifestPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif equal {\n\t\tfmt.Printf(\"[upgrade/staticpods] Current and new manifests of %s are equal, skipping upgrade\\n\", component)\n\t\treturn nil\n\t}\n\n\t// if certificate renewal should be performed\n\tif certsRenewMgr != nil {\n\t\t// renew all the certificates used by the current component\n\t\tif err := renewCertsByComponent(cfg, component, certsRenewMgr); err != nil {\n\t\t\treturn rollbackOldManifests(recoverManifests, errors.Wrapf(err, \"failed to renew certificates for component %q\", component), pathMgr, recoverEtcd)\n\t\t}\n\t}\n\n\t// Move the old manifest into the old-manifests directory\n\tif err := pathMgr.MoveFile(currentManifestPath, backupManifestPath); err != nil {\n\t\treturn rollbackOldManifests(recoverManifests, err, pathMgr, recoverEtcd)\n\t}\n\n\t// Move the new manifest into the manifests directory\n\tif err := pathMgr.MoveFile(newManifestPath, currentManifestPath); err != nil {\n\t\treturn rollbackOldManifests(recoverManifests, err, pathMgr, recoverEtcd)\n\t}\n\n\tfmt.Printf(\"[upgrade/staticpods] Moved new manifest to %q and backed up old manifest to %q\\n\", currentManifestPath, backupManifestPath)\n\n\tfmt.Println(\"[upgrade/staticpods] Waiting for the kubelet to restart the component\")\n\tfmt.Printf(\"[upgrade/staticpods] This might take a minute or longer depending on the component/version gap (timeout %v)\\n\", UpgradeManifestTimeout)\n\n\t// Wait for the mirror Pod hash to change; otherwise we'll run into race conditions here when the kubelet hasn't had time to\n\t// notice the removal of the Static Pod, leading to a false positive below where we check that the API endpoint is healthy\n\t// If we don't do this, there is a case where we remove the Static Pod manifest, kubelet is slow to react, kubeadm checks the\n\t// API endpoint below of the OLD Static Pod component and proceeds quickly enough, which might lead to unexpected results.\n\tif err := waiter.WaitForStaticPodHashChange(cfg.NodeRegistration.Name, component, beforePodHash); err != nil {\n\t\treturn rollbackOldManifests(recoverManifests, err, pathMgr, recoverEtcd)\n\t}\n\n\t// Wait for the static pod component to come up and register itself as a mirror pod\n\tif err := waiter.WaitForPodsWithLabel(\"component=\" + component); err != nil {\n\t\treturn rollbackOldManifests(recoverManifests, err, pathMgr, recoverEtcd)\n\t}\n\n\tfmt.Printf(\"[upgrade/staticpods] Component %q upgraded successfully!\\n\", component)\n\n\treturn nil\n}","line":{"from":195,"to":265}} {"id":100001110,"name":"performEtcdStaticPodUpgrade","signature":"func performEtcdStaticPodUpgrade(certsRenewMgr *renewal.Manager, client clientset.Interface, waiter apiclient.Waiter, pathMgr StaticPodPathManager, cfg *kubeadmapi.InitConfiguration, recoverManifests map[string]string, oldEtcdClient, newEtcdClient etcdutil.ClusterInterrogator) (bool, error)","file":"cmd/kubeadm/app/phases/upgrade/staticpods.go","code":"// performEtcdStaticPodUpgrade performs upgrade of etcd, it returns bool which indicates fatal error or not and the actual error.\nfunc performEtcdStaticPodUpgrade(certsRenewMgr *renewal.Manager, client clientset.Interface, waiter apiclient.Waiter, pathMgr StaticPodPathManager, cfg *kubeadmapi.InitConfiguration, recoverManifests map[string]string, oldEtcdClient, newEtcdClient etcdutil.ClusterInterrogator) (bool, error) {\n\t// Add etcd static pod spec only if external etcd is not configured\n\tif cfg.Etcd.External != nil {\n\t\treturn false, errors.New(\"external etcd detected, won't try to change any etcd state\")\n\t}\n\n\t// Checking health state of etcd before proceeding with the upgrade\n\terr := oldEtcdClient.CheckClusterHealth()\n\tif err != nil {\n\t\treturn true, errors.Wrap(err, \"etcd cluster is not healthy\")\n\t}\n\n\t// Backing up etcd data store\n\tbackupEtcdDir := pathMgr.BackupEtcdDir()\n\trunningEtcdDir := cfg.Etcd.Local.DataDir\n\toutput, err := kubeadmutil.CopyDir(runningEtcdDir, backupEtcdDir)\n\tif err != nil {\n\t\treturn true, errors.Wrapf(err, \"failed to back up etcd data, output: %q\", output)\n\t}\n\n\t// Get the desired etcd version. That's either the one specified by the user in cfg.Etcd.Local.ImageTag\n\t// or the kubeadm preferred one for the desired Kubernetes version\n\tvar desiredEtcdVersion *version.Version\n\tif cfg.Etcd.Local.ImageTag != \"\" {\n\t\tdesiredEtcdVersion, err = version.ParseSemantic(\n\t\t\tconvertImageTagMetadataToSemver(cfg.Etcd.Local.ImageTag))\n\t\tif err != nil {\n\t\t\treturn true, errors.Wrapf(err, \"failed to parse tag %q as a semantic version\", cfg.Etcd.Local.ImageTag)\n\t\t}\n\t} else {\n\t\t// Need to check currently used version and version from constants, if differs then upgrade\n\t\tvar warning error\n\t\tdesiredEtcdVersion, warning, err = constants.EtcdSupportedVersion(constants.SupportedEtcdVersion, cfg.KubernetesVersion)\n\t\tif err != nil {\n\t\t\treturn true, errors.Wrap(err, \"failed to retrieve an etcd version for the target Kubernetes version\")\n\t\t}\n\t\tif warning != nil {\n\t\t\tklog.Warningf(\"[upgrade/etcd] %v\", warning)\n\t\t}\n\t}\n\n\t// Get the etcd version of the local/stacked etcd member running on the current machine\n\tcurrentEtcdVersionStr, err := GetEtcdImageTagFromStaticPod(pathMgr.RealManifestDir())\n\tif err != nil {\n\t\treturn true, errors.Wrap(err, \"failed to retrieve the current etcd version\")\n\t}\n\n\tcmpResult, err := desiredEtcdVersion.Compare(currentEtcdVersionStr)\n\tif err != nil {\n\t\treturn true, errors.Wrapf(err, \"failed comparing the current etcd version %q to the desired one %q\", currentEtcdVersionStr, desiredEtcdVersion)\n\t}\n\tif cmpResult \u003c 0 {\n\t\treturn false, errors.Errorf(\"the desired etcd version %q is older than the currently installed %q. Skipping etcd upgrade\", desiredEtcdVersion, currentEtcdVersionStr)\n\t}\n\n\tbeforeEtcdPodHash, err := waiter.WaitForStaticPodSingleHash(cfg.NodeRegistration.Name, constants.Etcd)\n\tif err != nil {\n\t\treturn true, err\n\t}\n\n\t// Write the updated etcd static Pod manifest into the temporary directory, at this point no etcd change\n\t// has occurred in any aspects.\n\tif err := etcdphase.CreateLocalEtcdStaticPodManifestFile(pathMgr.TempManifestDir(), pathMgr.PatchesDir(), cfg.NodeRegistration.Name, \u0026cfg.ClusterConfiguration, \u0026cfg.LocalAPIEndpoint, false /* isDryRun */); err != nil {\n\t\treturn true, errors.Wrap(err, \"error creating local etcd static pod manifest file\")\n\t}\n\n\tretries := 10\n\tretryInterval := 15 * time.Second\n\n\t// Perform etcd upgrade using common to all control plane components function\n\tif err := upgradeComponent(constants.Etcd, certsRenewMgr, waiter, pathMgr, cfg, beforeEtcdPodHash, recoverManifests); err != nil {\n\t\tfmt.Printf(\"[upgrade/etcd] Failed to upgrade etcd: %v\\n\", err)\n\t\t// Since upgrade component failed, the old etcd manifest has either been restored or was never touched\n\t\t// Now we need to check the health of etcd cluster if it is up with old manifest\n\t\tfmt.Println(\"[upgrade/etcd] Waiting for previous etcd to become available\")\n\t\tif _, err := oldEtcdClient.WaitForClusterAvailable(retries, retryInterval); err != nil {\n\t\t\tfmt.Printf(\"[upgrade/etcd] Failed to healthcheck previous etcd: %v\\n\", err)\n\n\t\t\t// At this point we know that etcd cluster is dead and it is safe to copy backup datastore and to rollback old etcd manifest\n\t\t\tfmt.Println(\"[upgrade/etcd] Rolling back etcd data\")\n\t\t\tif err := rollbackEtcdData(cfg, pathMgr); err != nil {\n\t\t\t\t// Even copying back datastore failed, no options for recovery left, bailing out\n\t\t\t\treturn true, errors.Errorf(\"fatal error rolling back local etcd cluster datadir: %v, the backup of etcd database is stored here:(%s)\", err, backupEtcdDir)\n\t\t\t}\n\t\t\tfmt.Println(\"[upgrade/etcd] Etcd data rollback successful\")\n\n\t\t\t// Now that we've rolled back the data, let's check if the cluster comes up\n\t\t\tfmt.Println(\"[upgrade/etcd] Waiting for previous etcd to become available\")\n\t\t\tif _, err := oldEtcdClient.WaitForClusterAvailable(retries, retryInterval); err != nil {\n\t\t\t\tfmt.Printf(\"[upgrade/etcd] Failed to healthcheck previous etcd: %v\\n\", err)\n\t\t\t\t// Nothing else left to try to recover etcd cluster\n\t\t\t\treturn true, errors.Wrapf(err, \"fatal error rolling back local etcd cluster manifest, the backup of etcd database is stored here:(%s)\", backupEtcdDir)\n\t\t\t}\n\n\t\t\t// We've recovered to the previous etcd from this case\n\t\t}\n\t\tfmt.Println(\"[upgrade/etcd] Etcd was rolled back and is now available\")\n\n\t\t// Since etcd cluster came back up with the old manifest\n\t\treturn true, errors.Wrap(err, \"fatal error when trying to upgrade the etcd cluster, rolled the state back to pre-upgrade state\")\n\t}\n\n\t// Initialize the new etcd client if it wasn't pre-initialized\n\tif newEtcdClient == nil {\n\t\tetcdClient, err := etcdutil.NewFromCluster(client, cfg.CertificatesDir)\n\t\tif err != nil {\n\t\t\treturn true, errors.Wrap(err, \"fatal error creating etcd client\")\n\t\t}\n\t\tnewEtcdClient = etcdClient\n\t}\n\n\t// Checking health state of etcd after the upgrade\n\tfmt.Println(\"[upgrade/etcd] Waiting for etcd to become available\")\n\tif _, err = newEtcdClient.WaitForClusterAvailable(retries, retryInterval); err != nil {\n\t\tfmt.Printf(\"[upgrade/etcd] Failed to healthcheck etcd: %v\\n\", err)\n\t\t// Despite the fact that upgradeComponent was successful, there is something wrong with the etcd cluster\n\t\t// First step is to restore back up of datastore\n\t\tfmt.Println(\"[upgrade/etcd] Rolling back etcd data\")\n\t\tif err := rollbackEtcdData(cfg, pathMgr); err != nil {\n\t\t\t// Even copying back datastore failed, no options for recovery left, bailing out\n\t\t\treturn true, errors.Wrapf(err, \"fatal error rolling back local etcd cluster datadir, the backup of etcd database is stored here:(%s)\", backupEtcdDir)\n\t\t}\n\t\tfmt.Println(\"[upgrade/etcd] Etcd data rollback successful\")\n\n\t\t// Old datastore has been copied, rolling back old manifests\n\t\tfmt.Println(\"[upgrade/etcd] Rolling back etcd manifest\")\n\t\trollbackOldManifests(recoverManifests, err, pathMgr, true)\n\t\t// rollbackOldManifests() always returns an error -- ignore it and continue\n\n\t\t// Assuming rollback of the old etcd manifest was successful, check the status of etcd cluster again\n\t\tfmt.Println(\"[upgrade/etcd] Waiting for previous etcd to become available\")\n\t\tif _, err := oldEtcdClient.WaitForClusterAvailable(retries, retryInterval); err != nil {\n\t\t\tfmt.Printf(\"[upgrade/etcd] Failed to healthcheck previous etcd: %v\\n\", err)\n\t\t\t// Nothing else left to try to recover etcd cluster\n\t\t\treturn true, errors.Wrapf(err, \"fatal error rolling back local etcd cluster manifest, the backup of etcd database is stored here:(%s)\", backupEtcdDir)\n\t\t}\n\t\tfmt.Println(\"[upgrade/etcd] Etcd was rolled back and is now available\")\n\n\t\t// We've successfully rolled back etcd, and now return an error describing that the upgrade failed\n\t\treturn true, errors.Wrap(err, \"fatal error upgrading local etcd cluster, rolled the state back to pre-upgrade state\")\n\t}\n\n\treturn false, nil\n}","line":{"from":267,"to":411}} {"id":100001111,"name":"StaticPodControlPlane","signature":"func StaticPodControlPlane(client clientset.Interface, waiter apiclient.Waiter, pathMgr StaticPodPathManager, cfg *kubeadmapi.InitConfiguration, etcdUpgrade, renewCerts bool, oldEtcdClient, newEtcdClient etcdutil.ClusterInterrogator) error","file":"cmd/kubeadm/app/phases/upgrade/staticpods.go","code":"// StaticPodControlPlane upgrades a static pod-hosted control plane\nfunc StaticPodControlPlane(client clientset.Interface, waiter apiclient.Waiter, pathMgr StaticPodPathManager, cfg *kubeadmapi.InitConfiguration, etcdUpgrade, renewCerts bool, oldEtcdClient, newEtcdClient etcdutil.ClusterInterrogator) error {\n\trecoverManifests := map[string]string{}\n\tvar isExternalEtcd bool\n\n\tbeforePodHashMap, err := waiter.WaitForStaticPodControlPlaneHashes(cfg.NodeRegistration.Name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif oldEtcdClient == nil {\n\t\tif cfg.Etcd.External != nil {\n\t\t\t// External etcd\n\t\t\tisExternalEtcd = true\n\t\t\tetcdClient, err := etcdutil.New(\n\t\t\t\tcfg.Etcd.External.Endpoints,\n\t\t\t\tcfg.Etcd.External.CAFile,\n\t\t\t\tcfg.Etcd.External.CertFile,\n\t\t\t\tcfg.Etcd.External.KeyFile,\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"failed to create etcd client for external etcd\")\n\t\t\t}\n\t\t\toldEtcdClient = etcdClient\n\t\t\t// Since etcd is managed externally, the new etcd client will be the same as the old client\n\t\t\tif newEtcdClient == nil {\n\t\t\t\tnewEtcdClient = etcdClient\n\t\t\t}\n\t\t} else {\n\t\t\t// etcd Static Pod\n\t\t\tetcdClient, err := etcdutil.NewFromCluster(client, cfg.CertificatesDir)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"failed to create etcd client\")\n\t\t\t}\n\t\t\toldEtcdClient = etcdClient\n\t\t}\n\t}\n\n\tvar certsRenewMgr *renewal.Manager\n\tif renewCerts {\n\t\tcertsRenewMgr, err = renewal.NewManager(\u0026cfg.ClusterConfiguration, pathMgr.KubernetesDir())\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to create the certificate renewal manager\")\n\t\t}\n\t}\n\n\t// etcd upgrade is done prior to other control plane components\n\tif !isExternalEtcd \u0026\u0026 etcdUpgrade {\n\t\t// set the TLS upgrade flag for all components\n\t\tfmt.Printf(\"[upgrade/etcd] Upgrading to TLS for %s\\n\", constants.Etcd)\n\n\t\t// Perform etcd upgrade using common to all control plane components function\n\t\tfatal, err := performEtcdStaticPodUpgrade(certsRenewMgr, client, waiter, pathMgr, cfg, recoverManifests, oldEtcdClient, newEtcdClient)\n\t\tif err != nil {\n\t\t\tif fatal {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfmt.Printf(\"[upgrade/etcd] Non fatal issue encountered during upgrade: %v\\n\", err)\n\t\t}\n\t}\n\n\t// Write the updated static Pod manifests into the temporary directory\n\tfmt.Printf(\"[upgrade/staticpods] Writing new Static Pod manifests to %q\\n\", pathMgr.TempManifestDir())\n\terr = controlplane.CreateInitStaticPodManifestFiles(pathMgr.TempManifestDir(), pathMgr.PatchesDir(), cfg, false /* isDryRun */)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error creating init static pod manifest files\")\n\t}\n\n\tfor _, component := range constants.ControlPlaneComponents {\n\t\tif err = upgradeComponent(component, certsRenewMgr, waiter, pathMgr, cfg, beforePodHashMap[component], recoverManifests); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif renewCerts {\n\t\t// renew the certificate embedded in the admin.conf file\n\t\trenewed, err := certsRenewMgr.RenewUsingLocalCA(constants.AdminKubeConfigFileName)\n\t\tif err != nil {\n\t\t\treturn rollbackOldManifests(recoverManifests, errors.Wrapf(err, \"failed to upgrade the %s certificates\", constants.AdminKubeConfigFileName), pathMgr, false)\n\t\t}\n\n\t\tif !renewed {\n\t\t\t// if not error, but not renewed because of external CA detected, inform the user\n\t\t\tfmt.Printf(\"[upgrade/staticpods] External CA detected, %s certificate can't be renewed\\n\", constants.AdminKubeConfigFileName)\n\t\t}\n\t}\n\n\t// Remove the temporary directories used on a best-effort (don't fail if the calls error out)\n\t// The calls are set here by design; we should _not_ use \"defer\" above as that would remove the directories\n\t// even in the \"fail and rollback\" case, where we want the directories preserved for the user.\n\treturn pathMgr.CleanupDirs()\n}","line":{"from":413,"to":504}} {"id":100001112,"name":"rollbackOldManifests","signature":"func rollbackOldManifests(oldManifests map[string]string, origErr error, pathMgr StaticPodPathManager, restoreEtcd bool) error","file":"cmd/kubeadm/app/phases/upgrade/staticpods.go","code":"// rollbackOldManifests rolls back the backed-up manifests if something went wrong.\n// It always returns an error to the caller.\nfunc rollbackOldManifests(oldManifests map[string]string, origErr error, pathMgr StaticPodPathManager, restoreEtcd bool) error {\n\terrs := []error{origErr}\n\tfor component, backupPath := range oldManifests {\n\t\t// Will restore etcd manifest only if it was explicitly requested by setting restoreEtcd to True\n\t\tif component == constants.Etcd \u0026\u0026 !restoreEtcd {\n\t\t\tcontinue\n\t\t}\n\t\t// Where we should put back the backed up manifest\n\t\trealManifestPath := pathMgr.RealManifestPath(component)\n\n\t\t// Move the backup manifest back into the manifests directory\n\t\terr := pathMgr.MoveFile(backupPath, realManifestPath)\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\t// Let the user know there were problems, but we tried to recover\n\treturn errors.Wrap(utilerrors.NewAggregate(errs),\n\t\t\"couldn't upgrade control plane. kubeadm has tried to recover everything into the earlier state. Errors faced\")\n}","line":{"from":506,"to":527}} {"id":100001113,"name":"rollbackEtcdData","signature":"func rollbackEtcdData(cfg *kubeadmapi.InitConfiguration, pathMgr StaticPodPathManager) error","file":"cmd/kubeadm/app/phases/upgrade/staticpods.go","code":"// rollbackEtcdData rolls back the content of etcd folder if something went wrong.\n// When the folder contents are successfully rolled back, nil is returned, otherwise an error is returned.\nfunc rollbackEtcdData(cfg *kubeadmapi.InitConfiguration, pathMgr StaticPodPathManager) error {\n\tbackupEtcdDir := pathMgr.BackupEtcdDir()\n\trunningEtcdDir := cfg.Etcd.Local.DataDir\n\n\toutput, err := kubeadmutil.CopyDir(backupEtcdDir, runningEtcdDir)\n\tif err != nil {\n\t\t// Let the user know there we're problems, but we tried to reçover\n\t\treturn errors.Wrapf(err, \"couldn't recover etcd database with error, the location of etcd backup: %s, output: %q\", backupEtcdDir, output)\n\t}\n\n\treturn nil\n}","line":{"from":529,"to":542}} {"id":100001114,"name":"renewCertsByComponent","signature":"func renewCertsByComponent(cfg *kubeadmapi.InitConfiguration, component string, certsRenewMgr *renewal.Manager) error","file":"cmd/kubeadm/app/phases/upgrade/staticpods.go","code":"// renewCertsByComponent takes charge of renewing certificates used by a specific component before\n// the static pod of the component is upgraded\nfunc renewCertsByComponent(cfg *kubeadmapi.InitConfiguration, component string, certsRenewMgr *renewal.Manager) error {\n\tvar certificates []string\n\n\t// if etcd, only in case of local etcd, renew server, peer and health check certificate\n\tif component == constants.Etcd {\n\t\tif cfg.Etcd.Local != nil {\n\t\t\tcertificates = []string{\n\t\t\t\tcertsphase.KubeadmCertEtcdServer().Name,\n\t\t\t\tcertsphase.KubeadmCertEtcdPeer().Name,\n\t\t\t\tcertsphase.KubeadmCertEtcdHealthcheck().Name,\n\t\t\t}\n\t\t}\n\t}\n\n\t// if apiserver, renew apiserver serving certificate, kubelet and front-proxy client certificate.\n\t//if local etcd, renew also the etcd client certificate\n\tif component == constants.KubeAPIServer {\n\t\tcertificates = []string{\n\t\t\tcertsphase.KubeadmCertAPIServer().Name,\n\t\t\tcertsphase.KubeadmCertKubeletClient().Name,\n\t\t\tcertsphase.KubeadmCertFrontProxyClient().Name,\n\t\t}\n\t\tif cfg.Etcd.Local != nil {\n\t\t\tcertificates = append(certificates, certsphase.KubeadmCertEtcdAPIClient().Name)\n\t\t}\n\t}\n\n\t// if controller-manager, renew the certificate embedded in the controller-manager kubeConfig file\n\tif component == constants.KubeControllerManager {\n\t\tcertificates = []string{\n\t\t\tconstants.ControllerManagerKubeConfigFileName,\n\t\t}\n\t}\n\n\t// if scheduler, renew the certificate embedded in the scheduler kubeConfig file\n\tif component == constants.KubeScheduler {\n\t\tcertificates = []string{\n\t\t\tconstants.SchedulerKubeConfigFileName,\n\t\t}\n\t}\n\n\t// renew the selected components\n\tfor _, cert := range certificates {\n\t\tfmt.Printf(\"[upgrade/staticpods] Renewing %s certificate\\n\", cert)\n\t\trenewed, err := certsRenewMgr.RenewUsingLocalCA(cert)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !renewed {\n\t\t\t// if not error, but not renewed because of external CA detected, inform the user\n\t\t\tfmt.Printf(\"[upgrade/staticpods] External CA detected, %s certificate can't be renewed\\n\", cert)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":544,"to":601}} {"id":100001115,"name":"GetPathManagerForUpgrade","signature":"func GetPathManagerForUpgrade(kubernetesDir, patchesDir string, internalcfg *kubeadmapi.InitConfiguration, etcdUpgrade bool) (StaticPodPathManager, error)","file":"cmd/kubeadm/app/phases/upgrade/staticpods.go","code":"// GetPathManagerForUpgrade returns a path manager properly configured for the given InitConfiguration.\nfunc GetPathManagerForUpgrade(kubernetesDir, patchesDir string, internalcfg *kubeadmapi.InitConfiguration, etcdUpgrade bool) (StaticPodPathManager, error) {\n\tisExternalEtcd := internalcfg.Etcd.External != nil\n\treturn NewKubeStaticPodPathManagerUsingTempDirs(kubernetesDir, patchesDir, true, etcdUpgrade \u0026\u0026 !isExternalEtcd)\n}","line":{"from":603,"to":607}} {"id":100001116,"name":"PerformStaticPodUpgrade","signature":"func PerformStaticPodUpgrade(client clientset.Interface, waiter apiclient.Waiter, internalcfg *kubeadmapi.InitConfiguration, etcdUpgrade, renewCerts bool, patchesDir string) error","file":"cmd/kubeadm/app/phases/upgrade/staticpods.go","code":"// PerformStaticPodUpgrade performs the upgrade of the control plane components for a static pod hosted cluster\nfunc PerformStaticPodUpgrade(client clientset.Interface, waiter apiclient.Waiter, internalcfg *kubeadmapi.InitConfiguration, etcdUpgrade, renewCerts bool, patchesDir string) error {\n\tpathManager, err := GetPathManagerForUpgrade(constants.KubernetesDir, patchesDir, internalcfg, etcdUpgrade)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// The arguments oldEtcdClient and newEtdClient, are uninitialized because passing in the clients allow for mocking the client during testing\n\treturn StaticPodControlPlane(client, waiter, pathManager, internalcfg, etcdUpgrade, renewCerts, nil, nil)\n}","line":{"from":609,"to":618}} {"id":100001117,"name":"DryRunStaticPodUpgrade","signature":"func DryRunStaticPodUpgrade(patchesDir string, internalcfg *kubeadmapi.InitConfiguration) error","file":"cmd/kubeadm/app/phases/upgrade/staticpods.go","code":"// DryRunStaticPodUpgrade fakes an upgrade of the control plane\nfunc DryRunStaticPodUpgrade(patchesDir string, internalcfg *kubeadmapi.InitConfiguration) error {\n\n\tdryRunManifestDir, err := constants.CreateTempDirForKubeadm(\"\", \"kubeadm-upgrade-dryrun\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer os.RemoveAll(dryRunManifestDir)\n\tif err := controlplane.CreateInitStaticPodManifestFiles(dryRunManifestDir, patchesDir, internalcfg, true /* isDryRun */); err != nil {\n\t\treturn err\n\t}\n\n\t// Print the contents of the upgraded manifests and pretend like they were in /etc/kubernetes/manifests\n\tfiles := []dryrunutil.FileToPrint{}\n\tfor _, component := range constants.ControlPlaneComponents {\n\t\trealPath := constants.GetStaticPodFilepath(component, dryRunManifestDir)\n\t\toutputPath := constants.GetStaticPodFilepath(component, constants.GetStaticPodDirectory())\n\t\tfiles = append(files, dryrunutil.NewFileToPrint(realPath, outputPath))\n\t}\n\n\treturn dryrunutil.PrintDryRunFiles(files, os.Stdout)\n}","line":{"from":620,"to":641}} {"id":100001118,"name":"GetEtcdImageTagFromStaticPod","signature":"func GetEtcdImageTagFromStaticPod(manifestDir string) (string, error)","file":"cmd/kubeadm/app/phases/upgrade/staticpods.go","code":"// GetEtcdImageTagFromStaticPod returns the image tag of the local etcd static pod\nfunc GetEtcdImageTagFromStaticPod(manifestDir string) (string, error) {\n\trealPath := constants.GetStaticPodFilepath(constants.Etcd, manifestDir)\n\tpod, err := staticpod.ReadStaticPodFromDisk(realPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn convertImageTagMetadataToSemver(image.TagFromImage(pod.Spec.Containers[0].Image)), nil\n}","line":{"from":643,"to":652}} {"id":100001119,"name":"convertImageTagMetadataToSemver","signature":"func convertImageTagMetadataToSemver(tag string) string","file":"cmd/kubeadm/app/phases/upgrade/staticpods.go","code":"// convertImageTagMetadataToSemver converts imagetag in the format of semver_metadata to semver+metadata\nfunc convertImageTagMetadataToSemver(tag string) string {\n\t// Container registries do not support `+` characters in tag names. This prevents imagetags from\n\t// correctly representing semantic versions which use the plus symbol to delimit build metadata.\n\t// Kubernetes uses the convention of using an underscore in image registries to preserve\n\t// build metadata information in imagetags.\n\treturn strings.Replace(tag, \"_\", \"+\", 1)\n}","line":{"from":654,"to":661}} {"id":100001120,"name":"NewKubeVersionGetter","signature":"func NewKubeVersionGetter(client clientset.Interface) VersionGetter","file":"cmd/kubeadm/app/phases/upgrade/versiongetter.go","code":"// NewKubeVersionGetter returns a new instance of KubeVersionGetter\nfunc NewKubeVersionGetter(client clientset.Interface) VersionGetter {\n\treturn \u0026KubeVersionGetter{\n\t\tclient: client,\n\t}\n}","line":{"from":53,"to":58}} {"id":100001121,"name":"ClusterVersion","signature":"func (g *KubeVersionGetter) ClusterVersion() (string, *versionutil.Version, error)","file":"cmd/kubeadm/app/phases/upgrade/versiongetter.go","code":"// ClusterVersion gets API server version\nfunc (g *KubeVersionGetter) ClusterVersion() (string, *versionutil.Version, error) {\n\tvar (\n\t\tclusterVersionInfo *pkgversion.Info\n\t\terr error\n\t)\n\t// If we are dry-running, do not attempt to fetch the /version resource and just return\n\t// the stored FakeServerVersion, which is done when constructing the dry-run client in\n\t// common.go#getClient()\n\t// The problem here is that during upgrade dry-run client reactors are backed by a dynamic client\n\t// via NewClientBackedDryRunGetterFromKubeconfig() and for GetActions there seems to be no analog to\n\t// Discovery().Serverversion() resource for a dynamic client(?).\n\tfakeclientDiscovery, ok := g.client.Discovery().(*fakediscovery.FakeDiscovery)\n\tif ok {\n\t\tclusterVersionInfo = fakeclientDiscovery.FakedServerVersion\n\t} else {\n\t\tclusterVersionInfo, err = g.client.Discovery().ServerVersion()\n\t\tif err != nil {\n\t\t\treturn \"\", nil, errors.Wrap(err, \"Couldn't fetch cluster version from the API Server\")\n\t\t}\n\t}\n\n\tclusterVersion, err := versionutil.ParseSemantic(clusterVersionInfo.String())\n\tif err != nil {\n\t\treturn \"\", nil, errors.Wrap(err, \"Couldn't parse cluster version\")\n\t}\n\treturn clusterVersionInfo.String(), clusterVersion, nil\n}","line":{"from":60,"to":87}} {"id":100001122,"name":"KubeadmVersion","signature":"func (g *KubeVersionGetter) KubeadmVersion() (string, *versionutil.Version, error)","file":"cmd/kubeadm/app/phases/upgrade/versiongetter.go","code":"// KubeadmVersion gets kubeadm version\nfunc (g *KubeVersionGetter) KubeadmVersion() (string, *versionutil.Version, error) {\n\tkubeadmVersionInfo := version.Get()\n\n\tkubeadmVersion, err := versionutil.ParseSemantic(kubeadmVersionInfo.String())\n\tif err != nil {\n\t\treturn \"\", nil, errors.Wrap(err, \"Couldn't parse kubeadm version\")\n\t}\n\treturn kubeadmVersionInfo.String(), kubeadmVersion, nil\n}","line":{"from":89,"to":98}} {"id":100001123,"name":"VersionFromCILabel","signature":"func (g *KubeVersionGetter) VersionFromCILabel(ciVersionLabel, description string) (string, *versionutil.Version, error)","file":"cmd/kubeadm/app/phases/upgrade/versiongetter.go","code":"// VersionFromCILabel resolves a version label like \"latest\" or \"stable\" to an actual version using the public Kubernetes CI uploads\nfunc (g *KubeVersionGetter) VersionFromCILabel(ciVersionLabel, description string) (string, *versionutil.Version, error) {\n\tversionStr, err := kubeadmutil.KubernetesReleaseVersion(ciVersionLabel)\n\tif err != nil {\n\t\treturn \"\", nil, errors.Wrapf(err, \"Couldn't fetch latest %s from the internet\", description)\n\t}\n\n\tver, err := versionutil.ParseSemantic(versionStr)\n\tif err != nil {\n\t\treturn \"\", nil, errors.Wrapf(err, \"Couldn't parse latest %s\", description)\n\t}\n\treturn versionStr, ver, nil\n}","line":{"from":100,"to":112}} {"id":100001124,"name":"KubeletVersions","signature":"func (g *KubeVersionGetter) KubeletVersions() (map[string]uint16, error)","file":"cmd/kubeadm/app/phases/upgrade/versiongetter.go","code":"// KubeletVersions gets the versions of the kubelets in the cluster\nfunc (g *KubeVersionGetter) KubeletVersions() (map[string]uint16, error) {\n\tnodes, err := g.client.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, errors.New(\"couldn't list all nodes in cluster\")\n\t}\n\treturn computeKubeletVersions(nodes.Items), nil\n}","line":{"from":114,"to":121}} {"id":100001125,"name":"computeKubeletVersions","signature":"func computeKubeletVersions(nodes []v1.Node) map[string]uint16","file":"cmd/kubeadm/app/phases/upgrade/versiongetter.go","code":"// computeKubeletVersions returns a string-int map that describes how many nodes are of a specific version\nfunc computeKubeletVersions(nodes []v1.Node) map[string]uint16 {\n\tkubeletVersions := make(map[string]uint16)\n\tfor _, node := range nodes {\n\t\tkver := node.Status.NodeInfo.KubeletVersion\n\t\tif _, found := kubeletVersions[kver]; !found {\n\t\t\tkubeletVersions[kver] = 1\n\t\t\tcontinue\n\t\t}\n\t\tkubeletVersions[kver]++\n\t}\n\treturn kubeletVersions\n}","line":{"from":123,"to":135}} {"id":100001126,"name":"NewOfflineVersionGetter","signature":"func NewOfflineVersionGetter(versionGetter VersionGetter, version string) VersionGetter","file":"cmd/kubeadm/app/phases/upgrade/versiongetter.go","code":"// NewOfflineVersionGetter wraps a VersionGetter and skips online communication if default information is supplied.\n// Version can be \"\" and the behavior will be identical to the versionGetter passed in.\nfunc NewOfflineVersionGetter(versionGetter VersionGetter, version string) VersionGetter {\n\treturn \u0026OfflineVersionGetter{\n\t\tVersionGetter: versionGetter,\n\t\tversion: version,\n\t}\n}","line":{"from":143,"to":150}} {"id":100001127,"name":"VersionFromCILabel","signature":"func (o *OfflineVersionGetter) VersionFromCILabel(ciVersionLabel, description string) (string, *versionutil.Version, error)","file":"cmd/kubeadm/app/phases/upgrade/versiongetter.go","code":"// VersionFromCILabel will return the version that was passed into the struct\nfunc (o *OfflineVersionGetter) VersionFromCILabel(ciVersionLabel, description string) (string, *versionutil.Version, error) {\n\tif o.version == \"\" {\n\t\treturn o.VersionGetter.VersionFromCILabel(ciVersionLabel, description)\n\t}\n\tver, err := versionutil.ParseSemantic(o.version)\n\tif err != nil {\n\t\treturn \"\", nil, errors.Wrapf(err, \"Couldn't parse version %s\", description)\n\t}\n\treturn o.version, ver, nil\n}","line":{"from":152,"to":162}} {"id":100001128,"name":"UploadConfiguration","signature":"func UploadConfiguration(cfg *kubeadmapi.InitConfiguration, client clientset.Interface) error","file":"cmd/kubeadm/app/phases/uploadconfig/uploadconfig.go","code":"// UploadConfiguration saves the InitConfiguration used for later reference (when upgrading for instance)\nfunc UploadConfiguration(cfg *kubeadmapi.InitConfiguration, client clientset.Interface) error {\n\tfmt.Printf(\"[upload-config] Storing the configuration used in ConfigMap %q in the %q Namespace\\n\", kubeadmconstants.KubeadmConfigConfigMap, metav1.NamespaceSystem)\n\n\t// Prepare the ClusterConfiguration for upload\n\t// The components store their config in their own ConfigMaps, then reset the .ComponentConfig struct;\n\t// We don't want to mutate the cfg itself, so create a copy of it using .DeepCopy of it first\n\tclusterConfigurationToUpload := cfg.ClusterConfiguration.DeepCopy()\n\tclusterConfigurationToUpload.ComponentConfigs = kubeadmapi.ComponentConfigMap{}\n\n\t// restore the resolved Kubernetes version as CI Kubernetes version if needed\n\tif len(clusterConfigurationToUpload.CIKubernetesVersion) \u003e 0 {\n\t\tclusterConfigurationToUpload.KubernetesVersion = clusterConfigurationToUpload.CIKubernetesVersion\n\t}\n\n\t// Marshal the ClusterConfiguration into YAML\n\tclusterConfigurationYaml, err := configutil.MarshalKubeadmConfigObject(clusterConfigurationToUpload)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = apiclient.CreateOrMutateConfigMap(client, \u0026v1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: kubeadmconstants.KubeadmConfigConfigMap,\n\t\t\tNamespace: metav1.NamespaceSystem,\n\t\t},\n\t\tData: map[string]string{\n\t\t\tkubeadmconstants.ClusterConfigurationConfigMapKey: string(clusterConfigurationYaml),\n\t\t},\n\t}, func(cm *v1.ConfigMap) error {\n\t\t// Upgrade will call to UploadConfiguration with a modified KubernetesVersion reflecting the new\n\t\t// Kubernetes version. In that case, the mutation path will take place.\n\t\tcm.Data[kubeadmconstants.ClusterConfigurationConfigMapKey] = string(clusterConfigurationYaml)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Ensure that the NodesKubeadmConfigClusterRoleName exists\n\terr = apiclient.CreateOrUpdateRole(client, \u0026rbac.Role{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: NodesKubeadmConfigClusterRoleName,\n\t\t\tNamespace: metav1.NamespaceSystem,\n\t\t},\n\t\tRules: []rbac.PolicyRule{\n\t\t\t{\n\t\t\t\tVerbs: []string{\"get\"},\n\t\t\t\tAPIGroups: []string{\"\"},\n\t\t\t\tResources: []string{\"configmaps\"},\n\t\t\t\tResourceNames: []string{kubeadmconstants.KubeadmConfigConfigMap},\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Binds the NodesKubeadmConfigClusterRoleName to all the bootstrap tokens\n\t// that are members of the system:bootstrappers:kubeadm:default-node-token group\n\t// and to all nodes\n\treturn apiclient.CreateOrUpdateRoleBinding(client, \u0026rbac.RoleBinding{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: NodesKubeadmConfigClusterRoleName,\n\t\t\tNamespace: metav1.NamespaceSystem,\n\t\t},\n\t\tRoleRef: rbac.RoleRef{\n\t\t\tAPIGroup: rbac.GroupName,\n\t\t\tKind: \"Role\",\n\t\t\tName: NodesKubeadmConfigClusterRoleName,\n\t\t},\n\t\tSubjects: []rbac.Subject{\n\t\t\t{\n\t\t\t\tKind: rbac.GroupKind,\n\t\t\t\tName: kubeadmconstants.NodeBootstrapTokenAuthGroup,\n\t\t\t},\n\t\t\t{\n\t\t\t\tKind: rbac.GroupKind,\n\t\t\t\tName: kubeadmconstants.NodesGroup,\n\t\t\t},\n\t\t},\n\t})\n}","line":{"from":40,"to":122}} {"id":100001129,"name":"Error","signature":"func (e *Error) Error() string","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Error implements the standard error interface\nfunc (e *Error) Error() string {\n\treturn fmt.Sprintf(\"[preflight] Some fatal errors occurred:\\n%s%s\", e.Msg, \"[preflight] If you know what you are doing, you can make a check non-fatal with `--ignore-preflight-errors=...`\")\n}","line":{"from":75,"to":78}} {"id":100001130,"name":"Preflight","signature":"func (e *Error) Preflight() bool","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Preflight identifies this error as a preflight error\nfunc (e *Error) Preflight() bool {\n\treturn true\n}","line":{"from":80,"to":83}} {"id":100001131,"name":"Name","signature":"func (ContainerRuntimeCheck) Name() string","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Name returns label for RuntimeCheck.\nfunc (ContainerRuntimeCheck) Name() string {\n\treturn \"CRI\"\n}","line":{"from":97,"to":100}} {"id":100001132,"name":"Check","signature":"func (crc ContainerRuntimeCheck) Check() (warnings, errorList []error)","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Check validates the container runtime\nfunc (crc ContainerRuntimeCheck) Check() (warnings, errorList []error) {\n\tklog.V(1).Infoln(\"validating the container runtime\")\n\tif err := crc.runtime.IsRunning(); err != nil {\n\t\terrorList = append(errorList, err)\n\t}\n\treturn warnings, errorList\n}","line":{"from":102,"to":109}} {"id":100001133,"name":"Name","signature":"func (sc ServiceCheck) Name() string","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Name returns label for ServiceCheck. If not provided, will return based on the service parameter\nfunc (sc ServiceCheck) Name() string {\n\tif sc.Label != \"\" {\n\t\treturn sc.Label\n\t}\n\treturn fmt.Sprintf(\"Service-%s\", strings.Title(sc.Service))\n}","line":{"from":120,"to":126}} {"id":100001134,"name":"Check","signature":"func (sc ServiceCheck) Check() (warnings, errorList []error)","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Check validates if the service is enabled and active.\nfunc (sc ServiceCheck) Check() (warnings, errorList []error) {\n\tklog.V(1).Infof(\"validating if the %q service is enabled and active\", sc.Service)\n\tinitSystem, err := initsystem.GetInitSystem()\n\tif err != nil {\n\t\treturn []error{err}, nil\n\t}\n\n\tif !initSystem.ServiceExists(sc.Service) {\n\t\treturn []error{errors.Errorf(\"%s service does not exist\", sc.Service)}, nil\n\t}\n\n\tif !initSystem.ServiceIsEnabled(sc.Service) {\n\t\twarnings = append(warnings,\n\t\t\terrors.Errorf(\"%s service is not enabled, please run '%s'\",\n\t\t\t\tsc.Service, initSystem.EnableCommand(sc.Service)))\n\t}\n\n\tif sc.CheckIfActive \u0026\u0026 !initSystem.ServiceIsActive(sc.Service) {\n\t\terrorList = append(errorList,\n\t\t\terrors.Errorf(\"%s service is not active, please run 'systemctl start %s.service'\",\n\t\t\t\tsc.Service, sc.Service))\n\t}\n\n\treturn warnings, errorList\n}","line":{"from":128,"to":153}} {"id":100001135,"name":"Name","signature":"func (FirewalldCheck) Name() string","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Name returns label for FirewalldCheck.\nfunc (FirewalldCheck) Name() string {\n\treturn \"Firewalld\"\n}","line":{"from":161,"to":164}} {"id":100001136,"name":"Check","signature":"func (fc FirewalldCheck) Check() (warnings, errorList []error)","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Check validates if the firewall is enabled and active.\nfunc (fc FirewalldCheck) Check() (warnings, errorList []error) {\n\tklog.V(1).Infoln(\"validating if the firewall is enabled and active\")\n\tinitSystem, err := initsystem.GetInitSystem()\n\tif err != nil {\n\t\treturn []error{err}, nil\n\t}\n\n\tif !initSystem.ServiceExists(\"firewalld\") {\n\t\treturn nil, nil\n\t}\n\n\tif initSystem.ServiceIsActive(\"firewalld\") {\n\t\terr := errors.Errorf(\"firewalld is active, please ensure ports %v are open or your cluster may not function correctly\",\n\t\t\tfc.ports)\n\t\treturn []error{err}, nil\n\t}\n\n\treturn nil, nil\n}","line":{"from":166,"to":185}} {"id":100001137,"name":"Name","signature":"func (poc PortOpenCheck) Name() string","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Name returns name for PortOpenCheck. If not known, will return \"PortXXXX\" based on port number\nfunc (poc PortOpenCheck) Name() string {\n\tif poc.label != \"\" {\n\t\treturn poc.label\n\t}\n\treturn fmt.Sprintf(\"Port-%d\", poc.port)\n}","line":{"from":193,"to":199}} {"id":100001138,"name":"Check","signature":"func (poc PortOpenCheck) Check() (warnings, errorList []error)","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Check validates if the particular port is available.\nfunc (poc PortOpenCheck) Check() (warnings, errorList []error) {\n\tklog.V(1).Infof(\"validating availability of port %d\", poc.port)\n\n\tln, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", poc.port))\n\tif err != nil {\n\t\terrorList = []error{errors.Errorf(\"Port %d is in use\", poc.port)}\n\t}\n\tif ln != nil {\n\t\tif err = ln.Close(); err != nil {\n\t\t\twarnings = append(warnings,\n\t\t\t\terrors.Errorf(\"when closing port %d, encountered %v\", poc.port, err))\n\t\t}\n\t}\n\n\treturn warnings, errorList\n}","line":{"from":201,"to":217}} {"id":100001139,"name":"Name","signature":"func (IsPrivilegedUserCheck) Name() string","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Name returns name for IsPrivilegedUserCheck\nfunc (IsPrivilegedUserCheck) Name() string {\n\treturn \"IsPrivilegedUser\"\n}","line":{"from":222,"to":225}} {"id":100001140,"name":"Name","signature":"func (dac DirAvailableCheck) Name() string","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Name returns label for individual DirAvailableChecks. If not known, will return based on path.\nfunc (dac DirAvailableCheck) Name() string {\n\tif dac.Label != \"\" {\n\t\treturn dac.Label\n\t}\n\treturn fmt.Sprintf(\"DirAvailable-%s\", strings.Replace(dac.Path, \"/\", \"-\", -1))\n}","line":{"from":233,"to":239}} {"id":100001141,"name":"Check","signature":"func (dac DirAvailableCheck) Check() (warnings, errorList []error)","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Check validates if a directory does not exist or empty.\nfunc (dac DirAvailableCheck) Check() (warnings, errorList []error) {\n\tklog.V(1).Infof(\"validating the existence and emptiness of directory %s\", dac.Path)\n\n\t// If it doesn't exist we are good:\n\tif _, err := os.Stat(dac.Path); os.IsNotExist(err) {\n\t\treturn nil, nil\n\t}\n\n\tf, err := os.Open(dac.Path)\n\tif err != nil {\n\t\treturn nil, []error{errors.Wrapf(err, \"unable to check if %s is empty\", dac.Path)}\n\t}\n\tdefer f.Close()\n\n\t_, err = f.Readdirnames(1)\n\tif err != io.EOF {\n\t\treturn nil, []error{errors.Errorf(\"%s is not empty\", dac.Path)}\n\t}\n\n\treturn nil, nil\n}","line":{"from":241,"to":262}} {"id":100001142,"name":"Name","signature":"func (fac FileAvailableCheck) Name() string","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Name returns label for individual FileAvailableChecks. If not known, will return based on path.\nfunc (fac FileAvailableCheck) Name() string {\n\tif fac.Label != \"\" {\n\t\treturn fac.Label\n\t}\n\treturn fmt.Sprintf(\"FileAvailable-%s\", strings.Replace(fac.Path, \"/\", \"-\", -1))\n}","line":{"from":270,"to":276}} {"id":100001143,"name":"Check","signature":"func (fac FileAvailableCheck) Check() (warnings, errorList []error)","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Check validates if the given file does not already exist.\nfunc (fac FileAvailableCheck) Check() (warnings, errorList []error) {\n\tklog.V(1).Infof(\"validating the existence of file %s\", fac.Path)\n\n\tif _, err := os.Stat(fac.Path); err == nil {\n\t\treturn nil, []error{errors.Errorf(\"%s already exists\", fac.Path)}\n\t}\n\treturn nil, nil\n}","line":{"from":278,"to":286}} {"id":100001144,"name":"Name","signature":"func (fac FileExistingCheck) Name() string","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Name returns label for individual FileExistingChecks. If not known, will return based on path.\nfunc (fac FileExistingCheck) Name() string {\n\tif fac.Label != \"\" {\n\t\treturn fac.Label\n\t}\n\treturn fmt.Sprintf(\"FileExisting-%s\", strings.Replace(fac.Path, \"/\", \"-\", -1))\n}","line":{"from":294,"to":300}} {"id":100001145,"name":"Check","signature":"func (fac FileExistingCheck) Check() (warnings, errorList []error)","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Check validates if the given file already exists.\nfunc (fac FileExistingCheck) Check() (warnings, errorList []error) {\n\tklog.V(1).Infof(\"validating the existence of file %s\", fac.Path)\n\n\tif _, err := os.Stat(fac.Path); err != nil {\n\t\treturn nil, []error{errors.Errorf(\"%s doesn't exist\", fac.Path)}\n\t}\n\treturn nil, nil\n}","line":{"from":302,"to":310}} {"id":100001146,"name":"Name","signature":"func (fcc FileContentCheck) Name() string","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Name returns label for individual FileContentChecks. If not known, will return based on path.\nfunc (fcc FileContentCheck) Name() string {\n\tif fcc.Label != \"\" {\n\t\treturn fcc.Label\n\t}\n\treturn fmt.Sprintf(\"FileContent-%s\", strings.Replace(fcc.Path, \"/\", \"-\", -1))\n}","line":{"from":319,"to":325}} {"id":100001147,"name":"Check","signature":"func (fcc FileContentCheck) Check() (warnings, errorList []error)","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Check validates if the given file contains the given content.\nfunc (fcc FileContentCheck) Check() (warnings, errorList []error) {\n\tklog.V(1).Infof(\"validating the contents of file %s\", fcc.Path)\n\tf, err := os.Open(fcc.Path)\n\tif err != nil {\n\t\treturn nil, []error{errors.Errorf(\"%s does not exist\", fcc.Path)}\n\t}\n\n\tlr := io.LimitReader(f, int64(len(fcc.Content)))\n\tdefer f.Close()\n\n\tbuf := \u0026bytes.Buffer{}\n\t_, err = io.Copy(buf, lr)\n\tif err != nil {\n\t\treturn nil, []error{errors.Errorf(\"%s could not be read\", fcc.Path)}\n\t}\n\n\tif !bytes.Equal(buf.Bytes(), fcc.Content) {\n\t\treturn nil, []error{errors.Errorf(\"%s contents are not set to %s\", fcc.Path, fcc.Content)}\n\t}\n\treturn nil, []error{}\n\n}","line":{"from":327,"to":349}} {"id":100001148,"name":"Name","signature":"func (ipc InPathCheck) Name() string","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Name returns label for individual InPathCheck. If not known, will return based on path.\nfunc (ipc InPathCheck) Name() string {\n\tif ipc.label != \"\" {\n\t\treturn ipc.label\n\t}\n\treturn fmt.Sprintf(\"FileExisting-%s\", strings.Replace(ipc.executable, \"/\", \"-\", -1))\n}","line":{"from":360,"to":366}} {"id":100001149,"name":"Check","signature":"func (ipc InPathCheck) Check() (warnings, errs []error)","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Check validates if the given executable is present in the path.\nfunc (ipc InPathCheck) Check() (warnings, errs []error) {\n\tklog.V(1).Infof(\"validating the presence of executable %s\", ipc.executable)\n\t_, err := ipc.exec.LookPath(ipc.executable)\n\tif err != nil {\n\t\tif ipc.mandatory {\n\t\t\t// Return as an error:\n\t\t\treturn nil, []error{errors.Errorf(\"%s not found in system path\", ipc.executable)}\n\t\t}\n\t\t// Return as a warning:\n\t\twarningMessage := fmt.Sprintf(\"%s not found in system path\", ipc.executable)\n\t\tif ipc.suggestion != \"\" {\n\t\t\twarningMessage += fmt.Sprintf(\"\\nSuggestion: %s\", ipc.suggestion)\n\t\t}\n\t\treturn []error{errors.New(warningMessage)}, nil\n\t}\n\treturn nil, nil\n}","line":{"from":368,"to":385}} {"id":100001150,"name":"Name","signature":"func (HostnameCheck) Name() string","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Name will return Hostname as name for HostnameCheck\nfunc (HostnameCheck) Name() string {\n\treturn \"Hostname\"\n}","line":{"from":393,"to":396}} {"id":100001151,"name":"Check","signature":"func (hc HostnameCheck) Check() (warnings, errorList []error)","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Check validates if hostname match dns sub domain regex.\n// Check hostname length and format\nfunc (hc HostnameCheck) Check() (warnings, errorList []error) {\n\tklog.V(1).Infoln(\"checking whether the given node name is valid and reachable using net.LookupHost\")\n\tfor _, msg := range validation.IsQualifiedName(hc.nodeName) {\n\t\twarnings = append(warnings, errors.Errorf(\"invalid node name format %q: %s\", hc.nodeName, msg))\n\t}\n\n\taddr, err := net.LookupHost(hc.nodeName)\n\tif addr == nil {\n\t\twarnings = append(warnings, errors.Errorf(\"hostname \\\"%s\\\" could not be reached\", hc.nodeName))\n\t}\n\tif err != nil {\n\t\twarnings = append(warnings, errors.Wrapf(err, \"hostname \\\"%s\\\"\", hc.nodeName))\n\t}\n\treturn warnings, errorList\n}","line":{"from":398,"to":414}} {"id":100001152,"name":"Name","signature":"func (hst HTTPProxyCheck) Name() string","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Name returns HTTPProxy as name for HTTPProxyCheck\nfunc (hst HTTPProxyCheck) Name() string {\n\treturn \"HTTPProxy\"\n}","line":{"from":423,"to":426}} {"id":100001153,"name":"Check","signature":"func (hst HTTPProxyCheck) Check() (warnings, errorList []error)","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Check validates http connectivity type, direct or via proxy.\nfunc (hst HTTPProxyCheck) Check() (warnings, errorList []error) {\n\tklog.V(1).Infoln(\"validating if the connectivity type is via proxy or direct\")\n\tu := \u0026url.URL{Scheme: hst.Proto, Host: hst.Host}\n\tif netutils.IsIPv6String(hst.Host) {\n\t\tu.Host = net.JoinHostPort(hst.Host, \"1234\")\n\t}\n\n\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\tif err != nil {\n\t\treturn nil, []error{err}\n\t}\n\n\tproxy, err := netutil.SetOldTransportDefaults(\u0026http.Transport{}).Proxy(req)\n\tif err != nil {\n\t\treturn nil, []error{err}\n\t}\n\tif proxy != nil {\n\t\treturn []error{errors.Errorf(\"Connection to %q uses proxy %q. If that is not intended, adjust your proxy settings\", u, proxy)}, nil\n\t}\n\treturn nil, nil\n}","line":{"from":428,"to":449}} {"id":100001154,"name":"Name","signature":"func (HTTPProxyCIDRCheck) Name() string","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Name will return HTTPProxyCIDR as name for HTTPProxyCIDRCheck\nfunc (HTTPProxyCIDRCheck) Name() string {\n\treturn \"HTTPProxyCIDR\"\n}","line":{"from":461,"to":464}} {"id":100001155,"name":"Check","signature":"func (subnet HTTPProxyCIDRCheck) Check() (warnings, errorList []error)","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Check validates http connectivity to first IP address in the CIDR.\n// If it is not directly connected and goes via proxy it will produce warning.\nfunc (subnet HTTPProxyCIDRCheck) Check() (warnings, errorList []error) {\n\tklog.V(1).Infoln(\"validating http connectivity to first IP address in the CIDR\")\n\tif len(subnet.CIDR) == 0 {\n\t\treturn nil, nil\n\t}\n\n\t_, cidr, err := netutils.ParseCIDRSloppy(subnet.CIDR)\n\tif err != nil {\n\t\treturn nil, []error{errors.Wrapf(err, \"error parsing CIDR %q\", subnet.CIDR)}\n\t}\n\n\ttestIP, err := netutils.GetIndexedIP(cidr, 1)\n\tif err != nil {\n\t\treturn nil, []error{errors.Wrapf(err, \"unable to get first IP address from the given CIDR (%s)\", cidr.String())}\n\t}\n\n\ttestIPstring := testIP.String()\n\tif len(testIP) == net.IPv6len {\n\t\ttestIPstring = fmt.Sprintf(\"[%s]:1234\", testIP)\n\t}\n\turl := fmt.Sprintf(\"%s://%s/\", subnet.Proto, testIPstring)\n\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, []error{err}\n\t}\n\n\t// Utilize same transport defaults as it will be used by API server\n\tproxy, err := netutil.SetOldTransportDefaults(\u0026http.Transport{}).Proxy(req)\n\tif err != nil {\n\t\treturn nil, []error{err}\n\t}\n\tif proxy != nil {\n\t\treturn []error{errors.Errorf(\"connection to %q uses proxy %q. This may lead to malfunctional cluster setup. Make sure that Pod and Services IP ranges specified correctly as exceptions in proxy configuration\", subnet.CIDR, proxy)}, nil\n\t}\n\treturn nil, nil\n}","line":{"from":466,"to":504}} {"id":100001156,"name":"Name","signature":"func (SystemVerificationCheck) Name() string","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Name will return SystemVerification as name for SystemVerificationCheck\nfunc (SystemVerificationCheck) Name() string {\n\treturn \"SystemVerification\"\n}","line":{"from":509,"to":512}} {"id":100001157,"name":"Check","signature":"func (sysver SystemVerificationCheck) Check() (warnings, errorList []error)","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Check runs all individual checks\nfunc (sysver SystemVerificationCheck) Check() (warnings, errorList []error) {\n\tklog.V(1).Infoln(\"running all checks\")\n\t// Create a buffered writer and choose a quite large value (1M) and suppose the output from the system verification test won't exceed the limit\n\t// Run the system verification check, but write to out buffered writer instead of stdout\n\tbufw := bufio.NewWriterSize(os.Stdout, 1*1024*1024)\n\treporter := \u0026system.StreamReporter{WriteStream: bufw}\n\n\tvar errs []error\n\tvar warns []error\n\t// All the common validators we'd like to run:\n\tvar validators = []system.Validator{\n\t\t\u0026system.KernelValidator{Reporter: reporter}}\n\n\tvalidators = addOSValidator(validators, reporter)\n\n\t// Run all validators\n\tfor _, v := range validators {\n\t\twarn, err := v.Validate(system.DefaultSysSpec)\n\t\tif err != nil {\n\t\t\terrs = append(errs, err...)\n\t\t}\n\t\tif warn != nil {\n\t\t\twarns = append(warns, warn...)\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\t// Only print the output from the system verification check if the check failed\n\t\tfmt.Println(\"[preflight] The system verification failed. Printing the output from the verification:\")\n\t\tbufw.Flush()\n\t\treturn warns, errs\n\t}\n\treturn warns, nil\n}","line":{"from":514,"to":548}} {"id":100001158,"name":"Name","signature":"func (KubernetesVersionCheck) Name() string","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Name will return KubernetesVersion as name for KubernetesVersionCheck\nfunc (KubernetesVersionCheck) Name() string {\n\treturn \"KubernetesVersion\"\n}","line":{"from":556,"to":559}} {"id":100001159,"name":"Check","signature":"func (kubever KubernetesVersionCheck) Check() (warnings, errorList []error)","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Check validates Kubernetes and kubeadm versions\nfunc (kubever KubernetesVersionCheck) Check() (warnings, errorList []error) {\n\tklog.V(1).Infoln(\"validating Kubernetes and kubeadm version\")\n\t// Skip this check for \"super-custom builds\", where apimachinery/the overall codebase version is not set.\n\tif strings.HasPrefix(kubever.KubeadmVersion, \"v0.0.0\") {\n\t\treturn nil, nil\n\t}\n\n\tkadmVersion, err := versionutil.ParseSemantic(kubever.KubeadmVersion)\n\tif err != nil {\n\t\treturn nil, []error{errors.Wrapf(err, \"couldn't parse kubeadm version %q\", kubever.KubeadmVersion)}\n\t}\n\n\tk8sVersion, err := versionutil.ParseSemantic(kubever.KubernetesVersion)\n\tif err != nil {\n\t\treturn nil, []error{errors.Wrapf(err, \"couldn't parse Kubernetes version %q\", kubever.KubernetesVersion)}\n\t}\n\n\t// Checks if k8sVersion greater or equal than the first unsupported versions by current version of kubeadm,\n\t// that is major.minor+1 (all patch and pre-releases versions included)\n\t// NB. in semver patches number is a numeric, while prerelease is a string where numeric identifiers always have lower precedence than non-numeric identifiers.\n\t// thus setting the value to x.y.0-0 we are defining the very first patch - prereleases within x.y minor release.\n\tfirstUnsupportedVersion := versionutil.MustParseSemantic(fmt.Sprintf(\"%d.%d.%s\", kadmVersion.Major(), kadmVersion.Minor()+1, \"0-0\"))\n\tif k8sVersion.AtLeast(firstUnsupportedVersion) {\n\t\treturn []error{errors.Errorf(\"Kubernetes version is greater than kubeadm version. Please consider to upgrade kubeadm. Kubernetes version: %s. Kubeadm version: %d.%d.x\", k8sVersion, kadmVersion.Components()[0], kadmVersion.Components()[1])}, nil\n\t}\n\n\treturn nil, nil\n}","line":{"from":561,"to":589}} {"id":100001160,"name":"Name","signature":"func (KubeletVersionCheck) Name() string","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Name will return KubeletVersion as name for KubeletVersionCheck\nfunc (KubeletVersionCheck) Name() string {\n\treturn \"KubeletVersion\"\n}","line":{"from":598,"to":601}} {"id":100001161,"name":"Check","signature":"func (kubever KubeletVersionCheck) Check() (warnings, errorList []error)","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Check validates kubelet version. It should be not less than minimal supported version\nfunc (kubever KubeletVersionCheck) Check() (warnings, errorList []error) {\n\tklog.V(1).Infoln(\"validating kubelet version\")\n\tkubeletVersion, err := GetKubeletVersion(kubever.exec)\n\tif err != nil {\n\t\treturn nil, []error{errors.Wrap(err, \"couldn't get kubelet version\")}\n\t}\n\tif kubever.minKubeletVersion == nil {\n\t\tkubever.minKubeletVersion = kubeadmconstants.MinimumKubeletVersion\n\t}\n\tif kubeletVersion.LessThan(kubever.minKubeletVersion) {\n\t\treturn nil, []error{errors.Errorf(\"Kubelet version %q is lower than kubeadm can support. Please upgrade kubelet\", kubeletVersion)}\n\t}\n\n\tif kubever.KubernetesVersion != \"\" {\n\t\tk8sVersion, err := versionutil.ParseSemantic(kubever.KubernetesVersion)\n\t\tif err != nil {\n\t\t\treturn nil, []error{errors.Wrapf(err, \"couldn't parse Kubernetes version %q\", kubever.KubernetesVersion)}\n\t\t}\n\t\tif kubeletVersion.Major() \u003e k8sVersion.Major() || kubeletVersion.Minor() \u003e k8sVersion.Minor() {\n\t\t\treturn nil, []error{errors.Errorf(\"the kubelet version is higher than the control plane version. This is not a supported version skew and may lead to a malfunctional cluster. Kubelet version: %q Control plane version: %q\", kubeletVersion, k8sVersion)}\n\t\t}\n\t}\n\treturn nil, nil\n}","line":{"from":603,"to":627}} {"id":100001162,"name":"Name","signature":"func (SwapCheck) Name() string","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Name will return Swap as name for SwapCheck\nfunc (SwapCheck) Name() string {\n\treturn \"Swap\"\n}","line":{"from":632,"to":635}} {"id":100001163,"name":"Check","signature":"func (swc SwapCheck) Check() (warnings, errorList []error)","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Check validates whether swap is enabled or not\nfunc (swc SwapCheck) Check() (warnings, errorList []error) {\n\tklog.V(1).Infoln(\"validating whether swap is enabled or not\")\n\tf, err := os.Open(\"/proc/swaps\")\n\tif err != nil {\n\t\t// /proc/swaps not available, thus no reasons to warn\n\t\treturn nil, nil\n\t}\n\tdefer f.Close()\n\tvar buf []string\n\tscanner := bufio.NewScanner(f)\n\tfor scanner.Scan() {\n\t\tbuf = append(buf, scanner.Text())\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\treturn []error{errors.Wrap(err, \"error parsing /proc/swaps\")}, nil\n\t}\n\n\tif len(buf) \u003e 1 {\n\t\treturn []error{errors.New(\"swap is enabled; production deployments should disable swap unless testing the NodeSwap feature gate of the kubelet\")}, nil\n\t}\n\n\treturn nil, nil\n}","line":{"from":637,"to":660}} {"id":100001164,"name":"Name","signature":"func (ExternalEtcdVersionCheck) Name() string","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Name will return ExternalEtcdVersion as name for ExternalEtcdVersionCheck\nfunc (ExternalEtcdVersionCheck) Name() string {\n\treturn \"ExternalEtcdVersion\"\n}","line":{"from":672,"to":675}} {"id":100001165,"name":"Check","signature":"func (evc ExternalEtcdVersionCheck) Check() (warnings, errorList []error)","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Check validates external etcd version\n// TODO: Use the official etcd Golang client for this instead?\nfunc (evc ExternalEtcdVersionCheck) Check() (warnings, errorList []error) {\n\tklog.V(1).Infoln(\"validating the external etcd version\")\n\n\t// Return quickly if the user isn't using external etcd\n\tif evc.Etcd.External.Endpoints == nil {\n\t\treturn nil, nil\n\t}\n\n\tvar config *tls.Config\n\tvar err error\n\tif config, err = evc.configRootCAs(config); err != nil {\n\t\terrorList = append(errorList, err)\n\t\treturn nil, errorList\n\t}\n\tif config, err = evc.configCertAndKey(config); err != nil {\n\t\terrorList = append(errorList, err)\n\t\treturn nil, errorList\n\t}\n\n\tclient := evc.getHTTPClient(config)\n\tfor _, endpoint := range evc.Etcd.External.Endpoints {\n\t\tif _, err := url.Parse(endpoint); err != nil {\n\t\t\terrorList = append(errorList, errors.Wrapf(err, \"failed to parse external etcd endpoint %s\", endpoint))\n\t\t\tcontinue\n\t\t}\n\t\tresp := etcdVersionResponse{}\n\t\tvar err error\n\t\tversionURL := fmt.Sprintf(\"%s/%s\", endpoint, \"version\")\n\t\tif tmpVersionURL, err := normalizeURLString(versionURL); err != nil {\n\t\t\terrorList = append(errorList, errors.Wrapf(err, \"failed to normalize external etcd version url %s\", versionURL))\n\t\t\tcontinue\n\t\t} else {\n\t\t\tversionURL = tmpVersionURL\n\t\t}\n\t\tif err = getEtcdVersionResponse(client, versionURL, \u0026resp); err != nil {\n\t\t\terrorList = append(errorList, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tetcdVersion, err := versionutil.ParseSemantic(resp.Etcdserver)\n\t\tif err != nil {\n\t\t\terrorList = append(errorList, errors.Wrapf(err, \"couldn't parse external etcd version %q\", resp.Etcdserver))\n\t\t\tcontinue\n\t\t}\n\t\tif etcdVersion.LessThan(minExternalEtcdVersion) {\n\t\t\terrorList = append(errorList, errors.Errorf(\"this version of kubeadm only supports external etcd version \u003e= %s. Current version: %s\", kubeadmconstants.MinExternalEtcdVersion, resp.Etcdserver))\n\t\t\tcontinue\n\t\t}\n\t}\n\n\treturn nil, errorList\n}","line":{"from":677,"to":730}} {"id":100001166,"name":"configRootCAs","signature":"func (evc ExternalEtcdVersionCheck) configRootCAs(config *tls.Config) (*tls.Config, error)","file":"cmd/kubeadm/app/preflight/checks.go","code":"// configRootCAs configures and returns a reference to tls.Config instance if CAFile is provided\nfunc (evc ExternalEtcdVersionCheck) configRootCAs(config *tls.Config) (*tls.Config, error) {\n\tvar CACertPool *x509.CertPool\n\tif evc.Etcd.External.CAFile != \"\" {\n\t\tCACert, err := os.ReadFile(evc.Etcd.External.CAFile)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"couldn't load external etcd's server certificate %s\", evc.Etcd.External.CAFile)\n\t\t}\n\t\tCACertPool = x509.NewCertPool()\n\t\tCACertPool.AppendCertsFromPEM(CACert)\n\t}\n\tif CACertPool != nil {\n\t\tif config == nil {\n\t\t\tconfig = \u0026tls.Config{}\n\t\t}\n\t\tconfig.RootCAs = CACertPool\n\t}\n\treturn config, nil\n}","line":{"from":732,"to":750}} {"id":100001167,"name":"configCertAndKey","signature":"func (evc ExternalEtcdVersionCheck) configCertAndKey(config *tls.Config) (*tls.Config, error)","file":"cmd/kubeadm/app/preflight/checks.go","code":"// configCertAndKey configures and returns a reference to tls.Config instance if CertFile and KeyFile pair is provided\nfunc (evc ExternalEtcdVersionCheck) configCertAndKey(config *tls.Config) (*tls.Config, error) {\n\tvar cert tls.Certificate\n\tif evc.Etcd.External.CertFile != \"\" \u0026\u0026 evc.Etcd.External.KeyFile != \"\" {\n\t\tvar err error\n\t\tcert, err = tls.LoadX509KeyPair(evc.Etcd.External.CertFile, evc.Etcd.External.KeyFile)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"couldn't load external etcd's certificate and key pair %s, %s\", evc.Etcd.External.CertFile, evc.Etcd.External.KeyFile)\n\t\t}\n\t\tif config == nil {\n\t\t\tconfig = \u0026tls.Config{}\n\t\t}\n\t\tconfig.Certificates = []tls.Certificate{cert}\n\t}\n\treturn config, nil\n}","line":{"from":752,"to":767}} {"id":100001168,"name":"getHTTPClient","signature":"func (evc ExternalEtcdVersionCheck) getHTTPClient(config *tls.Config) *http.Client","file":"cmd/kubeadm/app/preflight/checks.go","code":"func (evc ExternalEtcdVersionCheck) getHTTPClient(config *tls.Config) *http.Client {\n\tif config != nil {\n\t\ttransport := netutil.SetOldTransportDefaults(\u0026http.Transport{\n\t\t\tTLSClientConfig: config,\n\t\t})\n\t\treturn \u0026http.Client{\n\t\t\tTransport: transport,\n\t\t\tTimeout: externalEtcdRequestTimeout,\n\t\t}\n\t}\n\treturn \u0026http.Client{Timeout: externalEtcdRequestTimeout, Transport: netutil.SetOldTransportDefaults(\u0026http.Transport{})}\n}","line":{"from":769,"to":780}} {"id":100001169,"name":"getEtcdVersionResponse","signature":"func getEtcdVersionResponse(client *http.Client, url string, target interface{}) error","file":"cmd/kubeadm/app/preflight/checks.go","code":"func getEtcdVersionResponse(client *http.Client, url string, target interface{}) error {\n\tloopCount := externalEtcdRequestRetries + 1\n\tvar err error\n\tvar stopRetry bool\n\tfor loopCount \u003e 0 {\n\t\tif loopCount \u003c= externalEtcdRequestRetries {\n\t\t\ttime.Sleep(externalEtcdRequestInterval)\n\t\t}\n\t\tstopRetry, err = func() (stopRetry bool, err error) {\n\t\t\tr, err := client.Get(url)\n\t\t\tif err != nil {\n\t\t\t\tloopCount--\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tdefer r.Body.Close()\n\n\t\t\tif r.StatusCode \u003e= 500 \u0026\u0026 r.StatusCode \u003c= 599 {\n\t\t\t\tloopCount--\n\t\t\t\treturn false, errors.Errorf(\"server responded with non-successful status: %s\", r.Status)\n\t\t\t}\n\t\t\treturn true, json.NewDecoder(r.Body).Decode(target)\n\n\t\t}()\n\t\tif stopRetry {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn err\n}","line":{"from":782,"to":810}} {"id":100001170,"name":"Name","signature":"func (ImagePullCheck) Name() string","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Name returns the label for ImagePullCheck\nfunc (ImagePullCheck) Name() string {\n\treturn \"ImagePull\"\n}","line":{"from":820,"to":823}} {"id":100001171,"name":"Check","signature":"func (ipc ImagePullCheck) Check() (warnings, errorList []error)","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Check pulls images required by kubeadm. This is a mutating check\nfunc (ipc ImagePullCheck) Check() (warnings, errorList []error) {\n\tpolicy := ipc.imagePullPolicy\n\tklog.V(1).Infof(\"using image pull policy: %s\", policy)\n\tfor _, image := range ipc.imageList {\n\t\tif image == ipc.sandboxImage {\n\t\t\tcriSandboxImage, err := ipc.runtime.SandboxImage()\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"failed to detect the sandbox image for local container runtime, %v\", err)\n\t\t\t} else if criSandboxImage != ipc.sandboxImage {\n\t\t\t\tklog.Warningf(\"detected that the sandbox image %q of the container runtime is inconsistent with that used by kubeadm. It is recommended that using %q as the CRI sandbox image.\",\n\t\t\t\t\tcriSandboxImage, ipc.sandboxImage)\n\t\t\t}\n\t\t}\n\t\tswitch policy {\n\t\tcase v1.PullNever:\n\t\t\tklog.V(1).Infof(\"skipping pull of image: %s\", image)\n\t\t\tcontinue\n\t\tcase v1.PullIfNotPresent:\n\t\t\tret, err := ipc.runtime.ImageExists(image)\n\t\t\tif ret \u0026\u0026 err == nil {\n\t\t\t\tklog.V(1).Infof(\"image exists: %s\", image)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terrorList = append(errorList, errors.Wrapf(err, \"failed to check if image %s exists\", image))\n\t\t\t}\n\t\t\tfallthrough // Proceed with pulling the image if it does not exist\n\t\tcase v1.PullAlways:\n\t\t\tklog.V(1).Infof(\"pulling: %s\", image)\n\t\t\tif err := ipc.runtime.PullImage(image); err != nil {\n\t\t\t\terrorList = append(errorList, errors.Wrapf(err, \"failed to pull image %s\", image))\n\t\t\t}\n\t\tdefault:\n\t\t\t// If the policy is unknown return early with an error\n\t\t\terrorList = append(errorList, errors.Errorf(\"unsupported pull policy %q\", policy))\n\t\t\treturn warnings, errorList\n\t\t}\n\t}\n\treturn warnings, errorList\n}","line":{"from":825,"to":865}} {"id":100001172,"name":"Name","signature":"func (NumCPUCheck) Name() string","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Name returns the label for NumCPUCheck\nfunc (NumCPUCheck) Name() string {\n\treturn \"NumCPU\"\n}","line":{"from":872,"to":875}} {"id":100001173,"name":"Check","signature":"func (ncc NumCPUCheck) Check() (warnings, errorList []error)","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Check number of CPUs required by kubeadm\nfunc (ncc NumCPUCheck) Check() (warnings, errorList []error) {\n\tnumCPU := runtime.NumCPU()\n\tif numCPU \u003c ncc.NumCPU {\n\t\terrorList = append(errorList, errors.Errorf(\"the number of available CPUs %d is less than the required %d\", numCPU, ncc.NumCPU))\n\t}\n\treturn warnings, errorList\n}","line":{"from":877,"to":884}} {"id":100001174,"name":"Name","signature":"func (MemCheck) Name() string","file":"cmd/kubeadm/app/preflight/checks.go","code":"// Name returns the label for memory\nfunc (MemCheck) Name() string {\n\treturn \"Mem\"\n}","line":{"from":891,"to":894}} {"id":100001175,"name":"InitNodeChecks","signature":"func InitNodeChecks(execer utilsexec.Interface, cfg *kubeadmapi.InitConfiguration, ignorePreflightErrors sets.Set[string], isSecondaryControlPlane bool, downloadCerts bool) ([]Checker, error)","file":"cmd/kubeadm/app/preflight/checks.go","code":"func InitNodeChecks(execer utilsexec.Interface, cfg *kubeadmapi.InitConfiguration, ignorePreflightErrors sets.Set[string], isSecondaryControlPlane bool, downloadCerts bool) ([]Checker, error) {\n\tif !isSecondaryControlPlane {\n\t\t// First, check if we're root separately from the other preflight checks and fail fast\n\t\tif err := RunRootCheckOnly(ignorePreflightErrors); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tmanifestsDir := filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.ManifestsSubDirName)\n\tchecks := []Checker{\n\t\tNumCPUCheck{NumCPU: kubeadmconstants.ControlPlaneNumCPU},\n\t\t// Linux only\n\t\t// TODO: support other OS, if control-plane is supported on it.\n\t\tMemCheck{Mem: kubeadmconstants.ControlPlaneMem},\n\t\tKubernetesVersionCheck{KubernetesVersion: cfg.KubernetesVersion, KubeadmVersion: kubeadmversion.Get().GitVersion},\n\t\tFirewalldCheck{ports: []int{int(cfg.LocalAPIEndpoint.BindPort), kubeadmconstants.KubeletPort}},\n\t\tPortOpenCheck{port: int(cfg.LocalAPIEndpoint.BindPort)},\n\t\tPortOpenCheck{port: kubeadmconstants.KubeSchedulerPort},\n\t\tPortOpenCheck{port: kubeadmconstants.KubeControllerManagerPort},\n\t\tFileAvailableCheck{Path: kubeadmconstants.GetStaticPodFilepath(kubeadmconstants.KubeAPIServer, manifestsDir)},\n\t\tFileAvailableCheck{Path: kubeadmconstants.GetStaticPodFilepath(kubeadmconstants.KubeControllerManager, manifestsDir)},\n\t\tFileAvailableCheck{Path: kubeadmconstants.GetStaticPodFilepath(kubeadmconstants.KubeScheduler, manifestsDir)},\n\t\tFileAvailableCheck{Path: kubeadmconstants.GetStaticPodFilepath(kubeadmconstants.Etcd, manifestsDir)},\n\t\tHTTPProxyCheck{Proto: \"https\", Host: cfg.LocalAPIEndpoint.AdvertiseAddress},\n\t}\n\n\t// File content check for IPV4 and IPV6 are needed if it is:\n\t// (dual stack) `--service-cidr` or `--pod-network-cidr` is set with an IPV4 and IPV6 CIDR, `--apiserver-advertise-address` is optional as it can be auto detected.\n\t// (single stack) which is decided by the `--apiserver-advertise-address`.\n\t// Note that for the case of dual stack, user might only give IPV6 CIDR for `--service-cidr` and leave the `--apiserver-advertise-address` a default value which will be\n\t// auto detected and properly bound to an IPV4 address, this will make the cluster non-functional eventually. The case like this should be avoided by the validation instead,\n\t// i.e. We don't care whether the input values for those parameters are set correctly here but if it's an IPV4 scoped CIDR or address we will add the file content check for IPV4,\n\t// as does the IPV6.\n\tIPV4Check := false\n\tIPV6Check := false\n\tcidrs := strings.Split(cfg.Networking.ServiceSubnet, \",\")\n\tfor _, cidr := range cidrs {\n\t\tchecks = append(checks, HTTPProxyCIDRCheck{Proto: \"https\", CIDR: cidr})\n\t\tif !IPV4Check \u0026\u0026 netutils.IsIPv4CIDRString(cidr) {\n\t\t\tIPV4Check = true\n\t\t}\n\t\tif !IPV6Check \u0026\u0026 netutils.IsIPv6CIDRString(cidr) {\n\t\t\tIPV6Check = true\n\t\t}\n\n\t}\n\tcidrs = strings.Split(cfg.Networking.PodSubnet, \",\")\n\tfor _, cidr := range cidrs {\n\t\tchecks = append(checks, HTTPProxyCIDRCheck{Proto: \"https\", CIDR: cidr})\n\t\tif !IPV4Check \u0026\u0026 netutils.IsIPv4CIDRString(cidr) {\n\t\t\tIPV4Check = true\n\t\t}\n\t\tif !IPV6Check \u0026\u0026 netutils.IsIPv6CIDRString(cidr) {\n\t\t\tIPV6Check = true\n\t\t}\n\t}\n\n\tif !isSecondaryControlPlane {\n\t\tchecks = addCommonChecks(execer, cfg.KubernetesVersion, \u0026cfg.NodeRegistration, checks)\n\n\t\t// Check if Bridge-netfilter and IPv6 relevant flags are set\n\t\tif ip := netutils.ParseIPSloppy(cfg.LocalAPIEndpoint.AdvertiseAddress); ip != nil {\n\t\t\tif !IPV4Check \u0026\u0026 netutils.IsIPv4(ip) {\n\t\t\t\tIPV4Check = true\n\t\t\t}\n\t\t\tif !IPV6Check \u0026\u0026 netutils.IsIPv6(ip) {\n\t\t\t\tIPV6Check = true\n\t\t\t}\n\t\t}\n\n\t\tif IPV4Check {\n\t\t\tchecks = addIPv4Checks(checks)\n\t\t}\n\t\tif IPV6Check {\n\t\t\tchecks = addIPv6Checks(checks)\n\t\t}\n\n\t\t// if using an external etcd\n\t\tif cfg.Etcd.External != nil {\n\t\t\t// Check external etcd version before creating the cluster\n\t\t\tchecks = append(checks, ExternalEtcdVersionCheck{Etcd: cfg.Etcd})\n\t\t}\n\t}\n\n\tif cfg.Etcd.Local != nil {\n\t\t// Only do etcd related checks when required to install a local etcd\n\t\tchecks = append(checks,\n\t\t\tPortOpenCheck{port: kubeadmconstants.EtcdListenClientPort},\n\t\t\tPortOpenCheck{port: kubeadmconstants.EtcdListenPeerPort},\n\t\t\tDirAvailableCheck{Path: cfg.Etcd.Local.DataDir},\n\t\t)\n\t}\n\n\tif cfg.Etcd.External != nil \u0026\u0026 !(isSecondaryControlPlane \u0026\u0026 downloadCerts) {\n\t\t// Only check etcd certificates when using an external etcd and not joining with automatic download of certs\n\t\tif cfg.Etcd.External.CAFile != \"\" {\n\t\t\tchecks = append(checks, FileExistingCheck{Path: cfg.Etcd.External.CAFile, Label: \"ExternalEtcdClientCertificates\"})\n\t\t}\n\t\tif cfg.Etcd.External.CertFile != \"\" {\n\t\t\tchecks = append(checks, FileExistingCheck{Path: cfg.Etcd.External.CertFile, Label: \"ExternalEtcdClientCertificates\"})\n\t\t}\n\t\tif cfg.Etcd.External.KeyFile != \"\" {\n\t\t\tchecks = append(checks, FileExistingCheck{Path: cfg.Etcd.External.KeyFile, Label: \"ExternalEtcdClientCertificates\"})\n\t\t}\n\t}\n\treturn checks, nil\n}","line":{"from":896,"to":1002}} {"id":100001176,"name":"RunInitNodeChecks","signature":"func RunInitNodeChecks(execer utilsexec.Interface, cfg *kubeadmapi.InitConfiguration, ignorePreflightErrors sets.Set[string], isSecondaryControlPlane bool, downloadCerts bool) error","file":"cmd/kubeadm/app/preflight/checks.go","code":"// RunInitNodeChecks executes all individual, applicable to control-plane node checks.\n// The boolean flag 'isSecondaryControlPlane' controls whether we are running checks in a --join-control-plane scenario.\n// The boolean flag 'downloadCerts' controls whether we should skip checks on certificates because we are downloading them.\n// If the flag is set to true we should skip checks already executed by RunJoinNodeChecks.\nfunc RunInitNodeChecks(execer utilsexec.Interface, cfg *kubeadmapi.InitConfiguration, ignorePreflightErrors sets.Set[string], isSecondaryControlPlane bool, downloadCerts bool) error {\n\tchecks, err := InitNodeChecks(execer, cfg, ignorePreflightErrors, isSecondaryControlPlane, downloadCerts)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn RunChecks(checks, os.Stderr, ignorePreflightErrors)\n}","line":{"from":1004,"to":1014}} {"id":100001177,"name":"JoinNodeChecks","signature":"func JoinNodeChecks(execer utilsexec.Interface, cfg *kubeadmapi.JoinConfiguration, ignorePreflightErrors sets.Set[string]) ([]Checker, error)","file":"cmd/kubeadm/app/preflight/checks.go","code":"func JoinNodeChecks(execer utilsexec.Interface, cfg *kubeadmapi.JoinConfiguration, ignorePreflightErrors sets.Set[string]) ([]Checker, error) {\n\t// First, check if we're root separately from the other preflight checks and fail fast\n\tif err := RunRootCheckOnly(ignorePreflightErrors); err != nil {\n\t\treturn nil, err\n\t}\n\n\tchecks := []Checker{\n\t\tFileAvailableCheck{Path: filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.KubeletKubeConfigFileName)},\n\t\tFileAvailableCheck{Path: filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.KubeletBootstrapKubeConfigFileName)},\n\t}\n\tchecks = addCommonChecks(execer, \"\", \u0026cfg.NodeRegistration, checks)\n\tif cfg.ControlPlane == nil {\n\t\tchecks = append(checks, FileAvailableCheck{Path: cfg.CACertPath})\n\t}\n\n\tif cfg.Discovery.BootstrapToken != nil {\n\t\tipstr, _, err := net.SplitHostPort(cfg.Discovery.BootstrapToken.APIServerEndpoint)\n\t\tif err == nil {\n\t\t\tchecks = append(checks,\n\t\t\t\tHTTPProxyCheck{Proto: \"https\", Host: ipstr},\n\t\t\t)\n\t\t\tif ip := netutils.ParseIPSloppy(ipstr); ip != nil {\n\t\t\t\tif netutils.IsIPv4(ip) {\n\t\t\t\t\tchecks = addIPv4Checks(checks)\n\t\t\t\t}\n\t\t\t\tif netutils.IsIPv6(ip) {\n\t\t\t\t\tchecks = addIPv6Checks(checks)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn checks, nil\n}","line":{"from":1016,"to":1048}} {"id":100001178,"name":"RunJoinNodeChecks","signature":"func RunJoinNodeChecks(execer utilsexec.Interface, cfg *kubeadmapi.JoinConfiguration, ignorePreflightErrors sets.Set[string]) error","file":"cmd/kubeadm/app/preflight/checks.go","code":"// RunJoinNodeChecks executes all individual, applicable to node checks.\nfunc RunJoinNodeChecks(execer utilsexec.Interface, cfg *kubeadmapi.JoinConfiguration, ignorePreflightErrors sets.Set[string]) error {\n\tchecks, err := JoinNodeChecks(execer, cfg, ignorePreflightErrors)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn RunChecks(checks, os.Stderr, ignorePreflightErrors)\n}","line":{"from":1050,"to":1057}} {"id":100001179,"name":"addCommonChecks","signature":"func addCommonChecks(execer utilsexec.Interface, k8sVersion string, nodeReg *kubeadmapi.NodeRegistrationOptions, checks []Checker) []Checker","file":"cmd/kubeadm/app/preflight/checks.go","code":"// addCommonChecks is a helper function to duplicate checks that are common between both the\n// kubeadm init and join commands\nfunc addCommonChecks(execer utilsexec.Interface, k8sVersion string, nodeReg *kubeadmapi.NodeRegistrationOptions, checks []Checker) []Checker {\n\tcontainerRuntime, err := utilruntime.NewContainerRuntime(execer, nodeReg.CRISocket)\n\tif err != nil {\n\t\tklog.Warningf(\"[preflight] WARNING: Couldn't create the interface used for talking to the container runtime: %v\\n\", err)\n\t} else {\n\t\tchecks = append(checks, ContainerRuntimeCheck{runtime: containerRuntime})\n\t}\n\n\t// non-windows checks\n\tchecks = addSwapCheck(checks)\n\tchecks = addExecChecks(checks, execer)\n\tchecks = append(checks,\n\t\tSystemVerificationCheck{},\n\t\tHostnameCheck{nodeName: nodeReg.Name},\n\t\tKubeletVersionCheck{KubernetesVersion: k8sVersion, exec: execer},\n\t\tServiceCheck{Service: \"kubelet\", CheckIfActive: false},\n\t\tPortOpenCheck{port: kubeadmconstants.KubeletPort})\n\treturn checks\n}","line":{"from":1059,"to":1079}} {"id":100001180,"name":"RunRootCheckOnly","signature":"func RunRootCheckOnly(ignorePreflightErrors sets.Set[string]) error","file":"cmd/kubeadm/app/preflight/checks.go","code":"// RunRootCheckOnly initializes checks slice of structs and call RunChecks\nfunc RunRootCheckOnly(ignorePreflightErrors sets.Set[string]) error {\n\tchecks := []Checker{\n\t\tIsPrivilegedUserCheck{},\n\t}\n\n\treturn RunChecks(checks, os.Stderr, ignorePreflightErrors)\n}","line":{"from":1081,"to":1088}} {"id":100001181,"name":"RunPullImagesCheck","signature":"func RunPullImagesCheck(execer utilsexec.Interface, cfg *kubeadmapi.InitConfiguration, ignorePreflightErrors sets.Set[string]) error","file":"cmd/kubeadm/app/preflight/checks.go","code":"// RunPullImagesCheck will pull images kubeadm needs if they are not found on the system\nfunc RunPullImagesCheck(execer utilsexec.Interface, cfg *kubeadmapi.InitConfiguration, ignorePreflightErrors sets.Set[string]) error {\n\tcontainerRuntime, err := utilruntime.NewContainerRuntime(utilsexec.New(), cfg.NodeRegistration.CRISocket)\n\tif err != nil {\n\t\treturn \u0026Error{Msg: err.Error()}\n\t}\n\n\tchecks := []Checker{\n\t\tImagePullCheck{\n\t\t\truntime: containerRuntime,\n\t\t\timageList: images.GetControlPlaneImages(\u0026cfg.ClusterConfiguration),\n\t\t\tsandboxImage: images.GetPauseImage(\u0026cfg.ClusterConfiguration),\n\t\t\timagePullPolicy: cfg.NodeRegistration.ImagePullPolicy,\n\t\t},\n\t}\n\treturn RunChecks(checks, os.Stderr, ignorePreflightErrors)\n}","line":{"from":1090,"to":1106}} {"id":100001182,"name":"RunChecks","signature":"func RunChecks(checks []Checker, ww io.Writer, ignorePreflightErrors sets.Set[string]) error","file":"cmd/kubeadm/app/preflight/checks.go","code":"// RunChecks runs each check, displays it's warnings/errors, and once all\n// are processed will exit if any errors occurred.\nfunc RunChecks(checks []Checker, ww io.Writer, ignorePreflightErrors sets.Set[string]) error {\n\tvar errsBuffer bytes.Buffer\n\n\tfor _, c := range checks {\n\t\tname := c.Name()\n\t\twarnings, errs := c.Check()\n\n\t\tif setHasItemOrAll(ignorePreflightErrors, name) {\n\t\t\t// Decrease severity of errors to warnings for this check\n\t\t\twarnings = append(warnings, errs...)\n\t\t\terrs = []error{}\n\t\t}\n\n\t\tfor _, w := range warnings {\n\t\t\tio.WriteString(ww, fmt.Sprintf(\"\\t[WARNING %s]: %v\\n\", name, w))\n\t\t}\n\t\tfor _, i := range errs {\n\t\t\terrsBuffer.WriteString(fmt.Sprintf(\"\\t[ERROR %s]: %v\\n\", name, i.Error()))\n\t\t}\n\t}\n\tif errsBuffer.Len() \u003e 0 {\n\t\treturn \u0026Error{Msg: errsBuffer.String()}\n\t}\n\treturn nil\n}","line":{"from":1108,"to":1134}} {"id":100001183,"name":"setHasItemOrAll","signature":"func setHasItemOrAll(s sets.Set[string], item string) bool","file":"cmd/kubeadm/app/preflight/checks.go","code":"// setHasItemOrAll is helper function that return true if item is present in the set (case insensitive) or special key 'all' is present\nfunc setHasItemOrAll(s sets.Set[string], item string) bool {\n\tif s.Has(\"all\") || s.Has(strings.ToLower(item)) {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":1136,"to":1142}} {"id":100001184,"name":"normalizeURLString","signature":"func normalizeURLString(s string) (string, error)","file":"cmd/kubeadm/app/preflight/checks.go","code":"// normalizeURLString returns the normalized string, or an error if it can't be parsed into an URL object.\n// It takes an URL string as input.\nfunc normalizeURLString(s string) (string, error) {\n\tu, err := url.Parse(s)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif len(u.Path) \u003e 0 {\n\t\tu.Path = strings.ReplaceAll(u.Path, \"//\", \"/\")\n\t}\n\treturn u.String(), nil\n}","line":{"from":1144,"to":1155}} {"id":100001185,"name":"Check","signature":"func (mc MemCheck) Check() (warnings, errorList []error)","file":"cmd/kubeadm/app/preflight/checks_darwin.go","code":"// Check number of memory required by kubeadm\n// No-op for Darwin (MacOS).\nfunc (mc MemCheck) Check() (warnings, errorList []error) {\n\treturn nil, nil\n}","line":{"from":24,"to":28}} {"id":100001186,"name":"Check","signature":"func (mc MemCheck) Check() (warnings, errorList []error)","file":"cmd/kubeadm/app/preflight/checks_linux.go","code":"// Check number of memory required by kubeadm\nfunc (mc MemCheck) Check() (warnings, errorList []error) {\n\tinfo := syscall.Sysinfo_t{}\n\terr := syscall.Sysinfo(\u0026info)\n\tif err != nil {\n\t\terrorList = append(errorList, errors.Wrapf(err, \"failed to get system info\"))\n\t}\n\n\t// Totalram holds the total usable memory. Unit holds the size of a memory unit in bytes. Multiply them and convert to MB\n\tactual := uint64(info.Totalram) * uint64(info.Unit) / 1024 / 1024\n\tif actual \u003c mc.Mem {\n\t\terrorList = append(errorList, errors.Errorf(\"the system RAM (%d MB) is less than the minimum %d MB\", actual, mc.Mem))\n\t}\n\treturn warnings, errorList\n}","line":{"from":31,"to":45}} {"id":100001187,"name":"addOSValidator","signature":"func addOSValidator(validators []system.Validator, reporter *system.StreamReporter) []system.Validator","file":"cmd/kubeadm/app/preflight/checks_linux.go","code":"// addOSValidator adds a new OSValidator\nfunc addOSValidator(validators []system.Validator, reporter *system.StreamReporter) []system.Validator {\n\tvalidators = append(validators, \u0026system.OSValidator{Reporter: reporter}, \u0026system.CgroupsValidator{Reporter: reporter})\n\treturn validators\n}","line":{"from":47,"to":51}} {"id":100001188,"name":"addIPv6Checks","signature":"func addIPv6Checks(checks []Checker) []Checker","file":"cmd/kubeadm/app/preflight/checks_linux.go","code":"// addIPv6Checks adds IPv6 related bridgenf and forwarding checks\nfunc addIPv6Checks(checks []Checker) []Checker {\n\tchecks = append(checks,\n\t\tFileContentCheck{Path: bridgenf6, Content: []byte{'1'}},\n\t\tFileContentCheck{Path: ipv6DefaultForwarding, Content: []byte{'1'}},\n\t)\n\treturn checks\n}","line":{"from":53,"to":60}} {"id":100001189,"name":"addIPv4Checks","signature":"func addIPv4Checks(checks []Checker) []Checker","file":"cmd/kubeadm/app/preflight/checks_linux.go","code":"// addIPv4Checks adds IPv4 related bridgenf and forwarding checks\nfunc addIPv4Checks(checks []Checker) []Checker {\n\tchecks = append(checks,\n\t\tFileContentCheck{Path: bridgenf, Content: []byte{'1'}},\n\t\tFileContentCheck{Path: ipv4Forward, Content: []byte{'1'}})\n\treturn checks\n}","line":{"from":62,"to":68}} {"id":100001190,"name":"addSwapCheck","signature":"func addSwapCheck(checks []Checker) []Checker","file":"cmd/kubeadm/app/preflight/checks_linux.go","code":"// addSwapCheck adds a swap check\nfunc addSwapCheck(checks []Checker) []Checker {\n\tchecks = append(checks, SwapCheck{})\n\treturn checks\n}","line":{"from":70,"to":74}} {"id":100001191,"name":"addExecChecks","signature":"func addExecChecks(checks []Checker, execer utilsexec.Interface) []Checker","file":"cmd/kubeadm/app/preflight/checks_linux.go","code":"// addExecChecks adds checks that verify if certain binaries are in PATH\nfunc addExecChecks(checks []Checker, execer utilsexec.Interface) []Checker {\n\tchecks = append(checks,\n\t\tInPathCheck{executable: \"crictl\", mandatory: true, exec: execer},\n\t\tInPathCheck{executable: \"conntrack\", mandatory: true, exec: execer},\n\t\tInPathCheck{executable: \"ip\", mandatory: true, exec: execer},\n\t\tInPathCheck{executable: \"iptables\", mandatory: true, exec: execer},\n\t\tInPathCheck{executable: \"mount\", mandatory: true, exec: execer},\n\t\tInPathCheck{executable: \"nsenter\", mandatory: true, exec: execer},\n\t\tInPathCheck{executable: \"ebtables\", mandatory: false, exec: execer},\n\t\tInPathCheck{executable: \"ethtool\", mandatory: false, exec: execer},\n\t\tInPathCheck{executable: \"socat\", mandatory: false, exec: execer},\n\t\tInPathCheck{executable: \"tc\", mandatory: false, exec: execer},\n\t\tInPathCheck{executable: \"touch\", mandatory: false, exec: execer})\n\treturn checks\n}","line":{"from":76,"to":91}} {"id":100001192,"name":"addOSValidator","signature":"func addOSValidator(validators []system.Validator, _ *system.StreamReporter) []system.Validator","file":"cmd/kubeadm/app/preflight/checks_other.go","code":"// addOSValidator adds a new OSValidator\n// No-op for Darwin (MacOS), Windows.\nfunc addOSValidator(validators []system.Validator, _ *system.StreamReporter) []system.Validator {\n\treturn validators\n}","line":{"from":27,"to":31}} {"id":100001193,"name":"addIPv6Checks","signature":"func addIPv6Checks(checks []Checker) []Checker","file":"cmd/kubeadm/app/preflight/checks_other.go","code":"// addIPv6Checks adds IPv6 related bridgenf and forwarding checks\n// No-op for Darwin (MacOS), Windows.\nfunc addIPv6Checks(checks []Checker) []Checker {\n\treturn checks\n}","line":{"from":33,"to":37}} {"id":100001194,"name":"addIPv4Checks","signature":"func addIPv4Checks(checks []Checker) []Checker","file":"cmd/kubeadm/app/preflight/checks_other.go","code":"// addIPv4Checks adds IPv4 related bridgenf and forwarding checks\n// No-op for Darwin (MacOS), Windows.\nfunc addIPv4Checks(checks []Checker) []Checker {\n\treturn checks\n}","line":{"from":39,"to":43}} {"id":100001195,"name":"addSwapCheck","signature":"func addSwapCheck(checks []Checker) []Checker","file":"cmd/kubeadm/app/preflight/checks_other.go","code":"// addSwapCheck adds a swap check\n// No-op for Darwin (MacOS), Windows.\nfunc addSwapCheck(checks []Checker) []Checker {\n\treturn checks\n}","line":{"from":45,"to":49}} {"id":100001196,"name":"addExecChecks","signature":"func addExecChecks(checks []Checker, _ utilsexec.Interface) []Checker","file":"cmd/kubeadm/app/preflight/checks_other.go","code":"// addExecChecks adds checks that verify if certain binaries are in PATH\n// No-op for Darwin (MacOS), Windows.\nfunc addExecChecks(checks []Checker, _ utilsexec.Interface) []Checker {\n\treturn checks\n}","line":{"from":51,"to":55}} {"id":100001197,"name":"Check","signature":"func (ipuc IsPrivilegedUserCheck) Check() (warnings, errorList []error)","file":"cmd/kubeadm/app/preflight/checks_unix.go","code":"// Check validates if an user has elevated (root) privileges.\nfunc (ipuc IsPrivilegedUserCheck) Check() (warnings, errorList []error) {\n\tif os.Getuid() != 0 {\n\t\treturn nil, []error{errors.New(\"user is not running as root\")}\n\t}\n\n\treturn nil, nil\n}","line":{"from":28,"to":35}} {"id":100001198,"name":"Check","signature":"func (ipuc IsPrivilegedUserCheck) Check() (warnings, errorList []error)","file":"cmd/kubeadm/app/preflight/checks_windows.go","code":"// Check validates if a user has elevated (administrator) privileges.\nfunc (ipuc IsPrivilegedUserCheck) Check() (warnings, errorList []error) {\n\tcurrUser, err := user.Current()\n\tif err != nil {\n\t\treturn nil, []error{errors.Wrap(err, \"cannot get current user\")}\n\t}\n\n\tgroupIds, err := currUser.GroupIds()\n\tif err != nil {\n\t\treturn nil, []error{errors.Wrap(err, \"cannot get group IDs for current user\")}\n\t}\n\n\tfor _, sid := range groupIds {\n\t\tif sid == administratorSID {\n\t\t\treturn nil, nil\n\t\t}\n\t}\n\n\treturn nil, []error{errors.New(\"user is not running as administrator\")}\n}","line":{"from":32,"to":51}} {"id":100001199,"name":"Check","signature":"func (mc MemCheck) Check() (warnings, errorList []error)","file":"cmd/kubeadm/app/preflight/checks_windows.go","code":"// Check number of memory required by kubeadm\n// No-op for Windows.\nfunc (mc MemCheck) Check() (warnings, errorList []error) {\n\treturn nil, nil\n}","line":{"from":53,"to":57}} {"id":100001200,"name":"GetKubeletVersion","signature":"func GetKubeletVersion(execer utilsexec.Interface) (*version.Version, error)","file":"cmd/kubeadm/app/preflight/utils.go","code":"// GetKubeletVersion is helper function that returns version of kubelet available in $PATH\nfunc GetKubeletVersion(execer utilsexec.Interface) (*version.Version, error) {\n\tkubeletVersionRegex := regexp.MustCompile(`^\\s*Kubernetes v((0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)([-\\w.+]*)?)\\s*$`)\n\n\tcommand := execer.Command(\"kubelet\", \"--version\")\n\tout, err := command.Output()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"cannot execute 'kubelet --version'\")\n\t}\n\n\tcleanOutput := strings.TrimSpace(string(out))\n\tsubs := kubeletVersionRegex.FindAllStringSubmatch(cleanOutput, -1)\n\tif len(subs) != 1 || len(subs[0]) \u003c 2 {\n\t\treturn nil, errors.Errorf(\"Unable to parse output from Kubelet: %q\", cleanOutput)\n\t}\n\treturn version.ParseSemantic(subs[0][1])\n}","line":{"from":29,"to":45}} {"id":100001201,"name":"NewClientBackedDryRunGetter","signature":"func NewClientBackedDryRunGetter(config *rest.Config) (*ClientBackedDryRunGetter, error)","file":"cmd/kubeadm/app/util/apiclient/clientbacked_dryrun.go","code":"// NewClientBackedDryRunGetter creates a new ClientBackedDryRunGetter instance based on the rest.Config object\nfunc NewClientBackedDryRunGetter(config *rest.Config) (*ClientBackedDryRunGetter, error) {\n\tclient, err := clientset.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdynamicClient, err := dynamic.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026ClientBackedDryRunGetter{\n\t\tclient: client,\n\t\tdynamicClient: dynamicClient,\n\t}, nil\n}","line":{"from":46,"to":61}} {"id":100001202,"name":"NewClientBackedDryRunGetterFromKubeconfig","signature":"func NewClientBackedDryRunGetterFromKubeconfig(file string) (*ClientBackedDryRunGetter, error)","file":"cmd/kubeadm/app/util/apiclient/clientbacked_dryrun.go","code":"// NewClientBackedDryRunGetterFromKubeconfig creates a new ClientBackedDryRunGetter instance from the given KubeConfig file\nfunc NewClientBackedDryRunGetterFromKubeconfig(file string) (*ClientBackedDryRunGetter, error) {\n\tconfig, err := clientcmd.LoadFromFile(file)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to load kubeconfig\")\n\t}\n\tclientConfig, err := clientcmd.NewDefaultClientConfig(*config, \u0026clientcmd.ConfigOverrides{}).ClientConfig()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create API client configuration from kubeconfig\")\n\t}\n\treturn NewClientBackedDryRunGetter(clientConfig)\n}","line":{"from":63,"to":74}} {"id":100001203,"name":"HandleGetAction","signature":"func (clg *ClientBackedDryRunGetter) HandleGetAction(action core.GetAction) (bool, runtime.Object, error)","file":"cmd/kubeadm/app/util/apiclient/clientbacked_dryrun.go","code":"// HandleGetAction handles GET actions to the dryrun clientset this interface supports\nfunc (clg *ClientBackedDryRunGetter) HandleGetAction(action core.GetAction) (bool, runtime.Object, error) {\n\tunstructuredObj, err := clg.dynamicClient.Resource(action.GetResource()).Namespace(action.GetNamespace()).Get(context.TODO(), action.GetName(), metav1.GetOptions{})\n\tif err != nil {\n\t\t// Inform the user that the requested object wasn't found.\n\t\tprintIfNotExists(err)\n\t\treturn true, nil, err\n\t}\n\tnewObj, err := decodeUnstructuredIntoAPIObject(action, unstructuredObj)\n\tif err != nil {\n\t\tfmt.Printf(\"error after decode: %v %v\\n\", unstructuredObj, err)\n\t\treturn true, nil, err\n\t}\n\treturn true, newObj, err\n}","line":{"from":76,"to":90}} {"id":100001204,"name":"HandleListAction","signature":"func (clg *ClientBackedDryRunGetter) HandleListAction(action core.ListAction) (bool, runtime.Object, error)","file":"cmd/kubeadm/app/util/apiclient/clientbacked_dryrun.go","code":"// HandleListAction handles LIST actions to the dryrun clientset this interface supports\nfunc (clg *ClientBackedDryRunGetter) HandleListAction(action core.ListAction) (bool, runtime.Object, error) {\n\tlistOpts := metav1.ListOptions{\n\t\tLabelSelector: action.GetListRestrictions().Labels.String(),\n\t\tFieldSelector: action.GetListRestrictions().Fields.String(),\n\t}\n\n\tunstructuredList, err := clg.dynamicClient.Resource(action.GetResource()).Namespace(action.GetNamespace()).List(context.TODO(), listOpts)\n\tif err != nil {\n\t\treturn true, nil, err\n\t}\n\tnewObj, err := decodeUnstructuredIntoAPIObject(action, unstructuredList)\n\tif err != nil {\n\t\tfmt.Printf(\"error after decode: %v %v\\n\", unstructuredList, err)\n\t\treturn true, nil, err\n\t}\n\treturn true, newObj, err\n}","line":{"from":92,"to":109}} {"id":100001205,"name":"Client","signature":"func (clg *ClientBackedDryRunGetter) Client() clientset.Interface","file":"cmd/kubeadm/app/util/apiclient/clientbacked_dryrun.go","code":"// Client gets the backing clientset.Interface\nfunc (clg *ClientBackedDryRunGetter) Client() clientset.Interface {\n\treturn clg.client\n}","line":{"from":111,"to":114}} {"id":100001206,"name":"decodeUnstructuredIntoAPIObject","signature":"func decodeUnstructuredIntoAPIObject(action core.Action, unstructuredObj runtime.Unstructured) (runtime.Object, error)","file":"cmd/kubeadm/app/util/apiclient/clientbacked_dryrun.go","code":"// decodeUnversionedIntoAPIObject converts the *unversioned.Unversioned object returned from the dynamic client\n// to bytes; and then decodes it back _to an external api version (k8s.io/api)_ using the normal API machinery\nfunc decodeUnstructuredIntoAPIObject(action core.Action, unstructuredObj runtime.Unstructured) (runtime.Object, error) {\n\tobjBytes, err := json.Marshal(unstructuredObj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnewObj, err := runtime.Decode(clientsetscheme.Codecs.UniversalDecoder(action.GetResource().GroupVersion()), objBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newObj, nil\n}","line":{"from":116,"to":128}} {"id":100001207,"name":"printIfNotExists","signature":"func printIfNotExists(err error)","file":"cmd/kubeadm/app/util/apiclient/clientbacked_dryrun.go","code":"func printIfNotExists(err error) {\n\tif apierrors.IsNotFound(err) {\n\t\tfmt.Println(\"[dryrun] The GET request didn't yield any result, the API Server returned a NotFound error.\")\n\t}\n}","line":{"from":130,"to":134}} {"id":100001208,"name":"DefaultMarshalFunc","signature":"func DefaultMarshalFunc(obj runtime.Object, gv schema.GroupVersion) ([]byte, error)","file":"cmd/kubeadm/app/util/apiclient/dryrunclient.go","code":"// DefaultMarshalFunc is the default MarshalFunc used; uses YAML to print objects to the user\nfunc DefaultMarshalFunc(obj runtime.Object, gv schema.GroupVersion) ([]byte, error) {\n\treturn kubeadmutil.MarshalToYaml(obj, gv)\n}","line":{"from":49,"to":52}} {"id":100001209,"name":"GetDefaultDryRunClientOptions","signature":"func GetDefaultDryRunClientOptions(drg DryRunGetter, w io.Writer) DryRunClientOptions","file":"cmd/kubeadm/app/util/apiclient/dryrunclient.go","code":"// GetDefaultDryRunClientOptions returns the default DryRunClientOptions values\nfunc GetDefaultDryRunClientOptions(drg DryRunGetter, w io.Writer) DryRunClientOptions {\n\treturn DryRunClientOptions{\n\t\tWriter: w,\n\t\tGetter: drg,\n\t\tPrependReactors: []core.Reactor{},\n\t\tAppendReactors: []core.Reactor{},\n\t\tMarshalFunc: DefaultMarshalFunc,\n\t\tPrintGETAndLIST: false,\n\t}\n}","line":{"from":64,"to":74}} {"id":100001210,"name":"NewDryRunClient","signature":"func NewDryRunClient(drg DryRunGetter, w io.Writer) clientset.Interface","file":"cmd/kubeadm/app/util/apiclient/dryrunclient.go","code":"// NewDryRunClient is a wrapper for NewDryRunClientWithOpts using some default values\nfunc NewDryRunClient(drg DryRunGetter, w io.Writer) clientset.Interface {\n\treturn NewDryRunClientWithOpts(GetDefaultDryRunClientOptions(drg, w))\n}","line":{"from":90,"to":93}} {"id":100001211,"name":"NewDryRunClientWithOpts","signature":"func NewDryRunClientWithOpts(opts DryRunClientOptions) clientset.Interface","file":"cmd/kubeadm/app/util/apiclient/dryrunclient.go","code":"// NewDryRunClientWithOpts returns a clientset.Interface that can be used normally for talking to the Kubernetes API.\n// This client doesn't apply changes to the backend. The client gets GET/LIST values from the DryRunGetter implementation.\n// This client logs all I/O to the writer w in YAML format\nfunc NewDryRunClientWithOpts(opts DryRunClientOptions) clientset.Interface {\n\t// Build a chain of reactors to act like a normal clientset; but log everything that is happening and don't change any state\n\tclient := fakeclientset.NewSimpleClientset()\n\n\t// Build the chain of reactors. Order matters; first item here will be invoked first on match, then the second one will be evaluated, etc.\n\tdefaultReactorChain := []core.Reactor{\n\t\t// Log everything that happens. Default the object if it's about to be created/updated so that the logged object is representative.\n\t\t\u0026core.SimpleReactor{\n\t\t\tVerb: \"*\",\n\t\t\tResource: \"*\",\n\t\t\tReaction: func(action core.Action) (bool, runtime.Object, error) {\n\t\t\t\tlogDryRunAction(action, opts.Writer, opts.MarshalFunc)\n\n\t\t\t\treturn false, nil, nil\n\t\t\t},\n\t\t},\n\t\t// Let the DryRunGetter implementation take care of all GET requests.\n\t\t// The DryRunGetter implementation may call a real API Server behind the scenes or just fake everything\n\t\t\u0026core.SimpleReactor{\n\t\t\tVerb: \"get\",\n\t\t\tResource: \"*\",\n\t\t\tReaction: func(action core.Action) (bool, runtime.Object, error) {\n\t\t\t\tgetAction, ok := action.(core.GetAction)\n\t\t\t\tif !ok {\n\t\t\t\t\t// If the GetAction cast fails, this could be an ActionImpl with a \"get\" verb.\n\t\t\t\t\t// Such actions could be invoked from any of the fake discovery calls, such as ServerVersion().\n\t\t\t\t\t// Attempt the cast to ActionImpl and construct a GetActionImpl from it.\n\t\t\t\t\tactionImpl, ok := action.(core.ActionImpl)\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tgetAction = core.GetActionImpl{ActionImpl: actionImpl}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// something's wrong, we can't handle this event\n\t\t\t\t\t\treturn true, nil, errors.New(\"can't cast get reactor event action object to GetAction interface\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\thandled, obj, err := opts.Getter.HandleGetAction(getAction)\n\n\t\t\t\tif opts.PrintGETAndLIST {\n\t\t\t\t\t// Print the marshalled object format with one tab indentation\n\t\t\t\t\tobjBytes, err := opts.MarshalFunc(obj, action.GetResource().GroupVersion())\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tfmt.Println(\"[dryrun] Returning faked GET response:\")\n\t\t\t\t\t\tPrintBytesWithLinePrefix(opts.Writer, objBytes, \"\\t\")\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn handled, obj, err\n\t\t\t},\n\t\t},\n\t\t// Let the DryRunGetter implementation take care of all GET requests.\n\t\t// The DryRunGetter implementation may call a real API Server behind the scenes or just fake everything\n\t\t\u0026core.SimpleReactor{\n\t\t\tVerb: \"list\",\n\t\t\tResource: \"*\",\n\t\t\tReaction: func(action core.Action) (bool, runtime.Object, error) {\n\t\t\t\tlistAction, ok := action.(core.ListAction)\n\t\t\t\tif !ok {\n\t\t\t\t\t// something's wrong, we can't handle this event\n\t\t\t\t\treturn true, nil, errors.New(\"can't cast list reactor event action object to ListAction interface\")\n\t\t\t\t}\n\t\t\t\thandled, objs, err := opts.Getter.HandleListAction(listAction)\n\n\t\t\t\tif opts.PrintGETAndLIST {\n\t\t\t\t\t// Print the marshalled object format with one tab indentation\n\t\t\t\t\tobjBytes, err := opts.MarshalFunc(objs, action.GetResource().GroupVersion())\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tfmt.Println(\"[dryrun] Returning faked LIST response:\")\n\t\t\t\t\t\tPrintBytesWithLinePrefix(opts.Writer, objBytes, \"\\t\")\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn handled, objs, err\n\t\t\t},\n\t\t},\n\t\t// For the verbs that modify anything on the server; just return the object if present and exit successfully\n\t\t\u0026core.SimpleReactor{\n\t\t\tVerb: \"create\",\n\t\t\tResource: \"*\",\n\t\t\tReaction: func(action core.Action) (bool, runtime.Object, error) {\n\t\t\t\tobjAction, ok := action.(actionWithObject)\n\t\t\t\tif obj := objAction.GetObject(); ok \u0026\u0026 obj != nil {\n\t\t\t\t\tif secret, ok := obj.(*v1.Secret); ok {\n\t\t\t\t\t\tif secret.Namespace == metav1.NamespaceSystem \u0026\u0026 strings.HasPrefix(secret.Name, bootstrapapi.BootstrapTokenSecretPrefix) {\n\t\t\t\t\t\t\t// bypass bootstrap token secret create event so that it can be persisted to the backing data store\n\t\t\t\t\t\t\t// this secret should be readable during the uploadcerts init phase if it has already been created\n\t\t\t\t\t\t\treturn false, nil, nil\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn successfulModificationReactorFunc(action)\n\t\t\t},\n\t\t},\n\t\t\u0026core.SimpleReactor{\n\t\t\tVerb: \"update\",\n\t\t\tResource: \"*\",\n\t\t\tReaction: successfulModificationReactorFunc,\n\t\t},\n\t\t\u0026core.SimpleReactor{\n\t\t\tVerb: \"delete\",\n\t\t\tResource: \"*\",\n\t\t\tReaction: successfulModificationReactorFunc,\n\t\t},\n\t\t\u0026core.SimpleReactor{\n\t\t\tVerb: \"delete-collection\",\n\t\t\tResource: \"*\",\n\t\t\tReaction: successfulModificationReactorFunc,\n\t\t},\n\t\t\u0026core.SimpleReactor{\n\t\t\tVerb: \"patch\",\n\t\t\tResource: \"*\",\n\t\t\tReaction: successfulModificationReactorFunc,\n\t\t},\n\t}\n\n\t// The chain of reactors will look like this:\n\t// opts.PrependReactors | defaultReactorChain | opts.AppendReactors | client.Fake.ReactionChain (default reactors for the fake clientset)\n\tfullReactorChain := append(opts.PrependReactors, defaultReactorChain...)\n\tfullReactorChain = append(fullReactorChain, opts.AppendReactors...)\n\n\t// Prepend the reaction chain with our reactors. Important, these MUST be prepended; not appended due to how the fake clientset works by default\n\tclient.Fake.ReactionChain = append(fullReactorChain, client.Fake.ReactionChain...)\n\treturn client\n}","line":{"from":95,"to":220}} {"id":100001212,"name":"successfulModificationReactorFunc","signature":"func successfulModificationReactorFunc(action core.Action) (bool, runtime.Object, error)","file":"cmd/kubeadm/app/util/apiclient/dryrunclient.go","code":"// successfulModificationReactorFunc is a no-op that just returns the POSTed/PUTed value if present; but does nothing to edit any backing data store.\nfunc successfulModificationReactorFunc(action core.Action) (bool, runtime.Object, error) {\n\tobjAction, ok := action.(actionWithObject)\n\tif ok {\n\t\treturn true, objAction.GetObject(), nil\n\t}\n\treturn true, nil, nil\n}","line":{"from":222,"to":229}} {"id":100001213,"name":"logDryRunAction","signature":"func logDryRunAction(action core.Action, w io.Writer, marshalFunc MarshalFunc)","file":"cmd/kubeadm/app/util/apiclient/dryrunclient.go","code":"// logDryRunAction logs the action that was recorded by the \"catch-all\" (*,*) reactor and tells the user what would have happened in an user-friendly way\nfunc logDryRunAction(action core.Action, w io.Writer, marshalFunc MarshalFunc) {\n\n\tgroup := action.GetResource().Group\n\tif len(group) == 0 {\n\t\tgroup = \"core\"\n\t}\n\tfmt.Fprintf(w, \"[dryrun] Would perform action %s on resource %q in API group \\\"%s/%s\\\"\\n\", strings.ToUpper(action.GetVerb()), action.GetResource().Resource, group, action.GetResource().Version)\n\n\tnamedAction, ok := action.(actionWithName)\n\tif ok {\n\t\tfmt.Fprintf(w, \"[dryrun] Resource name: %q\\n\", namedAction.GetName())\n\t}\n\n\tobjAction, ok := action.(actionWithObject)\n\tif ok \u0026\u0026 objAction.GetObject() != nil {\n\t\t// Print the marshalled object with a tab indentation\n\t\tobjBytes, err := marshalFunc(objAction.GetObject(), action.GetResource().GroupVersion())\n\t\tif err == nil {\n\t\t\tfmt.Println(\"[dryrun] Attached object:\")\n\t\t\tPrintBytesWithLinePrefix(w, objBytes, \"\\t\")\n\t\t}\n\t}\n\n\tpatchAction, ok := action.(core.PatchAction)\n\tif ok {\n\t\t// Replace all occurrences of \\\" with a simple \" when printing\n\t\tfmt.Fprintf(w, \"[dryrun] Attached patch:\\n\\t%s\\n\", strings.Replace(string(patchAction.GetPatch()), `\\\"`, `\"`, -1))\n\t}\n}","line":{"from":231,"to":260}} {"id":100001214,"name":"PrintBytesWithLinePrefix","signature":"func PrintBytesWithLinePrefix(w io.Writer, objBytes []byte, linePrefix string)","file":"cmd/kubeadm/app/util/apiclient/dryrunclient.go","code":"// PrintBytesWithLinePrefix prints objBytes to writer w with linePrefix in the beginning of every line\nfunc PrintBytesWithLinePrefix(w io.Writer, objBytes []byte, linePrefix string) {\n\tscanner := bufio.NewScanner(bytes.NewReader(objBytes))\n\tfor scanner.Scan() {\n\t\tfmt.Fprintf(w, \"%s%s\\n\", linePrefix, scanner.Text())\n\t}\n}","line":{"from":262,"to":268}} {"id":100001215,"name":"CreateOrUpdateConfigMap","signature":"func CreateOrUpdateConfigMap(client clientset.Interface, cm *v1.ConfigMap) error","file":"cmd/kubeadm/app/util/apiclient/idempotency.go","code":"// CreateOrUpdateConfigMap creates a ConfigMap if the target resource doesn't exist. If the resource exists already, this function will update the resource instead.\nfunc CreateOrUpdateConfigMap(client clientset.Interface, cm *v1.ConfigMap) error {\n\tif _, err := client.CoreV1().ConfigMaps(cm.ObjectMeta.Namespace).Create(context.TODO(), cm, metav1.CreateOptions{}); err != nil {\n\t\tif !apierrors.IsAlreadyExists(err) {\n\t\t\treturn errors.Wrap(err, \"unable to create ConfigMap\")\n\t\t}\n\n\t\tif _, err := client.CoreV1().ConfigMaps(cm.ObjectMeta.Namespace).Update(context.TODO(), cm, metav1.UpdateOptions{}); err != nil {\n\t\t\treturn errors.Wrap(err, \"unable to update ConfigMap\")\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":44,"to":56}} {"id":100001216,"name":"CreateOrMutateConfigMap","signature":"func CreateOrMutateConfigMap(client clientset.Interface, cm *v1.ConfigMap, mutator ConfigMapMutator) error","file":"cmd/kubeadm/app/util/apiclient/idempotency.go","code":"// CreateOrMutateConfigMap tries to create the ConfigMap provided as cm. If the resource exists already, the latest version will be fetched from\n// the cluster and mutator callback will be called on it, then an Update of the mutated ConfigMap will be performed. This function is resilient\n// to conflicts, and a retry will be issued if the ConfigMap was modified on the server between the refresh and the update (while the mutation was\n// taking place)\nfunc CreateOrMutateConfigMap(client clientset.Interface, cm *v1.ConfigMap, mutator ConfigMapMutator) error {\n\tvar lastError error\n\terr := wait.PollImmediate(constants.APICallRetryInterval, constants.APICallWithWriteTimeout, func() (bool, error) {\n\t\tif _, err := client.CoreV1().ConfigMaps(cm.ObjectMeta.Namespace).Create(context.TODO(), cm, metav1.CreateOptions{}); err != nil {\n\t\t\tlastError = err\n\t\t\tif apierrors.IsAlreadyExists(err) {\n\t\t\t\tlastError = MutateConfigMap(client, metav1.ObjectMeta{Namespace: cm.ObjectMeta.Namespace, Name: cm.ObjectMeta.Name}, mutator)\n\t\t\t\treturn lastError == nil, nil\n\t\t\t}\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\tif err == nil {\n\t\treturn nil\n\t}\n\treturn lastError\n}","line":{"from":58,"to":79}} {"id":100001217,"name":"MutateConfigMap","signature":"func MutateConfigMap(client clientset.Interface, meta metav1.ObjectMeta, mutator ConfigMapMutator) error","file":"cmd/kubeadm/app/util/apiclient/idempotency.go","code":"// MutateConfigMap takes a ConfigMap Object Meta (namespace and name), retrieves the resource from the server and tries to mutate it\n// by calling to the mutator callback, then an Update of the mutated ConfigMap will be performed. This function is resilient\n// to conflicts, and a retry will be issued if the ConfigMap was modified on the server between the refresh and the update (while the mutation was\n// taking place).\nfunc MutateConfigMap(client clientset.Interface, meta metav1.ObjectMeta, mutator ConfigMapMutator) error {\n\tvar lastError error\n\terr := wait.PollImmediate(constants.APICallRetryInterval, constants.APICallWithWriteTimeout, func() (bool, error) {\n\t\tconfigMap, err := client.CoreV1().ConfigMaps(meta.Namespace).Get(context.TODO(), meta.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\tlastError = err\n\t\t\treturn false, nil\n\t\t}\n\t\tif err = mutator(configMap); err != nil {\n\t\t\tlastError = errors.Wrap(err, \"unable to mutate ConfigMap\")\n\t\t\treturn false, nil\n\t\t}\n\t\t_, lastError = client.CoreV1().ConfigMaps(configMap.ObjectMeta.Namespace).Update(context.TODO(), configMap, metav1.UpdateOptions{})\n\t\treturn lastError == nil, nil\n\t})\n\tif err == nil {\n\t\treturn nil\n\t}\n\treturn lastError\n}","line":{"from":81,"to":104}} {"id":100001218,"name":"CreateOrRetainConfigMap","signature":"func CreateOrRetainConfigMap(client clientset.Interface, cm *v1.ConfigMap, configMapName string) error","file":"cmd/kubeadm/app/util/apiclient/idempotency.go","code":"// CreateOrRetainConfigMap creates a ConfigMap if the target resource doesn't exist. If the resource exists already, this function will retain the resource instead.\nfunc CreateOrRetainConfigMap(client clientset.Interface, cm *v1.ConfigMap, configMapName string) error {\n\tif _, err := client.CoreV1().ConfigMaps(cm.ObjectMeta.Namespace).Get(context.TODO(), configMapName, metav1.GetOptions{}); err != nil {\n\t\tif !apierrors.IsNotFound(err) {\n\t\t\treturn nil\n\t\t}\n\t\tif _, err := client.CoreV1().ConfigMaps(cm.ObjectMeta.Namespace).Create(context.TODO(), cm, metav1.CreateOptions{}); err != nil {\n\t\t\tif !apierrors.IsAlreadyExists(err) {\n\t\t\t\treturn errors.Wrap(err, \"unable to create ConfigMap\")\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":106,"to":119}} {"id":100001219,"name":"CreateOrUpdateSecret","signature":"func CreateOrUpdateSecret(client clientset.Interface, secret *v1.Secret) error","file":"cmd/kubeadm/app/util/apiclient/idempotency.go","code":"// CreateOrUpdateSecret creates a Secret if the target resource doesn't exist. If the resource exists already, this function will update the resource instead.\nfunc CreateOrUpdateSecret(client clientset.Interface, secret *v1.Secret) error {\n\tif _, err := client.CoreV1().Secrets(secret.ObjectMeta.Namespace).Create(context.TODO(), secret, metav1.CreateOptions{}); err != nil {\n\t\tif !apierrors.IsAlreadyExists(err) {\n\t\t\treturn errors.Wrap(err, \"unable to create secret\")\n\t\t}\n\n\t\tif _, err := client.CoreV1().Secrets(secret.ObjectMeta.Namespace).Update(context.TODO(), secret, metav1.UpdateOptions{}); err != nil {\n\t\t\treturn errors.Wrap(err, \"unable to update secret\")\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":121,"to":133}} {"id":100001220,"name":"CreateOrUpdateServiceAccount","signature":"func CreateOrUpdateServiceAccount(client clientset.Interface, sa *v1.ServiceAccount) error","file":"cmd/kubeadm/app/util/apiclient/idempotency.go","code":"// CreateOrUpdateServiceAccount creates a ServiceAccount if the target resource doesn't exist. If the resource exists already, this function will update the resource instead.\nfunc CreateOrUpdateServiceAccount(client clientset.Interface, sa *v1.ServiceAccount) error {\n\tif _, err := client.CoreV1().ServiceAccounts(sa.ObjectMeta.Namespace).Create(context.TODO(), sa, metav1.CreateOptions{}); err != nil {\n\t\t// Note: We don't run .Update here afterwards as that's probably not required\n\t\t// Only thing that could be updated is annotations/labels in .metadata, but we don't use that currently\n\t\tif !apierrors.IsAlreadyExists(err) {\n\t\t\treturn errors.Wrap(err, \"unable to create serviceaccount\")\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":135,"to":145}} {"id":100001221,"name":"CreateOrUpdateDeployment","signature":"func CreateOrUpdateDeployment(client clientset.Interface, deploy *apps.Deployment) error","file":"cmd/kubeadm/app/util/apiclient/idempotency.go","code":"// CreateOrUpdateDeployment creates a Deployment if the target resource doesn't exist. If the resource exists already, this function will update the resource instead.\nfunc CreateOrUpdateDeployment(client clientset.Interface, deploy *apps.Deployment) error {\n\tif _, err := client.AppsV1().Deployments(deploy.ObjectMeta.Namespace).Create(context.TODO(), deploy, metav1.CreateOptions{}); err != nil {\n\t\tif !apierrors.IsAlreadyExists(err) {\n\t\t\treturn errors.Wrap(err, \"unable to create deployment\")\n\t\t}\n\n\t\tif _, err := client.AppsV1().Deployments(deploy.ObjectMeta.Namespace).Update(context.TODO(), deploy, metav1.UpdateOptions{}); err != nil {\n\t\t\treturn errors.Wrap(err, \"unable to update deployment\")\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":147,"to":159}} {"id":100001222,"name":"CreateOrRetainDeployment","signature":"func CreateOrRetainDeployment(client clientset.Interface, deploy *apps.Deployment, deployName string) error","file":"cmd/kubeadm/app/util/apiclient/idempotency.go","code":"// CreateOrRetainDeployment creates a Deployment if the target resource doesn't exist. If the resource exists already, this function will retain the resource instead.\nfunc CreateOrRetainDeployment(client clientset.Interface, deploy *apps.Deployment, deployName string) error {\n\tif _, err := client.AppsV1().Deployments(deploy.ObjectMeta.Namespace).Get(context.TODO(), deployName, metav1.GetOptions{}); err != nil {\n\t\tif !apierrors.IsNotFound(err) {\n\t\t\treturn nil\n\t\t}\n\t\tif _, err := client.AppsV1().Deployments(deploy.ObjectMeta.Namespace).Create(context.TODO(), deploy, metav1.CreateOptions{}); err != nil {\n\t\t\tif !apierrors.IsAlreadyExists(err) {\n\t\t\t\treturn errors.Wrap(err, \"unable to create deployment\")\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":161,"to":174}} {"id":100001223,"name":"CreateOrUpdateDaemonSet","signature":"func CreateOrUpdateDaemonSet(client clientset.Interface, ds *apps.DaemonSet) error","file":"cmd/kubeadm/app/util/apiclient/idempotency.go","code":"// CreateOrUpdateDaemonSet creates a DaemonSet if the target resource doesn't exist. If the resource exists already, this function will update the resource instead.\nfunc CreateOrUpdateDaemonSet(client clientset.Interface, ds *apps.DaemonSet) error {\n\tif _, err := client.AppsV1().DaemonSets(ds.ObjectMeta.Namespace).Create(context.TODO(), ds, metav1.CreateOptions{}); err != nil {\n\t\tif !apierrors.IsAlreadyExists(err) {\n\t\t\treturn errors.Wrap(err, \"unable to create daemonset\")\n\t\t}\n\n\t\tif _, err := client.AppsV1().DaemonSets(ds.ObjectMeta.Namespace).Update(context.TODO(), ds, metav1.UpdateOptions{}); err != nil {\n\t\t\treturn errors.Wrap(err, \"unable to update daemonset\")\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":176,"to":188}} {"id":100001224,"name":"CreateOrUpdateRole","signature":"func CreateOrUpdateRole(client clientset.Interface, role *rbac.Role) error","file":"cmd/kubeadm/app/util/apiclient/idempotency.go","code":"// CreateOrUpdateRole creates a Role if the target resource doesn't exist. If the resource exists already, this function will update the resource instead.\nfunc CreateOrUpdateRole(client clientset.Interface, role *rbac.Role) error {\n\tvar lastError error\n\terr := wait.PollImmediate(constants.APICallRetryInterval, constants.APICallWithWriteTimeout, func() (bool, error) {\n\t\tif _, err := client.RbacV1().Roles(role.ObjectMeta.Namespace).Create(context.TODO(), role, metav1.CreateOptions{}); err != nil {\n\t\t\tif !apierrors.IsAlreadyExists(err) {\n\t\t\t\tlastError = errors.Wrap(err, \"unable to create RBAC role\")\n\t\t\t\treturn false, nil\n\t\t\t}\n\n\t\t\tif _, err := client.RbacV1().Roles(role.ObjectMeta.Namespace).Update(context.TODO(), role, metav1.UpdateOptions{}); err != nil {\n\t\t\t\tlastError = errors.Wrap(err, \"unable to update RBAC role\")\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t}\n\t\treturn true, nil\n\t})\n\tif err == nil {\n\t\treturn nil\n\t}\n\treturn lastError\n}","line":{"from":190,"to":211}} {"id":100001225,"name":"CreateOrUpdateRoleBinding","signature":"func CreateOrUpdateRoleBinding(client clientset.Interface, roleBinding *rbac.RoleBinding) error","file":"cmd/kubeadm/app/util/apiclient/idempotency.go","code":"// CreateOrUpdateRoleBinding creates a RoleBinding if the target resource doesn't exist. If the resource exists already, this function will update the resource instead.\nfunc CreateOrUpdateRoleBinding(client clientset.Interface, roleBinding *rbac.RoleBinding) error {\n\tvar lastError error\n\terr := wait.PollImmediate(constants.APICallRetryInterval, constants.APICallWithWriteTimeout, func() (bool, error) {\n\t\tif _, err := client.RbacV1().RoleBindings(roleBinding.ObjectMeta.Namespace).Create(context.TODO(), roleBinding, metav1.CreateOptions{}); err != nil {\n\t\t\tif !apierrors.IsAlreadyExists(err) {\n\t\t\t\tlastError = errors.Wrap(err, \"unable to create RBAC rolebinding\")\n\t\t\t\treturn false, nil\n\t\t\t}\n\n\t\t\tif _, err := client.RbacV1().RoleBindings(roleBinding.ObjectMeta.Namespace).Update(context.TODO(), roleBinding, metav1.UpdateOptions{}); err != nil {\n\t\t\t\tlastError = errors.Wrap(err, \"unable to update RBAC rolebinding\")\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t}\n\t\treturn true, nil\n\t})\n\tif err == nil {\n\t\treturn nil\n\t}\n\treturn lastError\n}","line":{"from":213,"to":234}} {"id":100001226,"name":"CreateOrUpdateClusterRole","signature":"func CreateOrUpdateClusterRole(client clientset.Interface, clusterRole *rbac.ClusterRole) error","file":"cmd/kubeadm/app/util/apiclient/idempotency.go","code":"// CreateOrUpdateClusterRole creates a ClusterRole if the target resource doesn't exist. If the resource exists already, this function will update the resource instead.\nfunc CreateOrUpdateClusterRole(client clientset.Interface, clusterRole *rbac.ClusterRole) error {\n\tif _, err := client.RbacV1().ClusterRoles().Create(context.TODO(), clusterRole, metav1.CreateOptions{}); err != nil {\n\t\tif !apierrors.IsAlreadyExists(err) {\n\t\t\treturn errors.Wrap(err, \"unable to create RBAC clusterrole\")\n\t\t}\n\n\t\tif _, err := client.RbacV1().ClusterRoles().Update(context.TODO(), clusterRole, metav1.UpdateOptions{}); err != nil {\n\t\t\treturn errors.Wrap(err, \"unable to update RBAC clusterrole\")\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":236,"to":248}} {"id":100001227,"name":"CreateOrUpdateClusterRoleBinding","signature":"func CreateOrUpdateClusterRoleBinding(client clientset.Interface, clusterRoleBinding *rbac.ClusterRoleBinding) error","file":"cmd/kubeadm/app/util/apiclient/idempotency.go","code":"// CreateOrUpdateClusterRoleBinding creates a ClusterRoleBinding if the target resource doesn't exist. If the resource exists already, this function will update the resource instead.\nfunc CreateOrUpdateClusterRoleBinding(client clientset.Interface, clusterRoleBinding *rbac.ClusterRoleBinding) error {\n\tif _, err := client.RbacV1().ClusterRoleBindings().Create(context.TODO(), clusterRoleBinding, metav1.CreateOptions{}); err != nil {\n\t\tif !apierrors.IsAlreadyExists(err) {\n\t\t\treturn errors.Wrap(err, \"unable to create RBAC clusterrolebinding\")\n\t\t}\n\n\t\tif _, err := client.RbacV1().ClusterRoleBindings().Update(context.TODO(), clusterRoleBinding, metav1.UpdateOptions{}); err != nil {\n\t\t\treturn errors.Wrap(err, \"unable to update RBAC clusterrolebinding\")\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":250,"to":262}} {"id":100001228,"name":"PatchNodeOnce","signature":"func PatchNodeOnce(client clientset.Interface, nodeName string, patchFn func(*v1.Node), lastError *error) func() (bool, error)","file":"cmd/kubeadm/app/util/apiclient/idempotency.go","code":"// PatchNodeOnce executes patchFn on the node object found by the node name.\n// This is a condition function meant to be used with wait.Poll. false, nil\n// implies it is safe to try again, an error indicates no more tries should be\n// made and true indicates success.\nfunc PatchNodeOnce(client clientset.Interface, nodeName string, patchFn func(*v1.Node), lastError *error) func() (bool, error) {\n\treturn func() (bool, error) {\n\t\t// First get the node object\n\t\tn, err := client.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\t*lastError = err\n\t\t\treturn false, nil // retry on any error\n\t\t}\n\n\t\t// The node may appear to have no labels at first,\n\t\t// so we wait for it to get hostname label.\n\t\tif _, found := n.ObjectMeta.Labels[v1.LabelHostname]; !found {\n\t\t\treturn false, nil\n\t\t}\n\n\t\toldData, err := json.Marshal(n)\n\t\tif err != nil {\n\t\t\t*lastError = errors.Wrapf(err, \"failed to marshal unmodified node %q into JSON\", n.Name)\n\t\t\treturn false, *lastError\n\t\t}\n\n\t\t// Execute the mutating function\n\t\tpatchFn(n)\n\n\t\tnewData, err := json.Marshal(n)\n\t\tif err != nil {\n\t\t\t*lastError = errors.Wrapf(err, \"failed to marshal modified node %q into JSON\", n.Name)\n\t\t\treturn false, *lastError\n\t\t}\n\n\t\tpatchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, v1.Node{})\n\t\tif err != nil {\n\t\t\t*lastError = errors.Wrap(err, \"failed to create two way merge patch\")\n\t\t\treturn false, *lastError\n\t\t}\n\n\t\tif _, err := client.CoreV1().Nodes().Patch(context.TODO(), n.Name, types.StrategicMergePatchType, patchBytes, metav1.PatchOptions{}); err != nil {\n\t\t\t*lastError = errors.Wrapf(err, \"error patching node %q through apiserver\", n.Name)\n\t\t\tif apierrors.IsTimeout(err) || apierrors.IsConflict(err) || apierrors.IsServerTimeout(err) || apierrors.IsServiceUnavailable(err) {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn false, *lastError\n\t\t}\n\n\t\treturn true, nil\n\t}\n}","line":{"from":264,"to":314}} {"id":100001229,"name":"PatchNode","signature":"func PatchNode(client clientset.Interface, nodeName string, patchFn func(*v1.Node)) error","file":"cmd/kubeadm/app/util/apiclient/idempotency.go","code":"// PatchNode tries to patch a node using patchFn for the actual mutating logic.\n// Retries are provided by the wait package.\nfunc PatchNode(client clientset.Interface, nodeName string, patchFn func(*v1.Node)) error {\n\tvar lastError error\n\t// wait.Poll will rerun the condition function every interval function if\n\t// the function returns false. If the condition function returns an error\n\t// then the retries end and the error is returned.\n\terr := wait.Poll(constants.APICallRetryInterval, constants.PatchNodeTimeout, PatchNodeOnce(client, nodeName, patchFn, \u0026lastError))\n\tif err == nil {\n\t\treturn nil\n\t}\n\treturn lastError\n}","line":{"from":316,"to":328}} {"id":100001230,"name":"GetConfigMapWithRetry","signature":"func GetConfigMapWithRetry(client clientset.Interface, namespace, name string) (*v1.ConfigMap, error)","file":"cmd/kubeadm/app/util/apiclient/idempotency.go","code":"// GetConfigMapWithRetry tries to retrieve a ConfigMap using the given client,\n// retrying if we get an unexpected error.\nfunc GetConfigMapWithRetry(client clientset.Interface, namespace, name string) (*v1.ConfigMap, error) {\n\tvar cm *v1.ConfigMap\n\tvar lastError error\n\terr := wait.ExponentialBackoff(clientsetretry.DefaultBackoff, func() (bool, error) {\n\t\tvar err error\n\t\tcm, err = client.CoreV1().ConfigMaps(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\t\tif err == nil {\n\t\t\treturn true, nil\n\t\t}\n\t\tlastError = err\n\t\treturn false, nil\n\t})\n\tif err == nil {\n\t\treturn cm, nil\n\t}\n\treturn nil, lastError\n}","line":{"from":330,"to":348}} {"id":100001231,"name":"NewInitDryRunGetter","signature":"func NewInitDryRunGetter(controlPlaneName string, serviceSubnet string) *InitDryRunGetter","file":"cmd/kubeadm/app/util/apiclient/init_dryrun.go","code":"// NewInitDryRunGetter creates a new instance of the InitDryRunGetter struct\nfunc NewInitDryRunGetter(controlPlaneName string, serviceSubnet string) *InitDryRunGetter {\n\treturn \u0026InitDryRunGetter{\n\t\tcontrolPlaneName: controlPlaneName,\n\t\tserviceSubnet: serviceSubnet,\n\t}\n}","line":{"from":47,"to":53}} {"id":100001232,"name":"HandleGetAction","signature":"func (idr *InitDryRunGetter) HandleGetAction(action core.GetAction) (bool, runtime.Object, error)","file":"cmd/kubeadm/app/util/apiclient/init_dryrun.go","code":"// HandleGetAction handles GET actions to the dryrun clientset this interface supports\nfunc (idr *InitDryRunGetter) HandleGetAction(action core.GetAction) (bool, runtime.Object, error) {\n\tfuncs := []func(core.GetAction) (bool, runtime.Object, error){\n\t\tidr.handleKubernetesService,\n\t\tidr.handleGetNode,\n\t\tidr.handleSystemNodesClusterRoleBinding,\n\t}\n\tfor _, f := range funcs {\n\t\thandled, obj, err := f(action)\n\t\tif handled {\n\t\t\treturn handled, obj, err\n\t\t}\n\t}\n\n\treturn false, nil, nil\n}","line":{"from":55,"to":70}} {"id":100001233,"name":"HandleListAction","signature":"func (idr *InitDryRunGetter) HandleListAction(action core.ListAction) (bool, runtime.Object, error)","file":"cmd/kubeadm/app/util/apiclient/init_dryrun.go","code":"// HandleListAction handles GET actions to the dryrun clientset this interface supports.\n// Currently there are no known LIST calls during kubeadm init this code has to take care of.\nfunc (idr *InitDryRunGetter) HandleListAction(action core.ListAction) (bool, runtime.Object, error) {\n\treturn false, nil, nil\n}","line":{"from":72,"to":76}} {"id":100001234,"name":"handleKubernetesService","signature":"func (idr *InitDryRunGetter) handleKubernetesService(action core.GetAction) (bool, runtime.Object, error)","file":"cmd/kubeadm/app/util/apiclient/init_dryrun.go","code":"// handleKubernetesService returns a faked Kubernetes service in order to be able to continue running kubeadm init.\n// The CoreDNS addon code GETs the Kubernetes service in order to extract the service subnet\nfunc (idr *InitDryRunGetter) handleKubernetesService(action core.GetAction) (bool, runtime.Object, error) {\n\tif action.GetName() != \"kubernetes\" || action.GetNamespace() != metav1.NamespaceDefault || action.GetResource().Resource != \"services\" {\n\t\t// We can't handle this event\n\t\treturn false, nil, nil\n\t}\n\n\t_, svcSubnet, err := netutils.ParseCIDRSloppy(idr.serviceSubnet)\n\tif err != nil {\n\t\treturn true, nil, errors.Wrapf(err, \"error parsing CIDR %q\", idr.serviceSubnet)\n\t}\n\n\tinternalAPIServerVirtualIP, err := netutils.GetIndexedIP(svcSubnet, 1)\n\tif err != nil {\n\t\treturn true, nil, errors.Wrapf(err, \"unable to get first IP address from the given CIDR (%s)\", svcSubnet.String())\n\t}\n\n\t// The only used field of this Service object is the ClusterIP, which CoreDNS uses to calculate its own IP\n\treturn true, \u0026v1.Service{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"kubernetes\",\n\t\t\tNamespace: metav1.NamespaceDefault,\n\t\t\tLabels: map[string]string{\n\t\t\t\t\"component\": \"apiserver\",\n\t\t\t\t\"provider\": \"kubernetes\",\n\t\t\t},\n\t\t},\n\t\tSpec: v1.ServiceSpec{\n\t\t\tClusterIP: internalAPIServerVirtualIP.String(),\n\t\t\tPorts: []v1.ServicePort{\n\t\t\t\t{\n\t\t\t\t\tName: \"https\",\n\t\t\t\t\tPort: 443,\n\t\t\t\t\tTargetPort: intstr.FromInt(6443),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, nil\n}","line":{"from":78,"to":117}} {"id":100001235,"name":"handleGetNode","signature":"func (idr *InitDryRunGetter) handleGetNode(action core.GetAction) (bool, runtime.Object, error)","file":"cmd/kubeadm/app/util/apiclient/init_dryrun.go","code":"// handleGetNode returns a fake node object for the purpose of moving kubeadm init forwards.\nfunc (idr *InitDryRunGetter) handleGetNode(action core.GetAction) (bool, runtime.Object, error) {\n\tif action.GetName() != idr.controlPlaneName || action.GetResource().Resource != \"nodes\" {\n\t\t// We can't handle this event\n\t\treturn false, nil, nil\n\t}\n\n\treturn true, \u0026v1.Node{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: idr.controlPlaneName,\n\t\t\tLabels: map[string]string{\n\t\t\t\t\"kubernetes.io/hostname\": idr.controlPlaneName,\n\t\t\t},\n\t\t\tAnnotations: map[string]string{},\n\t\t},\n\t}, nil\n}","line":{"from":119,"to":135}} {"id":100001236,"name":"handleSystemNodesClusterRoleBinding","signature":"func (idr *InitDryRunGetter) handleSystemNodesClusterRoleBinding(action core.GetAction) (bool, runtime.Object, error)","file":"cmd/kubeadm/app/util/apiclient/init_dryrun.go","code":"// handleSystemNodesClusterRoleBinding handles the GET call to the system:nodes clusterrolebinding\nfunc (idr *InitDryRunGetter) handleSystemNodesClusterRoleBinding(action core.GetAction) (bool, runtime.Object, error) {\n\tif action.GetName() != constants.NodesClusterRoleBinding || action.GetResource().Resource != \"clusterrolebindings\" {\n\t\t// We can't handle this event\n\t\treturn false, nil, nil\n\t}\n\t// We can safely return a NotFound error here as the code will just proceed normally and don't care about modifying this clusterrolebinding\n\t// This can only happen on an upgrade; and in that case the ClientBackedDryRunGetter impl will be used\n\treturn true, nil, apierrors.NewNotFound(action.GetResource().GroupResource(), \"clusterrolebinding not found\")\n}","line":{"from":137,"to":146}} {"id":100001237,"name":"NewKubeWaiter","signature":"func NewKubeWaiter(client clientset.Interface, timeout time.Duration, writer io.Writer) Waiter","file":"cmd/kubeadm/app/util/apiclient/wait.go","code":"// NewKubeWaiter returns a new Waiter object that talks to the given Kubernetes cluster\nfunc NewKubeWaiter(client clientset.Interface, timeout time.Duration, writer io.Writer) Waiter {\n\treturn \u0026KubeWaiter{\n\t\tclient: client,\n\t\ttimeout: timeout,\n\t\twriter: writer,\n\t}\n}","line":{"from":68,"to":75}} {"id":100001238,"name":"WaitForAPI","signature":"func (w *KubeWaiter) WaitForAPI() error","file":"cmd/kubeadm/app/util/apiclient/wait.go","code":"// WaitForAPI waits for the API Server's /healthz endpoint to report \"ok\"\nfunc (w *KubeWaiter) WaitForAPI() error {\n\tstart := time.Now()\n\treturn wait.PollImmediate(kubeadmconstants.APICallRetryInterval, w.timeout, func() (bool, error) {\n\t\thealthStatus := 0\n\t\tw.client.Discovery().RESTClient().Get().AbsPath(\"/healthz\").Do(context.TODO()).StatusCode(\u0026healthStatus)\n\t\tif healthStatus != http.StatusOK {\n\t\t\treturn false, nil\n\t\t}\n\n\t\tfmt.Printf(\"[apiclient] All control plane components are healthy after %f seconds\\n\", time.Since(start).Seconds())\n\t\treturn true, nil\n\t})\n}","line":{"from":77,"to":90}} {"id":100001239,"name":"WaitForPodsWithLabel","signature":"func (w *KubeWaiter) WaitForPodsWithLabel(kvLabel string) error","file":"cmd/kubeadm/app/util/apiclient/wait.go","code":"// WaitForPodsWithLabel will lookup pods with the given label and wait until they are all\n// reporting status as running.\nfunc (w *KubeWaiter) WaitForPodsWithLabel(kvLabel string) error {\n\n\tlastKnownPodNumber := -1\n\treturn wait.PollImmediate(kubeadmconstants.APICallRetryInterval, w.timeout, func() (bool, error) {\n\t\tlistOpts := metav1.ListOptions{LabelSelector: kvLabel}\n\t\tpods, err := w.client.CoreV1().Pods(metav1.NamespaceSystem).List(context.TODO(), listOpts)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(w.writer, \"[apiclient] Error getting Pods with label selector %q [%v]\\n\", kvLabel, err)\n\t\t\treturn false, nil\n\t\t}\n\n\t\tif lastKnownPodNumber != len(pods.Items) {\n\t\t\tfmt.Fprintf(w.writer, \"[apiclient] Found %d Pods for label selector %s\\n\", len(pods.Items), kvLabel)\n\t\t\tlastKnownPodNumber = len(pods.Items)\n\t\t}\n\n\t\tif len(pods.Items) == 0 {\n\t\t\treturn false, nil\n\t\t}\n\n\t\tfor _, pod := range pods.Items {\n\t\t\tif pod.Status.Phase != v1.PodRunning {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t}\n\n\t\treturn true, nil\n\t})\n}","line":{"from":92,"to":122}} {"id":100001240,"name":"WaitForPodToDisappear","signature":"func (w *KubeWaiter) WaitForPodToDisappear(podName string) error","file":"cmd/kubeadm/app/util/apiclient/wait.go","code":"// WaitForPodToDisappear blocks until it timeouts or gets a \"NotFound\" response from the API Server when getting the Static Pod in question\nfunc (w *KubeWaiter) WaitForPodToDisappear(podName string) error {\n\treturn wait.PollImmediate(kubeadmconstants.APICallRetryInterval, w.timeout, func() (bool, error) {\n\t\t_, err := w.client.CoreV1().Pods(metav1.NamespaceSystem).Get(context.TODO(), podName, metav1.GetOptions{})\n\t\tif err != nil \u0026\u0026 apierrors.IsNotFound(err) {\n\t\t\tfmt.Printf(\"[apiclient] The old Pod %q is now removed (which is desired)\\n\", podName)\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n}","line":{"from":124,"to":134}} {"id":100001241,"name":"WaitForHealthyKubelet","signature":"func (w *KubeWaiter) WaitForHealthyKubelet(initialTimeout time.Duration, healthzEndpoint string) error","file":"cmd/kubeadm/app/util/apiclient/wait.go","code":"// WaitForHealthyKubelet blocks until the kubelet /healthz endpoint returns 'ok'\nfunc (w *KubeWaiter) WaitForHealthyKubelet(initialTimeout time.Duration, healthzEndpoint string) error {\n\ttime.Sleep(initialTimeout)\n\tfmt.Printf(\"[kubelet-check] Initial timeout of %v passed.\\n\", initialTimeout)\n\treturn TryRunCommand(func() error {\n\t\tclient := \u0026http.Client{Transport: netutil.SetOldTransportDefaults(\u0026http.Transport{})}\n\t\tresp, err := client.Get(healthzEndpoint)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"[kubelet-check] It seems like the kubelet isn't running or healthy.\")\n\t\t\tfmt.Printf(\"[kubelet-check] The HTTP call equal to 'curl -sSL %s' failed with error: %v.\\n\", healthzEndpoint, err)\n\t\t\treturn err\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tif resp.StatusCode != http.StatusOK {\n\t\t\tfmt.Println(\"[kubelet-check] It seems like the kubelet isn't running or healthy.\")\n\t\t\tfmt.Printf(\"[kubelet-check] The HTTP call equal to 'curl -sSL %s' returned HTTP code %d\\n\", healthzEndpoint, resp.StatusCode)\n\t\t\treturn errors.New(\"the kubelet healthz endpoint is unhealthy\")\n\t\t}\n\t\treturn nil\n\t}, 5) // a failureThreshold of five means waiting for a total of 155 seconds\n}","line":{"from":136,"to":156}} {"id":100001242,"name":"WaitForKubeletAndFunc","signature":"func (w *KubeWaiter) WaitForKubeletAndFunc(f func() error) error","file":"cmd/kubeadm/app/util/apiclient/wait.go","code":"// WaitForKubeletAndFunc waits primarily for the function f to execute, even though it might take some time. If that takes a long time, and the kubelet\n// /healthz continuously are unhealthy, kubeadm will error out after a period of exponential backoff\nfunc (w *KubeWaiter) WaitForKubeletAndFunc(f func() error) error {\n\terrorChan := make(chan error, 1)\n\n\tgo func(errC chan error, waiter Waiter) {\n\t\tif err := waiter.WaitForHealthyKubelet(40*time.Second, fmt.Sprintf(\"http://localhost:%d/healthz\", kubeadmconstants.KubeletHealthzPort)); err != nil {\n\t\t\terrC \u003c- err\n\t\t}\n\t}(errorChan, w)\n\n\tgo func(errC chan error) {\n\t\t// This main goroutine sends whatever the f function returns (error or not) to the channel\n\t\t// This in order to continue on success (nil error), or just fail if the function returns an error\n\t\terrC \u003c- f()\n\t}(errorChan)\n\n\t// This call is blocking until one of the goroutines sends to errorChan\n\treturn \u003c-errorChan\n}","line":{"from":158,"to":177}} {"id":100001243,"name":"SetTimeout","signature":"func (w *KubeWaiter) SetTimeout(timeout time.Duration)","file":"cmd/kubeadm/app/util/apiclient/wait.go","code":"// SetTimeout adjusts the timeout to the specified duration\nfunc (w *KubeWaiter) SetTimeout(timeout time.Duration) {\n\tw.timeout = timeout\n}","line":{"from":179,"to":182}} {"id":100001244,"name":"WaitForStaticPodControlPlaneHashes","signature":"func (w *KubeWaiter) WaitForStaticPodControlPlaneHashes(nodeName string) (map[string]string, error)","file":"cmd/kubeadm/app/util/apiclient/wait.go","code":"// WaitForStaticPodControlPlaneHashes blocks until it timeouts or gets a hash map for all components and their Static Pods\nfunc (w *KubeWaiter) WaitForStaticPodControlPlaneHashes(nodeName string) (map[string]string, error) {\n\n\tcomponentHash := \"\"\n\tvar err, lastErr error\n\tmirrorPodHashes := map[string]string{}\n\tfor _, component := range kubeadmconstants.ControlPlaneComponents {\n\t\terr = wait.PollImmediate(kubeadmconstants.APICallRetryInterval, w.timeout, func() (bool, error) {\n\t\t\tcomponentHash, err = getStaticPodSingleHash(w.client, nodeName, component)\n\t\t\tif err != nil {\n\t\t\t\tlastErr = err\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn true, nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, lastErr\n\t\t}\n\t\tmirrorPodHashes[component] = componentHash\n\t}\n\n\treturn mirrorPodHashes, nil\n}","line":{"from":184,"to":206}} {"id":100001245,"name":"WaitForStaticPodSingleHash","signature":"func (w *KubeWaiter) WaitForStaticPodSingleHash(nodeName string, component string) (string, error)","file":"cmd/kubeadm/app/util/apiclient/wait.go","code":"// WaitForStaticPodSingleHash blocks until it timeouts or gets a hash for a single component and its Static Pod\nfunc (w *KubeWaiter) WaitForStaticPodSingleHash(nodeName string, component string) (string, error) {\n\n\tcomponentPodHash := \"\"\n\tvar err, lastErr error\n\terr = wait.PollImmediate(kubeadmconstants.APICallRetryInterval, w.timeout, func() (bool, error) {\n\t\tcomponentPodHash, err = getStaticPodSingleHash(w.client, nodeName, component)\n\t\tif err != nil {\n\t\t\tlastErr = err\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\terr = lastErr\n\t}\n\treturn componentPodHash, err\n}","line":{"from":208,"to":226}} {"id":100001246,"name":"WaitForStaticPodHashChange","signature":"func (w *KubeWaiter) WaitForStaticPodHashChange(nodeName, component, previousHash string) error","file":"cmd/kubeadm/app/util/apiclient/wait.go","code":"// WaitForStaticPodHashChange blocks until it timeouts or notices that the Mirror Pod (for the Static Pod, respectively) has changed\n// This implicitly means this function blocks until the kubelet has restarted the Static Pod in question\nfunc (w *KubeWaiter) WaitForStaticPodHashChange(nodeName, component, previousHash string) error {\n\tvar err, lastErr error\n\terr = wait.PollImmediate(kubeadmconstants.APICallRetryInterval, w.timeout, func() (bool, error) {\n\t\thash, err := getStaticPodSingleHash(w.client, nodeName, component)\n\t\tif err != nil {\n\t\t\tlastErr = err\n\t\t\treturn false, nil\n\t\t}\n\t\t// Set lastErr to nil to be able to later distinguish between getStaticPodSingleHash() and timeout errors\n\t\tlastErr = nil\n\t\t// We should continue polling until the UID changes\n\t\tif hash == previousHash {\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn true, nil\n\t})\n\n\t// If lastError is not nil, this must be a getStaticPodSingleHash() error, else if err is not nil there was a poll timeout\n\tif lastErr != nil {\n\t\treturn lastErr\n\t}\n\treturn errors.Wrapf(err, \"static Pod hash for component %s on Node %s did not change after %v\", component, nodeName, w.timeout)\n}","line":{"from":228,"to":253}} {"id":100001247,"name":"getStaticPodSingleHash","signature":"func getStaticPodSingleHash(client clientset.Interface, nodeName string, component string) (string, error)","file":"cmd/kubeadm/app/util/apiclient/wait.go","code":"// getStaticPodSingleHash computes hashes for a single Static Pod resource\nfunc getStaticPodSingleHash(client clientset.Interface, nodeName string, component string) (string, error) {\n\n\tstaticPodName := fmt.Sprintf(\"%s-%s\", component, nodeName)\n\tstaticPod, err := client.CoreV1().Pods(metav1.NamespaceSystem).Get(context.TODO(), staticPodName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"failed to obtain static Pod hash for component %s on Node %s\", component, nodeName)\n\t}\n\n\tstaticPodHash := staticPod.Annotations[\"kubernetes.io/config.hash\"]\n\treturn staticPodHash, nil\n}","line":{"from":255,"to":266}} {"id":100001248,"name":"TryRunCommand","signature":"func TryRunCommand(f func() error, failureThreshold int) error","file":"cmd/kubeadm/app/util/apiclient/wait.go","code":"// TryRunCommand runs a function a maximum of failureThreshold times, and retries on error. If failureThreshold is hit; the last error is returned\nfunc TryRunCommand(f func() error, failureThreshold int) error {\n\tbackoff := wait.Backoff{\n\t\tDuration: 5 * time.Second,\n\t\tFactor: 2, // double the timeout for every failure\n\t\tSteps: failureThreshold,\n\t}\n\treturn wait.ExponentialBackoff(backoff, func() (bool, error) {\n\t\terr := f()\n\t\tif err != nil {\n\t\t\t// Retry until the timeout\n\t\t\treturn false, nil\n\t\t}\n\t\t// The last f() call was a success, return cleanly\n\t\treturn true, nil\n\t})\n}","line":{"from":268,"to":284}} {"id":100001249,"name":"BuildArgumentListFromMap","signature":"func BuildArgumentListFromMap(baseArguments map[string]string, overrideArguments map[string]string) []string","file":"cmd/kubeadm/app/util/arguments.go","code":"// BuildArgumentListFromMap takes two string-string maps, one with the base arguments and one\n// with optional override arguments. In the return list override arguments will precede base\n// arguments\nfunc BuildArgumentListFromMap(baseArguments map[string]string, overrideArguments map[string]string) []string {\n\tvar command []string\n\tvar keys []string\n\n\targsMap := make(map[string]string)\n\n\tfor k, v := range baseArguments {\n\t\targsMap[k] = v\n\t}\n\n\tfor k, v := range overrideArguments {\n\t\targsMap[k] = v\n\t}\n\n\tfor k := range argsMap {\n\t\tkeys = append(keys, k)\n\t}\n\n\tsort.Strings(keys)\n\tfor _, k := range keys {\n\t\tcommand = append(command, fmt.Sprintf(\"--%s=%s\", k, argsMap[k]))\n\t}\n\n\treturn command\n}","line":{"from":29,"to":56}} {"id":100001250,"name":"ParseArgumentListToMap","signature":"func ParseArgumentListToMap(arguments []string) map[string]string","file":"cmd/kubeadm/app/util/arguments.go","code":"// ParseArgumentListToMap parses a CLI argument list in the form \"--foo=bar\" to a string-string map\nfunc ParseArgumentListToMap(arguments []string) map[string]string {\n\tresultingMap := map[string]string{}\n\tfor i, arg := range arguments {\n\t\tkey, val, err := parseArgument(arg)\n\n\t\t// Ignore if the first argument doesn't satisfy the criteria, it's most often the binary name\n\t\t// Warn in all other cases, but don't error out. This can happen only if the user has edited the argument list by hand, so they might know what they are doing\n\t\tif err != nil {\n\t\t\tif i != 0 {\n\t\t\t\tklog.Warningf(\"[kubeadm] WARNING: The component argument %q could not be parsed correctly. The argument must be of the form %q. Skipping...\\n\", arg, \"--\")\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tresultingMap[key] = val\n\t}\n\treturn resultingMap\n}","line":{"from":58,"to":76}} {"id":100001251,"name":"ReplaceArgument","signature":"func ReplaceArgument(command []string, argMutateFunc func(map[string]string) map[string]string) []string","file":"cmd/kubeadm/app/util/arguments.go","code":"// ReplaceArgument gets a command list; converts it to a map for easier modification, runs the provided function that\n// returns a new modified map, and then converts the map back to a command string slice\nfunc ReplaceArgument(command []string, argMutateFunc func(map[string]string) map[string]string) []string {\n\targMap := ParseArgumentListToMap(command)\n\n\t// Save the first command (the executable) if we're sure it's not an argument (i.e. no --)\n\tvar newCommand []string\n\tif len(command) \u003e 0 \u0026\u0026 !strings.HasPrefix(command[0], \"--\") {\n\t\tnewCommand = append(newCommand, command[0])\n\t}\n\tnewArgMap := argMutateFunc(argMap)\n\tnewCommand = append(newCommand, BuildArgumentListFromMap(newArgMap, map[string]string{})...)\n\treturn newCommand\n}","line":{"from":78,"to":91}} {"id":100001252,"name":"parseArgument","signature":"func parseArgument(arg string) (string, string, error)","file":"cmd/kubeadm/app/util/arguments.go","code":"// parseArgument parses the argument \"--foo=bar\" to \"foo\" and \"bar\"\nfunc parseArgument(arg string) (string, string, error) {\n\tif !strings.HasPrefix(arg, \"--\") {\n\t\treturn \"\", \"\", errors.New(\"the argument should start with '--'\")\n\t}\n\tif !strings.Contains(arg, \"=\") {\n\t\treturn \"\", \"\", errors.New(\"the argument should have a '=' between the flag and the value\")\n\t}\n\t// Remove the starting --\n\targ = strings.TrimPrefix(arg, \"--\")\n\t// Split the string on =. Return only two substrings, since we want only key/value, but the value can include '=' as well\n\tkeyvalSlice := strings.SplitN(arg, \"=\", 2)\n\n\t// Make sure both a key and value is present\n\tif len(keyvalSlice) != 2 {\n\t\treturn \"\", \"\", errors.New(\"the argument must have both a key and a value\")\n\t}\n\tif len(keyvalSlice[0]) == 0 {\n\t\treturn \"\", \"\", errors.New(\"the argument must have a key\")\n\t}\n\n\treturn keyvalSlice[0], keyvalSlice[1], nil\n}","line":{"from":93,"to":115}} {"id":100001253,"name":"SetupCertificateAuthority","signature":"func SetupCertificateAuthority(t *testing.T) (*x509.Certificate, crypto.Signer)","file":"cmd/kubeadm/app/util/certs/util.go","code":"// SetupCertificateAuthority is a utility function for kubeadm testing that creates a\n// CertificateAuthority cert/key pair\nfunc SetupCertificateAuthority(t *testing.T) (*x509.Certificate, crypto.Signer) {\n\tcaCert, caKey, err := pkiutil.NewCertificateAuthority(\u0026pkiutil.CertConfig{\n\t\tConfig: certutil.Config{CommonName: \"kubernetes\"},\n\t})\n\tif err != nil {\n\t\tt.Fatalf(\"failure while generating CA certificate and key: %v\", err)\n\t}\n\n\treturn caCert, caKey\n}","line":{"from":33,"to":44}} {"id":100001254,"name":"AssertCertificateIsSignedByCa","signature":"func AssertCertificateIsSignedByCa(t *testing.T, cert *x509.Certificate, signingCa *x509.Certificate)","file":"cmd/kubeadm/app/util/certs/util.go","code":"// AssertCertificateIsSignedByCa is a utility function for kubeadm testing that asserts if a given certificate is signed\n// by the expected CA\nfunc AssertCertificateIsSignedByCa(t *testing.T, cert *x509.Certificate, signingCa *x509.Certificate) {\n\tif err := cert.CheckSignatureFrom(signingCa); err != nil {\n\t\tt.Error(\"cert is not signed by signing CA as expected\")\n\t}\n}","line":{"from":46,"to":52}} {"id":100001255,"name":"AssertCertificateHasCommonName","signature":"func AssertCertificateHasCommonName(t *testing.T, cert *x509.Certificate, commonName string)","file":"cmd/kubeadm/app/util/certs/util.go","code":"// AssertCertificateHasCommonName is a utility function for kubeadm testing that asserts if a given certificate has\n// the expected SubjectCommonName\nfunc AssertCertificateHasCommonName(t *testing.T, cert *x509.Certificate, commonName string) {\n\tif cert.Subject.CommonName != commonName {\n\t\tt.Errorf(\"cert has Subject.CommonName %s, expected %s\", cert.Subject.CommonName, commonName)\n\t}\n}","line":{"from":54,"to":60}} {"id":100001256,"name":"AssertCertificateHasOrganizations","signature":"func AssertCertificateHasOrganizations(t *testing.T, cert *x509.Certificate, organizations ...string)","file":"cmd/kubeadm/app/util/certs/util.go","code":"// AssertCertificateHasOrganizations is a utility function for kubeadm testing that asserts if a given certificate has\n// the expected Subject.Organization\nfunc AssertCertificateHasOrganizations(t *testing.T, cert *x509.Certificate, organizations ...string) {\n\tfor _, organization := range organizations {\n\t\tfound := false\n\t\tfor i := range cert.Subject.Organization {\n\t\t\tif cert.Subject.Organization[i] == organization {\n\t\t\t\tfound = true\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tt.Errorf(\"cert does not contain Subject.Organization %s as expected\", organization)\n\t\t}\n\t}\n}","line":{"from":62,"to":76}} {"id":100001257,"name":"AssertCertificateHasClientAuthUsage","signature":"func AssertCertificateHasClientAuthUsage(t *testing.T, cert *x509.Certificate)","file":"cmd/kubeadm/app/util/certs/util.go","code":"// AssertCertificateHasClientAuthUsage is a utility function for kubeadm testing that asserts if a given certificate has\n// the expected ExtKeyUsageClientAuth\nfunc AssertCertificateHasClientAuthUsage(t *testing.T, cert *x509.Certificate) {\n\tfor i := range cert.ExtKeyUsage {\n\t\tif cert.ExtKeyUsage[i] == x509.ExtKeyUsageClientAuth {\n\t\t\treturn\n\t\t}\n\t}\n\tt.Error(\"cert has not ClientAuth usage as expected\")\n}","line":{"from":78,"to":87}} {"id":100001258,"name":"AssertCertificateHasServerAuthUsage","signature":"func AssertCertificateHasServerAuthUsage(t *testing.T, cert *x509.Certificate)","file":"cmd/kubeadm/app/util/certs/util.go","code":"// AssertCertificateHasServerAuthUsage is a utility function for kubeadm testing that asserts if a given certificate has\n// the expected ExtKeyUsageServerAuth\nfunc AssertCertificateHasServerAuthUsage(t *testing.T, cert *x509.Certificate) {\n\tfor i := range cert.ExtKeyUsage {\n\t\tif cert.ExtKeyUsage[i] == x509.ExtKeyUsageServerAuth {\n\t\t\treturn\n\t\t}\n\t}\n\tt.Error(\"cert is not a ServerAuth\")\n}","line":{"from":89,"to":98}} {"id":100001259,"name":"AssertCertificateHasDNSNames","signature":"func AssertCertificateHasDNSNames(t *testing.T, cert *x509.Certificate, DNSNames ...string)","file":"cmd/kubeadm/app/util/certs/util.go","code":"// AssertCertificateHasDNSNames is a utility function for kubeadm testing that asserts if a given certificate has\n// the expected DNSNames\nfunc AssertCertificateHasDNSNames(t *testing.T, cert *x509.Certificate, DNSNames ...string) {\n\tfor _, DNSName := range DNSNames {\n\t\tfound := false\n\t\tfor _, val := range cert.DNSNames {\n\t\t\tif val == DNSName {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\tt.Errorf(\"cert does not contain DNSName %s\", DNSName)\n\t\t}\n\t}\n}","line":{"from":100,"to":116}} {"id":100001260,"name":"AssertCertificateHasIPAddresses","signature":"func AssertCertificateHasIPAddresses(t *testing.T, cert *x509.Certificate, IPAddresses ...net.IP)","file":"cmd/kubeadm/app/util/certs/util.go","code":"// AssertCertificateHasIPAddresses is a utility function for kubeadm testing that asserts if a given certificate has\n// the expected IPAddresses\nfunc AssertCertificateHasIPAddresses(t *testing.T, cert *x509.Certificate, IPAddresses ...net.IP) {\n\tfor _, IPAddress := range IPAddresses {\n\t\tfound := false\n\t\tfor _, val := range cert.IPAddresses {\n\t\t\tif val.Equal(IPAddress) {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\tt.Errorf(\"cert does not contain IPAddress %s\", IPAddress)\n\t\t}\n\t}\n}","line":{"from":118,"to":134}} {"id":100001261,"name":"CreateCACert","signature":"func CreateCACert(t *testing.T) (*x509.Certificate, crypto.Signer)","file":"cmd/kubeadm/app/util/certs/util.go","code":"// CreateCACert creates a generic CA cert.\nfunc CreateCACert(t *testing.T) (*x509.Certificate, crypto.Signer) {\n\tcertCfg := \u0026pkiutil.CertConfig{Config: certutil.Config{CommonName: \"kubernetes\"}}\n\tcert, key, err := pkiutil.NewCertificateAuthority(certCfg)\n\tif err != nil {\n\t\tt.Fatalf(\"couldn't create CA: %v\", err)\n\t}\n\treturn cert, key\n}","line":{"from":136,"to":144}} {"id":100001262,"name":"CreateTestCert","signature":"func CreateTestCert(t *testing.T, caCert *x509.Certificate, caKey crypto.Signer, altNames certutil.AltNames) (*x509.Certificate, crypto.Signer, *pkiutil.CertConfig)","file":"cmd/kubeadm/app/util/certs/util.go","code":"// CreateTestCert makes a generic certificate with the given CA and alternative names.\nfunc CreateTestCert(t *testing.T, caCert *x509.Certificate, caKey crypto.Signer, altNames certutil.AltNames) (*x509.Certificate, crypto.Signer, *pkiutil.CertConfig) {\n\tconfig := \u0026pkiutil.CertConfig{\n\t\tConfig: certutil.Config{\n\t\t\tCommonName: \"testCert\",\n\t\t\tUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},\n\t\t\tAltNames: altNames,\n\t\t},\n\t}\n\tcert, key, err := pkiutil.NewCertAndKey(caCert, caKey, config)\n\tif err != nil {\n\t\tt.Fatalf(\"couldn't create test cert: %v\", err)\n\t}\n\treturn cert, key, config\n}","line":{"from":146,"to":160}} {"id":100001263,"name":"GetSparseCertTestCases","signature":"func GetSparseCertTestCases(t *testing.T) []CertTestCase","file":"cmd/kubeadm/app/util/certs/util.go","code":"// GetSparseCertTestCases produces a series of cert configurations and their intended outcomes.\nfunc GetSparseCertTestCases(t *testing.T) []CertTestCase {\n\n\tcaCert, caKey := CreateCACert(t)\n\tfpCACert, fpCAKey := CreateCACert(t)\n\tetcdCACert, etcdCAKey := CreateCACert(t)\n\n\tfpCert, fpKey, _ := CreateTestCert(t, fpCACert, fpCAKey, certutil.AltNames{})\n\n\treturn []CertTestCase{\n\t\t{\n\t\t\tName: \"nothing present\",\n\t\t},\n\t\t{\n\t\t\tName: \"CAs already exist\",\n\t\t\tFiles: PKIFiles{\n\t\t\t\t\"ca.crt\": caCert,\n\t\t\t\t\"ca.key\": caKey,\n\t\t\t\t\"front-proxy-ca.crt\": fpCACert,\n\t\t\t\t\"front-proxy-ca.key\": fpCAKey,\n\t\t\t\t\"etcd/ca.crt\": etcdCACert,\n\t\t\t\t\"etcd/ca.key\": etcdCAKey,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"CA certs only\",\n\t\t\tFiles: PKIFiles{\n\t\t\t\t\"ca.crt\": caCert,\n\t\t\t\t\"front-proxy-ca.crt\": fpCACert,\n\t\t\t\t\"etcd/ca.crt\": etcdCACert,\n\t\t\t},\n\t\t\tExpectError: true,\n\t\t},\n\t\t{\n\t\t\tName: \"FrontProxyCA with certs\",\n\t\t\tFiles: PKIFiles{\n\t\t\t\t\"ca.crt\": caCert,\n\t\t\t\t\"ca.key\": caKey,\n\t\t\t\t\"front-proxy-ca.crt\": fpCACert,\n\t\t\t\t\"front-proxy-client.crt\": fpCert,\n\t\t\t\t\"front-proxy-client.key\": fpKey,\n\t\t\t\t\"etcd/ca.crt\": etcdCACert,\n\t\t\t\t\"etcd/ca.key\": etcdCAKey,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"FrontProxy certs missing CA\",\n\t\t\tFiles: PKIFiles{\n\t\t\t\t\"front-proxy-client.crt\": fpCert,\n\t\t\t\t\"front-proxy-client.key\": fpKey,\n\t\t\t},\n\t\t\tExpectError: true,\n\t\t},\n\t}\n}","line":{"from":169,"to":223}} {"id":100001264,"name":"WritePKIFiles","signature":"func WritePKIFiles(t *testing.T, dir string, files PKIFiles)","file":"cmd/kubeadm/app/util/certs/util.go","code":"// WritePKIFiles writes the given files out to the given directory\nfunc WritePKIFiles(t *testing.T, dir string, files PKIFiles) {\n\tfor filename, body := range files {\n\t\tswitch body := body.(type) {\n\t\tcase *x509.Certificate:\n\t\t\tif err := certutil.WriteCert(path.Join(dir, filename), pkiutil.EncodeCertPEM(body)); err != nil {\n\t\t\t\tt.Errorf(\"unable to write certificate to file %q: [%v]\", dir, err)\n\t\t\t}\n\t\tcase *rsa.PublicKey:\n\t\t\tpublicKeyBytes, err := pkiutil.EncodePublicKeyPEM(body)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"unable to write public key to file %q: [%v]\", filename, err)\n\t\t\t}\n\t\t\tif err := keyutil.WriteKey(path.Join(dir, filename), publicKeyBytes); err != nil {\n\t\t\t\tt.Errorf(\"unable to write public key to file %q: [%v]\", filename, err)\n\t\t\t}\n\t\tcase *rsa.PrivateKey:\n\t\t\tprivateKey, err := keyutil.MarshalPrivateKeyToPEM(body)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"unable to write private key to file %q: [%v]\", filename, err)\n\t\t\t}\n\t\t\tif err := keyutil.WriteKey(path.Join(dir, filename), privateKey); err != nil {\n\t\t\t\tt.Errorf(\"unable to write private key to file %q: [%v]\", filename, err)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":228,"to":254}} {"id":100001265,"name":"Chroot","signature":"func Chroot(rootfs string) error","file":"cmd/kubeadm/app/util/chroot_unix.go","code":"// Chroot chroot()s to the new path.\n// NB: All file paths after this call are effectively relative to\n// `rootfs`\nfunc Chroot(rootfs string) error {\n\tif err := syscall.Chroot(rootfs); err != nil {\n\t\treturn errors.Wrapf(err, \"unable to chroot to %s\", rootfs)\n\t}\n\troot := filepath.FromSlash(\"/\")\n\tif err := os.Chdir(root); err != nil {\n\t\treturn errors.Wrapf(err, \"unable to chdir to %s\", root)\n\t}\n\treturn nil\n}","line":{"from":30,"to":42}} {"id":100001266,"name":"Chroot","signature":"func Chroot(rootfs string) error","file":"cmd/kubeadm/app/util/chroot_windows.go","code":"// Chroot chroot()s to the new path.\n// NB: All file paths after this call are effectively relative to\n// `rootfs`\nfunc Chroot(rootfs string) error {\n\treturn errors.New(\"chroot is not implemented on Windows\")\n}","line":{"from":26,"to":31}} {"id":100001267,"name":"FetchInitConfigurationFromCluster","signature":"func FetchInitConfigurationFromCluster(client clientset.Interface, printer output.Printer, logPrefix string, newControlPlane, skipComponentConfigs bool) (*kubeadmapi.InitConfiguration, error)","file":"cmd/kubeadm/app/util/config/cluster.go","code":"// FetchInitConfigurationFromCluster fetches configuration from a ConfigMap in the cluster\nfunc FetchInitConfigurationFromCluster(client clientset.Interface, printer output.Printer, logPrefix string, newControlPlane, skipComponentConfigs bool) (*kubeadmapi.InitConfiguration, error) {\n\tif printer == nil {\n\t\tprinter = \u0026output.TextPrinter{}\n\t}\n\tprinter.Printf(\"[%s] Reading configuration from the cluster...\\n\", logPrefix)\n\tprinter.Printf(\"[%s] FYI: You can look at this config file with 'kubectl -n %s get cm %s -o yaml'\\n\", logPrefix, metav1.NamespaceSystem, constants.KubeadmConfigConfigMap)\n\n\t// Fetch the actual config from cluster\n\tcfg, err := getInitConfigurationFromCluster(constants.KubernetesDir, client, newControlPlane, skipComponentConfigs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Apply dynamic defaults\n\tif err := SetInitDynamicDefaults(cfg); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cfg, nil\n}","line":{"from":47,"to":67}} {"id":100001268,"name":"getInitConfigurationFromCluster","signature":"func getInitConfigurationFromCluster(kubeconfigDir string, client clientset.Interface, newControlPlane, skipComponentConfigs bool) (*kubeadmapi.InitConfiguration, error)","file":"cmd/kubeadm/app/util/config/cluster.go","code":"// getInitConfigurationFromCluster is separate only for testing purposes, don't call it directly, use FetchInitConfigurationFromCluster instead\nfunc getInitConfigurationFromCluster(kubeconfigDir string, client clientset.Interface, newControlPlane, skipComponentConfigs bool) (*kubeadmapi.InitConfiguration, error) {\n\t// Also, the config map really should be KubeadmConfigConfigMap...\n\tconfigMap, err := apiclient.GetConfigMapWithRetry(client, metav1.NamespaceSystem, constants.KubeadmConfigConfigMap)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get config map\")\n\t}\n\n\t// Take an empty versioned InitConfiguration, statically default it and convert it to the internal type\n\tversionedInitcfg := \u0026kubeadmapiv1.InitConfiguration{}\n\tkubeadmscheme.Scheme.Default(versionedInitcfg)\n\tinitcfg := \u0026kubeadmapi.InitConfiguration{}\n\tif err := kubeadmscheme.Scheme.Convert(versionedInitcfg, initcfg, nil); err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not prepare a defaulted InitConfiguration\")\n\t}\n\n\t// gets ClusterConfiguration from kubeadm-config\n\tclusterConfigurationData, ok := configMap.Data[constants.ClusterConfigurationConfigMapKey]\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"unexpected error when reading kubeadm-config ConfigMap: %s key value pair missing\", constants.ClusterConfigurationConfigMapKey)\n\t}\n\t// If ClusterConfiguration was patched by something other than kubeadm, it may have errors. Warn about them.\n\tif err := strict.VerifyUnmarshalStrict([]*runtime.Scheme{kubeadmscheme.Scheme},\n\t\tkubeadmapiv1.SchemeGroupVersion.WithKind(constants.ClusterConfigurationKind),\n\t\t[]byte(clusterConfigurationData)); err != nil {\n\t\tklog.Warning(err.Error())\n\t}\n\tif err := runtime.DecodeInto(kubeadmscheme.Codecs.UniversalDecoder(), []byte(clusterConfigurationData), \u0026initcfg.ClusterConfiguration); err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to decode cluster configuration data\")\n\t}\n\n\tif !skipComponentConfigs {\n\t\t// get the component configs from the corresponding config maps\n\t\tif err := componentconfigs.FetchFromCluster(\u0026initcfg.ClusterConfiguration, client); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to get component configs\")\n\t\t}\n\t}\n\n\t// if this isn't a new controlplane instance (e.g. in case of kubeadm upgrades)\n\t// get nodes specific information as well\n\tif !newControlPlane {\n\t\t// gets the nodeRegistration for the current from the node object\n\t\tkubeconfigFile := filepath.Join(kubeconfigDir, constants.KubeletKubeConfigFileName)\n\t\tif err := GetNodeRegistration(kubeconfigFile, client, \u0026initcfg.NodeRegistration); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to get node registration\")\n\t\t}\n\t\t// gets the APIEndpoint for the current node\n\t\tif err := getAPIEndpoint(client, initcfg.NodeRegistration.Name, \u0026initcfg.LocalAPIEndpoint); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to getAPIEndpoint\")\n\t\t}\n\t} else {\n\t\t// In the case where newControlPlane is true we don't go through getNodeRegistration() and initcfg.NodeRegistration.CRISocket is empty.\n\t\t// This forces DetectCRISocket() to be called later on, and if there is more than one CRI installed on the system, it will error out,\n\t\t// while asking for the user to provide an override for the CRI socket. Even if the user provides an override, the call to\n\t\t// DetectCRISocket() can happen too early and thus ignore it (while still erroring out).\n\t\t// However, if newControlPlane == true, initcfg.NodeRegistration is not used at all and it's overwritten later on.\n\t\t// Thus it's necessary to supply some default value, that will avoid the call to DetectCRISocket() and as\n\t\t// initcfg.NodeRegistration is discarded, setting whatever value here is harmless.\n\t\tinitcfg.NodeRegistration.CRISocket = constants.UnknownCRISocket\n\t}\n\treturn initcfg, nil\n}","line":{"from":69,"to":130}} {"id":100001269,"name":"GetNodeRegistration","signature":"func GetNodeRegistration(kubeconfigFile string, client clientset.Interface, nodeRegistration *kubeadmapi.NodeRegistrationOptions) error","file":"cmd/kubeadm/app/util/config/cluster.go","code":"// GetNodeRegistration returns the nodeRegistration for the current node\nfunc GetNodeRegistration(kubeconfigFile string, client clientset.Interface, nodeRegistration *kubeadmapi.NodeRegistrationOptions) error {\n\t// gets the name of the current node\n\tnodeName, err := getNodeNameFromKubeletConfig(kubeconfigFile)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to get node name from kubelet config\")\n\t}\n\n\t// gets the corresponding node and retrieves attributes stored there.\n\tnode, err := client.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to get corresponding node\")\n\t}\n\n\tcriSocket, ok := node.ObjectMeta.Annotations[constants.AnnotationKubeadmCRISocket]\n\tif !ok {\n\t\treturn errors.Errorf(\"node %s doesn't have %s annotation\", nodeName, constants.AnnotationKubeadmCRISocket)\n\t}\n\n\t// returns the nodeRegistration attributes\n\tnodeRegistration.Name = nodeName\n\tnodeRegistration.CRISocket = criSocket\n\tnodeRegistration.Taints = node.Spec.Taints\n\t// NB. currently nodeRegistration.KubeletExtraArgs isn't stored at node level but only in the kubeadm-flags.env\n\t// that isn't modified during upgrades\n\t// in future we might reconsider this thus enabling changes to the kubeadm-flags.env during upgrades as well\n\treturn nil\n}","line":{"from":132,"to":159}} {"id":100001270,"name":"getNodeNameFromKubeletConfig","signature":"func getNodeNameFromKubeletConfig(fileName string) (string, error)","file":"cmd/kubeadm/app/util/config/cluster.go","code":"// getNodeNameFromKubeletConfig gets the node name from a kubelet config file\n// TODO: in future we want to switch to a more canonical way for doing this e.g. by having this\n// information in the local kubelet config.yaml\nfunc getNodeNameFromKubeletConfig(fileName string) (string, error) {\n\t// loads the kubelet.conf file\n\tconfig, err := clientcmd.LoadFromFile(fileName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// gets the info about the current user\n\tcurrentContext, exists := config.Contexts[config.CurrentContext]\n\tif !exists {\n\t\treturn \"\", errors.Errorf(\"invalid kubeconfig file %s: missing context %s\", fileName, config.CurrentContext)\n\t}\n\tauthInfo, exists := config.AuthInfos[currentContext.AuthInfo]\n\tif !exists {\n\t\treturn \"\", errors.Errorf(\"invalid kubeconfig file %s: missing AuthInfo %s\", fileName, currentContext.AuthInfo)\n\t}\n\n\t// gets the X509 certificate with current user credentials\n\tvar certs []*x509.Certificate\n\tif len(authInfo.ClientCertificateData) \u003e 0 {\n\t\t// if the config file uses an embedded x509 certificate (e.g. kubelet.conf created by kubeadm), parse it\n\t\tif certs, err = certutil.ParseCertsPEM(authInfo.ClientCertificateData); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t} else if len(authInfo.ClientCertificate) \u003e 0 {\n\t\t// if the config file links an external x509 certificate (e.g. kubelet.conf created by TLS bootstrap), load it\n\t\tif certs, err = certutil.CertsFromFile(authInfo.ClientCertificate); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t} else {\n\t\treturn \"\", errors.Errorf(\"invalid kubeconfig file %s. x509 certificate expected\", fileName)\n\t}\n\n\t// Safely pick the first one because the sender's certificate must come first in the list.\n\t// For details, see: https://www.rfc-editor.org/rfc/rfc4346#section-7.4.2\n\tcert := certs[0]\n\n\t// gets the node name from the certificate common name\n\treturn strings.TrimPrefix(cert.Subject.CommonName, constants.NodesUserPrefix), nil\n}","line":{"from":161,"to":203}} {"id":100001271,"name":"getAPIEndpoint","signature":"func getAPIEndpoint(client clientset.Interface, nodeName string, apiEndpoint *kubeadmapi.APIEndpoint) error","file":"cmd/kubeadm/app/util/config/cluster.go","code":"func getAPIEndpoint(client clientset.Interface, nodeName string, apiEndpoint *kubeadmapi.APIEndpoint) error {\n\treturn getAPIEndpointWithBackoff(client, nodeName, apiEndpoint, constants.StaticPodMirroringDefaultRetry)\n}","line":{"from":205,"to":207}} {"id":100001272,"name":"getAPIEndpointWithBackoff","signature":"func getAPIEndpointWithBackoff(client clientset.Interface, nodeName string, apiEndpoint *kubeadmapi.APIEndpoint, backoff wait.Backoff) error","file":"cmd/kubeadm/app/util/config/cluster.go","code":"func getAPIEndpointWithBackoff(client clientset.Interface, nodeName string, apiEndpoint *kubeadmapi.APIEndpoint, backoff wait.Backoff) error {\n\tvar err error\n\tvar errs []error\n\n\tif err = getAPIEndpointFromPodAnnotation(client, nodeName, apiEndpoint, backoff); err == nil {\n\t\treturn nil\n\t}\n\terrs = append(errs, errors.WithMessagef(err, \"could not retrieve API endpoints for node %q using pod annotations\", nodeName))\n\treturn errorsutil.NewAggregate(errs)\n}","line":{"from":209,"to":218}} {"id":100001273,"name":"getAPIEndpointFromPodAnnotation","signature":"func getAPIEndpointFromPodAnnotation(client clientset.Interface, nodeName string, apiEndpoint *kubeadmapi.APIEndpoint, backoff wait.Backoff) error","file":"cmd/kubeadm/app/util/config/cluster.go","code":"func getAPIEndpointFromPodAnnotation(client clientset.Interface, nodeName string, apiEndpoint *kubeadmapi.APIEndpoint, backoff wait.Backoff) error {\n\tvar rawAPIEndpoint string\n\tvar lastErr error\n\t// Let's tolerate some unexpected transient failures from the API server or load balancers. Also, if\n\t// static pods were not yet mirrored into the API server we want to wait for this propagation.\n\terr := wait.ExponentialBackoff(backoff, func() (bool, error) {\n\t\trawAPIEndpoint, lastErr = getRawAPIEndpointFromPodAnnotationWithoutRetry(client, nodeName)\n\t\treturn lastErr == nil, nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tparsedAPIEndpoint, err := kubeadmapi.APIEndpointFromString(rawAPIEndpoint)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"could not parse API endpoint for node %q\", nodeName)\n\t}\n\t*apiEndpoint = parsedAPIEndpoint\n\treturn nil\n}","line":{"from":220,"to":238}} {"id":100001274,"name":"getRawAPIEndpointFromPodAnnotationWithoutRetry","signature":"func getRawAPIEndpointFromPodAnnotationWithoutRetry(client clientset.Interface, nodeName string) (string, error)","file":"cmd/kubeadm/app/util/config/cluster.go","code":"func getRawAPIEndpointFromPodAnnotationWithoutRetry(client clientset.Interface, nodeName string) (string, error) {\n\tpodList, err := client.CoreV1().Pods(metav1.NamespaceSystem).List(\n\t\tcontext.TODO(),\n\t\tmetav1.ListOptions{\n\t\t\tFieldSelector: fmt.Sprintf(\"spec.nodeName=%s\", nodeName),\n\t\t\tLabelSelector: fmt.Sprintf(\"component=%s,tier=%s\", constants.KubeAPIServer, constants.ControlPlaneTier),\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"could not retrieve list of pods to determine api server endpoints\")\n\t}\n\tif len(podList.Items) != 1 {\n\t\treturn \"\", errors.Errorf(\"API server pod for node name %q has %d entries, only one was expected\", nodeName, len(podList.Items))\n\t}\n\tif apiServerEndpoint, ok := podList.Items[0].Annotations[constants.KubeAPIServerAdvertiseAddressEndpointAnnotationKey]; ok {\n\t\treturn apiServerEndpoint, nil\n\t}\n\treturn \"\", errors.Errorf(\"API server pod for node name %q hasn't got a %q annotation, cannot retrieve API endpoint\", nodeName, constants.KubeAPIServerAdvertiseAddressEndpointAnnotationKey)\n}","line":{"from":240,"to":258}} {"id":100001275,"name":"MarshalKubeadmConfigObject","signature":"func MarshalKubeadmConfigObject(obj runtime.Object) ([]byte, error)","file":"cmd/kubeadm/app/util/config/common.go","code":"// MarshalKubeadmConfigObject marshals an Object registered in the kubeadm scheme. If the object is a InitConfiguration or ClusterConfiguration, some extra logic is run\nfunc MarshalKubeadmConfigObject(obj runtime.Object) ([]byte, error) {\n\tswitch internalcfg := obj.(type) {\n\tcase *kubeadmapi.InitConfiguration:\n\t\treturn MarshalInitConfigurationToBytes(internalcfg, kubeadmapiv1.SchemeGroupVersion)\n\tdefault:\n\t\treturn kubeadmutil.MarshalToYamlForCodecs(obj, kubeadmapiv1.SchemeGroupVersion, kubeadmscheme.Codecs)\n\t}\n}","line":{"from":44,"to":52}} {"id":100001276,"name":"validateSupportedVersion","signature":"func validateSupportedVersion(gv schema.GroupVersion, allowDeprecated bool) error","file":"cmd/kubeadm/app/util/config/common.go","code":"// validateSupportedVersion checks if the supplied GroupVersion is not on the lists of old unsupported or deprecated GVs.\n// If it is, an error is returned.\nfunc validateSupportedVersion(gv schema.GroupVersion, allowDeprecated bool) error {\n\t// The support matrix will look something like this now and in the future:\n\t// v1.10 and earlier: v1alpha1\n\t// v1.11: v1alpha1 read-only, writes only v1alpha2 config\n\t// v1.12: v1alpha2 read-only, writes only v1alpha3 config. Errors if the user tries to use v1alpha1\n\t// v1.13: v1alpha3 read-only, writes only v1beta1 config. Errors if the user tries to use v1alpha1 or v1alpha2\n\t// v1.14: v1alpha3 convert only, writes only v1beta1 config. Errors if the user tries to use v1alpha1 or v1alpha2\n\t// v1.15: v1beta1 read-only, writes only v1beta2 config. Errors if the user tries to use v1alpha1, v1alpha2 or v1alpha3\n\t// v1.22: v1beta2 read-only, writes only v1beta3 config. Errors if the user tries to use v1beta1 and older\n\t// v1.27: only v1beta3 config. Errors if the user tries to use v1beta2 and older\n\toldKnownAPIVersions := map[string]string{\n\t\t\"kubeadm.k8s.io/v1alpha1\": \"v1.11\",\n\t\t\"kubeadm.k8s.io/v1alpha2\": \"v1.12\",\n\t\t\"kubeadm.k8s.io/v1alpha3\": \"v1.14\",\n\t\t\"kubeadm.k8s.io/v1beta1\": \"v1.15\",\n\t\t\"kubeadm.k8s.io/v1beta2\": \"v1.22\",\n\t}\n\n\t// Deprecated API versions are supported by us, but can only be used for migration.\n\tdeprecatedAPIVersions := map[string]struct{}{}\n\n\tgvString := gv.String()\n\n\tif useKubeadmVersion := oldKnownAPIVersions[gvString]; useKubeadmVersion != \"\" {\n\t\treturn errors.Errorf(\"your configuration file uses an old API spec: %q. Please use kubeadm %s instead and run 'kubeadm config migrate --old-config old.yaml --new-config new.yaml', which will write the new, similar spec using a newer API version.\", gv.String(), useKubeadmVersion)\n\t}\n\n\tif _, present := deprecatedAPIVersions[gvString]; present \u0026\u0026 !allowDeprecated {\n\t\tklog.Warningf(\"your configuration file uses a deprecated API spec: %q. Please use 'kubeadm config migrate --old-config old.yaml --new-config new.yaml', which will write the new, similar spec using a newer API version.\", gv)\n\t}\n\n\treturn nil\n}","line":{"from":54,"to":88}} {"id":100001277,"name":"NormalizeKubernetesVersion","signature":"func NormalizeKubernetesVersion(cfg *kubeadmapi.ClusterConfiguration) error","file":"cmd/kubeadm/app/util/config/common.go","code":"// NormalizeKubernetesVersion resolves version labels, sets alternative\n// image registry if requested for CI builds, and validates minimal\n// version that kubeadm SetInitDynamicDefaultssupports.\nfunc NormalizeKubernetesVersion(cfg *kubeadmapi.ClusterConfiguration) error {\n\tisCIVersion := kubeadmutil.KubernetesIsCIVersion(cfg.KubernetesVersion)\n\n\t// Requested version is automatic CI build, thus use KubernetesCI Image Repository for core images\n\tif isCIVersion \u0026\u0026 cfg.ImageRepository == kubeadmapiv1.DefaultImageRepository {\n\t\tcfg.CIImageRepository = constants.DefaultCIImageRepository\n\t}\n\n\t// Parse and validate the version argument and resolve possible CI version labels\n\tver, err := kubeadmutil.KubernetesReleaseVersion(cfg.KubernetesVersion)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Requested version is automatic CI build, thus mark CIKubernetesVersion as `ci/\u003cresolved-version\u003e`\n\tif isCIVersion {\n\t\tcfg.CIKubernetesVersion = fmt.Sprintf(\"%s%s\", constants.CIKubernetesVersionPrefix, ver)\n\t}\n\n\tcfg.KubernetesVersion = ver\n\n\t// Parse the given kubernetes version and make sure it's higher than the lowest supported\n\tk8sVersion, err := version.ParseSemantic(cfg.KubernetesVersion)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"couldn't parse Kubernetes version %q\", cfg.KubernetesVersion)\n\t}\n\n\t// During the k8s release process, a kubeadm version in the main branch could be 1.23.0-pre,\n\t// while the 1.22.0 version is not released yet. The MinimumControlPlaneVersion validation\n\t// in such a case will not pass, since the value of MinimumControlPlaneVersion would be\n\t// calculated as kubeadm version - 1 (1.22) and k8sVersion would still be at 1.21.x\n\t// (fetched from the 'stable' marker). Handle this case by only showing a warning.\n\tmcpVersion := constants.MinimumControlPlaneVersion\n\tversionInfo := componentversion.Get()\n\tif isKubeadmPrereleaseVersion(\u0026versionInfo, k8sVersion, mcpVersion) {\n\t\tklog.V(1).Infof(\"WARNING: tolerating control plane version %s as a pre-release version\", cfg.KubernetesVersion)\n\n\t\treturn nil\n\t}\n\t// If not a pre-release version, handle the validation normally.\n\tif k8sVersion.LessThan(mcpVersion) {\n\t\treturn errors.Errorf(\"this version of kubeadm only supports deploying clusters with the control plane version \u003e= %s. Current version: %s\",\n\t\t\tmcpVersion, cfg.KubernetesVersion)\n\t}\n\treturn nil\n}","line":{"from":90,"to":138}} {"id":100001278,"name":"LowercaseSANs","signature":"func LowercaseSANs(sans []string)","file":"cmd/kubeadm/app/util/config/common.go","code":"// LowercaseSANs can be used to force all SANs to be lowercase so it passes IsDNS1123Subdomain\nfunc LowercaseSANs(sans []string) {\n\tfor i, san := range sans {\n\t\tlowercase := strings.ToLower(san)\n\t\tif lowercase != san {\n\t\t\tklog.V(1).Infof(\"lowercasing SAN %q to %q\", san, lowercase)\n\t\t\tsans[i] = lowercase\n\t\t}\n\t}\n}","line":{"from":140,"to":149}} {"id":100001279,"name":"VerifyAPIServerBindAddress","signature":"func VerifyAPIServerBindAddress(address string) error","file":"cmd/kubeadm/app/util/config/common.go","code":"// VerifyAPIServerBindAddress can be used to verify if a bind address for the API Server is 0.0.0.0,\n// in which case this address is not valid and should not be used.\nfunc VerifyAPIServerBindAddress(address string) error {\n\tip := netutils.ParseIPSloppy(address)\n\tif ip == nil {\n\t\treturn errors.Errorf(\"cannot parse IP address: %s\", address)\n\t}\n\t// There are users with network setups where default routes are present, but network interfaces\n\t// use only link-local addresses (e.g. as described in RFC5549).\n\t// In many cases that matching global unicast IP address can be found on loopback interface,\n\t// so kubeadm allows users to specify address=Loopback for handling supporting the scenario above.\n\t// Nb. SetAPIEndpointDynamicDefaults will try to translate loopback to a valid address afterwards\n\tif ip.IsLoopback() {\n\t\treturn nil\n\t}\n\tif !ip.IsGlobalUnicast() {\n\t\treturn errors.Errorf(\"cannot use %q as the bind address for the API Server\", address)\n\t}\n\treturn nil\n}","line":{"from":151,"to":170}} {"id":100001280,"name":"ChooseAPIServerBindAddress","signature":"func ChooseAPIServerBindAddress(bindAddress net.IP) (net.IP, error)","file":"cmd/kubeadm/app/util/config/common.go","code":"// ChooseAPIServerBindAddress is a wrapper for netutil.ResolveBindAddress that also handles\n// the case where no default routes were found and an IP for the API server could not be obtained.\nfunc ChooseAPIServerBindAddress(bindAddress net.IP) (net.IP, error) {\n\tip, err := netutil.ResolveBindAddress(bindAddress)\n\tif err != nil {\n\t\tif netutil.IsNoRoutesError(err) {\n\t\t\tklog.Warningf(\"WARNING: could not obtain a bind address for the API Server: %v; using: %s\", err, constants.DefaultAPIServerBindAddress)\n\t\t\tdefaultIP := netutils.ParseIPSloppy(constants.DefaultAPIServerBindAddress)\n\t\t\tif defaultIP == nil {\n\t\t\t\treturn nil, errors.Errorf(\"cannot parse default IP address: %s\", constants.DefaultAPIServerBindAddress)\n\t\t\t}\n\t\t\treturn defaultIP, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\tif bindAddress != nil \u0026\u0026 !bindAddress.IsUnspecified() \u0026\u0026 !reflect.DeepEqual(ip, bindAddress) {\n\t\tklog.Warningf(\"WARNING: overriding requested API server bind address: requested %q, actual %q\", bindAddress, ip)\n\t}\n\treturn ip, nil\n}","line":{"from":172,"to":191}} {"id":100001281,"name":"MigrateOldConfig","signature":"func MigrateOldConfig(oldConfig []byte) ([]byte, error)","file":"cmd/kubeadm/app/util/config/common.go","code":"// MigrateOldConfig migrates an old configuration from a byte slice into a new one (returned again as a byte slice).\n// Only kubeadm kinds are migrated. Others are silently ignored.\nfunc MigrateOldConfig(oldConfig []byte) ([]byte, error) {\n\tnewConfig := [][]byte{}\n\n\tgvkmap, err := kubeadmutil.SplitYAMLDocuments(oldConfig)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\tgvks := []schema.GroupVersionKind{}\n\tfor gvk := range gvkmap {\n\t\tgvks = append(gvks, gvk)\n\t}\n\n\t// Migrate InitConfiguration and ClusterConfiguration if there are any in the config\n\tif kubeadmutil.GroupVersionKindsHasInitConfiguration(gvks...) || kubeadmutil.GroupVersionKindsHasClusterConfiguration(gvks...) {\n\t\to, err := documentMapToInitConfiguration(gvkmap, true)\n\t\tif err != nil {\n\t\t\treturn []byte{}, err\n\t\t}\n\t\tb, err := MarshalKubeadmConfigObject(o)\n\t\tif err != nil {\n\t\t\treturn []byte{}, err\n\t\t}\n\t\tnewConfig = append(newConfig, b)\n\t}\n\n\t// Migrate JoinConfiguration if there is any\n\tif kubeadmutil.GroupVersionKindsHasJoinConfiguration(gvks...) {\n\t\to, err := documentMapToJoinConfiguration(gvkmap, true)\n\t\tif err != nil {\n\t\t\treturn []byte{}, err\n\t\t}\n\t\tb, err := MarshalKubeadmConfigObject(o)\n\t\tif err != nil {\n\t\t\treturn []byte{}, err\n\t\t}\n\t\tnewConfig = append(newConfig, b)\n\t}\n\n\treturn bytes.Join(newConfig, []byte(constants.YAMLDocumentSeparator)), nil\n}","line":{"from":193,"to":235}} {"id":100001282,"name":"isKubeadmPrereleaseVersion","signature":"func isKubeadmPrereleaseVersion(versionInfo *apimachineryversion.Info, k8sVersion, mcpVersion *version.Version) bool","file":"cmd/kubeadm/app/util/config/common.go","code":"// isKubeadmPrereleaseVersion returns true if the kubeadm version is a pre-release version and\n// the minimum control plane version is N+2 MINOR version of the given k8sVersion.\nfunc isKubeadmPrereleaseVersion(versionInfo *apimachineryversion.Info, k8sVersion, mcpVersion *version.Version) bool {\n\tif len(versionInfo.Major) != 0 { // Make sure the component version is populated\n\t\tkubeadmVersion := version.MustParseSemantic(versionInfo.String())\n\t\tif len(kubeadmVersion.PreRelease()) != 0 { // Only handle this if the kubeadm binary is a pre-release\n\t\t\t// After incrementing the k8s MINOR version by one, if this version is equal or greater than the\n\t\t\t// MCP version, return true.\n\t\t\tv := k8sVersion.WithMinor(k8sVersion.Minor() + 1)\n\t\t\tif comp, _ := v.Compare(mcpVersion.String()); comp != -1 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":237,"to":252}} {"id":100001283,"name":"SetInitDynamicDefaults","signature":"func SetInitDynamicDefaults(cfg *kubeadmapi.InitConfiguration) error","file":"cmd/kubeadm/app/util/config/initconfiguration.go","code":"// SetInitDynamicDefaults checks and sets configuration values for the InitConfiguration object\nfunc SetInitDynamicDefaults(cfg *kubeadmapi.InitConfiguration) error {\n\tif err := SetBootstrapTokensDynamicDefaults(\u0026cfg.BootstrapTokens); err != nil {\n\t\treturn err\n\t}\n\tif err := SetNodeRegistrationDynamicDefaults(\u0026cfg.NodeRegistration, true); err != nil {\n\t\treturn err\n\t}\n\tif err := SetAPIEndpointDynamicDefaults(\u0026cfg.LocalAPIEndpoint); err != nil {\n\t\treturn err\n\t}\n\treturn SetClusterDynamicDefaults(\u0026cfg.ClusterConfiguration, \u0026cfg.LocalAPIEndpoint, \u0026cfg.NodeRegistration)\n}","line":{"from":59,"to":71}} {"id":100001284,"name":"SetBootstrapTokensDynamicDefaults","signature":"func SetBootstrapTokensDynamicDefaults(cfg *[]bootstraptokenv1.BootstrapToken) error","file":"cmd/kubeadm/app/util/config/initconfiguration.go","code":"// SetBootstrapTokensDynamicDefaults checks and sets configuration values for the BootstrapTokens object\nfunc SetBootstrapTokensDynamicDefaults(cfg *[]bootstraptokenv1.BootstrapToken) error {\n\t// Populate the .Token field with a random value if unset\n\t// We do this at this layer, and not the API defaulting layer\n\t// because of possible security concerns, and more practically\n\t// because we can't return errors in the API object defaulting\n\t// process but here we can.\n\tfor i, bt := range *cfg {\n\t\tif bt.Token != nil \u0026\u0026 len(bt.Token.String()) \u003e 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\ttokenStr, err := bootstraputil.GenerateBootstrapToken()\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"couldn't generate random token\")\n\t\t}\n\t\ttoken, err := bootstraptokenv1.NewBootstrapTokenString(tokenStr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t(*cfg)[i].Token = token\n\t}\n\n\treturn nil\n}","line":{"from":73,"to":97}} {"id":100001285,"name":"SetNodeRegistrationDynamicDefaults","signature":"func SetNodeRegistrationDynamicDefaults(cfg *kubeadmapi.NodeRegistrationOptions, controlPlaneTaint bool) error","file":"cmd/kubeadm/app/util/config/initconfiguration.go","code":"// SetNodeRegistrationDynamicDefaults checks and sets configuration values for the NodeRegistration object\nfunc SetNodeRegistrationDynamicDefaults(cfg *kubeadmapi.NodeRegistrationOptions, controlPlaneTaint bool) error {\n\tvar err error\n\tcfg.Name, err = nodeutil.GetHostname(cfg.Name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Only if the slice is nil, we should append the control-plane taint. This allows the user to specify an empty slice for no default control-plane taint\n\tif controlPlaneTaint \u0026\u0026 cfg.Taints == nil {\n\t\tcfg.Taints = []v1.Taint{kubeadmconstants.ControlPlaneTaint}\n\t}\n\n\tif cfg.CRISocket == \"\" {\n\t\tcfg.CRISocket, err = kubeadmruntime.DetectCRISocket()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tklog.V(1).Infof(\"detected and using CRI socket: %s\", cfg.CRISocket)\n\t} else {\n\t\tif !strings.HasPrefix(cfg.CRISocket, kubeadmapiv1.DefaultContainerRuntimeURLScheme) {\n\t\t\tklog.Warningf(\"Usage of CRI endpoints without URL scheme is deprecated and can cause kubelet errors \"+\n\t\t\t\t\"in the future. Automatically prepending scheme %q to the \\\"criSocket\\\" with value %q. \"+\n\t\t\t\t\"Please update your configuration!\", kubeadmapiv1.DefaultContainerRuntimeURLScheme, cfg.CRISocket)\n\t\t\tcfg.CRISocket = kubeadmapiv1.DefaultContainerRuntimeURLScheme + \"://\" + cfg.CRISocket\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":99,"to":128}} {"id":100001286,"name":"SetAPIEndpointDynamicDefaults","signature":"func SetAPIEndpointDynamicDefaults(cfg *kubeadmapi.APIEndpoint) error","file":"cmd/kubeadm/app/util/config/initconfiguration.go","code":"// SetAPIEndpointDynamicDefaults checks and sets configuration values for the APIEndpoint object\nfunc SetAPIEndpointDynamicDefaults(cfg *kubeadmapi.APIEndpoint) error {\n\t// validate cfg.API.AdvertiseAddress.\n\taddressIP := netutils.ParseIPSloppy(cfg.AdvertiseAddress)\n\tif addressIP == nil \u0026\u0026 cfg.AdvertiseAddress != \"\" {\n\t\treturn errors.Errorf(\"couldn't use \\\"%s\\\" as \\\"apiserver-advertise-address\\\", must be ipv4 or ipv6 address\", cfg.AdvertiseAddress)\n\t}\n\n\t// kubeadm allows users to specify address=Loopback as a selector for global unicast IP address that can be found on loopback interface.\n\t// e.g. This is required for network setups where default routes are present, but network interfaces use only link-local addresses (e.g. as described in RFC5549).\n\tif addressIP.IsLoopback() {\n\t\tloopbackIP, err := netutil.ChooseBindAddressForInterface(netutil.LoopbackInterfaceName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif loopbackIP != nil {\n\t\t\tklog.V(4).Infof(\"Found active IP %v on loopback interface\", loopbackIP.String())\n\t\t\tcfg.AdvertiseAddress = loopbackIP.String()\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.New(\"unable to resolve link-local addresses\")\n\t}\n\n\t// This is the same logic as the API Server uses, except that if no interface is found the address is set to 0.0.0.0, which is invalid and cannot be used\n\t// for bootstrapping a cluster.\n\tip, err := ChooseAPIServerBindAddress(addressIP)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcfg.AdvertiseAddress = ip.String()\n\n\treturn nil\n}","line":{"from":130,"to":162}} {"id":100001287,"name":"SetClusterDynamicDefaults","signature":"func SetClusterDynamicDefaults(cfg *kubeadmapi.ClusterConfiguration, localAPIEndpoint *kubeadmapi.APIEndpoint, nodeRegOpts *kubeadmapi.NodeRegistrationOptions) error","file":"cmd/kubeadm/app/util/config/initconfiguration.go","code":"// SetClusterDynamicDefaults checks and sets values for the ClusterConfiguration object\nfunc SetClusterDynamicDefaults(cfg *kubeadmapi.ClusterConfiguration, localAPIEndpoint *kubeadmapi.APIEndpoint, nodeRegOpts *kubeadmapi.NodeRegistrationOptions) error {\n\t// Default all the embedded ComponentConfig structs\n\tcomponentconfigs.Default(cfg, localAPIEndpoint, nodeRegOpts)\n\n\t// Resolve possible version labels and validate version string\n\tif err := NormalizeKubernetesVersion(cfg); err != nil {\n\t\treturn err\n\t}\n\n\t// If ControlPlaneEndpoint is specified without a port number defaults it to\n\t// the bindPort number of the APIEndpoint.\n\t// This will allow join of additional control plane instances with different bindPort number\n\tif cfg.ControlPlaneEndpoint != \"\" {\n\t\thost, port, err := kubeadmutil.ParseHostPort(cfg.ControlPlaneEndpoint)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif port == \"\" {\n\t\t\tcfg.ControlPlaneEndpoint = net.JoinHostPort(host, strconv.FormatInt(int64(localAPIEndpoint.BindPort), 10))\n\t\t}\n\t}\n\n\t// Downcase SANs. Some domain names (like ELBs) have capitals in them.\n\tLowercaseSANs(cfg.APIServer.CertSANs)\n\treturn nil\n}","line":{"from":164,"to":190}} {"id":100001288,"name":"DefaultedStaticInitConfiguration","signature":"func DefaultedStaticInitConfiguration() (*kubeadmapi.InitConfiguration, error)","file":"cmd/kubeadm/app/util/config/initconfiguration.go","code":"// DefaultedStaticInitConfiguration returns the internal InitConfiguration with static defaults.\nfunc DefaultedStaticInitConfiguration() (*kubeadmapi.InitConfiguration, error) {\n\tversionedInitCfg := \u0026kubeadmapiv1.InitConfiguration{\n\t\tLocalAPIEndpoint: kubeadmapiv1.APIEndpoint{AdvertiseAddress: \"1.2.3.4\"},\n\t\tBootstrapTokens: []bootstraptokenv1.BootstrapToken{PlaceholderToken},\n\t\tNodeRegistration: kubeadmapiv1.NodeRegistrationOptions{\n\t\t\tCRISocket: kubeadmconstants.DefaultCRISocket, // avoid CRI detection\n\t\t\tName: \"node\",\n\t\t},\n\t}\n\tversionedClusterCfg := \u0026kubeadmapiv1.ClusterConfiguration{\n\t\tKubernetesVersion: kubeadmconstants.CurrentKubernetesVersion.String(), // avoid going to the Internet for the current Kubernetes version\n\t}\n\n\tinternalcfg := \u0026kubeadmapi.InitConfiguration{}\n\n\t// Takes passed flags into account; the defaulting is executed once again enforcing assignment of\n\t// static default values to cfg only for values not provided with flags\n\tkubeadmscheme.Scheme.Default(versionedInitCfg)\n\tif err := kubeadmscheme.Scheme.Convert(versionedInitCfg, internalcfg, nil); err != nil {\n\t\treturn nil, err\n\t}\n\n\tkubeadmscheme.Scheme.Default(versionedClusterCfg)\n\tif err := kubeadmscheme.Scheme.Convert(versionedClusterCfg, \u0026internalcfg.ClusterConfiguration, nil); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Default all the embedded ComponentConfig structs\n\tcomponentconfigs.Default(\u0026internalcfg.ClusterConfiguration, \u0026internalcfg.LocalAPIEndpoint, \u0026internalcfg.NodeRegistration)\n\n\treturn internalcfg, nil\n}","line":{"from":192,"to":224}} {"id":100001289,"name":"DefaultedInitConfiguration","signature":"func DefaultedInitConfiguration(versionedInitCfg *kubeadmapiv1.InitConfiguration, versionedClusterCfg *kubeadmapiv1.ClusterConfiguration) (*kubeadmapi.InitConfiguration, error)","file":"cmd/kubeadm/app/util/config/initconfiguration.go","code":"// DefaultedInitConfiguration takes a versioned init config (often populated by flags), defaults it and converts it into internal InitConfiguration\nfunc DefaultedInitConfiguration(versionedInitCfg *kubeadmapiv1.InitConfiguration, versionedClusterCfg *kubeadmapiv1.ClusterConfiguration) (*kubeadmapi.InitConfiguration, error) {\n\tinternalcfg := \u0026kubeadmapi.InitConfiguration{}\n\n\t// Takes passed flags into account; the defaulting is executed once again enforcing assignment of\n\t// static default values to cfg only for values not provided with flags\n\tkubeadmscheme.Scheme.Default(versionedInitCfg)\n\tif err := kubeadmscheme.Scheme.Convert(versionedInitCfg, internalcfg, nil); err != nil {\n\t\treturn nil, err\n\t}\n\n\tkubeadmscheme.Scheme.Default(versionedClusterCfg)\n\tif err := kubeadmscheme.Scheme.Convert(versionedClusterCfg, \u0026internalcfg.ClusterConfiguration, nil); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Applies dynamic defaults to settings not provided with flags\n\tif err := SetInitDynamicDefaults(internalcfg); err != nil {\n\t\treturn nil, err\n\t}\n\t// Validates cfg (flags/configs + defaults + dynamic defaults)\n\tif err := validation.ValidateInitConfiguration(internalcfg).ToAggregate(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn internalcfg, nil\n}","line":{"from":226,"to":251}} {"id":100001290,"name":"LoadInitConfigurationFromFile","signature":"func LoadInitConfigurationFromFile(cfgPath string) (*kubeadmapi.InitConfiguration, error)","file":"cmd/kubeadm/app/util/config/initconfiguration.go","code":"// LoadInitConfigurationFromFile loads a supported versioned InitConfiguration from a file, converts it into internal config, defaults it and verifies it.\nfunc LoadInitConfigurationFromFile(cfgPath string) (*kubeadmapi.InitConfiguration, error) {\n\tklog.V(1).Infof(\"loading configuration from %q\", cfgPath)\n\n\tb, err := os.ReadFile(cfgPath)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to read config from %q \", cfgPath)\n\t}\n\n\treturn BytesToInitConfiguration(b)\n}","line":{"from":253,"to":263}} {"id":100001291,"name":"LoadOrDefaultInitConfiguration","signature":"func LoadOrDefaultInitConfiguration(cfgPath string, versionedInitCfg *kubeadmapiv1.InitConfiguration, versionedClusterCfg *kubeadmapiv1.ClusterConfiguration) (*kubeadmapi.InitConfiguration, error)","file":"cmd/kubeadm/app/util/config/initconfiguration.go","code":"// LoadOrDefaultInitConfiguration takes a path to a config file and a versioned configuration that can serve as the default config\n// If cfgPath is specified, the versioned configs will always get overridden with the one in the file (specified by cfgPath).\n// The external, versioned configuration is defaulted and converted to the internal type.\n// Right thereafter, the configuration is defaulted again with dynamic values (like IP addresses of a machine, etc)\n// Lastly, the internal config is validated and returned.\nfunc LoadOrDefaultInitConfiguration(cfgPath string, versionedInitCfg *kubeadmapiv1.InitConfiguration, versionedClusterCfg *kubeadmapiv1.ClusterConfiguration) (*kubeadmapi.InitConfiguration, error) {\n\tif cfgPath != \"\" {\n\t\t// Loads configuration from config file, if provided\n\t\t// Nb. --config overrides command line flags\n\t\treturn LoadInitConfigurationFromFile(cfgPath)\n\t}\n\n\treturn DefaultedInitConfiguration(versionedInitCfg, versionedClusterCfg)\n}","line":{"from":265,"to":278}} {"id":100001292,"name":"BytesToInitConfiguration","signature":"func BytesToInitConfiguration(b []byte) (*kubeadmapi.InitConfiguration, error)","file":"cmd/kubeadm/app/util/config/initconfiguration.go","code":"// BytesToInitConfiguration converts a byte slice to an internal, defaulted and validated InitConfiguration object.\n// The map may contain many different YAML documents. These YAML documents are parsed one-by-one\n// and well-known ComponentConfig GroupVersionKinds are stored inside of the internal InitConfiguration struct.\n// The resulting InitConfiguration is then dynamically defaulted and validated prior to return.\nfunc BytesToInitConfiguration(b []byte) (*kubeadmapi.InitConfiguration, error) {\n\tgvkmap, err := kubeadmutil.SplitYAMLDocuments(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn documentMapToInitConfiguration(gvkmap, false)\n}","line":{"from":280,"to":291}} {"id":100001293,"name":"documentMapToInitConfiguration","signature":"func documentMapToInitConfiguration(gvkmap kubeadmapi.DocumentMap, allowDeprecated bool) (*kubeadmapi.InitConfiguration, error)","file":"cmd/kubeadm/app/util/config/initconfiguration.go","code":"// documentMapToInitConfiguration converts a map of GVKs and YAML documents to defaulted and validated configuration object.\nfunc documentMapToInitConfiguration(gvkmap kubeadmapi.DocumentMap, allowDeprecated bool) (*kubeadmapi.InitConfiguration, error) {\n\tvar initcfg *kubeadmapi.InitConfiguration\n\tvar clustercfg *kubeadmapi.ClusterConfiguration\n\n\tfor gvk, fileContent := range gvkmap {\n\t\t// first, check if this GVK is supported and possibly not deprecated\n\t\tif err := validateSupportedVersion(gvk.GroupVersion(), allowDeprecated); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// verify the validity of the YAML\n\t\tif err := strict.VerifyUnmarshalStrict([]*runtime.Scheme{kubeadmscheme.Scheme, componentconfigs.Scheme}, gvk, fileContent); err != nil {\n\t\t\tklog.Warning(err.Error())\n\t\t}\n\n\t\tif kubeadmutil.GroupVersionKindsHasInitConfiguration(gvk) {\n\t\t\t// Set initcfg to an empty struct value the deserializer will populate\n\t\t\tinitcfg = \u0026kubeadmapi.InitConfiguration{}\n\t\t\t// Decode the bytes into the internal struct. Under the hood, the bytes will be unmarshalled into the\n\t\t\t// right external version, defaulted, and converted into the internal version.\n\t\t\tif err := runtime.DecodeInto(kubeadmscheme.Codecs.UniversalDecoder(), fileContent, initcfg); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif kubeadmutil.GroupVersionKindsHasClusterConfiguration(gvk) {\n\t\t\t// Set clustercfg to an empty struct value the deserializer will populate\n\t\t\tclustercfg = \u0026kubeadmapi.ClusterConfiguration{}\n\t\t\t// Decode the bytes into the internal struct. Under the hood, the bytes will be unmarshalled into the\n\t\t\t// right external version, defaulted, and converted into the internal version.\n\t\t\tif err := runtime.DecodeInto(kubeadmscheme.Codecs.UniversalDecoder(), fileContent, clustercfg); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// If the group is neither a kubeadm core type or of a supported component config group, we dump a warning about it being ignored\n\t\tif !componentconfigs.Scheme.IsGroupRegistered(gvk.Group) {\n\t\t\tklog.Warningf(\"[config] WARNING: Ignored YAML document with GroupVersionKind %v\\n\", gvk)\n\t\t}\n\t}\n\n\t// Enforce that InitConfiguration and/or ClusterConfiguration has to exist among the YAML documents\n\tif initcfg == nil \u0026\u0026 clustercfg == nil {\n\t\treturn nil, errors.New(\"no InitConfiguration or ClusterConfiguration kind was found in the YAML file\")\n\t}\n\n\t// If InitConfiguration wasn't given, default it by creating an external struct instance, default it and convert into the internal type\n\tif initcfg == nil {\n\t\textinitcfg := \u0026kubeadmapiv1.InitConfiguration{}\n\t\tkubeadmscheme.Scheme.Default(extinitcfg)\n\t\t// Set initcfg to an empty struct value the deserializer will populate\n\t\tinitcfg = \u0026kubeadmapi.InitConfiguration{}\n\t\tif err := kubeadmscheme.Scheme.Convert(extinitcfg, initcfg, nil); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\t// If ClusterConfiguration was given, populate it in the InitConfiguration struct\n\tif clustercfg != nil {\n\t\tinitcfg.ClusterConfiguration = *clustercfg\n\t} else {\n\t\t// Populate the internal InitConfiguration.ClusterConfiguration with defaults\n\t\textclustercfg := \u0026kubeadmapiv1.ClusterConfiguration{}\n\t\tkubeadmscheme.Scheme.Default(extclustercfg)\n\t\tif err := kubeadmscheme.Scheme.Convert(extclustercfg, \u0026initcfg.ClusterConfiguration, nil); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Load any component configs\n\tif err := componentconfigs.FetchFromDocumentMap(\u0026initcfg.ClusterConfiguration, gvkmap); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Applies dynamic defaults to settings not provided with flags\n\tif err := SetInitDynamicDefaults(initcfg); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Validates cfg (flags/configs + defaults + dynamic defaults)\n\tif err := validation.ValidateInitConfiguration(initcfg).ToAggregate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn initcfg, nil\n}","line":{"from":293,"to":379}} {"id":100001294,"name":"MarshalInitConfigurationToBytes","signature":"func MarshalInitConfigurationToBytes(cfg *kubeadmapi.InitConfiguration, gv schema.GroupVersion) ([]byte, error)","file":"cmd/kubeadm/app/util/config/initconfiguration.go","code":"// MarshalInitConfigurationToBytes marshals the internal InitConfiguration object to bytes. It writes the embedded\n// ClusterConfiguration object with ComponentConfigs out as separate YAML documents\nfunc MarshalInitConfigurationToBytes(cfg *kubeadmapi.InitConfiguration, gv schema.GroupVersion) ([]byte, error) {\n\tinitbytes, err := kubeadmutil.MarshalToYamlForCodecs(cfg, gv, kubeadmscheme.Codecs)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tallFiles := [][]byte{initbytes}\n\n\t// Exception: If the specified groupversion is targeting the internal type, don't print embedded ClusterConfiguration contents\n\t// This is mostly used for unit testing. In a real scenario the internal version of the API is never marshalled as-is.\n\tif gv.Version != runtime.APIVersionInternal {\n\t\tclusterbytes, err := kubeadmutil.MarshalToYamlForCodecs(\u0026cfg.ClusterConfiguration, gv, kubeadmscheme.Codecs)\n\t\tif err != nil {\n\t\t\treturn []byte{}, err\n\t\t}\n\t\tallFiles = append(allFiles, clusterbytes)\n\t}\n\treturn bytes.Join(allFiles, []byte(kubeadmconstants.YAMLDocumentSeparator)), nil\n}","line":{"from":381,"to":400}} {"id":100001295,"name":"SetJoinDynamicDefaults","signature":"func SetJoinDynamicDefaults(cfg *kubeadmapi.JoinConfiguration) error","file":"cmd/kubeadm/app/util/config/joinconfiguration.go","code":"// SetJoinDynamicDefaults checks and sets configuration values for the JoinConfiguration object\nfunc SetJoinDynamicDefaults(cfg *kubeadmapi.JoinConfiguration) error {\n\taddControlPlaneTaint := false\n\tif cfg.ControlPlane != nil {\n\t\taddControlPlaneTaint = true\n\t}\n\tif err := SetNodeRegistrationDynamicDefaults(\u0026cfg.NodeRegistration, addControlPlaneTaint); err != nil {\n\t\treturn err\n\t}\n\n\treturn SetJoinControlPlaneDefaults(cfg.ControlPlane)\n}","line":{"from":36,"to":47}} {"id":100001296,"name":"SetJoinControlPlaneDefaults","signature":"func SetJoinControlPlaneDefaults(cfg *kubeadmapi.JoinControlPlane) error","file":"cmd/kubeadm/app/util/config/joinconfiguration.go","code":"// SetJoinControlPlaneDefaults checks and sets configuration values for the JoinControlPlane object\nfunc SetJoinControlPlaneDefaults(cfg *kubeadmapi.JoinControlPlane) error {\n\tif cfg != nil {\n\t\tif err := SetAPIEndpointDynamicDefaults(\u0026cfg.LocalAPIEndpoint); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":49,"to":57}} {"id":100001297,"name":"LoadOrDefaultJoinConfiguration","signature":"func LoadOrDefaultJoinConfiguration(cfgPath string, defaultversionedcfg *kubeadmapiv1.JoinConfiguration) (*kubeadmapi.JoinConfiguration, error)","file":"cmd/kubeadm/app/util/config/joinconfiguration.go","code":"// LoadOrDefaultJoinConfiguration takes a path to a config file and a versioned configuration that can serve as the default config\n// If cfgPath is specified, defaultversionedcfg will always get overridden. Otherwise, the default config (often populated by flags) will be used.\n// Then the external, versioned configuration is defaulted and converted to the internal type.\n// Right thereafter, the configuration is defaulted again with dynamic values (like IP addresses of a machine, etc)\n// Lastly, the internal config is validated and returned.\nfunc LoadOrDefaultJoinConfiguration(cfgPath string, defaultversionedcfg *kubeadmapiv1.JoinConfiguration) (*kubeadmapi.JoinConfiguration, error) {\n\tif cfgPath != \"\" {\n\t\t// Loads configuration from config file, if provided\n\t\t// Nb. --config overrides command line flags, TODO: fix this\n\t\treturn LoadJoinConfigurationFromFile(cfgPath)\n\t}\n\n\treturn DefaultedJoinConfiguration(defaultversionedcfg)\n}","line":{"from":59,"to":72}} {"id":100001298,"name":"LoadJoinConfigurationFromFile","signature":"func LoadJoinConfigurationFromFile(cfgPath string) (*kubeadmapi.JoinConfiguration, error)","file":"cmd/kubeadm/app/util/config/joinconfiguration.go","code":"// LoadJoinConfigurationFromFile loads versioned JoinConfiguration from file, converts it to internal, defaults and validates it\nfunc LoadJoinConfigurationFromFile(cfgPath string) (*kubeadmapi.JoinConfiguration, error) {\n\tklog.V(1).Infof(\"loading configuration from %q\", cfgPath)\n\n\tb, err := os.ReadFile(cfgPath)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to read config from %q \", cfgPath)\n\t}\n\n\tgvkmap, err := kubeadmutil.SplitYAMLDocuments(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn documentMapToJoinConfiguration(gvkmap, false)\n}","line":{"from":74,"to":89}} {"id":100001299,"name":"documentMapToJoinConfiguration","signature":"func documentMapToJoinConfiguration(gvkmap kubeadmapi.DocumentMap, allowDeprecated bool) (*kubeadmapi.JoinConfiguration, error)","file":"cmd/kubeadm/app/util/config/joinconfiguration.go","code":"// documentMapToJoinConfiguration takes a map between GVKs and YAML documents (as returned by SplitYAMLDocuments),\n// finds a JoinConfiguration, decodes it, dynamically defaults it and then validates it prior to return.\nfunc documentMapToJoinConfiguration(gvkmap kubeadmapi.DocumentMap, allowDeprecated bool) (*kubeadmapi.JoinConfiguration, error) {\n\tjoinBytes := []byte{}\n\tfor gvk, bytes := range gvkmap {\n\t\t// not interested in anything other than JoinConfiguration\n\t\tif gvk.Kind != constants.JoinConfigurationKind {\n\t\t\tcontinue\n\t\t}\n\n\t\t// check if this version is supported and possibly not deprecated\n\t\tif err := validateSupportedVersion(gvk.GroupVersion(), allowDeprecated); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// verify the validity of the YAML\n\t\tif err := strict.VerifyUnmarshalStrict([]*runtime.Scheme{kubeadmscheme.Scheme}, gvk, bytes); err != nil {\n\t\t\tklog.Warning(err.Error())\n\t\t}\n\n\t\tjoinBytes = bytes\n\t}\n\n\tif len(joinBytes) == 0 {\n\t\treturn nil, errors.Errorf(\"no %s found in the supplied config\", constants.JoinConfigurationKind)\n\t}\n\n\tinternalcfg := \u0026kubeadmapi.JoinConfiguration{}\n\tif err := runtime.DecodeInto(kubeadmscheme.Codecs.UniversalDecoder(), joinBytes, internalcfg); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Applies dynamic defaults to settings not provided with flags\n\tif err := SetJoinDynamicDefaults(internalcfg); err != nil {\n\t\treturn nil, err\n\t}\n\t// Validates cfg (flags/configs + defaults)\n\tif err := validation.ValidateJoinConfiguration(internalcfg).ToAggregate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn internalcfg, nil\n}","line":{"from":91,"to":133}} {"id":100001300,"name":"DefaultedJoinConfiguration","signature":"func DefaultedJoinConfiguration(defaultversionedcfg *kubeadmapiv1.JoinConfiguration) (*kubeadmapi.JoinConfiguration, error)","file":"cmd/kubeadm/app/util/config/joinconfiguration.go","code":"// DefaultedJoinConfiguration takes a versioned JoinConfiguration (usually filled in by command line parameters), defaults it, converts it to internal and validates it\nfunc DefaultedJoinConfiguration(defaultversionedcfg *kubeadmapiv1.JoinConfiguration) (*kubeadmapi.JoinConfiguration, error) {\n\tinternalcfg := \u0026kubeadmapi.JoinConfiguration{}\n\n\t// Takes passed flags into account; the defaulting is executed once again enforcing assignment of\n\t// static default values to cfg only for values not provided with flags\n\tkubeadmscheme.Scheme.Default(defaultversionedcfg)\n\tif err := kubeadmscheme.Scheme.Convert(defaultversionedcfg, internalcfg, nil); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Applies dynamic defaults to settings not provided with flags\n\tif err := SetJoinDynamicDefaults(internalcfg); err != nil {\n\t\treturn nil, err\n\t}\n\t// Validates cfg (flags/configs + defaults)\n\tif err := validation.ValidateJoinConfiguration(internalcfg).ToAggregate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn internalcfg, nil\n}","line":{"from":135,"to":156}} {"id":100001301,"name":"VerifyUnmarshalStrict","signature":"func VerifyUnmarshalStrict(schemes []*runtime.Scheme, gvk schema.GroupVersionKind, bytes []byte) error","file":"cmd/kubeadm/app/util/config/strict/strict.go","code":"// VerifyUnmarshalStrict takes a slice of schems, a JSON/YAML byte slice and a GroupVersionKind\n// and verifies if the schema is known and if the byte slice unmarshals with strict mode.\nfunc VerifyUnmarshalStrict(schemes []*runtime.Scheme, gvk schema.GroupVersionKind, bytes []byte) error {\n\tvar scheme *runtime.Scheme\n\tfor _, s := range schemes {\n\t\tif _, err := s.New(gvk); err == nil {\n\t\t\tscheme = s\n\t\t\tbreak\n\t\t}\n\t}\n\tif scheme == nil {\n\t\treturn errors.Errorf(\"unknown configuration %#v\", gvk)\n\t}\n\n\topt := json.SerializerOptions{Yaml: true, Pretty: false, Strict: true}\n\tserializer := json.NewSerializerWithOptions(json.DefaultMetaFactory, scheme, scheme, opt)\n\t_, _, err := serializer.Decode(bytes, \u0026gvk, nil)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"error unmarshaling configuration %#v\", gvk)\n\t}\n\n\treturn nil\n}","line":{"from":27,"to":49}} {"id":100001302,"name":"CopyFile","signature":"func CopyFile(src, dest string) error","file":"cmd/kubeadm/app/util/copy.go","code":"// CopyFile copies a file from src to dest.\nfunc CopyFile(src, dest string) error {\n\tfileInfo, err := os.Stat(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcontents, err := os.ReadFile(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.WriteFile(dest, contents, fileInfo.Mode())\n\treturn err\n}","line":{"from":23,"to":35}} {"id":100001303,"name":"CopyDir","signature":"func CopyDir(src string, dst string) ([]byte, error)","file":"cmd/kubeadm/app/util/copy_unix.go","code":"// CopyDir copies the content of a folder\nfunc CopyDir(src string, dst string) ([]byte, error) {\n\treturn exec.Command(\"cp\", \"-r\", src, dst).CombinedOutput()\n}","line":{"from":26,"to":29}} {"id":100001304,"name":"CopyDir","signature":"func CopyDir(src string, dst string) ([]byte, error)","file":"cmd/kubeadm/app/util/copy_windows.go","code":"// CopyDir copies the content of a folder\nfunc CopyDir(src string, dst string) ([]byte, error) {\n\t// /E Copies directories and subdirectories, including empty ones.\n\t// /H Copies hidden and system files also.\n\treturn exec.Command(\"xcopy\", \"/E\", \"/H\", src, dst).CombinedOutput()\n}","line":{"from":26,"to":31}} {"id":100001305,"name":"CreateRandBytes","signature":"func CreateRandBytes(size uint32) ([]byte, error)","file":"cmd/kubeadm/app/util/crypto/crypto.go","code":"// CreateRandBytes returns a cryptographically secure slice of random bytes with a given size\nfunc CreateRandBytes(size uint32) ([]byte, error) {\n\tbytes := make([]byte, size)\n\tif _, err := rand.Read(bytes); err != nil {\n\t\treturn nil, err\n\t}\n\treturn bytes, nil\n}","line":{"from":27,"to":34}} {"id":100001306,"name":"EncryptBytes","signature":"func EncryptBytes(data, key []byte) ([]byte, error)","file":"cmd/kubeadm/app/util/crypto/crypto.go","code":"// EncryptBytes takes a byte slice of raw data and an encryption key and returns an encrypted byte slice of data.\n// The key must be an AES key, either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256\nfunc EncryptBytes(data, key []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnonce, err := CreateRandBytes(uint32(gcm.NonceSize()))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn gcm.Seal(nonce, nonce, data, nil), nil\n}","line":{"from":36,"to":52}} {"id":100001307,"name":"DecryptBytes","signature":"func DecryptBytes(data, key []byte) ([]byte, error)","file":"cmd/kubeadm/app/util/crypto/crypto.go","code":"// DecryptBytes takes a byte slice of encrypted data and an encryption key and returns a decrypted byte slice of data.\n// The key must be an AES key, either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256\nfunc DecryptBytes(data, key []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnonceSize := gcm.NonceSize()\n\tif len(data) \u003c nonceSize {\n\t\treturn nil, errors.New(\"size of data is less than the nonce\")\n\t}\n\n\tnonce, out := data[:nonceSize], data[nonceSize:]\n\tout, err = gcm.Open(nil, nonce, out, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}","line":{"from":54,"to":76}} {"id":100001308,"name":"NewFileToPrint","signature":"func NewFileToPrint(realPath, printPath string) FileToPrint","file":"cmd/kubeadm/app/util/dryrun/dryrun.go","code":"// NewFileToPrint makes a new instance of FileToPrint with the specified arguments\nfunc NewFileToPrint(realPath, printPath string) FileToPrint {\n\treturn FileToPrint{\n\t\tRealPath: realPath,\n\t\tPrintPath: printPath,\n\t}\n}","line":{"from":40,"to":46}} {"id":100001309,"name":"PrintDryRunFile","signature":"func PrintDryRunFile(fileName, realDir, printDir string, w io.Writer) error","file":"cmd/kubeadm/app/util/dryrun/dryrun.go","code":"// PrintDryRunFile is a helper method around PrintDryRunFiles\nfunc PrintDryRunFile(fileName, realDir, printDir string, w io.Writer) error {\n\treturn PrintDryRunFiles([]FileToPrint{\n\t\tNewFileToPrint(filepath.Join(realDir, fileName), filepath.Join(printDir, fileName)),\n\t}, w)\n}","line":{"from":48,"to":53}} {"id":100001310,"name":"PrintDryRunFiles","signature":"func PrintDryRunFiles(files []FileToPrint, w io.Writer) error","file":"cmd/kubeadm/app/util/dryrun/dryrun.go","code":"// PrintDryRunFiles prints the contents of the FileToPrints given to it to the writer w\nfunc PrintDryRunFiles(files []FileToPrint, w io.Writer) error {\n\terrs := []error{}\n\tfor _, file := range files {\n\t\tif len(file.RealPath) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tfileBytes, err := os.ReadFile(file.RealPath)\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Make it possible to fake the path of the file; i.e. you may want to tell the user\n\t\t// \"Here is what would be written to /etc/kubernetes/admin.conf\", although you wrote it to /tmp/kubeadm-dryrun/admin.conf and are loading it from there\n\t\t// Fall back to the \"real\" path if PrintPath is not set\n\t\toutputFilePath := file.PrintPath\n\t\tif len(outputFilePath) == 0 {\n\t\t\toutputFilePath = file.RealPath\n\t\t}\n\n\t\tfmt.Fprintf(w, \"[dryrun] Would write file %q with content:\\n\", outputFilePath)\n\t\tapiclient.PrintBytesWithLinePrefix(w, fileBytes, \"\\t\")\n\t}\n\treturn errorsutil.NewAggregate(errs)\n}","line":{"from":55,"to":81}} {"id":100001311,"name":"NewWaiter","signature":"func NewWaiter() apiclient.Waiter","file":"cmd/kubeadm/app/util/dryrun/dryrun.go","code":"// NewWaiter returns a new Waiter object that talks to the given Kubernetes cluster\nfunc NewWaiter() apiclient.Waiter {\n\treturn \u0026Waiter{}\n}","line":{"from":86,"to":89}} {"id":100001312,"name":"WaitForAPI","signature":"func (w *Waiter) WaitForAPI() error","file":"cmd/kubeadm/app/util/dryrun/dryrun.go","code":"// WaitForAPI just returns a dummy nil, to indicate that the program should just proceed\nfunc (w *Waiter) WaitForAPI() error {\n\tfmt.Println(\"[dryrun] Would wait for the API Server's /healthz endpoint to return 'ok'\")\n\treturn nil\n}","line":{"from":91,"to":95}} {"id":100001313,"name":"WaitForPodsWithLabel","signature":"func (w *Waiter) WaitForPodsWithLabel(kvLabel string) error","file":"cmd/kubeadm/app/util/dryrun/dryrun.go","code":"// WaitForPodsWithLabel just returns a dummy nil, to indicate that the program should just proceed\nfunc (w *Waiter) WaitForPodsWithLabel(kvLabel string) error {\n\tfmt.Printf(\"[dryrun] Would wait for the Pods with the label %q in the %s namespace to become Running\\n\", kvLabel, metav1.NamespaceSystem)\n\treturn nil\n}","line":{"from":97,"to":101}} {"id":100001314,"name":"WaitForPodToDisappear","signature":"func (w *Waiter) WaitForPodToDisappear(podName string) error","file":"cmd/kubeadm/app/util/dryrun/dryrun.go","code":"// WaitForPodToDisappear just returns a dummy nil, to indicate that the program should just proceed\nfunc (w *Waiter) WaitForPodToDisappear(podName string) error {\n\tfmt.Printf(\"[dryrun] Would wait for the %q Pod in the %s namespace to be deleted\\n\", podName, metav1.NamespaceSystem)\n\treturn nil\n}","line":{"from":103,"to":107}} {"id":100001315,"name":"WaitForHealthyKubelet","signature":"func (w *Waiter) WaitForHealthyKubelet(_ time.Duration, healthzEndpoint string) error","file":"cmd/kubeadm/app/util/dryrun/dryrun.go","code":"// WaitForHealthyKubelet blocks until the kubelet /healthz endpoint returns 'ok'\nfunc (w *Waiter) WaitForHealthyKubelet(_ time.Duration, healthzEndpoint string) error {\n\tfmt.Printf(\"[dryrun] Would make sure the kubelet %q endpoint is healthy\\n\", healthzEndpoint)\n\treturn nil\n}","line":{"from":109,"to":113}} {"id":100001316,"name":"WaitForKubeletAndFunc","signature":"func (w *Waiter) WaitForKubeletAndFunc(f func() error) error","file":"cmd/kubeadm/app/util/dryrun/dryrun.go","code":"// WaitForKubeletAndFunc is a wrapper for WaitForHealthyKubelet that also blocks for a function\nfunc (w *Waiter) WaitForKubeletAndFunc(f func() error) error {\n\treturn nil\n}","line":{"from":115,"to":118}} {"id":100001317,"name":"SetTimeout","signature":"func (w *Waiter) SetTimeout(_ time.Duration) {}","file":"cmd/kubeadm/app/util/dryrun/dryrun.go","code":"// SetTimeout is a no-op; we don't wait in this implementation\nfunc (w *Waiter) SetTimeout(_ time.Duration) {}","line":{"from":120,"to":121}} {"id":100001318,"name":"WaitForStaticPodControlPlaneHashes","signature":"func (w *Waiter) WaitForStaticPodControlPlaneHashes(_ string) (map[string]string, error)","file":"cmd/kubeadm/app/util/dryrun/dryrun.go","code":"// WaitForStaticPodControlPlaneHashes returns an empty hash for all control plane images;\nfunc (w *Waiter) WaitForStaticPodControlPlaneHashes(_ string) (map[string]string, error) {\n\treturn map[string]string{\n\t\tkubeadmconstants.KubeAPIServer: \"\",\n\t\tkubeadmconstants.KubeControllerManager: \"\",\n\t\tkubeadmconstants.KubeScheduler: \"\",\n\t}, nil\n}","line":{"from":123,"to":130}} {"id":100001319,"name":"WaitForStaticPodSingleHash","signature":"func (w *Waiter) WaitForStaticPodSingleHash(_ string, _ string) (string, error)","file":"cmd/kubeadm/app/util/dryrun/dryrun.go","code":"// WaitForStaticPodSingleHash returns an empty hash\n// but the empty strings there are needed\nfunc (w *Waiter) WaitForStaticPodSingleHash(_ string, _ string) (string, error) {\n\treturn \"\", nil\n}","line":{"from":132,"to":136}} {"id":100001320,"name":"WaitForStaticPodHashChange","signature":"func (w *Waiter) WaitForStaticPodHashChange(_, _, _ string) error","file":"cmd/kubeadm/app/util/dryrun/dryrun.go","code":"// WaitForStaticPodHashChange returns a dummy nil error in order for the flow to just continue as we're dryrunning\nfunc (w *Waiter) WaitForStaticPodHashChange(_, _, _ string) error {\n\treturn nil\n}","line":{"from":138,"to":141}} {"id":100001321,"name":"PrintFilesIfDryRunning","signature":"func PrintFilesIfDryRunning(needPrintManifest bool, manifestDir string, outputWriter io.Writer) error","file":"cmd/kubeadm/app/util/dryrun/dryrun.go","code":"// PrintFilesIfDryRunning prints the static pod manifests to stdout and informs about the temporary directory to go and lookup when dry running\nfunc PrintFilesIfDryRunning(needPrintManifest bool, manifestDir string, outputWriter io.Writer) error {\n\tvar files []FileToPrint\n\t// Print static pod manifests if it is a control plane\n\tif needPrintManifest {\n\t\tfmt.Printf(\"[dryrun] Wrote certificates, kubeconfig files and control plane manifests to the %q directory\\n\", manifestDir)\n\t\tfor _, component := range kubeadmconstants.ControlPlaneComponents {\n\t\t\trealPath := kubeadmconstants.GetStaticPodFilepath(component, manifestDir)\n\t\t\toutputPath := kubeadmconstants.GetStaticPodFilepath(component, kubeadmconstants.GetStaticPodDirectory())\n\t\t\tfiles = append(files, NewFileToPrint(realPath, outputPath))\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"[dryrun] Wrote certificates and kubeconfig files to the %q directory\\n\", manifestDir)\n\t}\n\n\tfmt.Println(\"[dryrun] The certificates or kubeconfig files would not be printed due to their sensitive nature\")\n\tfmt.Printf(\"[dryrun] Please examine the %q directory for details about what would be written\\n\", manifestDir)\n\n\t// Print kubelet config manifests\n\tkubeletConfigFiles := []string{kubeadmconstants.KubeletConfigurationFileName, kubeadmconstants.KubeletEnvFileName}\n\tfor _, filename := range kubeletConfigFiles {\n\t\trealPath := filepath.Join(manifestDir, filename)\n\t\toutputPath := filepath.Join(kubeadmconstants.KubeletRunDirectory, filename)\n\t\tfiles = append(files, NewFileToPrint(realPath, outputPath))\n\t}\n\n\treturn PrintDryRunFiles(files, outputWriter)\n}","line":{"from":143,"to":170}} {"id":100001322,"name":"GetControlPlaneEndpoint","signature":"func GetControlPlaneEndpoint(controlPlaneEndpoint string, localEndpoint *kubeadmapi.APIEndpoint) (string, error)","file":"cmd/kubeadm/app/util/endpoint.go","code":"// GetControlPlaneEndpoint returns a properly formatted endpoint for the control plane built according following rules:\n// - If the controlPlaneEndpoint is defined, use it.\n// - if the controlPlaneEndpoint is defined but without a port number, use the controlPlaneEndpoint + localEndpoint.BindPort is used.\n// - Otherwise, in case the controlPlaneEndpoint is not defined, use the localEndpoint.AdvertiseAddress + the localEndpoint.BindPort.\nfunc GetControlPlaneEndpoint(controlPlaneEndpoint string, localEndpoint *kubeadmapi.APIEndpoint) (string, error) {\n\t// get the URL of the local endpoint\n\tlocalAPIEndpoint, err := GetLocalAPIEndpoint(localEndpoint)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// if the controlplane endpoint is defined\n\tif len(controlPlaneEndpoint) \u003e 0 {\n\t\t// parse the controlplane endpoint\n\t\tvar host, port string\n\t\tvar err error\n\t\tif host, port, err = ParseHostPort(controlPlaneEndpoint); err != nil {\n\t\t\treturn \"\", errors.Wrapf(err, \"invalid value %q given for controlPlaneEndpoint\", controlPlaneEndpoint)\n\t\t}\n\n\t\t// if a port is provided within the controlPlaneAddress warn the users we are using it, else use the bindport\n\t\tlocalEndpointPort := strconv.Itoa(int(localEndpoint.BindPort))\n\t\tif port != \"\" {\n\t\t\tif port != localEndpointPort {\n\t\t\t\tklog.Warning(\"[endpoint] WARNING: port specified in controlPlaneEndpoint overrides bindPort in the controlplane address\")\n\t\t\t}\n\t\t} else {\n\t\t\tport = localEndpointPort\n\t\t}\n\n\t\t// overrides the control-plane url using the controlPlaneAddress (and eventually the bindport)\n\t\treturn formatURL(host, port).String(), nil\n\t}\n\n\treturn localAPIEndpoint, nil\n}","line":{"from":33,"to":68}} {"id":100001323,"name":"GetLocalAPIEndpoint","signature":"func GetLocalAPIEndpoint(localEndpoint *kubeadmapi.APIEndpoint) (string, error)","file":"cmd/kubeadm/app/util/endpoint.go","code":"// GetLocalAPIEndpoint parses an APIEndpoint and returns it as a string,\n// or returns and error in case it cannot be parsed.\nfunc GetLocalAPIEndpoint(localEndpoint *kubeadmapi.APIEndpoint) (string, error) {\n\t// get the URL of the local endpoint\n\tlocalEndpointIP, localEndpointPort, err := parseAPIEndpoint(localEndpoint)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\turl := formatURL(localEndpointIP.String(), localEndpointPort)\n\treturn url.String(), nil\n}","line":{"from":70,"to":80}} {"id":100001324,"name":"ParseHostPort","signature":"func ParseHostPort(hostport string) (string, string, error)","file":"cmd/kubeadm/app/util/endpoint.go","code":"// ParseHostPort parses a network address of the form \"host:port\", \"ipv4:port\", \"[ipv6]:port\" into host and port;\n// \":port\" can be eventually omitted.\n// If the string is not a valid representation of network address, ParseHostPort returns an error.\nfunc ParseHostPort(hostport string) (string, string, error) {\n\tvar host, port string\n\tvar err error\n\n\t// try to split host and port\n\tif host, port, err = net.SplitHostPort(hostport); err != nil {\n\t\t// if SplitHostPort returns an error, the entire hostport is considered as host\n\t\thost = hostport\n\t}\n\n\t// if port is defined, parse and validate it\n\tif port != \"\" {\n\t\tif _, err := ParsePort(port); err != nil {\n\t\t\treturn \"\", \"\", errors.Errorf(\"hostport %s: port %s must be a valid number between 1 and 65535, inclusive\", hostport, port)\n\t\t}\n\t}\n\n\t// if host is a valid IP, returns it\n\tif ip := netutils.ParseIPSloppy(host); ip != nil {\n\t\treturn host, port, nil\n\t}\n\n\t// if host is a validate RFC-1123 subdomain, returns it\n\tif errs := validation.IsDNS1123Subdomain(host); len(errs) == 0 {\n\t\treturn host, port, nil\n\t}\n\n\treturn \"\", \"\", errors.Errorf(\"hostport %s: host '%s' must be a valid IP address or a valid RFC-1123 DNS subdomain\", hostport, host)\n}","line":{"from":82,"to":113}} {"id":100001325,"name":"ParsePort","signature":"func ParsePort(port string) (int, error)","file":"cmd/kubeadm/app/util/endpoint.go","code":"// ParsePort parses a string representing a TCP port.\n// If the string is not a valid representation of a TCP port, ParsePort returns an error.\nfunc ParsePort(port string) (int, error) {\n\tportInt, err := netutils.ParsePort(port, true)\n\tif err == nil \u0026\u0026 (1 \u003c= portInt \u0026\u0026 portInt \u003c= 65535) {\n\t\treturn portInt, nil\n\t}\n\n\treturn 0, errors.New(\"port must be a valid number between 1 and 65535, inclusive\")\n}","line":{"from":115,"to":124}} {"id":100001326,"name":"parseAPIEndpoint","signature":"func parseAPIEndpoint(localEndpoint *kubeadmapi.APIEndpoint) (net.IP, string, error)","file":"cmd/kubeadm/app/util/endpoint.go","code":"// parseAPIEndpoint parses an APIEndpoint and returns the AdvertiseAddress as net.IP and the BindPort as string.\n// If the BindPort or AdvertiseAddress are invalid it returns an error.\nfunc parseAPIEndpoint(localEndpoint *kubeadmapi.APIEndpoint) (net.IP, string, error) {\n\t// parse the bind port\n\tbindPortString := strconv.Itoa(int(localEndpoint.BindPort))\n\tif _, err := ParsePort(bindPortString); err != nil {\n\t\treturn nil, \"\", errors.Wrapf(err, \"invalid value %q given for api.bindPort\", localEndpoint.BindPort)\n\t}\n\n\t// parse the AdvertiseAddress\n\tvar ip = netutils.ParseIPSloppy(localEndpoint.AdvertiseAddress)\n\tif ip == nil {\n\t\treturn nil, \"\", errors.Errorf(\"invalid value `%s` given for api.advertiseAddress\", localEndpoint.AdvertiseAddress)\n\t}\n\n\treturn ip, bindPortString, nil\n}","line":{"from":126,"to":142}} {"id":100001327,"name":"formatURL","signature":"func formatURL(host, port string) *url.URL","file":"cmd/kubeadm/app/util/endpoint.go","code":"// formatURL takes a host and a port string and creates a net.URL using https scheme\nfunc formatURL(host, port string) *url.URL {\n\treturn \u0026url.URL{\n\t\tScheme: \"https\",\n\t\tHost: net.JoinHostPort(host, port),\n\t}\n}","line":{"from":144,"to":150}} {"id":100001328,"name":"GetProxyEnvVars","signature":"func GetProxyEnvVars() []v1.EnvVar","file":"cmd/kubeadm/app/util/env.go","code":"// GetProxyEnvVars builds a list of environment variables in order to use the right proxy\nfunc GetProxyEnvVars() []v1.EnvVar {\n\tenvs := []v1.EnvVar{}\n\tfor _, env := range os.Environ() {\n\t\tpos := strings.Index(env, \"=\")\n\t\tif pos == -1 {\n\t\t\t// malformed environment variable, skip it.\n\t\t\tcontinue\n\t\t}\n\t\tname := env[:pos]\n\t\tvalue := env[pos+1:]\n\t\tif strings.HasSuffix(strings.ToLower(name), \"_proxy\") \u0026\u0026 value != \"\" {\n\t\t\tenvVar := v1.EnvVar{Name: name, Value: value}\n\t\t\tenvs = append(envs, envVar)\n\t\t}\n\t}\n\treturn envs\n}","line":{"from":26,"to":43}} {"id":100001329,"name":"fatal","signature":"func fatal(msg string, code int)","file":"cmd/kubeadm/app/util/error.go","code":"// fatal prints the message if set and then exits.\nfunc fatal(msg string, code int) {\n\tif len(msg) \u003e 0 {\n\t\t// add newline if needed\n\t\tif !strings.HasSuffix(msg, \"\\n\") {\n\t\t\tmsg += \"\\n\"\n\t\t}\n\n\t\tfmt.Fprint(os.Stderr, msg)\n\t}\n\tos.Exit(code)\n}","line":{"from":45,"to":56}} {"id":100001330,"name":"CheckErr","signature":"func CheckErr(err error)","file":"cmd/kubeadm/app/util/error.go","code":"// CheckErr prints a user friendly error to STDERR and exits with a non-zero\n// exit code. Unrecognized errors will be printed with an \"error: \" prefix.\n//\n// This method is generic to the command in use and may be used by non-Kubectl\n// commands.\nfunc CheckErr(err error) {\n\tcheckErr(err, fatal)\n}","line":{"from":58,"to":65}} {"id":100001331,"name":"checkErr","signature":"func checkErr(err error, handleErr func(string, int))","file":"cmd/kubeadm/app/util/error.go","code":"// checkErr formats a given error as a string and calls the passed handleErr\n// func with that string and an exit code.\nfunc checkErr(err error, handleErr func(string, int)) {\n\n\tvar msg string\n\tif err != nil {\n\t\tmsg = fmt.Sprintf(\"%s\\nTo see the stack trace of this error execute with --v=5 or higher\", err.Error())\n\t\t// check if the verbosity level in klog is high enough and print a stack trace.\n\t\tf := flag.CommandLine.Lookup(\"v\")\n\t\tif f != nil {\n\t\t\t// assume that the \"v\" flag contains a parseable Int32 as per klog's \"Level\" type alias,\n\t\t\t// thus no error from ParseInt is handled here.\n\t\t\tif v, e := strconv.ParseInt(f.Value.String(), 10, 32); e == nil {\n\t\t\t\t// https://git.k8s.io/community/contributors/devel/sig-instrumentation/logging.md\n\t\t\t\t// klog.V(5) - Trace level verbosity\n\t\t\t\tif v \u003e 4 {\n\t\t\t\t\tmsg = fmt.Sprintf(\"%+v\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif err == nil {\n\t\treturn\n\t}\n\tswitch {\n\tcase err == ErrExit:\n\t\thandleErr(\"\", DefaultErrorExitCode)\n\tcase strings.Contains(err.Error(), ErrInvalidSubCommandMsg):\n\t\thandleErr(err.Error(), DefaultErrorExitCode)\n\tdefault:\n\t\tswitch err.(type) {\n\t\tcase preflightError:\n\t\t\thandleErr(msg, PreFlightExitCode)\n\t\tcase errorsutil.Aggregate:\n\t\t\thandleErr(msg, ValidationExitCode)\n\n\t\tdefault:\n\t\t\thandleErr(msg, DefaultErrorExitCode)\n\t\t}\n\t}\n}","line":{"from":73,"to":114}} {"id":100001332,"name":"FormatErrMsg","signature":"func FormatErrMsg(errs []error) string","file":"cmd/kubeadm/app/util/error.go","code":"// FormatErrMsg returns a human-readable string describing the slice of errors passed to the function\nfunc FormatErrMsg(errs []error) string {\n\tvar errMsg string\n\tfor _, err := range errs {\n\t\terrMsg = fmt.Sprintf(\"%s\\t- %s\\n\", errMsg, err.Error())\n\t}\n\treturn errMsg\n}","line":{"from":116,"to":123}} {"id":100001333,"name":"New","signature":"func New(endpoints []string, ca, cert, key string) (*Client, error)","file":"cmd/kubeadm/app/util/etcd/etcd.go","code":"// New creates a new EtcdCluster client\nfunc New(endpoints []string, ca, cert, key string) (*Client, error) {\n\tclient := Client{Endpoints: endpoints}\n\n\tvar err error\n\tvar tlsConfig *tls.Config\n\tif ca != \"\" || cert != \"\" || key != \"\" {\n\t\ttlsInfo := transport.TLSInfo{\n\t\t\tCertFile: cert,\n\t\t\tKeyFile: key,\n\t\t\tTrustedCAFile: ca,\n\t\t}\n\t\ttlsConfig, err = tlsInfo.ClientConfig()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tclient.newEtcdClient = func(endpoints []string) (etcdClient, error) {\n\t\treturn clientv3.New(clientv3.Config{\n\t\t\tEndpoints: endpoints,\n\t\t\tDialTimeout: etcdTimeout,\n\t\t\tDialOptions: []grpc.DialOption{\n\t\t\t\tgrpc.WithBlock(), // block until the underlying connection is up\n\t\t\t},\n\t\t\tTLS: tlsConfig,\n\t\t})\n\t}\n\n\treturn \u0026client, nil\n}","line":{"from":107,"to":137}} {"id":100001334,"name":"NewFromCluster","signature":"func NewFromCluster(client clientset.Interface, certificatesDir string) (*Client, error)","file":"cmd/kubeadm/app/util/etcd/etcd.go","code":"// NewFromCluster creates an etcd client for the etcd endpoints present in etcd member list. In order to compose this information,\n// it will first discover at least one etcd endpoint to connect to. Once created, the client synchronizes client's endpoints with\n// the known endpoints from the etcd membership API, since it is the authoritative source of truth for the list of available members.\nfunc NewFromCluster(client clientset.Interface, certificatesDir string) (*Client, error) {\n\t// Discover at least one etcd endpoint to connect to by inspecting the existing etcd pods\n\n\t// Get the list of etcd endpoints\n\tendpoints, err := getEtcdEndpoints(client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tklog.V(1).Infof(\"etcd endpoints read from pods: %s\", strings.Join(endpoints, \",\"))\n\n\t// Creates an etcd client\n\tetcdClient, err := New(\n\t\tendpoints,\n\t\tfilepath.Join(certificatesDir, constants.EtcdCACertName),\n\t\tfilepath.Join(certificatesDir, constants.EtcdHealthcheckClientCertName),\n\t\tfilepath.Join(certificatesDir, constants.EtcdHealthcheckClientKeyName),\n\t)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"error creating etcd client for %v endpoints\", endpoints)\n\t}\n\n\t// synchronizes client's endpoints with the known endpoints from the etcd membership.\n\terr = etcdClient.Sync()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error syncing endpoints with etcd\")\n\t}\n\tklog.V(1).Infof(\"update etcd endpoints: %s\", strings.Join(etcdClient.Endpoints, \",\"))\n\n\treturn etcdClient, nil\n}","line":{"from":139,"to":171}} {"id":100001335,"name":"getEtcdEndpoints","signature":"func getEtcdEndpoints(client clientset.Interface) ([]string, error)","file":"cmd/kubeadm/app/util/etcd/etcd.go","code":"// getEtcdEndpoints returns the list of etcd endpoints.\nfunc getEtcdEndpoints(client clientset.Interface) ([]string, error) {\n\treturn getEtcdEndpointsWithBackoff(client, constants.StaticPodMirroringDefaultRetry)\n}","line":{"from":173,"to":176}} {"id":100001336,"name":"getEtcdEndpointsWithBackoff","signature":"func getEtcdEndpointsWithBackoff(client clientset.Interface, backoff wait.Backoff) ([]string, error)","file":"cmd/kubeadm/app/util/etcd/etcd.go","code":"func getEtcdEndpointsWithBackoff(client clientset.Interface, backoff wait.Backoff) ([]string, error) {\n\treturn getRawEtcdEndpointsFromPodAnnotation(client, backoff)\n}","line":{"from":178,"to":180}} {"id":100001337,"name":"getRawEtcdEndpointsFromPodAnnotation","signature":"func getRawEtcdEndpointsFromPodAnnotation(client clientset.Interface, backoff wait.Backoff) ([]string, error)","file":"cmd/kubeadm/app/util/etcd/etcd.go","code":"// getRawEtcdEndpointsFromPodAnnotation returns the list of endpoints as reported on etcd's pod annotations using the given backoff\nfunc getRawEtcdEndpointsFromPodAnnotation(client clientset.Interface, backoff wait.Backoff) ([]string, error) {\n\tetcdEndpoints := []string{}\n\tvar lastErr error\n\t// Let's tolerate some unexpected transient failures from the API server or load balancers. Also, if\n\t// static pods were not yet mirrored into the API server we want to wait for this propagation.\n\terr := wait.ExponentialBackoff(backoff, func() (bool, error) {\n\t\tvar overallEtcdPodCount int\n\t\tif etcdEndpoints, overallEtcdPodCount, lastErr = getRawEtcdEndpointsFromPodAnnotationWithoutRetry(client); lastErr != nil {\n\t\t\treturn false, nil\n\t\t}\n\t\tif len(etcdEndpoints) == 0 || overallEtcdPodCount != len(etcdEndpoints) {\n\t\t\tklog.V(4).Infof(\"found a total of %d etcd pods and the following endpoints: %v; retrying\",\n\t\t\t\toverallEtcdPodCount, etcdEndpoints)\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\tif err != nil {\n\t\tconst message = \"could not retrieve the list of etcd endpoints\"\n\t\tif lastErr != nil {\n\t\t\treturn []string{}, errors.Wrap(lastErr, message)\n\t\t}\n\t\treturn []string{}, errors.Wrap(err, message)\n\t}\n\treturn etcdEndpoints, nil\n}","line":{"from":182,"to":208}} {"id":100001338,"name":"getRawEtcdEndpointsFromPodAnnotationWithoutRetry","signature":"func getRawEtcdEndpointsFromPodAnnotationWithoutRetry(client clientset.Interface) ([]string, int, error)","file":"cmd/kubeadm/app/util/etcd/etcd.go","code":"// getRawEtcdEndpointsFromPodAnnotationWithoutRetry returns the list of etcd endpoints as reported by etcd Pod annotations,\n// along with the number of global etcd pods. This allows for callers to tell the difference between \"no endpoints found\",\n// and \"no endpoints found and pods were listed\", so they can skip retrying.\nfunc getRawEtcdEndpointsFromPodAnnotationWithoutRetry(client clientset.Interface) ([]string, int, error) {\n\tklog.V(3).Infof(\"retrieving etcd endpoints from %q annotation in etcd Pods\", constants.EtcdAdvertiseClientUrlsAnnotationKey)\n\tpodList, err := client.CoreV1().Pods(metav1.NamespaceSystem).List(\n\t\tcontext.TODO(),\n\t\tmetav1.ListOptions{\n\t\t\tLabelSelector: fmt.Sprintf(\"component=%s,tier=%s\", constants.Etcd, constants.ControlPlaneTier),\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn []string{}, 0, err\n\t}\n\tetcdEndpoints := []string{}\n\tfor _, pod := range podList.Items {\n\t\tetcdEndpoint, ok := pod.ObjectMeta.Annotations[constants.EtcdAdvertiseClientUrlsAnnotationKey]\n\t\tif !ok {\n\t\t\tklog.V(3).Infof(\"etcd Pod %q is missing the %q annotation; cannot infer etcd advertise client URL using the Pod annotation\", pod.ObjectMeta.Name, constants.EtcdAdvertiseClientUrlsAnnotationKey)\n\t\t\tcontinue\n\t\t}\n\t\tetcdEndpoints = append(etcdEndpoints, etcdEndpoint)\n\t}\n\treturn etcdEndpoints, len(podList.Items), nil\n}","line":{"from":210,"to":234}} {"id":100001339,"name":"Sync","signature":"func (c *Client) Sync() error","file":"cmd/kubeadm/app/util/etcd/etcd.go","code":"// Sync synchronizes client's endpoints with the known endpoints from the etcd membership.\nfunc (c *Client) Sync() error {\n\t// Syncs the list of endpoints\n\tvar cli etcdClient\n\tvar lastError error\n\terr := wait.ExponentialBackoff(etcdBackoff, func() (bool, error) {\n\t\tvar err error\n\t\tcli, err = c.newEtcdClient(c.Endpoints)\n\t\tif err != nil {\n\t\t\tlastError = err\n\t\t\treturn false, nil\n\t\t}\n\t\tdefer cli.Close()\n\t\tctx, cancel := context.WithTimeout(context.Background(), etcdTimeout)\n\t\terr = cli.Sync(ctx)\n\t\tcancel()\n\t\tif err == nil {\n\t\t\treturn true, nil\n\t\t}\n\t\tklog.V(5).Infof(\"Failed to sync etcd endpoints: %v\", err)\n\t\tlastError = err\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\treturn lastError\n\t}\n\tklog.V(1).Infof(\"etcd endpoints read from etcd: %s\", strings.Join(cli.Endpoints(), \",\"))\n\n\tc.Endpoints = cli.Endpoints()\n\treturn nil\n}","line":{"from":236,"to":266}} {"id":100001340,"name":"listMembers","signature":"func (c *Client) listMembers() (*clientv3.MemberListResponse, error)","file":"cmd/kubeadm/app/util/etcd/etcd.go","code":"func (c *Client) listMembers() (*clientv3.MemberListResponse, error) {\n\t// Gets the member list\n\tvar lastError error\n\tvar resp *clientv3.MemberListResponse\n\terr := wait.ExponentialBackoff(etcdBackoff, func() (bool, error) {\n\t\tcli, err := c.newEtcdClient(c.Endpoints)\n\t\tif err != nil {\n\t\t\tlastError = err\n\t\t\treturn false, nil\n\t\t}\n\t\tdefer cli.Close()\n\n\t\tctx, cancel := context.WithTimeout(context.Background(), etcdTimeout)\n\t\tresp, err = cli.MemberList(ctx)\n\t\tcancel()\n\t\tif err == nil {\n\t\t\treturn true, nil\n\t\t}\n\t\tklog.V(5).Infof(\"Failed to get etcd member list: %v\", err)\n\t\tlastError = err\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\treturn nil, lastError\n\t}\n\treturn resp, nil\n}","line":{"from":275,"to":301}} {"id":100001341,"name":"GetMemberID","signature":"func (c *Client) GetMemberID(peerURL string) (uint64, error)","file":"cmd/kubeadm/app/util/etcd/etcd.go","code":"// GetMemberID returns the member ID of the given peer URL\nfunc (c *Client) GetMemberID(peerURL string) (uint64, error) {\n\tresp, err := c.listMembers()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tfor _, member := range resp.Members {\n\t\tif member.GetPeerURLs()[0] == peerURL {\n\t\t\treturn member.GetID(), nil\n\t\t}\n\t}\n\treturn 0, ErrNoMemberIDForPeerURL\n}","line":{"from":303,"to":316}} {"id":100001342,"name":"ListMembers","signature":"func (c *Client) ListMembers() ([]Member, error)","file":"cmd/kubeadm/app/util/etcd/etcd.go","code":"// ListMembers returns the member list.\nfunc (c *Client) ListMembers() ([]Member, error) {\n\tresp, err := c.listMembers()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret := make([]Member, 0, len(resp.Members))\n\tfor _, m := range resp.Members {\n\t\tret = append(ret, Member{Name: m.Name, PeerURL: m.PeerURLs[0]})\n\t}\n\treturn ret, nil\n}","line":{"from":318,"to":330}} {"id":100001343,"name":"RemoveMember","signature":"func (c *Client) RemoveMember(id uint64) ([]Member, error)","file":"cmd/kubeadm/app/util/etcd/etcd.go","code":"// RemoveMember notifies an etcd cluster to remove an existing member\nfunc (c *Client) RemoveMember(id uint64) ([]Member, error) {\n\t// Remove an existing member from the cluster\n\tvar lastError error\n\tvar resp *clientv3.MemberRemoveResponse\n\terr := wait.ExponentialBackoff(etcdBackoff, func() (bool, error) {\n\t\tcli, err := c.newEtcdClient(c.Endpoints)\n\t\tif err != nil {\n\t\t\tlastError = err\n\t\t\treturn false, nil\n\t\t}\n\t\tdefer cli.Close()\n\n\t\tctx, cancel := context.WithTimeout(context.Background(), etcdTimeout)\n\t\tresp, err = cli.MemberRemove(ctx, id)\n\t\tcancel()\n\t\tif err == nil {\n\t\t\treturn true, nil\n\t\t}\n\t\tif errors.Is(rpctypes.ErrMemberNotFound, err) {\n\t\t\tklog.V(5).Infof(\"Member was already removed, because member %016x was not found\", id)\n\t\t\treturn true, nil\n\t\t}\n\t\tklog.V(5).Infof(\"Failed to remove etcd member: %v\", err)\n\t\tlastError = err\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\treturn nil, lastError\n\t}\n\n\t// Returns the updated list of etcd members\n\tret := []Member{}\n\tfor _, m := range resp.Members {\n\t\tret = append(ret, Member{Name: m.Name, PeerURL: m.PeerURLs[0]})\n\t}\n\n\treturn ret, nil\n}","line":{"from":332,"to":370}} {"id":100001344,"name":"AddMember","signature":"func (c *Client) AddMember(name string, peerAddrs string) ([]Member, error)","file":"cmd/kubeadm/app/util/etcd/etcd.go","code":"// AddMember adds a new member into the etcd cluster\nfunc (c *Client) AddMember(name string, peerAddrs string) ([]Member, error) {\n\treturn c.addMember(name, peerAddrs, false)\n}","line":{"from":372,"to":375}} {"id":100001345,"name":"AddMemberAsLearner","signature":"func (c *Client) AddMemberAsLearner(name string, peerAddrs string) ([]Member, error)","file":"cmd/kubeadm/app/util/etcd/etcd.go","code":"// AddMemberAsLearner adds a new learner member into the etcd cluster.\nfunc (c *Client) AddMemberAsLearner(name string, peerAddrs string) ([]Member, error) {\n\treturn c.addMember(name, peerAddrs, true)\n}","line":{"from":377,"to":380}} {"id":100001346,"name":"addMember","signature":"func (c *Client) addMember(name string, peerAddrs string, isLearner bool) ([]Member, error)","file":"cmd/kubeadm/app/util/etcd/etcd.go","code":"// addMember notifies an existing etcd cluster that a new member is joining, and\n// return the updated list of members. If the member has already been added to the\n// cluster, this will return the existing list of etcd members.\nfunc (c *Client) addMember(name string, peerAddrs string, isLearner bool) ([]Member, error) {\n\t// Parse the peer address, required to add the client URL later to the list\n\t// of endpoints for this client. Parsing as a first operation to make sure that\n\t// if this fails no member addition is performed on the etcd cluster.\n\tparsedPeerAddrs, err := url.Parse(peerAddrs)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"error parsing peer address %s\", peerAddrs)\n\t}\n\n\tcli, err := c.newEtcdClient(c.Endpoints)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer cli.Close()\n\n\t// Adds a new member to the cluster\n\tvar (\n\t\tlastError error\n\t\trespMembers []*etcdserverpb.Member\n\t\tlearnerID uint64\n\t\tresp *clientv3.MemberAddResponse\n\t)\n\terr = wait.ExponentialBackoff(etcdBackoff, func() (bool, error) {\n\t\tctx, cancel := context.WithTimeout(context.Background(), etcdTimeout)\n\t\tdefer cancel()\n\t\tif isLearner {\n\t\t\t// if learnerID is set, it means the etcd member is already added successfully.\n\t\t\tif learnerID == 0 {\n\t\t\t\tklog.V(1).Infof(\"[etcd] Adding etcd member as learner: %016x\", peerAddrs)\n\t\t\t\tresp, err = cli.MemberAddAsLearner(ctx, []string{peerAddrs})\n\t\t\t\tif err != nil {\n\t\t\t\t\tlastError = err\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t\tlearnerID = resp.Member.ID\n\t\t\t}\n\t\t\trespMembers = resp.Members\n\t\t\treturn true, nil\n\t\t}\n\n\t\tresp, err = cli.MemberAdd(ctx, []string{peerAddrs})\n\t\tif err == nil {\n\t\t\trespMembers = resp.Members\n\t\t\treturn true, nil\n\t\t}\n\n\t\t// If the error indicates that the peer already exists, exit early. In this situation, resp is nil, so\n\t\t// call out to MemberList to fetch all the members before returning.\n\t\tif errors.Is(err, rpctypes.ErrPeerURLExist) {\n\t\t\tklog.V(5).Info(\"The peer URL for the added etcd member already exists. Fetching the existing etcd members\")\n\t\t\tvar listResp *clientv3.MemberListResponse\n\t\t\tlistResp, err = cli.MemberList(ctx)\n\t\t\tif err == nil {\n\t\t\t\trespMembers = listResp.Members\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\n\t\tklog.V(5).Infof(\"Failed to add etcd member: %v\", err)\n\t\tlastError = err\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\treturn nil, lastError\n\t}\n\n\t// Returns the updated list of etcd members\n\tret := []Member{}\n\tfor _, m := range respMembers {\n\t\t// If the peer address matches, this is the member we are adding.\n\t\t// Use the name we passed to the function.\n\t\tif peerAddrs == m.PeerURLs[0] {\n\t\t\tret = append(ret, Member{Name: name, PeerURL: peerAddrs})\n\t\t\tcontinue\n\t\t}\n\t\t// Otherwise, we are processing other existing etcd members returned by AddMembers.\n\t\tmemberName := m.Name\n\t\t// In some cases during concurrent join, some members can end up without a name.\n\t\t// Use the member ID as name for those.\n\t\tif len(memberName) == 0 {\n\t\t\tmemberName = strconv.FormatUint(m.ID, 16)\n\t\t}\n\t\tret = append(ret, Member{Name: memberName, PeerURL: m.PeerURLs[0]})\n\t}\n\n\t// Add the new member client address to the list of endpoints\n\tc.Endpoints = append(c.Endpoints, GetClientURLByIP(parsedPeerAddrs.Hostname()))\n\n\treturn ret, nil\n}","line":{"from":382,"to":474}} {"id":100001347,"name":"isLearner","signature":"func (c *Client) isLearner(memberID uint64) (bool, error)","file":"cmd/kubeadm/app/util/etcd/etcd.go","code":"// isLearner returns true if the given member ID is a learner.\nfunc (c *Client) isLearner(memberID uint64) (bool, error) {\n\tresp, err := c.listMembers()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tfor _, member := range resp.Members {\n\t\tif member.ID == memberID \u0026\u0026 member.IsLearner {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}","line":{"from":476,"to":489}} {"id":100001348,"name":"MemberPromote","signature":"func (c *Client) MemberPromote(learnerID uint64) error","file":"cmd/kubeadm/app/util/etcd/etcd.go","code":"// MemberPromote promotes a member as a voting member. If the given member ID is already a voting member this method\n// will return early and do nothing.\nfunc (c *Client) MemberPromote(learnerID uint64) error {\n\tisLearner, err := c.isLearner(learnerID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !isLearner {\n\t\tklog.V(1).Infof(\"[etcd] Member %016x already promoted.\", learnerID)\n\t\treturn nil\n\t}\n\n\tklog.V(1).Infof(\"[etcd] Promoting a learner as a voting member: %016x\", learnerID)\n\tcli, err := c.newEtcdClient(c.Endpoints)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer cli.Close()\n\n\t// TODO: warning logs from etcd client should be removed.\n\t// The warning logs are printed by etcd client code for several reasons, including\n\t// 1. can not promote yet(no synced)\n\t// 2. context deadline exceeded\n\t// 3. peer URLs already exists\n\t// Once the client provides a way to check if the etcd learner is ready to promote, the retry logic can be revisited.\n\tvar (\n\t\tlastError error\n\t)\n\terr = wait.ExponentialBackoff(etcdBackoff, func() (bool, error) {\n\t\tctx, cancel := context.WithTimeout(context.Background(), etcdTimeout)\n\t\tdefer cancel()\n\n\t\t_, err = cli.MemberPromote(ctx, learnerID)\n\t\tif err == nil {\n\t\t\tklog.V(1).Infof(\"[etcd] The learner was promoted as a voting member: %016x\", learnerID)\n\t\t\treturn true, nil\n\t\t}\n\t\tklog.V(5).Infof(\"[etcd] Promoting the learner %016x failed: %v\", learnerID, err)\n\t\tlastError = err\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\treturn lastError\n\t}\n\treturn nil\n}","line":{"from":491,"to":536}} {"id":100001349,"name":"CheckClusterHealth","signature":"func (c *Client) CheckClusterHealth() error","file":"cmd/kubeadm/app/util/etcd/etcd.go","code":"// CheckClusterHealth returns nil for status Up or error for status Down\nfunc (c *Client) CheckClusterHealth() error {\n\t_, err := c.getClusterStatus()\n\treturn err\n}","line":{"from":538,"to":542}} {"id":100001350,"name":"getClusterStatus","signature":"func (c *Client) getClusterStatus() (map[string]*clientv3.StatusResponse, error)","file":"cmd/kubeadm/app/util/etcd/etcd.go","code":"// getClusterStatus returns nil for status Up (along with endpoint status response map) or error for status Down\nfunc (c *Client) getClusterStatus() (map[string]*clientv3.StatusResponse, error) {\n\tclusterStatus := make(map[string]*clientv3.StatusResponse)\n\tfor _, ep := range c.Endpoints {\n\t\t// Gets the member status\n\t\tvar lastError error\n\t\tvar resp *clientv3.StatusResponse\n\t\terr := wait.ExponentialBackoff(etcdBackoff, func() (bool, error) {\n\t\t\tcli, err := c.newEtcdClient(c.Endpoints)\n\t\t\tif err != nil {\n\t\t\t\tlastError = err\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\tdefer cli.Close()\n\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), etcdTimeout)\n\t\t\tresp, err = cli.Status(ctx, ep)\n\t\t\tcancel()\n\t\t\tif err == nil {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\tklog.V(5).Infof(\"Failed to get etcd status for %s: %v\", ep, err)\n\t\t\tlastError = err\n\t\t\treturn false, nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, lastError\n\t\t}\n\n\t\tclusterStatus[ep] = resp\n\t}\n\treturn clusterStatus, nil\n}","line":{"from":544,"to":576}} {"id":100001351,"name":"WaitForClusterAvailable","signature":"func (c *Client) WaitForClusterAvailable(retries int, retryInterval time.Duration) (bool, error)","file":"cmd/kubeadm/app/util/etcd/etcd.go","code":"// WaitForClusterAvailable returns true if all endpoints in the cluster are available after retry attempts, an error is returned otherwise\nfunc (c *Client) WaitForClusterAvailable(retries int, retryInterval time.Duration) (bool, error) {\n\tfor i := 0; i \u003c retries; i++ {\n\t\tif i \u003e 0 {\n\t\t\tklog.V(1).Infof(\"[etcd] Waiting %v until next retry\\n\", retryInterval)\n\t\t\ttime.Sleep(retryInterval)\n\t\t}\n\t\tklog.V(2).Infof(\"[etcd] attempting to see if all cluster endpoints (%s) are available %d/%d\", c.Endpoints, i+1, retries)\n\t\t_, err := c.getClusterStatus()\n\t\tif err != nil {\n\t\t\tswitch err {\n\t\t\tcase context.DeadlineExceeded:\n\t\t\t\tklog.V(1).Infof(\"[etcd] Attempt timed out\")\n\t\t\tdefault:\n\t\t\t\tklog.V(1).Infof(\"[etcd] Attempt failed with error: %v\\n\", err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\treturn true, nil\n\t}\n\treturn false, errors.New(\"timeout waiting for etcd cluster to be available\")\n}","line":{"from":578,"to":599}} {"id":100001352,"name":"GetClientURL","signature":"func GetClientURL(localEndpoint *kubeadmapi.APIEndpoint) string","file":"cmd/kubeadm/app/util/etcd/etcd.go","code":"// GetClientURL creates an HTTPS URL that uses the configured advertise\n// address and client port for the API controller\nfunc GetClientURL(localEndpoint *kubeadmapi.APIEndpoint) string {\n\treturn \"https://\" + net.JoinHostPort(localEndpoint.AdvertiseAddress, strconv.Itoa(constants.EtcdListenClientPort))\n}","line":{"from":601,"to":605}} {"id":100001353,"name":"GetPeerURL","signature":"func GetPeerURL(localEndpoint *kubeadmapi.APIEndpoint) string","file":"cmd/kubeadm/app/util/etcd/etcd.go","code":"// GetPeerURL creates an HTTPS URL that uses the configured advertise\n// address and peer port for the API controller\nfunc GetPeerURL(localEndpoint *kubeadmapi.APIEndpoint) string {\n\treturn \"https://\" + net.JoinHostPort(localEndpoint.AdvertiseAddress, strconv.Itoa(constants.EtcdListenPeerPort))\n}","line":{"from":607,"to":611}} {"id":100001354,"name":"GetClientURLByIP","signature":"func GetClientURLByIP(ip string) string","file":"cmd/kubeadm/app/util/etcd/etcd.go","code":"// GetClientURLByIP creates an HTTPS URL based on an IP address\n// and the client listening port.\nfunc GetClientURLByIP(ip string) string {\n\treturn \"https://\" + net.JoinHostPort(ip, strconv.Itoa(constants.EtcdListenClientPort))\n}","line":{"from":613,"to":617}} {"id":100001355,"name":"CreateDataDirectory","signature":"func CreateDataDirectory(dir string) error","file":"cmd/kubeadm/app/util/etcd/etcddata.go","code":"// CreateDataDirectory creates the etcd data directory (commonly /var/lib/etcd) with the right permissions.\nfunc CreateDataDirectory(dir string) error {\n\tif err := os.MkdirAll(dir, 0700); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to create the etcd data directory: %q\", dir)\n\t}\n\treturn nil\n}","line":{"from":25,"to":31}} {"id":100001356,"name":"TagFromImage","signature":"func TagFromImage(image string) string","file":"cmd/kubeadm/app/util/image/image.go","code":"// TagFromImage extracts a tag from image. An empty string is returned if no tag is discovered.\nfunc TagFromImage(image string) string {\n\tmatches := tagMatcher.FindStringSubmatch(image)\n\tif len(matches) \u003e= 2 {\n\t\treturn matches[1]\n\t}\n\treturn \"\"\n}","line":{"from":31,"to":38}} {"id":100001357,"name":"ServiceStart","signature":"func (openrc OpenRCInitSystem) ServiceStart(service string) error","file":"cmd/kubeadm/app/util/initsystem/initsystem_unix.go","code":"// ServiceStart tries to start a specific service\nfunc (openrc OpenRCInitSystem) ServiceStart(service string) error {\n\targs := []string{service, \"start\"}\n\treturn exec.Command(\"rc-service\", args...).Run()\n}","line":{"from":33,"to":37}} {"id":100001358,"name":"ServiceStop","signature":"func (openrc OpenRCInitSystem) ServiceStop(service string) error","file":"cmd/kubeadm/app/util/initsystem/initsystem_unix.go","code":"// ServiceStop tries to stop a specific service\nfunc (openrc OpenRCInitSystem) ServiceStop(service string) error {\n\targs := []string{service, \"stop\"}\n\treturn exec.Command(\"rc-service\", args...).Run()\n}","line":{"from":39,"to":43}} {"id":100001359,"name":"ServiceRestart","signature":"func (openrc OpenRCInitSystem) ServiceRestart(service string) error","file":"cmd/kubeadm/app/util/initsystem/initsystem_unix.go","code":"// ServiceRestart tries to reload the environment and restart the specific service\nfunc (openrc OpenRCInitSystem) ServiceRestart(service string) error {\n\targs := []string{service, \"restart\"}\n\treturn exec.Command(\"rc-service\", args...).Run()\n}","line":{"from":45,"to":49}} {"id":100001360,"name":"ServiceExists","signature":"func (openrc OpenRCInitSystem) ServiceExists(service string) bool","file":"cmd/kubeadm/app/util/initsystem/initsystem_unix.go","code":"// ServiceExists ensures the service is defined for this init system.\n// openrc writes to stderr if a service is not found or not enabled\n// this is in contrast to systemd which only writes to stdout.\n// Hence, we use the Combinedoutput, and ignore the error.\nfunc (openrc OpenRCInitSystem) ServiceExists(service string) bool {\n\targs := []string{service, \"status\"}\n\toutBytes, _ := exec.Command(\"rc-service\", args...).CombinedOutput()\n\treturn !strings.Contains(string(outBytes), \"does not exist\")\n}","line":{"from":51,"to":59}} {"id":100001361,"name":"ServiceIsEnabled","signature":"func (openrc OpenRCInitSystem) ServiceIsEnabled(service string) bool","file":"cmd/kubeadm/app/util/initsystem/initsystem_unix.go","code":"// ServiceIsEnabled ensures the service is enabled to start on each boot.\nfunc (openrc OpenRCInitSystem) ServiceIsEnabled(service string) bool {\n\targs := []string{\"show\", \"default\"}\n\toutBytes, _ := exec.Command(\"rc-update\", args...).Output()\n\treturn strings.Contains(string(outBytes), service)\n}","line":{"from":61,"to":66}} {"id":100001362,"name":"ServiceIsActive","signature":"func (openrc OpenRCInitSystem) ServiceIsActive(service string) bool","file":"cmd/kubeadm/app/util/initsystem/initsystem_unix.go","code":"// ServiceIsActive ensures the service is running, or attempting to run. (crash looping in the case of kubelet)\nfunc (openrc OpenRCInitSystem) ServiceIsActive(service string) bool {\n\targs := []string{service, \"status\"}\n\toutBytes, _ := exec.Command(\"rc-service\", args...).CombinedOutput()\n\toutStr := string(outBytes)\n\treturn !strings.Contains(outStr, \"stopped\") \u0026\u0026 !strings.Contains(outStr, \"does not exist\")\n}","line":{"from":68,"to":74}} {"id":100001363,"name":"EnableCommand","signature":"func (openrc OpenRCInitSystem) EnableCommand(service string) string","file":"cmd/kubeadm/app/util/initsystem/initsystem_unix.go","code":"// EnableCommand return a string describing how to enable a service\nfunc (openrc OpenRCInitSystem) EnableCommand(service string) string {\n\treturn fmt.Sprintf(\"rc-update add %s default\", service)\n}","line":{"from":76,"to":79}} {"id":100001364,"name":"EnableCommand","signature":"func (sysd SystemdInitSystem) EnableCommand(service string) string","file":"cmd/kubeadm/app/util/initsystem/initsystem_unix.go","code":"// EnableCommand return a string describing how to enable a service\nfunc (sysd SystemdInitSystem) EnableCommand(service string) string {\n\treturn fmt.Sprintf(\"systemctl enable %s.service\", service)\n}","line":{"from":84,"to":87}} {"id":100001365,"name":"reloadSystemd","signature":"func (sysd SystemdInitSystem) reloadSystemd() error","file":"cmd/kubeadm/app/util/initsystem/initsystem_unix.go","code":"// reloadSystemd reloads the systemd daemon\nfunc (sysd SystemdInitSystem) reloadSystemd() error {\n\tif err := exec.Command(\"systemctl\", \"daemon-reload\").Run(); err != nil {\n\t\treturn errors.Wrap(err, \"failed to reload systemd\")\n\t}\n\treturn nil\n}","line":{"from":89,"to":95}} {"id":100001366,"name":"ServiceStart","signature":"func (sysd SystemdInitSystem) ServiceStart(service string) error","file":"cmd/kubeadm/app/util/initsystem/initsystem_unix.go","code":"// ServiceStart tries to start a specific service\nfunc (sysd SystemdInitSystem) ServiceStart(service string) error {\n\t// Before we try to start any service, make sure that systemd is ready\n\tif err := sysd.reloadSystemd(); err != nil {\n\t\treturn err\n\t}\n\targs := []string{\"start\", service}\n\treturn exec.Command(\"systemctl\", args...).Run()\n}","line":{"from":97,"to":105}} {"id":100001367,"name":"ServiceRestart","signature":"func (sysd SystemdInitSystem) ServiceRestart(service string) error","file":"cmd/kubeadm/app/util/initsystem/initsystem_unix.go","code":"// ServiceRestart tries to reload the environment and restart the specific service\nfunc (sysd SystemdInitSystem) ServiceRestart(service string) error {\n\t// Before we try to restart any service, make sure that systemd is ready\n\tif err := sysd.reloadSystemd(); err != nil {\n\t\treturn err\n\t}\n\targs := []string{\"restart\", service}\n\treturn exec.Command(\"systemctl\", args...).Run()\n}","line":{"from":107,"to":115}} {"id":100001368,"name":"ServiceStop","signature":"func (sysd SystemdInitSystem) ServiceStop(service string) error","file":"cmd/kubeadm/app/util/initsystem/initsystem_unix.go","code":"// ServiceStop tries to stop a specific service\nfunc (sysd SystemdInitSystem) ServiceStop(service string) error {\n\targs := []string{\"stop\", service}\n\treturn exec.Command(\"systemctl\", args...).Run()\n}","line":{"from":117,"to":121}} {"id":100001369,"name":"ServiceExists","signature":"func (sysd SystemdInitSystem) ServiceExists(service string) bool","file":"cmd/kubeadm/app/util/initsystem/initsystem_unix.go","code":"// ServiceExists ensures the service is defined for this init system.\nfunc (sysd SystemdInitSystem) ServiceExists(service string) bool {\n\targs := []string{\"status\", service}\n\toutBytes, _ := exec.Command(\"systemctl\", args...).Output()\n\toutput := string(outBytes)\n\treturn !strings.Contains(output, \"Loaded: not-found\")\n}","line":{"from":123,"to":129}} {"id":100001370,"name":"ServiceIsEnabled","signature":"func (sysd SystemdInitSystem) ServiceIsEnabled(service string) bool","file":"cmd/kubeadm/app/util/initsystem/initsystem_unix.go","code":"// ServiceIsEnabled ensures the service is enabled to start on each boot.\nfunc (sysd SystemdInitSystem) ServiceIsEnabled(service string) bool {\n\targs := []string{\"is-enabled\", service}\n\terr := exec.Command(\"systemctl\", args...).Run()\n\treturn err == nil\n}","line":{"from":131,"to":136}} {"id":100001371,"name":"ServiceIsActive","signature":"func (sysd SystemdInitSystem) ServiceIsActive(service string) bool","file":"cmd/kubeadm/app/util/initsystem/initsystem_unix.go","code":"// ServiceIsActive will check is the service is \"active\". In the case of\n// crash looping services (kubelet in our case) status will return as\n// \"activating\", so we will consider this active as well.\nfunc (sysd SystemdInitSystem) ServiceIsActive(service string) bool {\n\targs := []string{\"is-active\", service}\n\t// Ignoring error here, command returns non-0 if in \"activating\" status:\n\toutBytes, _ := exec.Command(\"systemctl\", args...).Output()\n\toutput := strings.TrimSpace(string(outBytes))\n\tif output == \"active\" || output == \"activating\" {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":138,"to":150}} {"id":100001372,"name":"GetInitSystem","signature":"func GetInitSystem() (InitSystem, error)","file":"cmd/kubeadm/app/util/initsystem/initsystem_unix.go","code":"// GetInitSystem returns an InitSystem for the current system, or nil\n// if we cannot detect a supported init system.\n// This indicates we will skip init system checks, not an error.\nfunc GetInitSystem() (InitSystem, error) {\n\t// Assume existence of systemctl in path implies this is a systemd system:\n\t_, err := exec.LookPath(\"systemctl\")\n\tif err == nil {\n\t\treturn \u0026SystemdInitSystem{}, nil\n\t}\n\t_, err = exec.LookPath(\"openrc\")\n\tif err == nil {\n\t\treturn \u0026OpenRCInitSystem{}, nil\n\t}\n\n\treturn nil, errors.New(\"no supported init system detected, skipping checking for services\")\n}","line":{"from":152,"to":167}} {"id":100001373,"name":"EnableCommand","signature":"func (sysd WindowsInitSystem) EnableCommand(service string) string","file":"cmd/kubeadm/app/util/initsystem/initsystem_windows.go","code":"// EnableCommand return a string describing how to enable a service\nfunc (sysd WindowsInitSystem) EnableCommand(service string) string {\n\treturn fmt.Sprintf(\"Set-Service '%s' -StartupType Automatic\", service)\n}","line":{"from":34,"to":37}} {"id":100001374,"name":"ServiceStart","signature":"func (sysd WindowsInitSystem) ServiceStart(service string) error","file":"cmd/kubeadm/app/util/initsystem/initsystem_windows.go","code":"// ServiceStart tries to start a specific service\n// Following Windows documentation: https://docs.microsoft.com/en-us/windows/desktop/Services/starting-a-service\nfunc (sysd WindowsInitSystem) ServiceStart(service string) error {\n\tm, err := mgr.Connect()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer m.Disconnect()\n\n\ts, err := m.OpenService(service)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"could not access service %s\", service)\n\t}\n\tdefer s.Close()\n\n\t// Check if service is already started\n\tstatus, err := s.Query()\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"could not query service %s\", service)\n\t}\n\n\tif status.State != svc.Stopped \u0026\u0026 status.State != svc.StopPending {\n\t\treturn nil\n\t}\n\n\ttimeout := time.Now().Add(10 * time.Second)\n\tfor status.State != svc.Stopped {\n\t\tif timeout.Before(time.Now()) {\n\t\t\treturn errors.Errorf(\"timeout waiting for %s service to stop\", service)\n\t\t}\n\t\ttime.Sleep(300 * time.Millisecond)\n\t\tstatus, err = s.Query()\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"could not retrieve %s service status\", service)\n\t\t}\n\t}\n\n\t// Start the service\n\terr = s.Start(\"is\", \"manual-started\")\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"could not start service %s\", service)\n\t}\n\n\t// Check that the start was successful\n\tstatus, err = s.Query()\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"could not query service %s\", service)\n\t}\n\ttimeout = time.Now().Add(10 * time.Second)\n\tfor status.State != svc.Running {\n\t\tif timeout.Before(time.Now()) {\n\t\t\treturn errors.Errorf(\"timeout waiting for %s service to start\", service)\n\t\t}\n\t\ttime.Sleep(300 * time.Millisecond)\n\t\tstatus, err = s.Query()\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"could not retrieve %s service status\", service)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":39,"to":99}} {"id":100001375,"name":"ServiceRestart","signature":"func (sysd WindowsInitSystem) ServiceRestart(service string) error","file":"cmd/kubeadm/app/util/initsystem/initsystem_windows.go","code":"// ServiceRestart tries to reload the environment and restart the specific service\nfunc (sysd WindowsInitSystem) ServiceRestart(service string) error {\n\tif err := sysd.ServiceStop(service); err != nil {\n\t\treturn errors.Wrapf(err, \"couldn't stop service %s\", service)\n\t}\n\tif err := sysd.ServiceStart(service); err != nil {\n\t\treturn errors.Wrapf(err, \"couldn't start service %s\", service)\n\t}\n\n\treturn nil\n}","line":{"from":101,"to":111}} {"id":100001376,"name":"ServiceStop","signature":"func (sysd WindowsInitSystem) ServiceStop(service string) error","file":"cmd/kubeadm/app/util/initsystem/initsystem_windows.go","code":"// ServiceStop tries to stop a specific service\n// Following Windows documentation: https://docs.microsoft.com/en-us/windows/desktop/Services/stopping-a-service\nfunc (sysd WindowsInitSystem) ServiceStop(service string) error {\n\tm, err := mgr.Connect()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer m.Disconnect()\n\n\ts, err := m.OpenService(service)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"could not access service %s\", service)\n\t}\n\tdefer s.Close()\n\n\t// Check if service is already stopped\n\tstatus, err := s.Query()\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"could not query service %s\", service)\n\t}\n\n\tif status.State == svc.Stopped {\n\t\treturn nil\n\t}\n\n\t// If StopPending, check that service eventually stops\n\tif status.State == svc.StopPending {\n\t\ttimeout := time.Now().Add(10 * time.Second)\n\t\tfor status.State != svc.Stopped {\n\t\t\tif timeout.Before(time.Now()) {\n\t\t\t\treturn errors.Errorf(\"timeout waiting for %s service to stop\", service)\n\t\t\t}\n\t\t\ttime.Sleep(300 * time.Millisecond)\n\t\t\tstatus, err = s.Query()\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"could not retrieve %s service status\", service)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\t// Stop the service\n\tstatus, err = s.Control(svc.Stop)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"could not stop service %s\", service)\n\t}\n\n\t// Check that the stop was successful\n\tstatus, err = s.Query()\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"could not query service %s\", service)\n\t}\n\ttimeout := time.Now().Add(10 * time.Second)\n\tfor status.State != svc.Stopped {\n\t\tif timeout.Before(time.Now()) {\n\t\t\treturn errors.Errorf(\"timeout waiting for %s service to stop\", service)\n\t\t}\n\t\ttime.Sleep(300 * time.Millisecond)\n\t\tstatus, err = s.Query()\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"could not retrieve %s service status\", service)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":113,"to":177}} {"id":100001377,"name":"ServiceExists","signature":"func (sysd WindowsInitSystem) ServiceExists(service string) bool","file":"cmd/kubeadm/app/util/initsystem/initsystem_windows.go","code":"// ServiceExists ensures the service is defined for this init system.\nfunc (sysd WindowsInitSystem) ServiceExists(service string) bool {\n\tm, err := mgr.Connect()\n\tif err != nil {\n\t\treturn false\n\t}\n\tdefer m.Disconnect()\n\ts, err := m.OpenService(service)\n\tif err != nil {\n\t\treturn false\n\t}\n\tdefer s.Close()\n\n\treturn true\n}","line":{"from":179,"to":193}} {"id":100001378,"name":"ServiceIsEnabled","signature":"func (sysd WindowsInitSystem) ServiceIsEnabled(service string) bool","file":"cmd/kubeadm/app/util/initsystem/initsystem_windows.go","code":"// ServiceIsEnabled ensures the service is enabled to start on each boot.\nfunc (sysd WindowsInitSystem) ServiceIsEnabled(service string) bool {\n\tm, err := mgr.Connect()\n\tif err != nil {\n\t\treturn false\n\t}\n\tdefer m.Disconnect()\n\n\ts, err := m.OpenService(service)\n\tif err != nil {\n\t\treturn false\n\t}\n\tdefer s.Close()\n\n\tc, err := s.Config()\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn c.StartType != mgr.StartDisabled\n}","line":{"from":195,"to":215}} {"id":100001379,"name":"ServiceIsActive","signature":"func (sysd WindowsInitSystem) ServiceIsActive(service string) bool","file":"cmd/kubeadm/app/util/initsystem/initsystem_windows.go","code":"// ServiceIsActive ensures the service is running, or attempting to run. (crash looping in the case of kubelet)\nfunc (sysd WindowsInitSystem) ServiceIsActive(service string) bool {\n\tm, err := mgr.Connect()\n\tif err != nil {\n\t\treturn false\n\t}\n\tdefer m.Disconnect()\n\ts, err := m.OpenService(service)\n\tif err != nil {\n\t\treturn false\n\t}\n\tdefer s.Close()\n\n\tstatus, err := s.Query()\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn status.State == svc.Running\n}","line":{"from":217,"to":235}} {"id":100001380,"name":"GetInitSystem","signature":"func GetInitSystem() (InitSystem, error)","file":"cmd/kubeadm/app/util/initsystem/initsystem_windows.go","code":"// GetInitSystem returns an InitSystem for the current system, or nil\n// if we cannot detect a supported init system.\n// This indicates we will skip init system checks, not an error.\nfunc GetInitSystem() (InitSystem, error) {\n\tm, err := mgr.Connect()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"no supported init system detected\")\n\t}\n\tdefer m.Disconnect()\n\treturn \u0026WindowsInitSystem{}, nil\n}","line":{"from":237,"to":247}} {"id":100001381,"name":"CreateBasic","signature":"func CreateBasic(serverURL, clusterName, userName string, caCert []byte) *clientcmdapi.Config","file":"cmd/kubeadm/app/util/kubeconfig/kubeconfig.go","code":"// CreateBasic creates a basic, general KubeConfig object that then can be extended\nfunc CreateBasic(serverURL, clusterName, userName string, caCert []byte) *clientcmdapi.Config {\n\t// Use the cluster and the username as the context name\n\tcontextName := fmt.Sprintf(\"%s@%s\", userName, clusterName)\n\n\treturn \u0026clientcmdapi.Config{\n\t\tClusters: map[string]*clientcmdapi.Cluster{\n\t\t\tclusterName: {\n\t\t\t\tServer: serverURL,\n\t\t\t\tCertificateAuthorityData: caCert,\n\t\t\t},\n\t\t},\n\t\tContexts: map[string]*clientcmdapi.Context{\n\t\t\tcontextName: {\n\t\t\t\tCluster: clusterName,\n\t\t\t\tAuthInfo: userName,\n\t\t\t},\n\t\t},\n\t\tAuthInfos: map[string]*clientcmdapi.AuthInfo{},\n\t\tCurrentContext: contextName,\n\t}\n}","line":{"from":30,"to":51}} {"id":100001382,"name":"CreateWithCerts","signature":"func CreateWithCerts(serverURL, clusterName, userName string, caCert []byte, clientKey []byte, clientCert []byte) *clientcmdapi.Config","file":"cmd/kubeadm/app/util/kubeconfig/kubeconfig.go","code":"// CreateWithCerts creates a KubeConfig object with access to the API server with client certificates\nfunc CreateWithCerts(serverURL, clusterName, userName string, caCert []byte, clientKey []byte, clientCert []byte) *clientcmdapi.Config {\n\tconfig := CreateBasic(serverURL, clusterName, userName, caCert)\n\tconfig.AuthInfos[userName] = \u0026clientcmdapi.AuthInfo{\n\t\tClientKeyData: clientKey,\n\t\tClientCertificateData: clientCert,\n\t}\n\treturn config\n}","line":{"from":53,"to":61}} {"id":100001383,"name":"CreateWithToken","signature":"func CreateWithToken(serverURL, clusterName, userName string, caCert []byte, token string) *clientcmdapi.Config","file":"cmd/kubeadm/app/util/kubeconfig/kubeconfig.go","code":"// CreateWithToken creates a KubeConfig object with access to the API server with a token\nfunc CreateWithToken(serverURL, clusterName, userName string, caCert []byte, token string) *clientcmdapi.Config {\n\tconfig := CreateBasic(serverURL, clusterName, userName, caCert)\n\tconfig.AuthInfos[userName] = \u0026clientcmdapi.AuthInfo{\n\t\tToken: token,\n\t}\n\treturn config\n}","line":{"from":63,"to":70}} {"id":100001384,"name":"ClientSetFromFile","signature":"func ClientSetFromFile(path string) (*clientset.Clientset, error)","file":"cmd/kubeadm/app/util/kubeconfig/kubeconfig.go","code":"// ClientSetFromFile returns a ready-to-use client from a kubeconfig file\nfunc ClientSetFromFile(path string) (*clientset.Clientset, error) {\n\tconfig, err := clientcmd.LoadFromFile(path)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to load admin kubeconfig\")\n\t}\n\treturn ToClientSet(config)\n}","line":{"from":72,"to":79}} {"id":100001385,"name":"ToClientSet","signature":"func ToClientSet(config *clientcmdapi.Config) (*clientset.Clientset, error)","file":"cmd/kubeadm/app/util/kubeconfig/kubeconfig.go","code":"// ToClientSet converts a KubeConfig object to a client\nfunc ToClientSet(config *clientcmdapi.Config) (*clientset.Clientset, error) {\n\toverrides := clientcmd.ConfigOverrides{Timeout: \"10s\"}\n\tclientConfig, err := clientcmd.NewDefaultClientConfig(*config, \u0026overrides).ClientConfig()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create API client configuration from kubeconfig\")\n\t}\n\n\tclient, err := clientset.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create API client\")\n\t}\n\treturn client, nil\n}","line":{"from":81,"to":94}} {"id":100001386,"name":"WriteToDisk","signature":"func WriteToDisk(filename string, kubeconfig *clientcmdapi.Config) error","file":"cmd/kubeadm/app/util/kubeconfig/kubeconfig.go","code":"// WriteToDisk writes a KubeConfig object down to disk with mode 0600\nfunc WriteToDisk(filename string, kubeconfig *clientcmdapi.Config) error {\n\terr := clientcmd.WriteToFile(*kubeconfig, filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":96,"to":104}} {"id":100001387,"name":"GetClusterFromKubeConfig","signature":"func GetClusterFromKubeConfig(config *clientcmdapi.Config) (string, *clientcmdapi.Cluster)","file":"cmd/kubeadm/app/util/kubeconfig/kubeconfig.go","code":"// GetClusterFromKubeConfig returns the default Cluster of the specified KubeConfig\nfunc GetClusterFromKubeConfig(config *clientcmdapi.Config) (string, *clientcmdapi.Cluster) {\n\t// If there is an unnamed cluster object, use it\n\tif config.Clusters[\"\"] != nil {\n\t\treturn \"\", config.Clusters[\"\"]\n\t}\n\n\tcurrentContext := config.Contexts[config.CurrentContext]\n\tif currentContext != nil {\n\t\treturn currentContext.Cluster, config.Clusters[currentContext.Cluster]\n\t}\n\treturn \"\", nil\n}","line":{"from":106,"to":118}} {"id":100001388,"name":"HasAuthenticationCredentials","signature":"func HasAuthenticationCredentials(config *clientcmdapi.Config) bool","file":"cmd/kubeadm/app/util/kubeconfig/kubeconfig.go","code":"// HasAuthenticationCredentials returns true if the current user has valid authentication credentials for\n// token authentication, basic authentication or X509 authentication\nfunc HasAuthenticationCredentials(config *clientcmdapi.Config) bool {\n\tauthInfo := getCurrentAuthInfo(config)\n\tif authInfo == nil {\n\t\treturn false\n\t}\n\n\t// token authentication\n\tif len(authInfo.Token) != 0 || len(authInfo.TokenFile) != 0 {\n\t\treturn true\n\t}\n\n\t// basic authentication\n\tif len(authInfo.Username) != 0 \u0026\u0026 len(authInfo.Password) != 0 {\n\t\treturn true\n\t}\n\n\t// X509 authentication\n\tif (len(authInfo.ClientCertificate) != 0 || len(authInfo.ClientCertificateData) != 0) \u0026\u0026\n\t\t(len(authInfo.ClientKey) != 0 || len(authInfo.ClientKeyData) != 0) {\n\t\treturn true\n\t}\n\n\t// exec authentication\n\tif authInfo.Exec != nil \u0026\u0026 len(authInfo.Exec.Command) != 0 {\n\t\treturn true\n\t}\n\n\t// authprovider authentication\n\tif authInfo.AuthProvider != nil \u0026\u0026 len(authInfo.AuthProvider.Name) != 0 {\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":120,"to":155}} {"id":100001389,"name":"EnsureAuthenticationInfoAreEmbedded","signature":"func EnsureAuthenticationInfoAreEmbedded(config *clientcmdapi.Config) error","file":"cmd/kubeadm/app/util/kubeconfig/kubeconfig.go","code":"// EnsureAuthenticationInfoAreEmbedded check if some authentication info are provided as external key/certificate\n// files, and eventually embeds such files into the kubeconfig file\nfunc EnsureAuthenticationInfoAreEmbedded(config *clientcmdapi.Config) error {\n\tauthInfo := getCurrentAuthInfo(config)\n\tif authInfo == nil {\n\t\treturn errors.New(\"invalid kubeconfig file. AuthInfo is not defined for the current user\")\n\t}\n\n\tif len(authInfo.ClientCertificateData) == 0 \u0026\u0026 len(authInfo.ClientCertificate) != 0 {\n\t\tclientCert, err := os.ReadFile(authInfo.ClientCertificate)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"error while reading client cert file defined in kubeconfig\")\n\t\t}\n\t\tauthInfo.ClientCertificateData = clientCert\n\t\tauthInfo.ClientCertificate = \"\"\n\t}\n\tif len(authInfo.ClientKeyData) == 0 \u0026\u0026 len(authInfo.ClientKey) != 0 {\n\t\tclientKey, err := os.ReadFile(authInfo.ClientKey)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"error while reading client key file defined in kubeconfig\")\n\t\t}\n\t\tauthInfo.ClientKeyData = clientKey\n\t\tauthInfo.ClientKey = \"\"\n\t}\n\tif len(authInfo.Token) == 0 \u0026\u0026 len(authInfo.TokenFile) != 0 {\n\t\ttokenBytes, err := os.ReadFile(authInfo.TokenFile)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"error while reading token file defined in kubeconfig\")\n\t\t}\n\t\tauthInfo.Token = string(tokenBytes)\n\t\tauthInfo.TokenFile = \"\"\n\t}\n\n\treturn nil\n}","line":{"from":157,"to":191}} {"id":100001390,"name":"EnsureCertificateAuthorityIsEmbedded","signature":"func EnsureCertificateAuthorityIsEmbedded(cluster *clientcmdapi.Cluster) error","file":"cmd/kubeadm/app/util/kubeconfig/kubeconfig.go","code":"// EnsureCertificateAuthorityIsEmbedded check if the certificate authority is provided as an external\n// file and eventually embeds it into the kubeconfig\nfunc EnsureCertificateAuthorityIsEmbedded(cluster *clientcmdapi.Cluster) error {\n\tif cluster == nil {\n\t\treturn errors.New(\"received nil value for Cluster\")\n\t}\n\n\tif len(cluster.CertificateAuthorityData) == 0 \u0026\u0026 len(cluster.CertificateAuthority) != 0 {\n\t\tca, err := os.ReadFile(cluster.CertificateAuthority)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"error while reading certificate authority file defined in kubeconfig\")\n\t\t}\n\t\tcluster.CertificateAuthorityData = ca\n\t\tcluster.CertificateAuthority = \"\"\n\t}\n\n\treturn nil\n}","line":{"from":193,"to":210}} {"id":100001391,"name":"getCurrentAuthInfo","signature":"func getCurrentAuthInfo(config *clientcmdapi.Config) *clientcmdapi.AuthInfo","file":"cmd/kubeadm/app/util/kubeconfig/kubeconfig.go","code":"// getCurrentAuthInfo returns current authInfo, if defined\nfunc getCurrentAuthInfo(config *clientcmdapi.Config) *clientcmdapi.AuthInfo {\n\tif config == nil || config.CurrentContext == \"\" ||\n\t\tlen(config.Contexts) == 0 || config.Contexts[config.CurrentContext] == nil {\n\t\treturn nil\n\t}\n\tuser := config.Contexts[config.CurrentContext].AuthInfo\n\n\tif user == \"\" || len(config.AuthInfos) == 0 || config.AuthInfos[user] == nil {\n\t\treturn nil\n\t}\n\n\treturn config.AuthInfos[user]\n}","line":{"from":212,"to":225}} {"id":100001392,"name":"MarshalToYaml","signature":"func MarshalToYaml(obj runtime.Object, gv schema.GroupVersion) ([]byte, error)","file":"cmd/kubeadm/app/util/marshal.go","code":"// MarshalToYaml marshals an object into yaml.\nfunc MarshalToYaml(obj runtime.Object, gv schema.GroupVersion) ([]byte, error) {\n\treturn MarshalToYamlForCodecs(obj, gv, clientsetscheme.Codecs)\n}","line":{"from":38,"to":41}} {"id":100001393,"name":"MarshalToYamlForCodecs","signature":"func MarshalToYamlForCodecs(obj runtime.Object, gv schema.GroupVersion, codecs serializer.CodecFactory) ([]byte, error)","file":"cmd/kubeadm/app/util/marshal.go","code":"// MarshalToYamlForCodecs marshals an object into yaml using the specified codec\n// TODO: Is specifying the gv really needed here?\n// TODO: Can we support json out of the box easily here?\nfunc MarshalToYamlForCodecs(obj runtime.Object, gv schema.GroupVersion, codecs serializer.CodecFactory) ([]byte, error) {\n\tconst mediaType = runtime.ContentTypeYAML\n\tinfo, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), mediaType)\n\tif !ok {\n\t\treturn []byte{}, errors.Errorf(\"unsupported media type %q\", mediaType)\n\t}\n\n\tencoder := codecs.EncoderForVersion(info.Serializer, gv)\n\treturn runtime.Encode(encoder, obj)\n}","line":{"from":43,"to":55}} {"id":100001394,"name":"UnmarshalFromYaml","signature":"func UnmarshalFromYaml(buffer []byte, gv schema.GroupVersion) (runtime.Object, error)","file":"cmd/kubeadm/app/util/marshal.go","code":"// UnmarshalFromYaml unmarshals yaml into an object.\nfunc UnmarshalFromYaml(buffer []byte, gv schema.GroupVersion) (runtime.Object, error) {\n\treturn UnmarshalFromYamlForCodecs(buffer, gv, clientsetscheme.Codecs)\n}","line":{"from":57,"to":60}} {"id":100001395,"name":"UnmarshalFromYamlForCodecs","signature":"func UnmarshalFromYamlForCodecs(buffer []byte, gv schema.GroupVersion, codecs serializer.CodecFactory) (runtime.Object, error)","file":"cmd/kubeadm/app/util/marshal.go","code":"// UnmarshalFromYamlForCodecs unmarshals yaml into an object using the specified codec\n// TODO: Is specifying the gv really needed here?\n// TODO: Can we support json out of the box easily here?\nfunc UnmarshalFromYamlForCodecs(buffer []byte, gv schema.GroupVersion, codecs serializer.CodecFactory) (runtime.Object, error) {\n\tconst mediaType = runtime.ContentTypeYAML\n\tinfo, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), mediaType)\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"unsupported media type %q\", mediaType)\n\t}\n\n\tdecoder := codecs.DecoderToVersion(info.Serializer, gv)\n\tobj, err := runtime.Decode(decoder, buffer)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to decode %s into runtime.Object\", buffer)\n\t}\n\treturn obj, nil\n}","line":{"from":62,"to":78}} {"id":100001396,"name":"SplitYAMLDocuments","signature":"func SplitYAMLDocuments(yamlBytes []byte) (kubeadmapi.DocumentMap, error)","file":"cmd/kubeadm/app/util/marshal.go","code":"// SplitYAMLDocuments reads the YAML bytes per-document, unmarshals the TypeMeta information from each document\n// and returns a map between the GroupVersionKind of the document and the document bytes\nfunc SplitYAMLDocuments(yamlBytes []byte) (kubeadmapi.DocumentMap, error) {\n\tgvkmap := kubeadmapi.DocumentMap{}\n\tknownKinds := map[string]bool{}\n\terrs := []error{}\n\tbuf := bytes.NewBuffer(yamlBytes)\n\treader := utilyaml.NewYAMLReader(bufio.NewReader(buf))\n\tfor {\n\t\t// Read one YAML document at a time, until io.EOF is returned\n\t\tb, err := reader.Read()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(b) == 0 {\n\t\t\tbreak\n\t\t}\n\t\t// Deserialize the TypeMeta information of this byte slice\n\t\tgvk, err := yamlserializer.DefaultMetaFactory.Interpret(b)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(gvk.Group) == 0 || len(gvk.Version) == 0 || len(gvk.Kind) == 0 {\n\t\t\treturn nil, errors.Errorf(\"invalid configuration for GroupVersionKind %+v: kind and apiVersion is mandatory information that must be specified\", gvk)\n\t\t}\n\n\t\t// Check whether the kind has been registered before. If it has, throw an error\n\t\tif known := knownKinds[gvk.Kind]; known {\n\t\t\terrs = append(errs, errors.Errorf(\"invalid configuration: kind %q is specified twice in YAML file\", gvk.Kind))\n\t\t\tcontinue\n\t\t}\n\t\tknownKinds[gvk.Kind] = true\n\n\t\t// Save the mapping between the gvk and the bytes that object consists of\n\t\tgvkmap[*gvk] = b\n\t}\n\tif err := errorsutil.NewAggregate(errs); err != nil {\n\t\treturn nil, err\n\t}\n\treturn gvkmap, nil\n}","line":{"from":80,"to":122}} {"id":100001397,"name":"GroupVersionKindsFromBytes","signature":"func GroupVersionKindsFromBytes(b []byte) ([]schema.GroupVersionKind, error)","file":"cmd/kubeadm/app/util/marshal.go","code":"// GroupVersionKindsFromBytes parses the bytes and returns a gvk slice\nfunc GroupVersionKindsFromBytes(b []byte) ([]schema.GroupVersionKind, error) {\n\tgvkmap, err := SplitYAMLDocuments(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgvks := []schema.GroupVersionKind{}\n\tfor gvk := range gvkmap {\n\t\tgvks = append(gvks, gvk)\n\t}\n\treturn gvks, nil\n}","line":{"from":124,"to":135}} {"id":100001398,"name":"GroupVersionKindsHasKind","signature":"func GroupVersionKindsHasKind(gvks []schema.GroupVersionKind, kind string) bool","file":"cmd/kubeadm/app/util/marshal.go","code":"// GroupVersionKindsHasKind returns whether the following gvk slice contains the kind given as a parameter\nfunc GroupVersionKindsHasKind(gvks []schema.GroupVersionKind, kind string) bool {\n\tfor _, gvk := range gvks {\n\t\tif gvk.Kind == kind {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":137,"to":145}} {"id":100001399,"name":"GroupVersionKindsHasClusterConfiguration","signature":"func GroupVersionKindsHasClusterConfiguration(gvks ...schema.GroupVersionKind) bool","file":"cmd/kubeadm/app/util/marshal.go","code":"// GroupVersionKindsHasClusterConfiguration returns whether the following gvk slice contains a ClusterConfiguration object\nfunc GroupVersionKindsHasClusterConfiguration(gvks ...schema.GroupVersionKind) bool {\n\treturn GroupVersionKindsHasKind(gvks, constants.ClusterConfigurationKind)\n}","line":{"from":147,"to":150}} {"id":100001400,"name":"GroupVersionKindsHasInitConfiguration","signature":"func GroupVersionKindsHasInitConfiguration(gvks ...schema.GroupVersionKind) bool","file":"cmd/kubeadm/app/util/marshal.go","code":"// GroupVersionKindsHasInitConfiguration returns whether the following gvk slice contains a InitConfiguration object\nfunc GroupVersionKindsHasInitConfiguration(gvks ...schema.GroupVersionKind) bool {\n\treturn GroupVersionKindsHasKind(gvks, constants.InitConfigurationKind)\n}","line":{"from":152,"to":155}} {"id":100001401,"name":"GroupVersionKindsHasJoinConfiguration","signature":"func GroupVersionKindsHasJoinConfiguration(gvks ...schema.GroupVersionKind) bool","file":"cmd/kubeadm/app/util/marshal.go","code":"// GroupVersionKindsHasJoinConfiguration returns whether the following gvk slice contains a JoinConfiguration object\nfunc GroupVersionKindsHasJoinConfiguration(gvks ...schema.GroupVersionKind) bool {\n\treturn GroupVersionKindsHasKind(gvks, constants.JoinConfigurationKind)\n}","line":{"from":157,"to":160}} {"id":100001402,"name":"AllowedFormats","signature":"func (pf *PrintFlags) AllowedFormats() []string","file":"cmd/kubeadm/app/util/output/output.go","code":"// AllowedFormats returns a list of allowed output formats\nfunc (pf *PrintFlags) AllowedFormats() []string {\n\tret := []string{TextOutput}\n\tret = append(ret, pf.JSONYamlPrintFlags.AllowedFormats()...)\n\tret = append(ret, pf.KubeTemplatePrintFlags.AllowedFormats()...)\n\n\treturn ret\n}","line":{"from":63,"to":70}} {"id":100001403,"name":"ToPrinter","signature":"func (pf *PrintFlags) ToPrinter() (Printer, error)","file":"cmd/kubeadm/app/util/output/output.go","code":"// ToPrinter receives an outputFormat and returns a printer capable of\n// handling format printing.\n// Returns error if the specified outputFormat does not match supported formats.\nfunc (pf *PrintFlags) ToPrinter() (Printer, error) {\n\toutputFormat := \"\"\n\tif pf.OutputFormat != nil {\n\t\toutputFormat = *pf.OutputFormat\n\t}\n\n\tif pf.TextPrintFlags != nil {\n\t\tif p, err := pf.TextPrintFlags.ToPrinter(outputFormat); !genericclioptions.IsNoCompatiblePrinterError(err) {\n\t\t\treturn p, err\n\t\t}\n\t}\n\n\tif pf.JSONYamlPrintFlags != nil {\n\t\tif p, err := pf.JSONYamlPrintFlags.ToPrinter(outputFormat); !genericclioptions.IsNoCompatiblePrinterError(err) {\n\t\t\treturn NewResourcePrinterWrapper(pf.TypeSetterPrinter.WrapToPrinter(p, err))\n\t\t}\n\t}\n\n\tif pf.KubeTemplatePrintFlags != nil {\n\t\tif p, err := pf.KubeTemplatePrintFlags.ToPrinter(outputFormat); !genericclioptions.IsNoCompatiblePrinterError(err) {\n\t\t\treturn NewResourcePrinterWrapper(pf.TypeSetterPrinter.WrapToPrinter(p, err))\n\t\t}\n\t}\n\n\treturn nil, genericclioptions.NoCompatiblePrinterError{OutputFormat: pf.OutputFormat, AllowedFormats: pf.AllowedFormats()}\n}","line":{"from":72,"to":100}} {"id":100001404,"name":"AddFlags","signature":"func (pf *PrintFlags) AddFlags(cmd *cobra.Command)","file":"cmd/kubeadm/app/util/output/output.go","code":"// AddFlags receives a *cobra.Command reference and binds\n// flags related to Kubeadm printing to it\nfunc (pf *PrintFlags) AddFlags(cmd *cobra.Command) {\n\tpf.JSONYamlPrintFlags.AddFlags(cmd)\n\tpf.KubeTemplatePrintFlags.AddFlags(cmd)\n\tcmd.Flags().StringVarP(pf.OutputFormat, \"experimental-output\", \"o\", *pf.OutputFormat, fmt.Sprintf(\"Output format. One of: %s.\", strings.Join(pf.AllowedFormats(), \"|\")))\n}","line":{"from":102,"to":108}} {"id":100001405,"name":"WithDefaultOutput","signature":"func (pf *PrintFlags) WithDefaultOutput(outputFormat string) *PrintFlags","file":"cmd/kubeadm/app/util/output/output.go","code":"// WithDefaultOutput sets a default output format if one is not provided through a flag value\nfunc (pf *PrintFlags) WithDefaultOutput(outputFormat string) *PrintFlags {\n\tpf.OutputFormat = \u0026outputFormat\n\treturn pf\n}","line":{"from":110,"to":114}} {"id":100001406,"name":"WithTypeSetter","signature":"func (pf *PrintFlags) WithTypeSetter(scheme *runtime.Scheme) *PrintFlags","file":"cmd/kubeadm/app/util/output/output.go","code":"// WithTypeSetter sets a wrapper than will surround the returned printer with a printer to type resources\nfunc (pf *PrintFlags) WithTypeSetter(scheme *runtime.Scheme) *PrintFlags {\n\tpf.TypeSetterPrinter = printers.NewTypeSetter(scheme)\n\treturn pf\n}","line":{"from":116,"to":120}} {"id":100001407,"name":"NewOutputFlags","signature":"func NewOutputFlags(textPrintFlags TextPrintFlags) *PrintFlags","file":"cmd/kubeadm/app/util/output/output.go","code":"// NewOutputFlags creates new KubeadmOutputFlags\nfunc NewOutputFlags(textPrintFlags TextPrintFlags) *PrintFlags {\n\toutputFormat := \"\"\n\n\tpf := \u0026PrintFlags{\n\t\tOutputFormat: \u0026outputFormat,\n\n\t\tJSONYamlPrintFlags: genericclioptions.NewJSONYamlPrintFlags(),\n\t\tKubeTemplatePrintFlags: genericclioptions.NewKubeTemplatePrintFlags(),\n\t\tTextPrintFlags: textPrintFlags,\n\t}\n\n\t// disable deprecated --template option\n\tpf.KubeTemplatePrintFlags.TemplateArgument = nil\n\n\treturn pf\n}","line":{"from":122,"to":138}} {"id":100001408,"name":"PrintObj","signature":"func (tp *TextPrinter) PrintObj(obj runtime.Object, writer io.Writer) error","file":"cmd/kubeadm/app/util/output/output.go","code":"// PrintObj is an implementation of ResourcePrinter.PrintObj that prints object\nfunc (tp *TextPrinter) PrintObj(obj runtime.Object, writer io.Writer) error {\n\t_, err := fmt.Fprintf(writer, \"%+v\\n\", obj)\n\treturn err\n}","line":{"from":156,"to":160}} {"id":100001409,"name":"Fprintf","signature":"func (tp *TextPrinter) Fprintf(writer io.Writer, format string, args ...interface{}) (n int, err error)","file":"cmd/kubeadm/app/util/output/output.go","code":"// Fprintf is a wrapper around fmt.Fprintf\nfunc (tp *TextPrinter) Fprintf(writer io.Writer, format string, args ...interface{}) (n int, err error) {\n\treturn fmt.Fprintf(writer, format, args...)\n}","line":{"from":162,"to":165}} {"id":100001410,"name":"Fprintln","signature":"func (tp *TextPrinter) Fprintln(writer io.Writer, args ...interface{}) (n int, err error)","file":"cmd/kubeadm/app/util/output/output.go","code":"// Fprintln is a wrapper around fmt.Fprintln\nfunc (tp *TextPrinter) Fprintln(writer io.Writer, args ...interface{}) (n int, err error) {\n\treturn fmt.Fprintln(writer, args...)\n}","line":{"from":167,"to":170}} {"id":100001411,"name":"Printf","signature":"func (tp *TextPrinter) Printf(format string, args ...interface{}) (n int, err error)","file":"cmd/kubeadm/app/util/output/output.go","code":"// Printf is a wrapper around fmt.Printf\nfunc (tp *TextPrinter) Printf(format string, args ...interface{}) (n int, err error) {\n\treturn fmt.Printf(format, args...)\n}","line":{"from":172,"to":175}} {"id":100001412,"name":"Println","signature":"func (tp *TextPrinter) Println(args ...interface{}) (n int, err error)","file":"cmd/kubeadm/app/util/output/output.go","code":"// Println is a wrapper around fmt.Printf\nfunc (tp *TextPrinter) Println(args ...interface{}) (n int, err error) {\n\treturn fmt.Println(args...)\n}","line":{"from":177,"to":180}} {"id":100001413,"name":"Flush","signature":"func (tp *TextPrinter) Flush(writer io.Writer, last bool)","file":"cmd/kubeadm/app/util/output/output.go","code":"// Flush writes any buffered data\nfunc (tp *TextPrinter) Flush(writer io.Writer, last bool) {\n}","line":{"from":182,"to":184}} {"id":100001414,"name":"Close","signature":"func (tp *TextPrinter) Close(writer io.Writer)","file":"cmd/kubeadm/app/util/output/output.go","code":"// Close flushes any buffered data and closes the printer\nfunc (tp *TextPrinter) Close(writer io.Writer) {\n}","line":{"from":186,"to":188}} {"id":100001415,"name":"NewResourcePrinterWrapper","signature":"func NewResourcePrinterWrapper(resourcePrinter printers.ResourcePrinter, err error) (Printer, error)","file":"cmd/kubeadm/app/util/output/output.go","code":"// NewResourcePrinterWrapper creates new ResourcePrinter object\nfunc NewResourcePrinterWrapper(resourcePrinter printers.ResourcePrinter, err error) (Printer, error) {\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026ResourcePrinterWrapper{Printer: resourcePrinter}, nil\n}","line":{"from":195,"to":201}} {"id":100001416,"name":"Flush","signature":"func (rpw *ResourcePrinterWrapper) Flush(writer io.Writer, last bool)","file":"cmd/kubeadm/app/util/output/output.go","code":"// Flush writes any buffered data\nfunc (rpw *ResourcePrinterWrapper) Flush(writer io.Writer, last bool) {\n}","line":{"from":203,"to":205}} {"id":100001417,"name":"Close","signature":"func (rpw *ResourcePrinterWrapper) Close(writer io.Writer)","file":"cmd/kubeadm/app/util/output/output.go","code":"// Close flushes any buffered data and closes the printer\nfunc (rpw *ResourcePrinterWrapper) Close(writer io.Writer) {\n}","line":{"from":207,"to":209}} {"id":100001418,"name":"PrintObj","signature":"func (rpw *ResourcePrinterWrapper) PrintObj(obj runtime.Object, writer io.Writer) error","file":"cmd/kubeadm/app/util/output/output.go","code":"// PrintObj is an implementation of ResourcePrinter.PrintObj that calls underlying printer API\nfunc (rpw *ResourcePrinterWrapper) PrintObj(obj runtime.Object, writer io.Writer) error {\n\treturn rpw.Printer.PrintObj(obj, writer)\n}","line":{"from":211,"to":214}} {"id":100001419,"name":"Fprintf","signature":"func (rpw *ResourcePrinterWrapper) Fprintf(writer io.Writer, format string, args ...interface{}) (n int, err error)","file":"cmd/kubeadm/app/util/output/output.go","code":"// Fprintf is an empty method to satisfy Printer interface\n// and silent info printing for structured output\n// This method is usually redefined for the text output\nfunc (rpw *ResourcePrinterWrapper) Fprintf(writer io.Writer, format string, args ...interface{}) (n int, err error) {\n\treturn 0, nil\n}","line":{"from":216,"to":221}} {"id":100001420,"name":"Fprintln","signature":"func (rpw *ResourcePrinterWrapper) Fprintln(writer io.Writer, args ...interface{}) (n int, err error)","file":"cmd/kubeadm/app/util/output/output.go","code":"// Fprintln is an empty method to satisfy the Printer interface\n// and silent info printing for structured output\n// This method is usually redefined for the text output\nfunc (rpw *ResourcePrinterWrapper) Fprintln(writer io.Writer, args ...interface{}) (n int, err error) {\n\treturn 0, nil\n}","line":{"from":223,"to":228}} {"id":100001421,"name":"Printf","signature":"func (rpw *ResourcePrinterWrapper) Printf(format string, args ...interface{}) (n int, err error)","file":"cmd/kubeadm/app/util/output/output.go","code":"// Printf is an empty method to satisfy Printer interface\n// and silent info printing for structured output\n// This method is usually redefined for the text output\nfunc (rpw *ResourcePrinterWrapper) Printf(format string, args ...interface{}) (n int, err error) {\n\treturn 0, nil\n}","line":{"from":230,"to":235}} {"id":100001422,"name":"Println","signature":"func (rpw *ResourcePrinterWrapper) Println(args ...interface{}) (n int, err error)","file":"cmd/kubeadm/app/util/output/output.go","code":"// Println is an empty method to satisfy Printer interface\n// and silent info printing for structured output\n// This method is usually redefined for the text output\nfunc (rpw *ResourcePrinterWrapper) Println(args ...interface{}) (n int, err error) {\n\treturn 0, nil\n}","line":{"from":237,"to":242}} {"id":100001423,"name":"String","signature":"func (ps *patchSet) String() string","file":"cmd/kubeadm/app/util/patches/patches.go","code":"// String() is used for unit-testing.\nfunc (ps *patchSet) String() string {\n\treturn fmt.Sprintf(\n\t\t\"{%q, %q, %#v}\",\n\t\tps.targetName,\n\t\tps.patchType,\n\t\tps.patches,\n\t)\n}","line":{"from":68,"to":76}} {"id":100001424,"name":"KnownTargets","signature":"func KnownTargets() []string","file":"cmd/kubeadm/app/util/patches/patches.go","code":"func KnownTargets() []string {\n\treturn knownTargets\n}","line":{"from":105,"to":107}} {"id":100001425,"name":"GetPatchManagerForPath","signature":"func GetPatchManagerForPath(path string, knownTargets []string, output io.Writer) (*PatchManager, error)","file":"cmd/kubeadm/app/util/patches/patches.go","code":"// GetPatchManagerForPath creates a patch manager that can be used to apply patches to \"knownTargets\".\n// \"path\" should contain patches that can be used to patch the \"knownTargets\".\n// If \"output\" is non-nil, messages about actions performed by the manager would go on this io.Writer.\nfunc GetPatchManagerForPath(path string, knownTargets []string, output io.Writer) (*PatchManager, error) {\n\tpathLock.RLock()\n\tif pm, known := pathCache[path]; known {\n\t\tpathLock.RUnlock()\n\t\treturn pm, nil\n\t}\n\tpathLock.RUnlock()\n\n\tif output == nil {\n\t\toutput = io.Discard\n\t}\n\n\tfmt.Fprintf(output, \"[patches] Reading patches from path %q\\n\", path)\n\n\t// Get the files in the path.\n\tpatchSets, patchFiles, ignoredFiles, err := getPatchSetsFromPath(path, knownTargets, output)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(patchFiles) \u003e 0 {\n\t\tfmt.Fprintf(output, \"[patches] Found the following patch files: %v\\n\", patchFiles)\n\t}\n\tif len(ignoredFiles) \u003e 0 {\n\t\tfmt.Fprintf(output, \"[patches] Ignored the following files: %v\\n\", ignoredFiles)\n\t}\n\n\tpm := \u0026PatchManager{\n\t\tpatchSets: patchSets,\n\t\tknownTargets: knownTargets,\n\t\toutput: output,\n\t}\n\tpathLock.Lock()\n\tpathCache[path] = pm\n\tpathLock.Unlock()\n\n\treturn pm, nil\n}","line":{"from":109,"to":149}} {"id":100001426,"name":"ApplyPatchesToTarget","signature":"func (pm *PatchManager) ApplyPatchesToTarget(patchTarget *PatchTarget) error","file":"cmd/kubeadm/app/util/patches/patches.go","code":"// ApplyPatchesToTarget takes a patch target and patches its \"Data\" using the patches\n// stored in the patch manager. The resulted \"Data\" is always converted to JSON.\nfunc (pm *PatchManager) ApplyPatchesToTarget(patchTarget *PatchTarget) error {\n\tvar err error\n\tvar patchedData []byte\n\n\tvar found bool\n\tfor _, pt := range pm.knownTargets {\n\t\tif pt == patchTarget.Name {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\treturn errors.Errorf(\"unknown patch target name %q, must be one of %v\", patchTarget.Name, pm.knownTargets)\n\t}\n\n\t// Always convert the target data to JSON.\n\tpatchedData, err = yaml.YAMLToJSON(patchTarget.Data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Iterate over the patchSets.\n\tfor _, patchSet := range pm.patchSets {\n\t\tif patchSet.targetName != patchTarget.Name {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Iterate over the patches in the patchSets.\n\t\tfor _, patch := range patchSet.patches {\n\t\t\tpatchBytes := []byte(patch)\n\n\t\t\t// Patch based on the patch type.\n\t\t\tswitch patchSet.patchType {\n\n\t\t\t// JSON patch.\n\t\t\tcase types.JSONPatchType:\n\t\t\t\tvar patchObj jsonpatch.Patch\n\t\t\t\tpatchObj, err = jsonpatch.DecodePatch(patchBytes)\n\t\t\t\tif err == nil {\n\t\t\t\t\tpatchedData, err = patchObj.Apply(patchedData)\n\t\t\t\t}\n\n\t\t\t// Merge patch.\n\t\t\tcase types.MergePatchType:\n\t\t\t\tpatchedData, err = jsonpatch.MergePatch(patchedData, patchBytes)\n\n\t\t\t// Strategic merge patch.\n\t\t\tcase types.StrategicMergePatchType:\n\t\t\t\tpatchedData, err = strategicpatch.StrategicMergePatch(\n\t\t\t\t\tpatchedData,\n\t\t\t\t\tpatchBytes,\n\t\t\t\t\tpatchTarget.StrategicMergePatchObject,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"could not apply the following patch of type %q to target %q:\\n%s\\n\",\n\t\t\t\t\tpatchSet.patchType,\n\t\t\t\t\tpatchTarget.Name,\n\t\t\t\t\tpatch)\n\t\t\t}\n\t\t\tfmt.Fprintf(pm.output, \"[patches] Applied patch of type %q to target %q\\n\", patchSet.patchType, patchTarget.Name)\n\t\t}\n\n\t\t// Update the data for this patch target.\n\t\tpatchTarget.Data = patchedData\n\t}\n\n\treturn nil\n}","line":{"from":151,"to":222}} {"id":100001427,"name":"parseFilename","signature":"func parseFilename(fileName string, knownTargets []string) (string, types.PatchType, error, error)","file":"cmd/kubeadm/app/util/patches/patches.go","code":"// parseFilename validates a file name and retrieves the encoded target name and patch type.\n// - On unknown extension or target name it returns a warning\n// - On unknown patch type it returns an error\n// - On success it returns a target name and patch type\nfunc parseFilename(fileName string, knownTargets []string) (string, types.PatchType, error, error) {\n\t// Return a warning if the extension cannot be matched.\n\tif !regExtension.MatchString(fileName) {\n\t\treturn \"\", \"\", errors.Errorf(\"the file extension must be one of %v\", knownExtensions), nil\n\t}\n\n\tregFileNameSplit := regexp.MustCompile(\n\t\tfmt.Sprintf(`^(%s)([^.+\\n]*)?(\\+)?(%s)?`, strings.Join(knownTargets, \"|\"), patchTypesJoined),\n\t)\n\t// Extract the target name and patch type. The resulting sub-string slice would look like this:\n\t// [full-match, targetName, suffix, +, patchType]\n\tsub := regFileNameSplit.FindStringSubmatch(fileName)\n\tif sub == nil {\n\t\treturn \"\", \"\", errors.Errorf(\"unknown target, must be one of %v\", knownTargets), nil\n\t}\n\ttargetName := sub[1]\n\n\tif len(sub[3]) \u003e 0 \u0026\u0026 len(sub[4]) == 0 {\n\t\treturn \"\", \"\", nil, errors.Errorf(\"unknown or missing patch type after '+', must be one of %v\", patchTypeList)\n\t}\n\tpatchType := patchTypes[sub[4]]\n\n\treturn targetName, patchType, nil, nil\n}","line":{"from":224,"to":251}} {"id":100001428,"name":"createPatchSet","signature":"func createPatchSet(targetName string, patchType types.PatchType, data string) (*patchSet, error)","file":"cmd/kubeadm/app/util/patches/patches.go","code":"// createPatchSet creates a patchSet object, by splitting the given \"data\" by \"\\n---\".\nfunc createPatchSet(targetName string, patchType types.PatchType, data string) (*patchSet, error) {\n\tvar patches []string\n\n\t// Split the patches and convert them to JSON.\n\t// Data that is already JSON will not cause an error.\n\tbuf := bytes.NewBuffer([]byte(data))\n\treader := utilyaml.NewYAMLReader(bufio.NewReader(buf))\n\tfor {\n\t\tpatch, err := reader.Read()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"could not split patches for data:\\n%s\\n\", data)\n\t\t}\n\n\t\tpatch = bytes.TrimSpace(patch)\n\t\tif len(patch) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tpatchJSON, err := yaml.YAMLToJSON(patch)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"could not convert patch to JSON:\\n%s\\n\", patch)\n\t\t}\n\t\tpatches = append(patches, string(patchJSON))\n\t}\n\n\treturn \u0026patchSet{\n\t\ttargetName: targetName,\n\t\tpatchType: patchType,\n\t\tpatches: patches,\n\t}, nil\n}","line":{"from":253,"to":286}} {"id":100001429,"name":"getPatchSetsFromPath","signature":"func getPatchSetsFromPath(targetPath string, knownTargets []string, output io.Writer) ([]*patchSet, []string, []string, error)","file":"cmd/kubeadm/app/util/patches/patches.go","code":"// getPatchSetsFromPath walks a path, ignores sub-directories and non-patch files, and\n// returns a list of patchFile objects.\nfunc getPatchSetsFromPath(targetPath string, knownTargets []string, output io.Writer) ([]*patchSet, []string, []string, error) {\n\tpatchFiles := []string{}\n\tignoredFiles := []string{}\n\tpatchSets := []*patchSet{}\n\n\t// Check if targetPath is a directory.\n\tinfo, err := os.Lstat(targetPath)\n\tif err != nil {\n\t\tgoto return_path_error\n\t}\n\tif !info.IsDir() {\n\t\terr = \u0026os.PathError{\n\t\t\tOp: \"getPatchSetsFromPath\",\n\t\t\tPath: info.Name(),\n\t\t\tErr: errors.New(\"not a directory\"),\n\t\t}\n\t\tgoto return_path_error\n\t}\n\n\terr = filepath.Walk(targetPath, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Sub-directories and \".\" are ignored.\n\t\tif info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\tbaseName := info.Name()\n\n\t\t// Parse the filename and retrieve the target and patch type\n\t\ttargetName, patchType, warn, err := parseFilename(baseName, knownTargets)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif warn != nil {\n\t\t\tfmt.Fprintf(output, \"[patches] Ignoring file %q: %v\\n\", baseName, warn)\n\t\t\tignoredFiles = append(ignoredFiles, baseName)\n\t\t\treturn nil\n\t\t}\n\n\t\t// Read the patch file.\n\t\tdata, err := os.ReadFile(path)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"could not read the file %q\", path)\n\t\t}\n\n\t\tif len(data) == 0 {\n\t\t\tfmt.Fprintf(output, \"[patches] Ignoring empty file: %q\\n\", baseName)\n\t\t\tignoredFiles = append(ignoredFiles, baseName)\n\t\t\treturn nil\n\t\t}\n\n\t\t// Create a patchSet object.\n\t\tpatchSet, err := createPatchSet(targetName, patchType, string(data))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tpatchFiles = append(patchFiles, baseName)\n\t\tpatchSets = append(patchSets, patchSet)\n\t\treturn nil\n\t})\n\nreturn_path_error:\n\tif err != nil {\n\t\treturn nil, nil, nil, errors.Wrapf(err, \"could not list patch files for path %q\", targetPath)\n\t}\n\n\treturn patchSets, patchFiles, ignoredFiles, nil\n}","line":{"from":288,"to":361}} {"id":100001430,"name":"NewCertificateAuthority","signature":"func NewCertificateAuthority(config *CertConfig) (*x509.Certificate, crypto.Signer, error)","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// NewCertificateAuthority creates new certificate and private key for the certificate authority\nfunc NewCertificateAuthority(config *CertConfig) (*x509.Certificate, crypto.Signer, error) {\n\tkey, err := NewPrivateKey(config.PublicKeyAlgorithm)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"unable to create private key while generating CA certificate\")\n\t}\n\n\tcert, err := certutil.NewSelfSignedCACert(config.Config, key)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"unable to create self-signed CA certificate\")\n\t}\n\n\treturn cert, key, nil\n}","line":{"from":70,"to":83}} {"id":100001431,"name":"NewIntermediateCertificateAuthority","signature":"func NewIntermediateCertificateAuthority(parentCert *x509.Certificate, parentKey crypto.Signer, config *CertConfig) (*x509.Certificate, crypto.Signer, error)","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// NewIntermediateCertificateAuthority creates new certificate and private key for an intermediate certificate authority\nfunc NewIntermediateCertificateAuthority(parentCert *x509.Certificate, parentKey crypto.Signer, config *CertConfig) (*x509.Certificate, crypto.Signer, error) {\n\tkey, err := NewPrivateKey(config.PublicKeyAlgorithm)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"unable to create private key while generating intermediate CA certificate\")\n\t}\n\n\tcert, err := NewSignedCert(config, key, parentCert, parentKey, true)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"unable to sign intermediate CA certificate\")\n\t}\n\n\treturn cert, key, nil\n}","line":{"from":85,"to":98}} {"id":100001432,"name":"NewCertAndKey","signature":"func NewCertAndKey(caCert *x509.Certificate, caKey crypto.Signer, config *CertConfig) (*x509.Certificate, crypto.Signer, error)","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// NewCertAndKey creates new certificate and key by passing the certificate authority certificate and key\nfunc NewCertAndKey(caCert *x509.Certificate, caKey crypto.Signer, config *CertConfig) (*x509.Certificate, crypto.Signer, error) {\n\tif len(config.Usages) == 0 {\n\t\treturn nil, nil, errors.New(\"must specify at least one ExtKeyUsage\")\n\t}\n\n\tkey, err := NewPrivateKey(config.PublicKeyAlgorithm)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"unable to create private key\")\n\t}\n\n\tcert, err := NewSignedCert(config, key, caCert, caKey, false)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"unable to sign certificate\")\n\t}\n\n\treturn cert, key, nil\n}","line":{"from":100,"to":117}} {"id":100001433,"name":"NewCSRAndKey","signature":"func NewCSRAndKey(config *CertConfig) (*x509.CertificateRequest, crypto.Signer, error)","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// NewCSRAndKey generates a new key and CSR and that could be signed to create the given certificate\nfunc NewCSRAndKey(config *CertConfig) (*x509.CertificateRequest, crypto.Signer, error) {\n\tkey, err := NewPrivateKey(config.PublicKeyAlgorithm)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"unable to create private key\")\n\t}\n\n\tcsr, err := NewCSR(*config, key)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"unable to generate CSR\")\n\t}\n\n\treturn csr, key, nil\n}","line":{"from":119,"to":132}} {"id":100001434,"name":"HasServerAuth","signature":"func HasServerAuth(cert *x509.Certificate) bool","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// HasServerAuth returns true if the given certificate is a ServerAuth\nfunc HasServerAuth(cert *x509.Certificate) bool {\n\tfor i := range cert.ExtKeyUsage {\n\t\tif cert.ExtKeyUsage[i] == x509.ExtKeyUsageServerAuth {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":134,"to":142}} {"id":100001435,"name":"WriteCertAndKey","signature":"func WriteCertAndKey(pkiPath string, name string, cert *x509.Certificate, key crypto.Signer) error","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// WriteCertAndKey stores certificate and key at the specified location\nfunc WriteCertAndKey(pkiPath string, name string, cert *x509.Certificate, key crypto.Signer) error {\n\tif err := WriteKey(pkiPath, name, key); err != nil {\n\t\treturn errors.Wrap(err, \"couldn't write key\")\n\t}\n\n\treturn WriteCert(pkiPath, name, cert)\n}","line":{"from":144,"to":151}} {"id":100001436,"name":"WriteCert","signature":"func WriteCert(pkiPath, name string, cert *x509.Certificate) error","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// WriteCert stores the given certificate at the given location\nfunc WriteCert(pkiPath, name string, cert *x509.Certificate) error {\n\tif cert == nil {\n\t\treturn errors.New(\"certificate cannot be nil when writing to file\")\n\t}\n\n\tcertificatePath := pathForCert(pkiPath, name)\n\tif err := certutil.WriteCert(certificatePath, EncodeCertPEM(cert)); err != nil {\n\t\treturn errors.Wrapf(err, \"unable to write certificate to file %s\", certificatePath)\n\t}\n\n\treturn nil\n}","line":{"from":153,"to":165}} {"id":100001437,"name":"WriteCertBundle","signature":"func WriteCertBundle(pkiPath, name string, certs []*x509.Certificate) error","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// WriteCertBundle stores the given certificate bundle at the given location\nfunc WriteCertBundle(pkiPath, name string, certs []*x509.Certificate) error {\n\tfor i, cert := range certs {\n\t\tif cert == nil {\n\t\t\treturn errors.Errorf(\"found nil certificate at position %d when writing bundle to file\", i)\n\t\t}\n\t}\n\n\tcertificatePath := pathForCert(pkiPath, name)\n\tencoded, err := EncodeCertBundlePEM(certs)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"unable to marshal certificate bundle to PEM\")\n\t}\n\tif err := certutil.WriteCert(certificatePath, encoded); err != nil {\n\t\treturn errors.Wrapf(err, \"unable to write certificate bundle to file %s\", certificatePath)\n\t}\n\n\treturn nil\n}","line":{"from":167,"to":185}} {"id":100001438,"name":"WriteKey","signature":"func WriteKey(pkiPath, name string, key crypto.Signer) error","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// WriteKey stores the given key at the given location\nfunc WriteKey(pkiPath, name string, key crypto.Signer) error {\n\tif key == nil {\n\t\treturn errors.New(\"private key cannot be nil when writing to file\")\n\t}\n\n\tprivateKeyPath := pathForKey(pkiPath, name)\n\tencoded, err := keyutil.MarshalPrivateKeyToPEM(key)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"unable to marshal private key to PEM\")\n\t}\n\tif err := keyutil.WriteKey(privateKeyPath, encoded); err != nil {\n\t\treturn errors.Wrapf(err, \"unable to write private key to file %s\", privateKeyPath)\n\t}\n\n\treturn nil\n}","line":{"from":187,"to":203}} {"id":100001439,"name":"WriteCSR","signature":"func WriteCSR(csrDir, name string, csr *x509.CertificateRequest) error","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// WriteCSR writes the pem-encoded CSR data to csrPath.\n// The CSR file will be created with file mode 0600.\n// If the CSR file already exists, it will be overwritten.\n// The parent directory of the csrPath will be created as needed with file mode 0700.\nfunc WriteCSR(csrDir, name string, csr *x509.CertificateRequest) error {\n\tif csr == nil {\n\t\treturn errors.New(\"certificate request cannot be nil when writing to file\")\n\t}\n\n\tcsrPath := pathForCSR(csrDir, name)\n\tif err := os.MkdirAll(filepath.Dir(csrPath), os.FileMode(0700)); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to make directory %s\", filepath.Dir(csrPath))\n\t}\n\n\tif err := os.WriteFile(csrPath, EncodeCSRPEM(csr), os.FileMode(0600)); err != nil {\n\t\treturn errors.Wrapf(err, \"unable to write CSR to file %s\", csrPath)\n\t}\n\n\treturn nil\n}","line":{"from":205,"to":224}} {"id":100001440,"name":"WritePublicKey","signature":"func WritePublicKey(pkiPath, name string, key crypto.PublicKey) error","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// WritePublicKey stores the given public key at the given location\nfunc WritePublicKey(pkiPath, name string, key crypto.PublicKey) error {\n\tif key == nil {\n\t\treturn errors.New(\"public key cannot be nil when writing to file\")\n\t}\n\n\tpublicKeyBytes, err := EncodePublicKeyPEM(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpublicKeyPath := pathForPublicKey(pkiPath, name)\n\tif err := keyutil.WriteKey(publicKeyPath, publicKeyBytes); err != nil {\n\t\treturn errors.Wrapf(err, \"unable to write public key to file %s\", publicKeyPath)\n\t}\n\n\treturn nil\n}","line":{"from":226,"to":242}} {"id":100001441,"name":"CertOrKeyExist","signature":"func CertOrKeyExist(pkiPath, name string) bool","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// CertOrKeyExist returns a boolean whether the cert or the key exists\nfunc CertOrKeyExist(pkiPath, name string) bool {\n\tcertificatePath, privateKeyPath := PathsForCertAndKey(pkiPath, name)\n\n\t_, certErr := os.Stat(certificatePath)\n\t_, keyErr := os.Stat(privateKeyPath)\n\n\treturn !(os.IsNotExist(certErr) \u0026\u0026 os.IsNotExist(keyErr))\n}","line":{"from":244,"to":252}} {"id":100001442,"name":"CSROrKeyExist","signature":"func CSROrKeyExist(csrDir, name string) bool","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// CSROrKeyExist returns true if one of the CSR or key exists\nfunc CSROrKeyExist(csrDir, name string) bool {\n\tcsrPath := pathForCSR(csrDir, name)\n\tkeyPath := pathForKey(csrDir, name)\n\n\t_, csrErr := os.Stat(csrPath)\n\t_, keyErr := os.Stat(keyPath)\n\n\treturn !(os.IsNotExist(csrErr) \u0026\u0026 os.IsNotExist(keyErr))\n}","line":{"from":254,"to":263}} {"id":100001443,"name":"TryLoadCertAndKeyFromDisk","signature":"func TryLoadCertAndKeyFromDisk(pkiPath, name string) (*x509.Certificate, crypto.Signer, error)","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// TryLoadCertAndKeyFromDisk tries to load a cert and a key from the disk and validates that they are valid\nfunc TryLoadCertAndKeyFromDisk(pkiPath, name string) (*x509.Certificate, crypto.Signer, error) {\n\tcert, err := TryLoadCertFromDisk(pkiPath, name)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"failed to load certificate\")\n\t}\n\n\tkey, err := TryLoadKeyFromDisk(pkiPath, name)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"failed to load key\")\n\t}\n\n\treturn cert, key, nil\n}","line":{"from":265,"to":278}} {"id":100001444,"name":"TryLoadCertFromDisk","signature":"func TryLoadCertFromDisk(pkiPath, name string) (*x509.Certificate, error)","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// TryLoadCertFromDisk tries to load the cert from the disk\nfunc TryLoadCertFromDisk(pkiPath, name string) (*x509.Certificate, error) {\n\tcertificatePath := pathForCert(pkiPath, name)\n\n\tcerts, err := certutil.CertsFromFile(certificatePath)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"couldn't load the certificate file %s\", certificatePath)\n\t}\n\n\t// Safely pick the first one because the sender's certificate must come first in the list.\n\t// For details, see: https://www.rfc-editor.org/rfc/rfc4346#section-7.4.2\n\tcert := certs[0]\n\n\treturn cert, nil\n}","line":{"from":280,"to":294}} {"id":100001445,"name":"TryLoadCertChainFromDisk","signature":"func TryLoadCertChainFromDisk(pkiPath, name string) (*x509.Certificate, []*x509.Certificate, error)","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// TryLoadCertChainFromDisk tries to load the cert chain from the disk\nfunc TryLoadCertChainFromDisk(pkiPath, name string) (*x509.Certificate, []*x509.Certificate, error) {\n\tcertificatePath := pathForCert(pkiPath, name)\n\n\tcerts, err := certutil.CertsFromFile(certificatePath)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrapf(err, \"couldn't load the certificate file %s\", certificatePath)\n\t}\n\n\tcert := certs[0]\n\tintermediates := certs[1:]\n\n\treturn cert, intermediates, nil\n}","line":{"from":296,"to":309}} {"id":100001446,"name":"TryLoadKeyFromDisk","signature":"func TryLoadKeyFromDisk(pkiPath, name string) (crypto.Signer, error)","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// TryLoadKeyFromDisk tries to load the key from the disk and validates that it is valid\nfunc TryLoadKeyFromDisk(pkiPath, name string) (crypto.Signer, error) {\n\tprivateKeyPath := pathForKey(pkiPath, name)\n\n\t// Parse the private key from a file\n\tprivKey, err := keyutil.PrivateKeyFromFile(privateKeyPath)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"couldn't load the private key file %s\", privateKeyPath)\n\t}\n\n\t// Allow RSA and ECDSA formats only\n\tvar key crypto.Signer\n\tswitch k := privKey.(type) {\n\tcase *rsa.PrivateKey:\n\t\tkey = k\n\tcase *ecdsa.PrivateKey:\n\t\tkey = k\n\tdefault:\n\t\treturn nil, errors.Errorf(\"the private key file %s is neither in RSA nor ECDSA format\", privateKeyPath)\n\t}\n\n\treturn key, nil\n}","line":{"from":311,"to":333}} {"id":100001447,"name":"TryLoadCSRAndKeyFromDisk","signature":"func TryLoadCSRAndKeyFromDisk(pkiPath, name string) (*x509.CertificateRequest, crypto.Signer, error)","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// TryLoadCSRAndKeyFromDisk tries to load the CSR and key from the disk\nfunc TryLoadCSRAndKeyFromDisk(pkiPath, name string) (*x509.CertificateRequest, crypto.Signer, error) {\n\tcsr, err := TryLoadCSRFromDisk(pkiPath, name)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"could not load CSR file\")\n\t}\n\n\tkey, err := TryLoadKeyFromDisk(pkiPath, name)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"could not load key file\")\n\t}\n\n\treturn csr, key, nil\n}","line":{"from":335,"to":348}} {"id":100001448,"name":"TryLoadPrivatePublicKeyFromDisk","signature":"func TryLoadPrivatePublicKeyFromDisk(pkiPath, name string) (crypto.PrivateKey, crypto.PublicKey, error)","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// TryLoadPrivatePublicKeyFromDisk tries to load the key from the disk and validates that it is valid\nfunc TryLoadPrivatePublicKeyFromDisk(pkiPath, name string) (crypto.PrivateKey, crypto.PublicKey, error) {\n\tprivateKeyPath := pathForKey(pkiPath, name)\n\n\t// Parse the private key from a file\n\tprivKey, err := keyutil.PrivateKeyFromFile(privateKeyPath)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrapf(err, \"couldn't load the private key file %s\", privateKeyPath)\n\t}\n\n\tpublicKeyPath := pathForPublicKey(pkiPath, name)\n\n\t// Parse the public key from a file\n\tpubKeys, err := keyutil.PublicKeysFromFile(publicKeyPath)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrapf(err, \"couldn't load the public key file %s\", publicKeyPath)\n\t}\n\n\t// Allow RSA and ECDSA formats only\n\tswitch k := privKey.(type) {\n\tcase *rsa.PrivateKey:\n\t\treturn k, pubKeys[0].(*rsa.PublicKey), nil\n\tcase *ecdsa.PrivateKey:\n\t\treturn k, pubKeys[0].(*ecdsa.PublicKey), nil\n\tdefault:\n\t\treturn nil, nil, errors.Errorf(\"the private key file %s is neither in RSA nor ECDSA format\", privateKeyPath)\n\t}\n}","line":{"from":350,"to":377}} {"id":100001449,"name":"TryLoadCSRFromDisk","signature":"func TryLoadCSRFromDisk(pkiPath, name string) (*x509.CertificateRequest, error)","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// TryLoadCSRFromDisk tries to load the CSR from the disk\nfunc TryLoadCSRFromDisk(pkiPath, name string) (*x509.CertificateRequest, error) {\n\tcsrPath := pathForCSR(pkiPath, name)\n\n\tcsr, err := CertificateRequestFromFile(csrPath)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"could not load the CSR %s\", csrPath)\n\t}\n\n\treturn csr, nil\n}","line":{"from":379,"to":389}} {"id":100001450,"name":"PathsForCertAndKey","signature":"func PathsForCertAndKey(pkiPath, name string) (string, string)","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// PathsForCertAndKey returns the paths for the certificate and key given the path and basename.\nfunc PathsForCertAndKey(pkiPath, name string) (string, string) {\n\treturn pathForCert(pkiPath, name), pathForKey(pkiPath, name)\n}","line":{"from":391,"to":394}} {"id":100001451,"name":"pathForCert","signature":"func pathForCert(pkiPath, name string) string","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"func pathForCert(pkiPath, name string) string {\n\treturn filepath.Join(pkiPath, fmt.Sprintf(\"%s.crt\", name))\n}","line":{"from":396,"to":398}} {"id":100001452,"name":"pathForKey","signature":"func pathForKey(pkiPath, name string) string","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"func pathForKey(pkiPath, name string) string {\n\treturn filepath.Join(pkiPath, fmt.Sprintf(\"%s.key\", name))\n}","line":{"from":400,"to":402}} {"id":100001453,"name":"pathForPublicKey","signature":"func pathForPublicKey(pkiPath, name string) string","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"func pathForPublicKey(pkiPath, name string) string {\n\treturn filepath.Join(pkiPath, fmt.Sprintf(\"%s.pub\", name))\n}","line":{"from":404,"to":406}} {"id":100001454,"name":"pathForCSR","signature":"func pathForCSR(pkiPath, name string) string","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"func pathForCSR(pkiPath, name string) string {\n\treturn filepath.Join(pkiPath, fmt.Sprintf(\"%s.csr\", name))\n}","line":{"from":408,"to":410}} {"id":100001455,"name":"GetAPIServerAltNames","signature":"func GetAPIServerAltNames(cfg *kubeadmapi.InitConfiguration) (*certutil.AltNames, error)","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// GetAPIServerAltNames builds an AltNames object for to be used when generating apiserver certificate\nfunc GetAPIServerAltNames(cfg *kubeadmapi.InitConfiguration) (*certutil.AltNames, error) {\n\t// advertise address\n\tadvertiseAddress := netutils.ParseIPSloppy(cfg.LocalAPIEndpoint.AdvertiseAddress)\n\tif advertiseAddress == nil {\n\t\treturn nil, errors.Errorf(\"error parsing LocalAPIEndpoint AdvertiseAddress %v: is not a valid textual representation of an IP address\",\n\t\t\tcfg.LocalAPIEndpoint.AdvertiseAddress)\n\t}\n\n\tinternalAPIServerVirtualIP, err := kubeadmconstants.GetAPIServerVirtualIP(cfg.Networking.ServiceSubnet)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get first IP address from the given CIDR: %v\", cfg.Networking.ServiceSubnet)\n\t}\n\n\t// create AltNames with defaults DNSNames/IPs\n\taltNames := \u0026certutil.AltNames{\n\t\tDNSNames: []string{\n\t\t\tcfg.NodeRegistration.Name,\n\t\t\t\"kubernetes\",\n\t\t\t\"kubernetes.default\",\n\t\t\t\"kubernetes.default.svc\",\n\t\t\tfmt.Sprintf(\"kubernetes.default.svc.%s\", cfg.Networking.DNSDomain),\n\t\t},\n\t\tIPs: []net.IP{\n\t\t\tinternalAPIServerVirtualIP,\n\t\t\tadvertiseAddress,\n\t\t},\n\t}\n\n\t// add cluster controlPlaneEndpoint if present (dns or ip)\n\tif len(cfg.ControlPlaneEndpoint) \u003e 0 {\n\t\tif host, _, err := kubeadmutil.ParseHostPort(cfg.ControlPlaneEndpoint); err == nil {\n\t\t\tif ip := netutils.ParseIPSloppy(host); ip != nil {\n\t\t\t\taltNames.IPs = append(altNames.IPs, ip)\n\t\t\t} else {\n\t\t\t\taltNames.DNSNames = append(altNames.DNSNames, host)\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, errors.Wrapf(err, \"error parsing cluster controlPlaneEndpoint %q\", cfg.ControlPlaneEndpoint)\n\t\t}\n\t}\n\n\tappendSANsToAltNames(altNames, cfg.APIServer.CertSANs, kubeadmconstants.APIServerCertName)\n\n\treturn altNames, nil\n}","line":{"from":412,"to":457}} {"id":100001456,"name":"GetEtcdAltNames","signature":"func GetEtcdAltNames(cfg *kubeadmapi.InitConfiguration) (*certutil.AltNames, error)","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// GetEtcdAltNames builds an AltNames object for generating the etcd server certificate.\n// `advertise address` and localhost are included in the SAN since this is the interfaces the etcd static pod listens on.\n// The user can override the listen address with `Etcd.ExtraArgs` and add SANs with `Etcd.ServerCertSANs`.\nfunc GetEtcdAltNames(cfg *kubeadmapi.InitConfiguration) (*certutil.AltNames, error) {\n\treturn getAltNames(cfg, kubeadmconstants.EtcdServerCertName)\n}","line":{"from":459,"to":464}} {"id":100001457,"name":"GetEtcdPeerAltNames","signature":"func GetEtcdPeerAltNames(cfg *kubeadmapi.InitConfiguration) (*certutil.AltNames, error)","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// GetEtcdPeerAltNames builds an AltNames object for generating the etcd peer certificate.\n// Hostname and `API.AdvertiseAddress` are included if the user chooses to promote the single node etcd cluster into a multi-node one (stacked etcd).\n// The user can override the listen address with `Etcd.ExtraArgs` and add SANs with `Etcd.PeerCertSANs`.\nfunc GetEtcdPeerAltNames(cfg *kubeadmapi.InitConfiguration) (*certutil.AltNames, error) {\n\treturn getAltNames(cfg, kubeadmconstants.EtcdPeerCertName)\n}","line":{"from":466,"to":471}} {"id":100001458,"name":"getAltNames","signature":"func getAltNames(cfg *kubeadmapi.InitConfiguration, certName string) (*certutil.AltNames, error)","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// getAltNames builds an AltNames object with the cfg and certName.\nfunc getAltNames(cfg *kubeadmapi.InitConfiguration, certName string) (*certutil.AltNames, error) {\n\t// advertise address\n\tadvertiseAddress := netutils.ParseIPSloppy(cfg.LocalAPIEndpoint.AdvertiseAddress)\n\tif advertiseAddress == nil {\n\t\treturn nil, errors.Errorf(\"error parsing LocalAPIEndpoint AdvertiseAddress %v: is not a valid textual representation of an IP address\",\n\t\t\tcfg.LocalAPIEndpoint.AdvertiseAddress)\n\t}\n\n\t// create AltNames with defaults DNSNames/IPs\n\taltNames := \u0026certutil.AltNames{\n\t\tDNSNames: []string{cfg.NodeRegistration.Name, \"localhost\"},\n\t\tIPs: []net.IP{advertiseAddress, net.IPv4(127, 0, 0, 1), net.IPv6loopback},\n\t}\n\n\tif cfg.Etcd.Local != nil {\n\t\tif certName == kubeadmconstants.EtcdServerCertName {\n\t\t\tappendSANsToAltNames(altNames, cfg.Etcd.Local.ServerCertSANs, kubeadmconstants.EtcdServerCertName)\n\t\t} else if certName == kubeadmconstants.EtcdPeerCertName {\n\t\t\tappendSANsToAltNames(altNames, cfg.Etcd.Local.PeerCertSANs, kubeadmconstants.EtcdPeerCertName)\n\t\t}\n\t}\n\treturn altNames, nil\n}","line":{"from":473,"to":496}} {"id":100001459,"name":"appendSANsToAltNames","signature":"func appendSANsToAltNames(altNames *certutil.AltNames, SANs []string, certName string)","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// appendSANsToAltNames parses SANs from as list of strings and adds them to altNames for use on a specific cert\n// altNames is passed in with a pointer, and the struct is modified\n// valid IP address strings are parsed and added to altNames.IPs as net.IP's\n// RFC-1123 compliant DNS strings are added to altNames.DNSNames as strings\n// RFC-1123 compliant wildcard DNS strings are added to altNames.DNSNames as strings\n// certNames is used to print user facing warnings and should be the name of the cert the altNames will be used for\nfunc appendSANsToAltNames(altNames *certutil.AltNames, SANs []string, certName string) {\n\tfor _, altname := range SANs {\n\t\tif ip := netutils.ParseIPSloppy(altname); ip != nil {\n\t\t\taltNames.IPs = append(altNames.IPs, ip)\n\t\t} else if len(validation.IsDNS1123Subdomain(altname)) == 0 {\n\t\t\taltNames.DNSNames = append(altNames.DNSNames, altname)\n\t\t} else if len(validation.IsWildcardDNS1123Subdomain(altname)) == 0 {\n\t\t\taltNames.DNSNames = append(altNames.DNSNames, altname)\n\t\t} else {\n\t\t\tklog.Warningf(\n\t\t\t\t\"[certificates] WARNING: '%s' was not added to the '%s' SAN, because it is not a valid IP or RFC-1123 compliant DNS entry\\n\",\n\t\t\t\taltname,\n\t\t\t\tcertName,\n\t\t\t)\n\t\t}\n\t}\n}","line":{"from":498,"to":520}} {"id":100001460,"name":"EncodeCSRPEM","signature":"func EncodeCSRPEM(csr *x509.CertificateRequest) []byte","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// EncodeCSRPEM returns PEM-encoded CSR data\nfunc EncodeCSRPEM(csr *x509.CertificateRequest) []byte {\n\tblock := pem.Block{\n\t\tType: certutil.CertificateRequestBlockType,\n\t\tBytes: csr.Raw,\n\t}\n\treturn pem.EncodeToMemory(\u0026block)\n}","line":{"from":522,"to":529}} {"id":100001461,"name":"parseCSRPEM","signature":"func parseCSRPEM(pemCSR []byte) (*x509.CertificateRequest, error)","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"func parseCSRPEM(pemCSR []byte) (*x509.CertificateRequest, error) {\n\tblock, _ := pem.Decode(pemCSR)\n\tif block == nil {\n\t\treturn nil, errors.New(\"data doesn't contain a valid certificate request\")\n\t}\n\n\tif block.Type != certutil.CertificateRequestBlockType {\n\t\treturn nil, errors.Errorf(\"expected block type %q, but PEM had type %q\", certutil.CertificateRequestBlockType, block.Type)\n\t}\n\n\treturn x509.ParseCertificateRequest(block.Bytes)\n}","line":{"from":531,"to":542}} {"id":100001462,"name":"CertificateRequestFromFile","signature":"func CertificateRequestFromFile(file string) (*x509.CertificateRequest, error)","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// CertificateRequestFromFile returns the CertificateRequest from a given PEM-encoded file.\n// Returns an error if the file could not be read or if the CSR could not be parsed.\nfunc CertificateRequestFromFile(file string) (*x509.CertificateRequest, error) {\n\tpemBlock, err := os.ReadFile(file)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to read file\")\n\t}\n\n\tcsr, err := parseCSRPEM(pemBlock)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"error reading certificate request file %s\", file)\n\t}\n\treturn csr, nil\n}","line":{"from":544,"to":557}} {"id":100001463,"name":"NewCSR","signature":"func NewCSR(cfg CertConfig, key crypto.Signer) (*x509.CertificateRequest, error)","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// NewCSR creates a new CSR\nfunc NewCSR(cfg CertConfig, key crypto.Signer) (*x509.CertificateRequest, error) {\n\tRemoveDuplicateAltNames(\u0026cfg.AltNames)\n\n\ttemplate := \u0026x509.CertificateRequest{\n\t\tSubject: pkix.Name{\n\t\t\tCommonName: cfg.CommonName,\n\t\t\tOrganization: cfg.Organization,\n\t\t},\n\t\tDNSNames: cfg.AltNames.DNSNames,\n\t\tIPAddresses: cfg.AltNames.IPs,\n\t}\n\n\tcsrBytes, err := x509.CreateCertificateRequest(cryptorand.Reader, template, key)\n\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create a CSR\")\n\t}\n\n\treturn x509.ParseCertificateRequest(csrBytes)\n}","line":{"from":559,"to":579}} {"id":100001464,"name":"EncodeCertPEM","signature":"func EncodeCertPEM(cert *x509.Certificate) []byte","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// EncodeCertPEM returns PEM-endcoded certificate data\nfunc EncodeCertPEM(cert *x509.Certificate) []byte {\n\tblock := pem.Block{\n\t\tType: CertificateBlockType,\n\t\tBytes: cert.Raw,\n\t}\n\treturn pem.EncodeToMemory(\u0026block)\n}","line":{"from":581,"to":588}} {"id":100001465,"name":"EncodeCertBundlePEM","signature":"func EncodeCertBundlePEM(certs []*x509.Certificate) ([]byte, error)","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// EncodeCertBundlePEM returns PEM-endcoded certificate bundle\nfunc EncodeCertBundlePEM(certs []*x509.Certificate) ([]byte, error) {\n\tbuf := bytes.Buffer{}\n\n\tblock := pem.Block{\n\t\tType: CertificateBlockType,\n\t}\n\n\tfor _, cert := range certs {\n\t\tblock.Bytes = cert.Raw\n\t\tif err := pem.Encode(\u0026buf, \u0026block); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn buf.Bytes(), nil\n}","line":{"from":590,"to":606}} {"id":100001466,"name":"EncodePublicKeyPEM","signature":"func EncodePublicKeyPEM(key crypto.PublicKey) ([]byte, error)","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// EncodePublicKeyPEM returns PEM-encoded public data\nfunc EncodePublicKeyPEM(key crypto.PublicKey) ([]byte, error) {\n\tder, err := x509.MarshalPKIXPublicKey(key)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tblock := pem.Block{\n\t\tType: PublicKeyBlockType,\n\t\tBytes: der,\n\t}\n\treturn pem.EncodeToMemory(\u0026block), nil\n}","line":{"from":608,"to":619}} {"id":100001467,"name":"GeneratePrivateKey","signature":"func GeneratePrivateKey(keyType x509.PublicKeyAlgorithm) (crypto.Signer, error)","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"func GeneratePrivateKey(keyType x509.PublicKeyAlgorithm) (crypto.Signer, error) {\n\tif keyType == x509.ECDSA {\n\t\treturn ecdsa.GenerateKey(elliptic.P256(), cryptorand.Reader)\n\t}\n\n\treturn rsa.GenerateKey(cryptorand.Reader, rsaKeySize)\n}","line":{"from":624,"to":630}} {"id":100001468,"name":"NewSignedCert","signature":"func NewSignedCert(cfg *CertConfig, key crypto.Signer, caCert *x509.Certificate, caKey crypto.Signer, isCA bool) (*x509.Certificate, error)","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// NewSignedCert creates a signed certificate using the given CA certificate and key\nfunc NewSignedCert(cfg *CertConfig, key crypto.Signer, caCert *x509.Certificate, caKey crypto.Signer, isCA bool) (*x509.Certificate, error) {\n\t// returns a uniform random value in [0, max-1), then add 1 to serial to make it a uniform random value in [1, max).\n\tserial, err := cryptorand.Int(cryptorand.Reader, new(big.Int).SetInt64(math.MaxInt64-1))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tserial = new(big.Int).Add(serial, big.NewInt(1))\n\tif len(cfg.CommonName) == 0 {\n\t\treturn nil, errors.New(\"must specify a CommonName\")\n\t}\n\n\tkeyUsage := x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature\n\tif isCA {\n\t\tkeyUsage |= x509.KeyUsageCertSign\n\t}\n\n\tRemoveDuplicateAltNames(\u0026cfg.AltNames)\n\n\tnotAfter := time.Now().Add(kubeadmconstants.CertificateValidity).UTC()\n\tif cfg.NotAfter != nil {\n\t\tnotAfter = *cfg.NotAfter\n\t}\n\n\tcertTmpl := x509.Certificate{\n\t\tSubject: pkix.Name{\n\t\t\tCommonName: cfg.CommonName,\n\t\t\tOrganization: cfg.Organization,\n\t\t},\n\t\tDNSNames: cfg.AltNames.DNSNames,\n\t\tIPAddresses: cfg.AltNames.IPs,\n\t\tSerialNumber: serial,\n\t\tNotBefore: caCert.NotBefore,\n\t\tNotAfter: notAfter,\n\t\tKeyUsage: keyUsage,\n\t\tExtKeyUsage: cfg.Usages,\n\t\tBasicConstraintsValid: true,\n\t\tIsCA: isCA,\n\t}\n\tcertDERBytes, err := x509.CreateCertificate(cryptorand.Reader, \u0026certTmpl, caCert, key.Public(), caKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn x509.ParseCertificate(certDERBytes)\n}","line":{"from":632,"to":676}} {"id":100001469,"name":"RemoveDuplicateAltNames","signature":"func RemoveDuplicateAltNames(altNames *certutil.AltNames)","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// RemoveDuplicateAltNames removes duplicate items in altNames.\nfunc RemoveDuplicateAltNames(altNames *certutil.AltNames) {\n\tif altNames == nil {\n\t\treturn\n\t}\n\n\tif altNames.DNSNames != nil {\n\t\taltNames.DNSNames = sets.List(sets.New(altNames.DNSNames...))\n\t}\n\n\tipsKeys := make(map[string]struct{})\n\tvar ips []net.IP\n\tfor _, one := range altNames.IPs {\n\t\tif _, ok := ipsKeys[one.String()]; !ok {\n\t\t\tipsKeys[one.String()] = struct{}{}\n\t\t\tips = append(ips, one)\n\t\t}\n\t}\n\taltNames.IPs = ips\n}","line":{"from":678,"to":697}} {"id":100001470,"name":"ValidateCertPeriod","signature":"func ValidateCertPeriod(cert *x509.Certificate, offset time.Duration) error","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// ValidateCertPeriod checks if the certificate is valid relative to the current time\n// (+/- offset)\nfunc ValidateCertPeriod(cert *x509.Certificate, offset time.Duration) error {\n\tperiod := fmt.Sprintf(\"NotBefore: %v, NotAfter: %v\", cert.NotBefore, cert.NotAfter)\n\tnow := time.Now().Add(offset)\n\tif now.Before(cert.NotBefore) {\n\t\treturn errors.Errorf(\"the certificate is not valid yet: %s\", period)\n\t}\n\tif now.After(cert.NotAfter) {\n\t\treturn errors.Errorf(\"the certificate has expired: %s\", period)\n\t}\n\treturn nil\n}","line":{"from":699,"to":711}} {"id":100001471,"name":"VerifyCertChain","signature":"func VerifyCertChain(cert *x509.Certificate, intermediates []*x509.Certificate, root *x509.Certificate) error","file":"cmd/kubeadm/app/util/pkiutil/pki_helpers.go","code":"// VerifyCertChain verifies that a certificate has a valid chain of\n// intermediate CAs back to the root CA\nfunc VerifyCertChain(cert *x509.Certificate, intermediates []*x509.Certificate, root *x509.Certificate) error {\n\trootPool := x509.NewCertPool()\n\trootPool.AddCert(root)\n\n\tintermediatePool := x509.NewCertPool()\n\tfor _, c := range intermediates {\n\t\tintermediatePool.AddCert(c)\n\t}\n\n\tverifyOptions := x509.VerifyOptions{\n\t\tRoots: rootPool,\n\t\tIntermediates: intermediatePool,\n\t\tKeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},\n\t}\n\n\tif _, err := cert.Verify(verifyOptions); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":713,"to":735}} {"id":100001472,"name":"NewSet","signature":"func NewSet() *Set","file":"cmd/kubeadm/app/util/pubkeypin/pubkeypin.go","code":"// NewSet returns a new, empty PubKeyPinSet\nfunc NewSet() *Set {\n\treturn \u0026Set{make(map[string]bool)}\n}","line":{"from":45,"to":48}} {"id":100001473,"name":"Allow","signature":"func (s *Set) Allow(pubKeyHashes ...string) error","file":"cmd/kubeadm/app/util/pubkeypin/pubkeypin.go","code":"// Allow adds an allowed public key hash to the Set\nfunc (s *Set) Allow(pubKeyHashes ...string) error {\n\tfor _, pubKeyHash := range pubKeyHashes {\n\t\tparts := strings.Split(pubKeyHash, \":\")\n\t\tif len(parts) != 2 {\n\t\t\treturn errors.Errorf(\"invalid hash, expected \\\"format:hex-value\\\". \"+\n\t\t\t\t\"Known format(s) are: %s\", supportedFormats)\n\t\t}\n\t\tformat, value := parts[0], parts[1]\n\n\t\tswitch strings.ToLower(format) {\n\t\tcase \"sha256\":\n\t\t\tif err := s.allowSHA256(value); err != nil {\n\t\t\t\treturn errors.Errorf(\"invalid hash %q, %v\", pubKeyHash, err)\n\t\t\t}\n\t\tdefault:\n\t\t\treturn errors.Errorf(\"unknown hash format %q. Known format(s) are: %s\", format, supportedFormats)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":50,"to":70}} {"id":100001474,"name":"CheckAny","signature":"func (s *Set) CheckAny(certificates []*x509.Certificate) error","file":"cmd/kubeadm/app/util/pubkeypin/pubkeypin.go","code":"// CheckAny checks if at least one certificate matches one of the public keys in the set\nfunc (s *Set) CheckAny(certificates []*x509.Certificate) error {\n\tvar hashes []string\n\n\tfor _, certificate := range certificates {\n\t\tif s.checkSHA256(certificate) {\n\t\t\treturn nil\n\t\t}\n\n\t\thashes = append(hashes, Hash(certificate))\n\t}\n\treturn errors.Errorf(\"none of the public keys %q are pinned\", strings.Join(hashes, \":\"))\n}","line":{"from":72,"to":84}} {"id":100001475,"name":"Empty","signature":"func (s *Set) Empty() bool","file":"cmd/kubeadm/app/util/pubkeypin/pubkeypin.go","code":"// Empty returns true if the Set contains no pinned public keys.\nfunc (s *Set) Empty() bool {\n\treturn len(s.sha256Hashes) == 0\n}","line":{"from":86,"to":89}} {"id":100001476,"name":"Hash","signature":"func Hash(certificate *x509.Certificate) string","file":"cmd/kubeadm/app/util/pubkeypin/pubkeypin.go","code":"// Hash calculates the SHA-256 hash of the Subject Public Key Information (SPKI)\n// object in an x509 certificate (in DER encoding). It returns the full hash as a\n// hex encoded string (suitable for passing to Set.Allow).\nfunc Hash(certificate *x509.Certificate) string {\n\tspkiHash := sha256.Sum256(certificate.RawSubjectPublicKeyInfo)\n\treturn formatSHA256 + \":\" + strings.ToLower(hex.EncodeToString(spkiHash[:]))\n}","line":{"from":91,"to":97}} {"id":100001477,"name":"allowSHA256","signature":"func (s *Set) allowSHA256(hash string) error","file":"cmd/kubeadm/app/util/pubkeypin/pubkeypin.go","code":"// allowSHA256 validates a \"sha256\" format hash and adds a canonical version of it into the Set\nfunc (s *Set) allowSHA256(hash string) error {\n\t// validate that the hash is the right length to be a full SHA-256 hash\n\thashLength := hex.DecodedLen(len(hash))\n\tif hashLength != sha256.Size {\n\t\treturn errors.Errorf(\"expected a %d byte SHA-256 hash, found %d bytes\", sha256.Size, hashLength)\n\t}\n\n\t// validate that the hash is valid hex\n\t_, err := hex.DecodeString(hash)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"could not decode SHA-256 from hex\")\n\t}\n\n\t// in the end, just store the original hex string in memory (in lowercase)\n\ts.sha256Hashes[strings.ToLower(hash)] = true\n\treturn nil\n}","line":{"from":99,"to":116}} {"id":100001478,"name":"checkSHA256","signature":"func (s *Set) checkSHA256(certificate *x509.Certificate) bool","file":"cmd/kubeadm/app/util/pubkeypin/pubkeypin.go","code":"// checkSHA256 returns true if the certificate's \"sha256\" hash is pinned in the Set\nfunc (s *Set) checkSHA256(certificate *x509.Certificate) bool {\n\tactualHash := sha256.Sum256(certificate.RawSubjectPublicKeyInfo)\n\tactualHashHex := strings.ToLower(hex.EncodeToString(actualHash[:]))\n\treturn s.sha256Hashes[actualHashHex]\n}","line":{"from":118,"to":123}} {"id":100001479,"name":"NewContainerRuntime","signature":"func NewContainerRuntime(execer utilsexec.Interface, criSocket string) (ContainerRuntime, error)","file":"cmd/kubeadm/app/util/runtime/runtime.go","code":"// NewContainerRuntime sets up and returns a ContainerRuntime struct\nfunc NewContainerRuntime(execer utilsexec.Interface, criSocket string) (ContainerRuntime, error) {\n\tconst toolName = \"crictl\"\n\tcrictlPath, err := execer.LookPath(toolName)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"%s is required by the container runtime\", toolName)\n\t}\n\treturn \u0026CRIRuntime{execer, criSocket, crictlPath}, nil\n}","line":{"from":57,"to":65}} {"id":100001480,"name":"Socket","signature":"func (runtime *CRIRuntime) Socket() string","file":"cmd/kubeadm/app/util/runtime/runtime.go","code":"// Socket returns the CRI socket endpoint\nfunc (runtime *CRIRuntime) Socket() string {\n\treturn runtime.criSocket\n}","line":{"from":67,"to":70}} {"id":100001481,"name":"crictl","signature":"func (runtime *CRIRuntime) crictl(args ...string) utilsexec.Cmd","file":"cmd/kubeadm/app/util/runtime/runtime.go","code":"// crictl creates a crictl command for the provided args.\nfunc (runtime *CRIRuntime) crictl(args ...string) utilsexec.Cmd {\n\tcmd := runtime.exec.Command(runtime.crictlPath, append([]string{\"-r\", runtime.Socket()}, args...)...)\n\tcmd.SetEnv(os.Environ())\n\treturn cmd\n}","line":{"from":72,"to":77}} {"id":100001482,"name":"IsRunning","signature":"func (runtime *CRIRuntime) IsRunning() error","file":"cmd/kubeadm/app/util/runtime/runtime.go","code":"// IsRunning checks if runtime is running\nfunc (runtime *CRIRuntime) IsRunning() error {\n\tif out, err := runtime.crictl(\"info\").CombinedOutput(); err != nil {\n\t\treturn errors.Wrapf(err, \"container runtime is not running: output: %s, error\", string(out))\n\t}\n\treturn nil\n}","line":{"from":79,"to":85}} {"id":100001483,"name":"ListKubeContainers","signature":"func (runtime *CRIRuntime) ListKubeContainers() ([]string, error)","file":"cmd/kubeadm/app/util/runtime/runtime.go","code":"// ListKubeContainers lists running k8s CRI pods\nfunc (runtime *CRIRuntime) ListKubeContainers() ([]string, error) {\n\t// Disable debug mode regardless how the crictl is configured so that the debug info won't be\n\t// iterpreted to the Pod ID.\n\targs := []string{\"-D=false\", \"pods\", \"-q\"}\n\tout, err := runtime.crictl(args...).CombinedOutput()\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"output: %s, error\", string(out))\n\t}\n\tpods := []string{}\n\tpods = append(pods, strings.Fields(string(out))...)\n\treturn pods, nil\n}","line":{"from":87,"to":99}} {"id":100001484,"name":"RemoveContainers","signature":"func (runtime *CRIRuntime) RemoveContainers(containers []string) error","file":"cmd/kubeadm/app/util/runtime/runtime.go","code":"// RemoveContainers removes running k8s pods\nfunc (runtime *CRIRuntime) RemoveContainers(containers []string) error {\n\terrs := []error{}\n\tfor _, container := range containers {\n\t\tvar lastErr error\n\t\tfor i := 0; i \u003c constants.RemoveContainerRetry; i++ {\n\t\t\tklog.V(5).Infof(\"Attempting to remove container %v\", container)\n\t\t\tout, err := runtime.crictl(\"stopp\", container).CombinedOutput()\n\t\t\tif err != nil {\n\t\t\t\tlastErr = errors.Wrapf(err, \"failed to stop running pod %s: output: %s\", container, string(out))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tout, err = runtime.crictl(\"rmp\", container).CombinedOutput()\n\t\t\tif err != nil {\n\t\t\t\tlastErr = errors.Wrapf(err, \"failed to remove running container %s: output: %s\", container, string(out))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlastErr = nil\n\t\t\tbreak\n\t\t}\n\n\t\tif lastErr != nil {\n\t\t\terrs = append(errs, lastErr)\n\t\t}\n\t}\n\treturn errorsutil.NewAggregate(errs)\n}","line":{"from":101,"to":127}} {"id":100001485,"name":"PullImage","signature":"func (runtime *CRIRuntime) PullImage(image string) error","file":"cmd/kubeadm/app/util/runtime/runtime.go","code":"// PullImage pulls the image\nfunc (runtime *CRIRuntime) PullImage(image string) error {\n\tvar err error\n\tvar out []byte\n\tfor i := 0; i \u003c constants.PullImageRetry; i++ {\n\t\tout, err = runtime.crictl(\"pull\", image).CombinedOutput()\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn errors.Wrapf(err, \"output: %s, error\", out)\n}","line":{"from":129,"to":140}} {"id":100001486,"name":"ImageExists","signature":"func (runtime *CRIRuntime) ImageExists(image string) (bool, error)","file":"cmd/kubeadm/app/util/runtime/runtime.go","code":"// ImageExists checks to see if the image exists on the system\nfunc (runtime *CRIRuntime) ImageExists(image string) (bool, error) {\n\terr := runtime.crictl(\"inspecti\", image).Run()\n\treturn err == nil, nil\n}","line":{"from":142,"to":146}} {"id":100001487,"name":"detectCRISocketImpl","signature":"func detectCRISocketImpl(isSocket func(string) bool, knownCRISockets []string) (string, error)","file":"cmd/kubeadm/app/util/runtime/runtime.go","code":"// detectCRISocketImpl is separated out only for test purposes, DON'T call it directly, use DetectCRISocket instead\nfunc detectCRISocketImpl(isSocket func(string) bool, knownCRISockets []string) (string, error) {\n\tfoundCRISockets := []string{}\n\n\tfor _, socket := range knownCRISockets {\n\t\tif isSocket(socket) {\n\t\t\tfoundCRISockets = append(foundCRISockets, socket)\n\t\t}\n\t}\n\n\tswitch len(foundCRISockets) {\n\tcase 0:\n\t\t// Fall back to the default socket if no CRI is detected, we can error out later on if we need it\n\t\treturn constants.DefaultCRISocket, nil\n\tcase 1:\n\t\t// Precisely one CRI found, use that\n\t\treturn foundCRISockets[0], nil\n\tdefault:\n\t\t// Multiple CRIs installed?\n\t\treturn \"\", errors.Errorf(\"Found multiple CRI endpoints on the host. Please define which one do you wish \"+\n\t\t\t\"to use by setting the 'criSocket' field in the kubeadm configuration file: %s\",\n\t\t\tstrings.Join(foundCRISockets, \", \"))\n\t}\n}","line":{"from":148,"to":171}} {"id":100001488,"name":"DetectCRISocket","signature":"func DetectCRISocket() (string, error)","file":"cmd/kubeadm/app/util/runtime/runtime.go","code":"// DetectCRISocket uses a list of known CRI sockets to detect one. If more than one or none is discovered, an error is returned.\nfunc DetectCRISocket() (string, error) {\n\treturn detectCRISocketImpl(isExistingSocket, defaultKnownCRISockets)\n}","line":{"from":173,"to":176}} {"id":100001489,"name":"SandboxImage","signature":"func (runtime *CRIRuntime) SandboxImage() (string, error)","file":"cmd/kubeadm/app/util/runtime/runtime.go","code":"// SandboxImage returns the sandbox image used by the container runtime\nfunc (runtime *CRIRuntime) SandboxImage() (string, error) {\n\targs := []string{\"-D=false\", \"info\", \"-o\", \"go-template\", \"--template\", \"{{.config.sandboxImage}}\"}\n\tout, err := runtime.crictl(args...).CombinedOutput()\n\tif err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"output: %s, error\", string(out))\n\t}\n\n\tsandboxImage := strings.TrimSpace(string(out))\n\tif len(sandboxImage) \u003e 0 {\n\t\treturn sandboxImage, nil\n\t}\n\n\treturn \"\", errors.Errorf(\"the detected sandbox image is empty\")\n}","line":{"from":178,"to":192}} {"id":100001490,"name":"isExistingSocket","signature":"func isExistingSocket(path string) bool","file":"cmd/kubeadm/app/util/runtime/runtime_unix.go","code":"// isExistingSocket checks if path exists and is domain socket\nfunc isExistingSocket(path string) bool {\n\tu, err := url.Parse(path)\n\tif err != nil {\n\t\t// should not happen, since we are trying to access known / hardcoded sockets\n\t\treturn false\n\t}\n\n\tc, err := net.Dial(u.Scheme, u.Path)\n\tif err != nil {\n\t\treturn false\n\t}\n\tdefer c.Close()\n\treturn true\n}","line":{"from":27,"to":41}} {"id":100001491,"name":"isExistingSocket","signature":"func isExistingSocket(path string) bool","file":"cmd/kubeadm/app/util/runtime/runtime_windows.go","code":"// isExistingSocket checks if path exists and is domain socket\nfunc isExistingSocket(path string) bool {\n\tu, err := url.Parse(path)\n\tif err != nil {\n\t\t// should not happen, since we are trying to access known / hardcoded sockets\n\t\treturn false\n\t}\n\n\t// the dial path must be without \"npipe://\"\n\t_, err = winio.DialPipe(u.Path, nil)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn true\n}","line":{"from":28,"to":43}} {"id":100001492,"name":"ComponentPod","signature":"func ComponentPod(container v1.Container, volumes map[string]v1.Volume, annotations map[string]string) v1.Pod","file":"cmd/kubeadm/app/util/staticpod/utils.go","code":"// ComponentPod returns a Pod object from the container, volume and annotations specifications\nfunc ComponentPod(container v1.Container, volumes map[string]v1.Volume, annotations map[string]string) v1.Pod {\n\t// priority value for system-node-critical class\n\tpriority := int32(2000001000)\n\treturn v1.Pod{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"v1\",\n\t\t\tKind: \"Pod\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: container.Name,\n\t\t\tNamespace: metav1.NamespaceSystem,\n\t\t\t// The component and tier labels are useful for quickly identifying the control plane Pods when doing a .List()\n\t\t\t// against Pods in the kube-system namespace. Can for example be used together with the WaitForPodsWithLabel function\n\t\t\tLabels: map[string]string{\"component\": container.Name, \"tier\": kubeadmconstants.ControlPlaneTier},\n\t\t\tAnnotations: annotations,\n\t\t},\n\t\tSpec: v1.PodSpec{\n\t\t\tContainers: []v1.Container{container},\n\t\t\tPriority: \u0026priority,\n\t\t\tPriorityClassName: \"system-node-critical\",\n\t\t\tHostNetwork: true,\n\t\t\tVolumes: VolumeMapToSlice(volumes),\n\t\t\tSecurityContext: \u0026v1.PodSecurityContext{\n\t\t\t\tSeccompProfile: \u0026v1.SeccompProfile{\n\t\t\t\t\tType: v1.SeccompProfileTypeRuntimeDefault,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":60,"to":90}} {"id":100001493,"name":"ComponentResources","signature":"func ComponentResources(cpu string) v1.ResourceRequirements","file":"cmd/kubeadm/app/util/staticpod/utils.go","code":"// ComponentResources returns the v1.ResourceRequirements object needed for allocating a specified amount of the CPU\nfunc ComponentResources(cpu string) v1.ResourceRequirements {\n\treturn v1.ResourceRequirements{\n\t\tRequests: v1.ResourceList{\n\t\t\tv1.ResourceName(v1.ResourceCPU): resource.MustParse(cpu),\n\t\t},\n\t}\n}","line":{"from":92,"to":99}} {"id":100001494,"name":"NewVolume","signature":"func NewVolume(name, path string, pathType *v1.HostPathType) v1.Volume","file":"cmd/kubeadm/app/util/staticpod/utils.go","code":"// NewVolume creates a v1.Volume with a hostPath mount to the specified location\nfunc NewVolume(name, path string, pathType *v1.HostPathType) v1.Volume {\n\treturn v1.Volume{\n\t\tName: name,\n\t\tVolumeSource: v1.VolumeSource{\n\t\t\tHostPath: \u0026v1.HostPathVolumeSource{\n\t\t\t\tPath: path,\n\t\t\t\tType: pathType,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":101,"to":112}} {"id":100001495,"name":"NewVolumeMount","signature":"func NewVolumeMount(name, path string, readOnly bool) v1.VolumeMount","file":"cmd/kubeadm/app/util/staticpod/utils.go","code":"// NewVolumeMount creates a v1.VolumeMount to the specified location\nfunc NewVolumeMount(name, path string, readOnly bool) v1.VolumeMount {\n\treturn v1.VolumeMount{\n\t\tName: name,\n\t\tMountPath: path,\n\t\tReadOnly: readOnly,\n\t}\n}","line":{"from":114,"to":121}} {"id":100001496,"name":"VolumeMapToSlice","signature":"func VolumeMapToSlice(volumes map[string]v1.Volume) []v1.Volume","file":"cmd/kubeadm/app/util/staticpod/utils.go","code":"// VolumeMapToSlice returns a slice of volumes from a map's values\nfunc VolumeMapToSlice(volumes map[string]v1.Volume) []v1.Volume {\n\tv := make([]v1.Volume, 0, len(volumes))\n\n\tfor _, vol := range volumes {\n\t\tv = append(v, vol)\n\t}\n\n\tsort.Slice(v, func(i, j int) bool {\n\t\treturn strings.Compare(v[i].Name, v[j].Name) == -1\n\t})\n\n\treturn v\n}","line":{"from":123,"to":136}} {"id":100001497,"name":"VolumeMountMapToSlice","signature":"func VolumeMountMapToSlice(volumeMounts map[string]v1.VolumeMount) []v1.VolumeMount","file":"cmd/kubeadm/app/util/staticpod/utils.go","code":"// VolumeMountMapToSlice returns a slice of volumes from a map's values\nfunc VolumeMountMapToSlice(volumeMounts map[string]v1.VolumeMount) []v1.VolumeMount {\n\tv := make([]v1.VolumeMount, 0, len(volumeMounts))\n\n\tfor _, volMount := range volumeMounts {\n\t\tv = append(v, volMount)\n\t}\n\n\tsort.Slice(v, func(i, j int) bool {\n\t\treturn strings.Compare(v[i].Name, v[j].Name) == -1\n\t})\n\n\treturn v\n}","line":{"from":138,"to":151}} {"id":100001498,"name":"GetExtraParameters","signature":"func GetExtraParameters(overrides map[string]string, defaults map[string]string) []string","file":"cmd/kubeadm/app/util/staticpod/utils.go","code":"// GetExtraParameters builds a list of flag arguments two string-string maps, one with default, base commands and one with overrides\nfunc GetExtraParameters(overrides map[string]string, defaults map[string]string) []string {\n\tvar command []string\n\tfor k, v := range overrides {\n\t\tif len(v) \u003e 0 {\n\t\t\tcommand = append(command, fmt.Sprintf(\"--%s=%s\", k, v))\n\t\t}\n\t}\n\tfor k, v := range defaults {\n\t\tif _, overrideExists := overrides[k]; !overrideExists {\n\t\t\tcommand = append(command, fmt.Sprintf(\"--%s=%s\", k, v))\n\t\t}\n\t}\n\treturn command\n}","line":{"from":153,"to":167}} {"id":100001499,"name":"PatchStaticPod","signature":"func PatchStaticPod(pod *v1.Pod, patchesDir string, output io.Writer) (*v1.Pod, error)","file":"cmd/kubeadm/app/util/staticpod/utils.go","code":"// PatchStaticPod applies patches stored in patchesDir to a static Pod.\nfunc PatchStaticPod(pod *v1.Pod, patchesDir string, output io.Writer) (*v1.Pod, error) {\n\t// Marshal the Pod manifest into YAML.\n\tpodYAML, err := kubeadmutil.MarshalToYaml(pod, v1.SchemeGroupVersion)\n\tif err != nil {\n\t\treturn pod, errors.Wrapf(err, \"failed to marshal Pod manifest to YAML\")\n\t}\n\n\tpatchManager, err := patches.GetPatchManagerForPath(patchesDir, patches.KnownTargets(), output)\n\tif err != nil {\n\t\treturn pod, err\n\t}\n\n\tpatchTarget := \u0026patches.PatchTarget{\n\t\tName: pod.Name,\n\t\tStrategicMergePatchObject: v1.Pod{},\n\t\tData: podYAML,\n\t}\n\tif err := patchManager.ApplyPatchesToTarget(patchTarget); err != nil {\n\t\treturn pod, err\n\t}\n\n\tobj, err := kubeadmutil.UnmarshalFromYaml(patchTarget.Data, v1.SchemeGroupVersion)\n\tif err != nil {\n\t\treturn pod, errors.Wrap(err, \"failed to unmarshal patched manifest from YAML\")\n\t}\n\n\tpod2, ok := obj.(*v1.Pod)\n\tif !ok {\n\t\treturn pod, errors.Wrap(err, \"patched manifest is not a valid Pod object\")\n\t}\n\n\treturn pod2, nil\n}","line":{"from":169,"to":202}} {"id":100001500,"name":"WriteStaticPodToDisk","signature":"func WriteStaticPodToDisk(componentName, manifestDir string, pod v1.Pod) error","file":"cmd/kubeadm/app/util/staticpod/utils.go","code":"// WriteStaticPodToDisk writes a static pod file to disk\nfunc WriteStaticPodToDisk(componentName, manifestDir string, pod v1.Pod) error {\n\n\t// creates target folder if not already exists\n\tif err := os.MkdirAll(manifestDir, 0700); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to create directory %q\", manifestDir)\n\t}\n\n\t// writes the pod to disk\n\tserialized, err := kubeadmutil.MarshalToYaml(\u0026pod, v1.SchemeGroupVersion)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to marshal manifest for %q to YAML\", componentName)\n\t}\n\n\tfilename := kubeadmconstants.GetStaticPodFilepath(componentName, manifestDir)\n\n\tif err := os.WriteFile(filename, serialized, 0600); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to write static pod manifest file for %q (%q)\", componentName, filename)\n\t}\n\n\treturn nil\n}","line":{"from":204,"to":225}} {"id":100001501,"name":"ReadStaticPodFromDisk","signature":"func ReadStaticPodFromDisk(manifestPath string) (*v1.Pod, error)","file":"cmd/kubeadm/app/util/staticpod/utils.go","code":"// ReadStaticPodFromDisk reads a static pod file from disk\nfunc ReadStaticPodFromDisk(manifestPath string) (*v1.Pod, error) {\n\tbuf, err := os.ReadFile(manifestPath)\n\tif err != nil {\n\t\treturn \u0026v1.Pod{}, errors.Wrapf(err, \"failed to read manifest for %q\", manifestPath)\n\t}\n\n\tobj, err := kubeadmutil.UnmarshalFromYaml(buf, v1.SchemeGroupVersion)\n\tif err != nil {\n\t\treturn \u0026v1.Pod{}, errors.Errorf(\"failed to unmarshal manifest for %q from YAML: %v\", manifestPath, err)\n\t}\n\n\tpod := obj.(*v1.Pod)\n\n\treturn pod, nil\n}","line":{"from":227,"to":242}} {"id":100001502,"name":"LivenessProbe","signature":"func LivenessProbe(host, path string, port int, scheme v1.URIScheme) *v1.Probe","file":"cmd/kubeadm/app/util/staticpod/utils.go","code":"// LivenessProbe creates a Probe object with a HTTPGet handler\nfunc LivenessProbe(host, path string, port int, scheme v1.URIScheme) *v1.Probe {\n\t// sets initialDelaySeconds same as periodSeconds to skip one period before running a check\n\treturn createHTTPProbe(host, path, port, scheme, 10, 15, 8, 10)\n}","line":{"from":244,"to":248}} {"id":100001503,"name":"ReadinessProbe","signature":"func ReadinessProbe(host, path string, port int, scheme v1.URIScheme) *v1.Probe","file":"cmd/kubeadm/app/util/staticpod/utils.go","code":"// ReadinessProbe creates a Probe object with a HTTPGet handler\nfunc ReadinessProbe(host, path string, port int, scheme v1.URIScheme) *v1.Probe {\n\t// sets initialDelaySeconds as '0' because we don't want to delay user infrastructure checks\n\t// looking for \"ready\" status on kubeadm static Pods\n\treturn createHTTPProbe(host, path, port, scheme, 0, 15, 3, 1)\n}","line":{"from":250,"to":255}} {"id":100001504,"name":"StartupProbe","signature":"func StartupProbe(host, path string, port int, scheme v1.URIScheme, timeoutForControlPlane *metav1.Duration) *v1.Probe","file":"cmd/kubeadm/app/util/staticpod/utils.go","code":"// StartupProbe creates a Probe object with a HTTPGet handler\nfunc StartupProbe(host, path string, port int, scheme v1.URIScheme, timeoutForControlPlane *metav1.Duration) *v1.Probe {\n\tperiodSeconds, timeoutForControlPlaneSeconds := int32(10), kubeadmconstants.DefaultControlPlaneTimeout.Seconds()\n\tif timeoutForControlPlane != nil {\n\t\ttimeoutForControlPlaneSeconds = timeoutForControlPlane.Seconds()\n\t}\n\t// sets failureThreshold big enough to guarantee the full timeout can cover the worst case scenario for the control-plane to come alive\n\t// we ignore initialDelaySeconds in the calculation here for simplicity\n\tfailureThreshold := int32(math.Ceil(timeoutForControlPlaneSeconds / float64(periodSeconds)))\n\t// sets initialDelaySeconds same as periodSeconds to skip one period before running a check\n\treturn createHTTPProbe(host, path, port, scheme, periodSeconds, 15, failureThreshold, periodSeconds)\n}","line":{"from":257,"to":268}} {"id":100001505,"name":"createHTTPProbe","signature":"func createHTTPProbe(host, path string, port int, scheme v1.URIScheme, initialDelaySeconds, timeoutSeconds, failureThreshold, periodSeconds int32) *v1.Probe","file":"cmd/kubeadm/app/util/staticpod/utils.go","code":"func createHTTPProbe(host, path string, port int, scheme v1.URIScheme, initialDelaySeconds, timeoutSeconds, failureThreshold, periodSeconds int32) *v1.Probe {\n\treturn \u0026v1.Probe{\n\t\tProbeHandler: v1.ProbeHandler{\n\t\t\tHTTPGet: \u0026v1.HTTPGetAction{\n\t\t\t\tHost: host,\n\t\t\t\tPath: path,\n\t\t\t\tPort: intstr.FromInt(port),\n\t\t\t\tScheme: scheme,\n\t\t\t},\n\t\t},\n\t\tInitialDelaySeconds: initialDelaySeconds,\n\t\tTimeoutSeconds: timeoutSeconds,\n\t\tFailureThreshold: failureThreshold,\n\t\tPeriodSeconds: periodSeconds,\n\t}\n}","line":{"from":270,"to":285}} {"id":100001506,"name":"GetAPIServerProbeAddress","signature":"func GetAPIServerProbeAddress(endpoint *kubeadmapi.APIEndpoint) string","file":"cmd/kubeadm/app/util/staticpod/utils.go","code":"// GetAPIServerProbeAddress returns the probe address for the API server\nfunc GetAPIServerProbeAddress(endpoint *kubeadmapi.APIEndpoint) string {\n\tif endpoint != nil \u0026\u0026 endpoint.AdvertiseAddress != \"\" {\n\t\treturn getProbeAddress(endpoint.AdvertiseAddress)\n\t}\n\n\treturn \"127.0.0.1\"\n}","line":{"from":287,"to":294}} {"id":100001507,"name":"GetControllerManagerProbeAddress","signature":"func GetControllerManagerProbeAddress(cfg *kubeadmapi.ClusterConfiguration) string","file":"cmd/kubeadm/app/util/staticpod/utils.go","code":"// GetControllerManagerProbeAddress returns the kubernetes controller manager probe address\nfunc GetControllerManagerProbeAddress(cfg *kubeadmapi.ClusterConfiguration) string {\n\tif addr, exists := cfg.ControllerManager.ExtraArgs[kubeControllerManagerBindAddressArg]; exists {\n\t\treturn getProbeAddress(addr)\n\t}\n\treturn \"127.0.0.1\"\n}","line":{"from":296,"to":302}} {"id":100001508,"name":"GetSchedulerProbeAddress","signature":"func GetSchedulerProbeAddress(cfg *kubeadmapi.ClusterConfiguration) string","file":"cmd/kubeadm/app/util/staticpod/utils.go","code":"// GetSchedulerProbeAddress returns the kubernetes scheduler probe address\nfunc GetSchedulerProbeAddress(cfg *kubeadmapi.ClusterConfiguration) string {\n\tif addr, exists := cfg.Scheduler.ExtraArgs[kubeSchedulerBindAddressArg]; exists {\n\t\treturn getProbeAddress(addr)\n\t}\n\treturn \"127.0.0.1\"\n}","line":{"from":304,"to":310}} {"id":100001509,"name":"GetEtcdProbeEndpoint","signature":"func GetEtcdProbeEndpoint(cfg *kubeadmapi.Etcd, isIPv6 bool) (string, int, v1.URIScheme)","file":"cmd/kubeadm/app/util/staticpod/utils.go","code":"// GetEtcdProbeEndpoint takes a kubeadm Etcd configuration object and attempts to parse\n// the first URL in the listen-metrics-urls argument, returning an etcd probe hostname,\n// port and scheme\nfunc GetEtcdProbeEndpoint(cfg *kubeadmapi.Etcd, isIPv6 bool) (string, int, v1.URIScheme) {\n\tlocalhost := \"127.0.0.1\"\n\tif isIPv6 {\n\t\tlocalhost = \"::1\"\n\t}\n\tif cfg.Local == nil || cfg.Local.ExtraArgs == nil {\n\t\treturn localhost, kubeadmconstants.EtcdMetricsPort, v1.URISchemeHTTP\n\t}\n\tif arg, exists := cfg.Local.ExtraArgs[\"listen-metrics-urls\"]; exists {\n\t\t// Use the first url in the listen-metrics-urls if multiple URL's are specified.\n\t\targ = strings.Split(arg, \",\")[0]\n\t\tparsedURL, err := url.Parse(arg)\n\t\tif err != nil {\n\t\t\treturn localhost, kubeadmconstants.EtcdMetricsPort, v1.URISchemeHTTP\n\t\t}\n\t\t// Parse scheme\n\t\tscheme := v1.URISchemeHTTP\n\t\tif parsedURL.Scheme == \"https\" {\n\t\t\tscheme = v1.URISchemeHTTPS\n\t\t}\n\t\t// Parse hostname\n\t\thostname := parsedURL.Hostname()\n\t\tif len(hostname) == 0 {\n\t\t\thostname = localhost\n\t\t}\n\t\t// Parse port\n\t\tport := kubeadmconstants.EtcdMetricsPort\n\t\tportStr := parsedURL.Port()\n\t\tif len(portStr) != 0 {\n\t\t\tp, err := kubeadmutil.ParsePort(portStr)\n\t\t\tif err == nil {\n\t\t\t\tport = p\n\t\t\t}\n\t\t}\n\t\treturn hostname, port, scheme\n\t}\n\treturn localhost, kubeadmconstants.EtcdMetricsPort, v1.URISchemeHTTP\n}","line":{"from":312,"to":352}} {"id":100001510,"name":"ManifestFilesAreEqual","signature":"func ManifestFilesAreEqual(path1, path2 string) (bool, error)","file":"cmd/kubeadm/app/util/staticpod/utils.go","code":"// ManifestFilesAreEqual compares 2 files. It returns true if their contents are equal, false otherwise\nfunc ManifestFilesAreEqual(path1, path2 string) (bool, error) {\n\tpod1, err := ReadStaticPodFromDisk(path1)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tpod2, err := ReadStaticPodFromDisk(path2)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\thasher := md5.New()\n\tDeepHashObject(hasher, pod1)\n\thash1 := hasher.Sum(nil)[0:]\n\tDeepHashObject(hasher, pod2)\n\thash2 := hasher.Sum(nil)[0:]\n\n\treturn bytes.Equal(hash1, hash2), nil\n}","line":{"from":354,"to":372}} {"id":100001511,"name":"getProbeAddress","signature":"func getProbeAddress(addr string) string","file":"cmd/kubeadm/app/util/staticpod/utils.go","code":"// getProbeAddress returns a valid probe address.\n// Kubeadm uses the bind-address to configure the probe address. It's common to use the\n// unspecified address \"0.0.0.0\" or \"::\" as bind-address when we want to listen in all interfaces,\n// however this address can't be used as probe #86504.\n// If the address is an unspecified address getProbeAddress returns empty,\n// that means that kubelet will use the PodIP as probe address.\nfunc getProbeAddress(addr string) string {\n\tif addr == \"0.0.0.0\" || addr == \"::\" {\n\t\treturn \"\"\n\t}\n\treturn addr\n}","line":{"from":374,"to":385}} {"id":100001512,"name":"GetUsersAndGroups","signature":"func GetUsersAndGroups() (*users.UsersAndGroups, error)","file":"cmd/kubeadm/app/util/staticpod/utils.go","code":"func GetUsersAndGroups() (*users.UsersAndGroups, error) {\n\tvar err error\n\tusersAndGroupsOnce.Do(func() {\n\t\tusersAndGroups, err = users.AddUsersAndGroups()\n\t})\n\treturn usersAndGroups, err\n}","line":{"from":387,"to":393}} {"id":100001513,"name":"DeepHashObject","signature":"func DeepHashObject(hasher hash.Hash, objectToWrite interface{})","file":"cmd/kubeadm/app/util/staticpod/utils.go","code":"// DeepHashObject writes specified object to hash using the spew library\n// which follows pointers and prints actual values of the nested objects\n// ensuring the hash does not change when a pointer changes.\n// Copied from k8s.io/kubernetes/pkg/util/hash/hash.go#DeepHashObject\nfunc DeepHashObject(hasher hash.Hash, objectToWrite interface{}) {\n\thasher.Reset()\n\tprinter := spew.ConfigState{\n\t\tIndent: \" \",\n\t\tSortKeys: true,\n\t\tDisableMethods: true,\n\t\tSpewKeys: true,\n\t}\n\tprinter.Fprintf(hasher, \"%#v\", objectToWrite)\n}","line":{"from":395,"to":408}} {"id":100001514,"name":"RunComponentAsNonRoot","signature":"func RunComponentAsNonRoot(componentName string, pod *v1.Pod, usersAndGroups *users.UsersAndGroups, cfg *kubeadmapi.ClusterConfiguration) error","file":"cmd/kubeadm/app/util/staticpod/utils_linux.go","code":"// RunComponentAsNonRoot updates the pod manifest and the hostVolume permissions to run as non root.\nfunc RunComponentAsNonRoot(componentName string, pod *v1.Pod, usersAndGroups *users.UsersAndGroups, cfg *kubeadmapi.ClusterConfiguration) error {\n\tswitch componentName {\n\tcase kubeadmconstants.KubeAPIServer:\n\t\treturn runKubeAPIServerAsNonRoot(\n\t\t\tpod,\n\t\t\tusersAndGroups.Users.ID(kubeadmconstants.KubeAPIServerUserName),\n\t\t\tusersAndGroups.Groups.ID(kubeadmconstants.KubeAPIServerUserName),\n\t\t\tusersAndGroups.Groups.ID(kubeadmconstants.ServiceAccountKeyReadersGroupName),\n\t\t\tusers.UpdatePathOwnerAndPermissions,\n\t\t\tcfg,\n\t\t)\n\tcase kubeadmconstants.KubeControllerManager:\n\t\treturn runKubeControllerManagerAsNonRoot(\n\t\t\tpod,\n\t\t\tusersAndGroups.Users.ID(kubeadmconstants.KubeControllerManagerUserName),\n\t\t\tusersAndGroups.Groups.ID(kubeadmconstants.KubeControllerManagerUserName),\n\t\t\tusersAndGroups.Groups.ID(kubeadmconstants.ServiceAccountKeyReadersGroupName),\n\t\t\tusers.UpdatePathOwnerAndPermissions,\n\t\t\tcfg,\n\t\t)\n\tcase kubeadmconstants.KubeScheduler:\n\t\treturn runKubeSchedulerAsNonRoot(\n\t\t\tpod,\n\t\t\tusersAndGroups.Users.ID(kubeadmconstants.KubeSchedulerUserName),\n\t\t\tusersAndGroups.Groups.ID(kubeadmconstants.KubeSchedulerUserName),\n\t\t\tusers.UpdatePathOwnerAndPermissions,\n\t\t)\n\tcase kubeadmconstants.Etcd:\n\t\treturn runEtcdAsNonRoot(\n\t\t\tpod,\n\t\t\tusersAndGroups.Users.ID(kubeadmconstants.EtcdUserName),\n\t\t\tusersAndGroups.Groups.ID(kubeadmconstants.EtcdUserName),\n\t\t\tusers.UpdatePathOwnerAndPermissions,\n\t\t\tusers.UpdatePathOwner,\n\t\t\tcfg,\n\t\t)\n\t}\n\treturn errors.New(fmt.Sprintf(\"component name %q is not valid\", componentName))\n}","line":{"from":40,"to":79}} {"id":100001515,"name":"runKubeAPIServerAsNonRoot","signature":"func runKubeAPIServerAsNonRoot(pod *v1.Pod, runAsUser, runAsGroup, supplementalGroup *int64, updatePathOwnerAndPermissions pathOwnerAndPermissionsUpdaterFunc, cfg *kubeadmapi.ClusterConfiguration) error","file":"cmd/kubeadm/app/util/staticpod/utils_linux.go","code":"// runKubeAPIServerAsNonRoot updates the pod manifest and the hostVolume permissions to run kube-apiserver as non root.\nfunc runKubeAPIServerAsNonRoot(pod *v1.Pod, runAsUser, runAsGroup, supplementalGroup *int64, updatePathOwnerAndPermissions pathOwnerAndPermissionsUpdaterFunc, cfg *kubeadmapi.ClusterConfiguration) error {\n\tsaPublicKeyFile := filepath.Join(cfg.CertificatesDir, kubeadmconstants.ServiceAccountPublicKeyName)\n\tif err := updatePathOwnerAndPermissions(saPublicKeyFile, *runAsUser, *runAsGroup, 0600); err != nil {\n\t\treturn err\n\t}\n\tsaPrivateKeyFile := filepath.Join(cfg.CertificatesDir, kubeadmconstants.ServiceAccountPrivateKeyName)\n\tif err := updatePathOwnerAndPermissions(saPrivateKeyFile, 0, *supplementalGroup, 0640); err != nil {\n\t\treturn err\n\t}\n\tapiServerKeyFile := filepath.Join(cfg.CertificatesDir, kubeadmconstants.APIServerKeyName)\n\tif err := updatePathOwnerAndPermissions(apiServerKeyFile, *runAsUser, *runAsGroup, 0600); err != nil {\n\t\treturn err\n\t}\n\tapiServerKubeletClientKeyFile := filepath.Join(cfg.CertificatesDir, kubeadmconstants.APIServerKubeletClientKeyName)\n\tif err := updatePathOwnerAndPermissions(apiServerKubeletClientKeyFile, *runAsUser, *runAsGroup, 0600); err != nil {\n\t\treturn err\n\t}\n\tfrontProxyClientKeyName := filepath.Join(cfg.CertificatesDir, kubeadmconstants.FrontProxyClientKeyName)\n\tif err := updatePathOwnerAndPermissions(frontProxyClientKeyName, *runAsUser, *runAsGroup, 0600); err != nil {\n\t\treturn err\n\t}\n\tif cfg.Etcd.External == nil {\n\t\tapiServerEtcdClientKeyFile := filepath.Join(cfg.CertificatesDir, kubeadmconstants.APIServerEtcdClientKeyName)\n\t\tif err := updatePathOwnerAndPermissions(apiServerEtcdClientKeyFile, *runAsUser, *runAsGroup, 0600); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tpod.Spec.Containers[0].SecurityContext = \u0026v1.SecurityContext{\n\t\tCapabilities: \u0026v1.Capabilities{\n\t\t\t// We drop all capabilities that are added by default.\n\t\t\tDrop: []v1.Capability{\"ALL\"},\n\t\t\t// kube-apiserver binary has the file capability cap_net_bind_service applied to it.\n\t\t\t// This means that we must add this capability when running as non-root even if the\n\t\t\t// capability is not required.\n\t\t\tAdd: []v1.Capability{\"NET_BIND_SERVICE\"},\n\t\t},\n\t}\n\tpod.Spec.SecurityContext.RunAsGroup = runAsGroup\n\tpod.Spec.SecurityContext.RunAsUser = runAsUser\n\tpod.Spec.SecurityContext.SupplementalGroups = []int64{*supplementalGroup}\n\treturn nil\n}","line":{"from":81,"to":123}} {"id":100001516,"name":"runKubeControllerManagerAsNonRoot","signature":"func runKubeControllerManagerAsNonRoot(pod *v1.Pod, runAsUser, runAsGroup, supplementalGroup *int64, updatePathOwnerAndPermissions pathOwnerAndPermissionsUpdaterFunc, cfg *kubeadmapi.ClusterConfiguration) error","file":"cmd/kubeadm/app/util/staticpod/utils_linux.go","code":"// runKubeControllerManagerAsNonRoot updates the pod manifest and the hostVolume permissions to run kube-controller-manager as non root.\nfunc runKubeControllerManagerAsNonRoot(pod *v1.Pod, runAsUser, runAsGroup, supplementalGroup *int64, updatePathOwnerAndPermissions pathOwnerAndPermissionsUpdaterFunc, cfg *kubeadmapi.ClusterConfiguration) error {\n\tkubeconfigFile := filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.ControllerManagerKubeConfigFileName)\n\tif err := updatePathOwnerAndPermissions(kubeconfigFile, *runAsUser, *runAsGroup, 0600); err != nil {\n\t\treturn err\n\t}\n\tsaPrivateKeyFile := filepath.Join(cfg.CertificatesDir, kubeadmconstants.ServiceAccountPrivateKeyName)\n\tif err := updatePathOwnerAndPermissions(saPrivateKeyFile, 0, *supplementalGroup, 0640); err != nil {\n\t\treturn err\n\t}\n\tif res, _ := certphase.UsingExternalCA(cfg); !res {\n\t\tcaKeyFile := filepath.Join(cfg.CertificatesDir, kubeadmconstants.CAKeyName)\n\t\terr := updatePathOwnerAndPermissions(caKeyFile, *runAsUser, *runAsGroup, 0600)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tpod.Spec.Containers[0].SecurityContext = \u0026v1.SecurityContext{\n\t\tAllowPrivilegeEscalation: pointer.Bool(false),\n\t\tCapabilities: \u0026v1.Capabilities{\n\t\t\t// We drop all capabilities that are added by default.\n\t\t\tDrop: []v1.Capability{\"ALL\"},\n\t\t},\n\t}\n\tpod.Spec.SecurityContext.RunAsUser = runAsUser\n\tpod.Spec.SecurityContext.RunAsGroup = runAsGroup\n\tpod.Spec.SecurityContext.SupplementalGroups = []int64{*supplementalGroup}\n\treturn nil\n}","line":{"from":125,"to":153}} {"id":100001517,"name":"runKubeSchedulerAsNonRoot","signature":"func runKubeSchedulerAsNonRoot(pod *v1.Pod, runAsUser, runAsGroup *int64, updatePathOwnerAndPermissions pathOwnerAndPermissionsUpdaterFunc) error","file":"cmd/kubeadm/app/util/staticpod/utils_linux.go","code":"// runKubeSchedulerAsNonRoot updates the pod manifest and the hostVolume permissions to run kube-scheduler as non root.\nfunc runKubeSchedulerAsNonRoot(pod *v1.Pod, runAsUser, runAsGroup *int64, updatePathOwnerAndPermissions pathOwnerAndPermissionsUpdaterFunc) error {\n\tkubeconfigFile := filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.SchedulerKubeConfigFileName)\n\tif err := updatePathOwnerAndPermissions(kubeconfigFile, *runAsUser, *runAsGroup, 0600); err != nil {\n\t\treturn err\n\t}\n\tpod.Spec.Containers[0].SecurityContext = \u0026v1.SecurityContext{\n\t\tAllowPrivilegeEscalation: pointer.Bool(false),\n\t\t// We drop all capabilities that are added by default.\n\t\tCapabilities: \u0026v1.Capabilities{\n\t\t\tDrop: []v1.Capability{\"ALL\"},\n\t\t},\n\t}\n\tpod.Spec.SecurityContext.RunAsUser = runAsUser\n\tpod.Spec.SecurityContext.RunAsGroup = runAsGroup\n\treturn nil\n}","line":{"from":155,"to":171}} {"id":100001518,"name":"runEtcdAsNonRoot","signature":"func runEtcdAsNonRoot(pod *v1.Pod, runAsUser, runAsGroup *int64, updatePathOwnerAndPermissions pathOwnerAndPermissionsUpdaterFunc, updatePathOwner pathOwnerUpdaterFunc, cfg *kubeadmapi.ClusterConfiguration) error","file":"cmd/kubeadm/app/util/staticpod/utils_linux.go","code":"// runEtcdAsNonRoot updates the pod manifest and the hostVolume permissions to run etcd as non root.\nfunc runEtcdAsNonRoot(pod *v1.Pod, runAsUser, runAsGroup *int64, updatePathOwnerAndPermissions pathOwnerAndPermissionsUpdaterFunc, updatePathOwner pathOwnerUpdaterFunc, cfg *kubeadmapi.ClusterConfiguration) error {\n\tif err := updatePathOwner(cfg.Etcd.Local.DataDir, *runAsUser, *runAsGroup); err != nil {\n\t\treturn err\n\t}\n\tetcdServerKeyFile := filepath.Join(cfg.CertificatesDir, kubeadmconstants.EtcdServerKeyName)\n\tif err := updatePathOwnerAndPermissions(etcdServerKeyFile, *runAsUser, *runAsGroup, 0600); err != nil {\n\t\treturn err\n\t}\n\tetcdPeerKeyFile := filepath.Join(cfg.CertificatesDir, kubeadmconstants.EtcdPeerKeyName)\n\tif err := updatePathOwnerAndPermissions(etcdPeerKeyFile, *runAsUser, *runAsGroup, 0600); err != nil {\n\t\treturn err\n\t}\n\tpod.Spec.Containers[0].SecurityContext = \u0026v1.SecurityContext{\n\t\tAllowPrivilegeEscalation: pointer.Bool(false),\n\t\t// We drop all capabilities that are added by default.\n\t\tCapabilities: \u0026v1.Capabilities{\n\t\t\tDrop: []v1.Capability{\"ALL\"},\n\t\t},\n\t}\n\tpod.Spec.SecurityContext.RunAsUser = runAsUser\n\tpod.Spec.SecurityContext.RunAsGroup = runAsGroup\n\treturn nil\n}","line":{"from":173,"to":196}} {"id":100001519,"name":"RunComponentAsNonRoot","signature":"func RunComponentAsNonRoot(componentName string, pod *v1.Pod, usersAndGroups *users.UsersAndGroups, cfg *kubeadmapi.ClusterConfiguration) error","file":"cmd/kubeadm/app/util/staticpod/utils_others.go","code":"// RunComponentAsNonRoot is a NO-OP on non linux.\nfunc RunComponentAsNonRoot(componentName string, pod *v1.Pod, usersAndGroups *users.UsersAndGroups, cfg *kubeadmapi.ClusterConfiguration) error {\n\treturn nil\n}","line":{"from":29,"to":32}} {"id":100001520,"name":"ParseTemplate","signature":"func ParseTemplate(strtmpl string, obj interface{}) ([]byte, error)","file":"cmd/kubeadm/app/util/template.go","code":"// ParseTemplate validates and parses passed as argument template\nfunc ParseTemplate(strtmpl string, obj interface{}) ([]byte, error) {\n\tvar buf bytes.Buffer\n\ttmpl, err := template.New(\"template\").Parse(strtmpl)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error when parsing template\")\n\t}\n\terr = tmpl.Execute(\u0026buf, obj)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error when executing template\")\n\t}\n\treturn buf.Bytes(), nil\n}","line":{"from":26,"to":38}} {"id":100001521,"name":"ID","signature":"func (u *EntryMap) ID(name string) *int64","file":"cmd/kubeadm/app/util/users/users_linux.go","code":"// ID returns the ID for an entry based on the entry name.\n// In case of a user entry it returns the user UID.\n// In case of a group entry it returns the group GID.\n// It returns nil if no such entry exists.\nfunc (u *EntryMap) ID(name string) *int64 {\n\tentry, ok := u.entries[name]\n\tif !ok {\n\t\treturn nil\n\t}\n\tid := entry.id\n\treturn \u0026id\n}","line":{"from":109,"to":120}} {"id":100001522,"name":"String","signature":"func (u *EntryMap) String() string","file":"cmd/kubeadm/app/util/users/users_linux.go","code":"// String converts an EntryMap object to a readable string.\nfunc (u *EntryMap) String() string {\n\tlines := make([]string, 0, len(u.entries))\n\tfor k, e := range u.entries {\n\t\tlines = append(lines, fmt.Sprintf(\"%s{%d,%d};\", k, e.id, e.gid))\n\t}\n\tsort.Strings(lines)\n\treturn strings.Join(lines, \"\")\n}","line":{"from":122,"to":130}} {"id":100001523,"name":"AddUsersAndGroups","signature":"func AddUsersAndGroups() (*UsersAndGroups, error)","file":"cmd/kubeadm/app/util/users/users_linux.go","code":"// Is a public wrapper around addUsersAndGroupsImpl with default system file paths.\nfunc AddUsersAndGroups() (*UsersAndGroups, error) {\n\treturn addUsersAndGroupsImpl(fileEtcLoginDefs, fileEtcPasswd, fileEtcGroup)\n}","line":{"from":132,"to":135}} {"id":100001524,"name":"addUsersAndGroupsImpl","signature":"func addUsersAndGroupsImpl(pathLoginDef, pathUsers, pathGroups string) (*UsersAndGroups, error)","file":"cmd/kubeadm/app/util/users/users_linux.go","code":"// addUsersAndGroupsImpl adds the managed users and groups to the files specified\n// by pathUsers and pathGroups. It uses the file specified with pathLoginDef to\n// determine limits for UID and GID. If managed users and groups exist in these files\n// validation is performed on them. The function returns a pointer to a Users object\n// that can be used to return UID and GID of managed users.\nfunc addUsersAndGroupsImpl(pathLoginDef, pathUsers, pathGroups string) (*UsersAndGroups, error) {\n\tklog.V(1).Info(\"Adding managed users and groups\")\n\tklog.V(klogLevel).Infof(\"Parsing %q\", pathLoginDef)\n\n\t// Read and parse /etc/login.def. Some distributions might be missing this file, which makes\n\t// them non-standard. If an error occurs fallback to defaults by passing an empty string\n\t// to parseLoginDefs().\n\tvar loginDef string\n\tf, close, err := openFileWithLock(pathLoginDef)\n\tif err != nil {\n\t\tklog.V(1).Infof(\"Could not open %q, using default system limits: %v\", pathLoginDef, err)\n\t} else {\n\t\tloginDef, err = readFile(f)\n\t\tif err != nil {\n\t\t\tklog.V(1).Infof(\"Could not read %q, using default system limits: %v\", pathLoginDef, err)\n\t\t}\n\t\tclose()\n\t}\n\tlimits, err := parseLoginDefs(loginDef)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tklog.V(klogLevel).Infof(\"Using system UID/GID limits: %+v\", limits)\n\tklog.V(klogLevel).Infof(\"Parsing %q and %q\", pathUsers, pathGroups)\n\n\t// Open /etc/passwd and /etc/group with locks.\n\tfUsers, close, err := openFileWithLock(pathUsers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer close()\n\tfGroups, close, err := openFileWithLock(pathGroups)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer close()\n\n\t// Read the files.\n\tfileUsers, err := readFile(fUsers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfileGroups, err := readFile(fGroups)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Parse the files.\n\tusers, err := parseEntries(fileUsers, totalFieldsUser)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"could not parse %q\", pathUsers)\n\t}\n\tgroups, err := parseEntries(fileGroups, totalFieldsGroup)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"could not parse %q\", pathGroups)\n\t}\n\n\tklog.V(klogLevel).Info(\"Validating existing users and groups\")\n\n\t// Validate for existing tracked entries based on limits.\n\tusersToCreate, groupsToCreate, err := validateEntries(users, groups, limits)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error validating existing users and groups\")\n\t}\n\n\t// Allocate and assign IDs to users / groups.\n\tallocUIDs, err := allocateIDs(users, limits.minUID, limits.maxUID, len(usersToCreate))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tallocGIDs, err := allocateIDs(groups, limits.minGID, limits.maxGID, len(groupsToCreate))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := assignUserAndGroupIDs(groups, usersToCreate, groupsToCreate, allocUIDs, allocGIDs); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(usersToCreate) \u003e 0 {\n\t\tklog.V(klogLevel).Infof(\"Adding users: %s\", entriesToString(usersToCreate))\n\t}\n\tif len(groupsToCreate) \u003e 0 {\n\t\tklog.V(klogLevel).Infof(\"Adding groups: %s\", entriesToString(groupsToCreate))\n\t}\n\n\t// Add users and groups.\n\tfileUsers = addEntries(fileUsers, usersToCreate, createUser)\n\tfileGroups = addEntries(fileGroups, groupsToCreate, createGroup)\n\n\t// Write the files.\n\tklog.V(klogLevel).Infof(\"Writing %q and %q\", pathUsers, pathGroups)\n\tif err := writeFile(fUsers, fileUsers); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := writeFile(fGroups, fileGroups); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Prepare the maps of users and groups.\n\tusersConcat := append(users, usersToCreate...)\n\tmapUsers, err := entriesToEntryMap(usersConcat, usersToCreateSpec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgroupsConcat := append(groups, groupsToCreate...)\n\tmapGroups, err := entriesToEntryMap(groupsConcat, groupsToCreateSpec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026UsersAndGroups{Users: mapUsers, Groups: mapGroups}, nil\n}","line":{"from":137,"to":253}} {"id":100001525,"name":"RemoveUsersAndGroups","signature":"func RemoveUsersAndGroups() error","file":"cmd/kubeadm/app/util/users/users_linux.go","code":"// RemoveUsersAndGroups is a public wrapper around removeUsersAndGroupsImpl with\n// default system file paths.\nfunc RemoveUsersAndGroups() error {\n\treturn removeUsersAndGroupsImpl(fileEtcPasswd, fileEtcGroup)\n}","line":{"from":255,"to":259}} {"id":100001526,"name":"removeUsersAndGroupsImpl","signature":"func removeUsersAndGroupsImpl(pathUsers, pathGroups string) error","file":"cmd/kubeadm/app/util/users/users_linux.go","code":"// removeUsersAndGroupsImpl removes the managed users and groups from the files specified\n// by pathUsers and pathGroups.\nfunc removeUsersAndGroupsImpl(pathUsers, pathGroups string) error {\n\tklog.V(1).Info(\"Removing managed users and groups\")\n\tklog.V(klogLevel).Infof(\"Opening %q and %q\", pathUsers, pathGroups)\n\n\t// Open /etc/passwd and /etc/group.\n\tfUsers, close, err := openFileWithLock(pathUsers)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer close()\n\tfGroups, close, err := openFileWithLock(pathGroups)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer close()\n\n\t// Read the files.\n\tfileUsers, err := readFile(fUsers)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfileGroups, err := readFile(fGroups)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tklog.V(klogLevel).Infof(\"Removing users: %s\", entriesToString(usersToCreateSpec))\n\tklog.V(klogLevel).Infof(\"Removing groups: %s\", entriesToString(groupsToCreateSpec))\n\n\t// Delete users / groups.\n\tfileUsers, _ = removeEntries(fileUsers, usersToCreateSpec)\n\tfileGroups, _ = removeEntries(fileGroups, groupsToCreateSpec)\n\n\tklog.V(klogLevel).Infof(\"Writing %q and %q\", pathUsers, pathGroups)\n\n\t// Write the files.\n\tif err := writeFile(fUsers, fileUsers); err != nil {\n\t\treturn err\n\t}\n\tif err := writeFile(fGroups, fileGroups); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":261,"to":307}} {"id":100001527,"name":"parseLoginDefs","signature":"func parseLoginDefs(file string) (*limits, error)","file":"cmd/kubeadm/app/util/users/users_linux.go","code":"// parseLoginDefs can be used to parse an /etc/login.defs file and obtain system ranges for UID and GID.\n// Passing an empty string will return the defaults. The defaults are 100-999 for both UID and GID.\nfunc parseLoginDefs(file string) (*limits, error) {\n\tl := *defaultLimits\n\tif len(file) == 0 {\n\t\treturn \u0026l, nil\n\t}\n\tvar mapping = map[string]*int64{\n\t\t\"SYS_UID_MIN\": \u0026l.minUID,\n\t\t\"SYS_UID_MAX\": \u0026l.maxUID,\n\t\t\"SYS_GID_MIN\": \u0026l.minGID,\n\t\t\"SYS_GID_MAX\": \u0026l.maxGID,\n\t}\n\tlines := strings.Split(file, \"\\n\")\n\tfor i, line := range lines {\n\t\tfor k, v := range mapping {\n\t\t\t// A line must start with one of the definitions\n\t\t\tif !strings.HasPrefix(line, k) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tline = strings.TrimPrefix(line, k)\n\t\t\tline = strings.TrimSpace(line)\n\t\t\tval, err := strconv.ParseInt(line, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrapf(err, \"could not parse value for %s at line %d\", k, i)\n\t\t\t}\n\t\t\t*v = val\n\t\t}\n\t}\n\treturn \u0026l, nil\n}","line":{"from":309,"to":339}} {"id":100001528,"name":"parseEntries","signature":"func parseEntries(file string, totalFields int) ([]*entry, error)","file":"cmd/kubeadm/app/util/users/users_linux.go","code":"// parseEntries can be used to parse an /etc/passwd or /etc/group file as their format is similar.\n// It returns a slice of entries obtained from the file.\n// https://www.cyberciti.biz/faq/understanding-etcpasswd-file-format/\n// https://www.cyberciti.biz/faq/understanding-etcgroup-file/\nfunc parseEntries(file string, totalFields int) ([]*entry, error) {\n\tif totalFields != totalFieldsUser \u0026\u0026 totalFields != totalFieldsGroup {\n\t\treturn nil, errors.Errorf(\"unsupported total fields for entry parsing: %d\", totalFields)\n\t}\n\tlines := strings.Split(file, \"\\n\")\n\tentries := []*entry{}\n\tfor i, line := range lines {\n\t\tline = strings.TrimSpace(line)\n\t\tif len(line) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tfields := strings.Split(line, \":\")\n\t\tif len(fields) != totalFields {\n\t\t\treturn nil, errors.Errorf(\"entry must have %d fields separated by ':', \"+\n\t\t\t\t\"got %d at line %d: %s\", totalFields, len(fields), i, line)\n\t\t}\n\t\tid, err := strconv.ParseInt(fields[2], 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"error parsing id at line %d\", i)\n\t\t}\n\t\tentry := \u0026entry{name: fields[0], id: id}\n\t\tif totalFields == totalFieldsGroup {\n\t\t\tentry.userNames = strings.Split(fields[3], \",\")\n\t\t} else {\n\t\t\tgid, err := strconv.ParseInt(fields[3], 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrapf(err, \"error parsing GID at line %d\", i)\n\t\t\t}\n\t\t\tentry.gid = gid\n\t\t\tentry.shell = fields[6]\n\t\t}\n\t\tentries = append(entries, entry)\n\t}\n\treturn entries, nil\n}","line":{"from":341,"to":379}} {"id":100001529,"name":"validateEntries","signature":"func validateEntries(users, groups []*entry, limits *limits) ([]*entry, []*entry, error)","file":"cmd/kubeadm/app/util/users/users_linux.go","code":"// validateEntries takes user and group entries and validates if these entries are valid based on limits,\n// mapping between users and groups and specs. Returns slices of missing user and group entries that must be created.\n// Returns an error if existing users and groups do not match requirements.\nfunc validateEntries(users, groups []*entry, limits *limits) ([]*entry, []*entry, error) {\n\tu := []*entry{}\n\tg := []*entry{}\n\t// Validate users\n\tfor _, uc := range usersToCreateSpec {\n\t\tfor _, user := range users {\n\t\t\tif uc.name != user.name {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Found existing user\n\t\t\tif user.id \u003c limits.minUID || user.id \u003e limits.maxUID {\n\t\t\t\treturn nil, nil, errors.Errorf(\"UID %d for user %q is outside the system UID range: %d - %d\",\n\t\t\t\t\tuser.id, user.name, limits.minUID, limits.maxUID)\n\t\t\t}\n\t\t\tif user.shell != noshell {\n\t\t\t\treturn nil, nil, errors.Errorf(\"user %q has unexpected shell %q; expected %q\",\n\t\t\t\t\tuser.name, user.shell, noshell)\n\t\t\t}\n\t\t\tfor _, g := range groups {\n\t\t\t\tif g.id != user.gid {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// Found matching group GID for user GID\n\t\t\t\tif g.name != uc.name {\n\t\t\t\t\treturn nil, nil, errors.Errorf(\"user %q has GID %d but the group with that GID is not named %q\",\n\t\t\t\t\t\tuc.name, g.id, uc.name)\n\t\t\t\t}\n\t\t\t\tgoto skipUser // Valid group GID and name; skip\n\t\t\t}\n\t\t\treturn nil, nil, errors.Errorf(\"could not find group with GID %d for user %q\", user.gid, user.name)\n\t\t}\n\t\tu = append(u, uc)\n\tskipUser:\n\t}\n\t// validate groups\n\tfor _, gc := range groupsToCreateSpec {\n\t\tfor _, group := range groups {\n\t\t\tif gc.name != group.name {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif group.id \u003c limits.minGID || group.id \u003e limits.maxGID {\n\t\t\t\treturn nil, nil, errors.Errorf(\"GID %d for user %q is outside the system UID range: %d - %d\",\n\t\t\t\t\tgroup.id, group.name, limits.minGID, limits.maxGID)\n\t\t\t}\n\t\t\tu1 := strings.Join(gc.userNames, \",\")\n\t\t\tu2 := strings.Join(group.userNames, \",\")\n\t\t\tif u1 != u2 {\n\t\t\t\treturn nil, nil, errors.Errorf(\"expected users %q for group %q; got %q\",\n\t\t\t\t\tu1, gc.name, u2)\n\t\t\t}\n\t\t\tgoto skipGroup // group has valid users; skip\n\t\t}\n\t\tg = append(g, gc)\n\tskipGroup:\n\t}\n\treturn u, g, nil\n}","line":{"from":381,"to":440}} {"id":100001530,"name":"allocateIDs","signature":"func allocateIDs(entries []*entry, min, max int64, total int) ([]int64, error)","file":"cmd/kubeadm/app/util/users/users_linux.go","code":"// allocateIDs takes a list of entries and based on minimum and maximum ID allocates a \"total\" of IDs.\nfunc allocateIDs(entries []*entry, min, max int64, total int) ([]int64, error) {\n\tif total == 0 {\n\t\treturn []int64{}, nil\n\t}\n\tids := make([]int64, 0, total)\n\tfor i := min; i \u003c max+1; i++ {\n\t\ti64 := int64(i)\n\t\tfor _, e := range entries {\n\t\t\tif i64 == e.id {\n\t\t\t\tgoto continueLoop\n\t\t\t}\n\t\t}\n\t\tids = append(ids, i64)\n\t\tif len(ids) == total {\n\t\t\treturn ids, nil\n\t\t}\n\tcontinueLoop:\n\t}\n\treturn nil, errors.Errorf(\"could not allocate %d IDs based on existing entries in the range: %d - %d\",\n\t\ttotal, min, max)\n}","line":{"from":442,"to":463}} {"id":100001531,"name":"addEntries","signature":"func addEntries(file string, entries []*entry, createEntry func(*entry) string) string","file":"cmd/kubeadm/app/util/users/users_linux.go","code":"// addEntries takes /etc/passwd or /etc/group file content and appends entries to it based\n// on a createEntry function. Returns the updated contents of the file.\nfunc addEntries(file string, entries []*entry, createEntry func(*entry) string) string {\n\tout := file\n\tnewLines := make([]string, 0, len(entries))\n\tfor _, e := range entries {\n\t\tnewLines = append(newLines, createEntry(e))\n\t}\n\tnewLinesStr := \"\"\n\tif len(newLines) \u003e 0 {\n\t\tif !strings.HasSuffix(out, \"\\n\") { // Append a new line if its missing.\n\t\t\tnewLinesStr = \"\\n\"\n\t\t}\n\t\tnewLinesStr += strings.Join(newLines, \"\\n\") + \"\\n\"\n\t}\n\treturn out + newLinesStr\n}","line":{"from":465,"to":481}} {"id":100001532,"name":"removeEntries","signature":"func removeEntries(file string, entries []*entry) (string, int)","file":"cmd/kubeadm/app/util/users/users_linux.go","code":"// removeEntries takes /etc/passwd or /etc/group file content and deletes entries from them\n// by name matching. Returns the updated contents of the file and the number of entries removed.\nfunc removeEntries(file string, entries []*entry) (string, int) {\n\tlines := strings.Split(file, \"\\n\")\n\ttotal := len(lines) - len(entries)\n\tif total \u003c 0 {\n\t\ttotal = 0\n\t}\n\tnewLines := make([]string, 0, total)\n\tremoved := 0\n\tfor _, line := range lines {\n\t\tfor _, entry := range entries {\n\t\t\tif strings.HasPrefix(line, entry.name+\":\") {\n\t\t\t\tremoved++\n\t\t\t\tgoto continueLoop\n\t\t\t}\n\t\t}\n\t\tnewLines = append(newLines, line)\n\tcontinueLoop:\n\t}\n\treturn strings.Join(newLines, \"\\n\"), removed\n}","line":{"from":483,"to":504}} {"id":100001533,"name":"assignUserAndGroupIDs","signature":"func assignUserAndGroupIDs(groups, usersToCreate, groupsToCreate []*entry, uids, gids []int64) error","file":"cmd/kubeadm/app/util/users/users_linux.go","code":"// assignUserAndGroupIDs takes the list of existing groups, the users and groups to be created,\n// and assigns UIDs and GIDs to the users and groups to be created based on a list of provided UIDs and GIDs.\n// Returns an error if not enough UIDs or GIDs are passed. It does not perform any other validation.\nfunc assignUserAndGroupIDs(groups, usersToCreate, groupsToCreate []*entry, uids, gids []int64) error {\n\tif len(gids) \u003c len(groupsToCreate) {\n\t\treturn errors.Errorf(\"not enough GIDs to assign to groups: have %d, want %d\", len(gids), len(groupsToCreate))\n\t}\n\tif len(uids) \u003c len(usersToCreate) {\n\t\treturn errors.Errorf(\"not enough UIDs to assign to users: have %d, want %d\", len(uids), len(usersToCreate))\n\t}\n\tfor i := range groupsToCreate {\n\t\tgroupsToCreate[i].id = gids[i]\n\t}\n\t// Concat the list of old and new groups to find a matching GID.\n\tgroupsConcat := append([]*entry{}, groups...)\n\tgroupsConcat = append(groupsConcat, groupsToCreate...)\n\tfor i := range usersToCreate {\n\t\tusersToCreate[i].id = uids[i]\n\t\tfor _, g := range groupsConcat {\n\t\t\tif usersToCreate[i].name == g.name {\n\t\t\t\tusersToCreate[i].gid = g.id\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":506,"to":532}} {"id":100001534,"name":"createGroup","signature":"func createGroup(e *entry) string","file":"cmd/kubeadm/app/util/users/users_linux.go","code":"// createGroup is a helper function to produce a group from entry.\nfunc createGroup(e *entry) string {\n\treturn fmt.Sprintf(\"%s:x:%d:%s\", e.name, e.id, strings.Join(e.userNames, \",\"))\n}","line":{"from":534,"to":537}} {"id":100001535,"name":"createUser","signature":"func createUser(e *entry) string","file":"cmd/kubeadm/app/util/users/users_linux.go","code":"// createUser is a helper function to produce a user from entry.\nfunc createUser(e *entry) string {\n\treturn fmt.Sprintf(\"%s:x:%d:%d:::/bin/false\", e.name, e.id, e.gid)\n}","line":{"from":539,"to":542}} {"id":100001536,"name":"entriesToEntryMap","signature":"func entriesToEntryMap(entries, spec []*entry) (*EntryMap, error)","file":"cmd/kubeadm/app/util/users/users_linux.go","code":"// entriesToEntryMap takes a list of entries and prepares an EntryMap object.\nfunc entriesToEntryMap(entries, spec []*entry) (*EntryMap, error) {\n\tm := map[string]*entry{}\n\tfor _, spec := range spec {\n\t\tfor _, e := range entries {\n\t\t\tif spec.name == e.name {\n\t\t\t\tentry := *e\n\t\t\t\tm[e.name] = \u0026entry\n\t\t\t\tgoto continueLoop\n\t\t\t}\n\t\t}\n\t\treturn nil, errors.Errorf(\"could not find entry %q in the list\", spec.name)\n\tcontinueLoop:\n\t}\n\treturn \u0026EntryMap{entries: m}, nil\n}","line":{"from":544,"to":559}} {"id":100001537,"name":"entriesToString","signature":"func entriesToString(entries []*entry) string","file":"cmd/kubeadm/app/util/users/users_linux.go","code":"// entriesToString is a utility to convert a list of entries to string.\nfunc entriesToString(entries []*entry) string {\n\tlines := make([]string, 0, len(entries))\n\tfor _, e := range entries {\n\t\tlines = append(lines, e.name)\n\t}\n\tsort.Strings(lines)\n\treturn strings.Join(lines, \",\")\n}","line":{"from":561,"to":569}} {"id":100001538,"name":"openFileWithLock","signature":"func openFileWithLock(path string) (f *os.File, close func(), err error)","file":"cmd/kubeadm/app/util/users/users_linux.go","code":"// openFileWithLock opens the file at path by acquiring an exclive write lock.\n// The returned close() function should be called to release the lock and close the file.\n// If a lock cannot be obtained the function fails after a period of time.\nfunc openFileWithLock(path string) (f *os.File, close func(), err error) {\n\tf, err = os.OpenFile(path, os.O_RDWR, os.ModePerm)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdeadline := time.Now().Add(time.Second * 5)\n\tfor {\n\t\t// If another process is holding a write lock, this call will exit\n\t\t// with an error. F_SETLK is used instead of F_SETLKW to avoid\n\t\t// the case where a runaway process grabs the exclusive lock and\n\t\t// blocks this call indefinitely.\n\t\t// https://man7.org/linux/man-pages/man2/fcntl.2.html\n\t\tlock := syscall.Flock_t{Type: syscall.F_WRLCK}\n\t\tif err = syscall.FcntlFlock(f.Fd(), syscall.F_SETLK, \u0026lock); err == nil {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(200 * time.Millisecond)\n\t\tif time.Now().After(deadline) {\n\t\t\terr = errors.Wrapf(err, \"timeout attempting to obtain lock on file %q\", path)\n\t\t\tbreak\n\t\t}\n\t}\n\tif err != nil {\n\t\tf.Close()\n\t\treturn nil, nil, err\n\t}\n\tclose = func() {\n\t\t// This function should be called once operations with the file are finished.\n\t\t// It unlocks the file and closes it.\n\t\tunlock := syscall.Flock_t{Type: syscall.F_UNLCK}\n\t\tsyscall.FcntlFlock(f.Fd(), syscall.F_SETLK, \u0026unlock)\n\t\tf.Close()\n\t}\n\treturn f, close, nil\n}","line":{"from":571,"to":608}} {"id":100001539,"name":"readFile","signature":"func readFile(f *os.File) (string, error)","file":"cmd/kubeadm/app/util/users/users_linux.go","code":"// readFile reads a File into a string.\nfunc readFile(f *os.File) (string, error) {\n\tbuf := bytes.NewBuffer(nil)\n\tif _, err := f.Seek(0, io.SeekStart); err != nil {\n\t\treturn \"\", err\n\t}\n\tif _, err := io.Copy(buf, f); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn buf.String(), nil\n}","line":{"from":610,"to":620}} {"id":100001540,"name":"writeFile","signature":"func writeFile(f *os.File, str string) error","file":"cmd/kubeadm/app/util/users/users_linux.go","code":"// writeFile writes a string to a File.\nfunc writeFile(f *os.File, str string) error {\n\tif _, err := f.Seek(0, io.SeekStart); err != nil {\n\t\treturn err\n\t}\n\tif _, err := f.Write([]byte(str)); err != nil {\n\t\treturn err\n\t}\n\tif err := f.Truncate(int64(len(str))); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":622,"to":634}} {"id":100001541,"name":"UpdatePathOwnerAndPermissions","signature":"func UpdatePathOwnerAndPermissions(path string, uid, gid int64, perms uint32) error","file":"cmd/kubeadm/app/util/users/users_linux.go","code":"// UpdatePathOwnerAndPermissions updates the owner and permissions of the given path.\n// If the path is a directory it is not recursively updated.\nfunc UpdatePathOwnerAndPermissions(path string, uid, gid int64, perms uint32) error {\n\tif err := os.Chown(path, int(uid), int(gid)); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to update owner of %q to uid: %d and gid: %d\", path, uid, gid)\n\t}\n\tfm := os.FileMode(perms)\n\tif err := os.Chmod(path, fm); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to update permissions of %q to %s\", path, fm.String())\n\t}\n\treturn nil\n}","line":{"from":636,"to":647}} {"id":100001542,"name":"UpdatePathOwner","signature":"func UpdatePathOwner(dirPath string, uid, gid int64) error","file":"cmd/kubeadm/app/util/users/users_linux.go","code":"// UpdatePathOwner recursively updates the owners of a directory.\n// It is equivalent to calling `chown -R uid:gid /path/to/dir`.\nfunc UpdatePathOwner(dirPath string, uid, gid int64) error {\n\terr := filepath.WalkDir(dirPath, func(path string, d os.DirEntry, err error) error {\n\t\tif err := os.Chown(path, int(uid), int(gid)); err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to update owner of %q to uid: %d and gid: %d\", path, uid, gid)\n\t\t}\n\t\treturn nil\n\t})\n\treturn err\n}","line":{"from":649,"to":659}} {"id":100001543,"name":"ID","signature":"func (*EntryMap) ID(string) *int64","file":"cmd/kubeadm/app/util/users/users_other.go","code":"// ID is a NO-OP on non-Linux.\nfunc (*EntryMap) ID(string) *int64 {\n\treturn nil\n}","line":{"from":28,"to":31}} {"id":100001544,"name":"String","signature":"func (*EntryMap) String() string","file":"cmd/kubeadm/app/util/users/users_other.go","code":"// String is NO-OP on non-Linux.\nfunc (*EntryMap) String() string {\n\treturn \"\"\n}","line":{"from":33,"to":36}} {"id":100001545,"name":"AddUsersAndGroups","signature":"func AddUsersAndGroups() (*UsersAndGroups, error)","file":"cmd/kubeadm/app/util/users/users_other.go","code":"// AddUsersAndGroups is a NO-OP on non-Linux.\nfunc AddUsersAndGroups() (*UsersAndGroups, error) {\n\treturn nil, nil\n}","line":{"from":38,"to":41}} {"id":100001546,"name":"RemoveUsersAndGroups","signature":"func RemoveUsersAndGroups() error","file":"cmd/kubeadm/app/util/users/users_other.go","code":"// RemoveUsersAndGroups is a NO-OP on non-Linux.\nfunc RemoveUsersAndGroups() error {\n\treturn nil\n}","line":{"from":43,"to":46}} {"id":100001547,"name":"UpdatePathOwnerAndPermissions","signature":"func UpdatePathOwnerAndPermissions(path string, uid, gid int64, perms uint32) error","file":"cmd/kubeadm/app/util/users/users_other.go","code":"// UpdatePathOwnerAndPermissions is a NO-OP on non-Linux.\nfunc UpdatePathOwnerAndPermissions(path string, uid, gid int64, perms uint32) error {\n\treturn nil\n}","line":{"from":48,"to":51}} {"id":100001548,"name":"UpdatePathOwner","signature":"func UpdatePathOwner(dirPath string, uid, gid int64) error","file":"cmd/kubeadm/app/util/users/users_other.go","code":"// UpdatePathOwner is a NO-OP on non-Linux.\nfunc UpdatePathOwner(dirPath string, uid, gid int64) error {\n\treturn nil\n}","line":{"from":53,"to":56}} {"id":100001549,"name":"KubernetesReleaseVersion","signature":"func KubernetesReleaseVersion(version string) (string, error)","file":"cmd/kubeadm/app/util/version.go","code":"// KubernetesReleaseVersion is helper function that can fetch\n// available version information from release servers based on\n// label names, like \"stable\" or \"latest\".\n//\n// If argument is already semantic version string, it\n// will return same string.\n//\n// In case of labels, it tries to fetch from release\n// servers and then return actual semantic version.\n//\n// Available names on release servers:\n//\n//\tstable (latest stable release)\n//\tstable-1 (latest stable release in 1.x)\n//\tstable-1.0 (and similarly 1.1, 1.2, 1.3, ...)\n//\tlatest (latest release, including alpha/beta)\n//\tlatest-1 (latest release in 1.x, including alpha/beta)\n//\tlatest-1.0 (and similarly 1.1, 1.2, 1.3, ...)\nfunc KubernetesReleaseVersion(version string) (string, error) {\n\treturn kubernetesReleaseVersion(version, fetchFromURL)\n}","line":{"from":49,"to":69}} {"id":100001550,"name":"kubernetesReleaseVersion","signature":"func kubernetesReleaseVersion(version string, fetcher func(string, time.Duration) (string, error)) (string, error)","file":"cmd/kubeadm/app/util/version.go","code":"// kubernetesReleaseVersion is a helper function to fetch\n// available version information. Used for testing to eliminate\n// the need for internet calls.\nfunc kubernetesReleaseVersion(version string, fetcher func(string, time.Duration) (string, error)) (string, error) {\n\tver := normalizedBuildVersion(version)\n\tif len(ver) != 0 {\n\t\treturn ver, nil\n\t}\n\n\tbucketURL, versionLabel, err := splitVersion(version)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// revalidate, if exact build from e.g. CI bucket requested.\n\tver = normalizedBuildVersion(versionLabel)\n\tif len(ver) != 0 {\n\t\treturn ver, nil\n\t}\n\n\t// kubeReleaseLabelRegex matches labels such as: latest, latest-1, latest-1.10\n\tif kubeReleaseLabelRegex.MatchString(versionLabel) {\n\t\t// Try to obtain a client version.\n\t\t// pkgversion.Get().String() should always return a correct version added by the golang\n\t\t// linker and the build system. The version can still be missing when doing unit tests\n\t\t// on individual packages.\n\t\tclientVersion, clientVersionErr := kubeadmVersion(pkgversion.Get().String())\n\t\t// Fetch version from the internet.\n\t\turl := fmt.Sprintf(\"%s/%s.txt\", bucketURL, versionLabel)\n\t\tbody, err := fetcher(url, getReleaseVersionTimeout)\n\t\tif err != nil {\n\t\t\tif clientVersionErr == nil {\n\t\t\t\t// Handle air-gapped environments by falling back to the client version.\n\t\t\t\tklog.Warningf(\"could not fetch a Kubernetes version from the internet: %v\", err)\n\t\t\t\tklog.Warningf(\"falling back to the local client version: %s\", clientVersion)\n\t\t\t\treturn kubernetesReleaseVersion(clientVersion, fetcher)\n\t\t\t}\n\t\t}\n\n\t\tif clientVersionErr != nil {\n\t\t\tif err != nil {\n\t\t\t\tklog.Warningf(\"could not obtain neither client nor remote version; fall back to: %s\", constants.CurrentKubernetesVersion)\n\t\t\t\treturn kubernetesReleaseVersion(constants.CurrentKubernetesVersion.String(), fetcher)\n\t\t\t}\n\n\t\t\tklog.Warningf(\"could not obtain client version; using remote version: %s\", body)\n\t\t\treturn kubernetesReleaseVersion(body, fetcher)\n\t\t}\n\n\t\t// both the client and the remote version are obtained; validate them and pick a stable version\n\t\tbody, err = validateStableVersion(body, clientVersion)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\t// Re-validate received version and return.\n\t\treturn kubernetesReleaseVersion(body, fetcher)\n\t}\n\treturn \"\", errors.Errorf(\"version %q doesn't match patterns for neither semantic version nor labels (stable, latest, ...)\", version)\n}","line":{"from":71,"to":129}} {"id":100001551,"name":"KubernetesVersionToImageTag","signature":"func KubernetesVersionToImageTag(version string) string","file":"cmd/kubeadm/app/util/version.go","code":"// KubernetesVersionToImageTag is helper function that replaces all\n// non-allowed symbols in tag strings with underscores.\n// Image tag can only contain lowercase and uppercase letters, digits,\n// underscores, periods and dashes.\n// Current usage is for CI images where all of symbols except '+' are valid,\n// but function is for generic usage where input can't be always pre-validated.\nfunc KubernetesVersionToImageTag(version string) string {\n\tallowed := regexp.MustCompile(`[^-\\w.]`)\n\treturn allowed.ReplaceAllString(version, \"_\")\n}","line":{"from":131,"to":140}} {"id":100001552,"name":"KubernetesIsCIVersion","signature":"func KubernetesIsCIVersion(version string) bool","file":"cmd/kubeadm/app/util/version.go","code":"// KubernetesIsCIVersion checks if user requested CI version\nfunc KubernetesIsCIVersion(version string) bool {\n\tsubs := kubeBucketPrefixes.FindAllStringSubmatch(version, 1)\n\tif len(subs) == 1 \u0026\u0026 len(subs[0]) == 4 \u0026\u0026 strings.HasPrefix(subs[0][2], \"ci\") {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":142,"to":149}} {"id":100001553,"name":"normalizedBuildVersion","signature":"func normalizedBuildVersion(version string) string","file":"cmd/kubeadm/app/util/version.go","code":"// Internal helper: returns normalized build version (with \"v\" prefix if needed)\n// If input doesn't match known version pattern, returns empty string.\nfunc normalizedBuildVersion(version string) string {\n\tif kubeReleaseRegex.MatchString(version) {\n\t\tif strings.HasPrefix(version, \"v\") {\n\t\t\treturn version\n\t\t}\n\t\treturn \"v\" + version\n\t}\n\treturn \"\"\n}","line":{"from":151,"to":161}} {"id":100001554,"name":"splitVersion","signature":"func splitVersion(version string) (string, string, error)","file":"cmd/kubeadm/app/util/version.go","code":"// Internal helper: split version parts,\n// Return base URL and cleaned-up version\nfunc splitVersion(version string) (string, string, error) {\n\tvar bucketURL, urlSuffix string\n\tsubs := kubeBucketPrefixes.FindAllStringSubmatch(version, 1)\n\tif len(subs) != 1 || len(subs[0]) != 4 {\n\t\treturn \"\", \"\", errors.Errorf(\"invalid version %q\", version)\n\t}\n\n\tswitch {\n\tcase strings.HasPrefix(subs[0][2], \"ci\"):\n\t\t// Just use whichever the user specified\n\t\turlSuffix = subs[0][2]\n\t\tbucketURL = kubeCIBucketURL\n\tdefault:\n\t\turlSuffix = \"release\"\n\t\tbucketURL = kubeReleaseBucketURL\n\t}\n\turl := fmt.Sprintf(\"%s/%s\", bucketURL, urlSuffix)\n\treturn url, subs[0][3], nil\n}","line":{"from":163,"to":183}} {"id":100001555,"name":"fetchFromURL","signature":"func fetchFromURL(url string, timeout time.Duration) (string, error)","file":"cmd/kubeadm/app/util/version.go","code":"// Internal helper: return content of URL\nfunc fetchFromURL(url string, timeout time.Duration) (string, error) {\n\tklog.V(2).Infof(\"fetching Kubernetes version from URL: %s\", url)\n\tclient := \u0026http.Client{Timeout: timeout, Transport: netutil.SetOldTransportDefaults(\u0026http.Transport{})}\n\tresp, err := client.Get(url)\n\tif err != nil {\n\t\treturn \"\", errors.Errorf(\"unable to get URL %q: %s\", url, err.Error())\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", errors.Errorf(\"unable to read content of URL %q: %s\", url, err.Error())\n\t}\n\tbodyString := strings.TrimSpace(string(body))\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tmsg := fmt.Sprintf(\"unable to fetch file. URL: %q, status: %v\", url, resp.Status)\n\t\treturn bodyString, errors.New(msg)\n\t}\n\treturn bodyString, nil\n}","line":{"from":185,"to":205}} {"id":100001556,"name":"kubeadmVersion","signature":"func kubeadmVersion(info string) (string, error)","file":"cmd/kubeadm/app/util/version.go","code":"// kubeadmVersion returns the version of the client without metadata.\nfunc kubeadmVersion(info string) (string, error) {\n\tv, err := versionutil.ParseSemantic(info)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"kubeadm version error\")\n\t}\n\t// There is no utility in versionutil to get the version without the metadata,\n\t// so this needs some manual formatting.\n\t// Discard offsets after a release label and keep the labels down to e.g. `alpha.0` instead of\n\t// including the offset e.g. `alpha.0.206`. This is done to comply with GCR image tags.\n\tpre := v.PreRelease()\n\tpatch := v.Patch()\n\tif len(pre) \u003e 0 {\n\t\tif patch \u003e 0 {\n\t\t\t// If the patch version is more than zero, decrement it and remove the label.\n\t\t\t// this is done to comply with the latest stable patch release.\n\t\t\tpatch = patch - 1\n\t\t\tpre = \"\"\n\t\t} else {\n\t\t\tsplit := strings.Split(pre, \".\")\n\t\t\tif len(split) \u003e 2 {\n\t\t\t\tpre = split[0] + \".\" + split[1] // Exclude the third element\n\t\t\t} else if len(split) \u003c 2 {\n\t\t\t\tpre = split[0] + \".0\" // Append .0 to a partial label\n\t\t\t}\n\t\t\tpre = \"-\" + pre\n\t\t}\n\t}\n\tvStr := fmt.Sprintf(\"v%d.%d.%d%s\", v.Major(), v.Minor(), patch, pre)\n\treturn vStr, nil\n}","line":{"from":207,"to":237}} {"id":100001557,"name":"validateStableVersion","signature":"func validateStableVersion(remoteVersion, clientVersion string) (string, error)","file":"cmd/kubeadm/app/util/version.go","code":"// Validate if the remote version is one Minor release newer than the client version.\n// This is done to conform with \"stable-X\" and only allow remote versions from\n// the same Patch level release.\nfunc validateStableVersion(remoteVersion, clientVersion string) (string, error) {\n\tverRemote, err := versionutil.ParseGeneric(remoteVersion)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"remote version error\")\n\t}\n\tverClient, err := versionutil.ParseGeneric(clientVersion)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"client version error\")\n\t}\n\t// If the remote Major version is bigger or if the Major versions are the same,\n\t// but the remote Minor is bigger use the client version release. This handles Major bumps too.\n\tif verClient.Major() \u003c verRemote.Major() ||\n\t\t(verClient.Major() == verRemote.Major()) \u0026\u0026 verClient.Minor() \u003c verRemote.Minor() {\n\t\testimatedRelease := fmt.Sprintf(\"stable-%d.%d\", verClient.Major(), verClient.Minor())\n\t\tklog.Infof(\"remote version is much newer: %s; falling back to: %s\", remoteVersion, estimatedRelease)\n\t\treturn estimatedRelease, nil\n\t}\n\treturn remoteVersion, nil\n}","line":{"from":239,"to":260}} {"id":100001558,"name":"main","signature":"func main()","file":"cmd/kubeadm/kubeadm.go","code":"func main() {\n\tkubeadmutil.CheckErr(app.Run())\n}","line":{"from":24,"to":26}} {"id":100001559,"name":"main","signature":"func main()","file":"cmd/kubectl-convert/kubectl-convert.go","code":"func main() {\n\tflags := pflag.NewFlagSet(\"kubectl-convert\", pflag.ExitOnError)\n\tpflag.CommandLine = flags\n\n\tkubeConfigFlags := genericclioptions.NewConfigFlags(true).WithDeprecatedPasswordFlag()\n\tkubeConfigFlags.AddFlags(flags)\n\tmatchVersionKubeConfigFlags := cmdutil.NewMatchVersionFlags(kubeConfigFlags)\n\n\tf := cmdutil.NewFactory(matchVersionKubeConfigFlags)\n\tcmd := convert.NewCmdConvert(f, genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr})\n\tmatchVersionKubeConfigFlags.AddFlags(cmd.PersistentFlags())\n\tcode := cli.Run(cmd)\n\tos.Exit(code)\n}","line":{"from":30,"to":43}} {"id":100001560,"name":"main","signature":"func main()","file":"cmd/kubectl/kubectl.go","code":"func main() {\n\tcommand := cmd.NewDefaultKubectlCommand()\n\tif err := cli.RunNoErrOutput(command); err != nil {\n\t\t// Pretty-print the error and exit with an error.\n\t\tutil.CheckErr(err)\n\t}\n}","line":{"from":28,"to":34}} {"id":100001561,"name":"BuildAuth","signature":"func BuildAuth(nodeName types.NodeName, client clientset.Interface, config kubeletconfig.KubeletConfiguration) (server.AuthInterface, func(\u003c-chan struct{}), error)","file":"cmd/kubelet/app/auth.go","code":"// BuildAuth creates an authenticator, an authorizer, and a matching authorizer attributes getter compatible with the kubelet's needs\n// It returns AuthInterface, a run method to start internal controllers (like cert reloading) and error.\nfunc BuildAuth(nodeName types.NodeName, client clientset.Interface, config kubeletconfig.KubeletConfiguration) (server.AuthInterface, func(\u003c-chan struct{}), error) {\n\t// Get clients, if provided\n\tvar (\n\t\ttokenClient authenticationclient.AuthenticationV1Interface\n\t\tsarClient authorizationclient.AuthorizationV1Interface\n\t)\n\tif client != nil \u0026\u0026 !reflect.ValueOf(client).IsNil() {\n\t\ttokenClient = client.AuthenticationV1()\n\t\tsarClient = client.AuthorizationV1()\n\t}\n\n\tauthenticator, runAuthenticatorCAReload, err := BuildAuthn(tokenClient, config.Authentication)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tattributes := server.NewNodeAuthorizerAttributesGetter(nodeName)\n\n\tauthorizer, err := BuildAuthz(sarClient, config.Authorization)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn server.NewKubeletAuth(authenticator, attributes, authorizer), runAuthenticatorCAReload, nil\n}","line":{"from":40,"to":66}} {"id":100001562,"name":"BuildAuthn","signature":"func BuildAuthn(client authenticationclient.AuthenticationV1Interface, authn kubeletconfig.KubeletAuthentication) (authenticator.Request, func(\u003c-chan struct{}), error)","file":"cmd/kubelet/app/auth.go","code":"// BuildAuthn creates an authenticator compatible with the kubelet's needs\nfunc BuildAuthn(client authenticationclient.AuthenticationV1Interface, authn kubeletconfig.KubeletAuthentication) (authenticator.Request, func(\u003c-chan struct{}), error) {\n\tvar dynamicCAContentFromFile *dynamiccertificates.DynamicFileCAContent\n\tvar err error\n\tif len(authn.X509.ClientCAFile) \u003e 0 {\n\t\tdynamicCAContentFromFile, err = dynamiccertificates.NewDynamicCAContentFromFile(\"client-ca-bundle\", authn.X509.ClientCAFile)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\tauthenticatorConfig := authenticatorfactory.DelegatingAuthenticatorConfig{\n\t\tAnonymous: authn.Anonymous.Enabled,\n\t\tCacheTTL: authn.Webhook.CacheTTL.Duration,\n\t\tClientCertificateCAContentProvider: dynamicCAContentFromFile,\n\t}\n\n\tif authn.Webhook.Enabled {\n\t\tif client == nil {\n\t\t\treturn nil, nil, errors.New(\"no client provided, cannot use webhook authentication\")\n\t\t}\n\t\tauthenticatorConfig.WebhookRetryBackoff = genericoptions.DefaultAuthWebhookRetryBackoff()\n\t\tauthenticatorConfig.TokenAccessReviewClient = client\n\t}\n\n\tauthenticator, _, err := authenticatorConfig.New()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn authenticator, func(stopCh \u003c-chan struct{}) {\n\t\t// generate a context from stopCh. This is to avoid modifying files which are relying on this method\n\t\t// TODO: See if we can pass ctx to the current method\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tgo func() {\n\t\t\tselect {\n\t\t\tcase \u003c-stopCh:\n\t\t\t\tcancel() // stopCh closed, so cancel our context\n\t\t\tcase \u003c-ctx.Done():\n\t\t\t}\n\t\t}()\n\t\tif dynamicCAContentFromFile != nil {\n\t\t\tgo dynamicCAContentFromFile.Run(ctx, 1)\n\t\t}\n\t}, err\n}","line":{"from":68,"to":113}} {"id":100001563,"name":"BuildAuthz","signature":"func BuildAuthz(client authorizationclient.AuthorizationV1Interface, authz kubeletconfig.KubeletAuthorization) (authorizer.Authorizer, error)","file":"cmd/kubelet/app/auth.go","code":"// BuildAuthz creates an authorizer compatible with the kubelet's needs\nfunc BuildAuthz(client authorizationclient.AuthorizationV1Interface, authz kubeletconfig.KubeletAuthorization) (authorizer.Authorizer, error) {\n\tswitch authz.Mode {\n\tcase kubeletconfig.KubeletAuthorizationModeAlwaysAllow:\n\t\treturn authorizerfactory.NewAlwaysAllowAuthorizer(), nil\n\n\tcase kubeletconfig.KubeletAuthorizationModeWebhook:\n\t\tif client == nil {\n\t\t\treturn nil, errors.New(\"no client provided, cannot use webhook authorization\")\n\t\t}\n\t\tauthorizerConfig := authorizerfactory.DelegatingAuthorizerConfig{\n\t\t\tSubjectAccessReviewClient: client,\n\t\t\tAllowCacheTTL: authz.Webhook.CacheAuthorizedTTL.Duration,\n\t\t\tDenyCacheTTL: authz.Webhook.CacheUnauthorizedTTL.Duration,\n\t\t\tWebhookRetryBackoff: genericoptions.DefaultAuthWebhookRetryBackoff(),\n\t\t}\n\t\treturn authorizerConfig.New()\n\n\tcase \"\":\n\t\treturn nil, fmt.Errorf(\"no authorization mode specified\")\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown authorization mode %s\", authz.Mode)\n\n\t}\n}","line":{"from":115,"to":140}} {"id":100001564,"name":"initForOS","signature":"func initForOS(service bool, priorityClass string) error","file":"cmd/kubelet/app/init_others.go","code":"func initForOS(service bool, priorityClass string) error {\n\treturn nil\n}","line":{"from":22,"to":24}} {"id":100001565,"name":"getPriorityValue","signature":"func getPriorityValue(priorityClassName string) uint32","file":"cmd/kubelet/app/init_windows.go","code":"// getPriorityValue returns the value associated with a Windows process priorityClass\n// Ref: https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/setpriority-method-in-class-win32-process\nfunc getPriorityValue(priorityClassName string) uint32 {\n\tvar priorityClassMap = map[string]uint32{\n\t\t\"IDLE_PRIORITY_CLASS\": uint32(windows.IDLE_PRIORITY_CLASS),\n\t\t\"BELOW_NORMAL_PRIORITY_CLASS\": uint32(windows.BELOW_NORMAL_PRIORITY_CLASS),\n\t\t\"NORMAL_PRIORITY_CLASS\": uint32(windows.NORMAL_PRIORITY_CLASS),\n\t\t\"ABOVE_NORMAL_PRIORITY_CLASS\": uint32(windows.ABOVE_NORMAL_PRIORITY_CLASS),\n\t\t\"HIGH_PRIORITY_CLASS\": uint32(windows.HIGH_PRIORITY_CLASS),\n\t\t\"REALTIME_PRIORITY_CLASS\": uint32(windows.REALTIME_PRIORITY_CLASS),\n\t}\n\treturn priorityClassMap[priorityClassName]\n}","line":{"from":36,"to":48}} {"id":100001566,"name":"createWindowsJobObject","signature":"func createWindowsJobObject(pc uint32) (windows.Handle, error)","file":"cmd/kubelet/app/init_windows.go","code":"// createWindowsJobObject creates a new Job Object\n// (https://docs.microsoft.com/en-us/windows/win32/procthread/job-objects),\n// and specifies the priority class for the job object to the specified value.\n// A job object is used here so that any spawned processes such as powershell or\n// wmic are created at the specified thread priority class.\n// Running kubelet with above normal / high priority can help improve\n// responsiveness on machines with high CPU utilization.\nfunc createWindowsJobObject(pc uint32) (windows.Handle, error) {\n\tjob, err := windows.CreateJobObject(nil, nil)\n\tif err != nil {\n\t\treturn windows.InvalidHandle, fmt.Errorf(\"windows.CreateJobObject failed: %w\", err)\n\t}\n\tlimitInfo := windows.JOBOBJECT_BASIC_LIMIT_INFORMATION{\n\t\tLimitFlags: windows.JOB_OBJECT_LIMIT_PRIORITY_CLASS,\n\t\tPriorityClass: pc,\n\t}\n\tif _, err := windows.SetInformationJobObject(\n\t\tjob,\n\t\twindows.JobObjectBasicLimitInformation,\n\t\tuintptr(unsafe.Pointer(\u0026limitInfo)),\n\t\tuint32(unsafe.Sizeof(limitInfo))); err != nil {\n\t\treturn windows.InvalidHandle, fmt.Errorf(\"windows.SetInformationJobObject failed: %w\", err)\n\t}\n\treturn job, nil\n}","line":{"from":50,"to":74}} {"id":100001567,"name":"initForOS","signature":"func initForOS(windowsService bool, windowsPriorityClass string) error","file":"cmd/kubelet/app/init_windows.go","code":"func initForOS(windowsService bool, windowsPriorityClass string) error {\n\tpriority := getPriorityValue(windowsPriorityClass)\n\tif priority == 0 {\n\t\treturn fmt.Errorf(\"unknown priority class %s, valid ones are available at \"+\n\t\t\t\"https://docs.microsoft.com/en-us/windows/win32/procthread/scheduling-priorities\", windowsPriorityClass)\n\t}\n\tklog.InfoS(\"Creating a Windows job object and adding kubelet process to it\", \"windowsPriorityClass\", windowsPriorityClass)\n\tjob, err := createWindowsJobObject(priority)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := windows.AssignProcessToJobObject(job, windows.CurrentProcess()); err != nil {\n\t\treturn fmt.Errorf(\"windows.AssignProcessToJobObject failed: %w\", err)\n\t}\n\n\tif windowsService {\n\t\treturn service.InitService(serviceName)\n\t}\n\treturn nil\n}","line":{"from":76,"to":95}} {"id":100001568,"name":"NewContainerRuntimeOptions","signature":"func NewContainerRuntimeOptions() *config.ContainerRuntimeOptions","file":"cmd/kubelet/app/options/container_runtime.go","code":"// NewContainerRuntimeOptions will create a new ContainerRuntimeOptions with\n// default values.\nfunc NewContainerRuntimeOptions() *config.ContainerRuntimeOptions {\n\treturn \u0026config.ContainerRuntimeOptions{\n\t\tPodSandboxImage: defaultPodSandboxImage,\n\t}\n}","line":{"from":34,"to":40}} {"id":100001569,"name":"AddGlobalFlags","signature":"func AddGlobalFlags(fs *pflag.FlagSet)","file":"cmd/kubelet/app/options/globalflags.go","code":"// AddGlobalFlags explicitly registers flags that libraries (glog, verflag, etc.) register\n// against the global flagsets from \"flag\" and \"github.com/spf13/pflag\".\n// We do this in order to prevent unwanted flags from leaking into the Kubelet's flagset.\nfunc AddGlobalFlags(fs *pflag.FlagSet) {\n\taddCadvisorFlags(fs)\n\taddCredentialProviderFlags(fs)\n\tverflag.AddFlags(fs)\n\tlogs.AddFlags(fs, logs.SkipLoggingConfigurationFlags())\n}","line":{"from":36,"to":44}} {"id":100001570,"name":"normalize","signature":"func normalize(s string) string","file":"cmd/kubelet/app/options/globalflags.go","code":"// normalize replaces underscores with hyphens\n// we should always use hyphens instead of underscores when registering kubelet flags\nfunc normalize(s string) string {\n\treturn strings.Replace(s, \"_\", \"-\", -1)\n}","line":{"from":46,"to":50}} {"id":100001571,"name":"register","signature":"func register(global *flag.FlagSet, local *pflag.FlagSet, globalName string)","file":"cmd/kubelet/app/options/globalflags.go","code":"// register adds a flag to local that targets the Value associated with the Flag named globalName in global\nfunc register(global *flag.FlagSet, local *pflag.FlagSet, globalName string) {\n\tif f := global.Lookup(globalName); f != nil {\n\t\tpflagFlag := pflag.PFlagFromGoFlag(f)\n\t\tpflagFlag.Name = normalize(pflagFlag.Name)\n\t\tlocal.AddFlag(pflagFlag)\n\t} else {\n\t\tpanic(fmt.Sprintf(\"failed to find flag in global flagset (flag): %s\", globalName))\n\t}\n}","line":{"from":52,"to":61}} {"id":100001572,"name":"pflagRegister","signature":"func pflagRegister(global, local *pflag.FlagSet, globalName string)","file":"cmd/kubelet/app/options/globalflags.go","code":"// pflagRegister adds a flag to local that targets the Value associated with the Flag named globalName in global\nfunc pflagRegister(global, local *pflag.FlagSet, globalName string) {\n\tif f := global.Lookup(globalName); f != nil {\n\t\tf.Name = normalize(f.Name)\n\t\tlocal.AddFlag(f)\n\t} else {\n\t\tpanic(fmt.Sprintf(\"failed to find flag in global flagset (pflag): %s\", globalName))\n\t}\n}","line":{"from":63,"to":71}} {"id":100001573,"name":"registerDeprecated","signature":"func registerDeprecated(global *flag.FlagSet, local *pflag.FlagSet, globalName, deprecated string)","file":"cmd/kubelet/app/options/globalflags.go","code":"// registerDeprecated registers the flag with register, and then marks it deprecated\nfunc registerDeprecated(global *flag.FlagSet, local *pflag.FlagSet, globalName, deprecated string) {\n\tregister(global, local, globalName)\n\tlocal.Lookup(normalize(globalName)).Deprecated = deprecated\n}","line":{"from":73,"to":77}} {"id":100001574,"name":"addCredentialProviderFlags","signature":"func addCredentialProviderFlags(fs *pflag.FlagSet)","file":"cmd/kubelet/app/options/globalflags.go","code":"// addCredentialProviderFlags adds flags from k8s.io/kubernetes/pkg/credentialprovider\nfunc addCredentialProviderFlags(fs *pflag.FlagSet) {\n\t// lookup flags in global flag set and re-register the values with our flagset\n\tglobal := pflag.CommandLine\n\tlocal := pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)\n\n\taddLegacyCloudProviderCredentialProviderFlags(global, local)\n\n\tfs.AddFlagSet(local)\n}","line":{"from":79,"to":88}} {"id":100001575,"name":"addCadvisorFlags","signature":"func addCadvisorFlags(fs *pflag.FlagSet)","file":"cmd/kubelet/app/options/globalflags_linux.go","code":"// addCadvisorFlags adds flags from cadvisor\nfunc addCadvisorFlags(fs *pflag.FlagSet) {\n\t// lookup flags in global flag set and re-register the values with our flagset\n\tglobal := flag.CommandLine\n\tlocal := pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)\n\n\t// e2e node tests rely on this\n\tregister(global, local, \"housekeeping_interval\")\n\n\t// These flags were implicit from cadvisor, and are mistakes that should be registered deprecated:\n\tconst deprecated = \"This is a cadvisor flag that was mistakenly registered with the Kubelet. Due to legacy concerns, it will follow the standard CLI deprecation timeline before being removed.\"\n\n\tregisterDeprecated(global, local, \"application_metrics_count_limit\", deprecated)\n\tregisterDeprecated(global, local, \"boot_id_file\", deprecated)\n\tregisterDeprecated(global, local, \"container_hints\", deprecated)\n\tregisterDeprecated(global, local, \"containerd\", deprecated)\n\tregisterDeprecated(global, local, \"enable_load_reader\", deprecated)\n\tregisterDeprecated(global, local, \"event_storage_age_limit\", deprecated)\n\tregisterDeprecated(global, local, \"event_storage_event_limit\", deprecated)\n\tregisterDeprecated(global, local, \"global_housekeeping_interval\", deprecated)\n\tregisterDeprecated(global, local, \"log_cadvisor_usage\", deprecated)\n\tregisterDeprecated(global, local, \"machine_id_file\", deprecated)\n\tregisterDeprecated(global, local, \"storage_driver_user\", deprecated)\n\tregisterDeprecated(global, local, \"storage_driver_password\", deprecated)\n\tregisterDeprecated(global, local, \"storage_driver_host\", deprecated)\n\tregisterDeprecated(global, local, \"storage_driver_db\", deprecated)\n\tregisterDeprecated(global, local, \"storage_driver_table\", deprecated)\n\tregisterDeprecated(global, local, \"storage_driver_secure\", deprecated)\n\tregisterDeprecated(global, local, \"storage_driver_buffer_duration\", deprecated)\n\tregisterDeprecated(global, local, \"containerd-namespace\", deprecated)\n\n\t// finally, add cadvisor flags to the provided flagset\n\tfs.AddFlagSet(local)\n}","line":{"from":37,"to":70}} {"id":100001576,"name":"addCadvisorFlags","signature":"func addCadvisorFlags(fs *pflag.FlagSet)","file":"cmd/kubelet/app/options/globalflags_other.go","code":"func addCadvisorFlags(fs *pflag.FlagSet) {\n}","line":{"from":26,"to":27}} {"id":100001577,"name":"addLegacyCloudProviderCredentialProviderFlags","signature":"func addLegacyCloudProviderCredentialProviderFlags(global, local *pflag.FlagSet)","file":"cmd/kubelet/app/options/globalflags_providerless.go","code":"func addLegacyCloudProviderCredentialProviderFlags(global, local *pflag.FlagSet) {\n\t// no-op when no legacy providers are compiled in\n}","line":{"from":26,"to":28}} {"id":100001578,"name":"addLegacyCloudProviderCredentialProviderFlags","signature":"func addLegacyCloudProviderCredentialProviderFlags(global, local *pflag.FlagSet)","file":"cmd/kubelet/app/options/globalflags_providers.go","code":"func addLegacyCloudProviderCredentialProviderFlags(global, local *pflag.FlagSet) {\n\t// TODO(#58034): This is not a static file, so it's not quite as straightforward as --google-json-key.\n\t// We need to figure out how ACR users can dynamically provide pull credentials before we can deprecate this.\n\tpflagRegister(global, local, \"azure-container-registry-config\")\n}","line":{"from":26,"to":30}} {"id":100001579,"name":"NewKubeletFlags","signature":"func NewKubeletFlags() *KubeletFlags","file":"cmd/kubelet/app/options/options.go","code":"// NewKubeletFlags will create a new KubeletFlags with default values\nfunc NewKubeletFlags() *KubeletFlags {\n\treturn \u0026KubeletFlags{\n\t\tContainerRuntimeOptions: *NewContainerRuntimeOptions(),\n\t\tCertDirectory: \"/var/lib/kubelet/pki\",\n\t\tRootDirectory: filepath.Clean(defaultRootDir),\n\t\tMaxContainerCount: -1,\n\t\tMaxPerPodContainerCount: 1,\n\t\tMinimumGCAge: metav1.Duration{Duration: 0},\n\t\tRegisterSchedulable: true,\n\t\tNodeLabels: make(map[string]string),\n\t}\n}","line":{"from":137,"to":149}} {"id":100001580,"name":"ValidateKubeletFlags","signature":"func ValidateKubeletFlags(f *KubeletFlags) error","file":"cmd/kubelet/app/options/options.go","code":"// ValidateKubeletFlags validates Kubelet's configuration flags and returns an error if they are invalid.\nfunc ValidateKubeletFlags(f *KubeletFlags) error {\n\tunknownLabels := sets.NewString()\n\tinvalidLabelErrs := make(map[string][]string)\n\tfor k, v := range f.NodeLabels {\n\t\tif isKubernetesLabel(k) \u0026\u0026 !kubeletapis.IsKubeletLabel(k) {\n\t\t\tunknownLabels.Insert(k)\n\t\t}\n\n\t\tif errs := validation.IsQualifiedName(k); len(errs) \u003e 0 {\n\t\t\tinvalidLabelErrs[k] = append(invalidLabelErrs[k], errs...)\n\t\t}\n\t\tif errs := validation.IsValidLabelValue(v); len(errs) \u003e 0 {\n\t\t\tinvalidLabelErrs[v] = append(invalidLabelErrs[v], errs...)\n\t\t}\n\t}\n\tif len(unknownLabels) \u003e 0 {\n\t\treturn fmt.Errorf(\"unknown 'kubernetes.io' or 'k8s.io' labels specified with --node-labels: %v\\n--node-labels in the 'kubernetes.io' namespace must begin with an allowed prefix (%s) or be in the specifically allowed set (%s)\", unknownLabels.List(), strings.Join(kubeletapis.KubeletLabelNamespaces(), \", \"), strings.Join(kubeletapis.KubeletLabels(), \", \"))\n\t}\n\tif len(invalidLabelErrs) \u003e 0 {\n\t\tlabelErrs := []string{}\n\t\tfor k, v := range invalidLabelErrs {\n\t\t\tlabelErrs = append(labelErrs, fmt.Sprintf(\"'%s' - %s\", k, strings.Join(v, \", \")))\n\t\t}\n\t\treturn fmt.Errorf(\"invalid node labels: %s\", strings.Join(labelErrs, \"; \"))\n\t}\n\treturn nil\n}","line":{"from":151,"to":178}} {"id":100001581,"name":"isKubernetesLabel","signature":"func isKubernetesLabel(key string) bool","file":"cmd/kubelet/app/options/options.go","code":"func isKubernetesLabel(key string) bool {\n\tnamespace := getLabelNamespace(key)\n\tif namespace == \"kubernetes.io\" || strings.HasSuffix(namespace, \".kubernetes.io\") {\n\t\treturn true\n\t}\n\tif namespace == \"k8s.io\" || strings.HasSuffix(namespace, \".k8s.io\") {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":180,"to":189}} {"id":100001582,"name":"getLabelNamespace","signature":"func getLabelNamespace(key string) string","file":"cmd/kubelet/app/options/options.go","code":"func getLabelNamespace(key string) string {\n\tif parts := strings.SplitN(key, \"/\", 2); len(parts) == 2 {\n\t\treturn parts[0]\n\t}\n\treturn \"\"\n}","line":{"from":191,"to":196}} {"id":100001583,"name":"NewKubeletConfiguration","signature":"func NewKubeletConfiguration() (*kubeletconfig.KubeletConfiguration, error)","file":"cmd/kubelet/app/options/options.go","code":"// NewKubeletConfiguration will create a new KubeletConfiguration with default values\nfunc NewKubeletConfiguration() (*kubeletconfig.KubeletConfiguration, error) {\n\tscheme, _, err := kubeletscheme.NewSchemeAndCodecs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tversioned := \u0026v1beta1.KubeletConfiguration{}\n\tscheme.Default(versioned)\n\tconfig := \u0026kubeletconfig.KubeletConfiguration{}\n\tif err := scheme.Convert(versioned, config, nil); err != nil {\n\t\treturn nil, err\n\t}\n\tapplyLegacyDefaults(config)\n\treturn config, nil\n}","line":{"from":198,"to":212}} {"id":100001584,"name":"applyLegacyDefaults","signature":"func applyLegacyDefaults(kc *kubeletconfig.KubeletConfiguration)","file":"cmd/kubelet/app/options/options.go","code":"// applyLegacyDefaults applies legacy default values to the KubeletConfiguration in order to\n// preserve the command line API. This is used to construct the baseline default KubeletConfiguration\n// before the first round of flag parsing.\nfunc applyLegacyDefaults(kc *kubeletconfig.KubeletConfiguration) {\n\t// --anonymous-auth\n\tkc.Authentication.Anonymous.Enabled = true\n\t// --authentication-token-webhook\n\tkc.Authentication.Webhook.Enabled = false\n\t// --authorization-mode\n\tkc.Authorization.Mode = kubeletconfig.KubeletAuthorizationModeAlwaysAllow\n\t// --read-only-port\n\tkc.ReadOnlyPort = ports.KubeletReadOnlyPort\n}","line":{"from":214,"to":226}} {"id":100001585,"name":"NewKubeletServer","signature":"func NewKubeletServer() (*KubeletServer, error)","file":"cmd/kubelet/app/options/options.go","code":"// NewKubeletServer will create a new KubeletServer with default values.\nfunc NewKubeletServer() (*KubeletServer, error) {\n\tconfig, err := NewKubeletConfiguration()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026KubeletServer{\n\t\tKubeletFlags: *NewKubeletFlags(),\n\t\tKubeletConfiguration: *config,\n\t}, nil\n}","line":{"from":235,"to":245}} {"id":100001586,"name":"ValidateKubeletServer","signature":"func ValidateKubeletServer(s *KubeletServer) error","file":"cmd/kubelet/app/options/options.go","code":"// ValidateKubeletServer validates configuration of KubeletServer and returns an error if the input configuration is invalid.\nfunc ValidateKubeletServer(s *KubeletServer) error {\n\t// please add any KubeletConfiguration validation to the kubeletconfigvalidation.ValidateKubeletConfiguration function\n\tif err := kubeletconfigvalidation.ValidateKubeletConfiguration(\u0026s.KubeletConfiguration, utilfeature.DefaultFeatureGate); err != nil {\n\t\treturn err\n\t}\n\tif err := ValidateKubeletFlags(\u0026s.KubeletFlags); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":247,"to":257}} {"id":100001587,"name":"AddFlags","signature":"func (s *KubeletServer) AddFlags(fs *pflag.FlagSet)","file":"cmd/kubelet/app/options/options.go","code":"// AddFlags adds flags for a specific KubeletServer to the specified FlagSet\nfunc (s *KubeletServer) AddFlags(fs *pflag.FlagSet) {\n\ts.KubeletFlags.AddFlags(fs)\n\tAddKubeletConfigFlags(fs, \u0026s.KubeletConfiguration)\n}","line":{"from":259,"to":263}} {"id":100001588,"name":"AddFlags","signature":"func (f *KubeletFlags) AddFlags(mainfs *pflag.FlagSet)","file":"cmd/kubelet/app/options/options.go","code":"// AddFlags adds flags for a specific KubeletFlags to the specified FlagSet\nfunc (f *KubeletFlags) AddFlags(mainfs *pflag.FlagSet) {\n\tfs := pflag.NewFlagSet(\"\", pflag.ExitOnError)\n\tdefer func() {\n\t\t// Unhide deprecated flags. We want deprecated flags to show in Kubelet help.\n\t\t// We have some hidden flags, but we might as well unhide these when they are deprecated,\n\t\t// as silently deprecating and removing (even hidden) things is unkind to people who use them.\n\t\tfs.VisitAll(func(f *pflag.Flag) {\n\t\t\tif len(f.Deprecated) \u003e 0 {\n\t\t\t\tf.Hidden = false\n\t\t\t}\n\t\t})\n\t\tmainfs.AddFlagSet(fs)\n\t}()\n\n\tf.ContainerRuntimeOptions.AddFlags(fs)\n\tf.addOSFlags(fs)\n\n\tfs.StringVar(\u0026f.KubeletConfigFile, \"config\", f.KubeletConfigFile, \"The Kubelet will load its initial configuration from this file. The path may be absolute or relative; relative paths start at the Kubelet's current working directory. Omit this flag to use the built-in default configuration values. Command-line flags override configuration from this file.\")\n\tfs.StringVar(\u0026f.KubeConfig, \"kubeconfig\", f.KubeConfig, \"Path to a kubeconfig file, specifying how to connect to the API server. Providing --kubeconfig enables API server mode, omitting --kubeconfig enables standalone mode.\")\n\n\tfs.StringVar(\u0026f.BootstrapKubeconfig, \"bootstrap-kubeconfig\", f.BootstrapKubeconfig, \"Path to a kubeconfig file that will be used to get client certificate for kubelet. \"+\n\t\t\"If the file specified by --kubeconfig does not exist, the bootstrap kubeconfig is used to request a client certificate from the API server. \"+\n\t\t\"On success, a kubeconfig file referencing the generated client certificate and key is written to the path specified by --kubeconfig. \"+\n\t\t\"The client certificate and key file will be stored in the directory pointed by --cert-dir.\")\n\n\tfs.StringVar(\u0026f.HostnameOverride, \"hostname-override\", f.HostnameOverride, \"If non-empty, will use this string as identification instead of the actual hostname. If --cloud-provider is set, the cloud provider determines the name of the node (consult cloud provider documentation to determine if and how the hostname is used).\")\n\n\tfs.StringVar(\u0026f.NodeIP, \"node-ip\", f.NodeIP, \"IP address (or comma-separated dual-stack IP addresses) of the node. If unset, kubelet will use the node's default IPv4 address, if any, or its default IPv6 address if it has no IPv4 addresses. You can pass '::' to make it prefer the default IPv6 address rather than the default IPv4 address.\")\n\n\tfs.StringVar(\u0026f.CertDirectory, \"cert-dir\", f.CertDirectory, \"The directory where the TLS certs are located. \"+\n\t\t\"If --tls-cert-file and --tls-private-key-file are provided, this flag will be ignored.\")\n\n\tfs.StringVar(\u0026f.RootDirectory, \"root-dir\", f.RootDirectory, \"Directory path for managing kubelet files (volume mounts,etc).\")\n\tfs.BoolVar(\u0026f.SeccompDefault, \"seccomp-default\", f.SeccompDefault, \"Enable the use of `RuntimeDefault` as the default seccomp profile for all workloads.\")\n\n\t// EXPERIMENTAL FLAGS\n\tbindableNodeLabels := cliflag.ConfigurationMap(f.NodeLabels)\n\tfs.Var(\u0026bindableNodeLabels, \"node-labels\", fmt.Sprintf(\"\u003cWarning: Alpha feature\u003e Labels to add when registering the node in the cluster. Labels must be key=value pairs separated by ','. Labels in the 'kubernetes.io' namespace must begin with an allowed prefix (%s) or be in the specifically allowed set (%s)\", strings.Join(kubeletapis.KubeletLabelNamespaces(), \", \"), strings.Join(kubeletapis.KubeletLabels(), \", \")))\n\tfs.StringVar(\u0026f.LockFilePath, \"lock-file\", f.LockFilePath, \"\u003cWarning: Alpha feature\u003e The path to file for kubelet to use as a lock file.\")\n\tfs.BoolVar(\u0026f.ExitOnLockContention, \"exit-on-lock-contention\", f.ExitOnLockContention, \"Whether kubelet should exit upon lock-file contention.\")\n\n\t// DEPRECATED FLAGS\n\tfs.DurationVar(\u0026f.MinimumGCAge.Duration, \"minimum-container-ttl-duration\", f.MinimumGCAge.Duration, \"Minimum age for a finished container before it is garbage collected. Examples: '300ms', '10s' or '2h45m'\")\n\tfs.MarkDeprecated(\"minimum-container-ttl-duration\", \"Use --eviction-hard or --eviction-soft instead. Will be removed in a future version.\")\n\tfs.Int32Var(\u0026f.MaxPerPodContainerCount, \"maximum-dead-containers-per-container\", f.MaxPerPodContainerCount, \"Maximum number of old instances to retain per container. Each container takes up some disk space.\")\n\tfs.MarkDeprecated(\"maximum-dead-containers-per-container\", \"Use --eviction-hard or --eviction-soft instead. Will be removed in a future version.\")\n\tfs.Int32Var(\u0026f.MaxContainerCount, \"maximum-dead-containers\", f.MaxContainerCount, \"Maximum number of old instances of containers to retain globally. Each container takes up some disk space. To disable, set to a negative number.\")\n\tfs.MarkDeprecated(\"maximum-dead-containers\", \"Use --eviction-hard or --eviction-soft instead. Will be removed in a future version.\")\n\tfs.BoolVar(\u0026f.RegisterSchedulable, \"register-schedulable\", f.RegisterSchedulable, \"Register the node as schedulable. Won't have any effect if register-node is false.\")\n\tfs.MarkDeprecated(\"register-schedulable\", \"will be removed in a future version\")\n\tfs.BoolVar(\u0026f.KeepTerminatedPodVolumes, \"keep-terminated-pod-volumes\", f.KeepTerminatedPodVolumes, \"Keep terminated pod volumes mounted to the node after the pod terminates. Can be useful for debugging volume related issues.\")\n\tfs.MarkDeprecated(\"keep-terminated-pod-volumes\", \"will be removed in a future version\")\n\tfs.StringVar(\u0026f.ExperimentalMounterPath, \"experimental-mounter-path\", f.ExperimentalMounterPath, \"[Experimental] Path of mounter binary. Leave empty to use the default mount.\")\n\tfs.MarkDeprecated(\"experimental-mounter-path\", \"will be removed in 1.25 or later. in favor of using CSI.\")\n\tfs.StringVar(\u0026f.CloudProvider, \"cloud-provider\", f.CloudProvider, \"The provider for cloud services. Set to empty string for running with no cloud provider. If set, the cloud provider determines the name of the node (consult cloud provider documentation to determine if and how the hostname is used).\")\n\tfs.MarkDeprecated(\"cloud-provider\", \"will be removed in 1.25 or later, in favor of removing cloud provider code from Kubelet.\")\n\tfs.StringVar(\u0026f.CloudConfigFile, \"cloud-config\", f.CloudConfigFile, \"The path to the cloud provider configuration file. Empty string for no configuration file.\")\n\tfs.MarkDeprecated(\"cloud-config\", \"will be removed in 1.25 or later, in favor of removing cloud provider code from Kubelet.\")\n\tfs.BoolVar(\u0026f.ExperimentalNodeAllocatableIgnoreEvictionThreshold, \"experimental-allocatable-ignore-eviction\", f.ExperimentalNodeAllocatableIgnoreEvictionThreshold, \"When set to 'true', Hard Eviction Thresholds will be ignored while calculating Node Allocatable. See https://kubernetes.io/docs/tasks/administer-cluster/reserve-compute-resources/ for more details. [default=false]\")\n\tfs.MarkDeprecated(\"experimental-allocatable-ignore-eviction\", \"will be removed in 1.25 or later.\")\n}","line":{"from":265,"to":326}} {"id":100001589,"name":"AddKubeletConfigFlags","signature":"func AddKubeletConfigFlags(mainfs *pflag.FlagSet, c *kubeletconfig.KubeletConfiguration)","file":"cmd/kubelet/app/options/options.go","code":"// AddKubeletConfigFlags adds flags for a specific kubeletconfig.KubeletConfiguration to the specified FlagSet\nfunc AddKubeletConfigFlags(mainfs *pflag.FlagSet, c *kubeletconfig.KubeletConfiguration) {\n\tfs := pflag.NewFlagSet(\"\", pflag.ExitOnError)\n\tdefer func() {\n\t\t// All KubeletConfiguration flags are now deprecated, and any new flags that point to\n\t\t// KubeletConfiguration fields are deprecated-on-creation. When removing flags at the end\n\t\t// of their deprecation period, be careful to check that they have *actually* been deprecated\n\t\t// members of the KubeletConfiguration for the entire deprecation period:\n\t\t// e.g. if a flag was added after this deprecation function, it may not be at the end\n\t\t// of its lifetime yet, even if the rest are.\n\t\tdeprecated := \"This parameter should be set via the config file specified by the Kubelet's --config flag. See https://kubernetes.io/docs/tasks/administer-cluster/kubelet-config-file/ for more information.\"\n\t\t// Some flags are permanently (?) meant to be available. In\n\t\t// Kubernetes 1.23, the following options were added to\n\t\t// LoggingConfiguration (long-term goal, more complete\n\t\t// configuration file) but deprecating the flags seemed\n\t\t// premature.\n\t\tnotDeprecated := map[string]bool{\n\t\t\t\"v\": true,\n\t\t\t\"vmodule\": true,\n\t\t\t\"log-flush-frequency\": true,\n\t\t}\n\t\tfs.VisitAll(func(f *pflag.Flag) {\n\t\t\tif notDeprecated[f.Name] {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tf.Deprecated = deprecated\n\t\t})\n\t\tmainfs.AddFlagSet(fs)\n\t}()\n\n\tfs.BoolVar(\u0026c.EnableServer, \"enable-server\", c.EnableServer, \"Enable the Kubelet's server\")\n\n\tfs.BoolVar(\u0026c.FailSwapOn, \"fail-swap-on\", c.FailSwapOn, \"Makes the Kubelet fail to start if swap is enabled on the node. \")\n\tfs.StringVar(\u0026c.StaticPodPath, \"pod-manifest-path\", c.StaticPodPath, \"Path to the directory containing static pod files to run, or the path to a single static pod file. Files starting with dots will be ignored.\")\n\tfs.DurationVar(\u0026c.SyncFrequency.Duration, \"sync-frequency\", c.SyncFrequency.Duration, \"Max period between synchronizing running containers and config\")\n\tfs.DurationVar(\u0026c.FileCheckFrequency.Duration, \"file-check-frequency\", c.FileCheckFrequency.Duration, \"Duration between checking config files for new data\")\n\tfs.DurationVar(\u0026c.HTTPCheckFrequency.Duration, \"http-check-frequency\", c.HTTPCheckFrequency.Duration, \"Duration between checking http for new data\")\n\tfs.StringVar(\u0026c.StaticPodURL, \"manifest-url\", c.StaticPodURL, \"URL for accessing additional Pod specifications to run\")\n\tfs.Var(cliflag.NewColonSeparatedMultimapStringString(\u0026c.StaticPodURLHeader), \"manifest-url-header\", \"Comma-separated list of HTTP headers to use when accessing the url provided to --manifest-url. Multiple headers with the same name will be added in the same order provided. This flag can be repeatedly invoked. For example: --manifest-url-header 'a:hello,b:again,c:world' --manifest-url-header 'b:beautiful'\")\n\tfs.Var(\u0026utilflag.IPVar{Val: \u0026c.Address}, \"address\", \"The IP address for the Kubelet to serve on (set to '0.0.0.0' or '::' for listening in all interfaces and IP families)\")\n\tfs.Int32Var(\u0026c.Port, \"port\", c.Port, \"The port for the Kubelet to serve on.\")\n\tfs.Int32Var(\u0026c.ReadOnlyPort, \"read-only-port\", c.ReadOnlyPort, \"The read-only port for the Kubelet to serve on with no authentication/authorization (set to 0 to disable)\")\n\n\t// runtime flags\n\tfs.StringVar(\u0026c.ContainerRuntimeEndpoint, \"container-runtime-endpoint\", c.ContainerRuntimeEndpoint, \"The endpoint of container runtime service. Unix Domain Sockets are supported on Linux, while npipe and tcp endpoints are supported on Windows. Examples:'unix:///path/to/runtime.sock', 'npipe:////./pipe/runtime'\")\n\tfs.StringVar(\u0026c.ImageServiceEndpoint, \"image-service-endpoint\", c.ImageServiceEndpoint, \"The endpoint of container image service. If not specified, it will be the same with --container-runtime-endpoint by default. Unix Domain Socket are supported on Linux, while npipe and tcp endpoints are supported on Windows. Examples:'unix:///path/to/runtime.sock', 'npipe:////./pipe/runtime'\")\n\n\t// Authentication\n\tfs.BoolVar(\u0026c.Authentication.Anonymous.Enabled, \"anonymous-auth\", c.Authentication.Anonymous.Enabled, \"\"+\n\t\t\"Enables anonymous requests to the Kubelet server. Requests that are not rejected by another \"+\n\t\t\"authentication method are treated as anonymous requests. Anonymous requests have a username \"+\n\t\t\"of system:anonymous, and a group name of system:unauthenticated.\")\n\tfs.BoolVar(\u0026c.Authentication.Webhook.Enabled, \"authentication-token-webhook\", c.Authentication.Webhook.Enabled, \"\"+\n\t\t\"Use the TokenReview API to determine authentication for bearer tokens.\")\n\tfs.DurationVar(\u0026c.Authentication.Webhook.CacheTTL.Duration, \"authentication-token-webhook-cache-ttl\", c.Authentication.Webhook.CacheTTL.Duration, \"\"+\n\t\t\"The duration to cache responses from the webhook token authenticator.\")\n\tfs.StringVar(\u0026c.Authentication.X509.ClientCAFile, \"client-ca-file\", c.Authentication.X509.ClientCAFile, \"\"+\n\t\t\"If set, any request presenting a client certificate signed by one of the authorities in the client-ca-file \"+\n\t\t\"is authenticated with an identity corresponding to the CommonName of the client certificate.\")\n\n\t// Authorization\n\tfs.StringVar((*string)(\u0026c.Authorization.Mode), \"authorization-mode\", string(c.Authorization.Mode), \"\"+\n\t\t\"Authorization mode for Kubelet server. Valid options are AlwaysAllow or Webhook. \"+\n\t\t\"Webhook mode uses the SubjectAccessReview API to determine authorization.\")\n\tfs.DurationVar(\u0026c.Authorization.Webhook.CacheAuthorizedTTL.Duration, \"authorization-webhook-cache-authorized-ttl\", c.Authorization.Webhook.CacheAuthorizedTTL.Duration, \"\"+\n\t\t\"The duration to cache 'authorized' responses from the webhook authorizer.\")\n\tfs.DurationVar(\u0026c.Authorization.Webhook.CacheUnauthorizedTTL.Duration, \"authorization-webhook-cache-unauthorized-ttl\", c.Authorization.Webhook.CacheUnauthorizedTTL.Duration, \"\"+\n\t\t\"The duration to cache 'unauthorized' responses from the webhook authorizer.\")\n\n\tfs.StringVar(\u0026c.TLSCertFile, \"tls-cert-file\", c.TLSCertFile, \"\"+\n\t\t\"File containing x509 Certificate used for serving HTTPS (with intermediate certs, if any, concatenated after server cert). \"+\n\t\t\"If --tls-cert-file and --tls-private-key-file are not provided, a self-signed certificate and key \"+\n\t\t\"are generated for the public address and saved to the directory passed to --cert-dir.\")\n\tfs.StringVar(\u0026c.TLSPrivateKeyFile, \"tls-private-key-file\", c.TLSPrivateKeyFile, \"File containing x509 private key matching --tls-cert-file.\")\n\tfs.BoolVar(\u0026c.ServerTLSBootstrap, \"rotate-server-certificates\", c.ServerTLSBootstrap, \"Auto-request and rotate the kubelet serving certificates by requesting new certificates from the kube-apiserver when the certificate expiration approaches. Requires the RotateKubeletServerCertificate feature gate to be enabled, and approval of the submitted CertificateSigningRequest objects.\")\n\n\ttlsCipherPreferredValues := cliflag.PreferredTLSCipherNames()\n\ttlsCipherInsecureValues := cliflag.InsecureTLSCipherNames()\n\tfs.StringSliceVar(\u0026c.TLSCipherSuites, \"tls-cipher-suites\", c.TLSCipherSuites,\n\t\t\"Comma-separated list of cipher suites for the server. \"+\n\t\t\t\"If omitted, the default Go cipher suites will be used. \\n\"+\n\t\t\t\"Preferred values: \"+strings.Join(tlsCipherPreferredValues, \", \")+\". \\n\"+\n\t\t\t\"Insecure values: \"+strings.Join(tlsCipherInsecureValues, \", \")+\".\")\n\ttlsPossibleVersions := cliflag.TLSPossibleVersions()\n\tfs.StringVar(\u0026c.TLSMinVersion, \"tls-min-version\", c.TLSMinVersion,\n\t\t\"Minimum TLS version supported. \"+\n\t\t\t\"Possible values: \"+strings.Join(tlsPossibleVersions, \", \"))\n\tfs.BoolVar(\u0026c.RotateCertificates, \"rotate-certificates\", c.RotateCertificates, \"Auto rotate the kubelet client certificates by requesting new certificates from the kube-apiserver when the certificate expiration approaches.\")\n\n\tfs.Int32Var(\u0026c.RegistryPullQPS, \"registry-qps\", c.RegistryPullQPS, \"If \u003e 0, limit registry pull QPS to this value. If 0, unlimited.\")\n\tfs.Int32Var(\u0026c.RegistryBurst, \"registry-burst\", c.RegistryBurst, \"Maximum size of a bursty pulls, temporarily allows pulls to burst to this number, while still not exceeding registry-qps. Only used if --registry-qps \u003e 0\")\n\tfs.Int32Var(\u0026c.EventRecordQPS, \"event-qps\", c.EventRecordQPS, \"QPS to limit event creations. The number must be \u003e= 0. If 0 will use DefaultQPS: 5.\")\n\tfs.Int32Var(\u0026c.EventBurst, \"event-burst\", c.EventBurst, \"Maximum size of a bursty event records, temporarily allows event records to burst to this number, while still not exceeding event-qps. The number must be \u003e= 0. If 0 will use DefaultBurst: 10.\")\n\n\tfs.BoolVar(\u0026c.EnableDebuggingHandlers, \"enable-debugging-handlers\", c.EnableDebuggingHandlers, \"Enables server endpoints for log collection and local running of containers and commands\")\n\tfs.BoolVar(\u0026c.EnableContentionProfiling, \"contention-profiling\", c.EnableContentionProfiling, \"Enable block profiling, if profiling is enabled\")\n\tfs.Int32Var(\u0026c.HealthzPort, \"healthz-port\", c.HealthzPort, \"The port of the localhost healthz endpoint (set to 0 to disable)\")\n\tfs.Var(\u0026utilflag.IPVar{Val: \u0026c.HealthzBindAddress}, \"healthz-bind-address\", \"The IP address for the healthz server to serve on (set to '0.0.0.0' or '::' for listening in all interfaces and IP families)\")\n\tfs.Int32Var(\u0026c.OOMScoreAdj, \"oom-score-adj\", c.OOMScoreAdj, \"The oom-score-adj value for kubelet process. Values must be within the range [-1000, 1000]\")\n\tfs.StringVar(\u0026c.ClusterDomain, \"cluster-domain\", c.ClusterDomain, \"Domain for this cluster. If set, kubelet will configure all containers to search this domain in addition to the host's search domains\")\n\n\tfs.StringVar(\u0026c.VolumePluginDir, \"volume-plugin-dir\", c.VolumePluginDir, \"The full path of the directory in which to search for additional third party volume plugins\")\n\tfs.StringSliceVar(\u0026c.ClusterDNS, \"cluster-dns\", c.ClusterDNS, \"Comma-separated list of DNS server IP address. This value is used for containers DNS server in case of Pods with \\\"dnsPolicy=ClusterFirst\\\". Note: all DNS servers appearing in the list MUST serve the same set of records otherwise name resolution within the cluster may not work correctly. There is no guarantee as to which DNS server may be contacted for name resolution.\")\n\tfs.DurationVar(\u0026c.StreamingConnectionIdleTimeout.Duration, \"streaming-connection-idle-timeout\", c.StreamingConnectionIdleTimeout.Duration, \"Maximum time a streaming connection can be idle before the connection is automatically closed. 0 indicates no timeout. Example: '5m'. Note: All connections to the kubelet server have a maximum duration of 4 hours.\")\n\tfs.DurationVar(\u0026c.NodeStatusUpdateFrequency.Duration, \"node-status-update-frequency\", c.NodeStatusUpdateFrequency.Duration, \"Specifies how often kubelet posts node status to master. Note: be cautious when changing the constant, it must work with nodeMonitorGracePeriod in nodecontroller.\")\n\tfs.DurationVar(\u0026c.ImageMinimumGCAge.Duration, \"minimum-image-ttl-duration\", c.ImageMinimumGCAge.Duration, \"Minimum age for an unused image before it is garbage collected. Examples: '300ms', '10s' or '2h45m'.\")\n\tfs.Int32Var(\u0026c.ImageGCHighThresholdPercent, \"image-gc-high-threshold\", c.ImageGCHighThresholdPercent, \"The percent of disk usage after which image garbage collection is always run. Values must be within the range [0, 100], To disable image garbage collection, set to 100. \")\n\tfs.Int32Var(\u0026c.ImageGCLowThresholdPercent, \"image-gc-low-threshold\", c.ImageGCLowThresholdPercent, \"The percent of disk usage before which image garbage collection is never run. Lowest disk usage to garbage collect to. Values must be within the range [0, 100] and should not be larger than that of --image-gc-high-threshold.\")\n\tfs.DurationVar(\u0026c.VolumeStatsAggPeriod.Duration, \"volume-stats-agg-period\", c.VolumeStatsAggPeriod.Duration, \"Specifies interval for kubelet to calculate and cache the volume disk usage for all pods and volumes. To disable volume calculations, set to a negative number.\")\n\tfs.Var(cliflag.NewMapStringBool(\u0026c.FeatureGates), \"feature-gates\", \"A set of key=value pairs that describe feature gates for alpha/experimental features. \"+\n\t\t\"Options are:\\n\"+strings.Join(utilfeature.DefaultFeatureGate.KnownFeatures(), \"\\n\"))\n\tfs.StringVar(\u0026c.KubeletCgroups, \"kubelet-cgroups\", c.KubeletCgroups, \"Optional absolute name of cgroups to create and run the Kubelet in.\")\n\tfs.StringVar(\u0026c.SystemCgroups, \"system-cgroups\", c.SystemCgroups, \"Optional absolute name of cgroups in which to place all non-kernel processes that are not already inside a cgroup under '/'. Empty for no container. Rolling back the flag requires a reboot.\")\n\n\tfs.StringVar(\u0026c.ProviderID, \"provider-id\", c.ProviderID, \"Unique identifier for identifying the node in a machine database, i.e cloudprovider\")\n\n\tfs.BoolVar(\u0026c.CgroupsPerQOS, \"cgroups-per-qos\", c.CgroupsPerQOS, \"Enable creation of QoS cgroup hierarchy, if true top level QoS and pod cgroups are created.\")\n\tfs.StringVar(\u0026c.CgroupDriver, \"cgroup-driver\", c.CgroupDriver, \"Driver that the kubelet uses to manipulate cgroups on the host. Possible values: 'cgroupfs', 'systemd'\")\n\tfs.StringVar(\u0026c.CgroupRoot, \"cgroup-root\", c.CgroupRoot, \"Optional root cgroup to use for pods. This is handled by the container runtime on a best effort basis. Default: '', which means use the container runtime default.\")\n\tfs.StringVar(\u0026c.CPUManagerPolicy, \"cpu-manager-policy\", c.CPUManagerPolicy, \"CPU Manager policy to use. Possible values: 'none', 'static'.\")\n\tfs.Var(cliflag.NewMapStringStringNoSplit(\u0026c.CPUManagerPolicyOptions), \"cpu-manager-policy-options\", \"A set of key=value CPU Manager policy options to use, to fine tune their behaviour. If not supplied, keep the default behaviour.\")\n\tfs.DurationVar(\u0026c.CPUManagerReconcilePeriod.Duration, \"cpu-manager-reconcile-period\", c.CPUManagerReconcilePeriod.Duration, \"\u003cWarning: Alpha feature\u003e CPU Manager reconciliation period. Examples: '10s', or '1m'. If not supplied, defaults to 'NodeStatusUpdateFrequency'\")\n\tfs.Var(cliflag.NewMapStringString(\u0026c.QOSReserved), \"qos-reserved\", \"\u003cWarning: Alpha feature\u003e A set of ResourceName=Percentage (e.g. memory=50%) pairs that describe how pod resource requests are reserved at the QoS level. Currently only memory is supported. Requires the QOSReserved feature gate to be enabled.\")\n\tfs.StringVar(\u0026c.TopologyManagerPolicy, \"topology-manager-policy\", c.TopologyManagerPolicy, \"Topology Manager policy to use. Possible values: 'none', 'best-effort', 'restricted', 'single-numa-node'.\")\n\tfs.DurationVar(\u0026c.RuntimeRequestTimeout.Duration, \"runtime-request-timeout\", c.RuntimeRequestTimeout.Duration, \"Timeout of all runtime requests except long running request - pull, logs, exec and attach. When timeout exceeded, kubelet will cancel the request, throw out an error and retry later.\")\n\tfs.StringVar(\u0026c.HairpinMode, \"hairpin-mode\", c.HairpinMode, \"How should the kubelet setup hairpin NAT. This allows endpoints of a Service to loadbalance back to themselves if they should try to access their own Service. Valid values are \\\"promiscuous-bridge\\\", \\\"hairpin-veth\\\" and \\\"none\\\".\")\n\tfs.Int32Var(\u0026c.MaxPods, \"max-pods\", c.MaxPods, \"Number of Pods that can run on this Kubelet.\")\n\n\tfs.StringVar(\u0026c.PodCIDR, \"pod-cidr\", c.PodCIDR, \"The CIDR to use for pod IP addresses, only used in standalone mode. In cluster mode, this is obtained from the master. For IPv6, the maximum number of IP's allocated is 65536\")\n\tfs.Int64Var(\u0026c.PodPidsLimit, \"pod-max-pids\", c.PodPidsLimit, \"Set the maximum number of processes per pod. If -1, the kubelet defaults to the node allocatable pid capacity.\")\n\n\tfs.StringVar(\u0026c.ResolverConfig, \"resolv-conf\", c.ResolverConfig, \"Resolver configuration file used as the basis for the container DNS resolution configuration.\")\n\n\tfs.BoolVar(\u0026c.RunOnce, \"runonce\", c.RunOnce, \"If true, exit after spawning pods from static pod files or remote urls. Exclusive with --enable-server\")\n\n\tfs.BoolVar(\u0026c.CPUCFSQuota, \"cpu-cfs-quota\", c.CPUCFSQuota, \"Enable CPU CFS quota enforcement for containers that specify CPU limits\")\n\tfs.DurationVar(\u0026c.CPUCFSQuotaPeriod.Duration, \"cpu-cfs-quota-period\", c.CPUCFSQuotaPeriod.Duration, \"Sets CPU CFS quota period value, cpu.cfs_period_us, defaults to Linux Kernel default\")\n\tfs.BoolVar(\u0026c.EnableControllerAttachDetach, \"enable-controller-attach-detach\", c.EnableControllerAttachDetach, \"Enables the Attach/Detach controller to manage attachment/detachment of volumes scheduled to this node, and disables kubelet from executing any attach/detach operations\")\n\tfs.BoolVar(\u0026c.MakeIPTablesUtilChains, \"make-iptables-util-chains\", c.MakeIPTablesUtilChains, \"If true, kubelet will ensure iptables utility rules are present on host.\")\n\tfs.Int32Var(\u0026c.IPTablesMasqueradeBit, \"iptables-masquerade-bit\", c.IPTablesMasqueradeBit, \"The bit of the fwmark space to mark packets for SNAT. Must be within the range [0, 31]. Please match this parameter with corresponding parameter in kube-proxy.\")\n\tfs.Int32Var(\u0026c.IPTablesDropBit, \"iptables-drop-bit\", c.IPTablesDropBit, \"The bit of the fwmark space to mark packets for dropping. Must be within the range [0, 31].\")\n\tfs.StringVar(\u0026c.ContainerLogMaxSize, \"container-log-max-size\", c.ContainerLogMaxSize, \"\u003cWarning: Beta feature\u003e Set the maximum size (e.g. 10Mi) of container log file before it is rotated.\")\n\tfs.Int32Var(\u0026c.ContainerLogMaxFiles, \"container-log-max-files\", c.ContainerLogMaxFiles, \"\u003cWarning: Beta feature\u003e Set the maximum number of container log files that can be present for a container. The number must be \u003e= 2.\")\n\tfs.StringSliceVar(\u0026c.AllowedUnsafeSysctls, \"allowed-unsafe-sysctls\", c.AllowedUnsafeSysctls, \"Comma-separated whitelist of unsafe sysctls or unsafe sysctl patterns (ending in *). Use these at your own risk.\")\n\n\tfs.Int32Var(\u0026c.NodeStatusMaxImages, \"node-status-max-images\", c.NodeStatusMaxImages, \"The maximum number of images to report in Node.Status.Images. If -1 is specified, no cap will be applied.\")\n\tfs.BoolVar(\u0026c.KernelMemcgNotification, \"kernel-memcg-notification\", c.KernelMemcgNotification, \"If enabled, the kubelet will integrate with the kernel memcg notification to determine if memory eviction thresholds are crossed rather than polling.\")\n\tfs.BoolVar(\u0026c.LocalStorageCapacityIsolation, \"local-storage-capacity-isolation\", c.LocalStorageCapacityIsolation, \"If true, local ephemeral storage isolation is enabled. Otherwise, local storage isolation feature will be disabled\")\n\n\t// Flags intended for testing, not recommended used in production environments.\n\tfs.Int64Var(\u0026c.MaxOpenFiles, \"max-open-files\", c.MaxOpenFiles, \"Number of files that can be opened by Kubelet process.\")\n\n\tfs.StringVar(\u0026c.ContentType, \"kube-api-content-type\", c.ContentType, \"Content type of requests sent to apiserver.\")\n\tfs.Int32Var(\u0026c.KubeAPIQPS, \"kube-api-qps\", c.KubeAPIQPS, \"QPS to use while talking with kubernetes apiserver. The number must be \u003e= 0. If 0 will use DefaultQPS: 50. Doesn't cover events and node heartbeat apis which rate limiting is controlled by a different set of flags\")\n\tfs.Int32Var(\u0026c.KubeAPIBurst, \"kube-api-burst\", c.KubeAPIBurst, \"Burst to use while talking with kubernetes apiserver. The number must be \u003e= 0. If 0 will use DefaultBurst: 100. Doesn't cover events and node heartbeat apis which rate limiting is controlled by a different set of flags\")\n\tfs.BoolVar(\u0026c.SerializeImagePulls, \"serialize-image-pulls\", c.SerializeImagePulls, \"Pull images one at a time. We recommend *not* changing the default value on nodes that run docker daemon with version \u003c 1.9 or an Aufs storage backend. Issue #10959 has more details.\")\n\n\tfs.Var(cliflag.NewLangleSeparatedMapStringString(\u0026c.EvictionHard), \"eviction-hard\", \"A set of eviction thresholds (e.g. memory.available\u003c1Gi) that if met would trigger a pod eviction.\")\n\tfs.Var(cliflag.NewLangleSeparatedMapStringString(\u0026c.EvictionSoft), \"eviction-soft\", \"A set of eviction thresholds (e.g. memory.available\u003c1.5Gi) that if met over a corresponding grace period would trigger a pod eviction.\")\n\tfs.Var(cliflag.NewMapStringString(\u0026c.EvictionSoftGracePeriod), \"eviction-soft-grace-period\", \"A set of eviction grace periods (e.g. memory.available=1m30s) that correspond to how long a soft eviction threshold must hold before triggering a pod eviction.\")\n\tfs.DurationVar(\u0026c.EvictionPressureTransitionPeriod.Duration, \"eviction-pressure-transition-period\", c.EvictionPressureTransitionPeriod.Duration, \"Duration for which the kubelet has to wait before transitioning out of an eviction pressure condition.\")\n\tfs.Int32Var(\u0026c.EvictionMaxPodGracePeriod, \"eviction-max-pod-grace-period\", c.EvictionMaxPodGracePeriod, \"Maximum allowed grace period (in seconds) to use when terminating pods in response to a soft eviction threshold being met. If negative, defer to pod specified value.\")\n\tfs.Var(cliflag.NewMapStringString(\u0026c.EvictionMinimumReclaim), \"eviction-minimum-reclaim\", \"A set of minimum reclaims (e.g. imagefs.available=2Gi) that describes the minimum amount of resource the kubelet will reclaim when performing a pod eviction if that resource is under pressure.\")\n\tfs.Int32Var(\u0026c.PodsPerCore, \"pods-per-core\", c.PodsPerCore, \"Number of Pods per core that can run on this Kubelet. The total number of Pods on this Kubelet cannot exceed max-pods, so max-pods will be used if this calculation results in a larger number of Pods allowed on the Kubelet. A value of 0 disables this limit.\")\n\tfs.BoolVar(\u0026c.ProtectKernelDefaults, \"protect-kernel-defaults\", c.ProtectKernelDefaults, \"Default kubelet behaviour for kernel tuning. If set, kubelet errors if any of kernel tunables is different than kubelet defaults.\")\n\tfs.StringVar(\u0026c.ReservedSystemCPUs, \"reserved-cpus\", c.ReservedSystemCPUs, \"A comma-separated list of CPUs or CPU ranges that are reserved for system and kubernetes usage. This specific list will supersede cpu counts in --system-reserved and --kube-reserved.\")\n\tfs.StringVar(\u0026c.TopologyManagerScope, \"topology-manager-scope\", c.TopologyManagerScope, \"Scope to which topology hints applied. Topology Manager collects hints from Hint Providers and applies them to defined scope to ensure the pod admission. Possible values: 'container', 'pod'.\")\n\tfs.Var(cliflag.NewMapStringStringNoSplit(\u0026c.TopologyManagerPolicyOptions), \"topology-manager-policy-options\", \"A set of key=value Topology Manager policy options to use, to fine tune their behaviour. If not supplied, keep the default behaviour.\")\n\t// Node Allocatable Flags\n\tfs.Var(cliflag.NewMapStringString(\u0026c.SystemReserved), \"system-reserved\", \"A set of ResourceName=ResourceQuantity (e.g. cpu=200m,memory=500Mi,ephemeral-storage=1Gi) pairs that describe resources reserved for non-kubernetes components. Currently only cpu, memory and local ephemeral storage for root file system are supported. See https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/ for more detail. [default=none]\")\n\tfs.Var(cliflag.NewMapStringString(\u0026c.KubeReserved), \"kube-reserved\", \"A set of ResourceName=ResourceQuantity (e.g. cpu=200m,memory=500Mi,ephemeral-storage=1Gi) pairs that describe resources reserved for kubernetes system components. Currently only cpu, memory and local ephemeral storage for root file system are supported. See https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/ for more detail. [default=none]\")\n\tfs.StringSliceVar(\u0026c.EnforceNodeAllocatable, \"enforce-node-allocatable\", c.EnforceNodeAllocatable, \"A comma separated list of levels of node allocatable enforcement to be enforced by kubelet. Acceptable options are 'none', 'pods', 'system-reserved', and 'kube-reserved'. If the latter two options are specified, '--system-reserved-cgroup' and '--kube-reserved-cgroup' must also be set, respectively. If 'none' is specified, no additional options should be set. See https://kubernetes.io/docs/tasks/administer-cluster/reserve-compute-resources/ for more details.\")\n\tfs.StringVar(\u0026c.SystemReservedCgroup, \"system-reserved-cgroup\", c.SystemReservedCgroup, \"Absolute name of the top level cgroup that is used to manage non-kubernetes components for which compute resources were reserved via '--system-reserved' flag. Ex. '/system-reserved'. [default='']\")\n\tfs.StringVar(\u0026c.KubeReservedCgroup, \"kube-reserved-cgroup\", c.KubeReservedCgroup, \"Absolute name of the top level cgroup that is used to manage kubernetes components for which compute resources were reserved via '--kube-reserved' flag. Ex. '/kube-reserved'. [default='']\")\n\tlogsapi.AddFlags(\u0026c.Logging, fs)\n\n\t// Memory Manager Flags\n\tfs.StringVar(\u0026c.MemoryManagerPolicy, \"memory-manager-policy\", c.MemoryManagerPolicy, \"Memory Manager policy to use. Possible values: 'None', 'Static'.\")\n\tfs.Var(\u0026utilflag.ReservedMemoryVar{Value: \u0026c.ReservedMemory}, \"reserved-memory\", \"A comma separated list of memory reservations for NUMA nodes. (e.g. --reserved-memory 0:memory=1Gi,hugepages-1M=2Gi --reserved-memory 1:memory=2Gi). The total sum for each memory type should be equal to the sum of kube-reserved, system-reserved and eviction-threshold. See https://kubernetes.io/docs/tasks/administer-cluster/memory-manager/#reserved-memory-flag for more details.\")\n\n\tfs.BoolVar(\u0026c.RegisterNode, \"register-node\", c.RegisterNode, \"Register the node with the apiserver. If --kubeconfig is not provided, this flag is irrelevant, as the Kubelet won't have an apiserver to register with.\")\n\n\tfs.Var(\u0026utilflag.RegisterWithTaintsVar{Value: \u0026c.RegisterWithTaints}, \"register-with-taints\", \"Register the node with the given list of taints (comma separated \\\"\u003ckey\u003e=\u003cvalue\u003e:\u003ceffect\u003e\\\"). No-op if register-node is false.\")\n}","line":{"from":328,"to":511}} {"id":100001590,"name":"addOSFlags","signature":"func (f *KubeletFlags) addOSFlags(fs *pflag.FlagSet)","file":"cmd/kubelet/app/options/osflags_others.go","code":"func (f *KubeletFlags) addOSFlags(fs *pflag.FlagSet) {\n}","line":{"from":26,"to":27}} {"id":100001591,"name":"addOSFlags","signature":"func (f *KubeletFlags) addOSFlags(fs *pflag.FlagSet)","file":"cmd/kubelet/app/options/osflags_windows.go","code":"func (f *KubeletFlags) addOSFlags(fs *pflag.FlagSet) {\n\tfs.BoolVar(\u0026f.WindowsService, \"windows-service\", f.WindowsService, \"Enable Windows Service Control Manager API integration\")\n\t// The default priority class associated with any process in Windows is NORMAL_PRIORITY_CLASS. Keeping it as is\n\t// to maintain backwards compatibility.\n\t// Source: https://docs.microsoft.com/en-us/windows/win32/procthread/scheduling-priorities\n\tfs.StringVar(\u0026f.WindowsPriorityClass, \"windows-priorityclass\", \"NORMAL_PRIORITY_CLASS\",\n\t\t\"Set the PriorityClass associated with kubelet process, the default ones are available at \"+\n\t\t\t\"https://docs.microsoft.com/en-us/windows/win32/procthread/scheduling-priorities\")\n}","line":{"from":26,"to":34}} {"id":100001592,"name":"ProbeVolumePlugins","signature":"func ProbeVolumePlugins(featureGate featuregate.FeatureGate) ([]volume.VolumePlugin, error)","file":"cmd/kubelet/app/plugins.go","code":"// ProbeVolumePlugins collects all volume plugins into an easy to use list.\nfunc ProbeVolumePlugins(featureGate featuregate.FeatureGate) ([]volume.VolumePlugin, error) {\n\tallPlugins := []volume.VolumePlugin{}\n\n\t// The list of plugins to probe is decided by the kubelet binary, not\n\t// by dynamic linking or other \"magic\". Plugins will be analyzed and\n\t// initialized later.\n\t//\n\t// Kubelet does not currently need to configure volume plugins.\n\t// If/when it does, see kube-controller-manager/app/plugins.go for example of using volume.VolumeConfig\n\tvar err error\n\tallPlugins, err = appendLegacyProviderVolumes(allPlugins, featureGate)\n\tif err != nil {\n\t\treturn allPlugins, err\n\t}\n\tallPlugins = append(allPlugins, emptydir.ProbeVolumePlugins()...)\n\tallPlugins = append(allPlugins, git_repo.ProbeVolumePlugins()...)\n\tallPlugins = append(allPlugins, hostpath.ProbeVolumePlugins(volume.VolumeConfig{})...)\n\tallPlugins = append(allPlugins, nfs.ProbeVolumePlugins(volume.VolumeConfig{})...)\n\tallPlugins = append(allPlugins, secret.ProbeVolumePlugins()...)\n\tallPlugins = append(allPlugins, iscsi.ProbeVolumePlugins()...)\n\tallPlugins = append(allPlugins, cephfs.ProbeVolumePlugins()...)\n\tallPlugins = append(allPlugins, downwardapi.ProbeVolumePlugins()...)\n\tallPlugins = append(allPlugins, fc.ProbeVolumePlugins()...)\n\tallPlugins = append(allPlugins, configmap.ProbeVolumePlugins()...)\n\tallPlugins = append(allPlugins, projected.ProbeVolumePlugins()...)\n\tallPlugins = append(allPlugins, local.ProbeVolumePlugins()...)\n\tallPlugins = append(allPlugins, csi.ProbeVolumePlugins()...)\n\treturn allPlugins, nil\n}","line":{"from":45,"to":74}} {"id":100001593,"name":"GetDynamicPluginProber","signature":"func GetDynamicPluginProber(pluginDir string, runner exec.Interface) volume.DynamicPluginProber","file":"cmd/kubelet/app/plugins.go","code":"// GetDynamicPluginProber gets the probers of dynamically discoverable plugins\n// for kubelet.\n// Currently only Flexvolume plugins are dynamically discoverable.\nfunc GetDynamicPluginProber(pluginDir string, runner exec.Interface) volume.DynamicPluginProber {\n\treturn flexvolume.GetDynamicPluginProber(pluginDir, runner)\n}","line":{"from":76,"to":81}} {"id":100001594,"name":"appendLegacyProviderVolumes","signature":"func appendLegacyProviderVolumes(allPlugins []volume.VolumePlugin, featureGate featuregate.FeatureGate) ([]volume.VolumePlugin, error)","file":"cmd/kubelet/app/plugins_providerless.go","code":"func appendLegacyProviderVolumes(allPlugins []volume.VolumePlugin, featureGate featuregate.FeatureGate) ([]volume.VolumePlugin, error) {\n\t// no-op when we didn't compile in support for these\n\treturn allPlugins, nil\n}","line":{"from":28,"to":31}} {"id":100001595,"name":"appendPluginBasedOnFeatureFlags","signature":"func appendPluginBasedOnFeatureFlags(plugins []volume.VolumePlugin, inTreePluginName string,","file":"cmd/kubelet/app/plugins_providers.go","code":"func appendPluginBasedOnFeatureFlags(plugins []volume.VolumePlugin, inTreePluginName string,\n\tfeatureGate featuregate.FeatureGate, pluginInfo pluginInfo) ([]volume.VolumePlugin, error) {\n\t_, err := csimigration.CheckMigrationFeatureFlags(featureGate, pluginInfo.pluginMigrationFeature, pluginInfo.pluginUnregisterFeature)\n\tif err != nil {\n\t\tklog.InfoS(\"Unexpected CSI Migration Feature Flags combination detected, CSI Migration may not take effect\", \"err\", err)\n\t\t// TODO: fail and return here once alpha only tests can set the feature flags for a plugin correctly\n\t}\n\n\t// Skip appending the in-tree plugin to the list of plugins to be probed/initialized\n\t// if the plugin unregister feature flag is set\n\tif featureGate.Enabled(pluginInfo.pluginUnregisterFeature) {\n\t\tklog.InfoS(\"Skipped registration of plugin since feature flag is enabled\", \"pluginName\", inTreePluginName, \"featureFlag\", pluginInfo.pluginUnregisterFeature)\n\t\treturn plugins, nil\n\t}\n\n\tplugins = append(plugins, pluginInfo.pluginProbeFunction()...)\n\treturn plugins, nil\n}","line":{"from":42,"to":59}} {"id":100001596,"name":"appendLegacyProviderVolumes","signature":"func appendLegacyProviderVolumes(allPlugins []volume.VolumePlugin, featureGate featuregate.FeatureGate) ([]volume.VolumePlugin, error)","file":"cmd/kubelet/app/plugins_providers.go","code":"func appendLegacyProviderVolumes(allPlugins []volume.VolumePlugin, featureGate featuregate.FeatureGate) ([]volume.VolumePlugin, error) {\n\tpluginMigrationStatus := make(map[string]pluginInfo)\n\tpluginMigrationStatus[plugins.GCEPDInTreePluginName] = pluginInfo{pluginMigrationFeature: features.CSIMigrationGCE, pluginUnregisterFeature: features.InTreePluginGCEUnregister, pluginProbeFunction: gcepd.ProbeVolumePlugins}\n\tpluginMigrationStatus[plugins.AzureFileInTreePluginName] = pluginInfo{pluginMigrationFeature: features.CSIMigrationAzureFile, pluginUnregisterFeature: features.InTreePluginAzureFileUnregister, pluginProbeFunction: azure_file.ProbeVolumePlugins}\n\tpluginMigrationStatus[plugins.VSphereInTreePluginName] = pluginInfo{pluginMigrationFeature: features.CSIMigrationvSphere, pluginUnregisterFeature: features.InTreePluginvSphereUnregister, pluginProbeFunction: vsphere_volume.ProbeVolumePlugins}\n\tpluginMigrationStatus[plugins.PortworxVolumePluginName] = pluginInfo{pluginMigrationFeature: features.CSIMigrationPortworx, pluginUnregisterFeature: features.InTreePluginPortworxUnregister, pluginProbeFunction: portworx.ProbeVolumePlugins}\n\tpluginMigrationStatus[plugins.RBDVolumePluginName] = pluginInfo{pluginMigrationFeature: features.CSIMigrationRBD, pluginUnregisterFeature: features.InTreePluginRBDUnregister, pluginProbeFunction: rbd.ProbeVolumePlugins}\n\tvar err error\n\tfor pluginName, pluginInfo := range pluginMigrationStatus {\n\t\tallPlugins, err = appendPluginBasedOnFeatureFlags(allPlugins, pluginName, featureGate, pluginInfo)\n\t\tif err != nil {\n\t\t\treturn allPlugins, err\n\t\t}\n\t}\n\treturn allPlugins, nil\n}","line":{"from":67,"to":82}} {"id":100001597,"name":"init","signature":"func init()","file":"cmd/kubelet/app/server.go","code":"func init() {\n\tutilruntime.Must(logsapi.AddFeatureGates(utilfeature.DefaultMutableFeatureGate))\n}","line":{"from":115,"to":117}} {"id":100001598,"name":"NewKubeletCommand","signature":"func NewKubeletCommand() *cobra.Command","file":"cmd/kubelet/app/server.go","code":"// NewKubeletCommand creates a *cobra.Command object with default parameters\nfunc NewKubeletCommand() *cobra.Command {\n\tcleanFlagSet := pflag.NewFlagSet(componentKubelet, pflag.ContinueOnError)\n\tcleanFlagSet.SetNormalizeFunc(cliflag.WordSepNormalizeFunc)\n\tkubeletFlags := options.NewKubeletFlags()\n\n\tkubeletConfig, err := options.NewKubeletConfiguration()\n\t// programmer error\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to create a new kubelet configuration\")\n\t\tos.Exit(1)\n\t}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: componentKubelet,\n\t\tLong: `The kubelet is the primary \"node agent\" that runs on each\nnode. It can register the node with the apiserver using one of: the hostname; a flag to\noverride the hostname; or specific logic for a cloud provider.\n\nThe kubelet works in terms of a PodSpec. A PodSpec is a YAML or JSON object\nthat describes a pod. The kubelet takes a set of PodSpecs that are provided through\nvarious mechanisms (primarily through the apiserver) and ensures that the containers\ndescribed in those PodSpecs are running and healthy. The kubelet doesn't manage\ncontainers which were not created by Kubernetes.\n\nOther than from an PodSpec from the apiserver, there are two ways that a container\nmanifest can be provided to the Kubelet.\n\nFile: Path passed as a flag on the command line. Files under this path will be monitored\nperiodically for updates. The monitoring period is 20s by default and is configurable\nvia a flag.\n\nHTTP endpoint: HTTP endpoint passed as a parameter on the command line. This endpoint\nis checked every 20 seconds (also configurable with a flag).`,\n\t\t// The Kubelet has special flag parsing requirements to enforce flag precedence rules,\n\t\t// so we do all our parsing manually in Run, below.\n\t\t// DisableFlagParsing=true provides the full set of flags passed to the kubelet in the\n\t\t// `args` arg to Run, without Cobra's interference.\n\t\tDisableFlagParsing: true,\n\t\tSilenceUsage: true,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\t// initial flag parse, since we disable cobra's flag parsing\n\t\t\tif err := cleanFlagSet.Parse(args); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to parse kubelet flag: %w\", err)\n\t\t\t}\n\n\t\t\t// check if there are non-flag arguments in the command line\n\t\t\tcmds := cleanFlagSet.Args()\n\t\t\tif len(cmds) \u003e 0 {\n\t\t\t\treturn fmt.Errorf(\"unknown command %+s\", cmds[0])\n\t\t\t}\n\n\t\t\t// short-circuit on help\n\t\t\thelp, err := cleanFlagSet.GetBool(\"help\")\n\t\t\tif err != nil {\n\t\t\t\treturn errors.New(`\"help\" flag is non-bool, programmer error, please correct`)\n\t\t\t}\n\t\t\tif help {\n\t\t\t\treturn cmd.Help()\n\t\t\t}\n\n\t\t\t// short-circuit on verflag\n\t\t\tverflag.PrintAndExitIfRequested()\n\n\t\t\t// set feature gates from initial flags-based config\n\t\t\tif err := utilfeature.DefaultMutableFeatureGate.SetFromMap(kubeletConfig.FeatureGates); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to set feature gates from initial flags-based config: %w\", err)\n\t\t\t}\n\n\t\t\t// validate the initial KubeletFlags\n\t\t\tif err := options.ValidateKubeletFlags(kubeletFlags); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to validate kubelet flags: %w\", err)\n\t\t\t}\n\n\t\t\tif cleanFlagSet.Changed(\"pod-infra-container-image\") {\n\t\t\t\tklog.InfoS(\"--pod-infra-container-image will not be pruned by the image garbage collector in kubelet and should also be set in the remote runtime\")\n\t\t\t}\n\n\t\t\t// load kubelet config file, if provided\n\t\t\tif configFile := kubeletFlags.KubeletConfigFile; len(configFile) \u003e 0 {\n\t\t\t\tkubeletConfig, err = loadConfigFile(configFile)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"failed to load kubelet config file, error: %w, path: %s\", err, configFile)\n\t\t\t\t}\n\t\t\t\t// We must enforce flag precedence by re-parsing the command line into the new object.\n\t\t\t\t// This is necessary to preserve backwards-compatibility across binary upgrades.\n\t\t\t\t// See issue #56171 for more details.\n\t\t\t\tif err := kubeletConfigFlagPrecedence(kubeletConfig, args); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"failed to precedence kubeletConfigFlag: %w\", err)\n\t\t\t\t}\n\t\t\t\t// update feature gates based on new config\n\t\t\t\tif err := utilfeature.DefaultMutableFeatureGate.SetFromMap(kubeletConfig.FeatureGates); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"failed to set feature gates from initial flags-based config: %w\", err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Config and flags parsed, now we can initialize logging.\n\t\t\tlogs.InitLogs()\n\t\t\tif err := logsapi.ValidateAndApplyAsField(\u0026kubeletConfig.Logging, utilfeature.DefaultFeatureGate, field.NewPath(\"logging\")); err != nil {\n\t\t\t\treturn fmt.Errorf(\"initialize logging: %v\", err)\n\t\t\t}\n\t\t\tcliflag.PrintFlags(cleanFlagSet)\n\n\t\t\t// We always validate the local configuration (command line + config file).\n\t\t\t// This is the default \"last-known-good\" config for dynamic config, and must always remain valid.\n\t\t\tif err := kubeletconfigvalidation.ValidateKubeletConfiguration(kubeletConfig, utilfeature.DefaultFeatureGate); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to validate kubelet configuration, error: %w, path: %s\", err, kubeletConfig)\n\t\t\t}\n\n\t\t\tif (kubeletConfig.KubeletCgroups != \"\" \u0026\u0026 kubeletConfig.KubeReservedCgroup != \"\") \u0026\u0026 (strings.Index(kubeletConfig.KubeletCgroups, kubeletConfig.KubeReservedCgroup) != 0) {\n\t\t\t\tklog.InfoS(\"unsupported configuration:KubeletCgroups is not within KubeReservedCgroup\")\n\t\t\t}\n\n\t\t\t// construct a KubeletServer from kubeletFlags and kubeletConfig\n\t\t\tkubeletServer := \u0026options.KubeletServer{\n\t\t\t\tKubeletFlags: *kubeletFlags,\n\t\t\t\tKubeletConfiguration: *kubeletConfig,\n\t\t\t}\n\n\t\t\t// use kubeletServer to construct the default KubeletDeps\n\t\t\tkubeletDeps, err := UnsecuredDependencies(kubeletServer, utilfeature.DefaultFeatureGate)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to construct kubelet dependencies: %w\", err)\n\t\t\t}\n\n\t\t\tif err := checkPermissions(); err != nil {\n\t\t\t\tklog.ErrorS(err, \"kubelet running with insufficient permissions\")\n\t\t\t}\n\n\t\t\t// make the kubelet's config safe for logging\n\t\t\tconfig := kubeletServer.KubeletConfiguration.DeepCopy()\n\t\t\tfor k := range config.StaticPodURLHeader {\n\t\t\t\tconfig.StaticPodURLHeader[k] = []string{\"\u003cmasked\u003e\"}\n\t\t\t}\n\t\t\t// log the kubelet's config for inspection\n\t\t\tklog.V(5).InfoS(\"KubeletConfiguration\", \"configuration\", config)\n\n\t\t\t// set up signal context for kubelet shutdown\n\t\t\tctx := genericapiserver.SetupSignalContext()\n\n\t\t\tutilfeature.DefaultMutableFeatureGate.AddMetrics()\n\t\t\t// run the kubelet\n\t\t\treturn Run(ctx, kubeletServer, kubeletDeps, utilfeature.DefaultFeatureGate)\n\t\t},\n\t}\n\n\t// keep cleanFlagSet separate, so Cobra doesn't pollute it with the global flags\n\tkubeletFlags.AddFlags(cleanFlagSet)\n\toptions.AddKubeletConfigFlags(cleanFlagSet, kubeletConfig)\n\toptions.AddGlobalFlags(cleanFlagSet)\n\tcleanFlagSet.BoolP(\"help\", \"h\", false, fmt.Sprintf(\"help for %s\", cmd.Name()))\n\n\t// ugly, but necessary, because Cobra's default UsageFunc and HelpFunc pollute the flagset with global flags\n\tconst usageFmt = \"Usage:\\n %s\\n\\nFlags:\\n%s\"\n\tcmd.SetUsageFunc(func(cmd *cobra.Command) error {\n\t\tfmt.Fprintf(cmd.OutOrStderr(), usageFmt, cmd.UseLine(), cleanFlagSet.FlagUsagesWrapped(2))\n\t\treturn nil\n\t})\n\tcmd.SetHelpFunc(func(cmd *cobra.Command, args []string) {\n\t\tfmt.Fprintf(cmd.OutOrStdout(), \"%s\\n\\n\"+usageFmt, cmd.Long, cmd.UseLine(), cleanFlagSet.FlagUsagesWrapped(2))\n\t})\n\n\treturn cmd\n}","line":{"from":124,"to":287}} {"id":100001599,"name":"newFlagSetWithGlobals","signature":"func newFlagSetWithGlobals() *pflag.FlagSet","file":"cmd/kubelet/app/server.go","code":"// newFlagSetWithGlobals constructs a new pflag.FlagSet with global flags registered\n// on it.\nfunc newFlagSetWithGlobals() *pflag.FlagSet {\n\tfs := pflag.NewFlagSet(\"\", pflag.ExitOnError)\n\t// set the normalize func, similar to k8s.io/component-base/cli//flags.go:InitFlags\n\tfs.SetNormalizeFunc(cliflag.WordSepNormalizeFunc)\n\t// explicitly add flags from libs that register global flags\n\toptions.AddGlobalFlags(fs)\n\treturn fs\n}","line":{"from":289,"to":298}} {"id":100001600,"name":"newFakeFlagSet","signature":"func newFakeFlagSet(fs *pflag.FlagSet) *pflag.FlagSet","file":"cmd/kubelet/app/server.go","code":"// newFakeFlagSet constructs a pflag.FlagSet with the same flags as fs, but where\n// all values have noop Set implementations\nfunc newFakeFlagSet(fs *pflag.FlagSet) *pflag.FlagSet {\n\tret := pflag.NewFlagSet(\"\", pflag.ExitOnError)\n\tret.SetNormalizeFunc(fs.GetNormalizeFunc())\n\tfs.VisitAll(func(f *pflag.Flag) {\n\t\tret.VarP(cliflag.NoOp{}, f.Name, f.Shorthand, f.Usage)\n\t})\n\treturn ret\n}","line":{"from":300,"to":309}} {"id":100001601,"name":"kubeletConfigFlagPrecedence","signature":"func kubeletConfigFlagPrecedence(kc *kubeletconfiginternal.KubeletConfiguration, args []string) error","file":"cmd/kubelet/app/server.go","code":"// kubeletConfigFlagPrecedence re-parses flags over the KubeletConfiguration object.\n// We must enforce flag precedence by re-parsing the command line into the new object.\n// This is necessary to preserve backwards-compatibility across binary upgrades.\n// See issue #56171 for more details.\nfunc kubeletConfigFlagPrecedence(kc *kubeletconfiginternal.KubeletConfiguration, args []string) error {\n\t// We use a throwaway kubeletFlags and a fake global flagset to avoid double-parses,\n\t// as some Set implementations accumulate values from multiple flag invocations.\n\tfs := newFakeFlagSet(newFlagSetWithGlobals())\n\t// register throwaway KubeletFlags\n\toptions.NewKubeletFlags().AddFlags(fs)\n\t// register new KubeletConfiguration\n\toptions.AddKubeletConfigFlags(fs, kc)\n\t// Remember original feature gates, so we can merge with flag gates later\n\toriginal := kc.FeatureGates\n\t// avoid duplicate printing the flag deprecation warnings during re-parsing\n\tfs.SetOutput(io.Discard)\n\t// re-parse flags\n\tif err := fs.Parse(args); err != nil {\n\t\treturn err\n\t}\n\t// Add back feature gates that were set in the original kc, but not in flags\n\tfor k, v := range original {\n\t\tif _, ok := kc.FeatureGates[k]; !ok {\n\t\t\tkc.FeatureGates[k] = v\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":311,"to":338}} {"id":100001602,"name":"loadConfigFile","signature":"func loadConfigFile(name string) (*kubeletconfiginternal.KubeletConfiguration, error)","file":"cmd/kubelet/app/server.go","code":"func loadConfigFile(name string) (*kubeletconfiginternal.KubeletConfiguration, error) {\n\tconst errFmt = \"failed to load Kubelet config file %s, error %v\"\n\t// compute absolute path based on current working dir\n\tkubeletConfigFile, err := filepath.Abs(name)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(errFmt, name, err)\n\t}\n\tloader, err := configfiles.NewFsLoader(\u0026utilfs.DefaultFs{}, kubeletConfigFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(errFmt, name, err)\n\t}\n\tkc, err := loader.Load()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(errFmt, name, err)\n\t}\n\n\t// EvictionHard may be nil if it was not set in kubelet's config file.\n\t// EvictionHard can have OS-specific fields, which is why there's no default value for it.\n\t// See: https://github.com/kubernetes/kubernetes/pull/110263\n\tif kc.EvictionHard == nil {\n\t\tkc.EvictionHard = eviction.DefaultEvictionHard\n\t}\n\treturn kc, err\n}","line":{"from":340,"to":363}} {"id":100001603,"name":"UnsecuredDependencies","signature":"func UnsecuredDependencies(s *options.KubeletServer, featureGate featuregate.FeatureGate) (*kubelet.Dependencies, error)","file":"cmd/kubelet/app/server.go","code":"// UnsecuredDependencies returns a Dependencies suitable for being run, or an error if the server setup\n// is not valid. It will not start any background processes, and does not include authentication/authorization\nfunc UnsecuredDependencies(s *options.KubeletServer, featureGate featuregate.FeatureGate) (*kubelet.Dependencies, error) {\n\t// Initialize the TLS Options\n\ttlsOptions, err := InitializeTLS(\u0026s.KubeletFlags, \u0026s.KubeletConfiguration)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmounter := mount.New(s.ExperimentalMounterPath)\n\tsubpather := subpath.New(mounter)\n\thu := hostutil.NewHostUtil()\n\tvar pluginRunner = exec.New()\n\n\tplugins, err := ProbeVolumePlugins(featureGate)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttp := oteltrace.NewNoopTracerProvider()\n\tif utilfeature.DefaultFeatureGate.Enabled(features.KubeletTracing) {\n\t\ttp, err = newTracerProvider(s)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn \u0026kubelet.Dependencies{\n\t\tAuth: nil, // default does not enforce auth[nz]\n\t\tCAdvisorInterface: nil, // cadvisor.New launches background processes (bg http.ListenAndServe, and some bg cleaners), not set here\n\t\tCloud: nil, // cloud provider might start background processes\n\t\tContainerManager: nil,\n\t\tKubeClient: nil,\n\t\tHeartbeatClient: nil,\n\t\tEventClient: nil,\n\t\tTracerProvider: tp,\n\t\tHostUtil: hu,\n\t\tMounter: mounter,\n\t\tSubpather: subpather,\n\t\tOOMAdjuster: oom.NewOOMAdjuster(),\n\t\tOSInterface: kubecontainer.RealOS{},\n\t\tVolumePlugins: plugins,\n\t\tDynamicPluginProber: GetDynamicPluginProber(s.VolumePluginDir, pluginRunner),\n\t\tTLSOptions: tlsOptions}, nil\n}","line":{"from":365,"to":407}} {"id":100001604,"name":"Run","signature":"func Run(ctx context.Context, s *options.KubeletServer, kubeDeps *kubelet.Dependencies, featureGate featuregate.FeatureGate) error","file":"cmd/kubelet/app/server.go","code":"// Run runs the specified KubeletServer with the given Dependencies. This should never exit.\n// The kubeDeps argument may be nil - if so, it is initialized from the settings on KubeletServer.\n// Otherwise, the caller is assumed to have set up the Dependencies object and a default one will\n// not be generated.\nfunc Run(ctx context.Context, s *options.KubeletServer, kubeDeps *kubelet.Dependencies, featureGate featuregate.FeatureGate) error {\n\t// To help debugging, immediately log version\n\tklog.InfoS(\"Kubelet version\", \"kubeletVersion\", version.Get())\n\n\tklog.InfoS(\"Golang settings\", \"GOGC\", os.Getenv(\"GOGC\"), \"GOMAXPROCS\", os.Getenv(\"GOMAXPROCS\"), \"GOTRACEBACK\", os.Getenv(\"GOTRACEBACK\"))\n\n\tif err := initForOS(s.KubeletFlags.WindowsService, s.KubeletFlags.WindowsPriorityClass); err != nil {\n\t\treturn fmt.Errorf(\"failed OS init: %w\", err)\n\t}\n\tif err := run(ctx, s, kubeDeps, featureGate); err != nil {\n\t\treturn fmt.Errorf(\"failed to run Kubelet: %w\", err)\n\t}\n\treturn nil\n}","line":{"from":409,"to":426}} {"id":100001605,"name":"setConfigz","signature":"func setConfigz(cz *configz.Config, kc *kubeletconfiginternal.KubeletConfiguration) error","file":"cmd/kubelet/app/server.go","code":"func setConfigz(cz *configz.Config, kc *kubeletconfiginternal.KubeletConfiguration) error {\n\tscheme, _, err := kubeletscheme.NewSchemeAndCodecs()\n\tif err != nil {\n\t\treturn err\n\t}\n\tversioned := kubeletconfigv1beta1.KubeletConfiguration{}\n\tif err := scheme.Convert(kc, \u0026versioned, nil); err != nil {\n\t\treturn err\n\t}\n\tcz.Set(versioned)\n\treturn nil\n}","line":{"from":428,"to":439}} {"id":100001606,"name":"initConfigz","signature":"func initConfigz(kc *kubeletconfiginternal.KubeletConfiguration) error","file":"cmd/kubelet/app/server.go","code":"func initConfigz(kc *kubeletconfiginternal.KubeletConfiguration) error {\n\tcz, err := configz.New(\"kubeletconfig\")\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to register configz\")\n\t\treturn err\n\t}\n\tif err := setConfigz(cz, kc); err != nil {\n\t\tklog.ErrorS(err, \"Failed to register config\")\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":441,"to":452}} {"id":100001607,"name":"makeEventRecorder","signature":"func makeEventRecorder(kubeDeps *kubelet.Dependencies, nodeName types.NodeName)","file":"cmd/kubelet/app/server.go","code":"// makeEventRecorder sets up kubeDeps.Recorder if it's nil. It's a no-op otherwise.\nfunc makeEventRecorder(kubeDeps *kubelet.Dependencies, nodeName types.NodeName) {\n\tif kubeDeps.Recorder != nil {\n\t\treturn\n\t}\n\teventBroadcaster := record.NewBroadcaster()\n\tkubeDeps.Recorder = eventBroadcaster.NewRecorder(legacyscheme.Scheme, v1.EventSource{Component: componentKubelet, Host: string(nodeName)})\n\teventBroadcaster.StartStructuredLogging(3)\n\tif kubeDeps.EventClient != nil {\n\t\tklog.V(4).InfoS(\"Sending events to api server\")\n\t\teventBroadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: kubeDeps.EventClient.Events(\"\")})\n\t} else {\n\t\tklog.InfoS(\"No api server defined - no events will be sent to API server\")\n\t}\n}","line":{"from":454,"to":468}} {"id":100001608,"name":"getReservedCPUs","signature":"func getReservedCPUs(machineInfo *cadvisorapi.MachineInfo, cpus string) (cpuset.CPUSet, error)","file":"cmd/kubelet/app/server.go","code":"func getReservedCPUs(machineInfo *cadvisorapi.MachineInfo, cpus string) (cpuset.CPUSet, error) {\n\temptyCPUSet := cpuset.New()\n\n\tif cpus == \"\" {\n\t\treturn emptyCPUSet, nil\n\t}\n\n\ttopo, err := topology.Discover(machineInfo)\n\tif err != nil {\n\t\treturn emptyCPUSet, fmt.Errorf(\"unable to discover CPU topology info: %s\", err)\n\t}\n\treservedCPUSet, err := cpuset.Parse(cpus)\n\tif err != nil {\n\t\treturn emptyCPUSet, fmt.Errorf(\"unable to parse reserved-cpus list: %s\", err)\n\t}\n\tallCPUSet := topo.CPUDetails.CPUs()\n\tif !reservedCPUSet.IsSubsetOf(allCPUSet) {\n\t\treturn emptyCPUSet, fmt.Errorf(\"reserved-cpus: %s is not a subset of online-cpus: %s\", cpus, allCPUSet.String())\n\t}\n\treturn reservedCPUSet, nil\n}","line":{"from":470,"to":490}} {"id":100001609,"name":"run","signature":"func run(ctx context.Context, s *options.KubeletServer, kubeDeps *kubelet.Dependencies, featureGate featuregate.FeatureGate) (err error)","file":"cmd/kubelet/app/server.go","code":"func run(ctx context.Context, s *options.KubeletServer, kubeDeps *kubelet.Dependencies, featureGate featuregate.FeatureGate) (err error) {\n\t// Set global feature gates based on the value on the initial KubeletServer\n\terr = utilfeature.DefaultMutableFeatureGate.SetFromMap(s.KubeletConfiguration.FeatureGates)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// validate the initial KubeletServer (we set feature gates first, because this validation depends on feature gates)\n\tif err := options.ValidateKubeletServer(s); err != nil {\n\t\treturn err\n\t}\n\n\t// Warn if MemoryQoS enabled with cgroups v1\n\tif utilfeature.DefaultFeatureGate.Enabled(features.MemoryQoS) \u0026\u0026\n\t\t!isCgroup2UnifiedMode() {\n\t\tklog.InfoS(\"Warning: MemoryQoS feature only works with cgroups v2 on Linux, but enabled with cgroups v1\")\n\t}\n\t// Obtain Kubelet Lock File\n\tif s.ExitOnLockContention \u0026\u0026 s.LockFilePath == \"\" {\n\t\treturn errors.New(\"cannot exit on lock file contention: no lock file specified\")\n\t}\n\tdone := make(chan struct{})\n\tif s.LockFilePath != \"\" {\n\t\tklog.InfoS(\"Acquiring file lock\", \"path\", s.LockFilePath)\n\t\tif err := flock.Acquire(s.LockFilePath); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to acquire file lock on %q: %w\", s.LockFilePath, err)\n\t\t}\n\t\tif s.ExitOnLockContention {\n\t\t\tklog.InfoS(\"Watching for inotify events\", \"path\", s.LockFilePath)\n\t\t\tif err := watchForLockfileContention(s.LockFilePath, done); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// Register current configuration with /configz endpoint\n\terr = initConfigz(\u0026s.KubeletConfiguration)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to register kubelet configuration with configz\")\n\t}\n\n\tif len(s.ShowHiddenMetricsForVersion) \u003e 0 {\n\t\tmetrics.SetShowHidden()\n\t}\n\n\t// About to get clients and such, detect standaloneMode\n\tstandaloneMode := true\n\tif len(s.KubeConfig) \u003e 0 {\n\t\tstandaloneMode = false\n\t}\n\n\tif kubeDeps == nil {\n\t\tkubeDeps, err = UnsecuredDependencies(s, featureGate)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif kubeDeps.Cloud == nil {\n\t\tif !cloudprovider.IsExternal(s.CloudProvider) {\n\t\t\tcloudprovider.DeprecationWarningForProvider(s.CloudProvider)\n\t\t\tcloud, err := cloudprovider.InitCloudProvider(s.CloudProvider, s.CloudConfigFile)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif cloud != nil {\n\t\t\t\tklog.V(2).InfoS(\"Successfully initialized cloud provider\", \"cloudProvider\", s.CloudProvider, \"cloudConfigFile\", s.CloudConfigFile)\n\t\t\t}\n\t\t\tkubeDeps.Cloud = cloud\n\t\t}\n\t}\n\n\thostName, err := nodeutil.GetHostname(s.HostnameOverride)\n\tif err != nil {\n\t\treturn err\n\t}\n\tnodeName, err := getNodeName(kubeDeps.Cloud, hostName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// if in standalone mode, indicate as much by setting all clients to nil\n\tswitch {\n\tcase standaloneMode:\n\t\tkubeDeps.KubeClient = nil\n\t\tkubeDeps.EventClient = nil\n\t\tkubeDeps.HeartbeatClient = nil\n\t\tklog.InfoS(\"Standalone mode, no API client\")\n\n\tcase kubeDeps.KubeClient == nil, kubeDeps.EventClient == nil, kubeDeps.HeartbeatClient == nil:\n\t\tclientConfig, onHeartbeatFailure, err := buildKubeletClientConfig(ctx, s, kubeDeps.TracerProvider, nodeName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif onHeartbeatFailure == nil {\n\t\t\treturn errors.New(\"onHeartbeatFailure must be a valid function other than nil\")\n\t\t}\n\t\tkubeDeps.OnHeartbeatFailure = onHeartbeatFailure\n\n\t\tkubeDeps.KubeClient, err = clientset.NewForConfig(clientConfig)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to initialize kubelet client: %w\", err)\n\t\t}\n\n\t\t// make a separate client for events\n\t\teventClientConfig := *clientConfig\n\t\teventClientConfig.QPS = float32(s.EventRecordQPS)\n\t\teventClientConfig.Burst = int(s.EventBurst)\n\t\tkubeDeps.EventClient, err = v1core.NewForConfig(\u0026eventClientConfig)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to initialize kubelet event client: %w\", err)\n\t\t}\n\n\t\t// make a separate client for heartbeat with throttling disabled and a timeout attached\n\t\theartbeatClientConfig := *clientConfig\n\t\theartbeatClientConfig.Timeout = s.KubeletConfiguration.NodeStatusUpdateFrequency.Duration\n\t\t// The timeout is the minimum of the lease duration and status update frequency\n\t\tleaseTimeout := time.Duration(s.KubeletConfiguration.NodeLeaseDurationSeconds) * time.Second\n\t\tif heartbeatClientConfig.Timeout \u003e leaseTimeout {\n\t\t\theartbeatClientConfig.Timeout = leaseTimeout\n\t\t}\n\n\t\theartbeatClientConfig.QPS = float32(-1)\n\t\tkubeDeps.HeartbeatClient, err = clientset.NewForConfig(\u0026heartbeatClientConfig)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to initialize kubelet heartbeat client: %w\", err)\n\t\t}\n\t}\n\n\tif kubeDeps.Auth == nil {\n\t\tauth, runAuthenticatorCAReload, err := BuildAuth(nodeName, kubeDeps.KubeClient, s.KubeletConfiguration)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tkubeDeps.Auth = auth\n\t\trunAuthenticatorCAReload(ctx.Done())\n\t}\n\n\tvar cgroupRoots []string\n\tnodeAllocatableRoot := cm.NodeAllocatableRoot(s.CgroupRoot, s.CgroupsPerQOS, s.CgroupDriver)\n\tcgroupRoots = append(cgroupRoots, nodeAllocatableRoot)\n\tkubeletCgroup, err := cm.GetKubeletContainer(s.KubeletCgroups)\n\tif err != nil {\n\t\tklog.InfoS(\"Failed to get the kubelet's cgroup. Kubelet system container metrics may be missing.\", \"err\", err)\n\t} else if kubeletCgroup != \"\" {\n\t\tcgroupRoots = append(cgroupRoots, kubeletCgroup)\n\t}\n\n\tif s.RuntimeCgroups != \"\" {\n\t\t// RuntimeCgroups is optional, so ignore if it isn't specified\n\t\tcgroupRoots = append(cgroupRoots, s.RuntimeCgroups)\n\t}\n\n\tif s.SystemCgroups != \"\" {\n\t\t// SystemCgroups is optional, so ignore if it isn't specified\n\t\tcgroupRoots = append(cgroupRoots, s.SystemCgroups)\n\t}\n\n\tif kubeDeps.CAdvisorInterface == nil {\n\t\timageFsInfoProvider := cadvisor.NewImageFsInfoProvider(s.ContainerRuntimeEndpoint)\n\t\tkubeDeps.CAdvisorInterface, err = cadvisor.New(imageFsInfoProvider, s.RootDirectory, cgroupRoots, cadvisor.UsingLegacyCadvisorStats(s.ContainerRuntimeEndpoint), s.LocalStorageCapacityIsolation)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Setup event recorder if required.\n\tmakeEventRecorder(kubeDeps, nodeName)\n\n\tif kubeDeps.ContainerManager == nil {\n\t\tif s.CgroupsPerQOS \u0026\u0026 s.CgroupRoot == \"\" {\n\t\t\tklog.InfoS(\"--cgroups-per-qos enabled, but --cgroup-root was not specified. defaulting to /\")\n\t\t\ts.CgroupRoot = \"/\"\n\t\t}\n\n\t\tmachineInfo, err := kubeDeps.CAdvisorInterface.MachineInfo()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treservedSystemCPUs, err := getReservedCPUs(machineInfo, s.ReservedSystemCPUs)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif reservedSystemCPUs.Size() \u003e 0 {\n\t\t\t// at cmd option validation phase it is tested either --system-reserved-cgroup or --kube-reserved-cgroup is specified, so overwrite should be ok\n\t\t\tklog.InfoS(\"Option --reserved-cpus is specified, it will overwrite the cpu setting in KubeReserved and SystemReserved\", \"kubeReservedCPUs\", s.KubeReserved, \"systemReservedCPUs\", s.SystemReserved)\n\t\t\tif s.KubeReserved != nil {\n\t\t\t\tdelete(s.KubeReserved, \"cpu\")\n\t\t\t}\n\t\t\tif s.SystemReserved == nil {\n\t\t\t\ts.SystemReserved = make(map[string]string)\n\t\t\t}\n\t\t\ts.SystemReserved[\"cpu\"] = strconv.Itoa(reservedSystemCPUs.Size())\n\t\t\tklog.InfoS(\"After cpu setting is overwritten\", \"kubeReservedCPUs\", s.KubeReserved, \"systemReservedCPUs\", s.SystemReserved)\n\t\t}\n\n\t\tkubeReserved, err := parseResourceList(s.KubeReserved)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"--kube-reserved value failed to parse: %w\", err)\n\t\t}\n\t\tsystemReserved, err := parseResourceList(s.SystemReserved)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"--system-reserved value failed to parse: %w\", err)\n\t\t}\n\t\tvar hardEvictionThresholds []evictionapi.Threshold\n\t\t// If the user requested to ignore eviction thresholds, then do not set valid values for hardEvictionThresholds here.\n\t\tif !s.ExperimentalNodeAllocatableIgnoreEvictionThreshold {\n\t\t\thardEvictionThresholds, err = eviction.ParseThresholdConfig([]string{}, s.EvictionHard, nil, nil, nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\texperimentalQOSReserved, err := cm.ParseQOSReserved(s.QOSReserved)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"--qos-reserved value failed to parse: %w\", err)\n\t\t}\n\n\t\tvar cpuManagerPolicyOptions map[string]string\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.CPUManagerPolicyOptions) {\n\t\t\tcpuManagerPolicyOptions = s.CPUManagerPolicyOptions\n\t\t} else if s.CPUManagerPolicyOptions != nil {\n\t\t\treturn fmt.Errorf(\"CPU Manager policy options %v require feature gates %q, %q enabled\",\n\t\t\t\ts.CPUManagerPolicyOptions, features.CPUManager, features.CPUManagerPolicyOptions)\n\t\t}\n\n\t\tvar topologyManagerPolicyOptions map[string]string\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.TopologyManagerPolicyOptions) {\n\t\t\ttopologyManagerPolicyOptions = s.TopologyManagerPolicyOptions\n\t\t} else if s.TopologyManagerPolicyOptions != nil {\n\t\t\treturn fmt.Errorf(\"topology manager policy options %v require feature gates %q enabled\",\n\t\t\t\ts.TopologyManagerPolicyOptions, features.TopologyManagerPolicyOptions)\n\t\t}\n\n\t\tkubeDeps.ContainerManager, err = cm.NewContainerManager(\n\t\t\tkubeDeps.Mounter,\n\t\t\tkubeDeps.CAdvisorInterface,\n\t\t\tcm.NodeConfig{\n\t\t\t\tRuntimeCgroupsName: s.RuntimeCgroups,\n\t\t\t\tSystemCgroupsName: s.SystemCgroups,\n\t\t\t\tKubeletCgroupsName: s.KubeletCgroups,\n\t\t\t\tKubeletOOMScoreAdj: s.OOMScoreAdj,\n\t\t\t\tCgroupsPerQOS: s.CgroupsPerQOS,\n\t\t\t\tCgroupRoot: s.CgroupRoot,\n\t\t\t\tCgroupDriver: s.CgroupDriver,\n\t\t\t\tKubeletRootDir: s.RootDirectory,\n\t\t\t\tProtectKernelDefaults: s.ProtectKernelDefaults,\n\t\t\t\tNodeAllocatableConfig: cm.NodeAllocatableConfig{\n\t\t\t\t\tKubeReservedCgroupName: s.KubeReservedCgroup,\n\t\t\t\t\tSystemReservedCgroupName: s.SystemReservedCgroup,\n\t\t\t\t\tEnforceNodeAllocatable: sets.NewString(s.EnforceNodeAllocatable...),\n\t\t\t\t\tKubeReserved: kubeReserved,\n\t\t\t\t\tSystemReserved: systemReserved,\n\t\t\t\t\tReservedSystemCPUs: reservedSystemCPUs,\n\t\t\t\t\tHardEvictionThresholds: hardEvictionThresholds,\n\t\t\t\t},\n\t\t\t\tQOSReserved: *experimentalQOSReserved,\n\t\t\t\tCPUManagerPolicy: s.CPUManagerPolicy,\n\t\t\t\tCPUManagerPolicyOptions: cpuManagerPolicyOptions,\n\t\t\t\tCPUManagerReconcilePeriod: s.CPUManagerReconcilePeriod.Duration,\n\t\t\t\tExperimentalMemoryManagerPolicy: s.MemoryManagerPolicy,\n\t\t\t\tExperimentalMemoryManagerReservedMemory: s.ReservedMemory,\n\t\t\t\tPodPidsLimit: s.PodPidsLimit,\n\t\t\t\tEnforceCPULimits: s.CPUCFSQuota,\n\t\t\t\tCPUCFSQuotaPeriod: s.CPUCFSQuotaPeriod.Duration,\n\t\t\t\tTopologyManagerPolicy: s.TopologyManagerPolicy,\n\t\t\t\tTopologyManagerScope: s.TopologyManagerScope,\n\t\t\t\tExperimentalTopologyManagerPolicyOptions: topologyManagerPolicyOptions,\n\t\t\t},\n\t\t\ts.FailSwapOn,\n\t\t\tkubeDeps.Recorder,\n\t\t\tkubeDeps.KubeClient,\n\t\t)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif kubeDeps.PodStartupLatencyTracker == nil {\n\t\tkubeDeps.PodStartupLatencyTracker = kubeletutil.NewPodStartupLatencyTracker()\n\t}\n\n\t// TODO(vmarmol): Do this through container config.\n\toomAdjuster := kubeDeps.OOMAdjuster\n\tif err := oomAdjuster.ApplyOOMScoreAdj(0, int(s.OOMScoreAdj)); err != nil {\n\t\tklog.InfoS(\"Failed to ApplyOOMScoreAdj\", \"err\", err)\n\t}\n\n\terr = kubelet.PreInitRuntimeService(\u0026s.KubeletConfiguration, kubeDeps)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := RunKubelet(s, kubeDeps, s.RunOnce); err != nil {\n\t\treturn err\n\t}\n\n\tif s.HealthzPort \u003e 0 {\n\t\tmux := http.NewServeMux()\n\t\thealthz.InstallHandler(mux)\n\t\tgo wait.Until(func() {\n\t\t\terr := http.ListenAndServe(net.JoinHostPort(s.HealthzBindAddress, strconv.Itoa(int(s.HealthzPort))), mux)\n\t\t\tif err != nil {\n\t\t\t\tklog.ErrorS(err, \"Failed to start healthz server\")\n\t\t\t}\n\t\t}, 5*time.Second, wait.NeverStop)\n\t}\n\n\tif s.RunOnce {\n\t\treturn nil\n\t}\n\n\t// If systemd is used, notify it that we have started\n\tgo daemon.SdNotify(false, \"READY=1\")\n\n\tselect {\n\tcase \u003c-done:\n\t\tbreak\n\tcase \u003c-ctx.Done():\n\t\tbreak\n\t}\n\n\treturn nil\n}","line":{"from":492,"to":814}} {"id":100001610,"name":"buildKubeletClientConfig","signature":"func buildKubeletClientConfig(ctx context.Context, s *options.KubeletServer, tp oteltrace.TracerProvider, nodeName types.NodeName) (*restclient.Config, func(), error)","file":"cmd/kubelet/app/server.go","code":"// buildKubeletClientConfig constructs the appropriate client config for the kubelet depending on whether\n// bootstrapping is enabled or client certificate rotation is enabled.\nfunc buildKubeletClientConfig(ctx context.Context, s *options.KubeletServer, tp oteltrace.TracerProvider, nodeName types.NodeName) (*restclient.Config, func(), error) {\n\tif s.RotateCertificates {\n\t\t// Rules for client rotation and the handling of kube config files:\n\t\t//\n\t\t// 1. If the client provides only a kubeconfig file, we must use that as the initial client\n\t\t// kubeadm needs the initial data in the kubeconfig to be placed into the cert store\n\t\t// 2. If the client provides only an initial bootstrap kubeconfig file, we must create a\n\t\t// kubeconfig file at the target location that points to the cert store, but until\n\t\t// the file is present the client config will have no certs\n\t\t// 3. If the client provides both and the kubeconfig is valid, we must ignore the bootstrap\n\t\t// kubeconfig.\n\t\t// 4. If the client provides both and the kubeconfig is expired or otherwise invalid, we must\n\t\t// replace the kubeconfig with a new file that points to the cert dir\n\t\t//\n\t\t// The desired configuration for bootstrapping is to use a bootstrap kubeconfig and to have\n\t\t// the kubeconfig file be managed by this process. For backwards compatibility with kubeadm,\n\t\t// which provides a high powered kubeconfig on the master with cert/key data, we must\n\t\t// bootstrap the cert manager with the contents of the initial client config.\n\n\t\tklog.InfoS(\"Client rotation is on, will bootstrap in background\")\n\t\tcertConfig, clientConfig, err := bootstrap.LoadClientConfig(s.KubeConfig, s.BootstrapKubeconfig, s.CertDirectory)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\t// use the correct content type for cert rotation, but don't set QPS\n\t\tsetContentTypeForClient(certConfig, s.ContentType)\n\n\t\tkubeClientConfigOverrides(s, clientConfig)\n\n\t\tclientCertificateManager, err := buildClientCertificateManager(certConfig, clientConfig, s.CertDirectory, nodeName)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\tlegacyregistry.RawMustRegister(metrics.NewGaugeFunc(\n\t\t\t\u0026metrics.GaugeOpts{\n\t\t\t\tSubsystem: kubeletmetrics.KubeletSubsystem,\n\t\t\t\tName: \"certificate_manager_client_ttl_seconds\",\n\t\t\t\tHelp: \"Gauge of the TTL (time-to-live) of the Kubelet's client certificate. \" +\n\t\t\t\t\t\"The value is in seconds until certificate expiry (negative if already expired). \" +\n\t\t\t\t\t\"If client certificate is invalid or unused, the value will be +INF.\",\n\t\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t\t},\n\t\t\tfunc() float64 {\n\t\t\t\tif c := clientCertificateManager.Current(); c != nil \u0026\u0026 c.Leaf != nil {\n\t\t\t\t\treturn math.Trunc(time.Until(c.Leaf.NotAfter).Seconds())\n\t\t\t\t}\n\t\t\t\treturn math.Inf(1)\n\t\t\t},\n\t\t))\n\n\t\t// the rotating transport will use the cert from the cert manager instead of these files\n\t\ttransportConfig := restclient.AnonymousClientConfig(clientConfig)\n\n\t\t// we set exitAfter to five minutes because we use this client configuration to request new certs - if we are unable\n\t\t// to request new certs, we will be unable to continue normal operation. Exiting the process allows a wrapper\n\t\t// or the bootstrapping credentials to potentially lay down new initial config.\n\t\tcloseAllConns, err := kubeletcertificate.UpdateTransport(wait.NeverStop, transportConfig, clientCertificateManager, 5*time.Minute)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tvar onHeartbeatFailure func()\n\t\t// Kubelet needs to be able to recover from stale http connections.\n\t\t// HTTP2 has a mechanism to detect broken connections by sending periodical pings.\n\t\t// HTTP1 only can have one persistent connection, and it will close all Idle connections\n\t\t// once the Kubelet heartbeat fails. However, since there are many edge cases that we can't\n\t\t// control, users can still opt-in to the previous behavior for closing the connections by\n\t\t// setting the environment variable DISABLE_HTTP2.\n\t\tif s := os.Getenv(\"DISABLE_HTTP2\"); len(s) \u003e 0 {\n\t\t\tklog.InfoS(\"HTTP2 has been explicitly disabled, Kubelet will forcefully close active connections on heartbeat failures\")\n\t\t\tonHeartbeatFailure = closeAllConns\n\t\t} else {\n\t\t\tonHeartbeatFailure = func() { utilnet.CloseIdleConnectionsFor(transportConfig.Transport) }\n\t\t}\n\n\t\tklog.V(2).InfoS(\"Starting client certificate rotation\")\n\t\tclientCertificateManager.Start()\n\n\t\treturn transportConfig, onHeartbeatFailure, nil\n\t}\n\n\tif len(s.BootstrapKubeconfig) \u003e 0 {\n\t\tif err := bootstrap.LoadClientCert(ctx, s.KubeConfig, s.BootstrapKubeconfig, s.CertDirectory, nodeName); err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\tclientConfig, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(\n\t\t\u0026clientcmd.ClientConfigLoadingRules{ExplicitPath: s.KubeConfig},\n\t\t\u0026clientcmd.ConfigOverrides{},\n\t).ClientConfig()\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"invalid kubeconfig: %w\", err)\n\t}\n\n\tkubeClientConfigOverrides(s, clientConfig)\n\t// Kubelet needs to be able to recover from stale http connections.\n\t// HTTP2 has a mechanism to detect broken connections by sending periodical pings.\n\t// HTTP1 only can have one persistent connection, and it will close all Idle connections\n\t// once the Kubelet heartbeat fails. However, since there are many edge cases that we can't\n\t// control, users can still opt-in to the previous behavior for closing the connections by\n\t// setting the environment variable DISABLE_HTTP2.\n\tvar onHeartbeatFailure func()\n\tif s := os.Getenv(\"DISABLE_HTTP2\"); len(s) \u003e 0 {\n\t\tklog.InfoS(\"HTTP2 has been explicitly disabled, updating Kubelet client Dialer to forcefully close active connections on heartbeat failures\")\n\t\tonHeartbeatFailure, err = updateDialer(clientConfig)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t} else {\n\t\tonHeartbeatFailure = func() {\n\t\t\tutilnet.CloseIdleConnectionsFor(clientConfig.Transport)\n\t\t}\n\t}\n\tif utilfeature.DefaultFeatureGate.Enabled(features.KubeletTracing) {\n\t\tclientConfig.Wrap(tracing.WrapperFor(tp))\n\t}\n\treturn clientConfig, onHeartbeatFailure, nil\n}","line":{"from":816,"to":937}} {"id":100001611,"name":"updateDialer","signature":"func updateDialer(clientConfig *restclient.Config) (func(), error)","file":"cmd/kubelet/app/server.go","code":"// updateDialer instruments a restconfig with a dial. the returned function allows forcefully closing all active connections.\nfunc updateDialer(clientConfig *restclient.Config) (func(), error) {\n\tif clientConfig.Transport != nil || clientConfig.Dial != nil {\n\t\treturn nil, fmt.Errorf(\"there is already a transport or dialer configured\")\n\t}\n\td := connrotation.NewDialer((\u0026net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}).DialContext)\n\tclientConfig.Dial = d.DialContext\n\treturn d.CloseAll, nil\n}","line":{"from":939,"to":947}} {"id":100001612,"name":"buildClientCertificateManager","signature":"func buildClientCertificateManager(certConfig, clientConfig *restclient.Config, certDir string, nodeName types.NodeName) (certificate.Manager, error)","file":"cmd/kubelet/app/server.go","code":"// buildClientCertificateManager creates a certificate manager that will use certConfig to request a client certificate\n// if no certificate is available, or the most recent clientConfig (which is assumed to point to the cert that the manager will\n// write out).\nfunc buildClientCertificateManager(certConfig, clientConfig *restclient.Config, certDir string, nodeName types.NodeName) (certificate.Manager, error) {\n\tnewClientsetFn := func(current *tls.Certificate) (clientset.Interface, error) {\n\t\t// If we have a valid certificate, use that to fetch CSRs. Otherwise use the bootstrap\n\t\t// credentials. In the future it would be desirable to change the behavior of bootstrap\n\t\t// to always fall back to the external bootstrap credentials when such credentials are\n\t\t// provided by a fundamental trust system like cloud VM identity or an HSM module.\n\t\tconfig := certConfig\n\t\tif current != nil {\n\t\t\tconfig = clientConfig\n\t\t}\n\t\treturn clientset.NewForConfig(config)\n\t}\n\n\treturn kubeletcertificate.NewKubeletClientCertificateManager(\n\t\tcertDir,\n\t\tnodeName,\n\n\t\t// this preserves backwards compatibility with kubeadm which passes\n\t\t// a high powered certificate to the kubelet as --kubeconfig and expects\n\t\t// it to be rotated out immediately\n\t\tclientConfig.CertData,\n\t\tclientConfig.KeyData,\n\n\t\tclientConfig.CertFile,\n\t\tclientConfig.KeyFile,\n\t\tnewClientsetFn,\n\t)\n}","line":{"from":949,"to":979}} {"id":100001613,"name":"kubeClientConfigOverrides","signature":"func kubeClientConfigOverrides(s *options.KubeletServer, clientConfig *restclient.Config)","file":"cmd/kubelet/app/server.go","code":"func kubeClientConfigOverrides(s *options.KubeletServer, clientConfig *restclient.Config) {\n\tsetContentTypeForClient(clientConfig, s.ContentType)\n\t// Override kubeconfig qps/burst settings from flags\n\tclientConfig.QPS = float32(s.KubeAPIQPS)\n\tclientConfig.Burst = int(s.KubeAPIBurst)\n}","line":{"from":981,"to":986}} {"id":100001614,"name":"getNodeName","signature":"func getNodeName(cloud cloudprovider.Interface, hostname string) (types.NodeName, error)","file":"cmd/kubelet/app/server.go","code":"// getNodeName returns the node name according to the cloud provider\n// if cloud provider is specified. Otherwise, returns the hostname of the node.\nfunc getNodeName(cloud cloudprovider.Interface, hostname string) (types.NodeName, error) {\n\tif cloud == nil {\n\t\treturn types.NodeName(hostname), nil\n\t}\n\n\tinstances, ok := cloud.Instances()\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"failed to get instances from cloud provider\")\n\t}\n\n\tnodeName, err := instances.CurrentNodeName(context.TODO(), hostname)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error fetching current node name from cloud provider: %w\", err)\n\t}\n\n\tklog.V(2).InfoS(\"Cloud provider determined current node\", \"nodeName\", klog.KRef(\"\", string(nodeName)))\n\n\treturn nodeName, nil\n}","line":{"from":988,"to":1008}} {"id":100001615,"name":"InitializeTLS","signature":"func InitializeTLS(kf *options.KubeletFlags, kc *kubeletconfiginternal.KubeletConfiguration) (*server.TLSOptions, error)","file":"cmd/kubelet/app/server.go","code":"// InitializeTLS checks for a configured TLSCertFile and TLSPrivateKeyFile: if unspecified a new self-signed\n// certificate and key file are generated. Returns a configured server.TLSOptions object.\nfunc InitializeTLS(kf *options.KubeletFlags, kc *kubeletconfiginternal.KubeletConfiguration) (*server.TLSOptions, error) {\n\tif !kc.ServerTLSBootstrap \u0026\u0026 kc.TLSCertFile == \"\" \u0026\u0026 kc.TLSPrivateKeyFile == \"\" {\n\t\tkc.TLSCertFile = path.Join(kf.CertDirectory, \"kubelet.crt\")\n\t\tkc.TLSPrivateKeyFile = path.Join(kf.CertDirectory, \"kubelet.key\")\n\n\t\tcanReadCertAndKey, err := certutil.CanReadCertAndKey(kc.TLSCertFile, kc.TLSPrivateKeyFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !canReadCertAndKey {\n\t\t\thostName, err := nodeutil.GetHostname(kf.HostnameOverride)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tcert, key, err := certutil.GenerateSelfSignedCertKey(hostName, nil, nil)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"unable to generate self signed cert: %w\", err)\n\t\t\t}\n\n\t\t\tif err := certutil.WriteCert(kc.TLSCertFile, cert); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif err := keyutil.WriteKey(kc.TLSPrivateKeyFile, key); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tklog.V(4).InfoS(\"Using self-signed cert\", \"TLSCertFile\", kc.TLSCertFile, \"TLSPrivateKeyFile\", kc.TLSPrivateKeyFile)\n\t\t}\n\t}\n\n\ttlsCipherSuites, err := cliflag.TLSCipherSuites(kc.TLSCipherSuites)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(tlsCipherSuites) \u003e 0 {\n\t\tinsecureCiphers := cliflag.InsecureTLSCiphers()\n\t\tfor i := 0; i \u003c len(tlsCipherSuites); i++ {\n\t\t\tfor cipherName, cipherID := range insecureCiphers {\n\t\t\t\tif tlsCipherSuites[i] == cipherID {\n\t\t\t\t\tklog.InfoS(\"Use of insecure cipher detected.\", \"cipher\", cipherName)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tminTLSVersion, err := cliflag.TLSVersion(kc.TLSMinVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttlsOptions := \u0026server.TLSOptions{\n\t\tConfig: \u0026tls.Config{\n\t\t\tMinVersion: minTLSVersion,\n\t\t\tCipherSuites: tlsCipherSuites,\n\t\t},\n\t\tCertFile: kc.TLSCertFile,\n\t\tKeyFile: kc.TLSPrivateKeyFile,\n\t}\n\n\tif len(kc.Authentication.X509.ClientCAFile) \u003e 0 {\n\t\tclientCAs, err := certutil.NewPool(kc.Authentication.X509.ClientCAFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to load client CA file %s: %w\", kc.Authentication.X509.ClientCAFile, err)\n\t\t}\n\t\t// Specify allowed CAs for client certificates\n\t\ttlsOptions.Config.ClientCAs = clientCAs\n\t\t// Populate PeerCertificates in requests, but don't reject connections without verified certificates\n\t\ttlsOptions.Config.ClientAuth = tls.RequestClientCert\n\t}\n\n\treturn tlsOptions, nil\n}","line":{"from":1010,"to":1085}} {"id":100001616,"name":"setContentTypeForClient","signature":"func setContentTypeForClient(cfg *restclient.Config, contentType string)","file":"cmd/kubelet/app/server.go","code":"// setContentTypeForClient sets the appropriate content type into the rest config\n// and handles defaulting AcceptContentTypes based on that input.\nfunc setContentTypeForClient(cfg *restclient.Config, contentType string) {\n\tif len(contentType) == 0 {\n\t\treturn\n\t}\n\tcfg.ContentType = contentType\n\tswitch contentType {\n\tcase runtime.ContentTypeProtobuf:\n\t\tcfg.AcceptContentTypes = strings.Join([]string{runtime.ContentTypeProtobuf, runtime.ContentTypeJSON}, \",\")\n\tdefault:\n\t\t// otherwise let the rest client perform defaulting\n\t}\n}","line":{"from":1087,"to":1100}} {"id":100001617,"name":"RunKubelet","signature":"func RunKubelet(kubeServer *options.KubeletServer, kubeDeps *kubelet.Dependencies, runOnce bool) error","file":"cmd/kubelet/app/server.go","code":"// RunKubelet is responsible for setting up and running a kubelet. It is used in three different applications:\n//\n//\t1 Integration tests\n//\t2 Kubelet binary\n//\t3 Standalone 'kubernetes' binary\n//\n// Eventually, #2 will be replaced with instances of #3\nfunc RunKubelet(kubeServer *options.KubeletServer, kubeDeps *kubelet.Dependencies, runOnce bool) error {\n\thostname, err := nodeutil.GetHostname(kubeServer.HostnameOverride)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Query the cloud provider for our node name, default to hostname if kubeDeps.Cloud == nil\n\tnodeName, err := getNodeName(kubeDeps.Cloud, hostname)\n\tif err != nil {\n\t\treturn err\n\t}\n\thostnameOverridden := len(kubeServer.HostnameOverride) \u003e 0\n\t// Setup event recorder if required.\n\tmakeEventRecorder(kubeDeps, nodeName)\n\n\tnodeIPs, err := nodeutil.ParseNodeIPArgument(kubeServer.NodeIP, kubeServer.CloudProvider, utilfeature.DefaultFeatureGate.Enabled(features.CloudDualStackNodeIPs))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"bad --node-ip %q: %v\", kubeServer.NodeIP, err)\n\t}\n\n\tcapabilities.Initialize(capabilities.Capabilities{\n\t\tAllowPrivileged: true,\n\t})\n\n\tcredentialprovider.SetPreferredDockercfgPath(kubeServer.RootDirectory)\n\tklog.V(2).InfoS(\"Using root directory\", \"path\", kubeServer.RootDirectory)\n\n\tif kubeDeps.OSInterface == nil {\n\t\tkubeDeps.OSInterface = kubecontainer.RealOS{}\n\t}\n\n\tk, err := createAndInitKubelet(kubeServer,\n\t\tkubeDeps,\n\t\thostname,\n\t\thostnameOverridden,\n\t\tnodeName,\n\t\tnodeIPs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create kubelet: %w\", err)\n\t}\n\n\t// NewMainKubelet should have set up a pod source config if one didn't exist\n\t// when the builder was run. This is just a precaution.\n\tif kubeDeps.PodConfig == nil {\n\t\treturn fmt.Errorf(\"failed to create kubelet, pod source config was nil\")\n\t}\n\tpodCfg := kubeDeps.PodConfig\n\n\tif err := rlimit.SetNumFiles(uint64(kubeServer.MaxOpenFiles)); err != nil {\n\t\tklog.ErrorS(err, \"Failed to set rlimit on max file handles\")\n\t}\n\n\t// process pods and exit.\n\tif runOnce {\n\t\tif _, err := k.RunOnce(podCfg.Updates()); err != nil {\n\t\t\treturn fmt.Errorf(\"runonce failed: %w\", err)\n\t\t}\n\t\tklog.InfoS(\"Started kubelet as runonce\")\n\t} else {\n\t\tstartKubelet(k, podCfg, \u0026kubeServer.KubeletConfiguration, kubeDeps, kubeServer.EnableServer)\n\t\tklog.InfoS(\"Started kubelet\")\n\t}\n\treturn nil\n}","line":{"from":1102,"to":1171}} {"id":100001618,"name":"startKubelet","signature":"func startKubelet(k kubelet.Bootstrap, podCfg *config.PodConfig, kubeCfg *kubeletconfiginternal.KubeletConfiguration, kubeDeps *kubelet.Dependencies, enableServer bool)","file":"cmd/kubelet/app/server.go","code":"func startKubelet(k kubelet.Bootstrap, podCfg *config.PodConfig, kubeCfg *kubeletconfiginternal.KubeletConfiguration, kubeDeps *kubelet.Dependencies, enableServer bool) {\n\t// start the kubelet\n\tgo k.Run(podCfg.Updates())\n\n\t// start the kubelet server\n\tif enableServer {\n\t\tgo k.ListenAndServe(kubeCfg, kubeDeps.TLSOptions, kubeDeps.Auth, kubeDeps.TracerProvider)\n\t}\n\tif kubeCfg.ReadOnlyPort \u003e 0 {\n\t\tgo k.ListenAndServeReadOnly(netutils.ParseIPSloppy(kubeCfg.Address), uint(kubeCfg.ReadOnlyPort))\n\t}\n\tif utilfeature.DefaultFeatureGate.Enabled(features.KubeletPodResources) {\n\t\tgo k.ListenAndServePodResources()\n\t}\n}","line":{"from":1173,"to":1187}} {"id":100001619,"name":"createAndInitKubelet","signature":"func createAndInitKubelet(kubeServer *options.KubeletServer,","file":"cmd/kubelet/app/server.go","code":"func createAndInitKubelet(kubeServer *options.KubeletServer,\n\tkubeDeps *kubelet.Dependencies,\n\thostname string,\n\thostnameOverridden bool,\n\tnodeName types.NodeName,\n\tnodeIPs []net.IP) (k kubelet.Bootstrap, err error) {\n\t// TODO: block until all sources have delivered at least one update to the channel, or break the sync loop\n\t// up into \"per source\" synchronizations\n\n\tk, err = kubelet.NewMainKubelet(\u0026kubeServer.KubeletConfiguration,\n\t\tkubeDeps,\n\t\t\u0026kubeServer.ContainerRuntimeOptions,\n\t\thostname,\n\t\thostnameOverridden,\n\t\tnodeName,\n\t\tnodeIPs,\n\t\tkubeServer.ProviderID,\n\t\tkubeServer.CloudProvider,\n\t\tkubeServer.CertDirectory,\n\t\tkubeServer.RootDirectory,\n\t\tkubeServer.ImageCredentialProviderConfigFile,\n\t\tkubeServer.ImageCredentialProviderBinDir,\n\t\tkubeServer.RegisterNode,\n\t\tkubeServer.RegisterWithTaints,\n\t\tkubeServer.AllowedUnsafeSysctls,\n\t\tkubeServer.ExperimentalMounterPath,\n\t\tkubeServer.KernelMemcgNotification,\n\t\tkubeServer.ExperimentalNodeAllocatableIgnoreEvictionThreshold,\n\t\tkubeServer.MinimumGCAge,\n\t\tkubeServer.MaxPerPodContainerCount,\n\t\tkubeServer.MaxContainerCount,\n\t\tkubeServer.RegisterSchedulable,\n\t\tkubeServer.KeepTerminatedPodVolumes,\n\t\tkubeServer.NodeLabels,\n\t\tkubeServer.NodeStatusMaxImages,\n\t\tkubeServer.KubeletFlags.SeccompDefault || kubeServer.KubeletConfiguration.SeccompDefault)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tk.BirthCry()\n\n\tk.StartGarbageCollection()\n\n\treturn k, nil\n}","line":{"from":1189,"to":1234}} {"id":100001620,"name":"parseResourceList","signature":"func parseResourceList(m map[string]string) (v1.ResourceList, error)","file":"cmd/kubelet/app/server.go","code":"// parseResourceList parses the given configuration map into an API\n// ResourceList or returns an error.\nfunc parseResourceList(m map[string]string) (v1.ResourceList, error) {\n\tif len(m) == 0 {\n\t\treturn nil, nil\n\t}\n\trl := make(v1.ResourceList)\n\tfor k, v := range m {\n\t\tswitch v1.ResourceName(k) {\n\t\t// CPU, memory, local storage, and PID resources are supported.\n\t\tcase v1.ResourceCPU, v1.ResourceMemory, v1.ResourceEphemeralStorage, pidlimit.PIDs:\n\t\t\tq, err := resource.ParseQuantity(v)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to parse quantity %q for %q resource: %w\", v, k, err)\n\t\t\t}\n\t\t\tif q.Sign() == -1 {\n\t\t\t\treturn nil, fmt.Errorf(\"resource quantity for %q cannot be negative: %v\", k, v)\n\t\t\t}\n\t\t\trl[v1.ResourceName(k)] = q\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"cannot reserve %q resource\", k)\n\t\t}\n\t}\n\treturn rl, nil\n}","line":{"from":1236,"to":1260}} {"id":100001621,"name":"newTracerProvider","signature":"func newTracerProvider(s *options.KubeletServer) (oteltrace.TracerProvider, error)","file":"cmd/kubelet/app/server.go","code":"func newTracerProvider(s *options.KubeletServer) (oteltrace.TracerProvider, error) {\n\tif s.KubeletConfiguration.Tracing == nil {\n\t\treturn oteltrace.NewNoopTracerProvider(), nil\n\t}\n\thostname, err := nodeutil.GetHostname(s.HostnameOverride)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not determine hostname for tracer provider: %w\", err)\n\t}\n\tresourceOpts := []otelsdkresource.Option{\n\t\totelsdkresource.WithAttributes(\n\t\t\tsemconv.ServiceNameKey.String(componentKubelet),\n\t\t\tsemconv.HostNameKey.String(hostname),\n\t\t),\n\t}\n\ttp, err := tracing.NewProvider(context.Background(), s.KubeletConfiguration.Tracing, []otlptracegrpc.Option{}, resourceOpts)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not configure tracer provider: %w\", err)\n\t}\n\treturn tp, nil\n}","line":{"from":1262,"to":1281}} {"id":100001622,"name":"watchForLockfileContention","signature":"func watchForLockfileContention(path string, done chan struct{}) error","file":"cmd/kubelet/app/server_linux.go","code":"func watchForLockfileContention(path string, done chan struct{}) error {\n\twatcher, err := inotify.NewWatcher()\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Unable to create watcher for lockfile\")\n\t\treturn err\n\t}\n\tif err = watcher.AddWatch(path, inotify.InOpen|inotify.InDeleteSelf); err != nil {\n\t\tklog.ErrorS(err, \"Unable to watch lockfile\")\n\t\twatcher.Close()\n\t\treturn err\n\t}\n\tgo func() {\n\t\tselect {\n\t\tcase ev := \u003c-watcher.Event:\n\t\t\tklog.InfoS(\"Inotify event\", \"event\", ev)\n\t\tcase err = \u003c-watcher.Error:\n\t\t\tklog.ErrorS(err, \"inotify watcher error\")\n\t\t}\n\t\tclose(done)\n\t\twatcher.Close()\n\t}()\n\treturn nil\n}","line":{"from":26,"to":48}} {"id":100001623,"name":"isCgroup2UnifiedMode","signature":"func isCgroup2UnifiedMode() bool","file":"cmd/kubelet/app/server_linux.go","code":"func isCgroup2UnifiedMode() bool {\n\treturn libcontainercgroups.IsCgroup2UnifiedMode()\n}","line":{"from":50,"to":52}} {"id":100001624,"name":"checkPermissions","signature":"func checkPermissions() error","file":"cmd/kubelet/app/server_others.go","code":"func checkPermissions() error {\n\tif uid := os.Getuid(); uid != 0 {\n\t\treturn fmt.Errorf(\"kubelet needs to run as uid `0`. It is being run as %d\", uid)\n\t}\n\t// TODO: Check if kubelet is running in the `initial` user namespace.\n\t// http://man7.org/linux/man-pages/man7/user_namespaces.7.html\n\treturn nil\n}","line":{"from":27,"to":34}} {"id":100001625,"name":"watchForLockfileContention","signature":"func watchForLockfileContention(path string, done chan struct{}) error","file":"cmd/kubelet/app/server_unsupported.go","code":"func watchForLockfileContention(path string, done chan struct{}) error {\n\treturn errors.New(\"kubelet unsupported in this build\")\n}","line":{"from":24,"to":26}} {"id":100001626,"name":"isCgroup2UnifiedMode","signature":"func isCgroup2UnifiedMode() bool","file":"cmd/kubelet/app/server_unsupported.go","code":"func isCgroup2UnifiedMode() bool {\n\treturn false\n}","line":{"from":28,"to":30}} {"id":100001627,"name":"checkPermissions","signature":"func checkPermissions() error","file":"cmd/kubelet/app/server_windows.go","code":"func checkPermissions() error {\n\n\tu, err := user.Current()\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Unable to get current user\")\n\t\treturn err\n\t}\n\n\t// For Windows user.UserName contains the login name and user.Name contains\n\t// the user's display name - https://pkg.go.dev/os/user#User\n\tklog.InfoS(\"Kubelet is running as\", \"login name\", u.Username, \"dispaly name\", u.Name)\n\n\tif !windows.GetCurrentProcessToken().IsElevated() {\n\t\treturn errors.New(\"kubelet needs to run with elevated permissions!\")\n\t}\n\n\treturn nil\n}","line":{"from":30,"to":47}} {"id":100001628,"name":"main","signature":"func main()","file":"cmd/kubelet/kubelet.go","code":"func main() {\n\tcommand := app.NewKubeletCommand()\n\tcode := cli.Run(command)\n\tos.Exit(code)\n}","line":{"from":34,"to":38}} {"id":100001629,"name":"addFlags","signature":"func (c *hollowNodeConfig) addFlags(fs *pflag.FlagSet)","file":"cmd/kubemark/app/hollow_node.go","code":"func (c *hollowNodeConfig) addFlags(fs *pflag.FlagSet) {\n\tfs.StringVar(\u0026c.KubeconfigPath, \"kubeconfig\", \"/kubeconfig/kubeconfig\", \"Path to kubeconfig file.\")\n\tfs.StringVar(\u0026c.BootstrapKubeconfigPath, \"bootstrap-kubeconfig\", \"\", \"Path to bootstrap kubeconfig file.\")\n\tfs.StringVar(\u0026c.CertDirectory, \"cert-dir\", \"/etc/srv/\", \"Path to cert directory for bootstraping.\")\n\tfs.IntVar(\u0026c.KubeletPort, \"kubelet-port\", ports.KubeletPort, \"Port on which HollowKubelet should be listening.\")\n\tfs.IntVar(\u0026c.KubeletReadOnlyPort, \"kubelet-read-only-port\", ports.KubeletReadOnlyPort, \"Read-only port on which Kubelet is listening.\")\n\tfs.StringVar(\u0026c.NodeName, \"name\", \"fake-node\", \"Name of this Hollow Node.\")\n\tfs.IntVar(\u0026c.ServerPort, \"api-server-port\", 443, \"Port on which API server is listening.\")\n\tfs.StringVar(\u0026c.Morph, \"morph\", \"\", fmt.Sprintf(\"Specifies into which Hollow component this binary should morph. Allowed values: %v\", knownMorphs.List()))\n\tfs.StringVar(\u0026c.ContentType, \"kube-api-content-type\", \"application/vnd.kubernetes.protobuf\", \"ContentType of requests sent to apiserver.\")\n\tfs.BoolVar(\u0026c.UseRealProxier, \"use-real-proxier\", true, \"Set to true if you want to use real proxier inside hollow-proxy.\")\n\tfs.DurationVar(\u0026c.ProxierSyncPeriod, \"proxier-sync-period\", 30*time.Second, \"Period that proxy rules are refreshed in hollow-proxy.\")\n\tfs.DurationVar(\u0026c.ProxierMinSyncPeriod, \"proxier-min-sync-period\", 0, \"Minimum period that proxy rules are refreshed in hollow-proxy.\")\n\tbindableNodeLabels := cliflag.ConfigurationMap(c.NodeLabels)\n\tfs.Var(\u0026bindableNodeLabels, \"node-labels\", \"Additional node labels\")\n\tfs.Var(utilflag.RegisterWithTaintsVar{Value: \u0026c.RegisterWithTaints}, \"register-with-taints\", \"Register the node with the given list of taints (comma separated \\\"\u003ckey\u003e=\u003cvalue\u003e:\u003ceffect\u003e\\\"). No-op if register-node is false.\")\n\tfs.IntVar(\u0026c.MaxPods, \"max-pods\", maxPods, \"Number of pods that can run on this Kubelet.\")\n\tbindableExtendedResources := cliflag.ConfigurationMap(c.ExtendedResources)\n\tfs.Var(\u0026bindableExtendedResources, \"extended-resources\", \"Register the node with extended resources (comma separated \\\"\u003cname\u003e=\u003cquantity\u003e\\\")\")\n\tfs.BoolVar(\u0026c.UseHostImageService, \"use-host-image-service\", true, \"Set to true if the hollow-kubelet should use the host image service. If set to false the fake image service will be used\")\n}","line":{"from":88,"to":108}} {"id":100001630,"name":"createClientConfigFromFile","signature":"func (c *hollowNodeConfig) createClientConfigFromFile() (*restclient.Config, error)","file":"cmd/kubemark/app/hollow_node.go","code":"func (c *hollowNodeConfig) createClientConfigFromFile() (*restclient.Config, error) {\n\tclientConfig, err := clientcmd.LoadFromFile(c.KubeconfigPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while loading kubeconfig from file %v: %v\", c.KubeconfigPath, err)\n\t}\n\tconfig, err := clientcmd.NewDefaultClientConfig(*clientConfig, \u0026clientcmd.ConfigOverrides{}).ClientConfig()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while creating kubeconfig: %v\", err)\n\t}\n\tconfig.ContentType = c.ContentType\n\tconfig.QPS = 10\n\tconfig.Burst = 20\n\treturn config, nil\n}","line":{"from":110,"to":123}} {"id":100001631,"name":"bootstrapClientConfig","signature":"func (c *hollowNodeConfig) bootstrapClientConfig() error","file":"cmd/kubemark/app/hollow_node.go","code":"func (c *hollowNodeConfig) bootstrapClientConfig() error {\n\tif c.BootstrapKubeconfigPath != \"\" {\n\t\treturn bootstrap.LoadClientCert(context.TODO(), c.KubeconfigPath, c.BootstrapKubeconfigPath, c.CertDirectory, types.NodeName(c.NodeName))\n\t}\n\treturn nil\n}","line":{"from":125,"to":130}} {"id":100001632,"name":"createHollowKubeletOptions","signature":"func (c *hollowNodeConfig) createHollowKubeletOptions() *kubemark.HollowKubeletOptions","file":"cmd/kubemark/app/hollow_node.go","code":"func (c *hollowNodeConfig) createHollowKubeletOptions() *kubemark.HollowKubeletOptions {\n\treturn \u0026kubemark.HollowKubeletOptions{\n\t\tNodeName: c.NodeName,\n\t\tKubeletPort: c.KubeletPort,\n\t\tKubeletReadOnlyPort: c.KubeletReadOnlyPort,\n\t\tMaxPods: c.MaxPods,\n\t\tPodsPerCore: podsPerCore,\n\t\tNodeLabels: c.NodeLabels,\n\t\tRegisterWithTaints: c.RegisterWithTaints,\n\t}\n}","line":{"from":132,"to":142}} {"id":100001633,"name":"NewHollowNodeCommand","signature":"func NewHollowNodeCommand() *cobra.Command","file":"cmd/kubemark/app/hollow_node.go","code":"// NewHollowNodeCommand creates a *cobra.Command object with default parameters\nfunc NewHollowNodeCommand() *cobra.Command {\n\ts := \u0026hollowNodeConfig{\n\t\tNodeLabels: make(map[string]string),\n\t\tExtendedResources: make(map[string]string),\n\t}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"kubemark\",\n\t\tLong: \"kubemark\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tverflag.PrintAndExitIfRequested()\n\t\t\tcliflag.PrintFlags(cmd.Flags())\n\t\t\treturn run(s)\n\t\t},\n\t\tArgs: func(cmd *cobra.Command, args []string) error {\n\t\t\tfor _, arg := range args {\n\t\t\t\tif len(arg) \u003e 0 {\n\t\t\t\t\treturn fmt.Errorf(\"%q does not take any arguments, got %q\", cmd.CommandPath(), args)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tfs := cmd.Flags()\n\tfs.AddGoFlagSet(goflag.CommandLine) // for flags like --docker-only\n\ts.addFlags(fs)\n\n\treturn cmd\n}","line":{"from":144,"to":174}} {"id":100001634,"name":"run","signature":"func run(config *hollowNodeConfig) error","file":"cmd/kubemark/app/hollow_node.go","code":"func run(config *hollowNodeConfig) error {\n\t// To help debugging, immediately log version and print flags.\n\tklog.Infof(\"Version: %+v\", version.Get())\n\n\tif !knownMorphs.Has(config.Morph) {\n\t\treturn fmt.Errorf(\"Unknown morph: %v. allowed values: %v\", config.Morph, knownMorphs.List())\n\t}\n\n\t// create a client to communicate with API server.\n\terr := config.bootstrapClientConfig()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to bootstrap, error: %w. Exiting\", err)\n\t}\n\tclientConfig, err := config.createClientConfigFromFile()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to create a ClientConfig, error: %w. Exiting\", err)\n\t}\n\n\tif config.Morph == \"kubelet\" {\n\t\tclientConfig.UserAgent = \"hollow-kubelet\"\n\t\tclient, err := clientset.NewForConfig(clientConfig)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to create a ClientSet, error: %w. Exiting\", err)\n\t\t}\n\n\t\tf, c := kubemark.GetHollowKubeletConfig(config.createHollowKubeletOptions())\n\n\t\theartbeatClientConfig := *clientConfig\n\t\theartbeatClientConfig.Timeout = c.NodeStatusUpdateFrequency.Duration\n\t\t// The timeout is the minimum of the lease duration and status update frequency\n\t\tleaseTimeout := time.Duration(c.NodeLeaseDurationSeconds) * time.Second\n\t\tif heartbeatClientConfig.Timeout \u003e leaseTimeout {\n\t\t\theartbeatClientConfig.Timeout = leaseTimeout\n\t\t}\n\n\t\theartbeatClientConfig.QPS = float32(-1)\n\t\theartbeatClient, err := clientset.NewForConfig(\u0026heartbeatClientConfig)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to create a ClientSet, error: %w. Exiting\", err)\n\t\t}\n\n\t\tcadvisorInterface := \u0026cadvisortest.Fake{\n\t\t\tNodeName: config.NodeName,\n\t\t}\n\n\t\tvar containerManager cm.ContainerManager\n\t\tif config.ExtendedResources != nil {\n\t\t\textendedResources := v1.ResourceList{}\n\t\t\tfor k, v := range config.ExtendedResources {\n\t\t\t\textendedResources[v1.ResourceName(k)] = resource.MustParse(v)\n\t\t\t}\n\n\t\t\tcontainerManager = cm.NewStubContainerManagerWithDevicePluginResource(extendedResources)\n\t\t} else {\n\t\t\tcontainerManager = cm.NewStubContainerManager()\n\t\t}\n\n\t\tendpoint, err := fakeremote.GenerateEndpoint()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to generate fake endpoint, error: %w\", err)\n\t\t}\n\t\tfakeRemoteRuntime := fakeremote.NewFakeRemoteRuntime()\n\t\tif err = fakeRemoteRuntime.Start(endpoint); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to start fake runtime, error: %w\", err)\n\t\t}\n\t\tdefer fakeRemoteRuntime.Stop()\n\t\truntimeService, err := remote.NewRemoteRuntimeService(endpoint, 15*time.Second, oteltrace.NewNoopTracerProvider())\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to init runtime service, error: %w\", err)\n\t\t}\n\n\t\tvar imageService internalapi.ImageManagerService = fakeRemoteRuntime.ImageService\n\t\tif config.UseHostImageService {\n\t\t\timageService, err = remote.NewRemoteImageService(c.ImageServiceEndpoint, 15*time.Second, oteltrace.NewNoopTracerProvider())\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Failed to init image service, error: %w\", err)\n\t\t\t}\n\t\t}\n\n\t\thollowKubelet := kubemark.NewHollowKubelet(\n\t\t\tf, c,\n\t\t\tclient,\n\t\t\theartbeatClient,\n\t\t\tcadvisorInterface,\n\t\t\timageService,\n\t\t\truntimeService,\n\t\t\tcontainerManager,\n\t\t)\n\t\thollowKubelet.Run()\n\t}\n\n\tif config.Morph == \"proxy\" {\n\t\tclientConfig.UserAgent = \"hollow-proxy\"\n\n\t\tclient, err := clientset.NewForConfig(clientConfig)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to create API Server client, error: %w\", err)\n\t\t}\n\t\tiptInterface := fakeiptables.NewFake()\n\t\tsysctl := fakesysctl.NewFake()\n\t\texecer := \u0026fakeexec.FakeExec{\n\t\t\tLookPathFunc: func(_ string) (string, error) { return \"\", errors.New(\"fake execer\") },\n\t\t}\n\t\teventBroadcaster := events.NewBroadcaster(\u0026events.EventSinkImpl{Interface: client.EventsV1()})\n\t\trecorder := eventBroadcaster.NewRecorder(legacyscheme.Scheme, \"kube-proxy\")\n\n\t\thollowProxy, err := kubemark.NewHollowProxyOrDie(\n\t\t\tconfig.NodeName,\n\t\t\tclient,\n\t\t\tclient.CoreV1(),\n\t\t\tiptInterface,\n\t\t\tsysctl,\n\t\t\texecer,\n\t\t\teventBroadcaster,\n\t\t\trecorder,\n\t\t\tconfig.UseRealProxier,\n\t\t\tconfig.ProxierSyncPeriod,\n\t\t\tconfig.ProxierMinSyncPeriod,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to create hollowProxy instance, error: %w\", err)\n\t\t}\n\t\treturn hollowProxy.Run()\n\t}\n\n\treturn nil\n}","line":{"from":176,"to":302}} {"id":100001635,"name":"main","signature":"func main()","file":"cmd/kubemark/hollow-node.go","code":"func main() {\n\tcommand := app.NewHollowNodeCommand()\n\tcode := cli.Run(command)\n\tos.Exit(code)\n}","line":{"from":26,"to":30}} {"id":100001636,"name":"newAnalyzer","signature":"func newAnalyzer() *analyzer","file":"cmd/preferredimports/preferredimports.go","code":"func newAnalyzer() *analyzer {\n\tctx := build.Default\n\tctx.CgoEnabled = true\n\n\ta := \u0026analyzer{\n\t\tfset: token.NewFileSet(),\n\t\tctx: ctx,\n\t\tdonePaths: make(map[string]interface{}),\n\t}\n\n\treturn a\n}","line":{"from":56,"to":67}} {"id":100001637,"name":"collect","signature":"func (a *analyzer) collect(dir string)","file":"cmd/preferredimports/preferredimports.go","code":"// collect extracts test metadata from a file.\nfunc (a *analyzer) collect(dir string) {\n\tif _, ok := a.donePaths[dir]; ok {\n\t\treturn\n\t}\n\ta.donePaths[dir] = nil\n\n\t// Create the AST by parsing src.\n\tfs, err := parser.ParseDir(a.fset, dir, nil, parser.AllErrors|parser.ParseComments)\n\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"ERROR(syntax)\", logPrefix, err)\n\t\ta.failed = true\n\t\treturn\n\t}\n\n\tfor _, p := range fs {\n\t\t// returns first error, but a.handleError deals with it\n\t\tfiles := a.filterFiles(p.Files)\n\t\tfor _, file := range files {\n\t\t\treplacements := make(map[string]string)\n\t\t\tpathToFile := a.fset.File(file.Pos()).Name()\n\t\t\tfor _, imp := range file.Imports {\n\t\t\t\timportPath := strings.Replace(imp.Path.Value, \"\\\"\", \"\", -1)\n\t\t\t\tpathSegments := strings.Split(importPath, \"/\")\n\t\t\t\timportName := pathSegments[len(pathSegments)-1]\n\t\t\t\tif imp.Name != nil {\n\t\t\t\t\timportName = imp.Name.Name\n\t\t\t\t}\n\t\t\t\tfor re, template := range aliases {\n\t\t\t\t\tmatch := re.FindStringSubmatchIndex(importPath)\n\t\t\t\t\tif match == nil {\n\t\t\t\t\t\t// No match.\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif match[0] \u003e 0 || match[1] \u003c len(importPath) {\n\t\t\t\t\t\t// Not a full match.\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\talias := string(re.ExpandString(nil, template, importPath, match))\n\t\t\t\t\tif alias != importName {\n\t\t\t\t\t\tif !*confirm {\n\t\t\t\t\t\t\tfmt.Fprintf(os.Stderr, \"%sERROR wrong alias for import \\\"%s\\\" should be %s in file %s\\n\", logPrefix, importPath, alias, pathToFile)\n\t\t\t\t\t\t\ta.failed = true\n\t\t\t\t\t\t}\n\t\t\t\t\t\treplacements[importName] = alias\n\t\t\t\t\t\tif imp.Name != nil {\n\t\t\t\t\t\t\timp.Name.Name = alias\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\timp.Name = ast.NewIdent(alias)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(replacements) \u003e 0 {\n\t\t\t\tif *confirm {\n\t\t\t\t\tfmt.Printf(\"%sReplacing imports with aliases in file %s\\n\", logPrefix, pathToFile)\n\t\t\t\t\tfor key, value := range replacements {\n\t\t\t\t\t\trenameImportUsages(file, key, value)\n\t\t\t\t\t}\n\t\t\t\t\tast.SortImports(a.fset, file)\n\t\t\t\t\tvar buffer bytes.Buffer\n\t\t\t\t\tif err = format.Node(\u0026buffer, a.fset, file); err != nil {\n\t\t\t\t\t\tpanic(fmt.Sprintf(\"Error formatting ast node after rewriting import.\\n%s\\n\", err.Error()))\n\t\t\t\t\t}\n\n\t\t\t\t\tfileInfo, err := os.Stat(pathToFile)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tpanic(fmt.Sprintf(\"Error stat'ing file: %s\\n%s\\n\", pathToFile, err.Error()))\n\t\t\t\t\t}\n\n\t\t\t\t\terr = os.WriteFile(pathToFile, buffer.Bytes(), fileInfo.Mode())\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tpanic(fmt.Sprintf(\"Error writing file: %s\\n%s\\n\", pathToFile, err.Error()))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":69,"to":150}} {"id":100001638,"name":"renameImportUsages","signature":"func renameImportUsages(f *ast.File, old, new string)","file":"cmd/preferredimports/preferredimports.go","code":"func renameImportUsages(f *ast.File, old, new string) {\n\t// use this to avoid renaming the package declaration, eg:\n\t// given: package foo; import foo \"bar\"; foo.Baz, rename foo-\u003equx\n\t// yield: package foo; import qux \"bar\"; qux.Baz\n\tvar pkg *ast.Ident\n\n\t// Rename top-level old to new, both unresolved names\n\t// (probably defined in another file) and names that resolve\n\t// to a declaration we renamed.\n\tast.Inspect(f, func(node ast.Node) bool {\n\t\tif node == nil {\n\t\t\treturn false\n\t\t}\n\t\tswitch id := node.(type) {\n\t\tcase *ast.File:\n\t\t\tpkg = id.Name\n\t\tcase *ast.Ident:\n\t\t\tif pkg != nil \u0026\u0026 id == pkg {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif id.Name == old {\n\t\t\t\tid.Name = new\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n}","line":{"from":152,"to":178}} {"id":100001639,"name":"filterFiles","signature":"func (a *analyzer) filterFiles(fs map[string]*ast.File) []*ast.File","file":"cmd/preferredimports/preferredimports.go","code":"func (a *analyzer) filterFiles(fs map[string]*ast.File) []*ast.File {\n\tvar files []*ast.File\n\tfor _, f := range fs {\n\t\tfiles = append(files, f)\n\t}\n\treturn files\n}","line":{"from":180,"to":186}} {"id":100001640,"name":"handlePath","signature":"func (c *collector) handlePath(path string, info os.FileInfo, err error) error","file":"cmd/preferredimports/preferredimports.go","code":"// handlePath walks the filesystem recursively, collecting directories,\n// ignoring some unneeded directories (hidden/vendored) that are handled\n// specially later.\nfunc (c *collector) handlePath(path string, info os.FileInfo, err error) error {\n\tif err != nil {\n\t\treturn err\n\t}\n\tif info.IsDir() {\n\t\t// Ignore hidden directories (.git, .cache, etc)\n\t\tif len(path) \u003e 1 \u0026\u0026 path[0] == '.' ||\n\t\t\t// Staging code is symlinked from vendor/k8s.io, and uses import\n\t\t\t// paths as if it were inside of vendor/. It fails typechecking\n\t\t\t// inside of staging/, but works when typechecked as part of vendor/.\n\t\t\tpath == \"staging\" ||\n\t\t\t// OS-specific vendor code tends to be imported by OS-specific\n\t\t\t// packages. We recursively typecheck imported vendored packages for\n\t\t\t// each OS, but don't typecheck everything for every OS.\n\t\t\tpath == \"vendor\" ||\n\t\t\tpath == \"_output\" ||\n\t\t\t// This is a weird one. /testdata/ is *mostly* ignored by Go,\n\t\t\t// and this translates to kubernetes/vendor not working.\n\t\t\t// edit/record.go doesn't compile without gopkg.in/yaml.v2\n\t\t\t// in $GOSRC/$GOROOT (both typecheck and the shell script).\n\t\t\tpath == \"pkg/kubectl/cmd/testdata/edit\" {\n\t\t\treturn filepath.SkipDir\n\t\t}\n\t\tif c.regex.MatchString(path) {\n\t\t\tc.dirs = append(c.dirs, path)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":193,"to":224}} {"id":100001641,"name":"main","signature":"func main()","file":"cmd/preferredimports/preferredimports.go","code":"func main() {\n\tflag.Parse()\n\targs := flag.Args()\n\n\tif len(args) == 0 {\n\t\targs = append(args, \".\")\n\t}\n\n\tregex, err := regexp.Compile(*regex)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error compiling regex: %v\", err)\n\t}\n\tc := collector{regex: regex}\n\tfor _, arg := range args {\n\t\terr := filepath.Walk(arg, c.handlePath)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error walking: %v\", err)\n\t\t}\n\t}\n\tsort.Strings(c.dirs)\n\n\tif len(*importAliases) \u003e 0 {\n\t\tbytes, err := os.ReadFile(*importAliases)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error reading import aliases: %v\", err)\n\t\t}\n\t\tvar stringAliases map[string]string\n\t\terr = json.Unmarshal(bytes, \u0026stringAliases)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error loading aliases: %v\", err)\n\t\t}\n\t\tfor pattern, name := range stringAliases {\n\t\t\tre, err := regexp.Compile(pattern)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Error parsing import path pattern %q as regular expression: %v\", pattern, err)\n\t\t\t}\n\t\t\taliases[re] = name\n\t\t}\n\t}\n\tif isTerminal {\n\t\tlogPrefix = \"\\r\" // clear status bar when printing\n\t}\n\tfmt.Println(\"checking-imports: \")\n\n\ta := newAnalyzer()\n\tfor _, dir := range c.dirs {\n\t\tif isTerminal {\n\t\t\tfmt.Printf(\"\\r\\033[0m %-80s\", dir)\n\t\t}\n\t\ta.collect(dir)\n\t}\n\tfmt.Println()\n\tif a.failed {\n\t\tos.Exit(1)\n\t}\n}","line":{"from":226,"to":281}} {"id":100001642,"name":"main","signature":"func main()","file":"cmd/prune-junit-xml/prunexml.go","code":"func main() {\n\tmaxTextSize := flag.Int(\"max-text-size\", 1, \"maximum size of attribute or text (in MB)\")\n\tflag.Parse()\n\n\tif flag.NArg() \u003e 0 {\n\t\tfor _, path := range flag.Args() {\n\t\t\tfmt.Printf(\"processing junit xml file : %s\\n\", path)\n\t\t\txmlReader, err := os.Open(path)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tdefer xmlReader.Close()\n\t\t\tsuites, err := fetchXML(xmlReader) // convert MB into bytes (roughly!)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tpruneXML(suites, *maxTextSize*1e6) // convert MB into bytes (roughly!)\n\n\t\t\txmlWriter, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tdefer xmlWriter.Close()\n\t\t\terr = streamXML(xmlWriter, suites)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tfmt.Println(\"done.\")\n\t\t}\n\t}\n}","line":{"from":29,"to":60}} {"id":100001643,"name":"pruneXML","signature":"func pruneXML(suites *junitxml.JUnitTestSuites, maxBytes int)","file":"cmd/prune-junit-xml/prunexml.go","code":"func pruneXML(suites *junitxml.JUnitTestSuites, maxBytes int) {\n\tfor _, suite := range suites.Suites {\n\t\tfor _, testcase := range suite.TestCases {\n\t\t\tif testcase.SkipMessage != nil {\n\t\t\t\tif len(testcase.SkipMessage.Message) \u003e maxBytes {\n\t\t\t\t\tfmt.Printf(\"clipping skip message in test case : %s\\n\", testcase.Name)\n\t\t\t\t\thead := testcase.SkipMessage.Message[:maxBytes/2]\n\t\t\t\t\ttail := testcase.SkipMessage.Message[len(testcase.SkipMessage.Message)-maxBytes/2:]\n\t\t\t\t\ttestcase.SkipMessage.Message = head + \"[...clipped...]\" + tail\n\t\t\t\t}\n\t\t\t}\n\t\t\tif testcase.Failure != nil {\n\t\t\t\tif len(testcase.Failure.Contents) \u003e maxBytes {\n\t\t\t\t\tfmt.Printf(\"clipping failure message in test case : %s\\n\", testcase.Name)\n\t\t\t\t\thead := testcase.Failure.Contents[:maxBytes/2]\n\t\t\t\t\ttail := testcase.Failure.Contents[len(testcase.Failure.Contents)-maxBytes/2:]\n\t\t\t\t\ttestcase.Failure.Contents = head + \"[...clipped...]\" + tail\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":62,"to":83}} {"id":100001644,"name":"fetchXML","signature":"func fetchXML(xmlReader io.Reader) (*junitxml.JUnitTestSuites, error)","file":"cmd/prune-junit-xml/prunexml.go","code":"func fetchXML(xmlReader io.Reader) (*junitxml.JUnitTestSuites, error) {\n\tdecoder := xml.NewDecoder(xmlReader)\n\tvar suites junitxml.JUnitTestSuites\n\terr := decoder.Decode(\u0026suites)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026suites, nil\n}","line":{"from":85,"to":93}} {"id":100001645,"name":"streamXML","signature":"func streamXML(writer io.Writer, in *junitxml.JUnitTestSuites) error","file":"cmd/prune-junit-xml/prunexml.go","code":"func streamXML(writer io.Writer, in *junitxml.JUnitTestSuites) error {\n\t_, err := writer.Write([]byte(\"\u003c?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?\u003e\\n\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tencoder := xml.NewEncoder(writer)\n\tencoder.Indent(\"\", \"\\t\")\n\terr = encoder.Encode(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn encoder.Flush()\n}","line":{"from":95,"to":107}} {"id":100001646,"name":"main","signature":"func main()","file":"cmd/yamlfmt/yamlfmt.go","code":"func main() {\n\tindent := flag.Int(\"indent\", 2, \"default indent\")\n\tflag.Parse()\n\n\tif flag.NArg() \u003e 0 {\n\t\tfor _, path := range flag.Args() {\n\t\t\tsourceYaml, err := os.ReadFile(path)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"%s: %v\\n\", path, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\trootNode, err := fetchYaml(sourceYaml)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"%s: %v\\n\", path, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\twriter, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"%s: %v\\n\", path, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\terr = streamYaml(writer, indent, rootNode)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"%s: %v\\n\", path, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":28,"to":56}} {"id":100001647,"name":"fetchYaml","signature":"func fetchYaml(sourceYaml []byte) (*yaml.Node, error)","file":"cmd/yamlfmt/yamlfmt.go","code":"func fetchYaml(sourceYaml []byte) (*yaml.Node, error) {\n\trootNode := yaml.Node{}\n\terr := yaml.Unmarshal(sourceYaml, \u0026rootNode)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026rootNode, nil\n}","line":{"from":58,"to":65}} {"id":100001648,"name":"streamYaml","signature":"func streamYaml(writer io.Writer, indent *int, in *yaml.Node) error","file":"cmd/yamlfmt/yamlfmt.go","code":"func streamYaml(writer io.Writer, indent *int, in *yaml.Node) error {\n\tencoder := yaml.NewEncoder(writer)\n\tencoder.SetIndent(*indent)\n\terr := encoder.Encode(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn encoder.Close()\n}","line":{"from":67,"to":75}} {"id":100001649,"name":"GetNodeLabelDeprecatedMessage","signature":"func GetNodeLabelDeprecatedMessage(key string) (string, bool)","file":"pkg/api/node/util.go","code":"// GetNodeLabelDeprecatedMessage returns the message for the deprecated node label\n// and a bool indicating if the label is deprecated.\nfunc GetNodeLabelDeprecatedMessage(key string) (string, bool) {\n\tmsg, ok := deprecatedNodeLabels[key]\n\treturn msg, ok\n}","line":{"from":36,"to":41}} {"id":100001650,"name":"GetWarningsForRuntimeClass","signature":"func GetWarningsForRuntimeClass(rc *node.RuntimeClass) []string","file":"pkg/api/node/util.go","code":"func GetWarningsForRuntimeClass(rc *node.RuntimeClass) []string {\n\tvar warnings []string\n\n\tif rc != nil \u0026\u0026 rc.Scheduling != nil \u0026\u0026 rc.Scheduling.NodeSelector != nil {\n\t\t// use of deprecated node labels in scheduling's node affinity\n\t\tfor key := range rc.Scheduling.NodeSelector {\n\t\t\tif msg, deprecated := GetNodeLabelDeprecatedMessage(key); deprecated {\n\t\t\t\twarnings = append(warnings, fmt.Sprintf(\"%s: %s\", field.NewPath(\"scheduling\", \"nodeSelector\"), msg))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn warnings\n}","line":{"from":43,"to":56}} {"id":100001651,"name":"GetWarningsForNodeSelector","signature":"func GetWarningsForNodeSelector(nodeSelector *metav1.LabelSelector, fieldPath *field.Path) []string","file":"pkg/api/node/util.go","code":"// GetWarningsForNodeSelector tests if any of the node selector requirements in the template is deprecated.\n// If there are deprecated node selector requirements in either match expressions or match labels, a warning is returned.\nfunc GetWarningsForNodeSelector(nodeSelector *metav1.LabelSelector, fieldPath *field.Path) []string {\n\tif nodeSelector == nil {\n\t\treturn nil\n\t}\n\n\tvar warnings []string\n\t// use of deprecated node labels in matchLabelExpressions\n\tfor i, expression := range nodeSelector.MatchExpressions {\n\t\tif msg, deprecated := GetNodeLabelDeprecatedMessage(expression.Key); deprecated {\n\t\t\twarnings = append(\n\t\t\t\twarnings,\n\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\"%s: %s is %s\",\n\t\t\t\t\tfieldPath.Child(\"matchExpressions\").Index(i).Child(\"key\"),\n\t\t\t\t\texpression.Key,\n\t\t\t\t\tmsg,\n\t\t\t\t),\n\t\t\t)\n\t\t}\n\t}\n\n\t// use of deprecated node labels in matchLabels\n\tfor label := range nodeSelector.MatchLabels {\n\t\tif msg, deprecated := GetNodeLabelDeprecatedMessage(label); deprecated {\n\t\t\twarnings = append(warnings, fmt.Sprintf(\"%s: %s\", fieldPath.Child(\"matchLabels\").Child(label), msg))\n\t\t}\n\t}\n\treturn warnings\n}","line":{"from":58,"to":88}} {"id":100001652,"name":"GetWarningsForNodeSelectorTerm","signature":"func GetWarningsForNodeSelectorTerm(nodeSelectorTerm api.NodeSelectorTerm, fieldPath *field.Path) []string","file":"pkg/api/node/util.go","code":"// GetWarningsForNodeSelectorTerm checks match expressions of node selector term\nfunc GetWarningsForNodeSelectorTerm(nodeSelectorTerm api.NodeSelectorTerm, fieldPath *field.Path) []string {\n\tvar warnings []string\n\t// use of deprecated node labels in matchLabelExpressions\n\tfor i, expression := range nodeSelectorTerm.MatchExpressions {\n\t\tif msg, deprecated := GetNodeLabelDeprecatedMessage(expression.Key); deprecated {\n\t\t\twarnings = append(\n\t\t\t\twarnings,\n\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\"%s: %s is %s\",\n\t\t\t\t\tfieldPath.Child(\"matchExpressions\").Index(i).Child(\"key\"),\n\t\t\t\t\texpression.Key,\n\t\t\t\t\tmsg,\n\t\t\t\t),\n\t\t\t)\n\t\t}\n\t}\n\treturn warnings\n}","line":{"from":90,"to":108}} {"id":100001653,"name":"DropDisabledFields","signature":"func DropDisabledFields(pvSpec *api.PersistentVolumeSpec, oldPVSpec *api.PersistentVolumeSpec)","file":"pkg/api/persistentvolume/util.go","code":"// DropDisabledFields removes disabled fields from the pv spec.\n// This should be called from PrepareForCreate/PrepareForUpdate for all resources containing a pv spec.\nfunc DropDisabledFields(pvSpec *api.PersistentVolumeSpec, oldPVSpec *api.PersistentVolumeSpec) {\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.CSINodeExpandSecret) \u0026\u0026 !hasNodeExpansionSecrets(oldPVSpec) {\n\t\tif pvSpec.CSI != nil {\n\t\t\tpvSpec.CSI.NodeExpandSecretRef = nil\n\t\t}\n\t}\n}","line":{"from":27,"to":35}} {"id":100001654,"name":"hasNodeExpansionSecrets","signature":"func hasNodeExpansionSecrets(oldPVSpec *api.PersistentVolumeSpec) bool","file":"pkg/api/persistentvolume/util.go","code":"func hasNodeExpansionSecrets(oldPVSpec *api.PersistentVolumeSpec) bool {\n\tif oldPVSpec == nil || oldPVSpec.CSI == nil {\n\t\treturn false\n\t}\n\n\tif oldPVSpec.CSI.NodeExpandSecretRef != nil {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":37,"to":46}} {"id":100001655,"name":"GetWarningsForPersistentVolume","signature":"func GetWarningsForPersistentVolume(pv *api.PersistentVolume) []string","file":"pkg/api/persistentvolume/util.go","code":"func GetWarningsForPersistentVolume(pv *api.PersistentVolume) []string {\n\tif pv == nil {\n\t\treturn nil\n\t}\n\treturn warningsForPersistentVolumeSpecAndMeta(nil, \u0026pv.Spec)\n}","line":{"from":48,"to":53}} {"id":100001656,"name":"warningsForPersistentVolumeSpecAndMeta","signature":"func warningsForPersistentVolumeSpecAndMeta(fieldPath *field.Path, pvSpec *api.PersistentVolumeSpec) []string","file":"pkg/api/persistentvolume/util.go","code":"func warningsForPersistentVolumeSpecAndMeta(fieldPath *field.Path, pvSpec *api.PersistentVolumeSpec) []string {\n\tvar warnings []string\n\n\tif pvSpec.NodeAffinity != nil \u0026\u0026 pvSpec.NodeAffinity.Required != nil {\n\t\ttermFldPath := fieldPath.Child(\"spec\", \"nodeAffinity\", \"required\", \"nodeSelectorTerms\")\n\t\t// use of deprecated node labels in node affinity\n\t\tfor i, term := range pvSpec.NodeAffinity.Required.NodeSelectorTerms {\n\t\t\twarnings = append(warnings, nodeapi.GetWarningsForNodeSelectorTerm(term, termFldPath.Index(i))...)\n\t\t}\n\t}\n\n\treturn warnings\n}","line":{"from":55,"to":67}} {"id":100001657,"name":"DropDisabledFields","signature":"func DropDisabledFields(pvcSpec, oldPVCSpec *core.PersistentVolumeClaimSpec)","file":"pkg/api/persistentvolumeclaim/util.go","code":"// DropDisabledFields removes disabled fields from the pvc spec.\n// This should be called from PrepareForCreate/PrepareForUpdate for all resources containing a pvc spec.\nfunc DropDisabledFields(pvcSpec, oldPVCSpec *core.PersistentVolumeClaimSpec) {\n\t// Drop the contents of the dataSourceRef field if the AnyVolumeDataSource\n\t// feature gate is disabled.\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.AnyVolumeDataSource) {\n\t\tif !dataSourceRefInUse(oldPVCSpec) {\n\t\t\tpvcSpec.DataSourceRef = nil\n\t\t}\n\t}\n\n\t// Drop the contents of the dataSourceRef field if the CrossNamespaceVolumeDataSource\n\t// feature gate is disabled and dataSourceRef.Namespace is specified.\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.CrossNamespaceVolumeDataSource) \u0026\u0026\n\t\tpvcSpec.DataSourceRef != nil \u0026\u0026 pvcSpec.DataSourceRef.Namespace != nil \u0026\u0026 len(*pvcSpec.DataSourceRef.Namespace) != 0 {\n\t\tif !dataSourceRefInUse(oldPVCSpec) {\n\t\t\tpvcSpec.DataSourceRef = nil\n\t\t}\n\t}\n\n\t// Setting VolumeClaimTemplate.Resources.Claims should have been caught by validation when\n\t// extending ResourceRequirements in 1.26. Now we can only accept it and drop the field.\n\tpvcSpec.Resources.Claims = nil\n}","line":{"from":33,"to":56}} {"id":100001658,"name":"EnforceDataSourceBackwardsCompatibility","signature":"func EnforceDataSourceBackwardsCompatibility(pvcSpec, oldPVCSpec *core.PersistentVolumeClaimSpec)","file":"pkg/api/persistentvolumeclaim/util.go","code":"// EnforceDataSourceBackwardsCompatibility drops the data source field under certain conditions\n// to maintain backwards compatibility with old behavior.\n// See KEP 1495 for details.\n// Specifically, if this is an update of a PVC with no data source, or a creation of a new PVC,\n// and the dataSourceRef field is not filled in, then we will drop \"invalid\" data sources\n// (anything other than a PVC or a VolumeSnapshot) from this request as if an empty PVC had\n// been requested.\n// This should be called after DropDisabledFields so that if the AnyVolumeDataSource feature\n// gate is disabled, dataSourceRef will be forced to empty, ensuring pre-1.22 behavior.\n// This should be called before NormalizeDataSources, so that data sources other than PVCs\n// and VolumeSnapshots can only be set through the dataSourceRef field and not the dataSource\n// field.\nfunc EnforceDataSourceBackwardsCompatibility(pvcSpec, oldPVCSpec *core.PersistentVolumeClaimSpec) {\n\t// Check if the old PVC has a data source here is so that on updates from old clients\n\t// that omit dataSourceRef, we preserve the data source, even if it would have been\n\t// invalid to specify it at using the dataSource field at create.\n\tif dataSourceInUse(oldPVCSpec) {\n\t\treturn\n\t}\n\n\t// Check if dataSourceRef is empty is because if it's not empty, then there is\n\t// definitely a newer client and it definitely either wants to create a non-empty\n\t// volume, or it wants to update a PVC that has a data source. Whether the\n\t// specified data source is valid or satisfiable is a matter for validation and\n\t// the volume populator code, but we can say with certainty that the client is\n\t// not expecting the legacy behavior of ignoring invalid data sources.\n\tif pvcSpec.DataSourceRef != nil {\n\t\treturn\n\t}\n\n\t// Historically, we only allow PVCs and VolumeSnapshots in the dataSource field.\n\t// All other values are silently dropped.\n\tif !dataSourceIsPvcOrSnapshot(pvcSpec.DataSource) {\n\t\tpvcSpec.DataSource = nil\n\t}\n}","line":{"from":58,"to":93}} {"id":100001659,"name":"DropDisabledFieldsFromStatus","signature":"func DropDisabledFieldsFromStatus(pvc, oldPVC *core.PersistentVolumeClaim)","file":"pkg/api/persistentvolumeclaim/util.go","code":"func DropDisabledFieldsFromStatus(pvc, oldPVC *core.PersistentVolumeClaim) {\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.RecoverVolumeExpansionFailure) {\n\t\tif !allocatedResourcesInUse(oldPVC) {\n\t\t\tpvc.Status.AllocatedResources = nil\n\t\t}\n\t\tif !resizeStatusInUse(oldPVC) {\n\t\t\tpvc.Status.ResizeStatus = nil\n\t\t}\n\t}\n}","line":{"from":95,"to":104}} {"id":100001660,"name":"dataSourceInUse","signature":"func dataSourceInUse(oldPVCSpec *core.PersistentVolumeClaimSpec) bool","file":"pkg/api/persistentvolumeclaim/util.go","code":"func dataSourceInUse(oldPVCSpec *core.PersistentVolumeClaimSpec) bool {\n\tif oldPVCSpec == nil {\n\t\treturn false\n\t}\n\tif oldPVCSpec.DataSource != nil || oldPVCSpec.DataSourceRef != nil {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":106,"to":114}} {"id":100001661,"name":"dataSourceIsPvcOrSnapshot","signature":"func dataSourceIsPvcOrSnapshot(dataSource *core.TypedLocalObjectReference) bool","file":"pkg/api/persistentvolumeclaim/util.go","code":"func dataSourceIsPvcOrSnapshot(dataSource *core.TypedLocalObjectReference) bool {\n\tif dataSource != nil {\n\t\tapiGroup := \"\"\n\t\tif dataSource.APIGroup != nil {\n\t\t\tapiGroup = *dataSource.APIGroup\n\t\t}\n\t\tif dataSource.Kind == pvc \u0026\u0026\n\t\t\tapiGroup == \"\" {\n\t\t\treturn true\n\t\t}\n\n\t\tif dataSource.Kind == volumeSnapshot \u0026\u0026 apiGroup == \"snapshot.storage.k8s.io\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":116,"to":132}} {"id":100001662,"name":"dataSourceRefInUse","signature":"func dataSourceRefInUse(oldPVCSpec *core.PersistentVolumeClaimSpec) bool","file":"pkg/api/persistentvolumeclaim/util.go","code":"func dataSourceRefInUse(oldPVCSpec *core.PersistentVolumeClaimSpec) bool {\n\tif oldPVCSpec == nil {\n\t\treturn false\n\t}\n\tif oldPVCSpec.DataSourceRef != nil {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":134,"to":142}} {"id":100001663,"name":"NormalizeDataSources","signature":"func NormalizeDataSources(pvcSpec *core.PersistentVolumeClaimSpec)","file":"pkg/api/persistentvolumeclaim/util.go","code":"// NormalizeDataSources ensures that DataSource and DataSourceRef have the same contents\n// as long as both are not explicitly set.\n// This should be used by creates/gets of PVCs, but not updates\nfunc NormalizeDataSources(pvcSpec *core.PersistentVolumeClaimSpec) {\n\t// Don't enable this behavior if the feature gate is not on\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.AnyVolumeDataSource) {\n\t\treturn\n\t}\n\tif pvcSpec.DataSource != nil \u0026\u0026 pvcSpec.DataSourceRef == nil {\n\t\t// Using the old way of setting a data source\n\t\tpvcSpec.DataSourceRef = \u0026core.TypedObjectReference{\n\t\t\tKind: pvcSpec.DataSource.Kind,\n\t\t\tName: pvcSpec.DataSource.Name,\n\t\t}\n\t\tif pvcSpec.DataSource.APIGroup != nil {\n\t\t\tapiGroup := *pvcSpec.DataSource.APIGroup\n\t\t\tpvcSpec.DataSourceRef.APIGroup = \u0026apiGroup\n\t\t}\n\t} else if pvcSpec.DataSourceRef != nil \u0026\u0026 pvcSpec.DataSource == nil {\n\t\tif pvcSpec.DataSourceRef.Namespace == nil || len(*pvcSpec.DataSourceRef.Namespace) == 0 {\n\t\t\t// Using the new way of setting a data source\n\t\t\tpvcSpec.DataSource = \u0026core.TypedLocalObjectReference{\n\t\t\t\tKind: pvcSpec.DataSourceRef.Kind,\n\t\t\t\tName: pvcSpec.DataSourceRef.Name,\n\t\t\t}\n\t\t\tif pvcSpec.DataSourceRef.APIGroup != nil {\n\t\t\t\tapiGroup := *pvcSpec.DataSourceRef.APIGroup\n\t\t\t\tpvcSpec.DataSource.APIGroup = \u0026apiGroup\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":144,"to":175}} {"id":100001664,"name":"resizeStatusInUse","signature":"func resizeStatusInUse(oldPVC *core.PersistentVolumeClaim) bool","file":"pkg/api/persistentvolumeclaim/util.go","code":"func resizeStatusInUse(oldPVC *core.PersistentVolumeClaim) bool {\n\tif oldPVC == nil {\n\t\treturn false\n\t}\n\tif oldPVC.Status.ResizeStatus != nil {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":177,"to":185}} {"id":100001665,"name":"allocatedResourcesInUse","signature":"func allocatedResourcesInUse(oldPVC *core.PersistentVolumeClaim) bool","file":"pkg/api/persistentvolumeclaim/util.go","code":"func allocatedResourcesInUse(oldPVC *core.PersistentVolumeClaim) bool {\n\tif oldPVC == nil {\n\t\treturn false\n\t}\n\n\tif oldPVC.Status.AllocatedResources != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":187,"to":197}} {"id":100001666,"name":"GetWarningsForPersistentVolumeClaim","signature":"func GetWarningsForPersistentVolumeClaim(pv *core.PersistentVolumeClaim) []string","file":"pkg/api/persistentvolumeclaim/util.go","code":"func GetWarningsForPersistentVolumeClaim(pv *core.PersistentVolumeClaim) []string {\n\tif pv == nil {\n\t\treturn nil\n\t}\n\n\treturn GetWarningsForPersistentVolumeClaimSpec(field.NewPath(\"spec\"), pv.Spec)\n}","line":{"from":199,"to":205}} {"id":100001667,"name":"GetWarningsForPersistentVolumeClaimSpec","signature":"func GetWarningsForPersistentVolumeClaimSpec(fieldPath *field.Path, pvSpec core.PersistentVolumeClaimSpec) []string","file":"pkg/api/persistentvolumeclaim/util.go","code":"func GetWarningsForPersistentVolumeClaimSpec(fieldPath *field.Path, pvSpec core.PersistentVolumeClaimSpec) []string {\n\n\tvar warnings []string\n\trequestValue := pvSpec.Resources.Requests[core.ResourceStorage]\n\tif requestValue.MilliValue()%int64(1000) != int64(0) {\n\t\twarnings = append(warnings, fmt.Sprintf(\n\t\t\t\"%s: fractional byte value %q is invalid, must be an integer\",\n\t\t\tfieldPath.Child(\"resources\").Child(\"requests\").Key(core.ResourceStorage.String()), requestValue.String()))\n\t}\n\tlimitValue := pvSpec.Resources.Limits[core.ResourceStorage]\n\tif limitValue.MilliValue()%int64(1000) != int64(0) {\n\t\twarnings = append(warnings, fmt.Sprintf(\n\t\t\t\"%s: fractional byte value %q is invalid, must be an integer\",\n\t\t\tfieldPath.Child(\"resources\").Child(\"limits\").Key(core.ResourceStorage.String()), limitValue.String()))\n\t}\n\treturn warnings\n}","line":{"from":207,"to":223}} {"id":100001668,"name":"AllFeatureEnabledContainers","signature":"func AllFeatureEnabledContainers() ContainerType","file":"pkg/api/pod/util.go","code":"// AllFeatureEnabledContainers returns a ContainerType mask which includes all container\n// types except for the ones guarded by feature gate.\nfunc AllFeatureEnabledContainers() ContainerType {\n\treturn AllContainers\n}","line":{"from":48,"to":52}} {"id":100001669,"name":"VisitContainers","signature":"func VisitContainers(podSpec *api.PodSpec, mask ContainerType, visitor ContainerVisitor) bool","file":"pkg/api/pod/util.go","code":"// VisitContainers invokes the visitor function with a pointer to every container\n// spec in the given pod spec with type set in mask. If visitor returns false,\n// visiting is short-circuited. VisitContainers returns true if visiting completes,\n// false if visiting was short-circuited.\nfunc VisitContainers(podSpec *api.PodSpec, mask ContainerType, visitor ContainerVisitor) bool {\n\tif mask\u0026InitContainers != 0 {\n\t\tfor i := range podSpec.InitContainers {\n\t\t\tif !visitor(\u0026podSpec.InitContainers[i], InitContainers) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\tif mask\u0026Containers != 0 {\n\t\tfor i := range podSpec.Containers {\n\t\t\tif !visitor(\u0026podSpec.Containers[i], Containers) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\tif mask\u0026EphemeralContainers != 0 {\n\t\tfor i := range podSpec.EphemeralContainers {\n\t\t\tif !visitor((*api.Container)(\u0026podSpec.EphemeralContainers[i].EphemeralContainerCommon), EphemeralContainers) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}","line":{"from":58,"to":85}} {"id":100001670,"name":"skipEmptyNames","signature":"func skipEmptyNames(visitor Visitor) Visitor","file":"pkg/api/pod/util.go","code":"func skipEmptyNames(visitor Visitor) Visitor {\n\treturn func(name string) bool {\n\t\tif len(name) == 0 {\n\t\t\t// continue visiting\n\t\t\treturn true\n\t\t}\n\t\t// delegate to visitor\n\t\treturn visitor(name)\n\t}\n}","line":{"from":90,"to":99}} {"id":100001671,"name":"VisitPodSecretNames","signature":"func VisitPodSecretNames(pod *api.Pod, visitor Visitor, containerType ContainerType) bool","file":"pkg/api/pod/util.go","code":"// VisitPodSecretNames invokes the visitor function with the name of every secret\n// referenced by the pod spec. If visitor returns false, visiting is short-circuited.\n// Transitive references (e.g. pod -\u003e pvc -\u003e pv -\u003e secret) are not visited.\n// Returns true if visiting completed, false if visiting was short-circuited.\nfunc VisitPodSecretNames(pod *api.Pod, visitor Visitor, containerType ContainerType) bool {\n\tvisitor = skipEmptyNames(visitor)\n\tfor _, reference := range pod.Spec.ImagePullSecrets {\n\t\tif !visitor(reference.Name) {\n\t\t\treturn false\n\t\t}\n\t}\n\tVisitContainers(\u0026pod.Spec, containerType, func(c *api.Container, containerType ContainerType) bool {\n\t\treturn visitContainerSecretNames(c, visitor)\n\t})\n\tvar source *api.VolumeSource\n\tfor i := range pod.Spec.Volumes {\n\t\tsource = \u0026pod.Spec.Volumes[i].VolumeSource\n\t\tswitch {\n\t\tcase source.AzureFile != nil:\n\t\t\tif len(source.AzureFile.SecretName) \u003e 0 \u0026\u0026 !visitor(source.AzureFile.SecretName) {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase source.CephFS != nil:\n\t\t\tif source.CephFS.SecretRef != nil \u0026\u0026 !visitor(source.CephFS.SecretRef.Name) {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase source.Cinder != nil:\n\t\t\tif source.Cinder.SecretRef != nil \u0026\u0026 !visitor(source.Cinder.SecretRef.Name) {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase source.FlexVolume != nil:\n\t\t\tif source.FlexVolume.SecretRef != nil \u0026\u0026 !visitor(source.FlexVolume.SecretRef.Name) {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase source.Projected != nil:\n\t\t\tfor j := range source.Projected.Sources {\n\t\t\t\tif source.Projected.Sources[j].Secret != nil {\n\t\t\t\t\tif !visitor(source.Projected.Sources[j].Secret.Name) {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase source.RBD != nil:\n\t\t\tif source.RBD.SecretRef != nil \u0026\u0026 !visitor(source.RBD.SecretRef.Name) {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase source.Secret != nil:\n\t\t\tif !visitor(source.Secret.SecretName) {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase source.ScaleIO != nil:\n\t\t\tif source.ScaleIO.SecretRef != nil \u0026\u0026 !visitor(source.ScaleIO.SecretRef.Name) {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase source.ISCSI != nil:\n\t\t\tif source.ISCSI.SecretRef != nil \u0026\u0026 !visitor(source.ISCSI.SecretRef.Name) {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase source.StorageOS != nil:\n\t\t\tif source.StorageOS.SecretRef != nil \u0026\u0026 !visitor(source.StorageOS.SecretRef.Name) {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase source.CSI != nil:\n\t\t\tif source.CSI.NodePublishSecretRef != nil \u0026\u0026 !visitor(source.CSI.NodePublishSecretRef.Name) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}","line":{"from":101,"to":170}} {"id":100001672,"name":"visitContainerSecretNames","signature":"func visitContainerSecretNames(container *api.Container, visitor Visitor) bool","file":"pkg/api/pod/util.go","code":"func visitContainerSecretNames(container *api.Container, visitor Visitor) bool {\n\tfor _, env := range container.EnvFrom {\n\t\tif env.SecretRef != nil {\n\t\t\tif !visitor(env.SecretRef.Name) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\tfor _, envVar := range container.Env {\n\t\tif envVar.ValueFrom != nil \u0026\u0026 envVar.ValueFrom.SecretKeyRef != nil {\n\t\t\tif !visitor(envVar.ValueFrom.SecretKeyRef.Name) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}","line":{"from":172,"to":188}} {"id":100001673,"name":"VisitPodConfigmapNames","signature":"func VisitPodConfigmapNames(pod *api.Pod, visitor Visitor, containerType ContainerType) bool","file":"pkg/api/pod/util.go","code":"// VisitPodConfigmapNames invokes the visitor function with the name of every configmap\n// referenced by the pod spec. If visitor returns false, visiting is short-circuited.\n// Transitive references (e.g. pod -\u003e pvc -\u003e pv -\u003e secret) are not visited.\n// Returns true if visiting completed, false if visiting was short-circuited.\nfunc VisitPodConfigmapNames(pod *api.Pod, visitor Visitor, containerType ContainerType) bool {\n\tvisitor = skipEmptyNames(visitor)\n\tVisitContainers(\u0026pod.Spec, containerType, func(c *api.Container, containerType ContainerType) bool {\n\t\treturn visitContainerConfigmapNames(c, visitor)\n\t})\n\tvar source *api.VolumeSource\n\tfor i := range pod.Spec.Volumes {\n\t\tsource = \u0026pod.Spec.Volumes[i].VolumeSource\n\t\tswitch {\n\t\tcase source.Projected != nil:\n\t\t\tfor j := range source.Projected.Sources {\n\t\t\t\tif source.Projected.Sources[j].ConfigMap != nil {\n\t\t\t\t\tif !visitor(source.Projected.Sources[j].ConfigMap.Name) {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase source.ConfigMap != nil:\n\t\t\tif !visitor(source.ConfigMap.Name) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}","line":{"from":190,"to":218}} {"id":100001674,"name":"visitContainerConfigmapNames","signature":"func visitContainerConfigmapNames(container *api.Container, visitor Visitor) bool","file":"pkg/api/pod/util.go","code":"func visitContainerConfigmapNames(container *api.Container, visitor Visitor) bool {\n\tfor _, env := range container.EnvFrom {\n\t\tif env.ConfigMapRef != nil {\n\t\t\tif !visitor(env.ConfigMapRef.Name) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\tfor _, envVar := range container.Env {\n\t\tif envVar.ValueFrom != nil \u0026\u0026 envVar.ValueFrom.ConfigMapKeyRef != nil {\n\t\t\tif !visitor(envVar.ValueFrom.ConfigMapKeyRef.Name) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}","line":{"from":220,"to":236}} {"id":100001675,"name":"IsPodReady","signature":"func IsPodReady(pod *api.Pod) bool","file":"pkg/api/pod/util.go","code":"// IsPodReady returns true if a pod is ready; false otherwise.\nfunc IsPodReady(pod *api.Pod) bool {\n\treturn IsPodReadyConditionTrue(pod.Status)\n}","line":{"from":238,"to":241}} {"id":100001676,"name":"IsPodReadyConditionTrue","signature":"func IsPodReadyConditionTrue(status api.PodStatus) bool","file":"pkg/api/pod/util.go","code":"// IsPodReadyConditionTrue returns true if a pod is ready; false otherwise.\nfunc IsPodReadyConditionTrue(status api.PodStatus) bool {\n\tcondition := GetPodReadyCondition(status)\n\treturn condition != nil \u0026\u0026 condition.Status == api.ConditionTrue\n}","line":{"from":243,"to":247}} {"id":100001677,"name":"GetPodReadyCondition","signature":"func GetPodReadyCondition(status api.PodStatus) *api.PodCondition","file":"pkg/api/pod/util.go","code":"// GetPodReadyCondition extracts the pod ready condition from the given status and returns that.\n// Returns nil if the condition is not present.\nfunc GetPodReadyCondition(status api.PodStatus) *api.PodCondition {\n\t_, condition := GetPodCondition(\u0026status, api.PodReady)\n\treturn condition\n}","line":{"from":249,"to":254}} {"id":100001678,"name":"GetPodCondition","signature":"func GetPodCondition(status *api.PodStatus, conditionType api.PodConditionType) (int, *api.PodCondition)","file":"pkg/api/pod/util.go","code":"// GetPodCondition extracts the provided condition from the given status and returns that.\n// Returns nil and -1 if the condition is not present, and the index of the located condition.\nfunc GetPodCondition(status *api.PodStatus, conditionType api.PodConditionType) (int, *api.PodCondition) {\n\tif status == nil {\n\t\treturn -1, nil\n\t}\n\tfor i := range status.Conditions {\n\t\tif status.Conditions[i].Type == conditionType {\n\t\t\treturn i, \u0026status.Conditions[i]\n\t\t}\n\t}\n\treturn -1, nil\n}","line":{"from":256,"to":268}} {"id":100001679,"name":"UpdatePodCondition","signature":"func UpdatePodCondition(status *api.PodStatus, condition *api.PodCondition) bool","file":"pkg/api/pod/util.go","code":"// UpdatePodCondition updates existing pod condition or creates a new one. Sets LastTransitionTime to now if the\n// status has changed.\n// Returns true if pod condition has changed or has been added.\nfunc UpdatePodCondition(status *api.PodStatus, condition *api.PodCondition) bool {\n\tcondition.LastTransitionTime = metav1.Now()\n\t// Try to find this pod condition.\n\tconditionIndex, oldCondition := GetPodCondition(status, condition.Type)\n\n\tif oldCondition == nil {\n\t\t// We are adding new pod condition.\n\t\tstatus.Conditions = append(status.Conditions, *condition)\n\t\treturn true\n\t}\n\t// We are updating an existing condition, so we need to check if it has changed.\n\tif condition.Status == oldCondition.Status {\n\t\tcondition.LastTransitionTime = oldCondition.LastTransitionTime\n\t}\n\n\tisEqual := condition.Status == oldCondition.Status \u0026\u0026\n\t\tcondition.Reason == oldCondition.Reason \u0026\u0026\n\t\tcondition.Message == oldCondition.Message \u0026\u0026\n\t\tcondition.LastProbeTime.Equal(\u0026oldCondition.LastProbeTime) \u0026\u0026\n\t\tcondition.LastTransitionTime.Equal(\u0026oldCondition.LastTransitionTime)\n\n\tstatus.Conditions[conditionIndex] = *condition\n\t// Return true if one of the fields have changed.\n\treturn !isEqual\n}","line":{"from":270,"to":297}} {"id":100001680,"name":"checkContainerUseIndivisibleHugePagesValues","signature":"func checkContainerUseIndivisibleHugePagesValues(container api.Container) bool","file":"pkg/api/pod/util.go","code":"func checkContainerUseIndivisibleHugePagesValues(container api.Container) bool {\n\tfor resourceName, quantity := range container.Resources.Limits {\n\t\tif helper.IsHugePageResourceName(resourceName) {\n\t\t\tif !helper.IsHugePageResourceValueDivisible(resourceName, quantity) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\tfor resourceName, quantity := range container.Resources.Requests {\n\t\tif helper.IsHugePageResourceName(resourceName) {\n\t\t\tif !helper.IsHugePageResourceValueDivisible(resourceName, quantity) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":299,"to":317}} {"id":100001681,"name":"usesIndivisibleHugePagesValues","signature":"func usesIndivisibleHugePagesValues(podSpec *api.PodSpec) bool","file":"pkg/api/pod/util.go","code":"// usesIndivisibleHugePagesValues returns true if the one of the containers uses non-integer multiple\n// of huge page unit size\nfunc usesIndivisibleHugePagesValues(podSpec *api.PodSpec) bool {\n\tfoundIndivisibleHugePagesValue := false\n\tVisitContainers(podSpec, AllContainers, func(c *api.Container, containerType ContainerType) bool {\n\t\tif checkContainerUseIndivisibleHugePagesValues(*c) {\n\t\t\tfoundIndivisibleHugePagesValue = true\n\t\t}\n\t\treturn !foundIndivisibleHugePagesValue // continue visiting if we haven't seen an invalid value yet\n\t})\n\n\tif foundIndivisibleHugePagesValue {\n\t\treturn true\n\t}\n\n\tfor resourceName, quantity := range podSpec.Overhead {\n\t\tif helper.IsHugePageResourceName(resourceName) {\n\t\t\tif !helper.IsHugePageResourceValueDivisible(resourceName, quantity) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":319,"to":343}} {"id":100001682,"name":"haveSameExpandedDNSConfig","signature":"func haveSameExpandedDNSConfig(podSpec, oldPodSpec *api.PodSpec) bool","file":"pkg/api/pod/util.go","code":"// haveSameExpandedDNSConfig returns true if the oldPodSpec already had\n// ExpandedDNSConfig and podSpec has the same DNSConfig\nfunc haveSameExpandedDNSConfig(podSpec, oldPodSpec *api.PodSpec) bool {\n\tif oldPodSpec == nil || oldPodSpec.DNSConfig == nil {\n\t\treturn false\n\t}\n\tif podSpec == nil || podSpec.DNSConfig == nil {\n\t\treturn false\n\t}\n\n\tif len(oldPodSpec.DNSConfig.Searches) \u003c= apivalidation.MaxDNSSearchPathsLegacy \u0026\u0026\n\t\tlen(strings.Join(oldPodSpec.DNSConfig.Searches, \" \")) \u003c= apivalidation.MaxDNSSearchListCharsLegacy {\n\t\t// didn't have ExpandedDNSConfig\n\t\treturn false\n\t}\n\n\tif len(oldPodSpec.DNSConfig.Searches) != len(podSpec.DNSConfig.Searches) {\n\t\t// updates DNSConfig\n\t\treturn false\n\t}\n\n\tfor i, oldSearch := range oldPodSpec.DNSConfig.Searches {\n\t\tif podSpec.DNSConfig.Searches[i] != oldSearch {\n\t\t\t// updates DNSConfig\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}","line":{"from":345,"to":374}} {"id":100001683,"name":"hasInvalidTopologySpreadConstraintLabelSelector","signature":"func hasInvalidTopologySpreadConstraintLabelSelector(spec *api.PodSpec) bool","file":"pkg/api/pod/util.go","code":"// hasInvalidTopologySpreadConstraintLabelSelector return true if spec.TopologySpreadConstraints have any entry with invalid labelSelector\nfunc hasInvalidTopologySpreadConstraintLabelSelector(spec *api.PodSpec) bool {\n\tfor _, constraint := range spec.TopologySpreadConstraints {\n\t\terrs := metavalidation.ValidateLabelSelector(constraint.LabelSelector, metavalidation.LabelSelectorValidationOptions{AllowInvalidLabelValueInSelector: false}, nil)\n\t\tif len(errs) != 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":376,"to":385}} {"id":100001684,"name":"GetValidationOptionsFromPodSpecAndMeta","signature":"func GetValidationOptionsFromPodSpecAndMeta(podSpec, oldPodSpec *api.PodSpec, podMeta, oldPodMeta *metav1.ObjectMeta) apivalidation.PodValidationOptions","file":"pkg/api/pod/util.go","code":"// GetValidationOptionsFromPodSpecAndMeta returns validation options based on pod specs and metadata\nfunc GetValidationOptionsFromPodSpecAndMeta(podSpec, oldPodSpec *api.PodSpec, podMeta, oldPodMeta *metav1.ObjectMeta) apivalidation.PodValidationOptions {\n\t// default pod validation options based on feature gate\n\topts := apivalidation.PodValidationOptions{\n\t\tAllowInvalidPodDeletionCost: !utilfeature.DefaultFeatureGate.Enabled(features.PodDeletionCost),\n\t\t// Do not allow pod spec to use non-integer multiple of huge page unit size default\n\t\tAllowIndivisibleHugePagesValues: false,\n\t\t// Allow pod spec with expanded DNS configuration\n\t\tAllowExpandedDNSConfig: utilfeature.DefaultFeatureGate.Enabled(features.ExpandedDNSConfig) || haveSameExpandedDNSConfig(podSpec, oldPodSpec),\n\t\tAllowInvalidLabelValueInSelector: false,\n\t\tAllowInvalidTopologySpreadConstraintLabelSelector: false,\n\t\tAllowMutableNodeSelectorAndNodeAffinity: utilfeature.DefaultFeatureGate.Enabled(features.PodSchedulingReadiness),\n\t}\n\n\tif oldPodSpec != nil {\n\t\t// if old spec used non-integer multiple of huge page unit size, we must allow it\n\t\topts.AllowIndivisibleHugePagesValues = usesIndivisibleHugePagesValues(oldPodSpec)\n\n\t\topts.AllowInvalidLabelValueInSelector = hasInvalidLabelValueInAffinitySelector(oldPodSpec)\n\t\t// if old spec has invalid labelSelector in topologySpreadConstraint, we must allow it\n\t\topts.AllowInvalidTopologySpreadConstraintLabelSelector = hasInvalidTopologySpreadConstraintLabelSelector(oldPodSpec)\n\t}\n\tif oldPodMeta != nil \u0026\u0026 !opts.AllowInvalidPodDeletionCost {\n\t\t// This is an update, so validate only if the existing object was valid.\n\t\t_, err := helper.GetDeletionCostFromPodAnnotations(oldPodMeta.Annotations)\n\t\topts.AllowInvalidPodDeletionCost = err != nil\n\t}\n\n\treturn opts\n}","line":{"from":387,"to":416}} {"id":100001685,"name":"GetValidationOptionsFromPodTemplate","signature":"func GetValidationOptionsFromPodTemplate(podTemplate, oldPodTemplate *api.PodTemplateSpec) apivalidation.PodValidationOptions","file":"pkg/api/pod/util.go","code":"// GetValidationOptionsFromPodTemplate will return pod validation options for specified template.\nfunc GetValidationOptionsFromPodTemplate(podTemplate, oldPodTemplate *api.PodTemplateSpec) apivalidation.PodValidationOptions {\n\tvar newPodSpec, oldPodSpec *api.PodSpec\n\tvar newPodMeta, oldPodMeta *metav1.ObjectMeta\n\t// we have to be careful about nil pointers here\n\t// replication controller in particular is prone to passing nil\n\tif podTemplate != nil {\n\t\tnewPodSpec = \u0026podTemplate.Spec\n\t\tnewPodMeta = \u0026podTemplate.ObjectMeta\n\t}\n\tif oldPodTemplate != nil {\n\t\toldPodSpec = \u0026oldPodTemplate.Spec\n\t\toldPodMeta = \u0026oldPodTemplate.ObjectMeta\n\t}\n\treturn GetValidationOptionsFromPodSpecAndMeta(newPodSpec, oldPodSpec, newPodMeta, oldPodMeta)\n}","line":{"from":418,"to":433}} {"id":100001686,"name":"DropDisabledTemplateFields","signature":"func DropDisabledTemplateFields(podTemplate, oldPodTemplate *api.PodTemplateSpec)","file":"pkg/api/pod/util.go","code":"// DropDisabledTemplateFields removes disabled fields from the pod template metadata and spec.\n// This should be called from PrepareForCreate/PrepareForUpdate for all resources containing a PodTemplateSpec\nfunc DropDisabledTemplateFields(podTemplate, oldPodTemplate *api.PodTemplateSpec) {\n\tvar (\n\t\tpodSpec *api.PodSpec\n\t\tpodAnnotations map[string]string\n\t\toldPodSpec *api.PodSpec\n\t\toldPodAnnotations map[string]string\n\t)\n\tif podTemplate != nil {\n\t\tpodSpec = \u0026podTemplate.Spec\n\t\tpodAnnotations = podTemplate.Annotations\n\t}\n\tif oldPodTemplate != nil {\n\t\toldPodSpec = \u0026oldPodTemplate.Spec\n\t\toldPodAnnotations = oldPodTemplate.Annotations\n\t}\n\tdropDisabledFields(podSpec, podAnnotations, oldPodSpec, oldPodAnnotations)\n}","line":{"from":435,"to":453}} {"id":100001687,"name":"DropDisabledPodFields","signature":"func DropDisabledPodFields(pod, oldPod *api.Pod)","file":"pkg/api/pod/util.go","code":"// DropDisabledPodFields removes disabled fields from the pod metadata and spec.\n// This should be called from PrepareForCreate/PrepareForUpdate for all resources containing a Pod\nfunc DropDisabledPodFields(pod, oldPod *api.Pod) {\n\tvar (\n\t\tpodSpec *api.PodSpec\n\t\tpodStatus *api.PodStatus\n\t\tpodAnnotations map[string]string\n\t\toldPodSpec *api.PodSpec\n\t\toldPodStatus *api.PodStatus\n\t\toldPodAnnotations map[string]string\n\t)\n\tif pod != nil {\n\t\tpodSpec = \u0026pod.Spec\n\t\tpodStatus = \u0026pod.Status\n\t\tpodAnnotations = pod.Annotations\n\t}\n\tif oldPod != nil {\n\t\toldPodSpec = \u0026oldPod.Spec\n\t\toldPodStatus = \u0026oldPod.Status\n\t\toldPodAnnotations = oldPod.Annotations\n\t}\n\tdropDisabledFields(podSpec, podAnnotations, oldPodSpec, oldPodAnnotations)\n\tdropDisabledPodStatusFields(podStatus, oldPodStatus, podSpec, oldPodSpec)\n}","line":{"from":455,"to":478}} {"id":100001688,"name":"dropDisabledFields","signature":"func dropDisabledFields(","file":"pkg/api/pod/util.go","code":"// dropDisabledFields removes disabled fields from the pod metadata and spec.\nfunc dropDisabledFields(\n\tpodSpec *api.PodSpec, podAnnotations map[string]string,\n\toldPodSpec *api.PodSpec, oldPodAnnotations map[string]string,\n) {\n\t// the new spec must always be non-nil\n\tif podSpec == nil {\n\t\tpodSpec = \u0026api.PodSpec{}\n\t}\n\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.AppArmor) \u0026\u0026 !appArmorInUse(oldPodAnnotations) {\n\t\tfor k := range podAnnotations {\n\t\t\tif strings.HasPrefix(k, v1.AppArmorBetaContainerAnnotationKeyPrefix) {\n\t\t\t\tdelete(podAnnotations, k)\n\t\t\t}\n\t\t}\n\t}\n\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.ProbeTerminationGracePeriod) \u0026\u0026 !probeGracePeriodInUse(oldPodSpec) {\n\t\t// Set pod-level terminationGracePeriodSeconds to nil if the feature is disabled and it is not used\n\t\tVisitContainers(podSpec, AllContainers, func(c *api.Container, containerType ContainerType) bool {\n\t\t\tif c.LivenessProbe != nil {\n\t\t\t\tc.LivenessProbe.TerminationGracePeriodSeconds = nil\n\t\t\t}\n\t\t\tif c.StartupProbe != nil {\n\t\t\t\tc.StartupProbe.TerminationGracePeriodSeconds = nil\n\t\t\t}\n\t\t\t// cannot be set for readiness probes\n\t\t\treturn true\n\t\t})\n\t}\n\n\t// If the feature is disabled and not in use, drop the hostUsers field.\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.UserNamespacesStatelessPodsSupport) \u0026\u0026 !hostUsersInUse(oldPodSpec) {\n\t\t// Drop the field in podSpec only if SecurityContext is not nil.\n\t\t// If it is nil, there is no need to set hostUsers=nil (it will be nil too).\n\t\tif podSpec.SecurityContext != nil {\n\t\t\tpodSpec.SecurityContext.HostUsers = nil\n\t\t}\n\t}\n\n\t// If the feature is disabled and not in use, drop the schedulingGates field.\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.PodSchedulingReadiness) \u0026\u0026 !schedulingGatesInUse(oldPodSpec) {\n\t\tpodSpec.SchedulingGates = nil\n\t}\n\n\tdropDisabledProcMountField(podSpec, oldPodSpec)\n\n\tdropDisabledTopologySpreadConstraintsFields(podSpec, oldPodSpec)\n\tdropDisabledNodeInclusionPolicyFields(podSpec, oldPodSpec)\n\tdropDisabledMatchLabelKeysField(podSpec, oldPodSpec)\n\tdropDisabledDynamicResourceAllocationFields(podSpec, oldPodSpec)\n\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) \u0026\u0026 !inPlacePodVerticalScalingInUse(oldPodSpec) {\n\t\t// Drop ResizePolicy fields. Don't drop updates to Resources field as template.spec.resources\n\t\t// field is mutable for certain controllers. Let ValidatePodUpdate handle it.\n\t\tfor i := range podSpec.Containers {\n\t\t\tpodSpec.Containers[i].ResizePolicy = nil\n\t\t}\n\t\tfor i := range podSpec.InitContainers {\n\t\t\tpodSpec.InitContainers[i].ResizePolicy = nil\n\t\t}\n\t\tfor i := range podSpec.EphemeralContainers {\n\t\t\tpodSpec.EphemeralContainers[i].ResizePolicy = nil\n\t\t}\n\t}\n}","line":{"from":480,"to":546}} {"id":100001689,"name":"dropDisabledPodStatusFields","signature":"func dropDisabledPodStatusFields(podStatus, oldPodStatus *api.PodStatus, podSpec, oldPodSpec *api.PodSpec)","file":"pkg/api/pod/util.go","code":"// dropDisabledPodStatusFields removes disabled fields from the pod status\nfunc dropDisabledPodStatusFields(podStatus, oldPodStatus *api.PodStatus, podSpec, oldPodSpec *api.PodSpec) {\n\t// the new status is always be non-nil\n\tif podStatus == nil {\n\t\tpodStatus = \u0026api.PodStatus{}\n\t}\n\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) \u0026\u0026 !inPlacePodVerticalScalingInUse(oldPodSpec) {\n\t\t// Drop Resize, AllocatedResources, and Resources fields\n\t\tdropResourcesFields := func(csl []api.ContainerStatus) {\n\t\t\tfor i := range csl {\n\t\t\t\tcsl[i].AllocatedResources = nil\n\t\t\t\tcsl[i].Resources = nil\n\t\t\t}\n\t\t}\n\t\tdropResourcesFields(podStatus.ContainerStatuses)\n\t\tdropResourcesFields(podStatus.InitContainerStatuses)\n\t\tdropResourcesFields(podStatus.EphemeralContainerStatuses)\n\t\tpodStatus.Resize = \"\"\n\t}\n}","line":{"from":548,"to":568}} {"id":100001690,"name":"dropDisabledDynamicResourceAllocationFields","signature":"func dropDisabledDynamicResourceAllocationFields(podSpec, oldPodSpec *api.PodSpec)","file":"pkg/api/pod/util.go","code":"// dropDisabledDynamicResourceAllocationFields removes pod claim references from\n// container specs and pod-level resource claims unless they are already used\n// by the old pod spec.\nfunc dropDisabledDynamicResourceAllocationFields(podSpec, oldPodSpec *api.PodSpec) {\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.DynamicResourceAllocation) \u0026\u0026 !dynamicResourceAllocationInUse(oldPodSpec) {\n\t\tdropResourceClaimRequests(podSpec.Containers)\n\t\tdropResourceClaimRequests(podSpec.InitContainers)\n\t\tdropEphemeralResourceClaimRequests(podSpec.EphemeralContainers)\n\t\tpodSpec.ResourceClaims = nil\n\t}\n\n\t// Setting VolumeClaimTemplate.Resources.Claims should have been\n\t// treated as an error by validation when extending\n\t// ResourceRequirements in 1.26. Now we can only accept it and drop the\n\t// field.\n\tfor i := range podSpec.Volumes {\n\t\tif podSpec.Volumes[i].Ephemeral != nil \u0026\u0026 podSpec.Volumes[i].Ephemeral.VolumeClaimTemplate != nil {\n\t\t\tpodSpec.Volumes[i].Ephemeral.VolumeClaimTemplate.Spec.Resources.Claims = nil\n\t\t}\n\t}\n}","line":{"from":570,"to":590}} {"id":100001691,"name":"dynamicResourceAllocationInUse","signature":"func dynamicResourceAllocationInUse(podSpec *api.PodSpec) bool","file":"pkg/api/pod/util.go","code":"func dynamicResourceAllocationInUse(podSpec *api.PodSpec) bool {\n\tif podSpec == nil {\n\t\treturn false\n\t}\n\n\t// We only need to check this field because the containers cannot have\n\t// resource requirements entries for claims without a corresponding\n\t// entry at the pod spec level.\n\treturn len(podSpec.ResourceClaims) \u003e 0\n}","line":{"from":592,"to":601}} {"id":100001692,"name":"dropResourceClaimRequests","signature":"func dropResourceClaimRequests(containers []api.Container)","file":"pkg/api/pod/util.go","code":"func dropResourceClaimRequests(containers []api.Container) {\n\tfor i := range containers {\n\t\tcontainers[i].Resources.Claims = nil\n\t}\n}","line":{"from":603,"to":607}} {"id":100001693,"name":"dropEphemeralResourceClaimRequests","signature":"func dropEphemeralResourceClaimRequests(containers []api.EphemeralContainer)","file":"pkg/api/pod/util.go","code":"func dropEphemeralResourceClaimRequests(containers []api.EphemeralContainer) {\n\tfor i := range containers {\n\t\tcontainers[i].Resources.Claims = nil\n\t}\n}","line":{"from":609,"to":613}} {"id":100001694,"name":"dropDisabledTopologySpreadConstraintsFields","signature":"func dropDisabledTopologySpreadConstraintsFields(podSpec, oldPodSpec *api.PodSpec)","file":"pkg/api/pod/util.go","code":"// dropDisabledTopologySpreadConstraintsFields removes disabled fields from PodSpec related\n// to TopologySpreadConstraints only if it is not already used by the old spec.\nfunc dropDisabledTopologySpreadConstraintsFields(podSpec, oldPodSpec *api.PodSpec) {\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.MinDomainsInPodTopologySpread) \u0026\u0026\n\t\t!minDomainsInUse(oldPodSpec) \u0026\u0026\n\t\tpodSpec != nil {\n\t\tfor i := range podSpec.TopologySpreadConstraints {\n\t\t\tpodSpec.TopologySpreadConstraints[i].MinDomains = nil\n\t\t}\n\t}\n}","line":{"from":615,"to":625}} {"id":100001695,"name":"minDomainsInUse","signature":"func minDomainsInUse(podSpec *api.PodSpec) bool","file":"pkg/api/pod/util.go","code":"// minDomainsInUse returns true if the pod spec is non-nil\n// and has non-nil MinDomains field in TopologySpreadConstraints.\nfunc minDomainsInUse(podSpec *api.PodSpec) bool {\n\tif podSpec == nil {\n\t\treturn false\n\t}\n\n\tfor _, c := range podSpec.TopologySpreadConstraints {\n\t\tif c.MinDomains != nil {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":627,"to":640}} {"id":100001696,"name":"dropDisabledProcMountField","signature":"func dropDisabledProcMountField(podSpec, oldPodSpec *api.PodSpec)","file":"pkg/api/pod/util.go","code":"// dropDisabledProcMountField removes disabled fields from PodSpec related\n// to ProcMount only if it is not already used by the old spec\nfunc dropDisabledProcMountField(podSpec, oldPodSpec *api.PodSpec) {\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.ProcMountType) \u0026\u0026 !procMountInUse(oldPodSpec) {\n\t\tdefaultProcMount := api.DefaultProcMount\n\t\tVisitContainers(podSpec, AllContainers, func(c *api.Container, containerType ContainerType) bool {\n\t\t\tif c.SecurityContext != nil \u0026\u0026 c.SecurityContext.ProcMount != nil {\n\t\t\t\t// The ProcMount field was improperly forced to non-nil in 1.12.\n\t\t\t\t// If the feature is disabled, and the existing object is not using any non-default values, and the ProcMount field is present in the incoming object, force to the default value.\n\t\t\t\t// Note: we cannot force the field to nil when the feature is disabled because it causes a diff against previously persisted data.\n\t\t\t\tc.SecurityContext.ProcMount = \u0026defaultProcMount\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t}\n}","line":{"from":642,"to":657}} {"id":100001697,"name":"dropDisabledNodeInclusionPolicyFields","signature":"func dropDisabledNodeInclusionPolicyFields(podSpec, oldPodSpec *api.PodSpec)","file":"pkg/api/pod/util.go","code":"// dropDisabledNodeInclusionPolicyFields removes disabled fields from PodSpec related\n// to NodeInclusionPolicy only if it is not used by the old spec.\nfunc dropDisabledNodeInclusionPolicyFields(podSpec, oldPodSpec *api.PodSpec) {\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.NodeInclusionPolicyInPodTopologySpread) \u0026\u0026 podSpec != nil {\n\t\tif !nodeTaintsPolicyInUse(oldPodSpec) {\n\t\t\tfor i := range podSpec.TopologySpreadConstraints {\n\t\t\t\tpodSpec.TopologySpreadConstraints[i].NodeTaintsPolicy = nil\n\t\t\t}\n\t\t}\n\t\tif !nodeAffinityPolicyInUse(oldPodSpec) {\n\t\t\tfor i := range podSpec.TopologySpreadConstraints {\n\t\t\t\tpodSpec.TopologySpreadConstraints[i].NodeAffinityPolicy = nil\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":659,"to":674}} {"id":100001698,"name":"dropDisabledMatchLabelKeysField","signature":"func dropDisabledMatchLabelKeysField(podSpec, oldPodSpec *api.PodSpec)","file":"pkg/api/pod/util.go","code":"// dropDisabledMatchLabelKeysField removes disabled fields from PodSpec related\n// to MatchLabelKeys only if it is not already used by the old spec.\nfunc dropDisabledMatchLabelKeysField(podSpec, oldPodSpec *api.PodSpec) {\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.MatchLabelKeysInPodTopologySpread) \u0026\u0026 !matchLabelKeysInUse(oldPodSpec) {\n\t\tfor i := range podSpec.TopologySpreadConstraints {\n\t\t\tpodSpec.TopologySpreadConstraints[i].MatchLabelKeys = nil\n\t\t}\n\t}\n}","line":{"from":676,"to":684}} {"id":100001699,"name":"matchLabelKeysInUse","signature":"func matchLabelKeysInUse(podSpec *api.PodSpec) bool","file":"pkg/api/pod/util.go","code":"// matchLabelKeysInUse returns true if the pod spec is non-nil\n// and has MatchLabelKeys field set in TopologySpreadConstraints.\nfunc matchLabelKeysInUse(podSpec *api.PodSpec) bool {\n\tif podSpec == nil {\n\t\treturn false\n\t}\n\n\tfor _, c := range podSpec.TopologySpreadConstraints {\n\t\tif len(c.MatchLabelKeys) \u003e 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":686,"to":699}} {"id":100001700,"name":"nodeAffinityPolicyInUse","signature":"func nodeAffinityPolicyInUse(podSpec *api.PodSpec) bool","file":"pkg/api/pod/util.go","code":"// nodeAffinityPolicyInUse returns true if the pod spec is non-nil and has NodeAffinityPolicy field set\n// in TopologySpreadConstraints\nfunc nodeAffinityPolicyInUse(podSpec *api.PodSpec) bool {\n\tif podSpec == nil {\n\t\treturn false\n\t}\n\tfor _, c := range podSpec.TopologySpreadConstraints {\n\t\tif c.NodeAffinityPolicy != nil {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":701,"to":713}} {"id":100001701,"name":"nodeTaintsPolicyInUse","signature":"func nodeTaintsPolicyInUse(podSpec *api.PodSpec) bool","file":"pkg/api/pod/util.go","code":"// nodeTaintsPolicyInUse returns true if the pod spec is non-nil and has NodeTaintsPolicy field set\n// in TopologySpreadConstraints\nfunc nodeTaintsPolicyInUse(podSpec *api.PodSpec) bool {\n\tif podSpec == nil {\n\t\treturn false\n\t}\n\tfor _, c := range podSpec.TopologySpreadConstraints {\n\t\tif c.NodeTaintsPolicy != nil {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":715,"to":727}} {"id":100001702,"name":"hostUsersInUse","signature":"func hostUsersInUse(podSpec *api.PodSpec) bool","file":"pkg/api/pod/util.go","code":"// hostUsersInUse returns true if the pod spec has spec.hostUsers field set.\nfunc hostUsersInUse(podSpec *api.PodSpec) bool {\n\tif podSpec != nil \u0026\u0026 podSpec.SecurityContext != nil \u0026\u0026 podSpec.SecurityContext.HostUsers != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":729,"to":736}} {"id":100001703,"name":"inPlacePodVerticalScalingInUse","signature":"func inPlacePodVerticalScalingInUse(podSpec *api.PodSpec) bool","file":"pkg/api/pod/util.go","code":"// inPlacePodVerticalScalingInUse returns true if pod spec is non-nil and ResizePolicy is set\nfunc inPlacePodVerticalScalingInUse(podSpec *api.PodSpec) bool {\n\tif podSpec == nil {\n\t\treturn false\n\t}\n\tvar inUse bool\n\tVisitContainers(podSpec, Containers, func(c *api.Container, containerType ContainerType) bool {\n\t\tif len(c.ResizePolicy) \u003e 0 {\n\t\t\tinUse = true\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t})\n\treturn inUse\n}","line":{"from":738,"to":752}} {"id":100001704,"name":"procMountInUse","signature":"func procMountInUse(podSpec *api.PodSpec) bool","file":"pkg/api/pod/util.go","code":"// procMountInUse returns true if the pod spec is non-nil and has a SecurityContext's ProcMount field set to a non-default value\nfunc procMountInUse(podSpec *api.PodSpec) bool {\n\tif podSpec == nil {\n\t\treturn false\n\t}\n\n\tvar inUse bool\n\tVisitContainers(podSpec, AllContainers, func(c *api.Container, containerType ContainerType) bool {\n\t\tif c.SecurityContext == nil || c.SecurityContext.ProcMount == nil {\n\t\t\treturn true\n\t\t}\n\t\tif *c.SecurityContext.ProcMount != api.DefaultProcMount {\n\t\t\tinUse = true\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t})\n\n\treturn inUse\n}","line":{"from":754,"to":773}} {"id":100001705,"name":"appArmorInUse","signature":"func appArmorInUse(podAnnotations map[string]string) bool","file":"pkg/api/pod/util.go","code":"// appArmorInUse returns true if the pod has apparmor related information\nfunc appArmorInUse(podAnnotations map[string]string) bool {\n\tfor k := range podAnnotations {\n\t\tif strings.HasPrefix(k, v1.AppArmorBetaContainerAnnotationKeyPrefix) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":775,"to":783}} {"id":100001706,"name":"probeGracePeriodInUse","signature":"func probeGracePeriodInUse(podSpec *api.PodSpec) bool","file":"pkg/api/pod/util.go","code":"// probeGracePeriodInUse returns true if the pod spec is non-nil and has a probe that makes use\n// of the probe-level terminationGracePeriodSeconds feature\nfunc probeGracePeriodInUse(podSpec *api.PodSpec) bool {\n\tif podSpec == nil {\n\t\treturn false\n\t}\n\n\tvar inUse bool\n\tVisitContainers(podSpec, AllContainers, func(c *api.Container, containerType ContainerType) bool {\n\t\t// cannot be set for readiness probes\n\t\tif (c.LivenessProbe != nil \u0026\u0026 c.LivenessProbe.TerminationGracePeriodSeconds != nil) ||\n\t\t\t(c.StartupProbe != nil \u0026\u0026 c.StartupProbe.TerminationGracePeriodSeconds != nil) {\n\t\t\tinUse = true\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t})\n\n\treturn inUse\n}","line":{"from":785,"to":804}} {"id":100001707,"name":"schedulingGatesInUse","signature":"func schedulingGatesInUse(podSpec *api.PodSpec) bool","file":"pkg/api/pod/util.go","code":"// schedulingGatesInUse returns true if the pod spec is non-nil and it has SchedulingGates field set.\nfunc schedulingGatesInUse(podSpec *api.PodSpec) bool {\n\tif podSpec == nil {\n\t\treturn false\n\t}\n\treturn len(podSpec.SchedulingGates) != 0\n}","line":{"from":806,"to":812}} {"id":100001708,"name":"hasInvalidLabelValueInAffinitySelector","signature":"func hasInvalidLabelValueInAffinitySelector(spec *api.PodSpec) bool","file":"pkg/api/pod/util.go","code":"func hasInvalidLabelValueInAffinitySelector(spec *api.PodSpec) bool {\n\tif spec.Affinity != nil {\n\t\tif spec.Affinity.PodAffinity != nil {\n\t\t\tfor _, term := range spec.Affinity.PodAffinity.RequiredDuringSchedulingIgnoredDuringExecution {\n\t\t\t\tallErrs := apivalidation.ValidatePodAffinityTermSelector(term, false, nil)\n\t\t\t\tif len(allErrs) != 0 {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, term := range spec.Affinity.PodAffinity.PreferredDuringSchedulingIgnoredDuringExecution {\n\t\t\t\tallErrs := apivalidation.ValidatePodAffinityTermSelector(term.PodAffinityTerm, false, nil)\n\t\t\t\tif len(allErrs) != 0 {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif spec.Affinity.PodAntiAffinity != nil {\n\t\t\tfor _, term := range spec.Affinity.PodAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution {\n\t\t\t\tallErrs := apivalidation.ValidatePodAffinityTermSelector(term, false, nil)\n\t\t\t\tif len(allErrs) != 0 {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, term := range spec.Affinity.PodAntiAffinity.PreferredDuringSchedulingIgnoredDuringExecution {\n\t\t\t\tallErrs := apivalidation.ValidatePodAffinityTermSelector(term.PodAffinityTerm, false, nil)\n\t\t\t\tif len(allErrs) != 0 {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":814,"to":846}} {"id":100001709,"name":"MarkPodProposedForResize","signature":"func MarkPodProposedForResize(oldPod, newPod *api.Pod)","file":"pkg/api/pod/util.go","code":"func MarkPodProposedForResize(oldPod, newPod *api.Pod) {\n\tfor i, c := range newPod.Spec.Containers {\n\t\tif c.Resources.Requests == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif diff.ObjectDiff(oldPod.Spec.Containers[i].Resources, c.Resources) == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tfindContainerStatus := func(css []api.ContainerStatus, cName string) (api.ContainerStatus, bool) {\n\t\t\tfor i := range css {\n\t\t\t\tif css[i].Name == cName {\n\t\t\t\t\treturn css[i], true\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn api.ContainerStatus{}, false\n\t\t}\n\t\tif cs, ok := findContainerStatus(newPod.Status.ContainerStatuses, c.Name); ok {\n\t\t\tif diff.ObjectDiff(c.Resources.Requests, cs.AllocatedResources) != \"\" {\n\t\t\t\tnewPod.Status.Resize = api.PodResizeStatusProposed\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":848,"to":871}} {"id":100001710,"name":"GetWarningsForPod","signature":"func GetWarningsForPod(ctx context.Context, pod, oldPod *api.Pod) []string","file":"pkg/api/pod/warnings.go","code":"func GetWarningsForPod(ctx context.Context, pod, oldPod *api.Pod) []string {\n\tif pod == nil {\n\t\treturn nil\n\t}\n\n\tvar (\n\t\toldSpec *api.PodSpec\n\t\toldMeta *metav1.ObjectMeta\n\t)\n\tif oldPod != nil {\n\t\toldSpec = \u0026oldPod.Spec\n\t\toldMeta = \u0026oldPod.ObjectMeta\n\t}\n\treturn warningsForPodSpecAndMeta(nil, \u0026pod.Spec, \u0026pod.ObjectMeta, oldSpec, oldMeta)\n}","line":{"from":33,"to":47}} {"id":100001711,"name":"GetWarningsForPodTemplate","signature":"func GetWarningsForPodTemplate(ctx context.Context, fieldPath *field.Path, podTemplate, oldPodTemplate *api.PodTemplateSpec) []string","file":"pkg/api/pod/warnings.go","code":"func GetWarningsForPodTemplate(ctx context.Context, fieldPath *field.Path, podTemplate, oldPodTemplate *api.PodTemplateSpec) []string {\n\tif podTemplate == nil {\n\t\treturn nil\n\t}\n\n\tvar (\n\t\toldSpec *api.PodSpec\n\t\toldMeta *metav1.ObjectMeta\n\t)\n\tif oldPodTemplate != nil {\n\t\toldSpec = \u0026oldPodTemplate.Spec\n\t\toldMeta = \u0026oldPodTemplate.ObjectMeta\n\t}\n\treturn warningsForPodSpecAndMeta(fieldPath, \u0026podTemplate.Spec, \u0026podTemplate.ObjectMeta, oldSpec, oldMeta)\n}","line":{"from":49,"to":63}} {"id":100001712,"name":"warningsForPodSpecAndMeta","signature":"func warningsForPodSpecAndMeta(fieldPath *field.Path, podSpec *api.PodSpec, meta *metav1.ObjectMeta, oldPodSpec *api.PodSpec, oldMeta *metav1.ObjectMeta) []string","file":"pkg/api/pod/warnings.go","code":"func warningsForPodSpecAndMeta(fieldPath *field.Path, podSpec *api.PodSpec, meta *metav1.ObjectMeta, oldPodSpec *api.PodSpec, oldMeta *metav1.ObjectMeta) []string {\n\tvar warnings []string\n\n\t// use of deprecated node labels in selectors/affinity/topology\n\tfor k := range podSpec.NodeSelector {\n\t\tif msg, deprecated := nodeapi.GetNodeLabelDeprecatedMessage(k); deprecated {\n\t\t\twarnings = append(warnings, fmt.Sprintf(\"%s: %s\", fieldPath.Child(\"spec\", \"nodeSelector\").Key(k), msg))\n\t\t}\n\t}\n\tif podSpec.Affinity != nil \u0026\u0026 podSpec.Affinity.NodeAffinity != nil {\n\t\tn := podSpec.Affinity.NodeAffinity\n\t\tif n.RequiredDuringSchedulingIgnoredDuringExecution != nil {\n\t\t\ttermFldPath := fieldPath.Child(\"spec\", \"affinity\", \"nodeAffinity\", \"requiredDuringSchedulingIgnoredDuringExecution\", \"nodeSelectorTerms\")\n\t\t\tfor i, term := range n.RequiredDuringSchedulingIgnoredDuringExecution.NodeSelectorTerms {\n\t\t\t\twarnings = append(warnings, nodeapi.GetWarningsForNodeSelectorTerm(term, termFldPath.Index(i))...)\n\t\t\t}\n\t\t}\n\t\tpreferredFldPath := fieldPath.Child(\"spec\", \"affinity\", \"nodeAffinity\", \"preferredDuringSchedulingIgnoredDuringExecution\")\n\t\tfor i, term := range n.PreferredDuringSchedulingIgnoredDuringExecution {\n\t\t\twarnings = append(warnings, nodeapi.GetWarningsForNodeSelectorTerm(term.Preference, preferredFldPath.Index(i).Child(\"preference\"))...)\n\t\t}\n\t}\n\tfor i, t := range podSpec.TopologySpreadConstraints {\n\t\tif msg, deprecated := nodeapi.GetNodeLabelDeprecatedMessage(t.TopologyKey); deprecated {\n\t\t\twarnings = append(warnings, fmt.Sprintf(\n\t\t\t\t\"%s: %s is %s\",\n\t\t\t\tfieldPath.Child(\"spec\", \"topologySpreadConstraints\").Index(i).Child(\"topologyKey\"),\n\t\t\t\tt.TopologyKey,\n\t\t\t\tmsg,\n\t\t\t))\n\t\t}\n\t}\n\n\t// use of deprecated annotations\n\tfor _, deprecated := range deprecatedAnnotations {\n\t\tif _, exists := meta.Annotations[deprecated.key]; exists {\n\t\t\twarnings = append(warnings, fmt.Sprintf(\"%s: %s\", fieldPath.Child(\"metadata\", \"annotations\").Key(deprecated.key), deprecated.message))\n\t\t}\n\t\tif len(deprecated.prefix) \u003e 0 {\n\t\t\tfor k := range meta.Annotations {\n\t\t\t\tif strings.HasPrefix(k, deprecated.prefix) {\n\t\t\t\t\twarnings = append(warnings, fmt.Sprintf(\"%s: %s\", fieldPath.Child(\"metadata\", \"annotations\").Key(k), deprecated.message))\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// deprecated and removed volume plugins\n\tfor i, v := range podSpec.Volumes {\n\t\tif v.PhotonPersistentDisk != nil {\n\t\t\twarnings = append(warnings, fmt.Sprintf(\"%s: deprecated in v1.11, non-functional in v1.16+\", fieldPath.Child(\"spec\", \"volumes\").Index(i).Child(\"photonPersistentDisk\")))\n\t\t}\n\t\tif v.GitRepo != nil {\n\t\t\twarnings = append(warnings, fmt.Sprintf(\"%s: deprecated in v1.11\", fieldPath.Child(\"spec\", \"volumes\").Index(i).Child(\"gitRepo\")))\n\t\t}\n\t\tif v.ScaleIO != nil {\n\t\t\twarnings = append(warnings, fmt.Sprintf(\"%s: deprecated in v1.16, non-functional in v1.22+\", fieldPath.Child(\"spec\", \"volumes\").Index(i).Child(\"scaleIO\")))\n\t\t}\n\t\tif v.Flocker != nil {\n\t\t\twarnings = append(warnings, fmt.Sprintf(\"%s: deprecated in v1.22, non-functional in v1.25+\", fieldPath.Child(\"spec\", \"volumes\").Index(i).Child(\"flocker\")))\n\t\t}\n\t\tif v.StorageOS != nil {\n\t\t\twarnings = append(warnings, fmt.Sprintf(\"%s: deprecated in v1.22, non-functional in v1.25+\", fieldPath.Child(\"spec\", \"volumes\").Index(i).Child(\"storageOS\")))\n\t\t}\n\t\tif v.Quobyte != nil {\n\t\t\twarnings = append(warnings, fmt.Sprintf(\"%s: deprecated in v1.22, non-functional in v1.25+\", fieldPath.Child(\"spec\", \"volumes\").Index(i).Child(\"quobyte\")))\n\t\t}\n\t\tif v.Glusterfs != nil {\n\t\t\twarnings = append(warnings, fmt.Sprintf(\"%s: deprecated in v1.25, non-functional in v1.26+\", fieldPath.Child(\"spec\", \"volumes\").Index(i).Child(\"glusterfs\")))\n\t\t}\n\t\tif v.Ephemeral != nil \u0026\u0026 v.Ephemeral.VolumeClaimTemplate != nil {\n\t\t\twarnings = append(warnings, pvcutil.GetWarningsForPersistentVolumeClaimSpec(fieldPath.Child(\"spec\", \"volumes\").Index(i).Child(\"ephemeral\").Child(\"volumeClaimTemplate\").Child(\"spec\"), v.Ephemeral.VolumeClaimTemplate.Spec)...)\n\t\t}\n\t}\n\n\t// duplicate hostAliases (#91670, #58477)\n\tif len(podSpec.HostAliases) \u003e 1 {\n\t\titems := sets.NewString()\n\t\tfor i, item := range podSpec.HostAliases {\n\t\t\tif items.Has(item.IP) {\n\t\t\t\twarnings = append(warnings, fmt.Sprintf(\"%s: duplicate ip %q\", fieldPath.Child(\"spec\", \"hostAliases\").Index(i).Child(\"ip\"), item.IP))\n\t\t\t} else {\n\t\t\t\titems.Insert(item.IP)\n\t\t\t}\n\t\t}\n\t}\n\n\t// duplicate imagePullSecrets (#91629, #58477)\n\tif len(podSpec.ImagePullSecrets) \u003e 1 {\n\t\titems := sets.NewString()\n\t\tfor i, item := range podSpec.ImagePullSecrets {\n\t\t\tif items.Has(item.Name) {\n\t\t\t\twarnings = append(warnings, fmt.Sprintf(\"%s: duplicate name %q\", fieldPath.Child(\"spec\", \"imagePullSecrets\").Index(i).Child(\"name\"), item.Name))\n\t\t\t} else {\n\t\t\t\titems.Insert(item.Name)\n\t\t\t}\n\t\t}\n\t}\n\t// imagePullSecrets with empty name (#99454#issuecomment-787838112)\n\tfor i, item := range podSpec.ImagePullSecrets {\n\t\tif len(item.Name) == 0 {\n\t\t\twarnings = append(warnings, fmt.Sprintf(\"%s: invalid empty name %q\", fieldPath.Child(\"spec\", \"imagePullSecrets\").Index(i).Child(\"name\"), item.Name))\n\t\t}\n\t}\n\n\t// duplicate volume names (#78266, #58477)\n\tif len(podSpec.Volumes) \u003e 1 {\n\t\titems := sets.NewString()\n\t\tfor i, item := range podSpec.Volumes {\n\t\t\tif items.Has(item.Name) {\n\t\t\t\twarnings = append(warnings, fmt.Sprintf(\"%s: duplicate name %q\", fieldPath.Child(\"spec\", \"volumes\").Index(i).Child(\"name\"), item.Name))\n\t\t\t} else {\n\t\t\t\titems.Insert(item.Name)\n\t\t\t}\n\t\t}\n\t}\n\n\t// fractional memory/ephemeral-storage requests/limits (#79950, #49442, #18538)\n\tif value, ok := podSpec.Overhead[api.ResourceMemory]; ok \u0026\u0026 value.MilliValue()%int64(1000) != int64(0) {\n\t\twarnings = append(warnings, fmt.Sprintf(\"%s: fractional byte value %q is invalid, must be an integer\", fieldPath.Child(\"spec\", \"overhead\").Key(string(api.ResourceMemory)), value.String()))\n\t}\n\tif value, ok := podSpec.Overhead[api.ResourceEphemeralStorage]; ok \u0026\u0026 value.MilliValue()%int64(1000) != int64(0) {\n\t\twarnings = append(warnings, fmt.Sprintf(\"%s: fractional byte value %q is invalid, must be an integer\", fieldPath.Child(\"spec\", \"overhead\").Key(string(api.ResourceEphemeralStorage)), value.String()))\n\t}\n\n\t// use of pod seccomp annotation without accompanying field\n\tif podSpec.SecurityContext == nil || podSpec.SecurityContext.SeccompProfile == nil {\n\t\tif _, exists := meta.Annotations[api.SeccompPodAnnotationKey]; exists {\n\t\t\twarnings = append(warnings, fmt.Sprintf(`%s: non-functional in v1.27+; use the \"seccompProfile\" field instead`, fieldPath.Child(\"metadata\", \"annotations\").Key(api.SeccompPodAnnotationKey)))\n\t\t}\n\t}\n\n\tpods.VisitContainersWithPath(podSpec, fieldPath.Child(\"spec\"), func(c *api.Container, p *field.Path) bool {\n\t\t// use of container seccomp annotation without accompanying field\n\t\tif c.SecurityContext == nil || c.SecurityContext.SeccompProfile == nil {\n\t\t\tif _, exists := meta.Annotations[api.SeccompContainerAnnotationKeyPrefix+c.Name]; exists {\n\t\t\t\twarnings = append(warnings, fmt.Sprintf(`%s: non-functional in v1.27+; use the \"seccompProfile\" field instead`, fieldPath.Child(\"metadata\", \"annotations\").Key(api.SeccompContainerAnnotationKeyPrefix+c.Name)))\n\t\t\t}\n\t\t}\n\n\t\t// fractional memory/ephemeral-storage requests/limits (#79950, #49442, #18538)\n\t\tif value, ok := c.Resources.Limits[api.ResourceMemory]; ok \u0026\u0026 value.MilliValue()%int64(1000) != int64(0) {\n\t\t\twarnings = append(warnings, fmt.Sprintf(\"%s: fractional byte value %q is invalid, must be an integer\", p.Child(\"resources\", \"limits\").Key(string(api.ResourceMemory)), value.String()))\n\t\t}\n\t\tif value, ok := c.Resources.Requests[api.ResourceMemory]; ok \u0026\u0026 value.MilliValue()%int64(1000) != int64(0) {\n\t\t\twarnings = append(warnings, fmt.Sprintf(\"%s: fractional byte value %q is invalid, must be an integer\", p.Child(\"resources\", \"requests\").Key(string(api.ResourceMemory)), value.String()))\n\t\t}\n\t\tif value, ok := c.Resources.Limits[api.ResourceEphemeralStorage]; ok \u0026\u0026 value.MilliValue()%int64(1000) != int64(0) {\n\t\t\twarnings = append(warnings, fmt.Sprintf(\"%s: fractional byte value %q is invalid, must be an integer\", p.Child(\"resources\", \"limits\").Key(string(api.ResourceEphemeralStorage)), value.String()))\n\t\t}\n\t\tif value, ok := c.Resources.Requests[api.ResourceEphemeralStorage]; ok \u0026\u0026 value.MilliValue()%int64(1000) != int64(0) {\n\t\t\twarnings = append(warnings, fmt.Sprintf(\"%s: fractional byte value %q is invalid, must be an integer\", p.Child(\"resources\", \"requests\").Key(string(api.ResourceEphemeralStorage)), value.String()))\n\t\t}\n\n\t\t// duplicate containers[*].env (#86163, #93266, #58477)\n\t\tif len(c.Env) \u003e 1 {\n\t\t\titems := sets.NewString()\n\t\t\tfor i, item := range c.Env {\n\t\t\t\tif items.Has(item.Name) {\n\t\t\t\t\twarnings = append(warnings, fmt.Sprintf(\"%s: duplicate name %q\", p.Child(\"env\").Index(i).Child(\"name\"), item.Name))\n\t\t\t\t} else {\n\t\t\t\t\titems.Insert(item.Name)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n\n\t// warn if the terminationGracePeriodSeconds is negative.\n\tif podSpec.TerminationGracePeriodSeconds != nil \u0026\u0026 *podSpec.TerminationGracePeriodSeconds \u003c 0 {\n\t\twarnings = append(warnings, fmt.Sprintf(\"%s: must be \u003e= 0; negative values are invalid and will be treated as 1\", fieldPath.Child(\"spec\", \"terminationGracePeriodSeconds\")))\n\t}\n\treturn warnings\n}","line":{"from":84,"to":258}} {"id":100001713,"name":"IsAllowAll","signature":"func IsAllowAll(ipnets utilnet.IPNetSet) bool","file":"pkg/api/service/util.go","code":"// IsAllowAll checks whether the utilnet.IPNet allows traffic from 0.0.0.0/0\nfunc IsAllowAll(ipnets utilnet.IPNetSet) bool {\n\tfor _, s := range ipnets.StringSlice() {\n\t\tif s == \"0.0.0.0/0\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":31,"to":39}} {"id":100001714,"name":"GetLoadBalancerSourceRanges","signature":"func GetLoadBalancerSourceRanges(service *api.Service) (utilnet.IPNetSet, error)","file":"pkg/api/service/util.go","code":"// GetLoadBalancerSourceRanges first try to parse and verify LoadBalancerSourceRanges field from a service.\n// If the field is not specified, turn to parse and verify the AnnotationLoadBalancerSourceRangesKey annotation from a service,\n// extracting the source ranges to allow, and if not present returns a default (allow-all) value.\nfunc GetLoadBalancerSourceRanges(service *api.Service) (utilnet.IPNetSet, error) {\n\tvar ipnets utilnet.IPNetSet\n\tvar err error\n\t// if SourceRange field is specified, ignore sourceRange annotation\n\tif len(service.Spec.LoadBalancerSourceRanges) \u003e 0 {\n\t\tspecs := service.Spec.LoadBalancerSourceRanges\n\t\tipnets, err = utilnet.ParseIPNets(specs...)\n\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"service.Spec.LoadBalancerSourceRanges: %v is not valid. Expecting a list of IP ranges. For example, 10.0.0.0/24. Error msg: %v\", specs, err)\n\t\t}\n\t} else {\n\t\tval := service.Annotations[api.AnnotationLoadBalancerSourceRangesKey]\n\t\tval = strings.TrimSpace(val)\n\t\tif val == \"\" {\n\t\t\tval = defaultLoadBalancerSourceRanges\n\t\t}\n\t\tspecs := strings.Split(val, \",\")\n\t\tipnets, err = utilnet.ParseIPNets(specs...)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%s: %s is not valid. Expecting a comma-separated list of source IP ranges. For example, 10.0.0.0/24,192.168.2.0/24\", api.AnnotationLoadBalancerSourceRangesKey, val)\n\t\t}\n\t}\n\treturn ipnets, nil\n}","line":{"from":41,"to":68}} {"id":100001715,"name":"RequestsOnlyLocalTraffic","signature":"func RequestsOnlyLocalTraffic(service *api.Service) bool","file":"pkg/api/service/util.go","code":"// RequestsOnlyLocalTraffic checks if service requests OnlyLocal traffic.\nfunc RequestsOnlyLocalTraffic(service *api.Service) bool {\n\tif service.Spec.Type != api.ServiceTypeLoadBalancer \u0026\u0026\n\t\tservice.Spec.Type != api.ServiceTypeNodePort {\n\t\treturn false\n\t}\n\n\treturn service.Spec.ExternalTrafficPolicy == api.ServiceExternalTrafficPolicyLocal\n}","line":{"from":70,"to":78}} {"id":100001716,"name":"NeedsHealthCheck","signature":"func NeedsHealthCheck(service *api.Service) bool","file":"pkg/api/service/util.go","code":"// NeedsHealthCheck checks if service needs health check.\nfunc NeedsHealthCheck(service *api.Service) bool {\n\tif service.Spec.Type != api.ServiceTypeLoadBalancer {\n\t\treturn false\n\t}\n\treturn RequestsOnlyLocalTraffic(service)\n}","line":{"from":80,"to":86}} {"id":100001717,"name":"GetWarningsForService","signature":"func GetWarningsForService(service, oldService *api.Service) []string","file":"pkg/api/service/warnings.go","code":"func GetWarningsForService(service, oldService *api.Service) []string {\n\tif service == nil {\n\t\treturn nil\n\t}\n\tvar warnings []string\n\n\tif _, ok := service.Annotations[api.DeprecatedAnnotationTopologyAwareHints]; ok {\n\t\twarnings = append(warnings, fmt.Sprintf(\"annotation %s is deprecated, please use %s instead\", api.DeprecatedAnnotationTopologyAwareHints, api.AnnotationTopologyMode))\n\t}\n\n\tif helper.IsServiceIPSet(service) {\n\t\tfor i, clusterIP := range service.Spec.ClusterIPs {\n\t\t\twarnings = append(warnings, getWarningsForIP(field.NewPath(\"spec\").Child(\"clusterIPs\").Index(i), clusterIP)...)\n\t\t}\n\t}\n\n\tfor i, externalIP := range service.Spec.ExternalIPs {\n\t\twarnings = append(warnings, getWarningsForIP(field.NewPath(\"spec\").Child(\"externalIPs\").Index(i), externalIP)...)\n\t}\n\n\tif len(service.Spec.LoadBalancerIP) \u003e 0 {\n\t\twarnings = append(warnings, getWarningsForIP(field.NewPath(\"spec\").Child(\"loadBalancerIP\"), service.Spec.LoadBalancerIP)...)\n\t}\n\n\tfor i, cidr := range service.Spec.LoadBalancerSourceRanges {\n\t\twarnings = append(warnings, getWarningsForCIDR(field.NewPath(\"spec\").Child(\"loadBalancerSourceRanges\").Index(i), cidr)...)\n\t}\n\n\treturn warnings\n}","line":{"from":28,"to":57}} {"id":100001718,"name":"getWarningsForIP","signature":"func getWarningsForIP(fieldPath *field.Path, address string) []string","file":"pkg/api/service/warnings.go","code":"func getWarningsForIP(fieldPath *field.Path, address string) []string {\n\t// IPv4 addresses with leading zeros CVE-2021-29923 are not valid in golang since 1.17\n\t// This will also warn about possible future changes on the golang std library\n\t// xref: https://issues.k8s.io/108074\n\tip, err := netip.ParseAddr(address)\n\tif err != nil {\n\t\treturn []string{fmt.Sprintf(\"%s: IP address was accepted, but will be invalid in a future Kubernetes release: %v\", fieldPath, err)}\n\t}\n\t// A Recommendation for IPv6 Address Text Representation\n\t//\n\t// \"All of the above examples represent the same IPv6 address. This\n\t// flexibility has caused many problems for operators, systems\n\t// engineers, and customers.\n\t// ...\"\n\t// https://datatracker.ietf.org/doc/rfc5952/\n\tif ip.Is6() \u0026\u0026 ip.String() != address {\n\t\treturn []string{fmt.Sprintf(\"%s: IPv6 address %q is not in RFC 5952 canonical format (%q), which may cause controller apply-loops\", fieldPath, address, ip.String())}\n\t}\n\treturn []string{}\n}","line":{"from":59,"to":78}} {"id":100001719,"name":"getWarningsForCIDR","signature":"func getWarningsForCIDR(fieldPath *field.Path, cidr string) []string","file":"pkg/api/service/warnings.go","code":"func getWarningsForCIDR(fieldPath *field.Path, cidr string) []string {\n\t// IPv4 addresses with leading zeros CVE-2021-29923 are not valid in golang since 1.17\n\t// This will also warn about possible future changes on the golang std library\n\t// xref: https://issues.k8s.io/108074\n\tprefix, err := netip.ParsePrefix(cidr)\n\tif err != nil {\n\t\treturn []string{fmt.Sprintf(\"%s: IP prefix was accepted, but will be invalid in a future Kubernetes release: %v\", fieldPath, err)}\n\t}\n\t// A Recommendation for IPv6 Address Text Representation\n\t//\n\t// \"All of the above examples represent the same IPv6 address. This\n\t// flexibility has caused many problems for operators, systems\n\t// engineers, and customers.\n\t// ...\"\n\t// https://datatracker.ietf.org/doc/rfc5952/\n\tif prefix.Addr().Is6() \u0026\u0026 prefix.String() != cidr {\n\t\treturn []string{fmt.Sprintf(\"%s: IPv6 prefix %q is not in RFC 5952 canonical format (%q), which may cause controller apply-loops\", fieldPath, cidr, prefix.String())}\n\t}\n\treturn []string{}\n}","line":{"from":80,"to":99}} {"id":100001720,"name":"GetWarningsForStorageClass","signature":"func GetWarningsForStorageClass(sc *storage.StorageClass) []string","file":"pkg/api/storage/util.go","code":"func GetWarningsForStorageClass(sc *storage.StorageClass) []string {\n\tvar warnings []string\n\n\tif sc != nil \u0026\u0026 sc.AllowedTopologies != nil {\n\t\t// use of deprecated node labels in allowedTopologies's matchLabelExpressions\n\t\tfor i, topo := range sc.AllowedTopologies {\n\t\t\tfor j, expression := range topo.MatchLabelExpressions {\n\t\t\t\tif msg, deprecated := nodeapi.GetNodeLabelDeprecatedMessage(expression.Key); deprecated {\n\t\t\t\t\twarnings = append(warnings, fmt.Sprintf(\"%s: %s\", field.NewPath(\"allowedTopologies\").Index(i).Child(\"matchLabelExpressions\").Index(j).Child(\"key\"), msg))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn warnings\n}","line":{"from":27,"to":42}} {"id":100001721,"name":"GetWarningsForCSIStorageCapacity","signature":"func GetWarningsForCSIStorageCapacity(csc *storage.CSIStorageCapacity) []string","file":"pkg/api/storage/util.go","code":"func GetWarningsForCSIStorageCapacity(csc *storage.CSIStorageCapacity) []string {\n\tif csc != nil {\n\t\treturn nodeapi.GetWarningsForNodeSelector(csc.NodeTopology, field.NewPath(\"nodeTopology\"))\n\t}\n\treturn nil\n}","line":{"from":44,"to":49}} {"id":100001722,"name":"RepackSubsets","signature":"func RepackSubsets(subsets []v1.EndpointSubset) []v1.EndpointSubset","file":"pkg/api/v1/endpoints/util.go","code":"// RepackSubsets takes a slice of EndpointSubset objects, expands it to the full\n// representation, and then repacks that into the canonical layout. This\n// ensures that code which operates on these objects can rely on the common\n// form for things like comparison. The result is a newly allocated slice.\nfunc RepackSubsets(subsets []v1.EndpointSubset) []v1.EndpointSubset {\n\t// First map each unique port definition to the sets of hosts that\n\t// offer it.\n\tallAddrs := map[addressKey]*v1.EndpointAddress{}\n\tportToAddrReadyMap := map[v1.EndpointPort]addressSet{}\n\tfor i := range subsets {\n\t\tif len(subsets[i].Ports) == 0 {\n\t\t\t// Don't discard endpoints with no ports defined, use a sentinel.\n\t\t\tmapAddressesByPort(\u0026subsets[i], v1.EndpointPort{Port: -1}, allAddrs, portToAddrReadyMap)\n\t\t} else {\n\t\t\tfor _, port := range subsets[i].Ports {\n\t\t\t\tmapAddressesByPort(\u0026subsets[i], port, allAddrs, portToAddrReadyMap)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Next, map the sets of hosts to the sets of ports they offer.\n\t// Go does not allow maps or slices as keys to maps, so we have\n\t// to synthesize an artificial key and do a sort of 2-part\n\t// associative entity.\n\ttype keyString string\n\tkeyToAddrReadyMap := map[keyString]addressSet{}\n\taddrReadyMapKeyToPorts := map[keyString][]v1.EndpointPort{}\n\tfor port, addrs := range portToAddrReadyMap {\n\t\tkey := keyString(hashAddresses(addrs))\n\t\tkeyToAddrReadyMap[key] = addrs\n\t\tif port.Port \u003e 0 { // avoid sentinels\n\t\t\taddrReadyMapKeyToPorts[key] = append(addrReadyMapKeyToPorts[key], port)\n\t\t} else {\n\t\t\tif _, found := addrReadyMapKeyToPorts[key]; !found {\n\t\t\t\t// Force it to be present in the map\n\t\t\t\taddrReadyMapKeyToPorts[key] = nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// Next, build the N-to-M association the API wants.\n\tfinal := []v1.EndpointSubset{}\n\tfor key, ports := range addrReadyMapKeyToPorts {\n\t\tvar readyAddrs, notReadyAddrs []v1.EndpointAddress\n\t\tfor addr, ready := range keyToAddrReadyMap[key] {\n\t\t\tif ready {\n\t\t\t\treadyAddrs = append(readyAddrs, *addr)\n\t\t\t} else {\n\t\t\t\tnotReadyAddrs = append(notReadyAddrs, *addr)\n\t\t\t}\n\t\t}\n\t\tfinal = append(final, v1.EndpointSubset{Addresses: readyAddrs, NotReadyAddresses: notReadyAddrs, Ports: ports})\n\t}\n\n\t// Finally, sort it.\n\treturn SortSubsets(final)\n}","line":{"from":31,"to":87}} {"id":100001723,"name":"mapAddressesByPort","signature":"func mapAddressesByPort(subset *v1.EndpointSubset, port v1.EndpointPort, allAddrs map[addressKey]*v1.EndpointAddress, portToAddrReadyMap map[v1.EndpointPort]addressSet)","file":"pkg/api/v1/endpoints/util.go","code":"// mapAddressesByPort adds all ready and not-ready addresses into a map by a single port.\nfunc mapAddressesByPort(subset *v1.EndpointSubset, port v1.EndpointPort, allAddrs map[addressKey]*v1.EndpointAddress, portToAddrReadyMap map[v1.EndpointPort]addressSet) {\n\tfor k := range subset.Addresses {\n\t\tmapAddressByPort(\u0026subset.Addresses[k], port, true, allAddrs, portToAddrReadyMap)\n\t}\n\tfor k := range subset.NotReadyAddresses {\n\t\tmapAddressByPort(\u0026subset.NotReadyAddresses[k], port, false, allAddrs, portToAddrReadyMap)\n\t}\n}","line":{"from":95,"to":103}} {"id":100001724,"name":"mapAddressByPort","signature":"func mapAddressByPort(addr *v1.EndpointAddress, port v1.EndpointPort, ready bool, allAddrs map[addressKey]*v1.EndpointAddress, portToAddrReadyMap map[v1.EndpointPort]addressSet) *v1.EndpointAddress","file":"pkg/api/v1/endpoints/util.go","code":"// mapAddressByPort adds one address into a map by port, registering the address with a unique pointer, and preserving\n// any existing ready state.\nfunc mapAddressByPort(addr *v1.EndpointAddress, port v1.EndpointPort, ready bool, allAddrs map[addressKey]*v1.EndpointAddress, portToAddrReadyMap map[v1.EndpointPort]addressSet) *v1.EndpointAddress {\n\t// use addressKey to distinguish between two endpoints that are identical addresses\n\t// but may have come from different hosts, for attribution. For instance, Mesos\n\t// assigns pods the node IP, but the pods are distinct.\n\tkey := addressKey{ip: addr.IP}\n\tif addr.TargetRef != nil {\n\t\tkey.uid = addr.TargetRef.UID\n\t}\n\n\t// Accumulate the address. The full EndpointAddress structure is preserved for use when\n\t// we rebuild the subsets so that the final TargetRef has all of the necessary data.\n\texistingAddress := allAddrs[key]\n\tif existingAddress == nil {\n\t\t// Make a copy so we don't write to the\n\t\t// input args of this function.\n\t\texistingAddress = \u0026v1.EndpointAddress{}\n\t\t*existingAddress = *addr\n\t\tallAddrs[key] = existingAddress\n\t}\n\n\t// Remember that this port maps to this address.\n\tif _, found := portToAddrReadyMap[port]; !found {\n\t\tportToAddrReadyMap[port] = addressSet{}\n\t}\n\t// if we have not yet recorded this port for this address, or if the previous\n\t// state was ready, write the current ready state. not ready always trumps\n\t// ready.\n\tif wasReady, found := portToAddrReadyMap[port][existingAddress]; !found || wasReady {\n\t\tportToAddrReadyMap[port][existingAddress] = ready\n\t}\n\treturn existingAddress\n}","line":{"from":105,"to":138}} {"id":100001725,"name":"hashAddresses","signature":"func hashAddresses(addrs addressSet) string","file":"pkg/api/v1/endpoints/util.go","code":"func hashAddresses(addrs addressSet) string {\n\t// Flatten the list of addresses into a string so it can be used as a\n\t// map key. Unfortunately, DeepHashObject is implemented in terms of\n\t// spew, and spew does not handle non-primitive map keys well. So\n\t// first we collapse it into a slice, sort the slice, then hash that.\n\tslice := make([]addrReady, 0, len(addrs))\n\tfor k, ready := range addrs {\n\t\tslice = append(slice, addrReady{k, ready})\n\t}\n\tsort.Sort(addrsReady(slice))\n\thasher := md5.New()\n\thashutil.DeepHashObject(hasher, slice)\n\treturn hex.EncodeToString(hasher.Sum(nil)[0:])\n}","line":{"from":147,"to":160}} {"id":100001726,"name":"lessAddrReady","signature":"func lessAddrReady(a, b addrReady) bool","file":"pkg/api/v1/endpoints/util.go","code":"func lessAddrReady(a, b addrReady) bool {\n\t// ready is not significant to hashing since we can't have duplicate addresses\n\treturn LessEndpointAddress(a.addr, b.addr)\n}","line":{"from":162,"to":165}} {"id":100001727,"name":"Len","signature":"func (sl addrsReady) Len() int { return len(sl) }","file":"pkg/api/v1/endpoints/util.go","code":"func (sl addrsReady) Len() int { return len(sl) }","line":{"from":169,"to":169}} {"id":100001728,"name":"Swap","signature":"func (sl addrsReady) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] }","file":"pkg/api/v1/endpoints/util.go","code":"func (sl addrsReady) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] }","line":{"from":170,"to":170}} {"id":100001729,"name":"Less","signature":"func (sl addrsReady) Less(i, j int) bool","file":"pkg/api/v1/endpoints/util.go","code":"func (sl addrsReady) Less(i, j int) bool {\n\treturn lessAddrReady(sl[i], sl[j])\n}","line":{"from":171,"to":173}} {"id":100001730,"name":"LessEndpointAddress","signature":"func LessEndpointAddress(a, b *v1.EndpointAddress) bool","file":"pkg/api/v1/endpoints/util.go","code":"// LessEndpointAddress compares IP addresses lexicographically and returns true if first argument is lesser than second\nfunc LessEndpointAddress(a, b *v1.EndpointAddress) bool {\n\tipComparison := bytes.Compare([]byte(a.IP), []byte(b.IP))\n\tif ipComparison != 0 {\n\t\treturn ipComparison \u003c 0\n\t}\n\tif b.TargetRef == nil {\n\t\treturn false\n\t}\n\tif a.TargetRef == nil {\n\t\treturn true\n\t}\n\treturn a.TargetRef.UID \u003c b.TargetRef.UID\n}","line":{"from":175,"to":188}} {"id":100001731,"name":"SortSubsets","signature":"func SortSubsets(subsets []v1.EndpointSubset) []v1.EndpointSubset","file":"pkg/api/v1/endpoints/util.go","code":"// SortSubsets sorts an array of EndpointSubset objects in place. For ease of\n// use it returns the input slice.\nfunc SortSubsets(subsets []v1.EndpointSubset) []v1.EndpointSubset {\n\tfor i := range subsets {\n\t\tss := \u0026subsets[i]\n\t\tsort.Sort(addrsByIPAndUID(ss.Addresses))\n\t\tsort.Sort(addrsByIPAndUID(ss.NotReadyAddresses))\n\t\tsort.Sort(portsByHash(ss.Ports))\n\t}\n\tsort.Sort(subsetsByHash(subsets))\n\treturn subsets\n}","line":{"from":190,"to":201}} {"id":100001732,"name":"hashObject","signature":"func hashObject(hasher hash.Hash, obj interface{}) []byte","file":"pkg/api/v1/endpoints/util.go","code":"func hashObject(hasher hash.Hash, obj interface{}) []byte {\n\thashutil.DeepHashObject(hasher, obj)\n\treturn hasher.Sum(nil)\n}","line":{"from":203,"to":206}} {"id":100001733,"name":"Len","signature":"func (sl subsetsByHash) Len() int { return len(sl) }","file":"pkg/api/v1/endpoints/util.go","code":"func (sl subsetsByHash) Len() int { return len(sl) }","line":{"from":210,"to":210}} {"id":100001734,"name":"Swap","signature":"func (sl subsetsByHash) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] }","file":"pkg/api/v1/endpoints/util.go","code":"func (sl subsetsByHash) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] }","line":{"from":211,"to":211}} {"id":100001735,"name":"Less","signature":"func (sl subsetsByHash) Less(i, j int) bool","file":"pkg/api/v1/endpoints/util.go","code":"func (sl subsetsByHash) Less(i, j int) bool {\n\thasher := md5.New()\n\th1 := hashObject(hasher, sl[i])\n\th2 := hashObject(hasher, sl[j])\n\treturn bytes.Compare(h1, h2) \u003c 0\n}","line":{"from":212,"to":217}} {"id":100001736,"name":"Len","signature":"func (sl addrsByIPAndUID) Len() int { return len(sl) }","file":"pkg/api/v1/endpoints/util.go","code":"func (sl addrsByIPAndUID) Len() int { return len(sl) }","line":{"from":221,"to":221}} {"id":100001737,"name":"Swap","signature":"func (sl addrsByIPAndUID) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] }","file":"pkg/api/v1/endpoints/util.go","code":"func (sl addrsByIPAndUID) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] }","line":{"from":222,"to":222}} {"id":100001738,"name":"Less","signature":"func (sl addrsByIPAndUID) Less(i, j int) bool","file":"pkg/api/v1/endpoints/util.go","code":"func (sl addrsByIPAndUID) Less(i, j int) bool {\n\treturn LessEndpointAddress(\u0026sl[i], \u0026sl[j])\n}","line":{"from":223,"to":225}} {"id":100001739,"name":"Len","signature":"func (sl portsByHash) Len() int { return len(sl) }","file":"pkg/api/v1/endpoints/util.go","code":"func (sl portsByHash) Len() int { return len(sl) }","line":{"from":229,"to":229}} {"id":100001740,"name":"Swap","signature":"func (sl portsByHash) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] }","file":"pkg/api/v1/endpoints/util.go","code":"func (sl portsByHash) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] }","line":{"from":230,"to":230}} {"id":100001741,"name":"Less","signature":"func (sl portsByHash) Less(i, j int) bool","file":"pkg/api/v1/endpoints/util.go","code":"func (sl portsByHash) Less(i, j int) bool {\n\thasher := md5.New()\n\th1 := hashObject(hasher, sl[i])\n\th2 := hashObject(hasher, sl[j])\n\treturn bytes.Compare(h1, h2) \u003c 0\n}","line":{"from":231,"to":236}} {"id":100001742,"name":"getClaimRefNamespace","signature":"func getClaimRefNamespace(pv *corev1.PersistentVolume) string","file":"pkg/api/v1/persistentvolume/util.go","code":"func getClaimRefNamespace(pv *corev1.PersistentVolume) string {\n\tif pv.Spec.ClaimRef != nil {\n\t\treturn pv.Spec.ClaimRef.Namespace\n\t}\n\treturn \"\"\n}","line":{"from":23,"to":28}} {"id":100001743,"name":"skipEmptyNames","signature":"func skipEmptyNames(visitor Visitor) Visitor","file":"pkg/api/v1/persistentvolume/util.go","code":"func skipEmptyNames(visitor Visitor) Visitor {\n\treturn func(namespace, name string, kubeletVisible bool) bool {\n\t\tif len(name) == 0 {\n\t\t\t// continue visiting\n\t\t\treturn true\n\t\t}\n\t\t// delegate to visitor\n\t\treturn visitor(namespace, name, kubeletVisible)\n\t}\n}","line":{"from":33,"to":42}} {"id":100001744,"name":"VisitPVSecretNames","signature":"func VisitPVSecretNames(pv *corev1.PersistentVolume, visitor Visitor) bool","file":"pkg/api/v1/persistentvolume/util.go","code":"// VisitPVSecretNames invokes the visitor function with the name of every secret\n// referenced by the PV spec. If visitor returns false, visiting is short-circuited.\n// Returns true if visiting completed, false if visiting was short-circuited.\nfunc VisitPVSecretNames(pv *corev1.PersistentVolume, visitor Visitor) bool {\n\tvisitor = skipEmptyNames(visitor)\n\tsource := \u0026pv.Spec.PersistentVolumeSource\n\tswitch {\n\tcase source.AzureFile != nil:\n\t\tif source.AzureFile.SecretNamespace != nil \u0026\u0026 len(*source.AzureFile.SecretNamespace) \u003e 0 {\n\t\t\tif len(source.AzureFile.SecretName) \u003e 0 \u0026\u0026 !visitor(*source.AzureFile.SecretNamespace, source.AzureFile.SecretName, true /* kubeletVisible */) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t} else {\n\t\t\tif len(source.AzureFile.SecretName) \u003e 0 \u0026\u0026 !visitor(getClaimRefNamespace(pv), source.AzureFile.SecretName, true /* kubeletVisible */) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\tcase source.CephFS != nil:\n\t\tif source.CephFS.SecretRef != nil {\n\t\t\t// previously persisted PV objects use claimRef namespace\n\t\t\tns := getClaimRefNamespace(pv)\n\t\t\tif len(source.CephFS.SecretRef.Namespace) \u003e 0 {\n\t\t\t\t// use the secret namespace if namespace is set\n\t\t\t\tns = source.CephFS.SecretRef.Namespace\n\t\t\t}\n\t\t\tif !visitor(ns, source.CephFS.SecretRef.Name, true /* kubeletVisible */) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\tcase source.Cinder != nil:\n\t\tif source.Cinder.SecretRef != nil \u0026\u0026 !visitor(source.Cinder.SecretRef.Namespace, source.Cinder.SecretRef.Name, true /* kubeletVisible */) {\n\t\t\treturn false\n\t\t}\n\tcase source.FlexVolume != nil:\n\t\tif source.FlexVolume.SecretRef != nil {\n\t\t\t// previously persisted PV objects use claimRef namespace\n\t\t\tns := getClaimRefNamespace(pv)\n\t\t\tif len(source.FlexVolume.SecretRef.Namespace) \u003e 0 {\n\t\t\t\t// use the secret namespace if namespace is set\n\t\t\t\tns = source.FlexVolume.SecretRef.Namespace\n\t\t\t}\n\t\t\tif !visitor(ns, source.FlexVolume.SecretRef.Name, true /* kubeletVisible */) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\tcase source.RBD != nil:\n\t\tif source.RBD.SecretRef != nil {\n\t\t\t// previously persisted PV objects use claimRef namespace\n\t\t\tns := getClaimRefNamespace(pv)\n\t\t\tif len(source.RBD.SecretRef.Namespace) \u003e 0 {\n\t\t\t\t// use the secret namespace if namespace is set\n\t\t\t\tns = source.RBD.SecretRef.Namespace\n\t\t\t}\n\t\t\tif !visitor(ns, source.RBD.SecretRef.Name, true /* kubeletVisible */) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\tcase source.ScaleIO != nil:\n\t\tif source.ScaleIO.SecretRef != nil {\n\t\t\tns := getClaimRefNamespace(pv)\n\t\t\tif source.ScaleIO.SecretRef != nil \u0026\u0026 len(source.ScaleIO.SecretRef.Namespace) \u003e 0 {\n\t\t\t\tns = source.ScaleIO.SecretRef.Namespace\n\t\t\t}\n\t\t\tif !visitor(ns, source.ScaleIO.SecretRef.Name, true /* kubeletVisible */) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\tcase source.ISCSI != nil:\n\t\tif source.ISCSI.SecretRef != nil {\n\t\t\t// previously persisted PV objects use claimRef namespace\n\t\t\tns := getClaimRefNamespace(pv)\n\t\t\tif len(source.ISCSI.SecretRef.Namespace) \u003e 0 {\n\t\t\t\t// use the secret namespace if namespace is set\n\t\t\t\tns = source.ISCSI.SecretRef.Namespace\n\t\t\t}\n\t\t\tif !visitor(ns, source.ISCSI.SecretRef.Name, true /* kubeletVisible */) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\tcase source.StorageOS != nil:\n\t\tif source.StorageOS.SecretRef != nil \u0026\u0026 !visitor(source.StorageOS.SecretRef.Namespace, source.StorageOS.SecretRef.Name, true /* kubeletVisible */) {\n\t\t\treturn false\n\t\t}\n\tcase source.CSI != nil:\n\t\tif source.CSI.ControllerPublishSecretRef != nil {\n\t\t\tif !visitor(source.CSI.ControllerPublishSecretRef.Namespace, source.CSI.ControllerPublishSecretRef.Name, false /* kubeletVisible */) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\tif source.CSI.ControllerExpandSecretRef != nil {\n\t\t\tif !visitor(source.CSI.ControllerExpandSecretRef.Namespace, source.CSI.ControllerExpandSecretRef.Name, false /* kubeletVisible */) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\n\t\tif source.CSI.NodePublishSecretRef != nil {\n\t\t\tif !visitor(source.CSI.NodePublishSecretRef.Namespace, source.CSI.NodePublishSecretRef.Name, true /* kubeletVisible */) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\tif source.CSI.NodeStageSecretRef != nil {\n\t\t\tif !visitor(source.CSI.NodeStageSecretRef.Namespace, source.CSI.NodeStageSecretRef.Name, true /* kubeletVisible */) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\tif source.CSI.NodeExpandSecretRef != nil {\n\t\t\tif !visitor(source.CSI.NodeExpandSecretRef.Namespace, source.CSI.NodeExpandSecretRef.Name, true /* kubeletVisible */) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}","line":{"from":44,"to":157}} {"id":100001745,"name":"FindPort","signature":"func FindPort(pod *v1.Pod, svcPort *v1.ServicePort) (int, error)","file":"pkg/api/v1/pod/util.go","code":"// FindPort locates the container port for the given pod and portName. If the\n// targetPort is a number, use that. If the targetPort is a string, look that\n// string up in all named ports in all containers in the target pod. If no\n// match is found, fail.\nfunc FindPort(pod *v1.Pod, svcPort *v1.ServicePort) (int, error) {\n\tportName := svcPort.TargetPort\n\tswitch portName.Type {\n\tcase intstr.String:\n\t\tname := portName.StrVal\n\t\tfor _, container := range pod.Spec.Containers {\n\t\t\tfor _, port := range container.Ports {\n\t\t\t\tif port.Name == name \u0026\u0026 port.Protocol == svcPort.Protocol {\n\t\t\t\t\treturn int(port.ContainerPort), nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase intstr.Int:\n\t\treturn portName.IntValue(), nil\n\t}\n\n\treturn 0, fmt.Errorf(\"no suitable port for manifest: %s\", pod.UID)\n}","line":{"from":28,"to":49}} {"id":100001746,"name":"AllFeatureEnabledContainers","signature":"func AllFeatureEnabledContainers() ContainerType","file":"pkg/api/v1/pod/util.go","code":"// AllFeatureEnabledContainers returns a ContainerType mask which includes all container\n// types except for the ones guarded by feature gate.\nfunc AllFeatureEnabledContainers() ContainerType {\n\treturn AllContainers\n}","line":{"from":66,"to":70}} {"id":100001747,"name":"skipEmptyNames","signature":"func skipEmptyNames(visitor Visitor) Visitor","file":"pkg/api/v1/pod/util.go","code":"func skipEmptyNames(visitor Visitor) Visitor {\n\treturn func(name string) bool {\n\t\tif len(name) == 0 {\n\t\t\t// continue visiting\n\t\t\treturn true\n\t\t}\n\t\t// delegate to visitor\n\t\treturn visitor(name)\n\t}\n}","line":{"from":79,"to":88}} {"id":100001748,"name":"VisitContainers","signature":"func VisitContainers(podSpec *v1.PodSpec, mask ContainerType, visitor ContainerVisitor) bool","file":"pkg/api/v1/pod/util.go","code":"// VisitContainers invokes the visitor function with a pointer to every container\n// spec in the given pod spec with type set in mask. If visitor returns false,\n// visiting is short-circuited. VisitContainers returns true if visiting completes,\n// false if visiting was short-circuited.\nfunc VisitContainers(podSpec *v1.PodSpec, mask ContainerType, visitor ContainerVisitor) bool {\n\tif mask\u0026InitContainers != 0 {\n\t\tfor i := range podSpec.InitContainers {\n\t\t\tif !visitor(\u0026podSpec.InitContainers[i], InitContainers) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\tif mask\u0026Containers != 0 {\n\t\tfor i := range podSpec.Containers {\n\t\t\tif !visitor(\u0026podSpec.Containers[i], Containers) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\tif mask\u0026EphemeralContainers != 0 {\n\t\tfor i := range podSpec.EphemeralContainers {\n\t\t\tif !visitor((*v1.Container)(\u0026podSpec.EphemeralContainers[i].EphemeralContainerCommon), EphemeralContainers) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}","line":{"from":90,"to":117}} {"id":100001749,"name":"VisitPodSecretNames","signature":"func VisitPodSecretNames(pod *v1.Pod, visitor Visitor) bool","file":"pkg/api/v1/pod/util.go","code":"// VisitPodSecretNames invokes the visitor function with the name of every secret\n// referenced by the pod spec. If visitor returns false, visiting is short-circuited.\n// Transitive references (e.g. pod -\u003e pvc -\u003e pv -\u003e secret) are not visited.\n// Returns true if visiting completed, false if visiting was short-circuited.\nfunc VisitPodSecretNames(pod *v1.Pod, visitor Visitor) bool {\n\tvisitor = skipEmptyNames(visitor)\n\tfor _, reference := range pod.Spec.ImagePullSecrets {\n\t\tif !visitor(reference.Name) {\n\t\t\treturn false\n\t\t}\n\t}\n\tVisitContainers(\u0026pod.Spec, AllContainers, func(c *v1.Container, containerType ContainerType) bool {\n\t\treturn visitContainerSecretNames(c, visitor)\n\t})\n\tvar source *v1.VolumeSource\n\n\tfor i := range pod.Spec.Volumes {\n\t\tsource = \u0026pod.Spec.Volumes[i].VolumeSource\n\t\tswitch {\n\t\tcase source.AzureFile != nil:\n\t\t\tif len(source.AzureFile.SecretName) \u003e 0 \u0026\u0026 !visitor(source.AzureFile.SecretName) {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase source.CephFS != nil:\n\t\t\tif source.CephFS.SecretRef != nil \u0026\u0026 !visitor(source.CephFS.SecretRef.Name) {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase source.Cinder != nil:\n\t\t\tif source.Cinder.SecretRef != nil \u0026\u0026 !visitor(source.Cinder.SecretRef.Name) {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase source.FlexVolume != nil:\n\t\t\tif source.FlexVolume.SecretRef != nil \u0026\u0026 !visitor(source.FlexVolume.SecretRef.Name) {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase source.Projected != nil:\n\t\t\tfor j := range source.Projected.Sources {\n\t\t\t\tif source.Projected.Sources[j].Secret != nil {\n\t\t\t\t\tif !visitor(source.Projected.Sources[j].Secret.Name) {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase source.RBD != nil:\n\t\t\tif source.RBD.SecretRef != nil \u0026\u0026 !visitor(source.RBD.SecretRef.Name) {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase source.Secret != nil:\n\t\t\tif !visitor(source.Secret.SecretName) {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase source.ScaleIO != nil:\n\t\t\tif source.ScaleIO.SecretRef != nil \u0026\u0026 !visitor(source.ScaleIO.SecretRef.Name) {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase source.ISCSI != nil:\n\t\t\tif source.ISCSI.SecretRef != nil \u0026\u0026 !visitor(source.ISCSI.SecretRef.Name) {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase source.StorageOS != nil:\n\t\t\tif source.StorageOS.SecretRef != nil \u0026\u0026 !visitor(source.StorageOS.SecretRef.Name) {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase source.CSI != nil:\n\t\t\tif source.CSI.NodePublishSecretRef != nil \u0026\u0026 !visitor(source.CSI.NodePublishSecretRef.Name) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}","line":{"from":119,"to":189}} {"id":100001750,"name":"visitContainerSecretNames","signature":"func visitContainerSecretNames(container *v1.Container, visitor Visitor) bool","file":"pkg/api/v1/pod/util.go","code":"// visitContainerSecretNames returns true unless the visitor returned false when invoked with a secret reference\nfunc visitContainerSecretNames(container *v1.Container, visitor Visitor) bool {\n\tfor _, env := range container.EnvFrom {\n\t\tif env.SecretRef != nil {\n\t\t\tif !visitor(env.SecretRef.Name) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\tfor _, envVar := range container.Env {\n\t\tif envVar.ValueFrom != nil \u0026\u0026 envVar.ValueFrom.SecretKeyRef != nil {\n\t\t\tif !visitor(envVar.ValueFrom.SecretKeyRef.Name) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}","line":{"from":191,"to":208}} {"id":100001751,"name":"VisitPodConfigmapNames","signature":"func VisitPodConfigmapNames(pod *v1.Pod, visitor Visitor) bool","file":"pkg/api/v1/pod/util.go","code":"// VisitPodConfigmapNames invokes the visitor function with the name of every configmap\n// referenced by the pod spec. If visitor returns false, visiting is short-circuited.\n// Transitive references (e.g. pod -\u003e pvc -\u003e pv -\u003e secret) are not visited.\n// Returns true if visiting completed, false if visiting was short-circuited.\nfunc VisitPodConfigmapNames(pod *v1.Pod, visitor Visitor) bool {\n\tvisitor = skipEmptyNames(visitor)\n\tVisitContainers(\u0026pod.Spec, AllContainers, func(c *v1.Container, containerType ContainerType) bool {\n\t\treturn visitContainerConfigmapNames(c, visitor)\n\t})\n\tvar source *v1.VolumeSource\n\tfor i := range pod.Spec.Volumes {\n\t\tsource = \u0026pod.Spec.Volumes[i].VolumeSource\n\t\tswitch {\n\t\tcase source.Projected != nil:\n\t\t\tfor j := range source.Projected.Sources {\n\t\t\t\tif source.Projected.Sources[j].ConfigMap != nil {\n\t\t\t\t\tif !visitor(source.Projected.Sources[j].ConfigMap.Name) {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase source.ConfigMap != nil:\n\t\t\tif !visitor(source.ConfigMap.Name) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}","line":{"from":210,"to":238}} {"id":100001752,"name":"visitContainerConfigmapNames","signature":"func visitContainerConfigmapNames(container *v1.Container, visitor Visitor) bool","file":"pkg/api/v1/pod/util.go","code":"// visitContainerConfigmapNames returns true unless the visitor returned false when invoked with a configmap reference\nfunc visitContainerConfigmapNames(container *v1.Container, visitor Visitor) bool {\n\tfor _, env := range container.EnvFrom {\n\t\tif env.ConfigMapRef != nil {\n\t\t\tif !visitor(env.ConfigMapRef.Name) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\tfor _, envVar := range container.Env {\n\t\tif envVar.ValueFrom != nil \u0026\u0026 envVar.ValueFrom.ConfigMapKeyRef != nil {\n\t\t\tif !visitor(envVar.ValueFrom.ConfigMapKeyRef.Name) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}","line":{"from":240,"to":257}} {"id":100001753,"name":"GetContainerStatus","signature":"func GetContainerStatus(statuses []v1.ContainerStatus, name string) (v1.ContainerStatus, bool)","file":"pkg/api/v1/pod/util.go","code":"// GetContainerStatus extracts the status of container \"name\" from \"statuses\".\n// It returns true if \"name\" exists, else returns false.\nfunc GetContainerStatus(statuses []v1.ContainerStatus, name string) (v1.ContainerStatus, bool) {\n\tfor i := range statuses {\n\t\tif statuses[i].Name == name {\n\t\t\treturn statuses[i], true\n\t\t}\n\t}\n\treturn v1.ContainerStatus{}, false\n}","line":{"from":259,"to":268}} {"id":100001754,"name":"GetExistingContainerStatus","signature":"func GetExistingContainerStatus(statuses []v1.ContainerStatus, name string) v1.ContainerStatus","file":"pkg/api/v1/pod/util.go","code":"// GetExistingContainerStatus extracts the status of container \"name\" from \"statuses\",\n// It also returns if \"name\" exists.\nfunc GetExistingContainerStatus(statuses []v1.ContainerStatus, name string) v1.ContainerStatus {\n\tstatus, _ := GetContainerStatus(statuses, name)\n\treturn status\n}","line":{"from":270,"to":275}} {"id":100001755,"name":"GetIndexOfContainerStatus","signature":"func GetIndexOfContainerStatus(statuses []v1.ContainerStatus, name string) (int, bool)","file":"pkg/api/v1/pod/util.go","code":"// GetIndexOfContainerStatus gets the index of status of container \"name\" from \"statuses\",\n// It returns (index, true) if \"name\" exists, else returns (0, false).\nfunc GetIndexOfContainerStatus(statuses []v1.ContainerStatus, name string) (int, bool) {\n\tfor i := range statuses {\n\t\tif statuses[i].Name == name {\n\t\t\treturn i, true\n\t\t}\n\t}\n\treturn 0, false\n}","line":{"from":277,"to":286}} {"id":100001756,"name":"IsPodAvailable","signature":"func IsPodAvailable(pod *v1.Pod, minReadySeconds int32, now metav1.Time) bool","file":"pkg/api/v1/pod/util.go","code":"// IsPodAvailable returns true if a pod is available; false otherwise.\n// Precondition for an available pod is that it must be ready. On top\n// of that, there are two cases when a pod can be considered available:\n// 1. minReadySeconds == 0, or\n// 2. LastTransitionTime (is set) + minReadySeconds \u003c current time\nfunc IsPodAvailable(pod *v1.Pod, minReadySeconds int32, now metav1.Time) bool {\n\tif !IsPodReady(pod) {\n\t\treturn false\n\t}\n\n\tc := GetPodReadyCondition(pod.Status)\n\tminReadySecondsDuration := time.Duration(minReadySeconds) * time.Second\n\tif minReadySeconds == 0 || (!c.LastTransitionTime.IsZero() \u0026\u0026 c.LastTransitionTime.Add(minReadySecondsDuration).Before(now.Time)) {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":288,"to":304}} {"id":100001757,"name":"IsPodReady","signature":"func IsPodReady(pod *v1.Pod) bool","file":"pkg/api/v1/pod/util.go","code":"// IsPodReady returns true if a pod is ready; false otherwise.\nfunc IsPodReady(pod *v1.Pod) bool {\n\treturn IsPodReadyConditionTrue(pod.Status)\n}","line":{"from":306,"to":309}} {"id":100001758,"name":"IsPodTerminal","signature":"func IsPodTerminal(pod *v1.Pod) bool","file":"pkg/api/v1/pod/util.go","code":"// IsPodTerminal returns true if a pod is terminal, all containers are stopped and cannot ever regress.\nfunc IsPodTerminal(pod *v1.Pod) bool {\n\treturn IsPodPhaseTerminal(pod.Status.Phase)\n}","line":{"from":311,"to":314}} {"id":100001759,"name":"IsPodPhaseTerminal","signature":"func IsPodPhaseTerminal(phase v1.PodPhase) bool","file":"pkg/api/v1/pod/util.go","code":"// IsPodPhaseTerminal returns true if the pod's phase is terminal.\nfunc IsPodPhaseTerminal(phase v1.PodPhase) bool {\n\treturn phase == v1.PodFailed || phase == v1.PodSucceeded\n}","line":{"from":316,"to":319}} {"id":100001760,"name":"IsPodReadyConditionTrue","signature":"func IsPodReadyConditionTrue(status v1.PodStatus) bool","file":"pkg/api/v1/pod/util.go","code":"// IsPodReadyConditionTrue returns true if a pod is ready; false otherwise.\nfunc IsPodReadyConditionTrue(status v1.PodStatus) bool {\n\tcondition := GetPodReadyCondition(status)\n\treturn condition != nil \u0026\u0026 condition.Status == v1.ConditionTrue\n}","line":{"from":321,"to":325}} {"id":100001761,"name":"IsContainersReadyConditionTrue","signature":"func IsContainersReadyConditionTrue(status v1.PodStatus) bool","file":"pkg/api/v1/pod/util.go","code":"// IsContainersReadyConditionTrue returns true if a pod is ready; false otherwise.\nfunc IsContainersReadyConditionTrue(status v1.PodStatus) bool {\n\tcondition := GetContainersReadyCondition(status)\n\treturn condition != nil \u0026\u0026 condition.Status == v1.ConditionTrue\n}","line":{"from":327,"to":331}} {"id":100001762,"name":"GetPodReadyCondition","signature":"func GetPodReadyCondition(status v1.PodStatus) *v1.PodCondition","file":"pkg/api/v1/pod/util.go","code":"// GetPodReadyCondition extracts the pod ready condition from the given status and returns that.\n// Returns nil if the condition is not present.\nfunc GetPodReadyCondition(status v1.PodStatus) *v1.PodCondition {\n\t_, condition := GetPodCondition(\u0026status, v1.PodReady)\n\treturn condition\n}","line":{"from":333,"to":338}} {"id":100001763,"name":"GetContainersReadyCondition","signature":"func GetContainersReadyCondition(status v1.PodStatus) *v1.PodCondition","file":"pkg/api/v1/pod/util.go","code":"// GetContainersReadyCondition extracts the containers ready condition from the given status and returns that.\n// Returns nil if the condition is not present.\nfunc GetContainersReadyCondition(status v1.PodStatus) *v1.PodCondition {\n\t_, condition := GetPodCondition(\u0026status, v1.ContainersReady)\n\treturn condition\n}","line":{"from":340,"to":345}} {"id":100001764,"name":"GetPodCondition","signature":"func GetPodCondition(status *v1.PodStatus, conditionType v1.PodConditionType) (int, *v1.PodCondition)","file":"pkg/api/v1/pod/util.go","code":"// GetPodCondition extracts the provided condition from the given status and returns that.\n// Returns nil and -1 if the condition is not present, and the index of the located condition.\nfunc GetPodCondition(status *v1.PodStatus, conditionType v1.PodConditionType) (int, *v1.PodCondition) {\n\tif status == nil {\n\t\treturn -1, nil\n\t}\n\treturn GetPodConditionFromList(status.Conditions, conditionType)\n}","line":{"from":347,"to":354}} {"id":100001765,"name":"GetPodConditionFromList","signature":"func GetPodConditionFromList(conditions []v1.PodCondition, conditionType v1.PodConditionType) (int, *v1.PodCondition)","file":"pkg/api/v1/pod/util.go","code":"// GetPodConditionFromList extracts the provided condition from the given list of condition and\n// returns the index of the condition and the condition. Returns -1 and nil if the condition is not present.\nfunc GetPodConditionFromList(conditions []v1.PodCondition, conditionType v1.PodConditionType) (int, *v1.PodCondition) {\n\tif conditions == nil {\n\t\treturn -1, nil\n\t}\n\tfor i := range conditions {\n\t\tif conditions[i].Type == conditionType {\n\t\t\treturn i, \u0026conditions[i]\n\t\t}\n\t}\n\treturn -1, nil\n}","line":{"from":356,"to":368}} {"id":100001766,"name":"UpdatePodCondition","signature":"func UpdatePodCondition(status *v1.PodStatus, condition *v1.PodCondition) bool","file":"pkg/api/v1/pod/util.go","code":"// UpdatePodCondition updates existing pod condition or creates a new one. Sets LastTransitionTime to now if the\n// status has changed.\n// Returns true if pod condition has changed or has been added.\nfunc UpdatePodCondition(status *v1.PodStatus, condition *v1.PodCondition) bool {\n\tcondition.LastTransitionTime = metav1.Now()\n\t// Try to find this pod condition.\n\tconditionIndex, oldCondition := GetPodCondition(status, condition.Type)\n\n\tif oldCondition == nil {\n\t\t// We are adding new pod condition.\n\t\tstatus.Conditions = append(status.Conditions, *condition)\n\t\treturn true\n\t}\n\t// We are updating an existing condition, so we need to check if it has changed.\n\tif condition.Status == oldCondition.Status {\n\t\tcondition.LastTransitionTime = oldCondition.LastTransitionTime\n\t}\n\n\tisEqual := condition.Status == oldCondition.Status \u0026\u0026\n\t\tcondition.Reason == oldCondition.Reason \u0026\u0026\n\t\tcondition.Message == oldCondition.Message \u0026\u0026\n\t\tcondition.LastProbeTime.Equal(\u0026oldCondition.LastProbeTime) \u0026\u0026\n\t\tcondition.LastTransitionTime.Equal(\u0026oldCondition.LastTransitionTime)\n\n\tstatus.Conditions[conditionIndex] = *condition\n\t// Return true if one of the fields have changed.\n\treturn !isEqual\n}","line":{"from":370,"to":397}} {"id":100001767,"name":"PodRequests","signature":"func PodRequests(pod *v1.Pod, opts PodResourcesOptions) v1.ResourceList","file":"pkg/api/v1/resource/helpers.go","code":"// PodRequests computes the pod requests per the PodResourcesOptions supplied. If PodResourcesOptions is nil, then\n// the requests are returned including pod overhead. The computation is part of the API and must be reviewed\n// as an API change.\nfunc PodRequests(pod *v1.Pod, opts PodResourcesOptions) v1.ResourceList {\n\t// attempt to reuse the maps if passed, or allocate otherwise\n\treqs := reuseOrClearResourceList(opts.Reuse)\n\n\tvar containerStatuses map[string]*v1.ContainerStatus\n\tif opts.InPlacePodVerticalScalingEnabled {\n\t\tcontainerStatuses = map[string]*v1.ContainerStatus{}\n\t\tfor i := range pod.Status.ContainerStatuses {\n\t\t\tcontainerStatuses[pod.Status.ContainerStatuses[i].Name] = \u0026pod.Status.ContainerStatuses[i]\n\t\t}\n\t}\n\n\tfor _, container := range pod.Spec.Containers {\n\t\tcontainerReqs := container.Resources.Requests\n\t\tif opts.InPlacePodVerticalScalingEnabled {\n\t\t\tcs, found := containerStatuses[container.Name]\n\t\t\tif found {\n\t\t\t\tif pod.Status.Resize == v1.PodResizeStatusInfeasible {\n\t\t\t\t\tcontainerReqs = cs.AllocatedResources\n\t\t\t\t} else {\n\t\t\t\t\tcontainerReqs = max(container.Resources.Requests, cs.AllocatedResources)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(opts.NonMissingContainerRequests) \u003e 0 {\n\t\t\tcontainerReqs = applyNonMissing(containerReqs, opts.NonMissingContainerRequests)\n\t\t}\n\n\t\tif opts.ContainerFn != nil {\n\t\t\topts.ContainerFn(containerReqs, podutil.Containers)\n\t\t}\n\n\t\taddResourceList(reqs, containerReqs)\n\t}\n\n\t// init containers define the minimum of any resource\n\t// Note: In-place resize is not allowed for InitContainers, so no need to check for ResizeStatus value\n\tfor _, container := range pod.Spec.InitContainers {\n\t\tcontainerReqs := container.Resources.Requests\n\t\tif len(opts.NonMissingContainerRequests) \u003e 0 {\n\t\t\tcontainerReqs = applyNonMissing(containerReqs, opts.NonMissingContainerRequests)\n\t\t}\n\n\t\tif opts.ContainerFn != nil {\n\t\t\topts.ContainerFn(containerReqs, podutil.InitContainers)\n\t\t}\n\t\tmaxResourceList(reqs, containerReqs)\n\t}\n\n\t// Add overhead for running a pod to the sum of requests if requested:\n\tif !opts.ExcludeOverhead \u0026\u0026 pod.Spec.Overhead != nil {\n\t\taddResourceList(reqs, pod.Spec.Overhead)\n\t}\n\n\treturn reqs\n}","line":{"from":47,"to":106}} {"id":100001768,"name":"applyNonMissing","signature":"func applyNonMissing(reqs v1.ResourceList, nonMissing v1.ResourceList) v1.ResourceList","file":"pkg/api/v1/resource/helpers.go","code":"// applyNonMissing will return a copy of the given resource list with any missing values replaced by the nonMissing values\nfunc applyNonMissing(reqs v1.ResourceList, nonMissing v1.ResourceList) v1.ResourceList {\n\tcp := v1.ResourceList{}\n\tfor k, v := range reqs {\n\t\tcp[k] = v.DeepCopy()\n\t}\n\n\tfor k, v := range nonMissing {\n\t\tif _, found := reqs[k]; !found {\n\t\t\trk := cp[k]\n\t\t\trk.Add(v)\n\t\t\tcp[k] = rk\n\t\t}\n\t}\n\treturn cp\n}","line":{"from":108,"to":123}} {"id":100001769,"name":"PodLimits","signature":"func PodLimits(pod *v1.Pod, opts PodResourcesOptions) v1.ResourceList","file":"pkg/api/v1/resource/helpers.go","code":"// PodLimits computes the pod limits per the PodResourcesOptions supplied. If PodResourcesOptions is nil, then\n// the limits are returned including pod overhead for any non-zero limits. The computation is part of the API and must be reviewed\n// as an API change.\nfunc PodLimits(pod *v1.Pod, opts PodResourcesOptions) v1.ResourceList {\n\t// attempt to reuse the maps if passed, or allocate otherwise\n\tlimits := reuseOrClearResourceList(opts.Reuse)\n\n\tfor _, container := range pod.Spec.Containers {\n\t\tif opts.ContainerFn != nil {\n\t\t\topts.ContainerFn(container.Resources.Limits, podutil.Containers)\n\t\t}\n\t\taddResourceList(limits, container.Resources.Limits)\n\t}\n\t// init containers define the minimum of any resource\n\tfor _, container := range pod.Spec.InitContainers {\n\t\tif opts.ContainerFn != nil {\n\t\t\topts.ContainerFn(container.Resources.Limits, podutil.InitContainers)\n\t\t}\n\t\tmaxResourceList(limits, container.Resources.Limits)\n\t}\n\n\t// Add overhead to non-zero limits if requested:\n\tif !opts.ExcludeOverhead \u0026\u0026 pod.Spec.Overhead != nil {\n\t\tfor name, quantity := range pod.Spec.Overhead {\n\t\t\tif value, ok := limits[name]; ok \u0026\u0026 !value.IsZero() {\n\t\t\t\tvalue.Add(quantity)\n\t\t\t\tlimits[name] = value\n\t\t\t}\n\t\t}\n\t}\n\n\treturn limits\n}","line":{"from":125,"to":157}} {"id":100001770,"name":"addResourceList","signature":"func addResourceList(list, newList v1.ResourceList)","file":"pkg/api/v1/resource/helpers.go","code":"// addResourceList adds the resources in newList to list.\nfunc addResourceList(list, newList v1.ResourceList) {\n\tfor name, quantity := range newList {\n\t\tif value, ok := list[name]; !ok {\n\t\t\tlist[name] = quantity.DeepCopy()\n\t\t} else {\n\t\t\tvalue.Add(quantity)\n\t\t\tlist[name] = value\n\t\t}\n\t}\n}","line":{"from":159,"to":169}} {"id":100001771,"name":"maxResourceList","signature":"func maxResourceList(list, newList v1.ResourceList)","file":"pkg/api/v1/resource/helpers.go","code":"// maxResourceList sets list to the greater of list/newList for every resource in newList\nfunc maxResourceList(list, newList v1.ResourceList) {\n\tfor name, quantity := range newList {\n\t\tif value, ok := list[name]; !ok || quantity.Cmp(value) \u003e 0 {\n\t\t\tlist[name] = quantity.DeepCopy()\n\t\t}\n\t}\n}","line":{"from":171,"to":178}} {"id":100001772,"name":"max","signature":"func max(a v1.ResourceList, b v1.ResourceList) v1.ResourceList","file":"pkg/api/v1/resource/helpers.go","code":"// max returns the result of max(a, b) for each named resource and is only used if we can't\n// accumulate into an existing resource list\nfunc max(a v1.ResourceList, b v1.ResourceList) v1.ResourceList {\n\tresult := v1.ResourceList{}\n\tfor key, value := range a {\n\t\tif other, found := b[key]; found {\n\t\t\tif value.Cmp(other) \u003c= 0 {\n\t\t\t\tresult[key] = other.DeepCopy()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tresult[key] = value.DeepCopy()\n\t}\n\tfor key, value := range b {\n\t\tif _, found := result[key]; !found {\n\t\t\tresult[key] = value.DeepCopy()\n\t\t}\n\t}\n\treturn result\n}","line":{"from":180,"to":199}} {"id":100001773,"name":"reuseOrClearResourceList","signature":"func reuseOrClearResourceList(reuse v1.ResourceList) v1.ResourceList","file":"pkg/api/v1/resource/helpers.go","code":"// reuseOrClearResourceList is a helper for avoiding excessive allocations of\n// resource lists within the inner loop of resource calculations.\nfunc reuseOrClearResourceList(reuse v1.ResourceList) v1.ResourceList {\n\tif reuse == nil {\n\t\treturn make(v1.ResourceList, 4)\n\t}\n\tfor k := range reuse {\n\t\tdelete(reuse, k)\n\t}\n\treturn reuse\n}","line":{"from":201,"to":211}} {"id":100001774,"name":"GetResourceRequestQuantity","signature":"func GetResourceRequestQuantity(pod *v1.Pod, resourceName v1.ResourceName) resource.Quantity","file":"pkg/api/v1/resource/helpers.go","code":"// GetResourceRequestQuantity finds and returns the request quantity for a specific resource.\nfunc GetResourceRequestQuantity(pod *v1.Pod, resourceName v1.ResourceName) resource.Quantity {\n\trequestQuantity := resource.Quantity{}\n\n\tswitch resourceName {\n\tcase v1.ResourceCPU:\n\t\trequestQuantity = resource.Quantity{Format: resource.DecimalSI}\n\tcase v1.ResourceMemory, v1.ResourceStorage, v1.ResourceEphemeralStorage:\n\t\trequestQuantity = resource.Quantity{Format: resource.BinarySI}\n\tdefault:\n\t\trequestQuantity = resource.Quantity{Format: resource.DecimalSI}\n\t}\n\n\tfor _, container := range pod.Spec.Containers {\n\t\tif rQuantity, ok := container.Resources.Requests[resourceName]; ok {\n\t\t\trequestQuantity.Add(rQuantity)\n\t\t}\n\t}\n\n\tfor _, container := range pod.Spec.InitContainers {\n\t\tif rQuantity, ok := container.Resources.Requests[resourceName]; ok {\n\t\t\tif requestQuantity.Cmp(rQuantity) \u003c 0 {\n\t\t\t\trequestQuantity = rQuantity.DeepCopy()\n\t\t\t}\n\t\t}\n\t}\n\n\t// Add overhead for running a pod\n\t// to the total requests if the resource total is non-zero\n\tif pod.Spec.Overhead != nil {\n\t\tif podOverhead, ok := pod.Spec.Overhead[resourceName]; ok \u0026\u0026 !requestQuantity.IsZero() {\n\t\t\trequestQuantity.Add(podOverhead)\n\t\t}\n\t}\n\n\treturn requestQuantity\n}","line":{"from":213,"to":249}} {"id":100001775,"name":"GetResourceRequest","signature":"func GetResourceRequest(pod *v1.Pod, resource v1.ResourceName) int64","file":"pkg/api/v1/resource/helpers.go","code":"// GetResourceRequest finds and returns the request value for a specific resource.\nfunc GetResourceRequest(pod *v1.Pod, resource v1.ResourceName) int64 {\n\tif resource == v1.ResourcePods {\n\t\treturn 1\n\t}\n\n\trequestQuantity := GetResourceRequestQuantity(pod, resource)\n\n\tif resource == v1.ResourceCPU {\n\t\treturn requestQuantity.MilliValue()\n\t}\n\n\treturn requestQuantity.Value()\n}","line":{"from":251,"to":264}} {"id":100001776,"name":"ExtractResourceValueByContainerName","signature":"func ExtractResourceValueByContainerName(fs *v1.ResourceFieldSelector, pod *v1.Pod, containerName string) (string, error)","file":"pkg/api/v1/resource/helpers.go","code":"// ExtractResourceValueByContainerName extracts the value of a resource\n// by providing container name\nfunc ExtractResourceValueByContainerName(fs *v1.ResourceFieldSelector, pod *v1.Pod, containerName string) (string, error) {\n\tcontainer, err := findContainerInPod(pod, containerName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn ExtractContainerResourceValue(fs, container)\n}","line":{"from":266,"to":274}} {"id":100001777,"name":"ExtractResourceValueByContainerNameAndNodeAllocatable","signature":"func ExtractResourceValueByContainerNameAndNodeAllocatable(fs *v1.ResourceFieldSelector, pod *v1.Pod, containerName string, nodeAllocatable v1.ResourceList) (string, error)","file":"pkg/api/v1/resource/helpers.go","code":"// ExtractResourceValueByContainerNameAndNodeAllocatable extracts the value of a resource\n// by providing container name and node allocatable\nfunc ExtractResourceValueByContainerNameAndNodeAllocatable(fs *v1.ResourceFieldSelector, pod *v1.Pod, containerName string, nodeAllocatable v1.ResourceList) (string, error) {\n\trealContainer, err := findContainerInPod(pod, containerName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcontainer := realContainer.DeepCopy()\n\n\tMergeContainerResourceLimits(container, nodeAllocatable)\n\n\treturn ExtractContainerResourceValue(fs, container)\n}","line":{"from":276,"to":289}} {"id":100001778,"name":"ExtractContainerResourceValue","signature":"func ExtractContainerResourceValue(fs *v1.ResourceFieldSelector, container *v1.Container) (string, error)","file":"pkg/api/v1/resource/helpers.go","code":"// ExtractContainerResourceValue extracts the value of a resource\n// in an already known container\nfunc ExtractContainerResourceValue(fs *v1.ResourceFieldSelector, container *v1.Container) (string, error) {\n\tdivisor := resource.Quantity{}\n\tif divisor.Cmp(fs.Divisor) == 0 {\n\t\tdivisor = resource.MustParse(\"1\")\n\t} else {\n\t\tdivisor = fs.Divisor\n\t}\n\n\tswitch fs.Resource {\n\tcase \"limits.cpu\":\n\t\treturn convertResourceCPUToString(container.Resources.Limits.Cpu(), divisor)\n\tcase \"limits.memory\":\n\t\treturn convertResourceMemoryToString(container.Resources.Limits.Memory(), divisor)\n\tcase \"limits.ephemeral-storage\":\n\t\treturn convertResourceEphemeralStorageToString(container.Resources.Limits.StorageEphemeral(), divisor)\n\tcase \"requests.cpu\":\n\t\treturn convertResourceCPUToString(container.Resources.Requests.Cpu(), divisor)\n\tcase \"requests.memory\":\n\t\treturn convertResourceMemoryToString(container.Resources.Requests.Memory(), divisor)\n\tcase \"requests.ephemeral-storage\":\n\t\treturn convertResourceEphemeralStorageToString(container.Resources.Requests.StorageEphemeral(), divisor)\n\t}\n\t// handle extended standard resources with dynamic names\n\t// example: requests.hugepages-\u003cpageSize\u003e or limits.hugepages-\u003cpageSize\u003e\n\tif strings.HasPrefix(fs.Resource, \"requests.\") {\n\t\tresourceName := v1.ResourceName(strings.TrimPrefix(fs.Resource, \"requests.\"))\n\t\tif IsHugePageResourceName(resourceName) {\n\t\t\treturn convertResourceHugePagesToString(container.Resources.Requests.Name(resourceName, resource.BinarySI), divisor)\n\t\t}\n\t}\n\tif strings.HasPrefix(fs.Resource, \"limits.\") {\n\t\tresourceName := v1.ResourceName(strings.TrimPrefix(fs.Resource, \"limits.\"))\n\t\tif IsHugePageResourceName(resourceName) {\n\t\t\treturn convertResourceHugePagesToString(container.Resources.Limits.Name(resourceName, resource.BinarySI), divisor)\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"unsupported container resource : %v\", fs.Resource)\n}","line":{"from":291,"to":330}} {"id":100001779,"name":"convertResourceCPUToString","signature":"func convertResourceCPUToString(cpu *resource.Quantity, divisor resource.Quantity) (string, error)","file":"pkg/api/v1/resource/helpers.go","code":"// convertResourceCPUToString converts cpu value to the format of divisor and returns\n// ceiling of the value.\nfunc convertResourceCPUToString(cpu *resource.Quantity, divisor resource.Quantity) (string, error) {\n\tc := int64(math.Ceil(float64(cpu.MilliValue()) / float64(divisor.MilliValue())))\n\treturn strconv.FormatInt(c, 10), nil\n}","line":{"from":332,"to":337}} {"id":100001780,"name":"convertResourceMemoryToString","signature":"func convertResourceMemoryToString(memory *resource.Quantity, divisor resource.Quantity) (string, error)","file":"pkg/api/v1/resource/helpers.go","code":"// convertResourceMemoryToString converts memory value to the format of divisor and returns\n// ceiling of the value.\nfunc convertResourceMemoryToString(memory *resource.Quantity, divisor resource.Quantity) (string, error) {\n\tm := int64(math.Ceil(float64(memory.Value()) / float64(divisor.Value())))\n\treturn strconv.FormatInt(m, 10), nil\n}","line":{"from":339,"to":344}} {"id":100001781,"name":"convertResourceHugePagesToString","signature":"func convertResourceHugePagesToString(hugePages *resource.Quantity, divisor resource.Quantity) (string, error)","file":"pkg/api/v1/resource/helpers.go","code":"// convertResourceHugePagesToString converts hugepages value to the format of divisor and returns\n// ceiling of the value.\nfunc convertResourceHugePagesToString(hugePages *resource.Quantity, divisor resource.Quantity) (string, error) {\n\tm := int64(math.Ceil(float64(hugePages.Value()) / float64(divisor.Value())))\n\treturn strconv.FormatInt(m, 10), nil\n}","line":{"from":346,"to":351}} {"id":100001782,"name":"convertResourceEphemeralStorageToString","signature":"func convertResourceEphemeralStorageToString(ephemeralStorage *resource.Quantity, divisor resource.Quantity) (string, error)","file":"pkg/api/v1/resource/helpers.go","code":"// convertResourceEphemeralStorageToString converts ephemeral storage value to the format of divisor and returns\n// ceiling of the value.\nfunc convertResourceEphemeralStorageToString(ephemeralStorage *resource.Quantity, divisor resource.Quantity) (string, error) {\n\tm := int64(math.Ceil(float64(ephemeralStorage.Value()) / float64(divisor.Value())))\n\treturn strconv.FormatInt(m, 10), nil\n}","line":{"from":353,"to":358}} {"id":100001783,"name":"findContainerInPod","signature":"func findContainerInPod(pod *v1.Pod, containerName string) (*v1.Container, error)","file":"pkg/api/v1/resource/helpers.go","code":"// findContainerInPod finds a container by its name in the provided pod\nfunc findContainerInPod(pod *v1.Pod, containerName string) (*v1.Container, error) {\n\tfor _, container := range pod.Spec.Containers {\n\t\tif container.Name == containerName {\n\t\t\treturn \u0026container, nil\n\t\t}\n\t}\n\tfor _, container := range pod.Spec.InitContainers {\n\t\tif container.Name == containerName {\n\t\t\treturn \u0026container, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"container %s not found\", containerName)\n}","line":{"from":360,"to":373}} {"id":100001784,"name":"MergeContainerResourceLimits","signature":"func MergeContainerResourceLimits(container *v1.Container,","file":"pkg/api/v1/resource/helpers.go","code":"// MergeContainerResourceLimits checks if a limit is applied for\n// the container, and if not, it sets the limit to the passed resource list.\nfunc MergeContainerResourceLimits(container *v1.Container,\n\tallocatable v1.ResourceList) {\n\tif container.Resources.Limits == nil {\n\t\tcontainer.Resources.Limits = make(v1.ResourceList)\n\t}\n\t// NOTE: we exclude hugepages-* resources because hugepages are never overcommitted.\n\t// This means that the container always has a limit specified.\n\tfor _, resource := range []v1.ResourceName{v1.ResourceCPU, v1.ResourceMemory, v1.ResourceEphemeralStorage} {\n\t\tif quantity, exists := container.Resources.Limits[resource]; !exists || quantity.IsZero() {\n\t\t\tif cap, exists := allocatable[resource]; exists {\n\t\t\t\tcontainer.Resources.Limits[resource] = cap.DeepCopy()\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":375,"to":391}} {"id":100001785,"name":"IsHugePageResourceName","signature":"func IsHugePageResourceName(name v1.ResourceName) bool","file":"pkg/api/v1/resource/helpers.go","code":"// IsHugePageResourceName returns true if the resource name has the huge page\n// resource prefix.\nfunc IsHugePageResourceName(name v1.ResourceName) bool {\n\treturn strings.HasPrefix(string(name), v1.ResourceHugePagesPrefix)\n}","line":{"from":393,"to":397}} {"id":100001786,"name":"IsAllowAll","signature":"func IsAllowAll(ipnets utilnet.IPNetSet) bool","file":"pkg/api/v1/service/util.go","code":"// IsAllowAll checks whether the utilnet.IPNet allows traffic from 0.0.0.0/0\nfunc IsAllowAll(ipnets utilnet.IPNetSet) bool {\n\tfor _, s := range ipnets.StringSlice() {\n\t\tif s == \"0.0.0.0/0\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":31,"to":39}} {"id":100001787,"name":"GetLoadBalancerSourceRanges","signature":"func GetLoadBalancerSourceRanges(service *v1.Service) (utilnet.IPNetSet, error)","file":"pkg/api/v1/service/util.go","code":"// GetLoadBalancerSourceRanges first try to parse and verify LoadBalancerSourceRanges field from a service.\n// If the field is not specified, turn to parse and verify the AnnotationLoadBalancerSourceRangesKey annotation from a service,\n// extracting the source ranges to allow, and if not present returns a default (allow-all) value.\nfunc GetLoadBalancerSourceRanges(service *v1.Service) (utilnet.IPNetSet, error) {\n\tvar ipnets utilnet.IPNetSet\n\tvar err error\n\t// if SourceRange field is specified, ignore sourceRange annotation\n\tif len(service.Spec.LoadBalancerSourceRanges) \u003e 0 {\n\t\tspecs := service.Spec.LoadBalancerSourceRanges\n\t\tipnets, err = utilnet.ParseIPNets(specs...)\n\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"service.Spec.LoadBalancerSourceRanges: %v is not valid. Expecting a list of IP ranges. For example, 10.0.0.0/24. Error msg: %v\", specs, err)\n\t\t}\n\t} else {\n\t\tval := service.Annotations[v1.AnnotationLoadBalancerSourceRangesKey]\n\t\tval = strings.TrimSpace(val)\n\t\tif val == \"\" {\n\t\t\tval = defaultLoadBalancerSourceRanges\n\t\t}\n\t\tspecs := strings.Split(val, \",\")\n\t\tipnets, err = utilnet.ParseIPNets(specs...)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%s: %s is not valid. Expecting a comma-separated list of source IP ranges. For example, 10.0.0.0/24,192.168.2.0/24\", v1.AnnotationLoadBalancerSourceRangesKey, val)\n\t\t}\n\t}\n\treturn ipnets, nil\n}","line":{"from":41,"to":68}} {"id":100001788,"name":"ExternalPolicyLocal","signature":"func ExternalPolicyLocal(service *v1.Service) bool","file":"pkg/api/v1/service/util.go","code":"// ExternalPolicyLocal checks if service has ETP = Local.\nfunc ExternalPolicyLocal(service *v1.Service) bool {\n\tif service.Spec.Type != v1.ServiceTypeLoadBalancer \u0026\u0026\n\t\tservice.Spec.Type != v1.ServiceTypeNodePort {\n\t\treturn false\n\t}\n\treturn service.Spec.ExternalTrafficPolicy == v1.ServiceExternalTrafficPolicyLocal\n}","line":{"from":70,"to":77}} {"id":100001789,"name":"InternalPolicyLocal","signature":"func InternalPolicyLocal(service *v1.Service) bool","file":"pkg/api/v1/service/util.go","code":"// InternalPolicyLocal checks if service has ITP = Local.\nfunc InternalPolicyLocal(service *v1.Service) bool {\n\tif service.Spec.InternalTrafficPolicy == nil {\n\t\treturn false\n\t}\n\treturn *service.Spec.InternalTrafficPolicy == v1.ServiceInternalTrafficPolicyLocal\n}","line":{"from":79,"to":85}} {"id":100001790,"name":"NeedsHealthCheck","signature":"func NeedsHealthCheck(service *v1.Service) bool","file":"pkg/api/v1/service/util.go","code":"// NeedsHealthCheck checks if service needs health check.\nfunc NeedsHealthCheck(service *v1.Service) bool {\n\tif service.Spec.Type != v1.ServiceTypeLoadBalancer {\n\t\treturn false\n\t}\n\treturn ExternalPolicyLocal(service)\n}","line":{"from":87,"to":93}} {"id":100001791,"name":"init","signature":"func init()","file":"pkg/apis/abac/register.go","code":"func init() {\n\t// TODO: delete this, abac should not have its own scheme.\n\taddKnownTypes(Scheme)\n}","line":{"from":38,"to":41}} {"id":100001792,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/abac/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Policy{},\n\t)\n\treturn nil\n}","line":{"from":50,"to":55}} {"id":100001793,"name":"Convert_v0_Policy_To_abac_Policy","signature":"func Convert_v0_Policy_To_abac_Policy(in *Policy, out *abac.Policy, s conversion.Scope) error","file":"pkg/apis/abac/v0/conversion.go","code":"func Convert_v0_Policy_To_abac_Policy(in *Policy, out *abac.Policy, s conversion.Scope) error {\n\tout.Spec.User = in.User\n\tout.Spec.Group = in.Group\n\tout.Spec.Namespace = in.Namespace\n\tout.Spec.Resource = in.Resource\n\tout.Spec.Readonly = in.Readonly\n\n\t// In v0, unspecified user and group matches all authenticated subjects\n\tif len(in.User) == 0 \u0026\u0026 len(in.Group) == 0 {\n\t\tout.Spec.Group = allAuthenticated\n\t}\n\t// In v0, user or group of * matches all authenticated subjects\n\tif in.User == \"*\" || in.Group == \"*\" {\n\t\tout.Spec.Group = allAuthenticated\n\t\tout.Spec.User = \"\"\n\t}\n\n\t// In v0, leaving namespace empty matches all namespaces\n\tif len(in.Namespace) == 0 {\n\t\tout.Spec.Namespace = \"*\"\n\t}\n\t// In v0, leaving resource empty matches all resources\n\tif len(in.Resource) == 0 {\n\t\tout.Spec.Resource = \"*\"\n\t}\n\t// Any rule in v0 should match all API groups\n\tout.Spec.APIGroup = \"*\"\n\n\t// In v0, leaving namespace and resource blank allows non-resource paths\n\tif len(in.Namespace) == 0 \u0026\u0026 len(in.Resource) == 0 {\n\t\tout.Spec.NonResourcePath = \"*\"\n\t}\n\n\treturn nil\n}","line":{"from":28,"to":62}} {"id":100001794,"name":"init","signature":"func init()","file":"pkg/apis/abac/v0/register.go","code":"func init() {\n\t// TODO: Delete this init function, abac should not have its own scheme.\n\tutilruntime.Must(addKnownTypes(abac.Scheme))\n\n\tutilruntime.Must(RegisterConversions(abac.Scheme))\n}","line":{"from":32,"to":37}} {"id":100001795,"name":"init","signature":"func init()","file":"pkg/apis/abac/v0/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addKnownTypes)\n}","line":{"from":51,"to":56}} {"id":100001796,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/abac/v0/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Policy{},\n\t)\n\treturn nil\n}","line":{"from":58,"to":63}} {"id":100001797,"name":"Convert_v1beta1_Policy_To_abac_Policy","signature":"func Convert_v1beta1_Policy_To_abac_Policy(in *Policy, out *abac.Policy, s conversion.Scope) error","file":"pkg/apis/abac/v1beta1/conversion.go","code":"func Convert_v1beta1_Policy_To_abac_Policy(in *Policy, out *abac.Policy, s conversion.Scope) error {\n\tif err := autoConvert_v1beta1_Policy_To_abac_Policy(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\t// In v1beta1, * user or group maps to all authenticated subjects\n\tif in.Spec.User == \"*\" || in.Spec.Group == \"*\" {\n\t\tout.Spec.Group = allAuthenticated\n\t\tout.Spec.User = \"\"\n\t}\n\n\treturn nil\n}","line":{"from":28,"to":40}} {"id":100001798,"name":"init","signature":"func init()","file":"pkg/apis/abac/v1beta1/register.go","code":"func init() {\n\t// TODO: Delete this init function, abac should not have its own scheme.\n\tutilruntime.Must(addKnownTypes(abac.Scheme))\n\n\tutilruntime.Must(RegisterConversions(abac.Scheme))\n}","line":{"from":32,"to":37}} {"id":100001799,"name":"init","signature":"func init()","file":"pkg/apis/abac/v1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addKnownTypes, RegisterDefaults)\n}","line":{"from":51,"to":56}} {"id":100001800,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/abac/v1beta1/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Policy{},\n\t)\n\treturn nil\n}","line":{"from":58,"to":63}} {"id":100001801,"name":"init","signature":"func init()","file":"pkg/apis/admission/install/install.go","code":"func init() {\n\tInstall(legacyscheme.Scheme)\n}","line":{"from":30,"to":32}} {"id":100001802,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"pkg/apis/admission/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(admission.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1.SchemeGroupVersion, v1beta1.SchemeGroupVersion))\n}","line":{"from":34,"to":40}} {"id":100001803,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"pkg/apis/admission/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100001804,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/admission/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100001805,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/admission/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026AdmissionReview{},\n\t)\n\treturn nil\n}","line":{"from":47,"to":52}} {"id":100001806,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/admission/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100001807,"name":"init","signature":"func init()","file":"pkg/apis/admission/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(RegisterDefaults)\n}","line":{"from":41,"to":46}} {"id":100001808,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/admission/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100001809,"name":"init","signature":"func init()","file":"pkg/apis/admission/v1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(RegisterDefaults)\n}","line":{"from":41,"to":46}} {"id":100001810,"name":"init","signature":"func init()","file":"pkg/apis/admissionregistration/install/install.go","code":"func init() {\n\tInstall(legacyscheme.Scheme)\n}","line":{"from":29,"to":31}} {"id":100001811,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"pkg/apis/admissionregistration/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(admissionregistration.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(v1alpha1.AddToScheme(scheme))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1.SchemeGroupVersion, v1beta1.SchemeGroupVersion, v1alpha1.SchemeGroupVersion))\n}","line":{"from":33,"to":40}} {"id":100001812,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"pkg/apis/admissionregistration/register.go","code":"// Kind takes an unqualified kind and returns back a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100001813,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/admissionregistration/register.go","code":"// Resource takes an unqualified resource and returns back a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100001814,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/admissionregistration/register.go","code":"// Adds the list of known types to scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026ValidatingWebhookConfiguration{},\n\t\t\u0026ValidatingWebhookConfigurationList{},\n\t\t\u0026MutatingWebhookConfiguration{},\n\t\t\u0026MutatingWebhookConfigurationList{},\n\t\t\u0026ValidatingAdmissionPolicy{},\n\t\t\u0026ValidatingAdmissionPolicyList{},\n\t\t\u0026ValidatingAdmissionPolicyBinding{},\n\t\t\u0026ValidatingAdmissionPolicyBindingList{},\n\t)\n\treturn nil\n}","line":{"from":47,"to":60}} {"id":100001815,"name":"DropDisabledMutatingWebhookConfigurationFields","signature":"func DropDisabledMutatingWebhookConfigurationFields(mutatingWebhookConfiguration, oldMutatingWebhookConfiguration *MutatingWebhookConfiguration)","file":"pkg/apis/admissionregistration/util.go","code":"// DropDisabledMutatingWebhookConfigurationFields removes disabled fields from the mutatingWebhookConfiguration metadata and spec.\n// This should be called from PrepareForCreate/PrepareForUpdate for all resources containing a mutatingWebhookConfiguration\nfunc DropDisabledMutatingWebhookConfigurationFields(mutatingWebhookConfiguration, oldMutatingWebhookConfiguration *MutatingWebhookConfiguration) {\n\tif !utilfeature.DefaultFeatureGate.Enabled(genericfeatures.AdmissionWebhookMatchConditions) \u0026\u0026 !matchConditionsInUseMutatingWebhook(oldMutatingWebhookConfiguration) {\n\t\tfor i := range mutatingWebhookConfiguration.Webhooks {\n\t\t\tmutatingWebhookConfiguration.Webhooks[i].MatchConditions = nil\n\t\t}\n\t}\n}","line":{"from":24,"to":32}} {"id":100001816,"name":"matchConditionsInUseMutatingWebhook","signature":"func matchConditionsInUseMutatingWebhook(mutatingWebhookConfiguration *MutatingWebhookConfiguration) bool","file":"pkg/apis/admissionregistration/util.go","code":"func matchConditionsInUseMutatingWebhook(mutatingWebhookConfiguration *MutatingWebhookConfiguration) bool {\n\tif mutatingWebhookConfiguration == nil {\n\t\treturn false\n\t}\n\tfor _, webhook := range mutatingWebhookConfiguration.Webhooks {\n\t\tif len(webhook.MatchConditions) != 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":34,"to":44}} {"id":100001817,"name":"DropDisabledValidatingWebhookConfigurationFields","signature":"func DropDisabledValidatingWebhookConfigurationFields(validatingWebhookConfiguration, oldValidatingWebhookConfiguration *ValidatingWebhookConfiguration)","file":"pkg/apis/admissionregistration/util.go","code":"// DropDisabledValidatingWebhookConfigurationFields removes disabled fields from the validatingWebhookConfiguration metadata and spec.\n// This should be called from PrepareForCreate/PrepareForUpdate for all resources containing a validatingWebhookConfiguration\nfunc DropDisabledValidatingWebhookConfigurationFields(validatingWebhookConfiguration, oldValidatingWebhookConfiguration *ValidatingWebhookConfiguration) {\n\tif !utilfeature.DefaultFeatureGate.Enabled(genericfeatures.AdmissionWebhookMatchConditions) \u0026\u0026 !matchConditionsInUseValidatingWebhook(oldValidatingWebhookConfiguration) {\n\t\tfor i := range validatingWebhookConfiguration.Webhooks {\n\t\t\tvalidatingWebhookConfiguration.Webhooks[i].MatchConditions = nil\n\t\t}\n\t}\n}","line":{"from":46,"to":54}} {"id":100001818,"name":"matchConditionsInUseValidatingWebhook","signature":"func matchConditionsInUseValidatingWebhook(validatingWebhookConfiguration *ValidatingWebhookConfiguration) bool","file":"pkg/apis/admissionregistration/util.go","code":"func matchConditionsInUseValidatingWebhook(validatingWebhookConfiguration *ValidatingWebhookConfiguration) bool {\n\tif validatingWebhookConfiguration == nil {\n\t\treturn false\n\t}\n\tfor _, webhook := range validatingWebhookConfiguration.Webhooks {\n\t\tif len(webhook.MatchConditions) != 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":56,"to":66}} {"id":100001819,"name":"Convert_admissionregistration_Rule_To_v1_Rule","signature":"func Convert_admissionregistration_Rule_To_v1_Rule(in *admissionregistration.Rule, out *v1.Rule, s conversion.Scope) error","file":"pkg/apis/admissionregistration/v1/conversion.go","code":"// Convert_admissionregistration_Rule_To_v1_Rule is an autogenerated conversion function.\nfunc Convert_admissionregistration_Rule_To_v1_Rule(in *admissionregistration.Rule, out *v1.Rule, s conversion.Scope) error {\n\treturn autoConvert_admissionregistration_Rule_To_v1_Rule(in, out, s)\n}","line":{"from":25,"to":28}} {"id":100001820,"name":"Convert_v1_Rule_To_admissionregistration_Rule","signature":"func Convert_v1_Rule_To_admissionregistration_Rule(in *v1.Rule, out *admissionregistration.Rule, s conversion.Scope) error","file":"pkg/apis/admissionregistration/v1/conversion.go","code":"// Convert_v1_Rule_To_admissionregistration_Rule is an autogenerated conversion function.\nfunc Convert_v1_Rule_To_admissionregistration_Rule(in *v1.Rule, out *admissionregistration.Rule, s conversion.Scope) error {\n\treturn autoConvert_v1_Rule_To_admissionregistration_Rule(in, out, s)\n}","line":{"from":30,"to":33}} {"id":100001821,"name":"Convert_admissionregistration_RuleWithOperations_To_v1_RuleWithOperations","signature":"func Convert_admissionregistration_RuleWithOperations_To_v1_RuleWithOperations(in *admissionregistration.RuleWithOperations, out *v1.RuleWithOperations, s conversion.Scope) error","file":"pkg/apis/admissionregistration/v1/conversion.go","code":"// Convert_admissionregistration_RuleWithOperations_To_v1_RuleWithOperations is an autogenerated conversion function.\nfunc Convert_admissionregistration_RuleWithOperations_To_v1_RuleWithOperations(in *admissionregistration.RuleWithOperations, out *v1.RuleWithOperations, s conversion.Scope) error {\n\treturn autoConvert_admissionregistration_RuleWithOperations_To_v1_RuleWithOperations(in, out, s)\n}","line":{"from":35,"to":38}} {"id":100001822,"name":"Convert_v1_RuleWithOperations_To_admissionregistration_RuleWithOperations","signature":"func Convert_v1_RuleWithOperations_To_admissionregistration_RuleWithOperations(in *v1.RuleWithOperations, out *admissionregistration.RuleWithOperations, s conversion.Scope) error","file":"pkg/apis/admissionregistration/v1/conversion.go","code":"// Convert_v1_RuleWithOperations_To_admissionregistration_RuleWithOperations is an autogenerated conversion function.\nfunc Convert_v1_RuleWithOperations_To_admissionregistration_RuleWithOperations(in *v1.RuleWithOperations, out *admissionregistration.RuleWithOperations, s conversion.Scope) error {\n\treturn autoConvert_v1_RuleWithOperations_To_admissionregistration_RuleWithOperations(in, out, s)\n}","line":{"from":40,"to":43}} {"id":100001823,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/admissionregistration/v1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":26,"to":28}} {"id":100001824,"name":"SetDefaults_ValidatingWebhook","signature":"func SetDefaults_ValidatingWebhook(obj *admissionregistrationv1.ValidatingWebhook)","file":"pkg/apis/admissionregistration/v1/defaults.go","code":"// SetDefaults_ValidatingWebhook sets defaults for webhook validating\nfunc SetDefaults_ValidatingWebhook(obj *admissionregistrationv1.ValidatingWebhook) {\n\tif obj.FailurePolicy == nil {\n\t\tpolicy := admissionregistrationv1.Fail\n\t\tobj.FailurePolicy = \u0026policy\n\t}\n\tif obj.MatchPolicy == nil {\n\t\tpolicy := admissionregistrationv1.Equivalent\n\t\tobj.MatchPolicy = \u0026policy\n\t}\n\tif obj.NamespaceSelector == nil {\n\t\tselector := metav1.LabelSelector{}\n\t\tobj.NamespaceSelector = \u0026selector\n\t}\n\tif obj.ObjectSelector == nil {\n\t\tselector := metav1.LabelSelector{}\n\t\tobj.ObjectSelector = \u0026selector\n\t}\n\tif obj.TimeoutSeconds == nil {\n\t\tobj.TimeoutSeconds = new(int32)\n\t\t*obj.TimeoutSeconds = 10\n\t}\n}","line":{"from":30,"to":52}} {"id":100001825,"name":"SetDefaults_MutatingWebhook","signature":"func SetDefaults_MutatingWebhook(obj *admissionregistrationv1.MutatingWebhook)","file":"pkg/apis/admissionregistration/v1/defaults.go","code":"// SetDefaults_MutatingWebhook sets defaults for webhook mutating\nfunc SetDefaults_MutatingWebhook(obj *admissionregistrationv1.MutatingWebhook) {\n\tif obj.FailurePolicy == nil {\n\t\tpolicy := admissionregistrationv1.Fail\n\t\tobj.FailurePolicy = \u0026policy\n\t}\n\tif obj.MatchPolicy == nil {\n\t\tpolicy := admissionregistrationv1.Equivalent\n\t\tobj.MatchPolicy = \u0026policy\n\t}\n\tif obj.NamespaceSelector == nil {\n\t\tselector := metav1.LabelSelector{}\n\t\tobj.NamespaceSelector = \u0026selector\n\t}\n\tif obj.ObjectSelector == nil {\n\t\tselector := metav1.LabelSelector{}\n\t\tobj.ObjectSelector = \u0026selector\n\t}\n\tif obj.TimeoutSeconds == nil {\n\t\tobj.TimeoutSeconds = new(int32)\n\t\t*obj.TimeoutSeconds = 10\n\t}\n\tif obj.ReinvocationPolicy == nil {\n\t\tnever := admissionregistrationv1.NeverReinvocationPolicy\n\t\tobj.ReinvocationPolicy = \u0026never\n\t}\n}","line":{"from":54,"to":80}} {"id":100001826,"name":"SetDefaults_Rule","signature":"func SetDefaults_Rule(obj *admissionregistrationv1.Rule)","file":"pkg/apis/admissionregistration/v1/defaults.go","code":"// SetDefaults_Rule sets defaults for webhook rule\nfunc SetDefaults_Rule(obj *admissionregistrationv1.Rule) {\n\tif obj.Scope == nil {\n\t\ts := admissionregistrationv1.AllScopes\n\t\tobj.Scope = \u0026s\n\t}\n}","line":{"from":82,"to":88}} {"id":100001827,"name":"SetDefaults_ServiceReference","signature":"func SetDefaults_ServiceReference(obj *admissionregistrationv1.ServiceReference)","file":"pkg/apis/admissionregistration/v1/defaults.go","code":"// SetDefaults_ServiceReference sets defaults for Webhook's ServiceReference\nfunc SetDefaults_ServiceReference(obj *admissionregistrationv1.ServiceReference) {\n\tif obj.Port == nil {\n\t\tobj.Port = utilpointer.Int32(443)\n\t}\n}","line":{"from":90,"to":95}} {"id":100001828,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/admissionregistration/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100001829,"name":"init","signature":"func init()","file":"pkg/apis/admissionregistration/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":41,"to":46}} {"id":100001830,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/admissionregistration/v1alpha1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":25,"to":27}} {"id":100001831,"name":"SetDefaults_ValidatingAdmissionPolicySpec","signature":"func SetDefaults_ValidatingAdmissionPolicySpec(obj *admissionregistrationv1alpha1.ValidatingAdmissionPolicySpec)","file":"pkg/apis/admissionregistration/v1alpha1/defaults.go","code":"// SetDefaults_ValidatingAdmissionPolicySpec sets defaults for ValidatingAdmissionPolicySpec\nfunc SetDefaults_ValidatingAdmissionPolicySpec(obj *admissionregistrationv1alpha1.ValidatingAdmissionPolicySpec) {\n\tif obj.FailurePolicy == nil {\n\t\tpolicy := admissionregistrationv1alpha1.Fail\n\t\tobj.FailurePolicy = \u0026policy\n\t}\n}","line":{"from":29,"to":35}} {"id":100001832,"name":"SetDefaults_MatchResources","signature":"func SetDefaults_MatchResources(obj *admissionregistrationv1alpha1.MatchResources)","file":"pkg/apis/admissionregistration/v1alpha1/defaults.go","code":"// SetDefaults_MatchResources sets defaults for MatchResources\nfunc SetDefaults_MatchResources(obj *admissionregistrationv1alpha1.MatchResources) {\n\tif obj.MatchPolicy == nil {\n\t\tpolicy := admissionregistrationv1alpha1.Equivalent\n\t\tobj.MatchPolicy = \u0026policy\n\t}\n\tif obj.NamespaceSelector == nil {\n\t\tselector := metav1.LabelSelector{}\n\t\tobj.NamespaceSelector = \u0026selector\n\t}\n\tif obj.ObjectSelector == nil {\n\t\tselector := metav1.LabelSelector{}\n\t\tobj.ObjectSelector = \u0026selector\n\t}\n}","line":{"from":37,"to":51}} {"id":100001833,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/admissionregistration/v1alpha1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100001834,"name":"init","signature":"func init()","file":"pkg/apis/admissionregistration/v1alpha1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":41,"to":46}} {"id":100001835,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/admissionregistration/v1beta1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":26,"to":28}} {"id":100001836,"name":"SetDefaults_ValidatingWebhook","signature":"func SetDefaults_ValidatingWebhook(obj *admissionregistrationv1beta1.ValidatingWebhook)","file":"pkg/apis/admissionregistration/v1beta1/defaults.go","code":"// SetDefaults_ValidatingWebhook sets defaults for webhook validating\nfunc SetDefaults_ValidatingWebhook(obj *admissionregistrationv1beta1.ValidatingWebhook) {\n\tif obj.FailurePolicy == nil {\n\t\tpolicy := admissionregistrationv1beta1.Ignore\n\t\tobj.FailurePolicy = \u0026policy\n\t}\n\tif obj.MatchPolicy == nil {\n\t\tpolicy := admissionregistrationv1beta1.Exact\n\t\tobj.MatchPolicy = \u0026policy\n\t}\n\tif obj.NamespaceSelector == nil {\n\t\tselector := metav1.LabelSelector{}\n\t\tobj.NamespaceSelector = \u0026selector\n\t}\n\tif obj.ObjectSelector == nil {\n\t\tselector := metav1.LabelSelector{}\n\t\tobj.ObjectSelector = \u0026selector\n\t}\n\tif obj.SideEffects == nil {\n\t\t// TODO: revisit/remove this default and possibly make the field required when promoting to v1\n\t\tunknown := admissionregistrationv1beta1.SideEffectClassUnknown\n\t\tobj.SideEffects = \u0026unknown\n\t}\n\tif obj.TimeoutSeconds == nil {\n\t\tobj.TimeoutSeconds = new(int32)\n\t\t*obj.TimeoutSeconds = 30\n\t}\n\n\tif len(obj.AdmissionReviewVersions) == 0 {\n\t\tobj.AdmissionReviewVersions = []string{admissionregistrationv1beta1.SchemeGroupVersion.Version}\n\t}\n}","line":{"from":30,"to":61}} {"id":100001837,"name":"SetDefaults_MutatingWebhook","signature":"func SetDefaults_MutatingWebhook(obj *admissionregistrationv1beta1.MutatingWebhook)","file":"pkg/apis/admissionregistration/v1beta1/defaults.go","code":"// SetDefaults_MutatingWebhook sets defaults for webhook mutating\nfunc SetDefaults_MutatingWebhook(obj *admissionregistrationv1beta1.MutatingWebhook) {\n\tif obj.FailurePolicy == nil {\n\t\tpolicy := admissionregistrationv1beta1.Ignore\n\t\tobj.FailurePolicy = \u0026policy\n\t}\n\tif obj.MatchPolicy == nil {\n\t\tpolicy := admissionregistrationv1beta1.Exact\n\t\tobj.MatchPolicy = \u0026policy\n\t}\n\tif obj.NamespaceSelector == nil {\n\t\tselector := metav1.LabelSelector{}\n\t\tobj.NamespaceSelector = \u0026selector\n\t}\n\tif obj.ObjectSelector == nil {\n\t\tselector := metav1.LabelSelector{}\n\t\tobj.ObjectSelector = \u0026selector\n\t}\n\tif obj.SideEffects == nil {\n\t\t// TODO: revisit/remove this default and possibly make the field required when promoting to v1\n\t\tunknown := admissionregistrationv1beta1.SideEffectClassUnknown\n\t\tobj.SideEffects = \u0026unknown\n\t}\n\tif obj.TimeoutSeconds == nil {\n\t\tobj.TimeoutSeconds = new(int32)\n\t\t*obj.TimeoutSeconds = 30\n\t}\n\tif obj.ReinvocationPolicy == nil {\n\t\tnever := admissionregistrationv1beta1.NeverReinvocationPolicy\n\t\tobj.ReinvocationPolicy = \u0026never\n\t}\n\n\tif len(obj.AdmissionReviewVersions) == 0 {\n\t\tobj.AdmissionReviewVersions = []string{admissionregistrationv1beta1.SchemeGroupVersion.Version}\n\t}\n}","line":{"from":63,"to":98}} {"id":100001838,"name":"SetDefaults_ServiceReference","signature":"func SetDefaults_ServiceReference(obj *admissionregistrationv1beta1.ServiceReference)","file":"pkg/apis/admissionregistration/v1beta1/defaults.go","code":"// SetDefaults_ServiceReference sets defaults for Webhook's ServiceReference\nfunc SetDefaults_ServiceReference(obj *admissionregistrationv1beta1.ServiceReference) {\n\tif obj.Port == nil {\n\t\tobj.Port = utilpointer.Int32(443)\n\t}\n}","line":{"from":100,"to":105}} {"id":100001839,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/admissionregistration/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100001840,"name":"init","signature":"func init()","file":"pkg/apis/admissionregistration/v1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":41,"to":46}} {"id":100001841,"name":"hasWildcard","signature":"func hasWildcard(slice []string) bool","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func hasWildcard(slice []string) bool {\n\tfor _, s := range slice {\n\t\tif s == \"*\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":45,"to":52}} {"id":100001842,"name":"validateResources","signature":"func validateResources(resources []string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateResources(resources []string, fldPath *field.Path) field.ErrorList {\n\tvar allErrors field.ErrorList\n\tif len(resources) == 0 {\n\t\tallErrors = append(allErrors, field.Required(fldPath, \"\"))\n\t}\n\n\t// x/*\n\tresourcesWithWildcardSubresoures := sets.String{}\n\t// */x\n\tsubResourcesWithWildcardResource := sets.String{}\n\t// */*\n\thasDoubleWildcard := false\n\t// *\n\thasSingleWildcard := false\n\t// x\n\thasResourceWithoutSubresource := false\n\n\tfor i, resSub := range resources {\n\t\tif resSub == \"\" {\n\t\t\tallErrors = append(allErrors, field.Required(fldPath.Index(i), \"\"))\n\t\t\tcontinue\n\t\t}\n\t\tif resSub == \"*/*\" {\n\t\t\thasDoubleWildcard = true\n\t\t}\n\t\tif resSub == \"*\" {\n\t\t\thasSingleWildcard = true\n\t\t}\n\t\tparts := strings.SplitN(resSub, \"/\", 2)\n\t\tif len(parts) == 1 {\n\t\t\thasResourceWithoutSubresource = resSub != \"*\"\n\t\t\tcontinue\n\t\t}\n\t\tres, sub := parts[0], parts[1]\n\t\tif _, ok := resourcesWithWildcardSubresoures[res]; ok {\n\t\t\tallErrors = append(allErrors, field.Invalid(fldPath.Index(i), resSub, fmt.Sprintf(\"if '%s/*' is present, must not specify %s\", res, resSub)))\n\t\t}\n\t\tif _, ok := subResourcesWithWildcardResource[sub]; ok {\n\t\t\tallErrors = append(allErrors, field.Invalid(fldPath.Index(i), resSub, fmt.Sprintf(\"if '*/%s' is present, must not specify %s\", sub, resSub)))\n\t\t}\n\t\tif sub == \"*\" {\n\t\t\tresourcesWithWildcardSubresoures[res] = struct{}{}\n\t\t}\n\t\tif res == \"*\" {\n\t\t\tsubResourcesWithWildcardResource[sub] = struct{}{}\n\t\t}\n\t}\n\tif len(resources) \u003e 1 \u0026\u0026 hasDoubleWildcard {\n\t\tallErrors = append(allErrors, field.Invalid(fldPath, resources, \"if '*/*' is present, must not specify other resources\"))\n\t}\n\tif hasSingleWildcard \u0026\u0026 hasResourceWithoutSubresource {\n\t\tallErrors = append(allErrors, field.Invalid(fldPath, resources, \"if '*' is present, must not specify other resources without subresources\"))\n\t}\n\treturn allErrors\n}","line":{"from":54,"to":108}} {"id":100001843,"name":"validateResourcesNoSubResources","signature":"func validateResourcesNoSubResources(resources []string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateResourcesNoSubResources(resources []string, fldPath *field.Path) field.ErrorList {\n\tvar allErrors field.ErrorList\n\tif len(resources) == 0 {\n\t\tallErrors = append(allErrors, field.Required(fldPath, \"\"))\n\t}\n\tfor i, resource := range resources {\n\t\tif resource == \"\" {\n\t\t\tallErrors = append(allErrors, field.Required(fldPath.Index(i), \"\"))\n\t\t}\n\t\tif strings.Contains(resource, \"/\") {\n\t\t\tallErrors = append(allErrors, field.Invalid(fldPath.Index(i), resource, \"must not specify subresources\"))\n\t\t}\n\t}\n\tif len(resources) \u003e 1 \u0026\u0026 hasWildcard(resources) {\n\t\tallErrors = append(allErrors, field.Invalid(fldPath, resources, \"if '*' is present, must not specify other resources\"))\n\t}\n\treturn allErrors\n}","line":{"from":110,"to":127}} {"id":100001844,"name":"validateRule","signature":"func validateRule(rule *admissionregistration.Rule, fldPath *field.Path, allowSubResource bool) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateRule(rule *admissionregistration.Rule, fldPath *field.Path, allowSubResource bool) field.ErrorList {\n\tvar allErrors field.ErrorList\n\tif len(rule.APIGroups) == 0 {\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"apiGroups\"), \"\"))\n\t}\n\tif len(rule.APIGroups) \u003e 1 \u0026\u0026 hasWildcard(rule.APIGroups) {\n\t\tallErrors = append(allErrors, field.Invalid(fldPath.Child(\"apiGroups\"), rule.APIGroups, \"if '*' is present, must not specify other API groups\"))\n\t}\n\t// Note: group could be empty, e.g., the legacy \"v1\" API\n\tif len(rule.APIVersions) == 0 {\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"apiVersions\"), \"\"))\n\t}\n\tif len(rule.APIVersions) \u003e 1 \u0026\u0026 hasWildcard(rule.APIVersions) {\n\t\tallErrors = append(allErrors, field.Invalid(fldPath.Child(\"apiVersions\"), rule.APIVersions, \"if '*' is present, must not specify other API versions\"))\n\t}\n\tfor i, version := range rule.APIVersions {\n\t\tif version == \"\" {\n\t\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"apiVersions\").Index(i), \"\"))\n\t\t}\n\t}\n\tif allowSubResource {\n\t\tallErrors = append(allErrors, validateResources(rule.Resources, fldPath.Child(\"resources\"))...)\n\t} else {\n\t\tallErrors = append(allErrors, validateResourcesNoSubResources(rule.Resources, fldPath.Child(\"resources\"))...)\n\t}\n\tif rule.Scope != nil \u0026\u0026 !validScopes.Has(string(*rule.Scope)) {\n\t\tallErrors = append(allErrors, field.NotSupported(fldPath.Child(\"scope\"), *rule.Scope, validScopes.List()))\n\t}\n\treturn allErrors\n}","line":{"from":135,"to":164}} {"id":100001845,"name":"isAcceptedAdmissionReviewVersion","signature":"func isAcceptedAdmissionReviewVersion(v string) bool","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func isAcceptedAdmissionReviewVersion(v string) bool {\n\tfor _, version := range AcceptedAdmissionReviewVersions {\n\t\tif v == version {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":172,"to":179}} {"id":100001846,"name":"validateAdmissionReviewVersions","signature":"func validateAdmissionReviewVersions(versions []string, requireRecognizedAdmissionReviewVersion bool, fldPath *field.Path) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateAdmissionReviewVersions(versions []string, requireRecognizedAdmissionReviewVersion bool, fldPath *field.Path) field.ErrorList {\n\tallErrors := field.ErrorList{}\n\n\t// Currently only v1beta1 accepted in AdmissionReviewVersions\n\tif len(versions) \u003c 1 {\n\t\tallErrors = append(allErrors, field.Required(fldPath, fmt.Sprintf(\"must specify one of %v\", strings.Join(AcceptedAdmissionReviewVersions, \", \"))))\n\t} else {\n\t\tseen := map[string]bool{}\n\t\thasAcceptedVersion := false\n\t\tfor i, v := range versions {\n\t\t\tif seen[v] {\n\t\t\t\tallErrors = append(allErrors, field.Invalid(fldPath.Index(i), v, \"duplicate version\"))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tseen[v] = true\n\t\t\tfor _, errString := range utilvalidation.IsDNS1035Label(v) {\n\t\t\t\tallErrors = append(allErrors, field.Invalid(fldPath.Index(i), v, errString))\n\t\t\t}\n\t\t\tif isAcceptedAdmissionReviewVersion(v) {\n\t\t\t\thasAcceptedVersion = true\n\t\t\t}\n\t\t}\n\t\tif requireRecognizedAdmissionReviewVersion \u0026\u0026 !hasAcceptedVersion {\n\t\t\tallErrors = append(allErrors, field.Invalid(\n\t\t\t\tfldPath, versions,\n\t\t\t\tfmt.Sprintf(\"must include at least one of %v\",\n\t\t\t\t\tstrings.Join(AcceptedAdmissionReviewVersions, \", \"))))\n\t\t}\n\t}\n\treturn allErrors\n}","line":{"from":181,"to":211}} {"id":100001847,"name":"ValidateValidatingWebhookConfiguration","signature":"func ValidateValidatingWebhookConfiguration(e *admissionregistration.ValidatingWebhookConfiguration) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"// ValidateValidatingWebhookConfiguration validates a webhook before creation.\nfunc ValidateValidatingWebhookConfiguration(e *admissionregistration.ValidatingWebhookConfiguration) field.ErrorList {\n\treturn validateValidatingWebhookConfiguration(e, validationOptions{\n\t\tignoreMatchConditions: false,\n\t\tallowParamsInMatchConditions: false,\n\t\trequireNoSideEffects: true,\n\t\trequireRecognizedAdmissionReviewVersion: true,\n\t\trequireUniqueWebhookNames: true,\n\t\tallowInvalidLabelValueInSelector: false,\n\t})\n}","line":{"from":213,"to":223}} {"id":100001848,"name":"validateValidatingWebhookConfiguration","signature":"func validateValidatingWebhookConfiguration(e *admissionregistration.ValidatingWebhookConfiguration, opts validationOptions) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateValidatingWebhookConfiguration(e *admissionregistration.ValidatingWebhookConfiguration, opts validationOptions) field.ErrorList {\n\tallErrors := genericvalidation.ValidateObjectMeta(\u0026e.ObjectMeta, false, genericvalidation.NameIsDNSSubdomain, field.NewPath(\"metadata\"))\n\thookNames := sets.NewString()\n\tfor i, hook := range e.Webhooks {\n\t\tallErrors = append(allErrors, validateValidatingWebhook(\u0026hook, opts, field.NewPath(\"webhooks\").Index(i))...)\n\t\tallErrors = append(allErrors, validateAdmissionReviewVersions(hook.AdmissionReviewVersions, opts.requireRecognizedAdmissionReviewVersion, field.NewPath(\"webhooks\").Index(i).Child(\"admissionReviewVersions\"))...)\n\t\tif opts.requireUniqueWebhookNames \u0026\u0026 len(hook.Name) \u003e 0 {\n\t\t\tif hookNames.Has(hook.Name) {\n\t\t\t\tallErrors = append(allErrors, field.Duplicate(field.NewPath(\"webhooks\").Index(i).Child(\"name\"), hook.Name))\n\t\t\t} else {\n\t\t\t\thookNames.Insert(hook.Name)\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrors\n}","line":{"from":225,"to":240}} {"id":100001849,"name":"ValidateMutatingWebhookConfiguration","signature":"func ValidateMutatingWebhookConfiguration(e *admissionregistration.MutatingWebhookConfiguration) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"// ValidateMutatingWebhookConfiguration validates a webhook before creation.\nfunc ValidateMutatingWebhookConfiguration(e *admissionregistration.MutatingWebhookConfiguration) field.ErrorList {\n\treturn validateMutatingWebhookConfiguration(e, validationOptions{\n\t\tignoreMatchConditions: false,\n\t\tallowParamsInMatchConditions: false,\n\t\trequireNoSideEffects: true,\n\t\trequireRecognizedAdmissionReviewVersion: true,\n\t\trequireUniqueWebhookNames: true,\n\t\tallowInvalidLabelValueInSelector: false,\n\t})\n}","line":{"from":242,"to":252}} {"id":100001850,"name":"validateMutatingWebhookConfiguration","signature":"func validateMutatingWebhookConfiguration(e *admissionregistration.MutatingWebhookConfiguration, opts validationOptions) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateMutatingWebhookConfiguration(e *admissionregistration.MutatingWebhookConfiguration, opts validationOptions) field.ErrorList {\n\tallErrors := genericvalidation.ValidateObjectMeta(\u0026e.ObjectMeta, false, genericvalidation.NameIsDNSSubdomain, field.NewPath(\"metadata\"))\n\n\thookNames := sets.NewString()\n\tfor i, hook := range e.Webhooks {\n\t\tallErrors = append(allErrors, validateMutatingWebhook(\u0026hook, opts, field.NewPath(\"webhooks\").Index(i))...)\n\t\tallErrors = append(allErrors, validateAdmissionReviewVersions(hook.AdmissionReviewVersions, opts.requireRecognizedAdmissionReviewVersion, field.NewPath(\"webhooks\").Index(i).Child(\"admissionReviewVersions\"))...)\n\t\tif opts.requireUniqueWebhookNames \u0026\u0026 len(hook.Name) \u003e 0 {\n\t\t\tif hookNames.Has(hook.Name) {\n\t\t\t\tallErrors = append(allErrors, field.Duplicate(field.NewPath(\"webhooks\").Index(i).Child(\"name\"), hook.Name))\n\t\t\t} else {\n\t\t\t\thookNames.Insert(hook.Name)\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrors\n}","line":{"from":263,"to":279}} {"id":100001851,"name":"validateValidatingWebhook","signature":"func validateValidatingWebhook(hook *admissionregistration.ValidatingWebhook, opts validationOptions, fldPath *field.Path) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateValidatingWebhook(hook *admissionregistration.ValidatingWebhook, opts validationOptions, fldPath *field.Path) field.ErrorList {\n\tvar allErrors field.ErrorList\n\t// hook.Name must be fully qualified\n\tallErrors = append(allErrors, utilvalidation.IsFullyQualifiedName(fldPath.Child(\"name\"), hook.Name)...)\n\tlabelSelectorValidationOpts := metav1validation.LabelSelectorValidationOptions{\n\t\tAllowInvalidLabelValueInSelector: opts.allowInvalidLabelValueInSelector,\n\t}\n\n\tfor i, rule := range hook.Rules {\n\t\tallErrors = append(allErrors, validateRuleWithOperations(\u0026rule, fldPath.Child(\"rules\").Index(i))...)\n\t}\n\tif hook.FailurePolicy != nil \u0026\u0026 !supportedFailurePolicies.Has(string(*hook.FailurePolicy)) {\n\t\tallErrors = append(allErrors, field.NotSupported(fldPath.Child(\"failurePolicy\"), *hook.FailurePolicy, supportedFailurePolicies.List()))\n\t}\n\tif hook.MatchPolicy != nil \u0026\u0026 !supportedMatchPolicies.Has(string(*hook.MatchPolicy)) {\n\t\tallErrors = append(allErrors, field.NotSupported(fldPath.Child(\"matchPolicy\"), *hook.MatchPolicy, supportedMatchPolicies.List()))\n\t}\n\tallowedSideEffects := supportedSideEffectClasses\n\tif opts.requireNoSideEffects {\n\t\tallowedSideEffects = noSideEffectClasses\n\t}\n\tif hook.SideEffects == nil {\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"sideEffects\"), fmt.Sprintf(\"must specify one of %v\", strings.Join(allowedSideEffects.List(), \", \"))))\n\t}\n\tif hook.SideEffects != nil \u0026\u0026 !allowedSideEffects.Has(string(*hook.SideEffects)) {\n\t\tallErrors = append(allErrors, field.NotSupported(fldPath.Child(\"sideEffects\"), *hook.SideEffects, allowedSideEffects.List()))\n\t}\n\tif hook.TimeoutSeconds != nil \u0026\u0026 (*hook.TimeoutSeconds \u003e 30 || *hook.TimeoutSeconds \u003c 1) {\n\t\tallErrors = append(allErrors, field.Invalid(fldPath.Child(\"timeoutSeconds\"), *hook.TimeoutSeconds, \"the timeout value must be between 1 and 30 seconds\"))\n\t}\n\n\tif hook.NamespaceSelector != nil {\n\t\tallErrors = append(allErrors, metav1validation.ValidateLabelSelector(hook.NamespaceSelector, labelSelectorValidationOpts, fldPath.Child(\"namespaceSelector\"))...)\n\t}\n\n\tif hook.ObjectSelector != nil {\n\t\tallErrors = append(allErrors, metav1validation.ValidateLabelSelector(hook.ObjectSelector, labelSelectorValidationOpts, fldPath.Child(\"objectSelector\"))...)\n\t}\n\n\tcc := hook.ClientConfig\n\tswitch {\n\tcase (cc.URL == nil) == (cc.Service == nil):\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"clientConfig\"), \"exactly one of url or service is required\"))\n\tcase cc.URL != nil:\n\t\tallErrors = append(allErrors, webhook.ValidateWebhookURL(fldPath.Child(\"clientConfig\").Child(\"url\"), *cc.URL, true)...)\n\tcase cc.Service != nil:\n\t\tallErrors = append(allErrors, webhook.ValidateWebhookService(fldPath.Child(\"clientConfig\").Child(\"service\"), cc.Service.Name, cc.Service.Namespace, cc.Service.Path, cc.Service.Port)...)\n\t}\n\n\tif !opts.ignoreMatchConditions {\n\t\tallErrors = append(allErrors, validateMatchConditions(hook.MatchConditions, opts, fldPath.Child(\"matchConditions\"))...)\n\t}\n\n\treturn allErrors\n}","line":{"from":281,"to":335}} {"id":100001852,"name":"validateMutatingWebhook","signature":"func validateMutatingWebhook(hook *admissionregistration.MutatingWebhook, opts validationOptions, fldPath *field.Path) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateMutatingWebhook(hook *admissionregistration.MutatingWebhook, opts validationOptions, fldPath *field.Path) field.ErrorList {\n\tvar allErrors field.ErrorList\n\t// hook.Name must be fully qualified\n\tallErrors = append(allErrors, utilvalidation.IsFullyQualifiedName(fldPath.Child(\"name\"), hook.Name)...)\n\tlabelSelectorValidationOpts := metav1validation.LabelSelectorValidationOptions{\n\t\tAllowInvalidLabelValueInSelector: opts.allowInvalidLabelValueInSelector,\n\t}\n\n\tfor i, rule := range hook.Rules {\n\t\tallErrors = append(allErrors, validateRuleWithOperations(\u0026rule, fldPath.Child(\"rules\").Index(i))...)\n\t}\n\tif hook.FailurePolicy != nil \u0026\u0026 !supportedFailurePolicies.Has(string(*hook.FailurePolicy)) {\n\t\tallErrors = append(allErrors, field.NotSupported(fldPath.Child(\"failurePolicy\"), *hook.FailurePolicy, supportedFailurePolicies.List()))\n\t}\n\tif hook.MatchPolicy != nil \u0026\u0026 !supportedMatchPolicies.Has(string(*hook.MatchPolicy)) {\n\t\tallErrors = append(allErrors, field.NotSupported(fldPath.Child(\"matchPolicy\"), *hook.MatchPolicy, supportedMatchPolicies.List()))\n\t}\n\tallowedSideEffects := supportedSideEffectClasses\n\tif opts.requireNoSideEffects {\n\t\tallowedSideEffects = noSideEffectClasses\n\t}\n\tif hook.SideEffects == nil {\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"sideEffects\"), fmt.Sprintf(\"must specify one of %v\", strings.Join(allowedSideEffects.List(), \", \"))))\n\t}\n\tif hook.SideEffects != nil \u0026\u0026 !allowedSideEffects.Has(string(*hook.SideEffects)) {\n\t\tallErrors = append(allErrors, field.NotSupported(fldPath.Child(\"sideEffects\"), *hook.SideEffects, allowedSideEffects.List()))\n\t}\n\tif hook.TimeoutSeconds != nil \u0026\u0026 (*hook.TimeoutSeconds \u003e 30 || *hook.TimeoutSeconds \u003c 1) {\n\t\tallErrors = append(allErrors, field.Invalid(fldPath.Child(\"timeoutSeconds\"), *hook.TimeoutSeconds, \"the timeout value must be between 1 and 30 seconds\"))\n\t}\n\n\tif hook.NamespaceSelector != nil {\n\t\tallErrors = append(allErrors, metav1validation.ValidateLabelSelector(hook.NamespaceSelector, labelSelectorValidationOpts, fldPath.Child(\"namespaceSelector\"))...)\n\t}\n\tif hook.ObjectSelector != nil {\n\t\tallErrors = append(allErrors, metav1validation.ValidateLabelSelector(hook.ObjectSelector, labelSelectorValidationOpts, fldPath.Child(\"objectSelector\"))...)\n\t}\n\tif hook.ReinvocationPolicy != nil \u0026\u0026 !supportedReinvocationPolicies.Has(string(*hook.ReinvocationPolicy)) {\n\t\tallErrors = append(allErrors, field.NotSupported(fldPath.Child(\"reinvocationPolicy\"), *hook.ReinvocationPolicy, supportedReinvocationPolicies.List()))\n\t}\n\n\tcc := hook.ClientConfig\n\tswitch {\n\tcase (cc.URL == nil) == (cc.Service == nil):\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"clientConfig\"), \"exactly one of url or service is required\"))\n\tcase cc.URL != nil:\n\t\tallErrors = append(allErrors, webhook.ValidateWebhookURL(fldPath.Child(\"clientConfig\").Child(\"url\"), *cc.URL, true)...)\n\tcase cc.Service != nil:\n\t\tallErrors = append(allErrors, webhook.ValidateWebhookService(fldPath.Child(\"clientConfig\").Child(\"service\"), cc.Service.Name, cc.Service.Namespace, cc.Service.Path, cc.Service.Port)...)\n\t}\n\n\tif !opts.ignoreMatchConditions {\n\t\tallErrors = append(allErrors, validateMatchConditions(hook.MatchConditions, opts, fldPath.Child(\"matchConditions\"))...)\n\t}\n\n\treturn allErrors\n}","line":{"from":337,"to":393}} {"id":100001853,"name":"hasWildcardOperation","signature":"func hasWildcardOperation(operations []admissionregistration.OperationType) bool","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func hasWildcardOperation(operations []admissionregistration.OperationType) bool {\n\tfor _, o := range operations {\n\t\tif o == admissionregistration.OperationAll {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":436,"to":443}} {"id":100001854,"name":"validateRuleWithOperations","signature":"func validateRuleWithOperations(ruleWithOperations *admissionregistration.RuleWithOperations, fldPath *field.Path) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateRuleWithOperations(ruleWithOperations *admissionregistration.RuleWithOperations, fldPath *field.Path) field.ErrorList {\n\tvar allErrors field.ErrorList\n\tif len(ruleWithOperations.Operations) == 0 {\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"operations\"), \"\"))\n\t}\n\tif len(ruleWithOperations.Operations) \u003e 1 \u0026\u0026 hasWildcardOperation(ruleWithOperations.Operations) {\n\t\tallErrors = append(allErrors, field.Invalid(fldPath.Child(\"operations\"), ruleWithOperations.Operations, \"if '*' is present, must not specify other operations\"))\n\t}\n\tfor i, operation := range ruleWithOperations.Operations {\n\t\tif !supportedOperations.Has(string(operation)) {\n\t\t\tallErrors = append(allErrors, field.NotSupported(fldPath.Child(\"operations\").Index(i), operation, supportedOperations.List()))\n\t\t}\n\t}\n\tallowSubResource := true\n\tallErrors = append(allErrors, validateRule(\u0026ruleWithOperations.Rule, fldPath, allowSubResource)...)\n\treturn allErrors\n}","line":{"from":445,"to":461}} {"id":100001855,"name":"mutatingHasAcceptedAdmissionReviewVersions","signature":"func mutatingHasAcceptedAdmissionReviewVersions(webhooks []admissionregistration.MutatingWebhook) bool","file":"pkg/apis/admissionregistration/validation/validation.go","code":"// mutatingHasAcceptedAdmissionReviewVersions returns true if all webhooks have at least one\n// admission review version this apiserver accepts.\nfunc mutatingHasAcceptedAdmissionReviewVersions(webhooks []admissionregistration.MutatingWebhook) bool {\n\tfor _, hook := range webhooks {\n\t\thasRecognizedVersion := false\n\t\tfor _, version := range hook.AdmissionReviewVersions {\n\t\t\tif isAcceptedAdmissionReviewVersion(version) {\n\t\t\t\thasRecognizedVersion = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !hasRecognizedVersion \u0026\u0026 len(hook.AdmissionReviewVersions) \u003e 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":463,"to":479}} {"id":100001856,"name":"validatingHasAcceptedAdmissionReviewVersions","signature":"func validatingHasAcceptedAdmissionReviewVersions(webhooks []admissionregistration.ValidatingWebhook) bool","file":"pkg/apis/admissionregistration/validation/validation.go","code":"// validatingHasAcceptedAdmissionReviewVersions returns true if all webhooks have at least one\n// admission review version this apiserver accepts.\nfunc validatingHasAcceptedAdmissionReviewVersions(webhooks []admissionregistration.ValidatingWebhook) bool {\n\tfor _, hook := range webhooks {\n\t\thasRecognizedVersion := false\n\t\tfor _, version := range hook.AdmissionReviewVersions {\n\t\t\tif isAcceptedAdmissionReviewVersion(version) {\n\t\t\t\thasRecognizedVersion = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !hasRecognizedVersion \u0026\u0026 len(hook.AdmissionReviewVersions) \u003e 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":481,"to":497}} {"id":100001857,"name":"ignoreMutatingWebhookMatchConditions","signature":"func ignoreMutatingWebhookMatchConditions(new, old []admissionregistration.MutatingWebhook) bool","file":"pkg/apis/admissionregistration/validation/validation.go","code":"// ignoreMatchConditions returns false if any change to match conditions\nfunc ignoreMutatingWebhookMatchConditions(new, old []admissionregistration.MutatingWebhook) bool {\n\tif len(new) != len(old) {\n\t\treturn false\n\t}\n\tfor i := range old {\n\t\tif !reflect.DeepEqual(new[i].MatchConditions, old[i].MatchConditions) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}","line":{"from":499,"to":511}} {"id":100001858,"name":"ignoreValidatingWebhookMatchConditions","signature":"func ignoreValidatingWebhookMatchConditions(new, old []admissionregistration.ValidatingWebhook) bool","file":"pkg/apis/admissionregistration/validation/validation.go","code":"// ignoreMatchConditions returns true if any new expressions are added\nfunc ignoreValidatingWebhookMatchConditions(new, old []admissionregistration.ValidatingWebhook) bool {\n\tif len(new) != len(old) {\n\t\treturn false\n\t}\n\tfor i := range old {\n\t\tif !reflect.DeepEqual(new[i].MatchConditions, old[i].MatchConditions) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}","line":{"from":513,"to":525}} {"id":100001859,"name":"ignoreValidatingAdmissionPolicyMatchConditions","signature":"func ignoreValidatingAdmissionPolicyMatchConditions(new, old *admissionregistration.ValidatingAdmissionPolicy) bool","file":"pkg/apis/admissionregistration/validation/validation.go","code":"// ignoreValidatingAdmissionPolicyMatchConditions returns true if there have been no updates that could invalidate previously-valid match conditions\nfunc ignoreValidatingAdmissionPolicyMatchConditions(new, old *admissionregistration.ValidatingAdmissionPolicy) bool {\n\tif !reflect.DeepEqual(new.Spec.ParamKind, old.Spec.ParamKind) {\n\t\treturn false\n\t}\n\tif !reflect.DeepEqual(new.Spec.MatchConditions, old.Spec.MatchConditions) {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":527,"to":536}} {"id":100001860,"name":"mutatingHasUniqueWebhookNames","signature":"func mutatingHasUniqueWebhookNames(webhooks []admissionregistration.MutatingWebhook) bool","file":"pkg/apis/admissionregistration/validation/validation.go","code":"// mutatingHasUniqueWebhookNames returns true if all webhooks have unique names\nfunc mutatingHasUniqueWebhookNames(webhooks []admissionregistration.MutatingWebhook) bool {\n\tnames := sets.NewString()\n\tfor _, hook := range webhooks {\n\t\tif names.Has(hook.Name) {\n\t\t\treturn false\n\t\t}\n\t\tnames.Insert(hook.Name)\n\t}\n\treturn true\n}","line":{"from":538,"to":548}} {"id":100001861,"name":"validatingHasUniqueWebhookNames","signature":"func validatingHasUniqueWebhookNames(webhooks []admissionregistration.ValidatingWebhook) bool","file":"pkg/apis/admissionregistration/validation/validation.go","code":"// validatingHasUniqueWebhookNames returns true if all webhooks have unique names\nfunc validatingHasUniqueWebhookNames(webhooks []admissionregistration.ValidatingWebhook) bool {\n\tnames := sets.NewString()\n\tfor _, hook := range webhooks {\n\t\tif names.Has(hook.Name) {\n\t\t\treturn false\n\t\t}\n\t\tnames.Insert(hook.Name)\n\t}\n\treturn true\n}","line":{"from":550,"to":560}} {"id":100001862,"name":"mutatingHasNoSideEffects","signature":"func mutatingHasNoSideEffects(webhooks []admissionregistration.MutatingWebhook) bool","file":"pkg/apis/admissionregistration/validation/validation.go","code":"// mutatingHasNoSideEffects returns true if all webhooks have no side effects\nfunc mutatingHasNoSideEffects(webhooks []admissionregistration.MutatingWebhook) bool {\n\tfor _, hook := range webhooks {\n\t\tif hook.SideEffects == nil || !noSideEffectClasses.Has(string(*hook.SideEffects)) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":562,"to":570}} {"id":100001863,"name":"validatingHasNoSideEffects","signature":"func validatingHasNoSideEffects(webhooks []admissionregistration.ValidatingWebhook) bool","file":"pkg/apis/admissionregistration/validation/validation.go","code":"// validatingHasNoSideEffects returns true if all webhooks have no side effects\nfunc validatingHasNoSideEffects(webhooks []admissionregistration.ValidatingWebhook) bool {\n\tfor _, hook := range webhooks {\n\t\tif hook.SideEffects == nil || !noSideEffectClasses.Has(string(*hook.SideEffects)) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":572,"to":580}} {"id":100001864,"name":"validatingWebhookHasInvalidLabelValueInSelector","signature":"func validatingWebhookHasInvalidLabelValueInSelector(webhooks []admissionregistration.ValidatingWebhook) bool","file":"pkg/apis/admissionregistration/validation/validation.go","code":"// validatingWebhookAllowInvalidLabelValueInSelector returns true if all webhooksallow invalid label value in selector\nfunc validatingWebhookHasInvalidLabelValueInSelector(webhooks []admissionregistration.ValidatingWebhook) bool {\n\tlabelSelectorValidationOpts := metav1validation.LabelSelectorValidationOptions{\n\t\tAllowInvalidLabelValueInSelector: false,\n\t}\n\n\tfor _, hook := range webhooks {\n\t\tif hook.NamespaceSelector != nil {\n\t\t\tif len(metav1validation.ValidateLabelSelector(hook.NamespaceSelector, labelSelectorValidationOpts, nil)) \u003e 0 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\tif hook.ObjectSelector != nil {\n\t\t\tif len(metav1validation.ValidateLabelSelector(hook.ObjectSelector, labelSelectorValidationOpts, nil)) \u003e 0 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":582,"to":601}} {"id":100001865,"name":"mutatingWebhookHasInvalidLabelValueInSelector","signature":"func mutatingWebhookHasInvalidLabelValueInSelector(webhooks []admissionregistration.MutatingWebhook) bool","file":"pkg/apis/admissionregistration/validation/validation.go","code":"// mutatingWebhookAllowInvalidLabelValueInSelector returns true if all webhooks allow invalid label value in selector\nfunc mutatingWebhookHasInvalidLabelValueInSelector(webhooks []admissionregistration.MutatingWebhook) bool {\n\tlabelSelectorValidationOpts := metav1validation.LabelSelectorValidationOptions{\n\t\tAllowInvalidLabelValueInSelector: false,\n\t}\n\n\tfor _, hook := range webhooks {\n\t\tif hook.NamespaceSelector != nil {\n\t\t\tif len(metav1validation.ValidateLabelSelector(hook.NamespaceSelector, labelSelectorValidationOpts, nil)) \u003e 0 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\tif hook.ObjectSelector != nil {\n\t\t\tif len(metav1validation.ValidateLabelSelector(hook.ObjectSelector, labelSelectorValidationOpts, nil)) \u003e 0 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":603,"to":622}} {"id":100001866,"name":"ValidateValidatingWebhookConfigurationUpdate","signature":"func ValidateValidatingWebhookConfigurationUpdate(newC, oldC *admissionregistration.ValidatingWebhookConfiguration) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"// ValidateValidatingWebhookConfigurationUpdate validates update of validating webhook configuration\nfunc ValidateValidatingWebhookConfigurationUpdate(newC, oldC *admissionregistration.ValidatingWebhookConfiguration) field.ErrorList {\n\treturn validateValidatingWebhookConfiguration(newC, validationOptions{\n\t\tignoreMatchConditions: ignoreValidatingWebhookMatchConditions(newC.Webhooks, oldC.Webhooks),\n\t\tallowParamsInMatchConditions: false,\n\t\trequireNoSideEffects: validatingHasNoSideEffects(oldC.Webhooks),\n\t\trequireRecognizedAdmissionReviewVersion: validatingHasAcceptedAdmissionReviewVersions(oldC.Webhooks),\n\t\trequireUniqueWebhookNames: validatingHasUniqueWebhookNames(oldC.Webhooks),\n\t\tallowInvalidLabelValueInSelector: validatingWebhookHasInvalidLabelValueInSelector(oldC.Webhooks),\n\t})\n}","line":{"from":624,"to":634}} {"id":100001867,"name":"ValidateMutatingWebhookConfigurationUpdate","signature":"func ValidateMutatingWebhookConfigurationUpdate(newC, oldC *admissionregistration.MutatingWebhookConfiguration) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"// ValidateMutatingWebhookConfigurationUpdate validates update of mutating webhook configuration\nfunc ValidateMutatingWebhookConfigurationUpdate(newC, oldC *admissionregistration.MutatingWebhookConfiguration) field.ErrorList {\n\treturn validateMutatingWebhookConfiguration(newC, validationOptions{\n\t\tignoreMatchConditions: ignoreMutatingWebhookMatchConditions(newC.Webhooks, oldC.Webhooks),\n\t\tallowParamsInMatchConditions: false,\n\t\trequireNoSideEffects: mutatingHasNoSideEffects(oldC.Webhooks),\n\t\trequireRecognizedAdmissionReviewVersion: mutatingHasAcceptedAdmissionReviewVersions(oldC.Webhooks),\n\t\trequireUniqueWebhookNames: mutatingHasUniqueWebhookNames(oldC.Webhooks),\n\t\tallowInvalidLabelValueInSelector: mutatingWebhookHasInvalidLabelValueInSelector(oldC.Webhooks),\n\t})\n}","line":{"from":636,"to":646}} {"id":100001868,"name":"ValidateValidatingAdmissionPolicy","signature":"func ValidateValidatingAdmissionPolicy(p *admissionregistration.ValidatingAdmissionPolicy) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"// ValidateValidatingAdmissionPolicy validates a ValidatingAdmissionPolicy before creation.\nfunc ValidateValidatingAdmissionPolicy(p *admissionregistration.ValidatingAdmissionPolicy) field.ErrorList {\n\treturn validateValidatingAdmissionPolicy(p, validationOptions{ignoreMatchConditions: false})\n}","line":{"from":656,"to":659}} {"id":100001869,"name":"validateValidatingAdmissionPolicy","signature":"func validateValidatingAdmissionPolicy(p *admissionregistration.ValidatingAdmissionPolicy, opts validationOptions) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateValidatingAdmissionPolicy(p *admissionregistration.ValidatingAdmissionPolicy, opts validationOptions) field.ErrorList {\n\tallErrors := genericvalidation.ValidateObjectMeta(\u0026p.ObjectMeta, false, genericvalidation.NameIsDNSSubdomain, field.NewPath(\"metadata\"))\n\tallErrors = append(allErrors, validateValidatingAdmissionPolicySpec(p.ObjectMeta, \u0026p.Spec, opts, field.NewPath(\"spec\"))...)\n\treturn allErrors\n}","line":{"from":661,"to":665}} {"id":100001870,"name":"validateValidatingAdmissionPolicySpec","signature":"func validateValidatingAdmissionPolicySpec(meta metav1.ObjectMeta, spec *admissionregistration.ValidatingAdmissionPolicySpec, opts validationOptions, fldPath *field.Path) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateValidatingAdmissionPolicySpec(meta metav1.ObjectMeta, spec *admissionregistration.ValidatingAdmissionPolicySpec, opts validationOptions, fldPath *field.Path) field.ErrorList {\n\tvar allErrors field.ErrorList\n\tif spec.FailurePolicy == nil {\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"failurePolicy\"), \"\"))\n\t} else if !supportedFailurePolicies.Has(string(*spec.FailurePolicy)) {\n\t\tallErrors = append(allErrors, field.NotSupported(fldPath.Child(\"failurePolicy\"), *spec.FailurePolicy, supportedFailurePolicies.List()))\n\t}\n\tif spec.ParamKind != nil {\n\t\topts.allowParamsInMatchConditions = true\n\t\tallErrors = append(allErrors, validateParamKind(*spec.ParamKind, fldPath.Child(\"paramKind\"))...)\n\t}\n\tif spec.MatchConstraints == nil {\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"matchConstraints\"), \"\"))\n\t} else {\n\t\tallErrors = append(allErrors, validateMatchResources(spec.MatchConstraints, fldPath.Child(\"matchConstraints\"))...)\n\t\t// at least one resourceRule must be defined to provide type information\n\t\tif len(spec.MatchConstraints.ResourceRules) == 0 {\n\t\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"matchConstraints\", \"resourceRules\"), \"\"))\n\t\t}\n\t}\n\tif !opts.ignoreMatchConditions {\n\t\tallErrors = append(allErrors, validateMatchConditions(spec.MatchConditions, opts, fldPath.Child(\"matchConditions\"))...)\n\t}\n\tif len(spec.Validations) == 0 \u0026\u0026 len(spec.AuditAnnotations) == 0 {\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"validations\"), \"validations or auditAnnotations must contain at least one item\"))\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"auditAnnotations\"), \"validations or auditAnnotations must contain at least one item\"))\n\t} else {\n\t\tfor i, validation := range spec.Validations {\n\t\t\tallErrors = append(allErrors, validateValidation(\u0026validation, spec.ParamKind, fldPath.Child(\"validations\").Index(i))...)\n\t\t}\n\t\tif spec.AuditAnnotations != nil {\n\t\t\tkeys := sets.NewString()\n\t\t\tif len(spec.AuditAnnotations) \u003e maxAuditAnnotations {\n\t\t\t\tallErrors = append(allErrors, field.Invalid(fldPath.Child(\"auditAnnotations\"), spec.AuditAnnotations, fmt.Sprintf(\"must not have more than %d auditAnnotations\", maxAuditAnnotations)))\n\t\t\t}\n\t\t\tfor i, auditAnnotation := range spec.AuditAnnotations {\n\t\t\t\tallErrors = append(allErrors, validateAuditAnnotation(meta, \u0026auditAnnotation, spec.ParamKind, fldPath.Child(\"auditAnnotations\").Index(i))...)\n\t\t\t\tif keys.Has(auditAnnotation.Key) {\n\t\t\t\t\tallErrors = append(allErrors, field.Duplicate(fldPath.Child(\"auditAnnotations\").Index(i).Child(\"key\"), auditAnnotation.Key))\n\t\t\t\t}\n\t\t\t\tkeys.Insert(auditAnnotation.Key)\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrors\n}","line":{"from":667,"to":712}} {"id":100001871,"name":"validateParamKind","signature":"func validateParamKind(gvk admissionregistration.ParamKind, fldPath *field.Path) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateParamKind(gvk admissionregistration.ParamKind, fldPath *field.Path) field.ErrorList {\n\tvar allErrors field.ErrorList\n\tif len(gvk.APIVersion) == 0 {\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"apiVersion\"), \"\"))\n\t} else if gv, err := parseGroupVersion(gvk.APIVersion); err != nil {\n\t\tallErrors = append(allErrors, field.Invalid(fldPath.Child(\"apiVersion\"), gvk.APIVersion, err.Error()))\n\t} else {\n\t\t//this matches the APIService group field validation\n\t\tif len(gv.Group) \u003e 0 {\n\t\t\tif errs := utilvalidation.IsDNS1123Subdomain(gv.Group); len(errs) \u003e 0 {\n\t\t\t\tallErrors = append(allErrors, field.Invalid(fldPath.Child(\"apiVersion\"), gv.Group, strings.Join(errs, \",\")))\n\t\t\t}\n\t\t}\n\t\t//this matches the APIService version field validation\n\t\tif len(gv.Version) == 0 {\n\t\t\tallErrors = append(allErrors, field.Invalid(fldPath.Child(\"apiVersion\"), gvk.APIVersion, \"version must be specified\"))\n\t\t} else {\n\t\t\tif errs := utilvalidation.IsDNS1035Label(gv.Version); len(errs) \u003e 0 {\n\t\t\t\tallErrors = append(allErrors, field.Invalid(fldPath.Child(\"apiVersion\"), gv.Version, strings.Join(errs, \",\")))\n\t\t\t}\n\t\t}\n\t}\n\tif len(gvk.Kind) == 0 {\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"kind\"), \"\"))\n\t} else if errs := utilvalidation.IsDNS1035Label(strings.ToLower(gvk.Kind)); len(errs) \u003e 0 {\n\t\tallErrors = append(allErrors, field.Invalid(fldPath.Child(\"kind\"), gvk.Kind, \"may have mixed case, but should otherwise match: \"+strings.Join(errs, \",\")))\n\t}\n\n\treturn allErrors\n}","line":{"from":714,"to":743}} {"id":100001872,"name":"parseGroupVersion","signature":"func parseGroupVersion(gv string) (groupVersion, error)","file":"pkg/apis/admissionregistration/validation/validation.go","code":"// parseGroupVersion turns \"group/version\" string into a groupVersion struct. It reports error\n// if it cannot parse the string.\nfunc parseGroupVersion(gv string) (groupVersion, error) {\n\tif (len(gv) == 0) || (gv == \"/\") {\n\t\treturn groupVersion{}, nil\n\t}\n\n\tswitch strings.Count(gv, \"/\") {\n\tcase 0:\n\t\treturn groupVersion{\"\", gv}, nil\n\tcase 1:\n\t\ti := strings.Index(gv, \"/\")\n\t\treturn groupVersion{gv[:i], gv[i+1:]}, nil\n\tdefault:\n\t\treturn groupVersion{}, fmt.Errorf(\"unexpected GroupVersion string: %v\", gv)\n\t}\n}","line":{"from":750,"to":766}} {"id":100001873,"name":"validateMatchResources","signature":"func validateMatchResources(mc *admissionregistration.MatchResources, fldPath *field.Path) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateMatchResources(mc *admissionregistration.MatchResources, fldPath *field.Path) field.ErrorList {\n\tvar allErrors field.ErrorList\n\tif mc == nil {\n\t\treturn allErrors\n\t}\n\tif mc.MatchPolicy == nil {\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"matchPolicy\"), \"\"))\n\t} else if !supportedMatchPolicies.Has(string(*mc.MatchPolicy)) {\n\t\tallErrors = append(allErrors, field.NotSupported(fldPath.Child(\"matchPolicy\"), *mc.MatchPolicy, supportedMatchPolicies.List()))\n\t}\n\tif mc.NamespaceSelector == nil {\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"namespaceSelector\"), \"\"))\n\t} else {\n\t\t// validate selector strictly, this type was released after issue #99139 was resolved\n\t\tallErrors = append(allErrors, metav1validation.ValidateLabelSelector(mc.NamespaceSelector, metav1validation.LabelSelectorValidationOptions{}, fldPath.Child(\"namespaceSelector\"))...)\n\t}\n\n\tif mc.ObjectSelector == nil {\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"labelSelector\"), \"\"))\n\t} else {\n\t\t// validate selector strictly, this type was released after issue #99139 was resolved\n\t\tallErrors = append(allErrors, metav1validation.ValidateLabelSelector(mc.ObjectSelector, metav1validation.LabelSelectorValidationOptions{}, fldPath.Child(\"labelSelector\"))...)\n\t}\n\n\tfor i, namedRuleWithOperations := range mc.ResourceRules {\n\t\tallErrors = append(allErrors, validateNamedRuleWithOperations(\u0026namedRuleWithOperations, fldPath.Child(\"resourceRules\").Index(i))...)\n\t}\n\n\tfor i, namedRuleWithOperations := range mc.ExcludeResourceRules {\n\t\tallErrors = append(allErrors, validateNamedRuleWithOperations(\u0026namedRuleWithOperations, fldPath.Child(\"excludeResourceRules\").Index(i))...)\n\t}\n\treturn allErrors\n}","line":{"from":768,"to":800}} {"id":100001874,"name":"validateValidationActions","signature":"func validateValidationActions(va []admissionregistration.ValidationAction, fldPath *field.Path) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateValidationActions(va []admissionregistration.ValidationAction, fldPath *field.Path) field.ErrorList {\n\tvar allErrors field.ErrorList\n\tactions := sets.NewString()\n\tfor i, action := range va {\n\t\tif !validValidationActions.Has(string(action)) {\n\t\t\tallErrors = append(allErrors, field.NotSupported(fldPath.Index(i), action, validValidationActions.List()))\n\t\t}\n\t\tif actions.Has(string(action)) {\n\t\t\tallErrors = append(allErrors, field.Duplicate(fldPath.Index(i), action))\n\t\t}\n\t\tactions.Insert(string(action))\n\t}\n\tif actions.Has(string(admissionregistration.Deny)) \u0026\u0026 actions.Has(string(admissionregistration.Warn)) {\n\t\tallErrors = append(allErrors, field.Invalid(fldPath, va, \"must not contain both Deny and Warn (repeating the same validation failure information in the API response and headers serves no purpose)\"))\n\t}\n\tif len(actions) == 0 {\n\t\tallErrors = append(allErrors, field.Required(fldPath, \"at least one validation action is required\"))\n\t}\n\treturn allErrors\n}","line":{"from":808,"to":827}} {"id":100001875,"name":"validateNamedRuleWithOperations","signature":"func validateNamedRuleWithOperations(n *admissionregistration.NamedRuleWithOperations, fldPath *field.Path) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateNamedRuleWithOperations(n *admissionregistration.NamedRuleWithOperations, fldPath *field.Path) field.ErrorList {\n\tvar allErrors field.ErrorList\n\tresourceNames := sets.NewString()\n\tfor i, rName := range n.ResourceNames {\n\t\tfor _, msg := range path.ValidatePathSegmentName(rName, false) {\n\t\t\tallErrors = append(allErrors, field.Invalid(fldPath.Child(\"resourceNames\").Index(i), rName, msg))\n\t\t}\n\t\tif resourceNames.Has(rName) {\n\t\t\tallErrors = append(allErrors, field.Duplicate(fldPath.Child(\"resourceNames\").Index(i), rName))\n\t\t} else {\n\t\t\tresourceNames.Insert(rName)\n\t\t}\n\t}\n\tallErrors = append(allErrors, validateRuleWithOperations(\u0026n.RuleWithOperations, fldPath)...)\n\treturn allErrors\n}","line":{"from":829,"to":844}} {"id":100001876,"name":"validateMatchConditions","signature":"func validateMatchConditions(m []admissionregistration.MatchCondition, opts validationOptions, fldPath *field.Path) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateMatchConditions(m []admissionregistration.MatchCondition, opts validationOptions, fldPath *field.Path) field.ErrorList {\n\tvar allErrors field.ErrorList\n\tconditionNames := sets.NewString()\n\tif len(m) \u003e 64 {\n\t\tallErrors = append(allErrors, field.TooMany(fldPath, len(m), 64))\n\t}\n\tfor i, matchCondition := range m {\n\t\tallErrors = append(allErrors, validateMatchCondition(\u0026matchCondition, opts, fldPath.Index(i))...)\n\t\tif len(matchCondition.Name) \u003e 0 {\n\t\t\tif conditionNames.Has(matchCondition.Name) {\n\t\t\t\tallErrors = append(allErrors, field.Duplicate(fldPath.Index(i).Child(\"name\"), matchCondition.Name))\n\t\t\t} else {\n\t\t\t\tconditionNames.Insert(matchCondition.Name)\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrors\n}","line":{"from":846,"to":863}} {"id":100001877,"name":"validateMatchCondition","signature":"func validateMatchCondition(v *admissionregistration.MatchCondition, opts validationOptions, fldPath *field.Path) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateMatchCondition(v *admissionregistration.MatchCondition, opts validationOptions, fldPath *field.Path) field.ErrorList {\n\tvar allErrors field.ErrorList\n\ttrimmedExpression := strings.TrimSpace(v.Expression)\n\tif len(trimmedExpression) == 0 {\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"expression\"), \"\"))\n\t} else {\n\t\tallErrors = append(allErrors, validateMatchConditionsExpression(trimmedExpression, opts.allowParamsInMatchConditions, fldPath.Child(\"expression\"))...)\n\t}\n\tif len(v.Name) == 0 {\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"name\"), \"\"))\n\t} else {\n\t\tallErrors = append(allErrors, apivalidation.ValidateQualifiedName(v.Name, fldPath.Child(\"name\"))...)\n\t}\n\treturn allErrors\n}","line":{"from":865,"to":879}} {"id":100001878,"name":"validateValidation","signature":"func validateValidation(v *admissionregistration.Validation, paramKind *admissionregistration.ParamKind, fldPath *field.Path) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateValidation(v *admissionregistration.Validation, paramKind *admissionregistration.ParamKind, fldPath *field.Path) field.ErrorList {\n\tvar allErrors field.ErrorList\n\ttrimmedExpression := strings.TrimSpace(v.Expression)\n\ttrimmedMsg := strings.TrimSpace(v.Message)\n\ttrimmedMessageExpression := strings.TrimSpace(v.MessageExpression)\n\tif len(trimmedExpression) == 0 {\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"expression\"), \"expression is not specified\"))\n\t} else {\n\t\tallErrors = append(allErrors, validateValidationExpression(v.Expression, paramKind != nil, fldPath.Child(\"expression\"))...)\n\t}\n\tif len(v.MessageExpression) \u003e 0 \u0026\u0026 len(trimmedMessageExpression) == 0 {\n\t\tallErrors = append(allErrors, field.Invalid(fldPath.Child(\"messageExpression\"), v.MessageExpression, \"must be non-empty if specified\"))\n\t} else if len(trimmedMessageExpression) != 0 {\n\t\t// use v.MessageExpression instead of trimmedMessageExpression so that\n\t\t// the compiler output shows the correct column.\n\t\tallErrors = append(allErrors, validateMessageExpression(v.MessageExpression, paramKind != nil, fldPath.Child(\"messageExpression\"))...)\n\t}\n\tif len(v.Message) \u003e 0 \u0026\u0026 len(trimmedMsg) == 0 {\n\t\tallErrors = append(allErrors, field.Invalid(fldPath.Child(\"message\"), v.Message, \"message must be non-empty if specified\"))\n\t} else if hasNewlines(trimmedMsg) {\n\t\tallErrors = append(allErrors, field.Invalid(fldPath.Child(\"message\"), v.Message, \"message must not contain line breaks\"))\n\t} else if hasNewlines(trimmedMsg) \u0026\u0026 trimmedMsg == \"\" {\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"message\"), \"message must be specified if expression contains line breaks\"))\n\t}\n\tif v.Reason != nil \u0026\u0026 !supportedValidationPolicyReason.Has(string(*v.Reason)) {\n\t\tallErrors = append(allErrors, field.NotSupported(fldPath.Child(\"reason\"), *v.Reason, supportedValidationPolicyReason.List()))\n\t}\n\treturn allErrors\n}","line":{"from":881,"to":909}} {"id":100001879,"name":"validateCELCondition","signature":"func validateCELCondition(expression plugincel.ExpressionAccessor, variables plugincel.OptionalVariableDeclarations, fldPath *field.Path) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateCELCondition(expression plugincel.ExpressionAccessor, variables plugincel.OptionalVariableDeclarations, fldPath *field.Path) field.ErrorList {\n\tvar allErrors field.ErrorList\n\tresult := plugincel.CompileCELExpression(expression, variables, celconfig.PerCallLimit)\n\tif result.Error != nil {\n\t\tswitch result.Error.Type {\n\t\tcase cel.ErrorTypeRequired:\n\t\t\tallErrors = append(allErrors, field.Required(fldPath, result.Error.Detail))\n\t\tcase cel.ErrorTypeInvalid:\n\t\t\tallErrors = append(allErrors, field.Invalid(fldPath, expression.GetExpression(), result.Error.Detail))\n\t\tcase cel.ErrorTypeInternal:\n\t\t\tallErrors = append(allErrors, field.InternalError(fldPath, result.Error))\n\t\tdefault:\n\t\t\tallErrors = append(allErrors, field.InternalError(fldPath, fmt.Errorf(\"unsupported error type: %w\", result.Error)))\n\t\t}\n\t}\n\treturn allErrors\n}","line":{"from":911,"to":927}} {"id":100001880,"name":"validateValidationExpression","signature":"func validateValidationExpression(expression string, hasParams bool, fldPath *field.Path) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateValidationExpression(expression string, hasParams bool, fldPath *field.Path) field.ErrorList {\n\treturn validateCELCondition(\u0026validatingadmissionpolicy.ValidationCondition{\n\t\tExpression: expression,\n\t}, plugincel.OptionalVariableDeclarations{\n\t\tHasParams: hasParams,\n\t\tHasAuthorizer: true,\n\t}, fldPath)\n}","line":{"from":929,"to":936}} {"id":100001881,"name":"validateMatchConditionsExpression","signature":"func validateMatchConditionsExpression(expression string, hasParams bool, fldPath *field.Path) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateMatchConditionsExpression(expression string, hasParams bool, fldPath *field.Path) field.ErrorList {\n\treturn validateCELCondition(\u0026matchconditions.MatchCondition{\n\t\tExpression: expression,\n\t}, plugincel.OptionalVariableDeclarations{\n\t\tHasParams: hasParams,\n\t\tHasAuthorizer: true,\n\t}, fldPath)\n}","line":{"from":938,"to":945}} {"id":100001882,"name":"validateMessageExpression","signature":"func validateMessageExpression(expression string, hasParams bool, fldPath *field.Path) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateMessageExpression(expression string, hasParams bool, fldPath *field.Path) field.ErrorList {\n\treturn validateCELCondition(\u0026validatingadmissionpolicy.MessageExpressionCondition{\n\t\tMessageExpression: expression,\n\t}, plugincel.OptionalVariableDeclarations{\n\t\tHasParams: hasParams,\n\t\tHasAuthorizer: false,\n\t}, fldPath)\n}","line":{"from":947,"to":954}} {"id":100001883,"name":"validateAuditAnnotation","signature":"func validateAuditAnnotation(meta metav1.ObjectMeta, v *admissionregistration.AuditAnnotation, paramKind *admissionregistration.ParamKind, fldPath *field.Path) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateAuditAnnotation(meta metav1.ObjectMeta, v *admissionregistration.AuditAnnotation, paramKind *admissionregistration.ParamKind, fldPath *field.Path) field.ErrorList {\n\tvar allErrors field.ErrorList\n\tif len(meta.GetName()) != 0 {\n\t\tname := meta.GetName()\n\t\tallErrors = append(allErrors, apivalidation.ValidateQualifiedName(name+\"/\"+v.Key, fldPath.Child(\"key\"))...)\n\t} else {\n\t\tallErrors = append(allErrors, field.Invalid(fldPath.Child(\"key\"), v.Key, \"requires metadata.name be non-empty\"))\n\t}\n\n\ttrimmedValueExpression := strings.TrimSpace(v.ValueExpression)\n\tif len(trimmedValueExpression) == 0 {\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"valueExpression\"), \"valueExpression is not specified\"))\n\t} else if len(trimmedValueExpression) \u003e maxAuditAnnotationValueExpressionLength {\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"valueExpression\"), fmt.Sprintf(\"must not exceed %d bytes in length\", maxAuditAnnotationValueExpressionLength)))\n\t} else {\n\t\tresult := plugincel.CompileCELExpression(\u0026validatingadmissionpolicy.AuditAnnotationCondition{\n\t\t\tValueExpression: trimmedValueExpression,\n\t\t}, plugincel.OptionalVariableDeclarations{HasParams: paramKind != nil, HasAuthorizer: true}, celconfig.PerCallLimit)\n\t\tif result.Error != nil {\n\t\t\tswitch result.Error.Type {\n\t\t\tcase cel.ErrorTypeRequired:\n\t\t\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"valueExpression\"), result.Error.Detail))\n\t\t\tcase cel.ErrorTypeInvalid:\n\t\t\t\tallErrors = append(allErrors, field.Invalid(fldPath.Child(\"valueExpression\"), v.ValueExpression, result.Error.Detail))\n\t\t\tdefault:\n\t\t\t\tallErrors = append(allErrors, field.InternalError(fldPath.Child(\"valueExpression\"), result.Error))\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrors\n}","line":{"from":956,"to":986}} {"id":100001884,"name":"hasNewlines","signature":"func hasNewlines(s string) bool","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func hasNewlines(s string) bool {\n\treturn newlineMatcher.MatchString(s)\n}","line":{"from":989,"to":991}} {"id":100001885,"name":"ValidateValidatingAdmissionPolicyBinding","signature":"func ValidateValidatingAdmissionPolicyBinding(pb *admissionregistration.ValidatingAdmissionPolicyBinding) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"// ValidateValidatingAdmissionPolicyBinding validates a ValidatingAdmissionPolicyBinding before create.\nfunc ValidateValidatingAdmissionPolicyBinding(pb *admissionregistration.ValidatingAdmissionPolicyBinding) field.ErrorList {\n\treturn validateValidatingAdmissionPolicyBinding(pb)\n}","line":{"from":993,"to":996}} {"id":100001886,"name":"validateValidatingAdmissionPolicyBinding","signature":"func validateValidatingAdmissionPolicyBinding(pb *admissionregistration.ValidatingAdmissionPolicyBinding) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateValidatingAdmissionPolicyBinding(pb *admissionregistration.ValidatingAdmissionPolicyBinding) field.ErrorList {\n\tallErrors := genericvalidation.ValidateObjectMeta(\u0026pb.ObjectMeta, false, genericvalidation.NameIsDNSSubdomain, field.NewPath(\"metadata\"))\n\tallErrors = append(allErrors, validateValidatingAdmissionPolicyBindingSpec(\u0026pb.Spec, field.NewPath(\"spec\"))...)\n\n\treturn allErrors\n}","line":{"from":998,"to":1003}} {"id":100001887,"name":"validateValidatingAdmissionPolicyBindingSpec","signature":"func validateValidatingAdmissionPolicyBindingSpec(spec *admissionregistration.ValidatingAdmissionPolicyBindingSpec, fldPath *field.Path) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateValidatingAdmissionPolicyBindingSpec(spec *admissionregistration.ValidatingAdmissionPolicyBindingSpec, fldPath *field.Path) field.ErrorList {\n\tvar allErrors field.ErrorList\n\n\tif len(spec.PolicyName) == 0 {\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"policyName\"), \"\"))\n\t} else {\n\t\tfor _, msg := range genericvalidation.NameIsDNSSubdomain(spec.PolicyName, false) {\n\t\t\tallErrors = append(allErrors, field.Invalid(fldPath.Child(\"policyName\"), spec.PolicyName, msg))\n\t\t}\n\t}\n\tallErrors = append(allErrors, validateParamRef(spec.ParamRef, fldPath.Child(\"paramRef\"))...)\n\tallErrors = append(allErrors, validateMatchResources(spec.MatchResources, fldPath.Child(\"matchResouces\"))...)\n\tallErrors = append(allErrors, validateValidationActions(spec.ValidationActions, fldPath.Child(\"validationActions\"))...)\n\n\treturn allErrors\n}","line":{"from":1005,"to":1020}} {"id":100001888,"name":"validateParamRef","signature":"func validateParamRef(pr *admissionregistration.ParamRef, fldPath *field.Path) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateParamRef(pr *admissionregistration.ParamRef, fldPath *field.Path) field.ErrorList {\n\tvar allErrors field.ErrorList\n\tif pr == nil {\n\t\treturn allErrors\n\t}\n\tfor _, msg := range path.ValidatePathSegmentName(pr.Name, false) {\n\t\tallErrors = append(allErrors, field.Invalid(fldPath.Child(\"name\"), pr.Name, msg))\n\t}\n\treturn allErrors\n}","line":{"from":1022,"to":1031}} {"id":100001889,"name":"ValidateValidatingAdmissionPolicyUpdate","signature":"func ValidateValidatingAdmissionPolicyUpdate(newC, oldC *admissionregistration.ValidatingAdmissionPolicy) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"// ValidateValidatingAdmissionPolicyUpdate validates update of validating admission policy\nfunc ValidateValidatingAdmissionPolicyUpdate(newC, oldC *admissionregistration.ValidatingAdmissionPolicy) field.ErrorList {\n\treturn validateValidatingAdmissionPolicy(newC, validationOptions{ignoreMatchConditions: ignoreValidatingAdmissionPolicyMatchConditions(newC, oldC)})\n}","line":{"from":1033,"to":1036}} {"id":100001890,"name":"ValidateValidatingAdmissionPolicyStatusUpdate","signature":"func ValidateValidatingAdmissionPolicyStatusUpdate(newC, oldC *admissionregistration.ValidatingAdmissionPolicy) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"// ValidateValidatingAdmissionPolicyStatusUpdate validates update of status of validating admission policy\nfunc ValidateValidatingAdmissionPolicyStatusUpdate(newC, oldC *admissionregistration.ValidatingAdmissionPolicy) field.ErrorList {\n\treturn validateValidatingAdmissionPolicyStatus(\u0026newC.Status, field.NewPath(\"status\"))\n}","line":{"from":1038,"to":1041}} {"id":100001891,"name":"ValidateValidatingAdmissionPolicyBindingUpdate","signature":"func ValidateValidatingAdmissionPolicyBindingUpdate(newC, oldC *admissionregistration.ValidatingAdmissionPolicyBinding) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"// ValidateValidatingAdmissionPolicyBindingUpdate validates update of validating admission policy\nfunc ValidateValidatingAdmissionPolicyBindingUpdate(newC, oldC *admissionregistration.ValidatingAdmissionPolicyBinding) field.ErrorList {\n\treturn validateValidatingAdmissionPolicyBinding(newC)\n}","line":{"from":1043,"to":1046}} {"id":100001892,"name":"validateValidatingAdmissionPolicyStatus","signature":"func validateValidatingAdmissionPolicyStatus(status *admissionregistration.ValidatingAdmissionPolicyStatus, fldPath *field.Path) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateValidatingAdmissionPolicyStatus(status *admissionregistration.ValidatingAdmissionPolicyStatus, fldPath *field.Path) field.ErrorList {\n\tvar allErrors field.ErrorList\n\tallErrors = append(allErrors, validateTypeChecking(status.TypeChecking, fldPath.Child(\"typeChecking\"))...)\n\tallErrors = append(allErrors, metav1validation.ValidateConditions(status.Conditions, fldPath.Child(\"conditions\"))...)\n\treturn allErrors\n}","line":{"from":1048,"to":1053}} {"id":100001893,"name":"validateTypeChecking","signature":"func validateTypeChecking(typeChecking *admissionregistration.TypeChecking, fldPath *field.Path) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateTypeChecking(typeChecking *admissionregistration.TypeChecking, fldPath *field.Path) field.ErrorList {\n\tif typeChecking == nil {\n\t\treturn nil\n\t}\n\treturn validateExpressionWarnings(typeChecking.ExpressionWarnings, fldPath.Child(\"expressionWarnings\"))\n}","line":{"from":1055,"to":1060}} {"id":100001894,"name":"validateExpressionWarnings","signature":"func validateExpressionWarnings(expressionWarnings []admissionregistration.ExpressionWarning, fldPath *field.Path) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateExpressionWarnings(expressionWarnings []admissionregistration.ExpressionWarning, fldPath *field.Path) field.ErrorList {\n\tvar allErrors field.ErrorList\n\tfor i, warning := range expressionWarnings {\n\t\tallErrors = append(allErrors, validateExpressionWarning(\u0026warning, fldPath.Index(i))...)\n\t}\n\treturn allErrors\n}","line":{"from":1062,"to":1068}} {"id":100001895,"name":"validateExpressionWarning","signature":"func validateExpressionWarning(expressionWarning *admissionregistration.ExpressionWarning, fldPath *field.Path) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateExpressionWarning(expressionWarning *admissionregistration.ExpressionWarning, fldPath *field.Path) field.ErrorList {\n\tvar allErrors field.ErrorList\n\tif expressionWarning.Warning == \"\" {\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"warning\"), \"\"))\n\t}\n\tallErrors = append(allErrors, validateFieldRef(expressionWarning.FieldRef, fldPath.Child(\"fieldRef\"))...)\n\treturn allErrors\n}","line":{"from":1070,"to":1077}} {"id":100001896,"name":"validateFieldRef","signature":"func validateFieldRef(fieldRef string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/admissionregistration/validation/validation.go","code":"func validateFieldRef(fieldRef string, fldPath *field.Path) field.ErrorList {\n\tfieldRef = strings.TrimSpace(fieldRef)\n\tif fieldRef == \"\" {\n\t\treturn field.ErrorList{field.Required(fldPath, \"\")}\n\t}\n\tjsonPath := jsonpath.New(\"spec\")\n\tif err := jsonPath.Parse(fmt.Sprintf(\"{%s}\", fieldRef)); err != nil {\n\t\treturn field.ErrorList{field.Invalid(fldPath, fieldRef, fmt.Sprintf(\"invalid JSONPath: %v\", err))}\n\t}\n\t// no further checks, for an easier upgrade/rollback\n\treturn nil\n}","line":{"from":1079,"to":1090}} {"id":100001897,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"pkg/apis/apidiscovery/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100001898,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/apidiscovery/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100001899,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/apidiscovery/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026APIGroupDiscoveryList{},\n\t\t\u0026APIGroupDiscovery{},\n\t)\n\treturn nil\n}","line":{"from":47,"to":54}} {"id":100001900,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/apidiscovery/v2beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100001901,"name":"Funcs","signature":"func Funcs(codecs runtimeserializer.CodecFactory) []interface{}","file":"pkg/apis/apiserverinternal/fuzzer/fuzzer.go","code":"// Funcs returns the fuzzer functions for the apiserverinternal api group.\nfunc Funcs(codecs runtimeserializer.CodecFactory) []interface{} {\n\treturn []interface{}{}\n}","line":{"from":23,"to":26}} {"id":100001902,"name":"init","signature":"func init()","file":"pkg/apis/apiserverinternal/install/install.go","code":"func init() {\n\tInstall(legacyscheme.Scheme)\n}","line":{"from":29,"to":31}} {"id":100001903,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"pkg/apis/apiserverinternal/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(apiserverinternal.AddToScheme(scheme))\n\tutilruntime.Must(v1alpha1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1alpha1.SchemeGroupVersion))\n}","line":{"from":33,"to":38}} {"id":100001904,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"pkg/apis/apiserverinternal/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100001905,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/apiserverinternal/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100001906,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/apiserverinternal/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026StorageVersion{},\n\t\t\u0026StorageVersionList{},\n\t)\n\treturn nil\n}","line":{"from":47,"to":53}} {"id":100001907,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/apiserverinternal/v1alpha1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100001908,"name":"init","signature":"func init()","file":"pkg/apis/apiserverinternal/v1alpha1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(RegisterDefaults)\n}","line":{"from":41,"to":46}} {"id":100001909,"name":"ValidateStorageVersion","signature":"func ValidateStorageVersion(sv *apiserverinternal.StorageVersion) field.ErrorList","file":"pkg/apis/apiserverinternal/validation/validation.go","code":"// ValidateStorageVersion validate the storage version object.\nfunc ValidateStorageVersion(sv *apiserverinternal.StorageVersion) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tallErrs = append(allErrs, apivalidation.ValidateObjectMeta(\u0026sv.ObjectMeta, false, ValidateStorageVersionName, field.NewPath(\"metadata\"))...)\n\tallErrs = append(allErrs, validateStorageVersionStatus(sv.Status, field.NewPath(\"status\"))...)\n\treturn allErrs\n}","line":{"from":30,"to":36}} {"id":100001910,"name":"ValidateStorageVersionName","signature":"func ValidateStorageVersionName(name string, prefix bool) []string","file":"pkg/apis/apiserverinternal/validation/validation.go","code":"// ValidateStorageVersionName is a ValidateNameFunc for storage version names\nfunc ValidateStorageVersionName(name string, prefix bool) []string {\n\tvar allErrs []string\n\tidx := strings.LastIndex(name, \".\")\n\tif idx \u003c 0 {\n\t\tallErrs = append(allErrs, \"name must be in the form of \u003cgroup\u003e.\u003cresource\u003e\")\n\t} else {\n\t\tfor _, msg := range utilvalidation.IsDNS1123Subdomain(name[:idx]) {\n\t\t\tallErrs = append(allErrs, \"the group segment \"+msg)\n\t\t}\n\t\tfor _, msg := range utilvalidation.IsDNS1035Label(name[idx+1:]) {\n\t\t\tallErrs = append(allErrs, \"the resource segment \"+msg)\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":38,"to":53}} {"id":100001911,"name":"ValidateStorageVersionUpdate","signature":"func ValidateStorageVersionUpdate(sv, oldSV *apiserverinternal.StorageVersion) field.ErrorList","file":"pkg/apis/apiserverinternal/validation/validation.go","code":"// ValidateStorageVersionUpdate tests if an update to a StorageVersion is valid.\nfunc ValidateStorageVersionUpdate(sv, oldSV *apiserverinternal.StorageVersion) field.ErrorList {\n\t// no error since StorageVersionSpec is an empty spec\n\treturn field.ErrorList{}\n}","line":{"from":55,"to":59}} {"id":100001912,"name":"ValidateStorageVersionStatusUpdate","signature":"func ValidateStorageVersionStatusUpdate(sv, oldSV *apiserverinternal.StorageVersion) field.ErrorList","file":"pkg/apis/apiserverinternal/validation/validation.go","code":"// ValidateStorageVersionStatusUpdate tests if an update to a StorageVersionStatus is valid.\nfunc ValidateStorageVersionStatusUpdate(sv, oldSV *apiserverinternal.StorageVersion) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tallErrs = append(allErrs, validateStorageVersionStatus(sv.Status, field.NewPath(\"status\"))...)\n\treturn allErrs\n}","line":{"from":61,"to":66}} {"id":100001913,"name":"validateStorageVersionStatus","signature":"func validateStorageVersionStatus(ss apiserverinternal.StorageVersionStatus, fldPath *field.Path) field.ErrorList","file":"pkg/apis/apiserverinternal/validation/validation.go","code":"func validateStorageVersionStatus(ss apiserverinternal.StorageVersionStatus, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tfor i, ssv := range ss.StorageVersions {\n\t\tallErrs = append(allErrs, validateServerStorageVersion(ssv, fldPath.Child(\"storageVersions\").Index(i))...)\n\t}\n\tif err := validateCommonVersion(ss, fldPath); err != nil {\n\t\tallErrs = append(allErrs, err)\n\t}\n\tallErrs = append(allErrs, validateStorageVersionCondition(ss.Conditions, fldPath)...)\n\treturn allErrs\n}","line":{"from":68,"to":78}} {"id":100001914,"name":"validateServerStorageVersion","signature":"func validateServerStorageVersion(ssv apiserverinternal.ServerStorageVersion, fldPath *field.Path) field.ErrorList","file":"pkg/apis/apiserverinternal/validation/validation.go","code":"func validateServerStorageVersion(ssv apiserverinternal.ServerStorageVersion, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor _, msg := range apimachineryvalidation.NameIsDNSSubdomain(ssv.APIServerID, false) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"apiServerID\"), ssv.APIServerID, msg))\n\t}\n\tif errs := isValidAPIVersion(ssv.EncodingVersion); len(errs) \u003e 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"encodingVersion\"), ssv.EncodingVersion, strings.Join(errs, \",\")))\n\t}\n\n\tfound := false\n\tfor i, dv := range ssv.DecodableVersions {\n\t\tif errs := isValidAPIVersion(dv); len(errs) \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"decodableVersions\").Index(i), dv, strings.Join(errs, \",\")))\n\t\t}\n\t\tif dv == ssv.EncodingVersion {\n\t\t\tfound = true\n\t\t}\n\t}\n\tif !found {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"decodableVersions\"), ssv.DecodableVersions, fmt.Sprintf(\"decodableVersions must include encodingVersion %s\", ssv.EncodingVersion)))\n\t}\n\treturn allErrs\n}","line":{"from":80,"to":102}} {"id":100001915,"name":"commonVersion","signature":"func commonVersion(ssv []apiserverinternal.ServerStorageVersion) *string","file":"pkg/apis/apiserverinternal/validation/validation.go","code":"func commonVersion(ssv []apiserverinternal.ServerStorageVersion) *string {\n\tif len(ssv) == 0 {\n\t\treturn nil\n\t}\n\tcommonVersion := ssv[0].EncodingVersion\n\tfor _, v := range ssv[1:] {\n\t\tif v.EncodingVersion != commonVersion {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn \u0026commonVersion\n}","line":{"from":104,"to":115}} {"id":100001916,"name":"validateCommonVersion","signature":"func validateCommonVersion(svs apiserverinternal.StorageVersionStatus, fldPath *field.Path) *field.Error","file":"pkg/apis/apiserverinternal/validation/validation.go","code":"func validateCommonVersion(svs apiserverinternal.StorageVersionStatus, fldPath *field.Path) *field.Error {\n\tactualCommonVersion := commonVersion(svs.StorageVersions)\n\tif actualCommonVersion == nil \u0026\u0026 svs.CommonEncodingVersion == nil {\n\t\treturn nil\n\t}\n\tif actualCommonVersion == nil \u0026\u0026 svs.CommonEncodingVersion != nil {\n\t\treturn field.Invalid(fldPath.Child(\"commonEncodingVersion\"), *svs.CommonEncodingVersion, \"should be nil if servers do not agree on the same encoding version, or if there is no server reporting the supported versions yet\")\n\t}\n\tif actualCommonVersion != nil \u0026\u0026 svs.CommonEncodingVersion == nil {\n\t\treturn field.Invalid(fldPath.Child(\"commonEncodingVersion\"), svs.CommonEncodingVersion, fmt.Sprintf(\"the common encoding version is %s\", *actualCommonVersion))\n\t}\n\tif actualCommonVersion != nil \u0026\u0026 svs.CommonEncodingVersion != nil \u0026\u0026 *actualCommonVersion != *svs.CommonEncodingVersion {\n\t\treturn field.Invalid(fldPath.Child(\"commonEncodingVersion\"), *svs.CommonEncodingVersion, fmt.Sprintf(\"the actual common encoding version is %s\", *actualCommonVersion))\n\t}\n\treturn nil\n}","line":{"from":117,"to":132}} {"id":100001917,"name":"validateStorageVersionCondition","signature":"func validateStorageVersionCondition(conditions []apiserverinternal.StorageVersionCondition, fldPath *field.Path) field.ErrorList","file":"pkg/apis/apiserverinternal/validation/validation.go","code":"func validateStorageVersionCondition(conditions []apiserverinternal.StorageVersionCondition, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\t// We do not verify that the condition type or the condition status is\n\t// a predefined one because we might add more type or status later.\n\tseenType := make(map[apiserverinternal.StorageVersionConditionType]int)\n\tfor i, condition := range conditions {\n\t\tif ii, ok := seenType[condition.Type]; ok {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Index(i).Child(\"type\"), string(condition.Type),\n\t\t\t\tfmt.Sprintf(\"the type of the condition is not unique, it also appears in conditions[%d]\", ii)))\n\t\t}\n\t\tseenType[condition.Type] = i\n\t\tallErrs = append(allErrs, apivalidation.ValidateQualifiedName(string(condition.Type), fldPath.Index(i).Child(\"type\"))...)\n\t\tallErrs = append(allErrs, apivalidation.ValidateQualifiedName(string(condition.Status), fldPath.Index(i).Child(\"status\"))...)\n\t\tif condition.Reason == \"\" {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Index(i).Child(\"reason\"), \"reason cannot be empty\"))\n\t\t}\n\t\tif condition.Message == \"\" {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Index(i).Child(\"message\"), \"message cannot be empty\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":134,"to":155}} {"id":100001918,"name":"isValidAPIVersion","signature":"func isValidAPIVersion(apiVersion string) []string","file":"pkg/apis/apiserverinternal/validation/validation.go","code":"// isValidAPIVersion tests whether the value passed is a valid apiVersion. A\n// valid apiVersion contains a version string that matches DNS_LABEL format,\n// with an optional group/ prefix, where the group string matches DNS_SUBDOMAIN\n// format. If the value is not valid, a list of error strings is returned.\n// Otherwise an empty list (or nil) is returned.\nfunc isValidAPIVersion(apiVersion string) []string {\n\tvar errs []string\n\tparts := strings.Split(apiVersion, \"/\")\n\tvar version string\n\tswitch len(parts) {\n\tcase 1:\n\t\tversion = parts[0]\n\tcase 2:\n\t\tvar group string\n\t\tgroup, version = parts[0], parts[1]\n\t\tif len(group) == 0 {\n\t\t\terrs = append(errs, \"group part: \"+utilvalidation.EmptyError())\n\t\t} else if msgs := utilvalidation.IsDNS1123Subdomain(group); len(msgs) != 0 {\n\t\t\terrs = append(errs, prefixEach(msgs, \"group part: \")...)\n\t\t}\n\tdefault:\n\t\treturn append(errs, \"an apiVersion is \"+utilvalidation.RegexError(dns1035LabelErrMsg, dns1035LabelFmt, \"my-name\", \"abc-123\")+\n\t\t\t\" with an optional DNS subdomain prefix and '/' (e.g. 'example.com/MyVersion')\")\n\t}\n\n\tif len(version) == 0 {\n\t\terrs = append(errs, \"version part: \"+utilvalidation.EmptyError())\n\t} else if msgs := utilvalidation.IsDNS1035Label(version); len(msgs) != 0 {\n\t\terrs = append(errs, prefixEach(msgs, \"version part: \")...)\n\t}\n\treturn errs\n}","line":{"from":160,"to":191}} {"id":100001919,"name":"prefixEach","signature":"func prefixEach(msgs []string, prefix string) []string","file":"pkg/apis/apiserverinternal/validation/validation.go","code":"func prefixEach(msgs []string, prefix string) []string {\n\tfor i := range msgs {\n\t\tmsgs[i] = prefix + msgs[i]\n\t}\n\treturn msgs\n}","line":{"from":193,"to":198}} {"id":100001920,"name":"init","signature":"func init()","file":"pkg/apis/apps/install/install.go","code":"func init() {\n\tInstall(legacyscheme.Scheme)\n}","line":{"from":31,"to":33}} {"id":100001921,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"pkg/apis/apps/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(apps.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(v1beta2.AddToScheme(scheme))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1.SchemeGroupVersion, v1beta2.SchemeGroupVersion, v1beta1.SchemeGroupVersion))\n}","line":{"from":35,"to":42}} {"id":100001922,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"pkg/apis/apps/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":38,"to":41}} {"id":100001923,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/apps/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":43,"to":46}} {"id":100001924,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/apps/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\t// TODO this will get cleaned up with the scheme types are fixed\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026DaemonSet{},\n\t\t\u0026DaemonSetList{},\n\t\t\u0026Deployment{},\n\t\t\u0026DeploymentList{},\n\t\t\u0026DeploymentRollback{},\n\t\t\u0026autoscaling.Scale{},\n\t\t\u0026StatefulSet{},\n\t\t\u0026StatefulSetList{},\n\t\t\u0026ControllerRevision{},\n\t\t\u0026ControllerRevisionList{},\n\t\t\u0026ReplicaSet{},\n\t\t\u0026ReplicaSetList{},\n\t)\n\treturn nil\n}","line":{"from":48,"to":66}} {"id":100001925,"name":"Convert_apps_DeploymentSpec_To_v1_DeploymentSpec","signature":"func Convert_apps_DeploymentSpec_To_v1_DeploymentSpec(in *apps.DeploymentSpec, out *appsv1.DeploymentSpec, s conversion.Scope) error","file":"pkg/apis/apps/v1/conversion.go","code":"// Convert_apps_DeploymentSpec_To_v1_DeploymentSpec is defined here, because public\n// conversion is not auto-generated due to existing warnings.\nfunc Convert_apps_DeploymentSpec_To_v1_DeploymentSpec(in *apps.DeploymentSpec, out *appsv1.DeploymentSpec, s conversion.Scope) error {\n\tif err := autoConvert_apps_DeploymentSpec_To_v1_DeploymentSpec(in, out, s); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":30,"to":37}} {"id":100001926,"name":"Convert_v1_Deployment_To_apps_Deployment","signature":"func Convert_v1_Deployment_To_apps_Deployment(in *appsv1.Deployment, out *apps.Deployment, s conversion.Scope) error","file":"pkg/apis/apps/v1/conversion.go","code":"func Convert_v1_Deployment_To_apps_Deployment(in *appsv1.Deployment, out *apps.Deployment, s conversion.Scope) error {\n\tif err := autoConvert_v1_Deployment_To_apps_Deployment(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\t// Copy annotation to deprecated rollbackTo field for roundtrip\n\t// TODO: remove this conversion after we delete extensions/v1beta1 and apps/v1beta1 Deployment\n\tif revision := in.Annotations[appsv1.DeprecatedRollbackTo]; revision != \"\" {\n\t\tif revision64, err := strconv.ParseInt(revision, 10, 64); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to parse annotation[%s]=%s as int64: %v\", appsv1.DeprecatedRollbackTo, revision, err)\n\t\t} else {\n\t\t\tout.Spec.RollbackTo = new(apps.RollbackConfig)\n\t\t\tout.Spec.RollbackTo.Revision = revision64\n\t\t}\n\t\tout.Annotations = deepCopyStringMap(out.Annotations)\n\t\tdelete(out.Annotations, appsv1.DeprecatedRollbackTo)\n\t} else {\n\t\tout.Spec.RollbackTo = nil\n\t}\n\n\treturn nil\n}","line":{"from":39,"to":60}} {"id":100001927,"name":"Convert_apps_Deployment_To_v1_Deployment","signature":"func Convert_apps_Deployment_To_v1_Deployment(in *apps.Deployment, out *appsv1.Deployment, s conversion.Scope) error","file":"pkg/apis/apps/v1/conversion.go","code":"func Convert_apps_Deployment_To_v1_Deployment(in *apps.Deployment, out *appsv1.Deployment, s conversion.Scope) error {\n\tif err := autoConvert_apps_Deployment_To_v1_Deployment(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\tout.Annotations = deepCopyStringMap(out.Annotations) // deep copy because we modify it below\n\n\t// Copy deprecated rollbackTo field to annotation for roundtrip\n\t// TODO: remove this conversion after we delete extensions/v1beta1 and apps/v1beta1 Deployment\n\tif in.Spec.RollbackTo != nil {\n\t\tif out.Annotations == nil {\n\t\t\tout.Annotations = make(map[string]string)\n\t\t}\n\t\tout.Annotations[appsv1.DeprecatedRollbackTo] = strconv.FormatInt(in.Spec.RollbackTo.Revision, 10)\n\t} else {\n\t\tdelete(out.Annotations, appsv1.DeprecatedRollbackTo)\n\t}\n\n\treturn nil\n}","line":{"from":62,"to":81}} {"id":100001928,"name":"Convert_apps_DaemonSet_To_v1_DaemonSet","signature":"func Convert_apps_DaemonSet_To_v1_DaemonSet(in *apps.DaemonSet, out *appsv1.DaemonSet, s conversion.Scope) error","file":"pkg/apis/apps/v1/conversion.go","code":"func Convert_apps_DaemonSet_To_v1_DaemonSet(in *apps.DaemonSet, out *appsv1.DaemonSet, s conversion.Scope) error {\n\tif err := autoConvert_apps_DaemonSet_To_v1_DaemonSet(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\tout.Annotations = deepCopyStringMap(out.Annotations) // deep copy annotations because we change them below\n\tout.Annotations[appsv1.DeprecatedTemplateGeneration] = strconv.FormatInt(in.Spec.TemplateGeneration, 10)\n\treturn nil\n}","line":{"from":83,"to":91}} {"id":100001929,"name":"Convert_apps_DaemonSetSpec_To_v1_DaemonSetSpec","signature":"func Convert_apps_DaemonSetSpec_To_v1_DaemonSetSpec(in *apps.DaemonSetSpec, out *appsv1.DaemonSetSpec, s conversion.Scope) error","file":"pkg/apis/apps/v1/conversion.go","code":"// Convert_apps_DaemonSetSpec_To_v1_DaemonSetSpec is defined here, because public\n// conversion is not auto-generated due to existing warnings.\nfunc Convert_apps_DaemonSetSpec_To_v1_DaemonSetSpec(in *apps.DaemonSetSpec, out *appsv1.DaemonSetSpec, s conversion.Scope) error {\n\tif err := autoConvert_apps_DaemonSetSpec_To_v1_DaemonSetSpec(in, out, s); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":93,"to":100}} {"id":100001930,"name":"Convert_v1_DaemonSet_To_apps_DaemonSet","signature":"func Convert_v1_DaemonSet_To_apps_DaemonSet(in *appsv1.DaemonSet, out *apps.DaemonSet, s conversion.Scope) error","file":"pkg/apis/apps/v1/conversion.go","code":"func Convert_v1_DaemonSet_To_apps_DaemonSet(in *appsv1.DaemonSet, out *apps.DaemonSet, s conversion.Scope) error {\n\tif err := autoConvert_v1_DaemonSet_To_apps_DaemonSet(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tif value, ok := in.Annotations[appsv1.DeprecatedTemplateGeneration]; ok {\n\t\tif value64, err := strconv.ParseInt(value, 10, 64); err != nil {\n\t\t\treturn err\n\t\t} else {\n\t\t\tout.Spec.TemplateGeneration = value64\n\t\t\tout.Annotations = deepCopyStringMap(out.Annotations)\n\t\t\tdelete(out.Annotations, appsv1.DeprecatedTemplateGeneration)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":102,"to":116}} {"id":100001931,"name":"deepCopyStringMap","signature":"func deepCopyStringMap(m map[string]string) map[string]string","file":"pkg/apis/apps/v1/conversion.go","code":"func deepCopyStringMap(m map[string]string) map[string]string {\n\tret := make(map[string]string, len(m))\n\tfor k, v := range m {\n\t\tret[k] = v\n\t}\n\treturn ret\n}","line":{"from":118,"to":124}} {"id":100001932,"name":"Convert_v1_StatefulSetSpec_To_apps_StatefulSetSpec","signature":"func Convert_v1_StatefulSetSpec_To_apps_StatefulSetSpec(in *appsv1.StatefulSetSpec, out *apps.StatefulSetSpec, s conversion.Scope) error","file":"pkg/apis/apps/v1/conversion.go","code":"// Convert_apps_StatefulSetSpec_To_v1_StatefulSetSpec augments auto-conversion to preserve \u003c 1.17 behavior\n// setting apiVersion/kind in nested persistent volume claim objects.\nfunc Convert_v1_StatefulSetSpec_To_apps_StatefulSetSpec(in *appsv1.StatefulSetSpec, out *apps.StatefulSetSpec, s conversion.Scope) error {\n\tif err := autoConvert_v1_StatefulSetSpec_To_apps_StatefulSetSpec(in, out, s); err != nil {\n\t\treturn err\n\t}\n\t// set APIVersion/Kind to behave the same as reflective conversion \u003c 1.17.\n\t// see https://issue.k8s.io/87583\n\tif out.VolumeClaimTemplates != nil {\n\t\t// copy so we don't modify the input\n\t\ttemplatesCopy := make([]core.PersistentVolumeClaim, len(out.VolumeClaimTemplates))\n\t\tcopy(templatesCopy, out.VolumeClaimTemplates)\n\t\tout.VolumeClaimTemplates = templatesCopy\n\t\tfor i := range out.VolumeClaimTemplates {\n\t\t\tout.VolumeClaimTemplates[i].APIVersion = \"\"\n\t\t\tout.VolumeClaimTemplates[i].Kind = \"\"\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":126,"to":145}} {"id":100001933,"name":"Convert_apps_StatefulSetSpec_To_v1_StatefulSetSpec","signature":"func Convert_apps_StatefulSetSpec_To_v1_StatefulSetSpec(in *apps.StatefulSetSpec, out *appsv1.StatefulSetSpec, s conversion.Scope) error","file":"pkg/apis/apps/v1/conversion.go","code":"// Convert_apps_StatefulSetSpec_To_v1_StatefulSetSpec augments auto-conversion to preserve \u003c 1.17 behavior\n// setting apiVersion/kind in nested persistent volume claim objects.\nfunc Convert_apps_StatefulSetSpec_To_v1_StatefulSetSpec(in *apps.StatefulSetSpec, out *appsv1.StatefulSetSpec, s conversion.Scope) error {\n\tif err := autoConvert_apps_StatefulSetSpec_To_v1_StatefulSetSpec(in, out, s); err != nil {\n\t\treturn err\n\t}\n\t// set APIVersion/Kind to behave the same as reflective conversion \u003c 1.17.\n\t// see https://issue.k8s.io/87583\n\tif out.VolumeClaimTemplates != nil {\n\t\t// copy so we don't modify the input\n\t\ttemplatesCopy := make([]corev1.PersistentVolumeClaim, len(out.VolumeClaimTemplates))\n\t\tcopy(templatesCopy, out.VolumeClaimTemplates)\n\t\tout.VolumeClaimTemplates = templatesCopy\n\t\tfor i := range out.VolumeClaimTemplates {\n\t\t\tout.VolumeClaimTemplates[i].APIVersion = \"v1\"\n\t\t\tout.VolumeClaimTemplates[i].Kind = \"PersistentVolumeClaim\"\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":147,"to":166}} {"id":100001934,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/apps/v1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":28,"to":30}} {"id":100001935,"name":"SetDefaults_Deployment","signature":"func SetDefaults_Deployment(obj *appsv1.Deployment)","file":"pkg/apis/apps/v1/defaults.go","code":"// SetDefaults_Deployment sets additional defaults compared to its counterpart\n// in extensions. These addons are:\n// - MaxUnavailable during rolling update set to 25% (1 in extensions)\n// - MaxSurge value during rolling update set to 25% (1 in extensions)\n// - RevisionHistoryLimit set to 10 (not set in extensions)\n// - ProgressDeadlineSeconds set to 600s (not set in extensions)\nfunc SetDefaults_Deployment(obj *appsv1.Deployment) {\n\t// Set DeploymentSpec.Replicas to 1 if it is not set.\n\tif obj.Spec.Replicas == nil {\n\t\tobj.Spec.Replicas = new(int32)\n\t\t*obj.Spec.Replicas = 1\n\t}\n\tstrategy := \u0026obj.Spec.Strategy\n\t// Set default DeploymentStrategyType as RollingUpdate.\n\tif strategy.Type == \"\" {\n\t\tstrategy.Type = appsv1.RollingUpdateDeploymentStrategyType\n\t}\n\tif strategy.Type == appsv1.RollingUpdateDeploymentStrategyType {\n\t\tif strategy.RollingUpdate == nil {\n\t\t\trollingUpdate := appsv1.RollingUpdateDeployment{}\n\t\t\tstrategy.RollingUpdate = \u0026rollingUpdate\n\t\t}\n\t\tif strategy.RollingUpdate.MaxUnavailable == nil {\n\t\t\t// Set default MaxUnavailable as 25% by default.\n\t\t\tmaxUnavailable := intstr.FromString(\"25%\")\n\t\t\tstrategy.RollingUpdate.MaxUnavailable = \u0026maxUnavailable\n\t\t}\n\t\tif strategy.RollingUpdate.MaxSurge == nil {\n\t\t\t// Set default MaxSurge as 25% by default.\n\t\t\tmaxSurge := intstr.FromString(\"25%\")\n\t\t\tstrategy.RollingUpdate.MaxSurge = \u0026maxSurge\n\t\t}\n\t}\n\tif obj.Spec.RevisionHistoryLimit == nil {\n\t\tobj.Spec.RevisionHistoryLimit = new(int32)\n\t\t*obj.Spec.RevisionHistoryLimit = 10\n\t}\n\tif obj.Spec.ProgressDeadlineSeconds == nil {\n\t\tobj.Spec.ProgressDeadlineSeconds = new(int32)\n\t\t*obj.Spec.ProgressDeadlineSeconds = 600\n\t}\n}","line":{"from":32,"to":73}} {"id":100001936,"name":"SetDefaults_DaemonSet","signature":"func SetDefaults_DaemonSet(obj *appsv1.DaemonSet)","file":"pkg/apis/apps/v1/defaults.go","code":"func SetDefaults_DaemonSet(obj *appsv1.DaemonSet) {\n\tupdateStrategy := \u0026obj.Spec.UpdateStrategy\n\tif updateStrategy.Type == \"\" {\n\t\tupdateStrategy.Type = appsv1.RollingUpdateDaemonSetStrategyType\n\t}\n\tif updateStrategy.Type == appsv1.RollingUpdateDaemonSetStrategyType {\n\t\tif updateStrategy.RollingUpdate == nil {\n\t\t\trollingUpdate := appsv1.RollingUpdateDaemonSet{}\n\t\t\tupdateStrategy.RollingUpdate = \u0026rollingUpdate\n\t\t}\n\t\tif updateStrategy.RollingUpdate.MaxUnavailable == nil {\n\t\t\t// Set default MaxUnavailable as 1 by default.\n\t\t\tmaxUnavailable := intstr.FromInt(1)\n\t\t\tupdateStrategy.RollingUpdate.MaxUnavailable = \u0026maxUnavailable\n\t\t}\n\t\tif updateStrategy.RollingUpdate.MaxSurge == nil {\n\t\t\t// Set default MaxSurge as 0 by default.\n\t\t\tmaxSurge := intstr.FromInt(0)\n\t\t\tupdateStrategy.RollingUpdate.MaxSurge = \u0026maxSurge\n\t\t}\n\t}\n\tif obj.Spec.RevisionHistoryLimit == nil {\n\t\tobj.Spec.RevisionHistoryLimit = new(int32)\n\t\t*obj.Spec.RevisionHistoryLimit = 10\n\t}\n}","line":{"from":75,"to":100}} {"id":100001937,"name":"SetDefaults_StatefulSet","signature":"func SetDefaults_StatefulSet(obj *appsv1.StatefulSet)","file":"pkg/apis/apps/v1/defaults.go","code":"func SetDefaults_StatefulSet(obj *appsv1.StatefulSet) {\n\tif len(obj.Spec.PodManagementPolicy) == 0 {\n\t\tobj.Spec.PodManagementPolicy = appsv1.OrderedReadyPodManagement\n\t}\n\n\tif obj.Spec.UpdateStrategy.Type == \"\" {\n\t\tobj.Spec.UpdateStrategy.Type = appsv1.RollingUpdateStatefulSetStrategyType\n\n\t\tif obj.Spec.UpdateStrategy.RollingUpdate == nil {\n\t\t\t// UpdateStrategy.RollingUpdate will take default values below.\n\t\t\tobj.Spec.UpdateStrategy.RollingUpdate = \u0026appsv1.RollingUpdateStatefulSetStrategy{}\n\t\t}\n\t}\n\n\tif obj.Spec.UpdateStrategy.Type == appsv1.RollingUpdateStatefulSetStrategyType \u0026\u0026\n\t\tobj.Spec.UpdateStrategy.RollingUpdate != nil {\n\n\t\tif obj.Spec.UpdateStrategy.RollingUpdate.Partition == nil {\n\t\t\tobj.Spec.UpdateStrategy.RollingUpdate.Partition = pointer.Int32(0)\n\t\t}\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.MaxUnavailableStatefulSet) {\n\t\t\tif obj.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable == nil {\n\t\t\t\tmaxUnavailable := intstr.FromInt(1)\n\t\t\t\tobj.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable = \u0026maxUnavailable\n\t\t\t}\n\t\t}\n\t}\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.StatefulSetAutoDeletePVC) {\n\t\tif obj.Spec.PersistentVolumeClaimRetentionPolicy == nil {\n\t\t\tobj.Spec.PersistentVolumeClaimRetentionPolicy = \u0026appsv1.StatefulSetPersistentVolumeClaimRetentionPolicy{}\n\t\t}\n\t\tif len(obj.Spec.PersistentVolumeClaimRetentionPolicy.WhenDeleted) == 0 {\n\t\t\tobj.Spec.PersistentVolumeClaimRetentionPolicy.WhenDeleted = appsv1.RetainPersistentVolumeClaimRetentionPolicyType\n\t\t}\n\t\tif len(obj.Spec.PersistentVolumeClaimRetentionPolicy.WhenScaled) == 0 {\n\t\t\tobj.Spec.PersistentVolumeClaimRetentionPolicy.WhenScaled = appsv1.RetainPersistentVolumeClaimRetentionPolicyType\n\t\t}\n\t}\n\n\tif obj.Spec.Replicas == nil {\n\t\tobj.Spec.Replicas = new(int32)\n\t\t*obj.Spec.Replicas = 1\n\t}\n\tif obj.Spec.RevisionHistoryLimit == nil {\n\t\tobj.Spec.RevisionHistoryLimit = new(int32)\n\t\t*obj.Spec.RevisionHistoryLimit = 10\n\t}\n}","line":{"from":102,"to":150}} {"id":100001938,"name":"SetDefaults_ReplicaSet","signature":"func SetDefaults_ReplicaSet(obj *appsv1.ReplicaSet)","file":"pkg/apis/apps/v1/defaults.go","code":"func SetDefaults_ReplicaSet(obj *appsv1.ReplicaSet) {\n\tif obj.Spec.Replicas == nil {\n\t\tobj.Spec.Replicas = new(int32)\n\t\t*obj.Spec.Replicas = 1\n\t}\n}","line":{"from":151,"to":156}} {"id":100001939,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/apps/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100001940,"name":"init","signature":"func init()","file":"pkg/apis/apps/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":40,"to":45}} {"id":100001941,"name":"addConversionFuncs","signature":"func addConversionFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/apps/v1beta1/conversion.go","code":"func addConversionFuncs(scheme *runtime.Scheme) error {\n\t// Add field label conversions for kinds having selectable nothing but ObjectMeta fields.\n\tif err := scheme.AddFieldLabelConversionFunc(SchemeGroupVersion.WithKind(\"StatefulSet\"),\n\t\tfunc(label, value string) (string, string, error) {\n\t\t\tswitch label {\n\t\t\tcase \"metadata.name\", \"metadata.namespace\", \"status.successful\":\n\t\t\t\treturn label, value, nil\n\t\t\tdefault:\n\t\t\t\treturn \"\", \"\", fmt.Errorf(\"field label not supported for appsv1beta1.StatefulSet: %s\", label)\n\t\t\t}\n\t\t}); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":33,"to":48}} {"id":100001942,"name":"Convert_autoscaling_ScaleStatus_To_v1beta1_ScaleStatus","signature":"func Convert_autoscaling_ScaleStatus_To_v1beta1_ScaleStatus(in *autoscaling.ScaleStatus, out *appsv1beta1.ScaleStatus, s conversion.Scope) error","file":"pkg/apis/apps/v1beta1/conversion.go","code":"func Convert_autoscaling_ScaleStatus_To_v1beta1_ScaleStatus(in *autoscaling.ScaleStatus, out *appsv1beta1.ScaleStatus, s conversion.Scope) error {\n\tout.Replicas = int32(in.Replicas)\n\tout.TargetSelector = in.Selector\n\n\tout.Selector = nil\n\tselector, err := metav1.ParseToLabelSelector(in.Selector)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse selector: %v\", err)\n\t}\n\tif len(selector.MatchExpressions) == 0 {\n\t\tout.Selector = selector.MatchLabels\n\t}\n\n\treturn nil\n}","line":{"from":50,"to":64}} {"id":100001943,"name":"Convert_v1beta1_ScaleStatus_To_autoscaling_ScaleStatus","signature":"func Convert_v1beta1_ScaleStatus_To_autoscaling_ScaleStatus(in *appsv1beta1.ScaleStatus, out *autoscaling.ScaleStatus, s conversion.Scope) error","file":"pkg/apis/apps/v1beta1/conversion.go","code":"func Convert_v1beta1_ScaleStatus_To_autoscaling_ScaleStatus(in *appsv1beta1.ScaleStatus, out *autoscaling.ScaleStatus, s conversion.Scope) error {\n\tout.Replicas = in.Replicas\n\n\tif in.TargetSelector != \"\" {\n\t\tout.Selector = in.TargetSelector\n\t} else if in.Selector != nil {\n\t\tset := labels.Set{}\n\t\tfor key, val := range in.Selector {\n\t\t\tset[key] = val\n\t\t}\n\t\tout.Selector = labels.SelectorFromSet(set).String()\n\t} else {\n\t\tout.Selector = \"\"\n\t}\n\treturn nil\n}","line":{"from":66,"to":81}} {"id":100001944,"name":"Convert_v1beta1_StatefulSetSpec_To_apps_StatefulSetSpec","signature":"func Convert_v1beta1_StatefulSetSpec_To_apps_StatefulSetSpec(in *appsv1beta1.StatefulSetSpec, out *apps.StatefulSetSpec, s conversion.Scope) error","file":"pkg/apis/apps/v1beta1/conversion.go","code":"// Convert_v1beta1_StatefulSetSpec_To_apps_StatefulSetSpec augments auto-conversion to preserve \u003c 1.17 behavior\n// setting apiVersion/kind in nested persistent volume claim objects.\nfunc Convert_v1beta1_StatefulSetSpec_To_apps_StatefulSetSpec(in *appsv1beta1.StatefulSetSpec, out *apps.StatefulSetSpec, s conversion.Scope) error {\n\tif err := autoConvert_v1beta1_StatefulSetSpec_To_apps_StatefulSetSpec(in, out, s); err != nil {\n\t\treturn err\n\t}\n\t// set APIVersion/Kind to behave the same as reflective conversion \u003c 1.17.\n\t// see https://issue.k8s.io/87583\n\tif out.VolumeClaimTemplates != nil {\n\t\t// copy so we don't modify the input\n\t\ttemplatesCopy := make([]core.PersistentVolumeClaim, len(out.VolumeClaimTemplates))\n\t\tcopy(templatesCopy, out.VolumeClaimTemplates)\n\t\tout.VolumeClaimTemplates = templatesCopy\n\t\tfor i := range out.VolumeClaimTemplates {\n\t\t\tout.VolumeClaimTemplates[i].APIVersion = \"\"\n\t\t\tout.VolumeClaimTemplates[i].Kind = \"\"\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":83,"to":102}} {"id":100001945,"name":"Convert_apps_StatefulSetSpec_To_v1beta1_StatefulSetSpec","signature":"func Convert_apps_StatefulSetSpec_To_v1beta1_StatefulSetSpec(in *apps.StatefulSetSpec, out *appsv1beta1.StatefulSetSpec, s conversion.Scope) error","file":"pkg/apis/apps/v1beta1/conversion.go","code":"// Convert_apps_StatefulSetSpec_To_v1beta1_StatefulSetSpec augments auto-conversion to preserve \u003c 1.17 behavior\n// setting apiVersion/kind in nested persistent volume claim objects.\nfunc Convert_apps_StatefulSetSpec_To_v1beta1_StatefulSetSpec(in *apps.StatefulSetSpec, out *appsv1beta1.StatefulSetSpec, s conversion.Scope) error {\n\tif err := autoConvert_apps_StatefulSetSpec_To_v1beta1_StatefulSetSpec(in, out, s); err != nil {\n\t\treturn err\n\t}\n\t// set APIVersion/Kind to behave the same as reflective conversion \u003c 1.17.\n\t// see https://issue.k8s.io/87583\n\tif out.VolumeClaimTemplates != nil {\n\t\t// copy so we don't modify the input\n\t\ttemplatesCopy := make([]corev1.PersistentVolumeClaim, len(out.VolumeClaimTemplates))\n\t\tcopy(templatesCopy, out.VolumeClaimTemplates)\n\t\tout.VolumeClaimTemplates = templatesCopy\n\t\tfor i := range out.VolumeClaimTemplates {\n\t\t\tout.VolumeClaimTemplates[i].APIVersion = \"v1\"\n\t\t\tout.VolumeClaimTemplates[i].Kind = \"PersistentVolumeClaim\"\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":104,"to":123}} {"id":100001946,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/apps/v1beta1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":29,"to":31}} {"id":100001947,"name":"SetDefaults_StatefulSet","signature":"func SetDefaults_StatefulSet(obj *appsv1beta1.StatefulSet)","file":"pkg/apis/apps/v1beta1/defaults.go","code":"func SetDefaults_StatefulSet(obj *appsv1beta1.StatefulSet) {\n\tif len(obj.Spec.PodManagementPolicy) == 0 {\n\t\tobj.Spec.PodManagementPolicy = appsv1beta1.OrderedReadyPodManagement\n\t}\n\n\tif obj.Spec.UpdateStrategy.Type == \"\" {\n\t\tobj.Spec.UpdateStrategy.Type = appsv1beta1.OnDeleteStatefulSetStrategyType\n\t}\n\tlabels := obj.Spec.Template.Labels\n\tif labels != nil {\n\t\tif obj.Spec.Selector == nil {\n\t\t\tobj.Spec.Selector = \u0026metav1.LabelSelector{\n\t\t\t\tMatchLabels: labels,\n\t\t\t}\n\t\t}\n\t\tif len(obj.Labels) == 0 {\n\t\t\tobj.Labels = labels\n\t\t}\n\t}\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.StatefulSetAutoDeletePVC) {\n\t\tif obj.Spec.PersistentVolumeClaimRetentionPolicy == nil {\n\t\t\tobj.Spec.PersistentVolumeClaimRetentionPolicy = \u0026appsv1beta1.StatefulSetPersistentVolumeClaimRetentionPolicy{}\n\t\t}\n\t\tif len(obj.Spec.PersistentVolumeClaimRetentionPolicy.WhenDeleted) == 0 {\n\t\t\tobj.Spec.PersistentVolumeClaimRetentionPolicy.WhenDeleted = appsv1beta1.RetainPersistentVolumeClaimRetentionPolicyType\n\t\t}\n\t\tif len(obj.Spec.PersistentVolumeClaimRetentionPolicy.WhenScaled) == 0 {\n\t\t\tobj.Spec.PersistentVolumeClaimRetentionPolicy.WhenScaled = appsv1beta1.RetainPersistentVolumeClaimRetentionPolicyType\n\t\t}\n\t}\n\n\tif obj.Spec.Replicas == nil {\n\t\tobj.Spec.Replicas = new(int32)\n\t\t*obj.Spec.Replicas = 1\n\t}\n\tif obj.Spec.RevisionHistoryLimit == nil {\n\t\tobj.Spec.RevisionHistoryLimit = new(int32)\n\t\t*obj.Spec.RevisionHistoryLimit = 10\n\t}\n\tif obj.Spec.UpdateStrategy.Type == appsv1beta1.RollingUpdateStatefulSetStrategyType \u0026\u0026\n\t\tobj.Spec.UpdateStrategy.RollingUpdate != nil {\n\n\t\tif obj.Spec.UpdateStrategy.RollingUpdate.Partition == nil {\n\t\t\tobj.Spec.UpdateStrategy.RollingUpdate.Partition = pointer.Int32(0)\n\t\t}\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.MaxUnavailableStatefulSet) {\n\t\t\tif obj.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable == nil {\n\t\t\t\tmaxUnavailable := intstr.FromInt(1)\n\t\t\t\tobj.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable = \u0026maxUnavailable\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":33,"to":86}} {"id":100001948,"name":"SetDefaults_Deployment","signature":"func SetDefaults_Deployment(obj *appsv1beta1.Deployment)","file":"pkg/apis/apps/v1beta1/defaults.go","code":"// SetDefaults_Deployment sets additional defaults compared to its counterpart\n// in extensions. These addons are:\n// - MaxUnavailable during rolling update set to 25% (1 in extensions)\n// - MaxSurge value during rolling update set to 25% (1 in extensions)\n// - RevisionHistoryLimit set to 2 (not set in extensions)\n// - ProgressDeadlineSeconds set to 600s (not set in extensions)\nfunc SetDefaults_Deployment(obj *appsv1beta1.Deployment) {\n\t// Default labels and selector to labels from pod template spec.\n\tlabels := obj.Spec.Template.Labels\n\n\tif labels != nil {\n\t\tif obj.Spec.Selector == nil {\n\t\t\tobj.Spec.Selector = \u0026metav1.LabelSelector{MatchLabels: labels}\n\t\t}\n\t\tif len(obj.Labels) == 0 {\n\t\t\tobj.Labels = labels\n\t\t}\n\t}\n\t// Set appsv1beta1.DeploymentSpec.Replicas to 1 if it is not set.\n\tif obj.Spec.Replicas == nil {\n\t\tobj.Spec.Replicas = new(int32)\n\t\t*obj.Spec.Replicas = 1\n\t}\n\tstrategy := \u0026obj.Spec.Strategy\n\t// Set default appsv1beta1.DeploymentStrategyType as RollingUpdate.\n\tif strategy.Type == \"\" {\n\t\tstrategy.Type = appsv1beta1.RollingUpdateDeploymentStrategyType\n\t}\n\tif strategy.Type == appsv1beta1.RollingUpdateDeploymentStrategyType {\n\t\tif strategy.RollingUpdate == nil {\n\t\t\trollingUpdate := appsv1beta1.RollingUpdateDeployment{}\n\t\t\tstrategy.RollingUpdate = \u0026rollingUpdate\n\t\t}\n\t\tif strategy.RollingUpdate.MaxUnavailable == nil {\n\t\t\t// Set default MaxUnavailable as 25% by default.\n\t\t\tmaxUnavailable := intstr.FromString(\"25%\")\n\t\t\tstrategy.RollingUpdate.MaxUnavailable = \u0026maxUnavailable\n\t\t}\n\t\tif strategy.RollingUpdate.MaxSurge == nil {\n\t\t\t// Set default MaxSurge as 25% by default.\n\t\t\tmaxSurge := intstr.FromString(\"25%\")\n\t\t\tstrategy.RollingUpdate.MaxSurge = \u0026maxSurge\n\t\t}\n\t}\n\tif obj.Spec.RevisionHistoryLimit == nil {\n\t\tobj.Spec.RevisionHistoryLimit = new(int32)\n\t\t*obj.Spec.RevisionHistoryLimit = 2\n\t}\n\tif obj.Spec.ProgressDeadlineSeconds == nil {\n\t\tobj.Spec.ProgressDeadlineSeconds = new(int32)\n\t\t*obj.Spec.ProgressDeadlineSeconds = 600\n\t}\n}","line":{"from":88,"to":140}} {"id":100001949,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/apps/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100001950,"name":"init","signature":"func init()","file":"pkg/apis/apps/v1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs, addConversionFuncs)\n}","line":{"from":40,"to":45}} {"id":100001951,"name":"addConversionFuncs","signature":"func addConversionFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/apps/v1beta2/conversion.go","code":"func addConversionFuncs(scheme *runtime.Scheme) error {\n\t// Add field label conversions for kinds having selectable nothing but ObjectMeta fields.\n\tif err := scheme.AddFieldLabelConversionFunc(SchemeGroupVersion.WithKind(\"StatefulSet\"),\n\t\tfunc(label, value string) (string, string, error) {\n\t\t\tswitch label {\n\t\t\tcase \"metadata.name\", \"metadata.namespace\", \"status.successful\":\n\t\t\t\treturn label, value, nil\n\t\t\tdefault:\n\t\t\t\treturn \"\", \"\", fmt.Errorf(\"field label not supported for appsv1beta2.StatefulSet: %s\", label)\n\t\t\t}\n\t\t}); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":34,"to":49}} {"id":100001952,"name":"Convert_autoscaling_ScaleStatus_To_v1beta2_ScaleStatus","signature":"func Convert_autoscaling_ScaleStatus_To_v1beta2_ScaleStatus(in *autoscaling.ScaleStatus, out *appsv1beta2.ScaleStatus, s conversion.Scope) error","file":"pkg/apis/apps/v1beta2/conversion.go","code":"func Convert_autoscaling_ScaleStatus_To_v1beta2_ScaleStatus(in *autoscaling.ScaleStatus, out *appsv1beta2.ScaleStatus, s conversion.Scope) error {\n\tout.Replicas = int32(in.Replicas)\n\tout.TargetSelector = in.Selector\n\n\tout.Selector = nil\n\tselector, err := metav1.ParseToLabelSelector(in.Selector)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse selector: %v\", err)\n\t}\n\tif len(selector.MatchExpressions) == 0 {\n\t\tout.Selector = selector.MatchLabels\n\t}\n\n\treturn nil\n}","line":{"from":51,"to":65}} {"id":100001953,"name":"Convert_v1beta2_ScaleStatus_To_autoscaling_ScaleStatus","signature":"func Convert_v1beta2_ScaleStatus_To_autoscaling_ScaleStatus(in *appsv1beta2.ScaleStatus, out *autoscaling.ScaleStatus, s conversion.Scope) error","file":"pkg/apis/apps/v1beta2/conversion.go","code":"func Convert_v1beta2_ScaleStatus_To_autoscaling_ScaleStatus(in *appsv1beta2.ScaleStatus, out *autoscaling.ScaleStatus, s conversion.Scope) error {\n\tout.Replicas = in.Replicas\n\n\t// Normally when 2 fields map to the same internal value we favor the old field, since\n\t// old clients can't be expected to know about new fields but clients that know about the\n\t// new field can be expected to know about the old field (though that's not quite true, due\n\t// to kubectl apply). However, these fields are readonly, so any non-nil value should work.\n\tif in.TargetSelector != \"\" {\n\t\tout.Selector = in.TargetSelector\n\t} else if in.Selector != nil {\n\t\tset := labels.Set{}\n\t\tfor key, val := range in.Selector {\n\t\t\tset[key] = val\n\t\t}\n\t\tout.Selector = labels.SelectorFromSet(set).String()\n\t} else {\n\t\tout.Selector = \"\"\n\t}\n\treturn nil\n}","line":{"from":67,"to":86}} {"id":100001954,"name":"Convert_apps_DeploymentSpec_To_v1beta2_DeploymentSpec","signature":"func Convert_apps_DeploymentSpec_To_v1beta2_DeploymentSpec(in *apps.DeploymentSpec, out *appsv1beta2.DeploymentSpec, s conversion.Scope) error","file":"pkg/apis/apps/v1beta2/conversion.go","code":"// Convert_apps_DeploymentSpec_To_v1beta2_DeploymentSpec is defined here, because public\n// conversion is not auto-generated due to existing warnings.\nfunc Convert_apps_DeploymentSpec_To_v1beta2_DeploymentSpec(in *apps.DeploymentSpec, out *appsv1beta2.DeploymentSpec, s conversion.Scope) error {\n\tif err := autoConvert_apps_DeploymentSpec_To_v1beta2_DeploymentSpec(in, out, s); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":88,"to":95}} {"id":100001955,"name":"Convert_v1beta2_Deployment_To_apps_Deployment","signature":"func Convert_v1beta2_Deployment_To_apps_Deployment(in *appsv1beta2.Deployment, out *apps.Deployment, s conversion.Scope) error","file":"pkg/apis/apps/v1beta2/conversion.go","code":"func Convert_v1beta2_Deployment_To_apps_Deployment(in *appsv1beta2.Deployment, out *apps.Deployment, s conversion.Scope) error {\n\tif err := autoConvert_v1beta2_Deployment_To_apps_Deployment(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\t// Copy annotation to deprecated rollbackTo field for roundtrip\n\t// TODO: remove this conversion after we delete extensions/v1beta1 and apps/v1beta1 Deployment\n\tif revision := in.Annotations[appsv1beta2.DeprecatedRollbackTo]; revision != \"\" {\n\t\tif revision64, err := strconv.ParseInt(revision, 10, 64); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to parse annotation[%s]=%s as int64: %v\", appsv1beta2.DeprecatedRollbackTo, revision, err)\n\t\t} else {\n\t\t\tout.Spec.RollbackTo = new(apps.RollbackConfig)\n\t\t\tout.Spec.RollbackTo.Revision = revision64\n\t\t}\n\t\tout.Annotations = deepCopyStringMap(out.Annotations)\n\t\tdelete(out.Annotations, appsv1beta2.DeprecatedRollbackTo)\n\t} else {\n\t\tout.Spec.RollbackTo = nil\n\t}\n\n\treturn nil\n}","line":{"from":97,"to":118}} {"id":100001956,"name":"Convert_apps_Deployment_To_v1beta2_Deployment","signature":"func Convert_apps_Deployment_To_v1beta2_Deployment(in *apps.Deployment, out *appsv1beta2.Deployment, s conversion.Scope) error","file":"pkg/apis/apps/v1beta2/conversion.go","code":"func Convert_apps_Deployment_To_v1beta2_Deployment(in *apps.Deployment, out *appsv1beta2.Deployment, s conversion.Scope) error {\n\tif err := autoConvert_apps_Deployment_To_v1beta2_Deployment(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\tout.Annotations = deepCopyStringMap(out.Annotations) // deep copy because we modify annotations below\n\t// Copy deprecated rollbackTo field to annotation for roundtrip\n\t// TODO: remove this conversion after we delete extensions/v1beta1 and apps/v1beta1 Deployment\n\tif in.Spec.RollbackTo != nil {\n\t\tif out.Annotations == nil {\n\t\t\tout.Annotations = make(map[string]string)\n\t\t}\n\t\tout.Annotations[appsv1beta2.DeprecatedRollbackTo] = strconv.FormatInt(in.Spec.RollbackTo.Revision, 10)\n\t} else {\n\t\tdelete(out.Annotations, appsv1beta2.DeprecatedRollbackTo)\n\t}\n\n\treturn nil\n}","line":{"from":120,"to":138}} {"id":100001957,"name":"Convert_apps_DaemonSet_To_v1beta2_DaemonSet","signature":"func Convert_apps_DaemonSet_To_v1beta2_DaemonSet(in *apps.DaemonSet, out *appsv1beta2.DaemonSet, s conversion.Scope) error","file":"pkg/apis/apps/v1beta2/conversion.go","code":"func Convert_apps_DaemonSet_To_v1beta2_DaemonSet(in *apps.DaemonSet, out *appsv1beta2.DaemonSet, s conversion.Scope) error {\n\tif err := autoConvert_apps_DaemonSet_To_v1beta2_DaemonSet(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\tout.Annotations = deepCopyStringMap(out.Annotations)\n\tout.Annotations[appsv1beta2.DeprecatedTemplateGeneration] = strconv.FormatInt(in.Spec.TemplateGeneration, 10)\n\treturn nil\n}","line":{"from":140,"to":148}} {"id":100001958,"name":"Convert_apps_DaemonSetSpec_To_v1beta2_DaemonSetSpec","signature":"func Convert_apps_DaemonSetSpec_To_v1beta2_DaemonSetSpec(in *apps.DaemonSetSpec, out *appsv1beta2.DaemonSetSpec, s conversion.Scope) error","file":"pkg/apis/apps/v1beta2/conversion.go","code":"// Convert_apps_DaemonSetSpec_To_v1beta2_DaemonSetSpec is defined here, because public\n// conversion is not auto-generated due to existing warnings.\nfunc Convert_apps_DaemonSetSpec_To_v1beta2_DaemonSetSpec(in *apps.DaemonSetSpec, out *appsv1beta2.DaemonSetSpec, s conversion.Scope) error {\n\tif err := autoConvert_apps_DaemonSetSpec_To_v1beta2_DaemonSetSpec(in, out, s); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":150,"to":157}} {"id":100001959,"name":"Convert_v1beta2_DaemonSet_To_apps_DaemonSet","signature":"func Convert_v1beta2_DaemonSet_To_apps_DaemonSet(in *appsv1beta2.DaemonSet, out *apps.DaemonSet, s conversion.Scope) error","file":"pkg/apis/apps/v1beta2/conversion.go","code":"func Convert_v1beta2_DaemonSet_To_apps_DaemonSet(in *appsv1beta2.DaemonSet, out *apps.DaemonSet, s conversion.Scope) error {\n\tif err := autoConvert_v1beta2_DaemonSet_To_apps_DaemonSet(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\tif value, ok := in.Annotations[appsv1beta2.DeprecatedTemplateGeneration]; ok {\n\t\tif value64, err := strconv.ParseInt(value, 10, 64); err != nil {\n\t\t\treturn err\n\t\t} else {\n\t\t\tout.Spec.TemplateGeneration = value64\n\t\t\tout.Annotations = deepCopyStringMap(out.Annotations)\n\t\t\tdelete(out.Annotations, appsv1beta2.DeprecatedTemplateGeneration)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":159,"to":175}} {"id":100001960,"name":"deepCopyStringMap","signature":"func deepCopyStringMap(m map[string]string) map[string]string","file":"pkg/apis/apps/v1beta2/conversion.go","code":"func deepCopyStringMap(m map[string]string) map[string]string {\n\tret := make(map[string]string, len(m))\n\tfor k, v := range m {\n\t\tret[k] = v\n\t}\n\treturn ret\n}","line":{"from":177,"to":183}} {"id":100001961,"name":"Convert_v1beta2_StatefulSetSpec_To_apps_StatefulSetSpec","signature":"func Convert_v1beta2_StatefulSetSpec_To_apps_StatefulSetSpec(in *appsv1beta2.StatefulSetSpec, out *apps.StatefulSetSpec, s conversion.Scope) error","file":"pkg/apis/apps/v1beta2/conversion.go","code":"// Convert_v1beta2_StatefulSetSpec_To_apps_StatefulSetSpec augments auto-conversion to preserve \u003c 1.17 behavior\n// setting apiVersion/kind in nested persistent volume claim objects.\nfunc Convert_v1beta2_StatefulSetSpec_To_apps_StatefulSetSpec(in *appsv1beta2.StatefulSetSpec, out *apps.StatefulSetSpec, s conversion.Scope) error {\n\tif err := autoConvert_v1beta2_StatefulSetSpec_To_apps_StatefulSetSpec(in, out, s); err != nil {\n\t\treturn err\n\t}\n\t// set APIVersion/Kind to behave the same as reflective conversion \u003c 1.17.\n\t// see https://issue.k8s.io/87583\n\tif out.VolumeClaimTemplates != nil {\n\t\t// copy so we don't modify the input\n\t\ttemplatesCopy := make([]core.PersistentVolumeClaim, len(out.VolumeClaimTemplates))\n\t\tcopy(templatesCopy, out.VolumeClaimTemplates)\n\t\tout.VolumeClaimTemplates = templatesCopy\n\t\tfor i := range out.VolumeClaimTemplates {\n\t\t\tout.VolumeClaimTemplates[i].APIVersion = \"\"\n\t\t\tout.VolumeClaimTemplates[i].Kind = \"\"\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":185,"to":204}} {"id":100001962,"name":"Convert_apps_StatefulSetSpec_To_v1beta2_StatefulSetSpec","signature":"func Convert_apps_StatefulSetSpec_To_v1beta2_StatefulSetSpec(in *apps.StatefulSetSpec, out *appsv1beta2.StatefulSetSpec, s conversion.Scope) error","file":"pkg/apis/apps/v1beta2/conversion.go","code":"// Convert_apps_StatefulSetSpec_To_v1beta2_StatefulSetSpec augments auto-conversion to preserve \u003c 1.17 behavior\n// setting apiVersion/kind in nested persistent volume claim objects.\nfunc Convert_apps_StatefulSetSpec_To_v1beta2_StatefulSetSpec(in *apps.StatefulSetSpec, out *appsv1beta2.StatefulSetSpec, s conversion.Scope) error {\n\tif err := autoConvert_apps_StatefulSetSpec_To_v1beta2_StatefulSetSpec(in, out, s); err != nil {\n\t\treturn err\n\t}\n\t// set APIVersion/Kind to behave the same as reflective conversion \u003c 1.17.\n\t// see https://issue.k8s.io/87583\n\tif out.VolumeClaimTemplates != nil {\n\t\t// copy so we don't modify the input\n\t\ttemplatesCopy := make([]corev1.PersistentVolumeClaim, len(out.VolumeClaimTemplates))\n\t\tcopy(templatesCopy, out.VolumeClaimTemplates)\n\t\tout.VolumeClaimTemplates = templatesCopy\n\t\tfor i := range out.VolumeClaimTemplates {\n\t\t\tout.VolumeClaimTemplates[i].APIVersion = \"v1\"\n\t\t\tout.VolumeClaimTemplates[i].Kind = \"PersistentVolumeClaim\"\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":206,"to":225}} {"id":100001963,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/apps/v1beta2/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":28,"to":30}} {"id":100001964,"name":"SetDefaults_DaemonSet","signature":"func SetDefaults_DaemonSet(obj *appsv1beta2.DaemonSet)","file":"pkg/apis/apps/v1beta2/defaults.go","code":"func SetDefaults_DaemonSet(obj *appsv1beta2.DaemonSet) {\n\tupdateStrategy := \u0026obj.Spec.UpdateStrategy\n\tif updateStrategy.Type == \"\" {\n\t\tupdateStrategy.Type = appsv1beta2.RollingUpdateDaemonSetStrategyType\n\t}\n\tif updateStrategy.Type == appsv1beta2.RollingUpdateDaemonSetStrategyType {\n\t\tif updateStrategy.RollingUpdate == nil {\n\t\t\trollingUpdate := appsv1beta2.RollingUpdateDaemonSet{}\n\t\t\tupdateStrategy.RollingUpdate = \u0026rollingUpdate\n\t\t}\n\t\tif updateStrategy.RollingUpdate.MaxUnavailable == nil {\n\t\t\t// Set default MaxUnavailable as 1 by default.\n\t\t\tmaxUnavailable := intstr.FromInt(1)\n\t\t\tupdateStrategy.RollingUpdate.MaxUnavailable = \u0026maxUnavailable\n\t\t}\n\t\tif updateStrategy.RollingUpdate.MaxSurge == nil {\n\t\t\t// Set default MaxSurge as 0 by default.\n\t\t\tmaxSurge := intstr.FromInt(0)\n\t\t\tupdateStrategy.RollingUpdate.MaxSurge = \u0026maxSurge\n\t\t}\n\t}\n\tif obj.Spec.RevisionHistoryLimit == nil {\n\t\tobj.Spec.RevisionHistoryLimit = new(int32)\n\t\t*obj.Spec.RevisionHistoryLimit = 10\n\t}\n}","line":{"from":32,"to":57}} {"id":100001965,"name":"SetDefaults_StatefulSet","signature":"func SetDefaults_StatefulSet(obj *appsv1beta2.StatefulSet)","file":"pkg/apis/apps/v1beta2/defaults.go","code":"func SetDefaults_StatefulSet(obj *appsv1beta2.StatefulSet) {\n\tif len(obj.Spec.PodManagementPolicy) == 0 {\n\t\tobj.Spec.PodManagementPolicy = appsv1beta2.OrderedReadyPodManagement\n\t}\n\n\tif obj.Spec.UpdateStrategy.Type == \"\" {\n\t\tobj.Spec.UpdateStrategy.Type = appsv1beta2.RollingUpdateStatefulSetStrategyType\n\n\t\tif obj.Spec.UpdateStrategy.RollingUpdate == nil {\n\t\t\t// UpdateStrategy.RollingUpdate will take default values below.\n\t\t\tobj.Spec.UpdateStrategy.RollingUpdate = \u0026appsv1beta2.RollingUpdateStatefulSetStrategy{}\n\t\t}\n\t}\n\n\tif obj.Spec.UpdateStrategy.Type == appsv1beta2.RollingUpdateStatefulSetStrategyType \u0026\u0026\n\t\tobj.Spec.UpdateStrategy.RollingUpdate != nil {\n\n\t\tif obj.Spec.UpdateStrategy.RollingUpdate.Partition == nil {\n\t\t\tobj.Spec.UpdateStrategy.RollingUpdate.Partition = pointer.Int32(0)\n\t\t}\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.MaxUnavailableStatefulSet) {\n\t\t\tif obj.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable == nil {\n\t\t\t\tmaxUnavailable := intstr.FromInt(1)\n\t\t\t\tobj.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable = \u0026maxUnavailable\n\t\t\t}\n\t\t}\n\t}\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.StatefulSetAutoDeletePVC) {\n\t\tif obj.Spec.PersistentVolumeClaimRetentionPolicy == nil {\n\t\t\tobj.Spec.PersistentVolumeClaimRetentionPolicy = \u0026appsv1beta2.StatefulSetPersistentVolumeClaimRetentionPolicy{}\n\t\t}\n\t\tif len(obj.Spec.PersistentVolumeClaimRetentionPolicy.WhenDeleted) == 0 {\n\t\t\tobj.Spec.PersistentVolumeClaimRetentionPolicy.WhenDeleted = appsv1beta2.RetainPersistentVolumeClaimRetentionPolicyType\n\t\t}\n\t\tif len(obj.Spec.PersistentVolumeClaimRetentionPolicy.WhenScaled) == 0 {\n\t\t\tobj.Spec.PersistentVolumeClaimRetentionPolicy.WhenScaled = appsv1beta2.RetainPersistentVolumeClaimRetentionPolicyType\n\t\t}\n\t}\n\n\tif obj.Spec.Replicas == nil {\n\t\tobj.Spec.Replicas = new(int32)\n\t\t*obj.Spec.Replicas = 1\n\t}\n\tif obj.Spec.RevisionHistoryLimit == nil {\n\t\tobj.Spec.RevisionHistoryLimit = new(int32)\n\t\t*obj.Spec.RevisionHistoryLimit = 10\n\t}\n}","line":{"from":59,"to":107}} {"id":100001966,"name":"SetDefaults_Deployment","signature":"func SetDefaults_Deployment(obj *appsv1beta2.Deployment)","file":"pkg/apis/apps/v1beta2/defaults.go","code":"// SetDefaults_Deployment sets additional defaults compared to its counterpart\n// in extensions. These addons are:\n// - MaxUnavailable during rolling update set to 25% (1 in extensions)\n// - MaxSurge value during rolling update set to 25% (1 in extensions)\n// - RevisionHistoryLimit set to 10 (not set in extensions)\n// - ProgressDeadlineSeconds set to 600s (not set in extensions)\nfunc SetDefaults_Deployment(obj *appsv1beta2.Deployment) {\n\t// Set appsv1beta2.DeploymentSpec.Replicas to 1 if it is not set.\n\tif obj.Spec.Replicas == nil {\n\t\tobj.Spec.Replicas = new(int32)\n\t\t*obj.Spec.Replicas = 1\n\t}\n\tstrategy := \u0026obj.Spec.Strategy\n\t// Set default appsv1beta2.DeploymentStrategyType as RollingUpdate.\n\tif strategy.Type == \"\" {\n\t\tstrategy.Type = appsv1beta2.RollingUpdateDeploymentStrategyType\n\t}\n\tif strategy.Type == appsv1beta2.RollingUpdateDeploymentStrategyType {\n\t\tif strategy.RollingUpdate == nil {\n\t\t\trollingUpdate := appsv1beta2.RollingUpdateDeployment{}\n\t\t\tstrategy.RollingUpdate = \u0026rollingUpdate\n\t\t}\n\t\tif strategy.RollingUpdate.MaxUnavailable == nil {\n\t\t\t// Set default MaxUnavailable as 25% by default.\n\t\t\tmaxUnavailable := intstr.FromString(\"25%\")\n\t\t\tstrategy.RollingUpdate.MaxUnavailable = \u0026maxUnavailable\n\t\t}\n\t\tif strategy.RollingUpdate.MaxSurge == nil {\n\t\t\t// Set default MaxSurge as 25% by default.\n\t\t\tmaxSurge := intstr.FromString(\"25%\")\n\t\t\tstrategy.RollingUpdate.MaxSurge = \u0026maxSurge\n\t\t}\n\t}\n\tif obj.Spec.RevisionHistoryLimit == nil {\n\t\tobj.Spec.RevisionHistoryLimit = new(int32)\n\t\t*obj.Spec.RevisionHistoryLimit = 10\n\t}\n\tif obj.Spec.ProgressDeadlineSeconds == nil {\n\t\tobj.Spec.ProgressDeadlineSeconds = new(int32)\n\t\t*obj.Spec.ProgressDeadlineSeconds = 600\n\t}\n}","line":{"from":109,"to":150}} {"id":100001967,"name":"SetDefaults_ReplicaSet","signature":"func SetDefaults_ReplicaSet(obj *appsv1beta2.ReplicaSet)","file":"pkg/apis/apps/v1beta2/defaults.go","code":"func SetDefaults_ReplicaSet(obj *appsv1beta2.ReplicaSet) {\n\tif obj.Spec.Replicas == nil {\n\t\tobj.Spec.Replicas = new(int32)\n\t\t*obj.Spec.Replicas = 1\n\t}\n}","line":{"from":152,"to":157}} {"id":100001968,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/apps/v1beta2/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100001969,"name":"init","signature":"func init()","file":"pkg/apis/apps/v1beta2/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs, addConversionFuncs)\n}","line":{"from":40,"to":45}} {"id":100001970,"name":"ValidateStatefulSetName","signature":"func ValidateStatefulSetName(name string, prefix bool) []string","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateStatefulSetName can be used to check whether the given StatefulSet name is valid.\n// Prefix indicates this name will be used as part of generation, in which case\n// trailing dashes are allowed.\nfunc ValidateStatefulSetName(name string, prefix bool) []string {\n\t// TODO: Validate that there's room for the suffix inserted by the pods.\n\t// Currently this is just \"-index\". In the future we may allow a user\n\t// specified list of suffixes and we need to validate the longest one.\n\treturn apimachineryvalidation.NameIsDNSLabel(name, prefix)\n}","line":{"from":36,"to":44}} {"id":100001971,"name":"ValidatePodTemplateSpecForStatefulSet","signature":"func ValidatePodTemplateSpecForStatefulSet(template *api.PodTemplateSpec, selector labels.Selector, fldPath *field.Path, opts apivalidation.PodValidationOptions) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidatePodTemplateSpecForStatefulSet validates the given template and ensures that it is in accordance with the desired selector.\nfunc ValidatePodTemplateSpecForStatefulSet(template *api.PodTemplateSpec, selector labels.Selector, fldPath *field.Path, opts apivalidation.PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif template == nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath, \"\"))\n\t} else {\n\t\tif !selector.Empty() {\n\t\t\t// Verify that the StatefulSet selector matches the labels in template.\n\t\t\tlabels := labels.Set(template.Labels)\n\t\t\tif !selector.Matches(labels) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"metadata\", \"labels\"), template.Labels, \"`selector` does not match template `labels`\"))\n\t\t\t}\n\t\t}\n\t\t// TODO: Add validation for PodSpec, currently this will check volumes, which we know will\n\t\t// fail. We should really check that the union of the given volumes and volumeClaims match\n\t\t// volume mounts in the containers.\n\t\t// allErrs = append(allErrs, apivalidation.ValidatePodTemplateSpec(template, fldPath)...)\n\t\tallErrs = append(allErrs, unversionedvalidation.ValidateLabels(template.Labels, fldPath.Child(\"labels\"))...)\n\t\tallErrs = append(allErrs, apivalidation.ValidateAnnotations(template.Annotations, fldPath.Child(\"annotations\"))...)\n\t\tallErrs = append(allErrs, apivalidation.ValidatePodSpecificAnnotations(template.Annotations, \u0026template.Spec, fldPath.Child(\"annotations\"), opts)...)\n\t}\n\treturn allErrs\n}","line":{"from":46,"to":68}} {"id":100001972,"name":"ValidatePersistentVolumeClaimRetentionPolicyType","signature":"func ValidatePersistentVolumeClaimRetentionPolicyType(policy apps.PersistentVolumeClaimRetentionPolicyType, fldPath *field.Path) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"func ValidatePersistentVolumeClaimRetentionPolicyType(policy apps.PersistentVolumeClaimRetentionPolicyType, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tswitch policy {\n\tcase apps.RetainPersistentVolumeClaimRetentionPolicyType:\n\tcase apps.DeletePersistentVolumeClaimRetentionPolicyType:\n\tdefault:\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath, policy, []string{string(apps.RetainPersistentVolumeClaimRetentionPolicyType), string(apps.DeletePersistentVolumeClaimRetentionPolicyType)}))\n\t}\n\treturn allErrs\n}","line":{"from":70,"to":79}} {"id":100001973,"name":"ValidatePersistentVolumeClaimRetentionPolicy","signature":"func ValidatePersistentVolumeClaimRetentionPolicy(policy *apps.StatefulSetPersistentVolumeClaimRetentionPolicy, fldPath *field.Path) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"func ValidatePersistentVolumeClaimRetentionPolicy(policy *apps.StatefulSetPersistentVolumeClaimRetentionPolicy, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tif policy != nil {\n\t\tallErrs = append(allErrs, ValidatePersistentVolumeClaimRetentionPolicyType(policy.WhenDeleted, fldPath.Child(\"whenDeleted\"))...)\n\t\tallErrs = append(allErrs, ValidatePersistentVolumeClaimRetentionPolicyType(policy.WhenScaled, fldPath.Child(\"whenScaled\"))...)\n\t}\n\treturn allErrs\n}","line":{"from":81,"to":88}} {"id":100001974,"name":"ValidateStatefulSetSpec","signature":"func ValidateStatefulSetSpec(spec *apps.StatefulSetSpec, fldPath *field.Path, opts apivalidation.PodValidationOptions) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateStatefulSetSpec tests if required fields in the StatefulSet spec are set.\nfunc ValidateStatefulSetSpec(spec *apps.StatefulSetSpec, fldPath *field.Path, opts apivalidation.PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tswitch spec.PodManagementPolicy {\n\tcase \"\":\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"podManagementPolicy\"), \"\"))\n\tcase apps.OrderedReadyPodManagement, apps.ParallelPodManagement:\n\tdefault:\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"podManagementPolicy\"), spec.PodManagementPolicy, fmt.Sprintf(\"must be '%s' or '%s'\", apps.OrderedReadyPodManagement, apps.ParallelPodManagement)))\n\t}\n\n\tswitch spec.UpdateStrategy.Type {\n\tcase \"\":\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"updateStrategy\"), \"\"))\n\tcase apps.OnDeleteStatefulSetStrategyType:\n\t\tif spec.UpdateStrategy.RollingUpdate != nil {\n\t\t\tallErrs = append(\n\t\t\t\tallErrs,\n\t\t\t\tfield.Invalid(\n\t\t\t\t\tfldPath.Child(\"updateStrategy\").Child(\"rollingUpdate\"),\n\t\t\t\t\tspec.UpdateStrategy.RollingUpdate,\n\t\t\t\t\tfmt.Sprintf(\"only allowed for updateStrategy '%s'\", apps.RollingUpdateStatefulSetStrategyType)))\n\t\t}\n\tcase apps.RollingUpdateStatefulSetStrategyType:\n\t\tif spec.UpdateStrategy.RollingUpdate != nil {\n\t\t\tallErrs = append(allErrs, validateRollingUpdateStatefulSet(spec.UpdateStrategy.RollingUpdate, fldPath.Child(\"updateStrategy\", \"rollingUpdate\"))...)\n\n\t\t}\n\tdefault:\n\t\tallErrs = append(allErrs,\n\t\t\tfield.Invalid(fldPath.Child(\"updateStrategy\"), spec.UpdateStrategy,\n\t\t\t\tfmt.Sprintf(\"must be '%s' or '%s'\",\n\t\t\t\t\tapps.RollingUpdateStatefulSetStrategyType,\n\t\t\t\t\tapps.OnDeleteStatefulSetStrategyType)))\n\t}\n\n\tallErrs = append(allErrs, ValidatePersistentVolumeClaimRetentionPolicy(spec.PersistentVolumeClaimRetentionPolicy, fldPath.Child(\"persistentVolumeClaimRetentionPolicy\"))...)\n\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(spec.Replicas), fldPath.Child(\"replicas\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(spec.MinReadySeconds), fldPath.Child(\"minReadySeconds\"))...)\n\tif spec.Ordinals != nil {\n\t\treplicaStartOrdinal := spec.Ordinals.Start\n\t\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(replicaStartOrdinal), fldPath.Child(\"ordinals.start\"))...)\n\t}\n\n\tif spec.Selector == nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"selector\"), \"\"))\n\t} else {\n\t\t// validate selector strictly, spec.selector was always required to pass LabelSelectorAsSelector below\n\t\tallErrs = append(allErrs, unversionedvalidation.ValidateLabelSelector(spec.Selector, unversionedvalidation.LabelSelectorValidationOptions{AllowInvalidLabelValueInSelector: false}, fldPath.Child(\"selector\"))...)\n\t\tif len(spec.Selector.MatchLabels)+len(spec.Selector.MatchExpressions) == 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"selector\"), spec.Selector, \"empty selector is invalid for statefulset\"))\n\t\t}\n\t}\n\n\tselector, err := metav1.LabelSelectorAsSelector(spec.Selector)\n\tif err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"selector\"), spec.Selector, \"\"))\n\t} else {\n\t\tallErrs = append(allErrs, ValidatePodTemplateSpecForStatefulSet(\u0026spec.Template, selector, fldPath.Child(\"template\"), opts)...)\n\t}\n\n\tif spec.Template.Spec.RestartPolicy != api.RestartPolicyAlways {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"template\", \"spec\", \"restartPolicy\"), spec.Template.Spec.RestartPolicy, []string{string(api.RestartPolicyAlways)}))\n\t}\n\tif spec.Template.Spec.ActiveDeadlineSeconds != nil {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"template\", \"spec\", \"activeDeadlineSeconds\"), \"activeDeadlineSeconds in StatefulSet is not Supported\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":90,"to":161}} {"id":100001975,"name":"ValidateStatefulSet","signature":"func ValidateStatefulSet(statefulSet *apps.StatefulSet, opts apivalidation.PodValidationOptions) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateStatefulSet validates a StatefulSet.\nfunc ValidateStatefulSet(statefulSet *apps.StatefulSet, opts apivalidation.PodValidationOptions) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMeta(\u0026statefulSet.ObjectMeta, true, ValidateStatefulSetName, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateStatefulSetSpec(\u0026statefulSet.Spec, field.NewPath(\"spec\"), opts)...)\n\treturn allErrs\n}","line":{"from":163,"to":168}} {"id":100001976,"name":"ValidateStatefulSetUpdate","signature":"func ValidateStatefulSetUpdate(statefulSet, oldStatefulSet *apps.StatefulSet, opts apivalidation.PodValidationOptions) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateStatefulSetUpdate tests if required fields in the StatefulSet are set.\nfunc ValidateStatefulSetUpdate(statefulSet, oldStatefulSet *apps.StatefulSet, opts apivalidation.PodValidationOptions) field.ErrorList {\n\t// First, validate that the new statefulset is valid. Don't call\n\t// ValidateStatefulSet() because we don't want to revalidate the name on\n\t// update. This is important here because we used to allow DNS subdomain\n\t// for name, but that can't actually create pods. The only reasonable\n\t// thing to do it delete such an instance, but if there is a finalizer, it\n\t// would need to pass update validation. Name can't change anyway.\n\tallErrs := apivalidation.ValidateObjectMetaUpdate(\u0026statefulSet.ObjectMeta, \u0026oldStatefulSet.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateStatefulSetSpec(\u0026statefulSet.Spec, field.NewPath(\"spec\"), opts)...)\n\n\t// statefulset updates aren't super common and general updates are likely to be touching spec, so we'll do this\n\t// deep copy right away. This avoids mutating our inputs\n\tnewStatefulSetClone := statefulSet.DeepCopy()\n\tnewStatefulSetClone.Spec.Replicas = oldStatefulSet.Spec.Replicas // +k8s:verify-mutation:reason=clone\n\tnewStatefulSetClone.Spec.Template = oldStatefulSet.Spec.Template // +k8s:verify-mutation:reason=clone\n\tnewStatefulSetClone.Spec.UpdateStrategy = oldStatefulSet.Spec.UpdateStrategy // +k8s:verify-mutation:reason=clone\n\tnewStatefulSetClone.Spec.MinReadySeconds = oldStatefulSet.Spec.MinReadySeconds // +k8s:verify-mutation:reason=clone\n\tnewStatefulSetClone.Spec.Ordinals = oldStatefulSet.Spec.Ordinals // +k8s:verify-mutation:reason=clone\n\n\tnewStatefulSetClone.Spec.PersistentVolumeClaimRetentionPolicy = oldStatefulSet.Spec.PersistentVolumeClaimRetentionPolicy // +k8s:verify-mutation:reason=clone\n\tif !apiequality.Semantic.DeepEqual(newStatefulSetClone.Spec, oldStatefulSet.Spec) {\n\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"spec\"), \"updates to statefulset spec for fields other than 'replicas', 'ordinals', 'template', 'updateStrategy', 'persistentVolumeClaimRetentionPolicy' and 'minReadySeconds' are forbidden\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":170,"to":196}} {"id":100001977,"name":"ValidateStatefulSetStatus","signature":"func ValidateStatefulSetStatus(status *apps.StatefulSetStatus, fieldPath *field.Path) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateStatefulSetStatus validates a StatefulSetStatus.\nfunc ValidateStatefulSetStatus(status *apps.StatefulSetStatus, fieldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.Replicas), fieldPath.Child(\"replicas\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.ReadyReplicas), fieldPath.Child(\"readyReplicas\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.CurrentReplicas), fieldPath.Child(\"currentReplicas\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.UpdatedReplicas), fieldPath.Child(\"updatedReplicas\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.AvailableReplicas), fieldPath.Child(\"availableReplicas\"))...)\n\tif status.ObservedGeneration != nil {\n\t\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(*status.ObservedGeneration), fieldPath.Child(\"observedGeneration\"))...)\n\t}\n\tif status.CollisionCount != nil {\n\t\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(*status.CollisionCount), fieldPath.Child(\"collisionCount\"))...)\n\t}\n\n\tmsg := \"cannot be greater than status.replicas\"\n\tif status.ReadyReplicas \u003e status.Replicas {\n\t\tallErrs = append(allErrs, field.Invalid(fieldPath.Child(\"readyReplicas\"), status.ReadyReplicas, msg))\n\t}\n\tif status.CurrentReplicas \u003e status.Replicas {\n\t\tallErrs = append(allErrs, field.Invalid(fieldPath.Child(\"currentReplicas\"), status.CurrentReplicas, msg))\n\t}\n\tif status.UpdatedReplicas \u003e status.Replicas {\n\t\tallErrs = append(allErrs, field.Invalid(fieldPath.Child(\"updatedReplicas\"), status.UpdatedReplicas, msg))\n\t}\n\tif status.AvailableReplicas \u003e status.Replicas {\n\t\tallErrs = append(allErrs, field.Invalid(fieldPath.Child(\"availableReplicas\"), status.AvailableReplicas, msg))\n\t}\n\tif status.AvailableReplicas \u003e status.ReadyReplicas {\n\t\tallErrs = append(allErrs, field.Invalid(fieldPath.Child(\"availableReplicas\"), status.AvailableReplicas, \"cannot be greater than status.readyReplicas\"))\n\t}\n\treturn allErrs\n}","line":{"from":198,"to":231}} {"id":100001978,"name":"ValidateStatefulSetStatusUpdate","signature":"func ValidateStatefulSetStatusUpdate(statefulSet, oldStatefulSet *apps.StatefulSet) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateStatefulSetStatusUpdate tests if required fields in the StatefulSet are set.\nfunc ValidateStatefulSetStatusUpdate(statefulSet, oldStatefulSet *apps.StatefulSet) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, ValidateStatefulSetStatus(\u0026statefulSet.Status, field.NewPath(\"status\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateObjectMetaUpdate(\u0026statefulSet.ObjectMeta, \u0026oldStatefulSet.ObjectMeta, field.NewPath(\"metadata\"))...)\n\t// TODO: Validate status.\n\tif apivalidation.IsDecremented(statefulSet.Status.CollisionCount, oldStatefulSet.Status.CollisionCount) {\n\t\tvalue := int32(0)\n\t\tif statefulSet.Status.CollisionCount != nil {\n\t\t\tvalue = *statefulSet.Status.CollisionCount\n\t\t}\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"status\").Child(\"collisionCount\"), value, \"cannot be decremented\"))\n\t}\n\treturn allErrs\n}","line":{"from":233,"to":247}} {"id":100001979,"name":"ValidateControllerRevision","signature":"func ValidateControllerRevision(revision *apps.ControllerRevision) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateControllerRevision collects errors for the fields of state and returns those errors as an ErrorList. If the\n// returned list is empty, state is valid. Validation is performed to ensure that state is a valid ObjectMeta, its name\n// is valid, and that it doesn't exceed the MaxControllerRevisionSize.\nfunc ValidateControllerRevision(revision *apps.ControllerRevision) field.ErrorList {\n\terrs := field.ErrorList{}\n\n\terrs = append(errs, apivalidation.ValidateObjectMeta(\u0026revision.ObjectMeta, true, ValidateControllerRevisionName, field.NewPath(\"metadata\"))...)\n\tif revision.Data == nil {\n\t\terrs = append(errs, field.Required(field.NewPath(\"data\"), \"data is mandatory\"))\n\t}\n\terrs = append(errs, apivalidation.ValidateNonnegativeField(revision.Revision, field.NewPath(\"revision\"))...)\n\treturn errs\n}","line":{"from":254,"to":266}} {"id":100001980,"name":"ValidateControllerRevisionUpdate","signature":"func ValidateControllerRevisionUpdate(newHistory, oldHistory *apps.ControllerRevision) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateControllerRevisionUpdate collects errors pertaining to the mutation of an ControllerRevision Object. If the\n// returned ErrorList is empty the update operation is valid. Any mutation to the ControllerRevision's Data or Revision\n// is considered to be invalid.\nfunc ValidateControllerRevisionUpdate(newHistory, oldHistory *apps.ControllerRevision) field.ErrorList {\n\terrs := field.ErrorList{}\n\n\terrs = append(errs, apivalidation.ValidateObjectMetaUpdate(\u0026newHistory.ObjectMeta, \u0026oldHistory.ObjectMeta, field.NewPath(\"metadata\"))...)\n\terrs = append(errs, ValidateControllerRevision(newHistory)...)\n\terrs = append(errs, apivalidation.ValidateImmutableField(newHistory.Data, oldHistory.Data, field.NewPath(\"data\"))...)\n\treturn errs\n}","line":{"from":268,"to":278}} {"id":100001981,"name":"ValidateDaemonSet","signature":"func ValidateDaemonSet(ds *apps.DaemonSet, opts apivalidation.PodValidationOptions) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateDaemonSet tests if required fields in the DaemonSet are set.\nfunc ValidateDaemonSet(ds *apps.DaemonSet, opts apivalidation.PodValidationOptions) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMeta(\u0026ds.ObjectMeta, true, ValidateDaemonSetName, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateDaemonSetSpec(\u0026ds.Spec, field.NewPath(\"spec\"), opts)...)\n\treturn allErrs\n}","line":{"from":280,"to":285}} {"id":100001982,"name":"ValidateDaemonSetUpdate","signature":"func ValidateDaemonSetUpdate(ds, oldDS *apps.DaemonSet, opts apivalidation.PodValidationOptions) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateDaemonSetUpdate tests if required fields in the DaemonSet are set.\nfunc ValidateDaemonSetUpdate(ds, oldDS *apps.DaemonSet, opts apivalidation.PodValidationOptions) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMetaUpdate(\u0026ds.ObjectMeta, \u0026oldDS.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateDaemonSetSpecUpdate(\u0026ds.Spec, \u0026oldDS.Spec, field.NewPath(\"spec\"))...)\n\tallErrs = append(allErrs, ValidateDaemonSetSpec(\u0026ds.Spec, field.NewPath(\"spec\"), opts)...)\n\treturn allErrs\n}","line":{"from":287,"to":293}} {"id":100001983,"name":"ValidateDaemonSetSpecUpdate","signature":"func ValidateDaemonSetSpecUpdate(newSpec, oldSpec *apps.DaemonSetSpec, fldPath *field.Path) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateDaemonSetSpecUpdate tests if an update to a DaemonSetSpec is valid.\nfunc ValidateDaemonSetSpecUpdate(newSpec, oldSpec *apps.DaemonSetSpec, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\t// TemplateGeneration shouldn't be decremented\n\tif newSpec.TemplateGeneration \u003c oldSpec.TemplateGeneration {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"templateGeneration\"), newSpec.TemplateGeneration, \"must not be decremented\"))\n\t}\n\n\t// TemplateGeneration should be increased when and only when template is changed\n\ttemplateUpdated := !apiequality.Semantic.DeepEqual(newSpec.Template, oldSpec.Template)\n\tif newSpec.TemplateGeneration == oldSpec.TemplateGeneration \u0026\u0026 templateUpdated {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"templateGeneration\"), newSpec.TemplateGeneration, \"must be incremented upon template update\"))\n\t} else if newSpec.TemplateGeneration \u003e oldSpec.TemplateGeneration \u0026\u0026 !templateUpdated {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"templateGeneration\"), newSpec.TemplateGeneration, \"must not be incremented without template update\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":295,"to":313}} {"id":100001984,"name":"validateDaemonSetStatus","signature":"func validateDaemonSetStatus(status *apps.DaemonSetStatus, fldPath *field.Path) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// validateDaemonSetStatus validates a DaemonSetStatus\nfunc validateDaemonSetStatus(status *apps.DaemonSetStatus, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.CurrentNumberScheduled), fldPath.Child(\"currentNumberScheduled\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.NumberMisscheduled), fldPath.Child(\"numberMisscheduled\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.DesiredNumberScheduled), fldPath.Child(\"desiredNumberScheduled\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.NumberReady), fldPath.Child(\"numberReady\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(status.ObservedGeneration, fldPath.Child(\"observedGeneration\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.UpdatedNumberScheduled), fldPath.Child(\"updatedNumberScheduled\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.NumberAvailable), fldPath.Child(\"numberAvailable\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.NumberUnavailable), fldPath.Child(\"numberUnavailable\"))...)\n\tif status.CollisionCount != nil {\n\t\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(*status.CollisionCount), fldPath.Child(\"collisionCount\"))...)\n\t}\n\treturn allErrs\n}","line":{"from":315,"to":330}} {"id":100001985,"name":"ValidateDaemonSetStatusUpdate","signature":"func ValidateDaemonSetStatusUpdate(ds, oldDS *apps.DaemonSet) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateDaemonSetStatusUpdate tests if required fields in the DaemonSet Status section\nfunc ValidateDaemonSetStatusUpdate(ds, oldDS *apps.DaemonSet) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMetaUpdate(\u0026ds.ObjectMeta, \u0026oldDS.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, validateDaemonSetStatus(\u0026ds.Status, field.NewPath(\"status\"))...)\n\tif apivalidation.IsDecremented(ds.Status.CollisionCount, oldDS.Status.CollisionCount) {\n\t\tvalue := int32(0)\n\t\tif ds.Status.CollisionCount != nil {\n\t\t\tvalue = *ds.Status.CollisionCount\n\t\t}\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"status\").Child(\"collisionCount\"), value, \"cannot be decremented\"))\n\t}\n\treturn allErrs\n}","line":{"from":332,"to":344}} {"id":100001986,"name":"ValidateDaemonSetSpec","signature":"func ValidateDaemonSetSpec(spec *apps.DaemonSetSpec, fldPath *field.Path, opts apivalidation.PodValidationOptions) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateDaemonSetSpec tests if required fields in the DaemonSetSpec are set.\nfunc ValidateDaemonSetSpec(spec *apps.DaemonSetSpec, fldPath *field.Path, opts apivalidation.PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tlabelSelectorValidationOpts := unversionedvalidation.LabelSelectorValidationOptions{AllowInvalidLabelValueInSelector: opts.AllowInvalidLabelValueInSelector}\n\n\tallErrs = append(allErrs, unversionedvalidation.ValidateLabelSelector(spec.Selector, labelSelectorValidationOpts, fldPath.Child(\"selector\"))...)\n\n\tselector, err := metav1.LabelSelectorAsSelector(spec.Selector)\n\tif err == nil \u0026\u0026 !selector.Matches(labels.Set(spec.Template.Labels)) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"template\", \"metadata\", \"labels\"), spec.Template.Labels, \"`selector` does not match template `labels`\"))\n\t}\n\tif spec.Selector != nil \u0026\u0026 len(spec.Selector.MatchLabels)+len(spec.Selector.MatchExpressions) == 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"selector\"), spec.Selector, \"empty selector is invalid for daemonset\"))\n\t}\n\n\tallErrs = append(allErrs, apivalidation.ValidatePodTemplateSpec(\u0026spec.Template, fldPath.Child(\"template\"), opts)...)\n\t// Daemons typically run on more than one node, so mark Read-Write persistent disks as invalid.\n\tallErrs = append(allErrs, apivalidation.ValidateReadOnlyPersistentDisks(spec.Template.Spec.Volumes, fldPath.Child(\"template\", \"spec\", \"volumes\"))...)\n\t// RestartPolicy has already been first-order validated as per ValidatePodTemplateSpec().\n\tif spec.Template.Spec.RestartPolicy != api.RestartPolicyAlways {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"template\", \"spec\", \"restartPolicy\"), spec.Template.Spec.RestartPolicy, []string{string(api.RestartPolicyAlways)}))\n\t}\n\tif spec.Template.Spec.ActiveDeadlineSeconds != nil {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"template\", \"spec\", \"activeDeadlineSeconds\"), \"activeDeadlineSeconds in DaemonSet is not Supported\"))\n\t}\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(spec.MinReadySeconds), fldPath.Child(\"minReadySeconds\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(spec.TemplateGeneration), fldPath.Child(\"templateGeneration\"))...)\n\n\tallErrs = append(allErrs, ValidateDaemonSetUpdateStrategy(\u0026spec.UpdateStrategy, fldPath.Child(\"updateStrategy\"))...)\n\tif spec.RevisionHistoryLimit != nil {\n\t\t// zero is a valid RevisionHistoryLimit\n\t\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(*spec.RevisionHistoryLimit), fldPath.Child(\"revisionHistoryLimit\"))...)\n\t}\n\treturn allErrs\n}","line":{"from":346,"to":380}} {"id":100001987,"name":"ValidateRollingUpdateDaemonSet","signature":"func ValidateRollingUpdateDaemonSet(rollingUpdate *apps.RollingUpdateDaemonSet, fldPath *field.Path) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateRollingUpdateDaemonSet validates a given RollingUpdateDaemonSet.\nfunc ValidateRollingUpdateDaemonSet(rollingUpdate *apps.RollingUpdateDaemonSet, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\n\t// Validate both fields are positive ints or have a percentage value\n\tallErrs = append(allErrs, ValidatePositiveIntOrPercent(rollingUpdate.MaxUnavailable, fldPath.Child(\"maxUnavailable\"))...)\n\tallErrs = append(allErrs, ValidatePositiveIntOrPercent(rollingUpdate.MaxSurge, fldPath.Child(\"maxSurge\"))...)\n\n\t// Validate that MaxUnavailable and MaxSurge are not more than 100%.\n\tallErrs = append(allErrs, IsNotMoreThan100Percent(rollingUpdate.MaxUnavailable, fldPath.Child(\"maxUnavailable\"))...)\n\tallErrs = append(allErrs, IsNotMoreThan100Percent(rollingUpdate.MaxSurge, fldPath.Child(\"maxSurge\"))...)\n\n\t// Validate exactly one of MaxSurge or MaxUnavailable is non-zero\n\thasUnavailable := getIntOrPercentValue(rollingUpdate.MaxUnavailable) != 0\n\thasSurge := getIntOrPercentValue(rollingUpdate.MaxSurge) != 0\n\tswitch {\n\tcase hasUnavailable \u0026\u0026 hasSurge:\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"maxSurge\"), rollingUpdate.MaxSurge, \"may not be set when maxUnavailable is non-zero\"))\n\tcase !hasUnavailable \u0026\u0026 !hasSurge:\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"maxUnavailable\"), \"cannot be 0 when maxSurge is 0\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":382,"to":405}} {"id":100001988,"name":"validateRollingUpdateStatefulSet","signature":"func validateRollingUpdateStatefulSet(rollingUpdate *apps.RollingUpdateStatefulSetStrategy, fldPath *field.Path) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// validateRollingUpdateStatefulSet validates a given RollingUpdateStatefulSet.\nfunc validateRollingUpdateStatefulSet(rollingUpdate *apps.RollingUpdateStatefulSetStrategy, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tfldPathMaxUn := fldPath.Child(\"maxUnavailable\")\n\tallErrs = append(allErrs,\n\t\tapivalidation.ValidateNonnegativeField(\n\t\t\tint64(rollingUpdate.Partition),\n\t\t\tfldPath.Child(\"partition\"))...)\n\tif rollingUpdate.MaxUnavailable != nil {\n\t\tallErrs = append(allErrs, ValidatePositiveIntOrPercent(*rollingUpdate.MaxUnavailable, fldPathMaxUn)...)\n\t\tif getIntOrPercentValue(*rollingUpdate.MaxUnavailable) == 0 {\n\t\t\t// MaxUnavailable cannot be 0.\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPathMaxUn, *rollingUpdate.MaxUnavailable, \"cannot be 0\"))\n\t\t}\n\t\t// Validate that MaxUnavailable is not more than 100%.\n\t\tallErrs = append(allErrs, IsNotMoreThan100Percent(*rollingUpdate.MaxUnavailable, fldPathMaxUn)...)\n\t}\n\treturn allErrs\n}","line":{"from":407,"to":425}} {"id":100001989,"name":"ValidateDaemonSetUpdateStrategy","signature":"func ValidateDaemonSetUpdateStrategy(strategy *apps.DaemonSetUpdateStrategy, fldPath *field.Path) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateDaemonSetUpdateStrategy validates a given DaemonSetUpdateStrategy.\nfunc ValidateDaemonSetUpdateStrategy(strategy *apps.DaemonSetUpdateStrategy, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tswitch strategy.Type {\n\tcase apps.OnDeleteDaemonSetStrategyType:\n\tcase apps.RollingUpdateDaemonSetStrategyType:\n\t\t// Make sure RollingUpdate field isn't nil.\n\t\tif strategy.RollingUpdate == nil {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"rollingUpdate\"), \"\"))\n\t\t\treturn allErrs\n\t\t}\n\t\tallErrs = append(allErrs, ValidateRollingUpdateDaemonSet(strategy.RollingUpdate, fldPath.Child(\"rollingUpdate\"))...)\n\tdefault:\n\t\tvalidValues := []string{string(apps.RollingUpdateDaemonSetStrategyType), string(apps.OnDeleteDaemonSetStrategyType)}\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath, strategy, validValues))\n\t}\n\treturn allErrs\n}","line":{"from":427,"to":444}} {"id":100001990,"name":"ValidatePositiveIntOrPercent","signature":"func ValidatePositiveIntOrPercent(intOrPercent intstr.IntOrString, fldPath *field.Path) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidatePositiveIntOrPercent tests if a given value is a valid int or\n// percentage.\nfunc ValidatePositiveIntOrPercent(intOrPercent intstr.IntOrString, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tswitch intOrPercent.Type {\n\tcase intstr.String:\n\t\tfor _, msg := range validation.IsValidPercent(intOrPercent.StrVal) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, intOrPercent, msg))\n\t\t}\n\tcase intstr.Int:\n\t\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(intOrPercent.IntValue()), fldPath)...)\n\tdefault:\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, intOrPercent, \"must be an integer or percentage (e.g '5%%')\"))\n\t}\n\treturn allErrs\n}","line":{"from":454,"to":469}} {"id":100001991,"name":"getPercentValue","signature":"func getPercentValue(intOrStringValue intstr.IntOrString) (int, bool)","file":"pkg/apis/apps/validation/validation.go","code":"func getPercentValue(intOrStringValue intstr.IntOrString) (int, bool) {\n\tif intOrStringValue.Type != intstr.String {\n\t\treturn 0, false\n\t}\n\tif len(validation.IsValidPercent(intOrStringValue.StrVal)) != 0 {\n\t\treturn 0, false\n\t}\n\tvalue, _ := strconv.Atoi(intOrStringValue.StrVal[:len(intOrStringValue.StrVal)-1])\n\treturn value, true\n}","line":{"from":471,"to":480}} {"id":100001992,"name":"getIntOrPercentValue","signature":"func getIntOrPercentValue(intOrStringValue intstr.IntOrString) int","file":"pkg/apis/apps/validation/validation.go","code":"func getIntOrPercentValue(intOrStringValue intstr.IntOrString) int {\n\tvalue, isPercent := getPercentValue(intOrStringValue)\n\tif isPercent {\n\t\treturn value\n\t}\n\treturn intOrStringValue.IntValue()\n}","line":{"from":482,"to":488}} {"id":100001993,"name":"IsNotMoreThan100Percent","signature":"func IsNotMoreThan100Percent(intOrStringValue intstr.IntOrString, fldPath *field.Path) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// IsNotMoreThan100Percent tests is a value can be represented as a percentage\n// and if this value is not more than 100%.\nfunc IsNotMoreThan100Percent(intOrStringValue intstr.IntOrString, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tvalue, isPercent := getPercentValue(intOrStringValue)\n\tif !isPercent || value \u003c= 100 {\n\t\treturn nil\n\t}\n\tallErrs = append(allErrs, field.Invalid(fldPath, intOrStringValue, \"must not be greater than 100%\"))\n\treturn allErrs\n}","line":{"from":490,"to":500}} {"id":100001994,"name":"ValidateRollingUpdateDeployment","signature":"func ValidateRollingUpdateDeployment(rollingUpdate *apps.RollingUpdateDeployment, fldPath *field.Path) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateRollingUpdateDeployment validates a given RollingUpdateDeployment.\nfunc ValidateRollingUpdateDeployment(rollingUpdate *apps.RollingUpdateDeployment, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, ValidatePositiveIntOrPercent(rollingUpdate.MaxUnavailable, fldPath.Child(\"maxUnavailable\"))...)\n\tallErrs = append(allErrs, ValidatePositiveIntOrPercent(rollingUpdate.MaxSurge, fldPath.Child(\"maxSurge\"))...)\n\tif getIntOrPercentValue(rollingUpdate.MaxUnavailable) == 0 \u0026\u0026 getIntOrPercentValue(rollingUpdate.MaxSurge) == 0 {\n\t\t// Both MaxSurge and MaxUnavailable cannot be zero.\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"maxUnavailable\"), rollingUpdate.MaxUnavailable, \"may not be 0 when `maxSurge` is 0\"))\n\t}\n\t// Validate that MaxUnavailable is not more than 100%.\n\tallErrs = append(allErrs, IsNotMoreThan100Percent(rollingUpdate.MaxUnavailable, fldPath.Child(\"maxUnavailable\"))...)\n\treturn allErrs\n}","line":{"from":502,"to":514}} {"id":100001995,"name":"ValidateDeploymentStrategy","signature":"func ValidateDeploymentStrategy(strategy *apps.DeploymentStrategy, fldPath *field.Path) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateDeploymentStrategy validates given DeploymentStrategy.\nfunc ValidateDeploymentStrategy(strategy *apps.DeploymentStrategy, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tswitch strategy.Type {\n\tcase apps.RecreateDeploymentStrategyType:\n\t\tif strategy.RollingUpdate != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"rollingUpdate\"), \"may not be specified when strategy `type` is '\"+string(apps.RecreateDeploymentStrategyType+\"'\")))\n\t\t}\n\tcase apps.RollingUpdateDeploymentStrategyType:\n\t\t// This should never happen since it's set and checked in defaults.go\n\t\tif strategy.RollingUpdate == nil {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"rollingUpdate\"), \"this should be defaulted and never be nil\"))\n\t\t} else {\n\t\t\tallErrs = append(allErrs, ValidateRollingUpdateDeployment(strategy.RollingUpdate, fldPath.Child(\"rollingUpdate\"))...)\n\t\t}\n\tdefault:\n\t\tvalidValues := []string{string(apps.RecreateDeploymentStrategyType), string(apps.RollingUpdateDeploymentStrategyType)}\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath, strategy, validValues))\n\t}\n\treturn allErrs\n}","line":{"from":516,"to":536}} {"id":100001996,"name":"ValidateRollback","signature":"func ValidateRollback(rollback *apps.RollbackConfig, fldPath *field.Path) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateRollback validates given RollbackConfig.\nfunc ValidateRollback(rollback *apps.RollbackConfig, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tv := rollback.Revision\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(v), fldPath.Child(\"version\"))...)\n\treturn allErrs\n}","line":{"from":538,"to":544}} {"id":100001997,"name":"ValidateDeploymentSpec","signature":"func ValidateDeploymentSpec(spec *apps.DeploymentSpec, fldPath *field.Path, opts apivalidation.PodValidationOptions) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateDeploymentSpec validates given deployment spec.\nfunc ValidateDeploymentSpec(spec *apps.DeploymentSpec, fldPath *field.Path, opts apivalidation.PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(spec.Replicas), fldPath.Child(\"replicas\"))...)\n\n\tif spec.Selector == nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"selector\"), \"\"))\n\t} else {\n\t\t// validate selector strictly, spec.selector was always required to pass LabelSelectorAsSelector below\n\t\tallErrs = append(allErrs, unversionedvalidation.ValidateLabelSelector(spec.Selector, unversionedvalidation.LabelSelectorValidationOptions{AllowInvalidLabelValueInSelector: false}, fldPath.Child(\"selector\"))...)\n\t\tif len(spec.Selector.MatchLabels)+len(spec.Selector.MatchExpressions) == 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"selector\"), spec.Selector, \"empty selector is invalid for deployment\"))\n\t\t}\n\t}\n\n\tselector, err := metav1.LabelSelectorAsSelector(spec.Selector)\n\tif err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"selector\"), spec.Selector, \"invalid label selector\"))\n\t} else {\n\t\tallErrs = append(allErrs, ValidatePodTemplateSpecForReplicaSet(\u0026spec.Template, selector, spec.Replicas, fldPath.Child(\"template\"), opts)...)\n\t}\n\n\tallErrs = append(allErrs, ValidateDeploymentStrategy(\u0026spec.Strategy, fldPath.Child(\"strategy\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(spec.MinReadySeconds), fldPath.Child(\"minReadySeconds\"))...)\n\tif spec.RevisionHistoryLimit != nil {\n\t\t// zero is a valid RevisionHistoryLimit\n\t\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(*spec.RevisionHistoryLimit), fldPath.Child(\"revisionHistoryLimit\"))...)\n\t}\n\tif spec.RollbackTo != nil {\n\t\tallErrs = append(allErrs, ValidateRollback(spec.RollbackTo, fldPath.Child(\"rollback\"))...)\n\t}\n\tif spec.ProgressDeadlineSeconds != nil {\n\t\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(*spec.ProgressDeadlineSeconds), fldPath.Child(\"progressDeadlineSeconds\"))...)\n\t\tif *spec.ProgressDeadlineSeconds \u003c= spec.MinReadySeconds {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"progressDeadlineSeconds\"), spec.ProgressDeadlineSeconds, \"must be greater than minReadySeconds\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":546,"to":584}} {"id":100001998,"name":"ValidateDeploymentStatus","signature":"func ValidateDeploymentStatus(status *apps.DeploymentStatus, fldPath *field.Path) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateDeploymentStatus validates given deployment status.\nfunc ValidateDeploymentStatus(status *apps.DeploymentStatus, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(status.ObservedGeneration, fldPath.Child(\"observedGeneration\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.Replicas), fldPath.Child(\"replicas\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.UpdatedReplicas), fldPath.Child(\"updatedReplicas\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.ReadyReplicas), fldPath.Child(\"readyReplicas\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.AvailableReplicas), fldPath.Child(\"availableReplicas\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.UnavailableReplicas), fldPath.Child(\"unavailableReplicas\"))...)\n\tif status.CollisionCount != nil {\n\t\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(*status.CollisionCount), fldPath.Child(\"collisionCount\"))...)\n\t}\n\tmsg := \"cannot be greater than status.replicas\"\n\tif status.UpdatedReplicas \u003e status.Replicas {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"updatedReplicas\"), status.UpdatedReplicas, msg))\n\t}\n\tif status.ReadyReplicas \u003e status.Replicas {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"readyReplicas\"), status.ReadyReplicas, msg))\n\t}\n\tif status.AvailableReplicas \u003e status.Replicas {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"availableReplicas\"), status.AvailableReplicas, msg))\n\t}\n\tif status.AvailableReplicas \u003e status.ReadyReplicas {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"availableReplicas\"), status.AvailableReplicas, \"cannot be greater than readyReplicas\"))\n\t}\n\treturn allErrs\n}","line":{"from":586,"to":612}} {"id":100001999,"name":"ValidateDeploymentUpdate","signature":"func ValidateDeploymentUpdate(update, old *apps.Deployment, opts apivalidation.PodValidationOptions) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateDeploymentUpdate tests if an update to a Deployment is valid.\nfunc ValidateDeploymentUpdate(update, old *apps.Deployment, opts apivalidation.PodValidationOptions) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMetaUpdate(\u0026update.ObjectMeta, \u0026old.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateDeploymentSpec(\u0026update.Spec, field.NewPath(\"spec\"), opts)...)\n\treturn allErrs\n}","line":{"from":614,"to":619}} {"id":100002000,"name":"ValidateDeploymentStatusUpdate","signature":"func ValidateDeploymentStatusUpdate(update, old *apps.Deployment) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateDeploymentStatusUpdate tests if a an update to a Deployment status\n// is valid.\nfunc ValidateDeploymentStatusUpdate(update, old *apps.Deployment) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMetaUpdate(\u0026update.ObjectMeta, \u0026old.ObjectMeta, field.NewPath(\"metadata\"))\n\tfldPath := field.NewPath(\"status\")\n\tallErrs = append(allErrs, ValidateDeploymentStatus(\u0026update.Status, fldPath)...)\n\tif apivalidation.IsDecremented(update.Status.CollisionCount, old.Status.CollisionCount) {\n\t\tvalue := int32(0)\n\t\tif update.Status.CollisionCount != nil {\n\t\t\tvalue = *update.Status.CollisionCount\n\t\t}\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"collisionCount\"), value, \"cannot be decremented\"))\n\t}\n\treturn allErrs\n}","line":{"from":621,"to":635}} {"id":100002001,"name":"ValidateDeployment","signature":"func ValidateDeployment(obj *apps.Deployment, opts apivalidation.PodValidationOptions) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateDeployment validates a given Deployment.\nfunc ValidateDeployment(obj *apps.Deployment, opts apivalidation.PodValidationOptions) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMeta(\u0026obj.ObjectMeta, true, ValidateDeploymentName, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateDeploymentSpec(\u0026obj.Spec, field.NewPath(\"spec\"), opts)...)\n\treturn allErrs\n}","line":{"from":637,"to":642}} {"id":100002002,"name":"ValidateDeploymentRollback","signature":"func ValidateDeploymentRollback(obj *apps.DeploymentRollback) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateDeploymentRollback validates a given DeploymentRollback.\nfunc ValidateDeploymentRollback(obj *apps.DeploymentRollback) field.ErrorList {\n\tallErrs := apivalidation.ValidateAnnotations(obj.UpdatedAnnotations, field.NewPath(\"updatedAnnotations\"))\n\tif len(obj.Name) == 0 {\n\t\tallErrs = append(allErrs, field.Required(field.NewPath(\"name\"), \"name is required\"))\n\t}\n\tallErrs = append(allErrs, ValidateRollback(\u0026obj.RollbackTo, field.NewPath(\"rollback\"))...)\n\treturn allErrs\n}","line":{"from":644,"to":652}} {"id":100002003,"name":"ValidateReplicaSet","signature":"func ValidateReplicaSet(rs *apps.ReplicaSet, opts apivalidation.PodValidationOptions) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateReplicaSet tests if required fields in the ReplicaSet are set.\nfunc ValidateReplicaSet(rs *apps.ReplicaSet, opts apivalidation.PodValidationOptions) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMeta(\u0026rs.ObjectMeta, true, ValidateReplicaSetName, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateReplicaSetSpec(\u0026rs.Spec, field.NewPath(\"spec\"), opts)...)\n\treturn allErrs\n}","line":{"from":660,"to":665}} {"id":100002004,"name":"ValidateReplicaSetUpdate","signature":"func ValidateReplicaSetUpdate(rs, oldRs *apps.ReplicaSet, opts apivalidation.PodValidationOptions) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateReplicaSetUpdate tests if required fields in the ReplicaSet are set.\nfunc ValidateReplicaSetUpdate(rs, oldRs *apps.ReplicaSet, opts apivalidation.PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, apivalidation.ValidateObjectMetaUpdate(\u0026rs.ObjectMeta, \u0026oldRs.ObjectMeta, field.NewPath(\"metadata\"))...)\n\tallErrs = append(allErrs, ValidateReplicaSetSpec(\u0026rs.Spec, field.NewPath(\"spec\"), opts)...)\n\treturn allErrs\n}","line":{"from":667,"to":673}} {"id":100002005,"name":"ValidateReplicaSetStatusUpdate","signature":"func ValidateReplicaSetStatusUpdate(rs, oldRs *apps.ReplicaSet) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateReplicaSetStatusUpdate tests if required fields in the ReplicaSet are set.\nfunc ValidateReplicaSetStatusUpdate(rs, oldRs *apps.ReplicaSet) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, apivalidation.ValidateObjectMetaUpdate(\u0026rs.ObjectMeta, \u0026oldRs.ObjectMeta, field.NewPath(\"metadata\"))...)\n\tallErrs = append(allErrs, ValidateReplicaSetStatus(rs.Status, field.NewPath(\"status\"))...)\n\treturn allErrs\n}","line":{"from":675,"to":681}} {"id":100002006,"name":"ValidateReplicaSetStatus","signature":"func ValidateReplicaSetStatus(status apps.ReplicaSetStatus, fldPath *field.Path) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateReplicaSetStatus validates a given ReplicaSetStatus.\nfunc ValidateReplicaSetStatus(status apps.ReplicaSetStatus, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.Replicas), fldPath.Child(\"replicas\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.FullyLabeledReplicas), fldPath.Child(\"fullyLabeledReplicas\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.ReadyReplicas), fldPath.Child(\"readyReplicas\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.AvailableReplicas), fldPath.Child(\"availableReplicas\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.ObservedGeneration), fldPath.Child(\"observedGeneration\"))...)\n\tmsg := \"cannot be greater than status.replicas\"\n\tif status.FullyLabeledReplicas \u003e status.Replicas {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"fullyLabeledReplicas\"), status.FullyLabeledReplicas, msg))\n\t}\n\tif status.ReadyReplicas \u003e status.Replicas {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"readyReplicas\"), status.ReadyReplicas, msg))\n\t}\n\tif status.AvailableReplicas \u003e status.Replicas {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"availableReplicas\"), status.AvailableReplicas, msg))\n\t}\n\tif status.AvailableReplicas \u003e status.ReadyReplicas {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"availableReplicas\"), status.AvailableReplicas, \"cannot be greater than readyReplicas\"))\n\t}\n\treturn allErrs\n}","line":{"from":683,"to":705}} {"id":100002007,"name":"ValidateReplicaSetSpec","signature":"func ValidateReplicaSetSpec(spec *apps.ReplicaSetSpec, fldPath *field.Path, opts apivalidation.PodValidationOptions) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidateReplicaSetSpec tests if required fields in the ReplicaSet spec are set.\nfunc ValidateReplicaSetSpec(spec *apps.ReplicaSetSpec, fldPath *field.Path, opts apivalidation.PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(spec.Replicas), fldPath.Child(\"replicas\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(spec.MinReadySeconds), fldPath.Child(\"minReadySeconds\"))...)\n\n\tif spec.Selector == nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"selector\"), \"\"))\n\t} else {\n\t\t// validate selector strictly, spec.selector was always required to pass LabelSelectorAsSelector below\n\t\tallErrs = append(allErrs, unversionedvalidation.ValidateLabelSelector(spec.Selector, unversionedvalidation.LabelSelectorValidationOptions{AllowInvalidLabelValueInSelector: false}, fldPath.Child(\"selector\"))...)\n\t\tif len(spec.Selector.MatchLabels)+len(spec.Selector.MatchExpressions) == 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"selector\"), spec.Selector, \"empty selector is invalid for deployment\"))\n\t\t}\n\t}\n\n\tselector, err := metav1.LabelSelectorAsSelector(spec.Selector)\n\tif err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"selector\"), spec.Selector, \"invalid label selector\"))\n\t} else {\n\t\tallErrs = append(allErrs, ValidatePodTemplateSpecForReplicaSet(\u0026spec.Template, selector, spec.Replicas, fldPath.Child(\"template\"), opts)...)\n\t}\n\treturn allErrs\n}","line":{"from":707,"to":731}} {"id":100002008,"name":"ValidatePodTemplateSpecForReplicaSet","signature":"func ValidatePodTemplateSpecForReplicaSet(template *api.PodTemplateSpec, selector labels.Selector, replicas int32, fldPath *field.Path, opts apivalidation.PodValidationOptions) field.ErrorList","file":"pkg/apis/apps/validation/validation.go","code":"// ValidatePodTemplateSpecForReplicaSet validates the given template and ensures that it is in accordance with the desired selector and replicas.\nfunc ValidatePodTemplateSpecForReplicaSet(template *api.PodTemplateSpec, selector labels.Selector, replicas int32, fldPath *field.Path, opts apivalidation.PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif template == nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath, \"\"))\n\t} else {\n\t\tif !selector.Empty() {\n\t\t\t// Verify that the ReplicaSet selector matches the labels in template.\n\t\t\tlabels := labels.Set(template.Labels)\n\t\t\tif !selector.Matches(labels) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"metadata\", \"labels\"), template.Labels, \"`selector` does not match template `labels`\"))\n\t\t\t}\n\t\t}\n\t\tallErrs = append(allErrs, apivalidation.ValidatePodTemplateSpec(template, fldPath, opts)...)\n\t\tif replicas \u003e 1 {\n\t\t\tallErrs = append(allErrs, apivalidation.ValidateReadOnlyPersistentDisks(template.Spec.Volumes, fldPath.Child(\"spec\", \"volumes\"))...)\n\t\t}\n\t\t// RestartPolicy has already been first-order validated as per ValidatePodTemplateSpec().\n\t\tif template.Spec.RestartPolicy != api.RestartPolicyAlways {\n\t\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"spec\", \"restartPolicy\"), template.Spec.RestartPolicy, []string{string(api.RestartPolicyAlways)}))\n\t\t}\n\t\tif template.Spec.ActiveDeadlineSeconds != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"spec\", \"activeDeadlineSeconds\"), \"activeDeadlineSeconds in ReplicaSet is not Supported\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":733,"to":759}} {"id":100002009,"name":"init","signature":"func init()","file":"pkg/apis/authentication/install/install.go","code":"func init() {\n\tInstall(legacyscheme.Scheme)\n}","line":{"from":31,"to":33}} {"id":100002010,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"pkg/apis/authentication/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(authentication.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(v1alpha1.AddToScheme(scheme))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1.SchemeGroupVersion, v1beta1.SchemeGroupVersion, v1alpha1.SchemeGroupVersion))\n}","line":{"from":35,"to":42}} {"id":100002011,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"pkg/apis/authentication/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100002012,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/authentication/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100002013,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/authentication/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026TokenReview{},\n\t\t\u0026TokenRequest{},\n\t\t\u0026SelfSubjectReview{},\n\t)\n\treturn nil\n}","line":{"from":47,"to":54}} {"id":100002014,"name":"Convert_v1_UserInfo_To_authentication_UserInfo","signature":"func Convert_v1_UserInfo_To_authentication_UserInfo(in *v1.UserInfo, out *authentication.UserInfo, s conversion.Scope) error","file":"pkg/apis/authentication/v1/conversion.go","code":"// Convert_v1_UserInfo_To_authentication_UserInfo is defined outside the autogenerated file for use by other API packages\nfunc Convert_v1_UserInfo_To_authentication_UserInfo(in *v1.UserInfo, out *authentication.UserInfo, s conversion.Scope) error {\n\treturn autoConvert_v1_UserInfo_To_authentication_UserInfo(in, out, s)\n}","line":{"from":25,"to":28}} {"id":100002015,"name":"Convert_authentication_UserInfo_To_v1_UserInfo","signature":"func Convert_authentication_UserInfo_To_v1_UserInfo(in *authentication.UserInfo, out *v1.UserInfo, s conversion.Scope) error","file":"pkg/apis/authentication/v1/conversion.go","code":"// Convert_authentication_UserInfo_To_v1_UserInfo is defined outside the autogenerated file for use by other API packages\nfunc Convert_authentication_UserInfo_To_v1_UserInfo(in *authentication.UserInfo, out *v1.UserInfo, s conversion.Scope) error {\n\treturn autoConvert_authentication_UserInfo_To_v1_UserInfo(in, out, s)\n}","line":{"from":30,"to":33}} {"id":100002016,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/authentication/v1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":24,"to":26}} {"id":100002017,"name":"SetDefaults_TokenRequestSpec","signature":"func SetDefaults_TokenRequestSpec(obj *authenticationv1.TokenRequestSpec)","file":"pkg/apis/authentication/v1/defaults.go","code":"func SetDefaults_TokenRequestSpec(obj *authenticationv1.TokenRequestSpec) {\n\tif obj.ExpirationSeconds == nil {\n\t\thour := int64(60 * 60)\n\t\tobj.ExpirationSeconds = \u0026hour\n\t}\n}","line":{"from":28,"to":33}} {"id":100002018,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/authentication/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002019,"name":"init","signature":"func init()","file":"pkg/apis/authentication/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":40,"to":45}} {"id":100002020,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/authentication/v1alpha1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":23,"to":25}} {"id":100002021,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/authentication/v1alpha1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002022,"name":"init","signature":"func init()","file":"pkg/apis/authentication/v1alpha1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":41,"to":46}} {"id":100002023,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/authentication/v1beta1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":23,"to":25}} {"id":100002024,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/authentication/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002025,"name":"init","signature":"func init()","file":"pkg/apis/authentication/v1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":41,"to":46}} {"id":100002026,"name":"ValidateTokenRequest","signature":"func ValidateTokenRequest(tr *authentication.TokenRequest) field.ErrorList","file":"pkg/apis/authentication/validation/validation.go","code":"// ValidateTokenRequest validates a TokenRequest.\nfunc ValidateTokenRequest(tr *authentication.TokenRequest) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tspecPath := field.NewPath(\"spec\")\n\n\tconst min = 10 * time.Minute\n\tif tr.Spec.ExpirationSeconds \u003c int64(min.Seconds()) {\n\t\tallErrs = append(allErrs, field.Invalid(specPath.Child(\"expirationSeconds\"), tr.Spec.ExpirationSeconds, \"may not specify a duration less than 10 minutes\"))\n\t}\n\tif tr.Spec.ExpirationSeconds \u003e 1\u003c\u003c32 {\n\t\tallErrs = append(allErrs, field.Invalid(specPath.Child(\"expirationSeconds\"), tr.Spec.ExpirationSeconds, \"may not specify a duration larger than 2^32 seconds\"))\n\t}\n\treturn allErrs\n}","line":{"from":28,"to":41}} {"id":100002027,"name":"init","signature":"func init()","file":"pkg/apis/authorization/install/install.go","code":"func init() {\n\tInstall(legacyscheme.Scheme)\n}","line":{"from":30,"to":32}} {"id":100002028,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"pkg/apis/authorization/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(authorization.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1.SchemeGroupVersion, v1beta1.SchemeGroupVersion))\n}","line":{"from":34,"to":40}} {"id":100002029,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"pkg/apis/authorization/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100002030,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/authorization/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100002031,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/authorization/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026SelfSubjectRulesReview{},\n\t\t\u0026SelfSubjectAccessReview{},\n\t\t\u0026SubjectAccessReview{},\n\t\t\u0026LocalSubjectAccessReview{},\n\t)\n\treturn nil\n}","line":{"from":47,"to":55}} {"id":100002032,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/authorization/v1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":23,"to":25}} {"id":100002033,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/authorization/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002034,"name":"init","signature":"func init()","file":"pkg/apis/authorization/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":43,"to":48}} {"id":100002035,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/authorization/v1beta1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":23,"to":25}} {"id":100002036,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/authorization/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002037,"name":"init","signature":"func init()","file":"pkg/apis/authorization/v1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":41,"to":46}} {"id":100002038,"name":"ValidateSubjectAccessReviewSpec","signature":"func ValidateSubjectAccessReviewSpec(spec authorizationapi.SubjectAccessReviewSpec, fldPath *field.Path) field.ErrorList","file":"pkg/apis/authorization/validation/validation.go","code":"// ValidateSubjectAccessReviewSpec validates a SubjectAccessReviewSpec and returns an\n// ErrorList with any errors.\nfunc ValidateSubjectAccessReviewSpec(spec authorizationapi.SubjectAccessReviewSpec, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif spec.ResourceAttributes != nil \u0026\u0026 spec.NonResourceAttributes != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"nonResourceAttributes\"), spec.NonResourceAttributes, `cannot be specified in combination with resourceAttributes`))\n\t}\n\tif spec.ResourceAttributes == nil \u0026\u0026 spec.NonResourceAttributes == nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"resourceAttributes\"), spec.NonResourceAttributes, `exactly one of nonResourceAttributes or resourceAttributes must be specified`))\n\t}\n\tif len(spec.User) == 0 \u0026\u0026 len(spec.Groups) == 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"user\"), spec.User, `at least one of user or group must be specified`))\n\t}\n\n\treturn allErrs\n}","line":{"from":26,"to":41}} {"id":100002039,"name":"ValidateSelfSubjectAccessReviewSpec","signature":"func ValidateSelfSubjectAccessReviewSpec(spec authorizationapi.SelfSubjectAccessReviewSpec, fldPath *field.Path) field.ErrorList","file":"pkg/apis/authorization/validation/validation.go","code":"// ValidateSelfSubjectAccessReviewSpec validates a SelfSubjectAccessReviewSpec and returns an\n// ErrorList with any errors.\nfunc ValidateSelfSubjectAccessReviewSpec(spec authorizationapi.SelfSubjectAccessReviewSpec, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif spec.ResourceAttributes != nil \u0026\u0026 spec.NonResourceAttributes != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"nonResourceAttributes\"), spec.NonResourceAttributes, `cannot be specified in combination with resourceAttributes`))\n\t}\n\tif spec.ResourceAttributes == nil \u0026\u0026 spec.NonResourceAttributes == nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"resourceAttributes\"), spec.NonResourceAttributes, `exactly one of nonResourceAttributes or resourceAttributes must be specified`))\n\t}\n\n\treturn allErrs\n}","line":{"from":43,"to":55}} {"id":100002040,"name":"ValidateSelfSubjectRulesReview","signature":"func ValidateSelfSubjectRulesReview(review *authorizationapi.SelfSubjectRulesReview) field.ErrorList","file":"pkg/apis/authorization/validation/validation.go","code":"// ValidateSelfSubjectRulesReview validates a SelfSubjectRulesReview and returns an\n// ErrorList with any errors.\nfunc ValidateSelfSubjectRulesReview(review *authorizationapi.SelfSubjectRulesReview) field.ErrorList {\n\treturn field.ErrorList{}\n}","line":{"from":57,"to":61}} {"id":100002041,"name":"ValidateSubjectAccessReview","signature":"func ValidateSubjectAccessReview(sar *authorizationapi.SubjectAccessReview) field.ErrorList","file":"pkg/apis/authorization/validation/validation.go","code":"// ValidateSubjectAccessReview validates a SubjectAccessReview and returns an\n// ErrorList with any errors.\nfunc ValidateSubjectAccessReview(sar *authorizationapi.SubjectAccessReview) field.ErrorList {\n\tallErrs := ValidateSubjectAccessReviewSpec(sar.Spec, field.NewPath(\"spec\"))\n\tobjectMetaShallowCopy := sar.ObjectMeta\n\tobjectMetaShallowCopy.ManagedFields = nil\n\tif !apiequality.Semantic.DeepEqual(metav1.ObjectMeta{}, objectMetaShallowCopy) {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"metadata\"), sar.ObjectMeta, `must be empty`))\n\t}\n\treturn allErrs\n}","line":{"from":63,"to":73}} {"id":100002042,"name":"ValidateSelfSubjectAccessReview","signature":"func ValidateSelfSubjectAccessReview(sar *authorizationapi.SelfSubjectAccessReview) field.ErrorList","file":"pkg/apis/authorization/validation/validation.go","code":"// ValidateSelfSubjectAccessReview validates a SelfSubjectAccessReview and returns an\n// ErrorList with any errors.\nfunc ValidateSelfSubjectAccessReview(sar *authorizationapi.SelfSubjectAccessReview) field.ErrorList {\n\tallErrs := ValidateSelfSubjectAccessReviewSpec(sar.Spec, field.NewPath(\"spec\"))\n\tobjectMetaShallowCopy := sar.ObjectMeta\n\tobjectMetaShallowCopy.ManagedFields = nil\n\tif !apiequality.Semantic.DeepEqual(metav1.ObjectMeta{}, objectMetaShallowCopy) {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"metadata\"), sar.ObjectMeta, `must be empty`))\n\t}\n\treturn allErrs\n}","line":{"from":75,"to":85}} {"id":100002043,"name":"ValidateLocalSubjectAccessReview","signature":"func ValidateLocalSubjectAccessReview(sar *authorizationapi.LocalSubjectAccessReview) field.ErrorList","file":"pkg/apis/authorization/validation/validation.go","code":"// ValidateLocalSubjectAccessReview validates a LocalSubjectAccessReview and returns an\n// ErrorList with any errors.\nfunc ValidateLocalSubjectAccessReview(sar *authorizationapi.LocalSubjectAccessReview) field.ErrorList {\n\tallErrs := ValidateSubjectAccessReviewSpec(sar.Spec, field.NewPath(\"spec\"))\n\n\tobjectMetaShallowCopy := sar.ObjectMeta\n\tobjectMetaShallowCopy.Namespace = \"\"\n\tobjectMetaShallowCopy.ManagedFields = nil\n\tif !apiequality.Semantic.DeepEqual(metav1.ObjectMeta{}, objectMetaShallowCopy) {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"metadata\"), sar.ObjectMeta, `must be empty except for namespace`))\n\t}\n\n\tif sar.Spec.ResourceAttributes != nil \u0026\u0026 sar.Spec.ResourceAttributes.Namespace != sar.Namespace {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"spec.resourceAttributes.namespace\"), sar.Spec.ResourceAttributes.Namespace, `must match metadata.namespace`))\n\t}\n\tif sar.Spec.NonResourceAttributes != nil {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"spec.nonResourceAttributes\"), sar.Spec.NonResourceAttributes, `disallowed on this kind of request`))\n\t}\n\n\treturn allErrs\n}","line":{"from":87,"to":107}} {"id":100002044,"name":"DropRoundTripHorizontalPodAutoscalerAnnotations","signature":"func DropRoundTripHorizontalPodAutoscalerAnnotations(in map[string]string) (out map[string]string, copied bool)","file":"pkg/apis/autoscaling/helpers.go","code":"// DropRoundTripHorizontalPodAutoscalerAnnotations removes any annotations used to serialize round-tripped fields from later API versions,\n// and returns false if no changes were made and the original input object was returned.\n// It should always be called when converting internal -\u003e external versions, prior\n// to setting any of the custom annotations:\n//\n//\tannotations, copiedAnnotations := DropRoundTripHorizontalPodAutoscalerAnnotations(externalObj.Annotations)\n//\texternalObj.Annotations = annotations\n//\n//\tif internal.SomeField != nil {\n//\t if !copiedAnnotations {\n//\t externalObj.Annotations = DeepCopyStringMap(externalObj.Annotations)\n//\t copiedAnnotations = true\n//\t }\n//\t externalObj.Annotations[...] = json.Marshal(...)\n//\t}\nfunc DropRoundTripHorizontalPodAutoscalerAnnotations(in map[string]string) (out map[string]string, copied bool) {\n\t_, hasMetricsSpecs := in[MetricSpecsAnnotation]\n\t_, hasBehaviorSpecs := in[BehaviorSpecsAnnotation]\n\t_, hasMetricsStatuses := in[MetricStatusesAnnotation]\n\t_, hasConditions := in[HorizontalPodAutoscalerConditionsAnnotation]\n\tif hasMetricsSpecs || hasBehaviorSpecs || hasMetricsStatuses || hasConditions {\n\t\tout = DeepCopyStringMap(in)\n\t\tdelete(out, MetricSpecsAnnotation)\n\t\tdelete(out, BehaviorSpecsAnnotation)\n\t\tdelete(out, MetricStatusesAnnotation)\n\t\tdelete(out, HorizontalPodAutoscalerConditionsAnnotation)\n\t\treturn out, true\n\t}\n\treturn in, false\n}","line":{"from":19,"to":48}} {"id":100002045,"name":"DeepCopyStringMap","signature":"func DeepCopyStringMap(in map[string]string) map[string]string","file":"pkg/apis/autoscaling/helpers.go","code":"// DeepCopyStringMap returns a copy of the input map.\n// If input is nil, an empty map is returned.\nfunc DeepCopyStringMap(in map[string]string) map[string]string {\n\tout := make(map[string]string, len(in))\n\tfor k, v := range in {\n\t\tout[k] = v\n\t}\n\treturn out\n}","line":{"from":50,"to":58}} {"id":100002046,"name":"init","signature":"func init()","file":"pkg/apis/autoscaling/install/install.go","code":"func init() {\n\tInstall(legacyscheme.Scheme)\n}","line":{"from":32,"to":34}} {"id":100002047,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"pkg/apis/autoscaling/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(autoscaling.AddToScheme(scheme))\n\tutilruntime.Must(v2beta2.AddToScheme(scheme))\n\tutilruntime.Must(v2.AddToScheme(scheme))\n\tutilruntime.Must(v2beta1.AddToScheme(scheme))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v2.SchemeGroupVersion, v1.SchemeGroupVersion, v2beta1.SchemeGroupVersion, v2beta2.SchemeGroupVersion))\n}","line":{"from":36,"to":44}} {"id":100002048,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"pkg/apis/autoscaling/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100002049,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/autoscaling/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100002050,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/autoscaling/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Scale{},\n\t\t\u0026HorizontalPodAutoscaler{},\n\t\t\u0026HorizontalPodAutoscalerList{},\n\t)\n\treturn nil\n}","line":{"from":47,"to":55}} {"id":100002051,"name":"Convert_autoscaling_MetricTarget_To_v1_CrossVersionObjectReference","signature":"func Convert_autoscaling_MetricTarget_To_v1_CrossVersionObjectReference(in *autoscaling.MetricTarget, out *autoscalingv1.CrossVersionObjectReference, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_autoscaling_MetricTarget_To_v1_CrossVersionObjectReference(in *autoscaling.MetricTarget, out *autoscalingv1.CrossVersionObjectReference, s conversion.Scope) error {\n\treturn nil\n}","line":{"from":30,"to":32}} {"id":100002052,"name":"Convert_v1_CrossVersionObjectReference_To_autoscaling_MetricTarget","signature":"func Convert_v1_CrossVersionObjectReference_To_autoscaling_MetricTarget(in *autoscalingv1.CrossVersionObjectReference, out *autoscaling.MetricTarget, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_v1_CrossVersionObjectReference_To_autoscaling_MetricTarget(in *autoscalingv1.CrossVersionObjectReference, out *autoscaling.MetricTarget, s conversion.Scope) error {\n\treturn nil\n}","line":{"from":34,"to":36}} {"id":100002053,"name":"Convert_autoscaling_ExternalMetricSource_To_v1_ExternalMetricSource","signature":"func Convert_autoscaling_ExternalMetricSource_To_v1_ExternalMetricSource(in *autoscaling.ExternalMetricSource, out *autoscalingv1.ExternalMetricSource, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_autoscaling_ExternalMetricSource_To_v1_ExternalMetricSource(in *autoscaling.ExternalMetricSource, out *autoscalingv1.ExternalMetricSource, s conversion.Scope) error {\n\tout.MetricName = in.Metric.Name\n\tout.TargetValue = in.Target.Value\n\tout.TargetAverageValue = in.Target.AverageValue\n\tout.MetricSelector = in.Metric.Selector\n\treturn nil\n}","line":{"from":38,"to":44}} {"id":100002054,"name":"Convert_v1_ExternalMetricSource_To_autoscaling_ExternalMetricSource","signature":"func Convert_v1_ExternalMetricSource_To_autoscaling_ExternalMetricSource(in *autoscalingv1.ExternalMetricSource, out *autoscaling.ExternalMetricSource, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_v1_ExternalMetricSource_To_autoscaling_ExternalMetricSource(in *autoscalingv1.ExternalMetricSource, out *autoscaling.ExternalMetricSource, s conversion.Scope) error {\n\tvalue := in.TargetValue\n\taverageValue := in.TargetAverageValue\n\tvar metricType autoscaling.MetricTargetType\n\tif value == nil {\n\t\tmetricType = autoscaling.AverageValueMetricType\n\t} else {\n\t\tmetricType = autoscaling.ValueMetricType\n\t}\n\tout.Target = autoscaling.MetricTarget{\n\t\tType: metricType,\n\t\tValue: value,\n\t\tAverageValue: averageValue,\n\t}\n\n\tout.Metric = autoscaling.MetricIdentifier{\n\t\tName: in.MetricName,\n\t\tSelector: in.MetricSelector,\n\t}\n\treturn nil\n}","line":{"from":46,"to":66}} {"id":100002055,"name":"Convert_autoscaling_ObjectMetricSource_To_v1_ObjectMetricSource","signature":"func Convert_autoscaling_ObjectMetricSource_To_v1_ObjectMetricSource(in *autoscaling.ObjectMetricSource, out *autoscalingv1.ObjectMetricSource, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_autoscaling_ObjectMetricSource_To_v1_ObjectMetricSource(in *autoscaling.ObjectMetricSource, out *autoscalingv1.ObjectMetricSource, s conversion.Scope) error {\n\tif in.Target.Value != nil {\n\t\tout.TargetValue = *in.Target.Value\n\t}\n\tout.AverageValue = in.Target.AverageValue\n\tout.Target = autoscalingv1.CrossVersionObjectReference{\n\t\tKind: in.DescribedObject.Kind,\n\t\tName: in.DescribedObject.Name,\n\t\tAPIVersion: in.DescribedObject.APIVersion,\n\t}\n\tout.MetricName = in.Metric.Name\n\tout.Selector = in.Metric.Selector\n\treturn nil\n}","line":{"from":68,"to":81}} {"id":100002056,"name":"Convert_v1_ObjectMetricSource_To_autoscaling_ObjectMetricSource","signature":"func Convert_v1_ObjectMetricSource_To_autoscaling_ObjectMetricSource(in *autoscalingv1.ObjectMetricSource, out *autoscaling.ObjectMetricSource, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_v1_ObjectMetricSource_To_autoscaling_ObjectMetricSource(in *autoscalingv1.ObjectMetricSource, out *autoscaling.ObjectMetricSource, s conversion.Scope) error {\n\tvar metricType autoscaling.MetricTargetType\n\tif in.AverageValue == nil {\n\t\tmetricType = autoscaling.ValueMetricType\n\t} else {\n\t\tmetricType = autoscaling.AverageValueMetricType\n\t}\n\n\tout.Target = autoscaling.MetricTarget{\n\t\tType: metricType,\n\t\tValue: \u0026in.TargetValue,\n\t\tAverageValue: in.AverageValue,\n\t}\n\tout.DescribedObject = autoscaling.CrossVersionObjectReference{\n\t\tKind: in.Target.Kind,\n\t\tName: in.Target.Name,\n\t\tAPIVersion: in.Target.APIVersion,\n\t}\n\tout.Metric = autoscaling.MetricIdentifier{\n\t\tName: in.MetricName,\n\t\tSelector: in.Selector,\n\t}\n\treturn nil\n}","line":{"from":83,"to":106}} {"id":100002057,"name":"Convert_autoscaling_PodsMetricSource_To_v1_PodsMetricSource","signature":"func Convert_autoscaling_PodsMetricSource_To_v1_PodsMetricSource(in *autoscaling.PodsMetricSource, out *autoscalingv1.PodsMetricSource, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_autoscaling_PodsMetricSource_To_v1_PodsMetricSource(in *autoscaling.PodsMetricSource, out *autoscalingv1.PodsMetricSource, s conversion.Scope) error {\n\tif in.Target.AverageValue != nil {\n\t\tout.TargetAverageValue = *in.Target.AverageValue\n\t}\n\n\tout.MetricName = in.Metric.Name\n\tout.Selector = in.Metric.Selector\n\treturn nil\n}","line":{"from":108,"to":116}} {"id":100002058,"name":"Convert_v1_PodsMetricSource_To_autoscaling_PodsMetricSource","signature":"func Convert_v1_PodsMetricSource_To_autoscaling_PodsMetricSource(in *autoscalingv1.PodsMetricSource, out *autoscaling.PodsMetricSource, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_v1_PodsMetricSource_To_autoscaling_PodsMetricSource(in *autoscalingv1.PodsMetricSource, out *autoscaling.PodsMetricSource, s conversion.Scope) error {\n\tmetricType := autoscaling.AverageValueMetricType\n\n\tout.Target = autoscaling.MetricTarget{\n\t\tType: metricType,\n\t\tAverageValue: \u0026in.TargetAverageValue,\n\t}\n\tout.Metric = autoscaling.MetricIdentifier{\n\t\tName: in.MetricName,\n\t\tSelector: in.Selector,\n\t}\n\treturn nil\n}","line":{"from":118,"to":130}} {"id":100002059,"name":"Convert_autoscaling_ExternalMetricStatus_To_v1_ExternalMetricStatus","signature":"func Convert_autoscaling_ExternalMetricStatus_To_v1_ExternalMetricStatus(in *autoscaling.ExternalMetricStatus, out *autoscalingv1.ExternalMetricStatus, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_autoscaling_ExternalMetricStatus_To_v1_ExternalMetricStatus(in *autoscaling.ExternalMetricStatus, out *autoscalingv1.ExternalMetricStatus, s conversion.Scope) error {\n\tout.MetricName = in.Metric.Name\n\tif in.Current.Value != nil {\n\t\tout.CurrentValue = *in.Current.Value\n\t}\n\tif in.Current.AverageValue != nil {\n\t\tout.CurrentAverageValue = in.Current.AverageValue\n\t}\n\tout.MetricSelector = in.Metric.Selector\n\treturn nil\n}","line":{"from":132,"to":142}} {"id":100002060,"name":"Convert_v1_ExternalMetricStatus_To_autoscaling_ExternalMetricStatus","signature":"func Convert_v1_ExternalMetricStatus_To_autoscaling_ExternalMetricStatus(in *autoscalingv1.ExternalMetricStatus, out *autoscaling.ExternalMetricStatus, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_v1_ExternalMetricStatus_To_autoscaling_ExternalMetricStatus(in *autoscalingv1.ExternalMetricStatus, out *autoscaling.ExternalMetricStatus, s conversion.Scope) error {\n\tvalue := in.CurrentValue\n\taverageValue := in.CurrentAverageValue\n\tout.Current = autoscaling.MetricValueStatus{\n\t\tValue: \u0026value,\n\t\tAverageValue: averageValue,\n\t}\n\tout.Metric = autoscaling.MetricIdentifier{\n\t\tName: in.MetricName,\n\t\tSelector: in.MetricSelector,\n\t}\n\treturn nil\n}","line":{"from":144,"to":156}} {"id":100002061,"name":"Convert_autoscaling_ObjectMetricStatus_To_v1_ObjectMetricStatus","signature":"func Convert_autoscaling_ObjectMetricStatus_To_v1_ObjectMetricStatus(in *autoscaling.ObjectMetricStatus, out *autoscalingv1.ObjectMetricStatus, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_autoscaling_ObjectMetricStatus_To_v1_ObjectMetricStatus(in *autoscaling.ObjectMetricStatus, out *autoscalingv1.ObjectMetricStatus, s conversion.Scope) error {\n\tif in.Current.Value != nil {\n\t\tout.CurrentValue = *in.Current.Value\n\t}\n\tif in.Current.AverageValue != nil {\n\t\tcurrentAverageValue := *in.Current.AverageValue\n\t\tout.AverageValue = \u0026currentAverageValue\n\t}\n\tout.Target = autoscalingv1.CrossVersionObjectReference{\n\t\tKind: in.DescribedObject.Kind,\n\t\tName: in.DescribedObject.Name,\n\t\tAPIVersion: in.DescribedObject.APIVersion,\n\t}\n\tout.MetricName = in.Metric.Name\n\tout.Selector = in.Metric.Selector\n\treturn nil\n}","line":{"from":158,"to":174}} {"id":100002062,"name":"Convert_v1_ObjectMetricStatus_To_autoscaling_ObjectMetricStatus","signature":"func Convert_v1_ObjectMetricStatus_To_autoscaling_ObjectMetricStatus(in *autoscalingv1.ObjectMetricStatus, out *autoscaling.ObjectMetricStatus, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_v1_ObjectMetricStatus_To_autoscaling_ObjectMetricStatus(in *autoscalingv1.ObjectMetricStatus, out *autoscaling.ObjectMetricStatus, s conversion.Scope) error {\n\tout.Current = autoscaling.MetricValueStatus{\n\t\tValue: \u0026in.CurrentValue,\n\t\tAverageValue: in.AverageValue,\n\t}\n\tout.DescribedObject = autoscaling.CrossVersionObjectReference{\n\t\tKind: in.Target.Kind,\n\t\tName: in.Target.Name,\n\t\tAPIVersion: in.Target.APIVersion,\n\t}\n\tout.Metric = autoscaling.MetricIdentifier{\n\t\tName: in.MetricName,\n\t\tSelector: in.Selector,\n\t}\n\treturn nil\n}","line":{"from":176,"to":191}} {"id":100002063,"name":"Convert_autoscaling_PodsMetricStatus_To_v1_PodsMetricStatus","signature":"func Convert_autoscaling_PodsMetricStatus_To_v1_PodsMetricStatus(in *autoscaling.PodsMetricStatus, out *autoscalingv1.PodsMetricStatus, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_autoscaling_PodsMetricStatus_To_v1_PodsMetricStatus(in *autoscaling.PodsMetricStatus, out *autoscalingv1.PodsMetricStatus, s conversion.Scope) error {\n\tif in.Current.AverageValue != nil {\n\t\tout.CurrentAverageValue = *in.Current.AverageValue\n\t}\n\tout.MetricName = in.Metric.Name\n\tout.Selector = in.Metric.Selector\n\treturn nil\n}","line":{"from":193,"to":200}} {"id":100002064,"name":"Convert_v1_PodsMetricStatus_To_autoscaling_PodsMetricStatus","signature":"func Convert_v1_PodsMetricStatus_To_autoscaling_PodsMetricStatus(in *autoscalingv1.PodsMetricStatus, out *autoscaling.PodsMetricStatus, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_v1_PodsMetricStatus_To_autoscaling_PodsMetricStatus(in *autoscalingv1.PodsMetricStatus, out *autoscaling.PodsMetricStatus, s conversion.Scope) error {\n\tout.Current = autoscaling.MetricValueStatus{\n\t\tAverageValue: \u0026in.CurrentAverageValue,\n\t}\n\tout.Metric = autoscaling.MetricIdentifier{\n\t\tName: in.MetricName,\n\t\tSelector: in.Selector,\n\t}\n\treturn nil\n}","line":{"from":202,"to":211}} {"id":100002065,"name":"Convert_v1_ResourceMetricSource_To_autoscaling_ResourceMetricSource","signature":"func Convert_v1_ResourceMetricSource_To_autoscaling_ResourceMetricSource(in *autoscalingv1.ResourceMetricSource, out *autoscaling.ResourceMetricSource, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_v1_ResourceMetricSource_To_autoscaling_ResourceMetricSource(in *autoscalingv1.ResourceMetricSource, out *autoscaling.ResourceMetricSource, s conversion.Scope) error {\n\tout.Name = core.ResourceName(in.Name)\n\tutilization := in.TargetAverageUtilization\n\taverageValue := in.TargetAverageValue\n\tvar metricType autoscaling.MetricTargetType\n\tif utilization == nil {\n\t\tmetricType = autoscaling.AverageValueMetricType\n\t} else {\n\t\tmetricType = autoscaling.UtilizationMetricType\n\t}\n\tout.Target = autoscaling.MetricTarget{\n\t\tType: metricType,\n\t\tAverageValue: averageValue,\n\t\tAverageUtilization: utilization,\n\t}\n\treturn nil\n}","line":{"from":213,"to":229}} {"id":100002066,"name":"Convert_autoscaling_ResourceMetricSource_To_v1_ResourceMetricSource","signature":"func Convert_autoscaling_ResourceMetricSource_To_v1_ResourceMetricSource(in *autoscaling.ResourceMetricSource, out *autoscalingv1.ResourceMetricSource, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_autoscaling_ResourceMetricSource_To_v1_ResourceMetricSource(in *autoscaling.ResourceMetricSource, out *autoscalingv1.ResourceMetricSource, s conversion.Scope) error {\n\tout.Name = v1.ResourceName(in.Name)\n\tout.TargetAverageUtilization = in.Target.AverageUtilization\n\tout.TargetAverageValue = in.Target.AverageValue\n\treturn nil\n}","line":{"from":231,"to":236}} {"id":100002067,"name":"Convert_v1_ContainerResourceMetricStatus_To_autoscaling_ContainerResourceMetricStatus","signature":"func Convert_v1_ContainerResourceMetricStatus_To_autoscaling_ContainerResourceMetricStatus(in *autoscalingv1.ContainerResourceMetricStatus, out *autoscaling.ContainerResourceMetricStatus, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_v1_ContainerResourceMetricStatus_To_autoscaling_ContainerResourceMetricStatus(in *autoscalingv1.ContainerResourceMetricStatus, out *autoscaling.ContainerResourceMetricStatus, s conversion.Scope) error {\n\tout.Name = core.ResourceName(in.Name)\n\tout.Container = in.Container\n\tutilization := in.CurrentAverageUtilization\n\taverageValue := \u0026in.CurrentAverageValue\n\tout.Current = autoscaling.MetricValueStatus{\n\t\tAverageValue: averageValue,\n\t\tAverageUtilization: utilization,\n\t}\n\treturn nil\n}","line":{"from":238,"to":248}} {"id":100002068,"name":"Convert_autoscaling_ContainerResourceMetricStatus_To_v1_ContainerResourceMetricStatus","signature":"func Convert_autoscaling_ContainerResourceMetricStatus_To_v1_ContainerResourceMetricStatus(in *autoscaling.ContainerResourceMetricStatus, out *autoscalingv1.ContainerResourceMetricStatus, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_autoscaling_ContainerResourceMetricStatus_To_v1_ContainerResourceMetricStatus(in *autoscaling.ContainerResourceMetricStatus, out *autoscalingv1.ContainerResourceMetricStatus, s conversion.Scope) error {\n\tout.Name = v1.ResourceName(in.Name)\n\tout.Container = in.Container\n\tout.CurrentAverageUtilization = in.Current.AverageUtilization\n\tif in.Current.AverageValue != nil {\n\t\tout.CurrentAverageValue = *in.Current.AverageValue\n\t}\n\treturn nil\n}","line":{"from":250,"to":258}} {"id":100002069,"name":"Convert_v1_ResourceMetricStatus_To_autoscaling_ResourceMetricStatus","signature":"func Convert_v1_ResourceMetricStatus_To_autoscaling_ResourceMetricStatus(in *autoscalingv1.ResourceMetricStatus, out *autoscaling.ResourceMetricStatus, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_v1_ResourceMetricStatus_To_autoscaling_ResourceMetricStatus(in *autoscalingv1.ResourceMetricStatus, out *autoscaling.ResourceMetricStatus, s conversion.Scope) error {\n\tout.Name = core.ResourceName(in.Name)\n\tutilization := in.CurrentAverageUtilization\n\taverageValue := \u0026in.CurrentAverageValue\n\tout.Current = autoscaling.MetricValueStatus{\n\t\tAverageValue: averageValue,\n\t\tAverageUtilization: utilization,\n\t}\n\treturn nil\n}","line":{"from":260,"to":269}} {"id":100002070,"name":"Convert_autoscaling_ResourceMetricStatus_To_v1_ResourceMetricStatus","signature":"func Convert_autoscaling_ResourceMetricStatus_To_v1_ResourceMetricStatus(in *autoscaling.ResourceMetricStatus, out *autoscalingv1.ResourceMetricStatus, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_autoscaling_ResourceMetricStatus_To_v1_ResourceMetricStatus(in *autoscaling.ResourceMetricStatus, out *autoscalingv1.ResourceMetricStatus, s conversion.Scope) error {\n\tout.Name = v1.ResourceName(in.Name)\n\tout.CurrentAverageUtilization = in.Current.AverageUtilization\n\tif in.Current.AverageValue != nil {\n\t\tout.CurrentAverageValue = *in.Current.AverageValue\n\t}\n\treturn nil\n}","line":{"from":271,"to":278}} {"id":100002071,"name":"Convert_autoscaling_HorizontalPodAutoscaler_To_v1_HorizontalPodAutoscaler","signature":"func Convert_autoscaling_HorizontalPodAutoscaler_To_v1_HorizontalPodAutoscaler(in *autoscaling.HorizontalPodAutoscaler, out *autoscalingv1.HorizontalPodAutoscaler, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_autoscaling_HorizontalPodAutoscaler_To_v1_HorizontalPodAutoscaler(in *autoscaling.HorizontalPodAutoscaler, out *autoscalingv1.HorizontalPodAutoscaler, s conversion.Scope) error {\n\tif err := autoConvert_autoscaling_HorizontalPodAutoscaler_To_v1_HorizontalPodAutoscaler(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\t// clear any pre-existing round-trip annotations to make sure the only ones set are ones we produced during conversion\n\tannotations, copiedAnnotations := autoscaling.DropRoundTripHorizontalPodAutoscalerAnnotations(out.Annotations)\n\tout.Annotations = annotations\n\n\totherMetrics := make([]autoscalingv1.MetricSpec, 0, len(in.Spec.Metrics))\n\tfor _, metric := range in.Spec.Metrics {\n\t\tif metric.Type == autoscaling.ResourceMetricSourceType \u0026\u0026 metric.Resource != nil \u0026\u0026 metric.Resource.Name == core.ResourceCPU \u0026\u0026 metric.Resource.Target.AverageUtilization != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tconvMetric := autoscalingv1.MetricSpec{}\n\t\tif err := Convert_autoscaling_MetricSpec_To_v1_MetricSpec(\u0026metric, \u0026convMetric, s); err != nil {\n\t\t\treturn err\n\t\t}\n\t\totherMetrics = append(otherMetrics, convMetric)\n\t}\n\n\t// NB: we need to save the status even if it maps to a CPU utilization status in order to save the raw value as well\n\tcurrentMetrics := make([]autoscalingv1.MetricStatus, len(in.Status.CurrentMetrics))\n\tfor i, currentMetric := range in.Status.CurrentMetrics {\n\t\tif err := Convert_autoscaling_MetricStatus_To_v1_MetricStatus(\u0026currentMetric, \u0026currentMetrics[i], s); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// store HPA conditions in an annotation\n\tcurrentConditions := make([]autoscalingv1.HorizontalPodAutoscalerCondition, len(in.Status.Conditions))\n\tfor i, currentCondition := range in.Status.Conditions {\n\t\tif err := Convert_autoscaling_HorizontalPodAutoscalerCondition_To_v1_HorizontalPodAutoscalerCondition(\u0026currentCondition, \u0026currentConditions[i], s); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif len(otherMetrics) \u003e 0 {\n\t\totherMetricsEnc, err := json.Marshal(otherMetrics)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// copy before mutating\n\t\tif !copiedAnnotations {\n\t\t\tcopiedAnnotations = true\n\t\t\tout.Annotations = autoscaling.DeepCopyStringMap(out.Annotations)\n\t\t}\n\t\tout.Annotations[autoscaling.MetricSpecsAnnotation] = string(otherMetricsEnc)\n\t}\n\n\tif len(in.Status.CurrentMetrics) \u003e 0 {\n\t\tcurrentMetricsEnc, err := json.Marshal(currentMetrics)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// copy before mutating\n\t\tif !copiedAnnotations {\n\t\t\tcopiedAnnotations = true\n\t\t\tout.Annotations = autoscaling.DeepCopyStringMap(out.Annotations)\n\t\t}\n\t\tout.Annotations[autoscaling.MetricStatusesAnnotation] = string(currentMetricsEnc)\n\t}\n\n\tif in.Spec.Behavior != nil {\n\t\t// TODO: this is marshaling an internal type. Fix this without breaking backwards compatibility.\n\t\tbehaviorEnc, err := json.Marshal(in.Spec.Behavior)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// copy before mutating\n\t\tif !copiedAnnotations {\n\t\t\tcopiedAnnotations = true\n\t\t\tout.Annotations = autoscaling.DeepCopyStringMap(out.Annotations)\n\t\t}\n\t\tout.Annotations[autoscaling.BehaviorSpecsAnnotation] = string(behaviorEnc)\n\t}\n\n\tif len(in.Status.Conditions) \u003e 0 {\n\t\tcurrentConditionsEnc, err := json.Marshal(currentConditions)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// copy before mutating\n\t\tif !copiedAnnotations {\n\t\t\t//nolint:ineffassign\n\t\t\tcopiedAnnotations = true\n\t\t\tout.Annotations = autoscaling.DeepCopyStringMap(out.Annotations)\n\t\t}\n\t\tout.Annotations[autoscaling.HorizontalPodAutoscalerConditionsAnnotation] = string(currentConditionsEnc)\n\t}\n\n\treturn nil\n}","line":{"from":280,"to":373}} {"id":100002072,"name":"Convert_v1_HorizontalPodAutoscaler_To_autoscaling_HorizontalPodAutoscaler","signature":"func Convert_v1_HorizontalPodAutoscaler_To_autoscaling_HorizontalPodAutoscaler(in *autoscalingv1.HorizontalPodAutoscaler, out *autoscaling.HorizontalPodAutoscaler, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_v1_HorizontalPodAutoscaler_To_autoscaling_HorizontalPodAutoscaler(in *autoscalingv1.HorizontalPodAutoscaler, out *autoscaling.HorizontalPodAutoscaler, s conversion.Scope) error {\n\tif err := autoConvert_v1_HorizontalPodAutoscaler_To_autoscaling_HorizontalPodAutoscaler(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\tif otherMetricsEnc, hasOtherMetrics := out.Annotations[autoscaling.MetricSpecsAnnotation]; hasOtherMetrics {\n\t\tvar otherMetrics []autoscalingv1.MetricSpec\n\t\tif err := json.Unmarshal([]byte(otherMetricsEnc), \u0026otherMetrics); err == nil {\n\t\t\t// the normal Spec conversion could have populated out.Spec.Metrics with a single element, so deal with that\n\t\t\toutMetrics := make([]autoscaling.MetricSpec, len(otherMetrics)+len(out.Spec.Metrics))\n\t\t\tfor i, metric := range otherMetrics {\n\t\t\t\tif err := Convert_v1_MetricSpec_To_autoscaling_MetricSpec(\u0026metric, \u0026outMetrics[i], s); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif out.Spec.Metrics != nil {\n\t\t\t\toutMetrics[len(otherMetrics)] = out.Spec.Metrics[0]\n\t\t\t}\n\t\t\tout.Spec.Metrics = outMetrics\n\t\t}\n\t}\n\n\tif behaviorEnc, hasConstraints := out.Annotations[autoscaling.BehaviorSpecsAnnotation]; hasConstraints {\n\t\t// TODO: this is unmarshaling an internal type. Fix this without breaking backwards compatibility.\n\t\tvar behavior autoscaling.HorizontalPodAutoscalerBehavior\n\t\tif err := json.Unmarshal([]byte(behaviorEnc), \u0026behavior); err == nil \u0026\u0026 behavior != (autoscaling.HorizontalPodAutoscalerBehavior{}) {\n\t\t\tout.Spec.Behavior = \u0026behavior\n\t\t}\n\t}\n\n\tif currentMetricsEnc, hasCurrentMetrics := out.Annotations[autoscaling.MetricStatusesAnnotation]; hasCurrentMetrics {\n\t\t// ignore any existing status values -- the ones here have more information\n\t\tvar currentMetrics []autoscalingv1.MetricStatus\n\t\tif err := json.Unmarshal([]byte(currentMetricsEnc), \u0026currentMetrics); err == nil {\n\t\t\tout.Status.CurrentMetrics = make([]autoscaling.MetricStatus, len(currentMetrics))\n\t\t\tfor i, currentMetric := range currentMetrics {\n\t\t\t\tif err := Convert_v1_MetricStatus_To_autoscaling_MetricStatus(\u0026currentMetric, \u0026out.Status.CurrentMetrics[i], s); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// autoscaling/v1 formerly had an implicit default applied in the controller. In v2beta1, we apply it explicitly.\n\t// We apply it here, explicitly, since we have access to the full set of metrics from the annotation.\n\tif len(out.Spec.Metrics) == 0 {\n\t\t// no other metrics, no explicit CPU value set\n\t\tout.Spec.Metrics = []autoscaling.MetricSpec{\n\t\t\t{\n\t\t\t\tType: autoscaling.ResourceMetricSourceType,\n\t\t\t\tResource: \u0026autoscaling.ResourceMetricSource{\n\t\t\t\t\tName: core.ResourceCPU,\n\t\t\t\t\tTarget: autoscaling.MetricTarget{\n\t\t\t\t\t\tType: autoscaling.UtilizationMetricType,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\tout.Spec.Metrics[0].Resource.Target.AverageUtilization = new(int32)\n\t\t*out.Spec.Metrics[0].Resource.Target.AverageUtilization = autoscaling.DefaultCPUUtilization\n\t}\n\n\tif currentConditionsEnc, hasCurrentConditions := out.Annotations[autoscaling.HorizontalPodAutoscalerConditionsAnnotation]; hasCurrentConditions {\n\t\tvar currentConditions []autoscalingv1.HorizontalPodAutoscalerCondition\n\t\tif err := json.Unmarshal([]byte(currentConditionsEnc), \u0026currentConditions); err == nil {\n\t\t\tout.Status.Conditions = make([]autoscaling.HorizontalPodAutoscalerCondition, len(currentConditions))\n\t\t\tfor i, currentCondition := range currentConditions {\n\t\t\t\tif err := Convert_v1_HorizontalPodAutoscalerCondition_To_autoscaling_HorizontalPodAutoscalerCondition(\u0026currentCondition, \u0026out.Status.Conditions[i], s); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// drop round-tripping annotations after converting to internal\n\tout.Annotations, _ = autoscaling.DropRoundTripHorizontalPodAutoscalerAnnotations(out.Annotations)\n\n\treturn nil\n}","line":{"from":375,"to":453}} {"id":100002073,"name":"Convert_autoscaling_HorizontalPodAutoscalerSpec_To_v1_HorizontalPodAutoscalerSpec","signature":"func Convert_autoscaling_HorizontalPodAutoscalerSpec_To_v1_HorizontalPodAutoscalerSpec(in *autoscaling.HorizontalPodAutoscalerSpec, out *autoscalingv1.HorizontalPodAutoscalerSpec, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_autoscaling_HorizontalPodAutoscalerSpec_To_v1_HorizontalPodAutoscalerSpec(in *autoscaling.HorizontalPodAutoscalerSpec, out *autoscalingv1.HorizontalPodAutoscalerSpec, s conversion.Scope) error {\n\tif err := Convert_autoscaling_CrossVersionObjectReference_To_v1_CrossVersionObjectReference(\u0026in.ScaleTargetRef, \u0026out.ScaleTargetRef, s); err != nil {\n\t\treturn err\n\t}\n\n\tout.MinReplicas = in.MinReplicas\n\tout.MaxReplicas = in.MaxReplicas\n\n\tfor _, metric := range in.Metrics {\n\t\tif metric.Type == autoscaling.ResourceMetricSourceType \u0026\u0026 metric.Resource != nil \u0026\u0026 metric.Resource.Name == core.ResourceCPU \u0026\u0026 metric.Resource.Target.AverageUtilization != nil {\n\t\t\tout.TargetCPUUtilizationPercentage = new(int32)\n\t\t\t*out.TargetCPUUtilizationPercentage = *metric.Resource.Target.AverageUtilization\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":455,"to":472}} {"id":100002074,"name":"Convert_v1_HorizontalPodAutoscalerSpec_To_autoscaling_HorizontalPodAutoscalerSpec","signature":"func Convert_v1_HorizontalPodAutoscalerSpec_To_autoscaling_HorizontalPodAutoscalerSpec(in *autoscalingv1.HorizontalPodAutoscalerSpec, out *autoscaling.HorizontalPodAutoscalerSpec, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_v1_HorizontalPodAutoscalerSpec_To_autoscaling_HorizontalPodAutoscalerSpec(in *autoscalingv1.HorizontalPodAutoscalerSpec, out *autoscaling.HorizontalPodAutoscalerSpec, s conversion.Scope) error {\n\tif err := Convert_v1_CrossVersionObjectReference_To_autoscaling_CrossVersionObjectReference(\u0026in.ScaleTargetRef, \u0026out.ScaleTargetRef, s); err != nil {\n\t\treturn err\n\t}\n\n\tout.MinReplicas = in.MinReplicas\n\tout.MaxReplicas = in.MaxReplicas\n\n\tif in.TargetCPUUtilizationPercentage != nil {\n\t\tout.Metrics = []autoscaling.MetricSpec{\n\t\t\t{\n\t\t\t\tType: autoscaling.ResourceMetricSourceType,\n\t\t\t\tResource: \u0026autoscaling.ResourceMetricSource{\n\t\t\t\t\tName: core.ResourceCPU,\n\t\t\t\t\tTarget: autoscaling.MetricTarget{\n\t\t\t\t\t\tType: autoscaling.UtilizationMetricType,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\tout.Metrics[0].Resource.Target.AverageUtilization = new(int32)\n\t\t*out.Metrics[0].Resource.Target.AverageUtilization = *in.TargetCPUUtilizationPercentage\n\t}\n\n\treturn nil\n}","line":{"from":474,"to":499}} {"id":100002075,"name":"Convert_autoscaling_HorizontalPodAutoscalerStatus_To_v1_HorizontalPodAutoscalerStatus","signature":"func Convert_autoscaling_HorizontalPodAutoscalerStatus_To_v1_HorizontalPodAutoscalerStatus(in *autoscaling.HorizontalPodAutoscalerStatus, out *autoscalingv1.HorizontalPodAutoscalerStatus, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_autoscaling_HorizontalPodAutoscalerStatus_To_v1_HorizontalPodAutoscalerStatus(in *autoscaling.HorizontalPodAutoscalerStatus, out *autoscalingv1.HorizontalPodAutoscalerStatus, s conversion.Scope) error {\n\tout.ObservedGeneration = in.ObservedGeneration\n\tout.LastScaleTime = in.LastScaleTime\n\n\tout.CurrentReplicas = in.CurrentReplicas\n\tout.DesiredReplicas = in.DesiredReplicas\n\n\tfor _, metric := range in.CurrentMetrics {\n\t\tif metric.Type == autoscaling.ResourceMetricSourceType \u0026\u0026 metric.Resource != nil \u0026\u0026 metric.Resource.Name == core.ResourceCPU {\n\t\t\tif metric.Resource.Current.AverageUtilization != nil {\n\n\t\t\t\tout.CurrentCPUUtilizationPercentage = new(int32)\n\t\t\t\t*out.CurrentCPUUtilizationPercentage = *metric.Resource.Current.AverageUtilization\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":501,"to":518}} {"id":100002076,"name":"Convert_v1_HorizontalPodAutoscalerStatus_To_autoscaling_HorizontalPodAutoscalerStatus","signature":"func Convert_v1_HorizontalPodAutoscalerStatus_To_autoscaling_HorizontalPodAutoscalerStatus(in *autoscalingv1.HorizontalPodAutoscalerStatus, out *autoscaling.HorizontalPodAutoscalerStatus, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_v1_HorizontalPodAutoscalerStatus_To_autoscaling_HorizontalPodAutoscalerStatus(in *autoscalingv1.HorizontalPodAutoscalerStatus, out *autoscaling.HorizontalPodAutoscalerStatus, s conversion.Scope) error {\n\tout.ObservedGeneration = in.ObservedGeneration\n\tout.LastScaleTime = in.LastScaleTime\n\n\tout.CurrentReplicas = in.CurrentReplicas\n\tout.DesiredReplicas = in.DesiredReplicas\n\n\tif in.CurrentCPUUtilizationPercentage != nil {\n\t\tout.CurrentMetrics = []autoscaling.MetricStatus{\n\t\t\t{\n\t\t\t\tType: autoscaling.ResourceMetricSourceType,\n\t\t\t\tResource: \u0026autoscaling.ResourceMetricStatus{\n\t\t\t\t\tName: core.ResourceCPU,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\tout.CurrentMetrics[0].Resource.Current.AverageUtilization = new(int32)\n\t\t*out.CurrentMetrics[0].Resource.Current.AverageUtilization = *in.CurrentCPUUtilizationPercentage\n\t}\n\treturn nil\n}","line":{"from":520,"to":540}} {"id":100002077,"name":"Convert_v1_ContainerResourceMetricSource_To_autoscaling_ContainerResourceMetricSource","signature":"func Convert_v1_ContainerResourceMetricSource_To_autoscaling_ContainerResourceMetricSource(in *autoscalingv1.ContainerResourceMetricSource, out *autoscaling.ContainerResourceMetricSource, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_v1_ContainerResourceMetricSource_To_autoscaling_ContainerResourceMetricSource(in *autoscalingv1.ContainerResourceMetricSource, out *autoscaling.ContainerResourceMetricSource, s conversion.Scope) error {\n\tout.Name = core.ResourceName(in.Name)\n\tout.Container = in.Container\n\tutilization := in.TargetAverageUtilization\n\taverageValue := in.TargetAverageValue\n\tvar metricType autoscaling.MetricTargetType\n\tif utilization == nil {\n\t\tmetricType = autoscaling.AverageValueMetricType\n\t} else {\n\t\tmetricType = autoscaling.UtilizationMetricType\n\t}\n\tout.Target = autoscaling.MetricTarget{\n\t\tType: metricType,\n\t\tAverageValue: averageValue,\n\t\tAverageUtilization: utilization,\n\t}\n\treturn nil\n}","line":{"from":542,"to":559}} {"id":100002078,"name":"Convert_autoscaling_ContainerResourceMetricSource_To_v1_ContainerResourceMetricSource","signature":"func Convert_autoscaling_ContainerResourceMetricSource_To_v1_ContainerResourceMetricSource(in *autoscaling.ContainerResourceMetricSource, out *autoscalingv1.ContainerResourceMetricSource, s conversion.Scope) error","file":"pkg/apis/autoscaling/v1/conversion.go","code":"func Convert_autoscaling_ContainerResourceMetricSource_To_v1_ContainerResourceMetricSource(in *autoscaling.ContainerResourceMetricSource, out *autoscalingv1.ContainerResourceMetricSource, s conversion.Scope) error {\n\tout.Name = v1.ResourceName(in.Name)\n\tout.Container = in.Container\n\tout.TargetAverageUtilization = in.Target.AverageUtilization\n\tout.TargetAverageValue = in.Target.AverageValue\n\treturn nil\n}","line":{"from":561,"to":567}} {"id":100002079,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/autoscaling/v1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":25,"to":27}} {"id":100002080,"name":"SetDefaults_HorizontalPodAutoscaler","signature":"func SetDefaults_HorizontalPodAutoscaler(obj *autoscalingv1.HorizontalPodAutoscaler)","file":"pkg/apis/autoscaling/v1/defaults.go","code":"func SetDefaults_HorizontalPodAutoscaler(obj *autoscalingv1.HorizontalPodAutoscaler) {\n\tif obj.Spec.MinReplicas == nil {\n\t\tobj.Spec.MinReplicas = pointer.Int32(1)\n\t}\n\n\t// NB: we apply a default for CPU utilization in conversion because\n\t// we need access to the annotations to properly apply the default.\n}","line":{"from":29,"to":36}} {"id":100002081,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/autoscaling/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002082,"name":"init","signature":"func init()","file":"pkg/apis/autoscaling/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":40,"to":45}} {"id":100002083,"name":"Convert_autoscaling_HorizontalPodAutoscaler_To_v2_HorizontalPodAutoscaler","signature":"func Convert_autoscaling_HorizontalPodAutoscaler_To_v2_HorizontalPodAutoscaler(in *autoscaling.HorizontalPodAutoscaler, out *autoscalingv2.HorizontalPodAutoscaler, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2/conversion.go","code":"func Convert_autoscaling_HorizontalPodAutoscaler_To_v2_HorizontalPodAutoscaler(in *autoscaling.HorizontalPodAutoscaler, out *autoscalingv2.HorizontalPodAutoscaler, s conversion.Scope) error {\n\tif err := autoConvert_autoscaling_HorizontalPodAutoscaler_To_v2_HorizontalPodAutoscaler(in, out, s); err != nil {\n\t\treturn err\n\t}\n\t// v2 round-trips to internal without any serialized annotations, make sure any from other versions don't get serialized\n\tout.Annotations, _ = autoscaling.DropRoundTripHorizontalPodAutoscalerAnnotations(out.Annotations)\n\treturn nil\n}","line":{"from":26,"to":33}} {"id":100002084,"name":"Convert_v2_HorizontalPodAutoscaler_To_autoscaling_HorizontalPodAutoscaler","signature":"func Convert_v2_HorizontalPodAutoscaler_To_autoscaling_HorizontalPodAutoscaler(in *autoscalingv2.HorizontalPodAutoscaler, out *autoscaling.HorizontalPodAutoscaler, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2/conversion.go","code":"func Convert_v2_HorizontalPodAutoscaler_To_autoscaling_HorizontalPodAutoscaler(in *autoscalingv2.HorizontalPodAutoscaler, out *autoscaling.HorizontalPodAutoscaler, s conversion.Scope) error {\n\tif err := autoConvert_v2_HorizontalPodAutoscaler_To_autoscaling_HorizontalPodAutoscaler(in, out, s); err != nil {\n\t\treturn err\n\t}\n\t// v2 round-trips to internal without any serialized annotations, make sure any from other versions don't get serialized\n\tout.Annotations, _ = autoscaling.DropRoundTripHorizontalPodAutoscalerAnnotations(out.Annotations)\n\treturn nil\n}","line":{"from":35,"to":42}} {"id":100002085,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/autoscaling/v2/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":67,"to":69}} {"id":100002086,"name":"SetDefaults_HorizontalPodAutoscaler","signature":"func SetDefaults_HorizontalPodAutoscaler(obj *autoscalingv2.HorizontalPodAutoscaler)","file":"pkg/apis/autoscaling/v2/defaults.go","code":"func SetDefaults_HorizontalPodAutoscaler(obj *autoscalingv2.HorizontalPodAutoscaler) {\n\tif obj.Spec.MinReplicas == nil {\n\t\tobj.Spec.MinReplicas = pointer.Int32(1)\n\t}\n\n\tif len(obj.Spec.Metrics) == 0 {\n\t\tutilizationDefaultVal := int32(autoscaling.DefaultCPUUtilization)\n\t\tobj.Spec.Metrics = []autoscalingv2.MetricSpec{\n\t\t\t{\n\t\t\t\tType: autoscalingv2.ResourceMetricSourceType,\n\t\t\t\tResource: \u0026autoscalingv2.ResourceMetricSource{\n\t\t\t\t\tName: v1.ResourceCPU,\n\t\t\t\t\tTarget: autoscalingv2.MetricTarget{\n\t\t\t\t\t\tType: autoscalingv2.UtilizationMetricType,\n\t\t\t\t\t\tAverageUtilization: \u0026utilizationDefaultVal,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\tSetDefaults_HorizontalPodAutoscalerBehavior(obj)\n}","line":{"from":71,"to":92}} {"id":100002087,"name":"SetDefaults_HorizontalPodAutoscalerBehavior","signature":"func SetDefaults_HorizontalPodAutoscalerBehavior(obj *autoscalingv2.HorizontalPodAutoscaler)","file":"pkg/apis/autoscaling/v2/defaults.go","code":"// SetDefaults_HorizontalPodAutoscalerBehavior fills the behavior if it is not null\nfunc SetDefaults_HorizontalPodAutoscalerBehavior(obj *autoscalingv2.HorizontalPodAutoscaler) {\n\t// if behavior is specified, we should fill all the 'nil' values with the default ones\n\tif obj.Spec.Behavior != nil {\n\t\tobj.Spec.Behavior.ScaleUp = GenerateHPAScaleUpRules(obj.Spec.Behavior.ScaleUp)\n\t\tobj.Spec.Behavior.ScaleDown = GenerateHPAScaleDownRules(obj.Spec.Behavior.ScaleDown)\n\t}\n}","line":{"from":94,"to":101}} {"id":100002088,"name":"GenerateHPAScaleUpRules","signature":"func GenerateHPAScaleUpRules(scalingRules *autoscalingv2.HPAScalingRules) *autoscalingv2.HPAScalingRules","file":"pkg/apis/autoscaling/v2/defaults.go","code":"// GenerateHPAScaleUpRules returns a fully-initialized HPAScalingRules value\n// We guarantee that no pointer in the structure will have the 'nil' value\nfunc GenerateHPAScaleUpRules(scalingRules *autoscalingv2.HPAScalingRules) *autoscalingv2.HPAScalingRules {\n\tdefaultScalingRules := defaultHPAScaleUpRules.DeepCopy()\n\treturn copyHPAScalingRules(scalingRules, defaultScalingRules)\n}","line":{"from":103,"to":108}} {"id":100002089,"name":"GenerateHPAScaleDownRules","signature":"func GenerateHPAScaleDownRules(scalingRules *autoscalingv2.HPAScalingRules) *autoscalingv2.HPAScalingRules","file":"pkg/apis/autoscaling/v2/defaults.go","code":"// GenerateHPAScaleDownRules returns a fully-initialized HPAScalingRules value\n// We guarantee that no pointer in the structure will have the 'nil' value\n// EXCEPT StabilizationWindowSeconds, for reasoning check the comment for defaultHPAScaleDownRules\nfunc GenerateHPAScaleDownRules(scalingRules *autoscalingv2.HPAScalingRules) *autoscalingv2.HPAScalingRules {\n\tdefaultScalingRules := defaultHPAScaleDownRules.DeepCopy()\n\treturn copyHPAScalingRules(scalingRules, defaultScalingRules)\n}","line":{"from":110,"to":116}} {"id":100002090,"name":"copyHPAScalingRules","signature":"func copyHPAScalingRules(from, to *autoscalingv2.HPAScalingRules) *autoscalingv2.HPAScalingRules","file":"pkg/apis/autoscaling/v2/defaults.go","code":"// copyHPAScalingRules copies all non-`nil` fields in HPA constraint structure\nfunc copyHPAScalingRules(from, to *autoscalingv2.HPAScalingRules) *autoscalingv2.HPAScalingRules {\n\tif from == nil {\n\t\treturn to\n\t}\n\tif from.SelectPolicy != nil {\n\t\tto.SelectPolicy = from.SelectPolicy\n\t}\n\tif from.StabilizationWindowSeconds != nil {\n\t\tto.StabilizationWindowSeconds = from.StabilizationWindowSeconds\n\t}\n\tif from.Policies != nil {\n\t\tto.Policies = from.Policies\n\t}\n\treturn to\n}","line":{"from":118,"to":133}} {"id":100002091,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/autoscaling/v2/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002092,"name":"init","signature":"func init()","file":"pkg/apis/autoscaling/v2/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":40,"to":45}} {"id":100002093,"name":"Convert_autoscaling_MetricTarget_To_v2beta1_CrossVersionObjectReference","signature":"func Convert_autoscaling_MetricTarget_To_v2beta1_CrossVersionObjectReference(in *autoscaling.MetricTarget, out *autoscalingv2beta1.CrossVersionObjectReference, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta1/conversion.go","code":"func Convert_autoscaling_MetricTarget_To_v2beta1_CrossVersionObjectReference(in *autoscaling.MetricTarget, out *autoscalingv2beta1.CrossVersionObjectReference, s conversion.Scope) error {\n\treturn nil\n}","line":{"from":30,"to":32}} {"id":100002094,"name":"Convert_v2beta1_CrossVersionObjectReference_To_autoscaling_MetricTarget","signature":"func Convert_v2beta1_CrossVersionObjectReference_To_autoscaling_MetricTarget(in *autoscalingv2beta1.CrossVersionObjectReference, out *autoscaling.MetricTarget, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta1/conversion.go","code":"func Convert_v2beta1_CrossVersionObjectReference_To_autoscaling_MetricTarget(in *autoscalingv2beta1.CrossVersionObjectReference, out *autoscaling.MetricTarget, s conversion.Scope) error {\n\treturn nil\n}","line":{"from":34,"to":36}} {"id":100002095,"name":"Convert_v2beta1_ContainerResourceMetricStatus_To_autoscaling_ContainerResourceMetricStatus","signature":"func Convert_v2beta1_ContainerResourceMetricStatus_To_autoscaling_ContainerResourceMetricStatus(in *autoscalingv2beta1.ContainerResourceMetricStatus, out *autoscaling.ContainerResourceMetricStatus, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta1/conversion.go","code":"func Convert_v2beta1_ContainerResourceMetricStatus_To_autoscaling_ContainerResourceMetricStatus(in *autoscalingv2beta1.ContainerResourceMetricStatus, out *autoscaling.ContainerResourceMetricStatus, s conversion.Scope) error {\n\tout.Name = core.ResourceName(in.Name)\n\tout.Container = in.Container\n\tutilization := in.CurrentAverageUtilization\n\taverageValue := in.CurrentAverageValue\n\tout.Current = autoscaling.MetricValueStatus{\n\t\tAverageValue: \u0026averageValue,\n\t\tAverageUtilization: utilization,\n\t}\n\treturn nil\n}","line":{"from":38,"to":48}} {"id":100002096,"name":"Convert_autoscaling_ContainerResourceMetricStatus_To_v2beta1_ContainerResourceMetricStatus","signature":"func Convert_autoscaling_ContainerResourceMetricStatus_To_v2beta1_ContainerResourceMetricStatus(in *autoscaling.ContainerResourceMetricStatus, out *autoscalingv2beta1.ContainerResourceMetricStatus, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta1/conversion.go","code":"func Convert_autoscaling_ContainerResourceMetricStatus_To_v2beta1_ContainerResourceMetricStatus(in *autoscaling.ContainerResourceMetricStatus, out *autoscalingv2beta1.ContainerResourceMetricStatus, s conversion.Scope) error {\n\tout.Name = v1.ResourceName(in.Name)\n\tout.Container = in.Container\n\tout.CurrentAverageUtilization = in.Current.AverageUtilization\n\tif in.Current.AverageValue != nil {\n\t\tout.CurrentAverageValue = *in.Current.AverageValue\n\t}\n\treturn nil\n}","line":{"from":50,"to":58}} {"id":100002097,"name":"Convert_v2beta1_ResourceMetricStatus_To_autoscaling_ResourceMetricStatus","signature":"func Convert_v2beta1_ResourceMetricStatus_To_autoscaling_ResourceMetricStatus(in *autoscalingv2beta1.ResourceMetricStatus, out *autoscaling.ResourceMetricStatus, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta1/conversion.go","code":"func Convert_v2beta1_ResourceMetricStatus_To_autoscaling_ResourceMetricStatus(in *autoscalingv2beta1.ResourceMetricStatus, out *autoscaling.ResourceMetricStatus, s conversion.Scope) error {\n\tout.Name = core.ResourceName(in.Name)\n\tutilization := in.CurrentAverageUtilization\n\taverageValue := in.CurrentAverageValue\n\tout.Current = autoscaling.MetricValueStatus{\n\t\tAverageValue: \u0026averageValue,\n\t\tAverageUtilization: utilization,\n\t}\n\treturn nil\n}","line":{"from":60,"to":69}} {"id":100002098,"name":"Convert_autoscaling_ResourceMetricStatus_To_v2beta1_ResourceMetricStatus","signature":"func Convert_autoscaling_ResourceMetricStatus_To_v2beta1_ResourceMetricStatus(in *autoscaling.ResourceMetricStatus, out *autoscalingv2beta1.ResourceMetricStatus, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta1/conversion.go","code":"func Convert_autoscaling_ResourceMetricStatus_To_v2beta1_ResourceMetricStatus(in *autoscaling.ResourceMetricStatus, out *autoscalingv2beta1.ResourceMetricStatus, s conversion.Scope) error {\n\tout.Name = v1.ResourceName(in.Name)\n\tout.CurrentAverageUtilization = in.Current.AverageUtilization\n\tif in.Current.AverageValue != nil {\n\t\tout.CurrentAverageValue = *in.Current.AverageValue\n\t}\n\treturn nil\n}","line":{"from":71,"to":78}} {"id":100002099,"name":"Convert_v2beta1_ResourceMetricSource_To_autoscaling_ResourceMetricSource","signature":"func Convert_v2beta1_ResourceMetricSource_To_autoscaling_ResourceMetricSource(in *autoscalingv2beta1.ResourceMetricSource, out *autoscaling.ResourceMetricSource, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta1/conversion.go","code":"func Convert_v2beta1_ResourceMetricSource_To_autoscaling_ResourceMetricSource(in *autoscalingv2beta1.ResourceMetricSource, out *autoscaling.ResourceMetricSource, s conversion.Scope) error {\n\tout.Name = core.ResourceName(in.Name)\n\tutilization := in.TargetAverageUtilization\n\taverageValue := in.TargetAverageValue\n\n\tvar metricType autoscaling.MetricTargetType\n\tif utilization == nil {\n\t\tmetricType = autoscaling.AverageValueMetricType\n\t} else {\n\t\tmetricType = autoscaling.UtilizationMetricType\n\t}\n\tout.Target = autoscaling.MetricTarget{\n\t\tType: metricType,\n\t\tAverageValue: averageValue,\n\t\tAverageUtilization: utilization,\n\t}\n\treturn nil\n}","line":{"from":80,"to":97}} {"id":100002100,"name":"Convert_autoscaling_ResourceMetricSource_To_v2beta1_ResourceMetricSource","signature":"func Convert_autoscaling_ResourceMetricSource_To_v2beta1_ResourceMetricSource(in *autoscaling.ResourceMetricSource, out *autoscalingv2beta1.ResourceMetricSource, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta1/conversion.go","code":"func Convert_autoscaling_ResourceMetricSource_To_v2beta1_ResourceMetricSource(in *autoscaling.ResourceMetricSource, out *autoscalingv2beta1.ResourceMetricSource, s conversion.Scope) error {\n\tout.Name = v1.ResourceName(in.Name)\n\tout.TargetAverageUtilization = in.Target.AverageUtilization\n\tout.TargetAverageValue = in.Target.AverageValue\n\treturn nil\n}","line":{"from":99,"to":104}} {"id":100002101,"name":"Convert_autoscaling_ExternalMetricSource_To_v2beta1_ExternalMetricSource","signature":"func Convert_autoscaling_ExternalMetricSource_To_v2beta1_ExternalMetricSource(in *autoscaling.ExternalMetricSource, out *autoscalingv2beta1.ExternalMetricSource, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta1/conversion.go","code":"func Convert_autoscaling_ExternalMetricSource_To_v2beta1_ExternalMetricSource(in *autoscaling.ExternalMetricSource, out *autoscalingv2beta1.ExternalMetricSource, s conversion.Scope) error {\n\tout.MetricName = in.Metric.Name\n\tout.TargetValue = in.Target.Value\n\tout.TargetAverageValue = in.Target.AverageValue\n\tout.MetricSelector = in.Metric.Selector\n\treturn nil\n}","line":{"from":106,"to":112}} {"id":100002102,"name":"Convert_v2beta1_ExternalMetricSource_To_autoscaling_ExternalMetricSource","signature":"func Convert_v2beta1_ExternalMetricSource_To_autoscaling_ExternalMetricSource(in *autoscalingv2beta1.ExternalMetricSource, out *autoscaling.ExternalMetricSource, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta1/conversion.go","code":"func Convert_v2beta1_ExternalMetricSource_To_autoscaling_ExternalMetricSource(in *autoscalingv2beta1.ExternalMetricSource, out *autoscaling.ExternalMetricSource, s conversion.Scope) error {\n\tvalue := in.TargetValue\n\taverageValue := in.TargetAverageValue\n\n\tvar metricType autoscaling.MetricTargetType\n\tif value == nil {\n\t\tmetricType = autoscaling.AverageValueMetricType\n\t} else {\n\t\tmetricType = autoscaling.ValueMetricType\n\t}\n\n\tout.Target = autoscaling.MetricTarget{\n\t\tType: metricType,\n\t\tValue: value,\n\t\tAverageValue: averageValue,\n\t}\n\n\tout.Metric = autoscaling.MetricIdentifier{\n\t\tName: in.MetricName,\n\t\tSelector: in.MetricSelector,\n\t}\n\treturn nil\n}","line":{"from":114,"to":136}} {"id":100002103,"name":"Convert_autoscaling_ObjectMetricSource_To_v2beta1_ObjectMetricSource","signature":"func Convert_autoscaling_ObjectMetricSource_To_v2beta1_ObjectMetricSource(in *autoscaling.ObjectMetricSource, out *autoscalingv2beta1.ObjectMetricSource, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta1/conversion.go","code":"func Convert_autoscaling_ObjectMetricSource_To_v2beta1_ObjectMetricSource(in *autoscaling.ObjectMetricSource, out *autoscalingv2beta1.ObjectMetricSource, s conversion.Scope) error {\n\tif in.Target.Value != nil {\n\t\tout.TargetValue = *in.Target.Value\n\t}\n\tout.AverageValue = in.Target.AverageValue\n\n\tout.Target = autoscalingv2beta1.CrossVersionObjectReference{\n\t\tKind: in.DescribedObject.Kind,\n\t\tName: in.DescribedObject.Name,\n\t\tAPIVersion: in.DescribedObject.APIVersion,\n\t}\n\tout.MetricName = in.Metric.Name\n\tout.Selector = in.Metric.Selector\n\n\treturn nil\n}","line":{"from":138,"to":153}} {"id":100002104,"name":"Convert_v2beta1_ObjectMetricSource_To_autoscaling_ObjectMetricSource","signature":"func Convert_v2beta1_ObjectMetricSource_To_autoscaling_ObjectMetricSource(in *autoscalingv2beta1.ObjectMetricSource, out *autoscaling.ObjectMetricSource, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta1/conversion.go","code":"func Convert_v2beta1_ObjectMetricSource_To_autoscaling_ObjectMetricSource(in *autoscalingv2beta1.ObjectMetricSource, out *autoscaling.ObjectMetricSource, s conversion.Scope) error {\n\tvar metricType autoscaling.MetricTargetType\n\tif in.AverageValue == nil {\n\t\tmetricType = autoscaling.ValueMetricType\n\t} else {\n\t\tmetricType = autoscaling.AverageValueMetricType\n\t}\n\tout.Target = autoscaling.MetricTarget{\n\t\tType: metricType,\n\t\tValue: \u0026in.TargetValue,\n\t\tAverageValue: in.AverageValue,\n\t}\n\tout.DescribedObject = autoscaling.CrossVersionObjectReference{\n\t\tKind: in.Target.Kind,\n\t\tName: in.Target.Name,\n\t\tAPIVersion: in.Target.APIVersion,\n\t}\n\tout.Metric = autoscaling.MetricIdentifier{\n\t\tName: in.MetricName,\n\t\tSelector: in.Selector,\n\t}\n\treturn nil\n}","line":{"from":155,"to":177}} {"id":100002105,"name":"Convert_autoscaling_PodsMetricSource_To_v2beta1_PodsMetricSource","signature":"func Convert_autoscaling_PodsMetricSource_To_v2beta1_PodsMetricSource(in *autoscaling.PodsMetricSource, out *autoscalingv2beta1.PodsMetricSource, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta1/conversion.go","code":"func Convert_autoscaling_PodsMetricSource_To_v2beta1_PodsMetricSource(in *autoscaling.PodsMetricSource, out *autoscalingv2beta1.PodsMetricSource, s conversion.Scope) error {\n\tif in.Target.AverageValue != nil {\n\t\ttargetAverageValue := *in.Target.AverageValue\n\t\tout.TargetAverageValue = targetAverageValue\n\t}\n\n\tout.MetricName = in.Metric.Name\n\tout.Selector = in.Metric.Selector\n\n\treturn nil\n}","line":{"from":179,"to":189}} {"id":100002106,"name":"Convert_v2beta1_PodsMetricSource_To_autoscaling_PodsMetricSource","signature":"func Convert_v2beta1_PodsMetricSource_To_autoscaling_PodsMetricSource(in *autoscalingv2beta1.PodsMetricSource, out *autoscaling.PodsMetricSource, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta1/conversion.go","code":"func Convert_v2beta1_PodsMetricSource_To_autoscaling_PodsMetricSource(in *autoscalingv2beta1.PodsMetricSource, out *autoscaling.PodsMetricSource, s conversion.Scope) error {\n\ttargetAverageValue := \u0026in.TargetAverageValue\n\tmetricType := autoscaling.AverageValueMetricType\n\n\tout.Target = autoscaling.MetricTarget{\n\t\tType: metricType,\n\t\tAverageValue: targetAverageValue,\n\t}\n\tout.Metric = autoscaling.MetricIdentifier{\n\t\tName: in.MetricName,\n\t\tSelector: in.Selector,\n\t}\n\treturn nil\n}","line":{"from":191,"to":204}} {"id":100002107,"name":"Convert_autoscaling_ExternalMetricStatus_To_v2beta1_ExternalMetricStatus","signature":"func Convert_autoscaling_ExternalMetricStatus_To_v2beta1_ExternalMetricStatus(in *autoscaling.ExternalMetricStatus, out *autoscalingv2beta1.ExternalMetricStatus, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta1/conversion.go","code":"func Convert_autoscaling_ExternalMetricStatus_To_v2beta1_ExternalMetricStatus(in *autoscaling.ExternalMetricStatus, out *autoscalingv2beta1.ExternalMetricStatus, s conversion.Scope) error {\n\tout.CurrentAverageValue = in.Current.AverageValue\n\tout.MetricName = in.Metric.Name\n\tif in.Current.Value != nil {\n\t\tout.CurrentValue = *in.Current.Value\n\t}\n\tout.MetricSelector = in.Metric.Selector\n\treturn nil\n}","line":{"from":206,"to":214}} {"id":100002108,"name":"Convert_v2beta1_ExternalMetricStatus_To_autoscaling_ExternalMetricStatus","signature":"func Convert_v2beta1_ExternalMetricStatus_To_autoscaling_ExternalMetricStatus(in *autoscalingv2beta1.ExternalMetricStatus, out *autoscaling.ExternalMetricStatus, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta1/conversion.go","code":"func Convert_v2beta1_ExternalMetricStatus_To_autoscaling_ExternalMetricStatus(in *autoscalingv2beta1.ExternalMetricStatus, out *autoscaling.ExternalMetricStatus, s conversion.Scope) error {\n\tvalue := in.CurrentValue\n\taverageValue := in.CurrentAverageValue\n\tout.Current = autoscaling.MetricValueStatus{\n\t\tValue: \u0026value,\n\t\tAverageValue: averageValue,\n\t}\n\tout.Metric = autoscaling.MetricIdentifier{\n\t\tName: in.MetricName,\n\t\tSelector: in.MetricSelector,\n\t}\n\treturn nil\n}","line":{"from":216,"to":228}} {"id":100002109,"name":"Convert_autoscaling_ObjectMetricStatus_To_v2beta1_ObjectMetricStatus","signature":"func Convert_autoscaling_ObjectMetricStatus_To_v2beta1_ObjectMetricStatus(in *autoscaling.ObjectMetricStatus, out *autoscalingv2beta1.ObjectMetricStatus, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta1/conversion.go","code":"func Convert_autoscaling_ObjectMetricStatus_To_v2beta1_ObjectMetricStatus(in *autoscaling.ObjectMetricStatus, out *autoscalingv2beta1.ObjectMetricStatus, s conversion.Scope) error {\n\tif in.Current.Value != nil {\n\t\tout.CurrentValue = *in.Current.Value\n\t}\n\tout.Target = autoscalingv2beta1.CrossVersionObjectReference{\n\t\tKind: in.DescribedObject.Kind,\n\t\tName: in.DescribedObject.Name,\n\t\tAPIVersion: in.DescribedObject.APIVersion,\n\t}\n\tout.MetricName = in.Metric.Name\n\tout.Selector = in.Metric.Selector\n\tif in.Current.AverageValue != nil {\n\t\tcurrentAverageValue := *in.Current.AverageValue\n\t\tout.AverageValue = \u0026currentAverageValue\n\t}\n\treturn nil\n}","line":{"from":230,"to":246}} {"id":100002110,"name":"Convert_v2beta1_ObjectMetricStatus_To_autoscaling_ObjectMetricStatus","signature":"func Convert_v2beta1_ObjectMetricStatus_To_autoscaling_ObjectMetricStatus(in *autoscalingv2beta1.ObjectMetricStatus, out *autoscaling.ObjectMetricStatus, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta1/conversion.go","code":"func Convert_v2beta1_ObjectMetricStatus_To_autoscaling_ObjectMetricStatus(in *autoscalingv2beta1.ObjectMetricStatus, out *autoscaling.ObjectMetricStatus, s conversion.Scope) error {\n\tout.Current = autoscaling.MetricValueStatus{\n\t\tValue: \u0026in.CurrentValue,\n\t\tAverageValue: in.AverageValue,\n\t}\n\tout.DescribedObject = autoscaling.CrossVersionObjectReference{\n\t\tKind: in.Target.Kind,\n\t\tName: in.Target.Name,\n\t\tAPIVersion: in.Target.APIVersion,\n\t}\n\tout.Metric = autoscaling.MetricIdentifier{\n\t\tName: in.MetricName,\n\t\tSelector: in.Selector,\n\t}\n\treturn nil\n}","line":{"from":248,"to":263}} {"id":100002111,"name":"Convert_autoscaling_PodsMetricStatus_To_v2beta1_PodsMetricStatus","signature":"func Convert_autoscaling_PodsMetricStatus_To_v2beta1_PodsMetricStatus(in *autoscaling.PodsMetricStatus, out *autoscalingv2beta1.PodsMetricStatus, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta1/conversion.go","code":"func Convert_autoscaling_PodsMetricStatus_To_v2beta1_PodsMetricStatus(in *autoscaling.PodsMetricStatus, out *autoscalingv2beta1.PodsMetricStatus, s conversion.Scope) error {\n\tif in.Current.AverageValue != nil {\n\t\tout.CurrentAverageValue = *in.Current.AverageValue\n\t}\n\tout.MetricName = in.Metric.Name\n\tout.Selector = in.Metric.Selector\n\treturn nil\n}","line":{"from":265,"to":272}} {"id":100002112,"name":"Convert_v2beta1_PodsMetricStatus_To_autoscaling_PodsMetricStatus","signature":"func Convert_v2beta1_PodsMetricStatus_To_autoscaling_PodsMetricStatus(in *autoscalingv2beta1.PodsMetricStatus, out *autoscaling.PodsMetricStatus, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta1/conversion.go","code":"func Convert_v2beta1_PodsMetricStatus_To_autoscaling_PodsMetricStatus(in *autoscalingv2beta1.PodsMetricStatus, out *autoscaling.PodsMetricStatus, s conversion.Scope) error {\n\tout.Current = autoscaling.MetricValueStatus{\n\t\tAverageValue: \u0026in.CurrentAverageValue,\n\t}\n\tout.Metric = autoscaling.MetricIdentifier{\n\t\tName: in.MetricName,\n\t\tSelector: in.Selector,\n\t}\n\treturn nil\n}","line":{"from":274,"to":283}} {"id":100002113,"name":"Convert_autoscaling_HorizontalPodAutoscaler_To_v2beta1_HorizontalPodAutoscaler","signature":"func Convert_autoscaling_HorizontalPodAutoscaler_To_v2beta1_HorizontalPodAutoscaler(in *autoscaling.HorizontalPodAutoscaler, out *autoscalingv2beta1.HorizontalPodAutoscaler, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta1/conversion.go","code":"func Convert_autoscaling_HorizontalPodAutoscaler_To_v2beta1_HorizontalPodAutoscaler(in *autoscaling.HorizontalPodAutoscaler, out *autoscalingv2beta1.HorizontalPodAutoscaler, s conversion.Scope) error {\n\tif err := autoConvert_autoscaling_HorizontalPodAutoscaler_To_v2beta1_HorizontalPodAutoscaler(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\t// clear any pre-existing round-trip annotations to make sure the only ones set are ones we produced during conversion\n\tannotations, copiedAnnotations := autoscaling.DropRoundTripHorizontalPodAutoscalerAnnotations(out.Annotations)\n\tout.Annotations = annotations\n\n\tif in.Spec.Behavior != nil {\n\t\t// TODO: this is marshaling an internal type. Fix this without breaking backwards compatibility with n-1 API servers.\n\t\tbehaviorEnc, err := json.Marshal(in.Spec.Behavior)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// copy before mutating\n\t\tif !copiedAnnotations {\n\t\t\t//nolint:ineffassign\n\t\t\tcopiedAnnotations = true\n\t\t\tout.Annotations = autoscaling.DeepCopyStringMap(out.Annotations)\n\t\t}\n\t\tout.Annotations[autoscaling.BehaviorSpecsAnnotation] = string(behaviorEnc)\n\t}\n\n\treturn nil\n}","line":{"from":285,"to":310}} {"id":100002114,"name":"Convert_v2beta1_HorizontalPodAutoscaler_To_autoscaling_HorizontalPodAutoscaler","signature":"func Convert_v2beta1_HorizontalPodAutoscaler_To_autoscaling_HorizontalPodAutoscaler(in *autoscalingv2beta1.HorizontalPodAutoscaler, out *autoscaling.HorizontalPodAutoscaler, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta1/conversion.go","code":"func Convert_v2beta1_HorizontalPodAutoscaler_To_autoscaling_HorizontalPodAutoscaler(in *autoscalingv2beta1.HorizontalPodAutoscaler, out *autoscaling.HorizontalPodAutoscaler, s conversion.Scope) error {\n\tif err := autoConvert_v2beta1_HorizontalPodAutoscaler_To_autoscaling_HorizontalPodAutoscaler(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\tif behaviorEnc, hasBehaviors := out.Annotations[autoscaling.BehaviorSpecsAnnotation]; hasBehaviors {\n\t\t// TODO: this is unmarshaling an internal type. Fix this without breaking backwards compatibility with n-1 API servers.\n\t\tvar behavior autoscaling.HorizontalPodAutoscalerBehavior\n\t\tif err := json.Unmarshal([]byte(behaviorEnc), \u0026behavior); err == nil \u0026\u0026 behavior != (autoscaling.HorizontalPodAutoscalerBehavior{}) {\n\t\t\t// only move well-formed data from annotations to fields\n\t\t\tout.Spec.Behavior = \u0026behavior\n\t\t}\n\t}\n\n\t// drop round-tripping annotations after converting to internal\n\tout.Annotations, _ = autoscaling.DropRoundTripHorizontalPodAutoscalerAnnotations(out.Annotations)\n\n\treturn nil\n}","line":{"from":312,"to":330}} {"id":100002115,"name":"Convert_autoscaling_HorizontalPodAutoscalerSpec_To_v2beta1_HorizontalPodAutoscalerSpec","signature":"func Convert_autoscaling_HorizontalPodAutoscalerSpec_To_v2beta1_HorizontalPodAutoscalerSpec(in *autoscaling.HorizontalPodAutoscalerSpec, out *autoscalingv2beta1.HorizontalPodAutoscalerSpec, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta1/conversion.go","code":"func Convert_autoscaling_HorizontalPodAutoscalerSpec_To_v2beta1_HorizontalPodAutoscalerSpec(in *autoscaling.HorizontalPodAutoscalerSpec, out *autoscalingv2beta1.HorizontalPodAutoscalerSpec, s conversion.Scope) error {\n\treturn autoConvert_autoscaling_HorizontalPodAutoscalerSpec_To_v2beta1_HorizontalPodAutoscalerSpec(in, out, s)\n}","line":{"from":332,"to":334}} {"id":100002116,"name":"Convert_v2beta1_ContainerResourceMetricSource_To_autoscaling_ContainerResourceMetricSource","signature":"func Convert_v2beta1_ContainerResourceMetricSource_To_autoscaling_ContainerResourceMetricSource(in *autoscalingv2beta1.ContainerResourceMetricSource, out *autoscaling.ContainerResourceMetricSource, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta1/conversion.go","code":"func Convert_v2beta1_ContainerResourceMetricSource_To_autoscaling_ContainerResourceMetricSource(in *autoscalingv2beta1.ContainerResourceMetricSource, out *autoscaling.ContainerResourceMetricSource, s conversion.Scope) error {\n\tout.Name = core.ResourceName(in.Name)\n\tutilization := in.TargetAverageUtilization\n\taverageValue := in.TargetAverageValue\n\n\tvar metricType autoscaling.MetricTargetType\n\tif utilization == nil {\n\t\tmetricType = autoscaling.AverageValueMetricType\n\t} else {\n\t\tmetricType = autoscaling.UtilizationMetricType\n\t}\n\tout.Target = autoscaling.MetricTarget{\n\t\tType: metricType,\n\t\tAverageValue: averageValue,\n\t\tAverageUtilization: utilization,\n\t}\n\treturn nil\n}","line":{"from":336,"to":353}} {"id":100002117,"name":"Convert_autoscaling_ContainerResourceMetricSource_To_v2beta1_ContainerResourceMetricSource","signature":"func Convert_autoscaling_ContainerResourceMetricSource_To_v2beta1_ContainerResourceMetricSource(in *autoscaling.ContainerResourceMetricSource, out *autoscalingv2beta1.ContainerResourceMetricSource, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta1/conversion.go","code":"func Convert_autoscaling_ContainerResourceMetricSource_To_v2beta1_ContainerResourceMetricSource(in *autoscaling.ContainerResourceMetricSource, out *autoscalingv2beta1.ContainerResourceMetricSource, s conversion.Scope) error {\n\tout.Name = v1.ResourceName(in.Name)\n\tout.TargetAverageUtilization = in.Target.AverageUtilization\n\tout.TargetAverageValue = in.Target.AverageValue\n\treturn nil\n}","line":{"from":355,"to":360}} {"id":100002118,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/autoscaling/v2beta1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":27,"to":29}} {"id":100002119,"name":"SetDefaults_HorizontalPodAutoscaler","signature":"func SetDefaults_HorizontalPodAutoscaler(obj *autoscalingv2beta1.HorizontalPodAutoscaler)","file":"pkg/apis/autoscaling/v2beta1/defaults.go","code":"func SetDefaults_HorizontalPodAutoscaler(obj *autoscalingv2beta1.HorizontalPodAutoscaler) {\n\tif obj.Spec.MinReplicas == nil {\n\t\tobj.Spec.MinReplicas = pointer.Int32(1)\n\t}\n\n\tif len(obj.Spec.Metrics) == 0 {\n\t\tutilizationDefaultVal := int32(autoscaling.DefaultCPUUtilization)\n\t\tobj.Spec.Metrics = []autoscalingv2beta1.MetricSpec{\n\t\t\t{\n\t\t\t\tType: autoscalingv2beta1.ResourceMetricSourceType,\n\t\t\t\tResource: \u0026autoscalingv2beta1.ResourceMetricSource{\n\t\t\t\t\tName: v1.ResourceCPU,\n\t\t\t\t\tTargetAverageUtilization: \u0026utilizationDefaultVal,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n}","line":{"from":31,"to":48}} {"id":100002120,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/autoscaling/v2beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002121,"name":"init","signature":"func init()","file":"pkg/apis/autoscaling/v2beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":40,"to":45}} {"id":100002122,"name":"Convert_autoscaling_HorizontalPodAutoscaler_To_v2beta2_HorizontalPodAutoscaler","signature":"func Convert_autoscaling_HorizontalPodAutoscaler_To_v2beta2_HorizontalPodAutoscaler(in *autoscaling.HorizontalPodAutoscaler, out *autoscalingv2beta2.HorizontalPodAutoscaler, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta2/conversion.go","code":"func Convert_autoscaling_HorizontalPodAutoscaler_To_v2beta2_HorizontalPodAutoscaler(in *autoscaling.HorizontalPodAutoscaler, out *autoscalingv2beta2.HorizontalPodAutoscaler, s conversion.Scope) error {\n\tif err := autoConvert_autoscaling_HorizontalPodAutoscaler_To_v2beta2_HorizontalPodAutoscaler(in, out, s); err != nil {\n\t\treturn err\n\t}\n\t// v2beta2 round-trips to internal without any serialized annotations, make sure any from other versions don't get serialized\n\tout.Annotations, _ = autoscaling.DropRoundTripHorizontalPodAutoscalerAnnotations(out.Annotations)\n\treturn nil\n}","line":{"from":26,"to":33}} {"id":100002123,"name":"Convert_v2beta2_HorizontalPodAutoscaler_To_autoscaling_HorizontalPodAutoscaler","signature":"func Convert_v2beta2_HorizontalPodAutoscaler_To_autoscaling_HorizontalPodAutoscaler(in *autoscalingv2beta2.HorizontalPodAutoscaler, out *autoscaling.HorizontalPodAutoscaler, s conversion.Scope) error","file":"pkg/apis/autoscaling/v2beta2/conversion.go","code":"func Convert_v2beta2_HorizontalPodAutoscaler_To_autoscaling_HorizontalPodAutoscaler(in *autoscalingv2beta2.HorizontalPodAutoscaler, out *autoscaling.HorizontalPodAutoscaler, s conversion.Scope) error {\n\tif err := autoConvert_v2beta2_HorizontalPodAutoscaler_To_autoscaling_HorizontalPodAutoscaler(in, out, s); err != nil {\n\t\treturn err\n\t}\n\t// v2beta2 round-trips to internal without any serialized annotations, make sure any from other versions don't get serialized\n\tout.Annotations, _ = autoscaling.DropRoundTripHorizontalPodAutoscalerAnnotations(out.Annotations)\n\treturn nil\n}","line":{"from":35,"to":42}} {"id":100002124,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/autoscaling/v2beta2/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":68,"to":70}} {"id":100002125,"name":"SetDefaults_HorizontalPodAutoscaler","signature":"func SetDefaults_HorizontalPodAutoscaler(obj *autoscalingv2beta2.HorizontalPodAutoscaler)","file":"pkg/apis/autoscaling/v2beta2/defaults.go","code":"func SetDefaults_HorizontalPodAutoscaler(obj *autoscalingv2beta2.HorizontalPodAutoscaler) {\n\tif obj.Spec.MinReplicas == nil {\n\t\tobj.Spec.MinReplicas = pointer.Int32(1)\n\t}\n\n\tif len(obj.Spec.Metrics) == 0 {\n\t\tutilizationDefaultVal := int32(autoscaling.DefaultCPUUtilization)\n\t\tobj.Spec.Metrics = []autoscalingv2beta2.MetricSpec{\n\t\t\t{\n\t\t\t\tType: autoscalingv2beta2.ResourceMetricSourceType,\n\t\t\t\tResource: \u0026autoscalingv2beta2.ResourceMetricSource{\n\t\t\t\t\tName: v1.ResourceCPU,\n\t\t\t\t\tTarget: autoscalingv2beta2.MetricTarget{\n\t\t\t\t\t\tType: autoscalingv2beta2.UtilizationMetricType,\n\t\t\t\t\t\tAverageUtilization: \u0026utilizationDefaultVal,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\tSetDefaults_HorizontalPodAutoscalerBehavior(obj)\n}","line":{"from":72,"to":93}} {"id":100002126,"name":"SetDefaults_HorizontalPodAutoscalerBehavior","signature":"func SetDefaults_HorizontalPodAutoscalerBehavior(obj *autoscalingv2beta2.HorizontalPodAutoscaler)","file":"pkg/apis/autoscaling/v2beta2/defaults.go","code":"// SetDefaults_HorizontalPodAutoscalerBehavior fills the behavior if it is not null\nfunc SetDefaults_HorizontalPodAutoscalerBehavior(obj *autoscalingv2beta2.HorizontalPodAutoscaler) {\n\t// if behavior is specified, we should fill all the 'nil' values with the default ones\n\tif obj.Spec.Behavior != nil {\n\t\tobj.Spec.Behavior.ScaleUp = GenerateHPAScaleUpRules(obj.Spec.Behavior.ScaleUp)\n\t\tobj.Spec.Behavior.ScaleDown = GenerateHPAScaleDownRules(obj.Spec.Behavior.ScaleDown)\n\t}\n}","line":{"from":95,"to":102}} {"id":100002127,"name":"GenerateHPAScaleUpRules","signature":"func GenerateHPAScaleUpRules(scalingRules *autoscalingv2beta2.HPAScalingRules) *autoscalingv2beta2.HPAScalingRules","file":"pkg/apis/autoscaling/v2beta2/defaults.go","code":"// GenerateHPAScaleUpRules returns a fully-initialized HPAScalingRules value\n// We guarantee that no pointer in the structure will have the 'nil' value\nfunc GenerateHPAScaleUpRules(scalingRules *autoscalingv2beta2.HPAScalingRules) *autoscalingv2beta2.HPAScalingRules {\n\tdefaultScalingRules := defaultHPAScaleUpRules.DeepCopy()\n\treturn copyHPAScalingRules(scalingRules, defaultScalingRules)\n}","line":{"from":104,"to":109}} {"id":100002128,"name":"GenerateHPAScaleDownRules","signature":"func GenerateHPAScaleDownRules(scalingRules *autoscalingv2beta2.HPAScalingRules) *autoscalingv2beta2.HPAScalingRules","file":"pkg/apis/autoscaling/v2beta2/defaults.go","code":"// GenerateHPAScaleDownRules returns a fully-initialized HPAScalingRules value\n// We guarantee that no pointer in the structure will have the 'nil' value\n// EXCEPT StabilizationWindowSeconds, for reasoning check the comment for defaultHPAScaleDownRules\nfunc GenerateHPAScaleDownRules(scalingRules *autoscalingv2beta2.HPAScalingRules) *autoscalingv2beta2.HPAScalingRules {\n\tdefaultScalingRules := defaultHPAScaleDownRules.DeepCopy()\n\treturn copyHPAScalingRules(scalingRules, defaultScalingRules)\n}","line":{"from":111,"to":117}} {"id":100002129,"name":"copyHPAScalingRules","signature":"func copyHPAScalingRules(from, to *autoscalingv2beta2.HPAScalingRules) *autoscalingv2beta2.HPAScalingRules","file":"pkg/apis/autoscaling/v2beta2/defaults.go","code":"// copyHPAScalingRules copies all non-`nil` fields in HPA constraint structure\nfunc copyHPAScalingRules(from, to *autoscalingv2beta2.HPAScalingRules) *autoscalingv2beta2.HPAScalingRules {\n\tif from == nil {\n\t\treturn to\n\t}\n\tif from.SelectPolicy != nil {\n\t\tto.SelectPolicy = from.SelectPolicy\n\t}\n\tif from.StabilizationWindowSeconds != nil {\n\t\tto.StabilizationWindowSeconds = from.StabilizationWindowSeconds\n\t}\n\tif from.Policies != nil {\n\t\tto.Policies = from.Policies\n\t}\n\treturn to\n}","line":{"from":119,"to":134}} {"id":100002130,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/autoscaling/v2beta2/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002131,"name":"init","signature":"func init()","file":"pkg/apis/autoscaling/v2beta2/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":40,"to":45}} {"id":100002132,"name":"ValidateScale","signature":"func ValidateScale(scale *autoscaling.Scale) field.ErrorList","file":"pkg/apis/autoscaling/validation/validation.go","code":"// ValidateScale validates a Scale and returns an ErrorList with any errors.\nfunc ValidateScale(scale *autoscaling.Scale) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, apivalidation.ValidateObjectMeta(\u0026scale.ObjectMeta, true, apimachineryvalidation.NameIsDNSSubdomain, field.NewPath(\"metadata\"))...)\n\n\tif scale.Spec.Replicas \u003c 0 {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"spec\", \"replicas\"), scale.Spec.Replicas, \"must be greater than or equal to 0\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":39,"to":49}} {"id":100002133,"name":"validateHorizontalPodAutoscalerSpec","signature":"func validateHorizontalPodAutoscalerSpec(autoscaler autoscaling.HorizontalPodAutoscalerSpec, fldPath *field.Path, minReplicasLowerBound int32) field.ErrorList","file":"pkg/apis/autoscaling/validation/validation.go","code":"func validateHorizontalPodAutoscalerSpec(autoscaler autoscaling.HorizontalPodAutoscalerSpec, fldPath *field.Path, minReplicasLowerBound int32) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif autoscaler.MinReplicas != nil \u0026\u0026 *autoscaler.MinReplicas \u003c minReplicasLowerBound {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"minReplicas\"), *autoscaler.MinReplicas,\n\t\t\tfmt.Sprintf(\"must be greater than or equal to %d\", minReplicasLowerBound)))\n\t}\n\tif autoscaler.MaxReplicas \u003c 1 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"maxReplicas\"), autoscaler.MaxReplicas, \"must be greater than 0\"))\n\t}\n\tif autoscaler.MinReplicas != nil \u0026\u0026 autoscaler.MaxReplicas \u003c *autoscaler.MinReplicas {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"maxReplicas\"), autoscaler.MaxReplicas, \"must be greater than or equal to `minReplicas`\"))\n\t}\n\tif refErrs := ValidateCrossVersionObjectReference(autoscaler.ScaleTargetRef, fldPath.Child(\"scaleTargetRef\")); len(refErrs) \u003e 0 {\n\t\tallErrs = append(allErrs, refErrs...)\n\t}\n\tif refErrs := validateMetrics(autoscaler.Metrics, fldPath.Child(\"metrics\"), autoscaler.MinReplicas); len(refErrs) \u003e 0 {\n\t\tallErrs = append(allErrs, refErrs...)\n\t}\n\tif refErrs := validateBehavior(autoscaler.Behavior, fldPath.Child(\"behavior\")); len(refErrs) \u003e 0 {\n\t\tallErrs = append(allErrs, refErrs...)\n\t}\n\treturn allErrs\n}","line":{"from":55,"to":78}} {"id":100002134,"name":"ValidateCrossVersionObjectReference","signature":"func ValidateCrossVersionObjectReference(ref autoscaling.CrossVersionObjectReference, fldPath *field.Path) field.ErrorList","file":"pkg/apis/autoscaling/validation/validation.go","code":"// ValidateCrossVersionObjectReference validates a CrossVersionObjectReference and returns an\n// ErrorList with any errors.\nfunc ValidateCrossVersionObjectReference(ref autoscaling.CrossVersionObjectReference, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(ref.Kind) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"kind\"), \"\"))\n\t} else {\n\t\tfor _, msg := range pathvalidation.IsValidPathSegmentName(ref.Kind) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"kind\"), ref.Kind, msg))\n\t\t}\n\t}\n\n\tif len(ref.Name) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"name\"), \"\"))\n\t} else {\n\t\tfor _, msg := range pathvalidation.IsValidPathSegmentName(ref.Name) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"name\"), ref.Name, msg))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":80,"to":101}} {"id":100002135,"name":"ValidateHorizontalPodAutoscaler","signature":"func ValidateHorizontalPodAutoscaler(autoscaler *autoscaling.HorizontalPodAutoscaler) field.ErrorList","file":"pkg/apis/autoscaling/validation/validation.go","code":"// ValidateHorizontalPodAutoscaler validates a HorizontalPodAutoscaler and returns an\n// ErrorList with any errors.\nfunc ValidateHorizontalPodAutoscaler(autoscaler *autoscaling.HorizontalPodAutoscaler) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMeta(\u0026autoscaler.ObjectMeta, true, ValidateHorizontalPodAutoscalerName, field.NewPath(\"metadata\"))\n\n\t// MinReplicasLowerBound represents a minimum value for minReplicas\n\t// 0 when HPA scale-to-zero feature is enabled\n\tvar minReplicasLowerBound int32\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.HPAScaleToZero) {\n\t\tminReplicasLowerBound = 0\n\t} else {\n\t\tminReplicasLowerBound = 1\n\t}\n\tallErrs = append(allErrs, validateHorizontalPodAutoscalerSpec(autoscaler.Spec, field.NewPath(\"spec\"), minReplicasLowerBound)...)\n\treturn allErrs\n}","line":{"from":103,"to":119}} {"id":100002136,"name":"ValidateHorizontalPodAutoscalerUpdate","signature":"func ValidateHorizontalPodAutoscalerUpdate(newAutoscaler, oldAutoscaler *autoscaling.HorizontalPodAutoscaler) field.ErrorList","file":"pkg/apis/autoscaling/validation/validation.go","code":"// ValidateHorizontalPodAutoscalerUpdate validates an update to a HorizontalPodAutoscaler and returns an\n// ErrorList with any errors.\nfunc ValidateHorizontalPodAutoscalerUpdate(newAutoscaler, oldAutoscaler *autoscaling.HorizontalPodAutoscaler) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMetaUpdate(\u0026newAutoscaler.ObjectMeta, \u0026oldAutoscaler.ObjectMeta, field.NewPath(\"metadata\"))\n\n\t// minReplicasLowerBound represents a minimum value for minReplicas\n\t// 0 when HPA scale-to-zero feature is enabled or HPA object already has minReplicas=0\n\tvar minReplicasLowerBound int32\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.HPAScaleToZero) || (oldAutoscaler.Spec.MinReplicas != nil \u0026\u0026 *oldAutoscaler.Spec.MinReplicas == 0) {\n\t\tminReplicasLowerBound = 0\n\t} else {\n\t\tminReplicasLowerBound = 1\n\t}\n\n\tallErrs = append(allErrs, validateHorizontalPodAutoscalerSpec(newAutoscaler.Spec, field.NewPath(\"spec\"), minReplicasLowerBound)...)\n\treturn allErrs\n}","line":{"from":121,"to":138}} {"id":100002137,"name":"ValidateHorizontalPodAutoscalerStatusUpdate","signature":"func ValidateHorizontalPodAutoscalerStatusUpdate(newAutoscaler, oldAutoscaler *autoscaling.HorizontalPodAutoscaler) field.ErrorList","file":"pkg/apis/autoscaling/validation/validation.go","code":"// ValidateHorizontalPodAutoscalerStatusUpdate validates an update to status on a HorizontalPodAutoscaler and\n// returns an ErrorList with any errors.\nfunc ValidateHorizontalPodAutoscalerStatusUpdate(newAutoscaler, oldAutoscaler *autoscaling.HorizontalPodAutoscaler) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMetaUpdate(\u0026newAutoscaler.ObjectMeta, \u0026oldAutoscaler.ObjectMeta, field.NewPath(\"metadata\"))\n\tstatus := newAutoscaler.Status\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.CurrentReplicas), field.NewPath(\"status\", \"currentReplicas\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.DesiredReplicas), field.NewPath(\"status\", \"desiredReplicas\"))...)\n\treturn allErrs\n}","line":{"from":140,"to":148}} {"id":100002138,"name":"validateMetrics","signature":"func validateMetrics(metrics []autoscaling.MetricSpec, fldPath *field.Path, minReplicas *int32) field.ErrorList","file":"pkg/apis/autoscaling/validation/validation.go","code":"func validateMetrics(metrics []autoscaling.MetricSpec, fldPath *field.Path, minReplicas *int32) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\thasObjectMetrics := false\n\thasExternalMetrics := false\n\n\tfor i, metricSpec := range metrics {\n\t\tidxPath := fldPath.Index(i)\n\t\tif targetErrs := validateMetricSpec(metricSpec, idxPath); len(targetErrs) \u003e 0 {\n\t\t\tallErrs = append(allErrs, targetErrs...)\n\t\t}\n\t\tif metricSpec.Type == autoscaling.ObjectMetricSourceType {\n\t\t\thasObjectMetrics = true\n\t\t}\n\t\tif metricSpec.Type == autoscaling.ExternalMetricSourceType {\n\t\t\thasExternalMetrics = true\n\t\t}\n\t}\n\n\tif minReplicas != nil \u0026\u0026 *minReplicas == 0 {\n\t\tif !hasObjectMetrics \u0026\u0026 !hasExternalMetrics {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath, \"must specify at least one Object or External metric to support scaling to zero replicas\"))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":150,"to":175}} {"id":100002139,"name":"validateBehavior","signature":"func validateBehavior(behavior *autoscaling.HorizontalPodAutoscalerBehavior, fldPath *field.Path) field.ErrorList","file":"pkg/apis/autoscaling/validation/validation.go","code":"func validateBehavior(behavior *autoscaling.HorizontalPodAutoscalerBehavior, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif behavior != nil {\n\t\tif scaleUpErrs := validateScalingRules(behavior.ScaleUp, fldPath.Child(\"scaleUp\")); len(scaleUpErrs) \u003e 0 {\n\t\t\tallErrs = append(allErrs, scaleUpErrs...)\n\t\t}\n\t\tif scaleDownErrs := validateScalingRules(behavior.ScaleDown, fldPath.Child(\"scaleDown\")); len(scaleDownErrs) \u003e 0 {\n\t\t\tallErrs = append(allErrs, scaleDownErrs...)\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":177,"to":188}} {"id":100002140,"name":"validateScalingRules","signature":"func validateScalingRules(rules *autoscaling.HPAScalingRules, fldPath *field.Path) field.ErrorList","file":"pkg/apis/autoscaling/validation/validation.go","code":"func validateScalingRules(rules *autoscaling.HPAScalingRules, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif rules != nil {\n\t\tif rules.StabilizationWindowSeconds != nil \u0026\u0026 *rules.StabilizationWindowSeconds \u003c 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"stabilizationWindowSeconds\"), rules.StabilizationWindowSeconds, \"must be greater than or equal to zero\"))\n\t\t}\n\t\tif rules.StabilizationWindowSeconds != nil \u0026\u0026 *rules.StabilizationWindowSeconds \u003e MaxStabilizationWindowSeconds {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"stabilizationWindowSeconds\"), rules.StabilizationWindowSeconds,\n\t\t\t\tfmt.Sprintf(\"must be less than or equal to %v\", MaxStabilizationWindowSeconds)))\n\t\t}\n\t\tif rules.SelectPolicy != nil \u0026\u0026 !validSelectPolicyTypes.Has(string(*rules.SelectPolicy)) {\n\t\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"selectPolicy\"), rules.SelectPolicy, validSelectPolicyTypesList))\n\t\t}\n\t\tpoliciesPath := fldPath.Child(\"policies\")\n\t\tif len(rules.Policies) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(policiesPath, \"must specify at least one Policy\"))\n\t\t}\n\t\tfor i, policy := range rules.Policies {\n\t\t\tidxPath := policiesPath.Index(i)\n\t\t\tif policyErrs := validateScalingPolicy(policy, idxPath); len(policyErrs) \u003e 0 {\n\t\t\t\tallErrs = append(allErrs, policyErrs...)\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":193,"to":218}} {"id":100002141,"name":"validateScalingPolicy","signature":"func validateScalingPolicy(policy autoscaling.HPAScalingPolicy, fldPath *field.Path) field.ErrorList","file":"pkg/apis/autoscaling/validation/validation.go","code":"func validateScalingPolicy(policy autoscaling.HPAScalingPolicy, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif policy.Type != autoscaling.PodsScalingPolicy \u0026\u0026 policy.Type != autoscaling.PercentScalingPolicy {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"type\"), policy.Type, validPolicyTypesList))\n\t}\n\tif policy.Value \u003c= 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"value\"), policy.Value, \"must be greater than zero\"))\n\t}\n\tif policy.PeriodSeconds \u003c= 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"periodSeconds\"), policy.PeriodSeconds, \"must be greater than zero\"))\n\t}\n\tif policy.PeriodSeconds \u003e MaxPeriodSeconds {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"periodSeconds\"), policy.PeriodSeconds,\n\t\t\tfmt.Sprintf(\"must be less than or equal to %v\", MaxPeriodSeconds)))\n\t}\n\treturn allErrs\n}","line":{"from":223,"to":239}} {"id":100002142,"name":"validateMetricSpec","signature":"func validateMetricSpec(spec autoscaling.MetricSpec, fldPath *field.Path) field.ErrorList","file":"pkg/apis/autoscaling/validation/validation.go","code":"func validateMetricSpec(spec autoscaling.MetricSpec, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(string(spec.Type)) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"type\"), \"must specify a metric source type\"))\n\t}\n\n\tif !validMetricSourceTypes.Has(string(spec.Type)) {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"type\"), spec.Type, validMetricSourceTypesList))\n\t}\n\n\ttypesPresent := sets.NewString()\n\tif spec.Object != nil {\n\t\ttypesPresent.Insert(\"object\")\n\t\tif typesPresent.Len() == 1 {\n\t\t\tallErrs = append(allErrs, validateObjectSource(spec.Object, fldPath.Child(\"object\"))...)\n\t\t}\n\t}\n\n\tif spec.External != nil {\n\t\ttypesPresent.Insert(\"external\")\n\t\tif typesPresent.Len() == 1 {\n\t\t\tallErrs = append(allErrs, validateExternalSource(spec.External, fldPath.Child(\"external\"))...)\n\t\t}\n\t}\n\n\tif spec.Pods != nil {\n\t\ttypesPresent.Insert(\"pods\")\n\t\tif typesPresent.Len() == 1 {\n\t\t\tallErrs = append(allErrs, validatePodsSource(spec.Pods, fldPath.Child(\"pods\"))...)\n\t\t}\n\t}\n\n\tif spec.Resource != nil {\n\t\ttypesPresent.Insert(\"resource\")\n\t\tif typesPresent.Len() == 1 {\n\t\t\tallErrs = append(allErrs, validateResourceSource(spec.Resource, fldPath.Child(\"resource\"))...)\n\t\t}\n\t}\n\n\tif spec.ContainerResource != nil {\n\t\ttypesPresent.Insert(\"containerResource\")\n\t\tif typesPresent.Len() == 1 {\n\t\t\tallErrs = append(allErrs, validateContainerResourceSource(spec.ContainerResource, fldPath.Child(\"containerResource\"))...)\n\t\t}\n\t}\n\n\tvar expectedField string\n\tswitch spec.Type {\n\n\tcase autoscaling.ObjectMetricSourceType:\n\t\tif spec.Object == nil {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"object\"), \"must populate information for the given metric source\"))\n\t\t}\n\t\texpectedField = \"object\"\n\tcase autoscaling.PodsMetricSourceType:\n\t\tif spec.Pods == nil {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"pods\"), \"must populate information for the given metric source\"))\n\t\t}\n\t\texpectedField = \"pods\"\n\tcase autoscaling.ResourceMetricSourceType:\n\t\tif spec.Resource == nil {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"resource\"), \"must populate information for the given metric source\"))\n\t\t}\n\t\texpectedField = \"resource\"\n\tcase autoscaling.ExternalMetricSourceType:\n\t\tif spec.External == nil {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"external\"), \"must populate information for the given metric source\"))\n\t\t}\n\t\texpectedField = \"external\"\n\tcase autoscaling.ContainerResourceMetricSourceType:\n\t\tif spec.ContainerResource == nil {\n\t\t\tif utilfeature.DefaultFeatureGate.Enabled(features.HPAContainerMetrics) {\n\t\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"containerResource\"), \"must populate information for the given metric source\"))\n\t\t\t} else {\n\t\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"containerResource\"), \"must populate information for the given metric source (only allowed when HPAContainerMetrics feature is enabled)\"))\n\t\t\t}\n\t\t}\n\t\texpectedField = \"containerResource\"\n\tdefault:\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"type\"), spec.Type, validMetricSourceTypesList))\n\t}\n\n\tif typesPresent.Len() != 1 {\n\t\ttypesPresent.Delete(expectedField)\n\t\tfor typ := range typesPresent {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(typ), \"must populate the given metric source only\"))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":247,"to":338}} {"id":100002143,"name":"validateObjectSource","signature":"func validateObjectSource(src *autoscaling.ObjectMetricSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/autoscaling/validation/validation.go","code":"func validateObjectSource(src *autoscaling.ObjectMetricSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tallErrs = append(allErrs, ValidateCrossVersionObjectReference(src.DescribedObject, fldPath.Child(\"describedObject\"))...)\n\tallErrs = append(allErrs, validateMetricIdentifier(src.Metric, fldPath.Child(\"metric\"))...)\n\tallErrs = append(allErrs, validateMetricTarget(src.Target, fldPath.Child(\"target\"))...)\n\n\tif src.Target.Value == nil \u0026\u0026 src.Target.AverageValue == nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"target\").Child(\"averageValue\"), \"must set either a target value or averageValue\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":340,"to":352}} {"id":100002144,"name":"validateExternalSource","signature":"func validateExternalSource(src *autoscaling.ExternalMetricSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/autoscaling/validation/validation.go","code":"func validateExternalSource(src *autoscaling.ExternalMetricSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tallErrs = append(allErrs, validateMetricIdentifier(src.Metric, fldPath.Child(\"metric\"))...)\n\tallErrs = append(allErrs, validateMetricTarget(src.Target, fldPath.Child(\"target\"))...)\n\n\tif src.Target.Value == nil \u0026\u0026 src.Target.AverageValue == nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"target\").Child(\"averageValue\"), \"must set either a target value for metric or a per-pod target\"))\n\t}\n\n\tif src.Target.Value != nil \u0026\u0026 src.Target.AverageValue != nil {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"target\").Child(\"value\"), \"may not set both a target value for metric and a per-pod target\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":354,"to":369}} {"id":100002145,"name":"validatePodsSource","signature":"func validatePodsSource(src *autoscaling.PodsMetricSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/autoscaling/validation/validation.go","code":"func validatePodsSource(src *autoscaling.PodsMetricSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tallErrs = append(allErrs, validateMetricIdentifier(src.Metric, fldPath.Child(\"metric\"))...)\n\tallErrs = append(allErrs, validateMetricTarget(src.Target, fldPath.Child(\"target\"))...)\n\n\tif src.Target.AverageValue == nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"target\").Child(\"averageValue\"), \"must specify a positive target averageValue\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":371,"to":382}} {"id":100002146,"name":"validateContainerResourceSource","signature":"func validateContainerResourceSource(src *autoscaling.ContainerResourceMetricSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/autoscaling/validation/validation.go","code":"func validateContainerResourceSource(src *autoscaling.ContainerResourceMetricSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(src.Name) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"name\"), \"must specify a resource name\"))\n\t} else {\n\t\tallErrs = append(allErrs, corevalidation.ValidateContainerResourceName(string(src.Name), fldPath.Child(\"name\"))...)\n\t}\n\n\tif len(src.Container) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"container\"), \"must specify a container\"))\n\t} else {\n\t\tallErrs = append(allErrs, apivalidation.ValidateDNS1123Label(src.Container, fldPath.Child(\"container\"))...)\n\t}\n\n\tallErrs = append(allErrs, validateMetricTarget(src.Target, fldPath.Child(\"target\"))...)\n\n\tif src.Target.AverageUtilization == nil \u0026\u0026 src.Target.AverageValue == nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"target\").Child(\"averageUtilization\"), \"must set either a target raw value or a target utilization\"))\n\t}\n\n\tif src.Target.AverageUtilization != nil \u0026\u0026 src.Target.AverageValue != nil {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"target\").Child(\"averageValue\"), \"may not set both a target raw value and a target utilization\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":384,"to":410}} {"id":100002147,"name":"validateResourceSource","signature":"func validateResourceSource(src *autoscaling.ResourceMetricSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/autoscaling/validation/validation.go","code":"func validateResourceSource(src *autoscaling.ResourceMetricSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(src.Name) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"name\"), \"must specify a resource name\"))\n\t}\n\n\tallErrs = append(allErrs, validateMetricTarget(src.Target, fldPath.Child(\"target\"))...)\n\n\tif src.Target.AverageUtilization == nil \u0026\u0026 src.Target.AverageValue == nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"target\").Child(\"averageUtilization\"), \"must set either a target raw value or a target utilization\"))\n\t}\n\n\tif src.Target.AverageUtilization != nil \u0026\u0026 src.Target.AverageValue != nil {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"target\").Child(\"averageValue\"), \"may not set both a target raw value and a target utilization\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":412,"to":430}} {"id":100002148,"name":"validateMetricTarget","signature":"func validateMetricTarget(mt autoscaling.MetricTarget, fldPath *field.Path) field.ErrorList","file":"pkg/apis/autoscaling/validation/validation.go","code":"func validateMetricTarget(mt autoscaling.MetricTarget, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(mt.Type) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"type\"), \"must specify a metric target type\"))\n\t}\n\n\tif mt.Type != autoscaling.UtilizationMetricType \u0026\u0026\n\t\tmt.Type != autoscaling.ValueMetricType \u0026\u0026\n\t\tmt.Type != autoscaling.AverageValueMetricType {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"type\"), mt.Type, \"must be either Utilization, Value, or AverageValue\"))\n\t}\n\n\tif mt.Value != nil \u0026\u0026 mt.Value.Sign() != 1 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"value\"), mt.Value, \"must be positive\"))\n\t}\n\n\tif mt.AverageValue != nil \u0026\u0026 mt.AverageValue.Sign() != 1 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"averageValue\"), mt.AverageValue, \"must be positive\"))\n\t}\n\n\tif mt.AverageUtilization != nil \u0026\u0026 *mt.AverageUtilization \u003c 1 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"averageUtilization\"), mt.AverageUtilization, \"must be greater than 0\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":432,"to":458}} {"id":100002149,"name":"validateMetricIdentifier","signature":"func validateMetricIdentifier(id autoscaling.MetricIdentifier, fldPath *field.Path) field.ErrorList","file":"pkg/apis/autoscaling/validation/validation.go","code":"func validateMetricIdentifier(id autoscaling.MetricIdentifier, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(id.Name) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"name\"), \"must specify a metric name\"))\n\t} else {\n\t\tfor _, msg := range pathvalidation.IsValidPathSegmentName(id.Name) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"name\"), id.Name, msg))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":460,"to":471}} {"id":100002150,"name":"init","signature":"func init()","file":"pkg/apis/batch/install/install.go","code":"func init() {\n\tInstall(legacyscheme.Scheme)\n}","line":{"from":30,"to":32}} {"id":100002151,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"pkg/apis/batch/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(batch.AddToScheme(scheme))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1.SchemeGroupVersion, v1beta1.SchemeGroupVersion))\n}","line":{"from":34,"to":40}} {"id":100002152,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"pkg/apis/batch/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100002153,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/batch/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100002154,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/batch/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Job{},\n\t\t\u0026JobList{},\n\t\t\u0026CronJob{},\n\t\t\u0026CronJobList{},\n\t)\n\treturn nil\n}","line":{"from":47,"to":56}} {"id":100002155,"name":"addConversionFuncs","signature":"func addConversionFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/batch/v1/conversion.go","code":"func addConversionFuncs(scheme *runtime.Scheme) error {\n\treturn scheme.AddFieldLabelConversionFunc(SchemeGroupVersion.WithKind(\"Job\"),\n\t\tfunc(label, value string) (string, string, error) {\n\t\t\tswitch label {\n\t\t\tcase \"metadata.name\", \"metadata.namespace\", \"status.successful\":\n\t\t\t\treturn label, value, nil\n\t\t\tdefault:\n\t\t\t\treturn \"\", \"\", fmt.Errorf(\"field label %q not supported for Job\", label)\n\t\t\t}\n\t\t})\n}","line":{"from":28,"to":38}} {"id":100002156,"name":"Convert_batch_JobSpec_To_v1_JobSpec","signature":"func Convert_batch_JobSpec_To_v1_JobSpec(in *batch.JobSpec, out *v1.JobSpec, s conversion.Scope) error","file":"pkg/apis/batch/v1/conversion.go","code":"func Convert_batch_JobSpec_To_v1_JobSpec(in *batch.JobSpec, out *v1.JobSpec, s conversion.Scope) error {\n\treturn autoConvert_batch_JobSpec_To_v1_JobSpec(in, out, s)\n}","line":{"from":43,"to":45}} {"id":100002157,"name":"Convert_v1_JobSpec_To_batch_JobSpec","signature":"func Convert_v1_JobSpec_To_batch_JobSpec(in *v1.JobSpec, out *batch.JobSpec, s conversion.Scope) error","file":"pkg/apis/batch/v1/conversion.go","code":"func Convert_v1_JobSpec_To_batch_JobSpec(in *v1.JobSpec, out *batch.JobSpec, s conversion.Scope) error {\n\treturn autoConvert_v1_JobSpec_To_batch_JobSpec(in, out, s)\n}","line":{"from":47,"to":49}} {"id":100002158,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/batch/v1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":26,"to":28}} {"id":100002159,"name":"SetDefaults_Job","signature":"func SetDefaults_Job(obj *batchv1.Job)","file":"pkg/apis/batch/v1/defaults.go","code":"func SetDefaults_Job(obj *batchv1.Job) {\n\t// For a non-parallel job, you can leave both `.spec.completions` and\n\t// `.spec.parallelism` unset. When both are unset, both are defaulted to 1.\n\tif obj.Spec.Completions == nil \u0026\u0026 obj.Spec.Parallelism == nil {\n\t\tobj.Spec.Completions = utilpointer.Int32(1)\n\t\tobj.Spec.Parallelism = utilpointer.Int32(1)\n\t}\n\tif obj.Spec.Parallelism == nil {\n\t\tobj.Spec.Parallelism = utilpointer.Int32(1)\n\t}\n\tif obj.Spec.BackoffLimit == nil {\n\t\tobj.Spec.BackoffLimit = utilpointer.Int32(6)\n\t}\n\tlabels := obj.Spec.Template.Labels\n\tif labels != nil \u0026\u0026 len(obj.Labels) == 0 {\n\t\tobj.Labels = labels\n\t}\n\tif obj.Spec.CompletionMode == nil {\n\t\tmode := batchv1.NonIndexedCompletion\n\t\tobj.Spec.CompletionMode = \u0026mode\n\t}\n\tif obj.Spec.Suspend == nil {\n\t\tobj.Spec.Suspend = utilpointer.Bool(false)\n\t}\n\tif obj.Spec.PodFailurePolicy != nil {\n\t\tfor _, rule := range obj.Spec.PodFailurePolicy.Rules {\n\t\t\tif rule.OnPodConditions != nil {\n\t\t\t\tfor i, pattern := range rule.OnPodConditions {\n\t\t\t\t\tif pattern.Status == \"\" {\n\t\t\t\t\t\trule.OnPodConditions[i].Status = corev1.ConditionTrue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":30,"to":65}} {"id":100002160,"name":"SetDefaults_CronJob","signature":"func SetDefaults_CronJob(obj *batchv1.CronJob)","file":"pkg/apis/batch/v1/defaults.go","code":"func SetDefaults_CronJob(obj *batchv1.CronJob) {\n\tif obj.Spec.ConcurrencyPolicy == \"\" {\n\t\tobj.Spec.ConcurrencyPolicy = batchv1.AllowConcurrent\n\t}\n\tif obj.Spec.Suspend == nil {\n\t\tobj.Spec.Suspend = utilpointer.Bool(false)\n\t}\n\tif obj.Spec.SuccessfulJobsHistoryLimit == nil {\n\t\tobj.Spec.SuccessfulJobsHistoryLimit = utilpointer.Int32(3)\n\t}\n\tif obj.Spec.FailedJobsHistoryLimit == nil {\n\t\tobj.Spec.FailedJobsHistoryLimit = utilpointer.Int32(1)\n\t}\n}","line":{"from":67,"to":80}} {"id":100002161,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/batch/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002162,"name":"init","signature":"func init()","file":"pkg/apis/batch/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs, addConversionFuncs)\n}","line":{"from":40,"to":45}} {"id":100002163,"name":"addConversionFuncs","signature":"func addConversionFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/batch/v1beta1/conversion.go","code":"func addConversionFuncs(scheme *runtime.Scheme) error {\n\tvar err error\n\t// Add field label conversions for kinds having selectable nothing but ObjectMeta fields.\n\tfor _, k := range []string{\"Job\", \"JobTemplate\", \"CronJob\"} {\n\t\tkind := k // don't close over range variables\n\t\terr = scheme.AddFieldLabelConversionFunc(SchemeGroupVersion.WithKind(kind),\n\t\t\tfunc(label, value string) (string, string, error) {\n\t\t\t\tswitch label {\n\t\t\t\tcase \"metadata.name\", \"metadata.namespace\", \"status.successful\":\n\t\t\t\t\treturn label, value, nil\n\t\t\t\tdefault:\n\t\t\t\t\treturn \"\", \"\", fmt.Errorf(\"field label %q not supported for %q\", label, kind)\n\t\t\t\t}\n\t\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":25,"to":44}} {"id":100002164,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/batch/v1beta1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":24,"to":26}} {"id":100002165,"name":"SetDefaults_CronJob","signature":"func SetDefaults_CronJob(obj *batchv1beta1.CronJob)","file":"pkg/apis/batch/v1beta1/defaults.go","code":"func SetDefaults_CronJob(obj *batchv1beta1.CronJob) {\n\tif obj.Spec.ConcurrencyPolicy == \"\" {\n\t\tobj.Spec.ConcurrencyPolicy = batchv1beta1.AllowConcurrent\n\t}\n\tif obj.Spec.Suspend == nil {\n\t\tobj.Spec.Suspend = new(bool)\n\t}\n\tif obj.Spec.SuccessfulJobsHistoryLimit == nil {\n\t\tobj.Spec.SuccessfulJobsHistoryLimit = new(int32)\n\t\t*obj.Spec.SuccessfulJobsHistoryLimit = 3\n\t}\n\tif obj.Spec.FailedJobsHistoryLimit == nil {\n\t\tobj.Spec.FailedJobsHistoryLimit = new(int32)\n\t\t*obj.Spec.FailedJobsHistoryLimit = 1\n\t}\n}","line":{"from":28,"to":43}} {"id":100002166,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/batch/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002167,"name":"init","signature":"func init()","file":"pkg/apis/batch/v1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs, addConversionFuncs)\n}","line":{"from":40,"to":45}} {"id":100002168,"name":"validateGeneratedSelector","signature":"func validateGeneratedSelector(obj *batch.Job, validateBatchLabels bool) field.ErrorList","file":"pkg/apis/batch/validation/validation.go","code":"// validateGeneratedSelector validates that the generated selector on a controller object match the controller object\n// metadata, and the labels on the pod template are as generated.\n//\n// TODO: generalize for other controller objects that will follow the same pattern, such as ReplicaSet and DaemonSet, and\n// move to new location. Replace batch.Job with an interface.\nfunc validateGeneratedSelector(obj *batch.Job, validateBatchLabels bool) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif obj.Spec.ManualSelector != nil \u0026\u0026 *obj.Spec.ManualSelector {\n\t\treturn allErrs\n\t}\n\n\tif obj.Spec.Selector == nil {\n\t\treturn allErrs // This case should already have been checked in caller. No need for more errors.\n\t}\n\n\t// If somehow uid was unset then we would get \"controller-uid=\" as the selector\n\t// which is bad.\n\tif obj.ObjectMeta.UID == \"\" {\n\t\tallErrs = append(allErrs, field.Required(field.NewPath(\"metadata\").Child(\"uid\"), \"\"))\n\t}\n\n\t// If selector generation was requested, then expected labels must be\n\t// present on pod template, and must match job's uid and name. The\n\t// generated (not-manual) selectors/labels ensure no overlap with other\n\t// controllers. The manual mode allows orphaning, adoption,\n\t// backward-compatibility, and experimentation with new\n\t// labeling/selection schemes. Automatic selector generation should\n\t// have placed certain labels on the pod, but this could have failed if\n\t// the user added coflicting labels. Validate that the expected\n\t// generated ones are there.\n\tallErrs = append(allErrs, apivalidation.ValidateHasLabel(obj.Spec.Template.ObjectMeta, field.NewPath(\"spec\").Child(\"template\").Child(\"metadata\"), batch.LegacyControllerUidLabel, string(obj.UID))...)\n\tallErrs = append(allErrs, apivalidation.ValidateHasLabel(obj.Spec.Template.ObjectMeta, field.NewPath(\"spec\").Child(\"template\").Child(\"metadata\"), batch.LegacyJobNameLabel, string(obj.Name))...)\n\texpectedLabels := make(map[string]string)\n\tif validateBatchLabels {\n\t\tallErrs = append(allErrs, apivalidation.ValidateHasLabel(obj.Spec.Template.ObjectMeta, field.NewPath(\"spec\").Child(\"template\").Child(\"metadata\"), batch.ControllerUidLabel, string(obj.UID))...)\n\t\tallErrs = append(allErrs, apivalidation.ValidateHasLabel(obj.Spec.Template.ObjectMeta, field.NewPath(\"spec\").Child(\"template\").Child(\"metadata\"), batch.JobNameLabel, string(obj.Name))...)\n\t\texpectedLabels[batch.ControllerUidLabel] = string(obj.UID)\n\t\texpectedLabels[batch.JobNameLabel] = string(obj.Name)\n\t}\n\t// Labels created by the Kubernetes project should have a Kubernetes prefix.\n\t// These labels are set due to legacy reasons.\n\n\texpectedLabels[batch.LegacyControllerUidLabel] = string(obj.UID)\n\texpectedLabels[batch.LegacyJobNameLabel] = string(obj.Name)\n\t// Whether manually or automatically generated, the selector of the job must match the pods it will produce.\n\tif selector, err := metav1.LabelSelectorAsSelector(obj.Spec.Selector); err == nil {\n\t\tif !selector.Matches(labels.Set(expectedLabels)) {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"spec\").Child(\"selector\"), obj.Spec.Selector, \"`selector` not auto-generated\"))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":73,"to":125}} {"id":100002169,"name":"ValidateJob","signature":"func ValidateJob(job *batch.Job, opts JobValidationOptions) field.ErrorList","file":"pkg/apis/batch/validation/validation.go","code":"// ValidateJob validates a Job and returns an ErrorList with any errors.\nfunc ValidateJob(job *batch.Job, opts JobValidationOptions) field.ErrorList {\n\t// Jobs and rcs have the same name validation\n\tallErrs := apivalidation.ValidateObjectMeta(\u0026job.ObjectMeta, true, apivalidation.ValidateReplicationControllerName, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, validateGeneratedSelector(job, opts.RequirePrefixedLabels)...)\n\tallErrs = append(allErrs, ValidateJobSpec(\u0026job.Spec, field.NewPath(\"spec\"), opts.PodValidationOptions)...)\n\tif !opts.AllowTrackingAnnotation \u0026\u0026 hasJobTrackingAnnotation(job) {\n\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"metadata\").Child(\"annotations\").Key(batch.JobTrackingFinalizer), \"cannot add this annotation\"))\n\t}\n\tif job.Spec.CompletionMode != nil \u0026\u0026 *job.Spec.CompletionMode == batch.IndexedCompletion \u0026\u0026 job.Spec.Completions != nil \u0026\u0026 *job.Spec.Completions \u003e 0 {\n\t\t// For indexed job, the job controller appends a suffix (`-$INDEX`)\n\t\t// to the pod hostname when indexed job create pods.\n\t\t// The index could be maximum `.spec.completions-1`\n\t\t// If we don't validate this here, the indexed job will fail to create pods later.\n\t\tmaximumPodHostname := fmt.Sprintf(\"%s-%d\", job.ObjectMeta.Name, *job.Spec.Completions-1)\n\t\tif errs := apimachineryvalidation.IsDNS1123Label(maximumPodHostname); len(errs) \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"metadata\").Child(\"name\"), job.ObjectMeta.Name, fmt.Sprintf(\"will not able to create pod with invalid DNS label: %s\", maximumPodHostname)))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":127,"to":147}} {"id":100002170,"name":"hasJobTrackingAnnotation","signature":"func hasJobTrackingAnnotation(job *batch.Job) bool","file":"pkg/apis/batch/validation/validation.go","code":"func hasJobTrackingAnnotation(job *batch.Job) bool {\n\tif job.Annotations == nil {\n\t\treturn false\n\t}\n\t_, ok := job.Annotations[batch.JobTrackingFinalizer]\n\treturn ok\n}","line":{"from":149,"to":155}} {"id":100002171,"name":"ValidateJobSpec","signature":"func ValidateJobSpec(spec *batch.JobSpec, fldPath *field.Path, opts apivalidation.PodValidationOptions) field.ErrorList","file":"pkg/apis/batch/validation/validation.go","code":"// ValidateJobSpec validates a JobSpec and returns an ErrorList with any errors.\nfunc ValidateJobSpec(spec *batch.JobSpec, fldPath *field.Path, opts apivalidation.PodValidationOptions) field.ErrorList {\n\tallErrs := validateJobSpec(spec, fldPath, opts)\n\tif spec.Selector == nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"selector\"), \"\"))\n\t} else {\n\t\tlabelSelectorValidationOpts := unversionedvalidation.LabelSelectorValidationOptions{\n\t\t\tAllowInvalidLabelValueInSelector: opts.AllowInvalidLabelValueInSelector,\n\t\t}\n\t\tallErrs = append(allErrs, unversionedvalidation.ValidateLabelSelector(spec.Selector, labelSelectorValidationOpts, fldPath.Child(\"selector\"))...)\n\t}\n\n\t// Whether manually or automatically generated, the selector of the job must match the pods it will produce.\n\tif selector, err := metav1.LabelSelectorAsSelector(spec.Selector); err == nil {\n\t\tlabels := labels.Set(spec.Template.Labels)\n\t\tif !selector.Matches(labels) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"template\", \"metadata\", \"labels\"), spec.Template.Labels, \"`selector` does not match template `labels`\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":157,"to":177}} {"id":100002172,"name":"validateJobSpec","signature":"func validateJobSpec(spec *batch.JobSpec, fldPath *field.Path, opts apivalidation.PodValidationOptions) field.ErrorList","file":"pkg/apis/batch/validation/validation.go","code":"func validateJobSpec(spec *batch.JobSpec, fldPath *field.Path, opts apivalidation.PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif spec.Parallelism != nil {\n\t\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(*spec.Parallelism), fldPath.Child(\"parallelism\"))...)\n\t}\n\tif spec.Completions != nil {\n\t\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(*spec.Completions), fldPath.Child(\"completions\"))...)\n\t}\n\tif spec.ActiveDeadlineSeconds != nil {\n\t\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(*spec.ActiveDeadlineSeconds), fldPath.Child(\"activeDeadlineSeconds\"))...)\n\t}\n\tif spec.BackoffLimit != nil {\n\t\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(*spec.BackoffLimit), fldPath.Child(\"backoffLimit\"))...)\n\t}\n\tif spec.TTLSecondsAfterFinished != nil {\n\t\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(*spec.TTLSecondsAfterFinished), fldPath.Child(\"ttlSecondsAfterFinished\"))...)\n\t}\n\tif spec.CompletionMode != nil {\n\t\tif *spec.CompletionMode != batch.NonIndexedCompletion \u0026\u0026 *spec.CompletionMode != batch.IndexedCompletion {\n\t\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"completionMode\"), spec.CompletionMode, []string{string(batch.NonIndexedCompletion), string(batch.IndexedCompletion)}))\n\t\t}\n\t\tif *spec.CompletionMode == batch.IndexedCompletion {\n\t\t\tif spec.Completions == nil {\n\t\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"completions\"), fmt.Sprintf(\"when completion mode is %s\", batch.IndexedCompletion)))\n\t\t\t}\n\t\t\tif spec.Parallelism != nil \u0026\u0026 *spec.Parallelism \u003e maxParallelismForIndexedJob {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"parallelism\"), *spec.Parallelism, fmt.Sprintf(\"must be less than or equal to %d when completion mode is %s\", maxParallelismForIndexedJob, batch.IndexedCompletion)))\n\t\t\t}\n\t\t}\n\t}\n\n\tif spec.PodFailurePolicy != nil {\n\t\tallErrs = append(allErrs, validatePodFailurePolicy(spec, fldPath.Child(\"podFailurePolicy\"))...)\n\t}\n\n\tallErrs = append(allErrs, apivalidation.ValidatePodTemplateSpec(\u0026spec.Template, fldPath.Child(\"template\"), opts)...)\n\n\t// spec.Template.Spec.RestartPolicy can be defaulted as RestartPolicyAlways\n\t// by SetDefaults_PodSpec function when the user does not explicitly specify a value for it,\n\t// so we check both empty and RestartPolicyAlways cases here\n\tif spec.Template.Spec.RestartPolicy == api.RestartPolicyAlways || spec.Template.Spec.RestartPolicy == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"template\", \"spec\", \"restartPolicy\"),\n\t\t\tfmt.Sprintf(\"valid values: %q, %q\", api.RestartPolicyOnFailure, api.RestartPolicyNever)))\n\t} else if spec.Template.Spec.RestartPolicy != api.RestartPolicyOnFailure \u0026\u0026 spec.Template.Spec.RestartPolicy != api.RestartPolicyNever {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"template\", \"spec\", \"restartPolicy\"),\n\t\t\tspec.Template.Spec.RestartPolicy, []string{string(api.RestartPolicyOnFailure), string(api.RestartPolicyNever)}))\n\t} else if spec.PodFailurePolicy != nil \u0026\u0026 spec.Template.Spec.RestartPolicy != api.RestartPolicyNever {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"template\", \"spec\", \"restartPolicy\"),\n\t\t\tspec.Template.Spec.RestartPolicy, fmt.Sprintf(\"only %q is supported when podFailurePolicy is specified\", api.RestartPolicyNever)))\n\t}\n\treturn allErrs\n}","line":{"from":179,"to":231}} {"id":100002173,"name":"validatePodFailurePolicy","signature":"func validatePodFailurePolicy(spec *batch.JobSpec, fldPath *field.Path) field.ErrorList","file":"pkg/apis/batch/validation/validation.go","code":"func validatePodFailurePolicy(spec *batch.JobSpec, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\trulesPath := fldPath.Child(\"rules\")\n\tif len(spec.PodFailurePolicy.Rules) \u003e maxPodFailurePolicyRules {\n\t\tallErrs = append(allErrs, field.TooMany(rulesPath, len(spec.PodFailurePolicy.Rules), maxPodFailurePolicyRules))\n\t}\n\tcontainerNames := sets.NewString()\n\tfor _, containerSpec := range spec.Template.Spec.Containers {\n\t\tcontainerNames.Insert(containerSpec.Name)\n\t}\n\tfor _, containerSpec := range spec.Template.Spec.InitContainers {\n\t\tcontainerNames.Insert(containerSpec.Name)\n\t}\n\tfor i, rule := range spec.PodFailurePolicy.Rules {\n\t\tallErrs = append(allErrs, validatePodFailurePolicyRule(\u0026rule, rulesPath.Index(i), containerNames)...)\n\t}\n\treturn allErrs\n}","line":{"from":233,"to":250}} {"id":100002174,"name":"validatePodFailurePolicyRule","signature":"func validatePodFailurePolicyRule(rule *batch.PodFailurePolicyRule, rulePath *field.Path, containerNames sets.String) field.ErrorList","file":"pkg/apis/batch/validation/validation.go","code":"func validatePodFailurePolicyRule(rule *batch.PodFailurePolicyRule, rulePath *field.Path, containerNames sets.String) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tactionPath := rulePath.Child(\"action\")\n\tif rule.Action == \"\" {\n\t\tallErrs = append(allErrs, field.Required(actionPath, fmt.Sprintf(\"valid values: %q\", supportedPodFailurePolicyActions.List())))\n\t} else if !supportedPodFailurePolicyActions.Has(string(rule.Action)) {\n\t\tallErrs = append(allErrs, field.NotSupported(actionPath, rule.Action, supportedPodFailurePolicyActions.List()))\n\t}\n\tif rule.OnExitCodes != nil {\n\t\tallErrs = append(allErrs, validatePodFailurePolicyRuleOnExitCodes(rule.OnExitCodes, rulePath.Child(\"onExitCodes\"), containerNames)...)\n\t}\n\tif len(rule.OnPodConditions) \u003e 0 {\n\t\tallErrs = append(allErrs, validatePodFailurePolicyRuleOnPodConditions(rule.OnPodConditions, rulePath.Child(\"onPodConditions\"))...)\n\t}\n\tif rule.OnExitCodes != nil \u0026\u0026 len(rule.OnPodConditions) \u003e 0 {\n\t\tallErrs = append(allErrs, field.Invalid(rulePath, field.OmitValueType{}, \"specifying both OnExitCodes and OnPodConditions is not supported\"))\n\t}\n\tif rule.OnExitCodes == nil \u0026\u0026 len(rule.OnPodConditions) == 0 {\n\t\tallErrs = append(allErrs, field.Invalid(rulePath, field.OmitValueType{}, \"specifying one of OnExitCodes and OnPodConditions is required\"))\n\t}\n\treturn allErrs\n}","line":{"from":252,"to":273}} {"id":100002175,"name":"validatePodFailurePolicyRuleOnPodConditions","signature":"func validatePodFailurePolicyRuleOnPodConditions(onPodConditions []batch.PodFailurePolicyOnPodConditionsPattern, onPodConditionsPath *field.Path) field.ErrorList","file":"pkg/apis/batch/validation/validation.go","code":"func validatePodFailurePolicyRuleOnPodConditions(onPodConditions []batch.PodFailurePolicyOnPodConditionsPattern, onPodConditionsPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tif len(onPodConditions) \u003e maxPodFailurePolicyOnPodConditionsPatterns {\n\t\tallErrs = append(allErrs, field.TooMany(onPodConditionsPath, len(onPodConditions), maxPodFailurePolicyOnPodConditionsPatterns))\n\t}\n\tfor j, pattern := range onPodConditions {\n\t\tpatternPath := onPodConditionsPath.Index(j)\n\t\tstatusPath := patternPath.Child(\"status\")\n\t\tallErrs = append(allErrs, apivalidation.ValidateQualifiedName(string(pattern.Type), patternPath.Child(\"type\"))...)\n\t\tif pattern.Status == \"\" {\n\t\t\tallErrs = append(allErrs, field.Required(statusPath, fmt.Sprintf(\"valid values: %q\", supportedPodFailurePolicyOnPodConditionsStatus.List())))\n\t\t} else if !supportedPodFailurePolicyOnPodConditionsStatus.Has(string(pattern.Status)) {\n\t\t\tallErrs = append(allErrs, field.NotSupported(statusPath, pattern.Status, supportedPodFailurePolicyOnPodConditionsStatus.List()))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":275,"to":291}} {"id":100002176,"name":"validatePodFailurePolicyRuleOnExitCodes","signature":"func validatePodFailurePolicyRuleOnExitCodes(onExitCode *batch.PodFailurePolicyOnExitCodesRequirement, onExitCodesPath *field.Path, containerNames sets.String) field.ErrorList","file":"pkg/apis/batch/validation/validation.go","code":"func validatePodFailurePolicyRuleOnExitCodes(onExitCode *batch.PodFailurePolicyOnExitCodesRequirement, onExitCodesPath *field.Path, containerNames sets.String) field.ErrorList {\n\tvar allErrs field.ErrorList\n\toperatorPath := onExitCodesPath.Child(\"operator\")\n\tif onExitCode.Operator == \"\" {\n\t\tallErrs = append(allErrs, field.Required(operatorPath, fmt.Sprintf(\"valid values: %q\", supportedPodFailurePolicyOnExitCodesOperator.List())))\n\t} else if !supportedPodFailurePolicyOnExitCodesOperator.Has(string(onExitCode.Operator)) {\n\t\tallErrs = append(allErrs, field.NotSupported(operatorPath, onExitCode.Operator, supportedPodFailurePolicyOnExitCodesOperator.List()))\n\t}\n\tif onExitCode.ContainerName != nil \u0026\u0026 !containerNames.Has(*onExitCode.ContainerName) {\n\t\tallErrs = append(allErrs, field.Invalid(onExitCodesPath.Child(\"containerName\"), *onExitCode.ContainerName, \"must be one of the container or initContainer names in the pod template\"))\n\t}\n\tvaluesPath := onExitCodesPath.Child(\"values\")\n\tif len(onExitCode.Values) == 0 {\n\t\tallErrs = append(allErrs, field.Invalid(valuesPath, onExitCode.Values, \"at least one value is required\"))\n\t} else if len(onExitCode.Values) \u003e maxPodFailurePolicyOnExitCodesValues {\n\t\tallErrs = append(allErrs, field.TooMany(valuesPath, len(onExitCode.Values), maxPodFailurePolicyOnExitCodesValues))\n\t}\n\tisOrdered := true\n\tuniqueValues := sets.NewInt32()\n\tfor j, exitCodeValue := range onExitCode.Values {\n\t\tvaluePath := valuesPath.Index(j)\n\t\tif onExitCode.Operator == batch.PodFailurePolicyOnExitCodesOpIn \u0026\u0026 exitCodeValue == 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(valuePath, exitCodeValue, \"must not be 0 for the In operator\"))\n\t\t}\n\t\tif uniqueValues.Has(exitCodeValue) {\n\t\t\tallErrs = append(allErrs, field.Duplicate(valuePath, exitCodeValue))\n\t\t} else {\n\t\t\tuniqueValues.Insert(exitCodeValue)\n\t\t}\n\t\tif j \u003e 0 \u0026\u0026 onExitCode.Values[j-1] \u003e exitCodeValue {\n\t\t\tisOrdered = false\n\t\t}\n\t}\n\tif !isOrdered {\n\t\tallErrs = append(allErrs, field.Invalid(valuesPath, onExitCode.Values, \"must be ordered\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":293,"to":331}} {"id":100002177,"name":"validateJobStatus","signature":"func validateJobStatus(status *batch.JobStatus, fldPath *field.Path) field.ErrorList","file":"pkg/apis/batch/validation/validation.go","code":"// validateJobStatus validates a JobStatus and returns an ErrorList with any errors.\nfunc validateJobStatus(status *batch.JobStatus, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.Active), fldPath.Child(\"active\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.Succeeded), fldPath.Child(\"succeeded\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.Failed), fldPath.Child(\"failed\"))...)\n\tif status.Ready != nil {\n\t\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(*status.Ready), fldPath.Child(\"ready\"))...)\n\t}\n\tif status.UncountedTerminatedPods != nil {\n\t\tpath := fldPath.Child(\"uncountedTerminatedPods\")\n\t\tseen := sets.NewString()\n\t\tfor i, k := range status.UncountedTerminatedPods.Succeeded {\n\t\t\tp := path.Child(\"succeeded\").Index(i)\n\t\t\tif k == \"\" {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(p, k, \"must not be empty\"))\n\t\t\t} else if seen.Has(string(k)) {\n\t\t\t\tallErrs = append(allErrs, field.Duplicate(p, k))\n\t\t\t} else {\n\t\t\t\tseen.Insert(string(k))\n\t\t\t}\n\t\t}\n\t\tfor i, k := range status.UncountedTerminatedPods.Failed {\n\t\t\tp := path.Child(\"failed\").Index(i)\n\t\t\tif k == \"\" {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(p, k, \"must not be empty\"))\n\t\t\t} else if seen.Has(string(k)) {\n\t\t\t\tallErrs = append(allErrs, field.Duplicate(p, k))\n\t\t\t} else {\n\t\t\t\tseen.Insert(string(k))\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":333,"to":367}} {"id":100002178,"name":"ValidateJobUpdate","signature":"func ValidateJobUpdate(job, oldJob *batch.Job, opts JobValidationOptions) field.ErrorList","file":"pkg/apis/batch/validation/validation.go","code":"// ValidateJobUpdate validates an update to a Job and returns an ErrorList with any errors.\nfunc ValidateJobUpdate(job, oldJob *batch.Job, opts JobValidationOptions) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMetaUpdate(\u0026job.ObjectMeta, \u0026oldJob.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateJobSpecUpdate(job.Spec, oldJob.Spec, field.NewPath(\"spec\"), opts)...)\n\treturn allErrs\n}","line":{"from":369,"to":374}} {"id":100002179,"name":"ValidateJobUpdateStatus","signature":"func ValidateJobUpdateStatus(job, oldJob *batch.Job) field.ErrorList","file":"pkg/apis/batch/validation/validation.go","code":"// ValidateJobUpdateStatus validates an update to the status of a Job and returns an ErrorList with any errors.\nfunc ValidateJobUpdateStatus(job, oldJob *batch.Job) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMetaUpdate(\u0026job.ObjectMeta, \u0026oldJob.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateJobStatusUpdate(job.Status, oldJob.Status)...)\n\treturn allErrs\n}","line":{"from":376,"to":381}} {"id":100002180,"name":"ValidateJobSpecUpdate","signature":"func ValidateJobSpecUpdate(spec, oldSpec batch.JobSpec, fldPath *field.Path, opts JobValidationOptions) field.ErrorList","file":"pkg/apis/batch/validation/validation.go","code":"// ValidateJobSpecUpdate validates an update to a JobSpec and returns an ErrorList with any errors.\nfunc ValidateJobSpecUpdate(spec, oldSpec batch.JobSpec, fldPath *field.Path, opts JobValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, ValidateJobSpec(\u0026spec, fldPath, opts.PodValidationOptions)...)\n\tallErrs = append(allErrs, validateCompletions(spec, oldSpec, fldPath.Child(\"completions\"), opts)...)\n\tallErrs = append(allErrs, apivalidation.ValidateImmutableField(spec.Selector, oldSpec.Selector, fldPath.Child(\"selector\"))...)\n\tallErrs = append(allErrs, validatePodTemplateUpdate(spec, oldSpec, fldPath, opts)...)\n\tallErrs = append(allErrs, apivalidation.ValidateImmutableField(spec.CompletionMode, oldSpec.CompletionMode, fldPath.Child(\"completionMode\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateImmutableField(spec.PodFailurePolicy, oldSpec.PodFailurePolicy, fldPath.Child(\"podFailurePolicy\"))...)\n\treturn allErrs\n}","line":{"from":383,"to":393}} {"id":100002181,"name":"validatePodTemplateUpdate","signature":"func validatePodTemplateUpdate(spec, oldSpec batch.JobSpec, fldPath *field.Path, opts JobValidationOptions) field.ErrorList","file":"pkg/apis/batch/validation/validation.go","code":"func validatePodTemplateUpdate(spec, oldSpec batch.JobSpec, fldPath *field.Path, opts JobValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\ttemplate := \u0026spec.Template\n\toldTemplate := \u0026oldSpec.Template\n\tif opts.AllowMutableSchedulingDirectives {\n\t\toldTemplate = oldSpec.Template.DeepCopy() // +k8s:verify-mutation:reason=clone\n\t\tswitch {\n\t\tcase template.Spec.Affinity == nil \u0026\u0026 oldTemplate.Spec.Affinity != nil:\n\t\t\t// allow the Affinity field to be cleared if the old template had no affinity directives other than NodeAffinity\n\t\t\toldTemplate.Spec.Affinity.NodeAffinity = nil // +k8s:verify-mutation:reason=clone\n\t\t\tif (*oldTemplate.Spec.Affinity) == (api.Affinity{}) {\n\t\t\t\toldTemplate.Spec.Affinity = nil // +k8s:verify-mutation:reason=clone\n\t\t\t}\n\t\tcase template.Spec.Affinity != nil \u0026\u0026 oldTemplate.Spec.Affinity == nil:\n\t\t\t// allow the NodeAffinity field to skip immutability checking\n\t\t\toldTemplate.Spec.Affinity = \u0026api.Affinity{NodeAffinity: template.Spec.Affinity.NodeAffinity} // +k8s:verify-mutation:reason=clone\n\t\tcase template.Spec.Affinity != nil \u0026\u0026 oldTemplate.Spec.Affinity != nil:\n\t\t\t// allow the NodeAffinity field to skip immutability checking\n\t\t\toldTemplate.Spec.Affinity.NodeAffinity = template.Spec.Affinity.NodeAffinity // +k8s:verify-mutation:reason=clone\n\t\t}\n\t\toldTemplate.Spec.NodeSelector = template.Spec.NodeSelector // +k8s:verify-mutation:reason=clone\n\t\toldTemplate.Spec.Tolerations = template.Spec.Tolerations // +k8s:verify-mutation:reason=clone\n\t\toldTemplate.Annotations = template.Annotations // +k8s:verify-mutation:reason=clone\n\t\toldTemplate.Labels = template.Labels // +k8s:verify-mutation:reason=clone\n\t\toldTemplate.Spec.SchedulingGates = template.Spec.SchedulingGates // +k8s:verify-mutation:reason=clone\n\t}\n\tallErrs = append(allErrs, apivalidation.ValidateImmutableField(template, oldTemplate, fldPath.Child(\"template\"))...)\n\treturn allErrs\n}","line":{"from":395,"to":423}} {"id":100002182,"name":"ValidateJobStatusUpdate","signature":"func ValidateJobStatusUpdate(status, oldStatus batch.JobStatus) field.ErrorList","file":"pkg/apis/batch/validation/validation.go","code":"// ValidateJobStatusUpdate validates an update to a JobStatus and returns an ErrorList with any errors.\nfunc ValidateJobStatusUpdate(status, oldStatus batch.JobStatus) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, validateJobStatus(\u0026status, field.NewPath(\"status\"))...)\n\treturn allErrs\n}","line":{"from":425,"to":430}} {"id":100002183,"name":"ValidateCronJobCreate","signature":"func ValidateCronJobCreate(cronJob *batch.CronJob, opts apivalidation.PodValidationOptions) field.ErrorList","file":"pkg/apis/batch/validation/validation.go","code":"// ValidateCronJobCreate validates a CronJob on creation and returns an ErrorList with any errors.\nfunc ValidateCronJobCreate(cronJob *batch.CronJob, opts apivalidation.PodValidationOptions) field.ErrorList {\n\t// CronJobs and rcs have the same name validation\n\tallErrs := apivalidation.ValidateObjectMeta(\u0026cronJob.ObjectMeta, true, apivalidation.ValidateReplicationControllerName, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, validateCronJobSpec(\u0026cronJob.Spec, nil, field.NewPath(\"spec\"), opts)...)\n\tif len(cronJob.ObjectMeta.Name) \u003e apimachineryvalidation.DNS1035LabelMaxLength-11 {\n\t\t// The cronjob controller appends a 11-character suffix to the cronjob (`-$TIMESTAMP`) when\n\t\t// creating a job. The job name length limit is 63 characters.\n\t\t// Therefore cronjob names must have length \u003c= 63-11=52. If we don't validate this here,\n\t\t// then job creation will fail later.\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"metadata\").Child(\"name\"), cronJob.ObjectMeta.Name, \"must be no more than 52 characters\"))\n\t}\n\treturn allErrs\n}","line":{"from":432,"to":445}} {"id":100002184,"name":"ValidateCronJobUpdate","signature":"func ValidateCronJobUpdate(job, oldJob *batch.CronJob, opts apivalidation.PodValidationOptions) field.ErrorList","file":"pkg/apis/batch/validation/validation.go","code":"// ValidateCronJobUpdate validates an update to a CronJob and returns an ErrorList with any errors.\nfunc ValidateCronJobUpdate(job, oldJob *batch.CronJob, opts apivalidation.PodValidationOptions) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMetaUpdate(\u0026job.ObjectMeta, \u0026oldJob.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, validateCronJobSpec(\u0026job.Spec, \u0026oldJob.Spec, field.NewPath(\"spec\"), opts)...)\n\n\t// skip the 52-character name validation limit on update validation\n\t// to allow old cronjobs with names \u003e 52 chars to be updated/deleted\n\treturn allErrs\n}","line":{"from":447,"to":455}} {"id":100002185,"name":"validateCronJobSpec","signature":"func validateCronJobSpec(spec, oldSpec *batch.CronJobSpec, fldPath *field.Path, opts apivalidation.PodValidationOptions) field.ErrorList","file":"pkg/apis/batch/validation/validation.go","code":"// validateCronJobSpec validates a CronJobSpec and returns an ErrorList with any errors.\nfunc validateCronJobSpec(spec, oldSpec *batch.CronJobSpec, fldPath *field.Path, opts apivalidation.PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(spec.Schedule) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"schedule\"), \"\"))\n\t} else {\n\t\tallErrs = append(allErrs, validateScheduleFormat(spec.Schedule, spec.TimeZone, fldPath.Child(\"schedule\"))...)\n\t}\n\n\tif spec.StartingDeadlineSeconds != nil {\n\t\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(*spec.StartingDeadlineSeconds), fldPath.Child(\"startingDeadlineSeconds\"))...)\n\t}\n\n\tif oldSpec == nil || !pointer.StringEqual(oldSpec.TimeZone, spec.TimeZone) {\n\t\tallErrs = append(allErrs, validateTimeZone(spec.TimeZone, fldPath.Child(\"timeZone\"))...)\n\t}\n\n\tallErrs = append(allErrs, validateConcurrencyPolicy(\u0026spec.ConcurrencyPolicy, fldPath.Child(\"concurrencyPolicy\"))...)\n\tallErrs = append(allErrs, ValidateJobTemplateSpec(\u0026spec.JobTemplate, fldPath.Child(\"jobTemplate\"), opts)...)\n\n\tif spec.SuccessfulJobsHistoryLimit != nil {\n\t\t// zero is a valid SuccessfulJobsHistoryLimit\n\t\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(*spec.SuccessfulJobsHistoryLimit), fldPath.Child(\"successfulJobsHistoryLimit\"))...)\n\t}\n\tif spec.FailedJobsHistoryLimit != nil {\n\t\t// zero is a valid SuccessfulJobsHistoryLimit\n\t\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(*spec.FailedJobsHistoryLimit), fldPath.Child(\"failedJobsHistoryLimit\"))...)\n\t}\n\n\treturn allErrs\n}","line":{"from":457,"to":488}} {"id":100002186,"name":"validateConcurrencyPolicy","signature":"func validateConcurrencyPolicy(concurrencyPolicy *batch.ConcurrencyPolicy, fldPath *field.Path) field.ErrorList","file":"pkg/apis/batch/validation/validation.go","code":"func validateConcurrencyPolicy(concurrencyPolicy *batch.ConcurrencyPolicy, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tswitch *concurrencyPolicy {\n\tcase batch.AllowConcurrent, batch.ForbidConcurrent, batch.ReplaceConcurrent:\n\t\tbreak\n\tcase \"\":\n\t\tallErrs = append(allErrs, field.Required(fldPath, \"\"))\n\tdefault:\n\t\tvalidValues := []string{string(batch.AllowConcurrent), string(batch.ForbidConcurrent), string(batch.ReplaceConcurrent)}\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath, *concurrencyPolicy, validValues))\n\t}\n\n\treturn allErrs\n}","line":{"from":490,"to":503}} {"id":100002187,"name":"validateScheduleFormat","signature":"func validateScheduleFormat(schedule string, timeZone *string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/batch/validation/validation.go","code":"func validateScheduleFormat(schedule string, timeZone *string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif _, err := cron.ParseStandard(schedule); err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, schedule, err.Error()))\n\t}\n\tif strings.Contains(schedule, \"TZ\") \u0026\u0026 timeZone != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, schedule, \"cannot use both timeZone field and TZ or CRON_TZ in schedule\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":505,"to":515}} {"id":100002188,"name":"validateTimeZone","signature":"func validateTimeZone(timeZone *string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/batch/validation/validation.go","code":"func validateTimeZone(timeZone *string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif timeZone == nil {\n\t\treturn allErrs\n\t}\n\n\tif len(*timeZone) == 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, timeZone, \"timeZone must be nil or non-empty string\"))\n\t\treturn allErrs\n\t}\n\n\tfor _, part := range strings.Split(*timeZone, \"/\") {\n\t\tif part == \".\" || part == \"..\" || strings.HasPrefix(part, \"-\") || !validTimeZoneCharacters.MatchString(part) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, timeZone, fmt.Sprintf(\"unknown time zone %s\", *timeZone)))\n\t\t\treturn allErrs\n\t\t}\n\t}\n\n\tif strings.EqualFold(*timeZone, \"Local\") {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, timeZone, \"timeZone must be an explicit time zone as defined in https://www.iana.org/time-zones\"))\n\t}\n\n\tif _, err := time.LoadLocation(*timeZone); err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, timeZone, err.Error()))\n\t}\n\n\treturn allErrs\n}","line":{"from":527,"to":554}} {"id":100002189,"name":"ValidateJobTemplateSpec","signature":"func ValidateJobTemplateSpec(spec *batch.JobTemplateSpec, fldPath *field.Path, opts apivalidation.PodValidationOptions) field.ErrorList","file":"pkg/apis/batch/validation/validation.go","code":"// ValidateJobTemplateSpec validates a JobTemplateSpec and returns an ErrorList with any errors.\nfunc ValidateJobTemplateSpec(spec *batch.JobTemplateSpec, fldPath *field.Path, opts apivalidation.PodValidationOptions) field.ErrorList {\n\tallErrs := validateJobSpec(\u0026spec.Spec, fldPath.Child(\"spec\"), opts)\n\n\t// jobtemplate will always have the selector automatically generated\n\tif spec.Spec.Selector != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"spec\", \"selector\"), spec.Spec.Selector, \"`selector` will be auto-generated\"))\n\t}\n\tif spec.Spec.ManualSelector != nil \u0026\u0026 *spec.Spec.ManualSelector {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"spec\", \"manualSelector\"), spec.Spec.ManualSelector, []string{\"nil\", \"false\"}))\n\t}\n\treturn allErrs\n}","line":{"from":556,"to":568}} {"id":100002190,"name":"validateCompletions","signature":"func validateCompletions(spec, oldSpec batch.JobSpec, fldPath *field.Path, opts JobValidationOptions) field.ErrorList","file":"pkg/apis/batch/validation/validation.go","code":"func validateCompletions(spec, oldSpec batch.JobSpec, fldPath *field.Path, opts JobValidationOptions) field.ErrorList {\n\tif !opts.AllowElasticIndexedJobs {\n\t\treturn apivalidation.ValidateImmutableField(spec.Completions, oldSpec.Completions, fldPath)\n\t}\n\n\t// Completions is immutable for non-indexed jobs.\n\t// For Indexed Jobs, if ElasticIndexedJob feature gate is not enabled,\n\t// fall back to validating that spec.Completions is always immutable.\n\tisIndexedJob := spec.CompletionMode != nil \u0026\u0026 *spec.CompletionMode == batch.IndexedCompletion\n\tif !isIndexedJob {\n\t\treturn apivalidation.ValidateImmutableField(spec.Completions, oldSpec.Completions, fldPath)\n\t}\n\n\tvar allErrs field.ErrorList\n\tif apiequality.Semantic.DeepEqual(spec.Completions, oldSpec.Completions) {\n\t\treturn allErrs\n\t}\n\t// Indexed Jobs cannot set completions to nil. The nil check\n\t// is already performed in validateJobSpec, no need to add another error.\n\tif spec.Completions == nil {\n\t\treturn allErrs\n\t}\n\n\tif *spec.Completions != *spec.Parallelism {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, spec.Completions, fmt.Sprintf(\"can only be modified in tandem with %s\", fldPath.Root().Child(\"parallelism\").String())))\n\t}\n\treturn allErrs\n}","line":{"from":570,"to":597}} {"id":100002191,"name":"ParseCSR","signature":"func ParseCSR(pemBytes []byte) (*x509.CertificateRequest, error)","file":"pkg/apis/certificates/helpers.go","code":"// ParseCSR extracts the CSR from the bytes and decodes it.\nfunc ParseCSR(pemBytes []byte) (*x509.CertificateRequest, error) {\n\tblock, _ := pem.Decode(pemBytes)\n\tif block == nil || block.Type != \"CERTIFICATE REQUEST\" {\n\t\treturn nil, errors.New(\"PEM block type must be CERTIFICATE REQUEST\")\n\t}\n\tcsr, err := x509.ParseCertificateRequest(block.Bytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn csr, nil\n}","line":{"from":30,"to":41}} {"id":100002192,"name":"IsKubeletServingCSR","signature":"func IsKubeletServingCSR(req *x509.CertificateRequest, usages sets.String) bool","file":"pkg/apis/certificates/helpers.go","code":"func IsKubeletServingCSR(req *x509.CertificateRequest, usages sets.String) bool {\n\treturn ValidateKubeletServingCSR(req, usages) == nil\n}","line":{"from":65,"to":67}} {"id":100002193,"name":"ValidateKubeletServingCSR","signature":"func ValidateKubeletServingCSR(req *x509.CertificateRequest, usages sets.String) error","file":"pkg/apis/certificates/helpers.go","code":"func ValidateKubeletServingCSR(req *x509.CertificateRequest, usages sets.String) error {\n\tif !reflect.DeepEqual([]string{\"system:nodes\"}, req.Subject.Organization) {\n\t\treturn organizationNotSystemNodesErr\n\t}\n\n\t// at least one of dnsNames or ipAddresses must be specified\n\tif len(req.DNSNames) == 0 \u0026\u0026 len(req.IPAddresses) == 0 {\n\t\treturn dnsOrIPSANRequiredErr\n\t}\n\n\tif len(req.EmailAddresses) \u003e 0 {\n\t\treturn emailSANNotAllowedErr\n\t}\n\tif len(req.URIs) \u003e 0 {\n\t\treturn uriSANNotAllowedErr\n\t}\n\n\tif !kubeletServingRequiredUsages.Equal(usages) \u0026\u0026 !kubeletServingRequiredUsagesNoRSA.Equal(usages) {\n\t\treturn fmt.Errorf(\"usages did not match %v\", kubeletServingRequiredUsages.List())\n\t}\n\n\tif !strings.HasPrefix(req.Subject.CommonName, \"system:node:\") {\n\t\treturn commonNameNotSystemNode\n\t}\n\n\treturn nil\n}","line":{"from":68,"to":94}} {"id":100002194,"name":"IsKubeletClientCSR","signature":"func IsKubeletClientCSR(req *x509.CertificateRequest, usages sets.String) bool","file":"pkg/apis/certificates/helpers.go","code":"func IsKubeletClientCSR(req *x509.CertificateRequest, usages sets.String) bool {\n\treturn ValidateKubeletClientCSR(req, usages) == nil\n}","line":{"from":108,"to":110}} {"id":100002195,"name":"ValidateKubeletClientCSR","signature":"func ValidateKubeletClientCSR(req *x509.CertificateRequest, usages sets.String) error","file":"pkg/apis/certificates/helpers.go","code":"func ValidateKubeletClientCSR(req *x509.CertificateRequest, usages sets.String) error {\n\tif !reflect.DeepEqual([]string{\"system:nodes\"}, req.Subject.Organization) {\n\t\treturn organizationNotSystemNodesErr\n\t}\n\n\tif len(req.DNSNames) \u003e 0 {\n\t\treturn dnsSANNotAllowedErr\n\t}\n\tif len(req.EmailAddresses) \u003e 0 {\n\t\treturn emailSANNotAllowedErr\n\t}\n\tif len(req.IPAddresses) \u003e 0 {\n\t\treturn ipSANNotAllowedErr\n\t}\n\tif len(req.URIs) \u003e 0 {\n\t\treturn uriSANNotAllowedErr\n\t}\n\n\tif !strings.HasPrefix(req.Subject.CommonName, \"system:node:\") {\n\t\treturn commonNameNotSystemNode\n\t}\n\n\tif !kubeletClientRequiredUsages.Equal(usages) \u0026\u0026 !kubeletClientRequiredUsagesNoRSA.Equal(usages) {\n\t\treturn fmt.Errorf(\"usages did not match %v\", kubeletClientRequiredUsages.List())\n\t}\n\n\treturn nil\n}","line":{"from":111,"to":138}} {"id":100002196,"name":"init","signature":"func init()","file":"pkg/apis/certificates/install/install.go","code":"func init() {\n\tInstall(legacyscheme.Scheme)\n}","line":{"from":31,"to":33}} {"id":100002197,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"pkg/apis/certificates/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(certificates.AddToScheme(scheme))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(v1alpha1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1.SchemeGroupVersion, v1beta1.SchemeGroupVersion, v1alpha1.SchemeGroupVersion))\n}","line":{"from":35,"to":42}} {"id":100002198,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"pkg/apis/certificates/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":35,"to":38}} {"id":100002199,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/certificates/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":40,"to":43}} {"id":100002200,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/certificates/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026CertificateSigningRequest{},\n\t\t\u0026CertificateSigningRequestList{},\n\t\t\u0026ClusterTrustBundle{},\n\t\t\u0026ClusterTrustBundleList{},\n\t)\n\treturn nil\n}","line":{"from":45,"to":54}} {"id":100002201,"name":"addConversionFuncs","signature":"func addConversionFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/certificates/v1/conversion.go","code":"func addConversionFuncs(scheme *runtime.Scheme) error {\n\t// Add field conversion funcs.\n\treturn scheme.AddFieldLabelConversionFunc(SchemeGroupVersion.WithKind(\"CertificateSigningRequest\"),\n\t\tfunc(label, value string) (string, string, error) {\n\t\t\tswitch label {\n\t\t\tcase \"metadata.name\",\n\t\t\t\t\"spec.signerName\":\n\t\t\t\treturn label, value, nil\n\t\t\tdefault:\n\t\t\t\treturn \"\", \"\", fmt.Errorf(\"field label not supported: %s\", label)\n\t\t\t}\n\t\t},\n\t)\n}","line":{"from":25,"to":38}} {"id":100002202,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/certificates/v1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":23,"to":25}} {"id":100002203,"name":"ParseCSR","signature":"func ParseCSR(pemBytes []byte) (*x509.CertificateRequest, error)","file":"pkg/apis/certificates/v1/helpers.go","code":"// ParseCSR decodes a PEM encoded CSR\nfunc ParseCSR(pemBytes []byte) (*x509.CertificateRequest, error) {\n\t// extract PEM from request object\n\tblock, _ := pem.Decode(pemBytes)\n\tif block == nil || block.Type != \"CERTIFICATE REQUEST\" {\n\t\treturn nil, errors.New(\"PEM block type must be CERTIFICATE REQUEST\")\n\t}\n\tcsr, err := x509.ParseCertificateRequest(block.Bytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn csr, nil\n}","line":{"from":25,"to":37}} {"id":100002204,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"pkg/apis/certificates/v1/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100002205,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/certificates/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100002206,"name":"init","signature":"func init()","file":"pkg/apis/certificates/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs, addConversionFuncs)\n}","line":{"from":47,"to":52}} {"id":100002207,"name":"addConversionFuncs","signature":"func addConversionFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/certificates/v1alpha1/conversion.go","code":"func addConversionFuncs(scheme *runtime.Scheme) error {\n\treturn scheme.AddFieldLabelConversionFunc(\n\t\tSchemeGroupVersion.WithKind(\"ClusterTrustBundle\"),\n\t\tfunc(label, value string) (string, string, error) {\n\t\t\tswitch label {\n\t\t\tcase \"metadata.name\", \"spec.signerName\":\n\t\t\t\treturn label, value, nil\n\t\t\tdefault:\n\t\t\t\treturn \"\", \"\", fmt.Errorf(\"field label not supported: %s\", label)\n\t\t\t}\n\t\t},\n\t)\n}","line":{"from":25,"to":37}} {"id":100002208,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/certificates/v1alpha1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":21,"to":23}} {"id":100002209,"name":"init","signature":"func init()","file":"pkg/apis/certificates/v1alpha1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs, addConversionFuncs)\n}","line":{"from":38,"to":43}} {"id":100002210,"name":"addConversionFuncs","signature":"func addConversionFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/certificates/v1beta1/conversion.go","code":"func addConversionFuncs(scheme *runtime.Scheme) error {\n\t// Add field conversion funcs.\n\treturn scheme.AddFieldLabelConversionFunc(SchemeGroupVersion.WithKind(\"CertificateSigningRequest\"),\n\t\tfunc(label, value string) (string, string, error) {\n\t\t\tswitch label {\n\t\t\tcase \"metadata.name\",\n\t\t\t\t\"spec.signerName\":\n\t\t\t\treturn label, value, nil\n\t\t\tdefault:\n\t\t\t\treturn \"\", \"\", fmt.Errorf(\"field label not supported: %s\", label)\n\t\t\t}\n\t\t},\n\t)\n}","line":{"from":25,"to":38}} {"id":100002211,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/certificates/v1beta1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":29,"to":31}} {"id":100002212,"name":"SetDefaults_CertificateSigningRequestSpec","signature":"func SetDefaults_CertificateSigningRequestSpec(obj *certificatesv1beta1.CertificateSigningRequestSpec)","file":"pkg/apis/certificates/v1beta1/defaults.go","code":"func SetDefaults_CertificateSigningRequestSpec(obj *certificatesv1beta1.CertificateSigningRequestSpec) {\n\tif obj.Usages == nil {\n\t\tobj.Usages = []certificatesv1beta1.KeyUsage{certificatesv1beta1.UsageDigitalSignature, certificatesv1beta1.UsageKeyEncipherment}\n\t}\n\n\tif obj.SignerName == nil {\n\t\tsignerName := DefaultSignerNameFromSpec(obj)\n\t\tobj.SignerName = \u0026signerName\n\t}\n}","line":{"from":33,"to":42}} {"id":100002213,"name":"SetDefaults_CertificateSigningRequestCondition","signature":"func SetDefaults_CertificateSigningRequestCondition(obj *certificatesv1beta1.CertificateSigningRequestCondition)","file":"pkg/apis/certificates/v1beta1/defaults.go","code":"func SetDefaults_CertificateSigningRequestCondition(obj *certificatesv1beta1.CertificateSigningRequestCondition) {\n\tif len(obj.Status) == 0 {\n\t\tobj.Status = v1.ConditionTrue\n\t}\n}","line":{"from":44,"to":48}} {"id":100002214,"name":"DefaultSignerNameFromSpec","signature":"func DefaultSignerNameFromSpec(obj *certificatesv1beta1.CertificateSigningRequestSpec) string","file":"pkg/apis/certificates/v1beta1/defaults.go","code":"// DefaultSignerNameFromSpec will determine the signerName that should be set\n// by attempting to inspect the 'request' content and the spec options.\nfunc DefaultSignerNameFromSpec(obj *certificatesv1beta1.CertificateSigningRequestSpec) string {\n\tcsr, err := ParseCSR(obj.Request)\n\tswitch {\n\tcase err != nil:\n\t\t// Set the signerName to 'legacy-unknown' as the CSR could not be\n\t\t// recognised.\n\t\treturn certificatesv1beta1.LegacyUnknownSignerName\n\tcase IsKubeletClientCSR(csr, obj.Usages):\n\t\treturn certificatesv1beta1.KubeAPIServerClientKubeletSignerName\n\tcase IsKubeletServingCSR(csr, obj.Usages):\n\t\treturn certificatesv1beta1.KubeletServingSignerName\n\tdefault:\n\t\treturn certificatesv1beta1.LegacyUnknownSignerName\n\t}\n}","line":{"from":50,"to":66}} {"id":100002215,"name":"IsKubeletServingCSR","signature":"func IsKubeletServingCSR(req *x509.CertificateRequest, usages []certificatesv1beta1.KeyUsage) bool","file":"pkg/apis/certificates/v1beta1/defaults.go","code":"func IsKubeletServingCSR(req *x509.CertificateRequest, usages []certificatesv1beta1.KeyUsage) bool {\n\treturn certificates.IsKubeletServingCSR(req, usagesToSet(usages))\n}","line":{"from":68,"to":70}} {"id":100002216,"name":"ValidateKubeletServingCSR","signature":"func ValidateKubeletServingCSR(req *x509.CertificateRequest, usages []certificatesv1beta1.KeyUsage) error","file":"pkg/apis/certificates/v1beta1/defaults.go","code":"func ValidateKubeletServingCSR(req *x509.CertificateRequest, usages []certificatesv1beta1.KeyUsage) error {\n\treturn certificates.ValidateKubeletServingCSR(req, usagesToSet(usages))\n}","line":{"from":71,"to":73}} {"id":100002217,"name":"IsKubeletClientCSR","signature":"func IsKubeletClientCSR(req *x509.CertificateRequest, usages []certificatesv1beta1.KeyUsage) bool","file":"pkg/apis/certificates/v1beta1/defaults.go","code":"func IsKubeletClientCSR(req *x509.CertificateRequest, usages []certificatesv1beta1.KeyUsage) bool {\n\treturn certificates.IsKubeletClientCSR(req, usagesToSet(usages))\n}","line":{"from":75,"to":77}} {"id":100002218,"name":"ValidateKubeletClientCSR","signature":"func ValidateKubeletClientCSR(req *x509.CertificateRequest, usages []certificatesv1beta1.KeyUsage) error","file":"pkg/apis/certificates/v1beta1/defaults.go","code":"func ValidateKubeletClientCSR(req *x509.CertificateRequest, usages []certificatesv1beta1.KeyUsage) error {\n\treturn certificates.ValidateKubeletClientCSR(req, usagesToSet(usages))\n}","line":{"from":78,"to":80}} {"id":100002219,"name":"usagesToSet","signature":"func usagesToSet(usages []certificatesv1beta1.KeyUsage) sets.String","file":"pkg/apis/certificates/v1beta1/defaults.go","code":"func usagesToSet(usages []certificatesv1beta1.KeyUsage) sets.String {\n\tresult := sets.NewString()\n\tfor _, usage := range usages {\n\t\tresult.Insert(string(usage))\n\t}\n\treturn result\n}","line":{"from":82,"to":88}} {"id":100002220,"name":"ParseCSR","signature":"func ParseCSR(pemBytes []byte) (*x509.CertificateRequest, error)","file":"pkg/apis/certificates/v1beta1/helpers.go","code":"// ParseCSR decodes a PEM encoded CSR\nfunc ParseCSR(pemBytes []byte) (*x509.CertificateRequest, error) {\n\t// extract PEM from request object\n\tblock, _ := pem.Decode(pemBytes)\n\tif block == nil || block.Type != \"CERTIFICATE REQUEST\" {\n\t\treturn nil, errors.New(\"PEM block type must be CERTIFICATE REQUEST\")\n\t}\n\tcsr, err := x509.ParseCertificateRequest(block.Bytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn csr, nil\n}","line":{"from":25,"to":37}} {"id":100002221,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"pkg/apis/certificates/v1beta1/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100002222,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/certificates/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100002223,"name":"init","signature":"func init()","file":"pkg/apis/certificates/v1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs, addConversionFuncs)\n}","line":{"from":45,"to":50}} {"id":100002224,"name":"validateCSR","signature":"func validateCSR(obj *certificates.CertificateSigningRequest) error","file":"pkg/apis/certificates/validation/validation.go","code":"// validateCSR validates the signature and formatting of a base64-wrapped,\n// PEM-encoded PKCS#10 certificate signing request. If this is invalid, we must\n// not accept the CSR for further processing.\nfunc validateCSR(obj *certificates.CertificateSigningRequest) error {\n\tcsr, err := certificates.ParseCSR(obj.Spec.Request)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// check that the signature is valid\n\treturn csr.CheckSignature()\n}","line":{"from":82,"to":92}} {"id":100002225,"name":"validateCertificate","signature":"func validateCertificate(pemData []byte) error","file":"pkg/apis/certificates/validation/validation.go","code":"func validateCertificate(pemData []byte) error {\n\tif len(pemData) == 0 {\n\t\treturn nil\n\t}\n\n\tblocks := 0\n\tfor {\n\t\tblock, remainingData := pem.Decode(pemData)\n\t\tif block == nil {\n\t\t\tbreak\n\t\t}\n\n\t\tif block.Type != utilcert.CertificateBlockType {\n\t\t\treturn fmt.Errorf(\"only CERTIFICATE PEM blocks are allowed, found %q\", block.Type)\n\t\t}\n\t\tif len(block.Headers) != 0 {\n\t\t\treturn fmt.Errorf(\"no PEM block headers are permitted\")\n\t\t}\n\t\tblocks++\n\n\t\tcerts, err := x509.ParseCertificates(block.Bytes)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(certs) == 0 {\n\t\t\treturn fmt.Errorf(\"found CERTIFICATE PEM block containing 0 certificates\")\n\t\t}\n\n\t\tpemData = remainingData\n\t}\n\n\tif blocks == 0 {\n\t\treturn fmt.Errorf(\"must contain at least one CERTIFICATE PEM block\")\n\t}\n\n\treturn nil\n}","line":{"from":94,"to":130}} {"id":100002226,"name":"ValidateCertificateRequestName","signature":"func ValidateCertificateRequestName(name string, prefix bool) []string","file":"pkg/apis/certificates/validation/validation.go","code":"// We don't care what you call your certificate requests.\nfunc ValidateCertificateRequestName(name string, prefix bool) []string {\n\treturn nil\n}","line":{"from":132,"to":135}} {"id":100002227,"name":"ValidateCertificateSigningRequestCreate","signature":"func ValidateCertificateSigningRequestCreate(csr *certificates.CertificateSigningRequest) field.ErrorList","file":"pkg/apis/certificates/validation/validation.go","code":"func ValidateCertificateSigningRequestCreate(csr *certificates.CertificateSigningRequest) field.ErrorList {\n\topts := getValidationOptions(csr, nil)\n\treturn validateCertificateSigningRequest(csr, opts)\n}","line":{"from":137,"to":140}} {"id":100002228,"name":"validateCertificateSigningRequest","signature":"func validateCertificateSigningRequest(csr *certificates.CertificateSigningRequest, opts certificateValidationOptions) field.ErrorList","file":"pkg/apis/certificates/validation/validation.go","code":"func validateCertificateSigningRequest(csr *certificates.CertificateSigningRequest, opts certificateValidationOptions) field.ErrorList {\n\tisNamespaced := false\n\tallErrs := apivalidation.ValidateObjectMeta(\u0026csr.ObjectMeta, isNamespaced, ValidateCertificateRequestName, field.NewPath(\"metadata\"))\n\n\tspecPath := field.NewPath(\"spec\")\n\terr := validateCSR(csr)\n\tif err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(specPath.Child(\"request\"), csr.Spec.Request, fmt.Sprintf(\"%v\", err)))\n\t}\n\tif len(csr.Spec.Usages) == 0 {\n\t\tallErrs = append(allErrs, field.Required(specPath.Child(\"usages\"), \"\"))\n\t}\n\tif !opts.allowUnknownUsages {\n\t\tfor i, usage := range csr.Spec.Usages {\n\t\t\tif !allValidUsages.Has(string(usage)) {\n\t\t\t\tallErrs = append(allErrs, field.NotSupported(specPath.Child(\"usages\").Index(i), usage, allValidUsages.List()))\n\t\t\t}\n\t\t}\n\t}\n\tif !opts.allowDuplicateUsages {\n\t\tseen := make(map[certificates.KeyUsage]bool, len(csr.Spec.Usages))\n\t\tfor i, usage := range csr.Spec.Usages {\n\t\t\tif seen[usage] {\n\t\t\t\tallErrs = append(allErrs, field.Duplicate(specPath.Child(\"usages\").Index(i), usage))\n\t\t\t}\n\t\t\tseen[usage] = true\n\t\t}\n\t}\n\tif !opts.allowLegacySignerName \u0026\u0026 csr.Spec.SignerName == certificates.LegacyUnknownSignerName {\n\t\tallErrs = append(allErrs, field.Invalid(specPath.Child(\"signerName\"), csr.Spec.SignerName, \"the legacy signerName is not allowed via this API version\"))\n\t} else {\n\t\tallErrs = append(allErrs, ValidateSignerName(specPath.Child(\"signerName\"), csr.Spec.SignerName)...)\n\t}\n\tif csr.Spec.ExpirationSeconds != nil \u0026\u0026 *csr.Spec.ExpirationSeconds \u003c 600 {\n\t\tallErrs = append(allErrs, field.Invalid(specPath.Child(\"expirationSeconds\"), *csr.Spec.ExpirationSeconds, \"may not specify a duration less than 600 seconds (10 minutes)\"))\n\t}\n\tallErrs = append(allErrs, validateConditions(field.NewPath(\"status\", \"conditions\"), csr, opts)...)\n\n\tif !opts.allowArbitraryCertificate {\n\t\tif err := validateCertificate(csr.Status.Certificate); err != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"status\", \"certificate\"), \"\u003ccertificate data\u003e\", err.Error()))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":170,"to":215}} {"id":100002229,"name":"validateConditions","signature":"func validateConditions(fldPath *field.Path, csr *certificates.CertificateSigningRequest, opts certificateValidationOptions) field.ErrorList","file":"pkg/apis/certificates/validation/validation.go","code":"func validateConditions(fldPath *field.Path, csr *certificates.CertificateSigningRequest, opts certificateValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tseenTypes := map[certificates.RequestConditionType]bool{}\n\thasApproved := false\n\thasDenied := false\n\n\tfor i, c := range csr.Status.Conditions {\n\n\t\tif !opts.allowEmptyConditionType {\n\t\t\tif len(c.Type) == 0 {\n\t\t\t\tallErrs = append(allErrs, field.Required(fldPath.Index(i).Child(\"type\"), \"\"))\n\t\t\t}\n\t\t}\n\n\t\tallowedStatusValues := allStatusValues\n\t\tif trueConditionTypes.Has(string(c.Type)) {\n\t\t\tallowedStatusValues = trueStatusOnly\n\t\t}\n\t\tswitch {\n\t\tcase c.Status == \"\":\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Index(i).Child(\"status\"), \"\"))\n\t\tcase !allowedStatusValues.Has(string(c.Status)):\n\t\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Index(i).Child(\"status\"), c.Status, allowedStatusValues.List()))\n\t\t}\n\n\t\tif !opts.allowBothApprovedAndDenied {\n\t\t\tswitch c.Type {\n\t\t\tcase certificates.CertificateApproved:\n\t\t\t\thasApproved = true\n\t\t\t\tif hasDenied {\n\t\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Index(i).Child(\"type\"), c.Type, \"Approved and Denied conditions are mutually exclusive\"))\n\t\t\t\t}\n\t\t\tcase certificates.CertificateDenied:\n\t\t\t\thasDenied = true\n\t\t\t\tif hasApproved {\n\t\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Index(i).Child(\"type\"), c.Type, \"Approved and Denied conditions are mutually exclusive\"))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif !opts.allowDuplicateConditionTypes {\n\t\t\tif seenTypes[c.Type] {\n\t\t\t\tallErrs = append(allErrs, field.Duplicate(fldPath.Index(i).Child(\"type\"), c.Type))\n\t\t\t}\n\t\t\tseenTypes[c.Type] = true\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":217,"to":267}} {"id":100002230,"name":"ValidateSignerName","signature":"func ValidateSignerName(fldPath *field.Path, signerName string) field.ErrorList","file":"pkg/apis/certificates/validation/validation.go","code":"// ensure signerName is of the form domain.com/something and up to 571 characters.\n// This length and format is specified to accommodate signerNames like:\n// \u003cfqdn\u003e/\u003cresource-namespace\u003e.\u003cresource-name\u003e.\n// The max length of a FQDN is 253 characters (DNS1123Subdomain max length)\n// The max length of a namespace name is 63 characters (DNS1123Label max length)\n// The max length of a resource name is 253 characters (DNS1123Subdomain max length)\n// We then add an additional 2 characters to account for the one '.' and one '/'.\nfunc ValidateSignerName(fldPath *field.Path, signerName string) field.ErrorList {\n\tvar el field.ErrorList\n\tif len(signerName) == 0 {\n\t\tel = append(el, field.Required(fldPath, \"\"))\n\t\treturn el\n\t}\n\n\tsegments := strings.Split(signerName, \"/\")\n\t// validate that there is one '/' in the signerName.\n\t// we do this after validating the domain segment to provide more info to the user.\n\tif len(segments) != 2 {\n\t\tel = append(el, field.Invalid(fldPath, signerName, \"must be a fully qualified domain and path of the form 'example.com/signer-name'\"))\n\t\t// return early here as we should not continue attempting to validate a missing or malformed path segment\n\t\t// (i.e. one containing multiple or zero `/`)\n\t\treturn el\n\t}\n\n\t// validate that segments[0] is less than 253 characters altogether\n\tmaxDomainSegmentLength := utilvalidation.DNS1123SubdomainMaxLength\n\tif len(segments[0]) \u003e maxDomainSegmentLength {\n\t\tel = append(el, field.TooLong(fldPath, segments[0], maxDomainSegmentLength))\n\t}\n\t// validate that segments[0] consists of valid DNS1123 labels separated by '.'\n\tdomainLabels := strings.Split(segments[0], \".\")\n\tfor _, lbl := range domainLabels {\n\t\t// use IsDNS1123Label as we want to ensure the max length of any single label in the domain\n\t\t// is 63 characters\n\t\tif errs := utilvalidation.IsDNS1123Label(lbl); len(errs) \u003e 0 {\n\t\t\tfor _, err := range errs {\n\t\t\t\tel = append(el, field.Invalid(fldPath, segments[0], fmt.Sprintf(\"validating label %q: %s\", lbl, err)))\n\t\t\t}\n\t\t\t// if we encounter any errors whilst parsing the domain segment, break from\n\t\t\t// validation as any further error messages will be duplicates, and non-distinguishable\n\t\t\t// from each other, confusing users.\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// validate that there is at least one '.' in segments[0]\n\tif len(domainLabels) \u003c 2 {\n\t\tel = append(el, field.Invalid(fldPath, segments[0], \"should be a domain with at least two segments separated by dots\"))\n\t}\n\n\t// validate that segments[1] consists of valid DNS1123 subdomains separated by '.'.\n\tpathLabels := strings.Split(segments[1], \".\")\n\tfor _, lbl := range pathLabels {\n\t\t// use IsDNS1123Subdomain because it enforces a length restriction of 253 characters\n\t\t// which is required in order to fit a full resource name into a single 'label'\n\t\tif errs := utilvalidation.IsDNS1123Subdomain(lbl); len(errs) \u003e 0 {\n\t\t\tfor _, err := range errs {\n\t\t\t\tel = append(el, field.Invalid(fldPath, segments[1], fmt.Sprintf(\"validating label %q: %s\", lbl, err)))\n\t\t\t}\n\t\t\t// if we encounter any errors whilst parsing the path segment, break from\n\t\t\t// validation as any further error messages will be duplicates, and non-distinguishable\n\t\t\t// from each other, confusing users.\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// ensure that segments[1] can accommodate a dns label + dns subdomain + '.'\n\tmaxPathSegmentLength := utilvalidation.DNS1123SubdomainMaxLength + utilvalidation.DNS1123LabelMaxLength + 1\n\tmaxSignerNameLength := maxDomainSegmentLength + maxPathSegmentLength + 1\n\tif len(signerName) \u003e maxSignerNameLength {\n\t\tel = append(el, field.TooLong(fldPath, signerName, maxSignerNameLength))\n\t}\n\n\treturn el\n}","line":{"from":269,"to":343}} {"id":100002231,"name":"ValidateCertificateSigningRequestUpdate","signature":"func ValidateCertificateSigningRequestUpdate(newCSR, oldCSR *certificates.CertificateSigningRequest) field.ErrorList","file":"pkg/apis/certificates/validation/validation.go","code":"func ValidateCertificateSigningRequestUpdate(newCSR, oldCSR *certificates.CertificateSigningRequest) field.ErrorList {\n\topts := getValidationOptions(newCSR, oldCSR)\n\treturn validateCertificateSigningRequestUpdate(newCSR, oldCSR, opts)\n}","line":{"from":345,"to":348}} {"id":100002232,"name":"ValidateCertificateSigningRequestStatusUpdate","signature":"func ValidateCertificateSigningRequestStatusUpdate(newCSR, oldCSR *certificates.CertificateSigningRequest) field.ErrorList","file":"pkg/apis/certificates/validation/validation.go","code":"func ValidateCertificateSigningRequestStatusUpdate(newCSR, oldCSR *certificates.CertificateSigningRequest) field.ErrorList {\n\topts := getValidationOptions(newCSR, oldCSR)\n\topts.allowSettingCertificate = true\n\treturn validateCertificateSigningRequestUpdate(newCSR, oldCSR, opts)\n}","line":{"from":350,"to":354}} {"id":100002233,"name":"ValidateCertificateSigningRequestApprovalUpdate","signature":"func ValidateCertificateSigningRequestApprovalUpdate(newCSR, oldCSR *certificates.CertificateSigningRequest) field.ErrorList","file":"pkg/apis/certificates/validation/validation.go","code":"func ValidateCertificateSigningRequestApprovalUpdate(newCSR, oldCSR *certificates.CertificateSigningRequest) field.ErrorList {\n\topts := getValidationOptions(newCSR, oldCSR)\n\topts.allowSettingApprovalConditions = true\n\treturn validateCertificateSigningRequestUpdate(newCSR, oldCSR, opts)\n}","line":{"from":356,"to":360}} {"id":100002234,"name":"validateCertificateSigningRequestUpdate","signature":"func validateCertificateSigningRequestUpdate(newCSR, oldCSR *certificates.CertificateSigningRequest, opts certificateValidationOptions) field.ErrorList","file":"pkg/apis/certificates/validation/validation.go","code":"func validateCertificateSigningRequestUpdate(newCSR, oldCSR *certificates.CertificateSigningRequest, opts certificateValidationOptions) field.ErrorList {\n\tvalidationErrorList := validateCertificateSigningRequest(newCSR, opts)\n\tmetaUpdateErrorList := apivalidation.ValidateObjectMetaUpdate(\u0026newCSR.ObjectMeta, \u0026oldCSR.ObjectMeta, field.NewPath(\"metadata\"))\n\n\t// prevent removal of existing Approved/Denied/Failed conditions\n\tfor _, t := range []certificates.RequestConditionType{certificates.CertificateApproved, certificates.CertificateDenied, certificates.CertificateFailed} {\n\t\toldConditions := findConditions(oldCSR, t)\n\t\tnewConditions := findConditions(newCSR, t)\n\t\tif len(newConditions) \u003c len(oldConditions) {\n\t\t\tvalidationErrorList = append(validationErrorList, field.Forbidden(field.NewPath(\"status\", \"conditions\"), fmt.Sprintf(\"updates may not remove a condition of type %q\", t)))\n\t\t}\n\t}\n\n\tif !opts.allowSettingApprovalConditions {\n\t\t// prevent addition/removal/modification of Approved/Denied conditions\n\t\tfor _, t := range []certificates.RequestConditionType{certificates.CertificateApproved, certificates.CertificateDenied} {\n\t\t\toldConditions := findConditions(oldCSR, t)\n\t\t\tnewConditions := findConditions(newCSR, t)\n\t\t\tswitch {\n\t\t\tcase len(newConditions) \u003c len(oldConditions):\n\t\t\t\t// removals are prevented above\n\t\t\tcase len(newConditions) \u003e len(oldConditions):\n\t\t\t\tvalidationErrorList = append(validationErrorList, field.Forbidden(field.NewPath(\"status\", \"conditions\"), fmt.Sprintf(\"updates may not add a condition of type %q\", t)))\n\t\t\tcase !apiequality.Semantic.DeepEqual(oldConditions, newConditions):\n\t\t\t\tconditionDiff := diff.ObjectDiff(oldConditions, newConditions)\n\t\t\t\tvalidationErrorList = append(validationErrorList, field.Forbidden(field.NewPath(\"status\", \"conditions\"), fmt.Sprintf(\"updates may not modify a condition of type %q\\n%v\", t, conditionDiff)))\n\t\t\t}\n\t\t}\n\t}\n\n\tif !bytes.Equal(newCSR.Status.Certificate, oldCSR.Status.Certificate) {\n\t\tif !opts.allowSettingCertificate {\n\t\t\tvalidationErrorList = append(validationErrorList, field.Forbidden(field.NewPath(\"status\", \"certificate\"), \"updates may not set certificate content\"))\n\t\t} else if !opts.allowResettingCertificate \u0026\u0026 len(oldCSR.Status.Certificate) \u003e 0 {\n\t\t\tvalidationErrorList = append(validationErrorList, field.Forbidden(field.NewPath(\"status\", \"certificate\"), \"updates may not modify existing certificate content\"))\n\t\t}\n\t}\n\n\treturn append(validationErrorList, metaUpdateErrorList...)\n}","line":{"from":362,"to":401}} {"id":100002235,"name":"findConditions","signature":"func findConditions(csr *certificates.CertificateSigningRequest, conditionType certificates.RequestConditionType) []certificates.CertificateSigningRequestCondition","file":"pkg/apis/certificates/validation/validation.go","code":"// findConditions returns all instances of conditions of the specified type\nfunc findConditions(csr *certificates.CertificateSigningRequest, conditionType certificates.RequestConditionType) []certificates.CertificateSigningRequestCondition {\n\tvar retval []certificates.CertificateSigningRequestCondition\n\tfor i, c := range csr.Status.Conditions {\n\t\tif c.Type == conditionType {\n\t\t\tretval = append(retval, csr.Status.Conditions[i])\n\t\t}\n\t}\n\treturn retval\n}","line":{"from":403,"to":412}} {"id":100002236,"name":"getValidationOptions","signature":"func getValidationOptions(newCSR, oldCSR *certificates.CertificateSigningRequest) certificateValidationOptions","file":"pkg/apis/certificates/validation/validation.go","code":"// getValidationOptions returns the validation options to be\n// compatible with the specified version and existing CSR.\n// oldCSR may be nil if this is a create request.\n// validation options related to subresource-specific capabilities are set to false.\nfunc getValidationOptions(newCSR, oldCSR *certificates.CertificateSigningRequest) certificateValidationOptions {\n\treturn certificateValidationOptions{\n\t\tallowResettingCertificate: false,\n\t\tallowBothApprovedAndDenied: allowBothApprovedAndDenied(oldCSR),\n\t\tallowLegacySignerName: allowLegacySignerName(oldCSR),\n\t\tallowDuplicateConditionTypes: allowDuplicateConditionTypes(oldCSR),\n\t\tallowEmptyConditionType: allowEmptyConditionType(oldCSR),\n\t\tallowArbitraryCertificate: allowArbitraryCertificate(newCSR, oldCSR),\n\t\tallowDuplicateUsages: allowDuplicateUsages(oldCSR),\n\t\tallowUnknownUsages: allowUnknownUsages(oldCSR),\n\t}\n}","line":{"from":414,"to":429}} {"id":100002237,"name":"allowBothApprovedAndDenied","signature":"func allowBothApprovedAndDenied(oldCSR *certificates.CertificateSigningRequest) bool","file":"pkg/apis/certificates/validation/validation.go","code":"func allowBothApprovedAndDenied(oldCSR *certificates.CertificateSigningRequest) bool {\n\tif oldCSR == nil {\n\t\treturn false\n\t}\n\tapproved := false\n\tdenied := false\n\tfor _, c := range oldCSR.Status.Conditions {\n\t\tif c.Type == certificates.CertificateApproved {\n\t\t\tapproved = true\n\t\t} else if c.Type == certificates.CertificateDenied {\n\t\t\tdenied = true\n\t\t}\n\t}\n\t// compatibility with existing data\n\treturn approved \u0026\u0026 denied\n}","line":{"from":431,"to":446}} {"id":100002238,"name":"allowLegacySignerName","signature":"func allowLegacySignerName(oldCSR *certificates.CertificateSigningRequest) bool","file":"pkg/apis/certificates/validation/validation.go","code":"func allowLegacySignerName(oldCSR *certificates.CertificateSigningRequest) bool {\n\tswitch {\n\tcase oldCSR != nil \u0026\u0026 oldCSR.Spec.SignerName == certificates.LegacyUnknownSignerName:\n\t\treturn true // compatibility with existing data\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":448,"to":455}} {"id":100002239,"name":"allowDuplicateConditionTypes","signature":"func allowDuplicateConditionTypes(oldCSR *certificates.CertificateSigningRequest) bool","file":"pkg/apis/certificates/validation/validation.go","code":"func allowDuplicateConditionTypes(oldCSR *certificates.CertificateSigningRequest) bool {\n\tswitch {\n\tcase oldCSR != nil \u0026\u0026 hasDuplicateConditionTypes(oldCSR):\n\t\treturn true // compatibility with existing data\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":457,"to":464}} {"id":100002240,"name":"hasDuplicateConditionTypes","signature":"func hasDuplicateConditionTypes(csr *certificates.CertificateSigningRequest) bool","file":"pkg/apis/certificates/validation/validation.go","code":"func hasDuplicateConditionTypes(csr *certificates.CertificateSigningRequest) bool {\n\tseen := map[certificates.RequestConditionType]bool{}\n\tfor _, c := range csr.Status.Conditions {\n\t\tif seen[c.Type] {\n\t\t\treturn true\n\t\t}\n\t\tseen[c.Type] = true\n\t}\n\treturn false\n}","line":{"from":465,"to":474}} {"id":100002241,"name":"allowEmptyConditionType","signature":"func allowEmptyConditionType(oldCSR *certificates.CertificateSigningRequest) bool","file":"pkg/apis/certificates/validation/validation.go","code":"func allowEmptyConditionType(oldCSR *certificates.CertificateSigningRequest) bool {\n\tswitch {\n\tcase oldCSR != nil \u0026\u0026 hasEmptyConditionType(oldCSR):\n\t\treturn true // compatibility with existing data\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":476,"to":483}} {"id":100002242,"name":"hasEmptyConditionType","signature":"func hasEmptyConditionType(csr *certificates.CertificateSigningRequest) bool","file":"pkg/apis/certificates/validation/validation.go","code":"func hasEmptyConditionType(csr *certificates.CertificateSigningRequest) bool {\n\tfor _, c := range csr.Status.Conditions {\n\t\tif len(c.Type) == 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":484,"to":491}} {"id":100002243,"name":"allowArbitraryCertificate","signature":"func allowArbitraryCertificate(newCSR, oldCSR *certificates.CertificateSigningRequest) bool","file":"pkg/apis/certificates/validation/validation.go","code":"func allowArbitraryCertificate(newCSR, oldCSR *certificates.CertificateSigningRequest) bool {\n\tswitch {\n\tcase newCSR != nil \u0026\u0026 oldCSR != nil \u0026\u0026 bytes.Equal(newCSR.Status.Certificate, oldCSR.Status.Certificate):\n\t\treturn true // tolerate updates that don't touch status.certificate\n\tcase oldCSR != nil \u0026\u0026 validateCertificate(oldCSR.Status.Certificate) != nil:\n\t\treturn true // compatibility with existing data\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":493,"to":502}} {"id":100002244,"name":"allowUnknownUsages","signature":"func allowUnknownUsages(oldCSR *certificates.CertificateSigningRequest) bool","file":"pkg/apis/certificates/validation/validation.go","code":"func allowUnknownUsages(oldCSR *certificates.CertificateSigningRequest) bool {\n\tswitch {\n\tcase oldCSR != nil \u0026\u0026 hasUnknownUsage(oldCSR.Spec.Usages):\n\t\treturn true // compatibility with existing data\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":504,"to":511}} {"id":100002245,"name":"hasUnknownUsage","signature":"func hasUnknownUsage(usages []certificates.KeyUsage) bool","file":"pkg/apis/certificates/validation/validation.go","code":"func hasUnknownUsage(usages []certificates.KeyUsage) bool {\n\tfor _, usage := range usages {\n\t\tif !allValidUsages.Has(string(usage)) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":513,"to":520}} {"id":100002246,"name":"allowDuplicateUsages","signature":"func allowDuplicateUsages(oldCSR *certificates.CertificateSigningRequest) bool","file":"pkg/apis/certificates/validation/validation.go","code":"func allowDuplicateUsages(oldCSR *certificates.CertificateSigningRequest) bool {\n\tswitch {\n\tcase oldCSR != nil \u0026\u0026 hasDuplicateUsage(oldCSR.Spec.Usages):\n\t\treturn true // compatibility with existing data\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":522,"to":529}} {"id":100002247,"name":"hasDuplicateUsage","signature":"func hasDuplicateUsage(usages []certificates.KeyUsage) bool","file":"pkg/apis/certificates/validation/validation.go","code":"func hasDuplicateUsage(usages []certificates.KeyUsage) bool {\n\tseen := make(map[certificates.KeyUsage]bool, len(usages))\n\tfor _, usage := range usages {\n\t\tif seen[usage] {\n\t\t\treturn true\n\t\t}\n\t\tseen[usage] = true\n\t}\n\treturn false\n}","line":{"from":531,"to":540}} {"id":100002248,"name":"validateClusterTrustBundleName","signature":"func validateClusterTrustBundleName(signerName string) func(name string, prefix bool) []string","file":"pkg/apis/certificates/validation/validation.go","code":"// We require your name to be prefixed by .spec.signerName\nfunc validateClusterTrustBundleName(signerName string) func(name string, prefix bool) []string {\n\treturn func(name string, isPrefix bool) []string {\n\t\tif signerName == \"\" {\n\t\t\tif strings.Contains(name, \":\") {\n\t\t\t\treturn []string{\"ClusterTrustBundle without signer name must not have \\\":\\\" in its name\"}\n\t\t\t}\n\t\t\treturn apimachineryvalidation.NameIsDNSSubdomain(name, isPrefix)\n\t\t}\n\n\t\trequiredPrefix := strings.ReplaceAll(signerName, \"/\", \":\") + \":\"\n\t\tif !strings.HasPrefix(name, requiredPrefix) {\n\t\t\treturn []string{fmt.Sprintf(\"ClusterTrustBundle for signerName %s must be named with prefix %s\", signerName, requiredPrefix)}\n\t\t}\n\t\treturn apimachineryvalidation.NameIsDNSSubdomain(strings.TrimPrefix(name, requiredPrefix), isPrefix)\n\t}\n}","line":{"from":542,"to":558}} {"id":100002249,"name":"ValidateClusterTrustBundle","signature":"func ValidateClusterTrustBundle(bundle *certificates.ClusterTrustBundle, opts ValidateClusterTrustBundleOptions) field.ErrorList","file":"pkg/apis/certificates/validation/validation.go","code":"// ValidateClusterTrustBundle runs all validation checks on bundle.\nfunc ValidateClusterTrustBundle(bundle *certificates.ClusterTrustBundle, opts ValidateClusterTrustBundleOptions) field.ErrorList {\n\tvar allErrors field.ErrorList\n\n\tmetaErrors := apivalidation.ValidateObjectMeta(\u0026bundle.ObjectMeta, false, validateClusterTrustBundleName(bundle.Spec.SignerName), field.NewPath(\"metadata\"))\n\tallErrors = append(allErrors, metaErrors...)\n\n\tif bundle.Spec.SignerName != \"\" {\n\t\tsignerNameErrors := ValidateSignerName(field.NewPath(\"spec\", \"signerName\"), bundle.Spec.SignerName)\n\t\tallErrors = append(allErrors, signerNameErrors...)\n\t}\n\n\tif !opts.SuppressBundleParsing {\n\t\tpemErrors := validateTrustBundle(field.NewPath(\"spec\", \"trustBundle\"), bundle.Spec.TrustBundle)\n\t\tallErrors = append(allErrors, pemErrors...)\n\t}\n\n\treturn allErrors\n}","line":{"from":564,"to":582}} {"id":100002250,"name":"ValidateClusterTrustBundleUpdate","signature":"func ValidateClusterTrustBundleUpdate(newBundle, oldBundle *certificates.ClusterTrustBundle) field.ErrorList","file":"pkg/apis/certificates/validation/validation.go","code":"// ValidateClusterTrustBundleUpdate runs all update validation checks on an\n// update.\nfunc ValidateClusterTrustBundleUpdate(newBundle, oldBundle *certificates.ClusterTrustBundle) field.ErrorList {\n\t// If the caller isn't changing the TrustBundle field, don't parse it.\n\t// This helps smoothly handle changes in Go's PEM or X.509 parsing\n\t// libraries.\n\topts := ValidateClusterTrustBundleOptions{}\n\tif newBundle.Spec.TrustBundle == oldBundle.Spec.TrustBundle {\n\t\topts.SuppressBundleParsing = true\n\t}\n\n\tvar allErrors field.ErrorList\n\tallErrors = append(allErrors, ValidateClusterTrustBundle(newBundle, opts)...)\n\tallErrors = append(allErrors, apivalidation.ValidateObjectMetaUpdate(\u0026newBundle.ObjectMeta, \u0026oldBundle.ObjectMeta, field.NewPath(\"metadata\"))...)\n\tallErrors = append(allErrors, apivalidation.ValidateImmutableField(newBundle.Spec.SignerName, oldBundle.Spec.SignerName, field.NewPath(\"spec\", \"signerName\"))...)\n\treturn allErrors\n}","line":{"from":584,"to":600}} {"id":100002251,"name":"validateTrustBundle","signature":"func validateTrustBundle(path *field.Path, in string) field.ErrorList","file":"pkg/apis/certificates/validation/validation.go","code":"// validateTrustBundle rejects intra-block headers, blocks\n// that don't parse as X.509 CA certificates, and duplicate trust anchors. It\n// requires that at least one trust anchor is provided.\nfunc validateTrustBundle(path *field.Path, in string) field.ErrorList {\n\tvar allErrors field.ErrorList\n\n\tblockDedupe := map[string][]int{}\n\n\trest := []byte(in)\n\tvar b *pem.Block\n\ti := -1\n\tfor {\n\t\tb, rest = pem.Decode(rest)\n\t\tif b == nil {\n\t\t\tbreak\n\t\t}\n\t\ti++\n\n\t\tif b.Type != \"CERTIFICATE\" {\n\t\t\tallErrors = append(allErrors, field.Invalid(path, \"\u003cvalue omitted\u003e\", fmt.Sprintf(\"entry %d has bad block type: %v\", i, b.Type)))\n\t\t\tcontinue\n\t\t}\n\n\t\tif len(b.Headers) != 0 {\n\t\t\tallErrors = append(allErrors, field.Invalid(path, \"\u003cvalue omitted\u003e\", fmt.Sprintf(\"entry %d has PEM block headers\", i)))\n\t\t\tcontinue\n\t\t}\n\n\t\tcert, err := x509.ParseCertificate(b.Bytes)\n\t\tif err != nil {\n\t\t\tallErrors = append(allErrors, field.Invalid(path, \"\u003cvalue omitted\u003e\", fmt.Sprintf(\"entry %d does not parse as X.509\", i)))\n\t\t\tcontinue\n\t\t}\n\n\t\tif !cert.IsCA {\n\t\t\tallErrors = append(allErrors, field.Invalid(path, \"\u003cvalue omitted\u003e\", fmt.Sprintf(\"entry %d does not have the CA bit set\", i)))\n\t\t\tcontinue\n\t\t}\n\n\t\tif !cert.BasicConstraintsValid {\n\t\t\tallErrors = append(allErrors, field.Invalid(path, \"\u003cvalue omitted\u003e\", fmt.Sprintf(\"entry %d has invalid basic constraints\", i)))\n\t\t\tcontinue\n\t\t}\n\n\t\tblockDedupe[string(b.Bytes)] = append(blockDedupe[string(b.Bytes)], i)\n\t}\n\n\t// If we had a malformed block, don't also output potentially-redundant\n\t// errors about duplicate or missing trust anchors.\n\tif len(allErrors) != 0 {\n\t\treturn allErrors\n\t}\n\n\tif len(blockDedupe) == 0 {\n\t\tallErrors = append(allErrors, field.Invalid(path, \"\u003cvalue omitted\u003e\", \"at least one trust anchor must be provided\"))\n\t}\n\n\tfor _, indices := range blockDedupe {\n\t\tif len(indices) \u003e 1 {\n\t\t\tallErrors = append(allErrors, field.Invalid(path, \"\u003cvalue omitted\u003e\", fmt.Sprintf(\"duplicate trust anchor (indices %v)\", indices)))\n\t\t}\n\t}\n\n\treturn allErrors\n}","line":{"from":602,"to":666}} {"id":100002252,"name":"init","signature":"func init()","file":"pkg/apis/coordination/install/install.go","code":"func init() {\n\tInstall(legacyscheme.Scheme)\n}","line":{"from":30,"to":32}} {"id":100002253,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"pkg/apis/coordination/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(coordination.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1.SchemeGroupVersion, v1beta1.SchemeGroupVersion))\n}","line":{"from":34,"to":40}} {"id":100002254,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"pkg/apis/coordination/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100002255,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/coordination/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100002256,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/coordination/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\t// TODO this gets cleaned up when the types are fixed\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Lease{},\n\t\t\u0026LeaseList{},\n\t)\n\treturn nil\n}","line":{"from":47,"to":55}} {"id":100002257,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/coordination/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002258,"name":"init","signature":"func init()","file":"pkg/apis/coordination/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(RegisterDefaults)\n}","line":{"from":41,"to":46}} {"id":100002259,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/coordination/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002260,"name":"init","signature":"func init()","file":"pkg/apis/coordination/v1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(RegisterDefaults)\n}","line":{"from":41,"to":46}} {"id":100002261,"name":"ValidateLease","signature":"func ValidateLease(lease *coordination.Lease) field.ErrorList","file":"pkg/apis/coordination/validation/validation.go","code":"// ValidateLease validates a Lease.\nfunc ValidateLease(lease *coordination.Lease) field.ErrorList {\n\tallErrs := validation.ValidateObjectMeta(\u0026lease.ObjectMeta, true, validation.NameIsDNSSubdomain, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateLeaseSpec(\u0026lease.Spec, field.NewPath(\"spec\"))...)\n\treturn allErrs\n}","line":{"from":25,"to":30}} {"id":100002262,"name":"ValidateLeaseUpdate","signature":"func ValidateLeaseUpdate(lease, oldLease *coordination.Lease) field.ErrorList","file":"pkg/apis/coordination/validation/validation.go","code":"// ValidateLeaseUpdate validates an update of Lease object.\nfunc ValidateLeaseUpdate(lease, oldLease *coordination.Lease) field.ErrorList {\n\tallErrs := validation.ValidateObjectMetaUpdate(\u0026lease.ObjectMeta, \u0026oldLease.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateLeaseSpec(\u0026lease.Spec, field.NewPath(\"spec\"))...)\n\treturn allErrs\n}","line":{"from":32,"to":37}} {"id":100002263,"name":"ValidateLeaseSpec","signature":"func ValidateLeaseSpec(spec *coordination.LeaseSpec, fldPath *field.Path) field.ErrorList","file":"pkg/apis/coordination/validation/validation.go","code":"// ValidateLeaseSpec validates spec of Lease.\nfunc ValidateLeaseSpec(spec *coordination.LeaseSpec, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif spec.LeaseDurationSeconds != nil \u0026\u0026 *spec.LeaseDurationSeconds \u003c= 0 {\n\t\tfld := fldPath.Child(\"leaseDurationSeconds\")\n\t\tallErrs = append(allErrs, field.Invalid(fld, spec.LeaseDurationSeconds, \"must be greater than 0\"))\n\t}\n\tif spec.LeaseTransitions != nil \u0026\u0026 *spec.LeaseTransitions \u003c 0 {\n\t\tfld := fldPath.Child(\"leaseTransitions\")\n\t\tallErrs = append(allErrs, field.Invalid(fld, spec.LeaseTransitions, \"must be greater than or equal to 0\"))\n\t}\n\treturn allErrs\n}","line":{"from":39,"to":52}} {"id":100002264,"name":"IsHugePageResourceName","signature":"func IsHugePageResourceName(name core.ResourceName) bool","file":"pkg/apis/core/helper/helpers.go","code":"// IsHugePageResourceName returns true if the resource name has the huge page\n// resource prefix.\nfunc IsHugePageResourceName(name core.ResourceName) bool {\n\treturn strings.HasPrefix(string(name), core.ResourceHugePagesPrefix)\n}","line":{"from":35,"to":39}} {"id":100002265,"name":"IsHugePageResourceValueDivisible","signature":"func IsHugePageResourceValueDivisible(name core.ResourceName, quantity resource.Quantity) bool","file":"pkg/apis/core/helper/helpers.go","code":"// IsHugePageResourceValueDivisible returns true if the resource value of storage is\n// integer multiple of page size.\nfunc IsHugePageResourceValueDivisible(name core.ResourceName, quantity resource.Quantity) bool {\n\tpageSize, err := HugePageSizeFromResourceName(name)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tif pageSize.Sign() \u003c= 0 || pageSize.MilliValue()%int64(1000) != int64(0) {\n\t\treturn false\n\t}\n\n\treturn quantity.Value()%pageSize.Value() == 0\n}","line":{"from":41,"to":54}} {"id":100002266,"name":"IsQuotaHugePageResourceName","signature":"func IsQuotaHugePageResourceName(name core.ResourceName) bool","file":"pkg/apis/core/helper/helpers.go","code":"// IsQuotaHugePageResourceName returns true if the resource name has the quota\n// related huge page resource prefix.\nfunc IsQuotaHugePageResourceName(name core.ResourceName) bool {\n\treturn strings.HasPrefix(string(name), core.ResourceHugePagesPrefix) || strings.HasPrefix(string(name), core.ResourceRequestsHugePagesPrefix)\n}","line":{"from":56,"to":60}} {"id":100002267,"name":"HugePageResourceName","signature":"func HugePageResourceName(pageSize resource.Quantity) core.ResourceName","file":"pkg/apis/core/helper/helpers.go","code":"// HugePageResourceName returns a ResourceName with the canonical hugepage\n// prefix prepended for the specified page size. The page size is converted\n// to its canonical representation.\nfunc HugePageResourceName(pageSize resource.Quantity) core.ResourceName {\n\treturn core.ResourceName(fmt.Sprintf(\"%s%s\", core.ResourceHugePagesPrefix, pageSize.String()))\n}","line":{"from":62,"to":67}} {"id":100002268,"name":"HugePageSizeFromResourceName","signature":"func HugePageSizeFromResourceName(name core.ResourceName) (resource.Quantity, error)","file":"pkg/apis/core/helper/helpers.go","code":"// HugePageSizeFromResourceName returns the page size for the specified huge page\n// resource name. If the specified input is not a valid huge page resource name\n// an error is returned.\nfunc HugePageSizeFromResourceName(name core.ResourceName) (resource.Quantity, error) {\n\tif !IsHugePageResourceName(name) {\n\t\treturn resource.Quantity{}, fmt.Errorf(\"resource name: %s is an invalid hugepage name\", name)\n\t}\n\tpageSize := strings.TrimPrefix(string(name), core.ResourceHugePagesPrefix)\n\treturn resource.ParseQuantity(pageSize)\n}","line":{"from":69,"to":78}} {"id":100002269,"name":"NonConvertibleFields","signature":"func NonConvertibleFields(annotations map[string]string) map[string]string","file":"pkg/apis/core/helper/helpers.go","code":"// NonConvertibleFields iterates over the provided map and filters out all but\n// any keys with the \"non-convertible.kubernetes.io\" prefix.\nfunc NonConvertibleFields(annotations map[string]string) map[string]string {\n\tnonConvertibleKeys := map[string]string{}\n\tfor key, value := range annotations {\n\t\tif strings.HasPrefix(key, core.NonConvertibleAnnotationPrefix) {\n\t\t\tnonConvertibleKeys[key] = value\n\t\t}\n\t}\n\treturn nonConvertibleKeys\n}","line":{"from":80,"to":90}} {"id":100002270,"name":"IsStandardResourceQuotaScope","signature":"func IsStandardResourceQuotaScope(str string) bool","file":"pkg/apis/core/helper/helpers.go","code":"// IsStandardResourceQuotaScope returns true if the scope is a standard value\nfunc IsStandardResourceQuotaScope(str string) bool {\n\treturn standardResourceQuotaScopes.Has(str) || str == string(core.ResourceQuotaScopeCrossNamespacePodAffinity)\n}","line":{"from":124,"to":127}} {"id":100002271,"name":"IsResourceQuotaScopeValidForResource","signature":"func IsResourceQuotaScopeValidForResource(scope core.ResourceQuotaScope, resource string) bool","file":"pkg/apis/core/helper/helpers.go","code":"// IsResourceQuotaScopeValidForResource returns true if the resource applies to the specified scope\nfunc IsResourceQuotaScopeValidForResource(scope core.ResourceQuotaScope, resource string) bool {\n\tswitch scope {\n\tcase core.ResourceQuotaScopeTerminating, core.ResourceQuotaScopeNotTerminating, core.ResourceQuotaScopeNotBestEffort,\n\t\tcore.ResourceQuotaScopePriorityClass, core.ResourceQuotaScopeCrossNamespacePodAffinity:\n\t\treturn podObjectCountQuotaResources.Has(resource) || podComputeQuotaResources.Has(resource)\n\tcase core.ResourceQuotaScopeBestEffort:\n\t\treturn podObjectCountQuotaResources.Has(resource)\n\tdefault:\n\t\treturn true\n\t}\n}","line":{"from":142,"to":153}} {"id":100002272,"name":"IsStandardContainerResourceName","signature":"func IsStandardContainerResourceName(str string) bool","file":"pkg/apis/core/helper/helpers.go","code":"// IsStandardContainerResourceName returns true if the container can make a resource request\n// for the specified resource\nfunc IsStandardContainerResourceName(str string) bool {\n\treturn standardContainerResources.Has(str) || IsHugePageResourceName(core.ResourceName(str))\n}","line":{"from":161,"to":165}} {"id":100002273,"name":"IsExtendedResourceName","signature":"func IsExtendedResourceName(name core.ResourceName) bool","file":"pkg/apis/core/helper/helpers.go","code":"// IsExtendedResourceName returns true if:\n// 1. the resource name is not in the default namespace;\n// 2. resource name does not have \"requests.\" prefix,\n// to avoid confusion with the convention in quota\n// 3. it satisfies the rules in IsQualifiedName() after converted into quota resource name\nfunc IsExtendedResourceName(name core.ResourceName) bool {\n\tif IsNativeResource(name) || strings.HasPrefix(string(name), core.DefaultResourceRequestsPrefix) {\n\t\treturn false\n\t}\n\t// Ensure it satisfies the rules in IsQualifiedName() after converted into quota resource name\n\tnameForQuota := fmt.Sprintf(\"%s%s\", core.DefaultResourceRequestsPrefix, string(name))\n\tif errs := validation.IsQualifiedName(nameForQuota); len(errs) != 0 {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":167,"to":182}} {"id":100002274,"name":"IsNativeResource","signature":"func IsNativeResource(name core.ResourceName) bool","file":"pkg/apis/core/helper/helpers.go","code":"// IsNativeResource returns true if the resource name is in the\n// *kubernetes.io/ namespace. Partially-qualified (unprefixed) names are\n// implicitly in the kubernetes.io/ namespace.\nfunc IsNativeResource(name core.ResourceName) bool {\n\treturn !strings.Contains(string(name), \"/\") ||\n\t\tstrings.Contains(string(name), core.ResourceDefaultNamespacePrefix)\n}","line":{"from":184,"to":190}} {"id":100002275,"name":"IsOvercommitAllowed","signature":"func IsOvercommitAllowed(name core.ResourceName) bool","file":"pkg/apis/core/helper/helpers.go","code":"// IsOvercommitAllowed returns true if the resource is in the default\n// namespace and is not hugepages.\nfunc IsOvercommitAllowed(name core.ResourceName) bool {\n\treturn IsNativeResource(name) \u0026\u0026\n\t\t!IsHugePageResourceName(name)\n}","line":{"from":192,"to":197}} {"id":100002276,"name":"IsStandardLimitRangeType","signature":"func IsStandardLimitRangeType(str string) bool","file":"pkg/apis/core/helper/helpers.go","code":"// IsStandardLimitRangeType returns true if the type is Pod or Container\nfunc IsStandardLimitRangeType(str string) bool {\n\treturn standardLimitRangeTypes.Has(str)\n}","line":{"from":205,"to":208}} {"id":100002277,"name":"IsStandardQuotaResourceName","signature":"func IsStandardQuotaResourceName(str string) bool","file":"pkg/apis/core/helper/helpers.go","code":"// IsStandardQuotaResourceName returns true if the resource is known to\n// the quota tracking system\nfunc IsStandardQuotaResourceName(str string) bool {\n\treturn standardQuotaResources.Has(str) || IsQuotaHugePageResourceName(core.ResourceName(str))\n}","line":{"from":232,"to":236}} {"id":100002278,"name":"IsStandardResourceName","signature":"func IsStandardResourceName(str string) bool","file":"pkg/apis/core/helper/helpers.go","code":"// IsStandardResourceName returns true if the resource is known to the system\nfunc IsStandardResourceName(str string) bool {\n\treturn standardResources.Has(str) || IsQuotaHugePageResourceName(core.ResourceName(str))\n}","line":{"from":261,"to":264}} {"id":100002279,"name":"IsIntegerResourceName","signature":"func IsIntegerResourceName(str string) bool","file":"pkg/apis/core/helper/helpers.go","code":"// IsIntegerResourceName returns true if the resource is measured in integer values\nfunc IsIntegerResourceName(str string) bool {\n\treturn integerResources.Has(str) || IsExtendedResourceName(core.ResourceName(str))\n}","line":{"from":278,"to":281}} {"id":100002280,"name":"IsServiceIPSet","signature":"func IsServiceIPSet(service *core.Service) bool","file":"pkg/apis/core/helper/helpers.go","code":"// IsServiceIPSet aims to check if the service's ClusterIP is set or not\n// the objective is not to perform validation here\nfunc IsServiceIPSet(service *core.Service) bool {\n\t// This function assumes that the service is semantically validated\n\t// it does not test if the IP is valid, just makes sure that it is set.\n\treturn len(service.Spec.ClusterIP) \u003e 0 \u0026\u0026\n\t\tservice.Spec.ClusterIP != core.ClusterIPNone\n}","line":{"from":283,"to":290}} {"id":100002281,"name":"IsStandardFinalizerName","signature":"func IsStandardFinalizerName(str string) bool","file":"pkg/apis/core/helper/helpers.go","code":"// IsStandardFinalizerName checks if the input string is a standard finalizer name\nfunc IsStandardFinalizerName(str string) bool {\n\treturn standardFinalizers.Has(str)\n}","line":{"from":298,"to":301}} {"id":100002282,"name":"GetAccessModesAsString","signature":"func GetAccessModesAsString(modes []core.PersistentVolumeAccessMode) string","file":"pkg/apis/core/helper/helpers.go","code":"// GetAccessModesAsString returns a string representation of an array of access modes.\n// modes, when present, are always in the same order: RWO,ROX,RWX,RWOP.\nfunc GetAccessModesAsString(modes []core.PersistentVolumeAccessMode) string {\n\tmodes = removeDuplicateAccessModes(modes)\n\tmodesStr := []string{}\n\tif ContainsAccessMode(modes, core.ReadWriteOnce) {\n\t\tmodesStr = append(modesStr, \"RWO\")\n\t}\n\tif ContainsAccessMode(modes, core.ReadOnlyMany) {\n\t\tmodesStr = append(modesStr, \"ROX\")\n\t}\n\tif ContainsAccessMode(modes, core.ReadWriteMany) {\n\t\tmodesStr = append(modesStr, \"RWX\")\n\t}\n\tif ContainsAccessMode(modes, core.ReadWriteOncePod) {\n\t\tmodesStr = append(modesStr, \"RWOP\")\n\t}\n\treturn strings.Join(modesStr, \",\")\n}","line":{"from":303,"to":321}} {"id":100002283,"name":"GetAccessModesFromString","signature":"func GetAccessModesFromString(modes string) []core.PersistentVolumeAccessMode","file":"pkg/apis/core/helper/helpers.go","code":"// GetAccessModesFromString returns an array of AccessModes from a string created by GetAccessModesAsString\nfunc GetAccessModesFromString(modes string) []core.PersistentVolumeAccessMode {\n\tstrmodes := strings.Split(modes, \",\")\n\taccessModes := []core.PersistentVolumeAccessMode{}\n\tfor _, s := range strmodes {\n\t\ts = strings.Trim(s, \" \")\n\t\tswitch {\n\t\tcase s == \"RWO\":\n\t\t\taccessModes = append(accessModes, core.ReadWriteOnce)\n\t\tcase s == \"ROX\":\n\t\t\taccessModes = append(accessModes, core.ReadOnlyMany)\n\t\tcase s == \"RWX\":\n\t\t\taccessModes = append(accessModes, core.ReadWriteMany)\n\t\tcase s == \"RWOP\":\n\t\t\taccessModes = append(accessModes, core.ReadWriteOncePod)\n\t\t}\n\t}\n\treturn accessModes\n}","line":{"from":323,"to":341}} {"id":100002284,"name":"removeDuplicateAccessModes","signature":"func removeDuplicateAccessModes(modes []core.PersistentVolumeAccessMode) []core.PersistentVolumeAccessMode","file":"pkg/apis/core/helper/helpers.go","code":"// removeDuplicateAccessModes returns an array of access modes without any duplicates\nfunc removeDuplicateAccessModes(modes []core.PersistentVolumeAccessMode) []core.PersistentVolumeAccessMode {\n\taccessModes := []core.PersistentVolumeAccessMode{}\n\tfor _, m := range modes {\n\t\tif !ContainsAccessMode(accessModes, m) {\n\t\t\taccessModes = append(accessModes, m)\n\t\t}\n\t}\n\treturn accessModes\n}","line":{"from":343,"to":352}} {"id":100002285,"name":"ContainsAccessMode","signature":"func ContainsAccessMode(modes []core.PersistentVolumeAccessMode, mode core.PersistentVolumeAccessMode) bool","file":"pkg/apis/core/helper/helpers.go","code":"func ContainsAccessMode(modes []core.PersistentVolumeAccessMode, mode core.PersistentVolumeAccessMode) bool {\n\tfor _, m := range modes {\n\t\tif m == mode {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":354,"to":361}} {"id":100002286,"name":"GetTolerationsFromPodAnnotations","signature":"func GetTolerationsFromPodAnnotations(annotations map[string]string) ([]core.Toleration, error)","file":"pkg/apis/core/helper/helpers.go","code":"// GetTolerationsFromPodAnnotations gets the json serialized tolerations data from Pod.Annotations\n// and converts it to the []Toleration type in core.\nfunc GetTolerationsFromPodAnnotations(annotations map[string]string) ([]core.Toleration, error) {\n\tvar tolerations []core.Toleration\n\tif len(annotations) \u003e 0 \u0026\u0026 annotations[core.TolerationsAnnotationKey] != \"\" {\n\t\terr := json.Unmarshal([]byte(annotations[core.TolerationsAnnotationKey]), \u0026tolerations)\n\t\tif err != nil {\n\t\t\treturn tolerations, err\n\t\t}\n\t}\n\treturn tolerations, nil\n}","line":{"from":363,"to":374}} {"id":100002287,"name":"AddOrUpdateTolerationInPod","signature":"func AddOrUpdateTolerationInPod(pod *core.Pod, toleration *core.Toleration) bool","file":"pkg/apis/core/helper/helpers.go","code":"// AddOrUpdateTolerationInPod tries to add a toleration to the pod's toleration list.\n// Returns true if something was updated, false otherwise.\nfunc AddOrUpdateTolerationInPod(pod *core.Pod, toleration *core.Toleration) bool {\n\tpodTolerations := pod.Spec.Tolerations\n\n\tvar newTolerations []core.Toleration\n\tupdated := false\n\tfor i := range podTolerations {\n\t\tif toleration.MatchToleration(\u0026podTolerations[i]) {\n\t\t\tif Semantic.DeepEqual(toleration, podTolerations[i]) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tnewTolerations = append(newTolerations, *toleration)\n\t\t\tupdated = true\n\t\t\tcontinue\n\t\t}\n\n\t\tnewTolerations = append(newTolerations, podTolerations[i])\n\t}\n\n\tif !updated {\n\t\tnewTolerations = append(newTolerations, *toleration)\n\t}\n\n\tpod.Spec.Tolerations = newTolerations\n\treturn true\n}","line":{"from":376,"to":402}} {"id":100002288,"name":"GetTaintsFromNodeAnnotations","signature":"func GetTaintsFromNodeAnnotations(annotations map[string]string) ([]core.Taint, error)","file":"pkg/apis/core/helper/helpers.go","code":"// GetTaintsFromNodeAnnotations gets the json serialized taints data from Pod.Annotations\n// and converts it to the []Taint type in core.\nfunc GetTaintsFromNodeAnnotations(annotations map[string]string) ([]core.Taint, error) {\n\tvar taints []core.Taint\n\tif len(annotations) \u003e 0 \u0026\u0026 annotations[core.TaintsAnnotationKey] != \"\" {\n\t\terr := json.Unmarshal([]byte(annotations[core.TaintsAnnotationKey]), \u0026taints)\n\t\tif err != nil {\n\t\t\treturn []core.Taint{}, err\n\t\t}\n\t}\n\treturn taints, nil\n}","line":{"from":404,"to":415}} {"id":100002289,"name":"GetPersistentVolumeClass","signature":"func GetPersistentVolumeClass(volume *core.PersistentVolume) string","file":"pkg/apis/core/helper/helpers.go","code":"// GetPersistentVolumeClass returns StorageClassName.\nfunc GetPersistentVolumeClass(volume *core.PersistentVolume) string {\n\t// Use beta annotation first\n\tif class, found := volume.Annotations[core.BetaStorageClassAnnotation]; found {\n\t\treturn class\n\t}\n\n\treturn volume.Spec.StorageClassName\n}","line":{"from":417,"to":425}} {"id":100002290,"name":"GetPersistentVolumeClaimClass","signature":"func GetPersistentVolumeClaimClass(claim *core.PersistentVolumeClaim) string","file":"pkg/apis/core/helper/helpers.go","code":"// GetPersistentVolumeClaimClass returns StorageClassName. If no storage class was\n// requested, it returns \"\".\nfunc GetPersistentVolumeClaimClass(claim *core.PersistentVolumeClaim) string {\n\t// Use beta annotation first\n\tif class, found := claim.Annotations[core.BetaStorageClassAnnotation]; found {\n\t\treturn class\n\t}\n\n\tif claim.Spec.StorageClassName != nil {\n\t\treturn *claim.Spec.StorageClassName\n\t}\n\n\treturn \"\"\n}","line":{"from":427,"to":440}} {"id":100002291,"name":"PersistentVolumeClaimHasClass","signature":"func PersistentVolumeClaimHasClass(claim *core.PersistentVolumeClaim) bool","file":"pkg/apis/core/helper/helpers.go","code":"// PersistentVolumeClaimHasClass returns true if given claim has set StorageClassName field.\nfunc PersistentVolumeClaimHasClass(claim *core.PersistentVolumeClaim) bool {\n\t// Use beta annotation first\n\tif _, found := claim.Annotations[core.BetaStorageClassAnnotation]; found {\n\t\treturn true\n\t}\n\n\tif claim.Spec.StorageClassName != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":442,"to":454}} {"id":100002292,"name":"toResourceNames","signature":"func toResourceNames(resources core.ResourceList) []core.ResourceName","file":"pkg/apis/core/helper/helpers.go","code":"func toResourceNames(resources core.ResourceList) []core.ResourceName {\n\tresult := []core.ResourceName{}\n\tfor resourceName := range resources {\n\t\tresult = append(result, resourceName)\n\t}\n\treturn result\n}","line":{"from":456,"to":462}} {"id":100002293,"name":"toSet","signature":"func toSet(resourceNames []core.ResourceName) sets.String","file":"pkg/apis/core/helper/helpers.go","code":"func toSet(resourceNames []core.ResourceName) sets.String {\n\tresult := sets.NewString()\n\tfor _, resourceName := range resourceNames {\n\t\tresult.Insert(string(resourceName))\n\t}\n\treturn result\n}","line":{"from":464,"to":470}} {"id":100002294,"name":"toContainerResourcesSet","signature":"func toContainerResourcesSet(ctr *core.Container) sets.String","file":"pkg/apis/core/helper/helpers.go","code":"// toContainerResourcesSet returns a set of resources names in container resource requirements\nfunc toContainerResourcesSet(ctr *core.Container) sets.String {\n\tresourceNames := toResourceNames(ctr.Resources.Requests)\n\tresourceNames = append(resourceNames, toResourceNames(ctr.Resources.Limits)...)\n\treturn toSet(resourceNames)\n}","line":{"from":472,"to":477}} {"id":100002295,"name":"ToPodResourcesSet","signature":"func ToPodResourcesSet(podSpec *core.PodSpec) sets.String","file":"pkg/apis/core/helper/helpers.go","code":"// ToPodResourcesSet returns a set of resource names in all containers in a pod.\nfunc ToPodResourcesSet(podSpec *core.PodSpec) sets.String {\n\tresult := sets.NewString()\n\tfor i := range podSpec.InitContainers {\n\t\tresult = result.Union(toContainerResourcesSet(\u0026podSpec.InitContainers[i]))\n\t}\n\tfor i := range podSpec.Containers {\n\t\tresult = result.Union(toContainerResourcesSet(\u0026podSpec.Containers[i]))\n\t}\n\treturn result\n}","line":{"from":479,"to":489}} {"id":100002296,"name":"GetDeletionCostFromPodAnnotations","signature":"func GetDeletionCostFromPodAnnotations(annotations map[string]string) (int32, error)","file":"pkg/apis/core/helper/helpers.go","code":"// GetDeletionCostFromPodAnnotations returns the integer value of pod-deletion-cost. Returns 0\n// if not set or the value is invalid.\nfunc GetDeletionCostFromPodAnnotations(annotations map[string]string) (int32, error) {\n\tif value, exist := annotations[core.PodDeletionCost]; exist {\n\t\t// values that start with plus sign (e.g, \"+10\") or leading zeros (e.g., \"008\") are not valid.\n\t\tif !validFirstDigit(value) {\n\t\t\treturn 0, fmt.Errorf(\"invalid value %q\", value)\n\t\t}\n\n\t\ti, err := strconv.ParseInt(value, 10, 32)\n\t\tif err != nil {\n\t\t\t// make sure we default to 0 on error.\n\t\t\treturn 0, err\n\t\t}\n\t\treturn int32(i), nil\n\t}\n\treturn 0, nil\n}","line":{"from":491,"to":508}} {"id":100002297,"name":"validFirstDigit","signature":"func validFirstDigit(str string) bool","file":"pkg/apis/core/helper/helpers.go","code":"func validFirstDigit(str string) bool {\n\tif len(str) == 0 {\n\t\treturn false\n\t}\n\treturn str[0] == '-' || (str[0] == '0' \u0026\u0026 str == \"0\") || (str[0] \u003e= '1' \u0026\u0026 str[0] \u003c= '9')\n}","line":{"from":510,"to":515}} {"id":100002298,"name":"isSupportedQoSComputeResource","signature":"func isSupportedQoSComputeResource(name core.ResourceName) bool","file":"pkg/apis/core/helper/qos/qos.go","code":"func isSupportedQoSComputeResource(name core.ResourceName) bool {\n\treturn supportedQoSComputeResources.Has(string(name))\n}","line":{"from":29,"to":31}} {"id":100002299,"name":"GetPodQOS","signature":"func GetPodQOS(pod *core.Pod) core.PodQOSClass","file":"pkg/apis/core/helper/qos/qos.go","code":"// GetPodQOS returns the QoS class of a pod.\n// A pod is besteffort if none of its containers have specified any requests or limits.\n// A pod is guaranteed only when requests and limits are specified for all the containers and they are equal.\n// A pod is burstable if limits and requests do not match across all containers.\n// When this function is updated please also update staging/src/k8s.io/kubectl/pkg/util/qos/qos.go\nfunc GetPodQOS(pod *core.Pod) core.PodQOSClass {\n\trequests := core.ResourceList{}\n\tlimits := core.ResourceList{}\n\tzeroQuantity := resource.MustParse(\"0\")\n\tisGuaranteed := true\n\t// note, ephemeral containers are not considered for QoS as they cannot define resources\n\tallContainers := []core.Container{}\n\tallContainers = append(allContainers, pod.Spec.Containers...)\n\tallContainers = append(allContainers, pod.Spec.InitContainers...)\n\tfor _, container := range allContainers {\n\t\t// process requests\n\t\tfor name, quantity := range container.Resources.Requests {\n\t\t\tif !isSupportedQoSComputeResource(name) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif quantity.Cmp(zeroQuantity) == 1 {\n\t\t\t\tdelta := quantity.DeepCopy()\n\t\t\t\tif _, exists := requests[name]; !exists {\n\t\t\t\t\trequests[name] = delta\n\t\t\t\t} else {\n\t\t\t\t\tdelta.Add(requests[name])\n\t\t\t\t\trequests[name] = delta\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// process limits\n\t\tqosLimitsFound := sets.NewString()\n\t\tfor name, quantity := range container.Resources.Limits {\n\t\t\tif !isSupportedQoSComputeResource(name) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif quantity.Cmp(zeroQuantity) == 1 {\n\t\t\t\tqosLimitsFound.Insert(string(name))\n\t\t\t\tdelta := quantity.DeepCopy()\n\t\t\t\tif _, exists := limits[name]; !exists {\n\t\t\t\t\tlimits[name] = delta\n\t\t\t\t} else {\n\t\t\t\t\tdelta.Add(limits[name])\n\t\t\t\t\tlimits[name] = delta\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif !qosLimitsFound.HasAll(string(core.ResourceMemory), string(core.ResourceCPU)) {\n\t\t\tisGuaranteed = false\n\t\t}\n\t}\n\tif len(requests) == 0 \u0026\u0026 len(limits) == 0 {\n\t\treturn core.PodQOSBestEffort\n\t}\n\t// Check is requests match limits for all resources.\n\tif isGuaranteed {\n\t\tfor name, req := range requests {\n\t\t\tif lim, exists := limits[name]; !exists || lim.Cmp(req) != 0 {\n\t\t\t\tisGuaranteed = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif isGuaranteed \u0026\u0026\n\t\tlen(requests) == len(limits) {\n\t\treturn core.PodQOSGuaranteed\n\t}\n\treturn core.PodQOSBurstable\n}","line":{"from":33,"to":102}} {"id":100002300,"name":"init","signature":"func init()","file":"pkg/apis/core/install/install.go","code":"func init() {\n\tInstall(legacyscheme.Scheme)\n}","line":{"from":29,"to":31}} {"id":100002301,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"pkg/apis/core/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(core.AddToScheme(scheme))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1.SchemeGroupVersion))\n}","line":{"from":33,"to":38}} {"id":100002302,"name":"MarshalJSON","signature":"func (AvoidPods) MarshalJSON() ([]byte, error) { panic(\"do not marshal internal struct\") }","file":"pkg/apis/core/json.go","code":"// MarshalJSON panics to prevent marshalling of internal structs\nfunc (AvoidPods) MarshalJSON() ([]byte, error) { panic(\"do not marshal internal struct\") }","line":{"from":27,"to":28}} {"id":100002303,"name":"UnmarshalJSON","signature":"func (*AvoidPods) UnmarshalJSON([]byte) error { panic(\"do not unmarshal to internal struct\") }","file":"pkg/apis/core/json.go","code":"// UnmarshalJSON panics to prevent unmarshalling of internal structs\nfunc (*AvoidPods) UnmarshalJSON([]byte) error { panic(\"do not unmarshal to internal struct\") }","line":{"from":30,"to":31}} {"id":100002304,"name":"SetGroupVersionKind","signature":"func (obj *ObjectReference) SetGroupVersionKind(gvk schema.GroupVersionKind)","file":"pkg/apis/core/objectreference.go","code":"// SetGroupVersionKind sets the API version and kind of the object reference\nfunc (obj *ObjectReference) SetGroupVersionKind(gvk schema.GroupVersionKind) {\n\tobj.APIVersion, obj.Kind = gvk.ToAPIVersionAndKind()\n}","line":{"from":26,"to":29}} {"id":100002305,"name":"GroupVersionKind","signature":"func (obj *ObjectReference) GroupVersionKind() schema.GroupVersionKind","file":"pkg/apis/core/objectreference.go","code":"// GroupVersionKind returns the API version and kind of the object reference\nfunc (obj *ObjectReference) GroupVersionKind() schema.GroupVersionKind {\n\treturn schema.FromAPIVersionAndKind(obj.APIVersion, obj.Kind)\n}","line":{"from":31,"to":34}} {"id":100002306,"name":"GetObjectKind","signature":"func (obj *ObjectReference) GetObjectKind() schema.ObjectKind { return obj }","file":"pkg/apis/core/objectreference.go","code":"// GetObjectKind returns the kind of object reference\nfunc (obj *ObjectReference) GetObjectKind() schema.ObjectKind { return obj }","line":{"from":36,"to":37}} {"id":100002307,"name":"VisitContainersWithPath","signature":"func VisitContainersWithPath(podSpec *api.PodSpec, specPath *field.Path, visitor ContainerVisitorWithPath) bool","file":"pkg/apis/core/pods/helpers.go","code":"// VisitContainersWithPath invokes the visitor function with a pointer to the spec\n// of every container in the given pod spec and the field.Path to that container.\n// If visitor returns false, visiting is short-circuited. VisitContainersWithPath returns true if visiting completes,\n// false if visiting was short-circuited.\nfunc VisitContainersWithPath(podSpec *api.PodSpec, specPath *field.Path, visitor ContainerVisitorWithPath) bool {\n\tfldPath := specPath.Child(\"initContainers\")\n\tfor i := range podSpec.InitContainers {\n\t\tif !visitor(\u0026podSpec.InitContainers[i], fldPath.Index(i)) {\n\t\t\treturn false\n\t\t}\n\t}\n\tfldPath = specPath.Child(\"containers\")\n\tfor i := range podSpec.Containers {\n\t\tif !visitor(\u0026podSpec.Containers[i], fldPath.Index(i)) {\n\t\t\treturn false\n\t\t}\n\t}\n\tfldPath = specPath.Child(\"ephemeralContainers\")\n\tfor i := range podSpec.EphemeralContainers {\n\t\tif !visitor((*api.Container)(\u0026podSpec.EphemeralContainers[i].EphemeralContainerCommon), fldPath.Index(i)) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":31,"to":55}} {"id":100002308,"name":"ConvertDownwardAPIFieldLabel","signature":"func ConvertDownwardAPIFieldLabel(version, label, value string) (string, string, error)","file":"pkg/apis/core/pods/helpers.go","code":"// ConvertDownwardAPIFieldLabel converts the specified downward API field label\n// and its value in the pod of the specified version to the internal version,\n// and returns the converted label and value. This function returns an error if\n// the conversion fails.\nfunc ConvertDownwardAPIFieldLabel(version, label, value string) (string, string, error) {\n\tif version != \"v1\" {\n\t\treturn \"\", \"\", fmt.Errorf(\"unsupported pod version: %s\", version)\n\t}\n\n\tif path, _, ok := fieldpath.SplitMaybeSubscriptedPath(label); ok {\n\t\tswitch path {\n\t\tcase \"metadata.annotations\", \"metadata.labels\":\n\t\t\treturn label, value, nil\n\t\tdefault:\n\t\t\treturn \"\", \"\", fmt.Errorf(\"field label does not support subscript: %s\", label)\n\t\t}\n\t}\n\n\tswitch label {\n\tcase \"metadata.annotations\",\n\t\t\"metadata.labels\",\n\t\t\"metadata.name\",\n\t\t\"metadata.namespace\",\n\t\t\"metadata.uid\",\n\t\t\"spec.nodeName\",\n\t\t\"spec.restartPolicy\",\n\t\t\"spec.serviceAccountName\",\n\t\t\"spec.schedulerName\",\n\t\t\"status.phase\",\n\t\t\"status.hostIP\",\n\t\t\"status.podIP\",\n\t\t\"status.podIPs\":\n\t\treturn label, value, nil\n\t// This is for backwards compatibility with old v1 clients which send spec.host\n\tcase \"spec.host\":\n\t\treturn \"spec.nodeName\", value, nil\n\tdefault:\n\t\treturn \"\", \"\", fmt.Errorf(\"field label not supported: %s\", label)\n\t}\n}","line":{"from":57,"to":96}} {"id":100002309,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"pkg/apis/core/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":31,"to":34}} {"id":100002310,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/core/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":36,"to":39}} {"id":100002311,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/core/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tif err := scheme.AddIgnoredConversionType(\u0026metav1.TypeMeta{}, \u0026metav1.TypeMeta{}); err != nil {\n\t\treturn err\n\t}\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Pod{},\n\t\t\u0026PodList{},\n\t\t\u0026PodStatusResult{},\n\t\t\u0026PodTemplate{},\n\t\t\u0026PodTemplateList{},\n\t\t\u0026ReplicationControllerList{},\n\t\t\u0026ReplicationController{},\n\t\t\u0026ServiceList{},\n\t\t\u0026Service{},\n\t\t\u0026ServiceProxyOptions{},\n\t\t\u0026NodeList{},\n\t\t\u0026Node{},\n\t\t\u0026NodeProxyOptions{},\n\t\t\u0026Endpoints{},\n\t\t\u0026EndpointsList{},\n\t\t\u0026Binding{},\n\t\t\u0026Event{},\n\t\t\u0026EventList{},\n\t\t\u0026List{},\n\t\t\u0026LimitRange{},\n\t\t\u0026LimitRangeList{},\n\t\t\u0026ResourceQuota{},\n\t\t\u0026ResourceQuotaList{},\n\t\t\u0026Namespace{},\n\t\t\u0026NamespaceList{},\n\t\t\u0026ServiceAccount{},\n\t\t\u0026ServiceAccountList{},\n\t\t\u0026Secret{},\n\t\t\u0026SecretList{},\n\t\t\u0026PersistentVolume{},\n\t\t\u0026PersistentVolumeList{},\n\t\t\u0026PersistentVolumeClaim{},\n\t\t\u0026PersistentVolumeClaimList{},\n\t\t\u0026PodAttachOptions{},\n\t\t\u0026PodLogOptions{},\n\t\t\u0026PodExecOptions{},\n\t\t\u0026PodPortForwardOptions{},\n\t\t\u0026PodProxyOptions{},\n\t\t\u0026ComponentStatus{},\n\t\t\u0026ComponentStatusList{},\n\t\t\u0026SerializedReference{},\n\t\t\u0026RangeAllocation{},\n\t\t\u0026ConfigMap{},\n\t\t\u0026ConfigMapList{},\n\t)\n\n\treturn nil\n}","line":{"from":50,"to":102}} {"id":100002312,"name":"String","signature":"func (rn ResourceName) String() string","file":"pkg/apis/core/resource.go","code":"func (rn ResourceName) String() string {\n\treturn string(rn)\n}","line":{"from":23,"to":25}} {"id":100002313,"name":"CPU","signature":"func (rl *ResourceList) CPU() *resource.Quantity","file":"pkg/apis/core/resource.go","code":"// CPU returns the CPU limit if specified.\nfunc (rl *ResourceList) CPU() *resource.Quantity {\n\treturn rl.Name(ResourceCPU, resource.DecimalSI)\n}","line":{"from":27,"to":30}} {"id":100002314,"name":"Memory","signature":"func (rl *ResourceList) Memory() *resource.Quantity","file":"pkg/apis/core/resource.go","code":"// Memory returns the Memory limit if specified.\nfunc (rl *ResourceList) Memory() *resource.Quantity {\n\treturn rl.Name(ResourceMemory, resource.BinarySI)\n}","line":{"from":32,"to":35}} {"id":100002315,"name":"Storage","signature":"func (rl *ResourceList) Storage() *resource.Quantity","file":"pkg/apis/core/resource.go","code":"// Storage returns the Storage limit if specified.\nfunc (rl *ResourceList) Storage() *resource.Quantity {\n\treturn rl.Name(ResourceStorage, resource.BinarySI)\n}","line":{"from":37,"to":40}} {"id":100002316,"name":"Pods","signature":"func (rl *ResourceList) Pods() *resource.Quantity","file":"pkg/apis/core/resource.go","code":"// Pods returns the list of pods\nfunc (rl *ResourceList) Pods() *resource.Quantity {\n\treturn rl.Name(ResourcePods, resource.DecimalSI)\n}","line":{"from":42,"to":45}} {"id":100002317,"name":"StorageEphemeral","signature":"func (rl *ResourceList) StorageEphemeral() *resource.Quantity","file":"pkg/apis/core/resource.go","code":"// StorageEphemeral returns the list of ephemeral storage volumes, if any\nfunc (rl *ResourceList) StorageEphemeral() *resource.Quantity {\n\treturn rl.Name(ResourceEphemeralStorage, resource.BinarySI)\n}","line":{"from":47,"to":50}} {"id":100002318,"name":"Name","signature":"func (rl *ResourceList) Name(name ResourceName, defaultFormat resource.Format) *resource.Quantity","file":"pkg/apis/core/resource.go","code":"// Name returns the resource with name if specified, otherwise it returns a nil quantity with default format.\nfunc (rl *ResourceList) Name(name ResourceName, defaultFormat resource.Format) *resource.Quantity {\n\tif val, ok := (*rl)[name]; ok {\n\t\treturn \u0026val\n\t}\n\treturn \u0026resource.Quantity{Format: defaultFormat}\n}","line":{"from":52,"to":58}} {"id":100002319,"name":"MatchTaint","signature":"func (t *Taint) MatchTaint(taintToMatch Taint) bool","file":"pkg/apis/core/taint.go","code":"// MatchTaint checks if the taint matches taintToMatch. Taints are unique by key:effect,\n// if the two taints have same key:effect, regard as they match.\nfunc (t *Taint) MatchTaint(taintToMatch Taint) bool {\n\treturn t.Key == taintToMatch.Key \u0026\u0026 t.Effect == taintToMatch.Effect\n}","line":{"from":24,"to":28}} {"id":100002320,"name":"ToString","signature":"func (t *Taint) ToString() string","file":"pkg/apis/core/taint.go","code":"// ToString converts taint struct to string in format '\u003ckey\u003e=\u003cvalue\u003e:\u003ceffect\u003e', '\u003ckey\u003e=\u003cvalue\u003e:', '\u003ckey\u003e:\u003ceffect\u003e', or '\u003ckey\u003e'.\nfunc (t *Taint) ToString() string {\n\tif len(t.Effect) == 0 {\n\t\tif len(t.Value) == 0 {\n\t\t\treturn fmt.Sprintf(\"%v\", t.Key)\n\t\t}\n\t\treturn fmt.Sprintf(\"%v=%v:\", t.Key, t.Value)\n\t}\n\tif len(t.Value) == 0 {\n\t\treturn fmt.Sprintf(\"%v:%v\", t.Key, t.Effect)\n\t}\n\treturn fmt.Sprintf(\"%v=%v:%v\", t.Key, t.Value, t.Effect)\n}","line":{"from":30,"to":42}} {"id":100002321,"name":"MatchToleration","signature":"func (t *Toleration) MatchToleration(tolerationToMatch *Toleration) bool","file":"pkg/apis/core/toleration.go","code":"// MatchToleration checks if the toleration matches tolerationToMatch. Tolerations are unique by \u003ckey,effect,operator,value\u003e,\n// if the two tolerations have same \u003ckey,effect,operator,value\u003e combination, regard as they match.\n// TODO: uniqueness check for tolerations in api validations.\nfunc (t *Toleration) MatchToleration(tolerationToMatch *Toleration) bool {\n\treturn t.Key == tolerationToMatch.Key \u0026\u0026\n\t\tt.Effect == tolerationToMatch.Effect \u0026\u0026\n\t\tt.Operator == tolerationToMatch.Operator \u0026\u0026\n\t\tt.Value == tolerationToMatch.Value\n}","line":{"from":22,"to":30}} {"id":100002322,"name":"addConversionFuncs","signature":"func addConversionFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/core/v1/conversion.go","code":"func addConversionFuncs(scheme *runtime.Scheme) error {\n\t// Add field conversion funcs.\n\terr := scheme.AddFieldLabelConversionFunc(SchemeGroupVersion.WithKind(\"Pod\"),\n\t\tfunc(label, value string) (string, string, error) {\n\t\t\tswitch label {\n\t\t\tcase \"metadata.name\",\n\t\t\t\t\"metadata.namespace\",\n\t\t\t\t\"spec.nodeName\",\n\t\t\t\t\"spec.restartPolicy\",\n\t\t\t\t\"spec.schedulerName\",\n\t\t\t\t\"spec.serviceAccountName\",\n\t\t\t\t\"status.phase\",\n\t\t\t\t\"status.podIP\",\n\t\t\t\t\"status.podIPs\",\n\t\t\t\t\"status.nominatedNodeName\":\n\t\t\t\treturn label, value, nil\n\t\t\t// This is for backwards compatibility with old v1 clients which send spec.host\n\t\t\tcase \"spec.host\":\n\t\t\t\treturn \"spec.nodeName\", value, nil\n\t\t\tdefault:\n\t\t\t\treturn \"\", \"\", fmt.Errorf(\"field label not supported: %s\", label)\n\t\t\t}\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = scheme.AddFieldLabelConversionFunc(SchemeGroupVersion.WithKind(\"Node\"),\n\t\tfunc(label, value string) (string, string, error) {\n\t\t\tswitch label {\n\t\t\tcase \"metadata.name\":\n\t\t\t\treturn label, value, nil\n\t\t\tcase \"spec.unschedulable\":\n\t\t\t\treturn label, value, nil\n\t\t\tdefault:\n\t\t\t\treturn \"\", \"\", fmt.Errorf(\"field label not supported: %s\", label)\n\t\t\t}\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = scheme.AddFieldLabelConversionFunc(SchemeGroupVersion.WithKind(\"ReplicationController\"),\n\t\tfunc(label, value string) (string, string, error) {\n\t\t\tswitch label {\n\t\t\tcase \"metadata.name\",\n\t\t\t\t\"metadata.namespace\",\n\t\t\t\t\"status.replicas\":\n\t\t\t\treturn label, value, nil\n\t\t\tdefault:\n\t\t\t\treturn \"\", \"\", fmt.Errorf(\"field label not supported: %s\", label)\n\t\t\t}\n\t\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := AddFieldLabelConversionsForEvent(scheme); err != nil {\n\t\treturn err\n\t}\n\tif err := AddFieldLabelConversionsForNamespace(scheme); err != nil {\n\t\treturn err\n\t}\n\tif err := AddFieldLabelConversionsForSecret(scheme); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":34,"to":100}} {"id":100002323,"name":"Convert_v1_ReplicationController_To_apps_ReplicaSet","signature":"func Convert_v1_ReplicationController_To_apps_ReplicaSet(in *v1.ReplicationController, out *apps.ReplicaSet, s conversion.Scope) error","file":"pkg/apis/core/v1/conversion.go","code":"func Convert_v1_ReplicationController_To_apps_ReplicaSet(in *v1.ReplicationController, out *apps.ReplicaSet, s conversion.Scope) error {\n\tout.ObjectMeta = in.ObjectMeta\n\tif err := Convert_v1_ReplicationControllerSpec_To_apps_ReplicaSetSpec(\u0026in.Spec, \u0026out.Spec, s); err != nil {\n\t\treturn err\n\t}\n\tif err := Convert_v1_ReplicationControllerStatus_To_apps_ReplicaSetStatus(\u0026in.Status, \u0026out.Status, s); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":102,"to":111}} {"id":100002324,"name":"Convert_v1_ReplicationControllerSpec_To_apps_ReplicaSetSpec","signature":"func Convert_v1_ReplicationControllerSpec_To_apps_ReplicaSetSpec(in *v1.ReplicationControllerSpec, out *apps.ReplicaSetSpec, s conversion.Scope) error","file":"pkg/apis/core/v1/conversion.go","code":"func Convert_v1_ReplicationControllerSpec_To_apps_ReplicaSetSpec(in *v1.ReplicationControllerSpec, out *apps.ReplicaSetSpec, s conversion.Scope) error {\n\tout.Replicas = *in.Replicas\n\tout.MinReadySeconds = in.MinReadySeconds\n\tif in.Selector != nil {\n\t\tout.Selector = new(metav1.LabelSelector)\n\t\tmetav1.Convert_Map_string_To_string_To_v1_LabelSelector(\u0026in.Selector, out.Selector, s)\n\t}\n\tif in.Template != nil {\n\t\tif err := Convert_v1_PodTemplateSpec_To_core_PodTemplateSpec(in.Template, \u0026out.Template, s); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":113,"to":126}} {"id":100002325,"name":"Convert_v1_ReplicationControllerStatus_To_apps_ReplicaSetStatus","signature":"func Convert_v1_ReplicationControllerStatus_To_apps_ReplicaSetStatus(in *v1.ReplicationControllerStatus, out *apps.ReplicaSetStatus, s conversion.Scope) error","file":"pkg/apis/core/v1/conversion.go","code":"func Convert_v1_ReplicationControllerStatus_To_apps_ReplicaSetStatus(in *v1.ReplicationControllerStatus, out *apps.ReplicaSetStatus, s conversion.Scope) error {\n\tout.Replicas = in.Replicas\n\tout.FullyLabeledReplicas = in.FullyLabeledReplicas\n\tout.ReadyReplicas = in.ReadyReplicas\n\tout.AvailableReplicas = in.AvailableReplicas\n\tout.ObservedGeneration = in.ObservedGeneration\n\tfor _, cond := range in.Conditions {\n\t\tout.Conditions = append(out.Conditions, apps.ReplicaSetCondition{\n\t\t\tType: apps.ReplicaSetConditionType(cond.Type),\n\t\t\tStatus: core.ConditionStatus(cond.Status),\n\t\t\tLastTransitionTime: cond.LastTransitionTime,\n\t\t\tReason: cond.Reason,\n\t\t\tMessage: cond.Message,\n\t\t})\n\t}\n\treturn nil\n}","line":{"from":128,"to":144}} {"id":100002326,"name":"Convert_apps_ReplicaSet_To_v1_ReplicationController","signature":"func Convert_apps_ReplicaSet_To_v1_ReplicationController(in *apps.ReplicaSet, out *v1.ReplicationController, s conversion.Scope) error","file":"pkg/apis/core/v1/conversion.go","code":"func Convert_apps_ReplicaSet_To_v1_ReplicationController(in *apps.ReplicaSet, out *v1.ReplicationController, s conversion.Scope) error {\n\tout.ObjectMeta = in.ObjectMeta\n\tif err := Convert_apps_ReplicaSetSpec_To_v1_ReplicationControllerSpec(\u0026in.Spec, \u0026out.Spec, s); err != nil {\n\t\tfieldErr, ok := err.(*field.Error)\n\t\tif !ok {\n\t\t\treturn err\n\t\t}\n\t\tif out.Annotations == nil {\n\t\t\tout.Annotations = make(map[string]string)\n\t\t}\n\t\tout.Annotations[v1.NonConvertibleAnnotationPrefix+\"/\"+fieldErr.Field] = reflect.ValueOf(fieldErr.BadValue).String()\n\t}\n\tif err := Convert_apps_ReplicaSetStatus_To_v1_ReplicationControllerStatus(\u0026in.Status, \u0026out.Status, s); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":146,"to":162}} {"id":100002327,"name":"Convert_apps_ReplicaSetSpec_To_v1_ReplicationControllerSpec","signature":"func Convert_apps_ReplicaSetSpec_To_v1_ReplicationControllerSpec(in *apps.ReplicaSetSpec, out *v1.ReplicationControllerSpec, s conversion.Scope) error","file":"pkg/apis/core/v1/conversion.go","code":"func Convert_apps_ReplicaSetSpec_To_v1_ReplicationControllerSpec(in *apps.ReplicaSetSpec, out *v1.ReplicationControllerSpec, s conversion.Scope) error {\n\tout.Replicas = new(int32)\n\t*out.Replicas = in.Replicas\n\tout.MinReadySeconds = in.MinReadySeconds\n\tvar invalidErr error\n\tif in.Selector != nil {\n\t\tinvalidErr = metav1.Convert_v1_LabelSelector_To_Map_string_To_string(in.Selector, \u0026out.Selector, s)\n\t}\n\tout.Template = new(v1.PodTemplateSpec)\n\tif err := Convert_core_PodTemplateSpec_To_v1_PodTemplateSpec(\u0026in.Template, out.Template, s); err != nil {\n\t\treturn err\n\t}\n\treturn invalidErr\n}","line":{"from":164,"to":177}} {"id":100002328,"name":"Convert_apps_ReplicaSetStatus_To_v1_ReplicationControllerStatus","signature":"func Convert_apps_ReplicaSetStatus_To_v1_ReplicationControllerStatus(in *apps.ReplicaSetStatus, out *v1.ReplicationControllerStatus, s conversion.Scope) error","file":"pkg/apis/core/v1/conversion.go","code":"func Convert_apps_ReplicaSetStatus_To_v1_ReplicationControllerStatus(in *apps.ReplicaSetStatus, out *v1.ReplicationControllerStatus, s conversion.Scope) error {\n\tout.Replicas = in.Replicas\n\tout.FullyLabeledReplicas = in.FullyLabeledReplicas\n\tout.ReadyReplicas = in.ReadyReplicas\n\tout.AvailableReplicas = in.AvailableReplicas\n\tout.ObservedGeneration = in.ObservedGeneration\n\tfor _, cond := range in.Conditions {\n\t\tout.Conditions = append(out.Conditions, v1.ReplicationControllerCondition{\n\t\t\tType: v1.ReplicationControllerConditionType(cond.Type),\n\t\t\tStatus: v1.ConditionStatus(cond.Status),\n\t\t\tLastTransitionTime: cond.LastTransitionTime,\n\t\t\tReason: cond.Reason,\n\t\t\tMessage: cond.Message,\n\t\t})\n\t}\n\treturn nil\n}","line":{"from":179,"to":195}} {"id":100002329,"name":"Convert_core_ReplicationControllerSpec_To_v1_ReplicationControllerSpec","signature":"func Convert_core_ReplicationControllerSpec_To_v1_ReplicationControllerSpec(in *core.ReplicationControllerSpec, out *v1.ReplicationControllerSpec, s conversion.Scope) error","file":"pkg/apis/core/v1/conversion.go","code":"func Convert_core_ReplicationControllerSpec_To_v1_ReplicationControllerSpec(in *core.ReplicationControllerSpec, out *v1.ReplicationControllerSpec, s conversion.Scope) error {\n\tout.Replicas = \u0026in.Replicas\n\tout.MinReadySeconds = in.MinReadySeconds\n\tout.Selector = in.Selector\n\tif in.Template != nil {\n\t\tout.Template = new(v1.PodTemplateSpec)\n\t\tif err := Convert_core_PodTemplateSpec_To_v1_PodTemplateSpec(in.Template, out.Template, s); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tout.Template = nil\n\t}\n\treturn nil\n}","line":{"from":197,"to":210}} {"id":100002330,"name":"Convert_v1_ReplicationControllerSpec_To_core_ReplicationControllerSpec","signature":"func Convert_v1_ReplicationControllerSpec_To_core_ReplicationControllerSpec(in *v1.ReplicationControllerSpec, out *core.ReplicationControllerSpec, s conversion.Scope) error","file":"pkg/apis/core/v1/conversion.go","code":"func Convert_v1_ReplicationControllerSpec_To_core_ReplicationControllerSpec(in *v1.ReplicationControllerSpec, out *core.ReplicationControllerSpec, s conversion.Scope) error {\n\tif in.Replicas != nil {\n\t\tout.Replicas = *in.Replicas\n\t}\n\tout.MinReadySeconds = in.MinReadySeconds\n\tout.Selector = in.Selector\n\tif in.Template != nil {\n\t\tout.Template = new(core.PodTemplateSpec)\n\t\tif err := Convert_v1_PodTemplateSpec_To_core_PodTemplateSpec(in.Template, out.Template, s); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tout.Template = nil\n\t}\n\treturn nil\n}","line":{"from":212,"to":227}} {"id":100002331,"name":"Convert_core_PodTemplateSpec_To_v1_PodTemplateSpec","signature":"func Convert_core_PodTemplateSpec_To_v1_PodTemplateSpec(in *core.PodTemplateSpec, out *v1.PodTemplateSpec, s conversion.Scope) error","file":"pkg/apis/core/v1/conversion.go","code":"func Convert_core_PodTemplateSpec_To_v1_PodTemplateSpec(in *core.PodTemplateSpec, out *v1.PodTemplateSpec, s conversion.Scope) error {\n\tif err := autoConvert_core_PodTemplateSpec_To_v1_PodTemplateSpec(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\t// drop init container annotations so they don't take effect on legacy kubelets.\n\t// remove this once the oldest supported kubelet no longer honors the annotations over the field.\n\tout.Annotations = dropInitContainerAnnotations(out.Annotations)\n\n\treturn nil\n}","line":{"from":229,"to":239}} {"id":100002332,"name":"Convert_v1_PodTemplateSpec_To_core_PodTemplateSpec","signature":"func Convert_v1_PodTemplateSpec_To_core_PodTemplateSpec(in *v1.PodTemplateSpec, out *core.PodTemplateSpec, s conversion.Scope) error","file":"pkg/apis/core/v1/conversion.go","code":"func Convert_v1_PodTemplateSpec_To_core_PodTemplateSpec(in *v1.PodTemplateSpec, out *core.PodTemplateSpec, s conversion.Scope) error {\n\tif err := autoConvert_v1_PodTemplateSpec_To_core_PodTemplateSpec(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\t// drop init container annotations so they don't show up as differences when receiving requests from old clients\n\tout.Annotations = dropInitContainerAnnotations(out.Annotations)\n\n\treturn nil\n}","line":{"from":241,"to":250}} {"id":100002333,"name":"Convert_v1_PodStatus_To_core_PodStatus","signature":"func Convert_v1_PodStatus_To_core_PodStatus(in *v1.PodStatus, out *core.PodStatus, s conversion.Scope) error","file":"pkg/apis/core/v1/conversion.go","code":"func Convert_v1_PodStatus_To_core_PodStatus(in *v1.PodStatus, out *core.PodStatus, s conversion.Scope) error {\n\tif err := autoConvert_v1_PodStatus_To_core_PodStatus(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\t// If both fields (v1.PodIPs and v1.PodIP) are provided and differ, then PodIP is authoritative for compatibility with older kubelets\n\tif (len(in.PodIP) \u003e 0 \u0026\u0026 len(in.PodIPs) \u003e 0) \u0026\u0026 (in.PodIP != in.PodIPs[0].IP) {\n\t\tout.PodIPs = []core.PodIP{\n\t\t\t{\n\t\t\t\tIP: in.PodIP,\n\t\t\t},\n\t\t}\n\t}\n\t// at the this point, autoConvert copied v1.PodIPs -\u003e core.PodIPs\n\t// if v1.PodIPs was empty but v1.PodIP is not, then set core.PodIPs[0] with v1.PodIP\n\tif len(in.PodIP) \u003e 0 \u0026\u0026 len(in.PodIPs) == 0 {\n\t\tout.PodIPs = []core.PodIP{\n\t\t\t{\n\t\t\t\tIP: in.PodIP,\n\t\t\t},\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":252,"to":275}} {"id":100002334,"name":"Convert_core_PodStatus_To_v1_PodStatus","signature":"func Convert_core_PodStatus_To_v1_PodStatus(in *core.PodStatus, out *v1.PodStatus, s conversion.Scope) error","file":"pkg/apis/core/v1/conversion.go","code":"func Convert_core_PodStatus_To_v1_PodStatus(in *core.PodStatus, out *v1.PodStatus, s conversion.Scope) error {\n\tif err := autoConvert_core_PodStatus_To_v1_PodStatus(in, out, s); err != nil {\n\t\treturn err\n\t}\n\t// at the this point autoConvert copied core.PodIPs -\u003e v1.PodIPs\n\t// v1.PodIP (singular value field, which does not exist in core) needs to\n\t// be set with core.PodIPs[0]\n\tif len(in.PodIPs) \u003e 0 {\n\t\tout.PodIP = in.PodIPs[0].IP\n\t}\n\treturn nil\n}","line":{"from":277,"to":288}} {"id":100002335,"name":"Convert_core_PodSpec_To_v1_PodSpec","signature":"func Convert_core_PodSpec_To_v1_PodSpec(in *core.PodSpec, out *v1.PodSpec, s conversion.Scope) error","file":"pkg/apis/core/v1/conversion.go","code":"// The following two v1.PodSpec conversions are done here to support v1.ServiceAccount\n// as an alias for ServiceAccountName.\nfunc Convert_core_PodSpec_To_v1_PodSpec(in *core.PodSpec, out *v1.PodSpec, s conversion.Scope) error {\n\tif err := autoConvert_core_PodSpec_To_v1_PodSpec(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\t// DeprecatedServiceAccount is an alias for ServiceAccountName.\n\tout.DeprecatedServiceAccount = in.ServiceAccountName\n\n\tif in.SecurityContext != nil {\n\t\t// the host namespace fields have to be handled here for backward compatibility\n\t\t// with v1.0.0\n\t\tout.HostPID = in.SecurityContext.HostPID\n\t\tout.HostNetwork = in.SecurityContext.HostNetwork\n\t\tout.HostIPC = in.SecurityContext.HostIPC\n\t\tout.ShareProcessNamespace = in.SecurityContext.ShareProcessNamespace\n\t\tout.HostUsers = in.SecurityContext.HostUsers\n\t}\n\n\treturn nil\n}","line":{"from":290,"to":311}} {"id":100002336,"name":"Convert_core_NodeSpec_To_v1_NodeSpec","signature":"func Convert_core_NodeSpec_To_v1_NodeSpec(in *core.NodeSpec, out *v1.NodeSpec, s conversion.Scope) error","file":"pkg/apis/core/v1/conversion.go","code":"func Convert_core_NodeSpec_To_v1_NodeSpec(in *core.NodeSpec, out *v1.NodeSpec, s conversion.Scope) error {\n\tif err := autoConvert_core_NodeSpec_To_v1_NodeSpec(in, out, s); err != nil {\n\t\treturn err\n\t}\n\t// at the this point autoConvert copied core.PodCIDRs -\u003e v1.PodCIDRs\n\t// v1.PodCIDR (singular value field, which does not exist in core) needs to\n\t// be set with core.PodCIDRs[0]\n\tif len(in.PodCIDRs) \u003e 0 {\n\t\tout.PodCIDR = in.PodCIDRs[0]\n\t}\n\treturn nil\n}","line":{"from":313,"to":324}} {"id":100002337,"name":"Convert_v1_NodeSpec_To_core_NodeSpec","signature":"func Convert_v1_NodeSpec_To_core_NodeSpec(in *v1.NodeSpec, out *core.NodeSpec, s conversion.Scope) error","file":"pkg/apis/core/v1/conversion.go","code":"func Convert_v1_NodeSpec_To_core_NodeSpec(in *v1.NodeSpec, out *core.NodeSpec, s conversion.Scope) error {\n\tif err := autoConvert_v1_NodeSpec_To_core_NodeSpec(in, out, s); err != nil {\n\t\treturn err\n\t}\n\t// If both fields (v1.PodCIDRs and v1.PodCIDR) are provided and differ, then PodCIDR is authoritative for compatibility with older clients\n\tif (len(in.PodCIDR) \u003e 0 \u0026\u0026 len(in.PodCIDRs) \u003e 0) \u0026\u0026 (in.PodCIDR != in.PodCIDRs[0]) {\n\t\tout.PodCIDRs = []string{in.PodCIDR}\n\t}\n\n\t// at the this point, autoConvert copied v1.PodCIDRs -\u003e core.PodCIDRs\n\t// if v1.PodCIDRs was empty but v1.PodCIDR is not, then set core.PodCIDRs[0] with v1.PodCIDR\n\tif len(in.PodCIDR) \u003e 0 \u0026\u0026 len(in.PodCIDRs) == 0 {\n\t\tout.PodCIDRs = []string{in.PodCIDR}\n\t}\n\treturn nil\n}","line":{"from":326,"to":341}} {"id":100002338,"name":"Convert_v1_PodSpec_To_core_PodSpec","signature":"func Convert_v1_PodSpec_To_core_PodSpec(in *v1.PodSpec, out *core.PodSpec, s conversion.Scope) error","file":"pkg/apis/core/v1/conversion.go","code":"func Convert_v1_PodSpec_To_core_PodSpec(in *v1.PodSpec, out *core.PodSpec, s conversion.Scope) error {\n\tif err := autoConvert_v1_PodSpec_To_core_PodSpec(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\t// We support DeprecatedServiceAccount as an alias for ServiceAccountName.\n\t// If both are specified, ServiceAccountName (the new field) wins.\n\tif in.ServiceAccountName == \"\" {\n\t\tout.ServiceAccountName = in.DeprecatedServiceAccount\n\t}\n\n\t// the host namespace fields have to be handled specially for backward compatibility\n\t// with v1.0.0\n\tif out.SecurityContext == nil {\n\t\tout.SecurityContext = new(core.PodSecurityContext)\n\t}\n\tout.SecurityContext.HostNetwork = in.HostNetwork\n\tout.SecurityContext.HostPID = in.HostPID\n\tout.SecurityContext.HostIPC = in.HostIPC\n\tout.SecurityContext.ShareProcessNamespace = in.ShareProcessNamespace\n\tout.SecurityContext.HostUsers = in.HostUsers\n\n\treturn nil\n}","line":{"from":343,"to":366}} {"id":100002339,"name":"Convert_v1_Pod_To_core_Pod","signature":"func Convert_v1_Pod_To_core_Pod(in *v1.Pod, out *core.Pod, s conversion.Scope) error","file":"pkg/apis/core/v1/conversion.go","code":"func Convert_v1_Pod_To_core_Pod(in *v1.Pod, out *core.Pod, s conversion.Scope) error {\n\tif err := autoConvert_v1_Pod_To_core_Pod(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\t// drop init container annotations so they don't show up as differences when receiving requests from old clients\n\tout.Annotations = dropInitContainerAnnotations(out.Annotations)\n\n\t// Forcing the value of TerminationGracePeriodSeconds to 1 if it is negative.\n\t// Just for Pod, not for PodSpec, because we don't want to change the behavior of the PodTemplate.\n\tif in.Spec.TerminationGracePeriodSeconds != nil \u0026\u0026 *in.Spec.TerminationGracePeriodSeconds \u003c 0 {\n\t\tout.Spec.TerminationGracePeriodSeconds = utilpointer.Int64(1)\n\t}\n\treturn nil\n}","line":{"from":368,"to":382}} {"id":100002340,"name":"Convert_core_Pod_To_v1_Pod","signature":"func Convert_core_Pod_To_v1_Pod(in *core.Pod, out *v1.Pod, s conversion.Scope) error","file":"pkg/apis/core/v1/conversion.go","code":"func Convert_core_Pod_To_v1_Pod(in *core.Pod, out *v1.Pod, s conversion.Scope) error {\n\tif err := autoConvert_core_Pod_To_v1_Pod(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\t// drop init container annotations so they don't take effect on legacy kubelets.\n\t// remove this once the oldest supported kubelet no longer honors the annotations over the field.\n\tout.Annotations = dropInitContainerAnnotations(out.Annotations)\n\n\t// Forcing the value of TerminationGracePeriodSeconds to 1 if it is negative.\n\t// Just for Pod, not for PodSpec, because we don't want to change the behavior of the PodTemplate.\n\tif in.Spec.TerminationGracePeriodSeconds != nil \u0026\u0026 *in.Spec.TerminationGracePeriodSeconds \u003c 0 {\n\t\tout.Spec.TerminationGracePeriodSeconds = utilpointer.Int64(1)\n\t}\n\treturn nil\n}","line":{"from":384,"to":399}} {"id":100002341,"name":"Convert_v1_Secret_To_core_Secret","signature":"func Convert_v1_Secret_To_core_Secret(in *v1.Secret, out *core.Secret, s conversion.Scope) error","file":"pkg/apis/core/v1/conversion.go","code":"func Convert_v1_Secret_To_core_Secret(in *v1.Secret, out *core.Secret, s conversion.Scope) error {\n\tif err := autoConvert_v1_Secret_To_core_Secret(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\t// StringData overwrites Data\n\tif len(in.StringData) \u003e 0 {\n\t\tif out.Data == nil {\n\t\t\tout.Data = map[string][]byte{}\n\t\t}\n\t\tfor k, v := range in.StringData {\n\t\t\tout.Data[k] = []byte(v)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":401,"to":417}} {"id":100002342,"name":"Convert_v1_ResourceList_To_core_ResourceList","signature":"func Convert_v1_ResourceList_To_core_ResourceList(in *v1.ResourceList, out *core.ResourceList, s conversion.Scope) error","file":"pkg/apis/core/v1/conversion.go","code":"// +k8s:conversion-fn=copy-only\nfunc Convert_v1_ResourceList_To_core_ResourceList(in *v1.ResourceList, out *core.ResourceList, s conversion.Scope) error {\n\tif *in == nil {\n\t\treturn nil\n\t}\n\tif *out == nil {\n\t\t*out = make(core.ResourceList, len(*in))\n\t}\n\tfor key, val := range *in {\n\t\t// Moved to defaults\n\t\t// TODO(#18538): We round up resource values to milli scale to maintain API compatibility.\n\t\t// In the future, we should instead reject values that need rounding.\n\t\t// const milliScale = -3\n\t\t// val.RoundUp(milliScale)\n\n\t\t(*out)[core.ResourceName(key)] = val\n\t}\n\treturn nil\n}","line":{"from":419,"to":437}} {"id":100002343,"name":"AddFieldLabelConversionsForEvent","signature":"func AddFieldLabelConversionsForEvent(scheme *runtime.Scheme) error","file":"pkg/apis/core/v1/conversion.go","code":"func AddFieldLabelConversionsForEvent(scheme *runtime.Scheme) error {\n\treturn scheme.AddFieldLabelConversionFunc(SchemeGroupVersion.WithKind(\"Event\"),\n\t\tfunc(label, value string) (string, string, error) {\n\t\t\tswitch label {\n\t\t\tcase \"involvedObject.kind\",\n\t\t\t\t\"involvedObject.namespace\",\n\t\t\t\t\"involvedObject.name\",\n\t\t\t\t\"involvedObject.uid\",\n\t\t\t\t\"involvedObject.apiVersion\",\n\t\t\t\t\"involvedObject.resourceVersion\",\n\t\t\t\t\"involvedObject.fieldPath\",\n\t\t\t\t\"reason\",\n\t\t\t\t\"reportingComponent\",\n\t\t\t\t\"source\",\n\t\t\t\t\"type\",\n\t\t\t\t\"metadata.namespace\",\n\t\t\t\t\"metadata.name\":\n\t\t\t\treturn label, value, nil\n\t\t\tdefault:\n\t\t\t\treturn \"\", \"\", fmt.Errorf(\"field label not supported: %s\", label)\n\t\t\t}\n\t\t})\n}","line":{"from":439,"to":461}} {"id":100002344,"name":"AddFieldLabelConversionsForNamespace","signature":"func AddFieldLabelConversionsForNamespace(scheme *runtime.Scheme) error","file":"pkg/apis/core/v1/conversion.go","code":"func AddFieldLabelConversionsForNamespace(scheme *runtime.Scheme) error {\n\treturn scheme.AddFieldLabelConversionFunc(SchemeGroupVersion.WithKind(\"Namespace\"),\n\t\tfunc(label, value string) (string, string, error) {\n\t\t\tswitch label {\n\t\t\tcase \"status.phase\",\n\t\t\t\t\"metadata.name\":\n\t\t\t\treturn label, value, nil\n\t\t\tdefault:\n\t\t\t\treturn \"\", \"\", fmt.Errorf(\"field label not supported: %s\", label)\n\t\t\t}\n\t\t})\n}","line":{"from":463,"to":474}} {"id":100002345,"name":"AddFieldLabelConversionsForSecret","signature":"func AddFieldLabelConversionsForSecret(scheme *runtime.Scheme) error","file":"pkg/apis/core/v1/conversion.go","code":"func AddFieldLabelConversionsForSecret(scheme *runtime.Scheme) error {\n\treturn scheme.AddFieldLabelConversionFunc(SchemeGroupVersion.WithKind(\"Secret\"),\n\t\tfunc(label, value string) (string, string, error) {\n\t\t\tswitch label {\n\t\t\tcase \"type\",\n\t\t\t\t\"metadata.namespace\",\n\t\t\t\t\"metadata.name\":\n\t\t\t\treturn label, value, nil\n\t\t\tdefault:\n\t\t\t\treturn \"\", \"\", fmt.Errorf(\"field label not supported: %s\", label)\n\t\t\t}\n\t\t})\n}","line":{"from":476,"to":488}} {"id":100002346,"name":"dropInitContainerAnnotations","signature":"func dropInitContainerAnnotations(oldAnnotations map[string]string) map[string]string","file":"pkg/apis/core/v1/conversion.go","code":"// dropInitContainerAnnotations returns a copy of the annotations with init container annotations removed,\n// or the original annotations if no init container annotations were present.\n//\n// this can be removed once no clients prior to 1.8 are supported, and no kubelets prior to 1.8 can be run\n// (we don't support kubelets older than 2 versions skewed from the apiserver, but we don't prevent them, either)\nfunc dropInitContainerAnnotations(oldAnnotations map[string]string) map[string]string {\n\tif len(oldAnnotations) == 0 {\n\t\treturn oldAnnotations\n\t}\n\n\tfound := false\n\tfor k := range initContainerAnnotations {\n\t\tif _, ok := oldAnnotations[k]; ok {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\treturn oldAnnotations\n\t}\n\n\tnewAnnotations := make(map[string]string, len(oldAnnotations))\n\tfor k, v := range oldAnnotations {\n\t\tif !initContainerAnnotations[k] {\n\t\t\tnewAnnotations[k] = v\n\t\t}\n\t}\n\treturn newAnnotations\n}","line":{"from":497,"to":525}} {"id":100002347,"name":"Convert_core_LoadBalancerStatus_To_v1_LoadBalancerStatus","signature":"func Convert_core_LoadBalancerStatus_To_v1_LoadBalancerStatus(in *core.LoadBalancerStatus, out *v1.LoadBalancerStatus, s conversion.Scope) error","file":"pkg/apis/core/v1/conversion.go","code":"// Convert_core_LoadBalancerStatus_To_v1_LoadBalancerStatus is defined outside the autogenerated file for use by other API packages\nfunc Convert_core_LoadBalancerStatus_To_v1_LoadBalancerStatus(in *core.LoadBalancerStatus, out *v1.LoadBalancerStatus, s conversion.Scope) error {\n\treturn autoConvert_core_LoadBalancerStatus_To_v1_LoadBalancerStatus(in, out, s)\n}","line":{"from":527,"to":530}} {"id":100002348,"name":"Convert_v1_LoadBalancerStatus_To_core_LoadBalancerStatus","signature":"func Convert_v1_LoadBalancerStatus_To_core_LoadBalancerStatus(in *v1.LoadBalancerStatus, out *core.LoadBalancerStatus, s conversion.Scope) error","file":"pkg/apis/core/v1/conversion.go","code":"// Convert_v1_LoadBalancerStatus_To_core_LoadBalancerStatus is defined outside the autogenerated file for use by other API packages\nfunc Convert_v1_LoadBalancerStatus_To_core_LoadBalancerStatus(in *v1.LoadBalancerStatus, out *core.LoadBalancerStatus, s conversion.Scope) error {\n\treturn autoConvert_v1_LoadBalancerStatus_To_core_LoadBalancerStatus(in, out, s)\n}","line":{"from":532,"to":535}} {"id":100002349,"name":"Convert_core_Volume_To_v1_Volume","signature":"func Convert_core_Volume_To_v1_Volume(in *core.Volume, out *v1.Volume, s conversion.Scope) error","file":"pkg/apis/core/v1/conversion.go","code":"// Convert_core_Volume_To_v1_Volume is defined outside the autogenerated file for use by other API packages\nfunc Convert_core_Volume_To_v1_Volume(in *core.Volume, out *v1.Volume, s conversion.Scope) error {\n\treturn autoConvert_core_Volume_To_v1_Volume(in, out, s)\n}","line":{"from":537,"to":540}} {"id":100002350,"name":"Convert_v1_Volume_To_core_Volume","signature":"func Convert_v1_Volume_To_core_Volume(in *v1.Volume, out *core.Volume, s conversion.Scope) error","file":"pkg/apis/core/v1/conversion.go","code":"// Convert_v1_Volume_To_core_Volume is defined outside the autogenerated file for use by other API packages\nfunc Convert_v1_Volume_To_core_Volume(in *v1.Volume, out *core.Volume, s conversion.Scope) error {\n\treturn autoConvert_v1_Volume_To_core_Volume(in, out, s)\n}","line":{"from":542,"to":545}} {"id":100002351,"name":"Convert_core_PersistentVolumeSpec_To_v1_PersistentVolumeSpec","signature":"func Convert_core_PersistentVolumeSpec_To_v1_PersistentVolumeSpec(in *core.PersistentVolumeSpec, out *v1.PersistentVolumeSpec, s conversion.Scope) error","file":"pkg/apis/core/v1/conversion.go","code":"// Convert_core_PersistentVolumeSpec_To_v1_PersistentVolumeSpec is defined outside the autogenerated file for use by other API packages\nfunc Convert_core_PersistentVolumeSpec_To_v1_PersistentVolumeSpec(in *core.PersistentVolumeSpec, out *v1.PersistentVolumeSpec, s conversion.Scope) error {\n\treturn autoConvert_core_PersistentVolumeSpec_To_v1_PersistentVolumeSpec(in, out, s)\n}","line":{"from":547,"to":550}} {"id":100002352,"name":"Convert_v1_PersistentVolumeSpec_To_core_PersistentVolumeSpec","signature":"func Convert_v1_PersistentVolumeSpec_To_core_PersistentVolumeSpec(in *v1.PersistentVolumeSpec, out *core.PersistentVolumeSpec, s conversion.Scope) error","file":"pkg/apis/core/v1/conversion.go","code":"// Convert_v1_PersistentVolumeSpec_To_core_PersistentVolumeSpec is defined outside the autogenerated file for use by other API packages\nfunc Convert_v1_PersistentVolumeSpec_To_core_PersistentVolumeSpec(in *v1.PersistentVolumeSpec, out *core.PersistentVolumeSpec, s conversion.Scope) error {\n\treturn autoConvert_v1_PersistentVolumeSpec_To_core_PersistentVolumeSpec(in, out, s)\n}","line":{"from":552,"to":555}} {"id":100002353,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/core/v1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":31,"to":33}} {"id":100002354,"name":"SetDefaults_ResourceList","signature":"func SetDefaults_ResourceList(obj *v1.ResourceList)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_ResourceList(obj *v1.ResourceList) {\n\tfor key, val := range *obj {\n\t\t// TODO(#18538): We round up resource values to milli scale to maintain API compatibility.\n\t\t// In the future, we should instead reject values that need rounding.\n\t\tconst milliScale = -3\n\t\tval.RoundUp(milliScale)\n\n\t\t(*obj)[v1.ResourceName(key)] = val\n\t}\n}","line":{"from":35,"to":44}} {"id":100002355,"name":"SetDefaults_ReplicationController","signature":"func SetDefaults_ReplicationController(obj *v1.ReplicationController)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_ReplicationController(obj *v1.ReplicationController) {\n\tvar labels map[string]string\n\tif obj.Spec.Template != nil {\n\t\tlabels = obj.Spec.Template.Labels\n\t}\n\t// TODO: support templates defined elsewhere when we support them in the API\n\tif labels != nil {\n\t\tif len(obj.Spec.Selector) == 0 {\n\t\t\tobj.Spec.Selector = labels\n\t\t}\n\t\tif len(obj.Labels) == 0 {\n\t\t\tobj.Labels = labels\n\t\t}\n\t}\n\tif obj.Spec.Replicas == nil {\n\t\tobj.Spec.Replicas = new(int32)\n\t\t*obj.Spec.Replicas = 1\n\t}\n}","line":{"from":46,"to":64}} {"id":100002356,"name":"SetDefaults_Volume","signature":"func SetDefaults_Volume(obj *v1.Volume)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_Volume(obj *v1.Volume) {\n\tif pointer.AllPtrFieldsNil(\u0026obj.VolumeSource) {\n\t\tobj.VolumeSource = v1.VolumeSource{\n\t\t\tEmptyDir: \u0026v1.EmptyDirVolumeSource{},\n\t\t}\n\t}\n}","line":{"from":65,"to":71}} {"id":100002357,"name":"SetDefaults_Container","signature":"func SetDefaults_Container(obj *v1.Container)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_Container(obj *v1.Container) {\n\tif obj.ImagePullPolicy == \"\" {\n\t\t// Ignore error and assume it has been validated elsewhere\n\t\t_, tag, _, _ := parsers.ParseImageName(obj.Image)\n\n\t\t// Check image tag\n\t\tif tag == \"latest\" {\n\t\t\tobj.ImagePullPolicy = v1.PullAlways\n\t\t} else {\n\t\t\tobj.ImagePullPolicy = v1.PullIfNotPresent\n\t\t}\n\t}\n\tif obj.TerminationMessagePath == \"\" {\n\t\tobj.TerminationMessagePath = v1.TerminationMessagePathDefault\n\t}\n\tif obj.TerminationMessagePolicy == \"\" {\n\t\tobj.TerminationMessagePolicy = v1.TerminationMessageReadFile\n\t}\n}","line":{"from":72,"to":90}} {"id":100002358,"name":"SetDefaults_EphemeralContainer","signature":"func SetDefaults_EphemeralContainer(obj *v1.EphemeralContainer)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_EphemeralContainer(obj *v1.EphemeralContainer) {\n\tSetDefaults_Container((*v1.Container)(\u0026obj.EphemeralContainerCommon))\n}","line":{"from":92,"to":94}} {"id":100002359,"name":"SetDefaults_Service","signature":"func SetDefaults_Service(obj *v1.Service)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_Service(obj *v1.Service) {\n\tif obj.Spec.SessionAffinity == \"\" {\n\t\tobj.Spec.SessionAffinity = v1.ServiceAffinityNone\n\t}\n\tif obj.Spec.SessionAffinity == v1.ServiceAffinityNone {\n\t\tobj.Spec.SessionAffinityConfig = nil\n\t}\n\tif obj.Spec.SessionAffinity == v1.ServiceAffinityClientIP {\n\t\tif obj.Spec.SessionAffinityConfig == nil || obj.Spec.SessionAffinityConfig.ClientIP == nil || obj.Spec.SessionAffinityConfig.ClientIP.TimeoutSeconds == nil {\n\t\t\ttimeoutSeconds := v1.DefaultClientIPServiceAffinitySeconds\n\t\t\tobj.Spec.SessionAffinityConfig = \u0026v1.SessionAffinityConfig{\n\t\t\t\tClientIP: \u0026v1.ClientIPConfig{\n\t\t\t\t\tTimeoutSeconds: \u0026timeoutSeconds,\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t}\n\tif obj.Spec.Type == \"\" {\n\t\tobj.Spec.Type = v1.ServiceTypeClusterIP\n\t}\n\tfor i := range obj.Spec.Ports {\n\t\tsp := \u0026obj.Spec.Ports[i]\n\t\tif sp.Protocol == \"\" {\n\t\t\tsp.Protocol = v1.ProtocolTCP\n\t\t}\n\t\tif sp.TargetPort == intstr.FromInt(0) || sp.TargetPort == intstr.FromString(\"\") {\n\t\t\tsp.TargetPort = intstr.FromInt(int(sp.Port))\n\t\t}\n\t}\n\t// Defaults ExternalTrafficPolicy field for NodePort / LoadBalancer service\n\t// to Global for consistency.\n\tif (obj.Spec.Type == v1.ServiceTypeNodePort ||\n\t\tobj.Spec.Type == v1.ServiceTypeLoadBalancer) \u0026\u0026\n\t\tobj.Spec.ExternalTrafficPolicy == \"\" {\n\t\tobj.Spec.ExternalTrafficPolicy = v1.ServiceExternalTrafficPolicyCluster\n\t}\n\n\tif obj.Spec.InternalTrafficPolicy == nil {\n\t\tif obj.Spec.Type == v1.ServiceTypeNodePort || obj.Spec.Type == v1.ServiceTypeLoadBalancer || obj.Spec.Type == v1.ServiceTypeClusterIP {\n\t\t\tserviceInternalTrafficPolicyCluster := v1.ServiceInternalTrafficPolicyCluster\n\t\t\tobj.Spec.InternalTrafficPolicy = \u0026serviceInternalTrafficPolicyCluster\n\t\t}\n\t}\n\n\tif obj.Spec.Type == v1.ServiceTypeLoadBalancer {\n\t\tif obj.Spec.AllocateLoadBalancerNodePorts == nil {\n\t\t\tobj.Spec.AllocateLoadBalancerNodePorts = pointer.Bool(true)\n\t\t}\n\t}\n}","line":{"from":96,"to":145}} {"id":100002360,"name":"SetDefaults_Pod","signature":"func SetDefaults_Pod(obj *v1.Pod)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_Pod(obj *v1.Pod) {\n\t// If limits are specified, but requests are not, default requests to limits\n\t// This is done here rather than a more specific defaulting pass on v1.ResourceRequirements\n\t// because we only want this defaulting semantic to take place on a v1.Pod and not a v1.PodTemplate\n\tfor i := range obj.Spec.Containers {\n\t\t// set requests to limits if requests are not specified, but limits are\n\t\tif obj.Spec.Containers[i].Resources.Limits != nil {\n\t\t\tif obj.Spec.Containers[i].Resources.Requests == nil {\n\t\t\t\tobj.Spec.Containers[i].Resources.Requests = make(v1.ResourceList)\n\t\t\t}\n\t\t\tfor key, value := range obj.Spec.Containers[i].Resources.Limits {\n\t\t\t\tif _, exists := obj.Spec.Containers[i].Resources.Requests[key]; !exists {\n\t\t\t\t\tobj.Spec.Containers[i].Resources.Requests[key] = value.DeepCopy()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) \u0026\u0026\n\t\t\tobj.Spec.Containers[i].Resources.Requests != nil {\n\t\t\t// For normal containers, set resize restart policy to default value (NotRequired), if not specified.\n\t\t\tresizePolicySpecified := make(map[v1.ResourceName]bool)\n\t\t\tfor _, p := range obj.Spec.Containers[i].ResizePolicy {\n\t\t\t\tresizePolicySpecified[p.ResourceName] = true\n\t\t\t}\n\t\t\tsetDefaultResizePolicy := func(resourceName v1.ResourceName) {\n\t\t\t\tif _, found := resizePolicySpecified[resourceName]; !found {\n\t\t\t\t\tobj.Spec.Containers[i].ResizePolicy = append(obj.Spec.Containers[i].ResizePolicy,\n\t\t\t\t\t\tv1.ContainerResizePolicy{\n\t\t\t\t\t\t\tResourceName: resourceName,\n\t\t\t\t\t\t\tRestartPolicy: v1.NotRequired,\n\t\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t\tif _, exists := obj.Spec.Containers[i].Resources.Requests[v1.ResourceCPU]; exists {\n\t\t\t\tsetDefaultResizePolicy(v1.ResourceCPU)\n\t\t\t}\n\t\t\tif _, exists := obj.Spec.Containers[i].Resources.Requests[v1.ResourceMemory]; exists {\n\t\t\t\tsetDefaultResizePolicy(v1.ResourceMemory)\n\t\t\t}\n\t\t}\n\t}\n\tfor i := range obj.Spec.InitContainers {\n\t\tif obj.Spec.InitContainers[i].Resources.Limits != nil {\n\t\t\tif obj.Spec.InitContainers[i].Resources.Requests == nil {\n\t\t\t\tobj.Spec.InitContainers[i].Resources.Requests = make(v1.ResourceList)\n\t\t\t}\n\t\t\tfor key, value := range obj.Spec.InitContainers[i].Resources.Limits {\n\t\t\t\tif _, exists := obj.Spec.InitContainers[i].Resources.Requests[key]; !exists {\n\t\t\t\t\tobj.Spec.InitContainers[i].Resources.Requests[key] = value.DeepCopy()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif obj.Spec.EnableServiceLinks == nil {\n\t\tenableServiceLinks := v1.DefaultEnableServiceLinks\n\t\tobj.Spec.EnableServiceLinks = \u0026enableServiceLinks\n\t}\n}","line":{"from":146,"to":202}} {"id":100002361,"name":"SetDefaults_PodSpec","signature":"func SetDefaults_PodSpec(obj *v1.PodSpec)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_PodSpec(obj *v1.PodSpec) {\n\t// New fields added here will break upgrade tests:\n\t// https://github.com/kubernetes/kubernetes/issues/69445\n\t// In most cases the new defaulted field can added to SetDefaults_Pod instead of here, so\n\t// that it only materializes in the Pod object and not all objects with a PodSpec field.\n\tif obj.DNSPolicy == \"\" {\n\t\tobj.DNSPolicy = v1.DNSClusterFirst\n\t}\n\tif obj.RestartPolicy == \"\" {\n\t\tobj.RestartPolicy = v1.RestartPolicyAlways\n\t}\n\tif obj.HostNetwork {\n\t\tdefaultHostNetworkPorts(\u0026obj.Containers)\n\t\tdefaultHostNetworkPorts(\u0026obj.InitContainers)\n\t}\n\tif obj.SecurityContext == nil {\n\t\tobj.SecurityContext = \u0026v1.PodSecurityContext{}\n\t}\n\tif obj.TerminationGracePeriodSeconds == nil {\n\t\tperiod := int64(v1.DefaultTerminationGracePeriodSeconds)\n\t\tobj.TerminationGracePeriodSeconds = \u0026period\n\t}\n\tif obj.SchedulerName == \"\" {\n\t\tobj.SchedulerName = v1.DefaultSchedulerName\n\t}\n}","line":{"from":203,"to":228}} {"id":100002362,"name":"SetDefaults_Probe","signature":"func SetDefaults_Probe(obj *v1.Probe)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_Probe(obj *v1.Probe) {\n\tif obj.TimeoutSeconds == 0 {\n\t\tobj.TimeoutSeconds = 1\n\t}\n\tif obj.PeriodSeconds == 0 {\n\t\tobj.PeriodSeconds = 10\n\t}\n\tif obj.SuccessThreshold == 0 {\n\t\tobj.SuccessThreshold = 1\n\t}\n\tif obj.FailureThreshold == 0 {\n\t\tobj.FailureThreshold = 3\n\t}\n}","line":{"from":229,"to":242}} {"id":100002363,"name":"SetDefaults_SecretVolumeSource","signature":"func SetDefaults_SecretVolumeSource(obj *v1.SecretVolumeSource)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_SecretVolumeSource(obj *v1.SecretVolumeSource) {\n\tif obj.DefaultMode == nil {\n\t\tperm := int32(v1.SecretVolumeSourceDefaultMode)\n\t\tobj.DefaultMode = \u0026perm\n\t}\n}","line":{"from":243,"to":248}} {"id":100002364,"name":"SetDefaults_ConfigMapVolumeSource","signature":"func SetDefaults_ConfigMapVolumeSource(obj *v1.ConfigMapVolumeSource)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_ConfigMapVolumeSource(obj *v1.ConfigMapVolumeSource) {\n\tif obj.DefaultMode == nil {\n\t\tperm := int32(v1.ConfigMapVolumeSourceDefaultMode)\n\t\tobj.DefaultMode = \u0026perm\n\t}\n}","line":{"from":249,"to":254}} {"id":100002365,"name":"SetDefaults_DownwardAPIVolumeSource","signature":"func SetDefaults_DownwardAPIVolumeSource(obj *v1.DownwardAPIVolumeSource)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_DownwardAPIVolumeSource(obj *v1.DownwardAPIVolumeSource) {\n\tif obj.DefaultMode == nil {\n\t\tperm := int32(v1.DownwardAPIVolumeSourceDefaultMode)\n\t\tobj.DefaultMode = \u0026perm\n\t}\n}","line":{"from":255,"to":260}} {"id":100002366,"name":"SetDefaults_Secret","signature":"func SetDefaults_Secret(obj *v1.Secret)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_Secret(obj *v1.Secret) {\n\tif obj.Type == \"\" {\n\t\tobj.Type = v1.SecretTypeOpaque\n\t}\n}","line":{"from":261,"to":265}} {"id":100002367,"name":"SetDefaults_ProjectedVolumeSource","signature":"func SetDefaults_ProjectedVolumeSource(obj *v1.ProjectedVolumeSource)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_ProjectedVolumeSource(obj *v1.ProjectedVolumeSource) {\n\tif obj.DefaultMode == nil {\n\t\tperm := int32(v1.ProjectedVolumeSourceDefaultMode)\n\t\tobj.DefaultMode = \u0026perm\n\t}\n}","line":{"from":266,"to":271}} {"id":100002368,"name":"SetDefaults_ServiceAccountTokenProjection","signature":"func SetDefaults_ServiceAccountTokenProjection(obj *v1.ServiceAccountTokenProjection)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_ServiceAccountTokenProjection(obj *v1.ServiceAccountTokenProjection) {\n\thour := int64(time.Hour.Seconds())\n\tif obj.ExpirationSeconds == nil {\n\t\tobj.ExpirationSeconds = \u0026hour\n\t}\n}","line":{"from":272,"to":277}} {"id":100002369,"name":"SetDefaults_PersistentVolume","signature":"func SetDefaults_PersistentVolume(obj *v1.PersistentVolume)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_PersistentVolume(obj *v1.PersistentVolume) {\n\tif obj.Status.Phase == \"\" {\n\t\tobj.Status.Phase = v1.VolumePending\n\t}\n\tif obj.Spec.PersistentVolumeReclaimPolicy == \"\" {\n\t\tobj.Spec.PersistentVolumeReclaimPolicy = v1.PersistentVolumeReclaimRetain\n\t}\n\tif obj.Spec.VolumeMode == nil {\n\t\tobj.Spec.VolumeMode = new(v1.PersistentVolumeMode)\n\t\t*obj.Spec.VolumeMode = v1.PersistentVolumeFilesystem\n\t}\n}","line":{"from":278,"to":289}} {"id":100002370,"name":"SetDefaults_PersistentVolumeClaim","signature":"func SetDefaults_PersistentVolumeClaim(obj *v1.PersistentVolumeClaim)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_PersistentVolumeClaim(obj *v1.PersistentVolumeClaim) {\n\tif obj.Status.Phase == \"\" {\n\t\tobj.Status.Phase = v1.ClaimPending\n\t}\n}","line":{"from":290,"to":294}} {"id":100002371,"name":"SetDefaults_PersistentVolumeClaimSpec","signature":"func SetDefaults_PersistentVolumeClaimSpec(obj *v1.PersistentVolumeClaimSpec)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_PersistentVolumeClaimSpec(obj *v1.PersistentVolumeClaimSpec) {\n\tif obj.VolumeMode == nil {\n\t\tobj.VolumeMode = new(v1.PersistentVolumeMode)\n\t\t*obj.VolumeMode = v1.PersistentVolumeFilesystem\n\t}\n}","line":{"from":295,"to":300}} {"id":100002372,"name":"SetDefaults_ISCSIVolumeSource","signature":"func SetDefaults_ISCSIVolumeSource(obj *v1.ISCSIVolumeSource)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_ISCSIVolumeSource(obj *v1.ISCSIVolumeSource) {\n\tif obj.ISCSIInterface == \"\" {\n\t\tobj.ISCSIInterface = \"default\"\n\t}\n}","line":{"from":301,"to":305}} {"id":100002373,"name":"SetDefaults_ISCSIPersistentVolumeSource","signature":"func SetDefaults_ISCSIPersistentVolumeSource(obj *v1.ISCSIPersistentVolumeSource)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_ISCSIPersistentVolumeSource(obj *v1.ISCSIPersistentVolumeSource) {\n\tif obj.ISCSIInterface == \"\" {\n\t\tobj.ISCSIInterface = \"default\"\n\t}\n}","line":{"from":306,"to":310}} {"id":100002374,"name":"SetDefaults_AzureDiskVolumeSource","signature":"func SetDefaults_AzureDiskVolumeSource(obj *v1.AzureDiskVolumeSource)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_AzureDiskVolumeSource(obj *v1.AzureDiskVolumeSource) {\n\tif obj.CachingMode == nil {\n\t\tobj.CachingMode = new(v1.AzureDataDiskCachingMode)\n\t\t*obj.CachingMode = v1.AzureDataDiskCachingReadWrite\n\t}\n\tif obj.Kind == nil {\n\t\tobj.Kind = new(v1.AzureDataDiskKind)\n\t\t*obj.Kind = v1.AzureSharedBlobDisk\n\t}\n\tif obj.FSType == nil {\n\t\tobj.FSType = new(string)\n\t\t*obj.FSType = \"ext4\"\n\t}\n\tif obj.ReadOnly == nil {\n\t\tobj.ReadOnly = new(bool)\n\t\t*obj.ReadOnly = false\n\t}\n}","line":{"from":311,"to":328}} {"id":100002375,"name":"SetDefaults_Endpoints","signature":"func SetDefaults_Endpoints(obj *v1.Endpoints)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_Endpoints(obj *v1.Endpoints) {\n\tfor i := range obj.Subsets {\n\t\tss := \u0026obj.Subsets[i]\n\t\tfor i := range ss.Ports {\n\t\t\tep := \u0026ss.Ports[i]\n\t\t\tif ep.Protocol == \"\" {\n\t\t\t\tep.Protocol = v1.ProtocolTCP\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":329,"to":339}} {"id":100002376,"name":"SetDefaults_HTTPGetAction","signature":"func SetDefaults_HTTPGetAction(obj *v1.HTTPGetAction)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_HTTPGetAction(obj *v1.HTTPGetAction) {\n\tif obj.Path == \"\" {\n\t\tobj.Path = \"/\"\n\t}\n\tif obj.Scheme == \"\" {\n\t\tobj.Scheme = v1.URISchemeHTTP\n\t}\n}","line":{"from":340,"to":347}} {"id":100002377,"name":"SetDefaults_Namespace","signature":"func SetDefaults_Namespace(obj *v1.Namespace)","file":"pkg/apis/core/v1/defaults.go","code":"// SetDefaults_Namespace adds a default label for all namespaces\nfunc SetDefaults_Namespace(obj *v1.Namespace) {\n\t// we can't SetDefaults for nameless namespaces (generateName).\n\t// This code needs to be kept in sync with the implementation that exists\n\t// in Namespace Canonicalize strategy (pkg/registry/core/namespace)\n\n\t// note that this can result in many calls to feature enablement in some cases, but\n\t// we assume that there's no real cost there.\n\tif len(obj.Name) \u003e 0 {\n\t\tif obj.Labels == nil {\n\t\t\tobj.Labels = map[string]string{}\n\t\t}\n\t\tobj.Labels[v1.LabelMetadataName] = obj.Name\n\t}\n}","line":{"from":349,"to":363}} {"id":100002378,"name":"SetDefaults_NamespaceStatus","signature":"func SetDefaults_NamespaceStatus(obj *v1.NamespaceStatus)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_NamespaceStatus(obj *v1.NamespaceStatus) {\n\tif obj.Phase == \"\" {\n\t\tobj.Phase = v1.NamespaceActive\n\t}\n}","line":{"from":365,"to":369}} {"id":100002379,"name":"SetDefaults_NodeStatus","signature":"func SetDefaults_NodeStatus(obj *v1.NodeStatus)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_NodeStatus(obj *v1.NodeStatus) {\n\tif obj.Allocatable == nil \u0026\u0026 obj.Capacity != nil {\n\t\tobj.Allocatable = make(v1.ResourceList, len(obj.Capacity))\n\t\tfor key, value := range obj.Capacity {\n\t\t\tobj.Allocatable[key] = value.DeepCopy()\n\t\t}\n\t\tobj.Allocatable = obj.Capacity\n\t}\n}","line":{"from":370,"to":378}} {"id":100002380,"name":"SetDefaults_ObjectFieldSelector","signature":"func SetDefaults_ObjectFieldSelector(obj *v1.ObjectFieldSelector)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_ObjectFieldSelector(obj *v1.ObjectFieldSelector) {\n\tif obj.APIVersion == \"\" {\n\t\tobj.APIVersion = \"v1\"\n\t}\n}","line":{"from":379,"to":383}} {"id":100002381,"name":"SetDefaults_LimitRangeItem","signature":"func SetDefaults_LimitRangeItem(obj *v1.LimitRangeItem)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_LimitRangeItem(obj *v1.LimitRangeItem) {\n\t// for container limits, we apply default values\n\tif obj.Type == v1.LimitTypeContainer {\n\n\t\tif obj.Default == nil {\n\t\t\tobj.Default = make(v1.ResourceList)\n\t\t}\n\t\tif obj.DefaultRequest == nil {\n\t\t\tobj.DefaultRequest = make(v1.ResourceList)\n\t\t}\n\n\t\t// If a default limit is unspecified, but the max is specified, default the limit to the max\n\t\tfor key, value := range obj.Max {\n\t\t\tif _, exists := obj.Default[key]; !exists {\n\t\t\t\tobj.Default[key] = value.DeepCopy()\n\t\t\t}\n\t\t}\n\t\t// If a default limit is specified, but the default request is not, default request to limit\n\t\tfor key, value := range obj.Default {\n\t\t\tif _, exists := obj.DefaultRequest[key]; !exists {\n\t\t\t\tobj.DefaultRequest[key] = value.DeepCopy()\n\t\t\t}\n\t\t}\n\t\t// If a default request is not specified, but the min is provided, default request to the min\n\t\tfor key, value := range obj.Min {\n\t\t\tif _, exists := obj.DefaultRequest[key]; !exists {\n\t\t\t\tobj.DefaultRequest[key] = value.DeepCopy()\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":384,"to":414}} {"id":100002382,"name":"SetDefaults_ConfigMap","signature":"func SetDefaults_ConfigMap(obj *v1.ConfigMap)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_ConfigMap(obj *v1.ConfigMap) {\n\tif obj.Data == nil {\n\t\tobj.Data = make(map[string]string)\n\t}\n}","line":{"from":415,"to":419}} {"id":100002383,"name":"defaultHostNetworkPorts","signature":"func defaultHostNetworkPorts(containers *[]v1.Container)","file":"pkg/apis/core/v1/defaults.go","code":"// With host networking default all container ports to host ports.\nfunc defaultHostNetworkPorts(containers *[]v1.Container) {\n\tfor i := range *containers {\n\t\tfor j := range (*containers)[i].Ports {\n\t\t\tif (*containers)[i].Ports[j].HostPort == 0 {\n\t\t\t\t(*containers)[i].Ports[j].HostPort = (*containers)[i].Ports[j].ContainerPort\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":421,"to":430}} {"id":100002384,"name":"SetDefaults_RBDVolumeSource","signature":"func SetDefaults_RBDVolumeSource(obj *v1.RBDVolumeSource)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_RBDVolumeSource(obj *v1.RBDVolumeSource) {\n\tif obj.RBDPool == \"\" {\n\t\tobj.RBDPool = \"rbd\"\n\t}\n\tif obj.RadosUser == \"\" {\n\t\tobj.RadosUser = \"admin\"\n\t}\n\tif obj.Keyring == \"\" {\n\t\tobj.Keyring = \"/etc/ceph/keyring\"\n\t}\n}","line":{"from":432,"to":442}} {"id":100002385,"name":"SetDefaults_RBDPersistentVolumeSource","signature":"func SetDefaults_RBDPersistentVolumeSource(obj *v1.RBDPersistentVolumeSource)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_RBDPersistentVolumeSource(obj *v1.RBDPersistentVolumeSource) {\n\tif obj.RBDPool == \"\" {\n\t\tobj.RBDPool = \"rbd\"\n\t}\n\tif obj.RadosUser == \"\" {\n\t\tobj.RadosUser = \"admin\"\n\t}\n\tif obj.Keyring == \"\" {\n\t\tobj.Keyring = \"/etc/ceph/keyring\"\n\t}\n}","line":{"from":444,"to":454}} {"id":100002386,"name":"SetDefaults_ScaleIOVolumeSource","signature":"func SetDefaults_ScaleIOVolumeSource(obj *v1.ScaleIOVolumeSource)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_ScaleIOVolumeSource(obj *v1.ScaleIOVolumeSource) {\n\tif obj.StorageMode == \"\" {\n\t\tobj.StorageMode = \"ThinProvisioned\"\n\t}\n\tif obj.FSType == \"\" {\n\t\tobj.FSType = \"xfs\"\n\t}\n}","line":{"from":456,"to":463}} {"id":100002387,"name":"SetDefaults_ScaleIOPersistentVolumeSource","signature":"func SetDefaults_ScaleIOPersistentVolumeSource(obj *v1.ScaleIOPersistentVolumeSource)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_ScaleIOPersistentVolumeSource(obj *v1.ScaleIOPersistentVolumeSource) {\n\tif obj.StorageMode == \"\" {\n\t\tobj.StorageMode = \"ThinProvisioned\"\n\t}\n\tif obj.FSType == \"\" {\n\t\tobj.FSType = \"xfs\"\n\t}\n}","line":{"from":465,"to":472}} {"id":100002388,"name":"SetDefaults_HostPathVolumeSource","signature":"func SetDefaults_HostPathVolumeSource(obj *v1.HostPathVolumeSource)","file":"pkg/apis/core/v1/defaults.go","code":"func SetDefaults_HostPathVolumeSource(obj *v1.HostPathVolumeSource) {\n\ttypeVol := v1.HostPathUnset\n\tif obj.Type == nil {\n\t\tobj.Type = \u0026typeVol\n\t}\n}","line":{"from":474,"to":479}} {"id":100002389,"name":"IsExtendedResourceName","signature":"func IsExtendedResourceName(name v1.ResourceName) bool","file":"pkg/apis/core/v1/helper/helpers.go","code":"// IsExtendedResourceName returns true if:\n// 1. the resource name is not in the default namespace;\n// 2. resource name does not have \"requests.\" prefix,\n// to avoid confusion with the convention in quota\n// 3. it satisfies the rules in IsQualifiedName() after converted into quota resource name\nfunc IsExtendedResourceName(name v1.ResourceName) bool {\n\tif IsNativeResource(name) || strings.HasPrefix(string(name), v1.DefaultResourceRequestsPrefix) {\n\t\treturn false\n\t}\n\t// Ensure it satisfies the rules in IsQualifiedName() after converted into quota resource name\n\tnameForQuota := fmt.Sprintf(\"%s%s\", v1.DefaultResourceRequestsPrefix, string(name))\n\tif errs := validation.IsQualifiedName(nameForQuota); len(errs) != 0 {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":31,"to":46}} {"id":100002390,"name":"IsPrefixedNativeResource","signature":"func IsPrefixedNativeResource(name v1.ResourceName) bool","file":"pkg/apis/core/v1/helper/helpers.go","code":"// IsPrefixedNativeResource returns true if the resource name is in the\n// *kubernetes.io/ namespace.\nfunc IsPrefixedNativeResource(name v1.ResourceName) bool {\n\treturn strings.Contains(string(name), v1.ResourceDefaultNamespacePrefix)\n}","line":{"from":48,"to":52}} {"id":100002391,"name":"IsNativeResource","signature":"func IsNativeResource(name v1.ResourceName) bool","file":"pkg/apis/core/v1/helper/helpers.go","code":"// IsNativeResource returns true if the resource name is in the\n// *kubernetes.io/ namespace. Partially-qualified (unprefixed) names are\n// implicitly in the kubernetes.io/ namespace.\nfunc IsNativeResource(name v1.ResourceName) bool {\n\treturn !strings.Contains(string(name), \"/\") ||\n\t\tIsPrefixedNativeResource(name)\n}","line":{"from":54,"to":60}} {"id":100002392,"name":"IsHugePageResourceName","signature":"func IsHugePageResourceName(name v1.ResourceName) bool","file":"pkg/apis/core/v1/helper/helpers.go","code":"// IsHugePageResourceName returns true if the resource name has the huge page\n// resource prefix.\nfunc IsHugePageResourceName(name v1.ResourceName) bool {\n\treturn strings.HasPrefix(string(name), v1.ResourceHugePagesPrefix)\n}","line":{"from":62,"to":66}} {"id":100002393,"name":"HugePageResourceName","signature":"func HugePageResourceName(pageSize resource.Quantity) v1.ResourceName","file":"pkg/apis/core/v1/helper/helpers.go","code":"// HugePageResourceName returns a ResourceName with the canonical hugepage\n// prefix prepended for the specified page size. The page size is converted\n// to its canonical representation.\nfunc HugePageResourceName(pageSize resource.Quantity) v1.ResourceName {\n\treturn v1.ResourceName(fmt.Sprintf(\"%s%s\", v1.ResourceHugePagesPrefix, pageSize.String()))\n}","line":{"from":68,"to":73}} {"id":100002394,"name":"HugePageSizeFromResourceName","signature":"func HugePageSizeFromResourceName(name v1.ResourceName) (resource.Quantity, error)","file":"pkg/apis/core/v1/helper/helpers.go","code":"// HugePageSizeFromResourceName returns the page size for the specified huge page\n// resource name. If the specified input is not a valid huge page resource name\n// an error is returned.\nfunc HugePageSizeFromResourceName(name v1.ResourceName) (resource.Quantity, error) {\n\tif !IsHugePageResourceName(name) {\n\t\treturn resource.Quantity{}, fmt.Errorf(\"resource name: %s is an invalid hugepage name\", name)\n\t}\n\tpageSize := strings.TrimPrefix(string(name), v1.ResourceHugePagesPrefix)\n\treturn resource.ParseQuantity(pageSize)\n}","line":{"from":75,"to":84}} {"id":100002395,"name":"HugePageUnitSizeFromByteSize","signature":"func HugePageUnitSizeFromByteSize(size int64) (string, error)","file":"pkg/apis/core/v1/helper/helpers.go","code":"// HugePageUnitSizeFromByteSize returns hugepage size has the format.\n// `size` must be guaranteed to divisible into the largest units that can be expressed.\n// \u003csize\u003e\u003cunit-prefix\u003eB (1024 = \"1KB\", 1048576 = \"1MB\", etc).\nfunc HugePageUnitSizeFromByteSize(size int64) (string, error) {\n\t// hugePageSizeUnitList is borrowed from opencontainers/runc/libcontainer/cgroups/utils.go\n\tvar hugePageSizeUnitList = []string{\"B\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\"}\n\tidx := 0\n\tlen := len(hugePageSizeUnitList) - 1\n\tfor size%1024 == 0 \u0026\u0026 idx \u003c len {\n\t\tsize /= 1024\n\t\tidx++\n\t}\n\tif size \u003e 1024 \u0026\u0026 idx \u003c len {\n\t\treturn \"\", fmt.Errorf(\"size: %d%s must be guaranteed to divisible into the largest units\", size, hugePageSizeUnitList[idx])\n\t}\n\treturn fmt.Sprintf(\"%d%s\", size, hugePageSizeUnitList[idx]), nil\n}","line":{"from":86,"to":102}} {"id":100002396,"name":"IsHugePageMedium","signature":"func IsHugePageMedium(medium v1.StorageMedium) bool","file":"pkg/apis/core/v1/helper/helpers.go","code":"// IsHugePageMedium returns true if the volume medium is in 'HugePages[-size]' format\nfunc IsHugePageMedium(medium v1.StorageMedium) bool {\n\tif medium == v1.StorageMediumHugePages {\n\t\treturn true\n\t}\n\treturn strings.HasPrefix(string(medium), string(v1.StorageMediumHugePagesPrefix))\n}","line":{"from":104,"to":110}} {"id":100002397,"name":"HugePageSizeFromMedium","signature":"func HugePageSizeFromMedium(medium v1.StorageMedium) (resource.Quantity, error)","file":"pkg/apis/core/v1/helper/helpers.go","code":"// HugePageSizeFromMedium returns the page size for the specified huge page medium.\n// If the specified input is not a valid huge page medium an error is returned.\nfunc HugePageSizeFromMedium(medium v1.StorageMedium) (resource.Quantity, error) {\n\tif !IsHugePageMedium(medium) {\n\t\treturn resource.Quantity{}, fmt.Errorf(\"medium: %s is not a hugepage medium\", medium)\n\t}\n\tif medium == v1.StorageMediumHugePages {\n\t\treturn resource.Quantity{}, fmt.Errorf(\"medium: %s doesn't have size information\", medium)\n\t}\n\tpageSize := strings.TrimPrefix(string(medium), string(v1.StorageMediumHugePagesPrefix))\n\treturn resource.ParseQuantity(pageSize)\n}","line":{"from":112,"to":123}} {"id":100002398,"name":"IsOvercommitAllowed","signature":"func IsOvercommitAllowed(name v1.ResourceName) bool","file":"pkg/apis/core/v1/helper/helpers.go","code":"// IsOvercommitAllowed returns true if the resource is in the default\n// namespace and is not hugepages.\nfunc IsOvercommitAllowed(name v1.ResourceName) bool {\n\treturn IsNativeResource(name) \u0026\u0026\n\t\t!IsHugePageResourceName(name)\n}","line":{"from":125,"to":130}} {"id":100002399,"name":"IsAttachableVolumeResourceName","signature":"func IsAttachableVolumeResourceName(name v1.ResourceName) bool","file":"pkg/apis/core/v1/helper/helpers.go","code":"// IsAttachableVolumeResourceName returns true when the resource name is prefixed in attachable volume\nfunc IsAttachableVolumeResourceName(name v1.ResourceName) bool {\n\treturn strings.HasPrefix(string(name), v1.ResourceAttachableVolumesPrefix)\n}","line":{"from":132,"to":135}} {"id":100002400,"name":"IsServiceIPSet","signature":"func IsServiceIPSet(service *v1.Service) bool","file":"pkg/apis/core/v1/helper/helpers.go","code":"// IsServiceIPSet aims to check if the service's ClusterIP is set or not\n// the objective is not to perform validation here\nfunc IsServiceIPSet(service *v1.Service) bool {\n\treturn service.Spec.ClusterIP != v1.ClusterIPNone \u0026\u0026 service.Spec.ClusterIP != \"\"\n}","line":{"from":137,"to":141}} {"id":100002401,"name":"LoadBalancerStatusEqual","signature":"func LoadBalancerStatusEqual(l, r *v1.LoadBalancerStatus) bool","file":"pkg/apis/core/v1/helper/helpers.go","code":"// LoadBalancerStatusEqual evaluates the given load balancers' ingress IP addresses\n// and hostnames and returns true if equal or false if otherwise\n// TODO: make method on LoadBalancerStatus?\nfunc LoadBalancerStatusEqual(l, r *v1.LoadBalancerStatus) bool {\n\treturn ingressSliceEqual(l.Ingress, r.Ingress)\n}","line":{"from":143,"to":148}} {"id":100002402,"name":"ingressSliceEqual","signature":"func ingressSliceEqual(lhs, rhs []v1.LoadBalancerIngress) bool","file":"pkg/apis/core/v1/helper/helpers.go","code":"func ingressSliceEqual(lhs, rhs []v1.LoadBalancerIngress) bool {\n\tif len(lhs) != len(rhs) {\n\t\treturn false\n\t}\n\tfor i := range lhs {\n\t\tif !ingressEqual(\u0026lhs[i], \u0026rhs[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":150,"to":160}} {"id":100002403,"name":"ingressEqual","signature":"func ingressEqual(lhs, rhs *v1.LoadBalancerIngress) bool","file":"pkg/apis/core/v1/helper/helpers.go","code":"func ingressEqual(lhs, rhs *v1.LoadBalancerIngress) bool {\n\tif lhs.IP != rhs.IP {\n\t\treturn false\n\t}\n\tif lhs.Hostname != rhs.Hostname {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":162,"to":170}} {"id":100002404,"name":"GetAccessModesAsString","signature":"func GetAccessModesAsString(modes []v1.PersistentVolumeAccessMode) string","file":"pkg/apis/core/v1/helper/helpers.go","code":"// GetAccessModesAsString returns a string representation of an array of access modes.\n// modes, when present, are always in the same order: RWO,ROX,RWX,RWOP.\nfunc GetAccessModesAsString(modes []v1.PersistentVolumeAccessMode) string {\n\tmodes = removeDuplicateAccessModes(modes)\n\tmodesStr := []string{}\n\tif ContainsAccessMode(modes, v1.ReadWriteOnce) {\n\t\tmodesStr = append(modesStr, \"RWO\")\n\t}\n\tif ContainsAccessMode(modes, v1.ReadOnlyMany) {\n\t\tmodesStr = append(modesStr, \"ROX\")\n\t}\n\tif ContainsAccessMode(modes, v1.ReadWriteMany) {\n\t\tmodesStr = append(modesStr, \"RWX\")\n\t}\n\tif ContainsAccessMode(modes, v1.ReadWriteOncePod) {\n\t\tmodesStr = append(modesStr, \"RWOP\")\n\t}\n\treturn strings.Join(modesStr, \",\")\n}","line":{"from":172,"to":190}} {"id":100002405,"name":"GetAccessModesFromString","signature":"func GetAccessModesFromString(modes string) []v1.PersistentVolumeAccessMode","file":"pkg/apis/core/v1/helper/helpers.go","code":"// GetAccessModesFromString returns an array of AccessModes from a string created by GetAccessModesAsString\nfunc GetAccessModesFromString(modes string) []v1.PersistentVolumeAccessMode {\n\tstrmodes := strings.Split(modes, \",\")\n\taccessModes := []v1.PersistentVolumeAccessMode{}\n\tfor _, s := range strmodes {\n\t\ts = strings.Trim(s, \" \")\n\t\tswitch {\n\t\tcase s == \"RWO\":\n\t\t\taccessModes = append(accessModes, v1.ReadWriteOnce)\n\t\tcase s == \"ROX\":\n\t\t\taccessModes = append(accessModes, v1.ReadOnlyMany)\n\t\tcase s == \"RWX\":\n\t\t\taccessModes = append(accessModes, v1.ReadWriteMany)\n\t\tcase s == \"RWOP\":\n\t\t\taccessModes = append(accessModes, v1.ReadWriteOncePod)\n\t\t}\n\t}\n\treturn accessModes\n}","line":{"from":192,"to":210}} {"id":100002406,"name":"removeDuplicateAccessModes","signature":"func removeDuplicateAccessModes(modes []v1.PersistentVolumeAccessMode) []v1.PersistentVolumeAccessMode","file":"pkg/apis/core/v1/helper/helpers.go","code":"// removeDuplicateAccessModes returns an array of access modes without any duplicates\nfunc removeDuplicateAccessModes(modes []v1.PersistentVolumeAccessMode) []v1.PersistentVolumeAccessMode {\n\taccessModes := []v1.PersistentVolumeAccessMode{}\n\tfor _, m := range modes {\n\t\tif !ContainsAccessMode(accessModes, m) {\n\t\t\taccessModes = append(accessModes, m)\n\t\t}\n\t}\n\treturn accessModes\n}","line":{"from":212,"to":221}} {"id":100002407,"name":"ContainsAccessMode","signature":"func ContainsAccessMode(modes []v1.PersistentVolumeAccessMode, mode v1.PersistentVolumeAccessMode) bool","file":"pkg/apis/core/v1/helper/helpers.go","code":"func ContainsAccessMode(modes []v1.PersistentVolumeAccessMode, mode v1.PersistentVolumeAccessMode) bool {\n\tfor _, m := range modes {\n\t\tif m == mode {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":223,"to":230}} {"id":100002408,"name":"NodeSelectorRequirementKeysExistInNodeSelectorTerms","signature":"func NodeSelectorRequirementKeysExistInNodeSelectorTerms(reqs []v1.NodeSelectorRequirement, terms []v1.NodeSelectorTerm) bool","file":"pkg/apis/core/v1/helper/helpers.go","code":"// NodeSelectorRequirementKeysExistInNodeSelectorTerms checks if a NodeSelectorTerm with key is already specified in terms\nfunc NodeSelectorRequirementKeysExistInNodeSelectorTerms(reqs []v1.NodeSelectorRequirement, terms []v1.NodeSelectorTerm) bool {\n\tfor _, req := range reqs {\n\t\tfor _, term := range terms {\n\t\t\tfor _, r := range term.MatchExpressions {\n\t\t\t\tif r.Key == req.Key {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":232,"to":244}} {"id":100002409,"name":"TopologySelectorRequirementsAsSelector","signature":"func TopologySelectorRequirementsAsSelector(tsm []v1.TopologySelectorLabelRequirement) (labels.Selector, error)","file":"pkg/apis/core/v1/helper/helpers.go","code":"// TopologySelectorRequirementsAsSelector converts the []TopologySelectorLabelRequirement api type into a struct\n// that implements labels.Selector.\nfunc TopologySelectorRequirementsAsSelector(tsm []v1.TopologySelectorLabelRequirement) (labels.Selector, error) {\n\tif len(tsm) == 0 {\n\t\treturn labels.Nothing(), nil\n\t}\n\n\tselector := labels.NewSelector()\n\tfor _, expr := range tsm {\n\t\tr, err := labels.NewRequirement(expr.Key, selection.In, expr.Values)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tselector = selector.Add(*r)\n\t}\n\n\treturn selector, nil\n}","line":{"from":246,"to":263}} {"id":100002410,"name":"MatchTopologySelectorTerms","signature":"func MatchTopologySelectorTerms(topologySelectorTerms []v1.TopologySelectorTerm, lbls labels.Set) bool","file":"pkg/apis/core/v1/helper/helpers.go","code":"// MatchTopologySelectorTerms checks whether given labels match topology selector terms in ORed;\n// nil or empty term matches no objects; while empty term list matches all objects.\nfunc MatchTopologySelectorTerms(topologySelectorTerms []v1.TopologySelectorTerm, lbls labels.Set) bool {\n\tif len(topologySelectorTerms) == 0 {\n\t\t// empty term list matches all objects\n\t\treturn true\n\t}\n\n\tfor _, req := range topologySelectorTerms {\n\t\t// nil or empty term selects no objects\n\t\tif len(req.MatchLabelExpressions) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tlabelSelector, err := TopologySelectorRequirementsAsSelector(req.MatchLabelExpressions)\n\t\tif err != nil || !labelSelector.Matches(lbls) {\n\t\t\tcontinue\n\t\t}\n\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":265,"to":288}} {"id":100002411,"name":"AddOrUpdateTolerationInPodSpec","signature":"func AddOrUpdateTolerationInPodSpec(spec *v1.PodSpec, toleration *v1.Toleration) bool","file":"pkg/apis/core/v1/helper/helpers.go","code":"// AddOrUpdateTolerationInPodSpec tries to add a toleration to the toleration list in PodSpec.\n// Returns true if something was updated, false otherwise.\nfunc AddOrUpdateTolerationInPodSpec(spec *v1.PodSpec, toleration *v1.Toleration) bool {\n\tpodTolerations := spec.Tolerations\n\n\tvar newTolerations []v1.Toleration\n\tupdated := false\n\tfor i := range podTolerations {\n\t\tif toleration.MatchToleration(\u0026podTolerations[i]) {\n\t\t\tif helper.Semantic.DeepEqual(toleration, podTolerations[i]) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tnewTolerations = append(newTolerations, *toleration)\n\t\t\tupdated = true\n\t\t\tcontinue\n\t\t}\n\n\t\tnewTolerations = append(newTolerations, podTolerations[i])\n\t}\n\n\tif !updated {\n\t\tnewTolerations = append(newTolerations, *toleration)\n\t}\n\n\tspec.Tolerations = newTolerations\n\treturn true\n}","line":{"from":290,"to":316}} {"id":100002412,"name":"AddOrUpdateTolerationInPod","signature":"func AddOrUpdateTolerationInPod(pod *v1.Pod, toleration *v1.Toleration) bool","file":"pkg/apis/core/v1/helper/helpers.go","code":"// AddOrUpdateTolerationInPod tries to add a toleration to the pod's toleration list.\n// Returns true if something was updated, false otherwise.\nfunc AddOrUpdateTolerationInPod(pod *v1.Pod, toleration *v1.Toleration) bool {\n\treturn AddOrUpdateTolerationInPodSpec(\u0026pod.Spec, toleration)\n}","line":{"from":318,"to":322}} {"id":100002413,"name":"GetMatchingTolerations","signature":"func GetMatchingTolerations(taints []v1.Taint, tolerations []v1.Toleration) (bool, []v1.Toleration)","file":"pkg/apis/core/v1/helper/helpers.go","code":"// GetMatchingTolerations returns true and list of Tolerations matching all Taints if all are tolerated, or false otherwise.\nfunc GetMatchingTolerations(taints []v1.Taint, tolerations []v1.Toleration) (bool, []v1.Toleration) {\n\tif len(taints) == 0 {\n\t\treturn true, []v1.Toleration{}\n\t}\n\tif len(tolerations) == 0 \u0026\u0026 len(taints) \u003e 0 {\n\t\treturn false, []v1.Toleration{}\n\t}\n\tresult := []v1.Toleration{}\n\tfor i := range taints {\n\t\ttolerated := false\n\t\tfor j := range tolerations {\n\t\t\tif tolerations[j].ToleratesTaint(\u0026taints[i]) {\n\t\t\t\tresult = append(result, tolerations[j])\n\t\t\t\ttolerated = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !tolerated {\n\t\t\treturn false, []v1.Toleration{}\n\t\t}\n\t}\n\treturn true, result\n}","line":{"from":324,"to":347}} {"id":100002414,"name":"ScopedResourceSelectorRequirementsAsSelector","signature":"func ScopedResourceSelectorRequirementsAsSelector(ssr v1.ScopedResourceSelectorRequirement) (labels.Selector, error)","file":"pkg/apis/core/v1/helper/helpers.go","code":"// ScopedResourceSelectorRequirementsAsSelector converts the ScopedResourceSelectorRequirement api type into a struct that implements\n// labels.Selector.\nfunc ScopedResourceSelectorRequirementsAsSelector(ssr v1.ScopedResourceSelectorRequirement) (labels.Selector, error) {\n\tselector := labels.NewSelector()\n\tvar op selection.Operator\n\tswitch ssr.Operator {\n\tcase v1.ScopeSelectorOpIn:\n\t\top = selection.In\n\tcase v1.ScopeSelectorOpNotIn:\n\t\top = selection.NotIn\n\tcase v1.ScopeSelectorOpExists:\n\t\top = selection.Exists\n\tcase v1.ScopeSelectorOpDoesNotExist:\n\t\top = selection.DoesNotExist\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"%q is not a valid scope selector operator\", ssr.Operator)\n\t}\n\tr, err := labels.NewRequirement(string(ssr.ScopeName), op, ssr.Values)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tselector = selector.Add(*r)\n\treturn selector, nil\n}","line":{"from":349,"to":372}} {"id":100002415,"name":"isSupportedQoSComputeResource","signature":"func isSupportedQoSComputeResource(name v1.ResourceName) bool","file":"pkg/apis/core/v1/helper/qos/qos.go","code":"func isSupportedQoSComputeResource(name v1.ResourceName) bool {\n\treturn supportedQoSComputeResources.Has(string(name))\n}","line":{"from":31,"to":33}} {"id":100002416,"name":"GetPodQOS","signature":"func GetPodQOS(pod *v1.Pod) v1.PodQOSClass","file":"pkg/apis/core/v1/helper/qos/qos.go","code":"// GetPodQOS returns the QoS class of a pod.\n// A pod is besteffort if none of its containers have specified any requests or limits.\n// A pod is guaranteed only when requests and limits are specified for all the containers and they are equal.\n// A pod is burstable if limits and requests do not match across all containers.\nfunc GetPodQOS(pod *v1.Pod) v1.PodQOSClass {\n\trequests := v1.ResourceList{}\n\tlimits := v1.ResourceList{}\n\tzeroQuantity := resource.MustParse(\"0\")\n\tisGuaranteed := true\n\tallContainers := []v1.Container{}\n\tallContainers = append(allContainers, pod.Spec.Containers...)\n\tallContainers = append(allContainers, pod.Spec.InitContainers...)\n\tfor _, container := range allContainers {\n\t\t// process requests\n\t\tfor name, quantity := range container.Resources.Requests {\n\t\t\tif !isSupportedQoSComputeResource(name) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif quantity.Cmp(zeroQuantity) == 1 {\n\t\t\t\tdelta := quantity.DeepCopy()\n\t\t\t\tif _, exists := requests[name]; !exists {\n\t\t\t\t\trequests[name] = delta\n\t\t\t\t} else {\n\t\t\t\t\tdelta.Add(requests[name])\n\t\t\t\t\trequests[name] = delta\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// process limits\n\t\tqosLimitsFound := sets.NewString()\n\t\tfor name, quantity := range container.Resources.Limits {\n\t\t\tif !isSupportedQoSComputeResource(name) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif quantity.Cmp(zeroQuantity) == 1 {\n\t\t\t\tqosLimitsFound.Insert(string(name))\n\t\t\t\tdelta := quantity.DeepCopy()\n\t\t\t\tif _, exists := limits[name]; !exists {\n\t\t\t\t\tlimits[name] = delta\n\t\t\t\t} else {\n\t\t\t\t\tdelta.Add(limits[name])\n\t\t\t\t\tlimits[name] = delta\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif !qosLimitsFound.HasAll(string(v1.ResourceMemory), string(v1.ResourceCPU)) {\n\t\t\tisGuaranteed = false\n\t\t}\n\t}\n\tif len(requests) == 0 \u0026\u0026 len(limits) == 0 {\n\t\treturn v1.PodQOSBestEffort\n\t}\n\t// Check is requests match limits for all resources.\n\tif isGuaranteed {\n\t\tfor name, req := range requests {\n\t\t\tif lim, exists := limits[name]; !exists || lim.Cmp(req) != 0 {\n\t\t\t\tisGuaranteed = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif isGuaranteed \u0026\u0026\n\t\tlen(requests) == len(limits) {\n\t\treturn v1.PodQOSGuaranteed\n\t}\n\treturn v1.PodQOSBurstable\n}","line":{"from":35,"to":102}} {"id":100002417,"name":"init","signature":"func init()","file":"pkg/apis/core/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs, addConversionFuncs)\n}","line":{"from":29,"to":34}} {"id":100002418,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/core/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":43,"to":46}} {"id":100002419,"name":"ValidateResourceRequirements","signature":"func ValidateResourceRequirements(requirements *v1.ResourceRequirements, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/v1/validation/validation.go","code":"// ValidateResourceRequirements will check if any of the resource\n// Limits/Requests are of a valid value. Any incorrect value will be added to\n// the ErrorList.\nfunc ValidateResourceRequirements(requirements *v1.ResourceRequirements, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tlimPath := fldPath.Child(\"limits\")\n\treqPath := fldPath.Child(\"requests\")\n\tfor resourceName, quantity := range requirements.Limits {\n\t\tfldPath := limPath.Key(string(resourceName))\n\t\t// Validate resource name.\n\t\tallErrs = append(allErrs, ValidateContainerResourceName(string(resourceName), fldPath)...)\n\n\t\t// Validate resource quantity.\n\t\tallErrs = append(allErrs, ValidateResourceQuantityValue(string(resourceName), quantity, fldPath)...)\n\n\t}\n\tfor resourceName, quantity := range requirements.Requests {\n\t\tfldPath := reqPath.Key(string(resourceName))\n\t\t// Validate resource name.\n\t\tallErrs = append(allErrs, ValidateContainerResourceName(string(resourceName), fldPath)...)\n\t\t// Validate resource quantity.\n\t\tallErrs = append(allErrs, ValidateResourceQuantityValue(string(resourceName), quantity, fldPath)...)\n\n\t\t// Check that request \u003c= limit.\n\t\tlimitQuantity, exists := requirements.Limits[resourceName]\n\t\tif exists {\n\t\t\t// For GPUs, not only requests can't exceed limits, they also can't be lower, i.e. must be equal.\n\t\t\tif quantity.Cmp(limitQuantity) != 0 \u0026\u0026 !v1helper.IsOvercommitAllowed(resourceName) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(reqPath, quantity.String(), fmt.Sprintf(\"must be equal to %s limit of %s\", resourceName, limitQuantity.String())))\n\t\t\t} else if quantity.Cmp(limitQuantity) \u003e 0 {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(reqPath, quantity.String(), fmt.Sprintf(\"must be less than or equal to %s limit of %s\", resourceName, limitQuantity.String())))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":35,"to":71}} {"id":100002420,"name":"ValidateContainerResourceName","signature":"func ValidateContainerResourceName(value string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/v1/validation/validation.go","code":"// ValidateContainerResourceName checks the name of resource specified for a container\nfunc ValidateContainerResourceName(value string, fldPath *field.Path) field.ErrorList {\n\tallErrs := validateResourceName(value, fldPath)\n\tif len(strings.Split(value, \"/\")) == 1 {\n\t\tif !helper.IsStandardContainerResourceName(value) {\n\t\t\treturn append(allErrs, field.Invalid(fldPath, value, \"must be a standard resource for containers\"))\n\t\t}\n\t} else if !v1helper.IsNativeResource(v1.ResourceName(value)) {\n\t\tif !v1helper.IsExtendedResourceName(v1.ResourceName(value)) {\n\t\t\treturn append(allErrs, field.Invalid(fldPath, value, \"doesn't follow extended resource name standard\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":73,"to":86}} {"id":100002421,"name":"ValidateResourceQuantityValue","signature":"func ValidateResourceQuantityValue(resource string, value resource.Quantity, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/v1/validation/validation.go","code":"// ValidateResourceQuantityValue enforces that specified quantity is valid for specified resource\nfunc ValidateResourceQuantityValue(resource string, value resource.Quantity, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, ValidateNonnegativeQuantity(value, fldPath)...)\n\tif helper.IsIntegerResourceName(resource) {\n\t\tif value.MilliValue()%int64(1000) != int64(0) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, value, isNotIntegerErrorMsg))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":88,"to":98}} {"id":100002422,"name":"ValidateNonnegativeQuantity","signature":"func ValidateNonnegativeQuantity(value resource.Quantity, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/v1/validation/validation.go","code":"// ValidateNonnegativeQuantity checks that a Quantity is not negative.\nfunc ValidateNonnegativeQuantity(value resource.Quantity, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif value.Cmp(resource.Quantity{}) \u003c 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, value.String(), isNegativeErrorMsg))\n\t}\n\treturn allErrs\n}","line":{"from":100,"to":107}} {"id":100002423,"name":"validateResourceName","signature":"func validateResourceName(value string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/v1/validation/validation.go","code":"// Validate compute resource typename.\n// Refer to docs/design/resources.md for more details.\nfunc validateResourceName(value string, fldPath *field.Path) field.ErrorList {\n\tallErrs := apivalidation.ValidateQualifiedName(value, fldPath)\n\tif len(allErrs) != 0 {\n\t\treturn allErrs\n\t}\n\n\tif len(strings.Split(value, \"/\")) == 1 {\n\t\tif !helper.IsStandardResourceName(value) {\n\t\t\treturn append(allErrs, field.Invalid(fldPath, value, \"must be a standard resource type or fully qualified\"))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":109,"to":124}} {"id":100002424,"name":"ValidatePodLogOptions","signature":"func ValidatePodLogOptions(opts *v1.PodLogOptions) field.ErrorList","file":"pkg/apis/core/v1/validation/validation.go","code":"// ValidatePodLogOptions checks if options that are set are at the correct\n// value. Any incorrect value will be returned to the ErrorList.\nfunc ValidatePodLogOptions(opts *v1.PodLogOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif opts.TailLines != nil \u0026\u0026 *opts.TailLines \u003c 0 {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"tailLines\"), *opts.TailLines, isNegativeErrorMsg))\n\t}\n\tif opts.LimitBytes != nil \u0026\u0026 *opts.LimitBytes \u003c 1 {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"limitBytes\"), *opts.LimitBytes, \"must be greater than 0\"))\n\t}\n\tswitch {\n\tcase opts.SinceSeconds != nil \u0026\u0026 opts.SinceTime != nil:\n\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"\"), \"at most one of `sinceTime` or `sinceSeconds` may be specified\"))\n\tcase opts.SinceSeconds != nil:\n\t\tif *opts.SinceSeconds \u003c 1 {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"sinceSeconds\"), *opts.SinceSeconds, \"must be greater than 0\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":126,"to":145}} {"id":100002425,"name":"AccumulateUniqueHostPorts","signature":"func AccumulateUniqueHostPorts(containers []v1.Container, accumulator *sets.String, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/v1/validation/validation.go","code":"// AccumulateUniqueHostPorts checks all the containers for duplicates ports. Any\n// duplicate port will be returned in the ErrorList.\nfunc AccumulateUniqueHostPorts(containers []v1.Container, accumulator *sets.String, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tfor ci, ctr := range containers {\n\t\tidxPath := fldPath.Index(ci)\n\t\tportsPath := idxPath.Child(\"ports\")\n\t\tfor pi := range ctr.Ports {\n\t\t\tidxPath := portsPath.Index(pi)\n\t\t\tport := ctr.Ports[pi].HostPort\n\t\t\tif port == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstr := fmt.Sprintf(\"%d/%s\", port, ctr.Ports[pi].Protocol)\n\t\t\tif accumulator.Has(str) {\n\t\t\t\tallErrs = append(allErrs, field.Duplicate(idxPath.Child(\"hostPort\"), str))\n\t\t\t} else {\n\t\t\t\taccumulator.Insert(str)\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":147,"to":170}} {"id":100002426,"name":"ValidateEventCreate","signature":"func ValidateEventCreate(event *core.Event, requestVersion schema.GroupVersion) field.ErrorList","file":"pkg/apis/core/validation/events.go","code":"func ValidateEventCreate(event *core.Event, requestVersion schema.GroupVersion) field.ErrorList {\n\t// Make sure events always pass legacy validation.\n\tallErrs := legacyValidateEvent(event, requestVersion)\n\tif requestVersion == v1.SchemeGroupVersion || requestVersion == eventsv1beta1.SchemeGroupVersion {\n\t\t// No further validation for backwards compatibility.\n\t\treturn allErrs\n\t}\n\n\t// Strict validation applies to creation via events.k8s.io/v1 API and newer.\n\tallErrs = append(allErrs, ValidateObjectMeta(\u0026event.ObjectMeta, true, apimachineryvalidation.NameIsDNSSubdomain, field.NewPath(\"metadata\"))...)\n\tallErrs = append(allErrs, validateV1EventSeries(event)...)\n\tzeroTime := time.Time{}\n\tif event.EventTime.Time == zeroTime {\n\t\tallErrs = append(allErrs, field.Required(field.NewPath(\"eventTime\"), \"\"))\n\t}\n\tif event.Type != v1.EventTypeNormal \u0026\u0026 event.Type != v1.EventTypeWarning {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"type\"), \"\", fmt.Sprintf(\"has invalid value: %v\", event.Type)))\n\t}\n\tif event.FirstTimestamp.Time != zeroTime {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"firstTimestamp\"), \"\", \"needs to be unset\"))\n\t}\n\tif event.LastTimestamp.Time != zeroTime {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"lastTimestamp\"), \"\", \"needs to be unset\"))\n\t}\n\tif event.Count != 0 {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"count\"), \"\", \"needs to be unset\"))\n\t}\n\tif event.Source.Component != \"\" || event.Source.Host != \"\" {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"source\"), \"\", \"needs to be unset\"))\n\t}\n\treturn allErrs\n}","line":{"from":41,"to":72}} {"id":100002427,"name":"ValidateEventUpdate","signature":"func ValidateEventUpdate(newEvent, oldEvent *core.Event, requestVersion schema.GroupVersion) field.ErrorList","file":"pkg/apis/core/validation/events.go","code":"func ValidateEventUpdate(newEvent, oldEvent *core.Event, requestVersion schema.GroupVersion) field.ErrorList {\n\t// Make sure the new event always passes legacy validation.\n\tallErrs := legacyValidateEvent(newEvent, requestVersion)\n\tif requestVersion == v1.SchemeGroupVersion || requestVersion == eventsv1beta1.SchemeGroupVersion {\n\t\t// No further validation for backwards compatibility.\n\t\treturn allErrs\n\t}\n\n\t// Strict validation applies to update via events.k8s.io/v1 API and newer.\n\tallErrs = append(allErrs, ValidateObjectMetaUpdate(\u0026newEvent.ObjectMeta, \u0026oldEvent.ObjectMeta, field.NewPath(\"metadata\"))...)\n\t// if the series was modified, validate the new data\n\tif !reflect.DeepEqual(newEvent.Series, oldEvent.Series) {\n\t\tallErrs = append(allErrs, validateV1EventSeries(newEvent)...)\n\t}\n\n\tallErrs = append(allErrs, ValidateImmutableField(newEvent.InvolvedObject, oldEvent.InvolvedObject, field.NewPath(\"involvedObject\"))...)\n\tallErrs = append(allErrs, ValidateImmutableField(newEvent.Reason, oldEvent.Reason, field.NewPath(\"reason\"))...)\n\tallErrs = append(allErrs, ValidateImmutableField(newEvent.Message, oldEvent.Message, field.NewPath(\"message\"))...)\n\tallErrs = append(allErrs, ValidateImmutableField(newEvent.Source, oldEvent.Source, field.NewPath(\"source\"))...)\n\tallErrs = append(allErrs, ValidateImmutableField(newEvent.FirstTimestamp, oldEvent.FirstTimestamp, field.NewPath(\"firstTimestamp\"))...)\n\tallErrs = append(allErrs, ValidateImmutableField(newEvent.LastTimestamp, oldEvent.LastTimestamp, field.NewPath(\"lastTimestamp\"))...)\n\tallErrs = append(allErrs, ValidateImmutableField(newEvent.Count, oldEvent.Count, field.NewPath(\"count\"))...)\n\tallErrs = append(allErrs, ValidateImmutableField(newEvent.Reason, oldEvent.Reason, field.NewPath(\"reason\"))...)\n\tallErrs = append(allErrs, ValidateImmutableField(newEvent.Type, oldEvent.Type, field.NewPath(\"type\"))...)\n\n\t// Disallow changes to eventTime greater than microsecond-level precision.\n\t// Tolerating sub-microsecond changes is required to tolerate updates\n\t// from clients that correctly truncate to microsecond-precision when serializing,\n\t// or from clients built with incorrect nanosecond-precision protobuf serialization.\n\t// See https://github.com/kubernetes/kubernetes/issues/111928\n\tnewTruncated := newEvent.EventTime.Truncate(time.Microsecond).UTC()\n\toldTruncated := oldEvent.EventTime.Truncate(time.Microsecond).UTC()\n\tif newTruncated != oldTruncated {\n\t\tallErrs = append(allErrs, ValidateImmutableField(newEvent.EventTime, oldEvent.EventTime, field.NewPath(\"eventTime\"))...)\n\t}\n\n\tallErrs = append(allErrs, ValidateImmutableField(newEvent.Action, oldEvent.Action, field.NewPath(\"action\"))...)\n\tallErrs = append(allErrs, ValidateImmutableField(newEvent.Related, oldEvent.Related, field.NewPath(\"related\"))...)\n\tallErrs = append(allErrs, ValidateImmutableField(newEvent.ReportingController, oldEvent.ReportingController, field.NewPath(\"reportingController\"))...)\n\tallErrs = append(allErrs, ValidateImmutableField(newEvent.ReportingInstance, oldEvent.ReportingInstance, field.NewPath(\"reportingInstance\"))...)\n\n\treturn allErrs\n}","line":{"from":74,"to":116}} {"id":100002428,"name":"validateV1EventSeries","signature":"func validateV1EventSeries(event *core.Event) field.ErrorList","file":"pkg/apis/core/validation/events.go","code":"func validateV1EventSeries(event *core.Event) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tzeroTime := time.Time{}\n\tif event.Series != nil {\n\t\tif event.Series.Count \u003c 2 {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"series.count\"), \"\", \"should be at least 2\"))\n\t\t}\n\t\tif event.Series.LastObservedTime.Time == zeroTime {\n\t\t\tallErrs = append(allErrs, field.Required(field.NewPath(\"series.lastObservedTime\"), \"\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":118,"to":130}} {"id":100002429,"name":"legacyValidateEvent","signature":"func legacyValidateEvent(event *core.Event, requestVersion schema.GroupVersion) field.ErrorList","file":"pkg/apis/core/validation/events.go","code":"// legacyValidateEvent makes sure that the event makes sense.\nfunc legacyValidateEvent(event *core.Event, requestVersion schema.GroupVersion) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\t// Because go\n\tzeroTime := time.Time{}\n\n\treportingControllerFieldName := \"reportingController\"\n\tif requestVersion == v1.SchemeGroupVersion {\n\t\treportingControllerFieldName = \"reportingComponent\"\n\t}\n\n\t// \"New\" Events need to have EventTime set, so it's validating old object.\n\tif event.EventTime.Time == zeroTime {\n\t\t// Make sure event.Namespace and the involvedInvolvedObject.Namespace agree\n\t\tif len(event.InvolvedObject.Namespace) == 0 {\n\t\t\t// event.Namespace must also be empty (or \"default\", for compatibility with old clients)\n\t\t\tif event.Namespace != metav1.NamespaceNone \u0026\u0026 event.Namespace != metav1.NamespaceDefault {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"involvedObject\", \"namespace\"), event.InvolvedObject.Namespace, \"does not match event.namespace\"))\n\t\t\t}\n\t\t} else {\n\t\t\t// event namespace must match\n\t\t\tif event.Namespace != event.InvolvedObject.Namespace {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"involvedObject\", \"namespace\"), event.InvolvedObject.Namespace, \"does not match event.namespace\"))\n\t\t\t}\n\t\t}\n\n\t} else {\n\t\tif len(event.InvolvedObject.Namespace) == 0 \u0026\u0026 event.Namespace != metav1.NamespaceDefault \u0026\u0026 event.Namespace != metav1.NamespaceSystem {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"involvedObject\", \"namespace\"), event.InvolvedObject.Namespace, \"does not match event.namespace\"))\n\t\t}\n\t\tif len(event.ReportingController) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(field.NewPath(reportingControllerFieldName), \"\"))\n\t\t}\n\t\tallErrs = append(allErrs, ValidateQualifiedName(event.ReportingController, field.NewPath(reportingControllerFieldName))...)\n\t\tif len(event.ReportingInstance) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(field.NewPath(\"reportingInstance\"), \"\"))\n\t\t}\n\t\tif len(event.ReportingInstance) \u003e ReportingInstanceLengthLimit {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"reportingInstance\"), \"\", fmt.Sprintf(\"can have at most %v characters\", ReportingInstanceLengthLimit)))\n\t\t}\n\t\tif len(event.Action) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(field.NewPath(\"action\"), \"\"))\n\t\t}\n\t\tif len(event.Action) \u003e ActionLengthLimit {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"action\"), \"\", fmt.Sprintf(\"can have at most %v characters\", ActionLengthLimit)))\n\t\t}\n\t\tif len(event.Reason) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(field.NewPath(\"reason\"), \"\"))\n\t\t}\n\t\tif len(event.Reason) \u003e ReasonLengthLimit {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"reason\"), \"\", fmt.Sprintf(\"can have at most %v characters\", ReasonLengthLimit)))\n\t\t}\n\t\tif len(event.Message) \u003e NoteLengthLimit {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"message\"), \"\", fmt.Sprintf(\"can have at most %v characters\", NoteLengthLimit)))\n\t\t}\n\t}\n\n\tfor _, msg := range validation.IsDNS1123Subdomain(event.Namespace) {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"namespace\"), event.Namespace, msg))\n\t}\n\treturn allErrs\n}","line":{"from":132,"to":193}} {"id":100002430,"name":"ValidateHasLabel","signature":"func ValidateHasLabel(meta metav1.ObjectMeta, fldPath *field.Path, key, expectedValue string) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateHasLabel requires that metav1.ObjectMeta has a Label with key and expectedValue\nfunc ValidateHasLabel(meta metav1.ObjectMeta, fldPath *field.Path, key, expectedValue string) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tactualValue, found := meta.Labels[key]\n\tif !found {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"labels\").Key(key),\n\t\t\tfmt.Sprintf(\"must be '%s'\", expectedValue)))\n\t\treturn allErrs\n\t}\n\tif actualValue != expectedValue {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"labels\").Key(key), meta.Labels,\n\t\t\tfmt.Sprintf(\"must be '%s'\", expectedValue)))\n\t}\n\treturn allErrs\n}","line":{"from":109,"to":123}} {"id":100002431,"name":"ValidateAnnotations","signature":"func ValidateAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateAnnotations validates that a set of annotations are correctly defined.\nfunc ValidateAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList {\n\treturn apimachineryvalidation.ValidateAnnotations(annotations, fldPath)\n}","line":{"from":125,"to":128}} {"id":100002432,"name":"ValidateDNS1123Label","signature":"func ValidateDNS1123Label(value string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func ValidateDNS1123Label(value string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor _, msg := range validation.IsDNS1123Label(value) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, value, msg))\n\t}\n\treturn allErrs\n}","line":{"from":130,"to":136}} {"id":100002433,"name":"ValidateQualifiedName","signature":"func ValidateQualifiedName(value string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateQualifiedName validates if name is what Kubernetes calls a \"qualified name\".\nfunc ValidateQualifiedName(value string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor _, msg := range validation.IsQualifiedName(value) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, value, msg))\n\t}\n\treturn allErrs\n}","line":{"from":138,"to":145}} {"id":100002434,"name":"ValidateDNS1123Subdomain","signature":"func ValidateDNS1123Subdomain(value string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateDNS1123Subdomain validates that a name is a proper DNS subdomain.\nfunc ValidateDNS1123Subdomain(value string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor _, msg := range validation.IsDNS1123Subdomain(value) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, value, msg))\n\t}\n\treturn allErrs\n}","line":{"from":147,"to":154}} {"id":100002435,"name":"ValidatePodSpecificAnnotations","signature":"func ValidatePodSpecificAnnotations(annotations map[string]string, spec *core.PodSpec, fldPath *field.Path, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func ValidatePodSpecificAnnotations(annotations map[string]string, spec *core.PodSpec, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif value, isMirror := annotations[core.MirrorPodAnnotationKey]; isMirror {\n\t\tif len(spec.NodeName) == 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Key(core.MirrorPodAnnotationKey), value, \"must set spec.nodeName if mirror pod annotation is set\"))\n\t\t}\n\t}\n\n\tif annotations[core.TolerationsAnnotationKey] != \"\" {\n\t\tallErrs = append(allErrs, ValidateTolerationsInPodAnnotations(annotations, fldPath)...)\n\t}\n\n\tif !opts.AllowInvalidPodDeletionCost {\n\t\tif _, err := helper.GetDeletionCostFromPodAnnotations(annotations); err != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Key(core.PodDeletionCost), annotations[core.PodDeletionCost], \"must be a 32bit integer\"))\n\t\t}\n\t}\n\n\tallErrs = append(allErrs, ValidateSeccompPodAnnotations(annotations, fldPath)...)\n\tallErrs = append(allErrs, ValidateAppArmorPodAnnotations(annotations, spec, fldPath)...)\n\n\treturn allErrs\n}","line":{"from":156,"to":179}} {"id":100002436,"name":"ValidateTolerationsInPodAnnotations","signature":"func ValidateTolerationsInPodAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateTolerationsInPodAnnotations tests that the serialized tolerations in Pod.Annotations has valid data\nfunc ValidateTolerationsInPodAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\ttolerations, err := helper.GetTolerationsFromPodAnnotations(annotations)\n\tif err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, core.TolerationsAnnotationKey, err.Error()))\n\t\treturn allErrs\n\t}\n\n\tif len(tolerations) \u003e 0 {\n\t\tallErrs = append(allErrs, ValidateTolerations(tolerations, fldPath.Child(core.TolerationsAnnotationKey))...)\n\t}\n\n\treturn allErrs\n}","line":{"from":181,"to":196}} {"id":100002437,"name":"ValidatePodSpecificAnnotationUpdates","signature":"func ValidatePodSpecificAnnotationUpdates(newPod, oldPod *core.Pod, fldPath *field.Path, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func ValidatePodSpecificAnnotationUpdates(newPod, oldPod *core.Pod, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tnewAnnotations := newPod.Annotations\n\toldAnnotations := oldPod.Annotations\n\tfor k, oldVal := range oldAnnotations {\n\t\tif newVal, exists := newAnnotations[k]; exists \u0026\u0026 newVal == oldVal {\n\t\t\tcontinue // No change.\n\t\t}\n\t\tif strings.HasPrefix(k, v1.AppArmorBetaContainerAnnotationKeyPrefix) {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Key(k), \"may not remove or update AppArmor annotations\"))\n\t\t}\n\t\tif k == core.MirrorPodAnnotationKey {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Key(k), \"may not remove or update mirror pod annotation\"))\n\t\t}\n\t}\n\t// Check for additions\n\tfor k := range newAnnotations {\n\t\tif _, ok := oldAnnotations[k]; ok {\n\t\t\tcontinue // No change.\n\t\t}\n\t\tif strings.HasPrefix(k, v1.AppArmorBetaContainerAnnotationKeyPrefix) {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Key(k), \"may not add AppArmor annotations\"))\n\t\t}\n\t\tif k == core.MirrorPodAnnotationKey {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Key(k), \"may not add mirror pod annotation\"))\n\t\t}\n\t}\n\tallErrs = append(allErrs, ValidatePodSpecificAnnotations(newAnnotations, \u0026newPod.Spec, fldPath, opts)...)\n\treturn allErrs\n}","line":{"from":198,"to":227}} {"id":100002438,"name":"ValidateEndpointsSpecificAnnotations","signature":"func ValidateEndpointsSpecificAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func ValidateEndpointsSpecificAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\treturn allErrs\n}","line":{"from":229,"to":232}} {"id":100002439,"name":"ValidateRuntimeClassName","signature":"func ValidateRuntimeClassName(name string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateRuntimeClassName can be used to check whether the given RuntimeClass name is valid.\n// Prefix indicates this name will be used as part of generation, in which case\n// trailing dashes are allowed.\nfunc ValidateRuntimeClassName(name string, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tfor _, msg := range apimachineryvalidation.NameIsDNSSubdomain(name, false) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, name, msg))\n\t}\n\treturn allErrs\n}","line":{"from":310,"to":319}} {"id":100002440,"name":"validateOverhead","signature":"func validateOverhead(overhead core.ResourceList, fldPath *field.Path, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateOverhead can be used to check whether the given Overhead is valid.\nfunc validateOverhead(overhead core.ResourceList, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {\n\t// reuse the ResourceRequirements validation logic\n\treturn ValidateResourceRequirements(\u0026core.ResourceRequirements{Limits: overhead}, nil, fldPath, opts)\n}","line":{"from":321,"to":325}} {"id":100002441,"name":"ValidateNonnegativeField","signature":"func ValidateNonnegativeField(value int64, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// Validates that given value is not negative.\nfunc ValidateNonnegativeField(value int64, fldPath *field.Path) field.ErrorList {\n\treturn apimachineryvalidation.ValidateNonnegativeField(value, fldPath)\n}","line":{"from":327,"to":330}} {"id":100002442,"name":"ValidateNonnegativeQuantity","signature":"func ValidateNonnegativeQuantity(value resource.Quantity, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// Validates that a Quantity is not negative\nfunc ValidateNonnegativeQuantity(value resource.Quantity, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif value.Cmp(resource.Quantity{}) \u003c 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, value.String(), isNegativeErrorMsg))\n\t}\n\treturn allErrs\n}","line":{"from":332,"to":339}} {"id":100002443,"name":"ValidatePositiveQuantityValue","signature":"func ValidatePositiveQuantityValue(value resource.Quantity, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// Validates that a Quantity is positive\nfunc ValidatePositiveQuantityValue(value resource.Quantity, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif value.Cmp(resource.Quantity{}) \u003c= 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, value.String(), isNotPositiveErrorMsg))\n\t}\n\treturn allErrs\n}","line":{"from":341,"to":348}} {"id":100002444,"name":"ValidateImmutableField","signature":"func ValidateImmutableField(newVal, oldVal interface{}, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func ValidateImmutableField(newVal, oldVal interface{}, fldPath *field.Path) field.ErrorList {\n\treturn apimachineryvalidation.ValidateImmutableField(newVal, oldVal, fldPath)\n}","line":{"from":350,"to":352}} {"id":100002445,"name":"ValidateImmutableAnnotation","signature":"func ValidateImmutableAnnotation(newVal string, oldVal string, annotation string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func ValidateImmutableAnnotation(newVal string, oldVal string, annotation string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif oldVal != newVal {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"annotations\", annotation), newVal, fieldImmutableErrorMsg))\n\t}\n\treturn allErrs\n}","line":{"from":354,"to":361}} {"id":100002446,"name":"ValidateObjectMeta","signature":"func ValidateObjectMeta(meta *metav1.ObjectMeta, requiresNamespace bool, nameFn ValidateNameFunc, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateObjectMeta validates an object's metadata on creation. It expects that name generation has already\n// been performed.\n// It doesn't return an error for rootscoped resources with namespace, because namespace should already be cleared before.\n// TODO: Remove calls to this method scattered in validations of specific resources, e.g., ValidatePodUpdate.\nfunc ValidateObjectMeta(meta *metav1.ObjectMeta, requiresNamespace bool, nameFn ValidateNameFunc, fldPath *field.Path) field.ErrorList {\n\tallErrs := apimachineryvalidation.ValidateObjectMeta(meta, requiresNamespace, apimachineryvalidation.ValidateNameFunc(nameFn), fldPath)\n\t// run additional checks for the finalizer name\n\tfor i := range meta.Finalizers {\n\t\tallErrs = append(allErrs, validateKubeFinalizerName(string(meta.Finalizers[i]), fldPath.Child(\"finalizers\").Index(i))...)\n\t}\n\treturn allErrs\n}","line":{"from":363,"to":374}} {"id":100002447,"name":"ValidateObjectMetaUpdate","signature":"func ValidateObjectMetaUpdate(newMeta, oldMeta *metav1.ObjectMeta, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateObjectMetaUpdate validates an object's metadata when updated\nfunc ValidateObjectMetaUpdate(newMeta, oldMeta *metav1.ObjectMeta, fldPath *field.Path) field.ErrorList {\n\tallErrs := apimachineryvalidation.ValidateObjectMetaUpdate(newMeta, oldMeta, fldPath)\n\t// run additional checks for the finalizer name\n\tfor i := range newMeta.Finalizers {\n\t\tallErrs = append(allErrs, validateKubeFinalizerName(string(newMeta.Finalizers[i]), fldPath.Child(\"finalizers\").Index(i))...)\n\t}\n\n\treturn allErrs\n}","line":{"from":376,"to":385}} {"id":100002448,"name":"ValidateVolumes","signature":"func ValidateVolumes(volumes []core.Volume, podMeta *metav1.ObjectMeta, fldPath *field.Path, opts PodValidationOptions) (map[string]core.VolumeSource, field.ErrorList)","file":"pkg/apis/core/validation/validation.go","code":"func ValidateVolumes(volumes []core.Volume, podMeta *metav1.ObjectMeta, fldPath *field.Path, opts PodValidationOptions) (map[string]core.VolumeSource, field.ErrorList) {\n\tallErrs := field.ErrorList{}\n\n\tallNames := sets.String{}\n\tallCreatedPVCs := sets.String{}\n\t// Determine which PVCs will be created for this pod. We need\n\t// the exact name of the pod for this. Without it, this sanity\n\t// check has to be skipped.\n\tif podMeta != nil \u0026\u0026 podMeta.Name != \"\" {\n\t\tfor _, vol := range volumes {\n\t\t\tif vol.VolumeSource.Ephemeral != nil {\n\t\t\t\tallCreatedPVCs.Insert(podMeta.Name + \"-\" + vol.Name)\n\t\t\t}\n\t\t}\n\t}\n\tvols := make(map[string]core.VolumeSource)\n\tfor i, vol := range volumes {\n\t\tidxPath := fldPath.Index(i)\n\t\tnamePath := idxPath.Child(\"name\")\n\t\tel := validateVolumeSource(\u0026vol.VolumeSource, idxPath, vol.Name, podMeta, opts)\n\t\tif len(vol.Name) == 0 {\n\t\t\tel = append(el, field.Required(namePath, \"\"))\n\t\t} else {\n\t\t\tel = append(el, ValidateDNS1123Label(vol.Name, namePath)...)\n\t\t}\n\t\tif allNames.Has(vol.Name) {\n\t\t\tel = append(el, field.Duplicate(namePath, vol.Name))\n\t\t}\n\t\tif len(el) == 0 {\n\t\t\tallNames.Insert(vol.Name)\n\t\t\tvols[vol.Name] = vol.VolumeSource\n\t\t} else {\n\t\t\tallErrs = append(allErrs, el...)\n\t\t}\n\t\t// A PersistentVolumeClaimSource should not reference a created PVC. That doesn't\n\t\t// make sense.\n\t\tif vol.PersistentVolumeClaim != nil \u0026\u0026 allCreatedPVCs.Has(vol.PersistentVolumeClaim.ClaimName) {\n\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"persistentVolumeClaim\").Child(\"claimName\"), vol.PersistentVolumeClaim.ClaimName,\n\t\t\t\t\"must not reference a PVC that gets created for an ephemeral volume\"))\n\t\t}\n\t}\n\n\treturn vols, allErrs\n}","line":{"from":387,"to":430}} {"id":100002449,"name":"IsMatchedVolume","signature":"func IsMatchedVolume(name string, volumes map[string]core.VolumeSource) bool","file":"pkg/apis/core/validation/validation.go","code":"func IsMatchedVolume(name string, volumes map[string]core.VolumeSource) bool {\n\tif _, ok := volumes[name]; ok {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":432,"to":437}} {"id":100002450,"name":"isMatchedDevice","signature":"func isMatchedDevice(name string, volumes map[string]core.VolumeSource) (isMatched bool, isPVC bool)","file":"pkg/apis/core/validation/validation.go","code":"// isMatched checks whether the volume with the given name is used by a\n// container and if so, if it involves a PVC.\nfunc isMatchedDevice(name string, volumes map[string]core.VolumeSource) (isMatched bool, isPVC bool) {\n\tif source, ok := volumes[name]; ok {\n\t\tif source.PersistentVolumeClaim != nil ||\n\t\t\tsource.Ephemeral != nil {\n\t\t\treturn true, true\n\t\t}\n\t\treturn true, false\n\t}\n\treturn false, false\n}","line":{"from":439,"to":450}} {"id":100002451,"name":"mountNameAlreadyExists","signature":"func mountNameAlreadyExists(name string, devices map[string]string) bool","file":"pkg/apis/core/validation/validation.go","code":"func mountNameAlreadyExists(name string, devices map[string]string) bool {\n\tif _, ok := devices[name]; ok {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":452,"to":457}} {"id":100002452,"name":"mountPathAlreadyExists","signature":"func mountPathAlreadyExists(mountPath string, devices map[string]string) bool","file":"pkg/apis/core/validation/validation.go","code":"func mountPathAlreadyExists(mountPath string, devices map[string]string) bool {\n\tfor _, devPath := range devices {\n\t\tif mountPath == devPath {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":459,"to":467}} {"id":100002453,"name":"deviceNameAlreadyExists","signature":"func deviceNameAlreadyExists(name string, mounts map[string]string) bool","file":"pkg/apis/core/validation/validation.go","code":"func deviceNameAlreadyExists(name string, mounts map[string]string) bool {\n\tif _, ok := mounts[name]; ok {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":469,"to":474}} {"id":100002454,"name":"devicePathAlreadyExists","signature":"func devicePathAlreadyExists(devicePath string, mounts map[string]string) bool","file":"pkg/apis/core/validation/validation.go","code":"func devicePathAlreadyExists(devicePath string, mounts map[string]string) bool {\n\tfor _, mountPath := range mounts {\n\t\tif mountPath == devicePath {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":476,"to":484}} {"id":100002455,"name":"validateVolumeSource","signature":"func validateVolumeSource(source *core.VolumeSource, fldPath *field.Path, volName string, podMeta *metav1.ObjectMeta, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateVolumeSource(source *core.VolumeSource, fldPath *field.Path, volName string, podMeta *metav1.ObjectMeta, opts PodValidationOptions) field.ErrorList {\n\tnumVolumes := 0\n\tallErrs := field.ErrorList{}\n\tif source.EmptyDir != nil {\n\t\tnumVolumes++\n\t\tif source.EmptyDir.SizeLimit != nil \u0026\u0026 source.EmptyDir.SizeLimit.Cmp(resource.Quantity{}) \u003c 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"emptyDir\").Child(\"sizeLimit\"), \"SizeLimit field must be a valid resource quantity\"))\n\t\t}\n\t}\n\tif source.HostPath != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"hostPath\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateHostPathVolumeSource(source.HostPath, fldPath.Child(\"hostPath\"))...)\n\t\t}\n\t}\n\tif source.GitRepo != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"gitRepo\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateGitRepoVolumeSource(source.GitRepo, fldPath.Child(\"gitRepo\"))...)\n\t\t}\n\t}\n\tif source.GCEPersistentDisk != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"gcePersistentDisk\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateGCEPersistentDiskVolumeSource(source.GCEPersistentDisk, fldPath.Child(\"persistentDisk\"))...)\n\t\t}\n\t}\n\tif source.AWSElasticBlockStore != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"awsElasticBlockStore\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateAWSElasticBlockStoreVolumeSource(source.AWSElasticBlockStore, fldPath.Child(\"awsElasticBlockStore\"))...)\n\t\t}\n\t}\n\tif source.Secret != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"secret\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateSecretVolumeSource(source.Secret, fldPath.Child(\"secret\"))...)\n\t\t}\n\t}\n\tif source.NFS != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"nfs\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateNFSVolumeSource(source.NFS, fldPath.Child(\"nfs\"))...)\n\t\t}\n\t}\n\tif source.ISCSI != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"iscsi\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateISCSIVolumeSource(source.ISCSI, fldPath.Child(\"iscsi\"))...)\n\t\t}\n\t\tif source.ISCSI.InitiatorName != nil \u0026\u0026 len(volName+\":\"+source.ISCSI.TargetPortal) \u003e 64 {\n\t\t\ttooLongErr := \"Total length of \u003cvolume name\u003e:\u003ciscsi.targetPortal\u003e must be under 64 characters if iscsi.initiatorName is specified.\"\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"name\"), volName, tooLongErr))\n\t\t}\n\t}\n\tif source.Glusterfs != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"glusterfs\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateGlusterfsVolumeSource(source.Glusterfs, fldPath.Child(\"glusterfs\"))...)\n\t\t}\n\t}\n\tif source.Flocker != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"flocker\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateFlockerVolumeSource(source.Flocker, fldPath.Child(\"flocker\"))...)\n\t\t}\n\t}\n\tif source.PersistentVolumeClaim != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"persistentVolumeClaim\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validatePersistentClaimVolumeSource(source.PersistentVolumeClaim, fldPath.Child(\"persistentVolumeClaim\"))...)\n\t\t}\n\t}\n\tif source.RBD != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"rbd\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateRBDVolumeSource(source.RBD, fldPath.Child(\"rbd\"))...)\n\t\t}\n\t}\n\tif source.Cinder != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"cinder\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateCinderVolumeSource(source.Cinder, fldPath.Child(\"cinder\"))...)\n\t\t}\n\t}\n\tif source.CephFS != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"cephFS\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateCephFSVolumeSource(source.CephFS, fldPath.Child(\"cephfs\"))...)\n\t\t}\n\t}\n\tif source.Quobyte != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"quobyte\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateQuobyteVolumeSource(source.Quobyte, fldPath.Child(\"quobyte\"))...)\n\t\t}\n\t}\n\tif source.DownwardAPI != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"downwarAPI\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateDownwardAPIVolumeSource(source.DownwardAPI, fldPath.Child(\"downwardAPI\"), opts)...)\n\t\t}\n\t}\n\tif source.FC != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"fc\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateFCVolumeSource(source.FC, fldPath.Child(\"fc\"))...)\n\t\t}\n\t}\n\tif source.FlexVolume != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"flexVolume\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateFlexVolumeSource(source.FlexVolume, fldPath.Child(\"flexVolume\"))...)\n\t\t}\n\t}\n\tif source.ConfigMap != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"configMap\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateConfigMapVolumeSource(source.ConfigMap, fldPath.Child(\"configMap\"))...)\n\t\t}\n\t}\n\n\tif source.AzureFile != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"azureFile\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateAzureFile(source.AzureFile, fldPath.Child(\"azureFile\"))...)\n\t\t}\n\t}\n\n\tif source.VsphereVolume != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"vsphereVolume\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateVsphereVolumeSource(source.VsphereVolume, fldPath.Child(\"vsphereVolume\"))...)\n\t\t}\n\t}\n\tif source.PhotonPersistentDisk != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"photonPersistentDisk\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validatePhotonPersistentDiskVolumeSource(source.PhotonPersistentDisk, fldPath.Child(\"photonPersistentDisk\"))...)\n\t\t}\n\t}\n\tif source.PortworxVolume != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"portworxVolume\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validatePortworxVolumeSource(source.PortworxVolume, fldPath.Child(\"portworxVolume\"))...)\n\t\t}\n\t}\n\tif source.AzureDisk != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"azureDisk\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateAzureDisk(source.AzureDisk, fldPath.Child(\"azureDisk\"))...)\n\t\t}\n\t}\n\tif source.StorageOS != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"storageos\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateStorageOSVolumeSource(source.StorageOS, fldPath.Child(\"storageos\"))...)\n\t\t}\n\t}\n\tif source.Projected != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"projected\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateProjectedVolumeSource(source.Projected, fldPath.Child(\"projected\"), opts)...)\n\t\t}\n\t}\n\tif source.ScaleIO != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"scaleIO\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateScaleIOVolumeSource(source.ScaleIO, fldPath.Child(\"scaleIO\"))...)\n\t\t}\n\t}\n\tif source.CSI != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"csi\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateCSIVolumeSource(source.CSI, fldPath.Child(\"csi\"))...)\n\t\t}\n\t}\n\tif source.Ephemeral != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"ephemeral\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateEphemeralVolumeSource(source.Ephemeral, fldPath.Child(\"ephemeral\"))...)\n\t\t\t// Check the expected name for the PVC. This gets skipped if information is missing,\n\t\t\t// because that already gets flagged as a problem elsewhere. For example,\n\t\t\t// ValidateObjectMeta as called by validatePodMetadataAndSpec checks that the name is set.\n\t\t\tif podMeta != nil \u0026\u0026 podMeta.Name != \"\" \u0026\u0026 volName != \"\" {\n\t\t\t\tpvcName := podMeta.Name + \"-\" + volName\n\t\t\t\tfor _, msg := range ValidatePersistentVolumeName(pvcName, false) {\n\t\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"name\"), volName, fmt.Sprintf(\"PVC name %q: %v\", pvcName, msg)))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif numVolumes == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath, \"must specify a volume type\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":486,"to":740}} {"id":100002456,"name":"validateHostPathVolumeSource","signature":"func validateHostPathVolumeSource(hostPath *core.HostPathVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateHostPathVolumeSource(hostPath *core.HostPathVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(hostPath.Path) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"path\"), \"\"))\n\t\treturn allErrs\n\t}\n\n\tallErrs = append(allErrs, validatePathNoBacksteps(hostPath.Path, fldPath.Child(\"path\"))...)\n\tallErrs = append(allErrs, validateHostPathType(hostPath.Type, fldPath.Child(\"type\"))...)\n\treturn allErrs\n}","line":{"from":742,"to":752}} {"id":100002457,"name":"validateGitRepoVolumeSource","signature":"func validateGitRepoVolumeSource(gitRepo *core.GitRepoVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateGitRepoVolumeSource(gitRepo *core.GitRepoVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(gitRepo.Repository) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"repository\"), \"\"))\n\t}\n\n\tpathErrs := validateLocalDescendingPath(gitRepo.Directory, fldPath.Child(\"directory\"))\n\tallErrs = append(allErrs, pathErrs...)\n\treturn allErrs\n}","line":{"from":754,"to":763}} {"id":100002458,"name":"validateISCSIVolumeSource","signature":"func validateISCSIVolumeSource(iscsi *core.ISCSIVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateISCSIVolumeSource(iscsi *core.ISCSIVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(iscsi.TargetPortal) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"targetPortal\"), \"\"))\n\t}\n\tif len(iscsi.IQN) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"iqn\"), \"\"))\n\t} else {\n\t\tif !strings.HasPrefix(iscsi.IQN, \"iqn\") \u0026\u0026 !strings.HasPrefix(iscsi.IQN, \"eui\") \u0026\u0026 !strings.HasPrefix(iscsi.IQN, \"naa\") {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"iqn\"), iscsi.IQN, \"must be valid format starting with iqn, eui, or naa\"))\n\t\t} else if strings.HasPrefix(iscsi.IQN, \"iqn\") \u0026\u0026 !iscsiInitiatorIqnRegex.MatchString(iscsi.IQN) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"iqn\"), iscsi.IQN, \"must be valid format\"))\n\t\t} else if strings.HasPrefix(iscsi.IQN, \"eui\") \u0026\u0026 !iscsiInitiatorEuiRegex.MatchString(iscsi.IQN) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"iqn\"), iscsi.IQN, \"must be valid format\"))\n\t\t} else if strings.HasPrefix(iscsi.IQN, \"naa\") \u0026\u0026 !iscsiInitiatorNaaRegex.MatchString(iscsi.IQN) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"iqn\"), iscsi.IQN, \"must be valid format\"))\n\t\t}\n\t}\n\tif iscsi.Lun \u003c 0 || iscsi.Lun \u003e 255 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"lun\"), iscsi.Lun, validation.InclusiveRangeError(0, 255)))\n\t}\n\tif (iscsi.DiscoveryCHAPAuth || iscsi.SessionCHAPAuth) \u0026\u0026 iscsi.SecretRef == nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"secretRef\"), \"\"))\n\t}\n\tif iscsi.InitiatorName != nil {\n\t\tinitiator := *iscsi.InitiatorName\n\t\tif !strings.HasPrefix(initiator, \"iqn\") \u0026\u0026 !strings.HasPrefix(initiator, \"eui\") \u0026\u0026 !strings.HasPrefix(initiator, \"naa\") {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"initiatorname\"), initiator, \"must be valid format starting with iqn, eui, or naa\"))\n\t\t}\n\t\tif strings.HasPrefix(initiator, \"iqn\") \u0026\u0026 !iscsiInitiatorIqnRegex.MatchString(initiator) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"initiatorname\"), initiator, \"must be valid format\"))\n\t\t} else if strings.HasPrefix(initiator, \"eui\") \u0026\u0026 !iscsiInitiatorEuiRegex.MatchString(initiator) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"initiatorname\"), initiator, \"must be valid format\"))\n\t\t} else if strings.HasPrefix(initiator, \"naa\") \u0026\u0026 !iscsiInitiatorNaaRegex.MatchString(initiator) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"initiatorname\"), initiator, \"must be valid format\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":765,"to":803}} {"id":100002459,"name":"validateISCSIPersistentVolumeSource","signature":"func validateISCSIPersistentVolumeSource(iscsi *core.ISCSIPersistentVolumeSource, pvName string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateISCSIPersistentVolumeSource(iscsi *core.ISCSIPersistentVolumeSource, pvName string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(iscsi.TargetPortal) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"targetPortal\"), \"\"))\n\t}\n\tif iscsi.InitiatorName != nil \u0026\u0026 len(pvName+\":\"+iscsi.TargetPortal) \u003e 64 {\n\t\ttooLongErr := \"Total length of \u003cvolume name\u003e:\u003ciscsi.targetPortal\u003e must be under 64 characters if iscsi.initiatorName is specified.\"\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"targetportal\"), iscsi.TargetPortal, tooLongErr))\n\t}\n\tif len(iscsi.IQN) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"iqn\"), \"\"))\n\t} else {\n\t\tif !strings.HasPrefix(iscsi.IQN, \"iqn\") \u0026\u0026 !strings.HasPrefix(iscsi.IQN, \"eui\") \u0026\u0026 !strings.HasPrefix(iscsi.IQN, \"naa\") {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"iqn\"), iscsi.IQN, \"must be valid format\"))\n\t\t} else if strings.HasPrefix(iscsi.IQN, \"iqn\") \u0026\u0026 !iscsiInitiatorIqnRegex.MatchString(iscsi.IQN) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"iqn\"), iscsi.IQN, \"must be valid format\"))\n\t\t} else if strings.HasPrefix(iscsi.IQN, \"eui\") \u0026\u0026 !iscsiInitiatorEuiRegex.MatchString(iscsi.IQN) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"iqn\"), iscsi.IQN, \"must be valid format\"))\n\t\t} else if strings.HasPrefix(iscsi.IQN, \"naa\") \u0026\u0026 !iscsiInitiatorNaaRegex.MatchString(iscsi.IQN) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"iqn\"), iscsi.IQN, \"must be valid format\"))\n\t\t}\n\t}\n\tif iscsi.Lun \u003c 0 || iscsi.Lun \u003e 255 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"lun\"), iscsi.Lun, validation.InclusiveRangeError(0, 255)))\n\t}\n\tif (iscsi.DiscoveryCHAPAuth || iscsi.SessionCHAPAuth) \u0026\u0026 iscsi.SecretRef == nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"secretRef\"), \"\"))\n\t}\n\tif iscsi.SecretRef != nil {\n\t\tif len(iscsi.SecretRef.Name) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"secretRef\", \"name\"), \"\"))\n\t\t}\n\t}\n\tif iscsi.InitiatorName != nil {\n\t\tinitiator := *iscsi.InitiatorName\n\t\tif !strings.HasPrefix(initiator, \"iqn\") \u0026\u0026 !strings.HasPrefix(initiator, \"eui\") \u0026\u0026 !strings.HasPrefix(initiator, \"naa\") {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"initiatorname\"), initiator, \"must be valid format\"))\n\t\t}\n\t\tif strings.HasPrefix(initiator, \"iqn\") \u0026\u0026 !iscsiInitiatorIqnRegex.MatchString(initiator) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"initiatorname\"), initiator, \"must be valid format\"))\n\t\t} else if strings.HasPrefix(initiator, \"eui\") \u0026\u0026 !iscsiInitiatorEuiRegex.MatchString(initiator) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"initiatorname\"), initiator, \"must be valid format\"))\n\t\t} else if strings.HasPrefix(initiator, \"naa\") \u0026\u0026 !iscsiInitiatorNaaRegex.MatchString(initiator) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"initiatorname\"), initiator, \"must be valid format\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":805,"to":852}} {"id":100002460,"name":"validateFCVolumeSource","signature":"func validateFCVolumeSource(fc *core.FCVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateFCVolumeSource(fc *core.FCVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(fc.TargetWWNs) \u003c 1 \u0026\u0026 len(fc.WWIDs) \u003c 1 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"targetWWNs\"), \"must specify either targetWWNs or wwids, but not both\"))\n\t}\n\n\tif len(fc.TargetWWNs) != 0 \u0026\u0026 len(fc.WWIDs) != 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"targetWWNs\"), fc.TargetWWNs, \"targetWWNs and wwids can not be specified simultaneously\"))\n\t}\n\n\tif len(fc.TargetWWNs) != 0 {\n\t\tif fc.Lun == nil {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"lun\"), \"lun is required if targetWWNs is specified\"))\n\t\t} else {\n\t\t\tif *fc.Lun \u003c 0 || *fc.Lun \u003e 255 {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"lun\"), fc.Lun, validation.InclusiveRangeError(0, 255)))\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":854,"to":874}} {"id":100002461,"name":"validateGCEPersistentDiskVolumeSource","signature":"func validateGCEPersistentDiskVolumeSource(pd *core.GCEPersistentDiskVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateGCEPersistentDiskVolumeSource(pd *core.GCEPersistentDiskVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(pd.PDName) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"pdName\"), \"\"))\n\t}\n\tif pd.Partition \u003c 0 || pd.Partition \u003e 255 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"partition\"), pd.Partition, pdPartitionErrorMsg))\n\t}\n\treturn allErrs\n}","line":{"from":876,"to":885}} {"id":100002462,"name":"validateAWSElasticBlockStoreVolumeSource","signature":"func validateAWSElasticBlockStoreVolumeSource(PD *core.AWSElasticBlockStoreVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateAWSElasticBlockStoreVolumeSource(PD *core.AWSElasticBlockStoreVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(PD.VolumeID) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"volumeID\"), \"\"))\n\t}\n\tif PD.Partition \u003c 0 || PD.Partition \u003e 255 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"partition\"), PD.Partition, pdPartitionErrorMsg))\n\t}\n\treturn allErrs\n}","line":{"from":887,"to":896}} {"id":100002463,"name":"validateSecretVolumeSource","signature":"func validateSecretVolumeSource(secretSource *core.SecretVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateSecretVolumeSource(secretSource *core.SecretVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(secretSource.SecretName) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"secretName\"), \"\"))\n\t}\n\n\tsecretMode := secretSource.DefaultMode\n\tif secretMode != nil \u0026\u0026 (*secretMode \u003e 0777 || *secretMode \u003c 0) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"defaultMode\"), *secretMode, fileModeErrorMsg))\n\t}\n\n\titemsPath := fldPath.Child(\"items\")\n\tfor i, kp := range secretSource.Items {\n\t\titemPath := itemsPath.Index(i)\n\t\tallErrs = append(allErrs, validateKeyToPath(\u0026kp, itemPath)...)\n\t}\n\treturn allErrs\n}","line":{"from":898,"to":915}} {"id":100002464,"name":"validateConfigMapVolumeSource","signature":"func validateConfigMapVolumeSource(configMapSource *core.ConfigMapVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateConfigMapVolumeSource(configMapSource *core.ConfigMapVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(configMapSource.Name) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"name\"), \"\"))\n\t}\n\n\tconfigMapMode := configMapSource.DefaultMode\n\tif configMapMode != nil \u0026\u0026 (*configMapMode \u003e 0777 || *configMapMode \u003c 0) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"defaultMode\"), *configMapMode, fileModeErrorMsg))\n\t}\n\n\titemsPath := fldPath.Child(\"items\")\n\tfor i, kp := range configMapSource.Items {\n\t\titemPath := itemsPath.Index(i)\n\t\tallErrs = append(allErrs, validateKeyToPath(\u0026kp, itemPath)...)\n\t}\n\treturn allErrs\n}","line":{"from":917,"to":934}} {"id":100002465,"name":"validateKeyToPath","signature":"func validateKeyToPath(kp *core.KeyToPath, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateKeyToPath(kp *core.KeyToPath, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(kp.Key) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"key\"), \"\"))\n\t}\n\tif len(kp.Path) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"path\"), \"\"))\n\t}\n\tallErrs = append(allErrs, validateLocalNonReservedPath(kp.Path, fldPath.Child(\"path\"))...)\n\tif kp.Mode != nil \u0026\u0026 (*kp.Mode \u003e 0777 || *kp.Mode \u003c 0) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"mode\"), *kp.Mode, fileModeErrorMsg))\n\t}\n\n\treturn allErrs\n}","line":{"from":936,"to":950}} {"id":100002466,"name":"validatePersistentClaimVolumeSource","signature":"func validatePersistentClaimVolumeSource(claim *core.PersistentVolumeClaimVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validatePersistentClaimVolumeSource(claim *core.PersistentVolumeClaimVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(claim.ClaimName) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"claimName\"), \"\"))\n\t}\n\treturn allErrs\n}","line":{"from":952,"to":958}} {"id":100002467,"name":"validateNFSVolumeSource","signature":"func validateNFSVolumeSource(nfs *core.NFSVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateNFSVolumeSource(nfs *core.NFSVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(nfs.Server) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"server\"), \"\"))\n\t}\n\tif len(nfs.Path) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"path\"), \"\"))\n\t}\n\tif !path.IsAbs(nfs.Path) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"path\"), nfs.Path, \"must be an absolute path\"))\n\t}\n\treturn allErrs\n}","line":{"from":960,"to":972}} {"id":100002468,"name":"validateQuobyteVolumeSource","signature":"func validateQuobyteVolumeSource(quobyte *core.QuobyteVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateQuobyteVolumeSource(quobyte *core.QuobyteVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(quobyte.Registry) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"registry\"), \"must be a host:port pair or multiple pairs separated by commas\"))\n\t} else if len(quobyte.Tenant) \u003e= 65 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"tenant\"), \"must be a UUID and may not exceed a length of 64 characters\"))\n\t} else {\n\t\tfor _, hostPortPair := range strings.Split(quobyte.Registry, \",\") {\n\t\t\tif _, _, err := net.SplitHostPort(hostPortPair); err != nil {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"registry\"), quobyte.Registry, \"must be a host:port pair or multiple pairs separated by commas\"))\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(quobyte.Volume) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"volume\"), \"\"))\n\t}\n\treturn allErrs\n}","line":{"from":974,"to":992}} {"id":100002469,"name":"validateGlusterfsVolumeSource","signature":"func validateGlusterfsVolumeSource(glusterfs *core.GlusterfsVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateGlusterfsVolumeSource(glusterfs *core.GlusterfsVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(glusterfs.EndpointsName) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"endpoints\"), \"\"))\n\t}\n\tif len(glusterfs.Path) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"path\"), \"\"))\n\t}\n\treturn allErrs\n}","line":{"from":994,"to":1003}} {"id":100002470,"name":"validateGlusterfsPersistentVolumeSource","signature":"func validateGlusterfsPersistentVolumeSource(glusterfs *core.GlusterfsPersistentVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateGlusterfsPersistentVolumeSource(glusterfs *core.GlusterfsPersistentVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(glusterfs.EndpointsName) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"endpoints\"), \"\"))\n\t}\n\tif len(glusterfs.Path) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"path\"), \"\"))\n\t}\n\tif glusterfs.EndpointsNamespace != nil {\n\t\tendpointNs := glusterfs.EndpointsNamespace\n\t\tif *endpointNs == \"\" {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"endpointsNamespace\"), *endpointNs, \"if the endpointnamespace is set, it must be a valid namespace name\"))\n\t\t} else {\n\t\t\tfor _, msg := range ValidateNamespaceName(*endpointNs, false) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"endpointsNamespace\"), *endpointNs, msg))\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":1004,"to":1023}} {"id":100002471,"name":"validateFlockerVolumeSource","signature":"func validateFlockerVolumeSource(flocker *core.FlockerVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateFlockerVolumeSource(flocker *core.FlockerVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(flocker.DatasetName) == 0 \u0026\u0026 len(flocker.DatasetUUID) == 0 {\n\t\t// TODO: consider adding a RequiredOneOf() error for this and similar cases\n\t\tallErrs = append(allErrs, field.Required(fldPath, \"one of datasetName and datasetUUID is required\"))\n\t}\n\tif len(flocker.DatasetName) != 0 \u0026\u0026 len(flocker.DatasetUUID) != 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, \"resource\", \"datasetName and datasetUUID can not be specified simultaneously\"))\n\t}\n\tif strings.Contains(flocker.DatasetName, \"/\") {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"datasetName\"), flocker.DatasetName, \"must not contain '/'\"))\n\t}\n\treturn allErrs\n}","line":{"from":1025,"to":1038}} {"id":100002472,"name":"validateDownwardAPIVolumeFile","signature":"func validateDownwardAPIVolumeFile(file *core.DownwardAPIVolumeFile, fldPath *field.Path, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateDownwardAPIVolumeFile(file *core.DownwardAPIVolumeFile, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(file.Path) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"path\"), \"\"))\n\t}\n\tallErrs = append(allErrs, validateLocalNonReservedPath(file.Path, fldPath.Child(\"path\"))...)\n\tif file.FieldRef != nil {\n\t\tallErrs = append(allErrs, validateObjectFieldSelector(file.FieldRef, \u0026validVolumeDownwardAPIFieldPathExpressions, fldPath.Child(\"fieldRef\"))...)\n\t\tif file.ResourceFieldRef != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, \"resource\", \"fieldRef and resourceFieldRef can not be specified simultaneously\"))\n\t\t}\n\t} else if file.ResourceFieldRef != nil {\n\t\tlocalValidContainerResourceFieldPathPrefixes := validContainerResourceFieldPathPrefixesWithDownwardAPIHugePages\n\t\tallErrs = append(allErrs, validateContainerResourceFieldSelector(file.ResourceFieldRef, \u0026validContainerResourceFieldPathExpressions, \u0026localValidContainerResourceFieldPathPrefixes, fldPath.Child(\"resourceFieldRef\"), true)...)\n\t} else {\n\t\tallErrs = append(allErrs, field.Required(fldPath, \"one of fieldRef and resourceFieldRef is required\"))\n\t}\n\tif file.Mode != nil \u0026\u0026 (*file.Mode \u003e 0777 || *file.Mode \u003c 0) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"mode\"), *file.Mode, fileModeErrorMsg))\n\t}\n\n\treturn allErrs\n}","line":{"from":1047,"to":1069}} {"id":100002473,"name":"validateDownwardAPIVolumeSource","signature":"func validateDownwardAPIVolumeSource(downwardAPIVolume *core.DownwardAPIVolumeSource, fldPath *field.Path, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateDownwardAPIVolumeSource(downwardAPIVolume *core.DownwardAPIVolumeSource, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tdownwardAPIMode := downwardAPIVolume.DefaultMode\n\tif downwardAPIMode != nil \u0026\u0026 (*downwardAPIMode \u003e 0777 || *downwardAPIMode \u003c 0) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"defaultMode\"), *downwardAPIMode, fileModeErrorMsg))\n\t}\n\n\tfor _, file := range downwardAPIVolume.Items {\n\t\tallErrs = append(allErrs, validateDownwardAPIVolumeFile(\u0026file, fldPath, opts)...)\n\t}\n\treturn allErrs\n}","line":{"from":1071,"to":1083}} {"id":100002474,"name":"validateProjectionSources","signature":"func validateProjectionSources(projection *core.ProjectedVolumeSource, projectionMode *int32, fldPath *field.Path, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateProjectionSources(projection *core.ProjectedVolumeSource, projectionMode *int32, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallPaths := sets.String{}\n\n\tfor i, source := range projection.Sources {\n\t\tnumSources := 0\n\t\tsrcPath := fldPath.Child(\"sources\").Index(i)\n\t\tif projPath := srcPath.Child(\"secret\"); source.Secret != nil {\n\t\t\tnumSources++\n\t\t\tif len(source.Secret.Name) == 0 {\n\t\t\t\tallErrs = append(allErrs, field.Required(projPath.Child(\"name\"), \"\"))\n\t\t\t}\n\t\t\titemsPath := projPath.Child(\"items\")\n\t\t\tfor i, kp := range source.Secret.Items {\n\t\t\t\titemPath := itemsPath.Index(i)\n\t\t\t\tallErrs = append(allErrs, validateKeyToPath(\u0026kp, itemPath)...)\n\t\t\t\tif len(kp.Path) \u003e 0 {\n\t\t\t\t\tcurPath := kp.Path\n\t\t\t\t\tif !allPaths.Has(curPath) {\n\t\t\t\t\t\tallPaths.Insert(curPath)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, source.Secret.Name, \"conflicting duplicate paths\"))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif projPath := srcPath.Child(\"configMap\"); source.ConfigMap != nil {\n\t\t\tnumSources++\n\t\t\tif len(source.ConfigMap.Name) == 0 {\n\t\t\t\tallErrs = append(allErrs, field.Required(projPath.Child(\"name\"), \"\"))\n\t\t\t}\n\t\t\titemsPath := projPath.Child(\"items\")\n\t\t\tfor i, kp := range source.ConfigMap.Items {\n\t\t\t\titemPath := itemsPath.Index(i)\n\t\t\t\tallErrs = append(allErrs, validateKeyToPath(\u0026kp, itemPath)...)\n\t\t\t\tif len(kp.Path) \u003e 0 {\n\t\t\t\t\tcurPath := kp.Path\n\t\t\t\t\tif !allPaths.Has(curPath) {\n\t\t\t\t\t\tallPaths.Insert(curPath)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, source.ConfigMap.Name, \"conflicting duplicate paths\"))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif projPath := srcPath.Child(\"downwardAPI\"); source.DownwardAPI != nil {\n\t\t\tnumSources++\n\t\t\tfor _, file := range source.DownwardAPI.Items {\n\t\t\t\tallErrs = append(allErrs, validateDownwardAPIVolumeFile(\u0026file, projPath, opts)...)\n\t\t\t\tif len(file.Path) \u003e 0 {\n\t\t\t\t\tcurPath := file.Path\n\t\t\t\t\tif !allPaths.Has(curPath) {\n\t\t\t\t\t\tallPaths.Insert(curPath)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, curPath, \"conflicting duplicate paths\"))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif projPath := srcPath.Child(\"serviceAccountToken\"); source.ServiceAccountToken != nil {\n\t\t\tnumSources++\n\t\t\tif source.ServiceAccountToken.ExpirationSeconds \u003c 10*60 {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(projPath.Child(\"expirationSeconds\"), source.ServiceAccountToken.ExpirationSeconds, \"may not specify a duration less than 10 minutes\"))\n\t\t\t}\n\t\t\tif source.ServiceAccountToken.ExpirationSeconds \u003e 1\u003c\u003c32 {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(projPath.Child(\"expirationSeconds\"), source.ServiceAccountToken.ExpirationSeconds, \"may not specify a duration larger than 2^32 seconds\"))\n\t\t\t}\n\t\t\tif source.ServiceAccountToken.Path == \"\" {\n\t\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"path\"), \"\"))\n\t\t\t}\n\t\t}\n\t\tif numSources \u003e 1 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(srcPath, \"may not specify more than 1 volume type\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":1085,"to":1161}} {"id":100002475,"name":"validateProjectedVolumeSource","signature":"func validateProjectedVolumeSource(projection *core.ProjectedVolumeSource, fldPath *field.Path, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateProjectedVolumeSource(projection *core.ProjectedVolumeSource, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tprojectionMode := projection.DefaultMode\n\tif projectionMode != nil \u0026\u0026 (*projectionMode \u003e 0777 || *projectionMode \u003c 0) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"defaultMode\"), *projectionMode, fileModeErrorMsg))\n\t}\n\n\tallErrs = append(allErrs, validateProjectionSources(projection, projectionMode, fldPath, opts)...)\n\treturn allErrs\n}","line":{"from":1163,"to":1173}} {"id":100002476,"name":"validateHostPathType","signature":"func validateHostPathType(hostPathType *core.HostPathType, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateHostPathType(hostPathType *core.HostPathType, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif hostPathType != nil \u0026\u0026 !supportedHostPathTypes.Has(string(*hostPathType)) {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath, hostPathType, supportedHostPathTypes.List()))\n\t}\n\n\treturn allErrs\n}","line":{"from":1185,"to":1193}} {"id":100002477,"name":"validateLocalDescendingPath","signature":"func validateLocalDescendingPath(targetPath string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// This validate will make sure targetPath:\n// 1. is not abs path\n// 2. does not have any element which is \"..\"\nfunc validateLocalDescendingPath(targetPath string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif path.IsAbs(targetPath) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, targetPath, \"must be a relative path\"))\n\t}\n\n\tallErrs = append(allErrs, validatePathNoBacksteps(targetPath, fldPath)...)\n\n\treturn allErrs\n}","line":{"from":1195,"to":1207}} {"id":100002478,"name":"validatePathNoBacksteps","signature":"func validatePathNoBacksteps(targetPath string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validatePathNoBacksteps makes sure the targetPath does not have any `..` path elements when split\n//\n// This assumes the OS of the apiserver and the nodes are the same. The same check should be done\n// on the node to ensure there are no backsteps.\nfunc validatePathNoBacksteps(targetPath string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tparts := strings.Split(filepath.ToSlash(targetPath), \"/\")\n\tfor _, item := range parts {\n\t\tif item == \"..\" {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, targetPath, \"must not contain '..'\"))\n\t\t\tbreak // even for `../../..`, one error is sufficient to make the point\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":1209,"to":1223}} {"id":100002479,"name":"validateMountPropagation","signature":"func validateMountPropagation(mountPropagation *core.MountPropagationMode, container *core.Container, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateMountPropagation verifies that MountPropagation field is valid and\n// allowed for given container.\nfunc validateMountPropagation(mountPropagation *core.MountPropagationMode, container *core.Container, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif mountPropagation == nil {\n\t\treturn allErrs\n\t}\n\n\tsupportedMountPropagations := sets.NewString(string(core.MountPropagationBidirectional), string(core.MountPropagationHostToContainer), string(core.MountPropagationNone))\n\tif !supportedMountPropagations.Has(string(*mountPropagation)) {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath, *mountPropagation, supportedMountPropagations.List()))\n\t}\n\n\tif container == nil {\n\t\t// The container is not available yet.\n\t\t// Stop validation now, Pod validation will refuse final\n\t\t// Pods with Bidirectional propagation in non-privileged containers.\n\t\treturn allErrs\n\t}\n\n\tprivileged := container.SecurityContext != nil \u0026\u0026 container.SecurityContext.Privileged != nil \u0026\u0026 *container.SecurityContext.Privileged\n\tif *mountPropagation == core.MountPropagationBidirectional \u0026\u0026 !privileged {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath, \"Bidirectional mount propagation is available only to privileged containers\"))\n\t}\n\treturn allErrs\n}","line":{"from":1225,"to":1251}} {"id":100002480,"name":"validateLocalNonReservedPath","signature":"func validateLocalNonReservedPath(targetPath string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// This validate will make sure targetPath:\n// 1. is not abs path\n// 2. does not contain any '..' elements\n// 3. does not start with '..'\nfunc validateLocalNonReservedPath(targetPath string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, validateLocalDescendingPath(targetPath, fldPath)...)\n\t// Don't report this error if the check for .. elements already caught it.\n\tif strings.HasPrefix(targetPath, \"..\") \u0026\u0026 !strings.HasPrefix(targetPath, \"../\") {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, targetPath, \"must not start with '..'\"))\n\t}\n\treturn allErrs\n}","line":{"from":1253,"to":1265}} {"id":100002481,"name":"validateRBDVolumeSource","signature":"func validateRBDVolumeSource(rbd *core.RBDVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateRBDVolumeSource(rbd *core.RBDVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(rbd.CephMonitors) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"monitors\"), \"\"))\n\t}\n\tif len(rbd.RBDImage) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"image\"), \"\"))\n\t}\n\treturn allErrs\n}","line":{"from":1267,"to":1276}} {"id":100002482,"name":"validateRBDPersistentVolumeSource","signature":"func validateRBDPersistentVolumeSource(rbd *core.RBDPersistentVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateRBDPersistentVolumeSource(rbd *core.RBDPersistentVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(rbd.CephMonitors) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"monitors\"), \"\"))\n\t}\n\tif len(rbd.RBDImage) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"image\"), \"\"))\n\t}\n\treturn allErrs\n}","line":{"from":1278,"to":1287}} {"id":100002483,"name":"validateCinderVolumeSource","signature":"func validateCinderVolumeSource(cd *core.CinderVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateCinderVolumeSource(cd *core.CinderVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(cd.VolumeID) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"volumeID\"), \"\"))\n\t}\n\tif cd.SecretRef != nil {\n\t\tif len(cd.SecretRef.Name) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"secretRef\", \"name\"), \"\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":1289,"to":1300}} {"id":100002484,"name":"validateCinderPersistentVolumeSource","signature":"func validateCinderPersistentVolumeSource(cd *core.CinderPersistentVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateCinderPersistentVolumeSource(cd *core.CinderPersistentVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(cd.VolumeID) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"volumeID\"), \"\"))\n\t}\n\tif cd.SecretRef != nil {\n\t\tif len(cd.SecretRef.Name) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"secretRef\", \"name\"), \"\"))\n\t\t}\n\t\tif len(cd.SecretRef.Namespace) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"secretRef\", \"namespace\"), \"\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":1302,"to":1316}} {"id":100002485,"name":"validateCephFSVolumeSource","signature":"func validateCephFSVolumeSource(cephfs *core.CephFSVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateCephFSVolumeSource(cephfs *core.CephFSVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(cephfs.Monitors) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"monitors\"), \"\"))\n\t}\n\treturn allErrs\n}","line":{"from":1318,"to":1324}} {"id":100002486,"name":"validateCephFSPersistentVolumeSource","signature":"func validateCephFSPersistentVolumeSource(cephfs *core.CephFSPersistentVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateCephFSPersistentVolumeSource(cephfs *core.CephFSPersistentVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(cephfs.Monitors) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"monitors\"), \"\"))\n\t}\n\treturn allErrs\n}","line":{"from":1326,"to":1332}} {"id":100002487,"name":"validateFlexVolumeSource","signature":"func validateFlexVolumeSource(fv *core.FlexVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateFlexVolumeSource(fv *core.FlexVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(fv.Driver) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"driver\"), \"\"))\n\t}\n\n\t// Make sure user-specified options don't use kubernetes namespaces\n\tfor k := range fv.Options {\n\t\tnamespace := k\n\t\tif parts := strings.SplitN(k, \"/\", 2); len(parts) == 2 {\n\t\t\tnamespace = parts[0]\n\t\t}\n\t\tnormalized := \".\" + strings.ToLower(namespace)\n\t\tif strings.HasSuffix(normalized, \".kubernetes.io\") || strings.HasSuffix(normalized, \".k8s.io\") {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"options\").Key(k), k, \"kubernetes.io and k8s.io namespaces are reserved\"))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":1334,"to":1353}} {"id":100002488,"name":"validateFlexPersistentVolumeSource","signature":"func validateFlexPersistentVolumeSource(fv *core.FlexPersistentVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateFlexPersistentVolumeSource(fv *core.FlexPersistentVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(fv.Driver) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"driver\"), \"\"))\n\t}\n\n\t// Make sure user-specified options don't use kubernetes namespaces\n\tfor k := range fv.Options {\n\t\tnamespace := k\n\t\tif parts := strings.SplitN(k, \"/\", 2); len(parts) == 2 {\n\t\t\tnamespace = parts[0]\n\t\t}\n\t\tnormalized := \".\" + strings.ToLower(namespace)\n\t\tif strings.HasSuffix(normalized, \".kubernetes.io\") || strings.HasSuffix(normalized, \".k8s.io\") {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"options\").Key(k), k, \"kubernetes.io and k8s.io namespaces are reserved\"))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":1355,"to":1374}} {"id":100002489,"name":"validateAzureFile","signature":"func validateAzureFile(azure *core.AzureFileVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateAzureFile(azure *core.AzureFileVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif azure.SecretName == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"secretName\"), \"\"))\n\t}\n\tif azure.ShareName == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"shareName\"), \"\"))\n\t}\n\treturn allErrs\n}","line":{"from":1376,"to":1385}} {"id":100002490,"name":"validateAzureFilePV","signature":"func validateAzureFilePV(azure *core.AzureFilePersistentVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateAzureFilePV(azure *core.AzureFilePersistentVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif azure.SecretName == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"secretName\"), \"\"))\n\t}\n\tif azure.ShareName == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"shareName\"), \"\"))\n\t}\n\tif azure.SecretNamespace != nil {\n\t\tif len(*azure.SecretNamespace) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"secretNamespace\"), \"\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":1387,"to":1401}} {"id":100002491,"name":"validateAzureDisk","signature":"func validateAzureDisk(azure *core.AzureDiskVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateAzureDisk(azure *core.AzureDiskVolumeSource, fldPath *field.Path) field.ErrorList {\n\tvar supportedCachingModes = sets.NewString(string(core.AzureDataDiskCachingNone), string(core.AzureDataDiskCachingReadOnly), string(core.AzureDataDiskCachingReadWrite))\n\tvar supportedDiskKinds = sets.NewString(string(core.AzureSharedBlobDisk), string(core.AzureDedicatedBlobDisk), string(core.AzureManagedDisk))\n\n\tdiskURISupportedManaged := []string{\"/subscriptions/{sub-id}/resourcegroups/{group-name}/providers/microsoft.compute/disks/{disk-id}\"}\n\tdiskURISupportedblob := []string{\"https://{account-name}.blob.core.windows.net/{container-name}/{disk-name}.vhd\"}\n\n\tallErrs := field.ErrorList{}\n\tif azure.DiskName == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"diskName\"), \"\"))\n\t}\n\n\tif azure.DataDiskURI == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"diskURI\"), \"\"))\n\t}\n\n\tif azure.CachingMode != nil \u0026\u0026 !supportedCachingModes.Has(string(*azure.CachingMode)) {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"cachingMode\"), *azure.CachingMode, supportedCachingModes.List()))\n\t}\n\n\tif azure.Kind != nil \u0026\u0026 !supportedDiskKinds.Has(string(*azure.Kind)) {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"kind\"), *azure.Kind, supportedDiskKinds.List()))\n\t}\n\n\t// validate that DiskUri is the correct format\n\tif azure.Kind != nil \u0026\u0026 *azure.Kind == core.AzureManagedDisk \u0026\u0026 strings.Index(azure.DataDiskURI, \"/subscriptions/\") != 0 {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"diskURI\"), azure.DataDiskURI, diskURISupportedManaged))\n\t}\n\n\tif azure.Kind != nil \u0026\u0026 *azure.Kind != core.AzureManagedDisk \u0026\u0026 strings.Index(azure.DataDiskURI, \"https://\") != 0 {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"diskURI\"), azure.DataDiskURI, diskURISupportedblob))\n\t}\n\n\treturn allErrs\n}","line":{"from":1403,"to":1437}} {"id":100002492,"name":"validateVsphereVolumeSource","signature":"func validateVsphereVolumeSource(cd *core.VsphereVirtualDiskVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateVsphereVolumeSource(cd *core.VsphereVirtualDiskVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(cd.VolumePath) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"volumePath\"), \"\"))\n\t}\n\treturn allErrs\n}","line":{"from":1439,"to":1445}} {"id":100002493,"name":"validatePhotonPersistentDiskVolumeSource","signature":"func validatePhotonPersistentDiskVolumeSource(cd *core.PhotonPersistentDiskVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validatePhotonPersistentDiskVolumeSource(cd *core.PhotonPersistentDiskVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(cd.PdID) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"pdID\"), \"\"))\n\t}\n\treturn allErrs\n}","line":{"from":1447,"to":1453}} {"id":100002494,"name":"validatePortworxVolumeSource","signature":"func validatePortworxVolumeSource(pwx *core.PortworxVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validatePortworxVolumeSource(pwx *core.PortworxVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(pwx.VolumeID) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"volumeID\"), \"\"))\n\t}\n\treturn allErrs\n}","line":{"from":1455,"to":1461}} {"id":100002495,"name":"validateScaleIOVolumeSource","signature":"func validateScaleIOVolumeSource(sio *core.ScaleIOVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateScaleIOVolumeSource(sio *core.ScaleIOVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif sio.Gateway == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"gateway\"), \"\"))\n\t}\n\tif sio.System == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"system\"), \"\"))\n\t}\n\tif sio.VolumeName == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"volumeName\"), \"\"))\n\t}\n\treturn allErrs\n}","line":{"from":1463,"to":1475}} {"id":100002496,"name":"validateScaleIOPersistentVolumeSource","signature":"func validateScaleIOPersistentVolumeSource(sio *core.ScaleIOPersistentVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateScaleIOPersistentVolumeSource(sio *core.ScaleIOPersistentVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif sio.Gateway == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"gateway\"), \"\"))\n\t}\n\tif sio.System == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"system\"), \"\"))\n\t}\n\tif sio.VolumeName == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"volumeName\"), \"\"))\n\t}\n\treturn allErrs\n}","line":{"from":1477,"to":1489}} {"id":100002497,"name":"validateLocalVolumeSource","signature":"func validateLocalVolumeSource(ls *core.LocalVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateLocalVolumeSource(ls *core.LocalVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif ls.Path == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"path\"), \"\"))\n\t\treturn allErrs\n\t}\n\n\tallErrs = append(allErrs, validatePathNoBacksteps(ls.Path, fldPath.Child(\"path\"))...)\n\treturn allErrs\n}","line":{"from":1491,"to":1500}} {"id":100002498,"name":"validateStorageOSVolumeSource","signature":"func validateStorageOSVolumeSource(storageos *core.StorageOSVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateStorageOSVolumeSource(storageos *core.StorageOSVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(storageos.VolumeName) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"volumeName\"), \"\"))\n\t} else {\n\t\tallErrs = append(allErrs, ValidateDNS1123Label(storageos.VolumeName, fldPath.Child(\"volumeName\"))...)\n\t}\n\tif len(storageos.VolumeNamespace) \u003e 0 {\n\t\tallErrs = append(allErrs, ValidateDNS1123Label(storageos.VolumeNamespace, fldPath.Child(\"volumeNamespace\"))...)\n\t}\n\tif storageos.SecretRef != nil {\n\t\tif len(storageos.SecretRef.Name) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"secretRef\", \"name\"), \"\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":1502,"to":1518}} {"id":100002499,"name":"validateStorageOSPersistentVolumeSource","signature":"func validateStorageOSPersistentVolumeSource(storageos *core.StorageOSPersistentVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateStorageOSPersistentVolumeSource(storageos *core.StorageOSPersistentVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(storageos.VolumeName) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"volumeName\"), \"\"))\n\t} else {\n\t\tallErrs = append(allErrs, ValidateDNS1123Label(storageos.VolumeName, fldPath.Child(\"volumeName\"))...)\n\t}\n\tif len(storageos.VolumeNamespace) \u003e 0 {\n\t\tallErrs = append(allErrs, ValidateDNS1123Label(storageos.VolumeNamespace, fldPath.Child(\"volumeNamespace\"))...)\n\t}\n\tif storageos.SecretRef != nil {\n\t\tif len(storageos.SecretRef.Name) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"secretRef\", \"name\"), \"\"))\n\t\t}\n\t\tif len(storageos.SecretRef.Namespace) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"secretRef\", \"namespace\"), \"\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":1520,"to":1539}} {"id":100002500,"name":"validatePVSecretReference","signature":"func validatePVSecretReference(secretRef *core.SecretReference, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validatePVSecretReference(secretRef *core.SecretReference, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tif len(secretRef.Name) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"name\"), \"\"))\n\t} else {\n\t\tallErrs = append(allErrs, ValidateDNS1123Subdomain(secretRef.Name, fldPath.Child(\"name\"))...)\n\t}\n\n\tif len(secretRef.Namespace) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"namespace\"), \"\"))\n\t} else {\n\t\tallErrs = append(allErrs, ValidateDNS1123Label(secretRef.Namespace, fldPath.Child(\"namespace\"))...)\n\t}\n\treturn allErrs\n}","line":{"from":1543,"to":1557}} {"id":100002501,"name":"ValidateCSIDriverName","signature":"func ValidateCSIDriverName(driverName string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func ValidateCSIDriverName(driverName string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(driverName) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath, \"\"))\n\t}\n\n\tif len(driverName) \u003e 63 {\n\t\tallErrs = append(allErrs, field.TooLong(fldPath, driverName, 63))\n\t}\n\n\tfor _, msg := range validation.IsDNS1123Subdomain(strings.ToLower(driverName)) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, driverName, msg))\n\t}\n\n\treturn allErrs\n}","line":{"from":1559,"to":1575}} {"id":100002502,"name":"validateCSIPersistentVolumeSource","signature":"func validateCSIPersistentVolumeSource(csi *core.CSIPersistentVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateCSIPersistentVolumeSource(csi *core.CSIPersistentVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tallErrs = append(allErrs, ValidateCSIDriverName(csi.Driver, fldPath.Child(\"driver\"))...)\n\n\tif len(csi.VolumeHandle) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"volumeHandle\"), \"\"))\n\t}\n\tif csi.ControllerPublishSecretRef != nil {\n\t\tallErrs = append(allErrs, validatePVSecretReference(csi.ControllerPublishSecretRef, fldPath.Child(\"controllerPublishSecretRef\"))...)\n\t}\n\tif csi.ControllerExpandSecretRef != nil {\n\t\tallErrs = append(allErrs, validatePVSecretReference(csi.ControllerExpandSecretRef, fldPath.Child(\"controllerExpandSecretRef\"))...)\n\t}\n\tif csi.NodePublishSecretRef != nil {\n\t\tallErrs = append(allErrs, validatePVSecretReference(csi.NodePublishSecretRef, fldPath.Child(\"nodePublishSecretRef\"))...)\n\t}\n\tif csi.NodeExpandSecretRef != nil {\n\t\tallErrs = append(allErrs, validatePVSecretReference(csi.NodeExpandSecretRef, fldPath.Child(\"nodeExpandSecretRef\"))...)\n\t}\n\treturn allErrs\n}","line":{"from":1577,"to":1598}} {"id":100002503,"name":"validateCSIVolumeSource","signature":"func validateCSIVolumeSource(csi *core.CSIVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateCSIVolumeSource(csi *core.CSIVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, ValidateCSIDriverName(csi.Driver, fldPath.Child(\"driver\"))...)\n\n\tif csi.NodePublishSecretRef != nil {\n\t\tif len(csi.NodePublishSecretRef.Name) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"nodePublishSecretRef\", \"name\"), \"\"))\n\t\t} else {\n\t\t\tfor _, msg := range ValidateSecretName(csi.NodePublishSecretRef.Name, false) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"name\"), csi.NodePublishSecretRef.Name, msg))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":1600,"to":1615}} {"id":100002504,"name":"validateEphemeralVolumeSource","signature":"func validateEphemeralVolumeSource(ephemeral *core.EphemeralVolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateEphemeralVolumeSource(ephemeral *core.EphemeralVolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif ephemeral.VolumeClaimTemplate == nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"volumeClaimTemplate\"), \"\"))\n\t} else {\n\t\topts := ValidationOptionsForPersistentVolumeClaimTemplate(ephemeral.VolumeClaimTemplate, nil)\n\t\tallErrs = append(allErrs, ValidatePersistentVolumeClaimTemplate(ephemeral.VolumeClaimTemplate, fldPath.Child(\"volumeClaimTemplate\"), opts)...)\n\t}\n\treturn allErrs\n}","line":{"from":1617,"to":1626}} {"id":100002505,"name":"ValidatePersistentVolumeClaimTemplate","signature":"func ValidatePersistentVolumeClaimTemplate(claimTemplate *core.PersistentVolumeClaimTemplate, fldPath *field.Path, opts PersistentVolumeClaimSpecValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidatePersistentVolumeClaimTemplate verifies that the embedded object meta and spec are valid.\n// Checking of the object data is very minimal because only labels and annotations are used.\nfunc ValidatePersistentVolumeClaimTemplate(claimTemplate *core.PersistentVolumeClaimTemplate, fldPath *field.Path, opts PersistentVolumeClaimSpecValidationOptions) field.ErrorList {\n\tallErrs := ValidateTemplateObjectMeta(\u0026claimTemplate.ObjectMeta, fldPath.Child(\"metadata\"))\n\tallErrs = append(allErrs, ValidatePersistentVolumeClaimSpec(\u0026claimTemplate.Spec, fldPath.Child(\"spec\"), opts)...)\n\treturn allErrs\n}","line":{"from":1628,"to":1634}} {"id":100002506,"name":"ValidateTemplateObjectMeta","signature":"func ValidateTemplateObjectMeta(objMeta *metav1.ObjectMeta, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func ValidateTemplateObjectMeta(objMeta *metav1.ObjectMeta, fldPath *field.Path) field.ErrorList {\n\tallErrs := apimachineryvalidation.ValidateAnnotations(objMeta.Annotations, fldPath.Child(\"annotations\"))\n\tallErrs = append(allErrs, unversionedvalidation.ValidateLabels(objMeta.Labels, fldPath.Child(\"labels\"))...)\n\t// All other fields are not supported and thus must not be set\n\t// to avoid confusion. We could reject individual fields,\n\t// but then adding a new one to ObjectMeta wouldn't be checked\n\t// unless this code gets updated. Instead, we ensure that\n\t// only allowed fields are set via reflection.\n\tallErrs = append(allErrs, validateFieldAllowList(*objMeta, allowedTemplateObjectMetaFields, \"cannot be set\", fldPath)...)\n\treturn allErrs\n}","line":{"from":1636,"to":1646}} {"id":100002507,"name":"ValidationOptionsForPersistentVolume","signature":"func ValidationOptionsForPersistentVolume(pv, oldPv *core.PersistentVolume) PersistentVolumeSpecValidationOptions","file":"pkg/apis/core/validation/validation.go","code":"func ValidationOptionsForPersistentVolume(pv, oldPv *core.PersistentVolume) PersistentVolumeSpecValidationOptions {\n\topts := PersistentVolumeSpecValidationOptions{\n\t\tAllowReadWriteOncePod: utilfeature.DefaultFeatureGate.Enabled(features.ReadWriteOncePod),\n\t}\n\tif oldPv == nil {\n\t\t// If there's no old PV, use the options based solely on feature enablement\n\t\treturn opts\n\t}\n\tif helper.ContainsAccessMode(oldPv.Spec.AccessModes, core.ReadWriteOncePod) {\n\t\t// If the old object allowed \"ReadWriteOncePod\", continue to allow it in the new object\n\t\topts.AllowReadWriteOncePod = true\n\t}\n\treturn opts\n}","line":{"from":1669,"to":1682}} {"id":100002508,"name":"ValidatePersistentVolumeSpec","signature":"func ValidatePersistentVolumeSpec(pvSpec *core.PersistentVolumeSpec, pvName string, validateInlinePersistentVolumeSpec bool, fldPath *field.Path, opts PersistentVolumeSpecValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func ValidatePersistentVolumeSpec(pvSpec *core.PersistentVolumeSpec, pvName string, validateInlinePersistentVolumeSpec bool, fldPath *field.Path, opts PersistentVolumeSpecValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif validateInlinePersistentVolumeSpec {\n\t\tif pvSpec.ClaimRef != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"claimRef\"), \"may not be specified in the context of inline volumes\"))\n\t\t}\n\t\tif len(pvSpec.Capacity) != 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"capacity\"), \"may not be specified in the context of inline volumes\"))\n\t\t}\n\t\tif pvSpec.CSI == nil {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"csi\"), \"has to be specified in the context of inline volumes\"))\n\t\t}\n\t}\n\n\tif len(pvSpec.AccessModes) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"accessModes\"), \"\"))\n\t}\n\n\texpandedSupportedAccessModes := sets.StringKeySet(supportedAccessModes)\n\tif opts.AllowReadWriteOncePod {\n\t\texpandedSupportedAccessModes.Insert(string(core.ReadWriteOncePod))\n\t}\n\n\tfoundReadWriteOncePod, foundNonReadWriteOncePod := false, false\n\tfor _, mode := range pvSpec.AccessModes {\n\t\tif !expandedSupportedAccessModes.Has(string(mode)) {\n\t\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"accessModes\"), mode, expandedSupportedAccessModes.List()))\n\t\t}\n\n\t\tif mode == core.ReadWriteOncePod {\n\t\t\tfoundReadWriteOncePod = true\n\t\t} else if supportedAccessModes.Has(string(mode)) {\n\t\t\tfoundNonReadWriteOncePod = true\n\t\t}\n\t}\n\tif foundReadWriteOncePod \u0026\u0026 foundNonReadWriteOncePod {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"accessModes\"), \"may not use ReadWriteOncePod with other access modes\"))\n\t}\n\n\tif !validateInlinePersistentVolumeSpec {\n\t\tif len(pvSpec.Capacity) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"capacity\"), \"\"))\n\t\t}\n\n\t\tif _, ok := pvSpec.Capacity[core.ResourceStorage]; !ok || len(pvSpec.Capacity) \u003e 1 {\n\t\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"capacity\"), pvSpec.Capacity, []string{string(core.ResourceStorage)}))\n\t\t}\n\t\tcapPath := fldPath.Child(\"capacity\")\n\t\tfor r, qty := range pvSpec.Capacity {\n\t\t\tallErrs = append(allErrs, validateBasicResource(qty, capPath.Key(string(r)))...)\n\t\t\tallErrs = append(allErrs, ValidatePositiveQuantityValue(qty, capPath.Key(string(r)))...)\n\t\t}\n\t}\n\n\tif len(string(pvSpec.PersistentVolumeReclaimPolicy)) \u003e 0 {\n\t\tif validateInlinePersistentVolumeSpec {\n\t\t\tif pvSpec.PersistentVolumeReclaimPolicy != core.PersistentVolumeReclaimRetain {\n\t\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"persistentVolumeReclaimPolicy\"), \"may only be \"+string(core.PersistentVolumeReclaimRetain)+\" in the context of inline volumes\"))\n\t\t\t}\n\t\t} else {\n\t\t\tif !supportedReclaimPolicy.Has(string(pvSpec.PersistentVolumeReclaimPolicy)) {\n\t\t\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"persistentVolumeReclaimPolicy\"), pvSpec.PersistentVolumeReclaimPolicy, supportedReclaimPolicy.List()))\n\t\t\t}\n\t\t}\n\t}\n\n\tvar nodeAffinitySpecified bool\n\tvar errs field.ErrorList\n\tif pvSpec.NodeAffinity != nil {\n\t\tif validateInlinePersistentVolumeSpec {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"nodeAffinity\"), \"may not be specified in the context of inline volumes\"))\n\t\t} else {\n\t\t\tnodeAffinitySpecified, errs = validateVolumeNodeAffinity(pvSpec.NodeAffinity, fldPath.Child(\"nodeAffinity\"))\n\t\t\tallErrs = append(allErrs, errs...)\n\t\t}\n\t}\n\tnumVolumes := 0\n\tif pvSpec.HostPath != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"hostPath\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateHostPathVolumeSource(pvSpec.HostPath, fldPath.Child(\"hostPath\"))...)\n\t\t}\n\t}\n\tif pvSpec.GCEPersistentDisk != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"gcePersistentDisk\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateGCEPersistentDiskVolumeSource(pvSpec.GCEPersistentDisk, fldPath.Child(\"persistentDisk\"))...)\n\t\t}\n\t}\n\tif pvSpec.AWSElasticBlockStore != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"awsElasticBlockStore\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateAWSElasticBlockStoreVolumeSource(pvSpec.AWSElasticBlockStore, fldPath.Child(\"awsElasticBlockStore\"))...)\n\t\t}\n\t}\n\tif pvSpec.Glusterfs != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"glusterfs\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateGlusterfsPersistentVolumeSource(pvSpec.Glusterfs, fldPath.Child(\"glusterfs\"))...)\n\t\t}\n\t}\n\tif pvSpec.Flocker != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"flocker\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateFlockerVolumeSource(pvSpec.Flocker, fldPath.Child(\"flocker\"))...)\n\t\t}\n\t}\n\tif pvSpec.NFS != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"nfs\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateNFSVolumeSource(pvSpec.NFS, fldPath.Child(\"nfs\"))...)\n\t\t}\n\t}\n\tif pvSpec.RBD != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"rbd\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateRBDPersistentVolumeSource(pvSpec.RBD, fldPath.Child(\"rbd\"))...)\n\t\t}\n\t}\n\tif pvSpec.Quobyte != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"quobyte\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateQuobyteVolumeSource(pvSpec.Quobyte, fldPath.Child(\"quobyte\"))...)\n\t\t}\n\t}\n\tif pvSpec.CephFS != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"cephFS\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateCephFSPersistentVolumeSource(pvSpec.CephFS, fldPath.Child(\"cephfs\"))...)\n\t\t}\n\t}\n\tif pvSpec.ISCSI != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"iscsi\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateISCSIPersistentVolumeSource(pvSpec.ISCSI, pvName, fldPath.Child(\"iscsi\"))...)\n\t\t}\n\t}\n\tif pvSpec.Cinder != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"cinder\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateCinderPersistentVolumeSource(pvSpec.Cinder, fldPath.Child(\"cinder\"))...)\n\t\t}\n\t}\n\tif pvSpec.FC != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"fc\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateFCVolumeSource(pvSpec.FC, fldPath.Child(\"fc\"))...)\n\t\t}\n\t}\n\tif pvSpec.FlexVolume != nil {\n\t\tnumVolumes++\n\t\tallErrs = append(allErrs, validateFlexPersistentVolumeSource(pvSpec.FlexVolume, fldPath.Child(\"flexVolume\"))...)\n\t}\n\tif pvSpec.AzureFile != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"azureFile\"), \"may not specify more than 1 volume type\"))\n\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateAzureFilePV(pvSpec.AzureFile, fldPath.Child(\"azureFile\"))...)\n\t\t}\n\t}\n\n\tif pvSpec.VsphereVolume != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"vsphereVolume\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateVsphereVolumeSource(pvSpec.VsphereVolume, fldPath.Child(\"vsphereVolume\"))...)\n\t\t}\n\t}\n\tif pvSpec.PhotonPersistentDisk != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"photonPersistentDisk\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validatePhotonPersistentDiskVolumeSource(pvSpec.PhotonPersistentDisk, fldPath.Child(\"photonPersistentDisk\"))...)\n\t\t}\n\t}\n\tif pvSpec.PortworxVolume != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"portworxVolume\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validatePortworxVolumeSource(pvSpec.PortworxVolume, fldPath.Child(\"portworxVolume\"))...)\n\t\t}\n\t}\n\tif pvSpec.AzureDisk != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"azureDisk\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateAzureDisk(pvSpec.AzureDisk, fldPath.Child(\"azureDisk\"))...)\n\t\t}\n\t}\n\tif pvSpec.ScaleIO != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"scaleIO\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateScaleIOPersistentVolumeSource(pvSpec.ScaleIO, fldPath.Child(\"scaleIO\"))...)\n\t\t}\n\t}\n\tif pvSpec.Local != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"local\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateLocalVolumeSource(pvSpec.Local, fldPath.Child(\"local\"))...)\n\t\t\t// NodeAffinity is required\n\t\t\tif !nodeAffinitySpecified {\n\t\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"nodeAffinity\"), \"Local volume requires node affinity\"))\n\t\t\t}\n\t\t}\n\t}\n\tif pvSpec.StorageOS != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"storageos\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateStorageOSPersistentVolumeSource(pvSpec.StorageOS, fldPath.Child(\"storageos\"))...)\n\t\t}\n\t}\n\n\tif pvSpec.CSI != nil {\n\t\tif numVolumes \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"csi\"), \"may not specify more than 1 volume type\"))\n\t\t} else {\n\t\t\tnumVolumes++\n\t\t\tallErrs = append(allErrs, validateCSIPersistentVolumeSource(pvSpec.CSI, fldPath.Child(\"csi\"))...)\n\t\t}\n\t}\n\n\tif numVolumes == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath, \"must specify a volume type\"))\n\t}\n\n\t// do not allow hostPath mounts of '/' to have a 'recycle' reclaim policy\n\tif pvSpec.HostPath != nil \u0026\u0026 path.Clean(pvSpec.HostPath.Path) == \"/\" \u0026\u0026 pvSpec.PersistentVolumeReclaimPolicy == core.PersistentVolumeReclaimRecycle {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"persistentVolumeReclaimPolicy\"), \"may not be 'recycle' for a hostPath mount of '/'\"))\n\t}\n\n\tif len(pvSpec.StorageClassName) \u003e 0 {\n\t\tif validateInlinePersistentVolumeSpec {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"storageClassName\"), \"may not be specified in the context of inline volumes\"))\n\t\t} else {\n\t\t\tfor _, msg := range ValidateClassName(pvSpec.StorageClassName, false) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"storageClassName\"), pvSpec.StorageClassName, msg))\n\t\t\t}\n\t\t}\n\t}\n\tif pvSpec.VolumeMode != nil {\n\t\tif validateInlinePersistentVolumeSpec {\n\t\t\tif *pvSpec.VolumeMode != core.PersistentVolumeFilesystem {\n\t\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"volumeMode\"), \"may not specify volumeMode other than \"+string(core.PersistentVolumeFilesystem)+\" in the context of inline volumes\"))\n\t\t\t}\n\t\t} else {\n\t\t\tif !supportedVolumeModes.Has(string(*pvSpec.VolumeMode)) {\n\t\t\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"volumeMode\"), *pvSpec.VolumeMode, supportedVolumeModes.List()))\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":1684,"to":1972}} {"id":100002509,"name":"ValidatePersistentVolume","signature":"func ValidatePersistentVolume(pv *core.PersistentVolume, opts PersistentVolumeSpecValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func ValidatePersistentVolume(pv *core.PersistentVolume, opts PersistentVolumeSpecValidationOptions) field.ErrorList {\n\tmetaPath := field.NewPath(\"metadata\")\n\tallErrs := ValidateObjectMeta(\u0026pv.ObjectMeta, false, ValidatePersistentVolumeName, metaPath)\n\tallErrs = append(allErrs, ValidatePersistentVolumeSpec(\u0026pv.Spec, pv.ObjectMeta.Name, false, field.NewPath(\"spec\"), opts)...)\n\treturn allErrs\n}","line":{"from":1974,"to":1979}} {"id":100002510,"name":"ValidatePersistentVolumeUpdate","signature":"func ValidatePersistentVolumeUpdate(newPv, oldPv *core.PersistentVolume, opts PersistentVolumeSpecValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidatePersistentVolumeUpdate tests to see if the update is legal for an end user to make.\n// newPv is updated with fields that cannot be changed.\nfunc ValidatePersistentVolumeUpdate(newPv, oldPv *core.PersistentVolume, opts PersistentVolumeSpecValidationOptions) field.ErrorList {\n\tallErrs := ValidatePersistentVolume(newPv, opts)\n\n\t// if oldPV does not have ControllerExpandSecretRef then allow it to be set\n\tif (oldPv.Spec.CSI != nil \u0026\u0026 oldPv.Spec.CSI.ControllerExpandSecretRef == nil) \u0026\u0026\n\t\t(newPv.Spec.CSI != nil \u0026\u0026 newPv.Spec.CSI.ControllerExpandSecretRef != nil) {\n\t\tnewPv = newPv.DeepCopy()\n\t\tnewPv.Spec.CSI.ControllerExpandSecretRef = nil\n\t}\n\n\t// PersistentVolumeSource should be immutable after creation.\n\tif !apiequality.Semantic.DeepEqual(newPv.Spec.PersistentVolumeSource, oldPv.Spec.PersistentVolumeSource) {\n\t\tpvcSourceDiff := cmp.Diff(oldPv.Spec.PersistentVolumeSource, newPv.Spec.PersistentVolumeSource)\n\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"spec\", \"persistentvolumesource\"), fmt.Sprintf(\"spec.persistentvolumesource is immutable after creation\\n%v\", pvcSourceDiff)))\n\t}\n\tallErrs = append(allErrs, ValidateImmutableField(newPv.Spec.VolumeMode, oldPv.Spec.VolumeMode, field.NewPath(\"volumeMode\"))...)\n\n\t// Allow setting NodeAffinity if oldPv NodeAffinity was not set\n\tif oldPv.Spec.NodeAffinity != nil {\n\t\tallErrs = append(allErrs, validatePvNodeAffinity(newPv.Spec.NodeAffinity, oldPv.Spec.NodeAffinity, field.NewPath(\"nodeAffinity\"))...)\n\t}\n\n\treturn allErrs\n}","line":{"from":1981,"to":2006}} {"id":100002511,"name":"ValidatePersistentVolumeStatusUpdate","signature":"func ValidatePersistentVolumeStatusUpdate(newPv, oldPv *core.PersistentVolume) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidatePersistentVolumeStatusUpdate tests to see if the status update is legal for an end user to make.\nfunc ValidatePersistentVolumeStatusUpdate(newPv, oldPv *core.PersistentVolume) field.ErrorList {\n\tallErrs := ValidateObjectMetaUpdate(\u0026newPv.ObjectMeta, \u0026oldPv.ObjectMeta, field.NewPath(\"metadata\"))\n\tif len(newPv.ResourceVersion) == 0 {\n\t\tallErrs = append(allErrs, field.Required(field.NewPath(\"resourceVersion\"), \"\"))\n\t}\n\treturn allErrs\n}","line":{"from":2008,"to":2015}} {"id":100002512,"name":"ValidationOptionsForPersistentVolumeClaim","signature":"func ValidationOptionsForPersistentVolumeClaim(pvc, oldPvc *core.PersistentVolumeClaim) PersistentVolumeClaimSpecValidationOptions","file":"pkg/apis/core/validation/validation.go","code":"func ValidationOptionsForPersistentVolumeClaim(pvc, oldPvc *core.PersistentVolumeClaim) PersistentVolumeClaimSpecValidationOptions {\n\topts := PersistentVolumeClaimSpecValidationOptions{\n\t\tAllowReadWriteOncePod: utilfeature.DefaultFeatureGate.Enabled(features.ReadWriteOncePod),\n\t\tEnableRecoverFromExpansionFailure: utilfeature.DefaultFeatureGate.Enabled(features.RecoverVolumeExpansionFailure),\n\t\tEnableRetroactiveDefaultStorageClass: utilfeature.DefaultFeatureGate.Enabled(features.RetroactiveDefaultStorageClass),\n\t\tAllowInvalidLabelValueInSelector: false,\n\t}\n\tif oldPvc == nil {\n\t\t// If there's no old PVC, use the options based solely on feature enablement\n\t\treturn opts\n\t}\n\tlabelSelectorValidationOpts := unversionedvalidation.LabelSelectorValidationOptions{\n\t\tAllowInvalidLabelValueInSelector: opts.AllowInvalidLabelValueInSelector,\n\t}\n\tif len(unversionedvalidation.ValidateLabelSelector(oldPvc.Spec.Selector, labelSelectorValidationOpts, nil)) \u003e 0 {\n\t\t// If the old object had an invalid label selector, continue to allow it in the new object\n\t\topts.AllowInvalidLabelValueInSelector = true\n\t}\n\n\tif helper.ContainsAccessMode(oldPvc.Spec.AccessModes, core.ReadWriteOncePod) {\n\t\t// If the old object allowed \"ReadWriteOncePod\", continue to allow it in the new object\n\t\topts.AllowReadWriteOncePod = true\n\t}\n\treturn opts\n}","line":{"from":2028,"to":2052}} {"id":100002513,"name":"ValidationOptionsForPersistentVolumeClaimTemplate","signature":"func ValidationOptionsForPersistentVolumeClaimTemplate(claimTemplate, oldClaimTemplate *core.PersistentVolumeClaimTemplate) PersistentVolumeClaimSpecValidationOptions","file":"pkg/apis/core/validation/validation.go","code":"func ValidationOptionsForPersistentVolumeClaimTemplate(claimTemplate, oldClaimTemplate *core.PersistentVolumeClaimTemplate) PersistentVolumeClaimSpecValidationOptions {\n\topts := PersistentVolumeClaimSpecValidationOptions{\n\t\tAllowReadWriteOncePod: utilfeature.DefaultFeatureGate.Enabled(features.ReadWriteOncePod),\n\t\tAllowInvalidLabelValueInSelector: false,\n\t}\n\tif oldClaimTemplate == nil {\n\t\t// If there's no old PVC template, use the options based solely on feature enablement\n\t\treturn opts\n\t}\n\tlabelSelectorValidationOpts := unversionedvalidation.LabelSelectorValidationOptions{\n\t\tAllowInvalidLabelValueInSelector: opts.AllowInvalidLabelValueInSelector,\n\t}\n\tif len(unversionedvalidation.ValidateLabelSelector(oldClaimTemplate.Spec.Selector, labelSelectorValidationOpts, nil)) \u003e 0 {\n\t\t// If the old object had an invalid label selector, continue to allow it in the new object\n\t\topts.AllowInvalidLabelValueInSelector = true\n\t}\n\tif helper.ContainsAccessMode(oldClaimTemplate.Spec.AccessModes, core.ReadWriteOncePod) {\n\t\t// If the old object allowed \"ReadWriteOncePod\", continue to allow it in the new object\n\t\topts.AllowReadWriteOncePod = true\n\t}\n\treturn opts\n}","line":{"from":2054,"to":2075}} {"id":100002514,"name":"ValidatePersistentVolumeClaim","signature":"func ValidatePersistentVolumeClaim(pvc *core.PersistentVolumeClaim, opts PersistentVolumeClaimSpecValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidatePersistentVolumeClaim validates a PersistentVolumeClaim\nfunc ValidatePersistentVolumeClaim(pvc *core.PersistentVolumeClaim, opts PersistentVolumeClaimSpecValidationOptions) field.ErrorList {\n\tallErrs := ValidateObjectMeta(\u0026pvc.ObjectMeta, true, ValidatePersistentVolumeName, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidatePersistentVolumeClaimSpec(\u0026pvc.Spec, field.NewPath(\"spec\"), opts)...)\n\treturn allErrs\n}","line":{"from":2077,"to":2082}} {"id":100002515,"name":"validateDataSource","signature":"func validateDataSource(dataSource *core.TypedLocalObjectReference, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateDataSource validates a DataSource/DataSourceRef in a PersistentVolumeClaimSpec\nfunc validateDataSource(dataSource *core.TypedLocalObjectReference, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(dataSource.Name) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"name\"), \"\"))\n\t}\n\tif len(dataSource.Kind) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"kind\"), \"\"))\n\t}\n\tapiGroup := \"\"\n\tif dataSource.APIGroup != nil {\n\t\tapiGroup = *dataSource.APIGroup\n\t}\n\tif len(apiGroup) == 0 \u0026\u0026 dataSource.Kind != \"PersistentVolumeClaim\" {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, dataSource.Kind, \"must be 'PersistentVolumeClaim' when referencing the default apiGroup\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":2084,"to":2103}} {"id":100002516,"name":"validateDataSourceRef","signature":"func validateDataSourceRef(dataSourceRef *core.TypedObjectReference, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateDataSourceRef validates a DataSourceRef in a PersistentVolumeClaimSpec\nfunc validateDataSourceRef(dataSourceRef *core.TypedObjectReference, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(dataSourceRef.Name) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"name\"), \"\"))\n\t}\n\tif len(dataSourceRef.Kind) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"kind\"), \"\"))\n\t}\n\tapiGroup := \"\"\n\tif dataSourceRef.APIGroup != nil {\n\t\tapiGroup = *dataSourceRef.APIGroup\n\t}\n\tif len(apiGroup) == 0 \u0026\u0026 dataSourceRef.Kind != \"PersistentVolumeClaim\" {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, dataSourceRef.Kind, \"must be 'PersistentVolumeClaim' when referencing the default apiGroup\"))\n\t}\n\n\tif dataSourceRef.Namespace != nil \u0026\u0026 len(*dataSourceRef.Namespace) \u003e 0 {\n\t\tfor _, msg := range ValidateNameFunc(ValidateNamespaceName)(*dataSourceRef.Namespace, false) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"namespace\"), *dataSourceRef.Namespace, msg))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":2105,"to":2130}} {"id":100002517,"name":"ValidatePersistentVolumeClaimSpec","signature":"func ValidatePersistentVolumeClaimSpec(spec *core.PersistentVolumeClaimSpec, fldPath *field.Path, opts PersistentVolumeClaimSpecValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidatePersistentVolumeClaimSpec validates a PersistentVolumeClaimSpec\nfunc ValidatePersistentVolumeClaimSpec(spec *core.PersistentVolumeClaimSpec, fldPath *field.Path, opts PersistentVolumeClaimSpecValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(spec.AccessModes) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"accessModes\"), \"at least 1 access mode is required\"))\n\t}\n\tif spec.Selector != nil {\n\t\tlabelSelectorValidationOpts := unversionedvalidation.LabelSelectorValidationOptions{\n\t\t\tAllowInvalidLabelValueInSelector: opts.AllowInvalidLabelValueInSelector,\n\t\t}\n\t\tallErrs = append(allErrs, unversionedvalidation.ValidateLabelSelector(spec.Selector, labelSelectorValidationOpts, fldPath.Child(\"selector\"))...)\n\t}\n\n\texpandedSupportedAccessModes := sets.StringKeySet(supportedAccessModes)\n\tif opts.AllowReadWriteOncePod {\n\t\texpandedSupportedAccessModes.Insert(string(core.ReadWriteOncePod))\n\t}\n\n\tfoundReadWriteOncePod, foundNonReadWriteOncePod := false, false\n\tfor _, mode := range spec.AccessModes {\n\t\tif !expandedSupportedAccessModes.Has(string(mode)) {\n\t\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"accessModes\"), mode, expandedSupportedAccessModes.List()))\n\t\t}\n\n\t\tif mode == core.ReadWriteOncePod {\n\t\t\tfoundReadWriteOncePod = true\n\t\t} else if supportedAccessModes.Has(string(mode)) {\n\t\t\tfoundNonReadWriteOncePod = true\n\t\t}\n\t}\n\tif foundReadWriteOncePod \u0026\u0026 foundNonReadWriteOncePod {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"accessModes\"), \"may not use ReadWriteOncePod with other access modes\"))\n\t}\n\n\tstorageValue, ok := spec.Resources.Requests[core.ResourceStorage]\n\tif !ok {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"resources\").Key(string(core.ResourceStorage)), \"\"))\n\t} else if errs := ValidatePositiveQuantityValue(storageValue, fldPath.Child(\"resources\").Key(string(core.ResourceStorage))); len(errs) \u003e 0 {\n\t\tallErrs = append(allErrs, errs...)\n\t} else {\n\t\tallErrs = append(allErrs, ValidateResourceQuantityValue(string(core.ResourceStorage), storageValue, fldPath.Child(\"resources\").Key(string(core.ResourceStorage)))...)\n\t}\n\n\tif spec.StorageClassName != nil \u0026\u0026 len(*spec.StorageClassName) \u003e 0 {\n\t\tfor _, msg := range ValidateClassName(*spec.StorageClassName, false) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"storageClassName\"), *spec.StorageClassName, msg))\n\t\t}\n\t}\n\tif spec.VolumeMode != nil \u0026\u0026 !supportedVolumeModes.Has(string(*spec.VolumeMode)) {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"volumeMode\"), *spec.VolumeMode, supportedVolumeModes.List()))\n\t}\n\n\tif spec.DataSource != nil {\n\t\tallErrs = append(allErrs, validateDataSource(spec.DataSource, fldPath.Child(\"dataSource\"))...)\n\t}\n\tif spec.DataSourceRef != nil {\n\t\tallErrs = append(allErrs, validateDataSourceRef(spec.DataSourceRef, fldPath.Child(\"dataSourceRef\"))...)\n\t}\n\tif spec.DataSourceRef != nil \u0026\u0026 spec.DataSourceRef.Namespace != nil \u0026\u0026 len(*spec.DataSourceRef.Namespace) \u003e 0 {\n\t\tif spec.DataSource != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, fldPath.Child(\"dataSource\"),\n\t\t\t\t\"may not be specified when dataSourceRef.namespace is specified\"))\n\t\t}\n\t} else if spec.DataSource != nil \u0026\u0026 spec.DataSourceRef != nil {\n\t\tif !isDataSourceEqualDataSourceRef(spec.DataSource, spec.DataSourceRef) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, fldPath.Child(\"dataSource\"),\n\t\t\t\t\"must match dataSourceRef\"))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":2132,"to":2203}} {"id":100002518,"name":"isDataSourceEqualDataSourceRef","signature":"func isDataSourceEqualDataSourceRef(dataSource *core.TypedLocalObjectReference, dataSourceRef *core.TypedObjectReference) bool","file":"pkg/apis/core/validation/validation.go","code":"func isDataSourceEqualDataSourceRef(dataSource *core.TypedLocalObjectReference, dataSourceRef *core.TypedObjectReference) bool {\n\treturn reflect.DeepEqual(dataSource.APIGroup, dataSourceRef.APIGroup) \u0026\u0026 dataSource.Kind == dataSourceRef.Kind \u0026\u0026 dataSource.Name == dataSourceRef.Name\n}","line":{"from":2205,"to":2207}} {"id":100002519,"name":"ValidatePersistentVolumeClaimUpdate","signature":"func ValidatePersistentVolumeClaimUpdate(newPvc, oldPvc *core.PersistentVolumeClaim, opts PersistentVolumeClaimSpecValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidatePersistentVolumeClaimUpdate validates an update to a PersistentVolumeClaim\nfunc ValidatePersistentVolumeClaimUpdate(newPvc, oldPvc *core.PersistentVolumeClaim, opts PersistentVolumeClaimSpecValidationOptions) field.ErrorList {\n\tallErrs := ValidateObjectMetaUpdate(\u0026newPvc.ObjectMeta, \u0026oldPvc.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidatePersistentVolumeClaim(newPvc, opts)...)\n\tnewPvcClone := newPvc.DeepCopy()\n\toldPvcClone := oldPvc.DeepCopy()\n\n\t// PVController needs to update PVC.Spec w/ VolumeName.\n\t// Claims are immutable in order to enforce quota, range limits, etc. without gaming the system.\n\tif len(oldPvc.Spec.VolumeName) == 0 {\n\t\t// volumeName changes are allowed once.\n\t\toldPvcClone.Spec.VolumeName = newPvcClone.Spec.VolumeName // +k8s:verify-mutation:reason=clone\n\t}\n\n\tif validateStorageClassUpgradeFromAnnotation(oldPvcClone.Annotations, newPvcClone.Annotations,\n\t\toldPvcClone.Spec.StorageClassName, newPvcClone.Spec.StorageClassName) {\n\t\tnewPvcClone.Spec.StorageClassName = nil\n\t\tmetav1.SetMetaDataAnnotation(\u0026newPvcClone.ObjectMeta, core.BetaStorageClassAnnotation, oldPvcClone.Annotations[core.BetaStorageClassAnnotation])\n\t} else {\n\t\t// storageclass annotation should be immutable after creation\n\t\t// TODO: remove Beta when no longer needed\n\t\tallErrs = append(allErrs, ValidateImmutableAnnotation(newPvc.ObjectMeta.Annotations[v1.BetaStorageClassAnnotation], oldPvc.ObjectMeta.Annotations[v1.BetaStorageClassAnnotation], v1.BetaStorageClassAnnotation, field.NewPath(\"metadata\"))...)\n\n\t\t// If update from annotation to attribute failed we can attempt try to validate update from nil value.\n\t\tif validateStorageClassUpgradeFromNil(oldPvc.Annotations, oldPvc.Spec.StorageClassName, newPvc.Spec.StorageClassName, opts) {\n\t\t\tnewPvcClone.Spec.StorageClassName = oldPvcClone.Spec.StorageClassName // +k8s:verify-mutation:reason=clone\n\t\t}\n\t\t// TODO: add a specific error with a hint that storage class name can not be changed\n\t\t// (instead of letting spec comparison below return generic field forbidden error)\n\t}\n\n\t// lets make sure storage values are same.\n\tif newPvc.Status.Phase == core.ClaimBound \u0026\u0026 newPvcClone.Spec.Resources.Requests != nil {\n\t\tnewPvcClone.Spec.Resources.Requests[\"storage\"] = oldPvc.Spec.Resources.Requests[\"storage\"] // +k8s:verify-mutation:reason=clone\n\t}\n\n\toldSize := oldPvc.Spec.Resources.Requests[\"storage\"]\n\tnewSize := newPvc.Spec.Resources.Requests[\"storage\"]\n\tstatusSize := oldPvc.Status.Capacity[\"storage\"]\n\n\tif !apiequality.Semantic.DeepEqual(newPvcClone.Spec, oldPvcClone.Spec) {\n\t\tspecDiff := cmp.Diff(oldPvcClone.Spec, newPvcClone.Spec)\n\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"spec\"), fmt.Sprintf(\"spec is immutable after creation except resources.requests for bound claims\\n%v\", specDiff)))\n\t}\n\tif newSize.Cmp(oldSize) \u003c 0 {\n\t\tif !opts.EnableRecoverFromExpansionFailure {\n\t\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"spec\", \"resources\", \"requests\", \"storage\"), \"field can not be less than previous value\"))\n\t\t} else {\n\t\t\t// This validation permits reducing pvc requested size up to capacity recorded in pvc.status\n\t\t\t// so that users can recover from volume expansion failure, but Kubernetes does not actually\n\t\t\t// support volume shrinking\n\t\t\tif newSize.Cmp(statusSize) \u003c= 0 {\n\t\t\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"spec\", \"resources\", \"requests\", \"storage\"), \"field can not be less than status.capacity\"))\n\t\t\t}\n\t\t}\n\t}\n\n\tallErrs = append(allErrs, ValidateImmutableField(newPvc.Spec.VolumeMode, oldPvc.Spec.VolumeMode, field.NewPath(\"volumeMode\"))...)\n\n\treturn allErrs\n}","line":{"from":2209,"to":2269}} {"id":100002520,"name":"validateStorageClassUpgradeFromAnnotation","signature":"func validateStorageClassUpgradeFromAnnotation(oldAnnotations, newAnnotations map[string]string, oldScName, newScName *string) bool","file":"pkg/apis/core/validation/validation.go","code":"// Provide an upgrade path from PVC with storage class specified in beta\n// annotation to storage class specified in attribute. We allow update of\n// StorageClassName only if following four conditions are met at the same time:\n// 1. The old pvc's StorageClassAnnotation is set\n// 2. The old pvc's StorageClassName is not set\n// 3. The new pvc's StorageClassName is set and equal to the old value in annotation\n// 4. If the new pvc's StorageClassAnnotation is set,it must be equal to the old pv/pvc's StorageClassAnnotation\nfunc validateStorageClassUpgradeFromAnnotation(oldAnnotations, newAnnotations map[string]string, oldScName, newScName *string) bool {\n\toldSc, oldAnnotationExist := oldAnnotations[core.BetaStorageClassAnnotation]\n\tnewScInAnnotation, newAnnotationExist := newAnnotations[core.BetaStorageClassAnnotation]\n\treturn oldAnnotationExist /* condition 1 */ \u0026\u0026\n\t\toldScName == nil /* condition 2*/ \u0026\u0026\n\t\t(newScName != nil \u0026\u0026 *newScName == oldSc) /* condition 3 */ \u0026\u0026\n\t\t(!newAnnotationExist || newScInAnnotation == oldSc) /* condition 4 */\n}","line":{"from":2271,"to":2285}} {"id":100002521,"name":"validateStorageClassUpgradeFromNil","signature":"func validateStorageClassUpgradeFromNil(oldAnnotations map[string]string, oldScName, newScName *string, opts PersistentVolumeClaimSpecValidationOptions) bool","file":"pkg/apis/core/validation/validation.go","code":"// Provide an upgrade path from PVC with nil storage class. We allow update of\n// StorageClassName only if following four conditions are met at the same time:\n// 1. RetroactiveDefaultStorageClass FeatureGate is enabled\n// 2. The new pvc's StorageClassName is not nil\n// 3. The old pvc's StorageClassName is nil\n// 4. The old pvc either does not have beta annotation set, or the beta annotation matches new pvc's StorageClassName\nfunc validateStorageClassUpgradeFromNil(oldAnnotations map[string]string, oldScName, newScName *string, opts PersistentVolumeClaimSpecValidationOptions) bool {\n\toldAnnotation, oldAnnotationExist := oldAnnotations[core.BetaStorageClassAnnotation]\n\treturn opts.EnableRetroactiveDefaultStorageClass /* condition 1 */ \u0026\u0026\n\t\tnewScName != nil /* condition 2 */ \u0026\u0026\n\t\toldScName == nil /* condition 3 */ \u0026\u0026\n\t\t(!oldAnnotationExist || *newScName == oldAnnotation) /* condition 4 */\n}","line":{"from":2287,"to":2299}} {"id":100002522,"name":"ValidatePersistentVolumeClaimStatusUpdate","signature":"func ValidatePersistentVolumeClaimStatusUpdate(newPvc, oldPvc *core.PersistentVolumeClaim, validationOpts PersistentVolumeClaimSpecValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidatePersistentVolumeClaimStatusUpdate validates an update to status of a PersistentVolumeClaim\nfunc ValidatePersistentVolumeClaimStatusUpdate(newPvc, oldPvc *core.PersistentVolumeClaim, validationOpts PersistentVolumeClaimSpecValidationOptions) field.ErrorList {\n\tallErrs := ValidateObjectMetaUpdate(\u0026newPvc.ObjectMeta, \u0026oldPvc.ObjectMeta, field.NewPath(\"metadata\"))\n\tif len(newPvc.ResourceVersion) == 0 {\n\t\tallErrs = append(allErrs, field.Required(field.NewPath(\"resourceVersion\"), \"\"))\n\t}\n\tif len(newPvc.Spec.AccessModes) == 0 {\n\t\tallErrs = append(allErrs, field.Required(field.NewPath(\"Spec\", \"accessModes\"), \"\"))\n\t}\n\n\tcapPath := field.NewPath(\"status\", \"capacity\")\n\tfor r, qty := range newPvc.Status.Capacity {\n\t\tallErrs = append(allErrs, validateBasicResource(qty, capPath.Key(string(r)))...)\n\t}\n\tif validationOpts.EnableRecoverFromExpansionFailure {\n\t\tresizeStatusPath := field.NewPath(\"status\", \"resizeStatus\")\n\t\tif newPvc.Status.ResizeStatus != nil {\n\t\t\tresizeStatus := *newPvc.Status.ResizeStatus\n\t\t\tif !resizeStatusSet.Has(string(resizeStatus)) {\n\t\t\t\tallErrs = append(allErrs, field.NotSupported(resizeStatusPath, resizeStatus, resizeStatusSet.List()))\n\t\t\t}\n\t\t}\n\t\tallocPath := field.NewPath(\"status\", \"allocatedResources\")\n\t\tfor r, qty := range newPvc.Status.AllocatedResources {\n\t\t\tif r != core.ResourceStorage {\n\t\t\t\tallErrs = append(allErrs, field.NotSupported(allocPath, r, []string{string(core.ResourceStorage)}))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif errs := validateBasicResource(qty, allocPath.Key(string(r))); len(errs) \u003e 0 {\n\t\t\t\tallErrs = append(allErrs, errs...)\n\t\t\t} else {\n\t\t\t\tallErrs = append(allErrs, ValidateResourceQuantityValue(string(core.ResourceStorage), qty, allocPath.Key(string(r)))...)\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":2308,"to":2344}} {"id":100002523,"name":"validateContainerPorts","signature":"func validateContainerPorts(ports []core.ContainerPort, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateContainerPorts(ports []core.ContainerPort, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tallNames := sets.String{}\n\tfor i, port := range ports {\n\t\tidxPath := fldPath.Index(i)\n\t\tif len(port.Name) \u003e 0 {\n\t\t\tif msgs := validation.IsValidPortName(port.Name); len(msgs) != 0 {\n\t\t\t\tfor i = range msgs {\n\t\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"name\"), port.Name, msgs[i]))\n\t\t\t\t}\n\t\t\t} else if allNames.Has(port.Name) {\n\t\t\t\tallErrs = append(allErrs, field.Duplicate(idxPath.Child(\"name\"), port.Name))\n\t\t\t} else {\n\t\t\t\tallNames.Insert(port.Name)\n\t\t\t}\n\t\t}\n\t\tif port.ContainerPort == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(idxPath.Child(\"containerPort\"), \"\"))\n\t\t} else {\n\t\t\tfor _, msg := range validation.IsValidPortNum(int(port.ContainerPort)) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"containerPort\"), port.ContainerPort, msg))\n\t\t\t}\n\t\t}\n\t\tif port.HostPort != 0 {\n\t\t\tfor _, msg := range validation.IsValidPortNum(int(port.HostPort)) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"hostPort\"), port.HostPort, msg))\n\t\t\t}\n\t\t}\n\t\tif len(port.Protocol) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(idxPath.Child(\"protocol\"), \"\"))\n\t\t} else if !supportedPortProtocols.Has(string(port.Protocol)) {\n\t\t\tallErrs = append(allErrs, field.NotSupported(idxPath.Child(\"protocol\"), port.Protocol, supportedPortProtocols.List()))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":2348,"to":2384}} {"id":100002524,"name":"ValidateEnv","signature":"func ValidateEnv(vars []core.EnvVar, fldPath *field.Path, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateEnv validates env vars\nfunc ValidateEnv(vars []core.EnvVar, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tfor i, ev := range vars {\n\t\tidxPath := fldPath.Index(i)\n\t\tif len(ev.Name) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(idxPath.Child(\"name\"), \"\"))\n\t\t} else {\n\t\t\tfor _, msg := range validation.IsEnvVarName(ev.Name) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"name\"), ev.Name, msg))\n\t\t\t}\n\t\t}\n\t\tallErrs = append(allErrs, validateEnvVarValueFrom(ev, idxPath.Child(\"valueFrom\"), opts)...)\n\t}\n\treturn allErrs\n}","line":{"from":2386,"to":2402}} {"id":100002525,"name":"validateEnvVarValueFrom","signature":"func validateEnvVarValueFrom(ev core.EnvVar, fldPath *field.Path, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateEnvVarValueFrom(ev core.EnvVar, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif ev.ValueFrom == nil {\n\t\treturn allErrs\n\t}\n\n\tnumSources := 0\n\n\tif ev.ValueFrom.FieldRef != nil {\n\t\tnumSources++\n\t\tallErrs = append(allErrs, validateObjectFieldSelector(ev.ValueFrom.FieldRef, \u0026validEnvDownwardAPIFieldPathExpressions, fldPath.Child(\"fieldRef\"))...)\n\t}\n\tif ev.ValueFrom.ResourceFieldRef != nil {\n\t\tnumSources++\n\t\tlocalValidContainerResourceFieldPathPrefixes := validContainerResourceFieldPathPrefixesWithDownwardAPIHugePages\n\t\tallErrs = append(allErrs, validateContainerResourceFieldSelector(ev.ValueFrom.ResourceFieldRef, \u0026validContainerResourceFieldPathExpressions, \u0026localValidContainerResourceFieldPathPrefixes, fldPath.Child(\"resourceFieldRef\"), false)...)\n\t}\n\tif ev.ValueFrom.ConfigMapKeyRef != nil {\n\t\tnumSources++\n\t\tallErrs = append(allErrs, validateConfigMapKeySelector(ev.ValueFrom.ConfigMapKeyRef, fldPath.Child(\"configMapKeyRef\"))...)\n\t}\n\tif ev.ValueFrom.SecretKeyRef != nil {\n\t\tnumSources++\n\t\tallErrs = append(allErrs, validateSecretKeySelector(ev.ValueFrom.SecretKeyRef, fldPath.Child(\"secretKeyRef\"))...)\n\t}\n\n\tif numSources == 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, \"\", \"must specify one of: `fieldRef`, `resourceFieldRef`, `configMapKeyRef` or `secretKeyRef`\"))\n\t} else if len(ev.Value) != 0 {\n\t\tif numSources != 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, \"\", \"may not be specified when `value` is not empty\"))\n\t\t}\n\t} else if numSources \u003e 1 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, \"\", \"may not have more than one field specified at a time\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":2421,"to":2459}} {"id":100002526,"name":"validateObjectFieldSelector","signature":"func validateObjectFieldSelector(fs *core.ObjectFieldSelector, expressions *sets.String, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateObjectFieldSelector(fs *core.ObjectFieldSelector, expressions *sets.String, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(fs.APIVersion) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"apiVersion\"), \"\"))\n\t\treturn allErrs\n\t}\n\tif len(fs.FieldPath) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"fieldPath\"), \"\"))\n\t\treturn allErrs\n\t}\n\n\tinternalFieldPath, _, err := podshelper.ConvertDownwardAPIFieldLabel(fs.APIVersion, fs.FieldPath, \"\")\n\tif err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"fieldPath\"), fs.FieldPath, fmt.Sprintf(\"error converting fieldPath: %v\", err)))\n\t\treturn allErrs\n\t}\n\n\tif path, subscript, ok := fieldpath.SplitMaybeSubscriptedPath(internalFieldPath); ok {\n\t\tswitch path {\n\t\tcase \"metadata.annotations\":\n\t\t\tallErrs = append(allErrs, ValidateQualifiedName(strings.ToLower(subscript), fldPath)...)\n\t\tcase \"metadata.labels\":\n\t\t\tallErrs = append(allErrs, ValidateQualifiedName(subscript, fldPath)...)\n\t\tdefault:\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, path, \"does not support subscript\"))\n\t\t}\n\t} else if !expressions.Has(path) {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"fieldPath\"), path, expressions.List()))\n\t\treturn allErrs\n\t}\n\n\treturn allErrs\n}","line":{"from":2461,"to":2494}} {"id":100002527,"name":"validateContainerResourceFieldSelector","signature":"func validateContainerResourceFieldSelector(fs *core.ResourceFieldSelector, expressions *sets.String, prefixes *sets.String, fldPath *field.Path, volume bool) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateContainerResourceFieldSelector(fs *core.ResourceFieldSelector, expressions *sets.String, prefixes *sets.String, fldPath *field.Path, volume bool) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif volume \u0026\u0026 len(fs.ContainerName) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"containerName\"), \"\"))\n\t} else if len(fs.Resource) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"resource\"), \"\"))\n\t} else if !expressions.Has(fs.Resource) {\n\t\t// check if the prefix is present\n\t\tfoundPrefix := false\n\t\tif prefixes != nil {\n\t\t\tfor _, prefix := range prefixes.List() {\n\t\t\t\tif strings.HasPrefix(fs.Resource, prefix) {\n\t\t\t\t\tfoundPrefix = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif !foundPrefix {\n\t\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"resource\"), fs.Resource, expressions.List()))\n\t\t}\n\t}\n\tallErrs = append(allErrs, validateContainerResourceDivisor(fs.Resource, fs.Divisor, fldPath)...)\n\treturn allErrs\n}","line":{"from":2496,"to":2519}} {"id":100002528,"name":"ValidateEnvFrom","signature":"func ValidateEnvFrom(vars []core.EnvFromSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func ValidateEnvFrom(vars []core.EnvFromSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor i, ev := range vars {\n\t\tidxPath := fldPath.Index(i)\n\t\tif len(ev.Prefix) \u003e 0 {\n\t\t\tfor _, msg := range validation.IsEnvVarName(ev.Prefix) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"prefix\"), ev.Prefix, msg))\n\t\t\t}\n\t\t}\n\n\t\tnumSources := 0\n\t\tif ev.ConfigMapRef != nil {\n\t\t\tnumSources++\n\t\t\tallErrs = append(allErrs, validateConfigMapEnvSource(ev.ConfigMapRef, idxPath.Child(\"configMapRef\"))...)\n\t\t}\n\t\tif ev.SecretRef != nil {\n\t\t\tnumSources++\n\t\t\tallErrs = append(allErrs, validateSecretEnvSource(ev.SecretRef, idxPath.Child(\"secretRef\"))...)\n\t\t}\n\n\t\tif numSources == 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, \"\", \"must specify one of: `configMapRef` or `secretRef`\"))\n\t\t} else if numSources \u003e 1 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, \"\", \"may not have more than one field specified at a time\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":2521,"to":2548}} {"id":100002529,"name":"validateConfigMapEnvSource","signature":"func validateConfigMapEnvSource(configMapSource *core.ConfigMapEnvSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateConfigMapEnvSource(configMapSource *core.ConfigMapEnvSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(configMapSource.Name) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"name\"), \"\"))\n\t} else {\n\t\tfor _, msg := range ValidateConfigMapName(configMapSource.Name, true) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"name\"), configMapSource.Name, msg))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":2550,"to":2560}} {"id":100002530,"name":"validateSecretEnvSource","signature":"func validateSecretEnvSource(secretSource *core.SecretEnvSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateSecretEnvSource(secretSource *core.SecretEnvSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(secretSource.Name) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"name\"), \"\"))\n\t} else {\n\t\tfor _, msg := range ValidateSecretName(secretSource.Name, true) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"name\"), secretSource.Name, msg))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":2562,"to":2572}} {"id":100002531,"name":"validateContainerResourceDivisor","signature":"func validateContainerResourceDivisor(rName string, divisor resource.Quantity, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateContainerResourceDivisor(rName string, divisor resource.Quantity, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tunsetDivisor := resource.Quantity{}\n\tif unsetDivisor.Cmp(divisor) == 0 {\n\t\treturn allErrs\n\t}\n\tswitch rName {\n\tcase \"limits.cpu\", \"requests.cpu\":\n\t\tif !validContainerResourceDivisorForCPU.Has(divisor.String()) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"divisor\"), rName, \"only divisor's values 1m and 1 are supported with the cpu resource\"))\n\t\t}\n\tcase \"limits.memory\", \"requests.memory\":\n\t\tif !validContainerResourceDivisorForMemory.Has(divisor.String()) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"divisor\"), rName, \"only divisor's values 1, 1k, 1M, 1G, 1T, 1P, 1E, 1Ki, 1Mi, 1Gi, 1Ti, 1Pi, 1Ei are supported with the memory resource\"))\n\t\t}\n\tcase \"limits.ephemeral-storage\", \"requests.ephemeral-storage\":\n\t\tif !validContainerResourceDivisorForEphemeralStorage.Has(divisor.String()) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"divisor\"), rName, \"only divisor's values 1, 1k, 1M, 1G, 1T, 1P, 1E, 1Ki, 1Mi, 1Gi, 1Ti, 1Pi, 1Ei are supported with the local ephemeral storage resource\"))\n\t\t}\n\t}\n\tif strings.HasPrefix(rName, hugepagesRequestsPrefixDownwardAPI) || strings.HasPrefix(rName, hugepagesLimitsPrefixDownwardAPI) {\n\t\tif !validContainerResourceDivisorForHugePages.Has(divisor.String()) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"divisor\"), rName, \"only divisor's values 1, 1k, 1M, 1G, 1T, 1P, 1E, 1Ki, 1Mi, 1Gi, 1Ti, 1Pi, 1Ei are supported with the hugepages resource\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":2579,"to":2605}} {"id":100002532,"name":"validateConfigMapKeySelector","signature":"func validateConfigMapKeySelector(s *core.ConfigMapKeySelector, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateConfigMapKeySelector(s *core.ConfigMapKeySelector, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tnameFn := ValidateNameFunc(ValidateSecretName)\n\tfor _, msg := range nameFn(s.Name, false) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"name\"), s.Name, msg))\n\t}\n\tif len(s.Key) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"key\"), \"\"))\n\t} else {\n\t\tfor _, msg := range validation.IsConfigMapKey(s.Key) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"key\"), s.Key, msg))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":2607,"to":2623}} {"id":100002533,"name":"validateSecretKeySelector","signature":"func validateSecretKeySelector(s *core.SecretKeySelector, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateSecretKeySelector(s *core.SecretKeySelector, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tnameFn := ValidateNameFunc(ValidateSecretName)\n\tfor _, msg := range nameFn(s.Name, false) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"name\"), s.Name, msg))\n\t}\n\tif len(s.Key) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"key\"), \"\"))\n\t} else {\n\t\tfor _, msg := range validation.IsConfigMapKey(s.Key) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"key\"), s.Key, msg))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":2625,"to":2641}} {"id":100002534,"name":"GetVolumeMountMap","signature":"func GetVolumeMountMap(mounts []core.VolumeMount) map[string]string","file":"pkg/apis/core/validation/validation.go","code":"func GetVolumeMountMap(mounts []core.VolumeMount) map[string]string {\n\tvolmounts := make(map[string]string)\n\n\tfor _, mnt := range mounts {\n\t\tvolmounts[mnt.Name] = mnt.MountPath\n\t}\n\n\treturn volmounts\n}","line":{"from":2643,"to":2651}} {"id":100002535,"name":"GetVolumeDeviceMap","signature":"func GetVolumeDeviceMap(devices []core.VolumeDevice) map[string]string","file":"pkg/apis/core/validation/validation.go","code":"func GetVolumeDeviceMap(devices []core.VolumeDevice) map[string]string {\n\tvolDevices := make(map[string]string)\n\n\tfor _, dev := range devices {\n\t\tvolDevices[dev.Name] = dev.DevicePath\n\t}\n\n\treturn volDevices\n}","line":{"from":2653,"to":2661}} {"id":100002536,"name":"ValidateVolumeMounts","signature":"func ValidateVolumeMounts(mounts []core.VolumeMount, voldevices map[string]string, volumes map[string]core.VolumeSource, container *core.Container, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func ValidateVolumeMounts(mounts []core.VolumeMount, voldevices map[string]string, volumes map[string]core.VolumeSource, container *core.Container, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tmountpoints := sets.NewString()\n\n\tfor i, mnt := range mounts {\n\t\tidxPath := fldPath.Index(i)\n\t\tif len(mnt.Name) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(idxPath.Child(\"name\"), \"\"))\n\t\t}\n\t\tif !IsMatchedVolume(mnt.Name, volumes) {\n\t\t\tallErrs = append(allErrs, field.NotFound(idxPath.Child(\"name\"), mnt.Name))\n\t\t}\n\t\tif len(mnt.MountPath) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(idxPath.Child(\"mountPath\"), \"\"))\n\t\t}\n\t\tif mountpoints.Has(mnt.MountPath) {\n\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"mountPath\"), mnt.MountPath, \"must be unique\"))\n\t\t}\n\t\tmountpoints.Insert(mnt.MountPath)\n\n\t\t// check for overlap with VolumeDevice\n\t\tif mountNameAlreadyExists(mnt.Name, voldevices) {\n\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"name\"), mnt.Name, \"must not already exist in volumeDevices\"))\n\t\t}\n\t\tif mountPathAlreadyExists(mnt.MountPath, voldevices) {\n\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"mountPath\"), mnt.MountPath, \"must not already exist as a path in volumeDevices\"))\n\t\t}\n\n\t\tif len(mnt.SubPath) \u003e 0 {\n\t\t\tallErrs = append(allErrs, validateLocalDescendingPath(mnt.SubPath, fldPath.Child(\"subPath\"))...)\n\t\t}\n\n\t\tif len(mnt.SubPathExpr) \u003e 0 {\n\t\t\tif len(mnt.SubPath) \u003e 0 {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"subPathExpr\"), mnt.SubPathExpr, \"subPathExpr and subPath are mutually exclusive\"))\n\t\t\t}\n\n\t\t\tallErrs = append(allErrs, validateLocalDescendingPath(mnt.SubPathExpr, fldPath.Child(\"subPathExpr\"))...)\n\t\t}\n\n\t\tif mnt.MountPropagation != nil {\n\t\t\tallErrs = append(allErrs, validateMountPropagation(mnt.MountPropagation, container, fldPath.Child(\"mountPropagation\"))...)\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":2663,"to":2708}} {"id":100002537,"name":"ValidateVolumeDevices","signature":"func ValidateVolumeDevices(devices []core.VolumeDevice, volmounts map[string]string, volumes map[string]core.VolumeSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func ValidateVolumeDevices(devices []core.VolumeDevice, volmounts map[string]string, volumes map[string]core.VolumeSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tdevicepath := sets.NewString()\n\tdevicename := sets.NewString()\n\n\tfor i, dev := range devices {\n\t\tidxPath := fldPath.Index(i)\n\t\tdevName := dev.Name\n\t\tdevPath := dev.DevicePath\n\t\tdidMatch, isPVC := isMatchedDevice(devName, volumes)\n\t\tif len(devName) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(idxPath.Child(\"name\"), \"\"))\n\t\t}\n\t\tif devicename.Has(devName) {\n\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"name\"), devName, \"must be unique\"))\n\t\t}\n\t\t// Must be based on PersistentVolumeClaim (PVC reference or generic ephemeral inline volume)\n\t\tif didMatch \u0026\u0026 !isPVC {\n\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"name\"), devName, \"can only use volume source type of PersistentVolumeClaim or Ephemeral for block mode\"))\n\t\t}\n\t\tif !didMatch {\n\t\t\tallErrs = append(allErrs, field.NotFound(idxPath.Child(\"name\"), devName))\n\t\t}\n\t\tif len(devPath) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(idxPath.Child(\"devicePath\"), \"\"))\n\t\t}\n\t\tif devicepath.Has(devPath) {\n\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"devicePath\"), devPath, \"must be unique\"))\n\t\t}\n\t\tif len(devPath) \u003e 0 \u0026\u0026 len(validatePathNoBacksteps(devPath, fldPath.Child(\"devicePath\"))) \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"devicePath\"), devPath, \"can not contain backsteps ('..')\"))\n\t\t} else {\n\t\t\tdevicepath.Insert(devPath)\n\t\t}\n\t\t// check for overlap with VolumeMount\n\t\tif deviceNameAlreadyExists(devName, volmounts) {\n\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"name\"), devName, \"must not already exist in volumeMounts\"))\n\t\t}\n\t\tif devicePathAlreadyExists(devPath, volmounts) {\n\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"devicePath\"), devPath, \"must not already exist as a path in volumeMounts\"))\n\t\t}\n\t\tif len(devName) \u003e 0 {\n\t\t\tdevicename.Insert(devName)\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":2710,"to":2756}} {"id":100002538,"name":"validatePodResourceClaims","signature":"func validatePodResourceClaims(podMeta *metav1.ObjectMeta, claims []core.PodResourceClaim, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validatePodResourceClaims(podMeta *metav1.ObjectMeta, claims []core.PodResourceClaim, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tpodClaimNames := sets.NewString()\n\tfor i, claim := range claims {\n\t\tallErrs = append(allErrs, validatePodResourceClaim(podMeta, claim, \u0026podClaimNames, fldPath.Index(i))...)\n\t}\n\treturn allErrs\n}","line":{"from":2758,"to":2765}} {"id":100002539,"name":"gatherPodResourceClaimNames","signature":"func gatherPodResourceClaimNames(claims []core.PodResourceClaim) sets.String","file":"pkg/apis/core/validation/validation.go","code":"// gatherPodResourceClaimNames returns a set of all non-empty\n// PodResourceClaim.Name values. Validation that those names are valid is\n// handled by validatePodResourceClaims.\nfunc gatherPodResourceClaimNames(claims []core.PodResourceClaim) sets.String {\n\tpodClaimNames := sets.String{}\n\tfor _, claim := range claims {\n\t\tif claim.Name != \"\" {\n\t\t\tpodClaimNames.Insert(claim.Name)\n\t\t}\n\t}\n\treturn podClaimNames\n}","line":{"from":2767,"to":2778}} {"id":100002540,"name":"validatePodResourceClaim","signature":"func validatePodResourceClaim(podMeta *metav1.ObjectMeta, claim core.PodResourceClaim, podClaimNames *sets.String, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validatePodResourceClaim(podMeta *metav1.ObjectMeta, claim core.PodResourceClaim, podClaimNames *sets.String, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tif claim.Name == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"name\"), \"\"))\n\t} else if podClaimNames.Has(claim.Name) {\n\t\tallErrs = append(allErrs, field.Duplicate(fldPath.Child(\"name\"), claim.Name))\n\t} else {\n\t\tnameErrs := ValidateDNS1123Label(claim.Name, fldPath.Child(\"name\"))\n\t\tif len(nameErrs) \u003e 0 {\n\t\t\tallErrs = append(allErrs, nameErrs...)\n\t\t} else if podMeta != nil \u0026\u0026 claim.Source.ResourceClaimTemplateName != nil {\n\t\t\tclaimName := podMeta.Name + \"-\" + claim.Name\n\t\t\tfor _, detail := range ValidateResourceClaimName(claimName, false) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"name\"), claimName, \"final ResourceClaim name: \"+detail))\n\t\t\t}\n\t\t}\n\t\tpodClaimNames.Insert(claim.Name)\n\t}\n\tallErrs = append(allErrs, validatePodResourceClaimSource(claim.Source, fldPath.Child(\"source\"))...)\n\n\treturn allErrs\n}","line":{"from":2780,"to":2801}} {"id":100002541,"name":"validatePodResourceClaimSource","signature":"func validatePodResourceClaimSource(claimSource core.ClaimSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validatePodResourceClaimSource(claimSource core.ClaimSource, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tif claimSource.ResourceClaimName != nil \u0026\u0026 claimSource.ResourceClaimTemplateName != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, claimSource, \"at most one of `resourceClaimName` or `resourceClaimTemplateName` may be specified\"))\n\t}\n\tif claimSource.ResourceClaimName == nil \u0026\u0026 claimSource.ResourceClaimTemplateName == nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, claimSource, \"must specify one of: `resourceClaimName`, `resourceClaimTemplateName`\"))\n\t}\n\tif claimSource.ResourceClaimName != nil {\n\t\tfor _, detail := range ValidateResourceClaimName(*claimSource.ResourceClaimName, false) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"resourceClaimName\"), *claimSource.ResourceClaimName, detail))\n\t\t}\n\t}\n\tif claimSource.ResourceClaimTemplateName != nil {\n\t\tfor _, detail := range ValidateResourceClaimTemplateName(*claimSource.ResourceClaimTemplateName, false) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"resourceClaimTemplateName\"), *claimSource.ResourceClaimTemplateName, detail))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":2803,"to":2822}} {"id":100002542,"name":"validateProbe","signature":"func validateProbe(probe *core.Probe, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateProbe(probe *core.Probe, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif probe == nil {\n\t\treturn allErrs\n\t}\n\tallErrs = append(allErrs, validateHandler(handlerFromProbe(\u0026probe.ProbeHandler), fldPath)...)\n\n\tallErrs = append(allErrs, ValidateNonnegativeField(int64(probe.InitialDelaySeconds), fldPath.Child(\"initialDelaySeconds\"))...)\n\tallErrs = append(allErrs, ValidateNonnegativeField(int64(probe.TimeoutSeconds), fldPath.Child(\"timeoutSeconds\"))...)\n\tallErrs = append(allErrs, ValidateNonnegativeField(int64(probe.PeriodSeconds), fldPath.Child(\"periodSeconds\"))...)\n\tallErrs = append(allErrs, ValidateNonnegativeField(int64(probe.SuccessThreshold), fldPath.Child(\"successThreshold\"))...)\n\tallErrs = append(allErrs, ValidateNonnegativeField(int64(probe.FailureThreshold), fldPath.Child(\"failureThreshold\"))...)\n\tif probe.TerminationGracePeriodSeconds != nil \u0026\u0026 *probe.TerminationGracePeriodSeconds \u003c= 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"terminationGracePeriodSeconds\"), *probe.TerminationGracePeriodSeconds, \"must be greater than 0\"))\n\t}\n\treturn allErrs\n}","line":{"from":2824,"to":2841}} {"id":100002543,"name":"handlerFromProbe","signature":"func handlerFromProbe(ph *core.ProbeHandler) commonHandler","file":"pkg/apis/core/validation/validation.go","code":"func handlerFromProbe(ph *core.ProbeHandler) commonHandler {\n\treturn commonHandler{\n\t\tExec: ph.Exec,\n\t\tHTTPGet: ph.HTTPGet,\n\t\tTCPSocket: ph.TCPSocket,\n\t\tGRPC: ph.GRPC,\n\t}\n}","line":{"from":2850,"to":2857}} {"id":100002544,"name":"handlerFromLifecycle","signature":"func handlerFromLifecycle(lh *core.LifecycleHandler) commonHandler","file":"pkg/apis/core/validation/validation.go","code":"func handlerFromLifecycle(lh *core.LifecycleHandler) commonHandler {\n\treturn commonHandler{\n\t\tExec: lh.Exec,\n\t\tHTTPGet: lh.HTTPGet,\n\t\tTCPSocket: lh.TCPSocket,\n\t}\n}","line":{"from":2859,"to":2865}} {"id":100002545,"name":"validateClientIPAffinityConfig","signature":"func validateClientIPAffinityConfig(config *core.SessionAffinityConfig, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateClientIPAffinityConfig(config *core.SessionAffinityConfig, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif config == nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath, fmt.Sprintf(\"when session affinity type is %s\", core.ServiceAffinityClientIP)))\n\t\treturn allErrs\n\t}\n\tif config.ClientIP == nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"clientIP\"), fmt.Sprintf(\"when session affinity type is %s\", core.ServiceAffinityClientIP)))\n\t\treturn allErrs\n\t}\n\tif config.ClientIP.TimeoutSeconds == nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"clientIP\").Child(\"timeoutSeconds\"), fmt.Sprintf(\"when session affinity type is %s\", core.ServiceAffinityClientIP)))\n\t\treturn allErrs\n\t}\n\tallErrs = append(allErrs, validateAffinityTimeout(config.ClientIP.TimeoutSeconds, fldPath.Child(\"clientIP\").Child(\"timeoutSeconds\"))...)\n\n\treturn allErrs\n}","line":{"from":2867,"to":2884}} {"id":100002546,"name":"validateAffinityTimeout","signature":"func validateAffinityTimeout(timeout *int32, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateAffinityTimeout(timeout *int32, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif *timeout \u003c= 0 || *timeout \u003e core.MaxClientIPServiceAffinitySeconds {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, timeout, fmt.Sprintf(\"must be greater than 0 and less than %d\", core.MaxClientIPServiceAffinitySeconds)))\n\t}\n\treturn allErrs\n}","line":{"from":2886,"to":2892}} {"id":100002547,"name":"AccumulateUniqueHostPorts","signature":"func AccumulateUniqueHostPorts(containers []core.Container, accumulator *sets.String, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// AccumulateUniqueHostPorts extracts each HostPort of each Container,\n// accumulating the results and returning an error if any ports conflict.\nfunc AccumulateUniqueHostPorts(containers []core.Container, accumulator *sets.String, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tfor ci, ctr := range containers {\n\t\tidxPath := fldPath.Index(ci)\n\t\tportsPath := idxPath.Child(\"ports\")\n\t\tfor pi := range ctr.Ports {\n\t\t\tidxPath := portsPath.Index(pi)\n\t\t\tport := ctr.Ports[pi].HostPort\n\t\t\tif port == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstr := fmt.Sprintf(\"%s/%s/%d\", ctr.Ports[pi].Protocol, ctr.Ports[pi].HostIP, port)\n\t\t\tif accumulator.Has(str) {\n\t\t\t\tallErrs = append(allErrs, field.Duplicate(idxPath.Child(\"hostPort\"), str))\n\t\t\t} else {\n\t\t\t\taccumulator.Insert(str)\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":2894,"to":2917}} {"id":100002548,"name":"checkHostPortConflicts","signature":"func checkHostPortConflicts(containers []core.Container, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// checkHostPortConflicts checks for colliding Port.HostPort values across\n// a slice of containers.\nfunc checkHostPortConflicts(containers []core.Container, fldPath *field.Path) field.ErrorList {\n\tallPorts := sets.String{}\n\treturn AccumulateUniqueHostPorts(containers, \u0026allPorts, fldPath)\n}","line":{"from":2919,"to":2924}} {"id":100002549,"name":"validateExecAction","signature":"func validateExecAction(exec *core.ExecAction, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateExecAction(exec *core.ExecAction, fldPath *field.Path) field.ErrorList {\n\tallErrors := field.ErrorList{}\n\tif len(exec.Command) == 0 {\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"command\"), \"\"))\n\t}\n\treturn allErrors\n}","line":{"from":2926,"to":2932}} {"id":100002550,"name":"validateHTTPGetAction","signature":"func validateHTTPGetAction(http *core.HTTPGetAction, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateHTTPGetAction(http *core.HTTPGetAction, fldPath *field.Path) field.ErrorList {\n\tallErrors := field.ErrorList{}\n\tif len(http.Path) == 0 {\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"path\"), \"\"))\n\t}\n\tallErrors = append(allErrors, ValidatePortNumOrName(http.Port, fldPath.Child(\"port\"))...)\n\tif !supportedHTTPSchemes.Has(string(http.Scheme)) {\n\t\tallErrors = append(allErrors, field.NotSupported(fldPath.Child(\"scheme\"), http.Scheme, supportedHTTPSchemes.List()))\n\t}\n\tfor _, header := range http.HTTPHeaders {\n\t\tfor _, msg := range validation.IsHTTPHeaderName(header.Name) {\n\t\t\tallErrors = append(allErrors, field.Invalid(fldPath.Child(\"httpHeaders\"), header.Name, msg))\n\t\t}\n\t}\n\treturn allErrors\n}","line":{"from":2936,"to":2951}} {"id":100002551,"name":"ValidatePortNumOrName","signature":"func ValidatePortNumOrName(port intstr.IntOrString, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func ValidatePortNumOrName(port intstr.IntOrString, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif port.Type == intstr.Int {\n\t\tfor _, msg := range validation.IsValidPortNum(port.IntValue()) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, port.IntValue(), msg))\n\t\t}\n\t} else if port.Type == intstr.String {\n\t\tfor _, msg := range validation.IsValidPortName(port.StrVal) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, port.StrVal, msg))\n\t\t}\n\t} else {\n\t\tallErrs = append(allErrs, field.InternalError(fldPath, fmt.Errorf(\"unknown type: %v\", port.Type)))\n\t}\n\treturn allErrs\n}","line":{"from":2953,"to":2967}} {"id":100002552,"name":"validateTCPSocketAction","signature":"func validateTCPSocketAction(tcp *core.TCPSocketAction, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateTCPSocketAction(tcp *core.TCPSocketAction, fldPath *field.Path) field.ErrorList {\n\treturn ValidatePortNumOrName(tcp.Port, fldPath.Child(\"port\"))\n}","line":{"from":2969,"to":2971}} {"id":100002553,"name":"validateGRPCAction","signature":"func validateGRPCAction(grpc *core.GRPCAction, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateGRPCAction(grpc *core.GRPCAction, fldPath *field.Path) field.ErrorList {\n\treturn ValidatePortNumOrName(intstr.FromInt(int(grpc.Port)), fldPath.Child(\"port\"))\n}","line":{"from":2972,"to":2974}} {"id":100002554,"name":"validateHandler","signature":"func validateHandler(handler commonHandler, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateHandler(handler commonHandler, fldPath *field.Path) field.ErrorList {\n\tnumHandlers := 0\n\tallErrors := field.ErrorList{}\n\tif handler.Exec != nil {\n\t\tif numHandlers \u003e 0 {\n\t\t\tallErrors = append(allErrors, field.Forbidden(fldPath.Child(\"exec\"), \"may not specify more than 1 handler type\"))\n\t\t} else {\n\t\t\tnumHandlers++\n\t\t\tallErrors = append(allErrors, validateExecAction(handler.Exec, fldPath.Child(\"exec\"))...)\n\t\t}\n\t}\n\tif handler.HTTPGet != nil {\n\t\tif numHandlers \u003e 0 {\n\t\t\tallErrors = append(allErrors, field.Forbidden(fldPath.Child(\"httpGet\"), \"may not specify more than 1 handler type\"))\n\t\t} else {\n\t\t\tnumHandlers++\n\t\t\tallErrors = append(allErrors, validateHTTPGetAction(handler.HTTPGet, fldPath.Child(\"httpGet\"))...)\n\t\t}\n\t}\n\tif handler.TCPSocket != nil {\n\t\tif numHandlers \u003e 0 {\n\t\t\tallErrors = append(allErrors, field.Forbidden(fldPath.Child(\"tcpSocket\"), \"may not specify more than 1 handler type\"))\n\t\t} else {\n\t\t\tnumHandlers++\n\t\t\tallErrors = append(allErrors, validateTCPSocketAction(handler.TCPSocket, fldPath.Child(\"tcpSocket\"))...)\n\t\t}\n\t}\n\tif handler.GRPC != nil {\n\t\tif numHandlers \u003e 0 {\n\t\t\tallErrors = append(allErrors, field.Forbidden(fldPath.Child(\"grpc\"), \"may not specify more than 1 handler type\"))\n\t\t} else {\n\t\t\tnumHandlers++\n\t\t\tallErrors = append(allErrors, validateGRPCAction(handler.GRPC, fldPath.Child(\"grpc\"))...)\n\t\t}\n\t}\n\tif numHandlers == 0 {\n\t\tallErrors = append(allErrors, field.Required(fldPath, \"must specify a handler type\"))\n\t}\n\treturn allErrors\n}","line":{"from":2975,"to":3014}} {"id":100002555,"name":"validateLifecycle","signature":"func validateLifecycle(lifecycle *core.Lifecycle, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateLifecycle(lifecycle *core.Lifecycle, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif lifecycle.PostStart != nil {\n\t\tallErrs = append(allErrs, validateHandler(handlerFromLifecycle(lifecycle.PostStart), fldPath.Child(\"postStart\"))...)\n\t}\n\tif lifecycle.PreStop != nil {\n\t\tallErrs = append(allErrs, validateHandler(handlerFromLifecycle(lifecycle.PreStop), fldPath.Child(\"preStop\"))...)\n\t}\n\treturn allErrs\n}","line":{"from":3016,"to":3025}} {"id":100002556,"name":"validatePullPolicy","signature":"func validatePullPolicy(policy core.PullPolicy, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validatePullPolicy(policy core.PullPolicy, fldPath *field.Path) field.ErrorList {\n\tallErrors := field.ErrorList{}\n\n\tswitch policy {\n\tcase core.PullAlways, core.PullIfNotPresent, core.PullNever:\n\t\tbreak\n\tcase \"\":\n\t\tallErrors = append(allErrors, field.Required(fldPath, \"\"))\n\tdefault:\n\t\tallErrors = append(allErrors, field.NotSupported(fldPath, policy, supportedPullPolicies.List()))\n\t}\n\n\treturn allErrors\n}","line":{"from":3029,"to":3042}} {"id":100002557,"name":"validateResizePolicy","signature":"func validateResizePolicy(policyList []core.ContainerResizePolicy, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateResizePolicy(policyList []core.ContainerResizePolicy, fldPath *field.Path) field.ErrorList {\n\tallErrors := field.ErrorList{}\n\n\t// validate that resource name is not repeated, supported resource names and policy values are specified\n\tresources := make(map[core.ResourceName]bool)\n\tfor i, p := range policyList {\n\t\tif _, found := resources[p.ResourceName]; found {\n\t\t\tallErrors = append(allErrors, field.Duplicate(fldPath.Index(i), p.ResourceName))\n\t\t}\n\t\tresources[p.ResourceName] = true\n\t\tswitch p.ResourceName {\n\t\tcase core.ResourceCPU, core.ResourceMemory:\n\t\tcase \"\":\n\t\t\tallErrors = append(allErrors, field.Required(fldPath, \"\"))\n\t\tdefault:\n\t\t\tallErrors = append(allErrors, field.NotSupported(fldPath, p.ResourceName, supportedResizeResources.List()))\n\t\t}\n\t\tswitch p.RestartPolicy {\n\t\tcase core.NotRequired, core.RestartContainer:\n\t\tcase \"\":\n\t\t\tallErrors = append(allErrors, field.Required(fldPath, \"\"))\n\t\tdefault:\n\t\t\tallErrors = append(allErrors, field.NotSupported(fldPath, p.RestartPolicy, supportedResizePolicies.List()))\n\t\t}\n\t}\n\treturn allErrors\n}","line":{"from":3047,"to":3073}} {"id":100002558,"name":"validateEphemeralContainers","signature":"func validateEphemeralContainers(ephemeralContainers []core.EphemeralContainer, containers, initContainers []core.Container, volumes map[string]core.VolumeSource, podClaimNames sets.String, fldPath *field.Path, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateEphemeralContainers is called by pod spec and template validation to validate the list of ephemeral containers.\n// Note that this is called for pod template even though ephemeral containers aren't allowed in pod templates.\nfunc validateEphemeralContainers(ephemeralContainers []core.EphemeralContainer, containers, initContainers []core.Container, volumes map[string]core.VolumeSource, podClaimNames sets.String, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {\n\tvar allErrs field.ErrorList\n\n\tif len(ephemeralContainers) == 0 {\n\t\treturn allErrs\n\t}\n\n\totherNames, allNames := sets.String{}, sets.String{}\n\tfor _, c := range containers {\n\t\totherNames.Insert(c.Name)\n\t\tallNames.Insert(c.Name)\n\t}\n\tfor _, c := range initContainers {\n\t\totherNames.Insert(c.Name)\n\t\tallNames.Insert(c.Name)\n\t}\n\n\tfor i, ec := range ephemeralContainers {\n\t\tidxPath := fldPath.Index(i)\n\n\t\tc := (*core.Container)(\u0026ec.EphemeralContainerCommon)\n\t\tallErrs = append(allErrs, validateContainerCommon(c, volumes, podClaimNames, idxPath, opts)...)\n\t\t// Ephemeral containers don't need looser constraints for pod templates, so it's convenient to apply both validations\n\t\t// here where we've already converted EphemeralContainerCommon to Container.\n\t\tallErrs = append(allErrs, validateContainerOnlyForPod(c, idxPath)...)\n\n\t\t// Ephemeral containers must have a name unique across all container types.\n\t\tif allNames.Has(ec.Name) {\n\t\t\tallErrs = append(allErrs, field.Duplicate(idxPath.Child(\"name\"), ec.Name))\n\t\t} else {\n\t\t\tallNames.Insert(ec.Name)\n\t\t}\n\n\t\t// The target container name must exist and be non-ephemeral.\n\t\tif ec.TargetContainerName != \"\" \u0026\u0026 !otherNames.Has(ec.TargetContainerName) {\n\t\t\tallErrs = append(allErrs, field.NotFound(idxPath.Child(\"targetContainerName\"), ec.TargetContainerName))\n\t\t}\n\n\t\t// Ephemeral containers should not be relied upon for fundamental pod services, so fields such as\n\t\t// Lifecycle, probes, resources and ports should be disallowed. This is implemented as a list\n\t\t// of allowed fields so that new fields will be given consideration prior to inclusion in ephemeral containers.\n\t\tallErrs = append(allErrs, validateFieldAllowList(ec.EphemeralContainerCommon, allowedEphemeralContainerFields, \"cannot be set for an Ephemeral Container\", idxPath)...)\n\n\t\t// VolumeMount subpaths have the potential to leak resources since they're implemented with bind mounts\n\t\t// that aren't cleaned up until the pod exits. Since they also imply that the container is being used\n\t\t// as part of the workload, they're disallowed entirely.\n\t\tfor i, vm := range ec.VolumeMounts {\n\t\t\tif vm.SubPath != \"\" {\n\t\t\t\tallErrs = append(allErrs, field.Forbidden(idxPath.Child(\"volumeMounts\").Index(i).Child(\"subPath\"), \"cannot be set for an Ephemeral Container\"))\n\t\t\t}\n\t\t\tif vm.SubPathExpr != \"\" {\n\t\t\t\tallErrs = append(allErrs, field.Forbidden(idxPath.Child(\"volumeMounts\").Index(i).Child(\"subPathExpr\"), \"cannot be set for an Ephemeral Container\"))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":3075,"to":3134}} {"id":100002559,"name":"validateFieldAllowList","signature":"func validateFieldAllowList(value interface{}, allowedFields map[string]bool, errorText string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateFieldAcceptList checks that only allowed fields are set.\n// The value must be a struct (not a pointer to a struct!).\nfunc validateFieldAllowList(value interface{}, allowedFields map[string]bool, errorText string, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\n\treflectType, reflectValue := reflect.TypeOf(value), reflect.ValueOf(value)\n\tfor i := 0; i \u003c reflectType.NumField(); i++ {\n\t\tf := reflectType.Field(i)\n\t\tif allowedFields[f.Name] {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Compare the value of this field to its zero value to determine if it has been set\n\t\tif !reflect.DeepEqual(reflectValue.Field(i).Interface(), reflect.Zero(f.Type).Interface()) {\n\t\t\tr, n := utf8.DecodeRuneInString(f.Name)\n\t\t\tlcName := string(unicode.ToLower(r)) + f.Name[n:]\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(lcName), errorText))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":3136,"to":3157}} {"id":100002560,"name":"validateInitContainers","signature":"func validateInitContainers(containers []core.Container, regularContainers []core.Container, volumes map[string]core.VolumeSource, podClaimNames sets.String, fldPath *field.Path, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateInitContainers is called by pod spec and template validation to validate the list of init containers\nfunc validateInitContainers(containers []core.Container, regularContainers []core.Container, volumes map[string]core.VolumeSource, podClaimNames sets.String, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {\n\tvar allErrs field.ErrorList\n\n\tallNames := sets.String{}\n\tfor _, ctr := range regularContainers {\n\t\tallNames.Insert(ctr.Name)\n\t}\n\tfor i, ctr := range containers {\n\t\tidxPath := fldPath.Index(i)\n\n\t\t// Apply the validation common to all container types\n\t\tallErrs = append(allErrs, validateContainerCommon(\u0026ctr, volumes, podClaimNames, idxPath, opts)...)\n\n\t\t// Names must be unique within regular and init containers. Collisions with ephemeral containers\n\t\t// will be detected by validateEphemeralContainers().\n\t\tif allNames.Has(ctr.Name) {\n\t\t\tallErrs = append(allErrs, field.Duplicate(idxPath.Child(\"name\"), ctr.Name))\n\t\t} else if len(ctr.Name) \u003e 0 {\n\t\t\tallNames.Insert(ctr.Name)\n\t\t}\n\n\t\t// Check for port conflicts in init containers individually since init containers run one-by-one.\n\t\tallErrs = append(allErrs, checkHostPortConflicts([]core.Container{ctr}, fldPath)...)\n\n\t\t// These fields are disallowed for init containers.\n\t\tif ctr.Lifecycle != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(idxPath.Child(\"lifecycle\"), \"may not be set for init containers\"))\n\t\t}\n\t\tif ctr.LivenessProbe != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(idxPath.Child(\"livenessProbe\"), \"may not be set for init containers\"))\n\t\t}\n\t\tif ctr.ReadinessProbe != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(idxPath.Child(\"readinessProbe\"), \"may not be set for init containers\"))\n\t\t}\n\t\tif ctr.StartupProbe != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(idxPath.Child(\"startupProbe\"), \"may not be set for init containers\"))\n\t\t}\n\t\tif len(ctr.ResizePolicy) \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"resizePolicy\"), ctr.ResizePolicy, \"must not be set for init containers\"))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":3159,"to":3203}} {"id":100002561,"name":"validateContainerCommon","signature":"func validateContainerCommon(ctr *core.Container, volumes map[string]core.VolumeSource, podClaimNames sets.String, path *field.Path, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateContainerCommon applies validation common to all container types. It's called by regular, init, and ephemeral\n// container list validation to require a properly formatted name, image, etc.\nfunc validateContainerCommon(ctr *core.Container, volumes map[string]core.VolumeSource, podClaimNames sets.String, path *field.Path, opts PodValidationOptions) field.ErrorList {\n\tvar allErrs field.ErrorList\n\n\tnamePath := path.Child(\"name\")\n\tif len(ctr.Name) == 0 {\n\t\tallErrs = append(allErrs, field.Required(namePath, \"\"))\n\t} else {\n\t\tallErrs = append(allErrs, ValidateDNS1123Label(ctr.Name, namePath)...)\n\t}\n\n\t// TODO: do not validate leading and trailing whitespace to preserve backward compatibility.\n\t// for example: https://github.com/openshift/origin/issues/14659 image = \" \" is special token in pod template\n\t// others may have done similar\n\tif len(ctr.Image) == 0 {\n\t\tallErrs = append(allErrs, field.Required(path.Child(\"image\"), \"\"))\n\t}\n\n\tswitch ctr.TerminationMessagePolicy {\n\tcase core.TerminationMessageReadFile, core.TerminationMessageFallbackToLogsOnError:\n\tcase \"\":\n\t\tallErrs = append(allErrs, field.Required(path.Child(\"terminationMessagePolicy\"), \"\"))\n\tdefault:\n\t\tsupported := []string{\n\t\t\tstring(core.TerminationMessageReadFile),\n\t\t\tstring(core.TerminationMessageFallbackToLogsOnError),\n\t\t}\n\t\tallErrs = append(allErrs, field.NotSupported(path.Child(\"terminationMessagePolicy\"), ctr.TerminationMessagePolicy, supported))\n\t}\n\n\tvolMounts := GetVolumeMountMap(ctr.VolumeMounts)\n\tvolDevices := GetVolumeDeviceMap(ctr.VolumeDevices)\n\tallErrs = append(allErrs, validateContainerPorts(ctr.Ports, path.Child(\"ports\"))...)\n\tallErrs = append(allErrs, ValidateEnv(ctr.Env, path.Child(\"env\"), opts)...)\n\tallErrs = append(allErrs, ValidateEnvFrom(ctr.EnvFrom, path.Child(\"envFrom\"))...)\n\tallErrs = append(allErrs, ValidateVolumeMounts(ctr.VolumeMounts, volDevices, volumes, ctr, path.Child(\"volumeMounts\"))...)\n\tallErrs = append(allErrs, ValidateVolumeDevices(ctr.VolumeDevices, volMounts, volumes, path.Child(\"volumeDevices\"))...)\n\tallErrs = append(allErrs, validatePullPolicy(ctr.ImagePullPolicy, path.Child(\"imagePullPolicy\"))...)\n\tallErrs = append(allErrs, ValidateResourceRequirements(\u0026ctr.Resources, podClaimNames, path.Child(\"resources\"), opts)...)\n\tallErrs = append(allErrs, validateResizePolicy(ctr.ResizePolicy, path.Child(\"resizePolicy\"))...)\n\tallErrs = append(allErrs, ValidateSecurityContext(ctr.SecurityContext, path.Child(\"securityContext\"))...)\n\treturn allErrs\n}","line":{"from":3205,"to":3248}} {"id":100002562,"name":"validateHostUsers","signature":"func validateHostUsers(spec *core.PodSpec, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateHostUsers(spec *core.PodSpec, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\t// Only make the following checks if hostUsers is false (otherwise, the container uses the\n\t// same userns as the host, and so there isn't anything to check).\n\tif spec.SecurityContext == nil || spec.SecurityContext.HostUsers == nil || *spec.SecurityContext.HostUsers == true {\n\t\treturn allErrs\n\t}\n\n\t// For now only these volumes are supported:\n\t// - configmap\n\t// - secret\n\t// - downwardAPI\n\t// - emptyDir\n\t// - projected\n\t// So reject anything else.\n\tfor i, vol := range spec.Volumes {\n\t\tswitch {\n\t\tcase vol.EmptyDir != nil:\n\t\tcase vol.Secret != nil:\n\t\tcase vol.DownwardAPI != nil:\n\t\tcase vol.ConfigMap != nil:\n\t\tcase vol.Projected != nil:\n\t\tdefault:\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"volumes\").Index(i), \"volume type not supported when `pod.Spec.HostUsers` is false\"))\n\t\t}\n\t}\n\n\t// We decided to restrict the usage of userns with other host namespaces:\n\t// \thttps://github.com/kubernetes/kubernetes/pull/111090#discussion_r935994282\n\t// The tl;dr is: you can easily run into permission issues that seem unexpected, we don't\n\t// know of any good use case and we can always enable them later.\n\n\t// Note we already validated above spec.SecurityContext is not nil.\n\tif spec.SecurityContext.HostNetwork {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"hostNetwork\"), \"when `pod.Spec.HostUsers` is false\"))\n\t}\n\tif spec.SecurityContext.HostPID {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"HostPID\"), \"when `pod.Spec.HostUsers` is false\"))\n\t}\n\tif spec.SecurityContext.HostIPC {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"HostIPC\"), \"when `pod.Spec.HostUsers` is false\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":3250,"to":3295}} {"id":100002563,"name":"validateContainers","signature":"func validateContainers(containers []core.Container, volumes map[string]core.VolumeSource, podClaimNames sets.String, fldPath *field.Path, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateContainers is called by pod spec and template validation to validate the list of regular containers.\nfunc validateContainers(containers []core.Container, volumes map[string]core.VolumeSource, podClaimNames sets.String, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(containers) == 0 {\n\t\treturn append(allErrs, field.Required(fldPath, \"\"))\n\t}\n\n\tallNames := sets.String{}\n\tfor i, ctr := range containers {\n\t\tpath := fldPath.Index(i)\n\n\t\t// Apply validation common to all containers\n\t\tallErrs = append(allErrs, validateContainerCommon(\u0026ctr, volumes, podClaimNames, path, opts)...)\n\n\t\t// Container names must be unique within the list of regular containers.\n\t\t// Collisions with init or ephemeral container names will be detected by the init or ephemeral\n\t\t// container validation to prevent duplicate error messages.\n\t\tif allNames.Has(ctr.Name) {\n\t\t\tallErrs = append(allErrs, field.Duplicate(path.Child(\"name\"), ctr.Name))\n\t\t} else {\n\t\t\tallNames.Insert(ctr.Name)\n\t\t}\n\n\t\t// These fields are only allowed for regular containers, so only check supported values here.\n\t\t// Init and ephemeral container validation will return field.Forbidden() for these paths.\n\t\tif ctr.Lifecycle != nil {\n\t\t\tallErrs = append(allErrs, validateLifecycle(ctr.Lifecycle, path.Child(\"lifecycle\"))...)\n\t\t}\n\t\tallErrs = append(allErrs, validateProbe(ctr.LivenessProbe, path.Child(\"livenessProbe\"))...)\n\t\tif ctr.LivenessProbe != nil \u0026\u0026 ctr.LivenessProbe.SuccessThreshold != 1 {\n\t\t\tallErrs = append(allErrs, field.Invalid(path.Child(\"livenessProbe\", \"successThreshold\"), ctr.LivenessProbe.SuccessThreshold, \"must be 1\"))\n\t\t}\n\t\tallErrs = append(allErrs, validateProbe(ctr.ReadinessProbe, path.Child(\"readinessProbe\"))...)\n\t\tif ctr.ReadinessProbe != nil \u0026\u0026 ctr.ReadinessProbe.TerminationGracePeriodSeconds != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(path.Child(\"readinessProbe\", \"terminationGracePeriodSeconds\"), ctr.ReadinessProbe.TerminationGracePeriodSeconds, \"must not be set for readinessProbes\"))\n\t\t}\n\t\tallErrs = append(allErrs, validateProbe(ctr.StartupProbe, path.Child(\"startupProbe\"))...)\n\t\tif ctr.StartupProbe != nil \u0026\u0026 ctr.StartupProbe.SuccessThreshold != 1 {\n\t\t\tallErrs = append(allErrs, field.Invalid(path.Child(\"startupProbe\", \"successThreshold\"), ctr.StartupProbe.SuccessThreshold, \"must be 1\"))\n\t\t}\n\t}\n\n\t// Port conflicts are checked across all containers\n\tallErrs = append(allErrs, checkHostPortConflicts(containers, fldPath)...)\n\n\treturn allErrs\n}","line":{"from":3297,"to":3344}} {"id":100002564,"name":"validateRestartPolicy","signature":"func validateRestartPolicy(restartPolicy *core.RestartPolicy, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateRestartPolicy(restartPolicy *core.RestartPolicy, fldPath *field.Path) field.ErrorList {\n\tallErrors := field.ErrorList{}\n\tswitch *restartPolicy {\n\tcase core.RestartPolicyAlways, core.RestartPolicyOnFailure, core.RestartPolicyNever:\n\t\tbreak\n\tcase \"\":\n\t\tallErrors = append(allErrors, field.Required(fldPath, \"\"))\n\tdefault:\n\t\tvalidValues := []string{string(core.RestartPolicyAlways), string(core.RestartPolicyOnFailure), string(core.RestartPolicyNever)}\n\t\tallErrors = append(allErrors, field.NotSupported(fldPath, *restartPolicy, validValues))\n\t}\n\n\treturn allErrors\n}","line":{"from":3346,"to":3359}} {"id":100002565,"name":"ValidatePreemptionPolicy","signature":"func ValidatePreemptionPolicy(preemptionPolicy *core.PreemptionPolicy, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func ValidatePreemptionPolicy(preemptionPolicy *core.PreemptionPolicy, fldPath *field.Path) field.ErrorList {\n\tallErrors := field.ErrorList{}\n\tswitch *preemptionPolicy {\n\tcase core.PreemptLowerPriority, core.PreemptNever:\n\tcase \"\":\n\t\tallErrors = append(allErrors, field.Required(fldPath, \"\"))\n\tdefault:\n\t\tvalidValues := []string{string(core.PreemptLowerPriority), string(core.PreemptNever)}\n\t\tallErrors = append(allErrors, field.NotSupported(fldPath, preemptionPolicy, validValues))\n\t}\n\treturn allErrors\n}","line":{"from":3361,"to":3372}} {"id":100002566,"name":"validateDNSPolicy","signature":"func validateDNSPolicy(dnsPolicy *core.DNSPolicy, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateDNSPolicy(dnsPolicy *core.DNSPolicy, fldPath *field.Path) field.ErrorList {\n\tallErrors := field.ErrorList{}\n\tswitch *dnsPolicy {\n\tcase core.DNSClusterFirstWithHostNet, core.DNSClusterFirst, core.DNSDefault, core.DNSNone:\n\tcase \"\":\n\t\tallErrors = append(allErrors, field.Required(fldPath, \"\"))\n\tdefault:\n\t\tvalidValues := []string{string(core.DNSClusterFirstWithHostNet), string(core.DNSClusterFirst), string(core.DNSDefault), string(core.DNSNone)}\n\t\tallErrors = append(allErrors, field.NotSupported(fldPath, dnsPolicy, validValues))\n\t}\n\treturn allErrors\n}","line":{"from":3374,"to":3385}} {"id":100002567,"name":"validateFSGroupChangePolicy","signature":"func validateFSGroupChangePolicy(fsGroupPolicy *core.PodFSGroupChangePolicy, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateFSGroupChangePolicy(fsGroupPolicy *core.PodFSGroupChangePolicy, fldPath *field.Path) field.ErrorList {\n\tallErrors := field.ErrorList{}\n\tif !validFSGroupChangePolicies.Has(string(*fsGroupPolicy)) {\n\t\tallErrors = append(allErrors, field.NotSupported(fldPath, fsGroupPolicy, validFSGroupChangePolicies.List()))\n\t}\n\treturn allErrors\n}","line":{"from":3389,"to":3395}} {"id":100002568,"name":"validateReadinessGates","signature":"func validateReadinessGates(readinessGates []core.PodReadinessGate, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateReadinessGates(readinessGates []core.PodReadinessGate, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor i, value := range readinessGates {\n\t\tallErrs = append(allErrs, ValidateQualifiedName(string(value.ConditionType), fldPath.Index(i).Child(\"conditionType\"))...)\n\t}\n\treturn allErrs\n}","line":{"from":3412,"to":3418}} {"id":100002569,"name":"validateSchedulingGates","signature":"func validateSchedulingGates(schedulingGates []core.PodSchedulingGate, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateSchedulingGates(schedulingGates []core.PodSchedulingGate, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\t// There should be no duplicates in the list of scheduling gates.\n\tseen := sets.String{}\n\tfor i, schedulingGate := range schedulingGates {\n\t\tallErrs = append(allErrs, ValidateQualifiedName(schedulingGate.Name, fldPath.Index(i))...)\n\t\tif seen.Has(schedulingGate.Name) {\n\t\t\tallErrs = append(allErrs, field.Duplicate(fldPath.Index(i), schedulingGate.Name))\n\t\t}\n\t\tseen.Insert(schedulingGate.Name)\n\t}\n\treturn allErrs\n}","line":{"from":3420,"to":3432}} {"id":100002570,"name":"validatePodDNSConfig","signature":"func validatePodDNSConfig(dnsConfig *core.PodDNSConfig, dnsPolicy *core.DNSPolicy, fldPath *field.Path, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validatePodDNSConfig(dnsConfig *core.PodDNSConfig, dnsPolicy *core.DNSPolicy, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\t// Validate DNSNone case. Must provide at least one DNS name server.\n\tif dnsPolicy != nil \u0026\u0026 *dnsPolicy == core.DNSNone {\n\t\tif dnsConfig == nil {\n\t\t\treturn append(allErrs, field.Required(fldPath, fmt.Sprintf(\"must provide `dnsConfig` when `dnsPolicy` is %s\", core.DNSNone)))\n\t\t}\n\t\tif len(dnsConfig.Nameservers) == 0 {\n\t\t\treturn append(allErrs, field.Required(fldPath.Child(\"nameservers\"), fmt.Sprintf(\"must provide at least one DNS nameserver when `dnsPolicy` is %s\", core.DNSNone)))\n\t\t}\n\t}\n\n\tif dnsConfig != nil {\n\t\t// Validate nameservers.\n\t\tif len(dnsConfig.Nameservers) \u003e MaxDNSNameservers {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"nameservers\"), dnsConfig.Nameservers, fmt.Sprintf(\"must not have more than %v nameservers\", MaxDNSNameservers)))\n\t\t}\n\t\tfor i, ns := range dnsConfig.Nameservers {\n\t\t\tif ip := netutils.ParseIPSloppy(ns); ip == nil {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"nameservers\").Index(i), ns, \"must be valid IP address\"))\n\t\t\t}\n\t\t}\n\t\t// Validate searches.\n\t\tmaxDNSSearchPaths, maxDNSSearchListChars := MaxDNSSearchPathsLegacy, MaxDNSSearchListCharsLegacy\n\t\tif opts.AllowExpandedDNSConfig {\n\t\t\tmaxDNSSearchPaths, maxDNSSearchListChars = MaxDNSSearchPathsExpanded, MaxDNSSearchListCharsExpanded\n\t\t}\n\t\tif len(dnsConfig.Searches) \u003e maxDNSSearchPaths {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"searches\"), dnsConfig.Searches, fmt.Sprintf(\"must not have more than %v search paths\", maxDNSSearchPaths)))\n\t\t}\n\t\t// Include the space between search paths.\n\t\tif len(strings.Join(dnsConfig.Searches, \" \")) \u003e maxDNSSearchListChars {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"searches\"), dnsConfig.Searches, fmt.Sprintf(\"must not have more than %v characters (including spaces) in the search list\", maxDNSSearchListChars)))\n\t\t}\n\t\tfor i, search := range dnsConfig.Searches {\n\t\t\t// it is fine to have a trailing dot\n\t\t\tsearch = strings.TrimSuffix(search, \".\")\n\t\t\tallErrs = append(allErrs, ValidateDNS1123Subdomain(search, fldPath.Child(\"searches\").Index(i))...)\n\t\t}\n\t\t// Validate options.\n\t\tfor i, option := range dnsConfig.Options {\n\t\t\tif len(option.Name) == 0 {\n\t\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"options\").Index(i), \"must not be empty\"))\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":3434,"to":3482}} {"id":100002571,"name":"validateHostNetwork","signature":"func validateHostNetwork(hostNetwork bool, containers []core.Container, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateHostNetwork(hostNetwork bool, containers []core.Container, fldPath *field.Path) field.ErrorList {\n\tallErrors := field.ErrorList{}\n\tif hostNetwork {\n\t\tfor i, container := range containers {\n\t\t\tportsPath := fldPath.Index(i).Child(\"ports\")\n\t\t\tfor i, port := range container.Ports {\n\t\t\t\tidxPath := portsPath.Index(i)\n\t\t\t\tif port.HostPort != port.ContainerPort {\n\t\t\t\t\tallErrors = append(allErrors, field.Invalid(idxPath.Child(\"containerPort\"), port.ContainerPort, \"must match `hostPort` when `hostNetwork` is true\"))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrors\n}","line":{"from":3484,"to":3498}} {"id":100002572,"name":"validateImagePullSecrets","signature":"func validateImagePullSecrets(imagePullSecrets []core.LocalObjectReference, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateImagePullSecrets checks to make sure the pull secrets are well\n// formed. Right now, we only expect name to be set (it's the only field). If\n// this ever changes and someone decides to set those fields, we'd like to\n// know.\nfunc validateImagePullSecrets(imagePullSecrets []core.LocalObjectReference, fldPath *field.Path) field.ErrorList {\n\tallErrors := field.ErrorList{}\n\tfor i, currPullSecret := range imagePullSecrets {\n\t\tidxPath := fldPath.Index(i)\n\t\tstrippedRef := core.LocalObjectReference{Name: currPullSecret.Name}\n\t\tif !reflect.DeepEqual(strippedRef, currPullSecret) {\n\t\t\tallErrors = append(allErrors, field.Invalid(idxPath, currPullSecret, \"only name may be set\"))\n\t\t}\n\t}\n\treturn allErrors\n}","line":{"from":3500,"to":3514}} {"id":100002573,"name":"validateAffinity","signature":"func validateAffinity(affinity *core.Affinity, opts PodValidationOptions, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateAffinity checks if given affinities are valid\nfunc validateAffinity(affinity *core.Affinity, opts PodValidationOptions, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif affinity != nil {\n\t\tif affinity.NodeAffinity != nil {\n\t\t\tallErrs = append(allErrs, validateNodeAffinity(affinity.NodeAffinity, fldPath.Child(\"nodeAffinity\"))...)\n\t\t}\n\t\tif affinity.PodAffinity != nil {\n\t\t\tallErrs = append(allErrs, validatePodAffinity(affinity.PodAffinity, opts.AllowInvalidLabelValueInSelector, fldPath.Child(\"podAffinity\"))...)\n\t\t}\n\t\tif affinity.PodAntiAffinity != nil {\n\t\t\tallErrs = append(allErrs, validatePodAntiAffinity(affinity.PodAntiAffinity, opts.AllowInvalidLabelValueInSelector, fldPath.Child(\"podAntiAffinity\"))...)\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":3516,"to":3533}} {"id":100002574,"name":"validateTaintEffect","signature":"func validateTaintEffect(effect *core.TaintEffect, allowEmpty bool, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateTaintEffect(effect *core.TaintEffect, allowEmpty bool, fldPath *field.Path) field.ErrorList {\n\tif !allowEmpty \u0026\u0026 len(*effect) == 0 {\n\t\treturn field.ErrorList{field.Required(fldPath, \"\")}\n\t}\n\n\tallErrors := field.ErrorList{}\n\tswitch *effect {\n\t// TODO: Replace next line with subsequent commented-out line when implement TaintEffectNoScheduleNoAdmit.\n\tcase core.TaintEffectNoSchedule, core.TaintEffectPreferNoSchedule, core.TaintEffectNoExecute:\n\t\t// case core.TaintEffectNoSchedule, core.TaintEffectPreferNoSchedule, core.TaintEffectNoScheduleNoAdmit, core.TaintEffectNoExecute:\n\tdefault:\n\t\tvalidValues := []string{\n\t\t\tstring(core.TaintEffectNoSchedule),\n\t\t\tstring(core.TaintEffectPreferNoSchedule),\n\t\t\tstring(core.TaintEffectNoExecute),\n\t\t\t// TODO: Uncomment this block when implement TaintEffectNoScheduleNoAdmit.\n\t\t\t// string(core.TaintEffectNoScheduleNoAdmit),\n\t\t}\n\t\tallErrors = append(allErrors, field.NotSupported(fldPath, *effect, validValues))\n\t}\n\treturn allErrors\n}","line":{"from":3535,"to":3556}} {"id":100002575,"name":"validateOnlyAddedTolerations","signature":"func validateOnlyAddedTolerations(newTolerations []core.Toleration, oldTolerations []core.Toleration, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateOnlyAddedTolerations validates updated pod tolerations.\nfunc validateOnlyAddedTolerations(newTolerations []core.Toleration, oldTolerations []core.Toleration, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor _, old := range oldTolerations {\n\t\tfound := false\n\t\toldTolerationClone := old.DeepCopy()\n\t\tfor _, newToleration := range newTolerations {\n\t\t\t// assign to our clone before doing a deep equal so we can allow tolerationseconds to change.\n\t\t\toldTolerationClone.TolerationSeconds = newToleration.TolerationSeconds // +k8s:verify-mutation:reason=clone\n\t\t\tif reflect.DeepEqual(*oldTolerationClone, newToleration) {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath, \"existing toleration can not be modified except its tolerationSeconds\"))\n\t\t\treturn allErrs\n\t\t}\n\t}\n\n\tallErrs = append(allErrs, ValidateTolerations(newTolerations, fldPath)...)\n\treturn allErrs\n}","line":{"from":3558,"to":3580}} {"id":100002576,"name":"validateOnlyDeletedSchedulingGates","signature":"func validateOnlyDeletedSchedulingGates(newGates, oldGates []core.PodSchedulingGate, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateOnlyDeletedSchedulingGates(newGates, oldGates []core.PodSchedulingGate, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(newGates) == 0 {\n\t\treturn allErrs\n\t}\n\n\tadditionalGates := make(map[string]int)\n\tfor i, newGate := range newGates {\n\t\tadditionalGates[newGate.Name] = i\n\t}\n\n\tfor _, oldGate := range oldGates {\n\t\tdelete(additionalGates, oldGate.Name)\n\t}\n\n\tfor gate, i := range additionalGates {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Index(i).Child(\"name\"), fmt.Sprintf(\"only deletion is allowed, but found new scheduling gate '%s'\", gate)))\n\t}\n\n\treturn allErrs\n}","line":{"from":3582,"to":3602}} {"id":100002577,"name":"ValidateHostAliases","signature":"func ValidateHostAliases(hostAliases []core.HostAlias, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func ValidateHostAliases(hostAliases []core.HostAlias, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor _, hostAlias := range hostAliases {\n\t\tif ip := netutils.ParseIPSloppy(hostAlias.IP); ip == nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"ip\"), hostAlias.IP, \"must be valid IP address\"))\n\t\t}\n\t\tfor _, hostname := range hostAlias.Hostnames {\n\t\t\tallErrs = append(allErrs, ValidateDNS1123Subdomain(hostname, fldPath.Child(\"hostnames\"))...)\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":3604,"to":3615}} {"id":100002578,"name":"ValidateTolerations","signature":"func ValidateTolerations(tolerations []core.Toleration, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateTolerations tests if given tolerations have valid data.\nfunc ValidateTolerations(tolerations []core.Toleration, fldPath *field.Path) field.ErrorList {\n\tallErrors := field.ErrorList{}\n\tfor i, toleration := range tolerations {\n\t\tidxPath := fldPath.Index(i)\n\t\t// validate the toleration key\n\t\tif len(toleration.Key) \u003e 0 {\n\t\t\tallErrors = append(allErrors, unversionedvalidation.ValidateLabelName(toleration.Key, idxPath.Child(\"key\"))...)\n\t\t}\n\n\t\t// empty toleration key with Exists operator and empty value means match all taints\n\t\tif len(toleration.Key) == 0 \u0026\u0026 toleration.Operator != core.TolerationOpExists {\n\t\t\tallErrors = append(allErrors, field.Invalid(idxPath.Child(\"operator\"), toleration.Operator,\n\t\t\t\t\"operator must be Exists when `key` is empty, which means \\\"match all values and all keys\\\"\"))\n\t\t}\n\n\t\tif toleration.TolerationSeconds != nil \u0026\u0026 toleration.Effect != core.TaintEffectNoExecute {\n\t\t\tallErrors = append(allErrors, field.Invalid(idxPath.Child(\"effect\"), toleration.Effect,\n\t\t\t\t\"effect must be 'NoExecute' when `tolerationSeconds` is set\"))\n\t\t}\n\n\t\t// validate toleration operator and value\n\t\tswitch toleration.Operator {\n\t\t// empty operator means Equal\n\t\tcase core.TolerationOpEqual, \"\":\n\t\t\tif errs := validation.IsValidLabelValue(toleration.Value); len(errs) != 0 {\n\t\t\t\tallErrors = append(allErrors, field.Invalid(idxPath.Child(\"operator\"), toleration.Value, strings.Join(errs, \";\")))\n\t\t\t}\n\t\tcase core.TolerationOpExists:\n\t\t\tif len(toleration.Value) \u003e 0 {\n\t\t\t\tallErrors = append(allErrors, field.Invalid(idxPath.Child(\"operator\"), toleration, \"value must be empty when `operator` is 'Exists'\"))\n\t\t\t}\n\t\tdefault:\n\t\t\tvalidValues := []string{string(core.TolerationOpEqual), string(core.TolerationOpExists)}\n\t\t\tallErrors = append(allErrors, field.NotSupported(idxPath.Child(\"operator\"), toleration.Operator, validValues))\n\t\t}\n\n\t\t// validate toleration effect, empty toleration effect means match all taint effects\n\t\tif len(toleration.Effect) \u003e 0 {\n\t\t\tallErrors = append(allErrors, validateTaintEffect(\u0026toleration.Effect, true, idxPath.Child(\"effect\"))...)\n\t\t}\n\t}\n\treturn allErrors\n}","line":{"from":3617,"to":3660}} {"id":100002579,"name":"validateContainersOnlyForPod","signature":"func validateContainersOnlyForPod(containers []core.Container, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateContainersOnlyForPod does additional validation for containers on a pod versus a pod template\n// it only does additive validation of fields not covered in validateContainers and is not called for\n// ephemeral containers which require a conversion to core.Container.\nfunc validateContainersOnlyForPod(containers []core.Container, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor i, ctr := range containers {\n\t\tallErrs = append(allErrs, validateContainerOnlyForPod(\u0026ctr, fldPath.Index(i))...)\n\t}\n\treturn allErrs\n}","line":{"from":3662,"to":3671}} {"id":100002580,"name":"validateContainerOnlyForPod","signature":"func validateContainerOnlyForPod(ctr *core.Container, path *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateContainerOnlyForPod does pod-only (i.e. not pod template) validation for a single container.\n// This is called by validateContainersOnlyForPod and validateEphemeralContainers directly.\nfunc validateContainerOnlyForPod(ctr *core.Container, path *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(ctr.Image) != len(strings.TrimSpace(ctr.Image)) {\n\t\tallErrs = append(allErrs, field.Invalid(path.Child(\"image\"), ctr.Image, \"must not have leading or trailing whitespace\"))\n\t}\n\treturn allErrs\n}","line":{"from":3673,"to":3681}} {"id":100002581,"name":"validatePodMetadataAndSpec","signature":"func validatePodMetadataAndSpec(pod *core.Pod, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validatePodMetadataAndSpec tests if required fields in the pod.metadata and pod.spec are set,\n// and is called by ValidatePodCreate and ValidatePodUpdate.\nfunc validatePodMetadataAndSpec(pod *core.Pod, opts PodValidationOptions) field.ErrorList {\n\tfldPath := field.NewPath(\"metadata\")\n\tallErrs := ValidateObjectMeta(\u0026pod.ObjectMeta, true, ValidatePodName, fldPath)\n\tallErrs = append(allErrs, ValidatePodSpecificAnnotations(pod.ObjectMeta.Annotations, \u0026pod.Spec, fldPath.Child(\"annotations\"), opts)...)\n\tallErrs = append(allErrs, ValidatePodSpec(\u0026pod.Spec, \u0026pod.ObjectMeta, field.NewPath(\"spec\"), opts)...)\n\n\t// we do additional validation only pertinent for pods and not pod templates\n\t// this was done to preserve backwards compatibility\n\tspecPath := field.NewPath(\"spec\")\n\n\tif pod.Spec.ServiceAccountName == \"\" {\n\t\tfor vi, volume := range pod.Spec.Volumes {\n\t\t\tpath := specPath.Child(\"volumes\").Index(vi).Child(\"projected\")\n\t\t\tif volume.Projected != nil {\n\t\t\t\tfor si, source := range volume.Projected.Sources {\n\t\t\t\t\tsaPath := path.Child(\"sources\").Index(si).Child(\"serviceAccountToken\")\n\t\t\t\t\tif source.ServiceAccountToken != nil {\n\t\t\t\t\t\tallErrs = append(allErrs, field.Forbidden(saPath, \"must not be specified when serviceAccountName is not set\"))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tallErrs = append(allErrs, validateContainersOnlyForPod(pod.Spec.Containers, specPath.Child(\"containers\"))...)\n\tallErrs = append(allErrs, validateContainersOnlyForPod(pod.Spec.InitContainers, specPath.Child(\"initContainers\"))...)\n\t// validateContainersOnlyForPod() is checked for ephemeral containers by validateEphemeralContainers()\n\n\treturn allErrs\n}","line":{"from":3699,"to":3730}} {"id":100002582,"name":"validatePodIPs","signature":"func validatePodIPs(pod *core.Pod) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validatePodIPs validates IPs in pod status\nfunc validatePodIPs(pod *core.Pod) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tpodIPsField := field.NewPath(\"status\", \"podIPs\")\n\n\t// all PodIPs must be valid IPs\n\tfor i, podIP := range pod.Status.PodIPs {\n\t\tfor _, msg := range validation.IsValidIP(podIP.IP) {\n\t\t\tallErrs = append(allErrs, field.Invalid(podIPsField.Index(i), podIP.IP, msg))\n\t\t}\n\t}\n\n\t// if we have more than one Pod.PodIP then\n\t// - validate for dual stack\n\t// - validate for duplication\n\tif len(pod.Status.PodIPs) \u003e 1 {\n\t\tpodIPs := make([]string, 0, len(pod.Status.PodIPs))\n\t\tfor _, podIP := range pod.Status.PodIPs {\n\t\t\tpodIPs = append(podIPs, podIP.IP)\n\t\t}\n\n\t\tdualStack, err := netutils.IsDualStackIPStrings(podIPs)\n\t\tif err != nil {\n\t\t\tallErrs = append(allErrs, field.InternalError(podIPsField, fmt.Errorf(\"failed to check for dual stack with error:%v\", err)))\n\t\t}\n\n\t\t// We only support one from each IP family (i.e. max two IPs in this list).\n\t\tif !dualStack || len(podIPs) \u003e 2 {\n\t\t\tallErrs = append(allErrs, field.Invalid(podIPsField, pod.Status.PodIPs, \"may specify no more than one IP for each IP family\"))\n\t\t}\n\n\t\t// There should be no duplicates in list of Pod.PodIPs\n\t\tseen := sets.String{} // := make(map[string]int)\n\t\tfor i, podIP := range pod.Status.PodIPs {\n\t\t\tif seen.Has(podIP.IP) {\n\t\t\t\tallErrs = append(allErrs, field.Duplicate(podIPsField.Index(i), podIP))\n\t\t\t}\n\t\t\tseen.Insert(podIP.IP)\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":3732,"to":3775}} {"id":100002583,"name":"ValidatePodSpec","signature":"func ValidatePodSpec(spec *core.PodSpec, podMeta *metav1.ObjectMeta, fldPath *field.Path, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidatePodSpec tests that the specified PodSpec has valid data.\n// This includes checking formatting and uniqueness. It also canonicalizes the\n// structure by setting default values and implementing any backwards-compatibility\n// tricks.\n// The pod metadata is needed to validate generic ephemeral volumes. It is optional\n// and should be left empty unless the spec is from a real pod object.\nfunc ValidatePodSpec(spec *core.PodSpec, podMeta *metav1.ObjectMeta, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tvols, vErrs := ValidateVolumes(spec.Volumes, podMeta, fldPath.Child(\"volumes\"), opts)\n\tallErrs = append(allErrs, vErrs...)\n\tpodClaimNames := gatherPodResourceClaimNames(spec.ResourceClaims)\n\tallErrs = append(allErrs, validatePodResourceClaims(podMeta, spec.ResourceClaims, fldPath.Child(\"resourceClaims\"))...)\n\tallErrs = append(allErrs, validateContainers(spec.Containers, vols, podClaimNames, fldPath.Child(\"containers\"), opts)...)\n\tallErrs = append(allErrs, validateInitContainers(spec.InitContainers, spec.Containers, vols, podClaimNames, fldPath.Child(\"initContainers\"), opts)...)\n\tallErrs = append(allErrs, validateEphemeralContainers(spec.EphemeralContainers, spec.Containers, spec.InitContainers, vols, podClaimNames, fldPath.Child(\"ephemeralContainers\"), opts)...)\n\tallErrs = append(allErrs, validateRestartPolicy(\u0026spec.RestartPolicy, fldPath.Child(\"restartPolicy\"))...)\n\tallErrs = append(allErrs, validateDNSPolicy(\u0026spec.DNSPolicy, fldPath.Child(\"dnsPolicy\"))...)\n\tallErrs = append(allErrs, unversionedvalidation.ValidateLabels(spec.NodeSelector, fldPath.Child(\"nodeSelector\"))...)\n\tallErrs = append(allErrs, ValidatePodSecurityContext(spec.SecurityContext, spec, fldPath, fldPath.Child(\"securityContext\"), opts)...)\n\tallErrs = append(allErrs, validateImagePullSecrets(spec.ImagePullSecrets, fldPath.Child(\"imagePullSecrets\"))...)\n\tallErrs = append(allErrs, validateAffinity(spec.Affinity, opts, fldPath.Child(\"affinity\"))...)\n\tallErrs = append(allErrs, validatePodDNSConfig(spec.DNSConfig, \u0026spec.DNSPolicy, fldPath.Child(\"dnsConfig\"), opts)...)\n\tallErrs = append(allErrs, validateReadinessGates(spec.ReadinessGates, fldPath.Child(\"readinessGates\"))...)\n\tallErrs = append(allErrs, validateSchedulingGates(spec.SchedulingGates, fldPath.Child(\"schedulingGates\"))...)\n\tallErrs = append(allErrs, validateTopologySpreadConstraints(spec.TopologySpreadConstraints, fldPath.Child(\"topologySpreadConstraints\"), opts)...)\n\tallErrs = append(allErrs, validateWindowsHostProcessPod(spec, fldPath)...)\n\tallErrs = append(allErrs, validateHostUsers(spec, fldPath)...)\n\tif len(spec.ServiceAccountName) \u003e 0 {\n\t\tfor _, msg := range ValidateServiceAccountName(spec.ServiceAccountName, false) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"serviceAccountName\"), spec.ServiceAccountName, msg))\n\t\t}\n\t}\n\n\tif len(spec.NodeName) \u003e 0 {\n\t\tfor _, msg := range ValidateNodeName(spec.NodeName, false) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"nodeName\"), spec.NodeName, msg))\n\t\t}\n\t}\n\n\tif spec.ActiveDeadlineSeconds != nil {\n\t\tvalue := *spec.ActiveDeadlineSeconds\n\t\tif value \u003c 1 || value \u003e math.MaxInt32 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"activeDeadlineSeconds\"), value, validation.InclusiveRangeError(1, math.MaxInt32)))\n\t\t}\n\t}\n\n\tif len(spec.Hostname) \u003e 0 {\n\t\tallErrs = append(allErrs, ValidateDNS1123Label(spec.Hostname, fldPath.Child(\"hostname\"))...)\n\t}\n\n\tif len(spec.Subdomain) \u003e 0 {\n\t\tallErrs = append(allErrs, ValidateDNS1123Label(spec.Subdomain, fldPath.Child(\"subdomain\"))...)\n\t}\n\n\tif len(spec.Tolerations) \u003e 0 {\n\t\tallErrs = append(allErrs, ValidateTolerations(spec.Tolerations, fldPath.Child(\"tolerations\"))...)\n\t}\n\n\tif len(spec.HostAliases) \u003e 0 {\n\t\tallErrs = append(allErrs, ValidateHostAliases(spec.HostAliases, fldPath.Child(\"hostAliases\"))...)\n\t}\n\n\tif len(spec.PriorityClassName) \u003e 0 {\n\t\tfor _, msg := range ValidatePriorityClassName(spec.PriorityClassName, false) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"priorityClassName\"), spec.PriorityClassName, msg))\n\t\t}\n\t}\n\n\tif spec.RuntimeClassName != nil {\n\t\tallErrs = append(allErrs, ValidateRuntimeClassName(*spec.RuntimeClassName, fldPath.Child(\"runtimeClassName\"))...)\n\t}\n\n\tif spec.PreemptionPolicy != nil {\n\t\tallErrs = append(allErrs, ValidatePreemptionPolicy(spec.PreemptionPolicy, fldPath.Child(\"preemptionPolicy\"))...)\n\t}\n\n\tif spec.Overhead != nil {\n\t\tallErrs = append(allErrs, validateOverhead(spec.Overhead, fldPath.Child(\"overhead\"), opts)...)\n\t}\n\n\tif spec.OS != nil {\n\t\tosErrs := validateOS(spec, fldPath.Child(\"os\"), opts)\n\t\tswitch {\n\t\tcase len(osErrs) \u003e 0:\n\t\t\tallErrs = append(allErrs, osErrs...)\n\t\tcase spec.OS.Name == core.Linux:\n\t\t\tallErrs = append(allErrs, validateLinux(spec, fldPath)...)\n\t\tcase spec.OS.Name == core.Windows:\n\t\t\tallErrs = append(allErrs, validateWindows(spec, fldPath)...)\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":3777,"to":3870}} {"id":100002584,"name":"validateLinux","signature":"func validateLinux(spec *core.PodSpec, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateLinux(spec *core.PodSpec, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tsecurityContext := spec.SecurityContext\n\tif securityContext != nil \u0026\u0026 securityContext.WindowsOptions != nil {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"securityContext\").Child(\"windowsOptions\"), \"windows options cannot be set for a linux pod\"))\n\t}\n\tpodshelper.VisitContainersWithPath(spec, fldPath, func(c *core.Container, cFldPath *field.Path) bool {\n\t\tsc := c.SecurityContext\n\t\tif sc != nil \u0026\u0026 sc.WindowsOptions != nil {\n\t\t\tfldPath := cFldPath.Child(\"securityContext\")\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"windowsOptions\"), \"windows options cannot be set for a linux pod\"))\n\t\t}\n\t\treturn true\n\t})\n\treturn allErrs\n}","line":{"from":3872,"to":3887}} {"id":100002585,"name":"validateWindows","signature":"func validateWindows(spec *core.PodSpec, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateWindows(spec *core.PodSpec, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tsecurityContext := spec.SecurityContext\n\t// validate Pod SecurityContext\n\tif securityContext != nil {\n\t\tif securityContext.SELinuxOptions != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"securityContext\").Child(\"seLinuxOptions\"), \"cannot be set for a windows pod\"))\n\t\t}\n\t\tif securityContext.HostUsers != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"hostUsers\"), \"cannot be set for a windows pod\"))\n\t\t}\n\t\tif securityContext.HostPID {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"hostPID\"), \"cannot be set for a windows pod\"))\n\t\t}\n\t\tif securityContext.HostIPC {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"hostIPC\"), \"cannot be set for a windows pod\"))\n\t\t}\n\t\tif securityContext.SeccompProfile != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"securityContext\").Child(\"seccompProfile\"), \"cannot be set for a windows pod\"))\n\t\t}\n\t\tif securityContext.FSGroup != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"securityContext\").Child(\"fsGroup\"), \"cannot be set for a windows pod\"))\n\t\t}\n\t\tif securityContext.FSGroupChangePolicy != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"securityContext\").Child(\"fsGroupChangePolicy\"), \"cannot be set for a windows pod\"))\n\t\t}\n\t\tif len(securityContext.Sysctls) \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"securityContext\").Child(\"sysctls\"), \"cannot be set for a windows pod\"))\n\t\t}\n\t\tif securityContext.ShareProcessNamespace != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"shareProcessNamespace\"), \"cannot be set for a windows pod\"))\n\t\t}\n\t\tif securityContext.RunAsUser != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"securityContext\").Child(\"runAsUser\"), \"cannot be set for a windows pod\"))\n\t\t}\n\t\tif securityContext.RunAsGroup != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"securityContext\").Child(\"runAsGroup\"), \"cannot be set for a windows pod\"))\n\t\t}\n\t\tif securityContext.SupplementalGroups != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"securityContext\").Child(\"supplementalGroups\"), \"cannot be set for a windows pod\"))\n\t\t}\n\t}\n\tpodshelper.VisitContainersWithPath(spec, fldPath, func(c *core.Container, cFldPath *field.Path) bool {\n\t\t// validate container security context\n\t\tsc := c.SecurityContext\n\t\t// OS based podSecurityContext validation\n\t\t// There is some naming overlap between Windows and Linux Security Contexts but all the Windows Specific options\n\t\t// are set via securityContext.WindowsOptions which we validate below\n\t\t// TODO: Think if we need to relax this restriction or some of the restrictions\n\t\tif sc != nil {\n\t\t\tfldPath := cFldPath.Child(\"securityContext\")\n\t\t\tif sc.SELinuxOptions != nil {\n\t\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"seLinuxOptions\"), \"cannot be set for a windows pod\"))\n\t\t\t}\n\t\t\tif sc.SeccompProfile != nil {\n\t\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"seccompProfile\"), \"cannot be set for a windows pod\"))\n\t\t\t}\n\t\t\tif sc.Capabilities != nil {\n\t\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"capabilities\"), \"cannot be set for a windows pod\"))\n\t\t\t}\n\t\t\tif sc.ReadOnlyRootFilesystem != nil {\n\t\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"readOnlyRootFilesystem\"), \"cannot be set for a windows pod\"))\n\t\t\t}\n\t\t\tif sc.Privileged != nil {\n\t\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"privileged\"), \"cannot be set for a windows pod\"))\n\t\t\t}\n\t\t\tif sc.AllowPrivilegeEscalation != nil {\n\t\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"allowPrivilegeEscalation\"), \"cannot be set for a windows pod\"))\n\t\t\t}\n\t\t\tif sc.ProcMount != nil {\n\t\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"procMount\"), \"cannot be set for a windows pod\"))\n\t\t\t}\n\t\t\tif sc.RunAsUser != nil {\n\t\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"runAsUser\"), \"cannot be set for a windows pod\"))\n\t\t\t}\n\t\t\tif sc.RunAsGroup != nil {\n\t\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"runAsGroup\"), \"cannot be set for a windows pod\"))\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n\treturn allErrs\n}","line":{"from":3889,"to":3971}} {"id":100002586,"name":"ValidateNodeSelectorRequirement","signature":"func ValidateNodeSelectorRequirement(rq core.NodeSelectorRequirement, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateNodeSelectorRequirement tests that the specified NodeSelectorRequirement fields has valid data\nfunc ValidateNodeSelectorRequirement(rq core.NodeSelectorRequirement, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tswitch rq.Operator {\n\tcase core.NodeSelectorOpIn, core.NodeSelectorOpNotIn:\n\t\tif len(rq.Values) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"values\"), \"must be specified when `operator` is 'In' or 'NotIn'\"))\n\t\t}\n\tcase core.NodeSelectorOpExists, core.NodeSelectorOpDoesNotExist:\n\t\tif len(rq.Values) \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"values\"), \"may not be specified when `operator` is 'Exists' or 'DoesNotExist'\"))\n\t\t}\n\n\tcase core.NodeSelectorOpGt, core.NodeSelectorOpLt:\n\t\tif len(rq.Values) != 1 {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"values\"), \"must be specified single value when `operator` is 'Lt' or 'Gt'\"))\n\t\t}\n\tdefault:\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"operator\"), rq.Operator, \"not a valid selector operator\"))\n\t}\n\n\tallErrs = append(allErrs, unversionedvalidation.ValidateLabelName(rq.Key, fldPath.Child(\"key\"))...)\n\n\treturn allErrs\n}","line":{"from":3973,"to":3997}} {"id":100002587,"name":"ValidateNodeFieldSelectorRequirement","signature":"func ValidateNodeFieldSelectorRequirement(req core.NodeSelectorRequirement, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateNodeFieldSelectorRequirement tests that the specified NodeSelectorRequirement fields has valid data\nfunc ValidateNodeFieldSelectorRequirement(req core.NodeSelectorRequirement, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tswitch req.Operator {\n\tcase core.NodeSelectorOpIn, core.NodeSelectorOpNotIn:\n\t\tif len(req.Values) != 1 {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"values\"),\n\t\t\t\t\"must be only one value when `operator` is 'In' or 'NotIn' for node field selector\"))\n\t\t}\n\tdefault:\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"operator\"), req.Operator, \"not a valid selector operator\"))\n\t}\n\n\tif vf, found := nodeFieldSelectorValidators[req.Key]; !found {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"key\"), req.Key, \"not a valid field selector key\"))\n\t} else {\n\t\tfor i, v := range req.Values {\n\t\t\tfor _, msg := range vf(v, false) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"values\").Index(i), v, msg))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":4003,"to":4028}} {"id":100002588,"name":"ValidateNodeSelectorTerm","signature":"func ValidateNodeSelectorTerm(term core.NodeSelectorTerm, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateNodeSelectorTerm tests that the specified node selector term has valid data\nfunc ValidateNodeSelectorTerm(term core.NodeSelectorTerm, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tfor j, req := range term.MatchExpressions {\n\t\tallErrs = append(allErrs, ValidateNodeSelectorRequirement(req, fldPath.Child(\"matchExpressions\").Index(j))...)\n\t}\n\n\tfor j, req := range term.MatchFields {\n\t\tallErrs = append(allErrs, ValidateNodeFieldSelectorRequirement(req, fldPath.Child(\"matchFields\").Index(j))...)\n\t}\n\n\treturn allErrs\n}","line":{"from":4030,"to":4043}} {"id":100002589,"name":"ValidateNodeSelector","signature":"func ValidateNodeSelector(nodeSelector *core.NodeSelector, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateNodeSelector tests that the specified nodeSelector fields has valid data\nfunc ValidateNodeSelector(nodeSelector *core.NodeSelector, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\ttermFldPath := fldPath.Child(\"nodeSelectorTerms\")\n\tif len(nodeSelector.NodeSelectorTerms) == 0 {\n\t\treturn append(allErrs, field.Required(termFldPath, \"must have at least one node selector term\"))\n\t}\n\n\tfor i, term := range nodeSelector.NodeSelectorTerms {\n\t\tallErrs = append(allErrs, ValidateNodeSelectorTerm(term, termFldPath.Index(i))...)\n\t}\n\n\treturn allErrs\n}","line":{"from":4045,"to":4059}} {"id":100002590,"name":"validateTopologySelectorLabelRequirement","signature":"func validateTopologySelectorLabelRequirement(rq core.TopologySelectorLabelRequirement, fldPath *field.Path) (sets.String, field.ErrorList)","file":"pkg/apis/core/validation/validation.go","code":"// validateTopologySelectorLabelRequirement tests that the specified TopologySelectorLabelRequirement fields has valid data,\n// and constructs a set containing all of its Values.\nfunc validateTopologySelectorLabelRequirement(rq core.TopologySelectorLabelRequirement, fldPath *field.Path) (sets.String, field.ErrorList) {\n\tallErrs := field.ErrorList{}\n\tvalueSet := make(sets.String)\n\tvaluesPath := fldPath.Child(\"values\")\n\tif len(rq.Values) == 0 {\n\t\tallErrs = append(allErrs, field.Required(valuesPath, \"\"))\n\t}\n\n\t// Validate set property of Values field\n\tfor i, value := range rq.Values {\n\t\tif valueSet.Has(value) {\n\t\t\tallErrs = append(allErrs, field.Duplicate(valuesPath.Index(i), value))\n\t\t}\n\t\tvalueSet.Insert(value)\n\t}\n\n\tallErrs = append(allErrs, unversionedvalidation.ValidateLabelName(rq.Key, fldPath.Child(\"key\"))...)\n\n\treturn valueSet, allErrs\n}","line":{"from":4061,"to":4082}} {"id":100002591,"name":"ValidateTopologySelectorTerm","signature":"func ValidateTopologySelectorTerm(term core.TopologySelectorTerm, fldPath *field.Path) (map[string]sets.String, field.ErrorList)","file":"pkg/apis/core/validation/validation.go","code":"// ValidateTopologySelectorTerm tests that the specified topology selector term has valid data,\n// and constructs a map representing the term in raw form.\nfunc ValidateTopologySelectorTerm(term core.TopologySelectorTerm, fldPath *field.Path) (map[string]sets.String, field.ErrorList) {\n\tallErrs := field.ErrorList{}\n\texprMap := make(map[string]sets.String)\n\texprPath := fldPath.Child(\"matchLabelExpressions\")\n\n\t// Allow empty MatchLabelExpressions, in case this field becomes optional in the future.\n\tfor i, req := range term.MatchLabelExpressions {\n\t\tidxPath := exprPath.Index(i)\n\t\tvalueSet, exprErrs := validateTopologySelectorLabelRequirement(req, idxPath)\n\t\tallErrs = append(allErrs, exprErrs...)\n\n\t\t// Validate no duplicate keys exist.\n\t\tif _, exists := exprMap[req.Key]; exists {\n\t\t\tallErrs = append(allErrs, field.Duplicate(idxPath.Child(\"key\"), req.Key))\n\t\t}\n\t\texprMap[req.Key] = valueSet\n\t}\n\n\treturn exprMap, allErrs\n}","line":{"from":4084,"to":4105}} {"id":100002592,"name":"ValidateAvoidPodsInNodeAnnotations","signature":"func ValidateAvoidPodsInNodeAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateAvoidPodsInNodeAnnotations tests that the serialized AvoidPods in Node.Annotations has valid data\nfunc ValidateAvoidPodsInNodeAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tv1Avoids, err := schedulinghelper.GetAvoidPodsFromNodeAnnotations(annotations)\n\tif err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"AvoidPods\"), core.PreferAvoidPodsAnnotationKey, err.Error()))\n\t\treturn allErrs\n\t}\n\tvar avoids core.AvoidPods\n\tif err := corev1.Convert_v1_AvoidPods_To_core_AvoidPods(\u0026v1Avoids, \u0026avoids, nil); err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"AvoidPods\"), core.PreferAvoidPodsAnnotationKey, err.Error()))\n\t\treturn allErrs\n\t}\n\n\tif len(avoids.PreferAvoidPods) != 0 {\n\t\tfor i, pa := range avoids.PreferAvoidPods {\n\t\t\tidxPath := fldPath.Child(core.PreferAvoidPodsAnnotationKey).Index(i)\n\t\t\tallErrs = append(allErrs, validatePreferAvoidPodsEntry(pa, idxPath)...)\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":4107,"to":4130}} {"id":100002593,"name":"validatePreferAvoidPodsEntry","signature":"func validatePreferAvoidPodsEntry(avoidPodEntry core.PreferAvoidPodsEntry, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validatePreferAvoidPodsEntry tests if given PreferAvoidPodsEntry has valid data.\nfunc validatePreferAvoidPodsEntry(avoidPodEntry core.PreferAvoidPodsEntry, fldPath *field.Path) field.ErrorList {\n\tallErrors := field.ErrorList{}\n\tif avoidPodEntry.PodSignature.PodController == nil {\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"PodSignature\"), \"\"))\n\t} else {\n\t\tif !*(avoidPodEntry.PodSignature.PodController.Controller) {\n\t\t\tallErrors = append(allErrors,\n\t\t\t\tfield.Invalid(fldPath.Child(\"PodSignature\").Child(\"PodController\").Child(\"Controller\"),\n\t\t\t\t\t*(avoidPodEntry.PodSignature.PodController.Controller), \"must point to a controller\"))\n\t\t}\n\t}\n\treturn allErrors\n}","line":{"from":4132,"to":4145}} {"id":100002594,"name":"ValidatePreferredSchedulingTerms","signature":"func ValidatePreferredSchedulingTerms(terms []core.PreferredSchedulingTerm, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidatePreferredSchedulingTerms tests that the specified SoftNodeAffinity fields has valid data\nfunc ValidatePreferredSchedulingTerms(terms []core.PreferredSchedulingTerm, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tfor i, term := range terms {\n\t\tif term.Weight \u003c= 0 || term.Weight \u003e 100 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Index(i).Child(\"weight\"), term.Weight, \"must be in the range 1-100\"))\n\t\t}\n\n\t\tallErrs = append(allErrs, ValidateNodeSelectorTerm(term.Preference, fldPath.Index(i).Child(\"preference\"))...)\n\t}\n\treturn allErrs\n}","line":{"from":4147,"to":4159}} {"id":100002595,"name":"validatePodAffinityTerm","signature":"func validatePodAffinityTerm(podAffinityTerm core.PodAffinityTerm, allowInvalidLabelValueInSelector bool, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validatePodAffinityTerm tests that the specified podAffinityTerm fields have valid data\nfunc validatePodAffinityTerm(podAffinityTerm core.PodAffinityTerm, allowInvalidLabelValueInSelector bool, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tallErrs = append(allErrs, ValidatePodAffinityTermSelector(podAffinityTerm, allowInvalidLabelValueInSelector, fldPath)...)\n\tfor _, name := range podAffinityTerm.Namespaces {\n\t\tfor _, msg := range ValidateNamespaceName(name, false) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"namespace\"), name, msg))\n\t\t}\n\t}\n\tif len(podAffinityTerm.TopologyKey) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"topologyKey\"), \"can not be empty\"))\n\t}\n\treturn append(allErrs, unversionedvalidation.ValidateLabelName(podAffinityTerm.TopologyKey, fldPath.Child(\"topologyKey\"))...)\n}","line":{"from":4161,"to":4175}} {"id":100002596,"name":"validatePodAffinityTerms","signature":"func validatePodAffinityTerms(podAffinityTerms []core.PodAffinityTerm, allowInvalidLabelValueInSelector bool, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validatePodAffinityTerms tests that the specified podAffinityTerms fields have valid data\nfunc validatePodAffinityTerms(podAffinityTerms []core.PodAffinityTerm, allowInvalidLabelValueInSelector bool, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor i, podAffinityTerm := range podAffinityTerms {\n\t\tallErrs = append(allErrs, validatePodAffinityTerm(podAffinityTerm, allowInvalidLabelValueInSelector, fldPath.Index(i))...)\n\t}\n\treturn allErrs\n}","line":{"from":4177,"to":4184}} {"id":100002597,"name":"validateWeightedPodAffinityTerms","signature":"func validateWeightedPodAffinityTerms(weightedPodAffinityTerms []core.WeightedPodAffinityTerm, allowInvalidLabelValueInSelector bool, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateWeightedPodAffinityTerms tests that the specified weightedPodAffinityTerms fields have valid data\nfunc validateWeightedPodAffinityTerms(weightedPodAffinityTerms []core.WeightedPodAffinityTerm, allowInvalidLabelValueInSelector bool, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor j, weightedTerm := range weightedPodAffinityTerms {\n\t\tif weightedTerm.Weight \u003c= 0 || weightedTerm.Weight \u003e 100 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Index(j).Child(\"weight\"), weightedTerm.Weight, \"must be in the range 1-100\"))\n\t\t}\n\t\tallErrs = append(allErrs, validatePodAffinityTerm(weightedTerm.PodAffinityTerm, allowInvalidLabelValueInSelector, fldPath.Index(j).Child(\"podAffinityTerm\"))...)\n\t}\n\treturn allErrs\n}","line":{"from":4186,"to":4196}} {"id":100002598,"name":"validatePodAntiAffinity","signature":"func validatePodAntiAffinity(podAntiAffinity *core.PodAntiAffinity, allowInvalidLabelValueInSelector bool, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validatePodAntiAffinity tests that the specified podAntiAffinity fields have valid data\nfunc validatePodAntiAffinity(podAntiAffinity *core.PodAntiAffinity, allowInvalidLabelValueInSelector bool, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\t// TODO:Uncomment below code once RequiredDuringSchedulingRequiredDuringExecution is implemented.\n\t// if podAntiAffinity.RequiredDuringSchedulingRequiredDuringExecution != nil {\n\t//\tallErrs = append(allErrs, validatePodAffinityTerms(podAntiAffinity.RequiredDuringSchedulingRequiredDuringExecution, false,\n\t//\t\tfldPath.Child(\"requiredDuringSchedulingRequiredDuringExecution\"))...)\n\t// }\n\tif podAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution != nil {\n\t\tallErrs = append(allErrs, validatePodAffinityTerms(podAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution, allowInvalidLabelValueInSelector,\n\t\t\tfldPath.Child(\"requiredDuringSchedulingIgnoredDuringExecution\"))...)\n\t}\n\tif podAntiAffinity.PreferredDuringSchedulingIgnoredDuringExecution != nil {\n\t\tallErrs = append(allErrs, validateWeightedPodAffinityTerms(podAntiAffinity.PreferredDuringSchedulingIgnoredDuringExecution, allowInvalidLabelValueInSelector,\n\t\t\tfldPath.Child(\"preferredDuringSchedulingIgnoredDuringExecution\"))...)\n\t}\n\treturn allErrs\n}","line":{"from":4198,"to":4215}} {"id":100002599,"name":"validateNodeAffinity","signature":"func validateNodeAffinity(na *core.NodeAffinity, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateNodeAffinity tests that the specified nodeAffinity fields have valid data\nfunc validateNodeAffinity(na *core.NodeAffinity, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\t// TODO: Uncomment the next three lines once RequiredDuringSchedulingRequiredDuringExecution is implemented.\n\t// if na.RequiredDuringSchedulingRequiredDuringExecution != nil {\n\t//\tallErrs = append(allErrs, ValidateNodeSelector(na.RequiredDuringSchedulingRequiredDuringExecution, fldPath.Child(\"requiredDuringSchedulingRequiredDuringExecution\"))...)\n\t// }\n\tif na.RequiredDuringSchedulingIgnoredDuringExecution != nil {\n\t\tallErrs = append(allErrs, ValidateNodeSelector(na.RequiredDuringSchedulingIgnoredDuringExecution, fldPath.Child(\"requiredDuringSchedulingIgnoredDuringExecution\"))...)\n\t}\n\tif len(na.PreferredDuringSchedulingIgnoredDuringExecution) \u003e 0 {\n\t\tallErrs = append(allErrs, ValidatePreferredSchedulingTerms(na.PreferredDuringSchedulingIgnoredDuringExecution, fldPath.Child(\"preferredDuringSchedulingIgnoredDuringExecution\"))...)\n\t}\n\treturn allErrs\n}","line":{"from":4217,"to":4231}} {"id":100002600,"name":"validatePodAffinity","signature":"func validatePodAffinity(podAffinity *core.PodAffinity, allowInvalidLabelValueInSelector bool, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validatePodAffinity tests that the specified podAffinity fields have valid data\nfunc validatePodAffinity(podAffinity *core.PodAffinity, allowInvalidLabelValueInSelector bool, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\t// TODO:Uncomment below code once RequiredDuringSchedulingRequiredDuringExecution is implemented.\n\t// if podAffinity.RequiredDuringSchedulingRequiredDuringExecution != nil {\n\t//\tallErrs = append(allErrs, validatePodAffinityTerms(podAffinity.RequiredDuringSchedulingRequiredDuringExecution, false,\n\t//\t\tfldPath.Child(\"requiredDuringSchedulingRequiredDuringExecution\"))...)\n\t// }\n\tif podAffinity.RequiredDuringSchedulingIgnoredDuringExecution != nil {\n\t\tallErrs = append(allErrs, validatePodAffinityTerms(podAffinity.RequiredDuringSchedulingIgnoredDuringExecution, allowInvalidLabelValueInSelector,\n\t\t\tfldPath.Child(\"requiredDuringSchedulingIgnoredDuringExecution\"))...)\n\t}\n\tif podAffinity.PreferredDuringSchedulingIgnoredDuringExecution != nil {\n\t\tallErrs = append(allErrs, validateWeightedPodAffinityTerms(podAffinity.PreferredDuringSchedulingIgnoredDuringExecution, allowInvalidLabelValueInSelector,\n\t\t\tfldPath.Child(\"preferredDuringSchedulingIgnoredDuringExecution\"))...)\n\t}\n\treturn allErrs\n}","line":{"from":4233,"to":4250}} {"id":100002601,"name":"validateSeccompProfileField","signature":"func validateSeccompProfileField(sp *core.SeccompProfile, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateSeccompProfileField(sp *core.SeccompProfile, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif sp == nil {\n\t\treturn allErrs\n\t}\n\n\tif err := validateSeccompProfileType(fldPath.Child(\"type\"), sp.Type); err != nil {\n\t\tallErrs = append(allErrs, err)\n\t}\n\n\tif sp.Type == core.SeccompProfileTypeLocalhost {\n\t\tif sp.LocalhostProfile == nil {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"localhostProfile\"), \"must be set when seccomp type is Localhost\"))\n\t\t} else {\n\t\t\tallErrs = append(allErrs, validateLocalDescendingPath(*sp.LocalhostProfile, fldPath.Child(\"localhostProfile\"))...)\n\t\t}\n\t} else {\n\t\tif sp.LocalhostProfile != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"localhostProfile\"), sp, \"can only be set when seccomp type is Localhost\"))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":4252,"to":4275}} {"id":100002602,"name":"ValidateSeccompProfile","signature":"func ValidateSeccompProfile(p string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func ValidateSeccompProfile(p string, fldPath *field.Path) field.ErrorList {\n\tif p == core.SeccompProfileRuntimeDefault || p == core.DeprecatedSeccompProfileDockerDefault {\n\t\treturn nil\n\t}\n\tif p == v1.SeccompProfileNameUnconfined {\n\t\treturn nil\n\t}\n\tif strings.HasPrefix(p, v1.SeccompLocalhostProfileNamePrefix) {\n\t\treturn validateLocalDescendingPath(strings.TrimPrefix(p, v1.SeccompLocalhostProfileNamePrefix), fldPath)\n\t}\n\treturn field.ErrorList{field.Invalid(fldPath, p, \"must be a valid seccomp profile\")}\n}","line":{"from":4277,"to":4288}} {"id":100002603,"name":"ValidateSeccompPodAnnotations","signature":"func ValidateSeccompPodAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func ValidateSeccompPodAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif p, exists := annotations[core.SeccompPodAnnotationKey]; exists {\n\t\tallErrs = append(allErrs, ValidateSeccompProfile(p, fldPath.Child(core.SeccompPodAnnotationKey))...)\n\t}\n\tfor k, p := range annotations {\n\t\tif strings.HasPrefix(k, core.SeccompContainerAnnotationKeyPrefix) {\n\t\t\tallErrs = append(allErrs, ValidateSeccompProfile(p, fldPath.Child(k))...)\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":4290,"to":4302}} {"id":100002604,"name":"validateSeccompProfileType","signature":"func validateSeccompProfileType(fldPath *field.Path, seccompProfileType core.SeccompProfileType) *field.Error","file":"pkg/apis/core/validation/validation.go","code":"// ValidateSeccompProfileType tests that the argument is a valid SeccompProfileType.\nfunc validateSeccompProfileType(fldPath *field.Path, seccompProfileType core.SeccompProfileType) *field.Error {\n\tswitch seccompProfileType {\n\tcase core.SeccompProfileTypeLocalhost, core.SeccompProfileTypeRuntimeDefault, core.SeccompProfileTypeUnconfined:\n\t\treturn nil\n\tcase \"\":\n\t\treturn field.Required(fldPath, \"type is required when seccompProfile is set\")\n\tdefault:\n\t\treturn field.NotSupported(fldPath, seccompProfileType, []string{string(core.SeccompProfileTypeLocalhost), string(core.SeccompProfileTypeRuntimeDefault), string(core.SeccompProfileTypeUnconfined)})\n\t}\n}","line":{"from":4304,"to":4314}} {"id":100002605,"name":"ValidateAppArmorPodAnnotations","signature":"func ValidateAppArmorPodAnnotations(annotations map[string]string, spec *core.PodSpec, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func ValidateAppArmorPodAnnotations(annotations map[string]string, spec *core.PodSpec, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor k, p := range annotations {\n\t\tif !strings.HasPrefix(k, v1.AppArmorBetaContainerAnnotationKeyPrefix) {\n\t\t\tcontinue\n\t\t}\n\t\tcontainerName := strings.TrimPrefix(k, v1.AppArmorBetaContainerAnnotationKeyPrefix)\n\t\tif !podSpecHasContainer(spec, containerName) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Key(k), containerName, \"container not found\"))\n\t\t}\n\n\t\tif err := ValidateAppArmorProfileFormat(p); err != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Key(k), p, err.Error()))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":4316,"to":4333}} {"id":100002606,"name":"ValidateAppArmorProfileFormat","signature":"func ValidateAppArmorProfileFormat(profile string) error","file":"pkg/apis/core/validation/validation.go","code":"func ValidateAppArmorProfileFormat(profile string) error {\n\tif profile == \"\" || profile == v1.AppArmorBetaProfileRuntimeDefault || profile == v1.AppArmorBetaProfileNameUnconfined {\n\t\treturn nil\n\t}\n\tif !strings.HasPrefix(profile, v1.AppArmorBetaProfileNamePrefix) {\n\t\treturn fmt.Errorf(\"invalid AppArmor profile name: %q\", profile)\n\t}\n\treturn nil\n}","line":{"from":4335,"to":4343}} {"id":100002607,"name":"podSpecHasContainer","signature":"func podSpecHasContainer(spec *core.PodSpec, containerName string) bool","file":"pkg/apis/core/validation/validation.go","code":"func podSpecHasContainer(spec *core.PodSpec, containerName string) bool {\n\tvar hasContainer bool\n\tpodshelper.VisitContainersWithPath(spec, field.NewPath(\"spec\"), func(c *core.Container, _ *field.Path) bool {\n\t\tif c.Name == containerName {\n\t\t\thasContainer = true\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t})\n\treturn hasContainer\n}","line":{"from":4345,"to":4355}} {"id":100002608,"name":"IsValidSysctlName","signature":"func IsValidSysctlName(name string) bool","file":"pkg/apis/core/validation/validation.go","code":"// IsValidSysctlName checks that the given string is a valid sysctl name,\n// i.e. matches SysctlContainSlashFmt.\n// More info:\n//\n//\thttps://man7.org/linux/man-pages/man8/sysctl.8.html\n//\thttps://man7.org/linux/man-pages/man5/sysctl.d.5.html\nfunc IsValidSysctlName(name string) bool {\n\tif len(name) \u003e SysctlMaxLength {\n\t\treturn false\n\t}\n\treturn sysctlContainSlashRegexp.MatchString(name)\n}","line":{"from":4370,"to":4381}} {"id":100002609,"name":"validateSysctls","signature":"func validateSysctls(sysctls []core.Sysctl, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateSysctls(sysctls []core.Sysctl, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tnames := make(map[string]struct{})\n\tfor i, s := range sysctls {\n\t\tif len(s.Name) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Index(i).Child(\"name\"), \"\"))\n\t\t} else if !IsValidSysctlName(s.Name) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Index(i).Child(\"name\"), s.Name, fmt.Sprintf(\"must have at most %d characters and match regex %s\", SysctlMaxLength, sysctlContainSlashRegexp)))\n\t\t} else if _, ok := names[s.Name]; ok {\n\t\t\tallErrs = append(allErrs, field.Duplicate(fldPath.Index(i).Child(\"name\"), s.Name))\n\t\t}\n\t\tnames[s.Name] = struct{}{}\n\t}\n\treturn allErrs\n}","line":{"from":4383,"to":4397}} {"id":100002610,"name":"ValidatePodSecurityContext","signature":"func ValidatePodSecurityContext(securityContext *core.PodSecurityContext, spec *core.PodSpec, specPath, fldPath *field.Path, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidatePodSecurityContext test that the specified PodSecurityContext has valid data.\nfunc ValidatePodSecurityContext(securityContext *core.PodSecurityContext, spec *core.PodSpec, specPath, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif securityContext != nil {\n\t\tallErrs = append(allErrs, validateHostNetwork(securityContext.HostNetwork, spec.Containers, specPath.Child(\"containers\"))...)\n\t\tif securityContext.FSGroup != nil {\n\t\t\tfor _, msg := range validation.IsValidGroupID(*securityContext.FSGroup) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"fsGroup\"), *(securityContext.FSGroup), msg))\n\t\t\t}\n\t\t}\n\t\tif securityContext.RunAsUser != nil {\n\t\t\tfor _, msg := range validation.IsValidUserID(*securityContext.RunAsUser) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"runAsUser\"), *(securityContext.RunAsUser), msg))\n\t\t\t}\n\t\t}\n\t\tif securityContext.RunAsGroup != nil {\n\t\t\tfor _, msg := range validation.IsValidGroupID(*securityContext.RunAsGroup) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"runAsGroup\"), *(securityContext.RunAsGroup), msg))\n\t\t\t}\n\t\t}\n\t\tfor g, gid := range securityContext.SupplementalGroups {\n\t\t\tfor _, msg := range validation.IsValidGroupID(gid) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"supplementalGroups\").Index(g), gid, msg))\n\t\t\t}\n\t\t}\n\t\tif securityContext.ShareProcessNamespace != nil \u0026\u0026 securityContext.HostPID \u0026\u0026 *securityContext.ShareProcessNamespace {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"shareProcessNamespace\"), *securityContext.ShareProcessNamespace, \"ShareProcessNamespace and HostPID cannot both be enabled\"))\n\t\t}\n\n\t\tif len(securityContext.Sysctls) != 0 {\n\t\t\tallErrs = append(allErrs, validateSysctls(securityContext.Sysctls, fldPath.Child(\"sysctls\"))...)\n\t\t}\n\n\t\tif securityContext.FSGroupChangePolicy != nil {\n\t\t\tallErrs = append(allErrs, validateFSGroupChangePolicy(securityContext.FSGroupChangePolicy, fldPath.Child(\"fsGroupChangePolicy\"))...)\n\t\t}\n\n\t\tallErrs = append(allErrs, validateSeccompProfileField(securityContext.SeccompProfile, fldPath.Child(\"seccompProfile\"))...)\n\t\tallErrs = append(allErrs, validateWindowsSecurityContextOptions(securityContext.WindowsOptions, fldPath.Child(\"windowsOptions\"))...)\n\t}\n\n\treturn allErrs\n}","line":{"from":4399,"to":4442}} {"id":100002611,"name":"ValidateContainerUpdates","signature":"func ValidateContainerUpdates(newContainers, oldContainers []core.Container, fldPath *field.Path) (allErrs field.ErrorList, stop bool)","file":"pkg/apis/core/validation/validation.go","code":"func ValidateContainerUpdates(newContainers, oldContainers []core.Container, fldPath *field.Path) (allErrs field.ErrorList, stop bool) {\n\tallErrs = field.ErrorList{}\n\tif len(newContainers) != len(oldContainers) {\n\t\t// TODO: Pinpoint the specific container that causes the invalid error after we have strategic merge diff\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath, \"pod updates may not add or remove containers\"))\n\t\treturn allErrs, true\n\t}\n\n\t// validate updated container images\n\tfor i, ctr := range newContainers {\n\t\tif len(ctr.Image) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Index(i).Child(\"image\"), \"\"))\n\t\t}\n\t\t// this is only called from ValidatePodUpdate so its safe to check leading/trailing whitespace.\n\t\tif len(strings.TrimSpace(ctr.Image)) != len(ctr.Image) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Index(i).Child(\"image\"), ctr.Image, \"must not have leading or trailing whitespace\"))\n\t\t}\n\t}\n\treturn allErrs, false\n}","line":{"from":4444,"to":4463}} {"id":100002612,"name":"ValidatePodCreate","signature":"func ValidatePodCreate(pod *core.Pod, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidatePodCreate validates a pod in the context of its initial create\nfunc ValidatePodCreate(pod *core.Pod, opts PodValidationOptions) field.ErrorList {\n\tallErrs := validatePodMetadataAndSpec(pod, opts)\n\n\tfldPath := field.NewPath(\"spec\")\n\t// EphemeralContainers can only be set on update using the ephemeralcontainers subresource\n\tif len(pod.Spec.EphemeralContainers) \u003e 0 {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"ephemeralContainers\"), \"cannot be set on create\"))\n\t}\n\t// A Pod cannot be assigned a Node if there are remaining scheduling gates.\n\tif pod.Spec.NodeName != \"\" \u0026\u0026 len(pod.Spec.SchedulingGates) != 0 {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"nodeName\"), \"cannot be set until all schedulingGates have been cleared\"))\n\t}\n\tallErrs = append(allErrs, validateSeccompAnnotationsAndFields(pod.ObjectMeta, \u0026pod.Spec, fldPath)...)\n\n\treturn allErrs\n}","line":{"from":4465,"to":4481}} {"id":100002613,"name":"validateSeccompAnnotationsAndFields","signature":"func validateSeccompAnnotationsAndFields(objectMeta metav1.ObjectMeta, podSpec *core.PodSpec, specPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateSeccompAnnotationsAndFields iterates through all containers and ensure that when both seccompProfile and seccomp annotations exist they match.\nfunc validateSeccompAnnotationsAndFields(objectMeta metav1.ObjectMeta, podSpec *core.PodSpec, specPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif podSpec.SecurityContext != nil \u0026\u0026 podSpec.SecurityContext.SeccompProfile != nil {\n\t\t// If both seccomp annotations and fields are specified, the values must match.\n\t\tif annotation, found := objectMeta.Annotations[v1.SeccompPodAnnotationKey]; found {\n\t\t\tseccompPath := specPath.Child(\"securityContext\").Child(\"seccompProfile\")\n\t\t\terr := validateSeccompAnnotationsAndFieldsMatch(annotation, podSpec.SecurityContext.SeccompProfile, seccompPath)\n\t\t\tif err != nil {\n\t\t\t\tallErrs = append(allErrs, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tpodshelper.VisitContainersWithPath(podSpec, specPath, func(c *core.Container, cFldPath *field.Path) bool {\n\t\tvar field *core.SeccompProfile\n\t\tif c.SecurityContext != nil {\n\t\t\tfield = c.SecurityContext.SeccompProfile\n\t\t}\n\n\t\tif field == nil {\n\t\t\treturn true\n\t\t}\n\n\t\tkey := v1.SeccompContainerAnnotationKeyPrefix + c.Name\n\t\tif annotation, found := objectMeta.Annotations[key]; found {\n\t\t\tseccompPath := cFldPath.Child(\"securityContext\").Child(\"seccompProfile\")\n\t\t\terr := validateSeccompAnnotationsAndFieldsMatch(annotation, field, seccompPath)\n\t\t\tif err != nil {\n\t\t\t\tallErrs = append(allErrs, err)\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n\n\treturn allErrs\n}","line":{"from":4483,"to":4520}} {"id":100002614,"name":"validateSeccompAnnotationsAndFieldsMatch","signature":"func validateSeccompAnnotationsAndFieldsMatch(annotationValue string, seccompField *core.SeccompProfile, fldPath *field.Path) *field.Error","file":"pkg/apis/core/validation/validation.go","code":"func validateSeccompAnnotationsAndFieldsMatch(annotationValue string, seccompField *core.SeccompProfile, fldPath *field.Path) *field.Error {\n\tif seccompField == nil {\n\t\treturn nil\n\t}\n\n\tswitch seccompField.Type {\n\tcase core.SeccompProfileTypeUnconfined:\n\t\tif annotationValue != v1.SeccompProfileNameUnconfined {\n\t\t\treturn field.Forbidden(fldPath.Child(\"type\"), \"seccomp type in annotation and field must match\")\n\t\t}\n\n\tcase core.SeccompProfileTypeRuntimeDefault:\n\t\tif annotationValue != v1.SeccompProfileRuntimeDefault \u0026\u0026 annotationValue != v1.DeprecatedSeccompProfileDockerDefault {\n\t\t\treturn field.Forbidden(fldPath.Child(\"type\"), \"seccomp type in annotation and field must match\")\n\t\t}\n\n\tcase core.SeccompProfileTypeLocalhost:\n\t\tif !strings.HasPrefix(annotationValue, v1.SeccompLocalhostProfileNamePrefix) {\n\t\t\treturn field.Forbidden(fldPath.Child(\"type\"), \"seccomp type in annotation and field must match\")\n\t\t} else if seccompField.LocalhostProfile == nil || strings.TrimPrefix(annotationValue, v1.SeccompLocalhostProfileNamePrefix) != *seccompField.LocalhostProfile {\n\t\t\treturn field.Forbidden(fldPath.Child(\"localhostProfile\"), \"seccomp profile in annotation and field must match\")\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":4522,"to":4547}} {"id":100002615,"name":"ValidatePodUpdate","signature":"func ValidatePodUpdate(newPod, oldPod *core.Pod, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidatePodUpdate tests to see if the update is legal for an end user to make. newPod is updated with fields\n// that cannot be changed.\nfunc ValidatePodUpdate(newPod, oldPod *core.Pod, opts PodValidationOptions) field.ErrorList {\n\tfldPath := field.NewPath(\"metadata\")\n\tallErrs := ValidateObjectMetaUpdate(\u0026newPod.ObjectMeta, \u0026oldPod.ObjectMeta, fldPath)\n\tallErrs = append(allErrs, validatePodMetadataAndSpec(newPod, opts)...)\n\tallErrs = append(allErrs, ValidatePodSpecificAnnotationUpdates(newPod, oldPod, fldPath.Child(\"annotations\"), opts)...)\n\tspecPath := field.NewPath(\"spec\")\n\n\t// validate updateable fields:\n\t// 1. spec.containers[*].image\n\t// 2. spec.initContainers[*].image\n\t// 3. spec.activeDeadlineSeconds\n\t// 4. spec.terminationGracePeriodSeconds\n\t// 5. spec.schedulingGates\n\n\tcontainerErrs, stop := ValidateContainerUpdates(newPod.Spec.Containers, oldPod.Spec.Containers, specPath.Child(\"containers\"))\n\tallErrs = append(allErrs, containerErrs...)\n\tif stop {\n\t\treturn allErrs\n\t}\n\tcontainerErrs, stop = ValidateContainerUpdates(newPod.Spec.InitContainers, oldPod.Spec.InitContainers, specPath.Child(\"initContainers\"))\n\tallErrs = append(allErrs, containerErrs...)\n\tif stop {\n\t\treturn allErrs\n\t}\n\n\t// validate updated spec.activeDeadlineSeconds. two types of updates are allowed:\n\t// 1. from nil to a positive value\n\t// 2. from a positive value to a lesser, non-negative value\n\tif newPod.Spec.ActiveDeadlineSeconds != nil {\n\t\tnewActiveDeadlineSeconds := *newPod.Spec.ActiveDeadlineSeconds\n\t\tif newActiveDeadlineSeconds \u003c 0 || newActiveDeadlineSeconds \u003e math.MaxInt32 {\n\t\t\tallErrs = append(allErrs, field.Invalid(specPath.Child(\"activeDeadlineSeconds\"), newActiveDeadlineSeconds, validation.InclusiveRangeError(0, math.MaxInt32)))\n\t\t\treturn allErrs\n\t\t}\n\t\tif oldPod.Spec.ActiveDeadlineSeconds != nil {\n\t\t\toldActiveDeadlineSeconds := *oldPod.Spec.ActiveDeadlineSeconds\n\t\t\tif oldActiveDeadlineSeconds \u003c newActiveDeadlineSeconds {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(specPath.Child(\"activeDeadlineSeconds\"), newActiveDeadlineSeconds, \"must be less than or equal to previous value\"))\n\t\t\t\treturn allErrs\n\t\t\t}\n\t\t}\n\t} else if oldPod.Spec.ActiveDeadlineSeconds != nil {\n\t\tallErrs = append(allErrs, field.Invalid(specPath.Child(\"activeDeadlineSeconds\"), newPod.Spec.ActiveDeadlineSeconds, \"must not update from a positive integer to nil value\"))\n\t}\n\n\t// Allow only additions to tolerations updates.\n\tallErrs = append(allErrs, validateOnlyAddedTolerations(newPod.Spec.Tolerations, oldPod.Spec.Tolerations, specPath.Child(\"tolerations\"))...)\n\n\t// Allow only deletions to schedulingGates updates.\n\tallErrs = append(allErrs, validateOnlyDeletedSchedulingGates(newPod.Spec.SchedulingGates, oldPod.Spec.SchedulingGates, specPath.Child(\"schedulingGates\"))...)\n\n\t// the last thing to check is pod spec equality. If the pod specs are equal, then we can simply return the errors we have\n\t// so far and save the cost of a deep copy.\n\tif apiequality.Semantic.DeepEqual(newPod.Spec, oldPod.Spec) {\n\t\treturn allErrs\n\t}\n\n\t//TODO(vinaykul,InPlacePodVerticalScaling): With KEP 2527, we can rely on persistence of PodStatus.QOSClass\n\t// We can use PodStatus.QOSClass instead of GetPodQOS here, in kubelet, and elsewhere, as PodStatus.QOSClass\n\t// does not change once it is bootstrapped in podCreate. This needs to be addressed before beta as a\n\t// separate PR covering all uses of GetPodQOS. With that change, we can drop the below block.\n\t// Ref: https://github.com/kubernetes/kubernetes/pull/102884#discussion_r1093790446\n\t// Ref: https://github.com/kubernetes/kubernetes/pull/102884/#discussion_r663280487\n\tif utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) {\n\t\t// reject attempts to change pod qos\n\t\toldQoS := qos.GetPodQOS(oldPod)\n\t\tnewQoS := qos.GetPodQOS(newPod)\n\t\tif newQoS != oldQoS {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, newQoS, \"Pod QoS is immutable\"))\n\t\t}\n\t}\n\n\t// handle updateable fields by munging those fields prior to deep equal comparison.\n\tmungedPodSpec := *newPod.Spec.DeepCopy()\n\t// munge spec.containers[*].image\n\tvar newContainers []core.Container\n\tfor ix, container := range mungedPodSpec.Containers {\n\t\tcontainer.Image = oldPod.Spec.Containers[ix].Image // +k8s:verify-mutation:reason=clone\n\t\t// When the feature-gate is turned off, any new requests attempting to update CPU or memory\n\t\t// resource values will result in validation failure.\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) {\n\t\t\t// Resources are mutable for CPU \u0026 memory only\n\t\t\t// - user can now modify Resources to express new desired Resources\n\t\t\tmungeCpuMemResources := func(resourceList, oldResourceList core.ResourceList) core.ResourceList {\n\t\t\t\tif oldResourceList == nil {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\tvar mungedResourceList core.ResourceList\n\t\t\t\tif resourceList == nil {\n\t\t\t\t\tmungedResourceList = make(core.ResourceList)\n\t\t\t\t} else {\n\t\t\t\t\tmungedResourceList = resourceList.DeepCopy()\n\t\t\t\t}\n\t\t\t\tdelete(mungedResourceList, core.ResourceCPU)\n\t\t\t\tdelete(mungedResourceList, core.ResourceMemory)\n\t\t\t\tif cpu, found := oldResourceList[core.ResourceCPU]; found {\n\t\t\t\t\tmungedResourceList[core.ResourceCPU] = cpu\n\t\t\t\t}\n\t\t\t\tif mem, found := oldResourceList[core.ResourceMemory]; found {\n\t\t\t\t\tmungedResourceList[core.ResourceMemory] = mem\n\t\t\t\t}\n\t\t\t\treturn mungedResourceList\n\t\t\t}\n\t\t\tlim := mungeCpuMemResources(container.Resources.Limits, oldPod.Spec.Containers[ix].Resources.Limits)\n\t\t\treq := mungeCpuMemResources(container.Resources.Requests, oldPod.Spec.Containers[ix].Resources.Requests)\n\t\t\tcontainer.Resources = core.ResourceRequirements{Limits: lim, Requests: req}\n\t\t}\n\t\tnewContainers = append(newContainers, container)\n\t}\n\tmungedPodSpec.Containers = newContainers\n\t// munge spec.initContainers[*].image\n\tvar newInitContainers []core.Container\n\tfor ix, container := range mungedPodSpec.InitContainers {\n\t\tcontainer.Image = oldPod.Spec.InitContainers[ix].Image // +k8s:verify-mutation:reason=clone\n\t\tnewInitContainers = append(newInitContainers, container)\n\t}\n\tmungedPodSpec.InitContainers = newInitContainers\n\t// munge spec.activeDeadlineSeconds\n\tmungedPodSpec.ActiveDeadlineSeconds = nil\n\tif oldPod.Spec.ActiveDeadlineSeconds != nil {\n\t\tactiveDeadlineSeconds := *oldPod.Spec.ActiveDeadlineSeconds\n\t\tmungedPodSpec.ActiveDeadlineSeconds = \u0026activeDeadlineSeconds\n\t}\n\t// munge spec.schedulingGates\n\tmungedPodSpec.SchedulingGates = oldPod.Spec.SchedulingGates // +k8s:verify-mutation:reason=clone\n\t// tolerations are checked before the deep copy, so munge those too\n\tmungedPodSpec.Tolerations = oldPod.Spec.Tolerations // +k8s:verify-mutation:reason=clone\n\n\t// Relax validation of immutable fields to allow it to be set to 1 if it was previously negative.\n\tif oldPod.Spec.TerminationGracePeriodSeconds != nil \u0026\u0026 *oldPod.Spec.TerminationGracePeriodSeconds \u003c 0 \u0026\u0026\n\t\tmungedPodSpec.TerminationGracePeriodSeconds != nil \u0026\u0026 *mungedPodSpec.TerminationGracePeriodSeconds == 1 {\n\t\tmungedPodSpec.TerminationGracePeriodSeconds = oldPod.Spec.TerminationGracePeriodSeconds // +k8s:verify-mutation:reason=clone\n\t}\n\n\t// Handle validations specific to gated pods.\n\tpodIsGated := len(oldPod.Spec.SchedulingGates) \u003e 0\n\tif opts.AllowMutableNodeSelectorAndNodeAffinity \u0026\u0026 podIsGated {\n\t\t// Additions to spec.nodeSelector are allowed (no deletions or mutations) for gated pods.\n\t\tif !apiequality.Semantic.DeepEqual(mungedPodSpec.NodeSelector, oldPod.Spec.NodeSelector) {\n\t\t\tallErrs = append(allErrs, validateNodeSelectorMutation(specPath.Child(\"nodeSelector\"), mungedPodSpec.NodeSelector, oldPod.Spec.NodeSelector)...)\n\t\t\tmungedPodSpec.NodeSelector = oldPod.Spec.NodeSelector // +k8s:verify-mutation:reason=clone\n\t\t}\n\n\t\t// Validate node affinity mutations.\n\t\tvar oldNodeAffinity *core.NodeAffinity\n\t\tif oldPod.Spec.Affinity != nil {\n\t\t\toldNodeAffinity = oldPod.Spec.Affinity.NodeAffinity // +k8s:verify-mutation:reason=clone\n\t\t}\n\n\t\tvar mungedNodeAffinity *core.NodeAffinity\n\t\tif mungedPodSpec.Affinity != nil {\n\t\t\tmungedNodeAffinity = mungedPodSpec.Affinity.NodeAffinity // +k8s:verify-mutation:reason=clone\n\t\t}\n\n\t\tif !apiequality.Semantic.DeepEqual(oldNodeAffinity, mungedNodeAffinity) {\n\t\t\tallErrs = append(allErrs, validateNodeAffinityMutation(specPath.Child(\"affinity\").Child(\"nodeAffinity\"), mungedNodeAffinity, oldNodeAffinity)...)\n\t\t\tswitch {\n\t\t\tcase mungedPodSpec.Affinity == nil \u0026\u0026 oldNodeAffinity == nil:\n\t\t\t\t// already effectively nil, no change needed\n\t\t\tcase mungedPodSpec.Affinity == nil \u0026\u0026 oldNodeAffinity != nil:\n\t\t\t\tmungedPodSpec.Affinity = \u0026core.Affinity{NodeAffinity: oldNodeAffinity} // +k8s:verify-mutation:reason=clone\n\t\t\tcase mungedPodSpec.Affinity != nil \u0026\u0026 oldPod.Spec.Affinity == nil \u0026\u0026\n\t\t\t\tmungedPodSpec.Affinity.PodAntiAffinity == nil \u0026\u0026 mungedPodSpec.Affinity.PodAffinity == nil:\n\t\t\t\t// We ensure no other fields are being changed, but the NodeAffinity. If that's the case, and the\n\t\t\t\t// old pod's affinity is nil, we set the mungedPodSpec's affinity to nil.\n\t\t\t\tmungedPodSpec.Affinity = nil // +k8s:verify-mutation:reason=clone\n\t\t\tdefault:\n\t\t\t\t// The node affinity is being updated and the old pod Affinity is not nil.\n\t\t\t\t// We set the mungedPodSpec's node affinity to the old pod's node affinity.\n\t\t\t\tmungedPodSpec.Affinity.NodeAffinity = oldNodeAffinity // +k8s:verify-mutation:reason=clone\n\t\t\t}\n\t\t}\n\t}\n\n\tif !apiequality.Semantic.DeepEqual(mungedPodSpec, oldPod.Spec) {\n\t\t// This diff isn't perfect, but it's a helluva lot better an \"I'm not going to tell you what the difference is\".\n\t\t// TODO: Pinpoint the specific field that causes the invalid error after we have strategic merge diff\n\t\tspecDiff := cmp.Diff(oldPod.Spec, mungedPodSpec)\n\t\terrs := field.Forbidden(specPath, fmt.Sprintf(\"pod updates may not change fields other than %s\\n%v\", strings.Join(updatablePodSpecFieldsNoResources, \",\"), specDiff))\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) {\n\t\t\terrs = field.Forbidden(specPath, fmt.Sprintf(\"pod updates may not change fields other than %s\\n%v\", strings.Join(updatablePodSpecFields, \",\"), specDiff))\n\t\t}\n\t\tallErrs = append(allErrs, errs)\n\t}\n\treturn allErrs\n}","line":{"from":4567,"to":4754}} {"id":100002616,"name":"ValidateContainerStateTransition","signature":"func ValidateContainerStateTransition(newStatuses, oldStatuses []core.ContainerStatus, fldpath *field.Path, restartPolicy core.RestartPolicy) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateContainerStateTransition test to if any illegal container state transitions are being attempted\nfunc ValidateContainerStateTransition(newStatuses, oldStatuses []core.ContainerStatus, fldpath *field.Path, restartPolicy core.RestartPolicy) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\t// If we should always restart, containers are allowed to leave the terminated state\n\tif restartPolicy == core.RestartPolicyAlways {\n\t\treturn allErrs\n\t}\n\tfor i, oldStatus := range oldStatuses {\n\t\t// Skip any container that is not terminated\n\t\tif oldStatus.State.Terminated == nil {\n\t\t\tcontinue\n\t\t}\n\t\t// Skip any container that failed but is allowed to restart\n\t\tif oldStatus.State.Terminated.ExitCode != 0 \u0026\u0026 restartPolicy == core.RestartPolicyOnFailure {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, newStatus := range newStatuses {\n\t\t\tif oldStatus.Name == newStatus.Name \u0026\u0026 newStatus.State.Terminated == nil {\n\t\t\t\tallErrs = append(allErrs, field.Forbidden(fldpath.Index(i).Child(\"state\"), \"may not be transitioned to non-terminated state\"))\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":4756,"to":4779}} {"id":100002617,"name":"ValidatePodStatusUpdate","signature":"func ValidatePodStatusUpdate(newPod, oldPod *core.Pod, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidatePodStatusUpdate checks for changes to status that shouldn't occur in normal operation.\nfunc ValidatePodStatusUpdate(newPod, oldPod *core.Pod, opts PodValidationOptions) field.ErrorList {\n\tfldPath := field.NewPath(\"metadata\")\n\tallErrs := ValidateObjectMetaUpdate(\u0026newPod.ObjectMeta, \u0026oldPod.ObjectMeta, fldPath)\n\tallErrs = append(allErrs, ValidatePodSpecificAnnotationUpdates(newPod, oldPod, fldPath.Child(\"annotations\"), opts)...)\n\tallErrs = append(allErrs, validatePodConditions(newPod.Status.Conditions, fldPath.Child(\"conditions\"))...)\n\n\tfldPath = field.NewPath(\"status\")\n\tif newPod.Spec.NodeName != oldPod.Spec.NodeName {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"nodeName\"), \"may not be changed directly\"))\n\t}\n\n\tif newPod.Status.NominatedNodeName != oldPod.Status.NominatedNodeName \u0026\u0026 len(newPod.Status.NominatedNodeName) \u003e 0 {\n\t\tfor _, msg := range ValidateNodeName(newPod.Status.NominatedNodeName, false) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"nominatedNodeName\"), newPod.Status.NominatedNodeName, msg))\n\t\t}\n\t}\n\n\t// If pod should not restart, make sure the status update does not transition\n\t// any terminated containers to a non-terminated state.\n\tallErrs = append(allErrs, ValidateContainerStateTransition(newPod.Status.ContainerStatuses, oldPod.Status.ContainerStatuses, fldPath.Child(\"containerStatuses\"), oldPod.Spec.RestartPolicy)...)\n\tallErrs = append(allErrs, ValidateContainerStateTransition(newPod.Status.InitContainerStatuses, oldPod.Status.InitContainerStatuses, fldPath.Child(\"initContainerStatuses\"), oldPod.Spec.RestartPolicy)...)\n\t// The kubelet will never restart ephemeral containers, so treat them like they have an implicit RestartPolicyNever.\n\tallErrs = append(allErrs, ValidateContainerStateTransition(newPod.Status.EphemeralContainerStatuses, oldPod.Status.EphemeralContainerStatuses, fldPath.Child(\"ephemeralContainerStatuses\"), core.RestartPolicyNever)...)\n\n\tif newIPErrs := validatePodIPs(newPod); len(newIPErrs) \u003e 0 {\n\t\tallErrs = append(allErrs, newIPErrs...)\n\t}\n\n\treturn allErrs\n}","line":{"from":4781,"to":4811}} {"id":100002618,"name":"validatePodConditions","signature":"func validatePodConditions(conditions []core.PodCondition, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validatePodConditions tests if the custom pod conditions are valid.\nfunc validatePodConditions(conditions []core.PodCondition, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tsystemConditions := sets.NewString(string(core.PodScheduled), string(core.PodReady), string(core.PodInitialized))\n\tfor i, condition := range conditions {\n\t\tif systemConditions.Has(string(condition.Type)) {\n\t\t\tcontinue\n\t\t}\n\t\tallErrs = append(allErrs, ValidateQualifiedName(string(condition.Type), fldPath.Index(i).Child(\"Type\"))...)\n\t}\n\treturn allErrs\n}","line":{"from":4813,"to":4824}} {"id":100002619,"name":"ValidatePodEphemeralContainersUpdate","signature":"func ValidatePodEphemeralContainersUpdate(newPod, oldPod *core.Pod, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidatePodEphemeralContainersUpdate tests that a user update to EphemeralContainers is valid.\n// newPod and oldPod must only differ in their EphemeralContainers.\nfunc ValidatePodEphemeralContainersUpdate(newPod, oldPod *core.Pod, opts PodValidationOptions) field.ErrorList {\n\t// Part 1: Validate newPod's spec and updates to metadata\n\tfldPath := field.NewPath(\"metadata\")\n\tallErrs := ValidateObjectMetaUpdate(\u0026newPod.ObjectMeta, \u0026oldPod.ObjectMeta, fldPath)\n\tallErrs = append(allErrs, validatePodMetadataAndSpec(newPod, opts)...)\n\tallErrs = append(allErrs, ValidatePodSpecificAnnotationUpdates(newPod, oldPod, fldPath.Child(\"annotations\"), opts)...)\n\n\t// static pods don't support ephemeral containers #113935\n\tif _, ok := oldPod.Annotations[core.MirrorPodAnnotationKey]; ok {\n\t\treturn field.ErrorList{field.Forbidden(field.NewPath(\"\"), \"static pods do not support ephemeral containers\")}\n\t}\n\n\t// Part 2: Validate that the changes between oldPod.Spec.EphemeralContainers and\n\t// newPod.Spec.EphemeralContainers are allowed.\n\t//\n\t// Existing EphemeralContainers may not be changed. Order isn't preserved by patch, so check each individually.\n\tnewContainerIndex := make(map[string]*core.EphemeralContainer)\n\tspecPath := field.NewPath(\"spec\").Child(\"ephemeralContainers\")\n\tfor i := range newPod.Spec.EphemeralContainers {\n\t\tnewContainerIndex[newPod.Spec.EphemeralContainers[i].Name] = \u0026newPod.Spec.EphemeralContainers[i]\n\t}\n\tfor _, old := range oldPod.Spec.EphemeralContainers {\n\t\tif new, ok := newContainerIndex[old.Name]; !ok {\n\t\t\tallErrs = append(allErrs, field.Forbidden(specPath, fmt.Sprintf(\"existing ephemeral containers %q may not be removed\\n\", old.Name)))\n\t\t} else if !apiequality.Semantic.DeepEqual(old, *new) {\n\t\t\tspecDiff := cmp.Diff(old, *new)\n\t\t\tallErrs = append(allErrs, field.Forbidden(specPath, fmt.Sprintf(\"existing ephemeral containers %q may not be changed\\n%v\", old.Name, specDiff)))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":4826,"to":4859}} {"id":100002620,"name":"ValidatePodBinding","signature":"func ValidatePodBinding(binding *core.Binding) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidatePodBinding tests if required fields in the pod binding are legal.\nfunc ValidatePodBinding(binding *core.Binding) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(binding.Target.Kind) != 0 \u0026\u0026 binding.Target.Kind != \"Node\" {\n\t\t// TODO: When validation becomes versioned, this gets more complicated.\n\t\tallErrs = append(allErrs, field.NotSupported(field.NewPath(\"target\", \"kind\"), binding.Target.Kind, []string{\"Node\", \"\u003cempty\u003e\"}))\n\t}\n\tif len(binding.Target.Name) == 0 {\n\t\t// TODO: When validation becomes versioned, this gets more complicated.\n\t\tallErrs = append(allErrs, field.Required(field.NewPath(\"target\", \"name\"), \"\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":4861,"to":4875}} {"id":100002621,"name":"ValidatePodTemplate","signature":"func ValidatePodTemplate(pod *core.PodTemplate, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidatePodTemplate tests if required fields in the pod template are set.\nfunc ValidatePodTemplate(pod *core.PodTemplate, opts PodValidationOptions) field.ErrorList {\n\tallErrs := ValidateObjectMeta(\u0026pod.ObjectMeta, true, ValidatePodName, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidatePodTemplateSpec(\u0026pod.Template, field.NewPath(\"template\"), opts)...)\n\treturn allErrs\n}","line":{"from":4877,"to":4882}} {"id":100002622,"name":"ValidatePodTemplateUpdate","signature":"func ValidatePodTemplateUpdate(newPod, oldPod *core.PodTemplate, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidatePodTemplateUpdate tests to see if the update is legal for an end user to make. newPod is updated with fields\n// that cannot be changed.\nfunc ValidatePodTemplateUpdate(newPod, oldPod *core.PodTemplate, opts PodValidationOptions) field.ErrorList {\n\tallErrs := ValidateObjectMetaUpdate(\u0026newPod.ObjectMeta, \u0026oldPod.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidatePodTemplateSpec(\u0026newPod.Template, field.NewPath(\"template\"), opts)...)\n\treturn allErrs\n}","line":{"from":4884,"to":4890}} {"id":100002623,"name":"ValidateService","signature":"func ValidateService(service *core.Service) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateService tests if required fields/annotations of a Service are valid.\nfunc ValidateService(service *core.Service) field.ErrorList {\n\tmetaPath := field.NewPath(\"metadata\")\n\tallErrs := ValidateObjectMeta(\u0026service.ObjectMeta, true, ValidateServiceName, metaPath)\n\n\ttopologyHintsVal, topologyHintsSet := service.Annotations[core.DeprecatedAnnotationTopologyAwareHints]\n\ttopologyModeVal, topologyModeSet := service.Annotations[core.AnnotationTopologyMode]\n\n\tif topologyModeSet \u0026\u0026 topologyHintsSet \u0026\u0026 topologyModeVal != topologyHintsVal {\n\t\tmessage := fmt.Sprintf(\"must match annotations[%s] when both are specified\", core.DeprecatedAnnotationTopologyAwareHints)\n\t\tallErrs = append(allErrs, field.Invalid(metaPath.Child(\"annotations\").Key(core.AnnotationTopologyMode), topologyModeVal, message))\n\t}\n\n\tspecPath := field.NewPath(\"spec\")\n\n\tif len(service.Spec.Ports) == 0 \u0026\u0026 !isHeadlessService(service) \u0026\u0026 service.Spec.Type != core.ServiceTypeExternalName {\n\t\tallErrs = append(allErrs, field.Required(specPath.Child(\"ports\"), \"\"))\n\t}\n\tswitch service.Spec.Type {\n\tcase core.ServiceTypeLoadBalancer:\n\t\tfor ix := range service.Spec.Ports {\n\t\t\tport := \u0026service.Spec.Ports[ix]\n\t\t\t// This is a workaround for broken cloud environments that\n\t\t\t// over-open firewalls. Hopefully it can go away when more clouds\n\t\t\t// understand containers better.\n\t\t\tif port.Port == ports.KubeletPort {\n\t\t\t\tportPath := specPath.Child(\"ports\").Index(ix)\n\t\t\t\tallErrs = append(allErrs, field.Invalid(portPath, port.Port, fmt.Sprintf(\"may not expose port %v externally since it is used by kubelet\", ports.KubeletPort)))\n\t\t\t}\n\t\t}\n\t\tif isHeadlessService(service) {\n\t\t\tallErrs = append(allErrs, field.Invalid(specPath.Child(\"clusterIPs\").Index(0), service.Spec.ClusterIPs[0], \"may not be set to 'None' for LoadBalancer services\"))\n\t\t}\n\tcase core.ServiceTypeNodePort:\n\t\tif isHeadlessService(service) {\n\t\t\tallErrs = append(allErrs, field.Invalid(specPath.Child(\"clusterIPs\").Index(0), service.Spec.ClusterIPs[0], \"may not be set to 'None' for NodePort services\"))\n\t\t}\n\tcase core.ServiceTypeExternalName:\n\t\t// must have len(.spec.ClusterIPs) == 0 // note: strategy sets ClusterIPs based on ClusterIP\n\t\tif len(service.Spec.ClusterIPs) \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(specPath.Child(\"clusterIPs\"), \"may not be set for ExternalName services\"))\n\t\t}\n\n\t\t// must have nil families and nil policy\n\t\tif len(service.Spec.IPFamilies) \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(specPath.Child(\"ipFamilies\"), \"may not be set for ExternalName services\"))\n\t\t}\n\t\tif service.Spec.IPFamilyPolicy != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(specPath.Child(\"ipFamilyPolicy\"), \"may not be set for ExternalName services\"))\n\t\t}\n\n\t\t// The value (a CNAME) may have a trailing dot to denote it as fully qualified\n\t\tcname := strings.TrimSuffix(service.Spec.ExternalName, \".\")\n\t\tif len(cname) \u003e 0 {\n\t\t\tallErrs = append(allErrs, ValidateDNS1123Subdomain(cname, specPath.Child(\"externalName\"))...)\n\t\t} else {\n\t\t\tallErrs = append(allErrs, field.Required(specPath.Child(\"externalName\"), \"\"))\n\t\t}\n\t}\n\n\tallPortNames := sets.String{}\n\tportsPath := specPath.Child(\"ports\")\n\tfor i := range service.Spec.Ports {\n\t\tportPath := portsPath.Index(i)\n\t\tallErrs = append(allErrs, validateServicePort(\u0026service.Spec.Ports[i], len(service.Spec.Ports) \u003e 1, isHeadlessService(service), \u0026allPortNames, portPath)...)\n\t}\n\n\tif service.Spec.Selector != nil {\n\t\tallErrs = append(allErrs, unversionedvalidation.ValidateLabels(service.Spec.Selector, specPath.Child(\"selector\"))...)\n\t}\n\n\tif len(service.Spec.SessionAffinity) == 0 {\n\t\tallErrs = append(allErrs, field.Required(specPath.Child(\"sessionAffinity\"), \"\"))\n\t} else if !supportedSessionAffinityType.Has(string(service.Spec.SessionAffinity)) {\n\t\tallErrs = append(allErrs, field.NotSupported(specPath.Child(\"sessionAffinity\"), service.Spec.SessionAffinity, supportedSessionAffinityType.List()))\n\t}\n\n\tif service.Spec.SessionAffinity == core.ServiceAffinityClientIP {\n\t\tallErrs = append(allErrs, validateClientIPAffinityConfig(service.Spec.SessionAffinityConfig, specPath.Child(\"sessionAffinityConfig\"))...)\n\t} else if service.Spec.SessionAffinity == core.ServiceAffinityNone {\n\t\tif service.Spec.SessionAffinityConfig != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(specPath.Child(\"sessionAffinityConfig\"), fmt.Sprintf(\"must not be set when session affinity is %s\", string(core.ServiceAffinityNone))))\n\t\t}\n\t}\n\n\t// dualstack \u003c-\u003e ClusterIPs \u003c-\u003e ipfamilies\n\tallErrs = append(allErrs, ValidateServiceClusterIPsRelatedFields(service)...)\n\n\tipPath := specPath.Child(\"externalIPs\")\n\tfor i, ip := range service.Spec.ExternalIPs {\n\t\tidxPath := ipPath.Index(i)\n\t\tif msgs := validation.IsValidIP(ip); len(msgs) != 0 {\n\t\t\tfor i := range msgs {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath, ip, msgs[i]))\n\t\t\t}\n\t\t} else {\n\t\t\tallErrs = append(allErrs, ValidateNonSpecialIP(ip, idxPath)...)\n\t\t}\n\t}\n\n\tif len(service.Spec.Type) == 0 {\n\t\tallErrs = append(allErrs, field.Required(specPath.Child(\"type\"), \"\"))\n\t} else if !supportedServiceType.Has(string(service.Spec.Type)) {\n\t\tallErrs = append(allErrs, field.NotSupported(specPath.Child(\"type\"), service.Spec.Type, supportedServiceType.List()))\n\t}\n\n\tif service.Spec.Type == core.ServiceTypeClusterIP {\n\t\tportsPath := specPath.Child(\"ports\")\n\t\tfor i := range service.Spec.Ports {\n\t\t\tportPath := portsPath.Index(i)\n\t\t\tif service.Spec.Ports[i].NodePort != 0 {\n\t\t\t\tallErrs = append(allErrs, field.Forbidden(portPath.Child(\"nodePort\"), \"may not be used when `type` is 'ClusterIP'\"))\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check for duplicate NodePorts, considering (protocol,port) pairs\n\tportsPath = specPath.Child(\"ports\")\n\tnodePorts := make(map[core.ServicePort]bool)\n\tfor i := range service.Spec.Ports {\n\t\tport := \u0026service.Spec.Ports[i]\n\t\tif port.NodePort == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tportPath := portsPath.Index(i)\n\t\tvar key core.ServicePort\n\t\tkey.Protocol = port.Protocol\n\t\tkey.NodePort = port.NodePort\n\t\t_, found := nodePorts[key]\n\t\tif found {\n\t\t\tallErrs = append(allErrs, field.Duplicate(portPath.Child(\"nodePort\"), port.NodePort))\n\t\t}\n\t\tnodePorts[key] = true\n\t}\n\n\t// Check for duplicate Ports, considering (protocol,port) pairs\n\tportsPath = specPath.Child(\"ports\")\n\tports := make(map[core.ServicePort]bool)\n\tfor i, port := range service.Spec.Ports {\n\t\tportPath := portsPath.Index(i)\n\t\tkey := core.ServicePort{Protocol: port.Protocol, Port: port.Port}\n\t\t_, found := ports[key]\n\t\tif found {\n\t\t\tallErrs = append(allErrs, field.Duplicate(portPath, key))\n\t\t}\n\t\tports[key] = true\n\t}\n\n\t// Validate SourceRange field and annotation\n\t_, ok := service.Annotations[core.AnnotationLoadBalancerSourceRangesKey]\n\tif len(service.Spec.LoadBalancerSourceRanges) \u003e 0 || ok {\n\t\tvar fieldPath *field.Path\n\t\tvar val string\n\t\tif len(service.Spec.LoadBalancerSourceRanges) \u003e 0 {\n\t\t\tfieldPath = specPath.Child(\"LoadBalancerSourceRanges\")\n\t\t\tval = fmt.Sprintf(\"%v\", service.Spec.LoadBalancerSourceRanges)\n\t\t} else {\n\t\t\tfieldPath = field.NewPath(\"metadata\", \"annotations\").Key(core.AnnotationLoadBalancerSourceRangesKey)\n\t\t\tval = service.Annotations[core.AnnotationLoadBalancerSourceRangesKey]\n\t\t}\n\t\tif service.Spec.Type != core.ServiceTypeLoadBalancer {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fieldPath, \"may only be used when `type` is 'LoadBalancer'\"))\n\t\t}\n\t\t_, err := apiservice.GetLoadBalancerSourceRanges(service)\n\t\tif err != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(fieldPath, val, \"must be a list of IP ranges. For example, 10.240.0.0/24,10.250.0.0/24 \"))\n\t\t}\n\t}\n\n\tif service.Spec.AllocateLoadBalancerNodePorts != nil \u0026\u0026 service.Spec.Type != core.ServiceTypeLoadBalancer {\n\t\tallErrs = append(allErrs, field.Forbidden(specPath.Child(\"allocateLoadBalancerNodePorts\"), \"may only be used when `type` is 'LoadBalancer'\"))\n\t}\n\n\tif service.Spec.Type == core.ServiceTypeLoadBalancer \u0026\u0026 service.Spec.AllocateLoadBalancerNodePorts == nil {\n\t\tallErrs = append(allErrs, field.Required(field.NewPath(\"allocateLoadBalancerNodePorts\"), \"\"))\n\t}\n\n\t// validate LoadBalancerClass field\n\tallErrs = append(allErrs, validateLoadBalancerClassField(nil, service)...)\n\n\t// external traffic policy fields\n\tallErrs = append(allErrs, validateServiceExternalTrafficPolicy(service)...)\n\n\t// internal traffic policy field\n\tallErrs = append(allErrs, validateServiceInternalTrafficFieldsValue(service)...)\n\n\treturn allErrs\n}","line":{"from":4901,"to":5088}} {"id":100002624,"name":"validateServicePort","signature":"func validateServicePort(sp *core.ServicePort, requireName, isHeadlessService bool, allNames *sets.String, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateServicePort(sp *core.ServicePort, requireName, isHeadlessService bool, allNames *sets.String, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif requireName \u0026\u0026 len(sp.Name) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"name\"), \"\"))\n\t} else if len(sp.Name) != 0 {\n\t\tallErrs = append(allErrs, ValidateDNS1123Label(sp.Name, fldPath.Child(\"name\"))...)\n\t\tif allNames.Has(sp.Name) {\n\t\t\tallErrs = append(allErrs, field.Duplicate(fldPath.Child(\"name\"), sp.Name))\n\t\t} else {\n\t\t\tallNames.Insert(sp.Name)\n\t\t}\n\t}\n\n\tfor _, msg := range validation.IsValidPortNum(int(sp.Port)) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"port\"), sp.Port, msg))\n\t}\n\n\tif len(sp.Protocol) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"protocol\"), \"\"))\n\t} else if !supportedPortProtocols.Has(string(sp.Protocol)) {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"protocol\"), sp.Protocol, supportedPortProtocols.List()))\n\t}\n\n\tallErrs = append(allErrs, ValidatePortNumOrName(sp.TargetPort, fldPath.Child(\"targetPort\"))...)\n\n\tif sp.AppProtocol != nil {\n\t\tallErrs = append(allErrs, ValidateQualifiedName(*sp.AppProtocol, fldPath.Child(\"appProtocol\"))...)\n\t}\n\n\t// in the v1 API, targetPorts on headless services were tolerated.\n\t// once we have version-specific validation, we can reject this on newer API versions, but until then, we have to tolerate it for compatibility.\n\t//\n\t// if isHeadlessService {\n\t// \tif sp.TargetPort.Type == intstr.String || (sp.TargetPort.Type == intstr.Int \u0026\u0026 sp.Port != sp.TargetPort.IntValue()) {\n\t// \t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"targetPort\"), sp.TargetPort, \"must be equal to the value of 'port' when clusterIP = None\"))\n\t// \t}\n\t// }\n\n\treturn allErrs\n}","line":{"from":5090,"to":5130}} {"id":100002625,"name":"needsExternalTrafficPolicy","signature":"func needsExternalTrafficPolicy(svc *core.Service) bool","file":"pkg/apis/core/validation/validation.go","code":"func needsExternalTrafficPolicy(svc *core.Service) bool {\n\treturn svc.Spec.Type == core.ServiceTypeLoadBalancer || svc.Spec.Type == core.ServiceTypeNodePort\n}","line":{"from":5132,"to":5134}} {"id":100002626,"name":"validateServiceExternalTrafficPolicy","signature":"func validateServiceExternalTrafficPolicy(service *core.Service) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateServiceExternalTrafficPolicy(service *core.Service) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tfldPath := field.NewPath(\"spec\")\n\n\tif !needsExternalTrafficPolicy(service) {\n\t\tif service.Spec.ExternalTrafficPolicy != \"\" {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"externalTrafficPolicy\"), service.Spec.ExternalTrafficPolicy,\n\t\t\t\t\"may only be set when `type` is 'NodePort' or 'LoadBalancer'\"))\n\t\t}\n\t} else {\n\t\tif service.Spec.ExternalTrafficPolicy == \"\" {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"externalTrafficPolicy\"), \"\"))\n\t\t} else if !validExternalTrafficPolicies.Has(string(service.Spec.ExternalTrafficPolicy)) {\n\t\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"externalTrafficPolicy\"),\n\t\t\t\tservice.Spec.ExternalTrafficPolicy, validExternalTrafficPolicies.List()))\n\t\t}\n\t}\n\n\tif !apiservice.NeedsHealthCheck(service) {\n\t\tif service.Spec.HealthCheckNodePort != 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"healthCheckNodePort\"), service.Spec.HealthCheckNodePort,\n\t\t\t\t\"may only be set when `type` is 'LoadBalancer' and `externalTrafficPolicy` is 'Local'\"))\n\t\t}\n\t} else {\n\t\tif service.Spec.HealthCheckNodePort == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"healthCheckNodePort\"), \"\"))\n\t\t} else {\n\t\t\tfor _, msg := range validation.IsValidPortNum(int(service.Spec.HealthCheckNodePort)) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"healthCheckNodePort\"), service.Spec.HealthCheckNodePort, msg))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":5140,"to":5175}} {"id":100002627,"name":"validateServiceExternalTrafficFieldsUpdate","signature":"func validateServiceExternalTrafficFieldsUpdate(before, after *core.Service) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateServiceExternalTrafficFieldsUpdate(before, after *core.Service) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif apiservice.NeedsHealthCheck(before) \u0026\u0026 apiservice.NeedsHealthCheck(after) {\n\t\tif after.Spec.HealthCheckNodePort != before.Spec.HealthCheckNodePort {\n\t\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"spec\", \"healthCheckNodePort\"), \"field is immutable\"))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":5177,"to":5187}} {"id":100002628,"name":"validateServiceInternalTrafficFieldsValue","signature":"func validateServiceInternalTrafficFieldsValue(service *core.Service) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateServiceInternalTrafficFieldsValue validates InternalTraffic related\n// spec have legal value.\nfunc validateServiceInternalTrafficFieldsValue(service *core.Service) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif service.Spec.InternalTrafficPolicy == nil {\n\t\t// We do not forbid internalTrafficPolicy on other Service types because of historical reasons.\n\t\t// We did not check that before it went beta and we don't want to invalidate existing stored objects.\n\t\tif service.Spec.Type == core.ServiceTypeNodePort ||\n\t\t\tservice.Spec.Type == core.ServiceTypeLoadBalancer || service.Spec.Type == core.ServiceTypeClusterIP {\n\t\t\tallErrs = append(allErrs, field.Required(field.NewPath(\"spec\").Child(\"internalTrafficPolicy\"), \"\"))\n\t\t}\n\t}\n\n\tif service.Spec.InternalTrafficPolicy != nil \u0026\u0026 !supportedServiceInternalTrafficPolicy.Has(string(*service.Spec.InternalTrafficPolicy)) {\n\t\tallErrs = append(allErrs, field.NotSupported(field.NewPath(\"spec\").Child(\"internalTrafficPolicy\"), *service.Spec.InternalTrafficPolicy, supportedServiceInternalTrafficPolicy.List()))\n\t}\n\n\treturn allErrs\n}","line":{"from":5189,"to":5208}} {"id":100002629,"name":"ValidateServiceCreate","signature":"func ValidateServiceCreate(service *core.Service) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateServiceCreate validates Services as they are created.\nfunc ValidateServiceCreate(service *core.Service) field.ErrorList {\n\treturn ValidateService(service)\n}","line":{"from":5210,"to":5213}} {"id":100002630,"name":"ValidateServiceUpdate","signature":"func ValidateServiceUpdate(service, oldService *core.Service) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateServiceUpdate tests if required fields in the service are set during an update\nfunc ValidateServiceUpdate(service, oldService *core.Service) field.ErrorList {\n\tallErrs := ValidateObjectMetaUpdate(\u0026service.ObjectMeta, \u0026oldService.ObjectMeta, field.NewPath(\"metadata\"))\n\n\t// User can upgrade (add another clusterIP or ipFamily)\n\t// can downgrade (remove secondary clusterIP or ipFamily)\n\t// but *CAN NOT* change primary/secondary clusterIP || ipFamily *UNLESS*\n\t// they are changing from/to/ON ExternalName\n\n\tupgradeDowngradeClusterIPsErrs := validateUpgradeDowngradeClusterIPs(oldService, service)\n\tallErrs = append(allErrs, upgradeDowngradeClusterIPsErrs...)\n\n\tupgradeDowngradeIPFamiliesErrs := validateUpgradeDowngradeIPFamilies(oldService, service)\n\tallErrs = append(allErrs, upgradeDowngradeIPFamiliesErrs...)\n\n\tupgradeDowngradeLoadBalancerClassErrs := validateLoadBalancerClassField(oldService, service)\n\tallErrs = append(allErrs, upgradeDowngradeLoadBalancerClassErrs...)\n\n\tallErrs = append(allErrs, validateServiceExternalTrafficFieldsUpdate(oldService, service)...)\n\n\treturn append(allErrs, ValidateService(service)...)\n}","line":{"from":5215,"to":5236}} {"id":100002631,"name":"ValidateServiceStatusUpdate","signature":"func ValidateServiceStatusUpdate(service, oldService *core.Service) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateServiceStatusUpdate tests if required fields in the Service are set when updating status.\nfunc ValidateServiceStatusUpdate(service, oldService *core.Service) field.ErrorList {\n\tallErrs := ValidateObjectMetaUpdate(\u0026service.ObjectMeta, \u0026oldService.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateLoadBalancerStatus(\u0026service.Status.LoadBalancer, field.NewPath(\"status\", \"loadBalancer\"))...)\n\treturn allErrs\n}","line":{"from":5238,"to":5243}} {"id":100002632,"name":"ValidateReplicationController","signature":"func ValidateReplicationController(controller *core.ReplicationController, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateReplicationController tests if required fields in the replication controller are set.\nfunc ValidateReplicationController(controller *core.ReplicationController, opts PodValidationOptions) field.ErrorList {\n\tallErrs := ValidateObjectMeta(\u0026controller.ObjectMeta, true, ValidateReplicationControllerName, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateReplicationControllerSpec(\u0026controller.Spec, field.NewPath(\"spec\"), opts)...)\n\treturn allErrs\n}","line":{"from":5245,"to":5250}} {"id":100002633,"name":"ValidateReplicationControllerUpdate","signature":"func ValidateReplicationControllerUpdate(controller, oldController *core.ReplicationController, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateReplicationControllerUpdate tests if required fields in the replication controller are set.\nfunc ValidateReplicationControllerUpdate(controller, oldController *core.ReplicationController, opts PodValidationOptions) field.ErrorList {\n\tallErrs := ValidateObjectMetaUpdate(\u0026controller.ObjectMeta, \u0026oldController.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateReplicationControllerSpec(\u0026controller.Spec, field.NewPath(\"spec\"), opts)...)\n\treturn allErrs\n}","line":{"from":5252,"to":5257}} {"id":100002634,"name":"ValidateReplicationControllerStatusUpdate","signature":"func ValidateReplicationControllerStatusUpdate(controller, oldController *core.ReplicationController) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateReplicationControllerStatusUpdate tests if required fields in the replication controller are set.\nfunc ValidateReplicationControllerStatusUpdate(controller, oldController *core.ReplicationController) field.ErrorList {\n\tallErrs := ValidateObjectMetaUpdate(\u0026controller.ObjectMeta, \u0026oldController.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateReplicationControllerStatus(controller.Status, field.NewPath(\"status\"))...)\n\treturn allErrs\n}","line":{"from":5259,"to":5264}} {"id":100002635,"name":"ValidateReplicationControllerStatus","signature":"func ValidateReplicationControllerStatus(status core.ReplicationControllerStatus, statusPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func ValidateReplicationControllerStatus(status core.ReplicationControllerStatus, statusPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, ValidateNonnegativeField(int64(status.Replicas), statusPath.Child(\"replicas\"))...)\n\tallErrs = append(allErrs, ValidateNonnegativeField(int64(status.FullyLabeledReplicas), statusPath.Child(\"fullyLabeledReplicas\"))...)\n\tallErrs = append(allErrs, ValidateNonnegativeField(int64(status.ReadyReplicas), statusPath.Child(\"readyReplicas\"))...)\n\tallErrs = append(allErrs, ValidateNonnegativeField(int64(status.AvailableReplicas), statusPath.Child(\"availableReplicas\"))...)\n\tallErrs = append(allErrs, ValidateNonnegativeField(int64(status.ObservedGeneration), statusPath.Child(\"observedGeneration\"))...)\n\tmsg := \"cannot be greater than status.replicas\"\n\tif status.FullyLabeledReplicas \u003e status.Replicas {\n\t\tallErrs = append(allErrs, field.Invalid(statusPath.Child(\"fullyLabeledReplicas\"), status.FullyLabeledReplicas, msg))\n\t}\n\tif status.ReadyReplicas \u003e status.Replicas {\n\t\tallErrs = append(allErrs, field.Invalid(statusPath.Child(\"readyReplicas\"), status.ReadyReplicas, msg))\n\t}\n\tif status.AvailableReplicas \u003e status.Replicas {\n\t\tallErrs = append(allErrs, field.Invalid(statusPath.Child(\"availableReplicas\"), status.AvailableReplicas, msg))\n\t}\n\tif status.AvailableReplicas \u003e status.ReadyReplicas {\n\t\tallErrs = append(allErrs, field.Invalid(statusPath.Child(\"availableReplicas\"), status.AvailableReplicas, \"cannot be greater than readyReplicas\"))\n\t}\n\treturn allErrs\n}","line":{"from":5266,"to":5287}} {"id":100002636,"name":"ValidateNonEmptySelector","signature":"func ValidateNonEmptySelector(selectorMap map[string]string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// Validates that the given selector is non-empty.\nfunc ValidateNonEmptySelector(selectorMap map[string]string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tselector := labels.Set(selectorMap).AsSelector()\n\tif selector.Empty() {\n\t\tallErrs = append(allErrs, field.Required(fldPath, \"\"))\n\t}\n\treturn allErrs\n}","line":{"from":5289,"to":5297}} {"id":100002637,"name":"ValidatePodTemplateSpecForRC","signature":"func ValidatePodTemplateSpecForRC(template *core.PodTemplateSpec, selectorMap map[string]string, replicas int32, fldPath *field.Path, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// Validates the given template and ensures that it is in accordance with the desired selector and replicas.\nfunc ValidatePodTemplateSpecForRC(template *core.PodTemplateSpec, selectorMap map[string]string, replicas int32, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif template == nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath, \"\"))\n\t} else {\n\t\tselector := labels.Set(selectorMap).AsSelector()\n\t\tif !selector.Empty() {\n\t\t\t// Verify that the RC selector matches the labels in template.\n\t\t\tlabels := labels.Set(template.Labels)\n\t\t\tif !selector.Matches(labels) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"metadata\", \"labels\"), template.Labels, \"`selector` does not match template `labels`\"))\n\t\t\t}\n\t\t}\n\t\tallErrs = append(allErrs, ValidatePodTemplateSpec(template, fldPath, opts)...)\n\t\tif replicas \u003e 1 {\n\t\t\tallErrs = append(allErrs, ValidateReadOnlyPersistentDisks(template.Spec.Volumes, fldPath.Child(\"spec\", \"volumes\"))...)\n\t\t}\n\t\t// RestartPolicy has already been first-order validated as per ValidatePodTemplateSpec().\n\t\tif template.Spec.RestartPolicy != core.RestartPolicyAlways {\n\t\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"spec\", \"restartPolicy\"), template.Spec.RestartPolicy, []string{string(core.RestartPolicyAlways)}))\n\t\t}\n\t\tif template.Spec.ActiveDeadlineSeconds != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"spec\", \"activeDeadlineSeconds\"), \"activeDeadlineSeconds in ReplicationController is not Supported\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":5299,"to":5326}} {"id":100002638,"name":"ValidateReplicationControllerSpec","signature":"func ValidateReplicationControllerSpec(spec *core.ReplicationControllerSpec, fldPath *field.Path, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateReplicationControllerSpec tests if required fields in the replication controller spec are set.\nfunc ValidateReplicationControllerSpec(spec *core.ReplicationControllerSpec, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, ValidateNonnegativeField(int64(spec.MinReadySeconds), fldPath.Child(\"minReadySeconds\"))...)\n\tallErrs = append(allErrs, ValidateNonEmptySelector(spec.Selector, fldPath.Child(\"selector\"))...)\n\tallErrs = append(allErrs, ValidateNonnegativeField(int64(spec.Replicas), fldPath.Child(\"replicas\"))...)\n\tallErrs = append(allErrs, ValidatePodTemplateSpecForRC(spec.Template, spec.Selector, spec.Replicas, fldPath.Child(\"template\"), opts)...)\n\treturn allErrs\n}","line":{"from":5328,"to":5336}} {"id":100002639,"name":"ValidatePodTemplateSpec","signature":"func ValidatePodTemplateSpec(spec *core.PodTemplateSpec, fldPath *field.Path, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidatePodTemplateSpec validates the spec of a pod template\nfunc ValidatePodTemplateSpec(spec *core.PodTemplateSpec, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, unversionedvalidation.ValidateLabels(spec.Labels, fldPath.Child(\"labels\"))...)\n\tallErrs = append(allErrs, ValidateAnnotations(spec.Annotations, fldPath.Child(\"annotations\"))...)\n\tallErrs = append(allErrs, ValidatePodSpecificAnnotations(spec.Annotations, \u0026spec.Spec, fldPath.Child(\"annotations\"), opts)...)\n\tallErrs = append(allErrs, ValidatePodSpec(\u0026spec.Spec, nil, fldPath.Child(\"spec\"), opts)...)\n\tallErrs = append(allErrs, validateSeccompAnnotationsAndFields(spec.ObjectMeta, \u0026spec.Spec, fldPath.Child(\"spec\"))...)\n\n\tif len(spec.Spec.EphemeralContainers) \u003e 0 {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"spec\", \"ephemeralContainers\"), \"ephemeral containers not allowed in pod template\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":5338,"to":5352}} {"id":100002640,"name":"ValidateReadOnlyPersistentDisks","signature":"func ValidateReadOnlyPersistentDisks(volumes []core.Volume, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func ValidateReadOnlyPersistentDisks(volumes []core.Volume, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor i := range volumes {\n\t\tvol := \u0026volumes[i]\n\t\tidxPath := fldPath.Index(i)\n\t\tif vol.GCEPersistentDisk != nil {\n\t\t\tif !vol.GCEPersistentDisk.ReadOnly {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"gcePersistentDisk\", \"readOnly\"), false, \"must be true for replicated pods \u003e 1; GCE PD can only be mounted on multiple machines if it is read-only\"))\n\t\t\t}\n\t\t}\n\t\t// TODO: What to do for AWS? It doesn't support replicas\n\t}\n\treturn allErrs\n}","line":{"from":5354,"to":5367}} {"id":100002641,"name":"ValidateTaintsInNodeAnnotations","signature":"func ValidateTaintsInNodeAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateTaintsInNodeAnnotations tests that the serialized taints in Node.Annotations has valid data\nfunc ValidateTaintsInNodeAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\ttaints, err := helper.GetTaintsFromNodeAnnotations(annotations)\n\tif err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, core.TaintsAnnotationKey, err.Error()))\n\t\treturn allErrs\n\t}\n\n\tif len(taints) \u003e 0 {\n\t\tallErrs = append(allErrs, validateNodeTaints(taints, fldPath.Child(core.TaintsAnnotationKey))...)\n\t}\n\n\treturn allErrs\n}","line":{"from":5369,"to":5384}} {"id":100002642,"name":"validateNodeTaints","signature":"func validateNodeTaints(taints []core.Taint, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateNodeTaints tests if given taints have valid data.\nfunc validateNodeTaints(taints []core.Taint, fldPath *field.Path) field.ErrorList {\n\tallErrors := field.ErrorList{}\n\n\tuniqueTaints := map[core.TaintEffect]sets.String{}\n\n\tfor i, currTaint := range taints {\n\t\tidxPath := fldPath.Index(i)\n\t\t// validate the taint key\n\t\tallErrors = append(allErrors, unversionedvalidation.ValidateLabelName(currTaint.Key, idxPath.Child(\"key\"))...)\n\t\t// validate the taint value\n\t\tif errs := validation.IsValidLabelValue(currTaint.Value); len(errs) != 0 {\n\t\t\tallErrors = append(allErrors, field.Invalid(idxPath.Child(\"value\"), currTaint.Value, strings.Join(errs, \";\")))\n\t\t}\n\t\t// validate the taint effect\n\t\tallErrors = append(allErrors, validateTaintEffect(\u0026currTaint.Effect, false, idxPath.Child(\"effect\"))...)\n\n\t\t// validate if taint is unique by \u003ckey, effect\u003e\n\t\tif len(uniqueTaints[currTaint.Effect]) \u003e 0 \u0026\u0026 uniqueTaints[currTaint.Effect].Has(currTaint.Key) {\n\t\t\tduplicatedError := field.Duplicate(idxPath, currTaint)\n\t\t\tduplicatedError.Detail = \"taints must be unique by key and effect pair\"\n\t\t\tallErrors = append(allErrors, duplicatedError)\n\t\t\tcontinue\n\t\t}\n\n\t\t// add taint to existingTaints for uniqueness check\n\t\tif len(uniqueTaints[currTaint.Effect]) == 0 {\n\t\t\tuniqueTaints[currTaint.Effect] = sets.String{}\n\t\t}\n\t\tuniqueTaints[currTaint.Effect].Insert(currTaint.Key)\n\t}\n\treturn allErrors\n}","line":{"from":5386,"to":5418}} {"id":100002643,"name":"ValidateNodeSpecificAnnotations","signature":"func ValidateNodeSpecificAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func ValidateNodeSpecificAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif annotations[core.TaintsAnnotationKey] != \"\" {\n\t\tallErrs = append(allErrs, ValidateTaintsInNodeAnnotations(annotations, fldPath)...)\n\t}\n\n\tif annotations[core.PreferAvoidPodsAnnotationKey] != \"\" {\n\t\tallErrs = append(allErrs, ValidateAvoidPodsInNodeAnnotations(annotations, fldPath)...)\n\t}\n\treturn allErrs\n}","line":{"from":5420,"to":5431}} {"id":100002644,"name":"ValidateNode","signature":"func ValidateNode(node *core.Node) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateNode tests if required fields in the node are set.\nfunc ValidateNode(node *core.Node) field.ErrorList {\n\tfldPath := field.NewPath(\"metadata\")\n\tallErrs := ValidateObjectMeta(\u0026node.ObjectMeta, false, ValidateNodeName, fldPath)\n\tallErrs = append(allErrs, ValidateNodeSpecificAnnotations(node.ObjectMeta.Annotations, fldPath.Child(\"annotations\"))...)\n\tif len(node.Spec.Taints) \u003e 0 {\n\t\tallErrs = append(allErrs, validateNodeTaints(node.Spec.Taints, fldPath.Child(\"taints\"))...)\n\t}\n\n\t// Only validate spec.\n\t// All status fields are optional and can be updated later.\n\t// That said, if specified, we need to ensure they are valid.\n\tallErrs = append(allErrs, ValidateNodeResources(node)...)\n\n\t// validate PodCIDRS only if we need to\n\tif len(node.Spec.PodCIDRs) \u003e 0 {\n\t\tpodCIDRsField := field.NewPath(\"spec\", \"podCIDRs\")\n\n\t\t// all PodCIDRs should be valid ones\n\t\tfor idx, value := range node.Spec.PodCIDRs {\n\t\t\tif _, err := ValidateCIDR(value); err != nil {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(podCIDRsField.Index(idx), node.Spec.PodCIDRs, \"must be valid CIDR\"))\n\t\t\t}\n\t\t}\n\n\t\t// if more than PodCIDR then\n\t\t// - validate for dual stack\n\t\t// - validate for duplication\n\t\tif len(node.Spec.PodCIDRs) \u003e 1 {\n\t\t\tdualStack, err := netutils.IsDualStackCIDRStrings(node.Spec.PodCIDRs)\n\t\t\tif err != nil {\n\t\t\t\tallErrs = append(allErrs, field.InternalError(podCIDRsField, fmt.Errorf(\"invalid PodCIDRs. failed to check with dual stack with error:%v\", err)))\n\t\t\t}\n\t\t\tif !dualStack || len(node.Spec.PodCIDRs) \u003e 2 {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(podCIDRsField, node.Spec.PodCIDRs, \"may specify no more than one CIDR for each IP family\"))\n\t\t\t}\n\n\t\t\t// PodCIDRs must not contain duplicates\n\t\t\tseen := sets.String{}\n\t\t\tfor i, value := range node.Spec.PodCIDRs {\n\t\t\t\tif seen.Has(value) {\n\t\t\t\t\tallErrs = append(allErrs, field.Duplicate(podCIDRsField.Index(i), value))\n\t\t\t\t}\n\t\t\t\tseen.Insert(value)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":5433,"to":5482}} {"id":100002645,"name":"ValidateNodeResources","signature":"func ValidateNodeResources(node *core.Node) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateNodeResources is used to make sure a node has valid capacity and allocatable values.\nfunc ValidateNodeResources(node *core.Node) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\t// Validate resource quantities in capacity.\n\tfor k, v := range node.Status.Capacity {\n\t\tresPath := field.NewPath(\"status\", \"capacity\", string(k))\n\t\tallErrs = append(allErrs, ValidateResourceQuantityValue(string(k), v, resPath)...)\n\t}\n\n\t// Validate resource quantities in allocatable.\n\tfor k, v := range node.Status.Allocatable {\n\t\tresPath := field.NewPath(\"status\", \"allocatable\", string(k))\n\t\tallErrs = append(allErrs, ValidateResourceQuantityValue(string(k), v, resPath)...)\n\t}\n\treturn allErrs\n}","line":{"from":5484,"to":5500}} {"id":100002646,"name":"ValidateNodeUpdate","signature":"func ValidateNodeUpdate(node, oldNode *core.Node) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateNodeUpdate tests to make sure a node update can be applied. Modifies oldNode.\nfunc ValidateNodeUpdate(node, oldNode *core.Node) field.ErrorList {\n\tfldPath := field.NewPath(\"metadata\")\n\tallErrs := ValidateObjectMetaUpdate(\u0026node.ObjectMeta, \u0026oldNode.ObjectMeta, fldPath)\n\tallErrs = append(allErrs, ValidateNodeSpecificAnnotations(node.ObjectMeta.Annotations, fldPath.Child(\"annotations\"))...)\n\n\t// TODO: Enable the code once we have better core object.status update model. Currently,\n\t// anyone can update node status.\n\t// if !apiequality.Semantic.DeepEqual(node.Status, core.NodeStatus{}) {\n\t// \tallErrs = append(allErrs, field.Invalid(\"status\", node.Status, \"must be empty\"))\n\t// }\n\n\tallErrs = append(allErrs, ValidateNodeResources(node)...)\n\n\t// Validate no duplicate addresses in node status.\n\taddresses := make(map[core.NodeAddress]bool)\n\tfor i, address := range node.Status.Addresses {\n\t\tif _, ok := addresses[address]; ok {\n\t\t\tallErrs = append(allErrs, field.Duplicate(field.NewPath(\"status\", \"addresses\").Index(i), address))\n\t\t}\n\t\taddresses[address] = true\n\t}\n\n\t// Allow the controller manager to assign a CIDR to a node if it doesn't have one.\n\tif len(oldNode.Spec.PodCIDRs) \u003e 0 {\n\t\t// compare the entire slice\n\t\tif len(oldNode.Spec.PodCIDRs) != len(node.Spec.PodCIDRs) {\n\t\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"spec\", \"podCIDRs\"), \"node updates may not change podCIDR except from \\\"\\\" to valid\"))\n\t\t} else {\n\t\t\tfor idx, value := range oldNode.Spec.PodCIDRs {\n\t\t\t\tif value != node.Spec.PodCIDRs[idx] {\n\t\t\t\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"spec\", \"podCIDRs\"), \"node updates may not change podCIDR except from \\\"\\\" to valid\"))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Allow controller manager updating provider ID when not set\n\tif len(oldNode.Spec.ProviderID) \u003e 0 \u0026\u0026 oldNode.Spec.ProviderID != node.Spec.ProviderID {\n\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"spec\", \"providerID\"), \"node updates may not change providerID except from \\\"\\\" to valid\"))\n\t}\n\n\tif node.Spec.ConfigSource != nil {\n\t\tallErrs = append(allErrs, validateNodeConfigSourceSpec(node.Spec.ConfigSource, field.NewPath(\"spec\", \"configSource\"))...)\n\t}\n\tif node.Status.Config != nil {\n\t\tallErrs = append(allErrs, validateNodeConfigStatus(node.Status.Config, field.NewPath(\"status\", \"config\"))...)\n\t}\n\n\t// update taints\n\tif len(node.Spec.Taints) \u003e 0 {\n\t\tallErrs = append(allErrs, validateNodeTaints(node.Spec.Taints, fldPath.Child(\"taints\"))...)\n\t}\n\n\tif node.Spec.DoNotUseExternalID != oldNode.Spec.DoNotUseExternalID {\n\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"spec\", \"externalID\"), \"may not be updated\"))\n\t}\n\n\t// status and metadata are allowed change (barring restrictions above), so separately test spec field.\n\t// spec only has a few fields, so check the ones we don't allow changing\n\t// 1. PodCIDRs - immutable after first set - checked above\n\t// 2. ProviderID - immutable after first set - checked above\n\t// 3. Unschedulable - allowed to change\n\t// 4. Taints - allowed to change\n\t// 5. ConfigSource - allowed to change (and checked above)\n\t// 6. DoNotUseExternalID - immutable - checked above\n\n\treturn allErrs\n}","line":{"from":5502,"to":5570}} {"id":100002647,"name":"validateNodeConfigSourceSpec","signature":"func validateNodeConfigSourceSpec(source *core.NodeConfigSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validation specific to Node.Spec.ConfigSource\n// The field ConfigSource is deprecated and will not be used. The validation is kept in place\n// for the backward compatibility\nfunc validateNodeConfigSourceSpec(source *core.NodeConfigSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tcount := int(0)\n\tif source.ConfigMap != nil {\n\t\tcount++\n\t\tallErrs = append(allErrs, validateConfigMapNodeConfigSourceSpec(source.ConfigMap, fldPath.Child(\"configMap\"))...)\n\t}\n\t// add more subfields here in the future as they are added to NodeConfigSource\n\n\t// exactly one reference subfield must be non-nil\n\tif count != 1 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, source, \"exactly one reference subfield must be non-nil\"))\n\t}\n\treturn allErrs\n}","line":{"from":5572,"to":5589}} {"id":100002648,"name":"validateConfigMapNodeConfigSourceSpec","signature":"func validateConfigMapNodeConfigSourceSpec(source *core.ConfigMapNodeConfigSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validation specific to Node.Spec.ConfigSource.ConfigMap\n// The field ConfigSource is deprecated and will not be used. The validation is kept in place\n// for the backward compatibility\nfunc validateConfigMapNodeConfigSourceSpec(source *core.ConfigMapNodeConfigSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\t// uid and resourceVersion must not be set in spec\n\tif string(source.UID) != \"\" {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"uid\"), \"uid must not be set in spec\"))\n\t}\n\tif source.ResourceVersion != \"\" {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"resourceVersion\"), \"resourceVersion must not be set in spec\"))\n\t}\n\treturn append(allErrs, validateConfigMapNodeConfigSource(source, fldPath)...)\n}","line":{"from":5591,"to":5604}} {"id":100002649,"name":"validateNodeConfigStatus","signature":"func validateNodeConfigStatus(status *core.NodeConfigStatus, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validation specififc to Node.Status.Config\nfunc validateNodeConfigStatus(status *core.NodeConfigStatus, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif status.Assigned != nil {\n\t\tallErrs = append(allErrs, validateNodeConfigSourceStatus(status.Assigned, fldPath.Child(\"assigned\"))...)\n\t}\n\tif status.Active != nil {\n\t\tallErrs = append(allErrs, validateNodeConfigSourceStatus(status.Active, fldPath.Child(\"active\"))...)\n\t}\n\tif status.LastKnownGood != nil {\n\t\tallErrs = append(allErrs, validateNodeConfigSourceStatus(status.LastKnownGood, fldPath.Child(\"lastKnownGood\"))...)\n\t}\n\treturn allErrs\n}","line":{"from":5606,"to":5619}} {"id":100002650,"name":"validateNodeConfigSourceStatus","signature":"func validateNodeConfigSourceStatus(source *core.NodeConfigSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validation specific to Node.Status.Config.(Active|Assigned|LastKnownGood)\nfunc validateNodeConfigSourceStatus(source *core.NodeConfigSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tcount := int(0)\n\tif source.ConfigMap != nil {\n\t\tcount++\n\t\tallErrs = append(allErrs, validateConfigMapNodeConfigSourceStatus(source.ConfigMap, fldPath.Child(\"configMap\"))...)\n\t}\n\t// add more subfields here in the future as they are added to NodeConfigSource\n\n\t// exactly one reference subfield must be non-nil\n\tif count != 1 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, source, \"exactly one reference subfield must be non-nil\"))\n\t}\n\treturn allErrs\n}","line":{"from":5621,"to":5636}} {"id":100002651,"name":"validateConfigMapNodeConfigSourceStatus","signature":"func validateConfigMapNodeConfigSourceStatus(source *core.ConfigMapNodeConfigSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validation specific to Node.Status.Config.(Active|Assigned|LastKnownGood).ConfigMap\nfunc validateConfigMapNodeConfigSourceStatus(source *core.ConfigMapNodeConfigSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\t// uid and resourceVersion must be set in status\n\tif string(source.UID) == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"uid\"), \"uid must be set in status\"))\n\t}\n\tif source.ResourceVersion == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"resourceVersion\"), \"resourceVersion must be set in status\"))\n\t}\n\treturn append(allErrs, validateConfigMapNodeConfigSource(source, fldPath)...)\n}","line":{"from":5638,"to":5649}} {"id":100002652,"name":"validateConfigMapNodeConfigSource","signature":"func validateConfigMapNodeConfigSource(source *core.ConfigMapNodeConfigSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// common validation\nfunc validateConfigMapNodeConfigSource(source *core.ConfigMapNodeConfigSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\t// validate target configmap namespace\n\tif source.Namespace == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"namespace\"), \"namespace must be set\"))\n\t} else {\n\t\tfor _, msg := range ValidateNameFunc(ValidateNamespaceName)(source.Namespace, false) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"namespace\"), source.Namespace, msg))\n\t\t}\n\t}\n\t// validate target configmap name\n\tif source.Name == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"name\"), \"name must be set\"))\n\t} else {\n\t\tfor _, msg := range ValidateNameFunc(ValidateConfigMapName)(source.Name, false) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"name\"), source.Name, msg))\n\t\t}\n\t}\n\t// validate kubeletConfigKey against rules for configMap key names\n\tif source.KubeletConfigKey == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"kubeletConfigKey\"), \"kubeletConfigKey must be set\"))\n\t} else {\n\t\tfor _, msg := range validation.IsConfigMapKey(source.KubeletConfigKey) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"kubeletConfigKey\"), source.KubeletConfigKey, msg))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":5651,"to":5679}} {"id":100002653,"name":"validateResourceName","signature":"func validateResourceName(value string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// Validate compute resource typename.\n// Refer to docs/design/resources.md for more details.\nfunc validateResourceName(value string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor _, msg := range validation.IsQualifiedName(value) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, value, msg))\n\t}\n\tif len(allErrs) != 0 {\n\t\treturn allErrs\n\t}\n\n\tif len(strings.Split(value, \"/\")) == 1 {\n\t\tif !helper.IsStandardResourceName(value) {\n\t\t\treturn append(allErrs, field.Invalid(fldPath, value, \"must be a standard resource type or fully qualified\"))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":5681,"to":5699}} {"id":100002654,"name":"validateContainerResourceName","signature":"func validateContainerResourceName(value string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// Validate container resource name\n// Refer to docs/design/resources.md for more details.\nfunc validateContainerResourceName(value string, fldPath *field.Path) field.ErrorList {\n\tallErrs := validateResourceName(value, fldPath)\n\n\tif len(strings.Split(value, \"/\")) == 1 {\n\t\tif !helper.IsStandardContainerResourceName(value) {\n\t\t\treturn append(allErrs, field.Invalid(fldPath, value, \"must be a standard resource for containers\"))\n\t\t}\n\t} else if !helper.IsNativeResource(core.ResourceName(value)) {\n\t\tif !helper.IsExtendedResourceName(core.ResourceName(value)) {\n\t\t\treturn append(allErrs, field.Invalid(fldPath, value, \"doesn't follow extended resource name standard\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":5701,"to":5716}} {"id":100002655,"name":"ValidateResourceQuotaResourceName","signature":"func ValidateResourceQuotaResourceName(value string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// Validate resource names that can go in a resource quota\n// Refer to docs/design/resources.md for more details.\nfunc ValidateResourceQuotaResourceName(value string, fldPath *field.Path) field.ErrorList {\n\tallErrs := validateResourceName(value, fldPath)\n\n\tif len(strings.Split(value, \"/\")) == 1 {\n\t\tif !helper.IsStandardQuotaResourceName(value) {\n\t\t\treturn append(allErrs, field.Invalid(fldPath, value, isInvalidQuotaResource))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":5718,"to":5729}} {"id":100002656,"name":"validateLimitRangeTypeName","signature":"func validateLimitRangeTypeName(value string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// Validate limit range types\nfunc validateLimitRangeTypeName(value string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor _, msg := range validation.IsQualifiedName(value) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, value, msg))\n\t}\n\tif len(allErrs) != 0 {\n\t\treturn allErrs\n\t}\n\n\tif len(strings.Split(value, \"/\")) == 1 {\n\t\tif !helper.IsStandardLimitRangeType(value) {\n\t\t\treturn append(allErrs, field.Invalid(fldPath, value, \"must be a standard limit type or fully qualified\"))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":5731,"to":5748}} {"id":100002657,"name":"validateLimitRangeResourceName","signature":"func validateLimitRangeResourceName(limitType core.LimitType, value string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// Validate limit range resource name\n// limit types (other than Pod/Container) could contain storage not just cpu or memory\nfunc validateLimitRangeResourceName(limitType core.LimitType, value string, fldPath *field.Path) field.ErrorList {\n\tswitch limitType {\n\tcase core.LimitTypePod, core.LimitTypeContainer:\n\t\treturn validateContainerResourceName(value, fldPath)\n\tdefault:\n\t\treturn validateResourceName(value, fldPath)\n\t}\n}","line":{"from":5750,"to":5759}} {"id":100002658,"name":"ValidateLimitRange","signature":"func ValidateLimitRange(limitRange *core.LimitRange) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateLimitRange tests if required fields in the LimitRange are set.\nfunc ValidateLimitRange(limitRange *core.LimitRange) field.ErrorList {\n\tallErrs := ValidateObjectMeta(\u0026limitRange.ObjectMeta, true, ValidateLimitRangeName, field.NewPath(\"metadata\"))\n\n\t// ensure resource names are properly qualified per docs/design/resources.md\n\tlimitTypeSet := map[core.LimitType]bool{}\n\tfldPath := field.NewPath(\"spec\", \"limits\")\n\tfor i := range limitRange.Spec.Limits {\n\t\tidxPath := fldPath.Index(i)\n\t\tlimit := \u0026limitRange.Spec.Limits[i]\n\t\tallErrs = append(allErrs, validateLimitRangeTypeName(string(limit.Type), idxPath.Child(\"type\"))...)\n\n\t\t_, found := limitTypeSet[limit.Type]\n\t\tif found {\n\t\t\tallErrs = append(allErrs, field.Duplicate(idxPath.Child(\"type\"), limit.Type))\n\t\t}\n\t\tlimitTypeSet[limit.Type] = true\n\n\t\tkeys := sets.String{}\n\t\tmin := map[string]resource.Quantity{}\n\t\tmax := map[string]resource.Quantity{}\n\t\tdefaults := map[string]resource.Quantity{}\n\t\tdefaultRequests := map[string]resource.Quantity{}\n\t\tmaxLimitRequestRatios := map[string]resource.Quantity{}\n\n\t\tfor k, q := range limit.Max {\n\t\t\tallErrs = append(allErrs, validateLimitRangeResourceName(limit.Type, string(k), idxPath.Child(\"max\").Key(string(k)))...)\n\t\t\tkeys.Insert(string(k))\n\t\t\tmax[string(k)] = q\n\t\t}\n\t\tfor k, q := range limit.Min {\n\t\t\tallErrs = append(allErrs, validateLimitRangeResourceName(limit.Type, string(k), idxPath.Child(\"min\").Key(string(k)))...)\n\t\t\tkeys.Insert(string(k))\n\t\t\tmin[string(k)] = q\n\t\t}\n\n\t\tif limit.Type == core.LimitTypePod {\n\t\t\tif len(limit.Default) \u003e 0 {\n\t\t\t\tallErrs = append(allErrs, field.Forbidden(idxPath.Child(\"default\"), \"may not be specified when `type` is 'Pod'\"))\n\t\t\t}\n\t\t\tif len(limit.DefaultRequest) \u003e 0 {\n\t\t\t\tallErrs = append(allErrs, field.Forbidden(idxPath.Child(\"defaultRequest\"), \"may not be specified when `type` is 'Pod'\"))\n\t\t\t}\n\t\t} else {\n\t\t\tfor k, q := range limit.Default {\n\t\t\t\tallErrs = append(allErrs, validateLimitRangeResourceName(limit.Type, string(k), idxPath.Child(\"default\").Key(string(k)))...)\n\t\t\t\tkeys.Insert(string(k))\n\t\t\t\tdefaults[string(k)] = q\n\t\t\t}\n\t\t\tfor k, q := range limit.DefaultRequest {\n\t\t\t\tallErrs = append(allErrs, validateLimitRangeResourceName(limit.Type, string(k), idxPath.Child(\"defaultRequest\").Key(string(k)))...)\n\t\t\t\tkeys.Insert(string(k))\n\t\t\t\tdefaultRequests[string(k)] = q\n\t\t\t}\n\t\t}\n\n\t\tif limit.Type == core.LimitTypePersistentVolumeClaim {\n\t\t\t_, minQuantityFound := limit.Min[core.ResourceStorage]\n\t\t\t_, maxQuantityFound := limit.Max[core.ResourceStorage]\n\t\t\tif !minQuantityFound \u0026\u0026 !maxQuantityFound {\n\t\t\t\tallErrs = append(allErrs, field.Required(idxPath.Child(\"limits\"), \"either minimum or maximum storage value is required, but neither was provided\"))\n\t\t\t}\n\t\t}\n\n\t\tfor k, q := range limit.MaxLimitRequestRatio {\n\t\t\tallErrs = append(allErrs, validateLimitRangeResourceName(limit.Type, string(k), idxPath.Child(\"maxLimitRequestRatio\").Key(string(k)))...)\n\t\t\tkeys.Insert(string(k))\n\t\t\tmaxLimitRequestRatios[string(k)] = q\n\t\t}\n\n\t\tfor k := range keys {\n\t\t\tminQuantity, minQuantityFound := min[k]\n\t\t\tmaxQuantity, maxQuantityFound := max[k]\n\t\t\tdefaultQuantity, defaultQuantityFound := defaults[k]\n\t\t\tdefaultRequestQuantity, defaultRequestQuantityFound := defaultRequests[k]\n\t\t\tmaxRatio, maxRatioFound := maxLimitRequestRatios[k]\n\n\t\t\tif minQuantityFound \u0026\u0026 maxQuantityFound \u0026\u0026 minQuantity.Cmp(maxQuantity) \u003e 0 {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"min\").Key(string(k)), minQuantity, fmt.Sprintf(\"min value %s is greater than max value %s\", minQuantity.String(), maxQuantity.String())))\n\t\t\t}\n\n\t\t\tif defaultRequestQuantityFound \u0026\u0026 minQuantityFound \u0026\u0026 minQuantity.Cmp(defaultRequestQuantity) \u003e 0 {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"defaultRequest\").Key(string(k)), defaultRequestQuantity, fmt.Sprintf(\"min value %s is greater than default request value %s\", minQuantity.String(), defaultRequestQuantity.String())))\n\t\t\t}\n\n\t\t\tif defaultRequestQuantityFound \u0026\u0026 maxQuantityFound \u0026\u0026 defaultRequestQuantity.Cmp(maxQuantity) \u003e 0 {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"defaultRequest\").Key(string(k)), defaultRequestQuantity, fmt.Sprintf(\"default request value %s is greater than max value %s\", defaultRequestQuantity.String(), maxQuantity.String())))\n\t\t\t}\n\n\t\t\tif defaultRequestQuantityFound \u0026\u0026 defaultQuantityFound \u0026\u0026 defaultRequestQuantity.Cmp(defaultQuantity) \u003e 0 {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"defaultRequest\").Key(string(k)), defaultRequestQuantity, fmt.Sprintf(\"default request value %s is greater than default limit value %s\", defaultRequestQuantity.String(), defaultQuantity.String())))\n\t\t\t}\n\n\t\t\tif defaultQuantityFound \u0026\u0026 minQuantityFound \u0026\u0026 minQuantity.Cmp(defaultQuantity) \u003e 0 {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"default\").Key(string(k)), minQuantity, fmt.Sprintf(\"min value %s is greater than default value %s\", minQuantity.String(), defaultQuantity.String())))\n\t\t\t}\n\n\t\t\tif defaultQuantityFound \u0026\u0026 maxQuantityFound \u0026\u0026 defaultQuantity.Cmp(maxQuantity) \u003e 0 {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"default\").Key(string(k)), maxQuantity, fmt.Sprintf(\"default value %s is greater than max value %s\", defaultQuantity.String(), maxQuantity.String())))\n\t\t\t}\n\t\t\tif maxRatioFound \u0026\u0026 maxRatio.Cmp(*resource.NewQuantity(1, resource.DecimalSI)) \u003c 0 {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"maxLimitRequestRatio\").Key(string(k)), maxRatio, fmt.Sprintf(\"ratio %s is less than 1\", maxRatio.String())))\n\t\t\t}\n\t\t\tif maxRatioFound \u0026\u0026 minQuantityFound \u0026\u0026 maxQuantityFound {\n\t\t\t\tmaxRatioValue := float64(maxRatio.Value())\n\t\t\t\tminQuantityValue := minQuantity.Value()\n\t\t\t\tmaxQuantityValue := maxQuantity.Value()\n\t\t\t\tif maxRatio.Value() \u003c resource.MaxMilliValue \u0026\u0026 minQuantityValue \u003c resource.MaxMilliValue \u0026\u0026 maxQuantityValue \u003c resource.MaxMilliValue {\n\t\t\t\t\tmaxRatioValue = float64(maxRatio.MilliValue()) / 1000\n\t\t\t\t\tminQuantityValue = minQuantity.MilliValue()\n\t\t\t\t\tmaxQuantityValue = maxQuantity.MilliValue()\n\t\t\t\t}\n\t\t\t\tmaxRatioLimit := float64(maxQuantityValue) / float64(minQuantityValue)\n\t\t\t\tif maxRatioValue \u003e maxRatioLimit {\n\t\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"maxLimitRequestRatio\").Key(string(k)), maxRatio, fmt.Sprintf(\"ratio %s is greater than max/min = %f\", maxRatio.String(), maxRatioLimit)))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// for GPU, hugepages and other resources that are not allowed to overcommit,\n\t\t\t// the default value and defaultRequest value must match if both are specified\n\t\t\tif !helper.IsOvercommitAllowed(core.ResourceName(k)) \u0026\u0026 defaultQuantityFound \u0026\u0026 defaultRequestQuantityFound \u0026\u0026 defaultQuantity.Cmp(defaultRequestQuantity) != 0 {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"defaultRequest\").Key(string(k)), defaultRequestQuantity, fmt.Sprintf(\"default value %s must equal to defaultRequest value %s in %s\", defaultQuantity.String(), defaultRequestQuantity.String(), k)))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":5761,"to":5888}} {"id":100002659,"name":"ValidateServiceAccount","signature":"func ValidateServiceAccount(serviceAccount *core.ServiceAccount) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateServiceAccount tests if required fields in the ServiceAccount are set.\nfunc ValidateServiceAccount(serviceAccount *core.ServiceAccount) field.ErrorList {\n\tallErrs := ValidateObjectMeta(\u0026serviceAccount.ObjectMeta, true, ValidateServiceAccountName, field.NewPath(\"metadata\"))\n\treturn allErrs\n}","line":{"from":5890,"to":5894}} {"id":100002660,"name":"ValidateServiceAccountUpdate","signature":"func ValidateServiceAccountUpdate(newServiceAccount, oldServiceAccount *core.ServiceAccount) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateServiceAccountUpdate tests if required fields in the ServiceAccount are set.\nfunc ValidateServiceAccountUpdate(newServiceAccount, oldServiceAccount *core.ServiceAccount) field.ErrorList {\n\tallErrs := ValidateObjectMetaUpdate(\u0026newServiceAccount.ObjectMeta, \u0026oldServiceAccount.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateServiceAccount(newServiceAccount)...)\n\treturn allErrs\n}","line":{"from":5896,"to":5901}} {"id":100002661,"name":"ValidateSecret","signature":"func ValidateSecret(secret *core.Secret) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateSecret tests if required fields in the Secret are set.\nfunc ValidateSecret(secret *core.Secret) field.ErrorList {\n\tallErrs := ValidateObjectMeta(\u0026secret.ObjectMeta, true, ValidateSecretName, field.NewPath(\"metadata\"))\n\n\tdataPath := field.NewPath(\"data\")\n\ttotalSize := 0\n\tfor key, value := range secret.Data {\n\t\tfor _, msg := range validation.IsConfigMapKey(key) {\n\t\t\tallErrs = append(allErrs, field.Invalid(dataPath.Key(key), key, msg))\n\t\t}\n\t\ttotalSize += len(value)\n\t}\n\tif totalSize \u003e core.MaxSecretSize {\n\t\tallErrs = append(allErrs, field.TooLong(dataPath, \"\", core.MaxSecretSize))\n\t}\n\n\tswitch secret.Type {\n\tcase core.SecretTypeServiceAccountToken:\n\t\t// Only require Annotations[kubernetes.io/service-account.name]\n\t\t// Additional fields (like Annotations[kubernetes.io/service-account.uid] and Data[token]) might be contributed later by a controller loop\n\t\tif value := secret.Annotations[core.ServiceAccountNameKey]; len(value) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(field.NewPath(\"metadata\", \"annotations\").Key(core.ServiceAccountNameKey), \"\"))\n\t\t}\n\tcase core.SecretTypeOpaque, \"\":\n\t// no-op\n\tcase core.SecretTypeDockercfg:\n\t\tdockercfgBytes, exists := secret.Data[core.DockerConfigKey]\n\t\tif !exists {\n\t\t\tallErrs = append(allErrs, field.Required(dataPath.Key(core.DockerConfigKey), \"\"))\n\t\t\tbreak\n\t\t}\n\n\t\t// make sure that the content is well-formed json.\n\t\tif err := json.Unmarshal(dockercfgBytes, \u0026map[string]interface{}{}); err != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(dataPath.Key(core.DockerConfigKey), \"\u003csecret contents redacted\u003e\", err.Error()))\n\t\t}\n\tcase core.SecretTypeDockerConfigJSON:\n\t\tdockerConfigJSONBytes, exists := secret.Data[core.DockerConfigJSONKey]\n\t\tif !exists {\n\t\t\tallErrs = append(allErrs, field.Required(dataPath.Key(core.DockerConfigJSONKey), \"\"))\n\t\t\tbreak\n\t\t}\n\n\t\t// make sure that the content is well-formed json.\n\t\tif err := json.Unmarshal(dockerConfigJSONBytes, \u0026map[string]interface{}{}); err != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(dataPath.Key(core.DockerConfigJSONKey), \"\u003csecret contents redacted\u003e\", err.Error()))\n\t\t}\n\tcase core.SecretTypeBasicAuth:\n\t\t_, usernameFieldExists := secret.Data[core.BasicAuthUsernameKey]\n\t\t_, passwordFieldExists := secret.Data[core.BasicAuthPasswordKey]\n\n\t\t// username or password might be empty, but the field must be present\n\t\tif !usernameFieldExists \u0026\u0026 !passwordFieldExists {\n\t\t\tallErrs = append(allErrs, field.Required(dataPath.Key(core.BasicAuthUsernameKey), \"\"))\n\t\t\tallErrs = append(allErrs, field.Required(dataPath.Key(core.BasicAuthPasswordKey), \"\"))\n\t\t\tbreak\n\t\t}\n\tcase core.SecretTypeSSHAuth:\n\t\tif len(secret.Data[core.SSHAuthPrivateKey]) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(dataPath.Key(core.SSHAuthPrivateKey), \"\"))\n\t\t\tbreak\n\t\t}\n\n\tcase core.SecretTypeTLS:\n\t\tif _, exists := secret.Data[core.TLSCertKey]; !exists {\n\t\t\tallErrs = append(allErrs, field.Required(dataPath.Key(core.TLSCertKey), \"\"))\n\t\t}\n\t\tif _, exists := secret.Data[core.TLSPrivateKeyKey]; !exists {\n\t\t\tallErrs = append(allErrs, field.Required(dataPath.Key(core.TLSPrivateKeyKey), \"\"))\n\t\t}\n\tdefault:\n\t\t// no-op\n\t}\n\n\treturn allErrs\n}","line":{"from":5903,"to":5978}} {"id":100002662,"name":"ValidateSecretUpdate","signature":"func ValidateSecretUpdate(newSecret, oldSecret *core.Secret) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateSecretUpdate tests if required fields in the Secret are set.\nfunc ValidateSecretUpdate(newSecret, oldSecret *core.Secret) field.ErrorList {\n\tallErrs := ValidateObjectMetaUpdate(\u0026newSecret.ObjectMeta, \u0026oldSecret.ObjectMeta, field.NewPath(\"metadata\"))\n\n\tallErrs = append(allErrs, ValidateImmutableField(newSecret.Type, oldSecret.Type, field.NewPath(\"type\"))...)\n\tif oldSecret.Immutable != nil \u0026\u0026 *oldSecret.Immutable {\n\t\tif newSecret.Immutable == nil || !*newSecret.Immutable {\n\t\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"immutable\"), \"field is immutable when `immutable` is set\"))\n\t\t}\n\t\tif !reflect.DeepEqual(newSecret.Data, oldSecret.Data) {\n\t\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"data\"), \"field is immutable when `immutable` is set\"))\n\t\t}\n\t\t// We don't validate StringData, as it was already converted back to Data\n\t\t// before validation is happening.\n\t}\n\n\tallErrs = append(allErrs, ValidateSecret(newSecret)...)\n\treturn allErrs\n}","line":{"from":5980,"to":5998}} {"id":100002663,"name":"ValidateConfigMap","signature":"func ValidateConfigMap(cfg *core.ConfigMap) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateConfigMap tests whether required fields in the ConfigMap are set.\nfunc ValidateConfigMap(cfg *core.ConfigMap) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, ValidateObjectMeta(\u0026cfg.ObjectMeta, true, ValidateConfigMapName, field.NewPath(\"metadata\"))...)\n\n\ttotalSize := 0\n\n\tfor key, value := range cfg.Data {\n\t\tfor _, msg := range validation.IsConfigMapKey(key) {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"data\").Key(key), key, msg))\n\t\t}\n\t\t// check if we have a duplicate key in the other bag\n\t\tif _, isValue := cfg.BinaryData[key]; isValue {\n\t\t\tmsg := \"duplicate of key present in binaryData\"\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"data\").Key(key), key, msg))\n\t\t}\n\t\ttotalSize += len(value)\n\t}\n\tfor key, value := range cfg.BinaryData {\n\t\tfor _, msg := range validation.IsConfigMapKey(key) {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"binaryData\").Key(key), key, msg))\n\t\t}\n\t\ttotalSize += len(value)\n\t}\n\tif totalSize \u003e core.MaxSecretSize {\n\t\t// pass back \"\" to indicate that the error refers to the whole object.\n\t\tallErrs = append(allErrs, field.TooLong(field.NewPath(\"\"), cfg, core.MaxSecretSize))\n\t}\n\n\treturn allErrs\n}","line":{"from":6005,"to":6035}} {"id":100002664,"name":"ValidateConfigMapUpdate","signature":"func ValidateConfigMapUpdate(newCfg, oldCfg *core.ConfigMap) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateConfigMapUpdate tests if required fields in the ConfigMap are set.\nfunc ValidateConfigMapUpdate(newCfg, oldCfg *core.ConfigMap) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, ValidateObjectMetaUpdate(\u0026newCfg.ObjectMeta, \u0026oldCfg.ObjectMeta, field.NewPath(\"metadata\"))...)\n\n\tif oldCfg.Immutable != nil \u0026\u0026 *oldCfg.Immutable {\n\t\tif newCfg.Immutable == nil || !*newCfg.Immutable {\n\t\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"immutable\"), \"field is immutable when `immutable` is set\"))\n\t\t}\n\t\tif !reflect.DeepEqual(newCfg.Data, oldCfg.Data) {\n\t\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"data\"), \"field is immutable when `immutable` is set\"))\n\t\t}\n\t\tif !reflect.DeepEqual(newCfg.BinaryData, oldCfg.BinaryData) {\n\t\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"binaryData\"), \"field is immutable when `immutable` is set\"))\n\t\t}\n\t}\n\n\tallErrs = append(allErrs, ValidateConfigMap(newCfg)...)\n\treturn allErrs\n}","line":{"from":6037,"to":6056}} {"id":100002665,"name":"validateBasicResource","signature":"func validateBasicResource(quantity resource.Quantity, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateBasicResource(quantity resource.Quantity, fldPath *field.Path) field.ErrorList {\n\tif quantity.Value() \u003c 0 {\n\t\treturn field.ErrorList{field.Invalid(fldPath, quantity.Value(), \"must be a valid resource quantity\")}\n\t}\n\treturn field.ErrorList{}\n}","line":{"from":6058,"to":6063}} {"id":100002666,"name":"ValidateResourceRequirements","signature":"func ValidateResourceRequirements(requirements *core.ResourceRequirements, podClaimNames sets.String, fldPath *field.Path, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// Validates resource requirement spec.\nfunc ValidateResourceRequirements(requirements *core.ResourceRequirements, podClaimNames sets.String, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tlimPath := fldPath.Child(\"limits\")\n\treqPath := fldPath.Child(\"requests\")\n\tlimContainsCPUOrMemory := false\n\treqContainsCPUOrMemory := false\n\tlimContainsHugePages := false\n\treqContainsHugePages := false\n\tsupportedQoSComputeResources := sets.NewString(string(core.ResourceCPU), string(core.ResourceMemory))\n\tfor resourceName, quantity := range requirements.Limits {\n\n\t\tfldPath := limPath.Key(string(resourceName))\n\t\t// Validate resource name.\n\t\tallErrs = append(allErrs, validateContainerResourceName(string(resourceName), fldPath)...)\n\n\t\t// Validate resource quantity.\n\t\tallErrs = append(allErrs, ValidateResourceQuantityValue(string(resourceName), quantity, fldPath)...)\n\n\t\tif helper.IsHugePageResourceName(resourceName) {\n\t\t\tlimContainsHugePages = true\n\t\t\tif err := validateResourceQuantityHugePageValue(resourceName, quantity, opts); err != nil {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, quantity.String(), err.Error()))\n\t\t\t}\n\t\t}\n\n\t\tif supportedQoSComputeResources.Has(string(resourceName)) {\n\t\t\tlimContainsCPUOrMemory = true\n\t\t}\n\t}\n\tfor resourceName, quantity := range requirements.Requests {\n\t\tfldPath := reqPath.Key(string(resourceName))\n\t\t// Validate resource name.\n\t\tallErrs = append(allErrs, validateContainerResourceName(string(resourceName), fldPath)...)\n\t\t// Validate resource quantity.\n\t\tallErrs = append(allErrs, ValidateResourceQuantityValue(string(resourceName), quantity, fldPath)...)\n\n\t\t// Check that request \u003c= limit.\n\t\tlimitQuantity, exists := requirements.Limits[resourceName]\n\t\tif exists {\n\t\t\t// For non overcommitable resources, not only requests can't exceed limits, they also can't be lower, i.e. must be equal.\n\t\t\tif quantity.Cmp(limitQuantity) != 0 \u0026\u0026 !helper.IsOvercommitAllowed(resourceName) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(reqPath, quantity.String(), fmt.Sprintf(\"must be equal to %s limit of %s\", resourceName, limitQuantity.String())))\n\t\t\t} else if quantity.Cmp(limitQuantity) \u003e 0 {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(reqPath, quantity.String(), fmt.Sprintf(\"must be less than or equal to %s limit of %s\", resourceName, limitQuantity.String())))\n\t\t\t}\n\t\t} else if !helper.IsOvercommitAllowed(resourceName) {\n\t\t\tallErrs = append(allErrs, field.Required(limPath, \"Limit must be set for non overcommitable resources\"))\n\t\t}\n\t\tif helper.IsHugePageResourceName(resourceName) {\n\t\t\treqContainsHugePages = true\n\t\t\tif err := validateResourceQuantityHugePageValue(resourceName, quantity, opts); err != nil {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, quantity.String(), err.Error()))\n\t\t\t}\n\t\t}\n\t\tif supportedQoSComputeResources.Has(string(resourceName)) {\n\t\t\treqContainsCPUOrMemory = true\n\t\t}\n\n\t}\n\tif !limContainsCPUOrMemory \u0026\u0026 !reqContainsCPUOrMemory \u0026\u0026 (reqContainsHugePages || limContainsHugePages) {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath, \"HugePages require cpu or memory\"))\n\t}\n\n\tallErrs = append(allErrs, validateResourceClaimNames(requirements.Claims, podClaimNames, fldPath.Child(\"claims\"))...)\n\n\treturn allErrs\n}","line":{"from":6065,"to":6132}} {"id":100002667,"name":"validateResourceClaimNames","signature":"func validateResourceClaimNames(claims []core.ResourceClaim, podClaimNames sets.String, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateResourceClaimNames checks that the names in\n// ResourceRequirements.Claims have a corresponding entry in\n// PodSpec.ResourceClaims.\nfunc validateResourceClaimNames(claims []core.ResourceClaim, podClaimNames sets.String, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tnames := sets.String{}\n\tfor i, claim := range claims {\n\t\tname := claim.Name\n\t\tif name == \"\" {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Index(i), \"\"))\n\t\t} else {\n\t\t\tif names.Has(name) {\n\t\t\t\tallErrs = append(allErrs, field.Duplicate(fldPath.Index(i), name))\n\t\t\t} else {\n\t\t\t\tnames.Insert(name)\n\t\t\t}\n\t\t\tif !podClaimNames.Has(name) {\n\t\t\t\t// field.NotFound doesn't accept an\n\t\t\t\t// explanation. Adding one here is more\n\t\t\t\t// user-friendly.\n\t\t\t\terror := field.NotFound(fldPath.Index(i), name)\n\t\t\t\terror.Detail = \"must be one of the names in pod.spec.resourceClaims\"\n\t\t\t\tif len(podClaimNames) == 0 {\n\t\t\t\t\terror.Detail += \" which is empty\"\n\t\t\t\t} else {\n\t\t\t\t\terror.Detail += \": \" + strings.Join(podClaimNames.List(), \", \")\n\t\t\t\t}\n\t\t\t\tallErrs = append(allErrs, error)\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":6134,"to":6166}} {"id":100002668,"name":"validateResourceQuantityHugePageValue","signature":"func validateResourceQuantityHugePageValue(name core.ResourceName, quantity resource.Quantity, opts PodValidationOptions) error","file":"pkg/apis/core/validation/validation.go","code":"func validateResourceQuantityHugePageValue(name core.ResourceName, quantity resource.Quantity, opts PodValidationOptions) error {\n\tif !helper.IsHugePageResourceName(name) {\n\t\treturn nil\n\t}\n\n\tif !opts.AllowIndivisibleHugePagesValues \u0026\u0026 !helper.IsHugePageResourceValueDivisible(name, quantity) {\n\t\treturn fmt.Errorf(\"%s is not positive integer multiple of %s\", quantity.String(), name)\n\t}\n\n\treturn nil\n}","line":{"from":6168,"to":6178}} {"id":100002669,"name":"validateResourceQuotaScopes","signature":"func validateResourceQuotaScopes(resourceQuotaSpec *core.ResourceQuotaSpec, fld *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateResourceQuotaScopes ensures that each enumerated hard resource constraint is valid for set of scopes\nfunc validateResourceQuotaScopes(resourceQuotaSpec *core.ResourceQuotaSpec, fld *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(resourceQuotaSpec.Scopes) == 0 {\n\t\treturn allErrs\n\t}\n\thardLimits := sets.NewString()\n\tfor k := range resourceQuotaSpec.Hard {\n\t\thardLimits.Insert(string(k))\n\t}\n\tfldPath := fld.Child(\"scopes\")\n\tscopeSet := sets.NewString()\n\tfor _, scope := range resourceQuotaSpec.Scopes {\n\t\tif !helper.IsStandardResourceQuotaScope(string(scope)) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, resourceQuotaSpec.Scopes, \"unsupported scope\"))\n\t\t}\n\t\tfor _, k := range hardLimits.List() {\n\t\t\tif helper.IsStandardQuotaResourceName(k) \u0026\u0026 !helper.IsResourceQuotaScopeValidForResource(scope, k) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, resourceQuotaSpec.Scopes, \"unsupported scope applied to resource\"))\n\t\t\t}\n\t\t}\n\t\tscopeSet.Insert(string(scope))\n\t}\n\tinvalidScopePairs := []sets.String{\n\t\tsets.NewString(string(core.ResourceQuotaScopeBestEffort), string(core.ResourceQuotaScopeNotBestEffort)),\n\t\tsets.NewString(string(core.ResourceQuotaScopeTerminating), string(core.ResourceQuotaScopeNotTerminating)),\n\t}\n\tfor _, invalidScopePair := range invalidScopePairs {\n\t\tif scopeSet.HasAll(invalidScopePair.List()...) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, resourceQuotaSpec.Scopes, \"conflicting scopes\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":6180,"to":6213}} {"id":100002670,"name":"validateScopedResourceSelectorRequirement","signature":"func validateScopedResourceSelectorRequirement(resourceQuotaSpec *core.ResourceQuotaSpec, fld *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateScopedResourceSelectorRequirement tests that the match expressions has valid data\nfunc validateScopedResourceSelectorRequirement(resourceQuotaSpec *core.ResourceQuotaSpec, fld *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\thardLimits := sets.NewString()\n\tfor k := range resourceQuotaSpec.Hard {\n\t\thardLimits.Insert(string(k))\n\t}\n\tfldPath := fld.Child(\"matchExpressions\")\n\tscopeSet := sets.NewString()\n\tfor _, req := range resourceQuotaSpec.ScopeSelector.MatchExpressions {\n\t\tif !helper.IsStandardResourceQuotaScope(string(req.ScopeName)) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"scopeName\"), req.ScopeName, \"unsupported scope\"))\n\t\t}\n\t\tfor _, k := range hardLimits.List() {\n\t\t\tif helper.IsStandardQuotaResourceName(k) \u0026\u0026 !helper.IsResourceQuotaScopeValidForResource(req.ScopeName, k) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, resourceQuotaSpec.ScopeSelector, \"unsupported scope applied to resource\"))\n\t\t\t}\n\t\t}\n\t\tswitch req.ScopeName {\n\t\tcase core.ResourceQuotaScopeBestEffort, core.ResourceQuotaScopeNotBestEffort, core.ResourceQuotaScopeTerminating, core.ResourceQuotaScopeNotTerminating, core.ResourceQuotaScopeCrossNamespacePodAffinity:\n\t\t\tif req.Operator != core.ScopeSelectorOpExists {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"operator\"), req.Operator,\n\t\t\t\t\t\"must be 'Exist' when scope is any of ResourceQuotaScopeTerminating, ResourceQuotaScopeNotTerminating, ResourceQuotaScopeBestEffort, ResourceQuotaScopeNotBestEffort or ResourceQuotaScopeCrossNamespacePodAffinity\"))\n\t\t\t}\n\t\t}\n\n\t\tswitch req.Operator {\n\t\tcase core.ScopeSelectorOpIn, core.ScopeSelectorOpNotIn:\n\t\t\tif len(req.Values) == 0 {\n\t\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"values\"),\n\t\t\t\t\t\"must be at least one value when `operator` is 'In' or 'NotIn' for scope selector\"))\n\t\t\t}\n\t\tcase core.ScopeSelectorOpExists, core.ScopeSelectorOpDoesNotExist:\n\t\t\tif len(req.Values) != 0 {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"values\"), req.Values,\n\t\t\t\t\t\"must be no value when `operator` is 'Exist' or 'DoesNotExist' for scope selector\"))\n\t\t\t}\n\t\tdefault:\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"operator\"), req.Operator, \"not a valid selector operator\"))\n\t\t}\n\t\tscopeSet.Insert(string(req.ScopeName))\n\t}\n\tinvalidScopePairs := []sets.String{\n\t\tsets.NewString(string(core.ResourceQuotaScopeBestEffort), string(core.ResourceQuotaScopeNotBestEffort)),\n\t\tsets.NewString(string(core.ResourceQuotaScopeTerminating), string(core.ResourceQuotaScopeNotTerminating)),\n\t}\n\tfor _, invalidScopePair := range invalidScopePairs {\n\t\tif scopeSet.HasAll(invalidScopePair.List()...) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, resourceQuotaSpec.Scopes, \"conflicting scopes\"))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":6215,"to":6268}} {"id":100002671,"name":"validateScopeSelector","signature":"func validateScopeSelector(resourceQuotaSpec *core.ResourceQuotaSpec, fld *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateScopeSelector tests that the specified scope selector has valid data\nfunc validateScopeSelector(resourceQuotaSpec *core.ResourceQuotaSpec, fld *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif resourceQuotaSpec.ScopeSelector == nil {\n\t\treturn allErrs\n\t}\n\tallErrs = append(allErrs, validateScopedResourceSelectorRequirement(resourceQuotaSpec, fld.Child(\"scopeSelector\"))...)\n\treturn allErrs\n}","line":{"from":6270,"to":6278}} {"id":100002672,"name":"ValidateResourceQuota","signature":"func ValidateResourceQuota(resourceQuota *core.ResourceQuota) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateResourceQuota tests if required fields in the ResourceQuota are set.\nfunc ValidateResourceQuota(resourceQuota *core.ResourceQuota) field.ErrorList {\n\tallErrs := ValidateObjectMeta(\u0026resourceQuota.ObjectMeta, true, ValidateResourceQuotaName, field.NewPath(\"metadata\"))\n\n\tallErrs = append(allErrs, ValidateResourceQuotaSpec(\u0026resourceQuota.Spec, field.NewPath(\"spec\"))...)\n\tallErrs = append(allErrs, ValidateResourceQuotaStatus(\u0026resourceQuota.Status, field.NewPath(\"status\"))...)\n\n\treturn allErrs\n}","line":{"from":6280,"to":6288}} {"id":100002673,"name":"ValidateResourceQuotaStatus","signature":"func ValidateResourceQuotaStatus(status *core.ResourceQuotaStatus, fld *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func ValidateResourceQuotaStatus(status *core.ResourceQuotaStatus, fld *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tfldPath := fld.Child(\"hard\")\n\tfor k, v := range status.Hard {\n\t\tresPath := fldPath.Key(string(k))\n\t\tallErrs = append(allErrs, ValidateResourceQuotaResourceName(string(k), resPath)...)\n\t\tallErrs = append(allErrs, ValidateResourceQuantityValue(string(k), v, resPath)...)\n\t}\n\tfldPath = fld.Child(\"used\")\n\tfor k, v := range status.Used {\n\t\tresPath := fldPath.Key(string(k))\n\t\tallErrs = append(allErrs, ValidateResourceQuotaResourceName(string(k), resPath)...)\n\t\tallErrs = append(allErrs, ValidateResourceQuantityValue(string(k), v, resPath)...)\n\t}\n\n\treturn allErrs\n}","line":{"from":6290,"to":6307}} {"id":100002674,"name":"ValidateResourceQuotaSpec","signature":"func ValidateResourceQuotaSpec(resourceQuotaSpec *core.ResourceQuotaSpec, fld *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func ValidateResourceQuotaSpec(resourceQuotaSpec *core.ResourceQuotaSpec, fld *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tfldPath := fld.Child(\"hard\")\n\tfor k, v := range resourceQuotaSpec.Hard {\n\t\tresPath := fldPath.Key(string(k))\n\t\tallErrs = append(allErrs, ValidateResourceQuotaResourceName(string(k), resPath)...)\n\t\tallErrs = append(allErrs, ValidateResourceQuantityValue(string(k), v, resPath)...)\n\t}\n\n\tallErrs = append(allErrs, validateResourceQuotaScopes(resourceQuotaSpec, fld)...)\n\tallErrs = append(allErrs, validateScopeSelector(resourceQuotaSpec, fld)...)\n\n\treturn allErrs\n}","line":{"from":6309,"to":6323}} {"id":100002675,"name":"ValidateResourceQuantityValue","signature":"func ValidateResourceQuantityValue(resource string, value resource.Quantity, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateResourceQuantityValue enforces that specified quantity is valid for specified resource\nfunc ValidateResourceQuantityValue(resource string, value resource.Quantity, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, ValidateNonnegativeQuantity(value, fldPath)...)\n\tif helper.IsIntegerResourceName(resource) {\n\t\tif value.MilliValue()%int64(1000) != int64(0) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, value, isNotIntegerErrorMsg))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":6325,"to":6335}} {"id":100002676,"name":"ValidateResourceQuotaUpdate","signature":"func ValidateResourceQuotaUpdate(newResourceQuota, oldResourceQuota *core.ResourceQuota) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateResourceQuotaUpdate tests to see if the update is legal for an end user to make.\nfunc ValidateResourceQuotaUpdate(newResourceQuota, oldResourceQuota *core.ResourceQuota) field.ErrorList {\n\tallErrs := ValidateObjectMetaUpdate(\u0026newResourceQuota.ObjectMeta, \u0026oldResourceQuota.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateResourceQuotaSpec(\u0026newResourceQuota.Spec, field.NewPath(\"spec\"))...)\n\n\t// ensure scopes cannot change, and that resources are still valid for scope\n\tfldPath := field.NewPath(\"spec\", \"scopes\")\n\toldScopes := sets.NewString()\n\tnewScopes := sets.NewString()\n\tfor _, scope := range newResourceQuota.Spec.Scopes {\n\t\tnewScopes.Insert(string(scope))\n\t}\n\tfor _, scope := range oldResourceQuota.Spec.Scopes {\n\t\toldScopes.Insert(string(scope))\n\t}\n\tif !oldScopes.Equal(newScopes) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, newResourceQuota.Spec.Scopes, fieldImmutableErrorMsg))\n\t}\n\n\treturn allErrs\n}","line":{"from":6337,"to":6357}} {"id":100002677,"name":"ValidateResourceQuotaStatusUpdate","signature":"func ValidateResourceQuotaStatusUpdate(newResourceQuota, oldResourceQuota *core.ResourceQuota) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateResourceQuotaStatusUpdate tests to see if the status update is legal for an end user to make.\nfunc ValidateResourceQuotaStatusUpdate(newResourceQuota, oldResourceQuota *core.ResourceQuota) field.ErrorList {\n\tallErrs := ValidateObjectMetaUpdate(\u0026newResourceQuota.ObjectMeta, \u0026oldResourceQuota.ObjectMeta, field.NewPath(\"metadata\"))\n\tif len(newResourceQuota.ResourceVersion) == 0 {\n\t\tallErrs = append(allErrs, field.Required(field.NewPath(\"resourceVersion\"), \"\"))\n\t}\n\tfldPath := field.NewPath(\"status\", \"hard\")\n\tfor k, v := range newResourceQuota.Status.Hard {\n\t\tresPath := fldPath.Key(string(k))\n\t\tallErrs = append(allErrs, ValidateResourceQuotaResourceName(string(k), resPath)...)\n\t\tallErrs = append(allErrs, ValidateResourceQuantityValue(string(k), v, resPath)...)\n\t}\n\tfldPath = field.NewPath(\"status\", \"used\")\n\tfor k, v := range newResourceQuota.Status.Used {\n\t\tresPath := fldPath.Key(string(k))\n\t\tallErrs = append(allErrs, ValidateResourceQuotaResourceName(string(k), resPath)...)\n\t\tallErrs = append(allErrs, ValidateResourceQuantityValue(string(k), v, resPath)...)\n\t}\n\treturn allErrs\n}","line":{"from":6359,"to":6378}} {"id":100002678,"name":"ValidateNamespace","signature":"func ValidateNamespace(namespace *core.Namespace) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateNamespace tests if required fields are set.\nfunc ValidateNamespace(namespace *core.Namespace) field.ErrorList {\n\tallErrs := ValidateObjectMeta(\u0026namespace.ObjectMeta, false, ValidateNamespaceName, field.NewPath(\"metadata\"))\n\tfor i := range namespace.Spec.Finalizers {\n\t\tallErrs = append(allErrs, validateFinalizerName(string(namespace.Spec.Finalizers[i]), field.NewPath(\"spec\", \"finalizers\"))...)\n\t}\n\treturn allErrs\n}","line":{"from":6380,"to":6387}} {"id":100002679,"name":"validateFinalizerName","signature":"func validateFinalizerName(stringValue string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// Validate finalizer names\nfunc validateFinalizerName(stringValue string, fldPath *field.Path) field.ErrorList {\n\tallErrs := apimachineryvalidation.ValidateFinalizerName(stringValue, fldPath)\n\tallErrs = append(allErrs, validateKubeFinalizerName(stringValue, fldPath)...)\n\treturn allErrs\n}","line":{"from":6389,"to":6394}} {"id":100002680,"name":"validateKubeFinalizerName","signature":"func validateKubeFinalizerName(stringValue string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateKubeFinalizerName checks for \"standard\" names of legacy finalizer\nfunc validateKubeFinalizerName(stringValue string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(strings.Split(stringValue, \"/\")) == 1 {\n\t\tif !helper.IsStandardFinalizerName(stringValue) {\n\t\t\treturn append(allErrs, field.Invalid(fldPath, stringValue, \"name is neither a standard finalizer name nor is it fully qualified\"))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":6396,"to":6406}} {"id":100002681,"name":"ValidateNamespaceUpdate","signature":"func ValidateNamespaceUpdate(newNamespace *core.Namespace, oldNamespace *core.Namespace) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateNamespaceUpdate tests to make sure a namespace update can be applied.\nfunc ValidateNamespaceUpdate(newNamespace *core.Namespace, oldNamespace *core.Namespace) field.ErrorList {\n\tallErrs := ValidateObjectMetaUpdate(\u0026newNamespace.ObjectMeta, \u0026oldNamespace.ObjectMeta, field.NewPath(\"metadata\"))\n\treturn allErrs\n}","line":{"from":6408,"to":6412}} {"id":100002682,"name":"ValidateNamespaceStatusUpdate","signature":"func ValidateNamespaceStatusUpdate(newNamespace, oldNamespace *core.Namespace) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateNamespaceStatusUpdate tests to see if the update is legal for an end user to make.\nfunc ValidateNamespaceStatusUpdate(newNamespace, oldNamespace *core.Namespace) field.ErrorList {\n\tallErrs := ValidateObjectMetaUpdate(\u0026newNamespace.ObjectMeta, \u0026oldNamespace.ObjectMeta, field.NewPath(\"metadata\"))\n\tif newNamespace.DeletionTimestamp.IsZero() {\n\t\tif newNamespace.Status.Phase != core.NamespaceActive {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"status\", \"Phase\"), newNamespace.Status.Phase, \"may only be 'Active' if `deletionTimestamp` is empty\"))\n\t\t}\n\t} else {\n\t\tif newNamespace.Status.Phase != core.NamespaceTerminating {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"status\", \"Phase\"), newNamespace.Status.Phase, \"may only be 'Terminating' if `deletionTimestamp` is not empty\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":6414,"to":6427}} {"id":100002683,"name":"ValidateNamespaceFinalizeUpdate","signature":"func ValidateNamespaceFinalizeUpdate(newNamespace, oldNamespace *core.Namespace) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateNamespaceFinalizeUpdate tests to see if the update is legal for an end user to make.\nfunc ValidateNamespaceFinalizeUpdate(newNamespace, oldNamespace *core.Namespace) field.ErrorList {\n\tallErrs := ValidateObjectMetaUpdate(\u0026newNamespace.ObjectMeta, \u0026oldNamespace.ObjectMeta, field.NewPath(\"metadata\"))\n\n\tfldPath := field.NewPath(\"spec\", \"finalizers\")\n\tfor i := range newNamespace.Spec.Finalizers {\n\t\tidxPath := fldPath.Index(i)\n\t\tallErrs = append(allErrs, validateFinalizerName(string(newNamespace.Spec.Finalizers[i]), idxPath)...)\n\t}\n\treturn allErrs\n}","line":{"from":6429,"to":6439}} {"id":100002684,"name":"ValidateEndpoints","signature":"func ValidateEndpoints(endpoints *core.Endpoints) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateEndpoints validates Endpoints on create and update.\nfunc ValidateEndpoints(endpoints *core.Endpoints) field.ErrorList {\n\tallErrs := ValidateObjectMeta(\u0026endpoints.ObjectMeta, true, ValidateEndpointsName, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateEndpointsSpecificAnnotations(endpoints.Annotations, field.NewPath(\"annotations\"))...)\n\tallErrs = append(allErrs, validateEndpointSubsets(endpoints.Subsets, field.NewPath(\"subsets\"))...)\n\treturn allErrs\n}","line":{"from":6441,"to":6447}} {"id":100002685,"name":"ValidateEndpointsCreate","signature":"func ValidateEndpointsCreate(endpoints *core.Endpoints) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateEndpointsCreate validates Endpoints on create.\nfunc ValidateEndpointsCreate(endpoints *core.Endpoints) field.ErrorList {\n\treturn ValidateEndpoints(endpoints)\n}","line":{"from":6449,"to":6452}} {"id":100002686,"name":"ValidateEndpointsUpdate","signature":"func ValidateEndpointsUpdate(newEndpoints, oldEndpoints *core.Endpoints) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateEndpointsUpdate validates Endpoints on update. NodeName changes are\n// allowed during update to accommodate the case where nodeIP or PodCIDR is\n// reused. An existing endpoint ip will have a different nodeName if this\n// happens.\nfunc ValidateEndpointsUpdate(newEndpoints, oldEndpoints *core.Endpoints) field.ErrorList {\n\tallErrs := ValidateObjectMetaUpdate(\u0026newEndpoints.ObjectMeta, \u0026oldEndpoints.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateEndpoints(newEndpoints)...)\n\treturn allErrs\n}","line":{"from":6454,"to":6462}} {"id":100002687,"name":"validateEndpointSubsets","signature":"func validateEndpointSubsets(subsets []core.EndpointSubset, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateEndpointSubsets(subsets []core.EndpointSubset, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor i := range subsets {\n\t\tss := \u0026subsets[i]\n\t\tidxPath := fldPath.Index(i)\n\n\t\t// EndpointSubsets must include endpoint address. For headless service, we allow its endpoints not to have ports.\n\t\tif len(ss.Addresses) == 0 \u0026\u0026 len(ss.NotReadyAddresses) == 0 {\n\t\t\t// TODO: consider adding a RequiredOneOf() error for this and similar cases\n\t\t\tallErrs = append(allErrs, field.Required(idxPath, \"must specify `addresses` or `notReadyAddresses`\"))\n\t\t}\n\t\tfor addr := range ss.Addresses {\n\t\t\tallErrs = append(allErrs, validateEndpointAddress(\u0026ss.Addresses[addr], idxPath.Child(\"addresses\").Index(addr))...)\n\t\t}\n\t\tfor addr := range ss.NotReadyAddresses {\n\t\t\tallErrs = append(allErrs, validateEndpointAddress(\u0026ss.NotReadyAddresses[addr], idxPath.Child(\"notReadyAddresses\").Index(addr))...)\n\t\t}\n\t\tfor port := range ss.Ports {\n\t\t\tallErrs = append(allErrs, validateEndpointPort(\u0026ss.Ports[port], len(ss.Ports) \u003e 1, idxPath.Child(\"ports\").Index(port))...)\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":6464,"to":6487}} {"id":100002688,"name":"validateEndpointAddress","signature":"func validateEndpointAddress(address *core.EndpointAddress, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateEndpointAddress(address *core.EndpointAddress, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor _, msg := range validation.IsValidIP(address.IP) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"ip\"), address.IP, msg))\n\t}\n\tif len(address.Hostname) \u003e 0 {\n\t\tallErrs = append(allErrs, ValidateDNS1123Label(address.Hostname, fldPath.Child(\"hostname\"))...)\n\t}\n\t// During endpoint update, verify that NodeName is a DNS subdomain and transition rules allow the update\n\tif address.NodeName != nil {\n\t\tfor _, msg := range ValidateNodeName(*address.NodeName, false) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"nodeName\"), *address.NodeName, msg))\n\t\t}\n\t}\n\tallErrs = append(allErrs, ValidateNonSpecialIP(address.IP, fldPath.Child(\"ip\"))...)\n\treturn allErrs\n}","line":{"from":6489,"to":6505}} {"id":100002689,"name":"ValidateNonSpecialIP","signature":"func ValidateNonSpecialIP(ipAddress string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateNonSpecialIP is used to validate Endpoints, EndpointSlices, and\n// external IPs. Specifically, this disallows unspecified and loopback addresses\n// are nonsensical and link-local addresses tend to be used for node-centric\n// purposes (e.g. metadata service).\n//\n// IPv6 references\n// - https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml\n// - https://www.iana.org/assignments/ipv6-multicast-addresses/ipv6-multicast-addresses.xhtml\nfunc ValidateNonSpecialIP(ipAddress string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tip := netutils.ParseIPSloppy(ipAddress)\n\tif ip == nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, ipAddress, \"must be a valid IP address\"))\n\t\treturn allErrs\n\t}\n\tif ip.IsUnspecified() {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, ipAddress, fmt.Sprintf(\"may not be unspecified (%v)\", ipAddress)))\n\t}\n\tif ip.IsLoopback() {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, ipAddress, \"may not be in the loopback range (127.0.0.0/8, ::1/128)\"))\n\t}\n\tif ip.IsLinkLocalUnicast() {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, ipAddress, \"may not be in the link-local range (169.254.0.0/16, fe80::/10)\"))\n\t}\n\tif ip.IsLinkLocalMulticast() {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, ipAddress, \"may not be in the link-local multicast range (224.0.0.0/24, ff02::/10)\"))\n\t}\n\treturn allErrs\n}","line":{"from":6507,"to":6535}} {"id":100002690,"name":"validateEndpointPort","signature":"func validateEndpointPort(port *core.EndpointPort, requireName bool, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateEndpointPort(port *core.EndpointPort, requireName bool, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif requireName \u0026\u0026 len(port.Name) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"name\"), \"\"))\n\t} else if len(port.Name) != 0 {\n\t\tallErrs = append(allErrs, ValidateDNS1123Label(port.Name, fldPath.Child(\"name\"))...)\n\t}\n\tfor _, msg := range validation.IsValidPortNum(int(port.Port)) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"port\"), port.Port, msg))\n\t}\n\tif len(port.Protocol) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"protocol\"), \"\"))\n\t} else if !supportedPortProtocols.Has(string(port.Protocol)) {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"protocol\"), port.Protocol, supportedPortProtocols.List()))\n\t}\n\tif port.AppProtocol != nil {\n\t\tallErrs = append(allErrs, ValidateQualifiedName(*port.AppProtocol, fldPath.Child(\"appProtocol\"))...)\n\t}\n\treturn allErrs\n}","line":{"from":6537,"to":6556}} {"id":100002691,"name":"ValidateSecurityContext","signature":"func ValidateSecurityContext(sc *core.SecurityContext, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateSecurityContext ensures the security context contains valid settings\nfunc ValidateSecurityContext(sc *core.SecurityContext, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\t// this should only be true for testing since SecurityContext is defaulted by the core\n\tif sc == nil {\n\t\treturn allErrs\n\t}\n\n\tif sc.Privileged != nil {\n\t\tif *sc.Privileged \u0026\u0026 !capabilities.Get().AllowPrivileged {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"privileged\"), \"disallowed by cluster policy\"))\n\t\t}\n\t}\n\n\tif sc.RunAsUser != nil {\n\t\tfor _, msg := range validation.IsValidUserID(*sc.RunAsUser) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"runAsUser\"), *sc.RunAsUser, msg))\n\t\t}\n\t}\n\n\tif sc.RunAsGroup != nil {\n\t\tfor _, msg := range validation.IsValidGroupID(*sc.RunAsGroup) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"runAsGroup\"), *sc.RunAsGroup, msg))\n\t\t}\n\t}\n\n\tif sc.ProcMount != nil {\n\t\tif err := ValidateProcMountType(fldPath.Child(\"procMount\"), *sc.ProcMount); err != nil {\n\t\t\tallErrs = append(allErrs, err)\n\t\t}\n\n\t}\n\tallErrs = append(allErrs, validateSeccompProfileField(sc.SeccompProfile, fldPath.Child(\"seccompProfile\"))...)\n\tif sc.AllowPrivilegeEscalation != nil \u0026\u0026 !*sc.AllowPrivilegeEscalation {\n\t\tif sc.Privileged != nil \u0026\u0026 *sc.Privileged {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, sc, \"cannot set `allowPrivilegeEscalation` to false and `privileged` to true\"))\n\t\t}\n\n\t\tif sc.Capabilities != nil {\n\t\t\tfor _, cap := range sc.Capabilities.Add {\n\t\t\t\tif string(cap) == \"CAP_SYS_ADMIN\" {\n\t\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, sc, \"cannot set `allowPrivilegeEscalation` to false and `capabilities.Add` CAP_SYS_ADMIN\"))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tallErrs = append(allErrs, validateWindowsSecurityContextOptions(sc.WindowsOptions, fldPath.Child(\"windowsOptions\"))...)\n\n\treturn allErrs\n}","line":{"from":6558,"to":6608}} {"id":100002692,"name":"validateWindowsSecurityContextOptions","signature":"func validateWindowsSecurityContextOptions(windowsOptions *core.WindowsSecurityContextOptions, fieldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateWindowsSecurityContextOptions(windowsOptions *core.WindowsSecurityContextOptions, fieldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif windowsOptions == nil {\n\t\treturn allErrs\n\t}\n\n\tif windowsOptions.GMSACredentialSpecName != nil {\n\t\t// gmsaCredentialSpecName must be the name of a custom resource\n\t\tfor _, msg := range validation.IsDNS1123Subdomain(*windowsOptions.GMSACredentialSpecName) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fieldPath.Child(\"gmsaCredentialSpecName\"), windowsOptions.GMSACredentialSpecName, msg))\n\t\t}\n\t}\n\n\tif windowsOptions.GMSACredentialSpec != nil {\n\t\tif l := len(*windowsOptions.GMSACredentialSpec); l == 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fieldPath.Child(\"gmsaCredentialSpec\"), windowsOptions.GMSACredentialSpec, \"gmsaCredentialSpec cannot be an empty string\"))\n\t\t} else if l \u003e maxGMSACredentialSpecLength {\n\t\t\terrMsg := fmt.Sprintf(\"gmsaCredentialSpec size must be under %d KiB\", maxGMSACredentialSpecLengthInKiB)\n\t\t\tallErrs = append(allErrs, field.Invalid(fieldPath.Child(\"gmsaCredentialSpec\"), windowsOptions.GMSACredentialSpec, errMsg))\n\t\t}\n\t}\n\n\tif windowsOptions.RunAsUserName != nil {\n\t\tif l := len(*windowsOptions.RunAsUserName); l == 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fieldPath.Child(\"runAsUserName\"), windowsOptions.RunAsUserName, \"runAsUserName cannot be an empty string\"))\n\t\t} else if ctrlRegex.MatchString(*windowsOptions.RunAsUserName) {\n\t\t\terrMsg := \"runAsUserName cannot contain control characters\"\n\t\t\tallErrs = append(allErrs, field.Invalid(fieldPath.Child(\"runAsUserName\"), windowsOptions.RunAsUserName, errMsg))\n\t\t} else if parts := strings.Split(*windowsOptions.RunAsUserName, \"\\\\\"); len(parts) \u003e 2 {\n\t\t\terrMsg := \"runAsUserName cannot contain more than one backslash\"\n\t\t\tallErrs = append(allErrs, field.Invalid(fieldPath.Child(\"runAsUserName\"), windowsOptions.RunAsUserName, errMsg))\n\t\t} else {\n\t\t\tvar (\n\t\t\t\thasDomain = false\n\t\t\t\tdomain = \"\"\n\t\t\t\tuser string\n\t\t\t)\n\t\t\tif len(parts) == 1 {\n\t\t\t\tuser = parts[0]\n\t\t\t} else {\n\t\t\t\thasDomain = true\n\t\t\t\tdomain = parts[0]\n\t\t\t\tuser = parts[1]\n\t\t\t}\n\n\t\t\tif len(domain) \u003e= maxRunAsUserNameDomainLength {\n\t\t\t\terrMsg := fmt.Sprintf(\"runAsUserName's Domain length must be under %d characters\", maxRunAsUserNameDomainLength)\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fieldPath.Child(\"runAsUserName\"), windowsOptions.RunAsUserName, errMsg))\n\t\t\t}\n\n\t\t\tif hasDomain \u0026\u0026 !(validNetBiosRegex.MatchString(domain) || validWindowsUserDomainDNSRegex.MatchString(domain)) {\n\t\t\t\terrMsg := \"runAsUserName's Domain doesn't match the NetBios nor the DNS format\"\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fieldPath.Child(\"runAsUserName\"), windowsOptions.RunAsUserName, errMsg))\n\t\t\t}\n\n\t\t\tif l := len(user); l == 0 {\n\t\t\t\terrMsg := \"runAsUserName's User cannot be empty\"\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fieldPath.Child(\"runAsUserName\"), windowsOptions.RunAsUserName, errMsg))\n\t\t\t} else if l \u003e maxRunAsUserNameUserLength {\n\t\t\t\terrMsg := fmt.Sprintf(\"runAsUserName's User length must not be longer than %d characters\", maxRunAsUserNameUserLength)\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fieldPath.Child(\"runAsUserName\"), windowsOptions.RunAsUserName, errMsg))\n\t\t\t}\n\n\t\t\tif invalidUserNameDotsSpacesRegex.MatchString(user) {\n\t\t\t\terrMsg := `runAsUserName's User cannot contain only periods or spaces`\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fieldPath.Child(\"runAsUserName\"), windowsOptions.RunAsUserName, errMsg))\n\t\t\t}\n\n\t\t\tif invalidUserNameCharsRegex.MatchString(user) {\n\t\t\t\terrMsg := `runAsUserName's User cannot contain the following characters: \"/\\:;|=,+*?\u003c\u003e@[]`\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fieldPath.Child(\"runAsUserName\"), windowsOptions.RunAsUserName, errMsg))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":6646,"to":6723}} {"id":100002693,"name":"validateWindowsHostProcessPod","signature":"func validateWindowsHostProcessPod(podSpec *core.PodSpec, fieldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateWindowsHostProcessPod(podSpec *core.PodSpec, fieldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\t// Keep track of container and hostProcess container count for validate\n\tcontainerCount := 0\n\thostProcessContainerCount := 0\n\n\tvar podHostProcess *bool\n\tif podSpec.SecurityContext != nil \u0026\u0026 podSpec.SecurityContext.WindowsOptions != nil {\n\t\tpodHostProcess = podSpec.SecurityContext.WindowsOptions.HostProcess\n\t}\n\n\thostNetwork := false\n\tif podSpec.SecurityContext != nil {\n\t\thostNetwork = podSpec.SecurityContext.HostNetwork\n\t}\n\n\tpodshelper.VisitContainersWithPath(podSpec, fieldPath, func(c *core.Container, cFieldPath *field.Path) bool {\n\t\tcontainerCount++\n\n\t\tvar containerHostProcess *bool = nil\n\t\tif c.SecurityContext != nil \u0026\u0026 c.SecurityContext.WindowsOptions != nil {\n\t\t\tcontainerHostProcess = c.SecurityContext.WindowsOptions.HostProcess\n\t\t}\n\n\t\tif podHostProcess != nil \u0026\u0026 containerHostProcess != nil \u0026\u0026 *podHostProcess != *containerHostProcess {\n\t\t\terrMsg := fmt.Sprintf(\"pod hostProcess value must be identical if both are specified, was %v\", *podHostProcess)\n\t\t\tallErrs = append(allErrs, field.Invalid(cFieldPath.Child(\"securityContext\", \"windowsOptions\", \"hostProcess\"), *containerHostProcess, errMsg))\n\t\t}\n\n\t\tswitch {\n\t\tcase containerHostProcess != nil \u0026\u0026 *containerHostProcess:\n\t\t\t// Container explicitly sets hostProcess=true\n\t\t\thostProcessContainerCount++\n\t\tcase containerHostProcess == nil \u0026\u0026 podHostProcess != nil \u0026\u0026 *podHostProcess:\n\t\t\t// Container inherits hostProcess=true from pod settings\n\t\t\thostProcessContainerCount++\n\t\t}\n\n\t\treturn true\n\t})\n\n\tif hostProcessContainerCount \u003e 0 {\n\t\t// At present, if a Windows Pods contains any HostProcess containers than all containers must be\n\t\t// HostProcess containers (explicitly set or inherited).\n\t\tif hostProcessContainerCount != containerCount {\n\t\t\terrMsg := \"If pod contains any hostProcess containers then all containers must be HostProcess containers\"\n\t\t\tallErrs = append(allErrs, field.Invalid(fieldPath, \"\", errMsg))\n\t\t}\n\n\t\t// At present Windows Pods which contain HostProcess containers must also set HostNetwork.\n\t\tif !hostNetwork {\n\t\t\terrMsg := \"hostNetwork must be true if pod contains any hostProcess containers\"\n\t\t\tallErrs = append(allErrs, field.Invalid(fieldPath.Child(\"hostNetwork\"), hostNetwork, errMsg))\n\t\t}\n\n\t\tif !capabilities.Get().AllowPrivileged {\n\t\t\terrMsg := \"hostProcess containers are disallowed by cluster policy\"\n\t\t\tallErrs = append(allErrs, field.Forbidden(fieldPath, errMsg))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":6725,"to":6788}} {"id":100002694,"name":"validateOS","signature":"func validateOS(podSpec *core.PodSpec, fldPath *field.Path, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateOS validates the OS field within pod spec\nfunc validateOS(podSpec *core.PodSpec, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tos := podSpec.OS\n\tif os == nil {\n\t\treturn allErrs\n\t}\n\tif len(os.Name) == 0 {\n\t\treturn append(allErrs, field.Required(fldPath.Child(\"name\"), \"cannot be empty\"))\n\t}\n\tosName := string(os.Name)\n\tif !validOS.Has(osName) {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath, osName, validOS.List()))\n\t}\n\treturn allErrs\n}","line":{"from":6790,"to":6805}} {"id":100002695,"name":"ValidatePodLogOptions","signature":"func ValidatePodLogOptions(opts *core.PodLogOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func ValidatePodLogOptions(opts *core.PodLogOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif opts.TailLines != nil \u0026\u0026 *opts.TailLines \u003c 0 {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"tailLines\"), *opts.TailLines, isNegativeErrorMsg))\n\t}\n\tif opts.LimitBytes != nil \u0026\u0026 *opts.LimitBytes \u003c 1 {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"limitBytes\"), *opts.LimitBytes, \"must be greater than 0\"))\n\t}\n\tswitch {\n\tcase opts.SinceSeconds != nil \u0026\u0026 opts.SinceTime != nil:\n\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"\"), \"at most one of `sinceTime` or `sinceSeconds` may be specified\"))\n\tcase opts.SinceSeconds != nil:\n\t\tif *opts.SinceSeconds \u003c 1 {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"sinceSeconds\"), *opts.SinceSeconds, \"must be greater than 0\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":6807,"to":6824}} {"id":100002696,"name":"ValidateLoadBalancerStatus","signature":"func ValidateLoadBalancerStatus(status *core.LoadBalancerStatus, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateLoadBalancerStatus validates required fields on a LoadBalancerStatus\nfunc ValidateLoadBalancerStatus(status *core.LoadBalancerStatus, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor i, ingress := range status.Ingress {\n\t\tidxPath := fldPath.Child(\"ingress\").Index(i)\n\t\tif len(ingress.IP) \u003e 0 {\n\t\t\tif isIP := (netutils.ParseIPSloppy(ingress.IP) != nil); !isIP {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"ip\"), ingress.IP, \"must be a valid IP address\"))\n\t\t\t}\n\t\t}\n\t\tif len(ingress.Hostname) \u003e 0 {\n\t\t\tfor _, msg := range validation.IsDNS1123Subdomain(ingress.Hostname) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"hostname\"), ingress.Hostname, msg))\n\t\t\t}\n\t\t\tif isIP := (netutils.ParseIPSloppy(ingress.Hostname) != nil); isIP {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"hostname\"), ingress.Hostname, \"must be a DNS name, not an IP address\"))\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":6826,"to":6846}} {"id":100002697,"name":"validateVolumeNodeAffinity","signature":"func validateVolumeNodeAffinity(nodeAffinity *core.VolumeNodeAffinity, fldPath *field.Path) (bool, field.ErrorList)","file":"pkg/apis/core/validation/validation.go","code":"// validateVolumeNodeAffinity tests that the PersistentVolume.NodeAffinity has valid data\n// returns:\n// - true if volumeNodeAffinity is set\n// - errorList if there are validation errors\nfunc validateVolumeNodeAffinity(nodeAffinity *core.VolumeNodeAffinity, fldPath *field.Path) (bool, field.ErrorList) {\n\tallErrs := field.ErrorList{}\n\n\tif nodeAffinity == nil {\n\t\treturn false, allErrs\n\t}\n\n\tif nodeAffinity.Required != nil {\n\t\tallErrs = append(allErrs, ValidateNodeSelector(nodeAffinity.Required, fldPath.Child(\"required\"))...)\n\t} else {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"required\"), \"must specify required node constraints\"))\n\t}\n\n\treturn true, allErrs\n}","line":{"from":6848,"to":6866}} {"id":100002698,"name":"ValidateCIDR","signature":"func ValidateCIDR(cidr string) (*net.IPNet, error)","file":"pkg/apis/core/validation/validation.go","code":"// ValidateCIDR validates whether a CIDR matches the conventions expected by net.ParseCIDR\nfunc ValidateCIDR(cidr string) (*net.IPNet, error) {\n\t_, net, err := netutils.ParseCIDRSloppy(cidr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn net, nil\n}","line":{"from":6868,"to":6875}} {"id":100002699,"name":"IsDecremented","signature":"func IsDecremented(update, old *int32) bool","file":"pkg/apis/core/validation/validation.go","code":"func IsDecremented(update, old *int32) bool {\n\tif update == nil \u0026\u0026 old != nil {\n\t\treturn true\n\t}\n\tif update == nil || old == nil {\n\t\treturn false\n\t}\n\treturn *update \u003c *old\n}","line":{"from":6877,"to":6885}} {"id":100002700,"name":"ValidateProcMountType","signature":"func ValidateProcMountType(fldPath *field.Path, procMountType core.ProcMountType) *field.Error","file":"pkg/apis/core/validation/validation.go","code":"// ValidateProcMountType tests that the argument is a valid ProcMountType.\nfunc ValidateProcMountType(fldPath *field.Path, procMountType core.ProcMountType) *field.Error {\n\tswitch procMountType {\n\tcase core.DefaultProcMount, core.UnmaskedProcMount:\n\t\treturn nil\n\tdefault:\n\t\treturn field.NotSupported(fldPath, procMountType, []string{string(core.DefaultProcMount), string(core.UnmaskedProcMount)})\n\t}\n}","line":{"from":6887,"to":6895}} {"id":100002701,"name":"validateTopologySpreadConstraints","signature":"func validateTopologySpreadConstraints(constraints []core.TopologySpreadConstraint, fldPath *field.Path, opts PodValidationOptions) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateTopologySpreadConstraints validates given TopologySpreadConstraints.\nfunc validateTopologySpreadConstraints(constraints []core.TopologySpreadConstraint, fldPath *field.Path, opts PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tfor i, constraint := range constraints {\n\t\tsubFldPath := fldPath.Index(i)\n\t\tif err := ValidateMaxSkew(subFldPath.Child(\"maxSkew\"), constraint.MaxSkew); err != nil {\n\t\t\tallErrs = append(allErrs, err)\n\t\t}\n\t\tif err := ValidateTopologyKey(subFldPath.Child(\"topologyKey\"), constraint.TopologyKey); err != nil {\n\t\t\tallErrs = append(allErrs, err)\n\t\t}\n\t\tif err := ValidateWhenUnsatisfiable(subFldPath.Child(\"whenUnsatisfiable\"), constraint.WhenUnsatisfiable); err != nil {\n\t\t\tallErrs = append(allErrs, err)\n\t\t}\n\t\t// tuple {topologyKey, whenUnsatisfiable} denotes one kind of spread constraint\n\t\tif err := ValidateSpreadConstraintNotRepeat(subFldPath.Child(\"{topologyKey, whenUnsatisfiable}\"), constraint, constraints[i+1:]); err != nil {\n\t\t\tallErrs = append(allErrs, err)\n\t\t}\n\t\tallErrs = append(allErrs, validateMinDomains(subFldPath.Child(\"minDomains\"), constraint.MinDomains, constraint.WhenUnsatisfiable)...)\n\t\tif err := validateNodeInclusionPolicy(subFldPath.Child(\"nodeAffinityPolicy\"), constraint.NodeAffinityPolicy); err != nil {\n\t\t\tallErrs = append(allErrs, err)\n\t\t}\n\t\tif err := validateNodeInclusionPolicy(subFldPath.Child(\"nodeTaintsPolicy\"), constraint.NodeTaintsPolicy); err != nil {\n\t\t\tallErrs = append(allErrs, err)\n\t\t}\n\t\tallErrs = append(allErrs, validateMatchLabelKeys(subFldPath.Child(\"matchLabelKeys\"), constraint.MatchLabelKeys, constraint.LabelSelector)...)\n\t\tif !opts.AllowInvalidTopologySpreadConstraintLabelSelector {\n\t\t\tallErrs = append(allErrs, unversionedvalidation.ValidateLabelSelector(constraint.LabelSelector, unversionedvalidation.LabelSelectorValidationOptions{AllowInvalidLabelValueInSelector: false}, subFldPath.Child(\"labelSelector\"))...)\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":6901,"to":6934}} {"id":100002702,"name":"ValidateMaxSkew","signature":"func ValidateMaxSkew(fldPath *field.Path, maxSkew int32) *field.Error","file":"pkg/apis/core/validation/validation.go","code":"// ValidateMaxSkew tests that the argument is a valid MaxSkew.\nfunc ValidateMaxSkew(fldPath *field.Path, maxSkew int32) *field.Error {\n\tif maxSkew \u003c= 0 {\n\t\treturn field.Invalid(fldPath, maxSkew, isNotPositiveErrorMsg)\n\t}\n\treturn nil\n}","line":{"from":6936,"to":6942}} {"id":100002703,"name":"validateMinDomains","signature":"func validateMinDomains(fldPath *field.Path, minDomains *int32, action core.UnsatisfiableConstraintAction) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateMinDomains tests that the argument is a valid MinDomains.\nfunc validateMinDomains(fldPath *field.Path, minDomains *int32, action core.UnsatisfiableConstraintAction) field.ErrorList {\n\tif minDomains == nil {\n\t\treturn nil\n\t}\n\tvar allErrs field.ErrorList\n\tif *minDomains \u003c= 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, minDomains, isNotPositiveErrorMsg))\n\t}\n\t// When MinDomains is non-nil, whenUnsatisfiable must be DoNotSchedule.\n\tif action != core.DoNotSchedule {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, minDomains, fmt.Sprintf(\"can only use minDomains if whenUnsatisfiable=%s, not %s\", string(core.DoNotSchedule), string(action))))\n\t}\n\treturn allErrs\n}","line":{"from":6944,"to":6958}} {"id":100002704,"name":"ValidateTopologyKey","signature":"func ValidateTopologyKey(fldPath *field.Path, topologyKey string) *field.Error","file":"pkg/apis/core/validation/validation.go","code":"// ValidateTopologyKey tests that the argument is a valid TopologyKey.\nfunc ValidateTopologyKey(fldPath *field.Path, topologyKey string) *field.Error {\n\tif len(topologyKey) == 0 {\n\t\treturn field.Required(fldPath, \"can not be empty\")\n\t}\n\treturn nil\n}","line":{"from":6960,"to":6966}} {"id":100002705,"name":"ValidateWhenUnsatisfiable","signature":"func ValidateWhenUnsatisfiable(fldPath *field.Path, action core.UnsatisfiableConstraintAction) *field.Error","file":"pkg/apis/core/validation/validation.go","code":"// ValidateWhenUnsatisfiable tests that the argument is a valid UnsatisfiableConstraintAction.\nfunc ValidateWhenUnsatisfiable(fldPath *field.Path, action core.UnsatisfiableConstraintAction) *field.Error {\n\tif !supportedScheduleActions.Has(string(action)) {\n\t\treturn field.NotSupported(fldPath, action, supportedScheduleActions.List())\n\t}\n\treturn nil\n}","line":{"from":6968,"to":6974}} {"id":100002706,"name":"ValidateSpreadConstraintNotRepeat","signature":"func ValidateSpreadConstraintNotRepeat(fldPath *field.Path, constraint core.TopologySpreadConstraint, restingConstraints []core.TopologySpreadConstraint) *field.Error","file":"pkg/apis/core/validation/validation.go","code":"// ValidateSpreadConstraintNotRepeat tests that if `constraint` duplicates with `existingConstraintPairs`\n// on TopologyKey and WhenUnsatisfiable fields.\nfunc ValidateSpreadConstraintNotRepeat(fldPath *field.Path, constraint core.TopologySpreadConstraint, restingConstraints []core.TopologySpreadConstraint) *field.Error {\n\tfor _, restingConstraint := range restingConstraints {\n\t\tif constraint.TopologyKey == restingConstraint.TopologyKey \u0026\u0026\n\t\t\tconstraint.WhenUnsatisfiable == restingConstraint.WhenUnsatisfiable {\n\t\t\treturn field.Duplicate(fldPath, fmt.Sprintf(\"{%v, %v}\", constraint.TopologyKey, constraint.WhenUnsatisfiable))\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":6976,"to":6986}} {"id":100002707,"name":"validateNodeInclusionPolicy","signature":"func validateNodeInclusionPolicy(fldPath *field.Path, policy *core.NodeInclusionPolicy) *field.Error","file":"pkg/apis/core/validation/validation.go","code":"// validateNodeAffinityPolicy tests that the argument is a valid NodeInclusionPolicy.\nfunc validateNodeInclusionPolicy(fldPath *field.Path, policy *core.NodeInclusionPolicy) *field.Error {\n\tif policy == nil {\n\t\treturn nil\n\t}\n\n\tif !supportedPodTopologySpreadNodePolicies.Has(string(*policy)) {\n\t\treturn field.NotSupported(fldPath, policy, supportedPodTopologySpreadNodePolicies.List())\n\t}\n\treturn nil\n}","line":{"from":6992,"to":7002}} {"id":100002708,"name":"validateMatchLabelKeys","signature":"func validateMatchLabelKeys(fldPath *field.Path, matchLabelKeys []string, labelSelector *metav1.LabelSelector) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateMatchLabelKeys tests that the elements are a valid label name and are not already included in labelSelector.\nfunc validateMatchLabelKeys(fldPath *field.Path, matchLabelKeys []string, labelSelector *metav1.LabelSelector) field.ErrorList {\n\tif len(matchLabelKeys) == 0 {\n\t\treturn nil\n\t}\n\n\tvar allErrs field.ErrorList\n\tlabelSelectorKeys := sets.String{}\n\n\tif labelSelector != nil {\n\t\tfor key := range labelSelector.MatchLabels {\n\t\t\tlabelSelectorKeys.Insert(key)\n\t\t}\n\t\tfor _, matchExpression := range labelSelector.MatchExpressions {\n\t\t\tlabelSelectorKeys.Insert(matchExpression.Key)\n\t\t}\n\t} else {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath, \"must not be specified when labelSelector is not set\"))\n\t}\n\n\tfor i, key := range matchLabelKeys {\n\t\tallErrs = append(allErrs, unversionedvalidation.ValidateLabelName(key, fldPath.Index(i))...)\n\t\tif labelSelectorKeys.Has(key) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Index(i), key, \"exists in both matchLabelKeys and labelSelector\"))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":7004,"to":7032}} {"id":100002709,"name":"ValidateServiceClusterIPsRelatedFields","signature":"func ValidateServiceClusterIPsRelatedFields(service *core.Service) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// ValidateServiceClusterIPsRelatedFields validates .spec.ClusterIPs,,\n// .spec.IPFamilies, .spec.ipFamilyPolicy. This is exported because it is used\n// during IP init and allocation.\nfunc ValidateServiceClusterIPsRelatedFields(service *core.Service) field.ErrorList {\n\t// ClusterIP, ClusterIPs, IPFamilyPolicy and IPFamilies are validated prior (all must be unset) for ExternalName service\n\tif service.Spec.Type == core.ServiceTypeExternalName {\n\t\treturn field.ErrorList{}\n\t}\n\n\tallErrs := field.ErrorList{}\n\thasInvalidIPs := false\n\n\tspecPath := field.NewPath(\"spec\")\n\tclusterIPsField := specPath.Child(\"clusterIPs\")\n\tipFamiliesField := specPath.Child(\"ipFamilies\")\n\tipFamilyPolicyField := specPath.Child(\"ipFamilyPolicy\")\n\n\t// Make sure ClusterIP and ClusterIPs are synced. For most cases users can\n\t// just manage one or the other and we'll handle the rest (see PrepareFor*\n\t// in strategy).\n\tif len(service.Spec.ClusterIP) != 0 {\n\t\t// If ClusterIP is set, ClusterIPs[0] must match.\n\t\tif len(service.Spec.ClusterIPs) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(clusterIPsField, \"\"))\n\t\t} else if service.Spec.ClusterIPs[0] != service.Spec.ClusterIP {\n\t\t\tallErrs = append(allErrs, field.Invalid(clusterIPsField, service.Spec.ClusterIPs, \"first value must match `clusterIP`\"))\n\t\t}\n\t} else { // ClusterIP == \"\"\n\t\t// If ClusterIP is not set, ClusterIPs must also be unset.\n\t\tif len(service.Spec.ClusterIPs) != 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(clusterIPsField, service.Spec.ClusterIPs, \"must be empty when `clusterIP` is not specified\"))\n\t\t}\n\t}\n\n\t// ipfamilies stand alone validation\n\t// must be either IPv4 or IPv6\n\tseen := sets.String{}\n\tfor i, ipFamily := range service.Spec.IPFamilies {\n\t\tif !supportedServiceIPFamily.Has(string(ipFamily)) {\n\t\t\tallErrs = append(allErrs, field.NotSupported(ipFamiliesField.Index(i), ipFamily, supportedServiceIPFamily.List()))\n\t\t}\n\t\t// no duplicate check also ensures that ipfamilies is dualstacked, in any order\n\t\tif seen.Has(string(ipFamily)) {\n\t\t\tallErrs = append(allErrs, field.Duplicate(ipFamiliesField.Index(i), ipFamily))\n\t\t}\n\t\tseen.Insert(string(ipFamily))\n\t}\n\n\t// IPFamilyPolicy stand alone validation\n\t// note: nil is ok, defaulted in alloc check registry/core/service/*\n\tif service.Spec.IPFamilyPolicy != nil {\n\t\t// must have a supported value\n\t\tif !supportedServiceIPFamilyPolicy.Has(string(*(service.Spec.IPFamilyPolicy))) {\n\t\t\tallErrs = append(allErrs, field.NotSupported(ipFamilyPolicyField, service.Spec.IPFamilyPolicy, supportedServiceIPFamilyPolicy.List()))\n\t\t}\n\t}\n\n\t// clusterIPs stand alone validation\n\t// valid ips with None and empty string handling\n\t// duplication check is done as part of DualStackvalidation below\n\tfor i, clusterIP := range service.Spec.ClusterIPs {\n\t\t// valid at first location only. if and only if len(clusterIPs) == 1\n\t\tif i == 0 \u0026\u0026 clusterIP == core.ClusterIPNone {\n\t\t\tif len(service.Spec.ClusterIPs) \u003e 1 {\n\t\t\t\thasInvalidIPs = true\n\t\t\t\tallErrs = append(allErrs, field.Invalid(clusterIPsField, service.Spec.ClusterIPs, \"'None' must be the first and only value\"))\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// is it valid ip?\n\t\terrorMessages := validation.IsValidIP(clusterIP)\n\t\thasInvalidIPs = (len(errorMessages) != 0) || hasInvalidIPs\n\t\tfor _, msg := range errorMessages {\n\t\t\tallErrs = append(allErrs, field.Invalid(clusterIPsField.Index(i), clusterIP, msg))\n\t\t}\n\t}\n\n\t// max two\n\tif len(service.Spec.ClusterIPs) \u003e 2 {\n\t\tallErrs = append(allErrs, field.Invalid(clusterIPsField, service.Spec.ClusterIPs, \"may only hold up to 2 values\"))\n\t}\n\n\t// at this stage if there is an invalid ip or misplaced none/empty string\n\t// it will skew the error messages (bad index || dualstackness of already bad ips). so we\n\t// stop here if there are errors in clusterIPs validation\n\tif hasInvalidIPs {\n\t\treturn allErrs\n\t}\n\n\t// must be dual stacked ips if they are more than one ip\n\tif len(service.Spec.ClusterIPs) \u003e 1 /* meaning: it does not have a None or empty string */ {\n\t\tdualStack, err := netutils.IsDualStackIPStrings(service.Spec.ClusterIPs)\n\t\tif err != nil { // though we check for that earlier. safe \u003e sorry\n\t\t\tallErrs = append(allErrs, field.InternalError(clusterIPsField, fmt.Errorf(\"failed to check for dual stack with error:%v\", err)))\n\t\t}\n\n\t\t// We only support one from each IP family (i.e. max two IPs in this list).\n\t\tif !dualStack {\n\t\t\tallErrs = append(allErrs, field.Invalid(clusterIPsField, service.Spec.ClusterIPs, \"may specify no more than one IP for each IP family\"))\n\t\t}\n\t}\n\n\t// match clusterIPs to their families, if they were provided\n\tif !isHeadlessService(service) \u0026\u0026 len(service.Spec.ClusterIPs) \u003e 0 \u0026\u0026 len(service.Spec.IPFamilies) \u003e 0 {\n\t\tfor i, ip := range service.Spec.ClusterIPs {\n\t\t\tif i \u003e (len(service.Spec.IPFamilies) - 1) {\n\t\t\t\tbreak // no more families to check\n\t\t\t}\n\n\t\t\t// 4=\u003e6\n\t\t\tif service.Spec.IPFamilies[i] == core.IPv4Protocol \u0026\u0026 netutils.IsIPv6String(ip) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(clusterIPsField.Index(i), ip, fmt.Sprintf(\"expected an IPv4 value as indicated by `ipFamilies[%v]`\", i)))\n\t\t\t}\n\t\t\t// 6=\u003e4\n\t\t\tif service.Spec.IPFamilies[i] == core.IPv6Protocol \u0026\u0026 !netutils.IsIPv6String(ip) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(clusterIPsField.Index(i), ip, fmt.Sprintf(\"expected an IPv6 value as indicated by `ipFamilies[%v]`\", i)))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":7034,"to":7156}} {"id":100002710,"name":"validateUpgradeDowngradeClusterIPs","signature":"func validateUpgradeDowngradeClusterIPs(oldService, service *core.Service) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// specific validation for clusterIPs in cases of user upgrading or downgrading to/from dualstack\nfunc validateUpgradeDowngradeClusterIPs(oldService, service *core.Service) field.ErrorList {\n\tallErrs := make(field.ErrorList, 0)\n\n\t// bail out early for ExternalName\n\tif service.Spec.Type == core.ServiceTypeExternalName || oldService.Spec.Type == core.ServiceTypeExternalName {\n\t\treturn allErrs\n\t}\n\tnewIsHeadless := isHeadlessService(service)\n\toldIsHeadless := isHeadlessService(oldService)\n\n\tif oldIsHeadless \u0026\u0026 newIsHeadless {\n\t\treturn allErrs\n\t}\n\n\tswitch {\n\t// no change in ClusterIP lengths\n\t// compare each\n\tcase len(oldService.Spec.ClusterIPs) == len(service.Spec.ClusterIPs):\n\t\tfor i, ip := range oldService.Spec.ClusterIPs {\n\t\t\tif ip != service.Spec.ClusterIPs[i] {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"spec\", \"clusterIPs\").Index(i), service.Spec.ClusterIPs, \"may not change once set\"))\n\t\t\t}\n\t\t}\n\n\t// something has been released (downgraded)\n\tcase len(oldService.Spec.ClusterIPs) \u003e len(service.Spec.ClusterIPs):\n\t\t// primary ClusterIP has been released\n\t\tif len(service.Spec.ClusterIPs) == 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"spec\", \"clusterIPs\").Index(0), service.Spec.ClusterIPs, \"primary clusterIP can not be unset\"))\n\t\t}\n\n\t\t// test if primary clusterIP has changed\n\t\tif len(oldService.Spec.ClusterIPs) \u003e 0 \u0026\u0026\n\t\t\tlen(service.Spec.ClusterIPs) \u003e 0 \u0026\u0026\n\t\t\tservice.Spec.ClusterIPs[0] != oldService.Spec.ClusterIPs[0] {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"spec\", \"clusterIPs\").Index(0), service.Spec.ClusterIPs, \"may not change once set\"))\n\t\t}\n\n\t\t// test if secondary ClusterIP has been released. has this service been downgraded correctly?\n\t\t// user *must* set IPFamilyPolicy == SingleStack\n\t\tif len(service.Spec.ClusterIPs) == 1 {\n\t\t\tif service.Spec.IPFamilyPolicy == nil || *(service.Spec.IPFamilyPolicy) != core.IPFamilyPolicySingleStack {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"spec\", \"ipFamilyPolicy\"), service.Spec.IPFamilyPolicy, \"must be set to 'SingleStack' when releasing the secondary clusterIP\"))\n\t\t\t}\n\t\t}\n\tcase len(oldService.Spec.ClusterIPs) \u003c len(service.Spec.ClusterIPs):\n\t\t// something has been added (upgraded)\n\t\t// test if primary clusterIP has changed\n\t\tif len(oldService.Spec.ClusterIPs) \u003e 0 \u0026\u0026\n\t\t\tservice.Spec.ClusterIPs[0] != oldService.Spec.ClusterIPs[0] {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"spec\", \"clusterIPs\").Index(0), service.Spec.ClusterIPs, \"may not change once set\"))\n\t\t}\n\t\t// we don't check for Policy == RequireDualStack here since, Validation/Creation func takes care of it\n\t}\n\treturn allErrs\n}","line":{"from":7158,"to":7214}} {"id":100002711,"name":"validateUpgradeDowngradeIPFamilies","signature":"func validateUpgradeDowngradeIPFamilies(oldService, service *core.Service) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// specific validation for ipFamilies in cases of user upgrading or downgrading to/from dualstack\nfunc validateUpgradeDowngradeIPFamilies(oldService, service *core.Service) field.ErrorList {\n\tallErrs := make(field.ErrorList, 0)\n\t// bail out early for ExternalName\n\tif service.Spec.Type == core.ServiceTypeExternalName || oldService.Spec.Type == core.ServiceTypeExternalName {\n\t\treturn allErrs\n\t}\n\n\toldIsHeadless := isHeadlessService(oldService)\n\tnewIsHeadless := isHeadlessService(service)\n\n\t// if changed to/from headless, then bail out\n\tif newIsHeadless != oldIsHeadless {\n\t\treturn allErrs\n\t}\n\t// headless can change families\n\tif newIsHeadless {\n\t\treturn allErrs\n\t}\n\n\tswitch {\n\tcase len(oldService.Spec.IPFamilies) == len(service.Spec.IPFamilies):\n\t\t// no change in ClusterIP lengths\n\t\t// compare each\n\n\t\tfor i, ip := range oldService.Spec.IPFamilies {\n\t\t\tif ip != service.Spec.IPFamilies[i] {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"spec\", \"ipFamilies\").Index(0), service.Spec.IPFamilies, \"may not change once set\"))\n\t\t\t}\n\t\t}\n\n\tcase len(oldService.Spec.IPFamilies) \u003e len(service.Spec.IPFamilies):\n\t\t// something has been released (downgraded)\n\n\t\t// test if primary ipfamily has been released\n\t\tif len(service.Spec.ClusterIPs) == 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"spec\", \"ipFamilies\").Index(0), service.Spec.IPFamilies, \"primary ipFamily can not be unset\"))\n\t\t}\n\n\t\t// test if primary ipFamily has changed\n\t\tif len(service.Spec.IPFamilies) \u003e 0 \u0026\u0026\n\t\t\tservice.Spec.IPFamilies[0] != oldService.Spec.IPFamilies[0] {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"spec\", \"ipFamilies\").Index(0), service.Spec.ClusterIPs, \"may not change once set\"))\n\t\t}\n\n\t\t// test if secondary IPFamily has been released. has this service been downgraded correctly?\n\t\t// user *must* set IPFamilyPolicy == SingleStack\n\t\tif len(service.Spec.IPFamilies) == 1 {\n\t\t\tif service.Spec.IPFamilyPolicy == nil || *(service.Spec.IPFamilyPolicy) != core.IPFamilyPolicySingleStack {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"spec\", \"ipFamilyPolicy\"), service.Spec.IPFamilyPolicy, \"must be set to 'SingleStack' when releasing the secondary ipFamily\"))\n\t\t\t}\n\t\t}\n\tcase len(oldService.Spec.IPFamilies) \u003c len(service.Spec.IPFamilies):\n\t\t// something has been added (upgraded)\n\n\t\t// test if primary ipFamily has changed\n\t\tif len(oldService.Spec.IPFamilies) \u003e 0 \u0026\u0026\n\t\t\tlen(service.Spec.IPFamilies) \u003e 0 \u0026\u0026\n\t\t\tservice.Spec.IPFamilies[0] != oldService.Spec.IPFamilies[0] {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"spec\", \"ipFamilies\").Index(0), service.Spec.ClusterIPs, \"may not change once set\"))\n\t\t}\n\t\t// we don't check for Policy == RequireDualStack here since, Validation/Creation func takes care of it\n\t}\n\treturn allErrs\n}","line":{"from":7216,"to":7280}} {"id":100002712,"name":"isHeadlessService","signature":"func isHeadlessService(service *core.Service) bool","file":"pkg/apis/core/validation/validation.go","code":"func isHeadlessService(service *core.Service) bool {\n\treturn service != nil \u0026\u0026\n\t\tlen(service.Spec.ClusterIPs) == 1 \u0026\u0026\n\t\tservice.Spec.ClusterIPs[0] == core.ClusterIPNone\n}","line":{"from":7282,"to":7286}} {"id":100002713,"name":"validateLoadBalancerClassField","signature":"func validateLoadBalancerClassField(oldService, service *core.Service) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"// validateLoadBalancerClassField validation for loadBalancerClass\nfunc validateLoadBalancerClassField(oldService, service *core.Service) field.ErrorList {\n\tallErrs := make(field.ErrorList, 0)\n\tif oldService != nil {\n\t\t// validate update op\n\t\tif isTypeLoadBalancer(oldService) \u0026\u0026 isTypeLoadBalancer(service) {\n\t\t\t// old and new are both LoadBalancer\n\t\t\tif !sameLoadBalancerClass(oldService, service) {\n\t\t\t\t// can't change loadBalancerClass\n\t\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"spec\", \"loadBalancerClass\"), service.Spec.LoadBalancerClass, \"may not change once set\"))\n\t\t\t}\n\t\t}\n\t}\n\n\tif isTypeLoadBalancer(service) {\n\t\t// check LoadBalancerClass format\n\t\tif service.Spec.LoadBalancerClass != nil {\n\t\t\tallErrs = append(allErrs, ValidateQualifiedName(*service.Spec.LoadBalancerClass, field.NewPath(\"spec\", \"loadBalancerClass\"))...)\n\t\t}\n\t} else {\n\t\t// check if LoadBalancerClass set for non LoadBalancer type of service\n\t\tif service.Spec.LoadBalancerClass != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"spec\", \"loadBalancerClass\"), \"may only be used when `type` is 'LoadBalancer'\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":7288,"to":7314}} {"id":100002714,"name":"isTypeLoadBalancer","signature":"func isTypeLoadBalancer(service *core.Service) bool","file":"pkg/apis/core/validation/validation.go","code":"// isTypeLoadBalancer tests service type is loadBalancer or not\nfunc isTypeLoadBalancer(service *core.Service) bool {\n\treturn service.Spec.Type == core.ServiceTypeLoadBalancer\n}","line":{"from":7316,"to":7319}} {"id":100002715,"name":"sameLoadBalancerClass","signature":"func sameLoadBalancerClass(oldService, service *core.Service) bool","file":"pkg/apis/core/validation/validation.go","code":"// sameLoadBalancerClass check two services have the same loadBalancerClass or not\nfunc sameLoadBalancerClass(oldService, service *core.Service) bool {\n\tif oldService.Spec.LoadBalancerClass == nil \u0026\u0026 service.Spec.LoadBalancerClass == nil {\n\t\treturn true\n\t}\n\tif oldService.Spec.LoadBalancerClass == nil || service.Spec.LoadBalancerClass == nil {\n\t\treturn false\n\t}\n\treturn *oldService.Spec.LoadBalancerClass == *service.Spec.LoadBalancerClass\n}","line":{"from":7321,"to":7330}} {"id":100002716,"name":"ValidatePodAffinityTermSelector","signature":"func ValidatePodAffinityTermSelector(podAffinityTerm core.PodAffinityTerm, allowInvalidLabelValueInSelector bool, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func ValidatePodAffinityTermSelector(podAffinityTerm core.PodAffinityTerm, allowInvalidLabelValueInSelector bool, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tlabelSelectorValidationOptions := unversionedvalidation.LabelSelectorValidationOptions{AllowInvalidLabelValueInSelector: allowInvalidLabelValueInSelector}\n\tallErrs = append(allErrs, unversionedvalidation.ValidateLabelSelector(podAffinityTerm.LabelSelector, labelSelectorValidationOptions, fldPath.Child(\"labelSelector\"))...)\n\tallErrs = append(allErrs, unversionedvalidation.ValidateLabelSelector(podAffinityTerm.NamespaceSelector, labelSelectorValidationOptions, fldPath.Child(\"namespaceSelector\"))...)\n\treturn allErrs\n}","line":{"from":7332,"to":7338}} {"id":100002717,"name":"getMaskNodeSelectorLabelChangeEqualities","signature":"func getMaskNodeSelectorLabelChangeEqualities() conversion.Equalities","file":"pkg/apis/core/validation/validation.go","code":"func getMaskNodeSelectorLabelChangeEqualities() conversion.Equalities {\n\tinitMaskNodeSelectorLabelChangeEqualities.Do(func() {\n\t\tvar eqs = apiequality.Semantic.Copy()\n\t\terr := eqs.AddFunc(\n\t\t\tfunc(newReq, oldReq core.NodeSelectorRequirement) bool {\n\t\t\t\t// allow newReq to change to a GA key\n\t\t\t\tif oldReq.Key != newReq.Key \u0026\u0026 betaToGALabel[oldReq.Key] == newReq.Key {\n\t\t\t\t\toldReq.Key = newReq.Key // +k8s:verify-mutation:reason=clone\n\t\t\t\t}\n\t\t\t\treturn apiequality.Semantic.DeepEqual(newReq, oldReq)\n\t\t\t},\n\t\t)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"failed to instantiate semantic equalities: %w\", err))\n\t\t}\n\t\tmaskNodeSelectorLabelChangeEqualities = eqs\n\t})\n\treturn maskNodeSelectorLabelChangeEqualities\n}","line":{"from":7353,"to":7371}} {"id":100002718,"name":"validatePvNodeAffinity","signature":"func validatePvNodeAffinity(newPvNodeAffinity, oldPvNodeAffinity *core.VolumeNodeAffinity, fldPath *field.Path) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validatePvNodeAffinity(newPvNodeAffinity, oldPvNodeAffinity *core.VolumeNodeAffinity, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tif !getMaskNodeSelectorLabelChangeEqualities().DeepEqual(newPvNodeAffinity, oldPvNodeAffinity) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, newPvNodeAffinity, fieldImmutableErrorMsg+\", except for updating from beta label to GA\"))\n\t}\n\treturn allErrs\n}","line":{"from":7373,"to":7379}} {"id":100002719,"name":"validateNodeSelectorMutation","signature":"func validateNodeSelectorMutation(fldPath *field.Path, newNodeSelector, oldNodeSelector map[string]string) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateNodeSelectorMutation(fldPath *field.Path, newNodeSelector, oldNodeSelector map[string]string) field.ErrorList {\n\tvar allErrs field.ErrorList\n\n\t// Validate no existing node selectors were deleted or mutated.\n\tfor k, v1 := range oldNodeSelector {\n\t\tif v2, ok := newNodeSelector[k]; !ok || v1 != v2 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, newNodeSelector, \"only additions to spec.nodeSelector are allowed (no mutations or deletions)\"))\n\t\t\treturn allErrs\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":7381,"to":7392}} {"id":100002720,"name":"validateNodeAffinityMutation","signature":"func validateNodeAffinityMutation(nodeAffinityPath *field.Path, newNodeAffinity, oldNodeAffinity *core.NodeAffinity) field.ErrorList","file":"pkg/apis/core/validation/validation.go","code":"func validateNodeAffinityMutation(nodeAffinityPath *field.Path, newNodeAffinity, oldNodeAffinity *core.NodeAffinity) field.ErrorList {\n\tvar allErrs field.ErrorList\n\t// If old node affinity was nil, anything can be set.\n\tif oldNodeAffinity == nil || oldNodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution == nil {\n\t\treturn allErrs\n\t}\n\n\toldTerms := oldNodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution.NodeSelectorTerms\n\tvar newTerms []core.NodeSelectorTerm\n\tif newNodeAffinity != nil \u0026\u0026 newNodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution != nil {\n\t\tnewTerms = newNodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution.NodeSelectorTerms\n\t}\n\n\t// If there are no old terms, we can set the new terms to anything.\n\t// If there are old terms, we cannot add any new ones.\n\tif len(oldTerms) \u003e 0 \u0026\u0026 len(oldTerms) != len(newTerms) {\n\t\treturn append(allErrs, field.Invalid(nodeAffinityPath.Child(\"requiredDuringSchedulingIgnoredDuringExecution\").Child(\"nodeSelectorTerms\"), newTerms, \"no additions/deletions to non-empty NodeSelectorTerms list are allowed\"))\n\t}\n\n\t// For requiredDuringSchedulingIgnoredDuringExecution, if old NodeSelectorTerms\n\t// was empty, anything can be set. If non-empty, only additions of NodeSelectorRequirements\n\t// to matchExpressions or fieldExpressions are allowed.\n\tfor i := range oldTerms {\n\t\tif !validateNodeSelectorTermHasOnlyAdditions(newTerms[i], oldTerms[i]) {\n\t\t\tallErrs = append(allErrs, field.Invalid(nodeAffinityPath.Child(\"requiredDuringSchedulingIgnoredDuringExecution\").Child(\"nodeSelectorTerms\").Index(i), newTerms[i], \"only additions are allowed (no mutations or deletions)\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":7394,"to":7422}} {"id":100002721,"name":"validateNodeSelectorTermHasOnlyAdditions","signature":"func validateNodeSelectorTermHasOnlyAdditions(newTerm, oldTerm core.NodeSelectorTerm) bool","file":"pkg/apis/core/validation/validation.go","code":"func validateNodeSelectorTermHasOnlyAdditions(newTerm, oldTerm core.NodeSelectorTerm) bool {\n\tif len(oldTerm.MatchExpressions) == 0 \u0026\u0026 len(oldTerm.MatchFields) == 0 {\n\t\tif len(newTerm.MatchExpressions) \u003e 0 || len(newTerm.MatchFields) \u003e 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// Validate MatchExpressions only has additions (no deletions or mutations)\n\tif l := len(oldTerm.MatchExpressions); l \u003e 0 {\n\t\tif len(newTerm.MatchExpressions) \u003c l {\n\t\t\treturn false\n\t\t}\n\t\tif !apiequality.Semantic.DeepEqual(newTerm.MatchExpressions[:l], oldTerm.MatchExpressions) {\n\t\t\treturn false\n\t\t}\n\t}\n\t// Validate MatchFields only has additions (no deletions or mutations)\n\tif l := len(oldTerm.MatchFields); l \u003e 0 {\n\t\tif len(newTerm.MatchFields) \u003c l {\n\t\t\treturn false\n\t\t}\n\t\tif !apiequality.Semantic.DeepEqual(newTerm.MatchFields[:l], oldTerm.MatchFields) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":7424,"to":7450}} {"id":100002722,"name":"init","signature":"func init()","file":"pkg/apis/discovery/install/install.go","code":"func init() {\n\tInstall(legacyscheme.Scheme)\n}","line":{"from":30,"to":32}} {"id":100002723,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"pkg/apis/discovery/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(discovery.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1beta1.SchemeGroupVersion, v1.SchemeGroupVersion))\n}","line":{"from":34,"to":40}} {"id":100002724,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"pkg/apis/discovery/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100002725,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/discovery/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100002726,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/discovery/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026EndpointSlice{},\n\t\t\u0026EndpointSliceList{},\n\t)\n\treturn nil\n}","line":{"from":47,"to":54}} {"id":100002727,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/discovery/v1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":30,"to":32}} {"id":100002728,"name":"SetDefaults_EndpointPort","signature":"func SetDefaults_EndpointPort(obj *discoveryv1.EndpointPort)","file":"pkg/apis/discovery/v1/defaults.go","code":"func SetDefaults_EndpointPort(obj *discoveryv1.EndpointPort) {\n\tif obj.Name == nil {\n\t\tobj.Name = \u0026defaultPortName\n\t}\n\n\tif obj.Protocol == nil {\n\t\tobj.Protocol = \u0026defaultProtocol\n\t}\n}","line":{"from":34,"to":42}} {"id":100002729,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/discovery/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002730,"name":"init","signature":"func init()","file":"pkg/apis/discovery/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":40,"to":45}} {"id":100002731,"name":"Convert_v1beta1_Endpoint_To_discovery_Endpoint","signature":"func Convert_v1beta1_Endpoint_To_discovery_Endpoint(in *v1beta1.Endpoint, out *discovery.Endpoint, s conversion.Scope) error","file":"pkg/apis/discovery/v1beta1/conversion.go","code":"func Convert_v1beta1_Endpoint_To_discovery_Endpoint(in *v1beta1.Endpoint, out *discovery.Endpoint, s conversion.Scope) error {\n\tif err := autoConvert_v1beta1_Endpoint_To_discovery_Endpoint(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tif in.Topology != nil {\n\t\t// Copy\tTopology into Deprecated Topology\n\t\tout.DeprecatedTopology = make(map[string]string, len(in.Topology))\n\t\tfor k, v := range in.Topology {\n\t\t\tout.DeprecatedTopology[k] = v\n\t\t}\n\n\t\t// Move zone from the topology map into a field\n\t\tif zone, ok := in.Topology[corev1.LabelTopologyZone]; ok {\n\t\t\tout.Zone = \u0026zone\n\t\t\tdelete(out.DeprecatedTopology, corev1.LabelTopologyZone)\n\t\t}\n\n\t\t// Remove hostname from the topology map ONLY IF it is the same value as\n\t\t// nodeName. This preserves the (rather odd) ability to have different\n\t\t// values for topology[hostname] and nodename in v1beta1, without showing\n\t\t// duplicate values in v1.\n\t\tif node, ok := in.Topology[corev1.LabelHostname]; ok {\n\t\t\tif out.NodeName != nil \u0026\u0026 node == *out.NodeName {\n\t\t\t\tdelete(out.DeprecatedTopology, corev1.LabelHostname)\n\t\t\t}\n\t\t}\n\n\t\t// If zone \u0026 hostname were the only field in the map or topology was empty\n\t\t// set DeprecatedTopology to nil\n\t\tif len(out.DeprecatedTopology) == 0 {\n\t\t\tout.DeprecatedTopology = nil\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":26,"to":61}} {"id":100002732,"name":"Convert_discovery_Endpoint_To_v1beta1_Endpoint","signature":"func Convert_discovery_Endpoint_To_v1beta1_Endpoint(in *discovery.Endpoint, out *v1beta1.Endpoint, s conversion.Scope) error","file":"pkg/apis/discovery/v1beta1/conversion.go","code":"func Convert_discovery_Endpoint_To_v1beta1_Endpoint(in *discovery.Endpoint, out *v1beta1.Endpoint, s conversion.Scope) error {\n\tif err := autoConvert_discovery_Endpoint_To_v1beta1_Endpoint(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\t// If no deprecated topology, zone or node field, no conversion is necessary\n\tif in.DeprecatedTopology == nil \u0026\u0026 in.Zone == nil \u0026\u0026 in.NodeName == nil {\n\t\treturn nil\n\t}\n\n\t// Copy\tDeprecated Topology into Topology\n\tout.Topology = make(map[string]string, len(in.DeprecatedTopology))\n\tfor k, v := range in.DeprecatedTopology {\n\t\tout.Topology[k] = v\n\t}\n\n\t// Add zone field into the topology map\n\tif in.Zone != nil {\n\t\tout.Topology[corev1.LabelTopologyZone] = *in.Zone\n\t}\n\n\t// Add hostname into the topology map ONLY IF it is not already present.\n\t// This preserves the (rather odd) ability to have different values for\n\t// topology[hostname] and nodename in v1beta1.\n\tif in.NodeName != nil \u0026\u0026 out.Topology[corev1.LabelHostname] == \"\" {\n\t\tout.Topology[corev1.LabelHostname] = *in.NodeName\n\t}\n\n\treturn nil\n}","line":{"from":63,"to":92}} {"id":100002733,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/discovery/v1beta1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":30,"to":32}} {"id":100002734,"name":"SetDefaults_EndpointPort","signature":"func SetDefaults_EndpointPort(obj *discoveryv1beta1.EndpointPort)","file":"pkg/apis/discovery/v1beta1/defaults.go","code":"func SetDefaults_EndpointPort(obj *discoveryv1beta1.EndpointPort) {\n\tif obj.Name == nil {\n\t\tobj.Name = \u0026defaultPortName\n\t}\n\n\tif obj.Protocol == nil {\n\t\tobj.Protocol = \u0026defaultProtocol\n\t}\n}","line":{"from":34,"to":42}} {"id":100002735,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/discovery/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002736,"name":"init","signature":"func init()","file":"pkg/apis/discovery/v1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":40,"to":45}} {"id":100002737,"name":"ValidateEndpointSlice","signature":"func ValidateEndpointSlice(endpointSlice *discovery.EndpointSlice) field.ErrorList","file":"pkg/apis/discovery/validation/validation.go","code":"// ValidateEndpointSlice validates an EndpointSlice.\nfunc ValidateEndpointSlice(endpointSlice *discovery.EndpointSlice) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMeta(\u0026endpointSlice.ObjectMeta, true, ValidateEndpointSliceName, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, validateAddressType(endpointSlice.AddressType)...)\n\tallErrs = append(allErrs, validateEndpoints(endpointSlice.Endpoints, endpointSlice.AddressType, field.NewPath(\"endpoints\"))...)\n\tallErrs = append(allErrs, validatePorts(endpointSlice.Ports, field.NewPath(\"ports\"))...)\n\n\treturn allErrs\n}","line":{"from":56,"to":64}} {"id":100002738,"name":"ValidateEndpointSliceCreate","signature":"func ValidateEndpointSliceCreate(endpointSlice *discovery.EndpointSlice) field.ErrorList","file":"pkg/apis/discovery/validation/validation.go","code":"// ValidateEndpointSliceCreate validates an EndpointSlice when it is created.\nfunc ValidateEndpointSliceCreate(endpointSlice *discovery.EndpointSlice) field.ErrorList {\n\treturn ValidateEndpointSlice(endpointSlice)\n}","line":{"from":66,"to":69}} {"id":100002739,"name":"ValidateEndpointSliceUpdate","signature":"func ValidateEndpointSliceUpdate(newEndpointSlice, oldEndpointSlice *discovery.EndpointSlice) field.ErrorList","file":"pkg/apis/discovery/validation/validation.go","code":"// ValidateEndpointSliceUpdate validates an EndpointSlice when it is updated.\nfunc ValidateEndpointSliceUpdate(newEndpointSlice, oldEndpointSlice *discovery.EndpointSlice) field.ErrorList {\n\tallErrs := ValidateEndpointSlice(newEndpointSlice)\n\tallErrs = append(allErrs, apivalidation.ValidateImmutableField(newEndpointSlice.AddressType, oldEndpointSlice.AddressType, field.NewPath(\"addressType\"))...)\n\n\treturn allErrs\n}","line":{"from":71,"to":77}} {"id":100002740,"name":"validateEndpoints","signature":"func validateEndpoints(endpoints []discovery.Endpoint, addrType discovery.AddressType, fldPath *field.Path) field.ErrorList","file":"pkg/apis/discovery/validation/validation.go","code":"func validateEndpoints(endpoints []discovery.Endpoint, addrType discovery.AddressType, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(endpoints) \u003e maxEndpoints {\n\t\tallErrs = append(allErrs, field.TooMany(fldPath, len(endpoints), maxEndpoints))\n\t\treturn allErrs\n\t}\n\n\tfor i, endpoint := range endpoints {\n\t\tidxPath := fldPath.Index(i)\n\t\taddressPath := idxPath.Child(\"addresses\")\n\n\t\tif len(endpoint.Addresses) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(addressPath, \"must contain at least 1 address\"))\n\t\t} else if len(endpoint.Addresses) \u003e maxAddresses {\n\t\t\tallErrs = append(allErrs, field.TooMany(addressPath, len(endpoint.Addresses), maxAddresses))\n\t\t}\n\n\t\tfor i, address := range endpoint.Addresses {\n\t\t\t// This validates known address types, unknown types fall through\n\t\t\t// and do not get validated.\n\t\t\tswitch addrType {\n\t\t\tcase discovery.AddressTypeIPv4:\n\t\t\t\tallErrs = append(allErrs, validation.IsValidIPv4Address(addressPath.Index(i), address)...)\n\t\t\t\tallErrs = append(allErrs, apivalidation.ValidateNonSpecialIP(address, addressPath.Index(i))...)\n\t\t\tcase discovery.AddressTypeIPv6:\n\t\t\t\tallErrs = append(allErrs, validation.IsValidIPv6Address(addressPath.Index(i), address)...)\n\t\t\t\tallErrs = append(allErrs, apivalidation.ValidateNonSpecialIP(address, addressPath.Index(i))...)\n\t\t\tcase discovery.AddressTypeFQDN:\n\t\t\t\tallErrs = append(allErrs, validation.IsFullyQualifiedDomainName(addressPath.Index(i), address)...)\n\t\t\t}\n\t\t}\n\n\t\tif endpoint.NodeName != nil {\n\t\t\tnnPath := idxPath.Child(\"nodeName\")\n\t\t\tfor _, msg := range apivalidation.ValidateNodeName(*endpoint.NodeName, false) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(nnPath, *endpoint.NodeName, msg))\n\t\t\t}\n\t\t}\n\n\t\ttopologyPath := idxPath.Child(\"deprecatedTopology\")\n\t\tif len(endpoint.DeprecatedTopology) \u003e maxTopologyLabels {\n\t\t\tallErrs = append(allErrs, field.TooMany(topologyPath, len(endpoint.DeprecatedTopology), maxTopologyLabels))\n\t\t}\n\t\tallErrs = append(allErrs, metavalidation.ValidateLabels(endpoint.DeprecatedTopology, topologyPath)...)\n\t\tif _, found := endpoint.DeprecatedTopology[corev1.LabelTopologyZone]; found {\n\t\t\tallErrs = append(allErrs, field.InternalError(topologyPath.Key(corev1.LabelTopologyZone), fmt.Errorf(\"reserved key was not removed in conversion\")))\n\t\t}\n\n\t\tif endpoint.Hostname != nil {\n\t\t\tallErrs = append(allErrs, apivalidation.ValidateDNS1123Label(*endpoint.Hostname, idxPath.Child(\"hostname\"))...)\n\t\t}\n\n\t\tif endpoint.Hints != nil {\n\t\t\tallErrs = append(allErrs, validateHints(endpoint.Hints, idxPath.Child(\"hints\"))...)\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":79,"to":138}} {"id":100002741,"name":"validatePorts","signature":"func validatePorts(endpointPorts []discovery.EndpointPort, fldPath *field.Path) field.ErrorList","file":"pkg/apis/discovery/validation/validation.go","code":"func validatePorts(endpointPorts []discovery.EndpointPort, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(endpointPorts) \u003e maxPorts {\n\t\tallErrs = append(allErrs, field.TooMany(fldPath, len(endpointPorts), maxPorts))\n\t\treturn allErrs\n\t}\n\n\tportNames := sets.String{}\n\tfor i, endpointPort := range endpointPorts {\n\t\tidxPath := fldPath.Index(i)\n\n\t\tif len(*endpointPort.Name) \u003e 0 {\n\t\t\tallErrs = append(allErrs, apivalidation.ValidateDNS1123Label(*endpointPort.Name, idxPath.Child(\"name\"))...)\n\t\t}\n\n\t\tif portNames.Has(*endpointPort.Name) {\n\t\t\tallErrs = append(allErrs, field.Duplicate(idxPath.Child(\"name\"), endpointPort.Name))\n\t\t} else {\n\t\t\tportNames.Insert(*endpointPort.Name)\n\t\t}\n\n\t\tif endpointPort.Protocol == nil {\n\t\t\tallErrs = append(allErrs, field.Required(idxPath.Child(\"protocol\"), \"\"))\n\t\t} else if !supportedPortProtocols.Has(string(*endpointPort.Protocol)) {\n\t\t\tallErrs = append(allErrs, field.NotSupported(idxPath.Child(\"protocol\"), *endpointPort.Protocol, supportedPortProtocols.List()))\n\t\t}\n\n\t\tif endpointPort.AppProtocol != nil {\n\t\t\tallErrs = append(allErrs, apivalidation.ValidateQualifiedName(*endpointPort.AppProtocol, idxPath.Child(\"appProtocol\"))...)\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":140,"to":174}} {"id":100002742,"name":"validateAddressType","signature":"func validateAddressType(addressType discovery.AddressType) field.ErrorList","file":"pkg/apis/discovery/validation/validation.go","code":"func validateAddressType(addressType discovery.AddressType) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif addressType == \"\" {\n\t\tallErrs = append(allErrs, field.Required(field.NewPath(\"addressType\"), \"\"))\n\t} else if !supportedAddressTypes.Has(string(addressType)) {\n\t\tallErrs = append(allErrs, field.NotSupported(field.NewPath(\"addressType\"), addressType, supportedAddressTypes.List()))\n\t}\n\n\treturn allErrs\n}","line":{"from":176,"to":186}} {"id":100002743,"name":"validateHints","signature":"func validateHints(endpointHints *discovery.EndpointHints, fldPath *field.Path) field.ErrorList","file":"pkg/apis/discovery/validation/validation.go","code":"func validateHints(endpointHints *discovery.EndpointHints, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tfzPath := fldPath.Child(\"forZones\")\n\tif len(endpointHints.ForZones) \u003e maxZoneHints {\n\t\tallErrs = append(allErrs, field.TooMany(fzPath, len(endpointHints.ForZones), maxZoneHints))\n\t\treturn allErrs\n\t}\n\n\tzoneNames := sets.String{}\n\tfor i, forZone := range endpointHints.ForZones {\n\t\tzonePath := fzPath.Index(i).Child(\"name\")\n\t\tif zoneNames.Has(forZone.Name) {\n\t\t\tallErrs = append(allErrs, field.Duplicate(zonePath, forZone.Name))\n\t\t} else {\n\t\t\tzoneNames.Insert(forZone.Name)\n\t\t}\n\n\t\tfor _, msg := range validation.IsValidLabelValue(forZone.Name) {\n\t\t\tallErrs = append(allErrs, field.Invalid(zonePath, forZone.Name, msg))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":188,"to":212}} {"id":100002744,"name":"init","signature":"func init()","file":"pkg/apis/events/install/install.go","code":"func init() {\n\tInstall(legacyscheme.Scheme)\n}","line":{"from":30,"to":32}} {"id":100002745,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"pkg/apis/events/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(events.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1.SchemeGroupVersion, v1beta1.SchemeGroupVersion))\n}","line":{"from":34,"to":40}} {"id":100002746,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"pkg/apis/events/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":31,"to":34}} {"id":100002747,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/events/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":36,"to":39}} {"id":100002748,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/events/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026core.Event{},\n\t\t\u0026core.EventList{},\n\t)\n\treturn nil\n}","line":{"from":48,"to":54}} {"id":100002749,"name":"Convert_v1_Event_To_core_Event","signature":"func Convert_v1_Event_To_core_Event(in *v1.Event, out *k8s_api.Event, s conversion.Scope) error","file":"pkg/apis/events/v1/conversion.go","code":"func Convert_v1_Event_To_core_Event(in *v1.Event, out *k8s_api.Event, s conversion.Scope) error {\n\tif err := autoConvert_v1_Event_To_core_Event(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tif err := k8s_api_v1.Convert_v1_ObjectReference_To_core_ObjectReference(\u0026in.Regarding, \u0026out.InvolvedObject, s); err != nil {\n\t\treturn err\n\t}\n\tif err := k8s_api_v1.Convert_v1_EventSource_To_core_EventSource(\u0026in.DeprecatedSource, \u0026out.Source, s); err != nil {\n\t\treturn err\n\t}\n\tout.Message = in.Note\n\tout.FirstTimestamp = in.DeprecatedFirstTimestamp\n\tout.LastTimestamp = in.DeprecatedLastTimestamp\n\tout.Count = in.DeprecatedCount\n\treturn nil\n}","line":{"from":29,"to":44}} {"id":100002750,"name":"Convert_core_Event_To_v1_Event","signature":"func Convert_core_Event_To_v1_Event(in *k8s_api.Event, out *v1.Event, s conversion.Scope) error","file":"pkg/apis/events/v1/conversion.go","code":"func Convert_core_Event_To_v1_Event(in *k8s_api.Event, out *v1.Event, s conversion.Scope) error {\n\tif err := autoConvert_core_Event_To_v1_Event(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tif err := k8s_api_v1.Convert_core_ObjectReference_To_v1_ObjectReference(\u0026in.InvolvedObject, \u0026out.Regarding, s); err != nil {\n\t\treturn err\n\t}\n\tif err := k8s_api_v1.Convert_core_EventSource_To_v1_EventSource(\u0026in.Source, \u0026out.DeprecatedSource, s); err != nil {\n\t\treturn err\n\t}\n\tout.Note = in.Message\n\tout.DeprecatedFirstTimestamp = in.FirstTimestamp\n\tout.DeprecatedLastTimestamp = in.LastTimestamp\n\tout.DeprecatedCount = in.Count\n\treturn nil\n}","line":{"from":46,"to":61}} {"id":100002751,"name":"AddFieldLabelConversionsForEvent","signature":"func AddFieldLabelConversionsForEvent(scheme *runtime.Scheme) error","file":"pkg/apis/events/v1/conversion.go","code":"func AddFieldLabelConversionsForEvent(scheme *runtime.Scheme) error {\n\tmapping := map[string]string{\n\t\t\"reason\": \"reason\",\n\t\t\"regarding.kind\": \"involvedObject.kind\", // map events.k8s.io field to fieldset returned by ToSelectableFields\n\t\t\"regarding.namespace\": \"involvedObject.namespace\", // map events.k8s.io field to fieldset returned by ToSelectableFields\n\t\t\"regarding.name\": \"involvedObject.name\", // map events.k8s.io field to fieldset returned by ToSelectableFields\n\t\t\"regarding.uid\": \"involvedObject.uid\", // map events.k8s.io field to fieldset returned by ToSelectableFields\n\t\t\"regarding.apiVersion\": \"involvedObject.apiVersion\", // map events.k8s.io field to fieldset returned by ToSelectableFields\n\t\t\"regarding.resourceVersion\": \"involvedObject.resourceVersion\", // map events.k8s.io field to fieldset returned by ToSelectableFields\n\t\t\"regarding.fieldPath\": \"involvedObject.fieldPath\", // map events.k8s.io field to fieldset returned by ToSelectableFields\n\t\t\"reportingController\": \"reportingComponent\", // map events.k8s.io field to fieldset returned by ToSelectableFields\n\t\t\"type\": \"type\",\n\t\t\"metadata.namespace\": \"metadata.namespace\",\n\t\t\"metadata.name\": \"metadata.name\",\n\t}\n\treturn scheme.AddFieldLabelConversionFunc(SchemeGroupVersion.WithKind(\"Event\"),\n\t\tfunc(label, value string) (string, string, error) {\n\t\t\tmappedLabel, ok := mapping[label]\n\t\t\tif !ok {\n\t\t\t\treturn \"\", \"\", fmt.Errorf(\"field label not supported: %s\", label)\n\t\t\t}\n\t\t\treturn mappedLabel, value, nil\n\t\t},\n\t)\n}","line":{"from":63,"to":87}} {"id":100002752,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/events/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002753,"name":"init","signature":"func init()","file":"pkg/apis/events/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(RegisterDefaults, AddFieldLabelConversionsForEvent)\n}","line":{"from":40,"to":45}} {"id":100002754,"name":"Convert_v1beta1_Event_To_core_Event","signature":"func Convert_v1beta1_Event_To_core_Event(in *v1beta1.Event, out *k8s_api.Event, s conversion.Scope) error","file":"pkg/apis/events/v1beta1/conversion.go","code":"func Convert_v1beta1_Event_To_core_Event(in *v1beta1.Event, out *k8s_api.Event, s conversion.Scope) error {\n\tif err := autoConvert_v1beta1_Event_To_core_Event(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tif err := k8s_api_v1.Convert_v1_ObjectReference_To_core_ObjectReference(\u0026in.Regarding, \u0026out.InvolvedObject, s); err != nil {\n\t\treturn err\n\t}\n\tif err := k8s_api_v1.Convert_v1_EventSource_To_core_EventSource(\u0026in.DeprecatedSource, \u0026out.Source, s); err != nil {\n\t\treturn err\n\t}\n\tout.Message = in.Note\n\tout.FirstTimestamp = in.DeprecatedFirstTimestamp\n\tout.LastTimestamp = in.DeprecatedLastTimestamp\n\tout.Count = in.DeprecatedCount\n\treturn nil\n}","line":{"from":29,"to":44}} {"id":100002755,"name":"Convert_core_Event_To_v1beta1_Event","signature":"func Convert_core_Event_To_v1beta1_Event(in *k8s_api.Event, out *v1beta1.Event, s conversion.Scope) error","file":"pkg/apis/events/v1beta1/conversion.go","code":"func Convert_core_Event_To_v1beta1_Event(in *k8s_api.Event, out *v1beta1.Event, s conversion.Scope) error {\n\tif err := autoConvert_core_Event_To_v1beta1_Event(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tif err := k8s_api_v1.Convert_core_ObjectReference_To_v1_ObjectReference(\u0026in.InvolvedObject, \u0026out.Regarding, s); err != nil {\n\t\treturn err\n\t}\n\tif err := k8s_api_v1.Convert_core_EventSource_To_v1_EventSource(\u0026in.Source, \u0026out.DeprecatedSource, s); err != nil {\n\t\treturn err\n\t}\n\tout.Note = in.Message\n\tout.DeprecatedFirstTimestamp = in.FirstTimestamp\n\tout.DeprecatedLastTimestamp = in.LastTimestamp\n\tout.DeprecatedCount = in.Count\n\treturn nil\n}","line":{"from":46,"to":61}} {"id":100002756,"name":"AddFieldLabelConversionsForEvent","signature":"func AddFieldLabelConversionsForEvent(scheme *runtime.Scheme) error","file":"pkg/apis/events/v1beta1/conversion.go","code":"func AddFieldLabelConversionsForEvent(scheme *runtime.Scheme) error {\n\tmapping := map[string]string{\n\t\t\"reason\": \"reason\",\n\t\t\"regarding.kind\": \"involvedObject.kind\", // map events.k8s.io field to fieldset returned by ToSelectableFields\n\t\t\"regarding.namespace\": \"involvedObject.namespace\", // map events.k8s.io field to fieldset returned by ToSelectableFields\n\t\t\"regarding.name\": \"involvedObject.name\", // map events.k8s.io field to fieldset returned by ToSelectableFields\n\t\t\"regarding.uid\": \"involvedObject.uid\", // map events.k8s.io field to fieldset returned by ToSelectableFields\n\t\t\"regarding.apiVersion\": \"involvedObject.apiVersion\", // map events.k8s.io field to fieldset returned by ToSelectableFields\n\t\t\"regarding.resourceVersion\": \"involvedObject.resourceVersion\", // map events.k8s.io field to fieldset returned by ToSelectableFields\n\t\t\"regarding.fieldPath\": \"involvedObject.fieldPath\", // map events.k8s.io field to fieldset returned by ToSelectableFields\n\t\t\"reportingController\": \"reportingComponent\", // map events.k8s.io field to fieldset returned by ToSelectableFields\n\t\t\"type\": \"type\",\n\t\t\"metadata.namespace\": \"metadata.namespace\",\n\t\t\"metadata.name\": \"metadata.name\",\n\t}\n\treturn scheme.AddFieldLabelConversionFunc(SchemeGroupVersion.WithKind(\"Event\"),\n\t\tfunc(label, value string) (string, string, error) {\n\t\t\tmappedLabel, ok := mapping[label]\n\t\t\tif !ok {\n\t\t\t\treturn \"\", \"\", fmt.Errorf(\"field label not supported: %s\", label)\n\t\t\t}\n\t\t\treturn mappedLabel, value, nil\n\t\t},\n\t)\n}","line":{"from":63,"to":87}} {"id":100002757,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/events/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002758,"name":"init","signature":"func init()","file":"pkg/apis/events/v1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(RegisterDefaults, AddFieldLabelConversionsForEvent)\n}","line":{"from":40,"to":45}} {"id":100002759,"name":"init","signature":"func init()","file":"pkg/apis/extensions/install/install.go","code":"func init() {\n\tInstall(legacyscheme.Scheme)\n}","line":{"from":29,"to":31}} {"id":100002760,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"pkg/apis/extensions/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(extensions.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1beta1.SchemeGroupVersion))\n}","line":{"from":33,"to":38}} {"id":100002761,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"pkg/apis/extensions/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":33,"to":36}} {"id":100002762,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/extensions/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":38,"to":41}} {"id":100002763,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/extensions/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\t// TODO this gets cleaned up when the types are fixed\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026apps.Deployment{},\n\t\t\u0026apps.DeploymentList{},\n\t\t\u0026apps.DeploymentRollback{},\n\t\t\u0026apps.DaemonSetList{},\n\t\t\u0026apps.DaemonSet{},\n\t\t\u0026networking.Ingress{},\n\t\t\u0026networking.IngressList{},\n\t\t\u0026apps.ReplicaSet{},\n\t\t\u0026apps.ReplicaSetList{},\n\t\t\u0026autoscaling.Scale{},\n\t\t\u0026networking.NetworkPolicy{},\n\t\t\u0026networking.NetworkPolicyList{},\n\t)\n\treturn nil\n}","line":{"from":49,"to":67}} {"id":100002764,"name":"Convert_autoscaling_ScaleStatus_To_v1beta1_ScaleStatus","signature":"func Convert_autoscaling_ScaleStatus_To_v1beta1_ScaleStatus(in *autoscaling.ScaleStatus, out *extensionsv1beta1.ScaleStatus, s conversion.Scope) error","file":"pkg/apis/extensions/v1beta1/conversion.go","code":"func Convert_autoscaling_ScaleStatus_To_v1beta1_ScaleStatus(in *autoscaling.ScaleStatus, out *extensionsv1beta1.ScaleStatus, s conversion.Scope) error {\n\tout.Replicas = int32(in.Replicas)\n\tout.TargetSelector = in.Selector\n\n\tout.Selector = nil\n\tselector, err := metav1.ParseToLabelSelector(in.Selector)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse selector: %v\", err)\n\t}\n\tif len(selector.MatchExpressions) == 0 {\n\t\tout.Selector = selector.MatchLabels\n\t}\n\n\treturn nil\n}","line":{"from":31,"to":45}} {"id":100002765,"name":"Convert_v1beta1_ScaleStatus_To_autoscaling_ScaleStatus","signature":"func Convert_v1beta1_ScaleStatus_To_autoscaling_ScaleStatus(in *extensionsv1beta1.ScaleStatus, out *autoscaling.ScaleStatus, s conversion.Scope) error","file":"pkg/apis/extensions/v1beta1/conversion.go","code":"func Convert_v1beta1_ScaleStatus_To_autoscaling_ScaleStatus(in *extensionsv1beta1.ScaleStatus, out *autoscaling.ScaleStatus, s conversion.Scope) error {\n\tout.Replicas = in.Replicas\n\n\tif in.TargetSelector != \"\" {\n\t\tout.Selector = in.TargetSelector\n\t} else if in.Selector != nil {\n\t\tset := labels.Set{}\n\t\tfor key, val := range in.Selector {\n\t\t\tset[key] = val\n\t\t}\n\t\tout.Selector = labels.SelectorFromSet(set).String()\n\t} else {\n\t\tout.Selector = \"\"\n\t}\n\treturn nil\n}","line":{"from":47,"to":62}} {"id":100002766,"name":"Convert_v1beta1_NetworkPolicySpec_To_networking_NetworkPolicySpec","signature":"func Convert_v1beta1_NetworkPolicySpec_To_networking_NetworkPolicySpec(in *extensionsv1beta1.NetworkPolicySpec, out *networking.NetworkPolicySpec, s conversion.Scope) error","file":"pkg/apis/extensions/v1beta1/conversion.go","code":"func Convert_v1beta1_NetworkPolicySpec_To_networking_NetworkPolicySpec(in *extensionsv1beta1.NetworkPolicySpec, out *networking.NetworkPolicySpec, s conversion.Scope) error {\n\tif err := autoConvert_v1beta1_NetworkPolicySpec_To_networking_NetworkPolicySpec(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tif out.Ingress == nil {\n\t\t// Produce a zero-length non-nil slice for compatibility with previous manual conversion.\n\t\tout.Ingress = make([]networking.NetworkPolicyIngressRule, 0)\n\t}\n\tif out.Egress == nil {\n\t\t// Produce a zero-length non-nil slice for compatibility with previous manual conversion.\n\t\tout.Egress = make([]networking.NetworkPolicyEgressRule, 0)\n\t}\n\treturn nil\n}","line":{"from":64,"to":77}} {"id":100002767,"name":"Convert_networking_NetworkPolicySpec_To_v1beta1_NetworkPolicySpec","signature":"func Convert_networking_NetworkPolicySpec_To_v1beta1_NetworkPolicySpec(in *networking.NetworkPolicySpec, out *extensionsv1beta1.NetworkPolicySpec, s conversion.Scope) error","file":"pkg/apis/extensions/v1beta1/conversion.go","code":"func Convert_networking_NetworkPolicySpec_To_v1beta1_NetworkPolicySpec(in *networking.NetworkPolicySpec, out *extensionsv1beta1.NetworkPolicySpec, s conversion.Scope) error {\n\tif err := autoConvert_networking_NetworkPolicySpec_To_v1beta1_NetworkPolicySpec(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tif out.Ingress == nil {\n\t\t// Produce a zero-length non-nil slice for compatibility with previous manual conversion.\n\t\tout.Ingress = make([]extensionsv1beta1.NetworkPolicyIngressRule, 0)\n\t}\n\tif out.Egress == nil {\n\t\t// Produce a zero-length non-nil slice for compatibility with previous manual conversion.\n\t\tout.Egress = make([]extensionsv1beta1.NetworkPolicyEgressRule, 0)\n\t}\n\treturn nil\n}","line":{"from":79,"to":92}} {"id":100002768,"name":"Convert_v1beta1_NetworkPolicyIngressRule_To_networking_NetworkPolicyIngressRule","signature":"func Convert_v1beta1_NetworkPolicyIngressRule_To_networking_NetworkPolicyIngressRule(in *extensionsv1beta1.NetworkPolicyIngressRule, out *networking.NetworkPolicyIngressRule, s conversion.Scope) error","file":"pkg/apis/extensions/v1beta1/conversion.go","code":"func Convert_v1beta1_NetworkPolicyIngressRule_To_networking_NetworkPolicyIngressRule(in *extensionsv1beta1.NetworkPolicyIngressRule, out *networking.NetworkPolicyIngressRule, s conversion.Scope) error {\n\tif err := autoConvert_v1beta1_NetworkPolicyIngressRule_To_networking_NetworkPolicyIngressRule(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tif out.Ports == nil {\n\t\t// Produce a zero-length non-nil slice for compatibility with previous manual conversion.\n\t\tout.Ports = make([]networking.NetworkPolicyPort, 0)\n\t}\n\treturn nil\n}","line":{"from":94,"to":103}} {"id":100002769,"name":"Convert_networking_NetworkPolicyIngressRule_To_v1beta1_NetworkPolicyIngressRule","signature":"func Convert_networking_NetworkPolicyIngressRule_To_v1beta1_NetworkPolicyIngressRule(in *networking.NetworkPolicyIngressRule, out *extensionsv1beta1.NetworkPolicyIngressRule, s conversion.Scope) error","file":"pkg/apis/extensions/v1beta1/conversion.go","code":"func Convert_networking_NetworkPolicyIngressRule_To_v1beta1_NetworkPolicyIngressRule(in *networking.NetworkPolicyIngressRule, out *extensionsv1beta1.NetworkPolicyIngressRule, s conversion.Scope) error {\n\tif err := autoConvert_networking_NetworkPolicyIngressRule_To_v1beta1_NetworkPolicyIngressRule(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tif out.Ports == nil {\n\t\t// Produce a zero-length non-nil slice for compatibility with previous manual conversion.\n\t\tout.Ports = make([]extensionsv1beta1.NetworkPolicyPort, 0)\n\t}\n\treturn nil\n}","line":{"from":105,"to":114}} {"id":100002770,"name":"Convert_v1beta1_NetworkPolicyEgressRule_To_networking_NetworkPolicyEgressRule","signature":"func Convert_v1beta1_NetworkPolicyEgressRule_To_networking_NetworkPolicyEgressRule(in *extensionsv1beta1.NetworkPolicyEgressRule, out *networking.NetworkPolicyEgressRule, s conversion.Scope) error","file":"pkg/apis/extensions/v1beta1/conversion.go","code":"func Convert_v1beta1_NetworkPolicyEgressRule_To_networking_NetworkPolicyEgressRule(in *extensionsv1beta1.NetworkPolicyEgressRule, out *networking.NetworkPolicyEgressRule, s conversion.Scope) error {\n\tif err := autoConvert_v1beta1_NetworkPolicyEgressRule_To_networking_NetworkPolicyEgressRule(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tif out.Ports == nil {\n\t\t// Produce a zero-length non-nil slice for compatibility with previous manual conversion.\n\t\tout.Ports = make([]networking.NetworkPolicyPort, 0)\n\t}\n\tif out.To == nil {\n\t\t// Produce a zero-length non-nil slice for compatibility with previous manual conversion.\n\t\tout.To = make([]networking.NetworkPolicyPeer, 0)\n\t}\n\treturn nil\n}","line":{"from":116,"to":129}} {"id":100002771,"name":"Convert_networking_NetworkPolicyEgressRule_To_v1beta1_NetworkPolicyEgressRule","signature":"func Convert_networking_NetworkPolicyEgressRule_To_v1beta1_NetworkPolicyEgressRule(in *networking.NetworkPolicyEgressRule, out *extensionsv1beta1.NetworkPolicyEgressRule, s conversion.Scope) error","file":"pkg/apis/extensions/v1beta1/conversion.go","code":"func Convert_networking_NetworkPolicyEgressRule_To_v1beta1_NetworkPolicyEgressRule(in *networking.NetworkPolicyEgressRule, out *extensionsv1beta1.NetworkPolicyEgressRule, s conversion.Scope) error {\n\tif err := autoConvert_networking_NetworkPolicyEgressRule_To_v1beta1_NetworkPolicyEgressRule(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tif out.Ports == nil {\n\t\t// Produce a zero-length non-nil slice for compatibility with previous manual conversion.\n\t\tout.Ports = make([]extensionsv1beta1.NetworkPolicyPort, 0)\n\t}\n\tif out.To == nil {\n\t\t// Produce a zero-length non-nil slice for compatibility with previous manual conversion.\n\t\tout.To = make([]extensionsv1beta1.NetworkPolicyPeer, 0)\n\t}\n\treturn nil\n}","line":{"from":131,"to":144}} {"id":100002772,"name":"Convert_v1beta1_IPBlock_To_networking_IPBlock","signature":"func Convert_v1beta1_IPBlock_To_networking_IPBlock(in *extensionsv1beta1.IPBlock, out *networking.IPBlock, s conversion.Scope) error","file":"pkg/apis/extensions/v1beta1/conversion.go","code":"func Convert_v1beta1_IPBlock_To_networking_IPBlock(in *extensionsv1beta1.IPBlock, out *networking.IPBlock, s conversion.Scope) error {\n\tout.CIDR = in.CIDR\n\n\tout.Except = make([]string, len(in.Except))\n\tcopy(out.Except, in.Except)\n\treturn nil\n}","line":{"from":146,"to":152}} {"id":100002773,"name":"Convert_networking_IPBlock_To_v1beta1_IPBlock","signature":"func Convert_networking_IPBlock_To_v1beta1_IPBlock(in *networking.IPBlock, out *extensionsv1beta1.IPBlock, s conversion.Scope) error","file":"pkg/apis/extensions/v1beta1/conversion.go","code":"func Convert_networking_IPBlock_To_v1beta1_IPBlock(in *networking.IPBlock, out *extensionsv1beta1.IPBlock, s conversion.Scope) error {\n\tout.CIDR = in.CIDR\n\n\tout.Except = make([]string, len(in.Except))\n\tcopy(out.Except, in.Except)\n\treturn nil\n}","line":{"from":154,"to":160}} {"id":100002774,"name":"Convert_v1beta1_IngressBackend_To_networking_IngressBackend","signature":"func Convert_v1beta1_IngressBackend_To_networking_IngressBackend(in *extensionsv1beta1.IngressBackend, out *networking.IngressBackend, s conversion.Scope) error","file":"pkg/apis/extensions/v1beta1/conversion.go","code":"func Convert_v1beta1_IngressBackend_To_networking_IngressBackend(in *extensionsv1beta1.IngressBackend, out *networking.IngressBackend, s conversion.Scope) error {\n\tif err := autoConvert_v1beta1_IngressBackend_To_networking_IngressBackend(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tif len(in.ServiceName) \u003e 0 || in.ServicePort.IntVal != 0 || in.ServicePort.StrVal != \"\" || in.ServicePort.Type == intstr.String {\n\t\tout.Service = \u0026networking.IngressServiceBackend{}\n\t\tout.Service.Name = in.ServiceName\n\t\tout.Service.Port.Name = in.ServicePort.StrVal\n\t\tout.Service.Port.Number = in.ServicePort.IntVal\n\t}\n\treturn nil\n}","line":{"from":162,"to":173}} {"id":100002775,"name":"Convert_networking_IngressBackend_To_v1beta1_IngressBackend","signature":"func Convert_networking_IngressBackend_To_v1beta1_IngressBackend(in *networking.IngressBackend, out *extensionsv1beta1.IngressBackend, s conversion.Scope) error","file":"pkg/apis/extensions/v1beta1/conversion.go","code":"func Convert_networking_IngressBackend_To_v1beta1_IngressBackend(in *networking.IngressBackend, out *extensionsv1beta1.IngressBackend, s conversion.Scope) error {\n\tif err := autoConvert_networking_IngressBackend_To_v1beta1_IngressBackend(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tif in.Service != nil {\n\t\tout.ServiceName = in.Service.Name\n\t\tif len(in.Service.Port.Name) \u003e 0 {\n\t\t\tout.ServicePort = intstr.FromString(in.Service.Port.Name)\n\t\t} else {\n\t\t\tout.ServicePort = intstr.FromInt(int(in.Service.Port.Number))\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":175,"to":188}} {"id":100002776,"name":"Convert_v1beta1_IngressSpec_To_networking_IngressSpec","signature":"func Convert_v1beta1_IngressSpec_To_networking_IngressSpec(in *extensionsv1beta1.IngressSpec, out *networking.IngressSpec, s conversion.Scope) error","file":"pkg/apis/extensions/v1beta1/conversion.go","code":"func Convert_v1beta1_IngressSpec_To_networking_IngressSpec(in *extensionsv1beta1.IngressSpec, out *networking.IngressSpec, s conversion.Scope) error {\n\tif err := autoConvert_v1beta1_IngressSpec_To_networking_IngressSpec(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tif in.Backend != nil {\n\t\tout.DefaultBackend = \u0026networking.IngressBackend{}\n\t\tif err := Convert_v1beta1_IngressBackend_To_networking_IngressBackend(in.Backend, out.DefaultBackend, s); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":190,"to":201}} {"id":100002777,"name":"Convert_networking_IngressSpec_To_v1beta1_IngressSpec","signature":"func Convert_networking_IngressSpec_To_v1beta1_IngressSpec(in *networking.IngressSpec, out *extensionsv1beta1.IngressSpec, s conversion.Scope) error","file":"pkg/apis/extensions/v1beta1/conversion.go","code":"func Convert_networking_IngressSpec_To_v1beta1_IngressSpec(in *networking.IngressSpec, out *extensionsv1beta1.IngressSpec, s conversion.Scope) error {\n\tif err := autoConvert_networking_IngressSpec_To_v1beta1_IngressSpec(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tif in.DefaultBackend != nil {\n\t\tout.Backend = \u0026extensionsv1beta1.IngressBackend{}\n\t\tif err := Convert_networking_IngressBackend_To_v1beta1_IngressBackend(in.DefaultBackend, out.Backend, s); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":203,"to":214}} {"id":100002778,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/extensions/v1beta1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":29,"to":31}} {"id":100002779,"name":"SetDefaults_DaemonSet","signature":"func SetDefaults_DaemonSet(obj *extensionsv1beta1.DaemonSet)","file":"pkg/apis/extensions/v1beta1/defaults.go","code":"func SetDefaults_DaemonSet(obj *extensionsv1beta1.DaemonSet) {\n\tlabels := obj.Spec.Template.Labels\n\n\t// TODO: support templates defined elsewhere when we support them in the API\n\tif labels != nil {\n\t\tif obj.Spec.Selector == nil {\n\t\t\tobj.Spec.Selector = \u0026metav1.LabelSelector{\n\t\t\t\tMatchLabels: labels,\n\t\t\t}\n\t\t}\n\t\tif len(obj.Labels) == 0 {\n\t\t\tobj.Labels = labels\n\t\t}\n\t}\n\tupdateStrategy := \u0026obj.Spec.UpdateStrategy\n\tif updateStrategy.Type == \"\" {\n\t\tupdateStrategy.Type = extensionsv1beta1.OnDeleteDaemonSetStrategyType\n\t}\n\tif updateStrategy.Type == extensionsv1beta1.RollingUpdateDaemonSetStrategyType {\n\t\tif updateStrategy.RollingUpdate == nil {\n\t\t\trollingUpdate := extensionsv1beta1.RollingUpdateDaemonSet{}\n\t\t\tupdateStrategy.RollingUpdate = \u0026rollingUpdate\n\t\t}\n\t\tif updateStrategy.RollingUpdate.MaxUnavailable == nil {\n\t\t\t// Set default MaxUnavailable as 1 by default.\n\t\t\tmaxUnavailable := intstr.FromInt(1)\n\t\t\tupdateStrategy.RollingUpdate.MaxUnavailable = \u0026maxUnavailable\n\t\t}\n\t\tif updateStrategy.RollingUpdate.MaxSurge == nil {\n\t\t\t// Set default MaxSurge as 0 by default.\n\t\t\tmaxSurge := intstr.FromInt(0)\n\t\t\tupdateStrategy.RollingUpdate.MaxSurge = \u0026maxSurge\n\t\t}\n\t}\n\tif obj.Spec.RevisionHistoryLimit == nil {\n\t\tobj.Spec.RevisionHistoryLimit = new(int32)\n\t\t*obj.Spec.RevisionHistoryLimit = 10\n\t}\n}","line":{"from":33,"to":71}} {"id":100002780,"name":"SetDefaults_Deployment","signature":"func SetDefaults_Deployment(obj *extensionsv1beta1.Deployment)","file":"pkg/apis/extensions/v1beta1/defaults.go","code":"func SetDefaults_Deployment(obj *extensionsv1beta1.Deployment) {\n\t// Default labels and selector to labels from pod template spec.\n\tlabels := obj.Spec.Template.Labels\n\n\tif labels != nil {\n\t\tif obj.Spec.Selector == nil {\n\t\t\tobj.Spec.Selector = \u0026metav1.LabelSelector{MatchLabels: labels}\n\t\t}\n\t\tif len(obj.Labels) == 0 {\n\t\t\tobj.Labels = labels\n\t\t}\n\t}\n\t// Set extensionsv1beta1.DeploymentSpec.Replicas to 1 if it is not set.\n\tif obj.Spec.Replicas == nil {\n\t\tobj.Spec.Replicas = new(int32)\n\t\t*obj.Spec.Replicas = 1\n\t}\n\tstrategy := \u0026obj.Spec.Strategy\n\t// Set default extensionsv1beta1.DeploymentStrategyType as RollingUpdate.\n\tif strategy.Type == \"\" {\n\t\tstrategy.Type = extensionsv1beta1.RollingUpdateDeploymentStrategyType\n\t}\n\tif strategy.Type == extensionsv1beta1.RollingUpdateDeploymentStrategyType || strategy.RollingUpdate != nil {\n\t\tif strategy.RollingUpdate == nil {\n\t\t\trollingUpdate := extensionsv1beta1.RollingUpdateDeployment{}\n\t\t\tstrategy.RollingUpdate = \u0026rollingUpdate\n\t\t}\n\t\tif strategy.RollingUpdate.MaxUnavailable == nil {\n\t\t\t// Set default MaxUnavailable as 1 by default.\n\t\t\tmaxUnavailable := intstr.FromInt(1)\n\t\t\tstrategy.RollingUpdate.MaxUnavailable = \u0026maxUnavailable\n\t\t}\n\t\tif strategy.RollingUpdate.MaxSurge == nil {\n\t\t\t// Set default MaxSurge as 1 by default.\n\t\t\tmaxSurge := intstr.FromInt(1)\n\t\t\tstrategy.RollingUpdate.MaxSurge = \u0026maxSurge\n\t\t}\n\t}\n\t// Set extensionsv1beta1.DeploymentSpec.ProgressDeadlineSeconds to MaxInt,\n\t// which has the same meaning as unset.\n\tif obj.Spec.ProgressDeadlineSeconds == nil {\n\t\tobj.Spec.ProgressDeadlineSeconds = new(int32)\n\t\t*obj.Spec.ProgressDeadlineSeconds = math.MaxInt32\n\t}\n\t// Set extensionsv1beta1.DeploymentSpec.RevisionHistoryLimit to MaxInt32,\n\t// which has the same meaning as unset.\n\tif obj.Spec.RevisionHistoryLimit == nil {\n\t\tobj.Spec.RevisionHistoryLimit = new(int32)\n\t\t*obj.Spec.RevisionHistoryLimit = math.MaxInt32\n\t}\n}","line":{"from":73,"to":123}} {"id":100002781,"name":"SetDefaults_ReplicaSet","signature":"func SetDefaults_ReplicaSet(obj *extensionsv1beta1.ReplicaSet)","file":"pkg/apis/extensions/v1beta1/defaults.go","code":"func SetDefaults_ReplicaSet(obj *extensionsv1beta1.ReplicaSet) {\n\tlabels := obj.Spec.Template.Labels\n\n\t// TODO: support templates defined elsewhere when we support them in the API\n\tif labels != nil {\n\t\tif obj.Spec.Selector == nil {\n\t\t\tobj.Spec.Selector = \u0026metav1.LabelSelector{\n\t\t\t\tMatchLabels: labels,\n\t\t\t}\n\t\t}\n\t\tif len(obj.Labels) == 0 {\n\t\t\tobj.Labels = labels\n\t\t}\n\t}\n\tif obj.Spec.Replicas == nil {\n\t\tobj.Spec.Replicas = new(int32)\n\t\t*obj.Spec.Replicas = 1\n\t}\n}","line":{"from":125,"to":143}} {"id":100002782,"name":"SetDefaults_NetworkPolicy","signature":"func SetDefaults_NetworkPolicy(obj *extensionsv1beta1.NetworkPolicy)","file":"pkg/apis/extensions/v1beta1/defaults.go","code":"func SetDefaults_NetworkPolicy(obj *extensionsv1beta1.NetworkPolicy) {\n\t// Default any undefined Protocol fields to TCP.\n\tfor _, i := range obj.Spec.Ingress {\n\t\tfor _, p := range i.Ports {\n\t\t\tif p.Protocol == nil {\n\t\t\t\tproto := v1.ProtocolTCP\n\t\t\t\tp.Protocol = \u0026proto\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(obj.Spec.PolicyTypes) == 0 {\n\t\t// Any policy that does not specify policyTypes implies at least \"Ingress\".\n\t\tobj.Spec.PolicyTypes = []extensionsv1beta1.PolicyType{extensionsv1beta1.PolicyTypeIngress}\n\t\tif len(obj.Spec.Egress) != 0 {\n\t\t\tobj.Spec.PolicyTypes = append(obj.Spec.PolicyTypes, extensionsv1beta1.PolicyTypeEgress)\n\t\t}\n\t}\n}","line":{"from":145,"to":163}} {"id":100002783,"name":"SetDefaults_HTTPIngressPath","signature":"func SetDefaults_HTTPIngressPath(obj *extensionsv1beta1.HTTPIngressPath)","file":"pkg/apis/extensions/v1beta1/defaults.go","code":"func SetDefaults_HTTPIngressPath(obj *extensionsv1beta1.HTTPIngressPath) {\n\tvar defaultPathType = extensionsv1beta1.PathTypeImplementationSpecific\n\tif obj.PathType == nil {\n\t\tobj.PathType = \u0026defaultPathType\n\t}\n}","line":{"from":165,"to":170}} {"id":100002784,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/extensions/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002785,"name":"init","signature":"func init()","file":"pkg/apis/extensions/v1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":40,"to":45}} {"id":100002786,"name":"init","signature":"func init()","file":"pkg/apis/flowcontrol/install/install.go","code":"func init() {\n\tInstall(legacyscheme.Scheme)\n}","line":{"from":32,"to":34}} {"id":100002787,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"pkg/apis/flowcontrol/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(flowcontrol.AddToScheme(scheme))\n\tutilruntime.Must(flowcontrolv1alpha1.AddToScheme(scheme))\n\tutilruntime.Must(flowcontrolv1beta1.AddToScheme(scheme))\n\tutilruntime.Must(flowcontrolv1beta2.AddToScheme(scheme))\n\tutilruntime.Must(flowcontrolv1beta3.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(flowcontrolv1beta3.SchemeGroupVersion, flowcontrolv1beta2.SchemeGroupVersion,\n\t\tflowcontrolv1beta1.SchemeGroupVersion, flowcontrolv1alpha1.SchemeGroupVersion))\n}","line":{"from":36,"to":45}} {"id":100002788,"name":"NewAPFScheme","signature":"func NewAPFScheme() *runtime.Scheme","file":"pkg/apis/flowcontrol/internalbootstrap/default-internal.go","code":"// NewAPFScheme constructs and returns a Scheme configured to handle\n// the API object types that are used to configure API Priority and\n// Fairness\nfunc NewAPFScheme() *runtime.Scheme {\n\tscheme := runtime.NewScheme()\n\tinstall.Install(scheme)\n\treturn scheme\n}","line":{"from":40,"to":47}} {"id":100002789,"name":"internalizeFSes","signature":"func internalizeFSes(exts []*flowcontrolv1beta3.FlowSchema) map[string]*flowcontrol.FlowSchema","file":"pkg/apis/flowcontrol/internalbootstrap/default-internal.go","code":"func internalizeFSes(exts []*flowcontrolv1beta3.FlowSchema) map[string]*flowcontrol.FlowSchema {\n\tans := make(map[string]*flowcontrol.FlowSchema, len(exts))\n\tscheme := NewAPFScheme()\n\tfor _, ext := range exts {\n\t\tvar untyped flowcontrol.FlowSchema\n\t\tif err := scheme.Convert(ext, \u0026untyped, nil); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tans[ext.Name] = \u0026untyped\n\t}\n\treturn ans\n}","line":{"from":49,"to":60}} {"id":100002790,"name":"internalizePLs","signature":"func internalizePLs(exts []*flowcontrolv1beta3.PriorityLevelConfiguration) map[string]*flowcontrol.PriorityLevelConfiguration","file":"pkg/apis/flowcontrol/internalbootstrap/default-internal.go","code":"func internalizePLs(exts []*flowcontrolv1beta3.PriorityLevelConfiguration) map[string]*flowcontrol.PriorityLevelConfiguration {\n\tans := make(map[string]*flowcontrol.PriorityLevelConfiguration, len(exts))\n\tscheme := NewAPFScheme()\n\tfor _, ext := range exts {\n\t\tvar untyped flowcontrol.PriorityLevelConfiguration\n\t\tif err := scheme.Convert(ext, \u0026untyped, nil); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tans[ext.Name] = \u0026untyped\n\t}\n\treturn ans\n}","line":{"from":62,"to":73}} {"id":100002791,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"pkg/apis/flowcontrol/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100002792,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/flowcontrol/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100002793,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/flowcontrol/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026FlowSchema{},\n\t\t\u0026FlowSchemaList{},\n\t\t\u0026PriorityLevelConfiguration{},\n\t\t\u0026PriorityLevelConfigurationList{},\n\t)\n\treturn nil\n}","line":{"from":47,"to":56}} {"id":100002794,"name":"Len","signature":"func (s FlowSchemaSequence) Len() int","file":"pkg/apis/flowcontrol/util/helpers.go","code":"func (s FlowSchemaSequence) Len() int {\n\treturn len(s)\n}","line":{"from":31,"to":33}} {"id":100002795,"name":"Less","signature":"func (s FlowSchemaSequence) Less(i, j int) bool","file":"pkg/apis/flowcontrol/util/helpers.go","code":"func (s FlowSchemaSequence) Less(i, j int) bool {\n\t// the flow-schema w/ lower matching-precedence is prior\n\tif ip, jp := s[i].Spec.MatchingPrecedence, s[j].Spec.MatchingPrecedence; ip != jp {\n\t\treturn ip \u003c jp\n\t}\n\t// sort alphabetically\n\treturn s[i].Name \u003c s[j].Name\n}","line":{"from":35,"to":42}} {"id":100002796,"name":"Swap","signature":"func (s FlowSchemaSequence) Swap(i, j int)","file":"pkg/apis/flowcontrol/util/helpers.go","code":"func (s FlowSchemaSequence) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}","line":{"from":44,"to":46}} {"id":100002797,"name":"Convert_v1alpha1_LimitedPriorityLevelConfiguration_To_flowcontrol_LimitedPriorityLevelConfiguration","signature":"func Convert_v1alpha1_LimitedPriorityLevelConfiguration_To_flowcontrol_LimitedPriorityLevelConfiguration(in *v1alpha1.LimitedPriorityLevelConfiguration, out *flowcontrol.LimitedPriorityLevelConfiguration, s conversion.Scope) error","file":"pkg/apis/flowcontrol/v1alpha1/conversion.go","code":"// LimitedPriorityLevelConfiguration.AssuredConcurrencyShares has been\n// renamed to NominalConcurrencyShares in v1beta3.\nfunc Convert_v1alpha1_LimitedPriorityLevelConfiguration_To_flowcontrol_LimitedPriorityLevelConfiguration(in *v1alpha1.LimitedPriorityLevelConfiguration, out *flowcontrol.LimitedPriorityLevelConfiguration, s conversion.Scope) error {\n\tif err := autoConvert_v1alpha1_LimitedPriorityLevelConfiguration_To_flowcontrol_LimitedPriorityLevelConfiguration(in, out, nil); err != nil {\n\t\treturn err\n\t}\n\n\tout.NominalConcurrencyShares = in.AssuredConcurrencyShares\n\treturn nil\n}","line":{"from":25,"to":34}} {"id":100002798,"name":"Convert_flowcontrol_LimitedPriorityLevelConfiguration_To_v1alpha1_LimitedPriorityLevelConfiguration","signature":"func Convert_flowcontrol_LimitedPriorityLevelConfiguration_To_v1alpha1_LimitedPriorityLevelConfiguration(in *flowcontrol.LimitedPriorityLevelConfiguration, out *v1alpha1.LimitedPriorityLevelConfiguration, s conversion.Scope) error","file":"pkg/apis/flowcontrol/v1alpha1/conversion.go","code":"// LimitedPriorityLevelConfiguration.AssuredConcurrencyShares has been\n// renamed to NominalConcurrencyShares in v1beta3.\nfunc Convert_flowcontrol_LimitedPriorityLevelConfiguration_To_v1alpha1_LimitedPriorityLevelConfiguration(in *flowcontrol.LimitedPriorityLevelConfiguration, out *v1alpha1.LimitedPriorityLevelConfiguration, s conversion.Scope) error {\n\tif err := autoConvert_flowcontrol_LimitedPriorityLevelConfiguration_To_v1alpha1_LimitedPriorityLevelConfiguration(in, out, nil); err != nil {\n\t\treturn err\n\t}\n\n\tout.AssuredConcurrencyShares = in.NominalConcurrencyShares\n\treturn nil\n}","line":{"from":36,"to":45}} {"id":100002799,"name":"SetDefaults_FlowSchemaSpec","signature":"func SetDefaults_FlowSchemaSpec(spec *v1alpha1.FlowSchemaSpec)","file":"pkg/apis/flowcontrol/v1alpha1/defaults.go","code":"// SetDefaults_FlowSchema sets default values for flow schema\nfunc SetDefaults_FlowSchemaSpec(spec *v1alpha1.FlowSchemaSpec) {\n\tif spec.MatchingPrecedence == 0 {\n\t\tspec.MatchingPrecedence = FlowSchemaDefaultMatchingPrecedence\n\t}\n}","line":{"from":36,"to":41}} {"id":100002800,"name":"SetDefaults_LimitedPriorityLevelConfiguration","signature":"func SetDefaults_LimitedPriorityLevelConfiguration(lplc *v1alpha1.LimitedPriorityLevelConfiguration)","file":"pkg/apis/flowcontrol/v1alpha1/defaults.go","code":"func SetDefaults_LimitedPriorityLevelConfiguration(lplc *v1alpha1.LimitedPriorityLevelConfiguration) {\n\tif lplc.AssuredConcurrencyShares == 0 {\n\t\tlplc.AssuredConcurrencyShares = PriorityLevelConfigurationDefaultAssuredConcurrencyShares\n\t}\n\tif lplc.LendablePercent == nil {\n\t\tlplc.LendablePercent = new(int32)\n\t\t*lplc.LendablePercent = 0\n\t}\n}","line":{"from":43,"to":51}} {"id":100002801,"name":"SetDefaults_QueuingConfiguration","signature":"func SetDefaults_QueuingConfiguration(cfg *v1alpha1.QueuingConfiguration)","file":"pkg/apis/flowcontrol/v1alpha1/defaults.go","code":"// SetDefaults_FlowSchema sets default values for flow schema\nfunc SetDefaults_QueuingConfiguration(cfg *v1alpha1.QueuingConfiguration) {\n\tif cfg.HandSize == 0 {\n\t\tcfg.HandSize = PriorityLevelConfigurationDefaultHandSize\n\t}\n\tif cfg.Queues == 0 {\n\t\tcfg.Queues = PriorityLevelConfigurationDefaultQueues\n\t}\n\tif cfg.QueueLengthLimit == 0 {\n\t\tcfg.QueueLengthLimit = PriorityLevelConfigurationDefaultQueueLengthLimit\n\t}\n}","line":{"from":53,"to":64}} {"id":100002802,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/flowcontrol/v1alpha1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002803,"name":"init","signature":"func init()","file":"pkg/apis/flowcontrol/v1alpha1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(RegisterDefaults)\n}","line":{"from":41,"to":46}} {"id":100002804,"name":"Convert_v1beta1_LimitedPriorityLevelConfiguration_To_flowcontrol_LimitedPriorityLevelConfiguration","signature":"func Convert_v1beta1_LimitedPriorityLevelConfiguration_To_flowcontrol_LimitedPriorityLevelConfiguration(in *v1beta1.LimitedPriorityLevelConfiguration, out *flowcontrol.LimitedPriorityLevelConfiguration, s conversion.Scope) error","file":"pkg/apis/flowcontrol/v1beta1/conversion.go","code":"// LimitedPriorityLevelConfiguration.AssuredConcurrencyShares has been\n// renamed to NominalConcurrencyShares in v1beta3.\nfunc Convert_v1beta1_LimitedPriorityLevelConfiguration_To_flowcontrol_LimitedPriorityLevelConfiguration(in *v1beta1.LimitedPriorityLevelConfiguration, out *flowcontrol.LimitedPriorityLevelConfiguration, s conversion.Scope) error {\n\tif err := autoConvert_v1beta1_LimitedPriorityLevelConfiguration_To_flowcontrol_LimitedPriorityLevelConfiguration(in, out, nil); err != nil {\n\t\treturn err\n\t}\n\n\tout.NominalConcurrencyShares = in.AssuredConcurrencyShares\n\treturn nil\n}","line":{"from":25,"to":34}} {"id":100002805,"name":"Convert_flowcontrol_LimitedPriorityLevelConfiguration_To_v1beta1_LimitedPriorityLevelConfiguration","signature":"func Convert_flowcontrol_LimitedPriorityLevelConfiguration_To_v1beta1_LimitedPriorityLevelConfiguration(in *flowcontrol.LimitedPriorityLevelConfiguration, out *v1beta1.LimitedPriorityLevelConfiguration, s conversion.Scope) error","file":"pkg/apis/flowcontrol/v1beta1/conversion.go","code":"// LimitedPriorityLevelConfiguration.AssuredConcurrencyShares has been\n// renamed to NominalConcurrencyShares in v1beta3.\nfunc Convert_flowcontrol_LimitedPriorityLevelConfiguration_To_v1beta1_LimitedPriorityLevelConfiguration(in *flowcontrol.LimitedPriorityLevelConfiguration, out *v1beta1.LimitedPriorityLevelConfiguration, s conversion.Scope) error {\n\tif err := autoConvert_flowcontrol_LimitedPriorityLevelConfiguration_To_v1beta1_LimitedPriorityLevelConfiguration(in, out, nil); err != nil {\n\t\treturn err\n\t}\n\n\tout.AssuredConcurrencyShares = in.NominalConcurrencyShares\n\treturn nil\n}","line":{"from":36,"to":45}} {"id":100002806,"name":"SetDefaults_FlowSchemaSpec","signature":"func SetDefaults_FlowSchemaSpec(spec *v1beta1.FlowSchemaSpec)","file":"pkg/apis/flowcontrol/v1beta1/defaults.go","code":"// SetDefaults_FlowSchema sets default values for flow schema\nfunc SetDefaults_FlowSchemaSpec(spec *v1beta1.FlowSchemaSpec) {\n\tif spec.MatchingPrecedence == 0 {\n\t\tspec.MatchingPrecedence = FlowSchemaDefaultMatchingPrecedence\n\t}\n}","line":{"from":36,"to":41}} {"id":100002807,"name":"SetDefaults_LimitedPriorityLevelConfiguration","signature":"func SetDefaults_LimitedPriorityLevelConfiguration(lplc *v1beta1.LimitedPriorityLevelConfiguration)","file":"pkg/apis/flowcontrol/v1beta1/defaults.go","code":"func SetDefaults_LimitedPriorityLevelConfiguration(lplc *v1beta1.LimitedPriorityLevelConfiguration) {\n\tif lplc.AssuredConcurrencyShares == 0 {\n\t\tlplc.AssuredConcurrencyShares = PriorityLevelConfigurationDefaultAssuredConcurrencyShares\n\t}\n\tif lplc.LendablePercent == nil {\n\t\tlplc.LendablePercent = new(int32)\n\t\t*lplc.LendablePercent = 0\n\t}\n}","line":{"from":43,"to":51}} {"id":100002808,"name":"SetDefaults_QueuingConfiguration","signature":"func SetDefaults_QueuingConfiguration(cfg *v1beta1.QueuingConfiguration)","file":"pkg/apis/flowcontrol/v1beta1/defaults.go","code":"// SetDefaults_FlowSchema sets default values for flow schema\nfunc SetDefaults_QueuingConfiguration(cfg *v1beta1.QueuingConfiguration) {\n\tif cfg.HandSize == 0 {\n\t\tcfg.HandSize = PriorityLevelConfigurationDefaultHandSize\n\t}\n\tif cfg.Queues == 0 {\n\t\tcfg.Queues = PriorityLevelConfigurationDefaultQueues\n\t}\n\tif cfg.QueueLengthLimit == 0 {\n\t\tcfg.QueueLengthLimit = PriorityLevelConfigurationDefaultQueueLengthLimit\n\t}\n}","line":{"from":53,"to":64}} {"id":100002809,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/flowcontrol/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002810,"name":"init","signature":"func init()","file":"pkg/apis/flowcontrol/v1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(RegisterDefaults)\n}","line":{"from":41,"to":46}} {"id":100002811,"name":"Convert_v1beta2_LimitedPriorityLevelConfiguration_To_flowcontrol_LimitedPriorityLevelConfiguration","signature":"func Convert_v1beta2_LimitedPriorityLevelConfiguration_To_flowcontrol_LimitedPriorityLevelConfiguration(in *v1beta2.LimitedPriorityLevelConfiguration, out *flowcontrol.LimitedPriorityLevelConfiguration, s conversion.Scope) error","file":"pkg/apis/flowcontrol/v1beta2/conversion.go","code":"// LimitedPriorityLevelConfiguration.AssuredConcurrencyShares has been\n// renamed to NominalConcurrencyShares in v1beta3.\nfunc Convert_v1beta2_LimitedPriorityLevelConfiguration_To_flowcontrol_LimitedPriorityLevelConfiguration(in *v1beta2.LimitedPriorityLevelConfiguration, out *flowcontrol.LimitedPriorityLevelConfiguration, s conversion.Scope) error {\n\tif err := autoConvert_v1beta2_LimitedPriorityLevelConfiguration_To_flowcontrol_LimitedPriorityLevelConfiguration(in, out, nil); err != nil {\n\t\treturn err\n\t}\n\n\tout.NominalConcurrencyShares = in.AssuredConcurrencyShares\n\treturn nil\n}","line":{"from":25,"to":34}} {"id":100002812,"name":"Convert_flowcontrol_LimitedPriorityLevelConfiguration_To_v1beta2_LimitedPriorityLevelConfiguration","signature":"func Convert_flowcontrol_LimitedPriorityLevelConfiguration_To_v1beta2_LimitedPriorityLevelConfiguration(in *flowcontrol.LimitedPriorityLevelConfiguration, out *v1beta2.LimitedPriorityLevelConfiguration, s conversion.Scope) error","file":"pkg/apis/flowcontrol/v1beta2/conversion.go","code":"// LimitedPriorityLevelConfiguration.AssuredConcurrencyShares has been\n// renamed to NominalConcurrencyShares in v1beta3.\nfunc Convert_flowcontrol_LimitedPriorityLevelConfiguration_To_v1beta2_LimitedPriorityLevelConfiguration(in *flowcontrol.LimitedPriorityLevelConfiguration, out *v1beta2.LimitedPriorityLevelConfiguration, s conversion.Scope) error {\n\tif err := autoConvert_flowcontrol_LimitedPriorityLevelConfiguration_To_v1beta2_LimitedPriorityLevelConfiguration(in, out, nil); err != nil {\n\t\treturn err\n\t}\n\n\tout.AssuredConcurrencyShares = in.NominalConcurrencyShares\n\treturn nil\n}","line":{"from":36,"to":45}} {"id":100002813,"name":"SetDefaults_FlowSchemaSpec","signature":"func SetDefaults_FlowSchemaSpec(spec *v1beta2.FlowSchemaSpec)","file":"pkg/apis/flowcontrol/v1beta2/defaults.go","code":"// SetDefaults_FlowSchema sets default values for flow schema\nfunc SetDefaults_FlowSchemaSpec(spec *v1beta2.FlowSchemaSpec) {\n\tif spec.MatchingPrecedence == 0 {\n\t\tspec.MatchingPrecedence = FlowSchemaDefaultMatchingPrecedence\n\t}\n}","line":{"from":36,"to":41}} {"id":100002814,"name":"SetDefaults_LimitedPriorityLevelConfiguration","signature":"func SetDefaults_LimitedPriorityLevelConfiguration(lplc *v1beta2.LimitedPriorityLevelConfiguration)","file":"pkg/apis/flowcontrol/v1beta2/defaults.go","code":"func SetDefaults_LimitedPriorityLevelConfiguration(lplc *v1beta2.LimitedPriorityLevelConfiguration) {\n\tif lplc.AssuredConcurrencyShares == 0 {\n\t\tlplc.AssuredConcurrencyShares = PriorityLevelConfigurationDefaultAssuredConcurrencyShares\n\t}\n\tif lplc.LendablePercent == nil {\n\t\tlplc.LendablePercent = new(int32)\n\t\t*lplc.LendablePercent = 0\n\t}\n}","line":{"from":43,"to":51}} {"id":100002815,"name":"SetDefaults_QueuingConfiguration","signature":"func SetDefaults_QueuingConfiguration(cfg *v1beta2.QueuingConfiguration)","file":"pkg/apis/flowcontrol/v1beta2/defaults.go","code":"// SetDefaults_FlowSchema sets default values for flow schema\nfunc SetDefaults_QueuingConfiguration(cfg *v1beta2.QueuingConfiguration) {\n\tif cfg.HandSize == 0 {\n\t\tcfg.HandSize = PriorityLevelConfigurationDefaultHandSize\n\t}\n\tif cfg.Queues == 0 {\n\t\tcfg.Queues = PriorityLevelConfigurationDefaultQueues\n\t}\n\tif cfg.QueueLengthLimit == 0 {\n\t\tcfg.QueueLengthLimit = PriorityLevelConfigurationDefaultQueueLengthLimit\n\t}\n}","line":{"from":53,"to":64}} {"id":100002816,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/flowcontrol/v1beta2/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002817,"name":"init","signature":"func init()","file":"pkg/apis/flowcontrol/v1beta2/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(RegisterDefaults)\n}","line":{"from":41,"to":46}} {"id":100002818,"name":"SetDefaults_FlowSchemaSpec","signature":"func SetDefaults_FlowSchemaSpec(spec *v1beta3.FlowSchemaSpec)","file":"pkg/apis/flowcontrol/v1beta3/defaults.go","code":"// SetDefaults_FlowSchema sets default values for flow schema\nfunc SetDefaults_FlowSchemaSpec(spec *v1beta3.FlowSchemaSpec) {\n\tif spec.MatchingPrecedence == 0 {\n\t\tspec.MatchingPrecedence = FlowSchemaDefaultMatchingPrecedence\n\t}\n}","line":{"from":36,"to":41}} {"id":100002819,"name":"SetDefaults_LimitedPriorityLevelConfiguration","signature":"func SetDefaults_LimitedPriorityLevelConfiguration(lplc *v1beta3.LimitedPriorityLevelConfiguration)","file":"pkg/apis/flowcontrol/v1beta3/defaults.go","code":"func SetDefaults_LimitedPriorityLevelConfiguration(lplc *v1beta3.LimitedPriorityLevelConfiguration) {\n\tif lplc.NominalConcurrencyShares == 0 {\n\t\tlplc.NominalConcurrencyShares = PriorityLevelConfigurationDefaultNominalConcurrencyShares\n\t}\n\tif lplc.LendablePercent == nil {\n\t\tlplc.LendablePercent = new(int32)\n\t\t*lplc.LendablePercent = 0\n\t}\n}","line":{"from":43,"to":51}} {"id":100002820,"name":"SetDefaults_QueuingConfiguration","signature":"func SetDefaults_QueuingConfiguration(cfg *v1beta3.QueuingConfiguration)","file":"pkg/apis/flowcontrol/v1beta3/defaults.go","code":"// SetDefaults_FlowSchema sets default values for flow schema\nfunc SetDefaults_QueuingConfiguration(cfg *v1beta3.QueuingConfiguration) {\n\tif cfg.HandSize == 0 {\n\t\tcfg.HandSize = PriorityLevelConfigurationDefaultHandSize\n\t}\n\tif cfg.Queues == 0 {\n\t\tcfg.Queues = PriorityLevelConfigurationDefaultQueues\n\t}\n\tif cfg.QueueLengthLimit == 0 {\n\t\tcfg.QueueLengthLimit = PriorityLevelConfigurationDefaultQueueLengthLimit\n\t}\n}","line":{"from":53,"to":64}} {"id":100002821,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/flowcontrol/v1beta3/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002822,"name":"init","signature":"func init()","file":"pkg/apis/flowcontrol/v1beta3/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(RegisterDefaults)\n}","line":{"from":41,"to":46}} {"id":100002823,"name":"ValidateFlowSchema","signature":"func ValidateFlowSchema(fs *flowcontrol.FlowSchema) field.ErrorList","file":"pkg/apis/flowcontrol/validation/validation.go","code":"// ValidateFlowSchema validates the content of flow-schema\nfunc ValidateFlowSchema(fs *flowcontrol.FlowSchema) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMeta(\u0026fs.ObjectMeta, false, ValidateFlowSchemaName, field.NewPath(\"metadata\"))\n\tspecPath := field.NewPath(\"spec\")\n\tallErrs = append(allErrs, ValidateFlowSchemaSpec(fs.Name, \u0026fs.Spec, specPath)...)\n\tif mand, ok := internalbootstrap.MandatoryFlowSchemas[fs.Name]; ok {\n\t\t// Check for almost exact equality. This is a pretty\n\t\t// strict test, and it is OK in this context because both\n\t\t// sides of this comparison are intended to ultimately\n\t\t// come from the same code.\n\t\tif !apiequality.Semantic.DeepEqual(fs.Spec, mand.Spec) {\n\t\t\tallErrs = append(allErrs, field.Invalid(specPath, fs.Spec, fmt.Sprintf(\"spec of '%s' must equal the fixed value\", fs.Name)))\n\t\t}\n\t}\n\tallErrs = append(allErrs, ValidateFlowSchemaStatus(\u0026fs.Status, field.NewPath(\"status\"))...)\n\treturn allErrs\n}","line":{"from":78,"to":94}} {"id":100002824,"name":"ValidateFlowSchemaUpdate","signature":"func ValidateFlowSchemaUpdate(old, fs *flowcontrol.FlowSchema) field.ErrorList","file":"pkg/apis/flowcontrol/validation/validation.go","code":"// ValidateFlowSchemaUpdate validates the update of flow-schema\nfunc ValidateFlowSchemaUpdate(old, fs *flowcontrol.FlowSchema) field.ErrorList {\n\treturn ValidateFlowSchema(fs)\n}","line":{"from":96,"to":99}} {"id":100002825,"name":"ValidateFlowSchemaSpec","signature":"func ValidateFlowSchemaSpec(fsName string, spec *flowcontrol.FlowSchemaSpec, fldPath *field.Path) field.ErrorList","file":"pkg/apis/flowcontrol/validation/validation.go","code":"// ValidateFlowSchemaSpec validates the content of flow-schema's spec\nfunc ValidateFlowSchemaSpec(fsName string, spec *flowcontrol.FlowSchemaSpec, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tif spec.MatchingPrecedence \u003c= 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"matchingPrecedence\"), spec.MatchingPrecedence, \"must be a positive value\"))\n\t}\n\tif spec.MatchingPrecedence \u003e flowcontrol.FlowSchemaMaxMatchingPrecedence {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"matchingPrecedence\"), spec.MatchingPrecedence, fmt.Sprintf(\"must not be greater than %v\", flowcontrol.FlowSchemaMaxMatchingPrecedence)))\n\t}\n\tif (spec.MatchingPrecedence == 1) \u0026\u0026 (fsName != flowcontrol.FlowSchemaNameExempt) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"matchingPrecedence\"), spec.MatchingPrecedence, \"only the schema named 'exempt' may have matchingPrecedence 1\"))\n\t}\n\tif spec.DistinguisherMethod != nil {\n\t\tif !supportedDistinguisherMethods.Has(string(spec.DistinguisherMethod.Type)) {\n\t\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"distinguisherMethod\").Child(\"type\"), spec.DistinguisherMethod, supportedDistinguisherMethods.List()))\n\t\t}\n\t}\n\tif len(spec.PriorityLevelConfiguration.Name) \u003e 0 {\n\t\tfor _, msg := range ValidatePriorityLevelConfigurationName(spec.PriorityLevelConfiguration.Name, false) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"priorityLevelConfiguration\").Child(\"name\"), spec.PriorityLevelConfiguration.Name, msg))\n\t\t}\n\t} else {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"priorityLevelConfiguration\").Child(\"name\"), \"must reference a priority level\"))\n\t}\n\tfor i, rule := range spec.Rules {\n\t\tallErrs = append(allErrs, ValidateFlowSchemaPolicyRulesWithSubjects(\u0026rule, fldPath.Child(\"rules\").Index(i))...)\n\t}\n\treturn allErrs\n}","line":{"from":101,"to":129}} {"id":100002826,"name":"ValidateFlowSchemaPolicyRulesWithSubjects","signature":"func ValidateFlowSchemaPolicyRulesWithSubjects(rule *flowcontrol.PolicyRulesWithSubjects, fldPath *field.Path) field.ErrorList","file":"pkg/apis/flowcontrol/validation/validation.go","code":"// ValidateFlowSchemaPolicyRulesWithSubjects validates policy-rule-with-subjects object.\nfunc ValidateFlowSchemaPolicyRulesWithSubjects(rule *flowcontrol.PolicyRulesWithSubjects, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tif len(rule.Subjects) \u003e 0 {\n\t\tfor i, subject := range rule.Subjects {\n\t\t\tallErrs = append(allErrs, ValidateFlowSchemaSubject(\u0026subject, fldPath.Child(\"subjects\").Index(i))...)\n\t\t}\n\t} else {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"subjects\"), \"subjects must contain at least one value\"))\n\t}\n\n\tif len(rule.ResourceRules) == 0 \u0026\u0026 len(rule.NonResourceRules) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath, \"at least one of resourceRules and nonResourceRules has to be non-empty\"))\n\t}\n\tfor i, resourceRule := range rule.ResourceRules {\n\t\tallErrs = append(allErrs, ValidateFlowSchemaResourcePolicyRule(\u0026resourceRule, fldPath.Child(\"resourceRules\").Index(i))...)\n\t}\n\tfor i, nonResourceRule := range rule.NonResourceRules {\n\t\tallErrs = append(allErrs, ValidateFlowSchemaNonResourcePolicyRule(\u0026nonResourceRule, fldPath.Child(\"nonResourceRules\").Index(i))...)\n\t}\n\treturn allErrs\n}","line":{"from":131,"to":152}} {"id":100002827,"name":"ValidateFlowSchemaSubject","signature":"func ValidateFlowSchemaSubject(subject *flowcontrol.Subject, fldPath *field.Path) field.ErrorList","file":"pkg/apis/flowcontrol/validation/validation.go","code":"// ValidateFlowSchemaSubject validates flow-schema's subject object.\nfunc ValidateFlowSchemaSubject(subject *flowcontrol.Subject, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tswitch subject.Kind {\n\tcase flowcontrol.SubjectKindServiceAccount:\n\t\tallErrs = append(allErrs, ValidateServiceAccountSubject(subject.ServiceAccount, fldPath.Child(\"serviceAccount\"))...)\n\t\tif subject.User != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"user\"), \"user is forbidden when subject kind is not 'User'\"))\n\t\t}\n\t\tif subject.Group != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"group\"), \"group is forbidden when subject kind is not 'Group'\"))\n\t\t}\n\tcase flowcontrol.SubjectKindUser:\n\t\tallErrs = append(allErrs, ValidateUserSubject(subject.User, fldPath.Child(\"user\"))...)\n\t\tif subject.ServiceAccount != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"serviceAccount\"), \"serviceAccount is forbidden when subject kind is not 'ServiceAccount'\"))\n\t\t}\n\t\tif subject.Group != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"group\"), \"group is forbidden when subject kind is not 'Group'\"))\n\t\t}\n\tcase flowcontrol.SubjectKindGroup:\n\t\tallErrs = append(allErrs, ValidateGroupSubject(subject.Group, fldPath.Child(\"group\"))...)\n\t\tif subject.ServiceAccount != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"serviceAccount\"), \"serviceAccount is forbidden when subject kind is not 'ServiceAccount'\"))\n\t\t}\n\t\tif subject.User != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"user\"), \"user is forbidden when subject kind is not 'User'\"))\n\t\t}\n\tdefault:\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"kind\"), subject.Kind, supportedSubjectKinds.List()))\n\t}\n\treturn allErrs\n}","line":{"from":154,"to":186}} {"id":100002828,"name":"ValidateServiceAccountSubject","signature":"func ValidateServiceAccountSubject(subject *flowcontrol.ServiceAccountSubject, fldPath *field.Path) field.ErrorList","file":"pkg/apis/flowcontrol/validation/validation.go","code":"// ValidateServiceAccountSubject validates subject of \"ServiceAccount\" kind\nfunc ValidateServiceAccountSubject(subject *flowcontrol.ServiceAccountSubject, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tif subject == nil {\n\t\treturn append(allErrs, field.Required(fldPath, \"serviceAccount is required when subject kind is 'ServiceAccount'\"))\n\t}\n\tif len(subject.Name) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"name\"), \"\"))\n\t} else if subject.Name != flowcontrol.NameAll {\n\t\tfor _, msg := range apimachineryvalidation.ValidateServiceAccountName(subject.Name, false) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"name\"), subject.Name, msg))\n\t\t}\n\t}\n\n\tif len(subject.Namespace) \u003e 0 {\n\t\tfor _, msg := range apimachineryvalidation.ValidateNamespaceName(subject.Namespace, false) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"namespace\"), subject.Namespace, msg))\n\t\t}\n\t} else {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"namespace\"), \"must specify namespace for service account\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":188,"to":211}} {"id":100002829,"name":"ValidateUserSubject","signature":"func ValidateUserSubject(subject *flowcontrol.UserSubject, fldPath *field.Path) field.ErrorList","file":"pkg/apis/flowcontrol/validation/validation.go","code":"// ValidateUserSubject validates subject of \"User\" kind\nfunc ValidateUserSubject(subject *flowcontrol.UserSubject, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tif subject == nil {\n\t\treturn append(allErrs, field.Required(fldPath, \"user is required when subject kind is 'User'\"))\n\t}\n\tif len(subject.Name) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"name\"), \"\"))\n\t}\n\treturn allErrs\n}","line":{"from":213,"to":223}} {"id":100002830,"name":"ValidateGroupSubject","signature":"func ValidateGroupSubject(subject *flowcontrol.GroupSubject, fldPath *field.Path) field.ErrorList","file":"pkg/apis/flowcontrol/validation/validation.go","code":"// ValidateGroupSubject validates subject of \"Group\" kind\nfunc ValidateGroupSubject(subject *flowcontrol.GroupSubject, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tif subject == nil {\n\t\treturn append(allErrs, field.Required(fldPath, \"group is required when subject kind is 'Group'\"))\n\t}\n\tif len(subject.Name) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"name\"), \"\"))\n\t}\n\treturn allErrs\n}","line":{"from":225,"to":235}} {"id":100002831,"name":"ValidateFlowSchemaNonResourcePolicyRule","signature":"func ValidateFlowSchemaNonResourcePolicyRule(rule *flowcontrol.NonResourcePolicyRule, fldPath *field.Path) field.ErrorList","file":"pkg/apis/flowcontrol/validation/validation.go","code":"// ValidateFlowSchemaNonResourcePolicyRule validates non-resource policy-rule in the flow-schema.\nfunc ValidateFlowSchemaNonResourcePolicyRule(rule *flowcontrol.NonResourcePolicyRule, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\n\tif len(rule.Verbs) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"verbs\"), \"verbs must contain at least one value\"))\n\t} else if hasWildcard(rule.Verbs) {\n\t\tif len(rule.Verbs) \u003e 1 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"verbs\"), rule.Verbs, \"if '*' is present, must not specify other verbs\"))\n\t\t}\n\t} else if !supportedVerbs.IsSuperset(sets.NewString(rule.Verbs...)) {\n\t\t// only supported verbs are allowed\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"verbs\"), rule.Verbs, supportedVerbs.List()))\n\t}\n\n\tif len(rule.NonResourceURLs) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"nonResourceURLs\"), \"nonResourceURLs must contain at least one value\"))\n\t} else if hasWildcard(rule.NonResourceURLs) {\n\t\tif len(rule.NonResourceURLs) \u003e 1 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"nonResourceURLs\"), rule.NonResourceURLs, \"if '*' is present, must not specify other non-resource URLs\"))\n\t\t}\n\t} else {\n\t\tfor i, nonResourceURL := range rule.NonResourceURLs {\n\t\t\tif err := ValidateNonResourceURLPath(nonResourceURL, fldPath.Child(\"nonResourceURLs\").Index(i)); err != nil {\n\t\t\t\tallErrs = append(allErrs, err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":237,"to":267}} {"id":100002832,"name":"ValidateFlowSchemaResourcePolicyRule","signature":"func ValidateFlowSchemaResourcePolicyRule(rule *flowcontrol.ResourcePolicyRule, fldPath *field.Path) field.ErrorList","file":"pkg/apis/flowcontrol/validation/validation.go","code":"// ValidateFlowSchemaResourcePolicyRule validates resource policy-rule in the flow-schema.\nfunc ValidateFlowSchemaResourcePolicyRule(rule *flowcontrol.ResourcePolicyRule, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\n\tif len(rule.Verbs) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"verbs\"), \"verbs must contain at least one value\"))\n\t} else if hasWildcard(rule.Verbs) {\n\t\tif len(rule.Verbs) \u003e 1 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"verbs\"), rule.Verbs, \"if '*' is present, must not specify other verbs\"))\n\t\t}\n\t} else if !supportedVerbs.IsSuperset(sets.NewString(rule.Verbs...)) {\n\t\t// only supported verbs are allowed\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"verbs\"), rule.Verbs, supportedVerbs.List()))\n\t}\n\n\tif len(rule.APIGroups) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"apiGroups\"), \"resource rules must supply at least one api group\"))\n\t} else if len(rule.APIGroups) \u003e 1 \u0026\u0026 hasWildcard(rule.APIGroups) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"apiGroups\"), rule.APIGroups, \"if '*' is present, must not specify other api groups\"))\n\t}\n\n\tif len(rule.Resources) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"resources\"), \"resource rules must supply at least one resource\"))\n\t} else if len(rule.Resources) \u003e 1 \u0026\u0026 hasWildcard(rule.Resources) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"resources\"), rule.Resources, \"if '*' is present, must not specify other resources\"))\n\t}\n\n\tif len(rule.Namespaces) == 0 \u0026\u0026 !rule.ClusterScope {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"namespaces\"), \"resource rules that are not cluster scoped must supply at least one namespace\"))\n\t} else if hasWildcard(rule.Namespaces) {\n\t\tif len(rule.Namespaces) \u003e 1 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"namespaces\"), rule.Namespaces, \"if '*' is present, must not specify other namespaces\"))\n\t\t}\n\t} else {\n\t\tfor idx, tgtNS := range rule.Namespaces {\n\t\t\tfor _, msg := range apimachineryvalidation.ValidateNamespaceName(tgtNS, false) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"namespaces\").Index(idx), tgtNS, nsErrIntro+msg))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":269,"to":311}} {"id":100002833,"name":"ValidateFlowSchemaStatus","signature":"func ValidateFlowSchemaStatus(status *flowcontrol.FlowSchemaStatus, fldPath *field.Path) field.ErrorList","file":"pkg/apis/flowcontrol/validation/validation.go","code":"// ValidateFlowSchemaStatus validates status for the flow-schema.\nfunc ValidateFlowSchemaStatus(status *flowcontrol.FlowSchemaStatus, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tkeys := sets.NewString()\n\tfor i, condition := range status.Conditions {\n\t\tif keys.Has(string(condition.Type)) {\n\t\t\tallErrs = append(allErrs, field.Duplicate(fldPath.Child(\"conditions\").Index(i).Child(\"type\"), condition.Type))\n\t\t}\n\t\tkeys.Insert(string(condition.Type))\n\t\tallErrs = append(allErrs, ValidateFlowSchemaCondition(\u0026condition, fldPath.Child(\"conditions\").Index(i))...)\n\t}\n\treturn allErrs\n}","line":{"from":315,"to":327}} {"id":100002834,"name":"ValidateFlowSchemaStatusUpdate","signature":"func ValidateFlowSchemaStatusUpdate(old, fs *flowcontrol.FlowSchema) field.ErrorList","file":"pkg/apis/flowcontrol/validation/validation.go","code":"// ValidateFlowSchemaStatusUpdate validates the update of status for the flow-schema.\nfunc ValidateFlowSchemaStatusUpdate(old, fs *flowcontrol.FlowSchema) field.ErrorList {\n\treturn ValidateFlowSchemaStatus(\u0026fs.Status, field.NewPath(\"status\"))\n}","line":{"from":329,"to":332}} {"id":100002835,"name":"ValidateFlowSchemaCondition","signature":"func ValidateFlowSchemaCondition(condition *flowcontrol.FlowSchemaCondition, fldPath *field.Path) field.ErrorList","file":"pkg/apis/flowcontrol/validation/validation.go","code":"// ValidateFlowSchemaCondition validates condition in the flow-schema's status.\nfunc ValidateFlowSchemaCondition(condition *flowcontrol.FlowSchemaCondition, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tif len(condition.Type) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"type\"), \"must not be empty\"))\n\t}\n\treturn allErrs\n}","line":{"from":334,"to":341}} {"id":100002836,"name":"ValidatePriorityLevelConfiguration","signature":"func ValidatePriorityLevelConfiguration(pl *flowcontrol.PriorityLevelConfiguration, requestGV schema.GroupVersion) field.ErrorList","file":"pkg/apis/flowcontrol/validation/validation.go","code":"// ValidatePriorityLevelConfiguration validates priority-level-configuration.\nfunc ValidatePriorityLevelConfiguration(pl *flowcontrol.PriorityLevelConfiguration, requestGV schema.GroupVersion) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMeta(\u0026pl.ObjectMeta, false, ValidatePriorityLevelConfigurationName, field.NewPath(\"metadata\"))\n\tspecPath := field.NewPath(\"spec\")\n\tallErrs = append(allErrs, ValidatePriorityLevelConfigurationSpec(\u0026pl.Spec, requestGV, pl.Name, specPath)...)\n\tif mand, ok := internalbootstrap.MandatoryPriorityLevelConfigurations[pl.Name]; ok {\n\t\t// Check for almost exact equality. This is a pretty\n\t\t// strict test, and it is OK in this context because both\n\t\t// sides of this comparison are intended to ultimately\n\t\t// come from the same code.\n\t\tif !apiequality.Semantic.DeepEqual(pl.Spec, mand.Spec) {\n\t\t\tallErrs = append(allErrs, field.Invalid(specPath, pl.Spec, fmt.Sprintf(\"spec of '%s' must equal the fixed value\", pl.Name)))\n\t\t}\n\t}\n\tallErrs = append(allErrs, ValidatePriorityLevelConfigurationStatus(\u0026pl.Status, field.NewPath(\"status\"))...)\n\treturn allErrs\n}","line":{"from":343,"to":359}} {"id":100002837,"name":"ValidatePriorityLevelConfigurationSpec","signature":"func ValidatePriorityLevelConfigurationSpec(spec *flowcontrol.PriorityLevelConfigurationSpec, requestGV schema.GroupVersion, name string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/flowcontrol/validation/validation.go","code":"// ValidatePriorityLevelConfigurationSpec validates priority-level-configuration's spec.\nfunc ValidatePriorityLevelConfigurationSpec(spec *flowcontrol.PriorityLevelConfigurationSpec, requestGV schema.GroupVersion, name string, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tif (name == flowcontrol.PriorityLevelConfigurationNameExempt) != (spec.Type == flowcontrol.PriorityLevelEnablementExempt) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"type\"), spec.Type, \"type must be 'Exempt' if and only if name is 'exempt'\"))\n\t}\n\tswitch spec.Type {\n\tcase flowcontrol.PriorityLevelEnablementExempt:\n\t\tif spec.Limited != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"limited\"), \"must be nil if the type is not Limited\"))\n\t\t}\n\tcase flowcontrol.PriorityLevelEnablementLimited:\n\t\tif spec.Limited == nil {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"limited\"), \"must not be empty when type is Limited\"))\n\t\t} else {\n\t\t\tallErrs = append(allErrs, ValidateLimitedPriorityLevelConfiguration(spec.Limited, requestGV, fldPath.Child(\"limited\"))...)\n\t\t}\n\tdefault:\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"type\"), spec.Type, supportedPriorityLevelEnablement.List()))\n\t}\n\treturn allErrs\n}","line":{"from":361,"to":382}} {"id":100002838,"name":"ValidateLimitedPriorityLevelConfiguration","signature":"func ValidateLimitedPriorityLevelConfiguration(lplc *flowcontrol.LimitedPriorityLevelConfiguration, requestGV schema.GroupVersion, fldPath *field.Path) field.ErrorList","file":"pkg/apis/flowcontrol/validation/validation.go","code":"// ValidateLimitedPriorityLevelConfiguration validates the configuration for an execution-limited priority level\nfunc ValidateLimitedPriorityLevelConfiguration(lplc *flowcontrol.LimitedPriorityLevelConfiguration, requestGV schema.GroupVersion, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tif lplc.NominalConcurrencyShares \u003c= 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(getVersionedFieldNameForConcurrencyShares(requestGV)), lplc.NominalConcurrencyShares, \"must be positive\"))\n\t}\n\tallErrs = append(allErrs, ValidateLimitResponse(lplc.LimitResponse, fldPath.Child(\"limitResponse\"))...)\n\n\tif lplc.LendablePercent != nil \u0026\u0026 !(*lplc.LendablePercent \u003e= 0 \u0026\u0026 *lplc.LendablePercent \u003c= 100) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"lendablePercent\"), *lplc.LendablePercent, \"must be between 0 and 100, inclusive\"))\n\t}\n\tif lplc.BorrowingLimitPercent != nil \u0026\u0026 *lplc.BorrowingLimitPercent \u003c 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"borrowingLimitPercent\"), *lplc.BorrowingLimitPercent, \"if specified, must be a non-negative integer\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":384,"to":400}} {"id":100002839,"name":"getVersionedFieldNameForConcurrencyShares","signature":"func getVersionedFieldNameForConcurrencyShares(requestGV schema.GroupVersion) string","file":"pkg/apis/flowcontrol/validation/validation.go","code":"func getVersionedFieldNameForConcurrencyShares(requestGV schema.GroupVersion) string {\n\tswitch {\n\tcase requestGV == flowcontrolv1alpha1.SchemeGroupVersion ||\n\t\trequestGV == flowcontrolv1beta1.SchemeGroupVersion ||\n\t\trequestGV == flowcontrolv1beta2.SchemeGroupVersion:\n\t\treturn \"assuredConcurrencyShares\"\n\tdefault:\n\t\treturn \"nominalConcurrencyShares\"\n\t}\n}","line":{"from":402,"to":411}} {"id":100002840,"name":"ValidateLimitResponse","signature":"func ValidateLimitResponse(lr flowcontrol.LimitResponse, fldPath *field.Path) field.ErrorList","file":"pkg/apis/flowcontrol/validation/validation.go","code":"// ValidateLimitResponse validates a LimitResponse\nfunc ValidateLimitResponse(lr flowcontrol.LimitResponse, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tswitch lr.Type {\n\tcase flowcontrol.LimitResponseTypeReject:\n\t\tif lr.Queuing != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"queuing\"), \"must be nil if limited.limitResponse.type is not Limited\"))\n\t\t}\n\tcase flowcontrol.LimitResponseTypeQueue:\n\t\tif lr.Queuing == nil {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"queuing\"), \"must not be empty if limited.limitResponse.type is Limited\"))\n\t\t} else {\n\t\t\tallErrs = append(allErrs, ValidatePriorityLevelQueuingConfiguration(lr.Queuing, fldPath.Child(\"queuing\"))...)\n\t\t}\n\tdefault:\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"type\"), lr.Type, supportedLimitResponseType.List()))\n\t}\n\treturn allErrs\n}","line":{"from":413,"to":431}} {"id":100002841,"name":"ValidatePriorityLevelQueuingConfiguration","signature":"func ValidatePriorityLevelQueuingConfiguration(queuing *flowcontrol.QueuingConfiguration, fldPath *field.Path) field.ErrorList","file":"pkg/apis/flowcontrol/validation/validation.go","code":"// ValidatePriorityLevelQueuingConfiguration validates queuing-configuration for a priority-level\nfunc ValidatePriorityLevelQueuingConfiguration(queuing *flowcontrol.QueuingConfiguration, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tif queuing.QueueLengthLimit \u003c= 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"queueLengthLimit\"), queuing.QueueLengthLimit, \"must be positive\"))\n\t}\n\n\t// validate input arguments for shuffle-sharding\n\tif queuing.Queues \u003c= 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"queues\"), queuing.Queues, \"must be positive\"))\n\t} else if queuing.Queues \u003e priorityLevelConfigurationQueuingMaxQueues {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"queues\"), queuing.Queues,\n\t\t\tfmt.Sprintf(\"must not be greater than %d\", priorityLevelConfigurationQueuingMaxQueues)))\n\t}\n\n\tif queuing.HandSize \u003c= 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"handSize\"), queuing.HandSize, \"must be positive\"))\n\t} else if queuing.HandSize \u003e queuing.Queues {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"handSize\"), queuing.HandSize,\n\t\t\tfmt.Sprintf(\"should not be greater than queues (%d)\", queuing.Queues)))\n\t} else if entropy := shufflesharding.RequiredEntropyBits(int(queuing.Queues), int(queuing.HandSize)); entropy \u003e shufflesharding.MaxHashBits {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"handSize\"), queuing.HandSize,\n\t\t\tfmt.Sprintf(\"required entropy bits of deckSize %d and handSize %d should not be greater than %d\", queuing.Queues, queuing.HandSize, shufflesharding.MaxHashBits)))\n\t}\n\treturn allErrs\n}","line":{"from":433,"to":458}} {"id":100002842,"name":"ValidatePriorityLevelConfigurationStatus","signature":"func ValidatePriorityLevelConfigurationStatus(status *flowcontrol.PriorityLevelConfigurationStatus, fldPath *field.Path) field.ErrorList","file":"pkg/apis/flowcontrol/validation/validation.go","code":"// ValidatePriorityLevelConfigurationStatus validates priority-level-configuration's status.\nfunc ValidatePriorityLevelConfigurationStatus(status *flowcontrol.PriorityLevelConfigurationStatus, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tkeys := sets.NewString()\n\tfor i, condition := range status.Conditions {\n\t\tif keys.Has(string(condition.Type)) {\n\t\t\tallErrs = append(allErrs, field.Duplicate(fldPath.Child(\"conditions\").Index(i).Child(\"type\"), condition.Type))\n\t\t}\n\t\tkeys.Insert(string(condition.Type))\n\t\tallErrs = append(allErrs, ValidatePriorityLevelConfigurationCondition(\u0026condition, fldPath.Child(\"conditions\").Index(i))...)\n\t}\n\treturn allErrs\n}","line":{"from":460,"to":472}} {"id":100002843,"name":"ValidatePriorityLevelConfigurationStatusUpdate","signature":"func ValidatePriorityLevelConfigurationStatusUpdate(old, pl *flowcontrol.PriorityLevelConfiguration) field.ErrorList","file":"pkg/apis/flowcontrol/validation/validation.go","code":"// ValidatePriorityLevelConfigurationStatusUpdate validates the update of priority-level-configuration's status.\nfunc ValidatePriorityLevelConfigurationStatusUpdate(old, pl *flowcontrol.PriorityLevelConfiguration) field.ErrorList {\n\treturn ValidatePriorityLevelConfigurationStatus(\u0026pl.Status, field.NewPath(\"status\"))\n}","line":{"from":474,"to":477}} {"id":100002844,"name":"ValidatePriorityLevelConfigurationCondition","signature":"func ValidatePriorityLevelConfigurationCondition(condition *flowcontrol.PriorityLevelConfigurationCondition, fldPath *field.Path) field.ErrorList","file":"pkg/apis/flowcontrol/validation/validation.go","code":"// ValidatePriorityLevelConfigurationCondition validates condition in priority-level-configuration's status.\nfunc ValidatePriorityLevelConfigurationCondition(condition *flowcontrol.PriorityLevelConfigurationCondition, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tif len(condition.Type) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"type\"), \"must not be empty\"))\n\t}\n\treturn allErrs\n}","line":{"from":479,"to":486}} {"id":100002845,"name":"ValidateNonResourceURLPath","signature":"func ValidateNonResourceURLPath(path string, fldPath *field.Path) *field.Error","file":"pkg/apis/flowcontrol/validation/validation.go","code":"// ValidateNonResourceURLPath validates non-resource-url path by following rules:\n// 1. Slash must be the leading character of the path\n// 2. White-space is forbidden in the path\n// 3. Continuous/double slash is forbidden in the path\n// 4. Wildcard \"*\" should only do suffix glob matching. Note that wildcard also matches slashes.\nfunc ValidateNonResourceURLPath(path string, fldPath *field.Path) *field.Error {\n\tif len(path) == 0 {\n\t\treturn field.Invalid(fldPath, path, \"must not be empty\")\n\t}\n\tif path == \"/\" { // root path\n\t\treturn nil\n\t}\n\n\tif !strings.HasPrefix(path, \"/\") {\n\t\treturn field.Invalid(fldPath, path, \"must start with slash\")\n\t}\n\tif strings.Contains(path, \" \") {\n\t\treturn field.Invalid(fldPath, path, \"must not contain white-space\")\n\t}\n\tif strings.Contains(path, \"//\") {\n\t\treturn field.Invalid(fldPath, path, \"must not contain double slash\")\n\t}\n\twildcardCount := strings.Count(path, \"*\")\n\tif wildcardCount \u003e 1 || (wildcardCount == 1 \u0026\u0026 path[len(path)-2:] != \"/*\") {\n\t\treturn field.Invalid(fldPath, path, \"wildcard can only do suffix matching\")\n\t}\n\treturn nil\n}","line":{"from":488,"to":515}} {"id":100002846,"name":"hasWildcard","signature":"func hasWildcard(operations []string) bool","file":"pkg/apis/flowcontrol/validation/validation.go","code":"func hasWildcard(operations []string) bool {\n\treturn memberInList(\"*\", operations...)\n}","line":{"from":517,"to":519}} {"id":100002847,"name":"memberInList","signature":"func memberInList(seek string, a ...string) bool","file":"pkg/apis/flowcontrol/validation/validation.go","code":"func memberInList(seek string, a ...string) bool {\n\tfor _, ai := range a {\n\t\tif ai == seek {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":521,"to":528}} {"id":100002848,"name":"init","signature":"func init()","file":"pkg/apis/imagepolicy/install/install.go","code":"func init() {\n\tInstall(legacyscheme.Scheme)\n}","line":{"from":29,"to":31}} {"id":100002849,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"pkg/apis/imagepolicy/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(imagepolicy.AddToScheme(scheme))\n\tutilruntime.Must(v1alpha1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1alpha1.SchemeGroupVersion))\n}","line":{"from":33,"to":38}} {"id":100002850,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"pkg/apis/imagepolicy/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100002851,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/imagepolicy/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100002852,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/imagepolicy/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026ImageReview{},\n\t)\n\t//\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":47,"to":53}} {"id":100002853,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/imagepolicy/v1alpha1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002854,"name":"init","signature":"func init()","file":"pkg/apis/imagepolicy/v1alpha1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(RegisterDefaults)\n}","line":{"from":41,"to":46}} {"id":100002855,"name":"generateRandomIP","signature":"func generateRandomIP(is6 bool, c fuzz.Continue) string","file":"pkg/apis/networking/fuzzer/fuzzer.go","code":"func generateRandomIP(is6 bool, c fuzz.Continue) string {\n\tn := 4\n\tif is6 {\n\t\tn = 16\n\t}\n\tbytes := make([]byte, n)\n\tfor i := 0; i \u003c n; i++ {\n\t\tbytes[i] = uint8(c.Rand.Intn(255))\n\t}\n\n\tip, ok := netip.AddrFromSlice(bytes)\n\tif ok {\n\t\treturn ip.String()\n\t}\n\t// this should not happen but is better to\n\t// return a good IP address than nothing\n\tif is6 {\n\t\treturn \"2001:db8::1\"\n\t}\n\treturn \"192.168.1.1\"\n}","line":{"from":90,"to":110}} {"id":100002856,"name":"init","signature":"func init()","file":"pkg/apis/networking/install/install.go","code":"func init() {\n\tInstall(legacyscheme.Scheme)\n}","line":{"from":31,"to":33}} {"id":100002857,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"pkg/apis/networking/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(networking.AddToScheme(scheme))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(v1alpha1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1.SchemeGroupVersion, v1beta1.SchemeGroupVersion, v1alpha1.SchemeGroupVersion))\n}","line":{"from":35,"to":42}} {"id":100002858,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"pkg/apis/networking/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100002859,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/networking/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100002860,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/networking/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026NetworkPolicy{},\n\t\t\u0026NetworkPolicyList{},\n\t\t\u0026Ingress{},\n\t\t\u0026IngressList{},\n\t\t\u0026IngressClass{},\n\t\t\u0026IngressClassList{},\n\t\t\u0026ClusterCIDR{},\n\t\t\u0026ClusterCIDRList{},\n\t\t\u0026IPAddress{},\n\t\t\u0026IPAddressList{},\n\t)\n\treturn nil\n}","line":{"from":47,"to":61}} {"id":100002861,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/networking/v1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":26,"to":28}} {"id":100002862,"name":"SetDefaults_NetworkPolicyPort","signature":"func SetDefaults_NetworkPolicyPort(obj *networkingv1.NetworkPolicyPort)","file":"pkg/apis/networking/v1/defaults.go","code":"func SetDefaults_NetworkPolicyPort(obj *networkingv1.NetworkPolicyPort) {\n\t// Default any undefined Protocol fields to TCP.\n\tif obj.Protocol == nil {\n\t\tproto := v1.ProtocolTCP\n\t\tobj.Protocol = \u0026proto\n\t}\n}","line":{"from":30,"to":36}} {"id":100002863,"name":"SetDefaults_NetworkPolicy","signature":"func SetDefaults_NetworkPolicy(obj *networkingv1.NetworkPolicy)","file":"pkg/apis/networking/v1/defaults.go","code":"func SetDefaults_NetworkPolicy(obj *networkingv1.NetworkPolicy) {\n\tif len(obj.Spec.PolicyTypes) == 0 {\n\t\t// Any policy that does not specify policyTypes implies at least \"Ingress\".\n\t\tobj.Spec.PolicyTypes = []networkingv1.PolicyType{networkingv1.PolicyTypeIngress}\n\t\tif len(obj.Spec.Egress) != 0 {\n\t\t\tobj.Spec.PolicyTypes = append(obj.Spec.PolicyTypes, networkingv1.PolicyTypeEgress)\n\t\t}\n\t}\n}","line":{"from":38,"to":46}} {"id":100002864,"name":"SetDefaults_IngressClass","signature":"func SetDefaults_IngressClass(obj *networkingv1.IngressClass)","file":"pkg/apis/networking/v1/defaults.go","code":"func SetDefaults_IngressClass(obj *networkingv1.IngressClass) {\n\tif obj.Spec.Parameters != nil \u0026\u0026 obj.Spec.Parameters.Scope == nil {\n\t\tobj.Spec.Parameters.Scope = utilpointer.String(networkingv1.IngressClassParametersReferenceScopeCluster)\n\t}\n}","line":{"from":48,"to":52}} {"id":100002865,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/networking/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002866,"name":"init","signature":"func init()","file":"pkg/apis/networking/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":40,"to":45}} {"id":100002867,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/networking/v1alpha1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":23,"to":25}} {"id":100002868,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/networking/v1alpha1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource.\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002869,"name":"init","signature":"func init()","file":"pkg/apis/networking/v1alpha1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":40,"to":45}} {"id":100002870,"name":"Convert_v1beta1_IngressBackend_To_networking_IngressBackend","signature":"func Convert_v1beta1_IngressBackend_To_networking_IngressBackend(in *v1beta1.IngressBackend, out *networking.IngressBackend, s conversion.Scope) error","file":"pkg/apis/networking/v1beta1/conversion.go","code":"func Convert_v1beta1_IngressBackend_To_networking_IngressBackend(in *v1beta1.IngressBackend, out *networking.IngressBackend, s conversion.Scope) error {\n\tif err := autoConvert_v1beta1_IngressBackend_To_networking_IngressBackend(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tif len(in.ServiceName) \u003e 0 || in.ServicePort.IntVal != 0 || in.ServicePort.StrVal != \"\" || in.ServicePort.Type == intstr.String {\n\t\tout.Service = \u0026networking.IngressServiceBackend{}\n\t\tout.Service.Name = in.ServiceName\n\t\tout.Service.Port.Name = in.ServicePort.StrVal\n\t\tout.Service.Port.Number = in.ServicePort.IntVal\n\t}\n\treturn nil\n}","line":{"from":26,"to":37}} {"id":100002871,"name":"Convert_networking_IngressBackend_To_v1beta1_IngressBackend","signature":"func Convert_networking_IngressBackend_To_v1beta1_IngressBackend(in *networking.IngressBackend, out *v1beta1.IngressBackend, s conversion.Scope) error","file":"pkg/apis/networking/v1beta1/conversion.go","code":"func Convert_networking_IngressBackend_To_v1beta1_IngressBackend(in *networking.IngressBackend, out *v1beta1.IngressBackend, s conversion.Scope) error {\n\tif err := autoConvert_networking_IngressBackend_To_v1beta1_IngressBackend(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tif in.Service != nil {\n\t\tout.ServiceName = in.Service.Name\n\t\tif len(in.Service.Port.Name) \u003e 0 {\n\t\t\tout.ServicePort = intstr.FromString(in.Service.Port.Name)\n\t\t} else {\n\t\t\tout.ServicePort = intstr.FromInt(int(in.Service.Port.Number))\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":39,"to":52}} {"id":100002872,"name":"Convert_v1beta1_IngressSpec_To_networking_IngressSpec","signature":"func Convert_v1beta1_IngressSpec_To_networking_IngressSpec(in *v1beta1.IngressSpec, out *networking.IngressSpec, s conversion.Scope) error","file":"pkg/apis/networking/v1beta1/conversion.go","code":"func Convert_v1beta1_IngressSpec_To_networking_IngressSpec(in *v1beta1.IngressSpec, out *networking.IngressSpec, s conversion.Scope) error {\n\tif err := autoConvert_v1beta1_IngressSpec_To_networking_IngressSpec(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tif in.Backend != nil {\n\t\tout.DefaultBackend = \u0026networking.IngressBackend{}\n\t\tif err := Convert_v1beta1_IngressBackend_To_networking_IngressBackend(in.Backend, out.DefaultBackend, s); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":53,"to":64}} {"id":100002873,"name":"Convert_networking_IngressSpec_To_v1beta1_IngressSpec","signature":"func Convert_networking_IngressSpec_To_v1beta1_IngressSpec(in *networking.IngressSpec, out *v1beta1.IngressSpec, s conversion.Scope) error","file":"pkg/apis/networking/v1beta1/conversion.go","code":"func Convert_networking_IngressSpec_To_v1beta1_IngressSpec(in *networking.IngressSpec, out *v1beta1.IngressSpec, s conversion.Scope) error {\n\tif err := autoConvert_networking_IngressSpec_To_v1beta1_IngressSpec(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tif in.DefaultBackend != nil {\n\t\tout.Backend = \u0026v1beta1.IngressBackend{}\n\t\tif err := Convert_networking_IngressBackend_To_v1beta1_IngressBackend(in.DefaultBackend, out.Backend, s); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":66,"to":77}} {"id":100002874,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/networking/v1beta1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":24,"to":26}} {"id":100002875,"name":"SetDefaults_HTTPIngressPath","signature":"func SetDefaults_HTTPIngressPath(obj *networkingv1beta1.HTTPIngressPath)","file":"pkg/apis/networking/v1beta1/defaults.go","code":"func SetDefaults_HTTPIngressPath(obj *networkingv1beta1.HTTPIngressPath) {\n\tvar defaultPathType = networkingv1beta1.PathTypeImplementationSpecific\n\tif obj.PathType == nil {\n\t\tobj.PathType = \u0026defaultPathType\n\t}\n}","line":{"from":28,"to":33}} {"id":100002876,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/networking/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002877,"name":"init","signature":"func init()","file":"pkg/apis/networking/v1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":42,"to":47}} {"id":100002878,"name":"ValidateNetworkPolicyName","signature":"func ValidateNetworkPolicyName(name string, prefix bool) []string","file":"pkg/apis/networking/validation/validation.go","code":"// ValidateNetworkPolicyName can be used to check whether the given networkpolicy\n// name is valid.\nfunc ValidateNetworkPolicyName(name string, prefix bool) []string {\n\treturn apimachineryvalidation.NameIsDNSSubdomain(name, prefix)\n}","line":{"from":63,"to":67}} {"id":100002879,"name":"ValidateNetworkPolicyPort","signature":"func ValidateNetworkPolicyPort(port *networking.NetworkPolicyPort, portPath *field.Path) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"// ValidateNetworkPolicyPort validates a NetworkPolicyPort\nfunc ValidateNetworkPolicyPort(port *networking.NetworkPolicyPort, portPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif port.Protocol != nil \u0026\u0026 *port.Protocol != api.ProtocolTCP \u0026\u0026 *port.Protocol != api.ProtocolUDP \u0026\u0026 *port.Protocol != api.ProtocolSCTP {\n\t\tallErrs = append(allErrs, field.NotSupported(portPath.Child(\"protocol\"), *port.Protocol, []string{string(api.ProtocolTCP), string(api.ProtocolUDP), string(api.ProtocolSCTP)}))\n\t}\n\tif port.Port != nil {\n\t\tif port.Port.Type == intstr.Int {\n\t\t\tfor _, msg := range validation.IsValidPortNum(int(port.Port.IntVal)) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(portPath.Child(\"port\"), port.Port.IntVal, msg))\n\t\t\t}\n\t\t\tif port.EndPort != nil {\n\t\t\t\tif *port.EndPort \u003c port.Port.IntVal {\n\t\t\t\t\tallErrs = append(allErrs, field.Invalid(portPath.Child(\"endPort\"), port.Port.IntVal, \"must be greater than or equal to `port`\"))\n\t\t\t\t}\n\t\t\t\tfor _, msg := range validation.IsValidPortNum(int(*port.EndPort)) {\n\t\t\t\t\tallErrs = append(allErrs, field.Invalid(portPath.Child(\"endPort\"), *port.EndPort, msg))\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif port.EndPort != nil {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(portPath.Child(\"endPort\"), *port.EndPort, \"may not be specified when `port` is non-numeric\"))\n\t\t\t}\n\t\t\tfor _, msg := range validation.IsValidPortName(port.Port.StrVal) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(portPath.Child(\"port\"), port.Port.StrVal, msg))\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif port.EndPort != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(portPath.Child(\"endPort\"), *port.EndPort, \"may not be specified when `port` is not specified\"))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":69,"to":103}} {"id":100002880,"name":"ValidateNetworkPolicyPeer","signature":"func ValidateNetworkPolicyPeer(peer *networking.NetworkPolicyPeer, opts NetworkPolicyValidationOptions, peerPath *field.Path) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"// ValidateNetworkPolicyPeer validates a NetworkPolicyPeer\nfunc ValidateNetworkPolicyPeer(peer *networking.NetworkPolicyPeer, opts NetworkPolicyValidationOptions, peerPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tnumPeers := 0\n\tlabelSelectorValidationOpts := unversionedvalidation.LabelSelectorValidationOptions{\n\t\tAllowInvalidLabelValueInSelector: opts.AllowInvalidLabelValueInSelector,\n\t}\n\n\tif peer.PodSelector != nil {\n\t\tnumPeers++\n\t\tallErrs = append(allErrs, unversionedvalidation.ValidateLabelSelector(peer.PodSelector, labelSelectorValidationOpts, peerPath.Child(\"podSelector\"))...)\n\t}\n\tif peer.NamespaceSelector != nil {\n\t\tnumPeers++\n\t\tallErrs = append(allErrs, unversionedvalidation.ValidateLabelSelector(peer.NamespaceSelector, labelSelectorValidationOpts, peerPath.Child(\"namespaceSelector\"))...)\n\t}\n\tif peer.IPBlock != nil {\n\t\tnumPeers++\n\t\tallErrs = append(allErrs, ValidateIPBlock(peer.IPBlock, peerPath.Child(\"ipBlock\"))...)\n\t}\n\n\tif numPeers == 0 {\n\t\tallErrs = append(allErrs, field.Required(peerPath, \"must specify a peer\"))\n\t} else if numPeers \u003e 1 \u0026\u0026 peer.IPBlock != nil {\n\t\tallErrs = append(allErrs, field.Forbidden(peerPath, \"may not specify both ipBlock and another peer\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":105,"to":133}} {"id":100002881,"name":"ValidateNetworkPolicySpec","signature":"func ValidateNetworkPolicySpec(spec *networking.NetworkPolicySpec, opts NetworkPolicyValidationOptions, fldPath *field.Path) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"// ValidateNetworkPolicySpec tests if required fields in the networkpolicy spec are set.\nfunc ValidateNetworkPolicySpec(spec *networking.NetworkPolicySpec, opts NetworkPolicyValidationOptions, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tlabelSelectorValidationOpts := unversionedvalidation.LabelSelectorValidationOptions{\n\t\tAllowInvalidLabelValueInSelector: opts.AllowInvalidLabelValueInSelector,\n\t}\n\tallErrs = append(allErrs, unversionedvalidation.ValidateLabelSelector(\n\t\t\u0026spec.PodSelector,\n\t\tlabelSelectorValidationOpts,\n\t\tfldPath.Child(\"podSelector\"),\n\t)...)\n\n\t// Validate ingress rules.\n\tfor i, ingress := range spec.Ingress {\n\t\tingressPath := fldPath.Child(\"ingress\").Index(i)\n\t\tfor i, port := range ingress.Ports {\n\t\t\tportPath := ingressPath.Child(\"ports\").Index(i)\n\t\t\tallErrs = append(allErrs, ValidateNetworkPolicyPort(\u0026port, portPath)...)\n\t\t}\n\t\tfor i, from := range ingress.From {\n\t\t\tfromPath := ingressPath.Child(\"from\").Index(i)\n\t\t\tallErrs = append(allErrs, ValidateNetworkPolicyPeer(\u0026from, opts, fromPath)...)\n\t\t}\n\t}\n\t// Validate egress rules\n\tfor i, egress := range spec.Egress {\n\t\tegressPath := fldPath.Child(\"egress\").Index(i)\n\t\tfor i, port := range egress.Ports {\n\t\t\tportPath := egressPath.Child(\"ports\").Index(i)\n\t\t\tallErrs = append(allErrs, ValidateNetworkPolicyPort(\u0026port, portPath)...)\n\t\t}\n\t\tfor i, to := range egress.To {\n\t\t\ttoPath := egressPath.Child(\"to\").Index(i)\n\t\t\tallErrs = append(allErrs, ValidateNetworkPolicyPeer(\u0026to, opts, toPath)...)\n\t\t}\n\t}\n\t// Validate PolicyTypes\n\tallowed := sets.NewString(string(networking.PolicyTypeIngress), string(networking.PolicyTypeEgress))\n\tif len(spec.PolicyTypes) \u003e len(allowed) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"policyTypes\"), \u0026spec.PolicyTypes, \"may not specify more than two policyTypes\"))\n\t\treturn allErrs\n\t}\n\tfor i, pType := range spec.PolicyTypes {\n\t\tpolicyPath := fldPath.Child(\"policyTypes\").Index(i)\n\t\tif !allowed.Has(string(pType)) {\n\t\t\tallErrs = append(allErrs, field.NotSupported(policyPath, pType, []string{string(networking.PolicyTypeIngress), string(networking.PolicyTypeEgress)}))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":135,"to":184}} {"id":100002882,"name":"ValidateNetworkPolicy","signature":"func ValidateNetworkPolicy(np *networking.NetworkPolicy, opts NetworkPolicyValidationOptions) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"// ValidateNetworkPolicy validates a networkpolicy.\nfunc ValidateNetworkPolicy(np *networking.NetworkPolicy, opts NetworkPolicyValidationOptions) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMeta(\u0026np.ObjectMeta, true, ValidateNetworkPolicyName, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateNetworkPolicySpec(\u0026np.Spec, opts, field.NewPath(\"spec\"))...)\n\treturn allErrs\n}","line":{"from":186,"to":191}} {"id":100002883,"name":"ValidationOptionsForNetworking","signature":"func ValidationOptionsForNetworking(new, old *networking.NetworkPolicy) NetworkPolicyValidationOptions","file":"pkg/apis/networking/validation/validation.go","code":"// ValidationOptionsForNetworking generates NetworkPolicyValidationOptions for Networking\nfunc ValidationOptionsForNetworking(new, old *networking.NetworkPolicy) NetworkPolicyValidationOptions {\n\topts := NetworkPolicyValidationOptions{\n\t\tAllowInvalidLabelValueInSelector: false,\n\t}\n\tif old != nil {\n\t\tlabelSelectorValidationOpts := unversionedvalidation.LabelSelectorValidationOptions{\n\t\t\tAllowInvalidLabelValueInSelector: opts.AllowInvalidLabelValueInSelector,\n\t\t}\n\t\tif len(unversionedvalidation.ValidateLabelSelector(\u0026old.Spec.PodSelector, labelSelectorValidationOpts, nil)) \u003e 0 {\n\t\t\topts.AllowInvalidLabelValueInSelector = true\n\t\t}\n\t}\n\treturn opts\n}","line":{"from":193,"to":207}} {"id":100002884,"name":"ValidateNetworkPolicyUpdate","signature":"func ValidateNetworkPolicyUpdate(update, old *networking.NetworkPolicy, opts NetworkPolicyValidationOptions) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"// ValidateNetworkPolicyUpdate tests if an update to a NetworkPolicy is valid.\nfunc ValidateNetworkPolicyUpdate(update, old *networking.NetworkPolicy, opts NetworkPolicyValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, apivalidation.ValidateObjectMetaUpdate(\u0026update.ObjectMeta, \u0026old.ObjectMeta, field.NewPath(\"metadata\"))...)\n\tallErrs = append(allErrs, ValidateNetworkPolicySpec(\u0026update.Spec, opts, field.NewPath(\"spec\"))...)\n\treturn allErrs\n}","line":{"from":209,"to":215}} {"id":100002885,"name":"ValidateNetworkPolicyStatusUpdate","signature":"func ValidateNetworkPolicyStatusUpdate(status, oldstatus networking.NetworkPolicyStatus, fldPath *field.Path) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"// ValidateNetworkPolicyStatusUpdate tests if an update to a NetworkPolicy status is valid\nfunc ValidateNetworkPolicyStatusUpdate(status, oldstatus networking.NetworkPolicyStatus, fldPath *field.Path) field.ErrorList {\n\treturn unversionedvalidation.ValidateConditions(status.Conditions, fldPath.Child(\"conditions\"))\n}","line":{"from":217,"to":220}} {"id":100002886,"name":"ValidateIPBlock","signature":"func ValidateIPBlock(ipb *networking.IPBlock, fldPath *field.Path) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"// ValidateIPBlock validates a cidr and the except fields of an IpBlock NetworkPolicyPeer\nfunc ValidateIPBlock(ipb *networking.IPBlock, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(ipb.CIDR) == 0 || ipb.CIDR == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"cidr\"), \"\"))\n\t\treturn allErrs\n\t}\n\tcidrIPNet, err := apivalidation.ValidateCIDR(ipb.CIDR)\n\tif err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"cidr\"), ipb.CIDR, \"not a valid CIDR\"))\n\t\treturn allErrs\n\t}\n\texceptCIDR := ipb.Except\n\tfor i, exceptIP := range exceptCIDR {\n\t\texceptPath := fldPath.Child(\"except\").Index(i)\n\t\texceptCIDR, err := apivalidation.ValidateCIDR(exceptIP)\n\t\tif err != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(exceptPath, exceptIP, \"not a valid CIDR\"))\n\t\t\treturn allErrs\n\t\t}\n\t\tcidrMaskLen, _ := cidrIPNet.Mask.Size()\n\t\texceptMaskLen, _ := exceptCIDR.Mask.Size()\n\t\tif !cidrIPNet.Contains(exceptCIDR.IP) || cidrMaskLen \u003e= exceptMaskLen {\n\t\t\tallErrs = append(allErrs, field.Invalid(exceptPath, exceptIP, \"must be a strict subset of `cidr`\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":222,"to":249}} {"id":100002887,"name":"validateIngress","signature":"func validateIngress(ingress *networking.Ingress, opts IngressValidationOptions) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"// ValidateIngress validates Ingresses on create and update.\nfunc validateIngress(ingress *networking.Ingress, opts IngressValidationOptions) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMeta(\u0026ingress.ObjectMeta, true, ValidateIngressName, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateIngressSpec(\u0026ingress.Spec, field.NewPath(\"spec\"), opts)...)\n\treturn allErrs\n}","line":{"from":264,"to":269}} {"id":100002888,"name":"ValidateIngressCreate","signature":"func ValidateIngressCreate(ingress *networking.Ingress) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"// ValidateIngressCreate validates Ingresses on create.\nfunc ValidateIngressCreate(ingress *networking.Ingress) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\topts := IngressValidationOptions{\n\t\tAllowInvalidSecretName: false,\n\t\tAllowInvalidWildcardHostRule: false,\n\t}\n\tallErrs = append(allErrs, validateIngress(ingress, opts)...)\n\tannotationVal, annotationIsSet := ingress.Annotations[annotationIngressClass]\n\tif annotationIsSet \u0026\u0026 ingress.Spec.IngressClassName != nil \u0026\u0026 annotationVal != *ingress.Spec.IngressClassName {\n\t\tannotationPath := field.NewPath(\"annotations\").Child(annotationIngressClass)\n\t\tallErrs = append(allErrs, field.Invalid(annotationPath, annotationVal, \"must match `ingressClassName` when both are specified\"))\n\t}\n\treturn allErrs\n}","line":{"from":271,"to":285}} {"id":100002889,"name":"ValidateIngressUpdate","signature":"func ValidateIngressUpdate(ingress, oldIngress *networking.Ingress) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"// ValidateIngressUpdate validates ingresses on update.\nfunc ValidateIngressUpdate(ingress, oldIngress *networking.Ingress) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMetaUpdate(\u0026ingress.ObjectMeta, \u0026oldIngress.ObjectMeta, field.NewPath(\"metadata\"))\n\topts := IngressValidationOptions{\n\t\tAllowInvalidSecretName: allowInvalidSecretName(oldIngress),\n\t\tAllowInvalidWildcardHostRule: allowInvalidWildcardHostRule(oldIngress),\n\t}\n\n\tallErrs = append(allErrs, validateIngress(ingress, opts)...)\n\treturn allErrs\n}","line":{"from":287,"to":297}} {"id":100002890,"name":"validateIngressTLS","signature":"func validateIngressTLS(spec *networking.IngressSpec, fldPath *field.Path, opts IngressValidationOptions) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"func validateIngressTLS(spec *networking.IngressSpec, fldPath *field.Path, opts IngressValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\t// TODO: Perform a more thorough validation of spec.TLS.Hosts that takes\n\t// the wildcard spec from RFC 6125 into account.\n\tfor tlsIndex, itls := range spec.TLS {\n\t\tfor i, host := range itls.Hosts {\n\t\t\tif strings.Contains(host, \"*\") {\n\t\t\t\tfor _, msg := range validation.IsWildcardDNS1123Subdomain(host) {\n\t\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Index(tlsIndex).Child(\"hosts\").Index(i), host, msg))\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor _, msg := range validation.IsDNS1123Subdomain(host) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Index(tlsIndex).Child(\"hosts\").Index(i), host, msg))\n\t\t\t}\n\t\t}\n\n\t\tif !opts.AllowInvalidSecretName {\n\t\t\tfor _, msg := range validateTLSSecretName(itls.SecretName) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Index(tlsIndex).Child(\"secretName\"), itls.SecretName, msg))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":299,"to":324}} {"id":100002891,"name":"ValidateIngressSpec","signature":"func ValidateIngressSpec(spec *networking.IngressSpec, fldPath *field.Path, opts IngressValidationOptions) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"// ValidateIngressSpec tests if required fields in the IngressSpec are set.\nfunc ValidateIngressSpec(spec *networking.IngressSpec, fldPath *field.Path, opts IngressValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(spec.Rules) == 0 \u0026\u0026 spec.DefaultBackend == nil {\n\t\terrMsg := fmt.Sprintf(\"either `%s` or `rules` must be specified\", \"defaultBackend\")\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, spec.Rules, errMsg))\n\t}\n\tif spec.DefaultBackend != nil {\n\t\tallErrs = append(allErrs, validateIngressBackend(spec.DefaultBackend, fldPath.Child(\"defaultBackend\"), opts)...)\n\t}\n\tif len(spec.Rules) \u003e 0 {\n\t\tallErrs = append(allErrs, validateIngressRules(spec.Rules, fldPath.Child(\"rules\"), opts)...)\n\t}\n\tif len(spec.TLS) \u003e 0 {\n\t\tallErrs = append(allErrs, validateIngressTLS(spec, fldPath.Child(\"tls\"), opts)...)\n\t}\n\tif spec.IngressClassName != nil {\n\t\tfor _, msg := range ValidateIngressClassName(*spec.IngressClassName, false) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"ingressClassName\"), *spec.IngressClassName, msg))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":326,"to":348}} {"id":100002892,"name":"ValidateIngressStatusUpdate","signature":"func ValidateIngressStatusUpdate(ingress, oldIngress *networking.Ingress) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"// ValidateIngressStatusUpdate tests if required fields in the Ingress are set when updating status.\nfunc ValidateIngressStatusUpdate(ingress, oldIngress *networking.Ingress) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMetaUpdate(\u0026ingress.ObjectMeta, \u0026oldIngress.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateIngressLoadBalancerStatus(\u0026ingress.Status.LoadBalancer, field.NewPath(\"status\", \"loadBalancer\"))...)\n\treturn allErrs\n}","line":{"from":350,"to":355}} {"id":100002893,"name":"ValidateIngressLoadBalancerStatus","signature":"func ValidateIngressLoadBalancerStatus(status *networking.IngressLoadBalancerStatus, fldPath *field.Path) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"// ValidateLIngressoadBalancerStatus validates required fields on an IngressLoadBalancerStatus\nfunc ValidateIngressLoadBalancerStatus(status *networking.IngressLoadBalancerStatus, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor i, ingress := range status.Ingress {\n\t\tidxPath := fldPath.Child(\"ingress\").Index(i)\n\t\tif len(ingress.IP) \u003e 0 {\n\t\t\tif isIP := (netutils.ParseIPSloppy(ingress.IP) != nil); !isIP {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"ip\"), ingress.IP, \"must be a valid IP address\"))\n\t\t\t}\n\t\t}\n\t\tif len(ingress.Hostname) \u003e 0 {\n\t\t\tfor _, msg := range validation.IsDNS1123Subdomain(ingress.Hostname) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"hostname\"), ingress.Hostname, msg))\n\t\t\t}\n\t\t\tif isIP := (netutils.ParseIPSloppy(ingress.Hostname) != nil); isIP {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"hostname\"), ingress.Hostname, \"must be a DNS name, not an IP address\"))\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":357,"to":377}} {"id":100002894,"name":"validateIngressRules","signature":"func validateIngressRules(ingressRules []networking.IngressRule, fldPath *field.Path, opts IngressValidationOptions) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"func validateIngressRules(ingressRules []networking.IngressRule, fldPath *field.Path, opts IngressValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(ingressRules) == 0 {\n\t\treturn append(allErrs, field.Required(fldPath, \"\"))\n\t}\n\tfor i, ih := range ingressRules {\n\t\twildcardHost := false\n\t\tif len(ih.Host) \u003e 0 {\n\t\t\tif isIP := (netutils.ParseIPSloppy(ih.Host) != nil); isIP {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Index(i).Child(\"host\"), ih.Host, \"must be a DNS name, not an IP address\"))\n\t\t\t}\n\t\t\t// TODO: Ports and ips are allowed in the host part of a url\n\t\t\t// according to RFC 3986, consider allowing them.\n\t\t\tif strings.Contains(ih.Host, \"*\") {\n\t\t\t\tfor _, msg := range validation.IsWildcardDNS1123Subdomain(ih.Host) {\n\t\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Index(i).Child(\"host\"), ih.Host, msg))\n\t\t\t\t}\n\t\t\t\twildcardHost = true\n\t\t\t} else {\n\t\t\t\tfor _, msg := range validation.IsDNS1123Subdomain(ih.Host) {\n\t\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Index(i).Child(\"host\"), ih.Host, msg))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif !wildcardHost || !opts.AllowInvalidWildcardHostRule {\n\t\t\tallErrs = append(allErrs, validateIngressRuleValue(\u0026ih.IngressRuleValue, fldPath.Index(i), opts)...)\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":379,"to":409}} {"id":100002895,"name":"validateIngressRuleValue","signature":"func validateIngressRuleValue(ingressRule *networking.IngressRuleValue, fldPath *field.Path, opts IngressValidationOptions) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"func validateIngressRuleValue(ingressRule *networking.IngressRuleValue, fldPath *field.Path, opts IngressValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif ingressRule.HTTP != nil {\n\t\tallErrs = append(allErrs, validateHTTPIngressRuleValue(ingressRule.HTTP, fldPath.Child(\"http\"), opts)...)\n\t}\n\treturn allErrs\n}","line":{"from":411,"to":417}} {"id":100002896,"name":"validateHTTPIngressRuleValue","signature":"func validateHTTPIngressRuleValue(httpIngressRuleValue *networking.HTTPIngressRuleValue, fldPath *field.Path, opts IngressValidationOptions) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"func validateHTTPIngressRuleValue(httpIngressRuleValue *networking.HTTPIngressRuleValue, fldPath *field.Path, opts IngressValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(httpIngressRuleValue.Paths) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"paths\"), \"\"))\n\t}\n\tfor i, path := range httpIngressRuleValue.Paths {\n\t\tallErrs = append(allErrs, validateHTTPIngressPath(\u0026path, fldPath.Child(\"paths\").Index(i), opts)...)\n\t}\n\treturn allErrs\n}","line":{"from":419,"to":428}} {"id":100002897,"name":"validateHTTPIngressPath","signature":"func validateHTTPIngressPath(path *networking.HTTPIngressPath, fldPath *field.Path, opts IngressValidationOptions) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"func validateHTTPIngressPath(path *networking.HTTPIngressPath, fldPath *field.Path, opts IngressValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif path.PathType == nil {\n\t\treturn append(allErrs, field.Required(fldPath.Child(\"pathType\"), \"pathType must be specified\"))\n\t}\n\n\tswitch *path.PathType {\n\tcase networking.PathTypeExact, networking.PathTypePrefix:\n\t\tif !strings.HasPrefix(path.Path, \"/\") {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"path\"), path.Path, \"must be an absolute path\"))\n\t\t}\n\t\tif len(path.Path) \u003e 0 {\n\t\t\tfor _, invalidSeq := range invalidPathSequences {\n\t\t\t\tif strings.Contains(path.Path, invalidSeq) {\n\t\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"path\"), path.Path, fmt.Sprintf(\"must not contain '%s'\", invalidSeq)))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor _, invalidSuff := range invalidPathSuffixes {\n\t\t\t\tif strings.HasSuffix(path.Path, invalidSuff) {\n\t\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"path\"), path.Path, fmt.Sprintf(\"cannot end with '%s'\", invalidSuff)))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase networking.PathTypeImplementationSpecific:\n\t\tif len(path.Path) \u003e 0 {\n\t\t\tif !strings.HasPrefix(path.Path, \"/\") {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"path\"), path.Path, \"must be an absolute path\"))\n\t\t\t}\n\t\t}\n\tdefault:\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"pathType\"), *path.PathType, supportedPathTypes.List()))\n\t}\n\tallErrs = append(allErrs, validateIngressBackend(\u0026path.Backend, fldPath.Child(\"backend\"), opts)...)\n\treturn allErrs\n}","line":{"from":430,"to":466}} {"id":100002898,"name":"validateIngressBackend","signature":"func validateIngressBackend(backend *networking.IngressBackend, fldPath *field.Path, opts IngressValidationOptions) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"// validateIngressBackend tests if a given backend is valid.\nfunc validateIngressBackend(backend *networking.IngressBackend, fldPath *field.Path, opts IngressValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\thasResourceBackend := backend.Resource != nil\n\thasServiceBackend := backend.Service != nil\n\n\tswitch {\n\tcase hasResourceBackend \u0026\u0026 hasServiceBackend:\n\t\treturn append(allErrs, field.Invalid(fldPath, \"\", \"cannot set both resource and service backends\"))\n\tcase hasResourceBackend:\n\t\tallErrs = append(allErrs, validateIngressTypedLocalObjectReference(backend.Resource, fldPath.Child(\"resource\"))...)\n\tcase hasServiceBackend:\n\n\t\tif len(backend.Service.Name) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"service\", \"name\"), \"\"))\n\t\t} else {\n\t\t\tfor _, msg := range apivalidation.ValidateServiceName(backend.Service.Name, false) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"service\", \"name\"), backend.Service.Name, msg))\n\t\t\t}\n\t\t}\n\n\t\thasPortName := len(backend.Service.Port.Name) \u003e 0\n\t\thasPortNumber := backend.Service.Port.Number != 0\n\t\tif hasPortName \u0026\u0026 hasPortNumber {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, \"\", \"cannot set both port name \u0026 port number\"))\n\t\t} else if hasPortName {\n\t\t\tfor _, msg := range validation.IsValidPortName(backend.Service.Port.Name) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"service\", \"port\", \"name\"), backend.Service.Port.Name, msg))\n\t\t\t}\n\t\t} else if hasPortNumber {\n\t\t\tfor _, msg := range validation.IsValidPortNum(int(backend.Service.Port.Number)) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"service\", \"port\", \"number\"), backend.Service.Port.Number, msg))\n\t\t\t}\n\t\t} else {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath, \"port name or number is required\"))\n\t\t}\n\tdefault:\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, \"\", \"resource or service backend is required\"))\n\t}\n\treturn allErrs\n}","line":{"from":468,"to":509}} {"id":100002899,"name":"ValidateIngressClass","signature":"func ValidateIngressClass(ingressClass *networking.IngressClass) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"// ValidateIngressClass ensures that IngressClass resources are valid.\nfunc ValidateIngressClass(ingressClass *networking.IngressClass) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMeta(\u0026ingressClass.ObjectMeta, false, ValidateIngressClassName, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, validateIngressClassSpec(\u0026ingressClass.Spec, field.NewPath(\"spec\"))...)\n\treturn allErrs\n}","line":{"from":515,"to":520}} {"id":100002900,"name":"ValidateIngressClassUpdate","signature":"func ValidateIngressClassUpdate(newIngressClass, oldIngressClass *networking.IngressClass) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"// ValidateIngressClassUpdate ensures that IngressClass updates are valid.\nfunc ValidateIngressClassUpdate(newIngressClass, oldIngressClass *networking.IngressClass) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMetaUpdate(\u0026newIngressClass.ObjectMeta, \u0026oldIngressClass.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, validateIngressClassSpecUpdate(\u0026newIngressClass.Spec, \u0026oldIngressClass.Spec, field.NewPath(\"spec\"))...)\n\tallErrs = append(allErrs, ValidateIngressClass(newIngressClass)...)\n\treturn allErrs\n}","line":{"from":522,"to":528}} {"id":100002901,"name":"validateIngressClassSpec","signature":"func validateIngressClassSpec(spec *networking.IngressClassSpec, fldPath *field.Path) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"// validateIngressClassSpec ensures that IngressClassSpec fields are valid.\nfunc validateIngressClassSpec(spec *networking.IngressClassSpec, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(spec.Controller) \u003e maxLenIngressClassController {\n\t\tallErrs = append(allErrs, field.TooLong(fldPath.Child(\"controller\"), spec.Controller, maxLenIngressClassController))\n\t}\n\tallErrs = append(allErrs, validation.IsDomainPrefixedPath(fldPath.Child(\"controller\"), spec.Controller)...)\n\tallErrs = append(allErrs, validateIngressClassParametersReference(spec.Parameters, fldPath.Child(\"parameters\"))...)\n\treturn allErrs\n}","line":{"from":530,"to":539}} {"id":100002902,"name":"validateIngressClassSpecUpdate","signature":"func validateIngressClassSpecUpdate(newSpec, oldSpec *networking.IngressClassSpec, fldPath *field.Path) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"// validateIngressClassSpecUpdate ensures that IngressClassSpec updates are\n// valid.\nfunc validateIngressClassSpecUpdate(newSpec, oldSpec *networking.IngressClassSpec, fldPath *field.Path) field.ErrorList {\n\treturn apivalidation.ValidateImmutableField(newSpec.Controller, oldSpec.Controller, fldPath.Child(\"controller\"))\n}","line":{"from":541,"to":545}} {"id":100002903,"name":"validateIngressTypedLocalObjectReference","signature":"func validateIngressTypedLocalObjectReference(params *api.TypedLocalObjectReference, fldPath *field.Path) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"// validateIngressTypedLocalObjectReference ensures that Parameters fields are valid.\nfunc validateIngressTypedLocalObjectReference(params *api.TypedLocalObjectReference, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif params == nil {\n\t\treturn allErrs\n\t}\n\n\tif params.APIGroup != nil {\n\t\tfor _, msg := range validation.IsDNS1123Subdomain(*params.APIGroup) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"apiGroup\"), *params.APIGroup, msg))\n\t\t}\n\t}\n\n\tif params.Kind == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"kind\"), \"kind is required\"))\n\t} else {\n\t\tfor _, msg := range pathvalidation.IsValidPathSegmentName(params.Kind) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"kind\"), params.Kind, msg))\n\t\t}\n\t}\n\n\tif params.Name == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"name\"), \"name is required\"))\n\t} else {\n\t\tfor _, msg := range pathvalidation.IsValidPathSegmentName(params.Name) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"name\"), params.Name, msg))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":547,"to":578}} {"id":100002904,"name":"validateIngressClassParametersReference","signature":"func validateIngressClassParametersReference(params *networking.IngressClassParametersReference, fldPath *field.Path) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"// validateIngressClassParametersReference ensures that Parameters fields are valid.\n// Parameters was previously of type `TypedLocalObjectReference` and used\n// `validateIngressTypedLocalObjectReference()`. This function extends validation\n// for additional fields introduced for namespace-scoped references.\nfunc validateIngressClassParametersReference(params *networking.IngressClassParametersReference, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif params == nil {\n\t\treturn allErrs\n\t}\n\n\tallErrs = append(allErrs, validateIngressTypedLocalObjectReference(\u0026api.TypedLocalObjectReference{\n\t\tAPIGroup: params.APIGroup,\n\t\tKind: params.Kind,\n\t\tName: params.Name,\n\t}, fldPath)...)\n\n\tif params.Scope == nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"scope\"), \"\"))\n\t\treturn allErrs\n\t}\n\n\tif params.Scope != nil || params.Namespace != nil {\n\t\tscope := utilpointer.StringDeref(params.Scope, \"\")\n\n\t\tif !supportedIngressClassParametersReferenceScopes.Has(scope) {\n\t\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"scope\"), scope,\n\t\t\t\tsupportedIngressClassParametersReferenceScopes.List()))\n\t\t} else {\n\n\t\t\tif scope == networking.IngressClassParametersReferenceScopeNamespace {\n\t\t\t\tif params.Namespace == nil {\n\t\t\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"namespace\"), \"`parameters.scope` is set to 'Namespace'\"))\n\t\t\t\t} else {\n\t\t\t\t\tfor _, msg := range apivalidation.ValidateNamespaceName(*params.Namespace, false) {\n\t\t\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"namespace\"), *params.Namespace, msg))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif scope == networking.IngressClassParametersReferenceScopeCluster \u0026\u0026 params.Namespace != nil {\n\t\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"namespace\"), \"`parameters.scope` is set to 'Cluster'\"))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":580,"to":627}} {"id":100002905,"name":"allowInvalidSecretName","signature":"func allowInvalidSecretName(oldIngress *networking.Ingress) bool","file":"pkg/apis/networking/validation/validation.go","code":"func allowInvalidSecretName(oldIngress *networking.Ingress) bool {\n\tif oldIngress != nil {\n\t\tfor _, tls := range oldIngress.Spec.TLS {\n\t\t\tif len(validateTLSSecretName(tls.SecretName)) \u003e 0 {\n\t\t\t\t// backwards compatibility with existing persisted object\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":629,"to":639}} {"id":100002906,"name":"validateTLSSecretName","signature":"func validateTLSSecretName(name string) []string","file":"pkg/apis/networking/validation/validation.go","code":"func validateTLSSecretName(name string) []string {\n\tif len(name) == 0 {\n\t\treturn nil\n\t}\n\treturn apivalidation.ValidateSecretName(name, false)\n}","line":{"from":641,"to":646}} {"id":100002907,"name":"allowInvalidWildcardHostRule","signature":"func allowInvalidWildcardHostRule(oldIngress *networking.Ingress) bool","file":"pkg/apis/networking/validation/validation.go","code":"func allowInvalidWildcardHostRule(oldIngress *networking.Ingress) bool {\n\tif oldIngress != nil {\n\t\tfor _, rule := range oldIngress.Spec.Rules {\n\t\t\tif strings.Contains(rule.Host, \"*\") \u0026\u0026 len(validateIngressRuleValue(\u0026rule.IngressRuleValue, nil, IngressValidationOptions{})) \u003e 0 {\n\t\t\t\t// backwards compatibility with existing invalid data\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":648,"to":658}} {"id":100002908,"name":"ValidateClusterCIDR","signature":"func ValidateClusterCIDR(cc *networking.ClusterCIDR) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"// ValidateClusterCIDR validates a ClusterCIDR.\nfunc ValidateClusterCIDR(cc *networking.ClusterCIDR) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMeta(\u0026cc.ObjectMeta, false, ValidateClusterCIDRName, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateClusterCIDRSpec(\u0026cc.Spec, field.NewPath(\"spec\"))...)\n\treturn allErrs\n}","line":{"from":664,"to":669}} {"id":100002909,"name":"ValidateClusterCIDRSpec","signature":"func ValidateClusterCIDRSpec(spec *networking.ClusterCIDRSpec, fldPath *field.Path) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"// ValidateClusterCIDRSpec validates ClusterCIDR Spec.\nfunc ValidateClusterCIDRSpec(spec *networking.ClusterCIDRSpec, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tif spec.NodeSelector != nil {\n\t\tallErrs = append(allErrs, apivalidation.ValidateNodeSelector(spec.NodeSelector, fldPath.Child(\"nodeSelector\"))...)\n\t}\n\n\t// Validate if CIDR is specified for at least one IP Family(IPv4/IPv6).\n\tif spec.IPv4 == \"\" \u0026\u0026 spec.IPv6 == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath, \"one or both of `ipv4` and `ipv6` must be specified\"))\n\t\treturn allErrs\n\t}\n\n\t// Validate specified IPv4 CIDR and PerNodeHostBits.\n\tif spec.IPv4 != \"\" {\n\t\tallErrs = append(allErrs, validateCIDRConfig(spec.IPv4, spec.PerNodeHostBits, 32, v1.IPv4Protocol, fldPath)...)\n\t}\n\n\t// Validate specified IPv6 CIDR and PerNodeHostBits.\n\tif spec.IPv6 != \"\" {\n\t\tallErrs = append(allErrs, validateCIDRConfig(spec.IPv6, spec.PerNodeHostBits, 128, v1.IPv6Protocol, fldPath)...)\n\t}\n\n\treturn allErrs\n}","line":{"from":671,"to":695}} {"id":100002910,"name":"validateCIDRConfig","signature":"func validateCIDRConfig(configCIDR string, perNodeHostBits, maxMaskSize int32, ipFamily v1.IPFamily, fldPath *field.Path) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"func validateCIDRConfig(configCIDR string, perNodeHostBits, maxMaskSize int32, ipFamily v1.IPFamily, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tminPerNodeHostBits := int32(4)\n\n\tip, ipNet, err := netutils.ParseCIDRSloppy(configCIDR)\n\tif err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(string(ipFamily)), configCIDR, fmt.Sprintf(\"must be a valid CIDR: %s\", configCIDR)))\n\t\treturn allErrs\n\t}\n\n\tif ipFamily == v1.IPv4Protocol \u0026\u0026 !netutils.IsIPv4(ip) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(string(ipFamily)), configCIDR, \"must be a valid IPv4 CIDR\"))\n\t}\n\tif ipFamily == v1.IPv6Protocol \u0026\u0026 !netutils.IsIPv6(ip) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(string(ipFamily)), configCIDR, \"must be a valid IPv6 CIDR\"))\n\t}\n\n\t// Validate PerNodeHostBits\n\tmaskSize, _ := ipNet.Mask.Size()\n\tmaxPerNodeHostBits := maxMaskSize - int32(maskSize)\n\n\tif perNodeHostBits \u003c minPerNodeHostBits {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"perNodeHostBits\"), perNodeHostBits, fmt.Sprintf(\"must be greater than or equal to %d\", minPerNodeHostBits)))\n\t}\n\tif perNodeHostBits \u003e maxPerNodeHostBits {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"perNodeHostBits\"), perNodeHostBits, fmt.Sprintf(\"must be less than or equal to %d\", maxPerNodeHostBits)))\n\t}\n\treturn allErrs\n}","line":{"from":697,"to":725}} {"id":100002911,"name":"ValidateClusterCIDRUpdate","signature":"func ValidateClusterCIDRUpdate(update, old *networking.ClusterCIDR) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"// ValidateClusterCIDRUpdate tests if an update to a ClusterCIDR is valid.\nfunc ValidateClusterCIDRUpdate(update, old *networking.ClusterCIDR) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tallErrs = append(allErrs, apivalidation.ValidateObjectMetaUpdate(\u0026update.ObjectMeta, \u0026old.ObjectMeta, field.NewPath(\"metadata\"))...)\n\tallErrs = append(allErrs, validateClusterCIDRUpdateSpec(\u0026update.Spec, \u0026old.Spec, field.NewPath(\"spec\"))...)\n\treturn allErrs\n}","line":{"from":727,"to":733}} {"id":100002912,"name":"validateClusterCIDRUpdateSpec","signature":"func validateClusterCIDRUpdateSpec(update, old *networking.ClusterCIDRSpec, fldPath *field.Path) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"func validateClusterCIDRUpdateSpec(update, old *networking.ClusterCIDRSpec, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\n\tallErrs = append(allErrs, apivalidation.ValidateImmutableField(update.NodeSelector, old.NodeSelector, fldPath.Child(\"nodeSelector\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateImmutableField(update.PerNodeHostBits, old.PerNodeHostBits, fldPath.Child(\"perNodeHostBits\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateImmutableField(update.IPv4, old.IPv4, fldPath.Child(\"ipv4\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateImmutableField(update.IPv6, old.IPv6, fldPath.Child(\"ipv6\"))...)\n\n\treturn allErrs\n}","line":{"from":735,"to":744}} {"id":100002913,"name":"ValidateIPAddressName","signature":"func ValidateIPAddressName(name string, prefix bool) []string","file":"pkg/apis/networking/validation/validation.go","code":"// ValidateIPAddressName validates that the name is the decimal representation of an IP address.\n// IPAddress does not support generating names, prefix is not considered.\nfunc ValidateIPAddressName(name string, prefix bool) []string {\n\tvar errs []string\n\tip, err := netip.ParseAddr(name)\n\tif err != nil {\n\t\terrs = append(errs, err.Error())\n\t} else if ip.String() != name {\n\t\terrs = append(errs, \"not a valid ip in canonical format\")\n\n\t}\n\treturn errs\n}","line":{"from":746,"to":758}} {"id":100002914,"name":"ValidateIPAddress","signature":"func ValidateIPAddress(ipAddress *networking.IPAddress) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"func ValidateIPAddress(ipAddress *networking.IPAddress) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMeta(\u0026ipAddress.ObjectMeta, false, ValidateIPAddressName, field.NewPath(\"metadata\"))\n\terrs := validateIPAddressParentReference(ipAddress.Spec.ParentRef, field.NewPath(\"spec\"))\n\tallErrs = append(allErrs, errs...)\n\treturn allErrs\n\n}","line":{"from":760,"to":766}} {"id":100002915,"name":"validateIPAddressParentReference","signature":"func validateIPAddressParentReference(params *networking.ParentReference, fldPath *field.Path) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"// validateIPAddressParentReference ensures that the IPAddress ParenteReference exists and is valid.\nfunc validateIPAddressParentReference(params *networking.ParentReference, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif params == nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"parentRef\"), \"\"))\n\t\treturn allErrs\n\t}\n\n\tfldPath = fldPath.Child(\"parentRef\")\n\t// group is required but the Core group used by Services is the empty value, so it can not be enforced\n\tif params.Group != \"\" {\n\t\tfor _, msg := range validation.IsDNS1123Subdomain(params.Group) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"group\"), params.Group, msg))\n\t\t}\n\t}\n\n\t// resource is required\n\tif params.Resource == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"resource\"), \"\"))\n\t} else {\n\t\tfor _, msg := range pathvalidation.IsValidPathSegmentName(params.Resource) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"resource\"), params.Resource, msg))\n\t\t}\n\t}\n\n\t// name is required\n\tif params.Name == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"name\"), \"\"))\n\t} else {\n\t\tfor _, msg := range pathvalidation.IsValidPathSegmentName(params.Name) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"name\"), params.Name, msg))\n\t\t}\n\t}\n\n\t// namespace is optional\n\tif params.Namespace != \"\" {\n\t\tfor _, msg := range pathvalidation.IsValidPathSegmentName(params.Namespace) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"namespace\"), params.Namespace, msg))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":768,"to":810}} {"id":100002916,"name":"ValidateIPAddressUpdate","signature":"func ValidateIPAddressUpdate(update, old *networking.IPAddress) field.ErrorList","file":"pkg/apis/networking/validation/validation.go","code":"// ValidateIPAddressUpdate tests if an update to an IPAddress is valid.\nfunc ValidateIPAddressUpdate(update, old *networking.IPAddress) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tallErrs = append(allErrs, apivalidation.ValidateObjectMetaUpdate(\u0026update.ObjectMeta, \u0026old.ObjectMeta, field.NewPath(\"metadata\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateImmutableField(update.Spec.ParentRef, old.Spec.ParentRef, field.NewPath(\"spec\").Child(\"parentRef\"))...)\n\treturn allErrs\n}","line":{"from":812,"to":818}} {"id":100002917,"name":"init","signature":"func init()","file":"pkg/apis/node/install/install.go","code":"func init() {\n\tInstall(legacyscheme.Scheme)\n}","line":{"from":31,"to":33}} {"id":100002918,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"pkg/apis/node/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(node.AddToScheme(scheme))\n\tutilruntime.Must(v1alpha1.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1.SchemeGroupVersion, v1beta1.SchemeGroupVersion))\n}","line":{"from":35,"to":42}} {"id":100002919,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"pkg/apis/node/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100002920,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/node/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100002921,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/node/register.go","code":"// Adds the list of known types to api.Scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026RuntimeClass{},\n\t\t\u0026RuntimeClassList{},\n\t)\n\treturn nil\n}","line":{"from":47,"to":54}} {"id":100002922,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/node/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002923,"name":"Convert_v1alpha1_RuntimeClass_To_node_RuntimeClass","signature":"func Convert_v1alpha1_RuntimeClass_To_node_RuntimeClass(in *v1alpha1.RuntimeClass, out *node.RuntimeClass, s conversion.Scope) error","file":"pkg/apis/node/v1alpha1/conversion.go","code":"// Convert_v1alpha1_RuntimeClass_To_node_RuntimeClass must override the automatic\n// conversion since we unnested the spec struct after v1alpha1\nfunc Convert_v1alpha1_RuntimeClass_To_node_RuntimeClass(in *v1alpha1.RuntimeClass, out *node.RuntimeClass, s conversion.Scope) error {\n\tout.ObjectMeta = in.ObjectMeta\n\tout.Handler = in.Spec.RuntimeHandler\n\n\tif in.Spec.Overhead != nil {\n\t\tout.Overhead = \u0026node.Overhead{}\n\t\tif err := Convert_v1alpha1_Overhead_To_node_Overhead(in.Spec.Overhead, out.Overhead, s); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif in.Spec.Scheduling != nil {\n\t\tout.Scheduling = \u0026node.Scheduling{}\n\t\tif err := Convert_v1alpha1_Scheduling_To_node_Scheduling(in.Spec.Scheduling, out.Scheduling, s); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":25,"to":44}} {"id":100002924,"name":"Convert_node_RuntimeClass_To_v1alpha1_RuntimeClass","signature":"func Convert_node_RuntimeClass_To_v1alpha1_RuntimeClass(in *node.RuntimeClass, out *v1alpha1.RuntimeClass, s conversion.Scope) error","file":"pkg/apis/node/v1alpha1/conversion.go","code":"// Convert_node_RuntimeClass_To_v1alpha1_RuntimeClass must override the automatic\n// conversion since we unnested the spec struct after v1alpha1\nfunc Convert_node_RuntimeClass_To_v1alpha1_RuntimeClass(in *node.RuntimeClass, out *v1alpha1.RuntimeClass, s conversion.Scope) error {\n\tout.ObjectMeta = in.ObjectMeta\n\tout.Spec.RuntimeHandler = in.Handler\n\n\tif in.Overhead != nil {\n\t\tout.Spec.Overhead = \u0026v1alpha1.Overhead{}\n\t\tif err := Convert_node_Overhead_To_v1alpha1_Overhead(in.Overhead, out.Spec.Overhead, s); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif in.Scheduling != nil {\n\t\tout.Spec.Scheduling = \u0026v1alpha1.Scheduling{}\n\t\tif err := Convert_node_Scheduling_To_v1alpha1_Scheduling(in.Scheduling, out.Spec.Scheduling, s); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":46,"to":65}} {"id":100002925,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/node/v1alpha1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002926,"name":"init","signature":"func init()","file":"pkg/apis/node/v1alpha1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register()\n}","line":{"from":41,"to":46}} {"id":100002927,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/node/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002928,"name":"ValidateRuntimeClass","signature":"func ValidateRuntimeClass(rc *node.RuntimeClass) field.ErrorList","file":"pkg/apis/node/validation/validation.go","code":"// ValidateRuntimeClass validates the RuntimeClass\nfunc ValidateRuntimeClass(rc *node.RuntimeClass) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMeta(\u0026rc.ObjectMeta, false, apivalidation.NameIsDNSSubdomain, field.NewPath(\"metadata\"))\n\n\tfor _, msg := range apivalidation.NameIsDNSLabel(rc.Handler, false) {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"handler\"), rc.Handler, msg))\n\t}\n\n\tif rc.Overhead != nil {\n\t\tallErrs = append(allErrs, validateOverhead(rc.Overhead, field.NewPath(\"overhead\"))...)\n\t}\n\tif rc.Scheduling != nil {\n\t\tallErrs = append(allErrs, validateScheduling(rc.Scheduling, field.NewPath(\"scheduling\"))...)\n\t}\n\n\treturn allErrs\n}","line":{"from":28,"to":44}} {"id":100002929,"name":"ValidateRuntimeClassUpdate","signature":"func ValidateRuntimeClassUpdate(new, old *node.RuntimeClass) field.ErrorList","file":"pkg/apis/node/validation/validation.go","code":"// ValidateRuntimeClassUpdate validates an update to the object\nfunc ValidateRuntimeClassUpdate(new, old *node.RuntimeClass) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMetaUpdate(\u0026new.ObjectMeta, \u0026old.ObjectMeta, field.NewPath(\"metadata\"))\n\n\tallErrs = append(allErrs, apivalidation.ValidateImmutableField(new.Handler, old.Handler, field.NewPath(\"handler\"))...)\n\n\treturn allErrs\n}","line":{"from":46,"to":53}} {"id":100002930,"name":"validateOverhead","signature":"func validateOverhead(overhead *node.Overhead, fldPath *field.Path) field.ErrorList","file":"pkg/apis/node/validation/validation.go","code":"func validateOverhead(overhead *node.Overhead, fldPath *field.Path) field.ErrorList {\n\t// reuse the ResourceRequirements validation logic\n\treturn corevalidation.ValidateResourceRequirements(\u0026core.ResourceRequirements{Limits: overhead.PodFixed}, nil, fldPath,\n\t\tcorevalidation.PodValidationOptions{})\n}","line":{"from":55,"to":59}} {"id":100002931,"name":"validateScheduling","signature":"func validateScheduling(s *node.Scheduling, fldPath *field.Path) field.ErrorList","file":"pkg/apis/node/validation/validation.go","code":"func validateScheduling(s *node.Scheduling, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tif s.NodeSelector != nil {\n\t\tallErrs = append(allErrs, unversionedvalidation.ValidateLabels(s.NodeSelector, fldPath.Child(\"nodeSelector\"))...)\n\t}\n\tallErrs = append(allErrs, validateTolerations(s.Tolerations, fldPath.Child(\"tolerations\"))...)\n\treturn allErrs\n}","line":{"from":61,"to":68}} {"id":100002932,"name":"validateTolerations","signature":"func validateTolerations(tolerations []core.Toleration, fldPath *field.Path) field.ErrorList","file":"pkg/apis/node/validation/validation.go","code":"func validateTolerations(tolerations []core.Toleration, fldPath *field.Path) field.ErrorList {\n\tallErrs := corevalidation.ValidateTolerations(tolerations, fldPath.Child(\"tolerations\"))\n\t// Ensure uniquenes of tolerations.\n\ttolerationSet := map[core.Toleration]bool{}\n\tfor i, t := range tolerations {\n\t\t// listKey includes the toleration fields identified as listKeys in the API.\n\t\tlistKey := core.Toleration{\n\t\t\tKey: t.Key,\n\t\t\tOperator: t.Operator,\n\t\t\tValue: t.Value,\n\t\t\tEffect: t.Effect,\n\t\t}\n\t\tif tolerationSet[listKey] {\n\t\t\tallErrs = append(allErrs, field.Duplicate(fldPath.Index(i), t))\n\t\t} else {\n\t\t\ttolerationSet[listKey] = true\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":70,"to":89}} {"id":100002933,"name":"StripPDBV1beta1Label","signature":"func StripPDBV1beta1Label(selector *metav1.LabelSelector)","file":"pkg/apis/policy/helper.go","code":"func StripPDBV1beta1Label(selector *metav1.LabelSelector) {\n\tif selector == nil {\n\t\treturn\n\t}\n\n\ttrimmedMatchExpressions := selector.MatchExpressions[:0]\n\tfor _, exp := range selector.MatchExpressions {\n\t\tif exp.Key != PDBV1beta1Label {\n\t\t\ttrimmedMatchExpressions = append(trimmedMatchExpressions, exp)\n\t\t}\n\t}\n\tselector.MatchExpressions = trimmedMatchExpressions\n}","line":{"from":39,"to":51}} {"id":100002934,"name":"init","signature":"func init()","file":"pkg/apis/policy/install/install.go","code":"func init() {\n\tInstall(legacyscheme.Scheme)\n}","line":{"from":30,"to":32}} {"id":100002935,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"pkg/apis/policy/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(policy.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1.SchemeGroupVersion, v1beta1.SchemeGroupVersion))\n}","line":{"from":34,"to":40}} {"id":100002936,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"pkg/apis/policy/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100002937,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/policy/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100002938,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/policy/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\t// TODO this gets cleaned up when the types are fixed\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026PodDisruptionBudget{},\n\t\t\u0026PodDisruptionBudgetList{},\n\t\t\u0026PodSecurityPolicy{},\n\t\t\u0026PodSecurityPolicyList{},\n\t\t\u0026Eviction{},\n\t)\n\treturn nil\n}","line":{"from":47,"to":58}} {"id":100002939,"name":"Convert_v1_PodDisruptionBudget_To_policy_PodDisruptionBudget","signature":"func Convert_v1_PodDisruptionBudget_To_policy_PodDisruptionBudget(in *v1.PodDisruptionBudget, out *policy.PodDisruptionBudget, s conversion.Scope) error","file":"pkg/apis/policy/v1/conversion.go","code":"func Convert_v1_PodDisruptionBudget_To_policy_PodDisruptionBudget(in *v1.PodDisruptionBudget, out *policy.PodDisruptionBudget, s conversion.Scope) error {\n\tif err := autoConvert_v1_PodDisruptionBudget_To_policy_PodDisruptionBudget(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\tswitch {\n\tcase apiequality.Semantic.DeepEqual(in.Spec.Selector, policy.NonV1beta1MatchNoneSelector):\n\t\t// no-op, preserve\n\tcase apiequality.Semantic.DeepEqual(in.Spec.Selector, policy.NonV1beta1MatchAllSelector):\n\t\t// no-op, preserve\n\tdefault:\n\t\t// otherwise, make sure the label intended to be used in a match-all or match-none selector\n\t\t// never gets combined with user-specified fields\n\t\tpolicy.StripPDBV1beta1Label(out.Spec.Selector)\n\t}\n\treturn nil\n}","line":{"from":26,"to":42}} {"id":100002940,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/policy/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002941,"name":"init","signature":"func init()","file":"pkg/apis/policy/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(RegisterDefaults)\n}","line":{"from":40,"to":45}} {"id":100002942,"name":"Convert_v1beta1_PodDisruptionBudget_To_policy_PodDisruptionBudget","signature":"func Convert_v1beta1_PodDisruptionBudget_To_policy_PodDisruptionBudget(in *v1beta1.PodDisruptionBudget, out *policy.PodDisruptionBudget, s conversion.Scope) error","file":"pkg/apis/policy/v1beta1/conversion.go","code":"func Convert_v1beta1_PodDisruptionBudget_To_policy_PodDisruptionBudget(in *v1beta1.PodDisruptionBudget, out *policy.PodDisruptionBudget, s conversion.Scope) error {\n\tif err := autoConvert_v1beta1_PodDisruptionBudget_To_policy_PodDisruptionBudget(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\tswitch {\n\tcase apiequality.Semantic.DeepEqual(in.Spec.Selector, policy.V1beta1MatchNoneSelector):\n\t\t// If the v1beta1 version has a non-nil but empty selector, it should be\n\t\t// selecting no pods, even when used with the internal or v1 api. We\n\t\t// add a selector that is non-empty but will never match any pods.\n\t\tout.Spec.Selector = policy.NonV1beta1MatchNoneSelector.DeepCopy()\n\tcase apiequality.Semantic.DeepEqual(in.Spec.Selector, policy.V1beta1MatchAllSelector):\n\t\t// If the v1beta1 version has our v1beta1-specific \"match-all\" selector,\n\t\t// swap that out for a simpler empty \"match-all\" selector for v1\n\t\tout.Spec.Selector = policy.NonV1beta1MatchAllSelector.DeepCopy()\n\tdefault:\n\t\t// otherwise, make sure the label intended to be used in a match-all or match-none selector\n\t\t// never gets combined with user-specified fields\n\t\tpolicy.StripPDBV1beta1Label(out.Spec.Selector)\n\t}\n\treturn nil\n}","line":{"from":26,"to":47}} {"id":100002943,"name":"Convert_policy_PodDisruptionBudget_To_v1beta1_PodDisruptionBudget","signature":"func Convert_policy_PodDisruptionBudget_To_v1beta1_PodDisruptionBudget(in *policy.PodDisruptionBudget, out *v1beta1.PodDisruptionBudget, s conversion.Scope) error","file":"pkg/apis/policy/v1beta1/conversion.go","code":"func Convert_policy_PodDisruptionBudget_To_v1beta1_PodDisruptionBudget(in *policy.PodDisruptionBudget, out *v1beta1.PodDisruptionBudget, s conversion.Scope) error {\n\tif err := autoConvert_policy_PodDisruptionBudget_To_v1beta1_PodDisruptionBudget(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\tswitch {\n\tcase apiequality.Semantic.DeepEqual(in.Spec.Selector, policy.NonV1beta1MatchNoneSelector):\n\t\t// If the internal version has our v1beta1-specific \"match-none\" selector,\n\t\t// swap that out for a simpler empty \"match-none\" selector for v1beta1\n\t\tout.Spec.Selector = policy.V1beta1MatchNoneSelector.DeepCopy()\n\tcase apiequality.Semantic.DeepEqual(in.Spec.Selector, policy.NonV1beta1MatchAllSelector):\n\t\t// If the internal version has a non-nil but empty selector, we want it to\n\t\t// select all pods. We make sure this happens even with the v1beta1 api by\n\t\t// adding a non-empty selector that selects all pods.\n\t\tout.Spec.Selector = policy.V1beta1MatchAllSelector.DeepCopy()\n\t}\n\treturn nil\n}","line":{"from":49,"to":66}} {"id":100002944,"name":"SetDefaults_PodSecurityPolicySpec","signature":"func SetDefaults_PodSecurityPolicySpec(obj *policyv1beta1.PodSecurityPolicySpec)","file":"pkg/apis/policy/v1beta1/defaults.go","code":"func SetDefaults_PodSecurityPolicySpec(obj *policyv1beta1.PodSecurityPolicySpec) {\n\t// This field was added after PodSecurityPolicy was released.\n\t// Policies that do not include this field must remain as permissive as they were prior to the introduction of this field.\n\tif obj.AllowPrivilegeEscalation == nil {\n\t\tt := true\n\t\tobj.AllowPrivilegeEscalation = \u0026t\n\t}\n}","line":{"from":23,"to":30}} {"id":100002945,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/policy/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100002946,"name":"init","signature":"func init()","file":"pkg/apis/policy/v1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(RegisterDefaults)\n}","line":{"from":40,"to":45}} {"id":100002947,"name":"ValidatePodDisruptionBudget","signature":"func ValidatePodDisruptionBudget(pdb *policy.PodDisruptionBudget, opts PodDisruptionBudgetValidationOptions) field.ErrorList","file":"pkg/apis/policy/validation/validation.go","code":"// ValidatePodDisruptionBudget validates a PodDisruptionBudget and returns an ErrorList\n// with any errors.\nfunc ValidatePodDisruptionBudget(pdb *policy.PodDisruptionBudget, opts PodDisruptionBudgetValidationOptions) field.ErrorList {\n\tallErrs := ValidatePodDisruptionBudgetSpec(pdb.Spec, opts, field.NewPath(\"spec\"))\n\treturn allErrs\n}","line":{"from":56,"to":61}} {"id":100002948,"name":"ValidatePodDisruptionBudgetSpec","signature":"func ValidatePodDisruptionBudgetSpec(spec policy.PodDisruptionBudgetSpec, opts PodDisruptionBudgetValidationOptions, fldPath *field.Path) field.ErrorList","file":"pkg/apis/policy/validation/validation.go","code":"// ValidatePodDisruptionBudgetSpec validates a PodDisruptionBudgetSpec and returns an ErrorList\n// with any errors.\nfunc ValidatePodDisruptionBudgetSpec(spec policy.PodDisruptionBudgetSpec, opts PodDisruptionBudgetValidationOptions, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif spec.MinAvailable != nil \u0026\u0026 spec.MaxUnavailable != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, spec, \"minAvailable and maxUnavailable cannot be both set\"))\n\t}\n\n\tif spec.MinAvailable != nil {\n\t\tallErrs = append(allErrs, appsvalidation.ValidatePositiveIntOrPercent(*spec.MinAvailable, fldPath.Child(\"minAvailable\"))...)\n\t\tallErrs = append(allErrs, appsvalidation.IsNotMoreThan100Percent(*spec.MinAvailable, fldPath.Child(\"minAvailable\"))...)\n\t}\n\n\tif spec.MaxUnavailable != nil {\n\t\tallErrs = append(allErrs, appsvalidation.ValidatePositiveIntOrPercent(*spec.MaxUnavailable, fldPath.Child(\"maxUnavailable\"))...)\n\t\tallErrs = append(allErrs, appsvalidation.IsNotMoreThan100Percent(*spec.MaxUnavailable, fldPath.Child(\"maxUnavailable\"))...)\n\t}\n\n\tlabelSelectorValidationOptions := unversionedvalidation.LabelSelectorValidationOptions{AllowInvalidLabelValueInSelector: opts.AllowInvalidLabelValueInSelector}\n\n\tallErrs = append(allErrs, unversionedvalidation.ValidateLabelSelector(spec.Selector, labelSelectorValidationOptions, fldPath.Child(\"selector\"))...)\n\n\tif spec.UnhealthyPodEvictionPolicy != nil \u0026\u0026 !supportedUnhealthyPodEvictionPolicies.Has(string(*spec.UnhealthyPodEvictionPolicy)) {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"unhealthyPodEvictionPolicy\"), *spec.UnhealthyPodEvictionPolicy, supportedUnhealthyPodEvictionPolicies.List()))\n\t}\n\n\treturn allErrs\n}","line":{"from":63,"to":91}} {"id":100002949,"name":"ValidatePodDisruptionBudgetStatusUpdate","signature":"func ValidatePodDisruptionBudgetStatusUpdate(status, oldStatus policy.PodDisruptionBudgetStatus, fldPath *field.Path, apiVersion schema.GroupVersion) field.ErrorList","file":"pkg/apis/policy/validation/validation.go","code":"// ValidatePodDisruptionBudgetStatusUpdate validates a PodDisruptionBudgetStatus and returns an ErrorList\n// with any errors.\nfunc ValidatePodDisruptionBudgetStatusUpdate(status, oldStatus policy.PodDisruptionBudgetStatus, fldPath *field.Path, apiVersion schema.GroupVersion) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, unversionedvalidation.ValidateConditions(status.Conditions, fldPath.Child(\"conditions\"))...)\n\t// Don't run other validations for v1beta1 since we don't want to introduce\n\t// new validations retroactively.\n\tif apiVersion == policyapiv1beta1.SchemeGroupVersion {\n\t\treturn allErrs\n\t}\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.DisruptionsAllowed), fldPath.Child(\"disruptionsAllowed\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.CurrentHealthy), fldPath.Child(\"currentHealthy\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.DesiredHealthy), fldPath.Child(\"desiredHealthy\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(status.ExpectedPods), fldPath.Child(\"expectedPods\"))...)\n\treturn allErrs\n}","line":{"from":93,"to":108}} {"id":100002950,"name":"ValidatePodSecurityPolicy","signature":"func ValidatePodSecurityPolicy(psp *policy.PodSecurityPolicy) field.ErrorList","file":"pkg/apis/policy/validation/validation.go","code":"// ValidatePodSecurityPolicy validates a PodSecurityPolicy and returns an ErrorList\n// with any errors.\nfunc ValidatePodSecurityPolicy(psp *policy.PodSecurityPolicy) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, apivalidation.ValidateObjectMeta(\u0026psp.ObjectMeta, false, ValidatePodSecurityPolicyName, field.NewPath(\"metadata\"))...)\n\tallErrs = append(allErrs, ValidatePodSecurityPolicySpecificAnnotations(psp.Annotations, field.NewPath(\"metadata\").Child(\"annotations\"))...)\n\tallErrs = append(allErrs, ValidatePodSecurityPolicySpec(\u0026psp.Spec, field.NewPath(\"spec\"))...)\n\treturn allErrs\n}","line":{"from":116,"to":124}} {"id":100002951,"name":"ValidatePodSecurityPolicySpec","signature":"func ValidatePodSecurityPolicySpec(spec *policy.PodSecurityPolicySpec, fldPath *field.Path) field.ErrorList","file":"pkg/apis/policy/validation/validation.go","code":"// ValidatePodSecurityPolicySpec validates a PodSecurityPolicySpec and returns an ErrorList\n// with any errors.\nfunc ValidatePodSecurityPolicySpec(spec *policy.PodSecurityPolicySpec, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tallErrs = append(allErrs, validatePSPRunAsUser(fldPath.Child(\"runAsUser\"), \u0026spec.RunAsUser)...)\n\tallErrs = append(allErrs, validatePSPRunAsGroup(fldPath.Child(\"runAsGroup\"), spec.RunAsGroup)...)\n\tallErrs = append(allErrs, validatePSPSELinux(fldPath.Child(\"seLinux\"), \u0026spec.SELinux)...)\n\tallErrs = append(allErrs, validatePSPSupplementalGroup(fldPath.Child(\"supplementalGroups\"), \u0026spec.SupplementalGroups)...)\n\tallErrs = append(allErrs, validatePSPFSGroup(fldPath.Child(\"fsGroup\"), \u0026spec.FSGroup)...)\n\tallErrs = append(allErrs, validatePodSecurityPolicyVolumes(fldPath, spec.Volumes)...)\n\tif len(spec.RequiredDropCapabilities) \u003e 0 \u0026\u0026 hasCap(policy.AllowAllCapabilities, spec.AllowedCapabilities) {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"requiredDropCapabilities\"), spec.RequiredDropCapabilities,\n\t\t\t\"must be empty when all capabilities are allowed by a wildcard\"))\n\t}\n\tallErrs = append(allErrs, validatePSPCapsAgainstDrops(spec.RequiredDropCapabilities, spec.DefaultAddCapabilities, field.NewPath(\"defaultAddCapabilities\"))...)\n\tallErrs = append(allErrs, validatePSPCapsAgainstDrops(spec.RequiredDropCapabilities, spec.AllowedCapabilities, field.NewPath(\"allowedCapabilities\"))...)\n\tallErrs = append(allErrs, validatePSPDefaultAllowPrivilegeEscalation(fldPath.Child(\"defaultAllowPrivilegeEscalation\"), spec.DefaultAllowPrivilegeEscalation, spec.AllowPrivilegeEscalation)...)\n\tallErrs = append(allErrs, validatePSPAllowedProcMountTypes(fldPath.Child(\"allowedProcMountTypes\"), spec.AllowedProcMountTypes)...)\n\tallErrs = append(allErrs, validatePSPAllowedHostPaths(fldPath.Child(\"allowedHostPaths\"), spec.AllowedHostPaths)...)\n\tallErrs = append(allErrs, validatePSPAllowedFlexVolumes(fldPath.Child(\"allowedFlexVolumes\"), spec.AllowedFlexVolumes)...)\n\tallErrs = append(allErrs, validatePSPAllowedCSIDrivers(fldPath.Child(\"allowedCSIDrivers\"), spec.AllowedCSIDrivers)...)\n\tallErrs = append(allErrs, validatePodSecurityPolicySysctls(fldPath.Child(\"allowedUnsafeSysctls\"), spec.AllowedUnsafeSysctls)...)\n\tallErrs = append(allErrs, validatePodSecurityPolicySysctls(fldPath.Child(\"forbiddenSysctls\"), spec.ForbiddenSysctls)...)\n\tallErrs = append(allErrs, validatePodSecurityPolicySysctlListsDoNotOverlap(fldPath.Child(\"allowedUnsafeSysctls\"), fldPath.Child(\"forbiddenSysctls\"), spec.AllowedUnsafeSysctls, spec.ForbiddenSysctls)...)\n\tallErrs = append(allErrs, validateRuntimeClassStrategy(fldPath.Child(\"runtimeClass\"), spec.RuntimeClass)...)\n\n\treturn allErrs\n}","line":{"from":126,"to":154}} {"id":100002952,"name":"ValidatePodSecurityPolicySpecificAnnotations","signature":"func ValidatePodSecurityPolicySpecificAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/policy/validation/validation.go","code":"// ValidatePodSecurityPolicySpecificAnnotations validates annotations and returns an ErrorList\n// with any errors.\nfunc ValidatePodSecurityPolicySpecificAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif p := annotations[v1.AppArmorBetaDefaultProfileAnnotationKey]; p != \"\" {\n\t\tif err := apivalidation.ValidateAppArmorProfileFormat(p); err != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Key(v1.AppArmorBetaDefaultProfileAnnotationKey), p, err.Error()))\n\t\t}\n\t}\n\tif allowed := annotations[v1.AppArmorBetaAllowedProfilesAnnotationKey]; allowed != \"\" {\n\t\tfor _, p := range strings.Split(allowed, \",\") {\n\t\t\tif err := apivalidation.ValidateAppArmorProfileFormat(p); err != nil {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Key(v1.AppArmorBetaAllowedProfilesAnnotationKey), allowed, err.Error()))\n\t\t\t}\n\t\t}\n\t}\n\n\tif p := annotations[seccompDefaultProfileAnnotationKey]; p != \"\" {\n\t\tallErrs = append(allErrs, apivalidation.ValidateSeccompProfile(p, fldPath.Key(seccompDefaultProfileAnnotationKey))...)\n\t}\n\tif allowed := annotations[seccompAllowedProfilesAnnotationKey]; allowed != \"\" {\n\t\tfor _, p := range strings.Split(allowed, \",\") {\n\t\t\tif p == seccompAllowAny {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tallErrs = append(allErrs, apivalidation.ValidateSeccompProfile(p, fldPath.Key(seccompAllowedProfilesAnnotationKey))...)\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":156,"to":186}} {"id":100002953,"name":"validatePSPAllowedHostPaths","signature":"func validatePSPAllowedHostPaths(fldPath *field.Path, allowedHostPaths []policy.AllowedHostPath) field.ErrorList","file":"pkg/apis/policy/validation/validation.go","code":"// validatePSPAllowedHostPaths makes sure all allowed host paths follow:\n// 1. path prefix is required\n// 2. path prefix does not have any element which is \"..\"\nfunc validatePSPAllowedHostPaths(fldPath *field.Path, allowedHostPaths []policy.AllowedHostPath) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tfor i, target := range allowedHostPaths {\n\t\tif target.PathPrefix == \"\" {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Index(i), \"is required\"))\n\t\t\tbreak\n\t\t}\n\t\tparts := strings.Split(filepath.ToSlash(target.PathPrefix), \"/\")\n\t\tfor _, item := range parts {\n\t\t\tif item == \"..\" {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Index(i), target.PathPrefix, \"must not contain '..'\"))\n\t\t\t\tbreak // even for `../../..`, one error is sufficient to make the point\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":188,"to":209}} {"id":100002954,"name":"validatePSPAllowedFlexVolumes","signature":"func validatePSPAllowedFlexVolumes(fldPath *field.Path, flexVolumes []policy.AllowedFlexVolume) field.ErrorList","file":"pkg/apis/policy/validation/validation.go","code":"func validatePSPAllowedFlexVolumes(fldPath *field.Path, flexVolumes []policy.AllowedFlexVolume) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(flexVolumes) \u003e 0 {\n\t\tfor idx, fv := range flexVolumes {\n\t\t\tif len(fv.Driver) == 0 {\n\t\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"allowedFlexVolumes\").Index(idx).Child(\"driver\"),\n\t\t\t\t\t\"must specify a driver\"))\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":211,"to":222}} {"id":100002955,"name":"validatePSPAllowedCSIDrivers","signature":"func validatePSPAllowedCSIDrivers(fldPath *field.Path, csiDrivers []policy.AllowedCSIDriver) field.ErrorList","file":"pkg/apis/policy/validation/validation.go","code":"func validatePSPAllowedCSIDrivers(fldPath *field.Path, csiDrivers []policy.AllowedCSIDriver) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(csiDrivers) \u003e 0 {\n\t\tfor idx, csiDriver := range csiDrivers {\n\t\t\tfieldPath := fldPath.Child(\"allowedCSIDriver\").Index(idx).Child(\"name\")\n\t\t\tallErrs = append(allErrs, apivalidation.ValidateCSIDriverName(csiDriver.Name, fieldPath)...)\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":224,"to":233}} {"id":100002956,"name":"validatePSPSELinux","signature":"func validatePSPSELinux(fldPath *field.Path, seLinux *policy.SELinuxStrategyOptions) field.ErrorList","file":"pkg/apis/policy/validation/validation.go","code":"// validatePSPSELinux validates the SELinux fields of PodSecurityPolicy.\nfunc validatePSPSELinux(fldPath *field.Path, seLinux *policy.SELinuxStrategyOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\t// ensure the selinux strategy has a valid rule\n\tsupportedSELinuxRules := sets.NewString(\n\t\tstring(policy.SELinuxStrategyMustRunAs),\n\t\tstring(policy.SELinuxStrategyRunAsAny),\n\t)\n\tif !supportedSELinuxRules.Has(string(seLinux.Rule)) {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"rule\"), seLinux.Rule, supportedSELinuxRules.List()))\n\t}\n\n\treturn allErrs\n}","line":{"from":235,"to":249}} {"id":100002957,"name":"validatePSPRunAsUser","signature":"func validatePSPRunAsUser(fldPath *field.Path, runAsUser *policy.RunAsUserStrategyOptions) field.ErrorList","file":"pkg/apis/policy/validation/validation.go","code":"// validatePSPRunAsUser validates the RunAsUser fields of PodSecurityPolicy.\nfunc validatePSPRunAsUser(fldPath *field.Path, runAsUser *policy.RunAsUserStrategyOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\t// ensure the user strategy has a valid rule\n\tsupportedRunAsUserRules := sets.NewString(\n\t\tstring(policy.RunAsUserStrategyMustRunAs),\n\t\tstring(policy.RunAsUserStrategyMustRunAsNonRoot),\n\t\tstring(policy.RunAsUserStrategyRunAsAny),\n\t)\n\tif !supportedRunAsUserRules.Has(string(runAsUser.Rule)) {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"rule\"), runAsUser.Rule, supportedRunAsUserRules.List()))\n\t}\n\n\t// validate range settings\n\tfor idx, rng := range runAsUser.Ranges {\n\t\tallErrs = append(allErrs, validateUserIDRange(fldPath.Child(\"ranges\").Index(idx), rng)...)\n\t}\n\n\treturn allErrs\n}","line":{"from":251,"to":271}} {"id":100002958,"name":"validatePSPRunAsGroup","signature":"func validatePSPRunAsGroup(fldPath *field.Path, runAsGroup *policy.RunAsGroupStrategyOptions) field.ErrorList","file":"pkg/apis/policy/validation/validation.go","code":"// validatePSPRunAsGroup validates the RunAsGroup fields of PodSecurityPolicy.\nfunc validatePSPRunAsGroup(fldPath *field.Path, runAsGroup *policy.RunAsGroupStrategyOptions) field.ErrorList {\n\tvar allErrs field.ErrorList\n\n\tif runAsGroup == nil {\n\t\treturn allErrs\n\t}\n\n\tswitch runAsGroup.Rule {\n\tcase policy.RunAsGroupStrategyRunAsAny:\n\t\tif len(runAsGroup.Ranges) != 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"ranges\"), runAsGroup.Ranges, \"Ranges must be empty\"))\n\t\t}\n\tcase policy.RunAsGroupStrategyMustRunAs, policy.RunAsGroupStrategyMayRunAs:\n\t\tif len(runAsGroup.Ranges) == 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"ranges\"), runAsGroup.Ranges, \"must provide at least one range\"))\n\t\t}\n\t\t// validate range settings\n\t\tfor idx, rng := range runAsGroup.Ranges {\n\t\t\tallErrs = append(allErrs, validateGroupIDRange(fldPath.Child(\"ranges\").Index(idx), rng)...)\n\t\t}\n\tdefault:\n\t\tsupportedRunAsGroupRules := []string{\n\t\t\tstring(policy.RunAsGroupStrategyMustRunAs),\n\t\t\tstring(policy.RunAsGroupStrategyRunAsAny),\n\t\t\tstring(policy.RunAsGroupStrategyMayRunAs),\n\t\t}\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"rule\"), runAsGroup.Rule, supportedRunAsGroupRules))\n\t}\n\treturn allErrs\n}","line":{"from":273,"to":303}} {"id":100002959,"name":"validatePSPFSGroup","signature":"func validatePSPFSGroup(fldPath *field.Path, groupOptions *policy.FSGroupStrategyOptions) field.ErrorList","file":"pkg/apis/policy/validation/validation.go","code":"// validatePSPFSGroup validates the FSGroupStrategyOptions fields of the PodSecurityPolicy.\nfunc validatePSPFSGroup(fldPath *field.Path, groupOptions *policy.FSGroupStrategyOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tsupportedRules := sets.NewString(\n\t\tstring(policy.FSGroupStrategyMustRunAs),\n\t\tstring(policy.FSGroupStrategyMayRunAs),\n\t\tstring(policy.FSGroupStrategyRunAsAny),\n\t)\n\tif !supportedRules.Has(string(groupOptions.Rule)) {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"rule\"), groupOptions.Rule, supportedRules.List()))\n\t}\n\n\tfor idx, rng := range groupOptions.Ranges {\n\t\tallErrs = append(allErrs, validateGroupIDRange(fldPath.Child(\"ranges\").Index(idx), rng)...)\n\t}\n\treturn allErrs\n}","line":{"from":305,"to":322}} {"id":100002960,"name":"validatePSPSupplementalGroup","signature":"func validatePSPSupplementalGroup(fldPath *field.Path, groupOptions *policy.SupplementalGroupsStrategyOptions) field.ErrorList","file":"pkg/apis/policy/validation/validation.go","code":"// validatePSPSupplementalGroup validates the SupplementalGroupsStrategyOptions fields of the PodSecurityPolicy.\nfunc validatePSPSupplementalGroup(fldPath *field.Path, groupOptions *policy.SupplementalGroupsStrategyOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tsupportedRules := sets.NewString(\n\t\tstring(policy.SupplementalGroupsStrategyRunAsAny),\n\t\tstring(policy.SupplementalGroupsStrategyMayRunAs),\n\t\tstring(policy.SupplementalGroupsStrategyMustRunAs),\n\t)\n\tif !supportedRules.Has(string(groupOptions.Rule)) {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"rule\"), groupOptions.Rule, supportedRules.List()))\n\t}\n\n\tfor idx, rng := range groupOptions.Ranges {\n\t\tallErrs = append(allErrs, validateGroupIDRange(fldPath.Child(\"ranges\").Index(idx), rng)...)\n\t}\n\treturn allErrs\n}","line":{"from":324,"to":341}} {"id":100002961,"name":"validatePodSecurityPolicyVolumes","signature":"func validatePodSecurityPolicyVolumes(fldPath *field.Path, volumes []policy.FSType) field.ErrorList","file":"pkg/apis/policy/validation/validation.go","code":"// validatePodSecurityPolicyVolumes validates the volume fields of PodSecurityPolicy.\nfunc validatePodSecurityPolicyVolumes(fldPath *field.Path, volumes []policy.FSType) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallowed := getAllFSTypesAsSet()\n\t// add in the * value since that is a pseudo type that is not included by default\n\tallowed.Insert(string(policy.All))\n\tfor _, v := range volumes {\n\t\tif !allowed.Has(string(v)) {\n\t\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"volumes\"), v, allowed.List()))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":343,"to":355}} {"id":100002962,"name":"getAllFSTypesAsSet","signature":"func getAllFSTypesAsSet() sets.String","file":"pkg/apis/policy/validation/validation.go","code":"// getAllFSTypesAsSet returns all actual volume types, regardless\n// of feature gates. The special policy.All pseudo type is not included.\nfunc getAllFSTypesAsSet() sets.String {\n\tfstypes := sets.NewString()\n\tfstypes.Insert(\n\t\tstring(policy.HostPath),\n\t\tstring(policy.AzureFile),\n\t\tstring(policy.Flocker),\n\t\tstring(policy.FlexVolume),\n\t\tstring(policy.EmptyDir),\n\t\tstring(policy.GCEPersistentDisk),\n\t\tstring(policy.AWSElasticBlockStore),\n\t\tstring(policy.GitRepo),\n\t\tstring(policy.Secret),\n\t\tstring(policy.NFS),\n\t\tstring(policy.ISCSI),\n\t\tstring(policy.Glusterfs),\n\t\tstring(policy.PersistentVolumeClaim),\n\t\tstring(policy.RBD),\n\t\tstring(policy.Cinder),\n\t\tstring(policy.CephFS),\n\t\tstring(policy.DownwardAPI),\n\t\tstring(policy.FC),\n\t\tstring(policy.ConfigMap),\n\t\tstring(policy.VsphereVolume),\n\t\tstring(policy.Quobyte),\n\t\tstring(policy.AzureDisk),\n\t\tstring(policy.PhotonPersistentDisk),\n\t\tstring(policy.StorageOS),\n\t\tstring(policy.Projected),\n\t\tstring(policy.PortworxVolume),\n\t\tstring(policy.ScaleIO),\n\t\tstring(policy.CSI),\n\t\tstring(policy.Ephemeral),\n\t)\n\treturn fstypes\n}","line":{"from":357,"to":393}} {"id":100002963,"name":"validatePSPDefaultAllowPrivilegeEscalation","signature":"func validatePSPDefaultAllowPrivilegeEscalation(fldPath *field.Path, defaultAllowPrivilegeEscalation *bool, allowPrivilegeEscalation bool) field.ErrorList","file":"pkg/apis/policy/validation/validation.go","code":"// validatePSPDefaultAllowPrivilegeEscalation validates the DefaultAllowPrivilegeEscalation field against the AllowPrivilegeEscalation field of a PodSecurityPolicy.\nfunc validatePSPDefaultAllowPrivilegeEscalation(fldPath *field.Path, defaultAllowPrivilegeEscalation *bool, allowPrivilegeEscalation bool) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif defaultAllowPrivilegeEscalation != nil \u0026\u0026 *defaultAllowPrivilegeEscalation \u0026\u0026 !allowPrivilegeEscalation {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, defaultAllowPrivilegeEscalation, \"Cannot set DefaultAllowPrivilegeEscalation to true without also setting AllowPrivilegeEscalation to true\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":395,"to":403}} {"id":100002964,"name":"validatePSPAllowedProcMountTypes","signature":"func validatePSPAllowedProcMountTypes(fldPath *field.Path, allowedProcMountTypes []core.ProcMountType) field.ErrorList","file":"pkg/apis/policy/validation/validation.go","code":"// validatePSPAllowedProcMountTypes validates the DefaultAllowPrivilegeEscalation field against the AllowPrivilegeEscalation field of a PodSecurityPolicy.\nfunc validatePSPAllowedProcMountTypes(fldPath *field.Path, allowedProcMountTypes []core.ProcMountType) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor i, procMountType := range allowedProcMountTypes {\n\t\tif err := apivalidation.ValidateProcMountType(fldPath.Index(i), procMountType); err != nil {\n\t\t\tallErrs = append(allErrs, err)\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":405,"to":414}} {"id":100002965,"name":"IsValidSysctlPattern","signature":"func IsValidSysctlPattern(name string) bool","file":"pkg/apis/policy/validation/validation.go","code":"// IsValidSysctlPattern checks if name is a valid sysctl pattern.\n// i.e. matches sysctlContainSlashPatternRegexp.\n// More info:\n//\n//\thttps://man7.org/linux/man-pages/man8/sysctl.8.html\n//\thttps://man7.org/linux/man-pages/man5/sysctl.d.5.html\nfunc IsValidSysctlPattern(name string) bool {\n\tif len(name) \u003e apivalidation.SysctlMaxLength {\n\t\treturn false\n\t}\n\treturn sysctlContainSlashPatternRegexp.MatchString(name)\n}","line":{"from":423,"to":434}} {"id":100002966,"name":"validatePodSecurityPolicySysctlListsDoNotOverlap","signature":"func validatePodSecurityPolicySysctlListsDoNotOverlap(allowedSysctlsFldPath, forbiddenSysctlsFldPath *field.Path, allowedUnsafeSysctls, forbiddenSysctls []string) field.ErrorList","file":"pkg/apis/policy/validation/validation.go","code":"func validatePodSecurityPolicySysctlListsDoNotOverlap(allowedSysctlsFldPath, forbiddenSysctlsFldPath *field.Path, allowedUnsafeSysctls, forbiddenSysctls []string) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor i, allowedSysctl := range allowedUnsafeSysctls {\n\t\tisAllowedSysctlPattern := false\n\t\tallowedSysctlPrefix := \"\"\n\t\tif strings.HasSuffix(allowedSysctl, \"*\") {\n\t\t\tisAllowedSysctlPattern = true\n\t\t\tallowedSysctlPrefix = strings.TrimSuffix(allowedSysctl, \"*\")\n\t\t}\n\t\tfor j, forbiddenSysctl := range forbiddenSysctls {\n\t\t\tisForbiddenSysctlPattern := false\n\t\t\tforbiddenSysctlPrefix := \"\"\n\t\t\tif strings.HasSuffix(forbiddenSysctl, \"*\") {\n\t\t\t\tisForbiddenSysctlPattern = true\n\t\t\t\tforbiddenSysctlPrefix = strings.TrimSuffix(forbiddenSysctl, \"*\")\n\t\t\t}\n\t\t\tswitch {\n\t\t\tcase isAllowedSysctlPattern \u0026\u0026 isForbiddenSysctlPattern:\n\t\t\t\tif strings.HasPrefix(allowedSysctlPrefix, forbiddenSysctlPrefix) {\n\t\t\t\t\tallErrs = append(allErrs, field.Invalid(allowedSysctlsFldPath.Index(i), allowedUnsafeSysctls[i], fmt.Sprintf(\"sysctl overlaps with %v\", forbiddenSysctl)))\n\t\t\t\t} else if strings.HasPrefix(forbiddenSysctlPrefix, allowedSysctlPrefix) {\n\t\t\t\t\tallErrs = append(allErrs, field.Invalid(forbiddenSysctlsFldPath.Index(j), forbiddenSysctls[j], fmt.Sprintf(\"sysctl overlaps with %v\", allowedSysctl)))\n\t\t\t\t}\n\t\t\tcase isAllowedSysctlPattern:\n\t\t\t\tif strings.HasPrefix(forbiddenSysctl, allowedSysctlPrefix) {\n\t\t\t\t\tallErrs = append(allErrs, field.Invalid(forbiddenSysctlsFldPath.Index(j), forbiddenSysctls[j], fmt.Sprintf(\"sysctl overlaps with %v\", allowedSysctl)))\n\t\t\t\t}\n\t\t\tcase isForbiddenSysctlPattern:\n\t\t\t\tif strings.HasPrefix(allowedSysctl, forbiddenSysctlPrefix) {\n\t\t\t\t\tallErrs = append(allErrs, field.Invalid(allowedSysctlsFldPath.Index(i), allowedUnsafeSysctls[i], fmt.Sprintf(\"sysctl overlaps with %v\", forbiddenSysctl)))\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tif allowedSysctl == forbiddenSysctl {\n\t\t\t\t\tallErrs = append(allErrs, field.Invalid(allowedSysctlsFldPath.Index(i), allowedUnsafeSysctls[i], fmt.Sprintf(\"sysctl overlaps with %v\", forbiddenSysctl)))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":436,"to":475}} {"id":100002967,"name":"validatePodSecurityPolicySysctls","signature":"func validatePodSecurityPolicySysctls(fldPath *field.Path, sysctls []string) field.ErrorList","file":"pkg/apis/policy/validation/validation.go","code":"// validatePodSecurityPolicySysctls validates the sysctls fields of PodSecurityPolicy.\nfunc validatePodSecurityPolicySysctls(fldPath *field.Path, sysctls []string) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(sysctls) == 0 {\n\t\treturn allErrs\n\t}\n\n\tcoversAll := false\n\tfor i, s := range sysctls {\n\t\tif len(s) == 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Index(i), sysctls[i], \"empty sysctl not allowed\"))\n\t\t} else if !IsValidSysctlPattern(string(s)) {\n\t\t\tallErrs = append(\n\t\t\t\tallErrs,\n\t\t\t\tfield.Invalid(fldPath.Index(i), sysctls[i], fmt.Sprintf(\"must have at most %d characters and match regex %s\",\n\t\t\t\t\tapivalidation.SysctlMaxLength,\n\t\t\t\t\tSysctlContainSlashPatternFmt,\n\t\t\t\t)),\n\t\t\t)\n\t\t} else if s[0] == '*' {\n\t\t\tcoversAll = true\n\t\t}\n\t}\n\n\tif coversAll \u0026\u0026 len(sysctls) \u003e 1 {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"items\"), \"if '*' is present, must not specify other sysctls\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":477,"to":507}} {"id":100002968,"name":"validateUserIDRange","signature":"func validateUserIDRange(fldPath *field.Path, rng policy.IDRange) field.ErrorList","file":"pkg/apis/policy/validation/validation.go","code":"func validateUserIDRange(fldPath *field.Path, rng policy.IDRange) field.ErrorList {\n\treturn validateIDRanges(fldPath, rng.Min, rng.Max)\n}","line":{"from":509,"to":511}} {"id":100002969,"name":"validateGroupIDRange","signature":"func validateGroupIDRange(fldPath *field.Path, rng policy.IDRange) field.ErrorList","file":"pkg/apis/policy/validation/validation.go","code":"func validateGroupIDRange(fldPath *field.Path, rng policy.IDRange) field.ErrorList {\n\treturn validateIDRanges(fldPath, rng.Min, rng.Max)\n}","line":{"from":513,"to":515}} {"id":100002970,"name":"validateIDRanges","signature":"func validateIDRanges(fldPath *field.Path, min, max int64) field.ErrorList","file":"pkg/apis/policy/validation/validation.go","code":"// validateIDRanges ensures the range is valid.\nfunc validateIDRanges(fldPath *field.Path, min, max int64) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\t// if 0 \u003c= Min \u003c= Max then we do not need to validate max. It is always greater than or\n\t// equal to 0 and Min.\n\tif min \u003c 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"min\"), min, \"min cannot be negative\"))\n\t}\n\tif max \u003c 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"max\"), max, \"max cannot be negative\"))\n\t}\n\tif min \u003e max {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"min\"), min, \"min cannot be greater than max\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":517,"to":534}} {"id":100002971,"name":"validatePSPCapsAgainstDrops","signature":"func validatePSPCapsAgainstDrops(requiredDrops []core.Capability, capsToCheck []core.Capability, fldPath *field.Path) field.ErrorList","file":"pkg/apis/policy/validation/validation.go","code":"// validatePSPCapsAgainstDrops ensures an allowed cap is not listed in the required drops.\nfunc validatePSPCapsAgainstDrops(requiredDrops []core.Capability, capsToCheck []core.Capability, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif requiredDrops == nil {\n\t\treturn allErrs\n\t}\n\tfor _, cap := range capsToCheck {\n\t\tif hasCap(cap, requiredDrops) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, cap,\n\t\t\t\tfmt.Sprintf(\"capability is listed in %s and requiredDropCapabilities\", fldPath.String())))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":536,"to":549}} {"id":100002972,"name":"validateRuntimeClassStrategy","signature":"func validateRuntimeClassStrategy(fldPath *field.Path, rc *policy.RuntimeClassStrategyOptions) field.ErrorList","file":"pkg/apis/policy/validation/validation.go","code":"// validateRuntimeClassStrategy ensures all the RuntimeClass restrictions are valid.\nfunc validateRuntimeClassStrategy(fldPath *field.Path, rc *policy.RuntimeClassStrategyOptions) field.ErrorList {\n\tif rc == nil {\n\t\treturn nil\n\t}\n\n\tvar allErrs field.ErrorList\n\n\tallowed := map[string]bool{}\n\tfor i, name := range rc.AllowedRuntimeClassNames {\n\t\tif name != policy.AllowAllRuntimeClassNames {\n\t\t\tallErrs = append(allErrs, apivalidation.ValidateRuntimeClassName(name, fldPath.Child(\"allowedRuntimeClassNames\").Index(i))...)\n\t\t}\n\t\tif allowed[name] {\n\t\t\tallErrs = append(allErrs, field.Duplicate(fldPath.Child(\"allowedRuntimeClassNames\").Index(i), name))\n\t\t}\n\t\tallowed[name] = true\n\t}\n\n\tif rc.DefaultRuntimeClassName != nil {\n\t\tallErrs = append(allErrs, apivalidation.ValidateRuntimeClassName(*rc.DefaultRuntimeClassName, fldPath.Child(\"defaultRuntimeClassName\"))...)\n\t\tif !allowed[*rc.DefaultRuntimeClassName] \u0026\u0026 !allowed[policy.AllowAllRuntimeClassNames] {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"allowedRuntimeClassNames\"),\n\t\t\t\tfmt.Sprintf(\"default %q must be allowed\", *rc.DefaultRuntimeClassName)))\n\t\t}\n\t}\n\n\tif allowed[policy.AllowAllRuntimeClassNames] \u0026\u0026 len(rc.AllowedRuntimeClassNames) \u003e 1 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"allowedRuntimeClassNames\"), rc.AllowedRuntimeClassNames, \"if '*' is present, must not specify other RuntimeClass names\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":551,"to":583}} {"id":100002973,"name":"ValidatePodSecurityPolicyUpdate","signature":"func ValidatePodSecurityPolicyUpdate(old *policy.PodSecurityPolicy, new *policy.PodSecurityPolicy) field.ErrorList","file":"pkg/apis/policy/validation/validation.go","code":"// ValidatePodSecurityPolicyUpdate validates a PSP for updates.\nfunc ValidatePodSecurityPolicyUpdate(old *policy.PodSecurityPolicy, new *policy.PodSecurityPolicy) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, apivalidation.ValidateObjectMetaUpdate(\u0026new.ObjectMeta, \u0026old.ObjectMeta, field.NewPath(\"metadata\"))...)\n\tallErrs = append(allErrs, ValidatePodSecurityPolicySpecificAnnotations(new.Annotations, field.NewPath(\"metadata\").Child(\"annotations\"))...)\n\tallErrs = append(allErrs, ValidatePodSecurityPolicySpec(\u0026new.Spec, field.NewPath(\"spec\"))...)\n\treturn allErrs\n}","line":{"from":585,"to":592}} {"id":100002974,"name":"hasCap","signature":"func hasCap(needle core.Capability, haystack []core.Capability) bool","file":"pkg/apis/policy/validation/validation.go","code":"// hasCap checks for needle in haystack.\nfunc hasCap(needle core.Capability, haystack []core.Capability) bool {\n\tfor _, c := range haystack {\n\t\tif needle == c {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":594,"to":602}} {"id":100002975,"name":"ResourceMatches","signature":"func ResourceMatches(rule *PolicyRule, combinedRequestedResource, requestedSubresource string) bool","file":"pkg/apis/rbac/helpers.go","code":"// ResourceMatches returns the result of the rule.Resources matching.\nfunc ResourceMatches(rule *PolicyRule, combinedRequestedResource, requestedSubresource string) bool {\n\tfor _, ruleResource := range rule.Resources {\n\t\t// if everything is allowed, we match\n\t\tif ruleResource == ResourceAll {\n\t\t\treturn true\n\t\t}\n\t\t// if we have an exact match, we match\n\t\tif ruleResource == combinedRequestedResource {\n\t\t\treturn true\n\t\t}\n\n\t\t// We can also match a */subresource.\n\t\t// if there isn't a subresource, then continue\n\t\tif len(requestedSubresource) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\t// if the rule isn't in the format */subresource, then we don't match, continue\n\t\tif len(ruleResource) == len(requestedSubresource)+2 \u0026\u0026\n\t\t\tstrings.HasPrefix(ruleResource, \"*/\") \u0026\u0026\n\t\t\tstrings.HasSuffix(ruleResource, requestedSubresource) {\n\t\t\treturn true\n\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":27,"to":54}} {"id":100002976,"name":"SubjectsStrings","signature":"func SubjectsStrings(subjects []Subject) ([]string, []string, []string, []string)","file":"pkg/apis/rbac/helpers.go","code":"// SubjectsStrings returns users, groups, serviceaccounts, unknown for display purposes.\nfunc SubjectsStrings(subjects []Subject) ([]string, []string, []string, []string) {\n\tusers := []string{}\n\tgroups := []string{}\n\tsas := []string{}\n\tothers := []string{}\n\n\tfor _, subject := range subjects {\n\t\tswitch subject.Kind {\n\t\tcase ServiceAccountKind:\n\t\t\tsas = append(sas, fmt.Sprintf(\"%s/%s\", subject.Namespace, subject.Name))\n\n\t\tcase UserKind:\n\t\t\tusers = append(users, subject.Name)\n\n\t\tcase GroupKind:\n\t\t\tgroups = append(groups, subject.Name)\n\n\t\tdefault:\n\t\t\tothers = append(others, fmt.Sprintf(\"%s/%s/%s\", subject.Kind, subject.Namespace, subject.Name))\n\t\t}\n\t}\n\n\treturn users, groups, sas, others\n}","line":{"from":56,"to":80}} {"id":100002977,"name":"String","signature":"func (r PolicyRule) String() string","file":"pkg/apis/rbac/helpers.go","code":"func (r PolicyRule) String() string {\n\treturn \"PolicyRule\" + r.CompactString()\n}","line":{"from":82,"to":84}} {"id":100002978,"name":"CompactString","signature":"func (r PolicyRule) CompactString() string","file":"pkg/apis/rbac/helpers.go","code":"// CompactString exposes a compact string representation for use in escalation error messages\nfunc (r PolicyRule) CompactString() string {\n\tformatStringParts := []string{}\n\tformatArgs := []interface{}{}\n\tif len(r.APIGroups) \u003e 0 {\n\t\tformatStringParts = append(formatStringParts, \"APIGroups:%q\")\n\t\tformatArgs = append(formatArgs, r.APIGroups)\n\t}\n\tif len(r.Resources) \u003e 0 {\n\t\tformatStringParts = append(formatStringParts, \"Resources:%q\")\n\t\tformatArgs = append(formatArgs, r.Resources)\n\t}\n\tif len(r.NonResourceURLs) \u003e 0 {\n\t\tformatStringParts = append(formatStringParts, \"NonResourceURLs:%q\")\n\t\tformatArgs = append(formatArgs, r.NonResourceURLs)\n\t}\n\tif len(r.ResourceNames) \u003e 0 {\n\t\tformatStringParts = append(formatStringParts, \"ResourceNames:%q\")\n\t\tformatArgs = append(formatArgs, r.ResourceNames)\n\t}\n\tif len(r.Verbs) \u003e 0 {\n\t\tformatStringParts = append(formatStringParts, \"Verbs:%q\")\n\t\tformatArgs = append(formatArgs, r.Verbs)\n\t}\n\tformatString := \"{\" + strings.Join(formatStringParts, \", \") + \"}\"\n\treturn fmt.Sprintf(formatString, formatArgs...)\n}","line":{"from":86,"to":112}} {"id":100002979,"name":"NewRule","signature":"func NewRule(verbs ...string) *PolicyRuleBuilder","file":"pkg/apis/rbac/helpers.go","code":"// NewRule returns new PolicyRule made by input verbs.\nfunc NewRule(verbs ...string) *PolicyRuleBuilder {\n\treturn \u0026PolicyRuleBuilder{\n\t\tPolicyRule: PolicyRule{Verbs: sets.NewString(verbs...).List()},\n\t}\n}","line":{"from":122,"to":127}} {"id":100002980,"name":"Groups","signature":"func (r *PolicyRuleBuilder) Groups(groups ...string) *PolicyRuleBuilder","file":"pkg/apis/rbac/helpers.go","code":"// Groups combines the PolicyRule.APIGroups and input groups.\nfunc (r *PolicyRuleBuilder) Groups(groups ...string) *PolicyRuleBuilder {\n\tr.PolicyRule.APIGroups = combine(r.PolicyRule.APIGroups, groups)\n\treturn r\n}","line":{"from":129,"to":133}} {"id":100002981,"name":"Resources","signature":"func (r *PolicyRuleBuilder) Resources(resources ...string) *PolicyRuleBuilder","file":"pkg/apis/rbac/helpers.go","code":"// Resources combines the PolicyRule.Rule and input resources.\nfunc (r *PolicyRuleBuilder) Resources(resources ...string) *PolicyRuleBuilder {\n\tr.PolicyRule.Resources = combine(r.PolicyRule.Resources, resources)\n\treturn r\n}","line":{"from":135,"to":139}} {"id":100002982,"name":"Names","signature":"func (r *PolicyRuleBuilder) Names(names ...string) *PolicyRuleBuilder","file":"pkg/apis/rbac/helpers.go","code":"// Names combines the PolicyRule.ResourceNames and input names.\nfunc (r *PolicyRuleBuilder) Names(names ...string) *PolicyRuleBuilder {\n\tr.PolicyRule.ResourceNames = combine(r.PolicyRule.ResourceNames, names)\n\treturn r\n}","line":{"from":141,"to":145}} {"id":100002983,"name":"URLs","signature":"func (r *PolicyRuleBuilder) URLs(urls ...string) *PolicyRuleBuilder","file":"pkg/apis/rbac/helpers.go","code":"// URLs combines the PolicyRule.NonResourceURLs and input urls.\nfunc (r *PolicyRuleBuilder) URLs(urls ...string) *PolicyRuleBuilder {\n\tr.PolicyRule.NonResourceURLs = combine(r.PolicyRule.NonResourceURLs, urls)\n\treturn r\n}","line":{"from":147,"to":151}} {"id":100002984,"name":"RuleOrDie","signature":"func (r *PolicyRuleBuilder) RuleOrDie() PolicyRule","file":"pkg/apis/rbac/helpers.go","code":"// RuleOrDie calls the binding method and panics if there is an error.\nfunc (r *PolicyRuleBuilder) RuleOrDie() PolicyRule {\n\tret, err := r.Rule()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ret\n}","line":{"from":153,"to":160}} {"id":100002985,"name":"combine","signature":"func combine(s1, s2 []string) []string","file":"pkg/apis/rbac/helpers.go","code":"func combine(s1, s2 []string) []string {\n\ts := sets.NewString(s1...)\n\ts.Insert(s2...)\n\treturn s.List()\n}","line":{"from":162,"to":166}} {"id":100002986,"name":"Rule","signature":"func (r *PolicyRuleBuilder) Rule() (PolicyRule, error)","file":"pkg/apis/rbac/helpers.go","code":"// Rule returns PolicyRule and error.\nfunc (r *PolicyRuleBuilder) Rule() (PolicyRule, error) {\n\tif len(r.PolicyRule.Verbs) == 0 {\n\t\treturn PolicyRule{}, fmt.Errorf(\"verbs are required: %#v\", r.PolicyRule)\n\t}\n\n\tswitch {\n\tcase len(r.PolicyRule.NonResourceURLs) \u003e 0:\n\t\tif len(r.PolicyRule.APIGroups) != 0 || len(r.PolicyRule.Resources) != 0 || len(r.PolicyRule.ResourceNames) != 0 {\n\t\t\treturn PolicyRule{}, fmt.Errorf(\"non-resource rule may not have apiGroups, resources, or resourceNames: %#v\", r.PolicyRule)\n\t\t}\n\tcase len(r.PolicyRule.Resources) \u003e 0:\n\t\t// resource rule may not have nonResourceURLs\n\n\t\tif len(r.PolicyRule.APIGroups) == 0 {\n\t\t\t// this a common bug\n\t\t\treturn PolicyRule{}, fmt.Errorf(\"resource rule must have apiGroups: %#v\", r.PolicyRule)\n\t\t}\n\t\t// if resource names are set, then the verb must not be list, watch, create, or deletecollection\n\t\t// since verbs are largely opaque, we don't want to accidentally prevent things like \"impersonate\", so\n\t\t// we will backlist common mistakes, not whitelist acceptable options.\n\t\tif len(r.PolicyRule.ResourceNames) != 0 {\n\t\t\tillegalVerbs := []string{}\n\t\t\tfor _, verb := range r.PolicyRule.Verbs {\n\t\t\t\tswitch verb {\n\t\t\t\tcase \"list\", \"watch\", \"create\", \"deletecollection\":\n\t\t\t\t\tillegalVerbs = append(illegalVerbs, verb)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(illegalVerbs) \u003e 0 {\n\t\t\t\treturn PolicyRule{}, fmt.Errorf(\"verbs %v do not have names available: %#v\", illegalVerbs, r.PolicyRule)\n\t\t\t}\n\t\t}\n\n\tdefault:\n\t\treturn PolicyRule{}, fmt.Errorf(\"a rule must have either nonResourceURLs or resources: %#v\", r.PolicyRule)\n\t}\n\n\treturn r.PolicyRule, nil\n}","line":{"from":168,"to":207}} {"id":100002987,"name":"NewClusterBinding","signature":"func NewClusterBinding(clusterRoleName string) *ClusterRoleBindingBuilder","file":"pkg/apis/rbac/helpers.go","code":"// NewClusterBinding creates a ClusterRoleBinding builder that can be used\n// to define the subjects of a cluster role binding. At least one of\n// the `Groups`, `Users` or `SAs` method must be called before\n// calling the `Binding*` methods.\nfunc NewClusterBinding(clusterRoleName string) *ClusterRoleBindingBuilder {\n\treturn \u0026ClusterRoleBindingBuilder{\n\t\tClusterRoleBinding: ClusterRoleBinding{\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: clusterRoleName},\n\t\t\tRoleRef: RoleRef{\n\t\t\t\tAPIGroup: GroupName,\n\t\t\t\tKind: \"ClusterRole\",\n\t\t\t\tName: clusterRoleName,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":217,"to":232}} {"id":100002988,"name":"Groups","signature":"func (r *ClusterRoleBindingBuilder) Groups(groups ...string) *ClusterRoleBindingBuilder","file":"pkg/apis/rbac/helpers.go","code":"// Groups adds the specified groups as the subjects of the ClusterRoleBinding.\nfunc (r *ClusterRoleBindingBuilder) Groups(groups ...string) *ClusterRoleBindingBuilder {\n\tfor _, group := range groups {\n\t\tr.ClusterRoleBinding.Subjects = append(r.ClusterRoleBinding.Subjects, Subject{Kind: GroupKind, APIGroup: GroupName, Name: group})\n\t}\n\treturn r\n}","line":{"from":234,"to":240}} {"id":100002989,"name":"Users","signature":"func (r *ClusterRoleBindingBuilder) Users(users ...string) *ClusterRoleBindingBuilder","file":"pkg/apis/rbac/helpers.go","code":"// Users adds the specified users as the subjects of the ClusterRoleBinding.\nfunc (r *ClusterRoleBindingBuilder) Users(users ...string) *ClusterRoleBindingBuilder {\n\tfor _, user := range users {\n\t\tr.ClusterRoleBinding.Subjects = append(r.ClusterRoleBinding.Subjects, Subject{Kind: UserKind, APIGroup: GroupName, Name: user})\n\t}\n\treturn r\n}","line":{"from":242,"to":248}} {"id":100002990,"name":"SAs","signature":"func (r *ClusterRoleBindingBuilder) SAs(namespace string, serviceAccountNames ...string) *ClusterRoleBindingBuilder","file":"pkg/apis/rbac/helpers.go","code":"// SAs adds the specified sas as the subjects of the ClusterRoleBinding.\nfunc (r *ClusterRoleBindingBuilder) SAs(namespace string, serviceAccountNames ...string) *ClusterRoleBindingBuilder {\n\tfor _, saName := range serviceAccountNames {\n\t\tr.ClusterRoleBinding.Subjects = append(r.ClusterRoleBinding.Subjects, Subject{Kind: ServiceAccountKind, Namespace: namespace, Name: saName})\n\t}\n\treturn r\n}","line":{"from":250,"to":256}} {"id":100002991,"name":"BindingOrDie","signature":"func (r *ClusterRoleBindingBuilder) BindingOrDie() ClusterRoleBinding","file":"pkg/apis/rbac/helpers.go","code":"// BindingOrDie calls the binding method and panics if there is an error.\nfunc (r *ClusterRoleBindingBuilder) BindingOrDie() ClusterRoleBinding {\n\tret, err := r.Binding()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ret\n}","line":{"from":258,"to":265}} {"id":100002992,"name":"Binding","signature":"func (r *ClusterRoleBindingBuilder) Binding() (ClusterRoleBinding, error)","file":"pkg/apis/rbac/helpers.go","code":"// Binding builds and returns the ClusterRoleBinding API object from the builder\n// object.\nfunc (r *ClusterRoleBindingBuilder) Binding() (ClusterRoleBinding, error) {\n\tif len(r.ClusterRoleBinding.Subjects) == 0 {\n\t\treturn ClusterRoleBinding{}, fmt.Errorf(\"subjects are required: %#v\", r.ClusterRoleBinding)\n\t}\n\n\treturn r.ClusterRoleBinding, nil\n}","line":{"from":267,"to":275}} {"id":100002993,"name":"NewRoleBinding","signature":"func NewRoleBinding(roleName, namespace string) *RoleBindingBuilder","file":"pkg/apis/rbac/helpers.go","code":"// NewRoleBinding creates a RoleBinding builder that can be used\n// to define the subjects of a role binding. At least one of\n// the `Groups`, `Users` or `SAs` method must be called before\n// calling the `Binding*` methods.\nfunc NewRoleBinding(roleName, namespace string) *RoleBindingBuilder {\n\treturn \u0026RoleBindingBuilder{\n\t\tRoleBinding: RoleBinding{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: roleName,\n\t\t\t\tNamespace: namespace,\n\t\t\t},\n\t\t\tRoleRef: RoleRef{\n\t\t\t\tAPIGroup: GroupName,\n\t\t\t\tKind: \"Role\",\n\t\t\t\tName: roleName,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":284,"to":302}} {"id":100002994,"name":"NewRoleBindingForClusterRole","signature":"func NewRoleBindingForClusterRole(roleName, namespace string) *RoleBindingBuilder","file":"pkg/apis/rbac/helpers.go","code":"// NewRoleBindingForClusterRole creates a RoleBinding builder that can be used\n// to define the subjects of a cluster role binding. At least one of\n// the `Groups`, `Users` or `SAs` method must be called before\n// calling the `Binding*` methods.\nfunc NewRoleBindingForClusterRole(roleName, namespace string) *RoleBindingBuilder {\n\treturn \u0026RoleBindingBuilder{\n\t\tRoleBinding: RoleBinding{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: roleName,\n\t\t\t\tNamespace: namespace,\n\t\t\t},\n\t\t\tRoleRef: RoleRef{\n\t\t\t\tAPIGroup: GroupName,\n\t\t\t\tKind: \"ClusterRole\",\n\t\t\t\tName: roleName,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":304,"to":322}} {"id":100002995,"name":"Groups","signature":"func (r *RoleBindingBuilder) Groups(groups ...string) *RoleBindingBuilder","file":"pkg/apis/rbac/helpers.go","code":"// Groups adds the specified groups as the subjects of the RoleBinding.\nfunc (r *RoleBindingBuilder) Groups(groups ...string) *RoleBindingBuilder {\n\tfor _, group := range groups {\n\t\tr.RoleBinding.Subjects = append(r.RoleBinding.Subjects, Subject{Kind: GroupKind, APIGroup: GroupName, Name: group})\n\t}\n\treturn r\n}","line":{"from":324,"to":330}} {"id":100002996,"name":"Users","signature":"func (r *RoleBindingBuilder) Users(users ...string) *RoleBindingBuilder","file":"pkg/apis/rbac/helpers.go","code":"// Users adds the specified users as the subjects of the RoleBinding.\nfunc (r *RoleBindingBuilder) Users(users ...string) *RoleBindingBuilder {\n\tfor _, user := range users {\n\t\tr.RoleBinding.Subjects = append(r.RoleBinding.Subjects, Subject{Kind: UserKind, APIGroup: GroupName, Name: user})\n\t}\n\treturn r\n}","line":{"from":332,"to":338}} {"id":100002997,"name":"SAs","signature":"func (r *RoleBindingBuilder) SAs(namespace string, serviceAccountNames ...string) *RoleBindingBuilder","file":"pkg/apis/rbac/helpers.go","code":"// SAs adds the specified service accounts as the subjects of the\n// RoleBinding.\nfunc (r *RoleBindingBuilder) SAs(namespace string, serviceAccountNames ...string) *RoleBindingBuilder {\n\tfor _, saName := range serviceAccountNames {\n\t\tr.RoleBinding.Subjects = append(r.RoleBinding.Subjects, Subject{Kind: ServiceAccountKind, Namespace: namespace, Name: saName})\n\t}\n\treturn r\n}","line":{"from":340,"to":347}} {"id":100002998,"name":"BindingOrDie","signature":"func (r *RoleBindingBuilder) BindingOrDie() RoleBinding","file":"pkg/apis/rbac/helpers.go","code":"// BindingOrDie calls the binding method and panics if there is an error.\nfunc (r *RoleBindingBuilder) BindingOrDie() RoleBinding {\n\tret, err := r.Binding()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ret\n}","line":{"from":349,"to":356}} {"id":100002999,"name":"Binding","signature":"func (r *RoleBindingBuilder) Binding() (RoleBinding, error)","file":"pkg/apis/rbac/helpers.go","code":"// Binding builds and returns the RoleBinding API object from the builder\n// object.\nfunc (r *RoleBindingBuilder) Binding() (RoleBinding, error) {\n\tif len(r.RoleBinding.Subjects) == 0 {\n\t\treturn RoleBinding{}, fmt.Errorf(\"subjects are required: %#v\", r.RoleBinding)\n\t}\n\n\treturn r.RoleBinding, nil\n}","line":{"from":358,"to":366}} {"id":100003000,"name":"Len","signature":"func (s SortableRuleSlice) Len() int { return len(s) }","file":"pkg/apis/rbac/helpers.go","code":"func (s SortableRuleSlice) Len() int { return len(s) }","line":{"from":371,"to":371}} {"id":100003001,"name":"Swap","signature":"func (s SortableRuleSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","file":"pkg/apis/rbac/helpers.go","code":"func (s SortableRuleSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","line":{"from":372,"to":372}} {"id":100003002,"name":"Less","signature":"func (s SortableRuleSlice) Less(i, j int) bool","file":"pkg/apis/rbac/helpers.go","code":"func (s SortableRuleSlice) Less(i, j int) bool {\n\treturn strings.Compare(s[i].String(), s[j].String()) \u003c 0\n}","line":{"from":373,"to":375}} {"id":100003003,"name":"init","signature":"func init()","file":"pkg/apis/rbac/install/install.go","code":"func init() {\n\tInstall(legacyscheme.Scheme)\n}","line":{"from":31,"to":33}} {"id":100003004,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"pkg/apis/rbac/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(rbac.AddToScheme(scheme))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(v1alpha1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1.SchemeGroupVersion, v1beta1.SchemeGroupVersion, v1alpha1.SchemeGroupVersion))\n}","line":{"from":35,"to":42}} {"id":100003005,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"pkg/apis/rbac/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100003006,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/rbac/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100003007,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/rbac/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Role{},\n\t\t\u0026RoleBinding{},\n\t\t\u0026RoleBindingList{},\n\t\t\u0026RoleList{},\n\n\t\t\u0026ClusterRole{},\n\t\t\u0026ClusterRoleBinding{},\n\t\t\u0026ClusterRoleBindingList{},\n\t\t\u0026ClusterRoleList{},\n\t)\n\treturn nil\n}","line":{"from":46,"to":60}} {"id":100003008,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/rbac/v1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":24,"to":26}} {"id":100003009,"name":"SetDefaults_ClusterRoleBinding","signature":"func SetDefaults_ClusterRoleBinding(obj *rbacv1.ClusterRoleBinding)","file":"pkg/apis/rbac/v1/defaults.go","code":"func SetDefaults_ClusterRoleBinding(obj *rbacv1.ClusterRoleBinding) {\n\tif len(obj.RoleRef.APIGroup) == 0 {\n\t\tobj.RoleRef.APIGroup = GroupName\n\t}\n}","line":{"from":28,"to":32}} {"id":100003010,"name":"SetDefaults_RoleBinding","signature":"func SetDefaults_RoleBinding(obj *rbacv1.RoleBinding)","file":"pkg/apis/rbac/v1/defaults.go","code":"func SetDefaults_RoleBinding(obj *rbacv1.RoleBinding) {\n\tif len(obj.RoleRef.APIGroup) == 0 {\n\t\tobj.RoleRef.APIGroup = GroupName\n\t}\n}","line":{"from":33,"to":37}} {"id":100003011,"name":"SetDefaults_Subject","signature":"func SetDefaults_Subject(obj *rbacv1.Subject)","file":"pkg/apis/rbac/v1/defaults.go","code":"func SetDefaults_Subject(obj *rbacv1.Subject) {\n\tif len(obj.APIGroup) == 0 {\n\t\tswitch obj.Kind {\n\t\tcase rbacv1.ServiceAccountKind:\n\t\t\tobj.APIGroup = \"\"\n\t\tcase rbacv1.UserKind:\n\t\t\tobj.APIGroup = GroupName\n\t\tcase rbacv1.GroupKind:\n\t\t\tobj.APIGroup = GroupName\n\t\t}\n\t}\n}","line":{"from":38,"to":49}} {"id":100003012,"name":"RoleRefGroupKind","signature":"func RoleRefGroupKind(roleRef rbacv1.RoleRef) schema.GroupKind","file":"pkg/apis/rbac/v1/evaluation_helpers.go","code":"func RoleRefGroupKind(roleRef rbacv1.RoleRef) schema.GroupKind {\n\treturn schema.GroupKind{Group: roleRef.APIGroup, Kind: roleRef.Kind}\n}","line":{"from":27,"to":29}} {"id":100003013,"name":"VerbMatches","signature":"func VerbMatches(rule *rbacv1.PolicyRule, requestedVerb string) bool","file":"pkg/apis/rbac/v1/evaluation_helpers.go","code":"func VerbMatches(rule *rbacv1.PolicyRule, requestedVerb string) bool {\n\tfor _, ruleVerb := range rule.Verbs {\n\t\tif ruleVerb == rbacv1.VerbAll {\n\t\t\treturn true\n\t\t}\n\t\tif ruleVerb == requestedVerb {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":31,"to":42}} {"id":100003014,"name":"APIGroupMatches","signature":"func APIGroupMatches(rule *rbacv1.PolicyRule, requestedGroup string) bool","file":"pkg/apis/rbac/v1/evaluation_helpers.go","code":"func APIGroupMatches(rule *rbacv1.PolicyRule, requestedGroup string) bool {\n\tfor _, ruleGroup := range rule.APIGroups {\n\t\tif ruleGroup == rbacv1.APIGroupAll {\n\t\t\treturn true\n\t\t}\n\t\tif ruleGroup == requestedGroup {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":44,"to":55}} {"id":100003015,"name":"ResourceMatches","signature":"func ResourceMatches(rule *rbacv1.PolicyRule, combinedRequestedResource, requestedSubresource string) bool","file":"pkg/apis/rbac/v1/evaluation_helpers.go","code":"func ResourceMatches(rule *rbacv1.PolicyRule, combinedRequestedResource, requestedSubresource string) bool {\n\tfor _, ruleResource := range rule.Resources {\n\t\t// if everything is allowed, we match\n\t\tif ruleResource == rbacv1.ResourceAll {\n\t\t\treturn true\n\t\t}\n\t\t// if we have an exact match, we match\n\t\tif ruleResource == combinedRequestedResource {\n\t\t\treturn true\n\t\t}\n\n\t\t// We can also match a */subresource.\n\t\t// if there isn't a subresource, then continue\n\t\tif len(requestedSubresource) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\t// if the rule isn't in the format */subresource, then we don't match, continue\n\t\tif len(ruleResource) == len(requestedSubresource)+2 \u0026\u0026\n\t\t\tstrings.HasPrefix(ruleResource, \"*/\") \u0026\u0026\n\t\t\tstrings.HasSuffix(ruleResource, requestedSubresource) {\n\t\t\treturn true\n\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":57,"to":83}} {"id":100003016,"name":"ResourceNameMatches","signature":"func ResourceNameMatches(rule *rbacv1.PolicyRule, requestedName string) bool","file":"pkg/apis/rbac/v1/evaluation_helpers.go","code":"func ResourceNameMatches(rule *rbacv1.PolicyRule, requestedName string) bool {\n\tif len(rule.ResourceNames) == 0 {\n\t\treturn true\n\t}\n\n\tfor _, ruleName := range rule.ResourceNames {\n\t\tif ruleName == requestedName {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":85,"to":97}} {"id":100003017,"name":"NonResourceURLMatches","signature":"func NonResourceURLMatches(rule *rbacv1.PolicyRule, requestedURL string) bool","file":"pkg/apis/rbac/v1/evaluation_helpers.go","code":"func NonResourceURLMatches(rule *rbacv1.PolicyRule, requestedURL string) bool {\n\tfor _, ruleURL := range rule.NonResourceURLs {\n\t\tif ruleURL == rbacv1.NonResourceAll {\n\t\t\treturn true\n\t\t}\n\t\tif ruleURL == requestedURL {\n\t\t\treturn true\n\t\t}\n\t\tif strings.HasSuffix(ruleURL, \"*\") \u0026\u0026 strings.HasPrefix(requestedURL, strings.TrimRight(ruleURL, \"*\")) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":99,"to":113}} {"id":100003018,"name":"SubjectsStrings","signature":"func SubjectsStrings(subjects []rbacv1.Subject) ([]string, []string, []string, []string)","file":"pkg/apis/rbac/v1/evaluation_helpers.go","code":"// subjectsStrings returns users, groups, serviceaccounts, unknown for display purposes.\nfunc SubjectsStrings(subjects []rbacv1.Subject) ([]string, []string, []string, []string) {\n\tusers := []string{}\n\tgroups := []string{}\n\tsas := []string{}\n\tothers := []string{}\n\n\tfor _, subject := range subjects {\n\t\tswitch subject.Kind {\n\t\tcase rbacv1.ServiceAccountKind:\n\t\t\tsas = append(sas, fmt.Sprintf(\"%s/%s\", subject.Namespace, subject.Name))\n\n\t\tcase rbacv1.UserKind:\n\t\t\tusers = append(users, subject.Name)\n\n\t\tcase rbacv1.GroupKind:\n\t\t\tgroups = append(groups, subject.Name)\n\n\t\tdefault:\n\t\t\tothers = append(others, fmt.Sprintf(\"%s/%s/%s\", subject.Kind, subject.Namespace, subject.Name))\n\t\t}\n\t}\n\n\treturn users, groups, sas, others\n}","line":{"from":115,"to":139}} {"id":100003019,"name":"String","signature":"func String(r rbacv1.PolicyRule) string","file":"pkg/apis/rbac/v1/evaluation_helpers.go","code":"func String(r rbacv1.PolicyRule) string {\n\treturn \"PolicyRule\" + CompactString(r)\n}","line":{"from":141,"to":143}} {"id":100003020,"name":"CompactString","signature":"func CompactString(r rbacv1.PolicyRule) string","file":"pkg/apis/rbac/v1/evaluation_helpers.go","code":"// CompactString exposes a compact string representation for use in escalation error messages\nfunc CompactString(r rbacv1.PolicyRule) string {\n\tformatStringParts := []string{}\n\tformatArgs := []interface{}{}\n\tif len(r.APIGroups) \u003e 0 {\n\t\tformatStringParts = append(formatStringParts, \"APIGroups:%q\")\n\t\tformatArgs = append(formatArgs, r.APIGroups)\n\t}\n\tif len(r.Resources) \u003e 0 {\n\t\tformatStringParts = append(formatStringParts, \"Resources:%q\")\n\t\tformatArgs = append(formatArgs, r.Resources)\n\t}\n\tif len(r.NonResourceURLs) \u003e 0 {\n\t\tformatStringParts = append(formatStringParts, \"NonResourceURLs:%q\")\n\t\tformatArgs = append(formatArgs, r.NonResourceURLs)\n\t}\n\tif len(r.ResourceNames) \u003e 0 {\n\t\tformatStringParts = append(formatStringParts, \"ResourceNames:%q\")\n\t\tformatArgs = append(formatArgs, r.ResourceNames)\n\t}\n\tif len(r.Verbs) \u003e 0 {\n\t\tformatStringParts = append(formatStringParts, \"Verbs:%q\")\n\t\tformatArgs = append(formatArgs, r.Verbs)\n\t}\n\tformatString := \"{\" + strings.Join(formatStringParts, \", \") + \"}\"\n\treturn fmt.Sprintf(formatString, formatArgs...)\n}","line":{"from":145,"to":171}} {"id":100003021,"name":"Len","signature":"func (s SortableRuleSlice) Len() int { return len(s) }","file":"pkg/apis/rbac/v1/evaluation_helpers.go","code":"func (s SortableRuleSlice) Len() int { return len(s) }","line":{"from":175,"to":175}} {"id":100003022,"name":"Swap","signature":"func (s SortableRuleSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","file":"pkg/apis/rbac/v1/evaluation_helpers.go","code":"func (s SortableRuleSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","line":{"from":176,"to":176}} {"id":100003023,"name":"Less","signature":"func (s SortableRuleSlice) Less(i, j int) bool","file":"pkg/apis/rbac/v1/evaluation_helpers.go","code":"func (s SortableRuleSlice) Less(i, j int) bool {\n\treturn strings.Compare(s[i].String(), s[j].String()) \u003c 0\n}","line":{"from":177,"to":179}} {"id":100003024,"name":"NewRule","signature":"func NewRule(verbs ...string) *PolicyRuleBuilder","file":"pkg/apis/rbac/v1/helpers.go","code":"func NewRule(verbs ...string) *PolicyRuleBuilder {\n\treturn \u0026PolicyRuleBuilder{\n\t\tPolicyRule: rbacv1.PolicyRule{Verbs: verbs},\n\t}\n}","line":{"from":38,"to":42}} {"id":100003025,"name":"Groups","signature":"func (r *PolicyRuleBuilder) Groups(groups ...string) *PolicyRuleBuilder","file":"pkg/apis/rbac/v1/helpers.go","code":"func (r *PolicyRuleBuilder) Groups(groups ...string) *PolicyRuleBuilder {\n\tr.PolicyRule.APIGroups = append(r.PolicyRule.APIGroups, groups...)\n\treturn r\n}","line":{"from":44,"to":47}} {"id":100003026,"name":"Resources","signature":"func (r *PolicyRuleBuilder) Resources(resources ...string) *PolicyRuleBuilder","file":"pkg/apis/rbac/v1/helpers.go","code":"func (r *PolicyRuleBuilder) Resources(resources ...string) *PolicyRuleBuilder {\n\tr.PolicyRule.Resources = append(r.PolicyRule.Resources, resources...)\n\treturn r\n}","line":{"from":49,"to":52}} {"id":100003027,"name":"Names","signature":"func (r *PolicyRuleBuilder) Names(names ...string) *PolicyRuleBuilder","file":"pkg/apis/rbac/v1/helpers.go","code":"func (r *PolicyRuleBuilder) Names(names ...string) *PolicyRuleBuilder {\n\tr.PolicyRule.ResourceNames = append(r.PolicyRule.ResourceNames, names...)\n\treturn r\n}","line":{"from":54,"to":57}} {"id":100003028,"name":"URLs","signature":"func (r *PolicyRuleBuilder) URLs(urls ...string) *PolicyRuleBuilder","file":"pkg/apis/rbac/v1/helpers.go","code":"func (r *PolicyRuleBuilder) URLs(urls ...string) *PolicyRuleBuilder {\n\tr.PolicyRule.NonResourceURLs = append(r.PolicyRule.NonResourceURLs, urls...)\n\treturn r\n}","line":{"from":59,"to":62}} {"id":100003029,"name":"RuleOrDie","signature":"func (r *PolicyRuleBuilder) RuleOrDie() rbacv1.PolicyRule","file":"pkg/apis/rbac/v1/helpers.go","code":"func (r *PolicyRuleBuilder) RuleOrDie() rbacv1.PolicyRule {\n\tret, err := r.Rule()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ret\n}","line":{"from":64,"to":70}} {"id":100003030,"name":"Rule","signature":"func (r *PolicyRuleBuilder) Rule() (rbacv1.PolicyRule, error)","file":"pkg/apis/rbac/v1/helpers.go","code":"func (r *PolicyRuleBuilder) Rule() (rbacv1.PolicyRule, error) {\n\tif len(r.PolicyRule.Verbs) == 0 {\n\t\treturn rbacv1.PolicyRule{}, fmt.Errorf(\"verbs are required: %#v\", r.PolicyRule)\n\t}\n\n\tswitch {\n\tcase len(r.PolicyRule.NonResourceURLs) \u003e 0:\n\t\tif len(r.PolicyRule.APIGroups) != 0 || len(r.PolicyRule.Resources) != 0 || len(r.PolicyRule.ResourceNames) != 0 {\n\t\t\treturn rbacv1.PolicyRule{}, fmt.Errorf(\"non-resource rule may not have apiGroups, resources, or resourceNames: %#v\", r.PolicyRule)\n\t\t}\n\tcase len(r.PolicyRule.Resources) \u003e 0:\n\t\tif len(r.PolicyRule.NonResourceURLs) != 0 {\n\t\t\treturn rbacv1.PolicyRule{}, fmt.Errorf(\"resource rule may not have nonResourceURLs: %#v\", r.PolicyRule)\n\t\t}\n\t\tif len(r.PolicyRule.APIGroups) == 0 {\n\t\t\t// this a common bug\n\t\t\treturn rbacv1.PolicyRule{}, fmt.Errorf(\"resource rule must have apiGroups: %#v\", r.PolicyRule)\n\t\t}\n\tdefault:\n\t\treturn rbacv1.PolicyRule{}, fmt.Errorf(\"a rule must have either nonResourceURLs or resources: %#v\", r.PolicyRule)\n\t}\n\n\tsort.Strings(r.PolicyRule.Resources)\n\tsort.Strings(r.PolicyRule.ResourceNames)\n\tsort.Strings(r.PolicyRule.APIGroups)\n\tsort.Strings(r.PolicyRule.NonResourceURLs)\n\tsort.Strings(r.PolicyRule.Verbs)\n\treturn r.PolicyRule, nil\n}","line":{"from":72,"to":100}} {"id":100003031,"name":"NewClusterBinding","signature":"func NewClusterBinding(clusterRoleName string) *ClusterRoleBindingBuilder","file":"pkg/apis/rbac/v1/helpers.go","code":"func NewClusterBinding(clusterRoleName string) *ClusterRoleBindingBuilder {\n\treturn \u0026ClusterRoleBindingBuilder{\n\t\tClusterRoleBinding: rbacv1.ClusterRoleBinding{\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: clusterRoleName},\n\t\t\tRoleRef: rbacv1.RoleRef{\n\t\t\t\tAPIGroup: GroupName,\n\t\t\t\tKind: \"ClusterRole\",\n\t\t\t\tName: clusterRoleName,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":111,"to":122}} {"id":100003032,"name":"Groups","signature":"func (r *ClusterRoleBindingBuilder) Groups(groups ...string) *ClusterRoleBindingBuilder","file":"pkg/apis/rbac/v1/helpers.go","code":"func (r *ClusterRoleBindingBuilder) Groups(groups ...string) *ClusterRoleBindingBuilder {\n\tfor _, group := range groups {\n\t\tr.ClusterRoleBinding.Subjects = append(r.ClusterRoleBinding.Subjects, rbacv1.Subject{APIGroup: rbacv1.GroupName, Kind: rbacv1.GroupKind, Name: group})\n\t}\n\treturn r\n}","line":{"from":124,"to":129}} {"id":100003033,"name":"Users","signature":"func (r *ClusterRoleBindingBuilder) Users(users ...string) *ClusterRoleBindingBuilder","file":"pkg/apis/rbac/v1/helpers.go","code":"func (r *ClusterRoleBindingBuilder) Users(users ...string) *ClusterRoleBindingBuilder {\n\tfor _, user := range users {\n\t\tr.ClusterRoleBinding.Subjects = append(r.ClusterRoleBinding.Subjects, rbacv1.Subject{APIGroup: rbacv1.GroupName, Kind: rbacv1.UserKind, Name: user})\n\t}\n\treturn r\n}","line":{"from":131,"to":136}} {"id":100003034,"name":"SAs","signature":"func (r *ClusterRoleBindingBuilder) SAs(namespace string, serviceAccountNames ...string) *ClusterRoleBindingBuilder","file":"pkg/apis/rbac/v1/helpers.go","code":"func (r *ClusterRoleBindingBuilder) SAs(namespace string, serviceAccountNames ...string) *ClusterRoleBindingBuilder {\n\tfor _, saName := range serviceAccountNames {\n\t\tr.ClusterRoleBinding.Subjects = append(r.ClusterRoleBinding.Subjects, rbacv1.Subject{Kind: rbacv1.ServiceAccountKind, Namespace: namespace, Name: saName})\n\t}\n\treturn r\n}","line":{"from":138,"to":143}} {"id":100003035,"name":"BindingOrDie","signature":"func (r *ClusterRoleBindingBuilder) BindingOrDie() rbacv1.ClusterRoleBinding","file":"pkg/apis/rbac/v1/helpers.go","code":"func (r *ClusterRoleBindingBuilder) BindingOrDie() rbacv1.ClusterRoleBinding {\n\tret, err := r.Binding()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ret\n}","line":{"from":145,"to":151}} {"id":100003036,"name":"Binding","signature":"func (r *ClusterRoleBindingBuilder) Binding() (rbacv1.ClusterRoleBinding, error)","file":"pkg/apis/rbac/v1/helpers.go","code":"func (r *ClusterRoleBindingBuilder) Binding() (rbacv1.ClusterRoleBinding, error) {\n\tif len(r.ClusterRoleBinding.Subjects) == 0 {\n\t\treturn rbacv1.ClusterRoleBinding{}, fmt.Errorf(\"subjects are required: %#v\", r.ClusterRoleBinding)\n\t}\n\n\treturn r.ClusterRoleBinding, nil\n}","line":{"from":153,"to":159}} {"id":100003037,"name":"NewRoleBinding","signature":"func NewRoleBinding(roleName, namespace string) *RoleBindingBuilder","file":"pkg/apis/rbac/v1/helpers.go","code":"// NewRoleBinding creates a RoleBinding builder that can be used\n// to define the subjects of a role binding. At least one of\n// the `Groups`, `Users` or `SAs` method must be called before\n// calling the `Binding*` methods.\nfunc NewRoleBinding(roleName, namespace string) *RoleBindingBuilder {\n\treturn \u0026RoleBindingBuilder{\n\t\tRoleBinding: rbacv1.RoleBinding{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: roleName,\n\t\t\t\tNamespace: namespace,\n\t\t\t},\n\t\t\tRoleRef: rbacv1.RoleRef{\n\t\t\t\tAPIGroup: GroupName,\n\t\t\t\tKind: \"Role\",\n\t\t\t\tName: roleName,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":169,"to":187}} {"id":100003038,"name":"NewRoleBindingForClusterRole","signature":"func NewRoleBindingForClusterRole(roleName, namespace string) *RoleBindingBuilder","file":"pkg/apis/rbac/v1/helpers.go","code":"func NewRoleBindingForClusterRole(roleName, namespace string) *RoleBindingBuilder {\n\treturn \u0026RoleBindingBuilder{\n\t\tRoleBinding: rbacv1.RoleBinding{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: roleName,\n\t\t\t\tNamespace: namespace,\n\t\t\t},\n\t\t\tRoleRef: rbacv1.RoleRef{\n\t\t\t\tAPIGroup: GroupName,\n\t\t\t\tKind: \"ClusterRole\",\n\t\t\t\tName: roleName,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":189,"to":203}} {"id":100003039,"name":"Groups","signature":"func (r *RoleBindingBuilder) Groups(groups ...string) *RoleBindingBuilder","file":"pkg/apis/rbac/v1/helpers.go","code":"// Groups adds the specified groups as the subjects of the RoleBinding.\nfunc (r *RoleBindingBuilder) Groups(groups ...string) *RoleBindingBuilder {\n\tfor _, group := range groups {\n\t\tr.RoleBinding.Subjects = append(r.RoleBinding.Subjects, rbacv1.Subject{Kind: rbacv1.GroupKind, APIGroup: GroupName, Name: group})\n\t}\n\treturn r\n}","line":{"from":205,"to":211}} {"id":100003040,"name":"Users","signature":"func (r *RoleBindingBuilder) Users(users ...string) *RoleBindingBuilder","file":"pkg/apis/rbac/v1/helpers.go","code":"// Users adds the specified users as the subjects of the RoleBinding.\nfunc (r *RoleBindingBuilder) Users(users ...string) *RoleBindingBuilder {\n\tfor _, user := range users {\n\t\tr.RoleBinding.Subjects = append(r.RoleBinding.Subjects, rbacv1.Subject{Kind: rbacv1.UserKind, APIGroup: GroupName, Name: user})\n\t}\n\treturn r\n}","line":{"from":213,"to":219}} {"id":100003041,"name":"SAs","signature":"func (r *RoleBindingBuilder) SAs(namespace string, serviceAccountNames ...string) *RoleBindingBuilder","file":"pkg/apis/rbac/v1/helpers.go","code":"// SAs adds the specified service accounts as the subjects of the\n// RoleBinding.\nfunc (r *RoleBindingBuilder) SAs(namespace string, serviceAccountNames ...string) *RoleBindingBuilder {\n\tfor _, saName := range serviceAccountNames {\n\t\tr.RoleBinding.Subjects = append(r.RoleBinding.Subjects, rbacv1.Subject{Kind: rbacv1.ServiceAccountKind, Namespace: namespace, Name: saName})\n\t}\n\treturn r\n}","line":{"from":221,"to":228}} {"id":100003042,"name":"BindingOrDie","signature":"func (r *RoleBindingBuilder) BindingOrDie() rbacv1.RoleBinding","file":"pkg/apis/rbac/v1/helpers.go","code":"// BindingOrDie calls the binding method and panics if there is an error.\nfunc (r *RoleBindingBuilder) BindingOrDie() rbacv1.RoleBinding {\n\tret, err := r.Binding()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ret\n}","line":{"from":230,"to":237}} {"id":100003043,"name":"Binding","signature":"func (r *RoleBindingBuilder) Binding() (rbacv1.RoleBinding, error)","file":"pkg/apis/rbac/v1/helpers.go","code":"// Binding builds and returns the RoleBinding API object from the builder\n// object.\nfunc (r *RoleBindingBuilder) Binding() (rbacv1.RoleBinding, error) {\n\tif len(r.RoleBinding.Subjects) == 0 {\n\t\treturn rbacv1.RoleBinding{}, fmt.Errorf(\"subjects are required: %#v\", r.RoleBinding)\n\t}\n\n\treturn r.RoleBinding, nil\n}","line":{"from":239,"to":247}} {"id":100003044,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/rbac/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":29,"to":32}} {"id":100003045,"name":"init","signature":"func init()","file":"pkg/apis/rbac/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":39,"to":44}} {"id":100003046,"name":"Convert_v1alpha1_Subject_To_rbac_Subject","signature":"func Convert_v1alpha1_Subject_To_rbac_Subject(in *rbacv1alpha1.Subject, out *api.Subject, s conversion.Scope) error","file":"pkg/apis/rbac/v1alpha1/conversion.go","code":"func Convert_v1alpha1_Subject_To_rbac_Subject(in *rbacv1alpha1.Subject, out *api.Subject, s conversion.Scope) error {\n\tif err := autoConvert_v1alpha1_Subject_To_rbac_Subject(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\t// specifically set the APIGroup for the three subjects recognized in v1alpha1\n\tswitch {\n\tcase in.Kind == rbacv1alpha1.ServiceAccountKind:\n\t\tout.APIGroup = \"\"\n\tcase in.Kind == rbacv1alpha1.UserKind:\n\t\tout.APIGroup = GroupName\n\tcase in.Kind == rbacv1alpha1.GroupKind:\n\t\tout.APIGroup = GroupName\n\tdefault:\n\t\t// For unrecognized kinds, use the group portion of the APIVersion if we can get it\n\t\tif gv, err := schema.ParseGroupVersion(in.APIVersion); err == nil {\n\t\t\tout.APIGroup = gv.Group\n\t\t}\n\t}\n\n\t// User * in v1alpha1 will only match all authenticated users\n\t// This is only for compatibility with old RBAC bindings\n\t// Special treatment for * should not be included in v1beta1\n\tif out.Kind == rbacv1alpha1.UserKind \u0026\u0026 out.APIGroup == GroupName \u0026\u0026 out.Name == \"*\" {\n\t\tout.Kind = rbacv1alpha1.GroupKind\n\t\tout.Name = allAuthenticated\n\t}\n\n\treturn nil\n}","line":{"from":30,"to":59}} {"id":100003047,"name":"Convert_rbac_Subject_To_v1alpha1_Subject","signature":"func Convert_rbac_Subject_To_v1alpha1_Subject(in *api.Subject, out *rbacv1alpha1.Subject, s conversion.Scope) error","file":"pkg/apis/rbac/v1alpha1/conversion.go","code":"func Convert_rbac_Subject_To_v1alpha1_Subject(in *api.Subject, out *rbacv1alpha1.Subject, s conversion.Scope) error {\n\tif err := autoConvert_rbac_Subject_To_v1alpha1_Subject(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\tswitch {\n\tcase in.Kind == rbacv1alpha1.ServiceAccountKind \u0026\u0026 in.APIGroup == \"\":\n\t\t// Make service accounts v1\n\t\tout.APIVersion = \"v1\"\n\tcase in.Kind == rbacv1alpha1.UserKind \u0026\u0026 in.APIGroup == GroupName:\n\t\t// users in the rbac API group get v1alpha\n\t\tout.APIVersion = SchemeGroupVersion.String()\n\tcase in.Kind == rbacv1alpha1.GroupKind \u0026\u0026 in.APIGroup == GroupName:\n\t\t// groups in the rbac API group get v1alpha\n\t\tout.APIVersion = SchemeGroupVersion.String()\n\tdefault:\n\t\t// otherwise, they get an unspecified version of a group\n\t\tout.APIVersion = schema.GroupVersion{Group: in.APIGroup}.String()\n\t}\n\n\treturn nil\n}","line":{"from":61,"to":82}} {"id":100003048,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/rbac/v1alpha1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":24,"to":26}} {"id":100003049,"name":"SetDefaults_ClusterRoleBinding","signature":"func SetDefaults_ClusterRoleBinding(obj *rbacv1alpha1.ClusterRoleBinding)","file":"pkg/apis/rbac/v1alpha1/defaults.go","code":"func SetDefaults_ClusterRoleBinding(obj *rbacv1alpha1.ClusterRoleBinding) {\n\tif len(obj.RoleRef.APIGroup) == 0 {\n\t\tobj.RoleRef.APIGroup = GroupName\n\t}\n}","line":{"from":28,"to":32}} {"id":100003050,"name":"SetDefaults_RoleBinding","signature":"func SetDefaults_RoleBinding(obj *rbacv1alpha1.RoleBinding)","file":"pkg/apis/rbac/v1alpha1/defaults.go","code":"func SetDefaults_RoleBinding(obj *rbacv1alpha1.RoleBinding) {\n\tif len(obj.RoleRef.APIGroup) == 0 {\n\t\tobj.RoleRef.APIGroup = GroupName\n\t}\n}","line":{"from":33,"to":37}} {"id":100003051,"name":"SetDefaults_Subject","signature":"func SetDefaults_Subject(obj *rbacv1alpha1.Subject)","file":"pkg/apis/rbac/v1alpha1/defaults.go","code":"func SetDefaults_Subject(obj *rbacv1alpha1.Subject) {\n\tif len(obj.APIVersion) == 0 {\n\t\tswitch obj.Kind {\n\t\tcase rbacv1alpha1.ServiceAccountKind:\n\t\t\tobj.APIVersion = \"v1\"\n\t\tcase rbacv1alpha1.UserKind:\n\t\t\tobj.APIVersion = SchemeGroupVersion.String()\n\t\tcase rbacv1alpha1.GroupKind:\n\t\t\tobj.APIVersion = SchemeGroupVersion.String()\n\t\t}\n\t}\n}","line":{"from":38,"to":49}} {"id":100003052,"name":"NewRule","signature":"func NewRule(verbs ...string) *PolicyRuleBuilder","file":"pkg/apis/rbac/v1alpha1/helpers.go","code":"func NewRule(verbs ...string) *PolicyRuleBuilder {\n\treturn \u0026PolicyRuleBuilder{\n\t\tPolicyRule: rbacv1alpha1.PolicyRule{Verbs: verbs},\n\t}\n}","line":{"from":34,"to":38}} {"id":100003053,"name":"Groups","signature":"func (r *PolicyRuleBuilder) Groups(groups ...string) *PolicyRuleBuilder","file":"pkg/apis/rbac/v1alpha1/helpers.go","code":"func (r *PolicyRuleBuilder) Groups(groups ...string) *PolicyRuleBuilder {\n\tr.PolicyRule.APIGroups = append(r.PolicyRule.APIGroups, groups...)\n\treturn r\n}","line":{"from":40,"to":43}} {"id":100003054,"name":"Resources","signature":"func (r *PolicyRuleBuilder) Resources(resources ...string) *PolicyRuleBuilder","file":"pkg/apis/rbac/v1alpha1/helpers.go","code":"func (r *PolicyRuleBuilder) Resources(resources ...string) *PolicyRuleBuilder {\n\tr.PolicyRule.Resources = append(r.PolicyRule.Resources, resources...)\n\treturn r\n}","line":{"from":45,"to":48}} {"id":100003055,"name":"Names","signature":"func (r *PolicyRuleBuilder) Names(names ...string) *PolicyRuleBuilder","file":"pkg/apis/rbac/v1alpha1/helpers.go","code":"func (r *PolicyRuleBuilder) Names(names ...string) *PolicyRuleBuilder {\n\tr.PolicyRule.ResourceNames = append(r.PolicyRule.ResourceNames, names...)\n\treturn r\n}","line":{"from":50,"to":53}} {"id":100003056,"name":"URLs","signature":"func (r *PolicyRuleBuilder) URLs(urls ...string) *PolicyRuleBuilder","file":"pkg/apis/rbac/v1alpha1/helpers.go","code":"func (r *PolicyRuleBuilder) URLs(urls ...string) *PolicyRuleBuilder {\n\tr.PolicyRule.NonResourceURLs = append(r.PolicyRule.NonResourceURLs, urls...)\n\treturn r\n}","line":{"from":55,"to":58}} {"id":100003057,"name":"RuleOrDie","signature":"func (r *PolicyRuleBuilder) RuleOrDie() rbacv1alpha1.PolicyRule","file":"pkg/apis/rbac/v1alpha1/helpers.go","code":"func (r *PolicyRuleBuilder) RuleOrDie() rbacv1alpha1.PolicyRule {\n\tret, err := r.Rule()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ret\n}","line":{"from":60,"to":66}} {"id":100003058,"name":"Rule","signature":"func (r *PolicyRuleBuilder) Rule() (rbacv1alpha1.PolicyRule, error)","file":"pkg/apis/rbac/v1alpha1/helpers.go","code":"func (r *PolicyRuleBuilder) Rule() (rbacv1alpha1.PolicyRule, error) {\n\tif len(r.PolicyRule.Verbs) == 0 {\n\t\treturn rbacv1alpha1.PolicyRule{}, fmt.Errorf(\"verbs are required: %#v\", r.PolicyRule)\n\t}\n\n\tswitch {\n\tcase len(r.PolicyRule.NonResourceURLs) \u003e 0:\n\t\tif len(r.PolicyRule.APIGroups) != 0 || len(r.PolicyRule.Resources) != 0 || len(r.PolicyRule.ResourceNames) != 0 {\n\t\t\treturn rbacv1alpha1.PolicyRule{}, fmt.Errorf(\"non-resource rule may not have apiGroups, resources, or resourceNames: %#v\", r.PolicyRule)\n\t\t}\n\tcase len(r.PolicyRule.Resources) \u003e 0:\n\t\tif len(r.PolicyRule.NonResourceURLs) != 0 {\n\t\t\treturn rbacv1alpha1.PolicyRule{}, fmt.Errorf(\"resource rule may not have nonResourceURLs: %#v\", r.PolicyRule)\n\t\t}\n\t\tif len(r.PolicyRule.APIGroups) == 0 {\n\t\t\t// this a common bug\n\t\t\treturn rbacv1alpha1.PolicyRule{}, fmt.Errorf(\"resource rule must have apiGroups: %#v\", r.PolicyRule)\n\t\t}\n\tdefault:\n\t\treturn rbacv1alpha1.PolicyRule{}, fmt.Errorf(\"a rule must have either nonResourceURLs or resources: %#v\", r.PolicyRule)\n\t}\n\n\treturn r.PolicyRule, nil\n}","line":{"from":68,"to":91}} {"id":100003059,"name":"NewClusterBinding","signature":"func NewClusterBinding(clusterRoleName string) *ClusterRoleBindingBuilder","file":"pkg/apis/rbac/v1alpha1/helpers.go","code":"func NewClusterBinding(clusterRoleName string) *ClusterRoleBindingBuilder {\n\treturn \u0026ClusterRoleBindingBuilder{\n\t\tClusterRoleBinding: rbacv1alpha1.ClusterRoleBinding{\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: clusterRoleName},\n\t\t\tRoleRef: rbacv1alpha1.RoleRef{\n\t\t\t\tAPIGroup: GroupName,\n\t\t\t\tKind: \"ClusterRole\",\n\t\t\t\tName: clusterRoleName,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":100,"to":111}} {"id":100003060,"name":"Groups","signature":"func (r *ClusterRoleBindingBuilder) Groups(groups ...string) *ClusterRoleBindingBuilder","file":"pkg/apis/rbac/v1alpha1/helpers.go","code":"func (r *ClusterRoleBindingBuilder) Groups(groups ...string) *ClusterRoleBindingBuilder {\n\tfor _, group := range groups {\n\t\tr.ClusterRoleBinding.Subjects = append(r.ClusterRoleBinding.Subjects, rbacv1alpha1.Subject{Kind: rbacv1alpha1.GroupKind, Name: group})\n\t}\n\treturn r\n}","line":{"from":113,"to":118}} {"id":100003061,"name":"Users","signature":"func (r *ClusterRoleBindingBuilder) Users(users ...string) *ClusterRoleBindingBuilder","file":"pkg/apis/rbac/v1alpha1/helpers.go","code":"func (r *ClusterRoleBindingBuilder) Users(users ...string) *ClusterRoleBindingBuilder {\n\tfor _, user := range users {\n\t\tr.ClusterRoleBinding.Subjects = append(r.ClusterRoleBinding.Subjects, rbacv1alpha1.Subject{Kind: rbacv1alpha1.UserKind, Name: user})\n\t}\n\treturn r\n}","line":{"from":120,"to":125}} {"id":100003062,"name":"SAs","signature":"func (r *ClusterRoleBindingBuilder) SAs(namespace string, serviceAccountNames ...string) *ClusterRoleBindingBuilder","file":"pkg/apis/rbac/v1alpha1/helpers.go","code":"func (r *ClusterRoleBindingBuilder) SAs(namespace string, serviceAccountNames ...string) *ClusterRoleBindingBuilder {\n\tfor _, saName := range serviceAccountNames {\n\t\tr.ClusterRoleBinding.Subjects = append(r.ClusterRoleBinding.Subjects, rbacv1alpha1.Subject{Kind: rbacv1alpha1.ServiceAccountKind, Namespace: namespace, Name: saName})\n\t}\n\treturn r\n}","line":{"from":127,"to":132}} {"id":100003063,"name":"BindingOrDie","signature":"func (r *ClusterRoleBindingBuilder) BindingOrDie() rbacv1alpha1.ClusterRoleBinding","file":"pkg/apis/rbac/v1alpha1/helpers.go","code":"func (r *ClusterRoleBindingBuilder) BindingOrDie() rbacv1alpha1.ClusterRoleBinding {\n\tret, err := r.Binding()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ret\n}","line":{"from":134,"to":140}} {"id":100003064,"name":"Binding","signature":"func (r *ClusterRoleBindingBuilder) Binding() (rbacv1alpha1.ClusterRoleBinding, error)","file":"pkg/apis/rbac/v1alpha1/helpers.go","code":"func (r *ClusterRoleBindingBuilder) Binding() (rbacv1alpha1.ClusterRoleBinding, error) {\n\tif len(r.ClusterRoleBinding.Subjects) == 0 {\n\t\treturn rbacv1alpha1.ClusterRoleBinding{}, fmt.Errorf(\"subjects are required: %#v\", r.ClusterRoleBinding)\n\t}\n\n\treturn r.ClusterRoleBinding, nil\n}","line":{"from":142,"to":148}} {"id":100003065,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/rbac/v1alpha1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":29,"to":32}} {"id":100003066,"name":"init","signature":"func init()","file":"pkg/apis/rbac/v1alpha1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":39,"to":44}} {"id":100003067,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/rbac/v1beta1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":24,"to":26}} {"id":100003068,"name":"SetDefaults_ClusterRoleBinding","signature":"func SetDefaults_ClusterRoleBinding(obj *rbacv1beta1.ClusterRoleBinding)","file":"pkg/apis/rbac/v1beta1/defaults.go","code":"func SetDefaults_ClusterRoleBinding(obj *rbacv1beta1.ClusterRoleBinding) {\n\tif len(obj.RoleRef.APIGroup) == 0 {\n\t\tobj.RoleRef.APIGroup = GroupName\n\t}\n}","line":{"from":28,"to":32}} {"id":100003069,"name":"SetDefaults_RoleBinding","signature":"func SetDefaults_RoleBinding(obj *rbacv1beta1.RoleBinding)","file":"pkg/apis/rbac/v1beta1/defaults.go","code":"func SetDefaults_RoleBinding(obj *rbacv1beta1.RoleBinding) {\n\tif len(obj.RoleRef.APIGroup) == 0 {\n\t\tobj.RoleRef.APIGroup = GroupName\n\t}\n}","line":{"from":33,"to":37}} {"id":100003070,"name":"SetDefaults_Subject","signature":"func SetDefaults_Subject(obj *rbacv1beta1.Subject)","file":"pkg/apis/rbac/v1beta1/defaults.go","code":"func SetDefaults_Subject(obj *rbacv1beta1.Subject) {\n\tif len(obj.APIGroup) == 0 {\n\t\tswitch obj.Kind {\n\t\tcase rbacv1beta1.ServiceAccountKind:\n\t\t\tobj.APIGroup = \"\"\n\t\tcase rbacv1beta1.UserKind:\n\t\t\tobj.APIGroup = GroupName\n\t\tcase rbacv1beta1.GroupKind:\n\t\t\tobj.APIGroup = GroupName\n\t\t}\n\t}\n}","line":{"from":38,"to":49}} {"id":100003071,"name":"NewRule","signature":"func NewRule(verbs ...string) *PolicyRuleBuilder","file":"pkg/apis/rbac/v1beta1/helpers.go","code":"func NewRule(verbs ...string) *PolicyRuleBuilder {\n\treturn \u0026PolicyRuleBuilder{\n\t\tPolicyRule: rbacv1beta1.PolicyRule{Verbs: verbs},\n\t}\n}","line":{"from":34,"to":38}} {"id":100003072,"name":"Groups","signature":"func (r *PolicyRuleBuilder) Groups(groups ...string) *PolicyRuleBuilder","file":"pkg/apis/rbac/v1beta1/helpers.go","code":"func (r *PolicyRuleBuilder) Groups(groups ...string) *PolicyRuleBuilder {\n\tr.PolicyRule.APIGroups = append(r.PolicyRule.APIGroups, groups...)\n\treturn r\n}","line":{"from":40,"to":43}} {"id":100003073,"name":"Resources","signature":"func (r *PolicyRuleBuilder) Resources(resources ...string) *PolicyRuleBuilder","file":"pkg/apis/rbac/v1beta1/helpers.go","code":"func (r *PolicyRuleBuilder) Resources(resources ...string) *PolicyRuleBuilder {\n\tr.PolicyRule.Resources = append(r.PolicyRule.Resources, resources...)\n\treturn r\n}","line":{"from":45,"to":48}} {"id":100003074,"name":"Names","signature":"func (r *PolicyRuleBuilder) Names(names ...string) *PolicyRuleBuilder","file":"pkg/apis/rbac/v1beta1/helpers.go","code":"func (r *PolicyRuleBuilder) Names(names ...string) *PolicyRuleBuilder {\n\tr.PolicyRule.ResourceNames = append(r.PolicyRule.ResourceNames, names...)\n\treturn r\n}","line":{"from":50,"to":53}} {"id":100003075,"name":"URLs","signature":"func (r *PolicyRuleBuilder) URLs(urls ...string) *PolicyRuleBuilder","file":"pkg/apis/rbac/v1beta1/helpers.go","code":"func (r *PolicyRuleBuilder) URLs(urls ...string) *PolicyRuleBuilder {\n\tr.PolicyRule.NonResourceURLs = append(r.PolicyRule.NonResourceURLs, urls...)\n\treturn r\n}","line":{"from":55,"to":58}} {"id":100003076,"name":"RuleOrDie","signature":"func (r *PolicyRuleBuilder) RuleOrDie() rbacv1beta1.PolicyRule","file":"pkg/apis/rbac/v1beta1/helpers.go","code":"func (r *PolicyRuleBuilder) RuleOrDie() rbacv1beta1.PolicyRule {\n\tret, err := r.Rule()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ret\n}","line":{"from":60,"to":66}} {"id":100003077,"name":"Rule","signature":"func (r *PolicyRuleBuilder) Rule() (rbacv1beta1.PolicyRule, error)","file":"pkg/apis/rbac/v1beta1/helpers.go","code":"func (r *PolicyRuleBuilder) Rule() (rbacv1beta1.PolicyRule, error) {\n\tif len(r.PolicyRule.Verbs) == 0 {\n\t\treturn rbacv1beta1.PolicyRule{}, fmt.Errorf(\"verbs are required: %#v\", r.PolicyRule)\n\t}\n\n\tswitch {\n\tcase len(r.PolicyRule.NonResourceURLs) \u003e 0:\n\t\tif len(r.PolicyRule.APIGroups) != 0 || len(r.PolicyRule.Resources) != 0 || len(r.PolicyRule.ResourceNames) != 0 {\n\t\t\treturn rbacv1beta1.PolicyRule{}, fmt.Errorf(\"non-resource rule may not have apiGroups, resources, or resourceNames: %#v\", r.PolicyRule)\n\t\t}\n\tcase len(r.PolicyRule.Resources) \u003e 0:\n\t\tif len(r.PolicyRule.NonResourceURLs) != 0 {\n\t\t\treturn rbacv1beta1.PolicyRule{}, fmt.Errorf(\"resource rule may not have nonResourceURLs: %#v\", r.PolicyRule)\n\t\t}\n\t\tif len(r.PolicyRule.APIGroups) == 0 {\n\t\t\t// this a common bug\n\t\t\treturn rbacv1beta1.PolicyRule{}, fmt.Errorf(\"resource rule must have apiGroups: %#v\", r.PolicyRule)\n\t\t}\n\tdefault:\n\t\treturn rbacv1beta1.PolicyRule{}, fmt.Errorf(\"a rule must have either nonResourceURLs or resources: %#v\", r.PolicyRule)\n\t}\n\n\treturn r.PolicyRule, nil\n}","line":{"from":68,"to":91}} {"id":100003078,"name":"NewClusterBinding","signature":"func NewClusterBinding(clusterRoleName string) *ClusterRoleBindingBuilder","file":"pkg/apis/rbac/v1beta1/helpers.go","code":"func NewClusterBinding(clusterRoleName string) *ClusterRoleBindingBuilder {\n\treturn \u0026ClusterRoleBindingBuilder{\n\t\tClusterRoleBinding: rbacv1beta1.ClusterRoleBinding{\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: clusterRoleName},\n\t\t\tRoleRef: rbacv1beta1.RoleRef{\n\t\t\t\tAPIGroup: GroupName,\n\t\t\t\tKind: \"ClusterRole\",\n\t\t\t\tName: clusterRoleName,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":100,"to":111}} {"id":100003079,"name":"Groups","signature":"func (r *ClusterRoleBindingBuilder) Groups(groups ...string) *ClusterRoleBindingBuilder","file":"pkg/apis/rbac/v1beta1/helpers.go","code":"func (r *ClusterRoleBindingBuilder) Groups(groups ...string) *ClusterRoleBindingBuilder {\n\tfor _, group := range groups {\n\t\tr.ClusterRoleBinding.Subjects = append(r.ClusterRoleBinding.Subjects, rbacv1beta1.Subject{Kind: rbacv1beta1.GroupKind, Name: group})\n\t}\n\treturn r\n}","line":{"from":113,"to":118}} {"id":100003080,"name":"Users","signature":"func (r *ClusterRoleBindingBuilder) Users(users ...string) *ClusterRoleBindingBuilder","file":"pkg/apis/rbac/v1beta1/helpers.go","code":"func (r *ClusterRoleBindingBuilder) Users(users ...string) *ClusterRoleBindingBuilder {\n\tfor _, user := range users {\n\t\tr.ClusterRoleBinding.Subjects = append(r.ClusterRoleBinding.Subjects, rbacv1beta1.Subject{Kind: rbacv1beta1.UserKind, Name: user})\n\t}\n\treturn r\n}","line":{"from":120,"to":125}} {"id":100003081,"name":"SAs","signature":"func (r *ClusterRoleBindingBuilder) SAs(namespace string, serviceAccountNames ...string) *ClusterRoleBindingBuilder","file":"pkg/apis/rbac/v1beta1/helpers.go","code":"func (r *ClusterRoleBindingBuilder) SAs(namespace string, serviceAccountNames ...string) *ClusterRoleBindingBuilder {\n\tfor _, saName := range serviceAccountNames {\n\t\tr.ClusterRoleBinding.Subjects = append(r.ClusterRoleBinding.Subjects, rbacv1beta1.Subject{Kind: rbacv1beta1.ServiceAccountKind, Namespace: namespace, Name: saName})\n\t}\n\treturn r\n}","line":{"from":127,"to":132}} {"id":100003082,"name":"BindingOrDie","signature":"func (r *ClusterRoleBindingBuilder) BindingOrDie() rbacv1beta1.ClusterRoleBinding","file":"pkg/apis/rbac/v1beta1/helpers.go","code":"func (r *ClusterRoleBindingBuilder) BindingOrDie() rbacv1beta1.ClusterRoleBinding {\n\tret, err := r.Binding()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ret\n}","line":{"from":134,"to":140}} {"id":100003083,"name":"Binding","signature":"func (r *ClusterRoleBindingBuilder) Binding() (rbacv1beta1.ClusterRoleBinding, error)","file":"pkg/apis/rbac/v1beta1/helpers.go","code":"func (r *ClusterRoleBindingBuilder) Binding() (rbacv1beta1.ClusterRoleBinding, error) {\n\tif len(r.ClusterRoleBinding.Subjects) == 0 {\n\t\treturn rbacv1beta1.ClusterRoleBinding{}, fmt.Errorf(\"subjects are required: %#v\", r.ClusterRoleBinding)\n\t}\n\n\treturn r.ClusterRoleBinding, nil\n}","line":{"from":142,"to":148}} {"id":100003084,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/rbac/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":29,"to":32}} {"id":100003085,"name":"init","signature":"func init()","file":"pkg/apis/rbac/v1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":39,"to":44}} {"id":100003086,"name":"ValidateRBACName","signature":"func ValidateRBACName(name string, prefix bool) []string","file":"pkg/apis/rbac/validation/validation.go","code":"// ValidateRBACName is exported to allow types outside of the RBAC API group to reuse this validation logic\n// Minimal validation of names for roles and bindings. Identical to the validation for Openshift. See:\n// * https://github.com/kubernetes/kubernetes/blob/60db507b279ce45bd16ea3db49bf181f2aeb3c3d/pkg/api/validation/name.go\n// * https://github.com/openshift/origin/blob/388478c40e751c4295dcb9a44dd69e5ac65d0e3b/pkg/api/helpers.go\nfunc ValidateRBACName(name string, prefix bool) []string {\n\treturn path.IsValidPathSegmentName(name)\n}","line":{"from":28,"to":34}} {"id":100003087,"name":"ValidateRole","signature":"func ValidateRole(role *rbac.Role) field.ErrorList","file":"pkg/apis/rbac/validation/validation.go","code":"func ValidateRole(role *rbac.Role) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, validation.ValidateObjectMeta(\u0026role.ObjectMeta, true, ValidateRBACName, field.NewPath(\"metadata\"))...)\n\n\tfor i, rule := range role.Rules {\n\t\tif err := ValidatePolicyRule(rule, true, field.NewPath(\"rules\").Index(i)); err != nil {\n\t\t\tallErrs = append(allErrs, err...)\n\t\t}\n\t}\n\tif len(allErrs) != 0 {\n\t\treturn allErrs\n\t}\n\treturn nil\n}","line":{"from":36,"to":49}} {"id":100003088,"name":"ValidateRoleUpdate","signature":"func ValidateRoleUpdate(role *rbac.Role, oldRole *rbac.Role) field.ErrorList","file":"pkg/apis/rbac/validation/validation.go","code":"func ValidateRoleUpdate(role *rbac.Role, oldRole *rbac.Role) field.ErrorList {\n\tallErrs := ValidateRole(role)\n\tallErrs = append(allErrs, validation.ValidateObjectMetaUpdate(\u0026role.ObjectMeta, \u0026oldRole.ObjectMeta, field.NewPath(\"metadata\"))...)\n\n\treturn allErrs\n}","line":{"from":51,"to":56}} {"id":100003089,"name":"ValidateClusterRole","signature":"func ValidateClusterRole(role *rbac.ClusterRole, opts ClusterRoleValidationOptions) field.ErrorList","file":"pkg/apis/rbac/validation/validation.go","code":"func ValidateClusterRole(role *rbac.ClusterRole, opts ClusterRoleValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, validation.ValidateObjectMeta(\u0026role.ObjectMeta, false, ValidateRBACName, field.NewPath(\"metadata\"))...)\n\n\tfor i, rule := range role.Rules {\n\t\tif err := ValidatePolicyRule(rule, false, field.NewPath(\"rules\").Index(i)); err != nil {\n\t\t\tallErrs = append(allErrs, err...)\n\t\t}\n\t}\n\n\tlabelSelectorValidationOptions := unversionedvalidation.LabelSelectorValidationOptions{AllowInvalidLabelValueInSelector: opts.AllowInvalidLabelValueInSelector}\n\n\tif role.AggregationRule != nil {\n\t\tif len(role.AggregationRule.ClusterRoleSelectors) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(field.NewPath(\"aggregationRule\", \"clusterRoleSelectors\"), \"at least one clusterRoleSelector required if aggregationRule is non-nil\"))\n\t\t}\n\t\tfor i, selector := range role.AggregationRule.ClusterRoleSelectors {\n\t\t\tfieldPath := field.NewPath(\"aggregationRule\", \"clusterRoleSelectors\").Index(i)\n\t\t\tallErrs = append(allErrs, unversionedvalidation.ValidateLabelSelector(\u0026selector, labelSelectorValidationOptions, fieldPath)...)\n\n\t\t\tselector, err := metav1.LabelSelectorAsSelector(\u0026selector)\n\t\t\tif err != nil {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fieldPath, selector, \"invalid label selector.\"))\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(allErrs) != 0 {\n\t\treturn allErrs\n\t}\n\treturn nil\n}","line":{"from":62,"to":93}} {"id":100003090,"name":"ValidateClusterRoleUpdate","signature":"func ValidateClusterRoleUpdate(role *rbac.ClusterRole, oldRole *rbac.ClusterRole, opts ClusterRoleValidationOptions) field.ErrorList","file":"pkg/apis/rbac/validation/validation.go","code":"func ValidateClusterRoleUpdate(role *rbac.ClusterRole, oldRole *rbac.ClusterRole, opts ClusterRoleValidationOptions) field.ErrorList {\n\tallErrs := ValidateClusterRole(role, opts)\n\tallErrs = append(allErrs, validation.ValidateObjectMetaUpdate(\u0026role.ObjectMeta, \u0026oldRole.ObjectMeta, field.NewPath(\"metadata\"))...)\n\n\treturn allErrs\n}","line":{"from":95,"to":100}} {"id":100003091,"name":"ValidatePolicyRule","signature":"func ValidatePolicyRule(rule rbac.PolicyRule, isNamespaced bool, fldPath *field.Path) field.ErrorList","file":"pkg/apis/rbac/validation/validation.go","code":"// ValidatePolicyRule is exported to allow types outside of the RBAC API group to embed a rbac.PolicyRule and reuse this validation logic\nfunc ValidatePolicyRule(rule rbac.PolicyRule, isNamespaced bool, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(rule.Verbs) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"verbs\"), \"verbs must contain at least one value\"))\n\t}\n\n\tif len(rule.NonResourceURLs) \u003e 0 {\n\t\tif isNamespaced {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"nonResourceURLs\"), rule.NonResourceURLs, \"namespaced rules cannot apply to non-resource URLs\"))\n\t\t}\n\t\tif len(rule.APIGroups) \u003e 0 || len(rule.Resources) \u003e 0 || len(rule.ResourceNames) \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"nonResourceURLs\"), rule.NonResourceURLs, \"rules cannot apply to both regular resources and non-resource URLs\"))\n\t\t}\n\t\treturn allErrs\n\t}\n\n\tif len(rule.APIGroups) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"apiGroups\"), \"resource rules must supply at least one api group\"))\n\t}\n\tif len(rule.Resources) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"resources\"), \"resource rules must supply at least one resource\"))\n\t}\n\treturn allErrs\n}","line":{"from":102,"to":126}} {"id":100003092,"name":"ValidateRoleBinding","signature":"func ValidateRoleBinding(roleBinding *rbac.RoleBinding) field.ErrorList","file":"pkg/apis/rbac/validation/validation.go","code":"func ValidateRoleBinding(roleBinding *rbac.RoleBinding) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, validation.ValidateObjectMeta(\u0026roleBinding.ObjectMeta, true, ValidateRBACName, field.NewPath(\"metadata\"))...)\n\n\t// TODO allow multiple API groups. For now, restrict to one, but I can envision other experimental roles in other groups taking\n\t// advantage of the binding infrastructure\n\tif roleBinding.RoleRef.APIGroup != rbac.GroupName {\n\t\tallErrs = append(allErrs, field.NotSupported(field.NewPath(\"roleRef\", \"apiGroup\"), roleBinding.RoleRef.APIGroup, []string{rbac.GroupName}))\n\t}\n\n\tswitch roleBinding.RoleRef.Kind {\n\tcase \"Role\", \"ClusterRole\":\n\tdefault:\n\t\tallErrs = append(allErrs, field.NotSupported(field.NewPath(\"roleRef\", \"kind\"), roleBinding.RoleRef.Kind, []string{\"Role\", \"ClusterRole\"}))\n\n\t}\n\n\tif len(roleBinding.RoleRef.Name) == 0 {\n\t\tallErrs = append(allErrs, field.Required(field.NewPath(\"roleRef\", \"name\"), \"\"))\n\t} else {\n\t\tfor _, msg := range ValidateRBACName(roleBinding.RoleRef.Name, false) {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"roleRef\", \"name\"), roleBinding.RoleRef.Name, msg))\n\t\t}\n\t}\n\n\tsubjectsPath := field.NewPath(\"subjects\")\n\tfor i, subject := range roleBinding.Subjects {\n\t\tallErrs = append(allErrs, ValidateRoleBindingSubject(subject, true, subjectsPath.Index(i))...)\n\t}\n\n\treturn allErrs\n}","line":{"from":128,"to":159}} {"id":100003093,"name":"ValidateRoleBindingUpdate","signature":"func ValidateRoleBindingUpdate(roleBinding *rbac.RoleBinding, oldRoleBinding *rbac.RoleBinding) field.ErrorList","file":"pkg/apis/rbac/validation/validation.go","code":"func ValidateRoleBindingUpdate(roleBinding *rbac.RoleBinding, oldRoleBinding *rbac.RoleBinding) field.ErrorList {\n\tallErrs := ValidateRoleBinding(roleBinding)\n\tallErrs = append(allErrs, validation.ValidateObjectMetaUpdate(\u0026roleBinding.ObjectMeta, \u0026oldRoleBinding.ObjectMeta, field.NewPath(\"metadata\"))...)\n\n\tif oldRoleBinding.RoleRef != roleBinding.RoleRef {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"roleRef\"), roleBinding.RoleRef, \"cannot change roleRef\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":161,"to":170}} {"id":100003094,"name":"ValidateClusterRoleBinding","signature":"func ValidateClusterRoleBinding(roleBinding *rbac.ClusterRoleBinding) field.ErrorList","file":"pkg/apis/rbac/validation/validation.go","code":"func ValidateClusterRoleBinding(roleBinding *rbac.ClusterRoleBinding) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, validation.ValidateObjectMeta(\u0026roleBinding.ObjectMeta, false, ValidateRBACName, field.NewPath(\"metadata\"))...)\n\n\t// TODO allow multiple API groups. For now, restrict to one, but I can envision other experimental roles in other groups taking\n\t// advantage of the binding infrastructure\n\tif roleBinding.RoleRef.APIGroup != rbac.GroupName {\n\t\tallErrs = append(allErrs, field.NotSupported(field.NewPath(\"roleRef\", \"apiGroup\"), roleBinding.RoleRef.APIGroup, []string{rbac.GroupName}))\n\t}\n\n\tswitch roleBinding.RoleRef.Kind {\n\tcase \"ClusterRole\":\n\tdefault:\n\t\tallErrs = append(allErrs, field.NotSupported(field.NewPath(\"roleRef\", \"kind\"), roleBinding.RoleRef.Kind, []string{\"ClusterRole\"}))\n\n\t}\n\n\tif len(roleBinding.RoleRef.Name) == 0 {\n\t\tallErrs = append(allErrs, field.Required(field.NewPath(\"roleRef\", \"name\"), \"\"))\n\t} else {\n\t\tfor _, msg := range ValidateRBACName(roleBinding.RoleRef.Name, false) {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"roleRef\", \"name\"), roleBinding.RoleRef.Name, msg))\n\t\t}\n\t}\n\n\tsubjectsPath := field.NewPath(\"subjects\")\n\tfor i, subject := range roleBinding.Subjects {\n\t\tallErrs = append(allErrs, ValidateRoleBindingSubject(subject, false, subjectsPath.Index(i))...)\n\t}\n\n\treturn allErrs\n}","line":{"from":172,"to":203}} {"id":100003095,"name":"ValidateClusterRoleBindingUpdate","signature":"func ValidateClusterRoleBindingUpdate(roleBinding *rbac.ClusterRoleBinding, oldRoleBinding *rbac.ClusterRoleBinding) field.ErrorList","file":"pkg/apis/rbac/validation/validation.go","code":"func ValidateClusterRoleBindingUpdate(roleBinding *rbac.ClusterRoleBinding, oldRoleBinding *rbac.ClusterRoleBinding) field.ErrorList {\n\tallErrs := ValidateClusterRoleBinding(roleBinding)\n\tallErrs = append(allErrs, validation.ValidateObjectMetaUpdate(\u0026roleBinding.ObjectMeta, \u0026oldRoleBinding.ObjectMeta, field.NewPath(\"metadata\"))...)\n\n\tif oldRoleBinding.RoleRef != roleBinding.RoleRef {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"roleRef\"), roleBinding.RoleRef, \"cannot change roleRef\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":205,"to":214}} {"id":100003096,"name":"ValidateRoleBindingSubject","signature":"func ValidateRoleBindingSubject(subject rbac.Subject, isNamespaced bool, fldPath *field.Path) field.ErrorList","file":"pkg/apis/rbac/validation/validation.go","code":"// ValidateRoleBindingSubject is exported to allow types outside of the RBAC API group to embed a rbac.Subject and reuse this validation logic\nfunc ValidateRoleBindingSubject(subject rbac.Subject, isNamespaced bool, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(subject.Name) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"name\"), \"\"))\n\t}\n\n\tswitch subject.Kind {\n\tcase rbac.ServiceAccountKind:\n\t\tif len(subject.Name) \u003e 0 {\n\t\t\tfor _, msg := range validation.ValidateServiceAccountName(subject.Name, false) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"name\"), subject.Name, msg))\n\t\t\t}\n\t\t}\n\t\tif len(subject.APIGroup) \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"apiGroup\"), subject.APIGroup, []string{\"\"}))\n\t\t}\n\t\tif !isNamespaced \u0026\u0026 len(subject.Namespace) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"namespace\"), \"\"))\n\t\t}\n\n\tcase rbac.UserKind:\n\t\t// TODO(ericchiang): What other restrictions on user name are there?\n\t\tif subject.APIGroup != rbac.GroupName {\n\t\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"apiGroup\"), subject.APIGroup, []string{rbac.GroupName}))\n\t\t}\n\n\tcase rbac.GroupKind:\n\t\t// TODO(ericchiang): What other restrictions on group name are there?\n\t\tif subject.APIGroup != rbac.GroupName {\n\t\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"apiGroup\"), subject.APIGroup, []string{rbac.GroupName}))\n\t\t}\n\n\tdefault:\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"kind\"), subject.Kind, []string{rbac.ServiceAccountKind, rbac.UserKind, rbac.GroupKind}))\n\t}\n\n\treturn allErrs\n}","line":{"from":216,"to":255}} {"id":100003097,"name":"init","signature":"func init()","file":"pkg/apis/resource/install/install.go","code":"func init() {\n\tInstall(legacyscheme.Scheme)\n}","line":{"from":29,"to":31}} {"id":100003098,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"pkg/apis/resource/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(resource.AddToScheme(scheme))\n\tutilruntime.Must(v1alpha2.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1alpha2.SchemeGroupVersion))\n}","line":{"from":33,"to":38}} {"id":100003099,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"pkg/apis/resource/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":31,"to":34}} {"id":100003100,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/resource/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":36,"to":39}} {"id":100003101,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/resource/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tif err := scheme.AddIgnoredConversionType(\u0026metav1.TypeMeta{}, \u0026metav1.TypeMeta{}); err != nil {\n\t\treturn err\n\t}\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026ResourceClass{},\n\t\t\u0026ResourceClassList{},\n\t\t\u0026ResourceClaim{},\n\t\t\u0026ResourceClaimList{},\n\t\t\u0026ResourceClaimTemplate{},\n\t\t\u0026ResourceClaimTemplateList{},\n\t\t\u0026PodSchedulingContext{},\n\t\t\u0026PodSchedulingContextList{},\n\t)\n\n\treturn nil\n}","line":{"from":50,"to":66}} {"id":100003102,"name":"addConversionFuncs","signature":"func addConversionFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/resource/v1alpha2/conversion.go","code":"func addConversionFuncs(scheme *runtime.Scheme) error {\n\treturn nil\n}","line":{"from":23,"to":25}} {"id":100003103,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/resource/v1alpha2/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":24,"to":26}} {"id":100003104,"name":"SetDefaults_ResourceClaimSpec","signature":"func SetDefaults_ResourceClaimSpec(obj *v1alpha2.ResourceClaimSpec)","file":"pkg/apis/resource/v1alpha2/defaults.go","code":"func SetDefaults_ResourceClaimSpec(obj *v1alpha2.ResourceClaimSpec) {\n\tif obj.AllocationMode == \"\" {\n\t\tobj.AllocationMode = v1alpha2.AllocationModeWaitForFirstConsumer\n\t}\n}","line":{"from":28,"to":32}} {"id":100003105,"name":"init","signature":"func init()","file":"pkg/apis/resource/v1alpha2/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs, addConversionFuncs)\n}","line":{"from":29,"to":34}} {"id":100003106,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/resource/v1alpha2/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":43,"to":46}} {"id":100003107,"name":"ValidateClaim","signature":"func ValidateClaim(resourceClaim *resource.ResourceClaim) field.ErrorList","file":"pkg/apis/resource/validation/validation.go","code":"// ValidateClaim validates a ResourceClaim.\nfunc ValidateClaim(resourceClaim *resource.ResourceClaim) field.ErrorList {\n\tallErrs := corevalidation.ValidateObjectMeta(\u0026resourceClaim.ObjectMeta, true, corevalidation.ValidateResourceClaimName, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, validateResourceClaimSpec(\u0026resourceClaim.Spec, field.NewPath(\"spec\"))...)\n\treturn allErrs\n}","line":{"from":32,"to":37}} {"id":100003108,"name":"validateResourceClaimSpec","signature":"func validateResourceClaimSpec(spec *resource.ResourceClaimSpec, fldPath *field.Path) field.ErrorList","file":"pkg/apis/resource/validation/validation.go","code":"func validateResourceClaimSpec(spec *resource.ResourceClaimSpec, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor _, msg := range corevalidation.ValidateClassName(spec.ResourceClassName, false) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"resourceClassName\"), spec.ResourceClassName, msg))\n\t}\n\tallErrs = append(allErrs, validateResourceClaimParameters(spec.ParametersRef, fldPath.Child(\"parametersRef\"))...)\n\tif !supportedAllocationModes.Has(string(spec.AllocationMode)) {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"allocationMode\"), spec.AllocationMode, supportedAllocationModes.List()))\n\t}\n\treturn allErrs\n}","line":{"from":39,"to":49}} {"id":100003109,"name":"validateResourceClaimParameters","signature":"func validateResourceClaimParameters(ref *resource.ResourceClaimParametersReference, fldPath *field.Path) field.ErrorList","file":"pkg/apis/resource/validation/validation.go","code":"func validateResourceClaimParameters(ref *resource.ResourceClaimParametersReference, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tif ref != nil {\n\t\tif ref.Kind == \"\" {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"kind\"), \"\"))\n\t\t}\n\t\tif ref.Name == \"\" {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"name\"), \"\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":57,"to":68}} {"id":100003110,"name":"validateClassParameters","signature":"func validateClassParameters(ref *resource.ResourceClassParametersReference, fldPath *field.Path) field.ErrorList","file":"pkg/apis/resource/validation/validation.go","code":"func validateClassParameters(ref *resource.ResourceClassParametersReference, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tif ref != nil {\n\t\tif ref.Kind == \"\" {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"kind\"), \"\"))\n\t\t}\n\t\tif ref.Name == \"\" {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"name\"), \"\"))\n\t\t}\n\t\tif ref.Namespace != \"\" {\n\t\t\tfor _, msg := range apimachineryvalidation.ValidateNamespaceName(ref.Namespace, false) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"namespace\"), ref.Namespace, msg))\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":70,"to":86}} {"id":100003111,"name":"ValidateClass","signature":"func ValidateClass(resourceClass *resource.ResourceClass) field.ErrorList","file":"pkg/apis/resource/validation/validation.go","code":"// ValidateClass validates a ResourceClass.\nfunc ValidateClass(resourceClass *resource.ResourceClass) field.ErrorList {\n\tallErrs := corevalidation.ValidateObjectMeta(\u0026resourceClass.ObjectMeta, false, corevalidation.ValidateClassName, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, validateResourceDriverName(resourceClass.DriverName, field.NewPath(\"driverName\"))...)\n\tallErrs = append(allErrs, validateClassParameters(resourceClass.ParametersRef, field.NewPath(\"parametersRef\"))...)\n\tif resourceClass.SuitableNodes != nil {\n\t\tallErrs = append(allErrs, corevalidation.ValidateNodeSelector(resourceClass.SuitableNodes, field.NewPath(\"suitableNodes\"))...)\n\t}\n\n\treturn allErrs\n}","line":{"from":88,"to":98}} {"id":100003112,"name":"ValidateClassUpdate","signature":"func ValidateClassUpdate(resourceClass, oldClass *resource.ResourceClass) field.ErrorList","file":"pkg/apis/resource/validation/validation.go","code":"// ValidateClassUpdate tests if an update to ResourceClass is valid.\nfunc ValidateClassUpdate(resourceClass, oldClass *resource.ResourceClass) field.ErrorList {\n\tallErrs := corevalidation.ValidateObjectMetaUpdate(\u0026resourceClass.ObjectMeta, \u0026oldClass.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateClass(resourceClass)...)\n\treturn allErrs\n}","line":{"from":100,"to":105}} {"id":100003113,"name":"ValidateClaimUpdate","signature":"func ValidateClaimUpdate(resourceClaim, oldClaim *resource.ResourceClaim) field.ErrorList","file":"pkg/apis/resource/validation/validation.go","code":"// ValidateClaimUpdate tests if an update to ResourceClaim is valid.\nfunc ValidateClaimUpdate(resourceClaim, oldClaim *resource.ResourceClaim) field.ErrorList {\n\tallErrs := corevalidation.ValidateObjectMetaUpdate(\u0026resourceClaim.ObjectMeta, \u0026oldClaim.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, apimachineryvalidation.ValidateImmutableField(resourceClaim.Spec, oldClaim.Spec, field.NewPath(\"spec\"))...)\n\tallErrs = append(allErrs, ValidateClaim(resourceClaim)...)\n\treturn allErrs\n}","line":{"from":107,"to":113}} {"id":100003114,"name":"ValidateClaimStatusUpdate","signature":"func ValidateClaimStatusUpdate(resourceClaim, oldClaim *resource.ResourceClaim) field.ErrorList","file":"pkg/apis/resource/validation/validation.go","code":"// ValidateClaimStatusUpdate tests if an update to the status of a ResourceClaim is valid.\nfunc ValidateClaimStatusUpdate(resourceClaim, oldClaim *resource.ResourceClaim) field.ErrorList {\n\tallErrs := corevalidation.ValidateObjectMetaUpdate(\u0026resourceClaim.ObjectMeta, \u0026oldClaim.ObjectMeta, field.NewPath(\"metadata\"))\n\tfldPath := field.NewPath(\"status\")\n\t// The name might not be set yet.\n\tif resourceClaim.Status.DriverName != \"\" {\n\t\tallErrs = append(allErrs, validateResourceDriverName(resourceClaim.Status.DriverName, fldPath.Child(\"driverName\"))...)\n\t} else if resourceClaim.Status.Allocation != nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"driverName\"), \"must be specified when `allocation` is set\"))\n\t}\n\n\tallErrs = append(allErrs, validateAllocationResult(resourceClaim.Status.Allocation, fldPath.Child(\"allocation\"))...)\n\tallErrs = append(allErrs, validateResourceClaimConsumers(resourceClaim.Status.ReservedFor, resource.ResourceClaimReservedForMaxSize, fldPath.Child(\"reservedFor\"))...)\n\n\t// Now check for invariants that must be valid for a ResourceClaim.\n\tif len(resourceClaim.Status.ReservedFor) \u003e 0 {\n\t\tif resourceClaim.Status.Allocation == nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"reservedFor\"), \"may not be specified when `allocated` is not set\"))\n\t\t} else {\n\t\t\tif !resourceClaim.Status.Allocation.Shareable \u0026\u0026 len(resourceClaim.Status.ReservedFor) \u003e 1 {\n\t\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"reservedFor\"), \"may not be reserved more than once\"))\n\t\t\t}\n\t\t\t// Items may be removed from ReservedFor while the claim is meant to be deallocated,\n\t\t\t// but not added.\n\t\t\tif resourceClaim.DeletionTimestamp != nil || resourceClaim.Status.DeallocationRequested {\n\t\t\t\toldSet := sets.New(oldClaim.Status.ReservedFor...)\n\t\t\t\tnewSet := sets.New(resourceClaim.Status.ReservedFor...)\n\t\t\t\tnewItems := newSet.Difference(oldSet)\n\t\t\t\tif len(newItems) \u003e 0 {\n\t\t\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"reservedFor\"), \"new entries may not be added while `deallocationRequested` or `deletionTimestamp` are set\"))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Updates to a populated resourceClaim.Status.Allocation are not allowed\n\tif oldClaim.Status.Allocation != nil \u0026\u0026 resourceClaim.Status.Allocation != nil {\n\t\tallErrs = append(allErrs, apimachineryvalidation.ValidateImmutableField(resourceClaim.Status.Allocation, oldClaim.Status.Allocation, fldPath.Child(\"allocation\"))...)\n\t}\n\n\tif !oldClaim.Status.DeallocationRequested \u0026\u0026\n\t\tresourceClaim.Status.DeallocationRequested \u0026\u0026\n\t\tlen(resourceClaim.Status.ReservedFor) \u003e 0 {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"deallocationRequested\"), \"deallocation cannot be requested while `reservedFor` is set\"))\n\t}\n\n\tif resourceClaim.Status.Allocation == nil \u0026\u0026\n\t\tresourceClaim.Status.DeallocationRequested {\n\t\t// Either one or the other field was modified incorrectly.\n\t\t// For the sake of simplicity this only reports the invalid\n\t\t// end result.\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath, \"`allocation` must be set when `deallocationRequested` is set\"))\n\t}\n\n\t// Once deallocation has been requested, that request cannot be removed\n\t// anymore because the deallocation may already have started. The field\n\t// can only get reset by the driver together with removing the\n\t// allocation.\n\tif oldClaim.Status.DeallocationRequested \u0026\u0026\n\t\t!resourceClaim.Status.DeallocationRequested \u0026\u0026\n\t\tresourceClaim.Status.Allocation != nil {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"deallocationRequested\"), \"may not be cleared when `allocation` is set\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":115,"to":180}} {"id":100003115,"name":"validateAllocationResult","signature":"func validateAllocationResult(allocation *resource.AllocationResult, fldPath *field.Path) field.ErrorList","file":"pkg/apis/resource/validation/validation.go","code":"func validateAllocationResult(allocation *resource.AllocationResult, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tif allocation != nil {\n\t\tif len(allocation.ResourceHandles) \u003e 0 {\n\t\t\tallErrs = append(allErrs, validateResourceHandles(allocation.ResourceHandles, resource.AllocationResultResourceHandlesMaxSize, fldPath.Child(\"resourceHandles\"))...)\n\t\t}\n\t\tif allocation.AvailableOnNodes != nil {\n\t\t\tallErrs = append(allErrs, corevalidation.ValidateNodeSelector(allocation.AvailableOnNodes, fldPath.Child(\"availableOnNodes\"))...)\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":182,"to":193}} {"id":100003116,"name":"validateResourceHandles","signature":"func validateResourceHandles(resourceHandles []resource.ResourceHandle, maxSize int, fldPath *field.Path) field.ErrorList","file":"pkg/apis/resource/validation/validation.go","code":"func validateResourceHandles(resourceHandles []resource.ResourceHandle, maxSize int, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tfor i, resourceHandle := range resourceHandles {\n\t\tidxPath := fldPath.Index(i)\n\t\tallErrs = append(allErrs, validateResourceDriverName(resourceHandle.DriverName, idxPath.Child(\"driverName\"))...)\n\t\tif len(resourceHandle.Data) \u003e resource.ResourceHandleDataMaxSize {\n\t\t\tallErrs = append(allErrs, field.TooLongMaxLength(idxPath.Child(\"data\"), len(resourceHandle.Data), resource.ResourceHandleDataMaxSize))\n\t\t}\n\t}\n\tif len(resourceHandles) \u003e maxSize {\n\t\t// Dumping the entire field into the error message is likely to be too long,\n\t\t// in particular when it is already beyond the maximum size. Instead this\n\t\t// just shows the number of entries.\n\t\tallErrs = append(allErrs, field.TooLongMaxLength(fldPath, len(resourceHandles), maxSize))\n\t}\n\treturn allErrs\n}","line":{"from":195,"to":211}} {"id":100003117,"name":"validateResourceClaimUserReference","signature":"func validateResourceClaimUserReference(ref resource.ResourceClaimConsumerReference, fldPath *field.Path) field.ErrorList","file":"pkg/apis/resource/validation/validation.go","code":"func validateResourceClaimUserReference(ref resource.ResourceClaimConsumerReference, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tif ref.Resource == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"resource\"), \"\"))\n\t}\n\tif ref.Name == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"name\"), \"\"))\n\t}\n\tif ref.UID == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"uid\"), \"\"))\n\t}\n\treturn allErrs\n}","line":{"from":213,"to":225}} {"id":100003118,"name":"validateSliceIsASet","signature":"func validateSliceIsASet[T comparable](slice []T, maxSize int, validateItem func(item T, fldPath *field.Path) field.ErrorList, fldPath *field.Path) field.ErrorList","file":"pkg/apis/resource/validation/validation.go","code":"// validateSliceIsASet ensures that a slice contains no duplicates and does not exceed a certain maximum size.\nfunc validateSliceIsASet[T comparable](slice []T, maxSize int, validateItem func(item T, fldPath *field.Path) field.ErrorList, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tallItems := sets.New[T]()\n\tfor i, item := range slice {\n\t\tidxPath := fldPath.Index(i)\n\t\tif allItems.Has(item) {\n\t\t\tallErrs = append(allErrs, field.Duplicate(idxPath, item))\n\t\t} else {\n\t\t\tallErrs = append(allErrs, validateItem(item, idxPath)...)\n\t\t\tallItems.Insert(item)\n\t\t}\n\t}\n\tif len(slice) \u003e maxSize {\n\t\t// Dumping the entire field into the error message is likely to be too long,\n\t\t// in particular when it is already beyond the maximum size. Instead this\n\t\t// just shows the number of entries.\n\t\tallErrs = append(allErrs, field.TooLongMaxLength(fldPath, len(slice), maxSize))\n\t}\n\treturn allErrs\n}","line":{"from":227,"to":247}} {"id":100003119,"name":"validateResourceClaimConsumers","signature":"func validateResourceClaimConsumers(consumers []resource.ResourceClaimConsumerReference, maxSize int, fldPath *field.Path) field.ErrorList","file":"pkg/apis/resource/validation/validation.go","code":"// validateResourceClaimConsumers ensures that the slice contains no duplicate UIDs and does not exceed a certain maximum size.\nfunc validateResourceClaimConsumers(consumers []resource.ResourceClaimConsumerReference, maxSize int, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tallUIDs := sets.New[types.UID]()\n\tfor i, consumer := range consumers {\n\t\tidxPath := fldPath.Index(i)\n\t\tif allUIDs.Has(consumer.UID) {\n\t\t\tallErrs = append(allErrs, field.Duplicate(idxPath.Child(\"uid\"), consumer.UID))\n\t\t} else {\n\t\t\tallErrs = append(allErrs, validateResourceClaimUserReference(consumer, idxPath)...)\n\t\t\tallUIDs.Insert(consumer.UID)\n\t\t}\n\t}\n\tif len(consumers) \u003e maxSize {\n\t\t// Dumping the entire field into the error message is likely to be too long,\n\t\t// in particular when it is already beyond the maximum size. Instead this\n\t\t// just shows the number of entries.\n\t\tallErrs = append(allErrs, field.TooLongMaxLength(fldPath, len(consumers), maxSize))\n\t}\n\treturn allErrs\n}","line":{"from":249,"to":269}} {"id":100003120,"name":"ValidatePodSchedulingContexts","signature":"func ValidatePodSchedulingContexts(schedulingCtx *resource.PodSchedulingContext) field.ErrorList","file":"pkg/apis/resource/validation/validation.go","code":"// ValidatePodSchedulingContext validates a PodSchedulingContext.\nfunc ValidatePodSchedulingContexts(schedulingCtx *resource.PodSchedulingContext) field.ErrorList {\n\tallErrs := corevalidation.ValidateObjectMeta(\u0026schedulingCtx.ObjectMeta, true, corevalidation.ValidatePodName, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, validatePodSchedulingSpec(\u0026schedulingCtx.Spec, field.NewPath(\"spec\"))...)\n\treturn allErrs\n}","line":{"from":271,"to":276}} {"id":100003121,"name":"validatePodSchedulingSpec","signature":"func validatePodSchedulingSpec(spec *resource.PodSchedulingContextSpec, fldPath *field.Path) field.ErrorList","file":"pkg/apis/resource/validation/validation.go","code":"func validatePodSchedulingSpec(spec *resource.PodSchedulingContextSpec, fldPath *field.Path) field.ErrorList {\n\tallErrs := validateSliceIsASet(spec.PotentialNodes, resource.PodSchedulingNodeListMaxSize, validateNodeName, fldPath.Child(\"potentialNodes\"))\n\treturn allErrs\n}","line":{"from":278,"to":281}} {"id":100003122,"name":"ValidatePodSchedulingContextUpdate","signature":"func ValidatePodSchedulingContextUpdate(schedulingCtx, oldSchedulingCtx *resource.PodSchedulingContext) field.ErrorList","file":"pkg/apis/resource/validation/validation.go","code":"// ValidatePodSchedulingContextUpdate tests if an update to PodSchedulingContext is valid.\nfunc ValidatePodSchedulingContextUpdate(schedulingCtx, oldSchedulingCtx *resource.PodSchedulingContext) field.ErrorList {\n\tallErrs := corevalidation.ValidateObjectMetaUpdate(\u0026schedulingCtx.ObjectMeta, \u0026oldSchedulingCtx.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidatePodSchedulingContexts(schedulingCtx)...)\n\treturn allErrs\n}","line":{"from":283,"to":288}} {"id":100003123,"name":"ValidatePodSchedulingContextStatusUpdate","signature":"func ValidatePodSchedulingContextStatusUpdate(schedulingCtx, oldSchedulingCtx *resource.PodSchedulingContext) field.ErrorList","file":"pkg/apis/resource/validation/validation.go","code":"// ValidatePodSchedulingContextStatusUpdate tests if an update to the status of a PodSchedulingContext is valid.\nfunc ValidatePodSchedulingContextStatusUpdate(schedulingCtx, oldSchedulingCtx *resource.PodSchedulingContext) field.ErrorList {\n\tallErrs := corevalidation.ValidateObjectMetaUpdate(\u0026schedulingCtx.ObjectMeta, \u0026oldSchedulingCtx.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, validatePodSchedulingStatus(\u0026schedulingCtx.Status, field.NewPath(\"status\"))...)\n\treturn allErrs\n}","line":{"from":290,"to":295}} {"id":100003124,"name":"validatePodSchedulingStatus","signature":"func validatePodSchedulingStatus(status *resource.PodSchedulingContextStatus, fldPath *field.Path) field.ErrorList","file":"pkg/apis/resource/validation/validation.go","code":"func validatePodSchedulingStatus(status *resource.PodSchedulingContextStatus, fldPath *field.Path) field.ErrorList {\n\treturn validatePodSchedulingClaims(status.ResourceClaims, fldPath.Child(\"claims\"))\n}","line":{"from":297,"to":299}} {"id":100003125,"name":"validatePodSchedulingClaims","signature":"func validatePodSchedulingClaims(claimStatuses []resource.ResourceClaimSchedulingStatus, fldPath *field.Path) field.ErrorList","file":"pkg/apis/resource/validation/validation.go","code":"func validatePodSchedulingClaims(claimStatuses []resource.ResourceClaimSchedulingStatus, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tnames := sets.NewString()\n\tfor i, claimStatus := range claimStatuses {\n\t\tallErrs = append(allErrs, validatePodSchedulingClaim(claimStatus, fldPath.Index(i))...)\n\t\tif names.Has(claimStatus.Name) {\n\t\t\tallErrs = append(allErrs, field.Duplicate(fldPath.Index(i), claimStatus.Name))\n\t\t} else {\n\t\t\tnames.Insert(claimStatus.Name)\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":301,"to":313}} {"id":100003126,"name":"validatePodSchedulingClaim","signature":"func validatePodSchedulingClaim(status resource.ResourceClaimSchedulingStatus, fldPath *field.Path) field.ErrorList","file":"pkg/apis/resource/validation/validation.go","code":"func validatePodSchedulingClaim(status resource.ResourceClaimSchedulingStatus, fldPath *field.Path) field.ErrorList {\n\tallErrs := validateSliceIsASet(status.UnsuitableNodes, resource.PodSchedulingNodeListMaxSize, validateNodeName, fldPath.Child(\"unsuitableNodes\"))\n\treturn allErrs\n}","line":{"from":315,"to":318}} {"id":100003127,"name":"ValidateClaimTemplate","signature":"func ValidateClaimTemplate(template *resource.ResourceClaimTemplate) field.ErrorList","file":"pkg/apis/resource/validation/validation.go","code":"// ValidateClaimTemplace validates a ResourceClaimTemplate.\nfunc ValidateClaimTemplate(template *resource.ResourceClaimTemplate) field.ErrorList {\n\tallErrs := corevalidation.ValidateObjectMeta(\u0026template.ObjectMeta, true, corevalidation.ValidateResourceClaimTemplateName, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, validateResourceClaimTemplateSpec(\u0026template.Spec, field.NewPath(\"spec\"))...)\n\treturn allErrs\n}","line":{"from":320,"to":325}} {"id":100003128,"name":"validateResourceClaimTemplateSpec","signature":"func validateResourceClaimTemplateSpec(spec *resource.ResourceClaimTemplateSpec, fldPath *field.Path) field.ErrorList","file":"pkg/apis/resource/validation/validation.go","code":"func validateResourceClaimTemplateSpec(spec *resource.ResourceClaimTemplateSpec, fldPath *field.Path) field.ErrorList {\n\tallErrs := corevalidation.ValidateTemplateObjectMeta(\u0026spec.ObjectMeta, fldPath.Child(\"metadata\"))\n\tallErrs = append(allErrs, validateResourceClaimSpec(\u0026spec.Spec, fldPath.Child(\"spec\"))...)\n\treturn allErrs\n}","line":{"from":327,"to":331}} {"id":100003129,"name":"ValidateClaimTemplateUpdate","signature":"func ValidateClaimTemplateUpdate(template, oldTemplate *resource.ResourceClaimTemplate) field.ErrorList","file":"pkg/apis/resource/validation/validation.go","code":"// ValidateClaimTemplateUpdate tests if an update to template is valid.\nfunc ValidateClaimTemplateUpdate(template, oldTemplate *resource.ResourceClaimTemplate) field.ErrorList {\n\tallErrs := corevalidation.ValidateObjectMetaUpdate(\u0026template.ObjectMeta, \u0026oldTemplate.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, apimachineryvalidation.ValidateImmutableField(template.Spec, oldTemplate.Spec, field.NewPath(\"spec\"))...)\n\tallErrs = append(allErrs, ValidateClaimTemplate(template)...)\n\treturn allErrs\n}","line":{"from":333,"to":339}} {"id":100003130,"name":"validateNodeName","signature":"func validateNodeName(name string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/resource/validation/validation.go","code":"func validateNodeName(name string, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tfor _, msg := range corevalidation.ValidateNodeName(name, false) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, name, msg))\n\t}\n\treturn allErrs\n}","line":{"from":341,"to":347}} {"id":100003131,"name":"init","signature":"func init()","file":"pkg/apis/scheduling/install/install.go","code":"func init() {\n\tInstall(legacyscheme.Scheme)\n}","line":{"from":31,"to":33}} {"id":100003132,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"pkg/apis/scheduling/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(scheduling.AddToScheme(scheme))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(v1alpha1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1.SchemeGroupVersion, v1beta1.SchemeGroupVersion, v1alpha1.SchemeGroupVersion))\n}","line":{"from":35,"to":42}} {"id":100003133,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"pkg/apis/scheduling/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100003134,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/scheduling/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100003135,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/scheduling/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026PriorityClass{},\n\t\t\u0026PriorityClassList{},\n\t)\n\treturn nil\n}","line":{"from":47,"to":53}} {"id":100003136,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/scheduling/v1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":25,"to":27}} {"id":100003137,"name":"SetDefaults_PriorityClass","signature":"func SetDefaults_PriorityClass(obj *v1.PriorityClass)","file":"pkg/apis/scheduling/v1/defaults.go","code":"// SetDefaults_PriorityClass sets additional defaults compared to its counterpart\n// in extensions.\nfunc SetDefaults_PriorityClass(obj *v1.PriorityClass) {\n\tif obj.PreemptionPolicy == nil {\n\t\tpreemptLowerPriority := apiv1.PreemptLowerPriority\n\t\tobj.PreemptionPolicy = \u0026preemptLowerPriority\n\t}\n}","line":{"from":29,"to":36}} {"id":100003138,"name":"SystemPriorityClasses","signature":"func SystemPriorityClasses() []*v1.PriorityClass","file":"pkg/apis/scheduling/v1/helpers.go","code":"// SystemPriorityClasses returns the list of system priority classes.\n// NOTE: be careful not to modify any of elements of the returned array directly.\nfunc SystemPriorityClasses() []*v1.PriorityClass {\n\treturn systemPriorityClasses\n}","line":{"from":46,"to":50}} {"id":100003139,"name":"IsKnownSystemPriorityClass","signature":"func IsKnownSystemPriorityClass(name string, value int32, globalDefault bool) (bool, error)","file":"pkg/apis/scheduling/v1/helpers.go","code":"// IsKnownSystemPriorityClass returns true if there's any of the system priority classes exactly\n// matches \"name\", \"value\", \"globalDefault\". otherwise it will return an error.\nfunc IsKnownSystemPriorityClass(name string, value int32, globalDefault bool) (bool, error) {\n\tfor _, spc := range SystemPriorityClasses() {\n\t\tif spc.Name == name {\n\t\t\tif spc.Value != value {\n\t\t\t\treturn false, fmt.Errorf(\"value of %v PriorityClass must be %v\", spc.Name, spc.Value)\n\t\t\t}\n\t\t\tif spc.GlobalDefault != globalDefault {\n\t\t\t\treturn false, fmt.Errorf(\"globalDefault of %v PriorityClass must be %v\", spc.Name, spc.GlobalDefault)\n\t\t\t}\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, fmt.Errorf(\"%v is not a known system priority class\", name)\n}","line":{"from":52,"to":67}} {"id":100003140,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/scheduling/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100003141,"name":"init","signature":"func init()","file":"pkg/apis/scheduling/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":41,"to":46}} {"id":100003142,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/scheduling/v1alpha1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":25,"to":27}} {"id":100003143,"name":"SetDefaults_PriorityClass","signature":"func SetDefaults_PriorityClass(obj *v1alpha1.PriorityClass)","file":"pkg/apis/scheduling/v1alpha1/defaults.go","code":"// SetDefaults_PriorityClass sets additional defaults compared to its counterpart\n// in extensions.\nfunc SetDefaults_PriorityClass(obj *v1alpha1.PriorityClass) {\n\tif obj.PreemptionPolicy == nil {\n\t\tpreemptLowerPriority := apiv1.PreemptLowerPriority\n\t\tobj.PreemptionPolicy = \u0026preemptLowerPriority\n\t}\n}","line":{"from":29,"to":36}} {"id":100003144,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/scheduling/v1alpha1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100003145,"name":"init","signature":"func init()","file":"pkg/apis/scheduling/v1alpha1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":41,"to":46}} {"id":100003146,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/scheduling/v1beta1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":25,"to":27}} {"id":100003147,"name":"SetDefaults_PriorityClass","signature":"func SetDefaults_PriorityClass(obj *v1beta1.PriorityClass)","file":"pkg/apis/scheduling/v1beta1/defaults.go","code":"// SetDefaults_PriorityClass sets additional defaults compared to its counterpart\n// in extensions.\nfunc SetDefaults_PriorityClass(obj *v1beta1.PriorityClass) {\n\tif obj.PreemptionPolicy == nil {\n\t\tpreemptLowerPriority := apiv1.PreemptLowerPriority\n\t\tobj.PreemptionPolicy = \u0026preemptLowerPriority\n\t}\n}","line":{"from":29,"to":36}} {"id":100003148,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/scheduling/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100003149,"name":"init","signature":"func init()","file":"pkg/apis/scheduling/v1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":41,"to":46}} {"id":100003150,"name":"ValidatePriorityClass","signature":"func ValidatePriorityClass(pc *scheduling.PriorityClass) field.ErrorList","file":"pkg/apis/scheduling/validation/validation.go","code":"// ValidatePriorityClass tests whether required fields in the PriorityClass are\n// set correctly.\nfunc ValidatePriorityClass(pc *scheduling.PriorityClass) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, apivalidation.ValidateObjectMeta(\u0026pc.ObjectMeta, false, apimachineryvalidation.NameIsDNSSubdomain, field.NewPath(\"metadata\"))...)\n\t// If the priorityClass starts with a system prefix, it must be one of the\n\t// predefined system priority classes.\n\tif strings.HasPrefix(pc.Name, scheduling.SystemPriorityClassPrefix) {\n\t\tif is, err := schedulingapiv1.IsKnownSystemPriorityClass(pc.Name, pc.Value, pc.GlobalDefault); !is {\n\t\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"metadata\", \"name\"), \"priority class names with '\"+scheduling.SystemPriorityClassPrefix+\"' prefix are reserved for system use only. error: \"+err.Error()))\n\t\t}\n\t} else if pc.Value \u003e scheduling.HighestUserDefinablePriority {\n\t\t// Non-system critical priority classes are not allowed to have a value larger than HighestUserDefinablePriority.\n\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"value\"), fmt.Sprintf(\"maximum allowed value of a user defined priority is %v\", scheduling.HighestUserDefinablePriority)))\n\t}\n\tif pc.PreemptionPolicy != nil {\n\t\tallErrs = append(allErrs, apivalidation.ValidatePreemptionPolicy(pc.PreemptionPolicy, field.NewPath(\"preemptionPolicy\"))...)\n\t}\n\treturn allErrs\n}","line":{"from":30,"to":49}} {"id":100003151,"name":"ValidatePriorityClassUpdate","signature":"func ValidatePriorityClassUpdate(pc, oldPc *scheduling.PriorityClass) field.ErrorList","file":"pkg/apis/scheduling/validation/validation.go","code":"// ValidatePriorityClassUpdate tests if required fields in the PriorityClass are\n// set and are valid. PriorityClass does not allow updating name, value, and preemptionPolicy.\nfunc ValidatePriorityClassUpdate(pc, oldPc *scheduling.PriorityClass) field.ErrorList {\n\t// name is immutable and is checked by the ObjectMeta validator.\n\tallErrs := apivalidation.ValidateObjectMetaUpdate(\u0026pc.ObjectMeta, \u0026oldPc.ObjectMeta, field.NewPath(\"metadata\"))\n\t// value is immutable.\n\tif pc.Value != oldPc.Value {\n\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"value\"), \"may not be changed in an update.\"))\n\t}\n\t// preemptionPolicy is immutable.\n\tallErrs = append(allErrs, apivalidation.ValidateImmutableField(pc.PreemptionPolicy, oldPc.PreemptionPolicy, field.NewPath(\"preemptionPolicy\"))...)\n\treturn allErrs\n}","line":{"from":51,"to":63}} {"id":100003152,"name":"init","signature":"func init()","file":"pkg/apis/storage/install/install.go","code":"func init() {\n\tInstall(legacyscheme.Scheme)\n}","line":{"from":31,"to":33}} {"id":100003153,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"pkg/apis/storage/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(storage.AddToScheme(scheme))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(v1alpha1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1.SchemeGroupVersion, v1beta1.SchemeGroupVersion, v1alpha1.SchemeGroupVersion))\n}","line":{"from":35,"to":42}} {"id":100003154,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"pkg/apis/storage/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100003155,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/storage/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100003156,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/apis/storage/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026StorageClass{},\n\t\t\u0026StorageClassList{},\n\t\t\u0026VolumeAttachment{},\n\t\t\u0026VolumeAttachmentList{},\n\t\t\u0026CSINode{},\n\t\t\u0026CSINodeList{},\n\t\t\u0026CSIDriver{},\n\t\t\u0026CSIDriverList{},\n\t\t\u0026CSIStorageCapacity{},\n\t\t\u0026CSIStorageCapacityList{},\n\t)\n\treturn nil\n}","line":{"from":45,"to":59}} {"id":100003157,"name":"IsDefaultAnnotationText","signature":"func IsDefaultAnnotationText(obj metav1.ObjectMeta) string","file":"pkg/apis/storage/util/helpers.go","code":"// IsDefaultAnnotationText returns a pretty Yes/No String if\n// the annotation is set\n// TODO: remove Beta when no longer needed\nfunc IsDefaultAnnotationText(obj metav1.ObjectMeta) string {\n\tif obj.Annotations[IsDefaultStorageClassAnnotation] == \"true\" {\n\t\treturn \"Yes\"\n\t}\n\tif obj.Annotations[BetaIsDefaultStorageClassAnnotation] == \"true\" {\n\t\treturn \"Yes\"\n\t}\n\n\treturn \"No\"\n}","line":{"from":29,"to":41}} {"id":100003158,"name":"IsDefaultAnnotation","signature":"func IsDefaultAnnotation(obj metav1.ObjectMeta) bool","file":"pkg/apis/storage/util/helpers.go","code":"// IsDefaultAnnotation returns a boolean if\n// the annotation is set\n// TODO: remove Beta when no longer needed\nfunc IsDefaultAnnotation(obj metav1.ObjectMeta) bool {\n\tif obj.Annotations[IsDefaultStorageClassAnnotation] == \"true\" {\n\t\treturn true\n\t}\n\tif obj.Annotations[BetaIsDefaultStorageClassAnnotation] == \"true\" {\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":43,"to":55}} {"id":100003159,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/storage/v1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":27,"to":29}} {"id":100003160,"name":"SetDefaults_StorageClass","signature":"func SetDefaults_StorageClass(obj *storagev1.StorageClass)","file":"pkg/apis/storage/v1/defaults.go","code":"func SetDefaults_StorageClass(obj *storagev1.StorageClass) {\n\tif obj.ReclaimPolicy == nil {\n\t\tobj.ReclaimPolicy = new(v1.PersistentVolumeReclaimPolicy)\n\t\t*obj.ReclaimPolicy = v1.PersistentVolumeReclaimDelete\n\t}\n\n\tif obj.VolumeBindingMode == nil {\n\t\tobj.VolumeBindingMode = new(storagev1.VolumeBindingMode)\n\t\t*obj.VolumeBindingMode = storagev1.VolumeBindingImmediate\n\t}\n}","line":{"from":31,"to":41}} {"id":100003161,"name":"SetDefaults_CSIDriver","signature":"func SetDefaults_CSIDriver(obj *storagev1.CSIDriver)","file":"pkg/apis/storage/v1/defaults.go","code":"func SetDefaults_CSIDriver(obj *storagev1.CSIDriver) {\n\tif obj.Spec.AttachRequired == nil {\n\t\tobj.Spec.AttachRequired = new(bool)\n\t\t*(obj.Spec.AttachRequired) = true\n\t}\n\tif obj.Spec.PodInfoOnMount == nil {\n\t\tobj.Spec.PodInfoOnMount = new(bool)\n\t\t*(obj.Spec.PodInfoOnMount) = false\n\t}\n\tif obj.Spec.StorageCapacity == nil {\n\t\tobj.Spec.StorageCapacity = new(bool)\n\t\t*(obj.Spec.StorageCapacity) = false\n\t}\n\tif obj.Spec.FSGroupPolicy == nil {\n\t\tobj.Spec.FSGroupPolicy = new(storagev1.FSGroupPolicy)\n\t\t*obj.Spec.FSGroupPolicy = storagev1.ReadWriteOnceWithFSTypeFSGroupPolicy\n\t}\n\tif len(obj.Spec.VolumeLifecycleModes) == 0 {\n\t\tobj.Spec.VolumeLifecycleModes = append(obj.Spec.VolumeLifecycleModes, storagev1.VolumeLifecyclePersistent)\n\t}\n\tif obj.Spec.RequiresRepublish == nil {\n\t\tobj.Spec.RequiresRepublish = new(bool)\n\t\t*(obj.Spec.RequiresRepublish) = false\n\t}\n\tif obj.Spec.SELinuxMount == nil \u0026\u0026 utilfeature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {\n\t\tobj.Spec.SELinuxMount = new(bool)\n\t\t*(obj.Spec.SELinuxMount) = false\n\t}\n}","line":{"from":43,"to":71}} {"id":100003162,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/storage/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100003163,"name":"init","signature":"func init()","file":"pkg/apis/storage/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":40,"to":45}} {"id":100003164,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/storage/v1alpha1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100003165,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/apis/storage/v1beta1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":27,"to":29}} {"id":100003166,"name":"SetDefaults_StorageClass","signature":"func SetDefaults_StorageClass(obj *storagev1beta1.StorageClass)","file":"pkg/apis/storage/v1beta1/defaults.go","code":"func SetDefaults_StorageClass(obj *storagev1beta1.StorageClass) {\n\tif obj.ReclaimPolicy == nil {\n\t\tobj.ReclaimPolicy = new(v1.PersistentVolumeReclaimPolicy)\n\t\t*obj.ReclaimPolicy = v1.PersistentVolumeReclaimDelete\n\t}\n\n\tif obj.VolumeBindingMode == nil {\n\t\tobj.VolumeBindingMode = new(storagev1beta1.VolumeBindingMode)\n\t\t*obj.VolumeBindingMode = storagev1beta1.VolumeBindingImmediate\n\t}\n}","line":{"from":31,"to":41}} {"id":100003167,"name":"SetDefaults_CSIDriver","signature":"func SetDefaults_CSIDriver(obj *storagev1beta1.CSIDriver)","file":"pkg/apis/storage/v1beta1/defaults.go","code":"func SetDefaults_CSIDriver(obj *storagev1beta1.CSIDriver) {\n\tif obj.Spec.AttachRequired == nil {\n\t\tobj.Spec.AttachRequired = new(bool)\n\t\t*(obj.Spec.AttachRequired) = true\n\t}\n\tif obj.Spec.PodInfoOnMount == nil {\n\t\tobj.Spec.PodInfoOnMount = new(bool)\n\t\t*(obj.Spec.PodInfoOnMount) = false\n\t}\n\tif obj.Spec.StorageCapacity == nil {\n\t\tobj.Spec.StorageCapacity = new(bool)\n\t\t*(obj.Spec.StorageCapacity) = false\n\t}\n\tif obj.Spec.FSGroupPolicy == nil {\n\t\tobj.Spec.FSGroupPolicy = new(storagev1beta1.FSGroupPolicy)\n\t\t*obj.Spec.FSGroupPolicy = storagev1beta1.ReadWriteOnceWithFSTypeFSGroupPolicy\n\t}\n\tif len(obj.Spec.VolumeLifecycleModes) == 0 {\n\t\tobj.Spec.VolumeLifecycleModes = append(obj.Spec.VolumeLifecycleModes, storagev1beta1.VolumeLifecyclePersistent)\n\t}\n\tif obj.Spec.RequiresRepublish == nil {\n\t\tobj.Spec.RequiresRepublish = new(bool)\n\t\t*(obj.Spec.RequiresRepublish) = false\n\t}\n\tif obj.Spec.SELinuxMount == nil \u0026\u0026 utilfeature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {\n\t\tobj.Spec.SELinuxMount = new(bool)\n\t\t*(obj.Spec.SELinuxMount) = false\n\t}\n}","line":{"from":43,"to":71}} {"id":100003168,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"pkg/apis/storage/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100003169,"name":"init","signature":"func init()","file":"pkg/apis/storage/v1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":40,"to":45}} {"id":100003170,"name":"ValidateStorageClass","signature":"func ValidateStorageClass(storageClass *storage.StorageClass) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// ValidateStorageClass validates a StorageClass.\nfunc ValidateStorageClass(storageClass *storage.StorageClass) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMeta(\u0026storageClass.ObjectMeta, false, apivalidation.ValidateClassName, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, validateProvisioner(storageClass.Provisioner, field.NewPath(\"provisioner\"))...)\n\tallErrs = append(allErrs, validateParameters(storageClass.Parameters, field.NewPath(\"parameters\"))...)\n\tallErrs = append(allErrs, validateReclaimPolicy(storageClass.ReclaimPolicy, field.NewPath(\"reclaimPolicy\"))...)\n\tallErrs = append(allErrs, validateVolumeBindingMode(storageClass.VolumeBindingMode, field.NewPath(\"volumeBindingMode\"))...)\n\tallErrs = append(allErrs, validateAllowedTopologies(storageClass.AllowedTopologies, field.NewPath(\"allowedTopologies\"))...)\n\n\treturn allErrs\n}","line":{"from":54,"to":64}} {"id":100003171,"name":"ValidateStorageClassUpdate","signature":"func ValidateStorageClassUpdate(storageClass, oldStorageClass *storage.StorageClass) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// ValidateStorageClassUpdate tests if an update to StorageClass is valid.\nfunc ValidateStorageClassUpdate(storageClass, oldStorageClass *storage.StorageClass) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMetaUpdate(\u0026storageClass.ObjectMeta, \u0026oldStorageClass.ObjectMeta, field.NewPath(\"metadata\"))\n\tif !reflect.DeepEqual(oldStorageClass.Parameters, storageClass.Parameters) {\n\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"parameters\"), \"updates to parameters are forbidden.\"))\n\t}\n\n\tif storageClass.Provisioner != oldStorageClass.Provisioner {\n\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"provisioner\"), \"updates to provisioner are forbidden.\"))\n\t}\n\n\tif *storageClass.ReclaimPolicy != *oldStorageClass.ReclaimPolicy {\n\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"reclaimPolicy\"), \"updates to reclaimPolicy are forbidden.\"))\n\t}\n\n\tallErrs = append(allErrs, apivalidation.ValidateImmutableField(storageClass.VolumeBindingMode, oldStorageClass.VolumeBindingMode, field.NewPath(\"volumeBindingMode\"))...)\n\treturn allErrs\n}","line":{"from":66,"to":83}} {"id":100003172,"name":"validateProvisioner","signature":"func validateProvisioner(provisioner string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// validateProvisioner tests if provisioner is a valid qualified name.\nfunc validateProvisioner(provisioner string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(provisioner) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath, provisioner))\n\t}\n\tif len(provisioner) \u003e 0 {\n\t\tallErrs = append(allErrs, apivalidation.ValidateQualifiedName(strings.ToLower(provisioner), fldPath)...)\n\t}\n\treturn allErrs\n}","line":{"from":85,"to":95}} {"id":100003173,"name":"validateParameters","signature":"func validateParameters(params map[string]string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// validateParameters tests that keys are qualified names and that provisionerParameter are \u003c 256kB.\nfunc validateParameters(params map[string]string, fldPath *field.Path) field.ErrorList {\n\tvar totalSize int64\n\tallErrs := field.ErrorList{}\n\n\tif len(params) \u003e maxProvisionerParameterLen {\n\t\tallErrs = append(allErrs, field.TooLong(fldPath, \"Provisioner Parameters exceeded max allowed\", maxProvisionerParameterLen))\n\t\treturn allErrs\n\t}\n\n\tfor k, v := range params {\n\t\tif len(k) \u003c 1 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, k, \"field can not be empty.\"))\n\t\t}\n\t\ttotalSize += (int64)(len(k)) + (int64)(len(v))\n\t}\n\n\tif totalSize \u003e maxProvisionerParameterSize {\n\t\tallErrs = append(allErrs, field.TooLong(fldPath, \"\", maxProvisionerParameterSize))\n\t}\n\treturn allErrs\n}","line":{"from":97,"to":118}} {"id":100003174,"name":"validateReclaimPolicy","signature":"func validateReclaimPolicy(reclaimPolicy *api.PersistentVolumeReclaimPolicy, fldPath *field.Path) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// validateReclaimPolicy tests that the reclaim policy is one of the supported. It is up to the volume plugin to reject\n// provisioning for storage classes with impossible reclaim policies, e.g. EBS is not Recyclable\nfunc validateReclaimPolicy(reclaimPolicy *api.PersistentVolumeReclaimPolicy, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(string(*reclaimPolicy)) \u003e 0 {\n\t\tif !supportedReclaimPolicy.Has(string(*reclaimPolicy)) {\n\t\t\tallErrs = append(allErrs, field.NotSupported(fldPath, reclaimPolicy, supportedReclaimPolicy.List()))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":122,"to":132}} {"id":100003175,"name":"ValidateVolumeAttachment","signature":"func ValidateVolumeAttachment(volumeAttachment *storage.VolumeAttachment) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// ValidateVolumeAttachment validates a VolumeAttachment. This function is common for v1 and v1beta1 objects,\nfunc ValidateVolumeAttachment(volumeAttachment *storage.VolumeAttachment) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMeta(\u0026volumeAttachment.ObjectMeta, false, apivalidation.ValidateClassName, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, validateVolumeAttachmentSpec(\u0026volumeAttachment.Spec, field.NewPath(\"spec\"))...)\n\tallErrs = append(allErrs, validateVolumeAttachmentStatus(\u0026volumeAttachment.Status, field.NewPath(\"status\"))...)\n\treturn allErrs\n}","line":{"from":134,"to":140}} {"id":100003176,"name":"ValidateVolumeAttachmentV1","signature":"func ValidateVolumeAttachmentV1(volumeAttachment *storage.VolumeAttachment) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// ValidateVolumeAttachmentV1 validates a v1/VolumeAttachment. It contains only extra checks missing in\n// ValidateVolumeAttachment.\nfunc ValidateVolumeAttachmentV1(volumeAttachment *storage.VolumeAttachment) field.ErrorList {\n\tallErrs := apivalidation.ValidateCSIDriverName(volumeAttachment.Spec.Attacher, field.NewPath(\"spec.attacher\"))\n\n\tif volumeAttachment.Spec.Source.PersistentVolumeName != nil {\n\t\tpvName := *volumeAttachment.Spec.Source.PersistentVolumeName\n\t\tfor _, msg := range apivalidation.ValidatePersistentVolumeName(pvName, false) {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"spec.source.persistentVolumeName\"), pvName, msg))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":142,"to":154}} {"id":100003177,"name":"validateVolumeAttachmentSpec","signature":"func validateVolumeAttachmentSpec(","file":"pkg/apis/storage/validation/validation.go","code":"// ValidateVolumeAttachmentSpec tests that the specified VolumeAttachmentSpec\n// has valid data.\nfunc validateVolumeAttachmentSpec(\n\tspec *storage.VolumeAttachmentSpec, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, validateAttacher(spec.Attacher, fldPath.Child(\"attacher\"))...)\n\tallErrs = append(allErrs, validateVolumeAttachmentSource(\u0026spec.Source, fldPath.Child(\"source\"))...)\n\tallErrs = append(allErrs, validateNodeName(spec.NodeName, fldPath.Child(\"nodeName\"))...)\n\treturn allErrs\n}","line":{"from":156,"to":165}} {"id":100003178,"name":"validateAttacher","signature":"func validateAttacher(attacher string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// validateAttacher tests if attacher is a valid qualified name.\nfunc validateAttacher(attacher string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(attacher) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath, attacher))\n\t}\n\treturn allErrs\n}","line":{"from":167,"to":174}} {"id":100003179,"name":"validateVolumeAttachmentSource","signature":"func validateVolumeAttachmentSource(source *storage.VolumeAttachmentSource, fldPath *field.Path) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// validateSource tests if the source is valid for VolumeAttachment.\nfunc validateVolumeAttachmentSource(source *storage.VolumeAttachmentSource, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tswitch {\n\tcase source.InlineVolumeSpec == nil \u0026\u0026 source.PersistentVolumeName == nil:\n\t\tallErrs = append(allErrs, field.Required(fldPath, \"must specify exactly one of inlineVolumeSpec and persistentVolumeName\"))\n\tcase source.InlineVolumeSpec != nil \u0026\u0026 source.PersistentVolumeName != nil:\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath, \"must specify exactly one of inlineVolumeSpec and persistentVolumeName\"))\n\tcase source.PersistentVolumeName != nil:\n\t\tif len(*source.PersistentVolumeName) == 0 {\n\t\t\t// Invalid err\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"persistentVolumeName\"), \"must specify non empty persistentVolumeName\"))\n\t\t}\n\tcase source.InlineVolumeSpec != nil:\n\t\topts := apivalidation.PersistentVolumeSpecValidationOptions{}\n\t\tallErrs = append(allErrs, apivalidation.ValidatePersistentVolumeSpec(source.InlineVolumeSpec, \"\", true, fldPath.Child(\"inlineVolumeSpec\"), opts)...)\n\t}\n\treturn allErrs\n}","line":{"from":176,"to":194}} {"id":100003180,"name":"validateNodeName","signature":"func validateNodeName(nodeName string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// validateNodeName tests if the nodeName is valid for VolumeAttachment.\nfunc validateNodeName(nodeName string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor _, msg := range apivalidation.ValidateNodeName(nodeName, false /* prefix */) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, nodeName, msg))\n\t}\n\treturn allErrs\n}","line":{"from":196,"to":203}} {"id":100003181,"name":"validateVolumeAttachmentStatus","signature":"func validateVolumeAttachmentStatus(status *storage.VolumeAttachmentStatus, fldPath *field.Path) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// validaVolumeAttachmentStatus tests if volumeAttachmentStatus is valid.\nfunc validateVolumeAttachmentStatus(status *storage.VolumeAttachmentStatus, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, validateAttachmentMetadata(status.AttachmentMetadata, fldPath.Child(\"attachmentMetadata\"))...)\n\tallErrs = append(allErrs, validateVolumeError(status.AttachError, fldPath.Child(\"attachError\"))...)\n\tallErrs = append(allErrs, validateVolumeError(status.DetachError, fldPath.Child(\"detachError\"))...)\n\treturn allErrs\n}","line":{"from":205,"to":212}} {"id":100003182,"name":"validateAttachmentMetadata","signature":"func validateAttachmentMetadata(metadata map[string]string, fldPath *field.Path) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"func validateAttachmentMetadata(metadata map[string]string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tvar size int64\n\tfor k, v := range metadata {\n\t\tsize += (int64)(len(k)) + (int64)(len(v))\n\t}\n\tif size \u003e maxAttachedVolumeMetadataSize {\n\t\tallErrs = append(allErrs, field.TooLong(fldPath, metadata, maxAttachedVolumeMetadataSize))\n\t}\n\treturn allErrs\n}","line":{"from":214,"to":225}} {"id":100003183,"name":"validateVolumeError","signature":"func validateVolumeError(e *storage.VolumeError, fldPath *field.Path) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"func validateVolumeError(e *storage.VolumeError, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif e == nil {\n\t\treturn allErrs\n\t}\n\tif len(e.Message) \u003e maxVolumeErrorMessageSize {\n\t\tallErrs = append(allErrs, field.TooLong(fldPath.Child(\"message\"), e.Message, maxAttachedVolumeMetadataSize))\n\t}\n\treturn allErrs\n}","line":{"from":227,"to":237}} {"id":100003184,"name":"ValidateVolumeAttachmentUpdate","signature":"func ValidateVolumeAttachmentUpdate(new, old *storage.VolumeAttachment) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// ValidateVolumeAttachmentUpdate validates a VolumeAttachment.\nfunc ValidateVolumeAttachmentUpdate(new, old *storage.VolumeAttachment) field.ErrorList {\n\tallErrs := ValidateVolumeAttachment(new)\n\n\t// Spec is read-only\n\t// If this ever relaxes in the future, make sure to increment the Generation number in PrepareForUpdate\n\tif !apiequality.Semantic.DeepEqual(old.Spec, new.Spec) {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"spec\"), new.Spec, \"field is immutable\"))\n\t}\n\treturn allErrs\n}","line":{"from":239,"to":249}} {"id":100003185,"name":"validateVolumeBindingMode","signature":"func validateVolumeBindingMode(mode *storage.VolumeBindingMode, fldPath *field.Path) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// validateVolumeBindingMode tests that VolumeBindingMode specifies valid values.\nfunc validateVolumeBindingMode(mode *storage.VolumeBindingMode, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif mode == nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath, \"\"))\n\t} else if !supportedVolumeBindingModes.Has(string(*mode)) {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath, mode, supportedVolumeBindingModes.List()))\n\t}\n\n\treturn allErrs\n}","line":{"from":253,"to":263}} {"id":100003186,"name":"validateAllowedTopologies","signature":"func validateAllowedTopologies(topologies []api.TopologySelectorTerm, fldPath *field.Path) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// validateAllowedTopology tests that AllowedTopologies specifies valid values.\nfunc validateAllowedTopologies(topologies []api.TopologySelectorTerm, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(topologies) == 0 {\n\t\treturn allErrs\n\t}\n\n\trawTopologies := make([]map[string]sets.String, len(topologies))\n\tfor i, term := range topologies {\n\t\tidxPath := fldPath.Index(i)\n\t\texprMap, termErrs := apivalidation.ValidateTopologySelectorTerm(term, fldPath.Index(i))\n\t\tallErrs = append(allErrs, termErrs...)\n\n\t\t// TODO (verult) consider improving runtime\n\t\tfor _, t := range rawTopologies {\n\t\t\tif helper.Semantic.DeepEqual(exprMap, t) {\n\t\t\t\tallErrs = append(allErrs, field.Duplicate(idxPath.Child(\"matchLabelExpressions\"), \"\"))\n\t\t\t}\n\t\t}\n\n\t\trawTopologies = append(rawTopologies, exprMap)\n\t}\n\n\treturn allErrs\n}","line":{"from":265,"to":290}} {"id":100003187,"name":"ValidateCSINode","signature":"func ValidateCSINode(csiNode *storage.CSINode, validationOpts CSINodeValidationOptions) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// ValidateCSINode validates a CSINode.\nfunc ValidateCSINode(csiNode *storage.CSINode, validationOpts CSINodeValidationOptions) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMeta(\u0026csiNode.ObjectMeta, false, apivalidation.ValidateNodeName, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, validateCSINodeSpec(\u0026csiNode.Spec, field.NewPath(\"spec\"), validationOpts)...)\n\treturn allErrs\n}","line":{"from":292,"to":297}} {"id":100003188,"name":"ValidateCSINodeUpdate","signature":"func ValidateCSINodeUpdate(new, old *storage.CSINode, validationOpts CSINodeValidationOptions) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// ValidateCSINodeUpdate validates a CSINode.\nfunc ValidateCSINodeUpdate(new, old *storage.CSINode, validationOpts CSINodeValidationOptions) field.ErrorList {\n\tallErrs := ValidateCSINode(new, validationOpts)\n\n\t// Validate modifying fields inside an existing CSINodeDriver entry is not allowed\n\tfor _, oldDriver := range old.Spec.Drivers {\n\t\tfor _, newDriver := range new.Spec.Drivers {\n\t\t\tif oldDriver.Name == newDriver.Name {\n\t\t\t\tif !apiequality.Semantic.DeepEqual(oldDriver, newDriver) {\n\t\t\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"CSINodeDriver\"), newDriver, \"field is immutable\"))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":299,"to":315}} {"id":100003189,"name":"validateCSINodeSpec","signature":"func validateCSINodeSpec(","file":"pkg/apis/storage/validation/validation.go","code":"// ValidateCSINodeSpec tests that the specified CSINodeSpec has valid data.\nfunc validateCSINodeSpec(\n\tspec *storage.CSINodeSpec, fldPath *field.Path, validationOpts CSINodeValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, validateCSINodeDrivers(spec.Drivers, fldPath.Child(\"drivers\"), validationOpts)...)\n\treturn allErrs\n}","line":{"from":317,"to":323}} {"id":100003190,"name":"validateCSINodeDrivers","signature":"func validateCSINodeDrivers(drivers []storage.CSINodeDriver, fldPath *field.Path, validationOpts CSINodeValidationOptions) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// ValidateCSINodeDrivers tests that the specified CSINodeDrivers have valid data.\nfunc validateCSINodeDrivers(drivers []storage.CSINodeDriver, fldPath *field.Path, validationOpts CSINodeValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tdriverNamesInSpecs := make(sets.String)\n\tfor i, driver := range drivers {\n\t\tidxPath := fldPath.Index(i)\n\t\tallErrs = append(allErrs, validateCSINodeDriver(driver, driverNamesInSpecs, idxPath, validationOpts)...)\n\t}\n\n\treturn allErrs\n}","line":{"from":325,"to":335}} {"id":100003191,"name":"validateCSINodeDriverNodeID","signature":"func validateCSINodeDriverNodeID(nodeID string, fldPath *field.Path, validationOpts CSINodeValidationOptions) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// validateCSINodeDriverNodeID tests if Name in CSINodeDriver is a valid node id.\nfunc validateCSINodeDriverNodeID(nodeID string, fldPath *field.Path, validationOpts CSINodeValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\t// nodeID is always required\n\tif len(nodeID) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath, nodeID))\n\t}\n\tmaxLength := csiNodeIDMaxLength\n\tif validationOpts.AllowLongNodeID {\n\t\tmaxLength = csiNodeIDLongerMaxLength\n\t}\n\tif len(nodeID) \u003e maxLength {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, nodeID, fmt.Sprintf(\"must be %d characters or less\", maxLength)))\n\t}\n\treturn allErrs\n}","line":{"from":337,"to":353}} {"id":100003192,"name":"CSINodeLongerID","signature":"func CSINodeLongerID(nodeID string) bool","file":"pkg/apis/storage/validation/validation.go","code":"// CSINodeLongerID will check if the nodeID is longer than csiNodeIDMaxLength\nfunc CSINodeLongerID(nodeID string) bool {\n\treturn len(nodeID) \u003e csiNodeIDMaxLength\n}","line":{"from":355,"to":358}} {"id":100003193,"name":"validateCSINodeDriverAllocatable","signature":"func validateCSINodeDriverAllocatable(a *storage.VolumeNodeResources, fldPath *field.Path) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// validateCSINodeDriverAllocatable tests if Allocatable in CSINodeDriver has valid volume limits.\nfunc validateCSINodeDriverAllocatable(a *storage.VolumeNodeResources, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif a == nil || a.Count == nil {\n\t\treturn allErrs\n\t}\n\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(*a.Count), fldPath.Child(\"count\"))...)\n\treturn allErrs\n}","line":{"from":360,"to":370}} {"id":100003194,"name":"validateCSINodeDriver","signature":"func validateCSINodeDriver(driver storage.CSINodeDriver, driverNamesInSpecs sets.String, fldPath *field.Path,","file":"pkg/apis/storage/validation/validation.go","code":"// validateCSINodeDriver tests if CSINodeDriver has valid entries\nfunc validateCSINodeDriver(driver storage.CSINodeDriver, driverNamesInSpecs sets.String, fldPath *field.Path,\n\tvalidationOpts CSINodeValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tallErrs = append(allErrs, apivalidation.ValidateCSIDriverName(driver.Name, fldPath.Child(\"name\"))...)\n\tallErrs = append(allErrs, validateCSINodeDriverNodeID(driver.NodeID, fldPath.Child(\"nodeID\"), validationOpts)...)\n\tallErrs = append(allErrs, validateCSINodeDriverAllocatable(driver.Allocatable, fldPath.Child(\"allocatable\"))...)\n\n\t// check for duplicate entries for the same driver in specs\n\tif driverNamesInSpecs.Has(driver.Name) {\n\t\tallErrs = append(allErrs, field.Duplicate(fldPath.Child(\"name\"), driver.Name))\n\t}\n\tdriverNamesInSpecs.Insert(driver.Name)\n\ttopoKeys := make(sets.String)\n\tfor _, key := range driver.TopologyKeys {\n\t\tif len(key) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath, key))\n\t\t}\n\n\t\tif topoKeys.Has(key) {\n\t\t\tallErrs = append(allErrs, field.Duplicate(fldPath, key))\n\t\t}\n\t\ttopoKeys.Insert(key)\n\n\t\tallErrs = append(allErrs, apivalidation.ValidateQualifiedName(key, fldPath)...)\n\t}\n\n\treturn allErrs\n}","line":{"from":372,"to":401}} {"id":100003195,"name":"ValidateCSIDriver","signature":"func ValidateCSIDriver(csiDriver *storage.CSIDriver) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// ValidateCSIDriver validates a CSIDriver.\nfunc ValidateCSIDriver(csiDriver *storage.CSIDriver) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMeta(\u0026csiDriver.ObjectMeta, false, ValidateCSIDriverName, field.NewPath(\"metadata\"))\n\n\tallErrs = append(allErrs, validateCSIDriverSpec(\u0026csiDriver.Spec, field.NewPath(\"spec\"))...)\n\treturn allErrs\n}","line":{"from":407,"to":413}} {"id":100003196,"name":"ValidateCSIDriverUpdate","signature":"func ValidateCSIDriverUpdate(new, old *storage.CSIDriver) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// ValidateCSIDriverUpdate validates a CSIDriver.\nfunc ValidateCSIDriverUpdate(new, old *storage.CSIDriver) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMetaUpdate(\u0026new.ObjectMeta, \u0026old.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, validateCSIDriverSpec(\u0026new.Spec, field.NewPath(\"spec\"))...)\n\n\t// immutable fields should not be mutated.\n\tallErrs = append(allErrs, apimachineryvalidation.ValidateImmutableField(new.Spec.AttachRequired, old.Spec.AttachRequired, field.NewPath(\"spec\", \"attachedRequired\"))...)\n\tallErrs = append(allErrs, apimachineryvalidation.ValidateImmutableField(new.Spec.FSGroupPolicy, old.Spec.FSGroupPolicy, field.NewPath(\"spec\", \"fsGroupPolicy\"))...)\n\tallErrs = append(allErrs, apimachineryvalidation.ValidateImmutableField(new.Spec.PodInfoOnMount, old.Spec.PodInfoOnMount, field.NewPath(\"spec\", \"podInfoOnMount\"))...)\n\tallErrs = append(allErrs, apimachineryvalidation.ValidateImmutableField(new.Spec.VolumeLifecycleModes, old.Spec.VolumeLifecycleModes, field.NewPath(\"spec\", \"volumeLifecycleModes\"))...)\n\n\tallErrs = append(allErrs, validateTokenRequests(new.Spec.TokenRequests, field.NewPath(\"spec\", \"tokenRequests\"))...)\n\treturn allErrs\n}","line":{"from":415,"to":428}} {"id":100003197,"name":"validateCSIDriverSpec","signature":"func validateCSIDriverSpec(","file":"pkg/apis/storage/validation/validation.go","code":"// ValidateCSIDriverSpec tests that the specified CSIDriverSpec\n// has valid data.\nfunc validateCSIDriverSpec(\n\tspec *storage.CSIDriverSpec, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, validateAttachRequired(spec.AttachRequired, fldPath.Child(\"attachedRequired\"))...)\n\tallErrs = append(allErrs, validatePodInfoOnMount(spec.PodInfoOnMount, fldPath.Child(\"podInfoOnMount\"))...)\n\tallErrs = append(allErrs, validateStorageCapacity(spec.StorageCapacity, fldPath.Child(\"storageCapacity\"))...)\n\tallErrs = append(allErrs, validateFSGroupPolicy(spec.FSGroupPolicy, fldPath.Child(\"fsGroupPolicy\"))...)\n\tallErrs = append(allErrs, validateTokenRequests(spec.TokenRequests, fldPath.Child(\"tokenRequests\"))...)\n\tallErrs = append(allErrs, validateVolumeLifecycleModes(spec.VolumeLifecycleModes, fldPath.Child(\"volumeLifecycleModes\"))...)\n\tallErrs = append(allErrs, validateSELinuxMount(spec.SELinuxMount, fldPath.Child(\"seLinuxMount\"))...)\n\treturn allErrs\n}","line":{"from":430,"to":443}} {"id":100003198,"name":"validateAttachRequired","signature":"func validateAttachRequired(attachRequired *bool, fldPath *field.Path) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// validateAttachRequired tests if attachRequired is set for CSIDriver.\nfunc validateAttachRequired(attachRequired *bool, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif attachRequired == nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath, \"\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":445,"to":453}} {"id":100003199,"name":"validatePodInfoOnMount","signature":"func validatePodInfoOnMount(podInfoOnMount *bool, fldPath *field.Path) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// validatePodInfoOnMount tests if podInfoOnMount is set for CSIDriver.\nfunc validatePodInfoOnMount(podInfoOnMount *bool, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif podInfoOnMount == nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath, \"\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":455,"to":463}} {"id":100003200,"name":"validateStorageCapacity","signature":"func validateStorageCapacity(storageCapacity *bool, fldPath *field.Path) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// validateStorageCapacity tests if storageCapacity is set for CSIDriver.\nfunc validateStorageCapacity(storageCapacity *bool, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif storageCapacity == nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath, \"\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":465,"to":473}} {"id":100003201,"name":"validateFSGroupPolicy","signature":"func validateFSGroupPolicy(fsGroupPolicy *storage.FSGroupPolicy, fldPath *field.Path) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// validateFSGroupPolicy tests if FSGroupPolicy contains an appropriate value.\nfunc validateFSGroupPolicy(fsGroupPolicy *storage.FSGroupPolicy, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif fsGroupPolicy == nil {\n\t\t// This is not a required field, so if nothing is provided simply return\n\t\treturn allErrs\n\t}\n\n\tif !supportedFSGroupPolicy.Has(string(*fsGroupPolicy)) {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath, fsGroupPolicy, supportedFSGroupPolicy.List()))\n\t}\n\n\treturn allErrs\n}","line":{"from":477,"to":490}} {"id":100003202,"name":"validateTokenRequests","signature":"func validateTokenRequests(tokenRequests []storage.TokenRequest, fldPath *field.Path) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// validateTokenRequests tests if the Audience in each TokenRequest are different.\n// Besides, at most one TokenRequest can ignore Audience.\nfunc validateTokenRequests(tokenRequests []storage.TokenRequest, fldPath *field.Path) field.ErrorList {\n\tconst min = 10 * time.Minute\n\tallErrs := field.ErrorList{}\n\taudiences := make(map[string]bool)\n\tfor i, tokenRequest := range tokenRequests {\n\t\tpath := fldPath.Index(i)\n\t\taudience := tokenRequest.Audience\n\t\tif _, ok := audiences[audience]; ok {\n\t\t\tallErrs = append(allErrs, field.Duplicate(path.Child(\"audience\"), audience))\n\t\t\tcontinue\n\t\t}\n\t\taudiences[audience] = true\n\n\t\tif tokenRequest.ExpirationSeconds == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif *tokenRequest.ExpirationSeconds \u003c int64(min.Seconds()) {\n\t\t\tallErrs = append(allErrs, field.Invalid(path.Child(\"expirationSeconds\"), *tokenRequest.ExpirationSeconds, \"may not specify a duration less than 10 minutes\"))\n\t\t}\n\t\tif *tokenRequest.ExpirationSeconds \u003e 1\u003c\u003c32 {\n\t\t\tallErrs = append(allErrs, field.Invalid(path.Child(\"expirationSeconds\"), *tokenRequest.ExpirationSeconds, \"may not specify a duration larger than 2^32 seconds\"))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":492,"to":519}} {"id":100003203,"name":"validateVolumeLifecycleModes","signature":"func validateVolumeLifecycleModes(modes []storage.VolumeLifecycleMode, fldPath *field.Path) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// validateVolumeLifecycleModes tests if mode has one of the allowed values.\nfunc validateVolumeLifecycleModes(modes []storage.VolumeLifecycleMode, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor _, mode := range modes {\n\t\tswitch mode {\n\t\tcase storage.VolumeLifecyclePersistent, storage.VolumeLifecycleEphemeral:\n\t\tdefault:\n\t\t\tallErrs = append(allErrs, field.NotSupported(fldPath, mode,\n\t\t\t\t[]string{\n\t\t\t\t\tstring(storage.VolumeLifecyclePersistent),\n\t\t\t\t\tstring(storage.VolumeLifecycleEphemeral),\n\t\t\t\t}))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":521,"to":537}} {"id":100003204,"name":"validateSELinuxMount","signature":"func validateSELinuxMount(seLinuxMount *bool, fldPath *field.Path) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// validateSELinuxMount tests if seLinuxMount is set for CSIDriver.\nfunc validateSELinuxMount(seLinuxMount *bool, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif seLinuxMount == nil \u0026\u0026 utilfeature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {\n\t\tallErrs = append(allErrs, field.Required(fldPath, \"\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":539,"to":547}} {"id":100003205,"name":"ValidateCSIStorageCapacity","signature":"func ValidateCSIStorageCapacity(capacity *storage.CSIStorageCapacity, opts CSIStorageCapacityValidateOptions) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// ValidateCSIStorageCapacity validates a CSIStorageCapacity.\nfunc ValidateCSIStorageCapacity(capacity *storage.CSIStorageCapacity, opts CSIStorageCapacityValidateOptions) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMeta(\u0026capacity.ObjectMeta, true, ValidateStorageCapacityName, field.NewPath(\"metadata\"))\n\tlabelSelectorValidationOptions := metav1validation.LabelSelectorValidationOptions{AllowInvalidLabelValueInSelector: opts.AllowInvalidLabelValueInSelector}\n\tallErrs = append(allErrs, metav1validation.ValidateLabelSelector(capacity.NodeTopology, labelSelectorValidationOptions, field.NewPath(\"nodeTopology\"))...)\n\tfor _, msg := range apivalidation.ValidateClassName(capacity.StorageClassName, false) {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"storageClassName\"), capacity.StorageClassName, msg))\n\t}\n\tif capacity.Capacity != nil {\n\t\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeQuantity(*capacity.Capacity, field.NewPath(\"capacity\"))...)\n\t}\n\treturn allErrs\n}","line":{"from":557,"to":569}} {"id":100003206,"name":"ValidateCSIStorageCapacityUpdate","signature":"func ValidateCSIStorageCapacityUpdate(capacity, oldCapacity *storage.CSIStorageCapacity) field.ErrorList","file":"pkg/apis/storage/validation/validation.go","code":"// ValidateCSIStorageCapacityUpdate tests if an update to CSIStorageCapacity is valid.\nfunc ValidateCSIStorageCapacityUpdate(capacity, oldCapacity *storage.CSIStorageCapacity) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMetaUpdate(\u0026capacity.ObjectMeta, \u0026oldCapacity.ObjectMeta, field.NewPath(\"metadata\"))\n\n\t// Input fields for CSI GetCapacity are immutable.\n\t// If this ever relaxes in the future, make sure to increment the Generation number in PrepareForUpdate\n\tif !apiequality.Semantic.DeepEqual(capacity.NodeTopology, oldCapacity.NodeTopology) {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"nodeTopology\"), capacity.NodeTopology, \"field is immutable\"))\n\t}\n\tif capacity.StorageClassName != oldCapacity.StorageClassName {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"storageClassName\"), capacity.StorageClassName, \"field is immutable\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":571,"to":585}} {"id":100003207,"name":"Error","signature":"func (p policyLoadError) Error() string","file":"pkg/auth/authorizer/abac/abac.go","code":"func (p policyLoadError) Error() string {\n\tif p.line \u003e= 0 {\n\t\treturn fmt.Sprintf(\"error reading policy file %s, line %d: %s: %v\", p.path, p.line, string(p.data), p.err)\n\t}\n\treturn fmt.Sprintf(\"error reading policy file %s: %v\", p.path, p.err)\n}","line":{"from":46,"to":51}} {"id":100003208,"name":"NewFromFile","signature":"func NewFromFile(path string) (PolicyList, error)","file":"pkg/auth/authorizer/abac/abac.go","code":"// NewFromFile attempts to create a policy list from the given file.\n//\n// TODO: Have policies be created via an API call and stored in REST storage.\nfunc NewFromFile(path string) (PolicyList, error) {\n\t// File format is one map per line. This allows easy concatenation of files,\n\t// comments in files, and identification of errors by line number.\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\n\tscanner := bufio.NewScanner(file)\n\tpl := make(PolicyList, 0)\n\n\tdecoder := abac.Codecs.UniversalDecoder()\n\n\ti := 0\n\tunversionedLines := 0\n\tfor scanner.Scan() {\n\t\ti++\n\t\tp := \u0026abac.Policy{}\n\t\tb := scanner.Bytes()\n\n\t\t// skip comment lines and blank lines\n\t\ttrimmed := strings.TrimSpace(string(b))\n\t\tif len(trimmed) == 0 || strings.HasPrefix(trimmed, \"#\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tdecodedObj, _, err := decoder.Decode(b, nil, nil)\n\t\tif err != nil {\n\t\t\tif !(runtime.IsMissingVersion(err) || runtime.IsMissingKind(err) || runtime.IsNotRegisteredError(err)) {\n\t\t\t\treturn nil, policyLoadError{path, i, b, err}\n\t\t\t}\n\t\t\tunversionedLines++\n\t\t\t// Migrate unversioned policy object\n\t\t\toldPolicy := \u0026v0.Policy{}\n\t\t\tif err := runtime.DecodeInto(decoder, b, oldPolicy); err != nil {\n\t\t\t\treturn nil, policyLoadError{path, i, b, err}\n\t\t\t}\n\t\t\tif err := abac.Scheme.Convert(oldPolicy, p, nil); err != nil {\n\t\t\t\treturn nil, policyLoadError{path, i, b, err}\n\t\t\t}\n\t\t\tpl = append(pl, p)\n\t\t\tcontinue\n\t\t}\n\n\t\tdecodedPolicy, ok := decodedObj.(*abac.Policy)\n\t\tif !ok {\n\t\t\treturn nil, policyLoadError{path, i, b, fmt.Errorf(\"unrecognized object: %#v\", decodedObj)}\n\t\t}\n\t\tpl = append(pl, decodedPolicy)\n\t}\n\n\tif unversionedLines \u003e 0 {\n\t\tklog.Warningf(\"Policy file %s contained unversioned rules. See docs/admin/authorization.md#abac-mode for ABAC file format details.\", path)\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\treturn nil, policyLoadError{path, -1, nil, err}\n\t}\n\treturn pl, nil\n}","line":{"from":56,"to":119}} {"id":100003209,"name":"matches","signature":"func matches(p abac.Policy, a authorizer.Attributes) bool","file":"pkg/auth/authorizer/abac/abac.go","code":"func matches(p abac.Policy, a authorizer.Attributes) bool {\n\tif subjectMatches(p, a.GetUser()) {\n\t\tif verbMatches(p, a) {\n\t\t\t// Resource and non-resource requests are mutually exclusive, at most one will match a policy\n\t\t\tif resourceMatches(p, a) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif nonResourceMatches(p, a) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":121,"to":134}} {"id":100003210,"name":"subjectMatches","signature":"func subjectMatches(p abac.Policy, user user.Info) bool","file":"pkg/auth/authorizer/abac/abac.go","code":"// subjectMatches returns true if specified user and group properties in the policy match the attributes\nfunc subjectMatches(p abac.Policy, user user.Info) bool {\n\tmatched := false\n\n\tif user == nil {\n\t\treturn false\n\t}\n\tusername := user.GetName()\n\tgroups := user.GetGroups()\n\n\t// If the policy specified a user, ensure it matches\n\tif len(p.Spec.User) \u003e 0 {\n\t\tif p.Spec.User == \"*\" {\n\t\t\tmatched = true\n\t\t} else {\n\t\t\tmatched = p.Spec.User == username\n\t\t\tif !matched {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\t// If the policy specified a group, ensure it matches\n\tif len(p.Spec.Group) \u003e 0 {\n\t\tif p.Spec.Group == \"*\" {\n\t\t\tmatched = true\n\t\t} else {\n\t\t\tmatched = false\n\t\t\tfor _, group := range groups {\n\t\t\t\tif p.Spec.Group == group {\n\t\t\t\t\tmatched = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !matched {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn matched\n}","line":{"from":136,"to":177}} {"id":100003211,"name":"verbMatches","signature":"func verbMatches(p abac.Policy, a authorizer.Attributes) bool","file":"pkg/auth/authorizer/abac/abac.go","code":"func verbMatches(p abac.Policy, a authorizer.Attributes) bool {\n\t// TODO: match on verb\n\n\t// All policies allow read only requests\n\tif a.IsReadOnly() {\n\t\treturn true\n\t}\n\n\t// Allow if policy is not readonly\n\tif !p.Spec.Readonly {\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":179,"to":193}} {"id":100003212,"name":"nonResourceMatches","signature":"func nonResourceMatches(p abac.Policy, a authorizer.Attributes) bool","file":"pkg/auth/authorizer/abac/abac.go","code":"func nonResourceMatches(p abac.Policy, a authorizer.Attributes) bool {\n\t// A non-resource policy cannot match a resource request\n\tif !a.IsResourceRequest() {\n\t\t// Allow wildcard match\n\t\tif p.Spec.NonResourcePath == \"*\" {\n\t\t\treturn true\n\t\t}\n\t\t// Allow exact match\n\t\tif p.Spec.NonResourcePath == a.GetPath() {\n\t\t\treturn true\n\t\t}\n\t\t// Allow a trailing * subpath match\n\t\tif strings.HasSuffix(p.Spec.NonResourcePath, \"*\") \u0026\u0026 strings.HasPrefix(a.GetPath(), strings.TrimRight(p.Spec.NonResourcePath, \"*\")) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":195,"to":212}} {"id":100003213,"name":"resourceMatches","signature":"func resourceMatches(p abac.Policy, a authorizer.Attributes) bool","file":"pkg/auth/authorizer/abac/abac.go","code":"func resourceMatches(p abac.Policy, a authorizer.Attributes) bool {\n\t// A resource policy cannot match a non-resource request\n\tif a.IsResourceRequest() {\n\t\tif p.Spec.Namespace == \"*\" || p.Spec.Namespace == a.GetNamespace() {\n\t\t\tif p.Spec.Resource == \"*\" || p.Spec.Resource == a.GetResource() {\n\t\t\t\tif p.Spec.APIGroup == \"*\" || p.Spec.APIGroup == a.GetAPIGroup() {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":214,"to":226}} {"id":100003214,"name":"Authorize","signature":"func (pl PolicyList) Authorize(ctx context.Context, a authorizer.Attributes) (authorizer.Decision, string, error)","file":"pkg/auth/authorizer/abac/abac.go","code":"// Authorize implements authorizer.Authorize\nfunc (pl PolicyList) Authorize(ctx context.Context, a authorizer.Attributes) (authorizer.Decision, string, error) {\n\tfor _, p := range pl {\n\t\tif matches(*p, a) {\n\t\t\treturn authorizer.DecisionAllow, \"\", nil\n\t\t}\n\t}\n\treturn authorizer.DecisionNoOpinion, \"No policy matched.\", nil\n\t// TODO: Benchmark how much time policy matching takes with a medium size\n\t// policy file, compared to other steps such as encoding/decoding.\n\t// Then, add Caching only if needed.\n}","line":{"from":228,"to":239}} {"id":100003215,"name":"RulesFor","signature":"func (pl PolicyList) RulesFor(user user.Info, namespace string) ([]authorizer.ResourceRuleInfo, []authorizer.NonResourceRuleInfo, bool, error)","file":"pkg/auth/authorizer/abac/abac.go","code":"// RulesFor returns rules for the given user and namespace.\nfunc (pl PolicyList) RulesFor(user user.Info, namespace string) ([]authorizer.ResourceRuleInfo, []authorizer.NonResourceRuleInfo, bool, error) {\n\tvar (\n\t\tresourceRules []authorizer.ResourceRuleInfo\n\t\tnonResourceRules []authorizer.NonResourceRuleInfo\n\t)\n\n\tfor _, p := range pl {\n\t\tif subjectMatches(*p, user) {\n\t\t\tif p.Spec.Namespace == \"*\" || p.Spec.Namespace == namespace {\n\t\t\t\tif len(p.Spec.Resource) \u003e 0 {\n\t\t\t\t\tr := authorizer.DefaultResourceRuleInfo{\n\t\t\t\t\t\tVerbs: getVerbs(p.Spec.Readonly),\n\t\t\t\t\t\tAPIGroups: []string{p.Spec.APIGroup},\n\t\t\t\t\t\tResources: []string{p.Spec.Resource},\n\t\t\t\t\t}\n\t\t\t\t\tvar resourceRule authorizer.ResourceRuleInfo = \u0026r\n\t\t\t\t\tresourceRules = append(resourceRules, resourceRule)\n\t\t\t\t}\n\t\t\t\tif len(p.Spec.NonResourcePath) \u003e 0 {\n\t\t\t\t\tr := authorizer.DefaultNonResourceRuleInfo{\n\t\t\t\t\t\tVerbs: getVerbs(p.Spec.Readonly),\n\t\t\t\t\t\tNonResourceURLs: []string{p.Spec.NonResourcePath},\n\t\t\t\t\t}\n\t\t\t\t\tvar nonResourceRule authorizer.NonResourceRuleInfo = \u0026r\n\t\t\t\t\tnonResourceRules = append(nonResourceRules, nonResourceRule)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn resourceRules, nonResourceRules, false, nil\n}","line":{"from":241,"to":272}} {"id":100003216,"name":"getVerbs","signature":"func getVerbs(isReadOnly bool) []string","file":"pkg/auth/authorizer/abac/abac.go","code":"func getVerbs(isReadOnly bool) []string {\n\tif isReadOnly {\n\t\treturn []string{\"get\", \"list\", \"watch\"}\n\t}\n\treturn []string{\"*\"}\n}","line":{"from":274,"to":279}} {"id":100003217,"name":"NewDefaultNodeIdentifier","signature":"func NewDefaultNodeIdentifier() NodeIdentifier","file":"pkg/auth/nodeidentifier/default.go","code":"// NewDefaultNodeIdentifier returns a default NodeIdentifier implementation,\n// which returns isNode=true if the user groups contain the system:nodes group\n// and the user name matches the format system:node:\u003cnodeName\u003e, and populates\n// nodeName if isNode is true\nfunc NewDefaultNodeIdentifier() NodeIdentifier {\n\treturn defaultNodeIdentifier{}\n}","line":{"from":25,"to":31}} {"id":100003218,"name":"NodeIdentity","signature":"func (defaultNodeIdentifier) NodeIdentity(u user.Info) (string, bool)","file":"pkg/auth/nodeidentifier/default.go","code":"// NodeIdentity returns isNode=true if the user groups contain the system:nodes\n// group and the user name matches the format system:node:\u003cnodeName\u003e, and\n// populates nodeName if isNode is true\nfunc (defaultNodeIdentifier) NodeIdentity(u user.Info) (string, bool) {\n\t// Make sure we're a node, and can parse the node name\n\tif u == nil {\n\t\treturn \"\", false\n\t}\n\n\tuserName := u.GetName()\n\tif !strings.HasPrefix(userName, nodeUserNamePrefix) {\n\t\treturn \"\", false\n\t}\n\n\tisNode := false\n\tfor _, g := range u.GetGroups() {\n\t\tif g == user.NodesGroup {\n\t\t\tisNode = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !isNode {\n\t\treturn \"\", false\n\t}\n\n\tnodeName := strings.TrimPrefix(userName, nodeUserNamePrefix)\n\treturn nodeName, true\n}","line":{"from":39,"to":66}} {"id":100003219,"name":"Initialize","signature":"func Initialize(c Capabilities)","file":"pkg/capabilities/capabilities.go","code":"// Initialize the capability set. This can only be done once per binary, subsequent calls are ignored.\nfunc Initialize(c Capabilities) {\n\t// Only do this once\n\tcapInstance.once.Do(func() {\n\t\tcapInstance.capabilities = \u0026c\n\t})\n}","line":{"from":55,"to":61}} {"id":100003220,"name":"Setup","signature":"func Setup(allowPrivileged bool, perConnectionBytesPerSec int64)","file":"pkg/capabilities/capabilities.go","code":"// Setup the capability set. It wraps Initialize for improving usability.\nfunc Setup(allowPrivileged bool, perConnectionBytesPerSec int64) {\n\tInitialize(Capabilities{\n\t\tAllowPrivileged: allowPrivileged,\n\t\tPerConnectionBandwidthLimitBytesPerSec: perConnectionBytesPerSec,\n\t})\n}","line":{"from":63,"to":69}} {"id":100003221,"name":"SetForTests","signature":"func SetForTests(c Capabilities)","file":"pkg/capabilities/capabilities.go","code":"// SetForTests sets capabilities for tests. Convenience method for testing. This should only be called from tests.\nfunc SetForTests(c Capabilities) {\n\tcapInstance.lock.Lock()\n\tdefer capInstance.lock.Unlock()\n\tcapInstance.capabilities = \u0026c\n}","line":{"from":71,"to":76}} {"id":100003222,"name":"Get","signature":"func Get() Capabilities","file":"pkg/capabilities/capabilities.go","code":"// Get returns a read-only copy of the system capabilities.\nfunc Get() Capabilities {\n\tcapInstance.lock.Lock()\n\tdefer capInstance.lock.Unlock()\n\t// This check prevents clobbering of capabilities that might've been set via SetForTests\n\tif capInstance.capabilities == nil {\n\t\tInitialize(Capabilities{\n\t\t\tAllowPrivileged: false,\n\t\t\tPrivilegedSources: PrivilegedSources{\n\t\t\t\tHostNetworkSources: []string{},\n\t\t\t\tHostPIDSources: []string{},\n\t\t\t\tHostIPCSources: []string{},\n\t\t\t},\n\t\t})\n\t}\n\treturn *capInstance.capabilities\n}","line":{"from":78,"to":94}} {"id":100003223,"name":"PodRunning","signature":"func PodRunning(event watch.Event) (bool, error)","file":"pkg/client/conditions/conditions.go","code":"// PodRunning returns true if the pod is running, false if the pod has not yet reached running state,\n// returns ErrPodCompleted if the pod has run to completion, or an error in any other case.\nfunc PodRunning(event watch.Event) (bool, error) {\n\tswitch event.Type {\n\tcase watch.Deleted:\n\t\treturn false, errors.NewNotFound(schema.GroupResource{Resource: \"pods\"}, \"\")\n\t}\n\tswitch t := event.Object.(type) {\n\tcase *v1.Pod:\n\t\tswitch t.Status.Phase {\n\t\tcase v1.PodRunning:\n\t\t\treturn true, nil\n\t\tcase v1.PodFailed, v1.PodSucceeded:\n\t\t\treturn false, ErrPodCompleted\n\t\t}\n\t}\n\treturn false, nil\n}","line":{"from":32,"to":49}} {"id":100003224,"name":"PodCompleted","signature":"func PodCompleted(event watch.Event) (bool, error)","file":"pkg/client/conditions/conditions.go","code":"// PodCompleted returns true if the pod has run to completion, false if the pod has not yet\n// reached running state, or an error in any other case.\nfunc PodCompleted(event watch.Event) (bool, error) {\n\tswitch event.Type {\n\tcase watch.Deleted:\n\t\treturn false, errors.NewNotFound(schema.GroupResource{Resource: \"pods\"}, \"\")\n\t}\n\tswitch t := event.Object.(type) {\n\tcase *v1.Pod:\n\t\tswitch t.Status.Phase {\n\t\tcase v1.PodFailed, v1.PodSucceeded:\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}","line":{"from":51,"to":66}} {"id":100003225,"name":"Funcs","signature":"func Funcs(codecs runtimeserializer.CodecFactory) []interface{}","file":"pkg/controller/apis/config/fuzzer/fuzzer.go","code":"// Funcs returns the fuzzer functions for the kube-controller manager apis.\nfunc Funcs(codecs runtimeserializer.CodecFactory) []interface{} {\n\treturn []interface{}{\n\t\tfunc(obj *kubectrlmgrconfig.KubeControllerManagerConfiguration, c fuzz.Continue) {\n\t\t\tc.FuzzNoCustom(obj)\n\t\t\tobj.Generic.Address = fmt.Sprintf(\"%d.%d.%d.%d\", c.Intn(256), c.Intn(256), c.Intn(256), c.Intn(256))\n\t\t\tobj.Generic.ClientConnection.ContentType = fmt.Sprintf(\"%s/%s.%s.%s\", c.RandString(), c.RandString(), c.RandString(), c.RandString())\n\t\t\tif obj.Generic.LeaderElection.ResourceLock == \"\" {\n\t\t\t\tobj.Generic.LeaderElection.ResourceLock = \"endpoints\"\n\t\t\t}\n\t\t\tobj.Generic.Controllers = []string{fmt.Sprintf(\"%s\", c.RandString())}\n\t\t\tif obj.KubeCloudShared.ClusterName == \"\" {\n\t\t\t\tobj.KubeCloudShared.ClusterName = \"kubernetes\"\n\t\t\t}\n\t\t\tobj.CSRSigningController.ClusterSigningCertFile = fmt.Sprintf(\"/%s\", c.RandString())\n\t\t\tobj.CSRSigningController.ClusterSigningKeyFile = fmt.Sprintf(\"/%s\", c.RandString())\n\t\t\tobj.PersistentVolumeBinderController.VolumeConfiguration.FlexVolumePluginDir = fmt.Sprintf(\"/%s\", c.RandString())\n\t\t\tobj.TTLAfterFinishedController.ConcurrentTTLSyncs = c.Int31()\n\t\t},\n\t}\n}","line":{"from":28,"to":48}} {"id":100003226,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/controller/apis/config/register.go","code":"// addKnownTypes registers known types to the given scheme\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026KubeControllerManagerConfiguration{},\n\t)\n\treturn nil\n}","line":{"from":37,"to":43}} {"id":100003227,"name":"init","signature":"func init()","file":"pkg/controller/apis/config/scheme/scheme.go","code":"func init() {\n\tAddToScheme(Scheme)\n}","line":{"from":35,"to":37}} {"id":100003228,"name":"AddToScheme","signature":"func AddToScheme(scheme *runtime.Scheme)","file":"pkg/controller/apis/config/scheme/scheme.go","code":"// AddToScheme registers the API group and adds types to a scheme\nfunc AddToScheme(scheme *runtime.Scheme) {\n\tutilruntime.Must(config.AddToScheme(scheme))\n\tutilruntime.Must(v1alpha1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1alpha1.SchemeGroupVersion))\n}","line":{"from":39,"to":44}} {"id":100003229,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *kruntime.Scheme) error","file":"pkg/controller/apis/config/v1alpha1/defaults.go","code":"func addDefaultingFuncs(scheme *kruntime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":49,"to":51}} {"id":100003230,"name":"SetDefaults_KubeControllerManagerConfiguration","signature":"func SetDefaults_KubeControllerManagerConfiguration(obj *kubectrlmgrconfigv1alpha1.KubeControllerManagerConfiguration)","file":"pkg/controller/apis/config/v1alpha1/defaults.go","code":"func SetDefaults_KubeControllerManagerConfiguration(obj *kubectrlmgrconfigv1alpha1.KubeControllerManagerConfiguration) {\n\t// These defaults override the recommended defaults from the componentbaseconfigv1alpha1 package that are applied automatically\n\t// These client-connection defaults are specific to the kube-controller-manager\n\tif obj.Generic.ClientConnection.QPS == 0.0 {\n\t\tobj.Generic.ClientConnection.QPS = 20.0\n\t}\n\tif obj.Generic.ClientConnection.Burst == 0 {\n\t\tobj.Generic.ClientConnection.Burst = 30\n\t}\n\n\t// Use the default RecommendedDefaultGenericControllerManagerConfiguration options\n\tcmconfigv1alpha1.RecommendedDefaultGenericControllerManagerConfiguration(\u0026obj.Generic)\n\t// Use the default RecommendedDefaultHPAControllerConfiguration options\n\tattachdetachconfigv1alpha1.RecommendedDefaultAttachDetachControllerConfiguration(\u0026obj.AttachDetachController)\n\t// Use the default RecommendedDefaultCSRSigningControllerConfiguration options\n\tcsrsigningconfigv1alpha1.RecommendedDefaultCSRSigningControllerConfiguration(\u0026obj.CSRSigningController)\n\t// Use the default RecommendedDefaultDaemonSetControllerConfiguration options\n\tdaemonconfigv1alpha1.RecommendedDefaultDaemonSetControllerConfiguration(\u0026obj.DaemonSetController)\n\t// Use the default RecommendedDefaultDeploymentControllerConfiguration options\n\tdeploymentconfigv1alpha1.RecommendedDefaultDeploymentControllerConfiguration(\u0026obj.DeploymentController)\n\t// Use the default RecommendedDefaultStatefulSetControllerConfiguration options\n\tstatefulsetconfigv1alpha1.RecommendedDefaultStatefulSetControllerConfiguration(\u0026obj.StatefulSetController)\n\t// Use the default RecommendedDefaultEndpointControllerConfiguration options\n\tendpointconfigv1alpha1.RecommendedDefaultEndpointControllerConfiguration(\u0026obj.EndpointController)\n\t// Use the default RecommendedDefaultEndpointSliceControllerConfiguration options\n\tendpointsliceconfigv1alpha1.RecommendedDefaultEndpointSliceControllerConfiguration(\u0026obj.EndpointSliceController)\n\t// Use the default RecommendedDefaultEndpointSliceMirroringControllerConfiguration options\n\tendpointslicemirroringconfigv1alpha1.RecommendedDefaultEndpointSliceMirroringControllerConfiguration(\u0026obj.EndpointSliceMirroringController)\n\t// Use the default RecommendedDefaultEphemeralVolumeControllerConfiguration options\n\tephemeralvolumeconfigv1alpha1.RecommendedDefaultEphemeralVolumeControllerConfiguration(\u0026obj.EphemeralVolumeController)\n\t// Use the default RecommendedDefaultGenericControllerManagerConfiguration options\n\tgarbagecollectorconfigv1alpha1.RecommendedDefaultGarbageCollectorControllerConfiguration(\u0026obj.GarbageCollectorController)\n\t// Use the default RecommendedDefaultJobControllerConfiguration options\n\tjobconfigv1alpha1.RecommendedDefaultJobControllerConfiguration(\u0026obj.JobController)\n\t// Use the default RecommendedDefaultCronJobControllerConfiguration options\n\tcronjobconfigv1alpha1.RecommendedDefaultCronJobControllerConfiguration(\u0026obj.CronJobController)\n\t// Use the default RecommendedDefaultNamespaceControllerConfiguration options\n\tnamespaceconfigv1alpha1.RecommendedDefaultNamespaceControllerConfiguration(\u0026obj.NamespaceController)\n\t// Use the default RecommendedDefaultNodeIPAMControllerConfiguration options\n\tnodeipamconfigv1alpha1.RecommendedDefaultNodeIPAMControllerConfiguration(\u0026obj.NodeIPAMController)\n\t// Use the default RecommendedDefaultHPAControllerConfiguration options\n\tpoautosclerconfigv1alpha1.RecommendedDefaultHPAControllerConfiguration(\u0026obj.HPAController)\n\t// Use the default RecommendedDefaultNodeLifecycleControllerConfiguration options\n\tnodelifecycleconfigv1alpha1.RecommendedDefaultNodeLifecycleControllerConfiguration(\u0026obj.NodeLifecycleController)\n\t// Use the default RecommendedDefaultPodGCControllerConfiguration options\n\tpodgcconfigv1alpha1.RecommendedDefaultPodGCControllerConfiguration(\u0026obj.PodGCController)\n\t// Use the default RecommendedDefaultReplicaSetControllerConfiguration options\n\treplicasetconfigv1alpha1.RecommendedDefaultReplicaSetControllerConfiguration(\u0026obj.ReplicaSetController)\n\t// Use the default RecommendedDefaultReplicationControllerConfiguration options\n\treplicationconfigv1alpha1.RecommendedDefaultReplicationControllerConfiguration(\u0026obj.ReplicationController)\n\t// Use the default RecommendedDefaultResourceQuotaControllerConfiguration options\n\tresourcequotaconfigv1alpha1.RecommendedDefaultResourceQuotaControllerConfiguration(\u0026obj.ResourceQuotaController)\n\t// Use the default RecommendedDefaultGenericControllerManagerConfiguration options\n\tserviceconfigv1alpha1.RecommendedDefaultServiceControllerConfiguration(\u0026obj.ServiceController)\n\t// Use the default RecommendedDefaultSAControllerConfiguration options\n\tserviceaccountconfigv1alpha1.RecommendedDefaultSAControllerConfiguration(\u0026obj.SAController)\n\t// Use the default RecommendedDefaultTTLAfterFinishedControllerConfiguration options\n\tttlafterfinishedconfigv1alpha1.RecommendedDefaultTTLAfterFinishedControllerConfiguration(\u0026obj.TTLAfterFinishedController)\n\t// Use the default RecommendedDefaultPersistentVolumeBinderControllerConfiguration options\n\tpersistentvolumeconfigv1alpha1.RecommendedDefaultPersistentVolumeBinderControllerConfiguration(\u0026obj.PersistentVolumeBinderController)\n}","line":{"from":53,"to":113}} {"id":100003231,"name":"init","signature":"func init()","file":"pkg/controller/apis/config/v1alpha1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":38,"to":43}} {"id":100003232,"name":"DefaultSignerOptions","signature":"func DefaultSignerOptions() SignerOptions","file":"pkg/controller/bootstrap/bootstrapsigner.go","code":"// DefaultSignerOptions returns a set of default options for creating a Signer.\nfunc DefaultSignerOptions() SignerOptions {\n\treturn SignerOptions{\n\t\tConfigMapNamespace: api.NamespacePublic,\n\t\tConfigMapName: bootstrapapi.ConfigMapClusterInfo,\n\t\tTokenSecretNamespace: api.NamespaceSystem,\n\t}\n}","line":{"from":64,"to":71}} {"id":100003233,"name":"NewSigner","signature":"func NewSigner(cl clientset.Interface, secrets informers.SecretInformer, configMaps informers.ConfigMapInformer, options SignerOptions) (*Signer, error)","file":"pkg/controller/bootstrap/bootstrapsigner.go","code":"// NewSigner returns a new *Signer.\nfunc NewSigner(cl clientset.Interface, secrets informers.SecretInformer, configMaps informers.ConfigMapInformer, options SignerOptions) (*Signer, error) {\n\te := \u0026Signer{\n\t\tclient: cl,\n\t\tconfigMapKey: options.ConfigMapNamespace + \"/\" + options.ConfigMapName,\n\t\tconfigMapName: options.ConfigMapName,\n\t\tconfigMapNamespace: options.ConfigMapNamespace,\n\t\tsecretNamespace: options.TokenSecretNamespace,\n\t\tsecretLister: secrets.Lister(),\n\t\tsecretSynced: secrets.Informer().HasSynced,\n\t\tconfigMapLister: configMaps.Lister(),\n\t\tconfigMapSynced: configMaps.Informer().HasSynced,\n\t\tsyncQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"bootstrap_signer_queue\"),\n\t}\n\n\tconfigMaps.Informer().AddEventHandlerWithResyncPeriod(\n\t\tcache.FilteringResourceEventHandler{\n\t\t\tFilterFunc: func(obj interface{}) bool {\n\t\t\t\tswitch t := obj.(type) {\n\t\t\t\tcase *v1.ConfigMap:\n\t\t\t\t\treturn t.Name == options.ConfigMapName \u0026\u0026 t.Namespace == options.ConfigMapNamespace\n\t\t\t\tdefault:\n\t\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"object passed to %T that is not expected: %T\", e, obj))\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t},\n\t\t\tHandler: cache.ResourceEventHandlerFuncs{\n\t\t\t\tAddFunc: func(_ interface{}) { e.pokeConfigMapSync() },\n\t\t\t\tUpdateFunc: func(_, _ interface{}) { e.pokeConfigMapSync() },\n\t\t\t},\n\t\t},\n\t\toptions.ConfigMapResync,\n\t)\n\n\tsecrets.Informer().AddEventHandlerWithResyncPeriod(\n\t\tcache.FilteringResourceEventHandler{\n\t\t\tFilterFunc: func(obj interface{}) bool {\n\t\t\t\tswitch t := obj.(type) {\n\t\t\t\tcase *v1.Secret:\n\t\t\t\t\treturn t.Type == bootstrapapi.SecretTypeBootstrapToken \u0026\u0026 t.Namespace == e.secretNamespace\n\t\t\t\tdefault:\n\t\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"object passed to %T that is not expected: %T\", e, obj))\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t},\n\t\t\tHandler: cache.ResourceEventHandlerFuncs{\n\t\t\t\tAddFunc: func(_ interface{}) { e.pokeConfigMapSync() },\n\t\t\t\tUpdateFunc: func(_, _ interface{}) { e.pokeConfigMapSync() },\n\t\t\t\tDeleteFunc: func(_ interface{}) { e.pokeConfigMapSync() },\n\t\t\t},\n\t\t},\n\t\toptions.SecretResync,\n\t)\n\n\treturn e, nil\n}","line":{"from":94,"to":149}} {"id":100003234,"name":"Run","signature":"func (e *Signer) Run(ctx context.Context)","file":"pkg/controller/bootstrap/bootstrapsigner.go","code":"// Run runs controller loops and returns when they are done\nfunc (e *Signer) Run(ctx context.Context) {\n\t// Shut down queues\n\tdefer utilruntime.HandleCrash()\n\tdefer e.syncQueue.ShutDown()\n\n\tif !cache.WaitForNamedCacheSync(\"bootstrap_signer\", ctx.Done(), e.configMapSynced, e.secretSynced) {\n\t\treturn\n\t}\n\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(5).Info(\"Starting workers\")\n\tgo wait.UntilWithContext(ctx, e.serviceConfigMapQueue, 0)\n\t\u003c-ctx.Done()\n\tlogger.V(1).Info(\"Shutting down\")\n}","line":{"from":151,"to":166}} {"id":100003235,"name":"pokeConfigMapSync","signature":"func (e *Signer) pokeConfigMapSync()","file":"pkg/controller/bootstrap/bootstrapsigner.go","code":"func (e *Signer) pokeConfigMapSync() {\n\te.syncQueue.Add(e.configMapKey)\n}","line":{"from":168,"to":170}} {"id":100003236,"name":"serviceConfigMapQueue","signature":"func (e *Signer) serviceConfigMapQueue(ctx context.Context)","file":"pkg/controller/bootstrap/bootstrapsigner.go","code":"func (e *Signer) serviceConfigMapQueue(ctx context.Context) {\n\tkey, quit := e.syncQueue.Get()\n\tif quit {\n\t\treturn\n\t}\n\tdefer e.syncQueue.Done(key)\n\n\te.signConfigMap(ctx)\n}","line":{"from":172,"to":180}} {"id":100003237,"name":"signConfigMap","signature":"func (e *Signer) signConfigMap(ctx context.Context)","file":"pkg/controller/bootstrap/bootstrapsigner.go","code":"// signConfigMap computes the signatures on our latest cached objects and writes\n// back if necessary.\nfunc (e *Signer) signConfigMap(ctx context.Context) {\n\torigCM := e.getConfigMap()\n\n\tif origCM == nil {\n\t\treturn\n\t}\n\n\tvar needUpdate = false\n\n\tnewCM := origCM.DeepCopy()\n\n\tlogger := klog.FromContext(ctx)\n\n\t// First capture the config we are signing\n\tcontent, ok := newCM.Data[bootstrapapi.KubeConfigKey]\n\tif !ok {\n\t\tlogger.V(3).Info(\"No key in ConfigMap\", \"key\", bootstrapapi.KubeConfigKey, \"configMap\", klog.KObj(origCM))\n\t\treturn\n\t}\n\n\t// Next remove and save all existing signatures\n\tsigs := map[string]string{}\n\tfor key, value := range newCM.Data {\n\t\tif strings.HasPrefix(key, bootstrapapi.JWSSignatureKeyPrefix) {\n\t\t\ttokenID := strings.TrimPrefix(key, bootstrapapi.JWSSignatureKeyPrefix)\n\t\t\tsigs[tokenID] = value\n\t\t\tdelete(newCM.Data, key)\n\t\t}\n\t}\n\n\t// Now recompute signatures and store them on the new map\n\ttokens := e.getTokens(ctx)\n\tfor tokenID, tokenValue := range tokens {\n\t\tsig, err := jws.ComputeDetachedSignature(content, tokenID, tokenValue)\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(err)\n\t\t}\n\n\t\t// Check to see if this signature is changed or new.\n\t\toldSig, _ := sigs[tokenID]\n\t\tif sig != oldSig {\n\t\t\tneedUpdate = true\n\t\t}\n\t\tdelete(sigs, tokenID)\n\n\t\tnewCM.Data[bootstrapapi.JWSSignatureKeyPrefix+tokenID] = sig\n\t}\n\n\t// If we have signatures left over we know that some signatures were\n\t// removed. We now need to update the ConfigMap\n\tif len(sigs) != 0 {\n\t\tneedUpdate = true\n\t}\n\n\tif needUpdate {\n\t\te.updateConfigMap(ctx, newCM)\n\t}\n}","line":{"from":182,"to":241}} {"id":100003238,"name":"updateConfigMap","signature":"func (e *Signer) updateConfigMap(ctx context.Context, cm *v1.ConfigMap)","file":"pkg/controller/bootstrap/bootstrapsigner.go","code":"func (e *Signer) updateConfigMap(ctx context.Context, cm *v1.ConfigMap) {\n\t_, err := e.client.CoreV1().ConfigMaps(cm.Namespace).Update(ctx, cm, metav1.UpdateOptions{})\n\tif err != nil \u0026\u0026 !apierrors.IsConflict(err) \u0026\u0026 !apierrors.IsNotFound(err) {\n\t\tklog.FromContext(ctx).V(3).Info(\"Error updating ConfigMap\", \"err\", err)\n\t}\n}","line":{"from":243,"to":248}} {"id":100003239,"name":"getConfigMap","signature":"func (e *Signer) getConfigMap() *v1.ConfigMap","file":"pkg/controller/bootstrap/bootstrapsigner.go","code":"// getConfigMap gets the ConfigMap we are interested in\nfunc (e *Signer) getConfigMap() *v1.ConfigMap {\n\tconfigMap, err := e.configMapLister.ConfigMaps(e.configMapNamespace).Get(e.configMapName)\n\n\t// If we can't get the configmap just return nil. The resync will eventually\n\t// sync things up.\n\tif err != nil {\n\t\tif !apierrors.IsNotFound(err) {\n\t\t\tutilruntime.HandleError(err)\n\t\t}\n\t\treturn nil\n\t}\n\n\treturn configMap\n}","line":{"from":250,"to":264}} {"id":100003240,"name":"listSecrets","signature":"func (e *Signer) listSecrets() []*v1.Secret","file":"pkg/controller/bootstrap/bootstrapsigner.go","code":"func (e *Signer) listSecrets() []*v1.Secret {\n\tsecrets, err := e.secretLister.Secrets(e.secretNamespace).List(labels.Everything())\n\tif err != nil {\n\t\tutilruntime.HandleError(err)\n\t\treturn nil\n\t}\n\n\titems := []*v1.Secret{}\n\tfor _, secret := range secrets {\n\t\tif secret.Type == bootstrapapi.SecretTypeBootstrapToken {\n\t\t\titems = append(items, secret)\n\t\t}\n\t}\n\treturn items\n}","line":{"from":266,"to":280}} {"id":100003241,"name":"getTokens","signature":"func (e *Signer) getTokens(ctx context.Context) map[string]string","file":"pkg/controller/bootstrap/bootstrapsigner.go","code":"// getTokens returns a map of tokenID-\u003etokenSecret. It ensures the token is\n// valid for signing.\nfunc (e *Signer) getTokens(ctx context.Context) map[string]string {\n\tret := map[string]string{}\n\tsecretObjs := e.listSecrets()\n\tfor _, secret := range secretObjs {\n\t\ttokenID, tokenSecret, ok := validateSecretForSigning(ctx, secret)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Check and warn for duplicate secrets. Behavior here will be undefined.\n\t\tif _, ok := ret[tokenID]; ok {\n\t\t\t// This should never happen as we ensure a consistent secret name.\n\t\t\t// But leave this in here just in case.\n\t\t\tklog.FromContext(ctx).V(1).Info(\"Duplicate bootstrap tokens found for id, ignoring on the duplicate secret\", \"tokenID\", tokenID, \"ignoredSecret\", klog.KObj(secret))\n\t\t\tcontinue\n\t\t}\n\n\t\t// This secret looks good, add it to the list.\n\t\tret[tokenID] = tokenSecret\n\t}\n\n\treturn ret\n}","line":{"from":282,"to":306}} {"id":100003242,"name":"DefaultTokenCleanerOptions","signature":"func DefaultTokenCleanerOptions() TokenCleanerOptions","file":"pkg/controller/bootstrap/tokencleaner.go","code":"// DefaultTokenCleanerOptions returns a set of default options for creating a\n// TokenCleaner\nfunc DefaultTokenCleanerOptions() TokenCleanerOptions {\n\treturn TokenCleanerOptions{\n\t\tTokenSecretNamespace: api.NamespaceSystem,\n\t}\n}","line":{"from":51,"to":57}} {"id":100003243,"name":"NewTokenCleaner","signature":"func NewTokenCleaner(cl clientset.Interface, secrets coreinformers.SecretInformer, options TokenCleanerOptions) (*TokenCleaner, error)","file":"pkg/controller/bootstrap/tokencleaner.go","code":"// NewTokenCleaner returns a new *NewTokenCleaner.\nfunc NewTokenCleaner(cl clientset.Interface, secrets coreinformers.SecretInformer, options TokenCleanerOptions) (*TokenCleaner, error) {\n\te := \u0026TokenCleaner{\n\t\tclient: cl,\n\t\tsecretLister: secrets.Lister(),\n\t\tsecretSynced: secrets.Informer().HasSynced,\n\t\ttokenSecretNamespace: options.TokenSecretNamespace,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"token_cleaner\"),\n\t}\n\n\tsecrets.Informer().AddEventHandlerWithResyncPeriod(\n\t\tcache.FilteringResourceEventHandler{\n\t\t\tFilterFunc: func(obj interface{}) bool {\n\t\t\t\tswitch t := obj.(type) {\n\t\t\t\tcase *v1.Secret:\n\t\t\t\t\treturn t.Type == bootstrapapi.SecretTypeBootstrapToken \u0026\u0026 t.Namespace == e.tokenSecretNamespace\n\t\t\t\tdefault:\n\t\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"object passed to %T that is not expected: %T\", e, obj))\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t},\n\t\t\tHandler: cache.ResourceEventHandlerFuncs{\n\t\t\t\tAddFunc: e.enqueueSecrets,\n\t\t\t\tUpdateFunc: func(oldSecret, newSecret interface{}) { e.enqueueSecrets(newSecret) },\n\t\t\t},\n\t\t},\n\t\toptions.SecretResync,\n\t)\n\n\treturn e, nil\n}","line":{"from":74,"to":104}} {"id":100003244,"name":"Run","signature":"func (tc *TokenCleaner) Run(ctx context.Context)","file":"pkg/controller/bootstrap/tokencleaner.go","code":"// Run runs controller loops and returns when they are done\nfunc (tc *TokenCleaner) Run(ctx context.Context) {\n\tdefer utilruntime.HandleCrash()\n\tdefer tc.queue.ShutDown()\n\n\tlogger := klog.FromContext(ctx)\n\tlogger.Info(\"Starting token cleaner controller\")\n\tdefer logger.Info(\"Shutting down token cleaner controller\")\n\n\tif !cache.WaitForNamedCacheSync(\"token_cleaner\", ctx.Done(), tc.secretSynced) {\n\t\treturn\n\t}\n\n\tgo wait.UntilWithContext(ctx, tc.worker, 10*time.Second)\n\n\t\u003c-ctx.Done()\n}","line":{"from":106,"to":122}} {"id":100003245,"name":"enqueueSecrets","signature":"func (tc *TokenCleaner) enqueueSecrets(obj interface{})","file":"pkg/controller/bootstrap/tokencleaner.go","code":"func (tc *TokenCleaner) enqueueSecrets(obj interface{}) {\n\tkey, err := controller.KeyFunc(obj)\n\tif err != nil {\n\t\tutilruntime.HandleError(err)\n\t\treturn\n\t}\n\ttc.queue.Add(key)\n}","line":{"from":124,"to":131}} {"id":100003246,"name":"worker","signature":"func (tc *TokenCleaner) worker(ctx context.Context)","file":"pkg/controller/bootstrap/tokencleaner.go","code":"// worker runs a thread that dequeues secrets, handles them, and marks them done.\nfunc (tc *TokenCleaner) worker(ctx context.Context) {\n\tfor tc.processNextWorkItem(ctx) {\n\t}\n}","line":{"from":133,"to":137}} {"id":100003247,"name":"processNextWorkItem","signature":"func (tc *TokenCleaner) processNextWorkItem(ctx context.Context) bool","file":"pkg/controller/bootstrap/tokencleaner.go","code":"// processNextWorkItem deals with one key off the queue. It returns false when it's time to quit.\nfunc (tc *TokenCleaner) processNextWorkItem(ctx context.Context) bool {\n\tkey, quit := tc.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer tc.queue.Done(key)\n\n\tif err := tc.syncFunc(ctx, key.(string)); err != nil {\n\t\ttc.queue.AddRateLimited(key)\n\t\tutilruntime.HandleError(fmt.Errorf(\"Sync %v failed with : %v\", key, err))\n\t\treturn true\n\t}\n\n\ttc.queue.Forget(key)\n\treturn true\n}","line":{"from":139,"to":155}} {"id":100003248,"name":"syncFunc","signature":"func (tc *TokenCleaner) syncFunc(ctx context.Context, key string) error","file":"pkg/controller/bootstrap/tokencleaner.go","code":"func (tc *TokenCleaner) syncFunc(ctx context.Context, key string) error {\n\tlogger := klog.FromContext(ctx)\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tlogger.V(4).Info(\"Finished syncing secret\", \"secret\", key, \"elapsedTime\", time.Since(startTime))\n\t}()\n\n\tnamespace, name, err := cache.SplitMetaNamespaceKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tret, err := tc.secretLister.Secrets(namespace).Get(name)\n\tif apierrors.IsNotFound(err) {\n\t\tlogger.V(3).Info(\"Secret has been deleted\", \"secret\", key)\n\t\treturn nil\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif ret.Type == bootstrapapi.SecretTypeBootstrapToken {\n\t\ttc.evalSecret(ctx, ret)\n\t}\n\treturn nil\n}","line":{"from":157,"to":183}} {"id":100003249,"name":"evalSecret","signature":"func (tc *TokenCleaner) evalSecret(ctx context.Context, o interface{})","file":"pkg/controller/bootstrap/tokencleaner.go","code":"func (tc *TokenCleaner) evalSecret(ctx context.Context, o interface{}) {\n\tlogger := klog.FromContext(ctx)\n\tsecret := o.(*v1.Secret)\n\tttl, alreadyExpired := bootstrapsecretutil.GetExpiration(secret, time.Now())\n\tif alreadyExpired {\n\t\tlogger.V(3).Info(\"Deleting expired secret\", \"secret\", klog.KObj(secret))\n\t\tvar options metav1.DeleteOptions\n\t\tif len(secret.UID) \u003e 0 {\n\t\t\toptions.Preconditions = \u0026metav1.Preconditions{UID: \u0026secret.UID}\n\t\t}\n\t\terr := tc.client.CoreV1().Secrets(secret.Namespace).Delete(ctx, secret.Name, options)\n\t\t// NotFound isn't a real error (it's already been deleted)\n\t\t// Conflict isn't a real error (the UID precondition failed)\n\t\tif err != nil \u0026\u0026 !apierrors.IsConflict(err) \u0026\u0026 !apierrors.IsNotFound(err) {\n\t\t\tlogger.V(3).Info(\"Error deleting secret\", \"err\", err)\n\t\t}\n\t} else if ttl \u003e 0 {\n\t\tkey, err := controller.KeyFunc(o)\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(err)\n\t\t\treturn\n\t\t}\n\t\ttc.queue.AddAfter(key, ttl)\n\t}\n}","line":{"from":185,"to":209}} {"id":100003250,"name":"validateSecretForSigning","signature":"func validateSecretForSigning(ctx context.Context, secret *v1.Secret) (tokenID, tokenSecret string, ok bool)","file":"pkg/controller/bootstrap/util.go","code":"func validateSecretForSigning(ctx context.Context, secret *v1.Secret) (tokenID, tokenSecret string, ok bool) {\n\tlogger := klog.FromContext(ctx)\n\tnameTokenID, ok := bootstrapsecretutil.ParseName(secret.Name)\n\tif !ok {\n\t\tlogger.V(3).Info(\"Invalid secret name, must be of the form \"+bootstrapapi.BootstrapTokenSecretPrefix+\"\u003csecret-id\u003e\", \"secretName\", secret.Name)\n\t\treturn \"\", \"\", false\n\t}\n\n\ttokenID = bootstrapsecretutil.GetData(secret, bootstrapapi.BootstrapTokenIDKey)\n\tif len(tokenID) == 0 {\n\t\tlogger.V(3).Info(\"No key in Secret\", \"key\", bootstrapapi.BootstrapTokenIDKey, \"secret\", klog.KObj(secret))\n\t\treturn \"\", \"\", false\n\t}\n\n\tif nameTokenID != tokenID {\n\t\tlogger.V(3).Info(\"Token ID doesn't match secret name\", \"tokenID\", tokenID, \"secretName\", secret.Name)\n\t\treturn \"\", \"\", false\n\t}\n\n\ttokenSecret = bootstrapsecretutil.GetData(secret, bootstrapapi.BootstrapTokenSecretKey)\n\tif len(tokenSecret) == 0 {\n\t\tlogger.V(3).Info(\"No key in secret\", \"key\", bootstrapapi.BootstrapTokenSecretKey, \"secret\", klog.KObj(secret))\n\t\treturn \"\", \"\", false\n\t}\n\n\t// Ensure this secret hasn't expired. The TokenCleaner should remove this\n\t// but if that isn't working or it hasn't gotten there yet we should check\n\t// here.\n\tif bootstrapsecretutil.HasExpired(secret, time.Now()) {\n\t\treturn \"\", \"\", false\n\t}\n\n\t// Make sure this secret can be used for signing\n\tokToSign := bootstrapsecretutil.GetData(secret, bootstrapapi.BootstrapTokenUsageSigningKey)\n\tif okToSign != \"true\" {\n\t\treturn \"\", \"\", false\n\t}\n\n\treturn tokenID, tokenSecret, true\n}","line":{"from":30,"to":69}} {"id":100003251,"name":"NewCSRApprovingController","signature":"func NewCSRApprovingController(client clientset.Interface, csrInformer certificatesinformers.CertificateSigningRequestInformer) *certificates.CertificateController","file":"pkg/controller/certificates/approver/sarapprove.go","code":"// NewCSRApprovingController creates a new CSRApprovingController.\nfunc NewCSRApprovingController(client clientset.Interface, csrInformer certificatesinformers.CertificateSigningRequestInformer) *certificates.CertificateController {\n\tapprover := \u0026sarApprover{\n\t\tclient: client,\n\t\trecognizers: recognizers(),\n\t}\n\treturn certificates.NewCertificateController(\n\t\t\"csrapproving\",\n\t\tclient,\n\t\tcsrInformer,\n\t\tapprover.handle,\n\t)\n}","line":{"from":48,"to":60}} {"id":100003252,"name":"recognizers","signature":"func recognizers() []csrRecognizer","file":"pkg/controller/certificates/approver/sarapprove.go","code":"func recognizers() []csrRecognizer {\n\trecognizers := []csrRecognizer{\n\t\t{\n\t\t\trecognize: isSelfNodeClientCert,\n\t\t\tpermission: authorization.ResourceAttributes{Group: \"certificates.k8s.io\", Resource: \"certificatesigningrequests\", Verb: \"create\", Subresource: \"selfnodeclient\"},\n\t\t\tsuccessMessage: \"Auto approving self kubelet client certificate after SubjectAccessReview.\",\n\t\t},\n\t\t{\n\t\t\trecognize: isNodeClientCert,\n\t\t\tpermission: authorization.ResourceAttributes{Group: \"certificates.k8s.io\", Resource: \"certificatesigningrequests\", Verb: \"create\", Subresource: \"nodeclient\"},\n\t\t\tsuccessMessage: \"Auto approving kubelet client certificate after SubjectAccessReview.\",\n\t\t},\n\t}\n\treturn recognizers\n}","line":{"from":62,"to":76}} {"id":100003253,"name":"handle","signature":"func (a *sarApprover) handle(ctx context.Context, csr *capi.CertificateSigningRequest) error","file":"pkg/controller/certificates/approver/sarapprove.go","code":"func (a *sarApprover) handle(ctx context.Context, csr *capi.CertificateSigningRequest) error {\n\tif len(csr.Status.Certificate) != 0 {\n\t\treturn nil\n\t}\n\tif approved, denied := certificates.GetCertApprovalCondition(\u0026csr.Status); approved || denied {\n\t\treturn nil\n\t}\n\tx509cr, err := capihelper.ParseCSR(csr.Spec.Request)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to parse csr %q: %v\", csr.Name, err)\n\t}\n\n\ttried := []string{}\n\n\tfor _, r := range a.recognizers {\n\t\tif !r.recognize(csr, x509cr) {\n\t\t\tcontinue\n\t\t}\n\n\t\ttried = append(tried, r.permission.Subresource)\n\n\t\tapproved, err := a.authorize(ctx, csr, r.permission)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif approved {\n\t\t\tappendApprovalCondition(csr, r.successMessage)\n\t\t\t_, err = a.client.CertificatesV1().CertificateSigningRequests().UpdateApproval(ctx, csr.Name, csr, metav1.UpdateOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error updating approval for csr: %v\", err)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tif len(tried) != 0 {\n\t\treturn certificates.IgnorableError(\"recognized csr %q as %v but subject access review was not approved\", csr.Name, tried)\n\t}\n\n\treturn nil\n}","line":{"from":78,"to":118}} {"id":100003254,"name":"authorize","signature":"func (a *sarApprover) authorize(ctx context.Context, csr *capi.CertificateSigningRequest, rattrs authorization.ResourceAttributes) (bool, error)","file":"pkg/controller/certificates/approver/sarapprove.go","code":"func (a *sarApprover) authorize(ctx context.Context, csr *capi.CertificateSigningRequest, rattrs authorization.ResourceAttributes) (bool, error) {\n\textra := make(map[string]authorization.ExtraValue)\n\tfor k, v := range csr.Spec.Extra {\n\t\textra[k] = authorization.ExtraValue(v)\n\t}\n\n\tsar := \u0026authorization.SubjectAccessReview{\n\t\tSpec: authorization.SubjectAccessReviewSpec{\n\t\t\tUser: csr.Spec.Username,\n\t\t\tUID: csr.Spec.UID,\n\t\t\tGroups: csr.Spec.Groups,\n\t\t\tExtra: extra,\n\t\t\tResourceAttributes: \u0026rattrs,\n\t\t},\n\t}\n\tsar, err := a.client.AuthorizationV1().SubjectAccessReviews().Create(ctx, sar, metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn sar.Status.Allowed, nil\n}","line":{"from":120,"to":140}} {"id":100003255,"name":"appendApprovalCondition","signature":"func appendApprovalCondition(csr *capi.CertificateSigningRequest, message string)","file":"pkg/controller/certificates/approver/sarapprove.go","code":"func appendApprovalCondition(csr *capi.CertificateSigningRequest, message string) {\n\tcsr.Status.Conditions = append(csr.Status.Conditions, capi.CertificateSigningRequestCondition{\n\t\tType: capi.CertificateApproved,\n\t\tStatus: corev1.ConditionTrue,\n\t\tReason: \"AutoApproved\",\n\t\tMessage: message,\n\t})\n}","line":{"from":142,"to":149}} {"id":100003256,"name":"isNodeClientCert","signature":"func isNodeClientCert(csr *capi.CertificateSigningRequest, x509cr *x509.CertificateRequest) bool","file":"pkg/controller/certificates/approver/sarapprove.go","code":"func isNodeClientCert(csr *capi.CertificateSigningRequest, x509cr *x509.CertificateRequest) bool {\n\tif csr.Spec.SignerName != capi.KubeAPIServerClientKubeletSignerName {\n\t\treturn false\n\t}\n\treturn capihelper.IsKubeletClientCSR(x509cr, usagesToSet(csr.Spec.Usages))\n}","line":{"from":151,"to":156}} {"id":100003257,"name":"isSelfNodeClientCert","signature":"func isSelfNodeClientCert(csr *capi.CertificateSigningRequest, x509cr *x509.CertificateRequest) bool","file":"pkg/controller/certificates/approver/sarapprove.go","code":"func isSelfNodeClientCert(csr *capi.CertificateSigningRequest, x509cr *x509.CertificateRequest) bool {\n\tif csr.Spec.Username != x509cr.Subject.CommonName {\n\t\treturn false\n\t}\n\treturn isNodeClientCert(csr, x509cr)\n}","line":{"from":158,"to":163}} {"id":100003258,"name":"usagesToSet","signature":"func usagesToSet(usages []capi.KeyUsage) sets.String","file":"pkg/controller/certificates/approver/sarapprove.go","code":"func usagesToSet(usages []capi.KeyUsage) sets.String {\n\tresult := sets.NewString()\n\tfor _, usage := range usages {\n\t\tresult.Insert(string(usage))\n\t}\n\treturn result\n}","line":{"from":165,"to":171}} {"id":100003259,"name":"Sign","signature":"func (ca *CertificateAuthority) Sign(crDER []byte, policy SigningPolicy) ([]byte, error)","file":"pkg/controller/certificates/authority/authority.go","code":"// Sign signs a certificate request, applying a SigningPolicy and returns a DER\n// encoded x509 certificate.\nfunc (ca *CertificateAuthority) Sign(crDER []byte, policy SigningPolicy) ([]byte, error) {\n\tcr, err := x509.ParseCertificateRequest(crDER)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to parse certificate request: %v\", err)\n\t}\n\tif err := cr.CheckSignature(); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to verify certificate request signature: %v\", err)\n\t}\n\n\tserialNumber, err := rand.Int(rand.Reader, serialNumberLimit)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to generate a serial number for %s: %v\", cr.Subject.CommonName, err)\n\t}\n\n\ttmpl := \u0026x509.Certificate{\n\t\tSerialNumber: serialNumber,\n\t\tSubject: cr.Subject,\n\t\tDNSNames: cr.DNSNames,\n\t\tIPAddresses: cr.IPAddresses,\n\t\tEmailAddresses: cr.EmailAddresses,\n\t\tURIs: cr.URIs,\n\t\tPublicKeyAlgorithm: cr.PublicKeyAlgorithm,\n\t\tPublicKey: cr.PublicKey,\n\t\tExtensions: cr.Extensions,\n\t\tExtraExtensions: cr.ExtraExtensions,\n\t}\n\tif err := policy.apply(tmpl, ca.Certificate.NotAfter); err != nil {\n\t\treturn nil, err\n\t}\n\n\tder, err := x509.CreateCertificate(rand.Reader, tmpl, ca.Certificate, cr.PublicKey, ca.PrivateKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to sign certificate: %v\", err)\n\t}\n\treturn der, nil\n}","line":{"from":41,"to":78}} {"id":100003260,"name":"apply","signature":"func (p PermissiveSigningPolicy) apply(tmpl *x509.Certificate, signerNotAfter time.Time) error","file":"pkg/controller/certificates/authority/policies.go","code":"func (p PermissiveSigningPolicy) apply(tmpl *x509.Certificate, signerNotAfter time.Time) error {\n\tvar now time.Time\n\tif p.Now != nil {\n\t\tnow = p.Now()\n\t} else {\n\t\tnow = time.Now()\n\t}\n\n\tttl := p.TTL\n\n\tusage, extUsages, err := keyUsagesFromStrings(p.Usages)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttmpl.KeyUsage = usage\n\ttmpl.ExtKeyUsage = extUsages\n\n\ttmpl.ExtraExtensions = nil\n\ttmpl.Extensions = nil\n\ttmpl.BasicConstraintsValid = true\n\ttmpl.IsCA = false\n\n\ttmpl.NotBefore = now.Add(-p.Backdate)\n\n\tif ttl \u003c p.Short {\n\t\t// do not backdate the end time if we consider this to be a short lived certificate\n\t\ttmpl.NotAfter = now.Add(ttl)\n\t} else {\n\t\ttmpl.NotAfter = now.Add(ttl - p.Backdate)\n\t}\n\n\tif !tmpl.NotAfter.Before(signerNotAfter) {\n\t\ttmpl.NotAfter = signerNotAfter\n\t}\n\n\tif !tmpl.NotBefore.Before(signerNotAfter) {\n\t\treturn fmt.Errorf(\"the signer has expired: NotAfter=%v\", signerNotAfter)\n\t}\n\n\tif !now.Before(signerNotAfter) {\n\t\treturn fmt.Errorf(\"refusing to sign a certificate that expired in the past: NotAfter=%v\", signerNotAfter)\n\t}\n\n\treturn nil\n}","line":{"from":68,"to":112}} {"id":100003261,"name":"keyUsagesFromStrings","signature":"func keyUsagesFromStrings(usages []capi.KeyUsage) (x509.KeyUsage, []x509.ExtKeyUsage, error)","file":"pkg/controller/certificates/authority/policies.go","code":"// keyUsagesFromStrings will translate a slice of usage strings from the\n// certificates API (\"pkg/apis/certificates\".KeyUsage) to x509.KeyUsage and\n// x509.ExtKeyUsage types.\nfunc keyUsagesFromStrings(usages []capi.KeyUsage) (x509.KeyUsage, []x509.ExtKeyUsage, error) {\n\tvar keyUsage x509.KeyUsage\n\tvar unrecognized []capi.KeyUsage\n\textKeyUsages := make(map[x509.ExtKeyUsage]struct{})\n\tfor _, usage := range usages {\n\t\tif val, ok := keyUsageDict[usage]; ok {\n\t\t\tkeyUsage |= val\n\t\t} else if val, ok := extKeyUsageDict[usage]; ok {\n\t\t\textKeyUsages[val] = struct{}{}\n\t\t} else {\n\t\t\tunrecognized = append(unrecognized, usage)\n\t\t}\n\t}\n\n\tvar sorted sortedExtKeyUsage\n\tfor eku := range extKeyUsages {\n\t\tsorted = append(sorted, eku)\n\t}\n\tsort.Sort(sorted)\n\n\tif len(unrecognized) \u003e 0 {\n\t\treturn 0, nil, fmt.Errorf(\"unrecognized usage values: %q\", unrecognized)\n\t}\n\n\treturn keyUsage, sorted, nil\n}","line":{"from":143,"to":171}} {"id":100003262,"name":"Len","signature":"func (s sortedExtKeyUsage) Len() int","file":"pkg/controller/certificates/authority/policies.go","code":"func (s sortedExtKeyUsage) Len() int {\n\treturn len(s)\n}","line":{"from":175,"to":177}} {"id":100003263,"name":"Swap","signature":"func (s sortedExtKeyUsage) Swap(i, j int)","file":"pkg/controller/certificates/authority/policies.go","code":"func (s sortedExtKeyUsage) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}","line":{"from":179,"to":181}} {"id":100003264,"name":"Less","signature":"func (s sortedExtKeyUsage) Less(i, j int) bool","file":"pkg/controller/certificates/authority/policies.go","code":"func (s sortedExtKeyUsage) Less(i, j int) bool {\n\treturn s[i] \u003c s[j]\n}","line":{"from":183,"to":185}} {"id":100003265,"name":"NewCertificateController","signature":"func NewCertificateController(","file":"pkg/controller/certificates/certificate_controller.go","code":"func NewCertificateController(\n\tname string,\n\tkubeClient clientset.Interface,\n\tcsrInformer certificatesinformers.CertificateSigningRequestInformer,\n\thandler func(context.Context, *certificates.CertificateSigningRequest) error,\n) *CertificateController {\n\tcc := \u0026CertificateController{\n\t\tname: name,\n\t\tkubeClient: kubeClient,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.NewMaxOfRateLimiter(\n\t\t\tworkqueue.NewItemExponentialFailureRateLimiter(200*time.Millisecond, 1000*time.Second),\n\t\t\t// 10 qps, 100 bucket size. This is only for retry speed and its only the overall factor (not per item)\n\t\t\t\u0026workqueue.BucketRateLimiter{Limiter: rate.NewLimiter(rate.Limit(10), 100)},\n\t\t), \"certificate\"),\n\t\thandler: handler,\n\t}\n\n\t// Manage the addition/update of certificate requests\n\tcsrInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tcsr := obj.(*certificates.CertificateSigningRequest)\n\t\t\tklog.V(4).Infof(\"Adding certificate request %s\", csr.Name)\n\t\t\tcc.enqueueCertificateRequest(obj)\n\t\t},\n\t\tUpdateFunc: func(old, new interface{}) {\n\t\t\toldCSR := old.(*certificates.CertificateSigningRequest)\n\t\t\tklog.V(4).Infof(\"Updating certificate request %s\", oldCSR.Name)\n\t\t\tcc.enqueueCertificateRequest(new)\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tcsr, ok := obj.(*certificates.CertificateSigningRequest)\n\t\t\tif !ok {\n\t\t\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\t\t\tif !ok {\n\t\t\t\t\tklog.V(2).Infof(\"Couldn't get object from tombstone %#v\", obj)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcsr, ok = tombstone.Obj.(*certificates.CertificateSigningRequest)\n\t\t\t\tif !ok {\n\t\t\t\t\tklog.V(2).Infof(\"Tombstone contained object that is not a CSR: %#v\", obj)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tklog.V(4).Infof(\"Deleting certificate request %s\", csr.Name)\n\t\t\tcc.enqueueCertificateRequest(obj)\n\t\t},\n\t})\n\tcc.csrLister = csrInformer.Lister()\n\tcc.csrsSynced = csrInformer.Informer().HasSynced\n\treturn cc\n}","line":{"from":55,"to":105}} {"id":100003266,"name":"Run","signature":"func (cc *CertificateController) Run(ctx context.Context, workers int)","file":"pkg/controller/certificates/certificate_controller.go","code":"// Run the main goroutine responsible for watching and syncing jobs.\nfunc (cc *CertificateController) Run(ctx context.Context, workers int) {\n\tdefer utilruntime.HandleCrash()\n\tdefer cc.queue.ShutDown()\n\n\tklog.Infof(\"Starting certificate controller %q\", cc.name)\n\tdefer klog.Infof(\"Shutting down certificate controller %q\", cc.name)\n\n\tif !cache.WaitForNamedCacheSync(fmt.Sprintf(\"certificate-%s\", cc.name), ctx.Done(), cc.csrsSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.UntilWithContext(ctx, cc.worker, time.Second)\n\t}\n\n\t\u003c-ctx.Done()\n}","line":{"from":107,"to":124}} {"id":100003267,"name":"worker","signature":"func (cc *CertificateController) worker(ctx context.Context)","file":"pkg/controller/certificates/certificate_controller.go","code":"// worker runs a thread that dequeues CSRs, handles them, and marks them done.\nfunc (cc *CertificateController) worker(ctx context.Context) {\n\tfor cc.processNextWorkItem(ctx) {\n\t}\n}","line":{"from":126,"to":130}} {"id":100003268,"name":"processNextWorkItem","signature":"func (cc *CertificateController) processNextWorkItem(ctx context.Context) bool","file":"pkg/controller/certificates/certificate_controller.go","code":"// processNextWorkItem deals with one key off the queue. It returns false when it's time to quit.\nfunc (cc *CertificateController) processNextWorkItem(ctx context.Context) bool {\n\tcKey, quit := cc.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer cc.queue.Done(cKey)\n\n\tif err := cc.syncFunc(ctx, cKey.(string)); err != nil {\n\t\tcc.queue.AddRateLimited(cKey)\n\t\tif _, ignorable := err.(ignorableError); !ignorable {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"Sync %v failed with : %v\", cKey, err))\n\t\t} else {\n\t\t\tklog.V(4).Infof(\"Sync %v failed with : %v\", cKey, err)\n\t\t}\n\t\treturn true\n\t}\n\n\tcc.queue.Forget(cKey)\n\treturn true\n\n}","line":{"from":132,"to":153}} {"id":100003269,"name":"enqueueCertificateRequest","signature":"func (cc *CertificateController) enqueueCertificateRequest(obj interface{})","file":"pkg/controller/certificates/certificate_controller.go","code":"func (cc *CertificateController) enqueueCertificateRequest(obj interface{}) {\n\tkey, err := controller.KeyFunc(obj)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Couldn't get key for object %+v: %v\", obj, err))\n\t\treturn\n\t}\n\tcc.queue.Add(key)\n}","line":{"from":155,"to":162}} {"id":100003270,"name":"syncFunc","signature":"func (cc *CertificateController) syncFunc(ctx context.Context, key string) error","file":"pkg/controller/certificates/certificate_controller.go","code":"func (cc *CertificateController) syncFunc(ctx context.Context, key string) error {\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tklog.V(4).Infof(\"Finished syncing certificate request %q (%v)\", key, time.Since(startTime))\n\t}()\n\tcsr, err := cc.csrLister.Get(key)\n\tif errors.IsNotFound(err) {\n\t\tklog.V(3).Infof(\"csr has been deleted: %v\", key)\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(csr.Status.Certificate) \u003e 0 {\n\t\t// no need to do anything because it already has a cert\n\t\treturn nil\n\t}\n\n\t// need to operate on a copy so we don't mutate the csr in the shared cache\n\tcsr = csr.DeepCopy()\n\treturn cc.handler(ctx, csr)\n}","line":{"from":164,"to":186}} {"id":100003271,"name":"IgnorableError","signature":"func IgnorableError(s string, args ...interface{}) ignorableError","file":"pkg/controller/certificates/certificate_controller.go","code":"// IgnorableError returns an error that we shouldn't handle (i.e. log) because\n// it's spammy and usually user error. Instead we will log these errors at a\n// higher log level. We still need to throw these errors to signal that the\n// sync should be retried.\nfunc IgnorableError(s string, args ...interface{}) ignorableError {\n\treturn ignorableError(fmt.Sprintf(s, args...))\n}","line":{"from":188,"to":194}} {"id":100003272,"name":"Error","signature":"func (e ignorableError) Error() string","file":"pkg/controller/certificates/certificate_controller.go","code":"func (e ignorableError) Error() string {\n\treturn string(e)\n}","line":{"from":198,"to":200}} {"id":100003273,"name":"IsCertificateRequestApproved","signature":"func IsCertificateRequestApproved(csr *certificates.CertificateSigningRequest) bool","file":"pkg/controller/certificates/certificate_controller_utils.go","code":"// IsCertificateRequestApproved returns true if a certificate request has the\n// \"Approved\" condition and no \"Denied\" conditions; false otherwise.\nfunc IsCertificateRequestApproved(csr *certificates.CertificateSigningRequest) bool {\n\tapproved, denied := GetCertApprovalCondition(\u0026csr.Status)\n\treturn approved \u0026\u0026 !denied\n}","line":{"from":24,"to":29}} {"id":100003274,"name":"HasTrueCondition","signature":"func HasTrueCondition(csr *certificates.CertificateSigningRequest, conditionType certificates.RequestConditionType) bool","file":"pkg/controller/certificates/certificate_controller_utils.go","code":"// HasTrueCondition returns true if the csr contains a condition of the specified type with a status that is set to True or is empty\nfunc HasTrueCondition(csr *certificates.CertificateSigningRequest, conditionType certificates.RequestConditionType) bool {\n\tfor _, c := range csr.Status.Conditions {\n\t\tif c.Type == conditionType \u0026\u0026 (len(c.Status) == 0 || c.Status == v1.ConditionTrue) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":31,"to":39}} {"id":100003275,"name":"GetCertApprovalCondition","signature":"func GetCertApprovalCondition(status *certificates.CertificateSigningRequestStatus) (approved bool, denied bool)","file":"pkg/controller/certificates/certificate_controller_utils.go","code":"func GetCertApprovalCondition(status *certificates.CertificateSigningRequestStatus) (approved bool, denied bool) {\n\tfor _, c := range status.Conditions {\n\t\tif c.Type == certificates.CertificateApproved {\n\t\t\tapproved = true\n\t\t}\n\t\tif c.Type == certificates.CertificateDenied {\n\t\t\tdenied = true\n\t\t}\n\t}\n\treturn\n}","line":{"from":41,"to":51}} {"id":100003276,"name":"NewCSRCleanerController","signature":"func NewCSRCleanerController(","file":"pkg/controller/certificates/cleaner/cleaner.go","code":"// NewCSRCleanerController creates a new CSRCleanerController.\nfunc NewCSRCleanerController(\n\tcsrClient csrclient.CertificateSigningRequestInterface,\n\tcsrInformer certificatesinformers.CertificateSigningRequestInformer,\n) *CSRCleanerController {\n\treturn \u0026CSRCleanerController{\n\t\tcsrClient: csrClient,\n\t\tcsrLister: csrInformer.Lister(),\n\t}\n}","line":{"from":67,"to":76}} {"id":100003277,"name":"Run","signature":"func (ccc *CSRCleanerController) Run(ctx context.Context, workers int)","file":"pkg/controller/certificates/cleaner/cleaner.go","code":"// Run the main goroutine responsible for watching and syncing jobs.\nfunc (ccc *CSRCleanerController) Run(ctx context.Context, workers int) {\n\tdefer utilruntime.HandleCrash()\n\n\tklog.Infof(\"Starting CSR cleaner controller\")\n\tdefer klog.Infof(\"Shutting down CSR cleaner controller\")\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.UntilWithContext(ctx, ccc.worker, pollingInterval)\n\t}\n\n\t\u003c-ctx.Done()\n}","line":{"from":78,"to":90}} {"id":100003278,"name":"worker","signature":"func (ccc *CSRCleanerController) worker(ctx context.Context)","file":"pkg/controller/certificates/cleaner/cleaner.go","code":"// worker runs a thread that dequeues CSRs, handles them, and marks them done.\nfunc (ccc *CSRCleanerController) worker(ctx context.Context) {\n\tcsrs, err := ccc.csrLister.List(labels.Everything())\n\tif err != nil {\n\t\tklog.Errorf(\"Unable to list CSRs: %v\", err)\n\t\treturn\n\t}\n\tfor _, csr := range csrs {\n\t\tif err := ccc.handle(ctx, csr); err != nil {\n\t\t\tklog.Errorf(\"Error while attempting to clean CSR %q: %v\", csr.Name, err)\n\t\t}\n\t}\n}","line":{"from":92,"to":104}} {"id":100003279,"name":"handle","signature":"func (ccc *CSRCleanerController) handle(ctx context.Context, csr *capi.CertificateSigningRequest) error","file":"pkg/controller/certificates/cleaner/cleaner.go","code":"func (ccc *CSRCleanerController) handle(ctx context.Context, csr *capi.CertificateSigningRequest) error {\n\tif isIssuedPastDeadline(csr) || isDeniedPastDeadline(csr) || isFailedPastDeadline(csr) || isPendingPastDeadline(csr) || isIssuedExpired(csr) {\n\t\tif err := ccc.csrClient.Delete(ctx, csr.Name, metav1.DeleteOptions{}); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to delete CSR %q: %v\", csr.Name, err)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":106,"to":113}} {"id":100003280,"name":"isIssuedExpired","signature":"func isIssuedExpired(csr *capi.CertificateSigningRequest) bool","file":"pkg/controller/certificates/cleaner/cleaner.go","code":"// isIssuedExpired checks if the CSR has been issued a certificate and if the\n// expiration of the certificate (the NotAfter value) has passed.\nfunc isIssuedExpired(csr *capi.CertificateSigningRequest) bool {\n\tfor _, c := range csr.Status.Conditions {\n\t\tif c.Type == capi.CertificateApproved \u0026\u0026 isIssued(csr) \u0026\u0026 isExpired(csr) {\n\t\t\tklog.Infof(\"Cleaning CSR %q as the associated certificate is expired.\", csr.Name)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":115,"to":125}} {"id":100003281,"name":"isPendingPastDeadline","signature":"func isPendingPastDeadline(csr *capi.CertificateSigningRequest) bool","file":"pkg/controller/certificates/cleaner/cleaner.go","code":"// isPendingPastDeadline checks if the certificate has a Pending status and the\n// creation time of the CSR is passed the deadline that pending requests are\n// maintained for.\nfunc isPendingPastDeadline(csr *capi.CertificateSigningRequest) bool {\n\t// If there are no Conditions on the status, the CSR will appear via\n\t// `kubectl` as `Pending`.\n\tif len(csr.Status.Conditions) == 0 \u0026\u0026 isOlderThan(csr.CreationTimestamp, pendingExpiration) {\n\t\tklog.Infof(\"Cleaning CSR %q as it is more than %v old and unhandled.\", csr.Name, pendingExpiration)\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":127,"to":138}} {"id":100003282,"name":"isDeniedPastDeadline","signature":"func isDeniedPastDeadline(csr *capi.CertificateSigningRequest) bool","file":"pkg/controller/certificates/cleaner/cleaner.go","code":"// isDeniedPastDeadline checks if the certificate has a Denied status and the\n// creation time of the CSR is passed the deadline that denied requests are\n// maintained for.\nfunc isDeniedPastDeadline(csr *capi.CertificateSigningRequest) bool {\n\tfor _, c := range csr.Status.Conditions {\n\t\tif c.Type == capi.CertificateDenied \u0026\u0026 isOlderThan(c.LastUpdateTime, deniedExpiration) {\n\t\t\tklog.Infof(\"Cleaning CSR %q as it is more than %v old and denied.\", csr.Name, deniedExpiration)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":140,"to":151}} {"id":100003283,"name":"isFailedPastDeadline","signature":"func isFailedPastDeadline(csr *capi.CertificateSigningRequest) bool","file":"pkg/controller/certificates/cleaner/cleaner.go","code":"// isFailedPastDeadline checks if the certificate has a Failed status and the\n// creation time of the CSR is passed the deadline that pending requests are\n// maintained for.\nfunc isFailedPastDeadline(csr *capi.CertificateSigningRequest) bool {\n\tfor _, c := range csr.Status.Conditions {\n\t\tif c.Type == capi.CertificateFailed \u0026\u0026 isOlderThan(c.LastUpdateTime, deniedExpiration) {\n\t\t\tklog.Infof(\"Cleaning CSR %q as it is more than %v old and failed.\", csr.Name, deniedExpiration)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":153,"to":164}} {"id":100003284,"name":"isIssuedPastDeadline","signature":"func isIssuedPastDeadline(csr *capi.CertificateSigningRequest) bool","file":"pkg/controller/certificates/cleaner/cleaner.go","code":"// isIssuedPastDeadline checks if the certificate has an Issued status and the\n// creation time of the CSR is passed the deadline that issued requests are\n// maintained for.\nfunc isIssuedPastDeadline(csr *capi.CertificateSigningRequest) bool {\n\tfor _, c := range csr.Status.Conditions {\n\t\tif c.Type == capi.CertificateApproved \u0026\u0026 isIssued(csr) \u0026\u0026 isOlderThan(c.LastUpdateTime, approvedExpiration) {\n\t\t\tklog.Infof(\"Cleaning CSR %q as it is more than %v old and approved.\", csr.Name, approvedExpiration)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":166,"to":177}} {"id":100003285,"name":"isOlderThan","signature":"func isOlderThan(t metav1.Time, d time.Duration) bool","file":"pkg/controller/certificates/cleaner/cleaner.go","code":"// isOlderThan checks that t is a non-zero time after time.Now() + d.\nfunc isOlderThan(t metav1.Time, d time.Duration) bool {\n\treturn !t.IsZero() \u0026\u0026 t.Sub(time.Now()) \u003c -1*d\n}","line":{"from":179,"to":182}} {"id":100003286,"name":"isIssued","signature":"func isIssued(csr *capi.CertificateSigningRequest) bool","file":"pkg/controller/certificates/cleaner/cleaner.go","code":"// isIssued checks if the CSR has `Issued` status. There is no explicit\n// 'Issued' status. Implicitly, if there is a certificate associated with the\n// CSR, the CSR statuses that are visible via `kubectl` will include 'Issued'.\nfunc isIssued(csr *capi.CertificateSigningRequest) bool {\n\treturn len(csr.Status.Certificate) \u003e 0\n}","line":{"from":184,"to":189}} {"id":100003287,"name":"isExpired","signature":"func isExpired(csr *capi.CertificateSigningRequest) bool","file":"pkg/controller/certificates/cleaner/cleaner.go","code":"// isExpired checks if the CSR has a certificate and the date in the `NotAfter`\n// field has gone by.\nfunc isExpired(csr *capi.CertificateSigningRequest) bool {\n\tif len(csr.Status.Certificate) == 0 {\n\t\treturn false\n\t}\n\tblock, _ := pem.Decode(csr.Status.Certificate)\n\tif block == nil {\n\t\treturn false\n\t}\n\tcerts, err := x509.ParseCertificates(block.Bytes)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif len(certs) == 0 {\n\t\treturn false\n\t}\n\treturn time.Now().After(certs[0].NotAfter)\n}","line":{"from":191,"to":209}} {"id":100003288,"name":"recordMetrics","signature":"func recordMetrics(start time.Time, err error)","file":"pkg/controller/certificates/rootcacertpublisher/metrics.go","code":"func recordMetrics(start time.Time, err error) {\n\tcode := \"500\"\n\tif err == nil {\n\t\tcode = \"200\"\n\t} else if se, ok := err.(*apierrors.StatusError); ok \u0026\u0026 se.Status().Code != 0 {\n\t\tcode = strconv.Itoa(int(se.Status().Code))\n\t}\n\tsyncLatency.WithLabelValues(code).Observe(time.Since(start).Seconds())\n\tsyncCounter.WithLabelValues(code).Inc()\n}","line":{"from":54,"to":63}} {"id":100003289,"name":"registerMetrics","signature":"func registerMetrics()","file":"pkg/controller/certificates/rootcacertpublisher/metrics.go","code":"func registerMetrics() {\n\tonce.Do(func() {\n\t\tlegacyregistry.MustRegister(syncCounter)\n\t\tlegacyregistry.MustRegister(syncLatency)\n\t})\n}","line":{"from":67,"to":72}} {"id":100003290,"name":"init","signature":"func init()","file":"pkg/controller/certificates/rootcacertpublisher/publisher.go","code":"func init() {\n\tregisterMetrics()\n}","line":{"from":47,"to":49}} {"id":100003291,"name":"NewPublisher","signature":"func NewPublisher(cmInformer coreinformers.ConfigMapInformer, nsInformer coreinformers.NamespaceInformer, cl clientset.Interface, rootCA []byte) (*Publisher, error)","file":"pkg/controller/certificates/rootcacertpublisher/publisher.go","code":"// NewPublisher construct a new controller which would manage the configmap\n// which stores certificates in each namespace. It will make sure certificate\n// configmap exists in each namespace.\nfunc NewPublisher(cmInformer coreinformers.ConfigMapInformer, nsInformer coreinformers.NamespaceInformer, cl clientset.Interface, rootCA []byte) (*Publisher, error) {\n\te := \u0026Publisher{\n\t\tclient: cl,\n\t\trootCA: rootCA,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"root_ca_cert_publisher\"),\n\t}\n\n\tcmInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tDeleteFunc: e.configMapDeleted,\n\t\tUpdateFunc: e.configMapUpdated,\n\t})\n\te.cmLister = cmInformer.Lister()\n\te.cmListerSynced = cmInformer.Informer().HasSynced\n\n\tnsInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: e.namespaceAdded,\n\t\tUpdateFunc: e.namespaceUpdated,\n\t})\n\te.nsListerSynced = nsInformer.Informer().HasSynced\n\n\te.syncHandler = e.syncNamespace\n\n\treturn e, nil\n\n}","line":{"from":51,"to":78}} {"id":100003292,"name":"Run","signature":"func (c *Publisher) Run(ctx context.Context, workers int)","file":"pkg/controller/certificates/rootcacertpublisher/publisher.go","code":"// Run starts process\nfunc (c *Publisher) Run(ctx context.Context, workers int) {\n\tdefer utilruntime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\n\tklog.Infof(\"Starting root CA certificate configmap publisher\")\n\tdefer klog.Infof(\"Shutting down root CA certificate configmap publisher\")\n\n\tif !cache.WaitForNamedCacheSync(\"crt configmap\", ctx.Done(), c.cmListerSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.UntilWithContext(ctx, c.runWorker, time.Second)\n\t}\n\n\t\u003c-ctx.Done()\n}","line":{"from":96,"to":113}} {"id":100003293,"name":"configMapDeleted","signature":"func (c *Publisher) configMapDeleted(obj interface{})","file":"pkg/controller/certificates/rootcacertpublisher/publisher.go","code":"func (c *Publisher) configMapDeleted(obj interface{}) {\n\tcm, err := convertToCM(obj)\n\tif err != nil {\n\t\tutilruntime.HandleError(err)\n\t\treturn\n\t}\n\tif cm.Name != RootCACertConfigMapName {\n\t\treturn\n\t}\n\tc.queue.Add(cm.Namespace)\n}","line":{"from":115,"to":125}} {"id":100003294,"name":"configMapUpdated","signature":"func (c *Publisher) configMapUpdated(_, newObj interface{})","file":"pkg/controller/certificates/rootcacertpublisher/publisher.go","code":"func (c *Publisher) configMapUpdated(_, newObj interface{}) {\n\tcm, err := convertToCM(newObj)\n\tif err != nil {\n\t\tutilruntime.HandleError(err)\n\t\treturn\n\t}\n\tif cm.Name != RootCACertConfigMapName {\n\t\treturn\n\t}\n\tc.queue.Add(cm.Namespace)\n}","line":{"from":127,"to":137}} {"id":100003295,"name":"namespaceAdded","signature":"func (c *Publisher) namespaceAdded(obj interface{})","file":"pkg/controller/certificates/rootcacertpublisher/publisher.go","code":"func (c *Publisher) namespaceAdded(obj interface{}) {\n\tnamespace := obj.(*v1.Namespace)\n\tc.queue.Add(namespace.Name)\n}","line":{"from":139,"to":142}} {"id":100003296,"name":"namespaceUpdated","signature":"func (c *Publisher) namespaceUpdated(oldObj interface{}, newObj interface{})","file":"pkg/controller/certificates/rootcacertpublisher/publisher.go","code":"func (c *Publisher) namespaceUpdated(oldObj interface{}, newObj interface{}) {\n\tnewNamespace := newObj.(*v1.Namespace)\n\tif newNamespace.Status.Phase != v1.NamespaceActive {\n\t\treturn\n\t}\n\tc.queue.Add(newNamespace.Name)\n}","line":{"from":144,"to":150}} {"id":100003297,"name":"runWorker","signature":"func (c *Publisher) runWorker(ctx context.Context)","file":"pkg/controller/certificates/rootcacertpublisher/publisher.go","code":"func (c *Publisher) runWorker(ctx context.Context) {\n\tfor c.processNextWorkItem(ctx) {\n\t}\n}","line":{"from":152,"to":155}} {"id":100003298,"name":"processNextWorkItem","signature":"func (c *Publisher) processNextWorkItem(ctx context.Context) bool","file":"pkg/controller/certificates/rootcacertpublisher/publisher.go","code":"// processNextWorkItem deals with one key off the queue. It returns false when\n// it's time to quit.\nfunc (c *Publisher) processNextWorkItem(ctx context.Context) bool {\n\tkey, quit := c.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.queue.Done(key)\n\n\tif err := c.syncHandler(ctx, key.(string)); err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"syncing %q failed: %v\", key, err))\n\t\tc.queue.AddRateLimited(key)\n\t\treturn true\n\t}\n\n\tc.queue.Forget(key)\n\treturn true\n}","line":{"from":157,"to":174}} {"id":100003299,"name":"syncNamespace","signature":"func (c *Publisher) syncNamespace(ctx context.Context, ns string) (err error)","file":"pkg/controller/certificates/rootcacertpublisher/publisher.go","code":"func (c *Publisher) syncNamespace(ctx context.Context, ns string) (err error) {\n\tstartTime := time.Now()\n\tdefer func() {\n\t\trecordMetrics(startTime, err)\n\t\tklog.V(4).Infof(\"Finished syncing namespace %q (%v)\", ns, time.Since(startTime))\n\t}()\n\n\tcm, err := c.cmLister.ConfigMaps(ns).Get(RootCACertConfigMapName)\n\tswitch {\n\tcase apierrors.IsNotFound(err):\n\t\t_, err = c.client.CoreV1().ConfigMaps(ns).Create(ctx, \u0026v1.ConfigMap{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: RootCACertConfigMapName,\n\t\t\t\tAnnotations: map[string]string{DescriptionAnnotation: Description},\n\t\t\t},\n\t\t\tData: map[string]string{\n\t\t\t\t\"ca.crt\": string(c.rootCA),\n\t\t\t},\n\t\t}, metav1.CreateOptions{})\n\t\t// don't retry a create if the namespace doesn't exist or is terminating\n\t\tif apierrors.IsNotFound(err) || apierrors.HasStatusCause(err, v1.NamespaceTerminatingCause) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\tcase err != nil:\n\t\treturn err\n\t}\n\n\tdata := map[string]string{\n\t\t\"ca.crt\": string(c.rootCA),\n\t}\n\n\t// ensure the data and the one annotation describing usage of this configmap match.\n\tif reflect.DeepEqual(cm.Data, data) \u0026\u0026 len(cm.Annotations[DescriptionAnnotation]) \u003e 0 {\n\t\treturn nil\n\t}\n\n\t// copy so we don't modify the cache's instance of the configmap\n\tcm = cm.DeepCopy()\n\tcm.Data = data\n\tif cm.Annotations == nil {\n\t\tcm.Annotations = map[string]string{}\n\t}\n\tcm.Annotations[DescriptionAnnotation] = Description\n\n\t_, err = c.client.CoreV1().ConfigMaps(ns).Update(ctx, cm, metav1.UpdateOptions{})\n\treturn err\n}","line":{"from":176,"to":223}} {"id":100003300,"name":"convertToCM","signature":"func convertToCM(obj interface{}) (*v1.ConfigMap, error)","file":"pkg/controller/certificates/rootcacertpublisher/publisher.go","code":"func convertToCM(obj interface{}) (*v1.ConfigMap, error) {\n\tcm, ok := obj.(*v1.ConfigMap)\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"couldn't get object from tombstone %#v\", obj)\n\t\t}\n\t\tcm, ok = tombstone.Obj.(*v1.ConfigMap)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"tombstone contained object that is not a ConfigMap %#v\", obj)\n\t\t}\n\t}\n\treturn cm, nil\n}","line":{"from":225,"to":238}} {"id":100003301,"name":"newCAProvider","signature":"func newCAProvider(caFile, caKeyFile string) (*caProvider, error)","file":"pkg/controller/certificates/signer/ca_provider.go","code":"func newCAProvider(caFile, caKeyFile string) (*caProvider, error) {\n\tcaLoader, err := dynamiccertificates.NewDynamicServingContentFromFiles(\"csr-controller\", caFile, caKeyFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading CA cert file %q: %v\", caFile, err)\n\t}\n\n\tret := \u0026caProvider{\n\t\tcaLoader: caLoader,\n\t}\n\tif err := ret.setCA(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ret, nil\n}","line":{"from":31,"to":45}} {"id":100003302,"name":"setCA","signature":"func (p *caProvider) setCA() error","file":"pkg/controller/certificates/signer/ca_provider.go","code":"// setCA unconditionally stores the current cert/key content\nfunc (p *caProvider) setCA() error {\n\tcertPEM, keyPEM := p.caLoader.CurrentCertKeyContent()\n\n\tcerts, err := cert.ParseCertsPEM(certPEM)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error reading CA cert file %q: %v\", p.caLoader.Name(), err)\n\t}\n\tif len(certs) != 1 {\n\t\treturn fmt.Errorf(\"error reading CA cert file %q: expected 1 certificate, found %d\", p.caLoader.Name(), len(certs))\n\t}\n\n\tkey, err := keyutil.ParsePrivateKeyPEM(keyPEM)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error reading CA key file %q: %v\", p.caLoader.Name(), err)\n\t}\n\tpriv, ok := key.(crypto.Signer)\n\tif !ok {\n\t\treturn fmt.Errorf(\"error reading CA key file %q: key did not implement crypto.Signer\", p.caLoader.Name())\n\t}\n\n\tca := \u0026authority.CertificateAuthority{\n\t\tRawCert: certPEM,\n\t\tRawKey: keyPEM,\n\n\t\tCertificate: certs[0],\n\t\tPrivateKey: priv,\n\t}\n\tp.caValue.Store(ca)\n\n\treturn nil\n}","line":{"from":52,"to":83}} {"id":100003303,"name":"currentCA","signature":"func (p *caProvider) currentCA() (*authority.CertificateAuthority, error)","file":"pkg/controller/certificates/signer/ca_provider.go","code":"// currentCA provides the current value of the CA.\n// It always check for a stale value. This is cheap because it's all an in memory cache of small slices.\nfunc (p *caProvider) currentCA() (*authority.CertificateAuthority, error) {\n\tcertPEM, keyPEM := p.caLoader.CurrentCertKeyContent()\n\tcurrCA := p.caValue.Load().(*authority.CertificateAuthority)\n\tif bytes.Equal(currCA.RawCert, certPEM) \u0026\u0026 bytes.Equal(currCA.RawKey, keyPEM) {\n\t\treturn currCA, nil\n\t}\n\n\t// the bytes weren't equal, so we have to set and then load\n\tif err := p.setCA(); err != nil {\n\t\treturn currCA, err\n\t}\n\treturn p.caValue.Load().(*authority.CertificateAuthority), nil\n}","line":{"from":85,"to":99}} {"id":100003304,"name":"Convert_v1alpha1_CSRSigningControllerConfiguration_To_config_CSRSigningControllerConfiguration","signature":"func Convert_v1alpha1_CSRSigningControllerConfiguration_To_config_CSRSigningControllerConfiguration(in *v1alpha1.CSRSigningControllerConfiguration, out *csrsigningconfig.CSRSigningControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/certificates/signer/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_CSRSigningControllerConfiguration_To_config_CSRSigningControllerConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_CSRSigningControllerConfiguration_To_config_CSRSigningControllerConfiguration(in *v1alpha1.CSRSigningControllerConfiguration, out *csrsigningconfig.CSRSigningControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_CSRSigningControllerConfiguration_To_config_CSRSigningControllerConfiguration(in, out, s)\n}","line":{"from":32,"to":35}} {"id":100003305,"name":"Convert_config_CSRSigningControllerConfiguration_To_v1alpha1_CSRSigningControllerConfiguration","signature":"func Convert_config_CSRSigningControllerConfiguration_To_v1alpha1_CSRSigningControllerConfiguration(in *csrsigningconfig.CSRSigningControllerConfiguration, out *v1alpha1.CSRSigningControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/certificates/signer/config/v1alpha1/conversion.go","code":"// Convert_config_CSRSigningControllerConfiguration_To_v1alpha1_CSRSigningControllerConfiguration is an autogenerated conversion function.\nfunc Convert_config_CSRSigningControllerConfiguration_To_v1alpha1_CSRSigningControllerConfiguration(in *csrsigningconfig.CSRSigningControllerConfiguration, out *v1alpha1.CSRSigningControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_CSRSigningControllerConfiguration_To_v1alpha1_CSRSigningControllerConfiguration(in, out, s)\n}","line":{"from":37,"to":40}} {"id":100003306,"name":"RecommendedDefaultCSRSigningControllerConfiguration","signature":"func RecommendedDefaultCSRSigningControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.CSRSigningControllerConfiguration)","file":"pkg/controller/certificates/signer/config/v1alpha1/defaults.go","code":"// RecommendedDefaultCSRSigningControllerConfiguration defaults a pointer to a\n// CSRSigningControllerConfiguration struct. This will set the recommended default\n// values, but they may be subject to change between API versions. This function\n// is intentionally not registered in the scheme as a \"normal\" `SetDefaults_Foo`\n// function to allow consumers of this type to set whatever defaults for their\n// embedded configs. Forcing consumers to use these defaults would be problematic\n// as defaulting in the scheme is done as part of the conversion, and there would\n// be no easy way to opt-out. Instead, if you want to use this defaulting method\n// run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDefaultCSRSigningControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.CSRSigningControllerConfiguration) {\n\tzero := metav1.Duration{}\n\tif obj.ClusterSigningDuration == zero {\n\t\tobj.ClusterSigningDuration = metav1.Duration{Duration: 365 * 24 * time.Hour}\n\t}\n}","line":{"from":26,"to":40}} {"id":100003307,"name":"NewKubeletServingCSRSigningController","signature":"func NewKubeletServingCSRSigningController(","file":"pkg/controller/certificates/signer/signer.go","code":"func NewKubeletServingCSRSigningController(\n\tclient clientset.Interface,\n\tcsrInformer certificatesinformers.CertificateSigningRequestInformer,\n\tcaFile, caKeyFile string,\n\tcertTTL time.Duration,\n) (*CSRSigningController, error) {\n\treturn NewCSRSigningController(\"csrsigning-kubelet-serving\", capi.KubeletServingSignerName, client, csrInformer, caFile, caKeyFile, certTTL)\n}","line":{"from":46,"to":53}} {"id":100003308,"name":"NewKubeletClientCSRSigningController","signature":"func NewKubeletClientCSRSigningController(","file":"pkg/controller/certificates/signer/signer.go","code":"func NewKubeletClientCSRSigningController(\n\tclient clientset.Interface,\n\tcsrInformer certificatesinformers.CertificateSigningRequestInformer,\n\tcaFile, caKeyFile string,\n\tcertTTL time.Duration,\n) (*CSRSigningController, error) {\n\treturn NewCSRSigningController(\"csrsigning-kubelet-client\", capi.KubeAPIServerClientKubeletSignerName, client, csrInformer, caFile, caKeyFile, certTTL)\n}","line":{"from":55,"to":62}} {"id":100003309,"name":"NewKubeAPIServerClientCSRSigningController","signature":"func NewKubeAPIServerClientCSRSigningController(","file":"pkg/controller/certificates/signer/signer.go","code":"func NewKubeAPIServerClientCSRSigningController(\n\tclient clientset.Interface,\n\tcsrInformer certificatesinformers.CertificateSigningRequestInformer,\n\tcaFile, caKeyFile string,\n\tcertTTL time.Duration,\n) (*CSRSigningController, error) {\n\treturn NewCSRSigningController(\"csrsigning-kube-apiserver-client\", capi.KubeAPIServerClientSignerName, client, csrInformer, caFile, caKeyFile, certTTL)\n}","line":{"from":64,"to":71}} {"id":100003310,"name":"NewLegacyUnknownCSRSigningController","signature":"func NewLegacyUnknownCSRSigningController(","file":"pkg/controller/certificates/signer/signer.go","code":"func NewLegacyUnknownCSRSigningController(\n\tclient clientset.Interface,\n\tcsrInformer certificatesinformers.CertificateSigningRequestInformer,\n\tcaFile, caKeyFile string,\n\tcertTTL time.Duration,\n) (*CSRSigningController, error) {\n\treturn NewCSRSigningController(\"csrsigning-legacy-unknown\", capiv1beta1.LegacyUnknownSignerName, client, csrInformer, caFile, caKeyFile, certTTL)\n}","line":{"from":73,"to":80}} {"id":100003311,"name":"NewCSRSigningController","signature":"func NewCSRSigningController(","file":"pkg/controller/certificates/signer/signer.go","code":"func NewCSRSigningController(\n\tcontrollerName string,\n\tsignerName string,\n\tclient clientset.Interface,\n\tcsrInformer certificatesinformers.CertificateSigningRequestInformer,\n\tcaFile, caKeyFile string,\n\tcertTTL time.Duration,\n) (*CSRSigningController, error) {\n\tsigner, err := newSigner(signerName, caFile, caKeyFile, client, certTTL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026CSRSigningController{\n\t\tcertificateController: certificates.NewCertificateController(\n\t\t\tcontrollerName,\n\t\t\tclient,\n\t\t\tcsrInformer,\n\t\t\tsigner.handle,\n\t\t),\n\t\tdynamicCertReloader: signer.caProvider.caLoader,\n\t}, nil\n}","line":{"from":82,"to":104}} {"id":100003312,"name":"Run","signature":"func (c *CSRSigningController) Run(ctx context.Context, workers int)","file":"pkg/controller/certificates/signer/signer.go","code":"// Run the main goroutine responsible for watching and syncing jobs.\nfunc (c *CSRSigningController) Run(ctx context.Context, workers int) {\n\tgo c.dynamicCertReloader.Run(ctx, workers)\n\n\tc.certificateController.Run(ctx, workers)\n}","line":{"from":106,"to":111}} {"id":100003313,"name":"newSigner","signature":"func newSigner(signerName, caFile, caKeyFile string, client clientset.Interface, certificateDuration time.Duration) (*signer, error)","file":"pkg/controller/certificates/signer/signer.go","code":"func newSigner(signerName, caFile, caKeyFile string, client clientset.Interface, certificateDuration time.Duration) (*signer, error) {\n\tisRequestForSignerFn, err := getCSRVerificationFuncForSignerName(signerName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcaProvider, err := newCAProvider(caFile, caKeyFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret := \u0026signer{\n\t\tcaProvider: caProvider,\n\t\tclient: client,\n\t\tcertTTL: certificateDuration,\n\t\tsignerName: signerName,\n\t\tisRequestForSignerFn: isRequestForSignerFn,\n\t}\n\treturn ret, nil\n}","line":{"from":125,"to":143}} {"id":100003314,"name":"handle","signature":"func (s *signer) handle(ctx context.Context, csr *capi.CertificateSigningRequest) error","file":"pkg/controller/certificates/signer/signer.go","code":"func (s *signer) handle(ctx context.Context, csr *capi.CertificateSigningRequest) error {\n\t// Ignore unapproved or failed requests\n\tif !certificates.IsCertificateRequestApproved(csr) || certificates.HasTrueCondition(csr, capi.CertificateFailed) {\n\t\treturn nil\n\t}\n\n\t// Fast-path to avoid any additional processing if the CSRs signerName does not match\n\tif csr.Spec.SignerName != s.signerName {\n\t\treturn nil\n\t}\n\n\tx509cr, err := capihelper.ParseCSR(csr.Spec.Request)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to parse csr %q: %v\", csr.Name, err)\n\t}\n\tif recognized, err := s.isRequestForSignerFn(x509cr, csr.Spec.Usages, csr.Spec.SignerName); err != nil {\n\t\tcsr.Status.Conditions = append(csr.Status.Conditions, capi.CertificateSigningRequestCondition{\n\t\t\tType: capi.CertificateFailed,\n\t\t\tStatus: v1.ConditionTrue,\n\t\t\tReason: \"SignerValidationFailure\",\n\t\t\tMessage: err.Error(),\n\t\t\tLastUpdateTime: metav1.Now(),\n\t\t})\n\t\t_, err = s.client.CertificatesV1().CertificateSigningRequests().UpdateStatus(ctx, csr, metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error adding failure condition for csr: %v\", err)\n\t\t}\n\t\treturn nil\n\t} else if !recognized {\n\t\t// Ignore requests for kubernetes.io signerNames we don't recognize\n\t\treturn nil\n\t}\n\tcert, err := s.sign(x509cr, csr.Spec.Usages, csr.Spec.ExpirationSeconds, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error auto signing csr: %v\", err)\n\t}\n\tcsr.Status.Certificate = cert\n\t_, err = s.client.CertificatesV1().CertificateSigningRequests().UpdateStatus(ctx, csr, metav1.UpdateOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error updating signature for csr: %v\", err)\n\t}\n\treturn nil\n}","line":{"from":145,"to":187}} {"id":100003315,"name":"sign","signature":"func (s *signer) sign(x509cr *x509.CertificateRequest, usages []capi.KeyUsage, expirationSeconds *int32, now func() time.Time) ([]byte, error)","file":"pkg/controller/certificates/signer/signer.go","code":"func (s *signer) sign(x509cr *x509.CertificateRequest, usages []capi.KeyUsage, expirationSeconds *int32, now func() time.Time) ([]byte, error) {\n\tcurrCA, err := s.caProvider.currentCA()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tder, err := currCA.Sign(x509cr.Raw, authority.PermissiveSigningPolicy{\n\t\tTTL: s.duration(expirationSeconds),\n\t\tUsages: usages,\n\t\tBackdate: 5 * time.Minute, // this must always be less than the minimum TTL requested by a user (see sanity check requestedDuration below)\n\t\tShort: 8 * time.Hour, // 5 minutes of backdating is roughly 1% of 8 hours\n\t\tNow: now,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn pem.EncodeToMemory(\u0026pem.Block{Type: \"CERTIFICATE\", Bytes: der}), nil\n}","line":{"from":189,"to":205}} {"id":100003316,"name":"duration","signature":"func (s *signer) duration(expirationSeconds *int32) time.Duration","file":"pkg/controller/certificates/signer/signer.go","code":"func (s *signer) duration(expirationSeconds *int32) time.Duration {\n\tif expirationSeconds == nil {\n\t\treturn s.certTTL\n\t}\n\n\t// honor requested duration is if it is less than the default TTL\n\t// use 10 min (2x hard coded backdate above) as a sanity check lower bound\n\tconst min = 10 * time.Minute\n\tswitch requestedDuration := csr.ExpirationSecondsToDuration(*expirationSeconds); {\n\tcase requestedDuration \u003e s.certTTL:\n\t\treturn s.certTTL\n\n\tcase requestedDuration \u003c min:\n\t\treturn min\n\n\tdefault:\n\t\treturn requestedDuration\n\t}\n}","line":{"from":207,"to":225}} {"id":100003317,"name":"getCSRVerificationFuncForSignerName","signature":"func getCSRVerificationFuncForSignerName(signerName string) (isRequestForSignerFunc, error)","file":"pkg/controller/certificates/signer/signer.go","code":"// getCSRVerificationFuncForSignerName is a function that provides reliable mapping of signer names to verification so that\n// we don't have accidents with wiring at some later date.\nfunc getCSRVerificationFuncForSignerName(signerName string) (isRequestForSignerFunc, error) {\n\tswitch signerName {\n\tcase capi.KubeletServingSignerName:\n\t\treturn isKubeletServing, nil\n\tcase capi.KubeAPIServerClientKubeletSignerName:\n\t\treturn isKubeletClient, nil\n\tcase capi.KubeAPIServerClientSignerName:\n\t\treturn isKubeAPIServerClient, nil\n\tcase capiv1beta1.LegacyUnknownSignerName:\n\t\treturn isLegacyUnknown, nil\n\tdefault:\n\t\t// TODO type this error so that a different reporting loop (one without a signing cert), can mark\n\t\t// CSRs with unknown kube signers as terminal if we wish. This largely depends on how tightly we want to control\n\t\t// our signerNames.\n\t\treturn nil, fmt.Errorf(\"unrecognized signerName: %q\", signerName)\n\t}\n}","line":{"from":227,"to":245}} {"id":100003318,"name":"isKubeletServing","signature":"func isKubeletServing(req *x509.CertificateRequest, usages []capi.KeyUsage, signerName string) (bool, error)","file":"pkg/controller/certificates/signer/signer.go","code":"func isKubeletServing(req *x509.CertificateRequest, usages []capi.KeyUsage, signerName string) (bool, error) {\n\tif signerName != capi.KubeletServingSignerName {\n\t\treturn false, nil\n\t}\n\treturn true, capihelper.ValidateKubeletServingCSR(req, usagesToSet(usages))\n}","line":{"from":247,"to":252}} {"id":100003319,"name":"isKubeletClient","signature":"func isKubeletClient(req *x509.CertificateRequest, usages []capi.KeyUsage, signerName string) (bool, error)","file":"pkg/controller/certificates/signer/signer.go","code":"func isKubeletClient(req *x509.CertificateRequest, usages []capi.KeyUsage, signerName string) (bool, error) {\n\tif signerName != capi.KubeAPIServerClientKubeletSignerName {\n\t\treturn false, nil\n\t}\n\treturn true, capihelper.ValidateKubeletClientCSR(req, usagesToSet(usages))\n}","line":{"from":254,"to":259}} {"id":100003320,"name":"isKubeAPIServerClient","signature":"func isKubeAPIServerClient(req *x509.CertificateRequest, usages []capi.KeyUsage, signerName string) (bool, error)","file":"pkg/controller/certificates/signer/signer.go","code":"func isKubeAPIServerClient(req *x509.CertificateRequest, usages []capi.KeyUsage, signerName string) (bool, error) {\n\tif signerName != capi.KubeAPIServerClientSignerName {\n\t\treturn false, nil\n\t}\n\treturn true, validAPIServerClientUsages(usages)\n}","line":{"from":261,"to":266}} {"id":100003321,"name":"isLegacyUnknown","signature":"func isLegacyUnknown(req *x509.CertificateRequest, usages []capi.KeyUsage, signerName string) (bool, error)","file":"pkg/controller/certificates/signer/signer.go","code":"func isLegacyUnknown(req *x509.CertificateRequest, usages []capi.KeyUsage, signerName string) (bool, error) {\n\tif signerName != capiv1beta1.LegacyUnknownSignerName {\n\t\treturn false, nil\n\t}\n\t// No restrictions are applied to the legacy-unknown signerName to\n\t// maintain backward compatibility in v1.\n\treturn true, nil\n}","line":{"from":268,"to":275}} {"id":100003322,"name":"validAPIServerClientUsages","signature":"func validAPIServerClientUsages(usages []capi.KeyUsage) error","file":"pkg/controller/certificates/signer/signer.go","code":"func validAPIServerClientUsages(usages []capi.KeyUsage) error {\n\thasClientAuth := false\n\tfor _, u := range usages {\n\t\tswitch u {\n\t\t// these usages are optional\n\t\tcase capi.UsageDigitalSignature, capi.UsageKeyEncipherment:\n\t\tcase capi.UsageClientAuth:\n\t\t\thasClientAuth = true\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"invalid usage for client certificate: %s\", u)\n\t\t}\n\t}\n\tif !hasClientAuth {\n\t\treturn fmt.Errorf(\"missing required usage for client certificate: %s\", capi.UsageClientAuth)\n\t}\n\treturn nil\n}","line":{"from":277,"to":293}} {"id":100003323,"name":"usagesToSet","signature":"func usagesToSet(usages []capi.KeyUsage) sets.String","file":"pkg/controller/certificates/signer/signer.go","code":"func usagesToSet(usages []capi.KeyUsage) sets.String {\n\tresult := sets.NewString()\n\tfor _, usage := range usages {\n\t\tresult.Insert(string(usage))\n\t}\n\treturn result\n}","line":{"from":295,"to":301}} {"id":100003324,"name":"NewClusterRoleAggregation","signature":"func NewClusterRoleAggregation(clusterRoleInformer rbacinformers.ClusterRoleInformer, clusterRoleClient rbacclient.ClusterRolesGetter) *ClusterRoleAggregationController","file":"pkg/controller/clusterroleaggregation/clusterroleaggregation_controller.go","code":"// NewClusterRoleAggregation creates a new controller\nfunc NewClusterRoleAggregation(clusterRoleInformer rbacinformers.ClusterRoleInformer, clusterRoleClient rbacclient.ClusterRolesGetter) *ClusterRoleAggregationController {\n\tc := \u0026ClusterRoleAggregationController{\n\t\tclusterRoleClient: clusterRoleClient,\n\t\tclusterRoleLister: clusterRoleInformer.Lister(),\n\t\tclusterRolesSynced: clusterRoleInformer.Informer().HasSynced,\n\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"ClusterRoleAggregator\"),\n\t}\n\tc.syncHandler = c.syncClusterRole\n\n\tclusterRoleInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tc.enqueue()\n\t\t},\n\t\tUpdateFunc: func(old, cur interface{}) {\n\t\t\tc.enqueue()\n\t\t},\n\t\tDeleteFunc: func(uncast interface{}) {\n\t\t\tc.enqueue()\n\t\t},\n\t})\n\treturn c\n}","line":{"from":54,"to":77}} {"id":100003325,"name":"syncClusterRole","signature":"func (c *ClusterRoleAggregationController) syncClusterRole(ctx context.Context, key string) error","file":"pkg/controller/clusterroleaggregation/clusterroleaggregation_controller.go","code":"func (c *ClusterRoleAggregationController) syncClusterRole(ctx context.Context, key string) error {\n\t_, name, err := cache.SplitMetaNamespaceKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsharedClusterRole, err := c.clusterRoleLister.Get(name)\n\tif errors.IsNotFound(err) {\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tif sharedClusterRole.AggregationRule == nil {\n\t\treturn nil\n\t}\n\n\tnewPolicyRules := []rbacv1.PolicyRule{}\n\tfor i := range sharedClusterRole.AggregationRule.ClusterRoleSelectors {\n\t\tselector := sharedClusterRole.AggregationRule.ClusterRoleSelectors[i]\n\t\truntimeLabelSelector, err := metav1.LabelSelectorAsSelector(\u0026selector)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tclusterRoles, err := c.clusterRoleLister.List(runtimeLabelSelector)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsort.Sort(byName(clusterRoles))\n\n\t\tfor i := range clusterRoles {\n\t\t\tif clusterRoles[i].Name == sharedClusterRole.Name {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor j := range clusterRoles[i].Rules {\n\t\t\t\tcurrRule := clusterRoles[i].Rules[j]\n\t\t\t\tif !ruleExists(newPolicyRules, currRule) {\n\t\t\t\t\tnewPolicyRules = append(newPolicyRules, currRule)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif equality.Semantic.DeepEqual(newPolicyRules, sharedClusterRole.Rules) {\n\t\treturn nil\n\t}\n\n\terr = c.applyClusterRoles(ctx, sharedClusterRole.Name, newPolicyRules)\n\tif errors.IsUnsupportedMediaType(err) { // TODO: Remove this fallback at least one release after ServerSideApply GA\n\t\t// When Server Side Apply is not enabled, fallback to Update. This is required when running\n\t\t// 1.21 since api-server can be 1.20 during the upgrade/downgrade.\n\t\t// Since Server Side Apply is enabled by default in Beta, this fallback only kicks in\n\t\t// if the feature has been disabled using its feature flag.\n\t\terr = c.updateClusterRoles(ctx, sharedClusterRole, newPolicyRules)\n\t}\n\treturn err\n}","line":{"from":79,"to":135}} {"id":100003326,"name":"applyClusterRoles","signature":"func (c *ClusterRoleAggregationController) applyClusterRoles(ctx context.Context, name string, newPolicyRules []rbacv1.PolicyRule) error","file":"pkg/controller/clusterroleaggregation/clusterroleaggregation_controller.go","code":"func (c *ClusterRoleAggregationController) applyClusterRoles(ctx context.Context, name string, newPolicyRules []rbacv1.PolicyRule) error {\n\tclusterRoleApply := rbacv1ac.ClusterRole(name).\n\t\tWithRules(toApplyPolicyRules(newPolicyRules)...)\n\n\topts := metav1.ApplyOptions{FieldManager: \"clusterrole-aggregation-controller\", Force: true}\n\t_, err := c.clusterRoleClient.ClusterRoles().Apply(ctx, clusterRoleApply, opts)\n\treturn err\n}","line":{"from":137,"to":144}} {"id":100003327,"name":"updateClusterRoles","signature":"func (c *ClusterRoleAggregationController) updateClusterRoles(ctx context.Context, sharedClusterRole *rbacv1.ClusterRole, newPolicyRules []rbacv1.PolicyRule) error","file":"pkg/controller/clusterroleaggregation/clusterroleaggregation_controller.go","code":"func (c *ClusterRoleAggregationController) updateClusterRoles(ctx context.Context, sharedClusterRole *rbacv1.ClusterRole, newPolicyRules []rbacv1.PolicyRule) error {\n\tclusterRole := sharedClusterRole.DeepCopy()\n\tclusterRole.Rules = nil\n\tfor _, rule := range newPolicyRules {\n\t\tclusterRole.Rules = append(clusterRole.Rules, *rule.DeepCopy())\n\t}\n\t_, err := c.clusterRoleClient.ClusterRoles().Update(ctx, clusterRole, metav1.UpdateOptions{})\n\treturn err\n}","line":{"from":146,"to":154}} {"id":100003328,"name":"toApplyPolicyRules","signature":"func toApplyPolicyRules(rules []rbacv1.PolicyRule) []*rbacv1ac.PolicyRuleApplyConfiguration","file":"pkg/controller/clusterroleaggregation/clusterroleaggregation_controller.go","code":"func toApplyPolicyRules(rules []rbacv1.PolicyRule) []*rbacv1ac.PolicyRuleApplyConfiguration {\n\tvar result []*rbacv1ac.PolicyRuleApplyConfiguration\n\tfor _, rule := range rules {\n\t\tresult = append(result, toApplyPolicyRule(rule))\n\t}\n\treturn result\n}","line":{"from":156,"to":162}} {"id":100003329,"name":"toApplyPolicyRule","signature":"func toApplyPolicyRule(rule rbacv1.PolicyRule) *rbacv1ac.PolicyRuleApplyConfiguration","file":"pkg/controller/clusterroleaggregation/clusterroleaggregation_controller.go","code":"func toApplyPolicyRule(rule rbacv1.PolicyRule) *rbacv1ac.PolicyRuleApplyConfiguration {\n\tresult := rbacv1ac.PolicyRule()\n\tresult.Resources = rule.Resources\n\tresult.ResourceNames = rule.ResourceNames\n\tresult.APIGroups = rule.APIGroups\n\tresult.NonResourceURLs = rule.NonResourceURLs\n\tresult.Verbs = rule.Verbs\n\treturn result\n}","line":{"from":164,"to":172}} {"id":100003330,"name":"ruleExists","signature":"func ruleExists(haystack []rbacv1.PolicyRule, needle rbacv1.PolicyRule) bool","file":"pkg/controller/clusterroleaggregation/clusterroleaggregation_controller.go","code":"func ruleExists(haystack []rbacv1.PolicyRule, needle rbacv1.PolicyRule) bool {\n\tfor _, curr := range haystack {\n\t\tif equality.Semantic.DeepEqual(curr, needle) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":174,"to":181}} {"id":100003331,"name":"Run","signature":"func (c *ClusterRoleAggregationController) Run(ctx context.Context, workers int)","file":"pkg/controller/clusterroleaggregation/clusterroleaggregation_controller.go","code":"// Run starts the controller and blocks until stopCh is closed.\nfunc (c *ClusterRoleAggregationController) Run(ctx context.Context, workers int) {\n\tdefer utilruntime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\n\tlogger := klog.FromContext(ctx)\n\tlogger.Info(\"Starting ClusterRoleAggregator controller\")\n\tdefer logger.Info(\"Shutting down ClusterRoleAggregator controller\")\n\n\tif !cache.WaitForNamedCacheSync(\"ClusterRoleAggregator\", ctx.Done(), c.clusterRolesSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.UntilWithContext(ctx, c.runWorker, time.Second)\n\t}\n\n\t\u003c-ctx.Done()\n}","line":{"from":183,"to":201}} {"id":100003332,"name":"runWorker","signature":"func (c *ClusterRoleAggregationController) runWorker(ctx context.Context)","file":"pkg/controller/clusterroleaggregation/clusterroleaggregation_controller.go","code":"func (c *ClusterRoleAggregationController) runWorker(ctx context.Context) {\n\tfor c.processNextWorkItem(ctx) {\n\t}\n}","line":{"from":203,"to":206}} {"id":100003333,"name":"processNextWorkItem","signature":"func (c *ClusterRoleAggregationController) processNextWorkItem(ctx context.Context) bool","file":"pkg/controller/clusterroleaggregation/clusterroleaggregation_controller.go","code":"func (c *ClusterRoleAggregationController) processNextWorkItem(ctx context.Context) bool {\n\tdsKey, quit := c.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.queue.Done(dsKey)\n\n\terr := c.syncHandler(ctx, dsKey.(string))\n\tif err == nil {\n\t\tc.queue.Forget(dsKey)\n\t\treturn true\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"%v failed with : %v\", dsKey, err))\n\tc.queue.AddRateLimited(dsKey)\n\n\treturn true\n}","line":{"from":208,"to":225}} {"id":100003334,"name":"enqueue","signature":"func (c *ClusterRoleAggregationController) enqueue()","file":"pkg/controller/clusterroleaggregation/clusterroleaggregation_controller.go","code":"func (c *ClusterRoleAggregationController) enqueue() {\n\t// this is unusual, but since the set of all clusterroles is small and we don't know the dependency\n\t// graph, just queue up every thing each time. This allows errors to be selectively retried if there\n\t// is a problem updating a single role\n\tallClusterRoles, err := c.clusterRoleLister.List(labels.Everything())\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Couldn't list all objects %v\", err))\n\t\treturn\n\t}\n\tfor _, clusterRole := range allClusterRoles {\n\t\t// only queue ones that we may need to aggregate\n\t\tif clusterRole.AggregationRule == nil {\n\t\t\tcontinue\n\t\t}\n\t\tkey, err := controller.KeyFunc(clusterRole)\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"Couldn't get key for object %#v: %v\", clusterRole, err))\n\t\t\treturn\n\t\t}\n\t\tc.queue.Add(key)\n\t}\n}","line":{"from":227,"to":248}} {"id":100003335,"name":"Len","signature":"func (a byName) Len() int { return len(a) }","file":"pkg/controller/clusterroleaggregation/clusterroleaggregation_controller.go","code":"func (a byName) Len() int { return len(a) }","line":{"from":252,"to":252}} {"id":100003336,"name":"Swap","signature":"func (a byName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }","file":"pkg/controller/clusterroleaggregation/clusterroleaggregation_controller.go","code":"func (a byName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }","line":{"from":253,"to":253}} {"id":100003337,"name":"Less","signature":"func (a byName) Less(i, j int) bool { return a[i].Name \u003c a[j].Name }","file":"pkg/controller/clusterroleaggregation/clusterroleaggregation_controller.go","code":"func (a byName) Less(i, j int) bool { return a[i].Name \u003c a[j].Name }","line":{"from":254,"to":254}} {"id":100003338,"name":"CanAdopt","signature":"func (m *BaseControllerRefManager) CanAdopt(ctx context.Context) error","file":"pkg/controller/controller_ref_manager.go","code":"func (m *BaseControllerRefManager) CanAdopt(ctx context.Context) error {\n\tm.canAdoptOnce.Do(func() {\n\t\tif m.CanAdoptFunc != nil {\n\t\t\tm.canAdoptErr = m.CanAdoptFunc(ctx)\n\t\t}\n\t})\n\treturn m.canAdoptErr\n}","line":{"from":45,"to":52}} {"id":100003339,"name":"ClaimObject","signature":"func (m *BaseControllerRefManager) ClaimObject(ctx context.Context, obj metav1.Object, match func(metav1.Object) bool, adopt, release func(context.Context, metav1.Object) error) (bool, error)","file":"pkg/controller/controller_ref_manager.go","code":"// ClaimObject tries to take ownership of an object for this controller.\n//\n// It will reconcile the following:\n// - Adopt orphans if the match function returns true.\n// - Release owned objects if the match function returns false.\n//\n// A non-nil error is returned if some form of reconciliation was attempted and\n// failed. Usually, controllers should try again later in case reconciliation\n// is still needed.\n//\n// If the error is nil, either the reconciliation succeeded, or no\n// reconciliation was necessary. The returned boolean indicates whether you now\n// own the object.\n//\n// No reconciliation will be attempted if the controller is being deleted.\nfunc (m *BaseControllerRefManager) ClaimObject(ctx context.Context, obj metav1.Object, match func(metav1.Object) bool, adopt, release func(context.Context, metav1.Object) error) (bool, error) {\n\tcontrollerRef := metav1.GetControllerOfNoCopy(obj)\n\tif controllerRef != nil {\n\t\tif controllerRef.UID != m.Controller.GetUID() {\n\t\t\t// Owned by someone else. Ignore.\n\t\t\treturn false, nil\n\t\t}\n\t\tif match(obj) {\n\t\t\t// We already own it and the selector matches.\n\t\t\t// Return true (successfully claimed) before checking deletion timestamp.\n\t\t\t// We're still allowed to claim things we already own while being deleted\n\t\t\t// because doing so requires taking no actions.\n\t\t\treturn true, nil\n\t\t}\n\t\t// Owned by us but selector doesn't match.\n\t\t// Try to release, unless we're being deleted.\n\t\tif m.Controller.GetDeletionTimestamp() != nil {\n\t\t\treturn false, nil\n\t\t}\n\t\tif err := release(ctx, obj); err != nil {\n\t\t\t// If the pod no longer exists, ignore the error.\n\t\t\tif errors.IsNotFound(err) {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\t// Either someone else released it, or there was a transient error.\n\t\t\t// The controller should requeue and try again if it's still stale.\n\t\t\treturn false, err\n\t\t}\n\t\t// Successfully released.\n\t\treturn false, nil\n\t}\n\n\t// It's an orphan.\n\tif m.Controller.GetDeletionTimestamp() != nil || !match(obj) {\n\t\t// Ignore if we're being deleted or selector doesn't match.\n\t\treturn false, nil\n\t}\n\tif obj.GetDeletionTimestamp() != nil {\n\t\t// Ignore if the object is being deleted\n\t\treturn false, nil\n\t}\n\n\tif len(m.Controller.GetNamespace()) \u003e 0 \u0026\u0026 m.Controller.GetNamespace() != obj.GetNamespace() {\n\t\t// Ignore if namespace not match\n\t\treturn false, nil\n\t}\n\n\t// Selector matches. Try to adopt.\n\tif err := adopt(ctx, obj); err != nil {\n\t\t// If the pod no longer exists, ignore the error.\n\t\tif errors.IsNotFound(err) {\n\t\t\treturn false, nil\n\t\t}\n\t\t// Either someone else claimed it first, or there was a transient error.\n\t\t// The controller should requeue and try again if it's still orphaned.\n\t\treturn false, err\n\t}\n\t// Successfully adopted.\n\treturn true, nil\n}","line":{"from":54,"to":128}} {"id":100003340,"name":"NewPodControllerRefManager","signature":"func NewPodControllerRefManager(","file":"pkg/controller/controller_ref_manager.go","code":"// NewPodControllerRefManager returns a PodControllerRefManager that exposes\n// methods to manage the controllerRef of pods.\n//\n// The CanAdopt() function can be used to perform a potentially expensive check\n// (such as a live GET from the API server) prior to the first adoption.\n// It will only be called (at most once) if an adoption is actually attempted.\n// If CanAdopt() returns a non-nil error, all adoptions will fail.\n//\n// NOTE: Once CanAdopt() is called, it will not be called again by the same\n// PodControllerRefManager instance. Create a new instance if it makes\n// sense to check CanAdopt() again (e.g. in a different sync pass).\nfunc NewPodControllerRefManager(\n\tpodControl PodControlInterface,\n\tcontroller metav1.Object,\n\tselector labels.Selector,\n\tcontrollerKind schema.GroupVersionKind,\n\tcanAdopt func(ctx context.Context) error,\n\tfinalizers ...string,\n) *PodControllerRefManager {\n\treturn \u0026PodControllerRefManager{\n\t\tBaseControllerRefManager: BaseControllerRefManager{\n\t\t\tController: controller,\n\t\t\tSelector: selector,\n\t\t\tCanAdoptFunc: canAdopt,\n\t\t},\n\t\tcontrollerKind: controllerKind,\n\t\tpodControl: podControl,\n\t\tfinalizers: finalizers,\n\t}\n}","line":{"from":137,"to":166}} {"id":100003341,"name":"ClaimPods","signature":"func (m *PodControllerRefManager) ClaimPods(ctx context.Context, pods []*v1.Pod, filters ...func(*v1.Pod) bool) ([]*v1.Pod, error)","file":"pkg/controller/controller_ref_manager.go","code":"// ClaimPods tries to take ownership of a list of Pods.\n//\n// It will reconcile the following:\n// - Adopt orphans if the selector matches.\n// - Release owned objects if the selector no longer matches.\n//\n// Optional: If one or more filters are specified, a Pod will only be claimed if\n// all filters return true.\n//\n// A non-nil error is returned if some form of reconciliation was attempted and\n// failed. Usually, controllers should try again later in case reconciliation\n// is still needed.\n//\n// If the error is nil, either the reconciliation succeeded, or no\n// reconciliation was necessary. The list of Pods that you now own is returned.\nfunc (m *PodControllerRefManager) ClaimPods(ctx context.Context, pods []*v1.Pod, filters ...func(*v1.Pod) bool) ([]*v1.Pod, error) {\n\tvar claimed []*v1.Pod\n\tvar errlist []error\n\n\tmatch := func(obj metav1.Object) bool {\n\t\tpod := obj.(*v1.Pod)\n\t\t// Check selector first so filters only run on potentially matching Pods.\n\t\tif !m.Selector.Matches(labels.Set(pod.Labels)) {\n\t\t\treturn false\n\t\t}\n\t\tfor _, filter := range filters {\n\t\t\tif !filter(pod) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\tadopt := func(ctx context.Context, obj metav1.Object) error {\n\t\treturn m.AdoptPod(ctx, obj.(*v1.Pod))\n\t}\n\trelease := func(ctx context.Context, obj metav1.Object) error {\n\t\treturn m.ReleasePod(ctx, obj.(*v1.Pod))\n\t}\n\n\tfor _, pod := range pods {\n\t\tok, err := m.ClaimObject(ctx, pod, match, adopt, release)\n\t\tif err != nil {\n\t\t\terrlist = append(errlist, err)\n\t\t\tcontinue\n\t\t}\n\t\tif ok {\n\t\t\tclaimed = append(claimed, pod)\n\t\t}\n\t}\n\treturn claimed, utilerrors.NewAggregate(errlist)\n}","line":{"from":168,"to":218}} {"id":100003342,"name":"AdoptPod","signature":"func (m *PodControllerRefManager) AdoptPod(ctx context.Context, pod *v1.Pod) error","file":"pkg/controller/controller_ref_manager.go","code":"// AdoptPod sends a patch to take control of the pod. It returns the error if\n// the patching fails.\nfunc (m *PodControllerRefManager) AdoptPod(ctx context.Context, pod *v1.Pod) error {\n\tif err := m.CanAdopt(ctx); err != nil {\n\t\treturn fmt.Errorf(\"can't adopt Pod %v/%v (%v): %v\", pod.Namespace, pod.Name, pod.UID, err)\n\t}\n\t// Note that ValidateOwnerReferences() will reject this patch if another\n\t// OwnerReference exists with controller=true.\n\n\tpatchBytes, err := ownerRefControllerPatch(m.Controller, m.controllerKind, pod.UID, m.finalizers...)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn m.podControl.PatchPod(ctx, pod.Namespace, pod.Name, patchBytes)\n}","line":{"from":220,"to":234}} {"id":100003343,"name":"ReleasePod","signature":"func (m *PodControllerRefManager) ReleasePod(ctx context.Context, pod *v1.Pod) error","file":"pkg/controller/controller_ref_manager.go","code":"// ReleasePod sends a patch to free the pod from the control of the controller.\n// It returns the error if the patching fails. 404 and 422 errors are ignored.\nfunc (m *PodControllerRefManager) ReleasePod(ctx context.Context, pod *v1.Pod) error {\n\tklog.V(2).Infof(\"patching pod %s_%s to remove its controllerRef to %s/%s:%s\",\n\t\tpod.Namespace, pod.Name, m.controllerKind.GroupVersion(), m.controllerKind.Kind, m.Controller.GetName())\n\tpatchBytes, err := GenerateDeleteOwnerRefStrategicMergeBytes(pod.UID, []types.UID{m.Controller.GetUID()}, m.finalizers...)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = m.podControl.PatchPod(ctx, pod.Namespace, pod.Name, patchBytes)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t// If the pod no longer exists, ignore it.\n\t\t\treturn nil\n\t\t}\n\t\tif errors.IsInvalid(err) {\n\t\t\t// Invalid error will be returned in two cases: 1. the pod\n\t\t\t// has no owner reference, 2. the uid of the pod doesn't\n\t\t\t// match, which means the pod is deleted and then recreated.\n\t\t\t// In both cases, the error can be ignored.\n\n\t\t\t// TODO: If the pod has owner references, but none of them\n\t\t\t// has the owner.UID, server will silently ignore the patch.\n\t\t\t// Investigate why.\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn err\n}","line":{"from":236,"to":264}} {"id":100003344,"name":"NewReplicaSetControllerRefManager","signature":"func NewReplicaSetControllerRefManager(","file":"pkg/controller/controller_ref_manager.go","code":"// NewReplicaSetControllerRefManager returns a ReplicaSetControllerRefManager that exposes\n// methods to manage the controllerRef of ReplicaSets.\n//\n// The CanAdopt() function can be used to perform a potentially expensive check\n// (such as a live GET from the API server) prior to the first adoption.\n// It will only be called (at most once) if an adoption is actually attempted.\n// If CanAdopt() returns a non-nil error, all adoptions will fail.\n//\n// NOTE: Once CanAdopt() is called, it will not be called again by the same\n// ReplicaSetControllerRefManager instance. Create a new instance if it\n// makes sense to check CanAdopt() again (e.g. in a different sync pass).\nfunc NewReplicaSetControllerRefManager(\n\trsControl RSControlInterface,\n\tcontroller metav1.Object,\n\tselector labels.Selector,\n\tcontrollerKind schema.GroupVersionKind,\n\tcanAdopt func(ctx context.Context) error,\n) *ReplicaSetControllerRefManager {\n\treturn \u0026ReplicaSetControllerRefManager{\n\t\tBaseControllerRefManager: BaseControllerRefManager{\n\t\t\tController: controller,\n\t\t\tSelector: selector,\n\t\t\tCanAdoptFunc: canAdopt,\n\t\t},\n\t\tcontrollerKind: controllerKind,\n\t\trsControl: rsControl,\n\t}\n}","line":{"from":277,"to":304}} {"id":100003345,"name":"ClaimReplicaSets","signature":"func (m *ReplicaSetControllerRefManager) ClaimReplicaSets(ctx context.Context, sets []*apps.ReplicaSet) ([]*apps.ReplicaSet, error)","file":"pkg/controller/controller_ref_manager.go","code":"// ClaimReplicaSets tries to take ownership of a list of ReplicaSets.\n//\n// It will reconcile the following:\n// - Adopt orphans if the selector matches.\n// - Release owned objects if the selector no longer matches.\n//\n// A non-nil error is returned if some form of reconciliation was attempted and\n// failed. Usually, controllers should try again later in case reconciliation\n// is still needed.\n//\n// If the error is nil, either the reconciliation succeeded, or no\n// reconciliation was necessary. The list of ReplicaSets that you now own is\n// returned.\nfunc (m *ReplicaSetControllerRefManager) ClaimReplicaSets(ctx context.Context, sets []*apps.ReplicaSet) ([]*apps.ReplicaSet, error) {\n\tvar claimed []*apps.ReplicaSet\n\tvar errlist []error\n\n\tmatch := func(obj metav1.Object) bool {\n\t\treturn m.Selector.Matches(labels.Set(obj.GetLabels()))\n\t}\n\tadopt := func(ctx context.Context, obj metav1.Object) error {\n\t\treturn m.AdoptReplicaSet(ctx, obj.(*apps.ReplicaSet))\n\t}\n\trelease := func(ctx context.Context, obj metav1.Object) error {\n\t\treturn m.ReleaseReplicaSet(ctx, obj.(*apps.ReplicaSet))\n\t}\n\n\tfor _, rs := range sets {\n\t\tok, err := m.ClaimObject(ctx, rs, match, adopt, release)\n\t\tif err != nil {\n\t\t\terrlist = append(errlist, err)\n\t\t\tcontinue\n\t\t}\n\t\tif ok {\n\t\t\tclaimed = append(claimed, rs)\n\t\t}\n\t}\n\treturn claimed, utilerrors.NewAggregate(errlist)\n}","line":{"from":306,"to":344}} {"id":100003346,"name":"AdoptReplicaSet","signature":"func (m *ReplicaSetControllerRefManager) AdoptReplicaSet(ctx context.Context, rs *apps.ReplicaSet) error","file":"pkg/controller/controller_ref_manager.go","code":"// AdoptReplicaSet sends a patch to take control of the ReplicaSet. It returns\n// the error if the patching fails.\nfunc (m *ReplicaSetControllerRefManager) AdoptReplicaSet(ctx context.Context, rs *apps.ReplicaSet) error {\n\tif err := m.CanAdopt(ctx); err != nil {\n\t\treturn fmt.Errorf(\"can't adopt ReplicaSet %v/%v (%v): %v\", rs.Namespace, rs.Name, rs.UID, err)\n\t}\n\t// Note that ValidateOwnerReferences() will reject this patch if another\n\t// OwnerReference exists with controller=true.\n\tpatchBytes, err := ownerRefControllerPatch(m.Controller, m.controllerKind, rs.UID)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn m.rsControl.PatchReplicaSet(ctx, rs.Namespace, rs.Name, patchBytes)\n}","line":{"from":346,"to":359}} {"id":100003347,"name":"ReleaseReplicaSet","signature":"func (m *ReplicaSetControllerRefManager) ReleaseReplicaSet(ctx context.Context, replicaSet *apps.ReplicaSet) error","file":"pkg/controller/controller_ref_manager.go","code":"// ReleaseReplicaSet sends a patch to free the ReplicaSet from the control of the Deployment controller.\n// It returns the error if the patching fails. 404 and 422 errors are ignored.\nfunc (m *ReplicaSetControllerRefManager) ReleaseReplicaSet(ctx context.Context, replicaSet *apps.ReplicaSet) error {\n\tklog.V(2).Infof(\"patching ReplicaSet %s_%s to remove its controllerRef to %s/%s:%s\",\n\t\treplicaSet.Namespace, replicaSet.Name, m.controllerKind.GroupVersion(), m.controllerKind.Kind, m.Controller.GetName())\n\tpatchBytes, err := GenerateDeleteOwnerRefStrategicMergeBytes(replicaSet.UID, []types.UID{m.Controller.GetUID()})\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = m.rsControl.PatchReplicaSet(ctx, replicaSet.Namespace, replicaSet.Name, patchBytes)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t// If the ReplicaSet no longer exists, ignore it.\n\t\t\treturn nil\n\t\t}\n\t\tif errors.IsInvalid(err) {\n\t\t\t// Invalid error will be returned in two cases: 1. the ReplicaSet\n\t\t\t// has no owner reference, 2. the uid of the ReplicaSet doesn't\n\t\t\t// match, which means the ReplicaSet is deleted and then recreated.\n\t\t\t// In both cases, the error can be ignored.\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn err\n}","line":{"from":361,"to":385}} {"id":100003348,"name":"RecheckDeletionTimestamp","signature":"func RecheckDeletionTimestamp(getObject func(context.Context) (metav1.Object, error)) func(context.Context) error","file":"pkg/controller/controller_ref_manager.go","code":"// RecheckDeletionTimestamp returns a CanAdopt() function to recheck deletion.\n//\n// The CanAdopt() function calls getObject() to fetch the latest value,\n// and denies adoption attempts if that object has a non-nil DeletionTimestamp.\nfunc RecheckDeletionTimestamp(getObject func(context.Context) (metav1.Object, error)) func(context.Context) error {\n\treturn func(ctx context.Context) error {\n\t\tobj, err := getObject(ctx)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"can't recheck DeletionTimestamp: %v\", err)\n\t\t}\n\t\tif obj.GetDeletionTimestamp() != nil {\n\t\t\treturn fmt.Errorf(\"%v/%v has just been deleted at %v\", obj.GetNamespace(), obj.GetName(), obj.GetDeletionTimestamp())\n\t\t}\n\t\treturn nil\n\t}\n}","line":{"from":387,"to":402}} {"id":100003349,"name":"NewControllerRevisionControllerRefManager","signature":"func NewControllerRevisionControllerRefManager(","file":"pkg/controller/controller_ref_manager.go","code":"// NewControllerRevisionControllerRefManager returns a ControllerRevisionControllerRefManager that exposes\n// methods to manage the controllerRef of ControllerRevisions.\n//\n// The canAdopt() function can be used to perform a potentially expensive check\n// (such as a live GET from the API server) prior to the first adoption.\n// It will only be called (at most once) if an adoption is actually attempted.\n// If canAdopt() returns a non-nil error, all adoptions will fail.\n//\n// NOTE: Once canAdopt() is called, it will not be called again by the same\n// ControllerRevisionControllerRefManager instance. Create a new instance if it\n// makes sense to check canAdopt() again (e.g. in a different sync pass).\nfunc NewControllerRevisionControllerRefManager(\n\tcrControl ControllerRevisionControlInterface,\n\tcontroller metav1.Object,\n\tselector labels.Selector,\n\tcontrollerKind schema.GroupVersionKind,\n\tcanAdopt func(ctx context.Context) error,\n) *ControllerRevisionControllerRefManager {\n\treturn \u0026ControllerRevisionControllerRefManager{\n\t\tBaseControllerRefManager: BaseControllerRefManager{\n\t\t\tController: controller,\n\t\t\tSelector: selector,\n\t\t\tCanAdoptFunc: canAdopt,\n\t\t},\n\t\tcontrollerKind: controllerKind,\n\t\tcrControl: crControl,\n\t}\n}","line":{"from":415,"to":442}} {"id":100003350,"name":"ClaimControllerRevisions","signature":"func (m *ControllerRevisionControllerRefManager) ClaimControllerRevisions(ctx context.Context, histories []*apps.ControllerRevision) ([]*apps.ControllerRevision, error)","file":"pkg/controller/controller_ref_manager.go","code":"// ClaimControllerRevisions tries to take ownership of a list of ControllerRevisions.\n//\n// It will reconcile the following:\n// - Adopt orphans if the selector matches.\n// - Release owned objects if the selector no longer matches.\n//\n// A non-nil error is returned if some form of reconciliation was attempted and\n// failed. Usually, controllers should try again later in case reconciliation\n// is still needed.\n//\n// If the error is nil, either the reconciliation succeeded, or no\n// reconciliation was necessary. The list of ControllerRevisions that you now own is\n// returned.\nfunc (m *ControllerRevisionControllerRefManager) ClaimControllerRevisions(ctx context.Context, histories []*apps.ControllerRevision) ([]*apps.ControllerRevision, error) {\n\tvar claimed []*apps.ControllerRevision\n\tvar errlist []error\n\n\tmatch := func(obj metav1.Object) bool {\n\t\treturn m.Selector.Matches(labels.Set(obj.GetLabels()))\n\t}\n\tadopt := func(ctx context.Context, obj metav1.Object) error {\n\t\treturn m.AdoptControllerRevision(ctx, obj.(*apps.ControllerRevision))\n\t}\n\trelease := func(ctx context.Context, obj metav1.Object) error {\n\t\treturn m.ReleaseControllerRevision(ctx, obj.(*apps.ControllerRevision))\n\t}\n\n\tfor _, h := range histories {\n\t\tok, err := m.ClaimObject(ctx, h, match, adopt, release)\n\t\tif err != nil {\n\t\t\terrlist = append(errlist, err)\n\t\t\tcontinue\n\t\t}\n\t\tif ok {\n\t\t\tclaimed = append(claimed, h)\n\t\t}\n\t}\n\treturn claimed, utilerrors.NewAggregate(errlist)\n}","line":{"from":444,"to":482}} {"id":100003351,"name":"AdoptControllerRevision","signature":"func (m *ControllerRevisionControllerRefManager) AdoptControllerRevision(ctx context.Context, history *apps.ControllerRevision) error","file":"pkg/controller/controller_ref_manager.go","code":"// AdoptControllerRevision sends a patch to take control of the ControllerRevision. It returns the error if\n// the patching fails.\nfunc (m *ControllerRevisionControllerRefManager) AdoptControllerRevision(ctx context.Context, history *apps.ControllerRevision) error {\n\tif err := m.CanAdopt(ctx); err != nil {\n\t\treturn fmt.Errorf(\"can't adopt ControllerRevision %v/%v (%v): %v\", history.Namespace, history.Name, history.UID, err)\n\t}\n\t// Note that ValidateOwnerReferences() will reject this patch if another\n\t// OwnerReference exists with controller=true.\n\tpatchBytes, err := ownerRefControllerPatch(m.Controller, m.controllerKind, history.UID)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn m.crControl.PatchControllerRevision(ctx, history.Namespace, history.Name, patchBytes)\n}","line":{"from":484,"to":497}} {"id":100003352,"name":"ReleaseControllerRevision","signature":"func (m *ControllerRevisionControllerRefManager) ReleaseControllerRevision(ctx context.Context, history *apps.ControllerRevision) error","file":"pkg/controller/controller_ref_manager.go","code":"// ReleaseControllerRevision sends a patch to free the ControllerRevision from the control of its controller.\n// It returns the error if the patching fails. 404 and 422 errors are ignored.\nfunc (m *ControllerRevisionControllerRefManager) ReleaseControllerRevision(ctx context.Context, history *apps.ControllerRevision) error {\n\tklog.V(2).Infof(\"patching ControllerRevision %s_%s to remove its controllerRef to %s/%s:%s\",\n\t\thistory.Namespace, history.Name, m.controllerKind.GroupVersion(), m.controllerKind.Kind, m.Controller.GetName())\n\tpatchBytes, err := GenerateDeleteOwnerRefStrategicMergeBytes(history.UID, []types.UID{m.Controller.GetUID()})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = m.crControl.PatchControllerRevision(ctx, history.Namespace, history.Name, patchBytes)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t// If the ControllerRevision no longer exists, ignore it.\n\t\t\treturn nil\n\t\t}\n\t\tif errors.IsInvalid(err) {\n\t\t\t// Invalid error will be returned in two cases: 1. the ControllerRevision\n\t\t\t// has no owner reference, 2. the uid of the ControllerRevision doesn't\n\t\t\t// match, which means the ControllerRevision is deleted and then recreated.\n\t\t\t// In both cases, the error can be ignored.\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn err\n}","line":{"from":499,"to":524}} {"id":100003353,"name":"ownerRefControllerPatch","signature":"func ownerRefControllerPatch(controller metav1.Object, controllerKind schema.GroupVersionKind, uid types.UID, finalizers ...string) ([]byte, error)","file":"pkg/controller/controller_ref_manager.go","code":"func ownerRefControllerPatch(controller metav1.Object, controllerKind schema.GroupVersionKind, uid types.UID, finalizers ...string) ([]byte, error) {\n\tblockOwnerDeletion := true\n\tisController := true\n\taddControllerPatch := objectForAddOwnerRefPatch{\n\t\tMetadata: objectMetaForPatch{\n\t\t\tUID: uid,\n\t\t\tOwnerReferences: []metav1.OwnerReference{\n\t\t\t\t{\n\t\t\t\t\tAPIVersion: controllerKind.GroupVersion().String(),\n\t\t\t\t\tKind: controllerKind.Kind,\n\t\t\t\t\tName: controller.GetName(),\n\t\t\t\t\tUID: controller.GetUID(),\n\t\t\t\t\tController: \u0026isController,\n\t\t\t\t\tBlockOwnerDeletion: \u0026blockOwnerDeletion,\n\t\t\t\t},\n\t\t\t},\n\t\t\tFinalizers: finalizers,\n\t\t},\n\t}\n\tpatchBytes, err := json.Marshal(\u0026addControllerPatch)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn patchBytes, nil\n}","line":{"from":536,"to":560}} {"id":100003354,"name":"GenerateDeleteOwnerRefStrategicMergeBytes","signature":"func GenerateDeleteOwnerRefStrategicMergeBytes(dependentUID types.UID, ownerUIDs []types.UID, finalizers ...string) ([]byte, error)","file":"pkg/controller/controller_ref_manager.go","code":"func GenerateDeleteOwnerRefStrategicMergeBytes(dependentUID types.UID, ownerUIDs []types.UID, finalizers ...string) ([]byte, error) {\n\tvar ownerReferences []map[string]string\n\tfor _, ownerUID := range ownerUIDs {\n\t\townerReferences = append(ownerReferences, ownerReference(ownerUID, \"delete\"))\n\t}\n\tpatch := objectForDeleteOwnerRefStrategicMergePatch{\n\t\tMetadata: objectMetaForMergePatch{\n\t\t\tUID: dependentUID,\n\t\t\tOwnerReferences: ownerReferences,\n\t\t\tDeleteFinalizers: finalizers,\n\t\t},\n\t}\n\tpatchBytes, err := json.Marshal(\u0026patch)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn patchBytes, nil\n}","line":{"from":572,"to":589}} {"id":100003355,"name":"ownerReference","signature":"func ownerReference(uid types.UID, patchType string) map[string]string","file":"pkg/controller/controller_ref_manager.go","code":"func ownerReference(uid types.UID, patchType string) map[string]string {\n\treturn map[string]string{\n\t\t\"$patch\": patchType,\n\t\t\"uid\": string(uid),\n\t}\n}","line":{"from":591,"to":596}} {"id":100003356,"name":"NoResyncPeriodFunc","signature":"func NoResyncPeriodFunc() time.Duration","file":"pkg/controller/controller_utils.go","code":"// Returns 0 for resyncPeriod in case resyncing is not needed.\nfunc NoResyncPeriodFunc() time.Duration {\n\treturn 0\n}","line":{"from":108,"to":111}} {"id":100003357,"name":"StaticResyncPeriodFunc","signature":"func StaticResyncPeriodFunc(resyncPeriod time.Duration) ResyncPeriodFunc","file":"pkg/controller/controller_utils.go","code":"// StaticResyncPeriodFunc returns the resync period specified\nfunc StaticResyncPeriodFunc(resyncPeriod time.Duration) ResyncPeriodFunc {\n\treturn func() time.Duration {\n\t\treturn resyncPeriod\n\t}\n}","line":{"from":113,"to":118}} {"id":100003358,"name":"GetExpectations","signature":"func (r *ControllerExpectations) GetExpectations(controllerKey string) (*ControlleeExpectations, bool, error)","file":"pkg/controller/controller_utils.go","code":"// GetExpectations returns the ControlleeExpectations of the given controller.\nfunc (r *ControllerExpectations) GetExpectations(controllerKey string) (*ControlleeExpectations, bool, error) {\n\texp, exists, err := r.GetByKey(controllerKey)\n\tif err == nil \u0026\u0026 exists {\n\t\treturn exp.(*ControlleeExpectations), true, nil\n\t}\n\treturn nil, false, err\n}","line":{"from":165,"to":172}} {"id":100003359,"name":"DeleteExpectations","signature":"func (r *ControllerExpectations) DeleteExpectations(controllerKey string)","file":"pkg/controller/controller_utils.go","code":"// DeleteExpectations deletes the expectations of the given controller from the TTLStore.\nfunc (r *ControllerExpectations) DeleteExpectations(controllerKey string) {\n\tif exp, exists, err := r.GetByKey(controllerKey); err == nil \u0026\u0026 exists {\n\t\tif err := r.Delete(exp); err != nil {\n\t\t\tklog.V(2).Infof(\"Error deleting expectations for controller %v: %v\", controllerKey, err)\n\t\t}\n\t}\n}","line":{"from":174,"to":181}} {"id":100003360,"name":"SatisfiedExpectations","signature":"func (r *ControllerExpectations) SatisfiedExpectations(controllerKey string) bool","file":"pkg/controller/controller_utils.go","code":"// SatisfiedExpectations returns true if the required adds/dels for the given controller have been observed.\n// Add/del counts are established by the controller at sync time, and updated as controllees are observed by the controller\n// manager.\nfunc (r *ControllerExpectations) SatisfiedExpectations(controllerKey string) bool {\n\tif exp, exists, err := r.GetExpectations(controllerKey); exists {\n\t\tif exp.Fulfilled() {\n\t\t\tklog.V(4).Infof(\"Controller expectations fulfilled %#v\", exp)\n\t\t\treturn true\n\t\t} else if exp.isExpired() {\n\t\t\tklog.V(4).Infof(\"Controller expectations expired %#v\", exp)\n\t\t\treturn true\n\t\t} else {\n\t\t\tklog.V(4).Infof(\"Controller still waiting on expectations %#v\", exp)\n\t\t\treturn false\n\t\t}\n\t} else if err != nil {\n\t\tklog.V(2).Infof(\"Error encountered while checking expectations %#v, forcing sync\", err)\n\t} else {\n\t\t// When a new controller is created, it doesn't have expectations.\n\t\t// When it doesn't see expected watch events for \u003e TTL, the expectations expire.\n\t\t//\t- In this case it wakes up, creates/deletes controllees, and sets expectations again.\n\t\t// When it has satisfied expectations and no controllees need to be created/destroyed \u003e TTL, the expectations expire.\n\t\t//\t- In this case it continues without setting expectations till it needs to create/delete controllees.\n\t\tklog.V(4).Infof(\"Controller %v either never recorded expectations, or the ttl expired.\", controllerKey)\n\t}\n\t// Trigger a sync if we either encountered and error (which shouldn't happen since we're\n\t// getting from local store) or this controller hasn't established expectations.\n\treturn true\n}","line":{"from":183,"to":211}} {"id":100003361,"name":"isExpired","signature":"func (exp *ControlleeExpectations) isExpired() bool","file":"pkg/controller/controller_utils.go","code":"// TODO: Extend ExpirationCache to support explicit expiration.\n// TODO: Make this possible to disable in tests.\n// TODO: Support injection of clock.\nfunc (exp *ControlleeExpectations) isExpired() bool {\n\treturn clock.RealClock{}.Since(exp.timestamp) \u003e ExpectationsTimeout\n}","line":{"from":213,"to":218}} {"id":100003362,"name":"SetExpectations","signature":"func (r *ControllerExpectations) SetExpectations(controllerKey string, add, del int) error","file":"pkg/controller/controller_utils.go","code":"// SetExpectations registers new expectations for the given controller. Forgets existing expectations.\nfunc (r *ControllerExpectations) SetExpectations(controllerKey string, add, del int) error {\n\texp := \u0026ControlleeExpectations{add: int64(add), del: int64(del), key: controllerKey, timestamp: clock.RealClock{}.Now()}\n\tklog.V(4).Infof(\"Setting expectations %#v\", exp)\n\treturn r.Add(exp)\n}","line":{"from":220,"to":225}} {"id":100003363,"name":"ExpectCreations","signature":"func (r *ControllerExpectations) ExpectCreations(controllerKey string, adds int) error","file":"pkg/controller/controller_utils.go","code":"func (r *ControllerExpectations) ExpectCreations(controllerKey string, adds int) error {\n\treturn r.SetExpectations(controllerKey, adds, 0)\n}","line":{"from":227,"to":229}} {"id":100003364,"name":"ExpectDeletions","signature":"func (r *ControllerExpectations) ExpectDeletions(controllerKey string, dels int) error","file":"pkg/controller/controller_utils.go","code":"func (r *ControllerExpectations) ExpectDeletions(controllerKey string, dels int) error {\n\treturn r.SetExpectations(controllerKey, 0, dels)\n}","line":{"from":231,"to":233}} {"id":100003365,"name":"LowerExpectations","signature":"func (r *ControllerExpectations) LowerExpectations(controllerKey string, add, del int)","file":"pkg/controller/controller_utils.go","code":"// Decrements the expectation counts of the given controller.\nfunc (r *ControllerExpectations) LowerExpectations(controllerKey string, add, del int) {\n\tif exp, exists, err := r.GetExpectations(controllerKey); err == nil \u0026\u0026 exists {\n\t\texp.Add(int64(-add), int64(-del))\n\t\t// The expectations might've been modified since the update on the previous line.\n\t\tklog.V(4).Infof(\"Lowered expectations %#v\", exp)\n\t}\n}","line":{"from":235,"to":242}} {"id":100003366,"name":"RaiseExpectations","signature":"func (r *ControllerExpectations) RaiseExpectations(controllerKey string, add, del int)","file":"pkg/controller/controller_utils.go","code":"// Increments the expectation counts of the given controller.\nfunc (r *ControllerExpectations) RaiseExpectations(controllerKey string, add, del int) {\n\tif exp, exists, err := r.GetExpectations(controllerKey); err == nil \u0026\u0026 exists {\n\t\texp.Add(int64(add), int64(del))\n\t\t// The expectations might've been modified since the update on the previous line.\n\t\tklog.V(4).Infof(\"Raised expectations %#v\", exp)\n\t}\n}","line":{"from":244,"to":251}} {"id":100003367,"name":"CreationObserved","signature":"func (r *ControllerExpectations) CreationObserved(controllerKey string)","file":"pkg/controller/controller_utils.go","code":"// CreationObserved atomically decrements the `add` expectation count of the given controller.\nfunc (r *ControllerExpectations) CreationObserved(controllerKey string) {\n\tr.LowerExpectations(controllerKey, 1, 0)\n}","line":{"from":253,"to":256}} {"id":100003368,"name":"DeletionObserved","signature":"func (r *ControllerExpectations) DeletionObserved(controllerKey string)","file":"pkg/controller/controller_utils.go","code":"// DeletionObserved atomically decrements the `del` expectation count of the given controller.\nfunc (r *ControllerExpectations) DeletionObserved(controllerKey string) {\n\tr.LowerExpectations(controllerKey, 0, 1)\n}","line":{"from":258,"to":261}} {"id":100003369,"name":"Add","signature":"func (e *ControlleeExpectations) Add(add, del int64)","file":"pkg/controller/controller_utils.go","code":"// Add increments the add and del counters.\nfunc (e *ControlleeExpectations) Add(add, del int64) {\n\tatomic.AddInt64(\u0026e.add, add)\n\tatomic.AddInt64(\u0026e.del, del)\n}","line":{"from":273,"to":277}} {"id":100003370,"name":"Fulfilled","signature":"func (e *ControlleeExpectations) Fulfilled() bool","file":"pkg/controller/controller_utils.go","code":"// Fulfilled returns true if this expectation has been fulfilled.\nfunc (e *ControlleeExpectations) Fulfilled() bool {\n\t// TODO: think about why this line being atomic doesn't matter\n\treturn atomic.LoadInt64(\u0026e.add) \u003c= 0 \u0026\u0026 atomic.LoadInt64(\u0026e.del) \u003c= 0\n}","line":{"from":279,"to":283}} {"id":100003371,"name":"GetExpectations","signature":"func (e *ControlleeExpectations) GetExpectations() (int64, int64)","file":"pkg/controller/controller_utils.go","code":"// GetExpectations returns the add and del expectations of the controllee.\nfunc (e *ControlleeExpectations) GetExpectations() (int64, int64) {\n\treturn atomic.LoadInt64(\u0026e.add), atomic.LoadInt64(\u0026e.del)\n}","line":{"from":285,"to":288}} {"id":100003372,"name":"NewControllerExpectations","signature":"func NewControllerExpectations() *ControllerExpectations","file":"pkg/controller/controller_utils.go","code":"// NewControllerExpectations returns a store for ControllerExpectations.\nfunc NewControllerExpectations() *ControllerExpectations {\n\treturn \u0026ControllerExpectations{cache.NewStore(ExpKeyFunc)}\n}","line":{"from":290,"to":293}} {"id":100003373,"name":"GetUIDs","signature":"func (u *UIDTrackingControllerExpectations) GetUIDs(controllerKey string) sets.String","file":"pkg/controller/controller_utils.go","code":"// GetUIDs is a convenience method to avoid exposing the set of expected uids.\n// The returned set is not thread safe, all modifications must be made holding\n// the uidStoreLock.\nfunc (u *UIDTrackingControllerExpectations) GetUIDs(controllerKey string) sets.String {\n\tif uid, exists, err := u.uidStore.GetByKey(controllerKey); err == nil \u0026\u0026 exists {\n\t\treturn uid.(*UIDSet).String\n\t}\n\treturn nil\n}","line":{"from":327,"to":335}} {"id":100003374,"name":"ExpectDeletions","signature":"func (u *UIDTrackingControllerExpectations) ExpectDeletions(rcKey string, deletedKeys []string) error","file":"pkg/controller/controller_utils.go","code":"// ExpectDeletions records expectations for the given deleteKeys, against the given controller.\nfunc (u *UIDTrackingControllerExpectations) ExpectDeletions(rcKey string, deletedKeys []string) error {\n\texpectedUIDs := sets.NewString()\n\tfor _, k := range deletedKeys {\n\t\texpectedUIDs.Insert(k)\n\t}\n\tklog.V(4).Infof(\"Controller %v waiting on deletions for: %+v\", rcKey, deletedKeys)\n\tu.uidStoreLock.Lock()\n\tdefer u.uidStoreLock.Unlock()\n\n\tif existing := u.GetUIDs(rcKey); existing != nil \u0026\u0026 existing.Len() != 0 {\n\t\tklog.Errorf(\"Clobbering existing delete keys: %+v\", existing)\n\t}\n\tif err := u.uidStore.Add(\u0026UIDSet{expectedUIDs, rcKey}); err != nil {\n\t\treturn err\n\t}\n\treturn u.ControllerExpectationsInterface.ExpectDeletions(rcKey, expectedUIDs.Len())\n}","line":{"from":337,"to":354}} {"id":100003375,"name":"DeletionObserved","signature":"func (u *UIDTrackingControllerExpectations) DeletionObserved(rcKey, deleteKey string)","file":"pkg/controller/controller_utils.go","code":"// DeletionObserved records the given deleteKey as a deletion, for the given rc.\nfunc (u *UIDTrackingControllerExpectations) DeletionObserved(rcKey, deleteKey string) {\n\tu.uidStoreLock.Lock()\n\tdefer u.uidStoreLock.Unlock()\n\n\tuids := u.GetUIDs(rcKey)\n\tif uids != nil \u0026\u0026 uids.Has(deleteKey) {\n\t\tklog.V(4).Infof(\"Controller %v received delete for pod %v\", rcKey, deleteKey)\n\t\tu.ControllerExpectationsInterface.DeletionObserved(rcKey)\n\t\tuids.Delete(deleteKey)\n\t}\n}","line":{"from":356,"to":367}} {"id":100003376,"name":"DeleteExpectations","signature":"func (u *UIDTrackingControllerExpectations) DeleteExpectations(rcKey string)","file":"pkg/controller/controller_utils.go","code":"// DeleteExpectations deletes the UID set and invokes DeleteExpectations on the\n// underlying ControllerExpectationsInterface.\nfunc (u *UIDTrackingControllerExpectations) DeleteExpectations(rcKey string) {\n\tu.uidStoreLock.Lock()\n\tdefer u.uidStoreLock.Unlock()\n\n\tu.ControllerExpectationsInterface.DeleteExpectations(rcKey)\n\tif uidExp, exists, err := u.uidStore.GetByKey(rcKey); err == nil \u0026\u0026 exists {\n\t\tif err := u.uidStore.Delete(uidExp); err != nil {\n\t\t\tklog.V(2).Infof(\"Error deleting uid expectations for controller %v: %v\", rcKey, err)\n\t\t}\n\t}\n}","line":{"from":369,"to":381}} {"id":100003377,"name":"NewUIDTrackingControllerExpectations","signature":"func NewUIDTrackingControllerExpectations(ce ControllerExpectationsInterface) *UIDTrackingControllerExpectations","file":"pkg/controller/controller_utils.go","code":"// NewUIDTrackingControllerExpectations returns a wrapper around\n// ControllerExpectations that is aware of deleteKeys.\nfunc NewUIDTrackingControllerExpectations(ce ControllerExpectationsInterface) *UIDTrackingControllerExpectations {\n\treturn \u0026UIDTrackingControllerExpectations{ControllerExpectationsInterface: ce, uidStore: cache.NewStore(UIDSetKeyFunc)}\n}","line":{"from":383,"to":387}} {"id":100003378,"name":"PatchReplicaSet","signature":"func (r RealRSControl) PatchReplicaSet(ctx context.Context, namespace, name string, data []byte) error","file":"pkg/controller/controller_utils.go","code":"func (r RealRSControl) PatchReplicaSet(ctx context.Context, namespace, name string, data []byte) error {\n\t_, err := r.KubeClient.AppsV1().ReplicaSets(namespace).Patch(ctx, name, types.StrategicMergePatchType, data, metav1.PatchOptions{})\n\treturn err\n}","line":{"from":420,"to":423}} {"id":100003379,"name":"PatchControllerRevision","signature":"func (r RealControllerRevisionControl) PatchControllerRevision(ctx context.Context, namespace, name string, data []byte) error","file":"pkg/controller/controller_utils.go","code":"func (r RealControllerRevisionControl) PatchControllerRevision(ctx context.Context, namespace, name string, data []byte) error {\n\t_, err := r.KubeClient.AppsV1().ControllerRevisions(namespace).Patch(ctx, name, types.StrategicMergePatchType, data, metav1.PatchOptions{})\n\treturn err\n}","line":{"from":440,"to":443}} {"id":100003380,"name":"getPodsLabelSet","signature":"func getPodsLabelSet(template *v1.PodTemplateSpec) labels.Set","file":"pkg/controller/controller_utils.go","code":"func getPodsLabelSet(template *v1.PodTemplateSpec) labels.Set {\n\tdesiredLabels := make(labels.Set)\n\tfor k, v := range template.Labels {\n\t\tdesiredLabels[k] = v\n\t}\n\treturn desiredLabels\n}","line":{"from":466,"to":472}} {"id":100003381,"name":"getPodsFinalizers","signature":"func getPodsFinalizers(template *v1.PodTemplateSpec) []string","file":"pkg/controller/controller_utils.go","code":"func getPodsFinalizers(template *v1.PodTemplateSpec) []string {\n\tdesiredFinalizers := make([]string, len(template.Finalizers))\n\tcopy(desiredFinalizers, template.Finalizers)\n\treturn desiredFinalizers\n}","line":{"from":474,"to":478}} {"id":100003382,"name":"getPodsAnnotationSet","signature":"func getPodsAnnotationSet(template *v1.PodTemplateSpec) labels.Set","file":"pkg/controller/controller_utils.go","code":"func getPodsAnnotationSet(template *v1.PodTemplateSpec) labels.Set {\n\tdesiredAnnotations := make(labels.Set)\n\tfor k, v := range template.Annotations {\n\t\tdesiredAnnotations[k] = v\n\t}\n\treturn desiredAnnotations\n}","line":{"from":480,"to":486}} {"id":100003383,"name":"getPodsPrefix","signature":"func getPodsPrefix(controllerName string) string","file":"pkg/controller/controller_utils.go","code":"func getPodsPrefix(controllerName string) string {\n\t// use the dash (if the name isn't too long) to make the pod name a bit prettier\n\tprefix := fmt.Sprintf(\"%s-\", controllerName)\n\tif len(validation.ValidatePodName(prefix, true)) != 0 {\n\t\tprefix = controllerName\n\t}\n\treturn prefix\n}","line":{"from":488,"to":495}} {"id":100003384,"name":"validateControllerRef","signature":"func validateControllerRef(controllerRef *metav1.OwnerReference) error","file":"pkg/controller/controller_utils.go","code":"func validateControllerRef(controllerRef *metav1.OwnerReference) error {\n\tif controllerRef == nil {\n\t\treturn fmt.Errorf(\"controllerRef is nil\")\n\t}\n\tif len(controllerRef.APIVersion) == 0 {\n\t\treturn fmt.Errorf(\"controllerRef has empty APIVersion\")\n\t}\n\tif len(controllerRef.Kind) == 0 {\n\t\treturn fmt.Errorf(\"controllerRef has empty Kind\")\n\t}\n\tif controllerRef.Controller == nil || !*controllerRef.Controller {\n\t\treturn fmt.Errorf(\"controllerRef.Controller is not set to true\")\n\t}\n\tif controllerRef.BlockOwnerDeletion == nil || !*controllerRef.BlockOwnerDeletion {\n\t\treturn fmt.Errorf(\"controllerRef.BlockOwnerDeletion is not set\")\n\t}\n\treturn nil\n}","line":{"from":497,"to":514}} {"id":100003385,"name":"CreatePods","signature":"func (r RealPodControl) CreatePods(ctx context.Context, namespace string, template *v1.PodTemplateSpec, controllerObject runtime.Object, controllerRef *metav1.OwnerReference) error","file":"pkg/controller/controller_utils.go","code":"func (r RealPodControl) CreatePods(ctx context.Context, namespace string, template *v1.PodTemplateSpec, controllerObject runtime.Object, controllerRef *metav1.OwnerReference) error {\n\treturn r.CreatePodsWithGenerateName(ctx, namespace, template, controllerObject, controllerRef, \"\")\n}","line":{"from":516,"to":518}} {"id":100003386,"name":"CreatePodsWithGenerateName","signature":"func (r RealPodControl) CreatePodsWithGenerateName(ctx context.Context, namespace string, template *v1.PodTemplateSpec, controllerObject runtime.Object, controllerRef *metav1.OwnerReference, generateName string) error","file":"pkg/controller/controller_utils.go","code":"func (r RealPodControl) CreatePodsWithGenerateName(ctx context.Context, namespace string, template *v1.PodTemplateSpec, controllerObject runtime.Object, controllerRef *metav1.OwnerReference, generateName string) error {\n\tif err := validateControllerRef(controllerRef); err != nil {\n\t\treturn err\n\t}\n\tpod, err := GetPodFromTemplate(template, controllerObject, controllerRef)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(generateName) \u003e 0 {\n\t\tpod.ObjectMeta.GenerateName = generateName\n\t}\n\treturn r.createPods(ctx, namespace, pod, controllerObject)\n}","line":{"from":520,"to":532}} {"id":100003387,"name":"PatchPod","signature":"func (r RealPodControl) PatchPod(ctx context.Context, namespace, name string, data []byte) error","file":"pkg/controller/controller_utils.go","code":"func (r RealPodControl) PatchPod(ctx context.Context, namespace, name string, data []byte) error {\n\t_, err := r.KubeClient.CoreV1().Pods(namespace).Patch(ctx, name, types.StrategicMergePatchType, data, metav1.PatchOptions{})\n\treturn err\n}","line":{"from":534,"to":537}} {"id":100003388,"name":"GetPodFromTemplate","signature":"func GetPodFromTemplate(template *v1.PodTemplateSpec, parentObject runtime.Object, controllerRef *metav1.OwnerReference) (*v1.Pod, error)","file":"pkg/controller/controller_utils.go","code":"func GetPodFromTemplate(template *v1.PodTemplateSpec, parentObject runtime.Object, controllerRef *metav1.OwnerReference) (*v1.Pod, error) {\n\tdesiredLabels := getPodsLabelSet(template)\n\tdesiredFinalizers := getPodsFinalizers(template)\n\tdesiredAnnotations := getPodsAnnotationSet(template)\n\taccessor, err := meta.Accessor(parentObject)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"parentObject does not have ObjectMeta, %v\", err)\n\t}\n\tprefix := getPodsPrefix(accessor.GetName())\n\n\tpod := \u0026v1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tLabels: desiredLabels,\n\t\t\tAnnotations: desiredAnnotations,\n\t\t\tGenerateName: prefix,\n\t\t\tFinalizers: desiredFinalizers,\n\t\t},\n\t}\n\tif controllerRef != nil {\n\t\tpod.OwnerReferences = append(pod.OwnerReferences, *controllerRef)\n\t}\n\tpod.Spec = *template.Spec.DeepCopy()\n\treturn pod, nil\n}","line":{"from":539,"to":562}} {"id":100003389,"name":"createPods","signature":"func (r RealPodControl) createPods(ctx context.Context, namespace string, pod *v1.Pod, object runtime.Object) error","file":"pkg/controller/controller_utils.go","code":"func (r RealPodControl) createPods(ctx context.Context, namespace string, pod *v1.Pod, object runtime.Object) error {\n\tif len(labels.Set(pod.Labels)) == 0 {\n\t\treturn fmt.Errorf(\"unable to create pods, no labels\")\n\t}\n\tnewPod, err := r.KubeClient.CoreV1().Pods(namespace).Create(ctx, pod, metav1.CreateOptions{})\n\tif err != nil {\n\t\t// only send an event if the namespace isn't terminating\n\t\tif !apierrors.HasStatusCause(err, v1.NamespaceTerminatingCause) {\n\t\t\tr.Recorder.Eventf(object, v1.EventTypeWarning, FailedCreatePodReason, \"Error creating: %v\", err)\n\t\t}\n\t\treturn err\n\t}\n\taccessor, err := meta.Accessor(object)\n\tif err != nil {\n\t\tklog.Errorf(\"parentObject does not have ObjectMeta, %v\", err)\n\t\treturn nil\n\t}\n\tklog.V(4).Infof(\"Controller %v created pod %v\", accessor.GetName(), newPod.Name)\n\tr.Recorder.Eventf(object, v1.EventTypeNormal, SuccessfulCreatePodReason, \"Created pod: %v\", newPod.Name)\n\n\treturn nil\n}","line":{"from":564,"to":585}} {"id":100003390,"name":"DeletePod","signature":"func (r RealPodControl) DeletePod(ctx context.Context, namespace string, podID string, object runtime.Object) error","file":"pkg/controller/controller_utils.go","code":"func (r RealPodControl) DeletePod(ctx context.Context, namespace string, podID string, object runtime.Object) error {\n\taccessor, err := meta.Accessor(object)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"object does not have ObjectMeta, %v\", err)\n\t}\n\tklog.V(2).InfoS(\"Deleting pod\", \"controller\", accessor.GetName(), \"pod\", klog.KRef(namespace, podID))\n\tif err := r.KubeClient.CoreV1().Pods(namespace).Delete(ctx, podID, metav1.DeleteOptions{}); err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\tklog.V(4).Infof(\"pod %v/%v has already been deleted.\", namespace, podID)\n\t\t\treturn err\n\t\t}\n\t\tr.Recorder.Eventf(object, v1.EventTypeWarning, FailedDeletePodReason, \"Error deleting: %v\", err)\n\t\treturn fmt.Errorf(\"unable to delete pods: %v\", err)\n\t}\n\tr.Recorder.Eventf(object, v1.EventTypeNormal, SuccessfulDeletePodReason, \"Deleted pod: %v\", podID)\n\n\treturn nil\n}","line":{"from":587,"to":604}} {"id":100003391,"name":"PatchPod","signature":"func (f *FakePodControl) PatchPod(ctx context.Context, namespace, name string, data []byte) error","file":"pkg/controller/controller_utils.go","code":"func (f *FakePodControl) PatchPod(ctx context.Context, namespace, name string, data []byte) error {\n\tf.Lock()\n\tdefer f.Unlock()\n\tf.Patches = append(f.Patches, data)\n\tif f.Err != nil {\n\t\treturn f.Err\n\t}\n\treturn nil\n}","line":{"from":619,"to":627}} {"id":100003392,"name":"CreatePods","signature":"func (f *FakePodControl) CreatePods(ctx context.Context, namespace string, spec *v1.PodTemplateSpec, object runtime.Object, controllerRef *metav1.OwnerReference) error","file":"pkg/controller/controller_utils.go","code":"func (f *FakePodControl) CreatePods(ctx context.Context, namespace string, spec *v1.PodTemplateSpec, object runtime.Object, controllerRef *metav1.OwnerReference) error {\n\treturn f.CreatePodsWithGenerateName(ctx, namespace, spec, object, controllerRef, \"\")\n}","line":{"from":629,"to":631}} {"id":100003393,"name":"CreatePodsWithGenerateName","signature":"func (f *FakePodControl) CreatePodsWithGenerateName(ctx context.Context, namespace string, spec *v1.PodTemplateSpec, object runtime.Object, controllerRef *metav1.OwnerReference, generateNamePrefix string) error","file":"pkg/controller/controller_utils.go","code":"func (f *FakePodControl) CreatePodsWithGenerateName(ctx context.Context, namespace string, spec *v1.PodTemplateSpec, object runtime.Object, controllerRef *metav1.OwnerReference, generateNamePrefix string) error {\n\tf.Lock()\n\tdefer f.Unlock()\n\tf.CreateCallCount++\n\tif f.CreateLimit != 0 \u0026\u0026 f.CreateCallCount \u003e f.CreateLimit {\n\t\treturn fmt.Errorf(\"not creating pod, limit %d already reached (create call %d)\", f.CreateLimit, f.CreateCallCount)\n\t}\n\tspec.GenerateName = generateNamePrefix\n\tf.Templates = append(f.Templates, *spec)\n\tf.ControllerRefs = append(f.ControllerRefs, *controllerRef)\n\tif f.Err != nil {\n\t\treturn f.Err\n\t}\n\treturn nil\n}","line":{"from":633,"to":647}} {"id":100003394,"name":"DeletePod","signature":"func (f *FakePodControl) DeletePod(ctx context.Context, namespace string, podID string, object runtime.Object) error","file":"pkg/controller/controller_utils.go","code":"func (f *FakePodControl) DeletePod(ctx context.Context, namespace string, podID string, object runtime.Object) error {\n\tf.Lock()\n\tdefer f.Unlock()\n\tf.DeletePodName = append(f.DeletePodName, podID)\n\tif f.Err != nil {\n\t\treturn f.Err\n\t}\n\treturn nil\n}","line":{"from":649,"to":657}} {"id":100003395,"name":"Clear","signature":"func (f *FakePodControl) Clear()","file":"pkg/controller/controller_utils.go","code":"func (f *FakePodControl) Clear() {\n\tf.Lock()\n\tdefer f.Unlock()\n\tf.DeletePodName = []string{}\n\tf.Templates = []v1.PodTemplateSpec{}\n\tf.ControllerRefs = []metav1.OwnerReference{}\n\tf.Patches = [][]byte{}\n\tf.CreateLimit = 0\n\tf.CreateCallCount = 0\n}","line":{"from":659,"to":668}} {"id":100003396,"name":"Len","signature":"func (s ByLogging) Len() int { return len(s) }","file":"pkg/controller/controller_utils.go","code":"func (s ByLogging) Len() int { return len(s) }","line":{"from":673,"to":673}} {"id":100003397,"name":"Swap","signature":"func (s ByLogging) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","file":"pkg/controller/controller_utils.go","code":"func (s ByLogging) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","line":{"from":674,"to":674}} {"id":100003398,"name":"Less","signature":"func (s ByLogging) Less(i, j int) bool","file":"pkg/controller/controller_utils.go","code":"func (s ByLogging) Less(i, j int) bool {\n\t// 1. assigned \u003c unassigned\n\tif s[i].Spec.NodeName != s[j].Spec.NodeName \u0026\u0026 (len(s[i].Spec.NodeName) == 0 || len(s[j].Spec.NodeName) == 0) {\n\t\treturn len(s[i].Spec.NodeName) \u003e 0\n\t}\n\t// 2. PodRunning \u003c PodUnknown \u003c PodPending\n\tif s[i].Status.Phase != s[j].Status.Phase {\n\t\treturn podPhaseToOrdinal[s[i].Status.Phase] \u003e podPhaseToOrdinal[s[j].Status.Phase]\n\t}\n\t// 3. ready \u003c not ready\n\tif podutil.IsPodReady(s[i]) != podutil.IsPodReady(s[j]) {\n\t\treturn podutil.IsPodReady(s[i])\n\t}\n\t// TODO: take availability into account when we push minReadySeconds information from deployment into pods,\n\t// see https://github.com/kubernetes/kubernetes/issues/22065\n\t// 4. Been ready for more time \u003c less time \u003c empty time\n\tif podutil.IsPodReady(s[i]) \u0026\u0026 podutil.IsPodReady(s[j]) {\n\t\treadyTime1 := podReadyTime(s[i])\n\t\treadyTime2 := podReadyTime(s[j])\n\t\tif !readyTime1.Equal(readyTime2) {\n\t\t\treturn afterOrZero(readyTime2, readyTime1)\n\t\t}\n\t}\n\t// 5. Pods with containers with higher restart counts \u003c lower restart counts\n\tif maxContainerRestarts(s[i]) != maxContainerRestarts(s[j]) {\n\t\treturn maxContainerRestarts(s[i]) \u003e maxContainerRestarts(s[j])\n\t}\n\t// 6. older pods \u003c newer pods \u003c empty timestamp pods\n\tif !s[i].CreationTimestamp.Equal(\u0026s[j].CreationTimestamp) {\n\t\treturn afterOrZero(\u0026s[j].CreationTimestamp, \u0026s[i].CreationTimestamp)\n\t}\n\treturn false\n}","line":{"from":676,"to":708}} {"id":100003399,"name":"Len","signature":"func (s ActivePods) Len() int { return len(s) }","file":"pkg/controller/controller_utils.go","code":"func (s ActivePods) Len() int { return len(s) }","line":{"from":713,"to":713}} {"id":100003400,"name":"Swap","signature":"func (s ActivePods) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","file":"pkg/controller/controller_utils.go","code":"func (s ActivePods) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","line":{"from":714,"to":714}} {"id":100003401,"name":"Less","signature":"func (s ActivePods) Less(i, j int) bool","file":"pkg/controller/controller_utils.go","code":"func (s ActivePods) Less(i, j int) bool {\n\t// 1. Unassigned \u003c assigned\n\t// If only one of the pods is unassigned, the unassigned one is smaller\n\tif s[i].Spec.NodeName != s[j].Spec.NodeName \u0026\u0026 (len(s[i].Spec.NodeName) == 0 || len(s[j].Spec.NodeName) == 0) {\n\t\treturn len(s[i].Spec.NodeName) == 0\n\t}\n\t// 2. PodPending \u003c PodUnknown \u003c PodRunning\n\tif podPhaseToOrdinal[s[i].Status.Phase] != podPhaseToOrdinal[s[j].Status.Phase] {\n\t\treturn podPhaseToOrdinal[s[i].Status.Phase] \u003c podPhaseToOrdinal[s[j].Status.Phase]\n\t}\n\t// 3. Not ready \u003c ready\n\t// If only one of the pods is not ready, the not ready one is smaller\n\tif podutil.IsPodReady(s[i]) != podutil.IsPodReady(s[j]) {\n\t\treturn !podutil.IsPodReady(s[i])\n\t}\n\t// TODO: take availability into account when we push minReadySeconds information from deployment into pods,\n\t// see https://github.com/kubernetes/kubernetes/issues/22065\n\t// 4. Been ready for empty time \u003c less time \u003c more time\n\t// If both pods are ready, the latest ready one is smaller\n\tif podutil.IsPodReady(s[i]) \u0026\u0026 podutil.IsPodReady(s[j]) {\n\t\treadyTime1 := podReadyTime(s[i])\n\t\treadyTime2 := podReadyTime(s[j])\n\t\tif !readyTime1.Equal(readyTime2) {\n\t\t\treturn afterOrZero(readyTime1, readyTime2)\n\t\t}\n\t}\n\t// 5. Pods with containers with higher restart counts \u003c lower restart counts\n\tif maxContainerRestarts(s[i]) != maxContainerRestarts(s[j]) {\n\t\treturn maxContainerRestarts(s[i]) \u003e maxContainerRestarts(s[j])\n\t}\n\t// 6. Empty creation time pods \u003c newer pods \u003c older pods\n\tif !s[i].CreationTimestamp.Equal(\u0026s[j].CreationTimestamp) {\n\t\treturn afterOrZero(\u0026s[i].CreationTimestamp, \u0026s[j].CreationTimestamp)\n\t}\n\treturn false\n}","line":{"from":716,"to":751}} {"id":100003402,"name":"Len","signature":"func (s ActivePodsWithRanks) Len() int","file":"pkg/controller/controller_utils.go","code":"func (s ActivePodsWithRanks) Len() int {\n\treturn len(s.Pods)\n}","line":{"from":799,"to":801}} {"id":100003403,"name":"Swap","signature":"func (s ActivePodsWithRanks) Swap(i, j int)","file":"pkg/controller/controller_utils.go","code":"func (s ActivePodsWithRanks) Swap(i, j int) {\n\ts.Pods[i], s.Pods[j] = s.Pods[j], s.Pods[i]\n\ts.Rank[i], s.Rank[j] = s.Rank[j], s.Rank[i]\n}","line":{"from":803,"to":806}} {"id":100003404,"name":"Less","signature":"func (s ActivePodsWithRanks) Less(i, j int) bool","file":"pkg/controller/controller_utils.go","code":"// Less compares two pods with corresponding ranks and returns true if the first\n// one should be preferred for deletion.\nfunc (s ActivePodsWithRanks) Less(i, j int) bool {\n\t// 1. Unassigned \u003c assigned\n\t// If only one of the pods is unassigned, the unassigned one is smaller\n\tif s.Pods[i].Spec.NodeName != s.Pods[j].Spec.NodeName \u0026\u0026 (len(s.Pods[i].Spec.NodeName) == 0 || len(s.Pods[j].Spec.NodeName) == 0) {\n\t\treturn len(s.Pods[i].Spec.NodeName) == 0\n\t}\n\t// 2. PodPending \u003c PodUnknown \u003c PodRunning\n\tif podPhaseToOrdinal[s.Pods[i].Status.Phase] != podPhaseToOrdinal[s.Pods[j].Status.Phase] {\n\t\treturn podPhaseToOrdinal[s.Pods[i].Status.Phase] \u003c podPhaseToOrdinal[s.Pods[j].Status.Phase]\n\t}\n\t// 3. Not ready \u003c ready\n\t// If only one of the pods is not ready, the not ready one is smaller\n\tif podutil.IsPodReady(s.Pods[i]) != podutil.IsPodReady(s.Pods[j]) {\n\t\treturn !podutil.IsPodReady(s.Pods[i])\n\t}\n\n\t// 4. lower pod-deletion-cost \u003c higher pod-deletion cost\n\tif utilfeature.DefaultFeatureGate.Enabled(features.PodDeletionCost) {\n\t\tpi, _ := helper.GetDeletionCostFromPodAnnotations(s.Pods[i].Annotations)\n\t\tpj, _ := helper.GetDeletionCostFromPodAnnotations(s.Pods[j].Annotations)\n\t\tif pi != pj {\n\t\t\treturn pi \u003c pj\n\t\t}\n\t}\n\n\t// 5. Doubled up \u003c not doubled up\n\t// If one of the two pods is on the same node as one or more additional\n\t// ready pods that belong to the same replicaset, whichever pod has more\n\t// colocated ready pods is less\n\tif s.Rank[i] != s.Rank[j] {\n\t\treturn s.Rank[i] \u003e s.Rank[j]\n\t}\n\t// TODO: take availability into account when we push minReadySeconds information from deployment into pods,\n\t// see https://github.com/kubernetes/kubernetes/issues/22065\n\t// 6. Been ready for empty time \u003c less time \u003c more time\n\t// If both pods are ready, the latest ready one is smaller\n\tif podutil.IsPodReady(s.Pods[i]) \u0026\u0026 podutil.IsPodReady(s.Pods[j]) {\n\t\treadyTime1 := podReadyTime(s.Pods[i])\n\t\treadyTime2 := podReadyTime(s.Pods[j])\n\t\tif !readyTime1.Equal(readyTime2) {\n\t\t\tif !utilfeature.DefaultFeatureGate.Enabled(features.LogarithmicScaleDown) {\n\t\t\t\treturn afterOrZero(readyTime1, readyTime2)\n\t\t\t} else {\n\t\t\t\tif s.Now.IsZero() || readyTime1.IsZero() || readyTime2.IsZero() {\n\t\t\t\t\treturn afterOrZero(readyTime1, readyTime2)\n\t\t\t\t}\n\t\t\t\trankDiff := logarithmicRankDiff(*readyTime1, *readyTime2, s.Now)\n\t\t\t\tif rankDiff == 0 {\n\t\t\t\t\treturn s.Pods[i].UID \u003c s.Pods[j].UID\n\t\t\t\t}\n\t\t\t\treturn rankDiff \u003c 0\n\t\t\t}\n\t\t}\n\t}\n\t// 7. Pods with containers with higher restart counts \u003c lower restart counts\n\tif maxContainerRestarts(s.Pods[i]) != maxContainerRestarts(s.Pods[j]) {\n\t\treturn maxContainerRestarts(s.Pods[i]) \u003e maxContainerRestarts(s.Pods[j])\n\t}\n\t// 8. Empty creation time pods \u003c newer pods \u003c older pods\n\tif !s.Pods[i].CreationTimestamp.Equal(\u0026s.Pods[j].CreationTimestamp) {\n\t\tif !utilfeature.DefaultFeatureGate.Enabled(features.LogarithmicScaleDown) {\n\t\t\treturn afterOrZero(\u0026s.Pods[i].CreationTimestamp, \u0026s.Pods[j].CreationTimestamp)\n\t\t} else {\n\t\t\tif s.Now.IsZero() || s.Pods[i].CreationTimestamp.IsZero() || s.Pods[j].CreationTimestamp.IsZero() {\n\t\t\t\treturn afterOrZero(\u0026s.Pods[i].CreationTimestamp, \u0026s.Pods[j].CreationTimestamp)\n\t\t\t}\n\t\t\trankDiff := logarithmicRankDiff(s.Pods[i].CreationTimestamp, s.Pods[j].CreationTimestamp, s.Now)\n\t\t\tif rankDiff == 0 {\n\t\t\t\treturn s.Pods[i].UID \u003c s.Pods[j].UID\n\t\t\t}\n\t\t\treturn rankDiff \u003c 0\n\t\t}\n\t}\n\treturn false\n}","line":{"from":808,"to":884}} {"id":100003405,"name":"afterOrZero","signature":"func afterOrZero(t1, t2 *metav1.Time) bool","file":"pkg/controller/controller_utils.go","code":"// afterOrZero checks if time t1 is after time t2; if one of them\n// is zero, the zero time is seen as after non-zero time.\nfunc afterOrZero(t1, t2 *metav1.Time) bool {\n\tif t1.Time.IsZero() || t2.Time.IsZero() {\n\t\treturn t1.Time.IsZero()\n\t}\n\treturn t1.After(t2.Time)\n}","line":{"from":886,"to":893}} {"id":100003406,"name":"logarithmicRankDiff","signature":"func logarithmicRankDiff(t1, t2, now metav1.Time) int64","file":"pkg/controller/controller_utils.go","code":"// logarithmicRankDiff calculates the base-2 logarithmic ranks of 2 timestamps,\n// compared to the current timestamp\nfunc logarithmicRankDiff(t1, t2, now metav1.Time) int64 {\n\td1 := now.Sub(t1.Time)\n\td2 := now.Sub(t2.Time)\n\tr1 := int64(-1)\n\tr2 := int64(-1)\n\tif d1 \u003e 0 {\n\t\tr1 = int64(math.Log2(float64(d1)))\n\t}\n\tif d2 \u003e 0 {\n\t\tr2 = int64(math.Log2(float64(d2)))\n\t}\n\treturn r1 - r2\n}","line":{"from":895,"to":909}} {"id":100003407,"name":"podReadyTime","signature":"func podReadyTime(pod *v1.Pod) *metav1.Time","file":"pkg/controller/controller_utils.go","code":"func podReadyTime(pod *v1.Pod) *metav1.Time {\n\tif podutil.IsPodReady(pod) {\n\t\tfor _, c := range pod.Status.Conditions {\n\t\t\t// we only care about pod ready conditions\n\t\t\tif c.Type == v1.PodReady \u0026\u0026 c.Status == v1.ConditionTrue {\n\t\t\t\treturn \u0026c.LastTransitionTime\n\t\t\t}\n\t\t}\n\t}\n\treturn \u0026metav1.Time{}\n}","line":{"from":911,"to":921}} {"id":100003408,"name":"maxContainerRestarts","signature":"func maxContainerRestarts(pod *v1.Pod) int","file":"pkg/controller/controller_utils.go","code":"func maxContainerRestarts(pod *v1.Pod) int {\n\tmaxRestarts := 0\n\tfor _, c := range pod.Status.ContainerStatuses {\n\t\tmaxRestarts = integer.IntMax(maxRestarts, int(c.RestartCount))\n\t}\n\treturn maxRestarts\n}","line":{"from":923,"to":929}} {"id":100003409,"name":"FilterActivePods","signature":"func FilterActivePods(pods []*v1.Pod) []*v1.Pod","file":"pkg/controller/controller_utils.go","code":"// FilterActivePods returns pods that have not terminated.\nfunc FilterActivePods(pods []*v1.Pod) []*v1.Pod {\n\tvar result []*v1.Pod\n\tfor _, p := range pods {\n\t\tif IsPodActive(p) {\n\t\t\tresult = append(result, p)\n\t\t} else {\n\t\t\tklog.V(4).Infof(\"Ignoring inactive pod %v/%v in state %v, deletion time %v\",\n\t\t\t\tp.Namespace, p.Name, p.Status.Phase, p.DeletionTimestamp)\n\t\t}\n\t}\n\treturn result\n}","line":{"from":931,"to":943}} {"id":100003410,"name":"IsPodActive","signature":"func IsPodActive(p *v1.Pod) bool","file":"pkg/controller/controller_utils.go","code":"func IsPodActive(p *v1.Pod) bool {\n\treturn v1.PodSucceeded != p.Status.Phase \u0026\u0026\n\t\tv1.PodFailed != p.Status.Phase \u0026\u0026\n\t\tp.DeletionTimestamp == nil\n}","line":{"from":945,"to":949}} {"id":100003411,"name":"FilterActiveReplicaSets","signature":"func FilterActiveReplicaSets(replicaSets []*apps.ReplicaSet) []*apps.ReplicaSet","file":"pkg/controller/controller_utils.go","code":"// FilterActiveReplicaSets returns replica sets that have (or at least ought to have) pods.\nfunc FilterActiveReplicaSets(replicaSets []*apps.ReplicaSet) []*apps.ReplicaSet {\n\tactiveFilter := func(rs *apps.ReplicaSet) bool {\n\t\treturn rs != nil \u0026\u0026 *(rs.Spec.Replicas) \u003e 0\n\t}\n\treturn FilterReplicaSets(replicaSets, activeFilter)\n}","line":{"from":951,"to":957}} {"id":100003412,"name":"FilterReplicaSets","signature":"func FilterReplicaSets(RSes []*apps.ReplicaSet, filterFn filterRS) []*apps.ReplicaSet","file":"pkg/controller/controller_utils.go","code":"// FilterReplicaSets returns replica sets that are filtered by filterFn (all returned ones should match filterFn).\nfunc FilterReplicaSets(RSes []*apps.ReplicaSet, filterFn filterRS) []*apps.ReplicaSet {\n\tvar filtered []*apps.ReplicaSet\n\tfor i := range RSes {\n\t\tif filterFn(RSes[i]) {\n\t\t\tfiltered = append(filtered, RSes[i])\n\t\t}\n\t}\n\treturn filtered\n}","line":{"from":961,"to":970}} {"id":100003413,"name":"PodKey","signature":"func PodKey(pod *v1.Pod) string","file":"pkg/controller/controller_utils.go","code":"// PodKey returns a key unique to the given pod within a cluster.\n// It's used so we consistently use the same key scheme in this module.\n// It does exactly what cache.MetaNamespaceKeyFunc would have done\n// except there's not possibility for error since we know the exact type.\nfunc PodKey(pod *v1.Pod) string {\n\treturn fmt.Sprintf(\"%v/%v\", pod.Namespace, pod.Name)\n}","line":{"from":972,"to":978}} {"id":100003414,"name":"Len","signature":"func (o ControllersByCreationTimestamp) Len() int { return len(o) }","file":"pkg/controller/controller_utils.go","code":"func (o ControllersByCreationTimestamp) Len() int { return len(o) }","line":{"from":983,"to":983}} {"id":100003415,"name":"Swap","signature":"func (o ControllersByCreationTimestamp) Swap(i, j int) { o[i], o[j] = o[j], o[i] }","file":"pkg/controller/controller_utils.go","code":"func (o ControllersByCreationTimestamp) Swap(i, j int) { o[i], o[j] = o[j], o[i] }","line":{"from":984,"to":984}} {"id":100003416,"name":"Less","signature":"func (o ControllersByCreationTimestamp) Less(i, j int) bool","file":"pkg/controller/controller_utils.go","code":"func (o ControllersByCreationTimestamp) Less(i, j int) bool {\n\tif o[i].CreationTimestamp.Equal(\u0026o[j].CreationTimestamp) {\n\t\treturn o[i].Name \u003c o[j].Name\n\t}\n\treturn o[i].CreationTimestamp.Before(\u0026o[j].CreationTimestamp)\n}","line":{"from":985,"to":990}} {"id":100003417,"name":"Len","signature":"func (o ReplicaSetsByCreationTimestamp) Len() int { return len(o) }","file":"pkg/controller/controller_utils.go","code":"func (o ReplicaSetsByCreationTimestamp) Len() int { return len(o) }","line":{"from":995,"to":995}} {"id":100003418,"name":"Swap","signature":"func (o ReplicaSetsByCreationTimestamp) Swap(i, j int) { o[i], o[j] = o[j], o[i] }","file":"pkg/controller/controller_utils.go","code":"func (o ReplicaSetsByCreationTimestamp) Swap(i, j int) { o[i], o[j] = o[j], o[i] }","line":{"from":996,"to":996}} {"id":100003419,"name":"Less","signature":"func (o ReplicaSetsByCreationTimestamp) Less(i, j int) bool","file":"pkg/controller/controller_utils.go","code":"func (o ReplicaSetsByCreationTimestamp) Less(i, j int) bool {\n\tif o[i].CreationTimestamp.Equal(\u0026o[j].CreationTimestamp) {\n\t\treturn o[i].Name \u003c o[j].Name\n\t}\n\treturn o[i].CreationTimestamp.Before(\u0026o[j].CreationTimestamp)\n}","line":{"from":997,"to":1002}} {"id":100003420,"name":"Len","signature":"func (o ReplicaSetsBySizeOlder) Len() int { return len(o) }","file":"pkg/controller/controller_utils.go","code":"func (o ReplicaSetsBySizeOlder) Len() int { return len(o) }","line":{"from":1008,"to":1008}} {"id":100003421,"name":"Swap","signature":"func (o ReplicaSetsBySizeOlder) Swap(i, j int) { o[i], o[j] = o[j], o[i] }","file":"pkg/controller/controller_utils.go","code":"func (o ReplicaSetsBySizeOlder) Swap(i, j int) { o[i], o[j] = o[j], o[i] }","line":{"from":1009,"to":1009}} {"id":100003422,"name":"Less","signature":"func (o ReplicaSetsBySizeOlder) Less(i, j int) bool","file":"pkg/controller/controller_utils.go","code":"func (o ReplicaSetsBySizeOlder) Less(i, j int) bool {\n\tif *(o[i].Spec.Replicas) == *(o[j].Spec.Replicas) {\n\t\treturn ReplicaSetsByCreationTimestamp(o).Less(i, j)\n\t}\n\treturn *(o[i].Spec.Replicas) \u003e *(o[j].Spec.Replicas)\n}","line":{"from":1010,"to":1015}} {"id":100003423,"name":"Len","signature":"func (o ReplicaSetsBySizeNewer) Len() int { return len(o) }","file":"pkg/controller/controller_utils.go","code":"func (o ReplicaSetsBySizeNewer) Len() int { return len(o) }","line":{"from":1021,"to":1021}} {"id":100003424,"name":"Swap","signature":"func (o ReplicaSetsBySizeNewer) Swap(i, j int) { o[i], o[j] = o[j], o[i] }","file":"pkg/controller/controller_utils.go","code":"func (o ReplicaSetsBySizeNewer) Swap(i, j int) { o[i], o[j] = o[j], o[i] }","line":{"from":1022,"to":1022}} {"id":100003425,"name":"Less","signature":"func (o ReplicaSetsBySizeNewer) Less(i, j int) bool","file":"pkg/controller/controller_utils.go","code":"func (o ReplicaSetsBySizeNewer) Less(i, j int) bool {\n\tif *(o[i].Spec.Replicas) == *(o[j].Spec.Replicas) {\n\t\treturn ReplicaSetsByCreationTimestamp(o).Less(j, i)\n\t}\n\treturn *(o[i].Spec.Replicas) \u003e *(o[j].Spec.Replicas)\n}","line":{"from":1023,"to":1028}} {"id":100003426,"name":"AddOrUpdateTaintOnNode","signature":"func AddOrUpdateTaintOnNode(ctx context.Context, c clientset.Interface, nodeName string, taints ...*v1.Taint) error","file":"pkg/controller/controller_utils.go","code":"// AddOrUpdateTaintOnNode add taints to the node. If taint was added into node, it'll issue API calls\n// to update nodes; otherwise, no API calls. Return error if any.\nfunc AddOrUpdateTaintOnNode(ctx context.Context, c clientset.Interface, nodeName string, taints ...*v1.Taint) error {\n\tif len(taints) == 0 {\n\t\treturn nil\n\t}\n\tfirstTry := true\n\treturn clientretry.RetryOnConflict(UpdateTaintBackoff, func() error {\n\t\tvar err error\n\t\tvar oldNode *v1.Node\n\t\t// First we try getting node from the API server cache, as it's cheaper. If it fails\n\t\t// we get it from etcd to be sure to have fresh data.\n\t\toption := metav1.GetOptions{}\n\t\tif firstTry {\n\t\t\toption.ResourceVersion = \"0\"\n\t\t\tfirstTry = false\n\t\t}\n\t\toldNode, err = c.CoreV1().Nodes().Get(ctx, nodeName, option)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar newNode *v1.Node\n\t\toldNodeCopy := oldNode\n\t\tupdated := false\n\t\tfor _, taint := range taints {\n\t\t\tcurNewNode, ok, err := taintutils.AddOrUpdateTaint(oldNodeCopy, taint)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to update taint of node\")\n\t\t\t}\n\t\t\tupdated = updated || ok\n\t\t\tnewNode = curNewNode\n\t\t\toldNodeCopy = curNewNode\n\t\t}\n\t\tif !updated {\n\t\t\treturn nil\n\t\t}\n\t\treturn PatchNodeTaints(ctx, c, nodeName, oldNode, newNode)\n\t})\n}","line":{"from":1030,"to":1069}} {"id":100003427,"name":"RemoveTaintOffNode","signature":"func RemoveTaintOffNode(ctx context.Context, c clientset.Interface, nodeName string, node *v1.Node, taints ...*v1.Taint) error","file":"pkg/controller/controller_utils.go","code":"// RemoveTaintOffNode is for cleaning up taints temporarily added to node,\n// won't fail if target taint doesn't exist or has been removed.\n// If passed a node it'll check if there's anything to be done, if taint is not present it won't issue\n// any API calls.\nfunc RemoveTaintOffNode(ctx context.Context, c clientset.Interface, nodeName string, node *v1.Node, taints ...*v1.Taint) error {\n\tif len(taints) == 0 {\n\t\treturn nil\n\t}\n\t// Short circuit for limiting amount of API calls.\n\tif node != nil {\n\t\tmatch := false\n\t\tfor _, taint := range taints {\n\t\t\tif taintutils.TaintExists(node.Spec.Taints, taint) {\n\t\t\t\tmatch = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !match {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tfirstTry := true\n\treturn clientretry.RetryOnConflict(UpdateTaintBackoff, func() error {\n\t\tvar err error\n\t\tvar oldNode *v1.Node\n\t\t// First we try getting node from the API server cache, as it's cheaper. If it fails\n\t\t// we get it from etcd to be sure to have fresh data.\n\t\toption := metav1.GetOptions{}\n\t\tif firstTry {\n\t\t\toption.ResourceVersion = \"0\"\n\t\t\tfirstTry = false\n\t\t}\n\t\toldNode, err = c.CoreV1().Nodes().Get(ctx, nodeName, option)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar newNode *v1.Node\n\t\toldNodeCopy := oldNode\n\t\tupdated := false\n\t\tfor _, taint := range taints {\n\t\t\tcurNewNode, ok, err := taintutils.RemoveTaint(oldNodeCopy, taint)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to remove taint of node\")\n\t\t\t}\n\t\t\tupdated = updated || ok\n\t\t\tnewNode = curNewNode\n\t\t\toldNodeCopy = curNewNode\n\t\t}\n\t\tif !updated {\n\t\t\treturn nil\n\t\t}\n\t\treturn PatchNodeTaints(ctx, c, nodeName, oldNode, newNode)\n\t})\n}","line":{"from":1071,"to":1126}} {"id":100003428,"name":"PatchNodeTaints","signature":"func PatchNodeTaints(ctx context.Context, c clientset.Interface, nodeName string, oldNode *v1.Node, newNode *v1.Node) error","file":"pkg/controller/controller_utils.go","code":"// PatchNodeTaints patches node's taints.\nfunc PatchNodeTaints(ctx context.Context, c clientset.Interface, nodeName string, oldNode *v1.Node, newNode *v1.Node) error {\n\t// Strip base diff node from RV to ensure that our Patch request will set RV to check for conflicts over .spec.taints.\n\t// This is needed because .spec.taints does not specify patchMergeKey and patchStrategy and adding them is no longer an option for compatibility reasons.\n\t// Using other Patch strategy works for adding new taints, however will not resolve problem with taint removal.\n\toldNodeNoRV := oldNode.DeepCopy()\n\toldNodeNoRV.ResourceVersion = \"\"\n\toldDataNoRV, err := json.Marshal(\u0026oldNodeNoRV)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal old node %#v for node %q: %v\", oldNodeNoRV, nodeName, err)\n\t}\n\n\tnewTaints := newNode.Spec.Taints\n\tnewNodeClone := oldNode.DeepCopy()\n\tnewNodeClone.Spec.Taints = newTaints\n\tnewData, err := json.Marshal(newNodeClone)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal new node %#v for node %q: %v\", newNodeClone, nodeName, err)\n\t}\n\n\tpatchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldDataNoRV, newData, v1.Node{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create patch for node %q: %v\", nodeName, err)\n\t}\n\n\t_, err = c.CoreV1().Nodes().Patch(ctx, nodeName, types.StrategicMergePatchType, patchBytes, metav1.PatchOptions{})\n\treturn err\n}","line":{"from":1128,"to":1155}} {"id":100003429,"name":"ComputeHash","signature":"func ComputeHash(template *v1.PodTemplateSpec, collisionCount *int32) string","file":"pkg/controller/controller_utils.go","code":"// ComputeHash returns a hash value calculated from pod template and\n// a collisionCount to avoid hash collision. The hash will be safe encoded to\n// avoid bad words.\nfunc ComputeHash(template *v1.PodTemplateSpec, collisionCount *int32) string {\n\tpodTemplateSpecHasher := fnv.New32a()\n\thashutil.DeepHashObject(podTemplateSpecHasher, *template)\n\n\t// Add collisionCount in the hash if it exists.\n\tif collisionCount != nil {\n\t\tcollisionCountBytes := make([]byte, 8)\n\t\tbinary.LittleEndian.PutUint32(collisionCountBytes, uint32(*collisionCount))\n\t\tpodTemplateSpecHasher.Write(collisionCountBytes)\n\t}\n\n\treturn rand.SafeEncodeString(fmt.Sprint(podTemplateSpecHasher.Sum32()))\n}","line":{"from":1157,"to":1172}} {"id":100003430,"name":"AddOrUpdateLabelsOnNode","signature":"func AddOrUpdateLabelsOnNode(kubeClient clientset.Interface, nodeName string, labelsToUpdate map[string]string) error","file":"pkg/controller/controller_utils.go","code":"func AddOrUpdateLabelsOnNode(kubeClient clientset.Interface, nodeName string, labelsToUpdate map[string]string) error {\n\tfirstTry := true\n\treturn clientretry.RetryOnConflict(UpdateLabelBackoff, func() error {\n\t\tvar err error\n\t\tvar node *v1.Node\n\t\t// First we try getting node from the API server cache, as it's cheaper. If it fails\n\t\t// we get it from etcd to be sure to have fresh data.\n\t\toption := metav1.GetOptions{}\n\t\tif firstTry {\n\t\t\toption.ResourceVersion = \"0\"\n\t\t\tfirstTry = false\n\t\t}\n\t\tnode, err = kubeClient.CoreV1().Nodes().Get(context.TODO(), nodeName, option)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Make a copy of the node and update the labels.\n\t\tnewNode := node.DeepCopy()\n\t\tif newNode.Labels == nil {\n\t\t\tnewNode.Labels = make(map[string]string)\n\t\t}\n\t\tfor key, value := range labelsToUpdate {\n\t\t\tnewNode.Labels[key] = value\n\t\t}\n\n\t\toldData, err := json.Marshal(node)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to marshal the existing node %#v: %v\", node, err)\n\t\t}\n\t\tnewData, err := json.Marshal(newNode)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to marshal the new node %#v: %v\", newNode, err)\n\t\t}\n\t\tpatchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, \u0026v1.Node{})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create a two-way merge patch: %v\", err)\n\t\t}\n\t\tif _, err := kubeClient.CoreV1().Nodes().Patch(context.TODO(), node.Name, types.StrategicMergePatchType, patchBytes, metav1.PatchOptions{}); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to patch the node: %v\", err)\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":1174,"to":1217}} {"id":100003431,"name":"Convert_v1alpha1_CronJobControllerConfiguration_To_config_CronJobControllerConfiguration","signature":"func Convert_v1alpha1_CronJobControllerConfiguration_To_config_CronJobControllerConfiguration(in *v1alpha1.CronJobControllerConfiguration, out *config.CronJobControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/cronjob/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_CronJobControllerConfiguration_To_config_CronJobControllerConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_CronJobControllerConfiguration_To_config_CronJobControllerConfiguration(in *v1alpha1.CronJobControllerConfiguration, out *config.CronJobControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_CronJobControllerConfiguration_To_config_CronJobControllerConfiguration(in, out, s)\n}","line":{"from":32,"to":35}} {"id":100003432,"name":"Convert_config_CronJobControllerConfiguration_To_v1alpha1_CronJobControllerConfiguration","signature":"func Convert_config_CronJobControllerConfiguration_To_v1alpha1_CronJobControllerConfiguration(in *config.CronJobControllerConfiguration, out *v1alpha1.CronJobControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/cronjob/config/v1alpha1/conversion.go","code":"// Convert_config_CronJobControllerConfiguration_To_v1alpha1_CronJobControllerConfiguration is an autogenerated conversion function.\nfunc Convert_config_CronJobControllerConfiguration_To_v1alpha1_CronJobControllerConfiguration(in *config.CronJobControllerConfiguration, out *v1alpha1.CronJobControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_CronJobControllerConfiguration_To_v1alpha1_CronJobControllerConfiguration(in, out, s)\n}","line":{"from":37,"to":40}} {"id":100003433,"name":"RecommendedDefaultCronJobControllerConfiguration","signature":"func RecommendedDefaultCronJobControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.CronJobControllerConfiguration)","file":"pkg/controller/cronjob/config/v1alpha1/defaults.go","code":"// RecommendedDefaultCronJobControllerConfiguration defaults a pointer to a\n// CronJobControllerConfiguration struct. This will set the recommended default\n// values, but they may be subject to change between API versions. This function\n// is intentionally not registered in the scheme as a \"normal\" `SetDefaults_Foo`\n// function to allow consumers of this type to set whatever defaults for their\n// embedded configs. Forcing consumers to use these defaults would be problematic\n// as defaulting in the scheme is done as part of the conversion, and there would\n// be no easy way to opt-out. Instead, if you want to use this defaulting method\n// run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDefaultCronJobControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.CronJobControllerConfiguration) {\n\tif obj.ConcurrentCronJobSyncs == 0 {\n\t\tobj.ConcurrentCronJobSyncs = 5\n\t}\n}","line":{"from":23,"to":36}} {"id":100003434,"name":"NewControllerV2","signature":"func NewControllerV2(ctx context.Context, jobInformer batchv1informers.JobInformer, cronJobsInformer batchv1informers.CronJobInformer, kubeClient clientset.Interface) (*ControllerV2, error)","file":"pkg/controller/cronjob/cronjob_controllerv2.go","code":"// NewControllerV2 creates and initializes a new Controller.\nfunc NewControllerV2(ctx context.Context, jobInformer batchv1informers.JobInformer, cronJobsInformer batchv1informers.CronJobInformer, kubeClient clientset.Interface) (*ControllerV2, error) {\n\tlogger := klog.FromContext(ctx)\n\teventBroadcaster := record.NewBroadcaster()\n\n\tjm := \u0026ControllerV2{\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"cronjob\"),\n\t\tkubeClient: kubeClient,\n\t\tbroadcaster: eventBroadcaster,\n\t\trecorder: eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: \"cronjob-controller\"}),\n\n\t\tjobControl: realJobControl{KubeClient: kubeClient},\n\t\tcronJobControl: \u0026realCJControl{KubeClient: kubeClient},\n\n\t\tjobLister: jobInformer.Lister(),\n\t\tcronJobLister: cronJobsInformer.Lister(),\n\n\t\tjobListerSynced: jobInformer.Informer().HasSynced,\n\t\tcronJobListerSynced: cronJobsInformer.Informer().HasSynced,\n\t\tnow: time.Now,\n\t}\n\n\tjobInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: jm.addJob,\n\t\tUpdateFunc: jm.updateJob,\n\t\tDeleteFunc: jm.deleteJob,\n\t})\n\n\tcronJobsInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tjm.enqueueController(obj)\n\t\t},\n\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\tjm.updateCronJob(logger, oldObj, newObj)\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tjm.enqueueController(obj)\n\t\t},\n\t})\n\n\tmetrics.Register()\n\n\treturn jm, nil\n}","line":{"from":82,"to":125}} {"id":100003435,"name":"Run","signature":"func (jm *ControllerV2) Run(ctx context.Context, workers int)","file":"pkg/controller/cronjob/cronjob_controllerv2.go","code":"// Run starts the main goroutine responsible for watching and syncing jobs.\nfunc (jm *ControllerV2) Run(ctx context.Context, workers int) {\n\tdefer utilruntime.HandleCrash()\n\n\t// Start event processing pipeline.\n\tjm.broadcaster.StartStructuredLogging(0)\n\tjm.broadcaster.StartRecordingToSink(\u0026covev1client.EventSinkImpl{Interface: jm.kubeClient.CoreV1().Events(\"\")})\n\tdefer jm.broadcaster.Shutdown()\n\n\tdefer jm.queue.ShutDown()\n\n\tlogger := klog.FromContext(ctx)\n\tlogger.Info(\"Starting cronjob controller v2\")\n\tdefer logger.Info(\"Shutting down cronjob controller v2\")\n\n\tif !cache.WaitForNamedCacheSync(\"cronjob\", ctx.Done(), jm.jobListerSynced, jm.cronJobListerSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.UntilWithContext(ctx, jm.worker, time.Second)\n\t}\n\n\t\u003c-ctx.Done()\n}","line":{"from":127,"to":151}} {"id":100003436,"name":"worker","signature":"func (jm *ControllerV2) worker(ctx context.Context)","file":"pkg/controller/cronjob/cronjob_controllerv2.go","code":"func (jm *ControllerV2) worker(ctx context.Context) {\n\tfor jm.processNextWorkItem(ctx) {\n\t}\n}","line":{"from":153,"to":156}} {"id":100003437,"name":"processNextWorkItem","signature":"func (jm *ControllerV2) processNextWorkItem(ctx context.Context) bool","file":"pkg/controller/cronjob/cronjob_controllerv2.go","code":"func (jm *ControllerV2) processNextWorkItem(ctx context.Context) bool {\n\tkey, quit := jm.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer jm.queue.Done(key)\n\n\trequeueAfter, err := jm.sync(ctx, key.(string))\n\tswitch {\n\tcase err != nil:\n\t\tutilruntime.HandleError(fmt.Errorf(\"error syncing CronJobController %v, requeuing: %v\", key.(string), err))\n\t\tjm.queue.AddRateLimited(key)\n\tcase requeueAfter != nil:\n\t\tjm.queue.Forget(key)\n\t\tjm.queue.AddAfter(key, *requeueAfter)\n\t}\n\treturn true\n}","line":{"from":158,"to":175}} {"id":100003438,"name":"sync","signature":"func (jm *ControllerV2) sync(ctx context.Context, cronJobKey string) (*time.Duration, error)","file":"pkg/controller/cronjob/cronjob_controllerv2.go","code":"func (jm *ControllerV2) sync(ctx context.Context, cronJobKey string) (*time.Duration, error) {\n\tns, name, err := cache.SplitMetaNamespaceKey(cronJobKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlogger := klog.FromContext(ctx)\n\tcronJob, err := jm.cronJobLister.CronJobs(ns).Get(name)\n\tswitch {\n\tcase errors.IsNotFound(err):\n\t\t// may be cronjob is deleted, don't need to requeue this key\n\t\tlogger.V(4).Info(\"CronJob not found, may be it is deleted\", \"cronjob\", klog.KObj(cronJob), \"err\", err)\n\t\treturn nil, nil\n\tcase err != nil:\n\t\t// for other transient apiserver error requeue with exponential backoff\n\t\treturn nil, err\n\t}\n\n\tjobsToBeReconciled, err := jm.getJobsToBeReconciled(cronJob)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcronJobCopy, requeueAfter, updateStatus, err := jm.syncCronJob(ctx, cronJob, jobsToBeReconciled)\n\tif err != nil {\n\t\tlogger.V(2).Info(\"Error reconciling cronjob\", \"cronjob\", klog.KObj(cronJob), \"err\", err)\n\t\tif updateStatus {\n\t\t\tif _, err := jm.cronJobControl.UpdateStatus(ctx, cronJobCopy); err != nil {\n\t\t\t\tlogger.V(2).Info(\"Unable to update status for cronjob\", \"cronjob\", klog.KObj(cronJob), \"resourceVersion\", cronJob.ResourceVersion, \"err\", err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tif jm.cleanupFinishedJobs(ctx, cronJobCopy, jobsToBeReconciled) {\n\t\tupdateStatus = true\n\t}\n\n\t// Update the CronJob if needed\n\tif updateStatus {\n\t\tif _, err := jm.cronJobControl.UpdateStatus(ctx, cronJobCopy); err != nil {\n\t\t\tlogger.V(2).Info(\"Unable to update status for cronjob\", \"cronjob\", klog.KObj(cronJob), \"resourceVersion\", cronJob.ResourceVersion, \"err\", err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif requeueAfter != nil {\n\t\tlogger.V(4).Info(\"Re-queuing cronjob\", \"cronjob\", klog.KObj(cronJob), \"requeueAfter\", requeueAfter)\n\t\treturn requeueAfter, nil\n\t}\n\t// this marks the key done, currently only happens when the cronjob is suspended or spec has invalid schedule format\n\treturn nil, nil\n}","line":{"from":177,"to":229}} {"id":100003439,"name":"resolveControllerRef","signature":"func (jm *ControllerV2) resolveControllerRef(namespace string, controllerRef *metav1.OwnerReference) *batchv1.CronJob","file":"pkg/controller/cronjob/cronjob_controllerv2.go","code":"// resolveControllerRef returns the controller referenced by a ControllerRef,\n// or nil if the ControllerRef could not be resolved to a matching controller\n// of the correct Kind.\nfunc (jm *ControllerV2) resolveControllerRef(namespace string, controllerRef *metav1.OwnerReference) *batchv1.CronJob {\n\t// We can't look up by UID, so look up by Name and then verify UID.\n\t// Don't even try to look up by Name if it's the wrong Kind.\n\tif controllerRef.Kind != controllerKind.Kind {\n\t\treturn nil\n\t}\n\tcronJob, err := jm.cronJobLister.CronJobs(namespace).Get(controllerRef.Name)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tif cronJob.UID != controllerRef.UID {\n\t\t// The controller we found with this Name is not the same one that the\n\t\t// ControllerRef points to.\n\t\treturn nil\n\t}\n\treturn cronJob\n}","line":{"from":231,"to":250}} {"id":100003440,"name":"getJobsToBeReconciled","signature":"func (jm *ControllerV2) getJobsToBeReconciled(cronJob *batchv1.CronJob) ([]*batchv1.Job, error)","file":"pkg/controller/cronjob/cronjob_controllerv2.go","code":"func (jm *ControllerV2) getJobsToBeReconciled(cronJob *batchv1.CronJob) ([]*batchv1.Job, error) {\n\t// list all jobs: there may be jobs with labels that don't match the template anymore,\n\t// but that still have a ControllerRef to the given cronjob\n\tjobList, err := jm.jobLister.Jobs(cronJob.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tjobsToBeReconciled := []*batchv1.Job{}\n\n\tfor _, job := range jobList {\n\t\t// If it has a ControllerRef, that's all that matters.\n\t\tif controllerRef := metav1.GetControllerOf(job); controllerRef != nil \u0026\u0026 controllerRef.Name == cronJob.Name {\n\t\t\t// this job is needs to be reconciled\n\t\t\tjobsToBeReconciled = append(jobsToBeReconciled, job)\n\t\t}\n\t}\n\treturn jobsToBeReconciled, nil\n}","line":{"from":252,"to":270}} {"id":100003441,"name":"addJob","signature":"func (jm *ControllerV2) addJob(obj interface{})","file":"pkg/controller/cronjob/cronjob_controllerv2.go","code":"// When a job is created, enqueue the controller that manages it and update it's expectations.\nfunc (jm *ControllerV2) addJob(obj interface{}) {\n\tjob := obj.(*batchv1.Job)\n\tif job.DeletionTimestamp != nil {\n\t\t// on a restart of the controller, it's possible a new job shows up in a state that\n\t\t// is already pending deletion. Prevent the job from being a creation observation.\n\t\tjm.deleteJob(job)\n\t\treturn\n\t}\n\n\t// If it has a ControllerRef, that's all that matters.\n\tif controllerRef := metav1.GetControllerOf(job); controllerRef != nil {\n\t\tcronJob := jm.resolveControllerRef(job.Namespace, controllerRef)\n\t\tif cronJob == nil {\n\t\t\treturn\n\t\t}\n\t\tjm.enqueueController(cronJob)\n\t\treturn\n\t}\n}","line":{"from":272,"to":291}} {"id":100003442,"name":"updateJob","signature":"func (jm *ControllerV2) updateJob(old, cur interface{})","file":"pkg/controller/cronjob/cronjob_controllerv2.go","code":"// updateJob figures out what CronJob(s) manage a Job when the Job\n// is updated and wake them up. If the anything of the Job have changed, we need to\n// awaken both the old and new CronJob. old and cur must be *batchv1.Job\n// types.\nfunc (jm *ControllerV2) updateJob(old, cur interface{}) {\n\tcurJob := cur.(*batchv1.Job)\n\toldJob := old.(*batchv1.Job)\n\tif curJob.ResourceVersion == oldJob.ResourceVersion {\n\t\t// Periodic resync will send update events for all known jobs.\n\t\t// Two different versions of the same jobs will always have different RVs.\n\t\treturn\n\t}\n\n\tcurControllerRef := metav1.GetControllerOf(curJob)\n\toldControllerRef := metav1.GetControllerOf(oldJob)\n\tcontrollerRefChanged := !reflect.DeepEqual(curControllerRef, oldControllerRef)\n\tif controllerRefChanged \u0026\u0026 oldControllerRef != nil {\n\t\t// The ControllerRef was changed. Sync the old controller, if any.\n\t\tif cronJob := jm.resolveControllerRef(oldJob.Namespace, oldControllerRef); cronJob != nil {\n\t\t\tjm.enqueueController(cronJob)\n\t\t}\n\t}\n\n\t// If it has a ControllerRef, that's all that matters.\n\tif curControllerRef != nil {\n\t\tcronJob := jm.resolveControllerRef(curJob.Namespace, curControllerRef)\n\t\tif cronJob == nil {\n\t\t\treturn\n\t\t}\n\t\tjm.enqueueController(cronJob)\n\t\treturn\n\t}\n}","line":{"from":293,"to":325}} {"id":100003443,"name":"deleteJob","signature":"func (jm *ControllerV2) deleteJob(obj interface{})","file":"pkg/controller/cronjob/cronjob_controllerv2.go","code":"func (jm *ControllerV2) deleteJob(obj interface{}) {\n\tjob, ok := obj.(*batchv1.Job)\n\n\t// When a delete is dropped, the relist will notice a job in the store not\n\t// in the list, leading to the insertion of a tombstone object which contains\n\t// the deleted key/value. Note that this value might be stale.\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get object from tombstone %#v\", obj))\n\t\t\treturn\n\t\t}\n\t\tjob, ok = tombstone.Obj.(*batchv1.Job)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"tombstone contained object that is not a Job %#v\", obj))\n\t\t\treturn\n\t\t}\n\t}\n\n\tcontrollerRef := metav1.GetControllerOf(job)\n\tif controllerRef == nil {\n\t\t// No controller should care about orphans being deleted.\n\t\treturn\n\t}\n\tcronJob := jm.resolveControllerRef(job.Namespace, controllerRef)\n\tif cronJob == nil {\n\t\treturn\n\t}\n\tjm.enqueueController(cronJob)\n}","line":{"from":327,"to":356}} {"id":100003444,"name":"enqueueController","signature":"func (jm *ControllerV2) enqueueController(obj interface{})","file":"pkg/controller/cronjob/cronjob_controllerv2.go","code":"func (jm *ControllerV2) enqueueController(obj interface{}) {\n\tkey, err := controller.KeyFunc(obj)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get key for object %+v: %v\", obj, err))\n\t\treturn\n\t}\n\n\tjm.queue.Add(key)\n}","line":{"from":358,"to":366}} {"id":100003445,"name":"enqueueControllerAfter","signature":"func (jm *ControllerV2) enqueueControllerAfter(obj interface{}, t time.Duration)","file":"pkg/controller/cronjob/cronjob_controllerv2.go","code":"func (jm *ControllerV2) enqueueControllerAfter(obj interface{}, t time.Duration) {\n\tkey, err := controller.KeyFunc(obj)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get key for object %+v: %v\", obj, err))\n\t\treturn\n\t}\n\n\tjm.queue.AddAfter(key, t)\n}","line":{"from":368,"to":376}} {"id":100003446,"name":"updateCronJob","signature":"func (jm *ControllerV2) updateCronJob(logger klog.Logger, old interface{}, curr interface{})","file":"pkg/controller/cronjob/cronjob_controllerv2.go","code":"// updateCronJob re-queues the CronJob for next scheduled time if there is a\n// change in spec.schedule otherwise it re-queues it now\nfunc (jm *ControllerV2) updateCronJob(logger klog.Logger, old interface{}, curr interface{}) {\n\toldCJ, okOld := old.(*batchv1.CronJob)\n\tnewCJ, okNew := curr.(*batchv1.CronJob)\n\n\tif !okOld || !okNew {\n\t\t// typecasting of one failed, handle this better, may be log entry\n\t\treturn\n\t}\n\t// if the change in schedule results in next requeue having to be sooner than it already was,\n\t// it will be handled here by the queue. If the next requeue is further than previous schedule,\n\t// the sync loop will essentially be a no-op for the already queued key with old schedule.\n\tif oldCJ.Spec.Schedule != newCJ.Spec.Schedule || !pointer.StringEqual(oldCJ.Spec.TimeZone, newCJ.Spec.TimeZone) {\n\t\t// schedule changed, change the requeue time, pass nil recorder so that syncCronJob will output any warnings\n\t\tsched, err := cron.ParseStandard(formatSchedule(newCJ, nil))\n\t\tif err != nil {\n\t\t\t// this is likely a user error in defining the spec value\n\t\t\t// we should log the error and not reconcile this cronjob until an update to spec\n\t\t\tlogger.V(2).Info(\"Unparseable schedule for cronjob\", \"cronjob\", klog.KObj(newCJ), \"schedule\", newCJ.Spec.Schedule, \"err\", err)\n\t\t\tjm.recorder.Eventf(newCJ, corev1.EventTypeWarning, \"UnParseableCronJobSchedule\", \"unparseable schedule for cronjob: %s\", newCJ.Spec.Schedule)\n\t\t\treturn\n\t\t}\n\t\tnow := jm.now()\n\t\tt := nextScheduleTimeDuration(newCJ, now, sched)\n\n\t\tjm.enqueueControllerAfter(curr, *t)\n\t\treturn\n\t}\n\n\t// other parameters changed, requeue this now and if this gets triggered\n\t// within deadline, sync loop will work on the CJ otherwise updates will be handled\n\t// during the next schedule\n\t// TODO: need to handle the change of spec.JobTemplate.metadata.labels explicitly\n\t// to cleanup jobs with old labels\n\tjm.enqueueController(curr)\n}","line":{"from":378,"to":414}} {"id":100003447,"name":"syncCronJob","signature":"func (jm *ControllerV2) syncCronJob(","file":"pkg/controller/cronjob/cronjob_controllerv2.go","code":"// syncCronJob reconciles a CronJob with a list of any Jobs that it created.\n// All known jobs created by \"cronJob\" should be included in \"jobs\".\n// The current time is passed in to facilitate testing.\n// It returns a copy of the CronJob that is to be used by other functions\n// that mutates the object\n// It also returns a bool to indicate an update to api-server is needed\nfunc (jm *ControllerV2) syncCronJob(\n\tctx context.Context,\n\tcronJob *batchv1.CronJob,\n\tjobs []*batchv1.Job) (*batchv1.CronJob, *time.Duration, bool, error) {\n\n\tcronJob = cronJob.DeepCopy()\n\tnow := jm.now()\n\tupdateStatus := false\n\n\tchildrenJobs := make(map[types.UID]bool)\n\tfor _, j := range jobs {\n\t\tchildrenJobs[j.ObjectMeta.UID] = true\n\t\tfound := inActiveList(cronJob, j.ObjectMeta.UID)\n\t\tif !found \u0026\u0026 !IsJobFinished(j) {\n\t\t\tcjCopy, err := jm.cronJobControl.GetCronJob(ctx, cronJob.Namespace, cronJob.Name)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, updateStatus, err\n\t\t\t}\n\t\t\tif inActiveList(cjCopy, j.ObjectMeta.UID) {\n\t\t\t\tcronJob = cjCopy\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tjm.recorder.Eventf(cronJob, corev1.EventTypeWarning, \"UnexpectedJob\", \"Saw a job that the controller did not create or forgot: %s\", j.Name)\n\t\t\t// We found an unfinished job that has us as the parent, but it is not in our Active list.\n\t\t\t// This could happen if we crashed right after creating the Job and before updating the status,\n\t\t\t// or if our jobs list is newer than our cj status after a relist, or if someone intentionally created\n\t\t\t// a job that they wanted us to adopt.\n\t\t} else if found \u0026\u0026 IsJobFinished(j) {\n\t\t\t_, status := getFinishedStatus(j)\n\t\t\tdeleteFromActiveList(cronJob, j.ObjectMeta.UID)\n\t\t\tjm.recorder.Eventf(cronJob, corev1.EventTypeNormal, \"SawCompletedJob\", \"Saw completed job: %s, status: %v\", j.Name, status)\n\t\t\tupdateStatus = true\n\t\t} else if IsJobFinished(j) {\n\t\t\t// a job does not have to be in active list, as long as it is finished, we will process the timestamp\n\t\t\tif cronJob.Status.LastSuccessfulTime == nil {\n\t\t\t\tcronJob.Status.LastSuccessfulTime = j.Status.CompletionTime\n\t\t\t\tupdateStatus = true\n\t\t\t}\n\t\t\tif j.Status.CompletionTime != nil \u0026\u0026 j.Status.CompletionTime.After(cronJob.Status.LastSuccessfulTime.Time) {\n\t\t\t\tcronJob.Status.LastSuccessfulTime = j.Status.CompletionTime\n\t\t\t\tupdateStatus = true\n\t\t\t}\n\t\t}\n\t}\n\n\t// Remove any job reference from the active list if the corresponding job does not exist any more.\n\t// Otherwise, the cronjob may be stuck in active mode forever even though there is no matching\n\t// job running.\n\tfor _, j := range cronJob.Status.Active {\n\t\t_, found := childrenJobs[j.UID]\n\t\tif found {\n\t\t\tcontinue\n\t\t}\n\t\t// Explicitly try to get the job from api-server to avoid a slow watch not able to update\n\t\t// the job lister on time, giving an unwanted miss\n\t\t_, err := jm.jobControl.GetJob(j.Namespace, j.Name)\n\t\tswitch {\n\t\tcase errors.IsNotFound(err):\n\t\t\t// The job is actually missing, delete from active list and schedule a new one if within\n\t\t\t// deadline\n\t\t\tjm.recorder.Eventf(cronJob, corev1.EventTypeNormal, \"MissingJob\", \"Active job went missing: %v\", j.Name)\n\t\t\tdeleteFromActiveList(cronJob, j.UID)\n\t\t\tupdateStatus = true\n\t\tcase err != nil:\n\t\t\treturn cronJob, nil, updateStatus, err\n\t\t}\n\t\t// the job is missing in the lister but found in api-server\n\t}\n\n\tif cronJob.DeletionTimestamp != nil {\n\t\t// The CronJob is being deleted.\n\t\t// Don't do anything other than updating status.\n\t\treturn cronJob, nil, updateStatus, nil\n\t}\n\n\tlogger := klog.FromContext(ctx)\n\tif cronJob.Spec.TimeZone != nil {\n\t\ttimeZone := pointer.StringDeref(cronJob.Spec.TimeZone, \"\")\n\t\tif _, err := time.LoadLocation(timeZone); err != nil {\n\t\t\tlogger.V(4).Info(\"Not starting job because timeZone is invalid\", \"cronjob\", klog.KObj(cronJob), \"timeZone\", timeZone, \"err\", err)\n\t\t\tjm.recorder.Eventf(cronJob, corev1.EventTypeWarning, \"UnknownTimeZone\", \"invalid timeZone: %q: %s\", timeZone, err)\n\t\t\treturn cronJob, nil, updateStatus, nil\n\t\t}\n\t}\n\n\tif cronJob.Spec.Suspend != nil \u0026\u0026 *cronJob.Spec.Suspend {\n\t\tlogger.V(4).Info(\"Not starting job because the cron is suspended\", \"cronjob\", klog.KObj(cronJob))\n\t\treturn cronJob, nil, updateStatus, nil\n\t}\n\n\tsched, err := cron.ParseStandard(formatSchedule(cronJob, jm.recorder))\n\tif err != nil {\n\t\t// this is likely a user error in defining the spec value\n\t\t// we should log the error and not reconcile this cronjob until an update to spec\n\t\tlogger.V(2).Info(\"Unparseable schedule\", \"cronjob\", klog.KObj(cronJob), \"schedule\", cronJob.Spec.Schedule, \"err\", err)\n\t\tjm.recorder.Eventf(cronJob, corev1.EventTypeWarning, \"UnparseableSchedule\", \"unparseable schedule: %q : %s\", cronJob.Spec.Schedule, err)\n\t\treturn cronJob, nil, updateStatus, nil\n\t}\n\n\tscheduledTime, err := nextScheduleTime(logger, cronJob, now, sched, jm.recorder)\n\tif err != nil {\n\t\t// this is likely a user error in defining the spec value\n\t\t// we should log the error and not reconcile this cronjob until an update to spec\n\t\tlogger.V(2).Info(\"Invalid schedule\", \"cronjob\", klog.KObj(cronJob), \"schedule\", cronJob.Spec.Schedule, \"err\", err)\n\t\tjm.recorder.Eventf(cronJob, corev1.EventTypeWarning, \"InvalidSchedule\", \"invalid schedule: %s : %s\", cronJob.Spec.Schedule, err)\n\t\treturn cronJob, nil, updateStatus, nil\n\t}\n\tif scheduledTime == nil {\n\t\t// no unmet start time, return cj,.\n\t\t// The only time this should happen is if queue is filled after restart.\n\t\t// Otherwise, the queue is always suppose to trigger sync function at the time of\n\t\t// the scheduled time, that will give atleast 1 unmet time schedule\n\t\tlogger.V(4).Info(\"No unmet start times\", \"cronjob\", klog.KObj(cronJob))\n\t\tt := nextScheduleTimeDuration(cronJob, now, sched)\n\t\treturn cronJob, t, updateStatus, nil\n\t}\n\n\ttooLate := false\n\tif cronJob.Spec.StartingDeadlineSeconds != nil {\n\t\ttooLate = scheduledTime.Add(time.Second * time.Duration(*cronJob.Spec.StartingDeadlineSeconds)).Before(now)\n\t}\n\tif tooLate {\n\t\tlogger.V(4).Info(\"Missed starting window\", \"cronjob\", klog.KObj(cronJob))\n\t\tjm.recorder.Eventf(cronJob, corev1.EventTypeWarning, \"MissSchedule\", \"Missed scheduled time to start a job: %s\", scheduledTime.UTC().Format(time.RFC1123Z))\n\n\t\t// TODO: Since we don't set LastScheduleTime when not scheduling, we are going to keep noticing\n\t\t// the miss every cycle. In order to avoid sending multiple events, and to avoid processing\n\t\t// the cj again and again, we could set a Status.LastMissedTime when we notice a miss.\n\t\t// Then, when we call getRecentUnmetScheduleTimes, we can take max(creationTimestamp,\n\t\t// Status.LastScheduleTime, Status.LastMissedTime), and then so we won't generate\n\t\t// and event the next time we process it, and also so the user looking at the status\n\t\t// can see easily that there was a missed execution.\n\t\tt := nextScheduleTimeDuration(cronJob, now, sched)\n\t\treturn cronJob, t, updateStatus, nil\n\t}\n\tif inActiveListByName(cronJob, \u0026batchv1.Job{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: getJobName(cronJob, *scheduledTime),\n\t\t\tNamespace: cronJob.Namespace,\n\t\t}}) || cronJob.Status.LastScheduleTime.Equal(\u0026metav1.Time{Time: *scheduledTime}) {\n\t\tlogger.V(4).Info(\"Not starting job because the scheduled time is already processed\", \"cronjob\", klog.KObj(cronJob), \"schedule\", scheduledTime)\n\t\tt := nextScheduleTimeDuration(cronJob, now, sched)\n\t\treturn cronJob, t, updateStatus, nil\n\t}\n\tif cronJob.Spec.ConcurrencyPolicy == batchv1.ForbidConcurrent \u0026\u0026 len(cronJob.Status.Active) \u003e 0 {\n\t\t// Regardless which source of information we use for the set of active jobs,\n\t\t// there is some risk that we won't see an active job when there is one.\n\t\t// (because we haven't seen the status update to the SJ or the created pod).\n\t\t// So it is theoretically possible to have concurrency with Forbid.\n\t\t// As long the as the invocations are \"far enough apart in time\", this usually won't happen.\n\t\t//\n\t\t// TODO: for Forbid, we could use the same name for every execution, as a lock.\n\t\t// With replace, we could use a name that is deterministic per execution time.\n\t\t// But that would mean that you could not inspect prior successes or failures of Forbid jobs.\n\t\tlogger.V(4).Info(\"Not starting job because prior execution is still running and concurrency policy is Forbid\", \"cronjob\", klog.KObj(cronJob))\n\t\tjm.recorder.Eventf(cronJob, corev1.EventTypeNormal, \"JobAlreadyActive\", \"Not starting job because prior execution is running and concurrency policy is Forbid\")\n\t\tt := nextScheduleTimeDuration(cronJob, now, sched)\n\t\treturn cronJob, t, updateStatus, nil\n\t}\n\tif cronJob.Spec.ConcurrencyPolicy == batchv1.ReplaceConcurrent {\n\t\tfor _, j := range cronJob.Status.Active {\n\t\t\tlogger.V(4).Info(\"Deleting job that was still running at next scheduled start time\", \"job\", klog.KRef(j.Namespace, j.Name))\n\t\t\tjob, err := jm.jobControl.GetJob(j.Namespace, j.Name)\n\t\t\tif err != nil {\n\t\t\t\tjm.recorder.Eventf(cronJob, corev1.EventTypeWarning, \"FailedGet\", \"Get job: %v\", err)\n\t\t\t\treturn cronJob, nil, updateStatus, err\n\t\t\t}\n\t\t\tif !deleteJob(logger, cronJob, job, jm.jobControl, jm.recorder) {\n\t\t\t\treturn cronJob, nil, updateStatus, fmt.Errorf(\"could not replace job %s/%s\", job.Namespace, job.Name)\n\t\t\t}\n\t\t\tupdateStatus = true\n\t\t}\n\t}\n\n\tjobReq, err := getJobFromTemplate2(cronJob, *scheduledTime)\n\tif err != nil {\n\t\tlogger.Error(err, \"Unable to make Job from template\", \"cronjob\", klog.KObj(cronJob))\n\t\treturn cronJob, nil, updateStatus, err\n\t}\n\tjobResp, err := jm.jobControl.CreateJob(cronJob.Namespace, jobReq)\n\tswitch {\n\tcase errors.HasStatusCause(err, corev1.NamespaceTerminatingCause):\n\tcase errors.IsAlreadyExists(err):\n\t\t// If the job is created by other actor, assume it has updated the cronjob status accordingly\n\t\tlogger.Info(\"Job already exists\", \"cronjob\", klog.KObj(cronJob), \"job\", klog.KObj(jobReq))\n\t\treturn cronJob, nil, updateStatus, err\n\tcase err != nil:\n\t\t// default error handling\n\t\tjm.recorder.Eventf(cronJob, corev1.EventTypeWarning, \"FailedCreate\", \"Error creating job: %v\", err)\n\t\treturn cronJob, nil, updateStatus, err\n\t}\n\n\tmetrics.CronJobCreationSkew.Observe(jobResp.ObjectMeta.GetCreationTimestamp().Sub(*scheduledTime).Seconds())\n\tlogger.V(4).Info(\"Created Job\", \"job\", klog.KObj(jobResp), \"cronjob\", klog.KObj(cronJob))\n\tjm.recorder.Eventf(cronJob, corev1.EventTypeNormal, \"SuccessfulCreate\", \"Created job %v\", jobResp.Name)\n\n\t// ------------------------------------------------------------------ //\n\n\t// If this process restarts at this point (after posting a job, but\n\t// before updating the status), then we might try to start the job on\n\t// the next time. Actually, if we re-list the SJs and Jobs on the next\n\t// iteration of syncAll, we might not see our own status update, and\n\t// then post one again. So, we need to use the job name as a lock to\n\t// prevent us from making the job twice (name the job with hash of its\n\t// scheduled time).\n\n\t// Add the just-started job to the status list.\n\tjobRef, err := getRef(jobResp)\n\tif err != nil {\n\t\tlogger.V(2).Info(\"Unable to make object reference\", \"cronjob\", klog.KObj(cronJob), \"err\", err)\n\t\treturn cronJob, nil, updateStatus, fmt.Errorf(\"unable to make object reference for job for %s\", klog.KObj(cronJob))\n\t}\n\tcronJob.Status.Active = append(cronJob.Status.Active, *jobRef)\n\tcronJob.Status.LastScheduleTime = \u0026metav1.Time{Time: *scheduledTime}\n\tupdateStatus = true\n\n\tt := nextScheduleTimeDuration(cronJob, now, sched)\n\treturn cronJob, t, updateStatus, nil\n}","line":{"from":416,"to":640}} {"id":100003448,"name":"getJobName","signature":"func getJobName(cj *batchv1.CronJob, scheduledTime time.Time) string","file":"pkg/controller/cronjob/cronjob_controllerv2.go","code":"func getJobName(cj *batchv1.CronJob, scheduledTime time.Time) string {\n\treturn fmt.Sprintf(\"%s-%d\", cj.Name, getTimeHashInMinutes(scheduledTime))\n}","line":{"from":642,"to":644}} {"id":100003449,"name":"cleanupFinishedJobs","signature":"func (jm *ControllerV2) cleanupFinishedJobs(ctx context.Context, cj *batchv1.CronJob, js []*batchv1.Job) bool","file":"pkg/controller/cronjob/cronjob_controllerv2.go","code":"// cleanupFinishedJobs cleanups finished jobs created by a CronJob\n// It returns a bool to indicate an update to api-server is needed\nfunc (jm *ControllerV2) cleanupFinishedJobs(ctx context.Context, cj *batchv1.CronJob, js []*batchv1.Job) bool {\n\t// If neither limits are active, there is no need to do anything.\n\tif cj.Spec.FailedJobsHistoryLimit == nil \u0026\u0026 cj.Spec.SuccessfulJobsHistoryLimit == nil {\n\t\treturn false\n\t}\n\n\tupdateStatus := false\n\tfailedJobs := []*batchv1.Job{}\n\tsuccessfulJobs := []*batchv1.Job{}\n\n\tfor _, job := range js {\n\t\tisFinished, finishedStatus := jm.getFinishedStatus(job)\n\t\tif isFinished \u0026\u0026 finishedStatus == batchv1.JobComplete {\n\t\t\tsuccessfulJobs = append(successfulJobs, job)\n\t\t} else if isFinished \u0026\u0026 finishedStatus == batchv1.JobFailed {\n\t\t\tfailedJobs = append(failedJobs, job)\n\t\t}\n\t}\n\n\tif cj.Spec.SuccessfulJobsHistoryLimit != nil \u0026\u0026\n\t\tjm.removeOldestJobs(ctx, cj,\n\t\t\tsuccessfulJobs,\n\t\t\t*cj.Spec.SuccessfulJobsHistoryLimit) {\n\t\tupdateStatus = true\n\t}\n\n\tif cj.Spec.FailedJobsHistoryLimit != nil \u0026\u0026\n\t\tjm.removeOldestJobs(ctx, cj,\n\t\t\tfailedJobs,\n\t\t\t*cj.Spec.FailedJobsHistoryLimit) {\n\t\tupdateStatus = true\n\t}\n\n\treturn updateStatus\n}","line":{"from":646,"to":682}} {"id":100003450,"name":"getFinishedStatus","signature":"func (jm *ControllerV2) getFinishedStatus(j *batchv1.Job) (bool, batchv1.JobConditionType)","file":"pkg/controller/cronjob/cronjob_controllerv2.go","code":"func (jm *ControllerV2) getFinishedStatus(j *batchv1.Job) (bool, batchv1.JobConditionType) {\n\tfor _, c := range j.Status.Conditions {\n\t\tif (c.Type == batchv1.JobComplete || c.Type == batchv1.JobFailed) \u0026\u0026 c.Status == corev1.ConditionTrue {\n\t\t\treturn true, c.Type\n\t\t}\n\t}\n\treturn false, \"\"\n}","line":{"from":684,"to":691}} {"id":100003451,"name":"removeOldestJobs","signature":"func (jm *ControllerV2) removeOldestJobs(ctx context.Context, cj *batchv1.CronJob, js []*batchv1.Job, maxJobs int32) bool","file":"pkg/controller/cronjob/cronjob_controllerv2.go","code":"// removeOldestJobs removes the oldest jobs from a list of jobs\nfunc (jm *ControllerV2) removeOldestJobs(ctx context.Context, cj *batchv1.CronJob, js []*batchv1.Job, maxJobs int32) bool {\n\tupdateStatus := false\n\tnumToDelete := len(js) - int(maxJobs)\n\tif numToDelete \u003c= 0 {\n\t\treturn updateStatus\n\t}\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"Cleaning up jobs from CronJob list\", \"deletejobnum\", numToDelete, \"jobnum\", len(js), \"cronjob\", klog.KObj(cj))\n\n\tsort.Sort(byJobStartTime(js))\n\tfor i := 0; i \u003c numToDelete; i++ {\n\t\tlogger.V(4).Info(\"Removing job from CronJob list\", \"job\", js[i].Name, \"cronjob\", klog.KObj(cj))\n\t\tif deleteJob(logger, cj, js[i], jm.jobControl, jm.recorder) {\n\t\t\tupdateStatus = true\n\t\t}\n\t}\n\treturn updateStatus\n}","line":{"from":693,"to":711}} {"id":100003452,"name":"deleteJob","signature":"func deleteJob(logger klog.Logger, cj *batchv1.CronJob, job *batchv1.Job, jc jobControlInterface, recorder record.EventRecorder) bool","file":"pkg/controller/cronjob/cronjob_controllerv2.go","code":"// deleteJob reaps a job, deleting the job, the pods and the reference in the active list\nfunc deleteJob(logger klog.Logger, cj *batchv1.CronJob, job *batchv1.Job, jc jobControlInterface, recorder record.EventRecorder) bool {\n\t// delete the job itself...\n\tif err := jc.DeleteJob(job.Namespace, job.Name); err != nil {\n\t\trecorder.Eventf(cj, corev1.EventTypeWarning, \"FailedDelete\", \"Deleted job: %v\", err)\n\t\tlogger.Error(err, \"Error deleting job from cronjob\", \"job\", klog.KObj(job), \"cronjob\", klog.KObj(cj))\n\t\treturn false\n\t}\n\t// ... and its reference from active list\n\tdeleteFromActiveList(cj, job.ObjectMeta.UID)\n\trecorder.Eventf(cj, corev1.EventTypeNormal, \"SuccessfulDelete\", \"Deleted job %v\", job.Name)\n\n\treturn true\n}","line":{"from":713,"to":726}} {"id":100003453,"name":"getRef","signature":"func getRef(object runtime.Object) (*corev1.ObjectReference, error)","file":"pkg/controller/cronjob/cronjob_controllerv2.go","code":"func getRef(object runtime.Object) (*corev1.ObjectReference, error) {\n\treturn ref.GetReference(scheme.Scheme, object)\n}","line":{"from":728,"to":730}} {"id":100003454,"name":"formatSchedule","signature":"func formatSchedule(cj *batchv1.CronJob, recorder record.EventRecorder) string","file":"pkg/controller/cronjob/cronjob_controllerv2.go","code":"func formatSchedule(cj *batchv1.CronJob, recorder record.EventRecorder) string {\n\tif strings.Contains(cj.Spec.Schedule, \"TZ\") {\n\t\tif recorder != nil {\n\t\t\trecorder.Eventf(cj, corev1.EventTypeWarning, \"UnsupportedSchedule\", \"CRON_TZ or TZ used in schedule %q is not officially supported, see https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/ for more details\", cj.Spec.Schedule)\n\t\t}\n\n\t\treturn cj.Spec.Schedule\n\t}\n\n\tif cj.Spec.TimeZone != nil {\n\t\tif _, err := time.LoadLocation(*cj.Spec.TimeZone); err != nil {\n\t\t\treturn cj.Spec.Schedule\n\t\t}\n\n\t\treturn fmt.Sprintf(\"TZ=%s %s\", *cj.Spec.TimeZone, cj.Spec.Schedule)\n\t}\n\n\treturn cj.Spec.Schedule\n}","line":{"from":732,"to":750}} {"id":100003455,"name":"GetCronJob","signature":"func (c *realCJControl) GetCronJob(ctx context.Context, namespace, name string) (*batchv1.CronJob, error)","file":"pkg/controller/cronjob/injection.go","code":"func (c *realCJControl) GetCronJob(ctx context.Context, namespace, name string) (*batchv1.CronJob, error) {\n\treturn c.KubeClient.BatchV1().CronJobs(namespace).Get(ctx, name, metav1.GetOptions{})\n}","line":{"from":45,"to":47}} {"id":100003456,"name":"UpdateStatus","signature":"func (c *realCJControl) UpdateStatus(ctx context.Context, cj *batchv1.CronJob) (*batchv1.CronJob, error)","file":"pkg/controller/cronjob/injection.go","code":"func (c *realCJControl) UpdateStatus(ctx context.Context, cj *batchv1.CronJob) (*batchv1.CronJob, error) {\n\treturn c.KubeClient.BatchV1().CronJobs(cj.Namespace).UpdateStatus(ctx, cj, metav1.UpdateOptions{})\n}","line":{"from":51,"to":53}} {"id":100003457,"name":"GetCronJob","signature":"func (c *fakeCJControl) GetCronJob(ctx context.Context, namespace, name string) (*batchv1.CronJob, error)","file":"pkg/controller/cronjob/injection.go","code":"func (c *fakeCJControl) GetCronJob(ctx context.Context, namespace, name string) (*batchv1.CronJob, error) {\n\tif name == c.CronJob.Name \u0026\u0026 namespace == c.CronJob.Namespace {\n\t\treturn c.CronJob, nil\n\t}\n\treturn nil, errors.NewNotFound(schema.GroupResource{\n\t\tGroup: \"v1beta1\",\n\t\tResource: \"cronjobs\",\n\t}, name)\n}","line":{"from":61,"to":69}} {"id":100003458,"name":"UpdateStatus","signature":"func (c *fakeCJControl) UpdateStatus(ctx context.Context, cj *batchv1.CronJob) (*batchv1.CronJob, error)","file":"pkg/controller/cronjob/injection.go","code":"func (c *fakeCJControl) UpdateStatus(ctx context.Context, cj *batchv1.CronJob) (*batchv1.CronJob, error) {\n\tc.Updates = append(c.Updates, *cj)\n\treturn cj, nil\n}","line":{"from":73,"to":76}} {"id":100003459,"name":"GetJob","signature":"func (r realJobControl) GetJob(namespace, name string) (*batchv1.Job, error)","file":"pkg/controller/cronjob/injection.go","code":"func (r realJobControl) GetJob(namespace, name string) (*batchv1.Job, error) {\n\treturn r.KubeClient.BatchV1().Jobs(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n}","line":{"from":104,"to":106}} {"id":100003460,"name":"UpdateJob","signature":"func (r realJobControl) UpdateJob(namespace string, job *batchv1.Job) (*batchv1.Job, error)","file":"pkg/controller/cronjob/injection.go","code":"func (r realJobControl) UpdateJob(namespace string, job *batchv1.Job) (*batchv1.Job, error) {\n\treturn r.KubeClient.BatchV1().Jobs(namespace).Update(context.TODO(), job, metav1.UpdateOptions{})\n}","line":{"from":108,"to":110}} {"id":100003461,"name":"PatchJob","signature":"func (r realJobControl) PatchJob(namespace string, name string, pt types.PatchType, data []byte, subresources ...string) (*batchv1.Job, error)","file":"pkg/controller/cronjob/injection.go","code":"func (r realJobControl) PatchJob(namespace string, name string, pt types.PatchType, data []byte, subresources ...string) (*batchv1.Job, error) {\n\treturn r.KubeClient.BatchV1().Jobs(namespace).Patch(context.TODO(), name, pt, data, metav1.PatchOptions{}, subresources...)\n}","line":{"from":112,"to":114}} {"id":100003462,"name":"CreateJob","signature":"func (r realJobControl) CreateJob(namespace string, job *batchv1.Job) (*batchv1.Job, error)","file":"pkg/controller/cronjob/injection.go","code":"func (r realJobControl) CreateJob(namespace string, job *batchv1.Job) (*batchv1.Job, error) {\n\treturn r.KubeClient.BatchV1().Jobs(namespace).Create(context.TODO(), job, metav1.CreateOptions{})\n}","line":{"from":116,"to":118}} {"id":100003463,"name":"DeleteJob","signature":"func (r realJobControl) DeleteJob(namespace string, name string) error","file":"pkg/controller/cronjob/injection.go","code":"func (r realJobControl) DeleteJob(namespace string, name string) error {\n\tbackground := metav1.DeletePropagationBackground\n\treturn r.KubeClient.BatchV1().Jobs(namespace).Delete(context.TODO(), name, metav1.DeleteOptions{PropagationPolicy: \u0026background})\n}","line":{"from":120,"to":123}} {"id":100003464,"name":"CreateJob","signature":"func (f *fakeJobControl) CreateJob(namespace string, job *batchv1.Job) (*batchv1.Job, error)","file":"pkg/controller/cronjob/injection.go","code":"func (f *fakeJobControl) CreateJob(namespace string, job *batchv1.Job) (*batchv1.Job, error) {\n\tf.Lock()\n\tdefer f.Unlock()\n\tif f.CreateErr != nil {\n\t\treturn nil, f.CreateErr\n\t}\n\tf.Jobs = append(f.Jobs, *job)\n\tjob.UID = \"test-uid\"\n\treturn job, nil\n}","line":{"from":139,"to":148}} {"id":100003465,"name":"GetJob","signature":"func (f *fakeJobControl) GetJob(namespace, name string) (*batchv1.Job, error)","file":"pkg/controller/cronjob/injection.go","code":"func (f *fakeJobControl) GetJob(namespace, name string) (*batchv1.Job, error) {\n\tf.Lock()\n\tdefer f.Unlock()\n\tif f.Err != nil {\n\t\treturn nil, f.Err\n\t}\n\treturn f.Job, nil\n}","line":{"from":150,"to":157}} {"id":100003466,"name":"UpdateJob","signature":"func (f *fakeJobControl) UpdateJob(namespace string, job *batchv1.Job) (*batchv1.Job, error)","file":"pkg/controller/cronjob/injection.go","code":"func (f *fakeJobControl) UpdateJob(namespace string, job *batchv1.Job) (*batchv1.Job, error) {\n\tf.Lock()\n\tdefer f.Unlock()\n\tif f.Err != nil {\n\t\treturn nil, f.Err\n\t}\n\tf.UpdateJobName = append(f.UpdateJobName, job.Name)\n\treturn job, nil\n}","line":{"from":159,"to":167}} {"id":100003467,"name":"PatchJob","signature":"func (f *fakeJobControl) PatchJob(namespace string, name string, pt types.PatchType, data []byte, subresources ...string) (*batchv1.Job, error)","file":"pkg/controller/cronjob/injection.go","code":"func (f *fakeJobControl) PatchJob(namespace string, name string, pt types.PatchType, data []byte, subresources ...string) (*batchv1.Job, error) {\n\tf.Lock()\n\tdefer f.Unlock()\n\tif f.Err != nil {\n\t\treturn nil, f.Err\n\t}\n\tf.PatchJobName = append(f.PatchJobName, name)\n\tf.Patches = append(f.Patches, data)\n\t// We don't have anything to return. Just return something non-nil.\n\treturn \u0026batchv1.Job{}, nil\n}","line":{"from":169,"to":179}} {"id":100003468,"name":"DeleteJob","signature":"func (f *fakeJobControl) DeleteJob(namespace string, name string) error","file":"pkg/controller/cronjob/injection.go","code":"func (f *fakeJobControl) DeleteJob(namespace string, name string) error {\n\tf.Lock()\n\tdefer f.Unlock()\n\tif f.Err != nil {\n\t\treturn f.Err\n\t}\n\tf.DeleteJobName = append(f.DeleteJobName, name)\n\treturn nil\n}","line":{"from":181,"to":189}} {"id":100003469,"name":"Clear","signature":"func (f *fakeJobControl) Clear()","file":"pkg/controller/cronjob/injection.go","code":"func (f *fakeJobControl) Clear() {\n\tf.Lock()\n\tdefer f.Unlock()\n\tf.DeleteJobName = []string{}\n\tf.Jobs = []batchv1.Job{}\n\tf.Err = nil\n}","line":{"from":191,"to":197}} {"id":100003470,"name":"Register","signature":"func Register()","file":"pkg/controller/cronjob/metrics/metrics.go","code":"// Register registers CronjobController metrics.\nfunc Register() {\n\tregisterMetrics.Do(func() {\n\t\tlegacyregistry.MustRegister(CronJobCreationSkew)\n\t})\n}","line":{"from":42,"to":47}} {"id":100003471,"name":"inActiveList","signature":"func inActiveList(cj *batchv1.CronJob, uid types.UID) bool","file":"pkg/controller/cronjob/utils.go","code":"// inActiveList checks if cronjob's .status.active has a job with the same UID.\nfunc inActiveList(cj *batchv1.CronJob, uid types.UID) bool {\n\tfor _, j := range cj.Status.Active {\n\t\tif j.UID == uid {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":36,"to":44}} {"id":100003472,"name":"inActiveListByName","signature":"func inActiveListByName(cj *batchv1.CronJob, job *batchv1.Job) bool","file":"pkg/controller/cronjob/utils.go","code":"// inActiveListByName checks if cronjob's status.active has a job with the same\n// name and namespace.\nfunc inActiveListByName(cj *batchv1.CronJob, job *batchv1.Job) bool {\n\tfor _, j := range cj.Status.Active {\n\t\tif j.Name == job.Name \u0026\u0026 j.Namespace == job.Namespace {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":46,"to":55}} {"id":100003473,"name":"deleteFromActiveList","signature":"func deleteFromActiveList(cj *batchv1.CronJob, uid types.UID)","file":"pkg/controller/cronjob/utils.go","code":"func deleteFromActiveList(cj *batchv1.CronJob, uid types.UID) {\n\tif cj == nil {\n\t\treturn\n\t}\n\t// TODO: @alpatel the memory footprint can may be reduced here by\n\t// cj.Status.Active = append(cj.Status.Active[:indexToRemove], cj.Status.Active[indexToRemove:]...)\n\tnewActive := []corev1.ObjectReference{}\n\tfor _, j := range cj.Status.Active {\n\t\tif j.UID != uid {\n\t\t\tnewActive = append(newActive, j)\n\t\t}\n\t}\n\tcj.Status.Active = newActive\n}","line":{"from":57,"to":70}} {"id":100003474,"name":"mostRecentScheduleTime","signature":"func mostRecentScheduleTime(cj *batchv1.CronJob, now time.Time, schedule cron.Schedule, includeStartingDeadlineSeconds bool) (time.Time, *time.Time, bool, error)","file":"pkg/controller/cronjob/utils.go","code":"// mostRecentScheduleTime returns:\n// - the last schedule time or CronJob's creation time,\n// - the most recent time a Job should be created or nil, if that's after now,\n// - boolean indicating an excessive number of missed schedules,\n// - error in an edge case where the schedule specification is grammatically correct,\n// but logically doesn't make sense (31st day for months with only 30 days, for example).\nfunc mostRecentScheduleTime(cj *batchv1.CronJob, now time.Time, schedule cron.Schedule, includeStartingDeadlineSeconds bool) (time.Time, *time.Time, bool, error) {\n\tearliestTime := cj.ObjectMeta.CreationTimestamp.Time\n\tif cj.Status.LastScheduleTime != nil {\n\t\tearliestTime = cj.Status.LastScheduleTime.Time\n\t}\n\tif includeStartingDeadlineSeconds \u0026\u0026 cj.Spec.StartingDeadlineSeconds != nil {\n\t\t// controller is not going to schedule anything below this point\n\t\tschedulingDeadline := now.Add(-time.Second * time.Duration(*cj.Spec.StartingDeadlineSeconds))\n\n\t\tif schedulingDeadline.After(earliestTime) {\n\t\t\tearliestTime = schedulingDeadline\n\t\t}\n\t}\n\n\tt1 := schedule.Next(earliestTime)\n\tt2 := schedule.Next(t1)\n\n\tif now.Before(t1) {\n\t\treturn earliestTime, nil, false, nil\n\t}\n\tif now.Before(t2) {\n\t\treturn earliestTime, \u0026t1, false, nil\n\t}\n\n\t// It is possible for cron.ParseStandard(\"59 23 31 2 *\") to return an invalid schedule\n\t// minute - 59, hour - 23, dom - 31, month - 2, and dow is optional, clearly 31 is invalid\n\t// In this case the timeBetweenTwoSchedules will be 0, and we error out the invalid schedule\n\ttimeBetweenTwoSchedules := int64(t2.Sub(t1).Round(time.Second).Seconds())\n\tif timeBetweenTwoSchedules \u003c 1 {\n\t\treturn earliestTime, nil, false, fmt.Errorf(\"time difference between two schedules is less than 1 second\")\n\t}\n\t// this logic used for calculating number of missed schedules does a rough\n\t// approximation, by calculating a diff between two schedules (t1 and t2),\n\t// and counting how many of these will fit in between last schedule and now\n\ttimeElapsed := int64(now.Sub(t1).Seconds())\n\tnumberOfMissedSchedules := (timeElapsed / timeBetweenTwoSchedules) + 1\n\n\tvar mostRecentTime time.Time\n\t// to get the most recent time accurate for regular schedules and the ones\n\t// specified with @every form, we first need to calculate the potential earliest\n\t// time by multiplying the initial number of missed schedules by its interval,\n\t// this is critical to ensure @every starts at the correct time, this explains\n\t// the numberOfMissedSchedules-1, the additional -1 serves there to go back\n\t// in time one more time unit, and let the cron library calculate a proper\n\t// schedule, for case where the schedule is not consistent, for example\n\t// something like 30 6-16/4 * * 1-5\n\tpotentialEarliest := t1.Add(time.Duration((numberOfMissedSchedules-1-1)*timeBetweenTwoSchedules) * time.Second)\n\tfor t := schedule.Next(potentialEarliest); !t.After(now); t = schedule.Next(t) {\n\t\tmostRecentTime = t\n\t}\n\n\t// An object might miss several starts. For example, if\n\t// controller gets wedged on friday at 5:01pm when everyone has\n\t// gone home, and someone comes in on tuesday AM and discovers\n\t// the problem and restarts the controller, then all the hourly\n\t// jobs, more than 80 of them for one hourly cronJob, should\n\t// all start running with no further intervention (if the cronJob\n\t// allows concurrency and late starts).\n\t//\n\t// However, if there is a bug somewhere, or incorrect clock\n\t// on controller's server or apiservers (for setting creationTimestamp)\n\t// then there could be so many missed start times (it could be off\n\t// by decades or more), that it would eat up all the CPU and memory\n\t// of this controller. In that case, we want to not try to list\n\t// all the missed start times.\n\t//\n\t// I've somewhat arbitrarily picked 100, as more than 80,\n\t// but less than \"lots\".\n\ttooManyMissed := numberOfMissedSchedules \u003e 100\n\n\tif mostRecentTime.IsZero() {\n\t\treturn earliestTime, nil, tooManyMissed, nil\n\t}\n\treturn earliestTime, \u0026mostRecentTime, tooManyMissed, nil\n}","line":{"from":72,"to":152}} {"id":100003475,"name":"nextScheduleTimeDuration","signature":"func nextScheduleTimeDuration(cj *batchv1.CronJob, now time.Time, schedule cron.Schedule) *time.Duration","file":"pkg/controller/cronjob/utils.go","code":"// nextScheduleTimeDuration returns the time duration to requeue based on\n// the schedule and last schedule time. It adds a 100ms padding to the next requeue to account\n// for Network Time Protocol(NTP) time skews. If the time drifts the adjustment, which in most\n// realistic cases should be around 100s, the job will still be executed without missing\n// the schedule.\nfunc nextScheduleTimeDuration(cj *batchv1.CronJob, now time.Time, schedule cron.Schedule) *time.Duration {\n\tearliestTime, mostRecentTime, _, err := mostRecentScheduleTime(cj, now, schedule, false)\n\tif err != nil {\n\t\t// we still have to requeue at some point, so aim for the next scheduling slot from now\n\t\tmostRecentTime = \u0026now\n\t} else if mostRecentTime == nil {\n\t\t// no missed schedules since earliestTime\n\t\tmostRecentTime = \u0026earliestTime\n\t}\n\n\tt := schedule.Next(*mostRecentTime).Add(nextScheduleDelta).Sub(now)\n\treturn \u0026t\n}","line":{"from":154,"to":171}} {"id":100003476,"name":"nextScheduleTime","signature":"func nextScheduleTime(logger klog.Logger, cj *batchv1.CronJob, now time.Time, schedule cron.Schedule, recorder record.EventRecorder) (*time.Time, error)","file":"pkg/controller/cronjob/utils.go","code":"// nextScheduleTime returns the time.Time of the next schedule after the last scheduled\n// and before now, or nil if no unmet schedule times, and an error.\n// If there are too many (\u003e100) unstarted times, it will also record a warning.\nfunc nextScheduleTime(logger klog.Logger, cj *batchv1.CronJob, now time.Time, schedule cron.Schedule, recorder record.EventRecorder) (*time.Time, error) {\n\t_, mostRecentTime, tooManyMissed, err := mostRecentScheduleTime(cj, now, schedule, true)\n\n\tif mostRecentTime == nil || mostRecentTime.After(now) {\n\t\treturn nil, err\n\t}\n\n\tif tooManyMissed {\n\t\trecorder.Eventf(cj, corev1.EventTypeWarning, \"TooManyMissedTimes\", \"too many missed start times. Set or decrease .spec.startingDeadlineSeconds or check clock skew\")\n\t\tlogger.Info(\"too many missed times\", \"cronjob\", klog.KObj(cj))\n\t}\n\n\treturn mostRecentTime, err\n}","line":{"from":173,"to":189}} {"id":100003477,"name":"copyLabels","signature":"func copyLabels(template *batchv1.JobTemplateSpec) labels.Set","file":"pkg/controller/cronjob/utils.go","code":"func copyLabels(template *batchv1.JobTemplateSpec) labels.Set {\n\tl := make(labels.Set)\n\tfor k, v := range template.Labels {\n\t\tl[k] = v\n\t}\n\treturn l\n}","line":{"from":191,"to":197}} {"id":100003478,"name":"copyAnnotations","signature":"func copyAnnotations(template *batchv1.JobTemplateSpec) labels.Set","file":"pkg/controller/cronjob/utils.go","code":"func copyAnnotations(template *batchv1.JobTemplateSpec) labels.Set {\n\ta := make(labels.Set)\n\tfor k, v := range template.Annotations {\n\t\ta[k] = v\n\t}\n\treturn a\n}","line":{"from":199,"to":205}} {"id":100003479,"name":"getJobFromTemplate2","signature":"func getJobFromTemplate2(cj *batchv1.CronJob, scheduledTime time.Time) (*batchv1.Job, error)","file":"pkg/controller/cronjob/utils.go","code":"// getJobFromTemplate2 makes a Job from a CronJob. It converts the unix time into minutes from\n// epoch time and concatenates that to the job name, because the cronjob_controller v2 has the lowest\n// granularity of 1 minute for scheduling job.\nfunc getJobFromTemplate2(cj *batchv1.CronJob, scheduledTime time.Time) (*batchv1.Job, error) {\n\tlabels := copyLabels(\u0026cj.Spec.JobTemplate)\n\tannotations := copyAnnotations(\u0026cj.Spec.JobTemplate)\n\t// We want job names for a given nominal start time to have a deterministic name to avoid the same job being created twice\n\tname := getJobName(cj, scheduledTime)\n\n\tjob := \u0026batchv1.Job{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tLabels: labels,\n\t\t\tAnnotations: annotations,\n\t\t\tName: name,\n\t\t\tCreationTimestamp: metav1.Time{Time: scheduledTime},\n\t\t\tOwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(cj, controllerKind)},\n\t\t},\n\t}\n\tcj.Spec.JobTemplate.Spec.DeepCopyInto(\u0026job.Spec)\n\treturn job, nil\n}","line":{"from":207,"to":227}} {"id":100003480,"name":"getTimeHashInMinutes","signature":"func getTimeHashInMinutes(scheduledTime time.Time) int64","file":"pkg/controller/cronjob/utils.go","code":"// getTimeHash returns Unix Epoch Time in minutes\nfunc getTimeHashInMinutes(scheduledTime time.Time) int64 {\n\treturn scheduledTime.Unix() / 60\n}","line":{"from":229,"to":232}} {"id":100003481,"name":"getFinishedStatus","signature":"func getFinishedStatus(j *batchv1.Job) (bool, batchv1.JobConditionType)","file":"pkg/controller/cronjob/utils.go","code":"func getFinishedStatus(j *batchv1.Job) (bool, batchv1.JobConditionType) {\n\tfor _, c := range j.Status.Conditions {\n\t\tif (c.Type == batchv1.JobComplete || c.Type == batchv1.JobFailed) \u0026\u0026 c.Status == corev1.ConditionTrue {\n\t\t\treturn true, c.Type\n\t\t}\n\t}\n\treturn false, \"\"\n}","line":{"from":234,"to":241}} {"id":100003482,"name":"IsJobFinished","signature":"func IsJobFinished(j *batchv1.Job) bool","file":"pkg/controller/cronjob/utils.go","code":"// IsJobFinished returns whether or not a job has completed successfully or failed.\nfunc IsJobFinished(j *batchv1.Job) bool {\n\tisFinished, _ := getFinishedStatus(j)\n\treturn isFinished\n}","line":{"from":243,"to":247}} {"id":100003483,"name":"Len","signature":"func (o byJobStartTime) Len() int { return len(o) }","file":"pkg/controller/cronjob/utils.go","code":"func (o byJobStartTime) Len() int { return len(o) }","line":{"from":252,"to":252}} {"id":100003484,"name":"Swap","signature":"func (o byJobStartTime) Swap(i, j int) { o[i], o[j] = o[j], o[i] }","file":"pkg/controller/cronjob/utils.go","code":"func (o byJobStartTime) Swap(i, j int) { o[i], o[j] = o[j], o[i] }","line":{"from":253,"to":253}} {"id":100003485,"name":"Less","signature":"func (o byJobStartTime) Less(i, j int) bool","file":"pkg/controller/cronjob/utils.go","code":"func (o byJobStartTime) Less(i, j int) bool {\n\tif o[i].Status.StartTime == nil \u0026\u0026 o[j].Status.StartTime != nil {\n\t\treturn false\n\t}\n\tif o[i].Status.StartTime != nil \u0026\u0026 o[j].Status.StartTime == nil {\n\t\treturn true\n\t}\n\tif o[i].Status.StartTime.Equal(o[j].Status.StartTime) {\n\t\treturn o[i].Name \u003c o[j].Name\n\t}\n\treturn o[i].Status.StartTime.Before(o[j].Status.StartTime)\n}","line":{"from":255,"to":266}} {"id":100003486,"name":"Convert_v1alpha1_DaemonSetControllerConfiguration_To_config_DaemonSetControllerConfiguration","signature":"func Convert_v1alpha1_DaemonSetControllerConfiguration_To_config_DaemonSetControllerConfiguration(in *v1alpha1.DaemonSetControllerConfiguration, out *daemonconfig.DaemonSetControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/daemon/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_DaemonSetControllerConfiguration_To_config_DaemonSetControllerConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_DaemonSetControllerConfiguration_To_config_DaemonSetControllerConfiguration(in *v1alpha1.DaemonSetControllerConfiguration, out *daemonconfig.DaemonSetControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_DaemonSetControllerConfiguration_To_config_DaemonSetControllerConfiguration(in, out, s)\n}","line":{"from":32,"to":35}} {"id":100003487,"name":"Convert_config_DaemonSetControllerConfiguration_To_v1alpha1_DaemonSetControllerConfiguration","signature":"func Convert_config_DaemonSetControllerConfiguration_To_v1alpha1_DaemonSetControllerConfiguration(in *daemonconfig.DaemonSetControllerConfiguration, out *v1alpha1.DaemonSetControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/daemon/config/v1alpha1/conversion.go","code":"// Convert_config_DaemonSetControllerConfiguration_To_v1alpha1_DaemonSetControllerConfiguration is an autogenerated conversion function.\nfunc Convert_config_DaemonSetControllerConfiguration_To_v1alpha1_DaemonSetControllerConfiguration(in *daemonconfig.DaemonSetControllerConfiguration, out *v1alpha1.DaemonSetControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_DaemonSetControllerConfiguration_To_v1alpha1_DaemonSetControllerConfiguration(in, out, s)\n}","line":{"from":37,"to":40}} {"id":100003488,"name":"RecommendedDefaultDaemonSetControllerConfiguration","signature":"func RecommendedDefaultDaemonSetControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.DaemonSetControllerConfiguration)","file":"pkg/controller/daemon/config/v1alpha1/defaults.go","code":"// RecommendedDefaultDaemonSetControllerConfiguration defaults a pointer to a\n// DaemonSetControllerConfiguration struct. This will set the recommended default\n// values, but they may be subject to change between API versions. This function\n// is intentionally not registered in the scheme as a \"normal\" `SetDefaults_Foo`\n// function to allow consumers of this type to set whatever defaults for their\n// embedded configs. Forcing consumers to use these defaults would be problematic\n// as defaulting in the scheme is done as part of the conversion, and there would\n// be no easy way to opt-out. Instead, if you want to use this defaulting method\n// run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDefaultDaemonSetControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.DaemonSetControllerConfiguration) {\n\tif obj.ConcurrentDaemonSetSyncs == 0 {\n\t\tobj.ConcurrentDaemonSetSyncs = 2\n\t}\n}","line":{"from":23,"to":36}} {"id":100003489,"name":"NewDaemonSetsController","signature":"func NewDaemonSetsController(","file":"pkg/controller/daemon/daemon_controller.go","code":"// NewDaemonSetsController creates a new DaemonSetsController\nfunc NewDaemonSetsController(\n\tctx context.Context,\n\tdaemonSetInformer appsinformers.DaemonSetInformer,\n\thistoryInformer appsinformers.ControllerRevisionInformer,\n\tpodInformer coreinformers.PodInformer,\n\tnodeInformer coreinformers.NodeInformer,\n\tkubeClient clientset.Interface,\n\tfailedPodsBackoff *flowcontrol.Backoff,\n) (*DaemonSetsController, error) {\n\teventBroadcaster := record.NewBroadcaster()\n\tlogger := klog.FromContext(ctx)\n\tdsc := \u0026DaemonSetsController{\n\t\tkubeClient: kubeClient,\n\t\teventBroadcaster: eventBroadcaster,\n\t\teventRecorder: eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"daemonset-controller\"}),\n\t\tpodControl: controller.RealPodControl{\n\t\t\tKubeClient: kubeClient,\n\t\t\tRecorder: eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"daemonset-controller\"}),\n\t\t},\n\t\tcrControl: controller.RealControllerRevisionControl{\n\t\t\tKubeClient: kubeClient,\n\t\t},\n\t\tburstReplicas: BurstReplicas,\n\t\texpectations: controller.NewControllerExpectations(),\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"daemonset\"),\n\t}\n\n\tdaemonSetInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tdsc.addDaemonset(logger, obj)\n\t\t},\n\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\tdsc.updateDaemonset(logger, oldObj, newObj)\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tdsc.deleteDaemonset(logger, obj)\n\t\t},\n\t})\n\tdsc.dsLister = daemonSetInformer.Lister()\n\tdsc.dsStoreSynced = daemonSetInformer.Informer().HasSynced\n\n\thistoryInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tdsc.addHistory(logger, obj)\n\t\t},\n\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\tdsc.updateHistory(logger, oldObj, newObj)\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tdsc.deleteHistory(logger, obj)\n\t\t},\n\t})\n\tdsc.historyLister = historyInformer.Lister()\n\tdsc.historyStoreSynced = historyInformer.Informer().HasSynced\n\n\t// Watch for creation/deletion of pods. The reason we watch is that we don't want a daemon set to create/delete\n\t// more pods until all the effects (expectations) of a daemon set's create/delete have been observed.\n\tpodInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tdsc.addPod(logger, obj)\n\t\t},\n\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\tdsc.updatePod(logger, oldObj, newObj)\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tdsc.deletePod(logger, obj)\n\t\t},\n\t})\n\tdsc.podLister = podInformer.Lister()\n\tdsc.podStoreSynced = podInformer.Informer().HasSynced\n\n\tnodeInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tdsc.addNode(logger, obj)\n\t\t},\n\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\tdsc.updateNode(logger, oldObj, newObj)\n\t\t},\n\t},\n\t)\n\tdsc.nodeStoreSynced = nodeInformer.Informer().HasSynced\n\tdsc.nodeLister = nodeInformer.Lister()\n\n\tdsc.syncHandler = dsc.syncDaemonSet\n\tdsc.enqueueDaemonSet = dsc.enqueue\n\n\tdsc.failedPodsBackoff = failedPodsBackoff\n\n\treturn dsc, nil\n}","line":{"from":133,"to":223}} {"id":100003490,"name":"addDaemonset","signature":"func (dsc *DaemonSetsController) addDaemonset(logger klog.Logger, obj interface{})","file":"pkg/controller/daemon/daemon_controller.go","code":"func (dsc *DaemonSetsController) addDaemonset(logger klog.Logger, obj interface{}) {\n\tds := obj.(*apps.DaemonSet)\n\tlogger.V(4).Info(\"Adding daemon set\", \"daemonset\", klog.KObj(ds))\n\tdsc.enqueueDaemonSet(ds)\n}","line":{"from":225,"to":229}} {"id":100003491,"name":"updateDaemonset","signature":"func (dsc *DaemonSetsController) updateDaemonset(logger klog.Logger, cur, old interface{})","file":"pkg/controller/daemon/daemon_controller.go","code":"func (dsc *DaemonSetsController) updateDaemonset(logger klog.Logger, cur, old interface{}) {\n\toldDS := old.(*apps.DaemonSet)\n\tcurDS := cur.(*apps.DaemonSet)\n\n\t// TODO: make a KEP and fix informers to always call the delete event handler on re-create\n\tif curDS.UID != oldDS.UID {\n\t\tkey, err := controller.KeyFunc(oldDS)\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get key for object %#v: %v\", oldDS, err))\n\t\t\treturn\n\t\t}\n\t\tdsc.deleteDaemonset(logger, cache.DeletedFinalStateUnknown{\n\t\t\tKey: key,\n\t\t\tObj: oldDS,\n\t\t})\n\t}\n\n\tlogger.V(4).Info(\"Updating daemon set\", \"daemonset\", klog.KObj(oldDS))\n\tdsc.enqueueDaemonSet(curDS)\n}","line":{"from":231,"to":250}} {"id":100003492,"name":"deleteDaemonset","signature":"func (dsc *DaemonSetsController) deleteDaemonset(logger klog.Logger, obj interface{})","file":"pkg/controller/daemon/daemon_controller.go","code":"func (dsc *DaemonSetsController) deleteDaemonset(logger klog.Logger, obj interface{}) {\n\tds, ok := obj.(*apps.DaemonSet)\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get object from tombstone %#v\", obj))\n\t\t\treturn\n\t\t}\n\t\tds, ok = tombstone.Obj.(*apps.DaemonSet)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"tombstone contained object that is not a DaemonSet %#v\", obj))\n\t\t\treturn\n\t\t}\n\t}\n\tlogger.V(4).Info(\"Deleting daemon set\", \"daemonset\", klog.KObj(ds))\n\n\tkey, err := controller.KeyFunc(ds)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get key for object %#v: %v\", ds, err))\n\t\treturn\n\t}\n\n\t// Delete expectations for the DaemonSet so if we create a new one with the same name it starts clean\n\tdsc.expectations.DeleteExpectations(key)\n\n\tdsc.queue.Add(key)\n}","line":{"from":252,"to":278}} {"id":100003493,"name":"Run","signature":"func (dsc *DaemonSetsController) Run(ctx context.Context, workers int)","file":"pkg/controller/daemon/daemon_controller.go","code":"// Run begins watching and syncing daemon sets.\nfunc (dsc *DaemonSetsController) Run(ctx context.Context, workers int) {\n\tdefer utilruntime.HandleCrash()\n\n\tdsc.eventBroadcaster.StartStructuredLogging(0)\n\tdsc.eventBroadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: dsc.kubeClient.CoreV1().Events(\"\")})\n\tdefer dsc.eventBroadcaster.Shutdown()\n\n\tdefer dsc.queue.ShutDown()\n\n\tlogger := klog.FromContext(ctx)\n\tlogger.Info(\"Starting daemon sets controller\")\n\tdefer logger.Info(\"Shutting down daemon sets controller\")\n\n\tif !cache.WaitForNamedCacheSync(\"daemon sets\", ctx.Done(), dsc.podStoreSynced, dsc.nodeStoreSynced, dsc.historyStoreSynced, dsc.dsStoreSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.UntilWithContext(ctx, dsc.runWorker, time.Second)\n\t}\n\n\tgo wait.Until(dsc.failedPodsBackoff.GC, BackoffGCInterval, ctx.Done())\n\n\t\u003c-ctx.Done()\n}","line":{"from":280,"to":305}} {"id":100003494,"name":"runWorker","signature":"func (dsc *DaemonSetsController) runWorker(ctx context.Context)","file":"pkg/controller/daemon/daemon_controller.go","code":"func (dsc *DaemonSetsController) runWorker(ctx context.Context) {\n\tfor dsc.processNextWorkItem(ctx) {\n\t}\n}","line":{"from":307,"to":310}} {"id":100003495,"name":"processNextWorkItem","signature":"func (dsc *DaemonSetsController) processNextWorkItem(ctx context.Context) bool","file":"pkg/controller/daemon/daemon_controller.go","code":"// processNextWorkItem deals with one key off the queue. It returns false when it's time to quit.\nfunc (dsc *DaemonSetsController) processNextWorkItem(ctx context.Context) bool {\n\tdsKey, quit := dsc.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer dsc.queue.Done(dsKey)\n\n\terr := dsc.syncHandler(ctx, dsKey.(string))\n\tif err == nil {\n\t\tdsc.queue.Forget(dsKey)\n\t\treturn true\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"%v failed with : %v\", dsKey, err))\n\tdsc.queue.AddRateLimited(dsKey)\n\n\treturn true\n}","line":{"from":312,"to":330}} {"id":100003496,"name":"enqueue","signature":"func (dsc *DaemonSetsController) enqueue(ds *apps.DaemonSet)","file":"pkg/controller/daemon/daemon_controller.go","code":"func (dsc *DaemonSetsController) enqueue(ds *apps.DaemonSet) {\n\tkey, err := controller.KeyFunc(ds)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Couldn't get key for object %#v: %v\", ds, err))\n\t\treturn\n\t}\n\n\t// TODO: Handle overlapping controllers better. See comment in ReplicationManager.\n\tdsc.queue.Add(key)\n}","line":{"from":332,"to":341}} {"id":100003497,"name":"enqueueDaemonSetAfter","signature":"func (dsc *DaemonSetsController) enqueueDaemonSetAfter(obj interface{}, after time.Duration)","file":"pkg/controller/daemon/daemon_controller.go","code":"func (dsc *DaemonSetsController) enqueueDaemonSetAfter(obj interface{}, after time.Duration) {\n\tkey, err := controller.KeyFunc(obj)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Couldn't get key for object %+v: %v\", obj, err))\n\t\treturn\n\t}\n\n\t// TODO: Handle overlapping controllers better. See comment in ReplicationManager.\n\tdsc.queue.AddAfter(key, after)\n}","line":{"from":343,"to":352}} {"id":100003498,"name":"getDaemonSetsForPod","signature":"func (dsc *DaemonSetsController) getDaemonSetsForPod(pod *v1.Pod) []*apps.DaemonSet","file":"pkg/controller/daemon/daemon_controller.go","code":"// getDaemonSetsForPod returns a list of DaemonSets that potentially match the pod.\nfunc (dsc *DaemonSetsController) getDaemonSetsForPod(pod *v1.Pod) []*apps.DaemonSet {\n\tsets, err := dsc.dsLister.GetPodDaemonSets(pod)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tif len(sets) \u003e 1 {\n\t\t// ControllerRef will ensure we don't do anything crazy, but more than one\n\t\t// item in this list nevertheless constitutes user error.\n\t\tutilruntime.HandleError(fmt.Errorf(\"user error! more than one daemon is selecting pods with labels: %+v\", pod.Labels))\n\t}\n\treturn sets\n}","line":{"from":354,"to":366}} {"id":100003499,"name":"getDaemonSetsForHistory","signature":"func (dsc *DaemonSetsController) getDaemonSetsForHistory(logger klog.Logger, history *apps.ControllerRevision) []*apps.DaemonSet","file":"pkg/controller/daemon/daemon_controller.go","code":"// getDaemonSetsForHistory returns a list of DaemonSets that potentially\n// match a ControllerRevision.\nfunc (dsc *DaemonSetsController) getDaemonSetsForHistory(logger klog.Logger, history *apps.ControllerRevision) []*apps.DaemonSet {\n\tdaemonSets, err := dsc.dsLister.GetHistoryDaemonSets(history)\n\tif err != nil || len(daemonSets) == 0 {\n\t\treturn nil\n\t}\n\tif len(daemonSets) \u003e 1 {\n\t\t// ControllerRef will ensure we don't do anything crazy, but more than one\n\t\t// item in this list nevertheless constitutes user error.\n\t\tlogger.V(4).Info(\"Found more than one DaemonSet selecting the ControllerRevision. This is potentially a user error\",\n\t\t\t\"controllerRevision\", klog.KObj(history), \"labels\", history.Labels)\n\t}\n\treturn daemonSets\n}","line":{"from":368,"to":382}} {"id":100003500,"name":"addHistory","signature":"func (dsc *DaemonSetsController) addHistory(logger klog.Logger, obj interface{})","file":"pkg/controller/daemon/daemon_controller.go","code":"// addHistory enqueues the DaemonSet that manages a ControllerRevision when the ControllerRevision is created\n// or when the controller manager is restarted.\nfunc (dsc *DaemonSetsController) addHistory(logger klog.Logger, obj interface{}) {\n\thistory := obj.(*apps.ControllerRevision)\n\tif history.DeletionTimestamp != nil {\n\t\t// On a restart of the controller manager, it's possible for an object to\n\t\t// show up in a state that is already pending deletion.\n\t\tdsc.deleteHistory(logger, history)\n\t\treturn\n\t}\n\n\t// If it has a ControllerRef, that's all that matters.\n\tif controllerRef := metav1.GetControllerOf(history); controllerRef != nil {\n\t\tds := dsc.resolveControllerRef(history.Namespace, controllerRef)\n\t\tif ds == nil {\n\t\t\treturn\n\t\t}\n\t\tlogger.V(4).Info(\"Observed a ControllerRevision\", \"controllerRevision\", klog.KObj(history))\n\t\treturn\n\t}\n\n\t// Otherwise, it's an orphan. Get a list of all matching DaemonSets and sync\n\t// them to see if anyone wants to adopt it.\n\tdaemonSets := dsc.getDaemonSetsForHistory(logger, history)\n\tif len(daemonSets) == 0 {\n\t\treturn\n\t}\n\tlogger.V(4).Info(\"Orphan ControllerRevision added\", \"controllerRevision\", klog.KObj(history))\n\tfor _, ds := range daemonSets {\n\t\tdsc.enqueueDaemonSet(ds)\n\t}\n}","line":{"from":384,"to":415}} {"id":100003501,"name":"updateHistory","signature":"func (dsc *DaemonSetsController) updateHistory(logger klog.Logger, old, cur interface{})","file":"pkg/controller/daemon/daemon_controller.go","code":"// updateHistory figures out what DaemonSet(s) manage a ControllerRevision when the ControllerRevision\n// is updated and wake them up. If anything of the ControllerRevision has changed, we need to awaken\n// both the old and new DaemonSets.\nfunc (dsc *DaemonSetsController) updateHistory(logger klog.Logger, old, cur interface{}) {\n\tcurHistory := cur.(*apps.ControllerRevision)\n\toldHistory := old.(*apps.ControllerRevision)\n\tif curHistory.ResourceVersion == oldHistory.ResourceVersion {\n\t\t// Periodic resync will send update events for all known ControllerRevisions.\n\t\treturn\n\t}\n\n\tcurControllerRef := metav1.GetControllerOf(curHistory)\n\toldControllerRef := metav1.GetControllerOf(oldHistory)\n\tcontrollerRefChanged := !reflect.DeepEqual(curControllerRef, oldControllerRef)\n\tif controllerRefChanged \u0026\u0026 oldControllerRef != nil {\n\t\t// The ControllerRef was changed. Sync the old controller, if any.\n\t\tif ds := dsc.resolveControllerRef(oldHistory.Namespace, oldControllerRef); ds != nil {\n\t\t\tdsc.enqueueDaemonSet(ds)\n\t\t}\n\t}\n\n\t// If it has a ControllerRef, that's all that matters.\n\tif curControllerRef != nil {\n\t\tds := dsc.resolveControllerRef(curHistory.Namespace, curControllerRef)\n\t\tif ds == nil {\n\t\t\treturn\n\t\t}\n\t\tlogger.V(4).Info(\"Observed an update to a ControllerRevision\", \"controllerRevision\", klog.KObj(curHistory))\n\t\tdsc.enqueueDaemonSet(ds)\n\t\treturn\n\t}\n\n\t// Otherwise, it's an orphan. If anything changed, sync matching controllers\n\t// to see if anyone wants to adopt it now.\n\tlabelChanged := !reflect.DeepEqual(curHistory.Labels, oldHistory.Labels)\n\tif labelChanged || controllerRefChanged {\n\t\tdaemonSets := dsc.getDaemonSetsForHistory(logger, curHistory)\n\t\tif len(daemonSets) == 0 {\n\t\t\treturn\n\t\t}\n\t\tlogger.V(4).Info(\"Orphan ControllerRevision updated\", \"controllerRevision\", klog.KObj(curHistory))\n\t\tfor _, ds := range daemonSets {\n\t\t\tdsc.enqueueDaemonSet(ds)\n\t\t}\n\t}\n}","line":{"from":417,"to":462}} {"id":100003502,"name":"deleteHistory","signature":"func (dsc *DaemonSetsController) deleteHistory(logger klog.Logger, obj interface{})","file":"pkg/controller/daemon/daemon_controller.go","code":"// deleteHistory enqueues the DaemonSet that manages a ControllerRevision when\n// the ControllerRevision is deleted. obj could be an *app.ControllerRevision, or\n// a DeletionFinalStateUnknown marker item.\nfunc (dsc *DaemonSetsController) deleteHistory(logger klog.Logger, obj interface{}) {\n\thistory, ok := obj.(*apps.ControllerRevision)\n\n\t// When a delete is dropped, the relist will notice a ControllerRevision in the store not\n\t// in the list, leading to the insertion of a tombstone object which contains\n\t// the deleted key/value. Note that this value might be stale. If the ControllerRevision\n\t// changed labels the new DaemonSet will not be woken up till the periodic resync.\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"Couldn't get object from tombstone %#v\", obj))\n\t\t\treturn\n\t\t}\n\t\thistory, ok = tombstone.Obj.(*apps.ControllerRevision)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"Tombstone contained object that is not a ControllerRevision %#v\", obj))\n\t\t\treturn\n\t\t}\n\t}\n\n\tcontrollerRef := metav1.GetControllerOf(history)\n\tif controllerRef == nil {\n\t\t// No controller should care about orphans being deleted.\n\t\treturn\n\t}\n\tds := dsc.resolveControllerRef(history.Namespace, controllerRef)\n\tif ds == nil {\n\t\treturn\n\t}\n\tlogger.V(4).Info(\"ControllerRevision deleted\", \"controllerRevision\", klog.KObj(history))\n\tdsc.enqueueDaemonSet(ds)\n}","line":{"from":464,"to":498}} {"id":100003503,"name":"addPod","signature":"func (dsc *DaemonSetsController) addPod(logger klog.Logger, obj interface{})","file":"pkg/controller/daemon/daemon_controller.go","code":"func (dsc *DaemonSetsController) addPod(logger klog.Logger, obj interface{}) {\n\tpod := obj.(*v1.Pod)\n\n\tif pod.DeletionTimestamp != nil {\n\t\t// on a restart of the controller manager, it's possible a new pod shows up in a state that\n\t\t// is already pending deletion. Prevent the pod from being a creation observation.\n\t\tdsc.deletePod(logger, pod)\n\t\treturn\n\t}\n\n\t// If it has a ControllerRef, that's all that matters.\n\tif controllerRef := metav1.GetControllerOf(pod); controllerRef != nil {\n\t\tds := dsc.resolveControllerRef(pod.Namespace, controllerRef)\n\t\tif ds == nil {\n\t\t\treturn\n\t\t}\n\t\tdsKey, err := controller.KeyFunc(ds)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tlogger.V(4).Info(\"Pod added\", \"pod\", klog.KObj(pod))\n\t\tdsc.expectations.CreationObserved(dsKey)\n\t\tdsc.enqueueDaemonSet(ds)\n\t\treturn\n\t}\n\n\t// Otherwise, it's an orphan. Get a list of all matching DaemonSets and sync\n\t// them to see if anyone wants to adopt it.\n\t// DO NOT observe creation because no controller should be waiting for an\n\t// orphan.\n\tdss := dsc.getDaemonSetsForPod(pod)\n\tif len(dss) == 0 {\n\t\treturn\n\t}\n\tlogger.V(4).Info(\"Orphan Pod added\", \"pod\", klog.KObj(pod))\n\tfor _, ds := range dss {\n\t\tdsc.enqueueDaemonSet(ds)\n\t}\n}","line":{"from":500,"to":538}} {"id":100003504,"name":"updatePod","signature":"func (dsc *DaemonSetsController) updatePod(logger klog.Logger, old, cur interface{})","file":"pkg/controller/daemon/daemon_controller.go","code":"// When a pod is updated, figure out what sets manage it and wake them\n// up. If the labels of the pod have changed we need to awaken both the old\n// and new set. old and cur must be *v1.Pod types.\nfunc (dsc *DaemonSetsController) updatePod(logger klog.Logger, old, cur interface{}) {\n\tcurPod := cur.(*v1.Pod)\n\toldPod := old.(*v1.Pod)\n\tif curPod.ResourceVersion == oldPod.ResourceVersion {\n\t\t// Periodic resync will send update events for all known pods.\n\t\t// Two different versions of the same pod will always have different RVs.\n\t\treturn\n\t}\n\n\tif curPod.DeletionTimestamp != nil {\n\t\t// when a pod is deleted gracefully its deletion timestamp is first modified to reflect a grace period,\n\t\t// and after such time has passed, the kubelet actually deletes it from the store. We receive an update\n\t\t// for modification of the deletion timestamp and expect an ds to create more replicas asap, not wait\n\t\t// until the kubelet actually deletes the pod.\n\t\tdsc.deletePod(logger, curPod)\n\t\treturn\n\t}\n\n\tcurControllerRef := metav1.GetControllerOf(curPod)\n\toldControllerRef := metav1.GetControllerOf(oldPod)\n\tcontrollerRefChanged := !reflect.DeepEqual(curControllerRef, oldControllerRef)\n\tif controllerRefChanged \u0026\u0026 oldControllerRef != nil {\n\t\t// The ControllerRef was changed. Sync the old controller, if any.\n\t\tif ds := dsc.resolveControllerRef(oldPod.Namespace, oldControllerRef); ds != nil {\n\t\t\tdsc.enqueueDaemonSet(ds)\n\t\t}\n\t}\n\n\t// If it has a ControllerRef, that's all that matters.\n\tif curControllerRef != nil {\n\t\tds := dsc.resolveControllerRef(curPod.Namespace, curControllerRef)\n\t\tif ds == nil {\n\t\t\treturn\n\t\t}\n\t\tlogger.V(4).Info(\"Pod updated\", \"pod\", klog.KObj(curPod))\n\t\tdsc.enqueueDaemonSet(ds)\n\t\tchangedToReady := !podutil.IsPodReady(oldPod) \u0026\u0026 podutil.IsPodReady(curPod)\n\t\t// See https://github.com/kubernetes/kubernetes/pull/38076 for more details\n\t\tif changedToReady \u0026\u0026 ds.Spec.MinReadySeconds \u003e 0 {\n\t\t\t// Add a second to avoid milliseconds skew in AddAfter.\n\t\t\t// See https://github.com/kubernetes/kubernetes/issues/39785#issuecomment-279959133 for more info.\n\t\t\tdsc.enqueueDaemonSetAfter(ds, (time.Duration(ds.Spec.MinReadySeconds)*time.Second)+time.Second)\n\t\t}\n\t\treturn\n\t}\n\n\t// Otherwise, it's an orphan. If anything changed, sync matching controllers\n\t// to see if anyone wants to adopt it now.\n\tdss := dsc.getDaemonSetsForPod(curPod)\n\tif len(dss) == 0 {\n\t\treturn\n\t}\n\tlogger.V(4).Info(\"Orphan Pod updated\", \"pod\", klog.KObj(curPod))\n\tlabelChanged := !reflect.DeepEqual(curPod.Labels, oldPod.Labels)\n\tif labelChanged || controllerRefChanged {\n\t\tfor _, ds := range dss {\n\t\t\tdsc.enqueueDaemonSet(ds)\n\t\t}\n\t}\n}","line":{"from":540,"to":602}} {"id":100003505,"name":"deletePod","signature":"func (dsc *DaemonSetsController) deletePod(logger klog.Logger, obj interface{})","file":"pkg/controller/daemon/daemon_controller.go","code":"func (dsc *DaemonSetsController) deletePod(logger klog.Logger, obj interface{}) {\n\tpod, ok := obj.(*v1.Pod)\n\t// When a delete is dropped, the relist will notice a pod in the store not\n\t// in the list, leading to the insertion of a tombstone object which contains\n\t// the deleted key/value. Note that this value might be stale. If the pod\n\t// changed labels the new daemonset will not be woken up till the periodic\n\t// resync.\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get object from tombstone %#v\", obj))\n\t\t\treturn\n\t\t}\n\t\tpod, ok = tombstone.Obj.(*v1.Pod)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"tombstone contained object that is not a pod %#v\", obj))\n\t\t\treturn\n\t\t}\n\t}\n\n\tcontrollerRef := metav1.GetControllerOf(pod)\n\tif controllerRef == nil {\n\t\t// No controller should care about orphans being deleted.\n\t\treturn\n\t}\n\tds := dsc.resolveControllerRef(pod.Namespace, controllerRef)\n\tif ds == nil {\n\t\treturn\n\t}\n\tdsKey, err := controller.KeyFunc(ds)\n\tif err != nil {\n\t\treturn\n\t}\n\tlogger.V(4).Info(\"Pod deleted\", \"pod\", klog.KObj(pod))\n\tdsc.expectations.DeletionObserved(dsKey)\n\tdsc.enqueueDaemonSet(ds)\n}","line":{"from":604,"to":640}} {"id":100003506,"name":"addNode","signature":"func (dsc *DaemonSetsController) addNode(logger klog.Logger, obj interface{})","file":"pkg/controller/daemon/daemon_controller.go","code":"func (dsc *DaemonSetsController) addNode(logger klog.Logger, obj interface{}) {\n\t// TODO: it'd be nice to pass a hint with these enqueues, so that each ds would only examine the added node (unless it has other work to do, too).\n\tdsList, err := dsc.dsLister.List(labels.Everything())\n\tif err != nil {\n\t\tlogger.V(4).Info(\"Error enqueueing daemon sets\", \"err\", err)\n\t\treturn\n\t}\n\tnode := obj.(*v1.Node)\n\tfor _, ds := range dsList {\n\t\tif shouldRun, _ := NodeShouldRunDaemonPod(node, ds); shouldRun {\n\t\t\tdsc.enqueueDaemonSet(ds)\n\t\t}\n\t}\n}","line":{"from":642,"to":655}} {"id":100003507,"name":"nodeInSameCondition","signature":"func nodeInSameCondition(old []v1.NodeCondition, cur []v1.NodeCondition) bool","file":"pkg/controller/daemon/daemon_controller.go","code":"// nodeInSameCondition returns true if all effective types (\"Status\" is true) equals;\n// otherwise, returns false.\nfunc nodeInSameCondition(old []v1.NodeCondition, cur []v1.NodeCondition) bool {\n\tif len(old) == 0 \u0026\u0026 len(cur) == 0 {\n\t\treturn true\n\t}\n\n\tc1map := map[v1.NodeConditionType]v1.ConditionStatus{}\n\tfor _, c := range old {\n\t\tif c.Status == v1.ConditionTrue {\n\t\t\tc1map[c.Type] = c.Status\n\t\t}\n\t}\n\n\tfor _, c := range cur {\n\t\tif c.Status != v1.ConditionTrue {\n\t\t\tcontinue\n\t\t}\n\n\t\tif _, found := c1map[c.Type]; !found {\n\t\t\treturn false\n\t\t}\n\n\t\tdelete(c1map, c.Type)\n\t}\n\n\treturn len(c1map) == 0\n}","line":{"from":657,"to":684}} {"id":100003508,"name":"shouldIgnoreNodeUpdate","signature":"func shouldIgnoreNodeUpdate(oldNode, curNode v1.Node) bool","file":"pkg/controller/daemon/daemon_controller.go","code":"func shouldIgnoreNodeUpdate(oldNode, curNode v1.Node) bool {\n\tif !nodeInSameCondition(oldNode.Status.Conditions, curNode.Status.Conditions) {\n\t\treturn false\n\t}\n\toldNode.ResourceVersion = curNode.ResourceVersion\n\toldNode.Status.Conditions = curNode.Status.Conditions\n\treturn apiequality.Semantic.DeepEqual(oldNode, curNode)\n}","line":{"from":686,"to":693}} {"id":100003509,"name":"updateNode","signature":"func (dsc *DaemonSetsController) updateNode(logger klog.Logger, old, cur interface{})","file":"pkg/controller/daemon/daemon_controller.go","code":"func (dsc *DaemonSetsController) updateNode(logger klog.Logger, old, cur interface{}) {\n\toldNode := old.(*v1.Node)\n\tcurNode := cur.(*v1.Node)\n\tif shouldIgnoreNodeUpdate(*oldNode, *curNode) {\n\t\treturn\n\t}\n\n\tdsList, err := dsc.dsLister.List(labels.Everything())\n\tif err != nil {\n\t\tlogger.V(4).Info(\"Error listing daemon sets\", \"err\", err)\n\t\treturn\n\t}\n\t// TODO: it'd be nice to pass a hint with these enqueues, so that each ds would only examine the added node (unless it has other work to do, too).\n\tfor _, ds := range dsList {\n\t\toldShouldRun, oldShouldContinueRunning := NodeShouldRunDaemonPod(oldNode, ds)\n\t\tcurrentShouldRun, currentShouldContinueRunning := NodeShouldRunDaemonPod(curNode, ds)\n\t\tif (oldShouldRun != currentShouldRun) || (oldShouldContinueRunning != currentShouldContinueRunning) {\n\t\t\tdsc.enqueueDaemonSet(ds)\n\t\t}\n\t}\n}","line":{"from":695,"to":715}} {"id":100003510,"name":"getDaemonPods","signature":"func (dsc *DaemonSetsController) getDaemonPods(ctx context.Context, ds *apps.DaemonSet) ([]*v1.Pod, error)","file":"pkg/controller/daemon/daemon_controller.go","code":"// getDaemonPods returns daemon pods owned by the given ds.\n// This also reconciles ControllerRef by adopting/orphaning.\n// Note that returned Pods are pointers to objects in the cache.\n// If you want to modify one, you need to deep-copy it first.\nfunc (dsc *DaemonSetsController) getDaemonPods(ctx context.Context, ds *apps.DaemonSet) ([]*v1.Pod, error) {\n\tselector, err := metav1.LabelSelectorAsSelector(ds.Spec.Selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// List all pods to include those that don't match the selector anymore but\n\t// have a ControllerRef pointing to this controller.\n\tpods, err := dsc.podLister.Pods(ds.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// If any adoptions are attempted, we should first recheck for deletion with\n\t// an uncached quorum read sometime after listing Pods (see #42639).\n\tdsNotDeleted := controller.RecheckDeletionTimestamp(func(ctx context.Context) (metav1.Object, error) {\n\t\tfresh, err := dsc.kubeClient.AppsV1().DaemonSets(ds.Namespace).Get(ctx, ds.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif fresh.UID != ds.UID {\n\t\t\treturn nil, fmt.Errorf(\"original DaemonSet %v/%v is gone: got uid %v, wanted %v\", ds.Namespace, ds.Name, fresh.UID, ds.UID)\n\t\t}\n\t\treturn fresh, nil\n\t})\n\n\t// Use ControllerRefManager to adopt/orphan as needed.\n\tcm := controller.NewPodControllerRefManager(dsc.podControl, ds, selector, controllerKind, dsNotDeleted)\n\treturn cm.ClaimPods(ctx, pods)\n}","line":{"from":717,"to":749}} {"id":100003511,"name":"getNodesToDaemonPods","signature":"func (dsc *DaemonSetsController) getNodesToDaemonPods(ctx context.Context, ds *apps.DaemonSet, includeDeletedTerminal bool) (map[string][]*v1.Pod, error)","file":"pkg/controller/daemon/daemon_controller.go","code":"// getNodesToDaemonPods returns a map from nodes to daemon pods (corresponding to ds) created for the nodes.\n// This also reconciles ControllerRef by adopting/orphaning.\n// Note that returned Pods are pointers to objects in the cache.\n// If you want to modify one, you need to deep-copy it first.\nfunc (dsc *DaemonSetsController) getNodesToDaemonPods(ctx context.Context, ds *apps.DaemonSet, includeDeletedTerminal bool) (map[string][]*v1.Pod, error) {\n\tclaimedPods, err := dsc.getDaemonPods(ctx, ds)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Group Pods by Node name.\n\tnodeToDaemonPods := make(map[string][]*v1.Pod)\n\tlogger := klog.FromContext(ctx)\n\tfor _, pod := range claimedPods {\n\t\tif !includeDeletedTerminal \u0026\u0026 podutil.IsPodTerminal(pod) \u0026\u0026 pod.DeletionTimestamp != nil {\n\t\t\t// This Pod has a finalizer or is already scheduled for deletion from the\n\t\t\t// store by the kubelet or the Pod GC. The DS controller doesn't have\n\t\t\t// anything else to do with it.\n\t\t\tcontinue\n\t\t}\n\t\tnodeName, err := util.GetTargetNodeName(pod)\n\t\tif err != nil {\n\t\t\tlogger.Info(\"Failed to get target node name of Pod in DaemonSet\",\n\t\t\t\t\"pod\", klog.KObj(pod), \"daemonset\", klog.KObj(ds))\n\t\t\tcontinue\n\t\t}\n\n\t\tnodeToDaemonPods[nodeName] = append(nodeToDaemonPods[nodeName], pod)\n\t}\n\n\treturn nodeToDaemonPods, nil\n}","line":{"from":751,"to":781}} {"id":100003512,"name":"resolveControllerRef","signature":"func (dsc *DaemonSetsController) resolveControllerRef(namespace string, controllerRef *metav1.OwnerReference) *apps.DaemonSet","file":"pkg/controller/daemon/daemon_controller.go","code":"// resolveControllerRef returns the controller referenced by a ControllerRef,\n// or nil if the ControllerRef could not be resolved to a matching controller\n// of the correct Kind.\nfunc (dsc *DaemonSetsController) resolveControllerRef(namespace string, controllerRef *metav1.OwnerReference) *apps.DaemonSet {\n\t// We can't look up by UID, so look up by Name and then verify UID.\n\t// Don't even try to look up by Name if it's the wrong Kind.\n\tif controllerRef.Kind != controllerKind.Kind {\n\t\treturn nil\n\t}\n\tds, err := dsc.dsLister.DaemonSets(namespace).Get(controllerRef.Name)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tif ds.UID != controllerRef.UID {\n\t\t// The controller we found with this Name is not the same one that the\n\t\t// ControllerRef points to.\n\t\treturn nil\n\t}\n\treturn ds\n}","line":{"from":783,"to":802}} {"id":100003513,"name":"podsShouldBeOnNode","signature":"func (dsc *DaemonSetsController) podsShouldBeOnNode(","file":"pkg/controller/daemon/daemon_controller.go","code":"// podsShouldBeOnNode figures out the DaemonSet pods to be created and deleted on the given node:\n// - nodesNeedingDaemonPods: the pods need to start on the node\n// - podsToDelete: the Pods need to be deleted on the node\n// - err: unexpected error\nfunc (dsc *DaemonSetsController) podsShouldBeOnNode(\n\tlogger klog.Logger,\n\tnode *v1.Node,\n\tnodeToDaemonPods map[string][]*v1.Pod,\n\tds *apps.DaemonSet,\n\thash string,\n) (nodesNeedingDaemonPods, podsToDelete []string) {\n\n\tshouldRun, shouldContinueRunning := NodeShouldRunDaemonPod(node, ds)\n\tdaemonPods, exists := nodeToDaemonPods[node.Name]\n\n\tswitch {\n\tcase shouldRun \u0026\u0026 !exists:\n\t\t// If daemon pod is supposed to be running on node, but isn't, create daemon pod.\n\t\tnodesNeedingDaemonPods = append(nodesNeedingDaemonPods, node.Name)\n\tcase shouldContinueRunning:\n\t\t// If a daemon pod failed, delete it\n\t\t// If there's non-daemon pods left on this node, we will create it in the next sync loop\n\t\tvar daemonPodsRunning []*v1.Pod\n\t\tfor _, pod := range daemonPods {\n\t\t\tif pod.DeletionTimestamp != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif pod.Status.Phase == v1.PodFailed {\n\t\t\t\t// This is a critical place where DS is often fighting with kubelet that rejects pods.\n\t\t\t\t// We need to avoid hot looping and backoff.\n\t\t\t\tbackoffKey := failedPodsBackoffKey(ds, node.Name)\n\n\t\t\t\tnow := dsc.failedPodsBackoff.Clock.Now()\n\t\t\t\tinBackoff := dsc.failedPodsBackoff.IsInBackOffSinceUpdate(backoffKey, now)\n\t\t\t\tif inBackoff {\n\t\t\t\t\tdelay := dsc.failedPodsBackoff.Get(backoffKey)\n\t\t\t\t\tlogger.V(4).Info(\"Deleting failed pod on node has been limited by backoff\",\n\t\t\t\t\t\t\"pod\", klog.KObj(pod), \"node\", klog.KObj(node), \"currentDelay\", delay)\n\t\t\t\t\tdsc.enqueueDaemonSetAfter(ds, delay)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tdsc.failedPodsBackoff.Next(backoffKey, now)\n\n\t\t\t\tmsg := fmt.Sprintf(\"Found failed daemon pod %s/%s on node %s, will try to kill it\", pod.Namespace, pod.Name, node.Name)\n\t\t\t\tlogger.V(2).Info(\"Found failed daemon pod on node, will try to kill it\", \"pod\", klog.KObj(pod), \"node\", klog.KObj(node))\n\t\t\t\t// Emit an event so that it's discoverable to users.\n\t\t\t\tdsc.eventRecorder.Eventf(ds, v1.EventTypeWarning, FailedDaemonPodReason, msg)\n\t\t\t\tpodsToDelete = append(podsToDelete, pod.Name)\n\t\t\t} else if pod.Status.Phase == v1.PodSucceeded {\n\t\t\t\tmsg := fmt.Sprintf(\"Found succeeded daemon pod %s/%s on node %s, will try to delete it\", pod.Namespace, pod.Name, node.Name)\n\t\t\t\tlogger.V(2).Info(\"Found succeeded daemon pod on node, will try to delete it\", \"pod\", klog.KObj(pod), \"node\", klog.KObj(node))\n\t\t\t\t// Emit an event so that it's discoverable to users.\n\t\t\t\tdsc.eventRecorder.Eventf(ds, v1.EventTypeNormal, SucceededDaemonPodReason, msg)\n\t\t\t\tpodsToDelete = append(podsToDelete, pod.Name)\n\t\t\t} else {\n\t\t\t\tdaemonPodsRunning = append(daemonPodsRunning, pod)\n\t\t\t}\n\t\t}\n\n\t\t// When surge is not enabled, if there is more than 1 running pod on a node delete all but the oldest\n\t\tif !util.AllowsSurge(ds) {\n\t\t\tif len(daemonPodsRunning) \u003c= 1 {\n\t\t\t\t// There are no excess pods to be pruned, and no pods to create\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tsort.Sort(podByCreationTimestampAndPhase(daemonPodsRunning))\n\t\t\tfor i := 1; i \u003c len(daemonPodsRunning); i++ {\n\t\t\t\tpodsToDelete = append(podsToDelete, daemonPodsRunning[i].Name)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tif len(daemonPodsRunning) \u003c= 1 {\n\t\t\t// // There are no excess pods to be pruned\n\t\t\tif len(daemonPodsRunning) == 0 \u0026\u0026 shouldRun {\n\t\t\t\t// We are surging so we need to have at least one non-deleted pod on the node\n\t\t\t\tnodesNeedingDaemonPods = append(nodesNeedingDaemonPods, node.Name)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\t// When surge is enabled, we allow 2 pods if and only if the oldest pod matching the current hash state\n\t\t// is not ready AND the oldest pod that doesn't match the current hash state is ready. All other pods are\n\t\t// deleted. If neither pod is ready, only the one matching the current hash revision is kept.\n\t\tvar oldestNewPod, oldestOldPod *v1.Pod\n\t\tsort.Sort(podByCreationTimestampAndPhase(daemonPodsRunning))\n\t\tfor _, pod := range daemonPodsRunning {\n\t\t\tif pod.Labels[apps.ControllerRevisionHashLabelKey] == hash {\n\t\t\t\tif oldestNewPod == nil {\n\t\t\t\t\toldestNewPod = pod\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif oldestOldPod == nil {\n\t\t\t\t\toldestOldPod = pod\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tpodsToDelete = append(podsToDelete, pod.Name)\n\t\t}\n\t\tif oldestNewPod != nil \u0026\u0026 oldestOldPod != nil {\n\t\t\tswitch {\n\t\t\tcase !podutil.IsPodReady(oldestOldPod):\n\t\t\t\tlogger.V(5).Info(\"Pod from daemonset is no longer ready and will be replaced with newer pod\", \"oldPod\", klog.KObj(oldestOldPod), \"daemonset\", klog.KObj(ds), \"newPod\", klog.KObj(oldestNewPod))\n\t\t\t\tpodsToDelete = append(podsToDelete, oldestOldPod.Name)\n\t\t\tcase podutil.IsPodAvailable(oldestNewPod, ds.Spec.MinReadySeconds, metav1.Time{Time: dsc.failedPodsBackoff.Clock.Now()}):\n\t\t\t\tlogger.V(5).Info(\"Pod from daemonset is now ready and will replace older pod\", \"newPod\", klog.KObj(oldestNewPod), \"daemonset\", klog.KObj(ds), \"oldPod\", klog.KObj(oldestOldPod))\n\t\t\t\tpodsToDelete = append(podsToDelete, oldestOldPod.Name)\n\t\t\t}\n\t\t}\n\n\tcase !shouldContinueRunning \u0026\u0026 exists:\n\t\t// If daemon pod isn't supposed to run on node, but it is, delete all daemon pods on node.\n\t\tfor _, pod := range daemonPods {\n\t\t\tif pod.DeletionTimestamp != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpodsToDelete = append(podsToDelete, pod.Name)\n\t\t}\n\t}\n\n\treturn nodesNeedingDaemonPods, podsToDelete\n}","line":{"from":804,"to":928}} {"id":100003514,"name":"updateDaemonSet","signature":"func (dsc *DaemonSetsController) updateDaemonSet(ctx context.Context, ds *apps.DaemonSet, nodeList []*v1.Node, hash, key string, old []*apps.ControllerRevision) error","file":"pkg/controller/daemon/daemon_controller.go","code":"func (dsc *DaemonSetsController) updateDaemonSet(ctx context.Context, ds *apps.DaemonSet, nodeList []*v1.Node, hash, key string, old []*apps.ControllerRevision) error {\n\terr := dsc.manage(ctx, ds, nodeList, hash)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Process rolling updates if we're ready.\n\tif dsc.expectations.SatisfiedExpectations(key) {\n\t\tswitch ds.Spec.UpdateStrategy.Type {\n\t\tcase apps.OnDeleteDaemonSetStrategyType:\n\t\tcase apps.RollingUpdateDaemonSetStrategyType:\n\t\t\terr = dsc.rollingUpdate(ctx, ds, nodeList, hash)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = dsc.cleanupHistory(ctx, ds, old)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to clean up revisions of DaemonSet: %w\", err)\n\t}\n\n\treturn nil\n}","line":{"from":930,"to":954}} {"id":100003515,"name":"manage","signature":"func (dsc *DaemonSetsController) manage(ctx context.Context, ds *apps.DaemonSet, nodeList []*v1.Node, hash string) error","file":"pkg/controller/daemon/daemon_controller.go","code":"// manage manages the scheduling and running of Pods of ds on nodes.\n// After figuring out which nodes should run a Pod of ds but not yet running one and\n// which nodes should not run a Pod of ds but currently running one, it calls function\n// syncNodes with a list of pods to remove and a list of nodes to run a Pod of ds.\nfunc (dsc *DaemonSetsController) manage(ctx context.Context, ds *apps.DaemonSet, nodeList []*v1.Node, hash string) error {\n\t// Find out the pods which are created for the nodes by DaemonSet.\n\tnodeToDaemonPods, err := dsc.getNodesToDaemonPods(ctx, ds, false)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't get node to daemon pod mapping for daemon set %q: %v\", ds.Name, err)\n\t}\n\n\t// For each node, if the node is running the daemon pod but isn't supposed to, kill the daemon\n\t// pod. If the node is supposed to run the daemon pod, but isn't, create the daemon pod on the node.\n\tlogger := klog.FromContext(ctx)\n\tvar nodesNeedingDaemonPods, podsToDelete []string\n\tfor _, node := range nodeList {\n\t\tnodesNeedingDaemonPodsOnNode, podsToDeleteOnNode := dsc.podsShouldBeOnNode(\n\t\t\tlogger, node, nodeToDaemonPods, ds, hash)\n\n\t\tnodesNeedingDaemonPods = append(nodesNeedingDaemonPods, nodesNeedingDaemonPodsOnNode...)\n\t\tpodsToDelete = append(podsToDelete, podsToDeleteOnNode...)\n\t}\n\n\t// Remove unscheduled pods assigned to not existing nodes when daemonset pods are scheduled by scheduler.\n\t// If node doesn't exist then pods are never scheduled and can't be deleted by PodGCController.\n\tpodsToDelete = append(podsToDelete, getUnscheduledPodsWithoutNode(nodeList, nodeToDaemonPods)...)\n\n\t// Label new pods using the hash label value of the current history when creating them\n\tif err = dsc.syncNodes(ctx, ds, podsToDelete, nodesNeedingDaemonPods, hash); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":956,"to":989}} {"id":100003516,"name":"syncNodes","signature":"func (dsc *DaemonSetsController) syncNodes(ctx context.Context, ds *apps.DaemonSet, podsToDelete, nodesNeedingDaemonPods []string, hash string) error","file":"pkg/controller/daemon/daemon_controller.go","code":"// syncNodes deletes given pods and creates new daemon set pods on the given nodes\n// returns slice with errors if any\nfunc (dsc *DaemonSetsController) syncNodes(ctx context.Context, ds *apps.DaemonSet, podsToDelete, nodesNeedingDaemonPods []string, hash string) error {\n\t// We need to set expectations before creating/deleting pods to avoid race conditions.\n\tlogger := klog.FromContext(ctx)\n\tdsKey, err := controller.KeyFunc(ds)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't get key for object %#v: %v\", ds, err)\n\t}\n\n\tcreateDiff := len(nodesNeedingDaemonPods)\n\tdeleteDiff := len(podsToDelete)\n\n\tif createDiff \u003e dsc.burstReplicas {\n\t\tcreateDiff = dsc.burstReplicas\n\t}\n\tif deleteDiff \u003e dsc.burstReplicas {\n\t\tdeleteDiff = dsc.burstReplicas\n\t}\n\n\tdsc.expectations.SetExpectations(dsKey, createDiff, deleteDiff)\n\n\t// error channel to communicate back failures. make the buffer big enough to avoid any blocking\n\terrCh := make(chan error, createDiff+deleteDiff)\n\n\tlogger.V(4).Info(\"Nodes needing daemon pods for daemon set, creating\", \"daemonset\", klog.KObj(ds), \"needCount\", nodesNeedingDaemonPods, \"createCount\", createDiff)\n\tcreateWait := sync.WaitGroup{}\n\t// If the returned error is not nil we have a parse error.\n\t// The controller handles this via the hash.\n\tgeneration, err := util.GetTemplateGeneration(ds)\n\tif err != nil {\n\t\tgeneration = nil\n\t}\n\ttemplate := util.CreatePodTemplate(ds.Spec.Template, generation, hash)\n\t// Batch the pod creates. Batch sizes start at SlowStartInitialBatchSize\n\t// and double with each successful iteration in a kind of \"slow start\".\n\t// This handles attempts to start large numbers of pods that would\n\t// likely all fail with the same error. For example a project with a\n\t// low quota that attempts to create a large number of pods will be\n\t// prevented from spamming the API service with the pod create requests\n\t// after one of its pods fails. Conveniently, this also prevents the\n\t// event spam that those failures would generate.\n\tbatchSize := integer.IntMin(createDiff, controller.SlowStartInitialBatchSize)\n\tfor pos := 0; createDiff \u003e pos; batchSize, pos = integer.IntMin(2*batchSize, createDiff-(pos+batchSize)), pos+batchSize {\n\t\terrorCount := len(errCh)\n\t\tcreateWait.Add(batchSize)\n\t\tfor i := pos; i \u003c pos+batchSize; i++ {\n\t\t\tgo func(ix int) {\n\t\t\t\tdefer createWait.Done()\n\n\t\t\t\tpodTemplate := template.DeepCopy()\n\t\t\t\t// The pod's NodeAffinity will be updated to make sure the Pod is bound\n\t\t\t\t// to the target node by default scheduler. It is safe to do so because there\n\t\t\t\t// should be no conflicting node affinity with the target node.\n\t\t\t\tpodTemplate.Spec.Affinity = util.ReplaceDaemonSetPodNodeNameNodeAffinity(\n\t\t\t\t\tpodTemplate.Spec.Affinity, nodesNeedingDaemonPods[ix])\n\n\t\t\t\terr := dsc.podControl.CreatePods(ctx, ds.Namespace, podTemplate,\n\t\t\t\t\tds, metav1.NewControllerRef(ds, controllerKind))\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tif apierrors.HasStatusCause(err, v1.NamespaceTerminatingCause) {\n\t\t\t\t\t\t// If the namespace is being torn down, we can safely ignore\n\t\t\t\t\t\t// this error since all subsequent creations will fail.\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.V(2).Info(\"Failed creation, decrementing expectations for daemon set\", \"daemonset\", klog.KObj(ds))\n\t\t\t\t\tdsc.expectations.CreationObserved(dsKey)\n\t\t\t\t\terrCh \u003c- err\n\t\t\t\t\tutilruntime.HandleError(err)\n\t\t\t\t}\n\t\t\t}(i)\n\t\t}\n\t\tcreateWait.Wait()\n\t\t// any skipped pods that we never attempted to start shouldn't be expected.\n\t\tskippedPods := createDiff - (batchSize + pos)\n\t\tif errorCount \u003c len(errCh) \u0026\u0026 skippedPods \u003e 0 {\n\t\t\tlogger.V(2).Info(\"Slow-start failure. Skipping creation pods, decrementing expectations for daemon set\", \"skippedPods\", skippedPods, \"daemonset\", klog.KObj(ds))\n\t\t\tdsc.expectations.LowerExpectations(dsKey, skippedPods, 0)\n\t\t\t// The skipped pods will be retried later. The next controller resync will\n\t\t\t// retry the slow start process.\n\t\t\tbreak\n\t\t}\n\t}\n\n\tlogger.V(4).Info(\"Pods to delete for daemon set, deleting\", \"daemonset\", klog.KObj(ds), \"toDeleteCount\", podsToDelete, \"deleteCount\", deleteDiff)\n\tdeleteWait := sync.WaitGroup{}\n\tdeleteWait.Add(deleteDiff)\n\tfor i := 0; i \u003c deleteDiff; i++ {\n\t\tgo func(ix int) {\n\t\t\tdefer deleteWait.Done()\n\t\t\tif err := dsc.podControl.DeletePod(ctx, ds.Namespace, podsToDelete[ix], ds); err != nil {\n\t\t\t\tdsc.expectations.DeletionObserved(dsKey)\n\t\t\t\tif !apierrors.IsNotFound(err) {\n\t\t\t\t\tlogger.V(2).Info(\"Failed deletion, decremented expectations for daemon set\", \"daemonset\", klog.KObj(ds))\n\t\t\t\t\terrCh \u003c- err\n\t\t\t\t\tutilruntime.HandleError(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}(i)\n\t}\n\tdeleteWait.Wait()\n\n\t// collect errors if any for proper reporting/retry logic in the controller\n\terrors := []error{}\n\tclose(errCh)\n\tfor err := range errCh {\n\t\terrors = append(errors, err)\n\t}\n\treturn utilerrors.NewAggregate(errors)\n}","line":{"from":991,"to":1103}} {"id":100003517,"name":"storeDaemonSetStatus","signature":"func storeDaemonSetStatus(","file":"pkg/controller/daemon/daemon_controller.go","code":"func storeDaemonSetStatus(\n\tctx context.Context,\n\tdsClient unversionedapps.DaemonSetInterface,\n\tds *apps.DaemonSet, desiredNumberScheduled,\n\tcurrentNumberScheduled,\n\tnumberMisscheduled,\n\tnumberReady,\n\tupdatedNumberScheduled,\n\tnumberAvailable,\n\tnumberUnavailable int,\n\tupdateObservedGen bool) error {\n\tif int(ds.Status.DesiredNumberScheduled) == desiredNumberScheduled \u0026\u0026\n\t\tint(ds.Status.CurrentNumberScheduled) == currentNumberScheduled \u0026\u0026\n\t\tint(ds.Status.NumberMisscheduled) == numberMisscheduled \u0026\u0026\n\t\tint(ds.Status.NumberReady) == numberReady \u0026\u0026\n\t\tint(ds.Status.UpdatedNumberScheduled) == updatedNumberScheduled \u0026\u0026\n\t\tint(ds.Status.NumberAvailable) == numberAvailable \u0026\u0026\n\t\tint(ds.Status.NumberUnavailable) == numberUnavailable \u0026\u0026\n\t\tds.Status.ObservedGeneration \u003e= ds.Generation {\n\t\treturn nil\n\t}\n\n\ttoUpdate := ds.DeepCopy()\n\n\tvar updateErr, getErr error\n\tfor i := 0; ; i++ {\n\t\tif updateObservedGen {\n\t\t\ttoUpdate.Status.ObservedGeneration = ds.Generation\n\t\t}\n\t\ttoUpdate.Status.DesiredNumberScheduled = int32(desiredNumberScheduled)\n\t\ttoUpdate.Status.CurrentNumberScheduled = int32(currentNumberScheduled)\n\t\ttoUpdate.Status.NumberMisscheduled = int32(numberMisscheduled)\n\t\ttoUpdate.Status.NumberReady = int32(numberReady)\n\t\ttoUpdate.Status.UpdatedNumberScheduled = int32(updatedNumberScheduled)\n\t\ttoUpdate.Status.NumberAvailable = int32(numberAvailable)\n\t\ttoUpdate.Status.NumberUnavailable = int32(numberUnavailable)\n\n\t\tif _, updateErr = dsClient.UpdateStatus(ctx, toUpdate, metav1.UpdateOptions{}); updateErr == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\t// Stop retrying if we exceed statusUpdateRetries - the DaemonSet will be requeued with a rate limit.\n\t\tif i \u003e= StatusUpdateRetries {\n\t\t\tbreak\n\t\t}\n\t\t// Update the set with the latest resource version for the next poll\n\t\tif toUpdate, getErr = dsClient.Get(ctx, ds.Name, metav1.GetOptions{}); getErr != nil {\n\t\t\t// If the GET fails we can't trust status.Replicas anymore. This error\n\t\t\t// is bound to be more interesting than the update failure.\n\t\t\treturn getErr\n\t\t}\n\t}\n\treturn updateErr\n}","line":{"from":1105,"to":1158}} {"id":100003518,"name":"updateDaemonSetStatus","signature":"func (dsc *DaemonSetsController) updateDaemonSetStatus(ctx context.Context, ds *apps.DaemonSet, nodeList []*v1.Node, hash string, updateObservedGen bool) error","file":"pkg/controller/daemon/daemon_controller.go","code":"func (dsc *DaemonSetsController) updateDaemonSetStatus(ctx context.Context, ds *apps.DaemonSet, nodeList []*v1.Node, hash string, updateObservedGen bool) error {\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"Updating daemon set status\")\n\tnodeToDaemonPods, err := dsc.getNodesToDaemonPods(ctx, ds, false)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't get node to daemon pod mapping for daemon set %q: %v\", ds.Name, err)\n\t}\n\n\tvar desiredNumberScheduled, currentNumberScheduled, numberMisscheduled, numberReady, updatedNumberScheduled, numberAvailable int\n\tnow := dsc.failedPodsBackoff.Clock.Now()\n\tfor _, node := range nodeList {\n\t\tshouldRun, _ := NodeShouldRunDaemonPod(node, ds)\n\t\tscheduled := len(nodeToDaemonPods[node.Name]) \u003e 0\n\n\t\tif shouldRun {\n\t\t\tdesiredNumberScheduled++\n\t\t\tif !scheduled {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcurrentNumberScheduled++\n\t\t\t// Sort the daemon pods by creation time, so that the oldest is first.\n\t\t\tdaemonPods, _ := nodeToDaemonPods[node.Name]\n\t\t\tsort.Sort(podByCreationTimestampAndPhase(daemonPods))\n\t\t\tpod := daemonPods[0]\n\t\t\tif podutil.IsPodReady(pod) {\n\t\t\t\tnumberReady++\n\t\t\t\tif podutil.IsPodAvailable(pod, ds.Spec.MinReadySeconds, metav1.Time{Time: now}) {\n\t\t\t\t\tnumberAvailable++\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If the returned error is not nil we have a parse error.\n\t\t\t// The controller handles this via the hash.\n\t\t\tgeneration, err := util.GetTemplateGeneration(ds)\n\t\t\tif err != nil {\n\t\t\t\tgeneration = nil\n\t\t\t}\n\t\t\tif util.IsPodUpdated(pod, hash, generation) {\n\t\t\t\tupdatedNumberScheduled++\n\t\t\t}\n\t\t} else {\n\t\t\tif scheduled {\n\t\t\t\tnumberMisscheduled++\n\t\t\t}\n\t\t}\n\t}\n\tnumberUnavailable := desiredNumberScheduled - numberAvailable\n\n\terr = storeDaemonSetStatus(ctx, dsc.kubeClient.AppsV1().DaemonSets(ds.Namespace), ds, desiredNumberScheduled, currentNumberScheduled, numberMisscheduled, numberReady, updatedNumberScheduled, numberAvailable, numberUnavailable, updateObservedGen)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error storing status for daemon set %#v: %w\", ds, err)\n\t}\n\n\t// Resync the DaemonSet after MinReadySeconds as a last line of defense to guard against clock-skew.\n\tif ds.Spec.MinReadySeconds \u003e 0 \u0026\u0026 numberReady != numberAvailable {\n\t\tdsc.enqueueDaemonSetAfter(ds, time.Duration(ds.Spec.MinReadySeconds)*time.Second)\n\t}\n\treturn nil\n}","line":{"from":1160,"to":1218}} {"id":100003519,"name":"syncDaemonSet","signature":"func (dsc *DaemonSetsController) syncDaemonSet(ctx context.Context, key string) error","file":"pkg/controller/daemon/daemon_controller.go","code":"func (dsc *DaemonSetsController) syncDaemonSet(ctx context.Context, key string) error {\n\tlogger := klog.FromContext(ctx)\n\tstartTime := dsc.failedPodsBackoff.Clock.Now()\n\n\tdefer func() {\n\t\tlogger.V(4).Info(\"Finished syncing daemon set\", \"daemonset\", key, \"time\", dsc.failedPodsBackoff.Clock.Now().Sub(startTime))\n\t}()\n\n\tnamespace, name, err := cache.SplitMetaNamespaceKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tds, err := dsc.dsLister.DaemonSets(namespace).Get(name)\n\tif apierrors.IsNotFound(err) {\n\t\tlogger.V(3).Info(\"Daemon set has been deleted\", \"daemonset\", key)\n\t\tdsc.expectations.DeleteExpectations(key)\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to retrieve ds %v from store: %v\", key, err)\n\t}\n\n\tnodeList, err := dsc.nodeLister.List(labels.Everything())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't get list of nodes when syncing daemon set %#v: %v\", ds, err)\n\t}\n\n\teverything := metav1.LabelSelector{}\n\tif reflect.DeepEqual(ds.Spec.Selector, \u0026everything) {\n\t\tdsc.eventRecorder.Eventf(ds, v1.EventTypeWarning, SelectingAllReason, \"This daemon set is selecting all pods. A non-empty selector is required.\")\n\t\treturn nil\n\t}\n\n\t// Don't process a daemon set until all its creations and deletions have been processed.\n\t// For example if daemon set foo asked for 3 new daemon pods in the previous call to manage,\n\t// then we do not want to call manage on foo until the daemon pods have been created.\n\tdsKey, err := controller.KeyFunc(ds)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't get key for object %#v: %v\", ds, err)\n\t}\n\n\t// If the DaemonSet is being deleted (either by foreground deletion or\n\t// orphan deletion), we cannot be sure if the DaemonSet history objects\n\t// it owned still exist -- those history objects can either be deleted\n\t// or orphaned. Garbage collector doesn't guarantee that it will delete\n\t// DaemonSet pods before deleting DaemonSet history objects, because\n\t// DaemonSet history doesn't own DaemonSet pods. We cannot reliably\n\t// calculate the status of a DaemonSet being deleted. Therefore, return\n\t// here without updating status for the DaemonSet being deleted.\n\tif ds.DeletionTimestamp != nil {\n\t\treturn nil\n\t}\n\n\t// Construct histories of the DaemonSet, and get the hash of current history\n\tcur, old, err := dsc.constructHistory(ctx, ds)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to construct revisions of DaemonSet: %v\", err)\n\t}\n\thash := cur.Labels[apps.DefaultDaemonSetUniqueLabelKey]\n\n\tif !dsc.expectations.SatisfiedExpectations(dsKey) {\n\t\t// Only update status. Don't raise observedGeneration since controller didn't process object of that generation.\n\t\treturn dsc.updateDaemonSetStatus(ctx, ds, nodeList, hash, false)\n\t}\n\n\terr = dsc.updateDaemonSet(ctx, ds, nodeList, hash, dsKey, old)\n\tstatusErr := dsc.updateDaemonSetStatus(ctx, ds, nodeList, hash, true)\n\tswitch {\n\tcase err != nil \u0026\u0026 statusErr != nil:\n\t\t// If there was an error, and we failed to update status,\n\t\t// log it and return the original error.\n\t\tlogger.Error(statusErr, \"Failed to update status\", \"daemonSet\", klog.KObj(ds))\n\t\treturn err\n\tcase err != nil:\n\t\treturn err\n\tcase statusErr != nil:\n\t\treturn statusErr\n\t}\n\n\treturn nil\n}","line":{"from":1220,"to":1300}} {"id":100003520,"name":"NodeShouldRunDaemonPod","signature":"func NodeShouldRunDaemonPod(node *v1.Node, ds *apps.DaemonSet) (bool, bool)","file":"pkg/controller/daemon/daemon_controller.go","code":"// NodeShouldRunDaemonPod checks a set of preconditions against a (node,daemonset) and returns a\n// summary. Returned booleans are:\n// - shouldRun:\n// Returns true when a daemonset should run on the node if a daemonset pod is not already\n// running on that node.\n// - shouldContinueRunning:\n// Returns true when a daemonset should continue running on a node if a daemonset pod is already\n// running on that node.\nfunc NodeShouldRunDaemonPod(node *v1.Node, ds *apps.DaemonSet) (bool, bool) {\n\tpod := NewPod(ds, node.Name)\n\n\t// If the daemon set specifies a node name, check that it matches with node.Name.\n\tif !(ds.Spec.Template.Spec.NodeName == \"\" || ds.Spec.Template.Spec.NodeName == node.Name) {\n\t\treturn false, false\n\t}\n\n\ttaints := node.Spec.Taints\n\tfitsNodeName, fitsNodeAffinity, fitsTaints := predicates(pod, node, taints)\n\tif !fitsNodeName || !fitsNodeAffinity {\n\t\treturn false, false\n\t}\n\n\tif !fitsTaints {\n\t\t// Scheduled daemon pods should continue running if they tolerate NoExecute taint.\n\t\t_, hasUntoleratedTaint := v1helper.FindMatchingUntoleratedTaint(taints, pod.Spec.Tolerations, func(t *v1.Taint) bool {\n\t\t\treturn t.Effect == v1.TaintEffectNoExecute\n\t\t})\n\t\treturn false, !hasUntoleratedTaint\n\t}\n\n\treturn true, true\n}","line":{"from":1302,"to":1333}} {"id":100003521,"name":"predicates","signature":"func predicates(pod *v1.Pod, node *v1.Node, taints []v1.Taint) (fitsNodeName, fitsNodeAffinity, fitsTaints bool)","file":"pkg/controller/daemon/daemon_controller.go","code":"// predicates checks if a DaemonSet's pod can run on a node.\nfunc predicates(pod *v1.Pod, node *v1.Node, taints []v1.Taint) (fitsNodeName, fitsNodeAffinity, fitsTaints bool) {\n\tfitsNodeName = len(pod.Spec.NodeName) == 0 || pod.Spec.NodeName == node.Name\n\t// Ignore parsing errors for backwards compatibility.\n\tfitsNodeAffinity, _ = nodeaffinity.GetRequiredNodeAffinity(pod).Match(node)\n\t_, hasUntoleratedTaint := v1helper.FindMatchingUntoleratedTaint(taints, pod.Spec.Tolerations, func(t *v1.Taint) bool {\n\t\treturn t.Effect == v1.TaintEffectNoExecute || t.Effect == v1.TaintEffectNoSchedule\n\t})\n\tfitsTaints = !hasUntoleratedTaint\n\treturn\n}","line":{"from":1335,"to":1345}} {"id":100003522,"name":"NewPod","signature":"func NewPod(ds *apps.DaemonSet, nodeName string) *v1.Pod","file":"pkg/controller/daemon/daemon_controller.go","code":"// NewPod creates a new pod\nfunc NewPod(ds *apps.DaemonSet, nodeName string) *v1.Pod {\n\tnewPod := \u0026v1.Pod{Spec: ds.Spec.Template.Spec, ObjectMeta: ds.Spec.Template.ObjectMeta}\n\tnewPod.Namespace = ds.Namespace\n\tnewPod.Spec.NodeName = nodeName\n\n\t// Added default tolerations for DaemonSet pods.\n\tutil.AddOrUpdateDaemonPodTolerations(\u0026newPod.Spec)\n\n\treturn newPod\n}","line":{"from":1347,"to":1357}} {"id":100003523,"name":"Len","signature":"func (o podByCreationTimestampAndPhase) Len() int { return len(o) }","file":"pkg/controller/daemon/daemon_controller.go","code":"func (o podByCreationTimestampAndPhase) Len() int { return len(o) }","line":{"from":1361,"to":1361}} {"id":100003524,"name":"Swap","signature":"func (o podByCreationTimestampAndPhase) Swap(i, j int) { o[i], o[j] = o[j], o[i] }","file":"pkg/controller/daemon/daemon_controller.go","code":"func (o podByCreationTimestampAndPhase) Swap(i, j int) { o[i], o[j] = o[j], o[i] }","line":{"from":1362,"to":1362}} {"id":100003525,"name":"Less","signature":"func (o podByCreationTimestampAndPhase) Less(i, j int) bool","file":"pkg/controller/daemon/daemon_controller.go","code":"func (o podByCreationTimestampAndPhase) Less(i, j int) bool {\n\t// Scheduled Pod first\n\tif len(o[i].Spec.NodeName) != 0 \u0026\u0026 len(o[j].Spec.NodeName) == 0 {\n\t\treturn true\n\t}\n\n\tif len(o[i].Spec.NodeName) == 0 \u0026\u0026 len(o[j].Spec.NodeName) != 0 {\n\t\treturn false\n\t}\n\n\tif o[i].CreationTimestamp.Equal(\u0026o[j].CreationTimestamp) {\n\t\treturn o[i].Name \u003c o[j].Name\n\t}\n\treturn o[i].CreationTimestamp.Before(\u0026o[j].CreationTimestamp)\n}","line":{"from":1364,"to":1378}} {"id":100003526,"name":"failedPodsBackoffKey","signature":"func failedPodsBackoffKey(ds *apps.DaemonSet, nodeName string) string","file":"pkg/controller/daemon/daemon_controller.go","code":"func failedPodsBackoffKey(ds *apps.DaemonSet, nodeName string) string {\n\treturn fmt.Sprintf(\"%s/%d/%s\", ds.UID, ds.Status.ObservedGeneration, nodeName)\n}","line":{"from":1380,"to":1382}} {"id":100003527,"name":"getUnscheduledPodsWithoutNode","signature":"func getUnscheduledPodsWithoutNode(runningNodesList []*v1.Node, nodeToDaemonPods map[string][]*v1.Pod) []string","file":"pkg/controller/daemon/daemon_controller.go","code":"// getUnscheduledPodsWithoutNode returns list of unscheduled pods assigned to not existing nodes.\n// Returned pods can't be deleted by PodGCController so they should be deleted by DaemonSetController.\nfunc getUnscheduledPodsWithoutNode(runningNodesList []*v1.Node, nodeToDaemonPods map[string][]*v1.Pod) []string {\n\tvar results []string\n\tisNodeRunning := make(map[string]bool, len(runningNodesList))\n\tfor _, node := range runningNodesList {\n\t\tisNodeRunning[node.Name] = true\n\t}\n\n\tfor n, pods := range nodeToDaemonPods {\n\t\tif isNodeRunning[n] {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, pod := range pods {\n\t\t\tif len(pod.Spec.NodeName) == 0 {\n\t\t\t\tresults = append(results, pod.Name)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn results\n}","line":{"from":1384,"to":1405}} {"id":100003528,"name":"rollingUpdate","signature":"func (dsc *DaemonSetsController) rollingUpdate(ctx context.Context, ds *apps.DaemonSet, nodeList []*v1.Node, hash string) error","file":"pkg/controller/daemon/update.go","code":"// rollingUpdate identifies the set of old pods to delete, or additional pods to create on nodes,\n// remaining within the constraints imposed by the update strategy.\nfunc (dsc *DaemonSetsController) rollingUpdate(ctx context.Context, ds *apps.DaemonSet, nodeList []*v1.Node, hash string) error {\n\tlogger := klog.FromContext(ctx)\n\tnodeToDaemonPods, err := dsc.getNodesToDaemonPods(ctx, ds, false)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't get node to daemon pod mapping for daemon set %q: %v\", ds.Name, err)\n\t}\n\tmaxSurge, maxUnavailable, err := dsc.updatedDesiredNodeCounts(ctx, ds, nodeList, nodeToDaemonPods)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't get unavailable numbers: %v\", err)\n\t}\n\n\tnow := dsc.failedPodsBackoff.Clock.Now()\n\n\t// When not surging, we delete just enough pods to stay under the maxUnavailable limit, if any\n\t// are necessary, and let the core loop create new instances on those nodes.\n\t//\n\t// Assumptions:\n\t// * Expect manage loop to allow no more than one pod per node\n\t// * Expect manage loop will create new pods\n\t// * Expect manage loop will handle failed pods\n\t// * Deleted pods do not count as unavailable so that updates make progress when nodes are down\n\t// Invariants:\n\t// * The number of new pods that are unavailable must be less than maxUnavailable\n\t// * A node with an available old pod is a candidate for deletion if it does not violate other invariants\n\t//\n\tif maxSurge == 0 {\n\t\tvar numUnavailable int\n\t\tvar allowedReplacementPods []string\n\t\tvar candidatePodsToDelete []string\n\t\tfor nodeName, pods := range nodeToDaemonPods {\n\t\t\tnewPod, oldPod, ok := findUpdatedPodsOnNode(ds, pods, hash)\n\t\t\tif !ok {\n\t\t\t\t// let the manage loop clean up this node, and treat it as an unavailable node\n\t\t\t\tlogger.V(3).Info(\"DaemonSet has excess pods on node, skipping to allow the core loop to process\", \"daemonset\", klog.KObj(ds), \"node\", klog.KRef(\"\", nodeName))\n\t\t\t\tnumUnavailable++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tswitch {\n\t\t\tcase oldPod == nil \u0026\u0026 newPod == nil, oldPod != nil \u0026\u0026 newPod != nil:\n\t\t\t\t// the manage loop will handle creating or deleting the appropriate pod, consider this unavailable\n\t\t\t\tnumUnavailable++\n\t\t\tcase newPod != nil:\n\t\t\t\t// this pod is up to date, check its availability\n\t\t\t\tif !podutil.IsPodAvailable(newPod, ds.Spec.MinReadySeconds, metav1.Time{Time: now}) {\n\t\t\t\t\t// an unavailable new pod is counted against maxUnavailable\n\t\t\t\t\tnumUnavailable++\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\t// this pod is old, it is an update candidate\n\t\t\t\tswitch {\n\t\t\t\tcase !podutil.IsPodAvailable(oldPod, ds.Spec.MinReadySeconds, metav1.Time{Time: now}):\n\t\t\t\t\t// the old pod isn't available, so it needs to be replaced\n\t\t\t\t\tlogger.V(5).Info(\"DaemonSet pod on node is out of date and not available, allowing replacement\", \"daemonset\", klog.KObj(ds), \"pod\", klog.KObj(oldPod), \"node\", klog.KRef(\"\", nodeName))\n\t\t\t\t\t// record the replacement\n\t\t\t\t\tif allowedReplacementPods == nil {\n\t\t\t\t\t\tallowedReplacementPods = make([]string, 0, len(nodeToDaemonPods))\n\t\t\t\t\t}\n\t\t\t\t\tallowedReplacementPods = append(allowedReplacementPods, oldPod.Name)\n\t\t\t\tcase numUnavailable \u003e= maxUnavailable:\n\t\t\t\t\t// no point considering any other candidates\n\t\t\t\t\tcontinue\n\t\t\t\tdefault:\n\t\t\t\t\tlogger.V(5).Info(\"DaemonSet pod on node is out of date, this is a candidate to replace\", \"daemonset\", klog.KObj(ds), \"pod\", klog.KObj(oldPod), \"node\", klog.KRef(\"\", nodeName))\n\t\t\t\t\t// record the candidate\n\t\t\t\t\tif candidatePodsToDelete == nil {\n\t\t\t\t\t\tcandidatePodsToDelete = make([]string, 0, maxUnavailable)\n\t\t\t\t\t}\n\t\t\t\t\tcandidatePodsToDelete = append(candidatePodsToDelete, oldPod.Name)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// use any of the candidates we can, including the allowedReplacemnntPods\n\t\tlogger.V(5).Info(\"DaemonSet allowing replacements\", \"daemonset\", klog.KObj(ds), \"replacements\", len(allowedReplacementPods), \"maxUnavailable\", maxUnavailable, \"numUnavailable\", numUnavailable, \"candidates\", len(candidatePodsToDelete))\n\t\tremainingUnavailable := maxUnavailable - numUnavailable\n\t\tif remainingUnavailable \u003c 0 {\n\t\t\tremainingUnavailable = 0\n\t\t}\n\t\tif max := len(candidatePodsToDelete); remainingUnavailable \u003e max {\n\t\t\tremainingUnavailable = max\n\t\t}\n\t\toldPodsToDelete := append(allowedReplacementPods, candidatePodsToDelete[:remainingUnavailable]...)\n\n\t\treturn dsc.syncNodes(ctx, ds, oldPodsToDelete, nil, hash)\n\t}\n\n\t// When surging, we create new pods whenever an old pod is unavailable, and we can create up\n\t// to maxSurge extra pods\n\t//\n\t// Assumptions:\n\t// * Expect manage loop to allow no more than two pods per node, one old, one new\n\t// * Expect manage loop will create new pods if there are no pods on node\n\t// * Expect manage loop will handle failed pods\n\t// * Deleted pods do not count as unavailable so that updates make progress when nodes are down\n\t// Invariants:\n\t// * A node with an unavailable old pod is a candidate for immediate new pod creation\n\t// * An old available pod is deleted if a new pod is available\n\t// * No more than maxSurge new pods are created for old available pods at any one time\n\t//\n\tvar oldPodsToDelete []string\n\tvar candidateNewNodes []string\n\tvar allowedNewNodes []string\n\tvar numSurge int\n\n\tfor nodeName, pods := range nodeToDaemonPods {\n\t\tnewPod, oldPod, ok := findUpdatedPodsOnNode(ds, pods, hash)\n\t\tif !ok {\n\t\t\t// let the manage loop clean up this node, and treat it as a surge node\n\t\t\tlogger.V(3).Info(\"DaemonSet has excess pods on node, skipping to allow the core loop to process\", \"daemonset\", klog.KObj(ds), \"node\", klog.KRef(\"\", nodeName))\n\t\t\tnumSurge++\n\t\t\tcontinue\n\t\t}\n\t\tswitch {\n\t\tcase oldPod == nil:\n\t\t\t// we don't need to do anything to this node, the manage loop will handle it\n\t\tcase newPod == nil:\n\t\t\t// this is a surge candidate\n\t\t\tswitch {\n\t\t\tcase !podutil.IsPodAvailable(oldPod, ds.Spec.MinReadySeconds, metav1.Time{Time: now}):\n\t\t\t\t// the old pod isn't available, allow it to become a replacement\n\t\t\t\tlogger.V(5).Info(\"Pod on node is out of date and not available, allowing replacement\", \"daemonset\", klog.KObj(ds), \"pod\", klog.KObj(oldPod), \"node\", klog.KRef(\"\", nodeName))\n\t\t\t\t// record the replacement\n\t\t\t\tif allowedNewNodes == nil {\n\t\t\t\t\tallowedNewNodes = make([]string, 0, len(nodeToDaemonPods))\n\t\t\t\t}\n\t\t\t\tallowedNewNodes = append(allowedNewNodes, nodeName)\n\t\t\tcase numSurge \u003e= maxSurge:\n\t\t\t\t// no point considering any other candidates\n\t\t\t\tcontinue\n\t\t\tdefault:\n\t\t\t\tlogger.V(5).Info(\"DaemonSet pod on node is out of date, this is a surge candidate\", \"daemonset\", klog.KObj(ds), \"pod\", klog.KObj(oldPod), \"node\", klog.KRef(\"\", nodeName))\n\t\t\t\t// record the candidate\n\t\t\t\tif candidateNewNodes == nil {\n\t\t\t\t\tcandidateNewNodes = make([]string, 0, maxSurge)\n\t\t\t\t}\n\t\t\t\tcandidateNewNodes = append(candidateNewNodes, nodeName)\n\t\t\t}\n\t\tdefault:\n\t\t\t// we have already surged onto this node, determine our state\n\t\t\tif !podutil.IsPodAvailable(newPod, ds.Spec.MinReadySeconds, metav1.Time{Time: now}) {\n\t\t\t\t// we're waiting to go available here\n\t\t\t\tnumSurge++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// we're available, delete the old pod\n\t\t\tlogger.V(5).Info(\"DaemonSet pod on node is available, remove old pod\", \"daemonset\", klog.KObj(ds), \"newPod\", klog.KObj(newPod), \"node\", nodeName, \"oldPod\", klog.KObj(oldPod))\n\t\t\toldPodsToDelete = append(oldPodsToDelete, oldPod.Name)\n\t\t}\n\t}\n\n\t// use any of the candidates we can, including the allowedNewNodes\n\tlogger.V(5).Info(\"DaemonSet allowing replacements\", \"daemonset\", klog.KObj(ds), \"replacements\", len(allowedNewNodes), \"maxSurge\", maxSurge, \"numSurge\", numSurge, \"candidates\", len(candidateNewNodes))\n\tremainingSurge := maxSurge - numSurge\n\tif remainingSurge \u003c 0 {\n\t\tremainingSurge = 0\n\t}\n\tif max := len(candidateNewNodes); remainingSurge \u003e max {\n\t\tremainingSurge = max\n\t}\n\tnewNodesToCreate := append(allowedNewNodes, candidateNewNodes[:remainingSurge]...)\n\n\treturn dsc.syncNodes(ctx, ds, oldPodsToDelete, newNodesToCreate, hash)\n}","line":{"from":42,"to":206}} {"id":100003529,"name":"findUpdatedPodsOnNode","signature":"func findUpdatedPodsOnNode(ds *apps.DaemonSet, podsOnNode []*v1.Pod, hash string) (newPod, oldPod *v1.Pod, ok bool)","file":"pkg/controller/daemon/update.go","code":"// findUpdatedPodsOnNode looks at non-deleted pods on a given node and returns true if there\n// is at most one of each old and new pods, or false if there are multiples. We can skip\n// processing the particular node in those scenarios and let the manage loop prune the\n// excess pods for our next time around.\nfunc findUpdatedPodsOnNode(ds *apps.DaemonSet, podsOnNode []*v1.Pod, hash string) (newPod, oldPod *v1.Pod, ok bool) {\n\tfor _, pod := range podsOnNode {\n\t\tif pod.DeletionTimestamp != nil {\n\t\t\tcontinue\n\t\t}\n\t\tgeneration, err := util.GetTemplateGeneration(ds)\n\t\tif err != nil {\n\t\t\tgeneration = nil\n\t\t}\n\t\tif util.IsPodUpdated(pod, hash, generation) {\n\t\t\tif newPod != nil {\n\t\t\t\treturn nil, nil, false\n\t\t\t}\n\t\t\tnewPod = pod\n\t\t} else {\n\t\t\tif oldPod != nil {\n\t\t\t\treturn nil, nil, false\n\t\t\t}\n\t\t\toldPod = pod\n\t\t}\n\t}\n\treturn newPod, oldPod, true\n}","line":{"from":208,"to":234}} {"id":100003530,"name":"constructHistory","signature":"func (dsc *DaemonSetsController) constructHistory(ctx context.Context, ds *apps.DaemonSet) (cur *apps.ControllerRevision, old []*apps.ControllerRevision, err error)","file":"pkg/controller/daemon/update.go","code":"// constructHistory finds all histories controlled by the given DaemonSet, and\n// update current history revision number, or create current history if need to.\n// It also deduplicates current history, and adds missing unique labels to existing histories.\nfunc (dsc *DaemonSetsController) constructHistory(ctx context.Context, ds *apps.DaemonSet) (cur *apps.ControllerRevision, old []*apps.ControllerRevision, err error) {\n\tvar histories []*apps.ControllerRevision\n\tvar currentHistories []*apps.ControllerRevision\n\thistories, err = dsc.controlledHistories(ctx, ds)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tfor _, history := range histories {\n\t\t// Add the unique label if it's not already added to the history\n\t\t// We use history name instead of computing hash, so that we don't need to worry about hash collision\n\t\tif _, ok := history.Labels[apps.DefaultDaemonSetUniqueLabelKey]; !ok {\n\t\t\ttoUpdate := history.DeepCopy()\n\t\t\ttoUpdate.Labels[apps.DefaultDaemonSetUniqueLabelKey] = toUpdate.Name\n\t\t\thistory, err = dsc.kubeClient.AppsV1().ControllerRevisions(ds.Namespace).Update(ctx, toUpdate, metav1.UpdateOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t}\n\t\t// Compare histories with ds to separate cur and old history\n\t\tfound := false\n\t\tfound, err = Match(ds, history)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tif found {\n\t\t\tcurrentHistories = append(currentHistories, history)\n\t\t} else {\n\t\t\told = append(old, history)\n\t\t}\n\t}\n\n\tcurrRevision := maxRevision(old) + 1\n\tswitch len(currentHistories) {\n\tcase 0:\n\t\t// Create a new history if the current one isn't found\n\t\tcur, err = dsc.snapshot(ctx, ds, currRevision)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\tdefault:\n\t\tcur, err = dsc.dedupCurHistories(ctx, ds, currentHistories)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\t// Update revision number if necessary\n\t\tif cur.Revision \u003c currRevision {\n\t\t\ttoUpdate := cur.DeepCopy()\n\t\t\ttoUpdate.Revision = currRevision\n\t\t\t_, err = dsc.kubeClient.AppsV1().ControllerRevisions(ds.Namespace).Update(ctx, toUpdate, metav1.UpdateOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t}\n\t}\n\treturn cur, old, err\n}","line":{"from":236,"to":294}} {"id":100003531,"name":"cleanupHistory","signature":"func (dsc *DaemonSetsController) cleanupHistory(ctx context.Context, ds *apps.DaemonSet, old []*apps.ControllerRevision) error","file":"pkg/controller/daemon/update.go","code":"func (dsc *DaemonSetsController) cleanupHistory(ctx context.Context, ds *apps.DaemonSet, old []*apps.ControllerRevision) error {\n\t// Include deleted terminal pods when maintaining history.\n\tnodesToDaemonPods, err := dsc.getNodesToDaemonPods(ctx, ds, true)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't get node to daemon pod mapping for daemon set %q: %v\", ds.Name, err)\n\t}\n\n\ttoKeep := int(*ds.Spec.RevisionHistoryLimit)\n\ttoKill := len(old) - toKeep\n\tif toKill \u003c= 0 {\n\t\treturn nil\n\t}\n\n\t// Find all hashes of live pods\n\tliveHashes := make(map[string]bool)\n\tfor _, pods := range nodesToDaemonPods {\n\t\tfor _, pod := range pods {\n\t\t\tif hash := pod.Labels[apps.DefaultDaemonSetUniqueLabelKey]; len(hash) \u003e 0 {\n\t\t\t\tliveHashes[hash] = true\n\t\t\t}\n\t\t}\n\t}\n\n\t// Clean up old history from smallest to highest revision (from oldest to newest)\n\tsort.Sort(historiesByRevision(old))\n\tfor _, history := range old {\n\t\tif toKill \u003c= 0 {\n\t\t\tbreak\n\t\t}\n\t\tif hash := history.Labels[apps.DefaultDaemonSetUniqueLabelKey]; liveHashes[hash] {\n\t\t\tcontinue\n\t\t}\n\t\t// Clean up\n\t\terr := dsc.kubeClient.AppsV1().ControllerRevisions(ds.Namespace).Delete(ctx, history.Name, metav1.DeleteOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttoKill--\n\t}\n\treturn nil\n}","line":{"from":296,"to":336}} {"id":100003532,"name":"maxRevision","signature":"func maxRevision(histories []*apps.ControllerRevision) int64","file":"pkg/controller/daemon/update.go","code":"// maxRevision returns the max revision number of the given list of histories\nfunc maxRevision(histories []*apps.ControllerRevision) int64 {\n\tmax := int64(0)\n\tfor _, history := range histories {\n\t\tif history.Revision \u003e max {\n\t\t\tmax = history.Revision\n\t\t}\n\t}\n\treturn max\n}","line":{"from":338,"to":347}} {"id":100003533,"name":"dedupCurHistories","signature":"func (dsc *DaemonSetsController) dedupCurHistories(ctx context.Context, ds *apps.DaemonSet, curHistories []*apps.ControllerRevision) (*apps.ControllerRevision, error)","file":"pkg/controller/daemon/update.go","code":"func (dsc *DaemonSetsController) dedupCurHistories(ctx context.Context, ds *apps.DaemonSet, curHistories []*apps.ControllerRevision) (*apps.ControllerRevision, error) {\n\tif len(curHistories) == 1 {\n\t\treturn curHistories[0], nil\n\t}\n\tvar maxRevision int64\n\tvar keepCur *apps.ControllerRevision\n\tfor _, cur := range curHistories {\n\t\tif cur.Revision \u003e= maxRevision {\n\t\t\tkeepCur = cur\n\t\t\tmaxRevision = cur.Revision\n\t\t}\n\t}\n\t// Clean up duplicates and relabel pods\n\tfor _, cur := range curHistories {\n\t\tif cur.Name == keepCur.Name {\n\t\t\tcontinue\n\t\t}\n\t\t// Relabel pods before dedup\n\t\tpods, err := dsc.getDaemonPods(ctx, ds)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, pod := range pods {\n\t\t\tif pod.Labels[apps.DefaultDaemonSetUniqueLabelKey] != keepCur.Labels[apps.DefaultDaemonSetUniqueLabelKey] {\n\t\t\t\tpatchRaw := map[string]interface{}{\n\t\t\t\t\t\"metadata\": map[string]interface{}{\n\t\t\t\t\t\t\"labels\": map[string]interface{}{\n\t\t\t\t\t\t\tapps.DefaultDaemonSetUniqueLabelKey: keepCur.Labels[apps.DefaultDaemonSetUniqueLabelKey],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tpatchJson, err := json.Marshal(patchRaw)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\t_, err = dsc.kubeClient.CoreV1().Pods(ds.Namespace).Patch(ctx, pod.Name, types.MergePatchType, patchJson, metav1.PatchOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Remove duplicates\n\t\terr = dsc.kubeClient.AppsV1().ControllerRevisions(ds.Namespace).Delete(ctx, cur.Name, metav1.DeleteOptions{})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn keepCur, nil\n}","line":{"from":349,"to":397}} {"id":100003534,"name":"controlledHistories","signature":"func (dsc *DaemonSetsController) controlledHistories(ctx context.Context, ds *apps.DaemonSet) ([]*apps.ControllerRevision, error)","file":"pkg/controller/daemon/update.go","code":"// controlledHistories returns all ControllerRevisions controlled by the given DaemonSet.\n// This also reconciles ControllerRef by adopting/orphaning.\n// Note that returned histories are pointers to objects in the cache.\n// If you want to modify one, you need to deep-copy it first.\nfunc (dsc *DaemonSetsController) controlledHistories(ctx context.Context, ds *apps.DaemonSet) ([]*apps.ControllerRevision, error) {\n\tselector, err := metav1.LabelSelectorAsSelector(ds.Spec.Selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// List all histories to include those that don't match the selector anymore\n\t// but have a ControllerRef pointing to the controller.\n\thistories, err := dsc.historyLister.ControllerRevisions(ds.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// If any adoptions are attempted, we should first recheck for deletion with\n\t// an uncached quorum read sometime after listing Pods (see #42639).\n\tcanAdoptFunc := controller.RecheckDeletionTimestamp(func(ctx context.Context) (metav1.Object, error) {\n\t\tfresh, err := dsc.kubeClient.AppsV1().DaemonSets(ds.Namespace).Get(ctx, ds.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif fresh.UID != ds.UID {\n\t\t\treturn nil, fmt.Errorf(\"original DaemonSet %v/%v is gone: got uid %v, wanted %v\", ds.Namespace, ds.Name, fresh.UID, ds.UID)\n\t\t}\n\t\treturn fresh, nil\n\t})\n\t// Use ControllerRefManager to adopt/orphan as needed.\n\tcm := controller.NewControllerRevisionControllerRefManager(dsc.crControl, ds, selector, controllerKind, canAdoptFunc)\n\treturn cm.ClaimControllerRevisions(ctx, histories)\n}","line":{"from":399,"to":430}} {"id":100003535,"name":"Match","signature":"func Match(ds *apps.DaemonSet, history *apps.ControllerRevision) (bool, error)","file":"pkg/controller/daemon/update.go","code":"// Match check if the given DaemonSet's template matches the template stored in the given history.\nfunc Match(ds *apps.DaemonSet, history *apps.ControllerRevision) (bool, error) {\n\tpatch, err := getPatch(ds)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn bytes.Equal(patch, history.Data.Raw), nil\n}","line":{"from":432,"to":439}} {"id":100003536,"name":"getPatch","signature":"func getPatch(ds *apps.DaemonSet) ([]byte, error)","file":"pkg/controller/daemon/update.go","code":"// getPatch returns a strategic merge patch that can be applied to restore a Daemonset to a\n// previous version. If the returned error is nil the patch is valid. The current state that we save is just the\n// PodSpecTemplate. We can modify this later to encompass more state (or less) and remain compatible with previously\n// recorded patches.\nfunc getPatch(ds *apps.DaemonSet) ([]byte, error) {\n\tdsBytes, err := json.Marshal(ds)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar raw map[string]interface{}\n\terr = json.Unmarshal(dsBytes, \u0026raw)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tobjCopy := make(map[string]interface{})\n\tspecCopy := make(map[string]interface{})\n\n\t// Create a patch of the DaemonSet that replaces spec.template\n\tspec := raw[\"spec\"].(map[string]interface{})\n\ttemplate := spec[\"template\"].(map[string]interface{})\n\tspecCopy[\"template\"] = template\n\ttemplate[\"$patch\"] = \"replace\"\n\tobjCopy[\"spec\"] = specCopy\n\tpatch, err := json.Marshal(objCopy)\n\treturn patch, err\n}","line":{"from":441,"to":466}} {"id":100003537,"name":"snapshot","signature":"func (dsc *DaemonSetsController) snapshot(ctx context.Context, ds *apps.DaemonSet, revision int64) (*apps.ControllerRevision, error)","file":"pkg/controller/daemon/update.go","code":"func (dsc *DaemonSetsController) snapshot(ctx context.Context, ds *apps.DaemonSet, revision int64) (*apps.ControllerRevision, error) {\n\tpatch, err := getPatch(ds)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thash := controller.ComputeHash(\u0026ds.Spec.Template, ds.Status.CollisionCount)\n\tname := ds.Name + \"-\" + hash\n\thistory := \u0026apps.ControllerRevision{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: ds.Namespace,\n\t\t\tLabels: labelsutil.CloneAndAddLabel(ds.Spec.Template.Labels, apps.DefaultDaemonSetUniqueLabelKey, hash),\n\t\t\tAnnotations: ds.Annotations,\n\t\t\tOwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(ds, controllerKind)},\n\t\t},\n\t\tData: runtime.RawExtension{Raw: patch},\n\t\tRevision: revision,\n\t}\n\n\thistory, err = dsc.kubeClient.AppsV1().ControllerRevisions(ds.Namespace).Create(ctx, history, metav1.CreateOptions{})\n\tif outerErr := err; errors.IsAlreadyExists(outerErr) {\n\t\tlogger := klog.FromContext(ctx)\n\t\t// TODO: Is it okay to get from historyLister?\n\t\texistedHistory, getErr := dsc.kubeClient.AppsV1().ControllerRevisions(ds.Namespace).Get(ctx, name, metav1.GetOptions{})\n\t\tif getErr != nil {\n\t\t\treturn nil, getErr\n\t\t}\n\t\t// Check if we already created it\n\t\tdone, matchErr := Match(ds, existedHistory)\n\t\tif matchErr != nil {\n\t\t\treturn nil, matchErr\n\t\t}\n\t\tif done {\n\t\t\treturn existedHistory, nil\n\t\t}\n\n\t\t// Handle name collisions between different history\n\t\t// Get the latest DaemonSet from the API server to make sure collision count is only increased when necessary\n\t\tcurrDS, getErr := dsc.kubeClient.AppsV1().DaemonSets(ds.Namespace).Get(ctx, ds.Name, metav1.GetOptions{})\n\t\tif getErr != nil {\n\t\t\treturn nil, getErr\n\t\t}\n\t\t// If the collision count used to compute hash was in fact stale, there's no need to bump collision count; retry again\n\t\tif !reflect.DeepEqual(currDS.Status.CollisionCount, ds.Status.CollisionCount) {\n\t\t\treturn nil, fmt.Errorf(\"found a stale collision count (%d, expected %d) of DaemonSet %q while processing; will retry until it is updated\", ds.Status.CollisionCount, currDS.Status.CollisionCount, ds.Name)\n\t\t}\n\t\tif currDS.Status.CollisionCount == nil {\n\t\t\tcurrDS.Status.CollisionCount = new(int32)\n\t\t}\n\t\t*currDS.Status.CollisionCount++\n\t\t_, updateErr := dsc.kubeClient.AppsV1().DaemonSets(ds.Namespace).UpdateStatus(ctx, currDS, metav1.UpdateOptions{})\n\t\tif updateErr != nil {\n\t\t\treturn nil, updateErr\n\t\t}\n\t\tlogger.V(2).Info(\"Found a hash collision for DaemonSet - bumping collisionCount to resolve it\", \"daemonset\", klog.KObj(ds), \"collisionCount\", *currDS.Status.CollisionCount)\n\t\treturn nil, outerErr\n\t}\n\treturn history, err\n}","line":{"from":468,"to":526}} {"id":100003538,"name":"updatedDesiredNodeCounts","signature":"func (dsc *DaemonSetsController) updatedDesiredNodeCounts(ctx context.Context, ds *apps.DaemonSet, nodeList []*v1.Node, nodeToDaemonPods map[string][]*v1.Pod) (int, int, error)","file":"pkg/controller/daemon/update.go","code":"// updatedDesiredNodeCounts calculates the true number of allowed unavailable or surge pods and\n// updates the nodeToDaemonPods array to include an empty array for every node that is not scheduled.\nfunc (dsc *DaemonSetsController) updatedDesiredNodeCounts(ctx context.Context, ds *apps.DaemonSet, nodeList []*v1.Node, nodeToDaemonPods map[string][]*v1.Pod) (int, int, error) {\n\tvar desiredNumberScheduled int\n\tlogger := klog.FromContext(ctx)\n\tfor i := range nodeList {\n\t\tnode := nodeList[i]\n\t\twantToRun, _ := NodeShouldRunDaemonPod(node, ds)\n\t\tif !wantToRun {\n\t\t\tcontinue\n\t\t}\n\t\tdesiredNumberScheduled++\n\n\t\tif _, exists := nodeToDaemonPods[node.Name]; !exists {\n\t\t\tnodeToDaemonPods[node.Name] = nil\n\t\t}\n\t}\n\n\tmaxUnavailable, err := util.UnavailableCount(ds, desiredNumberScheduled)\n\tif err != nil {\n\t\treturn -1, -1, fmt.Errorf(\"invalid value for MaxUnavailable: %v\", err)\n\t}\n\n\tmaxSurge, err := util.SurgeCount(ds, desiredNumberScheduled)\n\tif err != nil {\n\t\treturn -1, -1, fmt.Errorf(\"invalid value for MaxSurge: %v\", err)\n\t}\n\n\t// if the daemonset returned with an impossible configuration, obey the default of unavailable=1 (in the\n\t// event the apiserver returns 0 for both surge and unavailability)\n\tif desiredNumberScheduled \u003e 0 \u0026\u0026 maxUnavailable == 0 \u0026\u0026 maxSurge == 0 {\n\t\tlogger.Info(\"DaemonSet is not configured for surge or unavailability, defaulting to accepting unavailability\", \"daemonset\", klog.KObj(ds))\n\t\tmaxUnavailable = 1\n\t}\n\tlogger.V(5).Info(\"DaemonSet with maxSurge and maxUnavailable\", \"daemonset\", klog.KObj(ds), \"maxSurge\", maxSurge, \"maxUnavailable\", maxUnavailable)\n\treturn maxSurge, maxUnavailable, nil\n}","line":{"from":528,"to":564}} {"id":100003539,"name":"Len","signature":"func (h historiesByRevision) Len() int { return len(h) }","file":"pkg/controller/daemon/update.go","code":"func (h historiesByRevision) Len() int { return len(h) }","line":{"from":568,"to":568}} {"id":100003540,"name":"Swap","signature":"func (h historiesByRevision) Swap(i, j int) { h[i], h[j] = h[j], h[i] }","file":"pkg/controller/daemon/update.go","code":"func (h historiesByRevision) Swap(i, j int) { h[i], h[j] = h[j], h[i] }","line":{"from":569,"to":569}} {"id":100003541,"name":"Less","signature":"func (h historiesByRevision) Less(i, j int) bool","file":"pkg/controller/daemon/update.go","code":"func (h historiesByRevision) Less(i, j int) bool {\n\treturn h[i].Revision \u003c h[j].Revision\n}","line":{"from":570,"to":572}} {"id":100003542,"name":"GetTemplateGeneration","signature":"func GetTemplateGeneration(ds *apps.DaemonSet) (*int64, error)","file":"pkg/controller/daemon/util/daemonset_util.go","code":"// GetTemplateGeneration gets the template generation associated with a v1.DaemonSet by extracting it from the\n// deprecated annotation. If no annotation is found nil is returned. If the annotation is found and fails to parse\n// nil is returned with an error. If the generation can be parsed from the annotation, a pointer to the parsed int64\n// value is returned.\nfunc GetTemplateGeneration(ds *apps.DaemonSet) (*int64, error) {\n\tannotation, found := ds.Annotations[apps.DeprecatedTemplateGeneration]\n\tif !found {\n\t\treturn nil, nil\n\t}\n\tgeneration, err := strconv.ParseInt(annotation, 10, 64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026generation, nil\n}","line":{"from":31,"to":45}} {"id":100003543,"name":"AddOrUpdateDaemonPodTolerations","signature":"func AddOrUpdateDaemonPodTolerations(spec *v1.PodSpec)","file":"pkg/controller/daemon/util/daemonset_util.go","code":"// AddOrUpdateDaemonPodTolerations apply necessary tolerations to DaemonSet Pods, e.g. node.kubernetes.io/not-ready:NoExecute.\nfunc AddOrUpdateDaemonPodTolerations(spec *v1.PodSpec) {\n\t// DaemonSet pods shouldn't be deleted by NodeController in case of node problems.\n\t// Add infinite toleration for taint notReady:NoExecute here\n\t// to survive taint-based eviction enforced by NodeController\n\t// when node turns not ready.\n\tv1helper.AddOrUpdateTolerationInPodSpec(spec, \u0026v1.Toleration{\n\t\tKey: v1.TaintNodeNotReady,\n\t\tOperator: v1.TolerationOpExists,\n\t\tEffect: v1.TaintEffectNoExecute,\n\t})\n\n\t// DaemonSet pods shouldn't be deleted by NodeController in case of node problems.\n\t// Add infinite toleration for taint unreachable:NoExecute here\n\t// to survive taint-based eviction enforced by NodeController\n\t// when node turns unreachable.\n\tv1helper.AddOrUpdateTolerationInPodSpec(spec, \u0026v1.Toleration{\n\t\tKey: v1.TaintNodeUnreachable,\n\t\tOperator: v1.TolerationOpExists,\n\t\tEffect: v1.TaintEffectNoExecute,\n\t})\n\n\t// According to TaintNodesByCondition feature, all DaemonSet pods should tolerate\n\t// MemoryPressure, DiskPressure, PIDPressure, Unschedulable and NetworkUnavailable taints.\n\tv1helper.AddOrUpdateTolerationInPodSpec(spec, \u0026v1.Toleration{\n\t\tKey: v1.TaintNodeDiskPressure,\n\t\tOperator: v1.TolerationOpExists,\n\t\tEffect: v1.TaintEffectNoSchedule,\n\t})\n\n\tv1helper.AddOrUpdateTolerationInPodSpec(spec, \u0026v1.Toleration{\n\t\tKey: v1.TaintNodeMemoryPressure,\n\t\tOperator: v1.TolerationOpExists,\n\t\tEffect: v1.TaintEffectNoSchedule,\n\t})\n\n\tv1helper.AddOrUpdateTolerationInPodSpec(spec, \u0026v1.Toleration{\n\t\tKey: v1.TaintNodePIDPressure,\n\t\tOperator: v1.TolerationOpExists,\n\t\tEffect: v1.TaintEffectNoSchedule,\n\t})\n\n\tv1helper.AddOrUpdateTolerationInPodSpec(spec, \u0026v1.Toleration{\n\t\tKey: v1.TaintNodeUnschedulable,\n\t\tOperator: v1.TolerationOpExists,\n\t\tEffect: v1.TaintEffectNoSchedule,\n\t})\n\n\tif spec.HostNetwork {\n\t\tv1helper.AddOrUpdateTolerationInPodSpec(spec, \u0026v1.Toleration{\n\t\t\tKey: v1.TaintNodeNetworkUnavailable,\n\t\t\tOperator: v1.TolerationOpExists,\n\t\t\tEffect: v1.TaintEffectNoSchedule,\n\t\t})\n\t}\n}","line":{"from":47,"to":102}} {"id":100003544,"name":"CreatePodTemplate","signature":"func CreatePodTemplate(template v1.PodTemplateSpec, generation *int64, hash string) v1.PodTemplateSpec","file":"pkg/controller/daemon/util/daemonset_util.go","code":"// CreatePodTemplate returns copy of provided template with additional\n// label which contains templateGeneration (for backward compatibility),\n// hash of provided template and sets default daemon tolerations.\nfunc CreatePodTemplate(template v1.PodTemplateSpec, generation *int64, hash string) v1.PodTemplateSpec {\n\tnewTemplate := *template.DeepCopy()\n\n\tAddOrUpdateDaemonPodTolerations(\u0026newTemplate.Spec)\n\n\tif newTemplate.ObjectMeta.Labels == nil {\n\t\tnewTemplate.ObjectMeta.Labels = make(map[string]string)\n\t}\n\tif generation != nil {\n\t\tnewTemplate.ObjectMeta.Labels[extensions.DaemonSetTemplateGenerationKey] = fmt.Sprint(*generation)\n\t}\n\t// TODO: do we need to validate if the DaemonSet is RollingUpdate or not?\n\tif len(hash) \u003e 0 {\n\t\tnewTemplate.ObjectMeta.Labels[extensions.DefaultDaemonSetUniqueLabelKey] = hash\n\t}\n\treturn newTemplate\n}","line":{"from":104,"to":123}} {"id":100003545,"name":"AllowsSurge","signature":"func AllowsSurge(ds *apps.DaemonSet) bool","file":"pkg/controller/daemon/util/daemonset_util.go","code":"// AllowsSurge returns true if the daemonset allows more than a single pod on any node.\nfunc AllowsSurge(ds *apps.DaemonSet) bool {\n\tmaxSurge, err := SurgeCount(ds, 1)\n\treturn err == nil \u0026\u0026 maxSurge \u003e 0\n}","line":{"from":125,"to":129}} {"id":100003546,"name":"SurgeCount","signature":"func SurgeCount(ds *apps.DaemonSet, numberToSchedule int) (int, error)","file":"pkg/controller/daemon/util/daemonset_util.go","code":"// SurgeCount returns 0 if surge is not requested, the expected surge number to allow\n// out of numberToSchedule if surge is configured, or an error if the surge percentage\n// requested is invalid.\nfunc SurgeCount(ds *apps.DaemonSet, numberToSchedule int) (int, error) {\n\tif ds.Spec.UpdateStrategy.Type != apps.RollingUpdateDaemonSetStrategyType {\n\t\treturn 0, nil\n\t}\n\n\tr := ds.Spec.UpdateStrategy.RollingUpdate\n\tif r == nil {\n\t\treturn 0, nil\n\t}\n\t// If surge is not requested, we should default to 0.\n\tif r.MaxSurge == nil {\n\t\treturn 0, nil\n\t}\n\treturn intstrutil.GetScaledValueFromIntOrPercent(r.MaxSurge, numberToSchedule, true)\n}","line":{"from":131,"to":148}} {"id":100003547,"name":"UnavailableCount","signature":"func UnavailableCount(ds *apps.DaemonSet, numberToSchedule int) (int, error)","file":"pkg/controller/daemon/util/daemonset_util.go","code":"// UnavailableCount returns 0 if unavailability is not requested, the expected\n// unavailability number to allow out of numberToSchedule if requested, or an error if\n// the unavailability percentage requested is invalid.\nfunc UnavailableCount(ds *apps.DaemonSet, numberToSchedule int) (int, error) {\n\tif ds.Spec.UpdateStrategy.Type != apps.RollingUpdateDaemonSetStrategyType {\n\t\treturn 0, nil\n\t}\n\tr := ds.Spec.UpdateStrategy.RollingUpdate\n\tif r == nil {\n\t\treturn 0, nil\n\t}\n\treturn intstrutil.GetScaledValueFromIntOrPercent(r.MaxUnavailable, numberToSchedule, true)\n}","line":{"from":150,"to":162}} {"id":100003548,"name":"IsPodUpdated","signature":"func IsPodUpdated(pod *v1.Pod, hash string, dsTemplateGeneration *int64) bool","file":"pkg/controller/daemon/util/daemonset_util.go","code":"// IsPodUpdated checks if pod contains label value that either matches templateGeneration or hash\nfunc IsPodUpdated(pod *v1.Pod, hash string, dsTemplateGeneration *int64) bool {\n\t// Compare with hash to see if the pod is updated, need to maintain backward compatibility of templateGeneration\n\ttemplateMatches := dsTemplateGeneration != nil \u0026\u0026\n\t\tpod.Labels[extensions.DaemonSetTemplateGenerationKey] == fmt.Sprint(*dsTemplateGeneration)\n\thashMatches := len(hash) \u003e 0 \u0026\u0026 pod.Labels[extensions.DefaultDaemonSetUniqueLabelKey] == hash\n\treturn hashMatches || templateMatches\n}","line":{"from":164,"to":171}} {"id":100003549,"name":"ReplaceDaemonSetPodNodeNameNodeAffinity","signature":"func ReplaceDaemonSetPodNodeNameNodeAffinity(affinity *v1.Affinity, nodename string) *v1.Affinity","file":"pkg/controller/daemon/util/daemonset_util.go","code":"// ReplaceDaemonSetPodNodeNameNodeAffinity replaces the RequiredDuringSchedulingIgnoredDuringExecution\n// NodeAffinity of the given affinity with a new NodeAffinity that selects the given nodeName.\n// Note that this function assumes that no NodeAffinity conflicts with the selected nodeName.\nfunc ReplaceDaemonSetPodNodeNameNodeAffinity(affinity *v1.Affinity, nodename string) *v1.Affinity {\n\tnodeSelReq := v1.NodeSelectorRequirement{\n\t\tKey: metav1.ObjectNameField,\n\t\tOperator: v1.NodeSelectorOpIn,\n\t\tValues: []string{nodename},\n\t}\n\n\tnodeSelector := \u0026v1.NodeSelector{\n\t\tNodeSelectorTerms: []v1.NodeSelectorTerm{\n\t\t\t{\n\t\t\t\tMatchFields: []v1.NodeSelectorRequirement{nodeSelReq},\n\t\t\t},\n\t\t},\n\t}\n\n\tif affinity == nil {\n\t\treturn \u0026v1.Affinity{\n\t\t\tNodeAffinity: \u0026v1.NodeAffinity{\n\t\t\t\tRequiredDuringSchedulingIgnoredDuringExecution: nodeSelector,\n\t\t\t},\n\t\t}\n\t}\n\n\tif affinity.NodeAffinity == nil {\n\t\taffinity.NodeAffinity = \u0026v1.NodeAffinity{\n\t\t\tRequiredDuringSchedulingIgnoredDuringExecution: nodeSelector,\n\t\t}\n\t\treturn affinity\n\t}\n\n\tnodeAffinity := affinity.NodeAffinity\n\n\tif nodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution == nil {\n\t\tnodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution = nodeSelector\n\t\treturn affinity\n\t}\n\n\t// Replace node selector with the new one.\n\tnodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution.NodeSelectorTerms = []v1.NodeSelectorTerm{\n\t\t{\n\t\t\tMatchFields: []v1.NodeSelectorRequirement{nodeSelReq},\n\t\t},\n\t}\n\n\treturn affinity\n}","line":{"from":173,"to":221}} {"id":100003550,"name":"GetTargetNodeName","signature":"func GetTargetNodeName(pod *v1.Pod) (string, error)","file":"pkg/controller/daemon/util/daemonset_util.go","code":"// GetTargetNodeName get the target node name of DaemonSet pods. If `.spec.NodeName` is not empty (nil),\n// return `.spec.NodeName`; otherwise, retrieve node name of pending pods from NodeAffinity. Return error\n// if failed to retrieve node name from `.spec.NodeName` and NodeAffinity.\nfunc GetTargetNodeName(pod *v1.Pod) (string, error) {\n\tif len(pod.Spec.NodeName) != 0 {\n\t\treturn pod.Spec.NodeName, nil\n\t}\n\n\t// Retrieve node name of unscheduled pods from NodeAffinity\n\tif pod.Spec.Affinity == nil ||\n\t\tpod.Spec.Affinity.NodeAffinity == nil ||\n\t\tpod.Spec.Affinity.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution == nil {\n\t\treturn \"\", fmt.Errorf(\"no spec.affinity.nodeAffinity.requiredDuringSchedulingIgnoredDuringExecution for pod %s/%s\",\n\t\t\tpod.Namespace, pod.Name)\n\t}\n\n\tterms := pod.Spec.Affinity.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution.NodeSelectorTerms\n\tif len(terms) \u003c 1 {\n\t\treturn \"\", fmt.Errorf(\"no nodeSelectorTerms in requiredDuringSchedulingIgnoredDuringExecution of pod %s/%s\",\n\t\t\tpod.Namespace, pod.Name)\n\t}\n\n\tfor _, term := range terms {\n\t\tfor _, exp := range term.MatchFields {\n\t\t\tif exp.Key == metav1.ObjectNameField \u0026\u0026\n\t\t\t\texp.Operator == v1.NodeSelectorOpIn {\n\t\t\t\tif len(exp.Values) != 1 {\n\t\t\t\t\treturn \"\", fmt.Errorf(\"the matchFields value of '%s' is not unique for pod %s/%s\",\n\t\t\t\t\t\tmetav1.ObjectNameField, pod.Namespace, pod.Name)\n\t\t\t\t}\n\n\t\t\t\treturn exp.Values[0], nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"no node name found for pod %s/%s\", pod.Namespace, pod.Name)\n}","line":{"from":223,"to":260}} {"id":100003551,"name":"Convert_v1alpha1_DeploymentControllerConfiguration_To_config_DeploymentControllerConfiguration","signature":"func Convert_v1alpha1_DeploymentControllerConfiguration_To_config_DeploymentControllerConfiguration(in *v1alpha1.DeploymentControllerConfiguration, out *deploymentconfig.DeploymentControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/deployment/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_DeploymentControllerConfiguration_To_config_DeploymentControllerConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_DeploymentControllerConfiguration_To_config_DeploymentControllerConfiguration(in *v1alpha1.DeploymentControllerConfiguration, out *deploymentconfig.DeploymentControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_DeploymentControllerConfiguration_To_config_DeploymentControllerConfiguration(in, out, s)\n}","line":{"from":32,"to":35}} {"id":100003552,"name":"Convert_config_DeploymentControllerConfiguration_To_v1alpha1_DeploymentControllerConfiguration","signature":"func Convert_config_DeploymentControllerConfiguration_To_v1alpha1_DeploymentControllerConfiguration(in *deploymentconfig.DeploymentControllerConfiguration, out *v1alpha1.DeploymentControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/deployment/config/v1alpha1/conversion.go","code":"// Convert_config_DeploymentControllerConfiguration_To_v1alpha1_DeploymentControllerConfiguration is an autogenerated conversion function.\nfunc Convert_config_DeploymentControllerConfiguration_To_v1alpha1_DeploymentControllerConfiguration(in *deploymentconfig.DeploymentControllerConfiguration, out *v1alpha1.DeploymentControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_DeploymentControllerConfiguration_To_v1alpha1_DeploymentControllerConfiguration(in, out, s)\n}","line":{"from":37,"to":40}} {"id":100003553,"name":"RecommendedDefaultDeploymentControllerConfiguration","signature":"func RecommendedDefaultDeploymentControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.DeploymentControllerConfiguration)","file":"pkg/controller/deployment/config/v1alpha1/defaults.go","code":"// RecommendedDefaultDeploymentControllerConfiguration defaults a pointer to a\n// DeploymentControllerConfiguration struct. This will set the recommended default\n// values, but they may be subject to change between API versions. This function\n// is intentionally not registered in the scheme as a \"normal\" `SetDefaults_Foo`\n// function to allow consumers of this type to set whatever defaults for their\n// embedded configs. Forcing consumers to use these defaults would be problematic\n// as defaulting in the scheme is done as part of the conversion, and there would\n// be no easy way to opt-out. Instead, if you want to use this defaulting method\n// run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDefaultDeploymentControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.DeploymentControllerConfiguration) {\n\tif obj.ConcurrentDeploymentSyncs == 0 {\n\t\tobj.ConcurrentDeploymentSyncs = 5\n\t}\n}","line":{"from":23,"to":36}} {"id":100003554,"name":"NewDeploymentController","signature":"func NewDeploymentController(ctx context.Context, dInformer appsinformers.DeploymentInformer, rsInformer appsinformers.ReplicaSetInformer, podInformer coreinformers.PodInformer, client clientset.Interface) (*DeploymentController, error)","file":"pkg/controller/deployment/deployment_controller.go","code":"// NewDeploymentController creates a new DeploymentController.\nfunc NewDeploymentController(ctx context.Context, dInformer appsinformers.DeploymentInformer, rsInformer appsinformers.ReplicaSetInformer, podInformer coreinformers.PodInformer, client clientset.Interface) (*DeploymentController, error) {\n\teventBroadcaster := record.NewBroadcaster()\n\tlogger := klog.FromContext(ctx)\n\tdc := \u0026DeploymentController{\n\t\tclient: client,\n\t\teventBroadcaster: eventBroadcaster,\n\t\teventRecorder: eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"deployment-controller\"}),\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"deployment\"),\n\t}\n\tdc.rsControl = controller.RealRSControl{\n\t\tKubeClient: client,\n\t\tRecorder: dc.eventRecorder,\n\t}\n\n\tdInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tdc.addDeployment(logger, obj)\n\t\t},\n\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\tdc.updateDeployment(logger, oldObj, newObj)\n\t\t},\n\t\t// This will enter the sync loop and no-op, because the deployment has been deleted from the store.\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tdc.deleteDeployment(logger, obj)\n\t\t},\n\t})\n\trsInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tdc.addReplicaSet(logger, obj)\n\t\t},\n\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\tdc.updateReplicaSet(logger, oldObj, newObj)\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tdc.deleteReplicaSet(logger, obj)\n\t\t},\n\t})\n\tpodInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tdc.deletePod(logger, obj)\n\t\t},\n\t})\n\n\tdc.syncHandler = dc.syncDeployment\n\tdc.enqueueDeployment = dc.enqueue\n\n\tdc.dLister = dInformer.Lister()\n\tdc.rsLister = rsInformer.Lister()\n\tdc.podLister = podInformer.Lister()\n\tdc.dListerSynced = dInformer.Informer().HasSynced\n\tdc.rsListerSynced = rsInformer.Informer().HasSynced\n\tdc.podListerSynced = podInformer.Informer().HasSynced\n\treturn dc, nil\n}","line":{"from":100,"to":154}} {"id":100003555,"name":"Run","signature":"func (dc *DeploymentController) Run(ctx context.Context, workers int)","file":"pkg/controller/deployment/deployment_controller.go","code":"// Run begins watching and syncing.\nfunc (dc *DeploymentController) Run(ctx context.Context, workers int) {\n\tdefer utilruntime.HandleCrash()\n\n\t// Start events processing pipeline.\n\tdc.eventBroadcaster.StartStructuredLogging(0)\n\tdc.eventBroadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: dc.client.CoreV1().Events(\"\")})\n\tdefer dc.eventBroadcaster.Shutdown()\n\n\tdefer dc.queue.ShutDown()\n\n\tlogger := klog.FromContext(ctx)\n\tlogger.Info(\"Starting controller\", \"controller\", \"deployment\")\n\tdefer logger.Info(\"Shutting down controller\", \"controller\", \"deployment\")\n\n\tif !cache.WaitForNamedCacheSync(\"deployment\", ctx.Done(), dc.dListerSynced, dc.rsListerSynced, dc.podListerSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.UntilWithContext(ctx, dc.worker, time.Second)\n\t}\n\n\t\u003c-ctx.Done()\n}","line":{"from":156,"to":180}} {"id":100003556,"name":"addDeployment","signature":"func (dc *DeploymentController) addDeployment(logger klog.Logger, obj interface{})","file":"pkg/controller/deployment/deployment_controller.go","code":"func (dc *DeploymentController) addDeployment(logger klog.Logger, obj interface{}) {\n\td := obj.(*apps.Deployment)\n\tlogger.V(4).Info(\"Adding deployment\", \"deployment\", klog.KObj(d))\n\tdc.enqueueDeployment(d)\n}","line":{"from":182,"to":186}} {"id":100003557,"name":"updateDeployment","signature":"func (dc *DeploymentController) updateDeployment(logger klog.Logger, old, cur interface{})","file":"pkg/controller/deployment/deployment_controller.go","code":"func (dc *DeploymentController) updateDeployment(logger klog.Logger, old, cur interface{}) {\n\toldD := old.(*apps.Deployment)\n\tcurD := cur.(*apps.Deployment)\n\tlogger.V(4).Info(\"Updating deployment\", \"deployment\", klog.KObj(oldD))\n\tdc.enqueueDeployment(curD)\n}","line":{"from":188,"to":193}} {"id":100003558,"name":"deleteDeployment","signature":"func (dc *DeploymentController) deleteDeployment(logger klog.Logger, obj interface{})","file":"pkg/controller/deployment/deployment_controller.go","code":"func (dc *DeploymentController) deleteDeployment(logger klog.Logger, obj interface{}) {\n\td, ok := obj.(*apps.Deployment)\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get object from tombstone %#v\", obj))\n\t\t\treturn\n\t\t}\n\t\td, ok = tombstone.Obj.(*apps.Deployment)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"tombstone contained object that is not a Deployment %#v\", obj))\n\t\t\treturn\n\t\t}\n\t}\n\tlogger.V(4).Info(\"Deleting deployment\", \"deployment\", klog.KObj(d))\n\tdc.enqueueDeployment(d)\n}","line":{"from":195,"to":211}} {"id":100003559,"name":"addReplicaSet","signature":"func (dc *DeploymentController) addReplicaSet(logger klog.Logger, obj interface{})","file":"pkg/controller/deployment/deployment_controller.go","code":"// addReplicaSet enqueues the deployment that manages a ReplicaSet when the ReplicaSet is created.\nfunc (dc *DeploymentController) addReplicaSet(logger klog.Logger, obj interface{}) {\n\trs := obj.(*apps.ReplicaSet)\n\n\tif rs.DeletionTimestamp != nil {\n\t\t// On a restart of the controller manager, it's possible for an object to\n\t\t// show up in a state that is already pending deletion.\n\t\tdc.deleteReplicaSet(logger, rs)\n\t\treturn\n\t}\n\t// If it has a ControllerRef, that's all that matters.\n\tif controllerRef := metav1.GetControllerOf(rs); controllerRef != nil {\n\t\td := dc.resolveControllerRef(rs.Namespace, controllerRef)\n\t\tif d == nil {\n\t\t\treturn\n\t\t}\n\t\tlogger.V(4).Info(\"ReplicaSet added\", \"replicaSet\", klog.KObj(rs))\n\t\tdc.enqueueDeployment(d)\n\t\treturn\n\t}\n\n\t// Otherwise, it's an orphan. Get a list of all matching Deployments and sync\n\t// them to see if anyone wants to adopt it.\n\tds := dc.getDeploymentsForReplicaSet(logger, rs)\n\tif len(ds) == 0 {\n\t\treturn\n\t}\n\tlogger.V(4).Info(\"Orphan ReplicaSet added\", \"replicaSet\", klog.KObj(rs))\n\tfor _, d := range ds {\n\t\tdc.enqueueDeployment(d)\n\t}\n}","line":{"from":213,"to":244}} {"id":100003560,"name":"getDeploymentsForReplicaSet","signature":"func (dc *DeploymentController) getDeploymentsForReplicaSet(logger klog.Logger, rs *apps.ReplicaSet) []*apps.Deployment","file":"pkg/controller/deployment/deployment_controller.go","code":"// getDeploymentsForReplicaSet returns a list of Deployments that potentially\n// match a ReplicaSet.\nfunc (dc *DeploymentController) getDeploymentsForReplicaSet(logger klog.Logger, rs *apps.ReplicaSet) []*apps.Deployment {\n\tdeployments, err := util.GetDeploymentsForReplicaSet(dc.dLister, rs)\n\tif err != nil || len(deployments) == 0 {\n\t\treturn nil\n\t}\n\t// Because all ReplicaSet's belonging to a deployment should have a unique label key,\n\t// there should never be more than one deployment returned by the above method.\n\t// If that happens we should probably dynamically repair the situation by ultimately\n\t// trying to clean up one of the controllers, for now we just return the older one\n\tif len(deployments) \u003e 1 {\n\t\t// ControllerRef will ensure we don't do anything crazy, but more than one\n\t\t// item in this list nevertheless constitutes user error.\n\t\tlogger.V(4).Info(\"user error! more than one deployment is selecting replica set\",\n\t\t\t\"replicaSet\", klog.KObj(rs), \"labels\", rs.Labels, \"deployment\", klog.KObj(deployments[0]))\n\t}\n\treturn deployments\n}","line":{"from":246,"to":264}} {"id":100003561,"name":"updateReplicaSet","signature":"func (dc *DeploymentController) updateReplicaSet(logger klog.Logger, old, cur interface{})","file":"pkg/controller/deployment/deployment_controller.go","code":"// updateReplicaSet figures out what deployment(s) manage a ReplicaSet when the ReplicaSet\n// is updated and wake them up. If the anything of the ReplicaSets have changed, we need to\n// awaken both the old and new deployments. old and cur must be *apps.ReplicaSet\n// types.\nfunc (dc *DeploymentController) updateReplicaSet(logger klog.Logger, old, cur interface{}) {\n\tcurRS := cur.(*apps.ReplicaSet)\n\toldRS := old.(*apps.ReplicaSet)\n\tif curRS.ResourceVersion == oldRS.ResourceVersion {\n\t\t// Periodic resync will send update events for all known replica sets.\n\t\t// Two different versions of the same replica set will always have different RVs.\n\t\treturn\n\t}\n\n\tcurControllerRef := metav1.GetControllerOf(curRS)\n\toldControllerRef := metav1.GetControllerOf(oldRS)\n\tcontrollerRefChanged := !reflect.DeepEqual(curControllerRef, oldControllerRef)\n\tif controllerRefChanged \u0026\u0026 oldControllerRef != nil {\n\t\t// The ControllerRef was changed. Sync the old controller, if any.\n\t\tif d := dc.resolveControllerRef(oldRS.Namespace, oldControllerRef); d != nil {\n\t\t\tdc.enqueueDeployment(d)\n\t\t}\n\t}\n\t// If it has a ControllerRef, that's all that matters.\n\tif curControllerRef != nil {\n\t\td := dc.resolveControllerRef(curRS.Namespace, curControllerRef)\n\t\tif d == nil {\n\t\t\treturn\n\t\t}\n\t\tlogger.V(4).Info(\"ReplicaSet updated\", \"replicaSet\", klog.KObj(curRS))\n\t\tdc.enqueueDeployment(d)\n\t\treturn\n\t}\n\n\t// Otherwise, it's an orphan. If anything changed, sync matching controllers\n\t// to see if anyone wants to adopt it now.\n\tlabelChanged := !reflect.DeepEqual(curRS.Labels, oldRS.Labels)\n\tif labelChanged || controllerRefChanged {\n\t\tds := dc.getDeploymentsForReplicaSet(logger, curRS)\n\t\tif len(ds) == 0 {\n\t\t\treturn\n\t\t}\n\t\tlogger.V(4).Info(\"Orphan ReplicaSet updated\", \"replicaSet\", klog.KObj(curRS))\n\t\tfor _, d := range ds {\n\t\t\tdc.enqueueDeployment(d)\n\t\t}\n\t}\n}","line":{"from":266,"to":312}} {"id":100003562,"name":"deleteReplicaSet","signature":"func (dc *DeploymentController) deleteReplicaSet(logger klog.Logger, obj interface{})","file":"pkg/controller/deployment/deployment_controller.go","code":"// deleteReplicaSet enqueues the deployment that manages a ReplicaSet when\n// the ReplicaSet is deleted. obj could be an *apps.ReplicaSet, or\n// a DeletionFinalStateUnknown marker item.\nfunc (dc *DeploymentController) deleteReplicaSet(logger klog.Logger, obj interface{}) {\n\trs, ok := obj.(*apps.ReplicaSet)\n\n\t// When a delete is dropped, the relist will notice a pod in the store not\n\t// in the list, leading to the insertion of a tombstone object which contains\n\t// the deleted key/value. Note that this value might be stale. If the ReplicaSet\n\t// changed labels the new deployment will not be woken up till the periodic resync.\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get object from tombstone %#v\", obj))\n\t\t\treturn\n\t\t}\n\t\trs, ok = tombstone.Obj.(*apps.ReplicaSet)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"tombstone contained object that is not a ReplicaSet %#v\", obj))\n\t\t\treturn\n\t\t}\n\t}\n\n\tcontrollerRef := metav1.GetControllerOf(rs)\n\tif controllerRef == nil {\n\t\t// No controller should care about orphans being deleted.\n\t\treturn\n\t}\n\td := dc.resolveControllerRef(rs.Namespace, controllerRef)\n\tif d == nil {\n\t\treturn\n\t}\n\tlogger.V(4).Info(\"ReplicaSet deleted\", \"replicaSet\", klog.KObj(rs))\n\tdc.enqueueDeployment(d)\n}","line":{"from":314,"to":348}} {"id":100003563,"name":"deletePod","signature":"func (dc *DeploymentController) deletePod(logger klog.Logger, obj interface{})","file":"pkg/controller/deployment/deployment_controller.go","code":"// deletePod will enqueue a Recreate Deployment once all of its pods have stopped running.\nfunc (dc *DeploymentController) deletePod(logger klog.Logger, obj interface{}) {\n\tpod, ok := obj.(*v1.Pod)\n\n\t// When a delete is dropped, the relist will notice a pod in the store not\n\t// in the list, leading to the insertion of a tombstone object which contains\n\t// the deleted key/value. Note that this value might be stale. If the Pod\n\t// changed labels the new deployment will not be woken up till the periodic resync.\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get object from tombstone %#v\", obj))\n\t\t\treturn\n\t\t}\n\t\tpod, ok = tombstone.Obj.(*v1.Pod)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"tombstone contained object that is not a pod %#v\", obj))\n\t\t\treturn\n\t\t}\n\t}\n\tlogger.V(4).Info(\"Pod deleted\", \"pod\", klog.KObj(pod))\n\tif d := dc.getDeploymentForPod(logger, pod); d != nil \u0026\u0026 d.Spec.Strategy.Type == apps.RecreateDeploymentStrategyType {\n\t\t// Sync if this Deployment now has no more Pods.\n\t\trsList, err := util.ListReplicaSets(d, util.RsListFromClient(dc.client.AppsV1()))\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tpodMap, err := dc.getPodMapForDeployment(d, rsList)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tnumPods := 0\n\t\tfor _, podList := range podMap {\n\t\t\tnumPods += len(podList)\n\t\t}\n\t\tif numPods == 0 {\n\t\t\tdc.enqueueDeployment(d)\n\t\t}\n\t}\n}","line":{"from":350,"to":389}} {"id":100003564,"name":"enqueue","signature":"func (dc *DeploymentController) enqueue(deployment *apps.Deployment)","file":"pkg/controller/deployment/deployment_controller.go","code":"func (dc *DeploymentController) enqueue(deployment *apps.Deployment) {\n\tkey, err := controller.KeyFunc(deployment)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get key for object %#v: %v\", deployment, err))\n\t\treturn\n\t}\n\n\tdc.queue.Add(key)\n}","line":{"from":391,"to":399}} {"id":100003565,"name":"enqueueRateLimited","signature":"func (dc *DeploymentController) enqueueRateLimited(deployment *apps.Deployment)","file":"pkg/controller/deployment/deployment_controller.go","code":"func (dc *DeploymentController) enqueueRateLimited(deployment *apps.Deployment) {\n\tkey, err := controller.KeyFunc(deployment)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get key for object %#v: %v\", deployment, err))\n\t\treturn\n\t}\n\n\tdc.queue.AddRateLimited(key)\n}","line":{"from":401,"to":409}} {"id":100003566,"name":"enqueueAfter","signature":"func (dc *DeploymentController) enqueueAfter(deployment *apps.Deployment, after time.Duration)","file":"pkg/controller/deployment/deployment_controller.go","code":"// enqueueAfter will enqueue a deployment after the provided amount of time.\nfunc (dc *DeploymentController) enqueueAfter(deployment *apps.Deployment, after time.Duration) {\n\tkey, err := controller.KeyFunc(deployment)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get key for object %#v: %v\", deployment, err))\n\t\treturn\n\t}\n\n\tdc.queue.AddAfter(key, after)\n}","line":{"from":411,"to":420}} {"id":100003567,"name":"getDeploymentForPod","signature":"func (dc *DeploymentController) getDeploymentForPod(logger klog.Logger, pod *v1.Pod) *apps.Deployment","file":"pkg/controller/deployment/deployment_controller.go","code":"// getDeploymentForPod returns the deployment managing the given Pod.\nfunc (dc *DeploymentController) getDeploymentForPod(logger klog.Logger, pod *v1.Pod) *apps.Deployment {\n\t// Find the owning replica set\n\tvar rs *apps.ReplicaSet\n\tvar err error\n\tcontrollerRef := metav1.GetControllerOf(pod)\n\tif controllerRef == nil {\n\t\t// No controller owns this Pod.\n\t\treturn nil\n\t}\n\tif controllerRef.Kind != apps.SchemeGroupVersion.WithKind(\"ReplicaSet\").Kind {\n\t\t// Not a pod owned by a replica set.\n\t\treturn nil\n\t}\n\trs, err = dc.rsLister.ReplicaSets(pod.Namespace).Get(controllerRef.Name)\n\tif err != nil || rs.UID != controllerRef.UID {\n\t\tlogger.V(4).Info(\"Cannot get replicaset for pod\", \"ownerReference\", controllerRef.Name, \"pod\", klog.KObj(pod), \"err\", err)\n\t\treturn nil\n\t}\n\n\t// Now find the Deployment that owns that ReplicaSet.\n\tcontrollerRef = metav1.GetControllerOf(rs)\n\tif controllerRef == nil {\n\t\treturn nil\n\t}\n\treturn dc.resolveControllerRef(rs.Namespace, controllerRef)\n}","line":{"from":422,"to":448}} {"id":100003568,"name":"resolveControllerRef","signature":"func (dc *DeploymentController) resolveControllerRef(namespace string, controllerRef *metav1.OwnerReference) *apps.Deployment","file":"pkg/controller/deployment/deployment_controller.go","code":"// resolveControllerRef returns the controller referenced by a ControllerRef,\n// or nil if the ControllerRef could not be resolved to a matching controller\n// of the correct Kind.\nfunc (dc *DeploymentController) resolveControllerRef(namespace string, controllerRef *metav1.OwnerReference) *apps.Deployment {\n\t// We can't look up by UID, so look up by Name and then verify UID.\n\t// Don't even try to look up by Name if it's the wrong Kind.\n\tif controllerRef.Kind != controllerKind.Kind {\n\t\treturn nil\n\t}\n\td, err := dc.dLister.Deployments(namespace).Get(controllerRef.Name)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tif d.UID != controllerRef.UID {\n\t\t// The controller we found with this Name is not the same one that the\n\t\t// ControllerRef points to.\n\t\treturn nil\n\t}\n\treturn d\n}","line":{"from":450,"to":469}} {"id":100003569,"name":"worker","signature":"func (dc *DeploymentController) worker(ctx context.Context)","file":"pkg/controller/deployment/deployment_controller.go","code":"// worker runs a worker thread that just dequeues items, processes them, and marks them done.\n// It enforces that the syncHandler is never invoked concurrently with the same key.\nfunc (dc *DeploymentController) worker(ctx context.Context) {\n\tfor dc.processNextWorkItem(ctx) {\n\t}\n}","line":{"from":471,"to":476}} {"id":100003570,"name":"processNextWorkItem","signature":"func (dc *DeploymentController) processNextWorkItem(ctx context.Context) bool","file":"pkg/controller/deployment/deployment_controller.go","code":"func (dc *DeploymentController) processNextWorkItem(ctx context.Context) bool {\n\tkey, quit := dc.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer dc.queue.Done(key)\n\n\terr := dc.syncHandler(ctx, key.(string))\n\tdc.handleErr(ctx, err, key)\n\n\treturn true\n}","line":{"from":478,"to":489}} {"id":100003571,"name":"handleErr","signature":"func (dc *DeploymentController) handleErr(ctx context.Context, err error, key interface{})","file":"pkg/controller/deployment/deployment_controller.go","code":"func (dc *DeploymentController) handleErr(ctx context.Context, err error, key interface{}) {\n\tlogger := klog.FromContext(ctx)\n\tif err == nil || errors.HasStatusCause(err, v1.NamespaceTerminatingCause) {\n\t\tdc.queue.Forget(key)\n\t\treturn\n\t}\n\tns, name, keyErr := cache.SplitMetaNamespaceKey(key.(string))\n\tif keyErr != nil {\n\t\tlogger.Error(err, \"Failed to split meta namespace cache key\", \"cacheKey\", key)\n\t}\n\n\tif dc.queue.NumRequeues(key) \u003c maxRetries {\n\t\tlogger.V(2).Info(\"Error syncing deployment\", \"deployment\", klog.KRef(ns, name), \"err\", err)\n\t\tdc.queue.AddRateLimited(key)\n\t\treturn\n\t}\n\n\tutilruntime.HandleError(err)\n\tlogger.V(2).Info(\"Dropping deployment out of the queue\", \"deployment\", klog.KRef(ns, name), \"err\", err)\n\tdc.queue.Forget(key)\n}","line":{"from":491,"to":511}} {"id":100003572,"name":"getReplicaSetsForDeployment","signature":"func (dc *DeploymentController) getReplicaSetsForDeployment(ctx context.Context, d *apps.Deployment) ([]*apps.ReplicaSet, error)","file":"pkg/controller/deployment/deployment_controller.go","code":"// getReplicaSetsForDeployment uses ControllerRefManager to reconcile\n// ControllerRef by adopting and orphaning.\n// It returns the list of ReplicaSets that this Deployment should manage.\nfunc (dc *DeploymentController) getReplicaSetsForDeployment(ctx context.Context, d *apps.Deployment) ([]*apps.ReplicaSet, error) {\n\t// List all ReplicaSets to find those we own but that no longer match our\n\t// selector. They will be orphaned by ClaimReplicaSets().\n\trsList, err := dc.rsLister.ReplicaSets(d.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdeploymentSelector, err := metav1.LabelSelectorAsSelector(d.Spec.Selector)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"deployment %s/%s has invalid label selector: %v\", d.Namespace, d.Name, err)\n\t}\n\t// If any adoptions are attempted, we should first recheck for deletion with\n\t// an uncached quorum read sometime after listing ReplicaSets (see #42639).\n\tcanAdoptFunc := controller.RecheckDeletionTimestamp(func(ctx context.Context) (metav1.Object, error) {\n\t\tfresh, err := dc.client.AppsV1().Deployments(d.Namespace).Get(ctx, d.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif fresh.UID != d.UID {\n\t\t\treturn nil, fmt.Errorf(\"original Deployment %v/%v is gone: got uid %v, wanted %v\", d.Namespace, d.Name, fresh.UID, d.UID)\n\t\t}\n\t\treturn fresh, nil\n\t})\n\tcm := controller.NewReplicaSetControllerRefManager(dc.rsControl, d, deploymentSelector, controllerKind, canAdoptFunc)\n\treturn cm.ClaimReplicaSets(ctx, rsList)\n}","line":{"from":513,"to":541}} {"id":100003573,"name":"getPodMapForDeployment","signature":"func (dc *DeploymentController) getPodMapForDeployment(d *apps.Deployment, rsList []*apps.ReplicaSet) (map[types.UID][]*v1.Pod, error)","file":"pkg/controller/deployment/deployment_controller.go","code":"// getPodMapForDeployment returns the Pods managed by a Deployment.\n//\n// It returns a map from ReplicaSet UID to a list of Pods controlled by that RS,\n// according to the Pod's ControllerRef.\n// NOTE: The pod pointers returned by this method point the pod objects in the cache and thus\n// shouldn't be modified in any way.\nfunc (dc *DeploymentController) getPodMapForDeployment(d *apps.Deployment, rsList []*apps.ReplicaSet) (map[types.UID][]*v1.Pod, error) {\n\t// Get all Pods that potentially belong to this Deployment.\n\tselector, err := metav1.LabelSelectorAsSelector(d.Spec.Selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpods, err := dc.podLister.Pods(d.Namespace).List(selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Group Pods by their controller (if it's in rsList).\n\tpodMap := make(map[types.UID][]*v1.Pod, len(rsList))\n\tfor _, rs := range rsList {\n\t\tpodMap[rs.UID] = []*v1.Pod{}\n\t}\n\tfor _, pod := range pods {\n\t\t// Do not ignore inactive Pods because Recreate Deployments need to verify that no\n\t\t// Pods from older versions are running before spinning up new Pods.\n\t\tcontrollerRef := metav1.GetControllerOf(pod)\n\t\tif controllerRef == nil {\n\t\t\tcontinue\n\t\t}\n\t\t// Only append if we care about this UID.\n\t\tif _, ok := podMap[controllerRef.UID]; ok {\n\t\t\tpodMap[controllerRef.UID] = append(podMap[controllerRef.UID], pod)\n\t\t}\n\t}\n\treturn podMap, nil\n}","line":{"from":543,"to":577}} {"id":100003574,"name":"syncDeployment","signature":"func (dc *DeploymentController) syncDeployment(ctx context.Context, key string) error","file":"pkg/controller/deployment/deployment_controller.go","code":"// syncDeployment will sync the deployment with the given key.\n// This function is not meant to be invoked concurrently with the same key.\nfunc (dc *DeploymentController) syncDeployment(ctx context.Context, key string) error {\n\tlogger := klog.FromContext(ctx)\n\tnamespace, name, err := cache.SplitMetaNamespaceKey(key)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to split meta namespace cache key\", \"cacheKey\", key)\n\t\treturn err\n\t}\n\n\tstartTime := time.Now()\n\tlogger.V(4).Info(\"Started syncing deployment\", \"deployment\", klog.KRef(namespace, name), \"startTime\", startTime)\n\tdefer func() {\n\t\tlogger.V(4).Info(\"Finished syncing deployment\", \"deployment\", klog.KRef(namespace, name), \"duration\", time.Since(startTime))\n\t}()\n\n\tdeployment, err := dc.dLister.Deployments(namespace).Get(name)\n\tif errors.IsNotFound(err) {\n\t\tlogger.V(2).Info(\"Deployment has been deleted\", \"deployment\", klog.KRef(namespace, name))\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Deep-copy otherwise we are mutating our cache.\n\t// TODO: Deep-copy only when needed.\n\td := deployment.DeepCopy()\n\n\teverything := metav1.LabelSelector{}\n\tif reflect.DeepEqual(d.Spec.Selector, \u0026everything) {\n\t\tdc.eventRecorder.Eventf(d, v1.EventTypeWarning, \"SelectingAll\", \"This deployment is selecting all pods. A non-empty selector is required.\")\n\t\tif d.Status.ObservedGeneration \u003c d.Generation {\n\t\t\td.Status.ObservedGeneration = d.Generation\n\t\t\tdc.client.AppsV1().Deployments(d.Namespace).UpdateStatus(ctx, d, metav1.UpdateOptions{})\n\t\t}\n\t\treturn nil\n\t}\n\n\t// List ReplicaSets owned by this Deployment, while reconciling ControllerRef\n\t// through adoption/orphaning.\n\trsList, err := dc.getReplicaSetsForDeployment(ctx, d)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// List all Pods owned by this Deployment, grouped by their ReplicaSet.\n\t// Current uses of the podMap are:\n\t//\n\t// * check if a Pod is labeled correctly with the pod-template-hash label.\n\t// * check that no old Pods are running in the middle of Recreate Deployments.\n\tpodMap, err := dc.getPodMapForDeployment(d, rsList)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif d.DeletionTimestamp != nil {\n\t\treturn dc.syncStatusOnly(ctx, d, rsList)\n\t}\n\n\t// Update deployment conditions with an Unknown condition when pausing/resuming\n\t// a deployment. In this way, we can be sure that we won't timeout when a user\n\t// resumes a Deployment with a set progressDeadlineSeconds.\n\tif err = dc.checkPausedConditions(ctx, d); err != nil {\n\t\treturn err\n\t}\n\n\tif d.Spec.Paused {\n\t\treturn dc.sync(ctx, d, rsList)\n\t}\n\n\t// rollback is not re-entrant in case the underlying replica sets are updated with a new\n\t// revision so we should ensure that we won't proceed to update replica sets until we\n\t// make sure that the deployment has cleaned up its rollback spec in subsequent enqueues.\n\tif getRollbackTo(d) != nil {\n\t\treturn dc.rollback(ctx, d, rsList)\n\t}\n\n\tscalingEvent, err := dc.isScalingEvent(ctx, d, rsList)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif scalingEvent {\n\t\treturn dc.sync(ctx, d, rsList)\n\t}\n\n\tswitch d.Spec.Strategy.Type {\n\tcase apps.RecreateDeploymentStrategyType:\n\t\treturn dc.rolloutRecreate(ctx, d, rsList, podMap)\n\tcase apps.RollingUpdateDeploymentStrategyType:\n\t\treturn dc.rolloutRolling(ctx, d, rsList)\n\t}\n\treturn fmt.Errorf(\"unexpected deployment strategy type: %s\", d.Spec.Strategy.Type)\n}","line":{"from":579,"to":671}} {"id":100003575,"name":"syncRolloutStatus","signature":"func (dc *DeploymentController) syncRolloutStatus(ctx context.Context, allRSs []*apps.ReplicaSet, newRS *apps.ReplicaSet, d *apps.Deployment) error","file":"pkg/controller/deployment/progress.go","code":"// syncRolloutStatus updates the status of a deployment during a rollout. There are\n// cases this helper will run that cannot be prevented from the scaling detection,\n// for example a resync of the deployment after it was scaled up. In those cases,\n// we shouldn't try to estimate any progress.\nfunc (dc *DeploymentController) syncRolloutStatus(ctx context.Context, allRSs []*apps.ReplicaSet, newRS *apps.ReplicaSet, d *apps.Deployment) error {\n\tnewStatus := calculateStatus(allRSs, newRS, d)\n\n\t// If there is no progressDeadlineSeconds set, remove any Progressing condition.\n\tif !util.HasProgressDeadline(d) {\n\t\tutil.RemoveDeploymentCondition(\u0026newStatus, apps.DeploymentProgressing)\n\t}\n\n\t// If there is only one replica set that is active then that means we are not running\n\t// a new rollout and this is a resync where we don't need to estimate any progress.\n\t// In such a case, we should simply not estimate any progress for this deployment.\n\tcurrentCond := util.GetDeploymentCondition(d.Status, apps.DeploymentProgressing)\n\tisCompleteDeployment := newStatus.Replicas == newStatus.UpdatedReplicas \u0026\u0026 currentCond != nil \u0026\u0026 currentCond.Reason == util.NewRSAvailableReason\n\t// Check for progress only if there is a progress deadline set and the latest rollout\n\t// hasn't completed yet.\n\tif util.HasProgressDeadline(d) \u0026\u0026 !isCompleteDeployment {\n\t\tswitch {\n\t\tcase util.DeploymentComplete(d, \u0026newStatus):\n\t\t\t// Update the deployment conditions with a message for the new replica set that\n\t\t\t// was successfully deployed. If the condition already exists, we ignore this update.\n\t\t\tmsg := fmt.Sprintf(\"Deployment %q has successfully progressed.\", d.Name)\n\t\t\tif newRS != nil {\n\t\t\t\tmsg = fmt.Sprintf(\"ReplicaSet %q has successfully progressed.\", newRS.Name)\n\t\t\t}\n\t\t\tcondition := util.NewDeploymentCondition(apps.DeploymentProgressing, v1.ConditionTrue, util.NewRSAvailableReason, msg)\n\t\t\tutil.SetDeploymentCondition(\u0026newStatus, *condition)\n\n\t\tcase util.DeploymentProgressing(d, \u0026newStatus):\n\t\t\t// If there is any progress made, continue by not checking if the deployment failed. This\n\t\t\t// behavior emulates the rolling updater progressDeadline check.\n\t\t\tmsg := fmt.Sprintf(\"Deployment %q is progressing.\", d.Name)\n\t\t\tif newRS != nil {\n\t\t\t\tmsg = fmt.Sprintf(\"ReplicaSet %q is progressing.\", newRS.Name)\n\t\t\t}\n\t\t\tcondition := util.NewDeploymentCondition(apps.DeploymentProgressing, v1.ConditionTrue, util.ReplicaSetUpdatedReason, msg)\n\t\t\t// Update the current Progressing condition or add a new one if it doesn't exist.\n\t\t\t// If a Progressing condition with status=true already exists, we should update\n\t\t\t// everything but lastTransitionTime. SetDeploymentCondition already does that but\n\t\t\t// it also is not updating conditions when the reason of the new condition is the\n\t\t\t// same as the old. The Progressing condition is a special case because we want to\n\t\t\t// update with the same reason and change just lastUpdateTime iff we notice any\n\t\t\t// progress. That's why we handle it here.\n\t\t\tif currentCond != nil {\n\t\t\t\tif currentCond.Status == v1.ConditionTrue {\n\t\t\t\t\tcondition.LastTransitionTime = currentCond.LastTransitionTime\n\t\t\t\t}\n\t\t\t\tutil.RemoveDeploymentCondition(\u0026newStatus, apps.DeploymentProgressing)\n\t\t\t}\n\t\t\tutil.SetDeploymentCondition(\u0026newStatus, *condition)\n\n\t\tcase util.DeploymentTimedOut(ctx, d, \u0026newStatus):\n\t\t\t// Update the deployment with a timeout condition. If the condition already exists,\n\t\t\t// we ignore this update.\n\t\t\tmsg := fmt.Sprintf(\"Deployment %q has timed out progressing.\", d.Name)\n\t\t\tif newRS != nil {\n\t\t\t\tmsg = fmt.Sprintf(\"ReplicaSet %q has timed out progressing.\", newRS.Name)\n\t\t\t}\n\t\t\tcondition := util.NewDeploymentCondition(apps.DeploymentProgressing, v1.ConditionFalse, util.TimedOutReason, msg)\n\t\t\tutil.SetDeploymentCondition(\u0026newStatus, *condition)\n\t\t}\n\t}\n\n\t// Move failure conditions of all replica sets in deployment conditions. For now,\n\t// only one failure condition is returned from getReplicaFailures.\n\tif replicaFailureCond := dc.getReplicaFailures(allRSs, newRS); len(replicaFailureCond) \u003e 0 {\n\t\t// There will be only one ReplicaFailure condition on the replica set.\n\t\tutil.SetDeploymentCondition(\u0026newStatus, replicaFailureCond[0])\n\t} else {\n\t\tutil.RemoveDeploymentCondition(\u0026newStatus, apps.DeploymentReplicaFailure)\n\t}\n\n\t// Do not update if there is nothing new to add.\n\tif reflect.DeepEqual(d.Status, newStatus) {\n\t\t// Requeue the deployment if required.\n\t\tdc.requeueStuckDeployment(ctx, d, newStatus)\n\t\treturn nil\n\t}\n\n\tnewDeployment := d\n\tnewDeployment.Status = newStatus\n\t_, err := dc.client.AppsV1().Deployments(newDeployment.Namespace).UpdateStatus(ctx, newDeployment, metav1.UpdateOptions{})\n\treturn err\n}","line":{"from":32,"to":118}} {"id":100003576,"name":"getReplicaFailures","signature":"func (dc *DeploymentController) getReplicaFailures(allRSs []*apps.ReplicaSet, newRS *apps.ReplicaSet) []apps.DeploymentCondition","file":"pkg/controller/deployment/progress.go","code":"// getReplicaFailures will convert replica failure conditions from replica sets\n// to deployment conditions.\nfunc (dc *DeploymentController) getReplicaFailures(allRSs []*apps.ReplicaSet, newRS *apps.ReplicaSet) []apps.DeploymentCondition {\n\tvar conditions []apps.DeploymentCondition\n\tif newRS != nil {\n\t\tfor _, c := range newRS.Status.Conditions {\n\t\t\tif c.Type != apps.ReplicaSetReplicaFailure {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconditions = append(conditions, util.ReplicaSetToDeploymentCondition(c))\n\t\t}\n\t}\n\n\t// Return failures for the new replica set over failures from old replica sets.\n\tif len(conditions) \u003e 0 {\n\t\treturn conditions\n\t}\n\n\tfor i := range allRSs {\n\t\trs := allRSs[i]\n\t\tif rs == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, c := range rs.Status.Conditions {\n\t\t\tif c.Type != apps.ReplicaSetReplicaFailure {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconditions = append(conditions, util.ReplicaSetToDeploymentCondition(c))\n\t\t}\n\t}\n\treturn conditions\n}","line":{"from":120,"to":152}} {"id":100003577,"name":"requeueStuckDeployment","signature":"func (dc *DeploymentController) requeueStuckDeployment(ctx context.Context, d *apps.Deployment, newStatus apps.DeploymentStatus) time.Duration","file":"pkg/controller/deployment/progress.go","code":"// requeueStuckDeployment checks whether the provided deployment needs to be synced for a progress\n// check. It returns the time after the deployment will be requeued for the progress check, 0 if it\n// will be requeued now, or -1 if it does not need to be requeued.\nfunc (dc *DeploymentController) requeueStuckDeployment(ctx context.Context, d *apps.Deployment, newStatus apps.DeploymentStatus) time.Duration {\n\tlogger := klog.FromContext(ctx)\n\tcurrentCond := util.GetDeploymentCondition(d.Status, apps.DeploymentProgressing)\n\t// Can't estimate progress if there is no deadline in the spec or progressing condition in the current status.\n\tif !util.HasProgressDeadline(d) || currentCond == nil {\n\t\treturn time.Duration(-1)\n\t}\n\t// No need to estimate progress if the rollout is complete or already timed out.\n\tif util.DeploymentComplete(d, \u0026newStatus) || currentCond.Reason == util.TimedOutReason {\n\t\treturn time.Duration(-1)\n\t}\n\t// If there is no sign of progress at this point then there is a high chance that the\n\t// deployment is stuck. We should resync this deployment at some point in the future[1]\n\t// and check whether it has timed out. We definitely need this, otherwise we depend on the\n\t// controller resync interval. See https://github.com/kubernetes/kubernetes/issues/34458.\n\t//\n\t// [1] ProgressingCondition.LastUpdatedTime + progressDeadlineSeconds - time.Now()\n\t//\n\t// For example, if a Deployment updated its Progressing condition 3 minutes ago and has a\n\t// deadline of 10 minutes, it would need to be resynced for a progress check after 7 minutes.\n\t//\n\t// lastUpdated: \t\t\t00:00:00\n\t// now: \t\t\t\t\t00:03:00\n\t// progressDeadlineSeconds: 600 (10 minutes)\n\t//\n\t// lastUpdated + progressDeadlineSeconds - now =\u003e 00:00:00 + 00:10:00 - 00:03:00 =\u003e 07:00\n\tafter := currentCond.LastUpdateTime.Time.Add(time.Duration(*d.Spec.ProgressDeadlineSeconds) * time.Second).Sub(nowFn())\n\t// If the remaining time is less than a second, then requeue the deployment immediately.\n\t// Make it ratelimited so we stay on the safe side, eventually the Deployment should\n\t// transition either to a Complete or to a TimedOut condition.\n\tif after \u003c time.Second {\n\t\tlogger.V(4).Info(\"Queueing up deployment for a progress check now\", \"deployment\", klog.KObj(d))\n\t\tdc.enqueueRateLimited(d)\n\t\treturn time.Duration(0)\n\t}\n\tlogger.V(4).Info(\"Queueing up deployment for a progress check\", \"deployment\", klog.KObj(d), \"queueAfter\", int(after.Seconds()))\n\t// Add a second to avoid milliseconds skew in AddAfter.\n\t// See https://github.com/kubernetes/kubernetes/issues/39785#issuecomment-279959133 for more info.\n\tdc.enqueueAfter(d, after+time.Second)\n\treturn after\n}","line":{"from":157,"to":200}} {"id":100003578,"name":"rolloutRecreate","signature":"func (dc *DeploymentController) rolloutRecreate(ctx context.Context, d *apps.Deployment, rsList []*apps.ReplicaSet, podMap map[types.UID][]*v1.Pod) error","file":"pkg/controller/deployment/recreate.go","code":"// rolloutRecreate implements the logic for recreating a replica set.\nfunc (dc *DeploymentController) rolloutRecreate(ctx context.Context, d *apps.Deployment, rsList []*apps.ReplicaSet, podMap map[types.UID][]*v1.Pod) error {\n\t// Don't create a new RS if not already existed, so that we avoid scaling up before scaling down.\n\tnewRS, oldRSs, err := dc.getAllReplicaSetsAndSyncRevision(ctx, d, rsList, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\tallRSs := append(oldRSs, newRS)\n\tactiveOldRSs := controller.FilterActiveReplicaSets(oldRSs)\n\n\t// scale down old replica sets.\n\tscaledDown, err := dc.scaleDownOldReplicaSetsForRecreate(ctx, activeOldRSs, d)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif scaledDown {\n\t\t// Update DeploymentStatus.\n\t\treturn dc.syncRolloutStatus(ctx, allRSs, newRS, d)\n\t}\n\n\t// Do not process a deployment when it has old pods running.\n\tif oldPodsRunning(newRS, oldRSs, podMap) {\n\t\treturn dc.syncRolloutStatus(ctx, allRSs, newRS, d)\n\t}\n\n\t// If we need to create a new RS, create it now.\n\tif newRS == nil {\n\t\tnewRS, oldRSs, err = dc.getAllReplicaSetsAndSyncRevision(ctx, d, rsList, true)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tallRSs = append(oldRSs, newRS)\n\t}\n\n\t// scale up new replica set.\n\tif _, err := dc.scaleUpNewReplicaSetForRecreate(ctx, newRS, d); err != nil {\n\t\treturn err\n\t}\n\n\tif util.DeploymentComplete(d, \u0026d.Status) {\n\t\tif err := dc.cleanupDeployment(ctx, oldRSs, d); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Sync deployment status.\n\treturn dc.syncRolloutStatus(ctx, allRSs, newRS, d)\n}","line":{"from":28,"to":75}} {"id":100003579,"name":"scaleDownOldReplicaSetsForRecreate","signature":"func (dc *DeploymentController) scaleDownOldReplicaSetsForRecreate(ctx context.Context, oldRSs []*apps.ReplicaSet, deployment *apps.Deployment) (bool, error)","file":"pkg/controller/deployment/recreate.go","code":"// scaleDownOldReplicaSetsForRecreate scales down old replica sets when deployment strategy is \"Recreate\".\nfunc (dc *DeploymentController) scaleDownOldReplicaSetsForRecreate(ctx context.Context, oldRSs []*apps.ReplicaSet, deployment *apps.Deployment) (bool, error) {\n\tscaled := false\n\tfor i := range oldRSs {\n\t\trs := oldRSs[i]\n\t\t// Scaling not required.\n\t\tif *(rs.Spec.Replicas) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tscaledRS, updatedRS, err := dc.scaleReplicaSetAndRecordEvent(ctx, rs, 0, deployment)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif scaledRS {\n\t\t\toldRSs[i] = updatedRS\n\t\t\tscaled = true\n\t\t}\n\t}\n\treturn scaled, nil\n}","line":{"from":77,"to":96}} {"id":100003580,"name":"oldPodsRunning","signature":"func oldPodsRunning(newRS *apps.ReplicaSet, oldRSs []*apps.ReplicaSet, podMap map[types.UID][]*v1.Pod) bool","file":"pkg/controller/deployment/recreate.go","code":"// oldPodsRunning returns whether there are old pods running or any of the old ReplicaSets thinks that it runs pods.\nfunc oldPodsRunning(newRS *apps.ReplicaSet, oldRSs []*apps.ReplicaSet, podMap map[types.UID][]*v1.Pod) bool {\n\tif oldPods := util.GetActualReplicaCountForReplicaSets(oldRSs); oldPods \u003e 0 {\n\t\treturn true\n\t}\n\tfor rsUID, podList := range podMap {\n\t\t// If the pods belong to the new ReplicaSet, ignore.\n\t\tif newRS != nil \u0026\u0026 newRS.UID == rsUID {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, pod := range podList {\n\t\t\tswitch pod.Status.Phase {\n\t\t\tcase v1.PodFailed, v1.PodSucceeded:\n\t\t\t\t// Don't count pods in terminal state.\n\t\t\t\tcontinue\n\t\t\tcase v1.PodUnknown:\n\t\t\t\t// v1.PodUnknown is a deprecated status.\n\t\t\t\t// This logic is kept for backward compatibility.\n\t\t\t\t// This used to happen in situation like when the node is temporarily disconnected from the cluster.\n\t\t\t\t// If we can't be sure that the pod is not running, we have to count it.\n\t\t\t\treturn true\n\t\t\tdefault:\n\t\t\t\t// Pod is not in terminal phase.\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":98,"to":126}} {"id":100003581,"name":"scaleUpNewReplicaSetForRecreate","signature":"func (dc *DeploymentController) scaleUpNewReplicaSetForRecreate(ctx context.Context, newRS *apps.ReplicaSet, deployment *apps.Deployment) (bool, error)","file":"pkg/controller/deployment/recreate.go","code":"// scaleUpNewReplicaSetForRecreate scales up new replica set when deployment strategy is \"Recreate\".\nfunc (dc *DeploymentController) scaleUpNewReplicaSetForRecreate(ctx context.Context, newRS *apps.ReplicaSet, deployment *apps.Deployment) (bool, error) {\n\tscaled, _, err := dc.scaleReplicaSetAndRecordEvent(ctx, newRS, *(deployment.Spec.Replicas), deployment)\n\treturn scaled, err\n}","line":{"from":128,"to":132}} {"id":100003582,"name":"rollback","signature":"func (dc *DeploymentController) rollback(ctx context.Context, d *apps.Deployment, rsList []*apps.ReplicaSet) error","file":"pkg/controller/deployment/rollback.go","code":"// rollback the deployment to the specified revision. In any case cleanup the rollback spec.\nfunc (dc *DeploymentController) rollback(ctx context.Context, d *apps.Deployment, rsList []*apps.ReplicaSet) error {\n\tlogger := klog.FromContext(ctx)\n\tnewRS, allOldRSs, err := dc.getAllReplicaSetsAndSyncRevision(ctx, d, rsList, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tallRSs := append(allOldRSs, newRS)\n\trollbackTo := getRollbackTo(d)\n\t// If rollback revision is 0, rollback to the last revision\n\tif rollbackTo.Revision == 0 {\n\t\tif rollbackTo.Revision = deploymentutil.LastRevision(allRSs); rollbackTo.Revision == 0 {\n\t\t\t// If we still can't find the last revision, gives up rollback\n\t\t\tdc.emitRollbackWarningEvent(d, deploymentutil.RollbackRevisionNotFound, \"Unable to find last revision.\")\n\t\t\t// Gives up rollback\n\t\t\treturn dc.updateDeploymentAndClearRollbackTo(ctx, d)\n\t\t}\n\t}\n\tfor _, rs := range allRSs {\n\t\tv, err := deploymentutil.Revision(rs)\n\t\tif err != nil {\n\t\t\tlogger.V(4).Info(\"Unable to extract revision from deployment's replica set\", \"replicaSet\", klog.KObj(rs), \"err\", err)\n\t\t\tcontinue\n\t\t}\n\t\tif v == rollbackTo.Revision {\n\t\t\tlogger.V(4).Info(\"Found replica set with desired revision\", \"replicaSet\", klog.KObj(rs), \"revision\", v)\n\t\t\t// rollback by copying podTemplate.Spec from the replica set\n\t\t\t// revision number will be incremented during the next getAllReplicaSetsAndSyncRevision call\n\t\t\t// no-op if the spec matches current deployment's podTemplate.Spec\n\t\t\tperformedRollback, err := dc.rollbackToTemplate(ctx, d, rs)\n\t\t\tif performedRollback \u0026\u0026 err == nil {\n\t\t\t\tdc.emitRollbackNormalEvent(d, fmt.Sprintf(\"Rolled back deployment %q to revision %d\", d.Name, rollbackTo.Revision))\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t}\n\tdc.emitRollbackWarningEvent(d, deploymentutil.RollbackRevisionNotFound, \"Unable to find the revision to rollback to.\")\n\t// Gives up rollback\n\treturn dc.updateDeploymentAndClearRollbackTo(ctx, d)\n}","line":{"from":32,"to":72}} {"id":100003583,"name":"rollbackToTemplate","signature":"func (dc *DeploymentController) rollbackToTemplate(ctx context.Context, d *apps.Deployment, rs *apps.ReplicaSet) (bool, error)","file":"pkg/controller/deployment/rollback.go","code":"// rollbackToTemplate compares the templates of the provided deployment and replica set and\n// updates the deployment with the replica set template in case they are different. It also\n// cleans up the rollback spec so subsequent requeues of the deployment won't end up in here.\nfunc (dc *DeploymentController) rollbackToTemplate(ctx context.Context, d *apps.Deployment, rs *apps.ReplicaSet) (bool, error) {\n\tlogger := klog.FromContext(ctx)\n\tperformedRollback := false\n\tif !deploymentutil.EqualIgnoreHash(\u0026d.Spec.Template, \u0026rs.Spec.Template) {\n\t\tlogger.V(4).Info(\"Rolling back deployment to old template spec\", \"deployment\", klog.KObj(d), \"templateSpec\", rs.Spec.Template.Spec)\n\t\tdeploymentutil.SetFromReplicaSetTemplate(d, rs.Spec.Template)\n\t\t// set RS (the old RS we'll rolling back to) annotations back to the deployment;\n\t\t// otherwise, the deployment's current annotations (should be the same as current new RS) will be copied to the RS after the rollback.\n\t\t//\n\t\t// For example,\n\t\t// A Deployment has old RS1 with annotation {change-cause:create}, and new RS2 {change-cause:edit}.\n\t\t// Note that both annotations are copied from Deployment, and the Deployment should be annotated {change-cause:edit} as well.\n\t\t// Now, rollback Deployment to RS1, we should update Deployment's pod-template and also copy annotation from RS1.\n\t\t// Deployment is now annotated {change-cause:create}, and we have new RS1 {change-cause:create}, old RS2 {change-cause:edit}.\n\t\t//\n\t\t// If we don't copy the annotations back from RS to deployment on rollback, the Deployment will stay as {change-cause:edit},\n\t\t// and new RS1 becomes {change-cause:edit} (copied from deployment after rollback), old RS2 {change-cause:edit}, which is not correct.\n\t\tdeploymentutil.SetDeploymentAnnotationsTo(d, rs)\n\t\tperformedRollback = true\n\t} else {\n\t\tlogger.V(4).Info(\"Rolling back to a revision that contains the same template as current deployment, skipping rollback...\", \"deployment\", klog.KObj(d))\n\t\teventMsg := fmt.Sprintf(\"The rollback revision contains the same template as current deployment %q\", d.Name)\n\t\tdc.emitRollbackWarningEvent(d, deploymentutil.RollbackTemplateUnchanged, eventMsg)\n\t}\n\n\treturn performedRollback, dc.updateDeploymentAndClearRollbackTo(ctx, d)\n}","line":{"from":74,"to":103}} {"id":100003584,"name":"emitRollbackWarningEvent","signature":"func (dc *DeploymentController) emitRollbackWarningEvent(d *apps.Deployment, reason, message string)","file":"pkg/controller/deployment/rollback.go","code":"func (dc *DeploymentController) emitRollbackWarningEvent(d *apps.Deployment, reason, message string) {\n\tdc.eventRecorder.Eventf(d, v1.EventTypeWarning, reason, message)\n}","line":{"from":105,"to":107}} {"id":100003585,"name":"emitRollbackNormalEvent","signature":"func (dc *DeploymentController) emitRollbackNormalEvent(d *apps.Deployment, message string)","file":"pkg/controller/deployment/rollback.go","code":"func (dc *DeploymentController) emitRollbackNormalEvent(d *apps.Deployment, message string) {\n\tdc.eventRecorder.Eventf(d, v1.EventTypeNormal, deploymentutil.RollbackDone, message)\n}","line":{"from":109,"to":111}} {"id":100003586,"name":"updateDeploymentAndClearRollbackTo","signature":"func (dc *DeploymentController) updateDeploymentAndClearRollbackTo(ctx context.Context, d *apps.Deployment) error","file":"pkg/controller/deployment/rollback.go","code":"// updateDeploymentAndClearRollbackTo sets .spec.rollbackTo to nil and update the input deployment\n// It is assumed that the caller will have updated the deployment template appropriately (in case\n// we want to rollback).\nfunc (dc *DeploymentController) updateDeploymentAndClearRollbackTo(ctx context.Context, d *apps.Deployment) error {\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"Cleans up rollbackTo of deployment\", \"deployment\", klog.KObj(d))\n\tsetRollbackTo(d, nil)\n\t_, err := dc.client.AppsV1().Deployments(d.Namespace).Update(ctx, d, metav1.UpdateOptions{})\n\treturn err\n}","line":{"from":113,"to":122}} {"id":100003587,"name":"getRollbackTo","signature":"func getRollbackTo(d *apps.Deployment) *extensions.RollbackConfig","file":"pkg/controller/deployment/rollback.go","code":"// TODO: Remove this when extensions/v1beta1 and apps/v1beta1 Deployment are dropped.\nfunc getRollbackTo(d *apps.Deployment) *extensions.RollbackConfig {\n\t// Extract the annotation used for round-tripping the deprecated RollbackTo field.\n\trevision := d.Annotations[apps.DeprecatedRollbackTo]\n\tif revision == \"\" {\n\t\treturn nil\n\t}\n\trevision64, err := strconv.ParseInt(revision, 10, 64)\n\tif err != nil {\n\t\t// If it's invalid, ignore it.\n\t\treturn nil\n\t}\n\treturn \u0026extensions.RollbackConfig{\n\t\tRevision: revision64,\n\t}\n}","line":{"from":124,"to":139}} {"id":100003588,"name":"setRollbackTo","signature":"func setRollbackTo(d *apps.Deployment, rollbackTo *extensions.RollbackConfig)","file":"pkg/controller/deployment/rollback.go","code":"// TODO: Remove this when extensions/v1beta1 and apps/v1beta1 Deployment are dropped.\nfunc setRollbackTo(d *apps.Deployment, rollbackTo *extensions.RollbackConfig) {\n\tif rollbackTo == nil {\n\t\tdelete(d.Annotations, apps.DeprecatedRollbackTo)\n\t\treturn\n\t}\n\tif d.Annotations == nil {\n\t\td.Annotations = make(map[string]string)\n\t}\n\td.Annotations[apps.DeprecatedRollbackTo] = strconv.FormatInt(rollbackTo.Revision, 10)\n}","line":{"from":141,"to":151}} {"id":100003589,"name":"rolloutRolling","signature":"func (dc *DeploymentController) rolloutRolling(ctx context.Context, d *apps.Deployment, rsList []*apps.ReplicaSet) error","file":"pkg/controller/deployment/rolling.go","code":"// rolloutRolling implements the logic for rolling a new replica set.\nfunc (dc *DeploymentController) rolloutRolling(ctx context.Context, d *apps.Deployment, rsList []*apps.ReplicaSet) error {\n\tnewRS, oldRSs, err := dc.getAllReplicaSetsAndSyncRevision(ctx, d, rsList, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\tallRSs := append(oldRSs, newRS)\n\n\t// Scale up, if we can.\n\tscaledUp, err := dc.reconcileNewReplicaSet(ctx, allRSs, newRS, d)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif scaledUp {\n\t\t// Update DeploymentStatus\n\t\treturn dc.syncRolloutStatus(ctx, allRSs, newRS, d)\n\t}\n\n\t// Scale down, if we can.\n\tscaledDown, err := dc.reconcileOldReplicaSets(ctx, allRSs, controller.FilterActiveReplicaSets(oldRSs), newRS, d)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif scaledDown {\n\t\t// Update DeploymentStatus\n\t\treturn dc.syncRolloutStatus(ctx, allRSs, newRS, d)\n\t}\n\n\tif deploymentutil.DeploymentComplete(d, \u0026d.Status) {\n\t\tif err := dc.cleanupDeployment(ctx, oldRSs, d); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Sync deployment status\n\treturn dc.syncRolloutStatus(ctx, allRSs, newRS, d)\n}","line":{"from":31,"to":67}} {"id":100003590,"name":"reconcileNewReplicaSet","signature":"func (dc *DeploymentController) reconcileNewReplicaSet(ctx context.Context, allRSs []*apps.ReplicaSet, newRS *apps.ReplicaSet, deployment *apps.Deployment) (bool, error)","file":"pkg/controller/deployment/rolling.go","code":"func (dc *DeploymentController) reconcileNewReplicaSet(ctx context.Context, allRSs []*apps.ReplicaSet, newRS *apps.ReplicaSet, deployment *apps.Deployment) (bool, error) {\n\tif *(newRS.Spec.Replicas) == *(deployment.Spec.Replicas) {\n\t\t// Scaling not required.\n\t\treturn false, nil\n\t}\n\tif *(newRS.Spec.Replicas) \u003e *(deployment.Spec.Replicas) {\n\t\t// Scale down.\n\t\tscaled, _, err := dc.scaleReplicaSetAndRecordEvent(ctx, newRS, *(deployment.Spec.Replicas), deployment)\n\t\treturn scaled, err\n\t}\n\tnewReplicasCount, err := deploymentutil.NewRSNewReplicas(deployment, allRSs, newRS)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tscaled, _, err := dc.scaleReplicaSetAndRecordEvent(ctx, newRS, newReplicasCount, deployment)\n\treturn scaled, err\n}","line":{"from":69,"to":85}} {"id":100003591,"name":"reconcileOldReplicaSets","signature":"func (dc *DeploymentController) reconcileOldReplicaSets(ctx context.Context, allRSs []*apps.ReplicaSet, oldRSs []*apps.ReplicaSet, newRS *apps.ReplicaSet, deployment *apps.Deployment) (bool, error)","file":"pkg/controller/deployment/rolling.go","code":"func (dc *DeploymentController) reconcileOldReplicaSets(ctx context.Context, allRSs []*apps.ReplicaSet, oldRSs []*apps.ReplicaSet, newRS *apps.ReplicaSet, deployment *apps.Deployment) (bool, error) {\n\tlogger := klog.FromContext(ctx)\n\toldPodsCount := deploymentutil.GetReplicaCountForReplicaSets(oldRSs)\n\tif oldPodsCount == 0 {\n\t\t// Can't scale down further\n\t\treturn false, nil\n\t}\n\tallPodsCount := deploymentutil.GetReplicaCountForReplicaSets(allRSs)\n\tlogger.V(4).Info(\"New replica set\", \"replicaSet\", klog.KObj(newRS), \"availableReplicas\", newRS.Status.AvailableReplicas)\n\tmaxUnavailable := deploymentutil.MaxUnavailable(*deployment)\n\n\t// Check if we can scale down. We can scale down in the following 2 cases:\n\t// * Some old replica sets have unhealthy replicas, we could safely scale down those unhealthy replicas since that won't further\n\t// increase unavailability.\n\t// * New replica set has scaled up and it's replicas becomes ready, then we can scale down old replica sets in a further step.\n\t//\n\t// maxScaledDown := allPodsCount - minAvailable - newReplicaSetPodsUnavailable\n\t// take into account not only maxUnavailable and any surge pods that have been created, but also unavailable pods from\n\t// the newRS, so that the unavailable pods from the newRS would not make us scale down old replica sets in a further\n\t// step(that will increase unavailability).\n\t//\n\t// Concrete example:\n\t//\n\t// * 10 replicas\n\t// * 2 maxUnavailable (absolute number, not percent)\n\t// * 3 maxSurge (absolute number, not percent)\n\t//\n\t// case 1:\n\t// * Deployment is updated, newRS is created with 3 replicas, oldRS is scaled down to 8, and newRS is scaled up to 5.\n\t// * The new replica set pods crashloop and never become available.\n\t// * allPodsCount is 13. minAvailable is 8. newRSPodsUnavailable is 5.\n\t// * A node fails and causes one of the oldRS pods to become unavailable. However, 13 - 8 - 5 = 0, so the oldRS won't be scaled down.\n\t// * The user notices the crashloop and does kubectl rollout undo to rollback.\n\t// * newRSPodsUnavailable is 1, since we rolled back to the good replica set, so maxScaledDown = 13 - 8 - 1 = 4. 4 of the crashlooping pods will be scaled down.\n\t// * The total number of pods will then be 9 and the newRS can be scaled up to 10.\n\t//\n\t// case 2:\n\t// Same example, but pushing a new pod template instead of rolling back (aka \"roll over\"):\n\t// * The new replica set created must start with 0 replicas because allPodsCount is already at 13.\n\t// * However, newRSPodsUnavailable would also be 0, so the 2 old replica sets could be scaled down by 5 (13 - 8 - 0), which would then\n\t// allow the new replica set to be scaled up by 5.\n\tminAvailable := *(deployment.Spec.Replicas) - maxUnavailable\n\tnewRSUnavailablePodCount := *(newRS.Spec.Replicas) - newRS.Status.AvailableReplicas\n\tmaxScaledDown := allPodsCount - minAvailable - newRSUnavailablePodCount\n\tif maxScaledDown \u003c= 0 {\n\t\treturn false, nil\n\t}\n\n\t// Clean up unhealthy replicas first, otherwise unhealthy replicas will block deployment\n\t// and cause timeout. See https://github.com/kubernetes/kubernetes/issues/16737\n\toldRSs, cleanupCount, err := dc.cleanupUnhealthyReplicas(ctx, oldRSs, deployment, maxScaledDown)\n\tif err != nil {\n\t\treturn false, nil\n\t}\n\tlogger.V(4).Info(\"Cleaned up unhealthy replicas from old RSes\", \"count\", cleanupCount)\n\n\t// Scale down old replica sets, need check maxUnavailable to ensure we can scale down\n\tallRSs = append(oldRSs, newRS)\n\tscaledDownCount, err := dc.scaleDownOldReplicaSetsForRollingUpdate(ctx, allRSs, oldRSs, deployment)\n\tif err != nil {\n\t\treturn false, nil\n\t}\n\tlogger.V(4).Info(\"Scaled down old RSes\", \"deployment\", klog.KObj(deployment), \"count\", scaledDownCount)\n\n\ttotalScaledDown := cleanupCount + scaledDownCount\n\treturn totalScaledDown \u003e 0, nil\n}","line":{"from":87,"to":153}} {"id":100003592,"name":"cleanupUnhealthyReplicas","signature":"func (dc *DeploymentController) cleanupUnhealthyReplicas(ctx context.Context, oldRSs []*apps.ReplicaSet, deployment *apps.Deployment, maxCleanupCount int32) ([]*apps.ReplicaSet, int32, error)","file":"pkg/controller/deployment/rolling.go","code":"// cleanupUnhealthyReplicas will scale down old replica sets with unhealthy replicas, so that all unhealthy replicas will be deleted.\nfunc (dc *DeploymentController) cleanupUnhealthyReplicas(ctx context.Context, oldRSs []*apps.ReplicaSet, deployment *apps.Deployment, maxCleanupCount int32) ([]*apps.ReplicaSet, int32, error) {\n\tlogger := klog.FromContext(ctx)\n\tsort.Sort(controller.ReplicaSetsByCreationTimestamp(oldRSs))\n\t// Safely scale down all old replica sets with unhealthy replicas. Replica set will sort the pods in the order\n\t// such that not-ready \u003c ready, unscheduled \u003c scheduled, and pending \u003c running. This ensures that unhealthy replicas will\n\t// been deleted first and won't increase unavailability.\n\ttotalScaledDown := int32(0)\n\tfor i, targetRS := range oldRSs {\n\t\tif totalScaledDown \u003e= maxCleanupCount {\n\t\t\tbreak\n\t\t}\n\t\tif *(targetRS.Spec.Replicas) == 0 {\n\t\t\t// cannot scale down this replica set.\n\t\t\tcontinue\n\t\t}\n\t\tlogger.V(4).Info(\"Found available pods in old RS\", \"replicaSet\", klog.KObj(targetRS), \"availableReplicas\", targetRS.Status.AvailableReplicas)\n\t\tif *(targetRS.Spec.Replicas) == targetRS.Status.AvailableReplicas {\n\t\t\t// no unhealthy replicas found, no scaling required.\n\t\t\tcontinue\n\t\t}\n\n\t\tscaledDownCount := int32(integer.IntMin(int(maxCleanupCount-totalScaledDown), int(*(targetRS.Spec.Replicas)-targetRS.Status.AvailableReplicas)))\n\t\tnewReplicasCount := *(targetRS.Spec.Replicas) - scaledDownCount\n\t\tif newReplicasCount \u003e *(targetRS.Spec.Replicas) {\n\t\t\treturn nil, 0, fmt.Errorf(\"when cleaning up unhealthy replicas, got invalid request to scale down %s/%s %d -\u003e %d\", targetRS.Namespace, targetRS.Name, *(targetRS.Spec.Replicas), newReplicasCount)\n\t\t}\n\t\t_, updatedOldRS, err := dc.scaleReplicaSetAndRecordEvent(ctx, targetRS, newReplicasCount, deployment)\n\t\tif err != nil {\n\t\t\treturn nil, totalScaledDown, err\n\t\t}\n\t\ttotalScaledDown += scaledDownCount\n\t\toldRSs[i] = updatedOldRS\n\t}\n\treturn oldRSs, totalScaledDown, nil\n}","line":{"from":155,"to":190}} {"id":100003593,"name":"scaleDownOldReplicaSetsForRollingUpdate","signature":"func (dc *DeploymentController) scaleDownOldReplicaSetsForRollingUpdate(ctx context.Context, allRSs []*apps.ReplicaSet, oldRSs []*apps.ReplicaSet, deployment *apps.Deployment) (int32, error)","file":"pkg/controller/deployment/rolling.go","code":"// scaleDownOldReplicaSetsForRollingUpdate scales down old replica sets when deployment strategy is \"RollingUpdate\".\n// Need check maxUnavailable to ensure availability\nfunc (dc *DeploymentController) scaleDownOldReplicaSetsForRollingUpdate(ctx context.Context, allRSs []*apps.ReplicaSet, oldRSs []*apps.ReplicaSet, deployment *apps.Deployment) (int32, error) {\n\tlogger := klog.FromContext(ctx)\n\tmaxUnavailable := deploymentutil.MaxUnavailable(*deployment)\n\n\t// Check if we can scale down.\n\tminAvailable := *(deployment.Spec.Replicas) - maxUnavailable\n\t// Find the number of available pods.\n\tavailablePodCount := deploymentutil.GetAvailableReplicaCountForReplicaSets(allRSs)\n\tif availablePodCount \u003c= minAvailable {\n\t\t// Cannot scale down.\n\t\treturn 0, nil\n\t}\n\tlogger.V(4).Info(\"Found available pods in deployment, scaling down old RSes\", \"deployment\", klog.KObj(deployment), \"availableReplicas\", availablePodCount)\n\n\tsort.Sort(controller.ReplicaSetsByCreationTimestamp(oldRSs))\n\n\ttotalScaledDown := int32(0)\n\ttotalScaleDownCount := availablePodCount - minAvailable\n\tfor _, targetRS := range oldRSs {\n\t\tif totalScaledDown \u003e= totalScaleDownCount {\n\t\t\t// No further scaling required.\n\t\t\tbreak\n\t\t}\n\t\tif *(targetRS.Spec.Replicas) == 0 {\n\t\t\t// cannot scale down this ReplicaSet.\n\t\t\tcontinue\n\t\t}\n\t\t// Scale down.\n\t\tscaleDownCount := int32(integer.IntMin(int(*(targetRS.Spec.Replicas)), int(totalScaleDownCount-totalScaledDown)))\n\t\tnewReplicasCount := *(targetRS.Spec.Replicas) - scaleDownCount\n\t\tif newReplicasCount \u003e *(targetRS.Spec.Replicas) {\n\t\t\treturn 0, fmt.Errorf(\"when scaling down old RS, got invalid request to scale down %s/%s %d -\u003e %d\", targetRS.Namespace, targetRS.Name, *(targetRS.Spec.Replicas), newReplicasCount)\n\t\t}\n\t\t_, _, err := dc.scaleReplicaSetAndRecordEvent(ctx, targetRS, newReplicasCount, deployment)\n\t\tif err != nil {\n\t\t\treturn totalScaledDown, err\n\t\t}\n\n\t\ttotalScaledDown += scaleDownCount\n\t}\n\n\treturn totalScaledDown, nil\n}","line":{"from":192,"to":236}} {"id":100003594,"name":"syncStatusOnly","signature":"func (dc *DeploymentController) syncStatusOnly(ctx context.Context, d *apps.Deployment, rsList []*apps.ReplicaSet) error","file":"pkg/controller/deployment/sync.go","code":"// syncStatusOnly only updates Deployments Status and doesn't take any mutating actions.\nfunc (dc *DeploymentController) syncStatusOnly(ctx context.Context, d *apps.Deployment, rsList []*apps.ReplicaSet) error {\n\tnewRS, oldRSs, err := dc.getAllReplicaSetsAndSyncRevision(ctx, d, rsList, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tallRSs := append(oldRSs, newRS)\n\treturn dc.syncDeploymentStatus(ctx, allRSs, newRS, d)\n}","line":{"from":36,"to":45}} {"id":100003595,"name":"sync","signature":"func (dc *DeploymentController) sync(ctx context.Context, d *apps.Deployment, rsList []*apps.ReplicaSet) error","file":"pkg/controller/deployment/sync.go","code":"// sync is responsible for reconciling deployments on scaling events or when they\n// are paused.\nfunc (dc *DeploymentController) sync(ctx context.Context, d *apps.Deployment, rsList []*apps.ReplicaSet) error {\n\tnewRS, oldRSs, err := dc.getAllReplicaSetsAndSyncRevision(ctx, d, rsList, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := dc.scale(ctx, d, newRS, oldRSs); err != nil {\n\t\t// If we get an error while trying to scale, the deployment will be requeued\n\t\t// so we can abort this resync\n\t\treturn err\n\t}\n\n\t// Clean up the deployment when it's paused and no rollback is in flight.\n\tif d.Spec.Paused \u0026\u0026 getRollbackTo(d) == nil {\n\t\tif err := dc.cleanupDeployment(ctx, oldRSs, d); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tallRSs := append(oldRSs, newRS)\n\treturn dc.syncDeploymentStatus(ctx, allRSs, newRS, d)\n}","line":{"from":47,"to":69}} {"id":100003596,"name":"checkPausedConditions","signature":"func (dc *DeploymentController) checkPausedConditions(ctx context.Context, d *apps.Deployment) error","file":"pkg/controller/deployment/sync.go","code":"// checkPausedConditions checks if the given deployment is paused or not and adds an appropriate condition.\n// These conditions are needed so that we won't accidentally report lack of progress for resumed deployments\n// that were paused for longer than progressDeadlineSeconds.\nfunc (dc *DeploymentController) checkPausedConditions(ctx context.Context, d *apps.Deployment) error {\n\tif !deploymentutil.HasProgressDeadline(d) {\n\t\treturn nil\n\t}\n\tcond := deploymentutil.GetDeploymentCondition(d.Status, apps.DeploymentProgressing)\n\tif cond != nil \u0026\u0026 cond.Reason == deploymentutil.TimedOutReason {\n\t\t// If we have reported lack of progress, do not overwrite it with a paused condition.\n\t\treturn nil\n\t}\n\tpausedCondExists := cond != nil \u0026\u0026 cond.Reason == deploymentutil.PausedDeployReason\n\n\tneedsUpdate := false\n\tif d.Spec.Paused \u0026\u0026 !pausedCondExists {\n\t\tcondition := deploymentutil.NewDeploymentCondition(apps.DeploymentProgressing, v1.ConditionUnknown, deploymentutil.PausedDeployReason, \"Deployment is paused\")\n\t\tdeploymentutil.SetDeploymentCondition(\u0026d.Status, *condition)\n\t\tneedsUpdate = true\n\t} else if !d.Spec.Paused \u0026\u0026 pausedCondExists {\n\t\tcondition := deploymentutil.NewDeploymentCondition(apps.DeploymentProgressing, v1.ConditionUnknown, deploymentutil.ResumedDeployReason, \"Deployment is resumed\")\n\t\tdeploymentutil.SetDeploymentCondition(\u0026d.Status, *condition)\n\t\tneedsUpdate = true\n\t}\n\n\tif !needsUpdate {\n\t\treturn nil\n\t}\n\n\tvar err error\n\t_, err = dc.client.AppsV1().Deployments(d.Namespace).UpdateStatus(ctx, d, metav1.UpdateOptions{})\n\treturn err\n}","line":{"from":71,"to":103}} {"id":100003597,"name":"getAllReplicaSetsAndSyncRevision","signature":"func (dc *DeploymentController) getAllReplicaSetsAndSyncRevision(ctx context.Context, d *apps.Deployment, rsList []*apps.ReplicaSet, createIfNotExisted bool) (*apps.ReplicaSet, []*apps.ReplicaSet, error)","file":"pkg/controller/deployment/sync.go","code":"// getAllReplicaSetsAndSyncRevision returns all the replica sets for the provided deployment (new and all old), with new RS's and deployment's revision updated.\n//\n// rsList should come from getReplicaSetsForDeployment(d).\n//\n// 1. Get all old RSes this deployment targets, and calculate the max revision number among them (maxOldV).\n// 2. Get new RS this deployment targets (whose pod template matches deployment's), and update new RS's revision number to (maxOldV + 1),\n// only if its revision number is smaller than (maxOldV + 1). If this step failed, we'll update it in the next deployment sync loop.\n// 3. Copy new RS's revision number to deployment (update deployment's revision). If this step failed, we'll update it in the next deployment sync loop.\n//\n// Note that currently the deployment controller is using caches to avoid querying the server for reads.\n// This may lead to stale reads of replica sets, thus incorrect deployment status.\nfunc (dc *DeploymentController) getAllReplicaSetsAndSyncRevision(ctx context.Context, d *apps.Deployment, rsList []*apps.ReplicaSet, createIfNotExisted bool) (*apps.ReplicaSet, []*apps.ReplicaSet, error) {\n\t_, allOldRSs := deploymentutil.FindOldReplicaSets(d, rsList)\n\n\t// Get new replica set with the updated revision number\n\tnewRS, err := dc.getNewReplicaSet(ctx, d, rsList, allOldRSs, createIfNotExisted)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn newRS, allOldRSs, nil\n}","line":{"from":105,"to":126}} {"id":100003598,"name":"getNewReplicaSet","signature":"func (dc *DeploymentController) getNewReplicaSet(ctx context.Context, d *apps.Deployment, rsList, oldRSs []*apps.ReplicaSet, createIfNotExisted bool) (*apps.ReplicaSet, error)","file":"pkg/controller/deployment/sync.go","code":"// Returns a replica set that matches the intent of the given deployment. Returns nil if the new replica set doesn't exist yet.\n// 1. Get existing new RS (the RS that the given deployment targets, whose pod template is the same as deployment's).\n// 2. If there's existing new RS, update its revision number if it's smaller than (maxOldRevision + 1), where maxOldRevision is the max revision number among all old RSes.\n// 3. If there's no existing new RS and createIfNotExisted is true, create one with appropriate revision number (maxOldRevision + 1) and replicas.\n// Note that the pod-template-hash will be added to adopted RSes and pods.\nfunc (dc *DeploymentController) getNewReplicaSet(ctx context.Context, d *apps.Deployment, rsList, oldRSs []*apps.ReplicaSet, createIfNotExisted bool) (*apps.ReplicaSet, error) {\n\tlogger := klog.FromContext(ctx)\n\texistingNewRS := deploymentutil.FindNewReplicaSet(d, rsList)\n\n\t// Calculate the max revision number among all old RSes\n\tmaxOldRevision := deploymentutil.MaxRevision(oldRSs)\n\t// Calculate revision number for this new replica set\n\tnewRevision := strconv.FormatInt(maxOldRevision+1, 10)\n\n\t// Latest replica set exists. We need to sync its annotations (includes copying all but\n\t// annotationsToSkip from the parent deployment, and update revision, desiredReplicas,\n\t// and maxReplicas) and also update the revision annotation in the deployment with the\n\t// latest revision.\n\tif existingNewRS != nil {\n\t\trsCopy := existingNewRS.DeepCopy()\n\n\t\t// Set existing new replica set's annotation\n\t\tannotationsUpdated := deploymentutil.SetNewReplicaSetAnnotations(ctx, d, rsCopy, newRevision, true, maxRevHistoryLengthInChars)\n\t\tminReadySecondsNeedsUpdate := rsCopy.Spec.MinReadySeconds != d.Spec.MinReadySeconds\n\t\tif annotationsUpdated || minReadySecondsNeedsUpdate {\n\t\t\trsCopy.Spec.MinReadySeconds = d.Spec.MinReadySeconds\n\t\t\treturn dc.client.AppsV1().ReplicaSets(rsCopy.ObjectMeta.Namespace).Update(ctx, rsCopy, metav1.UpdateOptions{})\n\t\t}\n\n\t\t// Should use the revision in existingNewRS's annotation, since it set by before\n\t\tneedsUpdate := deploymentutil.SetDeploymentRevision(d, rsCopy.Annotations[deploymentutil.RevisionAnnotation])\n\t\t// If no other Progressing condition has been recorded and we need to estimate the progress\n\t\t// of this deployment then it is likely that old users started caring about progress. In that\n\t\t// case we need to take into account the first time we noticed their new replica set.\n\t\tcond := deploymentutil.GetDeploymentCondition(d.Status, apps.DeploymentProgressing)\n\t\tif deploymentutil.HasProgressDeadline(d) \u0026\u0026 cond == nil {\n\t\t\tmsg := fmt.Sprintf(\"Found new replica set %q\", rsCopy.Name)\n\t\t\tcondition := deploymentutil.NewDeploymentCondition(apps.DeploymentProgressing, v1.ConditionTrue, deploymentutil.FoundNewRSReason, msg)\n\t\t\tdeploymentutil.SetDeploymentCondition(\u0026d.Status, *condition)\n\t\t\tneedsUpdate = true\n\t\t}\n\n\t\tif needsUpdate {\n\t\t\tvar err error\n\t\t\tif _, err = dc.client.AppsV1().Deployments(d.Namespace).UpdateStatus(ctx, d, metav1.UpdateOptions{}); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\treturn rsCopy, nil\n\t}\n\n\tif !createIfNotExisted {\n\t\treturn nil, nil\n\t}\n\n\t// new ReplicaSet does not exist, create one.\n\tnewRSTemplate := *d.Spec.Template.DeepCopy()\n\tpodTemplateSpecHash := controller.ComputeHash(\u0026newRSTemplate, d.Status.CollisionCount)\n\tnewRSTemplate.Labels = labelsutil.CloneAndAddLabel(d.Spec.Template.Labels, apps.DefaultDeploymentUniqueLabelKey, podTemplateSpecHash)\n\t// Add podTemplateHash label to selector.\n\tnewRSSelector := labelsutil.CloneSelectorAndAddLabel(d.Spec.Selector, apps.DefaultDeploymentUniqueLabelKey, podTemplateSpecHash)\n\n\t// Create new ReplicaSet\n\tnewRS := apps.ReplicaSet{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t// Make the name deterministic, to ensure idempotence\n\t\t\tName: d.Name + \"-\" + podTemplateSpecHash,\n\t\t\tNamespace: d.Namespace,\n\t\t\tOwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(d, controllerKind)},\n\t\t\tLabels: newRSTemplate.Labels,\n\t\t},\n\t\tSpec: apps.ReplicaSetSpec{\n\t\t\tReplicas: new(int32),\n\t\t\tMinReadySeconds: d.Spec.MinReadySeconds,\n\t\t\tSelector: newRSSelector,\n\t\t\tTemplate: newRSTemplate,\n\t\t},\n\t}\n\tallRSs := append(oldRSs, \u0026newRS)\n\tnewReplicasCount, err := deploymentutil.NewRSNewReplicas(d, allRSs, \u0026newRS)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t*(newRS.Spec.Replicas) = newReplicasCount\n\t// Set new replica set's annotation\n\tdeploymentutil.SetNewReplicaSetAnnotations(ctx, d, \u0026newRS, newRevision, false, maxRevHistoryLengthInChars)\n\t// Create the new ReplicaSet. If it already exists, then we need to check for possible\n\t// hash collisions. If there is any other error, we need to report it in the status of\n\t// the Deployment.\n\talreadyExists := false\n\tcreatedRS, err := dc.client.AppsV1().ReplicaSets(d.Namespace).Create(ctx, \u0026newRS, metav1.CreateOptions{})\n\tswitch {\n\t// We may end up hitting this due to a slow cache or a fast resync of the Deployment.\n\tcase errors.IsAlreadyExists(err):\n\t\talreadyExists = true\n\n\t\t// Fetch a copy of the ReplicaSet.\n\t\trs, rsErr := dc.rsLister.ReplicaSets(newRS.Namespace).Get(newRS.Name)\n\t\tif rsErr != nil {\n\t\t\treturn nil, rsErr\n\t\t}\n\n\t\t// If the Deployment owns the ReplicaSet and the ReplicaSet's PodTemplateSpec is semantically\n\t\t// deep equal to the PodTemplateSpec of the Deployment, it's the Deployment's new ReplicaSet.\n\t\t// Otherwise, this is a hash collision and we need to increment the collisionCount field in\n\t\t// the status of the Deployment and requeue to try the creation in the next sync.\n\t\tcontrollerRef := metav1.GetControllerOf(rs)\n\t\tif controllerRef != nil \u0026\u0026 controllerRef.UID == d.UID \u0026\u0026 deploymentutil.EqualIgnoreHash(\u0026d.Spec.Template, \u0026rs.Spec.Template) {\n\t\t\tcreatedRS = rs\n\t\t\terr = nil\n\t\t\tbreak\n\t\t}\n\n\t\t// Matching ReplicaSet is not equal - increment the collisionCount in the DeploymentStatus\n\t\t// and requeue the Deployment.\n\t\tif d.Status.CollisionCount == nil {\n\t\t\td.Status.CollisionCount = new(int32)\n\t\t}\n\t\tpreCollisionCount := *d.Status.CollisionCount\n\t\t*d.Status.CollisionCount++\n\t\t// Update the collisionCount for the Deployment and let it requeue by returning the original\n\t\t// error.\n\t\t_, dErr := dc.client.AppsV1().Deployments(d.Namespace).UpdateStatus(ctx, d, metav1.UpdateOptions{})\n\t\tif dErr == nil {\n\t\t\tlogger.V(2).Info(\"Found a hash collision for deployment - bumping collisionCount to resolve it\", \"deployment\", klog.KObj(d), \"oldCollisionCount\", preCollisionCount, \"newCollisionCount\", *d.Status.CollisionCount)\n\t\t}\n\t\treturn nil, err\n\tcase errors.HasStatusCause(err, v1.NamespaceTerminatingCause):\n\t\t// if the namespace is terminating, all subsequent creates will fail and we can safely do nothing\n\t\treturn nil, err\n\tcase err != nil:\n\t\tmsg := fmt.Sprintf(\"Failed to create new replica set %q: %v\", newRS.Name, err)\n\t\tif deploymentutil.HasProgressDeadline(d) {\n\t\t\tcond := deploymentutil.NewDeploymentCondition(apps.DeploymentProgressing, v1.ConditionFalse, deploymentutil.FailedRSCreateReason, msg)\n\t\t\tdeploymentutil.SetDeploymentCondition(\u0026d.Status, *cond)\n\t\t\t// We don't really care about this error at this point, since we have a bigger issue to report.\n\t\t\t// TODO: Identify which errors are permanent and switch DeploymentIsFailed to take into account\n\t\t\t// these reasons as well. Related issue: https://github.com/kubernetes/kubernetes/issues/18568\n\t\t\t_, _ = dc.client.AppsV1().Deployments(d.Namespace).UpdateStatus(ctx, d, metav1.UpdateOptions{})\n\t\t}\n\t\tdc.eventRecorder.Eventf(d, v1.EventTypeWarning, deploymentutil.FailedRSCreateReason, msg)\n\t\treturn nil, err\n\t}\n\tif !alreadyExists \u0026\u0026 newReplicasCount \u003e 0 {\n\t\tdc.eventRecorder.Eventf(d, v1.EventTypeNormal, \"ScalingReplicaSet\", \"Scaled up replica set %s to %d\", createdRS.Name, newReplicasCount)\n\t}\n\n\tneedsUpdate := deploymentutil.SetDeploymentRevision(d, newRevision)\n\tif !alreadyExists \u0026\u0026 deploymentutil.HasProgressDeadline(d) {\n\t\tmsg := fmt.Sprintf(\"Created new replica set %q\", createdRS.Name)\n\t\tcondition := deploymentutil.NewDeploymentCondition(apps.DeploymentProgressing, v1.ConditionTrue, deploymentutil.NewReplicaSetReason, msg)\n\t\tdeploymentutil.SetDeploymentCondition(\u0026d.Status, *condition)\n\t\tneedsUpdate = true\n\t}\n\tif needsUpdate {\n\t\t_, err = dc.client.AppsV1().Deployments(d.Namespace).UpdateStatus(ctx, d, metav1.UpdateOptions{})\n\t}\n\treturn createdRS, err\n}","line":{"from":133,"to":292}} {"id":100003599,"name":"scale","signature":"func (dc *DeploymentController) scale(ctx context.Context, deployment *apps.Deployment, newRS *apps.ReplicaSet, oldRSs []*apps.ReplicaSet) error","file":"pkg/controller/deployment/sync.go","code":"// scale scales proportionally in order to mitigate risk. Otherwise, scaling up can increase the size\n// of the new replica set and scaling down can decrease the sizes of the old ones, both of which would\n// have the effect of hastening the rollout progress, which could produce a higher proportion of unavailable\n// replicas in the event of a problem with the rolled out template. Should run only on scaling events or\n// when a deployment is paused and not during the normal rollout process.\nfunc (dc *DeploymentController) scale(ctx context.Context, deployment *apps.Deployment, newRS *apps.ReplicaSet, oldRSs []*apps.ReplicaSet) error {\n\t// If there is only one active replica set then we should scale that up to the full count of the\n\t// deployment. If there is no active replica set, then we should scale up the newest replica set.\n\tif activeOrLatest := deploymentutil.FindActiveOrLatest(newRS, oldRSs); activeOrLatest != nil {\n\t\tif *(activeOrLatest.Spec.Replicas) == *(deployment.Spec.Replicas) {\n\t\t\treturn nil\n\t\t}\n\t\t_, _, err := dc.scaleReplicaSetAndRecordEvent(ctx, activeOrLatest, *(deployment.Spec.Replicas), deployment)\n\t\treturn err\n\t}\n\n\t// If the new replica set is saturated, old replica sets should be fully scaled down.\n\t// This case handles replica set adoption during a saturated new replica set.\n\tif deploymentutil.IsSaturated(deployment, newRS) {\n\t\tfor _, old := range controller.FilterActiveReplicaSets(oldRSs) {\n\t\t\tif _, _, err := dc.scaleReplicaSetAndRecordEvent(ctx, old, 0, deployment); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\t// There are old replica sets with pods and the new replica set is not saturated.\n\t// We need to proportionally scale all replica sets (new and old) in case of a\n\t// rolling deployment.\n\tif deploymentutil.IsRollingUpdate(deployment) {\n\t\tallRSs := controller.FilterActiveReplicaSets(append(oldRSs, newRS))\n\t\tallRSsReplicas := deploymentutil.GetReplicaCountForReplicaSets(allRSs)\n\n\t\tallowedSize := int32(0)\n\t\tif *(deployment.Spec.Replicas) \u003e 0 {\n\t\t\tallowedSize = *(deployment.Spec.Replicas) + deploymentutil.MaxSurge(*deployment)\n\t\t}\n\n\t\t// Number of additional replicas that can be either added or removed from the total\n\t\t// replicas count. These replicas should be distributed proportionally to the active\n\t\t// replica sets.\n\t\tdeploymentReplicasToAdd := allowedSize - allRSsReplicas\n\n\t\t// The additional replicas should be distributed proportionally amongst the active\n\t\t// replica sets from the larger to the smaller in size replica set. Scaling direction\n\t\t// drives what happens in case we are trying to scale replica sets of the same size.\n\t\t// In such a case when scaling up, we should scale up newer replica sets first, and\n\t\t// when scaling down, we should scale down older replica sets first.\n\t\tvar scalingOperation string\n\t\tswitch {\n\t\tcase deploymentReplicasToAdd \u003e 0:\n\t\t\tsort.Sort(controller.ReplicaSetsBySizeNewer(allRSs))\n\t\t\tscalingOperation = \"up\"\n\n\t\tcase deploymentReplicasToAdd \u003c 0:\n\t\t\tsort.Sort(controller.ReplicaSetsBySizeOlder(allRSs))\n\t\t\tscalingOperation = \"down\"\n\t\t}\n\n\t\t// Iterate over all active replica sets and estimate proportions for each of them.\n\t\t// The absolute value of deploymentReplicasAdded should never exceed the absolute\n\t\t// value of deploymentReplicasToAdd.\n\t\tdeploymentReplicasAdded := int32(0)\n\t\tnameToSize := make(map[string]int32)\n\t\tlogger := klog.FromContext(ctx)\n\t\tfor i := range allRSs {\n\t\t\trs := allRSs[i]\n\n\t\t\t// Estimate proportions if we have replicas to add, otherwise simply populate\n\t\t\t// nameToSize with the current sizes for each replica set.\n\t\t\tif deploymentReplicasToAdd != 0 {\n\t\t\t\tproportion := deploymentutil.GetProportion(logger, rs, *deployment, deploymentReplicasToAdd, deploymentReplicasAdded)\n\n\t\t\t\tnameToSize[rs.Name] = *(rs.Spec.Replicas) + proportion\n\t\t\t\tdeploymentReplicasAdded += proportion\n\t\t\t} else {\n\t\t\t\tnameToSize[rs.Name] = *(rs.Spec.Replicas)\n\t\t\t}\n\t\t}\n\n\t\t// Update all replica sets\n\t\tfor i := range allRSs {\n\t\t\trs := allRSs[i]\n\n\t\t\t// Add/remove any leftovers to the largest replica set.\n\t\t\tif i == 0 \u0026\u0026 deploymentReplicasToAdd != 0 {\n\t\t\t\tleftover := deploymentReplicasToAdd - deploymentReplicasAdded\n\t\t\t\tnameToSize[rs.Name] = nameToSize[rs.Name] + leftover\n\t\t\t\tif nameToSize[rs.Name] \u003c 0 {\n\t\t\t\t\tnameToSize[rs.Name] = 0\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// TODO: Use transactions when we have them.\n\t\t\tif _, _, err := dc.scaleReplicaSet(ctx, rs, nameToSize[rs.Name], deployment, scalingOperation); err != nil {\n\t\t\t\t// Return as soon as we fail, the deployment is requeued\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":294,"to":396}} {"id":100003600,"name":"scaleReplicaSetAndRecordEvent","signature":"func (dc *DeploymentController) scaleReplicaSetAndRecordEvent(ctx context.Context, rs *apps.ReplicaSet, newScale int32, deployment *apps.Deployment) (bool, *apps.ReplicaSet, error)","file":"pkg/controller/deployment/sync.go","code":"func (dc *DeploymentController) scaleReplicaSetAndRecordEvent(ctx context.Context, rs *apps.ReplicaSet, newScale int32, deployment *apps.Deployment) (bool, *apps.ReplicaSet, error) {\n\t// No need to scale\n\tif *(rs.Spec.Replicas) == newScale {\n\t\treturn false, rs, nil\n\t}\n\tvar scalingOperation string\n\tif *(rs.Spec.Replicas) \u003c newScale {\n\t\tscalingOperation = \"up\"\n\t} else {\n\t\tscalingOperation = \"down\"\n\t}\n\tscaled, newRS, err := dc.scaleReplicaSet(ctx, rs, newScale, deployment, scalingOperation)\n\treturn scaled, newRS, err\n}","line":{"from":398,"to":411}} {"id":100003601,"name":"scaleReplicaSet","signature":"func (dc *DeploymentController) scaleReplicaSet(ctx context.Context, rs *apps.ReplicaSet, newScale int32, deployment *apps.Deployment, scalingOperation string) (bool, *apps.ReplicaSet, error)","file":"pkg/controller/deployment/sync.go","code":"func (dc *DeploymentController) scaleReplicaSet(ctx context.Context, rs *apps.ReplicaSet, newScale int32, deployment *apps.Deployment, scalingOperation string) (bool, *apps.ReplicaSet, error) {\n\n\tsizeNeedsUpdate := *(rs.Spec.Replicas) != newScale\n\n\tannotationsNeedUpdate := deploymentutil.ReplicasAnnotationsNeedUpdate(rs, *(deployment.Spec.Replicas), *(deployment.Spec.Replicas)+deploymentutil.MaxSurge(*deployment))\n\n\tscaled := false\n\tvar err error\n\tif sizeNeedsUpdate || annotationsNeedUpdate {\n\t\toldScale := *(rs.Spec.Replicas)\n\t\trsCopy := rs.DeepCopy()\n\t\t*(rsCopy.Spec.Replicas) = newScale\n\t\tdeploymentutil.SetReplicasAnnotations(rsCopy, *(deployment.Spec.Replicas), *(deployment.Spec.Replicas)+deploymentutil.MaxSurge(*deployment))\n\t\trs, err = dc.client.AppsV1().ReplicaSets(rsCopy.Namespace).Update(ctx, rsCopy, metav1.UpdateOptions{})\n\t\tif err == nil \u0026\u0026 sizeNeedsUpdate {\n\t\t\tscaled = true\n\t\t\tdc.eventRecorder.Eventf(deployment, v1.EventTypeNormal, \"ScalingReplicaSet\", \"Scaled %s replica set %s to %d from %d\", scalingOperation, rs.Name, newScale, oldScale)\n\t\t}\n\t}\n\treturn scaled, rs, err\n}","line":{"from":413,"to":433}} {"id":100003602,"name":"cleanupDeployment","signature":"func (dc *DeploymentController) cleanupDeployment(ctx context.Context, oldRSs []*apps.ReplicaSet, deployment *apps.Deployment) error","file":"pkg/controller/deployment/sync.go","code":"// cleanupDeployment is responsible for cleaning up a deployment ie. retains all but the latest N old replica sets\n// where N=d.Spec.RevisionHistoryLimit. Old replica sets are older versions of the podtemplate of a deployment kept\n// around by default 1) for historical reasons and 2) for the ability to rollback a deployment.\nfunc (dc *DeploymentController) cleanupDeployment(ctx context.Context, oldRSs []*apps.ReplicaSet, deployment *apps.Deployment) error {\n\tlogger := klog.FromContext(ctx)\n\tif !deploymentutil.HasRevisionHistoryLimit(deployment) {\n\t\treturn nil\n\t}\n\n\t// Avoid deleting replica set with deletion timestamp set\n\taliveFilter := func(rs *apps.ReplicaSet) bool {\n\t\treturn rs != nil \u0026\u0026 rs.ObjectMeta.DeletionTimestamp == nil\n\t}\n\tcleanableRSes := controller.FilterReplicaSets(oldRSs, aliveFilter)\n\n\tdiff := int32(len(cleanableRSes)) - *deployment.Spec.RevisionHistoryLimit\n\tif diff \u003c= 0 {\n\t\treturn nil\n\t}\n\n\tsort.Sort(deploymentutil.ReplicaSetsByRevision(cleanableRSes))\n\tlogger.V(4).Info(\"Looking to cleanup old replica sets for deployment\", \"deployment\", klog.KObj(deployment))\n\n\tfor i := int32(0); i \u003c diff; i++ {\n\t\trs := cleanableRSes[i]\n\t\t// Avoid delete replica set with non-zero replica counts\n\t\tif rs.Status.Replicas != 0 || *(rs.Spec.Replicas) != 0 || rs.Generation \u003e rs.Status.ObservedGeneration || rs.DeletionTimestamp != nil {\n\t\t\tcontinue\n\t\t}\n\t\tlogger.V(4).Info(\"Trying to cleanup replica set for deployment\", \"replicaSet\", klog.KObj(rs), \"deployment\", klog.KObj(deployment))\n\t\tif err := dc.client.AppsV1().ReplicaSets(rs.Namespace).Delete(ctx, rs.Name, metav1.DeleteOptions{}); err != nil \u0026\u0026 !errors.IsNotFound(err) {\n\t\t\t// Return error instead of aggregating and continuing DELETEs on the theory\n\t\t\t// that we may be overloading the api server.\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":435,"to":473}} {"id":100003603,"name":"syncDeploymentStatus","signature":"func (dc *DeploymentController) syncDeploymentStatus(ctx context.Context, allRSs []*apps.ReplicaSet, newRS *apps.ReplicaSet, d *apps.Deployment) error","file":"pkg/controller/deployment/sync.go","code":"// syncDeploymentStatus checks if the status is up-to-date and sync it if necessary\nfunc (dc *DeploymentController) syncDeploymentStatus(ctx context.Context, allRSs []*apps.ReplicaSet, newRS *apps.ReplicaSet, d *apps.Deployment) error {\n\tnewStatus := calculateStatus(allRSs, newRS, d)\n\n\tif reflect.DeepEqual(d.Status, newStatus) {\n\t\treturn nil\n\t}\n\n\tnewDeployment := d\n\tnewDeployment.Status = newStatus\n\t_, err := dc.client.AppsV1().Deployments(newDeployment.Namespace).UpdateStatus(ctx, newDeployment, metav1.UpdateOptions{})\n\treturn err\n}","line":{"from":475,"to":487}} {"id":100003604,"name":"calculateStatus","signature":"func calculateStatus(allRSs []*apps.ReplicaSet, newRS *apps.ReplicaSet, deployment *apps.Deployment) apps.DeploymentStatus","file":"pkg/controller/deployment/sync.go","code":"// calculateStatus calculates the latest status for the provided deployment by looking into the provided replica sets.\nfunc calculateStatus(allRSs []*apps.ReplicaSet, newRS *apps.ReplicaSet, deployment *apps.Deployment) apps.DeploymentStatus {\n\tavailableReplicas := deploymentutil.GetAvailableReplicaCountForReplicaSets(allRSs)\n\ttotalReplicas := deploymentutil.GetReplicaCountForReplicaSets(allRSs)\n\tunavailableReplicas := totalReplicas - availableReplicas\n\t// If unavailableReplicas is negative, then that means the Deployment has more available replicas running than\n\t// desired, e.g. whenever it scales down. In such a case we should simply default unavailableReplicas to zero.\n\tif unavailableReplicas \u003c 0 {\n\t\tunavailableReplicas = 0\n\t}\n\n\tstatus := apps.DeploymentStatus{\n\t\t// TODO: Ensure that if we start retrying status updates, we won't pick up a new Generation value.\n\t\tObservedGeneration: deployment.Generation,\n\t\tReplicas: deploymentutil.GetActualReplicaCountForReplicaSets(allRSs),\n\t\tUpdatedReplicas: deploymentutil.GetActualReplicaCountForReplicaSets([]*apps.ReplicaSet{newRS}),\n\t\tReadyReplicas: deploymentutil.GetReadyReplicaCountForReplicaSets(allRSs),\n\t\tAvailableReplicas: availableReplicas,\n\t\tUnavailableReplicas: unavailableReplicas,\n\t\tCollisionCount: deployment.Status.CollisionCount,\n\t}\n\n\t// Copy conditions one by one so we won't mutate the original object.\n\tconditions := deployment.Status.Conditions\n\tfor i := range conditions {\n\t\tstatus.Conditions = append(status.Conditions, conditions[i])\n\t}\n\n\tif availableReplicas \u003e= *(deployment.Spec.Replicas)-deploymentutil.MaxUnavailable(*deployment) {\n\t\tminAvailability := deploymentutil.NewDeploymentCondition(apps.DeploymentAvailable, v1.ConditionTrue, deploymentutil.MinimumReplicasAvailable, \"Deployment has minimum availability.\")\n\t\tdeploymentutil.SetDeploymentCondition(\u0026status, *minAvailability)\n\t} else {\n\t\tnoMinAvailability := deploymentutil.NewDeploymentCondition(apps.DeploymentAvailable, v1.ConditionFalse, deploymentutil.MinimumReplicasUnavailable, \"Deployment does not have minimum availability.\")\n\t\tdeploymentutil.SetDeploymentCondition(\u0026status, *noMinAvailability)\n\t}\n\n\treturn status\n}","line":{"from":489,"to":526}} {"id":100003605,"name":"isScalingEvent","signature":"func (dc *DeploymentController) isScalingEvent(ctx context.Context, d *apps.Deployment, rsList []*apps.ReplicaSet) (bool, error)","file":"pkg/controller/deployment/sync.go","code":"// isScalingEvent checks whether the provided deployment has been updated with a scaling event\n// by looking at the desired-replicas annotation in the active replica sets of the deployment.\n//\n// rsList should come from getReplicaSetsForDeployment(d).\nfunc (dc *DeploymentController) isScalingEvent(ctx context.Context, d *apps.Deployment, rsList []*apps.ReplicaSet) (bool, error) {\n\tnewRS, oldRSs, err := dc.getAllReplicaSetsAndSyncRevision(ctx, d, rsList, false)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tallRSs := append(oldRSs, newRS)\n\tlogger := klog.FromContext(ctx)\n\tfor _, rs := range controller.FilterActiveReplicaSets(allRSs) {\n\t\tdesired, ok := deploymentutil.GetDesiredReplicasAnnotation(logger, rs)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tif desired != *(d.Spec.Replicas) {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}","line":{"from":528,"to":549}} {"id":100003606,"name":"NewDeploymentCondition","signature":"func NewDeploymentCondition(condType apps.DeploymentConditionType, status v1.ConditionStatus, reason, message string) *apps.DeploymentCondition","file":"pkg/controller/deployment/util/deployment_util.go","code":"// NewDeploymentCondition creates a new deployment condition.\nfunc NewDeploymentCondition(condType apps.DeploymentConditionType, status v1.ConditionStatus, reason, message string) *apps.DeploymentCondition {\n\treturn \u0026apps.DeploymentCondition{\n\t\tType: condType,\n\t\tStatus: status,\n\t\tLastUpdateTime: metav1.Now(),\n\t\tLastTransitionTime: metav1.Now(),\n\t\tReason: reason,\n\t\tMessage: message,\n\t}\n}","line":{"from":103,"to":113}} {"id":100003607,"name":"GetDeploymentCondition","signature":"func GetDeploymentCondition(status apps.DeploymentStatus, condType apps.DeploymentConditionType) *apps.DeploymentCondition","file":"pkg/controller/deployment/util/deployment_util.go","code":"// GetDeploymentCondition returns the condition with the provided type.\nfunc GetDeploymentCondition(status apps.DeploymentStatus, condType apps.DeploymentConditionType) *apps.DeploymentCondition {\n\tfor i := range status.Conditions {\n\t\tc := status.Conditions[i]\n\t\tif c.Type == condType {\n\t\t\treturn \u0026c\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":115,"to":124}} {"id":100003608,"name":"SetDeploymentCondition","signature":"func SetDeploymentCondition(status *apps.DeploymentStatus, condition apps.DeploymentCondition)","file":"pkg/controller/deployment/util/deployment_util.go","code":"// SetDeploymentCondition updates the deployment to include the provided condition. If the condition that\n// we are about to add already exists and has the same status and reason then we are not going to update.\nfunc SetDeploymentCondition(status *apps.DeploymentStatus, condition apps.DeploymentCondition) {\n\tcurrentCond := GetDeploymentCondition(*status, condition.Type)\n\tif currentCond != nil \u0026\u0026 currentCond.Status == condition.Status \u0026\u0026 currentCond.Reason == condition.Reason {\n\t\treturn\n\t}\n\t// Do not update lastTransitionTime if the status of the condition doesn't change.\n\tif currentCond != nil \u0026\u0026 currentCond.Status == condition.Status {\n\t\tcondition.LastTransitionTime = currentCond.LastTransitionTime\n\t}\n\tnewConditions := filterOutCondition(status.Conditions, condition.Type)\n\tstatus.Conditions = append(newConditions, condition)\n}","line":{"from":126,"to":139}} {"id":100003609,"name":"RemoveDeploymentCondition","signature":"func RemoveDeploymentCondition(status *apps.DeploymentStatus, condType apps.DeploymentConditionType)","file":"pkg/controller/deployment/util/deployment_util.go","code":"// RemoveDeploymentCondition removes the deployment condition with the provided type.\nfunc RemoveDeploymentCondition(status *apps.DeploymentStatus, condType apps.DeploymentConditionType) {\n\tstatus.Conditions = filterOutCondition(status.Conditions, condType)\n}","line":{"from":141,"to":144}} {"id":100003610,"name":"filterOutCondition","signature":"func filterOutCondition(conditions []apps.DeploymentCondition, condType apps.DeploymentConditionType) []apps.DeploymentCondition","file":"pkg/controller/deployment/util/deployment_util.go","code":"// filterOutCondition returns a new slice of deployment conditions without conditions with the provided type.\nfunc filterOutCondition(conditions []apps.DeploymentCondition, condType apps.DeploymentConditionType) []apps.DeploymentCondition {\n\tvar newConditions []apps.DeploymentCondition\n\tfor _, c := range conditions {\n\t\tif c.Type == condType {\n\t\t\tcontinue\n\t\t}\n\t\tnewConditions = append(newConditions, c)\n\t}\n\treturn newConditions\n}","line":{"from":146,"to":156}} {"id":100003611,"name":"ReplicaSetToDeploymentCondition","signature":"func ReplicaSetToDeploymentCondition(cond apps.ReplicaSetCondition) apps.DeploymentCondition","file":"pkg/controller/deployment/util/deployment_util.go","code":"// ReplicaSetToDeploymentCondition converts a replica set condition into a deployment condition.\n// Useful for promoting replica set failure conditions into deployments.\nfunc ReplicaSetToDeploymentCondition(cond apps.ReplicaSetCondition) apps.DeploymentCondition {\n\treturn apps.DeploymentCondition{\n\t\tType: apps.DeploymentConditionType(cond.Type),\n\t\tStatus: cond.Status,\n\t\tLastTransitionTime: cond.LastTransitionTime,\n\t\tLastUpdateTime: cond.LastTransitionTime,\n\t\tReason: cond.Reason,\n\t\tMessage: cond.Message,\n\t}\n}","line":{"from":158,"to":169}} {"id":100003612,"name":"SetDeploymentRevision","signature":"func SetDeploymentRevision(deployment *apps.Deployment, revision string) bool","file":"pkg/controller/deployment/util/deployment_util.go","code":"// SetDeploymentRevision updates the revision for a deployment.\nfunc SetDeploymentRevision(deployment *apps.Deployment, revision string) bool {\n\tupdated := false\n\n\tif deployment.Annotations == nil {\n\t\tdeployment.Annotations = make(map[string]string)\n\t}\n\tif deployment.Annotations[RevisionAnnotation] != revision {\n\t\tdeployment.Annotations[RevisionAnnotation] = revision\n\t\tupdated = true\n\t}\n\n\treturn updated\n}","line":{"from":171,"to":184}} {"id":100003613,"name":"MaxRevision","signature":"func MaxRevision(allRSs []*apps.ReplicaSet) int64","file":"pkg/controller/deployment/util/deployment_util.go","code":"// MaxRevision finds the highest revision in the replica sets\nfunc MaxRevision(allRSs []*apps.ReplicaSet) int64 {\n\tmax := int64(0)\n\tfor _, rs := range allRSs {\n\t\tif v, err := Revision(rs); err != nil {\n\t\t\t// Skip the replica sets when it failed to parse their revision information\n\t\t\tklog.V(4).Info(\"Couldn't parse revision for replica set, deployment controller will skip it when reconciling revisions\", \"replicaSet\", klog.KObj(rs), \"err\", err)\n\t\t} else if v \u003e max {\n\t\t\tmax = v\n\t\t}\n\t}\n\treturn max\n}","line":{"from":186,"to":198}} {"id":100003614,"name":"LastRevision","signature":"func LastRevision(allRSs []*apps.ReplicaSet) int64","file":"pkg/controller/deployment/util/deployment_util.go","code":"// LastRevision finds the second max revision number in all replica sets (the last revision)\nfunc LastRevision(allRSs []*apps.ReplicaSet) int64 {\n\tmax, secMax := int64(0), int64(0)\n\tfor _, rs := range allRSs {\n\t\tif v, err := Revision(rs); err != nil {\n\t\t\t// Skip the replica sets when it failed to parse their revision information\n\t\t\tklog.V(4).Info(\"Couldn't parse revision for replica set, deployment controller will skip it when reconciling revisions\", \"replicaSet\", klog.KObj(rs), \"err\", err)\n\t\t} else if v \u003e= max {\n\t\t\tsecMax = max\n\t\t\tmax = v\n\t\t} else if v \u003e secMax {\n\t\t\tsecMax = v\n\t\t}\n\t}\n\treturn secMax\n}","line":{"from":200,"to":215}} {"id":100003615,"name":"Revision","signature":"func Revision(obj runtime.Object) (int64, error)","file":"pkg/controller/deployment/util/deployment_util.go","code":"// Revision returns the revision number of the input object.\nfunc Revision(obj runtime.Object) (int64, error) {\n\tacc, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tv, ok := acc.GetAnnotations()[RevisionAnnotation]\n\tif !ok {\n\t\treturn 0, nil\n\t}\n\treturn strconv.ParseInt(v, 10, 64)\n}","line":{"from":217,"to":228}} {"id":100003616,"name":"SetNewReplicaSetAnnotations","signature":"func SetNewReplicaSetAnnotations(ctx context.Context, deployment *apps.Deployment, newRS *apps.ReplicaSet, newRevision string, exists bool, revHistoryLimitInChars int) bool","file":"pkg/controller/deployment/util/deployment_util.go","code":"// SetNewReplicaSetAnnotations sets new replica set's annotations appropriately by updating its revision and\n// copying required deployment annotations to it; it returns true if replica set's annotation is changed.\nfunc SetNewReplicaSetAnnotations(ctx context.Context, deployment *apps.Deployment, newRS *apps.ReplicaSet, newRevision string, exists bool, revHistoryLimitInChars int) bool {\n\tlogger := klog.FromContext(ctx)\n\t// First, copy deployment's annotations (except for apply and revision annotations)\n\tannotationChanged := copyDeploymentAnnotationsToReplicaSet(deployment, newRS)\n\t// Then, update replica set's revision annotation\n\tif newRS.Annotations == nil {\n\t\tnewRS.Annotations = make(map[string]string)\n\t}\n\toldRevision, ok := newRS.Annotations[RevisionAnnotation]\n\t// The newRS's revision should be the greatest among all RSes. Usually, its revision number is newRevision (the max revision number\n\t// of all old RSes + 1). However, it's possible that some of the old RSes are deleted after the newRS revision being updated, and\n\t// newRevision becomes smaller than newRS's revision. We should only update newRS revision when it's smaller than newRevision.\n\n\toldRevisionInt, err := strconv.ParseInt(oldRevision, 10, 64)\n\tif err != nil {\n\t\tif oldRevision != \"\" {\n\t\t\tlogger.Info(\"Updating replica set revision OldRevision not int\", \"err\", err)\n\t\t\treturn false\n\t\t}\n\t\t//If the RS annotation is empty then initialise it to 0\n\t\toldRevisionInt = 0\n\t}\n\tnewRevisionInt, err := strconv.ParseInt(newRevision, 10, 64)\n\tif err != nil {\n\t\tlogger.Info(\"Updating replica set revision NewRevision not int\", \"err\", err)\n\t\treturn false\n\t}\n\tif oldRevisionInt \u003c newRevisionInt {\n\t\tnewRS.Annotations[RevisionAnnotation] = newRevision\n\t\tannotationChanged = true\n\t\tlogger.V(4).Info(\"Updating replica set revision\", \"replicaSet\", klog.KObj(newRS), \"newRevision\", newRevision)\n\t}\n\t// If a revision annotation already existed and this replica set was updated with a new revision\n\t// then that means we are rolling back to this replica set. We need to preserve the old revisions\n\t// for historical information.\n\tif ok \u0026\u0026 oldRevisionInt \u003c newRevisionInt {\n\t\trevisionHistoryAnnotation := newRS.Annotations[RevisionHistoryAnnotation]\n\t\toldRevisions := strings.Split(revisionHistoryAnnotation, \",\")\n\t\tif len(oldRevisions[0]) == 0 {\n\t\t\tnewRS.Annotations[RevisionHistoryAnnotation] = oldRevision\n\t\t} else {\n\t\t\ttotalLen := len(revisionHistoryAnnotation) + len(oldRevision) + 1\n\t\t\t// index for the starting position in oldRevisions\n\t\t\tstart := 0\n\t\t\tfor totalLen \u003e revHistoryLimitInChars \u0026\u0026 start \u003c len(oldRevisions) {\n\t\t\t\ttotalLen = totalLen - len(oldRevisions[start]) - 1\n\t\t\t\tstart++\n\t\t\t}\n\t\t\tif totalLen \u003c= revHistoryLimitInChars {\n\t\t\t\toldRevisions = append(oldRevisions[start:], oldRevision)\n\t\t\t\tnewRS.Annotations[RevisionHistoryAnnotation] = strings.Join(oldRevisions, \",\")\n\t\t\t} else {\n\t\t\t\tlogger.Info(\"Not appending revision due to revision history length limit reached\", \"revisionHistoryLimit\", revHistoryLimitInChars)\n\t\t\t}\n\t\t}\n\t}\n\t// If the new replica set is about to be created, we need to add replica annotations to it.\n\tif !exists \u0026\u0026 SetReplicasAnnotations(newRS, *(deployment.Spec.Replicas), *(deployment.Spec.Replicas)+MaxSurge(*deployment)) {\n\t\tannotationChanged = true\n\t}\n\treturn annotationChanged\n}","line":{"from":230,"to":293}} {"id":100003617,"name":"skipCopyAnnotation","signature":"func skipCopyAnnotation(key string) bool","file":"pkg/controller/deployment/util/deployment_util.go","code":"// skipCopyAnnotation returns true if we should skip copying the annotation with the given annotation key\n// TODO: How to decide which annotations should / should not be copied?\n//\n// See https://github.com/kubernetes/kubernetes/pull/20035#issuecomment-179558615\nfunc skipCopyAnnotation(key string) bool {\n\treturn annotationsToSkip[key]\n}","line":{"from":304,"to":310}} {"id":100003618,"name":"copyDeploymentAnnotationsToReplicaSet","signature":"func copyDeploymentAnnotationsToReplicaSet(deployment *apps.Deployment, rs *apps.ReplicaSet) bool","file":"pkg/controller/deployment/util/deployment_util.go","code":"// copyDeploymentAnnotationsToReplicaSet copies deployment's annotations to replica set's annotations,\n// and returns true if replica set's annotation is changed.\n// Note that apply and revision annotations are not copied.\nfunc copyDeploymentAnnotationsToReplicaSet(deployment *apps.Deployment, rs *apps.ReplicaSet) bool {\n\trsAnnotationsChanged := false\n\tif rs.Annotations == nil {\n\t\trs.Annotations = make(map[string]string)\n\t}\n\tfor k, v := range deployment.Annotations {\n\t\t// newRS revision is updated automatically in getNewReplicaSet, and the deployment's revision number is then updated\n\t\t// by copying its newRS revision number. We should not copy deployment's revision to its newRS, since the update of\n\t\t// deployment revision number may fail (revision becomes stale) and the revision number in newRS is more reliable.\n\t\tif _, exist := rs.Annotations[k]; skipCopyAnnotation(k) || (exist \u0026\u0026 rs.Annotations[k] == v) {\n\t\t\tcontinue\n\t\t}\n\t\trs.Annotations[k] = v\n\t\trsAnnotationsChanged = true\n\t}\n\treturn rsAnnotationsChanged\n}","line":{"from":312,"to":331}} {"id":100003619,"name":"SetDeploymentAnnotationsTo","signature":"func SetDeploymentAnnotationsTo(deployment *apps.Deployment, rollbackToRS *apps.ReplicaSet)","file":"pkg/controller/deployment/util/deployment_util.go","code":"// SetDeploymentAnnotationsTo sets deployment's annotations as given RS's annotations.\n// This action should be done if and only if the deployment is rolling back to this rs.\n// Note that apply and revision annotations are not changed.\nfunc SetDeploymentAnnotationsTo(deployment *apps.Deployment, rollbackToRS *apps.ReplicaSet) {\n\tdeployment.Annotations = getSkippedAnnotations(deployment.Annotations)\n\tfor k, v := range rollbackToRS.Annotations {\n\t\tif !skipCopyAnnotation(k) {\n\t\t\tdeployment.Annotations[k] = v\n\t\t}\n\t}\n}","line":{"from":333,"to":343}} {"id":100003620,"name":"getSkippedAnnotations","signature":"func getSkippedAnnotations(annotations map[string]string) map[string]string","file":"pkg/controller/deployment/util/deployment_util.go","code":"func getSkippedAnnotations(annotations map[string]string) map[string]string {\n\tskippedAnnotations := make(map[string]string)\n\tfor k, v := range annotations {\n\t\tif skipCopyAnnotation(k) {\n\t\t\tskippedAnnotations[k] = v\n\t\t}\n\t}\n\treturn skippedAnnotations\n}","line":{"from":345,"to":353}} {"id":100003621,"name":"FindActiveOrLatest","signature":"func FindActiveOrLatest(newRS *apps.ReplicaSet, oldRSs []*apps.ReplicaSet) *apps.ReplicaSet","file":"pkg/controller/deployment/util/deployment_util.go","code":"// FindActiveOrLatest returns the only active or the latest replica set in case there is at most one active\n// replica set. If there are more active replica sets, then we should proportionally scale them.\nfunc FindActiveOrLatest(newRS *apps.ReplicaSet, oldRSs []*apps.ReplicaSet) *apps.ReplicaSet {\n\tif newRS == nil \u0026\u0026 len(oldRSs) == 0 {\n\t\treturn nil\n\t}\n\n\tsort.Sort(sort.Reverse(controller.ReplicaSetsByCreationTimestamp(oldRSs)))\n\tallRSs := controller.FilterActiveReplicaSets(append(oldRSs, newRS))\n\n\tswitch len(allRSs) {\n\tcase 0:\n\t\t// If there is no active replica set then we should return the newest.\n\t\tif newRS != nil {\n\t\t\treturn newRS\n\t\t}\n\t\treturn oldRSs[0]\n\tcase 1:\n\t\treturn allRSs[0]\n\tdefault:\n\t\treturn nil\n\t}\n}","line":{"from":355,"to":377}} {"id":100003622,"name":"GetDesiredReplicasAnnotation","signature":"func GetDesiredReplicasAnnotation(logger klog.Logger, rs *apps.ReplicaSet) (int32, bool)","file":"pkg/controller/deployment/util/deployment_util.go","code":"// GetDesiredReplicasAnnotation returns the number of desired replicas\nfunc GetDesiredReplicasAnnotation(logger klog.Logger, rs *apps.ReplicaSet) (int32, bool) {\n\treturn getIntFromAnnotation(logger, rs, DesiredReplicasAnnotation)\n}","line":{"from":379,"to":382}} {"id":100003623,"name":"getMaxReplicasAnnotation","signature":"func getMaxReplicasAnnotation(logger klog.Logger, rs *apps.ReplicaSet) (int32, bool)","file":"pkg/controller/deployment/util/deployment_util.go","code":"func getMaxReplicasAnnotation(logger klog.Logger, rs *apps.ReplicaSet) (int32, bool) {\n\treturn getIntFromAnnotation(logger, rs, MaxReplicasAnnotation)\n}","line":{"from":384,"to":386}} {"id":100003624,"name":"getIntFromAnnotation","signature":"func getIntFromAnnotation(logger klog.Logger, rs *apps.ReplicaSet, annotationKey string) (int32, bool)","file":"pkg/controller/deployment/util/deployment_util.go","code":"func getIntFromAnnotation(logger klog.Logger, rs *apps.ReplicaSet, annotationKey string) (int32, bool) {\n\tannotationValue, ok := rs.Annotations[annotationKey]\n\tif !ok {\n\t\treturn int32(0), false\n\t}\n\tintValue, err := strconv.Atoi(annotationValue)\n\tif err != nil {\n\t\tlogger.V(2).Info(\"Could not convert the value with annotation key for the replica set\", \"annotationValue\", annotationValue, \"annotationKey\", annotationKey, \"replicaSet\", klog.KObj(rs))\n\t\treturn int32(0), false\n\t}\n\treturn int32(intValue), true\n}","line":{"from":388,"to":399}} {"id":100003625,"name":"SetReplicasAnnotations","signature":"func SetReplicasAnnotations(rs *apps.ReplicaSet, desiredReplicas, maxReplicas int32) bool","file":"pkg/controller/deployment/util/deployment_util.go","code":"// SetReplicasAnnotations sets the desiredReplicas and maxReplicas into the annotations\nfunc SetReplicasAnnotations(rs *apps.ReplicaSet, desiredReplicas, maxReplicas int32) bool {\n\tupdated := false\n\tif rs.Annotations == nil {\n\t\trs.Annotations = make(map[string]string)\n\t}\n\tdesiredString := fmt.Sprintf(\"%d\", desiredReplicas)\n\tif hasString := rs.Annotations[DesiredReplicasAnnotation]; hasString != desiredString {\n\t\trs.Annotations[DesiredReplicasAnnotation] = desiredString\n\t\tupdated = true\n\t}\n\tmaxString := fmt.Sprintf(\"%d\", maxReplicas)\n\tif hasString := rs.Annotations[MaxReplicasAnnotation]; hasString != maxString {\n\t\trs.Annotations[MaxReplicasAnnotation] = maxString\n\t\tupdated = true\n\t}\n\treturn updated\n}","line":{"from":401,"to":418}} {"id":100003626,"name":"ReplicasAnnotationsNeedUpdate","signature":"func ReplicasAnnotationsNeedUpdate(rs *apps.ReplicaSet, desiredReplicas, maxReplicas int32) bool","file":"pkg/controller/deployment/util/deployment_util.go","code":"// ReplicasAnnotationsNeedUpdate return true if ReplicasAnnotations need to be updated\nfunc ReplicasAnnotationsNeedUpdate(rs *apps.ReplicaSet, desiredReplicas, maxReplicas int32) bool {\n\tif rs.Annotations == nil {\n\t\treturn true\n\t}\n\tdesiredString := fmt.Sprintf(\"%d\", desiredReplicas)\n\tif hasString := rs.Annotations[DesiredReplicasAnnotation]; hasString != desiredString {\n\t\treturn true\n\t}\n\tmaxString := fmt.Sprintf(\"%d\", maxReplicas)\n\tif hasString := rs.Annotations[MaxReplicasAnnotation]; hasString != maxString {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":420,"to":434}} {"id":100003627,"name":"MaxUnavailable","signature":"func MaxUnavailable(deployment apps.Deployment) int32","file":"pkg/controller/deployment/util/deployment_util.go","code":"// MaxUnavailable returns the maximum unavailable pods a rolling deployment can take.\nfunc MaxUnavailable(deployment apps.Deployment) int32 {\n\tif !IsRollingUpdate(\u0026deployment) || *(deployment.Spec.Replicas) == 0 {\n\t\treturn int32(0)\n\t}\n\t// Error caught by validation\n\t_, maxUnavailable, _ := ResolveFenceposts(deployment.Spec.Strategy.RollingUpdate.MaxSurge, deployment.Spec.Strategy.RollingUpdate.MaxUnavailable, *(deployment.Spec.Replicas))\n\tif maxUnavailable \u003e *deployment.Spec.Replicas {\n\t\treturn *deployment.Spec.Replicas\n\t}\n\treturn maxUnavailable\n}","line":{"from":436,"to":447}} {"id":100003628,"name":"MinAvailable","signature":"func MinAvailable(deployment *apps.Deployment) int32","file":"pkg/controller/deployment/util/deployment_util.go","code":"// MinAvailable returns the minimum available pods of a given deployment\nfunc MinAvailable(deployment *apps.Deployment) int32 {\n\tif !IsRollingUpdate(deployment) {\n\t\treturn int32(0)\n\t}\n\treturn *(deployment.Spec.Replicas) - MaxUnavailable(*deployment)\n}","line":{"from":449,"to":455}} {"id":100003629,"name":"MaxSurge","signature":"func MaxSurge(deployment apps.Deployment) int32","file":"pkg/controller/deployment/util/deployment_util.go","code":"// MaxSurge returns the maximum surge pods a rolling deployment can take.\nfunc MaxSurge(deployment apps.Deployment) int32 {\n\tif !IsRollingUpdate(\u0026deployment) {\n\t\treturn int32(0)\n\t}\n\t// Error caught by validation\n\tmaxSurge, _, _ := ResolveFenceposts(deployment.Spec.Strategy.RollingUpdate.MaxSurge, deployment.Spec.Strategy.RollingUpdate.MaxUnavailable, *(deployment.Spec.Replicas))\n\treturn maxSurge\n}","line":{"from":457,"to":465}} {"id":100003630,"name":"GetProportion","signature":"func GetProportion(logger klog.Logger, rs *apps.ReplicaSet, d apps.Deployment, deploymentReplicasToAdd, deploymentReplicasAdded int32) int32","file":"pkg/controller/deployment/util/deployment_util.go","code":"// GetProportion will estimate the proportion for the provided replica set using 1. the current size\n// of the parent deployment, 2. the replica count that needs be added on the replica sets of the\n// deployment, and 3. the total replicas added in the replica sets of the deployment so far.\nfunc GetProportion(logger klog.Logger, rs *apps.ReplicaSet, d apps.Deployment, deploymentReplicasToAdd, deploymentReplicasAdded int32) int32 {\n\tif rs == nil || *(rs.Spec.Replicas) == 0 || deploymentReplicasToAdd == 0 || deploymentReplicasToAdd == deploymentReplicasAdded {\n\t\treturn int32(0)\n\t}\n\n\trsFraction := getReplicaSetFraction(logger, *rs, d)\n\tallowed := deploymentReplicasToAdd - deploymentReplicasAdded\n\n\tif deploymentReplicasToAdd \u003e 0 {\n\t\t// Use the minimum between the replica set fraction and the maximum allowed replicas\n\t\t// when scaling up. This way we ensure we will not scale up more than the allowed\n\t\t// replicas we can add.\n\t\treturn integer.Int32Min(rsFraction, allowed)\n\t}\n\t// Use the maximum between the replica set fraction and the maximum allowed replicas\n\t// when scaling down. This way we ensure we will not scale down more than the allowed\n\t// replicas we can remove.\n\treturn integer.Int32Max(rsFraction, allowed)\n}","line":{"from":467,"to":488}} {"id":100003631,"name":"getReplicaSetFraction","signature":"func getReplicaSetFraction(logger klog.Logger, rs apps.ReplicaSet, d apps.Deployment) int32","file":"pkg/controller/deployment/util/deployment_util.go","code":"// getReplicaSetFraction estimates the fraction of replicas a replica set can have in\n// 1. a scaling event during a rollout or 2. when scaling a paused deployment.\nfunc getReplicaSetFraction(logger klog.Logger, rs apps.ReplicaSet, d apps.Deployment) int32 {\n\t// If we are scaling down to zero then the fraction of this replica set is its whole size (negative)\n\tif *(d.Spec.Replicas) == int32(0) {\n\t\treturn -*(rs.Spec.Replicas)\n\t}\n\n\tdeploymentReplicas := *(d.Spec.Replicas) + MaxSurge(d)\n\tannotatedReplicas, ok := getMaxReplicasAnnotation(logger, \u0026rs)\n\tif !ok {\n\t\t// If we cannot find the annotation then fallback to the current deployment size. Note that this\n\t\t// will not be an accurate proportion estimation in case other replica sets have different values\n\t\t// which means that the deployment was scaled at some point but we at least will stay in limits\n\t\t// due to the min-max comparisons in getProportion.\n\t\tannotatedReplicas = d.Status.Replicas\n\t}\n\n\t// We should never proportionally scale up from zero which means rs.spec.replicas and annotatedReplicas\n\t// will never be zero here.\n\tnewRSsize := (float64(*(rs.Spec.Replicas) * deploymentReplicas)) / float64(annotatedReplicas)\n\treturn integer.RoundToInt32(newRSsize) - *(rs.Spec.Replicas)\n}","line":{"from":490,"to":512}} {"id":100003632,"name":"RsListFromClient","signature":"func RsListFromClient(c appsclient.AppsV1Interface) RsListFunc","file":"pkg/controller/deployment/util/deployment_util.go","code":"// RsListFromClient returns an rsListFunc that wraps the given client.\nfunc RsListFromClient(c appsclient.AppsV1Interface) RsListFunc {\n\treturn func(namespace string, options metav1.ListOptions) ([]*apps.ReplicaSet, error) {\n\t\trsList, err := c.ReplicaSets(namespace).List(context.TODO(), options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar ret []*apps.ReplicaSet\n\t\tfor i := range rsList.Items {\n\t\t\tret = append(ret, \u0026rsList.Items[i])\n\t\t}\n\t\treturn ret, err\n\t}\n}","line":{"from":514,"to":527}} {"id":100003633,"name":"ListReplicaSets","signature":"func ListReplicaSets(deployment *apps.Deployment, getRSList RsListFunc) ([]*apps.ReplicaSet, error)","file":"pkg/controller/deployment/util/deployment_util.go","code":"// ListReplicaSets returns a slice of RSes the given deployment targets.\n// Note that this does NOT attempt to reconcile ControllerRef (adopt/orphan),\n// because only the controller itself should do that.\n// However, it does filter out anything whose ControllerRef doesn't match.\nfunc ListReplicaSets(deployment *apps.Deployment, getRSList RsListFunc) ([]*apps.ReplicaSet, error) {\n\t// TODO: Right now we list replica sets by their labels. We should list them by selector, i.e. the replica set's selector\n\t// should be a superset of the deployment's selector, see https://github.com/kubernetes/kubernetes/issues/19830.\n\tnamespace := deployment.Namespace\n\tselector, err := metav1.LabelSelectorAsSelector(deployment.Spec.Selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\toptions := metav1.ListOptions{LabelSelector: selector.String()}\n\tall, err := getRSList(namespace, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Only include those whose ControllerRef matches the Deployment.\n\towned := make([]*apps.ReplicaSet, 0, len(all))\n\tfor _, rs := range all {\n\t\tif metav1.IsControlledBy(rs, deployment) {\n\t\t\towned = append(owned, rs)\n\t\t}\n\t}\n\treturn owned, nil\n}","line":{"from":537,"to":562}} {"id":100003634,"name":"ListPods","signature":"func ListPods(deployment *apps.Deployment, rsList []*apps.ReplicaSet, getPodList podListFunc) (*v1.PodList, error)","file":"pkg/controller/deployment/util/deployment_util.go","code":"// ListPods returns a list of pods the given deployment targets.\n// This needs a list of ReplicaSets for the Deployment,\n// which can be found with ListReplicaSets().\n// Note that this does NOT attempt to reconcile ControllerRef (adopt/orphan),\n// because only the controller itself should do that.\n// However, it does filter out anything whose ControllerRef doesn't match.\nfunc ListPods(deployment *apps.Deployment, rsList []*apps.ReplicaSet, getPodList podListFunc) (*v1.PodList, error) {\n\tnamespace := deployment.Namespace\n\tselector, err := metav1.LabelSelectorAsSelector(deployment.Spec.Selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\toptions := metav1.ListOptions{LabelSelector: selector.String()}\n\tall, err := getPodList(namespace, options)\n\tif err != nil {\n\t\treturn all, err\n\t}\n\t// Only include those whose ControllerRef points to a ReplicaSet that is in\n\t// turn owned by this Deployment.\n\trsMap := make(map[types.UID]bool, len(rsList))\n\tfor _, rs := range rsList {\n\t\trsMap[rs.UID] = true\n\t}\n\towned := \u0026v1.PodList{Items: make([]v1.Pod, 0, len(all.Items))}\n\tfor i := range all.Items {\n\t\tpod := \u0026all.Items[i]\n\t\tcontrollerRef := metav1.GetControllerOf(pod)\n\t\tif controllerRef != nil \u0026\u0026 rsMap[controllerRef.UID] {\n\t\t\towned.Items = append(owned.Items, *pod)\n\t\t}\n\t}\n\treturn owned, nil\n}","line":{"from":564,"to":596}} {"id":100003635,"name":"EqualIgnoreHash","signature":"func EqualIgnoreHash(template1, template2 *v1.PodTemplateSpec) bool","file":"pkg/controller/deployment/util/deployment_util.go","code":"// EqualIgnoreHash returns true if two given podTemplateSpec are equal, ignoring the diff in value of Labels[pod-template-hash]\n// We ignore pod-template-hash because:\n// 1. The hash result would be different upon podTemplateSpec API changes\n// (e.g. the addition of a new field will cause the hash code to change)\n// 2. The deployment template won't have hash labels\nfunc EqualIgnoreHash(template1, template2 *v1.PodTemplateSpec) bool {\n\tt1Copy := template1.DeepCopy()\n\tt2Copy := template2.DeepCopy()\n\t// Remove hash labels from template.Labels before comparing\n\tdelete(t1Copy.Labels, apps.DefaultDeploymentUniqueLabelKey)\n\tdelete(t2Copy.Labels, apps.DefaultDeploymentUniqueLabelKey)\n\treturn apiequality.Semantic.DeepEqual(t1Copy, t2Copy)\n}","line":{"from":598,"to":610}} {"id":100003636,"name":"FindNewReplicaSet","signature":"func FindNewReplicaSet(deployment *apps.Deployment, rsList []*apps.ReplicaSet) *apps.ReplicaSet","file":"pkg/controller/deployment/util/deployment_util.go","code":"// FindNewReplicaSet returns the new RS this given deployment targets (the one with the same pod template).\nfunc FindNewReplicaSet(deployment *apps.Deployment, rsList []*apps.ReplicaSet) *apps.ReplicaSet {\n\tsort.Sort(controller.ReplicaSetsByCreationTimestamp(rsList))\n\tfor i := range rsList {\n\t\tif EqualIgnoreHash(\u0026rsList[i].Spec.Template, \u0026deployment.Spec.Template) {\n\t\t\t// In rare cases, such as after cluster upgrades, Deployment may end up with\n\t\t\t// having more than one new ReplicaSets that have the same template as its template,\n\t\t\t// see https://github.com/kubernetes/kubernetes/issues/40415\n\t\t\t// We deterministically choose the oldest new ReplicaSet.\n\t\t\treturn rsList[i]\n\t\t}\n\t}\n\t// new ReplicaSet does not exist.\n\treturn nil\n}","line":{"from":612,"to":626}} {"id":100003637,"name":"FindOldReplicaSets","signature":"func FindOldReplicaSets(deployment *apps.Deployment, rsList []*apps.ReplicaSet) ([]*apps.ReplicaSet, []*apps.ReplicaSet)","file":"pkg/controller/deployment/util/deployment_util.go","code":"// FindOldReplicaSets returns the old replica sets targeted by the given Deployment, with the given slice of RSes.\n// Note that the first set of old replica sets doesn't include the ones with no pods, and the second set of old replica sets include all old replica sets.\nfunc FindOldReplicaSets(deployment *apps.Deployment, rsList []*apps.ReplicaSet) ([]*apps.ReplicaSet, []*apps.ReplicaSet) {\n\tvar requiredRSs []*apps.ReplicaSet\n\tvar allRSs []*apps.ReplicaSet\n\tnewRS := FindNewReplicaSet(deployment, rsList)\n\tfor _, rs := range rsList {\n\t\t// Filter out new replica set\n\t\tif newRS != nil \u0026\u0026 rs.UID == newRS.UID {\n\t\t\tcontinue\n\t\t}\n\t\tallRSs = append(allRSs, rs)\n\t\tif *(rs.Spec.Replicas) != 0 {\n\t\t\trequiredRSs = append(requiredRSs, rs)\n\t\t}\n\t}\n\treturn requiredRSs, allRSs\n}","line":{"from":628,"to":645}} {"id":100003638,"name":"SetFromReplicaSetTemplate","signature":"func SetFromReplicaSetTemplate(deployment *apps.Deployment, template v1.PodTemplateSpec) *apps.Deployment","file":"pkg/controller/deployment/util/deployment_util.go","code":"// SetFromReplicaSetTemplate sets the desired PodTemplateSpec from a replica set template to the given deployment.\nfunc SetFromReplicaSetTemplate(deployment *apps.Deployment, template v1.PodTemplateSpec) *apps.Deployment {\n\tdeployment.Spec.Template.ObjectMeta = template.ObjectMeta\n\tdeployment.Spec.Template.Spec = template.Spec\n\tdeployment.Spec.Template.ObjectMeta.Labels = labelsutil.CloneAndRemoveLabel(\n\t\tdeployment.Spec.Template.ObjectMeta.Labels,\n\t\tapps.DefaultDeploymentUniqueLabelKey)\n\treturn deployment\n}","line":{"from":647,"to":655}} {"id":100003639,"name":"GetReplicaCountForReplicaSets","signature":"func GetReplicaCountForReplicaSets(replicaSets []*apps.ReplicaSet) int32","file":"pkg/controller/deployment/util/deployment_util.go","code":"// GetReplicaCountForReplicaSets returns the sum of Replicas of the given replica sets.\nfunc GetReplicaCountForReplicaSets(replicaSets []*apps.ReplicaSet) int32 {\n\ttotalReplicas := int32(0)\n\tfor _, rs := range replicaSets {\n\t\tif rs != nil {\n\t\t\ttotalReplicas += *(rs.Spec.Replicas)\n\t\t}\n\t}\n\treturn totalReplicas\n}","line":{"from":657,"to":666}} {"id":100003640,"name":"GetActualReplicaCountForReplicaSets","signature":"func GetActualReplicaCountForReplicaSets(replicaSets []*apps.ReplicaSet) int32","file":"pkg/controller/deployment/util/deployment_util.go","code":"// GetActualReplicaCountForReplicaSets returns the sum of actual replicas of the given replica sets.\nfunc GetActualReplicaCountForReplicaSets(replicaSets []*apps.ReplicaSet) int32 {\n\ttotalActualReplicas := int32(0)\n\tfor _, rs := range replicaSets {\n\t\tif rs != nil {\n\t\t\ttotalActualReplicas += rs.Status.Replicas\n\t\t}\n\t}\n\treturn totalActualReplicas\n}","line":{"from":668,"to":677}} {"id":100003641,"name":"GetReadyReplicaCountForReplicaSets","signature":"func GetReadyReplicaCountForReplicaSets(replicaSets []*apps.ReplicaSet) int32","file":"pkg/controller/deployment/util/deployment_util.go","code":"// GetReadyReplicaCountForReplicaSets returns the number of ready pods corresponding to the given replica sets.\nfunc GetReadyReplicaCountForReplicaSets(replicaSets []*apps.ReplicaSet) int32 {\n\ttotalReadyReplicas := int32(0)\n\tfor _, rs := range replicaSets {\n\t\tif rs != nil {\n\t\t\ttotalReadyReplicas += rs.Status.ReadyReplicas\n\t\t}\n\t}\n\treturn totalReadyReplicas\n}","line":{"from":679,"to":688}} {"id":100003642,"name":"GetAvailableReplicaCountForReplicaSets","signature":"func GetAvailableReplicaCountForReplicaSets(replicaSets []*apps.ReplicaSet) int32","file":"pkg/controller/deployment/util/deployment_util.go","code":"// GetAvailableReplicaCountForReplicaSets returns the number of available pods corresponding to the given replica sets.\nfunc GetAvailableReplicaCountForReplicaSets(replicaSets []*apps.ReplicaSet) int32 {\n\ttotalAvailableReplicas := int32(0)\n\tfor _, rs := range replicaSets {\n\t\tif rs != nil {\n\t\t\ttotalAvailableReplicas += rs.Status.AvailableReplicas\n\t\t}\n\t}\n\treturn totalAvailableReplicas\n}","line":{"from":690,"to":699}} {"id":100003643,"name":"IsRollingUpdate","signature":"func IsRollingUpdate(deployment *apps.Deployment) bool","file":"pkg/controller/deployment/util/deployment_util.go","code":"// IsRollingUpdate returns true if the strategy type is a rolling update.\nfunc IsRollingUpdate(deployment *apps.Deployment) bool {\n\treturn deployment.Spec.Strategy.Type == apps.RollingUpdateDeploymentStrategyType\n}","line":{"from":701,"to":704}} {"id":100003644,"name":"DeploymentComplete","signature":"func DeploymentComplete(deployment *apps.Deployment, newStatus *apps.DeploymentStatus) bool","file":"pkg/controller/deployment/util/deployment_util.go","code":"// DeploymentComplete considers a deployment to be complete once all of its desired replicas\n// are updated and available, and no old pods are running.\nfunc DeploymentComplete(deployment *apps.Deployment, newStatus *apps.DeploymentStatus) bool {\n\treturn newStatus.UpdatedReplicas == *(deployment.Spec.Replicas) \u0026\u0026\n\t\tnewStatus.Replicas == *(deployment.Spec.Replicas) \u0026\u0026\n\t\tnewStatus.AvailableReplicas == *(deployment.Spec.Replicas) \u0026\u0026\n\t\tnewStatus.ObservedGeneration \u003e= deployment.Generation\n}","line":{"from":706,"to":713}} {"id":100003645,"name":"DeploymentProgressing","signature":"func DeploymentProgressing(deployment *apps.Deployment, newStatus *apps.DeploymentStatus) bool","file":"pkg/controller/deployment/util/deployment_util.go","code":"// DeploymentProgressing reports progress for a deployment. Progress is estimated by comparing the\n// current with the new status of the deployment that the controller is observing. More specifically,\n// when new pods are scaled up or become ready or available, or old pods are scaled down, then we\n// consider the deployment is progressing.\nfunc DeploymentProgressing(deployment *apps.Deployment, newStatus *apps.DeploymentStatus) bool {\n\toldStatus := deployment.Status\n\n\t// Old replicas that need to be scaled down\n\toldStatusOldReplicas := oldStatus.Replicas - oldStatus.UpdatedReplicas\n\tnewStatusOldReplicas := newStatus.Replicas - newStatus.UpdatedReplicas\n\n\treturn (newStatus.UpdatedReplicas \u003e oldStatus.UpdatedReplicas) ||\n\t\t(newStatusOldReplicas \u003c oldStatusOldReplicas) ||\n\t\tnewStatus.ReadyReplicas \u003e deployment.Status.ReadyReplicas ||\n\t\tnewStatus.AvailableReplicas \u003e deployment.Status.AvailableReplicas\n}","line":{"from":715,"to":730}} {"id":100003646,"name":"DeploymentTimedOut","signature":"func DeploymentTimedOut(ctx context.Context, deployment *apps.Deployment, newStatus *apps.DeploymentStatus) bool","file":"pkg/controller/deployment/util/deployment_util.go","code":"// DeploymentTimedOut considers a deployment to have timed out once its condition that reports progress\n// is older than progressDeadlineSeconds or a Progressing condition with a TimedOutReason reason already\n// exists.\nfunc DeploymentTimedOut(ctx context.Context, deployment *apps.Deployment, newStatus *apps.DeploymentStatus) bool {\n\tif !HasProgressDeadline(deployment) {\n\t\treturn false\n\t}\n\n\t// Look for the Progressing condition. If it doesn't exist, we have no base to estimate progress.\n\t// If it's already set with a TimedOutReason reason, we have already timed out, no need to check\n\t// again.\n\tcondition := GetDeploymentCondition(*newStatus, apps.DeploymentProgressing)\n\tif condition == nil {\n\t\treturn false\n\t}\n\t// If the previous condition has been a successful rollout then we shouldn't try to\n\t// estimate any progress. Scenario:\n\t//\n\t// * progressDeadlineSeconds is smaller than the difference between now and the time\n\t// the last rollout finished in the past.\n\t// * the creation of a new ReplicaSet triggers a resync of the Deployment prior to the\n\t// cached copy of the Deployment getting updated with the status.condition that indicates\n\t// the creation of the new ReplicaSet.\n\t//\n\t// The Deployment will be resynced and eventually its Progressing condition will catch\n\t// up with the state of the world.\n\tif condition.Reason == NewRSAvailableReason {\n\t\treturn false\n\t}\n\tif condition.Reason == TimedOutReason {\n\t\treturn true\n\t}\n\tlogger := klog.FromContext(ctx)\n\t// Look at the difference in seconds between now and the last time we reported any\n\t// progress or tried to create a replica set, or resumed a paused deployment and\n\t// compare against progressDeadlineSeconds.\n\tfrom := condition.LastUpdateTime\n\tnow := nowFn()\n\tdelta := time.Duration(*deployment.Spec.ProgressDeadlineSeconds) * time.Second\n\ttimedOut := from.Add(delta).Before(now)\n\n\tlogger.V(4).Info(\"Deployment timed out from last progress check\", \"deployment\", klog.KObj(deployment), \"timeout\", timedOut, \"from\", from, \"now\", now)\n\treturn timedOut\n}","line":{"from":735,"to":778}} {"id":100003647,"name":"NewRSNewReplicas","signature":"func NewRSNewReplicas(deployment *apps.Deployment, allRSs []*apps.ReplicaSet, newRS *apps.ReplicaSet) (int32, error)","file":"pkg/controller/deployment/util/deployment_util.go","code":"// NewRSNewReplicas calculates the number of replicas a deployment's new RS should have.\n// When one of the followings is true, we're rolling out the deployment; otherwise, we're scaling it.\n// 1) The new RS is saturated: newRS's replicas == deployment's replicas\n// 2) Max number of pods allowed is reached: deployment's replicas + maxSurge == all RSs' replicas\nfunc NewRSNewReplicas(deployment *apps.Deployment, allRSs []*apps.ReplicaSet, newRS *apps.ReplicaSet) (int32, error) {\n\tswitch deployment.Spec.Strategy.Type {\n\tcase apps.RollingUpdateDeploymentStrategyType:\n\t\t// Check if we can scale up.\n\t\tmaxSurge, err := intstrutil.GetScaledValueFromIntOrPercent(deployment.Spec.Strategy.RollingUpdate.MaxSurge, int(*(deployment.Spec.Replicas)), true)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\t// Find the total number of pods\n\t\tcurrentPodCount := GetReplicaCountForReplicaSets(allRSs)\n\t\tmaxTotalPods := *(deployment.Spec.Replicas) + int32(maxSurge)\n\t\tif currentPodCount \u003e= maxTotalPods {\n\t\t\t// Cannot scale up.\n\t\t\treturn *(newRS.Spec.Replicas), nil\n\t\t}\n\t\t// Scale up.\n\t\tscaleUpCount := maxTotalPods - currentPodCount\n\t\t// Do not exceed the number of desired replicas.\n\t\tscaleUpCount = int32(integer.IntMin(int(scaleUpCount), int(*(deployment.Spec.Replicas)-*(newRS.Spec.Replicas))))\n\t\treturn *(newRS.Spec.Replicas) + scaleUpCount, nil\n\tcase apps.RecreateDeploymentStrategyType:\n\t\treturn *(deployment.Spec.Replicas), nil\n\tdefault:\n\t\treturn 0, fmt.Errorf(\"deployment type %v isn't supported\", deployment.Spec.Strategy.Type)\n\t}\n}","line":{"from":780,"to":809}} {"id":100003648,"name":"IsSaturated","signature":"func IsSaturated(deployment *apps.Deployment, rs *apps.ReplicaSet) bool","file":"pkg/controller/deployment/util/deployment_util.go","code":"// IsSaturated checks if the new replica set is saturated by comparing its size with its deployment size.\n// Both the deployment and the replica set have to believe this replica set can own all of the desired\n// replicas in the deployment and the annotation helps in achieving that. All pods of the ReplicaSet\n// need to be available.\nfunc IsSaturated(deployment *apps.Deployment, rs *apps.ReplicaSet) bool {\n\tif rs == nil {\n\t\treturn false\n\t}\n\tdesiredString := rs.Annotations[DesiredReplicasAnnotation]\n\tdesired, err := strconv.Atoi(desiredString)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn *(rs.Spec.Replicas) == *(deployment.Spec.Replicas) \u0026\u0026\n\t\tint32(desired) == *(deployment.Spec.Replicas) \u0026\u0026\n\t\trs.Status.AvailableReplicas == *(deployment.Spec.Replicas)\n}","line":{"from":811,"to":827}} {"id":100003649,"name":"WaitForObservedDeployment","signature":"func WaitForObservedDeployment(getDeploymentFunc func() (*apps.Deployment, error), desiredGeneration int64, interval, timeout time.Duration) error","file":"pkg/controller/deployment/util/deployment_util.go","code":"// WaitForObservedDeployment polls for deployment to be updated so that deployment.Status.ObservedGeneration \u003e= desiredGeneration.\n// Returns error if polling timesout.\nfunc WaitForObservedDeployment(getDeploymentFunc func() (*apps.Deployment, error), desiredGeneration int64, interval, timeout time.Duration) error {\n\t// TODO: This should take clientset.Interface when all code is updated to use clientset. Keeping it this way allows the function to be used by callers who have client.Interface.\n\treturn wait.PollImmediate(interval, timeout, func() (bool, error) {\n\t\tdeployment, err := getDeploymentFunc()\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\treturn deployment.Status.ObservedGeneration \u003e= desiredGeneration, nil\n\t})\n}","line":{"from":829,"to":840}} {"id":100003650,"name":"ResolveFenceposts","signature":"func ResolveFenceposts(maxSurge, maxUnavailable *intstrutil.IntOrString, desired int32) (int32, int32, error)","file":"pkg/controller/deployment/util/deployment_util.go","code":"// ResolveFenceposts resolves both maxSurge and maxUnavailable. This needs to happen in one\n// step. For example:\n//\n// 2 desired, max unavailable 1%, surge 0% - should scale old(-1), then new(+1), then old(-1), then new(+1)\n// 1 desired, max unavailable 1%, surge 0% - should scale old(-1), then new(+1)\n// 2 desired, max unavailable 25%, surge 1% - should scale new(+1), then old(-1), then new(+1), then old(-1)\n// 1 desired, max unavailable 25%, surge 1% - should scale new(+1), then old(-1)\n// 2 desired, max unavailable 0%, surge 1% - should scale new(+1), then old(-1), then new(+1), then old(-1)\n// 1 desired, max unavailable 0%, surge 1% - should scale new(+1), then old(-1)\nfunc ResolveFenceposts(maxSurge, maxUnavailable *intstrutil.IntOrString, desired int32) (int32, int32, error) {\n\tsurge, err := intstrutil.GetScaledValueFromIntOrPercent(intstrutil.ValueOrDefault(maxSurge, intstrutil.FromInt(0)), int(desired), true)\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\tunavailable, err := intstrutil.GetScaledValueFromIntOrPercent(intstrutil.ValueOrDefault(maxUnavailable, intstrutil.FromInt(0)), int(desired), false)\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\n\tif surge == 0 \u0026\u0026 unavailable == 0 {\n\t\t// Validation should never allow the user to explicitly use zero values for both maxSurge\n\t\t// maxUnavailable. Due to rounding down maxUnavailable though, it may resolve to zero.\n\t\t// If both fenceposts resolve to zero, then we should set maxUnavailable to 1 on the\n\t\t// theory that surge might not work due to quota.\n\t\tunavailable = 1\n\t}\n\n\treturn int32(surge), int32(unavailable), nil\n}","line":{"from":842,"to":870}} {"id":100003651,"name":"HasProgressDeadline","signature":"func HasProgressDeadline(d *apps.Deployment) bool","file":"pkg/controller/deployment/util/deployment_util.go","code":"// HasProgressDeadline checks if the Deployment d is expected to surface the reason\n// \"ProgressDeadlineExceeded\" when the Deployment progress takes longer than expected time.\nfunc HasProgressDeadline(d *apps.Deployment) bool {\n\treturn d.Spec.ProgressDeadlineSeconds != nil \u0026\u0026 *d.Spec.ProgressDeadlineSeconds != math.MaxInt32\n}","line":{"from":872,"to":876}} {"id":100003652,"name":"HasRevisionHistoryLimit","signature":"func HasRevisionHistoryLimit(d *apps.Deployment) bool","file":"pkg/controller/deployment/util/deployment_util.go","code":"// HasRevisionHistoryLimit checks if the Deployment d is expected to keep a specified number of\n// old replicaSets. These replicaSets are mainly kept with the purpose of rollback.\n// The RevisionHistoryLimit can start from 0 (no retained replicasSet). When set to math.MaxInt32,\n// the Deployment will keep all revisions.\nfunc HasRevisionHistoryLimit(d *apps.Deployment) bool {\n\treturn d.Spec.RevisionHistoryLimit != nil \u0026\u0026 *d.Spec.RevisionHistoryLimit != math.MaxInt32\n}","line":{"from":878,"to":884}} {"id":100003653,"name":"GetDeploymentsForReplicaSet","signature":"func GetDeploymentsForReplicaSet(deploymentLister appslisters.DeploymentLister, rs *apps.ReplicaSet) ([]*apps.Deployment, error)","file":"pkg/controller/deployment/util/deployment_util.go","code":"// GetDeploymentsForReplicaSet returns a list of Deployments that potentially\n// match a ReplicaSet. Only the one specified in the ReplicaSet's ControllerRef\n// will actually manage it.\n// Returns an error only if no matching Deployments are found.\nfunc GetDeploymentsForReplicaSet(deploymentLister appslisters.DeploymentLister, rs *apps.ReplicaSet) ([]*apps.Deployment, error) {\n\tif len(rs.Labels) == 0 {\n\t\treturn nil, fmt.Errorf(\"no deployments found for ReplicaSet %v because it has no labels\", rs.Name)\n\t}\n\n\t// TODO: MODIFY THIS METHOD so that it checks for the podTemplateSpecHash label\n\tdList, err := deploymentLister.Deployments(rs.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar deployments []*apps.Deployment\n\tfor _, d := range dList {\n\t\tselector, err := metav1.LabelSelectorAsSelector(d.Spec.Selector)\n\t\tif err != nil {\n\t\t\t// This object has an invalid selector, it does not match the replicaset\n\t\t\tcontinue\n\t\t}\n\t\t// If a deployment with a nil or empty selector creeps in, it should match nothing, not everything.\n\t\tif selector.Empty() || !selector.Matches(labels.Set(rs.Labels)) {\n\t\t\tcontinue\n\t\t}\n\t\tdeployments = append(deployments, d)\n\t}\n\n\tif len(deployments) == 0 {\n\t\treturn nil, fmt.Errorf(\"could not find deployments set for ReplicaSet %s in namespace %s with labels: %v\", rs.Name, rs.Namespace, rs.Labels)\n\t}\n\n\treturn deployments, nil\n}","line":{"from":886,"to":920}} {"id":100003654,"name":"Len","signature":"func (o ReplicaSetsByRevision) Len() int { return len(o) }","file":"pkg/controller/deployment/util/deployment_util.go","code":"func (o ReplicaSetsByRevision) Len() int { return len(o) }","line":{"from":926,"to":926}} {"id":100003655,"name":"Swap","signature":"func (o ReplicaSetsByRevision) Swap(i, j int) { o[i], o[j] = o[j], o[i] }","file":"pkg/controller/deployment/util/deployment_util.go","code":"func (o ReplicaSetsByRevision) Swap(i, j int) { o[i], o[j] = o[j], o[i] }","line":{"from":927,"to":927}} {"id":100003656,"name":"Less","signature":"func (o ReplicaSetsByRevision) Less(i, j int) bool","file":"pkg/controller/deployment/util/deployment_util.go","code":"func (o ReplicaSetsByRevision) Less(i, j int) bool {\n\trevision1, err1 := Revision(o[i])\n\trevision2, err2 := Revision(o[j])\n\tif err1 != nil || err2 != nil || revision1 == revision2 {\n\t\treturn controller.ReplicaSetsByCreationTimestamp(o).Less(i, j)\n\t}\n\treturn revision1 \u003c revision2\n}","line":{"from":928,"to":935}} {"id":100003657,"name":"NewDisruptionController","signature":"func NewDisruptionController(","file":"pkg/controller/disruption/disruption.go","code":"func NewDisruptionController(\n\tpodInformer coreinformers.PodInformer,\n\tpdbInformer policyinformers.PodDisruptionBudgetInformer,\n\trcInformer coreinformers.ReplicationControllerInformer,\n\trsInformer appsv1informers.ReplicaSetInformer,\n\tdInformer appsv1informers.DeploymentInformer,\n\tssInformer appsv1informers.StatefulSetInformer,\n\tkubeClient clientset.Interface,\n\trestMapper apimeta.RESTMapper,\n\tscaleNamespacer scaleclient.ScalesGetter,\n\tdiscoveryClient discovery.DiscoveryInterface,\n) *DisruptionController {\n\treturn NewDisruptionControllerInternal(\n\t\tpodInformer,\n\t\tpdbInformer,\n\t\trcInformer,\n\t\trsInformer,\n\t\tdInformer,\n\t\tssInformer,\n\t\tkubeClient,\n\t\trestMapper,\n\t\tscaleNamespacer,\n\t\tdiscoveryClient,\n\t\tclock.RealClock{},\n\t\tstalePodDisruptionTimeout)\n}","line":{"from":136,"to":161}} {"id":100003658,"name":"NewDisruptionControllerInternal","signature":"func NewDisruptionControllerInternal(","file":"pkg/controller/disruption/disruption.go","code":"// NewDisruptionControllerInternal allows to set a clock and\n// stalePodDisruptionTimeout\n// It is only supposed to be used by tests.\nfunc NewDisruptionControllerInternal(\n\tpodInformer coreinformers.PodInformer,\n\tpdbInformer policyinformers.PodDisruptionBudgetInformer,\n\trcInformer coreinformers.ReplicationControllerInformer,\n\trsInformer appsv1informers.ReplicaSetInformer,\n\tdInformer appsv1informers.DeploymentInformer,\n\tssInformer appsv1informers.StatefulSetInformer,\n\tkubeClient clientset.Interface,\n\trestMapper apimeta.RESTMapper,\n\tscaleNamespacer scaleclient.ScalesGetter,\n\tdiscoveryClient discovery.DiscoveryInterface,\n\tclock clock.WithTicker,\n\tstalePodDisruptionTimeout time.Duration,\n) *DisruptionController {\n\tdc := \u0026DisruptionController{\n\t\tkubeClient: kubeClient,\n\t\tqueue: workqueue.NewRateLimitingQueueWithDelayingInterface(workqueue.NewDelayingQueueWithCustomClock(clock, \"disruption\"), workqueue.DefaultControllerRateLimiter()),\n\t\trecheckQueue: workqueue.NewDelayingQueueWithCustomClock(clock, \"disruption_recheck\"),\n\t\tstalePodDisruptionQueue: workqueue.NewRateLimitingQueueWithDelayingInterface(workqueue.NewDelayingQueueWithCustomClock(clock, \"stale_pod_disruption\"), workqueue.DefaultControllerRateLimiter()),\n\t\tbroadcaster: record.NewBroadcaster(),\n\t\tstalePodDisruptionTimeout: stalePodDisruptionTimeout,\n\t}\n\tdc.recorder = dc.broadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"controllermanager\"})\n\n\tdc.getUpdater = func() updater { return dc.writePdbStatus }\n\n\tpodInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: dc.addPod,\n\t\tUpdateFunc: dc.updatePod,\n\t\tDeleteFunc: dc.deletePod,\n\t})\n\tdc.podLister = podInformer.Lister()\n\tdc.podListerSynced = podInformer.Informer().HasSynced\n\n\tpdbInformer.Informer().AddEventHandler(\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: dc.addDb,\n\t\t\tUpdateFunc: dc.updateDb,\n\t\t\tDeleteFunc: dc.removeDb,\n\t\t},\n\t)\n\tdc.pdbLister = pdbInformer.Lister()\n\tdc.pdbListerSynced = pdbInformer.Informer().HasSynced\n\n\tdc.rcLister = rcInformer.Lister()\n\tdc.rcListerSynced = rcInformer.Informer().HasSynced\n\n\tdc.rsLister = rsInformer.Lister()\n\tdc.rsListerSynced = rsInformer.Informer().HasSynced\n\n\tdc.dLister = dInformer.Lister()\n\tdc.dListerSynced = dInformer.Informer().HasSynced\n\n\tdc.ssLister = ssInformer.Lister()\n\tdc.ssListerSynced = ssInformer.Informer().HasSynced\n\n\tdc.mapper = restMapper\n\tdc.scaleNamespacer = scaleNamespacer\n\tdc.discoveryClient = discoveryClient\n\n\tdc.clock = clock\n\n\treturn dc\n}","line":{"from":163,"to":229}} {"id":100003659,"name":"finders","signature":"func (dc *DisruptionController) finders() []podControllerFinder","file":"pkg/controller/disruption/disruption.go","code":"// The workload resources do implement the scale subresource, so it would\n// be possible to only check the scale subresource here. But since there is no\n// way to take advantage of listers with scale subresources, we use the workload\n// resources directly and only fall back to the scale subresource when needed.\nfunc (dc *DisruptionController) finders() []podControllerFinder {\n\treturn []podControllerFinder{dc.getPodReplicationController, dc.getPodDeployment, dc.getPodReplicaSet,\n\t\tdc.getPodStatefulSet, dc.getScaleController}\n}","line":{"from":231,"to":238}} {"id":100003660,"name":"getPodReplicaSet","signature":"func (dc *DisruptionController) getPodReplicaSet(ctx context.Context, controllerRef *metav1.OwnerReference, namespace string) (*controllerAndScale, error)","file":"pkg/controller/disruption/disruption.go","code":"// getPodReplicaSet finds a replicaset which has no matching deployments.\nfunc (dc *DisruptionController) getPodReplicaSet(ctx context.Context, controllerRef *metav1.OwnerReference, namespace string) (*controllerAndScale, error) {\n\tok, err := verifyGroupKind(controllerRef, controllerKindRS.Kind, []string{\"apps\", \"extensions\"})\n\tif !ok || err != nil {\n\t\treturn nil, err\n\t}\n\trs, err := dc.rsLister.ReplicaSets(namespace).Get(controllerRef.Name)\n\tif err != nil {\n\t\t// The only possible error is NotFound, which is ok here.\n\t\treturn nil, nil\n\t}\n\tif rs.UID != controllerRef.UID {\n\t\treturn nil, nil\n\t}\n\tcontrollerRef = metav1.GetControllerOf(rs)\n\tif controllerRef != nil \u0026\u0026 controllerRef.Kind == controllerKindDep.Kind {\n\t\t// Skip RS if it's controlled by a Deployment.\n\t\treturn nil, nil\n\t}\n\treturn \u0026controllerAndScale{rs.UID, *(rs.Spec.Replicas)}, nil\n}","line":{"from":247,"to":267}} {"id":100003661,"name":"getPodStatefulSet","signature":"func (dc *DisruptionController) getPodStatefulSet(ctx context.Context, controllerRef *metav1.OwnerReference, namespace string) (*controllerAndScale, error)","file":"pkg/controller/disruption/disruption.go","code":"// getPodStatefulSet returns the statefulset referenced by the provided controllerRef.\nfunc (dc *DisruptionController) getPodStatefulSet(ctx context.Context, controllerRef *metav1.OwnerReference, namespace string) (*controllerAndScale, error) {\n\tok, err := verifyGroupKind(controllerRef, controllerKindSS.Kind, []string{\"apps\"})\n\tif !ok || err != nil {\n\t\treturn nil, err\n\t}\n\tss, err := dc.ssLister.StatefulSets(namespace).Get(controllerRef.Name)\n\tif err != nil {\n\t\t// The only possible error is NotFound, which is ok here.\n\t\treturn nil, nil\n\t}\n\tif ss.UID != controllerRef.UID {\n\t\treturn nil, nil\n\t}\n\n\treturn \u0026controllerAndScale{ss.UID, *(ss.Spec.Replicas)}, nil\n}","line":{"from":269,"to":285}} {"id":100003662,"name":"getPodDeployment","signature":"func (dc *DisruptionController) getPodDeployment(ctx context.Context, controllerRef *metav1.OwnerReference, namespace string) (*controllerAndScale, error)","file":"pkg/controller/disruption/disruption.go","code":"// getPodDeployments finds deployments for any replicasets which are being managed by deployments.\nfunc (dc *DisruptionController) getPodDeployment(ctx context.Context, controllerRef *metav1.OwnerReference, namespace string) (*controllerAndScale, error) {\n\tok, err := verifyGroupKind(controllerRef, controllerKindRS.Kind, []string{\"apps\", \"extensions\"})\n\tif !ok || err != nil {\n\t\treturn nil, err\n\t}\n\trs, err := dc.rsLister.ReplicaSets(namespace).Get(controllerRef.Name)\n\tif err != nil {\n\t\t// The only possible error is NotFound, which is ok here.\n\t\treturn nil, nil\n\t}\n\tif rs.UID != controllerRef.UID {\n\t\treturn nil, nil\n\t}\n\tcontrollerRef = metav1.GetControllerOf(rs)\n\tif controllerRef == nil {\n\t\treturn nil, nil\n\t}\n\n\tok, err = verifyGroupKind(controllerRef, controllerKindDep.Kind, []string{\"apps\", \"extensions\"})\n\tif !ok || err != nil {\n\t\treturn nil, err\n\t}\n\tdeployment, err := dc.dLister.Deployments(rs.Namespace).Get(controllerRef.Name)\n\tif err != nil {\n\t\t// The only possible error is NotFound, which is ok here.\n\t\treturn nil, nil\n\t}\n\tif deployment.UID != controllerRef.UID {\n\t\treturn nil, nil\n\t}\n\treturn \u0026controllerAndScale{deployment.UID, *(deployment.Spec.Replicas)}, nil\n}","line":{"from":287,"to":319}} {"id":100003663,"name":"getPodReplicationController","signature":"func (dc *DisruptionController) getPodReplicationController(ctx context.Context, controllerRef *metav1.OwnerReference, namespace string) (*controllerAndScale, error)","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) getPodReplicationController(ctx context.Context, controllerRef *metav1.OwnerReference, namespace string) (*controllerAndScale, error) {\n\tok, err := verifyGroupKind(controllerRef, controllerKindRC.Kind, []string{\"\"})\n\tif !ok || err != nil {\n\t\treturn nil, err\n\t}\n\trc, err := dc.rcLister.ReplicationControllers(namespace).Get(controllerRef.Name)\n\tif err != nil {\n\t\t// The only possible error is NotFound, which is ok here.\n\t\treturn nil, nil\n\t}\n\tif rc.UID != controllerRef.UID {\n\t\treturn nil, nil\n\t}\n\treturn \u0026controllerAndScale{rc.UID, *(rc.Spec.Replicas)}, nil\n}","line":{"from":321,"to":335}} {"id":100003664,"name":"getScaleController","signature":"func (dc *DisruptionController) getScaleController(ctx context.Context, controllerRef *metav1.OwnerReference, namespace string) (*controllerAndScale, error)","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) getScaleController(ctx context.Context, controllerRef *metav1.OwnerReference, namespace string) (*controllerAndScale, error) {\n\tgv, err := schema.ParseGroupVersion(controllerRef.APIVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgk := schema.GroupKind{\n\t\tGroup: gv.Group,\n\t\tKind: controllerRef.Kind,\n\t}\n\n\tmapping, err := dc.mapper.RESTMapping(gk, gv.Version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgr := mapping.Resource.GroupResource()\n\tscale, err := dc.scaleNamespacer.Scales(namespace).Get(ctx, gr, controllerRef.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t// The IsNotFound error can mean either that the resource does not exist,\n\t\t\t// or it exist but doesn't implement the scale subresource. We check which\n\t\t\t// situation we are facing so we can give an appropriate error message.\n\t\t\tisScale, err := dc.implementsScale(mapping.Resource)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif !isScale {\n\t\t\t\treturn nil, fmt.Errorf(\"%s does not implement the scale subresource\", gr.String())\n\t\t\t}\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\tif scale.UID != controllerRef.UID {\n\t\treturn nil, nil\n\t}\n\treturn \u0026controllerAndScale{scale.UID, scale.Spec.Replicas}, nil\n}","line":{"from":337,"to":374}} {"id":100003665,"name":"implementsScale","signature":"func (dc *DisruptionController) implementsScale(gvr schema.GroupVersionResource) (bool, error)","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) implementsScale(gvr schema.GroupVersionResource) (bool, error) {\n\tresourceList, err := dc.discoveryClient.ServerResourcesForGroupVersion(gvr.GroupVersion().String())\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tscaleSubresourceName := fmt.Sprintf(\"%s/scale\", gvr.Resource)\n\tfor _, resource := range resourceList.APIResources {\n\t\tif resource.Name != scaleSubresourceName {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, scaleGv := range scaleclient.NewScaleConverter().ScaleVersions() {\n\t\t\tif resource.Group == scaleGv.Group \u0026\u0026\n\t\t\t\tresource.Version == scaleGv.Version \u0026\u0026\n\t\t\t\tresource.Kind == \"Scale\" {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn false, nil\n}","line":{"from":376,"to":397}} {"id":100003666,"name":"verifyGroupKind","signature":"func verifyGroupKind(controllerRef *metav1.OwnerReference, expectedKind string, expectedGroups []string) (bool, error)","file":"pkg/controller/disruption/disruption.go","code":"func verifyGroupKind(controllerRef *metav1.OwnerReference, expectedKind string, expectedGroups []string) (bool, error) {\n\tgv, err := schema.ParseGroupVersion(controllerRef.APIVersion)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif controllerRef.Kind != expectedKind {\n\t\treturn false, nil\n\t}\n\n\tfor _, group := range expectedGroups {\n\t\tif group == gv.Group {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, nil\n}","line":{"from":399,"to":416}} {"id":100003667,"name":"Run","signature":"func (dc *DisruptionController) Run(ctx context.Context)","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) Run(ctx context.Context) {\n\tdefer utilruntime.HandleCrash()\n\n\t// Start events processing pipeline.\n\tif dc.kubeClient != nil {\n\t\tklog.Infof(\"Sending events to api server.\")\n\t\tdc.broadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: dc.kubeClient.CoreV1().Events(\"\")})\n\t} else {\n\t\tklog.Infof(\"No api server defined - no events will be sent to API server.\")\n\t}\n\tdefer dc.broadcaster.Shutdown()\n\n\tdefer dc.queue.ShutDown()\n\tdefer dc.recheckQueue.ShutDown()\n\tdefer dc.stalePodDisruptionQueue.ShutDown()\n\n\tklog.Infof(\"Starting disruption controller\")\n\tdefer klog.Infof(\"Shutting down disruption controller\")\n\n\tif !cache.WaitForNamedCacheSync(\"disruption\", ctx.Done(), dc.podListerSynced, dc.pdbListerSynced, dc.rcListerSynced, dc.rsListerSynced, dc.dListerSynced, dc.ssListerSynced) {\n\t\treturn\n\t}\n\n\tgo wait.UntilWithContext(ctx, dc.worker, time.Second)\n\tgo wait.Until(dc.recheckWorker, time.Second, ctx.Done())\n\tgo wait.UntilWithContext(ctx, dc.stalePodDisruptionWorker, time.Second)\n\n\t\u003c-ctx.Done()\n}","line":{"from":418,"to":446}} {"id":100003668,"name":"addDb","signature":"func (dc *DisruptionController) addDb(obj interface{})","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) addDb(obj interface{}) {\n\tpdb := obj.(*policy.PodDisruptionBudget)\n\tklog.V(4).Infof(\"add DB %q\", pdb.Name)\n\tdc.enqueuePdb(pdb)\n}","line":{"from":448,"to":452}} {"id":100003669,"name":"updateDb","signature":"func (dc *DisruptionController) updateDb(old, cur interface{})","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) updateDb(old, cur interface{}) {\n\t// TODO(mml) ignore updates where 'old' is equivalent to 'cur'.\n\tpdb := cur.(*policy.PodDisruptionBudget)\n\tklog.V(4).Infof(\"update DB %q\", pdb.Name)\n\tdc.enqueuePdb(pdb)\n}","line":{"from":454,"to":459}} {"id":100003670,"name":"removeDb","signature":"func (dc *DisruptionController) removeDb(obj interface{})","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) removeDb(obj interface{}) {\n\tpdb, ok := obj.(*policy.PodDisruptionBudget)\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"Couldn't get object from tombstone %+v\", obj)\n\t\t\treturn\n\t\t}\n\t\tpdb, ok = tombstone.Obj.(*policy.PodDisruptionBudget)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"Tombstone contained object that is not a pdb %+v\", obj)\n\t\t\treturn\n\t\t}\n\t}\n\tklog.V(4).Infof(\"remove DB %q\", pdb.Name)\n\tdc.enqueuePdb(pdb)\n}","line":{"from":461,"to":477}} {"id":100003671,"name":"addPod","signature":"func (dc *DisruptionController) addPod(obj interface{})","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) addPod(obj interface{}) {\n\tpod := obj.(*v1.Pod)\n\tklog.V(4).Infof(\"addPod called on pod %q\", pod.Name)\n\tpdb := dc.getPdbForPod(pod)\n\tif pdb == nil {\n\t\tklog.V(4).Infof(\"No matching pdb for pod %q\", pod.Name)\n\t} else {\n\t\tklog.V(4).Infof(\"addPod %q -\u003e PDB %q\", pod.Name, pdb.Name)\n\t\tdc.enqueuePdb(pdb)\n\t}\n\tif has, cleanAfter := dc.nonTerminatingPodHasStaleDisruptionCondition(pod); has {\n\t\tdc.enqueueStalePodDisruptionCleanup(pod, cleanAfter)\n\t}\n}","line":{"from":479,"to":492}} {"id":100003672,"name":"updatePod","signature":"func (dc *DisruptionController) updatePod(_, cur interface{})","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) updatePod(_, cur interface{}) {\n\tpod := cur.(*v1.Pod)\n\tklog.V(4).Infof(\"updatePod called on pod %q\", pod.Name)\n\tpdb := dc.getPdbForPod(pod)\n\tif pdb == nil {\n\t\tklog.V(4).Infof(\"No matching pdb for pod %q\", pod.Name)\n\t} else {\n\t\tklog.V(4).Infof(\"updatePod %q -\u003e PDB %q\", pod.Name, pdb.Name)\n\t\tdc.enqueuePdb(pdb)\n\t}\n\tif has, cleanAfter := dc.nonTerminatingPodHasStaleDisruptionCondition(pod); has {\n\t\tdc.enqueueStalePodDisruptionCleanup(pod, cleanAfter)\n\t}\n}","line":{"from":494,"to":507}} {"id":100003673,"name":"deletePod","signature":"func (dc *DisruptionController) deletePod(obj interface{})","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) deletePod(obj interface{}) {\n\tpod, ok := obj.(*v1.Pod)\n\t// When a delete is dropped, the relist will notice a pod in the store not\n\t// in the list, leading to the insertion of a tombstone object which contains\n\t// the deleted key/value. Note that this value might be stale. If the pod\n\t// changed labels the new ReplicaSet will not be woken up till the periodic\n\t// resync.\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"Couldn't get object from tombstone %+v\", obj)\n\t\t\treturn\n\t\t}\n\t\tpod, ok = tombstone.Obj.(*v1.Pod)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"Tombstone contained object that is not a pod %+v\", obj)\n\t\t\treturn\n\t\t}\n\t}\n\tklog.V(4).Infof(\"deletePod called on pod %q\", pod.Name)\n\tpdb := dc.getPdbForPod(pod)\n\tif pdb == nil {\n\t\tklog.V(4).Infof(\"No matching pdb for pod %q\", pod.Name)\n\t\treturn\n\t}\n\tklog.V(4).Infof(\"deletePod %q -\u003e PDB %q\", pod.Name, pdb.Name)\n\tdc.enqueuePdb(pdb)\n}","line":{"from":509,"to":536}} {"id":100003674,"name":"enqueuePdb","signature":"func (dc *DisruptionController) enqueuePdb(pdb *policy.PodDisruptionBudget)","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) enqueuePdb(pdb *policy.PodDisruptionBudget) {\n\tkey, err := controller.KeyFunc(pdb)\n\tif err != nil {\n\t\tklog.Errorf(\"Couldn't get key for PodDisruptionBudget object %+v: %v\", pdb, err)\n\t\treturn\n\t}\n\tdc.queue.Add(key)\n}","line":{"from":538,"to":545}} {"id":100003675,"name":"enqueuePdbForRecheck","signature":"func (dc *DisruptionController) enqueuePdbForRecheck(pdb *policy.PodDisruptionBudget, delay time.Duration)","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) enqueuePdbForRecheck(pdb *policy.PodDisruptionBudget, delay time.Duration) {\n\tkey, err := controller.KeyFunc(pdb)\n\tif err != nil {\n\t\tklog.Errorf(\"Couldn't get key for PodDisruptionBudget object %+v: %v\", pdb, err)\n\t\treturn\n\t}\n\tdc.recheckQueue.AddAfter(key, delay)\n}","line":{"from":547,"to":554}} {"id":100003676,"name":"enqueueStalePodDisruptionCleanup","signature":"func (dc *DisruptionController) enqueueStalePodDisruptionCleanup(pod *v1.Pod, d time.Duration)","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) enqueueStalePodDisruptionCleanup(pod *v1.Pod, d time.Duration) {\n\tkey, err := controller.KeyFunc(pod)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Couldn't get key for Pod object\", \"pod\", klog.KObj(pod))\n\t\treturn\n\t}\n\tdc.stalePodDisruptionQueue.AddAfter(key, d)\n\tklog.V(4).InfoS(\"Enqueued pod to cleanup stale DisruptionTarget condition\", \"pod\", klog.KObj(pod))\n}","line":{"from":556,"to":564}} {"id":100003677,"name":"getPdbForPod","signature":"func (dc *DisruptionController) getPdbForPod(pod *v1.Pod) *policy.PodDisruptionBudget","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) getPdbForPod(pod *v1.Pod) *policy.PodDisruptionBudget {\n\t// GetPodPodDisruptionBudgets returns an error only if no\n\t// PodDisruptionBudgets are found. We don't return that as an error to the\n\t// caller.\n\tpdbs, err := dc.pdbLister.GetPodPodDisruptionBudgets(pod)\n\tif err != nil {\n\t\tklog.V(4).Infof(\"No PodDisruptionBudgets found for pod %v, PodDisruptionBudget controller will avoid syncing.\", pod.Name)\n\t\treturn nil\n\t}\n\n\tif len(pdbs) \u003e 1 {\n\t\tmsg := fmt.Sprintf(\"Pod %q/%q matches multiple PodDisruptionBudgets. Chose %q arbitrarily.\", pod.Namespace, pod.Name, pdbs[0].Name)\n\t\tklog.Warning(msg)\n\t\tdc.recorder.Event(pod, v1.EventTypeWarning, \"MultiplePodDisruptionBudgets\", msg)\n\t}\n\treturn pdbs[0]\n}","line":{"from":566,"to":582}} {"id":100003678,"name":"getPodsForPdb","signature":"func (dc *DisruptionController) getPodsForPdb(pdb *policy.PodDisruptionBudget) ([]*v1.Pod, error)","file":"pkg/controller/disruption/disruption.go","code":"// This function returns pods using the PodDisruptionBudget object.\n// IMPORTANT NOTE : the returned pods should NOT be modified.\nfunc (dc *DisruptionController) getPodsForPdb(pdb *policy.PodDisruptionBudget) ([]*v1.Pod, error) {\n\tsel, err := metav1.LabelSelectorAsSelector(pdb.Spec.Selector)\n\tif err != nil {\n\t\treturn []*v1.Pod{}, err\n\t}\n\tpods, err := dc.podLister.Pods(pdb.Namespace).List(sel)\n\tif err != nil {\n\t\treturn []*v1.Pod{}, err\n\t}\n\treturn pods, nil\n}","line":{"from":584,"to":596}} {"id":100003679,"name":"worker","signature":"func (dc *DisruptionController) worker(ctx context.Context)","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) worker(ctx context.Context) {\n\tfor dc.processNextWorkItem(ctx) {\n\t}\n}","line":{"from":598,"to":601}} {"id":100003680,"name":"processNextWorkItem","signature":"func (dc *DisruptionController) processNextWorkItem(ctx context.Context) bool","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) processNextWorkItem(ctx context.Context) bool {\n\tdKey, quit := dc.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer dc.queue.Done(dKey)\n\n\terr := dc.sync(ctx, dKey.(string))\n\tif err == nil {\n\t\tdc.queue.Forget(dKey)\n\t\treturn true\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"Error syncing PodDisruptionBudget %v, requeuing: %v\", dKey.(string), err))\n\tdc.queue.AddRateLimited(dKey)\n\n\treturn true\n}","line":{"from":603,"to":620}} {"id":100003681,"name":"recheckWorker","signature":"func (dc *DisruptionController) recheckWorker()","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) recheckWorker() {\n\tfor dc.processNextRecheckWorkItem() {\n\t}\n}","line":{"from":622,"to":625}} {"id":100003682,"name":"processNextRecheckWorkItem","signature":"func (dc *DisruptionController) processNextRecheckWorkItem() bool","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) processNextRecheckWorkItem() bool {\n\tdKey, quit := dc.recheckQueue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer dc.recheckQueue.Done(dKey)\n\tdc.queue.AddRateLimited(dKey)\n\treturn true\n}","line":{"from":627,"to":635}} {"id":100003683,"name":"stalePodDisruptionWorker","signature":"func (dc *DisruptionController) stalePodDisruptionWorker(ctx context.Context)","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) stalePodDisruptionWorker(ctx context.Context) {\n\tfor dc.processNextStalePodDisruptionWorkItem(ctx) {\n\t}\n}","line":{"from":637,"to":640}} {"id":100003684,"name":"processNextStalePodDisruptionWorkItem","signature":"func (dc *DisruptionController) processNextStalePodDisruptionWorkItem(ctx context.Context) bool","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) processNextStalePodDisruptionWorkItem(ctx context.Context) bool {\n\tkey, quit := dc.stalePodDisruptionQueue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer dc.stalePodDisruptionQueue.Done(key)\n\terr := dc.syncStalePodDisruption(ctx, key.(string))\n\tif err == nil {\n\t\tdc.stalePodDisruptionQueue.Forget(key)\n\t\treturn true\n\t}\n\tutilruntime.HandleError(fmt.Errorf(\"error syncing Pod %v to clear DisruptionTarget condition, requeueing: %v\", key.(string), err))\n\tdc.stalePodDisruptionQueue.AddRateLimited(key)\n\treturn true\n}","line":{"from":642,"to":656}} {"id":100003685,"name":"sync","signature":"func (dc *DisruptionController) sync(ctx context.Context, key string) error","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) sync(ctx context.Context, key string) error {\n\tstartTime := dc.clock.Now()\n\tdefer func() {\n\t\tklog.V(4).Infof(\"Finished syncing PodDisruptionBudget %q (%v)\", key, dc.clock.Since(startTime))\n\t}()\n\n\tnamespace, name, err := cache.SplitMetaNamespaceKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpdb, err := dc.pdbLister.PodDisruptionBudgets(namespace).Get(name)\n\tif errors.IsNotFound(err) {\n\t\tklog.V(4).Infof(\"PodDisruptionBudget %q has been deleted\", key)\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = dc.trySync(ctx, pdb)\n\t// If the reason for failure was a conflict, then allow this PDB update to be\n\t// requeued without triggering the failSafe logic.\n\tif errors.IsConflict(err) {\n\t\treturn err\n\t}\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to sync pdb %s/%s: %v\", pdb.Namespace, pdb.Name, err)\n\t\treturn dc.failSafe(ctx, pdb, err)\n\t}\n\n\treturn nil\n}","line":{"from":658,"to":689}} {"id":100003686,"name":"trySync","signature":"func (dc *DisruptionController) trySync(ctx context.Context, pdb *policy.PodDisruptionBudget) error","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) trySync(ctx context.Context, pdb *policy.PodDisruptionBudget) error {\n\tpods, err := dc.getPodsForPdb(pdb)\n\tif err != nil {\n\t\tdc.recorder.Eventf(pdb, v1.EventTypeWarning, \"NoPods\", \"Failed to get pods: %v\", err)\n\t\treturn err\n\t}\n\tif len(pods) == 0 {\n\t\tdc.recorder.Eventf(pdb, v1.EventTypeNormal, \"NoPods\", \"No matching pods found\")\n\t}\n\n\texpectedCount, desiredHealthy, unmanagedPods, err := dc.getExpectedPodCount(ctx, pdb, pods)\n\tif err != nil {\n\t\tdc.recorder.Eventf(pdb, v1.EventTypeWarning, \"CalculateExpectedPodCountFailed\", \"Failed to calculate the number of expected pods: %v\", err)\n\t\treturn err\n\t}\n\t// We have unmamanged pods, instead of erroring and hotlooping in disruption controller, log and continue.\n\tif len(unmanagedPods) \u003e 0 {\n\t\tklog.Warningf(\"found unmanaged pods associated with this PDB: %v\", unmanagedPods)\n\t\tdc.recorder.Eventf(pdb, v1.EventTypeWarning, \"UnmanagedPods\", \"Pods selected by this PodDisruptionBudget (selector: %v) were found \"+\n\t\t\t\"to be unmanaged. As a result, the status of the PDB cannot be calculated correctly, which may result in undefined behavior. \"+\n\t\t\t\"To account for these pods please set \\\".spec.minAvailable\\\" \"+\n\t\t\t\"field of the PDB to an integer value.\", pdb.Spec.Selector)\n\t}\n\n\tcurrentTime := dc.clock.Now()\n\tdisruptedPods, recheckTime := dc.buildDisruptedPodMap(pods, pdb, currentTime)\n\tcurrentHealthy := countHealthyPods(pods, disruptedPods, currentTime)\n\terr = dc.updatePdbStatus(ctx, pdb, currentHealthy, desiredHealthy, expectedCount, disruptedPods)\n\n\tif err == nil \u0026\u0026 recheckTime != nil {\n\t\t// There is always at most one PDB waiting with a particular name in the queue,\n\t\t// and each PDB in the queue is associated with the lowest timestamp\n\t\t// that was supplied when a PDB with that name was added.\n\t\tdc.enqueuePdbForRecheck(pdb, recheckTime.Sub(currentTime))\n\t}\n\treturn err\n}","line":{"from":691,"to":727}} {"id":100003687,"name":"syncStalePodDisruption","signature":"func (dc *DisruptionController) syncStalePodDisruption(ctx context.Context, key string) error","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) syncStalePodDisruption(ctx context.Context, key string) error {\n\tstartTime := dc.clock.Now()\n\tnamespace, name, err := cache.SplitMetaNamespaceKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tklog.V(4).InfoS(\"Finished syncing Pod to clear DisruptionTarget condition\", \"pod\", klog.KRef(namespace, name), \"duration\", dc.clock.Since(startTime))\n\t}()\n\tpod, err := dc.podLister.Pods(namespace).Get(name)\n\tif errors.IsNotFound(err) {\n\t\tklog.V(4).InfoS(\"Skipping clearing DisruptionTarget condition because pod was deleted\", \"pod\", klog.KObj(pod))\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\thasCond, cleanAfter := dc.nonTerminatingPodHasStaleDisruptionCondition(pod)\n\tif !hasCond {\n\t\treturn nil\n\t}\n\tif cleanAfter \u003e 0 {\n\t\tdc.enqueueStalePodDisruptionCleanup(pod, cleanAfter)\n\t\treturn nil\n\t}\n\n\tpodApply := corev1apply.Pod(pod.Name, pod.Namespace).\n\t\tWithStatus(corev1apply.PodStatus()).\n\t\tWithResourceVersion(pod.ResourceVersion)\n\tpodApply.Status.WithConditions(corev1apply.PodCondition().\n\t\tWithType(v1.DisruptionTarget).\n\t\tWithStatus(v1.ConditionFalse).\n\t\tWithLastTransitionTime(metav1.Now()),\n\t)\n\n\tif _, err := dc.kubeClient.CoreV1().Pods(pod.Namespace).ApplyStatus(ctx, podApply, metav1.ApplyOptions{FieldManager: fieldManager, Force: true}); err != nil {\n\t\treturn err\n\t}\n\tklog.V(2).InfoS(\"Reset stale DisruptionTarget condition to False\", \"pod\", klog.KObj(pod))\n\treturn nil\n}","line":{"from":729,"to":770}} {"id":100003688,"name":"getExpectedPodCount","signature":"func (dc *DisruptionController) getExpectedPodCount(ctx context.Context, pdb *policy.PodDisruptionBudget, pods []*v1.Pod) (expectedCount, desiredHealthy int32, unmanagedPods []string, err error)","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) getExpectedPodCount(ctx context.Context, pdb *policy.PodDisruptionBudget, pods []*v1.Pod) (expectedCount, desiredHealthy int32, unmanagedPods []string, err error) {\n\terr = nil\n\t// TODO(davidopp): consider making the way expectedCount and rules about\n\t// permitted controller configurations (specifically, considering it an error\n\t// if a pod covered by a PDB has 0 controllers or \u003e 1 controller) should be\n\t// handled the same way for integer and percentage minAvailable\n\n\tif pdb.Spec.MaxUnavailable != nil {\n\t\texpectedCount, unmanagedPods, err = dc.getExpectedScale(ctx, pdb, pods)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tvar maxUnavailable int\n\t\tmaxUnavailable, err = intstr.GetScaledValueFromIntOrPercent(pdb.Spec.MaxUnavailable, int(expectedCount), true)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tdesiredHealthy = expectedCount - int32(maxUnavailable)\n\t\tif desiredHealthy \u003c 0 {\n\t\t\tdesiredHealthy = 0\n\t\t}\n\t} else if pdb.Spec.MinAvailable != nil {\n\t\tif pdb.Spec.MinAvailable.Type == intstr.Int {\n\t\t\tdesiredHealthy = pdb.Spec.MinAvailable.IntVal\n\t\t\texpectedCount = int32(len(pods))\n\t\t} else if pdb.Spec.MinAvailable.Type == intstr.String {\n\t\t\texpectedCount, unmanagedPods, err = dc.getExpectedScale(ctx, pdb, pods)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tvar minAvailable int\n\t\t\tminAvailable, err = intstr.GetScaledValueFromIntOrPercent(pdb.Spec.MinAvailable, int(expectedCount), true)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdesiredHealthy = int32(minAvailable)\n\t\t}\n\t}\n\treturn\n}","line":{"from":772,"to":812}} {"id":100003689,"name":"getExpectedScale","signature":"func (dc *DisruptionController) getExpectedScale(ctx context.Context, pdb *policy.PodDisruptionBudget, pods []*v1.Pod) (expectedCount int32, unmanagedPods []string, err error)","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) getExpectedScale(ctx context.Context, pdb *policy.PodDisruptionBudget, pods []*v1.Pod) (expectedCount int32, unmanagedPods []string, err error) {\n\t// When the user specifies a fraction of pods that must be available, we\n\t// use as the fraction's denominator\n\t// SUM_{all c in C} scale(c)\n\t// where C is the union of C_p1, C_p2, ..., C_pN\n\t// and each C_pi is the set of controllers controlling the pod pi\n\n\t// k8s only defines what will happens when 0 or 1 controllers control a\n\t// given pod. We explicitly exclude the 0 controllers case here, and we\n\t// report an error if we find a pod with more than 1 controller. Thus in\n\t// practice each C_pi is a set of exactly 1 controller.\n\n\t// A mapping from controllers to their scale.\n\tcontrollerScale := map[types.UID]int32{}\n\n\t// 1. Find the controller for each pod.\n\n\t// As of now, we allow PDBs to be applied to pods via selectors, so there\n\t// can be unmanaged pods(pods that don't have backing controllers) but still have PDBs associated.\n\t// Such pods are to be collected and PDB backing them should be enqueued instead of immediately throwing\n\t// a sync error. This ensures disruption controller is not frequently updating the status subresource and thus\n\t// preventing excessive and expensive writes to etcd.\n\t// With ControllerRef, a pod can only have 1 controller.\n\tfor _, pod := range pods {\n\t\tcontrollerRef := metav1.GetControllerOf(pod)\n\t\tif controllerRef == nil {\n\t\t\tunmanagedPods = append(unmanagedPods, pod.Name)\n\t\t\tcontinue\n\t\t}\n\n\t\t// If we already know the scale of the controller there is no need to do anything.\n\t\tif _, found := controllerScale[controllerRef.UID]; found {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Check all the supported controllers to find the desired scale.\n\t\tfoundController := false\n\t\tfor _, finder := range dc.finders() {\n\t\t\tvar controllerNScale *controllerAndScale\n\t\t\tcontrollerNScale, err = finder(ctx, controllerRef, pod.Namespace)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif controllerNScale != nil {\n\t\t\t\tcontrollerScale[controllerNScale.UID] = controllerNScale.scale\n\t\t\t\tfoundController = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !foundController {\n\t\t\terr = fmt.Errorf(\"found no controllers for pod %q\", pod.Name)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// 2. Add up all the controllers.\n\texpectedCount = 0\n\tfor _, count := range controllerScale {\n\t\texpectedCount += count\n\t}\n\n\treturn\n}","line":{"from":814,"to":876}} {"id":100003690,"name":"countHealthyPods","signature":"func countHealthyPods(pods []*v1.Pod, disruptedPods map[string]metav1.Time, currentTime time.Time) (currentHealthy int32)","file":"pkg/controller/disruption/disruption.go","code":"func countHealthyPods(pods []*v1.Pod, disruptedPods map[string]metav1.Time, currentTime time.Time) (currentHealthy int32) {\n\tfor _, pod := range pods {\n\t\t// Pod is being deleted.\n\t\tif pod.DeletionTimestamp != nil {\n\t\t\tcontinue\n\t\t}\n\t\t// Pod is expected to be deleted soon.\n\t\tif disruptionTime, found := disruptedPods[pod.Name]; found \u0026\u0026 disruptionTime.Time.Add(DeletionTimeout).After(currentTime) {\n\t\t\tcontinue\n\t\t}\n\t\tif apipod.IsPodReady(pod) {\n\t\t\tcurrentHealthy++\n\t\t}\n\t}\n\n\treturn\n}","line":{"from":878,"to":894}} {"id":100003691,"name":"buildDisruptedPodMap","signature":"func (dc *DisruptionController) buildDisruptedPodMap(pods []*v1.Pod, pdb *policy.PodDisruptionBudget, currentTime time.Time) (map[string]metav1.Time, *time.Time)","file":"pkg/controller/disruption/disruption.go","code":"// Builds new PodDisruption map, possibly removing items that refer to non-existing, already deleted\n// or not-deleted at all items. Also returns an information when this check should be repeated.\nfunc (dc *DisruptionController) buildDisruptedPodMap(pods []*v1.Pod, pdb *policy.PodDisruptionBudget, currentTime time.Time) (map[string]metav1.Time, *time.Time) {\n\tdisruptedPods := pdb.Status.DisruptedPods\n\tresult := make(map[string]metav1.Time)\n\tvar recheckTime *time.Time\n\n\tif disruptedPods == nil {\n\t\treturn result, recheckTime\n\t}\n\tfor _, pod := range pods {\n\t\tif pod.DeletionTimestamp != nil {\n\t\t\t// Already being deleted.\n\t\t\tcontinue\n\t\t}\n\t\tdisruptionTime, found := disruptedPods[pod.Name]\n\t\tif !found {\n\t\t\t// Pod not on the list.\n\t\t\tcontinue\n\t\t}\n\t\texpectedDeletion := disruptionTime.Time.Add(DeletionTimeout)\n\t\tif expectedDeletion.Before(currentTime) {\n\t\t\tklog.V(1).Infof(\"Pod %s/%s was expected to be deleted at %s but it wasn't, updating pdb %s/%s\",\n\t\t\t\tpod.Namespace, pod.Name, disruptionTime.String(), pdb.Namespace, pdb.Name)\n\t\t\tdc.recorder.Eventf(pod, v1.EventTypeWarning, \"NotDeleted\", \"Pod was expected by PDB %s/%s to be deleted but it wasn't\",\n\t\t\t\tpdb.Namespace, pdb.Namespace)\n\t\t} else {\n\t\t\tif recheckTime == nil || expectedDeletion.Before(*recheckTime) {\n\t\t\t\trecheckTime = \u0026expectedDeletion\n\t\t\t}\n\t\t\tresult[pod.Name] = disruptionTime\n\t\t}\n\t}\n\treturn result, recheckTime\n}","line":{"from":896,"to":930}} {"id":100003692,"name":"failSafe","signature":"func (dc *DisruptionController) failSafe(ctx context.Context, pdb *policy.PodDisruptionBudget, err error) error","file":"pkg/controller/disruption/disruption.go","code":"// failSafe is an attempt to at least update the DisruptionsAllowed field to\n// 0 if everything else has failed. This is one place we\n// implement the \"fail open\" part of the design since if we manage to update\n// this field correctly, we will prevent the /evict handler from approving an\n// eviction when it may be unsafe to do so.\nfunc (dc *DisruptionController) failSafe(ctx context.Context, pdb *policy.PodDisruptionBudget, err error) error {\n\tnewPdb := pdb.DeepCopy()\n\tnewPdb.Status.DisruptionsAllowed = 0\n\n\tif newPdb.Status.Conditions == nil {\n\t\tnewPdb.Status.Conditions = make([]metav1.Condition, 0)\n\t}\n\tapimeta.SetStatusCondition(\u0026newPdb.Status.Conditions, metav1.Condition{\n\t\tType: policy.DisruptionAllowedCondition,\n\t\tStatus: metav1.ConditionFalse,\n\t\tReason: policy.SyncFailedReason,\n\t\tMessage: err.Error(),\n\t\tObservedGeneration: newPdb.Status.ObservedGeneration,\n\t})\n\n\treturn dc.getUpdater()(ctx, newPdb)\n}","line":{"from":932,"to":953}} {"id":100003693,"name":"updatePdbStatus","signature":"func (dc *DisruptionController) updatePdbStatus(ctx context.Context, pdb *policy.PodDisruptionBudget, currentHealthy, desiredHealthy, expectedCount int32,","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) updatePdbStatus(ctx context.Context, pdb *policy.PodDisruptionBudget, currentHealthy, desiredHealthy, expectedCount int32,\n\tdisruptedPods map[string]metav1.Time) error {\n\n\t// We require expectedCount to be \u003e 0 so that PDBs which currently match no\n\t// pods are in a safe state when their first pods appear but this controller\n\t// has not updated their status yet. This isn't the only race, but it's a\n\t// common one that's easy to detect.\n\tdisruptionsAllowed := currentHealthy - desiredHealthy\n\tif expectedCount \u003c= 0 || disruptionsAllowed \u003c= 0 {\n\t\tdisruptionsAllowed = 0\n\t}\n\n\tif pdb.Status.CurrentHealthy == currentHealthy \u0026\u0026\n\t\tpdb.Status.DesiredHealthy == desiredHealthy \u0026\u0026\n\t\tpdb.Status.ExpectedPods == expectedCount \u0026\u0026\n\t\tpdb.Status.DisruptionsAllowed == disruptionsAllowed \u0026\u0026\n\t\tapiequality.Semantic.DeepEqual(pdb.Status.DisruptedPods, disruptedPods) \u0026\u0026\n\t\tpdb.Status.ObservedGeneration == pdb.Generation \u0026\u0026\n\t\tpdbhelper.ConditionsAreUpToDate(pdb) {\n\t\treturn nil\n\t}\n\n\tnewPdb := pdb.DeepCopy()\n\tnewPdb.Status = policy.PodDisruptionBudgetStatus{\n\t\tCurrentHealthy: currentHealthy,\n\t\tDesiredHealthy: desiredHealthy,\n\t\tExpectedPods: expectedCount,\n\t\tDisruptionsAllowed: disruptionsAllowed,\n\t\tDisruptedPods: disruptedPods,\n\t\tObservedGeneration: pdb.Generation,\n\t}\n\n\tpdbhelper.UpdateDisruptionAllowedCondition(newPdb)\n\n\treturn dc.getUpdater()(ctx, newPdb)\n}","line":{"from":955,"to":990}} {"id":100003694,"name":"writePdbStatus","signature":"func (dc *DisruptionController) writePdbStatus(ctx context.Context, pdb *policy.PodDisruptionBudget) error","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) writePdbStatus(ctx context.Context, pdb *policy.PodDisruptionBudget) error {\n\t// If this update fails, don't retry it. Allow the failure to get handled \u0026\n\t// retried in `processNextWorkItem()`.\n\t_, err := dc.kubeClient.PolicyV1().PodDisruptionBudgets(pdb.Namespace).UpdateStatus(ctx, pdb, metav1.UpdateOptions{})\n\treturn err\n}","line":{"from":992,"to":997}} {"id":100003695,"name":"nonTerminatingPodHasStaleDisruptionCondition","signature":"func (dc *DisruptionController) nonTerminatingPodHasStaleDisruptionCondition(pod *v1.Pod) (bool, time.Duration)","file":"pkg/controller/disruption/disruption.go","code":"func (dc *DisruptionController) nonTerminatingPodHasStaleDisruptionCondition(pod *v1.Pod) (bool, time.Duration) {\n\tif pod.DeletionTimestamp != nil {\n\t\treturn false, 0\n\t}\n\t_, cond := apipod.GetPodCondition(\u0026pod.Status, v1.DisruptionTarget)\n\t// Pod disruption conditions added by kubelet are never considered stale because the condition might take\n\t// arbitrarily long before the pod is terminating (has deletion timestamp). Also, pod conditions present\n\t// on pods in terminal phase are not stale to avoid unnecessary status updates.\n\tif cond == nil || cond.Status != v1.ConditionTrue || cond.Reason == v1.PodReasonTerminationByKubelet || apipod.IsPodPhaseTerminal(pod.Status.Phase) {\n\t\treturn false, 0\n\t}\n\twaitFor := dc.stalePodDisruptionTimeout - dc.clock.Since(cond.LastTransitionTime.Time)\n\tif waitFor \u003c 0 {\n\t\twaitFor = 0\n\t}\n\treturn true, waitFor\n}","line":{"from":999,"to":1015}} {"id":100003696,"name":"Convert_v1alpha1_EndpointControllerConfiguration_To_config_EndpointControllerConfiguration","signature":"func Convert_v1alpha1_EndpointControllerConfiguration_To_config_EndpointControllerConfiguration(in *v1alpha1.EndpointControllerConfiguration, out *endpointconfig.EndpointControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/endpoint/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_EndpointControllerConfiguration_To_config_EndpointControllerConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_EndpointControllerConfiguration_To_config_EndpointControllerConfiguration(in *v1alpha1.EndpointControllerConfiguration, out *endpointconfig.EndpointControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_EndpointControllerConfiguration_To_config_EndpointControllerConfiguration(in, out, s)\n}","line":{"from":32,"to":35}} {"id":100003697,"name":"Convert_config_EndpointControllerConfiguration_To_v1alpha1_EndpointControllerConfiguration","signature":"func Convert_config_EndpointControllerConfiguration_To_v1alpha1_EndpointControllerConfiguration(in *endpointconfig.EndpointControllerConfiguration, out *v1alpha1.EndpointControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/endpoint/config/v1alpha1/conversion.go","code":"// Convert_config_EndpointControllerConfiguration_To_v1alpha1_EndpointControllerConfiguration is an autogenerated conversion function.\nfunc Convert_config_EndpointControllerConfiguration_To_v1alpha1_EndpointControllerConfiguration(in *endpointconfig.EndpointControllerConfiguration, out *v1alpha1.EndpointControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_EndpointControllerConfiguration_To_v1alpha1_EndpointControllerConfiguration(in, out, s)\n}","line":{"from":37,"to":40}} {"id":100003698,"name":"RecommendedDefaultEndpointControllerConfiguration","signature":"func RecommendedDefaultEndpointControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.EndpointControllerConfiguration)","file":"pkg/controller/endpoint/config/v1alpha1/defaults.go","code":"// RecommendedDefaultEndpointControllerConfiguration defaults a pointer to a\n// EndpointControllerConfiguration struct. This will set the recommended default\n// values, but they may be subject to change between API versions. This function\n// is intentionally not registered in the scheme as a \"normal\" `SetDefaults_Foo`\n// function to allow consumers of this type to set whatever defaults for their\n// embedded configs. Forcing consumers to use these defaults would be problematic\n// as defaulting in the scheme is done as part of the conversion, and there would\n// be no easy way to opt-out. Instead, if you want to use this defaulting method\n// run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDefaultEndpointControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.EndpointControllerConfiguration) {\n\tif obj.ConcurrentEndpointSyncs == 0 {\n\t\tobj.ConcurrentEndpointSyncs = 5\n\t}\n}","line":{"from":23,"to":36}} {"id":100003699,"name":"NewEndpointController","signature":"func NewEndpointController(podInformer coreinformers.PodInformer, serviceInformer coreinformers.ServiceInformer,","file":"pkg/controller/endpoint/endpoints_controller.go","code":"// NewEndpointController returns a new *Controller.\nfunc NewEndpointController(podInformer coreinformers.PodInformer, serviceInformer coreinformers.ServiceInformer,\n\tendpointsInformer coreinformers.EndpointsInformer, client clientset.Interface, endpointUpdatesBatchPeriod time.Duration) *Controller {\n\tbroadcaster := record.NewBroadcaster()\n\trecorder := broadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"endpoint-controller\"})\n\n\te := \u0026Controller{\n\t\tclient: client,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"endpoint\"),\n\t\tworkerLoopPeriod: time.Second,\n\t}\n\n\tserviceInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: e.onServiceUpdate,\n\t\tUpdateFunc: func(old, cur interface{}) {\n\t\t\te.onServiceUpdate(cur)\n\t\t},\n\t\tDeleteFunc: e.onServiceDelete,\n\t})\n\te.serviceLister = serviceInformer.Lister()\n\te.servicesSynced = serviceInformer.Informer().HasSynced\n\n\tpodInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: e.addPod,\n\t\tUpdateFunc: e.updatePod,\n\t\tDeleteFunc: e.deletePod,\n\t})\n\te.podLister = podInformer.Lister()\n\te.podsSynced = podInformer.Informer().HasSynced\n\n\tendpointsInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tDeleteFunc: e.onEndpointsDelete,\n\t})\n\te.endpointsLister = endpointsInformer.Lister()\n\te.endpointsSynced = endpointsInformer.Informer().HasSynced\n\n\te.triggerTimeTracker = endpointutil.NewTriggerTimeTracker()\n\te.eventBroadcaster = broadcaster\n\te.eventRecorder = recorder\n\n\te.endpointUpdatesBatchPeriod = endpointUpdatesBatchPeriod\n\n\treturn e\n}","line":{"from":71,"to":114}} {"id":100003700,"name":"Run","signature":"func (e *Controller) Run(ctx context.Context, workers int)","file":"pkg/controller/endpoint/endpoints_controller.go","code":"// Run will not return until stopCh is closed. workers determines how many\n// endpoints will be handled in parallel.\nfunc (e *Controller) Run(ctx context.Context, workers int) {\n\tdefer utilruntime.HandleCrash()\n\n\t// Start events processing pipeline.\n\te.eventBroadcaster.StartStructuredLogging(0)\n\te.eventBroadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: e.client.CoreV1().Events(\"\")})\n\tdefer e.eventBroadcaster.Shutdown()\n\n\tdefer e.queue.ShutDown()\n\n\tklog.Infof(\"Starting endpoint controller\")\n\tdefer klog.Infof(\"Shutting down endpoint controller\")\n\n\tif !cache.WaitForNamedCacheSync(\"endpoint\", ctx.Done(), e.podsSynced, e.servicesSynced, e.endpointsSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.UntilWithContext(ctx, e.worker, e.workerLoopPeriod)\n\t}\n\n\tgo func() {\n\t\tdefer utilruntime.HandleCrash()\n\t\te.checkLeftoverEndpoints()\n\t}()\n\n\t\u003c-ctx.Done()\n}","line":{"from":160,"to":189}} {"id":100003701,"name":"addPod","signature":"func (e *Controller) addPod(obj interface{})","file":"pkg/controller/endpoint/endpoints_controller.go","code":"// When a pod is added, figure out what services it will be a member of and\n// enqueue them. obj must have *v1.Pod type.\nfunc (e *Controller) addPod(obj interface{}) {\n\tpod := obj.(*v1.Pod)\n\tservices, err := endpointutil.GetPodServiceMemberships(e.serviceLister, pod)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Unable to get pod %s/%s's service memberships: %v\", pod.Namespace, pod.Name, err))\n\t\treturn\n\t}\n\tfor key := range services {\n\t\te.queue.AddAfter(key, e.endpointUpdatesBatchPeriod)\n\t}\n}","line":{"from":191,"to":203}} {"id":100003702,"name":"podToEndpointAddressForService","signature":"func podToEndpointAddressForService(svc *v1.Service, pod *v1.Pod) (*v1.EndpointAddress, error)","file":"pkg/controller/endpoint/endpoints_controller.go","code":"func podToEndpointAddressForService(svc *v1.Service, pod *v1.Pod) (*v1.EndpointAddress, error) {\n\tvar endpointIP string\n\tipFamily := v1.IPv4Protocol\n\n\tif len(svc.Spec.IPFamilies) \u003e 0 {\n\t\t// controller is connected to an api-server that correctly sets IPFamilies\n\t\tipFamily = svc.Spec.IPFamilies[0] // this works for headful and headless\n\t} else {\n\t\t// controller is connected to an api server that does not correctly\n\t\t// set IPFamilies (e.g. old api-server during an upgrade)\n\t\t// TODO (khenidak): remove by when the possibility of upgrading\n\t\t// from a cluster that does not support dual stack is nil\n\t\tif len(svc.Spec.ClusterIP) \u003e 0 \u0026\u0026 svc.Spec.ClusterIP != v1.ClusterIPNone {\n\t\t\t// headful service. detect via service clusterIP\n\t\t\tif utilnet.IsIPv6String(svc.Spec.ClusterIP) {\n\t\t\t\tipFamily = v1.IPv6Protocol\n\t\t\t}\n\t\t} else {\n\t\t\t// Since this is a headless service we use podIP to identify the family.\n\t\t\t// This assumes that status.PodIP is assigned correctly (follows pod cidr and\n\t\t\t// pod cidr list order is same as service cidr list order). The expectation is\n\t\t\t// this is *most probably* the case.\n\n\t\t\t// if the family was incorrectly identified then this will be corrected once the\n\t\t\t// upgrade is completed (controller connects to api-server that correctly defaults services)\n\t\t\tif utilnet.IsIPv6String(pod.Status.PodIP) {\n\t\t\t\tipFamily = v1.IPv6Protocol\n\t\t\t}\n\t\t}\n\t}\n\n\t// find an ip that matches the family\n\tfor _, podIP := range pod.Status.PodIPs {\n\t\tif (ipFamily == v1.IPv6Protocol) == utilnet.IsIPv6String(podIP.IP) {\n\t\t\tendpointIP = podIP.IP\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif endpointIP == \"\" {\n\t\treturn nil, fmt.Errorf(\"failed to find a matching endpoint for service %v\", svc.Name)\n\t}\n\n\treturn \u0026v1.EndpointAddress{\n\t\tIP: endpointIP,\n\t\tNodeName: \u0026pod.Spec.NodeName,\n\t\tTargetRef: \u0026v1.ObjectReference{\n\t\t\tKind: \"Pod\",\n\t\t\tNamespace: pod.ObjectMeta.Namespace,\n\t\t\tName: pod.ObjectMeta.Name,\n\t\t\tUID: pod.ObjectMeta.UID,\n\t\t},\n\t}, nil\n}","line":{"from":205,"to":258}} {"id":100003703,"name":"updatePod","signature":"func (e *Controller) updatePod(old, cur interface{})","file":"pkg/controller/endpoint/endpoints_controller.go","code":"// When a pod is updated, figure out what services it used to be a member of\n// and what services it will be a member of, and enqueue the union of these.\n// old and cur must be *v1.Pod types.\nfunc (e *Controller) updatePod(old, cur interface{}) {\n\tservices := endpointutil.GetServicesToUpdateOnPodChange(e.serviceLister, old, cur)\n\tfor key := range services {\n\t\te.queue.AddAfter(key, e.endpointUpdatesBatchPeriod)\n\t}\n}","line":{"from":260,"to":268}} {"id":100003704,"name":"deletePod","signature":"func (e *Controller) deletePod(obj interface{})","file":"pkg/controller/endpoint/endpoints_controller.go","code":"// When a pod is deleted, enqueue the services the pod used to be a member of.\n// obj could be an *v1.Pod, or a DeletionFinalStateUnknown marker item.\nfunc (e *Controller) deletePod(obj interface{}) {\n\tpod := endpointutil.GetPodFromDeleteAction(obj)\n\tif pod != nil {\n\t\te.addPod(pod)\n\t}\n}","line":{"from":270,"to":277}} {"id":100003705,"name":"onServiceUpdate","signature":"func (e *Controller) onServiceUpdate(obj interface{})","file":"pkg/controller/endpoint/endpoints_controller.go","code":"// onServiceUpdate updates the Service Selector in the cache and queues the Service for processing.\nfunc (e *Controller) onServiceUpdate(obj interface{}) {\n\tkey, err := controller.KeyFunc(obj)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Couldn't get key for object %+v: %v\", obj, err))\n\t\treturn\n\t}\n\te.queue.Add(key)\n}","line":{"from":279,"to":287}} {"id":100003706,"name":"onServiceDelete","signature":"func (e *Controller) onServiceDelete(obj interface{})","file":"pkg/controller/endpoint/endpoints_controller.go","code":"// onServiceDelete removes the Service Selector from the cache and queues the Service for processing.\nfunc (e *Controller) onServiceDelete(obj interface{}) {\n\tkey, err := controller.KeyFunc(obj)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Couldn't get key for object %+v: %v\", obj, err))\n\t\treturn\n\t}\n\te.queue.Add(key)\n}","line":{"from":289,"to":297}} {"id":100003707,"name":"onEndpointsDelete","signature":"func (e *Controller) onEndpointsDelete(obj interface{})","file":"pkg/controller/endpoint/endpoints_controller.go","code":"func (e *Controller) onEndpointsDelete(obj interface{}) {\n\tkey, err := controller.KeyFunc(obj)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Couldn't get key for object %+v: %v\", obj, err))\n\t\treturn\n\t}\n\te.queue.Add(key)\n}","line":{"from":299,"to":306}} {"id":100003708,"name":"worker","signature":"func (e *Controller) worker(ctx context.Context)","file":"pkg/controller/endpoint/endpoints_controller.go","code":"// worker runs a worker thread that just dequeues items, processes them, and\n// marks them done. You may run as many of these in parallel as you wish; the\n// workqueue guarantees that they will not end up processing the same service\n// at the same time.\nfunc (e *Controller) worker(ctx context.Context) {\n\tfor e.processNextWorkItem(ctx) {\n\t}\n}","line":{"from":308,"to":315}} {"id":100003709,"name":"processNextWorkItem","signature":"func (e *Controller) processNextWorkItem(ctx context.Context) bool","file":"pkg/controller/endpoint/endpoints_controller.go","code":"func (e *Controller) processNextWorkItem(ctx context.Context) bool {\n\teKey, quit := e.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer e.queue.Done(eKey)\n\n\terr := e.syncService(ctx, eKey.(string))\n\te.handleErr(err, eKey)\n\n\treturn true\n}","line":{"from":317,"to":328}} {"id":100003710,"name":"handleErr","signature":"func (e *Controller) handleErr(err error, key interface{})","file":"pkg/controller/endpoint/endpoints_controller.go","code":"func (e *Controller) handleErr(err error, key interface{}) {\n\tif err == nil {\n\t\te.queue.Forget(key)\n\t\treturn\n\t}\n\n\tns, name, keyErr := cache.SplitMetaNamespaceKey(key.(string))\n\tif keyErr != nil {\n\t\tklog.ErrorS(err, \"Failed to split meta namespace cache key\", \"key\", key)\n\t}\n\n\tif e.queue.NumRequeues(key) \u003c maxRetries {\n\t\tklog.V(2).InfoS(\"Error syncing endpoints, retrying\", \"service\", klog.KRef(ns, name), \"err\", err)\n\t\te.queue.AddRateLimited(key)\n\t\treturn\n\t}\n\n\tklog.Warningf(\"Dropping service %q out of the queue: %v\", key, err)\n\te.queue.Forget(key)\n\tutilruntime.HandleError(err)\n}","line":{"from":330,"to":350}} {"id":100003711,"name":"syncService","signature":"func (e *Controller) syncService(ctx context.Context, key string) error","file":"pkg/controller/endpoint/endpoints_controller.go","code":"func (e *Controller) syncService(ctx context.Context, key string) error {\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tklog.V(4).Infof(\"Finished syncing service %q endpoints. (%v)\", key, time.Since(startTime))\n\t}()\n\n\tnamespace, name, err := cache.SplitMetaNamespaceKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tservice, err := e.serviceLister.Services(namespace).Get(name)\n\tif err != nil {\n\t\tif !errors.IsNotFound(err) {\n\t\t\treturn err\n\t\t}\n\n\t\t// Delete the corresponding endpoint, as the service has been deleted.\n\t\t// TODO: Please note that this will delete an endpoint when a\n\t\t// service is deleted. However, if we're down at the time when\n\t\t// the service is deleted, we will miss that deletion, so this\n\t\t// doesn't completely solve the problem. See #6877.\n\t\terr = e.client.CoreV1().Endpoints(namespace).Delete(ctx, name, metav1.DeleteOptions{})\n\t\tif err != nil \u0026\u0026 !errors.IsNotFound(err) {\n\t\t\treturn err\n\t\t}\n\t\te.triggerTimeTracker.DeleteService(namespace, name)\n\t\treturn nil\n\t}\n\n\tif service.Spec.Type == v1.ServiceTypeExternalName {\n\t\t// services with Type ExternalName receive no endpoints from this controller;\n\t\t// Ref: https://issues.k8s.io/105986\n\t\treturn nil\n\t}\n\n\tif service.Spec.Selector == nil {\n\t\t// services without a selector receive no endpoints from this controller;\n\t\t// these services will receive the endpoints that are created out-of-band via the REST API.\n\t\treturn nil\n\t}\n\n\tklog.V(5).Infof(\"About to update endpoints for service %q\", key)\n\tpods, err := e.podLister.Pods(service.Namespace).List(labels.Set(service.Spec.Selector).AsSelectorPreValidated())\n\tif err != nil {\n\t\t// Since we're getting stuff from a local cache, it is\n\t\t// basically impossible to get this error.\n\t\treturn err\n\t}\n\n\t// We call ComputeEndpointLastChangeTriggerTime here to make sure that the\n\t// state of the trigger time tracker gets updated even if the sync turns out\n\t// to be no-op and we don't update the endpoints object.\n\tendpointsLastChangeTriggerTime := e.triggerTimeTracker.\n\t\tComputeEndpointLastChangeTriggerTime(namespace, service, pods)\n\n\tsubsets := []v1.EndpointSubset{}\n\tvar totalReadyEps int\n\tvar totalNotReadyEps int\n\n\tfor _, pod := range pods {\n\t\tif !endpointutil.ShouldPodBeInEndpoints(pod, service.Spec.PublishNotReadyAddresses) {\n\t\t\tklog.V(5).Infof(\"Pod %s/%s is not included on endpoints for Service %s/%s\", pod.Namespace, pod.Name, service.Namespace, service.Name)\n\t\t\tcontinue\n\t\t}\n\n\t\tep, err := podToEndpointAddressForService(service, pod)\n\t\tif err != nil {\n\t\t\t// this will happen, if the cluster runs with some nodes configured as dual stack and some as not\n\t\t\t// such as the case of an upgrade..\n\t\t\tklog.V(2).Infof(\"Failed to find endpoint for service:%s with ClusterIP:%s on pod:%s with error:%v\", service.Name, service.Spec.ClusterIP, klog.KObj(pod), err)\n\t\t\tcontinue\n\t\t}\n\n\t\tepa := *ep\n\t\tif endpointutil.ShouldSetHostname(pod, service) {\n\t\t\tepa.Hostname = pod.Spec.Hostname\n\t\t}\n\n\t\t// Allow headless service not to have ports.\n\t\tif len(service.Spec.Ports) == 0 {\n\t\t\tif service.Spec.ClusterIP == api.ClusterIPNone {\n\t\t\t\tsubsets, totalReadyEps, totalNotReadyEps = addEndpointSubset(subsets, pod, epa, nil, service.Spec.PublishNotReadyAddresses)\n\t\t\t\t// No need to repack subsets for headless service without ports.\n\t\t\t}\n\t\t} else {\n\t\t\tfor i := range service.Spec.Ports {\n\t\t\t\tservicePort := \u0026service.Spec.Ports[i]\n\t\t\t\tportNum, err := podutil.FindPort(pod, servicePort)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.V(4).Infof(\"Failed to find port for service %s/%s: %v\", service.Namespace, service.Name, err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tepp := endpointPortFromServicePort(servicePort, portNum)\n\n\t\t\t\tvar readyEps, notReadyEps int\n\t\t\t\tsubsets, readyEps, notReadyEps = addEndpointSubset(subsets, pod, epa, epp, service.Spec.PublishNotReadyAddresses)\n\t\t\t\ttotalReadyEps = totalReadyEps + readyEps\n\t\t\t\ttotalNotReadyEps = totalNotReadyEps + notReadyEps\n\t\t\t}\n\t\t}\n\t}\n\tsubsets = endpoints.RepackSubsets(subsets)\n\n\t// See if there's actually an update here.\n\tcurrentEndpoints, err := e.endpointsLister.Endpoints(service.Namespace).Get(service.Name)\n\tif err != nil {\n\t\tif !errors.IsNotFound(err) {\n\t\t\treturn err\n\t\t}\n\t\tcurrentEndpoints = \u0026v1.Endpoints{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: service.Name,\n\t\t\t\tLabels: service.Labels,\n\t\t\t},\n\t\t}\n\t}\n\n\tcreateEndpoints := len(currentEndpoints.ResourceVersion) == 0\n\n\t// Compare the sorted subsets and labels\n\t// Remove the HeadlessService label from the endpoints if it exists,\n\t// as this won't be set on the service itself\n\t// and will cause a false negative in this diff check.\n\t// But first check if it has that label to avoid expensive copies.\n\tcompareLabels := currentEndpoints.Labels\n\tif _, ok := currentEndpoints.Labels[v1.IsHeadlessService]; ok {\n\t\tcompareLabels = utillabels.CloneAndRemoveLabel(currentEndpoints.Labels, v1.IsHeadlessService)\n\t}\n\t// When comparing the subsets, we ignore the difference in ResourceVersion of Pod to avoid unnecessary Endpoints\n\t// updates caused by Pod updates that we don't care, e.g. annotation update.\n\tif !createEndpoints \u0026\u0026\n\t\tendpointutil.EndpointSubsetsEqualIgnoreResourceVersion(currentEndpoints.Subsets, subsets) \u0026\u0026\n\t\tapiequality.Semantic.DeepEqual(compareLabels, service.Labels) \u0026\u0026\n\t\tcapacityAnnotationSetCorrectly(currentEndpoints.Annotations, currentEndpoints.Subsets) {\n\t\tklog.V(5).Infof(\"endpoints are equal for %s/%s, skipping update\", service.Namespace, service.Name)\n\t\treturn nil\n\t}\n\tnewEndpoints := currentEndpoints.DeepCopy()\n\tnewEndpoints.Subsets = subsets\n\tnewEndpoints.Labels = service.Labels\n\tif newEndpoints.Annotations == nil {\n\t\tnewEndpoints.Annotations = make(map[string]string)\n\t}\n\n\tif !endpointsLastChangeTriggerTime.IsZero() {\n\t\tnewEndpoints.Annotations[v1.EndpointsLastChangeTriggerTime] =\n\t\t\tendpointsLastChangeTriggerTime.UTC().Format(time.RFC3339Nano)\n\t} else { // No new trigger time, clear the annotation.\n\t\tdelete(newEndpoints.Annotations, v1.EndpointsLastChangeTriggerTime)\n\t}\n\n\tif truncateEndpoints(newEndpoints) {\n\t\tnewEndpoints.Annotations[v1.EndpointsOverCapacity] = truncated\n\t} else {\n\t\tdelete(newEndpoints.Annotations, v1.EndpointsOverCapacity)\n\t}\n\n\tif newEndpoints.Labels == nil {\n\t\tnewEndpoints.Labels = make(map[string]string)\n\t}\n\n\tif !helper.IsServiceIPSet(service) {\n\t\tnewEndpoints.Labels = utillabels.CloneAndAddLabel(newEndpoints.Labels, v1.IsHeadlessService, \"\")\n\t} else {\n\t\tnewEndpoints.Labels = utillabels.CloneAndRemoveLabel(newEndpoints.Labels, v1.IsHeadlessService)\n\t}\n\n\tklog.V(4).Infof(\"Update endpoints for %v/%v, ready: %d not ready: %d\", service.Namespace, service.Name, totalReadyEps, totalNotReadyEps)\n\tif createEndpoints {\n\t\t// No previous endpoints, create them\n\t\t_, err = e.client.CoreV1().Endpoints(service.Namespace).Create(ctx, newEndpoints, metav1.CreateOptions{})\n\t} else {\n\t\t// Pre-existing\n\t\t_, err = e.client.CoreV1().Endpoints(service.Namespace).Update(ctx, newEndpoints, metav1.UpdateOptions{})\n\t}\n\tif err != nil {\n\t\tif createEndpoints \u0026\u0026 errors.IsForbidden(err) {\n\t\t\t// A request is forbidden primarily for two reasons:\n\t\t\t// 1. namespace is terminating, endpoint creation is not allowed by default.\n\t\t\t// 2. policy is misconfigured, in which case no service would function anywhere.\n\t\t\t// Given the frequency of 1, we log at a lower level.\n\t\t\tklog.V(5).Infof(\"Forbidden from creating endpoints: %v\", err)\n\n\t\t\t// If the namespace is terminating, creates will continue to fail. Simply drop the item.\n\t\t\tif errors.HasStatusCause(err, v1.NamespaceTerminatingCause) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\tif createEndpoints {\n\t\t\te.eventRecorder.Eventf(newEndpoints, v1.EventTypeWarning, \"FailedToCreateEndpoint\", \"Failed to create endpoint for service %v/%v: %v\", service.Namespace, service.Name, err)\n\t\t} else {\n\t\t\te.eventRecorder.Eventf(newEndpoints, v1.EventTypeWarning, \"FailedToUpdateEndpoint\", \"Failed to update endpoint %v/%v: %v\", service.Namespace, service.Name, err)\n\t\t}\n\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":352,"to":550}} {"id":100003712,"name":"checkLeftoverEndpoints","signature":"func (e *Controller) checkLeftoverEndpoints()","file":"pkg/controller/endpoint/endpoints_controller.go","code":"// checkLeftoverEndpoints lists all currently existing endpoints and adds their\n// service to the queue. This will detect endpoints that exist with no\n// corresponding service; these endpoints need to be deleted. We only need to\n// do this once on startup, because in steady-state these are detected (but\n// some stragglers could have been left behind if the endpoint controller\n// reboots).\nfunc (e *Controller) checkLeftoverEndpoints() {\n\tlist, err := e.endpointsLister.List(labels.Everything())\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Unable to list endpoints (%v); orphaned endpoints will not be cleaned up. (They're pretty harmless, but you can restart this component if you want another attempt made.)\", err))\n\t\treturn\n\t}\n\tfor _, ep := range list {\n\t\tif _, ok := ep.Annotations[resourcelock.LeaderElectionRecordAnnotationKey]; ok {\n\t\t\t// when there are multiple controller-manager instances,\n\t\t\t// we observe that it will delete leader-election endpoints after 5min\n\t\t\t// and cause re-election\n\t\t\t// so skip the delete here\n\t\t\t// as leader-election only have endpoints without service\n\t\t\tcontinue\n\t\t}\n\t\tkey, err := controller.KeyFunc(ep)\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"Unable to get key for endpoint %#v\", ep))\n\t\t\tcontinue\n\t\t}\n\t\te.queue.Add(key)\n\t}\n}","line":{"from":552,"to":580}} {"id":100003713,"name":"addEndpointSubset","signature":"func addEndpointSubset(subsets []v1.EndpointSubset, pod *v1.Pod, epa v1.EndpointAddress,","file":"pkg/controller/endpoint/endpoints_controller.go","code":"// addEndpointSubset add the endpoints addresses and ports to the EndpointSubset.\n// The addresses are added to the corresponding field, ready or not ready, depending\n// on the pod status and the Service PublishNotReadyAddresses field value.\n// The pod passed to this function must have already been filtered through ShouldPodBeInEndpoints.\nfunc addEndpointSubset(subsets []v1.EndpointSubset, pod *v1.Pod, epa v1.EndpointAddress,\n\tepp *v1.EndpointPort, tolerateUnreadyEndpoints bool) ([]v1.EndpointSubset, int, int) {\n\tvar readyEps int\n\tvar notReadyEps int\n\tports := []v1.EndpointPort{}\n\tif epp != nil {\n\t\tports = append(ports, *epp)\n\t}\n\tif tolerateUnreadyEndpoints || podutil.IsPodReady(pod) {\n\t\tsubsets = append(subsets, v1.EndpointSubset{\n\t\t\tAddresses: []v1.EndpointAddress{epa},\n\t\t\tPorts: ports,\n\t\t})\n\t\treadyEps++\n\t} else { // if it is not a ready address it has to be not ready\n\t\tklog.V(5).Infof(\"Pod is out of service: %s/%s\", pod.Namespace, pod.Name)\n\t\tsubsets = append(subsets, v1.EndpointSubset{\n\t\t\tNotReadyAddresses: []v1.EndpointAddress{epa},\n\t\t\tPorts: ports,\n\t\t})\n\t\tnotReadyEps++\n\t}\n\treturn subsets, readyEps, notReadyEps\n}","line":{"from":582,"to":609}} {"id":100003714,"name":"endpointPortFromServicePort","signature":"func endpointPortFromServicePort(servicePort *v1.ServicePort, portNum int) *v1.EndpointPort","file":"pkg/controller/endpoint/endpoints_controller.go","code":"func endpointPortFromServicePort(servicePort *v1.ServicePort, portNum int) *v1.EndpointPort {\n\treturn \u0026v1.EndpointPort{\n\t\tName: servicePort.Name,\n\t\tPort: int32(portNum),\n\t\tProtocol: servicePort.Protocol,\n\t\tAppProtocol: servicePort.AppProtocol,\n\t}\n}","line":{"from":611,"to":618}} {"id":100003715,"name":"capacityAnnotationSetCorrectly","signature":"func capacityAnnotationSetCorrectly(annotations map[string]string, subsets []v1.EndpointSubset) bool","file":"pkg/controller/endpoint/endpoints_controller.go","code":"// capacityAnnotationSetCorrectly returns false if number of endpoints is greater than maxCapacity or\n// returns true if underCapacity and the annotation is not set.\nfunc capacityAnnotationSetCorrectly(annotations map[string]string, subsets []v1.EndpointSubset) bool {\n\tnumEndpoints := 0\n\tfor _, subset := range subsets {\n\t\tnumEndpoints += len(subset.Addresses) + len(subset.NotReadyAddresses)\n\t}\n\tif numEndpoints \u003e maxCapacity {\n\t\t// If subsets are over capacity, they must be truncated so consider\n\t\t// the annotation as not set correctly\n\t\treturn false\n\t}\n\t_, ok := annotations[v1.EndpointsOverCapacity]\n\treturn !ok\n}","line":{"from":620,"to":634}} {"id":100003716,"name":"truncateEndpoints","signature":"func truncateEndpoints(endpoints *v1.Endpoints) bool","file":"pkg/controller/endpoint/endpoints_controller.go","code":"// truncateEndpoints by best effort will distribute the endpoints over the subsets based on the proportion\n// of endpoints per subset and will prioritize Ready Endpoints over NotReady Endpoints.\nfunc truncateEndpoints(endpoints *v1.Endpoints) bool {\n\ttotalReady := 0\n\ttotalNotReady := 0\n\tfor _, subset := range endpoints.Subsets {\n\t\ttotalReady += len(subset.Addresses)\n\t\ttotalNotReady += len(subset.NotReadyAddresses)\n\t}\n\n\tif totalReady+totalNotReady \u003c= maxCapacity {\n\t\treturn false\n\t}\n\n\ttruncateReady := false\n\tmax := maxCapacity - totalReady\n\tnumTotal := totalNotReady\n\tif totalReady \u003e maxCapacity {\n\t\ttruncateReady = true\n\t\tmax = maxCapacity\n\t\tnumTotal = totalReady\n\t}\n\tcanBeAdded := max\n\n\tfor i := range endpoints.Subsets {\n\t\tsubset := endpoints.Subsets[i]\n\t\tnumInSubset := len(subset.Addresses)\n\t\tif !truncateReady {\n\t\t\tnumInSubset = len(subset.NotReadyAddresses)\n\t\t}\n\n\t\t// The number of endpoints per subset will be based on the propotion of endpoints\n\t\t// in this subset versus the total number of endpoints. The proportion of endpoints\n\t\t// will be rounded up which most likely will lead to the last subset having less\n\t\t// endpoints than the expected proportion.\n\t\ttoBeAdded := int(math.Ceil((float64(numInSubset) / float64(numTotal)) * float64(max)))\n\t\t// If there is not enough endpoints for the last subset, ensure only the number up\n\t\t// to the capacity are added\n\t\tif toBeAdded \u003e canBeAdded {\n\t\t\ttoBeAdded = canBeAdded\n\t\t}\n\n\t\tif truncateReady {\n\t\t\t// Truncate ready Addresses to allocated proportion and truncate all not ready\n\t\t\t// addresses\n\t\t\tsubset.Addresses = addressSubset(subset.Addresses, toBeAdded)\n\t\t\tsubset.NotReadyAddresses = []v1.EndpointAddress{}\n\t\t\tcanBeAdded -= len(subset.Addresses)\n\t\t} else {\n\t\t\t// Only truncate the not ready addresses\n\t\t\tsubset.NotReadyAddresses = addressSubset(subset.NotReadyAddresses, toBeAdded)\n\t\t\tcanBeAdded -= len(subset.NotReadyAddresses)\n\t\t}\n\t\tendpoints.Subsets[i] = subset\n\t}\n\treturn true\n}","line":{"from":636,"to":692}} {"id":100003717,"name":"addressSubset","signature":"func addressSubset(addresses []v1.EndpointAddress, maxNum int) []v1.EndpointAddress","file":"pkg/controller/endpoint/endpoints_controller.go","code":"// addressSubset takes a list of addresses and returns a subset if the length is greater\n// than the maxNum. If less than the maxNum, the entire list is returned.\nfunc addressSubset(addresses []v1.EndpointAddress, maxNum int) []v1.EndpointAddress {\n\tif len(addresses) \u003c= maxNum {\n\t\treturn addresses\n\t}\n\treturn addresses[0:maxNum]\n}","line":{"from":694,"to":701}} {"id":100003718,"name":"Convert_v1alpha1_EndpointSliceControllerConfiguration_To_config_EndpointSliceControllerConfiguration","signature":"func Convert_v1alpha1_EndpointSliceControllerConfiguration_To_config_EndpointSliceControllerConfiguration(in *v1alpha1.EndpointSliceControllerConfiguration, out *endpointsliceconfig.EndpointSliceControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/endpointslice/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_EndpointSliceControllerConfiguration_To_config_EndpointSliceControllerConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_EndpointSliceControllerConfiguration_To_config_EndpointSliceControllerConfiguration(in *v1alpha1.EndpointSliceControllerConfiguration, out *endpointsliceconfig.EndpointSliceControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_EndpointSliceControllerConfiguration_To_config_EndpointSliceControllerConfiguration(in, out, s)\n}","line":{"from":32,"to":35}} {"id":100003719,"name":"Convert_config_EndpointSliceControllerConfiguration_To_v1alpha1_EndpointSliceControllerConfiguration","signature":"func Convert_config_EndpointSliceControllerConfiguration_To_v1alpha1_EndpointSliceControllerConfiguration(in *endpointsliceconfig.EndpointSliceControllerConfiguration, out *v1alpha1.EndpointSliceControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/endpointslice/config/v1alpha1/conversion.go","code":"// Convert_config_EndpointSliceControllerConfiguration_To_v1alpha1_EndpointSliceControllerConfiguration is an autogenerated conversion function.\nfunc Convert_config_EndpointSliceControllerConfiguration_To_v1alpha1_EndpointSliceControllerConfiguration(in *endpointsliceconfig.EndpointSliceControllerConfiguration, out *v1alpha1.EndpointSliceControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_EndpointSliceControllerConfiguration_To_v1alpha1_EndpointSliceControllerConfiguration(in, out, s)\n}","line":{"from":37,"to":40}} {"id":100003720,"name":"RecommendedDefaultEndpointSliceControllerConfiguration","signature":"func RecommendedDefaultEndpointSliceControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.EndpointSliceControllerConfiguration)","file":"pkg/controller/endpointslice/config/v1alpha1/defaults.go","code":"// RecommendedDefaultEndpointSliceControllerConfiguration defaults a pointer to\n// a EndpointSliceControllerConfiguration struct. This will set the recommended\n// default values, but they may be subject to change between API versions. This\n// function is intentionally not registered in the scheme as a \"normal\"\n// `SetDefaults_Foo` function to allow consumers of this type to set whatever\n// defaults for their embedded configs. Forcing consumers to use these defaults\n// would be problematic as defaulting in the scheme is done as part of the\n// conversion, and there would be no easy way to opt-out. Instead, if you want\n// to use this defaulting method run it in your wrapper struct of this type in\n// its `SetDefaults_` method.\nfunc RecommendedDefaultEndpointSliceControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.EndpointSliceControllerConfiguration) {\n\tif obj.ConcurrentServiceEndpointSyncs == 0 {\n\t\tobj.ConcurrentServiceEndpointSyncs = 5\n\t}\n\n\tif obj.MaxEndpointsPerSlice == 0 {\n\t\tobj.MaxEndpointsPerSlice = 100\n\t}\n}","line":{"from":23,"to":41}} {"id":100003721,"name":"NewController","signature":"func NewController(podInformer coreinformers.PodInformer,","file":"pkg/controller/endpointslice/endpointslice_controller.go","code":"// NewController creates and initializes a new Controller\nfunc NewController(podInformer coreinformers.PodInformer,\n\tserviceInformer coreinformers.ServiceInformer,\n\tnodeInformer coreinformers.NodeInformer,\n\tendpointSliceInformer discoveryinformers.EndpointSliceInformer,\n\tmaxEndpointsPerSlice int32,\n\tclient clientset.Interface,\n\tendpointUpdatesBatchPeriod time.Duration,\n) *Controller {\n\tbroadcaster := record.NewBroadcaster()\n\trecorder := broadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"endpoint-slice-controller\"})\n\n\tendpointslicemetrics.RegisterMetrics()\n\n\tc := \u0026Controller{\n\t\tclient: client,\n\t\t// This is similar to the DefaultControllerRateLimiter, just with a\n\t\t// significantly higher default backoff (1s vs 5ms). This controller\n\t\t// processes events that can require significant EndpointSlice changes,\n\t\t// such as an update to a Service or Deployment. A more significant\n\t\t// rate limit back off here helps ensure that the Controller does not\n\t\t// overwhelm the API Server.\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.NewMaxOfRateLimiter(\n\t\t\tworkqueue.NewItemExponentialFailureRateLimiter(defaultSyncBackOff, maxSyncBackOff),\n\t\t\t// 10 qps, 100 bucket size. This is only for retry speed and its\n\t\t\t// only the overall factor (not per item).\n\t\t\t\u0026workqueue.BucketRateLimiter{Limiter: rate.NewLimiter(rate.Limit(10), 100)},\n\t\t), \"endpoint_slice\"),\n\t\tworkerLoopPeriod: time.Second,\n\t}\n\n\tserviceInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: c.onServiceUpdate,\n\t\tUpdateFunc: func(old, cur interface{}) {\n\t\t\tc.onServiceUpdate(cur)\n\t\t},\n\t\tDeleteFunc: c.onServiceDelete,\n\t})\n\tc.serviceLister = serviceInformer.Lister()\n\tc.servicesSynced = serviceInformer.Informer().HasSynced\n\n\tpodInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: c.addPod,\n\t\tUpdateFunc: c.updatePod,\n\t\tDeleteFunc: c.deletePod,\n\t})\n\tc.podLister = podInformer.Lister()\n\tc.podsSynced = podInformer.Informer().HasSynced\n\n\tc.nodeLister = nodeInformer.Lister()\n\tc.nodesSynced = nodeInformer.Informer().HasSynced\n\n\tendpointSliceInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: c.onEndpointSliceAdd,\n\t\tUpdateFunc: c.onEndpointSliceUpdate,\n\t\tDeleteFunc: c.onEndpointSliceDelete,\n\t})\n\n\tc.endpointSliceLister = endpointSliceInformer.Lister()\n\tc.endpointSlicesSynced = endpointSliceInformer.Informer().HasSynced\n\tc.endpointSliceTracker = endpointsliceutil.NewEndpointSliceTracker()\n\n\tc.maxEndpointsPerSlice = maxEndpointsPerSlice\n\n\tc.triggerTimeTracker = endpointutil.NewTriggerTimeTracker()\n\n\tc.eventBroadcaster = broadcaster\n\tc.eventRecorder = recorder\n\n\tc.endpointUpdatesBatchPeriod = endpointUpdatesBatchPeriod\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.TopologyAwareHints) {\n\t\tnodeInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: c.addNode,\n\t\t\tUpdateFunc: c.updateNode,\n\t\t\tDeleteFunc: c.deleteNode,\n\t\t})\n\n\t\tc.topologyCache = topologycache.NewTopologyCache()\n\t}\n\n\tc.reconciler = \u0026reconciler{\n\t\tclient: c.client,\n\t\tnodeLister: c.nodeLister,\n\t\tmaxEndpointsPerSlice: c.maxEndpointsPerSlice,\n\t\tendpointSliceTracker: c.endpointSliceTracker,\n\t\tmetricsCache: endpointslicemetrics.NewCache(maxEndpointsPerSlice),\n\t\ttopologyCache: c.topologyCache,\n\t\teventRecorder: c.eventRecorder,\n\t}\n\n\treturn c\n}","line":{"from":78,"to":170}} {"id":100003722,"name":"Run","signature":"func (c *Controller) Run(workers int, stopCh \u003c-chan struct{})","file":"pkg/controller/endpointslice/endpointslice_controller.go","code":"// Run will not return until stopCh is closed.\nfunc (c *Controller) Run(workers int, stopCh \u003c-chan struct{}) {\n\tdefer utilruntime.HandleCrash()\n\n\t// Start events processing pipeline.\n\tc.eventBroadcaster.StartLogging(klog.Infof)\n\tc.eventBroadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: c.client.CoreV1().Events(\"\")})\n\tdefer c.eventBroadcaster.Shutdown()\n\n\tdefer c.queue.ShutDown()\n\n\tklog.Infof(\"Starting endpoint slice controller\")\n\tdefer klog.Infof(\"Shutting down endpoint slice controller\")\n\n\tif !cache.WaitForNamedCacheSync(\"endpoint_slice\", stopCh, c.podsSynced, c.servicesSynced, c.endpointSlicesSynced, c.nodesSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.Until(c.worker, c.workerLoopPeriod, stopCh)\n\t}\n\n\t\u003c-stopCh\n}","line":{"from":241,"to":264}} {"id":100003723,"name":"worker","signature":"func (c *Controller) worker()","file":"pkg/controller/endpointslice/endpointslice_controller.go","code":"// worker runs a worker thread that just dequeues items, processes them, and\n// marks them done. You may run as many of these in parallel as you wish; the\n// workqueue guarantees that they will not end up processing the same service\n// at the same time\nfunc (c *Controller) worker() {\n\tfor c.processNextWorkItem() {\n\t}\n}","line":{"from":266,"to":273}} {"id":100003724,"name":"processNextWorkItem","signature":"func (c *Controller) processNextWorkItem() bool","file":"pkg/controller/endpointslice/endpointslice_controller.go","code":"func (c *Controller) processNextWorkItem() bool {\n\tcKey, quit := c.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.queue.Done(cKey)\n\n\terr := c.syncService(cKey.(string))\n\tc.handleErr(err, cKey)\n\n\treturn true\n}","line":{"from":275,"to":286}} {"id":100003725,"name":"handleErr","signature":"func (c *Controller) handleErr(err error, key interface{})","file":"pkg/controller/endpointslice/endpointslice_controller.go","code":"func (c *Controller) handleErr(err error, key interface{}) {\n\ttrackSync(err)\n\n\tif err == nil {\n\t\tc.queue.Forget(key)\n\t\treturn\n\t}\n\n\tif c.queue.NumRequeues(key) \u003c maxRetries {\n\t\tklog.Warningf(\"Error syncing endpoint slices for service %q, retrying. Error: %v\", key, err)\n\t\tc.queue.AddRateLimited(key)\n\t\treturn\n\t}\n\n\tklog.Warningf(\"Retry budget exceeded, dropping service %q out of the queue: %v\", key, err)\n\tc.queue.Forget(key)\n\tutilruntime.HandleError(err)\n}","line":{"from":288,"to":305}} {"id":100003726,"name":"syncService","signature":"func (c *Controller) syncService(key string) error","file":"pkg/controller/endpointslice/endpointslice_controller.go","code":"func (c *Controller) syncService(key string) error {\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tklog.V(4).Infof(\"Finished syncing service %q endpoint slices. (%v)\", key, time.Since(startTime))\n\t}()\n\n\tnamespace, name, err := cache.SplitMetaNamespaceKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tservice, err := c.serviceLister.Services(namespace).Get(name)\n\tif err != nil {\n\t\tif !apierrors.IsNotFound(err) {\n\t\t\treturn err\n\t\t}\n\n\t\tc.triggerTimeTracker.DeleteService(namespace, name)\n\t\tc.reconciler.deleteService(namespace, name)\n\t\tc.endpointSliceTracker.DeleteService(namespace, name)\n\t\t// The service has been deleted, return nil so that it won't be retried.\n\t\treturn nil\n\t}\n\n\tif service.Spec.Type == v1.ServiceTypeExternalName {\n\t\t// services with Type ExternalName receive no endpoints from this controller;\n\t\t// Ref: https://issues.k8s.io/105986\n\t\treturn nil\n\t}\n\n\tif service.Spec.Selector == nil {\n\t\t// services without a selector receive no endpoint slices from this controller;\n\t\t// these services will receive endpoint slices that are created out-of-band via the REST API.\n\t\treturn nil\n\t}\n\n\tklog.V(5).Infof(\"About to update endpoint slices for service %q\", key)\n\n\tpodLabelSelector := labels.Set(service.Spec.Selector).AsSelectorPreValidated()\n\tpods, err := c.podLister.Pods(service.Namespace).List(podLabelSelector)\n\tif err != nil {\n\t\t// Since we're getting stuff from a local cache, it is basically\n\t\t// impossible to get this error.\n\t\tc.eventRecorder.Eventf(service, v1.EventTypeWarning, \"FailedToListPods\",\n\t\t\t\"Error listing Pods for Service %s/%s: %v\", service.Namespace, service.Name, err)\n\t\treturn err\n\t}\n\n\tesLabelSelector := labels.Set(map[string]string{\n\t\tdiscovery.LabelServiceName: service.Name,\n\t\tdiscovery.LabelManagedBy: controllerName,\n\t}).AsSelectorPreValidated()\n\tendpointSlices, err := c.endpointSliceLister.EndpointSlices(service.Namespace).List(esLabelSelector)\n\n\tif err != nil {\n\t\t// Since we're getting stuff from a local cache, it is basically\n\t\t// impossible to get this error.\n\t\tc.eventRecorder.Eventf(service, v1.EventTypeWarning, \"FailedToListEndpointSlices\",\n\t\t\t\"Error listing Endpoint Slices for Service %s/%s: %v\", service.Namespace, service.Name, err)\n\t\treturn err\n\t}\n\n\t// Drop EndpointSlices that have been marked for deletion to prevent the controller from getting stuck.\n\tendpointSlices = dropEndpointSlicesPendingDeletion(endpointSlices)\n\n\tif c.endpointSliceTracker.StaleSlices(service, endpointSlices) {\n\t\treturn endpointsliceutil.NewStaleInformerCache(\"EndpointSlice informer cache is out of date\")\n\t}\n\n\t// We call ComputeEndpointLastChangeTriggerTime here to make sure that the\n\t// state of the trigger time tracker gets updated even if the sync turns out\n\t// to be no-op and we don't update the EndpointSlice objects.\n\tlastChangeTriggerTime := c.triggerTimeTracker.\n\t\tComputeEndpointLastChangeTriggerTime(namespace, service, pods)\n\n\terr = c.reconciler.reconcile(service, pods, endpointSlices, lastChangeTriggerTime)\n\tif err != nil {\n\t\tc.eventRecorder.Eventf(service, v1.EventTypeWarning, \"FailedToUpdateEndpointSlices\",\n\t\t\t\"Error updating Endpoint Slices for Service %s/%s: %v\", service.Namespace, service.Name, err)\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":307,"to":390}} {"id":100003727,"name":"onServiceUpdate","signature":"func (c *Controller) onServiceUpdate(obj interface{})","file":"pkg/controller/endpointslice/endpointslice_controller.go","code":"// onServiceUpdate updates the Service Selector in the cache and queues the Service for processing.\nfunc (c *Controller) onServiceUpdate(obj interface{}) {\n\tkey, err := controller.KeyFunc(obj)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Couldn't get key for object %+v: %v\", obj, err))\n\t\treturn\n\t}\n\n\tc.queue.Add(key)\n}","line":{"from":392,"to":401}} {"id":100003728,"name":"onServiceDelete","signature":"func (c *Controller) onServiceDelete(obj interface{})","file":"pkg/controller/endpointslice/endpointslice_controller.go","code":"// onServiceDelete removes the Service Selector from the cache and queues the Service for processing.\nfunc (c *Controller) onServiceDelete(obj interface{}) {\n\tkey, err := controller.KeyFunc(obj)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Couldn't get key for object %+v: %v\", obj, err))\n\t\treturn\n\t}\n\n\tc.queue.Add(key)\n}","line":{"from":403,"to":412}} {"id":100003729,"name":"onEndpointSliceAdd","signature":"func (c *Controller) onEndpointSliceAdd(obj interface{})","file":"pkg/controller/endpointslice/endpointslice_controller.go","code":"// onEndpointSliceAdd queues a sync for the relevant Service for a sync if the\n// EndpointSlice resource version does not match the expected version in the\n// endpointSliceTracker.\nfunc (c *Controller) onEndpointSliceAdd(obj interface{}) {\n\tendpointSlice := obj.(*discovery.EndpointSlice)\n\tif endpointSlice == nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Invalid EndpointSlice provided to onEndpointSliceAdd()\"))\n\t\treturn\n\t}\n\tif managedByController(endpointSlice) \u0026\u0026 c.endpointSliceTracker.ShouldSync(endpointSlice) {\n\t\tc.queueServiceForEndpointSlice(endpointSlice)\n\t}\n}","line":{"from":414,"to":426}} {"id":100003730,"name":"onEndpointSliceUpdate","signature":"func (c *Controller) onEndpointSliceUpdate(prevObj, obj interface{})","file":"pkg/controller/endpointslice/endpointslice_controller.go","code":"// onEndpointSliceUpdate queues a sync for the relevant Service for a sync if\n// the EndpointSlice resource version does not match the expected version in the\n// endpointSliceTracker or the managed-by value of the EndpointSlice has changed\n// from or to this controller.\nfunc (c *Controller) onEndpointSliceUpdate(prevObj, obj interface{}) {\n\tprevEndpointSlice := prevObj.(*discovery.EndpointSlice)\n\tendpointSlice := obj.(*discovery.EndpointSlice)\n\tif endpointSlice == nil || prevEndpointSlice == nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Invalid EndpointSlice provided to onEndpointSliceUpdate()\"))\n\t\treturn\n\t}\n\t// EndpointSlice generation does not change when labels change. Although the\n\t// controller will never change LabelServiceName, users might. This check\n\t// ensures that we handle changes to this label.\n\tsvcName := endpointSlice.Labels[discovery.LabelServiceName]\n\tprevSvcName := prevEndpointSlice.Labels[discovery.LabelServiceName]\n\tif svcName != prevSvcName {\n\t\tklog.Warningf(\"%s label changed from %s to %s for %s\", discovery.LabelServiceName, prevSvcName, svcName, endpointSlice.Name)\n\t\tc.queueServiceForEndpointSlice(endpointSlice)\n\t\tc.queueServiceForEndpointSlice(prevEndpointSlice)\n\t\treturn\n\t}\n\tif managedByChanged(prevEndpointSlice, endpointSlice) || (managedByController(endpointSlice) \u0026\u0026 c.endpointSliceTracker.ShouldSync(endpointSlice)) {\n\t\tc.queueServiceForEndpointSlice(endpointSlice)\n\t}\n}","line":{"from":428,"to":453}} {"id":100003731,"name":"onEndpointSliceDelete","signature":"func (c *Controller) onEndpointSliceDelete(obj interface{})","file":"pkg/controller/endpointslice/endpointslice_controller.go","code":"// onEndpointSliceDelete queues a sync for the relevant Service for a sync if the\n// EndpointSlice resource version does not match the expected version in the\n// endpointSliceTracker.\nfunc (c *Controller) onEndpointSliceDelete(obj interface{}) {\n\tendpointSlice := getEndpointSliceFromDeleteAction(obj)\n\tif endpointSlice != nil \u0026\u0026 managedByController(endpointSlice) \u0026\u0026 c.endpointSliceTracker.Has(endpointSlice) {\n\t\t// This returns false if we didn't expect the EndpointSlice to be\n\t\t// deleted. If that is the case, we queue the Service for another sync.\n\t\tif !c.endpointSliceTracker.HandleDeletion(endpointSlice) {\n\t\t\tc.queueServiceForEndpointSlice(endpointSlice)\n\t\t}\n\t}\n}","line":{"from":455,"to":467}} {"id":100003732,"name":"queueServiceForEndpointSlice","signature":"func (c *Controller) queueServiceForEndpointSlice(endpointSlice *discovery.EndpointSlice)","file":"pkg/controller/endpointslice/endpointslice_controller.go","code":"// queueServiceForEndpointSlice attempts to queue the corresponding Service for\n// the provided EndpointSlice.\nfunc (c *Controller) queueServiceForEndpointSlice(endpointSlice *discovery.EndpointSlice) {\n\tkey, err := serviceControllerKey(endpointSlice)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Couldn't get key for EndpointSlice %+v: %v\", endpointSlice, err))\n\t\treturn\n\t}\n\n\t// queue after the max of endpointSliceChangeMinSyncDelay and\n\t// endpointUpdatesBatchPeriod.\n\tdelay := endpointSliceChangeMinSyncDelay\n\tif c.endpointUpdatesBatchPeriod \u003e delay {\n\t\tdelay = c.endpointUpdatesBatchPeriod\n\t}\n\tc.queue.AddAfter(key, delay)\n}","line":{"from":469,"to":485}} {"id":100003733,"name":"addPod","signature":"func (c *Controller) addPod(obj interface{})","file":"pkg/controller/endpointslice/endpointslice_controller.go","code":"func (c *Controller) addPod(obj interface{}) {\n\tpod := obj.(*v1.Pod)\n\tservices, err := endpointutil.GetPodServiceMemberships(c.serviceLister, pod)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Unable to get pod %s/%s's service memberships: %v\", pod.Namespace, pod.Name, err))\n\t\treturn\n\t}\n\tfor key := range services {\n\t\tc.queue.AddAfter(key, c.endpointUpdatesBatchPeriod)\n\t}\n}","line":{"from":487,"to":497}} {"id":100003734,"name":"updatePod","signature":"func (c *Controller) updatePod(old, cur interface{})","file":"pkg/controller/endpointslice/endpointslice_controller.go","code":"func (c *Controller) updatePod(old, cur interface{}) {\n\tservices := endpointutil.GetServicesToUpdateOnPodChange(c.serviceLister, old, cur)\n\tfor key := range services {\n\t\tc.queue.AddAfter(key, c.endpointUpdatesBatchPeriod)\n\t}\n}","line":{"from":499,"to":504}} {"id":100003735,"name":"deletePod","signature":"func (c *Controller) deletePod(obj interface{})","file":"pkg/controller/endpointslice/endpointslice_controller.go","code":"// When a pod is deleted, enqueue the services the pod used to be a member of\n// obj could be an *v1.Pod, or a DeletionFinalStateUnknown marker item.\nfunc (c *Controller) deletePod(obj interface{}) {\n\tpod := endpointutil.GetPodFromDeleteAction(obj)\n\tif pod != nil {\n\t\tc.addPod(pod)\n\t}\n}","line":{"from":506,"to":513}} {"id":100003736,"name":"addNode","signature":"func (c *Controller) addNode(obj interface{})","file":"pkg/controller/endpointslice/endpointslice_controller.go","code":"func (c *Controller) addNode(obj interface{}) {\n\tc.checkNodeTopologyDistribution()\n}","line":{"from":515,"to":517}} {"id":100003737,"name":"updateNode","signature":"func (c *Controller) updateNode(old, cur interface{})","file":"pkg/controller/endpointslice/endpointslice_controller.go","code":"func (c *Controller) updateNode(old, cur interface{}) {\n\toldNode := old.(*v1.Node)\n\tcurNode := cur.(*v1.Node)\n\n\tif topologycache.NodeReady(oldNode.Status) != topologycache.NodeReady(curNode.Status) {\n\t\tc.checkNodeTopologyDistribution()\n\t}\n}","line":{"from":519,"to":526}} {"id":100003738,"name":"deleteNode","signature":"func (c *Controller) deleteNode(obj interface{})","file":"pkg/controller/endpointslice/endpointslice_controller.go","code":"func (c *Controller) deleteNode(obj interface{}) {\n\tc.checkNodeTopologyDistribution()\n}","line":{"from":528,"to":530}} {"id":100003739,"name":"checkNodeTopologyDistribution","signature":"func (c *Controller) checkNodeTopologyDistribution()","file":"pkg/controller/endpointslice/endpointslice_controller.go","code":"// checkNodeTopologyDistribution updates Nodes in the topology cache and then\n// queues any Services that are past the threshold.\nfunc (c *Controller) checkNodeTopologyDistribution() {\n\tif c.topologyCache == nil {\n\t\treturn\n\t}\n\tnodes, err := c.nodeLister.List(labels.Everything())\n\tif err != nil {\n\t\tklog.Errorf(\"Error listing Nodes: %v\", err)\n\t\treturn\n\t}\n\tc.topologyCache.SetNodes(nodes)\n\tserviceKeys := c.topologyCache.GetOverloadedServices()\n\tfor _, serviceKey := range serviceKeys {\n\t\tklog.V(2).Infof(\"Queuing %s Service after Node change due to overloading\", serviceKey)\n\t\tc.queue.Add(serviceKey)\n\t}\n}","line":{"from":532,"to":549}} {"id":100003740,"name":"trackSync","signature":"func trackSync(err error)","file":"pkg/controller/endpointslice/endpointslice_controller.go","code":"// trackSync increments the EndpointSliceSyncs metric with the result of a sync.\nfunc trackSync(err error) {\n\tmetricLabel := \"success\"\n\tif err != nil {\n\t\tif endpointsliceutil.IsStaleInformerCacheErr(err) {\n\t\t\tmetricLabel = \"stale\"\n\t\t} else {\n\t\t\tmetricLabel = \"error\"\n\t\t}\n\t}\n\tendpointslicemetrics.EndpointSliceSyncs.WithLabelValues(metricLabel).Inc()\n}","line":{"from":551,"to":562}} {"id":100003741,"name":"dropEndpointSlicesPendingDeletion","signature":"func dropEndpointSlicesPendingDeletion(endpointSlices []*discovery.EndpointSlice) []*discovery.EndpointSlice","file":"pkg/controller/endpointslice/endpointslice_controller.go","code":"func dropEndpointSlicesPendingDeletion(endpointSlices []*discovery.EndpointSlice) []*discovery.EndpointSlice {\n\tn := 0\n\tfor _, endpointSlice := range endpointSlices {\n\t\tif endpointSlice.DeletionTimestamp == nil {\n\t\t\tendpointSlices[n] = endpointSlice\n\t\t\tn++\n\t\t}\n\t}\n\treturn endpointSlices[:n]\n}","line":{"from":564,"to":573}} {"id":100003742,"name":"NewCache","signature":"func NewCache(endpointsPerSlice int32) *Cache","file":"pkg/controller/endpointslice/metrics/cache.go","code":"// NewCache returns a new Cache with the specified endpointsPerSlice.\nfunc NewCache(endpointsPerSlice int32) *Cache {\n\treturn \u0026Cache{\n\t\tmaxEndpointsPerSlice: endpointsPerSlice,\n\t\tcache: map[types.NamespacedName]*ServicePortCache{},\n\t}\n}","line":{"from":27,"to":33}} {"id":100003743,"name":"NewServicePortCache","signature":"func NewServicePortCache() *ServicePortCache","file":"pkg/controller/endpointslice/metrics/cache.go","code":"// NewServicePortCache initializes and returns a new ServicePortCache.\nfunc NewServicePortCache() *ServicePortCache {\n\treturn \u0026ServicePortCache{\n\t\titems: map[endpointutil.PortMapKey]EfficiencyInfo{},\n\t}\n}","line":{"from":72,"to":77}} {"id":100003744,"name":"Set","signature":"func (spc *ServicePortCache) Set(pmKey endpointutil.PortMapKey, eInfo EfficiencyInfo)","file":"pkg/controller/endpointslice/metrics/cache.go","code":"// Set updates the ServicePortCache to contain the provided EfficiencyInfo\n// for the provided PortMapKey.\nfunc (spc *ServicePortCache) Set(pmKey endpointutil.PortMapKey, eInfo EfficiencyInfo) {\n\tspc.items[pmKey] = eInfo\n}","line":{"from":79,"to":83}} {"id":100003745,"name":"totals","signature":"func (spc *ServicePortCache) totals(maxEndpointsPerSlice int) (int, int, int)","file":"pkg/controller/endpointslice/metrics/cache.go","code":"// totals returns the total number of endpoints and slices represented by a\n// ServicePortCache.\nfunc (spc *ServicePortCache) totals(maxEndpointsPerSlice int) (int, int, int) {\n\tvar actualSlices, desiredSlices, endpoints int\n\tfor _, eInfo := range spc.items {\n\t\tendpoints += eInfo.Endpoints\n\t\tactualSlices += eInfo.Slices\n\t\tdesiredSlices += numDesiredSlices(eInfo.Endpoints, maxEndpointsPerSlice)\n\t}\n\t// there is always a placeholder slice\n\tif desiredSlices == 0 {\n\t\tdesiredSlices = 1\n\t}\n\treturn actualSlices, desiredSlices, endpoints\n}","line":{"from":85,"to":99}} {"id":100003746,"name":"UpdateServicePortCache","signature":"func (c *Cache) UpdateServicePortCache(serviceNN types.NamespacedName, spCache *ServicePortCache)","file":"pkg/controller/endpointslice/metrics/cache.go","code":"// UpdateServicePortCache updates a ServicePortCache in the global cache for a\n// given Service and updates the corresponding metrics.\n// Parameters:\n// * serviceNN refers to a NamespacedName representing the Service.\n// * spCache refers to a ServicePortCache for the specified Service.\nfunc (c *Cache) UpdateServicePortCache(serviceNN types.NamespacedName, spCache *ServicePortCache) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tvar prevActualSlices, prevDesiredSlices, prevEndpoints int\n\tif existingSPCache, ok := c.cache[serviceNN]; ok {\n\t\tprevActualSlices, prevDesiredSlices, prevEndpoints = existingSPCache.totals(int(c.maxEndpointsPerSlice))\n\t}\n\n\tcurrActualSlices, currDesiredSlices, currEndpoints := spCache.totals(int(c.maxEndpointsPerSlice))\n\t// To keep numEndpoints up to date, add the difference between the number of\n\t// endpoints in the provided spCache and any spCache it might be replacing.\n\tc.numEndpoints = c.numEndpoints + currEndpoints - prevEndpoints\n\n\tc.numSlicesDesired += currDesiredSlices - prevDesiredSlices\n\tc.numSlicesActual += currActualSlices - prevActualSlices\n\n\tc.cache[serviceNN] = spCache\n\tc.updateMetrics()\n}","line":{"from":101,"to":125}} {"id":100003747,"name":"DeleteService","signature":"func (c *Cache) DeleteService(serviceNN types.NamespacedName)","file":"pkg/controller/endpointslice/metrics/cache.go","code":"// DeleteService removes references of a Service from the global cache and\n// updates the corresponding metrics.\nfunc (c *Cache) DeleteService(serviceNN types.NamespacedName) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tif spCache, ok := c.cache[serviceNN]; ok {\n\t\tactualSlices, desiredSlices, endpoints := spCache.totals(int(c.maxEndpointsPerSlice))\n\t\tc.numEndpoints = c.numEndpoints - endpoints\n\t\tc.numSlicesDesired -= desiredSlices\n\t\tc.numSlicesActual -= actualSlices\n\t\tc.updateMetrics()\n\t\tdelete(c.cache, serviceNN)\n\n\t}\n}","line":{"from":127,"to":142}} {"id":100003748,"name":"updateMetrics","signature":"func (c *Cache) updateMetrics()","file":"pkg/controller/endpointslice/metrics/cache.go","code":"// updateMetrics updates metrics with the values from this Cache.\n// Must be called holding lock.\nfunc (c *Cache) updateMetrics() {\n\tNumEndpointSlices.WithLabelValues().Set(float64(c.numSlicesActual))\n\tDesiredEndpointSlices.WithLabelValues().Set(float64(c.numSlicesDesired))\n\tEndpointsDesired.WithLabelValues().Set(float64(c.numEndpoints))\n}","line":{"from":144,"to":150}} {"id":100003749,"name":"numDesiredSlices","signature":"func numDesiredSlices(numEndpoints, maxEndpointsPerSlice int) int","file":"pkg/controller/endpointslice/metrics/cache.go","code":"// numDesiredSlices calculates the number of EndpointSlices that would exist\n// with ideal endpoint distribution.\nfunc numDesiredSlices(numEndpoints, maxEndpointsPerSlice int) int {\n\tif numEndpoints == 0 {\n\t\treturn 0\n\t}\n\tif numEndpoints \u003c= maxEndpointsPerSlice {\n\t\treturn 1\n\t}\n\treturn int(math.Ceil(float64(numEndpoints) / float64(maxEndpointsPerSlice)))\n}","line":{"from":152,"to":162}} {"id":100003750,"name":"RegisterMetrics","signature":"func RegisterMetrics()","file":"pkg/controller/endpointslice/metrics/metrics.go","code":"// RegisterMetrics registers EndpointSlice metrics.\nfunc RegisterMetrics() {\n\tregisterMetrics.Do(func() {\n\t\tlegacyregistry.MustRegister(EndpointsAddedPerSync)\n\t\tlegacyregistry.MustRegister(EndpointsRemovedPerSync)\n\t\tlegacyregistry.MustRegister(EndpointsDesired)\n\t\tlegacyregistry.MustRegister(NumEndpointSlices)\n\t\tlegacyregistry.MustRegister(DesiredEndpointSlices)\n\t\tlegacyregistry.MustRegister(EndpointSliceChanges)\n\t\tlegacyregistry.MustRegister(EndpointSlicesChangedPerSync)\n\t\tlegacyregistry.MustRegister(EndpointSliceSyncs)\n\t})\n}","line":{"from":123,"to":135}} {"id":100003751,"name":"reconcile","signature":"func (r *reconciler) reconcile(service *corev1.Service, pods []*corev1.Pod, existingSlices []*discovery.EndpointSlice, triggerTime time.Time) error","file":"pkg/controller/endpointslice/reconciler.go","code":"// reconcile takes a set of pods currently matching a service selector and\n// compares them with the endpoints already present in any existing endpoint\n// slices for the given service. It creates, updates, or deletes endpoint slices\n// to ensure the desired set of pods are represented by endpoint slices.\nfunc (r *reconciler) reconcile(service *corev1.Service, pods []*corev1.Pod, existingSlices []*discovery.EndpointSlice, triggerTime time.Time) error {\n\tslicesToDelete := []*discovery.EndpointSlice{} // slices that are no longer matching any address the service has\n\terrs := []error{} // all errors generated in the process of reconciling\n\tslicesByAddressType := make(map[discovery.AddressType][]*discovery.EndpointSlice) // slices by address type\n\n\t// addresses that this service supports [o(1) find]\n\tserviceSupportedAddressesTypes := getAddressTypesForService(service)\n\n\t// loop through slices identifying their address type.\n\t// slices that no longer match address type supported by services\n\t// go to delete, other slices goes to the reconciler machinery\n\t// for further adjustment\n\tfor _, existingSlice := range existingSlices {\n\t\t// service no longer supports that address type, add it to deleted slices\n\t\tif _, ok := serviceSupportedAddressesTypes[existingSlice.AddressType]; !ok {\n\t\t\tif r.topologyCache != nil {\n\t\t\t\tsvcKey, err := serviceControllerKey(existingSlice)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Warningf(\"Couldn't get key to remove EndpointSlice from topology cache %+v: %v\", existingSlice, err)\n\t\t\t\t} else {\n\t\t\t\t\tr.topologyCache.RemoveHints(svcKey, existingSlice.AddressType)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tslicesToDelete = append(slicesToDelete, existingSlice)\n\t\t\tcontinue\n\t\t}\n\n\t\t// add list if it is not on our map\n\t\tif _, ok := slicesByAddressType[existingSlice.AddressType]; !ok {\n\t\t\tslicesByAddressType[existingSlice.AddressType] = make([]*discovery.EndpointSlice, 0, 1)\n\t\t}\n\n\t\tslicesByAddressType[existingSlice.AddressType] = append(slicesByAddressType[existingSlice.AddressType], existingSlice)\n\t}\n\n\t// reconcile for existing.\n\tfor addressType := range serviceSupportedAddressesTypes {\n\t\texistingSlices := slicesByAddressType[addressType]\n\t\terr := r.reconcileByAddressType(service, pods, existingSlices, triggerTime, addressType)\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\t// delete those which are of addressType that is no longer supported\n\t// by the service\n\tfor _, sliceToDelete := range slicesToDelete {\n\t\terr := r.client.DiscoveryV1().EndpointSlices(service.Namespace).Delete(context.TODO(), sliceToDelete.Name, metav1.DeleteOptions{})\n\t\tif err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"error deleting %s EndpointSlice for Service %s/%s: %w\", sliceToDelete.Name, service.Namespace, service.Name, err))\n\t\t} else {\n\t\t\tr.endpointSliceTracker.ExpectDeletion(sliceToDelete)\n\t\t\tmetrics.EndpointSliceChanges.WithLabelValues(\"delete\").Inc()\n\t\t}\n\t}\n\n\treturn utilerrors.NewAggregate(errs)\n}","line":{"from":65,"to":127}} {"id":100003752,"name":"reconcileByAddressType","signature":"func (r *reconciler) reconcileByAddressType(service *corev1.Service, pods []*corev1.Pod, existingSlices []*discovery.EndpointSlice, triggerTime time.Time, addressType discovery.AddressType) error","file":"pkg/controller/endpointslice/reconciler.go","code":"// reconcileByAddressType takes a set of pods currently matching a service selector and\n// compares them with the endpoints already present in any existing endpoint\n// slices (by address type) for the given service. It creates, updates, or deletes endpoint slices\n// to ensure the desired set of pods are represented by endpoint slices.\nfunc (r *reconciler) reconcileByAddressType(service *corev1.Service, pods []*corev1.Pod, existingSlices []*discovery.EndpointSlice, triggerTime time.Time, addressType discovery.AddressType) error {\n\terrs := []error{}\n\n\tslicesToCreate := []*discovery.EndpointSlice{}\n\tslicesToUpdate := []*discovery.EndpointSlice{}\n\tslicesToDelete := []*discovery.EndpointSlice{}\n\tevents := []*topologycache.EventBuilder{}\n\n\t// Build data structures for existing state.\n\texistingSlicesByPortMap := map[endpointutil.PortMapKey][]*discovery.EndpointSlice{}\n\tfor _, existingSlice := range existingSlices {\n\t\tif ownedBy(existingSlice, service) {\n\t\t\tepHash := endpointutil.NewPortMapKey(existingSlice.Ports)\n\t\t\texistingSlicesByPortMap[epHash] = append(existingSlicesByPortMap[epHash], existingSlice)\n\t\t} else {\n\t\t\tslicesToDelete = append(slicesToDelete, existingSlice)\n\t\t}\n\t}\n\n\t// Build data structures for desired state.\n\tdesiredMetaByPortMap := map[endpointutil.PortMapKey]*endpointMeta{}\n\tdesiredEndpointsByPortMap := map[endpointutil.PortMapKey]endpointsliceutil.EndpointSet{}\n\n\tfor _, pod := range pods {\n\t\tif !endpointutil.ShouldPodBeInEndpoints(pod, true) {\n\t\t\tcontinue\n\t\t}\n\n\t\tendpointPorts := getEndpointPorts(service, pod)\n\t\tepHash := endpointutil.NewPortMapKey(endpointPorts)\n\t\tif _, ok := desiredEndpointsByPortMap[epHash]; !ok {\n\t\t\tdesiredEndpointsByPortMap[epHash] = endpointsliceutil.EndpointSet{}\n\t\t}\n\n\t\tif _, ok := desiredMetaByPortMap[epHash]; !ok {\n\t\t\tdesiredMetaByPortMap[epHash] = \u0026endpointMeta{\n\t\t\t\tAddressType: addressType,\n\t\t\t\tPorts: endpointPorts,\n\t\t\t}\n\t\t}\n\n\t\tnode, err := r.nodeLister.Get(pod.Spec.NodeName)\n\t\tif err != nil {\n\t\t\t// we are getting the information from the local informer,\n\t\t\t// an error different than IsNotFound should not happen\n\t\t\tif !errors.IsNotFound(err) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// If the Node specified by the Pod doesn't exist we want to requeue the Service so we\n\t\t\t// retry later, but also update the EndpointSlice without the problematic Pod.\n\t\t\t// Theoretically, the pod Garbage Collector will remove the Pod, but we want to avoid\n\t\t\t// situations where a reference from a Pod to a missing node can leave the EndpointSlice\n\t\t\t// stuck forever.\n\t\t\t// On the other side, if the service.Spec.PublishNotReadyAddresses is set we just add the\n\t\t\t// Pod, since the user is explicitly indicating that the Pod address should be published.\n\t\t\tif !service.Spec.PublishNotReadyAddresses {\n\t\t\t\tklog.Warningf(\"skipping Pod %s for Service %s/%s: Node %s Not Found\", pod.Name, service.Namespace, service.Name, pod.Spec.NodeName)\n\t\t\t\terrs = append(errs, fmt.Errorf(\"skipping Pod %s for Service %s/%s: Node %s Not Found\", pod.Name, service.Namespace, service.Name, pod.Spec.NodeName))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tendpoint := podToEndpoint(pod, node, service, addressType)\n\t\tif len(endpoint.Addresses) \u003e 0 {\n\t\t\tdesiredEndpointsByPortMap[epHash].Insert(\u0026endpoint)\n\t\t}\n\t}\n\n\tspMetrics := metrics.NewServicePortCache()\n\ttotalAdded := 0\n\ttotalRemoved := 0\n\n\t// Determine changes necessary for each group of slices by port map.\n\tfor portMap, desiredEndpoints := range desiredEndpointsByPortMap {\n\t\tnumEndpoints := len(desiredEndpoints)\n\t\tpmSlicesToCreate, pmSlicesToUpdate, pmSlicesToDelete, added, removed := r.reconcileByPortMapping(\n\t\t\tservice, existingSlicesByPortMap[portMap], desiredEndpoints, desiredMetaByPortMap[portMap])\n\n\t\ttotalAdded += added\n\t\ttotalRemoved += removed\n\n\t\tspMetrics.Set(portMap, metrics.EfficiencyInfo{\n\t\t\tEndpoints: numEndpoints,\n\t\t\tSlices: len(existingSlicesByPortMap[portMap]) + len(pmSlicesToCreate) - len(pmSlicesToDelete),\n\t\t})\n\n\t\tslicesToCreate = append(slicesToCreate, pmSlicesToCreate...)\n\t\tslicesToUpdate = append(slicesToUpdate, pmSlicesToUpdate...)\n\t\tslicesToDelete = append(slicesToDelete, pmSlicesToDelete...)\n\t}\n\n\t// If there are unique sets of ports that are no longer desired, mark\n\t// the corresponding endpoint slices for deletion.\n\tfor portMap, existingSlices := range existingSlicesByPortMap {\n\t\tif _, ok := desiredEndpointsByPortMap[portMap]; !ok {\n\t\t\tslicesToDelete = append(slicesToDelete, existingSlices...)\n\t\t}\n\t}\n\n\t// When no endpoint slices would usually exist, we need to add a placeholder.\n\tif len(existingSlices) == len(slicesToDelete) \u0026\u0026 len(slicesToCreate) \u003c 1 {\n\t\t// Check for existing placeholder slice outside of the core control flow\n\t\tplaceholderSlice := newEndpointSlice(service, \u0026endpointMeta{Ports: []discovery.EndpointPort{}, AddressType: addressType})\n\t\tif len(slicesToDelete) == 1 \u0026\u0026 placeholderSliceCompare.DeepEqual(slicesToDelete[0], placeholderSlice) {\n\t\t\t// We are about to unnecessarily delete/recreate the placeholder, remove it now.\n\t\t\tslicesToDelete = slicesToDelete[:0]\n\t\t} else {\n\t\t\tslicesToCreate = append(slicesToCreate, placeholderSlice)\n\t\t}\n\t\tspMetrics.Set(endpointutil.NewPortMapKey(placeholderSlice.Ports), metrics.EfficiencyInfo{\n\t\t\tEndpoints: 0,\n\t\t\tSlices: 1,\n\t\t})\n\t}\n\n\tmetrics.EndpointsAddedPerSync.WithLabelValues().Observe(float64(totalAdded))\n\tmetrics.EndpointsRemovedPerSync.WithLabelValues().Observe(float64(totalRemoved))\n\n\tserviceNN := types.NamespacedName{Name: service.Name, Namespace: service.Namespace}\n\tr.metricsCache.UpdateServicePortCache(serviceNN, spMetrics)\n\n\t// Topology hints are assigned per address type. This means it is\n\t// theoretically possible for endpoints of one address type to be assigned\n\t// hints while another endpoints of another address type are not.\n\tsi := \u0026topologycache.SliceInfo{\n\t\tServiceKey: fmt.Sprintf(\"%s/%s\", service.Namespace, service.Name),\n\t\tAddressType: addressType,\n\t\tToCreate: slicesToCreate,\n\t\tToUpdate: slicesToUpdate,\n\t\tUnchanged: unchangedSlices(existingSlices, slicesToUpdate, slicesToDelete),\n\t}\n\n\tif r.topologyCache != nil \u0026\u0026 hintsEnabled(service.Annotations) {\n\t\tslicesToCreate, slicesToUpdate, events = r.topologyCache.AddHints(si)\n\t} else {\n\t\tif r.topologyCache != nil {\n\t\t\tif r.topologyCache.HasPopulatedHints(si.ServiceKey) {\n\t\t\t\tklog.InfoS(\"TopologyAwareHints annotation has changed, removing hints\", \"serviceKey\", si.ServiceKey, \"addressType\", si.AddressType)\n\t\t\t\tevents = append(events, \u0026topologycache.EventBuilder{\n\t\t\t\t\tEventType: corev1.EventTypeWarning,\n\t\t\t\t\tReason: \"TopologyAwareHintsDisabled\",\n\t\t\t\t\tMessage: topologycache.FormatWithAddressType(topologycache.TopologyAwareHintsDisabled, si.AddressType),\n\t\t\t\t})\n\t\t\t}\n\t\t\tr.topologyCache.RemoveHints(si.ServiceKey, addressType)\n\t\t}\n\t\tslicesToCreate, slicesToUpdate = topologycache.RemoveHintsFromSlices(si)\n\t}\n\terr := r.finalize(service, slicesToCreate, slicesToUpdate, slicesToDelete, triggerTime)\n\tif err != nil {\n\t\terrs = append(errs, err)\n\t}\n\tfor _, event := range events {\n\t\tr.eventRecorder.Event(service, event.EventType, event.Reason, event.Message)\n\t}\n\treturn utilerrors.NewAggregate(errs)\n\n}","line":{"from":129,"to":289}} {"id":100003753,"name":"finalize","signature":"func (r *reconciler) finalize(","file":"pkg/controller/endpointslice/reconciler.go","code":"// finalize creates, updates, and deletes slices as specified\nfunc (r *reconciler) finalize(\n\tservice *corev1.Service,\n\tslicesToCreate,\n\tslicesToUpdate,\n\tslicesToDelete []*discovery.EndpointSlice,\n\ttriggerTime time.Time,\n) error {\n\t// If there are slices to create and delete, change the creates to updates\n\t// of the slices that would otherwise be deleted.\n\tfor i := 0; i \u003c len(slicesToDelete); {\n\t\tif len(slicesToCreate) == 0 {\n\t\t\tbreak\n\t\t}\n\t\tsliceToDelete := slicesToDelete[i]\n\t\tslice := slicesToCreate[len(slicesToCreate)-1]\n\t\t// Only update EndpointSlices that are owned by this Service and have\n\t\t// the same AddressType. We need to avoid updating EndpointSlices that\n\t\t// are being garbage collected for an old Service with the same name.\n\t\t// The AddressType field is immutable. Since Services also consider\n\t\t// IPFamily immutable, the only case where this should matter will be\n\t\t// the migration from IP to IPv4 and IPv6 AddressTypes, where there's a\n\t\t// chance EndpointSlices with an IP AddressType would otherwise be\n\t\t// updated to IPv4 or IPv6 without this check.\n\t\tif sliceToDelete.AddressType == slice.AddressType \u0026\u0026 ownedBy(sliceToDelete, service) {\n\t\t\tslice.Name = sliceToDelete.Name\n\t\t\tslicesToCreate = slicesToCreate[:len(slicesToCreate)-1]\n\t\t\tslicesToUpdate = append(slicesToUpdate, slice)\n\t\t\tslicesToDelete = append(slicesToDelete[:i], slicesToDelete[i+1:]...)\n\t\t} else {\n\t\t\ti++\n\t\t}\n\t}\n\n\t// Don't create new EndpointSlices if the Service is pending deletion. This\n\t// is to avoid a potential race condition with the garbage collector where\n\t// it tries to delete EndpointSlices as this controller replaces them.\n\tif service.DeletionTimestamp == nil {\n\t\tfor _, endpointSlice := range slicesToCreate {\n\t\t\taddTriggerTimeAnnotation(endpointSlice, triggerTime)\n\t\t\tcreatedSlice, err := r.client.DiscoveryV1().EndpointSlices(service.Namespace).Create(context.TODO(), endpointSlice, metav1.CreateOptions{})\n\t\t\tif err != nil {\n\t\t\t\t// If the namespace is terminating, creates will continue to fail. Simply drop the item.\n\t\t\t\tif errors.HasStatusCause(err, corev1.NamespaceTerminatingCause) {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn fmt.Errorf(\"failed to create EndpointSlice for Service %s/%s: %v\", service.Namespace, service.Name, err)\n\t\t\t}\n\t\t\tr.endpointSliceTracker.Update(createdSlice)\n\t\t\tmetrics.EndpointSliceChanges.WithLabelValues(\"create\").Inc()\n\t\t}\n\t}\n\n\tfor _, endpointSlice := range slicesToUpdate {\n\t\taddTriggerTimeAnnotation(endpointSlice, triggerTime)\n\t\tupdatedSlice, err := r.client.DiscoveryV1().EndpointSlices(service.Namespace).Update(context.TODO(), endpointSlice, metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to update %s EndpointSlice for Service %s/%s: %v\", endpointSlice.Name, service.Namespace, service.Name, err)\n\t\t}\n\t\tr.endpointSliceTracker.Update(updatedSlice)\n\t\tmetrics.EndpointSliceChanges.WithLabelValues(\"update\").Inc()\n\t}\n\n\tfor _, endpointSlice := range slicesToDelete {\n\t\terr := r.client.DiscoveryV1().EndpointSlices(service.Namespace).Delete(context.TODO(), endpointSlice.Name, metav1.DeleteOptions{})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to delete %s EndpointSlice for Service %s/%s: %v\", endpointSlice.Name, service.Namespace, service.Name, err)\n\t\t}\n\t\tr.endpointSliceTracker.ExpectDeletion(endpointSlice)\n\t\tmetrics.EndpointSliceChanges.WithLabelValues(\"delete\").Inc()\n\t}\n\n\ttopologyLabel := \"Disabled\"\n\tif r.topologyCache != nil \u0026\u0026 hintsEnabled(service.Annotations) {\n\t\ttopologyLabel = \"Auto\"\n\t}\n\n\tnumSlicesChanged := len(slicesToCreate) + len(slicesToUpdate) + len(slicesToDelete)\n\tmetrics.EndpointSlicesChangedPerSync.WithLabelValues(topologyLabel).Observe(float64(numSlicesChanged))\n\n\treturn nil\n}","line":{"from":315,"to":396}} {"id":100003754,"name":"reconcileByPortMapping","signature":"func (r *reconciler) reconcileByPortMapping(","file":"pkg/controller/endpointslice/reconciler.go","code":"// reconcileByPortMapping compares the endpoints found in existing slices with\n// the list of desired endpoints and returns lists of slices to create, update,\n// and delete. It also checks that the slices mirror the parent services labels.\n// The logic is split up into several main steps:\n// 1. Iterate through existing slices, delete endpoints that are no longer\n// desired and update matching endpoints that have changed. It also checks\n// if the slices have the labels of the parent services, and updates them if not.\n// 2. Iterate through slices that have been modified in 1 and fill them up with\n// any remaining desired endpoints.\n// 3. If there still desired endpoints left, try to fit them into a previously\n// unchanged slice and/or create new ones.\nfunc (r *reconciler) reconcileByPortMapping(\n\tservice *corev1.Service,\n\texistingSlices []*discovery.EndpointSlice,\n\tdesiredSet endpointsliceutil.EndpointSet,\n\tendpointMeta *endpointMeta,\n) ([]*discovery.EndpointSlice, []*discovery.EndpointSlice, []*discovery.EndpointSlice, int, int) {\n\tslicesByName := map[string]*discovery.EndpointSlice{}\n\tsliceNamesUnchanged := sets.String{}\n\tsliceNamesToUpdate := sets.String{}\n\tsliceNamesToDelete := sets.String{}\n\tnumRemoved := 0\n\n\t// 1. Iterate through existing slices to delete endpoints no longer desired\n\t// and update endpoints that have changed\n\tfor _, existingSlice := range existingSlices {\n\t\tslicesByName[existingSlice.Name] = existingSlice\n\t\tnewEndpoints := []discovery.Endpoint{}\n\t\tendpointUpdated := false\n\t\tfor _, endpoint := range existingSlice.Endpoints {\n\t\t\tgot := desiredSet.Get(\u0026endpoint)\n\t\t\t// If endpoint is desired add it to list of endpoints to keep.\n\t\t\tif got != nil {\n\t\t\t\tnewEndpoints = append(newEndpoints, *got)\n\t\t\t\t// If existing version of endpoint doesn't match desired version\n\t\t\t\t// set endpointUpdated to ensure endpoint changes are persisted.\n\t\t\t\tif !endpointutil.EndpointsEqualBeyondHash(got, \u0026endpoint) {\n\t\t\t\t\tendpointUpdated = true\n\t\t\t\t}\n\t\t\t\t// once an endpoint has been placed/found in a slice, it no\n\t\t\t\t// longer needs to be handled\n\t\t\t\tdesiredSet.Delete(\u0026endpoint)\n\t\t\t}\n\t\t}\n\n\t\t// generate the slice labels and check if parent labels have changed\n\t\tlabels, labelsChanged := setEndpointSliceLabels(existingSlice, service)\n\n\t\t// If an endpoint was updated or removed, mark for update or delete\n\t\tif endpointUpdated || len(existingSlice.Endpoints) != len(newEndpoints) {\n\t\t\tif len(existingSlice.Endpoints) \u003e len(newEndpoints) {\n\t\t\t\tnumRemoved += len(existingSlice.Endpoints) - len(newEndpoints)\n\t\t\t}\n\t\t\tif len(newEndpoints) == 0 {\n\t\t\t\t// if no endpoints desired in this slice, mark for deletion\n\t\t\t\tsliceNamesToDelete.Insert(existingSlice.Name)\n\t\t\t} else {\n\t\t\t\t// otherwise, copy and mark for update\n\t\t\t\tepSlice := existingSlice.DeepCopy()\n\t\t\t\tepSlice.Endpoints = newEndpoints\n\t\t\t\tepSlice.Labels = labels\n\t\t\t\tslicesByName[existingSlice.Name] = epSlice\n\t\t\t\tsliceNamesToUpdate.Insert(epSlice.Name)\n\t\t\t}\n\t\t} else if labelsChanged {\n\t\t\t// if labels have changed, copy and mark for update\n\t\t\tepSlice := existingSlice.DeepCopy()\n\t\t\tepSlice.Labels = labels\n\t\t\tslicesByName[existingSlice.Name] = epSlice\n\t\t\tsliceNamesToUpdate.Insert(epSlice.Name)\n\t\t} else {\n\t\t\t// slices with no changes will be useful if there are leftover endpoints\n\t\t\tsliceNamesUnchanged.Insert(existingSlice.Name)\n\t\t}\n\t}\n\n\tnumAdded := desiredSet.Len()\n\n\t// 2. If we still have desired endpoints to add and slices marked for update,\n\t// iterate through the slices and fill them up with the desired endpoints.\n\tif desiredSet.Len() \u003e 0 \u0026\u0026 sliceNamesToUpdate.Len() \u003e 0 {\n\t\tslices := []*discovery.EndpointSlice{}\n\t\tfor _, sliceName := range sliceNamesToUpdate.UnsortedList() {\n\t\t\tslices = append(slices, slicesByName[sliceName])\n\t\t}\n\t\t// Sort endpoint slices by length so we're filling up the fullest ones\n\t\t// first.\n\t\tsort.Sort(endpointSliceEndpointLen(slices))\n\n\t\t// Iterate through slices and fill them up with desired endpoints.\n\t\tfor _, slice := range slices {\n\t\t\tfor desiredSet.Len() \u003e 0 \u0026\u0026 len(slice.Endpoints) \u003c int(r.maxEndpointsPerSlice) {\n\t\t\t\tendpoint, _ := desiredSet.PopAny()\n\t\t\t\tslice.Endpoints = append(slice.Endpoints, *endpoint)\n\t\t\t}\n\t\t}\n\t}\n\n\t// 3. If there are still desired endpoints left at this point, we try to fit\n\t// the endpoints in a single existing slice. If there are no slices with\n\t// that capacity, we create new slices for the endpoints.\n\tslicesToCreate := []*discovery.EndpointSlice{}\n\n\tfor desiredSet.Len() \u003e 0 {\n\t\tvar sliceToFill *discovery.EndpointSlice\n\n\t\t// If the remaining amounts of endpoints is smaller than the max\n\t\t// endpoints per slice and we have slices that haven't already been\n\t\t// filled, try to fit them in one.\n\t\tif desiredSet.Len() \u003c int(r.maxEndpointsPerSlice) \u0026\u0026 sliceNamesUnchanged.Len() \u003e 0 {\n\t\t\tunchangedSlices := []*discovery.EndpointSlice{}\n\t\t\tfor _, sliceName := range sliceNamesUnchanged.UnsortedList() {\n\t\t\t\tunchangedSlices = append(unchangedSlices, slicesByName[sliceName])\n\t\t\t}\n\t\t\tsliceToFill = getSliceToFill(unchangedSlices, desiredSet.Len(), int(r.maxEndpointsPerSlice))\n\t\t}\n\n\t\t// If we didn't find a sliceToFill, generate a new empty one.\n\t\tif sliceToFill == nil {\n\t\t\tsliceToFill = newEndpointSlice(service, endpointMeta)\n\t\t} else {\n\t\t\t// deep copy required to modify this slice.\n\t\t\tsliceToFill = sliceToFill.DeepCopy()\n\t\t\tslicesByName[sliceToFill.Name] = sliceToFill\n\t\t}\n\n\t\t// Fill the slice up with remaining endpoints.\n\t\tfor desiredSet.Len() \u003e 0 \u0026\u0026 len(sliceToFill.Endpoints) \u003c int(r.maxEndpointsPerSlice) {\n\t\t\tendpoint, _ := desiredSet.PopAny()\n\t\t\tsliceToFill.Endpoints = append(sliceToFill.Endpoints, *endpoint)\n\t\t}\n\n\t\t// New slices will not have a Name set, use this to determine whether\n\t\t// this should be an update or create.\n\t\tif sliceToFill.Name != \"\" {\n\t\t\tsliceNamesToUpdate.Insert(sliceToFill.Name)\n\t\t\tsliceNamesUnchanged.Delete(sliceToFill.Name)\n\t\t} else {\n\t\t\tslicesToCreate = append(slicesToCreate, sliceToFill)\n\t\t}\n\t}\n\n\t// Build slicesToUpdate from slice names.\n\tslicesToUpdate := []*discovery.EndpointSlice{}\n\tfor _, sliceName := range sliceNamesToUpdate.UnsortedList() {\n\t\tslicesToUpdate = append(slicesToUpdate, slicesByName[sliceName])\n\t}\n\n\t// Build slicesToDelete from slice names.\n\tslicesToDelete := []*discovery.EndpointSlice{}\n\tfor _, sliceName := range sliceNamesToDelete.UnsortedList() {\n\t\tslicesToDelete = append(slicesToDelete, slicesByName[sliceName])\n\t}\n\n\treturn slicesToCreate, slicesToUpdate, slicesToDelete, numAdded, numRemoved\n}","line":{"from":398,"to":553}} {"id":100003755,"name":"deleteService","signature":"func (r *reconciler) deleteService(namespace, name string)","file":"pkg/controller/endpointslice/reconciler.go","code":"func (r *reconciler) deleteService(namespace, name string) {\n\tr.metricsCache.DeleteService(types.NamespacedName{Namespace: namespace, Name: name})\n}","line":{"from":555,"to":557}} {"id":100003756,"name":"getTotalReadyEndpoints","signature":"func (si *SliceInfo) getTotalReadyEndpoints() int","file":"pkg/controller/endpointslice/topologycache/sliceinfo.go","code":"func (si *SliceInfo) getTotalReadyEndpoints() int {\n\ttotalEndpoints := 0\n\tfor _, slice := range si.ToCreate {\n\t\ttotalEndpoints += numReadyEndpoints(slice.Endpoints)\n\t}\n\tfor _, slice := range si.ToUpdate {\n\t\ttotalEndpoints += numReadyEndpoints(slice.Endpoints)\n\t}\n\tfor _, slice := range si.Unchanged {\n\t\ttotalEndpoints += numReadyEndpoints(slice.Endpoints)\n\t}\n\treturn totalEndpoints\n}","line":{"from":33,"to":45}} {"id":100003757,"name":"getAllocatedHintsByZone","signature":"func (si *SliceInfo) getAllocatedHintsByZone(allocations map[string]Allocation) EndpointZoneInfo","file":"pkg/controller/endpointslice/topologycache/sliceinfo.go","code":"// getAllocatedHintsByZone sums up the allocated hints we currently have in\n// unchanged slices and marks slices for update as necessary. A slice needs to\n// be updated if any of the following are true:\n// - It has an endpoint without zone hints\n// - It has an endpoint hint for a zone that no longer needs any\n// - It has endpoint hints that would make the minimum allocations necessary\n// impossible with changes to slices that are already being updated or\n// created.\nfunc (si *SliceInfo) getAllocatedHintsByZone(allocations map[string]Allocation) EndpointZoneInfo {\n\tallocatedHintsByZone := EndpointZoneInfo{}\n\n\t// Using filtering in place to remove any endpoints that are no longer\n\t// unchanged (https://github.com/golang/go/wiki/SliceTricks#filter-in-place)\n\tj := 0\n\tfor _, slice := range si.Unchanged {\n\t\thintsByZone := getHintsByZone(slice, allocatedHintsByZone, allocations)\n\t\tif hintsByZone == nil {\n\t\t\tsi.ToUpdate = append(si.ToUpdate, slice.DeepCopy())\n\t\t} else {\n\t\t\tsi.Unchanged[j] = slice\n\t\t\tj++\n\t\t\tfor zone, numHints := range hintsByZone {\n\t\t\t\tallocatedHintsByZone[zone] += numHints\n\t\t\t}\n\t\t}\n\t}\n\n\tsi.Unchanged = si.Unchanged[:j]\n\treturn allocatedHintsByZone\n}","line":{"from":47,"to":76}} {"id":100003758,"name":"NewTopologyCache","signature":"func NewTopologyCache() *TopologyCache","file":"pkg/controller/endpointslice/topologycache/topologycache.go","code":"// NewTopologyCache initializes a new TopologyCache.\nfunc NewTopologyCache() *TopologyCache {\n\treturn \u0026TopologyCache{\n\t\tcpuByZone: map[string]*resource.Quantity{},\n\t\tcpuRatiosByZone: map[string]float64{},\n\t\tendpointsByService: map[string]map[discovery.AddressType]EndpointZoneInfo{},\n\t\thintsPopulatedByService: sets.Set[string]{},\n\t}\n}","line":{"from":60,"to":68}} {"id":100003759,"name":"GetOverloadedServices","signature":"func (t *TopologyCache) GetOverloadedServices() []string","file":"pkg/controller/endpointslice/topologycache/topologycache.go","code":"// GetOverloadedServices returns a list of Service keys that refer to Services\n// that have crossed the overload threshold for any zone.\nfunc (t *TopologyCache) GetOverloadedServices() []string {\n\tt.lock.Lock()\n\tdefer t.lock.Unlock()\n\n\tsvcKeys := []string{}\n\tfor svcKey, eziByAddrType := range t.endpointsByService {\n\t\tfor _, ezi := range eziByAddrType {\n\t\t\tif serviceOverloaded(ezi, t.cpuRatiosByZone) {\n\t\t\t\tsvcKeys = append(svcKeys, svcKey)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn svcKeys\n}","line":{"from":70,"to":87}} {"id":100003760,"name":"AddHints","signature":"func (t *TopologyCache) AddHints(si *SliceInfo) ([]*discovery.EndpointSlice, []*discovery.EndpointSlice, []*EventBuilder)","file":"pkg/controller/endpointslice/topologycache/topologycache.go","code":"// AddHints adds or updates topology hints on EndpointSlices and returns updated\n// lists of EndpointSlices to create and update.\nfunc (t *TopologyCache) AddHints(si *SliceInfo) ([]*discovery.EndpointSlice, []*discovery.EndpointSlice, []*EventBuilder) {\n\ttotalEndpoints := si.getTotalReadyEndpoints()\n\tallocations, allocationsEvent := t.getAllocations(totalEndpoints)\n\tevents := []*EventBuilder{}\n\tif allocationsEvent != nil {\n\t\tklog.InfoS(allocationsEvent.Message+\", removing hints\", \"serviceKey\", si.ServiceKey, \"addressType\", si.AddressType)\n\t\tallocationsEvent.Message = FormatWithAddressType(allocationsEvent.Message, si.AddressType)\n\t\tevents = append(events, allocationsEvent)\n\t\tt.RemoveHints(si.ServiceKey, si.AddressType)\n\t\tslicesToCreate, slicesToUpdate := RemoveHintsFromSlices(si)\n\t\treturn slicesToCreate, slicesToUpdate, events\n\t}\n\n\tallocatedHintsByZone := si.getAllocatedHintsByZone(allocations)\n\n\tallocatableSlices := si.ToCreate\n\tfor _, slice := range si.ToUpdate {\n\t\tallocatableSlices = append(allocatableSlices, slice)\n\t}\n\n\t// step 1: assign same-zone hints for all endpoints as a starting point.\n\tfor _, slice := range allocatableSlices {\n\t\tfor i, endpoint := range slice.Endpoints {\n\t\t\tif !endpointsliceutil.EndpointReady(endpoint) {\n\t\t\t\tendpoint.Hints = nil\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif endpoint.Zone == nil || *endpoint.Zone == \"\" {\n\t\t\t\tklog.InfoS(\"Endpoint found without zone specified, removing hints\", \"serviceKey\", si.ServiceKey, \"addressType\", si.AddressType)\n\t\t\t\tevents = append(events, \u0026EventBuilder{\n\t\t\t\t\tEventType: v1.EventTypeWarning,\n\t\t\t\t\tReason: \"TopologyAwareHintsDisabled\",\n\t\t\t\t\tMessage: FormatWithAddressType(NoZoneSpecified, si.AddressType),\n\t\t\t\t})\n\t\t\t\tt.RemoveHints(si.ServiceKey, si.AddressType)\n\t\t\t\tslicesToCreate, slicesToUpdate := RemoveHintsFromSlices(si)\n\t\t\t\treturn slicesToCreate, slicesToUpdate, events\n\t\t\t}\n\n\t\t\tallocatedHintsByZone[*endpoint.Zone]++\n\t\t\tslice.Endpoints[i].Hints = \u0026discovery.EndpointHints{ForZones: []discovery.ForZone{{Name: *endpoint.Zone}}}\n\t\t}\n\t}\n\n\t// step 2. Identify which zones need to donate slices and which need more.\n\tgivingZones, receivingZones := getGivingAndReceivingZones(allocations, allocatedHintsByZone)\n\n\t// step 3. Redistribute endpoints based on data from step 2.\n\tredistributions := redistributeHints(allocatableSlices, givingZones, receivingZones)\n\n\tfor zone, diff := range redistributions {\n\t\tallocatedHintsByZone[zone] += diff\n\t}\n\n\tif len(allocatedHintsByZone) == 0 {\n\t\tklog.V(2).InfoS(\"No hints allocated for zones, removing them\", \"serviceKey\", si.ServiceKey, \"addressType\", si.AddressType)\n\t\tevents = append(events, \u0026EventBuilder{\n\t\t\tEventType: v1.EventTypeWarning,\n\t\t\tReason: \"TopologyAwareHintsDisabled\",\n\t\t\tMessage: FormatWithAddressType(NoAllocatedHintsForZones, si.AddressType),\n\t\t})\n\t\tt.RemoveHints(si.ServiceKey, si.AddressType)\n\t\tslicesToCreate, slicesToUpdate := RemoveHintsFromSlices(si)\n\t\treturn slicesToCreate, slicesToUpdate, events\n\t}\n\n\thintsEnabled := t.hintsPopulatedByService.Has(si.ServiceKey)\n\tt.SetHints(si.ServiceKey, si.AddressType, allocatedHintsByZone)\n\n\t// if hints were not enabled before, we publish an event to indicate we enabled them.\n\tif !hintsEnabled {\n\t\tklog.InfoS(\"Topology Aware Hints has been enabled, adding hints.\", \"serviceKey\", si.ServiceKey, \"addressType\", si.AddressType)\n\t\tevents = append(events, \u0026EventBuilder{\n\t\t\tEventType: v1.EventTypeNormal,\n\t\t\tReason: \"TopologyAwareHintsEnabled\",\n\t\t\tMessage: FormatWithAddressType(TopologyAwareHintsEnabled, si.AddressType),\n\t\t})\n\t}\n\treturn si.ToCreate, si.ToUpdate, events\n}","line":{"from":89,"to":170}} {"id":100003761,"name":"SetHints","signature":"func (t *TopologyCache) SetHints(serviceKey string, addrType discovery.AddressType, allocatedHintsByZone EndpointZoneInfo)","file":"pkg/controller/endpointslice/topologycache/topologycache.go","code":"// SetHints sets topology hints for the provided serviceKey and addrType in this\n// cache.\nfunc (t *TopologyCache) SetHints(serviceKey string, addrType discovery.AddressType, allocatedHintsByZone EndpointZoneInfo) {\n\tt.lock.Lock()\n\tdefer t.lock.Unlock()\n\n\t_, ok := t.endpointsByService[serviceKey]\n\tif !ok {\n\t\tt.endpointsByService[serviceKey] = map[discovery.AddressType]EndpointZoneInfo{}\n\t}\n\tt.endpointsByService[serviceKey][addrType] = allocatedHintsByZone\n\n\tt.hintsPopulatedByService.Insert(serviceKey)\n}","line":{"from":172,"to":185}} {"id":100003762,"name":"RemoveHints","signature":"func (t *TopologyCache) RemoveHints(serviceKey string, addrType discovery.AddressType)","file":"pkg/controller/endpointslice/topologycache/topologycache.go","code":"// RemoveHints removes topology hints for the provided serviceKey and addrType\n// from this cache.\nfunc (t *TopologyCache) RemoveHints(serviceKey string, addrType discovery.AddressType) {\n\tt.lock.Lock()\n\tdefer t.lock.Unlock()\n\n\t_, ok := t.endpointsByService[serviceKey]\n\tif ok {\n\t\tdelete(t.endpointsByService[serviceKey], addrType)\n\t}\n\tif len(t.endpointsByService[serviceKey]) == 0 {\n\t\tdelete(t.endpointsByService, serviceKey)\n\t}\n\tt.hintsPopulatedByService.Delete(serviceKey)\n}","line":{"from":187,"to":201}} {"id":100003763,"name":"SetNodes","signature":"func (t *TopologyCache) SetNodes(nodes []*v1.Node)","file":"pkg/controller/endpointslice/topologycache/topologycache.go","code":"// SetNodes updates the Node distribution for the TopologyCache.\nfunc (t *TopologyCache) SetNodes(nodes []*v1.Node) {\n\tcpuByZone := map[string]*resource.Quantity{}\n\tsufficientNodeInfo := true\n\n\ttotalCPU := resource.Quantity{}\n\n\tfor _, node := range nodes {\n\t\tif hasExcludedLabels(node.Labels) {\n\t\t\tklog.V(2).Infof(\"Ignoring node %s because it has an excluded label\", node.Name)\n\t\t\tcontinue\n\t\t}\n\t\tif !NodeReady(node.Status) {\n\t\t\tklog.V(2).Infof(\"Ignoring node %s because it is not ready: %v\", node.Name, node.Status.Conditions)\n\t\t\tcontinue\n\t\t}\n\n\t\tnodeCPU := node.Status.Allocatable.Cpu()\n\t\tzone, ok := node.Labels[v1.LabelTopologyZone]\n\n\t\t// TODO(robscott): Figure out if there's an acceptable proportion of\n\t\t// nodes with inadequate information. The current logic means that as\n\t\t// soon as we find any node without a zone or allocatable CPU specified,\n\t\t// we bail out entirely. Bailing out at this level will make our cluster\n\t\t// wide ratios nil, which would result in slices for all Services having\n\t\t// their hints removed.\n\t\tif !ok || zone == \"\" || nodeCPU.IsZero() {\n\t\t\tcpuByZone = map[string]*resource.Quantity{}\n\t\t\tsufficientNodeInfo = false\n\t\t\tklog.Warningf(\"Can't get CPU or zone information for %s node\", node.Name)\n\t\t\tbreak\n\t\t}\n\n\t\ttotalCPU.Add(*nodeCPU)\n\t\tif _, ok = cpuByZone[zone]; !ok {\n\t\t\tcpuByZone[zone] = nodeCPU\n\t\t} else {\n\t\t\tcpuByZone[zone].Add(*nodeCPU)\n\t\t}\n\t}\n\n\tt.lock.Lock()\n\tdefer t.lock.Unlock()\n\n\tif totalCPU.IsZero() || !sufficientNodeInfo || len(cpuByZone) \u003c 2 {\n\t\tklog.V(2).Infof(\"Insufficient node info for topology hints (%d zones, %s CPU, %t)\", len(cpuByZone), totalCPU.String(), sufficientNodeInfo)\n\t\tt.sufficientNodeInfo = false\n\t\tt.cpuByZone = nil\n\t\tt.cpuRatiosByZone = nil\n\n\t} else {\n\t\tt.sufficientNodeInfo = sufficientNodeInfo\n\t\tt.cpuByZone = cpuByZone\n\n\t\tt.cpuRatiosByZone = map[string]float64{}\n\t\tfor zone, cpu := range cpuByZone {\n\t\t\tt.cpuRatiosByZone[zone] = float64(cpu.MilliValue()) / float64(totalCPU.MilliValue())\n\t\t}\n\t}\n}","line":{"from":203,"to":262}} {"id":100003764,"name":"HasPopulatedHints","signature":"func (t *TopologyCache) HasPopulatedHints(serviceKey string) bool","file":"pkg/controller/endpointslice/topologycache/topologycache.go","code":"// HasPopulatedHints checks whether there are populated hints for a given service in the cache.\nfunc (t *TopologyCache) HasPopulatedHints(serviceKey string) bool {\n\treturn t.hintsPopulatedByService.Has(serviceKey)\n}","line":{"from":264,"to":267}} {"id":100003765,"name":"getAllocations","signature":"func (t *TopologyCache) getAllocations(numEndpoints int) (map[string]Allocation, *EventBuilder)","file":"pkg/controller/endpointslice/topologycache/topologycache.go","code":"// getAllocations returns a set of minimum and maximum allocations per zone. If\n// it is not possible to provide allocations that are below the overload\n// threshold, a nil value will be returned.\nfunc (t *TopologyCache) getAllocations(numEndpoints int) (map[string]Allocation, *EventBuilder) {\n\t// it is similar to checking !t.sufficientNodeInfo\n\tif t.cpuRatiosByZone == nil {\n\t\treturn nil, \u0026EventBuilder{\n\t\t\tEventType: v1.EventTypeWarning,\n\t\t\tReason: \"TopologyAwareHintsDisabled\",\n\t\t\tMessage: InsufficientNodeInfo,\n\t\t}\n\t}\n\tif len(t.cpuRatiosByZone) \u003c 2 {\n\t\treturn nil, \u0026EventBuilder{\n\t\t\tEventType: v1.EventTypeWarning,\n\t\t\tReason: \"TopologyAwareHintsDisabled\",\n\t\t\tMessage: NodesReadyInOneZoneOnly,\n\t\t}\n\t}\n\tif len(t.cpuRatiosByZone) \u003e numEndpoints {\n\t\treturn nil, \u0026EventBuilder{\n\t\t\tEventType: v1.EventTypeWarning,\n\t\t\tReason: \"TopologyAwareHintsDisabled\",\n\t\t\tMessage: fmt.Sprintf(\"%s (%d endpoints, %d zones)\", InsufficientNumberOfEndpoints, numEndpoints, len(t.cpuRatiosByZone)),\n\t\t}\n\t}\n\n\tt.lock.Lock()\n\tdefer t.lock.Unlock()\n\n\tremainingMinEndpoints := numEndpoints\n\tminTotal := 0\n\tallocations := map[string]Allocation{}\n\n\tfor zone, ratio := range t.cpuRatiosByZone {\n\t\tdesired := ratio * float64(numEndpoints)\n\t\tminimum := int(math.Ceil(desired * (1 / (1 + OverloadThreshold))))\n\t\tallocations[zone] = Allocation{\n\t\t\tMinimum: minimum,\n\t\t\tDesired: math.Max(desired, float64(minimum)),\n\t\t}\n\t\tminTotal += minimum\n\t\tremainingMinEndpoints -= minimum\n\t\tif remainingMinEndpoints \u003c 0 {\n\t\t\treturn nil, \u0026EventBuilder{\n\t\t\t\tEventType: v1.EventTypeWarning,\n\t\t\t\tReason: \"TopologyAwareHintsDisabled\",\n\t\t\t\tMessage: fmt.Sprintf(\"%s (%d endpoints, %d zones)\", MinAllocationExceedsOverloadThreshold, numEndpoints, len(t.cpuRatiosByZone)),\n\t\t\t}\n\t\t}\n\t}\n\n\tfor zone, allocation := range allocations {\n\t\tallocation.Maximum = allocation.Minimum + numEndpoints - minTotal\n\t\tallocations[zone] = allocation\n\t}\n\n\treturn allocations, nil\n}","line":{"from":269,"to":327}} {"id":100003766,"name":"hasExcludedLabels","signature":"func hasExcludedLabels(labels map[string]string) bool","file":"pkg/controller/endpointslice/topologycache/topologycache.go","code":"// Nodes with any of these labels set to any value will be excluded from\n// topology capacity calculations.\nfunc hasExcludedLabels(labels map[string]string) bool {\n\tif len(labels) == 0 {\n\t\treturn false\n\t}\n\tif _, ok := labels[\"node-role.kubernetes.io/control-plane\"]; ok {\n\t\treturn true\n\t}\n\tif _, ok := labels[\"node-role.kubernetes.io/master\"]; ok {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":329,"to":342}} {"id":100003767,"name":"RemoveHintsFromSlices","signature":"func RemoveHintsFromSlices(si *SliceInfo) ([]*discovery.EndpointSlice, []*discovery.EndpointSlice)","file":"pkg/controller/endpointslice/topologycache/utils.go","code":"// RemoveHintsFromSlices removes topology hints on EndpointSlices and returns\n// updated lists of EndpointSlices to create and update.\nfunc RemoveHintsFromSlices(si *SliceInfo) ([]*discovery.EndpointSlice, []*discovery.EndpointSlice) {\n\t// Remove hints on all EndpointSlices we were already going to change.\n\tslices := append(si.ToCreate, si.ToUpdate...)\n\tfor _, slice := range slices {\n\t\tfor i := range slice.Endpoints {\n\t\t\tslice.Endpoints[i].Hints = nil\n\t\t}\n\t}\n\n\t// Remove hints on all unchanged EndpointSlices and mark them for update\n\t// if any already had hints. We use j to track the number/index of slices\n\t// that are still unchanged.\n\tj := 0\n\tfor _, slice := range si.Unchanged {\n\t\tchanged := false\n\t\tfor i, endpoint := range slice.Endpoints {\n\t\t\tif endpoint.Hints != nil {\n\t\t\t\t// Unchanged slices are still direct copies from informer cache.\n\t\t\t\t// Need to deep copy before we make any modifications to avoid\n\t\t\t\t// accidentally changing informer cache.\n\t\t\t\tslice = slice.DeepCopy()\n\t\t\t\tslice.Endpoints[i].Hints = nil\n\t\t\t\tchanged = true\n\t\t\t}\n\t\t}\n\t\tif changed {\n\t\t\tsi.ToUpdate = append(si.ToUpdate, slice)\n\t\t} else {\n\t\t\tsi.Unchanged[j] = slice\n\t\t\tj++\n\t\t}\n\t}\n\n\t// truncate si.Unchanged so it only includes slices that are still\n\t// unchanged.\n\tsi.Unchanged = si.Unchanged[:j]\n\n\treturn si.ToCreate, si.ToUpdate\n}","line":{"from":29,"to":69}} {"id":100003768,"name":"FormatWithAddressType","signature":"func FormatWithAddressType(s string, addressType discovery.AddressType) string","file":"pkg/controller/endpointslice/topologycache/utils.go","code":"// FormatWithAddressType foramts a given string by adding an addressType to the end of it.\nfunc FormatWithAddressType(s string, addressType discovery.AddressType) string {\n\treturn fmt.Sprintf(\"%s, addressType: %s\", s, addressType)\n}","line":{"from":71,"to":74}} {"id":100003769,"name":"redistributeHints","signature":"func redistributeHints(slices []*discovery.EndpointSlice, givingZones, receivingZones map[string]int) map[string]int","file":"pkg/controller/endpointslice/topologycache/utils.go","code":"// redistributeHints redistributes hints based in the provided EndpointSlices.\n// It allocates endpoints from the provided givingZones to the provided\n// receivingZones. This returns a map that represents the changes in allocated\n// endpoints by zone.\nfunc redistributeHints(slices []*discovery.EndpointSlice, givingZones, receivingZones map[string]int) map[string]int {\n\tredistributions := map[string]int{}\n\n\tfor _, slice := range slices {\n\t\tfor i, endpoint := range slice.Endpoints {\n\t\t\tif !endpointsliceutil.EndpointReady(endpoint) {\n\t\t\t\tendpoint.Hints = nil\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(givingZones) == 0 || len(receivingZones) == 0 {\n\t\t\t\treturn redistributions\n\t\t\t}\n\t\t\tif endpoint.Zone == nil || *endpoint.Zone == \"\" {\n\t\t\t\t// This should always be caught earlier in AddHints()\n\t\t\t\tklog.Warningf(\"Endpoint found without zone specified\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tgivingZone := *endpoint.Zone\n\t\t\tnumToGive, ok := givingZones[givingZone]\n\t\t\tif ok \u0026\u0026 numToGive \u003e 0 {\n\t\t\t\tfor receivingZone, numToReceive := range receivingZones {\n\t\t\t\t\tif numToReceive \u003e 0 {\n\t\t\t\t\t\tslice.Endpoints[i].Hints = \u0026discovery.EndpointHints{ForZones: []discovery.ForZone{{Name: receivingZone}}}\n\t\t\t\t\t\tif numToGive == 1 {\n\t\t\t\t\t\t\tdelete(givingZones, givingZone)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tgivingZones[givingZone]--\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif numToReceive == 1 {\n\t\t\t\t\t\t\tdelete(receivingZones, receivingZone)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treceivingZones[receivingZone]--\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tredistributions[receivingZone]++\n\t\t\t\t\t\tredistributions[givingZone]--\n\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn redistributions\n}","line":{"from":76,"to":125}} {"id":100003770,"name":"getGivingAndReceivingZones","signature":"func getGivingAndReceivingZones(allocations map[string]Allocation, allocatedHintsByZone map[string]int) (map[string]int, map[string]int)","file":"pkg/controller/endpointslice/topologycache/utils.go","code":"// getGivingAndReceivingZones returns the number of endpoints each zone should\n// give to other zones along with the number of endpoints each zone should\n// receive from other zones. This is calculated with the provided allocations\n// (desired state) and allocatedHintsByZone (current state).\nfunc getGivingAndReceivingZones(allocations map[string]Allocation, allocatedHintsByZone map[string]int) (map[string]int, map[string]int) {\n\t// 1. Determine the precise number of additional endpoints each zone has\n\t// (giving) or needs (receiving).\n\tgivingZonesDesired := map[string]float64{}\n\treceivingZonesDesired := map[string]float64{}\n\n\tfor zone, allocation := range allocations {\n\t\tallocatedHints, _ := allocatedHintsByZone[zone]\n\t\ttarget := allocation.Desired\n\t\tif float64(allocatedHints) \u003e target {\n\t\t\tgivingZonesDesired[zone] = float64(allocatedHints) - target\n\t\t} else if float64(allocatedHints) \u003c target {\n\t\t\treceivingZonesDesired[zone] = target - float64(allocatedHints)\n\t\t}\n\t}\n\n\t// 2. Convert the precise numbers needed into ints representing real\n\t// endpoints given from one zone to another.\n\tgivingZones := map[string]int{}\n\treceivingZones := map[string]int{}\n\n\tfor {\n\t\tgivingZone, numToGive := getMost(givingZonesDesired)\n\t\treceivingZone, numToReceive := getMost(receivingZonesDesired)\n\n\t\t// return early if any of the following are true:\n\t\t// - giving OR receiving zone are unspecified\n\t\t// - giving AND receiving zones have less than 1 endpoint left to give or receive\n\t\t// - giving OR receiving zones have less than 0.5 endpoints left to give or receive\n\t\tif givingZone == \"\" || receivingZone == \"\" || (numToGive \u003c 1.0 \u0026\u0026 numToReceive \u003c 1.0) || numToGive \u003c 0.5 || numToReceive \u003c 0.5 {\n\t\t\tbreak\n\t\t}\n\n\t\tgivingZones[givingZone]++\n\t\tgivingZonesDesired[givingZone]--\n\t\treceivingZones[receivingZone]++\n\t\treceivingZonesDesired[receivingZone]--\n\t}\n\n\treturn givingZones, receivingZones\n}","line":{"from":127,"to":171}} {"id":100003771,"name":"getMost","signature":"func getMost(zones map[string]float64) (string, float64)","file":"pkg/controller/endpointslice/topologycache/utils.go","code":"// getMost accepts a map[string]float64 and returns the string and float64 that\n// represent the greatest value in this provided map. This function is not very\n// efficient but it is expected that len() will rarely be greater than 2.\nfunc getMost(zones map[string]float64) (string, float64) {\n\tzone := \"\"\n\tnum := 0.0\n\tfor z, n := range zones {\n\t\tif n \u003e num {\n\t\t\tzone = z\n\t\t\tnum = n\n\t\t}\n\t}\n\n\treturn zone, num\n}","line":{"from":173,"to":187}} {"id":100003772,"name":"getHintsByZone","signature":"func getHintsByZone(slice *discovery.EndpointSlice, allocatedHintsByZone EndpointZoneInfo, allocations map[string]Allocation) map[string]int","file":"pkg/controller/endpointslice/topologycache/utils.go","code":"// getHintsByZone returns the number of hints allocated to each zone by the\n// provided EndpointSlice. This function returns nil to indicate that the\n// current allocations are invalid and that the EndpointSlice needs to be\n// updated. This could be caused by:\n// - A hint for a zone that no longer requires any allocations.\n// - An endpoint with no hints.\n// - Hints that would make minimum allocations impossible.\nfunc getHintsByZone(slice *discovery.EndpointSlice, allocatedHintsByZone EndpointZoneInfo, allocations map[string]Allocation) map[string]int {\n\thintsByZone := map[string]int{}\n\tfor _, endpoint := range slice.Endpoints {\n\t\tif !endpointsliceutil.EndpointReady(endpoint) {\n\t\t\tcontinue\n\t\t}\n\t\tif endpoint.Hints == nil || len(endpoint.Hints.ForZones) == 0 {\n\t\t\treturn nil\n\t\t}\n\n\t\tfor i := range endpoint.Hints.ForZones {\n\t\t\tzone := endpoint.Hints.ForZones[i].Name\n\t\t\tif _, ok := allocations[zone]; !ok {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\thintsByZone[zone]++\n\t\t}\n\t}\n\n\tfor zone, numHints := range hintsByZone {\n\t\talreadyAllocated, _ := allocatedHintsByZone[zone]\n\t\tallocation, ok := allocations[zone]\n\t\tif !ok || (numHints+alreadyAllocated) \u003e allocation.Maximum {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn hintsByZone\n}","line":{"from":189,"to":224}} {"id":100003773,"name":"serviceOverloaded","signature":"func serviceOverloaded(ezi EndpointZoneInfo, zoneRatios map[string]float64) bool","file":"pkg/controller/endpointslice/topologycache/utils.go","code":"// serviceOverloaded returns true if the Service has an insufficient amount of\n// endpoints for any zone.\nfunc serviceOverloaded(ezi EndpointZoneInfo, zoneRatios map[string]float64) bool {\n\tif len(ezi) == 0 {\n\t\treturn false\n\t}\n\tif len(zoneRatios) == 0 {\n\t\treturn true\n\t}\n\n\ttotalEndpoints := 0.0\n\tfor _, numEndpoints := range ezi {\n\t\ttotalEndpoints += float64(numEndpoints)\n\t}\n\n\tfor zone, ratio := range zoneRatios {\n\t\tsvcEndpoints, ok := ezi[zone]\n\t\tif !ok {\n\t\t\treturn true\n\t\t}\n\t\tminEndpoints := math.Ceil(totalEndpoints * ratio * (1 / (1 + OverloadThreshold)))\n\t\tif svcEndpoints \u003c int(minEndpoints) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":226,"to":253}} {"id":100003774,"name":"NodeReady","signature":"func NodeReady(nodeStatus v1.NodeStatus) bool","file":"pkg/controller/endpointslice/topologycache/utils.go","code":"// NodeReady returns true if the Node has a status condition of type \"NodeReady\"\n// with a status of \"True\".\nfunc NodeReady(nodeStatus v1.NodeStatus) bool {\n\tfor _, cond := range nodeStatus.Conditions {\n\t\tif cond.Type == v1.NodeReady {\n\t\t\treturn cond.Status == v1.ConditionTrue\n\t\t}\n\t}\n\treturn false\n}","line":{"from":255,"to":264}} {"id":100003775,"name":"numReadyEndpoints","signature":"func numReadyEndpoints(endpoints []discovery.Endpoint) int","file":"pkg/controller/endpointslice/topologycache/utils.go","code":"// numReadyEndpoints returns the number of Endpoints that are ready from the\n// specified list.\nfunc numReadyEndpoints(endpoints []discovery.Endpoint) int {\n\tvar total int\n\tfor _, ep := range endpoints {\n\t\tif ep.Conditions.Ready != nil \u0026\u0026 *ep.Conditions.Ready {\n\t\t\ttotal++\n\t\t}\n\t}\n\treturn total\n}","line":{"from":266,"to":276}} {"id":100003776,"name":"podToEndpoint","signature":"func podToEndpoint(pod *v1.Pod, node *v1.Node, service *v1.Service, addressType discovery.AddressType) discovery.Endpoint","file":"pkg/controller/endpointslice/utils.go","code":"// podToEndpoint returns an Endpoint object generated from a Pod, a Node, and a Service for a particular addressType.\nfunc podToEndpoint(pod *v1.Pod, node *v1.Node, service *v1.Service, addressType discovery.AddressType) discovery.Endpoint {\n\tserving := podutil.IsPodReady(pod)\n\tterminating := pod.DeletionTimestamp != nil\n\t// For compatibility reasons, \"ready\" should never be \"true\" if a pod is terminatng, unless\n\t// publishNotReadyAddresses was set.\n\tready := service.Spec.PublishNotReadyAddresses || (serving \u0026\u0026 !terminating)\n\tep := discovery.Endpoint{\n\t\tAddresses: getEndpointAddresses(pod.Status, service, addressType),\n\t\tConditions: discovery.EndpointConditions{\n\t\t\tReady: \u0026ready,\n\t\t\tServing: \u0026serving,\n\t\t\tTerminating: \u0026terminating,\n\t\t},\n\t\tTargetRef: \u0026v1.ObjectReference{\n\t\t\tKind: \"Pod\",\n\t\t\tNamespace: pod.ObjectMeta.Namespace,\n\t\t\tName: pod.ObjectMeta.Name,\n\t\t\tUID: pod.ObjectMeta.UID,\n\t\t},\n\t}\n\n\tif pod.Spec.NodeName != \"\" {\n\t\tep.NodeName = \u0026pod.Spec.NodeName\n\t}\n\n\tif node != nil \u0026\u0026 node.Labels[v1.LabelTopologyZone] != \"\" {\n\t\tzone := node.Labels[v1.LabelTopologyZone]\n\t\tep.Zone = \u0026zone\n\t}\n\n\tif endpointutil.ShouldSetHostname(pod, service) {\n\t\tep.Hostname = \u0026pod.Spec.Hostname\n\t}\n\n\treturn ep\n}","line":{"from":40,"to":76}} {"id":100003777,"name":"getEndpointPorts","signature":"func getEndpointPorts(service *v1.Service, pod *v1.Pod) []discovery.EndpointPort","file":"pkg/controller/endpointslice/utils.go","code":"// getEndpointPorts returns a list of EndpointPorts generated from a Service\n// and Pod.\nfunc getEndpointPorts(service *v1.Service, pod *v1.Pod) []discovery.EndpointPort {\n\tendpointPorts := []discovery.EndpointPort{}\n\n\t// Allow headless service not to have ports.\n\tif len(service.Spec.Ports) == 0 \u0026\u0026 service.Spec.ClusterIP == api.ClusterIPNone {\n\t\treturn endpointPorts\n\t}\n\n\tfor i := range service.Spec.Ports {\n\t\tservicePort := \u0026service.Spec.Ports[i]\n\n\t\tportName := servicePort.Name\n\t\tportProto := servicePort.Protocol\n\t\tportNum, err := podutil.FindPort(pod, servicePort)\n\t\tif err != nil {\n\t\t\tklog.V(4).Infof(\"Failed to find port for service %s/%s: %v\", service.Namespace, service.Name, err)\n\t\t\tcontinue\n\t\t}\n\n\t\ti32PortNum := int32(portNum)\n\t\tendpointPorts = append(endpointPorts, discovery.EndpointPort{\n\t\t\tName: \u0026portName,\n\t\t\tPort: \u0026i32PortNum,\n\t\t\tProtocol: \u0026portProto,\n\t\t\tAppProtocol: servicePort.AppProtocol,\n\t\t})\n\t}\n\n\treturn endpointPorts\n}","line":{"from":78,"to":109}} {"id":100003778,"name":"getEndpointAddresses","signature":"func getEndpointAddresses(podStatus v1.PodStatus, service *v1.Service, addressType discovery.AddressType) []string","file":"pkg/controller/endpointslice/utils.go","code":"// getEndpointAddresses returns a list of addresses generated from a pod status.\nfunc getEndpointAddresses(podStatus v1.PodStatus, service *v1.Service, addressType discovery.AddressType) []string {\n\taddresses := []string{}\n\n\tfor _, podIP := range podStatus.PodIPs {\n\t\tisIPv6PodIP := utilnet.IsIPv6String(podIP.IP)\n\t\tif isIPv6PodIP \u0026\u0026 addressType == discovery.AddressTypeIPv6 {\n\t\t\taddresses = append(addresses, podIP.IP)\n\t\t}\n\n\t\tif !isIPv6PodIP \u0026\u0026 addressType == discovery.AddressTypeIPv4 {\n\t\t\taddresses = append(addresses, podIP.IP)\n\t\t}\n\t}\n\n\treturn addresses\n}","line":{"from":111,"to":127}} {"id":100003779,"name":"newEndpointSlice","signature":"func newEndpointSlice(service *v1.Service, endpointMeta *endpointMeta) *discovery.EndpointSlice","file":"pkg/controller/endpointslice/utils.go","code":"// newEndpointSlice returns an EndpointSlice generated from a service and\n// endpointMeta.\nfunc newEndpointSlice(service *v1.Service, endpointMeta *endpointMeta) *discovery.EndpointSlice {\n\tgvk := schema.GroupVersionKind{Version: \"v1\", Kind: \"Service\"}\n\townerRef := metav1.NewControllerRef(service, gvk)\n\tepSlice := \u0026discovery.EndpointSlice{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tLabels: map[string]string{},\n\t\t\tGenerateName: getEndpointSlicePrefix(service.Name),\n\t\t\tOwnerReferences: []metav1.OwnerReference{*ownerRef},\n\t\t\tNamespace: service.Namespace,\n\t\t},\n\t\tPorts: endpointMeta.Ports,\n\t\tAddressType: endpointMeta.AddressType,\n\t\tEndpoints: []discovery.Endpoint{},\n\t}\n\t// add parent service labels\n\tepSlice.Labels, _ = setEndpointSliceLabels(epSlice, service)\n\n\treturn epSlice\n}","line":{"from":129,"to":149}} {"id":100003780,"name":"getEndpointSlicePrefix","signature":"func getEndpointSlicePrefix(serviceName string) string","file":"pkg/controller/endpointslice/utils.go","code":"// getEndpointSlicePrefix returns a suitable prefix for an EndpointSlice name.\nfunc getEndpointSlicePrefix(serviceName string) string {\n\t// use the dash (if the name isn't too long) to make the pod name a bit prettier\n\tprefix := fmt.Sprintf(\"%s-\", serviceName)\n\tif len(validation.ValidateEndpointSliceName(prefix, true)) != 0 {\n\t\tprefix = serviceName\n\t}\n\treturn prefix\n}","line":{"from":151,"to":159}} {"id":100003781,"name":"ownedBy","signature":"func ownedBy(endpointSlice *discovery.EndpointSlice, svc *v1.Service) bool","file":"pkg/controller/endpointslice/utils.go","code":"// ownedBy returns true if the provided EndpointSlice is owned by the provided\n// Service.\nfunc ownedBy(endpointSlice *discovery.EndpointSlice, svc *v1.Service) bool {\n\tfor _, o := range endpointSlice.OwnerReferences {\n\t\tif o.UID == svc.UID \u0026\u0026 o.Kind == \"Service\" \u0026\u0026 o.APIVersion == \"v1\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":161,"to":170}} {"id":100003782,"name":"getSliceToFill","signature":"func getSliceToFill(endpointSlices []*discovery.EndpointSlice, numEndpoints, maxEndpoints int) (slice *discovery.EndpointSlice)","file":"pkg/controller/endpointslice/utils.go","code":"// getSliceToFill will return the EndpointSlice that will be closest to full\n// when numEndpoints are added. If no EndpointSlice can be found, a nil pointer\n// will be returned.\nfunc getSliceToFill(endpointSlices []*discovery.EndpointSlice, numEndpoints, maxEndpoints int) (slice *discovery.EndpointSlice) {\n\tclosestDiff := maxEndpoints\n\tvar closestSlice *discovery.EndpointSlice\n\tfor _, endpointSlice := range endpointSlices {\n\t\tcurrentDiff := maxEndpoints - (numEndpoints + len(endpointSlice.Endpoints))\n\t\tif currentDiff \u003e= 0 \u0026\u0026 currentDiff \u003c closestDiff {\n\t\t\tclosestDiff = currentDiff\n\t\t\tclosestSlice = endpointSlice\n\t\t\tif closestDiff == 0 {\n\t\t\t\treturn closestSlice\n\t\t\t}\n\t\t}\n\t}\n\treturn closestSlice\n}","line":{"from":172,"to":189}} {"id":100003783,"name":"getEndpointSliceFromDeleteAction","signature":"func getEndpointSliceFromDeleteAction(obj interface{}) *discovery.EndpointSlice","file":"pkg/controller/endpointslice/utils.go","code":"// getEndpointSliceFromDeleteAction parses an EndpointSlice from a delete action.\nfunc getEndpointSliceFromDeleteAction(obj interface{}) *discovery.EndpointSlice {\n\tif endpointSlice, ok := obj.(*discovery.EndpointSlice); ok {\n\t\t// Enqueue all the services that the pod used to be a member of.\n\t\t// This is the same thing we do when we add a pod.\n\t\treturn endpointSlice\n\t}\n\t// If we reached here it means the pod was deleted but its final state is unrecorded.\n\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Couldn't get object from tombstone %#v\", obj))\n\t\treturn nil\n\t}\n\tendpointSlice, ok := tombstone.Obj.(*discovery.EndpointSlice)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Tombstone contained object that is not a EndpointSlice: %#v\", obj))\n\t\treturn nil\n\t}\n\treturn endpointSlice\n}","line":{"from":191,"to":210}} {"id":100003784,"name":"addTriggerTimeAnnotation","signature":"func addTriggerTimeAnnotation(endpointSlice *discovery.EndpointSlice, triggerTime time.Time)","file":"pkg/controller/endpointslice/utils.go","code":"// addTriggerTimeAnnotation adds a triggerTime annotation to an EndpointSlice\nfunc addTriggerTimeAnnotation(endpointSlice *discovery.EndpointSlice, triggerTime time.Time) {\n\tif endpointSlice.Annotations == nil {\n\t\tendpointSlice.Annotations = make(map[string]string)\n\t}\n\n\tif !triggerTime.IsZero() {\n\t\tendpointSlice.Annotations[v1.EndpointsLastChangeTriggerTime] = triggerTime.UTC().Format(time.RFC3339Nano)\n\t} else { // No new trigger time, clear the annotation.\n\t\tdelete(endpointSlice.Annotations, v1.EndpointsLastChangeTriggerTime)\n\t}\n}","line":{"from":212,"to":223}} {"id":100003785,"name":"serviceControllerKey","signature":"func serviceControllerKey(endpointSlice *discovery.EndpointSlice) (string, error)","file":"pkg/controller/endpointslice/utils.go","code":"// serviceControllerKey returns a controller key for a Service but derived from\n// an EndpointSlice.\nfunc serviceControllerKey(endpointSlice *discovery.EndpointSlice) (string, error) {\n\tif endpointSlice == nil {\n\t\treturn \"\", fmt.Errorf(\"nil EndpointSlice passed to serviceControllerKey()\")\n\t}\n\tserviceName, ok := endpointSlice.Labels[discovery.LabelServiceName]\n\tif !ok || serviceName == \"\" {\n\t\treturn \"\", fmt.Errorf(\"EndpointSlice missing %s label\", discovery.LabelServiceName)\n\t}\n\treturn fmt.Sprintf(\"%s/%s\", endpointSlice.Namespace, serviceName), nil\n}","line":{"from":225,"to":236}} {"id":100003786,"name":"setEndpointSliceLabels","signature":"func setEndpointSliceLabels(epSlice *discovery.EndpointSlice, service *v1.Service) (map[string]string, bool)","file":"pkg/controller/endpointslice/utils.go","code":"// setEndpointSliceLabels returns a map with the new endpoint slices labels and true if there was an update.\n// Slices labels must be equivalent to the Service labels except for the reserved IsHeadlessService, LabelServiceName and LabelManagedBy labels\n// Changes to IsHeadlessService, LabelServiceName and LabelManagedBy labels on the Service do not result in updates to EndpointSlice labels.\nfunc setEndpointSliceLabels(epSlice *discovery.EndpointSlice, service *v1.Service) (map[string]string, bool) {\n\tupdated := false\n\tepLabels := make(map[string]string)\n\tsvcLabels := make(map[string]string)\n\n\t// check if the endpoint slice and the service have the same labels\n\t// clone current slice labels except the reserved labels\n\tfor key, value := range epSlice.Labels {\n\t\tif IsReservedLabelKey(key) {\n\t\t\tcontinue\n\t\t}\n\t\t// copy endpoint slice labels\n\t\tepLabels[key] = value\n\t}\n\n\tfor key, value := range service.Labels {\n\t\tif IsReservedLabelKey(key) {\n\t\t\tklog.Warningf(\"Service %s/%s using reserved endpoint slices label, skipping label %s: %s\", service.Namespace, service.Name, key, value)\n\t\t\tcontinue\n\t\t}\n\t\t// copy service labels\n\t\tsvcLabels[key] = value\n\t}\n\n\t// if the labels are not identical update the slice with the corresponding service labels\n\tif !apiequality.Semantic.DeepEqual(epLabels, svcLabels) {\n\t\tupdated = true\n\t}\n\n\t// add or remove headless label depending on the service Type\n\tif !helper.IsServiceIPSet(service) {\n\t\tsvcLabels[v1.IsHeadlessService] = \"\"\n\t} else {\n\t\tdelete(svcLabels, v1.IsHeadlessService)\n\t}\n\n\t// override endpoint slices reserved labels\n\tsvcLabels[discovery.LabelServiceName] = service.Name\n\tsvcLabels[discovery.LabelManagedBy] = controllerName\n\n\treturn svcLabels, updated\n}","line":{"from":238,"to":282}} {"id":100003787,"name":"IsReservedLabelKey","signature":"func IsReservedLabelKey(label string) bool","file":"pkg/controller/endpointslice/utils.go","code":"// IsReservedLabelKey return true if the label is one of the reserved label for slices\nfunc IsReservedLabelKey(label string) bool {\n\tif label == discovery.LabelServiceName ||\n\t\tlabel == discovery.LabelManagedBy ||\n\t\tlabel == v1.IsHeadlessService {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":284,"to":292}} {"id":100003788,"name":"Len","signature":"func (sl endpointSliceEndpointLen) Len() int { return len(sl) }","file":"pkg/controller/endpointslice/utils.go","code":"func (sl endpointSliceEndpointLen) Len() int { return len(sl) }","line":{"from":298,"to":298}} {"id":100003789,"name":"Swap","signature":"func (sl endpointSliceEndpointLen) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] }","file":"pkg/controller/endpointslice/utils.go","code":"func (sl endpointSliceEndpointLen) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] }","line":{"from":299,"to":299}} {"id":100003790,"name":"Less","signature":"func (sl endpointSliceEndpointLen) Less(i, j int) bool","file":"pkg/controller/endpointslice/utils.go","code":"func (sl endpointSliceEndpointLen) Less(i, j int) bool {\n\treturn len(sl[i].Endpoints) \u003e len(sl[j].Endpoints)\n}","line":{"from":300,"to":302}} {"id":100003791,"name":"getAddressTypesForService","signature":"func getAddressTypesForService(service *v1.Service) map[discovery.AddressType]struct{}","file":"pkg/controller/endpointslice/utils.go","code":"// returns a map of address types used by a service\nfunc getAddressTypesForService(service *v1.Service) map[discovery.AddressType]struct{} {\n\tserviceSupportedAddresses := make(map[discovery.AddressType]struct{})\n\t// TODO: (khenidak) when address types are removed in favor of\n\t// v1.IPFamily this will need to be removed, and work directly with\n\t// v1.IPFamily types\n\n\t// IMPORTANT: we assume that IP of (discovery.AddressType enum) is never in use\n\t// as it gets deprecated\n\tfor _, family := range service.Spec.IPFamilies {\n\t\tif family == v1.IPv4Protocol {\n\t\t\tserviceSupportedAddresses[discovery.AddressTypeIPv4] = struct{}{}\n\t\t}\n\n\t\tif family == v1.IPv6Protocol {\n\t\t\tserviceSupportedAddresses[discovery.AddressTypeIPv6] = struct{}{}\n\t\t}\n\t}\n\n\tif len(serviceSupportedAddresses) \u003e 0 {\n\t\treturn serviceSupportedAddresses // we have found families for this service\n\t}\n\n\t// TODO (khenidak) remove when (1) dual stack becomes\n\t// enabled by default (2) v1.19 falls off supported versions\n\n\t// Why do we need this:\n\t// a cluster being upgraded to the new apis\n\t// will have service.spec.IPFamilies: nil\n\t// if the controller manager connected to old api\n\t// server. This will have the nasty side effect of\n\t// removing all slices already created for this service.\n\t// this will disable all routing to service vip (ClusterIP)\n\t// this ensures that this does not happen. Same for headless services\n\t// we assume it is dual stack, until they get defaulted by *new* api-server\n\t// this ensures that traffic is not disrupted until then. But *may*\n\t// include undesired families for headless services until then.\n\n\tif len(service.Spec.ClusterIP) \u003e 0 \u0026\u0026 service.Spec.ClusterIP != v1.ClusterIPNone { // headfull\n\t\taddrType := discovery.AddressTypeIPv4\n\t\tif utilnet.IsIPv6String(service.Spec.ClusterIP) {\n\t\t\taddrType = discovery.AddressTypeIPv6\n\t\t}\n\t\tserviceSupportedAddresses[addrType] = struct{}{}\n\t\tklog.V(2).Infof(\"couldn't find ipfamilies for service: %v/%v. This could happen if controller manager is connected to an old apiserver that does not support ip families yet. EndpointSlices for this Service will use %s as the IP Family based on familyOf(ClusterIP:%v).\", service.Namespace, service.Name, addrType, service.Spec.ClusterIP)\n\t\treturn serviceSupportedAddresses\n\t}\n\n\t// headless\n\t// for now we assume two families. This should have minimal side effect\n\t// if the service is headless with no selector, then this will remain the case\n\t// if the service is headless with selector then chances are pods are still using single family\n\t// since kubelet will need to restart in order to start patching pod status with multiple ips\n\tserviceSupportedAddresses[discovery.AddressTypeIPv4] = struct{}{}\n\tserviceSupportedAddresses[discovery.AddressTypeIPv6] = struct{}{}\n\tklog.V(2).Infof(\"couldn't find ipfamilies for headless service: %v/%v likely because controller manager is likely connected to an old apiserver that does not support ip families yet. The service endpoint slice will use dual stack families until api-server default it correctly\", service.Namespace, service.Name)\n\treturn serviceSupportedAddresses\n}","line":{"from":304,"to":361}} {"id":100003792,"name":"unchangedSlices","signature":"func unchangedSlices(existingSlices, slicesToUpdate, slicesToDelete []*discovery.EndpointSlice) []*discovery.EndpointSlice","file":"pkg/controller/endpointslice/utils.go","code":"func unchangedSlices(existingSlices, slicesToUpdate, slicesToDelete []*discovery.EndpointSlice) []*discovery.EndpointSlice {\n\tchangedSliceNames := sets.String{}\n\tfor _, slice := range slicesToUpdate {\n\t\tchangedSliceNames.Insert(slice.Name)\n\t}\n\tfor _, slice := range slicesToDelete {\n\t\tchangedSliceNames.Insert(slice.Name)\n\t}\n\tunchangedSlices := []*discovery.EndpointSlice{}\n\tfor _, slice := range existingSlices {\n\t\tif !changedSliceNames.Has(slice.Name) {\n\t\t\tunchangedSlices = append(unchangedSlices, slice)\n\t\t}\n\t}\n\n\treturn unchangedSlices\n}","line":{"from":363,"to":379}} {"id":100003793,"name":"hintsEnabled","signature":"func hintsEnabled(annotations map[string]string) bool","file":"pkg/controller/endpointslice/utils.go","code":"// hintsEnabled returns true if the provided annotations include either\n// v1.AnnotationTopologyMode or v1.DeprecatedAnnotationTopologyAwareHints key\n// with a value set to \"Auto\" or \"auto\". When both are set,\n// v1.DeprecatedAnnotationTopologyAwareHints has precedence.\nfunc hintsEnabled(annotations map[string]string) bool {\n\tval, ok := annotations[v1.DeprecatedAnnotationTopologyAwareHints]\n\tif !ok {\n\t\tval, ok = annotations[v1.AnnotationTopologyMode]\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn val == \"Auto\" || val == \"auto\"\n}","line":{"from":381,"to":394}} {"id":100003794,"name":"managedByChanged","signature":"func managedByChanged(endpointSlice1, endpointSlice2 *discovery.EndpointSlice) bool","file":"pkg/controller/endpointslice/utils.go","code":"// managedByChanged returns true if one of the provided EndpointSlices is\n// managed by the EndpointSlice controller while the other is not.\nfunc managedByChanged(endpointSlice1, endpointSlice2 *discovery.EndpointSlice) bool {\n\treturn managedByController(endpointSlice1) != managedByController(endpointSlice2)\n}","line":{"from":396,"to":400}} {"id":100003795,"name":"managedByController","signature":"func managedByController(endpointSlice *discovery.EndpointSlice) bool","file":"pkg/controller/endpointslice/utils.go","code":"// managedByController returns true if the controller of the provided\n// EndpointSlices is the EndpointSlice controller.\nfunc managedByController(endpointSlice *discovery.EndpointSlice) bool {\n\tmanagedBy, _ := endpointSlice.Labels[discovery.LabelManagedBy]\n\treturn managedBy == controllerName\n}","line":{"from":402,"to":407}} {"id":100003796,"name":"Convert_v1alpha1_EndpointSliceMirroringControllerConfiguration_To_config_EndpointSliceMirroringControllerConfiguration","signature":"func Convert_v1alpha1_EndpointSliceMirroringControllerConfiguration_To_config_EndpointSliceMirroringControllerConfiguration(in *v1alpha1.EndpointSliceMirroringControllerConfiguration, out *endpointslicemirroringconfig.EndpointSliceMirroringControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/endpointslicemirroring/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_EndpointSliceMirroringControllerConfiguration_To_config_EndpointSliceMirroringControllerConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_EndpointSliceMirroringControllerConfiguration_To_config_EndpointSliceMirroringControllerConfiguration(in *v1alpha1.EndpointSliceMirroringControllerConfiguration, out *endpointslicemirroringconfig.EndpointSliceMirroringControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_EndpointSliceMirroringControllerConfiguration_To_config_EndpointSliceMirroringControllerConfiguration(in, out, s)\n}","line":{"from":32,"to":35}} {"id":100003797,"name":"Convert_config_EndpointSliceMirroringControllerConfiguration_To_v1alpha1_EndpointSliceMirroringControllerConfiguration","signature":"func Convert_config_EndpointSliceMirroringControllerConfiguration_To_v1alpha1_EndpointSliceMirroringControllerConfiguration(in *endpointslicemirroringconfig.EndpointSliceMirroringControllerConfiguration, out *v1alpha1.EndpointSliceMirroringControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/endpointslicemirroring/config/v1alpha1/conversion.go","code":"// Convert_config_EndpointSliceMirroringControllerConfiguration_To_v1alpha1_EndpointSliceMirroringControllerConfiguration is an autogenerated conversion function.\nfunc Convert_config_EndpointSliceMirroringControllerConfiguration_To_v1alpha1_EndpointSliceMirroringControllerConfiguration(in *endpointslicemirroringconfig.EndpointSliceMirroringControllerConfiguration, out *v1alpha1.EndpointSliceMirroringControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_EndpointSliceMirroringControllerConfiguration_To_v1alpha1_EndpointSliceMirroringControllerConfiguration(in, out, s)\n}","line":{"from":37,"to":40}} {"id":100003798,"name":"RecommendedDefaultEndpointSliceMirroringControllerConfiguration","signature":"func RecommendedDefaultEndpointSliceMirroringControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.EndpointSliceMirroringControllerConfiguration)","file":"pkg/controller/endpointslicemirroring/config/v1alpha1/defaults.go","code":"// RecommendedDefaultEndpointSliceMirroringControllerConfiguration defaults a\n// pointer to a EndpointSliceMirroringControllerConfiguration struct. This will\n// set the recommended default values, but they may be subject to change between\n// API versions. This function is intentionally not registered in the scheme as\n// a \"normal\" `SetDefaults_Foo` function to allow consumers of this type to set\n// whatever defaults for their embedded configs. Forcing consumers to use these\n// defaults would be problematic as defaulting in the scheme is done as part of\n// the conversion, and there would be no easy way to opt-out. Instead, if you\n// want to use this defaulting method run it in your wrapper struct of this type\n// in its `SetDefaults_` method.\nfunc RecommendedDefaultEndpointSliceMirroringControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.EndpointSliceMirroringControllerConfiguration) {\n\tif obj.MirroringConcurrentServiceEndpointSyncs == 0 {\n\t\tobj.MirroringConcurrentServiceEndpointSyncs = 5\n\t}\n\n\tif obj.MirroringMaxEndpointsPerSubset == 0 {\n\t\tobj.MirroringMaxEndpointsPerSubset = 1000\n\t}\n}","line":{"from":23,"to":41}} {"id":100003799,"name":"NewController","signature":"func NewController(endpointsInformer coreinformers.EndpointsInformer,","file":"pkg/controller/endpointslicemirroring/endpointslicemirroring_controller.go","code":"// NewController creates and initializes a new Controller\nfunc NewController(endpointsInformer coreinformers.EndpointsInformer,\n\tendpointSliceInformer discoveryinformers.EndpointSliceInformer,\n\tserviceInformer coreinformers.ServiceInformer,\n\tmaxEndpointsPerSubset int32,\n\tclient clientset.Interface,\n\tendpointUpdatesBatchPeriod time.Duration,\n) *Controller {\n\tbroadcaster := record.NewBroadcaster()\n\trecorder := broadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"endpoint-slice-mirroring-controller\"})\n\n\tmetrics.RegisterMetrics()\n\n\tc := \u0026Controller{\n\t\tclient: client,\n\t\t// This is similar to the DefaultControllerRateLimiter, just with a\n\t\t// significantly higher default backoff (1s vs 5ms). This controller\n\t\t// processes events that can require significant EndpointSlice changes.\n\t\t// A more significant rate limit back off here helps ensure that the\n\t\t// Controller does not overwhelm the API Server.\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.NewMaxOfRateLimiter(\n\t\t\tworkqueue.NewItemExponentialFailureRateLimiter(defaultSyncBackOff, maxSyncBackOff),\n\t\t\t// 10 qps, 100 bucket size. This is only for retry speed and its\n\t\t\t// only the overall factor (not per item).\n\t\t\t\u0026workqueue.BucketRateLimiter{Limiter: rate.NewLimiter(rate.Limit(10), 100)},\n\t\t), \"endpoint_slice_mirroring\"),\n\t\tworkerLoopPeriod: time.Second,\n\t}\n\n\tendpointsInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: c.onEndpointsAdd,\n\t\tUpdateFunc: c.onEndpointsUpdate,\n\t\tDeleteFunc: c.onEndpointsDelete,\n\t})\n\tc.endpointsLister = endpointsInformer.Lister()\n\tc.endpointsSynced = endpointsInformer.Informer().HasSynced\n\n\tendpointSliceInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: c.onEndpointSliceAdd,\n\t\tUpdateFunc: c.onEndpointSliceUpdate,\n\t\tDeleteFunc: c.onEndpointSliceDelete,\n\t})\n\n\tc.endpointSliceLister = endpointSliceInformer.Lister()\n\tc.endpointSlicesSynced = endpointSliceInformer.Informer().HasSynced\n\tc.endpointSliceTracker = endpointsliceutil.NewEndpointSliceTracker()\n\n\tc.serviceLister = serviceInformer.Lister()\n\tc.servicesSynced = serviceInformer.Informer().HasSynced\n\tserviceInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: c.onServiceAdd,\n\t\tUpdateFunc: c.onServiceUpdate,\n\t\tDeleteFunc: c.onServiceDelete,\n\t})\n\n\tc.maxEndpointsPerSubset = maxEndpointsPerSubset\n\n\tc.reconciler = \u0026reconciler{\n\t\tclient: c.client,\n\t\tmaxEndpointsPerSubset: c.maxEndpointsPerSubset,\n\t\tendpointSliceTracker: c.endpointSliceTracker,\n\t\tmetricsCache: metrics.NewCache(maxEndpointsPerSubset),\n\t\teventRecorder: recorder,\n\t}\n\n\tc.eventBroadcaster = broadcaster\n\tc.eventRecorder = recorder\n\n\tc.endpointUpdatesBatchPeriod = endpointUpdatesBatchPeriod\n\n\treturn c\n}","line":{"from":68,"to":139}} {"id":100003800,"name":"Run","signature":"func (c *Controller) Run(workers int, stopCh \u003c-chan struct{})","file":"pkg/controller/endpointslicemirroring/endpointslicemirroring_controller.go","code":"// Run will not return until stopCh is closed.\nfunc (c *Controller) Run(workers int, stopCh \u003c-chan struct{}) {\n\tdefer utilruntime.HandleCrash()\n\n\t// Start events processing pipeline.\n\tc.eventBroadcaster.StartLogging(klog.Infof)\n\tc.eventBroadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: c.client.CoreV1().Events(\"\")})\n\tdefer c.eventBroadcaster.Shutdown()\n\n\tdefer c.queue.ShutDown()\n\n\tklog.Infof(\"Starting EndpointSliceMirroring controller\")\n\tdefer klog.Infof(\"Shutting down EndpointSliceMirroring controller\")\n\n\tif !cache.WaitForNamedCacheSync(\"endpoint_slice_mirroring\", stopCh, c.endpointsSynced, c.endpointSlicesSynced, c.servicesSynced) {\n\t\treturn\n\t}\n\n\tklog.V(2).Infof(\"Starting %d worker threads\", workers)\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.Until(c.worker, c.workerLoopPeriod, stopCh)\n\t}\n\n\t\u003c-stopCh\n}","line":{"from":200,"to":224}} {"id":100003801,"name":"worker","signature":"func (c *Controller) worker()","file":"pkg/controller/endpointslicemirroring/endpointslicemirroring_controller.go","code":"// worker runs a worker thread that just dequeues items, processes them, and\n// marks them done. You may run as many of these in parallel as you wish; the\n// workqueue guarantees that they will not end up processing the same service\n// at the same time\nfunc (c *Controller) worker() {\n\tfor c.processNextWorkItem() {\n\t}\n}","line":{"from":226,"to":233}} {"id":100003802,"name":"processNextWorkItem","signature":"func (c *Controller) processNextWorkItem() bool","file":"pkg/controller/endpointslicemirroring/endpointslicemirroring_controller.go","code":"func (c *Controller) processNextWorkItem() bool {\n\tcKey, quit := c.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.queue.Done(cKey)\n\n\terr := c.syncEndpoints(cKey.(string))\n\tc.handleErr(err, cKey)\n\n\treturn true\n}","line":{"from":235,"to":246}} {"id":100003803,"name":"handleErr","signature":"func (c *Controller) handleErr(err error, key interface{})","file":"pkg/controller/endpointslicemirroring/endpointslicemirroring_controller.go","code":"func (c *Controller) handleErr(err error, key interface{}) {\n\tif err == nil {\n\t\tc.queue.Forget(key)\n\t\treturn\n\t}\n\n\tif c.queue.NumRequeues(key) \u003c maxRetries {\n\t\tklog.Warningf(\"Error mirroring EndpointSlices for %q Endpoints, retrying. Error: %v\", key, err)\n\t\tc.queue.AddRateLimited(key)\n\t\treturn\n\t}\n\n\tklog.Warningf(\"Retry budget exceeded, dropping %q Endpoints out of the queue: %v\", key, err)\n\tc.queue.Forget(key)\n\tutilruntime.HandleError(err)\n}","line":{"from":248,"to":263}} {"id":100003804,"name":"syncEndpoints","signature":"func (c *Controller) syncEndpoints(key string) error","file":"pkg/controller/endpointslicemirroring/endpointslicemirroring_controller.go","code":"func (c *Controller) syncEndpoints(key string) error {\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tsyncDuration := float64(time.Since(startTime).Milliseconds()) / 1000\n\t\tmetrics.EndpointsSyncDuration.WithLabelValues().Observe(syncDuration)\n\t\tklog.V(4).Infof(\"Finished syncing EndpointSlices for %q Endpoints. (%v)\", key, time.Since(startTime))\n\t}()\n\n\tklog.V(4).Infof(\"syncEndpoints(%q)\", key)\n\n\tnamespace, name, err := cache.SplitMetaNamespaceKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tendpoints, err := c.endpointsLister.Endpoints(namespace).Get(name)\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\tklog.V(4).Infof(\"%s/%s Endpoints not found, cleaning up any mirrored EndpointSlices\", namespace, name)\n\t\t\tc.endpointSliceTracker.DeleteService(namespace, name)\n\t\t\treturn c.deleteMirroredSlices(namespace, name)\n\t\t}\n\t\treturn err\n\t}\n\n\tif !c.shouldMirror(endpoints) {\n\t\tklog.V(4).Infof(\"%s/%s Endpoints should not be mirrored, cleaning up any mirrored EndpointSlices\", namespace, name)\n\t\tc.endpointSliceTracker.DeleteService(namespace, name)\n\t\treturn c.deleteMirroredSlices(namespace, name)\n\t}\n\n\tsvc, err := c.serviceLister.Services(namespace).Get(name)\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\tklog.V(4).Infof(\"%s/%s Service not found, cleaning up any mirrored EndpointSlices\", namespace, name)\n\t\t\tc.endpointSliceTracker.DeleteService(namespace, name)\n\t\t\treturn c.deleteMirroredSlices(namespace, name)\n\t\t}\n\t\treturn err\n\t}\n\n\t// If a selector is specified, clean up any mirrored slices.\n\tif svc.Spec.Selector != nil {\n\t\tklog.V(4).Infof(\"%s/%s Service now has selector, cleaning up any mirrored EndpointSlices\", namespace, name)\n\t\tc.endpointSliceTracker.DeleteService(namespace, name)\n\t\treturn c.deleteMirroredSlices(namespace, name)\n\t}\n\n\tendpointSlices, err := endpointSlicesMirroredForService(c.endpointSliceLister, namespace, name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif c.endpointSliceTracker.StaleSlices(svc, endpointSlices) {\n\t\treturn endpointsliceutil.NewStaleInformerCache(\"EndpointSlice informer cache is out of date\")\n\t}\n\n\terr = c.reconciler.reconcile(endpoints, endpointSlices)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":265,"to":328}} {"id":100003805,"name":"queueEndpoints","signature":"func (c *Controller) queueEndpoints(obj interface{})","file":"pkg/controller/endpointslicemirroring/endpointslicemirroring_controller.go","code":"// queueEndpoints queues the Endpoints resource for processing.\nfunc (c *Controller) queueEndpoints(obj interface{}) {\n\tkey, err := controller.KeyFunc(obj)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Couldn't get key for object %+v (type %T): %v\", obj, obj, err))\n\t\treturn\n\t}\n\n\tc.queue.Add(key)\n}","line":{"from":330,"to":339}} {"id":100003806,"name":"shouldMirror","signature":"func (c *Controller) shouldMirror(endpoints *v1.Endpoints) bool","file":"pkg/controller/endpointslicemirroring/endpointslicemirroring_controller.go","code":"// shouldMirror returns true if an Endpoints resource should be mirrored by this\n// controller. This will be false if:\n// - the Endpoints resource is nil.\n// - the Endpoints resource has a skip-mirror label.\n// - the Endpoints resource has a leader election annotation.\n// This does not ensure that a corresponding Service exists with a nil selector.\n// That check should be performed separately.\nfunc (c *Controller) shouldMirror(endpoints *v1.Endpoints) bool {\n\tif endpoints == nil || skipMirror(endpoints.Labels) || hasLeaderElection(endpoints.Annotations) {\n\t\treturn false\n\t}\n\n\treturn true\n}","line":{"from":341,"to":354}} {"id":100003807,"name":"onServiceAdd","signature":"func (c *Controller) onServiceAdd(obj interface{})","file":"pkg/controller/endpointslicemirroring/endpointslicemirroring_controller.go","code":"// onServiceAdd queues a sync for the relevant Endpoints resource.\nfunc (c *Controller) onServiceAdd(obj interface{}) {\n\tservice := obj.(*v1.Service)\n\tif service == nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"onServiceAdd() expected type v1.Service, got %T\", obj))\n\t\treturn\n\t}\n\tif service.Spec.Selector == nil {\n\t\tc.queueEndpoints(obj)\n\t}\n}","line":{"from":356,"to":366}} {"id":100003808,"name":"onServiceUpdate","signature":"func (c *Controller) onServiceUpdate(prevObj, obj interface{})","file":"pkg/controller/endpointslicemirroring/endpointslicemirroring_controller.go","code":"// onServiceUpdate queues a sync for the relevant Endpoints resource.\nfunc (c *Controller) onServiceUpdate(prevObj, obj interface{}) {\n\tservice := obj.(*v1.Service)\n\tprevService := prevObj.(*v1.Service)\n\tif service == nil || prevService == nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"onServiceUpdate() expected type v1.Service, got %T, %T\", prevObj, obj))\n\t\treturn\n\t}\n\tif (service.Spec.Selector == nil) != (prevService.Spec.Selector == nil) {\n\t\tc.queueEndpoints(obj)\n\t}\n}","line":{"from":368,"to":379}} {"id":100003809,"name":"onServiceDelete","signature":"func (c *Controller) onServiceDelete(obj interface{})","file":"pkg/controller/endpointslicemirroring/endpointslicemirroring_controller.go","code":"// onServiceDelete queues a sync for the relevant Endpoints resource.\nfunc (c *Controller) onServiceDelete(obj interface{}) {\n\tservice := getServiceFromDeleteAction(obj)\n\tif service == nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"onServiceDelete() expected type v1.Service, got %T\", obj))\n\t\treturn\n\t}\n\tif service.Spec.Selector == nil {\n\t\tc.queueEndpoints(obj)\n\t}\n}","line":{"from":381,"to":391}} {"id":100003810,"name":"onEndpointsAdd","signature":"func (c *Controller) onEndpointsAdd(obj interface{})","file":"pkg/controller/endpointslicemirroring/endpointslicemirroring_controller.go","code":"// onEndpointsAdd queues a sync for the relevant Endpoints resource.\nfunc (c *Controller) onEndpointsAdd(obj interface{}) {\n\tendpoints := obj.(*v1.Endpoints)\n\tif endpoints == nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"onEndpointsAdd() expected type v1.Endpoints, got %T\", obj))\n\t\treturn\n\t}\n\tif !c.shouldMirror(endpoints) {\n\t\tklog.V(5).Infof(\"Skipping mirroring for %s/%s\", endpoints.Namespace, endpoints.Name)\n\t\treturn\n\t}\n\tc.queueEndpoints(obj)\n}","line":{"from":393,"to":405}} {"id":100003811,"name":"onEndpointsUpdate","signature":"func (c *Controller) onEndpointsUpdate(prevObj, obj interface{})","file":"pkg/controller/endpointslicemirroring/endpointslicemirroring_controller.go","code":"// onEndpointsUpdate queues a sync for the relevant Endpoints resource.\nfunc (c *Controller) onEndpointsUpdate(prevObj, obj interface{}) {\n\tendpoints := obj.(*v1.Endpoints)\n\tprevEndpoints := prevObj.(*v1.Endpoints)\n\tif endpoints == nil || prevEndpoints == nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"onEndpointsUpdate() expected type v1.Endpoints, got %T, %T\", prevObj, obj))\n\t\treturn\n\t}\n\tif !c.shouldMirror(endpoints) \u0026\u0026 !c.shouldMirror(prevEndpoints) {\n\t\tklog.V(5).Infof(\"Skipping mirroring for %s/%s\", endpoints.Namespace, endpoints.Name)\n\t\treturn\n\t}\n\tc.queueEndpoints(obj)\n}","line":{"from":407,"to":420}} {"id":100003812,"name":"onEndpointsDelete","signature":"func (c *Controller) onEndpointsDelete(obj interface{})","file":"pkg/controller/endpointslicemirroring/endpointslicemirroring_controller.go","code":"// onEndpointsDelete queues a sync for the relevant Endpoints resource.\nfunc (c *Controller) onEndpointsDelete(obj interface{}) {\n\tendpoints := getEndpointsFromDeleteAction(obj)\n\tif endpoints == nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"onEndpointsDelete() expected type v1.Endpoints, got %T\", obj))\n\t\treturn\n\t}\n\tif !c.shouldMirror(endpoints) {\n\t\tklog.V(5).Infof(\"Skipping mirroring for %s/%s\", endpoints.Namespace, endpoints.Name)\n\t\treturn\n\t}\n\tc.queueEndpoints(obj)\n}","line":{"from":422,"to":434}} {"id":100003813,"name":"onEndpointSliceAdd","signature":"func (c *Controller) onEndpointSliceAdd(obj interface{})","file":"pkg/controller/endpointslicemirroring/endpointslicemirroring_controller.go","code":"// onEndpointSliceAdd queues a sync for the relevant Endpoints resource for a\n// sync if the EndpointSlice resource version does not match the expected\n// version in the endpointSliceTracker.\nfunc (c *Controller) onEndpointSliceAdd(obj interface{}) {\n\tendpointSlice := obj.(*discovery.EndpointSlice)\n\tif endpointSlice == nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"onEndpointSliceAdd() expected type discovery.EndpointSlice, got %T\", obj))\n\t\treturn\n\t}\n\tif managedByController(endpointSlice) \u0026\u0026 c.endpointSliceTracker.ShouldSync(endpointSlice) {\n\t\tc.queueEndpointsForEndpointSlice(endpointSlice)\n\t}\n}","line":{"from":436,"to":448}} {"id":100003814,"name":"onEndpointSliceUpdate","signature":"func (c *Controller) onEndpointSliceUpdate(prevObj, obj interface{})","file":"pkg/controller/endpointslicemirroring/endpointslicemirroring_controller.go","code":"// onEndpointSliceUpdate queues a sync for the relevant Endpoints resource for a\n// sync if the EndpointSlice resource version does not match the expected\n// version in the endpointSliceTracker or the managed-by value of the\n// EndpointSlice has changed from or to this controller.\nfunc (c *Controller) onEndpointSliceUpdate(prevObj, obj interface{}) {\n\tprevEndpointSlice := obj.(*discovery.EndpointSlice)\n\tendpointSlice := prevObj.(*discovery.EndpointSlice)\n\tif endpointSlice == nil || prevEndpointSlice == nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"onEndpointSliceUpdated() expected type discovery.EndpointSlice, got %T, %T\", prevObj, obj))\n\t\treturn\n\t}\n\t// EndpointSlice generation does not change when labels change. Although the\n\t// controller will never change LabelServiceName, users might. This check\n\t// ensures that we handle changes to this label.\n\tsvcName := endpointSlice.Labels[discovery.LabelServiceName]\n\tprevSvcName := prevEndpointSlice.Labels[discovery.LabelServiceName]\n\tif svcName != prevSvcName {\n\t\tklog.Warningf(\"%s label changed from %s to %s for %s\", discovery.LabelServiceName, prevSvcName, svcName, endpointSlice.Name)\n\t\tc.queueEndpointsForEndpointSlice(endpointSlice)\n\t\tc.queueEndpointsForEndpointSlice(prevEndpointSlice)\n\t\treturn\n\t}\n\tif managedByChanged(prevEndpointSlice, endpointSlice) || (managedByController(endpointSlice) \u0026\u0026 c.endpointSliceTracker.ShouldSync(endpointSlice)) {\n\t\tc.queueEndpointsForEndpointSlice(endpointSlice)\n\t}\n}","line":{"from":450,"to":475}} {"id":100003815,"name":"onEndpointSliceDelete","signature":"func (c *Controller) onEndpointSliceDelete(obj interface{})","file":"pkg/controller/endpointslicemirroring/endpointslicemirroring_controller.go","code":"// onEndpointSliceDelete queues a sync for the relevant Endpoints resource for a\n// sync if the EndpointSlice resource version does not match the expected\n// version in the endpointSliceTracker.\nfunc (c *Controller) onEndpointSliceDelete(obj interface{}) {\n\tendpointSlice := getEndpointSliceFromDeleteAction(obj)\n\tif endpointSlice == nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"onEndpointSliceDelete() expected type discovery.EndpointSlice, got %T\", obj))\n\t\treturn\n\t}\n\tif managedByController(endpointSlice) \u0026\u0026 c.endpointSliceTracker.Has(endpointSlice) {\n\t\t// This returns false if we didn't expect the EndpointSlice to be\n\t\t// deleted. If that is the case, we queue the Service for another sync.\n\t\tif !c.endpointSliceTracker.HandleDeletion(endpointSlice) {\n\t\t\tc.queueEndpointsForEndpointSlice(endpointSlice)\n\t\t}\n\t}\n}","line":{"from":477,"to":493}} {"id":100003816,"name":"queueEndpointsForEndpointSlice","signature":"func (c *Controller) queueEndpointsForEndpointSlice(endpointSlice *discovery.EndpointSlice)","file":"pkg/controller/endpointslicemirroring/endpointslicemirroring_controller.go","code":"// queueEndpointsForEndpointSlice attempts to queue the corresponding Endpoints\n// resource for the provided EndpointSlice.\nfunc (c *Controller) queueEndpointsForEndpointSlice(endpointSlice *discovery.EndpointSlice) {\n\tkey, err := endpointsControllerKey(endpointSlice)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Couldn't get key for EndpointSlice %+v (type %T): %v\", endpointSlice, endpointSlice, err))\n\t\treturn\n\t}\n\n\tc.queue.AddAfter(key, c.endpointUpdatesBatchPeriod)\n}","line":{"from":495,"to":505}} {"id":100003817,"name":"deleteMirroredSlices","signature":"func (c *Controller) deleteMirroredSlices(namespace, name string) error","file":"pkg/controller/endpointslicemirroring/endpointslicemirroring_controller.go","code":"// deleteMirroredSlices will delete and EndpointSlices that have been mirrored\n// for Endpoints with this namespace and name.\nfunc (c *Controller) deleteMirroredSlices(namespace, name string) error {\n\tendpointSlices, err := endpointSlicesMirroredForService(c.endpointSliceLister, namespace, name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.endpointSliceTracker.DeleteService(namespace, name)\n\treturn c.reconciler.deleteEndpoints(namespace, name, endpointSlices)\n}","line":{"from":507,"to":517}} {"id":100003818,"name":"endpointSlicesMirroredForService","signature":"func endpointSlicesMirroredForService(endpointSliceLister discoverylisters.EndpointSliceLister, namespace, name string) ([]*discovery.EndpointSlice, error)","file":"pkg/controller/endpointslicemirroring/endpointslicemirroring_controller.go","code":"// endpointSlicesMirroredForService returns the EndpointSlices that have been\n// mirrored for a Service by this controller.\nfunc endpointSlicesMirroredForService(endpointSliceLister discoverylisters.EndpointSliceLister, namespace, name string) ([]*discovery.EndpointSlice, error) {\n\tesLabelSelector := labels.Set(map[string]string{\n\t\tdiscovery.LabelServiceName: name,\n\t\tdiscovery.LabelManagedBy: controllerName,\n\t}).AsSelectorPreValidated()\n\treturn endpointSliceLister.EndpointSlices(namespace).List(esLabelSelector)\n}","line":{"from":519,"to":527}} {"id":100003819,"name":"NewCache","signature":"func NewCache(endpointsPerSlice int32) *Cache","file":"pkg/controller/endpointslicemirroring/metrics/cache.go","code":"// NewCache returns a new Cache with the specified endpointsPerSlice.\nfunc NewCache(endpointsPerSlice int32) *Cache {\n\treturn \u0026Cache{\n\t\tmaxEndpointsPerSlice: endpointsPerSlice,\n\t\tcache: map[types.NamespacedName]*EndpointPortCache{},\n\t}\n}","line":{"from":27,"to":33}} {"id":100003820,"name":"NewEndpointPortCache","signature":"func NewEndpointPortCache() *EndpointPortCache","file":"pkg/controller/endpointslicemirroring/metrics/cache.go","code":"// NewEndpointPortCache initializes and returns a new EndpointPortCache.\nfunc NewEndpointPortCache() *EndpointPortCache {\n\treturn \u0026EndpointPortCache{\n\t\titems: map[endpointutil.PortMapKey]EfficiencyInfo{},\n\t}\n}","line":{"from":67,"to":72}} {"id":100003821,"name":"Set","signature":"func (spc *EndpointPortCache) Set(pmKey endpointutil.PortMapKey, eInfo EfficiencyInfo)","file":"pkg/controller/endpointslicemirroring/metrics/cache.go","code":"// Set updates the EndpointPortCache to contain the provided EfficiencyInfo\n// for the provided PortMapKey.\nfunc (spc *EndpointPortCache) Set(pmKey endpointutil.PortMapKey, eInfo EfficiencyInfo) {\n\tspc.items[pmKey] = eInfo\n}","line":{"from":74,"to":78}} {"id":100003822,"name":"numEndpoints","signature":"func (spc *EndpointPortCache) numEndpoints() int","file":"pkg/controller/endpointslicemirroring/metrics/cache.go","code":"// numEndpoints returns the total number of endpoints represented by a\n// EndpointPortCache.\nfunc (spc *EndpointPortCache) numEndpoints() int {\n\tnum := 0\n\tfor _, eInfo := range spc.items {\n\t\tnum += eInfo.Endpoints\n\t}\n\treturn num\n}","line":{"from":80,"to":88}} {"id":100003823,"name":"UpdateEndpointPortCache","signature":"func (c *Cache) UpdateEndpointPortCache(endpointsNN types.NamespacedName, epCache *EndpointPortCache)","file":"pkg/controller/endpointslicemirroring/metrics/cache.go","code":"// UpdateEndpointPortCache updates a EndpointPortCache in the global cache for a\n// given Service and updates the corresponding metrics.\n// Parameters:\n// * endpointsNN refers to a NamespacedName representing the Endpoints resource.\n// * epCache refers to a EndpointPortCache for the specified Endpoints reosource.\nfunc (c *Cache) UpdateEndpointPortCache(endpointsNN types.NamespacedName, epCache *EndpointPortCache) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tprevNumEndpoints := 0\n\tif existingEPCache, ok := c.cache[endpointsNN]; ok {\n\t\tprevNumEndpoints = existingEPCache.numEndpoints()\n\t}\n\n\tcurrNumEndpoints := epCache.numEndpoints()\n\t// To keep numEndpoints up to date, add the difference between the number of\n\t// endpoints in the provided spCache and any spCache it might be replacing.\n\tc.numEndpoints = c.numEndpoints + currNumEndpoints - prevNumEndpoints\n\n\tc.cache[endpointsNN] = epCache\n\tc.updateMetrics()\n}","line":{"from":90,"to":111}} {"id":100003824,"name":"DeleteEndpoints","signature":"func (c *Cache) DeleteEndpoints(endpointsNN types.NamespacedName)","file":"pkg/controller/endpointslicemirroring/metrics/cache.go","code":"// DeleteEndpoints removes references to an Endpoints resource from the global\n// cache and updates the corresponding metrics.\nfunc (c *Cache) DeleteEndpoints(endpointsNN types.NamespacedName) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tif spCache, ok := c.cache[endpointsNN]; ok {\n\t\tc.numEndpoints = c.numEndpoints - spCache.numEndpoints()\n\t\tdelete(c.cache, endpointsNN)\n\t\tc.updateMetrics()\n\t}\n}","line":{"from":113,"to":124}} {"id":100003825,"name":"desiredAndActualSlices","signature":"func (c *Cache) desiredAndActualSlices() metricsUpdate","file":"pkg/controller/endpointslicemirroring/metrics/cache.go","code":"// desiredAndActualSlices returns a metricsUpdate with the desired and actual\n// number of EndpointSlices given the current values in the cache.\n// Must be called holding lock.\nfunc (c *Cache) desiredAndActualSlices() metricsUpdate {\n\tmUpdate := metricsUpdate{}\n\tfor _, spCache := range c.cache {\n\t\tfor _, eInfo := range spCache.items {\n\t\t\tmUpdate.actual += eInfo.Slices\n\t\t\tmUpdate.desired += numDesiredSlices(eInfo.Endpoints, int(c.maxEndpointsPerSlice))\n\t\t}\n\t}\n\treturn mUpdate\n}","line":{"from":131,"to":143}} {"id":100003826,"name":"updateMetrics","signature":"func (c *Cache) updateMetrics()","file":"pkg/controller/endpointslicemirroring/metrics/cache.go","code":"// updateMetrics updates metrics with the values from this Cache.\n// Must be called holding lock.\nfunc (c *Cache) updateMetrics() {\n\tmUpdate := c.desiredAndActualSlices()\n\tNumEndpointSlices.WithLabelValues().Set(float64(mUpdate.actual))\n\tDesiredEndpointSlices.WithLabelValues().Set(float64(mUpdate.desired))\n\tEndpointsDesired.WithLabelValues().Set(float64(c.numEndpoints))\n}","line":{"from":145,"to":152}} {"id":100003827,"name":"numDesiredSlices","signature":"func numDesiredSlices(numEndpoints, maxPerSlice int) int","file":"pkg/controller/endpointslicemirroring/metrics/cache.go","code":"// numDesiredSlices calculates the number of EndpointSlices that would exist\n// with ideal endpoint distribution.\nfunc numDesiredSlices(numEndpoints, maxPerSlice int) int {\n\treturn int(math.Ceil(float64(numEndpoints) / float64(maxPerSlice)))\n}","line":{"from":154,"to":158}} {"id":100003828,"name":"RegisterMetrics","signature":"func RegisterMetrics()","file":"pkg/controller/endpointslicemirroring/metrics/metrics.go","code":"// RegisterMetrics registers EndpointSlice metrics.\nfunc RegisterMetrics() {\n\tregisterMetrics.Do(func() {\n\t\tlegacyregistry.MustRegister(EndpointsAddedPerSync)\n\t\tlegacyregistry.MustRegister(EndpointsUpdatedPerSync)\n\t\tlegacyregistry.MustRegister(EndpointsRemovedPerSync)\n\t\tlegacyregistry.MustRegister(AddressesSkippedPerSync)\n\t\tlegacyregistry.MustRegister(EndpointsSyncDuration)\n\t\tlegacyregistry.MustRegister(EndpointsDesired)\n\t\tlegacyregistry.MustRegister(NumEndpointSlices)\n\t\tlegacyregistry.MustRegister(DesiredEndpointSlices)\n\t\tlegacyregistry.MustRegister(EndpointSliceChanges)\n\t})\n}","line":{"from":136,"to":149}} {"id":100003829,"name":"reconcile","signature":"func (r *reconciler) reconcile(endpoints *corev1.Endpoints, existingSlices []*discovery.EndpointSlice) error","file":"pkg/controller/endpointslicemirroring/reconciler.go","code":"// reconcile takes an Endpoints resource and ensures that corresponding\n// EndpointSlices exist. It creates, updates, or deletes EndpointSlices to\n// ensure the desired set of addresses are represented by EndpointSlices.\nfunc (r *reconciler) reconcile(endpoints *corev1.Endpoints, existingSlices []*discovery.EndpointSlice) error {\n\t// Calculate desired state.\n\td := newDesiredCalc()\n\n\tnumInvalidAddresses := 0\n\taddressesSkipped := 0\n\n\t// canonicalize the Endpoints subsets before processing them\n\tsubsets := endpointsv1.RepackSubsets(endpoints.Subsets)\n\tfor _, subset := range subsets {\n\t\tmultiKey := d.initPorts(subset.Ports)\n\n\t\ttotalAddresses := len(subset.Addresses) + len(subset.NotReadyAddresses)\n\t\ttotalAddressesAdded := 0\n\n\t\tfor _, address := range subset.Addresses {\n\t\t\t// Break if we've reached the max number of addresses to mirror\n\t\t\t// per EndpointSubset. This allows for a simple 1:1 mapping between\n\t\t\t// EndpointSubset and EndpointSlice.\n\t\t\tif totalAddressesAdded \u003e= int(r.maxEndpointsPerSubset) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif ok := d.addAddress(address, multiKey, true); ok {\n\t\t\t\ttotalAddressesAdded++\n\t\t\t} else {\n\t\t\t\tnumInvalidAddresses++\n\t\t\t\tklog.Warningf(\"Address in %s/%s Endpoints is not a valid IP, it will not be mirrored to an EndpointSlice: %s\", endpoints.Namespace, endpoints.Name, address.IP)\n\t\t\t}\n\t\t}\n\n\t\tfor _, address := range subset.NotReadyAddresses {\n\t\t\t// Break if we've reached the max number of addresses to mirror\n\t\t\t// per EndpointSubset. This allows for a simple 1:1 mapping between\n\t\t\t// EndpointSubset and EndpointSlice.\n\t\t\tif totalAddressesAdded \u003e= int(r.maxEndpointsPerSubset) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif ok := d.addAddress(address, multiKey, false); ok {\n\t\t\t\ttotalAddressesAdded++\n\t\t\t} else {\n\t\t\t\tnumInvalidAddresses++\n\t\t\t\tklog.Warningf(\"Address in %s/%s Endpoints is not a valid IP, it will not be mirrored to an EndpointSlice: %s\", endpoints.Namespace, endpoints.Name, address.IP)\n\t\t\t}\n\t\t}\n\n\t\taddressesSkipped += totalAddresses - totalAddressesAdded\n\t}\n\n\t// This metric includes addresses skipped for being invalid or exceeding\n\t// MaxEndpointsPerSubset.\n\tmetrics.AddressesSkippedPerSync.WithLabelValues().Observe(float64(addressesSkipped))\n\n\t// Record an event on the Endpoints resource if we skipped mirroring for any\n\t// invalid IP addresses.\n\tif numInvalidAddresses \u003e 0 {\n\t\tr.eventRecorder.Eventf(endpoints, corev1.EventTypeWarning, InvalidIPAddress,\n\t\t\t\"Skipped %d invalid IP addresses when mirroring to EndpointSlices\", numInvalidAddresses)\n\t}\n\n\t// Record a separate event if we skipped mirroring due to the number of\n\t// addresses exceeding MaxEndpointsPerSubset.\n\tif addressesSkipped \u003e numInvalidAddresses {\n\t\tklog.Warningf(\"%d addresses in %s/%s Endpoints were skipped due to exceeding MaxEndpointsPerSubset\", addressesSkipped, endpoints.Namespace, endpoints.Name)\n\t\tr.eventRecorder.Eventf(endpoints, corev1.EventTypeWarning, TooManyAddressesToMirror,\n\t\t\t\"A max of %d addresses can be mirrored to EndpointSlices per Endpoints subset. %d addresses were skipped\", r.maxEndpointsPerSubset, addressesSkipped)\n\t}\n\n\t// Build data structures for existing state.\n\texistingSlicesByKey := endpointSlicesByKey(existingSlices)\n\n\t// Determine changes necessary for each group of slices by port map.\n\tepMetrics := metrics.NewEndpointPortCache()\n\ttotals := totalsByAction{}\n\tslices := slicesByAction{}\n\n\tfor portKey, desiredEndpoints := range d.endpointsByKey {\n\t\tnumEndpoints := len(desiredEndpoints)\n\t\tpmSlices, pmTotals := r.reconcileByPortMapping(\n\t\t\tendpoints, existingSlicesByKey[portKey], desiredEndpoints, d.portsByKey[portKey], portKey.addressType())\n\n\t\tslices.append(pmSlices)\n\t\ttotals.add(pmTotals)\n\n\t\tepMetrics.Set(endpointutil.PortMapKey(portKey), metrics.EfficiencyInfo{\n\t\t\tEndpoints: numEndpoints,\n\t\t\tSlices: len(existingSlicesByKey[portKey]) + len(pmSlices.toCreate) - len(pmSlices.toDelete),\n\t\t})\n\t}\n\n\t// If there are unique sets of ports that are no longer desired, mark\n\t// the corresponding endpoint slices for deletion.\n\tfor portKey, existingSlices := range existingSlicesByKey {\n\t\tif _, ok := d.endpointsByKey[portKey]; !ok {\n\t\t\tfor _, existingSlice := range existingSlices {\n\t\t\t\tslices.toDelete = append(slices.toDelete, existingSlice)\n\t\t\t}\n\t\t}\n\t}\n\n\tmetrics.EndpointsAddedPerSync.WithLabelValues().Observe(float64(totals.added))\n\tmetrics.EndpointsUpdatedPerSync.WithLabelValues().Observe(float64(totals.updated))\n\tmetrics.EndpointsRemovedPerSync.WithLabelValues().Observe(float64(totals.removed))\n\n\tendpointsNN := types.NamespacedName{Name: endpoints.Name, Namespace: endpoints.Namespace}\n\tr.metricsCache.UpdateEndpointPortCache(endpointsNN, epMetrics)\n\n\treturn r.finalize(endpoints, slices)\n}","line":{"from":62,"to":172}} {"id":100003830,"name":"reconcileByPortMapping","signature":"func (r *reconciler) reconcileByPortMapping(","file":"pkg/controller/endpointslicemirroring/reconciler.go","code":"// reconcileByPortMapping compares the endpoints found in existing slices with\n// the list of desired endpoints and returns lists of slices to create, update,\n// and delete.\nfunc (r *reconciler) reconcileByPortMapping(\n\tendpoints *corev1.Endpoints,\n\texistingSlices []*discovery.EndpointSlice,\n\tdesiredSet endpointsliceutil.EndpointSet,\n\tendpointPorts []discovery.EndpointPort,\n\taddressType discovery.AddressType,\n) (slicesByAction, totalsByAction) {\n\tslices := slicesByAction{}\n\ttotals := totalsByAction{}\n\n\t// If no endpoints are desired, mark existing slices for deletion and\n\t// return.\n\tif desiredSet.Len() == 0 {\n\t\tslices.toDelete = existingSlices\n\t\tfor _, epSlice := range existingSlices {\n\t\t\ttotals.removed += len(epSlice.Endpoints)\n\t\t}\n\t\treturn slices, totals\n\t}\n\n\tif len(existingSlices) == 0 {\n\t\t// if no existing slices, all desired endpoints will be added.\n\t\ttotals.added = desiredSet.Len()\n\t} else {\n\t\t// if \u003e0 existing slices, mark all but 1 for deletion.\n\t\tslices.toDelete = existingSlices[1:]\n\n\t\t// generated slices must mirror all endpoints annotations but EndpointsLastChangeTriggerTime and LastAppliedConfigAnnotation\n\t\tcompareAnnotations := cloneAndRemoveKeys(endpoints.Annotations, corev1.EndpointsLastChangeTriggerTime, corev1.LastAppliedConfigAnnotation)\n\t\tcompareLabels := cloneAndRemoveKeys(existingSlices[0].Labels, discovery.LabelManagedBy, discovery.LabelServiceName)\n\t\t// Return early if first slice matches desired endpoints, labels and annotations\n\t\ttotals = totalChanges(existingSlices[0], desiredSet)\n\t\tif totals.added == 0 \u0026\u0026 totals.updated == 0 \u0026\u0026 totals.removed == 0 \u0026\u0026\n\t\t\tapiequality.Semantic.DeepEqual(endpoints.Labels, compareLabels) \u0026\u0026\n\t\t\tapiequality.Semantic.DeepEqual(compareAnnotations, existingSlices[0].Annotations) {\n\t\t\treturn slices, totals\n\t\t}\n\t}\n\n\t// generate a new slice with the desired endpoints.\n\tvar sliceName string\n\tif len(existingSlices) \u003e 0 {\n\t\tsliceName = existingSlices[0].Name\n\t}\n\tnewSlice := newEndpointSlice(endpoints, endpointPorts, addressType, sliceName)\n\tfor desiredSet.Len() \u003e 0 \u0026\u0026 len(newSlice.Endpoints) \u003c int(r.maxEndpointsPerSubset) {\n\t\tendpoint, _ := desiredSet.PopAny()\n\t\tnewSlice.Endpoints = append(newSlice.Endpoints, *endpoint)\n\t}\n\n\tif newSlice.Name != \"\" {\n\t\tslices.toUpdate = []*discovery.EndpointSlice{newSlice}\n\t} else { // Slices to be created set GenerateName instead of Name.\n\t\tslices.toCreate = []*discovery.EndpointSlice{newSlice}\n\t}\n\n\treturn slices, totals\n}","line":{"from":174,"to":234}} {"id":100003831,"name":"finalize","signature":"func (r *reconciler) finalize(endpoints *corev1.Endpoints, slices slicesByAction) error","file":"pkg/controller/endpointslicemirroring/reconciler.go","code":"// finalize creates, updates, and deletes slices as specified\nfunc (r *reconciler) finalize(endpoints *corev1.Endpoints, slices slicesByAction) error {\n\t// If there are slices to create and delete, recycle the slices marked for\n\t// deletion by replacing creates with updates of slices that would otherwise\n\t// be deleted.\n\trecycleSlices(\u0026slices)\n\n\tepsClient := r.client.DiscoveryV1().EndpointSlices(endpoints.Namespace)\n\n\t// Don't create more EndpointSlices if corresponding Endpoints resource is\n\t// being deleted.\n\tif endpoints.DeletionTimestamp == nil {\n\t\tfor _, endpointSlice := range slices.toCreate {\n\t\t\tcreatedSlice, err := epsClient.Create(context.TODO(), endpointSlice, metav1.CreateOptions{})\n\t\t\tif err != nil {\n\t\t\t\t// If the namespace is terminating, creates will continue to fail. Simply drop the item.\n\t\t\t\tif errors.HasStatusCause(err, corev1.NamespaceTerminatingCause) {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn fmt.Errorf(\"failed to create EndpointSlice for Endpoints %s/%s: %v\", endpoints.Namespace, endpoints.Name, err)\n\t\t\t}\n\t\t\tr.endpointSliceTracker.Update(createdSlice)\n\t\t\tmetrics.EndpointSliceChanges.WithLabelValues(\"create\").Inc()\n\t\t}\n\t}\n\n\tfor _, endpointSlice := range slices.toUpdate {\n\t\tupdatedSlice, err := epsClient.Update(context.TODO(), endpointSlice, metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to update %s EndpointSlice for Endpoints %s/%s: %v\", endpointSlice.Name, endpoints.Namespace, endpoints.Name, err)\n\t\t}\n\t\tr.endpointSliceTracker.Update(updatedSlice)\n\t\tmetrics.EndpointSliceChanges.WithLabelValues(\"update\").Inc()\n\t}\n\n\tfor _, endpointSlice := range slices.toDelete {\n\t\terr := epsClient.Delete(context.TODO(), endpointSlice.Name, metav1.DeleteOptions{})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to delete %s EndpointSlice for Endpoints %s/%s: %v\", endpointSlice.Name, endpoints.Namespace, endpoints.Name, err)\n\t\t}\n\t\tr.endpointSliceTracker.ExpectDeletion(endpointSlice)\n\t\tmetrics.EndpointSliceChanges.WithLabelValues(\"delete\").Inc()\n\t}\n\n\treturn nil\n}","line":{"from":236,"to":281}} {"id":100003832,"name":"deleteEndpoints","signature":"func (r *reconciler) deleteEndpoints(namespace, name string, endpointSlices []*discovery.EndpointSlice) error","file":"pkg/controller/endpointslicemirroring/reconciler.go","code":"// deleteEndpoints deletes any associated EndpointSlices and cleans up any\n// Endpoints references from the metricsCache.\nfunc (r *reconciler) deleteEndpoints(namespace, name string, endpointSlices []*discovery.EndpointSlice) error {\n\tr.metricsCache.DeleteEndpoints(types.NamespacedName{Namespace: namespace, Name: name})\n\tvar errs []error\n\tfor _, endpointSlice := range endpointSlices {\n\t\terr := r.client.DiscoveryV1().EndpointSlices(namespace).Delete(context.TODO(), endpointSlice.Name, metav1.DeleteOptions{})\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\tif len(errs) \u003e 0 {\n\t\treturn fmt.Errorf(\"error(s) deleting %d/%d EndpointSlices for %s/%s Endpoints, including: %s\", len(errs), len(endpointSlices), namespace, name, errs[0])\n\t}\n\treturn nil\n}","line":{"from":283,"to":298}} {"id":100003833,"name":"endpointSlicesByKey","signature":"func endpointSlicesByKey(existingSlices []*discovery.EndpointSlice) map[addrTypePortMapKey][]*discovery.EndpointSlice","file":"pkg/controller/endpointslicemirroring/reconciler.go","code":"// endpointSlicesByKey returns a map that groups EndpointSlices by unique\n// addrTypePortMapKey values.\nfunc endpointSlicesByKey(existingSlices []*discovery.EndpointSlice) map[addrTypePortMapKey][]*discovery.EndpointSlice {\n\tslicesByKey := map[addrTypePortMapKey][]*discovery.EndpointSlice{}\n\tfor _, existingSlice := range existingSlices {\n\t\tepKey := newAddrTypePortMapKey(existingSlice.Ports, existingSlice.AddressType)\n\t\tslicesByKey[epKey] = append(slicesByKey[epKey], existingSlice)\n\t}\n\treturn slicesByKey\n}","line":{"from":300,"to":309}} {"id":100003834,"name":"totalChanges","signature":"func totalChanges(existingSlice *discovery.EndpointSlice, desiredSet endpointsliceutil.EndpointSet) totalsByAction","file":"pkg/controller/endpointslicemirroring/reconciler.go","code":"// totalChanges returns the total changes that will be required for an\n// EndpointSlice to match a desired set of endpoints.\nfunc totalChanges(existingSlice *discovery.EndpointSlice, desiredSet endpointsliceutil.EndpointSet) totalsByAction {\n\ttotals := totalsByAction{}\n\texistingMatches := 0\n\n\tfor _, endpoint := range existingSlice.Endpoints {\n\t\tgot := desiredSet.Get(\u0026endpoint)\n\t\tif got == nil {\n\t\t\t// If not desired, increment number of endpoints to be deleted.\n\t\t\ttotals.removed++\n\t\t} else {\n\t\t\texistingMatches++\n\n\t\t\t// If existing version of endpoint doesn't match desired version\n\t\t\t// increment number of endpoints to be updated.\n\t\t\tif !endpointutil.EndpointsEqualBeyondHash(got, \u0026endpoint) {\n\t\t\t\ttotals.updated++\n\t\t\t}\n\t\t}\n\t}\n\n\t// Any desired endpoints that have not been found in the existing slice will\n\t// be added.\n\ttotals.added = desiredSet.Len() - existingMatches\n\treturn totals\n}","line":{"from":311,"to":337}} {"id":100003835,"name":"append","signature":"func (s *slicesByAction) append(slices slicesByAction)","file":"pkg/controller/endpointslicemirroring/reconciler_helpers.go","code":"// append appends slices from another slicesByAction struct.\nfunc (s *slicesByAction) append(slices slicesByAction) {\n\ts.toCreate = append(s.toCreate, slices.toCreate...)\n\ts.toUpdate = append(s.toUpdate, slices.toUpdate...)\n\ts.toDelete = append(s.toDelete, slices.toDelete...)\n}","line":{"from":30,"to":35}} {"id":100003836,"name":"add","signature":"func (t *totalsByAction) add(totals totalsByAction)","file":"pkg/controller/endpointslicemirroring/reconciler_helpers.go","code":"// add adds totals from another totalsByAction struct.\nfunc (t *totalsByAction) add(totals totalsByAction) {\n\tt.added += totals.added\n\tt.updated += totals.updated\n\tt.removed += totals.removed\n}","line":{"from":42,"to":47}} {"id":100003837,"name":"newDesiredCalc","signature":"func newDesiredCalc() *desiredCalc","file":"pkg/controller/endpointslicemirroring/reconciler_helpers.go","code":"// newDesiredCalc initializes and returns a new desiredCalc.\nfunc newDesiredCalc() *desiredCalc {\n\treturn \u0026desiredCalc{\n\t\tportsByKey: map[addrTypePortMapKey][]discovery.EndpointPort{},\n\t\tendpointsByKey: map[addrTypePortMapKey]endpointsliceutil.EndpointSet{},\n\t\tnumDesiredEndpoints: 0,\n\t}\n}","line":{"from":49,"to":56}} {"id":100003838,"name":"initPorts","signature":"func (d *desiredCalc) initPorts(subsetPorts []v1.EndpointPort) multiAddrTypePortMapKey","file":"pkg/controller/endpointslicemirroring/reconciler_helpers.go","code":"// initPorts initializes ports for a subset and address type and returns the\n// corresponding addrTypePortMapKey.\nfunc (d *desiredCalc) initPorts(subsetPorts []v1.EndpointPort) multiAddrTypePortMapKey {\n\tendpointPorts := epPortsToEpsPorts(subsetPorts)\n\taddrTypes := []discovery.AddressType{discovery.AddressTypeIPv4, discovery.AddressTypeIPv6}\n\tmultiKey := multiAddrTypePortMapKey{}\n\n\tfor _, addrType := range addrTypes {\n\t\tmultiKey[addrType] = newAddrTypePortMapKey(endpointPorts, addrType)\n\t\tif _, ok := d.endpointsByKey[multiKey[addrType]]; !ok {\n\t\t\td.endpointsByKey[multiKey[addrType]] = endpointsliceutil.EndpointSet{}\n\t\t}\n\t\td.portsByKey[multiKey[addrType]] = endpointPorts\n\t}\n\n\treturn multiKey\n}","line":{"from":69,"to":85}} {"id":100003839,"name":"addAddress","signature":"func (d *desiredCalc) addAddress(address v1.EndpointAddress, multiKey multiAddrTypePortMapKey, ready bool) bool","file":"pkg/controller/endpointslicemirroring/reconciler_helpers.go","code":"// addAddress adds an EndpointAddress to the desired state if it is valid. It\n// returns false if the address was invalid.\nfunc (d *desiredCalc) addAddress(address v1.EndpointAddress, multiKey multiAddrTypePortMapKey, ready bool) bool {\n\tendpoint := addressToEndpoint(address, ready)\n\taddrType := getAddressType(address.IP)\n\tif addrType == nil {\n\t\treturn false\n\t}\n\n\td.endpointsByKey[multiKey[*addrType]].Insert(endpoint)\n\td.numDesiredEndpoints++\n\treturn true\n}","line":{"from":87,"to":99}} {"id":100003840,"name":"recycleSlices","signature":"func recycleSlices(slices *slicesByAction)","file":"pkg/controller/endpointslicemirroring/reconciler_helpers.go","code":"// recycleSlices will recycle the slices marked for deletion by replacing\n// creates with updates of slices that would otherwise be deleted.\nfunc recycleSlices(slices *slicesByAction) {\n\ttoCreateByAddrType := toSlicesByAddrType(slices.toCreate)\n\ttoDeleteByAddrType := toSlicesByAddrType(slices.toDelete)\n\n\tfor addrType, slicesToCreate := range toCreateByAddrType {\n\t\tslicesToDelete := toDeleteByAddrType[addrType]\n\t\tfor i := 0; len(slicesToCreate) \u003e i \u0026\u0026 len(slicesToDelete) \u003e i; i++ {\n\t\t\tslices.toCreate = removeSlice(slices.toCreate, slicesToCreate[i])\n\t\t\tslices.toDelete = removeSlice(slices.toDelete, slicesToDelete[i])\n\t\t\tslice := slicesToCreate[i]\n\t\t\tslice.Name = slicesToDelete[i].Name\n\t\t\tslices.toUpdate = append(slices.toUpdate, slice)\n\t\t}\n\t}\n}","line":{"from":103,"to":119}} {"id":100003841,"name":"removeSlice","signature":"func removeSlice(slices []*discovery.EndpointSlice, sliceToRemove *discovery.EndpointSlice) []*discovery.EndpointSlice","file":"pkg/controller/endpointslicemirroring/reconciler_helpers.go","code":"// removeSlice removes an EndpointSlice from a list of EndpointSlices.\nfunc removeSlice(slices []*discovery.EndpointSlice, sliceToRemove *discovery.EndpointSlice) []*discovery.EndpointSlice {\n\tfor i, slice := range slices {\n\t\tif slice.Name == sliceToRemove.Name {\n\t\t\treturn append(slices[:i], slices[i+1:]...)\n\t\t}\n\t}\n\treturn slices\n}","line":{"from":121,"to":129}} {"id":100003842,"name":"toSlicesByAddrType","signature":"func toSlicesByAddrType(slices []*discovery.EndpointSlice) slicesByAddrType","file":"pkg/controller/endpointslicemirroring/reconciler_helpers.go","code":"// toSliceByAddrType returns lists of EndpointSlices grouped by address.\nfunc toSlicesByAddrType(slices []*discovery.EndpointSlice) slicesByAddrType {\n\tbyAddrType := slicesByAddrType{}\n\tfor _, slice := range slices {\n\t\tbyAddrType[slice.AddressType] = append(byAddrType[slice.AddressType], slice)\n\t}\n\treturn byAddrType\n}","line":{"from":131,"to":138}} {"id":100003843,"name":"newAddrTypePortMapKey","signature":"func newAddrTypePortMapKey(endpointPorts []discovery.EndpointPort, addrType discovery.AddressType) addrTypePortMapKey","file":"pkg/controller/endpointslicemirroring/utils.go","code":"// newAddrTypePortMapKey generates a PortMapKey from endpoint ports.\nfunc newAddrTypePortMapKey(endpointPorts []discovery.EndpointPort, addrType discovery.AddressType) addrTypePortMapKey {\n\tpmk := fmt.Sprintf(\"%s-%s\", addrType, endpointutil.NewPortMapKey(endpointPorts))\n\treturn addrTypePortMapKey(pmk)\n}","line":{"from":39,"to":43}} {"id":100003844,"name":"addressType","signature":"func (pk addrTypePortMapKey) addressType() discovery.AddressType","file":"pkg/controller/endpointslicemirroring/utils.go","code":"func (pk addrTypePortMapKey) addressType() discovery.AddressType {\n\tif strings.HasPrefix(string(pk), string(discovery.AddressTypeIPv6)) {\n\t\treturn discovery.AddressTypeIPv6\n\t}\n\treturn discovery.AddressTypeIPv4\n}","line":{"from":45,"to":50}} {"id":100003845,"name":"getAddressType","signature":"func getAddressType(address string) *discovery.AddressType","file":"pkg/controller/endpointslicemirroring/utils.go","code":"func getAddressType(address string) *discovery.AddressType {\n\tip := netutils.ParseIPSloppy(address)\n\tif ip == nil {\n\t\treturn nil\n\t}\n\taddressType := discovery.AddressTypeIPv4\n\tif ip.To4() == nil {\n\t\taddressType = discovery.AddressTypeIPv6\n\t}\n\treturn \u0026addressType\n}","line":{"from":52,"to":62}} {"id":100003846,"name":"newEndpointSlice","signature":"func newEndpointSlice(endpoints *corev1.Endpoints, ports []discovery.EndpointPort, addrType discovery.AddressType, sliceName string) *discovery.EndpointSlice","file":"pkg/controller/endpointslicemirroring/utils.go","code":"// newEndpointSlice returns an EndpointSlice generated from an Endpoints\n// resource, ports, and address type.\nfunc newEndpointSlice(endpoints *corev1.Endpoints, ports []discovery.EndpointPort, addrType discovery.AddressType, sliceName string) *discovery.EndpointSlice {\n\tgvk := schema.GroupVersionKind{Version: \"v1\", Kind: \"Endpoints\"}\n\townerRef := metav1.NewControllerRef(endpoints, gvk)\n\tepSlice := \u0026discovery.EndpointSlice{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tLabels: map[string]string{},\n\t\t\tAnnotations: map[string]string{},\n\t\t\tOwnerReferences: []metav1.OwnerReference{*ownerRef},\n\t\t\tNamespace: endpoints.Namespace,\n\t\t},\n\t\tPorts: ports,\n\t\tAddressType: addrType,\n\t\tEndpoints: []discovery.Endpoint{},\n\t}\n\n\t// clone all labels\n\tfor label, val := range endpoints.Labels {\n\t\tepSlice.Labels[label] = val\n\t}\n\n\t// overwrite specific labels\n\tepSlice.Labels[discovery.LabelServiceName] = endpoints.Name\n\tepSlice.Labels[discovery.LabelManagedBy] = controllerName\n\n\t// clone all annotations but EndpointsLastChangeTriggerTime and LastAppliedConfigAnnotation\n\tfor annotation, val := range endpoints.Annotations {\n\t\tif annotation == corev1.EndpointsLastChangeTriggerTime || annotation == corev1.LastAppliedConfigAnnotation {\n\t\t\tcontinue\n\t\t}\n\t\tepSlice.Annotations[annotation] = val\n\t}\n\n\tif sliceName == \"\" {\n\t\tepSlice.GenerateName = getEndpointSlicePrefix(endpoints.Name)\n\t} else {\n\t\tepSlice.Name = sliceName\n\t}\n\n\treturn epSlice\n}","line":{"from":64,"to":105}} {"id":100003847,"name":"getEndpointSlicePrefix","signature":"func getEndpointSlicePrefix(serviceName string) string","file":"pkg/controller/endpointslicemirroring/utils.go","code":"// getEndpointSlicePrefix returns a suitable prefix for an EndpointSlice name.\nfunc getEndpointSlicePrefix(serviceName string) string {\n\t// use the dash (if the name isn't too long) to make the name a bit prettier.\n\tprefix := fmt.Sprintf(\"%s-\", serviceName)\n\tif len(validation.ValidateEndpointSliceName(prefix, true)) != 0 {\n\t\tprefix = serviceName\n\t}\n\treturn prefix\n}","line":{"from":107,"to":115}} {"id":100003848,"name":"addressToEndpoint","signature":"func addressToEndpoint(address corev1.EndpointAddress, ready bool) *discovery.Endpoint","file":"pkg/controller/endpointslicemirroring/utils.go","code":"// addressToEndpoint converts an address from an Endpoints resource to an\n// EndpointSlice endpoint.\nfunc addressToEndpoint(address corev1.EndpointAddress, ready bool) *discovery.Endpoint {\n\tendpoint := \u0026discovery.Endpoint{\n\t\tAddresses: []string{address.IP},\n\t\tConditions: discovery.EndpointConditions{\n\t\t\tReady: \u0026ready,\n\t\t},\n\t\tTargetRef: address.TargetRef,\n\t}\n\n\tif address.NodeName != nil {\n\t\tendpoint.NodeName = address.NodeName\n\t}\n\tif address.Hostname != \"\" {\n\t\tendpoint.Hostname = \u0026address.Hostname\n\t}\n\n\treturn endpoint\n}","line":{"from":117,"to":136}} {"id":100003849,"name":"epPortsToEpsPorts","signature":"func epPortsToEpsPorts(epPorts []corev1.EndpointPort) []discovery.EndpointPort","file":"pkg/controller/endpointslicemirroring/utils.go","code":"// epPortsToEpsPorts converts ports from an Endpoints resource to ports for an\n// EndpointSlice resource.\nfunc epPortsToEpsPorts(epPorts []corev1.EndpointPort) []discovery.EndpointPort {\n\tepsPorts := []discovery.EndpointPort{}\n\tfor _, epPort := range epPorts {\n\t\tepp := epPort.DeepCopy()\n\t\tepsPorts = append(epsPorts, discovery.EndpointPort{\n\t\t\tName: \u0026epp.Name,\n\t\t\tPort: \u0026epp.Port,\n\t\t\tProtocol: \u0026epp.Protocol,\n\t\t\tAppProtocol: epp.AppProtocol,\n\t\t})\n\t}\n\treturn epsPorts\n}","line":{"from":138,"to":152}} {"id":100003850,"name":"getServiceFromDeleteAction","signature":"func getServiceFromDeleteAction(obj interface{}) *corev1.Service","file":"pkg/controller/endpointslicemirroring/utils.go","code":"// getServiceFromDeleteAction parses a Service resource from a delete\n// action.\nfunc getServiceFromDeleteAction(obj interface{}) *corev1.Service {\n\tif service, ok := obj.(*corev1.Service); ok {\n\t\treturn service\n\t}\n\t// If we reached here it means the Service was deleted but its final state\n\t// is unrecorded.\n\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get object from tombstone %#v\", obj))\n\t\treturn nil\n\t}\n\tservice, ok := tombstone.Obj.(*corev1.Service)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"tombstone contained object that is not a Service resource: %#v\", obj))\n\t\treturn nil\n\t}\n\treturn service\n}","line":{"from":154,"to":173}} {"id":100003851,"name":"getEndpointsFromDeleteAction","signature":"func getEndpointsFromDeleteAction(obj interface{}) *corev1.Endpoints","file":"pkg/controller/endpointslicemirroring/utils.go","code":"// getEndpointsFromDeleteAction parses an Endpoints resource from a delete\n// action.\nfunc getEndpointsFromDeleteAction(obj interface{}) *corev1.Endpoints {\n\tif endpoints, ok := obj.(*corev1.Endpoints); ok {\n\t\treturn endpoints\n\t}\n\t// If we reached here it means the Endpoints resource was deleted but its\n\t// final state is unrecorded.\n\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get object from tombstone %#v\", obj))\n\t\treturn nil\n\t}\n\tendpoints, ok := tombstone.Obj.(*corev1.Endpoints)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"tombstone contained object that is not an Endpoints resource: %#v\", obj))\n\t\treturn nil\n\t}\n\treturn endpoints\n}","line":{"from":175,"to":194}} {"id":100003852,"name":"getEndpointSliceFromDeleteAction","signature":"func getEndpointSliceFromDeleteAction(obj interface{}) *discovery.EndpointSlice","file":"pkg/controller/endpointslicemirroring/utils.go","code":"// getEndpointSliceFromDeleteAction parses an EndpointSlice from a delete action.\nfunc getEndpointSliceFromDeleteAction(obj interface{}) *discovery.EndpointSlice {\n\tif endpointSlice, ok := obj.(*discovery.EndpointSlice); ok {\n\t\treturn endpointSlice\n\t}\n\t// If we reached here it means the EndpointSlice was deleted but its final\n\t// state is unrecorded.\n\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get object from tombstone %#v\", obj))\n\t\treturn nil\n\t}\n\tendpointSlice, ok := tombstone.Obj.(*discovery.EndpointSlice)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"tombstone contained object that is not an EndpointSlice resource: %#v\", obj))\n\t\treturn nil\n\t}\n\treturn endpointSlice\n}","line":{"from":196,"to":214}} {"id":100003853,"name":"endpointsControllerKey","signature":"func endpointsControllerKey(endpointSlice *discovery.EndpointSlice) (string, error)","file":"pkg/controller/endpointslicemirroring/utils.go","code":"// endpointsControllerKey returns a controller key for an Endpoints resource but\n// derived from an EndpointSlice.\nfunc endpointsControllerKey(endpointSlice *discovery.EndpointSlice) (string, error) {\n\tif endpointSlice == nil {\n\t\treturn \"\", fmt.Errorf(\"nil EndpointSlice passed to serviceControllerKey()\")\n\t}\n\tserviceName, ok := endpointSlice.Labels[discovery.LabelServiceName]\n\tif !ok || serviceName == \"\" {\n\t\treturn \"\", fmt.Errorf(\"EndpointSlice missing %s label\", discovery.LabelServiceName)\n\t}\n\treturn fmt.Sprintf(\"%s/%s\", endpointSlice.Namespace, serviceName), nil\n}","line":{"from":216,"to":227}} {"id":100003854,"name":"skipMirror","signature":"func skipMirror(labels map[string]string) bool","file":"pkg/controller/endpointslicemirroring/utils.go","code":"// skipMirror return true if the LabelSkipMirror label has been set to\n// \"true\".\nfunc skipMirror(labels map[string]string) bool {\n\tskipMirror, _ := labels[discovery.LabelSkipMirror]\n\treturn skipMirror == \"true\"\n}","line":{"from":229,"to":234}} {"id":100003855,"name":"hasLeaderElection","signature":"func hasLeaderElection(annotations map[string]string) bool","file":"pkg/controller/endpointslicemirroring/utils.go","code":"// hasLeaderElection returns true if the LeaderElectionRecordAnnotationKey is\n// set as an annotation.\nfunc hasLeaderElection(annotations map[string]string) bool {\n\t_, ok := annotations[resourcelock.LeaderElectionRecordAnnotationKey]\n\treturn ok\n}","line":{"from":236,"to":241}} {"id":100003856,"name":"cloneAndRemoveKeys","signature":"func cloneAndRemoveKeys(a map[string]string, keys ...string) map[string]string","file":"pkg/controller/endpointslicemirroring/utils.go","code":"// cloneAndRemoveKeys is a copy of CloneAndRemoveLabels\n// it is used here for annotations and labels\nfunc cloneAndRemoveKeys(a map[string]string, keys ...string) map[string]string {\n\tif len(keys) == 0 {\n\t\t// Don't need to remove a key.\n\t\treturn a\n\t}\n\t// Clone.\n\tnewMap := map[string]string{}\n\tfor k, v := range a {\n\t\tnewMap[k] = v\n\t}\n\t// remove keys\n\tfor _, key := range keys {\n\t\tdelete(newMap, key)\n\t}\n\treturn newMap\n}","line":{"from":243,"to":260}} {"id":100003857,"name":"managedByChanged","signature":"func managedByChanged(endpointSlice1, endpointSlice2 *discovery.EndpointSlice) bool","file":"pkg/controller/endpointslicemirroring/utils.go","code":"// managedByChanged returns true if one of the provided EndpointSlices is\n// managed by the EndpointSlice controller while the other is not.\nfunc managedByChanged(endpointSlice1, endpointSlice2 *discovery.EndpointSlice) bool {\n\treturn managedByController(endpointSlice1) != managedByController(endpointSlice2)\n}","line":{"from":262,"to":266}} {"id":100003858,"name":"managedByController","signature":"func managedByController(endpointSlice *discovery.EndpointSlice) bool","file":"pkg/controller/endpointslicemirroring/utils.go","code":"// managedByController returns true if the controller of the provided\n// EndpointSlices is the EndpointSlice controller.\nfunc managedByController(endpointSlice *discovery.EndpointSlice) bool {\n\tmanagedBy, _ := endpointSlice.Labels[discovery.LabelManagedBy]\n\treturn managedBy == controllerName\n}","line":{"from":268,"to":273}} {"id":100003859,"name":"Convert_v1alpha1_GarbageCollectorControllerConfiguration_To_config_GarbageCollectorControllerConfiguration","signature":"func Convert_v1alpha1_GarbageCollectorControllerConfiguration_To_config_GarbageCollectorControllerConfiguration(in *v1alpha1.GarbageCollectorControllerConfiguration, out *config.GarbageCollectorControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/garbagecollector/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_GarbageCollectorControllerConfiguration_To_config_GarbageCollectorControllerConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_GarbageCollectorControllerConfiguration_To_config_GarbageCollectorControllerConfiguration(in *v1alpha1.GarbageCollectorControllerConfiguration, out *config.GarbageCollectorControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_GarbageCollectorControllerConfiguration_To_config_GarbageCollectorControllerConfiguration(in, out, s)\n}","line":{"from":32,"to":35}} {"id":100003860,"name":"Convert_config_GarbageCollectorControllerConfiguration_To_v1alpha1_GarbageCollectorControllerConfiguration","signature":"func Convert_config_GarbageCollectorControllerConfiguration_To_v1alpha1_GarbageCollectorControllerConfiguration(in *config.GarbageCollectorControllerConfiguration, out *v1alpha1.GarbageCollectorControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/garbagecollector/config/v1alpha1/conversion.go","code":"// Convert_config_GarbageCollectorControllerConfiguration_To_v1alpha1_GarbageCollectorControllerConfiguration is an autogenerated conversion function.\nfunc Convert_config_GarbageCollectorControllerConfiguration_To_v1alpha1_GarbageCollectorControllerConfiguration(in *config.GarbageCollectorControllerConfiguration, out *v1alpha1.GarbageCollectorControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_GarbageCollectorControllerConfiguration_To_v1alpha1_GarbageCollectorControllerConfiguration(in, out, s)\n}","line":{"from":37,"to":40}} {"id":100003861,"name":"RecommendedDefaultGarbageCollectorControllerConfiguration","signature":"func RecommendedDefaultGarbageCollectorControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.GarbageCollectorControllerConfiguration)","file":"pkg/controller/garbagecollector/config/v1alpha1/defaults.go","code":"// RecommendedDefaultGarbageCollectorControllerConfiguration defaults a pointer to a\n// GarbageCollectorControllerConfiguration struct. This will set the recommended default\n// values, but they may be subject to change between API versions. This function\n// is intentionally not registered in the scheme as a \"normal\" `SetDefaults_Foo`\n// function to allow consumers of this type to set whatever defaults for their\n// embedded configs. Forcing consumers to use these defaults would be problematic\n// as defaulting in the scheme is done as part of the conversion, and there would\n// be no easy way to opt-out. Instead, if you want to use this defaulting method\n// run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDefaultGarbageCollectorControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.GarbageCollectorControllerConfiguration) {\n\tif obj.EnableGarbageCollector == nil {\n\t\tobj.EnableGarbageCollector = pointer.Bool(true)\n\t}\n\tif obj.ConcurrentGCSyncs == 0 {\n\t\tobj.ConcurrentGCSyncs = 20\n\t}\n}","line":{"from":24,"to":40}} {"id":100003862,"name":"MarshalDOT","signature":"func (v *dotVertex) MarshalDOT(w io.Writer) error","file":"pkg/controller/garbagecollector/dump.go","code":"func (v *dotVertex) MarshalDOT(w io.Writer) error {\n\tattrs := v.Attributes()\n\tif _, err := fmt.Fprintf(w, \" %q [\\n\", v.uid); err != nil {\n\t\treturn err\n\t}\n\tfor _, a := range attrs {\n\t\tif _, err := fmt.Fprintf(w, \" %s=%q\\n\", a.Key, a.Value); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif _, err := fmt.Fprintf(w, \" ];\\n\"); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":44,"to":58}} {"id":100003863,"name":"String","signature":"func (v *dotVertex) String() string","file":"pkg/controller/garbagecollector/dump.go","code":"func (v *dotVertex) String() string {\n\tkind := v.gvk.Kind + \".\" + v.gvk.Version\n\tif len(v.gvk.Group) \u003e 0 {\n\t\tkind = kind + \".\" + v.gvk.Group\n\t}\n\tmissing := \"\"\n\tif v.missingFromGraph {\n\t\tmissing = \"(missing)\"\n\t}\n\tdeleting := \"\"\n\tif v.beingDeleted {\n\t\tdeleting = \"(deleting)\"\n\t}\n\tdeletingDependents := \"\"\n\tif v.deletingDependents {\n\t\tdeleting = \"(deletingDependents)\"\n\t}\n\tvirtual := \"\"\n\tif v.virtual {\n\t\tvirtual = \"(virtual)\"\n\t}\n\treturn fmt.Sprintf(`%s/%s[%s]-%v%s%s%s%s`, kind, v.name, v.namespace, v.uid, missing, deleting, deletingDependents, virtual)\n}","line":{"from":60,"to":82}} {"id":100003864,"name":"Attributes","signature":"func (v *dotVertex) Attributes() []attribute","file":"pkg/controller/garbagecollector/dump.go","code":"func (v *dotVertex) Attributes() []attribute {\n\tkubectlString := v.gvk.Kind + \".\" + v.gvk.Version\n\tif len(v.gvk.Group) \u003e 0 {\n\t\tkubectlString = kubectlString + \".\" + v.gvk.Group\n\t}\n\tkubectlString = kubectlString + \"/\" + v.name\n\n\tlabel := fmt.Sprintf(`uid=%v\nnamespace=%v\n%v\n`,\n\t\tv.uid,\n\t\tv.namespace,\n\t\tkubectlString,\n\t)\n\n\tconditionStrings := []string{}\n\tif v.beingDeleted {\n\t\tconditionStrings = append(conditionStrings, \"beingDeleted\")\n\t}\n\tif v.deletingDependents {\n\t\tconditionStrings = append(conditionStrings, \"deletingDependents\")\n\t}\n\tif v.virtual {\n\t\tconditionStrings = append(conditionStrings, \"virtual\")\n\t}\n\tif v.missingFromGraph {\n\t\tconditionStrings = append(conditionStrings, \"missingFromGraph\")\n\t}\n\tconditionString := strings.Join(conditionStrings, \",\")\n\tif len(conditionString) \u003e 0 {\n\t\tlabel = label + conditionString + \"\\n\"\n\t}\n\n\treturn []attribute{\n\t\t{Key: \"label\", Value: label},\n\t\t// these place metadata in the correct location, but don't conform to any normal attribute for rendering\n\t\t{Key: \"group\", Value: v.gvk.Group},\n\t\t{Key: \"version\", Value: v.gvk.Version},\n\t\t{Key: \"kind\", Value: v.gvk.Kind},\n\t\t{Key: \"namespace\", Value: v.namespace},\n\t\t{Key: \"name\", Value: v.name},\n\t\t{Key: \"uid\", Value: string(v.uid)},\n\t\t{Key: \"missing\", Value: fmt.Sprintf(`%v`, v.missingFromGraph)},\n\t\t{Key: \"beingDeleted\", Value: fmt.Sprintf(`%v`, v.beingDeleted)},\n\t\t{Key: \"deletingDependents\", Value: fmt.Sprintf(`%v`, v.deletingDependents)},\n\t\t{Key: \"virtual\", Value: fmt.Sprintf(`%v`, v.virtual)},\n\t}\n}","line":{"from":89,"to":137}} {"id":100003865,"name":"NewDOTVertex","signature":"func NewDOTVertex(node *node) *dotVertex","file":"pkg/controller/garbagecollector/dump.go","code":"// NewDOTVertex creates a new dotVertex.\nfunc NewDOTVertex(node *node) *dotVertex {\n\tgv, err := schema.ParseGroupVersion(node.identity.APIVersion)\n\tif err != nil {\n\t\t// this indicates a bad data serialization that should be prevented during storage of the API\n\t\tutilruntime.HandleError(err)\n\t}\n\treturn \u0026dotVertex{\n\t\tuid: node.identity.UID,\n\t\tgvk: gv.WithKind(node.identity.Kind),\n\t\tnamespace: node.identity.Namespace,\n\t\tname: node.identity.Name,\n\t\tbeingDeleted: node.beingDeleted,\n\t\tdeletingDependents: node.deletingDependents,\n\t\tvirtual: node.virtual,\n\t}\n}","line":{"from":139,"to":155}} {"id":100003866,"name":"NewMissingdotVertex","signature":"func NewMissingdotVertex(ownerRef metav1.OwnerReference) *dotVertex","file":"pkg/controller/garbagecollector/dump.go","code":"// NewMissingdotVertex creates a new dotVertex.\nfunc NewMissingdotVertex(ownerRef metav1.OwnerReference) *dotVertex {\n\tgv, err := schema.ParseGroupVersion(ownerRef.APIVersion)\n\tif err != nil {\n\t\t// this indicates a bad data serialization that should be prevented during storage of the API\n\t\tutilruntime.HandleError(err)\n\t}\n\treturn \u0026dotVertex{\n\t\tuid: ownerRef.UID,\n\t\tgvk: gv.WithKind(ownerRef.Kind),\n\t\tname: ownerRef.Name,\n\t\tmissingFromGraph: true,\n\t}\n}","line":{"from":157,"to":170}} {"id":100003867,"name":"ToDOTNodesAndEdges","signature":"func (m *concurrentUIDToNode) ToDOTNodesAndEdges() ([]*dotVertex, []dotEdge)","file":"pkg/controller/garbagecollector/dump.go","code":"func (m *concurrentUIDToNode) ToDOTNodesAndEdges() ([]*dotVertex, []dotEdge) {\n\tm.uidToNodeLock.Lock()\n\tdefer m.uidToNodeLock.Unlock()\n\n\treturn toDOTNodesAndEdges(m.uidToNode)\n}","line":{"from":172,"to":177}} {"id":100003868,"name":"MarshalDOT","signature":"func (e dotEdge) MarshalDOT(w io.Writer) error","file":"pkg/controller/garbagecollector/dump.go","code":"func (e dotEdge) MarshalDOT(w io.Writer) error {\n\t_, err := fmt.Fprintf(w, \" %q -\u003e %q;\\n\", e.F, e.T)\n\treturn err\n}","line":{"from":184,"to":187}} {"id":100003869,"name":"toDOTNodesAndEdges","signature":"func toDOTNodesAndEdges(uidToNode map[types.UID]*node) ([]*dotVertex, []dotEdge)","file":"pkg/controller/garbagecollector/dump.go","code":"func toDOTNodesAndEdges(uidToNode map[types.UID]*node) ([]*dotVertex, []dotEdge) {\n\tnodes := []*dotVertex{}\n\tedges := []dotEdge{}\n\n\tuidToVertex := map[types.UID]*dotVertex{}\n\n\t// add the vertices first, then edges. That avoids having to deal with missing refs.\n\tfor _, node := range uidToNode {\n\t\t// skip adding objects that don't have owner references and aren't referred to.\n\t\tif len(node.dependents) == 0 \u0026\u0026 len(node.owners) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tvertex := NewDOTVertex(node)\n\t\tuidToVertex[node.identity.UID] = vertex\n\t\tnodes = append(nodes, vertex)\n\t}\n\tfor _, node := range uidToNode {\n\t\tcurrVertex := uidToVertex[node.identity.UID]\n\t\tfor _, ownerRef := range node.owners {\n\t\t\tcurrOwnerVertex, ok := uidToVertex[ownerRef.UID]\n\t\t\tif !ok {\n\t\t\t\tcurrOwnerVertex = NewMissingdotVertex(ownerRef)\n\t\t\t\tuidToVertex[node.identity.UID] = currOwnerVertex\n\t\t\t\tnodes = append(nodes, currOwnerVertex)\n\t\t\t}\n\t\t\tedges = append(edges, dotEdge{F: currVertex.uid, T: currOwnerVertex.uid})\n\t\t}\n\t}\n\n\tsort.SliceStable(nodes, func(i, j int) bool { return nodes[i].uid \u003c nodes[j].uid })\n\tsort.SliceStable(edges, func(i, j int) bool {\n\t\tif edges[i].F != edges[j].F {\n\t\t\treturn edges[i].F \u003c edges[j].F\n\t\t}\n\t\treturn edges[i].T \u003c edges[j].T\n\t})\n\n\treturn nodes, edges\n}","line":{"from":189,"to":227}} {"id":100003870,"name":"ToDOTNodesAndEdgesForObj","signature":"func (m *concurrentUIDToNode) ToDOTNodesAndEdgesForObj(uids ...types.UID) ([]*dotVertex, []dotEdge)","file":"pkg/controller/garbagecollector/dump.go","code":"func (m *concurrentUIDToNode) ToDOTNodesAndEdgesForObj(uids ...types.UID) ([]*dotVertex, []dotEdge) {\n\tm.uidToNodeLock.Lock()\n\tdefer m.uidToNodeLock.Unlock()\n\n\treturn toDOTNodesAndEdgesForObj(m.uidToNode, uids...)\n}","line":{"from":229,"to":234}} {"id":100003871,"name":"toDOTNodesAndEdgesForObj","signature":"func toDOTNodesAndEdgesForObj(uidToNode map[types.UID]*node, uids ...types.UID) ([]*dotVertex, []dotEdge)","file":"pkg/controller/garbagecollector/dump.go","code":"func toDOTNodesAndEdgesForObj(uidToNode map[types.UID]*node, uids ...types.UID) ([]*dotVertex, []dotEdge) {\n\tuidsToCheck := append([]types.UID{}, uids...)\n\tinterestingNodes := map[types.UID]*node{}\n\n\t// build the set of nodes to inspect first, then use the normal construction on the subset\n\tfor i := 0; i \u003c len(uidsToCheck); i++ {\n\t\tuid := uidsToCheck[i]\n\t\t// if we've already been observed, there was a bug, but skip it so we don't loop forever\n\t\tif _, ok := interestingNodes[uid]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tnode, ok := uidToNode[uid]\n\t\t// if there is no node for the UID, skip over it. We may add it to the list multiple times\n\t\t// but we won't loop forever and hopefully the condition doesn't happen very often\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tinterestingNodes[node.identity.UID] = node\n\n\t\tfor _, ownerRef := range node.owners {\n\t\t\t// if we've already inspected this UID, don't add it to be inspected again\n\t\t\tif _, ok := interestingNodes[ownerRef.UID]; ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tuidsToCheck = append(uidsToCheck, ownerRef.UID)\n\t\t}\n\t\tfor dependent := range node.dependents {\n\t\t\t// if we've already inspected this UID, don't add it to be inspected again\n\t\t\tif _, ok := interestingNodes[dependent.identity.UID]; ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tuidsToCheck = append(uidsToCheck, dependent.identity.UID)\n\t\t}\n\t}\n\n\treturn toDOTNodesAndEdges(interestingNodes)\n}","line":{"from":236,"to":273}} {"id":100003872,"name":"NewDebugHandler","signature":"func NewDebugHandler(controller *GarbageCollector) http.Handler","file":"pkg/controller/garbagecollector/dump.go","code":"// NewDebugHandler creates a new debugHTTPHandler.\nfunc NewDebugHandler(controller *GarbageCollector) http.Handler {\n\treturn \u0026debugHTTPHandler{controller: controller}\n}","line":{"from":275,"to":278}} {"id":100003873,"name":"marshalDOT","signature":"func marshalDOT(w io.Writer, nodes []*dotVertex, edges []dotEdge) error","file":"pkg/controller/garbagecollector/dump.go","code":"func marshalDOT(w io.Writer, nodes []*dotVertex, edges []dotEdge) error {\n\tif _, err := w.Write([]byte(\"strict digraph full {\\n\")); err != nil {\n\t\treturn err\n\t}\n\tif len(nodes) \u003e 0 {\n\t\tif _, err := w.Write([]byte(\" // Node definitions.\\n\")); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, node := range nodes {\n\t\t\tif err := node.MarshalDOT(w); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\tif len(edges) \u003e 0 {\n\t\tif _, err := w.Write([]byte(\" // Edge definitions.\\n\")); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, edge := range edges {\n\t\t\tif err := edge.MarshalDOT(w); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\tif _, err := w.Write([]byte(\"}\\n\")); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":284,"to":312}} {"id":100003874,"name":"ServeHTTP","signature":"func (h *debugHTTPHandler) ServeHTTP(w http.ResponseWriter, req *http.Request)","file":"pkg/controller/garbagecollector/dump.go","code":"func (h *debugHTTPHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tif req.URL.Path != \"/graph\" {\n\t\thttp.Error(w, \"\", http.StatusNotFound)\n\t\treturn\n\t}\n\n\tvar nodes []*dotVertex\n\tvar edges []dotEdge\n\tif uidStrings := req.URL.Query()[\"uid\"]; len(uidStrings) \u003e 0 {\n\t\tuids := []types.UID{}\n\t\tfor _, uidString := range uidStrings {\n\t\t\tuids = append(uids, types.UID(uidString))\n\t\t}\n\t\tnodes, edges = h.controller.dependencyGraphBuilder.uidToNode.ToDOTNodesAndEdgesForObj(uids...)\n\n\t} else {\n\t\tnodes, edges = h.controller.dependencyGraphBuilder.uidToNode.ToDOTNodesAndEdges()\n\t}\n\n\tb := bytes.NewBuffer(nil)\n\tif err := marshalDOT(b, nodes, edges); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"text/vnd.graphviz\")\n\tw.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\tw.Write(b.Bytes())\n\tw.WriteHeader(http.StatusOK)\n}","line":{"from":314,"to":343}} {"id":100003875,"name":"DebuggingHandler","signature":"func (gc *GarbageCollector) DebuggingHandler() http.Handler","file":"pkg/controller/garbagecollector/dump.go","code":"func (gc *GarbageCollector) DebuggingHandler() http.Handler {\n\treturn NewDebugHandler(gc)\n}","line":{"from":345,"to":347}} {"id":100003876,"name":"Error","signature":"func (r *restMappingError) Error() string","file":"pkg/controller/garbagecollector/errors.go","code":"func (r *restMappingError) Error() string {\n\tversionKind := fmt.Sprintf(\"%s/%s\", r.version, r.kind)\n\treturn fmt.Sprintf(\"unable to get REST mapping for %s.\", versionKind)\n}","line":{"from":28,"to":31}} {"id":100003877,"name":"Message","signature":"func (r *restMappingError) Message() string","file":"pkg/controller/garbagecollector/errors.go","code":"// Message prints more details\nfunc (r *restMappingError) Message() string {\n\tversionKind := fmt.Sprintf(\"%s/%s\", r.version, r.kind)\n\terrMsg := fmt.Sprintf(\"unable to get REST mapping for %s. \", versionKind)\n\terrMsg += fmt.Sprintf(\" If %s is an invalid resource, then you should manually remove ownerReferences that refer %s objects.\", versionKind, versionKind)\n\treturn errMsg\n}","line":{"from":33,"to":39}} {"id":100003878,"name":"newRESTMappingError","signature":"func newRESTMappingError(kind, version string) *restMappingError","file":"pkg/controller/garbagecollector/errors.go","code":"func newRESTMappingError(kind, version string) *restMappingError {\n\treturn \u0026restMappingError{kind: kind, version: version}\n}","line":{"from":41,"to":43}} {"id":100003879,"name":"NewGarbageCollector","signature":"func NewGarbageCollector(","file":"pkg/controller/garbagecollector/garbagecollector.go","code":"// NewGarbageCollector creates a new GarbageCollector.\nfunc NewGarbageCollector(\n\tkubeClient clientset.Interface,\n\tmetadataClient metadata.Interface,\n\tmapper meta.ResettableRESTMapper,\n\tignoredResources map[schema.GroupResource]struct{},\n\tsharedInformers informerfactory.InformerFactory,\n\tinformersStarted \u003c-chan struct{},\n) (*GarbageCollector, error) {\n\n\teventBroadcaster := record.NewBroadcaster()\n\teventRecorder := eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"garbage-collector-controller\"})\n\n\tattemptToDelete := workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"garbage_collector_attempt_to_delete\")\n\tattemptToOrphan := workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"garbage_collector_attempt_to_orphan\")\n\tabsentOwnerCache := NewReferenceCache(500)\n\tgc := \u0026GarbageCollector{\n\t\tmetadataClient: metadataClient,\n\t\trestMapper: mapper,\n\t\tattemptToDelete: attemptToDelete,\n\t\tattemptToOrphan: attemptToOrphan,\n\t\tabsentOwnerCache: absentOwnerCache,\n\t\tkubeClient: kubeClient,\n\t\teventBroadcaster: eventBroadcaster,\n\t}\n\tgc.dependencyGraphBuilder = \u0026GraphBuilder{\n\t\teventRecorder: eventRecorder,\n\t\tmetadataClient: metadataClient,\n\t\tinformersStarted: informersStarted,\n\t\trestMapper: mapper,\n\t\tgraphChanges: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"garbage_collector_graph_changes\"),\n\t\tuidToNode: \u0026concurrentUIDToNode{\n\t\t\tuidToNode: make(map[types.UID]*node),\n\t\t},\n\t\tattemptToDelete: attemptToDelete,\n\t\tattemptToOrphan: attemptToOrphan,\n\t\tabsentOwnerCache: absentOwnerCache,\n\t\tsharedInformers: sharedInformers,\n\t\tignoredResources: ignoredResources,\n\t}\n\n\tmetrics.Register()\n\n\treturn gc, nil\n}","line":{"from":86,"to":130}} {"id":100003880,"name":"resyncMonitors","signature":"func (gc *GarbageCollector) resyncMonitors(logger klog.Logger, deletableResources map[schema.GroupVersionResource]struct{}) error","file":"pkg/controller/garbagecollector/garbagecollector.go","code":"// resyncMonitors starts or stops resource monitors as needed to ensure that all\n// (and only) those resources present in the map are monitored.\nfunc (gc *GarbageCollector) resyncMonitors(logger klog.Logger, deletableResources map[schema.GroupVersionResource]struct{}) error {\n\tif err := gc.dependencyGraphBuilder.syncMonitors(logger, deletableResources); err != nil {\n\t\treturn err\n\t}\n\tgc.dependencyGraphBuilder.startMonitors(logger)\n\treturn nil\n}","line":{"from":132,"to":140}} {"id":100003881,"name":"Run","signature":"func (gc *GarbageCollector) Run(ctx context.Context, workers int)","file":"pkg/controller/garbagecollector/garbagecollector.go","code":"// Run starts garbage collector workers.\nfunc (gc *GarbageCollector) Run(ctx context.Context, workers int) {\n\tdefer utilruntime.HandleCrash()\n\tdefer gc.attemptToDelete.ShutDown()\n\tdefer gc.attemptToOrphan.ShutDown()\n\tdefer gc.dependencyGraphBuilder.graphChanges.ShutDown()\n\n\t// Start events processing pipeline.\n\tgc.eventBroadcaster.StartStructuredLogging(0)\n\tgc.eventBroadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: gc.kubeClient.CoreV1().Events(\"\")})\n\tdefer gc.eventBroadcaster.Shutdown()\n\n\tlogger := klog.FromContext(ctx)\n\tlogger.Info(\"Starting controller\", \"controller\", \"garbagecollector\")\n\tdefer logger.Info(\"Shutting down controller\", \"controller\", \"garbagecollector\")\n\n\tgo gc.dependencyGraphBuilder.Run(ctx)\n\n\tif !cache.WaitForNamedCacheSync(\"garbage collector\", ctx.Done(), func() bool {\n\t\treturn gc.dependencyGraphBuilder.IsSynced(logger)\n\t}) {\n\t\treturn\n\t}\n\n\tlogger.Info(\"All resource monitors have synced. Proceeding to collect garbage\")\n\n\t// gc workers\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.UntilWithContext(ctx, gc.runAttemptToDeleteWorker, 1*time.Second)\n\t\tgo wait.Until(func() { gc.runAttemptToOrphanWorker(logger) }, 1*time.Second, ctx.Done())\n\t}\n\n\t\u003c-ctx.Done()\n}","line":{"from":142,"to":175}} {"id":100003882,"name":"Sync","signature":"func (gc *GarbageCollector) Sync(ctx context.Context, discoveryClient discovery.ServerResourcesInterface, period time.Duration)","file":"pkg/controller/garbagecollector/garbagecollector.go","code":"// Sync periodically resyncs the garbage collector when new resources are\n// observed from discovery. When new resources are detected, Sync will stop all\n// GC workers, reset gc.restMapper, and resync the monitors.\n//\n// Note that discoveryClient should NOT be shared with gc.restMapper, otherwise\n// the mapper's underlying discovery client will be unnecessarily reset during\n// the course of detecting new resources.\nfunc (gc *GarbageCollector) Sync(ctx context.Context, discoveryClient discovery.ServerResourcesInterface, period time.Duration) {\n\toldResources := make(map[schema.GroupVersionResource]struct{})\n\twait.UntilWithContext(ctx, func(ctx context.Context) {\n\t\tlogger := klog.FromContext(ctx)\n\n\t\t// Get the current resource list from discovery.\n\t\tnewResources := GetDeletableResources(discoveryClient)\n\n\t\t// This can occur if there is an internal error in GetDeletableResources.\n\t\tif len(newResources) == 0 {\n\t\t\tlogger.V(2).Info(\"no resources reported by discovery, skipping garbage collector sync\")\n\t\t\tmetrics.GarbageCollectorResourcesSyncError.Inc()\n\t\t\treturn\n\t\t}\n\n\t\t// Decide whether discovery has reported a change.\n\t\tif reflect.DeepEqual(oldResources, newResources) {\n\t\t\tlogger.V(5).Info(\"no resource updates from discovery, skipping garbage collector sync\")\n\t\t\treturn\n\t\t}\n\n\t\t// Ensure workers are paused to avoid processing events before informers\n\t\t// have resynced.\n\t\tgc.workerLock.Lock()\n\t\tdefer gc.workerLock.Unlock()\n\n\t\t// Once we get here, we should not unpause workers until we've successfully synced\n\t\tattempt := 0\n\t\twait.PollImmediateUntilWithContext(ctx, 100*time.Millisecond, func(ctx context.Context) (bool, error) {\n\t\t\tattempt++\n\n\t\t\t// On a reattempt, check if available resources have changed\n\t\t\tif attempt \u003e 1 {\n\t\t\t\tnewResources = GetDeletableResources(discoveryClient)\n\t\t\t\tif len(newResources) == 0 {\n\t\t\t\t\tlogger.V(2).Info(\"no resources reported by discovery\", \"attempt\", attempt)\n\t\t\t\t\tmetrics.GarbageCollectorResourcesSyncError.Inc()\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlogger.V(2).Info(\n\t\t\t\t\"syncing garbage collector with updated resources from discovery\",\n\t\t\t\t\"attempt\", attempt,\n\t\t\t\t\"diff\", printDiff(oldResources, newResources),\n\t\t\t)\n\n\t\t\t// Resetting the REST mapper will also invalidate the underlying discovery\n\t\t\t// client. This is a leaky abstraction and assumes behavior about the REST\n\t\t\t// mapper, but we'll deal with it for now.\n\t\t\tgc.restMapper.Reset()\n\t\t\tlogger.V(4).Info(\"reset restmapper\")\n\n\t\t\t// Perform the monitor resync and wait for controllers to report cache sync.\n\t\t\t//\n\t\t\t// NOTE: It's possible that newResources will diverge from the resources\n\t\t\t// discovered by restMapper during the call to Reset, since they are\n\t\t\t// distinct discovery clients invalidated at different times. For example,\n\t\t\t// newResources may contain resources not returned in the restMapper's\n\t\t\t// discovery call if the resources appeared in-between the calls. In that\n\t\t\t// case, the restMapper will fail to map some of newResources until the next\n\t\t\t// attempt.\n\t\t\tif err := gc.resyncMonitors(logger, newResources); err != nil {\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"failed to sync resource monitors (attempt %d): %v\", attempt, err))\n\t\t\t\tmetrics.GarbageCollectorResourcesSyncError.Inc()\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\tlogger.V(4).Info(\"resynced monitors\")\n\n\t\t\t// wait for caches to fill for a while (our sync period) before attempting to rediscover resources and retry syncing.\n\t\t\t// this protects us from deadlocks where available resources changed and one of our informer caches will never fill.\n\t\t\t// informers keep attempting to sync in the background, so retrying doesn't interrupt them.\n\t\t\t// the call to resyncMonitors on the reattempt will no-op for resources that still exist.\n\t\t\t// note that workers stay paused until we successfully resync.\n\t\t\tif !cache.WaitForNamedCacheSync(\"garbage collector\", waitForStopOrTimeout(ctx.Done(), period), func() bool {\n\t\t\t\treturn gc.dependencyGraphBuilder.IsSynced(logger)\n\t\t\t}) {\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"timed out waiting for dependency graph builder sync during GC sync (attempt %d)\", attempt))\n\t\t\t\tmetrics.GarbageCollectorResourcesSyncError.Inc()\n\t\t\t\treturn false, nil\n\t\t\t}\n\n\t\t\t// success, break out of the loop\n\t\t\treturn true, nil\n\t\t})\n\n\t\t// Finally, keep track of our new state. Do this after all preceding steps\n\t\t// have succeeded to ensure we'll retry on subsequent syncs if an error\n\t\t// occurred.\n\t\toldResources = newResources\n\t\tlogger.V(2).Info(\"synced garbage collector\")\n\t}, period)\n}","line":{"from":177,"to":276}} {"id":100003883,"name":"printDiff","signature":"func printDiff(oldResources, newResources map[schema.GroupVersionResource]struct{}) string","file":"pkg/controller/garbagecollector/garbagecollector.go","code":"// printDiff returns a human-readable summary of what resources were added and removed\nfunc printDiff(oldResources, newResources map[schema.GroupVersionResource]struct{}) string {\n\tremoved := sets.NewString()\n\tfor oldResource := range oldResources {\n\t\tif _, ok := newResources[oldResource]; !ok {\n\t\t\tremoved.Insert(fmt.Sprintf(\"%+v\", oldResource))\n\t\t}\n\t}\n\tadded := sets.NewString()\n\tfor newResource := range newResources {\n\t\tif _, ok := oldResources[newResource]; !ok {\n\t\t\tadded.Insert(fmt.Sprintf(\"%+v\", newResource))\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"added: %v, removed: %v\", added.List(), removed.List())\n}","line":{"from":278,"to":293}} {"id":100003884,"name":"waitForStopOrTimeout","signature":"func waitForStopOrTimeout(stopCh \u003c-chan struct{}, timeout time.Duration) \u003c-chan struct{}","file":"pkg/controller/garbagecollector/garbagecollector.go","code":"// waitForStopOrTimeout returns a stop channel that closes when the provided stop channel closes or when the specified timeout is reached\nfunc waitForStopOrTimeout(stopCh \u003c-chan struct{}, timeout time.Duration) \u003c-chan struct{} {\n\tstopChWithTimeout := make(chan struct{})\n\tgo func() {\n\t\tselect {\n\t\tcase \u003c-stopCh:\n\t\tcase \u003c-time.After(timeout):\n\t\t}\n\t\tclose(stopChWithTimeout)\n\t}()\n\treturn stopChWithTimeout\n}","line":{"from":295,"to":306}} {"id":100003885,"name":"IsSynced","signature":"func (gc *GarbageCollector) IsSynced(logger klog.Logger) bool","file":"pkg/controller/garbagecollector/garbagecollector.go","code":"// IsSynced returns true if dependencyGraphBuilder is synced.\nfunc (gc *GarbageCollector) IsSynced(logger klog.Logger) bool {\n\treturn gc.dependencyGraphBuilder.IsSynced(logger)\n}","line":{"from":308,"to":311}} {"id":100003886,"name":"runAttemptToDeleteWorker","signature":"func (gc *GarbageCollector) runAttemptToDeleteWorker(ctx context.Context)","file":"pkg/controller/garbagecollector/garbagecollector.go","code":"func (gc *GarbageCollector) runAttemptToDeleteWorker(ctx context.Context) {\n\tfor gc.processAttemptToDeleteWorker(ctx) {\n\t}\n}","line":{"from":313,"to":316}} {"id":100003887,"name":"processAttemptToDeleteWorker","signature":"func (gc *GarbageCollector) processAttemptToDeleteWorker(ctx context.Context) bool","file":"pkg/controller/garbagecollector/garbagecollector.go","code":"func (gc *GarbageCollector) processAttemptToDeleteWorker(ctx context.Context) bool {\n\titem, quit := gc.attemptToDelete.Get()\n\tgc.workerLock.RLock()\n\tdefer gc.workerLock.RUnlock()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer gc.attemptToDelete.Done(item)\n\n\taction := gc.attemptToDeleteWorker(ctx, item)\n\tswitch action {\n\tcase forgetItem:\n\t\tgc.attemptToDelete.Forget(item)\n\tcase requeueItem:\n\t\tgc.attemptToDelete.AddRateLimited(item)\n\t}\n\n\treturn true\n}","line":{"from":322,"to":340}} {"id":100003888,"name":"attemptToDeleteWorker","signature":"func (gc *GarbageCollector) attemptToDeleteWorker(ctx context.Context, item interface{}) workQueueItemAction","file":"pkg/controller/garbagecollector/garbagecollector.go","code":"func (gc *GarbageCollector) attemptToDeleteWorker(ctx context.Context, item interface{}) workQueueItemAction {\n\tn, ok := item.(*node)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"expect *node, got %#v\", item))\n\t\treturn forgetItem\n\t}\n\n\tlogger := klog.FromContext(ctx)\n\n\tif !n.isObserved() {\n\t\tnodeFromGraph, existsInGraph := gc.dependencyGraphBuilder.uidToNode.Read(n.identity.UID)\n\t\tif !existsInGraph {\n\t\t\t// this can happen if attemptToDelete loops on a requeued virtual node because attemptToDeleteItem returned an error,\n\t\t\t// and in the meantime a deletion of the real object associated with that uid was observed\n\t\t\tlogger.V(5).Info(\"item no longer in the graph, skipping attemptToDeleteItem\", \"item\", n.identity)\n\t\t\treturn forgetItem\n\t\t}\n\t\tif nodeFromGraph.isObserved() {\n\t\t\t// this can happen if attemptToDelete loops on a requeued virtual node because attemptToDeleteItem returned an error,\n\t\t\t// and in the meantime the real object associated with that uid was observed\n\t\t\tlogger.V(5).Info(\"item no longer virtual in the graph, skipping attemptToDeleteItem on virtual node\", \"item\", n.identity)\n\t\t\treturn forgetItem\n\t\t}\n\t}\n\n\terr := gc.attemptToDeleteItem(ctx, n)\n\tif err == enqueuedVirtualDeleteEventErr {\n\t\t// a virtual event was produced and will be handled by processGraphChanges, no need to requeue this node\n\t\treturn forgetItem\n\t} else if err == namespacedOwnerOfClusterScopedObjectErr {\n\t\t// a cluster-scoped object referring to a namespaced owner is an error that will not resolve on retry, no need to requeue this node\n\t\treturn forgetItem\n\t} else if err != nil {\n\t\tif _, ok := err.(*restMappingError); ok {\n\t\t\t// There are at least two ways this can happen:\n\t\t\t// 1. The reference is to an object of a custom type that has not yet been\n\t\t\t// recognized by gc.restMapper (this is a transient error).\n\t\t\t// 2. The reference is to an invalid group/version. We don't currently\n\t\t\t// have a way to distinguish this from a valid type we will recognize\n\t\t\t// after the next discovery sync.\n\t\t\t// For now, record the error and retry.\n\t\t\tlogger.V(5).Error(err, \"error syncing item\", \"item\", n.identity)\n\t\t} else {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"error syncing item %s: %v\", n, err))\n\t\t}\n\t\t// retry if garbage collection of an object failed.\n\t\treturn requeueItem\n\t} else if !n.isObserved() {\n\t\t// requeue if item hasn't been observed via an informer event yet.\n\t\t// otherwise a virtual node for an item added AND removed during watch reestablishment can get stuck in the graph and never removed.\n\t\t// see https://issue.k8s.io/56121\n\t\tlogger.V(5).Info(\"item hasn't been observed via informer yet\", \"item\", n.identity)\n\t\treturn requeueItem\n\t}\n\n\treturn forgetItem\n}","line":{"from":349,"to":405}} {"id":100003889,"name":"isDangling","signature":"func (gc *GarbageCollector) isDangling(ctx context.Context, reference metav1.OwnerReference, item *node) (","file":"pkg/controller/garbagecollector/garbagecollector.go","code":"// isDangling check if a reference is pointing to an object that doesn't exist.\n// If isDangling looks up the referenced object at the API server, it also\n// returns its latest state.\nfunc (gc *GarbageCollector) isDangling(ctx context.Context, reference metav1.OwnerReference, item *node) (\n\tdangling bool, owner *metav1.PartialObjectMetadata, err error) {\n\n\tlogger := klog.FromContext(ctx)\n\t// check for recorded absent cluster-scoped parent\n\tabsentOwnerCacheKey := objectReference{OwnerReference: ownerReferenceCoordinates(reference)}\n\tif gc.absentOwnerCache.Has(absentOwnerCacheKey) {\n\t\tlogger.V(5).Info(\"according to the absentOwnerCache, item's owner does not exist\",\n\t\t\t\"item\", item.identity,\n\t\t\t\"owner\", reference,\n\t\t)\n\t\treturn true, nil, nil\n\t}\n\n\t// check for recorded absent namespaced parent\n\tabsentOwnerCacheKey.Namespace = item.identity.Namespace\n\tif gc.absentOwnerCache.Has(absentOwnerCacheKey) {\n\t\tlogger.V(5).Info(\"according to the absentOwnerCache, item's owner does not exist in namespace\",\n\t\t\t\"item\", item.identity,\n\t\t\t\"owner\", reference,\n\t\t)\n\t\treturn true, nil, nil\n\t}\n\n\t// TODO: we need to verify the reference resource is supported by the\n\t// system. If it's not a valid resource, the garbage collector should i)\n\t// ignore the reference when decide if the object should be deleted, and\n\t// ii) should update the object to remove such references. This is to\n\t// prevent objects having references to an old resource from being\n\t// deleted during a cluster upgrade.\n\tresource, namespaced, err := gc.apiResource(reference.APIVersion, reference.Kind)\n\tif err != nil {\n\t\treturn false, nil, err\n\t}\n\tif !namespaced {\n\t\tabsentOwnerCacheKey.Namespace = \"\"\n\t}\n\n\tif len(item.identity.Namespace) == 0 \u0026\u0026 namespaced {\n\t\t// item is a cluster-scoped object referring to a namespace-scoped owner, which is not valid.\n\t\t// return a marker error, rather than retrying on the lookup failure forever.\n\t\tlogger.V(2).Info(\"item is cluster-scoped, but refers to a namespaced owner\",\n\t\t\t\"item\", item.identity,\n\t\t\t\"owner\", reference,\n\t\t)\n\t\treturn false, nil, namespacedOwnerOfClusterScopedObjectErr\n\t}\n\n\t// TODO: It's only necessary to talk to the API server if the owner node\n\t// is a \"virtual\" node. The local graph could lag behind the real\n\t// status, but in practice, the difference is small.\n\towner, err = gc.metadataClient.Resource(resource).Namespace(resourceDefaultNamespace(namespaced, item.identity.Namespace)).Get(ctx, reference.Name, metav1.GetOptions{})\n\tswitch {\n\tcase errors.IsNotFound(err):\n\t\tgc.absentOwnerCache.Add(absentOwnerCacheKey)\n\t\tlogger.V(5).Info(\"item's owner is not found\",\n\t\t\t\"item\", item.identity,\n\t\t\t\"owner\", reference,\n\t\t)\n\t\treturn true, nil, nil\n\tcase err != nil:\n\t\treturn false, nil, err\n\t}\n\n\tif owner.GetUID() != reference.UID {\n\t\tlogger.V(5).Info(\"item's owner is not found, UID mismatch\",\n\t\t\t\"item\", item.identity,\n\t\t\t\"owner\", reference,\n\t\t)\n\t\tgc.absentOwnerCache.Add(absentOwnerCacheKey)\n\t\treturn true, nil, nil\n\t}\n\treturn false, owner, nil\n}","line":{"from":407,"to":483}} {"id":100003890,"name":"classifyReferences","signature":"func (gc *GarbageCollector) classifyReferences(ctx context.Context, item *node, latestReferences []metav1.OwnerReference) (","file":"pkg/controller/garbagecollector/garbagecollector.go","code":"// classify the latestReferences to three categories:\n// solid: the owner exists, and is not \"waitingForDependentsDeletion\"\n// dangling: the owner does not exist\n// waitingForDependentsDeletion: the owner exists, its deletionTimestamp is non-nil, and it has\n// FinalizerDeletingDependents\n// This function communicates with the server.\nfunc (gc *GarbageCollector) classifyReferences(ctx context.Context, item *node, latestReferences []metav1.OwnerReference) (\n\tsolid, dangling, waitingForDependentsDeletion []metav1.OwnerReference, err error) {\n\tfor _, reference := range latestReferences {\n\t\tisDangling, owner, err := gc.isDangling(ctx, reference, item)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t\tif isDangling {\n\t\t\tdangling = append(dangling, reference)\n\t\t\tcontinue\n\t\t}\n\n\t\townerAccessor, err := meta.Accessor(owner)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t\tif ownerAccessor.GetDeletionTimestamp() != nil \u0026\u0026 hasDeleteDependentsFinalizer(ownerAccessor) {\n\t\t\twaitingForDependentsDeletion = append(waitingForDependentsDeletion, reference)\n\t\t} else {\n\t\t\tsolid = append(solid, reference)\n\t\t}\n\t}\n\treturn solid, dangling, waitingForDependentsDeletion, nil\n}","line":{"from":485,"to":514}} {"id":100003891,"name":"ownerRefsToUIDs","signature":"func ownerRefsToUIDs(refs []metav1.OwnerReference) []types.UID","file":"pkg/controller/garbagecollector/garbagecollector.go","code":"func ownerRefsToUIDs(refs []metav1.OwnerReference) []types.UID {\n\tvar ret []types.UID\n\tfor _, ref := range refs {\n\t\tret = append(ret, ref.UID)\n\t}\n\treturn ret\n}","line":{"from":516,"to":522}} {"id":100003892,"name":"attemptToDeleteItem","signature":"func (gc *GarbageCollector) attemptToDeleteItem(ctx context.Context, item *node) error","file":"pkg/controller/garbagecollector/garbagecollector.go","code":"// attemptToDeleteItem looks up the live API object associated with the node,\n// and issues a delete IFF the uid matches, the item is not blocked on deleting dependents,\n// and all owner references are dangling.\n//\n// if the API get request returns a NotFound error, or the retrieved item's uid does not match,\n// a virtual delete event for the node is enqueued and enqueuedVirtualDeleteEventErr is returned.\nfunc (gc *GarbageCollector) attemptToDeleteItem(ctx context.Context, item *node) error {\n\tlogger := klog.FromContext(ctx)\n\n\tlogger.V(2).Info(\"Processing item\",\n\t\t\"item\", item.identity,\n\t\t\"virtual\", !item.isObserved(),\n\t)\n\n\t// \"being deleted\" is an one-way trip to the final deletion. We'll just wait for the final deletion, and then process the object's dependents.\n\tif item.isBeingDeleted() \u0026\u0026 !item.isDeletingDependents() {\n\t\tlogger.V(5).Info(\"processing item returned at once, because its DeletionTimestamp is non-nil\",\n\t\t\t\"item\", item.identity,\n\t\t)\n\t\treturn nil\n\t}\n\t// TODO: It's only necessary to talk to the API server if this is a\n\t// \"virtual\" node. The local graph could lag behind the real status, but in\n\t// practice, the difference is small.\n\tlatest, err := gc.getObject(item.identity)\n\tswitch {\n\tcase errors.IsNotFound(err):\n\t\t// the GraphBuilder can add \"virtual\" node for an owner that doesn't\n\t\t// exist yet, so we need to enqueue a virtual Delete event to remove\n\t\t// the virtual node from GraphBuilder.uidToNode.\n\t\tlogger.V(5).Info(\"item not found, generating a virtual delete event\",\n\t\t\t\"item\", item.identity,\n\t\t)\n\t\tgc.dependencyGraphBuilder.enqueueVirtualDeleteEvent(item.identity)\n\t\treturn enqueuedVirtualDeleteEventErr\n\tcase err != nil:\n\t\treturn err\n\t}\n\n\tif latest.GetUID() != item.identity.UID {\n\t\tlogger.V(5).Info(\"UID doesn't match, item not found, generating a virtual delete event\",\n\t\t\t\"item\", item.identity,\n\t\t)\n\t\tgc.dependencyGraphBuilder.enqueueVirtualDeleteEvent(item.identity)\n\t\treturn enqueuedVirtualDeleteEventErr\n\t}\n\n\t// TODO: attemptToOrphanWorker() routine is similar. Consider merging\n\t// attemptToOrphanWorker() into attemptToDeleteItem() as well.\n\tif item.isDeletingDependents() {\n\t\treturn gc.processDeletingDependentsItem(logger, item)\n\t}\n\n\t// compute if we should delete the item\n\townerReferences := latest.GetOwnerReferences()\n\tif len(ownerReferences) == 0 {\n\t\tlogger.V(2).Info(\"item doesn't have an owner, continue on next item\",\n\t\t\t\"item\", item.identity,\n\t\t)\n\t\treturn nil\n\t}\n\n\tsolid, dangling, waitingForDependentsDeletion, err := gc.classifyReferences(ctx, item, ownerReferences)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlogger.V(5).Info(\"classify item's references\",\n\t\t\"item\", item.identity,\n\t\t\"solid\", solid,\n\t\t\"dangling\", dangling,\n\t\t\"waitingForDependentsDeletion\", waitingForDependentsDeletion,\n\t)\n\n\tswitch {\n\tcase len(solid) != 0:\n\t\tlogger.V(2).Info(\"item has at least one existing owner, will not garbage collect\",\n\t\t\t\"item\", item.identity,\n\t\t\t\"owner\", solid,\n\t\t)\n\t\tif len(dangling) == 0 \u0026\u0026 len(waitingForDependentsDeletion) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\tlogger.V(2).Info(\"remove dangling references and waiting references for item\",\n\t\t\t\"item\", item.identity,\n\t\t\t\"dangling\", dangling,\n\t\t\t\"waitingForDependentsDeletion\", waitingForDependentsDeletion,\n\t\t)\n\t\t// waitingForDependentsDeletion needs to be deleted from the\n\t\t// ownerReferences, otherwise the referenced objects will be stuck with\n\t\t// the FinalizerDeletingDependents and never get deleted.\n\t\townerUIDs := append(ownerRefsToUIDs(dangling), ownerRefsToUIDs(waitingForDependentsDeletion)...)\n\t\tp, err := c.GenerateDeleteOwnerRefStrategicMergeBytes(item.identity.UID, ownerUIDs)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = gc.patch(item, p, func(n *node) ([]byte, error) {\n\t\t\treturn gc.deleteOwnerRefJSONMergePatch(n, ownerUIDs...)\n\t\t})\n\t\treturn err\n\tcase len(waitingForDependentsDeletion) != 0 \u0026\u0026 item.dependentsLength() != 0:\n\t\tdeps := item.getDependents()\n\t\tfor _, dep := range deps {\n\t\t\tif dep.isDeletingDependents() {\n\t\t\t\t// this circle detection has false positives, we need to\n\t\t\t\t// apply a more rigorous detection if this turns out to be a\n\t\t\t\t// problem.\n\t\t\t\t// there are multiple workers run attemptToDeleteItem in\n\t\t\t\t// parallel, the circle detection can fail in a race condition.\n\t\t\t\tlogger.V(2).Info(\"processing item, some of its owners and its dependent have FinalizerDeletingDependents, to prevent potential cycle, its ownerReferences are going to be modified to be non-blocking, then the item is going to be deleted with Foreground\",\n\t\t\t\t\t\"item\", item.identity,\n\t\t\t\t\t\"dependent\", dep.identity,\n\t\t\t\t)\n\t\t\t\tpatch, err := item.unblockOwnerReferencesStrategicMergePatch()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif _, err := gc.patch(item, patch, gc.unblockOwnerReferencesJSONMergePatch); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tlogger.V(2).Info(\"at least one owner of item has FinalizerDeletingDependents, and the item itself has dependents, so it is going to be deleted in Foreground\",\n\t\t\t\"item\", item.identity,\n\t\t)\n\t\t// the deletion event will be observed by the graphBuilder, so the item\n\t\t// will be processed again in processDeletingDependentsItem. If it\n\t\t// doesn't have dependents, the function will remove the\n\t\t// FinalizerDeletingDependents from the item, resulting in the final\n\t\t// deletion of the item.\n\t\tpolicy := metav1.DeletePropagationForeground\n\t\treturn gc.deleteObject(item.identity, \u0026policy)\n\tdefault:\n\t\t// item doesn't have any solid owner, so it needs to be garbage\n\t\t// collected. Also, none of item's owners is waiting for the deletion of\n\t\t// the dependents, so set propagationPolicy based on existing finalizers.\n\t\tvar policy metav1.DeletionPropagation\n\t\tswitch {\n\t\tcase hasOrphanFinalizer(latest):\n\t\t\t// if an existing orphan finalizer is already on the object, honor it.\n\t\t\tpolicy = metav1.DeletePropagationOrphan\n\t\tcase hasDeleteDependentsFinalizer(latest):\n\t\t\t// if an existing foreground finalizer is already on the object, honor it.\n\t\t\tpolicy = metav1.DeletePropagationForeground\n\t\tdefault:\n\t\t\t// otherwise, default to background.\n\t\t\tpolicy = metav1.DeletePropagationBackground\n\t\t}\n\t\tlogger.V(2).Info(\"Deleting item\",\n\t\t\t\"item\", item.identity,\n\t\t\t\"propagationPolicy\", policy,\n\t\t)\n\t\treturn gc.deleteObject(item.identity, \u0026policy)\n\t}\n}","line":{"from":524,"to":678}} {"id":100003893,"name":"processDeletingDependentsItem","signature":"func (gc *GarbageCollector) processDeletingDependentsItem(logger klog.Logger, item *node) error","file":"pkg/controller/garbagecollector/garbagecollector.go","code":"// process item that's waiting for its dependents to be deleted\nfunc (gc *GarbageCollector) processDeletingDependentsItem(logger klog.Logger, item *node) error {\n\tblockingDependents := item.blockingDependents()\n\tif len(blockingDependents) == 0 {\n\t\tlogger.V(2).Info(\"remove DeleteDependents finalizer for item\", \"item\", item.identity)\n\t\treturn gc.removeFinalizer(logger, item, metav1.FinalizerDeleteDependents)\n\t}\n\tfor _, dep := range blockingDependents {\n\t\tif !dep.isDeletingDependents() {\n\t\t\tlogger.V(2).Info(\"adding dependent to attemptToDelete, because its owner is deletingDependents\",\n\t\t\t\t\"item\", item.identity,\n\t\t\t\t\"dependent\", dep.identity,\n\t\t\t)\n\t\t\tgc.attemptToDelete.Add(dep)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":680,"to":697}} {"id":100003894,"name":"orphanDependents","signature":"func (gc *GarbageCollector) orphanDependents(logger klog.Logger, owner objectReference, dependents []*node) error","file":"pkg/controller/garbagecollector/garbagecollector.go","code":"// dependents are copies of pointers to the owner's dependents, they don't need to be locked.\nfunc (gc *GarbageCollector) orphanDependents(logger klog.Logger, owner objectReference, dependents []*node) error {\n\terrCh := make(chan error, len(dependents))\n\twg := sync.WaitGroup{}\n\twg.Add(len(dependents))\n\tfor i := range dependents {\n\t\tgo func(dependent *node) {\n\t\t\tdefer wg.Done()\n\t\t\t// the dependent.identity.UID is used as precondition\n\t\t\tp, err := c.GenerateDeleteOwnerRefStrategicMergeBytes(dependent.identity.UID, []types.UID{owner.UID})\n\t\t\tif err != nil {\n\t\t\t\terrCh \u003c- fmt.Errorf(\"orphaning %s failed, %v\", dependent.identity, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t_, err = gc.patch(dependent, p, func(n *node) ([]byte, error) {\n\t\t\t\treturn gc.deleteOwnerRefJSONMergePatch(n, owner.UID)\n\t\t\t})\n\t\t\t// note that if the target ownerReference doesn't exist in the\n\t\t\t// dependent, strategic merge patch will NOT return an error.\n\t\t\tif err != nil \u0026\u0026 !errors.IsNotFound(err) {\n\t\t\t\terrCh \u003c- fmt.Errorf(\"orphaning %s failed, %v\", dependent.identity, err)\n\t\t\t}\n\t\t}(dependents[i])\n\t}\n\twg.Wait()\n\tclose(errCh)\n\n\tvar errorsSlice []error\n\tfor e := range errCh {\n\t\terrorsSlice = append(errorsSlice, e)\n\t}\n\n\tif len(errorsSlice) != 0 {\n\t\treturn fmt.Errorf(\"failed to orphan dependents of owner %s, got errors: %s\", owner, utilerrors.NewAggregate(errorsSlice).Error())\n\t}\n\tlogger.V(5).Info(\"successfully updated all dependents\", \"owner\", owner)\n\treturn nil\n}","line":{"from":699,"to":736}} {"id":100003895,"name":"runAttemptToOrphanWorker","signature":"func (gc *GarbageCollector) runAttemptToOrphanWorker(logger klog.Logger)","file":"pkg/controller/garbagecollector/garbagecollector.go","code":"func (gc *GarbageCollector) runAttemptToOrphanWorker(logger klog.Logger) {\n\tfor gc.processAttemptToOrphanWorker(logger) {\n\t}\n}","line":{"from":738,"to":741}} {"id":100003896,"name":"processAttemptToOrphanWorker","signature":"func (gc *GarbageCollector) processAttemptToOrphanWorker(logger klog.Logger) bool","file":"pkg/controller/garbagecollector/garbagecollector.go","code":"// processAttemptToOrphanWorker dequeues a node from the attemptToOrphan, then finds its\n// dependents based on the graph maintained by the GC, then removes it from the\n// OwnerReferences of its dependents, and finally updates the owner to remove\n// the \"Orphan\" finalizer. The node is added back into the attemptToOrphan if any of\n// these steps fail.\nfunc (gc *GarbageCollector) processAttemptToOrphanWorker(logger klog.Logger) bool {\n\titem, quit := gc.attemptToOrphan.Get()\n\tgc.workerLock.RLock()\n\tdefer gc.workerLock.RUnlock()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer gc.attemptToOrphan.Done(item)\n\n\taction := gc.attemptToOrphanWorker(logger, item)\n\tswitch action {\n\tcase forgetItem:\n\t\tgc.attemptToOrphan.Forget(item)\n\tcase requeueItem:\n\t\tgc.attemptToOrphan.AddRateLimited(item)\n\t}\n\n\treturn true\n}","line":{"from":743,"to":766}} {"id":100003897,"name":"attemptToOrphanWorker","signature":"func (gc *GarbageCollector) attemptToOrphanWorker(logger klog.Logger, item interface{}) workQueueItemAction","file":"pkg/controller/garbagecollector/garbagecollector.go","code":"func (gc *GarbageCollector) attemptToOrphanWorker(logger klog.Logger, item interface{}) workQueueItemAction {\n\towner, ok := item.(*node)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"expect *node, got %#v\", item))\n\t\treturn forgetItem\n\t}\n\t// we don't need to lock each element, because they never get updated\n\towner.dependentsLock.RLock()\n\tdependents := make([]*node, 0, len(owner.dependents))\n\tfor dependent := range owner.dependents {\n\t\tdependents = append(dependents, dependent)\n\t}\n\towner.dependentsLock.RUnlock()\n\n\terr := gc.orphanDependents(logger, owner.identity, dependents)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"orphanDependents for %s failed with %v\", owner.identity, err))\n\t\treturn requeueItem\n\t}\n\t// update the owner, remove \"orphaningFinalizer\" from its finalizers list\n\terr = gc.removeFinalizer(logger, owner, metav1.FinalizerOrphanDependents)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"removeOrphanFinalizer for %s failed with %v\", owner.identity, err))\n\t\treturn requeueItem\n\t}\n\treturn forgetItem\n}","line":{"from":768,"to":794}} {"id":100003898,"name":"GraphHasUID","signature":"func (gc *GarbageCollector) GraphHasUID(u types.UID) bool","file":"pkg/controller/garbagecollector/garbagecollector.go","code":"// *FOR TEST USE ONLY*\n// GraphHasUID returns if the GraphBuilder has a particular UID store in its\n// uidToNode graph. It's useful for debugging.\n// This method is used by integration tests.\nfunc (gc *GarbageCollector) GraphHasUID(u types.UID) bool {\n\t_, ok := gc.dependencyGraphBuilder.uidToNode.Read(u)\n\treturn ok\n}","line":{"from":796,"to":803}} {"id":100003899,"name":"GetDeletableResources","signature":"func GetDeletableResources(discoveryClient discovery.ServerResourcesInterface) map[schema.GroupVersionResource]struct{}","file":"pkg/controller/garbagecollector/garbagecollector.go","code":"// GetDeletableResources returns all resources from discoveryClient that the\n// garbage collector should recognize and work with. More specifically, all\n// preferred resources which support the 'delete', 'list', and 'watch' verbs.\n//\n// All discovery errors are considered temporary. Upon encountering any error,\n// GetDeletableResources will log and return any discovered resources it was\n// able to process (which may be none).\nfunc GetDeletableResources(discoveryClient discovery.ServerResourcesInterface) map[schema.GroupVersionResource]struct{} {\n\tpreferredResources, err := discoveryClient.ServerPreferredResources()\n\tif err != nil {\n\t\tif discovery.IsGroupDiscoveryFailedError(err) {\n\t\t\tklog.Warningf(\"failed to discover some groups: %v\", err.(*discovery.ErrGroupDiscoveryFailed).Groups)\n\t\t} else {\n\t\t\tklog.Warningf(\"failed to discover preferred resources: %v\", err)\n\t\t}\n\t}\n\tif preferredResources == nil {\n\t\treturn map[schema.GroupVersionResource]struct{}{}\n\t}\n\n\t// This is extracted from discovery.GroupVersionResources to allow tolerating\n\t// failures on a per-resource basis.\n\tdeletableResources := discovery.FilteredBy(discovery.SupportsAllVerbs{Verbs: []string{\"delete\", \"list\", \"watch\"}}, preferredResources)\n\tdeletableGroupVersionResources := map[schema.GroupVersionResource]struct{}{}\n\tfor _, rl := range deletableResources {\n\t\tgv, err := schema.ParseGroupVersion(rl.GroupVersion)\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"ignoring invalid discovered resource %q: %v\", rl.GroupVersion, err)\n\t\t\tcontinue\n\t\t}\n\t\tfor i := range rl.APIResources {\n\t\t\tdeletableGroupVersionResources[schema.GroupVersionResource{Group: gv.Group, Version: gv.Version, Resource: rl.APIResources[i].Name}] = struct{}{}\n\t\t}\n\t}\n\n\treturn deletableGroupVersionResources\n}","line":{"from":805,"to":841}} {"id":100003900,"name":"Name","signature":"func (gc *GarbageCollector) Name() string","file":"pkg/controller/garbagecollector/garbagecollector.go","code":"func (gc *GarbageCollector) Name() string {\n\treturn \"garbagecollector\"\n}","line":{"from":843,"to":845}} {"id":100003901,"name":"String","signature":"func (s objectReference) String() string","file":"pkg/controller/garbagecollector/graph.go","code":"// String is used when logging an objectReference in text format.\nfunc (s objectReference) String() string {\n\treturn fmt.Sprintf(\"[%s/%s, namespace: %s, name: %s, uid: %s]\", s.APIVersion, s.Kind, s.Namespace, s.Name, s.UID)\n}","line":{"from":35,"to":38}} {"id":100003902,"name":"MarshalLog","signature":"func (s objectReference) MarshalLog() interface{}","file":"pkg/controller/garbagecollector/graph.go","code":"// MarshalLog is used when logging an objectReference in JSON format.\nfunc (s objectReference) MarshalLog() interface{} {\n\treturn struct {\n\t\tName string `json:\"name\"`\n\t\tNamespace string `json:\"namespace\"`\n\t\tAPIVersion string `json:\"apiVersion\"`\n\t\tUID types.UID `json:\"uid\"`\n\t}{\n\t\tNamespace: s.Namespace,\n\t\tName: s.Name,\n\t\tAPIVersion: s.APIVersion,\n\t\tUID: s.UID,\n\t}\n}","line":{"from":40,"to":53}} {"id":100003903,"name":"clone","signature":"func (n *node) clone() *node","file":"pkg/controller/garbagecollector/graph.go","code":"// clone() must only be called from the single-threaded GraphBuilder.processGraphChanges()\nfunc (n *node) clone() *node {\n\tc := \u0026node{\n\t\tidentity: n.identity,\n\t\tdependents: make(map[*node]struct{}, len(n.dependents)),\n\t\tdeletingDependents: n.deletingDependents,\n\t\tbeingDeleted: n.beingDeleted,\n\t\tvirtual: n.virtual,\n\t\towners: make([]metav1.OwnerReference, 0, len(n.owners)),\n\t}\n\tfor dep := range n.dependents {\n\t\tc.dependents[dep] = struct{}{}\n\t}\n\tfor _, owner := range n.owners {\n\t\tc.owners = append(c.owners, owner)\n\t}\n\treturn c\n}","line":{"from":85,"to":102}} {"id":100003904,"name":"markBeingDeleted","signature":"func (n *node) markBeingDeleted()","file":"pkg/controller/garbagecollector/graph.go","code":"// An object is on a one way trip to its final deletion if it starts being\n// deleted, so we only provide a function to set beingDeleted to true.\nfunc (n *node) markBeingDeleted() {\n\tn.beingDeletedLock.Lock()\n\tdefer n.beingDeletedLock.Unlock()\n\tn.beingDeleted = true\n}","line":{"from":104,"to":110}} {"id":100003905,"name":"isBeingDeleted","signature":"func (n *node) isBeingDeleted() bool","file":"pkg/controller/garbagecollector/graph.go","code":"func (n *node) isBeingDeleted() bool {\n\tn.beingDeletedLock.RLock()\n\tdefer n.beingDeletedLock.RUnlock()\n\treturn n.beingDeleted\n}","line":{"from":112,"to":116}} {"id":100003906,"name":"markObserved","signature":"func (n *node) markObserved()","file":"pkg/controller/garbagecollector/graph.go","code":"func (n *node) markObserved() {\n\tn.virtualLock.Lock()\n\tdefer n.virtualLock.Unlock()\n\tn.virtual = false\n}","line":{"from":118,"to":122}} {"id":100003907,"name":"isObserved","signature":"func (n *node) isObserved() bool","file":"pkg/controller/garbagecollector/graph.go","code":"func (n *node) isObserved() bool {\n\tn.virtualLock.RLock()\n\tdefer n.virtualLock.RUnlock()\n\treturn !n.virtual\n}","line":{"from":123,"to":127}} {"id":100003908,"name":"markDeletingDependents","signature":"func (n *node) markDeletingDependents()","file":"pkg/controller/garbagecollector/graph.go","code":"func (n *node) markDeletingDependents() {\n\tn.deletingDependentsLock.Lock()\n\tdefer n.deletingDependentsLock.Unlock()\n\tn.deletingDependents = true\n}","line":{"from":129,"to":133}} {"id":100003909,"name":"isDeletingDependents","signature":"func (n *node) isDeletingDependents() bool","file":"pkg/controller/garbagecollector/graph.go","code":"func (n *node) isDeletingDependents() bool {\n\tn.deletingDependentsLock.RLock()\n\tdefer n.deletingDependentsLock.RUnlock()\n\treturn n.deletingDependents\n}","line":{"from":135,"to":139}} {"id":100003910,"name":"addDependent","signature":"func (n *node) addDependent(dependent *node)","file":"pkg/controller/garbagecollector/graph.go","code":"func (n *node) addDependent(dependent *node) {\n\tn.dependentsLock.Lock()\n\tdefer n.dependentsLock.Unlock()\n\tn.dependents[dependent] = struct{}{}\n}","line":{"from":141,"to":145}} {"id":100003911,"name":"deleteDependent","signature":"func (n *node) deleteDependent(dependent *node)","file":"pkg/controller/garbagecollector/graph.go","code":"func (n *node) deleteDependent(dependent *node) {\n\tn.dependentsLock.Lock()\n\tdefer n.dependentsLock.Unlock()\n\tdelete(n.dependents, dependent)\n}","line":{"from":147,"to":151}} {"id":100003912,"name":"dependentsLength","signature":"func (n *node) dependentsLength() int","file":"pkg/controller/garbagecollector/graph.go","code":"func (n *node) dependentsLength() int {\n\tn.dependentsLock.RLock()\n\tdefer n.dependentsLock.RUnlock()\n\treturn len(n.dependents)\n}","line":{"from":153,"to":157}} {"id":100003913,"name":"getDependents","signature":"func (n *node) getDependents() []*node","file":"pkg/controller/garbagecollector/graph.go","code":"// Note that this function does not provide any synchronization guarantees;\n// items could be added to or removed from ownerNode.dependents the moment this\n// function returns.\nfunc (n *node) getDependents() []*node {\n\tn.dependentsLock.RLock()\n\tdefer n.dependentsLock.RUnlock()\n\tvar ret []*node\n\tfor dep := range n.dependents {\n\t\tret = append(ret, dep)\n\t}\n\treturn ret\n}","line":{"from":159,"to":170}} {"id":100003914,"name":"blockingDependents","signature":"func (n *node) blockingDependents() []*node","file":"pkg/controller/garbagecollector/graph.go","code":"// blockingDependents returns the dependents that are blocking the deletion of\n// n, i.e., the dependent that has an ownerReference pointing to n, and\n// the BlockOwnerDeletion field of that ownerReference is true.\n// Note that this function does not provide any synchronization guarantees;\n// items could be added to or removed from ownerNode.dependents the moment this\n// function returns.\nfunc (n *node) blockingDependents() []*node {\n\tdependents := n.getDependents()\n\tvar ret []*node\n\tfor _, dep := range dependents {\n\t\tfor _, owner := range dep.owners {\n\t\t\tif owner.UID == n.identity.UID \u0026\u0026 owner.BlockOwnerDeletion != nil \u0026\u0026 *owner.BlockOwnerDeletion {\n\t\t\t\tret = append(ret, dep)\n\t\t\t}\n\t\t}\n\t}\n\treturn ret\n}","line":{"from":172,"to":189}} {"id":100003915,"name":"ownerReferenceCoordinates","signature":"func ownerReferenceCoordinates(ref metav1.OwnerReference) metav1.OwnerReference","file":"pkg/controller/garbagecollector/graph.go","code":"// ownerReferenceCoordinates returns an owner reference containing only the coordinate fields\n// from the input reference (uid, name, kind, apiVersion)\nfunc ownerReferenceCoordinates(ref metav1.OwnerReference) metav1.OwnerReference {\n\treturn metav1.OwnerReference{\n\t\tUID: ref.UID,\n\t\tName: ref.Name,\n\t\tKind: ref.Kind,\n\t\tAPIVersion: ref.APIVersion,\n\t}\n}","line":{"from":191,"to":200}} {"id":100003916,"name":"ownerReferenceMatchesCoordinates","signature":"func ownerReferenceMatchesCoordinates(a, b metav1.OwnerReference) bool","file":"pkg/controller/garbagecollector/graph.go","code":"// ownerReferenceMatchesCoordinates returns true if all of the coordinate fields match\n// between the two references (uid, name, kind, apiVersion)\nfunc ownerReferenceMatchesCoordinates(a, b metav1.OwnerReference) bool {\n\treturn a.UID == b.UID \u0026\u0026 a.Name == b.Name \u0026\u0026 a.Kind == b.Kind \u0026\u0026 a.APIVersion == b.APIVersion\n}","line":{"from":202,"to":206}} {"id":100003917,"name":"String","signature":"func (n *node) String() string","file":"pkg/controller/garbagecollector/graph.go","code":"// String renders node as a string using fmt. Acquires a read lock to ensure the\n// reflective dump of dependents doesn't race with any concurrent writes.\nfunc (n *node) String() string {\n\tn.dependentsLock.RLock()\n\tdefer n.dependentsLock.RUnlock()\n\treturn fmt.Sprintf(\"%#v\", n)\n}","line":{"from":208,"to":214}} {"id":100003918,"name":"Write","signature":"func (m *concurrentUIDToNode) Write(node *node)","file":"pkg/controller/garbagecollector/graph.go","code":"func (m *concurrentUIDToNode) Write(node *node) {\n\tm.uidToNodeLock.Lock()\n\tdefer m.uidToNodeLock.Unlock()\n\tm.uidToNode[node.identity.UID] = node\n}","line":{"from":221,"to":225}} {"id":100003919,"name":"Read","signature":"func (m *concurrentUIDToNode) Read(uid types.UID) (*node, bool)","file":"pkg/controller/garbagecollector/graph.go","code":"func (m *concurrentUIDToNode) Read(uid types.UID) (*node, bool) {\n\tm.uidToNodeLock.RLock()\n\tdefer m.uidToNodeLock.RUnlock()\n\tn, ok := m.uidToNode[uid]\n\treturn n, ok\n}","line":{"from":227,"to":232}} {"id":100003920,"name":"Delete","signature":"func (m *concurrentUIDToNode) Delete(uid types.UID)","file":"pkg/controller/garbagecollector/graph.go","code":"func (m *concurrentUIDToNode) Delete(uid types.UID) {\n\tm.uidToNodeLock.Lock()\n\tdefer m.uidToNodeLock.Unlock()\n\tdelete(m.uidToNode, uid)\n}","line":{"from":234,"to":238}} {"id":100003921,"name":"String","signature":"func (e eventType) String() string","file":"pkg/controller/garbagecollector/graph_builder.go","code":"func (e eventType) String() string {\n\tswitch e {\n\tcase addEvent:\n\t\treturn \"add\"\n\tcase updateEvent:\n\t\treturn \"update\"\n\tcase deleteEvent:\n\t\treturn \"delete\"\n\tdefault:\n\t\treturn fmt.Sprintf(\"unknown(%d)\", int(e))\n\t}\n}","line":{"from":49,"to":60}} {"id":100003922,"name":"Run","signature":"func (m *monitor) Run()","file":"pkg/controller/garbagecollector/graph_builder.go","code":"// Run is intended to be called in a goroutine. Multiple calls of this is an\n// error.\nfunc (m *monitor) Run() {\n\tm.controller.Run(m.stopCh)\n}","line":{"from":129,"to":133}} {"id":100003923,"name":"controllerFor","signature":"func (gb *GraphBuilder) controllerFor(logger klog.Logger, resource schema.GroupVersionResource, kind schema.GroupVersionKind) (cache.Controller, cache.Store, error)","file":"pkg/controller/garbagecollector/graph_builder.go","code":"func (gb *GraphBuilder) controllerFor(logger klog.Logger, resource schema.GroupVersionResource, kind schema.GroupVersionKind) (cache.Controller, cache.Store, error) {\n\thandlers := cache.ResourceEventHandlerFuncs{\n\t\t// add the event to the dependencyGraphBuilder's graphChanges.\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tevent := \u0026event{\n\t\t\t\teventType: addEvent,\n\t\t\t\tobj: obj,\n\t\t\t\tgvk: kind,\n\t\t\t}\n\t\t\tgb.graphChanges.Add(event)\n\t\t},\n\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\t// TODO: check if there are differences in the ownerRefs,\n\t\t\t// finalizers, and DeletionTimestamp; if not, ignore the update.\n\t\t\tevent := \u0026event{\n\t\t\t\teventType: updateEvent,\n\t\t\t\tobj: newObj,\n\t\t\t\toldObj: oldObj,\n\t\t\t\tgvk: kind,\n\t\t\t}\n\t\t\tgb.graphChanges.Add(event)\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\t// delta fifo may wrap the object in a cache.DeletedFinalStateUnknown, unwrap it\n\t\t\tif deletedFinalStateUnknown, ok := obj.(cache.DeletedFinalStateUnknown); ok {\n\t\t\t\tobj = deletedFinalStateUnknown.Obj\n\t\t\t}\n\t\t\tevent := \u0026event{\n\t\t\t\teventType: deleteEvent,\n\t\t\t\tobj: obj,\n\t\t\t\tgvk: kind,\n\t\t\t}\n\t\t\tgb.graphChanges.Add(event)\n\t\t},\n\t}\n\n\tshared, err := gb.sharedInformers.ForResource(resource)\n\tif err != nil {\n\t\tlogger.V(4).Error(err, \"unable to use a shared informer\", \"resource\", resource, \"kind\", kind)\n\t\treturn nil, nil, err\n\t}\n\tlogger.V(4).Info(\"using a shared informer\", \"resource\", resource, \"kind\", kind)\n\t// need to clone because it's from a shared cache\n\tshared.Informer().AddEventHandlerWithResyncPeriod(handlers, ResourceResyncTime)\n\treturn shared.Informer().GetController(), shared.Informer().GetStore(), nil\n}","line":{"from":137,"to":182}} {"id":100003924,"name":"syncMonitors","signature":"func (gb *GraphBuilder) syncMonitors(logger klog.Logger, resources map[schema.GroupVersionResource]struct{}) error","file":"pkg/controller/garbagecollector/graph_builder.go","code":"// syncMonitors rebuilds the monitor set according to the supplied resources,\n// creating or deleting monitors as necessary. It will return any error\n// encountered, but will make an attempt to create a monitor for each resource\n// instead of immediately exiting on an error. It may be called before or after\n// Run. Monitors are NOT started as part of the sync. To ensure all existing\n// monitors are started, call startMonitors.\nfunc (gb *GraphBuilder) syncMonitors(logger klog.Logger, resources map[schema.GroupVersionResource]struct{}) error {\n\tgb.monitorLock.Lock()\n\tdefer gb.monitorLock.Unlock()\n\n\ttoRemove := gb.monitors\n\tif toRemove == nil {\n\t\ttoRemove = monitors{}\n\t}\n\tcurrent := monitors{}\n\terrs := []error{}\n\tkept := 0\n\tadded := 0\n\tfor resource := range resources {\n\t\tif _, ok := gb.ignoredResources[resource.GroupResource()]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tif m, ok := toRemove[resource]; ok {\n\t\t\tcurrent[resource] = m\n\t\t\tdelete(toRemove, resource)\n\t\t\tkept++\n\t\t\tcontinue\n\t\t}\n\t\tkind, err := gb.restMapper.KindFor(resource)\n\t\tif err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"couldn't look up resource %q: %v\", resource, err))\n\t\t\tcontinue\n\t\t}\n\t\tc, s, err := gb.controllerFor(logger, resource, kind)\n\t\tif err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"couldn't start monitor for resource %q: %v\", resource, err))\n\t\t\tcontinue\n\t\t}\n\t\tcurrent[resource] = \u0026monitor{store: s, controller: c}\n\t\tadded++\n\t}\n\tgb.monitors = current\n\n\tfor _, monitor := range toRemove {\n\t\tif monitor.stopCh != nil {\n\t\t\tclose(monitor.stopCh)\n\t\t}\n\t}\n\n\tlogger.V(4).Info(\"synced monitors\", \"added\", added, \"kept\", kept, \"removed\", len(toRemove))\n\t// NewAggregate returns nil if errs is 0-length\n\treturn utilerrors.NewAggregate(errs)\n}","line":{"from":184,"to":236}} {"id":100003925,"name":"startMonitors","signature":"func (gb *GraphBuilder) startMonitors(logger klog.Logger)","file":"pkg/controller/garbagecollector/graph_builder.go","code":"// startMonitors ensures the current set of monitors are running. Any newly\n// started monitors will also cause shared informers to be started.\n//\n// If called before Run, startMonitors does nothing (as there is no stop channel\n// to support monitor/informer execution).\nfunc (gb *GraphBuilder) startMonitors(logger klog.Logger) {\n\tgb.monitorLock.Lock()\n\tdefer gb.monitorLock.Unlock()\n\n\tif !gb.running {\n\t\treturn\n\t}\n\n\t// we're waiting until after the informer start that happens once all the controllers are initialized. This ensures\n\t// that they don't get unexpected events on their work queues.\n\t\u003c-gb.informersStarted\n\n\tmonitors := gb.monitors\n\tstarted := 0\n\tfor _, monitor := range monitors {\n\t\tif monitor.stopCh == nil {\n\t\t\tmonitor.stopCh = make(chan struct{})\n\t\t\tgb.sharedInformers.Start(gb.stopCh)\n\t\t\tgo monitor.Run()\n\t\t\tstarted++\n\t\t}\n\t}\n\tlogger.V(4).Info(\"started new monitors\", \"new\", started, \"current\", len(monitors))\n}","line":{"from":238,"to":266}} {"id":100003926,"name":"IsSynced","signature":"func (gb *GraphBuilder) IsSynced(logger klog.Logger) bool","file":"pkg/controller/garbagecollector/graph_builder.go","code":"// IsSynced returns true if any monitors exist AND all those monitors'\n// controllers HasSynced functions return true. This means IsSynced could return\n// true at one time, and then later return false if all monitors were\n// reconstructed.\nfunc (gb *GraphBuilder) IsSynced(logger klog.Logger) bool {\n\tgb.monitorLock.Lock()\n\tdefer gb.monitorLock.Unlock()\n\n\tif len(gb.monitors) == 0 {\n\t\tlogger.V(4).Info(\"garbage controller monitor not synced: no monitors\")\n\t\treturn false\n\t}\n\n\tfor resource, monitor := range gb.monitors {\n\t\tif !monitor.controller.HasSynced() {\n\t\t\tlogger.V(4).Info(\"garbage controller monitor not yet synced\", \"resource\", resource)\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":268,"to":288}} {"id":100003927,"name":"Run","signature":"func (gb *GraphBuilder) Run(ctx context.Context)","file":"pkg/controller/garbagecollector/graph_builder.go","code":"// Run sets the stop channel and starts monitor execution until stopCh is\n// closed. Any running monitors will be stopped before Run returns.\nfunc (gb *GraphBuilder) Run(ctx context.Context) {\n\tlogger := klog.FromContext(ctx)\n\tlogger.Info(\"Running\", \"component\", \"GraphBuilder\")\n\tdefer logger.Info(\"Stopping\", \"component\", \"GraphBuilder\")\n\n\t// Set up the stop channel.\n\tgb.monitorLock.Lock()\n\tgb.stopCh = ctx.Done()\n\tgb.running = true\n\tgb.monitorLock.Unlock()\n\n\t// Start monitors and begin change processing until the stop channel is\n\t// closed.\n\tgb.startMonitors(logger)\n\twait.Until(func() { gb.runProcessGraphChanges(logger) }, 1*time.Second, ctx.Done())\n\n\t// Stop any running monitors.\n\tgb.monitorLock.Lock()\n\tdefer gb.monitorLock.Unlock()\n\tmonitors := gb.monitors\n\tstopped := 0\n\tfor _, monitor := range monitors {\n\t\tif monitor.stopCh != nil {\n\t\t\tstopped++\n\t\t\tclose(monitor.stopCh)\n\t\t}\n\t}\n\n\t// reset monitors so that the graph builder can be safely re-run/synced.\n\tgb.monitors = nil\n\tlogger.Info(\"stopped monitors\", \"stopped\", stopped, \"total\", len(monitors))\n}","line":{"from":290,"to":323}} {"id":100003928,"name":"DefaultIgnoredResources","signature":"func DefaultIgnoredResources() map[schema.GroupResource]struct{}","file":"pkg/controller/garbagecollector/graph_builder.go","code":"// DefaultIgnoredResources returns the default set of resources that the garbage collector controller\n// should ignore. This is exposed so downstream integrators can have access to the defaults, and add\n// to them as necessary when constructing the controller.\nfunc DefaultIgnoredResources() map[schema.GroupResource]struct{} {\n\treturn ignoredResources\n}","line":{"from":330,"to":335}} {"id":100003929,"name":"enqueueVirtualDeleteEvent","signature":"func (gb *GraphBuilder) enqueueVirtualDeleteEvent(ref objectReference)","file":"pkg/controller/garbagecollector/graph_builder.go","code":"// enqueueVirtualDeleteEvent is used to add a virtual delete event to be processed for virtual nodes\n// once it is determined they do not have backing objects in storage\nfunc (gb *GraphBuilder) enqueueVirtualDeleteEvent(ref objectReference) {\n\tgv, _ := schema.ParseGroupVersion(ref.APIVersion)\n\tgb.graphChanges.Add(\u0026event{\n\t\tvirtual: true,\n\t\teventType: deleteEvent,\n\t\tgvk: gv.WithKind(ref.Kind),\n\t\tobj: \u0026metaonly.MetadataOnlyObject{\n\t\t\tTypeMeta: metav1.TypeMeta{APIVersion: ref.APIVersion, Kind: ref.Kind},\n\t\t\tObjectMeta: metav1.ObjectMeta{Namespace: ref.Namespace, UID: ref.UID, Name: ref.Name},\n\t\t},\n\t})\n}","line":{"from":337,"to":350}} {"id":100003930,"name":"addDependentToOwners","signature":"func (gb *GraphBuilder) addDependentToOwners(logger klog.Logger, n *node, owners []metav1.OwnerReference)","file":"pkg/controller/garbagecollector/graph_builder.go","code":"// addDependentToOwners adds n to owners' dependents list. If the owner does not\n// exist in the gb.uidToNode yet, a \"virtual\" node will be created to represent\n// the owner. The \"virtual\" node will be enqueued to the attemptToDelete, so that\n// attemptToDeleteItem() will verify if the owner exists according to the API server.\nfunc (gb *GraphBuilder) addDependentToOwners(logger klog.Logger, n *node, owners []metav1.OwnerReference) {\n\t// track if some of the referenced owners already exist in the graph and have been observed,\n\t// and the dependent's ownerRef does not match their observed coordinates\n\thasPotentiallyInvalidOwnerReference := false\n\n\tfor _, owner := range owners {\n\t\townerNode, ok := gb.uidToNode.Read(owner.UID)\n\t\tif !ok {\n\t\t\t// Create a \"virtual\" node in the graph for the owner if it doesn't\n\t\t\t// exist in the graph yet.\n\t\t\townerNode = \u0026node{\n\t\t\t\tidentity: objectReference{\n\t\t\t\t\tOwnerReference: ownerReferenceCoordinates(owner),\n\t\t\t\t\tNamespace: n.identity.Namespace,\n\t\t\t\t},\n\t\t\t\tdependents: make(map[*node]struct{}),\n\t\t\t\tvirtual: true,\n\t\t\t}\n\t\t\tlogger.V(5).Info(\"add virtual item\", \"identity\", ownerNode.identity)\n\t\t\tgb.uidToNode.Write(ownerNode)\n\t\t}\n\t\townerNode.addDependent(n)\n\t\tif !ok {\n\t\t\t// Enqueue the virtual node into attemptToDelete.\n\t\t\t// The garbage processor will enqueue a virtual delete\n\t\t\t// event to delete it from the graph if API server confirms this\n\t\t\t// owner doesn't exist.\n\t\t\tgb.attemptToDelete.Add(ownerNode)\n\t\t} else if !hasPotentiallyInvalidOwnerReference {\n\t\t\townerIsNamespaced := len(ownerNode.identity.Namespace) \u003e 0\n\t\t\tif ownerIsNamespaced \u0026\u0026 ownerNode.identity.Namespace != n.identity.Namespace {\n\t\t\t\tif ownerNode.isObserved() {\n\t\t\t\t\t// The owner node has been observed via an informer\n\t\t\t\t\t// the dependent's namespace doesn't match the observed owner's namespace, this is definitely wrong.\n\t\t\t\t\t// cluster-scoped owners can be referenced as an owner from any namespace or cluster-scoped object.\n\t\t\t\t\tlogger.V(2).Info(\"item references an owner but does not match namespaces\", \"item\", n.identity, \"owner\", ownerNode.identity)\n\t\t\t\t\tgb.reportInvalidNamespaceOwnerRef(n, owner.UID)\n\t\t\t\t}\n\t\t\t\thasPotentiallyInvalidOwnerReference = true\n\t\t\t} else if !ownerReferenceMatchesCoordinates(owner, ownerNode.identity.OwnerReference) {\n\t\t\t\tif ownerNode.isObserved() {\n\t\t\t\t\t// The owner node has been observed via an informer\n\t\t\t\t\t// n's owner reference doesn't match the observed identity, this might be wrong.\n\t\t\t\t\tlogger.V(2).Info(\"item references an owner with coordinates that do not match the observed identity\", \"item\", n.identity, \"owner\", ownerNode.identity)\n\t\t\t\t}\n\t\t\t\thasPotentiallyInvalidOwnerReference = true\n\t\t\t} else if !ownerIsNamespaced \u0026\u0026 ownerNode.identity.Namespace != n.identity.Namespace \u0026\u0026 !ownerNode.isObserved() {\n\t\t\t\t// the ownerNode is cluster-scoped and virtual, and does not match the child node's namespace.\n\t\t\t\t// the owner could be a missing instance of a namespaced type incorrectly referenced by a cluster-scoped child (issue #98040).\n\t\t\t\t// enqueue this child to attemptToDelete to verify parent references.\n\t\t\t\thasPotentiallyInvalidOwnerReference = true\n\t\t\t}\n\t\t}\n\t}\n\n\tif hasPotentiallyInvalidOwnerReference {\n\t\t// Enqueue the potentially invalid dependent node into attemptToDelete.\n\t\t// The garbage processor will verify whether the owner references are dangling\n\t\t// and delete the dependent if all owner references are confirmed absent.\n\t\tgb.attemptToDelete.Add(n)\n\t}\n}","line":{"from":352,"to":417}} {"id":100003931,"name":"reportInvalidNamespaceOwnerRef","signature":"func (gb *GraphBuilder) reportInvalidNamespaceOwnerRef(n *node, invalidOwnerUID types.UID)","file":"pkg/controller/garbagecollector/graph_builder.go","code":"func (gb *GraphBuilder) reportInvalidNamespaceOwnerRef(n *node, invalidOwnerUID types.UID) {\n\tvar invalidOwnerRef metav1.OwnerReference\n\tvar found = false\n\tfor _, ownerRef := range n.owners {\n\t\tif ownerRef.UID == invalidOwnerUID {\n\t\t\tinvalidOwnerRef = ownerRef\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\treturn\n\t}\n\tref := \u0026v1.ObjectReference{\n\t\tKind: n.identity.Kind,\n\t\tAPIVersion: n.identity.APIVersion,\n\t\tNamespace: n.identity.Namespace,\n\t\tName: n.identity.Name,\n\t\tUID: n.identity.UID,\n\t}\n\tinvalidIdentity := objectReference{\n\t\tOwnerReference: metav1.OwnerReference{\n\t\t\tKind: invalidOwnerRef.Kind,\n\t\t\tAPIVersion: invalidOwnerRef.APIVersion,\n\t\t\tName: invalidOwnerRef.Name,\n\t\t\tUID: invalidOwnerRef.UID,\n\t\t},\n\t\tNamespace: n.identity.Namespace,\n\t}\n\tgb.eventRecorder.Eventf(ref, v1.EventTypeWarning, \"OwnerRefInvalidNamespace\", \"ownerRef %s does not exist in namespace %q\", invalidIdentity, n.identity.Namespace)\n}","line":{"from":419,"to":449}} {"id":100003932,"name":"insertNode","signature":"func (gb *GraphBuilder) insertNode(logger klog.Logger, n *node)","file":"pkg/controller/garbagecollector/graph_builder.go","code":"// insertNode insert the node to gb.uidToNode; then it finds all owners as listed\n// in n.owners, and adds the node to their dependents list.\nfunc (gb *GraphBuilder) insertNode(logger klog.Logger, n *node) {\n\tgb.uidToNode.Write(n)\n\tgb.addDependentToOwners(logger, n, n.owners)\n}","line":{"from":451,"to":456}} {"id":100003933,"name":"removeDependentFromOwners","signature":"func (gb *GraphBuilder) removeDependentFromOwners(n *node, owners []metav1.OwnerReference)","file":"pkg/controller/garbagecollector/graph_builder.go","code":"// removeDependentFromOwners remove n from owners' dependents list.\nfunc (gb *GraphBuilder) removeDependentFromOwners(n *node, owners []metav1.OwnerReference) {\n\tfor _, owner := range owners {\n\t\townerNode, ok := gb.uidToNode.Read(owner.UID)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\townerNode.deleteDependent(n)\n\t}\n}","line":{"from":458,"to":467}} {"id":100003934,"name":"removeNode","signature":"func (gb *GraphBuilder) removeNode(n *node)","file":"pkg/controller/garbagecollector/graph_builder.go","code":"// removeNode removes the node from gb.uidToNode, then finds all\n// owners as listed in n.owners, and removes n from their dependents list.\nfunc (gb *GraphBuilder) removeNode(n *node) {\n\tgb.uidToNode.Delete(n.identity.UID)\n\tgb.removeDependentFromOwners(n, n.owners)\n}","line":{"from":469,"to":474}} {"id":100003935,"name":"referencesDiffs","signature":"func referencesDiffs(old []metav1.OwnerReference, new []metav1.OwnerReference) (added []metav1.OwnerReference, removed []metav1.OwnerReference, changed []ownerRefPair)","file":"pkg/controller/garbagecollector/graph_builder.go","code":"// TODO: profile this function to see if a naive N^2 algorithm performs better\n// when the number of references is small.\nfunc referencesDiffs(old []metav1.OwnerReference, new []metav1.OwnerReference) (added []metav1.OwnerReference, removed []metav1.OwnerReference, changed []ownerRefPair) {\n\toldUIDToRef := make(map[string]metav1.OwnerReference)\n\tfor _, value := range old {\n\t\toldUIDToRef[string(value.UID)] = value\n\t}\n\toldUIDSet := sets.StringKeySet(oldUIDToRef)\n\tfor _, value := range new {\n\t\tnewUID := string(value.UID)\n\t\tif oldUIDSet.Has(newUID) {\n\t\t\tif !reflect.DeepEqual(oldUIDToRef[newUID], value) {\n\t\t\t\tchanged = append(changed, ownerRefPair{oldRef: oldUIDToRef[newUID], newRef: value})\n\t\t\t}\n\t\t\toldUIDSet.Delete(newUID)\n\t\t} else {\n\t\t\tadded = append(added, value)\n\t\t}\n\t}\n\tfor oldUID := range oldUIDSet {\n\t\tremoved = append(removed, oldUIDToRef[oldUID])\n\t}\n\n\treturn added, removed, changed\n}","line":{"from":481,"to":505}} {"id":100003936,"name":"deletionStartsWithFinalizer","signature":"func deletionStartsWithFinalizer(oldObj interface{}, newAccessor metav1.Object, matchingFinalizer string) bool","file":"pkg/controller/garbagecollector/graph_builder.go","code":"func deletionStartsWithFinalizer(oldObj interface{}, newAccessor metav1.Object, matchingFinalizer string) bool {\n\t// if the new object isn't being deleted, or doesn't have the finalizer we're interested in, return false\n\tif !beingDeleted(newAccessor) || !hasFinalizer(newAccessor, matchingFinalizer) {\n\t\treturn false\n\t}\n\n\t// if the old object is nil, or wasn't being deleted, or didn't have the finalizer, return true\n\tif oldObj == nil {\n\t\treturn true\n\t}\n\toldAccessor, err := meta.Accessor(oldObj)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"cannot access oldObj: %v\", err))\n\t\treturn false\n\t}\n\treturn !beingDeleted(oldAccessor) || !hasFinalizer(oldAccessor, matchingFinalizer)\n}","line":{"from":507,"to":523}} {"id":100003937,"name":"beingDeleted","signature":"func beingDeleted(accessor metav1.Object) bool","file":"pkg/controller/garbagecollector/graph_builder.go","code":"func beingDeleted(accessor metav1.Object) bool {\n\treturn accessor.GetDeletionTimestamp() != nil\n}","line":{"from":525,"to":527}} {"id":100003938,"name":"hasDeleteDependentsFinalizer","signature":"func hasDeleteDependentsFinalizer(accessor metav1.Object) bool","file":"pkg/controller/garbagecollector/graph_builder.go","code":"func hasDeleteDependentsFinalizer(accessor metav1.Object) bool {\n\treturn hasFinalizer(accessor, metav1.FinalizerDeleteDependents)\n}","line":{"from":529,"to":531}} {"id":100003939,"name":"hasOrphanFinalizer","signature":"func hasOrphanFinalizer(accessor metav1.Object) bool","file":"pkg/controller/garbagecollector/graph_builder.go","code":"func hasOrphanFinalizer(accessor metav1.Object) bool {\n\treturn hasFinalizer(accessor, metav1.FinalizerOrphanDependents)\n}","line":{"from":533,"to":535}} {"id":100003940,"name":"hasFinalizer","signature":"func hasFinalizer(accessor metav1.Object, matchingFinalizer string) bool","file":"pkg/controller/garbagecollector/graph_builder.go","code":"func hasFinalizer(accessor metav1.Object, matchingFinalizer string) bool {\n\tfinalizers := accessor.GetFinalizers()\n\tfor _, finalizer := range finalizers {\n\t\tif finalizer == matchingFinalizer {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":537,"to":545}} {"id":100003941,"name":"startsWaitingForDependentsDeleted","signature":"func startsWaitingForDependentsDeleted(oldObj interface{}, newAccessor metav1.Object) bool","file":"pkg/controller/garbagecollector/graph_builder.go","code":"// this function takes newAccessor directly because the caller already\n// instantiates an accessor for the newObj.\nfunc startsWaitingForDependentsDeleted(oldObj interface{}, newAccessor metav1.Object) bool {\n\treturn deletionStartsWithFinalizer(oldObj, newAccessor, metav1.FinalizerDeleteDependents)\n}","line":{"from":547,"to":551}} {"id":100003942,"name":"startsWaitingForDependentsOrphaned","signature":"func startsWaitingForDependentsOrphaned(oldObj interface{}, newAccessor metav1.Object) bool","file":"pkg/controller/garbagecollector/graph_builder.go","code":"// this function takes newAccessor directly because the caller already\n// instantiates an accessor for the newObj.\nfunc startsWaitingForDependentsOrphaned(oldObj interface{}, newAccessor metav1.Object) bool {\n\treturn deletionStartsWithFinalizer(oldObj, newAccessor, metav1.FinalizerOrphanDependents)\n}","line":{"from":553,"to":557}} {"id":100003943,"name":"addUnblockedOwnersToDeleteQueue","signature":"func (gb *GraphBuilder) addUnblockedOwnersToDeleteQueue(logger klog.Logger, removed []metav1.OwnerReference, changed []ownerRefPair)","file":"pkg/controller/garbagecollector/graph_builder.go","code":"// if an blocking ownerReference points to an object gets removed, or gets set to\n// \"BlockOwnerDeletion=false\", add the object to the attemptToDelete queue.\nfunc (gb *GraphBuilder) addUnblockedOwnersToDeleteQueue(logger klog.Logger, removed []metav1.OwnerReference, changed []ownerRefPair) {\n\tfor _, ref := range removed {\n\t\tif ref.BlockOwnerDeletion != nil \u0026\u0026 *ref.BlockOwnerDeletion {\n\t\t\tnode, found := gb.uidToNode.Read(ref.UID)\n\t\t\tif !found {\n\t\t\t\tlogger.V(5).Info(\"cannot find uid in uidToNode\", \"uid\", ref.UID)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgb.attemptToDelete.Add(node)\n\t\t}\n\t}\n\tfor _, c := range changed {\n\t\twasBlocked := c.oldRef.BlockOwnerDeletion != nil \u0026\u0026 *c.oldRef.BlockOwnerDeletion\n\t\tisUnblocked := c.newRef.BlockOwnerDeletion == nil || (c.newRef.BlockOwnerDeletion != nil \u0026\u0026 !*c.newRef.BlockOwnerDeletion)\n\t\tif wasBlocked \u0026\u0026 isUnblocked {\n\t\t\tnode, found := gb.uidToNode.Read(c.newRef.UID)\n\t\t\tif !found {\n\t\t\t\tlogger.V(5).Info(\"cannot find uid in uidToNode\", \"uid\", c.newRef.UID)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgb.attemptToDelete.Add(node)\n\t\t}\n\t}\n}","line":{"from":559,"to":584}} {"id":100003944,"name":"processTransitions","signature":"func (gb *GraphBuilder) processTransitions(logger klog.Logger, oldObj interface{}, newAccessor metav1.Object, n *node)","file":"pkg/controller/garbagecollector/graph_builder.go","code":"func (gb *GraphBuilder) processTransitions(logger klog.Logger, oldObj interface{}, newAccessor metav1.Object, n *node) {\n\tif startsWaitingForDependentsOrphaned(oldObj, newAccessor) {\n\t\tlogger.V(5).Info(\"add item to attemptToOrphan\", \"item\", n.identity)\n\t\tgb.attemptToOrphan.Add(n)\n\t\treturn\n\t}\n\tif startsWaitingForDependentsDeleted(oldObj, newAccessor) {\n\t\tlogger.V(2).Info(\"add item to attemptToDelete, because it's waiting for its dependents to be deleted\", \"item\", n.identity)\n\t\t// if the n is added as a \"virtual\" node, its deletingDependents field is not properly set, so always set it here.\n\t\tn.markDeletingDependents()\n\t\tfor dep := range n.dependents {\n\t\t\tgb.attemptToDelete.Add(dep)\n\t\t}\n\t\tgb.attemptToDelete.Add(n)\n\t}\n}","line":{"from":586,"to":601}} {"id":100003945,"name":"runProcessGraphChanges","signature":"func (gb *GraphBuilder) runProcessGraphChanges(logger klog.Logger)","file":"pkg/controller/garbagecollector/graph_builder.go","code":"func (gb *GraphBuilder) runProcessGraphChanges(logger klog.Logger) {\n\tfor gb.processGraphChanges(logger) {\n\t}\n}","line":{"from":603,"to":606}} {"id":100003946,"name":"identityFromEvent","signature":"func identityFromEvent(event *event, accessor metav1.Object) objectReference","file":"pkg/controller/garbagecollector/graph_builder.go","code":"func identityFromEvent(event *event, accessor metav1.Object) objectReference {\n\treturn objectReference{\n\t\tOwnerReference: metav1.OwnerReference{\n\t\t\tAPIVersion: event.gvk.GroupVersion().String(),\n\t\t\tKind: event.gvk.Kind,\n\t\t\tUID: accessor.GetUID(),\n\t\t\tName: accessor.GetName(),\n\t\t},\n\t\tNamespace: accessor.GetNamespace(),\n\t}\n}","line":{"from":608,"to":618}} {"id":100003947,"name":"processGraphChanges","signature":"func (gb *GraphBuilder) processGraphChanges(logger klog.Logger) bool","file":"pkg/controller/garbagecollector/graph_builder.go","code":"// Dequeueing an event from graphChanges, updating graph, populating dirty_queue.\nfunc (gb *GraphBuilder) processGraphChanges(logger klog.Logger) bool {\n\titem, quit := gb.graphChanges.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer gb.graphChanges.Done(item)\n\tevent, ok := item.(*event)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"expect a *event, got %v\", item))\n\t\treturn true\n\t}\n\tobj := event.obj\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"cannot access obj: %v\", err))\n\t\treturn true\n\t}\n\n\tlogger.V(5).Info(\"GraphBuilder process object\",\n\t\t\"apiVersion\", event.gvk.GroupVersion().String(),\n\t\t\"kind\", event.gvk.Kind,\n\t\t\"object\", klog.KObj(accessor),\n\t\t\"uid\", string(accessor.GetUID()),\n\t\t\"eventType\", event.eventType,\n\t\t\"virtual\", event.virtual,\n\t)\n\n\t// Check if the node already exists\n\texistingNode, found := gb.uidToNode.Read(accessor.GetUID())\n\tif found \u0026\u0026 !event.virtual \u0026\u0026 !existingNode.isObserved() {\n\t\t// this marks the node as having been observed via an informer event\n\t\t// 1. this depends on graphChanges only containing add/update events from the actual informer\n\t\t// 2. this allows things tracking virtual nodes' existence to stop polling and rely on informer events\n\t\tobservedIdentity := identityFromEvent(event, accessor)\n\t\tif observedIdentity != existingNode.identity {\n\t\t\t// find dependents that don't match the identity we observed\n\t\t\t_, potentiallyInvalidDependents := partitionDependents(existingNode.getDependents(), observedIdentity)\n\t\t\t// add those potentially invalid dependents to the attemptToDelete queue.\n\t\t\t// if their owners are still solid the attemptToDelete will be a no-op.\n\t\t\t// this covers the bad child -\u003e good parent observation sequence.\n\t\t\t// the good parent -\u003e bad child observation sequence is handled in addDependentToOwners\n\t\t\tfor _, dep := range potentiallyInvalidDependents {\n\t\t\t\tif len(observedIdentity.Namespace) \u003e 0 \u0026\u0026 dep.identity.Namespace != observedIdentity.Namespace {\n\t\t\t\t\t// Namespace mismatch, this is definitely wrong\n\t\t\t\t\tlogger.V(2).Info(\"item references an owner but does not match namespaces\",\n\t\t\t\t\t\t\"item\", dep.identity,\n\t\t\t\t\t\t\"owner\", observedIdentity,\n\t\t\t\t\t)\n\t\t\t\t\tgb.reportInvalidNamespaceOwnerRef(dep, observedIdentity.UID)\n\t\t\t\t}\n\t\t\t\tgb.attemptToDelete.Add(dep)\n\t\t\t}\n\n\t\t\t// make a copy (so we don't modify the existing node in place), store the observed identity, and replace the virtual node\n\t\t\tlogger.V(2).Info(\"replacing virtual item with observed item\",\n\t\t\t\t\"virtual\", existingNode.identity,\n\t\t\t\t\"observed\", observedIdentity,\n\t\t\t)\n\t\t\texistingNode = existingNode.clone()\n\t\t\texistingNode.identity = observedIdentity\n\t\t\tgb.uidToNode.Write(existingNode)\n\t\t}\n\t\texistingNode.markObserved()\n\t}\n\tswitch {\n\tcase (event.eventType == addEvent || event.eventType == updateEvent) \u0026\u0026 !found:\n\t\tnewNode := \u0026node{\n\t\t\tidentity: identityFromEvent(event, accessor),\n\t\t\tdependents: make(map[*node]struct{}),\n\t\t\towners: accessor.GetOwnerReferences(),\n\t\t\tdeletingDependents: beingDeleted(accessor) \u0026\u0026 hasDeleteDependentsFinalizer(accessor),\n\t\t\tbeingDeleted: beingDeleted(accessor),\n\t\t}\n\t\tgb.insertNode(logger, newNode)\n\t\t// the underlying delta_fifo may combine a creation and a deletion into\n\t\t// one event, so we need to further process the event.\n\t\tgb.processTransitions(logger, event.oldObj, accessor, newNode)\n\tcase (event.eventType == addEvent || event.eventType == updateEvent) \u0026\u0026 found:\n\t\t// handle changes in ownerReferences\n\t\tadded, removed, changed := referencesDiffs(existingNode.owners, accessor.GetOwnerReferences())\n\t\tif len(added) != 0 || len(removed) != 0 || len(changed) != 0 {\n\t\t\t// check if the changed dependency graph unblock owners that are\n\t\t\t// waiting for the deletion of their dependents.\n\t\t\tgb.addUnblockedOwnersToDeleteQueue(logger, removed, changed)\n\t\t\t// update the node itself\n\t\t\texistingNode.owners = accessor.GetOwnerReferences()\n\t\t\t// Add the node to its new owners' dependent lists.\n\t\t\tgb.addDependentToOwners(logger, existingNode, added)\n\t\t\t// remove the node from the dependent list of node that are no longer in\n\t\t\t// the node's owners list.\n\t\t\tgb.removeDependentFromOwners(existingNode, removed)\n\t\t}\n\n\t\tif beingDeleted(accessor) {\n\t\t\texistingNode.markBeingDeleted()\n\t\t}\n\t\tgb.processTransitions(logger, event.oldObj, accessor, existingNode)\n\tcase event.eventType == deleteEvent:\n\t\tif !found {\n\t\t\tlogger.V(5).Info(\"item doesn't exist in the graph, this shouldn't happen\",\n\t\t\t\t\"item\", accessor.GetUID(),\n\t\t\t)\n\t\t\treturn true\n\t\t}\n\n\t\tremoveExistingNode := true\n\n\t\tif event.virtual {\n\t\t\t// this is a virtual delete event, not one observed from an informer\n\t\t\tdeletedIdentity := identityFromEvent(event, accessor)\n\t\t\tif existingNode.virtual {\n\n\t\t\t\t// our existing node is also virtual, we're not sure of its coordinates.\n\t\t\t\t// see if any dependents reference this owner with coordinates other than the one we got a virtual delete event for.\n\t\t\t\tif matchingDependents, nonmatchingDependents := partitionDependents(existingNode.getDependents(), deletedIdentity); len(nonmatchingDependents) \u003e 0 {\n\n\t\t\t\t\t// some of our dependents disagree on our coordinates, so do not remove the existing virtual node from the graph\n\t\t\t\t\tremoveExistingNode = false\n\n\t\t\t\t\tif len(matchingDependents) \u003e 0 {\n\t\t\t\t\t\t// mark the observed deleted identity as absent\n\t\t\t\t\t\tgb.absentOwnerCache.Add(deletedIdentity)\n\t\t\t\t\t\t// attempt to delete dependents that do match the verified deleted identity\n\t\t\t\t\t\tfor _, dep := range matchingDependents {\n\t\t\t\t\t\t\tgb.attemptToDelete.Add(dep)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// if the delete event verified existingNode.identity doesn't exist...\n\t\t\t\t\tif existingNode.identity == deletedIdentity {\n\t\t\t\t\t\t// find an alternative identity our nonmatching dependents refer to us by\n\t\t\t\t\t\treplacementIdentity := getAlternateOwnerIdentity(nonmatchingDependents, deletedIdentity)\n\t\t\t\t\t\tif replacementIdentity != nil {\n\t\t\t\t\t\t\t// replace the existing virtual node with a new one with one of our other potential identities\n\t\t\t\t\t\t\treplacementNode := existingNode.clone()\n\t\t\t\t\t\t\treplacementNode.identity = *replacementIdentity\n\t\t\t\t\t\t\tgb.uidToNode.Write(replacementNode)\n\t\t\t\t\t\t\t// and add the new virtual node back to the attemptToDelete queue\n\t\t\t\t\t\t\tgb.attemptToDelete.AddRateLimited(replacementNode)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} else if existingNode.identity != deletedIdentity {\n\t\t\t\t// do not remove the existing real node from the graph based on a virtual delete event\n\t\t\t\tremoveExistingNode = false\n\n\t\t\t\t// our existing node which was observed via informer disagrees with the virtual delete event's coordinates\n\t\t\t\tmatchingDependents, _ := partitionDependents(existingNode.getDependents(), deletedIdentity)\n\n\t\t\t\tif len(matchingDependents) \u003e 0 {\n\t\t\t\t\t// mark the observed deleted identity as absent\n\t\t\t\t\tgb.absentOwnerCache.Add(deletedIdentity)\n\t\t\t\t\t// attempt to delete dependents that do match the verified deleted identity\n\t\t\t\t\tfor _, dep := range matchingDependents {\n\t\t\t\t\t\tgb.attemptToDelete.Add(dep)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif removeExistingNode {\n\t\t\t// removeNode updates the graph\n\t\t\tgb.removeNode(existingNode)\n\t\t\texistingNode.dependentsLock.RLock()\n\t\t\tdefer existingNode.dependentsLock.RUnlock()\n\t\t\tif len(existingNode.dependents) \u003e 0 {\n\t\t\t\tgb.absentOwnerCache.Add(identityFromEvent(event, accessor))\n\t\t\t}\n\t\t\tfor dep := range existingNode.dependents {\n\t\t\t\tgb.attemptToDelete.Add(dep)\n\t\t\t}\n\t\t\tfor _, owner := range existingNode.owners {\n\t\t\t\townerNode, found := gb.uidToNode.Read(owner.UID)\n\t\t\t\tif !found || !ownerNode.isDeletingDependents() {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// this is to let attempToDeleteItem check if all the owner's\n\t\t\t\t// dependents are deleted, if so, the owner will be deleted.\n\t\t\t\tgb.attemptToDelete.Add(ownerNode)\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}","line":{"from":620,"to":805}} {"id":100003948,"name":"partitionDependents","signature":"func partitionDependents(dependents []*node, matchOwnerIdentity objectReference) (matching, nonmatching []*node)","file":"pkg/controller/garbagecollector/graph_builder.go","code":"// partitionDependents divides the provided dependents into a list which have an ownerReference matching the provided identity,\n// and ones which have an ownerReference for the given uid that do not match the provided identity.\n// Note that a dependent with multiple ownerReferences for the target uid can end up in both lists.\nfunc partitionDependents(dependents []*node, matchOwnerIdentity objectReference) (matching, nonmatching []*node) {\n\townerIsNamespaced := len(matchOwnerIdentity.Namespace) \u003e 0\n\tfor i := range dependents {\n\t\tdep := dependents[i]\n\t\tfoundMatch := false\n\t\tfoundMismatch := false\n\t\t// if the dep namespace matches or the owner is cluster scoped ...\n\t\tif ownerIsNamespaced \u0026\u0026 matchOwnerIdentity.Namespace != dep.identity.Namespace {\n\t\t\t// all references to the parent do not match, since the dependent namespace does not match the owner\n\t\t\tfoundMismatch = true\n\t\t} else {\n\t\t\tfor _, ownerRef := range dep.owners {\n\t\t\t\t// ... find the ownerRef with a matching uid ...\n\t\t\t\tif ownerRef.UID == matchOwnerIdentity.UID {\n\t\t\t\t\t// ... and check if it matches all coordinates\n\t\t\t\t\tif ownerReferenceMatchesCoordinates(ownerRef, matchOwnerIdentity.OwnerReference) {\n\t\t\t\t\t\tfoundMatch = true\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfoundMismatch = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif foundMatch {\n\t\t\tmatching = append(matching, dep)\n\t\t}\n\t\tif foundMismatch {\n\t\t\tnonmatching = append(nonmatching, dep)\n\t\t}\n\t}\n\treturn matching, nonmatching\n}","line":{"from":807,"to":842}} {"id":100003949,"name":"referenceLessThan","signature":"func referenceLessThan(a, b objectReference) bool","file":"pkg/controller/garbagecollector/graph_builder.go","code":"func referenceLessThan(a, b objectReference) bool {\n\t// kind/apiVersion are more significant than namespace,\n\t// so that we get coherent ordering between kinds\n\t// regardless of whether they are cluster-scoped or namespaced\n\tif a.Kind != b.Kind {\n\t\treturn a.Kind \u003c b.Kind\n\t}\n\tif a.APIVersion != b.APIVersion {\n\t\treturn a.APIVersion \u003c b.APIVersion\n\t}\n\t// namespace is more significant than name\n\tif a.Namespace != b.Namespace {\n\t\treturn a.Namespace \u003c b.Namespace\n\t}\n\t// name is more significant than uid\n\tif a.Name != b.Name {\n\t\treturn a.Name \u003c b.Name\n\t}\n\t// uid is included for completeness, but is expected to be identical\n\t// when getting alternate identities for an owner since they are keyed by uid\n\tif a.UID != b.UID {\n\t\treturn a.UID \u003c b.UID\n\t}\n\treturn false\n}","line":{"from":844,"to":868}} {"id":100003950,"name":"getAlternateOwnerIdentity","signature":"func getAlternateOwnerIdentity(deps []*node, verifiedAbsentIdentity objectReference) *objectReference","file":"pkg/controller/garbagecollector/graph_builder.go","code":"// getAlternateOwnerIdentity searches deps for owner references which match\n// verifiedAbsentIdentity.UID but differ in apiVersion/kind/name or namespace.\n// The first that follows verifiedAbsentIdentity (according to referenceLessThan) is returned.\n// If none follow verifiedAbsentIdentity, the first (according to referenceLessThan) is returned.\n// If no alternate identities are found, nil is returned.\nfunc getAlternateOwnerIdentity(deps []*node, verifiedAbsentIdentity objectReference) *objectReference {\n\tabsentIdentityIsClusterScoped := len(verifiedAbsentIdentity.Namespace) == 0\n\n\tseenAlternates := map[objectReference]bool{verifiedAbsentIdentity: true}\n\n\t// keep track of the first alternate reference (according to referenceLessThan)\n\tvar first *objectReference\n\t// keep track of the first reference following verifiedAbsentIdentity (according to referenceLessThan)\n\tvar firstFollowing *objectReference\n\n\tfor _, dep := range deps {\n\t\tfor _, ownerRef := range dep.owners {\n\t\t\tif ownerRef.UID != verifiedAbsentIdentity.UID {\n\t\t\t\t// skip references that aren't the uid we care about\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif ownerReferenceMatchesCoordinates(ownerRef, verifiedAbsentIdentity.OwnerReference) {\n\t\t\t\tif absentIdentityIsClusterScoped || verifiedAbsentIdentity.Namespace == dep.identity.Namespace {\n\t\t\t\t\t// skip references that exactly match verifiedAbsentIdentity\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tref := objectReference{OwnerReference: ownerReferenceCoordinates(ownerRef), Namespace: dep.identity.Namespace}\n\t\t\tif absentIdentityIsClusterScoped \u0026\u0026 ref.APIVersion == verifiedAbsentIdentity.APIVersion \u0026\u0026 ref.Kind == verifiedAbsentIdentity.Kind {\n\t\t\t\t// we know this apiVersion/kind is cluster-scoped because of verifiedAbsentIdentity,\n\t\t\t\t// so clear the namespace from the alternate identity\n\t\t\t\tref.Namespace = \"\"\n\t\t\t}\n\n\t\t\tif seenAlternates[ref] {\n\t\t\t\t// skip references we've already seen\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tseenAlternates[ref] = true\n\n\t\t\tif first == nil || referenceLessThan(ref, *first) {\n\t\t\t\t// this alternate comes first lexically\n\t\t\t\tfirst = \u0026ref\n\t\t\t}\n\t\t\tif referenceLessThan(verifiedAbsentIdentity, ref) \u0026\u0026 (firstFollowing == nil || referenceLessThan(ref, *firstFollowing)) {\n\t\t\t\t// this alternate is the first following verifiedAbsentIdentity lexically\n\t\t\t\tfirstFollowing = \u0026ref\n\t\t\t}\n\t\t}\n\t}\n\n\t// return the first alternate identity following the verified absent identity, if there is one\n\tif firstFollowing != nil {\n\t\treturn firstFollowing\n\t}\n\t// otherwise return the first alternate identity\n\treturn first\n}","line":{"from":870,"to":929}} {"id":100003951,"name":"Register","signature":"func Register()","file":"pkg/controller/garbagecollector/metrics/metrics.go","code":"// Register registers GarbageCollectorController metrics.\nfunc Register() {\n\tregisterMetrics.Do(func() {\n\t\tlegacyregistry.MustRegister(GarbageCollectorResourcesSyncError)\n\t})\n}","line":{"from":40,"to":45}} {"id":100003952,"name":"resourceDefaultNamespace","signature":"func resourceDefaultNamespace(namespaced bool, defaultNamespace string) string","file":"pkg/controller/garbagecollector/operations.go","code":"// cluster scoped resources don't have namespaces. Default to the item's namespace, but clear it for cluster scoped resources\nfunc resourceDefaultNamespace(namespaced bool, defaultNamespace string) string {\n\tif namespaced {\n\t\treturn defaultNamespace\n\t}\n\treturn \"\"\n}","line":{"from":33,"to":39}} {"id":100003953,"name":"apiResource","signature":"func (gc *GarbageCollector) apiResource(apiVersion, kind string) (schema.GroupVersionResource, bool, error)","file":"pkg/controller/garbagecollector/operations.go","code":"// apiResource consults the REST mapper to translate an \u003capiVersion, kind,\n// namespace\u003e tuple to a unversioned.APIResource struct.\nfunc (gc *GarbageCollector) apiResource(apiVersion, kind string) (schema.GroupVersionResource, bool, error) {\n\tfqKind := schema.FromAPIVersionAndKind(apiVersion, kind)\n\tmapping, err := gc.restMapper.RESTMapping(fqKind.GroupKind(), fqKind.Version)\n\tif err != nil {\n\t\treturn schema.GroupVersionResource{}, false, newRESTMappingError(kind, apiVersion)\n\t}\n\treturn mapping.Resource, mapping.Scope == meta.RESTScopeNamespace, nil\n}","line":{"from":41,"to":50}} {"id":100003954,"name":"deleteObject","signature":"func (gc *GarbageCollector) deleteObject(item objectReference, policy *metav1.DeletionPropagation) error","file":"pkg/controller/garbagecollector/operations.go","code":"func (gc *GarbageCollector) deleteObject(item objectReference, policy *metav1.DeletionPropagation) error {\n\tresource, namespaced, err := gc.apiResource(item.APIVersion, item.Kind)\n\tif err != nil {\n\t\treturn err\n\t}\n\tuid := item.UID\n\tpreconditions := metav1.Preconditions{UID: \u0026uid}\n\tdeleteOptions := metav1.DeleteOptions{Preconditions: \u0026preconditions, PropagationPolicy: policy}\n\treturn gc.metadataClient.Resource(resource).Namespace(resourceDefaultNamespace(namespaced, item.Namespace)).Delete(context.TODO(), item.Name, deleteOptions)\n}","line":{"from":52,"to":61}} {"id":100003955,"name":"getObject","signature":"func (gc *GarbageCollector) getObject(item objectReference) (*metav1.PartialObjectMetadata, error)","file":"pkg/controller/garbagecollector/operations.go","code":"func (gc *GarbageCollector) getObject(item objectReference) (*metav1.PartialObjectMetadata, error) {\n\tresource, namespaced, err := gc.apiResource(item.APIVersion, item.Kind)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnamespace := resourceDefaultNamespace(namespaced, item.Namespace)\n\tif namespaced \u0026\u0026 len(namespace) == 0 {\n\t\t// the type is namespaced, but we have no namespace coordinate.\n\t\t// the only way this can happen is if a cluster-scoped object referenced this type as an owner.\n\t\treturn nil, namespacedOwnerOfClusterScopedObjectErr\n\t}\n\treturn gc.metadataClient.Resource(resource).Namespace(namespace).Get(context.TODO(), item.Name, metav1.GetOptions{})\n}","line":{"from":63,"to":75}} {"id":100003956,"name":"patchObject","signature":"func (gc *GarbageCollector) patchObject(item objectReference, patch []byte, pt types.PatchType) (*metav1.PartialObjectMetadata, error)","file":"pkg/controller/garbagecollector/operations.go","code":"func (gc *GarbageCollector) patchObject(item objectReference, patch []byte, pt types.PatchType) (*metav1.PartialObjectMetadata, error) {\n\tresource, namespaced, err := gc.apiResource(item.APIVersion, item.Kind)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn gc.metadataClient.Resource(resource).Namespace(resourceDefaultNamespace(namespaced, item.Namespace)).Patch(context.TODO(), item.Name, pt, patch, metav1.PatchOptions{})\n}","line":{"from":77,"to":83}} {"id":100003957,"name":"removeFinalizer","signature":"func (gc *GarbageCollector) removeFinalizer(logger klog.Logger, owner *node, targetFinalizer string) error","file":"pkg/controller/garbagecollector/operations.go","code":"func (gc *GarbageCollector) removeFinalizer(logger klog.Logger, owner *node, targetFinalizer string) error {\n\terr := retry.RetryOnConflict(retry.DefaultBackoff, func() error {\n\t\townerObject, err := gc.getObject(owner.identity)\n\t\tif errors.IsNotFound(err) {\n\t\t\treturn nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"cannot finalize owner %s, because cannot get it: %v. The garbage collector will retry later\", owner.identity, err)\n\t\t}\n\t\taccessor, err := meta.Accessor(ownerObject)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"cannot access the owner object %v: %v. The garbage collector will retry later\", ownerObject, err)\n\t\t}\n\t\tfinalizers := accessor.GetFinalizers()\n\t\tvar newFinalizers []string\n\t\tfound := false\n\t\tfor _, f := range finalizers {\n\t\t\tif f == targetFinalizer {\n\t\t\t\tfound = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnewFinalizers = append(newFinalizers, f)\n\t\t}\n\t\tif !found {\n\t\t\tlogger.V(5).Info(\"finalizer already removed from object\", \"finalizer\", targetFinalizer, \"object\", owner.identity)\n\t\t\treturn nil\n\t\t}\n\n\t\t// remove the owner from dependent's OwnerReferences\n\t\tpatch, err := json.Marshal(\u0026objectForFinalizersPatch{\n\t\t\tObjectMetaForFinalizersPatch: ObjectMetaForFinalizersPatch{\n\t\t\t\tResourceVersion: accessor.GetResourceVersion(),\n\t\t\t\tFinalizers: newFinalizers,\n\t\t\t},\n\t\t})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to finalize %s due to an error serializing patch: %v\", owner.identity, err)\n\t\t}\n\t\t_, err = gc.patchObject(owner.identity, patch, types.MergePatchType)\n\t\treturn err\n\t})\n\tif errors.IsConflict(err) {\n\t\treturn fmt.Errorf(\"updateMaxRetries(%d) has reached. The garbage collector will retry later for owner %v\", retry.DefaultBackoff.Steps, owner.identity)\n\t}\n\treturn err\n}","line":{"from":85,"to":130}} {"id":100003958,"name":"getMetadata","signature":"func (gc *GarbageCollector) getMetadata(apiVersion, kind, namespace, name string) (metav1.Object, error)","file":"pkg/controller/garbagecollector/patch.go","code":"// getMetadata tries getting object metadata from local cache, and sends GET request to apiserver when\n// local cache is not available or not latest.\nfunc (gc *GarbageCollector) getMetadata(apiVersion, kind, namespace, name string) (metav1.Object, error) {\n\tapiResource, _, err := gc.apiResource(apiVersion, kind)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgc.dependencyGraphBuilder.monitorLock.RLock()\n\tdefer gc.dependencyGraphBuilder.monitorLock.RUnlock()\n\tm, ok := gc.dependencyGraphBuilder.monitors[apiResource]\n\tif !ok || m == nil {\n\t\t// If local cache doesn't exist for mapping.Resource, send a GET request to API server\n\t\treturn gc.metadataClient.Resource(apiResource).Namespace(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\t}\n\tkey := name\n\tif len(namespace) != 0 {\n\t\tkey = namespace + \"/\" + name\n\t}\n\traw, exist, err := m.store.GetByKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exist {\n\t\t// If local cache doesn't contain the object, send a GET request to API server\n\t\treturn gc.metadataClient.Resource(apiResource).Namespace(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\t}\n\tobj, ok := raw.(runtime.Object)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"expect a runtime.Object, got %v\", raw)\n\t}\n\treturn meta.Accessor(obj)\n}","line":{"from":32,"to":63}} {"id":100003959,"name":"patch","signature":"func (gc *GarbageCollector) patch(item *node, smp []byte, jmp jsonMergePatchFunc) (*metav1.PartialObjectMetadata, error)","file":"pkg/controller/garbagecollector/patch.go","code":"// patch tries strategic merge patch on item first, and if SMP is not supported, it fallbacks to JSON merge\n// patch.\nfunc (gc *GarbageCollector) patch(item *node, smp []byte, jmp jsonMergePatchFunc) (*metav1.PartialObjectMetadata, error) {\n\tsmpResult, err := gc.patchObject(item.identity, smp, types.StrategicMergePatchType)\n\tif err == nil {\n\t\treturn smpResult, nil\n\t}\n\tif !errors.IsUnsupportedMediaType(err) {\n\t\treturn nil, err\n\t}\n\t// StrategicMergePatch is not supported, use JSON merge patch instead\n\tpatch, err := jmp(item)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn gc.patchObject(item.identity, patch, types.MergePatchType)\n}","line":{"from":89,"to":105}} {"id":100003960,"name":"deleteOwnerRefJSONMergePatch","signature":"func (gc *GarbageCollector) deleteOwnerRefJSONMergePatch(item *node, ownerUIDs ...types.UID) ([]byte, error)","file":"pkg/controller/garbagecollector/patch.go","code":"// Returns JSON merge patch that removes the ownerReferences matching ownerUIDs.\nfunc (gc *GarbageCollector) deleteOwnerRefJSONMergePatch(item *node, ownerUIDs ...types.UID) ([]byte, error) {\n\taccessor, err := gc.getMetadata(item.identity.APIVersion, item.identity.Kind, item.identity.Namespace, item.identity.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\texpectedObjectMeta := ObjectMetaForPatch{}\n\texpectedObjectMeta.ResourceVersion = accessor.GetResourceVersion()\n\trefs := accessor.GetOwnerReferences()\n\tfor _, ref := range refs {\n\t\tvar skip bool\n\t\tfor _, ownerUID := range ownerUIDs {\n\t\t\tif ref.UID == ownerUID {\n\t\t\t\tskip = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !skip {\n\t\t\texpectedObjectMeta.OwnerReferences = append(expectedObjectMeta.OwnerReferences, ref)\n\t\t}\n\t}\n\treturn json.Marshal(objectForPatch{expectedObjectMeta})\n}","line":{"from":107,"to":129}} {"id":100003961,"name":"unblockOwnerReferencesStrategicMergePatch","signature":"func (n *node) unblockOwnerReferencesStrategicMergePatch() ([]byte, error)","file":"pkg/controller/garbagecollector/patch.go","code":"// Generate a patch that unsets the BlockOwnerDeletion field of all\n// ownerReferences of node.\nfunc (n *node) unblockOwnerReferencesStrategicMergePatch() ([]byte, error) {\n\tvar dummy metaonly.MetadataOnlyObject\n\tvar blockingRefs []metav1.OwnerReference\n\tfalseVar := false\n\tfor _, owner := range n.owners {\n\t\tif owner.BlockOwnerDeletion != nil \u0026\u0026 *owner.BlockOwnerDeletion {\n\t\t\tref := owner\n\t\t\tref.BlockOwnerDeletion = \u0026falseVar\n\t\t\tblockingRefs = append(blockingRefs, ref)\n\t\t}\n\t}\n\tdummy.ObjectMeta.SetOwnerReferences(blockingRefs)\n\tdummy.ObjectMeta.UID = n.identity.UID\n\treturn json.Marshal(dummy)\n}","line":{"from":131,"to":147}} {"id":100003962,"name":"unblockOwnerReferencesJSONMergePatch","signature":"func (gc *GarbageCollector) unblockOwnerReferencesJSONMergePatch(n *node) ([]byte, error)","file":"pkg/controller/garbagecollector/patch.go","code":"// Generate a JSON merge patch that unsets the BlockOwnerDeletion field of all\n// ownerReferences of node.\nfunc (gc *GarbageCollector) unblockOwnerReferencesJSONMergePatch(n *node) ([]byte, error) {\n\taccessor, err := gc.getMetadata(n.identity.APIVersion, n.identity.Kind, n.identity.Namespace, n.identity.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\texpectedObjectMeta := ObjectMetaForPatch{}\n\texpectedObjectMeta.ResourceVersion = accessor.GetResourceVersion()\n\tvar expectedOwners []metav1.OwnerReference\n\tfalseVar := false\n\tfor _, owner := range n.owners {\n\t\towner.BlockOwnerDeletion = \u0026falseVar\n\t\texpectedOwners = append(expectedOwners, owner)\n\t}\n\texpectedObjectMeta.OwnerReferences = expectedOwners\n\treturn json.Marshal(objectForPatch{expectedObjectMeta})\n}","line":{"from":149,"to":166}} {"id":100003963,"name":"NewReferenceCache","signature":"func NewReferenceCache(maxCacheEntries int) *ReferenceCache","file":"pkg/controller/garbagecollector/uid_cache.go","code":"// NewReferenceCache returns a ReferenceCache.\nfunc NewReferenceCache(maxCacheEntries int) *ReferenceCache {\n\treturn \u0026ReferenceCache{\n\t\tcache: lru.New(maxCacheEntries),\n\t}\n}","line":{"from":31,"to":36}} {"id":100003964,"name":"Add","signature":"func (c *ReferenceCache) Add(reference objectReference)","file":"pkg/controller/garbagecollector/uid_cache.go","code":"// Add adds a uid to the cache.\nfunc (c *ReferenceCache) Add(reference objectReference) {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tc.cache.Add(reference, nil)\n}","line":{"from":38,"to":43}} {"id":100003965,"name":"Has","signature":"func (c *ReferenceCache) Has(reference objectReference) bool","file":"pkg/controller/garbagecollector/uid_cache.go","code":"// Has returns if a uid is in the cache.\nfunc (c *ReferenceCache) Has(reference objectReference) bool {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\t_, found := c.cache.Get(reference)\n\treturn found\n}","line":{"from":45,"to":51}} {"id":100003966,"name":"ControllerRevisionName","signature":"func ControllerRevisionName(prefix string, hash string) string","file":"pkg/controller/history/controller_history.go","code":"// ControllerRevisionName returns the Name for a ControllerRevision in the form prefix-hash. If the length\n// of prefix is greater than 223 bytes, it is truncated to allow for a name that is no larger than 253 bytes.\nfunc ControllerRevisionName(prefix string, hash string) string {\n\tif len(prefix) \u003e 223 {\n\t\tprefix = prefix[:223]\n\t}\n\n\treturn fmt.Sprintf(\"%s-%s\", prefix, hash)\n}","line":{"from":51,"to":59}} {"id":100003967,"name":"NewControllerRevision","signature":"func NewControllerRevision(parent metav1.Object,","file":"pkg/controller/history/controller_history.go","code":"// NewControllerRevision returns a ControllerRevision with a ControllerRef pointing to parent and indicating that\n// parent is of parentKind. The ControllerRevision has labels matching template labels, contains Data equal to data, and\n// has a Revision equal to revision. The collisionCount is used when creating the name of the ControllerRevision\n// so the name is likely unique. If the returned error is nil, the returned ControllerRevision is valid. If the\n// returned error is not nil, the returned ControllerRevision is invalid for use.\nfunc NewControllerRevision(parent metav1.Object,\n\tparentKind schema.GroupVersionKind,\n\ttemplateLabels map[string]string,\n\tdata runtime.RawExtension,\n\trevision int64,\n\tcollisionCount *int32) (*apps.ControllerRevision, error) {\n\tlabelMap := make(map[string]string)\n\tfor k, v := range templateLabels {\n\t\tlabelMap[k] = v\n\t}\n\tcr := \u0026apps.ControllerRevision{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tLabels: labelMap,\n\t\t\tOwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(parent, parentKind)},\n\t\t},\n\t\tData: data,\n\t\tRevision: revision,\n\t}\n\thash := HashControllerRevision(cr, collisionCount)\n\tcr.Name = ControllerRevisionName(parent.GetName(), hash)\n\tcr.Labels[ControllerRevisionHashLabel] = hash\n\treturn cr, nil\n}","line":{"from":61,"to":88}} {"id":100003968,"name":"HashControllerRevision","signature":"func HashControllerRevision(revision *apps.ControllerRevision, probe *int32) string","file":"pkg/controller/history/controller_history.go","code":"// HashControllerRevision hashes the contents of revision's Data using FNV hashing. If probe is not nil, the byte value\n// of probe is added written to the hash as well. The returned hash will be a safe encoded string to avoid bad words.\nfunc HashControllerRevision(revision *apps.ControllerRevision, probe *int32) string {\n\thf := fnv.New32()\n\tif len(revision.Data.Raw) \u003e 0 {\n\t\thf.Write(revision.Data.Raw)\n\t}\n\tif revision.Data.Object != nil {\n\t\thashutil.DeepHashObject(hf, revision.Data.Object)\n\t}\n\tif probe != nil {\n\t\thf.Write([]byte(strconv.FormatInt(int64(*probe), 10)))\n\t}\n\treturn rand.SafeEncodeString(fmt.Sprint(hf.Sum32()))\n}","line":{"from":90,"to":104}} {"id":100003969,"name":"SortControllerRevisions","signature":"func SortControllerRevisions(revisions []*apps.ControllerRevision)","file":"pkg/controller/history/controller_history.go","code":"// SortControllerRevisions sorts revisions by their Revision.\nfunc SortControllerRevisions(revisions []*apps.ControllerRevision) {\n\tsort.Stable(byRevision(revisions))\n}","line":{"from":106,"to":109}} {"id":100003970,"name":"EqualRevision","signature":"func EqualRevision(lhs *apps.ControllerRevision, rhs *apps.ControllerRevision) bool","file":"pkg/controller/history/controller_history.go","code":"// EqualRevision returns true if lhs and rhs are either both nil, or both point to non-nil ControllerRevisions that\n// contain semantically equivalent data. Otherwise this method returns false.\nfunc EqualRevision(lhs *apps.ControllerRevision, rhs *apps.ControllerRevision) bool {\n\tvar lhsHash, rhsHash *uint32\n\tif lhs == nil || rhs == nil {\n\t\treturn lhs == rhs\n\t}\n\tif hs, found := lhs.Labels[ControllerRevisionHashLabel]; found {\n\t\thash, err := strconv.ParseInt(hs, 10, 32)\n\t\tif err == nil {\n\t\t\tlhsHash = new(uint32)\n\t\t\t*lhsHash = uint32(hash)\n\t\t}\n\t}\n\tif hs, found := rhs.Labels[ControllerRevisionHashLabel]; found {\n\t\thash, err := strconv.ParseInt(hs, 10, 32)\n\t\tif err == nil {\n\t\t\trhsHash = new(uint32)\n\t\t\t*rhsHash = uint32(hash)\n\t\t}\n\t}\n\tif lhsHash != nil \u0026\u0026 rhsHash != nil \u0026\u0026 *lhsHash != *rhsHash {\n\t\treturn false\n\t}\n\treturn bytes.Equal(lhs.Data.Raw, rhs.Data.Raw) \u0026\u0026 apiequality.Semantic.DeepEqual(lhs.Data.Object, rhs.Data.Object)\n}","line":{"from":111,"to":136}} {"id":100003971,"name":"FindEqualRevisions","signature":"func FindEqualRevisions(revisions []*apps.ControllerRevision, needle *apps.ControllerRevision) []*apps.ControllerRevision","file":"pkg/controller/history/controller_history.go","code":"// FindEqualRevisions returns all ControllerRevisions in revisions that are equal to needle using EqualRevision as the\n// equality test. The returned slice preserves the order of revisions.\nfunc FindEqualRevisions(revisions []*apps.ControllerRevision, needle *apps.ControllerRevision) []*apps.ControllerRevision {\n\tvar eq []*apps.ControllerRevision\n\tfor i := range revisions {\n\t\tif EqualRevision(revisions[i], needle) {\n\t\t\teq = append(eq, revisions[i])\n\t\t}\n\t}\n\treturn eq\n}","line":{"from":138,"to":148}} {"id":100003972,"name":"Len","signature":"func (br byRevision) Len() int","file":"pkg/controller/history/controller_history.go","code":"func (br byRevision) Len() int {\n\treturn len(br)\n}","line":{"from":153,"to":155}} {"id":100003973,"name":"Less","signature":"func (br byRevision) Less(i, j int) bool","file":"pkg/controller/history/controller_history.go","code":"// Less breaks ties first by creation timestamp, then by name\nfunc (br byRevision) Less(i, j int) bool {\n\tif br[i].Revision == br[j].Revision {\n\t\tif br[j].CreationTimestamp.Equal(\u0026br[i].CreationTimestamp) {\n\t\t\treturn br[i].Name \u003c br[j].Name\n\t\t}\n\t\treturn br[j].CreationTimestamp.After(br[i].CreationTimestamp.Time)\n\t}\n\treturn br[i].Revision \u003c br[j].Revision\n}","line":{"from":157,"to":166}} {"id":100003974,"name":"Swap","signature":"func (br byRevision) Swap(i, j int)","file":"pkg/controller/history/controller_history.go","code":"func (br byRevision) Swap(i, j int) {\n\tbr[i], br[j] = br[j], br[i]\n}","line":{"from":168,"to":170}} {"id":100003975,"name":"NewHistory","signature":"func NewHistory(client clientset.Interface, lister appslisters.ControllerRevisionLister) Interface","file":"pkg/controller/history/controller_history.go","code":"// NewHistory returns an instance of Interface that uses client to communicate with the API Server and lister to list\n// ControllerRevisions. This method should be used to create an Interface for all scenarios other than testing.\nfunc NewHistory(client clientset.Interface, lister appslisters.ControllerRevisionLister) Interface {\n\treturn \u0026realHistory{client, lister}\n}","line":{"from":205,"to":209}} {"id":100003976,"name":"NewFakeHistory","signature":"func NewFakeHistory(informer appsinformers.ControllerRevisionInformer) Interface","file":"pkg/controller/history/controller_history.go","code":"// NewFakeHistory returns an instance of Interface that uses informer to create, update, list, and delete\n// ControllerRevisions. This method should be used to create an Interface for testing purposes.\nfunc NewFakeHistory(informer appsinformers.ControllerRevisionInformer) Interface {\n\treturn \u0026fakeHistory{informer.Informer().GetIndexer(), informer.Lister()}\n}","line":{"from":211,"to":215}} {"id":100003977,"name":"ListControllerRevisions","signature":"func (rh *realHistory) ListControllerRevisions(parent metav1.Object, selector labels.Selector) ([]*apps.ControllerRevision, error)","file":"pkg/controller/history/controller_history.go","code":"func (rh *realHistory) ListControllerRevisions(parent metav1.Object, selector labels.Selector) ([]*apps.ControllerRevision, error) {\n\t// List all revisions in the namespace that match the selector\n\thistory, err := rh.lister.ControllerRevisions(parent.GetNamespace()).List(selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar owned []*apps.ControllerRevision\n\tfor i := range history {\n\t\tref := metav1.GetControllerOfNoCopy(history[i])\n\t\tif ref == nil || ref.UID == parent.GetUID() {\n\t\t\towned = append(owned, history[i])\n\t\t}\n\n\t}\n\treturn owned, err\n}","line":{"from":222,"to":237}} {"id":100003978,"name":"CreateControllerRevision","signature":"func (rh *realHistory) CreateControllerRevision(parent metav1.Object, revision *apps.ControllerRevision, collisionCount *int32) (*apps.ControllerRevision, error)","file":"pkg/controller/history/controller_history.go","code":"func (rh *realHistory) CreateControllerRevision(parent metav1.Object, revision *apps.ControllerRevision, collisionCount *int32) (*apps.ControllerRevision, error) {\n\tif collisionCount == nil {\n\t\treturn nil, fmt.Errorf(\"collisionCount should not be nil\")\n\t}\n\n\t// Clone the input\n\tclone := revision.DeepCopy()\n\n\t// Continue to attempt to create the revision updating the name with a new hash on each iteration\n\tfor {\n\t\thash := HashControllerRevision(revision, collisionCount)\n\t\t// Update the revisions name\n\t\tclone.Name = ControllerRevisionName(parent.GetName(), hash)\n\t\tns := parent.GetNamespace()\n\t\tcreated, err := rh.client.AppsV1().ControllerRevisions(ns).Create(context.TODO(), clone, metav1.CreateOptions{})\n\t\tif errors.IsAlreadyExists(err) {\n\t\t\texists, err := rh.client.AppsV1().ControllerRevisions(ns).Get(context.TODO(), clone.Name, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif bytes.Equal(exists.Data.Raw, clone.Data.Raw) {\n\t\t\t\treturn exists, nil\n\t\t\t}\n\t\t\t*collisionCount++\n\t\t\tcontinue\n\t\t}\n\t\treturn created, err\n\t}\n}","line":{"from":239,"to":267}} {"id":100003979,"name":"UpdateControllerRevision","signature":"func (rh *realHistory) UpdateControllerRevision(revision *apps.ControllerRevision, newRevision int64) (*apps.ControllerRevision, error)","file":"pkg/controller/history/controller_history.go","code":"func (rh *realHistory) UpdateControllerRevision(revision *apps.ControllerRevision, newRevision int64) (*apps.ControllerRevision, error) {\n\tclone := revision.DeepCopy()\n\terr := retry.RetryOnConflict(retry.DefaultBackoff, func() error {\n\t\tif clone.Revision == newRevision {\n\t\t\treturn nil\n\t\t}\n\t\tclone.Revision = newRevision\n\t\tupdated, updateErr := rh.client.AppsV1().ControllerRevisions(clone.Namespace).Update(context.TODO(), clone, metav1.UpdateOptions{})\n\t\tif updateErr == nil {\n\t\t\treturn nil\n\t\t}\n\t\tif updated != nil {\n\t\t\tclone = updated\n\t\t}\n\t\tif updated, err := rh.lister.ControllerRevisions(clone.Namespace).Get(clone.Name); err == nil {\n\t\t\t// make a copy so we don't mutate the shared cache\n\t\t\tclone = updated.DeepCopy()\n\t\t}\n\t\treturn updateErr\n\t})\n\treturn clone, err\n}","line":{"from":269,"to":290}} {"id":100003980,"name":"DeleteControllerRevision","signature":"func (rh *realHistory) DeleteControllerRevision(revision *apps.ControllerRevision) error","file":"pkg/controller/history/controller_history.go","code":"func (rh *realHistory) DeleteControllerRevision(revision *apps.ControllerRevision) error {\n\treturn rh.client.AppsV1().ControllerRevisions(revision.Namespace).Delete(context.TODO(), revision.Name, metav1.DeleteOptions{})\n}","line":{"from":292,"to":294}} {"id":100003981,"name":"AdoptControllerRevision","signature":"func (rh *realHistory) AdoptControllerRevision(parent metav1.Object, parentKind schema.GroupVersionKind, revision *apps.ControllerRevision) (*apps.ControllerRevision, error)","file":"pkg/controller/history/controller_history.go","code":"func (rh *realHistory) AdoptControllerRevision(parent metav1.Object, parentKind schema.GroupVersionKind, revision *apps.ControllerRevision) (*apps.ControllerRevision, error) {\n\tblockOwnerDeletion := true\n\tisController := true\n\t// Return an error if the revision is not orphan\n\tif owner := metav1.GetControllerOfNoCopy(revision); owner != nil {\n\t\treturn nil, fmt.Errorf(\"attempt to adopt revision owned by %v\", owner)\n\t}\n\taddControllerPatch := objectForPatch{\n\t\tMetadata: objectMetaForPatch{\n\t\t\tUID: revision.UID,\n\t\t\tOwnerReferences: []metav1.OwnerReference{{\n\t\t\t\tAPIVersion: parentKind.GroupVersion().String(),\n\t\t\t\tKind: parentKind.Kind,\n\t\t\t\tName: parent.GetName(),\n\t\t\t\tUID: parent.GetUID(),\n\t\t\t\tController: \u0026isController,\n\t\t\t\tBlockOwnerDeletion: \u0026blockOwnerDeletion,\n\t\t\t}},\n\t\t},\n\t}\n\tpatchBytes, err := json.Marshal(\u0026addControllerPatch)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Use strategic merge patch to add an owner reference indicating a controller ref\n\treturn rh.client.AppsV1().ControllerRevisions(parent.GetNamespace()).Patch(context.TODO(), revision.GetName(),\n\t\ttypes.StrategicMergePatchType, patchBytes, metav1.PatchOptions{})\n}","line":{"from":306,"to":333}} {"id":100003982,"name":"ReleaseControllerRevision","signature":"func (rh *realHistory) ReleaseControllerRevision(parent metav1.Object, revision *apps.ControllerRevision) (*apps.ControllerRevision, error)","file":"pkg/controller/history/controller_history.go","code":"func (rh *realHistory) ReleaseControllerRevision(parent metav1.Object, revision *apps.ControllerRevision) (*apps.ControllerRevision, error) {\n\tdataBytes, err := controller.GenerateDeleteOwnerRefStrategicMergeBytes(revision.UID, []types.UID{parent.GetUID()})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Use strategic merge patch to add an owner reference indicating a controller ref\n\treleased, err := rh.client.AppsV1().ControllerRevisions(revision.GetNamespace()).Patch(context.TODO(), revision.GetName(),\n\t\ttypes.StrategicMergePatchType, dataBytes, metav1.PatchOptions{})\n\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t// We ignore deleted revisions\n\t\t\treturn nil, nil\n\t\t}\n\t\tif errors.IsInvalid(err) {\n\t\t\t// We ignore cases where the parent no longer owns the revision or where the revision has no\n\t\t\t// owner.\n\t\t\treturn nil, nil\n\t\t}\n\t}\n\treturn released, err\n}","line":{"from":335,"to":357}} {"id":100003983,"name":"ListControllerRevisions","signature":"func (fh *fakeHistory) ListControllerRevisions(parent metav1.Object, selector labels.Selector) ([]*apps.ControllerRevision, error)","file":"pkg/controller/history/controller_history.go","code":"func (fh *fakeHistory) ListControllerRevisions(parent metav1.Object, selector labels.Selector) ([]*apps.ControllerRevision, error) {\n\thistory, err := fh.lister.ControllerRevisions(parent.GetNamespace()).List(selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar owned []*apps.ControllerRevision\n\tfor i := range history {\n\t\tref := metav1.GetControllerOf(history[i])\n\t\tif ref == nil || ref.UID == parent.GetUID() {\n\t\t\towned = append(owned, history[i])\n\t\t}\n\n\t}\n\treturn owned, err\n}","line":{"from":364,"to":379}} {"id":100003984,"name":"addRevision","signature":"func (fh *fakeHistory) addRevision(revision *apps.ControllerRevision) (*apps.ControllerRevision, error)","file":"pkg/controller/history/controller_history.go","code":"func (fh *fakeHistory) addRevision(revision *apps.ControllerRevision) (*apps.ControllerRevision, error) {\n\tkey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(revision)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tobj, found, err := fh.indexer.GetByKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif found {\n\t\tfoundRevision := obj.(*apps.ControllerRevision)\n\t\treturn foundRevision, errors.NewAlreadyExists(apps.Resource(\"controllerrevision\"), revision.Name)\n\t}\n\treturn revision, fh.indexer.Update(revision)\n}","line":{"from":381,"to":395}} {"id":100003985,"name":"CreateControllerRevision","signature":"func (fh *fakeHistory) CreateControllerRevision(parent metav1.Object, revision *apps.ControllerRevision, collisionCount *int32) (*apps.ControllerRevision, error)","file":"pkg/controller/history/controller_history.go","code":"func (fh *fakeHistory) CreateControllerRevision(parent metav1.Object, revision *apps.ControllerRevision, collisionCount *int32) (*apps.ControllerRevision, error) {\n\tif collisionCount == nil {\n\t\treturn nil, fmt.Errorf(\"collisionCount should not be nil\")\n\t}\n\n\t// Clone the input\n\tclone := revision.DeepCopy()\n\tclone.Namespace = parent.GetNamespace()\n\n\t// Continue to attempt to create the revision updating the name with a new hash on each iteration\n\tfor {\n\t\thash := HashControllerRevision(revision, collisionCount)\n\t\t// Update the revisions name and labels\n\t\tclone.Name = ControllerRevisionName(parent.GetName(), hash)\n\t\tcreated, err := fh.addRevision(clone)\n\t\tif errors.IsAlreadyExists(err) {\n\t\t\t*collisionCount++\n\t\t\tcontinue\n\t\t}\n\t\treturn created, err\n\t}\n}","line":{"from":397,"to":418}} {"id":100003986,"name":"DeleteControllerRevision","signature":"func (fh *fakeHistory) DeleteControllerRevision(revision *apps.ControllerRevision) error","file":"pkg/controller/history/controller_history.go","code":"func (fh *fakeHistory) DeleteControllerRevision(revision *apps.ControllerRevision) error {\n\tkey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(revision)\n\tif err != nil {\n\t\treturn err\n\t}\n\tobj, found, err := fh.indexer.GetByKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !found {\n\t\treturn errors.NewNotFound(apps.Resource(\"controllerrevisions\"), revision.Name)\n\t}\n\treturn fh.indexer.Delete(obj)\n}","line":{"from":420,"to":433}} {"id":100003987,"name":"UpdateControllerRevision","signature":"func (fh *fakeHistory) UpdateControllerRevision(revision *apps.ControllerRevision, newRevision int64) (*apps.ControllerRevision, error)","file":"pkg/controller/history/controller_history.go","code":"func (fh *fakeHistory) UpdateControllerRevision(revision *apps.ControllerRevision, newRevision int64) (*apps.ControllerRevision, error) {\n\tclone := revision.DeepCopy()\n\tclone.Revision = newRevision\n\treturn clone, fh.indexer.Update(clone)\n}","line":{"from":435,"to":439}} {"id":100003988,"name":"AdoptControllerRevision","signature":"func (fh *fakeHistory) AdoptControllerRevision(parent metav1.Object, parentKind schema.GroupVersionKind, revision *apps.ControllerRevision) (*apps.ControllerRevision, error)","file":"pkg/controller/history/controller_history.go","code":"func (fh *fakeHistory) AdoptControllerRevision(parent metav1.Object, parentKind schema.GroupVersionKind, revision *apps.ControllerRevision) (*apps.ControllerRevision, error) {\n\tif owner := metav1.GetControllerOf(revision); owner != nil {\n\t\treturn nil, fmt.Errorf(\"attempt to adopt revision owned by %v\", owner)\n\t}\n\tkey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(revision)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, found, err := fh.indexer.GetByKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !found {\n\t\treturn nil, errors.NewNotFound(apps.Resource(\"controllerrevisions\"), revision.Name)\n\t}\n\tclone := revision.DeepCopy()\n\tclone.OwnerReferences = append(clone.OwnerReferences, *metav1.NewControllerRef(parent, parentKind))\n\treturn clone, fh.indexer.Update(clone)\n}","line":{"from":441,"to":459}} {"id":100003989,"name":"ReleaseControllerRevision","signature":"func (fh *fakeHistory) ReleaseControllerRevision(parent metav1.Object, revision *apps.ControllerRevision) (*apps.ControllerRevision, error)","file":"pkg/controller/history/controller_history.go","code":"func (fh *fakeHistory) ReleaseControllerRevision(parent metav1.Object, revision *apps.ControllerRevision) (*apps.ControllerRevision, error) {\n\tkey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(revision)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, found, err := fh.indexer.GetByKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !found {\n\t\treturn nil, nil\n\t}\n\tclone := revision.DeepCopy()\n\trefs := clone.OwnerReferences\n\tclone.OwnerReferences = nil\n\tfor i := range refs {\n\t\tif refs[i].UID != parent.GetUID() {\n\t\t\tclone.OwnerReferences = append(clone.OwnerReferences, refs[i])\n\t\t}\n\t}\n\treturn clone, fh.indexer.Update(clone)\n}","line":{"from":461,"to":482}} {"id":100003990,"name":"updateBackoffRecord","signature":"func (s *backoffStore) updateBackoffRecord(record backoffRecord) error","file":"pkg/controller/job/backoff_utils.go","code":"func (s *backoffStore) updateBackoffRecord(record backoffRecord) error {\n\tb, ok, err := s.store.GetByKey(record.key)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !ok {\n\t\terr = s.store.Add(\u0026record)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tbackoffRecord := b.(*backoffRecord)\n\t\tbackoffRecord.failuresAfterLastSuccess = record.failuresAfterLastSuccess\n\t\tbackoffRecord.lastFailureTime = record.lastFailureTime\n\t}\n\n\treturn nil\n}","line":{"from":39,"to":57}} {"id":100003991,"name":"removeBackoffRecord","signature":"func (s *backoffStore) removeBackoffRecord(jobId string) error","file":"pkg/controller/job/backoff_utils.go","code":"func (s *backoffStore) removeBackoffRecord(jobId string) error {\n\tb, ok, err := s.store.GetByKey(jobId)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif ok {\n\t\terr = s.store.Delete(b)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n\n}","line":{"from":59,"to":74}} {"id":100003992,"name":"newBackoffRecordStore","signature":"func newBackoffRecordStore() *backoffStore","file":"pkg/controller/job/backoff_utils.go","code":"func newBackoffRecordStore() *backoffStore {\n\treturn \u0026backoffStore{\n\t\tstore: cache.NewStore(backoffRecordKeyFunc),\n\t}\n}","line":{"from":76,"to":80}} {"id":100003993,"name":"newBackoffRecord","signature":"func (backoffRecordStore *backoffStore) newBackoffRecord(clock clock.WithTicker, key string, newSucceededPods []*v1.Pod, newFailedPods []*v1.Pod) backoffRecord","file":"pkg/controller/job/backoff_utils.go","code":"func (backoffRecordStore *backoffStore) newBackoffRecord(clock clock.WithTicker, key string, newSucceededPods []*v1.Pod, newFailedPods []*v1.Pod) backoffRecord {\n\tnow := clock.Now()\n\tvar backoff *backoffRecord\n\n\tif b, exists, _ := backoffRecordStore.store.GetByKey(key); exists {\n\t\told := b.(*backoffRecord)\n\t\tbackoff = \u0026backoffRecord{\n\t\t\tkey: old.key,\n\t\t\tfailuresAfterLastSuccess: old.failuresAfterLastSuccess,\n\t\t\tlastFailureTime: old.lastFailureTime,\n\t\t}\n\t} else {\n\t\tbackoff = \u0026backoffRecord{\n\t\t\tkey: key,\n\t\t\tfailuresAfterLastSuccess: 0,\n\t\t\tlastFailureTime: nil,\n\t\t}\n\t}\n\n\tsortByFinishedTime(newSucceededPods, now)\n\tsortByFinishedTime(newFailedPods, now)\n\n\tif len(newSucceededPods) == 0 {\n\t\tif len(newFailedPods) == 0 {\n\t\t\treturn *backoff\n\t\t}\n\n\t\tbackoff.failuresAfterLastSuccess = backoff.failuresAfterLastSuccess + int32(len(newFailedPods))\n\t\tlastFailureTime := getFinishedTime(newFailedPods[len(newFailedPods)-1], now)\n\t\tbackoff.lastFailureTime = \u0026lastFailureTime\n\t\treturn *backoff\n\n\t} else {\n\t\tif len(newFailedPods) == 0 {\n\t\t\tbackoff.failuresAfterLastSuccess = 0\n\t\t\tbackoff.lastFailureTime = nil\n\t\t\treturn *backoff\n\t\t}\n\n\t\tbackoff.failuresAfterLastSuccess = 0\n\t\tbackoff.lastFailureTime = nil\n\n\t\tlastSuccessTime := getFinishedTime(newSucceededPods[len(newSucceededPods)-1], now)\n\t\tfor i := len(newFailedPods) - 1; i \u003e= 0; i-- {\n\t\t\tfailedTime := getFinishedTime(newFailedPods[i], now)\n\t\t\tif !failedTime.After(lastSuccessTime) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif backoff.lastFailureTime == nil {\n\t\t\t\tbackoff.lastFailureTime = \u0026failedTime\n\t\t\t}\n\t\t\tbackoff.failuresAfterLastSuccess += 1\n\t\t}\n\n\t\treturn *backoff\n\n\t}\n\n}","line":{"from":89,"to":147}} {"id":100003994,"name":"sortByFinishedTime","signature":"func sortByFinishedTime(pods []*v1.Pod, currentTime time.Time)","file":"pkg/controller/job/backoff_utils.go","code":"func sortByFinishedTime(pods []*v1.Pod, currentTime time.Time) {\n\tsort.Slice(pods, func(i, j int) bool {\n\t\tp1 := pods[i]\n\t\tp2 := pods[j]\n\t\tp1FinishTime := getFinishedTime(p1, currentTime)\n\t\tp2FinishTime := getFinishedTime(p2, currentTime)\n\n\t\treturn p1FinishTime.Before(p2FinishTime)\n\t})\n}","line":{"from":149,"to":158}} {"id":100003995,"name":"getFinishedTime","signature":"func getFinishedTime(p *v1.Pod, currentTime time.Time) time.Time","file":"pkg/controller/job/backoff_utils.go","code":"func getFinishedTime(p *v1.Pod, currentTime time.Time) time.Time {\n\tvar finishTime *time.Time\n\tfor _, containerState := range p.Status.ContainerStatuses {\n\t\tif containerState.State.Terminated == nil {\n\t\t\tfinishTime = nil\n\t\t\tbreak\n\t\t}\n\n\t\tif finishTime == nil {\n\t\t\tfinishTime = \u0026containerState.State.Terminated.FinishedAt.Time\n\t\t} else {\n\t\t\tif finishTime.Before(containerState.State.Terminated.FinishedAt.Time) {\n\t\t\t\tfinishTime = \u0026containerState.State.Terminated.FinishedAt.Time\n\t\t\t}\n\t\t}\n\t}\n\n\tif finishTime == nil || finishTime.IsZero() {\n\t\treturn currentTime\n\t}\n\n\treturn *finishTime\n}","line":{"from":160,"to":182}} {"id":100003996,"name":"getRemainingTime","signature":"func (backoff backoffRecord) getRemainingTime(clock clock.WithTicker, defaultBackoff time.Duration, maxBackoff time.Duration) time.Duration","file":"pkg/controller/job/backoff_utils.go","code":"func (backoff backoffRecord) getRemainingTime(clock clock.WithTicker, defaultBackoff time.Duration, maxBackoff time.Duration) time.Duration {\n\tif backoff.failuresAfterLastSuccess == 0 {\n\t\treturn 0\n\t}\n\n\tbackoffDuration := defaultBackoff\n\tfor i := 1; i \u003c int(backoff.failuresAfterLastSuccess); i++ {\n\t\tbackoffDuration = backoffDuration * 2\n\t\tif backoffDuration \u003e= maxBackoff {\n\t\t\tbackoffDuration = maxBackoff\n\t\t\tbreak\n\t\t}\n\t}\n\n\ttimeElapsedSinceLastFailure := clock.Since(*backoff.lastFailureTime)\n\n\tif backoffDuration \u003c timeElapsedSinceLastFailure {\n\t\treturn 0\n\t}\n\n\treturn backoffDuration - timeElapsedSinceLastFailure\n}","line":{"from":184,"to":205}} {"id":100003997,"name":"Convert_v1alpha1_JobControllerConfiguration_To_config_JobControllerConfiguration","signature":"func Convert_v1alpha1_JobControllerConfiguration_To_config_JobControllerConfiguration(in *v1alpha1.JobControllerConfiguration, out *config.JobControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/job/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_JobControllerConfiguration_To_config_JobControllerConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_JobControllerConfiguration_To_config_JobControllerConfiguration(in *v1alpha1.JobControllerConfiguration, out *config.JobControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_JobControllerConfiguration_To_config_JobControllerConfiguration(in, out, s)\n}","line":{"from":32,"to":35}} {"id":100003998,"name":"Convert_config_JobControllerConfiguration_To_v1alpha1_JobControllerConfiguration","signature":"func Convert_config_JobControllerConfiguration_To_v1alpha1_JobControllerConfiguration(in *config.JobControllerConfiguration, out *v1alpha1.JobControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/job/config/v1alpha1/conversion.go","code":"// Convert_config_JobControllerConfiguration_To_v1alpha1_JobControllerConfiguration is an autogenerated conversion function.\nfunc Convert_config_JobControllerConfiguration_To_v1alpha1_JobControllerConfiguration(in *config.JobControllerConfiguration, out *v1alpha1.JobControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_JobControllerConfiguration_To_v1alpha1_JobControllerConfiguration(in, out, s)\n}","line":{"from":37,"to":40}} {"id":100003999,"name":"RecommendedDefaultJobControllerConfiguration","signature":"func RecommendedDefaultJobControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.JobControllerConfiguration)","file":"pkg/controller/job/config/v1alpha1/defaults.go","code":"// RecommendedDefaultJobControllerConfiguration defaults a pointer to a\n// JobControllerConfiguration struct. This will set the recommended default\n// values, but they may be subject to change between API versions. This function\n// is intentionally not registered in the scheme as a \"normal\" `SetDefaults_Foo`\n// function to allow consumers of this type to set whatever defaults for their\n// embedded configs. Forcing consumers to use these defaults would be problematic\n// as defaulting in the scheme is done as part of the conversion, and there would\n// be no easy way to opt-out. Instead, if you want to use this defaulting method\n// run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDefaultJobControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.JobControllerConfiguration) {\n\tif obj.ConcurrentJobSyncs == 0 {\n\t\tobj.ConcurrentJobSyncs = 5\n\t}\n}","line":{"from":23,"to":36}} {"id":100004000,"name":"isIndexedJob","signature":"func isIndexedJob(job *batch.Job) bool","file":"pkg/controller/job/indexed_job_utils.go","code":"func isIndexedJob(job *batch.Job) bool {\n\treturn job.Spec.CompletionMode != nil \u0026\u0026 *job.Spec.CompletionMode == batch.IndexedCompletion\n}","line":{"from":38,"to":40}} {"id":100004001,"name":"calculateSucceededIndexes","signature":"func calculateSucceededIndexes(job *batch.Job, pods []*v1.Pod) (orderedIntervals, orderedIntervals)","file":"pkg/controller/job/indexed_job_utils.go","code":"// calculateSucceededIndexes returns the old and new list of succeeded indexes\n// in compressed format (intervals).\n// The old list is solely based off .status.completedIndexes, but returns an\n// empty list if this Job is not tracked with finalizers. The new list includes\n// the indexes that succeeded since the last sync.\nfunc calculateSucceededIndexes(job *batch.Job, pods []*v1.Pod) (orderedIntervals, orderedIntervals) {\n\tprevIntervals := succeededIndexesFromString(job.Status.CompletedIndexes, int(*job.Spec.Completions))\n\tnewSucceeded := sets.NewInt()\n\tfor _, p := range pods {\n\t\tix := getCompletionIndex(p.Annotations)\n\t\t// Succeeded Pod with valid index and, if tracking with finalizers,\n\t\t// has a finalizer (meaning that it is not counted yet).\n\t\tif p.Status.Phase == v1.PodSucceeded \u0026\u0026 ix != unknownCompletionIndex \u0026\u0026 ix \u003c int(*job.Spec.Completions) \u0026\u0026 hasJobTrackingFinalizer(p) {\n\t\t\tnewSucceeded.Insert(ix)\n\t\t}\n\t}\n\t// List returns the items of the set in order.\n\tresult := prevIntervals.withOrderedIndexes(newSucceeded.List())\n\treturn prevIntervals, result\n}","line":{"from":49,"to":68}} {"id":100004002,"name":"withOrderedIndexes","signature":"func (oi orderedIntervals) withOrderedIndexes(newIndexes []int) orderedIntervals","file":"pkg/controller/job/indexed_job_utils.go","code":"// withOrderedIndexes returns a new list of ordered intervals that contains\n// the newIndexes, provided in increasing order.\nfunc (oi orderedIntervals) withOrderedIndexes(newIndexes []int) orderedIntervals {\n\tvar result orderedIntervals\n\ti := 0\n\tj := 0\n\tvar lastInterval *interval\n\tappendOrMergeWithLastInterval := func(thisInterval interval) {\n\t\tif lastInterval == nil || thisInterval.First \u003e lastInterval.Last+1 {\n\t\t\tresult = append(result, thisInterval)\n\t\t\tlastInterval = \u0026result[len(result)-1]\n\t\t} else if lastInterval.Last \u003c thisInterval.Last {\n\t\t\tlastInterval.Last = thisInterval.Last\n\t\t}\n\t}\n\tfor i \u003c len(oi) \u0026\u0026 j \u003c len(newIndexes) {\n\t\tif oi[i].First \u003c newIndexes[j] {\n\t\t\tappendOrMergeWithLastInterval(oi[i])\n\t\t\ti++\n\t\t} else {\n\t\t\tappendOrMergeWithLastInterval(interval{newIndexes[j], newIndexes[j]})\n\t\t\tj++\n\t\t}\n\t}\n\tfor i \u003c len(oi) {\n\t\tappendOrMergeWithLastInterval(oi[i])\n\t\ti++\n\t}\n\tfor j \u003c len(newIndexes) {\n\t\tappendOrMergeWithLastInterval(interval{newIndexes[j], newIndexes[j]})\n\t\tj++\n\t}\n\treturn result\n}","line":{"from":70,"to":103}} {"id":100004003,"name":"total","signature":"func (oi orderedIntervals) total() int","file":"pkg/controller/job/indexed_job_utils.go","code":"// total returns number of indexes contained in the intervals.\nfunc (oi orderedIntervals) total() int {\n\tvar count int\n\tfor _, iv := range oi {\n\t\tcount += iv.Last - iv.First + 1\n\t}\n\treturn count\n}","line":{"from":105,"to":112}} {"id":100004004,"name":"String","signature":"func (oi orderedIntervals) String() string","file":"pkg/controller/job/indexed_job_utils.go","code":"func (oi orderedIntervals) String() string {\n\tvar builder strings.Builder\n\tfor _, v := range oi {\n\t\tif builder.Len() \u003e 0 {\n\t\t\tbuilder.WriteRune(',')\n\t\t}\n\t\tbuilder.WriteString(strconv.Itoa(v.First))\n\t\tif v.Last \u003e v.First {\n\t\t\tif v.Last == v.First+1 {\n\t\t\t\tbuilder.WriteRune(',')\n\t\t\t} else {\n\t\t\t\tbuilder.WriteRune('-')\n\t\t\t}\n\t\t\tbuilder.WriteString(strconv.Itoa(v.Last))\n\t\t}\n\t}\n\treturn builder.String()\n}","line":{"from":114,"to":131}} {"id":100004005,"name":"has","signature":"func (oi orderedIntervals) has(ix int) bool","file":"pkg/controller/job/indexed_job_utils.go","code":"func (oi orderedIntervals) has(ix int) bool {\n\tlo := 0\n\thi := len(oi)\n\t// Invariant: oi[hi].Last \u003e= ix\n\tfor hi \u003e lo {\n\t\tmid := lo + (hi-lo)/2\n\t\tif oi[mid].Last \u003e= ix {\n\t\t\thi = mid\n\t\t} else {\n\t\t\tlo = mid + 1\n\t\t}\n\t}\n\tif hi == len(oi) {\n\t\treturn false\n\t}\n\treturn oi[hi].First \u003c= ix\n}","line":{"from":133,"to":149}} {"id":100004006,"name":"succeededIndexesFromString","signature":"func succeededIndexesFromString(completedIndexes string, completions int) orderedIntervals","file":"pkg/controller/job/indexed_job_utils.go","code":"func succeededIndexesFromString(completedIndexes string, completions int) orderedIntervals {\n\tif completedIndexes == \"\" {\n\t\treturn nil\n\t}\n\tvar result orderedIntervals\n\tvar lastInterval *interval\n\tfor _, intervalStr := range strings.Split(completedIndexes, \",\") {\n\t\tlimitsStr := strings.Split(intervalStr, \"-\")\n\t\tvar inter interval\n\t\tvar err error\n\t\tinter.First, err = strconv.Atoi(limitsStr[0])\n\t\tif err != nil {\n\t\t\tklog.InfoS(\"Corrupted completed indexes interval, ignoring\", \"interval\", intervalStr, \"err\", err)\n\t\t\tcontinue\n\t\t}\n\t\tif inter.First \u003e= completions {\n\t\t\tbreak\n\t\t}\n\t\tif len(limitsStr) \u003e 1 {\n\t\t\tinter.Last, err = strconv.Atoi(limitsStr[1])\n\t\t\tif err != nil {\n\t\t\t\tklog.InfoS(\"Corrupted completed indexes interval, ignoring\", \"interval\", intervalStr, \"err\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif inter.Last \u003e= completions {\n\t\t\t\tinter.Last = completions - 1\n\t\t\t}\n\t\t} else {\n\t\t\tinter.Last = inter.First\n\t\t}\n\t\tif lastInterval != nil \u0026\u0026 lastInterval.Last == inter.First-1 {\n\t\t\tlastInterval.Last = inter.Last\n\t\t} else {\n\t\t\tresult = append(result, inter)\n\t\t\tlastInterval = \u0026result[len(result)-1]\n\t\t}\n\t}\n\treturn result\n}","line":{"from":151,"to":189}} {"id":100004007,"name":"firstPendingIndexes","signature":"func firstPendingIndexes(activePods []*v1.Pod, succeededIndexes orderedIntervals, count, completions int) []int","file":"pkg/controller/job/indexed_job_utils.go","code":"// firstPendingIndexes returns `count` indexes less than `completions` that are\n// not covered by `activePods` or `succeededIndexes`.\nfunc firstPendingIndexes(activePods []*v1.Pod, succeededIndexes orderedIntervals, count, completions int) []int {\n\tif count == 0 {\n\t\treturn nil\n\t}\n\tactive := sets.NewInt()\n\tfor _, p := range activePods {\n\t\tix := getCompletionIndex(p.Annotations)\n\t\tif ix != unknownCompletionIndex {\n\t\t\tactive.Insert(ix)\n\t\t}\n\t}\n\tresult := make([]int, 0, count)\n\tnonPending := succeededIndexes.withOrderedIndexes(active.List())\n\t// The following algorithm is bounded by len(nonPending) and count.\n\tcandidate := 0\n\tfor _, sInterval := range nonPending {\n\t\tfor ; candidate \u003c completions \u0026\u0026 len(result) \u003c count \u0026\u0026 candidate \u003c sInterval.First; candidate++ {\n\t\t\tresult = append(result, candidate)\n\t\t}\n\t\tif candidate \u003c sInterval.Last+1 {\n\t\t\tcandidate = sInterval.Last + 1\n\t\t}\n\t}\n\tfor ; candidate \u003c completions \u0026\u0026 len(result) \u003c count; candidate++ {\n\t\tresult = append(result, candidate)\n\t}\n\treturn result\n}","line":{"from":191,"to":220}} {"id":100004008,"name":"appendDuplicatedIndexPodsForRemoval","signature":"func appendDuplicatedIndexPodsForRemoval(rm, left, pods []*v1.Pod, completions int) ([]*v1.Pod, []*v1.Pod)","file":"pkg/controller/job/indexed_job_utils.go","code":"// appendDuplicatedIndexPodsForRemoval scans active `pods` for duplicated\n// completion indexes. For each index, it selects n-1 pods for removal, where n\n// is the number of repetitions. The pods to be removed are appended to `rm`,\n// while the remaining pods are appended to `left`.\n// All pods that don't have a completion index are appended to `rm`.\n// All pods with index not in valid range are appended to `rm`.\nfunc appendDuplicatedIndexPodsForRemoval(rm, left, pods []*v1.Pod, completions int) ([]*v1.Pod, []*v1.Pod) {\n\tsort.Sort(byCompletionIndex(pods))\n\tlastIndex := unknownCompletionIndex\n\tfirstRepeatPos := 0\n\tcountLooped := 0\n\tfor i, p := range pods {\n\t\tix := getCompletionIndex(p.Annotations)\n\t\tif ix \u003e= completions {\n\t\t\trm = append(rm, pods[i:]...)\n\t\t\tbreak\n\t\t}\n\t\tif ix != lastIndex {\n\t\t\trm, left = appendPodsWithSameIndexForRemovalAndRemaining(rm, left, pods[firstRepeatPos:i], lastIndex)\n\t\t\tfirstRepeatPos = i\n\t\t\tlastIndex = ix\n\t\t}\n\t\tcountLooped += 1\n\t}\n\treturn appendPodsWithSameIndexForRemovalAndRemaining(rm, left, pods[firstRepeatPos:countLooped], lastIndex)\n}","line":{"from":222,"to":247}} {"id":100004009,"name":"appendPodsWithSameIndexForRemovalAndRemaining","signature":"func appendPodsWithSameIndexForRemovalAndRemaining(rm, left, pods []*v1.Pod, ix int) ([]*v1.Pod, []*v1.Pod)","file":"pkg/controller/job/indexed_job_utils.go","code":"func appendPodsWithSameIndexForRemovalAndRemaining(rm, left, pods []*v1.Pod, ix int) ([]*v1.Pod, []*v1.Pod) {\n\tif ix == unknownCompletionIndex {\n\t\trm = append(rm, pods...)\n\t\treturn rm, left\n\t}\n\tif len(pods) == 1 {\n\t\tleft = append(left, pods[0])\n\t\treturn rm, left\n\t}\n\tsort.Sort(controller.ActivePods(pods))\n\trm = append(rm, pods[:len(pods)-1]...)\n\tleft = append(left, pods[len(pods)-1])\n\treturn rm, left\n}","line":{"from":249,"to":262}} {"id":100004010,"name":"getCompletionIndex","signature":"func getCompletionIndex(annotations map[string]string) int","file":"pkg/controller/job/indexed_job_utils.go","code":"func getCompletionIndex(annotations map[string]string) int {\n\tif annotations == nil {\n\t\treturn unknownCompletionIndex\n\t}\n\tv, ok := annotations[batch.JobCompletionIndexAnnotation]\n\tif !ok {\n\t\treturn unknownCompletionIndex\n\t}\n\ti, err := strconv.Atoi(v)\n\tif err != nil {\n\t\treturn unknownCompletionIndex\n\t}\n\tif i \u003c 0 {\n\t\treturn unknownCompletionIndex\n\t}\n\treturn i\n}","line":{"from":264,"to":280}} {"id":100004011,"name":"addCompletionIndexEnvVariables","signature":"func addCompletionIndexEnvVariables(template *v1.PodTemplateSpec)","file":"pkg/controller/job/indexed_job_utils.go","code":"func addCompletionIndexEnvVariables(template *v1.PodTemplateSpec) {\n\tfor i := range template.Spec.InitContainers {\n\t\taddCompletionIndexEnvVariable(\u0026template.Spec.InitContainers[i])\n\t}\n\tfor i := range template.Spec.Containers {\n\t\taddCompletionIndexEnvVariable(\u0026template.Spec.Containers[i])\n\t}\n}","line":{"from":282,"to":289}} {"id":100004012,"name":"addCompletionIndexEnvVariable","signature":"func addCompletionIndexEnvVariable(container *v1.Container)","file":"pkg/controller/job/indexed_job_utils.go","code":"func addCompletionIndexEnvVariable(container *v1.Container) {\n\tfor _, v := range container.Env {\n\t\tif v.Name == completionIndexEnvName {\n\t\t\treturn\n\t\t}\n\t}\n\tcontainer.Env = append(container.Env, v1.EnvVar{\n\t\tName: completionIndexEnvName,\n\t\tValueFrom: \u0026v1.EnvVarSource{\n\t\t\tFieldRef: \u0026v1.ObjectFieldSelector{\n\t\t\t\tFieldPath: fmt.Sprintf(\"metadata.annotations['%s']\", batch.JobCompletionIndexAnnotation),\n\t\t\t},\n\t\t},\n\t})\n}","line":{"from":291,"to":305}} {"id":100004013,"name":"addCompletionIndexAnnotation","signature":"func addCompletionIndexAnnotation(template *v1.PodTemplateSpec, index int)","file":"pkg/controller/job/indexed_job_utils.go","code":"func addCompletionIndexAnnotation(template *v1.PodTemplateSpec, index int) {\n\tif template.Annotations == nil {\n\t\ttemplate.Annotations = make(map[string]string, 1)\n\t}\n\ttemplate.Annotations[batch.JobCompletionIndexAnnotation] = strconv.Itoa(index)\n}","line":{"from":307,"to":312}} {"id":100004014,"name":"podGenerateNameWithIndex","signature":"func podGenerateNameWithIndex(jobName string, index int) string","file":"pkg/controller/job/indexed_job_utils.go","code":"func podGenerateNameWithIndex(jobName string, index int) string {\n\tappendIndex := \"-\" + strconv.Itoa(index) + \"-\"\n\tgenerateNamePrefix := jobName + appendIndex\n\tif len(generateNamePrefix) \u003e names.MaxGeneratedNameLength {\n\t\tgenerateNamePrefix = generateNamePrefix[:names.MaxGeneratedNameLength-len(appendIndex)] + appendIndex\n\t}\n\treturn generateNamePrefix\n}","line":{"from":314,"to":321}} {"id":100004015,"name":"Less","signature":"func (bci byCompletionIndex) Less(i, j int) bool","file":"pkg/controller/job/indexed_job_utils.go","code":"func (bci byCompletionIndex) Less(i, j int) bool {\n\treturn getCompletionIndex(bci[i].Annotations) \u003c getCompletionIndex(bci[j].Annotations)\n}","line":{"from":325,"to":327}} {"id":100004016,"name":"Swap","signature":"func (bci byCompletionIndex) Swap(i, j int)","file":"pkg/controller/job/indexed_job_utils.go","code":"func (bci byCompletionIndex) Swap(i, j int) {\n\tbci[i], bci[j] = bci[j], bci[i]\n}","line":{"from":329,"to":331}} {"id":100004017,"name":"Len","signature":"func (bci byCompletionIndex) Len() int","file":"pkg/controller/job/indexed_job_utils.go","code":"func (bci byCompletionIndex) Len() int {\n\treturn len(bci)\n}","line":{"from":333,"to":335}} {"id":100004018,"name":"completionModeStr","signature":"func completionModeStr(job *batch.Job) string","file":"pkg/controller/job/indexed_job_utils.go","code":"func completionModeStr(job *batch.Job) string {\n\tif job.Spec.CompletionMode != nil {\n\t\treturn string(*job.Spec.CompletionMode)\n\t}\n\treturn string(batch.NonIndexedCompletion)\n}","line":{"from":337,"to":342}} {"id":100004019,"name":"NewController","signature":"func NewController(podInformer coreinformers.PodInformer, jobInformer batchinformers.JobInformer, kubeClient clientset.Interface) *Controller","file":"pkg/controller/job/job_controller.go","code":"// NewController creates a new Job controller that keeps the relevant pods\n// in sync with their corresponding Job objects.\nfunc NewController(podInformer coreinformers.PodInformer, jobInformer batchinformers.JobInformer, kubeClient clientset.Interface) *Controller {\n\treturn newControllerWithClock(podInformer, jobInformer, kubeClient, \u0026clock.RealClock{})\n}","line":{"from":133,"to":137}} {"id":100004020,"name":"newControllerWithClock","signature":"func newControllerWithClock(podInformer coreinformers.PodInformer, jobInformer batchinformers.JobInformer, kubeClient clientset.Interface, clock clock.WithTicker) *Controller","file":"pkg/controller/job/job_controller.go","code":"func newControllerWithClock(podInformer coreinformers.PodInformer, jobInformer batchinformers.JobInformer, kubeClient clientset.Interface, clock clock.WithTicker) *Controller {\n\teventBroadcaster := record.NewBroadcaster()\n\n\tjm := \u0026Controller{\n\t\tkubeClient: kubeClient,\n\t\tpodControl: controller.RealPodControl{\n\t\t\tKubeClient: kubeClient,\n\t\t\tRecorder: eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"job-controller\"}),\n\t\t},\n\t\texpectations: controller.NewControllerExpectations(),\n\t\tfinalizerExpectations: newUIDTrackingExpectations(),\n\t\tqueue: workqueue.NewRateLimitingQueueWithDelayingInterface(workqueue.NewDelayingQueueWithCustomClock(clock, \"job\"), workqueue.NewItemExponentialFailureRateLimiter(DefaultJobBackOff, MaxJobBackOff)),\n\t\torphanQueue: workqueue.NewRateLimitingQueueWithDelayingInterface(workqueue.NewDelayingQueueWithCustomClock(clock, \"job_orphan_pod\"), workqueue.NewItemExponentialFailureRateLimiter(DefaultJobBackOff, MaxJobBackOff)),\n\t\tbroadcaster: eventBroadcaster,\n\t\trecorder: eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"job-controller\"}),\n\t\tclock: clock,\n\t\tbackoffRecordStore: newBackoffRecordStore(),\n\t}\n\tif feature.DefaultFeatureGate.Enabled(features.JobReadyPods) {\n\t\tjm.podUpdateBatchPeriod = podUpdateBatchPeriod\n\t}\n\n\tjobInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tjm.enqueueController(obj, true)\n\t\t},\n\t\tUpdateFunc: jm.updateJob,\n\t\tDeleteFunc: jm.deleteJob,\n\t})\n\tjm.jobLister = jobInformer.Lister()\n\tjm.jobStoreSynced = jobInformer.Informer().HasSynced\n\n\tpodInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: jm.addPod,\n\t\tUpdateFunc: jm.updatePod,\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tjm.deletePod(obj, true)\n\t\t},\n\t})\n\tjm.podStore = podInformer.Lister()\n\tjm.podStoreSynced = podInformer.Informer().HasSynced\n\n\tjm.updateStatusHandler = jm.updateJobStatus\n\tjm.patchJobHandler = jm.patchJob\n\tjm.syncHandler = jm.syncJob\n\n\tmetrics.Register()\n\n\treturn jm\n}","line":{"from":139,"to":188}} {"id":100004021,"name":"Run","signature":"func (jm *Controller) Run(ctx context.Context, workers int)","file":"pkg/controller/job/job_controller.go","code":"// Run the main goroutine responsible for watching and syncing jobs.\nfunc (jm *Controller) Run(ctx context.Context, workers int) {\n\tdefer utilruntime.HandleCrash()\n\n\t// Start events processing pipeline.\n\tjm.broadcaster.StartStructuredLogging(0)\n\tjm.broadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: jm.kubeClient.CoreV1().Events(\"\")})\n\tdefer jm.broadcaster.Shutdown()\n\n\tdefer jm.queue.ShutDown()\n\tdefer jm.orphanQueue.ShutDown()\n\n\tklog.Infof(\"Starting job controller\")\n\tdefer klog.Infof(\"Shutting down job controller\")\n\n\tif !cache.WaitForNamedCacheSync(\"job\", ctx.Done(), jm.podStoreSynced, jm.jobStoreSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.UntilWithContext(ctx, jm.worker, time.Second)\n\t}\n\n\tgo wait.UntilWithContext(ctx, jm.orphanWorker, time.Second)\n\n\t\u003c-ctx.Done()\n}","line":{"from":190,"to":216}} {"id":100004022,"name":"getPodJobs","signature":"func (jm *Controller) getPodJobs(pod *v1.Pod) []*batch.Job","file":"pkg/controller/job/job_controller.go","code":"// getPodJobs returns a list of Jobs that potentially match a Pod.\nfunc (jm *Controller) getPodJobs(pod *v1.Pod) []*batch.Job {\n\tjobs, err := jm.jobLister.GetPodJobs(pod)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tif len(jobs) \u003e 1 {\n\t\t// ControllerRef will ensure we don't do anything crazy, but more than one\n\t\t// item in this list nevertheless constitutes user error.\n\t\tutilruntime.HandleError(fmt.Errorf(\"user error! more than one job is selecting pods with labels: %+v\", pod.Labels))\n\t}\n\tret := make([]*batch.Job, 0, len(jobs))\n\tfor i := range jobs {\n\t\tret = append(ret, \u0026jobs[i])\n\t}\n\treturn ret\n}","line":{"from":218,"to":234}} {"id":100004023,"name":"resolveControllerRef","signature":"func (jm *Controller) resolveControllerRef(namespace string, controllerRef *metav1.OwnerReference) *batch.Job","file":"pkg/controller/job/job_controller.go","code":"// resolveControllerRef returns the controller referenced by a ControllerRef,\n// or nil if the ControllerRef could not be resolved to a matching controller\n// of the correct Kind.\nfunc (jm *Controller) resolveControllerRef(namespace string, controllerRef *metav1.OwnerReference) *batch.Job {\n\t// We can't look up by UID, so look up by Name and then verify UID.\n\t// Don't even try to look up by Name if it's the wrong Kind.\n\tif controllerRef.Kind != controllerKind.Kind {\n\t\treturn nil\n\t}\n\tjob, err := jm.jobLister.Jobs(namespace).Get(controllerRef.Name)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tif job.UID != controllerRef.UID {\n\t\t// The controller we found with this Name is not the same one that the\n\t\t// ControllerRef points to.\n\t\treturn nil\n\t}\n\treturn job\n}","line":{"from":236,"to":255}} {"id":100004024,"name":"addPod","signature":"func (jm *Controller) addPod(obj interface{})","file":"pkg/controller/job/job_controller.go","code":"// When a pod is created, enqueue the controller that manages it and update its expectations.\nfunc (jm *Controller) addPod(obj interface{}) {\n\tpod := obj.(*v1.Pod)\n\trecordFinishedPodWithTrackingFinalizer(nil, pod)\n\tif pod.DeletionTimestamp != nil {\n\t\t// on a restart of the controller, it's possible a new pod shows up in a state that\n\t\t// is already pending deletion. Prevent the pod from being a creation observation.\n\t\tjm.deletePod(pod, false)\n\t\treturn\n\t}\n\n\t// If it has a ControllerRef, that's all that matters.\n\tif controllerRef := metav1.GetControllerOf(pod); controllerRef != nil {\n\t\tjob := jm.resolveControllerRef(pod.Namespace, controllerRef)\n\t\tif job == nil {\n\t\t\treturn\n\t\t}\n\t\tjobKey, err := controller.KeyFunc(job)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tjm.expectations.CreationObserved(jobKey)\n\t\tjm.enqueueControllerPodUpdate(job, true)\n\t\treturn\n\t}\n\n\t// Otherwise, it's an orphan.\n\t// Clean the finalizer.\n\tif hasJobTrackingFinalizer(pod) {\n\t\tjm.enqueueOrphanPod(pod)\n\t}\n\t// Get a list of all matching controllers and sync\n\t// them to see if anyone wants to adopt it.\n\t// DO NOT observe creation because no controller should be waiting for an\n\t// orphan.\n\tfor _, job := range jm.getPodJobs(pod) {\n\t\tjm.enqueueControllerPodUpdate(job, true)\n\t}\n}","line":{"from":257,"to":295}} {"id":100004025,"name":"updatePod","signature":"func (jm *Controller) updatePod(old, cur interface{})","file":"pkg/controller/job/job_controller.go","code":"// When a pod is updated, figure out what job/s manage it and wake them up.\n// If the labels of the pod have changed we need to awaken both the old\n// and new job. old and cur must be *v1.Pod types.\nfunc (jm *Controller) updatePod(old, cur interface{}) {\n\tcurPod := cur.(*v1.Pod)\n\toldPod := old.(*v1.Pod)\n\trecordFinishedPodWithTrackingFinalizer(oldPod, curPod)\n\tif curPod.ResourceVersion == oldPod.ResourceVersion {\n\t\t// Periodic resync will send update events for all known pods.\n\t\t// Two different versions of the same pod will always have different RVs.\n\t\treturn\n\t}\n\tif curPod.DeletionTimestamp != nil {\n\t\t// when a pod is deleted gracefully it's deletion timestamp is first modified to reflect a grace period,\n\t\t// and after such time has passed, the kubelet actually deletes it from the store. We receive an update\n\t\t// for modification of the deletion timestamp and expect an job to create more pods asap, not wait\n\t\t// until the kubelet actually deletes the pod.\n\t\tjm.deletePod(curPod, false)\n\t\treturn\n\t}\n\n\t// the only time we want the backoff to kick-in, is when the pod failed for the first time.\n\t// we don't want to re-calculate backoff for an update event when the tracking finalizer\n\t// for a failed pod is removed.\n\timmediate := !(curPod.Status.Phase == v1.PodFailed \u0026\u0026 oldPod.Status.Phase != v1.PodFailed)\n\n\t// Don't check if oldPod has the finalizer, as during ownership transfer\n\t// finalizers might be re-added and removed again in behalf of the new owner.\n\t// If all those Pod updates collapse into a single event, the finalizer\n\t// might be removed in oldPod and curPod. We want to record the latest\n\t// state.\n\tfinalizerRemoved := !hasJobTrackingFinalizer(curPod)\n\tcurControllerRef := metav1.GetControllerOf(curPod)\n\toldControllerRef := metav1.GetControllerOf(oldPod)\n\tcontrollerRefChanged := !reflect.DeepEqual(curControllerRef, oldControllerRef)\n\tif controllerRefChanged \u0026\u0026 oldControllerRef != nil {\n\t\t// The ControllerRef was changed. Sync the old controller, if any.\n\t\tif job := jm.resolveControllerRef(oldPod.Namespace, oldControllerRef); job != nil {\n\t\t\tif finalizerRemoved {\n\t\t\t\tkey, err := controller.KeyFunc(job)\n\t\t\t\tif err == nil {\n\t\t\t\t\tjm.finalizerExpectations.finalizerRemovalObserved(key, string(curPod.UID))\n\t\t\t\t}\n\t\t\t}\n\t\t\tjm.enqueueControllerPodUpdate(job, immediate)\n\t\t}\n\t}\n\n\t// If it has a ControllerRef, that's all that matters.\n\tif curControllerRef != nil {\n\t\tjob := jm.resolveControllerRef(curPod.Namespace, curControllerRef)\n\t\tif job == nil {\n\t\t\treturn\n\t\t}\n\t\tif finalizerRemoved {\n\t\t\tkey, err := controller.KeyFunc(job)\n\t\t\tif err == nil {\n\t\t\t\tjm.finalizerExpectations.finalizerRemovalObserved(key, string(curPod.UID))\n\t\t\t}\n\t\t}\n\t\tjm.enqueueControllerPodUpdate(job, immediate)\n\t\treturn\n\t}\n\n\t// Otherwise, it's an orphan.\n\t// Clean the finalizer.\n\tif hasJobTrackingFinalizer(curPod) {\n\t\tjm.enqueueOrphanPod(curPod)\n\t}\n\t// If anything changed, sync matching controllers\n\t// to see if anyone wants to adopt it now.\n\tlabelChanged := !reflect.DeepEqual(curPod.Labels, oldPod.Labels)\n\tif labelChanged || controllerRefChanged {\n\t\tfor _, job := range jm.getPodJobs(curPod) {\n\t\t\tjm.enqueueControllerPodUpdate(job, immediate)\n\t\t}\n\t}\n}","line":{"from":297,"to":374}} {"id":100004026,"name":"deletePod","signature":"func (jm *Controller) deletePod(obj interface{}, final bool)","file":"pkg/controller/job/job_controller.go","code":"// When a pod is deleted, enqueue the job that manages the pod and update its expectations.\n// obj could be an *v1.Pod, or a DeleteFinalStateUnknown marker item.\nfunc (jm *Controller) deletePod(obj interface{}, final bool) {\n\tpod, ok := obj.(*v1.Pod)\n\tif final {\n\t\trecordFinishedPodWithTrackingFinalizer(pod, nil)\n\t}\n\n\t// When a delete is dropped, the relist will notice a pod in the store not\n\t// in the list, leading to the insertion of a tombstone object which contains\n\t// the deleted key/value. Note that this value might be stale. If the pod\n\t// changed labels the new job will not be woken up till the periodic resync.\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get object from tombstone %+v\", obj))\n\t\t\treturn\n\t\t}\n\t\tpod, ok = tombstone.Obj.(*v1.Pod)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"tombstone contained object that is not a pod %+v\", obj))\n\t\t\treturn\n\t\t}\n\t}\n\n\tcontrollerRef := metav1.GetControllerOf(pod)\n\thasFinalizer := hasJobTrackingFinalizer(pod)\n\tif controllerRef == nil {\n\t\t// No controller should care about orphans being deleted.\n\t\t// But this pod might have belonged to a Job and the GC removed the reference.\n\t\tif hasFinalizer {\n\t\t\tjm.enqueueOrphanPod(pod)\n\t\t}\n\t\treturn\n\t}\n\tjob := jm.resolveControllerRef(pod.Namespace, controllerRef)\n\tif job == nil || IsJobFinished(job) {\n\t\t// syncJob will not remove this finalizer.\n\t\tif hasFinalizer {\n\t\t\tjm.enqueueOrphanPod(pod)\n\t\t}\n\t\treturn\n\t}\n\tjobKey, err := controller.KeyFunc(job)\n\tif err != nil {\n\t\treturn\n\t}\n\tjm.expectations.DeletionObserved(jobKey)\n\n\t// Consider the finalizer removed if this is the final delete. Otherwise,\n\t// it's an update for the deletion timestamp, then check finalizer.\n\tif final || !hasFinalizer {\n\t\tjm.finalizerExpectations.finalizerRemovalObserved(jobKey, string(pod.UID))\n\t}\n\n\tjm.enqueueControllerPodUpdate(job, true)\n}","line":{"from":376,"to":432}} {"id":100004027,"name":"updateJob","signature":"func (jm *Controller) updateJob(old, cur interface{})","file":"pkg/controller/job/job_controller.go","code":"func (jm *Controller) updateJob(old, cur interface{}) {\n\toldJob := old.(*batch.Job)\n\tcurJob := cur.(*batch.Job)\n\n\t// never return error\n\tkey, err := controller.KeyFunc(curJob)\n\tif err != nil {\n\t\treturn\n\t}\n\tjm.enqueueController(curJob, true)\n\t// check if need to add a new rsync for ActiveDeadlineSeconds\n\tif curJob.Status.StartTime != nil {\n\t\tcurADS := curJob.Spec.ActiveDeadlineSeconds\n\t\tif curADS == nil {\n\t\t\treturn\n\t\t}\n\t\toldADS := oldJob.Spec.ActiveDeadlineSeconds\n\t\tif oldADS == nil || *oldADS != *curADS {\n\t\t\tpassed := jm.clock.Since(curJob.Status.StartTime.Time)\n\t\t\ttotal := time.Duration(*curADS) * time.Second\n\t\t\t// AddAfter will handle total \u003c passed\n\t\t\tjm.queue.AddAfter(key, total-passed)\n\t\t\tklog.V(4).Infof(\"job %q ActiveDeadlineSeconds updated, will rsync after %d seconds\", key, total-passed)\n\t\t}\n\t}\n}","line":{"from":434,"to":459}} {"id":100004028,"name":"deleteJob","signature":"func (jm *Controller) deleteJob(obj interface{})","file":"pkg/controller/job/job_controller.go","code":"// deleteJob enqueues the job and all the pods associated with it that still\n// have a finalizer.\nfunc (jm *Controller) deleteJob(obj interface{}) {\n\tjm.enqueueController(obj, true)\n\tjobObj, ok := obj.(*batch.Job)\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get object from tombstone %+v\", obj))\n\t\t\treturn\n\t\t}\n\t\tjobObj, ok = tombstone.Obj.(*batch.Job)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"tombstone contained object that is not a job %+v\", obj))\n\t\t\treturn\n\t\t}\n\t}\n\t// Listing pods shouldn't really fail, as we are just querying the informer cache.\n\tselector, err := metav1.LabelSelectorAsSelector(jobObj.Spec.Selector)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"parsing deleted job selector: %v\", err))\n\t\treturn\n\t}\n\tpods, _ := jm.podStore.Pods(jobObj.Namespace).List(selector)\n\tfor _, pod := range pods {\n\t\tif metav1.IsControlledBy(pod, jobObj) \u0026\u0026 hasJobTrackingFinalizer(pod) {\n\t\t\tjm.enqueueOrphanPod(pod)\n\t\t}\n\t}\n}","line":{"from":461,"to":490}} {"id":100004029,"name":"enqueueController","signature":"func (jm *Controller) enqueueController(obj interface{}, immediate bool)","file":"pkg/controller/job/job_controller.go","code":"// obj could be an *batch.Job, or a DeletionFinalStateUnknown marker item,\n// immediate tells the controller to update the status right away, and should\n// happen ONLY when there was a successful pod run.\nfunc (jm *Controller) enqueueController(obj interface{}, immediate bool) {\n\tjm.enqueueControllerDelayed(obj, immediate, 0)\n}","line":{"from":492,"to":497}} {"id":100004030,"name":"enqueueControllerPodUpdate","signature":"func (jm *Controller) enqueueControllerPodUpdate(obj interface{}, immediate bool)","file":"pkg/controller/job/job_controller.go","code":"func (jm *Controller) enqueueControllerPodUpdate(obj interface{}, immediate bool) {\n\tjm.enqueueControllerDelayed(obj, immediate, jm.podUpdateBatchPeriod)\n}","line":{"from":499,"to":501}} {"id":100004031,"name":"enqueueControllerDelayed","signature":"func (jm *Controller) enqueueControllerDelayed(obj interface{}, immediate bool, delay time.Duration)","file":"pkg/controller/job/job_controller.go","code":"func (jm *Controller) enqueueControllerDelayed(obj interface{}, immediate bool, delay time.Duration) {\n\tkey, err := controller.KeyFunc(obj)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Couldn't get key for object %+v: %v\", obj, err))\n\t\treturn\n\t}\n\n\tbackoff := delay\n\tif !immediate {\n\t\tif calculatedBackoff := getBackoff(jm.queue, key); calculatedBackoff \u003e 0 {\n\t\t\tbackoff = calculatedBackoff\n\t\t}\n\t}\n\n\t// TODO: Handle overlapping controllers better. Either disallow them at admission time or\n\t// deterministically avoid syncing controllers that fight over pods. Currently, we only\n\t// ensure that the same controller is synced for a given pod. When we periodically relist\n\t// all controllers there will still be some replica instability. One way to handle this is\n\t// by querying the store for all controllers that this rc overlaps, as well as all\n\t// controllers that overlap this rc, and sorting them.\n\tklog.Infof(\"enqueueing job %s\", key)\n\tjm.queue.AddAfter(key, backoff)\n}","line":{"from":503,"to":525}} {"id":100004032,"name":"enqueueOrphanPod","signature":"func (jm *Controller) enqueueOrphanPod(obj *v1.Pod)","file":"pkg/controller/job/job_controller.go","code":"func (jm *Controller) enqueueOrphanPod(obj *v1.Pod) {\n\tkey, err := controller.KeyFunc(obj)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get key for object %+v: %v\", obj, err))\n\t\treturn\n\t}\n\tjm.orphanQueue.Add(key)\n}","line":{"from":527,"to":534}} {"id":100004033,"name":"worker","signature":"func (jm *Controller) worker(ctx context.Context)","file":"pkg/controller/job/job_controller.go","code":"// worker runs a worker thread that just dequeues items, processes them, and marks them done.\n// It enforces that the syncHandler is never invoked concurrently with the same key.\nfunc (jm *Controller) worker(ctx context.Context) {\n\tfor jm.processNextWorkItem(ctx) {\n\t}\n}","line":{"from":536,"to":541}} {"id":100004034,"name":"processNextWorkItem","signature":"func (jm *Controller) processNextWorkItem(ctx context.Context) bool","file":"pkg/controller/job/job_controller.go","code":"func (jm *Controller) processNextWorkItem(ctx context.Context) bool {\n\tkey, quit := jm.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer jm.queue.Done(key)\n\n\terr := jm.syncHandler(ctx, key.(string))\n\tif err == nil {\n\t\tjm.queue.Forget(key)\n\t\treturn true\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"syncing job: %w\", err))\n\tjm.queue.AddRateLimited(key)\n\n\treturn true\n}","line":{"from":543,"to":560}} {"id":100004035,"name":"orphanWorker","signature":"func (jm *Controller) orphanWorker(ctx context.Context)","file":"pkg/controller/job/job_controller.go","code":"func (jm *Controller) orphanWorker(ctx context.Context) {\n\tfor jm.processNextOrphanPod(ctx) {\n\t}\n}","line":{"from":562,"to":565}} {"id":100004036,"name":"processNextOrphanPod","signature":"func (jm Controller) processNextOrphanPod(ctx context.Context) bool","file":"pkg/controller/job/job_controller.go","code":"func (jm Controller) processNextOrphanPod(ctx context.Context) bool {\n\tkey, quit := jm.orphanQueue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer jm.orphanQueue.Done(key)\n\terr := jm.syncOrphanPod(ctx, key.(string))\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Error syncing orphan pod: %v\", err))\n\t\tjm.orphanQueue.AddRateLimited(key)\n\t} else {\n\t\tjm.orphanQueue.Forget(key)\n\t}\n\n\treturn true\n}","line":{"from":567,"to":582}} {"id":100004037,"name":"syncOrphanPod","signature":"func (jm Controller) syncOrphanPod(ctx context.Context, key string) error","file":"pkg/controller/job/job_controller.go","code":"// syncOrphanPod removes the tracking finalizer from an orphan pod if found.\nfunc (jm Controller) syncOrphanPod(ctx context.Context, key string) error {\n\tstartTime := jm.clock.Now()\n\tdefer func() {\n\t\tklog.V(4).Infof(\"Finished syncing orphan pod %q (%v)\", key, jm.clock.Since(startTime))\n\t}()\n\n\tns, name, err := cache.SplitMetaNamespaceKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsharedPod, err := jm.podStore.Pods(ns).Get(name)\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\tklog.V(4).Infof(\"Orphan pod has been deleted: %v\", key)\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\t// Make sure the pod is still orphaned.\n\tif controllerRef := metav1.GetControllerOf(sharedPod); controllerRef != nil {\n\t\tjob := jm.resolveControllerRef(sharedPod.Namespace, controllerRef)\n\t\tif job != nil \u0026\u0026 !IsJobFinished(job) {\n\t\t\t// The pod was adopted. Do not remove finalizer.\n\t\t\treturn nil\n\t\t}\n\t}\n\tif patch := removeTrackingFinalizerPatch(sharedPod); patch != nil {\n\t\tif err := jm.podControl.PatchPod(ctx, ns, name, patch); err != nil \u0026\u0026 !apierrors.IsNotFound(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":584,"to":618}} {"id":100004038,"name":"getPodsForJob","signature":"func (jm *Controller) getPodsForJob(ctx context.Context, j *batch.Job) ([]*v1.Pod, error)","file":"pkg/controller/job/job_controller.go","code":"// getPodsForJob returns the set of pods that this Job should manage.\n// It also reconciles ControllerRef by adopting/orphaning, adding tracking\n// finalizers.\n// Note that the returned Pods are pointers into the cache.\nfunc (jm *Controller) getPodsForJob(ctx context.Context, j *batch.Job) ([]*v1.Pod, error) {\n\tselector, err := metav1.LabelSelectorAsSelector(j.Spec.Selector)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"couldn't convert Job selector: %v\", err)\n\t}\n\t// List all pods to include those that don't match the selector anymore\n\t// but have a ControllerRef pointing to this controller.\n\tpods, err := jm.podStore.Pods(j.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// If any adoptions are attempted, we should first recheck for deletion\n\t// with an uncached quorum read sometime after listing Pods (see #42639).\n\tcanAdoptFunc := controller.RecheckDeletionTimestamp(func(ctx context.Context) (metav1.Object, error) {\n\t\tfresh, err := jm.kubeClient.BatchV1().Jobs(j.Namespace).Get(ctx, j.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif fresh.UID != j.UID {\n\t\t\treturn nil, fmt.Errorf(\"original Job %v/%v is gone: got uid %v, wanted %v\", j.Namespace, j.Name, fresh.UID, j.UID)\n\t\t}\n\t\treturn fresh, nil\n\t})\n\tcm := controller.NewPodControllerRefManager(jm.podControl, j, selector, controllerKind, canAdoptFunc, batch.JobTrackingFinalizer)\n\t// When adopting Pods, this operation adds an ownerRef and finalizers.\n\tpods, err = cm.ClaimPods(ctx, pods)\n\tif err != nil {\n\t\treturn pods, err\n\t}\n\t// Set finalizer on adopted pods for the remaining calculations.\n\tfor i, p := range pods {\n\t\tadopted := true\n\t\tfor _, r := range p.OwnerReferences {\n\t\t\tif r.UID == j.UID {\n\t\t\t\tadopted = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif adopted \u0026\u0026 !hasJobTrackingFinalizer(p) {\n\t\t\tpods[i] = p.DeepCopy()\n\t\t\tpods[i].Finalizers = append(p.Finalizers, batch.JobTrackingFinalizer)\n\t\t}\n\t}\n\treturn pods, err\n}","line":{"from":620,"to":668}} {"id":100004039,"name":"syncJob","signature":"func (jm *Controller) syncJob(ctx context.Context, key string) (rErr error)","file":"pkg/controller/job/job_controller.go","code":"// syncJob will sync the job with the given key if it has had its expectations fulfilled, meaning\n// it did not expect to see any more of its pods created or deleted. This function is not meant to be invoked\n// concurrently with the same key.\nfunc (jm *Controller) syncJob(ctx context.Context, key string) (rErr error) {\n\tstartTime := jm.clock.Now()\n\tdefer func() {\n\t\tklog.V(4).Infof(\"Finished syncing job %q (%v)\", key, jm.clock.Since(startTime))\n\t}()\n\n\tns, name, err := cache.SplitMetaNamespaceKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(ns) == 0 || len(name) == 0 {\n\t\treturn fmt.Errorf(\"invalid job key %q: either namespace or name is missing\", key)\n\t}\n\tsharedJob, err := jm.jobLister.Jobs(ns).Get(name)\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\tklog.V(4).Infof(\"Job has been deleted: %v\", key)\n\t\t\tjm.expectations.DeleteExpectations(key)\n\t\t\tjm.finalizerExpectations.deleteExpectations(key)\n\n\t\t\terr := jm.backoffRecordStore.removeBackoffRecord(key)\n\t\t\tif err != nil {\n\t\t\t\t// re-syncing here as the record has to be removed for finished/deleted jobs\n\t\t\t\treturn fmt.Errorf(\"error removing backoff record %w\", err)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\t// make a copy so we don't mutate the shared cache\n\tjob := *sharedJob.DeepCopy()\n\n\t// if job was finished previously, we don't want to redo the termination\n\tif IsJobFinished(\u0026job) {\n\t\terr := jm.backoffRecordStore.removeBackoffRecord(key)\n\t\tif err != nil {\n\t\t\t// re-syncing here as the record has to be removed for finished/deleted jobs\n\t\t\treturn fmt.Errorf(\"error removing backoff record %w\", err)\n\t\t}\n\t\treturn nil\n\t}\n\n\tif job.Spec.CompletionMode != nil \u0026\u0026 *job.Spec.CompletionMode != batch.NonIndexedCompletion \u0026\u0026 *job.Spec.CompletionMode != batch.IndexedCompletion {\n\t\tjm.recorder.Event(\u0026job, v1.EventTypeWarning, \"UnknownCompletionMode\", \"Skipped Job sync because completion mode is unknown\")\n\t\treturn nil\n\t}\n\n\tcompletionMode := getCompletionMode(\u0026job)\n\taction := metrics.JobSyncActionReconciling\n\n\tdefer func() {\n\t\tresult := \"success\"\n\t\tif rErr != nil {\n\t\t\tresult = \"error\"\n\t\t}\n\n\t\tmetrics.JobSyncDurationSeconds.WithLabelValues(completionMode, result, action).Observe(jm.clock.Since(startTime).Seconds())\n\t\tmetrics.JobSyncNum.WithLabelValues(completionMode, result, action).Inc()\n\t}()\n\n\tif job.Status.UncountedTerminatedPods == nil {\n\t\tjob.Status.UncountedTerminatedPods = \u0026batch.UncountedTerminatedPods{}\n\t}\n\tuncounted := newUncountedTerminatedPods(*job.Status.UncountedTerminatedPods)\n\texpectedRmFinalizers := jm.finalizerExpectations.getExpectedUIDs(key)\n\n\t// Check the expectations of the job before counting active pods, otherwise a new pod can sneak in\n\t// and update the expectations after we've retrieved active pods from the store. If a new pod enters\n\t// the store after we've checked the expectation, the job sync is just deferred till the next relist.\n\tsatisfiedExpectations := jm.expectations.SatisfiedExpectations(key)\n\n\tpods, err := jm.getPodsForJob(ctx, \u0026job)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tactivePods := controller.FilterActivePods(pods)\n\tactive := int32(len(activePods))\n\tnewSucceededPods, newFailedPods := getNewFinishedPods(\u0026job, pods, uncounted, expectedRmFinalizers)\n\tsucceeded := job.Status.Succeeded + int32(len(newSucceededPods)) + int32(len(uncounted.succeeded))\n\tfailed := job.Status.Failed + int32(len(newFailedPods)) + int32(len(uncounted.failed))\n\tvar ready *int32\n\tif feature.DefaultFeatureGate.Enabled(features.JobReadyPods) {\n\t\tready = pointer.Int32(countReadyPods(activePods))\n\t}\n\n\t// Job first start. Set StartTime only if the job is not in the suspended state.\n\tif job.Status.StartTime == nil \u0026\u0026 !jobSuspended(\u0026job) {\n\t\tnow := metav1.NewTime(jm.clock.Now())\n\t\tjob.Status.StartTime = \u0026now\n\t}\n\n\tnewBackoffInfo := jm.backoffRecordStore.newBackoffRecord(jm.clock, key, newSucceededPods, newFailedPods)\n\n\tvar manageJobErr error\n\tvar finishedCondition *batch.JobCondition\n\n\tjobHasNewFailure := failed \u003e job.Status.Failed\n\texceedsBackoffLimit := failed \u003e *job.Spec.BackoffLimit\n\n\tif feature.DefaultFeatureGate.Enabled(features.JobPodFailurePolicy) {\n\t\tif failureTargetCondition := findConditionByType(job.Status.Conditions, batch.JobFailureTarget); failureTargetCondition != nil {\n\t\t\tfinishedCondition = newFailedConditionForFailureTarget(failureTargetCondition, jm.clock.Now())\n\t\t} else if failJobMessage := getFailJobMessage(\u0026job, pods, uncounted.Failed()); failJobMessage != nil {\n\t\t\t// Prepare the interim FailureTarget condition to record the failure message before the finalizers (allowing removal of the pods) are removed.\n\t\t\tfinishedCondition = newCondition(batch.JobFailureTarget, v1.ConditionTrue, jobConditionReasonPodFailurePolicy, *failJobMessage, jm.clock.Now())\n\t\t}\n\t}\n\tif finishedCondition == nil {\n\t\tif exceedsBackoffLimit || pastBackoffLimitOnFailure(\u0026job, pods) {\n\t\t\t// check if the number of pod restart exceeds backoff (for restart OnFailure only)\n\t\t\t// OR if the number of failed jobs increased since the last syncJob\n\t\t\tfinishedCondition = newCondition(batch.JobFailed, v1.ConditionTrue, \"BackoffLimitExceeded\", \"Job has reached the specified backoff limit\", jm.clock.Now())\n\t\t} else if jm.pastActiveDeadline(\u0026job) {\n\t\t\tfinishedCondition = newCondition(batch.JobFailed, v1.ConditionTrue, \"DeadlineExceeded\", \"Job was active longer than specified deadline\", jm.clock.Now())\n\t\t} else if job.Spec.ActiveDeadlineSeconds != nil \u0026\u0026 !jobSuspended(\u0026job) {\n\t\t\tsyncDuration := time.Duration(*job.Spec.ActiveDeadlineSeconds)*time.Second - jm.clock.Since(job.Status.StartTime.Time)\n\t\t\tklog.V(2).InfoS(\"Job has activeDeadlineSeconds configuration. Will sync this job again\", \"job\", key, \"nextSyncIn\", syncDuration)\n\t\t\tjm.queue.AddAfter(key, syncDuration)\n\t\t}\n\t}\n\n\tvar prevSucceededIndexes, succeededIndexes orderedIntervals\n\tif isIndexedJob(\u0026job) {\n\t\tprevSucceededIndexes, succeededIndexes = calculateSucceededIndexes(\u0026job, pods)\n\t\tsucceeded = int32(succeededIndexes.total())\n\t}\n\tsuspendCondChanged := false\n\t// Remove active pods if Job failed.\n\tif finishedCondition != nil {\n\t\tdeleted, err := jm.deleteActivePods(ctx, \u0026job, activePods)\n\t\tif deleted != active || !satisfiedExpectations {\n\t\t\t// Can't declare the Job as finished yet, as there might be remaining\n\t\t\t// pod finalizers or pods that are not in the informer's cache yet.\n\t\t\tfinishedCondition = nil\n\t\t}\n\t\tactive -= deleted\n\t\tmanageJobErr = err\n\t} else {\n\t\tmanageJobCalled := false\n\t\tif satisfiedExpectations \u0026\u0026 job.DeletionTimestamp == nil {\n\t\t\tactive, action, manageJobErr = jm.manageJob(ctx, \u0026job, activePods, succeeded, succeededIndexes, newBackoffInfo)\n\t\t\tmanageJobCalled = true\n\t\t}\n\t\tcomplete := false\n\t\tif job.Spec.Completions == nil {\n\t\t\t// This type of job is complete when any pod exits with success.\n\t\t\t// Each pod is capable of\n\t\t\t// determining whether or not the entire Job is done. Subsequent pods are\n\t\t\t// not expected to fail, but if they do, the failure is ignored. Once any\n\t\t\t// pod succeeds, the controller waits for remaining pods to finish, and\n\t\t\t// then the job is complete.\n\t\t\tcomplete = succeeded \u003e 0 \u0026\u0026 active == 0\n\t\t} else {\n\t\t\t// Job specifies a number of completions. This type of job signals\n\t\t\t// success by having that number of successes. Since we do not\n\t\t\t// start more pods than there are remaining completions, there should\n\t\t\t// not be any remaining active pods once this count is reached.\n\t\t\tcomplete = succeeded \u003e= *job.Spec.Completions \u0026\u0026 active == 0\n\t\t}\n\t\tif complete {\n\t\t\tfinishedCondition = newCondition(batch.JobComplete, v1.ConditionTrue, \"\", \"\", jm.clock.Now())\n\t\t} else if manageJobCalled {\n\t\t\t// Update the conditions / emit events only if manageJob was called in\n\t\t\t// this syncJob. Otherwise wait for the right syncJob call to make\n\t\t\t// updates.\n\t\t\tif job.Spec.Suspend != nil \u0026\u0026 *job.Spec.Suspend {\n\t\t\t\t// Job can be in the suspended state only if it is NOT completed.\n\t\t\t\tvar isUpdated bool\n\t\t\t\tjob.Status.Conditions, isUpdated = ensureJobConditionStatus(job.Status.Conditions, batch.JobSuspended, v1.ConditionTrue, \"JobSuspended\", \"Job suspended\", jm.clock.Now())\n\t\t\t\tif isUpdated {\n\t\t\t\t\tsuspendCondChanged = true\n\t\t\t\t\tjm.recorder.Event(\u0026job, v1.EventTypeNormal, \"Suspended\", \"Job suspended\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Job not suspended.\n\t\t\t\tvar isUpdated bool\n\t\t\t\tjob.Status.Conditions, isUpdated = ensureJobConditionStatus(job.Status.Conditions, batch.JobSuspended, v1.ConditionFalse, \"JobResumed\", \"Job resumed\", jm.clock.Now())\n\t\t\t\tif isUpdated {\n\t\t\t\t\tsuspendCondChanged = true\n\t\t\t\t\tjm.recorder.Event(\u0026job, v1.EventTypeNormal, \"Resumed\", \"Job resumed\")\n\t\t\t\t\t// Resumed jobs will always reset StartTime to current time. This is\n\t\t\t\t\t// done because the ActiveDeadlineSeconds timer shouldn't go off\n\t\t\t\t\t// whilst the Job is still suspended and resetting StartTime is\n\t\t\t\t\t// consistent with resuming a Job created in the suspended state.\n\t\t\t\t\t// (ActiveDeadlineSeconds is interpreted as the number of seconds a\n\t\t\t\t\t// Job is continuously active.)\n\t\t\t\t\tnow := metav1.NewTime(jm.clock.Now())\n\t\t\t\t\tjob.Status.StartTime = \u0026now\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tneedsStatusUpdate := suspendCondChanged || active != job.Status.Active || !equalReady(ready, job.Status.Ready)\n\tjob.Status.Active = active\n\tjob.Status.Ready = ready\n\terr = jm.trackJobStatusAndRemoveFinalizers(ctx, \u0026job, pods, prevSucceededIndexes, *uncounted, expectedRmFinalizers, finishedCondition, needsStatusUpdate, newBackoffInfo)\n\tif err != nil {\n\t\tif apierrors.IsConflict(err) {\n\t\t\t// we probably have a stale informer cache\n\t\t\t// so don't return an error to avoid backoff\n\t\t\tjm.enqueueController(\u0026job, false)\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"tracking status: %w\", err)\n\t}\n\n\tjobFinished := IsJobFinished(\u0026job)\n\tif jobHasNewFailure \u0026\u0026 !jobFinished {\n\t\t// returning an error will re-enqueue Job after the backoff period\n\t\treturn fmt.Errorf(\"failed pod(s) detected for job key %q\", key)\n\t}\n\n\treturn manageJobErr\n}","line":{"from":670,"to":888}} {"id":100004040,"name":"deleteActivePods","signature":"func (jm *Controller) deleteActivePods(ctx context.Context, job *batch.Job, pods []*v1.Pod) (int32, error)","file":"pkg/controller/job/job_controller.go","code":"// deleteActivePods issues deletion for active Pods, preserving finalizers.\n// This is done through DELETE calls that set deletion timestamps.\n// The method trackJobStatusAndRemoveFinalizers removes the finalizers, after\n// which the objects can actually be deleted.\n// Returns number of successfully deletions issued.\nfunc (jm *Controller) deleteActivePods(ctx context.Context, job *batch.Job, pods []*v1.Pod) (int32, error) {\n\terrCh := make(chan error, len(pods))\n\tsuccessfulDeletes := int32(len(pods))\n\twg := sync.WaitGroup{}\n\twg.Add(len(pods))\n\tfor i := range pods {\n\t\tgo func(pod *v1.Pod) {\n\t\t\tdefer wg.Done()\n\t\t\tif err := jm.podControl.DeletePod(ctx, job.Namespace, pod.Name, job); err != nil \u0026\u0026 !apierrors.IsNotFound(err) {\n\t\t\t\tatomic.AddInt32(\u0026successfulDeletes, -1)\n\t\t\t\terrCh \u003c- err\n\t\t\t\tutilruntime.HandleError(err)\n\t\t\t}\n\t\t}(pods[i])\n\t}\n\twg.Wait()\n\treturn successfulDeletes, errorFromChannel(errCh)\n}","line":{"from":890,"to":912}} {"id":100004041,"name":"deleteJobPods","signature":"func (jm *Controller) deleteJobPods(ctx context.Context, job *batch.Job, jobKey string, pods []*v1.Pod) (int32, error)","file":"pkg/controller/job/job_controller.go","code":"// deleteJobPods deletes the pods, returns the number of successful removals\n// and any error.\nfunc (jm *Controller) deleteJobPods(ctx context.Context, job *batch.Job, jobKey string, pods []*v1.Pod) (int32, error) {\n\terrCh := make(chan error, len(pods))\n\tsuccessfulDeletes := int32(len(pods))\n\n\tfailDelete := func(pod *v1.Pod, err error) {\n\t\t// Decrement the expected number of deletes because the informer won't observe this deletion\n\t\tjm.expectations.DeletionObserved(jobKey)\n\t\tif !apierrors.IsNotFound(err) {\n\t\t\tklog.V(2).Infof(\"Failed to delete Pod\", \"job\", klog.KObj(job), \"pod\", klog.KObj(pod), \"err\", err)\n\t\t\tatomic.AddInt32(\u0026successfulDeletes, -1)\n\t\t\terrCh \u003c- err\n\t\t\tutilruntime.HandleError(err)\n\t\t}\n\t}\n\n\twg := sync.WaitGroup{}\n\twg.Add(len(pods))\n\tfor i := range pods {\n\t\tgo func(pod *v1.Pod) {\n\t\t\tdefer wg.Done()\n\t\t\tif patch := removeTrackingFinalizerPatch(pod); patch != nil {\n\t\t\t\tif err := jm.podControl.PatchPod(ctx, pod.Namespace, pod.Name, patch); err != nil {\n\t\t\t\t\tfailDelete(pod, fmt.Errorf(\"removing completion finalizer: %w\", err))\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err := jm.podControl.DeletePod(ctx, job.Namespace, pod.Name, job); err != nil {\n\t\t\t\tfailDelete(pod, err)\n\t\t\t}\n\t\t}(pods[i])\n\t}\n\twg.Wait()\n\treturn successfulDeletes, errorFromChannel(errCh)\n}","line":{"from":914,"to":949}} {"id":100004042,"name":"trackJobStatusAndRemoveFinalizers","signature":"func (jm *Controller) trackJobStatusAndRemoveFinalizers(ctx context.Context, job *batch.Job, pods []*v1.Pod, succeededIndexes orderedIntervals, uncounted uncountedTerminatedPods, expectedRmFinalizers sets.String, finishedCond *batch.JobCondition, needsFlush bool, newBackoffRecord backoffRecord) error","file":"pkg/controller/job/job_controller.go","code":"// trackJobStatusAndRemoveFinalizers does:\n// 1. Add finished Pods to .status.uncountedTerminatedPods\n// 2. Remove the finalizers from the Pods if they completed or were removed\n// or the job was removed.\n// 3. Increment job counters for pods that no longer have a finalizer.\n// 4. Add Complete condition if satisfied with current counters.\n//\n// It does this up to a limited number of Pods so that the size of .status\n// doesn't grow too much and this sync doesn't starve other Jobs.\nfunc (jm *Controller) trackJobStatusAndRemoveFinalizers(ctx context.Context, job *batch.Job, pods []*v1.Pod, succeededIndexes orderedIntervals, uncounted uncountedTerminatedPods, expectedRmFinalizers sets.String, finishedCond *batch.JobCondition, needsFlush bool, newBackoffRecord backoffRecord) error {\n\tisIndexed := isIndexedJob(job)\n\tvar podsToRemoveFinalizer []*v1.Pod\n\tuncountedStatus := job.Status.UncountedTerminatedPods\n\tvar newSucceededIndexes []int\n\tif isIndexed {\n\t\t// Sort to introduce completed Indexes in order.\n\t\tsort.Sort(byCompletionIndex(pods))\n\t}\n\tuidsWithFinalizer := make(sets.String, len(pods))\n\tfor _, p := range pods {\n\t\tuid := string(p.UID)\n\t\tif hasJobTrackingFinalizer(p) \u0026\u0026 !expectedRmFinalizers.Has(uid) {\n\t\t\tuidsWithFinalizer.Insert(uid)\n\t\t}\n\t}\n\n\t// Shallow copy, as it will only be used to detect changes in the counters.\n\toldCounters := job.Status\n\tif cleanUncountedPodsWithoutFinalizers(\u0026job.Status, uidsWithFinalizer) {\n\t\tneedsFlush = true\n\t}\n\tpodFailureCountByPolicyAction := map[string]int{}\n\treachedMaxUncountedPods := false\n\tfor _, pod := range pods {\n\t\tif !hasJobTrackingFinalizer(pod) || expectedRmFinalizers.Has(string(pod.UID)) {\n\t\t\t// This pod was processed in a previous sync.\n\t\t\tcontinue\n\t\t}\n\t\t// Terminating pods are counted as failed. This guarantees that orphan Pods\n\t\t// count as failures.\n\t\t// Active pods are terminated when the job has completed, thus they count as\n\t\t// failures as well.\n\t\tconsiderTerminated := pod.DeletionTimestamp != nil || finishedCond != nil\n\n\t\tif feature.DefaultFeatureGate.Enabled(features.PodDisruptionConditions) \u0026\u0026 feature.DefaultFeatureGate.Enabled(features.JobPodFailurePolicy) \u0026\u0026 job.Spec.PodFailurePolicy != nil {\n\t\t\t// TODO(#113855): Stop limiting this behavior to Jobs with podFailurePolicy.\n\t\t\t// For now, we do so to avoid affecting all running Jobs without the\n\t\t\t// avaibility to opt-out into the old behavior.\n\t\t\t// We can also simplify the check to remove finalizers to:\n\t\t\t// considerTerminated || job.DeletionTimestamp != nil\n\t\t\tconsiderTerminated = podutil.IsPodTerminal(pod) ||\n\t\t\t\tfinishedCond != nil || // The Job is terminating. Any running Pod is considered failed.\n\t\t\t\tisPodFailed(pod, job)\n\t\t}\n\t\tif podutil.IsPodTerminal(pod) || considerTerminated || job.DeletionTimestamp != nil {\n\t\t\tpodsToRemoveFinalizer = append(podsToRemoveFinalizer, pod)\n\t\t}\n\t\tif pod.Status.Phase == v1.PodSucceeded \u0026\u0026 !uncounted.failed.Has(string(pod.UID)) {\n\t\t\tif isIndexed {\n\t\t\t\t// The completion index is enough to avoid recounting succeeded pods.\n\t\t\t\t// No need to track UIDs.\n\t\t\t\tix := getCompletionIndex(pod.Annotations)\n\t\t\t\tif ix != unknownCompletionIndex \u0026\u0026 ix \u003c int(*job.Spec.Completions) \u0026\u0026 !succeededIndexes.has(ix) {\n\t\t\t\t\tnewSucceededIndexes = append(newSucceededIndexes, ix)\n\t\t\t\t\tneedsFlush = true\n\t\t\t\t}\n\t\t\t} else if !uncounted.succeeded.Has(string(pod.UID)) {\n\t\t\t\tneedsFlush = true\n\t\t\t\tuncountedStatus.Succeeded = append(uncountedStatus.Succeeded, pod.UID)\n\t\t\t}\n\t\t} else if pod.Status.Phase == v1.PodFailed || considerTerminated {\n\t\t\tix := getCompletionIndex(pod.Annotations)\n\t\t\tif !uncounted.failed.Has(string(pod.UID)) \u0026\u0026 (!isIndexed || (ix != unknownCompletionIndex \u0026\u0026 ix \u003c int(*job.Spec.Completions))) {\n\t\t\t\tif feature.DefaultFeatureGate.Enabled(features.JobPodFailurePolicy) \u0026\u0026 job.Spec.PodFailurePolicy != nil {\n\t\t\t\t\t_, countFailed, action := matchPodFailurePolicy(job.Spec.PodFailurePolicy, pod)\n\t\t\t\t\tif action != nil {\n\t\t\t\t\t\tpodFailureCountByPolicyAction[string(*action)] += 1\n\t\t\t\t\t}\n\t\t\t\t\tif countFailed {\n\t\t\t\t\t\tneedsFlush = true\n\t\t\t\t\t\tuncountedStatus.Failed = append(uncountedStatus.Failed, pod.UID)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tneedsFlush = true\n\t\t\t\t\tuncountedStatus.Failed = append(uncountedStatus.Failed, pod.UID)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif len(newSucceededIndexes)+len(uncountedStatus.Succeeded)+len(uncountedStatus.Failed) \u003e= MaxUncountedPods {\n\t\t\t// The controller added enough Pods already to .status.uncountedTerminatedPods\n\t\t\t// We stop counting pods and removing finalizers here to:\n\t\t\t// 1. Ensure that the UIDs representation are under 20 KB.\n\t\t\t// 2. Cap the number of finalizer removals so that syncing of big Jobs\n\t\t\t// doesn't starve smaller ones.\n\t\t\t//\n\t\t\t// The job will be synced again because the Job status and Pod updates\n\t\t\t// will put the Job back to the work queue.\n\t\t\treachedMaxUncountedPods = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif isIndexed {\n\t\tsucceededIndexes = succeededIndexes.withOrderedIndexes(newSucceededIndexes)\n\t\tsucceededIndexesStr := succeededIndexes.String()\n\t\tif succeededIndexesStr != job.Status.CompletedIndexes {\n\t\t\tneedsFlush = true\n\t\t}\n\t\tjob.Status.Succeeded = int32(succeededIndexes.total())\n\t\tjob.Status.CompletedIndexes = succeededIndexesStr\n\t}\n\tif feature.DefaultFeatureGate.Enabled(features.JobPodFailurePolicy) {\n\t\tif finishedCond != nil \u0026\u0026 finishedCond.Type == batch.JobFailureTarget {\n\n\t\t\t// Append the interim FailureTarget condition to update the job status with before finalizers are removed.\n\t\t\tjob.Status.Conditions = append(job.Status.Conditions, *finishedCond)\n\t\t\tneedsFlush = true\n\n\t\t\t// Prepare the final Failed condition to update the job status with after the finalizers are removed.\n\t\t\t// It is also used in the enactJobFinished function for reporting.\n\t\t\tfinishedCond = newFailedConditionForFailureTarget(finishedCond, jm.clock.Now())\n\t\t}\n\t}\n\tvar err error\n\tif job, needsFlush, err = jm.flushUncountedAndRemoveFinalizers(ctx, job, podsToRemoveFinalizer, uidsWithFinalizer, \u0026oldCounters, podFailureCountByPolicyAction, needsFlush, newBackoffRecord); err != nil {\n\t\treturn err\n\t}\n\tjobFinished := !reachedMaxUncountedPods \u0026\u0026 jm.enactJobFinished(job, finishedCond)\n\tif jobFinished {\n\t\tneedsFlush = true\n\t}\n\tif needsFlush {\n\t\tif _, err := jm.updateStatusHandler(ctx, job); err != nil {\n\t\t\treturn fmt.Errorf(\"removing uncounted pods from status: %w\", err)\n\t\t}\n\t\tif jobFinished {\n\t\t\tjm.recordJobFinished(job, finishedCond)\n\t\t}\n\t\trecordJobPodFinished(job, oldCounters)\n\t}\n\treturn nil\n}","line":{"from":951,"to":1091}} {"id":100004043,"name":"flushUncountedAndRemoveFinalizers","signature":"func (jm *Controller) flushUncountedAndRemoveFinalizers(ctx context.Context, job *batch.Job, podsToRemoveFinalizer []*v1.Pod, uidsWithFinalizer sets.String, oldCounters *batch.JobStatus, podFailureCountByPolicyAction map[string]int, needsFlush bool, newBackoffRecord backoffRecord) (*batch.Job, bool, error)","file":"pkg/controller/job/job_controller.go","code":"// flushUncountedAndRemoveFinalizers does:\n// 1. flush the Job status that might include new uncounted Pod UIDs. Also flush the interim FailureTarget condition\n// if present.\n// 2. perform the removal of finalizers from Pods which are in the uncounted\n// lists.\n// 3. update the counters based on the Pods for which it successfully removed\n// the finalizers.\n// 4. (if not all removals succeeded) flush Job status again.\n//\n// Returns whether there are pending changes in the Job status that need to be\n// flushed in subsequent calls.\nfunc (jm *Controller) flushUncountedAndRemoveFinalizers(ctx context.Context, job *batch.Job, podsToRemoveFinalizer []*v1.Pod, uidsWithFinalizer sets.String, oldCounters *batch.JobStatus, podFailureCountByPolicyAction map[string]int, needsFlush bool, newBackoffRecord backoffRecord) (*batch.Job, bool, error) {\n\tvar err error\n\tif needsFlush {\n\t\tif job, err = jm.updateStatusHandler(ctx, job); err != nil {\n\t\t\treturn job, needsFlush, fmt.Errorf(\"adding uncounted pods to status: %w\", err)\n\t\t}\n\n\t\terr = jm.backoffRecordStore.updateBackoffRecord(newBackoffRecord)\n\n\t\tif err != nil {\n\t\t\t// this error might undercount the backoff.\n\t\t\t// re-syncing from the current state might not help to recover\n\t\t\t// the backoff information\n\t\t\tklog.ErrorS(err, \"Backoff update failed\")\n\t\t}\n\n\t\trecordJobPodFinished(job, *oldCounters)\n\t\t// Shallow copy, as it will only be used to detect changes in the counters.\n\t\t*oldCounters = job.Status\n\t\tneedsFlush = false\n\t}\n\trecordJobPodFailurePolicyActions(job, podFailureCountByPolicyAction)\n\n\tjobKey, err := controller.KeyFunc(job)\n\tif err != nil {\n\t\treturn job, needsFlush, fmt.Errorf(\"getting job key: %w\", err)\n\t}\n\tvar rmErr error\n\tif len(podsToRemoveFinalizer) \u003e 0 {\n\t\tvar rmSucceded []bool\n\t\trmSucceded, rmErr = jm.removeTrackingFinalizerFromPods(ctx, jobKey, podsToRemoveFinalizer)\n\t\tfor i, p := range podsToRemoveFinalizer {\n\t\t\tif rmSucceded[i] {\n\t\t\t\tuidsWithFinalizer.Delete(string(p.UID))\n\t\t\t}\n\t\t}\n\t}\n\t// Failed to remove some finalizers. Attempt to update the status with the\n\t// partial progress.\n\tif cleanUncountedPodsWithoutFinalizers(\u0026job.Status, uidsWithFinalizer) {\n\t\tneedsFlush = true\n\t}\n\tif rmErr != nil \u0026\u0026 needsFlush {\n\t\tif job, err := jm.updateStatusHandler(ctx, job); err != nil {\n\t\t\treturn job, needsFlush, fmt.Errorf(\"removing uncounted pods from status: %w\", err)\n\t\t}\n\t}\n\treturn job, needsFlush, rmErr\n}","line":{"from":1093,"to":1152}} {"id":100004044,"name":"cleanUncountedPodsWithoutFinalizers","signature":"func cleanUncountedPodsWithoutFinalizers(status *batch.JobStatus, uidsWithFinalizer sets.String) bool","file":"pkg/controller/job/job_controller.go","code":"// cleanUncountedPodsWithoutFinalizers removes the Pod UIDs from\n// .status.uncountedTerminatedPods for which the finalizer was successfully\n// removed and increments the corresponding status counters.\n// Returns whether there was any status change.\nfunc cleanUncountedPodsWithoutFinalizers(status *batch.JobStatus, uidsWithFinalizer sets.String) bool {\n\tupdated := false\n\tuncountedStatus := status.UncountedTerminatedPods\n\tnewUncounted := filterInUncountedUIDs(uncountedStatus.Succeeded, uidsWithFinalizer)\n\tif len(newUncounted) != len(uncountedStatus.Succeeded) {\n\t\tupdated = true\n\t\tstatus.Succeeded += int32(len(uncountedStatus.Succeeded) - len(newUncounted))\n\t\tuncountedStatus.Succeeded = newUncounted\n\t}\n\tnewUncounted = filterInUncountedUIDs(uncountedStatus.Failed, uidsWithFinalizer)\n\tif len(newUncounted) != len(uncountedStatus.Failed) {\n\t\tupdated = true\n\t\tstatus.Failed += int32(len(uncountedStatus.Failed) - len(newUncounted))\n\t\tuncountedStatus.Failed = newUncounted\n\t}\n\treturn updated\n}","line":{"from":1154,"to":1174}} {"id":100004045,"name":"removeTrackingFinalizerFromPods","signature":"func (jm *Controller) removeTrackingFinalizerFromPods(ctx context.Context, jobKey string, pods []*v1.Pod) ([]bool, error)","file":"pkg/controller/job/job_controller.go","code":"// removeTrackingFinalizerFromPods removes tracking finalizers from Pods and\n// returns an array of booleans where the i-th value is true if the finalizer\n// of the i-th Pod was successfully removed (if the pod was deleted when this\n// function was called, it's considered as the finalizer was removed successfully).\nfunc (jm *Controller) removeTrackingFinalizerFromPods(ctx context.Context, jobKey string, pods []*v1.Pod) ([]bool, error) {\n\terrCh := make(chan error, len(pods))\n\tsucceeded := make([]bool, len(pods))\n\tuids := make([]string, len(pods))\n\tfor i, p := range pods {\n\t\tuids[i] = string(p.UID)\n\t}\n\tif jobKey != \"\" {\n\t\terr := jm.finalizerExpectations.expectFinalizersRemoved(jobKey, uids)\n\t\tif err != nil {\n\t\t\treturn succeeded, fmt.Errorf(\"setting expected removed finalizers: %w\", err)\n\t\t}\n\t}\n\twg := sync.WaitGroup{}\n\twg.Add(len(pods))\n\tfor i := range pods {\n\t\tgo func(i int) {\n\t\t\tpod := pods[i]\n\t\t\tdefer wg.Done()\n\t\t\tif patch := removeTrackingFinalizerPatch(pod); patch != nil {\n\t\t\t\tif err := jm.podControl.PatchPod(ctx, pod.Namespace, pod.Name, patch); err != nil {\n\t\t\t\t\t// In case of any failure, we don't expect a Pod update for the\n\t\t\t\t\t// finalizer removed. Clear expectation now.\n\t\t\t\t\tif jobKey != \"\" {\n\t\t\t\t\t\tjm.finalizerExpectations.finalizerRemovalObserved(jobKey, string(pod.UID))\n\t\t\t\t\t}\n\t\t\t\t\tif !apierrors.IsNotFound(err) {\n\t\t\t\t\t\terrCh \u003c- err\n\t\t\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"removing tracking finalizer: %w\", err))\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tsucceeded[i] = true\n\t\t\t}\n\t\t}(i)\n\t}\n\twg.Wait()\n\n\treturn succeeded, errorFromChannel(errCh)\n}","line":{"from":1176,"to":1219}} {"id":100004046,"name":"enactJobFinished","signature":"func (jm *Controller) enactJobFinished(job *batch.Job, finishedCond *batch.JobCondition) bool","file":"pkg/controller/job/job_controller.go","code":"// enactJobFinished adds the Complete or Failed condition and records events.\n// Returns whether the Job was considered finished.\nfunc (jm *Controller) enactJobFinished(job *batch.Job, finishedCond *batch.JobCondition) bool {\n\tif finishedCond == nil {\n\t\treturn false\n\t}\n\tif uncounted := job.Status.UncountedTerminatedPods; uncounted != nil {\n\t\tif len(uncounted.Succeeded) \u003e 0 || len(uncounted.Failed) \u003e 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\tjob.Status.Conditions, _ = ensureJobConditionStatus(job.Status.Conditions, finishedCond.Type, finishedCond.Status, finishedCond.Reason, finishedCond.Message, jm.clock.Now())\n\tif finishedCond.Type == batch.JobComplete {\n\t\tjob.Status.CompletionTime = \u0026finishedCond.LastTransitionTime\n\t}\n\treturn true\n}","line":{"from":1221,"to":1237}} {"id":100004047,"name":"recordJobFinished","signature":"func (jm *Controller) recordJobFinished(job *batch.Job, finishedCond *batch.JobCondition) bool","file":"pkg/controller/job/job_controller.go","code":"// recordJobFinished records events and the job_finished_total metric for a finished job.\nfunc (jm *Controller) recordJobFinished(job *batch.Job, finishedCond *batch.JobCondition) bool {\n\tcompletionMode := getCompletionMode(job)\n\tif finishedCond.Type == batch.JobComplete {\n\t\tif job.Spec.Completions != nil \u0026\u0026 job.Status.Succeeded \u003e *job.Spec.Completions {\n\t\t\tjm.recorder.Event(job, v1.EventTypeWarning, \"TooManySucceededPods\", \"Too many succeeded pods running after completion count reached\")\n\t\t}\n\t\tjm.recorder.Event(job, v1.EventTypeNormal, \"Completed\", \"Job completed\")\n\t\tmetrics.JobFinishedNum.WithLabelValues(completionMode, \"succeeded\", \"\").Inc()\n\t} else {\n\t\tjm.recorder.Event(job, v1.EventTypeWarning, finishedCond.Reason, finishedCond.Message)\n\t\tmetrics.JobFinishedNum.WithLabelValues(completionMode, \"failed\", finishedCond.Reason).Inc()\n\t}\n\treturn true\n}","line":{"from":1239,"to":1253}} {"id":100004048,"name":"filterInUncountedUIDs","signature":"func filterInUncountedUIDs(uncounted []types.UID, include sets.String) []types.UID","file":"pkg/controller/job/job_controller.go","code":"func filterInUncountedUIDs(uncounted []types.UID, include sets.String) []types.UID {\n\tvar newUncounted []types.UID\n\tfor _, uid := range uncounted {\n\t\tif include.Has(string(uid)) {\n\t\t\tnewUncounted = append(newUncounted, uid)\n\t\t}\n\t}\n\treturn newUncounted\n}","line":{"from":1255,"to":1263}} {"id":100004049,"name":"newFailedConditionForFailureTarget","signature":"func newFailedConditionForFailureTarget(condition *batch.JobCondition, now time.Time) *batch.JobCondition","file":"pkg/controller/job/job_controller.go","code":"// newFailedConditionForFailureTarget creates a job Failed condition based on\n// the interim FailureTarget condition.\nfunc newFailedConditionForFailureTarget(condition *batch.JobCondition, now time.Time) *batch.JobCondition {\n\treturn newCondition(batch.JobFailed, v1.ConditionTrue, condition.Reason, condition.Message, now)\n}","line":{"from":1265,"to":1269}} {"id":100004050,"name":"pastBackoffLimitOnFailure","signature":"func pastBackoffLimitOnFailure(job *batch.Job, pods []*v1.Pod) bool","file":"pkg/controller/job/job_controller.go","code":"// pastBackoffLimitOnFailure checks if container restartCounts sum exceeds BackoffLimit\n// this method applies only to pods with restartPolicy == OnFailure\nfunc pastBackoffLimitOnFailure(job *batch.Job, pods []*v1.Pod) bool {\n\tif job.Spec.Template.Spec.RestartPolicy != v1.RestartPolicyOnFailure {\n\t\treturn false\n\t}\n\tresult := int32(0)\n\tfor i := range pods {\n\t\tpo := pods[i]\n\t\tif po.Status.Phase == v1.PodRunning || po.Status.Phase == v1.PodPending {\n\t\t\tfor j := range po.Status.InitContainerStatuses {\n\t\t\t\tstat := po.Status.InitContainerStatuses[j]\n\t\t\t\tresult += stat.RestartCount\n\t\t\t}\n\t\t\tfor j := range po.Status.ContainerStatuses {\n\t\t\t\tstat := po.Status.ContainerStatuses[j]\n\t\t\t\tresult += stat.RestartCount\n\t\t\t}\n\t\t}\n\t}\n\tif *job.Spec.BackoffLimit == 0 {\n\t\treturn result \u003e 0\n\t}\n\treturn result \u003e= *job.Spec.BackoffLimit\n}","line":{"from":1271,"to":1295}} {"id":100004051,"name":"pastActiveDeadline","signature":"func (jm *Controller) pastActiveDeadline(job *batch.Job) bool","file":"pkg/controller/job/job_controller.go","code":"// pastActiveDeadline checks if job has ActiveDeadlineSeconds field set and if\n// it is exceeded. If the job is currently suspended, the function will always\n// return false.\nfunc (jm *Controller) pastActiveDeadline(job *batch.Job) bool {\n\tif job.Spec.ActiveDeadlineSeconds == nil || job.Status.StartTime == nil || jobSuspended(job) {\n\t\treturn false\n\t}\n\tduration := jm.clock.Since(job.Status.StartTime.Time)\n\tallowedDuration := time.Duration(*job.Spec.ActiveDeadlineSeconds) * time.Second\n\treturn duration \u003e= allowedDuration\n}","line":{"from":1297,"to":1307}} {"id":100004052,"name":"newCondition","signature":"func newCondition(conditionType batch.JobConditionType, status v1.ConditionStatus, reason, message string, now time.Time) *batch.JobCondition","file":"pkg/controller/job/job_controller.go","code":"func newCondition(conditionType batch.JobConditionType, status v1.ConditionStatus, reason, message string, now time.Time) *batch.JobCondition {\n\treturn \u0026batch.JobCondition{\n\t\tType: conditionType,\n\t\tStatus: status,\n\t\tLastProbeTime: metav1.NewTime(now),\n\t\tLastTransitionTime: metav1.NewTime(now),\n\t\tReason: reason,\n\t\tMessage: message,\n\t}\n}","line":{"from":1309,"to":1318}} {"id":100004053,"name":"getFailJobMessage","signature":"func getFailJobMessage(job *batch.Job, pods []*v1.Pod, uncounted sets.String) *string","file":"pkg/controller/job/job_controller.go","code":"// getFailJobMessage returns a job failure message if the job should fail with the current counters\nfunc getFailJobMessage(job *batch.Job, pods []*v1.Pod, uncounted sets.String) *string {\n\tif !feature.DefaultFeatureGate.Enabled(features.JobPodFailurePolicy) || job.Spec.PodFailurePolicy == nil {\n\t\treturn nil\n\t}\n\tfor _, p := range pods {\n\t\tif isPodFailed(p, job) {\n\t\t\tjobFailureMessage, _, _ := matchPodFailurePolicy(job.Spec.PodFailurePolicy, p)\n\t\t\tif jobFailureMessage != nil {\n\t\t\t\treturn jobFailureMessage\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":1320,"to":1334}} {"id":100004054,"name":"getNewFinishedPods","signature":"func getNewFinishedPods(job *batch.Job, pods []*v1.Pod, uncounted *uncountedTerminatedPods, expectedRmFinalizers sets.String) (succeededPods, failedPods []*v1.Pod)","file":"pkg/controller/job/job_controller.go","code":"// getNewFinishedPods returns the list of newly succeeded and failed pods that are not accounted\n// in the job status. The list of failed pods can be affected by the podFailurePolicy.\nfunc getNewFinishedPods(job *batch.Job, pods []*v1.Pod, uncounted *uncountedTerminatedPods, expectedRmFinalizers sets.String) (succeededPods, failedPods []*v1.Pod) {\n\tsucceededPods = getValidPodsWithFilter(job, pods, uncounted.Succeeded(), expectedRmFinalizers, func(p *v1.Pod) bool {\n\t\treturn p.Status.Phase == v1.PodSucceeded\n\t})\n\tfailedPods = getValidPodsWithFilter(job, pods, uncounted.Failed(), expectedRmFinalizers, func(p *v1.Pod) bool {\n\t\tif feature.DefaultFeatureGate.Enabled(features.JobPodFailurePolicy) \u0026\u0026 job.Spec.PodFailurePolicy != nil {\n\t\t\tif !isPodFailed(p, job) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\t_, countFailed, _ := matchPodFailurePolicy(job.Spec.PodFailurePolicy, p)\n\t\t\treturn countFailed\n\t\t} else {\n\t\t\treturn isPodFailed(p, job)\n\t\t}\n\t})\n\treturn succeededPods, failedPods\n}","line":{"from":1336,"to":1354}} {"id":100004055,"name":"jobSuspended","signature":"func jobSuspended(job *batch.Job) bool","file":"pkg/controller/job/job_controller.go","code":"// jobSuspended returns whether a Job is suspended while taking the feature\n// gate into account.\nfunc jobSuspended(job *batch.Job) bool {\n\treturn job.Spec.Suspend != nil \u0026\u0026 *job.Spec.Suspend\n}","line":{"from":1356,"to":1360}} {"id":100004056,"name":"manageJob","signature":"func (jm *Controller) manageJob(ctx context.Context, job *batch.Job, activePods []*v1.Pod, succeeded int32, succeededIndexes []interval, backoff backoffRecord) (int32, string, error)","file":"pkg/controller/job/job_controller.go","code":"// manageJob is the core method responsible for managing the number of running\n// pods according to what is specified in the job.Spec.\n// Respects back-off; does not create new pods if the back-off time has not passed\n// Does NOT modify \u003cactivePods\u003e.\nfunc (jm *Controller) manageJob(ctx context.Context, job *batch.Job, activePods []*v1.Pod, succeeded int32, succeededIndexes []interval, backoff backoffRecord) (int32, string, error) {\n\tactive := int32(len(activePods))\n\tparallelism := *job.Spec.Parallelism\n\tjobKey, err := controller.KeyFunc(job)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Couldn't get key for job %#v: %v\", job, err))\n\t\treturn 0, metrics.JobSyncActionTracking, nil\n\t}\n\n\tif jobSuspended(job) {\n\t\tklog.V(4).InfoS(\"Deleting all active pods in suspended job\", \"job\", klog.KObj(job), \"active\", active)\n\t\tpodsToDelete := activePodsForRemoval(job, activePods, int(active))\n\t\tjm.expectations.ExpectDeletions(jobKey, len(podsToDelete))\n\t\tremoved, err := jm.deleteJobPods(ctx, job, jobKey, podsToDelete)\n\t\tactive -= removed\n\t\treturn active, metrics.JobSyncActionPodsDeleted, err\n\t}\n\n\twantActive := int32(0)\n\tif job.Spec.Completions == nil {\n\t\t// Job does not specify a number of completions. Therefore, number active\n\t\t// should be equal to parallelism, unless the job has seen at least\n\t\t// once success, in which leave whatever is running, running.\n\t\tif succeeded \u003e 0 {\n\t\t\twantActive = active\n\t\t} else {\n\t\t\twantActive = parallelism\n\t\t}\n\t} else {\n\t\t// Job specifies a specific number of completions. Therefore, number\n\t\t// active should not ever exceed number of remaining completions.\n\t\twantActive = *job.Spec.Completions - succeeded\n\t\tif wantActive \u003e parallelism {\n\t\t\twantActive = parallelism\n\t\t}\n\t\tif wantActive \u003c 0 {\n\t\t\twantActive = 0\n\t\t}\n\t}\n\n\trmAtLeast := active - wantActive\n\tif rmAtLeast \u003c 0 {\n\t\trmAtLeast = 0\n\t}\n\tpodsToDelete := activePodsForRemoval(job, activePods, int(rmAtLeast))\n\tif len(podsToDelete) \u003e MaxPodCreateDeletePerSync {\n\t\tpodsToDelete = podsToDelete[:MaxPodCreateDeletePerSync]\n\t}\n\tif len(podsToDelete) \u003e 0 {\n\t\tjm.expectations.ExpectDeletions(jobKey, len(podsToDelete))\n\t\tklog.V(4).InfoS(\"Too many pods running for job\", \"job\", klog.KObj(job), \"deleted\", len(podsToDelete), \"target\", wantActive)\n\t\tremoved, err := jm.deleteJobPods(ctx, job, jobKey, podsToDelete)\n\t\tactive -= removed\n\t\t// While it is possible for a Job to require both pod creations and\n\t\t// deletions at the same time (e.g. indexed Jobs with repeated indexes), we\n\t\t// restrict ourselves to either just pod deletion or pod creation in any\n\t\t// given sync cycle. Of these two, pod deletion takes precedence.\n\t\treturn active, metrics.JobSyncActionPodsDeleted, err\n\t}\n\n\tif active \u003c wantActive {\n\t\tremainingTime := backoff.getRemainingTime(jm.clock, DefaultJobBackOff, MaxJobBackOff)\n\t\tif remainingTime \u003e 0 {\n\t\t\tjm.enqueueControllerDelayed(job, true, remainingTime)\n\t\t\treturn 0, metrics.JobSyncActionPodsCreated, nil\n\t\t}\n\t\tdiff := wantActive - active\n\t\tif diff \u003e int32(MaxPodCreateDeletePerSync) {\n\t\t\tdiff = int32(MaxPodCreateDeletePerSync)\n\t\t}\n\n\t\tjm.expectations.ExpectCreations(jobKey, int(diff))\n\t\terrCh := make(chan error, diff)\n\t\tklog.V(4).Infof(\"Too few pods running job %q, need %d, creating %d\", jobKey, wantActive, diff)\n\n\t\twait := sync.WaitGroup{}\n\n\t\tvar indexesToAdd []int\n\t\tif isIndexedJob(job) {\n\t\t\tindexesToAdd = firstPendingIndexes(activePods, succeededIndexes, int(diff), int(*job.Spec.Completions))\n\t\t\tdiff = int32(len(indexesToAdd))\n\t\t}\n\t\tactive += diff\n\n\t\tpodTemplate := job.Spec.Template.DeepCopy()\n\t\tif isIndexedJob(job) {\n\t\t\taddCompletionIndexEnvVariables(podTemplate)\n\t\t}\n\t\tpodTemplate.Finalizers = appendJobCompletionFinalizerIfNotFound(podTemplate.Finalizers)\n\n\t\t// Batch the pod creates. Batch sizes start at SlowStartInitialBatchSize\n\t\t// and double with each successful iteration in a kind of \"slow start\".\n\t\t// This handles attempts to start large numbers of pods that would\n\t\t// likely all fail with the same error. For example a project with a\n\t\t// low quota that attempts to create a large number of pods will be\n\t\t// prevented from spamming the API service with the pod create requests\n\t\t// after one of its pods fails. Conveniently, this also prevents the\n\t\t// event spam that those failures would generate.\n\t\tfor batchSize := int32(integer.IntMin(int(diff), controller.SlowStartInitialBatchSize)); diff \u003e 0; batchSize = integer.Int32Min(2*batchSize, diff) {\n\t\t\terrorCount := len(errCh)\n\t\t\twait.Add(int(batchSize))\n\t\t\tfor i := int32(0); i \u003c batchSize; i++ {\n\t\t\t\tcompletionIndex := unknownCompletionIndex\n\t\t\t\tif len(indexesToAdd) \u003e 0 {\n\t\t\t\t\tcompletionIndex = indexesToAdd[0]\n\t\t\t\t\tindexesToAdd = indexesToAdd[1:]\n\t\t\t\t}\n\t\t\t\tgo func() {\n\t\t\t\t\ttemplate := podTemplate\n\t\t\t\t\tgenerateName := \"\"\n\t\t\t\t\tif completionIndex != unknownCompletionIndex {\n\t\t\t\t\t\ttemplate = podTemplate.DeepCopy()\n\t\t\t\t\t\taddCompletionIndexAnnotation(template, completionIndex)\n\t\t\t\t\t\ttemplate.Spec.Hostname = fmt.Sprintf(\"%s-%d\", job.Name, completionIndex)\n\t\t\t\t\t\tgenerateName = podGenerateNameWithIndex(job.Name, completionIndex)\n\t\t\t\t\t}\n\t\t\t\t\tdefer wait.Done()\n\t\t\t\t\terr := jm.podControl.CreatePodsWithGenerateName(ctx, job.Namespace, template, job, metav1.NewControllerRef(job, controllerKind), generateName)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tif apierrors.HasStatusCause(err, v1.NamespaceTerminatingCause) {\n\t\t\t\t\t\t\t// If the namespace is being torn down, we can safely ignore\n\t\t\t\t\t\t\t// this error since all subsequent creations will fail.\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tdefer utilruntime.HandleError(err)\n\t\t\t\t\t\t// Decrement the expected number of creates because the informer won't observe this pod\n\t\t\t\t\t\tklog.V(2).Infof(\"Failed creation, decrementing expectations for job %q/%q\", job.Namespace, job.Name)\n\t\t\t\t\t\tjm.expectations.CreationObserved(jobKey)\n\t\t\t\t\t\tatomic.AddInt32(\u0026active, -1)\n\t\t\t\t\t\terrCh \u003c- err\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t}\n\t\t\twait.Wait()\n\t\t\t// any skipped pods that we never attempted to start shouldn't be expected.\n\t\t\tskippedPods := diff - batchSize\n\t\t\tif errorCount \u003c len(errCh) \u0026\u0026 skippedPods \u003e 0 {\n\t\t\t\tklog.V(2).Infof(\"Slow-start failure. Skipping creation of %d pods, decrementing expectations for job %q/%q\", skippedPods, job.Namespace, job.Name)\n\t\t\t\tactive -= skippedPods\n\t\t\t\tfor i := int32(0); i \u003c skippedPods; i++ {\n\t\t\t\t\t// Decrement the expected number of creates because the informer won't observe this pod\n\t\t\t\t\tjm.expectations.CreationObserved(jobKey)\n\t\t\t\t}\n\t\t\t\t// The skipped pods will be retried later. The next controller resync will\n\t\t\t\t// retry the slow start process.\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tdiff -= batchSize\n\t\t}\n\t\treturn active, metrics.JobSyncActionPodsCreated, errorFromChannel(errCh)\n\t}\n\n\treturn active, metrics.JobSyncActionTracking, nil\n}","line":{"from":1362,"to":1521}} {"id":100004057,"name":"activePodsForRemoval","signature":"func activePodsForRemoval(job *batch.Job, pods []*v1.Pod, rmAtLeast int) []*v1.Pod","file":"pkg/controller/job/job_controller.go","code":"// activePodsForRemoval returns Pods that should be removed because there\n// are too many pods running or, if this is an indexed job, there are repeated\n// indexes or invalid indexes or some pods don't have indexes.\n// Sorts candidate pods in the order such that not-ready \u003c ready, unscheduled\n// \u003c scheduled, and pending \u003c running. This ensures that we delete pods\n// in the earlier stages whenever possible.\nfunc activePodsForRemoval(job *batch.Job, pods []*v1.Pod, rmAtLeast int) []*v1.Pod {\n\tvar rm, left []*v1.Pod\n\n\tif isIndexedJob(job) {\n\t\trm = make([]*v1.Pod, 0, rmAtLeast)\n\t\tleft = make([]*v1.Pod, 0, len(pods)-rmAtLeast)\n\t\trm, left = appendDuplicatedIndexPodsForRemoval(rm, left, pods, int(*job.Spec.Completions))\n\t} else {\n\t\tleft = pods\n\t}\n\n\tif len(rm) \u003c rmAtLeast {\n\t\tsort.Sort(controller.ActivePods(left))\n\t\trm = append(rm, left[:rmAtLeast-len(rm)]...)\n\t}\n\treturn rm\n}","line":{"from":1523,"to":1545}} {"id":100004058,"name":"updateJobStatus","signature":"func (jm *Controller) updateJobStatus(ctx context.Context, job *batch.Job) (*batch.Job, error)","file":"pkg/controller/job/job_controller.go","code":"// updateJobStatus calls the API to update the job status.\nfunc (jm *Controller) updateJobStatus(ctx context.Context, job *batch.Job) (*batch.Job, error) {\n\treturn jm.kubeClient.BatchV1().Jobs(job.Namespace).UpdateStatus(ctx, job, metav1.UpdateOptions{})\n}","line":{"from":1547,"to":1550}} {"id":100004059,"name":"patchJob","signature":"func (jm *Controller) patchJob(ctx context.Context, job *batch.Job, data []byte) error","file":"pkg/controller/job/job_controller.go","code":"func (jm *Controller) patchJob(ctx context.Context, job *batch.Job, data []byte) error {\n\t_, err := jm.kubeClient.BatchV1().Jobs(job.Namespace).Patch(\n\t\tctx, job.Name, types.StrategicMergePatchType, data, metav1.PatchOptions{})\n\treturn err\n}","line":{"from":1552,"to":1556}} {"id":100004060,"name":"getBackoff","signature":"func getBackoff(queue workqueue.RateLimitingInterface, key interface{}) time.Duration","file":"pkg/controller/job/job_controller.go","code":"func getBackoff(queue workqueue.RateLimitingInterface, key interface{}) time.Duration {\n\texp := queue.NumRequeues(key)\n\n\tif exp \u003c= 0 {\n\t\treturn time.Duration(0)\n\t}\n\n\t// The backoff is capped such that 'calculated' value never overflows.\n\tbackoff := float64(DefaultJobBackOff.Nanoseconds()) * math.Pow(2, float64(exp-1))\n\tif backoff \u003e math.MaxInt64 {\n\t\treturn MaxJobBackOff\n\t}\n\n\tcalculated := time.Duration(backoff)\n\tif calculated \u003e MaxJobBackOff {\n\t\treturn MaxJobBackOff\n\t}\n\treturn calculated\n}","line":{"from":1558,"to":1576}} {"id":100004061,"name":"getValidPodsWithFilter","signature":"func getValidPodsWithFilter(job *batch.Job, pods []*v1.Pod, uncounted sets.String, expectedRmFinalizers sets.String, filter func(*v1.Pod) bool) []*v1.Pod","file":"pkg/controller/job/job_controller.go","code":"// getValidPodsWithFilter returns the valid pods that pass the filter.\n// Pods are valid if they have a finalizer or in uncounted set\n// and, for Indexed Jobs, a valid completion index.\nfunc getValidPodsWithFilter(job *batch.Job, pods []*v1.Pod, uncounted sets.String, expectedRmFinalizers sets.String, filter func(*v1.Pod) bool) []*v1.Pod {\n\tvar result []*v1.Pod\n\tfor _, p := range pods {\n\t\tuid := string(p.UID)\n\n\t\t// Pods that don't have a completion finalizer are in the uncounted set or\n\t\t// have already been accounted for in the Job status.\n\t\tif !hasJobTrackingFinalizer(p) || uncounted.Has(uid) || expectedRmFinalizers.Has(uid) {\n\t\t\tcontinue\n\t\t}\n\t\tif isIndexedJob(job) {\n\t\t\tidx := getCompletionIndex(p.Annotations)\n\t\t\tif idx == unknownCompletionIndex || idx \u003e= int(*job.Spec.Completions) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif filter(p) {\n\t\t\tresult = append(result, p)\n\t\t}\n\t}\n\treturn result\n}","line":{"from":1578,"to":1602}} {"id":100004062,"name":"getCompletionMode","signature":"func getCompletionMode(job *batch.Job) string","file":"pkg/controller/job/job_controller.go","code":"// getCompletionMode returns string representation of the completion mode. Used as a label value for metrics.\nfunc getCompletionMode(job *batch.Job) string {\n\tif isIndexedJob(job) {\n\t\treturn string(batch.IndexedCompletion)\n\t}\n\treturn string(batch.NonIndexedCompletion)\n}","line":{"from":1604,"to":1610}} {"id":100004063,"name":"appendJobCompletionFinalizerIfNotFound","signature":"func appendJobCompletionFinalizerIfNotFound(finalizers []string) []string","file":"pkg/controller/job/job_controller.go","code":"func appendJobCompletionFinalizerIfNotFound(finalizers []string) []string {\n\tfor _, fin := range finalizers {\n\t\tif fin == batch.JobTrackingFinalizer {\n\t\t\treturn finalizers\n\t\t}\n\t}\n\treturn append(finalizers, batch.JobTrackingFinalizer)\n}","line":{"from":1612,"to":1619}} {"id":100004064,"name":"removeTrackingFinalizerPatch","signature":"func removeTrackingFinalizerPatch(pod *v1.Pod) []byte","file":"pkg/controller/job/job_controller.go","code":"func removeTrackingFinalizerPatch(pod *v1.Pod) []byte {\n\tif !hasJobTrackingFinalizer(pod) {\n\t\treturn nil\n\t}\n\tpatch := map[string]interface{}{\n\t\t\"metadata\": map[string]interface{}{\n\t\t\t\"$deleteFromPrimitiveList/finalizers\": []string{batch.JobTrackingFinalizer},\n\t\t},\n\t}\n\tpatchBytes, _ := json.Marshal(patch)\n\treturn patchBytes\n}","line":{"from":1621,"to":1632}} {"id":100004065,"name":"newUncountedTerminatedPods","signature":"func newUncountedTerminatedPods(in batch.UncountedTerminatedPods) *uncountedTerminatedPods","file":"pkg/controller/job/job_controller.go","code":"func newUncountedTerminatedPods(in batch.UncountedTerminatedPods) *uncountedTerminatedPods {\n\tobj := uncountedTerminatedPods{\n\t\tsucceeded: make(sets.String, len(in.Succeeded)),\n\t\tfailed: make(sets.String, len(in.Failed)),\n\t}\n\tfor _, v := range in.Succeeded {\n\t\tobj.succeeded.Insert(string(v))\n\t}\n\tfor _, v := range in.Failed {\n\t\tobj.failed.Insert(string(v))\n\t}\n\treturn \u0026obj\n}","line":{"from":1639,"to":1651}} {"id":100004066,"name":"Succeeded","signature":"func (u *uncountedTerminatedPods) Succeeded() sets.String","file":"pkg/controller/job/job_controller.go","code":"func (u *uncountedTerminatedPods) Succeeded() sets.String {\n\tif u == nil {\n\t\treturn nil\n\t}\n\treturn u.succeeded\n}","line":{"from":1653,"to":1658}} {"id":100004067,"name":"Failed","signature":"func (u *uncountedTerminatedPods) Failed() sets.String","file":"pkg/controller/job/job_controller.go","code":"func (u *uncountedTerminatedPods) Failed() sets.String {\n\tif u == nil {\n\t\treturn nil\n\t}\n\treturn u.failed\n}","line":{"from":1660,"to":1665}} {"id":100004068,"name":"errorFromChannel","signature":"func errorFromChannel(errCh \u003c-chan error) error","file":"pkg/controller/job/job_controller.go","code":"func errorFromChannel(errCh \u003c-chan error) error {\n\tselect {\n\tcase err := \u003c-errCh:\n\t\treturn err\n\tdefault:\n\t}\n\treturn nil\n}","line":{"from":1667,"to":1674}} {"id":100004069,"name":"ensureJobConditionStatus","signature":"func ensureJobConditionStatus(list []batch.JobCondition, cType batch.JobConditionType, status v1.ConditionStatus, reason, message string, now time.Time) ([]batch.JobCondition, bool)","file":"pkg/controller/job/job_controller.go","code":"// ensureJobConditionStatus appends or updates an existing job condition of the\n// given type with the given status value. Note that this function will not\n// append to the conditions list if the new condition's status is false\n// (because going from nothing to false is meaningless); it can, however,\n// update the status condition to false. The function returns a bool to let the\n// caller know if the list was changed (either appended or updated).\nfunc ensureJobConditionStatus(list []batch.JobCondition, cType batch.JobConditionType, status v1.ConditionStatus, reason, message string, now time.Time) ([]batch.JobCondition, bool) {\n\tif condition := findConditionByType(list, cType); condition != nil {\n\t\tif condition.Status != status || condition.Reason != reason || condition.Message != message {\n\t\t\t*condition = *newCondition(cType, status, reason, message, now)\n\t\t\treturn list, true\n\t\t}\n\t\treturn list, false\n\t}\n\t// A condition with that type doesn't exist in the list.\n\tif status != v1.ConditionFalse {\n\t\treturn append(list, *newCondition(cType, status, reason, message, now)), true\n\t}\n\treturn list, false\n}","line":{"from":1676,"to":1695}} {"id":100004070,"name":"isPodFailed","signature":"func isPodFailed(p *v1.Pod, job *batch.Job) bool","file":"pkg/controller/job/job_controller.go","code":"func isPodFailed(p *v1.Pod, job *batch.Job) bool {\n\tif feature.DefaultFeatureGate.Enabled(features.PodDisruptionConditions) \u0026\u0026 feature.DefaultFeatureGate.Enabled(features.JobPodFailurePolicy) \u0026\u0026 job.Spec.PodFailurePolicy != nil {\n\t\t// When PodDisruptionConditions is enabled, orphan Pods and unschedulable\n\t\t// terminating Pods are marked as Failed. So we only need to check the phase.\n\t\t// TODO(#113855): Stop limiting this behavior to Jobs with podFailurePolicy.\n\t\t// For now, we do so to avoid affecting all running Jobs without the\n\t\t// avaibility to opt-out into the old behavior.\n\t\treturn p.Status.Phase == v1.PodFailed\n\t}\n\tif p.Status.Phase == v1.PodFailed {\n\t\treturn true\n\t}\n\t// Count deleted Pods as failures to account for orphan Pods that\n\t// never have a chance to reach the Failed phase.\n\treturn p.DeletionTimestamp != nil \u0026\u0026 p.Status.Phase != v1.PodSucceeded\n}","line":{"from":1697,"to":1712}} {"id":100004071,"name":"findConditionByType","signature":"func findConditionByType(list []batch.JobCondition, cType batch.JobConditionType) *batch.JobCondition","file":"pkg/controller/job/job_controller.go","code":"func findConditionByType(list []batch.JobCondition, cType batch.JobConditionType) *batch.JobCondition {\n\tfor i := range list {\n\t\tif list[i].Type == cType {\n\t\t\treturn \u0026list[i]\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":1714,"to":1721}} {"id":100004072,"name":"recordJobPodFinished","signature":"func recordJobPodFinished(job *batch.Job, oldCounters batch.JobStatus)","file":"pkg/controller/job/job_controller.go","code":"func recordJobPodFinished(job *batch.Job, oldCounters batch.JobStatus) {\n\tcompletionMode := completionModeStr(job)\n\tvar diff int\n\n\t// Updating succeeded metric must be handled differently\n\t// for Indexed Jobs to handle the case where the job has\n\t// been scaled down by reducing completions \u0026 parallelism\n\t// in tandem, and now a previously completed index is\n\t// now out of range (i.e. index \u003e= spec.Completions).\n\tif isIndexedJob(job) {\n\t\tif job.Status.CompletedIndexes != oldCounters.CompletedIndexes {\n\t\t\tdiff = succeededIndexesFromString(job.Status.CompletedIndexes, int(*job.Spec.Completions)).total() - succeededIndexesFromString(oldCounters.CompletedIndexes, int(*job.Spec.Completions)).total()\n\t\t}\n\t} else {\n\t\tdiff = int(job.Status.Succeeded) - int(oldCounters.Succeeded)\n\t}\n\tmetrics.JobPodsFinished.WithLabelValues(completionMode, metrics.Succeeded).Add(float64(diff))\n\n\t// Update failed metric.\n\tdiff = int(job.Status.Failed - oldCounters.Failed)\n\tmetrics.JobPodsFinished.WithLabelValues(completionMode, metrics.Failed).Add(float64(diff))\n}","line":{"from":1723,"to":1744}} {"id":100004073,"name":"recordJobPodFailurePolicyActions","signature":"func recordJobPodFailurePolicyActions(job *batch.Job, podFailureCountByPolicyAction map[string]int)","file":"pkg/controller/job/job_controller.go","code":"func recordJobPodFailurePolicyActions(job *batch.Job, podFailureCountByPolicyAction map[string]int) {\n\tfor action, count := range podFailureCountByPolicyAction {\n\t\tmetrics.PodFailuresHandledByFailurePolicy.WithLabelValues(action).Add(float64(count))\n\t}\n}","line":{"from":1746,"to":1750}} {"id":100004074,"name":"countReadyPods","signature":"func countReadyPods(pods []*v1.Pod) int32","file":"pkg/controller/job/job_controller.go","code":"func countReadyPods(pods []*v1.Pod) int32 {\n\tcnt := int32(0)\n\tfor _, p := range pods {\n\t\tif podutil.IsPodReady(p) {\n\t\t\tcnt++\n\t\t}\n\t}\n\treturn cnt\n}","line":{"from":1752,"to":1760}} {"id":100004075,"name":"equalReady","signature":"func equalReady(a, b *int32) bool","file":"pkg/controller/job/job_controller.go","code":"func equalReady(a, b *int32) bool {\n\tif a != nil \u0026\u0026 b != nil {\n\t\treturn *a == *b\n\t}\n\treturn a == b\n}","line":{"from":1762,"to":1767}} {"id":100004076,"name":"Register","signature":"func Register()","file":"pkg/controller/job/metrics/metrics.go","code":"// Register registers Job controller metrics.\nfunc Register() {\n\tregisterMetrics.Do(func() {\n\t\tlegacyregistry.MustRegister(JobSyncDurationSeconds)\n\t\tlegacyregistry.MustRegister(JobSyncNum)\n\t\tlegacyregistry.MustRegister(JobFinishedNum)\n\t\tlegacyregistry.MustRegister(JobPodsFinished)\n\t\tlegacyregistry.MustRegister(PodFailuresHandledByFailurePolicy)\n\t\tlegacyregistry.MustRegister(TerminatedPodsTrackingFinalizerTotal)\n\t})\n}","line":{"from":152,"to":162}} {"id":100004077,"name":"matchPodFailurePolicy","signature":"func matchPodFailurePolicy(podFailurePolicy *batch.PodFailurePolicy, failedPod *v1.Pod) (*string, bool, *batch.PodFailurePolicyAction)","file":"pkg/controller/job/pod_failure_policy.go","code":"// matchPodFailurePolicy returns information about matching a given failed pod\n// against the pod failure policy rules. The information is represented as an\n// optional job failure message (present in case the pod matched a 'FailJob'\n// rule), a boolean indicating if the failure should be counted towards\n// backoffLimit (it should not be counted if the pod matched an 'Ignore' rule),\n// and a pointer to the matched pod failure policy action.\nfunc matchPodFailurePolicy(podFailurePolicy *batch.PodFailurePolicy, failedPod *v1.Pod) (*string, bool, *batch.PodFailurePolicyAction) {\n\tif podFailurePolicy == nil {\n\t\treturn nil, true, nil\n\t}\n\tignore := batch.PodFailurePolicyActionIgnore\n\tfailJob := batch.PodFailurePolicyActionFailJob\n\tcount := batch.PodFailurePolicyActionCount\n\tfor index, podFailurePolicyRule := range podFailurePolicy.Rules {\n\t\tif podFailurePolicyRule.OnExitCodes != nil {\n\t\t\tif containerStatus := matchOnExitCodes(\u0026failedPod.Status, podFailurePolicyRule.OnExitCodes); containerStatus != nil {\n\t\t\t\tswitch podFailurePolicyRule.Action {\n\t\t\t\tcase batch.PodFailurePolicyActionIgnore:\n\t\t\t\t\treturn nil, false, \u0026ignore\n\t\t\t\tcase batch.PodFailurePolicyActionCount:\n\t\t\t\t\treturn nil, true, \u0026count\n\t\t\t\tcase batch.PodFailurePolicyActionFailJob:\n\t\t\t\t\tmsg := fmt.Sprintf(\"Container %s for pod %s/%s failed with exit code %v matching %v rule at index %d\",\n\t\t\t\t\t\tcontainerStatus.Name, failedPod.Namespace, failedPod.Name, containerStatus.State.Terminated.ExitCode, podFailurePolicyRule.Action, index)\n\t\t\t\t\treturn \u0026msg, true, \u0026failJob\n\t\t\t\t}\n\t\t\t}\n\t\t} else if podFailurePolicyRule.OnPodConditions != nil {\n\t\t\tif podCondition := matchOnPodConditions(\u0026failedPod.Status, podFailurePolicyRule.OnPodConditions); podCondition != nil {\n\t\t\t\tswitch podFailurePolicyRule.Action {\n\t\t\t\tcase batch.PodFailurePolicyActionIgnore:\n\t\t\t\t\treturn nil, false, \u0026ignore\n\t\t\t\tcase batch.PodFailurePolicyActionCount:\n\t\t\t\t\treturn nil, true, \u0026count\n\t\t\t\tcase batch.PodFailurePolicyActionFailJob:\n\t\t\t\t\tmsg := fmt.Sprintf(\"Pod %s/%s has condition %v matching %v rule at index %d\",\n\t\t\t\t\t\tfailedPod.Namespace, failedPod.Name, podCondition.Type, podFailurePolicyRule.Action, index)\n\t\t\t\t\treturn \u0026msg, true, \u0026failJob\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, true, nil\n}","line":{"from":26,"to":69}} {"id":100004078,"name":"matchOnExitCodes","signature":"func matchOnExitCodes(podStatus *v1.PodStatus, requirement *batch.PodFailurePolicyOnExitCodesRequirement) *v1.ContainerStatus","file":"pkg/controller/job/pod_failure_policy.go","code":"// matchOnExitCodes returns a terminated container status that matches the error code requirement, if any exists.\n// If the returned status is non-nil, it has a non-nil Terminated field.\nfunc matchOnExitCodes(podStatus *v1.PodStatus, requirement *batch.PodFailurePolicyOnExitCodesRequirement) *v1.ContainerStatus {\n\tif containerStatus := getMatchingContainerFromList(podStatus.ContainerStatuses, requirement); containerStatus != nil {\n\t\treturn containerStatus\n\t}\n\treturn getMatchingContainerFromList(podStatus.InitContainerStatuses, requirement)\n}","line":{"from":71,"to":78}} {"id":100004079,"name":"matchOnPodConditions","signature":"func matchOnPodConditions(podStatus *v1.PodStatus, requirement []batch.PodFailurePolicyOnPodConditionsPattern) *v1.PodCondition","file":"pkg/controller/job/pod_failure_policy.go","code":"func matchOnPodConditions(podStatus *v1.PodStatus, requirement []batch.PodFailurePolicyOnPodConditionsPattern) *v1.PodCondition {\n\tfor _, podCondition := range podStatus.Conditions {\n\t\tfor _, pattern := range requirement {\n\t\t\tif podCondition.Type == pattern.Type \u0026\u0026 podCondition.Status == pattern.Status {\n\t\t\t\treturn \u0026podCondition\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":80,"to":89}} {"id":100004080,"name":"getMatchingContainerFromList","signature":"func getMatchingContainerFromList(containerStatuses []v1.ContainerStatus, requirement *batch.PodFailurePolicyOnExitCodesRequirement) *v1.ContainerStatus","file":"pkg/controller/job/pod_failure_policy.go","code":"// getMatchingContainerFromList returns the first terminated container status in the list that matches the error code requirement, or nil if none match.\n// If the returned status is non-nil, it has a non-nil Terminated field\nfunc getMatchingContainerFromList(containerStatuses []v1.ContainerStatus, requirement *batch.PodFailurePolicyOnExitCodesRequirement) *v1.ContainerStatus {\n\tfor _, containerStatus := range containerStatuses {\n\t\tif containerStatus.State.Terminated == nil {\n\t\t\t// This container is still be terminating. There is no exit code to match.\n\t\t\tcontinue\n\t\t}\n\t\tif requirement.ContainerName == nil || *requirement.ContainerName == containerStatus.Name {\n\t\t\tif containerStatus.State.Terminated.ExitCode != 0 {\n\t\t\t\tif isOnExitCodesOperatorMatching(containerStatus.State.Terminated.ExitCode, requirement) {\n\t\t\t\t\treturn \u0026containerStatus\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":91,"to":108}} {"id":100004081,"name":"isOnExitCodesOperatorMatching","signature":"func isOnExitCodesOperatorMatching(exitCode int32, requirement *batch.PodFailurePolicyOnExitCodesRequirement) bool","file":"pkg/controller/job/pod_failure_policy.go","code":"func isOnExitCodesOperatorMatching(exitCode int32, requirement *batch.PodFailurePolicyOnExitCodesRequirement) bool {\n\tswitch requirement.Operator {\n\tcase batch.PodFailurePolicyOnExitCodesOpIn:\n\t\tfor _, value := range requirement.Values {\n\t\t\tif value == exitCode {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\tcase batch.PodFailurePolicyOnExitCodesOpNotIn:\n\t\tfor _, value := range requirement.Values {\n\t\t\tif value == exitCode {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":110,"to":129}} {"id":100004082,"name":"getSet","signature":"func (u *uidTrackingExpectations) getSet(controllerKey string) *uidSet","file":"pkg/controller/job/tracking_utils.go","code":"// GetUIDs is a convenience method to avoid exposing the set of expected uids.\n// The returned set is not thread safe, all modifications must be made holding\n// the uidStoreLock.\nfunc (u *uidTrackingExpectations) getSet(controllerKey string) *uidSet {\n\tif obj, exists, err := u.store.GetByKey(controllerKey); err == nil \u0026\u0026 exists {\n\t\treturn obj.(*uidSet)\n\t}\n\treturn nil\n}","line":{"from":53,"to":61}} {"id":100004083,"name":"getExpectedUIDs","signature":"func (u *uidTrackingExpectations) getExpectedUIDs(controllerKey string) sets.String","file":"pkg/controller/job/tracking_utils.go","code":"func (u *uidTrackingExpectations) getExpectedUIDs(controllerKey string) sets.String {\n\tuids := u.getSet(controllerKey)\n\tif uids == nil {\n\t\treturn nil\n\t}\n\tuids.RLock()\n\tset := uids.set.Clone()\n\tuids.RUnlock()\n\treturn set\n}","line":{"from":63,"to":72}} {"id":100004084,"name":"expectFinalizersRemoved","signature":"func (u *uidTrackingExpectations) expectFinalizersRemoved(jobKey string, deletedKeys []string) error","file":"pkg/controller/job/tracking_utils.go","code":"// ExpectDeletions records expectations for the given deleteKeys, against the\n// given job-key.\n// This is thread-safe across different job keys.\nfunc (u *uidTrackingExpectations) expectFinalizersRemoved(jobKey string, deletedKeys []string) error {\n\tklog.V(4).InfoS(\"Expecting tracking finalizers removed\", \"job\", jobKey, \"podUIDs\", deletedKeys)\n\n\tuids := u.getSet(jobKey)\n\tif uids == nil {\n\t\tuids = \u0026uidSet{\n\t\t\tkey: jobKey,\n\t\t\tset: sets.NewString(),\n\t\t}\n\t\tif err := u.store.Add(uids); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tuids.Lock()\n\tuids.set.Insert(deletedKeys...)\n\tuids.Unlock()\n\treturn nil\n}","line":{"from":74,"to":94}} {"id":100004085,"name":"finalizerRemovalObserved","signature":"func (u *uidTrackingExpectations) finalizerRemovalObserved(jobKey, deleteKey string)","file":"pkg/controller/job/tracking_utils.go","code":"// FinalizerRemovalObserved records the given deleteKey as a deletion, for the given job.\nfunc (u *uidTrackingExpectations) finalizerRemovalObserved(jobKey, deleteKey string) {\n\tuids := u.getSet(jobKey)\n\tif uids != nil {\n\t\tuids.Lock()\n\t\tif uids.set.Has(deleteKey) {\n\t\t\tklog.V(4).InfoS(\"Observed tracking finalizer removed\", \"job\", jobKey, \"podUID\", deleteKey)\n\t\t\tuids.set.Delete(deleteKey)\n\t\t}\n\t\tuids.Unlock()\n\t}\n}","line":{"from":96,"to":107}} {"id":100004086,"name":"deleteExpectations","signature":"func (u *uidTrackingExpectations) deleteExpectations(jobKey string)","file":"pkg/controller/job/tracking_utils.go","code":"// DeleteExpectations deletes the UID set.\nfunc (u *uidTrackingExpectations) deleteExpectations(jobKey string) {\n\tset := u.getSet(jobKey)\n\tif set != nil {\n\t\tif err := u.store.Delete(set); err != nil {\n\t\t\tklog.ErrorS(err, \"Could not delete tracking annotation UID expectations\", \"job\", jobKey)\n\t\t}\n\t}\n}","line":{"from":109,"to":117}} {"id":100004087,"name":"newUIDTrackingExpectations","signature":"func newUIDTrackingExpectations() *uidTrackingExpectations","file":"pkg/controller/job/tracking_utils.go","code":"// NewUIDTrackingControllerExpectations returns a wrapper around\n// ControllerExpectations that is aware of deleteKeys.\nfunc newUIDTrackingExpectations() *uidTrackingExpectations {\n\treturn \u0026uidTrackingExpectations{store: cache.NewStore(uidSetKeyFunc)}\n}","line":{"from":119,"to":123}} {"id":100004088,"name":"hasJobTrackingFinalizer","signature":"func hasJobTrackingFinalizer(pod *v1.Pod) bool","file":"pkg/controller/job/tracking_utils.go","code":"func hasJobTrackingFinalizer(pod *v1.Pod) bool {\n\tfor _, fin := range pod.Finalizers {\n\t\tif fin == batch.JobTrackingFinalizer {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":125,"to":132}} {"id":100004089,"name":"recordFinishedPodWithTrackingFinalizer","signature":"func recordFinishedPodWithTrackingFinalizer(oldPod, newPod *v1.Pod)","file":"pkg/controller/job/tracking_utils.go","code":"func recordFinishedPodWithTrackingFinalizer(oldPod, newPod *v1.Pod) {\n\twas := isFinishedPodWithTrackingFinalizer(oldPod)\n\tis := isFinishedPodWithTrackingFinalizer(newPod)\n\tif was == is {\n\t\treturn\n\t}\n\tvar event = metrics.Delete\n\tif is {\n\t\tevent = metrics.Add\n\t}\n\tmetrics.TerminatedPodsTrackingFinalizerTotal.WithLabelValues(event).Inc()\n}","line":{"from":134,"to":145}} {"id":100004090,"name":"isFinishedPodWithTrackingFinalizer","signature":"func isFinishedPodWithTrackingFinalizer(pod *v1.Pod) bool","file":"pkg/controller/job/tracking_utils.go","code":"func isFinishedPodWithTrackingFinalizer(pod *v1.Pod) bool {\n\tif pod == nil {\n\t\treturn false\n\t}\n\treturn (pod.Status.Phase == v1.PodFailed || pod.Status.Phase == v1.PodSucceeded) \u0026\u0026 hasJobTrackingFinalizer(pod)\n}","line":{"from":147,"to":152}} {"id":100004091,"name":"IsJobFinished","signature":"func IsJobFinished(j *batch.Job) bool","file":"pkg/controller/job/utils.go","code":"// IsJobFinished checks whether the given Job has finished execution.\n// It does not discriminate between successful and failed terminations.\nfunc IsJobFinished(j *batch.Job) bool {\n\tfor _, c := range j.Status.Conditions {\n\t\tif (c.Type == batch.JobComplete || c.Type == batch.JobFailed) \u0026\u0026 c.Status == v1.ConditionTrue {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":24,"to":33}} {"id":100004092,"name":"keyFunc","signature":"func keyFunc(obj objectWithMeta) uint64","file":"pkg/controller/lookup_cache.go","code":"// keyFunc returns the key of an object, which is used to look up in the cache for it's matching object.\n// Since we match objects by namespace and Labels/Selector, so if two objects have the same namespace and labels,\n// they will have the same key.\nfunc keyFunc(obj objectWithMeta) uint64 {\n\thash := fnv.New32a()\n\thashutil.DeepHashObject(hash, \u0026equivalenceLabelObj{\n\t\tnamespace: obj.GetNamespace(),\n\t\tlabels: obj.GetLabels(),\n\t})\n\treturn uint64(hash.Sum32())\n}","line":{"from":32,"to":42}} {"id":100004093,"name":"NewMatchingCache","signature":"func NewMatchingCache(maxCacheEntries int) *MatchingCache","file":"pkg/controller/lookup_cache.go","code":"// NewMatchingCache return a NewMatchingCache, which save label and selector matching relationship.\nfunc NewMatchingCache(maxCacheEntries int) *MatchingCache {\n\treturn \u0026MatchingCache{\n\t\tcache: lru.New(maxCacheEntries),\n\t}\n}","line":{"from":55,"to":60}} {"id":100004094,"name":"Add","signature":"func (c *MatchingCache) Add(labelObj objectWithMeta, selectorObj objectWithMeta)","file":"pkg/controller/lookup_cache.go","code":"// Add will add matching information to the cache.\nfunc (c *MatchingCache) Add(labelObj objectWithMeta, selectorObj objectWithMeta) {\n\tkey := keyFunc(labelObj)\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tc.cache.Add(key, selectorObj)\n}","line":{"from":62,"to":68}} {"id":100004095,"name":"GetMatchingObject","signature":"func (c *MatchingCache) GetMatchingObject(labelObj objectWithMeta) (controller interface{}, exists bool)","file":"pkg/controller/lookup_cache.go","code":"// GetMatchingObject lookup the matching object for a given object.\n// Note: the cache information may be invalid since the controller may be deleted or updated,\n// we need check in the external request to ensure the cache data is not dirty.\nfunc (c *MatchingCache) GetMatchingObject(labelObj objectWithMeta) (controller interface{}, exists bool) {\n\tkey := keyFunc(labelObj)\n\t// NOTE: we use Lock() instead of RLock() here because lru's Get() method also modifies state(\n\t// it need update the least recently usage information). So we can not call it concurrently.\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\treturn c.cache.Get(key)\n}","line":{"from":70,"to":80}} {"id":100004096,"name":"Update","signature":"func (c *MatchingCache) Update(labelObj objectWithMeta, selectorObj objectWithMeta)","file":"pkg/controller/lookup_cache.go","code":"// Update update the cached matching information.\nfunc (c *MatchingCache) Update(labelObj objectWithMeta, selectorObj objectWithMeta) {\n\tc.Add(labelObj, selectorObj)\n}","line":{"from":82,"to":85}} {"id":100004097,"name":"InvalidateAll","signature":"func (c *MatchingCache) InvalidateAll()","file":"pkg/controller/lookup_cache.go","code":"// InvalidateAll invalidate the whole cache.\nfunc (c *MatchingCache) InvalidateAll() {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tc.cache = lru.New(c.cache.MaxEntries)\n}","line":{"from":87,"to":92}} {"id":100004098,"name":"Convert_v1alpha1_NamespaceControllerConfiguration_To_config_NamespaceControllerConfiguration","signature":"func Convert_v1alpha1_NamespaceControllerConfiguration_To_config_NamespaceControllerConfiguration(in *v1alpha1.NamespaceControllerConfiguration, out *config.NamespaceControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/namespace/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_NamespaceControllerConfiguration_To_config_NamespaceControllerConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_NamespaceControllerConfiguration_To_config_NamespaceControllerConfiguration(in *v1alpha1.NamespaceControllerConfiguration, out *config.NamespaceControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_NamespaceControllerConfiguration_To_config_NamespaceControllerConfiguration(in, out, s)\n}","line":{"from":32,"to":35}} {"id":100004099,"name":"Convert_config_NamespaceControllerConfiguration_To_v1alpha1_NamespaceControllerConfiguration","signature":"func Convert_config_NamespaceControllerConfiguration_To_v1alpha1_NamespaceControllerConfiguration(in *config.NamespaceControllerConfiguration, out *v1alpha1.NamespaceControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/namespace/config/v1alpha1/conversion.go","code":"// Convert_config_NamespaceControllerConfiguration_To_v1alpha1_NamespaceControllerConfiguration is an autogenerated conversion function.\nfunc Convert_config_NamespaceControllerConfiguration_To_v1alpha1_NamespaceControllerConfiguration(in *config.NamespaceControllerConfiguration, out *v1alpha1.NamespaceControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_NamespaceControllerConfiguration_To_v1alpha1_NamespaceControllerConfiguration(in, out, s)\n}","line":{"from":37,"to":40}} {"id":100004100,"name":"RecommendedDefaultNamespaceControllerConfiguration","signature":"func RecommendedDefaultNamespaceControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.NamespaceControllerConfiguration)","file":"pkg/controller/namespace/config/v1alpha1/defaults.go","code":"// RecommendedDefaultNamespaceControllerConfiguration defaults a pointer to a\n// NamespaceControllerConfiguration struct. This will set the recommended default\n// values, but they may be subject to change between API versions. This function\n// is intentionally not registered in the scheme as a \"normal\" `SetDefaults_Foo`\n// function to allow consumers of this type to set whatever defaults for their\n// embedded configs. Forcing consumers to use these defaults would be problematic\n// as defaulting in the scheme is done as part of the conversion, and there would\n// be no easy way to opt-out. Instead, if you want to use this defaulting method\n// run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDefaultNamespaceControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.NamespaceControllerConfiguration) {\n\tzero := metav1.Duration{}\n\tif obj.ConcurrentNamespaceSyncs == 0 {\n\t\tobj.ConcurrentNamespaceSyncs = 10\n\t}\n\tif obj.NamespaceSyncPeriod == zero {\n\t\tobj.NamespaceSyncPeriod = metav1.Duration{Duration: 5 * time.Minute}\n\t}\n}","line":{"from":26,"to":43}} {"id":100004101,"name":"NewNamespacedResourcesDeleter","signature":"func NewNamespacedResourcesDeleter(ctx context.Context, nsClient v1clientset.NamespaceInterface,","file":"pkg/controller/namespace/deletion/namespaced_resources_deleter.go","code":"// NewNamespacedResourcesDeleter returns a new NamespacedResourcesDeleter.\nfunc NewNamespacedResourcesDeleter(ctx context.Context, nsClient v1clientset.NamespaceInterface,\n\tmetadataClient metadata.Interface, podsGetter v1clientset.PodsGetter,\n\tdiscoverResourcesFn func() ([]*metav1.APIResourceList, error),\n\tfinalizerToken v1.FinalizerName) NamespacedResourcesDeleterInterface {\n\td := \u0026namespacedResourcesDeleter{\n\t\tnsClient: nsClient,\n\t\tmetadataClient: metadataClient,\n\t\tpodsGetter: podsGetter,\n\t\topCache: \u0026operationNotSupportedCache{\n\t\t\tm: make(map[operationKey]bool),\n\t\t},\n\t\tdiscoverResourcesFn: discoverResourcesFn,\n\t\tfinalizerToken: finalizerToken,\n\t}\n\td.initOpCache(ctx)\n\treturn d\n}","line":{"from":45,"to":62}} {"id":100004102,"name":"Delete","signature":"func (d *namespacedResourcesDeleter) Delete(ctx context.Context, nsName string) error","file":"pkg/controller/namespace/deletion/namespaced_resources_deleter.go","code":"// Delete deletes all resources in the given namespace.\n// Before deleting resources:\n// - It ensures that deletion timestamp is set on the\n// namespace (does nothing if deletion timestamp is missing).\n// - Verifies that the namespace is in the \"terminating\" phase\n// (updates the namespace phase if it is not yet marked terminating)\n//\n// After deleting the resources:\n// * It removes finalizer token from the given namespace.\n//\n// Returns an error if any of those steps fail.\n// Returns ResourcesRemainingError if it deleted some resources but needs\n// to wait for them to go away.\n// Caller is expected to keep calling this until it succeeds.\nfunc (d *namespacedResourcesDeleter) Delete(ctx context.Context, nsName string) error {\n\t// Multiple controllers may edit a namespace during termination\n\t// first get the latest state of the namespace before proceeding\n\t// if the namespace was deleted already, don't do anything\n\tnamespace, err := d.nsClient.Get(context.TODO(), nsName, metav1.GetOptions{})\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\tif namespace.DeletionTimestamp == nil {\n\t\treturn nil\n\t}\n\n\tklog.FromContext(ctx).V(5).Info(\"Namespace controller - syncNamespace\", \"namespace\", namespace.Name, \"finalizerToken\", d.finalizerToken)\n\n\t// ensure that the status is up to date on the namespace\n\t// if we get a not found error, we assume the namespace is truly gone\n\tnamespace, err = d.retryOnConflictError(namespace, d.updateNamespaceStatusFunc)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\t// the latest view of the namespace asserts that namespace is no longer deleting..\n\tif namespace.DeletionTimestamp.IsZero() {\n\t\treturn nil\n\t}\n\n\t// return if it is already finalized.\n\tif finalized(namespace) {\n\t\treturn nil\n\t}\n\n\t// there may still be content for us to remove\n\testimate, err := d.deleteAllContent(ctx, namespace)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif estimate \u003e 0 {\n\t\treturn \u0026ResourcesRemainingError{estimate}\n\t}\n\n\t// we have removed content, so mark it finalized by us\n\t_, err = d.retryOnConflictError(namespace, d.finalizeNamespace)\n\tif err != nil {\n\t\t// in normal practice, this should not be possible, but if a deployment is running\n\t\t// two controllers to do namespace deletion that share a common finalizer token it's\n\t\t// possible that a not found could occur since the other controller would have finished the delete.\n\t\tif errors.IsNotFound(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":82,"to":154}} {"id":100004103,"name":"initOpCache","signature":"func (d *namespacedResourcesDeleter) initOpCache(ctx context.Context)","file":"pkg/controller/namespace/deletion/namespaced_resources_deleter.go","code":"func (d *namespacedResourcesDeleter) initOpCache(ctx context.Context) {\n\t// pre-fill opCache with the discovery info\n\t//\n\t// TODO(sttts): get rid of opCache and http 405 logic around it and trust discovery info\n\tresources, err := d.discoverResourcesFn()\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unable to get all supported resources from server: %v\", err))\n\t}\n\tlogger := klog.FromContext(ctx)\n\tif len(resources) == 0 {\n\t\tlogger.Error(err, \"Unable to get any supported resources from server\")\n\t\tklog.FlushAndExit(klog.ExitFlushTimeout, 1)\n\t}\n\n\tfor _, rl := range resources {\n\t\tgv, err := schema.ParseGroupVersion(rl.GroupVersion)\n\t\tif err != nil {\n\t\t\tlogger.Error(err, \"Failed to parse GroupVersion, skipping\", \"groupVersion\", rl.GroupVersion)\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, r := range rl.APIResources {\n\t\t\tgvr := schema.GroupVersionResource{Group: gv.Group, Version: gv.Version, Resource: r.Name}\n\t\t\tverbs := sets.NewString([]string(r.Verbs)...)\n\n\t\t\tif !verbs.Has(\"delete\") {\n\t\t\t\tlogger.V(6).Info(\"Skipping resource because it cannot be deleted\", \"resource\", gvr)\n\t\t\t}\n\n\t\t\tfor _, op := range []operation{operationList, operationDeleteCollection} {\n\t\t\t\tif !verbs.Has(string(op)) {\n\t\t\t\t\td.opCache.setNotSupported(operationKey{operation: op, gvr: gvr})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":156,"to":192}} {"id":100004104,"name":"Error","signature":"func (e *ResourcesRemainingError) Error() string","file":"pkg/controller/namespace/deletion/namespaced_resources_deleter.go","code":"func (e *ResourcesRemainingError) Error() string {\n\treturn fmt.Sprintf(\"some content remains in the namespace, estimate %d seconds before it is removed\", e.Estimate)\n}","line":{"from":199,"to":201}} {"id":100004105,"name":"isSupported","signature":"func (o *operationNotSupportedCache) isSupported(key operationKey) bool","file":"pkg/controller/namespace/deletion/namespaced_resources_deleter.go","code":"// isSupported returns true if the operation is supported\nfunc (o *operationNotSupportedCache) isSupported(key operationKey) bool {\n\to.lock.RLock()\n\tdefer o.lock.RUnlock()\n\treturn !o.m[key]\n}","line":{"from":226,"to":231}} {"id":100004106,"name":"setNotSupported","signature":"func (o *operationNotSupportedCache) setNotSupported(key operationKey)","file":"pkg/controller/namespace/deletion/namespaced_resources_deleter.go","code":"func (o *operationNotSupportedCache) setNotSupported(key operationKey) {\n\to.lock.Lock()\n\tdefer o.lock.Unlock()\n\to.m[key] = true\n}","line":{"from":233,"to":237}} {"id":100004107,"name":"retryOnConflictError","signature":"func (d *namespacedResourcesDeleter) retryOnConflictError(namespace *v1.Namespace, fn updateNamespaceFunc) (result *v1.Namespace, err error)","file":"pkg/controller/namespace/deletion/namespaced_resources_deleter.go","code":"// retryOnConflictError retries the specified fn if there was a conflict error\n// it will return an error if the UID for an object changes across retry operations.\n// TODO RetryOnConflict should be a generic concept in client code\nfunc (d *namespacedResourcesDeleter) retryOnConflictError(namespace *v1.Namespace, fn updateNamespaceFunc) (result *v1.Namespace, err error) {\n\tlatestNamespace := namespace\n\tfor {\n\t\tresult, err = fn(latestNamespace)\n\t\tif err == nil {\n\t\t\treturn result, nil\n\t\t}\n\t\tif !errors.IsConflict(err) {\n\t\t\treturn nil, err\n\t\t}\n\t\tprevNamespace := latestNamespace\n\t\tlatestNamespace, err = d.nsClient.Get(context.TODO(), latestNamespace.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif prevNamespace.UID != latestNamespace.UID {\n\t\t\treturn nil, fmt.Errorf(\"namespace uid has changed across retries\")\n\t\t}\n\t}\n}","line":{"from":242,"to":264}} {"id":100004108,"name":"updateNamespaceStatusFunc","signature":"func (d *namespacedResourcesDeleter) updateNamespaceStatusFunc(namespace *v1.Namespace) (*v1.Namespace, error)","file":"pkg/controller/namespace/deletion/namespaced_resources_deleter.go","code":"// updateNamespaceStatusFunc will verify that the status of the namespace is correct\nfunc (d *namespacedResourcesDeleter) updateNamespaceStatusFunc(namespace *v1.Namespace) (*v1.Namespace, error) {\n\tif namespace.DeletionTimestamp.IsZero() || namespace.Status.Phase == v1.NamespaceTerminating {\n\t\treturn namespace, nil\n\t}\n\tnewNamespace := namespace.DeepCopy()\n\tnewNamespace.Status.Phase = v1.NamespaceTerminating\n\treturn d.nsClient.UpdateStatus(context.TODO(), newNamespace, metav1.UpdateOptions{})\n}","line":{"from":266,"to":274}} {"id":100004109,"name":"finalized","signature":"func finalized(namespace *v1.Namespace) bool","file":"pkg/controller/namespace/deletion/namespaced_resources_deleter.go","code":"// finalized returns true if the namespace.Spec.Finalizers is an empty list\nfunc finalized(namespace *v1.Namespace) bool {\n\treturn len(namespace.Spec.Finalizers) == 0\n}","line":{"from":276,"to":279}} {"id":100004110,"name":"finalizeNamespace","signature":"func (d *namespacedResourcesDeleter) finalizeNamespace(namespace *v1.Namespace) (*v1.Namespace, error)","file":"pkg/controller/namespace/deletion/namespaced_resources_deleter.go","code":"// finalizeNamespace removes the specified finalizerToken and finalizes the namespace\nfunc (d *namespacedResourcesDeleter) finalizeNamespace(namespace *v1.Namespace) (*v1.Namespace, error) {\n\tnamespaceFinalize := v1.Namespace{}\n\tnamespaceFinalize.ObjectMeta = namespace.ObjectMeta\n\tnamespaceFinalize.Spec = namespace.Spec\n\tfinalizerSet := sets.NewString()\n\tfor i := range namespace.Spec.Finalizers {\n\t\tif namespace.Spec.Finalizers[i] != d.finalizerToken {\n\t\t\tfinalizerSet.Insert(string(namespace.Spec.Finalizers[i]))\n\t\t}\n\t}\n\tnamespaceFinalize.Spec.Finalizers = make([]v1.FinalizerName, 0, len(finalizerSet))\n\tfor _, value := range finalizerSet.List() {\n\t\tnamespaceFinalize.Spec.Finalizers = append(namespaceFinalize.Spec.Finalizers, v1.FinalizerName(value))\n\t}\n\tnamespace, err := d.nsClient.Finalize(context.Background(), \u0026namespaceFinalize, metav1.UpdateOptions{})\n\tif err != nil {\n\t\t// it was removed already, so life is good\n\t\tif errors.IsNotFound(err) {\n\t\t\treturn namespace, nil\n\t\t}\n\t}\n\treturn namespace, err\n}","line":{"from":281,"to":304}} {"id":100004111,"name":"deleteCollection","signature":"func (d *namespacedResourcesDeleter) deleteCollection(ctx context.Context, gvr schema.GroupVersionResource, namespace string) (bool, error)","file":"pkg/controller/namespace/deletion/namespaced_resources_deleter.go","code":"// deleteCollection is a helper function that will delete the collection of resources\n// it returns true if the operation was supported on the server.\n// it returns an error if the operation was supported on the server but was unable to complete.\nfunc (d *namespacedResourcesDeleter) deleteCollection(ctx context.Context, gvr schema.GroupVersionResource, namespace string) (bool, error) {\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(5).Info(\"Namespace controller - deleteCollection\", \"namespace\", namespace, \"resource\", gvr)\n\n\tkey := operationKey{operation: operationDeleteCollection, gvr: gvr}\n\tif !d.opCache.isSupported(key) {\n\t\tlogger.V(5).Info(\"Namespace controller - deleteCollection ignored since not supported\", \"namespace\", namespace, \"resource\", gvr)\n\t\treturn false, nil\n\t}\n\n\t// namespace controller does not want the garbage collector to insert the orphan finalizer since it calls\n\t// resource deletions generically. it will ensure all resources in the namespace are purged prior to releasing\n\t// namespace itself.\n\tbackground := metav1.DeletePropagationBackground\n\topts := metav1.DeleteOptions{PropagationPolicy: \u0026background}\n\terr := d.metadataClient.Resource(gvr).Namespace(namespace).DeleteCollection(context.TODO(), opts, metav1.ListOptions{})\n\n\tif err == nil {\n\t\treturn true, nil\n\t}\n\n\t// this is strange, but we need to special case for both MethodNotSupported and NotFound errors\n\t// TODO: https://github.com/kubernetes/kubernetes/issues/22413\n\t// we have a resource returned in the discovery API that supports no top-level verbs:\n\t// /apis/extensions/v1beta1/namespaces/default/replicationcontrollers\n\t// when working with this resource type, we will get a literal not found error rather than expected method not supported\n\tif errors.IsMethodNotSupported(err) || errors.IsNotFound(err) {\n\t\tlogger.V(5).Info(\"Namespace controller - deleteCollection not supported\", \"namespace\", namespace, \"resource\", gvr)\n\t\treturn false, nil\n\t}\n\n\tlogger.V(5).Info(\"Namespace controller - deleteCollection unexpected error\", \"namespace\", namespace, \"resource\", gvr, \"err\", err)\n\treturn true, err\n}","line":{"from":306,"to":342}} {"id":100004112,"name":"listCollection","signature":"func (d *namespacedResourcesDeleter) listCollection(ctx context.Context, gvr schema.GroupVersionResource, namespace string) (*metav1.PartialObjectMetadataList, bool, error)","file":"pkg/controller/namespace/deletion/namespaced_resources_deleter.go","code":"// listCollection will list the items in the specified namespace\n// it returns the following:\n//\n//\tthe list of items in the collection (if found)\n//\ta boolean if the operation is supported\n//\tan error if the operation is supported but could not be completed.\nfunc (d *namespacedResourcesDeleter) listCollection(ctx context.Context, gvr schema.GroupVersionResource, namespace string) (*metav1.PartialObjectMetadataList, bool, error) {\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(5).Info(\"Namespace controller - listCollection\", \"namespace\", namespace, \"resource\", gvr)\n\n\tkey := operationKey{operation: operationList, gvr: gvr}\n\tif !d.opCache.isSupported(key) {\n\t\tlogger.V(5).Info(\"Namespace controller - listCollection ignored since not supported\", \"namespace\", namespace, \"resource\", gvr)\n\t\treturn nil, false, nil\n\t}\n\n\tpartialList, err := d.metadataClient.Resource(gvr).Namespace(namespace).List(context.TODO(), metav1.ListOptions{})\n\tif err == nil {\n\t\treturn partialList, true, nil\n\t}\n\n\t// this is strange, but we need to special case for both MethodNotSupported and NotFound errors\n\t// TODO: https://github.com/kubernetes/kubernetes/issues/22413\n\t// we have a resource returned in the discovery API that supports no top-level verbs:\n\t// /apis/extensions/v1beta1/namespaces/default/replicationcontrollers\n\t// when working with this resource type, we will get a literal not found error rather than expected method not supported\n\tif errors.IsMethodNotSupported(err) || errors.IsNotFound(err) {\n\t\tlogger.V(5).Info(\"Namespace controller - listCollection not supported\", \"namespace\", namespace, \"resource\", gvr)\n\t\treturn nil, false, nil\n\t}\n\n\treturn nil, true, err\n}","line":{"from":344,"to":376}} {"id":100004113,"name":"deleteEachItem","signature":"func (d *namespacedResourcesDeleter) deleteEachItem(ctx context.Context, gvr schema.GroupVersionResource, namespace string) error","file":"pkg/controller/namespace/deletion/namespaced_resources_deleter.go","code":"// deleteEachItem is a helper function that will list the collection of resources and delete each item 1 by 1.\nfunc (d *namespacedResourcesDeleter) deleteEachItem(ctx context.Context, gvr schema.GroupVersionResource, namespace string) error {\n\tklog.FromContext(ctx).V(5).Info(\"Namespace controller - deleteEachItem\", \"namespace\", namespace, \"resource\", gvr)\n\n\tunstructuredList, listSupported, err := d.listCollection(ctx, gvr, namespace)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !listSupported {\n\t\treturn nil\n\t}\n\tfor _, item := range unstructuredList.Items {\n\t\tbackground := metav1.DeletePropagationBackground\n\t\topts := metav1.DeleteOptions{PropagationPolicy: \u0026background}\n\t\tif err = d.metadataClient.Resource(gvr).Namespace(namespace).Delete(context.TODO(), item.GetName(), opts); err != nil \u0026\u0026 !errors.IsNotFound(err) \u0026\u0026 !errors.IsMethodNotSupported(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":378,"to":397}} {"id":100004114,"name":"deleteAllContentForGroupVersionResource","signature":"func (d *namespacedResourcesDeleter) deleteAllContentForGroupVersionResource(","file":"pkg/controller/namespace/deletion/namespaced_resources_deleter.go","code":"// deleteAllContentForGroupVersionResource will use the dynamic client to delete each resource identified in gvr.\n// It returns an estimate of the time remaining before the remaining resources are deleted.\n// If estimate \u003e 0, not all resources are guaranteed to be gone.\nfunc (d *namespacedResourcesDeleter) deleteAllContentForGroupVersionResource(\n\tctx context.Context,\n\tgvr schema.GroupVersionResource, namespace string,\n\tnamespaceDeletedAt metav1.Time) (gvrDeletionMetadata, error) {\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(5).Info(\"Namespace controller - deleteAllContentForGroupVersionResource\", \"namespace\", namespace, \"resource\", gvr)\n\n\t// estimate how long it will take for the resource to be deleted (needed for objects that support graceful delete)\n\testimate, err := d.estimateGracefulTermination(ctx, gvr, namespace, namespaceDeletedAt)\n\tif err != nil {\n\t\tlogger.V(5).Info(\"Namespace controller - deleteAllContentForGroupVersionResource - unable to estimate\", \"namespace\", namespace, \"resource\", gvr, \"err\", err)\n\t\treturn gvrDeletionMetadata{}, err\n\t}\n\tlogger.V(5).Info(\"Namespace controller - deleteAllContentForGroupVersionResource - estimate\", \"namespace\", namespace, \"resource\", gvr, \"estimate\", estimate)\n\n\t// first try to delete the entire collection\n\tdeleteCollectionSupported, err := d.deleteCollection(ctx, gvr, namespace)\n\tif err != nil {\n\t\treturn gvrDeletionMetadata{finalizerEstimateSeconds: estimate}, err\n\t}\n\n\t// delete collection was not supported, so we list and delete each item...\n\tif !deleteCollectionSupported {\n\t\terr = d.deleteEachItem(ctx, gvr, namespace)\n\t\tif err != nil {\n\t\t\treturn gvrDeletionMetadata{finalizerEstimateSeconds: estimate}, err\n\t\t}\n\t}\n\n\t// verify there are no more remaining items\n\t// it is not an error condition for there to be remaining items if local estimate is non-zero\n\tlogger.V(5).Info(\"Namespace controller - deleteAllContentForGroupVersionResource - checking for no more items in namespace\", \"namespace\", namespace, \"resource\", gvr)\n\tunstructuredList, listSupported, err := d.listCollection(ctx, gvr, namespace)\n\tif err != nil {\n\t\tlogger.V(5).Info(\"Namespace controller - deleteAllContentForGroupVersionResource - error verifying no items in namespace\", \"namespace\", namespace, \"resource\", gvr, \"err\", err)\n\t\treturn gvrDeletionMetadata{finalizerEstimateSeconds: estimate}, err\n\t}\n\tif !listSupported {\n\t\treturn gvrDeletionMetadata{finalizerEstimateSeconds: estimate}, nil\n\t}\n\tlogger.V(5).Info(\"Namespace controller - deleteAllContentForGroupVersionResource - items remaining\", \"namespace\", namespace, \"resource\", gvr, \"items\", len(unstructuredList.Items))\n\tif len(unstructuredList.Items) == 0 {\n\t\t// we're done\n\t\treturn gvrDeletionMetadata{finalizerEstimateSeconds: 0, numRemaining: 0}, nil\n\t}\n\n\t// use the list to find the finalizers\n\tfinalizersToNumRemaining := map[string]int{}\n\tfor _, item := range unstructuredList.Items {\n\t\tfor _, finalizer := range item.GetFinalizers() {\n\t\t\tfinalizersToNumRemaining[finalizer] = finalizersToNumRemaining[finalizer] + 1\n\t\t}\n\t}\n\n\tif estimate != int64(0) {\n\t\tlogger.V(5).Info(\"Namespace controller - deleteAllContentForGroupVersionResource - estimate is present\", \"namespace\", namespace, \"resource\", gvr, \"finalizers\", finalizersToNumRemaining)\n\t\treturn gvrDeletionMetadata{\n\t\t\tfinalizerEstimateSeconds: estimate,\n\t\t\tnumRemaining: len(unstructuredList.Items),\n\t\t\tfinalizersToNumRemaining: finalizersToNumRemaining,\n\t\t}, nil\n\t}\n\n\t// if any item has a finalizer, we treat that as a normal condition, and use a default estimation to allow for GC to complete.\n\tif len(finalizersToNumRemaining) \u003e 0 {\n\t\tlogger.V(5).Info(\"Namespace controller - deleteAllContentForGroupVersionResource - items remaining with finalizers\", \"namespace\", namespace, \"resource\", gvr, \"finalizers\", finalizersToNumRemaining)\n\t\treturn gvrDeletionMetadata{\n\t\t\tfinalizerEstimateSeconds: finalizerEstimateSeconds,\n\t\t\tnumRemaining: len(unstructuredList.Items),\n\t\t\tfinalizersToNumRemaining: finalizersToNumRemaining,\n\t\t}, nil\n\t}\n\n\t// nothing reported a finalizer, so something was unexpected as it should have been deleted.\n\treturn gvrDeletionMetadata{\n\t\tfinalizerEstimateSeconds: estimate,\n\t\tnumRemaining: len(unstructuredList.Items),\n\t}, fmt.Errorf(\"unexpected items still remain in namespace: %s for gvr: %v\", namespace, gvr)\n}","line":{"from":409,"to":490}} {"id":100004115,"name":"deleteAllContent","signature":"func (d *namespacedResourcesDeleter) deleteAllContent(ctx context.Context, ns *v1.Namespace) (int64, error)","file":"pkg/controller/namespace/deletion/namespaced_resources_deleter.go","code":"// deleteAllContent will use the dynamic client to delete each resource identified in groupVersionResources.\n// It returns an estimate of the time remaining before the remaining resources are deleted.\n// If estimate \u003e 0, not all resources are guaranteed to be gone.\nfunc (d *namespacedResourcesDeleter) deleteAllContent(ctx context.Context, ns *v1.Namespace) (int64, error) {\n\tnamespace := ns.Name\n\tnamespaceDeletedAt := *ns.DeletionTimestamp\n\tvar errs []error\n\tconditionUpdater := namespaceConditionUpdater{}\n\testimate := int64(0)\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"namespace controller - deleteAllContent\", \"namespace\", namespace)\n\n\tresources, err := d.discoverResourcesFn()\n\tif err != nil {\n\t\t// discovery errors are not fatal. We often have some set of resources we can operate against even if we don't have a complete list\n\t\terrs = append(errs, err)\n\t\tconditionUpdater.ProcessDiscoverResourcesErr(err)\n\t}\n\t// TODO(sttts): get rid of opCache and pass the verbs (especially \"deletecollection\") down into the deleter\n\tdeletableResources := discovery.FilteredBy(discovery.SupportsAllVerbs{Verbs: []string{\"delete\"}}, resources)\n\tgroupVersionResources, err := discovery.GroupVersionResources(deletableResources)\n\tif err != nil {\n\t\t// discovery errors are not fatal. We often have some set of resources we can operate against even if we don't have a complete list\n\t\terrs = append(errs, err)\n\t\tconditionUpdater.ProcessGroupVersionErr(err)\n\t}\n\n\tnumRemainingTotals := allGVRDeletionMetadata{\n\t\tgvrToNumRemaining: map[schema.GroupVersionResource]int{},\n\t\tfinalizersToNumRemaining: map[string]int{},\n\t}\n\tfor gvr := range groupVersionResources {\n\t\tgvrDeletionMetadata, err := d.deleteAllContentForGroupVersionResource(ctx, gvr, namespace, namespaceDeletedAt)\n\t\tif err != nil {\n\t\t\t// If there is an error, hold on to it but proceed with all the remaining\n\t\t\t// groupVersionResources.\n\t\t\terrs = append(errs, err)\n\t\t\tconditionUpdater.ProcessDeleteContentErr(err)\n\t\t}\n\t\tif gvrDeletionMetadata.finalizerEstimateSeconds \u003e estimate {\n\t\t\testimate = gvrDeletionMetadata.finalizerEstimateSeconds\n\t\t}\n\t\tif gvrDeletionMetadata.numRemaining \u003e 0 {\n\t\t\tnumRemainingTotals.gvrToNumRemaining[gvr] = gvrDeletionMetadata.numRemaining\n\t\t\tfor finalizer, numRemaining := range gvrDeletionMetadata.finalizersToNumRemaining {\n\t\t\t\tif numRemaining == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tnumRemainingTotals.finalizersToNumRemaining[finalizer] = numRemainingTotals.finalizersToNumRemaining[finalizer] + numRemaining\n\t\t\t}\n\t\t}\n\t}\n\tconditionUpdater.ProcessContentTotals(numRemainingTotals)\n\n\t// we always want to update the conditions because if we have set a condition to \"it worked\" after it was previously, \"it didn't work\",\n\t// we need to reflect that information. Recall that additional finalizers can be set on namespaces, so this finalizer may clear itself and\n\t// NOT remove the resource instance.\n\tif hasChanged := conditionUpdater.Update(ns); hasChanged {\n\t\tif _, err = d.nsClient.UpdateStatus(context.TODO(), ns, metav1.UpdateOptions{}); err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't update status condition for namespace %q: %v\", namespace, err))\n\t\t}\n\t}\n\n\t// if len(errs)==0, NewAggregate returns nil.\n\terr = utilerrors.NewAggregate(errs)\n\tlogger.V(4).Info(\"namespace controller - deleteAllContent\", \"namespace\", namespace, \"estimate\", estimate, \"err\", err)\n\treturn estimate, err\n}","line":{"from":499,"to":566}} {"id":100004116,"name":"estimateGracefulTermination","signature":"func (d *namespacedResourcesDeleter) estimateGracefulTermination(ctx context.Context, gvr schema.GroupVersionResource, ns string, namespaceDeletedAt metav1.Time) (int64, error)","file":"pkg/controller/namespace/deletion/namespaced_resources_deleter.go","code":"// estimateGracefulTermination will estimate the graceful termination required for the specific entity in the namespace\nfunc (d *namespacedResourcesDeleter) estimateGracefulTermination(ctx context.Context, gvr schema.GroupVersionResource, ns string, namespaceDeletedAt metav1.Time) (int64, error) {\n\tgroupResource := gvr.GroupResource()\n\tklog.FromContext(ctx).V(5).Info(\"Namespace controller - estimateGracefulTermination\", \"group\", groupResource.Group, \"resource\", groupResource.Resource)\n\testimate := int64(0)\n\tvar err error\n\tswitch groupResource {\n\tcase schema.GroupResource{Group: \"\", Resource: \"pods\"}:\n\t\testimate, err = d.estimateGracefulTerminationForPods(ctx, ns)\n\t}\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\t// determine if the estimate is greater than the deletion timestamp\n\tduration := time.Since(namespaceDeletedAt.Time)\n\tallowedEstimate := time.Duration(estimate) * time.Second\n\tif duration \u003e= allowedEstimate {\n\t\testimate = int64(0)\n\t}\n\treturn estimate, nil\n}","line":{"from":568,"to":588}} {"id":100004117,"name":"estimateGracefulTerminationForPods","signature":"func (d *namespacedResourcesDeleter) estimateGracefulTerminationForPods(ctx context.Context, ns string) (int64, error)","file":"pkg/controller/namespace/deletion/namespaced_resources_deleter.go","code":"// estimateGracefulTerminationForPods determines the graceful termination period for pods in the namespace\nfunc (d *namespacedResourcesDeleter) estimateGracefulTerminationForPods(ctx context.Context, ns string) (int64, error) {\n\tklog.FromContext(ctx).V(5).Info(\"Namespace controller - estimateGracefulTerminationForPods\", \"namespace\", ns)\n\testimate := int64(0)\n\tpodsGetter := d.podsGetter\n\tif podsGetter == nil || reflect.ValueOf(podsGetter).IsNil() {\n\t\treturn 0, fmt.Errorf(\"unexpected: podsGetter is nil. Cannot estimate grace period seconds for pods\")\n\t}\n\titems, err := podsGetter.Pods(ns).List(context.TODO(), metav1.ListOptions{})\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tfor i := range items.Items {\n\t\tpod := items.Items[i]\n\t\t// filter out terminal pods\n\t\tphase := pod.Status.Phase\n\t\tif v1.PodSucceeded == phase || v1.PodFailed == phase {\n\t\t\tcontinue\n\t\t}\n\t\tif pod.Spec.TerminationGracePeriodSeconds != nil {\n\t\t\tgrace := *pod.Spec.TerminationGracePeriodSeconds\n\t\t\tif grace \u003e estimate {\n\t\t\t\testimate = grace\n\t\t\t}\n\t\t}\n\t}\n\treturn estimate, nil\n}","line":{"from":590,"to":617}} {"id":100004118,"name":"ProcessGroupVersionErr","signature":"func (u *namespaceConditionUpdater) ProcessGroupVersionErr(err error)","file":"pkg/controller/namespace/deletion/status_condition_utils.go","code":"// ProcessGroupVersionErr creates error condition if parsing GroupVersion of resources fails.\nfunc (u *namespaceConditionUpdater) ProcessGroupVersionErr(err error) {\n\td := v1.NamespaceCondition{\n\t\tType: v1.NamespaceDeletionGVParsingFailure,\n\t\tStatus: v1.ConditionTrue,\n\t\tLastTransitionTime: metav1.Now(),\n\t\tReason: \"GroupVersionParsingFailed\",\n\t\tMessage: err.Error(),\n\t}\n\tu.newConditions = append(u.newConditions, d)\n}","line":{"from":70,"to":80}} {"id":100004119,"name":"ProcessDiscoverResourcesErr","signature":"func (u *namespaceConditionUpdater) ProcessDiscoverResourcesErr(err error)","file":"pkg/controller/namespace/deletion/status_condition_utils.go","code":"// ProcessDiscoverResourcesErr creates error condition from ErrGroupDiscoveryFailed.\nfunc (u *namespaceConditionUpdater) ProcessDiscoverResourcesErr(err error) {\n\tvar msg string\n\tif derr, ok := err.(*discovery.ErrGroupDiscoveryFailed); ok {\n\t\tmsg = fmt.Sprintf(\"Discovery failed for some groups, %d failing: %v\", len(derr.Groups), err)\n\t} else {\n\t\tmsg = err.Error()\n\t}\n\td := v1.NamespaceCondition{\n\t\tType: v1.NamespaceDeletionDiscoveryFailure,\n\t\tStatus: v1.ConditionTrue,\n\t\tLastTransitionTime: metav1.Now(),\n\t\tReason: \"DiscoveryFailed\",\n\t\tMessage: msg,\n\t}\n\tu.newConditions = append(u.newConditions, d)\n\n}","line":{"from":82,"to":99}} {"id":100004120,"name":"ProcessContentTotals","signature":"func (u *namespaceConditionUpdater) ProcessContentTotals(contentTotals allGVRDeletionMetadata)","file":"pkg/controller/namespace/deletion/status_condition_utils.go","code":"// ProcessContentTotals may create conditions for NamespaceContentRemaining and NamespaceFinalizersRemaining.\nfunc (u *namespaceConditionUpdater) ProcessContentTotals(contentTotals allGVRDeletionMetadata) {\n\tif len(contentTotals.gvrToNumRemaining) != 0 {\n\t\tremainingResources := []string{}\n\t\tfor gvr, numRemaining := range contentTotals.gvrToNumRemaining {\n\t\t\tif numRemaining == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tremainingResources = append(remainingResources, fmt.Sprintf(\"%s.%s has %d resource instances\", gvr.Resource, gvr.Group, numRemaining))\n\t\t}\n\t\t// sort for stable updates\n\t\tsort.Strings(remainingResources)\n\t\tu.newConditions = append(u.newConditions, v1.NamespaceCondition{\n\t\t\tType: v1.NamespaceContentRemaining,\n\t\t\tStatus: v1.ConditionTrue,\n\t\t\tLastTransitionTime: metav1.Now(),\n\t\t\tReason: \"SomeResourcesRemain\",\n\t\t\tMessage: fmt.Sprintf(\"Some resources are remaining: %s\", strings.Join(remainingResources, \", \")),\n\t\t})\n\t}\n\n\tif len(contentTotals.finalizersToNumRemaining) != 0 {\n\t\tremainingByFinalizer := []string{}\n\t\tfor finalizer, numRemaining := range contentTotals.finalizersToNumRemaining {\n\t\t\tif numRemaining == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tremainingByFinalizer = append(remainingByFinalizer, fmt.Sprintf(\"%s in %d resource instances\", finalizer, numRemaining))\n\t\t}\n\t\t// sort for stable updates\n\t\tsort.Strings(remainingByFinalizer)\n\t\tu.newConditions = append(u.newConditions, v1.NamespaceCondition{\n\t\t\tType: v1.NamespaceFinalizersRemaining,\n\t\t\tStatus: v1.ConditionTrue,\n\t\t\tLastTransitionTime: metav1.Now(),\n\t\t\tReason: \"SomeFinalizersRemain\",\n\t\t\tMessage: fmt.Sprintf(\"Some content in the namespace has finalizers remaining: %s\", strings.Join(remainingByFinalizer, \", \")),\n\t\t})\n\t}\n}","line":{"from":101,"to":140}} {"id":100004121,"name":"ProcessDeleteContentErr","signature":"func (u *namespaceConditionUpdater) ProcessDeleteContentErr(err error)","file":"pkg/controller/namespace/deletion/status_condition_utils.go","code":"// ProcessDeleteContentErr creates error condition from multiple delete content errors.\nfunc (u *namespaceConditionUpdater) ProcessDeleteContentErr(err error) {\n\tu.deleteContentErrors = append(u.deleteContentErrors, err)\n}","line":{"from":142,"to":145}} {"id":100004122,"name":"Update","signature":"func (u *namespaceConditionUpdater) Update(ns *v1.Namespace) bool","file":"pkg/controller/namespace/deletion/status_condition_utils.go","code":"// Update compiles processed errors from namespace deletion into status conditions.\nfunc (u *namespaceConditionUpdater) Update(ns *v1.Namespace) bool {\n\tif c := getCondition(u.newConditions, v1.NamespaceDeletionContentFailure); c == nil {\n\t\tif c := makeDeleteContentCondition(u.deleteContentErrors); c != nil {\n\t\t\tu.newConditions = append(u.newConditions, *c)\n\t\t}\n\t}\n\treturn updateConditions(\u0026ns.Status, u.newConditions)\n}","line":{"from":147,"to":155}} {"id":100004123,"name":"makeDeleteContentCondition","signature":"func makeDeleteContentCondition(err []error) *v1.NamespaceCondition","file":"pkg/controller/namespace/deletion/status_condition_utils.go","code":"func makeDeleteContentCondition(err []error) *v1.NamespaceCondition {\n\tif len(err) == 0 {\n\t\treturn nil\n\t}\n\tmsgs := make([]string, 0, len(err))\n\tfor _, e := range err {\n\t\tmsgs = append(msgs, e.Error())\n\t}\n\tsort.Strings(msgs)\n\treturn \u0026v1.NamespaceCondition{\n\t\tType: v1.NamespaceDeletionContentFailure,\n\t\tStatus: v1.ConditionTrue,\n\t\tLastTransitionTime: metav1.Now(),\n\t\tReason: \"ContentDeletionFailed\",\n\t\tMessage: fmt.Sprintf(\"Failed to delete all resource types, %d remaining: %v\", len(err), strings.Join(msgs, \", \")),\n\t}\n}","line":{"from":157,"to":173}} {"id":100004124,"name":"updateConditions","signature":"func updateConditions(status *v1.NamespaceStatus, newConditions []v1.NamespaceCondition) (hasChanged bool)","file":"pkg/controller/namespace/deletion/status_condition_utils.go","code":"func updateConditions(status *v1.NamespaceStatus, newConditions []v1.NamespaceCondition) (hasChanged bool) {\n\tfor _, conditionType := range conditionTypes {\n\t\tnewCondition := getCondition(newConditions, conditionType)\n\t\t// if we weren't failing, then this returned nil. We should set the \"ok\" variant of the condition\n\t\tif newCondition == nil {\n\t\t\tnewCondition = newSuccessfulCondition(conditionType)\n\t\t}\n\t\toldCondition := getCondition(status.Conditions, conditionType)\n\n\t\t// only new condition of this type exists, add to the list\n\t\tif oldCondition == nil {\n\t\t\tstatus.Conditions = append(status.Conditions, *newCondition)\n\t\t\thasChanged = true\n\n\t\t} else if oldCondition.Status != newCondition.Status || oldCondition.Message != newCondition.Message || oldCondition.Reason != newCondition.Reason {\n\t\t\t// old condition needs to be updated\n\t\t\tif oldCondition.Status != newCondition.Status {\n\t\t\t\toldCondition.LastTransitionTime = metav1.Now()\n\t\t\t}\n\t\t\toldCondition.Type = newCondition.Type\n\t\t\toldCondition.Status = newCondition.Status\n\t\t\toldCondition.Reason = newCondition.Reason\n\t\t\toldCondition.Message = newCondition.Message\n\t\t\thasChanged = true\n\t\t}\n\t}\n\treturn\n}","line":{"from":175,"to":202}} {"id":100004125,"name":"newSuccessfulCondition","signature":"func newSuccessfulCondition(conditionType v1.NamespaceConditionType) *v1.NamespaceCondition","file":"pkg/controller/namespace/deletion/status_condition_utils.go","code":"func newSuccessfulCondition(conditionType v1.NamespaceConditionType) *v1.NamespaceCondition {\n\treturn \u0026v1.NamespaceCondition{\n\t\tType: conditionType,\n\t\tStatus: v1.ConditionFalse,\n\t\tLastTransitionTime: metav1.Now(),\n\t\tReason: okReasons[conditionType],\n\t\tMessage: okMessages[conditionType],\n\t}\n}","line":{"from":204,"to":212}} {"id":100004126,"name":"getCondition","signature":"func getCondition(conditions []v1.NamespaceCondition, conditionType v1.NamespaceConditionType) *v1.NamespaceCondition","file":"pkg/controller/namespace/deletion/status_condition_utils.go","code":"func getCondition(conditions []v1.NamespaceCondition, conditionType v1.NamespaceConditionType) *v1.NamespaceCondition {\n\tfor i := range conditions {\n\t\tif conditions[i].Type == conditionType {\n\t\t\treturn \u0026(conditions[i])\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":214,"to":221}} {"id":100004127,"name":"NewNamespaceController","signature":"func NewNamespaceController(","file":"pkg/controller/namespace/namespace_controller.go","code":"// NewNamespaceController creates a new NamespaceController\nfunc NewNamespaceController(\n\tctx context.Context,\n\tkubeClient clientset.Interface,\n\tmetadataClient metadata.Interface,\n\tdiscoverResourcesFn func() ([]*metav1.APIResourceList, error),\n\tnamespaceInformer coreinformers.NamespaceInformer,\n\tresyncPeriod time.Duration,\n\tfinalizerToken v1.FinalizerName) *NamespaceController {\n\n\t// create the controller so we can inject the enqueue function\n\tnamespaceController := \u0026NamespaceController{\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(nsControllerRateLimiter(), \"namespace\"),\n\t\tnamespacedResourcesDeleter: deletion.NewNamespacedResourcesDeleter(ctx, kubeClient.CoreV1().Namespaces(), metadataClient, kubeClient.CoreV1(), discoverResourcesFn, finalizerToken),\n\t}\n\n\t// configure the namespace informer event handlers\n\tnamespaceInformer.Informer().AddEventHandlerWithResyncPeriod(\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: func(obj interface{}) {\n\t\t\t\tnamespace := obj.(*v1.Namespace)\n\t\t\t\tnamespaceController.enqueueNamespace(namespace)\n\t\t\t},\n\t\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\t\tnamespace := newObj.(*v1.Namespace)\n\t\t\t\tnamespaceController.enqueueNamespace(namespace)\n\t\t\t},\n\t\t},\n\t\tresyncPeriod,\n\t)\n\tnamespaceController.lister = namespaceInformer.Lister()\n\tnamespaceController.listerSynced = namespaceInformer.Informer().HasSynced\n\n\treturn namespaceController\n}","line":{"from":65,"to":99}} {"id":100004128,"name":"nsControllerRateLimiter","signature":"func nsControllerRateLimiter() workqueue.RateLimiter","file":"pkg/controller/namespace/namespace_controller.go","code":"// nsControllerRateLimiter is tuned for a faster than normal recycle time with default backoff speed and default overall\n// requeing speed. We do this so that namespace cleanup is reliably faster and we know that the number of namespaces being\n// deleted is smaller than total number of other namespace scoped resources in a cluster.\nfunc nsControllerRateLimiter() workqueue.RateLimiter {\n\treturn workqueue.NewMaxOfRateLimiter(\n\t\t// this ensures that we retry namespace deletion at least every minute, never longer.\n\t\tworkqueue.NewItemExponentialFailureRateLimiter(5*time.Millisecond, 60*time.Second),\n\t\t// 10 qps, 100 bucket size. This is only for retry speed and its only the overall factor (not per item)\n\t\t\u0026workqueue.BucketRateLimiter{Limiter: rate.NewLimiter(rate.Limit(10), 100)},\n\t)\n}","line":{"from":101,"to":111}} {"id":100004129,"name":"enqueueNamespace","signature":"func (nm *NamespaceController) enqueueNamespace(obj interface{})","file":"pkg/controller/namespace/namespace_controller.go","code":"// enqueueNamespace adds an object to the controller work queue\n// obj could be an *v1.Namespace, or a DeletionFinalStateUnknown item.\nfunc (nm *NamespaceController) enqueueNamespace(obj interface{}) {\n\tkey, err := controller.KeyFunc(obj)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Couldn't get key for object %+v: %v\", obj, err))\n\t\treturn\n\t}\n\n\tnamespace := obj.(*v1.Namespace)\n\t// don't queue if we aren't deleted\n\tif namespace.DeletionTimestamp == nil || namespace.DeletionTimestamp.IsZero() {\n\t\treturn\n\t}\n\n\t// delay processing namespace events to allow HA api servers to observe namespace deletion,\n\t// and HA etcd servers to observe last minute object creations inside the namespace\n\tnm.queue.AddAfter(key, namespaceDeletionGracePeriod)\n}","line":{"from":113,"to":131}} {"id":100004130,"name":"worker","signature":"func (nm *NamespaceController) worker(ctx context.Context)","file":"pkg/controller/namespace/namespace_controller.go","code":"// worker processes the queue of namespace objects.\n// Each namespace can be in the queue at most once.\n// The system ensures that no two workers can process\n// the same namespace at the same time.\nfunc (nm *NamespaceController) worker(ctx context.Context) {\n\tworkFunc := func(ctx context.Context) bool {\n\t\tkey, quit := nm.queue.Get()\n\t\tif quit {\n\t\t\treturn true\n\t\t}\n\t\tdefer nm.queue.Done(key)\n\n\t\terr := nm.syncNamespaceFromKey(ctx, key.(string))\n\t\tif err == nil {\n\t\t\t// no error, forget this entry and return\n\t\t\tnm.queue.Forget(key)\n\t\t\treturn false\n\t\t}\n\n\t\tif estimate, ok := err.(*deletion.ResourcesRemainingError); ok {\n\t\t\tt := estimate.Estimate/2 + 1\n\t\t\tklog.FromContext(ctx).V(4).Info(\"Content remaining in namespace\", \"namespace\", key, \"waitSeconds\", t)\n\t\t\tnm.queue.AddAfter(key, time.Duration(t)*time.Second)\n\t\t} else {\n\t\t\t// rather than wait for a full resync, re-add the namespace to the queue to be processed\n\t\t\tnm.queue.AddRateLimited(key)\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"deletion of namespace %v failed: %v\", key, err))\n\t\t}\n\t\treturn false\n\t}\n\tfor {\n\t\tquit := workFunc(ctx)\n\n\t\tif quit {\n\t\t\treturn\n\t\t}\n\t}\n}","line":{"from":133,"to":170}} {"id":100004131,"name":"syncNamespaceFromKey","signature":"func (nm *NamespaceController) syncNamespaceFromKey(ctx context.Context, key string) (err error)","file":"pkg/controller/namespace/namespace_controller.go","code":"// syncNamespaceFromKey looks for a namespace with the specified key in its store and synchronizes it\nfunc (nm *NamespaceController) syncNamespaceFromKey(ctx context.Context, key string) (err error) {\n\tstartTime := time.Now()\n\tlogger := klog.FromContext(ctx)\n\tdefer func() {\n\t\tlogger.V(4).Info(\"Finished syncing namespace\", \"namespace\", key, \"duration\", time.Since(startTime))\n\t}()\n\n\tnamespace, err := nm.lister.Get(key)\n\tif errors.IsNotFound(err) {\n\t\tlogger.Info(\"Namespace has been deleted\", \"namespace\", key)\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Unable to retrieve namespace %v from store: %v\", key, err))\n\t\treturn err\n\t}\n\treturn nm.namespacedResourcesDeleter.Delete(ctx, namespace.Name)\n}","line":{"from":172,"to":190}} {"id":100004132,"name":"Run","signature":"func (nm *NamespaceController) Run(ctx context.Context, workers int)","file":"pkg/controller/namespace/namespace_controller.go","code":"// Run starts observing the system with the specified number of workers.\nfunc (nm *NamespaceController) Run(ctx context.Context, workers int) {\n\tdefer utilruntime.HandleCrash()\n\tdefer nm.queue.ShutDown()\n\tlogger := klog.FromContext(ctx)\n\tlogger.Info(\"Starting namespace controller\")\n\tdefer logger.Info(\"Shutting down namespace controller\")\n\n\tif !cache.WaitForNamedCacheSync(\"namespace\", ctx.Done(), nm.listerSynced) {\n\t\treturn\n\t}\n\n\tlogger.V(5).Info(\"Starting workers of namespace controller\")\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.UntilWithContext(ctx, nm.worker, time.Second)\n\t}\n\t\u003c-ctx.Done()\n}","line":{"from":192,"to":209}} {"id":100004133,"name":"Convert_v1alpha1_NodeIPAMControllerConfiguration_To_config_NodeIPAMControllerConfiguration","signature":"func Convert_v1alpha1_NodeIPAMControllerConfiguration_To_config_NodeIPAMControllerConfiguration(in *v1alpha1.NodeIPAMControllerConfiguration, out *config.NodeIPAMControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/nodeipam/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_NodeIPAMControllerConfiguration_To_config_NodeIPAMControllerConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_NodeIPAMControllerConfiguration_To_config_NodeIPAMControllerConfiguration(in *v1alpha1.NodeIPAMControllerConfiguration, out *config.NodeIPAMControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_NodeIPAMControllerConfiguration_To_config_NodeIPAMControllerConfiguration(in, out, s)\n}","line":{"from":32,"to":35}} {"id":100004134,"name":"Convert_config_NodeIPAMControllerConfiguration_To_v1alpha1_NodeIPAMControllerConfiguration","signature":"func Convert_config_NodeIPAMControllerConfiguration_To_v1alpha1_NodeIPAMControllerConfiguration(in *config.NodeIPAMControllerConfiguration, out *v1alpha1.NodeIPAMControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/nodeipam/config/v1alpha1/conversion.go","code":"// Convert_config_NodeIPAMControllerConfiguration_To_v1alpha1_NodeIPAMControllerConfiguration is an autogenerated conversion function.\nfunc Convert_config_NodeIPAMControllerConfiguration_To_v1alpha1_NodeIPAMControllerConfiguration(in *config.NodeIPAMControllerConfiguration, out *v1alpha1.NodeIPAMControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_NodeIPAMControllerConfiguration_To_v1alpha1_NodeIPAMControllerConfiguration(in, out, s)\n}","line":{"from":37,"to":40}} {"id":100004135,"name":"RecommendedDefaultNodeIPAMControllerConfiguration","signature":"func RecommendedDefaultNodeIPAMControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.NodeIPAMControllerConfiguration)","file":"pkg/controller/nodeipam/config/v1alpha1/defaults.go","code":"// RecommendedDefaultNodeIPAMControllerConfiguration defaults a pointer to a\n// NodeIPAMControllerConfiguration struct. This will set the recommended default\n// values, but they may be subject to change between API versions. This function\n// is intentionally not registered in the scheme as a \"normal\" `SetDefaults_Foo`\n// function to allow consumers of this type to set whatever defaults for their\n// embedded configs. Forcing consumers to use these defaults would be problematic\n// as defaulting in the scheme is done as part of the conversion, and there would\n// be no easy way to opt-out. Instead, if you want to use this defaulting method\n// run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDefaultNodeIPAMControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.NodeIPAMControllerConfiguration) {\n\t// The default mask size is not set here because we need to determine the cluster cidr family before setting the\n\t// appropriate mask size.\n}","line":{"from":23,"to":35}} {"id":100004136,"name":"newAdapter","signature":"func newAdapter(k8s clientset.Interface, cloud *gce.Cloud) *adapter","file":"pkg/controller/nodeipam/ipam/adapter.go","code":"func newAdapter(k8s clientset.Interface, cloud *gce.Cloud) *adapter {\n\tbroadcaster := record.NewBroadcaster()\n\n\tret := \u0026adapter{\n\t\tk8s: k8s,\n\t\tcloud: cloud,\n\t\tbroadcaster: broadcaster,\n\t\trecorder: broadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"cloudCIDRAllocator\"}),\n\t}\n\n\treturn ret\n}","line":{"from":51,"to":62}} {"id":100004137,"name":"Run","signature":"func (a *adapter) Run(ctx context.Context)","file":"pkg/controller/nodeipam/ipam/adapter.go","code":"func (a *adapter) Run(ctx context.Context) {\n\tdefer utilruntime.HandleCrash()\n\n\t// Start event processing pipeline.\n\ta.broadcaster.StartStructuredLogging(0)\n\ta.broadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: a.k8s.CoreV1().Events(\"\")})\n\tdefer a.broadcaster.Shutdown()\n\n\t\u003c-ctx.Done()\n}","line":{"from":64,"to":73}} {"id":100004138,"name":"Alias","signature":"func (a *adapter) Alias(ctx context.Context, node *v1.Node) (*net.IPNet, error)","file":"pkg/controller/nodeipam/ipam/adapter.go","code":"func (a *adapter) Alias(ctx context.Context, node *v1.Node) (*net.IPNet, error) {\n\tif node.Spec.ProviderID == \"\" {\n\t\treturn nil, fmt.Errorf(\"node %s doesn't have providerID\", node.Name)\n\t}\n\n\tcidrs, err := a.cloud.AliasRangesByProviderID(node.Spec.ProviderID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch len(cidrs) {\n\tcase 0:\n\t\treturn nil, nil\n\tcase 1:\n\t\tbreak\n\tdefault:\n\t\tklog.FromContext(ctx).Info(\"Node has more than one alias assigned, defaulting to the first\", \"node\", klog.KObj(node), \"CIDRs\", cidrs)\n\t}\n\n\t_, cidrRange, err := netutils.ParseCIDRSloppy(cidrs[0])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cidrRange, nil\n}","line":{"from":75,"to":100}} {"id":100004139,"name":"AddAlias","signature":"func (a *adapter) AddAlias(ctx context.Context, node *v1.Node, cidrRange *net.IPNet) error","file":"pkg/controller/nodeipam/ipam/adapter.go","code":"func (a *adapter) AddAlias(ctx context.Context, node *v1.Node, cidrRange *net.IPNet) error {\n\tif node.Spec.ProviderID == \"\" {\n\t\treturn fmt.Errorf(\"node %s doesn't have providerID\", node.Name)\n\t}\n\n\treturn a.cloud.AddAliasToInstanceByProviderID(node.Spec.ProviderID, cidrRange)\n}","line":{"from":102,"to":108}} {"id":100004140,"name":"Node","signature":"func (a *adapter) Node(ctx context.Context, name string) (*v1.Node, error)","file":"pkg/controller/nodeipam/ipam/adapter.go","code":"func (a *adapter) Node(ctx context.Context, name string) (*v1.Node, error) {\n\treturn a.k8s.CoreV1().Nodes().Get(context.TODO(), name, metav1.GetOptions{})\n}","line":{"from":110,"to":112}} {"id":100004141,"name":"UpdateNodePodCIDR","signature":"func (a *adapter) UpdateNodePodCIDR(ctx context.Context, node *v1.Node, cidrRange *net.IPNet) error","file":"pkg/controller/nodeipam/ipam/adapter.go","code":"func (a *adapter) UpdateNodePodCIDR(ctx context.Context, node *v1.Node, cidrRange *net.IPNet) error {\n\tpatch := map[string]interface{}{\n\t\t\"apiVersion\": node.APIVersion,\n\t\t\"kind\": node.Kind,\n\t\t\"metadata\": map[string]interface{}{\"name\": node.Name},\n\t\t\"spec\": map[string]interface{}{\"podCIDR\": cidrRange.String()},\n\t}\n\tbytes, err := json.Marshal(patch)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = a.k8s.CoreV1().Nodes().Patch(context.TODO(), node.Name, types.StrategicMergePatchType, bytes, metav1.PatchOptions{})\n\treturn err\n}","line":{"from":114,"to":128}} {"id":100004142,"name":"UpdateNodeNetworkUnavailable","signature":"func (a *adapter) UpdateNodeNetworkUnavailable(nodeName string, unavailable bool) error","file":"pkg/controller/nodeipam/ipam/adapter.go","code":"func (a *adapter) UpdateNodeNetworkUnavailable(nodeName string, unavailable bool) error {\n\tcondition := v1.ConditionFalse\n\tif unavailable {\n\t\tcondition = v1.ConditionTrue\n\t}\n\treturn nodeutil.SetNodeCondition(a.k8s, types.NodeName(nodeName), v1.NodeCondition{\n\t\tType: v1.NodeNetworkUnavailable,\n\t\tStatus: condition,\n\t\tReason: \"RouteCreated\",\n\t\tMessage: \"NodeController created an implicit route\",\n\t\tLastTransitionTime: metav1.Now(),\n\t})\n}","line":{"from":130,"to":142}} {"id":100004143,"name":"EmitNodeWarningEvent","signature":"func (a *adapter) EmitNodeWarningEvent(nodeName, reason, fmt string, args ...interface{})","file":"pkg/controller/nodeipam/ipam/adapter.go","code":"func (a *adapter) EmitNodeWarningEvent(nodeName, reason, fmt string, args ...interface{}) {\n\tref := \u0026v1.ObjectReference{Kind: \"Node\", Name: nodeName}\n\ta.recorder.Eventf(ref, v1.EventTypeNormal, reason, fmt, args...)\n}","line":{"from":144,"to":147}} {"id":100004144,"name":"New","signature":"func New(ctx context.Context, kubeClient clientset.Interface, cloud cloudprovider.Interface, nodeInformer informers.NodeInformer, clusterCIDRInformer networkinginformers.ClusterCIDRInformer, allocatorType CIDRAllocatorType, allocatorParams CIDRAllocatorParams) (CIDRAllocator, error)","file":"pkg/controller/nodeipam/ipam/cidr_allocator.go","code":"// New creates a new CIDR range allocator.\nfunc New(ctx context.Context, kubeClient clientset.Interface, cloud cloudprovider.Interface, nodeInformer informers.NodeInformer, clusterCIDRInformer networkinginformers.ClusterCIDRInformer, allocatorType CIDRAllocatorType, allocatorParams CIDRAllocatorParams) (CIDRAllocator, error) {\n\tlogger := klog.FromContext(ctx)\n\tnodeList, err := listNodes(logger, kubeClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch allocatorType {\n\tcase RangeAllocatorType:\n\t\treturn NewCIDRRangeAllocator(logger, kubeClient, nodeInformer, allocatorParams, nodeList)\n\tcase MultiCIDRRangeAllocatorType:\n\t\tif !utilfeature.DefaultFeatureGate.Enabled(features.MultiCIDRRangeAllocator) {\n\t\t\treturn nil, fmt.Errorf(\"invalid CIDR allocator type: %v, feature gate %v must be enabled\", allocatorType, features.MultiCIDRRangeAllocator)\n\t\t}\n\t\treturn NewMultiCIDRRangeAllocator(ctx, kubeClient, nodeInformer, clusterCIDRInformer, allocatorParams, nodeList, nil)\n\n\tcase CloudAllocatorType:\n\t\treturn NewCloudCIDRAllocator(logger, kubeClient, cloud, nodeInformer)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid CIDR allocator type: %v\", allocatorType)\n\t}\n}","line":{"from":121,"to":143}} {"id":100004145,"name":"listNodes","signature":"func listNodes(logger klog.Logger, kubeClient clientset.Interface) (*v1.NodeList, error)","file":"pkg/controller/nodeipam/ipam/cidr_allocator.go","code":"func listNodes(logger klog.Logger, kubeClient clientset.Interface) (*v1.NodeList, error) {\n\tvar nodeList *v1.NodeList\n\t// We must poll because apiserver might not be up. This error causes\n\t// controller manager to restart.\n\tif pollErr := wait.Poll(nodePollInterval, apiserverStartupGracePeriod, func() (bool, error) {\n\t\tvar err error\n\t\tnodeList, err = kubeClient.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{\n\t\t\tFieldSelector: fields.Everything().String(),\n\t\t\tLabelSelector: labels.Everything().String(),\n\t\t})\n\t\tif err != nil {\n\t\t\tlogger.Error(err, \"Failed to list all nodes\")\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t}); pollErr != nil {\n\t\treturn nil, fmt.Errorf(\"failed to list all nodes in %v, cannot proceed without updating CIDR map\",\n\t\t\tapiserverStartupGracePeriod)\n\t}\n\treturn nodeList, nil\n}","line":{"from":145,"to":165}} {"id":100004146,"name":"ipnetToStringList","signature":"func ipnetToStringList(inCIDRs []*net.IPNet) []string","file":"pkg/controller/nodeipam/ipam/cidr_allocator.go","code":"// ipnetToStringList converts a slice of net.IPNet into a list of CIDR in string format\nfunc ipnetToStringList(inCIDRs []*net.IPNet) []string {\n\toutCIDRs := make([]string, len(inCIDRs))\n\tfor idx, inCIDR := range inCIDRs {\n\t\toutCIDRs[idx] = inCIDR.String()\n\t}\n\treturn outCIDRs\n}","line":{"from":167,"to":174}} {"id":100004147,"name":"NewCIDRSet","signature":"func NewCIDRSet(clusterCIDR *net.IPNet, subNetMaskSize int) (*CidrSet, error)","file":"pkg/controller/nodeipam/ipam/cidrset/cidr_set.go","code":"// NewCIDRSet creates a new CidrSet.\nfunc NewCIDRSet(clusterCIDR *net.IPNet, subNetMaskSize int) (*CidrSet, error) {\n\tclusterMask := clusterCIDR.Mask\n\tclusterMaskSize, bits := clusterMask.Size()\n\n\tif (clusterCIDR.IP.To4() == nil) \u0026\u0026 (subNetMaskSize-clusterMaskSize \u003e clusterSubnetMaxDiff) {\n\t\treturn nil, ErrCIDRSetSubNetTooBig\n\t}\n\n\t// register CidrSet metrics\n\tregisterCidrsetMetrics()\n\n\tmaxCIDRs := getMaxCIDRs(subNetMaskSize, clusterMaskSize)\n\tcidrSet := \u0026CidrSet{\n\t\tclusterCIDR: clusterCIDR,\n\t\tnodeMask: net.CIDRMask(subNetMaskSize, bits),\n\t\tclusterMaskSize: clusterMaskSize,\n\t\tmaxCIDRs: maxCIDRs,\n\t\tnodeMaskSize: subNetMaskSize,\n\t\tlabel: clusterCIDR.String(),\n\t}\n\tcidrSetMaxCidrs.WithLabelValues(cidrSet.label).Set(float64(maxCIDRs))\n\n\treturn cidrSet, nil\n}","line":{"from":77,"to":101}} {"id":100004148,"name":"indexToCIDRBlock","signature":"func (s *CidrSet) indexToCIDRBlock(index int) *net.IPNet","file":"pkg/controller/nodeipam/ipam/cidrset/cidr_set.go","code":"func (s *CidrSet) indexToCIDRBlock(index int) *net.IPNet {\n\tvar ip []byte\n\tswitch /*v4 or v6*/ {\n\tcase s.clusterCIDR.IP.To4() != nil:\n\t\t{\n\t\t\tj := uint32(index) \u003c\u003c uint32(32-s.nodeMaskSize)\n\t\t\tipInt := (binary.BigEndian.Uint32(s.clusterCIDR.IP)) | j\n\t\t\tip = make([]byte, net.IPv4len)\n\t\t\tbinary.BigEndian.PutUint32(ip, ipInt)\n\t\t}\n\tcase s.clusterCIDR.IP.To16() != nil:\n\t\t{\n\t\t\t// leftClusterIP | rightClusterIP\n\t\t\t// 2001:0DB8:1234:0000:0000:0000:0000:0000\n\t\t\tconst v6NBits = 128\n\t\t\tconst halfV6NBits = v6NBits / 2\n\t\t\tleftClusterIP := binary.BigEndian.Uint64(s.clusterCIDR.IP[:halfIPv6Len])\n\t\t\trightClusterIP := binary.BigEndian.Uint64(s.clusterCIDR.IP[halfIPv6Len:])\n\n\t\t\tip = make([]byte, net.IPv6len)\n\n\t\t\tif s.nodeMaskSize \u003c= halfV6NBits {\n\t\t\t\t// We only care about left side IP\n\t\t\t\tleftClusterIP |= uint64(index) \u003c\u003c uint(halfV6NBits-s.nodeMaskSize)\n\t\t\t} else {\n\t\t\t\tif s.clusterMaskSize \u003c halfV6NBits {\n\t\t\t\t\t// see how many bits are needed to reach the left side\n\t\t\t\t\tbtl := uint(s.nodeMaskSize - halfV6NBits)\n\t\t\t\t\tindexMaxBit := uint(64 - bits.LeadingZeros64(uint64(index)))\n\t\t\t\t\tif indexMaxBit \u003e btl {\n\t\t\t\t\t\tleftClusterIP |= uint64(index) \u003e\u003e btl\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// the right side will be calculated the same way either the\n\t\t\t\t// subNetMaskSize affects both left and right sides\n\t\t\t\trightClusterIP |= uint64(index) \u003c\u003c uint(v6NBits-s.nodeMaskSize)\n\t\t\t}\n\t\t\tbinary.BigEndian.PutUint64(ip[:halfIPv6Len], leftClusterIP)\n\t\t\tbinary.BigEndian.PutUint64(ip[halfIPv6Len:], rightClusterIP)\n\t\t}\n\t}\n\treturn \u0026net.IPNet{\n\t\tIP: ip,\n\t\tMask: s.nodeMask,\n\t}\n}","line":{"from":103,"to":148}} {"id":100004149,"name":"AllocateNext","signature":"func (s *CidrSet) AllocateNext() (*net.IPNet, error)","file":"pkg/controller/nodeipam/ipam/cidrset/cidr_set.go","code":"// AllocateNext allocates the next free CIDR range. This will set the range\n// as occupied and return the allocated range.\nfunc (s *CidrSet) AllocateNext() (*net.IPNet, error) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tif s.allocatedCIDRs == s.maxCIDRs {\n\t\treturn nil, ErrCIDRRangeNoCIDRsRemaining\n\t}\n\tcandidate := s.nextCandidate\n\tvar i int\n\tfor i = 0; i \u003c s.maxCIDRs; i++ {\n\t\tif s.used.Bit(candidate) == 0 {\n\t\t\tbreak\n\t\t}\n\t\tcandidate = (candidate + 1) % s.maxCIDRs\n\t}\n\n\ts.nextCandidate = (candidate + 1) % s.maxCIDRs\n\ts.used.SetBit(\u0026s.used, candidate, 1)\n\ts.allocatedCIDRs++\n\t// Update metrics\n\tcidrSetAllocations.WithLabelValues(s.label).Inc()\n\tcidrSetAllocationTriesPerRequest.WithLabelValues(s.label).Observe(float64(i))\n\tcidrSetUsage.WithLabelValues(s.label).Set(float64(s.allocatedCIDRs) / float64(s.maxCIDRs))\n\n\treturn s.indexToCIDRBlock(candidate), nil\n}","line":{"from":150,"to":177}} {"id":100004150,"name":"getBeginningAndEndIndices","signature":"func (s *CidrSet) getBeginningAndEndIndices(cidr *net.IPNet) (begin, end int, err error)","file":"pkg/controller/nodeipam/ipam/cidrset/cidr_set.go","code":"func (s *CidrSet) getBeginningAndEndIndices(cidr *net.IPNet) (begin, end int, err error) {\n\tif cidr == nil {\n\t\treturn -1, -1, fmt.Errorf(\"error getting indices for cluster cidr %v, cidr is nil\", s.clusterCIDR)\n\t}\n\tbegin, end = 0, s.maxCIDRs-1\n\tcidrMask := cidr.Mask\n\tmaskSize, _ := cidrMask.Size()\n\tvar ipSize int\n\n\tif !s.clusterCIDR.Contains(cidr.IP.Mask(s.clusterCIDR.Mask)) \u0026\u0026 !cidr.Contains(s.clusterCIDR.IP.Mask(cidr.Mask)) {\n\t\treturn -1, -1, fmt.Errorf(\"cidr %v is out the range of cluster cidr %v\", cidr, s.clusterCIDR)\n\t}\n\n\tif s.clusterMaskSize \u003c maskSize {\n\n\t\tipSize = net.IPv4len\n\t\tif cidr.IP.To4() == nil {\n\t\t\tipSize = net.IPv6len\n\t\t}\n\t\tbegin, err = s.getIndexForCIDR(\u0026net.IPNet{\n\t\t\tIP: cidr.IP.Mask(s.nodeMask),\n\t\t\tMask: s.nodeMask,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn -1, -1, err\n\t\t}\n\t\tip := make([]byte, ipSize)\n\t\tif cidr.IP.To4() != nil {\n\t\t\tipInt := binary.BigEndian.Uint32(cidr.IP) | (^binary.BigEndian.Uint32(cidr.Mask))\n\t\t\tbinary.BigEndian.PutUint32(ip, ipInt)\n\t\t} else {\n\t\t\t// ipIntLeft | ipIntRight\n\t\t\t// 2001:0DB8:1234:0000:0000:0000:0000:0000\n\t\t\tipIntLeft := binary.BigEndian.Uint64(cidr.IP[:net.IPv6len/2]) | (^binary.BigEndian.Uint64(cidr.Mask[:net.IPv6len/2]))\n\t\t\tipIntRight := binary.BigEndian.Uint64(cidr.IP[net.IPv6len/2:]) | (^binary.BigEndian.Uint64(cidr.Mask[net.IPv6len/2:]))\n\t\t\tbinary.BigEndian.PutUint64(ip[:net.IPv6len/2], ipIntLeft)\n\t\t\tbinary.BigEndian.PutUint64(ip[net.IPv6len/2:], ipIntRight)\n\t\t}\n\t\tend, err = s.getIndexForCIDR(\u0026net.IPNet{\n\t\t\tIP: net.IP(ip).Mask(s.nodeMask),\n\t\t\tMask: s.nodeMask,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn -1, -1, err\n\t\t}\n\t}\n\treturn begin, end, nil\n}","line":{"from":179,"to":226}} {"id":100004151,"name":"Release","signature":"func (s *CidrSet) Release(cidr *net.IPNet) error","file":"pkg/controller/nodeipam/ipam/cidrset/cidr_set.go","code":"// Release releases the given CIDR range.\nfunc (s *CidrSet) Release(cidr *net.IPNet) error {\n\tbegin, end, err := s.getBeginningAndEndIndices(cidr)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Lock()\n\tdefer s.Unlock()\n\tfor i := begin; i \u003c= end; i++ {\n\t\t// Only change the counters if we change the bit to prevent\n\t\t// double counting.\n\t\tif s.used.Bit(i) != 0 {\n\t\t\ts.used.SetBit(\u0026s.used, i, 0)\n\t\t\ts.allocatedCIDRs--\n\t\t\tcidrSetReleases.WithLabelValues(s.label).Inc()\n\t\t}\n\t}\n\n\tcidrSetUsage.WithLabelValues(s.label).Set(float64(s.allocatedCIDRs) / float64(s.maxCIDRs))\n\treturn nil\n}","line":{"from":228,"to":248}} {"id":100004152,"name":"Occupy","signature":"func (s *CidrSet) Occupy(cidr *net.IPNet) (err error)","file":"pkg/controller/nodeipam/ipam/cidrset/cidr_set.go","code":"// Occupy marks the given CIDR range as used. Occupy succeeds even if the CIDR\n// range was previously used.\nfunc (s *CidrSet) Occupy(cidr *net.IPNet) (err error) {\n\tbegin, end, err := s.getBeginningAndEndIndices(cidr)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Lock()\n\tdefer s.Unlock()\n\tfor i := begin; i \u003c= end; i++ {\n\t\t// Only change the counters if we change the bit to prevent\n\t\t// double counting.\n\t\tif s.used.Bit(i) == 0 {\n\t\t\ts.used.SetBit(\u0026s.used, i, 1)\n\t\t\ts.allocatedCIDRs++\n\t\t\tcidrSetAllocations.WithLabelValues(s.label).Inc()\n\t\t}\n\t}\n\n\tcidrSetUsage.WithLabelValues(s.label).Set(float64(s.allocatedCIDRs) / float64(s.maxCIDRs))\n\treturn nil\n}","line":{"from":250,"to":271}} {"id":100004153,"name":"getIndexForCIDR","signature":"func (s *CidrSet) getIndexForCIDR(cidr *net.IPNet) (int, error)","file":"pkg/controller/nodeipam/ipam/cidrset/cidr_set.go","code":"func (s *CidrSet) getIndexForCIDR(cidr *net.IPNet) (int, error) {\n\treturn s.getIndexForIP(cidr.IP)\n}","line":{"from":273,"to":275}} {"id":100004154,"name":"getIndexForIP","signature":"func (s *CidrSet) getIndexForIP(ip net.IP) (int, error)","file":"pkg/controller/nodeipam/ipam/cidrset/cidr_set.go","code":"func (s *CidrSet) getIndexForIP(ip net.IP) (int, error) {\n\tif ip.To4() != nil {\n\t\tcidrIndex := (binary.BigEndian.Uint32(s.clusterCIDR.IP) ^ binary.BigEndian.Uint32(ip.To4())) \u003e\u003e uint32(32-s.nodeMaskSize)\n\t\tif cidrIndex \u003e= uint32(s.maxCIDRs) {\n\t\t\treturn 0, fmt.Errorf(\"CIDR: %v/%v is out of the range of CIDR allocator\", ip, s.nodeMaskSize)\n\t\t}\n\t\treturn int(cidrIndex), nil\n\t}\n\tif ip.To16() != nil {\n\t\tbigIP := big.NewInt(0).SetBytes(s.clusterCIDR.IP)\n\t\tbigIP = bigIP.Xor(bigIP, big.NewInt(0).SetBytes(ip))\n\t\tcidrIndexBig := bigIP.Rsh(bigIP, uint(net.IPv6len*8-s.nodeMaskSize))\n\t\tcidrIndex := cidrIndexBig.Uint64()\n\t\tif cidrIndex \u003e= uint64(s.maxCIDRs) {\n\t\t\treturn 0, fmt.Errorf(\"CIDR: %v/%v is out of the range of CIDR allocator\", ip, s.nodeMaskSize)\n\t\t}\n\t\treturn int(cidrIndex), nil\n\t}\n\n\treturn 0, fmt.Errorf(\"invalid IP: %v\", ip)\n}","line":{"from":277,"to":297}} {"id":100004155,"name":"getMaxCIDRs","signature":"func getMaxCIDRs(subNetMaskSize, clusterMaskSize int) int","file":"pkg/controller/nodeipam/ipam/cidrset/cidr_set.go","code":"// getMaxCIDRs returns the max number of CIDRs that can be obtained by subdividing a mask of size `clusterMaskSize`\n// into subnets with mask of size `subNetMaskSize`.\nfunc getMaxCIDRs(subNetMaskSize, clusterMaskSize int) int {\n\treturn 1 \u003c\u003c uint32(subNetMaskSize-clusterMaskSize)\n}","line":{"from":299,"to":303}} {"id":100004156,"name":"registerCidrsetMetrics","signature":"func registerCidrsetMetrics()","file":"pkg/controller/nodeipam/ipam/cidrset/metrics.go","code":"// registerCidrsetMetrics the metrics that are to be monitored.\nfunc registerCidrsetMetrics() {\n\tregisterMetrics.Do(func() {\n\t\tlegacyregistry.MustRegister(cidrSetAllocations)\n\t\tlegacyregistry.MustRegister(cidrSetReleases)\n\t\tlegacyregistry.MustRegister(cidrSetMaxCidrs)\n\t\tlegacyregistry.MustRegister(cidrSetUsage)\n\t\tlegacyregistry.MustRegister(cidrSetAllocationTriesPerRequest)\n\t})\n}","line":{"from":80,"to":89}} {"id":100004157,"name":"NewCloudCIDRAllocator","signature":"func NewCloudCIDRAllocator(logger klog.Logger, client clientset.Interface, cloud cloudprovider.Interface, nodeInformer informers.NodeInformer) (CIDRAllocator, error)","file":"pkg/controller/nodeipam/ipam/cloud_cidr_allocator.go","code":"// NewCloudCIDRAllocator creates a new cloud CIDR allocator.\nfunc NewCloudCIDRAllocator(logger klog.Logger, client clientset.Interface, cloud cloudprovider.Interface, nodeInformer informers.NodeInformer) (CIDRAllocator, error) {\n\tif client == nil {\n\t\tlogger.Error(nil, \"kubeClient is nil when starting cloud CIDR allocator\")\n\t\tklog.FlushAndExit(klog.ExitFlushTimeout, 1)\n\t}\n\n\teventBroadcaster := record.NewBroadcaster()\n\trecorder := eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"cidrAllocator\"})\n\n\tgceCloud, ok := cloud.(*gce.Cloud)\n\tif !ok {\n\t\terr := fmt.Errorf(\"cloudCIDRAllocator does not support %v provider\", cloud.ProviderName())\n\t\treturn nil, err\n\t}\n\n\tca := \u0026cloudCIDRAllocator{\n\t\tclient: client,\n\t\tcloud: gceCloud,\n\t\tnodeLister: nodeInformer.Lister(),\n\t\tnodesSynced: nodeInformer.Informer().HasSynced,\n\t\tnodeUpdateChannel: make(chan string, cidrUpdateQueueSize),\n\t\tbroadcaster: eventBroadcaster,\n\t\trecorder: recorder,\n\t\tnodesInProcessing: map[string]*nodeProcessingInfo{},\n\t}\n\n\tnodeInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: controllerutil.CreateAddNodeHandler(\n\t\t\tfunc(node *v1.Node) error {\n\t\t\t\treturn ca.AllocateOrOccupyCIDR(logger, node)\n\t\t\t}),\n\t\tUpdateFunc: controllerutil.CreateUpdateNodeHandler(func(_, newNode *v1.Node) error {\n\t\t\tif newNode.Spec.PodCIDR == \"\" {\n\t\t\t\treturn ca.AllocateOrOccupyCIDR(logger, newNode)\n\t\t\t}\n\t\t\t// Even if PodCIDR is assigned, but NetworkUnavailable condition is\n\t\t\t// set to true, we need to process the node to set the condition.\n\t\t\tnetworkUnavailableTaint := \u0026v1.Taint{Key: v1.TaintNodeNetworkUnavailable, Effect: v1.TaintEffectNoSchedule}\n\t\t\t_, cond := controllerutil.GetNodeCondition(\u0026newNode.Status, v1.NodeNetworkUnavailable)\n\t\t\tif cond == nil || cond.Status != v1.ConditionFalse || utiltaints.TaintExists(newNode.Spec.Taints, networkUnavailableTaint) {\n\t\t\t\treturn ca.AllocateOrOccupyCIDR(logger, newNode)\n\t\t\t}\n\t\t\treturn nil\n\t\t}),\n\t\tDeleteFunc: controllerutil.CreateDeleteNodeHandler(func(node *v1.Node) error {\n\t\t\treturn ca.ReleaseCIDR(logger, node)\n\t\t}),\n\t})\n\tlogger.Info(\"Using cloud CIDR allocator\", \"provider\", cloud.ProviderName())\n\treturn ca, nil\n}","line":{"from":89,"to":140}} {"id":100004158,"name":"Run","signature":"func (ca *cloudCIDRAllocator) Run(ctx context.Context)","file":"pkg/controller/nodeipam/ipam/cloud_cidr_allocator.go","code":"func (ca *cloudCIDRAllocator) Run(ctx context.Context) {\n\tdefer utilruntime.HandleCrash()\n\n\t// Start event processing pipeline.\n\tca.broadcaster.StartStructuredLogging(0)\n\tlogger := klog.FromContext(ctx)\n\tlogger.Info(\"Sending events to api server\")\n\tca.broadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: ca.client.CoreV1().Events(\"\")})\n\tdefer ca.broadcaster.Shutdown()\n\n\tlogger.Info(\"Starting cloud CIDR allocator\")\n\tdefer logger.Info(\"Shutting down cloud CIDR allocator\")\n\n\tif !cache.WaitForNamedCacheSync(\"cidrallocator\", ctx.Done(), ca.nodesSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c cidrUpdateWorkers; i++ {\n\t\tgo ca.worker(ctx)\n\t}\n\n\t\u003c-ctx.Done()\n}","line":{"from":142,"to":164}} {"id":100004159,"name":"worker","signature":"func (ca *cloudCIDRAllocator) worker(ctx context.Context)","file":"pkg/controller/nodeipam/ipam/cloud_cidr_allocator.go","code":"func (ca *cloudCIDRAllocator) worker(ctx context.Context) {\n\tlogger := klog.FromContext(ctx)\n\tfor {\n\t\tselect {\n\t\tcase workItem, ok := \u003c-ca.nodeUpdateChannel:\n\t\t\tif !ok {\n\t\t\t\tlogger.Info(\"Channel nodeCIDRUpdateChannel was unexpectedly closed\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err := ca.updateCIDRAllocation(logger, workItem); err == nil {\n\t\t\t\tlogger.V(3).Info(\"Updated CIDR\", \"workItem\", workItem)\n\t\t\t} else {\n\t\t\t\tlogger.Error(err, \"Error updating CIDR\", \"workItem\", workItem)\n\t\t\t\tif canRetry, timeout := ca.retryParams(logger, workItem); canRetry {\n\t\t\t\t\tlogger.V(2).Info(\"Retrying update on next period\", \"workItem\", workItem, \"timeout\", timeout)\n\t\t\t\t\ttime.AfterFunc(timeout, func() {\n\t\t\t\t\t\t// Requeue the failed node for update again.\n\t\t\t\t\t\tca.nodeUpdateChannel \u003c- workItem\n\t\t\t\t\t})\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tlogger.Error(nil, \"Exceeded retry count, dropping from queue\", \"workItem\", workItem)\n\t\t\t}\n\t\t\tca.removeNodeFromProcessing(workItem)\n\t\tcase \u003c-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}","line":{"from":166,"to":194}} {"id":100004160,"name":"insertNodeToProcessing","signature":"func (ca *cloudCIDRAllocator) insertNodeToProcessing(nodeName string) bool","file":"pkg/controller/nodeipam/ipam/cloud_cidr_allocator.go","code":"func (ca *cloudCIDRAllocator) insertNodeToProcessing(nodeName string) bool {\n\tca.lock.Lock()\n\tdefer ca.lock.Unlock()\n\tif _, found := ca.nodesInProcessing[nodeName]; found {\n\t\treturn false\n\t}\n\tca.nodesInProcessing[nodeName] = \u0026nodeProcessingInfo{}\n\treturn true\n}","line":{"from":196,"to":204}} {"id":100004161,"name":"retryParams","signature":"func (ca *cloudCIDRAllocator) retryParams(logger klog.Logger, nodeName string) (bool, time.Duration)","file":"pkg/controller/nodeipam/ipam/cloud_cidr_allocator.go","code":"func (ca *cloudCIDRAllocator) retryParams(logger klog.Logger, nodeName string) (bool, time.Duration) {\n\tca.lock.Lock()\n\tdefer ca.lock.Unlock()\n\n\tentry, ok := ca.nodesInProcessing[nodeName]\n\tif !ok {\n\t\tlogger.Error(nil, \"Cannot get retryParams for node as entry does not exist\", \"node\", klog.KRef(\"\", nodeName))\n\t\treturn false, 0\n\t}\n\n\tcount := entry.retries + 1\n\tif count \u003e updateMaxRetries {\n\t\treturn false, 0\n\t}\n\tca.nodesInProcessing[nodeName].retries = count\n\n\treturn true, nodeUpdateRetryTimeout(count)\n}","line":{"from":206,"to":223}} {"id":100004162,"name":"nodeUpdateRetryTimeout","signature":"func nodeUpdateRetryTimeout(count int) time.Duration","file":"pkg/controller/nodeipam/ipam/cloud_cidr_allocator.go","code":"func nodeUpdateRetryTimeout(count int) time.Duration {\n\ttimeout := updateRetryTimeout\n\tfor i := 0; i \u003c count \u0026\u0026 timeout \u003c maxUpdateRetryTimeout; i++ {\n\t\ttimeout *= 2\n\t}\n\tif timeout \u003e maxUpdateRetryTimeout {\n\t\ttimeout = maxUpdateRetryTimeout\n\t}\n\treturn time.Duration(timeout.Nanoseconds()/2 + rand.Int63n(timeout.Nanoseconds()))\n}","line":{"from":225,"to":234}} {"id":100004163,"name":"removeNodeFromProcessing","signature":"func (ca *cloudCIDRAllocator) removeNodeFromProcessing(nodeName string)","file":"pkg/controller/nodeipam/ipam/cloud_cidr_allocator.go","code":"func (ca *cloudCIDRAllocator) removeNodeFromProcessing(nodeName string) {\n\tca.lock.Lock()\n\tdefer ca.lock.Unlock()\n\tdelete(ca.nodesInProcessing, nodeName)\n}","line":{"from":236,"to":240}} {"id":100004164,"name":"AllocateOrOccupyCIDR","signature":"func (ca *cloudCIDRAllocator) AllocateOrOccupyCIDR(logger klog.Logger, node *v1.Node) error","file":"pkg/controller/nodeipam/ipam/cloud_cidr_allocator.go","code":"// WARNING: If you're adding any return calls or defer any more work from this\n// function you have to make sure to update nodesInProcessing properly with the\n// disposition of the node when the work is done.\nfunc (ca *cloudCIDRAllocator) AllocateOrOccupyCIDR(logger klog.Logger, node *v1.Node) error {\n\tif node == nil {\n\t\treturn nil\n\t}\n\tif !ca.insertNodeToProcessing(node.Name) {\n\t\tlogger.V(2).Info(\"Node is already in a process of CIDR assignment\", \"node\", klog.KObj(node))\n\t\treturn nil\n\t}\n\n\tlogger.V(4).Info(\"Putting node into the work queue\", \"node\", klog.KObj(node))\n\tca.nodeUpdateChannel \u003c- node.Name\n\treturn nil\n}","line":{"from":242,"to":257}} {"id":100004165,"name":"updateCIDRAllocation","signature":"func (ca *cloudCIDRAllocator) updateCIDRAllocation(logger klog.Logger, nodeName string) error","file":"pkg/controller/nodeipam/ipam/cloud_cidr_allocator.go","code":"// updateCIDRAllocation assigns CIDR to Node and sends an update to the API server.\nfunc (ca *cloudCIDRAllocator) updateCIDRAllocation(logger klog.Logger, nodeName string) error {\n\tnode, err := ca.nodeLister.Get(nodeName)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\treturn nil // node no longer available, skip processing\n\t\t}\n\t\tlogger.Error(err, \"Failed while getting the node for updating Node.Spec.PodCIDR\", \"node\", klog.KRef(\"\", nodeName))\n\t\treturn err\n\t}\n\tif node.Spec.ProviderID == \"\" {\n\t\treturn fmt.Errorf(\"node %s doesn't have providerID\", nodeName)\n\t}\n\n\tcidrStrings, err := ca.cloud.AliasRangesByProviderID(node.Spec.ProviderID)\n\tif err != nil {\n\t\tcontrollerutil.RecordNodeStatusChange(ca.recorder, node, \"CIDRNotAvailable\")\n\t\treturn fmt.Errorf(\"failed to get cidr(s) from provider: %v\", err)\n\t}\n\tif len(cidrStrings) == 0 {\n\t\tcontrollerutil.RecordNodeStatusChange(ca.recorder, node, \"CIDRNotAvailable\")\n\t\treturn fmt.Errorf(\"failed to allocate cidr: Node %v has no CIDRs\", node.Name)\n\t}\n\t//Can have at most 2 ips (one for v4 and one for v6)\n\tif len(cidrStrings) \u003e 2 {\n\t\tlogger.Info(\"Got more than 2 ips, truncating to 2\", \"cidrStrings\", cidrStrings)\n\t\tcidrStrings = cidrStrings[:2]\n\t}\n\n\tcidrs, err := netutils.ParseCIDRs(cidrStrings)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse strings %v as CIDRs: %v\", cidrStrings, err)\n\t}\n\n\tneedUpdate, err := needPodCIDRsUpdate(logger, node, cidrs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"err: %v, CIDRS: %v\", err, cidrStrings)\n\t}\n\tif needUpdate {\n\t\tif node.Spec.PodCIDR != \"\" {\n\t\t\tlogger.Error(nil, \"PodCIDR being reassigned\", \"node\", klog.KObj(node), \"podCIDRs\", node.Spec.PodCIDRs, \"cidrStrings\", cidrStrings)\n\t\t\t// We fall through and set the CIDR despite this error. This\n\t\t\t// implements the same logic as implemented in the\n\t\t\t// rangeAllocator.\n\t\t\t//\n\t\t\t// See https://github.com/kubernetes/kubernetes/pull/42147#discussion_r103357248\n\t\t}\n\t\tfor i := 0; i \u003c cidrUpdateRetries; i++ {\n\t\t\tif err = nodeutil.PatchNodeCIDRs(ca.client, types.NodeName(node.Name), cidrStrings); err == nil {\n\t\t\t\tlogger.Info(\"Set the node PodCIDRs\", \"node\", klog.KObj(node), \"cidrStrings\", cidrStrings)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif err != nil {\n\t\tcontrollerutil.RecordNodeStatusChange(ca.recorder, node, \"CIDRAssignmentFailed\")\n\t\tlogger.Error(err, \"Failed to update the node PodCIDR after multiple attempts\", \"node\", klog.KObj(node), \"cidrStrings\", cidrStrings)\n\t\treturn err\n\t}\n\n\terr = nodeutil.SetNodeCondition(ca.client, types.NodeName(node.Name), v1.NodeCondition{\n\t\tType: v1.NodeNetworkUnavailable,\n\t\tStatus: v1.ConditionFalse,\n\t\tReason: \"RouteCreated\",\n\t\tMessage: \"NodeController create implicit route\",\n\t\tLastTransitionTime: metav1.Now(),\n\t})\n\tif err != nil {\n\t\tlogger.Error(err, \"Error setting route status for the node\", \"node\", klog.KObj(node))\n\t}\n\treturn err\n}","line":{"from":259,"to":330}} {"id":100004166,"name":"needPodCIDRsUpdate","signature":"func needPodCIDRsUpdate(logger klog.Logger, node *v1.Node, podCIDRs []*net.IPNet) (bool, error)","file":"pkg/controller/nodeipam/ipam/cloud_cidr_allocator.go","code":"func needPodCIDRsUpdate(logger klog.Logger, node *v1.Node, podCIDRs []*net.IPNet) (bool, error) {\n\tif node.Spec.PodCIDR == \"\" {\n\t\treturn true, nil\n\t}\n\t_, nodePodCIDR, err := netutils.ParseCIDRSloppy(node.Spec.PodCIDR)\n\tif err != nil {\n\t\tlogger.Error(err, \"Found invalid node.Spec.PodCIDR\", \"podCIDR\", node.Spec.PodCIDR)\n\t\t// We will try to overwrite with new CIDR(s)\n\t\treturn true, nil\n\t}\n\tnodePodCIDRs, err := netutils.ParseCIDRs(node.Spec.PodCIDRs)\n\tif err != nil {\n\t\tlogger.Error(err, \"Found invalid node.Spec.PodCIDRs\", \"podCIDRs\", node.Spec.PodCIDRs)\n\t\t// We will try to overwrite with new CIDR(s)\n\t\treturn true, nil\n\t}\n\n\tif len(podCIDRs) == 1 {\n\t\tif cmp.Equal(nodePodCIDR, podCIDRs[0]) {\n\t\t\tlogger.V(4).Info(\"Node already has allocated CIDR. It matches the proposed one\", \"node\", klog.KObj(node), \"podCIDR\", podCIDRs[0])\n\t\t\treturn false, nil\n\t\t}\n\t} else if len(nodePodCIDRs) == len(podCIDRs) {\n\t\tif dualStack, _ := netutils.IsDualStackCIDRs(podCIDRs); !dualStack {\n\t\t\treturn false, fmt.Errorf(\"IPs are not dual stack\")\n\t\t}\n\t\tfor idx, cidr := range podCIDRs {\n\t\t\tif !cmp.Equal(nodePodCIDRs[idx], cidr) {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\t\tlogger.V(4).Info(\"Node already has allocated CIDRs. It matches the proposed one\", \"node\", klog.KObj(node), \"podCIDRs\", podCIDRs)\n\t\treturn false, nil\n\t}\n\n\treturn true, nil\n}","line":{"from":332,"to":368}} {"id":100004167,"name":"ReleaseCIDR","signature":"func (ca *cloudCIDRAllocator) ReleaseCIDR(logger klog.Logger, node *v1.Node) error","file":"pkg/controller/nodeipam/ipam/cloud_cidr_allocator.go","code":"func (ca *cloudCIDRAllocator) ReleaseCIDR(logger klog.Logger, node *v1.Node) error {\n\tlogger.V(2).Info(\"Node's PodCIDR will be released by external cloud provider (not managed by controller)\",\n\t\t\"node\", klog.KObj(node), \"podCIDR\", node.Spec.PodCIDR)\n\treturn nil\n}","line":{"from":370,"to":374}} {"id":100004168,"name":"NewCloudCIDRAllocator","signature":"func NewCloudCIDRAllocator(logger klog.Logger, client clientset.Interface, cloud cloudprovider.Interface, nodeInformer informers.NodeInformer) (CIDRAllocator, error)","file":"pkg/controller/nodeipam/ipam/cloud_cidr_allocator_nolegacyproviders.go","code":"// NewCloudCIDRAllocator creates a new cloud CIDR allocator.\nfunc NewCloudCIDRAllocator(logger klog.Logger, client clientset.Interface, cloud cloudprovider.Interface, nodeInformer informers.NodeInformer) (CIDRAllocator, error) {\n\treturn nil, errors.New(\"legacy cloud provider support not built\")\n}","line":{"from":31,"to":34}} {"id":100004169,"name":"NewController","signature":"func NewController(","file":"pkg/controller/nodeipam/ipam/controller_legacyprovider.go","code":"// NewController returns a new instance of the IPAM controller.\nfunc NewController(\n\tconfig *Config,\n\tkubeClient clientset.Interface,\n\tcloud cloudprovider.Interface,\n\tclusterCIDR, serviceCIDR *net.IPNet,\n\tnodeCIDRMaskSize int) (*Controller, error) {\n\n\tif !nodesync.IsValidMode(config.Mode) {\n\t\treturn nil, fmt.Errorf(\"invalid IPAM controller mode %q\", config.Mode)\n\t}\n\n\tgceCloud, ok := cloud.(*gce.Cloud)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"cloud IPAM controller does not support %q provider\", cloud.ProviderName())\n\t}\n\n\tset, err := cidrset.NewCIDRSet(clusterCIDR, nodeCIDRMaskSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc := \u0026Controller{\n\t\tconfig: config,\n\t\tadapter: newAdapter(kubeClient, gceCloud),\n\t\tsyncers: make(map[string]*nodesync.NodeSync),\n\t\tset: set,\n\t}\n\n\tif err := occupyServiceCIDR(c.set, clusterCIDR, serviceCIDR); err != nil {\n\t\treturn nil, err\n\t}\n\n\t//check whether there is a remaining cidr after occupyServiceCIDR\n\tcidr, err := c.set.AllocateNext()\n\tswitch err {\n\tcase cidrset.ErrCIDRRangeNoCIDRsRemaining:\n\t\treturn nil, fmt.Errorf(\"failed after occupy serviceCIDR: %v\", err)\n\tcase nil:\n\t\terr := c.set.Release(cidr)\n\t\treturn c, err\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unexpected error when check remaining CIDR range: %v\", err)\n\t}\n}","line":{"from":68,"to":112}} {"id":100004170,"name":"Start","signature":"func (c *Controller) Start(logger klog.Logger, nodeInformer informers.NodeInformer) error","file":"pkg/controller/nodeipam/ipam/controller_legacyprovider.go","code":"// Start initializes the Controller with the existing list of nodes and\n// registers the informers for node changes. This will start synchronization\n// of the node and cloud CIDR range allocations.\nfunc (c *Controller) Start(logger klog.Logger, nodeInformer informers.NodeInformer) error {\n\tlogger.Info(\"Starting IPAM controller\", \"config\", c.config)\n\n\tnodes, err := listNodes(logger, c.adapter.k8s)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, node := range nodes.Items {\n\t\tif node.Spec.PodCIDR != \"\" {\n\t\t\t_, cidrRange, err := netutils.ParseCIDRSloppy(node.Spec.PodCIDR)\n\t\t\tif err == nil {\n\t\t\t\tc.set.Occupy(cidrRange)\n\t\t\t\tlogger.V(3).Info(\"Occupying CIDR for node\", \"CIDR\", node.Spec.PodCIDR, \"node\", klog.KObj(\u0026node))\n\t\t\t} else {\n\t\t\t\tlogger.Error(err, \"Node has an invalid CIDR\", \"node\", klog.KObj(\u0026node), \"CIDR\", node.Spec.PodCIDR)\n\t\t\t}\n\t\t}\n\n\t\tfunc() {\n\t\t\tc.lock.Lock()\n\t\t\tdefer c.lock.Unlock()\n\n\t\t\t// XXX/bowei -- stagger the start of each sync cycle.\n\t\t\tsyncer := c.newSyncer(node.Name)\n\t\t\tc.syncers[node.Name] = syncer\n\t\t\tgo syncer.Loop(logger, nil)\n\t\t}()\n\t}\n\n\tnodeInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: controllerutil.CreateAddNodeHandler(func(node *v1.Node) error {\n\t\t\treturn c.onAdd(logger, node)\n\t\t}),\n\t\tUpdateFunc: controllerutil.CreateUpdateNodeHandler(func(_, newNode *v1.Node) error {\n\t\t\treturn c.onUpdate(logger, newNode)\n\t\t}),\n\t\tDeleteFunc: controllerutil.CreateDeleteNodeHandler(func(node *v1.Node) error {\n\t\t\treturn c.onDelete(logger, node)\n\t\t}),\n\t})\n\n\treturn nil\n}","line":{"from":114,"to":159}} {"id":100004171,"name":"Run","signature":"func (c *Controller) Run(ctx context.Context)","file":"pkg/controller/nodeipam/ipam/controller_legacyprovider.go","code":"func (c *Controller) Run(ctx context.Context) {\n\tdefer utilruntime.HandleCrash()\n\n\tgo c.adapter.Run(ctx)\n\t\u003c-ctx.Done()\n}","line":{"from":161,"to":166}} {"id":100004172,"name":"occupyServiceCIDR","signature":"func occupyServiceCIDR(set *cidrset.CidrSet, clusterCIDR, serviceCIDR *net.IPNet) error","file":"pkg/controller/nodeipam/ipam/controller_legacyprovider.go","code":"// occupyServiceCIDR removes the service CIDR range from the cluster CIDR if it\n// intersects.\nfunc occupyServiceCIDR(set *cidrset.CidrSet, clusterCIDR, serviceCIDR *net.IPNet) error {\n\tif clusterCIDR.Contains(serviceCIDR.IP) || serviceCIDR.Contains(clusterCIDR.IP) {\n\t\tif err := set.Occupy(serviceCIDR); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":168,"to":177}} {"id":100004173,"name":"ReportResult","signature":"func (ns *nodeState) ReportResult(err error)","file":"pkg/controller/nodeipam/ipam/controller_legacyprovider.go","code":"func (ns *nodeState) ReportResult(err error) {\n\tns.t.Update(err == nil)\n}","line":{"from":183,"to":185}} {"id":100004174,"name":"ResyncTimeout","signature":"func (ns *nodeState) ResyncTimeout() time.Duration","file":"pkg/controller/nodeipam/ipam/controller_legacyprovider.go","code":"func (ns *nodeState) ResyncTimeout() time.Duration {\n\treturn ns.t.Next()\n}","line":{"from":187,"to":189}} {"id":100004175,"name":"newSyncer","signature":"func (c *Controller) newSyncer(name string) *nodesync.NodeSync","file":"pkg/controller/nodeipam/ipam/controller_legacyprovider.go","code":"func (c *Controller) newSyncer(name string) *nodesync.NodeSync {\n\tns := \u0026nodeState{\n\t\tTimeout{\n\t\t\tResync: c.config.Resync,\n\t\t\tMaxBackoff: c.config.MaxBackoff,\n\t\t\tInitialRetry: c.config.InitialRetry,\n\t\t},\n\t}\n\treturn nodesync.New(ns, c.adapter, c.adapter, c.config.Mode, name, c.set)\n}","line":{"from":191,"to":200}} {"id":100004176,"name":"onAdd","signature":"func (c *Controller) onAdd(logger klog.Logger, node *v1.Node) error","file":"pkg/controller/nodeipam/ipam/controller_legacyprovider.go","code":"func (c *Controller) onAdd(logger klog.Logger, node *v1.Node) error {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tsyncer, ok := c.syncers[node.Name]\n\tif !ok {\n\t\tsyncer = c.newSyncer(node.Name)\n\t\tc.syncers[node.Name] = syncer\n\t\tgo syncer.Loop(logger, nil)\n\t} else {\n\t\tlogger.Info(\"Add for node that already exists\", \"node\", klog.KObj(node))\n\t}\n\tsyncer.Update(node)\n\n\treturn nil\n}","line":{"from":202,"to":217}} {"id":100004177,"name":"onUpdate","signature":"func (c *Controller) onUpdate(logger klog.Logger, node *v1.Node) error","file":"pkg/controller/nodeipam/ipam/controller_legacyprovider.go","code":"func (c *Controller) onUpdate(logger klog.Logger, node *v1.Node) error {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tif sync, ok := c.syncers[node.Name]; ok {\n\t\tsync.Update(node)\n\t} else {\n\t\tlogger.Error(nil, \"Received update for non-existent node\", \"node\", klog.KObj(node))\n\t\treturn fmt.Errorf(\"unknown node %q\", node.Name)\n\t}\n\n\treturn nil\n}","line":{"from":219,"to":231}} {"id":100004178,"name":"onDelete","signature":"func (c *Controller) onDelete(logger klog.Logger, node *v1.Node) error","file":"pkg/controller/nodeipam/ipam/controller_legacyprovider.go","code":"func (c *Controller) onDelete(logger klog.Logger, node *v1.Node) error {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tif syncer, ok := c.syncers[node.Name]; ok {\n\t\tsyncer.Delete(node)\n\t\tdelete(c.syncers, node.Name)\n\t} else {\n\t\tlogger.Info(\"Node was already deleted\", \"node\", klog.KObj(node))\n\t}\n\n\treturn nil\n}","line":{"from":233,"to":245}} {"id":100004179,"name":"Len","signature":"func (pq PriorityQueue) Len() int { return len(pq) }","file":"pkg/controller/nodeipam/ipam/multi_cidr_priority_queue.go","code":"func (pq PriorityQueue) Len() int { return len(pq) }","line":{"from":41,"to":41}} {"id":100004180,"name":"Less","signature":"func (pq PriorityQueue) Less(i, j int) bool","file":"pkg/controller/nodeipam/ipam/multi_cidr_priority_queue.go","code":"// Less compares the priority queue items, to store in a min heap.\n// Less(i,j) == true denotes i has higher priority than j.\nfunc (pq PriorityQueue) Less(i, j int) bool {\n\tif pq[i].labelMatchCount != pq[j].labelMatchCount {\n\t\t// P0: CidrSet with higher number of matching labels has the highest priority.\n\t\treturn pq[i].labelMatchCount \u003e pq[j].labelMatchCount\n\t}\n\n\t// If the count of matching labels is equal, compare the max allocatable pod CIDRs.\n\tif pq[i].maxAllocatable() != pq[j].maxAllocatable() {\n\t\t// P1: CidrSet with fewer allocatable pod CIDRs has higher priority.\n\t\treturn pq[i].maxAllocatable() \u003c pq[j].maxAllocatable()\n\t}\n\n\t// If the value of allocatable pod CIDRs is equal, compare the node mask size.\n\tif pq[i].nodeMaskSize() != pq[j].nodeMaskSize() {\n\t\t// P2: CidrSet with a PerNodeMaskSize having fewer IPs has higher priority.\n\t\t// For example, `27` (32 IPs) picked before `25` (128 IPs).\n\t\treturn pq[i].nodeMaskSize() \u003e pq[j].nodeMaskSize()\n\t}\n\n\t// If the per node mask size are equal compare the CIDR labels.\n\tif pq[i].selectorString != pq[j].selectorString {\n\t\t// P3: CidrSet having label with lower alphanumeric value has higher priority.\n\t\treturn pq[i].selectorString \u003c pq[j].selectorString\n\t}\n\n\t// P4: CidrSet having an alpha-numerically smaller IP address value has a higher priority.\n\treturn pq[i].cidrLabel() \u003c pq[j].cidrLabel()\n}","line":{"from":43,"to":72}} {"id":100004181,"name":"Swap","signature":"func (pq PriorityQueue) Swap(i, j int)","file":"pkg/controller/nodeipam/ipam/multi_cidr_priority_queue.go","code":"func (pq PriorityQueue) Swap(i, j int) {\n\tpq[i], pq[j] = pq[j], pq[i]\n\tpq[i].index = i\n\tpq[j].index = j\n}","line":{"from":74,"to":78}} {"id":100004182,"name":"Push","signature":"func (pq *PriorityQueue) Push(x interface{})","file":"pkg/controller/nodeipam/ipam/multi_cidr_priority_queue.go","code":"func (pq *PriorityQueue) Push(x interface{}) {\n\tn := len(*pq)\n\tif item, ok := x.(*PriorityQueueItem); ok {\n\t\titem.index = n\n\t\t*pq = append(*pq, item)\n\t}\n}","line":{"from":80,"to":86}} {"id":100004183,"name":"Pop","signature":"func (pq *PriorityQueue) Pop() interface{}","file":"pkg/controller/nodeipam/ipam/multi_cidr_priority_queue.go","code":"func (pq *PriorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil // avoid memory leak.\n\titem.index = -1 // for safety.\n\t*pq = old[0 : n-1]\n\treturn item\n}","line":{"from":88,"to":96}} {"id":100004184,"name":"maxAllocatable","signature":"func (pqi *PriorityQueueItem) maxAllocatable() int","file":"pkg/controller/nodeipam/ipam/multi_cidr_priority_queue.go","code":"// maxAllocatable computes the minimum value of the MaxCIDRs for a ClusterCIDR.\n// It compares the MaxCIDRs for each CIDR family and returns the minimum.\n// e.g. IPv4 - 10.0.0.0/16 PerNodeMaskSize: 24 MaxCIDRs = 256\n// IPv6 - ff:ff::/120 PerNodeMaskSize: 120 MaxCIDRs = 1\n// MaxAllocatable for this ClusterCIDR = 1\nfunc (pqi *PriorityQueueItem) maxAllocatable() int {\n\tipv4Allocatable := math.MaxInt\n\tipv6Allocatable := math.MaxInt\n\n\tif pqi.clusterCIDR.IPv4CIDRSet != nil {\n\t\tipv4Allocatable = pqi.clusterCIDR.IPv4CIDRSet.MaxCIDRs\n\t}\n\n\tif pqi.clusterCIDR.IPv6CIDRSet != nil {\n\t\tipv6Allocatable = pqi.clusterCIDR.IPv6CIDRSet.MaxCIDRs\n\t}\n\n\tif ipv4Allocatable \u003c ipv6Allocatable {\n\t\treturn ipv4Allocatable\n\t}\n\n\treturn ipv6Allocatable\n}","line":{"from":98,"to":120}} {"id":100004185,"name":"nodeMaskSize","signature":"func (pqi *PriorityQueueItem) nodeMaskSize() int","file":"pkg/controller/nodeipam/ipam/multi_cidr_priority_queue.go","code":"// nodeMaskSize returns IPv4 NodeMaskSize if present, else returns IPv6 NodeMaskSize.\n// Note the requirement: 32 - IPv4 NodeMaskSize == 128 - IPv6 NodeMaskSize\n// Due to the above requirement it does not matter which NodeMaskSize we compare.\nfunc (pqi *PriorityQueueItem) nodeMaskSize() int {\n\tif pqi.clusterCIDR.IPv4CIDRSet != nil {\n\t\treturn pqi.clusterCIDR.IPv4CIDRSet.NodeMaskSize\n\t}\n\n\treturn pqi.clusterCIDR.IPv6CIDRSet.NodeMaskSize\n}","line":{"from":122,"to":131}} {"id":100004186,"name":"cidrLabel","signature":"func (pqi *PriorityQueueItem) cidrLabel() string","file":"pkg/controller/nodeipam/ipam/multi_cidr_priority_queue.go","code":"// cidrLabel returns IPv4 CIDR if present, else returns IPv6 CIDR.\nfunc (pqi *PriorityQueueItem) cidrLabel() string {\n\tif pqi.clusterCIDR.IPv4CIDRSet != nil {\n\t\treturn pqi.clusterCIDR.IPv4CIDRSet.Label\n\t}\n\n\treturn pqi.clusterCIDR.IPv6CIDRSet.Label\n}","line":{"from":133,"to":140}} {"id":100004187,"name":"NewMultiCIDRRangeAllocator","signature":"func NewMultiCIDRRangeAllocator(","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// NewMultiCIDRRangeAllocator returns a CIDRAllocator to allocate CIDRs for node (one for each ip family).\n// Caller must always pass in a list of existing nodes to the new allocator.\n// NodeList is only nil in testing.\nfunc NewMultiCIDRRangeAllocator(\n\tctx context.Context,\n\tclient clientset.Interface,\n\tnodeInformer informers.NodeInformer,\n\tclusterCIDRInformer networkinginformers.ClusterCIDRInformer,\n\tallocatorParams CIDRAllocatorParams,\n\tnodeList *v1.NodeList,\n\ttestCIDRMap map[string][]*cidrset.ClusterCIDR,\n) (CIDRAllocator, error) {\n\tlogger := klog.FromContext(ctx)\n\tif client == nil {\n\t\tlogger.Error(nil, \"kubeClient is nil when starting multi CIDRRangeAllocator\")\n\t\tklog.FlushAndExit(klog.ExitFlushTimeout, 1)\n\t}\n\n\teventBroadcaster := record.NewBroadcaster()\n\teventSource := v1.EventSource{\n\t\tComponent: \"multiCIDRRangeAllocator\",\n\t}\n\trecorder := eventBroadcaster.NewRecorder(scheme.Scheme, eventSource)\n\n\tra := \u0026multiCIDRRangeAllocator{\n\t\tclient: client,\n\t\tnodeLister: nodeInformer.Lister(),\n\t\tnodesSynced: nodeInformer.Informer().HasSynced,\n\t\tclusterCIDRLister: clusterCIDRInformer.Lister(),\n\t\tclusterCIDRSynced: clusterCIDRInformer.Informer().HasSynced,\n\t\tnodeCIDRUpdateChannel: make(chan multiCIDRNodeReservedCIDRs, cidrUpdateQueueSize),\n\t\tbroadcaster: eventBroadcaster,\n\t\trecorder: recorder,\n\t\tcidrQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"multi_cidr_range_allocator_cidr\"),\n\t\tnodeQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"multi_cidr_range_allocator_node\"),\n\t\tlock: \u0026sync.Mutex{},\n\t\tcidrMap: make(map[string][]*cidrset.ClusterCIDR, 0),\n\t}\n\n\t// testCIDRMap is only set for testing purposes.\n\tif len(testCIDRMap) \u003e 0 {\n\t\tra.cidrMap = testCIDRMap\n\t\tlogger.Info(\"TestCIDRMap should only be set for testing purposes, if this is seen in production logs, it might be a misconfiguration or a bug\")\n\t}\n\n\tccList, err := listClusterCIDRs(ctx, client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif ccList == nil {\n\t\tccList = \u0026networkingv1alpha1.ClusterCIDRList{}\n\t}\n\tcreateDefaultClusterCIDR(logger, ccList, allocatorParams)\n\n\t// Regenerate the cidrMaps from the existing ClusterCIDRs.\n\tfor _, clusterCIDR := range ccList.Items {\n\t\tlogger.Info(\"Regenerating existing ClusterCIDR\", \"clusterCIDR\", clusterCIDR)\n\t\t// Create an event for invalid ClusterCIDRs, do not crash on failures.\n\t\tif err := ra.reconcileBootstrap(ctx, \u0026clusterCIDR); err != nil {\n\t\t\tlogger.Error(err, \"Error while regenerating existing ClusterCIDR\")\n\t\t\tra.recorder.Event(\u0026clusterCIDR, \"Warning\", \"InvalidClusterCIDR encountered while regenerating ClusterCIDR during bootstrap.\", err.Error())\n\t\t}\n\t}\n\n\tclusterCIDRInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tkey, err := cache.MetaNamespaceKeyFunc(obj)\n\t\t\tif err == nil {\n\t\t\t\tra.cidrQueue.Add(key)\n\t\t\t}\n\t\t},\n\t\tUpdateFunc: func(old, new interface{}) {\n\t\t\tkey, err := cache.MetaNamespaceKeyFunc(new)\n\t\t\tif err == nil {\n\t\t\t\tra.cidrQueue.Add(key)\n\t\t\t}\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\t// IndexerInformer uses a delta nodeQueue, therefore for deletes we have to use this\n\t\t\t// key function.\n\t\t\tkey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)\n\t\t\tif err == nil {\n\t\t\t\tra.cidrQueue.Add(key)\n\t\t\t}\n\t\t},\n\t})\n\n\tif allocatorParams.ServiceCIDR != nil {\n\t\tra.filterOutServiceRange(logger, allocatorParams.ServiceCIDR)\n\t} else {\n\t\tlogger.Info(\"No Service CIDR provided. Skipping filtering out service addresses\")\n\t}\n\n\tif allocatorParams.SecondaryServiceCIDR != nil {\n\t\tra.filterOutServiceRange(logger, allocatorParams.SecondaryServiceCIDR)\n\t} else {\n\t\tlogger.Info(\"No Secondary Service CIDR provided. Skipping filtering out secondary service addresses\")\n\t}\n\n\tif nodeList != nil {\n\t\tfor _, node := range nodeList.Items {\n\t\t\tif len(node.Spec.PodCIDRs) == 0 {\n\t\t\t\tlogger.V(4).Info(\"Node has no CIDR, ignoring\", \"node\", klog.KObj(\u0026node))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlogger.Info(\"Node has CIDR, occupying it in CIDR map\", \"node\", klog.KObj(\u0026node), \"podCIDRs\", node.Spec.PodCIDRs)\n\t\t\tif err := ra.occupyCIDRs(logger, \u0026node); err != nil {\n\t\t\t\t// This will happen if:\n\t\t\t\t// 1. We find garbage in the podCIDRs field. Retrying is useless.\n\t\t\t\t// 2. CIDR out of range: This means ClusterCIDR is not yet created\n\t\t\t\t// This error will keep crashing controller-manager until the\n\t\t\t\t// appropriate ClusterCIDR has been created\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\tnodeInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tkey, err := cache.MetaNamespaceKeyFunc(obj)\n\t\t\tif err == nil {\n\t\t\t\tra.nodeQueue.Add(key)\n\t\t\t}\n\t\t},\n\t\tUpdateFunc: func(old, new interface{}) {\n\t\t\tkey, err := cache.MetaNamespaceKeyFunc(new)\n\t\t\tif err == nil {\n\t\t\t\tra.nodeQueue.Add(key)\n\t\t\t}\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\t// The informer cache no longer has the object, and since Node doesn't have a finalizer,\n\t\t\t// we don't see the Update with DeletionTimestamp != 0.\n\t\t\t// TODO: instead of executing the operation directly in the handler, build a small cache with key node.Name\n\t\t\t// and value PodCIDRs use ReleaseCIDR on the reconcile loop so we can retry on `ReleaseCIDR` failures.\n\t\t\tra.ReleaseCIDR(logger, obj.(*v1.Node))\n\t\t\t// IndexerInformer uses a delta nodeQueue, therefore for deletes we have to use this\n\t\t\t// key function.\n\t\t\tkey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)\n\t\t\tif err == nil {\n\t\t\t\tra.nodeQueue.Add(key)\n\t\t\t}\n\t\t},\n\t})\n\n\treturn ra, nil\n}","line":{"from":101,"to":248}} {"id":100004188,"name":"Run","signature":"func (r *multiCIDRRangeAllocator) Run(ctx context.Context)","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"func (r *multiCIDRRangeAllocator) Run(ctx context.Context) {\n\tdefer utilruntime.HandleCrash()\n\n\t// Start event processing pipeline.\n\tlogger := klog.FromContext(ctx)\n\tr.broadcaster.StartStructuredLogging(0)\n\tlogger.Info(\"Started sending events to API Server\")\n\tr.broadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: r.client.CoreV1().Events(\"\")})\n\tdefer r.broadcaster.Shutdown()\n\n\tdefer r.cidrQueue.ShutDown()\n\tdefer r.nodeQueue.ShutDown()\n\n\tlogger.Info(\"Starting Multi CIDR Range allocator\")\n\tdefer logger.Info(\"Shutting down Multi CIDR Range allocator\")\n\n\tif !cache.WaitForNamedCacheSync(\"multi_cidr_range_allocator\", ctx.Done(), r.nodesSynced, r.clusterCIDRSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c cidrUpdateWorkers; i++ {\n\t\tgo wait.UntilWithContext(ctx, r.runCIDRWorker, time.Second)\n\t\tgo wait.UntilWithContext(ctx, r.runNodeWorker, time.Second)\n\t}\n\n\t\u003c-ctx.Done()\n}","line":{"from":250,"to":276}} {"id":100004189,"name":"runCIDRWorker","signature":"func (r *multiCIDRRangeAllocator) runCIDRWorker(ctx context.Context)","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// runWorker is a long-running function that will continually call the\n// processNextWorkItem function in order to read and process a message on the\n// cidrQueue.\nfunc (r *multiCIDRRangeAllocator) runCIDRWorker(ctx context.Context) {\n\tfor r.processNextCIDRWorkItem(ctx) {\n\t}\n}","line":{"from":278,"to":284}} {"id":100004190,"name":"processNextCIDRWorkItem","signature":"func (r *multiCIDRRangeAllocator) processNextCIDRWorkItem(ctx context.Context) bool","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// processNextWorkItem will read a single work item off the cidrQueue and\n// attempt to process it, by calling the syncHandler.\nfunc (r *multiCIDRRangeAllocator) processNextCIDRWorkItem(ctx context.Context) bool {\n\tobj, shutdown := r.cidrQueue.Get()\n\tif shutdown {\n\t\treturn false\n\t}\n\n\t// We wrap this block in a func so we can defer c.cidrQueue.Done.\n\terr := func(ctx context.Context, obj interface{}) error {\n\t\t// We call Done here so the cidrQueue knows we have finished\n\t\t// processing this item. We also must remember to call Forget if we\n\t\t// do not want this work item being re-queued. For example, we do\n\t\t// not call Forget if a transient error occurs, instead the item is\n\t\t// put back on the cidrQueue and attempted again after a back-off\n\t\t// period.\n\t\tdefer r.cidrQueue.Done(obj)\n\t\tvar key string\n\t\tvar ok bool\n\t\t// We expect strings to come off the cidrQueue. These are of the\n\t\t// form namespace/name. We do this as the delayed nature of the\n\t\t// cidrQueue means the items in the informer cache may actually be\n\t\t// more up to date that when the item was initially put onto the\n\t\t// cidrQueue.\n\t\tif key, ok = obj.(string); !ok {\n\t\t\t// As the item in the cidrQueue is actually invalid, we call\n\t\t\t// Forget here else we'd go into a loop of attempting to\n\t\t\t// process a work item that is invalid.\n\t\t\tr.cidrQueue.Forget(obj)\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"expected string in cidrQueue but got %#v\", obj))\n\t\t\treturn nil\n\t\t}\n\t\t// Run the syncHandler, passing it the namespace/name string of the\n\t\t// Foo resource to be synced.\n\t\tif err := r.syncClusterCIDR(ctx, key); err != nil {\n\t\t\t// Put the item back on the cidrQueue to handle any transient errors.\n\t\t\tr.cidrQueue.AddRateLimited(key)\n\t\t\treturn fmt.Errorf(\"error syncing '%s': %s, requeuing\", key, err.Error())\n\t\t}\n\t\t// Finally, if no error occurs we Forget this item so it does not\n\t\t// get cidrQueued again until another change happens.\n\t\tr.cidrQueue.Forget(obj)\n\t\tklog.Infof(\"Successfully synced '%s'\", key)\n\t\treturn nil\n\t}(ctx, obj)\n\n\tif err != nil {\n\t\tutilruntime.HandleError(err)\n\t\treturn true\n\t}\n\n\treturn true\n}","line":{"from":286,"to":338}} {"id":100004191,"name":"runNodeWorker","signature":"func (r *multiCIDRRangeAllocator) runNodeWorker(ctx context.Context)","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"func (r *multiCIDRRangeAllocator) runNodeWorker(ctx context.Context) {\n\tfor r.processNextNodeWorkItem(ctx) {\n\t}\n}","line":{"from":340,"to":343}} {"id":100004192,"name":"processNextNodeWorkItem","signature":"func (r *multiCIDRRangeAllocator) processNextNodeWorkItem(ctx context.Context) bool","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// processNextWorkItem will read a single work item off the cidrQueue and\n// attempt to process it, by calling the syncHandler.\nfunc (r *multiCIDRRangeAllocator) processNextNodeWorkItem(ctx context.Context) bool {\n\tobj, shutdown := r.nodeQueue.Get()\n\tif shutdown {\n\t\treturn false\n\t}\n\n\t// We wrap this block in a func so we can defer c.cidrQueue.Done.\n\terr := func(logger klog.Logger, obj interface{}) error {\n\t\t// We call Done here so the workNodeQueue knows we have finished\n\t\t// processing this item. We also must remember to call Forget if we\n\t\t// do not want this work item being re-queued. For example, we do\n\t\t// not call Forget if a transient error occurs, instead the item is\n\t\t// put back on the nodeQueue and attempted again after a back-off\n\t\t// period.\n\t\tdefer r.nodeQueue.Done(obj)\n\t\tvar key string\n\t\tvar ok bool\n\t\t// We expect strings to come off the workNodeQueue. These are of the\n\t\t// form namespace/name. We do this as the delayed nature of the\n\t\t// workNodeQueue means the items in the informer cache may actually be\n\t\t// more up to date that when the item was initially put onto the\n\t\t// workNodeQueue.\n\t\tif key, ok = obj.(string); !ok {\n\t\t\t// As the item in the workNodeQueue is actually invalid, we call\n\t\t\t// Forget here else we'd go into a loop of attempting to\n\t\t\t// process a work item that is invalid.\n\t\t\tr.nodeQueue.Forget(obj)\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"expected string in workNodeQueue but got %#v\", obj))\n\t\t\treturn nil\n\t\t}\n\t\t// Run the syncHandler, passing it the namespace/name string of the\n\t\t// Foo resource to be synced.\n\t\tif err := r.syncNode(logger, key); err != nil {\n\t\t\t// Put the item back on the cidrQueue to handle any transient errors.\n\t\t\tr.nodeQueue.AddRateLimited(key)\n\t\t\treturn fmt.Errorf(\"error syncing '%s': %s, requeuing\", key, err.Error())\n\t\t}\n\t\t// Finally, if no error occurs we Forget this item so it does not\n\t\t// get nodeQueue again until another change happens.\n\t\tr.nodeQueue.Forget(obj)\n\t\tklog.Infof(\"Successfully synced '%s'\", key)\n\t\treturn nil\n\t}(klog.FromContext(ctx), obj)\n\n\tif err != nil {\n\t\tutilruntime.HandleError(err)\n\t\treturn true\n\t}\n\n\treturn true\n}","line":{"from":345,"to":397}} {"id":100004193,"name":"syncNode","signature":"func (r *multiCIDRRangeAllocator) syncNode(logger klog.Logger, key string) error","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"func (r *multiCIDRRangeAllocator) syncNode(logger klog.Logger, key string) error {\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tklog.V(4).Infof(\"Finished syncing Node request %q (%v)\", key, time.Since(startTime))\n\t}()\n\n\tnode, err := r.nodeLister.Get(key)\n\tif apierrors.IsNotFound(err) {\n\t\tklog.V(3).Infof(\"node has been deleted: %v\", key)\n\t\t// TODO: obtain the node object information to call ReleaseCIDR from here\n\t\t// and retry if there is an error.\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Check the DeletionTimestamp to determine if object is under deletion.\n\tif !node.DeletionTimestamp.IsZero() {\n\t\tklog.V(3).Infof(\"node is being deleted: %v\", key)\n\t\treturn r.ReleaseCIDR(logger, node)\n\t}\n\treturn r.AllocateOrOccupyCIDR(logger, node)\n}","line":{"from":399,"to":421}} {"id":100004194,"name":"needToAddFinalizer","signature":"func needToAddFinalizer(obj metav1.Object, finalizer string) bool","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// needToAddFinalizer checks if a finalizer should be added to the object.\nfunc needToAddFinalizer(obj metav1.Object, finalizer string) bool {\n\treturn obj.GetDeletionTimestamp() == nil \u0026\u0026 !slice.ContainsString(obj.GetFinalizers(),\n\t\tfinalizer, nil)\n}","line":{"from":423,"to":427}} {"id":100004195,"name":"syncClusterCIDR","signature":"func (r *multiCIDRRangeAllocator) syncClusterCIDR(ctx context.Context, key string) error","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"func (r *multiCIDRRangeAllocator) syncClusterCIDR(ctx context.Context, key string) error {\n\tstartTime := time.Now()\n\tlogger := klog.FromContext(ctx)\n\tdefer func() {\n\t\tlogger.V(4).Info(\"Finished syncing clusterCIDR request\", \"key\", key, \"latency\", time.Since(startTime))\n\t}()\n\n\tclusterCIDR, err := r.clusterCIDRLister.Get(key)\n\tif apierrors.IsNotFound(err) {\n\t\tlogger.V(3).Info(\"clusterCIDR has been deleted\", \"key\", key)\n\t\treturn nil\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Check the DeletionTimestamp to determine if object is under deletion.\n\tif !clusterCIDR.DeletionTimestamp.IsZero() {\n\t\treturn r.reconcileDelete(ctx, clusterCIDR)\n\t}\n\treturn r.reconcileCreate(ctx, clusterCIDR)\n}","line":{"from":429,"to":451}} {"id":100004196,"name":"occupyCIDRs","signature":"func (r *multiCIDRRangeAllocator) occupyCIDRs(logger klog.Logger, node *v1.Node) error","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// occupyCIDRs marks node.PodCIDRs[...] as used in allocator's tracked cidrSet.\nfunc (r *multiCIDRRangeAllocator) occupyCIDRs(logger klog.Logger, node *v1.Node) error {\n\n\terr := func(node *v1.Node) error {\n\n\t\tif len(node.Spec.PodCIDRs) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\tclusterCIDRList, err := r.orderedMatchingClusterCIDRs(logger, node, true)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor _, clusterCIDR := range clusterCIDRList {\n\t\t\toccupiedCount := 0\n\n\t\t\tfor _, cidr := range node.Spec.PodCIDRs {\n\t\t\t\t_, podCIDR, err := netutil.ParseCIDRSloppy(cidr)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"failed to parse CIDR %s on Node %v: %w\", cidr, node.Name, err)\n\t\t\t\t}\n\n\t\t\t\tlogger.Info(\"occupy CIDR for node\", \"CIDR\", cidr, \"node\", klog.KObj(node))\n\n\t\t\t\tif err := r.Occupy(clusterCIDR, podCIDR); err != nil {\n\t\t\t\t\tlogger.V(3).Info(\"Could not occupy cidr, trying next range\", \"podCIDRs\", node.Spec.PodCIDRs, \"err\", err)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\toccupiedCount++\n\t\t\t}\n\n\t\t\t// Mark CIDRs as occupied only if the CCC is able to occupy all the node CIDRs.\n\t\t\tif occupiedCount == len(node.Spec.PodCIDRs) {\n\t\t\t\tclusterCIDR.AssociatedNodes[node.Name] = true\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\treturn fmt.Errorf(\"could not occupy cidrs: %v, No matching ClusterCIDRs found\", node.Spec.PodCIDRs)\n\t}(node)\n\n\treturn err\n}","line":{"from":453,"to":496}} {"id":100004197,"name":"associatedCIDRSet","signature":"func (r *multiCIDRRangeAllocator) associatedCIDRSet(clusterCIDR *cidrset.ClusterCIDR, cidr *net.IPNet) (*cidrset.MultiCIDRSet, error)","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// associatedCIDRSet returns the CIDRSet, based on the ip family of the CIDR.\nfunc (r *multiCIDRRangeAllocator) associatedCIDRSet(clusterCIDR *cidrset.ClusterCIDR, cidr *net.IPNet) (*cidrset.MultiCIDRSet, error) {\n\tswitch {\n\tcase netutil.IsIPv4CIDR(cidr):\n\t\treturn clusterCIDR.IPv4CIDRSet, nil\n\tcase netutil.IsIPv6CIDR(cidr):\n\t\treturn clusterCIDR.IPv6CIDRSet, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid cidr: %v\", cidr)\n\t}\n}","line":{"from":498,"to":508}} {"id":100004198,"name":"Occupy","signature":"func (r *multiCIDRRangeAllocator) Occupy(clusterCIDR *cidrset.ClusterCIDR, cidr *net.IPNet) error","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// Occupy marks the CIDR as occupied in the allocatedCIDRMap of the cidrSet.\nfunc (r *multiCIDRRangeAllocator) Occupy(clusterCIDR *cidrset.ClusterCIDR, cidr *net.IPNet) error {\n\tcurrCIDRSet, err := r.associatedCIDRSet(clusterCIDR, cidr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := currCIDRSet.Occupy(cidr); err != nil {\n\t\treturn fmt.Errorf(\"unable to occupy cidr %v in cidrSet\", cidr)\n\t}\n\n\treturn nil\n}","line":{"from":510,"to":522}} {"id":100004199,"name":"Release","signature":"func (r *multiCIDRRangeAllocator) Release(logger klog.Logger, clusterCIDR *cidrset.ClusterCIDR, cidr *net.IPNet) error","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// Release marks the CIDR as free in the cidrSet used bitmap,\n// Also removes the CIDR from the allocatedCIDRSet.\nfunc (r *multiCIDRRangeAllocator) Release(logger klog.Logger, clusterCIDR *cidrset.ClusterCIDR, cidr *net.IPNet) error {\n\tcurrCIDRSet, err := r.associatedCIDRSet(clusterCIDR, cidr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := currCIDRSet.Release(cidr); err != nil {\n\t\tlogger.Info(\"Unable to release cidr in cidrSet\", \"CIDR\", cidr)\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":524,"to":538}} {"id":100004200,"name":"AllocateOrOccupyCIDR","signature":"func (r *multiCIDRRangeAllocator) AllocateOrOccupyCIDR(logger klog.Logger, node *v1.Node) error","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// AllocateOrOccupyCIDR allocates a CIDR to the node if the node doesn't have a\n// CIDR already allocated, occupies the CIDR and marks as used if the node\n// already has a PodCIDR assigned.\n// WARNING: If you're adding any return calls or defer any more work from this\n// function you have to make sure to update nodesInProcessing properly with the\n// disposition of the node when the work is done.\nfunc (r *multiCIDRRangeAllocator) AllocateOrOccupyCIDR(logger klog.Logger, node *v1.Node) error {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\n\tif node == nil {\n\t\treturn nil\n\t}\n\n\tif len(node.Spec.PodCIDRs) \u003e 0 {\n\t\treturn r.occupyCIDRs(logger, node)\n\t}\n\n\tcidrs, clusterCIDR, err := r.prioritizedCIDRs(logger, node)\n\tif err != nil {\n\t\tcontrollerutil.RecordNodeStatusChange(r.recorder, node, \"CIDRNotAvailable\")\n\t\treturn fmt.Errorf(\"failed to get cidrs for node %s\", node.Name)\n\t}\n\n\tif len(cidrs) == 0 {\n\t\tcontrollerutil.RecordNodeStatusChange(r.recorder, node, \"CIDRNotAvailable\")\n\t\treturn fmt.Errorf(\"no cidrSets with matching labels found for node %s\", node.Name)\n\t}\n\n\t// allocate and queue the assignment.\n\tallocated := multiCIDRNodeReservedCIDRs{\n\t\tnodeReservedCIDRs: nodeReservedCIDRs{\n\t\t\tnodeName: node.Name,\n\t\t\tallocatedCIDRs: cidrs,\n\t\t},\n\t\tclusterCIDR: clusterCIDR,\n\t}\n\n\treturn r.updateCIDRsAllocation(logger, allocated)\n}","line":{"from":540,"to":579}} {"id":100004201,"name":"ReleaseCIDR","signature":"func (r *multiCIDRRangeAllocator) ReleaseCIDR(logger klog.Logger, node *v1.Node) error","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// ReleaseCIDR marks node.podCIDRs[...] as unused in our tracked cidrSets.\nfunc (r *multiCIDRRangeAllocator) ReleaseCIDR(logger klog.Logger, node *v1.Node) error {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\n\tif node == nil || len(node.Spec.PodCIDRs) == 0 {\n\t\treturn nil\n\t}\n\n\tclusterCIDR, err := r.allocatedClusterCIDR(logger, node)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, cidr := range node.Spec.PodCIDRs {\n\t\t_, podCIDR, err := netutil.ParseCIDRSloppy(cidr)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to parse CIDR %q on Node %q: %w\", cidr, node.Name, err)\n\t\t}\n\n\t\tlogger.Info(\"release CIDR for node\", \"CIDR\", cidr, \"node\", klog.KObj(node))\n\t\tif err := r.Release(logger, clusterCIDR, podCIDR); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to release cidr %q from clusterCIDR %q for node %q: %w\", cidr, clusterCIDR.Name, node.Name, err)\n\t\t}\n\t}\n\n\t// Remove the node from the ClusterCIDR AssociatedNodes.\n\tdelete(clusterCIDR.AssociatedNodes, node.Name)\n\n\treturn nil\n}","line":{"from":581,"to":611}} {"id":100004202,"name":"filterOutServiceRange","signature":"func (r *multiCIDRRangeAllocator) filterOutServiceRange(logger klog.Logger, serviceCIDR *net.IPNet)","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// Marks all CIDRs with subNetMaskSize that belongs to serviceCIDR as used across all cidrs\n// so that they won't be assignable.\nfunc (r *multiCIDRRangeAllocator) filterOutServiceRange(logger klog.Logger, serviceCIDR *net.IPNet) {\n\t// Checks if service CIDR has a nonempty intersection with cluster\n\t// CIDR. It is the case if either clusterCIDR contains serviceCIDR with\n\t// clusterCIDR's Mask applied (this means that clusterCIDR contains\n\t// serviceCIDR) or vice versa (which means that serviceCIDR contains\n\t// clusterCIDR).\n\tfor _, clusterCIDRList := range r.cidrMap {\n\t\tfor _, clusterCIDR := range clusterCIDRList {\n\t\t\tif err := r.occupyServiceCIDR(clusterCIDR, serviceCIDR); err != nil {\n\t\t\t\tlogger.Error(err, \"Unable to occupy service CIDR\")\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":613,"to":628}} {"id":100004203,"name":"occupyServiceCIDR","signature":"func (r *multiCIDRRangeAllocator) occupyServiceCIDR(clusterCIDR *cidrset.ClusterCIDR, serviceCIDR *net.IPNet) error","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"func (r *multiCIDRRangeAllocator) occupyServiceCIDR(clusterCIDR *cidrset.ClusterCIDR, serviceCIDR *net.IPNet) error {\n\n\tcidrSet, err := r.associatedCIDRSet(clusterCIDR, serviceCIDR)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcidr := cidrSet.ClusterCIDR\n\n\t// No need to occupy as Service CIDR doesn't intersect with the current ClusterCIDR.\n\tif !cidr.Contains(serviceCIDR.IP.Mask(cidr.Mask)) \u0026\u0026 !serviceCIDR.Contains(cidr.IP.Mask(serviceCIDR.Mask)) {\n\t\treturn nil\n\t}\n\n\tif err := r.Occupy(clusterCIDR, serviceCIDR); err != nil {\n\t\treturn fmt.Errorf(\"error filtering out service cidr %v from cluster cidr %v: %w\", cidr, serviceCIDR, err)\n\t}\n\n\treturn nil\n}","line":{"from":630,"to":649}} {"id":100004204,"name":"updateCIDRsAllocation","signature":"func (r *multiCIDRRangeAllocator) updateCIDRsAllocation(logger klog.Logger, data multiCIDRNodeReservedCIDRs) error","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// updateCIDRsAllocation assigns CIDR to Node and sends an update to the API server.\nfunc (r *multiCIDRRangeAllocator) updateCIDRsAllocation(logger klog.Logger, data multiCIDRNodeReservedCIDRs) error {\n\terr := func(data multiCIDRNodeReservedCIDRs) error {\n\t\tcidrsString := ipnetToStringList(data.allocatedCIDRs)\n\t\tnode, err := r.nodeLister.Get(data.nodeName)\n\t\tif err != nil {\n\t\t\tlogger.Error(err, \"Failed while getting node for updating Node.Spec.PodCIDRs\", \"node\", klog.KRef(\"\", data.nodeName))\n\t\t\treturn err\n\t\t}\n\n\t\t// if cidr list matches the proposed,\n\t\t// then we possibly updated this node\n\t\t// and just failed to ack the success.\n\t\tif len(node.Spec.PodCIDRs) == len(data.allocatedCIDRs) {\n\t\t\tmatch := true\n\t\t\tfor idx, cidr := range cidrsString {\n\t\t\t\tif node.Spec.PodCIDRs[idx] != cidr {\n\t\t\t\t\tmatch = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif match {\n\t\t\t\tlogger.V(4).Info(\"Node already has allocated CIDR. It matches the proposed one.\", \"node\", klog.KObj(node), \"CIDRs\", data.allocatedCIDRs)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\t// node has cidrs allocated, release the reserved.\n\t\tif len(node.Spec.PodCIDRs) != 0 {\n\t\t\tlogger.Error(nil, \"Node already has a CIDR allocated. Releasing the new one\", \"node\", klog.KObj(node), \"podCIDRs\", node.Spec.PodCIDRs)\n\t\t\tfor _, cidr := range data.allocatedCIDRs {\n\t\t\t\tif err := r.Release(logger, data.clusterCIDR, cidr); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"failed to release cidr %s from clusterCIDR %s for node: %s: %w\", cidr, data.clusterCIDR.Name, node.Name, err)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\t// If we reached here, it means that the node has no CIDR currently assigned. So we set it.\n\t\tfor i := 0; i \u003c cidrUpdateRetries; i++ {\n\t\t\tif err = nodeutil.PatchNodeCIDRs(r.client, types.NodeName(node.Name), cidrsString); err == nil {\n\t\t\t\tdata.clusterCIDR.AssociatedNodes[node.Name] = true\n\t\t\t\tlogger.Info(\"Set node PodCIDR\", \"node\", klog.KObj(node), \"podCIDR\", cidrsString)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\t// failed release back to the pool.\n\t\tlogger.Error(err, \"Failed to update node PodCIDR after attempts\", \"node\", klog.KObj(node), \"podCIDR\", cidrsString, \"retries\", cidrUpdateRetries)\n\t\tcontrollerutil.RecordNodeStatusChange(r.recorder, node, \"CIDRAssignmentFailed\")\n\t\t// We accept the fact that we may leak CIDRs here. This is safer than releasing\n\t\t// them in case when we don't know if request went through.\n\t\t// NodeController restart will return all falsely allocated CIDRs to the pool.\n\t\tif !apierrors.IsServerTimeout(err) {\n\t\t\tlogger.Error(err, \"CIDR assignment for node failed. Releasing allocated CIDR\", \"node\", klog.KObj(node))\n\t\t\tfor _, cidr := range data.allocatedCIDRs {\n\t\t\t\tif err := r.Release(logger, data.clusterCIDR, cidr); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"failed to release cidr %q from clusterCIDR %q for node: %q: %w\", cidr, data.clusterCIDR.Name, node.Name, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn err\n\t}(data)\n\n\treturn err\n}","line":{"from":651,"to":715}} {"id":100004205,"name":"defaultNodeSelector","signature":"func defaultNodeSelector() *v1.NodeSelector","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// defaultNodeSelector generates a label with defaultClusterCIDRKey as the key and\n// defaultClusterCIDRValue as the value, it is an internal nodeSelector matching all\n// nodes. Only used if no ClusterCIDR selects the node.\nfunc defaultNodeSelector() *v1.NodeSelector {\n\treturn \u0026v1.NodeSelector{\n\t\tNodeSelectorTerms: []v1.NodeSelectorTerm{\n\t\t\t{\n\t\t\t\tMatchExpressions: []v1.NodeSelectorRequirement{\n\t\t\t\t\t{\n\t\t\t\t\t\tKey: defaultClusterCIDRKey,\n\t\t\t\t\t\tOperator: v1.NodeSelectorOpIn,\n\t\t\t\t\t\tValues: []string{defaultClusterCIDRValue},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":717,"to":734}} {"id":100004206,"name":"prioritizedCIDRs","signature":"func (r *multiCIDRRangeAllocator) prioritizedCIDRs(logger klog.Logger, node *v1.Node) ([]*net.IPNet, *cidrset.ClusterCIDR, error)","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// prioritizedCIDRs returns a list of CIDRs to be allocated to the node.\n// Returns 1 CIDR if single stack.\n// Returns 2 CIDRs , 1 from each ip family if dual stack.\nfunc (r *multiCIDRRangeAllocator) prioritizedCIDRs(logger klog.Logger, node *v1.Node) ([]*net.IPNet, *cidrset.ClusterCIDR, error) {\n\tclusterCIDRList, err := r.orderedMatchingClusterCIDRs(logger, node, true)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"unable to get a clusterCIDR for node %s: %w\", node.Name, err)\n\t}\n\n\tfor _, clusterCIDR := range clusterCIDRList {\n\t\tcidrs := make([]*net.IPNet, 0)\n\t\tif clusterCIDR.IPv4CIDRSet != nil {\n\t\t\tcidr, err := r.allocateCIDR(clusterCIDR, clusterCIDR.IPv4CIDRSet)\n\t\t\tif err != nil {\n\t\t\t\tlogger.V(3).Info(\"Unable to allocate IPv4 CIDR, trying next range\", \"err\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcidrs = append(cidrs, cidr)\n\t\t}\n\n\t\tif clusterCIDR.IPv6CIDRSet != nil {\n\t\t\tcidr, err := r.allocateCIDR(clusterCIDR, clusterCIDR.IPv6CIDRSet)\n\t\t\tif err != nil {\n\t\t\t\tlogger.V(3).Info(\"Unable to allocate IPv6 CIDR, trying next range\", \"err\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcidrs = append(cidrs, cidr)\n\t\t}\n\n\t\treturn cidrs, clusterCIDR, nil\n\t}\n\treturn nil, nil, fmt.Errorf(\"unable to get a clusterCIDR for node %s, no available CIDRs\", node.Name)\n}","line":{"from":736,"to":768}} {"id":100004207,"name":"allocateCIDR","signature":"func (r *multiCIDRRangeAllocator) allocateCIDR(clusterCIDR *cidrset.ClusterCIDR, cidrSet *cidrset.MultiCIDRSet) (*net.IPNet, error)","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"func (r *multiCIDRRangeAllocator) allocateCIDR(clusterCIDR *cidrset.ClusterCIDR, cidrSet *cidrset.MultiCIDRSet) (*net.IPNet, error) {\n\n\tfor evaluated := 0; evaluated \u003c cidrSet.MaxCIDRs; evaluated++ {\n\t\tcandidate, lastEvaluated, err := cidrSet.NextCandidate()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tevaluated += lastEvaluated\n\n\t\tif r.cidrInAllocatedList(candidate) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Deep Check.\n\t\tif r.cidrOverlapWithAllocatedList(candidate) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Mark the CIDR as occupied in the map.\n\t\tif err := r.Occupy(clusterCIDR, candidate); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// Increment the evaluated count metric.\n\t\tcidrSet.UpdateEvaluatedCount(evaluated)\n\t\treturn candidate, nil\n\t}\n\treturn nil, \u0026cidrset.CIDRRangeNoCIDRsRemainingErr{\n\t\tCIDR: cidrSet.Label,\n\t}\n}","line":{"from":770,"to":800}} {"id":100004208,"name":"cidrInAllocatedList","signature":"func (r *multiCIDRRangeAllocator) cidrInAllocatedList(cidr *net.IPNet) bool","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"func (r *multiCIDRRangeAllocator) cidrInAllocatedList(cidr *net.IPNet) bool {\n\tfor _, clusterCIDRList := range r.cidrMap {\n\t\tfor _, clusterCIDR := range clusterCIDRList {\n\t\t\tcidrSet, _ := r.associatedCIDRSet(clusterCIDR, cidr)\n\t\t\tif cidrSet != nil {\n\t\t\t\tif ok := cidrSet.AllocatedCIDRMap[cidr.String()]; ok {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":802,"to":814}} {"id":100004209,"name":"cidrOverlapWithAllocatedList","signature":"func (r *multiCIDRRangeAllocator) cidrOverlapWithAllocatedList(cidr *net.IPNet) bool","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"func (r *multiCIDRRangeAllocator) cidrOverlapWithAllocatedList(cidr *net.IPNet) bool {\n\tfor _, clusterCIDRList := range r.cidrMap {\n\t\tfor _, clusterCIDR := range clusterCIDRList {\n\t\t\tcidrSet, _ := r.associatedCIDRSet(clusterCIDR, cidr)\n\t\t\tif cidrSet != nil {\n\t\t\t\tfor allocated := range cidrSet.AllocatedCIDRMap {\n\t\t\t\t\t_, allocatedCIDR, _ := netutil.ParseCIDRSloppy(allocated)\n\t\t\t\t\tif cidr.Contains(allocatedCIDR.IP.Mask(cidr.Mask)) || allocatedCIDR.Contains(cidr.IP.Mask(allocatedCIDR.Mask)) {\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":816,"to":831}} {"id":100004210,"name":"allocatedClusterCIDR","signature":"func (r *multiCIDRRangeAllocator) allocatedClusterCIDR(logger klog.Logger, node *v1.Node) (*cidrset.ClusterCIDR, error)","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// allocatedClusterCIDR returns the ClusterCIDR from which the node CIDRs were allocated.\nfunc (r *multiCIDRRangeAllocator) allocatedClusterCIDR(logger klog.Logger, node *v1.Node) (*cidrset.ClusterCIDR, error) {\n\tclusterCIDRList, err := r.orderedMatchingClusterCIDRs(logger, node, false)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to get a clusterCIDR for node %s: %w\", node.Name, err)\n\t}\n\n\tfor _, clusterCIDR := range clusterCIDRList {\n\t\tif ok := clusterCIDR.AssociatedNodes[node.Name]; ok {\n\t\t\treturn clusterCIDR, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"no clusterCIDR found associated with node: %s\", node.Name)\n}","line":{"from":833,"to":846}} {"id":100004211,"name":"orderedMatchingClusterCIDRs","signature":"func (r *multiCIDRRangeAllocator) orderedMatchingClusterCIDRs(logger klog.Logger, node *v1.Node, occupy bool) ([]*cidrset.ClusterCIDR, error)","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// orderedMatchingClusterCIDRs returns a list of all the ClusterCIDRs matching the node labels.\n// The list is ordered with the following priority, which act as tie-breakers.\n// P0: ClusterCIDR with higher number of matching labels has the highest priority.\n// P1: ClusterCIDR having cidrSet with fewer allocatable Pod CIDRs has higher priority.\n// P2: ClusterCIDR with a PerNodeMaskSize having fewer IPs has higher priority.\n// P3: ClusterCIDR having label with lower alphanumeric value has higher priority.\n// P4: ClusterCIDR with a cidrSet having a smaller IP address value has a higher priority.\n//\n// orderedMatchingClusterCIDRs takes `occupy` as an argument, it determines whether the function\n// is called during an occupy or a release operation. For a release operation, a ClusterCIDR must\n// be added to the matching ClusterCIDRs list, irrespective of whether the ClusterCIDR is terminating.\nfunc (r *multiCIDRRangeAllocator) orderedMatchingClusterCIDRs(logger klog.Logger, node *v1.Node, occupy bool) ([]*cidrset.ClusterCIDR, error) {\n\tmatchingCIDRs := make([]*cidrset.ClusterCIDR, 0)\n\tpq := make(PriorityQueue, 0)\n\n\tfor label, clusterCIDRList := range r.cidrMap {\n\t\tlabelsMatch, matchCnt, err := r.matchCIDRLabels(logger, node, label)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif !labelsMatch {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, clusterCIDR := range clusterCIDRList {\n\t\t\tpqItem := \u0026PriorityQueueItem{\n\t\t\t\tclusterCIDR: clusterCIDR,\n\t\t\t\tlabelMatchCount: matchCnt,\n\t\t\t\tselectorString: label,\n\t\t\t}\n\n\t\t\t// Only push the CIDRsets which are not marked for termination.\n\t\t\t// Always push the CIDRsets when marked for release.\n\t\t\tif !occupy || !clusterCIDR.Terminating {\n\t\t\t\theap.Push(\u0026pq, pqItem)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Remove the ClusterCIDRs from the PriorityQueue.\n\t// They arrive in descending order of matchCnt,\n\t// if matchCnt is equal it is ordered in ascending order of labels.\n\tfor pq.Len() \u003e 0 {\n\t\tpqItem := heap.Pop(\u0026pq).(*PriorityQueueItem)\n\t\tmatchingCIDRs = append(matchingCIDRs, pqItem.clusterCIDR)\n\t}\n\n\t// Append the catch all CIDR config.\n\tdefaultSelector, err := nodeSelectorAsSelector(defaultNodeSelector())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif clusterCIDRList, ok := r.cidrMap[defaultSelector.String()]; ok {\n\t\tmatchingCIDRs = append(matchingCIDRs, clusterCIDRList...)\n\t}\n\treturn matchingCIDRs, nil\n}","line":{"from":848,"to":905}} {"id":100004212,"name":"matchCIDRLabels","signature":"func (r *multiCIDRRangeAllocator) matchCIDRLabels(logger klog.Logger, node *v1.Node, label string) (bool, int, error)","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// matchCIDRLabels Matches the Node labels to CIDR Configs.\n// Returns true only if all the labels match, also returns the count of matching labels.\nfunc (r *multiCIDRRangeAllocator) matchCIDRLabels(logger klog.Logger, node *v1.Node, label string) (bool, int, error) {\n\tvar labelSet labels.Set\n\tvar matchCnt int\n\tlabelsMatch := false\n\n\tls, err := labels.Parse(label)\n\tif err != nil {\n\t\tlogger.Error(err, \"Unable to parse label to labels.Selector\", \"label\", label)\n\t\treturn labelsMatch, 0, err\n\t}\n\treqs, selectable := ls.Requirements()\n\n\tlabelSet = node.ObjectMeta.Labels\n\tif selectable {\n\t\tmatchCnt = 0\n\t\tfor _, req := range reqs {\n\t\t\tif req.Matches(labelSet) {\n\t\t\t\tmatchCnt += 1\n\t\t\t}\n\t\t}\n\t\tif matchCnt == len(reqs) {\n\t\t\tlabelsMatch = true\n\t\t}\n\t}\n\treturn labelsMatch, matchCnt, nil\n}","line":{"from":907,"to":934}} {"id":100004213,"name":"createDefaultClusterCIDR","signature":"func createDefaultClusterCIDR(logger klog.Logger, existingConfigList *networkingv1alpha1.ClusterCIDRList,","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// createDefaultClusterCIDR creates a default ClusterCIDR if --cluster-cidr has\n// been configured. It converts the --cluster-cidr and --per-node-mask-size* flags\n// to appropriate ClusterCIDR fields.\nfunc createDefaultClusterCIDR(logger klog.Logger, existingConfigList *networkingv1alpha1.ClusterCIDRList,\n\tallocatorParams CIDRAllocatorParams) {\n\t// Create default ClusterCIDR only if --cluster-cidr has been configured\n\tif len(allocatorParams.ClusterCIDRs) == 0 {\n\t\treturn\n\t}\n\n\tfor _, clusterCIDR := range existingConfigList.Items {\n\t\tif clusterCIDR.Name == defaultClusterCIDRName {\n\t\t\t// Default ClusterCIDR already exists, no further action required.\n\t\t\tlogger.V(3).Info(\"Default ClusterCIDR already exists\", \"defaultClusterCIDRName\", defaultClusterCIDRName)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Create a default ClusterCIDR as it is not already created.\n\tdefaultCIDRConfig := \u0026networkingv1alpha1.ClusterCIDR{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: defaultClusterCIDRAPIVersion,\n\t\t\tKind: \"ClusterCIDR\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: defaultClusterCIDRName,\n\t\t},\n\t\tSpec: networkingv1alpha1.ClusterCIDRSpec{\n\t\t\tPerNodeHostBits: minPerNodeHostBits,\n\t\t},\n\t}\n\n\tipv4PerNodeHostBits := int32(math.MinInt32)\n\tipv6PerNodeHostBits := int32(math.MinInt32)\n\tisDualstack := false\n\tif len(allocatorParams.ClusterCIDRs) == 2 {\n\t\tisDualstack = true\n\t}\n\n\tfor i, cidr := range allocatorParams.ClusterCIDRs {\n\t\tif netutil.IsIPv4CIDR(cidr) {\n\t\t\tdefaultCIDRConfig.Spec.IPv4 = cidr.String()\n\t\t\tipv4PerNodeHostBits = ipv4MaxCIDRMask - int32(allocatorParams.NodeCIDRMaskSizes[i])\n\t\t\tif !isDualstack \u0026\u0026 ipv4PerNodeHostBits \u003e minPerNodeHostBits {\n\t\t\t\tdefaultCIDRConfig.Spec.PerNodeHostBits = ipv4PerNodeHostBits\n\t\t\t}\n\t\t} else if netutil.IsIPv6CIDR(cidr) {\n\t\t\tdefaultCIDRConfig.Spec.IPv6 = cidr.String()\n\t\t\tipv6PerNodeHostBits = ipv6MaxCIDRMask - int32(allocatorParams.NodeCIDRMaskSizes[i])\n\t\t\tif !isDualstack \u0026\u0026 ipv6PerNodeHostBits \u003e minPerNodeHostBits {\n\t\t\t\tdefaultCIDRConfig.Spec.PerNodeHostBits = ipv6PerNodeHostBits\n\t\t\t}\n\t\t}\n\t}\n\n\tif isDualstack {\n\t\t// In case of dualstack CIDRs, currently the default values for PerNodeMaskSize are\n\t\t// 24 for IPv4 (PerNodeHostBits=8) and 64 for IPv6(PerNodeHostBits=64), there is no\n\t\t// requirement for the PerNodeHostBits to be equal for IPv4 and IPv6, However with\n\t\t// the introduction of ClusterCIDRs, we enforce the requirement for a single\n\t\t// PerNodeHostBits field, thus we choose the minimum PerNodeHostBits value, to avoid\n\t\t// overflow for IPv4 CIDRs.\n\t\tif ipv4PerNodeHostBits \u003e= minPerNodeHostBits \u0026\u0026 ipv4PerNodeHostBits \u003c= ipv6PerNodeHostBits {\n\t\t\tdefaultCIDRConfig.Spec.PerNodeHostBits = ipv4PerNodeHostBits\n\t\t} else if ipv6PerNodeHostBits \u003e= minPerNodeHostBits \u0026\u0026 ipv6PerNodeHostBits \u003c= ipv4MaxCIDRMask {\n\t\t\tdefaultCIDRConfig.Spec.PerNodeHostBits = ipv6PerNodeHostBits\n\t\t}\n\t}\n\n\texistingConfigList.Items = append(existingConfigList.Items, *defaultCIDRConfig)\n\n\treturn\n}","line":{"from":938,"to":1010}} {"id":100004214,"name":"reconcileCreate","signature":"func (r *multiCIDRRangeAllocator) reconcileCreate(ctx context.Context, clusterCIDR *networkingv1alpha1.ClusterCIDR) error","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// reconcileCreate handles create ClusterCIDR events.\nfunc (r *multiCIDRRangeAllocator) reconcileCreate(ctx context.Context, clusterCIDR *networkingv1alpha1.ClusterCIDR) error {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\n\tlogger := klog.FromContext(ctx)\n\tif needToAddFinalizer(clusterCIDR, clusterCIDRFinalizer) {\n\t\tlogger.V(3).Info(\"Creating ClusterCIDR\", \"clusterCIDR\", clusterCIDR.Name)\n\t\tif err := r.createClusterCIDR(ctx, clusterCIDR, false); err != nil {\n\t\t\tlogger.Error(err, \"Unable to create ClusterCIDR\", \"clusterCIDR\", clusterCIDR.Name)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":1012,"to":1026}} {"id":100004215,"name":"reconcileBootstrap","signature":"func (r *multiCIDRRangeAllocator) reconcileBootstrap(ctx context.Context, clusterCIDR *networkingv1alpha1.ClusterCIDR) error","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// reconcileBootstrap handles creation of existing ClusterCIDRs.\n// adds a finalizer if not already present.\nfunc (r *multiCIDRRangeAllocator) reconcileBootstrap(ctx context.Context, clusterCIDR *networkingv1alpha1.ClusterCIDR) error {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\n\tlogger := klog.FromContext(ctx)\n\tterminating := false\n\t// Create the ClusterCIDR only if the Spec has not been modified.\n\tif clusterCIDR.Generation \u003e 1 {\n\t\tterminating = true\n\t\terr := fmt.Errorf(\"CIDRs from ClusterCIDR %s will not be used for allocation as it was modified\", clusterCIDR.Name)\n\t\tlogger.Error(err, \"ClusterCIDR Modified\")\n\t}\n\n\tlogger.V(2).Info(\"Creating ClusterCIDR during bootstrap\", \"clusterCIDR\", clusterCIDR.Name)\n\tif err := r.createClusterCIDR(ctx, clusterCIDR, terminating); err != nil {\n\t\tlogger.Error(err, \"Unable to create ClusterCIDR\", \"clusterCIDR\", clusterCIDR.Name)\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":1028,"to":1050}} {"id":100004216,"name":"createClusterCIDR","signature":"func (r *multiCIDRRangeAllocator) createClusterCIDR(ctx context.Context, clusterCIDR *networkingv1alpha1.ClusterCIDR, terminating bool) error","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// createClusterCIDR creates and maps the cidrSets in the cidrMap.\nfunc (r *multiCIDRRangeAllocator) createClusterCIDR(ctx context.Context, clusterCIDR *networkingv1alpha1.ClusterCIDR, terminating bool) error {\n\tnodeSelector, err := r.nodeSelectorKey(clusterCIDR)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to get labelSelector key: %w\", err)\n\t}\n\n\tclusterCIDRSet, err := r.createClusterCIDRSet(clusterCIDR, terminating)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"invalid ClusterCIDR: %w\", err)\n\t}\n\n\tif clusterCIDRSet.IPv4CIDRSet == nil \u0026\u0026 clusterCIDRSet.IPv6CIDRSet == nil {\n\t\treturn errors.New(\"invalid ClusterCIDR: must provide IPv4 and/or IPv6 config\")\n\t}\n\n\tif err := r.mapClusterCIDRSet(r.cidrMap, nodeSelector, clusterCIDRSet); err != nil {\n\t\treturn fmt.Errorf(\"unable to map clusterCIDRSet: %w\", err)\n\t}\n\n\t// Make a copy so we don't mutate the shared informer cache.\n\tupdatedClusterCIDR := clusterCIDR.DeepCopy()\n\tif needToAddFinalizer(clusterCIDR, clusterCIDRFinalizer) {\n\t\tupdatedClusterCIDR.ObjectMeta.Finalizers = append(clusterCIDR.ObjectMeta.Finalizers, clusterCIDRFinalizer)\n\t}\n\n\tlogger := klog.FromContext(ctx)\n\tif updatedClusterCIDR.ResourceVersion == \"\" {\n\t\t// Create is only used for creating default ClusterCIDR.\n\t\tif _, err := r.client.NetworkingV1alpha1().ClusterCIDRs().Create(ctx, updatedClusterCIDR, metav1.CreateOptions{}); err != nil {\n\t\t\tlogger.V(2).Info(\"Error creating ClusterCIDR\", \"clusterCIDR\", klog.KObj(clusterCIDR), \"err\", err)\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t// Update the ClusterCIDR object when called from reconcileCreate.\n\t\tif _, err := r.client.NetworkingV1alpha1().ClusterCIDRs().Update(ctx, updatedClusterCIDR, metav1.UpdateOptions{}); err != nil {\n\t\t\tlogger.V(2).Info(\"Error creating ClusterCIDR\", \"clusterCIDR\", clusterCIDR.Name, \"err\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":1052,"to":1094}} {"id":100004217,"name":"createClusterCIDRSet","signature":"func (r *multiCIDRRangeAllocator) createClusterCIDRSet(clusterCIDR *networkingv1alpha1.ClusterCIDR, terminating bool) (*cidrset.ClusterCIDR, error)","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// createClusterCIDRSet creates and returns new cidrset.ClusterCIDR based on ClusterCIDR API object.\nfunc (r *multiCIDRRangeAllocator) createClusterCIDRSet(clusterCIDR *networkingv1alpha1.ClusterCIDR, terminating bool) (*cidrset.ClusterCIDR, error) {\n\n\tclusterCIDRSet := \u0026cidrset.ClusterCIDR{\n\t\tName: clusterCIDR.Name,\n\t\tAssociatedNodes: make(map[string]bool, 0),\n\t\tTerminating: terminating,\n\t}\n\n\tif clusterCIDR.Spec.IPv4 != \"\" {\n\t\t_, ipv4CIDR, err := netutil.ParseCIDRSloppy(clusterCIDR.Spec.IPv4)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to parse provided IPv4 CIDR: %w\", err)\n\t\t}\n\t\tclusterCIDRSet.IPv4CIDRSet, err = cidrset.NewMultiCIDRSet(ipv4CIDR, int(clusterCIDR.Spec.PerNodeHostBits))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to create IPv4 cidrSet: %w\", err)\n\t\t}\n\t}\n\n\tif clusterCIDR.Spec.IPv6 != \"\" {\n\t\t_, ipv6CIDR, err := netutil.ParseCIDRSloppy(clusterCIDR.Spec.IPv6)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to parse provided IPv6 CIDR: %w\", err)\n\t\t}\n\t\tclusterCIDRSet.IPv6CIDRSet, err = cidrset.NewMultiCIDRSet(ipv6CIDR, int(clusterCIDR.Spec.PerNodeHostBits))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to create IPv6 cidrSet: %w\", err)\n\t\t}\n\t}\n\n\treturn clusterCIDRSet, nil\n}","line":{"from":1096,"to":1128}} {"id":100004218,"name":"mapClusterCIDRSet","signature":"func (r *multiCIDRRangeAllocator) mapClusterCIDRSet(cidrMap map[string][]*cidrset.ClusterCIDR, nodeSelector string, clusterCIDRSet *cidrset.ClusterCIDR) error","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// mapClusterCIDRSet maps the ClusterCIDRSet to the provided labelSelector in the cidrMap.\nfunc (r *multiCIDRRangeAllocator) mapClusterCIDRSet(cidrMap map[string][]*cidrset.ClusterCIDR, nodeSelector string, clusterCIDRSet *cidrset.ClusterCIDR) error {\n\tif clusterCIDRSet == nil {\n\t\treturn errors.New(\"invalid clusterCIDRSet, clusterCIDRSet cannot be nil\")\n\t}\n\n\tif clusterCIDRSetList, ok := cidrMap[nodeSelector]; ok {\n\t\tcidrMap[nodeSelector] = append(clusterCIDRSetList, clusterCIDRSet)\n\t} else {\n\t\tcidrMap[nodeSelector] = []*cidrset.ClusterCIDR{clusterCIDRSet}\n\t}\n\treturn nil\n}","line":{"from":1130,"to":1142}} {"id":100004219,"name":"reconcileDelete","signature":"func (r *multiCIDRRangeAllocator) reconcileDelete(ctx context.Context, clusterCIDR *networkingv1alpha1.ClusterCIDR) error","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// reconcileDelete releases the assigned ClusterCIDR and removes the finalizer\n// if the deletion timestamp is set.\nfunc (r *multiCIDRRangeAllocator) reconcileDelete(ctx context.Context, clusterCIDR *networkingv1alpha1.ClusterCIDR) error {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\n\tlogger := klog.FromContext(ctx)\n\tif slice.ContainsString(clusterCIDR.GetFinalizers(), clusterCIDRFinalizer, nil) {\n\t\tlogger.V(2).Info(\"Releasing ClusterCIDR\", \"clusterCIDR\", clusterCIDR.Name)\n\t\tif err := r.deleteClusterCIDR(logger, clusterCIDR); err != nil {\n\t\t\tklog.V(2).Info(\"Error while deleting ClusterCIDR\", \"err\", err)\n\t\t\treturn err\n\t\t}\n\t\t// Remove the finalizer as delete is successful.\n\t\tcccCopy := clusterCIDR.DeepCopy()\n\t\tcccCopy.ObjectMeta.Finalizers = slice.RemoveString(cccCopy.ObjectMeta.Finalizers, clusterCIDRFinalizer, nil)\n\t\tif _, err := r.client.NetworkingV1alpha1().ClusterCIDRs().Update(ctx, cccCopy, metav1.UpdateOptions{}); err != nil {\n\t\t\tlogger.V(2).Info(\"Error removing finalizer for ClusterCIDR\", \"clusterCIDR\", clusterCIDR.Name, \"err\", err)\n\t\t\treturn err\n\t\t}\n\t\tlogger.V(2).Info(\"Removed finalizer for ClusterCIDR\", \"clusterCIDR\", clusterCIDR.Name)\n\t}\n\treturn nil\n}","line":{"from":1144,"to":1167}} {"id":100004220,"name":"deleteClusterCIDR","signature":"func (r *multiCIDRRangeAllocator) deleteClusterCIDR(logger klog.Logger, clusterCIDR *networkingv1alpha1.ClusterCIDR) error","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// deleteClusterCIDR Deletes and unmaps the ClusterCIDRs from the cidrMap.\nfunc (r *multiCIDRRangeAllocator) deleteClusterCIDR(logger klog.Logger, clusterCIDR *networkingv1alpha1.ClusterCIDR) error {\n\n\tlabelSelector, err := r.nodeSelectorKey(clusterCIDR)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to delete cidr: %w\", err)\n\t}\n\n\tclusterCIDRSetList, ok := r.cidrMap[labelSelector]\n\tif !ok {\n\t\tlogger.Info(\"Label not found in CIDRMap, proceeding with delete\", \"labelSelector\", labelSelector)\n\t\treturn nil\n\t}\n\n\tfor i, clusterCIDRSet := range clusterCIDRSetList {\n\t\tif clusterCIDRSet.Name != clusterCIDR.Name {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Mark clusterCIDRSet as terminating.\n\t\tclusterCIDRSet.Terminating = true\n\n\t\t// Allow deletion only if no nodes are associated with the ClusterCIDR.\n\t\tif len(clusterCIDRSet.AssociatedNodes) \u003e 0 {\n\t\t\treturn fmt.Errorf(\"ClusterCIDRSet %s marked as terminating, won't be deleted until all associated nodes are deleted\", clusterCIDR.Name)\n\t\t}\n\n\t\t// Remove the label from the map if this was the only clusterCIDR associated\n\t\t// with it.\n\t\tif len(clusterCIDRSetList) == 1 {\n\t\t\tdelete(r.cidrMap, labelSelector)\n\t\t\treturn nil\n\t\t}\n\n\t\tclusterCIDRSetList = append(clusterCIDRSetList[:i], clusterCIDRSetList[i+1:]...)\n\t\tr.cidrMap[labelSelector] = clusterCIDRSetList\n\t\treturn nil\n\t}\n\tlogger.V(2).Info(\"clusterCIDR not found, proceeding with delete\", \"clusterCIDR\", clusterCIDR.Name, \"label\", labelSelector)\n\treturn nil\n}","line":{"from":1169,"to":1209}} {"id":100004221,"name":"nodeSelectorKey","signature":"func (r *multiCIDRRangeAllocator) nodeSelectorKey(clusterCIDR *networkingv1alpha1.ClusterCIDR) (string, error)","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"func (r *multiCIDRRangeAllocator) nodeSelectorKey(clusterCIDR *networkingv1alpha1.ClusterCIDR) (string, error) {\n\tvar nodeSelector labels.Selector\n\tvar err error\n\n\tif clusterCIDR.Spec.NodeSelector != nil {\n\t\tnodeSelector, err = nodeSelectorAsSelector(clusterCIDR.Spec.NodeSelector)\n\t} else {\n\t\tnodeSelector, err = nodeSelectorAsSelector(defaultNodeSelector())\n\t}\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn nodeSelector.String(), nil\n}","line":{"from":1211,"to":1226}} {"id":100004222,"name":"listClusterCIDRs","signature":"func listClusterCIDRs(ctx context.Context, kubeClient clientset.Interface) (*networkingv1alpha1.ClusterCIDRList, error)","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"func listClusterCIDRs(ctx context.Context, kubeClient clientset.Interface) (*networkingv1alpha1.ClusterCIDRList, error) {\n\tvar clusterCIDRList *networkingv1alpha1.ClusterCIDRList\n\t// We must poll because apiserver might not be up. This error causes\n\t// controller manager to restart.\n\tstartTimestamp := time.Now()\n\n\t// start with 2s, multiply the duration by 1.6 each step, 11 steps = 9.7 minutes\n\tbackoff := wait.Backoff{\n\t\tDuration: 2 * time.Second,\n\t\tFactor: 1.6,\n\t\tSteps: 11,\n\t}\n\n\tlogger := klog.FromContext(ctx)\n\tif pollErr := wait.ExponentialBackoff(backoff, func() (bool, error) {\n\t\tvar err error\n\t\tclusterCIDRList, err = kubeClient.NetworkingV1alpha1().ClusterCIDRs().List(ctx, metav1.ListOptions{\n\t\t\tFieldSelector: fields.Everything().String(),\n\t\t\tLabelSelector: labels.Everything().String(),\n\t\t})\n\t\tif err != nil {\n\t\t\tlogger.Error(err, \"Failed to list all clusterCIDRs\")\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t}); pollErr != nil {\n\t\tlogger.Error(nil, \"Failed to list clusterCIDRs\", \"latency\", time.Now().Sub(startTimestamp))\n\t\treturn nil, fmt.Errorf(\"failed to list all clusterCIDRs in %v, cannot proceed without updating CIDR map\",\n\t\t\tapiserverStartupGracePeriod)\n\t}\n\treturn clusterCIDRList, nil\n}","line":{"from":1228,"to":1259}} {"id":100004223,"name":"nodeSelectorRequirementsAsLabelRequirements","signature":"func nodeSelectorRequirementsAsLabelRequirements(nsr v1.NodeSelectorRequirement) (*labels.Requirement, error)","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// nodeSelectorRequirementsAsLabelRequirements converts the NodeSelectorRequirement\n// type to a labels.Requirement type.\nfunc nodeSelectorRequirementsAsLabelRequirements(nsr v1.NodeSelectorRequirement) (*labels.Requirement, error) {\n\tvar op selection.Operator\n\tswitch nsr.Operator {\n\tcase v1.NodeSelectorOpIn:\n\t\top = selection.In\n\tcase v1.NodeSelectorOpNotIn:\n\t\top = selection.NotIn\n\tcase v1.NodeSelectorOpExists:\n\t\top = selection.Exists\n\tcase v1.NodeSelectorOpDoesNotExist:\n\t\top = selection.DoesNotExist\n\tcase v1.NodeSelectorOpGt:\n\t\top = selection.GreaterThan\n\tcase v1.NodeSelectorOpLt:\n\t\top = selection.LessThan\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"%q is not a valid node selector operator\", nsr.Operator)\n\t}\n\treturn labels.NewRequirement(nsr.Key, op, nsr.Values)\n}","line":{"from":1261,"to":1282}} {"id":100004224,"name":"nodeSelectorAsSelector","signature":"func nodeSelectorAsSelector(ns *v1.NodeSelector) (labels.Selector, error)","file":"pkg/controller/nodeipam/ipam/multi_cidr_range_allocator.go","code":"// TODO: nodeSelect and labelSelector semantics are different and the function\n// doesn't translate them correctly, this has to be fixed before Beta\n// xref: https://issues.k8s.io/116419\n// nodeSelectorAsSelector converts the NodeSelector api type into a struct that\n// implements labels.Selector\n// Note: This function should be kept in sync with the selector methods in\n// pkg/labels/selector.go\nfunc nodeSelectorAsSelector(ns *v1.NodeSelector) (labels.Selector, error) {\n\tif ns == nil {\n\t\treturn labels.Nothing(), nil\n\t}\n\tif len(ns.NodeSelectorTerms) == 0 {\n\t\treturn labels.Everything(), nil\n\t}\n\tvar requirements []labels.Requirement\n\n\tfor _, nsTerm := range ns.NodeSelectorTerms {\n\t\tfor _, expr := range nsTerm.MatchExpressions {\n\t\t\treq, err := nodeSelectorRequirementsAsLabelRequirements(expr)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\trequirements = append(requirements, *req)\n\t\t}\n\n\t\tfor _, field := range nsTerm.MatchFields {\n\t\t\treq, err := nodeSelectorRequirementsAsLabelRequirements(field)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\trequirements = append(requirements, *req)\n\t\t}\n\t}\n\n\tselector := labels.NewSelector()\n\tselector = selector.Add(requirements...)\n\treturn selector, nil\n}","line":{"from":1284,"to":1321}} {"id":100004225,"name":"registerCidrsetMetrics","signature":"func registerCidrsetMetrics()","file":"pkg/controller/nodeipam/ipam/multicidrset/metrics.go","code":"// registerCidrsetMetrics the metrics that are to be monitored.\nfunc registerCidrsetMetrics() {\n\tregisterMetrics.Do(func() {\n\t\tlegacyregistry.MustRegister(cidrSetAllocations)\n\t\tlegacyregistry.MustRegister(cidrSetReleases)\n\t\tlegacyregistry.MustRegister(cidrSetMaxCidrs)\n\t\tlegacyregistry.MustRegister(cidrSetUsage)\n\t\tlegacyregistry.MustRegister(cidrSetAllocationTriesPerRequest)\n\t})\n}","line":{"from":80,"to":89}} {"id":100004226,"name":"Error","signature":"func (err *CIDRRangeNoCIDRsRemainingErr) Error() string","file":"pkg/controller/nodeipam/ipam/multicidrset/multi_cidr_set.go","code":"func (err *CIDRRangeNoCIDRsRemainingErr) Error() string {\n\treturn fmt.Sprintf(\"CIDR allocation failed; there are no remaining CIDRs left to allocate in the range %s\", err.CIDR)\n}","line":{"from":96,"to":98}} {"id":100004227,"name":"Error","signature":"func (err *CIDRSetSubNetTooBigErr) Error() string","file":"pkg/controller/nodeipam/ipam/multicidrset/multi_cidr_set.go","code":"func (err *CIDRSetSubNetTooBigErr) Error() string {\n\treturn fmt.Sprintf(\"Creation of New CIDR Set failed for %s. \"+\n\t\t\"PerNodeMaskSize %d is too big for CIDR Mask %d, Maximum difference allowed \"+\n\t\t\"is %d\", err.cidr, err.subnetMaskSize, err.clusterMaskSize, clusterSubnetMaxDiff)\n}","line":{"from":108,"to":112}} {"id":100004228,"name":"NewMultiCIDRSet","signature":"func NewMultiCIDRSet(cidrConfig *net.IPNet, perNodeHostBits int) (*MultiCIDRSet, error)","file":"pkg/controller/nodeipam/ipam/multicidrset/multi_cidr_set.go","code":"// NewMultiCIDRSet creates a new MultiCIDRSet.\nfunc NewMultiCIDRSet(cidrConfig *net.IPNet, perNodeHostBits int) (*MultiCIDRSet, error) {\n\tclusterMask := cidrConfig.Mask\n\tclusterMaskSize, bits := clusterMask.Size()\n\n\tvar subNetMaskSize int\n\tswitch /*v4 or v6*/ {\n\tcase netutils.IsIPv4(cidrConfig.IP):\n\t\tsubNetMaskSize = 32 - perNodeHostBits\n\tcase netutils.IsIPv6(cidrConfig.IP):\n\t\tsubNetMaskSize = 128 - perNodeHostBits\n\t}\n\n\tif netutils.IsIPv6(cidrConfig.IP) \u0026\u0026 (subNetMaskSize-clusterMaskSize \u003e clusterSubnetMaxDiff) {\n\t\treturn nil, \u0026CIDRSetSubNetTooBigErr{\n\t\t\tcidr: cidrConfig.String(),\n\t\t\tsubnetMaskSize: subNetMaskSize,\n\t\t\tclusterMaskSize: clusterMaskSize,\n\t\t}\n\t}\n\n\t// Register MultiCIDRSet metrics.\n\tregisterCidrsetMetrics()\n\n\tmaxCIDRs := getMaxCIDRs(subNetMaskSize, clusterMaskSize)\n\tmultiCIDRSet := \u0026MultiCIDRSet{\n\t\tClusterCIDR: cidrConfig,\n\t\tnodeMask: net.CIDRMask(subNetMaskSize, bits),\n\t\tclusterMaskSize: clusterMaskSize,\n\t\tMaxCIDRs: maxCIDRs,\n\t\tNodeMaskSize: subNetMaskSize,\n\t\tLabel: cidrConfig.String(),\n\t\tAllocatedCIDRMap: make(map[string]bool, 0),\n\t}\n\tcidrSetMaxCidrs.WithLabelValues(multiCIDRSet.Label).Set(float64(maxCIDRs))\n\n\treturn multiCIDRSet, nil\n}","line":{"from":114,"to":151}} {"id":100004229,"name":"indexToCIDRBlock","signature":"func (s *MultiCIDRSet) indexToCIDRBlock(index int) (*net.IPNet, error)","file":"pkg/controller/nodeipam/ipam/multicidrset/multi_cidr_set.go","code":"func (s *MultiCIDRSet) indexToCIDRBlock(index int) (*net.IPNet, error) {\n\tvar ip []byte\n\tswitch /*v4 or v6*/ {\n\tcase netutils.IsIPv4(s.ClusterCIDR.IP):\n\t\tj := uint32(index) \u003c\u003c uint32(32-s.NodeMaskSize)\n\t\tipInt := (binary.BigEndian.Uint32(s.ClusterCIDR.IP)) | j\n\t\tip = make([]byte, net.IPv4len)\n\t\tbinary.BigEndian.PutUint32(ip, ipInt)\n\tcase netutils.IsIPv6(s.ClusterCIDR.IP):\n\t\t// leftClusterIP | rightClusterIP\n\t\t// 2001:0DB8:1234:0000:0000:0000:0000:0000\n\t\tconst v6NBits = 128\n\t\tconst halfV6NBits = v6NBits / 2\n\t\tleftClusterIP := binary.BigEndian.Uint64(s.ClusterCIDR.IP[:halfIPv6Len])\n\t\trightClusterIP := binary.BigEndian.Uint64(s.ClusterCIDR.IP[halfIPv6Len:])\n\n\t\tip = make([]byte, net.IPv6len)\n\n\t\tif s.NodeMaskSize \u003c= halfV6NBits {\n\t\t\t// We only care about left side IP.\n\t\t\tleftClusterIP |= uint64(index) \u003c\u003c uint(halfV6NBits-s.NodeMaskSize)\n\t\t} else {\n\t\t\tif s.clusterMaskSize \u003c halfV6NBits {\n\t\t\t\t// see how many bits are needed to reach the left side.\n\t\t\t\tbtl := uint(s.NodeMaskSize - halfV6NBits)\n\t\t\t\tindexMaxBit := uint(64 - bits.LeadingZeros64(uint64(index)))\n\t\t\t\tif indexMaxBit \u003e btl {\n\t\t\t\t\tleftClusterIP |= uint64(index) \u003e\u003e btl\n\t\t\t\t}\n\t\t\t}\n\t\t\t// the right side will be calculated the same way either the\n\t\t\t// subNetMaskSize affects both left and right sides.\n\t\t\trightClusterIP |= uint64(index) \u003c\u003c uint(v6NBits-s.NodeMaskSize)\n\t\t}\n\t\tbinary.BigEndian.PutUint64(ip[:halfIPv6Len], leftClusterIP)\n\t\tbinary.BigEndian.PutUint64(ip[halfIPv6Len:], rightClusterIP)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid IP: %s\", s.ClusterCIDR.IP)\n\t}\n\treturn \u0026net.IPNet{\n\t\tIP: ip,\n\t\tMask: s.nodeMask,\n\t}, nil\n}","line":{"from":153,"to":196}} {"id":100004230,"name":"NextCandidate","signature":"func (s *MultiCIDRSet) NextCandidate() (*net.IPNet, int, error)","file":"pkg/controller/nodeipam/ipam/multicidrset/multi_cidr_set.go","code":"// NextCandidate returns the next candidate and the last evaluated index\n// for the current cidrSet. Returns nil if the candidate is already allocated.\nfunc (s *MultiCIDRSet) NextCandidate() (*net.IPNet, int, error) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tif s.allocatedCIDRs == s.MaxCIDRs {\n\t\treturn nil, 0, \u0026CIDRRangeNoCIDRsRemainingErr{\n\t\t\tCIDR: s.Label,\n\t\t}\n\t}\n\n\tcandidate := s.nextCandidate\n\tfor i := 0; i \u003c s.MaxCIDRs; i++ {\n\t\tnextCandidateCIDR, err := s.indexToCIDRBlock(candidate)\n\t\tif err != nil {\n\t\t\treturn nil, i, err\n\t\t}\n\t\t// Check if the nextCandidate is not already allocated.\n\t\tif _, ok := s.AllocatedCIDRMap[nextCandidateCIDR.String()]; !ok {\n\t\t\ts.nextCandidate = (candidate + 1) % s.MaxCIDRs\n\t\t\treturn nextCandidateCIDR, i, nil\n\t\t}\n\t\tcandidate = (candidate + 1) % s.MaxCIDRs\n\t}\n\n\treturn nil, s.MaxCIDRs, \u0026CIDRRangeNoCIDRsRemainingErr{\n\t\tCIDR: s.Label,\n\t}\n}","line":{"from":198,"to":227}} {"id":100004231,"name":"getBeginningAndEndIndices","signature":"func (s *MultiCIDRSet) getBeginningAndEndIndices(cidr *net.IPNet) (int, int, error)","file":"pkg/controller/nodeipam/ipam/multicidrset/multi_cidr_set.go","code":"// getBeginningAndEndIndices returns the indices for the given CIDR, returned\n// values are inclusive indices [beginning, end].\nfunc (s *MultiCIDRSet) getBeginningAndEndIndices(cidr *net.IPNet) (int, int, error) {\n\tif cidr == nil {\n\t\treturn -1, -1, fmt.Errorf(\"error getting indices for cluster cidr %v, cidr is nil\", s.ClusterCIDR)\n\t}\n\tbegin, end := 0, s.MaxCIDRs-1\n\tcidrMask := cidr.Mask\n\tmaskSize, _ := cidrMask.Size()\n\tvar ipSize int\n\n\tif !s.ClusterCIDR.Contains(cidr.IP.Mask(s.ClusterCIDR.Mask)) \u0026\u0026 !cidr.Contains(s.ClusterCIDR.IP.Mask(cidr.Mask)) {\n\t\treturn -1, -1, fmt.Errorf(\"cidr %v is out the range of cluster cidr %v\", cidr, s.ClusterCIDR)\n\t}\n\n\tif s.clusterMaskSize \u003c maskSize {\n\t\tvar err error\n\t\tipSize = net.IPv4len\n\t\tif netutils.IsIPv6(cidr.IP) {\n\t\t\tipSize = net.IPv6len\n\t\t}\n\t\tbegin, err = s.getIndexForCIDR(\u0026net.IPNet{\n\t\t\tIP: cidr.IP.Mask(s.nodeMask),\n\t\t\tMask: s.nodeMask,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn -1, -1, err\n\t\t}\n\t\tip := make([]byte, ipSize)\n\t\tif netutils.IsIPv4(cidr.IP) {\n\t\t\tipInt := binary.BigEndian.Uint32(cidr.IP) | (^binary.BigEndian.Uint32(cidr.Mask))\n\t\t\tbinary.BigEndian.PutUint32(ip, ipInt)\n\t\t} else {\n\t\t\t// ipIntLeft | ipIntRight\n\t\t\t// 2001:0DB8:1234:0000:0000:0000:0000:0000\n\t\t\tipIntLeft := binary.BigEndian.Uint64(cidr.IP[:net.IPv6len/2]) | (^binary.BigEndian.Uint64(cidr.Mask[:net.IPv6len/2]))\n\t\t\tipIntRight := binary.BigEndian.Uint64(cidr.IP[net.IPv6len/2:]) | (^binary.BigEndian.Uint64(cidr.Mask[net.IPv6len/2:]))\n\t\t\tbinary.BigEndian.PutUint64(ip[:net.IPv6len/2], ipIntLeft)\n\t\t\tbinary.BigEndian.PutUint64(ip[net.IPv6len/2:], ipIntRight)\n\t\t}\n\t\tend, err = s.getIndexForCIDR(\u0026net.IPNet{\n\t\t\tIP: net.IP(ip).Mask(s.nodeMask),\n\t\t\tMask: s.nodeMask,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn -1, -1, err\n\t\t}\n\t}\n\treturn begin, end, nil\n}","line":{"from":229,"to":278}} {"id":100004232,"name":"Release","signature":"func (s *MultiCIDRSet) Release(cidr *net.IPNet) error","file":"pkg/controller/nodeipam/ipam/multicidrset/multi_cidr_set.go","code":"// Release releases the given CIDR range.\nfunc (s *MultiCIDRSet) Release(cidr *net.IPNet) error {\n\tbegin, end, err := s.getBeginningAndEndIndices(cidr)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tfor i := begin; i \u003c= end; i++ {\n\t\t// Remove from the allocated CIDR Map and decrement the counter only if currently\n\t\t// marked allocated. Avoids double counting.\n\t\tcurrCIDR, err := s.indexToCIDRBlock(i)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, ok := s.AllocatedCIDRMap[currCIDR.String()]; ok {\n\t\t\tdelete(s.AllocatedCIDRMap, currCIDR.String())\n\t\t\ts.allocatedCIDRs--\n\t\t\tcidrSetReleases.WithLabelValues(s.Label).Inc()\n\t\t}\n\t}\n\n\tcidrSetUsage.WithLabelValues(s.Label).Set(float64(s.allocatedCIDRs) / float64(s.MaxCIDRs))\n\n\treturn nil\n}","line":{"from":280,"to":306}} {"id":100004233,"name":"Occupy","signature":"func (s *MultiCIDRSet) Occupy(cidr *net.IPNet) (err error)","file":"pkg/controller/nodeipam/ipam/multicidrset/multi_cidr_set.go","code":"// Occupy marks the given CIDR range as used. Occupy succeeds even if the CIDR\n// range was previously used.\nfunc (s *MultiCIDRSet) Occupy(cidr *net.IPNet) (err error) {\n\tbegin, end, err := s.getBeginningAndEndIndices(cidr)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tfor i := begin; i \u003c= end; i++ {\n\t\t// Add to the allocated CIDR Map and increment the counter only if not already\n\t\t// marked allocated. Prevents double counting.\n\t\tcurrCIDR, err := s.indexToCIDRBlock(i)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, ok := s.AllocatedCIDRMap[currCIDR.String()]; !ok {\n\t\t\ts.AllocatedCIDRMap[currCIDR.String()] = true\n\t\t\tcidrSetAllocations.WithLabelValues(s.Label).Inc()\n\t\t\ts.allocatedCIDRs++\n\t\t}\n\t}\n\tcidrSetUsage.WithLabelValues(s.Label).Set(float64(s.allocatedCIDRs) / float64(s.MaxCIDRs))\n\n\treturn nil\n}","line":{"from":308,"to":334}} {"id":100004234,"name":"getIndexForCIDR","signature":"func (s *MultiCIDRSet) getIndexForCIDR(cidr *net.IPNet) (int, error)","file":"pkg/controller/nodeipam/ipam/multicidrset/multi_cidr_set.go","code":"func (s *MultiCIDRSet) getIndexForCIDR(cidr *net.IPNet) (int, error) {\n\treturn s.getIndexForIP(cidr.IP)\n}","line":{"from":336,"to":338}} {"id":100004235,"name":"getIndexForIP","signature":"func (s *MultiCIDRSet) getIndexForIP(ip net.IP) (int, error)","file":"pkg/controller/nodeipam/ipam/multicidrset/multi_cidr_set.go","code":"func (s *MultiCIDRSet) getIndexForIP(ip net.IP) (int, error) {\n\tif ip.To4() != nil {\n\t\tcidrIndex := (binary.BigEndian.Uint32(s.ClusterCIDR.IP) ^ binary.BigEndian.Uint32(ip.To4())) \u003e\u003e uint32(32-s.NodeMaskSize)\n\t\tif cidrIndex \u003e= uint32(s.MaxCIDRs) {\n\t\t\treturn 0, fmt.Errorf(\"CIDR: %v/%v is out of the range of CIDR allocator\", ip, s.NodeMaskSize)\n\t\t}\n\t\treturn int(cidrIndex), nil\n\t}\n\tif netutils.IsIPv6(ip) {\n\t\tbigIP := big.NewInt(0).SetBytes(s.ClusterCIDR.IP)\n\t\tbigIP = bigIP.Xor(bigIP, big.NewInt(0).SetBytes(ip))\n\t\tcidrIndexBig := bigIP.Rsh(bigIP, uint(net.IPv6len*8-s.NodeMaskSize))\n\t\tcidrIndex := cidrIndexBig.Uint64()\n\t\tif cidrIndex \u003e= uint64(s.MaxCIDRs) {\n\t\t\treturn 0, fmt.Errorf(\"CIDR: %v/%v is out of the range of CIDR allocator\", ip, s.NodeMaskSize)\n\t\t}\n\t\treturn int(cidrIndex), nil\n\t}\n\n\treturn 0, fmt.Errorf(\"invalid IP: %v\", ip)\n}","line":{"from":340,"to":360}} {"id":100004236,"name":"UpdateEvaluatedCount","signature":"func (s *MultiCIDRSet) UpdateEvaluatedCount(evaluated int)","file":"pkg/controller/nodeipam/ipam/multicidrset/multi_cidr_set.go","code":"// UpdateEvaluatedCount increments the evaluated count.\nfunc (s *MultiCIDRSet) UpdateEvaluatedCount(evaluated int) {\n\tcidrSetAllocationTriesPerRequest.WithLabelValues(s.Label).Observe(float64(evaluated))\n}","line":{"from":362,"to":365}} {"id":100004237,"name":"getMaxCIDRs","signature":"func getMaxCIDRs(subNetMaskSize, clusterMaskSize int) int","file":"pkg/controller/nodeipam/ipam/multicidrset/multi_cidr_set.go","code":"// getMaxCIDRs returns the max number of CIDRs that can be obtained by subdividing a mask of size `clusterMaskSize`\n// into subnets with mask of size `subNetMaskSize`.\nfunc getMaxCIDRs(subNetMaskSize, clusterMaskSize int) int {\n\treturn 1 \u003c\u003c uint32(subNetMaskSize-clusterMaskSize)\n}","line":{"from":367,"to":371}} {"id":100004238,"name":"NewCIDRRangeAllocator","signature":"func NewCIDRRangeAllocator(logger klog.Logger, client clientset.Interface, nodeInformer informers.NodeInformer, allocatorParams CIDRAllocatorParams, nodeList *v1.NodeList) (CIDRAllocator, error)","file":"pkg/controller/nodeipam/ipam/range_allocator.go","code":"// NewCIDRRangeAllocator returns a CIDRAllocator to allocate CIDRs for node (one from each of clusterCIDRs)\n// Caller must ensure subNetMaskSize is not less than cluster CIDR mask size.\n// Caller must always pass in a list of existing nodes so the new allocator.\n// Caller must ensure that ClusterCIDRs are semantically correct e.g (1 for non DualStack, 2 for DualStack etc..)\n// can initialize its CIDR map. NodeList is only nil in testing.\nfunc NewCIDRRangeAllocator(logger klog.Logger, client clientset.Interface, nodeInformer informers.NodeInformer, allocatorParams CIDRAllocatorParams, nodeList *v1.NodeList) (CIDRAllocator, error) {\n\tif client == nil {\n\t\tlogger.Error(nil, \"kubeClient is nil when starting CIDRRangeAllocator\")\n\t\tklog.FlushAndExit(klog.ExitFlushTimeout, 1)\n\t}\n\n\teventBroadcaster := record.NewBroadcaster()\n\trecorder := eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"cidrAllocator\"})\n\n\t// create a cidrSet for each cidr we operate on\n\t// cidrSet are mapped to clusterCIDR by index\n\tcidrSets := make([]*cidrset.CidrSet, len(allocatorParams.ClusterCIDRs))\n\tfor idx, cidr := range allocatorParams.ClusterCIDRs {\n\t\tcidrSet, err := cidrset.NewCIDRSet(cidr, allocatorParams.NodeCIDRMaskSizes[idx])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcidrSets[idx] = cidrSet\n\t}\n\n\tra := \u0026rangeAllocator{\n\t\tclient: client,\n\t\tclusterCIDRs: allocatorParams.ClusterCIDRs,\n\t\tcidrSets: cidrSets,\n\t\tnodeLister: nodeInformer.Lister(),\n\t\tnodesSynced: nodeInformer.Informer().HasSynced,\n\t\tnodeCIDRUpdateChannel: make(chan nodeReservedCIDRs, cidrUpdateQueueSize),\n\t\tbroadcaster: eventBroadcaster,\n\t\trecorder: recorder,\n\t\tnodesInProcessing: sets.NewString(),\n\t}\n\n\tif allocatorParams.ServiceCIDR != nil {\n\t\tra.filterOutServiceRange(logger, allocatorParams.ServiceCIDR)\n\t} else {\n\t\tlogger.Info(\"No Service CIDR provided. Skipping filtering out service addresses\")\n\t}\n\n\tif allocatorParams.SecondaryServiceCIDR != nil {\n\t\tra.filterOutServiceRange(logger, allocatorParams.SecondaryServiceCIDR)\n\t} else {\n\t\tlogger.Info(\"No Secondary Service CIDR provided. Skipping filtering out secondary service addresses\")\n\t}\n\n\tif nodeList != nil {\n\t\tfor _, node := range nodeList.Items {\n\t\t\tif len(node.Spec.PodCIDRs) == 0 {\n\t\t\t\tlogger.V(4).Info(\"Node has no CIDR, ignoring\", \"node\", klog.KObj(\u0026node))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlogger.V(4).Info(\"Node has CIDR, occupying it in CIDR map\", \"node\", klog.KObj(\u0026node), \"podCIDR\", node.Spec.PodCIDR)\n\t\t\tif err := ra.occupyCIDRs(\u0026node); err != nil {\n\t\t\t\t// This will happen if:\n\t\t\t\t// 1. We find garbage in the podCIDRs field. Retrying is useless.\n\t\t\t\t// 2. CIDR out of range: This means a node CIDR has changed.\n\t\t\t\t// This error will keep crashing controller-manager.\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\tnodeInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: controllerutil.CreateAddNodeHandler(func(node *v1.Node) error {\n\t\t\treturn ra.AllocateOrOccupyCIDR(logger, node)\n\t\t}),\n\t\tUpdateFunc: controllerutil.CreateUpdateNodeHandler(func(_, newNode *v1.Node) error {\n\t\t\t// If the PodCIDRs list is not empty we either:\n\t\t\t// - already processed a Node that already had CIDRs after NC restarted\n\t\t\t// (cidr is marked as used),\n\t\t\t// - already processed a Node successfully and allocated CIDRs for it\n\t\t\t// (cidr is marked as used),\n\t\t\t// - already processed a Node but we did saw a \"timeout\" response and\n\t\t\t// request eventually got through in this case we haven't released\n\t\t\t// the allocated CIDRs (cidr is still marked as used).\n\t\t\t// There's a possible error here:\n\t\t\t// - NC sees a new Node and assigns CIDRs X,Y.. to it,\n\t\t\t// - Update Node call fails with a timeout,\n\t\t\t// - Node is updated by some other component, NC sees an update and\n\t\t\t// assigns CIDRs A,B.. to the Node,\n\t\t\t// - Both CIDR X,Y.. and CIDR A,B.. are marked as used in the local cache,\n\t\t\t// even though Node sees only CIDR A,B..\n\t\t\t// The problem here is that in in-memory cache we see CIDR X,Y.. as marked,\n\t\t\t// which prevents it from being assigned to any new node. The cluster\n\t\t\t// state is correct.\n\t\t\t// Restart of NC fixes the issue.\n\t\t\tif len(newNode.Spec.PodCIDRs) == 0 {\n\t\t\t\treturn ra.AllocateOrOccupyCIDR(logger, newNode)\n\t\t\t}\n\t\t\treturn nil\n\t\t}),\n\t\tDeleteFunc: controllerutil.CreateDeleteNodeHandler(func(node *v1.Node) error {\n\t\t\treturn ra.ReleaseCIDR(logger, node)\n\t\t}),\n\t})\n\n\treturn ra, nil\n}","line":{"from":65,"to":166}} {"id":100004239,"name":"Run","signature":"func (r *rangeAllocator) Run(ctx context.Context)","file":"pkg/controller/nodeipam/ipam/range_allocator.go","code":"func (r *rangeAllocator) Run(ctx context.Context) {\n\tdefer utilruntime.HandleCrash()\n\n\t// Start event processing pipeline.\n\tr.broadcaster.StartStructuredLogging(0)\n\tlogger := klog.FromContext(ctx)\n\tlogger.Info(\"Sending events to api server\")\n\tr.broadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: r.client.CoreV1().Events(\"\")})\n\tdefer r.broadcaster.Shutdown()\n\n\tlogger.Info(\"Starting range CIDR allocator\")\n\tdefer logger.Info(\"Shutting down range CIDR allocator\")\n\n\tif !cache.WaitForNamedCacheSync(\"cidrallocator\", ctx.Done(), r.nodesSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c cidrUpdateWorkers; i++ {\n\t\tgo r.worker(ctx)\n\t}\n\n\t\u003c-ctx.Done()\n}","line":{"from":168,"to":190}} {"id":100004240,"name":"worker","signature":"func (r *rangeAllocator) worker(ctx context.Context)","file":"pkg/controller/nodeipam/ipam/range_allocator.go","code":"func (r *rangeAllocator) worker(ctx context.Context) {\n\tlogger := klog.FromContext(ctx)\n\tfor {\n\t\tselect {\n\t\tcase workItem, ok := \u003c-r.nodeCIDRUpdateChannel:\n\t\t\tif !ok {\n\t\t\t\tlogger.Info(\"Channel nodeCIDRUpdateChannel was unexpectedly closed\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err := r.updateCIDRsAllocation(logger, workItem); err != nil {\n\t\t\t\t// Requeue the failed node for update again.\n\t\t\t\tr.nodeCIDRUpdateChannel \u003c- workItem\n\t\t\t}\n\t\tcase \u003c-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}","line":{"from":192,"to":209}} {"id":100004241,"name":"insertNodeToProcessing","signature":"func (r *rangeAllocator) insertNodeToProcessing(nodeName string) bool","file":"pkg/controller/nodeipam/ipam/range_allocator.go","code":"func (r *rangeAllocator) insertNodeToProcessing(nodeName string) bool {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\tif r.nodesInProcessing.Has(nodeName) {\n\t\treturn false\n\t}\n\tr.nodesInProcessing.Insert(nodeName)\n\treturn true\n}","line":{"from":211,"to":219}} {"id":100004242,"name":"removeNodeFromProcessing","signature":"func (r *rangeAllocator) removeNodeFromProcessing(nodeName string)","file":"pkg/controller/nodeipam/ipam/range_allocator.go","code":"func (r *rangeAllocator) removeNodeFromProcessing(nodeName string) {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\tr.nodesInProcessing.Delete(nodeName)\n}","line":{"from":221,"to":225}} {"id":100004243,"name":"occupyCIDRs","signature":"func (r *rangeAllocator) occupyCIDRs(node *v1.Node) error","file":"pkg/controller/nodeipam/ipam/range_allocator.go","code":"// marks node.PodCIDRs[...] as used in allocator's tracked cidrSet\nfunc (r *rangeAllocator) occupyCIDRs(node *v1.Node) error {\n\tdefer r.removeNodeFromProcessing(node.Name)\n\tif len(node.Spec.PodCIDRs) == 0 {\n\t\treturn nil\n\t}\n\tfor idx, cidr := range node.Spec.PodCIDRs {\n\t\t_, podCIDR, err := netutils.ParseCIDRSloppy(cidr)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to parse node %s, CIDR %s\", node.Name, node.Spec.PodCIDR)\n\t\t}\n\t\t// If node has a pre allocate cidr that does not exist in our cidrs.\n\t\t// This will happen if cluster went from dualstack(multi cidrs) to non-dualstack\n\t\t// then we have now way of locking it\n\t\tif idx \u003e= len(r.cidrSets) {\n\t\t\treturn fmt.Errorf(\"node:%s has an allocated cidr: %v at index:%v that does not exist in cluster cidrs configuration\", node.Name, cidr, idx)\n\t\t}\n\n\t\tif err := r.cidrSets[idx].Occupy(podCIDR); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to mark cidr[%v] at idx [%v] as occupied for node: %v: %v\", podCIDR, idx, node.Name, err)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":227,"to":250}} {"id":100004244,"name":"AllocateOrOccupyCIDR","signature":"func (r *rangeAllocator) AllocateOrOccupyCIDR(logger klog.Logger, node *v1.Node) error","file":"pkg/controller/nodeipam/ipam/range_allocator.go","code":"// WARNING: If you're adding any return calls or defer any more work from this\n// function you have to make sure to update nodesInProcessing properly with the\n// disposition of the node when the work is done.\nfunc (r *rangeAllocator) AllocateOrOccupyCIDR(logger klog.Logger, node *v1.Node) error {\n\tif node == nil {\n\t\treturn nil\n\t}\n\tif !r.insertNodeToProcessing(node.Name) {\n\t\tlogger.V(2).Info(\"Node is already in a process of CIDR assignment\", \"node\", klog.KObj(node))\n\t\treturn nil\n\t}\n\n\tif len(node.Spec.PodCIDRs) \u003e 0 {\n\t\treturn r.occupyCIDRs(node)\n\t}\n\t// allocate and queue the assignment\n\tallocated := nodeReservedCIDRs{\n\t\tnodeName: node.Name,\n\t\tallocatedCIDRs: make([]*net.IPNet, len(r.cidrSets)),\n\t}\n\n\tfor idx := range r.cidrSets {\n\t\tpodCIDR, err := r.cidrSets[idx].AllocateNext()\n\t\tif err != nil {\n\t\t\tr.removeNodeFromProcessing(node.Name)\n\t\t\tcontrollerutil.RecordNodeStatusChange(r.recorder, node, \"CIDRNotAvailable\")\n\t\t\treturn fmt.Errorf(\"failed to allocate cidr from cluster cidr at idx:%v: %v\", idx, err)\n\t\t}\n\t\tallocated.allocatedCIDRs[idx] = podCIDR\n\t}\n\n\t//queue the assignment\n\tlogger.V(4).Info(\"Putting node with CIDR into the work queue\", \"node\", klog.KObj(node), \"CIDRs\", allocated.allocatedCIDRs)\n\tr.nodeCIDRUpdateChannel \u003c- allocated\n\treturn nil\n}","line":{"from":252,"to":287}} {"id":100004245,"name":"ReleaseCIDR","signature":"func (r *rangeAllocator) ReleaseCIDR(logger klog.Logger, node *v1.Node) error","file":"pkg/controller/nodeipam/ipam/range_allocator.go","code":"// ReleaseCIDR marks node.podCIDRs[...] as unused in our tracked cidrSets\nfunc (r *rangeAllocator) ReleaseCIDR(logger klog.Logger, node *v1.Node) error {\n\tif node == nil || len(node.Spec.PodCIDRs) == 0 {\n\t\treturn nil\n\t}\n\n\tfor idx, cidr := range node.Spec.PodCIDRs {\n\t\t_, podCIDR, err := netutils.ParseCIDRSloppy(cidr)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to parse CIDR %s on Node %v: %v\", cidr, node.Name, err)\n\t\t}\n\n\t\t// If node has a pre allocate cidr that does not exist in our cidrs.\n\t\t// This will happen if cluster went from dualstack(multi cidrs) to non-dualstack\n\t\t// then we have now way of locking it\n\t\tif idx \u003e= len(r.cidrSets) {\n\t\t\treturn fmt.Errorf(\"node:%s has an allocated cidr: %v at index:%v that does not exist in cluster cidrs configuration\", node.Name, cidr, idx)\n\t\t}\n\n\t\tlogger.V(4).Info(\"Release CIDR for node\", \"CIDR\", cidr, \"node\", klog.KObj(node))\n\t\tif err = r.cidrSets[idx].Release(podCIDR); err != nil {\n\t\t\treturn fmt.Errorf(\"error when releasing CIDR %v: %v\", cidr, err)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":289,"to":314}} {"id":100004246,"name":"filterOutServiceRange","signature":"func (r *rangeAllocator) filterOutServiceRange(logger klog.Logger, serviceCIDR *net.IPNet)","file":"pkg/controller/nodeipam/ipam/range_allocator.go","code":"// Marks all CIDRs with subNetMaskSize that belongs to serviceCIDR as used across all cidrs\n// so that they won't be assignable.\nfunc (r *rangeAllocator) filterOutServiceRange(logger klog.Logger, serviceCIDR *net.IPNet) {\n\t// Checks if service CIDR has a nonempty intersection with cluster\n\t// CIDR. It is the case if either clusterCIDR contains serviceCIDR with\n\t// clusterCIDR's Mask applied (this means that clusterCIDR contains\n\t// serviceCIDR) or vice versa (which means that serviceCIDR contains\n\t// clusterCIDR).\n\tfor idx, cidr := range r.clusterCIDRs {\n\t\t// if they don't overlap then ignore the filtering\n\t\tif !cidr.Contains(serviceCIDR.IP.Mask(cidr.Mask)) \u0026\u0026 !serviceCIDR.Contains(cidr.IP.Mask(serviceCIDR.Mask)) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// at this point, len(cidrSet) == len(clusterCidr)\n\t\tif err := r.cidrSets[idx].Occupy(serviceCIDR); err != nil {\n\t\t\tlogger.Error(err, \"Error filtering out service cidr out cluster cidr\", \"CIDR\", cidr, \"index\", idx, \"serviceCIDR\", serviceCIDR)\n\t\t}\n\t}\n}","line":{"from":316,"to":335}} {"id":100004247,"name":"updateCIDRsAllocation","signature":"func (r *rangeAllocator) updateCIDRsAllocation(logger klog.Logger, data nodeReservedCIDRs) error","file":"pkg/controller/nodeipam/ipam/range_allocator.go","code":"// updateCIDRsAllocation assigns CIDR to Node and sends an update to the API server.\nfunc (r *rangeAllocator) updateCIDRsAllocation(logger klog.Logger, data nodeReservedCIDRs) error {\n\tvar err error\n\tvar node *v1.Node\n\tdefer r.removeNodeFromProcessing(data.nodeName)\n\tcidrsString := ipnetToStringList(data.allocatedCIDRs)\n\tnode, err = r.nodeLister.Get(data.nodeName)\n\tif err != nil {\n\t\tlogger.Error(err, \"Failed while getting node for updating Node.Spec.PodCIDRs\", \"node\", klog.KRef(\"\", data.nodeName))\n\t\treturn err\n\t}\n\n\t// if cidr list matches the proposed.\n\t// then we possibly updated this node\n\t// and just failed to ack the success.\n\tif len(node.Spec.PodCIDRs) == len(data.allocatedCIDRs) {\n\t\tmatch := true\n\t\tfor idx, cidr := range cidrsString {\n\t\t\tif node.Spec.PodCIDRs[idx] != cidr {\n\t\t\t\tmatch = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif match {\n\t\t\tlogger.V(4).Info(\"Node already has allocated CIDR. It matches the proposed one\", \"node\", klog.KObj(node), \"CIDRs\", data.allocatedCIDRs)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t// node has cidrs, release the reserved\n\tif len(node.Spec.PodCIDRs) != 0 {\n\t\tlogger.Error(nil, \"Node already has a CIDR allocated. Releasing the new one\", \"node\", klog.KObj(node), \"podCIDRs\", node.Spec.PodCIDRs)\n\t\tfor idx, cidr := range data.allocatedCIDRs {\n\t\t\tif releaseErr := r.cidrSets[idx].Release(cidr); releaseErr != nil {\n\t\t\t\tlogger.Error(releaseErr, \"Error when releasing CIDR\", \"index\", idx, \"CIDR\", cidr)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\t// If we reached here, it means that the node has no CIDR currently assigned. So we set it.\n\tfor i := 0; i \u003c cidrUpdateRetries; i++ {\n\t\tif err = nodeutil.PatchNodeCIDRs(r.client, types.NodeName(node.Name), cidrsString); err == nil {\n\t\t\tlogger.Info(\"Set node PodCIDR\", \"node\", klog.KObj(node), \"podCIDRs\", cidrsString)\n\t\t\treturn nil\n\t\t}\n\t}\n\t// failed release back to the pool\n\tlogger.Error(err, \"Failed to update node PodCIDR after multiple attempts\", \"node\", klog.KObj(node), \"podCIDRs\", cidrsString)\n\tcontrollerutil.RecordNodeStatusChange(r.recorder, node, \"CIDRAssignmentFailed\")\n\t// We accept the fact that we may leak CIDRs here. This is safer than releasing\n\t// them in case when we don't know if request went through.\n\t// NodeController restart will return all falsely allocated CIDRs to the pool.\n\tif !apierrors.IsServerTimeout(err) {\n\t\tlogger.Error(err, \"CIDR assignment for node failed. Releasing allocated CIDR\", \"node\", klog.KObj(node))\n\t\tfor idx, cidr := range data.allocatedCIDRs {\n\t\t\tif releaseErr := r.cidrSets[idx].Release(cidr); releaseErr != nil {\n\t\t\t\tlogger.Error(releaseErr, \"Error releasing allocated CIDR for node\", \"node\", klog.KObj(node))\n\t\t\t}\n\t\t}\n\t}\n\treturn err\n}","line":{"from":337,"to":399}} {"id":100004248,"name":"IsValidMode","signature":"func IsValidMode(m NodeSyncMode) bool","file":"pkg/controller/nodeipam/ipam/sync/sync.go","code":"// IsValidMode returns true if the given mode is valid.\nfunc IsValidMode(m NodeSyncMode) bool {\n\tswitch m {\n\tcase SyncFromCloud:\n\tcase SyncFromCluster:\n\tdefault:\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":86,"to":95}} {"id":100004249,"name":"New","signature":"func New(c controller, cloudAlias cloudAlias, kubeAPI kubeAPI, mode NodeSyncMode, nodeName string, set *cidrset.CidrSet) *NodeSync","file":"pkg/controller/nodeipam/ipam/sync/sync.go","code":"// New returns a new syncer for a given node.\nfunc New(c controller, cloudAlias cloudAlias, kubeAPI kubeAPI, mode NodeSyncMode, nodeName string, set *cidrset.CidrSet) *NodeSync {\n\treturn \u0026NodeSync{\n\t\tc: c,\n\t\tcloudAlias: cloudAlias,\n\t\tkubeAPI: kubeAPI,\n\t\tmode: mode,\n\t\tnodeName: nodeName,\n\t\topChan: make(chan syncOp, 1),\n\t\tset: set,\n\t}\n}","line":{"from":108,"to":119}} {"id":100004250,"name":"Loop","signature":"func (sync *NodeSync) Loop(logger klog.Logger, done chan struct{})","file":"pkg/controller/nodeipam/ipam/sync/sync.go","code":"// Loop runs the sync loop for a given node. done is an optional channel that\n// is closed when the Loop() returns.\nfunc (sync *NodeSync) Loop(logger klog.Logger, done chan struct{}) {\n\tlogger.V(2).Info(\"Starting sync loop\", \"node\", klog.KRef(\"\", sync.nodeName))\n\n\tdefer func() {\n\t\tif done != nil {\n\t\t\tclose(done)\n\t\t}\n\t}()\n\n\ttimeout := sync.c.ResyncTimeout()\n\tdelayTimer := time.NewTimer(timeout)\n\tlogger.V(4).Info(\"Try to resync node later\", \"node\", klog.KRef(\"\", sync.nodeName), \"resyncTime\", timeout)\n\n\tfor {\n\t\tselect {\n\t\tcase op, more := \u003c-sync.opChan:\n\t\t\tif !more {\n\t\t\t\tlogger.V(2).Info(\"Stopping sync loop\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tsync.c.ReportResult(op.run(logger, sync))\n\t\t\tif !delayTimer.Stop() {\n\t\t\t\t\u003c-delayTimer.C\n\t\t\t}\n\t\tcase \u003c-delayTimer.C:\n\t\t\tlogger.V(4).Info(\"Running resync\", \"node\", klog.KRef(\"\", sync.nodeName))\n\t\t\tsync.c.ReportResult((\u0026updateOp{}).run(logger, sync))\n\t\t}\n\n\t\ttimeout := sync.c.ResyncTimeout()\n\t\tdelayTimer.Reset(timeout)\n\t\tlogger.V(4).Info(\"Try to resync node later\", \"node\", klog.KRef(\"\", sync.nodeName), \"resyncTime\", timeout)\n\t}\n}","line":{"from":121,"to":156}} {"id":100004251,"name":"Update","signature":"func (sync *NodeSync) Update(node *v1.Node)","file":"pkg/controller/nodeipam/ipam/sync/sync.go","code":"// Update causes an update operation on the given node. If node is nil, then\n// the syncer will fetch the node spec from the API server before syncing.\n//\n// This method is safe to call from multiple goroutines.\nfunc (sync *NodeSync) Update(node *v1.Node) {\n\tsync.opChan \u003c- \u0026updateOp{node}\n}","line":{"from":158,"to":164}} {"id":100004252,"name":"Delete","signature":"func (sync *NodeSync) Delete(node *v1.Node)","file":"pkg/controller/nodeipam/ipam/sync/sync.go","code":"// Delete performs the sync operations necessary to remove the node from the\n// IPAM state.\n//\n// This method is safe to call from multiple goroutines.\nfunc (sync *NodeSync) Delete(node *v1.Node) {\n\tsync.opChan \u003c- \u0026deleteOp{node}\n\tclose(sync.opChan)\n}","line":{"from":166,"to":173}} {"id":100004253,"name":"String","signature":"func (op *updateOp) String() string","file":"pkg/controller/nodeipam/ipam/sync/sync.go","code":"func (op *updateOp) String() string {\n\tif op.node == nil {\n\t\treturn fmt.Sprintf(\"updateOp(nil)\")\n\t}\n\treturn fmt.Sprintf(\"updateOp(%q,%v)\", op.node.Name, op.node.Spec.PodCIDR)\n}","line":{"from":186,"to":191}} {"id":100004254,"name":"run","signature":"func (op *updateOp) run(logger klog.Logger, sync *NodeSync) error","file":"pkg/controller/nodeipam/ipam/sync/sync.go","code":"func (op *updateOp) run(logger klog.Logger, sync *NodeSync) error {\n\tlogger.V(3).Info(\"Running updateOp\", \"updateOp\", op)\n\n\tctx := context.Background()\n\n\tif op.node == nil {\n\t\tlogger.V(3).Info(\"Getting node spec\", \"node\", klog.KRef(\"\", sync.nodeName))\n\t\tnode, err := sync.kubeAPI.Node(ctx, sync.nodeName)\n\t\tif err != nil {\n\t\t\tlogger.Error(err, \"Error getting node pec\", \"node\", klog.KRef(\"\", sync.nodeName))\n\t\t\treturn err\n\t\t}\n\t\top.node = node\n\t}\n\n\taliasRange, err := sync.cloudAlias.Alias(ctx, op.node)\n\tif err != nil {\n\t\tlogger.Error(err, \"Error getting cloud alias for node\", \"node\", klog.KRef(\"\", sync.nodeName))\n\t\treturn err\n\t}\n\n\tswitch {\n\tcase op.node.Spec.PodCIDR == \"\" \u0026\u0026 aliasRange == nil:\n\t\terr = op.allocateRange(ctx, sync, op.node)\n\tcase op.node.Spec.PodCIDR == \"\" \u0026\u0026 aliasRange != nil:\n\t\terr = op.updateNodeFromAlias(ctx, sync, op.node, aliasRange)\n\tcase op.node.Spec.PodCIDR != \"\" \u0026\u0026 aliasRange == nil:\n\t\terr = op.updateAliasFromNode(ctx, sync, op.node)\n\tcase op.node.Spec.PodCIDR != \"\" \u0026\u0026 aliasRange != nil:\n\t\terr = op.validateRange(ctx, sync, op.node, aliasRange)\n\t}\n\n\treturn err\n}","line":{"from":193,"to":226}} {"id":100004255,"name":"validateRange","signature":"func (op *updateOp) validateRange(ctx context.Context, sync *NodeSync, node *v1.Node, aliasRange *net.IPNet) error","file":"pkg/controller/nodeipam/ipam/sync/sync.go","code":"// validateRange checks that the allocated range and the alias range\n// match.\nfunc (op *updateOp) validateRange(ctx context.Context, sync *NodeSync, node *v1.Node, aliasRange *net.IPNet) error {\n\tif node.Spec.PodCIDR != aliasRange.String() {\n\t\tklog.FromContext(ctx).Error(nil, \"Inconsistency detected between node PodCIDR and node alias\", \"podCIDR\", node.Spec.PodCIDR, \"alias\", aliasRange)\n\t\tsync.kubeAPI.EmitNodeWarningEvent(node.Name, MismatchEvent,\n\t\t\t\"Node.Spec.PodCIDR != cloud alias (%v != %v)\", node.Spec.PodCIDR, aliasRange)\n\t\t// User intervention is required in this case, as this is most likely due\n\t\t// to the user mucking around with their VM aliases on the side.\n\t} else {\n\t\tklog.FromContext(ctx).V(4).Info(\"Node CIDR range is matches cloud assignment\", \"node\", klog.KObj(node), \"podCIDR\", node.Spec.PodCIDR)\n\t}\n\treturn nil\n}","line":{"from":228,"to":241}} {"id":100004256,"name":"updateNodeFromAlias","signature":"func (op *updateOp) updateNodeFromAlias(ctx context.Context, sync *NodeSync, node *v1.Node, aliasRange *net.IPNet) error","file":"pkg/controller/nodeipam/ipam/sync/sync.go","code":"// updateNodeFromAlias updates the node from the cloud allocated\n// alias.\nfunc (op *updateOp) updateNodeFromAlias(ctx context.Context, sync *NodeSync, node *v1.Node, aliasRange *net.IPNet) error {\n\tif sync.mode != SyncFromCloud {\n\t\tsync.kubeAPI.EmitNodeWarningEvent(node.Name, InvalidModeEvent,\n\t\t\t\"Cannot sync from cloud in mode %q\", sync.mode)\n\t\treturn fmt.Errorf(\"cannot sync from cloud in mode %q\", sync.mode)\n\t}\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(2).Info(\"Updating node spec with alias range\", \"podCIDR\", aliasRange)\n\n\tif err := sync.set.Occupy(aliasRange); err != nil {\n\t\tlogger.Error(nil, \"Error occupying range for node\", \"node\", klog.KRef(\"\", sync.nodeName), \"alias\", aliasRange)\n\t\treturn err\n\t}\n\n\tif err := sync.kubeAPI.UpdateNodePodCIDR(ctx, node, aliasRange); err != nil {\n\t\tlogger.Error(err, \"Could not update node PodCIDR\", \"node\", klog.KObj(node), \"podCIDR\", aliasRange)\n\t\treturn err\n\t}\n\n\tlogger.V(2).Info(\"Node PodCIDR updated\", \"node\", klog.KObj(node), \"podCIDR\", aliasRange)\n\n\tif err := sync.kubeAPI.UpdateNodeNetworkUnavailable(node.Name, false); err != nil {\n\t\tlogger.Error(err, \"Could not update node NetworkUnavailable status to false\")\n\t\treturn err\n\t}\n\n\tlogger.V(2).Info(\"Updated node PodCIDR from cloud alias\", \"node\", klog.KObj(node), \"alias\", aliasRange)\n\n\treturn nil\n}","line":{"from":243,"to":274}} {"id":100004257,"name":"updateAliasFromNode","signature":"func (op *updateOp) updateAliasFromNode(ctx context.Context, sync *NodeSync, node *v1.Node) error","file":"pkg/controller/nodeipam/ipam/sync/sync.go","code":"// updateAliasFromNode updates the cloud alias given the node allocation.\nfunc (op *updateOp) updateAliasFromNode(ctx context.Context, sync *NodeSync, node *v1.Node) error {\n\tif sync.mode != SyncFromCluster {\n\t\tsync.kubeAPI.EmitNodeWarningEvent(\n\t\t\tnode.Name, InvalidModeEvent, \"Cannot sync to cloud in mode %q\", sync.mode)\n\t\treturn fmt.Errorf(\"cannot sync to cloud in mode %q\", sync.mode)\n\t}\n\n\t_, aliasRange, err := netutils.ParseCIDRSloppy(node.Spec.PodCIDR)\n\n\tlogger := klog.FromContext(ctx)\n\tif err != nil {\n\t\tlogger.Error(err, \"Could not parse PodCIDR for node\", \"node\", klog.KObj(node), \"podCIDR\", node.Spec.PodCIDR)\n\t\treturn err\n\t}\n\n\tif err := sync.set.Occupy(aliasRange); err != nil {\n\t\tlogger.Error(nil, \"Error occupying range for node\", \"node\", klog.KRef(\"\", sync.nodeName), \"alias\", aliasRange)\n\t\treturn err\n\t}\n\n\tif err := sync.cloudAlias.AddAlias(ctx, node, aliasRange); err != nil {\n\t\tlogger.Error(err, \"Could not add alias for node\", \"node\", klog.KObj(node), \"alias\", aliasRange)\n\t\treturn err\n\t}\n\n\tif err := sync.kubeAPI.UpdateNodeNetworkUnavailable(node.Name, false); err != nil {\n\t\tlogger.Error(err, \"Could not update node NetworkUnavailable status to false\")\n\t\treturn err\n\t}\n\n\tlogger.V(2).Info(\"Updated node cloud alias with node spec\", \"node\", klog.KObj(node), \"podCIDR\", node.Spec.PodCIDR)\n\n\treturn nil\n}","line":{"from":276,"to":310}} {"id":100004258,"name":"allocateRange","signature":"func (op *updateOp) allocateRange(ctx context.Context, sync *NodeSync, node *v1.Node) error","file":"pkg/controller/nodeipam/ipam/sync/sync.go","code":"// allocateRange allocates a new range and updates both the cloud\n// platform and the node allocation.\nfunc (op *updateOp) allocateRange(ctx context.Context, sync *NodeSync, node *v1.Node) error {\n\tif sync.mode != SyncFromCluster {\n\t\tsync.kubeAPI.EmitNodeWarningEvent(node.Name, InvalidModeEvent,\n\t\t\t\"Cannot allocate CIDRs in mode %q\", sync.mode)\n\t\treturn fmt.Errorf(\"controller cannot allocate CIDRS in mode %q\", sync.mode)\n\t}\n\n\tcidrRange, err := sync.set.AllocateNext()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// If addAlias returns a hard error, cidrRange will be leaked as there\n\t// is no durable record of the range. The missing space will be\n\t// recovered on the next restart of the controller.\n\tlogger := klog.FromContext(ctx)\n\tif err := sync.cloudAlias.AddAlias(ctx, node, cidrRange); err != nil {\n\t\tlogger.Error(err, \"Could not add alias for node\", \"node\", klog.KObj(node), \"alias\", cidrRange)\n\t\treturn err\n\t}\n\n\tif err := sync.kubeAPI.UpdateNodePodCIDR(ctx, node, cidrRange); err != nil {\n\t\tlogger.Error(err, \"Could not update node PodCIDR\", \"node\", klog.KObj(node), \"podCIDR\", cidrRange)\n\t\treturn err\n\t}\n\n\tif err := sync.kubeAPI.UpdateNodeNetworkUnavailable(node.Name, false); err != nil {\n\t\tlogger.Error(err, \"Could not update node NetworkUnavailable status to false\")\n\t\treturn err\n\t}\n\n\tlogger.V(2).Info(\"Allocated PodCIDR for node\", \"node\", klog.KObj(node), \"podCIDR\", cidrRange)\n\n\treturn nil\n}","line":{"from":312,"to":347}} {"id":100004259,"name":"String","signature":"func (op *deleteOp) String() string","file":"pkg/controller/nodeipam/ipam/sync/sync.go","code":"func (op *deleteOp) String() string {\n\tif op.node == nil {\n\t\treturn fmt.Sprintf(\"deleteOp(nil)\")\n\t}\n\treturn fmt.Sprintf(\"deleteOp(%q,%v)\", op.node.Name, op.node.Spec.PodCIDR)\n}","line":{"from":354,"to":359}} {"id":100004260,"name":"run","signature":"func (op *deleteOp) run(logger klog.Logger, sync *NodeSync) error","file":"pkg/controller/nodeipam/ipam/sync/sync.go","code":"func (op *deleteOp) run(logger klog.Logger, sync *NodeSync) error {\n\tlogger.V(3).Info(\"Running deleteOp\", \"deleteOp\", op)\n\tif op.node.Spec.PodCIDR == \"\" {\n\t\tlogger.V(2).Info(\"Node was deleted, node had no PodCIDR range assigned\", \"node\", klog.KObj(op.node))\n\t\treturn nil\n\t}\n\n\t_, cidrRange, err := netutils.ParseCIDRSloppy(op.node.Spec.PodCIDR)\n\tif err != nil {\n\t\tlogger.Error(err, \"Deleted node has an invalid podCIDR\", \"node\", klog.KObj(op.node), \"podCIDR\", op.node.Spec.PodCIDR)\n\t\tsync.kubeAPI.EmitNodeWarningEvent(op.node.Name, InvalidPodCIDR,\n\t\t\t\"Node %q has an invalid PodCIDR: %q\", op.node.Name, op.node.Spec.PodCIDR)\n\t\treturn nil\n\t}\n\n\tsync.set.Release(cidrRange)\n\tlogger.V(2).Info(\"Node was deleted, releasing CIDR range\", \"node\", klog.KObj(op.node), \"podCIDR\", op.node.Spec.PodCIDR)\n\n\treturn nil\n}","line":{"from":361,"to":380}} {"id":100004261,"name":"Update","signature":"func (b *Timeout) Update(ok bool)","file":"pkg/controller/nodeipam/ipam/timeout.go","code":"// Update the timeout with the current error state.\nfunc (b *Timeout) Update(ok bool) {\n\tif ok {\n\t\tb.errs = 0\n\t\tb.current = b.Resync\n\t\treturn\n\t}\n\n\tb.errs++\n\tif b.errs == 1 {\n\t\tb.current = b.InitialRetry\n\t\treturn\n\t}\n\n\tb.current *= 2\n\tif b.current \u003e= b.MaxBackoff {\n\t\tb.current = b.MaxBackoff\n\t}\n}","line":{"from":41,"to":59}} {"id":100004262,"name":"Next","signature":"func (b *Timeout) Next() time.Duration","file":"pkg/controller/nodeipam/ipam/timeout.go","code":"// Next returns the next operation timeout given the disposition of err.\nfunc (b *Timeout) Next() time.Duration {\n\tif b.errs == 0 {\n\t\treturn b.Resync\n\t}\n\treturn b.current\n}","line":{"from":61,"to":67}} {"id":100004263,"name":"createLegacyIPAM","signature":"func createLegacyIPAM(","file":"pkg/controller/nodeipam/legacyprovider.go","code":"func createLegacyIPAM(\n\tlogger klog.Logger,\n\tic *Controller,\n\tnodeInformer coreinformers.NodeInformer,\n\tcloud cloudprovider.Interface,\n\tkubeClient clientset.Interface,\n\tclusterCIDRs []*net.IPNet,\n\tserviceCIDR *net.IPNet,\n\tnodeCIDRMaskSizes []int,\n) (*ipam.Controller, error) {\n\tcfg := \u0026ipam.Config{\n\t\tResync: ipamResyncInterval,\n\t\tMaxBackoff: ipamMaxBackoff,\n\t\tInitialRetry: ipamInitialBackoff,\n\t}\n\tswitch ic.allocatorType {\n\tcase ipam.IPAMFromClusterAllocatorType:\n\t\tcfg.Mode = nodesync.SyncFromCluster\n\tcase ipam.IPAMFromCloudAllocatorType:\n\t\tcfg.Mode = nodesync.SyncFromCloud\n\t}\n\n\t// we may end up here with no cidr at all in case of FromCloud/FromCluster\n\tvar cidr *net.IPNet\n\tif len(clusterCIDRs) \u003e 0 {\n\t\tcidr = clusterCIDRs[0]\n\t}\n\tif len(clusterCIDRs) \u003e 1 {\n\t\tlogger.Info(\"Multiple cidrs were configured with FromCluster or FromCloud. cidrs except first one were discarded\")\n\t}\n\tipamc, err := ipam.NewController(cfg, kubeClient, cloud, cidr, serviceCIDR, nodeCIDRMaskSizes[0])\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating ipam controller: %w\", err)\n\t}\n\tif err := ipamc.Start(logger, nodeInformer); err != nil {\n\t\treturn nil, fmt.Errorf(\"error trying to Init(): %w\", err)\n\t}\n\treturn ipamc, nil\n}","line":{"from":35,"to":73}} {"id":100004264,"name":"NewNodeIpamController","signature":"func NewNodeIpamController(","file":"pkg/controller/nodeipam/node_ipam_controller.go","code":"// NewNodeIpamController returns a new node IP Address Management controller to\n// sync instances from cloudprovider.\n// This method returns an error if it is unable to initialize the CIDR bitmap with\n// podCIDRs it has already allocated to nodes. Since we don't allow podCIDR changes\n// currently, this should be handled as a fatal error.\nfunc NewNodeIpamController(\n\tctx context.Context,\n\tnodeInformer coreinformers.NodeInformer,\n\tclusterCIDRInformer networkinginformers.ClusterCIDRInformer,\n\tcloud cloudprovider.Interface,\n\tkubeClient clientset.Interface,\n\tclusterCIDRs []*net.IPNet,\n\tserviceCIDR *net.IPNet,\n\tsecondaryServiceCIDR *net.IPNet,\n\tnodeCIDRMaskSizes []int,\n\tallocatorType ipam.CIDRAllocatorType) (*Controller, error) {\n\n\tlogger := klog.FromContext(ctx)\n\tif kubeClient == nil {\n\t\treturn nil, fmt.Errorf(\"kubeClient is nil when starting Controller\")\n\t}\n\n\t// Cloud CIDR allocator does not rely on clusterCIDR or nodeCIDRMaskSize for allocation.\n\tif allocatorType != ipam.CloudAllocatorType {\n\t\tif len(clusterCIDRs) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"Controller: Must specify --cluster-cidr if --allocate-node-cidrs is set\")\n\t\t}\n\n\t\tfor idx, cidr := range clusterCIDRs {\n\t\t\tmask := cidr.Mask\n\t\t\tif maskSize, _ := mask.Size(); maskSize \u003e nodeCIDRMaskSizes[idx] {\n\t\t\t\treturn nil, fmt.Errorf(\"Controller: Invalid --cluster-cidr, mask size of cluster CIDR must be less than or equal to --node-cidr-mask-size configured for CIDR family\")\n\t\t\t}\n\t\t}\n\t}\n\n\tic := \u0026Controller{\n\t\tcloud: cloud,\n\t\tkubeClient: kubeClient,\n\t\teventBroadcaster: record.NewBroadcaster(),\n\t\tlookupIP: net.LookupIP,\n\t\tclusterCIDRs: clusterCIDRs,\n\t\tserviceCIDR: serviceCIDR,\n\t\tsecondaryServiceCIDR: secondaryServiceCIDR,\n\t\tallocatorType: allocatorType,\n\t}\n\n\t// TODO: Abstract this check into a generic controller manager should run method.\n\tif ic.allocatorType == ipam.IPAMFromClusterAllocatorType || ic.allocatorType == ipam.IPAMFromCloudAllocatorType {\n\t\tvar err error\n\t\tic.legacyIPAM, err = createLegacyIPAM(logger, ic, nodeInformer, cloud, kubeClient, clusterCIDRs, serviceCIDR, nodeCIDRMaskSizes)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tvar err error\n\n\t\tallocatorParams := ipam.CIDRAllocatorParams{\n\t\t\tClusterCIDRs: clusterCIDRs,\n\t\t\tServiceCIDR: ic.serviceCIDR,\n\t\t\tSecondaryServiceCIDR: ic.secondaryServiceCIDR,\n\t\t\tNodeCIDRMaskSizes: nodeCIDRMaskSizes,\n\t\t}\n\n\t\tic.cidrAllocator, err = ipam.New(ctx, kubeClient, cloud, nodeInformer, clusterCIDRInformer, ic.allocatorType, allocatorParams)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tic.nodeLister = nodeInformer.Lister()\n\tic.nodeInformerSynced = nodeInformer.Informer().HasSynced\n\n\treturn ic, nil\n}","line":{"from":78,"to":152}} {"id":100004265,"name":"Run","signature":"func (nc *Controller) Run(ctx context.Context)","file":"pkg/controller/nodeipam/node_ipam_controller.go","code":"// Run starts an asynchronous loop that monitors the status of cluster nodes.\nfunc (nc *Controller) Run(ctx context.Context) {\n\tdefer utilruntime.HandleCrash()\n\n\t// Start event processing pipeline.\n\tnc.eventBroadcaster.StartStructuredLogging(0)\n\tnc.eventBroadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: nc.kubeClient.CoreV1().Events(\"\")})\n\tdefer nc.eventBroadcaster.Shutdown()\n\tklog.FromContext(ctx).Info(\"Starting ipam controller\")\n\tdefer klog.FromContext(ctx).Info(\"Shutting down ipam controller\")\n\n\tif !cache.WaitForNamedCacheSync(\"node\", ctx.Done(), nc.nodeInformerSynced) {\n\t\treturn\n\t}\n\n\tif nc.allocatorType == ipam.IPAMFromClusterAllocatorType || nc.allocatorType == ipam.IPAMFromCloudAllocatorType {\n\t\tgo nc.legacyIPAM.Run(ctx)\n\t} else {\n\t\tgo nc.cidrAllocator.Run(ctx)\n\t}\n\n\t\u003c-ctx.Done()\n}","line":{"from":154,"to":176}} {"id":100004266,"name":"RunWithMetrics","signature":"func (nc *Controller) RunWithMetrics(ctx context.Context, controllerManagerMetrics *controllersmetrics.ControllerManagerMetrics)","file":"pkg/controller/nodeipam/node_ipam_controller.go","code":"// RunWithMetrics is a wrapper for Run that also tracks starting and stopping of the nodeipam controller with additional metric\nfunc (nc *Controller) RunWithMetrics(ctx context.Context, controllerManagerMetrics *controllersmetrics.ControllerManagerMetrics) {\n\tcontrollerManagerMetrics.ControllerStarted(\"nodeipam\")\n\tdefer controllerManagerMetrics.ControllerStopped(\"nodeipam\")\n\tnc.Run(ctx)\n}","line":{"from":178,"to":183}} {"id":100004267,"name":"Run","signature":"func (f *fakeController) Run(ctx context.Context)","file":"pkg/controller/nodeipam/nolegacyprovider.go","code":"func (f *fakeController) Run(ctx context.Context) {\n\t\u003c-ctx.Done()\n}","line":{"from":36,"to":38}} {"id":100004268,"name":"createLegacyIPAM","signature":"func createLegacyIPAM(","file":"pkg/controller/nodeipam/nolegacyprovider.go","code":"func createLegacyIPAM(\n\tlogger klog.Logger,\n\tic *Controller,\n\tnodeInformer coreinformers.NodeInformer,\n\tcloud cloudprovider.Interface,\n\tkubeClient clientset.Interface,\n\tclusterCIDRs []*net.IPNet,\n\tserviceCIDR *net.IPNet,\n\tnodeCIDRMaskSizes []int,\n) (*fakeController, error) {\n\treturn nil, errors.New(\"Error trying to Init(): legacy cloud provider support disabled at build time\")\n}","line":{"from":40,"to":51}} {"id":100004269,"name":"Convert_v1alpha1_NodeLifecycleControllerConfiguration_To_config_NodeLifecycleControllerConfiguration","signature":"func Convert_v1alpha1_NodeLifecycleControllerConfiguration_To_config_NodeLifecycleControllerConfiguration(in *v1alpha1.NodeLifecycleControllerConfiguration, out *config.NodeLifecycleControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/nodelifecycle/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_NodeLifecycleControllerConfiguration_To_config_NodeLifecycleControllerConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_NodeLifecycleControllerConfiguration_To_config_NodeLifecycleControllerConfiguration(in *v1alpha1.NodeLifecycleControllerConfiguration, out *config.NodeLifecycleControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_NodeLifecycleControllerConfiguration_To_config_NodeLifecycleControllerConfiguration(in, out, s)\n}","line":{"from":32,"to":35}} {"id":100004270,"name":"Convert_config_NodeLifecycleControllerConfiguration_To_v1alpha1_NodeLifecycleControllerConfiguration","signature":"func Convert_config_NodeLifecycleControllerConfiguration_To_v1alpha1_NodeLifecycleControllerConfiguration(in *config.NodeLifecycleControllerConfiguration, out *v1alpha1.NodeLifecycleControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/nodelifecycle/config/v1alpha1/conversion.go","code":"// Convert_config_NodeLifecycleControllerConfiguration_To_v1alpha1_NodeLifecycleControllerConfiguration is an autogenerated conversion function.\nfunc Convert_config_NodeLifecycleControllerConfiguration_To_v1alpha1_NodeLifecycleControllerConfiguration(in *config.NodeLifecycleControllerConfiguration, out *v1alpha1.NodeLifecycleControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_NodeLifecycleControllerConfiguration_To_v1alpha1_NodeLifecycleControllerConfiguration(in, out, s)\n}","line":{"from":37,"to":40}} {"id":100004271,"name":"RecommendedDefaultNodeLifecycleControllerConfiguration","signature":"func RecommendedDefaultNodeLifecycleControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.NodeLifecycleControllerConfiguration)","file":"pkg/controller/nodelifecycle/config/v1alpha1/defaults.go","code":"// RecommendedDefaultNodeLifecycleControllerConfiguration defaults a pointer to a\n// NodeLifecycleControllerConfiguration struct. This will set the recommended default\n// values, but they may be subject to change between API versions. This function\n// is intentionally not registered in the scheme as a \"normal\" `SetDefaults_Foo`\n// function to allow consumers of this type to set whatever defaults for their\n// embedded configs. Forcing consumers to use these defaults would be problematic\n// as defaulting in the scheme is done as part of the conversion, and there would\n// be no easy way to opt-out. Instead, if you want to use this defaulting method\n// run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDefaultNodeLifecycleControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.NodeLifecycleControllerConfiguration) {\n\tzero := metav1.Duration{}\n\tif obj.PodEvictionTimeout == zero {\n\t\tobj.PodEvictionTimeout = metav1.Duration{Duration: 5 * time.Minute}\n\t}\n\tif obj.NodeMonitorGracePeriod == zero {\n\t\tobj.NodeMonitorGracePeriod = metav1.Duration{Duration: 40 * time.Second}\n\t}\n\tif obj.NodeStartupGracePeriod == zero {\n\t\tobj.NodeStartupGracePeriod = metav1.Duration{Duration: 60 * time.Second}\n\t}\n}","line":{"from":26,"to":46}} {"id":100004272,"name":"Register","signature":"func Register()","file":"pkg/controller/nodelifecycle/metrics.go","code":"// Register the metrics that are to be monitored.\nfunc Register() {\n\tregisterMetrics.Do(func() {\n\t\tlegacyregistry.MustRegister(zoneHealth)\n\t\tlegacyregistry.MustRegister(zoneSize)\n\t\tlegacyregistry.MustRegister(unhealthyNodes)\n\t\tlegacyregistry.MustRegister(evictionsTotal)\n\t\tlegacyregistry.MustRegister(updateNodeHealthDuration)\n\t\tlegacyregistry.MustRegister(updateAllNodesHealthDuration)\n\t})\n}","line":{"from":97,"to":107}} {"id":100004273,"name":"init","signature":"func init()","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"func init() {\n\t// Register prometheus metrics\n\tRegister()\n}","line":{"from":61,"to":64}} {"id":100004274,"name":"deepCopy","signature":"func (n *nodeHealthData) deepCopy() *nodeHealthData","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"func (n *nodeHealthData) deepCopy() *nodeHealthData {\n\tif n == nil {\n\t\treturn nil\n\t}\n\treturn \u0026nodeHealthData{\n\t\tprobeTimestamp: n.probeTimestamp,\n\t\treadyTransitionTimestamp: n.readyTransitionTimestamp,\n\t\tstatus: n.status.DeepCopy(),\n\t\tlease: n.lease.DeepCopy(),\n\t}\n}","line":{"from":166,"to":176}} {"id":100004275,"name":"newNodeHealthMap","signature":"func newNodeHealthMap() *nodeHealthMap","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"func newNodeHealthMap() *nodeHealthMap {\n\treturn \u0026nodeHealthMap{\n\t\tnodeHealths: make(map[string]*nodeHealthData),\n\t}\n}","line":{"from":183,"to":187}} {"id":100004276,"name":"getDeepCopy","signature":"func (n *nodeHealthMap) getDeepCopy(name string) *nodeHealthData","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"// getDeepCopy - returns copy of node health data.\n// It prevents data being changed after retrieving it from the map.\nfunc (n *nodeHealthMap) getDeepCopy(name string) *nodeHealthData {\n\tn.lock.RLock()\n\tdefer n.lock.RUnlock()\n\treturn n.nodeHealths[name].deepCopy()\n}","line":{"from":189,"to":195}} {"id":100004277,"name":"set","signature":"func (n *nodeHealthMap) set(name string, data *nodeHealthData)","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"func (n *nodeHealthMap) set(name string, data *nodeHealthData) {\n\tn.lock.Lock()\n\tdefer n.lock.Unlock()\n\tn.nodeHealths[name] = data\n}","line":{"from":197,"to":201}} {"id":100004278,"name":"NewNodeLifecycleController","signature":"func NewNodeLifecycleController(","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"// NewNodeLifecycleController returns a new taint controller.\nfunc NewNodeLifecycleController(\n\tctx context.Context,\n\tleaseInformer coordinformers.LeaseInformer,\n\tpodInformer coreinformers.PodInformer,\n\tnodeInformer coreinformers.NodeInformer,\n\tdaemonSetInformer appsv1informers.DaemonSetInformer,\n\tkubeClient clientset.Interface,\n\tnodeMonitorPeriod time.Duration,\n\tnodeStartupGracePeriod time.Duration,\n\tnodeMonitorGracePeriod time.Duration,\n\tevictionLimiterQPS float32,\n\tsecondaryEvictionLimiterQPS float32,\n\tlargeClusterThreshold int32,\n\tunhealthyZoneThreshold float32,\n) (*Controller, error) {\n\tlogger := klog.FromContext(ctx)\n\tif kubeClient == nil {\n\t\tlogger.Error(nil, \"kubeClient is nil when starting nodelifecycle Controller\")\n\t\tklog.FlushAndExit(klog.ExitFlushTimeout, 1)\n\t}\n\n\teventBroadcaster := record.NewBroadcaster()\n\trecorder := eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"node-controller\"})\n\n\tnc := \u0026Controller{\n\t\tkubeClient: kubeClient,\n\t\tnow: metav1.Now,\n\t\tknownNodeSet: make(map[string]*v1.Node),\n\t\tnodeHealthMap: newNodeHealthMap(),\n\t\tbroadcaster: eventBroadcaster,\n\t\trecorder: recorder,\n\t\tnodeMonitorPeriod: nodeMonitorPeriod,\n\t\tnodeStartupGracePeriod: nodeStartupGracePeriod,\n\t\tnodeMonitorGracePeriod: nodeMonitorGracePeriod,\n\t\tnodeUpdateWorkerSize: scheduler.UpdateWorkerSize,\n\t\tzoneNoExecuteTainter: make(map[string]*scheduler.RateLimitedTimedQueue),\n\t\tnodesToRetry: sync.Map{},\n\t\tzoneStates: make(map[string]ZoneState),\n\t\tevictionLimiterQPS: evictionLimiterQPS,\n\t\tsecondaryEvictionLimiterQPS: secondaryEvictionLimiterQPS,\n\t\tlargeClusterThreshold: largeClusterThreshold,\n\t\tunhealthyZoneThreshold: unhealthyZoneThreshold,\n\t\tnodeUpdateQueue: workqueue.NewNamed(\"node_lifecycle_controller\"),\n\t\tpodUpdateQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"node_lifecycle_controller_pods\"),\n\t}\n\n\tnc.enterPartialDisruptionFunc = nc.ReducedQPSFunc\n\tnc.enterFullDisruptionFunc = nc.HealthyQPSFunc\n\tnc.computeZoneStateFunc = nc.ComputeZoneState\n\n\tpodInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tpod := obj.(*v1.Pod)\n\t\t\tnc.podUpdated(nil, pod)\n\t\t\tif nc.taintManager != nil {\n\t\t\t\tnc.taintManager.PodUpdated(nil, pod)\n\t\t\t}\n\t\t},\n\t\tUpdateFunc: func(prev, obj interface{}) {\n\t\t\tprevPod := prev.(*v1.Pod)\n\t\t\tnewPod := obj.(*v1.Pod)\n\t\t\tnc.podUpdated(prevPod, newPod)\n\t\t\tif nc.taintManager != nil {\n\t\t\t\tnc.taintManager.PodUpdated(prevPod, newPod)\n\t\t\t}\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tpod, isPod := obj.(*v1.Pod)\n\t\t\t// We can get DeletedFinalStateUnknown instead of *v1.Pod here and we need to handle that correctly.\n\t\t\tif !isPod {\n\t\t\t\tdeletedState, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\t\t\tif !ok {\n\t\t\t\t\tlogger.Error(nil, \"Received unexpected object\", \"object\", obj)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tpod, ok = deletedState.Obj.(*v1.Pod)\n\t\t\t\tif !ok {\n\t\t\t\t\tlogger.Error(nil, \"DeletedFinalStateUnknown contained non-Pod object\", \"object\", deletedState.Obj)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tnc.podUpdated(pod, nil)\n\t\t\tif nc.taintManager != nil {\n\t\t\t\tnc.taintManager.PodUpdated(pod, nil)\n\t\t\t}\n\t\t},\n\t})\n\tnc.podInformerSynced = podInformer.Informer().HasSynced\n\tpodInformer.Informer().AddIndexers(cache.Indexers{\n\t\tnodeNameKeyIndex: func(obj interface{}) ([]string, error) {\n\t\t\tpod, ok := obj.(*v1.Pod)\n\t\t\tif !ok {\n\t\t\t\treturn []string{}, nil\n\t\t\t}\n\t\t\tif len(pod.Spec.NodeName) == 0 {\n\t\t\t\treturn []string{}, nil\n\t\t\t}\n\t\t\treturn []string{pod.Spec.NodeName}, nil\n\t\t},\n\t})\n\n\tpodIndexer := podInformer.Informer().GetIndexer()\n\tnc.getPodsAssignedToNode = func(nodeName string) ([]*v1.Pod, error) {\n\t\tobjs, err := podIndexer.ByIndex(nodeNameKeyIndex, nodeName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpods := make([]*v1.Pod, 0, len(objs))\n\t\tfor _, obj := range objs {\n\t\t\tpod, ok := obj.(*v1.Pod)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpods = append(pods, pod)\n\t\t}\n\t\treturn pods, nil\n\t}\n\tnc.podLister = podInformer.Lister()\n\tnc.nodeLister = nodeInformer.Lister()\n\n\tnc.taintManager = scheduler.NewNoExecuteTaintManager(ctx, kubeClient, nc.podLister, nc.nodeLister, nc.getPodsAssignedToNode)\n\tnodeInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: controllerutil.CreateAddNodeHandler(func(node *v1.Node) error {\n\t\t\tnc.taintManager.NodeUpdated(nil, node)\n\t\t\treturn nil\n\t\t}),\n\t\tUpdateFunc: controllerutil.CreateUpdateNodeHandler(func(oldNode, newNode *v1.Node) error {\n\t\t\tnc.taintManager.NodeUpdated(oldNode, newNode)\n\t\t\treturn nil\n\t\t}),\n\t\tDeleteFunc: controllerutil.CreateDeleteNodeHandler(func(node *v1.Node) error {\n\t\t\tnc.taintManager.NodeUpdated(node, nil)\n\t\t\treturn nil\n\t\t}),\n\t})\n\n\tlogger.Info(\"Controller will reconcile labels\")\n\tnodeInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: controllerutil.CreateAddNodeHandler(func(node *v1.Node) error {\n\t\t\tnc.nodeUpdateQueue.Add(node.Name)\n\t\t\treturn nil\n\t\t}),\n\t\tUpdateFunc: controllerutil.CreateUpdateNodeHandler(func(_, newNode *v1.Node) error {\n\t\t\tnc.nodeUpdateQueue.Add(newNode.Name)\n\t\t\treturn nil\n\t\t}),\n\t\tDeleteFunc: controllerutil.CreateDeleteNodeHandler(func(node *v1.Node) error {\n\t\t\tnc.nodesToRetry.Delete(node.Name)\n\t\t\treturn nil\n\t\t}),\n\t})\n\n\tnc.leaseLister = leaseInformer.Lister()\n\tnc.leaseInformerSynced = leaseInformer.Informer().HasSynced\n\n\tnc.nodeInformerSynced = nodeInformer.Informer().HasSynced\n\n\tnc.daemonSetStore = daemonSetInformer.Lister()\n\tnc.daemonSetInformerSynced = daemonSetInformer.Informer().HasSynced\n\n\treturn nc, nil\n}","line":{"from":294,"to":456}} {"id":100004279,"name":"Run","signature":"func (nc *Controller) Run(ctx context.Context)","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"// Run starts an asynchronous loop that monitors the status of cluster nodes.\nfunc (nc *Controller) Run(ctx context.Context) {\n\tdefer utilruntime.HandleCrash()\n\n\t// Start events processing pipeline.\n\tnc.broadcaster.StartStructuredLogging(0)\n\tlogger := klog.FromContext(ctx)\n\tlogger.Info(\"Sending events to api server\")\n\tnc.broadcaster.StartRecordingToSink(\n\t\t\u0026v1core.EventSinkImpl{\n\t\t\tInterface: v1core.New(nc.kubeClient.CoreV1().RESTClient()).Events(\"\"),\n\t\t})\n\tdefer nc.broadcaster.Shutdown()\n\n\t// Close node update queue to cleanup go routine.\n\tdefer nc.nodeUpdateQueue.ShutDown()\n\tdefer nc.podUpdateQueue.ShutDown()\n\n\tlogger.Info(\"Starting node controller\")\n\tdefer logger.Info(\"Shutting down node controller\")\n\n\tif !cache.WaitForNamedCacheSync(\"taint\", ctx.Done(), nc.leaseInformerSynced, nc.nodeInformerSynced, nc.podInformerSynced, nc.daemonSetInformerSynced) {\n\t\treturn\n\t}\n\n\tgo nc.taintManager.Run(ctx)\n\n\t// Start workers to reconcile labels and/or update NoSchedule taint for nodes.\n\tfor i := 0; i \u003c scheduler.UpdateWorkerSize; i++ {\n\t\t// Thanks to \"workqueue\", each worker just need to get item from queue, because\n\t\t// the item is flagged when got from queue: if new event come, the new item will\n\t\t// be re-queued until \"Done\", so no more than one worker handle the same item and\n\t\t// no event missed.\n\t\tgo wait.UntilWithContext(ctx, nc.doNodeProcessingPassWorker, time.Second)\n\t}\n\n\tfor i := 0; i \u003c podUpdateWorkerSize; i++ {\n\t\tgo wait.UntilWithContext(ctx, nc.doPodProcessingWorker, time.Second)\n\t}\n\n\t// Handling taint based evictions. Because we don't want a dedicated logic in TaintManager for NC-originated\n\t// taints and we normally don't rate limit evictions caused by taints, we need to rate limit adding taints.\n\tgo wait.UntilWithContext(ctx, nc.doNoExecuteTaintingPass, scheduler.NodeEvictionPeriod)\n\n\t// Incorporate the results of node health signal pushed from kubelet to master.\n\tgo wait.UntilWithContext(ctx, func(ctx context.Context) {\n\t\tif err := nc.monitorNodeHealth(ctx); err != nil {\n\t\t\tlogger.Error(err, \"Error monitoring node health\")\n\t\t}\n\t}, nc.nodeMonitorPeriod)\n\n\t\u003c-ctx.Done()\n}","line":{"from":458,"to":510}} {"id":100004280,"name":"doNodeProcessingPassWorker","signature":"func (nc *Controller) doNodeProcessingPassWorker(ctx context.Context)","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"func (nc *Controller) doNodeProcessingPassWorker(ctx context.Context) {\n\tlogger := klog.FromContext(ctx)\n\tfor {\n\t\tobj, shutdown := nc.nodeUpdateQueue.Get()\n\t\t// \"nodeUpdateQueue\" will be shutdown when \"stopCh\" closed;\n\t\t// we do not need to re-check \"stopCh\" again.\n\t\tif shutdown {\n\t\t\treturn\n\t\t}\n\t\tnodeName := obj.(string)\n\t\tif err := nc.doNoScheduleTaintingPass(ctx, nodeName); err != nil {\n\t\t\tlogger.Error(err, \"Failed to taint NoSchedule on node, requeue it\", \"node\", klog.KRef(\"\", nodeName))\n\t\t\t// TODO(k82cn): Add nodeName back to the queue\n\t\t}\n\t\t// TODO: re-evaluate whether there are any labels that need to be\n\t\t// reconcile in 1.19. Remove this function if it's no longer necessary.\n\t\tif err := nc.reconcileNodeLabels(ctx, nodeName); err != nil {\n\t\t\tlogger.Error(err, \"Failed to reconcile labels for node, requeue it\", \"node\", klog.KRef(\"\", nodeName))\n\t\t\t// TODO(yujuhong): Add nodeName back to the queue\n\t\t}\n\t\tnc.nodeUpdateQueue.Done(nodeName)\n\t}\n}","line":{"from":512,"to":534}} {"id":100004281,"name":"doNoScheduleTaintingPass","signature":"func (nc *Controller) doNoScheduleTaintingPass(ctx context.Context, nodeName string) error","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"func (nc *Controller) doNoScheduleTaintingPass(ctx context.Context, nodeName string) error {\n\tnode, err := nc.nodeLister.Get(nodeName)\n\tif err != nil {\n\t\t// If node not found, just ignore it.\n\t\tif apierrors.IsNotFound(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\t// Map node's condition to Taints.\n\tvar taints []v1.Taint\n\tfor _, condition := range node.Status.Conditions {\n\t\tif taintMap, found := nodeConditionToTaintKeyStatusMap[condition.Type]; found {\n\t\t\tif taintKey, found := taintMap[condition.Status]; found {\n\t\t\t\ttaints = append(taints, v1.Taint{\n\t\t\t\t\tKey: taintKey,\n\t\t\t\t\tEffect: v1.TaintEffectNoSchedule,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\tif node.Spec.Unschedulable {\n\t\t// If unschedulable, append related taint.\n\t\ttaints = append(taints, v1.Taint{\n\t\t\tKey: v1.TaintNodeUnschedulable,\n\t\t\tEffect: v1.TaintEffectNoSchedule,\n\t\t})\n\t}\n\n\t// Get exist taints of node.\n\tnodeTaints := taintutils.TaintSetFilter(node.Spec.Taints, func(t *v1.Taint) bool {\n\t\t// only NoSchedule taints are candidates to be compared with \"taints\" later\n\t\tif t.Effect != v1.TaintEffectNoSchedule {\n\t\t\treturn false\n\t\t}\n\t\t// Find unschedulable taint of node.\n\t\tif t.Key == v1.TaintNodeUnschedulable {\n\t\t\treturn true\n\t\t}\n\t\t// Find node condition taints of node.\n\t\t_, found := taintKeyToNodeConditionMap[t.Key]\n\t\treturn found\n\t})\n\ttaintsToAdd, taintsToDel := taintutils.TaintSetDiff(taints, nodeTaints)\n\t// If nothing to add or delete, return true directly.\n\tif len(taintsToAdd) == 0 \u0026\u0026 len(taintsToDel) == 0 {\n\t\treturn nil\n\t}\n\tif !controllerutil.SwapNodeControllerTaint(ctx, nc.kubeClient, taintsToAdd, taintsToDel, node) {\n\t\treturn fmt.Errorf(\"failed to swap taints of node %+v\", node)\n\t}\n\treturn nil\n}","line":{"from":536,"to":589}} {"id":100004282,"name":"doNoExecuteTaintingPass","signature":"func (nc *Controller) doNoExecuteTaintingPass(ctx context.Context)","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"func (nc *Controller) doNoExecuteTaintingPass(ctx context.Context) {\n\t// Extract out the keys of the map in order to not hold\n\t// the evictorLock for the entire function and hold it\n\t// only when nescessary.\n\tvar zoneNoExecuteTainterKeys []string\n\tfunc() {\n\t\tnc.evictorLock.Lock()\n\t\tdefer nc.evictorLock.Unlock()\n\n\t\tzoneNoExecuteTainterKeys = make([]string, 0, len(nc.zoneNoExecuteTainter))\n\t\tfor k := range nc.zoneNoExecuteTainter {\n\t\t\tzoneNoExecuteTainterKeys = append(zoneNoExecuteTainterKeys, k)\n\t\t}\n\t}()\n\tlogger := klog.FromContext(ctx)\n\tfor _, k := range zoneNoExecuteTainterKeys {\n\t\tvar zoneNoExecuteTainterWorker *scheduler.RateLimitedTimedQueue\n\t\tfunc() {\n\t\t\tnc.evictorLock.Lock()\n\t\t\tdefer nc.evictorLock.Unlock()\n\t\t\t// Extracting the value without checking if the key\n\t\t\t// exists or not is safe to do here since zones do\n\t\t\t// not get removed, and consequently pod evictors for\n\t\t\t// these zones also do not get removed, only added.\n\t\t\tzoneNoExecuteTainterWorker = nc.zoneNoExecuteTainter[k]\n\t\t}()\n\t\t// Function should return 'false' and a time after which it should be retried, or 'true' if it shouldn't (it succeeded).\n\t\tzoneNoExecuteTainterWorker.Try(logger, func(value scheduler.TimedValue) (bool, time.Duration) {\n\t\t\tnode, err := nc.nodeLister.Get(value.Value)\n\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\tlogger.Info(\"Node no longer present in nodeLister\", \"node\", klog.KRef(\"\", value.Value))\n\t\t\t\treturn true, 0\n\t\t\t} else if err != nil {\n\t\t\t\tlogger.Info(\"Failed to get Node from the nodeLister\", \"node\", klog.KRef(\"\", value.Value), \"err\", err)\n\t\t\t\t// retry in 50 millisecond\n\t\t\t\treturn false, 50 * time.Millisecond\n\t\t\t}\n\t\t\t_, condition := controllerutil.GetNodeCondition(\u0026node.Status, v1.NodeReady)\n\t\t\t// Because we want to mimic NodeStatus.Condition[\"Ready\"] we make \"unreachable\" and \"not ready\" taints mutually exclusive.\n\t\t\ttaintToAdd := v1.Taint{}\n\t\t\toppositeTaint := v1.Taint{}\n\t\t\tswitch condition.Status {\n\t\t\tcase v1.ConditionFalse:\n\t\t\t\ttaintToAdd = *NotReadyTaintTemplate\n\t\t\t\toppositeTaint = *UnreachableTaintTemplate\n\t\t\tcase v1.ConditionUnknown:\n\t\t\t\ttaintToAdd = *UnreachableTaintTemplate\n\t\t\t\toppositeTaint = *NotReadyTaintTemplate\n\t\t\tdefault:\n\t\t\t\t// It seems that the Node is ready again, so there's no need to taint it.\n\t\t\t\tlogger.V(4).Info(\"Node was in a taint queue, but it's ready now. Ignoring taint request\", \"node\", klog.KRef(\"\", value.Value))\n\t\t\t\treturn true, 0\n\t\t\t}\n\t\t\tresult := controllerutil.SwapNodeControllerTaint(ctx, nc.kubeClient, []*v1.Taint{\u0026taintToAdd}, []*v1.Taint{\u0026oppositeTaint}, node)\n\t\t\tif result {\n\t\t\t\t// Count the number of evictions.\n\t\t\t\tzone := nodetopology.GetZoneKey(node)\n\t\t\t\tevictionsTotal.WithLabelValues(zone).Inc()\n\t\t\t}\n\n\t\t\treturn result, 0\n\t\t})\n\t}\n}","line":{"from":591,"to":654}} {"id":100004283,"name":"monitorNodeHealth","signature":"func (nc *Controller) monitorNodeHealth(ctx context.Context) error","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"// monitorNodeHealth verifies node health are constantly updated by kubelet, and\n// if not, post \"NodeReady==ConditionUnknown\".\n// This function will taint nodes who are not ready or not reachable for a long period of time.\nfunc (nc *Controller) monitorNodeHealth(ctx context.Context) error {\n\tstart := nc.now()\n\tdefer func() {\n\t\tupdateAllNodesHealthDuration.Observe(time.Since(start.Time).Seconds())\n\t}()\n\n\t// We are listing nodes from local cache as we can tolerate some small delays\n\t// comparing to state from etcd and there is eventual consistency anyway.\n\tnodes, err := nc.nodeLister.List(labels.Everything())\n\tif err != nil {\n\t\treturn err\n\t}\n\tadded, deleted, newZoneRepresentatives := nc.classifyNodes(nodes)\n\tlogger := klog.FromContext(ctx)\n\tfor i := range newZoneRepresentatives {\n\t\tnc.addPodEvictorForNewZone(logger, newZoneRepresentatives[i])\n\t}\n\tfor i := range added {\n\t\tlogger.V(1).Info(\"Controller observed a new Node\", \"node\", klog.KRef(\"\", added[i].Name))\n\t\tcontrollerutil.RecordNodeEvent(ctx, nc.recorder, added[i].Name, string(added[i].UID), v1.EventTypeNormal, \"RegisteredNode\", fmt.Sprintf(\"Registered Node %v in Controller\", added[i].Name))\n\t\tnc.knownNodeSet[added[i].Name] = added[i]\n\t\tnc.addPodEvictorForNewZone(logger, added[i])\n\t\tnc.markNodeAsReachable(ctx, added[i])\n\t}\n\n\tfor i := range deleted {\n\t\tlogger.V(1).Info(\"Controller observed a Node deletion\", \"node\", klog.KRef(\"\", deleted[i].Name))\n\t\tcontrollerutil.RecordNodeEvent(ctx, nc.recorder, deleted[i].Name, string(deleted[i].UID), v1.EventTypeNormal, \"RemovingNode\", fmt.Sprintf(\"Removing Node %v from Controller\", deleted[i].Name))\n\t\tdelete(nc.knownNodeSet, deleted[i].Name)\n\t}\n\n\tvar zoneToNodeConditionsLock sync.Mutex\n\tzoneToNodeConditions := map[string][]*v1.NodeCondition{}\n\tupdateNodeFunc := func(piece int) {\n\t\tstart := nc.now()\n\t\tdefer func() {\n\t\t\tupdateNodeHealthDuration.Observe(time.Since(start.Time).Seconds())\n\t\t}()\n\n\t\tvar observedReadyCondition v1.NodeCondition\n\t\tvar currentReadyCondition *v1.NodeCondition\n\t\tnode := nodes[piece].DeepCopy()\n\n\t\tif err := wait.PollImmediate(retrySleepTime, retrySleepTime*scheduler.NodeHealthUpdateRetry, func() (bool, error) {\n\t\t\tvar err error\n\t\t\t_, observedReadyCondition, currentReadyCondition, err = nc.tryUpdateNodeHealth(ctx, node)\n\t\t\tif err == nil {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\tname := node.Name\n\t\t\tnode, err = nc.kubeClient.CoreV1().Nodes().Get(ctx, name, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\tlogger.Error(nil, \"Failed while getting a Node to retry updating node health. Probably Node was deleted\", \"node\", klog.KRef(\"\", name))\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\treturn false, nil\n\t\t}); err != nil {\n\t\t\tlogger.Error(err, \"Update health of Node from Controller error, Skipping - no pods will be evicted\", \"node\", klog.KObj(node))\n\t\t\treturn\n\t\t}\n\n\t\t// Some nodes may be excluded from disruption checking\n\t\tif !isNodeExcludedFromDisruptionChecks(node) {\n\t\t\tzoneToNodeConditionsLock.Lock()\n\t\t\tzoneToNodeConditions[nodetopology.GetZoneKey(node)] = append(zoneToNodeConditions[nodetopology.GetZoneKey(node)], currentReadyCondition)\n\t\t\tzoneToNodeConditionsLock.Unlock()\n\t\t}\n\n\t\tif currentReadyCondition != nil {\n\t\t\tpods, err := nc.getPodsAssignedToNode(node.Name)\n\t\t\tif err != nil {\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"unable to list pods of node %v: %v\", node.Name, err))\n\t\t\t\tif currentReadyCondition.Status != v1.ConditionTrue \u0026\u0026 observedReadyCondition.Status == v1.ConditionTrue {\n\t\t\t\t\t// If error happened during node status transition (Ready -\u003e NotReady)\n\t\t\t\t\t// we need to mark node for retry to force MarkPodsNotReady execution\n\t\t\t\t\t// in the next iteration.\n\t\t\t\t\tnc.nodesToRetry.Store(node.Name, struct{}{})\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tnc.processTaintBaseEviction(ctx, node, \u0026observedReadyCondition)\n\n\t\t\t_, needsRetry := nc.nodesToRetry.Load(node.Name)\n\t\t\tswitch {\n\t\t\tcase currentReadyCondition.Status != v1.ConditionTrue \u0026\u0026 observedReadyCondition.Status == v1.ConditionTrue:\n\t\t\t\t// Report node event only once when status changed.\n\t\t\t\tcontrollerutil.RecordNodeStatusChange(nc.recorder, node, \"NodeNotReady\")\n\t\t\t\tfallthrough\n\t\t\tcase needsRetry \u0026\u0026 observedReadyCondition.Status != v1.ConditionTrue:\n\t\t\t\tif err = controllerutil.MarkPodsNotReady(ctx, nc.kubeClient, nc.recorder, pods, node.Name); err != nil {\n\t\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"unable to mark all pods NotReady on node %v: %v; queuing for retry\", node.Name, err))\n\t\t\t\t\tnc.nodesToRetry.Store(node.Name, struct{}{})\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tnc.nodesToRetry.Delete(node.Name)\n\t}\n\n\t// Marking the pods not ready on a node requires looping over them and\n\t// updating each pod's status one at a time. This is performed serially, and\n\t// can take a while if we're processing each node serially as well. So we\n\t// process them with bounded concurrency instead, since most of the time is\n\t// spent waiting on io.\n\tworkqueue.ParallelizeUntil(ctx, nc.nodeUpdateWorkerSize, len(nodes), updateNodeFunc)\n\n\tnc.handleDisruption(ctx, zoneToNodeConditions, nodes)\n\n\treturn nil\n}","line":{"from":656,"to":768}} {"id":100004284,"name":"processTaintBaseEviction","signature":"func (nc *Controller) processTaintBaseEviction(ctx context.Context, node *v1.Node, observedReadyCondition *v1.NodeCondition)","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"func (nc *Controller) processTaintBaseEviction(ctx context.Context, node *v1.Node, observedReadyCondition *v1.NodeCondition) {\n\tdecisionTimestamp := nc.now()\n\t// Check eviction timeout against decisionTimestamp\n\tlogger := klog.FromContext(ctx)\n\tswitch observedReadyCondition.Status {\n\tcase v1.ConditionFalse:\n\t\t// We want to update the taint straight away if Node is already tainted with the UnreachableTaint\n\t\tif taintutils.TaintExists(node.Spec.Taints, UnreachableTaintTemplate) {\n\t\t\ttaintToAdd := *NotReadyTaintTemplate\n\t\t\tif !controllerutil.SwapNodeControllerTaint(ctx, nc.kubeClient, []*v1.Taint{\u0026taintToAdd}, []*v1.Taint{UnreachableTaintTemplate}, node) {\n\t\t\t\tlogger.Error(nil, \"Failed to instantly swap UnreachableTaint to NotReadyTaint. Will try again in the next cycle\")\n\t\t\t}\n\t\t} else if nc.markNodeForTainting(node, v1.ConditionFalse) {\n\t\t\tlogger.V(2).Info(\"Node is NotReady. Adding it to the Taint queue\", \"node\", klog.KObj(node), \"timeStamp\", decisionTimestamp)\n\t\t}\n\tcase v1.ConditionUnknown:\n\t\t// We want to update the taint straight away if Node is already tainted with the UnreachableTaint\n\t\tif taintutils.TaintExists(node.Spec.Taints, NotReadyTaintTemplate) {\n\t\t\ttaintToAdd := *UnreachableTaintTemplate\n\t\t\tif !controllerutil.SwapNodeControllerTaint(ctx, nc.kubeClient, []*v1.Taint{\u0026taintToAdd}, []*v1.Taint{NotReadyTaintTemplate}, node) {\n\t\t\t\tlogger.Error(nil, \"Failed to instantly swap NotReadyTaint to UnreachableTaint. Will try again in the next cycle\")\n\t\t\t}\n\t\t} else if nc.markNodeForTainting(node, v1.ConditionUnknown) {\n\t\t\tlogger.V(2).Info(\"Node is unresponsive. Adding it to the Taint queue\", \"node\", klog.KObj(node), \"timeStamp\", decisionTimestamp)\n\t\t}\n\tcase v1.ConditionTrue:\n\t\tremoved, err := nc.markNodeAsReachable(ctx, node)\n\t\tif err != nil {\n\t\t\tlogger.Error(nil, \"Failed to remove taints from node. Will retry in next iteration\", \"node\", klog.KObj(node))\n\t\t}\n\t\tif removed {\n\t\t\tlogger.V(2).Info(\"Node is healthy again, removing all taints\", \"node\", klog.KObj(node))\n\t\t}\n\t}\n}","line":{"from":770,"to":804}} {"id":100004285,"name":"isNodeExcludedFromDisruptionChecks","signature":"func isNodeExcludedFromDisruptionChecks(node *v1.Node) bool","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"func isNodeExcludedFromDisruptionChecks(node *v1.Node) bool {\n\tif _, ok := node.Labels[labelNodeDisruptionExclusion]; ok {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":810,"to":815}} {"id":100004286,"name":"tryUpdateNodeHealth","signature":"func (nc *Controller) tryUpdateNodeHealth(ctx context.Context, node *v1.Node) (time.Duration, v1.NodeCondition, *v1.NodeCondition, error)","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"// tryUpdateNodeHealth checks a given node's conditions and tries to update it. Returns grace period to\n// which given node is entitled, state of current and last observed Ready Condition, and an error if it occurred.\nfunc (nc *Controller) tryUpdateNodeHealth(ctx context.Context, node *v1.Node) (time.Duration, v1.NodeCondition, *v1.NodeCondition, error) {\n\tnodeHealth := nc.nodeHealthMap.getDeepCopy(node.Name)\n\tdefer func() {\n\t\tnc.nodeHealthMap.set(node.Name, nodeHealth)\n\t}()\n\n\tvar gracePeriod time.Duration\n\tvar observedReadyCondition v1.NodeCondition\n\t_, currentReadyCondition := controllerutil.GetNodeCondition(\u0026node.Status, v1.NodeReady)\n\tif currentReadyCondition == nil {\n\t\t// If ready condition is nil, then kubelet (or nodecontroller) never posted node status.\n\t\t// A fake ready condition is created, where LastHeartbeatTime and LastTransitionTime is set\n\t\t// to node.CreationTimestamp to avoid handle the corner case.\n\t\tobservedReadyCondition = v1.NodeCondition{\n\t\t\tType: v1.NodeReady,\n\t\t\tStatus: v1.ConditionUnknown,\n\t\t\tLastHeartbeatTime: node.CreationTimestamp,\n\t\t\tLastTransitionTime: node.CreationTimestamp,\n\t\t}\n\t\tgracePeriod = nc.nodeStartupGracePeriod\n\t\tif nodeHealth != nil {\n\t\t\tnodeHealth.status = \u0026node.Status\n\t\t} else {\n\t\t\tnodeHealth = \u0026nodeHealthData{\n\t\t\t\tstatus: \u0026node.Status,\n\t\t\t\tprobeTimestamp: node.CreationTimestamp,\n\t\t\t\treadyTransitionTimestamp: node.CreationTimestamp,\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// If ready condition is not nil, make a copy of it, since we may modify it in place later.\n\t\tobservedReadyCondition = *currentReadyCondition\n\t\tgracePeriod = nc.nodeMonitorGracePeriod\n\t}\n\t// There are following cases to check:\n\t// - both saved and new status have no Ready Condition set - we leave everything as it is,\n\t// - saved status have no Ready Condition, but current one does - Controller was restarted with Node data already present in etcd,\n\t// - saved status have some Ready Condition, but current one does not - it's an error, but we fill it up because that's probably a good thing to do,\n\t// - both saved and current statuses have Ready Conditions and they have the same LastProbeTime - nothing happened on that Node, it may be\n\t// unresponsive, so we leave it as it is,\n\t// - both saved and current statuses have Ready Conditions, they have different LastProbeTimes, but the same Ready Condition State -\n\t// everything's in order, no transition occurred, we update only probeTimestamp,\n\t// - both saved and current statuses have Ready Conditions, different LastProbeTimes and different Ready Condition State -\n\t// Ready Condition changed it state since we last seen it, so we update both probeTimestamp and readyTransitionTimestamp.\n\t// TODO: things to consider:\n\t// - if 'LastProbeTime' have gone back in time its probably an error, currently we ignore it,\n\t// - currently only correct Ready State transition outside of Node Controller is marking it ready by Kubelet, we don't check\n\t// if that's the case, but it does not seem necessary.\n\tvar savedCondition *v1.NodeCondition\n\tvar savedLease *coordv1.Lease\n\tif nodeHealth != nil {\n\t\t_, savedCondition = controllerutil.GetNodeCondition(nodeHealth.status, v1.NodeReady)\n\t\tsavedLease = nodeHealth.lease\n\t}\n\tlogger := klog.FromContext(ctx)\n\tif nodeHealth == nil {\n\t\tlogger.Info(\"Missing timestamp for Node. Assuming now as a timestamp\", \"node\", klog.KObj(node))\n\t\tnodeHealth = \u0026nodeHealthData{\n\t\t\tstatus: \u0026node.Status,\n\t\t\tprobeTimestamp: nc.now(),\n\t\t\treadyTransitionTimestamp: nc.now(),\n\t\t}\n\t} else if savedCondition == nil \u0026\u0026 currentReadyCondition != nil {\n\t\tlogger.V(1).Info(\"Creating timestamp entry for newly observed Node\", \"node\", klog.KObj(node))\n\t\tnodeHealth = \u0026nodeHealthData{\n\t\t\tstatus: \u0026node.Status,\n\t\t\tprobeTimestamp: nc.now(),\n\t\t\treadyTransitionTimestamp: nc.now(),\n\t\t}\n\t} else if savedCondition != nil \u0026\u0026 currentReadyCondition == nil {\n\t\tlogger.Error(nil, \"ReadyCondition was removed from Status of Node\", \"node\", klog.KObj(node))\n\t\t// TODO: figure out what to do in this case. For now we do the same thing as above.\n\t\tnodeHealth = \u0026nodeHealthData{\n\t\t\tstatus: \u0026node.Status,\n\t\t\tprobeTimestamp: nc.now(),\n\t\t\treadyTransitionTimestamp: nc.now(),\n\t\t}\n\t} else if savedCondition != nil \u0026\u0026 currentReadyCondition != nil \u0026\u0026 savedCondition.LastHeartbeatTime != currentReadyCondition.LastHeartbeatTime {\n\t\tvar transitionTime metav1.Time\n\t\t// If ReadyCondition changed since the last time we checked, we update the transition timestamp to \"now\",\n\t\t// otherwise we leave it as it is.\n\t\tif savedCondition.LastTransitionTime != currentReadyCondition.LastTransitionTime {\n\t\t\tlogger.V(3).Info(\"ReadyCondition for Node transitioned from savedCondition to currentReadyCondition\", \"node\", klog.KObj(node), \"savedCondition\", savedCondition, \"currentReadyCondition\", currentReadyCondition)\n\t\t\ttransitionTime = nc.now()\n\t\t} else {\n\t\t\ttransitionTime = nodeHealth.readyTransitionTimestamp\n\t\t}\n\t\tif loggerV := logger.V(5); loggerV.Enabled() {\n\t\t\tloggerV.Info(\"Node ReadyCondition updated. Updating timestamp\", \"node\", klog.KObj(node), \"nodeHealthStatus\", nodeHealth.status, \"nodeStatus\", node.Status)\n\t\t} else {\n\t\t\tlogger.V(3).Info(\"Node ReadyCondition updated. Updating timestamp\", \"node\", klog.KObj(node))\n\t\t}\n\t\tnodeHealth = \u0026nodeHealthData{\n\t\t\tstatus: \u0026node.Status,\n\t\t\tprobeTimestamp: nc.now(),\n\t\t\treadyTransitionTimestamp: transitionTime,\n\t\t}\n\t}\n\t// Always update the probe time if node lease is renewed.\n\t// Note: If kubelet never posted the node status, but continues renewing the\n\t// heartbeat leases, the node controller will assume the node is healthy and\n\t// take no action.\n\tobservedLease, _ := nc.leaseLister.Leases(v1.NamespaceNodeLease).Get(node.Name)\n\tif observedLease != nil \u0026\u0026 (savedLease == nil || savedLease.Spec.RenewTime.Before(observedLease.Spec.RenewTime)) {\n\t\tnodeHealth.lease = observedLease\n\t\tnodeHealth.probeTimestamp = nc.now()\n\t}\n\n\tif nc.now().After(nodeHealth.probeTimestamp.Add(gracePeriod)) {\n\t\t// NodeReady condition or lease was last set longer ago than gracePeriod, so\n\t\t// update it to Unknown (regardless of its current value) in the master.\n\n\t\tnodeConditionTypes := []v1.NodeConditionType{\n\t\t\tv1.NodeReady,\n\t\t\tv1.NodeMemoryPressure,\n\t\t\tv1.NodeDiskPressure,\n\t\t\tv1.NodePIDPressure,\n\t\t\t// We don't change 'NodeNetworkUnavailable' condition, as it's managed on a control plane level.\n\t\t\t// v1.NodeNetworkUnavailable,\n\t\t}\n\n\t\tnowTimestamp := nc.now()\n\t\tfor _, nodeConditionType := range nodeConditionTypes {\n\t\t\t_, currentCondition := controllerutil.GetNodeCondition(\u0026node.Status, nodeConditionType)\n\t\t\tif currentCondition == nil {\n\t\t\t\tlogger.V(2).Info(\"Condition of node was never updated by kubelet\", \"nodeConditionType\", nodeConditionType, \"node\", klog.KObj(node))\n\t\t\t\tnode.Status.Conditions = append(node.Status.Conditions, v1.NodeCondition{\n\t\t\t\t\tType: nodeConditionType,\n\t\t\t\t\tStatus: v1.ConditionUnknown,\n\t\t\t\t\tReason: \"NodeStatusNeverUpdated\",\n\t\t\t\t\tMessage: \"Kubelet never posted node status.\",\n\t\t\t\t\tLastHeartbeatTime: node.CreationTimestamp,\n\t\t\t\t\tLastTransitionTime: nowTimestamp,\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\tlogger.V(2).Info(\"Node hasn't been updated\",\n\t\t\t\t\t\"node\", klog.KObj(node), \"duration\", nc.now().Time.Sub(nodeHealth.probeTimestamp.Time), \"nodeConditionType\", nodeConditionType, \"currentCondition\", currentCondition)\n\t\t\t\tif currentCondition.Status != v1.ConditionUnknown {\n\t\t\t\t\tcurrentCondition.Status = v1.ConditionUnknown\n\t\t\t\t\tcurrentCondition.Reason = \"NodeStatusUnknown\"\n\t\t\t\t\tcurrentCondition.Message = \"Kubelet stopped posting node status.\"\n\t\t\t\t\tcurrentCondition.LastTransitionTime = nowTimestamp\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// We need to update currentReadyCondition due to its value potentially changed.\n\t\t_, currentReadyCondition = controllerutil.GetNodeCondition(\u0026node.Status, v1.NodeReady)\n\n\t\tif !apiequality.Semantic.DeepEqual(currentReadyCondition, \u0026observedReadyCondition) {\n\t\t\tif _, err := nc.kubeClient.CoreV1().Nodes().UpdateStatus(ctx, node, metav1.UpdateOptions{}); err != nil {\n\t\t\t\tlogger.Error(err, \"Error updating node\", \"node\", klog.KObj(node))\n\t\t\t\treturn gracePeriod, observedReadyCondition, currentReadyCondition, err\n\t\t\t}\n\t\t\tnodeHealth = \u0026nodeHealthData{\n\t\t\t\tstatus: \u0026node.Status,\n\t\t\t\tprobeTimestamp: nodeHealth.probeTimestamp,\n\t\t\t\treadyTransitionTimestamp: nc.now(),\n\t\t\t\tlease: observedLease,\n\t\t\t}\n\t\t\treturn gracePeriod, observedReadyCondition, currentReadyCondition, nil\n\t\t}\n\t}\n\n\treturn gracePeriod, observedReadyCondition, currentReadyCondition, nil\n}","line":{"from":817,"to":983}} {"id":100004287,"name":"handleDisruption","signature":"func (nc *Controller) handleDisruption(ctx context.Context, zoneToNodeConditions map[string][]*v1.NodeCondition, nodes []*v1.Node)","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"func (nc *Controller) handleDisruption(ctx context.Context, zoneToNodeConditions map[string][]*v1.NodeCondition, nodes []*v1.Node) {\n\tnewZoneStates := map[string]ZoneState{}\n\tallAreFullyDisrupted := true\n\tlogger := klog.FromContext(ctx)\n\tfor k, v := range zoneToNodeConditions {\n\t\tzoneSize.WithLabelValues(k).Set(float64(len(v)))\n\t\tunhealthy, newState := nc.computeZoneStateFunc(v)\n\t\tzoneHealth.WithLabelValues(k).Set(float64(100*(len(v)-unhealthy)) / float64(len(v)))\n\t\tunhealthyNodes.WithLabelValues(k).Set(float64(unhealthy))\n\t\tif newState != stateFullDisruption {\n\t\t\tallAreFullyDisrupted = false\n\t\t}\n\t\tnewZoneStates[k] = newState\n\t\tif _, had := nc.zoneStates[k]; !had {\n\t\t\tlogger.Error(nil, \"Setting initial state for unseen zone\", \"zone\", k)\n\t\t\tnc.zoneStates[k] = stateInitial\n\t\t}\n\t}\n\n\tallWasFullyDisrupted := true\n\tfor k, v := range nc.zoneStates {\n\t\tif _, have := zoneToNodeConditions[k]; !have {\n\t\t\tzoneSize.WithLabelValues(k).Set(0)\n\t\t\tzoneHealth.WithLabelValues(k).Set(100)\n\t\t\tunhealthyNodes.WithLabelValues(k).Set(0)\n\t\t\tdelete(nc.zoneStates, k)\n\t\t\tcontinue\n\t\t}\n\t\tif v != stateFullDisruption {\n\t\t\tallWasFullyDisrupted = false\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// At least one node was responding in previous pass or in the current pass. Semantics is as follows:\n\t// - if the new state is \"partialDisruption\" we call a user defined function that returns a new limiter to use,\n\t// - if the new state is \"normal\" we resume normal operation (go back to default limiter settings),\n\t// - if new state is \"fullDisruption\" we restore normal eviction rate,\n\t// - unless all zones in the cluster are in \"fullDisruption\" - in that case we stop all evictions.\n\tif !allAreFullyDisrupted || !allWasFullyDisrupted {\n\t\t// We're switching to full disruption mode\n\t\tif allAreFullyDisrupted {\n\t\t\tlogger.Info(\"Controller detected that all Nodes are not-Ready. Entering master disruption mode\")\n\t\t\tfor i := range nodes {\n\t\t\t\t_, err := nc.markNodeAsReachable(ctx, nodes[i])\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Error(nil, \"Failed to remove taints from Node\", \"node\", klog.KObj(nodes[i]))\n\t\t\t\t}\n\t\t\t}\n\t\t\t// We stop all evictions.\n\t\t\tfor k := range nc.zoneStates {\n\t\t\t\tnc.zoneNoExecuteTainter[k].SwapLimiter(0)\n\t\t\t}\n\t\t\tfor k := range nc.zoneStates {\n\t\t\t\tnc.zoneStates[k] = stateFullDisruption\n\t\t\t}\n\t\t\t// All rate limiters are updated, so we can return early here.\n\t\t\treturn\n\t\t}\n\t\t// We're exiting full disruption mode\n\t\tif allWasFullyDisrupted {\n\t\t\tlogger.Info(\"Controller detected that some Nodes are Ready. Exiting master disruption mode\")\n\t\t\t// When exiting disruption mode update probe timestamps on all Nodes.\n\t\t\tnow := nc.now()\n\t\t\tfor i := range nodes {\n\t\t\t\tv := nc.nodeHealthMap.getDeepCopy(nodes[i].Name)\n\t\t\t\tv.probeTimestamp = now\n\t\t\t\tv.readyTransitionTimestamp = now\n\t\t\t\tnc.nodeHealthMap.set(nodes[i].Name, v)\n\t\t\t}\n\t\t\t// We reset all rate limiters to settings appropriate for the given state.\n\t\t\tfor k := range nc.zoneStates {\n\t\t\t\tnc.setLimiterInZone(k, len(zoneToNodeConditions[k]), newZoneStates[k])\n\t\t\t\tnc.zoneStates[k] = newZoneStates[k]\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\t// We know that there's at least one not-fully disrupted so,\n\t\t// we can use default behavior for rate limiters\n\t\tfor k, v := range nc.zoneStates {\n\t\t\tnewState := newZoneStates[k]\n\t\t\tif v == newState {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlogger.Info(\"Controller detected that zone is now in new state\", \"zone\", k, \"newState\", newState)\n\t\t\tnc.setLimiterInZone(k, len(zoneToNodeConditions[k]), newState)\n\t\t\tnc.zoneStates[k] = newState\n\t\t}\n\t}\n}","line":{"from":985,"to":1074}} {"id":100004288,"name":"podUpdated","signature":"func (nc *Controller) podUpdated(oldPod, newPod *v1.Pod)","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"func (nc *Controller) podUpdated(oldPod, newPod *v1.Pod) {\n\tif newPod == nil {\n\t\treturn\n\t}\n\tif len(newPod.Spec.NodeName) != 0 \u0026\u0026 (oldPod == nil || newPod.Spec.NodeName != oldPod.Spec.NodeName) {\n\t\tpodItem := podUpdateItem{newPod.Namespace, newPod.Name}\n\t\tnc.podUpdateQueue.Add(podItem)\n\t}\n}","line":{"from":1076,"to":1084}} {"id":100004289,"name":"doPodProcessingWorker","signature":"func (nc *Controller) doPodProcessingWorker(ctx context.Context)","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"func (nc *Controller) doPodProcessingWorker(ctx context.Context) {\n\tfor {\n\t\tobj, shutdown := nc.podUpdateQueue.Get()\n\t\t// \"podUpdateQueue\" will be shutdown when \"stopCh\" closed;\n\t\t// we do not need to re-check \"stopCh\" again.\n\t\tif shutdown {\n\t\t\treturn\n\t\t}\n\n\t\tpodItem := obj.(podUpdateItem)\n\t\tnc.processPod(ctx, podItem)\n\t}\n}","line":{"from":1086,"to":1098}} {"id":100004290,"name":"processPod","signature":"func (nc *Controller) processPod(ctx context.Context, podItem podUpdateItem)","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"// processPod is processing events of assigning pods to nodes. In particular:\n// 1. for NodeReady=true node, taint eviction for this pod will be cancelled\n// 2. for NodeReady=false or unknown node, taint eviction of pod will happen and pod will be marked as not ready\n// 3. if node doesn't exist in cache, it will be skipped.\nfunc (nc *Controller) processPod(ctx context.Context, podItem podUpdateItem) {\n\tdefer nc.podUpdateQueue.Done(podItem)\n\tpod, err := nc.podLister.Pods(podItem.namespace).Get(podItem.name)\n\tlogger := klog.FromContext(ctx)\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\t// If the pod was deleted, there is no need to requeue.\n\t\t\treturn\n\t\t}\n\t\tlogger.Info(\"Failed to read pod\", \"pod\", klog.KRef(podItem.namespace, podItem.name), \"err\", err)\n\t\tnc.podUpdateQueue.AddRateLimited(podItem)\n\t\treturn\n\t}\n\n\tnodeName := pod.Spec.NodeName\n\n\tnodeHealth := nc.nodeHealthMap.getDeepCopy(nodeName)\n\tif nodeHealth == nil {\n\t\t// Node data is not gathered yet or node has been removed in the meantime.\n\t\treturn\n\t}\n\n\t_, err = nc.nodeLister.Get(nodeName)\n\tif err != nil {\n\t\tlogger.Info(\"Failed to read node\", \"node\", klog.KRef(\"\", nodeName), \"err\", err)\n\t\tnc.podUpdateQueue.AddRateLimited(podItem)\n\t\treturn\n\t}\n\n\t_, currentReadyCondition := controllerutil.GetNodeCondition(nodeHealth.status, v1.NodeReady)\n\tif currentReadyCondition == nil {\n\t\t// Lack of NodeReady condition may only happen after node addition (or if it will be maliciously deleted).\n\t\t// In both cases, the pod will be handled correctly (evicted if needed) during processing\n\t\t// of the next node update event.\n\t\treturn\n\t}\n\n\tpods := []*v1.Pod{pod}\n\tif currentReadyCondition.Status != v1.ConditionTrue {\n\t\tif err := controllerutil.MarkPodsNotReady(ctx, nc.kubeClient, nc.recorder, pods, nodeName); err != nil {\n\t\t\tlogger.Info(\"Unable to mark pod NotReady on node\", \"pod\", klog.KRef(podItem.namespace, podItem.name), \"node\", klog.KRef(\"\", nodeName), \"err\", err)\n\t\t\tnc.podUpdateQueue.AddRateLimited(podItem)\n\t\t}\n\t}\n}","line":{"from":1100,"to":1148}} {"id":100004291,"name":"setLimiterInZone","signature":"func (nc *Controller) setLimiterInZone(zone string, zoneSize int, state ZoneState)","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"func (nc *Controller) setLimiterInZone(zone string, zoneSize int, state ZoneState) {\n\tswitch state {\n\tcase stateNormal:\n\t\tnc.zoneNoExecuteTainter[zone].SwapLimiter(nc.evictionLimiterQPS)\n\tcase statePartialDisruption:\n\t\tnc.zoneNoExecuteTainter[zone].SwapLimiter(\n\t\t\tnc.enterPartialDisruptionFunc(zoneSize))\n\tcase stateFullDisruption:\n\t\tnc.zoneNoExecuteTainter[zone].SwapLimiter(\n\t\t\tnc.enterFullDisruptionFunc(zoneSize))\n\t}\n}","line":{"from":1150,"to":1161}} {"id":100004292,"name":"classifyNodes","signature":"func (nc *Controller) classifyNodes(allNodes []*v1.Node) (added, deleted, newZoneRepresentatives []*v1.Node)","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"// classifyNodes classifies the allNodes to three categories:\n// 1. added: the nodes that in 'allNodes', but not in 'knownNodeSet'\n// 2. deleted: the nodes that in 'knownNodeSet', but not in 'allNodes'\n// 3. newZoneRepresentatives: the nodes that in both 'knownNodeSet' and 'allNodes', but no zone states\nfunc (nc *Controller) classifyNodes(allNodes []*v1.Node) (added, deleted, newZoneRepresentatives []*v1.Node) {\n\tfor i := range allNodes {\n\t\tif _, has := nc.knownNodeSet[allNodes[i].Name]; !has {\n\t\t\tadded = append(added, allNodes[i])\n\t\t} else {\n\t\t\t// Currently, we only consider new zone as updated.\n\t\t\tzone := nodetopology.GetZoneKey(allNodes[i])\n\t\t\tif _, found := nc.zoneStates[zone]; !found {\n\t\t\t\tnewZoneRepresentatives = append(newZoneRepresentatives, allNodes[i])\n\t\t\t}\n\t\t}\n\t}\n\n\t// If there's a difference between lengths of known Nodes and observed nodes\n\t// we must have removed some Node.\n\tif len(nc.knownNodeSet)+len(added) != len(allNodes) {\n\t\tknowSetCopy := map[string]*v1.Node{}\n\t\tfor k, v := range nc.knownNodeSet {\n\t\t\tknowSetCopy[k] = v\n\t\t}\n\t\tfor i := range allNodes {\n\t\t\tdelete(knowSetCopy, allNodes[i].Name)\n\t\t}\n\t\tfor i := range knowSetCopy {\n\t\t\tdeleted = append(deleted, knowSetCopy[i])\n\t\t}\n\t}\n\treturn\n}","line":{"from":1163,"to":1195}} {"id":100004293,"name":"HealthyQPSFunc","signature":"func (nc *Controller) HealthyQPSFunc(nodeNum int) float32","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"// HealthyQPSFunc returns the default value for cluster eviction rate - we take\n// nodeNum for consistency with ReducedQPSFunc.\nfunc (nc *Controller) HealthyQPSFunc(nodeNum int) float32 {\n\treturn nc.evictionLimiterQPS\n}","line":{"from":1197,"to":1201}} {"id":100004294,"name":"ReducedQPSFunc","signature":"func (nc *Controller) ReducedQPSFunc(nodeNum int) float32","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"// ReducedQPSFunc returns the QPS for when a the cluster is large make\n// evictions slower, if they're small stop evictions altogether.\nfunc (nc *Controller) ReducedQPSFunc(nodeNum int) float32 {\n\tif int32(nodeNum) \u003e nc.largeClusterThreshold {\n\t\treturn nc.secondaryEvictionLimiterQPS\n\t}\n\treturn 0\n}","line":{"from":1203,"to":1210}} {"id":100004295,"name":"addPodEvictorForNewZone","signature":"func (nc *Controller) addPodEvictorForNewZone(logger klog.Logger, node *v1.Node)","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"// addPodEvictorForNewZone checks if new zone appeared, and if so add new evictor.\nfunc (nc *Controller) addPodEvictorForNewZone(logger klog.Logger, node *v1.Node) {\n\tnc.evictorLock.Lock()\n\tdefer nc.evictorLock.Unlock()\n\tzone := nodetopology.GetZoneKey(node)\n\tif _, found := nc.zoneStates[zone]; !found {\n\t\tnc.zoneStates[zone] = stateInitial\n\t\tnc.zoneNoExecuteTainter[zone] =\n\t\t\tscheduler.NewRateLimitedTimedQueue(\n\t\t\t\tflowcontrol.NewTokenBucketRateLimiter(nc.evictionLimiterQPS, scheduler.EvictionRateLimiterBurst))\n\t\t// Init the metric for the new zone.\n\t\tlogger.Info(\"Initializing eviction metric for zone\", \"zone\", zone)\n\t\tevictionsTotal.WithLabelValues(zone).Add(0)\n\t}\n}","line":{"from":1212,"to":1226}} {"id":100004296,"name":"markNodeForTainting","signature":"func (nc *Controller) markNodeForTainting(node *v1.Node, status v1.ConditionStatus) bool","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"func (nc *Controller) markNodeForTainting(node *v1.Node, status v1.ConditionStatus) bool {\n\tnc.evictorLock.Lock()\n\tdefer nc.evictorLock.Unlock()\n\tif status == v1.ConditionFalse {\n\t\tif !taintutils.TaintExists(node.Spec.Taints, NotReadyTaintTemplate) {\n\t\t\tnc.zoneNoExecuteTainter[nodetopology.GetZoneKey(node)].Remove(node.Name)\n\t\t}\n\t}\n\n\tif status == v1.ConditionUnknown {\n\t\tif !taintutils.TaintExists(node.Spec.Taints, UnreachableTaintTemplate) {\n\t\t\tnc.zoneNoExecuteTainter[nodetopology.GetZoneKey(node)].Remove(node.Name)\n\t\t}\n\t}\n\n\treturn nc.zoneNoExecuteTainter[nodetopology.GetZoneKey(node)].Add(node.Name, string(node.UID))\n}","line":{"from":1228,"to":1244}} {"id":100004297,"name":"markNodeAsReachable","signature":"func (nc *Controller) markNodeAsReachable(ctx context.Context, node *v1.Node) (bool, error)","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"func (nc *Controller) markNodeAsReachable(ctx context.Context, node *v1.Node) (bool, error) {\n\terr := controller.RemoveTaintOffNode(ctx, nc.kubeClient, node.Name, node, UnreachableTaintTemplate)\n\tlogger := klog.FromContext(ctx)\n\tif err != nil {\n\t\tlogger.Error(err, \"Failed to remove taint from node\", \"node\", klog.KObj(node))\n\t\treturn false, err\n\t}\n\terr = controller.RemoveTaintOffNode(ctx, nc.kubeClient, node.Name, node, NotReadyTaintTemplate)\n\tif err != nil {\n\t\tlogger.Error(err, \"Failed to remove taint from node\", \"node\", klog.KObj(node))\n\t\treturn false, err\n\t}\n\tnc.evictorLock.Lock()\n\tdefer nc.evictorLock.Unlock()\n\n\treturn nc.zoneNoExecuteTainter[nodetopology.GetZoneKey(node)].Remove(node.Name), nil\n}","line":{"from":1246,"to":1262}} {"id":100004298,"name":"ComputeZoneState","signature":"func (nc *Controller) ComputeZoneState(nodeReadyConditions []*v1.NodeCondition) (int, ZoneState)","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"// ComputeZoneState returns a slice of NodeReadyConditions for all Nodes in a given zone.\n// The zone is considered:\n// - fullyDisrupted if there're no Ready Nodes,\n// - partiallyDisrupted if at least than nc.unhealthyZoneThreshold percent of Nodes are not Ready,\n// - normal otherwise\nfunc (nc *Controller) ComputeZoneState(nodeReadyConditions []*v1.NodeCondition) (int, ZoneState) {\n\treadyNodes := 0\n\tnotReadyNodes := 0\n\tfor i := range nodeReadyConditions {\n\t\tif nodeReadyConditions[i] != nil \u0026\u0026 nodeReadyConditions[i].Status == v1.ConditionTrue {\n\t\t\treadyNodes++\n\t\t} else {\n\t\t\tnotReadyNodes++\n\t\t}\n\t}\n\tswitch {\n\tcase readyNodes == 0 \u0026\u0026 notReadyNodes \u003e 0:\n\t\treturn notReadyNodes, stateFullDisruption\n\tcase notReadyNodes \u003e 2 \u0026\u0026 float32(notReadyNodes)/float32(notReadyNodes+readyNodes) \u003e= nc.unhealthyZoneThreshold:\n\t\treturn notReadyNodes, statePartialDisruption\n\tdefault:\n\t\treturn notReadyNodes, stateNormal\n\t}\n}","line":{"from":1264,"to":1287}} {"id":100004299,"name":"reconcileNodeLabels","signature":"func (nc *Controller) reconcileNodeLabels(ctx context.Context, nodeName string) error","file":"pkg/controller/nodelifecycle/node_lifecycle_controller.go","code":"// reconcileNodeLabels reconciles node labels.\nfunc (nc *Controller) reconcileNodeLabels(ctx context.Context, nodeName string) error {\n\tnode, err := nc.nodeLister.Get(nodeName)\n\tif err != nil {\n\t\t// If node not found, just ignore it.\n\t\tif apierrors.IsNotFound(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\tif node.Labels == nil {\n\t\t// Nothing to reconcile.\n\t\treturn nil\n\t}\n\n\tlabelsToUpdate := map[string]string{}\n\tfor _, r := range labelReconcileInfo {\n\t\tprimaryValue, primaryExists := node.Labels[r.primaryKey]\n\t\tsecondaryValue, secondaryExists := node.Labels[r.secondaryKey]\n\n\t\tif !primaryExists {\n\t\t\t// The primary label key does not exist. This should not happen\n\t\t\t// within our supported version skew range, when no external\n\t\t\t// components/factors modifying the node object. Ignore this case.\n\t\t\tcontinue\n\t\t}\n\t\tif secondaryExists \u0026\u0026 primaryValue != secondaryValue {\n\t\t\t// Secondary label exists, but not consistent with the primary\n\t\t\t// label. Need to reconcile.\n\t\t\tlabelsToUpdate[r.secondaryKey] = primaryValue\n\n\t\t} else if !secondaryExists \u0026\u0026 r.ensureSecondaryExists {\n\t\t\t// Apply secondary label based on primary label.\n\t\t\tlabelsToUpdate[r.secondaryKey] = primaryValue\n\t\t}\n\t}\n\n\tif len(labelsToUpdate) == 0 {\n\t\treturn nil\n\t}\n\tif !controllerutil.AddOrUpdateLabelsOnNode(ctx, nc.kubeClient, labelsToUpdate, node) {\n\t\treturn fmt.Errorf(\"failed update labels for node %+v\", node)\n\t}\n\treturn nil\n}","line":{"from":1289,"to":1334}} {"id":100004300,"name":"Len","signature":"func (h TimedQueue) Len() int { return len(h) }","file":"pkg/controller/nodelifecycle/scheduler/rate_limited_queue.go","code":"// Len is the length of the queue.\nfunc (h TimedQueue) Len() int { return len(h) }","line":{"from":56,"to":57}} {"id":100004301,"name":"Less","signature":"func (h TimedQueue) Less(i, j int) bool { return h[i].ProcessAt.Before(h[j].ProcessAt) }","file":"pkg/controller/nodelifecycle/scheduler/rate_limited_queue.go","code":"// Less returns true if queue[i] \u003c queue[j].\nfunc (h TimedQueue) Less(i, j int) bool { return h[i].ProcessAt.Before(h[j].ProcessAt) }","line":{"from":59,"to":60}} {"id":100004302,"name":"Swap","signature":"func (h TimedQueue) Swap(i, j int) { h[i], h[j] = h[j], h[i] }","file":"pkg/controller/nodelifecycle/scheduler/rate_limited_queue.go","code":"// Swap swaps index i and j.\nfunc (h TimedQueue) Swap(i, j int) { h[i], h[j] = h[j], h[i] }","line":{"from":62,"to":63}} {"id":100004303,"name":"Push","signature":"func (h *TimedQueue) Push(x interface{})","file":"pkg/controller/nodelifecycle/scheduler/rate_limited_queue.go","code":"// Push a new TimedValue on to the queue.\nfunc (h *TimedQueue) Push(x interface{}) {\n\t*h = append(*h, x.(*TimedValue))\n}","line":{"from":65,"to":68}} {"id":100004304,"name":"Pop","signature":"func (h *TimedQueue) Pop() interface{}","file":"pkg/controller/nodelifecycle/scheduler/rate_limited_queue.go","code":"// Pop the lowest ProcessAt item.\nfunc (h *TimedQueue) Pop() interface{} {\n\told := *h\n\tn := len(old)\n\tx := old[n-1]\n\t*h = old[0 : n-1]\n\treturn x\n}","line":{"from":70,"to":77}} {"id":100004305,"name":"Add","signature":"func (q *UniqueQueue) Add(value TimedValue) bool","file":"pkg/controller/nodelifecycle/scheduler/rate_limited_queue.go","code":"// Add a new value to the queue if it wasn't added before, or was\n// explicitly removed by the Remove call. Returns true if new value\n// was added.\nfunc (q *UniqueQueue) Add(value TimedValue) bool {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\tif q.set.Has(value.Value) {\n\t\treturn false\n\t}\n\theap.Push(\u0026q.queue, \u0026value)\n\tq.set.Insert(value.Value)\n\treturn true\n}","line":{"from":87,"to":100}} {"id":100004306,"name":"Replace","signature":"func (q *UniqueQueue) Replace(value TimedValue) bool","file":"pkg/controller/nodelifecycle/scheduler/rate_limited_queue.go","code":"// Replace replaces an existing value in the queue if it already\n// exists, otherwise it does nothing. Returns true if the item was\n// found.\nfunc (q *UniqueQueue) Replace(value TimedValue) bool {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\tfor i := range q.queue {\n\t\tif q.queue[i].Value != value.Value {\n\t\t\tcontinue\n\t\t}\n\t\theap.Remove(\u0026q.queue, i)\n\t\theap.Push(\u0026q.queue, \u0026value)\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":102,"to":118}} {"id":100004307,"name":"RemoveFromQueue","signature":"func (q *UniqueQueue) RemoveFromQueue(value string) bool","file":"pkg/controller/nodelifecycle/scheduler/rate_limited_queue.go","code":"// RemoveFromQueue the value from the queue, but keeps it in the set,\n// so it won't be added second time. Returns true if something was\n// removed.\nfunc (q *UniqueQueue) RemoveFromQueue(value string) bool {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\tif !q.set.Has(value) {\n\t\treturn false\n\t}\n\tfor i, val := range q.queue {\n\t\tif val.Value == value {\n\t\t\theap.Remove(\u0026q.queue, i)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":120,"to":137}} {"id":100004308,"name":"Remove","signature":"func (q *UniqueQueue) Remove(value string) bool","file":"pkg/controller/nodelifecycle/scheduler/rate_limited_queue.go","code":"// Remove the value from the queue, so Get() call won't return it, and\n// allow subsequent addition of the given value. If the value is not\n// present does nothing and returns false.\nfunc (q *UniqueQueue) Remove(value string) bool {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\tif !q.set.Has(value) {\n\t\treturn false\n\t}\n\tq.set.Delete(value)\n\tfor i, val := range q.queue {\n\t\tif val.Value == value {\n\t\t\theap.Remove(\u0026q.queue, i)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn true\n}","line":{"from":139,"to":157}} {"id":100004309,"name":"Get","signature":"func (q *UniqueQueue) Get() (TimedValue, bool)","file":"pkg/controller/nodelifecycle/scheduler/rate_limited_queue.go","code":"// Get returns the oldest added value that wasn't returned yet.\nfunc (q *UniqueQueue) Get() (TimedValue, bool) {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\tif len(q.queue) == 0 {\n\t\treturn TimedValue{}, false\n\t}\n\tresult := heap.Pop(\u0026q.queue).(*TimedValue)\n\tq.set.Delete(result.Value)\n\treturn *result, true\n}","line":{"from":159,"to":169}} {"id":100004310,"name":"Head","signature":"func (q *UniqueQueue) Head() (TimedValue, bool)","file":"pkg/controller/nodelifecycle/scheduler/rate_limited_queue.go","code":"// Head returns the oldest added value that wasn't returned yet\n// without removing it.\nfunc (q *UniqueQueue) Head() (TimedValue, bool) {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\tif len(q.queue) == 0 {\n\t\treturn TimedValue{}, false\n\t}\n\tresult := q.queue[0]\n\treturn *result, true\n}","line":{"from":171,"to":181}} {"id":100004311,"name":"Clear","signature":"func (q *UniqueQueue) Clear()","file":"pkg/controller/nodelifecycle/scheduler/rate_limited_queue.go","code":"// Clear removes all items from the queue and duplication preventing\n// set.\nfunc (q *UniqueQueue) Clear() {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\tif q.queue.Len() \u003e 0 {\n\t\tq.queue = make(TimedQueue, 0)\n\t}\n\tif len(q.set) \u003e 0 {\n\t\tq.set = sets.NewString()\n\t}\n}","line":{"from":183,"to":194}} {"id":100004312,"name":"NewRateLimitedTimedQueue","signature":"func NewRateLimitedTimedQueue(limiter flowcontrol.RateLimiter) *RateLimitedTimedQueue","file":"pkg/controller/nodelifecycle/scheduler/rate_limited_queue.go","code":"// NewRateLimitedTimedQueue creates new queue which will use given\n// RateLimiter to oversee execution.\nfunc NewRateLimitedTimedQueue(limiter flowcontrol.RateLimiter) *RateLimitedTimedQueue {\n\treturn \u0026RateLimitedTimedQueue{\n\t\tqueue: UniqueQueue{\n\t\t\tqueue: TimedQueue{},\n\t\t\tset: sets.NewString(),\n\t\t},\n\t\tlimiter: limiter,\n\t}\n}","line":{"from":204,"to":214}} {"id":100004313,"name":"Try","signature":"func (q *RateLimitedTimedQueue) Try(logger klog.Logger, fn ActionFunc)","file":"pkg/controller/nodelifecycle/scheduler/rate_limited_queue.go","code":"// Try processes the queue.Ends prematurely if RateLimiter forbids an\n// action and leak is true. Otherwise, requeues the item to be\n// processed. Each value is processed once if fn returns true,\n// otherwise it is added back to the queue. The returned remaining is\n// used to identify the minimum time to execute the next item in the\n// queue. The same value is processed only once unless Remove is\n// explicitly called on it (it's done by the cancelPodEviction\n// function in NodeController when Node becomes Ready again) TODO:\n// figure out a good way to do garbage collection for all Nodes that\n// were removed from the cluster.\nfunc (q *RateLimitedTimedQueue) Try(logger klog.Logger, fn ActionFunc) {\n\tval, ok := q.queue.Head()\n\tq.limiterLock.Lock()\n\tdefer q.limiterLock.Unlock()\n\tfor ok {\n\t\t// rate limit the queue checking\n\t\tif !q.limiter.TryAccept() {\n\t\t\tlogger.V(10).Info(\"Try rate limited\", \"value\", val)\n\t\t\t// Try again later\n\t\t\tbreak\n\t\t}\n\n\t\tnow := now()\n\t\tif now.Before(val.ProcessAt) {\n\t\t\tbreak\n\t\t}\n\n\t\tif ok, wait := fn(val); !ok {\n\t\t\tval.ProcessAt = now.Add(wait + 1)\n\t\t\tq.queue.Replace(val)\n\t\t} else {\n\t\t\tq.queue.RemoveFromQueue(val.Value)\n\t\t}\n\t\tval, ok = q.queue.Head()\n\t}\n}","line":{"from":221,"to":256}} {"id":100004314,"name":"Add","signature":"func (q *RateLimitedTimedQueue) Add(value string, uid interface{}) bool","file":"pkg/controller/nodelifecycle/scheduler/rate_limited_queue.go","code":"// Add value to the queue to be processed. Won't add the same\n// value(comparison by value) a second time if it was already added\n// and not removed.\nfunc (q *RateLimitedTimedQueue) Add(value string, uid interface{}) bool {\n\tnow := now()\n\treturn q.queue.Add(TimedValue{\n\t\tValue: value,\n\t\tUID: uid,\n\t\tAddedAt: now,\n\t\tProcessAt: now,\n\t})\n}","line":{"from":258,"to":269}} {"id":100004315,"name":"Remove","signature":"func (q *RateLimitedTimedQueue) Remove(value string) bool","file":"pkg/controller/nodelifecycle/scheduler/rate_limited_queue.go","code":"// Remove Node from the Evictor. The Node won't be processed until\n// added again.\nfunc (q *RateLimitedTimedQueue) Remove(value string) bool {\n\treturn q.queue.Remove(value)\n}","line":{"from":271,"to":275}} {"id":100004316,"name":"Clear","signature":"func (q *RateLimitedTimedQueue) Clear()","file":"pkg/controller/nodelifecycle/scheduler/rate_limited_queue.go","code":"// Clear removes all items from the queue\nfunc (q *RateLimitedTimedQueue) Clear() {\n\tq.queue.Clear()\n}","line":{"from":277,"to":280}} {"id":100004317,"name":"SwapLimiter","signature":"func (q *RateLimitedTimedQueue) SwapLimiter(newQPS float32)","file":"pkg/controller/nodelifecycle/scheduler/rate_limited_queue.go","code":"// SwapLimiter safely swaps current limiter for this queue with the\n// passed one if capacities or qps's differ.\nfunc (q *RateLimitedTimedQueue) SwapLimiter(newQPS float32) {\n\tq.limiterLock.Lock()\n\tdefer q.limiterLock.Unlock()\n\tif q.limiter.QPS() == newQPS {\n\t\treturn\n\t}\n\tvar newLimiter flowcontrol.RateLimiter\n\tif newQPS \u003c= 0 {\n\t\tnewLimiter = flowcontrol.NewFakeNeverRateLimiter()\n\t} else {\n\t\tnewLimiter = flowcontrol.NewTokenBucketRateLimiter(newQPS, EvictionRateLimiterBurst)\n\n\t\t// If we're currently waiting on limiter, we drain the new one - this is a good approach when Burst value is 1\n\t\t// TODO: figure out if we need to support higher Burst values and decide on the drain logic, should we keep:\n\t\t// - saturation (percentage of used tokens)\n\t\t// - number of used tokens\n\t\t// - number of available tokens\n\t\t// - something else\n\t\tif q.limiter.TryAccept() == false {\n\t\t\tnewLimiter.TryAccept()\n\t\t}\n\t}\n\tq.limiter.Stop()\n\tq.limiter = newLimiter\n}","line":{"from":282,"to":308}} {"id":100004318,"name":"hash","signature":"func hash(val string, max int) int","file":"pkg/controller/nodelifecycle/scheduler/taint_manager.go","code":"func hash(val string, max int) int {\n\thasher := fnv.New32a()\n\tio.WriteString(hasher, val)\n\treturn int(hasher.Sum32() % uint32(max))\n}","line":{"from":73,"to":77}} {"id":100004319,"name":"deletePodHandler","signature":"func deletePodHandler(c clientset.Interface, emitEventFunc func(types.NamespacedName)) func(ctx context.Context, args *WorkArgs) error","file":"pkg/controller/nodelifecycle/scheduler/taint_manager.go","code":"func deletePodHandler(c clientset.Interface, emitEventFunc func(types.NamespacedName)) func(ctx context.Context, args *WorkArgs) error {\n\treturn func(ctx context.Context, args *WorkArgs) error {\n\t\tns := args.NamespacedName.Namespace\n\t\tname := args.NamespacedName.Name\n\t\tklog.FromContext(ctx).Info(\"NoExecuteTaintManager is deleting pod\", \"pod\", args.NamespacedName.String())\n\t\tif emitEventFunc != nil {\n\t\t\temitEventFunc(args.NamespacedName)\n\t\t}\n\t\tvar err error\n\t\tfor i := 0; i \u003c retries; i++ {\n\t\t\terr = addConditionAndDeletePod(ctx, c, name, ns)\n\t\t\tif err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(10 * time.Millisecond)\n\t\t}\n\t\treturn err\n\t}\n}","line":{"from":104,"to":122}} {"id":100004320,"name":"addConditionAndDeletePod","signature":"func addConditionAndDeletePod(ctx context.Context, c clientset.Interface, name, ns string) (err error)","file":"pkg/controller/nodelifecycle/scheduler/taint_manager.go","code":"func addConditionAndDeletePod(ctx context.Context, c clientset.Interface, name, ns string) (err error) {\n\tif feature.DefaultFeatureGate.Enabled(features.PodDisruptionConditions) {\n\t\tpod, err := c.CoreV1().Pods(ns).Get(ctx, name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpodApply := corev1apply.Pod(pod.Name, pod.Namespace).WithStatus(corev1apply.PodStatus())\n\t\tpodApply.Status.WithConditions(corev1apply.PodCondition().\n\t\t\tWithType(v1.DisruptionTarget).\n\t\t\tWithStatus(v1.ConditionTrue).\n\t\t\tWithReason(\"DeletionByTaintManager\").\n\t\t\tWithMessage(\"Taint manager: deleting due to NoExecute taint\").\n\t\t\tWithLastTransitionTime(metav1.Now()),\n\t\t)\n\t\tif _, err := c.CoreV1().Pods(pod.Namespace).ApplyStatus(ctx, podApply, metav1.ApplyOptions{FieldManager: fieldManager, Force: true}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn c.CoreV1().Pods(ns).Delete(ctx, name, metav1.DeleteOptions{})\n}","line":{"from":124,"to":143}} {"id":100004321,"name":"getNoExecuteTaints","signature":"func getNoExecuteTaints(taints []v1.Taint) []v1.Taint","file":"pkg/controller/nodelifecycle/scheduler/taint_manager.go","code":"func getNoExecuteTaints(taints []v1.Taint) []v1.Taint {\n\tresult := []v1.Taint{}\n\tfor i := range taints {\n\t\tif taints[i].Effect == v1.TaintEffectNoExecute {\n\t\t\tresult = append(result, taints[i])\n\t\t}\n\t}\n\treturn result\n}","line":{"from":145,"to":153}} {"id":100004322,"name":"getMinTolerationTime","signature":"func getMinTolerationTime(tolerations []v1.Toleration) time.Duration","file":"pkg/controller/nodelifecycle/scheduler/taint_manager.go","code":"// getMinTolerationTime returns minimal toleration time from the given slice, or -1 if it's infinite.\nfunc getMinTolerationTime(tolerations []v1.Toleration) time.Duration {\n\tminTolerationTime := int64(math.MaxInt64)\n\tif len(tolerations) == 0 {\n\t\treturn 0\n\t}\n\n\tfor i := range tolerations {\n\t\tif tolerations[i].TolerationSeconds != nil {\n\t\t\ttolerationSeconds := *(tolerations[i].TolerationSeconds)\n\t\t\tif tolerationSeconds \u003c= 0 {\n\t\t\t\treturn 0\n\t\t\t} else if tolerationSeconds \u003c minTolerationTime {\n\t\t\t\tminTolerationTime = tolerationSeconds\n\t\t\t}\n\t\t}\n\t}\n\n\tif minTolerationTime == int64(math.MaxInt64) {\n\t\treturn -1\n\t}\n\treturn time.Duration(minTolerationTime) * time.Second\n}","line":{"from":155,"to":177}} {"id":100004323,"name":"NewNoExecuteTaintManager","signature":"func NewNoExecuteTaintManager(ctx context.Context, c clientset.Interface, podLister corelisters.PodLister, nodeLister corelisters.NodeLister, getPodsAssignedToNode GetPodsByNodeNameFunc) *NoExecuteTaintManager","file":"pkg/controller/nodelifecycle/scheduler/taint_manager.go","code":"// NewNoExecuteTaintManager creates a new NoExecuteTaintManager that will use passed clientset to\n// communicate with the API server.\nfunc NewNoExecuteTaintManager(ctx context.Context, c clientset.Interface, podLister corelisters.PodLister, nodeLister corelisters.NodeLister, getPodsAssignedToNode GetPodsByNodeNameFunc) *NoExecuteTaintManager {\n\teventBroadcaster := record.NewBroadcaster()\n\trecorder := eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"taint-controller\"})\n\n\ttm := \u0026NoExecuteTaintManager{\n\t\tclient: c,\n\t\tbroadcaster: eventBroadcaster,\n\t\trecorder: recorder,\n\t\tpodLister: podLister,\n\t\tnodeLister: nodeLister,\n\t\tgetPodsAssignedToNode: getPodsAssignedToNode,\n\t\ttaintedNodes: make(map[string][]v1.Taint),\n\n\t\tnodeUpdateQueue: workqueue.NewNamed(\"noexec_taint_node\"),\n\t\tpodUpdateQueue: workqueue.NewNamed(\"noexec_taint_pod\"),\n\t}\n\ttm.taintEvictionQueue = CreateWorkerQueue(deletePodHandler(c, tm.emitPodDeletionEvent))\n\n\treturn tm\n}","line":{"from":179,"to":200}} {"id":100004324,"name":"Run","signature":"func (tc *NoExecuteTaintManager) Run(ctx context.Context)","file":"pkg/controller/nodelifecycle/scheduler/taint_manager.go","code":"// Run starts NoExecuteTaintManager which will run in loop until `stopCh` is closed.\nfunc (tc *NoExecuteTaintManager) Run(ctx context.Context) {\n\tdefer utilruntime.HandleCrash()\n\tlogger := klog.FromContext(ctx)\n\tlogger.Info(\"Starting NoExecuteTaintManager\")\n\n\t// Start events processing pipeline.\n\ttc.broadcaster.StartStructuredLogging(0)\n\tif tc.client != nil {\n\t\tlogger.Info(\"Sending events to api server\")\n\t\ttc.broadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: tc.client.CoreV1().Events(\"\")})\n\t} else {\n\t\tlogger.Error(nil, \"kubeClient is nil when starting NodeController\")\n\t\tklog.FlushAndExit(klog.ExitFlushTimeout, 1)\n\t}\n\tdefer tc.broadcaster.Shutdown()\n\n\tdefer tc.nodeUpdateQueue.ShutDown()\n\tdefer tc.podUpdateQueue.ShutDown()\n\n\tfor i := 0; i \u003c UpdateWorkerSize; i++ {\n\t\ttc.nodeUpdateChannels = append(tc.nodeUpdateChannels, make(chan nodeUpdateItem, NodeUpdateChannelSize))\n\t\ttc.podUpdateChannels = append(tc.podUpdateChannels, make(chan podUpdateItem, podUpdateChannelSize))\n\t}\n\n\t// Functions that are responsible for taking work items out of the workqueues and putting them\n\t// into channels.\n\tgo func(stopCh \u003c-chan struct{}) {\n\t\tfor {\n\t\t\titem, shutdown := tc.nodeUpdateQueue.Get()\n\t\t\tif shutdown {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tnodeUpdate := item.(nodeUpdateItem)\n\t\t\thash := hash(nodeUpdate.nodeName, UpdateWorkerSize)\n\t\t\tselect {\n\t\t\tcase \u003c-stopCh:\n\t\t\t\ttc.nodeUpdateQueue.Done(item)\n\t\t\t\treturn\n\t\t\tcase tc.nodeUpdateChannels[hash] \u003c- nodeUpdate:\n\t\t\t\t// tc.nodeUpdateQueue.Done is called by the nodeUpdateChannels worker\n\t\t\t}\n\t\t}\n\t}(ctx.Done())\n\n\tgo func(stopCh \u003c-chan struct{}) {\n\t\tfor {\n\t\t\titem, shutdown := tc.podUpdateQueue.Get()\n\t\t\tif shutdown {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// The fact that pods are processed by the same worker as nodes is used to avoid races\n\t\t\t// between node worker setting tc.taintedNodes and pod worker reading this to decide\n\t\t\t// whether to delete pod.\n\t\t\t// It's possible that even without this assumption this code is still correct.\n\t\t\tpodUpdate := item.(podUpdateItem)\n\t\t\thash := hash(podUpdate.nodeName, UpdateWorkerSize)\n\t\t\tselect {\n\t\t\tcase \u003c-stopCh:\n\t\t\t\ttc.podUpdateQueue.Done(item)\n\t\t\t\treturn\n\t\t\tcase tc.podUpdateChannels[hash] \u003c- podUpdate:\n\t\t\t\t// tc.podUpdateQueue.Done is called by the podUpdateChannels worker\n\t\t\t}\n\t\t}\n\t}(ctx.Done())\n\n\twg := sync.WaitGroup{}\n\twg.Add(UpdateWorkerSize)\n\tfor i := 0; i \u003c UpdateWorkerSize; i++ {\n\t\tgo tc.worker(ctx, i, wg.Done, ctx.Done())\n\t}\n\twg.Wait()\n}","line":{"from":202,"to":275}} {"id":100004325,"name":"worker","signature":"func (tc *NoExecuteTaintManager) worker(ctx context.Context, worker int, done func(), stopCh \u003c-chan struct{})","file":"pkg/controller/nodelifecycle/scheduler/taint_manager.go","code":"func (tc *NoExecuteTaintManager) worker(ctx context.Context, worker int, done func(), stopCh \u003c-chan struct{}) {\n\tdefer done()\n\n\t// When processing events we want to prioritize Node updates over Pod updates,\n\t// as NodeUpdates that interest NoExecuteTaintManager should be handled as soon as possible -\n\t// we don't want user (or system) to wait until PodUpdate queue is drained before it can\n\t// start evicting Pods from tainted Nodes.\n\tfor {\n\t\tselect {\n\t\tcase \u003c-stopCh:\n\t\t\treturn\n\t\tcase nodeUpdate := \u003c-tc.nodeUpdateChannels[worker]:\n\t\t\ttc.handleNodeUpdate(ctx, nodeUpdate)\n\t\t\ttc.nodeUpdateQueue.Done(nodeUpdate)\n\t\tcase podUpdate := \u003c-tc.podUpdateChannels[worker]:\n\t\t\t// If we found a Pod update we need to empty Node queue first.\n\t\tpriority:\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase nodeUpdate := \u003c-tc.nodeUpdateChannels[worker]:\n\t\t\t\t\ttc.handleNodeUpdate(ctx, nodeUpdate)\n\t\t\t\t\ttc.nodeUpdateQueue.Done(nodeUpdate)\n\t\t\t\tdefault:\n\t\t\t\t\tbreak priority\n\t\t\t\t}\n\t\t\t}\n\t\t\t// After Node queue is emptied we process podUpdate.\n\t\t\ttc.handlePodUpdate(ctx, podUpdate)\n\t\t\ttc.podUpdateQueue.Done(podUpdate)\n\t\t}\n\t}\n}","line":{"from":277,"to":308}} {"id":100004326,"name":"PodUpdated","signature":"func (tc *NoExecuteTaintManager) PodUpdated(oldPod *v1.Pod, newPod *v1.Pod)","file":"pkg/controller/nodelifecycle/scheduler/taint_manager.go","code":"// PodUpdated is used to notify NoExecuteTaintManager about Pod changes.\nfunc (tc *NoExecuteTaintManager) PodUpdated(oldPod *v1.Pod, newPod *v1.Pod) {\n\tpodName := \"\"\n\tpodNamespace := \"\"\n\tnodeName := \"\"\n\toldTolerations := []v1.Toleration{}\n\tif oldPod != nil {\n\t\tpodName = oldPod.Name\n\t\tpodNamespace = oldPod.Namespace\n\t\tnodeName = oldPod.Spec.NodeName\n\t\toldTolerations = oldPod.Spec.Tolerations\n\t}\n\tnewTolerations := []v1.Toleration{}\n\tif newPod != nil {\n\t\tpodName = newPod.Name\n\t\tpodNamespace = newPod.Namespace\n\t\tnodeName = newPod.Spec.NodeName\n\t\tnewTolerations = newPod.Spec.Tolerations\n\t}\n\n\tif oldPod != nil \u0026\u0026 newPod != nil \u0026\u0026 helper.Semantic.DeepEqual(oldTolerations, newTolerations) \u0026\u0026 oldPod.Spec.NodeName == newPod.Spec.NodeName {\n\t\treturn\n\t}\n\tupdateItem := podUpdateItem{\n\t\tpodName: podName,\n\t\tpodNamespace: podNamespace,\n\t\tnodeName: nodeName,\n\t}\n\n\ttc.podUpdateQueue.Add(updateItem)\n}","line":{"from":310,"to":340}} {"id":100004327,"name":"NodeUpdated","signature":"func (tc *NoExecuteTaintManager) NodeUpdated(oldNode *v1.Node, newNode *v1.Node)","file":"pkg/controller/nodelifecycle/scheduler/taint_manager.go","code":"// NodeUpdated is used to notify NoExecuteTaintManager about Node changes.\nfunc (tc *NoExecuteTaintManager) NodeUpdated(oldNode *v1.Node, newNode *v1.Node) {\n\tnodeName := \"\"\n\toldTaints := []v1.Taint{}\n\tif oldNode != nil {\n\t\tnodeName = oldNode.Name\n\t\toldTaints = getNoExecuteTaints(oldNode.Spec.Taints)\n\t}\n\n\tnewTaints := []v1.Taint{}\n\tif newNode != nil {\n\t\tnodeName = newNode.Name\n\t\tnewTaints = getNoExecuteTaints(newNode.Spec.Taints)\n\t}\n\n\tif oldNode != nil \u0026\u0026 newNode != nil \u0026\u0026 helper.Semantic.DeepEqual(oldTaints, newTaints) {\n\t\treturn\n\t}\n\tupdateItem := nodeUpdateItem{\n\t\tnodeName: nodeName,\n\t}\n\n\ttc.nodeUpdateQueue.Add(updateItem)\n}","line":{"from":342,"to":365}} {"id":100004328,"name":"cancelWorkWithEvent","signature":"func (tc *NoExecuteTaintManager) cancelWorkWithEvent(logger klog.Logger, nsName types.NamespacedName)","file":"pkg/controller/nodelifecycle/scheduler/taint_manager.go","code":"func (tc *NoExecuteTaintManager) cancelWorkWithEvent(logger klog.Logger, nsName types.NamespacedName) {\n\tif tc.taintEvictionQueue.CancelWork(logger, nsName.String()) {\n\t\ttc.emitCancelPodDeletionEvent(nsName)\n\t}\n}","line":{"from":367,"to":371}} {"id":100004329,"name":"processPodOnNode","signature":"func (tc *NoExecuteTaintManager) processPodOnNode(","file":"pkg/controller/nodelifecycle/scheduler/taint_manager.go","code":"func (tc *NoExecuteTaintManager) processPodOnNode(\n\tctx context.Context,\n\tpodNamespacedName types.NamespacedName,\n\tnodeName string,\n\ttolerations []v1.Toleration,\n\ttaints []v1.Taint,\n\tnow time.Time,\n) {\n\tlogger := klog.FromContext(ctx)\n\tif len(taints) == 0 {\n\t\ttc.cancelWorkWithEvent(logger, podNamespacedName)\n\t}\n\tallTolerated, usedTolerations := v1helper.GetMatchingTolerations(taints, tolerations)\n\tif !allTolerated {\n\t\tlogger.V(2).Info(\"Not all taints are tolerated after update for pod on node\", \"pod\", podNamespacedName.String(), \"node\", klog.KRef(\"\", nodeName))\n\t\t// We're canceling scheduled work (if any), as we're going to delete the Pod right away.\n\t\ttc.cancelWorkWithEvent(logger, podNamespacedName)\n\t\ttc.taintEvictionQueue.AddWork(ctx, NewWorkArgs(podNamespacedName.Name, podNamespacedName.Namespace), time.Now(), time.Now())\n\t\treturn\n\t}\n\tminTolerationTime := getMinTolerationTime(usedTolerations)\n\t// getMinTolerationTime returns negative value to denote infinite toleration.\n\tif minTolerationTime \u003c 0 {\n\t\tlogger.V(4).Info(\"Current tolerations for pod tolerate forever, cancelling any scheduled deletion\", \"pod\", podNamespacedName.String())\n\t\ttc.cancelWorkWithEvent(logger, podNamespacedName)\n\t\treturn\n\t}\n\n\tstartTime := now\n\ttriggerTime := startTime.Add(minTolerationTime)\n\tscheduledEviction := tc.taintEvictionQueue.GetWorkerUnsafe(podNamespacedName.String())\n\tif scheduledEviction != nil {\n\t\tstartTime = scheduledEviction.CreatedAt\n\t\tif startTime.Add(minTolerationTime).Before(triggerTime) {\n\t\t\treturn\n\t\t}\n\t\ttc.cancelWorkWithEvent(logger, podNamespacedName)\n\t}\n\ttc.taintEvictionQueue.AddWork(ctx, NewWorkArgs(podNamespacedName.Name, podNamespacedName.Namespace), startTime, triggerTime)\n}","line":{"from":373,"to":412}} {"id":100004330,"name":"handlePodUpdate","signature":"func (tc *NoExecuteTaintManager) handlePodUpdate(ctx context.Context, podUpdate podUpdateItem)","file":"pkg/controller/nodelifecycle/scheduler/taint_manager.go","code":"func (tc *NoExecuteTaintManager) handlePodUpdate(ctx context.Context, podUpdate podUpdateItem) {\n\tpod, err := tc.podLister.Pods(podUpdate.podNamespace).Get(podUpdate.podName)\n\tlogger := klog.FromContext(ctx)\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\t// Delete\n\t\t\tpodNamespacedName := types.NamespacedName{Namespace: podUpdate.podNamespace, Name: podUpdate.podName}\n\t\t\tlogger.V(4).Info(\"Noticed pod deletion\", \"pod\", podNamespacedName)\n\t\t\ttc.cancelWorkWithEvent(logger, podNamespacedName)\n\t\t\treturn\n\t\t}\n\t\tutilruntime.HandleError(fmt.Errorf(\"could not get pod %s/%s: %v\", podUpdate.podName, podUpdate.podNamespace, err))\n\t\treturn\n\t}\n\n\t// We key the workqueue and shard workers by nodeName. If we don't match the current state we should not be the one processing the current object.\n\tif pod.Spec.NodeName != podUpdate.nodeName {\n\t\treturn\n\t}\n\n\t// Create or Update\n\tpodNamespacedName := types.NamespacedName{Namespace: pod.Namespace, Name: pod.Name}\n\tlogger.V(4).Info(\"Noticed pod update\", \"pod\", podNamespacedName)\n\tnodeName := pod.Spec.NodeName\n\tif nodeName == \"\" {\n\t\treturn\n\t}\n\ttaints, ok := func() ([]v1.Taint, bool) {\n\t\ttc.taintedNodesLock.Lock()\n\t\tdefer tc.taintedNodesLock.Unlock()\n\t\ttaints, ok := tc.taintedNodes[nodeName]\n\t\treturn taints, ok\n\t}()\n\t// It's possible that Node was deleted, or Taints were removed before, which triggered\n\t// eviction cancelling if it was needed.\n\tif !ok {\n\t\treturn\n\t}\n\ttc.processPodOnNode(ctx, podNamespacedName, nodeName, pod.Spec.Tolerations, taints, time.Now())\n}","line":{"from":414,"to":453}} {"id":100004331,"name":"handleNodeUpdate","signature":"func (tc *NoExecuteTaintManager) handleNodeUpdate(ctx context.Context, nodeUpdate nodeUpdateItem)","file":"pkg/controller/nodelifecycle/scheduler/taint_manager.go","code":"func (tc *NoExecuteTaintManager) handleNodeUpdate(ctx context.Context, nodeUpdate nodeUpdateItem) {\n\tnode, err := tc.nodeLister.Get(nodeUpdate.nodeName)\n\tlogger := klog.FromContext(ctx)\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\t// Delete\n\t\t\tlogger.V(4).Info(\"Noticed node deletion\", \"node\", klog.KRef(\"\", nodeUpdate.nodeName))\n\t\t\ttc.taintedNodesLock.Lock()\n\t\t\tdefer tc.taintedNodesLock.Unlock()\n\t\t\tdelete(tc.taintedNodes, nodeUpdate.nodeName)\n\t\t\treturn\n\t\t}\n\t\tutilruntime.HandleError(fmt.Errorf(\"cannot get node %s: %v\", nodeUpdate.nodeName, err))\n\t\treturn\n\t}\n\n\t// Create or Update\n\tlogger.V(4).Info(\"Noticed node update\", \"node\", klog.KObj(node))\n\ttaints := getNoExecuteTaints(node.Spec.Taints)\n\tfunc() {\n\t\ttc.taintedNodesLock.Lock()\n\t\tdefer tc.taintedNodesLock.Unlock()\n\t\tlogger.V(4).Info(\"Updating known taints on node\", \"node\", klog.KObj(node), \"taints\", taints)\n\t\tif len(taints) == 0 {\n\t\t\tdelete(tc.taintedNodes, node.Name)\n\t\t} else {\n\t\t\ttc.taintedNodes[node.Name] = taints\n\t\t}\n\t}()\n\n\t// This is critical that we update tc.taintedNodes before we call getPodsAssignedToNode:\n\t// getPodsAssignedToNode can be delayed as long as all future updates to pods will call\n\t// tc.PodUpdated which will use tc.taintedNodes to potentially delete delayed pods.\n\tpods, err := tc.getPodsAssignedToNode(node.Name)\n\tif err != nil {\n\t\tlogger.Error(err, \"Failed to get pods assigned to node\", \"node\", klog.KObj(node))\n\t\treturn\n\t}\n\tif len(pods) == 0 {\n\t\treturn\n\t}\n\t// Short circuit, to make this controller a bit faster.\n\tif len(taints) == 0 {\n\t\tlogger.V(4).Info(\"All taints were removed from the node. Cancelling all evictions...\", \"node\", klog.KObj(node))\n\t\tfor i := range pods {\n\t\t\ttc.cancelWorkWithEvent(logger, types.NamespacedName{Namespace: pods[i].Namespace, Name: pods[i].Name})\n\t\t}\n\t\treturn\n\t}\n\n\tnow := time.Now()\n\tfor _, pod := range pods {\n\t\tpodNamespacedName := types.NamespacedName{Namespace: pod.Namespace, Name: pod.Name}\n\t\ttc.processPodOnNode(ctx, podNamespacedName, node.Name, pod.Spec.Tolerations, taints, now)\n\t}\n}","line":{"from":455,"to":510}} {"id":100004332,"name":"emitPodDeletionEvent","signature":"func (tc *NoExecuteTaintManager) emitPodDeletionEvent(nsName types.NamespacedName)","file":"pkg/controller/nodelifecycle/scheduler/taint_manager.go","code":"func (tc *NoExecuteTaintManager) emitPodDeletionEvent(nsName types.NamespacedName) {\n\tif tc.recorder == nil {\n\t\treturn\n\t}\n\tref := \u0026v1.ObjectReference{\n\t\tKind: \"Pod\",\n\t\tName: nsName.Name,\n\t\tNamespace: nsName.Namespace,\n\t}\n\ttc.recorder.Eventf(ref, v1.EventTypeNormal, \"TaintManagerEviction\", \"Marking for deletion Pod %s\", nsName.String())\n}","line":{"from":512,"to":522}} {"id":100004333,"name":"emitCancelPodDeletionEvent","signature":"func (tc *NoExecuteTaintManager) emitCancelPodDeletionEvent(nsName types.NamespacedName)","file":"pkg/controller/nodelifecycle/scheduler/taint_manager.go","code":"func (tc *NoExecuteTaintManager) emitCancelPodDeletionEvent(nsName types.NamespacedName) {\n\tif tc.recorder == nil {\n\t\treturn\n\t}\n\tref := \u0026v1.ObjectReference{\n\t\tKind: \"Pod\",\n\t\tName: nsName.Name,\n\t\tNamespace: nsName.Namespace,\n\t}\n\ttc.recorder.Eventf(ref, v1.EventTypeNormal, \"TaintManagerEviction\", \"Cancelling deletion of Pod %s\", nsName.String())\n}","line":{"from":524,"to":534}} {"id":100004334,"name":"KeyFromWorkArgs","signature":"func (w *WorkArgs) KeyFromWorkArgs() string","file":"pkg/controller/nodelifecycle/scheduler/timed_workers.go","code":"// KeyFromWorkArgs creates a key for the given `WorkArgs`\nfunc (w *WorkArgs) KeyFromWorkArgs() string {\n\treturn w.NamespacedName.String()\n}","line":{"from":34,"to":37}} {"id":100004335,"name":"NewWorkArgs","signature":"func NewWorkArgs(name, namespace string) *WorkArgs","file":"pkg/controller/nodelifecycle/scheduler/timed_workers.go","code":"// NewWorkArgs is a helper function to create new `WorkArgs`\nfunc NewWorkArgs(name, namespace string) *WorkArgs {\n\treturn \u0026WorkArgs{types.NamespacedName{Namespace: namespace, Name: name}}\n}","line":{"from":39,"to":42}} {"id":100004336,"name":"createWorker","signature":"func createWorker(ctx context.Context, args *WorkArgs, createdAt time.Time, fireAt time.Time, f func(ctx context.Context, args *WorkArgs) error, clock clock.WithDelayedExecution) *TimedWorker","file":"pkg/controller/nodelifecycle/scheduler/timed_workers.go","code":"// createWorker creates a TimedWorker that will execute `f` not earlier than `fireAt`.\nfunc createWorker(ctx context.Context, args *WorkArgs, createdAt time.Time, fireAt time.Time, f func(ctx context.Context, args *WorkArgs) error, clock clock.WithDelayedExecution) *TimedWorker {\n\tdelay := fireAt.Sub(createdAt)\n\tlogger := klog.FromContext(ctx)\n\tfWithErrorLogging := func() {\n\t\terr := f(ctx, args)\n\t\tif err != nil {\n\t\t\tlogger.Error(err, \"NodeLifecycle: timed worker failed\")\n\t\t}\n\t}\n\tif delay \u003c= 0 {\n\t\tgo fWithErrorLogging()\n\t\treturn nil\n\t}\n\ttimer := clock.AfterFunc(delay, fWithErrorLogging)\n\treturn \u0026TimedWorker{\n\t\tWorkItem: args,\n\t\tCreatedAt: createdAt,\n\t\tFireAt: fireAt,\n\t\tTimer: timer,\n\t}\n}","line":{"from":52,"to":73}} {"id":100004337,"name":"Cancel","signature":"func (w *TimedWorker) Cancel()","file":"pkg/controller/nodelifecycle/scheduler/timed_workers.go","code":"// Cancel cancels the execution of function by the `TimedWorker`\nfunc (w *TimedWorker) Cancel() {\n\tif w != nil {\n\t\tw.Timer.Stop()\n\t}\n}","line":{"from":75,"to":80}} {"id":100004338,"name":"CreateWorkerQueue","signature":"func CreateWorkerQueue(f func(ctx context.Context, args *WorkArgs) error) *TimedWorkerQueue","file":"pkg/controller/nodelifecycle/scheduler/timed_workers.go","code":"// CreateWorkerQueue creates a new TimedWorkerQueue for workers that will execute\n// given function `f`.\nfunc CreateWorkerQueue(f func(ctx context.Context, args *WorkArgs) error) *TimedWorkerQueue {\n\treturn \u0026TimedWorkerQueue{\n\t\tworkers: make(map[string]*TimedWorker),\n\t\tworkFunc: f,\n\t\tclock: clock.RealClock{},\n\t}\n}","line":{"from":91,"to":99}} {"id":100004339,"name":"getWrappedWorkerFunc","signature":"func (q *TimedWorkerQueue) getWrappedWorkerFunc(key string) func(ctx context.Context, args *WorkArgs) error","file":"pkg/controller/nodelifecycle/scheduler/timed_workers.go","code":"func (q *TimedWorkerQueue) getWrappedWorkerFunc(key string) func(ctx context.Context, args *WorkArgs) error {\n\treturn func(ctx context.Context, args *WorkArgs) error {\n\t\terr := q.workFunc(ctx, args)\n\t\tq.Lock()\n\t\tdefer q.Unlock()\n\t\tif err == nil {\n\t\t\t// To avoid duplicated calls we keep the key in the queue, to prevent\n\t\t\t// subsequent additions.\n\t\t\tq.workers[key] = nil\n\t\t} else {\n\t\t\tdelete(q.workers, key)\n\t\t}\n\t\treturn err\n\t}\n}","line":{"from":101,"to":115}} {"id":100004340,"name":"AddWork","signature":"func (q *TimedWorkerQueue) AddWork(ctx context.Context, args *WorkArgs, createdAt time.Time, fireAt time.Time)","file":"pkg/controller/nodelifecycle/scheduler/timed_workers.go","code":"// AddWork adds a work to the WorkerQueue which will be executed not earlier than `fireAt`.\nfunc (q *TimedWorkerQueue) AddWork(ctx context.Context, args *WorkArgs, createdAt time.Time, fireAt time.Time) {\n\tkey := args.KeyFromWorkArgs()\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"Adding TimedWorkerQueue item and to be fired at firedTime\", \"item\", key, \"createTime\", createdAt, \"firedTime\", fireAt)\n\n\tq.Lock()\n\tdefer q.Unlock()\n\tif _, exists := q.workers[key]; exists {\n\t\tlogger.Info(\"Trying to add already existing work, skipping\", \"args\", args)\n\t\treturn\n\t}\n\tworker := createWorker(ctx, args, createdAt, fireAt, q.getWrappedWorkerFunc(key), q.clock)\n\tq.workers[key] = worker\n}","line":{"from":117,"to":131}} {"id":100004341,"name":"CancelWork","signature":"func (q *TimedWorkerQueue) CancelWork(logger klog.Logger, key string) bool","file":"pkg/controller/nodelifecycle/scheduler/timed_workers.go","code":"// CancelWork removes scheduled function execution from the queue. Returns true if work was cancelled.\nfunc (q *TimedWorkerQueue) CancelWork(logger klog.Logger, key string) bool {\n\tq.Lock()\n\tdefer q.Unlock()\n\tworker, found := q.workers[key]\n\tresult := false\n\tif found {\n\t\tlogger.V(4).Info(\"Cancelling TimedWorkerQueue item\", \"item\", key, \"time\", time.Now())\n\t\tif worker != nil {\n\t\t\tresult = true\n\t\t\tworker.Cancel()\n\t\t}\n\t\tdelete(q.workers, key)\n\t}\n\treturn result\n}","line":{"from":133,"to":148}} {"id":100004342,"name":"GetWorkerUnsafe","signature":"func (q *TimedWorkerQueue) GetWorkerUnsafe(key string) *TimedWorker","file":"pkg/controller/nodelifecycle/scheduler/timed_workers.go","code":"// GetWorkerUnsafe returns a TimedWorker corresponding to the given key.\n// Unsafe method - workers have attached goroutines which can fire after this function is called.\nfunc (q *TimedWorkerQueue) GetWorkerUnsafe(key string) *TimedWorker {\n\tq.Lock()\n\tdefer q.Unlock()\n\treturn q.workers[key]\n}","line":{"from":150,"to":156}} {"id":100004343,"name":"Convert_config_HPAControllerConfiguration_To_v1alpha1_HPAControllerConfiguration","signature":"func Convert_config_HPAControllerConfiguration_To_v1alpha1_HPAControllerConfiguration(in *config.HPAControllerConfiguration, out *v1alpha1.HPAControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/podautoscaler/config/v1alpha1/conversion.go","code":"// Convert_config_HPAControllerConfiguration_To_v1alpha1_HPAControllerConfiguration is an autogenerated conversion function.\nfunc Convert_config_HPAControllerConfiguration_To_v1alpha1_HPAControllerConfiguration(in *config.HPAControllerConfiguration, out *v1alpha1.HPAControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_HPAControllerConfiguration_To_v1alpha1_HPAControllerConfiguration(in, out, s)\n}","line":{"from":32,"to":35}} {"id":100004344,"name":"Convert_v1alpha1_HPAControllerConfiguration_To_config_HPAControllerConfiguration","signature":"func Convert_v1alpha1_HPAControllerConfiguration_To_config_HPAControllerConfiguration(in *v1alpha1.HPAControllerConfiguration, out *config.HPAControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/podautoscaler/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_HPAControllerConfiguration_To_config_HPAControllerConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_HPAControllerConfiguration_To_config_HPAControllerConfiguration(in *v1alpha1.HPAControllerConfiguration, out *config.HPAControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_HPAControllerConfiguration_To_config_HPAControllerConfiguration(in, out, s)\n}","line":{"from":37,"to":40}} {"id":100004345,"name":"RecommendedDefaultHPAControllerConfiguration","signature":"func RecommendedDefaultHPAControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.HPAControllerConfiguration)","file":"pkg/controller/podautoscaler/config/v1alpha1/defaults.go","code":"// RecommendedDefaultHPAControllerConfiguration defaults a pointer to a\n// HPAControllerConfiguration struct. This will set the recommended default\n// values, but they may be subject to change between API versions. This function\n// is intentionally not registered in the scheme as a \"normal\" `SetDefaults_Foo`\n// function to allow consumers of this type to set whatever defaults for their\n// embedded configs. Forcing consumers to use these defaults would be problematic\n// as defaulting in the scheme is done as part of the conversion, and there would\n// be no easy way to opt-out. Instead, if you want to use this defaulting method\n// run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDefaultHPAControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.HPAControllerConfiguration) {\n\tzero := metav1.Duration{}\n\tif obj.ConcurrentHorizontalPodAutoscalerSyncs == 0 {\n\t\tobj.ConcurrentHorizontalPodAutoscalerSyncs = 5\n\t}\n\tif obj.HorizontalPodAutoscalerSyncPeriod == zero {\n\t\tobj.HorizontalPodAutoscalerSyncPeriod = metav1.Duration{Duration: 15 * time.Second}\n\t}\n\tif obj.HorizontalPodAutoscalerUpscaleForbiddenWindow == zero {\n\t\tobj.HorizontalPodAutoscalerUpscaleForbiddenWindow = metav1.Duration{Duration: 3 * time.Minute}\n\t}\n\tif obj.HorizontalPodAutoscalerDownscaleStabilizationWindow == zero {\n\t\tobj.HorizontalPodAutoscalerDownscaleStabilizationWindow = metav1.Duration{Duration: 5 * time.Minute}\n\t}\n\tif obj.HorizontalPodAutoscalerCPUInitializationPeriod == zero {\n\t\tobj.HorizontalPodAutoscalerCPUInitializationPeriod = metav1.Duration{Duration: 5 * time.Minute}\n\t}\n\tif obj.HorizontalPodAutoscalerInitialReadinessDelay == zero {\n\t\tobj.HorizontalPodAutoscalerInitialReadinessDelay = metav1.Duration{Duration: 30 * time.Second}\n\t}\n\tif obj.HorizontalPodAutoscalerDownscaleForbiddenWindow == zero {\n\t\tobj.HorizontalPodAutoscalerDownscaleForbiddenWindow = metav1.Duration{Duration: 5 * time.Minute}\n\t}\n\tif obj.HorizontalPodAutoscalerTolerance == 0 {\n\t\tobj.HorizontalPodAutoscalerTolerance = 0.1\n\t}\n}","line":{"from":26,"to":61}} {"id":100004346,"name":"NewHorizontalController","signature":"func NewHorizontalController(","file":"pkg/controller/podautoscaler/horizontal.go","code":"// NewHorizontalController creates a new HorizontalController.\nfunc NewHorizontalController(\n\tevtNamespacer v1core.EventsGetter,\n\tscaleNamespacer scaleclient.ScalesGetter,\n\thpaNamespacer autoscalingclient.HorizontalPodAutoscalersGetter,\n\tmapper apimeta.RESTMapper,\n\tmetricsClient metricsclient.MetricsClient,\n\thpaInformer autoscalinginformers.HorizontalPodAutoscalerInformer,\n\tpodInformer coreinformers.PodInformer,\n\tresyncPeriod time.Duration,\n\tdownscaleStabilisationWindow time.Duration,\n\ttolerance float64,\n\tcpuInitializationPeriod,\n\tdelayOfInitialReadinessStatus time.Duration,\n\tcontainerResourceMetricsEnabled bool,\n) *HorizontalController {\n\tbroadcaster := record.NewBroadcaster()\n\tbroadcaster.StartStructuredLogging(0)\n\tbroadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: evtNamespacer.Events(\"\")})\n\trecorder := broadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"horizontal-pod-autoscaler\"})\n\n\thpaController := \u0026HorizontalController{\n\t\teventRecorder: recorder,\n\t\tscaleNamespacer: scaleNamespacer,\n\t\thpaNamespacer: hpaNamespacer,\n\t\tdownscaleStabilisationWindow: downscaleStabilisationWindow,\n\t\tmonitor: monitor.New(),\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(NewDefaultHPARateLimiter(resyncPeriod), \"horizontalpodautoscaler\"),\n\t\tmapper: mapper,\n\t\trecommendations: map[string][]timestampedRecommendation{},\n\t\trecommendationsLock: sync.Mutex{},\n\t\tscaleUpEvents: map[string][]timestampedScaleEvent{},\n\t\tscaleUpEventsLock: sync.RWMutex{},\n\t\tscaleDownEvents: map[string][]timestampedScaleEvent{},\n\t\tscaleDownEventsLock: sync.RWMutex{},\n\t\thpaSelectors: selectors.NewBiMultimap(),\n\t\tcontainerResourceMetricsEnabled: containerResourceMetricsEnabled,\n\t}\n\n\thpaInformer.Informer().AddEventHandlerWithResyncPeriod(\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: hpaController.enqueueHPA,\n\t\t\tUpdateFunc: hpaController.updateHPA,\n\t\t\tDeleteFunc: hpaController.deleteHPA,\n\t\t},\n\t\tresyncPeriod,\n\t)\n\thpaController.hpaLister = hpaInformer.Lister()\n\thpaController.hpaListerSynced = hpaInformer.Informer().HasSynced\n\n\thpaController.podLister = podInformer.Lister()\n\thpaController.podListerSynced = podInformer.Informer().HasSynced\n\n\treplicaCalc := NewReplicaCalculator(\n\t\tmetricsClient,\n\t\thpaController.podLister,\n\t\ttolerance,\n\t\tcpuInitializationPeriod,\n\t\tdelayOfInitialReadinessStatus,\n\t)\n\thpaController.replicaCalc = replicaCalc\n\n\tmonitor.Register()\n\n\treturn hpaController\n}","line":{"from":127,"to":192}} {"id":100004347,"name":"Run","signature":"func (a *HorizontalController) Run(ctx context.Context, workers int)","file":"pkg/controller/podautoscaler/horizontal.go","code":"// Run begins watching and syncing.\nfunc (a *HorizontalController) Run(ctx context.Context, workers int) {\n\tdefer utilruntime.HandleCrash()\n\tdefer a.queue.ShutDown()\n\n\tlogger := klog.FromContext(ctx)\n\tlogger.Info(\"Starting HPA controller\")\n\tdefer logger.Info(\"Shutting down HPA controller\")\n\n\tif !cache.WaitForNamedCacheSync(\"HPA\", ctx.Done(), a.hpaListerSynced, a.podListerSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.UntilWithContext(ctx, a.worker, time.Second)\n\t}\n\n\t\u003c-ctx.Done()\n}","line":{"from":194,"to":212}} {"id":100004348,"name":"updateHPA","signature":"func (a *HorizontalController) updateHPA(old, cur interface{})","file":"pkg/controller/podautoscaler/horizontal.go","code":"// obj could be an *v1.HorizontalPodAutoscaler, or a DeletionFinalStateUnknown marker item.\nfunc (a *HorizontalController) updateHPA(old, cur interface{}) {\n\ta.enqueueHPA(cur)\n}","line":{"from":214,"to":217}} {"id":100004349,"name":"enqueueHPA","signature":"func (a *HorizontalController) enqueueHPA(obj interface{})","file":"pkg/controller/podautoscaler/horizontal.go","code":"// obj could be an *v1.HorizontalPodAutoscaler, or a DeletionFinalStateUnknown marker item.\nfunc (a *HorizontalController) enqueueHPA(obj interface{}) {\n\tkey, err := controller.KeyFunc(obj)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get key for object %+v: %v\", obj, err))\n\t\treturn\n\t}\n\n\t// Requests are always added to queue with resyncPeriod delay. If there's already\n\t// request for the HPA in the queue then a new request is always dropped. Requests spend resync\n\t// interval in queue so HPAs are processed every resync interval.\n\ta.queue.AddRateLimited(key)\n\n\t// Register HPA in the hpaSelectors map if it's not present yet. Attaching the Nothing selector\n\t// that does not select objects. The actual selector is going to be updated\n\t// when it's available during the autoscaler reconciliation.\n\ta.hpaSelectorsMux.Lock()\n\tdefer a.hpaSelectorsMux.Unlock()\n\tif hpaKey := selectors.Parse(key); !a.hpaSelectors.SelectorExists(hpaKey) {\n\t\ta.hpaSelectors.PutSelector(hpaKey, labels.Nothing())\n\t}\n}","line":{"from":219,"to":240}} {"id":100004350,"name":"deleteHPA","signature":"func (a *HorizontalController) deleteHPA(obj interface{})","file":"pkg/controller/podautoscaler/horizontal.go","code":"func (a *HorizontalController) deleteHPA(obj interface{}) {\n\tkey, err := controller.KeyFunc(obj)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get key for object %+v: %v\", obj, err))\n\t\treturn\n\t}\n\n\t// TODO: could we leak if we fail to get the key?\n\ta.queue.Forget(key)\n\n\t// Remove HPA and attached selector.\n\ta.hpaSelectorsMux.Lock()\n\tdefer a.hpaSelectorsMux.Unlock()\n\ta.hpaSelectors.DeleteSelector(selectors.Parse(key))\n}","line":{"from":242,"to":256}} {"id":100004351,"name":"worker","signature":"func (a *HorizontalController) worker(ctx context.Context)","file":"pkg/controller/podautoscaler/horizontal.go","code":"func (a *HorizontalController) worker(ctx context.Context) {\n\tfor a.processNextWorkItem(ctx) {\n\t}\n\tlogger := klog.FromContext(ctx)\n\tlogger.Info(\"Horizontal Pod Autoscaler controller worker shutting down\")\n}","line":{"from":258,"to":263}} {"id":100004352,"name":"processNextWorkItem","signature":"func (a *HorizontalController) processNextWorkItem(ctx context.Context) bool","file":"pkg/controller/podautoscaler/horizontal.go","code":"func (a *HorizontalController) processNextWorkItem(ctx context.Context) bool {\n\tkey, quit := a.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer a.queue.Done(key)\n\n\tdeleted, err := a.reconcileKey(ctx, key.(string))\n\tif err != nil {\n\t\tutilruntime.HandleError(err)\n\t}\n\t// Add request processing HPA to queue with resyncPeriod delay.\n\t// Requests are always added to queue with resyncPeriod delay. If there's already request\n\t// for the HPA in the queue then a new request is always dropped. Requests spend resyncPeriod\n\t// in queue so HPAs are processed every resyncPeriod.\n\t// Request is added here just in case last resync didn't insert request into the queue. This\n\t// happens quite often because there is race condition between adding request after resyncPeriod\n\t// and removing them from queue. Request can be added by resync before previous request is\n\t// removed from queue. If we didn't add request here then in this case one request would be dropped\n\t// and HPA would processed after 2 x resyncPeriod.\n\tif !deleted {\n\t\ta.queue.AddRateLimited(key)\n\t}\n\n\treturn true\n}","line":{"from":265,"to":290}} {"id":100004353,"name":"computeReplicasForMetrics","signature":"func (a *HorizontalController) computeReplicasForMetrics(ctx context.Context, hpa *autoscalingv2.HorizontalPodAutoscaler, scale *autoscalingv1.Scale,","file":"pkg/controller/podautoscaler/horizontal.go","code":"// computeReplicasForMetrics computes the desired number of replicas for the metric specifications listed in the HPA,\n// returning the maximum of the computed replica counts, a description of the associated metric, and the statuses of\n// all metrics computed.\n// It may return both valid metricDesiredReplicas and an error,\n// when some metrics still work and HPA should perform scaling based on them.\n// If HPA cannot do anything due to error, it returns -1 in metricDesiredReplicas as a failure signal.\nfunc (a *HorizontalController) computeReplicasForMetrics(ctx context.Context, hpa *autoscalingv2.HorizontalPodAutoscaler, scale *autoscalingv1.Scale,\n\tmetricSpecs []autoscalingv2.MetricSpec) (replicas int32, metric string, statuses []autoscalingv2.MetricStatus, timestamp time.Time, err error) {\n\n\tselector, err := a.validateAndParseSelector(hpa, scale.Status.Selector)\n\tif err != nil {\n\t\treturn -1, \"\", nil, time.Time{}, err\n\t}\n\n\tspecReplicas := scale.Spec.Replicas\n\tstatusReplicas := scale.Status.Replicas\n\tstatuses = make([]autoscalingv2.MetricStatus, len(metricSpecs))\n\n\tinvalidMetricsCount := 0\n\tvar invalidMetricError error\n\tvar invalidMetricCondition autoscalingv2.HorizontalPodAutoscalerCondition\n\n\tfor i, metricSpec := range metricSpecs {\n\t\treplicaCountProposal, metricNameProposal, timestampProposal, condition, err := a.computeReplicasForMetric(ctx, hpa, metricSpec, specReplicas, statusReplicas, selector, \u0026statuses[i])\n\n\t\tif err != nil {\n\t\t\tif invalidMetricsCount \u003c= 0 {\n\t\t\t\tinvalidMetricCondition = condition\n\t\t\t\tinvalidMetricError = err\n\t\t\t}\n\t\t\tinvalidMetricsCount++\n\t\t\tcontinue\n\t\t}\n\t\tif replicas == 0 || replicaCountProposal \u003e replicas {\n\t\t\ttimestamp = timestampProposal\n\t\t\treplicas = replicaCountProposal\n\t\t\tmetric = metricNameProposal\n\t\t}\n\t}\n\n\tif invalidMetricError != nil {\n\t\tinvalidMetricError = fmt.Errorf(\"invalid metrics (%v invalid out of %v), first error is: %v\", invalidMetricsCount, len(metricSpecs), invalidMetricError)\n\t}\n\n\t// If all metrics are invalid or some are invalid and we would scale down,\n\t// return an error and set the condition of the hpa based on the first invalid metric.\n\t// Otherwise set the condition as scaling active as we're going to scale\n\tif invalidMetricsCount \u003e= len(metricSpecs) || (invalidMetricsCount \u003e 0 \u0026\u0026 replicas \u003c specReplicas) {\n\t\tsetCondition(hpa, invalidMetricCondition.Type, invalidMetricCondition.Status, invalidMetricCondition.Reason, invalidMetricCondition.Message)\n\t\treturn -1, \"\", statuses, time.Time{}, invalidMetricError\n\t}\n\tsetCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionTrue, \"ValidMetricFound\", \"the HPA was able to successfully calculate a replica count from %s\", metric)\n\n\treturn replicas, metric, statuses, timestamp, invalidMetricError\n}","line":{"from":292,"to":346}} {"id":100004354,"name":"hpasControllingPodsUnderSelector","signature":"func (a *HorizontalController) hpasControllingPodsUnderSelector(pods []*v1.Pod) []selectors.Key","file":"pkg/controller/podautoscaler/horizontal.go","code":"// hpasControllingPodsUnderSelector returns a list of keys of all HPAs that control a given list of pods.\nfunc (a *HorizontalController) hpasControllingPodsUnderSelector(pods []*v1.Pod) []selectors.Key {\n\ta.hpaSelectorsMux.Lock()\n\tdefer a.hpaSelectorsMux.Unlock()\n\n\thpas := map[selectors.Key]struct{}{}\n\tfor _, p := range pods {\n\t\tpodKey := selectors.Key{Name: p.Name, Namespace: p.Namespace}\n\t\ta.hpaSelectors.Put(podKey, p.Labels)\n\n\t\tselectingHpas, ok := a.hpaSelectors.ReverseSelect(podKey)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, hpa := range selectingHpas {\n\t\t\thpas[hpa] = struct{}{}\n\t\t}\n\t}\n\t// Clean up all added pods.\n\ta.hpaSelectors.KeepOnly([]selectors.Key{})\n\n\thpaList := []selectors.Key{}\n\tfor hpa := range hpas {\n\t\thpaList = append(hpaList, hpa)\n\t}\n\treturn hpaList\n}","line":{"from":348,"to":374}} {"id":100004355,"name":"validateAndParseSelector","signature":"func (a *HorizontalController) validateAndParseSelector(hpa *autoscalingv2.HorizontalPodAutoscaler, selector string) (labels.Selector, error)","file":"pkg/controller/podautoscaler/horizontal.go","code":"// validateAndParseSelector verifies that:\n// - selector is not empty;\n// - selector format is valid;\n// - all pods by current selector are controlled by only one HPA.\n// Returns an error if the check has failed or the parsed selector if succeeded.\n// In case of an error the ScalingActive is set to false with the corresponding reason.\nfunc (a *HorizontalController) validateAndParseSelector(hpa *autoscalingv2.HorizontalPodAutoscaler, selector string) (labels.Selector, error) {\n\tif selector == \"\" {\n\t\terrMsg := \"selector is required\"\n\t\ta.eventRecorder.Event(hpa, v1.EventTypeWarning, \"SelectorRequired\", errMsg)\n\t\tsetCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, \"InvalidSelector\", \"the HPA target's scale is missing a selector\")\n\t\treturn nil, fmt.Errorf(errMsg)\n\t}\n\n\tparsedSelector, err := labels.Parse(selector)\n\tif err != nil {\n\t\terrMsg := fmt.Sprintf(\"couldn't convert selector into a corresponding internal selector object: %v\", err)\n\t\ta.eventRecorder.Event(hpa, v1.EventTypeWarning, \"InvalidSelector\", errMsg)\n\t\tsetCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, \"InvalidSelector\", errMsg)\n\t\treturn nil, fmt.Errorf(errMsg)\n\t}\n\n\thpaKey := selectors.Key{Name: hpa.Name, Namespace: hpa.Namespace}\n\ta.hpaSelectorsMux.Lock()\n\tif a.hpaSelectors.SelectorExists(hpaKey) {\n\t\t// Update HPA selector only if the HPA was registered in enqueueHPA.\n\t\ta.hpaSelectors.PutSelector(hpaKey, parsedSelector)\n\t}\n\ta.hpaSelectorsMux.Unlock()\n\n\tpods, err := a.podLister.Pods(hpa.Namespace).List(parsedSelector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tselectingHpas := a.hpasControllingPodsUnderSelector(pods)\n\tif len(selectingHpas) \u003e 1 {\n\t\terrMsg := fmt.Sprintf(\"pods by selector %v are controlled by multiple HPAs: %v\", selector, selectingHpas)\n\t\ta.eventRecorder.Event(hpa, v1.EventTypeWarning, \"AmbiguousSelector\", errMsg)\n\t\tsetCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, \"AmbiguousSelector\", errMsg)\n\t\treturn nil, fmt.Errorf(errMsg)\n\t}\n\n\treturn parsedSelector, nil\n}","line":{"from":376,"to":420}} {"id":100004356,"name":"computeReplicasForMetric","signature":"func (a *HorizontalController) computeReplicasForMetric(ctx context.Context, hpa *autoscalingv2.HorizontalPodAutoscaler, spec autoscalingv2.MetricSpec,","file":"pkg/controller/podautoscaler/horizontal.go","code":"// Computes the desired number of replicas for a specific hpa and metric specification,\n// returning the metric status and a proposed condition to be set on the HPA object.\nfunc (a *HorizontalController) computeReplicasForMetric(ctx context.Context, hpa *autoscalingv2.HorizontalPodAutoscaler, spec autoscalingv2.MetricSpec,\n\tspecReplicas, statusReplicas int32, selector labels.Selector, status *autoscalingv2.MetricStatus) (replicaCountProposal int32, metricNameProposal string,\n\ttimestampProposal time.Time, condition autoscalingv2.HorizontalPodAutoscalerCondition, err error) {\n\t// actionLabel is used to report which actions this reconciliation has taken.\n\tstart := time.Now()\n\tdefer func() {\n\t\tactionLabel := monitor.ActionLabelNone\n\t\tswitch {\n\t\tcase replicaCountProposal \u003e hpa.Status.CurrentReplicas:\n\t\t\tactionLabel = monitor.ActionLabelScaleUp\n\t\tcase replicaCountProposal \u003c hpa.Status.CurrentReplicas:\n\t\t\tactionLabel = monitor.ActionLabelScaleDown\n\t\t}\n\n\t\terrorLabel := monitor.ErrorLabelNone\n\t\tif err != nil {\n\t\t\t// In case of error, set \"internal\" as default.\n\t\t\terrorLabel = monitor.ErrorLabelInternal\n\t\t\tactionLabel = monitor.ActionLabelNone\n\t\t}\n\t\tif errors.Is(err, errSpec) {\n\t\t\terrorLabel = monitor.ErrorLabelSpec\n\t\t}\n\n\t\ta.monitor.ObserveMetricComputationResult(actionLabel, errorLabel, time.Since(start), spec.Type)\n\t}()\n\n\tswitch spec.Type {\n\tcase autoscalingv2.ObjectMetricSourceType:\n\t\tmetricSelector, err := metav1.LabelSelectorAsSelector(spec.Object.Metric.Selector)\n\t\tif err != nil {\n\t\t\tcondition := a.getUnableComputeReplicaCountCondition(hpa, \"FailedGetObjectMetric\", err)\n\t\t\treturn 0, \"\", time.Time{}, condition, fmt.Errorf(\"failed to get object metric value: %v\", err)\n\t\t}\n\t\treplicaCountProposal, timestampProposal, metricNameProposal, condition, err = a.computeStatusForObjectMetric(specReplicas, statusReplicas, spec, hpa, selector, status, metricSelector)\n\t\tif err != nil {\n\t\t\treturn 0, \"\", time.Time{}, condition, fmt.Errorf(\"failed to get object metric value: %v\", err)\n\t\t}\n\tcase autoscalingv2.PodsMetricSourceType:\n\t\tmetricSelector, err := metav1.LabelSelectorAsSelector(spec.Pods.Metric.Selector)\n\t\tif err != nil {\n\t\t\tcondition := a.getUnableComputeReplicaCountCondition(hpa, \"FailedGetPodsMetric\", err)\n\t\t\treturn 0, \"\", time.Time{}, condition, fmt.Errorf(\"failed to get pods metric value: %v\", err)\n\t\t}\n\t\treplicaCountProposal, timestampProposal, metricNameProposal, condition, err = a.computeStatusForPodsMetric(specReplicas, spec, hpa, selector, status, metricSelector)\n\t\tif err != nil {\n\t\t\treturn 0, \"\", time.Time{}, condition, fmt.Errorf(\"failed to get pods metric value: %v\", err)\n\t\t}\n\tcase autoscalingv2.ResourceMetricSourceType:\n\t\treplicaCountProposal, timestampProposal, metricNameProposal, condition, err = a.computeStatusForResourceMetric(ctx, specReplicas, spec, hpa, selector, status)\n\t\tif err != nil {\n\t\t\treturn 0, \"\", time.Time{}, condition, fmt.Errorf(\"failed to get %s resource metric value: %v\", spec.Resource.Name, err)\n\t\t}\n\tcase autoscalingv2.ContainerResourceMetricSourceType:\n\t\tif !a.containerResourceMetricsEnabled {\n\t\t\t// If the container resource metrics feature is disabled but the object has the one,\n\t\t\t// that means the user enabled the feature once,\n\t\t\t// created some HPAs with the container resource metrics, and disabled it finally.\n\t\t\treturn 0, \"\", time.Time{}, condition, fmt.Errorf(\"ContainerResource metric type is not supported: disabled by the feature gate\")\n\t\t}\n\t\treplicaCountProposal, timestampProposal, metricNameProposal, condition, err = a.computeStatusForContainerResourceMetric(ctx, specReplicas, spec, hpa, selector, status)\n\t\tif err != nil {\n\t\t\treturn 0, \"\", time.Time{}, condition, fmt.Errorf(\"failed to get %s container metric value: %v\", spec.ContainerResource.Container, err)\n\t\t}\n\tcase autoscalingv2.ExternalMetricSourceType:\n\t\treplicaCountProposal, timestampProposal, metricNameProposal, condition, err = a.computeStatusForExternalMetric(specReplicas, statusReplicas, spec, hpa, selector, status)\n\t\tif err != nil {\n\t\t\treturn 0, \"\", time.Time{}, condition, fmt.Errorf(\"failed to get %s external metric value: %v\", spec.External.Metric.Name, err)\n\t\t}\n\tdefault:\n\t\t// It shouldn't reach here as invalid metric source type is filtered out in the api-server's validation.\n\t\terr = fmt.Errorf(\"unknown metric source type %q%w\", string(spec.Type), errSpec)\n\t\tcondition := a.getUnableComputeReplicaCountCondition(hpa, \"InvalidMetricSourceType\", err)\n\t\treturn 0, \"\", time.Time{}, condition, err\n\t}\n\treturn replicaCountProposal, metricNameProposal, timestampProposal, autoscalingv2.HorizontalPodAutoscalerCondition{}, nil\n}","line":{"from":422,"to":500}} {"id":100004357,"name":"reconcileKey","signature":"func (a *HorizontalController) reconcileKey(ctx context.Context, key string) (deleted bool, err error)","file":"pkg/controller/podautoscaler/horizontal.go","code":"func (a *HorizontalController) reconcileKey(ctx context.Context, key string) (deleted bool, err error) {\n\tnamespace, name, err := cache.SplitMetaNamespaceKey(key)\n\tif err != nil {\n\t\treturn true, err\n\t}\n\n\tlogger := klog.FromContext(ctx)\n\n\thpa, err := a.hpaLister.HorizontalPodAutoscalers(namespace).Get(name)\n\tif k8serrors.IsNotFound(err) {\n\t\tlogger.Info(\"Horizontal Pod Autoscaler has been deleted\", \"HPA\", klog.KRef(namespace, name))\n\n\t\ta.recommendationsLock.Lock()\n\t\tdelete(a.recommendations, key)\n\t\ta.recommendationsLock.Unlock()\n\n\t\ta.scaleUpEventsLock.Lock()\n\t\tdelete(a.scaleUpEvents, key)\n\t\ta.scaleUpEventsLock.Unlock()\n\n\t\ta.scaleDownEventsLock.Lock()\n\t\tdelete(a.scaleDownEvents, key)\n\t\ta.scaleDownEventsLock.Unlock()\n\n\t\treturn true, nil\n\t}\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn false, a.reconcileAutoscaler(ctx, hpa, key)\n}","line":{"from":502,"to":533}} {"id":100004358,"name":"computeStatusForObjectMetric","signature":"func (a *HorizontalController) computeStatusForObjectMetric(specReplicas, statusReplicas int32, metricSpec autoscalingv2.MetricSpec, hpa *autoscalingv2.HorizontalPodAutoscaler, selector labels.Selector, status *autoscalingv2.MetricStatus, metricSelector labels.Selector) (replicas int32, timestamp time.Time, metricName string, condition autoscalingv2.HorizontalPodAutoscalerCondition, err error)","file":"pkg/controller/podautoscaler/horizontal.go","code":"// computeStatusForObjectMetric computes the desired number of replicas for the specified metric of type ObjectMetricSourceType.\nfunc (a *HorizontalController) computeStatusForObjectMetric(specReplicas, statusReplicas int32, metricSpec autoscalingv2.MetricSpec, hpa *autoscalingv2.HorizontalPodAutoscaler, selector labels.Selector, status *autoscalingv2.MetricStatus, metricSelector labels.Selector) (replicas int32, timestamp time.Time, metricName string, condition autoscalingv2.HorizontalPodAutoscalerCondition, err error) {\n\tif metricSpec.Object.Target.Type == autoscalingv2.ValueMetricType {\n\t\treplicaCountProposal, usageProposal, timestampProposal, err := a.replicaCalc.GetObjectMetricReplicas(specReplicas, metricSpec.Object.Target.Value.MilliValue(), metricSpec.Object.Metric.Name, hpa.Namespace, \u0026metricSpec.Object.DescribedObject, selector, metricSelector)\n\t\tif err != nil {\n\t\t\tcondition := a.getUnableComputeReplicaCountCondition(hpa, \"FailedGetObjectMetric\", err)\n\t\t\treturn 0, timestampProposal, \"\", condition, err\n\t\t}\n\t\t*status = autoscalingv2.MetricStatus{\n\t\t\tType: autoscalingv2.ObjectMetricSourceType,\n\t\t\tObject: \u0026autoscalingv2.ObjectMetricStatus{\n\t\t\t\tDescribedObject: metricSpec.Object.DescribedObject,\n\t\t\t\tMetric: autoscalingv2.MetricIdentifier{\n\t\t\t\t\tName: metricSpec.Object.Metric.Name,\n\t\t\t\t\tSelector: metricSpec.Object.Metric.Selector,\n\t\t\t\t},\n\t\t\t\tCurrent: autoscalingv2.MetricValueStatus{\n\t\t\t\t\tValue: resource.NewMilliQuantity(usageProposal, resource.DecimalSI),\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\treturn replicaCountProposal, timestampProposal, fmt.Sprintf(\"%s metric %s\", metricSpec.Object.DescribedObject.Kind, metricSpec.Object.Metric.Name), autoscalingv2.HorizontalPodAutoscalerCondition{}, nil\n\t} else if metricSpec.Object.Target.Type == autoscalingv2.AverageValueMetricType {\n\t\treplicaCountProposal, usageProposal, timestampProposal, err := a.replicaCalc.GetObjectPerPodMetricReplicas(statusReplicas, metricSpec.Object.Target.AverageValue.MilliValue(), metricSpec.Object.Metric.Name, hpa.Namespace, \u0026metricSpec.Object.DescribedObject, metricSelector)\n\t\tif err != nil {\n\t\t\tcondition := a.getUnableComputeReplicaCountCondition(hpa, \"FailedGetObjectMetric\", err)\n\t\t\treturn 0, time.Time{}, \"\", condition, fmt.Errorf(\"failed to get %s object metric: %v\", metricSpec.Object.Metric.Name, err)\n\t\t}\n\t\t*status = autoscalingv2.MetricStatus{\n\t\t\tType: autoscalingv2.ObjectMetricSourceType,\n\t\t\tObject: \u0026autoscalingv2.ObjectMetricStatus{\n\t\t\t\tMetric: autoscalingv2.MetricIdentifier{\n\t\t\t\t\tName: metricSpec.Object.Metric.Name,\n\t\t\t\t\tSelector: metricSpec.Object.Metric.Selector,\n\t\t\t\t},\n\t\t\t\tCurrent: autoscalingv2.MetricValueStatus{\n\t\t\t\t\tAverageValue: resource.NewMilliQuantity(usageProposal, resource.DecimalSI),\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\treturn replicaCountProposal, timestampProposal, fmt.Sprintf(\"external metric %s(%+v)\", metricSpec.Object.Metric.Name, metricSpec.Object.Metric.Selector), autoscalingv2.HorizontalPodAutoscalerCondition{}, nil\n\t}\n\terrMsg := \"invalid object metric source: neither a value target nor an average value target was set\"\n\terr = fmt.Errorf(errMsg)\n\tcondition = a.getUnableComputeReplicaCountCondition(hpa, \"FailedGetObjectMetric\", err)\n\treturn 0, time.Time{}, \"\", condition, err\n}","line":{"from":535,"to":581}} {"id":100004359,"name":"computeStatusForPodsMetric","signature":"func (a *HorizontalController) computeStatusForPodsMetric(currentReplicas int32, metricSpec autoscalingv2.MetricSpec, hpa *autoscalingv2.HorizontalPodAutoscaler, selector labels.Selector, status *autoscalingv2.MetricStatus, metricSelector labels.Selector) (replicaCountProposal int32, timestampProposal time.Time, metricNameProposal string, condition autoscalingv2.HorizontalPodAutoscalerCondition, err error)","file":"pkg/controller/podautoscaler/horizontal.go","code":"// computeStatusForPodsMetric computes the desired number of replicas for the specified metric of type PodsMetricSourceType.\nfunc (a *HorizontalController) computeStatusForPodsMetric(currentReplicas int32, metricSpec autoscalingv2.MetricSpec, hpa *autoscalingv2.HorizontalPodAutoscaler, selector labels.Selector, status *autoscalingv2.MetricStatus, metricSelector labels.Selector) (replicaCountProposal int32, timestampProposal time.Time, metricNameProposal string, condition autoscalingv2.HorizontalPodAutoscalerCondition, err error) {\n\treplicaCountProposal, usageProposal, timestampProposal, err := a.replicaCalc.GetMetricReplicas(currentReplicas, metricSpec.Pods.Target.AverageValue.MilliValue(), metricSpec.Pods.Metric.Name, hpa.Namespace, selector, metricSelector)\n\tif err != nil {\n\t\tcondition = a.getUnableComputeReplicaCountCondition(hpa, \"FailedGetPodsMetric\", err)\n\t\treturn 0, timestampProposal, \"\", condition, err\n\t}\n\t*status = autoscalingv2.MetricStatus{\n\t\tType: autoscalingv2.PodsMetricSourceType,\n\t\tPods: \u0026autoscalingv2.PodsMetricStatus{\n\t\t\tMetric: autoscalingv2.MetricIdentifier{\n\t\t\t\tName: metricSpec.Pods.Metric.Name,\n\t\t\t\tSelector: metricSpec.Pods.Metric.Selector,\n\t\t\t},\n\t\t\tCurrent: autoscalingv2.MetricValueStatus{\n\t\t\t\tAverageValue: resource.NewMilliQuantity(usageProposal, resource.DecimalSI),\n\t\t\t},\n\t\t},\n\t}\n\n\treturn replicaCountProposal, timestampProposal, fmt.Sprintf(\"pods metric %s\", metricSpec.Pods.Metric.Name), autoscalingv2.HorizontalPodAutoscalerCondition{}, nil\n}","line":{"from":583,"to":604}} {"id":100004360,"name":"computeStatusForResourceMetricGeneric","signature":"func (a *HorizontalController) computeStatusForResourceMetricGeneric(ctx context.Context, currentReplicas int32, target autoscalingv2.MetricTarget,","file":"pkg/controller/podautoscaler/horizontal.go","code":"func (a *HorizontalController) computeStatusForResourceMetricGeneric(ctx context.Context, currentReplicas int32, target autoscalingv2.MetricTarget,\n\tresourceName v1.ResourceName, namespace string, container string, selector labels.Selector, sourceType autoscalingv2.MetricSourceType) (replicaCountProposal int32,\n\tmetricStatus *autoscalingv2.MetricValueStatus, timestampProposal time.Time, metricNameProposal string,\n\tcondition autoscalingv2.HorizontalPodAutoscalerCondition, err error) {\n\tif target.AverageValue != nil {\n\t\tvar rawProposal int64\n\t\treplicaCountProposal, rawProposal, timestampProposal, err := a.replicaCalc.GetRawResourceReplicas(ctx, currentReplicas, target.AverageValue.MilliValue(), resourceName, namespace, selector, container)\n\t\tif err != nil {\n\t\t\treturn 0, nil, time.Time{}, \"\", condition, fmt.Errorf(\"failed to get %s usage: %v\", resourceName, err)\n\t\t}\n\t\tmetricNameProposal = fmt.Sprintf(\"%s resource\", resourceName.String())\n\t\tstatus := autoscalingv2.MetricValueStatus{\n\t\t\tAverageValue: resource.NewMilliQuantity(rawProposal, resource.DecimalSI),\n\t\t}\n\t\treturn replicaCountProposal, \u0026status, timestampProposal, metricNameProposal, autoscalingv2.HorizontalPodAutoscalerCondition{}, nil\n\t}\n\n\tif target.AverageUtilization == nil {\n\t\terrMsg := \"invalid resource metric source: neither an average utilization target nor an average value (usage) target was set\"\n\t\treturn 0, nil, time.Time{}, \"\", condition, fmt.Errorf(errMsg)\n\t}\n\n\ttargetUtilization := *target.AverageUtilization\n\treplicaCountProposal, percentageProposal, rawProposal, timestampProposal, err := a.replicaCalc.GetResourceReplicas(ctx, currentReplicas, targetUtilization, resourceName, namespace, selector, container)\n\tif err != nil {\n\t\treturn 0, nil, time.Time{}, \"\", condition, fmt.Errorf(\"failed to get %s utilization: %v\", resourceName, err)\n\t}\n\n\tmetricNameProposal = fmt.Sprintf(\"%s resource utilization (percentage of request)\", resourceName)\n\tif sourceType == autoscalingv2.ContainerResourceMetricSourceType {\n\t\tmetricNameProposal = fmt.Sprintf(\"%s container resource utilization (percentage of request)\", resourceName)\n\t}\n\tstatus := autoscalingv2.MetricValueStatus{\n\t\tAverageUtilization: \u0026percentageProposal,\n\t\tAverageValue: resource.NewMilliQuantity(rawProposal, resource.DecimalSI),\n\t}\n\treturn replicaCountProposal, \u0026status, timestampProposal, metricNameProposal, autoscalingv2.HorizontalPodAutoscalerCondition{}, nil\n}","line":{"from":606,"to":643}} {"id":100004361,"name":"computeStatusForResourceMetric","signature":"func (a *HorizontalController) computeStatusForResourceMetric(ctx context.Context, currentReplicas int32, metricSpec autoscalingv2.MetricSpec, hpa *autoscalingv2.HorizontalPodAutoscaler,","file":"pkg/controller/podautoscaler/horizontal.go","code":"// computeStatusForResourceMetric computes the desired number of replicas for the specified metric of type ResourceMetricSourceType.\nfunc (a *HorizontalController) computeStatusForResourceMetric(ctx context.Context, currentReplicas int32, metricSpec autoscalingv2.MetricSpec, hpa *autoscalingv2.HorizontalPodAutoscaler,\n\tselector labels.Selector, status *autoscalingv2.MetricStatus) (replicaCountProposal int32, timestampProposal time.Time,\n\tmetricNameProposal string, condition autoscalingv2.HorizontalPodAutoscalerCondition, err error) {\n\treplicaCountProposal, metricValueStatus, timestampProposal, metricNameProposal, condition, err := a.computeStatusForResourceMetricGeneric(ctx, currentReplicas, metricSpec.Resource.Target, metricSpec.Resource.Name, hpa.Namespace, \"\", selector, autoscalingv2.ResourceMetricSourceType)\n\tif err != nil {\n\t\tcondition = a.getUnableComputeReplicaCountCondition(hpa, \"FailedGetResourceMetric\", err)\n\t\treturn replicaCountProposal, timestampProposal, metricNameProposal, condition, err\n\t}\n\t*status = autoscalingv2.MetricStatus{\n\t\tType: autoscalingv2.ResourceMetricSourceType,\n\t\tResource: \u0026autoscalingv2.ResourceMetricStatus{\n\t\t\tName: metricSpec.Resource.Name,\n\t\t\tCurrent: *metricValueStatus,\n\t\t},\n\t}\n\treturn replicaCountProposal, timestampProposal, metricNameProposal, condition, nil\n}","line":{"from":645,"to":662}} {"id":100004362,"name":"computeStatusForContainerResourceMetric","signature":"func (a *HorizontalController) computeStatusForContainerResourceMetric(ctx context.Context, currentReplicas int32, metricSpec autoscalingv2.MetricSpec, hpa *autoscalingv2.HorizontalPodAutoscaler,","file":"pkg/controller/podautoscaler/horizontal.go","code":"// computeStatusForContainerResourceMetric computes the desired number of replicas for the specified metric of type ResourceMetricSourceType.\nfunc (a *HorizontalController) computeStatusForContainerResourceMetric(ctx context.Context, currentReplicas int32, metricSpec autoscalingv2.MetricSpec, hpa *autoscalingv2.HorizontalPodAutoscaler,\n\tselector labels.Selector, status *autoscalingv2.MetricStatus) (replicaCountProposal int32, timestampProposal time.Time,\n\tmetricNameProposal string, condition autoscalingv2.HorizontalPodAutoscalerCondition, err error) {\n\treplicaCountProposal, metricValueStatus, timestampProposal, metricNameProposal, condition, err := a.computeStatusForResourceMetricGeneric(ctx, currentReplicas, metricSpec.ContainerResource.Target, metricSpec.ContainerResource.Name, hpa.Namespace, metricSpec.ContainerResource.Container, selector, autoscalingv2.ContainerResourceMetricSourceType)\n\tif err != nil {\n\t\tcondition = a.getUnableComputeReplicaCountCondition(hpa, \"FailedGetContainerResourceMetric\", err)\n\t\treturn replicaCountProposal, timestampProposal, metricNameProposal, condition, err\n\t}\n\t*status = autoscalingv2.MetricStatus{\n\t\tType: autoscalingv2.ContainerResourceMetricSourceType,\n\t\tContainerResource: \u0026autoscalingv2.ContainerResourceMetricStatus{\n\t\t\tName: metricSpec.ContainerResource.Name,\n\t\t\tContainer: metricSpec.ContainerResource.Container,\n\t\t\tCurrent: *metricValueStatus,\n\t\t},\n\t}\n\treturn replicaCountProposal, timestampProposal, metricNameProposal, condition, nil\n}","line":{"from":664,"to":682}} {"id":100004363,"name":"computeStatusForExternalMetric","signature":"func (a *HorizontalController) computeStatusForExternalMetric(specReplicas, statusReplicas int32, metricSpec autoscalingv2.MetricSpec, hpa *autoscalingv2.HorizontalPodAutoscaler, selector labels.Selector, status *autoscalingv2.MetricStatus) (replicaCountProposal int32, timestampProposal time.Time, metricNameProposal string, condition autoscalingv2.HorizontalPodAutoscalerCondition, err error)","file":"pkg/controller/podautoscaler/horizontal.go","code":"// computeStatusForExternalMetric computes the desired number of replicas for the specified metric of type ExternalMetricSourceType.\nfunc (a *HorizontalController) computeStatusForExternalMetric(specReplicas, statusReplicas int32, metricSpec autoscalingv2.MetricSpec, hpa *autoscalingv2.HorizontalPodAutoscaler, selector labels.Selector, status *autoscalingv2.MetricStatus) (replicaCountProposal int32, timestampProposal time.Time, metricNameProposal string, condition autoscalingv2.HorizontalPodAutoscalerCondition, err error) {\n\tif metricSpec.External.Target.AverageValue != nil {\n\t\treplicaCountProposal, usageProposal, timestampProposal, err := a.replicaCalc.GetExternalPerPodMetricReplicas(statusReplicas, metricSpec.External.Target.AverageValue.MilliValue(), metricSpec.External.Metric.Name, hpa.Namespace, metricSpec.External.Metric.Selector)\n\t\tif err != nil {\n\t\t\tcondition = a.getUnableComputeReplicaCountCondition(hpa, \"FailedGetExternalMetric\", err)\n\t\t\treturn 0, time.Time{}, \"\", condition, fmt.Errorf(\"failed to get %s external metric: %v\", metricSpec.External.Metric.Name, err)\n\t\t}\n\t\t*status = autoscalingv2.MetricStatus{\n\t\t\tType: autoscalingv2.ExternalMetricSourceType,\n\t\t\tExternal: \u0026autoscalingv2.ExternalMetricStatus{\n\t\t\t\tMetric: autoscalingv2.MetricIdentifier{\n\t\t\t\t\tName: metricSpec.External.Metric.Name,\n\t\t\t\t\tSelector: metricSpec.External.Metric.Selector,\n\t\t\t\t},\n\t\t\t\tCurrent: autoscalingv2.MetricValueStatus{\n\t\t\t\t\tAverageValue: resource.NewMilliQuantity(usageProposal, resource.DecimalSI),\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\treturn replicaCountProposal, timestampProposal, fmt.Sprintf(\"external metric %s(%+v)\", metricSpec.External.Metric.Name, metricSpec.External.Metric.Selector), autoscalingv2.HorizontalPodAutoscalerCondition{}, nil\n\t}\n\tif metricSpec.External.Target.Value != nil {\n\t\treplicaCountProposal, usageProposal, timestampProposal, err := a.replicaCalc.GetExternalMetricReplicas(specReplicas, metricSpec.External.Target.Value.MilliValue(), metricSpec.External.Metric.Name, hpa.Namespace, metricSpec.External.Metric.Selector, selector)\n\t\tif err != nil {\n\t\t\tcondition = a.getUnableComputeReplicaCountCondition(hpa, \"FailedGetExternalMetric\", err)\n\t\t\treturn 0, time.Time{}, \"\", condition, fmt.Errorf(\"failed to get external metric %s: %v\", metricSpec.External.Metric.Name, err)\n\t\t}\n\t\t*status = autoscalingv2.MetricStatus{\n\t\t\tType: autoscalingv2.ExternalMetricSourceType,\n\t\t\tExternal: \u0026autoscalingv2.ExternalMetricStatus{\n\t\t\t\tMetric: autoscalingv2.MetricIdentifier{\n\t\t\t\t\tName: metricSpec.External.Metric.Name,\n\t\t\t\t\tSelector: metricSpec.External.Metric.Selector,\n\t\t\t\t},\n\t\t\t\tCurrent: autoscalingv2.MetricValueStatus{\n\t\t\t\t\tValue: resource.NewMilliQuantity(usageProposal, resource.DecimalSI),\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\treturn replicaCountProposal, timestampProposal, fmt.Sprintf(\"external metric %s(%+v)\", metricSpec.External.Metric.Name, metricSpec.External.Metric.Selector), autoscalingv2.HorizontalPodAutoscalerCondition{}, nil\n\t}\n\terrMsg := \"invalid external metric source: neither a value target nor an average value target was set\"\n\terr = fmt.Errorf(errMsg)\n\tcondition = a.getUnableComputeReplicaCountCondition(hpa, \"FailedGetExternalMetric\", err)\n\treturn 0, time.Time{}, \"\", condition, fmt.Errorf(errMsg)\n}","line":{"from":684,"to":730}} {"id":100004364,"name":"recordInitialRecommendation","signature":"func (a *HorizontalController) recordInitialRecommendation(currentReplicas int32, key string)","file":"pkg/controller/podautoscaler/horizontal.go","code":"func (a *HorizontalController) recordInitialRecommendation(currentReplicas int32, key string) {\n\ta.recommendationsLock.Lock()\n\tdefer a.recommendationsLock.Unlock()\n\tif a.recommendations[key] == nil {\n\t\ta.recommendations[key] = []timestampedRecommendation{{currentReplicas, time.Now()}}\n\t}\n}","line":{"from":732,"to":738}} {"id":100004365,"name":"reconcileAutoscaler","signature":"func (a *HorizontalController) reconcileAutoscaler(ctx context.Context, hpaShared *autoscalingv2.HorizontalPodAutoscaler, key string) (retErr error)","file":"pkg/controller/podautoscaler/horizontal.go","code":"func (a *HorizontalController) reconcileAutoscaler(ctx context.Context, hpaShared *autoscalingv2.HorizontalPodAutoscaler, key string) (retErr error) {\n\t// actionLabel is used to report which actions this reconciliation has taken.\n\tactionLabel := monitor.ActionLabelNone\n\tstart := time.Now()\n\tdefer func() {\n\t\terrorLabel := monitor.ErrorLabelNone\n\t\tif retErr != nil {\n\t\t\t// In case of error, set \"internal\" as default.\n\t\t\terrorLabel = monitor.ErrorLabelInternal\n\t\t}\n\t\tif errors.Is(retErr, errSpec) {\n\t\t\terrorLabel = monitor.ErrorLabelSpec\n\t\t}\n\n\t\ta.monitor.ObserveReconciliationResult(actionLabel, errorLabel, time.Since(start))\n\t}()\n\n\t// make a copy so that we never mutate the shared informer cache (conversion can mutate the object)\n\thpa := hpaShared.DeepCopy()\n\thpaStatusOriginal := hpa.Status.DeepCopy()\n\n\treference := fmt.Sprintf(\"%s/%s/%s\", hpa.Spec.ScaleTargetRef.Kind, hpa.Namespace, hpa.Spec.ScaleTargetRef.Name)\n\n\ttargetGV, err := schema.ParseGroupVersion(hpa.Spec.ScaleTargetRef.APIVersion)\n\tif err != nil {\n\t\ta.eventRecorder.Event(hpa, v1.EventTypeWarning, \"FailedGetScale\", err.Error())\n\t\tsetCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionFalse, \"FailedGetScale\", \"the HPA controller was unable to get the target's current scale: %v\", err)\n\t\tif err := a.updateStatusIfNeeded(ctx, hpaStatusOriginal, hpa); err != nil {\n\t\t\tutilruntime.HandleError(err)\n\t\t}\n\t\treturn fmt.Errorf(\"invalid API version in scale target reference: %v%w\", err, errSpec)\n\t}\n\n\ttargetGK := schema.GroupKind{\n\t\tGroup: targetGV.Group,\n\t\tKind: hpa.Spec.ScaleTargetRef.Kind,\n\t}\n\n\tmappings, err := a.mapper.RESTMappings(targetGK)\n\tif err != nil {\n\t\ta.eventRecorder.Event(hpa, v1.EventTypeWarning, \"FailedGetScale\", err.Error())\n\t\tsetCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionFalse, \"FailedGetScale\", \"the HPA controller was unable to get the target's current scale: %v\", err)\n\t\tif err := a.updateStatusIfNeeded(ctx, hpaStatusOriginal, hpa); err != nil {\n\t\t\tutilruntime.HandleError(err)\n\t\t}\n\t\treturn fmt.Errorf(\"unable to determine resource for scale target reference: %v\", err)\n\t}\n\n\tscale, targetGR, err := a.scaleForResourceMappings(ctx, hpa.Namespace, hpa.Spec.ScaleTargetRef.Name, mappings)\n\tif err != nil {\n\t\ta.eventRecorder.Event(hpa, v1.EventTypeWarning, \"FailedGetScale\", err.Error())\n\t\tsetCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionFalse, \"FailedGetScale\", \"the HPA controller was unable to get the target's current scale: %v\", err)\n\t\tif err := a.updateStatusIfNeeded(ctx, hpaStatusOriginal, hpa); err != nil {\n\t\t\tutilruntime.HandleError(err)\n\t\t}\n\t\treturn fmt.Errorf(\"failed to query scale subresource for %s: %v\", reference, err)\n\t}\n\tsetCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionTrue, \"SucceededGetScale\", \"the HPA controller was able to get the target's current scale\")\n\tcurrentReplicas := scale.Spec.Replicas\n\ta.recordInitialRecommendation(currentReplicas, key)\n\n\tvar (\n\t\tmetricStatuses []autoscalingv2.MetricStatus\n\t\tmetricDesiredReplicas int32\n\t\tmetricName string\n\t)\n\n\tdesiredReplicas := int32(0)\n\trescaleReason := \"\"\n\n\tvar minReplicas int32\n\n\tif hpa.Spec.MinReplicas != nil {\n\t\tminReplicas = *hpa.Spec.MinReplicas\n\t} else {\n\t\t// Default value\n\t\tminReplicas = 1\n\t}\n\n\trescale := true\n\tlogger := klog.FromContext(ctx)\n\n\tif scale.Spec.Replicas == 0 \u0026\u0026 minReplicas != 0 {\n\t\t// Autoscaling is disabled for this resource\n\t\tdesiredReplicas = 0\n\t\trescale = false\n\t\tsetCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, \"ScalingDisabled\", \"scaling is disabled since the replica count of the target is zero\")\n\t} else if currentReplicas \u003e hpa.Spec.MaxReplicas {\n\t\trescaleReason = \"Current number of replicas above Spec.MaxReplicas\"\n\t\tdesiredReplicas = hpa.Spec.MaxReplicas\n\t} else if currentReplicas \u003c minReplicas {\n\t\trescaleReason = \"Current number of replicas below Spec.MinReplicas\"\n\t\tdesiredReplicas = minReplicas\n\t} else {\n\t\tvar metricTimestamp time.Time\n\t\tmetricDesiredReplicas, metricName, metricStatuses, metricTimestamp, err = a.computeReplicasForMetrics(ctx, hpa, scale, hpa.Spec.Metrics)\n\t\t// computeReplicasForMetrics may return both non-zero metricDesiredReplicas and an error.\n\t\t// That means some metrics still work and HPA should perform scaling based on them.\n\t\tif err != nil \u0026\u0026 metricDesiredReplicas == -1 {\n\t\t\ta.setCurrentReplicasInStatus(hpa, currentReplicas)\n\t\t\tif err := a.updateStatusIfNeeded(ctx, hpaStatusOriginal, hpa); err != nil {\n\t\t\t\tutilruntime.HandleError(err)\n\t\t\t}\n\t\t\ta.eventRecorder.Event(hpa, v1.EventTypeWarning, \"FailedComputeMetricsReplicas\", err.Error())\n\t\t\treturn fmt.Errorf(\"failed to compute desired number of replicas based on listed metrics for %s: %v\", reference, err)\n\t\t}\n\t\tif err != nil {\n\t\t\t// We proceed to scaling, but return this error from reconcileAutoscaler() finally.\n\t\t\tretErr = err\n\t\t}\n\n\t\tlogger.V(4).Info(\"Proposing desired replicas\",\n\t\t\t\"desiredReplicas\", metricDesiredReplicas,\n\t\t\t\"metric\", metricName,\n\t\t\t\"timestamp\", metricTimestamp,\n\t\t\t\"scaleTarget\", reference)\n\n\t\trescaleMetric := \"\"\n\t\tif metricDesiredReplicas \u003e desiredReplicas {\n\t\t\tdesiredReplicas = metricDesiredReplicas\n\t\t\trescaleMetric = metricName\n\t\t}\n\t\tif desiredReplicas \u003e currentReplicas {\n\t\t\trescaleReason = fmt.Sprintf(\"%s above target\", rescaleMetric)\n\t\t}\n\t\tif desiredReplicas \u003c currentReplicas {\n\t\t\trescaleReason = \"All metrics below target\"\n\t\t}\n\t\tif hpa.Spec.Behavior == nil {\n\t\t\tdesiredReplicas = a.normalizeDesiredReplicas(hpa, key, currentReplicas, desiredReplicas, minReplicas)\n\t\t} else {\n\t\t\tdesiredReplicas = a.normalizeDesiredReplicasWithBehaviors(hpa, key, currentReplicas, desiredReplicas, minReplicas)\n\t\t}\n\t\trescale = desiredReplicas != currentReplicas\n\t}\n\n\tif rescale {\n\t\tscale.Spec.Replicas = desiredReplicas\n\t\t_, err = a.scaleNamespacer.Scales(hpa.Namespace).Update(ctx, targetGR, scale, metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\ta.eventRecorder.Eventf(hpa, v1.EventTypeWarning, \"FailedRescale\", \"New size: %d; reason: %s; error: %v\", desiredReplicas, rescaleReason, err.Error())\n\t\t\tsetCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionFalse, \"FailedUpdateScale\", \"the HPA controller was unable to update the target scale: %v\", err)\n\t\t\ta.setCurrentReplicasInStatus(hpa, currentReplicas)\n\t\t\tif err := a.updateStatusIfNeeded(ctx, hpaStatusOriginal, hpa); err != nil {\n\t\t\t\tutilruntime.HandleError(err)\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"failed to rescale %s: %v\", reference, err)\n\t\t}\n\t\tsetCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionTrue, \"SucceededRescale\", \"the HPA controller was able to update the target scale to %d\", desiredReplicas)\n\t\ta.eventRecorder.Eventf(hpa, v1.EventTypeNormal, \"SuccessfulRescale\", \"New size: %d; reason: %s\", desiredReplicas, rescaleReason)\n\t\ta.storeScaleEvent(hpa.Spec.Behavior, key, currentReplicas, desiredReplicas)\n\t\tlogger.Info(\"Successfully rescaled\",\n\t\t\t\"HPA\", klog.KObj(hpa),\n\t\t\t\"currentReplicas\", currentReplicas,\n\t\t\t\"desiredReplicas\", desiredReplicas,\n\t\t\t\"reason\", rescaleReason)\n\n\t\tif desiredReplicas \u003e currentReplicas {\n\t\t\tactionLabel = monitor.ActionLabelScaleUp\n\t\t} else {\n\t\t\tactionLabel = monitor.ActionLabelScaleDown\n\t\t}\n\t} else {\n\t\tlogger.V(4).Info(\"Decided not to scale\",\n\t\t\t\"scaleTarget\", reference,\n\t\t\t\"desiredReplicas\", desiredReplicas,\n\t\t\t\"lastScaleTime\", hpa.Status.LastScaleTime)\n\t\tdesiredReplicas = currentReplicas\n\t}\n\n\ta.setStatus(hpa, currentReplicas, desiredReplicas, metricStatuses, rescale)\n\n\terr = a.updateStatusIfNeeded(ctx, hpaStatusOriginal, hpa)\n\tif err != nil {\n\t\t// we can overwrite retErr in this case because it's an internal error.\n\t\treturn err\n\t}\n\n\treturn retErr\n}","line":{"from":740,"to":919}} {"id":100004366,"name":"stabilizeRecommendation","signature":"func (a *HorizontalController) stabilizeRecommendation(key string, prenormalizedDesiredReplicas int32) int32","file":"pkg/controller/podautoscaler/horizontal.go","code":"// stabilizeRecommendation:\n// - replaces old recommendation with the newest recommendation,\n// - returns max of recommendations that are not older than downscaleStabilisationWindow.\nfunc (a *HorizontalController) stabilizeRecommendation(key string, prenormalizedDesiredReplicas int32) int32 {\n\tmaxRecommendation := prenormalizedDesiredReplicas\n\tfoundOldSample := false\n\toldSampleIndex := 0\n\tcutoff := time.Now().Add(-a.downscaleStabilisationWindow)\n\n\ta.recommendationsLock.Lock()\n\tdefer a.recommendationsLock.Unlock()\n\tfor i, rec := range a.recommendations[key] {\n\t\tif rec.timestamp.Before(cutoff) {\n\t\t\tfoundOldSample = true\n\t\t\toldSampleIndex = i\n\t\t} else if rec.recommendation \u003e maxRecommendation {\n\t\t\tmaxRecommendation = rec.recommendation\n\t\t}\n\t}\n\tif foundOldSample {\n\t\ta.recommendations[key][oldSampleIndex] = timestampedRecommendation{prenormalizedDesiredReplicas, time.Now()}\n\t} else {\n\t\ta.recommendations[key] = append(a.recommendations[key], timestampedRecommendation{prenormalizedDesiredReplicas, time.Now()})\n\t}\n\treturn maxRecommendation\n}","line":{"from":921,"to":946}} {"id":100004367,"name":"normalizeDesiredReplicas","signature":"func (a *HorizontalController) normalizeDesiredReplicas(hpa *autoscalingv2.HorizontalPodAutoscaler, key string, currentReplicas int32, prenormalizedDesiredReplicas int32, minReplicas int32) int32","file":"pkg/controller/podautoscaler/horizontal.go","code":"// normalizeDesiredReplicas takes the metrics desired replicas value and normalizes it based on the appropriate conditions (i.e. \u003c maxReplicas, \u003e\n// minReplicas, etc...)\nfunc (a *HorizontalController) normalizeDesiredReplicas(hpa *autoscalingv2.HorizontalPodAutoscaler, key string, currentReplicas int32, prenormalizedDesiredReplicas int32, minReplicas int32) int32 {\n\tstabilizedRecommendation := a.stabilizeRecommendation(key, prenormalizedDesiredReplicas)\n\tif stabilizedRecommendation != prenormalizedDesiredReplicas {\n\t\tsetCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionTrue, \"ScaleDownStabilized\", \"recent recommendations were higher than current one, applying the highest recent recommendation\")\n\t} else {\n\t\tsetCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionTrue, \"ReadyForNewScale\", \"recommended size matches current size\")\n\t}\n\n\tdesiredReplicas, condition, reason := convertDesiredReplicasWithRules(currentReplicas, stabilizedRecommendation, minReplicas, hpa.Spec.MaxReplicas)\n\n\tif desiredReplicas == stabilizedRecommendation {\n\t\tsetCondition(hpa, autoscalingv2.ScalingLimited, v1.ConditionFalse, condition, reason)\n\t} else {\n\t\tsetCondition(hpa, autoscalingv2.ScalingLimited, v1.ConditionTrue, condition, reason)\n\t}\n\n\treturn desiredReplicas\n}","line":{"from":948,"to":967}} {"id":100004368,"name":"normalizeDesiredReplicasWithBehaviors","signature":"func (a *HorizontalController) normalizeDesiredReplicasWithBehaviors(hpa *autoscalingv2.HorizontalPodAutoscaler, key string, currentReplicas, prenormalizedDesiredReplicas, minReplicas int32) int32","file":"pkg/controller/podautoscaler/horizontal.go","code":"// normalizeDesiredReplicasWithBehaviors takes the metrics desired replicas value and normalizes it:\n// 1. Apply the basic conditions (i.e. \u003c maxReplicas, \u003e minReplicas, etc...)\n// 2. Apply the scale up/down limits from the hpaSpec.Behaviors (i.e. add no more than 4 pods)\n// 3. Apply the constraints period (i.e. add no more than 4 pods per minute)\n// 4. Apply the stabilization (i.e. add no more than 4 pods per minute, and pick the smallest recommendation during last 5 minutes)\nfunc (a *HorizontalController) normalizeDesiredReplicasWithBehaviors(hpa *autoscalingv2.HorizontalPodAutoscaler, key string, currentReplicas, prenormalizedDesiredReplicas, minReplicas int32) int32 {\n\ta.maybeInitScaleDownStabilizationWindow(hpa)\n\tnormalizationArg := NormalizationArg{\n\t\tKey: key,\n\t\tScaleUpBehavior: hpa.Spec.Behavior.ScaleUp,\n\t\tScaleDownBehavior: hpa.Spec.Behavior.ScaleDown,\n\t\tMinReplicas: minReplicas,\n\t\tMaxReplicas: hpa.Spec.MaxReplicas,\n\t\tCurrentReplicas: currentReplicas,\n\t\tDesiredReplicas: prenormalizedDesiredReplicas}\n\tstabilizedRecommendation, reason, message := a.stabilizeRecommendationWithBehaviors(normalizationArg)\n\tnormalizationArg.DesiredReplicas = stabilizedRecommendation\n\tif stabilizedRecommendation != prenormalizedDesiredReplicas {\n\t\t// \"ScaleUpStabilized\" || \"ScaleDownStabilized\"\n\t\tsetCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionTrue, reason, message)\n\t} else {\n\t\tsetCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionTrue, \"ReadyForNewScale\", \"recommended size matches current size\")\n\t}\n\tdesiredReplicas, reason, message := a.convertDesiredReplicasWithBehaviorRate(normalizationArg)\n\tif desiredReplicas == stabilizedRecommendation {\n\t\tsetCondition(hpa, autoscalingv2.ScalingLimited, v1.ConditionFalse, reason, message)\n\t} else {\n\t\tsetCondition(hpa, autoscalingv2.ScalingLimited, v1.ConditionTrue, reason, message)\n\t}\n\n\treturn desiredReplicas\n}","line":{"from":980,"to":1011}} {"id":100004369,"name":"maybeInitScaleDownStabilizationWindow","signature":"func (a *HorizontalController) maybeInitScaleDownStabilizationWindow(hpa *autoscalingv2.HorizontalPodAutoscaler)","file":"pkg/controller/podautoscaler/horizontal.go","code":"func (a *HorizontalController) maybeInitScaleDownStabilizationWindow(hpa *autoscalingv2.HorizontalPodAutoscaler) {\n\tbehavior := hpa.Spec.Behavior\n\tif behavior != nil \u0026\u0026 behavior.ScaleDown != nil \u0026\u0026 behavior.ScaleDown.StabilizationWindowSeconds == nil {\n\t\tstabilizationWindowSeconds := (int32)(a.downscaleStabilisationWindow.Seconds())\n\t\thpa.Spec.Behavior.ScaleDown.StabilizationWindowSeconds = \u0026stabilizationWindowSeconds\n\t}\n}","line":{"from":1013,"to":1019}} {"id":100004370,"name":"getReplicasChangePerPeriod","signature":"func getReplicasChangePerPeriod(periodSeconds int32, scaleEvents []timestampedScaleEvent) int32","file":"pkg/controller/podautoscaler/horizontal.go","code":"// getReplicasChangePerPeriod function find all the replica changes per period\nfunc getReplicasChangePerPeriod(periodSeconds int32, scaleEvents []timestampedScaleEvent) int32 {\n\tperiod := time.Second * time.Duration(periodSeconds)\n\tcutoff := time.Now().Add(-period)\n\tvar replicas int32\n\tfor _, rec := range scaleEvents {\n\t\tif rec.timestamp.After(cutoff) {\n\t\t\treplicas += rec.replicaChange\n\t\t}\n\t}\n\treturn replicas\n\n}","line":{"from":1021,"to":1033}} {"id":100004371,"name":"getUnableComputeReplicaCountCondition","signature":"func (a *HorizontalController) getUnableComputeReplicaCountCondition(hpa runtime.Object, reason string, err error) (condition autoscalingv2.HorizontalPodAutoscalerCondition)","file":"pkg/controller/podautoscaler/horizontal.go","code":"func (a *HorizontalController) getUnableComputeReplicaCountCondition(hpa runtime.Object, reason string, err error) (condition autoscalingv2.HorizontalPodAutoscalerCondition) {\n\ta.eventRecorder.Event(hpa, v1.EventTypeWarning, reason, err.Error())\n\treturn autoscalingv2.HorizontalPodAutoscalerCondition{\n\t\tType: autoscalingv2.ScalingActive,\n\t\tStatus: v1.ConditionFalse,\n\t\tReason: reason,\n\t\tMessage: fmt.Sprintf(\"the HPA was unable to compute the replica count: %v\", err),\n\t}\n}","line":{"from":1035,"to":1043}} {"id":100004372,"name":"storeScaleEvent","signature":"func (a *HorizontalController) storeScaleEvent(behavior *autoscalingv2.HorizontalPodAutoscalerBehavior, key string, prevReplicas, newReplicas int32)","file":"pkg/controller/podautoscaler/horizontal.go","code":"// storeScaleEvent stores (adds or replaces outdated) scale event.\n// outdated events to be replaced were marked as outdated in the `markScaleEventsOutdated` function\nfunc (a *HorizontalController) storeScaleEvent(behavior *autoscalingv2.HorizontalPodAutoscalerBehavior, key string, prevReplicas, newReplicas int32) {\n\tif behavior == nil {\n\t\treturn // we should not store any event as they will not be used\n\t}\n\tvar oldSampleIndex int\n\tvar longestPolicyPeriod int32\n\tfoundOldSample := false\n\tif newReplicas \u003e prevReplicas {\n\t\tlongestPolicyPeriod = getLongestPolicyPeriod(behavior.ScaleUp)\n\n\t\ta.scaleUpEventsLock.Lock()\n\t\tdefer a.scaleUpEventsLock.Unlock()\n\t\tmarkScaleEventsOutdated(a.scaleUpEvents[key], longestPolicyPeriod)\n\t\treplicaChange := newReplicas - prevReplicas\n\t\tfor i, event := range a.scaleUpEvents[key] {\n\t\t\tif event.outdated {\n\t\t\t\tfoundOldSample = true\n\t\t\t\toldSampleIndex = i\n\t\t\t}\n\t\t}\n\t\tnewEvent := timestampedScaleEvent{replicaChange, time.Now(), false}\n\t\tif foundOldSample {\n\t\t\ta.scaleUpEvents[key][oldSampleIndex] = newEvent\n\t\t} else {\n\t\t\ta.scaleUpEvents[key] = append(a.scaleUpEvents[key], newEvent)\n\t\t}\n\t} else {\n\t\tlongestPolicyPeriod = getLongestPolicyPeriod(behavior.ScaleDown)\n\n\t\ta.scaleDownEventsLock.Lock()\n\t\tdefer a.scaleDownEventsLock.Unlock()\n\t\tmarkScaleEventsOutdated(a.scaleDownEvents[key], longestPolicyPeriod)\n\t\treplicaChange := prevReplicas - newReplicas\n\t\tfor i, event := range a.scaleDownEvents[key] {\n\t\t\tif event.outdated {\n\t\t\t\tfoundOldSample = true\n\t\t\t\toldSampleIndex = i\n\t\t\t}\n\t\t}\n\t\tnewEvent := timestampedScaleEvent{replicaChange, time.Now(), false}\n\t\tif foundOldSample {\n\t\t\ta.scaleDownEvents[key][oldSampleIndex] = newEvent\n\t\t} else {\n\t\t\ta.scaleDownEvents[key] = append(a.scaleDownEvents[key], newEvent)\n\t\t}\n\t}\n}","line":{"from":1045,"to":1093}} {"id":100004373,"name":"stabilizeRecommendationWithBehaviors","signature":"func (a *HorizontalController) stabilizeRecommendationWithBehaviors(args NormalizationArg) (int32, string, string)","file":"pkg/controller/podautoscaler/horizontal.go","code":"// stabilizeRecommendationWithBehaviors:\n// - replaces old recommendation with the newest recommendation,\n// - returns {max,min} of recommendations that are not older than constraints.Scale{Up,Down}.DelaySeconds\nfunc (a *HorizontalController) stabilizeRecommendationWithBehaviors(args NormalizationArg) (int32, string, string) {\n\tnow := time.Now()\n\n\tfoundOldSample := false\n\toldSampleIndex := 0\n\n\tupRecommendation := args.DesiredReplicas\n\tupDelaySeconds := *args.ScaleUpBehavior.StabilizationWindowSeconds\n\tupCutoff := now.Add(-time.Second * time.Duration(upDelaySeconds))\n\n\tdownRecommendation := args.DesiredReplicas\n\tdownDelaySeconds := *args.ScaleDownBehavior.StabilizationWindowSeconds\n\tdownCutoff := now.Add(-time.Second * time.Duration(downDelaySeconds))\n\n\t// Calculate the upper and lower stabilization limits.\n\ta.recommendationsLock.Lock()\n\tdefer a.recommendationsLock.Unlock()\n\tfor i, rec := range a.recommendations[args.Key] {\n\t\tif rec.timestamp.After(upCutoff) {\n\t\t\tupRecommendation = min(rec.recommendation, upRecommendation)\n\t\t}\n\t\tif rec.timestamp.After(downCutoff) {\n\t\t\tdownRecommendation = max(rec.recommendation, downRecommendation)\n\t\t}\n\t\tif rec.timestamp.Before(upCutoff) \u0026\u0026 rec.timestamp.Before(downCutoff) {\n\t\t\tfoundOldSample = true\n\t\t\toldSampleIndex = i\n\t\t}\n\t}\n\n\t// Bring the recommendation to within the upper and lower limits (stabilize).\n\trecommendation := args.CurrentReplicas\n\tif recommendation \u003c upRecommendation {\n\t\trecommendation = upRecommendation\n\t}\n\tif recommendation \u003e downRecommendation {\n\t\trecommendation = downRecommendation\n\t}\n\n\t// Record the unstabilized recommendation.\n\tif foundOldSample {\n\t\ta.recommendations[args.Key][oldSampleIndex] = timestampedRecommendation{args.DesiredReplicas, time.Now()}\n\t} else {\n\t\ta.recommendations[args.Key] = append(a.recommendations[args.Key], timestampedRecommendation{args.DesiredReplicas, time.Now()})\n\t}\n\n\t// Determine a human-friendly message.\n\tvar reason, message string\n\tif args.DesiredReplicas \u003e= args.CurrentReplicas {\n\t\treason = \"ScaleUpStabilized\"\n\t\tmessage = \"recent recommendations were lower than current one, applying the lowest recent recommendation\"\n\t} else {\n\t\treason = \"ScaleDownStabilized\"\n\t\tmessage = \"recent recommendations were higher than current one, applying the highest recent recommendation\"\n\t}\n\treturn recommendation, reason, message\n}","line":{"from":1095,"to":1154}} {"id":100004374,"name":"convertDesiredReplicasWithBehaviorRate","signature":"func (a *HorizontalController) convertDesiredReplicasWithBehaviorRate(args NormalizationArg) (int32, string, string)","file":"pkg/controller/podautoscaler/horizontal.go","code":"// convertDesiredReplicasWithBehaviorRate performs the actual normalization, given the constraint rate\n// It doesn't consider the stabilizationWindow, it is done separately\nfunc (a *HorizontalController) convertDesiredReplicasWithBehaviorRate(args NormalizationArg) (int32, string, string) {\n\tvar possibleLimitingReason, possibleLimitingMessage string\n\n\tif args.DesiredReplicas \u003e args.CurrentReplicas {\n\t\ta.scaleUpEventsLock.RLock()\n\t\tdefer a.scaleUpEventsLock.RUnlock()\n\t\ta.scaleDownEventsLock.RLock()\n\t\tdefer a.scaleDownEventsLock.RUnlock()\n\t\tscaleUpLimit := calculateScaleUpLimitWithScalingRules(args.CurrentReplicas, a.scaleUpEvents[args.Key], a.scaleDownEvents[args.Key], args.ScaleUpBehavior)\n\n\t\tif scaleUpLimit \u003c args.CurrentReplicas {\n\t\t\t// We shouldn't scale up further until the scaleUpEvents will be cleaned up\n\t\t\tscaleUpLimit = args.CurrentReplicas\n\t\t}\n\t\tmaximumAllowedReplicas := args.MaxReplicas\n\t\tif maximumAllowedReplicas \u003e scaleUpLimit {\n\t\t\tmaximumAllowedReplicas = scaleUpLimit\n\t\t\tpossibleLimitingReason = \"ScaleUpLimit\"\n\t\t\tpossibleLimitingMessage = \"the desired replica count is increasing faster than the maximum scale rate\"\n\t\t} else {\n\t\t\tpossibleLimitingReason = \"TooManyReplicas\"\n\t\t\tpossibleLimitingMessage = \"the desired replica count is more than the maximum replica count\"\n\t\t}\n\t\tif args.DesiredReplicas \u003e maximumAllowedReplicas {\n\t\t\treturn maximumAllowedReplicas, possibleLimitingReason, possibleLimitingMessage\n\t\t}\n\t} else if args.DesiredReplicas \u003c args.CurrentReplicas {\n\t\ta.scaleUpEventsLock.RLock()\n\t\tdefer a.scaleUpEventsLock.RUnlock()\n\t\ta.scaleDownEventsLock.RLock()\n\t\tdefer a.scaleDownEventsLock.RUnlock()\n\t\tscaleDownLimit := calculateScaleDownLimitWithBehaviors(args.CurrentReplicas, a.scaleUpEvents[args.Key], a.scaleDownEvents[args.Key], args.ScaleDownBehavior)\n\n\t\tif scaleDownLimit \u003e args.CurrentReplicas {\n\t\t\t// We shouldn't scale down further until the scaleDownEvents will be cleaned up\n\t\t\tscaleDownLimit = args.CurrentReplicas\n\t\t}\n\t\tminimumAllowedReplicas := args.MinReplicas\n\t\tif minimumAllowedReplicas \u003c scaleDownLimit {\n\t\t\tminimumAllowedReplicas = scaleDownLimit\n\t\t\tpossibleLimitingReason = \"ScaleDownLimit\"\n\t\t\tpossibleLimitingMessage = \"the desired replica count is decreasing faster than the maximum scale rate\"\n\t\t} else {\n\t\t\tpossibleLimitingMessage = \"the desired replica count is less than the minimum replica count\"\n\t\t\tpossibleLimitingReason = \"TooFewReplicas\"\n\t\t}\n\t\tif args.DesiredReplicas \u003c minimumAllowedReplicas {\n\t\t\treturn minimumAllowedReplicas, possibleLimitingReason, possibleLimitingMessage\n\t\t}\n\t}\n\treturn args.DesiredReplicas, \"DesiredWithinRange\", \"the desired count is within the acceptable range\"\n}","line":{"from":1156,"to":1209}} {"id":100004375,"name":"convertDesiredReplicasWithRules","signature":"func convertDesiredReplicasWithRules(currentReplicas, desiredReplicas, hpaMinReplicas, hpaMaxReplicas int32) (int32, string, string)","file":"pkg/controller/podautoscaler/horizontal.go","code":"// convertDesiredReplicas performs the actual normalization, without depending on `HorizontalController` or `HorizontalPodAutoscaler`\nfunc convertDesiredReplicasWithRules(currentReplicas, desiredReplicas, hpaMinReplicas, hpaMaxReplicas int32) (int32, string, string) {\n\n\tvar minimumAllowedReplicas int32\n\tvar maximumAllowedReplicas int32\n\n\tvar possibleLimitingCondition string\n\tvar possibleLimitingReason string\n\n\tminimumAllowedReplicas = hpaMinReplicas\n\n\t// Do not scaleup too much to prevent incorrect rapid increase of the number of master replicas caused by\n\t// bogus CPU usage report from heapster/kubelet (like in issue #32304).\n\tscaleUpLimit := calculateScaleUpLimit(currentReplicas)\n\n\tif hpaMaxReplicas \u003e scaleUpLimit {\n\t\tmaximumAllowedReplicas = scaleUpLimit\n\t\tpossibleLimitingCondition = \"ScaleUpLimit\"\n\t\tpossibleLimitingReason = \"the desired replica count is increasing faster than the maximum scale rate\"\n\t} else {\n\t\tmaximumAllowedReplicas = hpaMaxReplicas\n\t\tpossibleLimitingCondition = \"TooManyReplicas\"\n\t\tpossibleLimitingReason = \"the desired replica count is more than the maximum replica count\"\n\t}\n\n\tif desiredReplicas \u003c minimumAllowedReplicas {\n\t\tpossibleLimitingCondition = \"TooFewReplicas\"\n\t\tpossibleLimitingReason = \"the desired replica count is less than the minimum replica count\"\n\n\t\treturn minimumAllowedReplicas, possibleLimitingCondition, possibleLimitingReason\n\t} else if desiredReplicas \u003e maximumAllowedReplicas {\n\t\treturn maximumAllowedReplicas, possibleLimitingCondition, possibleLimitingReason\n\t}\n\n\treturn desiredReplicas, \"DesiredWithinRange\", \"the desired count is within the acceptable range\"\n}","line":{"from":1211,"to":1246}} {"id":100004376,"name":"calculateScaleUpLimit","signature":"func calculateScaleUpLimit(currentReplicas int32) int32","file":"pkg/controller/podautoscaler/horizontal.go","code":"func calculateScaleUpLimit(currentReplicas int32) int32 {\n\treturn int32(math.Max(scaleUpLimitFactor*float64(currentReplicas), scaleUpLimitMinimum))\n}","line":{"from":1248,"to":1250}} {"id":100004377,"name":"markScaleEventsOutdated","signature":"func markScaleEventsOutdated(scaleEvents []timestampedScaleEvent, longestPolicyPeriod int32)","file":"pkg/controller/podautoscaler/horizontal.go","code":"// markScaleEventsOutdated set 'outdated=true' flag for all scale events that are not used by any HPA object\nfunc markScaleEventsOutdated(scaleEvents []timestampedScaleEvent, longestPolicyPeriod int32) {\n\tperiod := time.Second * time.Duration(longestPolicyPeriod)\n\tcutoff := time.Now().Add(-period)\n\tfor i, event := range scaleEvents {\n\t\tif event.timestamp.Before(cutoff) {\n\t\t\t// outdated scale event are marked for later reuse\n\t\t\tscaleEvents[i].outdated = true\n\t\t}\n\t}\n}","line":{"from":1252,"to":1262}} {"id":100004378,"name":"getLongestPolicyPeriod","signature":"func getLongestPolicyPeriod(scalingRules *autoscalingv2.HPAScalingRules) int32","file":"pkg/controller/podautoscaler/horizontal.go","code":"func getLongestPolicyPeriod(scalingRules *autoscalingv2.HPAScalingRules) int32 {\n\tvar longestPolicyPeriod int32\n\tfor _, policy := range scalingRules.Policies {\n\t\tif policy.PeriodSeconds \u003e longestPolicyPeriod {\n\t\t\tlongestPolicyPeriod = policy.PeriodSeconds\n\t\t}\n\t}\n\treturn longestPolicyPeriod\n}","line":{"from":1264,"to":1272}} {"id":100004379,"name":"calculateScaleUpLimitWithScalingRules","signature":"func calculateScaleUpLimitWithScalingRules(currentReplicas int32, scaleUpEvents, scaleDownEvents []timestampedScaleEvent, scalingRules *autoscalingv2.HPAScalingRules) int32","file":"pkg/controller/podautoscaler/horizontal.go","code":"// calculateScaleUpLimitWithScalingRules returns the maximum number of pods that could be added for the given HPAScalingRules\nfunc calculateScaleUpLimitWithScalingRules(currentReplicas int32, scaleUpEvents, scaleDownEvents []timestampedScaleEvent, scalingRules *autoscalingv2.HPAScalingRules) int32 {\n\tvar result int32\n\tvar proposed int32\n\tvar selectPolicyFn func(int32, int32) int32\n\tif *scalingRules.SelectPolicy == autoscalingv2.DisabledPolicySelect {\n\t\treturn currentReplicas // Scaling is disabled\n\t} else if *scalingRules.SelectPolicy == autoscalingv2.MinChangePolicySelect {\n\t\tresult = math.MaxInt32\n\t\tselectPolicyFn = min // For scaling up, the lowest change ('min' policy) produces a minimum value\n\t} else {\n\t\tresult = math.MinInt32\n\t\tselectPolicyFn = max // Use the default policy otherwise to produce a highest possible change\n\t}\n\tfor _, policy := range scalingRules.Policies {\n\t\treplicasAddedInCurrentPeriod := getReplicasChangePerPeriod(policy.PeriodSeconds, scaleUpEvents)\n\t\treplicasDeletedInCurrentPeriod := getReplicasChangePerPeriod(policy.PeriodSeconds, scaleDownEvents)\n\t\tperiodStartReplicas := currentReplicas - replicasAddedInCurrentPeriod + replicasDeletedInCurrentPeriod\n\t\tif policy.Type == autoscalingv2.PodsScalingPolicy {\n\t\t\tproposed = periodStartReplicas + policy.Value\n\t\t} else if policy.Type == autoscalingv2.PercentScalingPolicy {\n\t\t\t// the proposal has to be rounded up because the proposed change might not increase the replica count causing the target to never scale up\n\t\t\tproposed = int32(math.Ceil(float64(periodStartReplicas) * (1 + float64(policy.Value)/100)))\n\t\t}\n\t\tresult = selectPolicyFn(result, proposed)\n\t}\n\treturn result\n}","line":{"from":1274,"to":1301}} {"id":100004380,"name":"calculateScaleDownLimitWithBehaviors","signature":"func calculateScaleDownLimitWithBehaviors(currentReplicas int32, scaleUpEvents, scaleDownEvents []timestampedScaleEvent, scalingRules *autoscalingv2.HPAScalingRules) int32","file":"pkg/controller/podautoscaler/horizontal.go","code":"// calculateScaleDownLimitWithBehavior returns the maximum number of pods that could be deleted for the given HPAScalingRules\nfunc calculateScaleDownLimitWithBehaviors(currentReplicas int32, scaleUpEvents, scaleDownEvents []timestampedScaleEvent, scalingRules *autoscalingv2.HPAScalingRules) int32 {\n\tvar result int32\n\tvar proposed int32\n\tvar selectPolicyFn func(int32, int32) int32\n\tif *scalingRules.SelectPolicy == autoscalingv2.DisabledPolicySelect {\n\t\treturn currentReplicas // Scaling is disabled\n\t} else if *scalingRules.SelectPolicy == autoscalingv2.MinChangePolicySelect {\n\t\tresult = math.MinInt32\n\t\tselectPolicyFn = max // For scaling down, the lowest change ('min' policy) produces a maximum value\n\t} else {\n\t\tresult = math.MaxInt32\n\t\tselectPolicyFn = min // Use the default policy otherwise to produce a highest possible change\n\t}\n\tfor _, policy := range scalingRules.Policies {\n\t\treplicasAddedInCurrentPeriod := getReplicasChangePerPeriod(policy.PeriodSeconds, scaleUpEvents)\n\t\treplicasDeletedInCurrentPeriod := getReplicasChangePerPeriod(policy.PeriodSeconds, scaleDownEvents)\n\t\tperiodStartReplicas := currentReplicas - replicasAddedInCurrentPeriod + replicasDeletedInCurrentPeriod\n\t\tif policy.Type == autoscalingv2.PodsScalingPolicy {\n\t\t\tproposed = periodStartReplicas - policy.Value\n\t\t} else if policy.Type == autoscalingv2.PercentScalingPolicy {\n\t\t\tproposed = int32(float64(periodStartReplicas) * (1 - float64(policy.Value)/100))\n\t\t}\n\t\tresult = selectPolicyFn(result, proposed)\n\t}\n\treturn result\n}","line":{"from":1303,"to":1329}} {"id":100004381,"name":"scaleForResourceMappings","signature":"func (a *HorizontalController) scaleForResourceMappings(ctx context.Context, namespace, name string, mappings []*apimeta.RESTMapping) (*autoscalingv1.Scale, schema.GroupResource, error)","file":"pkg/controller/podautoscaler/horizontal.go","code":"// scaleForResourceMappings attempts to fetch the scale for the\n// resource with the given name and namespace, trying each RESTMapping\n// in turn until a working one is found. If none work, the first error\n// is returned. It returns both the scale, as well as the group-resource from\n// the working mapping.\nfunc (a *HorizontalController) scaleForResourceMappings(ctx context.Context, namespace, name string, mappings []*apimeta.RESTMapping) (*autoscalingv1.Scale, schema.GroupResource, error) {\n\tvar firstErr error\n\tfor i, mapping := range mappings {\n\t\ttargetGR := mapping.Resource.GroupResource()\n\t\tscale, err := a.scaleNamespacer.Scales(namespace).Get(ctx, targetGR, name, metav1.GetOptions{})\n\t\tif err == nil {\n\t\t\treturn scale, targetGR, nil\n\t\t}\n\n\t\t// if this is the first error, remember it,\n\t\t// then go on and try other mappings until we find a good one\n\t\tif i == 0 {\n\t\t\tfirstErr = err\n\t\t}\n\t}\n\n\t// make sure we handle an empty set of mappings\n\tif firstErr == nil {\n\t\tfirstErr = fmt.Errorf(\"unrecognized resource\")\n\t}\n\n\treturn nil, schema.GroupResource{}, firstErr\n}","line":{"from":1331,"to":1358}} {"id":100004382,"name":"setCurrentReplicasInStatus","signature":"func (a *HorizontalController) setCurrentReplicasInStatus(hpa *autoscalingv2.HorizontalPodAutoscaler, currentReplicas int32)","file":"pkg/controller/podautoscaler/horizontal.go","code":"// setCurrentReplicasInStatus sets the current replica count in the status of the HPA.\nfunc (a *HorizontalController) setCurrentReplicasInStatus(hpa *autoscalingv2.HorizontalPodAutoscaler, currentReplicas int32) {\n\ta.setStatus(hpa, currentReplicas, hpa.Status.DesiredReplicas, hpa.Status.CurrentMetrics, false)\n}","line":{"from":1360,"to":1363}} {"id":100004383,"name":"setStatus","signature":"func (a *HorizontalController) setStatus(hpa *autoscalingv2.HorizontalPodAutoscaler, currentReplicas, desiredReplicas int32, metricStatuses []autoscalingv2.MetricStatus, rescale bool)","file":"pkg/controller/podautoscaler/horizontal.go","code":"// setStatus recreates the status of the given HPA, updating the current and\n// desired replicas, as well as the metric statuses\nfunc (a *HorizontalController) setStatus(hpa *autoscalingv2.HorizontalPodAutoscaler, currentReplicas, desiredReplicas int32, metricStatuses []autoscalingv2.MetricStatus, rescale bool) {\n\thpa.Status = autoscalingv2.HorizontalPodAutoscalerStatus{\n\t\tCurrentReplicas: currentReplicas,\n\t\tDesiredReplicas: desiredReplicas,\n\t\tLastScaleTime: hpa.Status.LastScaleTime,\n\t\tCurrentMetrics: metricStatuses,\n\t\tConditions: hpa.Status.Conditions,\n\t}\n\n\tif rescale {\n\t\tnow := metav1.NewTime(time.Now())\n\t\thpa.Status.LastScaleTime = \u0026now\n\t}\n}","line":{"from":1365,"to":1380}} {"id":100004384,"name":"updateStatusIfNeeded","signature":"func (a *HorizontalController) updateStatusIfNeeded(ctx context.Context, oldStatus *autoscalingv2.HorizontalPodAutoscalerStatus, newHPA *autoscalingv2.HorizontalPodAutoscaler) error","file":"pkg/controller/podautoscaler/horizontal.go","code":"// updateStatusIfNeeded calls updateStatus only if the status of the new HPA is not the same as the old status\nfunc (a *HorizontalController) updateStatusIfNeeded(ctx context.Context, oldStatus *autoscalingv2.HorizontalPodAutoscalerStatus, newHPA *autoscalingv2.HorizontalPodAutoscaler) error {\n\t// skip a write if we wouldn't need to update\n\tif apiequality.Semantic.DeepEqual(oldStatus, \u0026newHPA.Status) {\n\t\treturn nil\n\t}\n\treturn a.updateStatus(ctx, newHPA)\n}","line":{"from":1382,"to":1389}} {"id":100004385,"name":"updateStatus","signature":"func (a *HorizontalController) updateStatus(ctx context.Context, hpa *autoscalingv2.HorizontalPodAutoscaler) error","file":"pkg/controller/podautoscaler/horizontal.go","code":"// updateStatus actually does the update request for the status of the given HPA\nfunc (a *HorizontalController) updateStatus(ctx context.Context, hpa *autoscalingv2.HorizontalPodAutoscaler) error {\n\t_, err := a.hpaNamespacer.HorizontalPodAutoscalers(hpa.Namespace).UpdateStatus(ctx, hpa, metav1.UpdateOptions{})\n\tif err != nil {\n\t\ta.eventRecorder.Event(hpa, v1.EventTypeWarning, \"FailedUpdateStatus\", err.Error())\n\t\treturn fmt.Errorf(\"failed to update status for %s: %v\", hpa.Name, err)\n\t}\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(2).Info(\"Successfully updated status\", \"HPA\", klog.KObj(hpa))\n\treturn nil\n}","line":{"from":1391,"to":1401}} {"id":100004386,"name":"setCondition","signature":"func setCondition(hpa *autoscalingv2.HorizontalPodAutoscaler, conditionType autoscalingv2.HorizontalPodAutoscalerConditionType, status v1.ConditionStatus, reason, message string, args ...interface{})","file":"pkg/controller/podautoscaler/horizontal.go","code":"// setCondition sets the specific condition type on the given HPA to the specified value with the given reason\n// and message. The message and args are treated like a format string. The condition will be added if it is\n// not present.\nfunc setCondition(hpa *autoscalingv2.HorizontalPodAutoscaler, conditionType autoscalingv2.HorizontalPodAutoscalerConditionType, status v1.ConditionStatus, reason, message string, args ...interface{}) {\n\thpa.Status.Conditions = setConditionInList(hpa.Status.Conditions, conditionType, status, reason, message, args...)\n}","line":{"from":1403,"to":1408}} {"id":100004387,"name":"setConditionInList","signature":"func setConditionInList(inputList []autoscalingv2.HorizontalPodAutoscalerCondition, conditionType autoscalingv2.HorizontalPodAutoscalerConditionType, status v1.ConditionStatus, reason, message string, args ...interface{}) []autoscalingv2.HorizontalPodAutoscalerCondition","file":"pkg/controller/podautoscaler/horizontal.go","code":"// setConditionInList sets the specific condition type on the given HPA to the specified value with the given\n// reason and message. The message and args are treated like a format string. The condition will be added if\n// it is not present. The new list will be returned.\nfunc setConditionInList(inputList []autoscalingv2.HorizontalPodAutoscalerCondition, conditionType autoscalingv2.HorizontalPodAutoscalerConditionType, status v1.ConditionStatus, reason, message string, args ...interface{}) []autoscalingv2.HorizontalPodAutoscalerCondition {\n\tresList := inputList\n\tvar existingCond *autoscalingv2.HorizontalPodAutoscalerCondition\n\tfor i, condition := range resList {\n\t\tif condition.Type == conditionType {\n\t\t\t// can't take a pointer to an iteration variable\n\t\t\texistingCond = \u0026resList[i]\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif existingCond == nil {\n\t\tresList = append(resList, autoscalingv2.HorizontalPodAutoscalerCondition{\n\t\t\tType: conditionType,\n\t\t})\n\t\texistingCond = \u0026resList[len(resList)-1]\n\t}\n\n\tif existingCond.Status != status {\n\t\texistingCond.LastTransitionTime = metav1.Now()\n\t}\n\n\texistingCond.Status = status\n\texistingCond.Reason = reason\n\texistingCond.Message = fmt.Sprintf(message, args...)\n\n\treturn resList\n}","line":{"from":1410,"to":1440}} {"id":100004388,"name":"max","signature":"func max(a, b int32) int32","file":"pkg/controller/podautoscaler/horizontal.go","code":"func max(a, b int32) int32 {\n\tif a \u003e= b {\n\t\treturn a\n\t}\n\treturn b\n}","line":{"from":1442,"to":1447}} {"id":100004389,"name":"min","signature":"func min(a, b int32) int32","file":"pkg/controller/podautoscaler/horizontal.go","code":"func min(a, b int32) int32 {\n\tif a \u003c= b {\n\t\treturn a\n\t}\n\treturn b\n}","line":{"from":1449,"to":1454}} {"id":100004390,"name":"NewRESTMetricsClient","signature":"func NewRESTMetricsClient(resourceClient resourceclient.PodMetricsesGetter, customClient customclient.CustomMetricsClient, externalClient externalclient.ExternalMetricsClient) MetricsClient","file":"pkg/controller/podautoscaler/metrics/client.go","code":"func NewRESTMetricsClient(resourceClient resourceclient.PodMetricsesGetter, customClient customclient.CustomMetricsClient, externalClient externalclient.ExternalMetricsClient) MetricsClient {\n\treturn \u0026restMetricsClient{\n\t\t\u0026resourceMetricsClient{resourceClient},\n\t\t\u0026customMetricsClient{customClient},\n\t\t\u0026externalMetricsClient{externalClient},\n\t}\n}","line":{"from":42,"to":48}} {"id":100004391,"name":"GetResourceMetric","signature":"func (c *resourceMetricsClient) GetResourceMetric(ctx context.Context, resource v1.ResourceName, namespace string, selector labels.Selector, container string) (PodMetricsInfo, time.Time, error)","file":"pkg/controller/podautoscaler/metrics/client.go","code":"// GetResourceMetric gets the given resource metric (and an associated oldest timestamp)\n// for all pods matching the specified selector in the given namespace\nfunc (c *resourceMetricsClient) GetResourceMetric(ctx context.Context, resource v1.ResourceName, namespace string, selector labels.Selector, container string) (PodMetricsInfo, time.Time, error) {\n\tmetrics, err := c.client.PodMetricses(namespace).List(ctx, metav1.ListOptions{LabelSelector: selector.String()})\n\tif err != nil {\n\t\treturn nil, time.Time{}, fmt.Errorf(\"unable to fetch metrics from resource metrics API: %v\", err)\n\t}\n\n\tif len(metrics.Items) == 0 {\n\t\treturn nil, time.Time{}, fmt.Errorf(\"no metrics returned from resource metrics API\")\n\t}\n\tvar res PodMetricsInfo\n\tif container != \"\" {\n\t\tres, err = getContainerMetrics(metrics.Items, resource, container)\n\t\tif err != nil {\n\t\t\treturn nil, time.Time{}, fmt.Errorf(\"failed to get container metrics: %v\", err)\n\t\t}\n\t} else {\n\t\tres = getPodMetrics(ctx, metrics.Items, resource)\n\t}\n\ttimestamp := metrics.Items[0].Timestamp.Time\n\treturn res, timestamp, nil\n}","line":{"from":65,"to":87}} {"id":100004392,"name":"getContainerMetrics","signature":"func getContainerMetrics(rawMetrics []metricsapi.PodMetrics, resource v1.ResourceName, container string) (PodMetricsInfo, error)","file":"pkg/controller/podautoscaler/metrics/client.go","code":"func getContainerMetrics(rawMetrics []metricsapi.PodMetrics, resource v1.ResourceName, container string) (PodMetricsInfo, error) {\n\tres := make(PodMetricsInfo, len(rawMetrics))\n\tfor _, m := range rawMetrics {\n\t\tcontainerFound := false\n\t\tfor _, c := range m.Containers {\n\t\t\tif c.Name == container {\n\t\t\t\tcontainerFound = true\n\t\t\t\tif val, resFound := c.Usage[resource]; resFound {\n\t\t\t\t\tres[m.Name] = PodMetric{\n\t\t\t\t\t\tTimestamp: m.Timestamp.Time,\n\t\t\t\t\t\tWindow: m.Window.Duration,\n\t\t\t\t\t\tValue: val.MilliValue(),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !containerFound {\n\t\t\treturn nil, fmt.Errorf(\"container %s not present in metrics for pod %s/%s\", container, m.Namespace, m.Name)\n\t\t}\n\t}\n\treturn res, nil\n}","line":{"from":89,"to":111}} {"id":100004393,"name":"getPodMetrics","signature":"func getPodMetrics(ctx context.Context, rawMetrics []metricsapi.PodMetrics, resource v1.ResourceName) PodMetricsInfo","file":"pkg/controller/podautoscaler/metrics/client.go","code":"func getPodMetrics(ctx context.Context, rawMetrics []metricsapi.PodMetrics, resource v1.ResourceName) PodMetricsInfo {\n\tres := make(PodMetricsInfo, len(rawMetrics))\n\tfor _, m := range rawMetrics {\n\t\tpodSum := int64(0)\n\t\tmissing := len(m.Containers) == 0\n\t\tfor _, c := range m.Containers {\n\t\t\tresValue, found := c.Usage[resource]\n\t\t\tif !found {\n\t\t\t\tmissing = true\n\t\t\t\tklog.FromContext(ctx).V(2).Info(\"Missing resource metric\", \"resourceMetric\", resource, \"pod\", klog.KRef(m.Namespace, m.Name))\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tpodSum += resValue.MilliValue()\n\t\t}\n\t\tif !missing {\n\t\t\tres[m.Name] = PodMetric{\n\t\t\t\tTimestamp: m.Timestamp.Time,\n\t\t\t\tWindow: m.Window.Duration,\n\t\t\t\tValue: podSum,\n\t\t\t}\n\t\t}\n\t}\n\treturn res\n}","line":{"from":113,"to":136}} {"id":100004394,"name":"GetRawMetric","signature":"func (c *customMetricsClient) GetRawMetric(metricName string, namespace string, selector labels.Selector, metricSelector labels.Selector) (PodMetricsInfo, time.Time, error)","file":"pkg/controller/podautoscaler/metrics/client.go","code":"// GetRawMetric gets the given metric (and an associated oldest timestamp)\n// for all pods matching the specified selector in the given namespace\nfunc (c *customMetricsClient) GetRawMetric(metricName string, namespace string, selector labels.Selector, metricSelector labels.Selector) (PodMetricsInfo, time.Time, error) {\n\tmetrics, err := c.client.NamespacedMetrics(namespace).GetForObjects(schema.GroupKind{Kind: \"Pod\"}, selector, metricName, metricSelector)\n\tif err != nil {\n\t\treturn nil, time.Time{}, fmt.Errorf(\"unable to fetch metrics from custom metrics API: %v\", err)\n\t}\n\n\tif len(metrics.Items) == 0 {\n\t\treturn nil, time.Time{}, fmt.Errorf(\"no metrics returned from custom metrics API\")\n\t}\n\n\tres := make(PodMetricsInfo, len(metrics.Items))\n\tfor _, m := range metrics.Items {\n\t\twindow := metricServerDefaultMetricWindow\n\t\tif m.WindowSeconds != nil {\n\t\t\twindow = time.Duration(*m.WindowSeconds) * time.Second\n\t\t}\n\t\tres[m.DescribedObject.Name] = PodMetric{\n\t\t\tTimestamp: m.Timestamp.Time,\n\t\t\tWindow: window,\n\t\t\tValue: int64(m.Value.MilliValue()),\n\t\t}\n\n\t\tm.Value.MilliValue()\n\t}\n\n\ttimestamp := metrics.Items[0].Timestamp.Time\n\n\treturn res, timestamp, nil\n}","line":{"from":144,"to":174}} {"id":100004395,"name":"GetObjectMetric","signature":"func (c *customMetricsClient) GetObjectMetric(metricName string, namespace string, objectRef *autoscaling.CrossVersionObjectReference, metricSelector labels.Selector) (int64, time.Time, error)","file":"pkg/controller/podautoscaler/metrics/client.go","code":"// GetObjectMetric gets the given metric (and an associated timestamp) for the given\n// object in the given namespace\nfunc (c *customMetricsClient) GetObjectMetric(metricName string, namespace string, objectRef *autoscaling.CrossVersionObjectReference, metricSelector labels.Selector) (int64, time.Time, error) {\n\tgvk := schema.FromAPIVersionAndKind(objectRef.APIVersion, objectRef.Kind)\n\tvar metricValue *customapi.MetricValue\n\tvar err error\n\tif gvk.Kind == \"Namespace\" \u0026\u0026 gvk.Group == \"\" {\n\t\t// handle namespace separately\n\t\t// NB: we ignore namespace name here, since CrossVersionObjectReference isn't\n\t\t// supposed to allow you to escape your namespace\n\t\tmetricValue, err = c.client.RootScopedMetrics().GetForObject(gvk.GroupKind(), namespace, metricName, metricSelector)\n\t} else {\n\t\tmetricValue, err = c.client.NamespacedMetrics(namespace).GetForObject(gvk.GroupKind(), objectRef.Name, metricName, metricSelector)\n\t}\n\n\tif err != nil {\n\t\treturn 0, time.Time{}, fmt.Errorf(\"unable to fetch metrics from custom metrics API: %v\", err)\n\t}\n\n\treturn metricValue.Value.MilliValue(), metricValue.Timestamp.Time, nil\n}","line":{"from":176,"to":196}} {"id":100004396,"name":"GetExternalMetric","signature":"func (c *externalMetricsClient) GetExternalMetric(metricName, namespace string, selector labels.Selector) ([]int64, time.Time, error)","file":"pkg/controller/podautoscaler/metrics/client.go","code":"// GetExternalMetric gets all the values of a given external metric\n// that match the specified selector.\nfunc (c *externalMetricsClient) GetExternalMetric(metricName, namespace string, selector labels.Selector) ([]int64, time.Time, error) {\n\tmetrics, err := c.client.NamespacedMetrics(namespace).List(metricName, selector)\n\tif err != nil {\n\t\treturn []int64{}, time.Time{}, fmt.Errorf(\"unable to fetch metrics from external metrics API: %v\", err)\n\t}\n\n\tif len(metrics.Items) == 0 {\n\t\treturn nil, time.Time{}, fmt.Errorf(\"no metrics returned from external metrics API\")\n\t}\n\n\tres := make([]int64, 0)\n\tfor _, m := range metrics.Items {\n\t\tres = append(res, m.Value.MilliValue())\n\t}\n\ttimestamp := metrics.Items[0].Timestamp.Time\n\treturn res, timestamp, nil\n}","line":{"from":204,"to":222}} {"id":100004397,"name":"GetResourceUtilizationRatio","signature":"func GetResourceUtilizationRatio(metrics PodMetricsInfo, requests map[string]int64, targetUtilization int32) (utilizationRatio float64, currentUtilization int32, rawAverageValue int64, err error)","file":"pkg/controller/podautoscaler/metrics/utilization.go","code":"// GetResourceUtilizationRatio takes in a set of metrics, a set of matching requests,\n// and a target utilization percentage, and calculates the ratio of\n// desired to actual utilization (returning that, the actual utilization, and the raw average value)\nfunc GetResourceUtilizationRatio(metrics PodMetricsInfo, requests map[string]int64, targetUtilization int32) (utilizationRatio float64, currentUtilization int32, rawAverageValue int64, err error) {\n\tmetricsTotal := int64(0)\n\trequestsTotal := int64(0)\n\tnumEntries := 0\n\n\tfor podName, metric := range metrics {\n\t\trequest, hasRequest := requests[podName]\n\t\tif !hasRequest {\n\t\t\t// we check for missing requests elsewhere, so assuming missing requests == extraneous metrics\n\t\t\tcontinue\n\t\t}\n\n\t\tmetricsTotal += metric.Value\n\t\trequestsTotal += request\n\t\tnumEntries++\n\t}\n\n\t// if the set of requests is completely disjoint from the set of metrics,\n\t// then we could have an issue where the requests total is zero\n\tif requestsTotal == 0 {\n\t\treturn 0, 0, 0, fmt.Errorf(\"no metrics returned matched known pods\")\n\t}\n\n\tcurrentUtilization = int32((metricsTotal * 100) / requestsTotal)\n\n\treturn float64(currentUtilization) / float64(targetUtilization), currentUtilization, metricsTotal / int64(numEntries), nil\n}","line":{"from":23,"to":52}} {"id":100004398,"name":"GetMetricUsageRatio","signature":"func GetMetricUsageRatio(metrics PodMetricsInfo, targetUsage int64) (usageRatio float64, currentUsage int64)","file":"pkg/controller/podautoscaler/metrics/utilization.go","code":"// GetMetricUsageRatio takes in a set of metrics and a target usage value,\n// and calculates the ratio of desired to actual usage\n// (returning that and the actual usage)\nfunc GetMetricUsageRatio(metrics PodMetricsInfo, targetUsage int64) (usageRatio float64, currentUsage int64) {\n\tmetricsTotal := int64(0)\n\tfor _, metric := range metrics {\n\t\tmetricsTotal += metric.Value\n\t}\n\n\tcurrentUsage = metricsTotal / int64(len(metrics))\n\n\treturn float64(currentUsage) / float64(targetUsage), currentUsage\n}","line":{"from":54,"to":66}} {"id":100004399,"name":"Register","signature":"func Register()","file":"pkg/controller/podautoscaler/monitor/metrics.go","code":"// Register all metrics.\nfunc Register() {\n\t// Register the metrics.\n\tregister.Do(func() {\n\t\tregisterMetrics(metricsList...)\n\t})\n}","line":{"from":75,"to":81}} {"id":100004400,"name":"registerMetrics","signature":"func registerMetrics(extraMetrics ...metrics.Registerable)","file":"pkg/controller/podautoscaler/monitor/metrics.go","code":"// RegisterMetrics registers a list of metrics.\nfunc registerMetrics(extraMetrics ...metrics.Registerable) {\n\tfor _, metric := range extraMetrics {\n\t\tlegacyregistry.MustRegister(metric)\n\t}\n}","line":{"from":83,"to":88}} {"id":100004401,"name":"New","signature":"func New() Monitor","file":"pkg/controller/podautoscaler/monitor/monitor.go","code":"func New() Monitor {\n\treturn \u0026monitor{}\n}","line":{"from":48,"to":50}} {"id":100004402,"name":"ObserveReconciliationResult","signature":"func (r *monitor) ObserveReconciliationResult(action ActionLabel, err ErrorLabel, duration time.Duration)","file":"pkg/controller/podautoscaler/monitor/monitor.go","code":"// ObserveReconciliationResult observes some metrics from a reconciliation result.\nfunc (r *monitor) ObserveReconciliationResult(action ActionLabel, err ErrorLabel, duration time.Duration) {\n\treconciliationsTotal.WithLabelValues(string(action), string(err)).Inc()\n\treconciliationsDuration.WithLabelValues(string(action), string(err)).Observe(duration.Seconds())\n}","line":{"from":52,"to":56}} {"id":100004403,"name":"ObserveMetricComputationResult","signature":"func (r *monitor) ObserveMetricComputationResult(action ActionLabel, err ErrorLabel, duration time.Duration, metricType v2.MetricSourceType)","file":"pkg/controller/podautoscaler/monitor/monitor.go","code":"// ObserveMetricComputationResult observes some metrics from a metric computation result.\nfunc (r *monitor) ObserveMetricComputationResult(action ActionLabel, err ErrorLabel, duration time.Duration, metricType v2.MetricSourceType) {\n\tmetricComputationTotal.WithLabelValues(string(action), string(err), string(metricType)).Inc()\n\tmetricComputationDuration.WithLabelValues(string(action), string(err), string(metricType)).Observe(duration.Seconds())\n}","line":{"from":58,"to":62}} {"id":100004404,"name":"NewFixedItemIntervalRateLimiter","signature":"func NewFixedItemIntervalRateLimiter(interval time.Duration) workqueue.RateLimiter","file":"pkg/controller/podautoscaler/rate_limiters.go","code":"// NewFixedItemIntervalRateLimiter creates a new instance of a RateLimiter using a fixed interval\nfunc NewFixedItemIntervalRateLimiter(interval time.Duration) workqueue.RateLimiter {\n\treturn \u0026FixedItemIntervalRateLimiter{\n\t\tinterval: interval,\n\t}\n}","line":{"from":32,"to":37}} {"id":100004405,"name":"When","signature":"func (r *FixedItemIntervalRateLimiter) When(item interface{}) time.Duration","file":"pkg/controller/podautoscaler/rate_limiters.go","code":"// When returns the interval of the rate limiter\nfunc (r *FixedItemIntervalRateLimiter) When(item interface{}) time.Duration {\n\treturn r.interval\n}","line":{"from":39,"to":42}} {"id":100004406,"name":"NumRequeues","signature":"func (r *FixedItemIntervalRateLimiter) NumRequeues(item interface{}) int","file":"pkg/controller/podautoscaler/rate_limiters.go","code":"// NumRequeues returns back how many failures the item has had\nfunc (r *FixedItemIntervalRateLimiter) NumRequeues(item interface{}) int {\n\treturn 1\n}","line":{"from":44,"to":47}} {"id":100004407,"name":"Forget","signature":"func (r *FixedItemIntervalRateLimiter) Forget(item interface{})","file":"pkg/controller/podautoscaler/rate_limiters.go","code":"// Forget indicates that an item is finished being retried.\nfunc (r *FixedItemIntervalRateLimiter) Forget(item interface{}) {\n}","line":{"from":49,"to":51}} {"id":100004408,"name":"NewDefaultHPARateLimiter","signature":"func NewDefaultHPARateLimiter(interval time.Duration) workqueue.RateLimiter","file":"pkg/controller/podautoscaler/rate_limiters.go","code":"// NewDefaultHPARateLimiter creates a rate limiter which limits overall (as per the\n// default controller rate limiter), as well as per the resync interval\nfunc NewDefaultHPARateLimiter(interval time.Duration) workqueue.RateLimiter {\n\treturn NewFixedItemIntervalRateLimiter(interval)\n}","line":{"from":53,"to":57}} {"id":100004409,"name":"NewReplicaCalculator","signature":"func NewReplicaCalculator(metricsClient metricsclient.MetricsClient, podLister corelisters.PodLister, tolerance float64, cpuInitializationPeriod, delayOfInitialReadinessStatus time.Duration) *ReplicaCalculator","file":"pkg/controller/podautoscaler/replica_calculator.go","code":"// NewReplicaCalculator creates a new ReplicaCalculator and passes all necessary information to the new instance\nfunc NewReplicaCalculator(metricsClient metricsclient.MetricsClient, podLister corelisters.PodLister, tolerance float64, cpuInitializationPeriod, delayOfInitialReadinessStatus time.Duration) *ReplicaCalculator {\n\treturn \u0026ReplicaCalculator{\n\t\tmetricsClient: metricsClient,\n\t\tpodLister: podLister,\n\t\ttolerance: tolerance,\n\t\tcpuInitializationPeriod: cpuInitializationPeriod,\n\t\tdelayOfInitialReadinessStatus: delayOfInitialReadinessStatus,\n\t}\n}","line":{"from":52,"to":61}} {"id":100004410,"name":"GetResourceReplicas","signature":"func (c *ReplicaCalculator) GetResourceReplicas(ctx context.Context, currentReplicas int32, targetUtilization int32, resource v1.ResourceName, namespace string, selector labels.Selector, container string) (replicaCount int32, utilization int32, rawUtilization int64, timestamp time.Time, err error)","file":"pkg/controller/podautoscaler/replica_calculator.go","code":"// GetResourceReplicas calculates the desired replica count based on a target resource utilization percentage\n// of the given resource for pods matching the given selector in the given namespace, and the current replica count\nfunc (c *ReplicaCalculator) GetResourceReplicas(ctx context.Context, currentReplicas int32, targetUtilization int32, resource v1.ResourceName, namespace string, selector labels.Selector, container string) (replicaCount int32, utilization int32, rawUtilization int64, timestamp time.Time, err error) {\n\tmetrics, timestamp, err := c.metricsClient.GetResourceMetric(ctx, resource, namespace, selector, container)\n\tif err != nil {\n\t\treturn 0, 0, 0, time.Time{}, fmt.Errorf(\"unable to get metrics for resource %s: %v\", resource, err)\n\t}\n\tpodList, err := c.podLister.Pods(namespace).List(selector)\n\tif err != nil {\n\t\treturn 0, 0, 0, time.Time{}, fmt.Errorf(\"unable to get pods while calculating replica count: %v\", err)\n\t}\n\tif len(podList) == 0 {\n\t\treturn 0, 0, 0, time.Time{}, fmt.Errorf(\"no pods returned by selector while calculating replica count\")\n\t}\n\n\treadyPodCount, unreadyPods, missingPods, ignoredPods := groupPods(podList, metrics, resource, c.cpuInitializationPeriod, c.delayOfInitialReadinessStatus)\n\tremoveMetricsForPods(metrics, ignoredPods)\n\tremoveMetricsForPods(metrics, unreadyPods)\n\tif len(metrics) == 0 {\n\t\treturn 0, 0, 0, time.Time{}, fmt.Errorf(\"did not receive metrics for targeted pods (pods might be unready)\")\n\t}\n\n\trequests, err := calculatePodRequests(podList, container, resource)\n\tif err != nil {\n\t\treturn 0, 0, 0, time.Time{}, err\n\t}\n\n\tusageRatio, utilization, rawUtilization, err := metricsclient.GetResourceUtilizationRatio(metrics, requests, targetUtilization)\n\tif err != nil {\n\t\treturn 0, 0, 0, time.Time{}, err\n\t}\n\n\tscaleUpWithUnready := len(unreadyPods) \u003e 0 \u0026\u0026 usageRatio \u003e 1.0\n\tif !scaleUpWithUnready \u0026\u0026 len(missingPods) == 0 {\n\t\tif math.Abs(1.0-usageRatio) \u003c= c.tolerance {\n\t\t\t// return the current replicas if the change would be too small\n\t\t\treturn currentReplicas, utilization, rawUtilization, timestamp, nil\n\t\t}\n\n\t\t// if we don't have any unready or missing pods, we can calculate the new replica count now\n\t\treturn int32(math.Ceil(usageRatio * float64(readyPodCount))), utilization, rawUtilization, timestamp, nil\n\t}\n\n\tif len(missingPods) \u003e 0 {\n\t\tif usageRatio \u003c 1.0 {\n\t\t\t// on a scale-down, treat missing pods as using 100% (all) of the resource request\n\t\t\t// or the utilization target for targets higher than 100%\n\t\t\tfallbackUtilization := int64(max(100, targetUtilization))\n\t\t\tfor podName := range missingPods {\n\t\t\t\tmetrics[podName] = metricsclient.PodMetric{Value: requests[podName] * fallbackUtilization / 100}\n\t\t\t}\n\t\t} else if usageRatio \u003e 1.0 {\n\t\t\t// on a scale-up, treat missing pods as using 0% of the resource request\n\t\t\tfor podName := range missingPods {\n\t\t\t\tmetrics[podName] = metricsclient.PodMetric{Value: 0}\n\t\t\t}\n\t\t}\n\t}\n\n\tif scaleUpWithUnready {\n\t\t// on a scale-up, treat unready pods as using 0% of the resource request\n\t\tfor podName := range unreadyPods {\n\t\t\tmetrics[podName] = metricsclient.PodMetric{Value: 0}\n\t\t}\n\t}\n\n\t// re-run the utilization calculation with our new numbers\n\tnewUsageRatio, _, _, err := metricsclient.GetResourceUtilizationRatio(metrics, requests, targetUtilization)\n\tif err != nil {\n\t\treturn 0, utilization, rawUtilization, time.Time{}, err\n\t}\n\n\tif math.Abs(1.0-newUsageRatio) \u003c= c.tolerance || (usageRatio \u003c 1.0 \u0026\u0026 newUsageRatio \u003e 1.0) || (usageRatio \u003e 1.0 \u0026\u0026 newUsageRatio \u003c 1.0) {\n\t\t// return the current replicas if the change would be too small,\n\t\t// or if the new usage ratio would cause a change in scale direction\n\t\treturn currentReplicas, utilization, rawUtilization, timestamp, nil\n\t}\n\n\tnewReplicas := int32(math.Ceil(newUsageRatio * float64(len(metrics))))\n\tif (newUsageRatio \u003c 1.0 \u0026\u0026 newReplicas \u003e currentReplicas) || (newUsageRatio \u003e 1.0 \u0026\u0026 newReplicas \u003c currentReplicas) {\n\t\t// return the current replicas if the change of metrics length would cause a change in scale direction\n\t\treturn currentReplicas, utilization, rawUtilization, timestamp, nil\n\t}\n\n\t// return the result, where the number of replicas considered is\n\t// however many replicas factored into our calculation\n\treturn newReplicas, utilization, rawUtilization, timestamp, nil\n}","line":{"from":63,"to":150}} {"id":100004411,"name":"GetRawResourceReplicas","signature":"func (c *ReplicaCalculator) GetRawResourceReplicas(ctx context.Context, currentReplicas int32, targetUsage int64, resource v1.ResourceName, namespace string, selector labels.Selector, container string) (replicaCount int32, usage int64, timestamp time.Time, err error)","file":"pkg/controller/podautoscaler/replica_calculator.go","code":"// GetRawResourceReplicas calculates the desired replica count based on a target resource usage (as a raw milli-value)\n// for pods matching the given selector in the given namespace, and the current replica count\nfunc (c *ReplicaCalculator) GetRawResourceReplicas(ctx context.Context, currentReplicas int32, targetUsage int64, resource v1.ResourceName, namespace string, selector labels.Selector, container string) (replicaCount int32, usage int64, timestamp time.Time, err error) {\n\tmetrics, timestamp, err := c.metricsClient.GetResourceMetric(ctx, resource, namespace, selector, container)\n\tif err != nil {\n\t\treturn 0, 0, time.Time{}, fmt.Errorf(\"unable to get metrics for resource %s: %v\", resource, err)\n\t}\n\n\treplicaCount, usage, err = c.calcPlainMetricReplicas(metrics, currentReplicas, targetUsage, namespace, selector, resource)\n\treturn replicaCount, usage, timestamp, err\n}","line":{"from":152,"to":162}} {"id":100004412,"name":"GetMetricReplicas","signature":"func (c *ReplicaCalculator) GetMetricReplicas(currentReplicas int32, targetUsage int64, metricName string, namespace string, selector labels.Selector, metricSelector labels.Selector) (replicaCount int32, usage int64, timestamp time.Time, err error)","file":"pkg/controller/podautoscaler/replica_calculator.go","code":"// GetMetricReplicas calculates the desired replica count based on a target metric usage\n// (as a milli-value) for pods matching the given selector in the given namespace, and the\n// current replica count\nfunc (c *ReplicaCalculator) GetMetricReplicas(currentReplicas int32, targetUsage int64, metricName string, namespace string, selector labels.Selector, metricSelector labels.Selector) (replicaCount int32, usage int64, timestamp time.Time, err error) {\n\tmetrics, timestamp, err := c.metricsClient.GetRawMetric(metricName, namespace, selector, metricSelector)\n\tif err != nil {\n\t\treturn 0, 0, time.Time{}, fmt.Errorf(\"unable to get metric %s: %v\", metricName, err)\n\t}\n\n\treplicaCount, usage, err = c.calcPlainMetricReplicas(metrics, currentReplicas, targetUsage, namespace, selector, v1.ResourceName(\"\"))\n\treturn replicaCount, usage, timestamp, err\n}","line":{"from":164,"to":175}} {"id":100004413,"name":"calcPlainMetricReplicas","signature":"func (c *ReplicaCalculator) calcPlainMetricReplicas(metrics metricsclient.PodMetricsInfo, currentReplicas int32, targetUsage int64, namespace string, selector labels.Selector, resource v1.ResourceName) (replicaCount int32, usage int64, err error)","file":"pkg/controller/podautoscaler/replica_calculator.go","code":"// calcPlainMetricReplicas calculates the desired replicas for plain (i.e. non-utilization percentage) metrics.\nfunc (c *ReplicaCalculator) calcPlainMetricReplicas(metrics metricsclient.PodMetricsInfo, currentReplicas int32, targetUsage int64, namespace string, selector labels.Selector, resource v1.ResourceName) (replicaCount int32, usage int64, err error) {\n\n\tpodList, err := c.podLister.Pods(namespace).List(selector)\n\tif err != nil {\n\t\treturn 0, 0, fmt.Errorf(\"unable to get pods while calculating replica count: %v\", err)\n\t}\n\n\tif len(podList) == 0 {\n\t\treturn 0, 0, fmt.Errorf(\"no pods returned by selector while calculating replica count\")\n\t}\n\n\treadyPodCount, unreadyPods, missingPods, ignoredPods := groupPods(podList, metrics, resource, c.cpuInitializationPeriod, c.delayOfInitialReadinessStatus)\n\tremoveMetricsForPods(metrics, ignoredPods)\n\tremoveMetricsForPods(metrics, unreadyPods)\n\n\tif len(metrics) == 0 {\n\t\treturn 0, 0, fmt.Errorf(\"did not receive metrics for targeted pods (pods might be unready)\")\n\t}\n\n\tusageRatio, usage := metricsclient.GetMetricUsageRatio(metrics, targetUsage)\n\n\tscaleUpWithUnready := len(unreadyPods) \u003e 0 \u0026\u0026 usageRatio \u003e 1.0\n\n\tif !scaleUpWithUnready \u0026\u0026 len(missingPods) == 0 {\n\t\tif math.Abs(1.0-usageRatio) \u003c= c.tolerance {\n\t\t\t// return the current replicas if the change would be too small\n\t\t\treturn currentReplicas, usage, nil\n\t\t}\n\n\t\t// if we don't have any unready or missing pods, we can calculate the new replica count now\n\t\treturn int32(math.Ceil(usageRatio * float64(readyPodCount))), usage, nil\n\t}\n\n\tif len(missingPods) \u003e 0 {\n\t\tif usageRatio \u003c 1.0 {\n\t\t\t// on a scale-down, treat missing pods as using exactly the target amount\n\t\t\tfor podName := range missingPods {\n\t\t\t\tmetrics[podName] = metricsclient.PodMetric{Value: targetUsage}\n\t\t\t}\n\t\t} else {\n\t\t\t// on a scale-up, treat missing pods as using 0% of the resource request\n\t\t\tfor podName := range missingPods {\n\t\t\t\tmetrics[podName] = metricsclient.PodMetric{Value: 0}\n\t\t\t}\n\t\t}\n\t}\n\n\tif scaleUpWithUnready {\n\t\t// on a scale-up, treat unready pods as using 0% of the resource request\n\t\tfor podName := range unreadyPods {\n\t\t\tmetrics[podName] = metricsclient.PodMetric{Value: 0}\n\t\t}\n\t}\n\n\t// re-run the usage calculation with our new numbers\n\tnewUsageRatio, _ := metricsclient.GetMetricUsageRatio(metrics, targetUsage)\n\n\tif math.Abs(1.0-newUsageRatio) \u003c= c.tolerance || (usageRatio \u003c 1.0 \u0026\u0026 newUsageRatio \u003e 1.0) || (usageRatio \u003e 1.0 \u0026\u0026 newUsageRatio \u003c 1.0) {\n\t\t// return the current replicas if the change would be too small,\n\t\t// or if the new usage ratio would cause a change in scale direction\n\t\treturn currentReplicas, usage, nil\n\t}\n\n\tnewReplicas := int32(math.Ceil(newUsageRatio * float64(len(metrics))))\n\tif (newUsageRatio \u003c 1.0 \u0026\u0026 newReplicas \u003e currentReplicas) || (newUsageRatio \u003e 1.0 \u0026\u0026 newReplicas \u003c currentReplicas) {\n\t\t// return the current replicas if the change of metrics length would cause a change in scale direction\n\t\treturn currentReplicas, usage, nil\n\t}\n\n\t// return the result, where the number of replicas considered is\n\t// however many replicas factored into our calculation\n\treturn newReplicas, usage, nil\n}","line":{"from":177,"to":250}} {"id":100004414,"name":"GetObjectMetricReplicas","signature":"func (c *ReplicaCalculator) GetObjectMetricReplicas(currentReplicas int32, targetUsage int64, metricName string, namespace string, objectRef *autoscaling.CrossVersionObjectReference, selector labels.Selector, metricSelector labels.Selector) (replicaCount int32, usage int64, timestamp time.Time, err error)","file":"pkg/controller/podautoscaler/replica_calculator.go","code":"// GetObjectMetricReplicas calculates the desired replica count based on a target metric usage (as a milli-value)\n// for the given object in the given namespace, and the current replica count.\nfunc (c *ReplicaCalculator) GetObjectMetricReplicas(currentReplicas int32, targetUsage int64, metricName string, namespace string, objectRef *autoscaling.CrossVersionObjectReference, selector labels.Selector, metricSelector labels.Selector) (replicaCount int32, usage int64, timestamp time.Time, err error) {\n\tusage, _, err = c.metricsClient.GetObjectMetric(metricName, namespace, objectRef, metricSelector)\n\tif err != nil {\n\t\treturn 0, 0, time.Time{}, fmt.Errorf(\"unable to get metric %s: %v on %s %s/%s\", metricName, objectRef.Kind, namespace, objectRef.Name, err)\n\t}\n\n\tusageRatio := float64(usage) / float64(targetUsage)\n\treplicaCount, timestamp, err = c.getUsageRatioReplicaCount(currentReplicas, usageRatio, namespace, selector)\n\treturn replicaCount, usage, timestamp, err\n}","line":{"from":252,"to":263}} {"id":100004415,"name":"getUsageRatioReplicaCount","signature":"func (c *ReplicaCalculator) getUsageRatioReplicaCount(currentReplicas int32, usageRatio float64, namespace string, selector labels.Selector) (replicaCount int32, timestamp time.Time, err error)","file":"pkg/controller/podautoscaler/replica_calculator.go","code":"// getUsageRatioReplicaCount calculates the desired replica count based on usageRatio and ready pods count.\n// For currentReplicas=0 doesn't take into account ready pods count and tolerance to support scaling to zero pods.\nfunc (c *ReplicaCalculator) getUsageRatioReplicaCount(currentReplicas int32, usageRatio float64, namespace string, selector labels.Selector) (replicaCount int32, timestamp time.Time, err error) {\n\tif currentReplicas != 0 {\n\t\tif math.Abs(1.0-usageRatio) \u003c= c.tolerance {\n\t\t\t// return the current replicas if the change would be too small\n\t\t\treturn currentReplicas, timestamp, nil\n\t\t}\n\t\treadyPodCount := int64(0)\n\t\treadyPodCount, err = c.getReadyPodsCount(namespace, selector)\n\t\tif err != nil {\n\t\t\treturn 0, time.Time{}, fmt.Errorf(\"unable to calculate ready pods: %s\", err)\n\t\t}\n\t\treplicaCount = int32(math.Ceil(usageRatio * float64(readyPodCount)))\n\t} else {\n\t\t// Scale to zero or n pods depending on usageRatio\n\t\treplicaCount = int32(math.Ceil(usageRatio))\n\t}\n\n\treturn replicaCount, timestamp, err\n}","line":{"from":265,"to":285}} {"id":100004416,"name":"GetObjectPerPodMetricReplicas","signature":"func (c *ReplicaCalculator) GetObjectPerPodMetricReplicas(statusReplicas int32, targetAverageUsage int64, metricName string, namespace string, objectRef *autoscaling.CrossVersionObjectReference, metricSelector labels.Selector) (replicaCount int32, usage int64, timestamp time.Time, err error)","file":"pkg/controller/podautoscaler/replica_calculator.go","code":"// GetObjectPerPodMetricReplicas calculates the desired replica count based on a target metric usage (as a milli-value)\n// for the given object in the given namespace, and the current replica count.\nfunc (c *ReplicaCalculator) GetObjectPerPodMetricReplicas(statusReplicas int32, targetAverageUsage int64, metricName string, namespace string, objectRef *autoscaling.CrossVersionObjectReference, metricSelector labels.Selector) (replicaCount int32, usage int64, timestamp time.Time, err error) {\n\tusage, timestamp, err = c.metricsClient.GetObjectMetric(metricName, namespace, objectRef, metricSelector)\n\tif err != nil {\n\t\treturn 0, 0, time.Time{}, fmt.Errorf(\"unable to get metric %s: %v on %s %s/%s\", metricName, objectRef.Kind, namespace, objectRef.Name, err)\n\t}\n\n\treplicaCount = statusReplicas\n\tusageRatio := float64(usage) / (float64(targetAverageUsage) * float64(replicaCount))\n\tif math.Abs(1.0-usageRatio) \u003e c.tolerance {\n\t\t// update number of replicas if change is large enough\n\t\treplicaCount = int32(math.Ceil(float64(usage) / float64(targetAverageUsage)))\n\t}\n\tusage = int64(math.Ceil(float64(usage) / float64(statusReplicas)))\n\treturn replicaCount, usage, timestamp, nil\n}","line":{"from":287,"to":303}} {"id":100004417,"name":"getReadyPodsCount","signature":"func (c *ReplicaCalculator) getReadyPodsCount(namespace string, selector labels.Selector) (int64, error)","file":"pkg/controller/podautoscaler/replica_calculator.go","code":"// @TODO(mattjmcnaughton) Many different functions in this module use variations\n// of this function. Make this function generic, so we don't repeat the same\n// logic in multiple places.\nfunc (c *ReplicaCalculator) getReadyPodsCount(namespace string, selector labels.Selector) (int64, error) {\n\tpodList, err := c.podLister.Pods(namespace).List(selector)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"unable to get pods while calculating replica count: %v\", err)\n\t}\n\n\tif len(podList) == 0 {\n\t\treturn 0, fmt.Errorf(\"no pods returned by selector while calculating replica count\")\n\t}\n\n\treadyPodCount := 0\n\n\tfor _, pod := range podList {\n\t\tif pod.Status.Phase == v1.PodRunning \u0026\u0026 podutil.IsPodReady(pod) {\n\t\t\treadyPodCount++\n\t\t}\n\t}\n\n\treturn int64(readyPodCount), nil\n}","line":{"from":305,"to":327}} {"id":100004418,"name":"GetExternalMetricReplicas","signature":"func (c *ReplicaCalculator) GetExternalMetricReplicas(currentReplicas int32, targetUsage int64, metricName, namespace string, metricSelector *metav1.LabelSelector, podSelector labels.Selector) (replicaCount int32, usage int64, timestamp time.Time, err error)","file":"pkg/controller/podautoscaler/replica_calculator.go","code":"// GetExternalMetricReplicas calculates the desired replica count based on a\n// target metric value (as a milli-value) for the external metric in the given\n// namespace, and the current replica count.\nfunc (c *ReplicaCalculator) GetExternalMetricReplicas(currentReplicas int32, targetUsage int64, metricName, namespace string, metricSelector *metav1.LabelSelector, podSelector labels.Selector) (replicaCount int32, usage int64, timestamp time.Time, err error) {\n\tmetricLabelSelector, err := metav1.LabelSelectorAsSelector(metricSelector)\n\tif err != nil {\n\t\treturn 0, 0, time.Time{}, err\n\t}\n\tmetrics, _, err := c.metricsClient.GetExternalMetric(metricName, namespace, metricLabelSelector)\n\tif err != nil {\n\t\treturn 0, 0, time.Time{}, fmt.Errorf(\"unable to get external metric %s/%s/%+v: %s\", namespace, metricName, metricSelector, err)\n\t}\n\tusage = 0\n\tfor _, val := range metrics {\n\t\tusage = usage + val\n\t}\n\n\tusageRatio := float64(usage) / float64(targetUsage)\n\treplicaCount, timestamp, err = c.getUsageRatioReplicaCount(currentReplicas, usageRatio, namespace, podSelector)\n\treturn replicaCount, usage, timestamp, err\n}","line":{"from":329,"to":349}} {"id":100004419,"name":"GetExternalPerPodMetricReplicas","signature":"func (c *ReplicaCalculator) GetExternalPerPodMetricReplicas(statusReplicas int32, targetUsagePerPod int64, metricName, namespace string, metricSelector *metav1.LabelSelector) (replicaCount int32, usage int64, timestamp time.Time, err error)","file":"pkg/controller/podautoscaler/replica_calculator.go","code":"// GetExternalPerPodMetricReplicas calculates the desired replica count based on a\n// target metric value per pod (as a milli-value) for the external metric in the\n// given namespace, and the current replica count.\nfunc (c *ReplicaCalculator) GetExternalPerPodMetricReplicas(statusReplicas int32, targetUsagePerPod int64, metricName, namespace string, metricSelector *metav1.LabelSelector) (replicaCount int32, usage int64, timestamp time.Time, err error) {\n\tmetricLabelSelector, err := metav1.LabelSelectorAsSelector(metricSelector)\n\tif err != nil {\n\t\treturn 0, 0, time.Time{}, err\n\t}\n\tmetrics, timestamp, err := c.metricsClient.GetExternalMetric(metricName, namespace, metricLabelSelector)\n\tif err != nil {\n\t\treturn 0, 0, time.Time{}, fmt.Errorf(\"unable to get external metric %s/%s/%+v: %s\", namespace, metricName, metricSelector, err)\n\t}\n\tusage = 0\n\tfor _, val := range metrics {\n\t\tusage = usage + val\n\t}\n\n\treplicaCount = statusReplicas\n\tusageRatio := float64(usage) / (float64(targetUsagePerPod) * float64(replicaCount))\n\tif math.Abs(1.0-usageRatio) \u003e c.tolerance {\n\t\t// update number of replicas if the change is large enough\n\t\treplicaCount = int32(math.Ceil(float64(usage) / float64(targetUsagePerPod)))\n\t}\n\tusage = int64(math.Ceil(float64(usage) / float64(statusReplicas)))\n\treturn replicaCount, usage, timestamp, nil\n}","line":{"from":351,"to":376}} {"id":100004420,"name":"groupPods","signature":"func groupPods(pods []*v1.Pod, metrics metricsclient.PodMetricsInfo, resource v1.ResourceName, cpuInitializationPeriod, delayOfInitialReadinessStatus time.Duration) (readyPodCount int, unreadyPods, missingPods, ignoredPods sets.String)","file":"pkg/controller/podautoscaler/replica_calculator.go","code":"func groupPods(pods []*v1.Pod, metrics metricsclient.PodMetricsInfo, resource v1.ResourceName, cpuInitializationPeriod, delayOfInitialReadinessStatus time.Duration) (readyPodCount int, unreadyPods, missingPods, ignoredPods sets.String) {\n\tmissingPods = sets.NewString()\n\tunreadyPods = sets.NewString()\n\tignoredPods = sets.NewString()\n\tfor _, pod := range pods {\n\t\tif pod.DeletionTimestamp != nil || pod.Status.Phase == v1.PodFailed {\n\t\t\tignoredPods.Insert(pod.Name)\n\t\t\tcontinue\n\t\t}\n\t\t// Pending pods are ignored.\n\t\tif pod.Status.Phase == v1.PodPending {\n\t\t\tunreadyPods.Insert(pod.Name)\n\t\t\tcontinue\n\t\t}\n\t\t// Pods missing metrics.\n\t\tmetric, found := metrics[pod.Name]\n\t\tif !found {\n\t\t\tmissingPods.Insert(pod.Name)\n\t\t\tcontinue\n\t\t}\n\t\t// Unready pods are ignored.\n\t\tif resource == v1.ResourceCPU {\n\t\t\tvar unready bool\n\t\t\t_, condition := podutil.GetPodCondition(\u0026pod.Status, v1.PodReady)\n\t\t\tif condition == nil || pod.Status.StartTime == nil {\n\t\t\t\tunready = true\n\t\t\t} else {\n\t\t\t\t// Pod still within possible initialisation period.\n\t\t\t\tif pod.Status.StartTime.Add(cpuInitializationPeriod).After(time.Now()) {\n\t\t\t\t\t// Ignore sample if pod is unready or one window of metric wasn't collected since last state transition.\n\t\t\t\t\tunready = condition.Status == v1.ConditionFalse || metric.Timestamp.Before(condition.LastTransitionTime.Time.Add(metric.Window))\n\t\t\t\t} else {\n\t\t\t\t\t// Ignore metric if pod is unready and it has never been ready.\n\t\t\t\t\tunready = condition.Status == v1.ConditionFalse \u0026\u0026 pod.Status.StartTime.Add(delayOfInitialReadinessStatus).After(condition.LastTransitionTime.Time)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif unready {\n\t\t\t\tunreadyPods.Insert(pod.Name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\treadyPodCount++\n\t}\n\treturn\n}","line":{"from":378,"to":422}} {"id":100004421,"name":"calculatePodRequests","signature":"func calculatePodRequests(pods []*v1.Pod, container string, resource v1.ResourceName) (map[string]int64, error)","file":"pkg/controller/podautoscaler/replica_calculator.go","code":"func calculatePodRequests(pods []*v1.Pod, container string, resource v1.ResourceName) (map[string]int64, error) {\n\trequests := make(map[string]int64, len(pods))\n\tfor _, pod := range pods {\n\t\tpodSum := int64(0)\n\t\tfor _, c := range pod.Spec.Containers {\n\t\t\tif container == \"\" || container == c.Name {\n\t\t\t\tif containerRequest, ok := c.Resources.Requests[resource]; ok {\n\t\t\t\t\tpodSum += containerRequest.MilliValue()\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, fmt.Errorf(\"missing request for %s in container %s of Pod %s\", resource, c.Name, pod.ObjectMeta.Name)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\trequests[pod.Name] = podSum\n\t}\n\treturn requests, nil\n}","line":{"from":424,"to":440}} {"id":100004422,"name":"removeMetricsForPods","signature":"func removeMetricsForPods(metrics metricsclient.PodMetricsInfo, pods sets.String)","file":"pkg/controller/podautoscaler/replica_calculator.go","code":"func removeMetricsForPods(metrics metricsclient.PodMetricsInfo, pods sets.String) {\n\tfor _, pod := range pods.UnsortedList() {\n\t\tdelete(metrics, pod)\n\t}\n}","line":{"from":442,"to":446}} {"id":100004423,"name":"Convert_v1alpha1_PodGCControllerConfiguration_To_config_PodGCControllerConfiguration","signature":"func Convert_v1alpha1_PodGCControllerConfiguration_To_config_PodGCControllerConfiguration(in *v1alpha1.PodGCControllerConfiguration, out *config.PodGCControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/podgc/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_PodGCControllerConfiguration_To_config_PodGCControllerConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_PodGCControllerConfiguration_To_config_PodGCControllerConfiguration(in *v1alpha1.PodGCControllerConfiguration, out *config.PodGCControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_PodGCControllerConfiguration_To_config_PodGCControllerConfiguration(in, out, s)\n}","line":{"from":32,"to":35}} {"id":100004424,"name":"Convert_config_PodGCControllerConfiguration_To_v1alpha1_PodGCControllerConfiguration","signature":"func Convert_config_PodGCControllerConfiguration_To_v1alpha1_PodGCControllerConfiguration(in *config.PodGCControllerConfiguration, out *v1alpha1.PodGCControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/podgc/config/v1alpha1/conversion.go","code":"// Convert_config_PodGCControllerConfiguration_To_v1alpha1_PodGCControllerConfiguration is an autogenerated conversion function.\nfunc Convert_config_PodGCControllerConfiguration_To_v1alpha1_PodGCControllerConfiguration(in *config.PodGCControllerConfiguration, out *v1alpha1.PodGCControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_PodGCControllerConfiguration_To_v1alpha1_PodGCControllerConfiguration(in, out, s)\n}","line":{"from":37,"to":40}} {"id":100004425,"name":"RecommendedDefaultPodGCControllerConfiguration","signature":"func RecommendedDefaultPodGCControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.PodGCControllerConfiguration)","file":"pkg/controller/podgc/config/v1alpha1/defaults.go","code":"// RecommendedDefaultPodGCControllerConfiguration defaults a pointer to a\n// PodGCControllerConfiguration struct. This will set the recommended default\n// values, but they may be subject to change between API versions. This function\n// is intentionally not registered in the scheme as a \"normal\" `SetDefaults_Foo`\n// function to allow consumers of this type to set whatever defaults for their\n// embedded configs. Forcing consumers to use these defaults would be problematic\n// as defaulting in the scheme is done as part of the conversion, and there would\n// be no easy way to opt-out. Instead, if you want to use this defaulting method\n// run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDefaultPodGCControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.PodGCControllerConfiguration) {\n\tif obj.TerminatedPodGCThreshold == 0 {\n\t\tobj.TerminatedPodGCThreshold = 12500\n\t}\n}","line":{"from":23,"to":36}} {"id":100004426,"name":"init","signature":"func init()","file":"pkg/controller/podgc/gc_controller.go","code":"func init() {\n\t// Register prometheus metrics\n\tRegisterMetrics()\n}","line":{"from":72,"to":75}} {"id":100004427,"name":"NewPodGC","signature":"func NewPodGC(ctx context.Context, kubeClient clientset.Interface, podInformer coreinformers.PodInformer,","file":"pkg/controller/podgc/gc_controller.go","code":"func NewPodGC(ctx context.Context, kubeClient clientset.Interface, podInformer coreinformers.PodInformer,\n\tnodeInformer coreinformers.NodeInformer, terminatedPodThreshold int) *PodGCController {\n\treturn NewPodGCInternal(ctx, kubeClient, podInformer, nodeInformer, terminatedPodThreshold, gcCheckPeriod, quarantineTime)\n}","line":{"from":77,"to":80}} {"id":100004428,"name":"NewPodGCInternal","signature":"func NewPodGCInternal(ctx context.Context, kubeClient clientset.Interface, podInformer coreinformers.PodInformer,","file":"pkg/controller/podgc/gc_controller.go","code":"// This function is only intended for integration tests\nfunc NewPodGCInternal(ctx context.Context, kubeClient clientset.Interface, podInformer coreinformers.PodInformer,\n\tnodeInformer coreinformers.NodeInformer, terminatedPodThreshold int, gcCheckPeriod, quarantineTime time.Duration) *PodGCController {\n\tgcc := \u0026PodGCController{\n\t\tkubeClient: kubeClient,\n\t\tterminatedPodThreshold: terminatedPodThreshold,\n\t\tpodLister: podInformer.Lister(),\n\t\tpodListerSynced: podInformer.Informer().HasSynced,\n\t\tnodeLister: nodeInformer.Lister(),\n\t\tnodeListerSynced: nodeInformer.Informer().HasSynced,\n\t\tnodeQueue: workqueue.NewNamedDelayingQueue(\"orphaned_pods_nodes\"),\n\t\tgcCheckPeriod: gcCheckPeriod,\n\t\tquarantineTime: quarantineTime,\n\t}\n\n\treturn gcc\n}","line":{"from":82,"to":98}} {"id":100004429,"name":"Run","signature":"func (gcc *PodGCController) Run(ctx context.Context)","file":"pkg/controller/podgc/gc_controller.go","code":"func (gcc *PodGCController) Run(ctx context.Context) {\n\tdefer utilruntime.HandleCrash()\n\n\tklog.Infof(\"Starting GC controller\")\n\tdefer gcc.nodeQueue.ShutDown()\n\tdefer klog.Infof(\"Shutting down GC controller\")\n\n\tif !cache.WaitForNamedCacheSync(\"GC\", ctx.Done(), gcc.podListerSynced, gcc.nodeListerSynced) {\n\t\treturn\n\t}\n\n\tgo wait.UntilWithContext(ctx, gcc.gc, gcc.gcCheckPeriod)\n\n\t\u003c-ctx.Done()\n}","line":{"from":100,"to":114}} {"id":100004430,"name":"gc","signature":"func (gcc *PodGCController) gc(ctx context.Context)","file":"pkg/controller/podgc/gc_controller.go","code":"func (gcc *PodGCController) gc(ctx context.Context) {\n\tpods, err := gcc.podLister.List(labels.Everything())\n\tif err != nil {\n\t\tklog.Errorf(\"Error while listing all pods: %v\", err)\n\t\treturn\n\t}\n\tnodes, err := gcc.nodeLister.List(labels.Everything())\n\tif err != nil {\n\t\tklog.Errorf(\"Error while listing all nodes: %v\", err)\n\t\treturn\n\t}\n\tif gcc.terminatedPodThreshold \u003e 0 {\n\t\tgcc.gcTerminated(ctx, pods)\n\t}\n\tif utilfeature.DefaultFeatureGate.Enabled(features.NodeOutOfServiceVolumeDetach) {\n\t\tgcc.gcTerminating(ctx, pods)\n\t}\n\tgcc.gcOrphaned(ctx, pods, nodes)\n\tgcc.gcUnscheduledTerminating(ctx, pods)\n}","line":{"from":116,"to":135}} {"id":100004431,"name":"isPodTerminated","signature":"func isPodTerminated(pod *v1.Pod) bool","file":"pkg/controller/podgc/gc_controller.go","code":"func isPodTerminated(pod *v1.Pod) bool {\n\tif phase := pod.Status.Phase; phase != v1.PodPending \u0026\u0026 phase != v1.PodRunning \u0026\u0026 phase != v1.PodUnknown {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":137,"to":142}} {"id":100004432,"name":"isPodTerminating","signature":"func isPodTerminating(pod *v1.Pod) bool","file":"pkg/controller/podgc/gc_controller.go","code":"// isPodTerminating returns true if the pod is terminating.\nfunc isPodTerminating(pod *v1.Pod) bool {\n\treturn pod.ObjectMeta.DeletionTimestamp != nil\n}","line":{"from":144,"to":147}} {"id":100004433,"name":"gcTerminating","signature":"func (gcc *PodGCController) gcTerminating(ctx context.Context, pods []*v1.Pod)","file":"pkg/controller/podgc/gc_controller.go","code":"func (gcc *PodGCController) gcTerminating(ctx context.Context, pods []*v1.Pod) {\n\tklog.V(4).Info(\"GC'ing terminating pods that are on out-of-service nodes\")\n\tterminatingPods := []*v1.Pod{}\n\tfor _, pod := range pods {\n\t\tif isPodTerminating(pod) {\n\t\t\tnode, err := gcc.nodeLister.Get(pod.Spec.NodeName)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"failed to get node %s : %s\", pod.Spec.NodeName, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Add this pod to terminatingPods list only if the following conditions are met:\n\t\t\t// 1. Node is not ready.\n\t\t\t// 2. Node has `node.kubernetes.io/out-of-service` taint.\n\t\t\tif !nodeutil.IsNodeReady(node) \u0026\u0026 taints.TaintKeyExists(node.Spec.Taints, v1.TaintNodeOutOfService) {\n\t\t\t\tklog.V(4).Infof(\"garbage collecting pod %s that is terminating. Phase [%v]\", pod.Name, pod.Status.Phase)\n\t\t\t\tterminatingPods = append(terminatingPods, pod)\n\t\t\t}\n\t\t}\n\t}\n\n\tdeleteCount := len(terminatingPods)\n\tif deleteCount == 0 {\n\t\treturn\n\t}\n\n\tklog.V(4).Infof(\"Garbage collecting %v pods that are terminating on node tainted with node.kubernetes.io/out-of-service\", deleteCount)\n\t// sort only when necessary\n\tsort.Sort(byEvictionAndCreationTimestamp(terminatingPods))\n\tvar wait sync.WaitGroup\n\tfor i := 0; i \u003c deleteCount; i++ {\n\t\twait.Add(1)\n\t\tgo func(pod *v1.Pod) {\n\t\t\tdefer wait.Done()\n\t\t\tdeletingPodsTotal.WithLabelValues().Inc()\n\t\t\tif err := gcc.markFailedAndDeletePod(ctx, pod); err != nil {\n\t\t\t\t// ignore not founds\n\t\t\t\tutilruntime.HandleError(err)\n\t\t\t\tdeletingPodsErrorTotal.WithLabelValues().Inc()\n\t\t\t}\n\t\t}(terminatingPods[i])\n\t}\n\twait.Wait()\n}","line":{"from":149,"to":191}} {"id":100004434,"name":"gcTerminated","signature":"func (gcc *PodGCController) gcTerminated(ctx context.Context, pods []*v1.Pod)","file":"pkg/controller/podgc/gc_controller.go","code":"func (gcc *PodGCController) gcTerminated(ctx context.Context, pods []*v1.Pod) {\n\tterminatedPods := []*v1.Pod{}\n\tfor _, pod := range pods {\n\t\tif isPodTerminated(pod) {\n\t\t\tterminatedPods = append(terminatedPods, pod)\n\t\t}\n\t}\n\n\tterminatedPodCount := len(terminatedPods)\n\tdeleteCount := terminatedPodCount - gcc.terminatedPodThreshold\n\n\tif deleteCount \u003c= 0 {\n\t\treturn\n\t}\n\n\tklog.InfoS(\"Garbage collecting pods\", \"numPods\", deleteCount)\n\t// sort only when necessary\n\tsort.Sort(byEvictionAndCreationTimestamp(terminatedPods))\n\tvar wait sync.WaitGroup\n\tfor i := 0; i \u003c deleteCount; i++ {\n\t\twait.Add(1)\n\t\tgo func(pod *v1.Pod) {\n\t\t\tdefer wait.Done()\n\t\t\tif err := gcc.markFailedAndDeletePod(ctx, pod); err != nil {\n\t\t\t\t// ignore not founds\n\t\t\t\tdefer utilruntime.HandleError(err)\n\t\t\t}\n\t\t}(terminatedPods[i])\n\t}\n\twait.Wait()\n}","line":{"from":193,"to":223}} {"id":100004435,"name":"gcOrphaned","signature":"func (gcc *PodGCController) gcOrphaned(ctx context.Context, pods []*v1.Pod, nodes []*v1.Node)","file":"pkg/controller/podgc/gc_controller.go","code":"// gcOrphaned deletes pods that are bound to nodes that don't exist.\nfunc (gcc *PodGCController) gcOrphaned(ctx context.Context, pods []*v1.Pod, nodes []*v1.Node) {\n\tklog.V(4).Infof(\"GC'ing orphaned\")\n\texistingNodeNames := sets.NewString()\n\tfor _, node := range nodes {\n\t\texistingNodeNames.Insert(node.Name)\n\t}\n\t// Add newly found unknown nodes to quarantine\n\tfor _, pod := range pods {\n\t\tif pod.Spec.NodeName != \"\" \u0026\u0026 !existingNodeNames.Has(pod.Spec.NodeName) {\n\t\t\tgcc.nodeQueue.AddAfter(pod.Spec.NodeName, gcc.quarantineTime)\n\t\t}\n\t}\n\t// Check if nodes are still missing after quarantine period\n\tdeletedNodesNames, quit := gcc.discoverDeletedNodes(ctx, existingNodeNames)\n\tif quit {\n\t\treturn\n\t}\n\t// Delete orphaned pods\n\tfor _, pod := range pods {\n\t\tif !deletedNodesNames.Has(pod.Spec.NodeName) {\n\t\t\tcontinue\n\t\t}\n\t\tklog.V(2).InfoS(\"Found orphaned Pod assigned to the Node, deleting.\", \"pod\", klog.KObj(pod), \"node\", pod.Spec.NodeName)\n\t\tcondition := corev1apply.PodCondition().\n\t\t\tWithType(v1.DisruptionTarget).\n\t\t\tWithStatus(v1.ConditionTrue).\n\t\t\tWithReason(\"DeletionByPodGC\").\n\t\t\tWithMessage(\"PodGC: node no longer exists\").\n\t\t\tWithLastTransitionTime(metav1.Now())\n\t\tif err := gcc.markFailedAndDeletePodWithCondition(ctx, pod, condition); err != nil {\n\t\t\tutilruntime.HandleError(err)\n\t\t} else {\n\t\t\tklog.InfoS(\"Forced deletion of orphaned Pod succeeded\", \"pod\", klog.KObj(pod))\n\t\t}\n\t}\n}","line":{"from":225,"to":261}} {"id":100004436,"name":"discoverDeletedNodes","signature":"func (gcc *PodGCController) discoverDeletedNodes(ctx context.Context, existingNodeNames sets.String) (sets.String, bool)","file":"pkg/controller/podgc/gc_controller.go","code":"func (gcc *PodGCController) discoverDeletedNodes(ctx context.Context, existingNodeNames sets.String) (sets.String, bool) {\n\tdeletedNodesNames := sets.NewString()\n\tfor gcc.nodeQueue.Len() \u003e 0 {\n\t\titem, quit := gcc.nodeQueue.Get()\n\t\tif quit {\n\t\t\treturn nil, true\n\t\t}\n\t\tnodeName := item.(string)\n\t\tif !existingNodeNames.Has(nodeName) {\n\t\t\texists, err := gcc.checkIfNodeExists(ctx, nodeName)\n\t\t\tswitch {\n\t\t\tcase err != nil:\n\t\t\t\tklog.ErrorS(err, \"Error while getting node\", \"node\", klog.KRef(\"\", nodeName))\n\t\t\t\t// Node will be added back to the queue in the subsequent loop if still needed\n\t\t\tcase !exists:\n\t\t\t\tdeletedNodesNames.Insert(nodeName)\n\t\t\t}\n\t\t}\n\t\tgcc.nodeQueue.Done(item)\n\t}\n\treturn deletedNodesNames, false\n}","line":{"from":263,"to":284}} {"id":100004437,"name":"checkIfNodeExists","signature":"func (gcc *PodGCController) checkIfNodeExists(ctx context.Context, name string) (bool, error)","file":"pkg/controller/podgc/gc_controller.go","code":"func (gcc *PodGCController) checkIfNodeExists(ctx context.Context, name string) (bool, error) {\n\t_, fetchErr := gcc.kubeClient.CoreV1().Nodes().Get(ctx, name, metav1.GetOptions{})\n\tif errors.IsNotFound(fetchErr) {\n\t\treturn false, nil\n\t}\n\treturn fetchErr == nil, fetchErr\n}","line":{"from":286,"to":292}} {"id":100004438,"name":"gcUnscheduledTerminating","signature":"func (gcc *PodGCController) gcUnscheduledTerminating(ctx context.Context, pods []*v1.Pod)","file":"pkg/controller/podgc/gc_controller.go","code":"// gcUnscheduledTerminating deletes pods that are terminating and haven't been scheduled to a particular node.\nfunc (gcc *PodGCController) gcUnscheduledTerminating(ctx context.Context, pods []*v1.Pod) {\n\tklog.V(4).Infof(\"GC'ing unscheduled pods which are terminating.\")\n\n\tfor _, pod := range pods {\n\t\tif pod.DeletionTimestamp == nil || len(pod.Spec.NodeName) \u003e 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tklog.V(2).InfoS(\"Found unscheduled terminating Pod not assigned to any Node, deleting.\", \"pod\", klog.KObj(pod))\n\t\tif err := gcc.markFailedAndDeletePod(ctx, pod); err != nil {\n\t\t\tutilruntime.HandleError(err)\n\t\t} else {\n\t\t\tklog.InfoS(\"Forced deletion of unscheduled terminating Pod succeeded\", \"pod\", klog.KObj(pod))\n\t\t}\n\t}\n}","line":{"from":294,"to":310}} {"id":100004439,"name":"Len","signature":"func (o byEvictionAndCreationTimestamp) Len() int { return len(o) }","file":"pkg/controller/podgc/gc_controller.go","code":"func (o byEvictionAndCreationTimestamp) Len() int { return len(o) }","line":{"from":317,"to":317}} {"id":100004440,"name":"Swap","signature":"func (o byEvictionAndCreationTimestamp) Swap(i, j int) { o[i], o[j] = o[j], o[i] }","file":"pkg/controller/podgc/gc_controller.go","code":"func (o byEvictionAndCreationTimestamp) Swap(i, j int) { o[i], o[j] = o[j], o[i] }","line":{"from":318,"to":318}} {"id":100004441,"name":"Less","signature":"func (o byEvictionAndCreationTimestamp) Less(i, j int) bool","file":"pkg/controller/podgc/gc_controller.go","code":"func (o byEvictionAndCreationTimestamp) Less(i, j int) bool {\n\tiEvicted, jEvicted := eviction.PodIsEvicted(o[i].Status), eviction.PodIsEvicted(o[j].Status)\n\t// Evicted pod is smaller\n\tif iEvicted != jEvicted {\n\t\treturn iEvicted\n\t}\n\tif o[i].CreationTimestamp.Equal(\u0026o[j].CreationTimestamp) {\n\t\treturn o[i].Name \u003c o[j].Name\n\t}\n\treturn o[i].CreationTimestamp.Before(\u0026o[j].CreationTimestamp)\n}","line":{"from":320,"to":330}} {"id":100004442,"name":"markFailedAndDeletePod","signature":"func (gcc *PodGCController) markFailedAndDeletePod(ctx context.Context, pod *v1.Pod) error","file":"pkg/controller/podgc/gc_controller.go","code":"func (gcc *PodGCController) markFailedAndDeletePod(ctx context.Context, pod *v1.Pod) error {\n\treturn gcc.markFailedAndDeletePodWithCondition(ctx, pod, nil)\n}","line":{"from":332,"to":334}} {"id":100004443,"name":"markFailedAndDeletePodWithCondition","signature":"func (gcc *PodGCController) markFailedAndDeletePodWithCondition(ctx context.Context, pod *v1.Pod, condition *corev1apply.PodConditionApplyConfiguration) error","file":"pkg/controller/podgc/gc_controller.go","code":"func (gcc *PodGCController) markFailedAndDeletePodWithCondition(ctx context.Context, pod *v1.Pod, condition *corev1apply.PodConditionApplyConfiguration) error {\n\tklog.InfoS(\"PodGC is force deleting Pod\", \"pod\", klog.KRef(pod.Namespace, pod.Name))\n\tif utilfeature.DefaultFeatureGate.Enabled(features.PodDisruptionConditions) {\n\n\t\t// Mark the pod as failed - this is especially important in case the pod\n\t\t// is orphaned, in which case the pod would remain in the Running phase\n\t\t// forever as there is no kubelet running to change the phase.\n\t\tif pod.Status.Phase != v1.PodSucceeded \u0026\u0026 pod.Status.Phase != v1.PodFailed {\n\t\t\tpodApply := corev1apply.Pod(pod.Name, pod.Namespace).WithStatus(corev1apply.PodStatus())\n\t\t\t// we don't need to extract the pod apply configuration and can send\n\t\t\t// only phase and the DisruptionTarget condition as PodGC would not\n\t\t\t// own other fields. If the DisruptionTarget condition is owned by\n\t\t\t// PodGC it means that it is in the Failed phase, so sending the\n\t\t\t// condition will not be re-attempted.\n\t\t\tpodApply.Status.WithPhase(v1.PodFailed)\n\t\t\tif condition != nil {\n\t\t\t\tpodApply.Status.WithConditions(condition)\n\t\t\t}\n\t\t\tif _, err := gcc.kubeClient.CoreV1().Pods(pod.Namespace).ApplyStatus(ctx, podApply, metav1.ApplyOptions{FieldManager: fieldManager, Force: true}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn gcc.kubeClient.CoreV1().Pods(pod.Namespace).Delete(ctx, pod.Name, *metav1.NewDeleteOptions(0))\n}","line":{"from":336,"to":360}} {"id":100004444,"name":"RegisterMetrics","signature":"func RegisterMetrics()","file":"pkg/controller/podgc/metrics.go","code":"// Register the metrics that are to be monitored.\nfunc RegisterMetrics() {\n\tregisterMetrics.Do(func() {\n\t\tlegacyregistry.MustRegister(deletingPodsTotal)\n\t\tlegacyregistry.MustRegister(deletingPodsErrorTotal)\n\t})\n}","line":{"from":53,"to":59}} {"id":100004445,"name":"Convert_v1alpha1_ReplicaSetControllerConfiguration_To_config_ReplicaSetControllerConfiguration","signature":"func Convert_v1alpha1_ReplicaSetControllerConfiguration_To_config_ReplicaSetControllerConfiguration(in *v1alpha1.ReplicaSetControllerConfiguration, out *config.ReplicaSetControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/replicaset/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_ReplicaSetControllerConfiguration_To_config_ReplicaSetControllerConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_ReplicaSetControllerConfiguration_To_config_ReplicaSetControllerConfiguration(in *v1alpha1.ReplicaSetControllerConfiguration, out *config.ReplicaSetControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_ReplicaSetControllerConfiguration_To_config_ReplicaSetControllerConfiguration(in, out, s)\n}","line":{"from":32,"to":35}} {"id":100004446,"name":"Convert_config_ReplicaSetControllerConfiguration_To_v1alpha1_ReplicaSetControllerConfiguration","signature":"func Convert_config_ReplicaSetControllerConfiguration_To_v1alpha1_ReplicaSetControllerConfiguration(in *config.ReplicaSetControllerConfiguration, out *v1alpha1.ReplicaSetControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/replicaset/config/v1alpha1/conversion.go","code":"// Convert_config_ReplicaSetControllerConfiguration_To_v1alpha1_ReplicaSetControllerConfiguration is an autogenerated conversion function.\nfunc Convert_config_ReplicaSetControllerConfiguration_To_v1alpha1_ReplicaSetControllerConfiguration(in *config.ReplicaSetControllerConfiguration, out *v1alpha1.ReplicaSetControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_ReplicaSetControllerConfiguration_To_v1alpha1_ReplicaSetControllerConfiguration(in, out, s)\n}","line":{"from":37,"to":40}} {"id":100004447,"name":"RecommendedDefaultReplicaSetControllerConfiguration","signature":"func RecommendedDefaultReplicaSetControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.ReplicaSetControllerConfiguration)","file":"pkg/controller/replicaset/config/v1alpha1/defaults.go","code":"// RecommendedDefaultReplicaSetControllerConfiguration defaults a pointer to a\n// ReplicaSetControllerConfiguration struct. This will set the recommended default\n// values, but they may be subject to change between API versions. This function\n// is intentionally not registered in the scheme as a \"normal\" `SetDefaults_Foo`\n// function to allow consumers of this type to set whatever defaults for their\n// embedded configs. Forcing consumers to use these defaults would be problematic\n// as defaulting in the scheme is done as part of the conversion, and there would\n// be no easy way to opt-out. Instead, if you want to use this defaulting method\n// run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDefaultReplicaSetControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.ReplicaSetControllerConfiguration) {\n\tif obj.ConcurrentRSSyncs == 0 {\n\t\tobj.ConcurrentRSSyncs = 5\n\t}\n}","line":{"from":23,"to":36}} {"id":100004448,"name":"Register","signature":"func Register(registrationFunc func(metrics.Registerable) error) error","file":"pkg/controller/replicaset/metrics/metrics.go","code":"// Register registers ReplicaSet controller metrics.\nfunc Register(registrationFunc func(metrics.Registerable) error) error {\n\treturn registrationFunc(SortingDeletionAgeRatio)\n}","line":{"from":37,"to":40}} {"id":100004449,"name":"NewReplicaSetController","signature":"func NewReplicaSetController(logger klog.Logger, rsInformer appsinformers.ReplicaSetInformer, podInformer coreinformers.PodInformer, kubeClient clientset.Interface, burstReplicas int) *ReplicaSetController","file":"pkg/controller/replicaset/replica_set.go","code":"// NewReplicaSetController configures a replica set controller with the specified event recorder\nfunc NewReplicaSetController(logger klog.Logger, rsInformer appsinformers.ReplicaSetInformer, podInformer coreinformers.PodInformer, kubeClient clientset.Interface, burstReplicas int) *ReplicaSetController {\n\teventBroadcaster := record.NewBroadcaster()\n\tif err := metrics.Register(legacyregistry.Register); err != nil {\n\t\tlogger.Error(err, \"unable to register metrics\")\n\t}\n\treturn NewBaseController(rsInformer, podInformer, kubeClient, burstReplicas,\n\t\tapps.SchemeGroupVersion.WithKind(\"ReplicaSet\"),\n\t\t\"replicaset_controller\",\n\t\t\"replicaset\",\n\t\tcontroller.RealPodControl{\n\t\t\tKubeClient: kubeClient,\n\t\t\tRecorder: eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"replicaset-controller\"}),\n\t\t},\n\t\teventBroadcaster,\n\t)\n}","line":{"from":118,"to":134}} {"id":100004450,"name":"NewBaseController","signature":"func NewBaseController(rsInformer appsinformers.ReplicaSetInformer, podInformer coreinformers.PodInformer, kubeClient clientset.Interface, burstReplicas int,","file":"pkg/controller/replicaset/replica_set.go","code":"// NewBaseController is the implementation of NewReplicaSetController with additional injected\n// parameters so that it can also serve as the implementation of NewReplicationController.\nfunc NewBaseController(rsInformer appsinformers.ReplicaSetInformer, podInformer coreinformers.PodInformer, kubeClient clientset.Interface, burstReplicas int,\n\tgvk schema.GroupVersionKind, metricOwnerName, queueName string, podControl controller.PodControlInterface, eventBroadcaster record.EventBroadcaster) *ReplicaSetController {\n\n\trsc := \u0026ReplicaSetController{\n\t\tGroupVersionKind: gvk,\n\t\tkubeClient: kubeClient,\n\t\tpodControl: podControl,\n\t\teventBroadcaster: eventBroadcaster,\n\t\tburstReplicas: burstReplicas,\n\t\texpectations: controller.NewUIDTrackingControllerExpectations(controller.NewControllerExpectations()),\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), queueName),\n\t}\n\n\trsInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: rsc.addRS,\n\t\tUpdateFunc: rsc.updateRS,\n\t\tDeleteFunc: rsc.deleteRS,\n\t})\n\trsInformer.Informer().AddIndexers(cache.Indexers{\n\t\tcontrollerUIDIndex: func(obj interface{}) ([]string, error) {\n\t\t\trs, ok := obj.(*apps.ReplicaSet)\n\t\t\tif !ok {\n\t\t\t\treturn []string{}, nil\n\t\t\t}\n\t\t\tcontrollerRef := metav1.GetControllerOf(rs)\n\t\t\tif controllerRef == nil {\n\t\t\t\treturn []string{}, nil\n\t\t\t}\n\t\t\treturn []string{string(controllerRef.UID)}, nil\n\t\t},\n\t})\n\trsc.rsIndexer = rsInformer.Informer().GetIndexer()\n\trsc.rsLister = rsInformer.Lister()\n\trsc.rsListerSynced = rsInformer.Informer().HasSynced\n\n\tpodInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: rsc.addPod,\n\t\t// This invokes the ReplicaSet for every pod change, eg: host assignment. Though this might seem like\n\t\t// overkill the most frequent pod update is status, and the associated ReplicaSet will only list from\n\t\t// local storage, so it should be ok.\n\t\tUpdateFunc: rsc.updatePod,\n\t\tDeleteFunc: rsc.deletePod,\n\t})\n\trsc.podLister = podInformer.Lister()\n\trsc.podListerSynced = podInformer.Informer().HasSynced\n\n\trsc.syncHandler = rsc.syncReplicaSet\n\n\treturn rsc\n}","line":{"from":136,"to":187}} {"id":100004451,"name":"Run","signature":"func (rsc *ReplicaSetController) Run(ctx context.Context, workers int)","file":"pkg/controller/replicaset/replica_set.go","code":"// Run begins watching and syncing.\nfunc (rsc *ReplicaSetController) Run(ctx context.Context, workers int) {\n\tdefer utilruntime.HandleCrash()\n\n\t// Start events processing pipeline.\n\trsc.eventBroadcaster.StartStructuredLogging(0)\n\trsc.eventBroadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: rsc.kubeClient.CoreV1().Events(\"\")})\n\tdefer rsc.eventBroadcaster.Shutdown()\n\n\tdefer rsc.queue.ShutDown()\n\n\tcontrollerName := strings.ToLower(rsc.Kind)\n\tklog.FromContext(ctx).Info(\"Starting controller\", \"name\", controllerName)\n\tdefer klog.FromContext(ctx).Info(\"Shutting down controller\", \"name\", controllerName)\n\n\tif !cache.WaitForNamedCacheSync(rsc.Kind, ctx.Done(), rsc.podListerSynced, rsc.rsListerSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.UntilWithContext(ctx, rsc.worker, time.Second)\n\t}\n\n\t\u003c-ctx.Done()\n}","line":{"from":189,"to":213}} {"id":100004452,"name":"getReplicaSetsWithSameController","signature":"func (rsc *ReplicaSetController) getReplicaSetsWithSameController(logger klog.Logger, rs *apps.ReplicaSet) []*apps.ReplicaSet","file":"pkg/controller/replicaset/replica_set.go","code":"// getReplicaSetsWithSameController returns a list of ReplicaSets with the same\n// owner as the given ReplicaSet.\nfunc (rsc *ReplicaSetController) getReplicaSetsWithSameController(logger klog.Logger, rs *apps.ReplicaSet) []*apps.ReplicaSet {\n\tcontrollerRef := metav1.GetControllerOf(rs)\n\tif controllerRef == nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"ReplicaSet has no controller: %v\", rs))\n\t\treturn nil\n\t}\n\n\tobjects, err := rsc.rsIndexer.ByIndex(controllerUIDIndex, string(controllerRef.UID))\n\tif err != nil {\n\t\tutilruntime.HandleError(err)\n\t\treturn nil\n\t}\n\trelatedRSs := make([]*apps.ReplicaSet, 0, len(objects))\n\tfor _, obj := range objects {\n\t\trelatedRSs = append(relatedRSs, obj.(*apps.ReplicaSet))\n\t}\n\n\tif klogV := logger.V(2); klogV.Enabled() {\n\t\tklogV.Info(\"Found related ReplicaSets\", \"replicaSet\", klog.KObj(rs), \"relatedReplicaSets\", klog.KObjSlice(relatedRSs))\n\t}\n\n\treturn relatedRSs\n}","line":{"from":215,"to":239}} {"id":100004453,"name":"getPodReplicaSets","signature":"func (rsc *ReplicaSetController) getPodReplicaSets(pod *v1.Pod) []*apps.ReplicaSet","file":"pkg/controller/replicaset/replica_set.go","code":"// getPodReplicaSets returns a list of ReplicaSets matching the given pod.\nfunc (rsc *ReplicaSetController) getPodReplicaSets(pod *v1.Pod) []*apps.ReplicaSet {\n\trss, err := rsc.rsLister.GetPodReplicaSets(pod)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tif len(rss) \u003e 1 {\n\t\t// ControllerRef will ensure we don't do anything crazy, but more than one\n\t\t// item in this list nevertheless constitutes user error.\n\t\tutilruntime.HandleError(fmt.Errorf(\"user error! more than one %v is selecting pods with labels: %+v\", rsc.Kind, pod.Labels))\n\t}\n\treturn rss\n}","line":{"from":241,"to":253}} {"id":100004454,"name":"resolveControllerRef","signature":"func (rsc *ReplicaSetController) resolveControllerRef(namespace string, controllerRef *metav1.OwnerReference) *apps.ReplicaSet","file":"pkg/controller/replicaset/replica_set.go","code":"// resolveControllerRef returns the controller referenced by a ControllerRef,\n// or nil if the ControllerRef could not be resolved to a matching controller\n// of the correct Kind.\nfunc (rsc *ReplicaSetController) resolveControllerRef(namespace string, controllerRef *metav1.OwnerReference) *apps.ReplicaSet {\n\t// We can't look up by UID, so look up by Name and then verify UID.\n\t// Don't even try to look up by Name if it's the wrong Kind.\n\tif controllerRef.Kind != rsc.Kind {\n\t\treturn nil\n\t}\n\trs, err := rsc.rsLister.ReplicaSets(namespace).Get(controllerRef.Name)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tif rs.UID != controllerRef.UID {\n\t\t// The controller we found with this Name is not the same one that the\n\t\t// ControllerRef points to.\n\t\treturn nil\n\t}\n\treturn rs\n}","line":{"from":255,"to":274}} {"id":100004455,"name":"enqueueRS","signature":"func (rsc *ReplicaSetController) enqueueRS(rs *apps.ReplicaSet)","file":"pkg/controller/replicaset/replica_set.go","code":"func (rsc *ReplicaSetController) enqueueRS(rs *apps.ReplicaSet) {\n\tkey, err := controller.KeyFunc(rs)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get key for object %#v: %v\", rs, err))\n\t\treturn\n\t}\n\n\trsc.queue.Add(key)\n}","line":{"from":276,"to":284}} {"id":100004456,"name":"enqueueRSAfter","signature":"func (rsc *ReplicaSetController) enqueueRSAfter(rs *apps.ReplicaSet, duration time.Duration)","file":"pkg/controller/replicaset/replica_set.go","code":"func (rsc *ReplicaSetController) enqueueRSAfter(rs *apps.ReplicaSet, duration time.Duration) {\n\tkey, err := controller.KeyFunc(rs)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get key for object %#v: %v\", rs, err))\n\t\treturn\n\t}\n\n\trsc.queue.AddAfter(key, duration)\n}","line":{"from":286,"to":294}} {"id":100004457,"name":"addRS","signature":"func (rsc *ReplicaSetController) addRS(obj interface{})","file":"pkg/controller/replicaset/replica_set.go","code":"func (rsc *ReplicaSetController) addRS(obj interface{}) {\n\trs := obj.(*apps.ReplicaSet)\n\tklog.V(4).Infof(\"Adding %s %s/%s\", rsc.Kind, rs.Namespace, rs.Name)\n\trsc.enqueueRS(rs)\n}","line":{"from":296,"to":300}} {"id":100004458,"name":"updateRS","signature":"func (rsc *ReplicaSetController) updateRS(old, cur interface{})","file":"pkg/controller/replicaset/replica_set.go","code":"// callback when RS is updated\nfunc (rsc *ReplicaSetController) updateRS(old, cur interface{}) {\n\toldRS := old.(*apps.ReplicaSet)\n\tcurRS := cur.(*apps.ReplicaSet)\n\n\t// TODO: make a KEP and fix informers to always call the delete event handler on re-create\n\tif curRS.UID != oldRS.UID {\n\t\tkey, err := controller.KeyFunc(oldRS)\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get key for object %#v: %v\", oldRS, err))\n\t\t\treturn\n\t\t}\n\t\trsc.deleteRS(cache.DeletedFinalStateUnknown{\n\t\t\tKey: key,\n\t\t\tObj: oldRS,\n\t\t})\n\t}\n\n\t// You might imagine that we only really need to enqueue the\n\t// replica set when Spec changes, but it is safer to sync any\n\t// time this function is triggered. That way a full informer\n\t// resync can requeue any replica set that don't yet have pods\n\t// but whose last attempts at creating a pod have failed (since\n\t// we don't block on creation of pods) instead of those\n\t// replica sets stalling indefinitely. Enqueueing every time\n\t// does result in some spurious syncs (like when Status.Replica\n\t// is updated and the watch notification from it retriggers\n\t// this function), but in general extra resyncs shouldn't be\n\t// that bad as ReplicaSets that haven't met expectations yet won't\n\t// sync, and all the listing is done using local stores.\n\tif *(oldRS.Spec.Replicas) != *(curRS.Spec.Replicas) {\n\t\tklog.V(4).Infof(\"%v %v updated. Desired pod count change: %d-\u003e%d\", rsc.Kind, curRS.Name, *(oldRS.Spec.Replicas), *(curRS.Spec.Replicas))\n\t}\n\trsc.enqueueRS(curRS)\n}","line":{"from":302,"to":336}} {"id":100004459,"name":"deleteRS","signature":"func (rsc *ReplicaSetController) deleteRS(obj interface{})","file":"pkg/controller/replicaset/replica_set.go","code":"func (rsc *ReplicaSetController) deleteRS(obj interface{}) {\n\trs, ok := obj.(*apps.ReplicaSet)\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get object from tombstone %#v\", obj))\n\t\t\treturn\n\t\t}\n\t\trs, ok = tombstone.Obj.(*apps.ReplicaSet)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"tombstone contained object that is not a ReplicaSet %#v\", obj))\n\t\t\treturn\n\t\t}\n\t}\n\n\tkey, err := controller.KeyFunc(rs)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get key for object %#v: %v\", rs, err))\n\t\treturn\n\t}\n\n\tklog.V(4).Infof(\"Deleting %s %q\", rsc.Kind, key)\n\n\t// Delete expectations for the ReplicaSet so if we create a new one with the same name it starts clean\n\trsc.expectations.DeleteExpectations(key)\n\n\trsc.queue.Add(key)\n}","line":{"from":338,"to":365}} {"id":100004460,"name":"addPod","signature":"func (rsc *ReplicaSetController) addPod(obj interface{})","file":"pkg/controller/replicaset/replica_set.go","code":"// When a pod is created, enqueue the replica set that manages it and update its expectations.\nfunc (rsc *ReplicaSetController) addPod(obj interface{}) {\n\tpod := obj.(*v1.Pod)\n\n\tif pod.DeletionTimestamp != nil {\n\t\t// on a restart of the controller manager, it's possible a new pod shows up in a state that\n\t\t// is already pending deletion. Prevent the pod from being a creation observation.\n\t\trsc.deletePod(pod)\n\t\treturn\n\t}\n\n\t// If it has a ControllerRef, that's all that matters.\n\tif controllerRef := metav1.GetControllerOf(pod); controllerRef != nil {\n\t\trs := rsc.resolveControllerRef(pod.Namespace, controllerRef)\n\t\tif rs == nil {\n\t\t\treturn\n\t\t}\n\t\trsKey, err := controller.KeyFunc(rs)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tklog.V(4).Infof(\"Pod %s created: %#v.\", pod.Name, pod)\n\t\trsc.expectations.CreationObserved(rsKey)\n\t\trsc.queue.Add(rsKey)\n\t\treturn\n\t}\n\n\t// Otherwise, it's an orphan. Get a list of all matching ReplicaSets and sync\n\t// them to see if anyone wants to adopt it.\n\t// DO NOT observe creation because no controller should be waiting for an\n\t// orphan.\n\trss := rsc.getPodReplicaSets(pod)\n\tif len(rss) == 0 {\n\t\treturn\n\t}\n\tklog.V(4).Infof(\"Orphan Pod %s created: %#v.\", pod.Name, pod)\n\tfor _, rs := range rss {\n\t\trsc.enqueueRS(rs)\n\t}\n}","line":{"from":367,"to":406}} {"id":100004461,"name":"updatePod","signature":"func (rsc *ReplicaSetController) updatePod(old, cur interface{})","file":"pkg/controller/replicaset/replica_set.go","code":"// When a pod is updated, figure out what replica set/s manage it and wake them\n// up. If the labels of the pod have changed we need to awaken both the old\n// and new replica set. old and cur must be *v1.Pod types.\nfunc (rsc *ReplicaSetController) updatePod(old, cur interface{}) {\n\tcurPod := cur.(*v1.Pod)\n\toldPod := old.(*v1.Pod)\n\tif curPod.ResourceVersion == oldPod.ResourceVersion {\n\t\t// Periodic resync will send update events for all known pods.\n\t\t// Two different versions of the same pod will always have different RVs.\n\t\treturn\n\t}\n\n\tlabelChanged := !reflect.DeepEqual(curPod.Labels, oldPod.Labels)\n\tif curPod.DeletionTimestamp != nil {\n\t\t// when a pod is deleted gracefully it's deletion timestamp is first modified to reflect a grace period,\n\t\t// and after such time has passed, the kubelet actually deletes it from the store. We receive an update\n\t\t// for modification of the deletion timestamp and expect an rs to create more replicas asap, not wait\n\t\t// until the kubelet actually deletes the pod. This is different from the Phase of a pod changing, because\n\t\t// an rs never initiates a phase change, and so is never asleep waiting for the same.\n\t\trsc.deletePod(curPod)\n\t\tif labelChanged {\n\t\t\t// we don't need to check the oldPod.DeletionTimestamp because DeletionTimestamp cannot be unset.\n\t\t\trsc.deletePod(oldPod)\n\t\t}\n\t\treturn\n\t}\n\n\tcurControllerRef := metav1.GetControllerOf(curPod)\n\toldControllerRef := metav1.GetControllerOf(oldPod)\n\tcontrollerRefChanged := !reflect.DeepEqual(curControllerRef, oldControllerRef)\n\tif controllerRefChanged \u0026\u0026 oldControllerRef != nil {\n\t\t// The ControllerRef was changed. Sync the old controller, if any.\n\t\tif rs := rsc.resolveControllerRef(oldPod.Namespace, oldControllerRef); rs != nil {\n\t\t\trsc.enqueueRS(rs)\n\t\t}\n\t}\n\n\t// If it has a ControllerRef, that's all that matters.\n\tif curControllerRef != nil {\n\t\trs := rsc.resolveControllerRef(curPod.Namespace, curControllerRef)\n\t\tif rs == nil {\n\t\t\treturn\n\t\t}\n\t\tklog.V(4).Infof(\"Pod %s updated, objectMeta %+v -\u003e %+v.\", curPod.Name, oldPod.ObjectMeta, curPod.ObjectMeta)\n\t\trsc.enqueueRS(rs)\n\t\t// TODO: MinReadySeconds in the Pod will generate an Available condition to be added in\n\t\t// the Pod status which in turn will trigger a requeue of the owning replica set thus\n\t\t// having its status updated with the newly available replica. For now, we can fake the\n\t\t// update by resyncing the controller MinReadySeconds after the it is requeued because\n\t\t// a Pod transitioned to Ready.\n\t\t// Note that this still suffers from #29229, we are just moving the problem one level\n\t\t// \"closer\" to kubelet (from the deployment to the replica set controller).\n\t\tif !podutil.IsPodReady(oldPod) \u0026\u0026 podutil.IsPodReady(curPod) \u0026\u0026 rs.Spec.MinReadySeconds \u003e 0 {\n\t\t\tklog.V(2).Infof(\"%v %q will be enqueued after %ds for availability check\", rsc.Kind, rs.Name, rs.Spec.MinReadySeconds)\n\t\t\t// Add a second to avoid milliseconds skew in AddAfter.\n\t\t\t// See https://github.com/kubernetes/kubernetes/issues/39785#issuecomment-279959133 for more info.\n\t\t\trsc.enqueueRSAfter(rs, (time.Duration(rs.Spec.MinReadySeconds)*time.Second)+time.Second)\n\t\t}\n\t\treturn\n\t}\n\n\t// Otherwise, it's an orphan. If anything changed, sync matching controllers\n\t// to see if anyone wants to adopt it now.\n\tif labelChanged || controllerRefChanged {\n\t\trss := rsc.getPodReplicaSets(curPod)\n\t\tif len(rss) == 0 {\n\t\t\treturn\n\t\t}\n\t\tklog.V(4).Infof(\"Orphan Pod %s updated, objectMeta %+v -\u003e %+v.\", curPod.Name, oldPod.ObjectMeta, curPod.ObjectMeta)\n\t\tfor _, rs := range rss {\n\t\t\trsc.enqueueRS(rs)\n\t\t}\n\t}\n}","line":{"from":408,"to":481}} {"id":100004462,"name":"deletePod","signature":"func (rsc *ReplicaSetController) deletePod(obj interface{})","file":"pkg/controller/replicaset/replica_set.go","code":"// When a pod is deleted, enqueue the replica set that manages the pod and update its expectations.\n// obj could be an *v1.Pod, or a DeletionFinalStateUnknown marker item.\nfunc (rsc *ReplicaSetController) deletePod(obj interface{}) {\n\tpod, ok := obj.(*v1.Pod)\n\n\t// When a delete is dropped, the relist will notice a pod in the store not\n\t// in the list, leading to the insertion of a tombstone object which contains\n\t// the deleted key/value. Note that this value might be stale. If the pod\n\t// changed labels the new ReplicaSet will not be woken up till the periodic resync.\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get object from tombstone %+v\", obj))\n\t\t\treturn\n\t\t}\n\t\tpod, ok = tombstone.Obj.(*v1.Pod)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"tombstone contained object that is not a pod %#v\", obj))\n\t\t\treturn\n\t\t}\n\t}\n\n\tcontrollerRef := metav1.GetControllerOf(pod)\n\tif controllerRef == nil {\n\t\t// No controller should care about orphans being deleted.\n\t\treturn\n\t}\n\trs := rsc.resolveControllerRef(pod.Namespace, controllerRef)\n\tif rs == nil {\n\t\treturn\n\t}\n\trsKey, err := controller.KeyFunc(rs)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get key for object %#v: %v\", rs, err))\n\t\treturn\n\t}\n\tklog.V(4).Infof(\"Pod %s/%s deleted through %v, timestamp %+v: %#v.\", pod.Namespace, pod.Name, utilruntime.GetCaller(), pod.DeletionTimestamp, pod)\n\trsc.expectations.DeletionObserved(rsKey, controller.PodKey(pod))\n\trsc.queue.Add(rsKey)\n}","line":{"from":483,"to":522}} {"id":100004463,"name":"worker","signature":"func (rsc *ReplicaSetController) worker(ctx context.Context)","file":"pkg/controller/replicaset/replica_set.go","code":"// worker runs a worker thread that just dequeues items, processes them, and marks them done.\n// It enforces that the syncHandler is never invoked concurrently with the same key.\nfunc (rsc *ReplicaSetController) worker(ctx context.Context) {\n\tfor rsc.processNextWorkItem(ctx) {\n\t}\n}","line":{"from":524,"to":529}} {"id":100004464,"name":"processNextWorkItem","signature":"func (rsc *ReplicaSetController) processNextWorkItem(ctx context.Context) bool","file":"pkg/controller/replicaset/replica_set.go","code":"func (rsc *ReplicaSetController) processNextWorkItem(ctx context.Context) bool {\n\tkey, quit := rsc.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer rsc.queue.Done(key)\n\n\terr := rsc.syncHandler(ctx, key.(string))\n\tif err == nil {\n\t\trsc.queue.Forget(key)\n\t\treturn true\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"sync %q failed with %v\", key, err))\n\trsc.queue.AddRateLimited(key)\n\n\treturn true\n}","line":{"from":531,"to":548}} {"id":100004465,"name":"manageReplicas","signature":"func (rsc *ReplicaSetController) manageReplicas(ctx context.Context, filteredPods []*v1.Pod, rs *apps.ReplicaSet) error","file":"pkg/controller/replicaset/replica_set.go","code":"// manageReplicas checks and updates replicas for the given ReplicaSet.\n// Does NOT modify \u003cfilteredPods\u003e.\n// It will requeue the replica set in case of an error while creating/deleting pods.\nfunc (rsc *ReplicaSetController) manageReplicas(ctx context.Context, filteredPods []*v1.Pod, rs *apps.ReplicaSet) error {\n\tdiff := len(filteredPods) - int(*(rs.Spec.Replicas))\n\trsKey, err := controller.KeyFunc(rs)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get key for %v %#v: %v\", rsc.Kind, rs, err))\n\t\treturn nil\n\t}\n\tif diff \u003c 0 {\n\t\tdiff *= -1\n\t\tif diff \u003e rsc.burstReplicas {\n\t\t\tdiff = rsc.burstReplicas\n\t\t}\n\t\t// TODO: Track UIDs of creates just like deletes. The problem currently\n\t\t// is we'd need to wait on the result of a create to record the pod's\n\t\t// UID, which would require locking *across* the create, which will turn\n\t\t// into a performance bottleneck. We should generate a UID for the pod\n\t\t// beforehand and store it via ExpectCreations.\n\t\trsc.expectations.ExpectCreations(rsKey, diff)\n\t\tklog.FromContext(ctx).V(2).Info(\"Too few replicas\", \"replicaSet\", klog.KObj(rs), \"need\", *(rs.Spec.Replicas), \"creating\", diff)\n\t\t// Batch the pod creates. Batch sizes start at SlowStartInitialBatchSize\n\t\t// and double with each successful iteration in a kind of \"slow start\".\n\t\t// This handles attempts to start large numbers of pods that would\n\t\t// likely all fail with the same error. For example a project with a\n\t\t// low quota that attempts to create a large number of pods will be\n\t\t// prevented from spamming the API service with the pod create requests\n\t\t// after one of its pods fails. Conveniently, this also prevents the\n\t\t// event spam that those failures would generate.\n\t\tsuccessfulCreations, err := slowStartBatch(diff, controller.SlowStartInitialBatchSize, func() error {\n\t\t\terr := rsc.podControl.CreatePods(ctx, rs.Namespace, \u0026rs.Spec.Template, rs, metav1.NewControllerRef(rs, rsc.GroupVersionKind))\n\t\t\tif err != nil {\n\t\t\t\tif apierrors.HasStatusCause(err, v1.NamespaceTerminatingCause) {\n\t\t\t\t\t// if the namespace is being terminated, we don't have to do\n\t\t\t\t\t// anything because any creation will fail\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn err\n\t\t})\n\n\t\t// Any skipped pods that we never attempted to start shouldn't be expected.\n\t\t// The skipped pods will be retried later. The next controller resync will\n\t\t// retry the slow start process.\n\t\tif skippedPods := diff - successfulCreations; skippedPods \u003e 0 {\n\t\t\tklog.FromContext(ctx).V(2).Info(\"Slow-start failure. Skipping creation of pods, decrementing expectations\", \"podsSkipped\", skippedPods, \"kind\", rsc.Kind, \"replicaSet\", klog.KObj(rs))\n\t\t\tfor i := 0; i \u003c skippedPods; i++ {\n\t\t\t\t// Decrement the expected number of creates because the informer won't observe this pod\n\t\t\t\trsc.expectations.CreationObserved(rsKey)\n\t\t\t}\n\t\t}\n\t\treturn err\n\t} else if diff \u003e 0 {\n\t\tif diff \u003e rsc.burstReplicas {\n\t\t\tdiff = rsc.burstReplicas\n\t\t}\n\t\tklog.FromContext(ctx).V(2).Info(\"Too many replicas\", \"replicaSet\", klog.KObj(rs), \"need\", *(rs.Spec.Replicas), \"deleting\", diff)\n\n\t\trelatedPods, err := rsc.getIndirectlyRelatedPods(klog.FromContext(ctx), rs)\n\t\tutilruntime.HandleError(err)\n\n\t\t// Choose which Pods to delete, preferring those in earlier phases of startup.\n\t\tpodsToDelete := getPodsToDelete(filteredPods, relatedPods, diff)\n\n\t\t// Snapshot the UIDs (ns/name) of the pods we're expecting to see\n\t\t// deleted, so we know to record their expectations exactly once either\n\t\t// when we see it as an update of the deletion timestamp, or as a delete.\n\t\t// Note that if the labels on a pod/rs change in a way that the pod gets\n\t\t// orphaned, the rs will only wake up after the expectations have\n\t\t// expired even if other pods are deleted.\n\t\trsc.expectations.ExpectDeletions(rsKey, getPodKeys(podsToDelete))\n\n\t\terrCh := make(chan error, diff)\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(diff)\n\t\tfor _, pod := range podsToDelete {\n\t\t\tgo func(targetPod *v1.Pod) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tif err := rsc.podControl.DeletePod(ctx, rs.Namespace, targetPod.Name, rs); err != nil {\n\t\t\t\t\t// Decrement the expected number of deletes because the informer won't observe this deletion\n\t\t\t\t\tpodKey := controller.PodKey(targetPod)\n\t\t\t\t\trsc.expectations.DeletionObserved(rsKey, podKey)\n\t\t\t\t\tif !apierrors.IsNotFound(err) {\n\t\t\t\t\t\tklog.FromContext(ctx).V(2).Info(\"Failed to delete pod, decremented expectations\", \"pod\", podKey, \"kind\", rsc.Kind, \"replicaSet\", klog.KObj(rs))\n\t\t\t\t\t\terrCh \u003c- err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}(pod)\n\t\t}\n\t\twg.Wait()\n\n\t\tselect {\n\t\tcase err := \u003c-errCh:\n\t\t\t// all errors have been reported before and they're likely to be the same, so we'll only return the first one we hit.\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":550,"to":653}} {"id":100004466,"name":"syncReplicaSet","signature":"func (rsc *ReplicaSetController) syncReplicaSet(ctx context.Context, key string) error","file":"pkg/controller/replicaset/replica_set.go","code":"// syncReplicaSet will sync the ReplicaSet with the given key if it has had its expectations fulfilled,\n// meaning it did not expect to see any more of its pods created or deleted. This function is not meant to be\n// invoked concurrently with the same key.\nfunc (rsc *ReplicaSetController) syncReplicaSet(ctx context.Context, key string) error {\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tklog.FromContext(ctx).V(4).Info(\"Finished syncing\", \"kind\", rsc.Kind, \"key\", key, \"duration\", time.Since(startTime))\n\t}()\n\n\tnamespace, name, err := cache.SplitMetaNamespaceKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\trs, err := rsc.rsLister.ReplicaSets(namespace).Get(name)\n\tif apierrors.IsNotFound(err) {\n\t\tklog.FromContext(ctx).V(4).Info(\"deleted\", \"kind\", rsc.Kind, \"key\", key)\n\t\trsc.expectations.DeleteExpectations(key)\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trsNeedsSync := rsc.expectations.SatisfiedExpectations(key)\n\tselector, err := metav1.LabelSelectorAsSelector(rs.Spec.Selector)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"error converting pod selector to selector for rs %v/%v: %v\", namespace, name, err))\n\t\treturn nil\n\t}\n\n\t// list all pods to include the pods that don't match the rs`s selector\n\t// anymore but has the stale controller ref.\n\t// TODO: Do the List and Filter in a single pass, or use an index.\n\tallPods, err := rsc.podLister.Pods(rs.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Ignore inactive pods.\n\tfilteredPods := controller.FilterActivePods(allPods)\n\n\t// NOTE: filteredPods are pointing to objects from cache - if you need to\n\t// modify them, you need to copy it first.\n\tfilteredPods, err = rsc.claimPods(ctx, rs, selector, filteredPods)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar manageReplicasErr error\n\tif rsNeedsSync \u0026\u0026 rs.DeletionTimestamp == nil {\n\t\tmanageReplicasErr = rsc.manageReplicas(ctx, filteredPods, rs)\n\t}\n\trs = rs.DeepCopy()\n\tnewStatus := calculateStatus(rs, filteredPods, manageReplicasErr)\n\n\t// Always updates status as pods come up or die.\n\tupdatedRS, err := updateReplicaSetStatus(klog.FromContext(ctx), rsc.kubeClient.AppsV1().ReplicaSets(rs.Namespace), rs, newStatus)\n\tif err != nil {\n\t\t// Multiple things could lead to this update failing. Requeuing the replica set ensures\n\t\t// Returning an error causes a requeue without forcing a hotloop\n\t\treturn err\n\t}\n\t// Resync the ReplicaSet after MinReadySeconds as a last line of defense to guard against clock-skew.\n\tif manageReplicasErr == nil \u0026\u0026 updatedRS.Spec.MinReadySeconds \u003e 0 \u0026\u0026\n\t\tupdatedRS.Status.ReadyReplicas == *(updatedRS.Spec.Replicas) \u0026\u0026\n\t\tupdatedRS.Status.AvailableReplicas != *(updatedRS.Spec.Replicas) {\n\t\trsc.queue.AddAfter(key, time.Duration(updatedRS.Spec.MinReadySeconds)*time.Second)\n\t}\n\treturn manageReplicasErr\n}","line":{"from":655,"to":723}} {"id":100004467,"name":"claimPods","signature":"func (rsc *ReplicaSetController) claimPods(ctx context.Context, rs *apps.ReplicaSet, selector labels.Selector, filteredPods []*v1.Pod) ([]*v1.Pod, error)","file":"pkg/controller/replicaset/replica_set.go","code":"func (rsc *ReplicaSetController) claimPods(ctx context.Context, rs *apps.ReplicaSet, selector labels.Selector, filteredPods []*v1.Pod) ([]*v1.Pod, error) {\n\t// If any adoptions are attempted, we should first recheck for deletion with\n\t// an uncached quorum read sometime after listing Pods (see #42639).\n\tcanAdoptFunc := controller.RecheckDeletionTimestamp(func(ctx context.Context) (metav1.Object, error) {\n\t\tfresh, err := rsc.kubeClient.AppsV1().ReplicaSets(rs.Namespace).Get(ctx, rs.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif fresh.UID != rs.UID {\n\t\t\treturn nil, fmt.Errorf(\"original %v %v/%v is gone: got uid %v, wanted %v\", rsc.Kind, rs.Namespace, rs.Name, fresh.UID, rs.UID)\n\t\t}\n\t\treturn fresh, nil\n\t})\n\tcm := controller.NewPodControllerRefManager(rsc.podControl, rs, selector, rsc.GroupVersionKind, canAdoptFunc)\n\treturn cm.ClaimPods(ctx, filteredPods)\n}","line":{"from":725,"to":740}} {"id":100004468,"name":"slowStartBatch","signature":"func slowStartBatch(count int, initialBatchSize int, fn func() error) (int, error)","file":"pkg/controller/replicaset/replica_set.go","code":"// slowStartBatch tries to call the provided function a total of 'count' times,\n// starting slow to check for errors, then speeding up if calls succeed.\n//\n// It groups the calls into batches, starting with a group of initialBatchSize.\n// Within each batch, it may call the function multiple times concurrently.\n//\n// If a whole batch succeeds, the next batch may get exponentially larger.\n// If there are any failures in a batch, all remaining batches are skipped\n// after waiting for the current batch to complete.\n//\n// It returns the number of successful calls to the function.\nfunc slowStartBatch(count int, initialBatchSize int, fn func() error) (int, error) {\n\tremaining := count\n\tsuccesses := 0\n\tfor batchSize := integer.IntMin(remaining, initialBatchSize); batchSize \u003e 0; batchSize = integer.IntMin(2*batchSize, remaining) {\n\t\terrCh := make(chan error, batchSize)\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(batchSize)\n\t\tfor i := 0; i \u003c batchSize; i++ {\n\t\t\tgo func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tif err := fn(); err != nil {\n\t\t\t\t\terrCh \u003c- err\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\twg.Wait()\n\t\tcurSuccesses := batchSize - len(errCh)\n\t\tsuccesses += curSuccesses\n\t\tif len(errCh) \u003e 0 {\n\t\t\treturn successes, \u003c-errCh\n\t\t}\n\t\tremaining -= batchSize\n\t}\n\treturn successes, nil\n}","line":{"from":742,"to":777}} {"id":100004469,"name":"getIndirectlyRelatedPods","signature":"func (rsc *ReplicaSetController) getIndirectlyRelatedPods(logger klog.Logger, rs *apps.ReplicaSet) ([]*v1.Pod, error)","file":"pkg/controller/replicaset/replica_set.go","code":"// getIndirectlyRelatedPods returns all pods that are owned by any ReplicaSet\n// that is owned by the given ReplicaSet's owner.\nfunc (rsc *ReplicaSetController) getIndirectlyRelatedPods(logger klog.Logger, rs *apps.ReplicaSet) ([]*v1.Pod, error) {\n\tvar relatedPods []*v1.Pod\n\tseen := make(map[types.UID]*apps.ReplicaSet)\n\tfor _, relatedRS := range rsc.getReplicaSetsWithSameController(logger, rs) {\n\t\tselector, err := metav1.LabelSelectorAsSelector(relatedRS.Spec.Selector)\n\t\tif err != nil {\n\t\t\t// This object has an invalid selector, it does not match any pods\n\t\t\tcontinue\n\t\t}\n\t\tpods, err := rsc.podLister.Pods(relatedRS.Namespace).List(selector)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, pod := range pods {\n\t\t\tif otherRS, found := seen[pod.UID]; found {\n\t\t\t\tlogger.V(5).Info(\"Pod is owned by both\", \"pod\", klog.KObj(pod), \"kind\", rsc.Kind, \"replicaSets\", klog.KObjSlice([]klog.KMetadata{otherRS, relatedRS}))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tseen[pod.UID] = relatedRS\n\t\t\trelatedPods = append(relatedPods, pod)\n\t\t}\n\t}\n\tlogger.V(4).Info(\"Found related pods\", \"kind\", rsc.Kind, \"replicaSet\", klog.KObj(rs), \"pods\", klog.KObjSlice(relatedPods))\n\treturn relatedPods, nil\n}","line":{"from":779,"to":805}} {"id":100004470,"name":"getPodsToDelete","signature":"func getPodsToDelete(filteredPods, relatedPods []*v1.Pod, diff int) []*v1.Pod","file":"pkg/controller/replicaset/replica_set.go","code":"func getPodsToDelete(filteredPods, relatedPods []*v1.Pod, diff int) []*v1.Pod {\n\t// No need to sort pods if we are about to delete all of them.\n\t// diff will always be \u003c= len(filteredPods), so not need to handle \u003e case.\n\tif diff \u003c len(filteredPods) {\n\t\tpodsWithRanks := getPodsRankedByRelatedPodsOnSameNode(filteredPods, relatedPods)\n\t\tsort.Sort(podsWithRanks)\n\t\treportSortingDeletionAgeRatioMetric(filteredPods, diff)\n\t}\n\treturn filteredPods[:diff]\n}","line":{"from":807,"to":816}} {"id":100004471,"name":"reportSortingDeletionAgeRatioMetric","signature":"func reportSortingDeletionAgeRatioMetric(filteredPods []*v1.Pod, diff int)","file":"pkg/controller/replicaset/replica_set.go","code":"func reportSortingDeletionAgeRatioMetric(filteredPods []*v1.Pod, diff int) {\n\tnow := time.Now()\n\tyoungestTime := time.Time{}\n\t// first we need to check all of the ready pods to get the youngest, as they may not necessarily be sorted by timestamp alone\n\tfor _, pod := range filteredPods {\n\t\tif pod.CreationTimestamp.Time.After(youngestTime) \u0026\u0026 podutil.IsPodReady(pod) {\n\t\t\tyoungestTime = pod.CreationTimestamp.Time\n\t\t}\n\t}\n\n\t// for each pod chosen for deletion, report the ratio of its age to the youngest pod's age\n\tfor _, pod := range filteredPods[:diff] {\n\t\tif !podutil.IsPodReady(pod) {\n\t\t\tcontinue\n\t\t}\n\t\tratio := float64(now.Sub(pod.CreationTimestamp.Time).Milliseconds() / now.Sub(youngestTime).Milliseconds())\n\t\tmetrics.SortingDeletionAgeRatio.Observe(ratio)\n\t}\n}","line":{"from":818,"to":836}} {"id":100004472,"name":"getPodsRankedByRelatedPodsOnSameNode","signature":"func getPodsRankedByRelatedPodsOnSameNode(podsToRank, relatedPods []*v1.Pod) controller.ActivePodsWithRanks","file":"pkg/controller/replicaset/replica_set.go","code":"// getPodsRankedByRelatedPodsOnSameNode returns an ActivePodsWithRanks value\n// that wraps podsToRank and assigns each pod a rank equal to the number of\n// active pods in relatedPods that are colocated on the same node with the pod.\n// relatedPods generally should be a superset of podsToRank.\nfunc getPodsRankedByRelatedPodsOnSameNode(podsToRank, relatedPods []*v1.Pod) controller.ActivePodsWithRanks {\n\tpodsOnNode := make(map[string]int)\n\tfor _, pod := range relatedPods {\n\t\tif controller.IsPodActive(pod) {\n\t\t\tpodsOnNode[pod.Spec.NodeName]++\n\t\t}\n\t}\n\tranks := make([]int, len(podsToRank))\n\tfor i, pod := range podsToRank {\n\t\tranks[i] = podsOnNode[pod.Spec.NodeName]\n\t}\n\treturn controller.ActivePodsWithRanks{Pods: podsToRank, Rank: ranks, Now: metav1.Now()}\n}","line":{"from":838,"to":854}} {"id":100004473,"name":"getPodKeys","signature":"func getPodKeys(pods []*v1.Pod) []string","file":"pkg/controller/replicaset/replica_set.go","code":"func getPodKeys(pods []*v1.Pod) []string {\n\tpodKeys := make([]string, 0, len(pods))\n\tfor _, pod := range pods {\n\t\tpodKeys = append(podKeys, controller.PodKey(pod))\n\t}\n\treturn podKeys\n}","line":{"from":856,"to":862}} {"id":100004474,"name":"updateReplicaSetStatus","signature":"func updateReplicaSetStatus(logger klog.Logger, c appsclient.ReplicaSetInterface, rs *apps.ReplicaSet, newStatus apps.ReplicaSetStatus) (*apps.ReplicaSet, error)","file":"pkg/controller/replicaset/replica_set_utils.go","code":"// updateReplicaSetStatus attempts to update the Status.Replicas of the given ReplicaSet, with a single GET/PUT retry.\nfunc updateReplicaSetStatus(logger klog.Logger, c appsclient.ReplicaSetInterface, rs *apps.ReplicaSet, newStatus apps.ReplicaSetStatus) (*apps.ReplicaSet, error) {\n\t// This is the steady state. It happens when the ReplicaSet doesn't have any expectations, since\n\t// we do a periodic relist every 30s. If the generations differ but the replicas are\n\t// the same, a caller might've resized to the same replica count.\n\tif rs.Status.Replicas == newStatus.Replicas \u0026\u0026\n\t\trs.Status.FullyLabeledReplicas == newStatus.FullyLabeledReplicas \u0026\u0026\n\t\trs.Status.ReadyReplicas == newStatus.ReadyReplicas \u0026\u0026\n\t\trs.Status.AvailableReplicas == newStatus.AvailableReplicas \u0026\u0026\n\t\trs.Generation == rs.Status.ObservedGeneration \u0026\u0026\n\t\treflect.DeepEqual(rs.Status.Conditions, newStatus.Conditions) {\n\t\treturn rs, nil\n\t}\n\n\t// Save the generation number we acted on, otherwise we might wrongfully indicate\n\t// that we've seen a spec update when we retry.\n\t// TODO: This can clobber an update if we allow multiple agents to write to the\n\t// same status.\n\tnewStatus.ObservedGeneration = rs.Generation\n\n\tvar getErr, updateErr error\n\tvar updatedRS *apps.ReplicaSet\n\tfor i, rs := 0, rs; ; i++ {\n\t\tlogger.V(4).Info(fmt.Sprintf(\"Updating status for %v: %s/%s, \", rs.Kind, rs.Namespace, rs.Name) +\n\t\t\tfmt.Sprintf(\"replicas %d-\u003e%d (need %d), \", rs.Status.Replicas, newStatus.Replicas, *(rs.Spec.Replicas)) +\n\t\t\tfmt.Sprintf(\"fullyLabeledReplicas %d-\u003e%d, \", rs.Status.FullyLabeledReplicas, newStatus.FullyLabeledReplicas) +\n\t\t\tfmt.Sprintf(\"readyReplicas %d-\u003e%d, \", rs.Status.ReadyReplicas, newStatus.ReadyReplicas) +\n\t\t\tfmt.Sprintf(\"availableReplicas %d-\u003e%d, \", rs.Status.AvailableReplicas, newStatus.AvailableReplicas) +\n\t\t\tfmt.Sprintf(\"sequence No: %v-\u003e%v\", rs.Status.ObservedGeneration, newStatus.ObservedGeneration))\n\n\t\trs.Status = newStatus\n\t\tupdatedRS, updateErr = c.UpdateStatus(context.TODO(), rs, metav1.UpdateOptions{})\n\t\tif updateErr == nil {\n\t\t\treturn updatedRS, nil\n\t\t}\n\t\t// Stop retrying if we exceed statusUpdateRetries - the replicaSet will be requeued with a rate limit.\n\t\tif i \u003e= statusUpdateRetries {\n\t\t\tbreak\n\t\t}\n\t\t// Update the ReplicaSet with the latest resource version for the next poll\n\t\tif rs, getErr = c.Get(context.TODO(), rs.Name, metav1.GetOptions{}); getErr != nil {\n\t\t\t// If the GET fails we can't trust status.Replicas anymore. This error\n\t\t\t// is bound to be more interesting than the update failure.\n\t\t\treturn nil, getErr\n\t\t}\n\t}\n\n\treturn nil, updateErr\n}","line":{"from":36,"to":84}} {"id":100004475,"name":"calculateStatus","signature":"func calculateStatus(rs *apps.ReplicaSet, filteredPods []*v1.Pod, manageReplicasErr error) apps.ReplicaSetStatus","file":"pkg/controller/replicaset/replica_set_utils.go","code":"func calculateStatus(rs *apps.ReplicaSet, filteredPods []*v1.Pod, manageReplicasErr error) apps.ReplicaSetStatus {\n\tnewStatus := rs.Status\n\t// Count the number of pods that have labels matching the labels of the pod\n\t// template of the replica set, the matching pods may have more\n\t// labels than are in the template. Because the label of podTemplateSpec is\n\t// a superset of the selector of the replica set, so the possible\n\t// matching pods must be part of the filteredPods.\n\tfullyLabeledReplicasCount := 0\n\treadyReplicasCount := 0\n\tavailableReplicasCount := 0\n\ttemplateLabel := labels.Set(rs.Spec.Template.Labels).AsSelectorPreValidated()\n\tfor _, pod := range filteredPods {\n\t\tif templateLabel.Matches(labels.Set(pod.Labels)) {\n\t\t\tfullyLabeledReplicasCount++\n\t\t}\n\t\tif podutil.IsPodReady(pod) {\n\t\t\treadyReplicasCount++\n\t\t\tif podutil.IsPodAvailable(pod, rs.Spec.MinReadySeconds, metav1.Now()) {\n\t\t\t\tavailableReplicasCount++\n\t\t\t}\n\t\t}\n\t}\n\n\tfailureCond := GetCondition(rs.Status, apps.ReplicaSetReplicaFailure)\n\tif manageReplicasErr != nil \u0026\u0026 failureCond == nil {\n\t\tvar reason string\n\t\tif diff := len(filteredPods) - int(*(rs.Spec.Replicas)); diff \u003c 0 {\n\t\t\treason = \"FailedCreate\"\n\t\t} else if diff \u003e 0 {\n\t\t\treason = \"FailedDelete\"\n\t\t}\n\t\tcond := NewReplicaSetCondition(apps.ReplicaSetReplicaFailure, v1.ConditionTrue, reason, manageReplicasErr.Error())\n\t\tSetCondition(\u0026newStatus, cond)\n\t} else if manageReplicasErr == nil \u0026\u0026 failureCond != nil {\n\t\tRemoveCondition(\u0026newStatus, apps.ReplicaSetReplicaFailure)\n\t}\n\n\tnewStatus.Replicas = int32(len(filteredPods))\n\tnewStatus.FullyLabeledReplicas = int32(fullyLabeledReplicasCount)\n\tnewStatus.ReadyReplicas = int32(readyReplicasCount)\n\tnewStatus.AvailableReplicas = int32(availableReplicasCount)\n\treturn newStatus\n}","line":{"from":86,"to":128}} {"id":100004476,"name":"NewReplicaSetCondition","signature":"func NewReplicaSetCondition(condType apps.ReplicaSetConditionType, status v1.ConditionStatus, reason, msg string) apps.ReplicaSetCondition","file":"pkg/controller/replicaset/replica_set_utils.go","code":"// NewReplicaSetCondition creates a new replicaset condition.\nfunc NewReplicaSetCondition(condType apps.ReplicaSetConditionType, status v1.ConditionStatus, reason, msg string) apps.ReplicaSetCondition {\n\treturn apps.ReplicaSetCondition{\n\t\tType: condType,\n\t\tStatus: status,\n\t\tLastTransitionTime: metav1.Now(),\n\t\tReason: reason,\n\t\tMessage: msg,\n\t}\n}","line":{"from":130,"to":139}} {"id":100004477,"name":"GetCondition","signature":"func GetCondition(status apps.ReplicaSetStatus, condType apps.ReplicaSetConditionType) *apps.ReplicaSetCondition","file":"pkg/controller/replicaset/replica_set_utils.go","code":"// GetCondition returns a replicaset condition with the provided type if it exists.\nfunc GetCondition(status apps.ReplicaSetStatus, condType apps.ReplicaSetConditionType) *apps.ReplicaSetCondition {\n\tfor _, c := range status.Conditions {\n\t\tif c.Type == condType {\n\t\t\treturn \u0026c\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":141,"to":149}} {"id":100004478,"name":"SetCondition","signature":"func SetCondition(status *apps.ReplicaSetStatus, condition apps.ReplicaSetCondition)","file":"pkg/controller/replicaset/replica_set_utils.go","code":"// SetCondition adds/replaces the given condition in the replicaset status. If the condition that we\n// are about to add already exists and has the same status and reason then we are not going to update.\nfunc SetCondition(status *apps.ReplicaSetStatus, condition apps.ReplicaSetCondition) {\n\tcurrentCond := GetCondition(*status, condition.Type)\n\tif currentCond != nil \u0026\u0026 currentCond.Status == condition.Status \u0026\u0026 currentCond.Reason == condition.Reason {\n\t\treturn\n\t}\n\tnewConditions := filterOutCondition(status.Conditions, condition.Type)\n\tstatus.Conditions = append(newConditions, condition)\n}","line":{"from":151,"to":160}} {"id":100004479,"name":"RemoveCondition","signature":"func RemoveCondition(status *apps.ReplicaSetStatus, condType apps.ReplicaSetConditionType)","file":"pkg/controller/replicaset/replica_set_utils.go","code":"// RemoveCondition removes the condition with the provided type from the replicaset status.\nfunc RemoveCondition(status *apps.ReplicaSetStatus, condType apps.ReplicaSetConditionType) {\n\tstatus.Conditions = filterOutCondition(status.Conditions, condType)\n}","line":{"from":162,"to":165}} {"id":100004480,"name":"filterOutCondition","signature":"func filterOutCondition(conditions []apps.ReplicaSetCondition, condType apps.ReplicaSetConditionType) []apps.ReplicaSetCondition","file":"pkg/controller/replicaset/replica_set_utils.go","code":"// filterOutCondition returns a new slice of replicaset conditions without conditions with the provided type.\nfunc filterOutCondition(conditions []apps.ReplicaSetCondition, condType apps.ReplicaSetConditionType) []apps.ReplicaSetCondition {\n\tvar newConditions []apps.ReplicaSetCondition\n\tfor _, c := range conditions {\n\t\tif c.Type == condType {\n\t\t\tcontinue\n\t\t}\n\t\tnewConditions = append(newConditions, c)\n\t}\n\treturn newConditions\n}","line":{"from":167,"to":177}} {"id":100004481,"name":"Convert_v1alpha1_ReplicationControllerConfiguration_To_config_ReplicationControllerConfiguration","signature":"func Convert_v1alpha1_ReplicationControllerConfiguration_To_config_ReplicationControllerConfiguration(in *v1alpha1.ReplicationControllerConfiguration, out *config.ReplicationControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/replication/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_ReplicationControllerConfiguration_To_config_ReplicationControllerConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_ReplicationControllerConfiguration_To_config_ReplicationControllerConfiguration(in *v1alpha1.ReplicationControllerConfiguration, out *config.ReplicationControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_ReplicationControllerConfiguration_To_config_ReplicationControllerConfiguration(in, out, s)\n}","line":{"from":32,"to":35}} {"id":100004482,"name":"Convert_config_ReplicationControllerConfiguration_To_v1alpha1_ReplicationControllerConfiguration","signature":"func Convert_config_ReplicationControllerConfiguration_To_v1alpha1_ReplicationControllerConfiguration(in *config.ReplicationControllerConfiguration, out *v1alpha1.ReplicationControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/replication/config/v1alpha1/conversion.go","code":"// Convert_config_ReplicationControllerConfiguration_To_v1alpha1_ReplicationControllerConfiguration is an autogenerated conversion function.\nfunc Convert_config_ReplicationControllerConfiguration_To_v1alpha1_ReplicationControllerConfiguration(in *config.ReplicationControllerConfiguration, out *v1alpha1.ReplicationControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_ReplicationControllerConfiguration_To_v1alpha1_ReplicationControllerConfiguration(in, out, s)\n}","line":{"from":37,"to":40}} {"id":100004483,"name":"RecommendedDefaultReplicationControllerConfiguration","signature":"func RecommendedDefaultReplicationControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.ReplicationControllerConfiguration)","file":"pkg/controller/replication/config/v1alpha1/defaults.go","code":"// RecommendedDefaultReplicationControllerConfiguration defaults a pointer to a\n// ReplicationControllerConfiguration struct. This will set the recommended default\n// values, but they may be subject to change between API versions. This function\n// is intentionally not registered in the scheme as a \"normal\" `SetDefaults_Foo`\n// function to allow consumers of this type to set whatever defaults for their\n// embedded configs. Forcing consumers to use these defaults would be problematic\n// as defaulting in the scheme is done as part of the conversion, and there would\n// be no easy way to opt-out. Instead, if you want to use this defaulting method\n// run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDefaultReplicationControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.ReplicationControllerConfiguration) {\n\tif obj.ConcurrentRCSyncs == 0 {\n\t\tobj.ConcurrentRCSyncs = 5\n\t}\n}","line":{"from":23,"to":36}} {"id":100004484,"name":"Informer","signature":"func (i informerAdapter) Informer() cache.SharedIndexInformer","file":"pkg/controller/replication/conversion.go","code":"func (i informerAdapter) Informer() cache.SharedIndexInformer {\n\treturn conversionInformer{i.rcInformer.Informer()}\n}","line":{"from":60,"to":62}} {"id":100004485,"name":"Lister","signature":"func (i informerAdapter) Lister() appslisters.ReplicaSetLister","file":"pkg/controller/replication/conversion.go","code":"func (i informerAdapter) Lister() appslisters.ReplicaSetLister {\n\treturn conversionLister{i.rcInformer.Lister()}\n}","line":{"from":64,"to":66}} {"id":100004486,"name":"AddEventHandler","signature":"func (i conversionInformer) AddEventHandler(handler cache.ResourceEventHandler) (cache.ResourceEventHandlerRegistration, error)","file":"pkg/controller/replication/conversion.go","code":"func (i conversionInformer) AddEventHandler(handler cache.ResourceEventHandler) (cache.ResourceEventHandlerRegistration, error) {\n\treturn i.SharedIndexInformer.AddEventHandler(conversionEventHandler{handler})\n}","line":{"from":72,"to":74}} {"id":100004487,"name":"AddEventHandlerWithResyncPeriod","signature":"func (i conversionInformer) AddEventHandlerWithResyncPeriod(handler cache.ResourceEventHandler, resyncPeriod time.Duration) (cache.ResourceEventHandlerRegistration, error)","file":"pkg/controller/replication/conversion.go","code":"func (i conversionInformer) AddEventHandlerWithResyncPeriod(handler cache.ResourceEventHandler, resyncPeriod time.Duration) (cache.ResourceEventHandlerRegistration, error) {\n\treturn i.SharedIndexInformer.AddEventHandlerWithResyncPeriod(conversionEventHandler{handler}, resyncPeriod)\n}","line":{"from":76,"to":78}} {"id":100004488,"name":"List","signature":"func (l conversionLister) List(selector labels.Selector) ([]*apps.ReplicaSet, error)","file":"pkg/controller/replication/conversion.go","code":"func (l conversionLister) List(selector labels.Selector) ([]*apps.ReplicaSet, error) {\n\trcList, err := l.rcLister.List(selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn convertSlice(rcList)\n}","line":{"from":84,"to":90}} {"id":100004489,"name":"ReplicaSets","signature":"func (l conversionLister) ReplicaSets(namespace string) appslisters.ReplicaSetNamespaceLister","file":"pkg/controller/replication/conversion.go","code":"func (l conversionLister) ReplicaSets(namespace string) appslisters.ReplicaSetNamespaceLister {\n\treturn conversionNamespaceLister{l.rcLister.ReplicationControllers(namespace)}\n}","line":{"from":92,"to":94}} {"id":100004490,"name":"GetPodReplicaSets","signature":"func (l conversionLister) GetPodReplicaSets(pod *v1.Pod) ([]*apps.ReplicaSet, error)","file":"pkg/controller/replication/conversion.go","code":"func (l conversionLister) GetPodReplicaSets(pod *v1.Pod) ([]*apps.ReplicaSet, error) {\n\trcList, err := l.rcLister.GetPodControllers(pod)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn convertSlice(rcList)\n}","line":{"from":96,"to":102}} {"id":100004491,"name":"List","signature":"func (l conversionNamespaceLister) List(selector labels.Selector) ([]*apps.ReplicaSet, error)","file":"pkg/controller/replication/conversion.go","code":"func (l conversionNamespaceLister) List(selector labels.Selector) ([]*apps.ReplicaSet, error) {\n\trcList, err := l.rcLister.List(selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn convertSlice(rcList)\n}","line":{"from":108,"to":114}} {"id":100004492,"name":"Get","signature":"func (l conversionNamespaceLister) Get(name string) (*apps.ReplicaSet, error)","file":"pkg/controller/replication/conversion.go","code":"func (l conversionNamespaceLister) Get(name string) (*apps.ReplicaSet, error) {\n\trc, err := l.rcLister.Get(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn convertRCtoRS(rc, nil)\n}","line":{"from":116,"to":122}} {"id":100004493,"name":"OnAdd","signature":"func (h conversionEventHandler) OnAdd(obj interface{}, isInInitialList bool)","file":"pkg/controller/replication/conversion.go","code":"func (h conversionEventHandler) OnAdd(obj interface{}, isInInitialList bool) {\n\trs, err := convertRCtoRS(obj.(*v1.ReplicationController), nil)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"dropping RC OnAdd event: can't convert object %#v to RS: %v\", obj, err))\n\t\treturn\n\t}\n\th.handler.OnAdd(rs, isInInitialList)\n}","line":{"from":128,"to":135}} {"id":100004494,"name":"OnUpdate","signature":"func (h conversionEventHandler) OnUpdate(oldObj, newObj interface{})","file":"pkg/controller/replication/conversion.go","code":"func (h conversionEventHandler) OnUpdate(oldObj, newObj interface{}) {\n\toldRS, err := convertRCtoRS(oldObj.(*v1.ReplicationController), nil)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"dropping RC OnUpdate event: can't convert old object %#v to RS: %v\", oldObj, err))\n\t\treturn\n\t}\n\tnewRS, err := convertRCtoRS(newObj.(*v1.ReplicationController), nil)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"dropping RC OnUpdate event: can't convert new object %#v to RS: %v\", newObj, err))\n\t\treturn\n\t}\n\th.handler.OnUpdate(oldRS, newRS)\n}","line":{"from":137,"to":149}} {"id":100004495,"name":"OnDelete","signature":"func (h conversionEventHandler) OnDelete(obj interface{})","file":"pkg/controller/replication/conversion.go","code":"func (h conversionEventHandler) OnDelete(obj interface{}) {\n\trc, ok := obj.(*v1.ReplicationController)\n\tif !ok {\n\t\t// Convert the Obj inside DeletedFinalStateUnknown.\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"dropping RC OnDelete event: couldn't get object from tombstone %+v\", obj))\n\t\t\treturn\n\t\t}\n\t\trc, ok = tombstone.Obj.(*v1.ReplicationController)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"dropping RC OnDelete event: tombstone contained object that is not a RC %#v\", obj))\n\t\t\treturn\n\t\t}\n\t\trs, err := convertRCtoRS(rc, nil)\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"dropping RC OnDelete event: can't convert object %#v to RS: %v\", obj, err))\n\t\t\treturn\n\t\t}\n\t\th.handler.OnDelete(cache.DeletedFinalStateUnknown{Key: tombstone.Key, Obj: rs})\n\t\treturn\n\t}\n\n\t// It's a regular RC object.\n\trs, err := convertRCtoRS(rc, nil)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"dropping RC OnDelete event: can't convert object %#v to RS: %v\", obj, err))\n\t\treturn\n\t}\n\th.handler.OnDelete(rs)\n}","line":{"from":151,"to":181}} {"id":100004496,"name":"AppsV1","signature":"func (c clientsetAdapter) AppsV1() appsv1client.AppsV1Interface","file":"pkg/controller/replication/conversion.go","code":"func (c clientsetAdapter) AppsV1() appsv1client.AppsV1Interface {\n\treturn conversionAppsV1Client{c.Interface, c.Interface.AppsV1()}\n}","line":{"from":187,"to":189}} {"id":100004497,"name":"Apps","signature":"func (c clientsetAdapter) Apps() appsv1client.AppsV1Interface","file":"pkg/controller/replication/conversion.go","code":"func (c clientsetAdapter) Apps() appsv1client.AppsV1Interface {\n\treturn conversionAppsV1Client{c.Interface, c.Interface.AppsV1()}\n}","line":{"from":191,"to":193}} {"id":100004498,"name":"ReplicaSets","signature":"func (c conversionAppsV1Client) ReplicaSets(namespace string) appsv1client.ReplicaSetInterface","file":"pkg/controller/replication/conversion.go","code":"func (c conversionAppsV1Client) ReplicaSets(namespace string) appsv1client.ReplicaSetInterface {\n\treturn conversionClient{c.clientset.CoreV1().ReplicationControllers(namespace)}\n}","line":{"from":200,"to":202}} {"id":100004499,"name":"Create","signature":"func (c conversionClient) Create(ctx context.Context, rs *apps.ReplicaSet, opts metav1.CreateOptions) (*apps.ReplicaSet, error)","file":"pkg/controller/replication/conversion.go","code":"func (c conversionClient) Create(ctx context.Context, rs *apps.ReplicaSet, opts metav1.CreateOptions) (*apps.ReplicaSet, error) {\n\treturn convertCall(func(rc *v1.ReplicationController) (*v1.ReplicationController, error) {\n\t\treturn c.ReplicationControllerInterface.Create(ctx, rc, opts)\n\t}, rs)\n}","line":{"from":208,"to":212}} {"id":100004500,"name":"Update","signature":"func (c conversionClient) Update(ctx context.Context, rs *apps.ReplicaSet, opts metav1.UpdateOptions) (*apps.ReplicaSet, error)","file":"pkg/controller/replication/conversion.go","code":"func (c conversionClient) Update(ctx context.Context, rs *apps.ReplicaSet, opts metav1.UpdateOptions) (*apps.ReplicaSet, error) {\n\treturn convertCall(func(rc *v1.ReplicationController) (*v1.ReplicationController, error) {\n\t\treturn c.ReplicationControllerInterface.Update(ctx, rc, opts)\n\t}, rs)\n}","line":{"from":214,"to":218}} {"id":100004501,"name":"UpdateStatus","signature":"func (c conversionClient) UpdateStatus(ctx context.Context, rs *apps.ReplicaSet, opts metav1.UpdateOptions) (*apps.ReplicaSet, error)","file":"pkg/controller/replication/conversion.go","code":"func (c conversionClient) UpdateStatus(ctx context.Context, rs *apps.ReplicaSet, opts metav1.UpdateOptions) (*apps.ReplicaSet, error) {\n\treturn convertCall(func(rc *v1.ReplicationController) (*v1.ReplicationController, error) {\n\t\treturn c.ReplicationControllerInterface.UpdateStatus(ctx, rc, opts)\n\t}, rs)\n}","line":{"from":220,"to":224}} {"id":100004502,"name":"Get","signature":"func (c conversionClient) Get(ctx context.Context, name string, options metav1.GetOptions) (*apps.ReplicaSet, error)","file":"pkg/controller/replication/conversion.go","code":"func (c conversionClient) Get(ctx context.Context, name string, options metav1.GetOptions) (*apps.ReplicaSet, error) {\n\trc, err := c.ReplicationControllerInterface.Get(ctx, name, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn convertRCtoRS(rc, nil)\n}","line":{"from":226,"to":232}} {"id":100004503,"name":"List","signature":"func (c conversionClient) List(ctx context.Context, opts metav1.ListOptions) (*apps.ReplicaSetList, error)","file":"pkg/controller/replication/conversion.go","code":"func (c conversionClient) List(ctx context.Context, opts metav1.ListOptions) (*apps.ReplicaSetList, error) {\n\trcList, err := c.ReplicationControllerInterface.List(ctx, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn convertList(rcList)\n}","line":{"from":234,"to":240}} {"id":100004504,"name":"Watch","signature":"func (c conversionClient) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"pkg/controller/replication/conversion.go","code":"func (c conversionClient) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\t// This is not used by RSC because we wrap the shared informer instead.\n\treturn nil, errors.New(\"Watch() is not implemented for conversionClient\")\n}","line":{"from":242,"to":245}} {"id":100004505,"name":"Patch","signature":"func (c conversionClient) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *apps.ReplicaSet, err error)","file":"pkg/controller/replication/conversion.go","code":"func (c conversionClient) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *apps.ReplicaSet, err error) {\n\t// This is not used by RSC.\n\treturn nil, errors.New(\"Patch() is not implemented for conversionClient\")\n}","line":{"from":247,"to":250}} {"id":100004506,"name":"Apply","signature":"func (c conversionClient) Apply(ctx context.Context, rs *appsv1apply.ReplicaSetApplyConfiguration, opts metav1.ApplyOptions) (*apps.ReplicaSet, error)","file":"pkg/controller/replication/conversion.go","code":"func (c conversionClient) Apply(ctx context.Context, rs *appsv1apply.ReplicaSetApplyConfiguration, opts metav1.ApplyOptions) (*apps.ReplicaSet, error) {\n\treturn nil, errors.New(\"Apply() is not implemented for conversionClient\")\n}","line":{"from":252,"to":254}} {"id":100004507,"name":"ApplyStatus","signature":"func (c conversionClient) ApplyStatus(ctx context.Context, rs *appsv1apply.ReplicaSetApplyConfiguration, opts metav1.ApplyOptions) (*apps.ReplicaSet, error)","file":"pkg/controller/replication/conversion.go","code":"func (c conversionClient) ApplyStatus(ctx context.Context, rs *appsv1apply.ReplicaSetApplyConfiguration, opts metav1.ApplyOptions) (*apps.ReplicaSet, error) {\n\treturn nil, errors.New(\"ApplyStatus() is not implemented for conversionClient\")\n}","line":{"from":256,"to":258}} {"id":100004508,"name":"GetScale","signature":"func (c conversionClient) GetScale(ctx context.Context, name string, options metav1.GetOptions) (result *autoscalingv1.Scale, err error)","file":"pkg/controller/replication/conversion.go","code":"func (c conversionClient) GetScale(ctx context.Context, name string, options metav1.GetOptions) (result *autoscalingv1.Scale, err error) {\n\t// This is not used by RSC.\n\treturn nil, errors.New(\"GetScale() is not implemented for conversionClient\")\n}","line":{"from":260,"to":263}} {"id":100004509,"name":"UpdateScale","signature":"func (c conversionClient) UpdateScale(ctx context.Context, name string, scale *autoscalingv1.Scale, opts metav1.UpdateOptions) (result *autoscalingv1.Scale, err error)","file":"pkg/controller/replication/conversion.go","code":"func (c conversionClient) UpdateScale(ctx context.Context, name string, scale *autoscalingv1.Scale, opts metav1.UpdateOptions) (result *autoscalingv1.Scale, err error) {\n\t// This is not used by RSC.\n\treturn nil, errors.New(\"UpdateScale() is not implemented for conversionClient\")\n}","line":{"from":265,"to":268}} {"id":100004510,"name":"ApplyScale","signature":"func (c conversionClient) ApplyScale(ctx context.Context, name string, scale *appsv1autoscaling.ScaleApplyConfiguration, opts metav1.ApplyOptions) (*autoscalingv1.Scale, error)","file":"pkg/controller/replication/conversion.go","code":"func (c conversionClient) ApplyScale(ctx context.Context, name string, scale *appsv1autoscaling.ScaleApplyConfiguration, opts metav1.ApplyOptions) (*autoscalingv1.Scale, error) {\n\treturn nil, errors.New(\"ApplyScale() is not implemented for conversionClient\")\n}","line":{"from":270,"to":272}} {"id":100004511,"name":"convertSlice","signature":"func convertSlice(rcList []*v1.ReplicationController) ([]*apps.ReplicaSet, error)","file":"pkg/controller/replication/conversion.go","code":"func convertSlice(rcList []*v1.ReplicationController) ([]*apps.ReplicaSet, error) {\n\trsList := make([]*apps.ReplicaSet, 0, len(rcList))\n\tfor _, rc := range rcList {\n\t\trs, err := convertRCtoRS(rc, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trsList = append(rsList, rs)\n\t}\n\treturn rsList, nil\n}","line":{"from":274,"to":284}} {"id":100004512,"name":"convertList","signature":"func convertList(rcList *v1.ReplicationControllerList) (*apps.ReplicaSetList, error)","file":"pkg/controller/replication/conversion.go","code":"func convertList(rcList *v1.ReplicationControllerList) (*apps.ReplicaSetList, error) {\n\trsList := \u0026apps.ReplicaSetList{Items: make([]apps.ReplicaSet, len(rcList.Items))}\n\tfor i := range rcList.Items {\n\t\trc := \u0026rcList.Items[i]\n\t\t_, err := convertRCtoRS(rc, \u0026rsList.Items[i])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn rsList, nil\n}","line":{"from":286,"to":296}} {"id":100004513,"name":"convertCall","signature":"func convertCall(fn func(*v1.ReplicationController) (*v1.ReplicationController, error), rs *apps.ReplicaSet) (*apps.ReplicaSet, error)","file":"pkg/controller/replication/conversion.go","code":"func convertCall(fn func(*v1.ReplicationController) (*v1.ReplicationController, error), rs *apps.ReplicaSet) (*apps.ReplicaSet, error) {\n\trc, err := convertRStoRC(rs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult, err := fn(rc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn convertRCtoRS(result, nil)\n}","line":{"from":298,"to":308}} {"id":100004514,"name":"convertRCtoRS","signature":"func convertRCtoRS(rc *v1.ReplicationController, out *apps.ReplicaSet) (*apps.ReplicaSet, error)","file":"pkg/controller/replication/conversion.go","code":"func convertRCtoRS(rc *v1.ReplicationController, out *apps.ReplicaSet) (*apps.ReplicaSet, error) {\n\tvar rsInternal appsinternal.ReplicaSet\n\tif err := apiv1.Convert_v1_ReplicationController_To_apps_ReplicaSet(rc, \u0026rsInternal, nil); err != nil {\n\t\treturn nil, fmt.Errorf(\"can't convert ReplicationController %v/%v to ReplicaSet: %v\", rc.Namespace, rc.Name, err)\n\t}\n\tif out == nil {\n\t\tout = new(apps.ReplicaSet)\n\t}\n\tif err := appsconversion.Convert_apps_ReplicaSet_To_v1_ReplicaSet(\u0026rsInternal, out, nil); err != nil {\n\t\treturn nil, fmt.Errorf(\"can't convert ReplicaSet (converted from ReplicationController %v/%v) from internal to apps/v1: %v\", rc.Namespace, rc.Name, err)\n\t}\n\treturn out, nil\n}","line":{"from":310,"to":322}} {"id":100004515,"name":"convertRStoRC","signature":"func convertRStoRC(rs *apps.ReplicaSet) (*v1.ReplicationController, error)","file":"pkg/controller/replication/conversion.go","code":"func convertRStoRC(rs *apps.ReplicaSet) (*v1.ReplicationController, error) {\n\tvar rsInternal appsinternal.ReplicaSet\n\tif err := appsconversion.Convert_v1_ReplicaSet_To_apps_ReplicaSet(rs, \u0026rsInternal, nil); err != nil {\n\t\treturn nil, fmt.Errorf(\"can't convert ReplicaSet (converting to ReplicationController %v/%v) from apps/v1 to internal: %v\", rs.Namespace, rs.Name, err)\n\t}\n\tvar rc v1.ReplicationController\n\tif err := apiv1.Convert_apps_ReplicaSet_To_v1_ReplicationController(\u0026rsInternal, \u0026rc, nil); err != nil {\n\t\treturn nil, fmt.Errorf(\"can't convert ReplicaSet to ReplicationController %v/%v: %v\", rs.Namespace, rs.Name, err)\n\t}\n\treturn \u0026rc, nil\n}","line":{"from":324,"to":334}} {"id":100004516,"name":"CreatePods","signature":"func (pc podControlAdapter) CreatePods(ctx context.Context, namespace string, template *v1.PodTemplateSpec, object runtime.Object, controllerRef *metav1.OwnerReference) error","file":"pkg/controller/replication/conversion.go","code":"func (pc podControlAdapter) CreatePods(ctx context.Context, namespace string, template *v1.PodTemplateSpec, object runtime.Object, controllerRef *metav1.OwnerReference) error {\n\trc, err := convertRStoRC(object.(*apps.ReplicaSet))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn pc.PodControlInterface.CreatePods(ctx, namespace, template, rc, controllerRef)\n}","line":{"from":340,"to":346}} {"id":100004517,"name":"DeletePod","signature":"func (pc podControlAdapter) DeletePod(ctx context.Context, namespace string, podID string, object runtime.Object) error","file":"pkg/controller/replication/conversion.go","code":"func (pc podControlAdapter) DeletePod(ctx context.Context, namespace string, podID string, object runtime.Object) error {\n\trc, err := convertRStoRC(object.(*apps.ReplicaSet))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn pc.PodControlInterface.DeletePod(ctx, namespace, podID, rc)\n}","line":{"from":348,"to":354}} {"id":100004518,"name":"NewReplicationManager","signature":"func NewReplicationManager(podInformer coreinformers.PodInformer, rcInformer coreinformers.ReplicationControllerInformer, kubeClient clientset.Interface, burstReplicas int) *ReplicationManager","file":"pkg/controller/replication/replication_controller.go","code":"// NewReplicationManager configures a replication manager with the specified event recorder\nfunc NewReplicationManager(podInformer coreinformers.PodInformer, rcInformer coreinformers.ReplicationControllerInformer, kubeClient clientset.Interface, burstReplicas int) *ReplicationManager {\n\teventBroadcaster := record.NewBroadcaster()\n\treturn \u0026ReplicationManager{\n\t\t*replicaset.NewBaseController(informerAdapter{rcInformer}, podInformer, clientsetAdapter{kubeClient}, burstReplicas,\n\t\t\tv1.SchemeGroupVersion.WithKind(\"ReplicationController\"),\n\t\t\t\"replication_controller\",\n\t\t\t\"replicationmanager\",\n\t\t\tpodControlAdapter{controller.RealPodControl{\n\t\t\t\tKubeClient: kubeClient,\n\t\t\t\tRecorder: eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"replication-controller\"}),\n\t\t\t}},\n\t\t\teventBroadcaster,\n\t\t),\n\t}\n}","line":{"from":49,"to":64}} {"id":100004519,"name":"NewReplicationControllerCondition","signature":"func NewReplicationControllerCondition(condType v1.ReplicationControllerConditionType, status v1.ConditionStatus, reason, msg string) v1.ReplicationControllerCondition","file":"pkg/controller/replication/replication_controller_utils.go","code":"// NewReplicationControllerCondition creates a new replication controller condition.\nfunc NewReplicationControllerCondition(condType v1.ReplicationControllerConditionType, status v1.ConditionStatus, reason, msg string) v1.ReplicationControllerCondition {\n\treturn v1.ReplicationControllerCondition{\n\t\tType: condType,\n\t\tStatus: status,\n\t\tLastTransitionTime: metav1.Now(),\n\t\tReason: reason,\n\t\tMessage: msg,\n\t}\n}","line":{"from":26,"to":35}} {"id":100004520,"name":"GetCondition","signature":"func GetCondition(status v1.ReplicationControllerStatus, condType v1.ReplicationControllerConditionType) *v1.ReplicationControllerCondition","file":"pkg/controller/replication/replication_controller_utils.go","code":"// GetCondition returns a replication controller condition with the provided type if it exists.\nfunc GetCondition(status v1.ReplicationControllerStatus, condType v1.ReplicationControllerConditionType) *v1.ReplicationControllerCondition {\n\tfor i := range status.Conditions {\n\t\tc := status.Conditions[i]\n\t\tif c.Type == condType {\n\t\t\treturn \u0026c\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":37,"to":46}} {"id":100004521,"name":"SetCondition","signature":"func SetCondition(status *v1.ReplicationControllerStatus, condition v1.ReplicationControllerCondition)","file":"pkg/controller/replication/replication_controller_utils.go","code":"// SetCondition adds/replaces the given condition in the replication controller status.\nfunc SetCondition(status *v1.ReplicationControllerStatus, condition v1.ReplicationControllerCondition) {\n\tcurrentCond := GetCondition(*status, condition.Type)\n\tif currentCond != nil \u0026\u0026 currentCond.Status == condition.Status \u0026\u0026 currentCond.Reason == condition.Reason {\n\t\treturn\n\t}\n\tnewConditions := filterOutCondition(status.Conditions, condition.Type)\n\tstatus.Conditions = append(newConditions, condition)\n}","line":{"from":48,"to":56}} {"id":100004522,"name":"RemoveCondition","signature":"func RemoveCondition(status *v1.ReplicationControllerStatus, condType v1.ReplicationControllerConditionType)","file":"pkg/controller/replication/replication_controller_utils.go","code":"// RemoveCondition removes the condition with the provided type from the replication controller status.\nfunc RemoveCondition(status *v1.ReplicationControllerStatus, condType v1.ReplicationControllerConditionType) {\n\tstatus.Conditions = filterOutCondition(status.Conditions, condType)\n}","line":{"from":58,"to":61}} {"id":100004523,"name":"filterOutCondition","signature":"func filterOutCondition(conditions []v1.ReplicationControllerCondition, condType v1.ReplicationControllerConditionType) []v1.ReplicationControllerCondition","file":"pkg/controller/replication/replication_controller_utils.go","code":"// filterOutCondition returns a new slice of replication controller conditions without conditions with the provided type.\nfunc filterOutCondition(conditions []v1.ReplicationControllerCondition, condType v1.ReplicationControllerConditionType) []v1.ReplicationControllerCondition {\n\tvar newConditions []v1.ReplicationControllerCondition\n\tfor _, c := range conditions {\n\t\tif c.Type == condType {\n\t\t\tcontinue\n\t\t}\n\t\tnewConditions = append(newConditions, c)\n\t}\n\treturn newConditions\n}","line":{"from":63,"to":73}} {"id":100004524,"name":"NewController","signature":"func NewController(","file":"pkg/controller/resourceclaim/controller.go","code":"// NewController creates a ResourceClaim controller.\nfunc NewController(\n\tkubeClient clientset.Interface,\n\tpodInformer v1informers.PodInformer,\n\tclaimInformer resourcev1alpha2informers.ResourceClaimInformer,\n\ttemplateInformer resourcev1alpha2informers.ResourceClaimTemplateInformer) (*Controller, error) {\n\n\tec := \u0026Controller{\n\t\tkubeClient: kubeClient,\n\t\tpodLister: podInformer.Lister(),\n\t\tpodIndexer: podInformer.Informer().GetIndexer(),\n\t\tpodSynced: podInformer.Informer().HasSynced,\n\t\tclaimLister: claimInformer.Lister(),\n\t\tclaimsSynced: claimInformer.Informer().HasSynced,\n\t\ttemplateLister: templateInformer.Lister(),\n\t\ttemplatesSynced: templateInformer.Informer().HasSynced,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"resource_claim\"),\n\t\tdeletedObjects: newUIDCache(maxUIDCacheEntries),\n\t}\n\n\tmetrics.RegisterMetrics()\n\n\tif _, err := podInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tec.enqueuePod(obj, false)\n\t\t},\n\t\tUpdateFunc: func(old, updated interface{}) {\n\t\t\tec.enqueuePod(updated, false)\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tec.enqueuePod(obj, true)\n\t\t},\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\tif _, err := claimInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: ec.onResourceClaimAddOrUpdate,\n\t\tUpdateFunc: func(old, updated interface{}) {\n\t\t\tec.onResourceClaimAddOrUpdate(updated)\n\t\t},\n\t\tDeleteFunc: ec.onResourceClaimDelete,\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := ec.podIndexer.AddIndexers(cache.Indexers{podResourceClaimIndex: podResourceClaimIndexFunc}); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not initialize ResourceClaim controller: %w\", err)\n\t}\n\n\treturn ec, nil\n}","line":{"from":99,"to":148}} {"id":100004525,"name":"enqueuePod","signature":"func (ec *Controller) enqueuePod(obj interface{}, deleted bool)","file":"pkg/controller/resourceclaim/controller.go","code":"func (ec *Controller) enqueuePod(obj interface{}, deleted bool) {\n\tif d, ok := obj.(cache.DeletedFinalStateUnknown); ok {\n\t\tobj = d.Obj\n\t}\n\tpod, ok := obj.(*v1.Pod)\n\tif !ok {\n\t\t// Not a pod?!\n\t\treturn\n\t}\n\n\tif deleted {\n\t\tec.deletedObjects.Add(pod.UID)\n\t}\n\n\tif len(pod.Spec.ResourceClaims) == 0 {\n\t\t// Nothing to do for it at all.\n\t\treturn\n\t}\n\n\t// Release reservations of a deleted or completed pod?\n\tif deleted ||\n\t\tpodutil.IsPodTerminal(pod) ||\n\t\t// Deleted and not scheduled:\n\t\tpod.DeletionTimestamp != nil \u0026\u0026 pod.Spec.NodeName == \"\" {\n\t\tfor _, podClaim := range pod.Spec.ResourceClaims {\n\t\t\tclaimName := resourceclaim.Name(pod, \u0026podClaim)\n\t\t\tec.queue.Add(claimKeyPrefix + pod.Namespace + \"/\" + claimName)\n\t\t}\n\t}\n\n\t// Create ResourceClaim for inline templates?\n\tif pod.DeletionTimestamp == nil {\n\t\tfor _, podClaim := range pod.Spec.ResourceClaims {\n\t\t\tif podClaim.Source.ResourceClaimTemplateName != nil {\n\t\t\t\t// It has at least one inline template, work on it.\n\t\t\t\tec.queue.Add(podKeyPrefix + pod.Namespace + \"/\" + pod.Name)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":150,"to":190}} {"id":100004526,"name":"onResourceClaimAddOrUpdate","signature":"func (ec *Controller) onResourceClaimAddOrUpdate(obj interface{})","file":"pkg/controller/resourceclaim/controller.go","code":"func (ec *Controller) onResourceClaimAddOrUpdate(obj interface{}) {\n\tclaim, ok := obj.(*resourcev1alpha2.ResourceClaim)\n\tif !ok {\n\t\treturn\n\t}\n\n\t// When starting up, we have to check all claims to find those with\n\t// stale pods in ReservedFor. During an update, a pod might get added\n\t// that already no longer exists.\n\tec.queue.Add(claimKeyPrefix + claim.Namespace + \"/\" + claim.Name)\n}","line":{"from":192,"to":202}} {"id":100004527,"name":"onResourceClaimDelete","signature":"func (ec *Controller) onResourceClaimDelete(obj interface{})","file":"pkg/controller/resourceclaim/controller.go","code":"func (ec *Controller) onResourceClaimDelete(obj interface{}) {\n\tclaim, ok := obj.(*resourcev1alpha2.ResourceClaim)\n\tif !ok {\n\t\treturn\n\t}\n\n\t// Someone deleted a ResourceClaim, either intentionally or\n\t// accidentally. If there is a pod referencing it because of\n\t// an inline resource, then we should re-create the ResourceClaim.\n\t// The common indexer does some prefiltering for us by\n\t// limiting the list to those pods which reference\n\t// the ResourceClaim.\n\tobjs, err := ec.podIndexer.ByIndex(podResourceClaimIndex, fmt.Sprintf(\"%s/%s\", claim.Namespace, claim.Name))\n\tif err != nil {\n\t\truntime.HandleError(fmt.Errorf(\"listing pods from cache: %v\", err))\n\t\treturn\n\t}\n\tfor _, obj := range objs {\n\t\tec.enqueuePod(obj, false)\n\t}\n}","line":{"from":204,"to":224}} {"id":100004528,"name":"Run","signature":"func (ec *Controller) Run(ctx context.Context, workers int)","file":"pkg/controller/resourceclaim/controller.go","code":"func (ec *Controller) Run(ctx context.Context, workers int) {\n\tdefer runtime.HandleCrash()\n\tdefer ec.queue.ShutDown()\n\n\tlogger := klog.FromContext(ctx)\n\tlogger.Info(\"Starting ephemeral volume controller\")\n\tdefer logger.Info(\"Shutting down ephemeral volume controller\")\n\n\teventBroadcaster := record.NewBroadcaster()\n\teventBroadcaster.StartLogging(klog.Infof)\n\teventBroadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: ec.kubeClient.CoreV1().Events(\"\")})\n\tec.recorder = eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"resource_claim\"})\n\tdefer eventBroadcaster.Shutdown()\n\n\tif !cache.WaitForNamedCacheSync(\"ephemeral\", ctx.Done(), ec.podSynced, ec.claimsSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.UntilWithContext(ctx, ec.runWorker, time.Second)\n\t}\n\n\t\u003c-ctx.Done()\n}","line":{"from":226,"to":249}} {"id":100004529,"name":"runWorker","signature":"func (ec *Controller) runWorker(ctx context.Context)","file":"pkg/controller/resourceclaim/controller.go","code":"func (ec *Controller) runWorker(ctx context.Context) {\n\tfor ec.processNextWorkItem(ctx) {\n\t}\n}","line":{"from":251,"to":254}} {"id":100004530,"name":"processNextWorkItem","signature":"func (ec *Controller) processNextWorkItem(ctx context.Context) bool","file":"pkg/controller/resourceclaim/controller.go","code":"func (ec *Controller) processNextWorkItem(ctx context.Context) bool {\n\tkey, shutdown := ec.queue.Get()\n\tif shutdown {\n\t\treturn false\n\t}\n\tdefer ec.queue.Done(key)\n\n\terr := ec.syncHandler(ctx, key.(string))\n\tif err == nil {\n\t\tec.queue.Forget(key)\n\t\treturn true\n\t}\n\n\truntime.HandleError(fmt.Errorf(\"%v failed with: %v\", key, err))\n\tec.queue.AddRateLimited(key)\n\n\treturn true\n}","line":{"from":256,"to":273}} {"id":100004531,"name":"syncHandler","signature":"func (ec *Controller) syncHandler(ctx context.Context, key string) error","file":"pkg/controller/resourceclaim/controller.go","code":"// syncHandler is invoked for each work item which might need to be processed.\n// If an error is returned from this function, the item will be requeued.\nfunc (ec *Controller) syncHandler(ctx context.Context, key string) error {\n\tsep := strings.Index(key, \":\")\n\tif sep \u003c 0 {\n\t\treturn fmt.Errorf(\"unexpected key: %s\", key)\n\t}\n\tprefix, object := key[0:sep+1], key[sep+1:]\n\tnamespace, name, err := cache.SplitMetaNamespaceKey(object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch prefix {\n\tcase podKeyPrefix:\n\t\treturn ec.syncPod(ctx, namespace, name)\n\tcase claimKeyPrefix:\n\t\treturn ec.syncClaim(ctx, namespace, name)\n\tdefault:\n\t\treturn fmt.Errorf(\"unexpected key prefix: %s\", prefix)\n\t}\n\n}","line":{"from":275,"to":297}} {"id":100004532,"name":"syncPod","signature":"func (ec *Controller) syncPod(ctx context.Context, namespace, name string) error","file":"pkg/controller/resourceclaim/controller.go","code":"func (ec *Controller) syncPod(ctx context.Context, namespace, name string) error {\n\tlogger := klog.LoggerWithValues(klog.FromContext(ctx), \"pod\", klog.KRef(namespace, name))\n\tctx = klog.NewContext(ctx, logger)\n\tpod, err := ec.podLister.Pods(namespace).Get(name)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\tlogger.V(5).Info(\"nothing to do for pod, it is gone\")\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\t// Ignore pods which are already getting deleted.\n\tif pod.DeletionTimestamp != nil {\n\t\tlogger.V(5).Info(\"nothing to do for pod, it is marked for deletion\")\n\t\treturn nil\n\t}\n\n\tfor _, podClaim := range pod.Spec.ResourceClaims {\n\t\tif err := ec.handleClaim(ctx, pod, podClaim); err != nil {\n\t\t\tif ec.recorder != nil {\n\t\t\t\tec.recorder.Event(pod, v1.EventTypeWarning, \"FailedResourceClaimCreation\", fmt.Sprintf(\"PodResourceClaim %s: %v\", podClaim.Name, err))\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"pod %s/%s, PodResourceClaim %s: %v\", namespace, name, podClaim.Name, err)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":299,"to":327}} {"id":100004533,"name":"handleClaim","signature":"func (ec *Controller) handleClaim(ctx context.Context, pod *v1.Pod, podClaim v1.PodResourceClaim) error","file":"pkg/controller/resourceclaim/controller.go","code":"// handleResourceClaim is invoked for each volume of a pod.\nfunc (ec *Controller) handleClaim(ctx context.Context, pod *v1.Pod, podClaim v1.PodResourceClaim) error {\n\tlogger := klog.LoggerWithValues(klog.FromContext(ctx), \"podClaim\", podClaim.Name)\n\tctx = klog.NewContext(ctx, logger)\n\tlogger.V(5).Info(\"checking\", \"podClaim\", podClaim.Name)\n\ttemplateName := podClaim.Source.ResourceClaimTemplateName\n\tif templateName == nil {\n\t\treturn nil\n\t}\n\n\tclaimName := resourceclaim.Name(pod, \u0026podClaim)\n\tclaim, err := ec.claimLister.ResourceClaims(pod.Namespace).Get(claimName)\n\tif err != nil \u0026\u0026 !errors.IsNotFound(err) {\n\t\treturn err\n\t}\n\tif claim != nil {\n\t\tif err := resourceclaim.IsForPod(pod, claim); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Already created, nothing more to do.\n\t\tlogger.V(5).Info(\"claim already created\", \"podClaim\", podClaim.Name, \"resourceClaim\", claimName)\n\t\treturn nil\n\t}\n\n\ttemplate, err := ec.templateLister.ResourceClaimTemplates(pod.Namespace).Get(*templateName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"resource claim template %q: %v\", *templateName, err)\n\t}\n\n\t// Create the ResourceClaim with pod as owner.\n\tisTrue := true\n\tclaim = \u0026resourcev1alpha2.ResourceClaim{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: claimName,\n\t\t\tOwnerReferences: []metav1.OwnerReference{\n\t\t\t\t{\n\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t\tKind: \"Pod\",\n\t\t\t\t\tName: pod.Name,\n\t\t\t\t\tUID: pod.UID,\n\t\t\t\t\tController: \u0026isTrue,\n\t\t\t\t\tBlockOwnerDeletion: \u0026isTrue,\n\t\t\t\t},\n\t\t\t},\n\t\t\tAnnotations: template.Spec.ObjectMeta.Annotations,\n\t\t\tLabels: template.Spec.ObjectMeta.Labels,\n\t\t},\n\t\tSpec: template.Spec.Spec,\n\t}\n\tmetrics.ResourceClaimCreateAttempts.Inc()\n\t_, err = ec.kubeClient.ResourceV1alpha2().ResourceClaims(pod.Namespace).Create(ctx, claim, metav1.CreateOptions{})\n\tif err != nil {\n\t\tmetrics.ResourceClaimCreateFailures.Inc()\n\t\treturn fmt.Errorf(\"create ResourceClaim %s: %v\", claimName, err)\n\t}\n\treturn nil\n}","line":{"from":329,"to":385}} {"id":100004534,"name":"syncClaim","signature":"func (ec *Controller) syncClaim(ctx context.Context, namespace, name string) error","file":"pkg/controller/resourceclaim/controller.go","code":"func (ec *Controller) syncClaim(ctx context.Context, namespace, name string) error {\n\tlogger := klog.LoggerWithValues(klog.FromContext(ctx), \"PVC\", klog.KRef(namespace, name))\n\tctx = klog.NewContext(ctx, logger)\n\tclaim, err := ec.claimLister.ResourceClaims(namespace).Get(name)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\tlogger.V(5).Info(\"nothing to do for claim, it is gone\")\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\t// Check if the ReservedFor entries are all still valid.\n\tvalid := make([]resourcev1alpha2.ResourceClaimConsumerReference, 0, len(claim.Status.ReservedFor))\n\tfor _, reservedFor := range claim.Status.ReservedFor {\n\t\tif reservedFor.APIGroup == \"\" \u0026\u0026\n\t\t\treservedFor.Resource == \"pods\" {\n\t\t\t// A pod falls into one of three categories:\n\t\t\t// - we have it in our cache -\u003e don't remove it until we are told that it got removed\n\t\t\t// - we don't have it in our cache anymore, but we have seen it before -\u003e it was deleted, remove it\n\t\t\t// - not in our cache, not seen -\u003e double-check with API server before removal\n\n\t\t\tkeepEntry := true\n\n\t\t\t// Tracking deleted pods in the LRU cache is an\n\t\t\t// optimization. Without this cache, the code would\n\t\t\t// have to do the API call below for every deleted pod\n\t\t\t// to ensure that the pod really doesn't exist. With\n\t\t\t// the cache, most of the time the pod will be recorded\n\t\t\t// as deleted and the API call can be avoided.\n\t\t\tif ec.deletedObjects.Has(reservedFor.UID) {\n\t\t\t\t// We know that the pod was deleted. This is\n\t\t\t\t// easy to check and thus is done first.\n\t\t\t\tkeepEntry = false\n\t\t\t} else {\n\t\t\t\tpod, err := ec.podLister.Pods(claim.Namespace).Get(reservedFor.Name)\n\t\t\t\tif err != nil \u0026\u0026 !errors.IsNotFound(err) {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif pod == nil {\n\t\t\t\t\t// We might not have it in our informer cache\n\t\t\t\t\t// yet. Removing the pod while the scheduler is\n\t\t\t\t\t// scheduling it would be bad. We have to be\n\t\t\t\t\t// absolutely sure and thus have to check with\n\t\t\t\t\t// the API server.\n\t\t\t\t\tpod, err := ec.kubeClient.CoreV1().Pods(claim.Namespace).Get(ctx, reservedFor.Name, metav1.GetOptions{})\n\t\t\t\t\tif err != nil \u0026\u0026 !errors.IsNotFound(err) {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tif pod == nil || pod.UID != reservedFor.UID {\n\t\t\t\t\t\tkeepEntry = false\n\t\t\t\t\t}\n\t\t\t\t} else if pod.UID != reservedFor.UID {\n\t\t\t\t\t// Pod exists, but is a different incarnation under the same name.\n\t\t\t\t\tkeepEntry = false\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif keepEntry {\n\t\t\t\tvalid = append(valid, reservedFor)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// TODO: support generic object lookup\n\t\treturn fmt.Errorf(\"unsupported ReservedFor entry: %v\", reservedFor)\n\t}\n\n\tif len(valid) \u003c len(claim.Status.ReservedFor) {\n\t\t// TODO (#113700): patch\n\t\tclaim := claim.DeepCopy()\n\t\tclaim.Status.ReservedFor = valid\n\t\t_, err := ec.kubeClient.ResourceV1alpha2().ResourceClaims(claim.Namespace).UpdateStatus(ctx, claim, metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":387,"to":466}} {"id":100004535,"name":"podResourceClaimIndexFunc","signature":"func podResourceClaimIndexFunc(obj interface{}) ([]string, error)","file":"pkg/controller/resourceclaim/controller.go","code":"// podResourceClaimIndexFunc is an index function that returns ResourceClaim keys (=\n// namespace/name) for ResourceClaimTemplates in a given pod.\nfunc podResourceClaimIndexFunc(obj interface{}) ([]string, error) {\n\tpod, ok := obj.(*v1.Pod)\n\tif !ok {\n\t\treturn []string{}, nil\n\t}\n\tkeys := []string{}\n\tfor _, podClaim := range pod.Spec.ResourceClaims {\n\t\tif podClaim.Source.ResourceClaimTemplateName != nil {\n\t\t\tclaimName := resourceclaim.Name(pod, \u0026podClaim)\n\t\t\tkeys = append(keys, fmt.Sprintf(\"%s/%s\", pod.Namespace, claimName))\n\t\t}\n\t}\n\treturn keys, nil\n}","line":{"from":468,"to":483}} {"id":100004536,"name":"RegisterMetrics","signature":"func RegisterMetrics()","file":"pkg/controller/resourceclaim/metrics/metrics.go","code":"// RegisterMetrics registers ResourceClaim metrics.\nfunc RegisterMetrics() {\n\tregisterMetrics.Do(func() {\n\t\tlegacyregistry.MustRegister(ResourceClaimCreateAttempts)\n\t\tlegacyregistry.MustRegister(ResourceClaimCreateFailures)\n\t})\n}","line":{"from":52,"to":58}} {"id":100004537,"name":"newUIDCache","signature":"func newUIDCache(maxCacheEntries int) *uidCache","file":"pkg/controller/resourceclaim/uid_cache.go","code":"// newUIDCache returns a uidCache.\nfunc newUIDCache(maxCacheEntries int) *uidCache {\n\treturn \u0026uidCache{\n\t\tcache: lru.New(maxCacheEntries),\n\t}\n}","line":{"from":33,"to":38}} {"id":100004538,"name":"Add","signature":"func (c *uidCache) Add(uid types.UID)","file":"pkg/controller/resourceclaim/uid_cache.go","code":"// Add adds a uid to the cache.\nfunc (c *uidCache) Add(uid types.UID) {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tc.cache.Add(uid, nil)\n}","line":{"from":40,"to":45}} {"id":100004539,"name":"Has","signature":"func (c *uidCache) Has(uid types.UID) bool","file":"pkg/controller/resourceclaim/uid_cache.go","code":"// Has returns if a uid is in the cache.\nfunc (c *uidCache) Has(uid types.UID) bool {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\t_, found := c.cache.Get(uid)\n\treturn found\n}","line":{"from":47,"to":53}} {"id":100004540,"name":"Convert_v1alpha1_ResourceQuotaControllerConfiguration_To_config_ResourceQuotaControllerConfiguration","signature":"func Convert_v1alpha1_ResourceQuotaControllerConfiguration_To_config_ResourceQuotaControllerConfiguration(in *v1alpha1.ResourceQuotaControllerConfiguration, out *config.ResourceQuotaControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/resourcequota/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_ResourceQuotaControllerConfiguration_To_config_ResourceQuotaControllerConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_ResourceQuotaControllerConfiguration_To_config_ResourceQuotaControllerConfiguration(in *v1alpha1.ResourceQuotaControllerConfiguration, out *config.ResourceQuotaControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_ResourceQuotaControllerConfiguration_To_config_ResourceQuotaControllerConfiguration(in, out, s)\n}","line":{"from":32,"to":35}} {"id":100004541,"name":"Convert_config_ResourceQuotaControllerConfiguration_To_v1alpha1_ResourceQuotaControllerConfiguration","signature":"func Convert_config_ResourceQuotaControllerConfiguration_To_v1alpha1_ResourceQuotaControllerConfiguration(in *config.ResourceQuotaControllerConfiguration, out *v1alpha1.ResourceQuotaControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/resourcequota/config/v1alpha1/conversion.go","code":"// Convert_config_ResourceQuotaControllerConfiguration_To_v1alpha1_ResourceQuotaControllerConfiguration is an autogenerated conversion function.\nfunc Convert_config_ResourceQuotaControllerConfiguration_To_v1alpha1_ResourceQuotaControllerConfiguration(in *config.ResourceQuotaControllerConfiguration, out *v1alpha1.ResourceQuotaControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_ResourceQuotaControllerConfiguration_To_v1alpha1_ResourceQuotaControllerConfiguration(in, out, s)\n}","line":{"from":37,"to":40}} {"id":100004542,"name":"RecommendedDefaultResourceQuotaControllerConfiguration","signature":"func RecommendedDefaultResourceQuotaControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.ResourceQuotaControllerConfiguration)","file":"pkg/controller/resourcequota/config/v1alpha1/defaults.go","code":"// RecommendedDefaultResourceQuotaControllerConfiguration defaults a pointer to a\n// ResourceQuotaControllerConfiguration struct. This will set the recommended default\n// values, but they may be subject to change between API versions. This function\n// is intentionally not registered in the scheme as a \"normal\" `SetDefaults_Foo`\n// function to allow consumers of this type to set whatever defaults for their\n// embedded configs. Forcing consumers to use these defaults would be problematic\n// as defaulting in the scheme is done as part of the conversion, and there would\n// be no easy way to opt-out. Instead, if you want to use this defaulting method\n// run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDefaultResourceQuotaControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.ResourceQuotaControllerConfiguration) {\n\tzero := metav1.Duration{}\n\tif obj.ConcurrentResourceQuotaSyncs == 0 {\n\t\tobj.ConcurrentResourceQuotaSyncs = 5\n\t}\n\tif obj.ResourceQuotaSyncPeriod == zero {\n\t\tobj.ResourceQuotaSyncPeriod = metav1.Duration{Duration: 5 * time.Minute}\n\t}\n}","line":{"from":26,"to":43}} {"id":100004543,"name":"NewController","signature":"func NewController(ctx context.Context, options *ControllerOptions) (*Controller, error)","file":"pkg/controller/resourcequota/resource_quota_controller.go","code":"// NewController creates a quota controller with specified options\nfunc NewController(ctx context.Context, options *ControllerOptions) (*Controller, error) {\n\t// build the resource quota controller\n\trq := \u0026Controller{\n\t\trqClient: options.QuotaClient,\n\t\trqLister: options.ResourceQuotaInformer.Lister(),\n\t\tinformerSyncedFuncs: []cache.InformerSynced{options.ResourceQuotaInformer.Informer().HasSynced},\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"resourcequota_primary\"),\n\t\tmissingUsageQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"resourcequota_priority\"),\n\t\tresyncPeriod: options.ResyncPeriod,\n\t\tregistry: options.Registry,\n\t}\n\t// set the synchronization handler\n\trq.syncHandler = rq.syncResourceQuotaFromKey\n\n\tlogger := klog.FromContext(ctx)\n\n\toptions.ResourceQuotaInformer.Informer().AddEventHandlerWithResyncPeriod(\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: func(obj interface{}) {\n\t\t\t\trq.addQuota(logger, obj)\n\t\t\t},\n\t\t\tUpdateFunc: func(old, cur interface{}) {\n\t\t\t\t// We are only interested in observing updates to quota.spec to drive updates to quota.status.\n\t\t\t\t// We ignore all updates to quota.Status because they are all driven by this controller.\n\t\t\t\t// IMPORTANT:\n\t\t\t\t// We do not use this function to queue up a full quota recalculation. To do so, would require\n\t\t\t\t// us to enqueue all quota.Status updates, and since quota.Status updates involve additional queries\n\t\t\t\t// that cannot be backed by a cache and result in a full query of a namespace's content, we do not\n\t\t\t\t// want to pay the price on spurious status updates. As a result, we have a separate routine that is\n\t\t\t\t// responsible for enqueue of all resource quotas when doing a full resync (enqueueAll)\n\t\t\t\toldResourceQuota := old.(*v1.ResourceQuota)\n\t\t\t\tcurResourceQuota := cur.(*v1.ResourceQuota)\n\t\t\t\tif quota.Equals(oldResourceQuota.Spec.Hard, curResourceQuota.Spec.Hard) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\trq.addQuota(logger, curResourceQuota)\n\t\t\t},\n\t\t\t// This will enter the sync loop and no-op, because the controller has been deleted from the store.\n\t\t\t// Note that deleting a controller immediately after scaling it to 0 will not work. The recommended\n\t\t\t// way of achieving this is by performing a `stop` operation on the controller.\n\t\t\tDeleteFunc: func(obj interface{}) {\n\t\t\t\trq.enqueueResourceQuota(logger, obj)\n\t\t\t},\n\t\t},\n\t\trq.resyncPeriod(),\n\t)\n\n\tif options.DiscoveryFunc != nil {\n\t\tqm := \u0026QuotaMonitor{\n\t\t\tinformersStarted: options.InformersStarted,\n\t\t\tinformerFactory: options.InformerFactory,\n\t\t\tignoredResources: options.IgnoredResourcesFunc(),\n\t\t\tresourceChanges: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"resource_quota_controller_resource_changes\"),\n\t\t\tresyncPeriod: options.ReplenishmentResyncPeriod,\n\t\t\treplenishmentFunc: rq.replenishQuota,\n\t\t\tregistry: rq.registry,\n\t\t\tupdateFilter: options.UpdateFilter,\n\t\t}\n\n\t\trq.quotaMonitor = qm\n\n\t\t// do initial quota monitor setup. If we have a discovery failure here, it's ok. We'll discover more resources when a later sync happens.\n\t\tresources, err := GetQuotableResources(options.DiscoveryFunc)\n\t\tif discovery.IsGroupDiscoveryFailedError(err) {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"initial discovery check failure, continuing and counting on future sync update: %v\", err))\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err = qm.SyncMonitors(ctx, resources); err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"initial monitor sync has error: %v\", err))\n\t\t}\n\n\t\t// only start quota once all informers synced\n\t\trq.informerSyncedFuncs = append(rq.informerSyncedFuncs, func() bool {\n\t\t\treturn qm.IsSynced(ctx)\n\t\t})\n\t}\n\n\treturn rq, nil\n}","line":{"from":105,"to":186}} {"id":100004544,"name":"enqueueAll","signature":"func (rq *Controller) enqueueAll(ctx context.Context)","file":"pkg/controller/resourcequota/resource_quota_controller.go","code":"// enqueueAll is called at the fullResyncPeriod interval to force a full recalculation of quota usage statistics\nfunc (rq *Controller) enqueueAll(ctx context.Context) {\n\tlogger := klog.FromContext(ctx)\n\tdefer logger.V(4).Info(\"Resource quota controller queued all resource quota for full calculation of usage\")\n\trqs, err := rq.rqLister.List(labels.Everything())\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unable to enqueue all - error listing resource quotas: %v\", err))\n\t\treturn\n\t}\n\tfor i := range rqs {\n\t\tkey, err := controller.KeyFunc(rqs[i])\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get key for object %+v: %v\", rqs[i], err))\n\t\t\tcontinue\n\t\t}\n\t\trq.queue.Add(key)\n\t}\n}","line":{"from":188,"to":205}} {"id":100004545,"name":"enqueueResourceQuota","signature":"func (rq *Controller) enqueueResourceQuota(logger klog.Logger, obj interface{})","file":"pkg/controller/resourcequota/resource_quota_controller.go","code":"// obj could be an *v1.ResourceQuota, or a DeletionFinalStateUnknown marker item.\nfunc (rq *Controller) enqueueResourceQuota(logger klog.Logger, obj interface{}) {\n\tkey, err := controller.KeyFunc(obj)\n\tif err != nil {\n\t\tlogger.Error(err, \"Couldn't get key\", \"object\", obj)\n\t\treturn\n\t}\n\trq.queue.Add(key)\n}","line":{"from":207,"to":215}} {"id":100004546,"name":"addQuota","signature":"func (rq *Controller) addQuota(logger klog.Logger, obj interface{})","file":"pkg/controller/resourcequota/resource_quota_controller.go","code":"func (rq *Controller) addQuota(logger klog.Logger, obj interface{}) {\n\tkey, err := controller.KeyFunc(obj)\n\tif err != nil {\n\t\tlogger.Error(err, \"Couldn't get key\", \"object\", obj)\n\t\treturn\n\t}\n\n\tresourceQuota := obj.(*v1.ResourceQuota)\n\n\t// if we declared an intent that is not yet captured in status (prioritize it)\n\tif !apiequality.Semantic.DeepEqual(resourceQuota.Spec.Hard, resourceQuota.Status.Hard) {\n\t\trq.missingUsageQueue.Add(key)\n\t\treturn\n\t}\n\n\t// if we declared a constraint that has no usage (which this controller can calculate, prioritize it)\n\tfor constraint := range resourceQuota.Status.Hard {\n\t\tif _, usageFound := resourceQuota.Status.Used[constraint]; !usageFound {\n\t\t\tmatchedResources := []v1.ResourceName{constraint}\n\t\t\tfor _, evaluator := range rq.registry.List() {\n\t\t\t\tif intersection := evaluator.MatchingResources(matchedResources); len(intersection) \u003e 0 {\n\t\t\t\t\trq.missingUsageQueue.Add(key)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// no special priority, go in normal recalc queue\n\trq.queue.Add(key)\n}","line":{"from":217,"to":247}} {"id":100004547,"name":"worker","signature":"func (rq *Controller) worker(queue workqueue.RateLimitingInterface) func(context.Context)","file":"pkg/controller/resourcequota/resource_quota_controller.go","code":"// worker runs a worker thread that just dequeues items, processes them, and marks them done.\nfunc (rq *Controller) worker(queue workqueue.RateLimitingInterface) func(context.Context) {\n\tworkFunc := func(ctx context.Context) bool {\n\t\tkey, quit := queue.Get()\n\t\tif quit {\n\t\t\treturn true\n\t\t}\n\t\tdefer queue.Done(key)\n\n\t\trq.workerLock.RLock()\n\t\tdefer rq.workerLock.RUnlock()\n\n\t\tlogger := klog.FromContext(ctx)\n\t\tlogger = klog.LoggerWithValues(logger, \"queueKey\", key)\n\t\tctx = klog.NewContext(ctx, logger)\n\n\t\terr := rq.syncHandler(ctx, key.(string))\n\t\tif err == nil {\n\t\t\tqueue.Forget(key)\n\t\t\treturn false\n\t\t}\n\n\t\tutilruntime.HandleError(err)\n\t\tqueue.AddRateLimited(key)\n\n\t\treturn false\n\t}\n\n\treturn func(ctx context.Context) {\n\t\tfor {\n\t\t\tif quit := workFunc(ctx); quit {\n\t\t\t\tklog.FromContext(ctx).Info(\"resource quota controller worker shutting down\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":249,"to":285}} {"id":100004548,"name":"Run","signature":"func (rq *Controller) Run(ctx context.Context, workers int)","file":"pkg/controller/resourcequota/resource_quota_controller.go","code":"// Run begins quota controller using the specified number of workers\nfunc (rq *Controller) Run(ctx context.Context, workers int) {\n\tdefer utilruntime.HandleCrash()\n\tdefer rq.queue.ShutDown()\n\tdefer rq.missingUsageQueue.ShutDown()\n\n\tlogger := klog.FromContext(ctx)\n\n\tlogger.Info(\"Starting resource quota controller\")\n\tdefer logger.Info(\"Shutting down resource quota controller\")\n\n\tif rq.quotaMonitor != nil {\n\t\tgo rq.quotaMonitor.Run(ctx)\n\t}\n\n\tif !cache.WaitForNamedCacheSync(\"resource quota\", ctx.Done(), rq.informerSyncedFuncs...) {\n\t\treturn\n\t}\n\n\t// the workers that chug through the quota calculation backlog\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.UntilWithContext(ctx, rq.worker(rq.queue), time.Second)\n\t\tgo wait.UntilWithContext(ctx, rq.worker(rq.missingUsageQueue), time.Second)\n\t}\n\t// the timer for how often we do a full recalculation across all quotas\n\tif rq.resyncPeriod() \u003e 0 {\n\t\tgo wait.UntilWithContext(ctx, rq.enqueueAll, rq.resyncPeriod())\n\t} else {\n\t\tlogger.Info(\"periodic quota controller resync disabled\")\n\t}\n\t\u003c-ctx.Done()\n}","line":{"from":287,"to":318}} {"id":100004549,"name":"syncResourceQuotaFromKey","signature":"func (rq *Controller) syncResourceQuotaFromKey(ctx context.Context, key string) (err error)","file":"pkg/controller/resourcequota/resource_quota_controller.go","code":"// syncResourceQuotaFromKey syncs a quota key\nfunc (rq *Controller) syncResourceQuotaFromKey(ctx context.Context, key string) (err error) {\n\tstartTime := time.Now()\n\n\tlogger := klog.FromContext(ctx)\n\tlogger = klog.LoggerWithValues(logger, \"key\", key)\n\n\tdefer func() {\n\t\tlogger.V(4).Info(\"Finished syncing resource quota\", \"key\", key, \"duration\", time.Since(startTime))\n\t}()\n\n\tnamespace, name, err := cache.SplitMetaNamespaceKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresourceQuota, err := rq.rqLister.ResourceQuotas(namespace).Get(name)\n\tif errors.IsNotFound(err) {\n\t\tlogger.Info(\"Resource quota has been deleted\", \"key\", key)\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\tlogger.Error(err, \"Unable to retrieve resource quota from store\", \"key\", key)\n\t\treturn err\n\t}\n\treturn rq.syncResourceQuota(ctx, resourceQuota)\n}","line":{"from":320,"to":345}} {"id":100004550,"name":"syncResourceQuota","signature":"func (rq *Controller) syncResourceQuota(ctx context.Context, resourceQuota *v1.ResourceQuota) (err error)","file":"pkg/controller/resourcequota/resource_quota_controller.go","code":"// syncResourceQuota runs a complete sync of resource quota status across all known kinds\nfunc (rq *Controller) syncResourceQuota(ctx context.Context, resourceQuota *v1.ResourceQuota) (err error) {\n\t// quota is dirty if any part of spec hard limits differs from the status hard limits\n\tstatusLimitsDirty := !apiequality.Semantic.DeepEqual(resourceQuota.Spec.Hard, resourceQuota.Status.Hard)\n\n\t// dirty tracks if the usage status differs from the previous sync,\n\t// if so, we send a new usage with latest status\n\t// if this is our first sync, it will be dirty by default, since we need track usage\n\tdirty := statusLimitsDirty || resourceQuota.Status.Hard == nil || resourceQuota.Status.Used == nil\n\n\tused := v1.ResourceList{}\n\tif resourceQuota.Status.Used != nil {\n\t\tused = quota.Add(v1.ResourceList{}, resourceQuota.Status.Used)\n\t}\n\thardLimits := quota.Add(v1.ResourceList{}, resourceQuota.Spec.Hard)\n\n\tvar errs []error\n\n\tnewUsage, err := quota.CalculateUsage(resourceQuota.Namespace, resourceQuota.Spec.Scopes, hardLimits, rq.registry, resourceQuota.Spec.ScopeSelector)\n\tif err != nil {\n\t\t// if err is non-nil, remember it to return, but continue updating status with any resources in newUsage\n\t\terrs = append(errs, err)\n\t}\n\tfor key, value := range newUsage {\n\t\tused[key] = value\n\t}\n\n\t// ensure set of used values match those that have hard constraints\n\thardResources := quota.ResourceNames(hardLimits)\n\tused = quota.Mask(used, hardResources)\n\n\t// Create a usage object that is based on the quota resource version that will handle updates\n\t// by default, we preserve the past usage observation, and set hard to the current spec\n\tusage := resourceQuota.DeepCopy()\n\tusage.Status = v1.ResourceQuotaStatus{\n\t\tHard: hardLimits,\n\t\tUsed: used,\n\t}\n\n\tdirty = dirty || !quota.Equals(usage.Status.Used, resourceQuota.Status.Used)\n\n\t// there was a change observed by this controller that requires we update quota\n\tif dirty {\n\t\t_, err = rq.rqClient.ResourceQuotas(usage.Namespace).UpdateStatus(ctx, usage, metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\treturn utilerrors.NewAggregate(errs)\n}","line":{"from":347,"to":396}} {"id":100004551,"name":"replenishQuota","signature":"func (rq *Controller) replenishQuota(ctx context.Context, groupResource schema.GroupResource, namespace string)","file":"pkg/controller/resourcequota/resource_quota_controller.go","code":"// replenishQuota is a replenishment function invoked by a controller to notify that a quota should be recalculated\nfunc (rq *Controller) replenishQuota(ctx context.Context, groupResource schema.GroupResource, namespace string) {\n\t// check if the quota controller can evaluate this groupResource, if not, ignore it altogether...\n\tevaluator := rq.registry.Get(groupResource)\n\tif evaluator == nil {\n\t\treturn\n\t}\n\n\t// check if this namespace even has a quota...\n\tresourceQuotas, err := rq.rqLister.ResourceQuotas(namespace).List(labels.Everything())\n\tif errors.IsNotFound(err) {\n\t\tutilruntime.HandleError(fmt.Errorf(\"quota controller could not find ResourceQuota associated with namespace: %s, could take up to %v before a quota replenishes\", namespace, rq.resyncPeriod()))\n\t\treturn\n\t}\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"error checking to see if namespace %s has any ResourceQuota associated with it: %v\", namespace, err))\n\t\treturn\n\t}\n\tif len(resourceQuotas) == 0 {\n\t\treturn\n\t}\n\n\tlogger := klog.FromContext(ctx)\n\n\t// only queue those quotas that are tracking a resource associated with this kind.\n\tfor i := range resourceQuotas {\n\t\tresourceQuota := resourceQuotas[i]\n\t\tresourceQuotaResources := quota.ResourceNames(resourceQuota.Status.Hard)\n\t\tif intersection := evaluator.MatchingResources(resourceQuotaResources); len(intersection) \u003e 0 {\n\t\t\t// TODO: make this support targeted replenishment to a specific kind, right now it does a full recalc on that quota.\n\t\t\trq.enqueueResourceQuota(logger, resourceQuota)\n\t\t}\n\t}\n}","line":{"from":398,"to":431}} {"id":100004552,"name":"Sync","signature":"func (rq *Controller) Sync(ctx context.Context, discoveryFunc NamespacedResourcesFunc, period time.Duration)","file":"pkg/controller/resourcequota/resource_quota_controller.go","code":"// Sync periodically resyncs the controller when new resources are observed from discovery.\nfunc (rq *Controller) Sync(ctx context.Context, discoveryFunc NamespacedResourcesFunc, period time.Duration) {\n\t// Something has changed, so track the new state and perform a sync.\n\toldResources := make(map[schema.GroupVersionResource]struct{})\n\twait.UntilWithContext(ctx, func(ctx context.Context) {\n\t\t// Get the current resource list from discovery.\n\t\tnewResources, err := GetQuotableResources(discoveryFunc)\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(err)\n\n\t\t\tif discovery.IsGroupDiscoveryFailedError(err) \u0026\u0026 len(newResources) \u003e 0 {\n\t\t\t\t// In partial discovery cases, don't remove any existing informers, just add new ones\n\t\t\t\tfor k, v := range oldResources {\n\t\t\t\t\tnewResources[k] = v\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// short circuit in non-discovery error cases or if discovery returned zero resources\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tlogger := klog.FromContext(ctx)\n\n\t\t// Decide whether discovery has reported a change.\n\t\tif reflect.DeepEqual(oldResources, newResources) {\n\t\t\tlogger.V(4).Info(\"no resource updates from discovery, skipping resource quota sync\")\n\t\t\treturn\n\t\t}\n\n\t\t// Ensure workers are paused to avoid processing events before informers\n\t\t// have resynced.\n\t\trq.workerLock.Lock()\n\t\tdefer rq.workerLock.Unlock()\n\n\t\t// Something has changed, so track the new state and perform a sync.\n\t\tif loggerV := logger.V(2); loggerV.Enabled() {\n\t\t\tloggerV.Info(\"syncing resource quota controller with updated resources from discovery\", \"diff\", printDiff(oldResources, newResources))\n\t\t}\n\n\t\t// Perform the monitor resync and wait for controllers to report cache sync.\n\t\tif err := rq.resyncMonitors(ctx, newResources); err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"failed to sync resource monitors: %v\", err))\n\t\t\treturn\n\t\t}\n\t\t// wait for caches to fill for a while (our sync period).\n\t\t// this protects us from deadlocks where available resources changed and one of our informer caches will never fill.\n\t\t// informers keep attempting to sync in the background, so retrying doesn't interrupt them.\n\t\t// the call to resyncMonitors on the reattempt will no-op for resources that still exist.\n\t\tif rq.quotaMonitor != nil \u0026\u0026\n\t\t\t!cache.WaitForNamedCacheSync(\n\t\t\t\t\"resource quota\",\n\t\t\t\twaitForStopOrTimeout(ctx.Done(), period),\n\t\t\t\tfunc() bool { return rq.quotaMonitor.IsSynced(ctx) },\n\t\t\t) {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"timed out waiting for quota monitor sync\"))\n\t\t\treturn\n\t\t}\n\n\t\t// success, remember newly synced resources\n\t\toldResources = newResources\n\t\tlogger.V(2).Info(\"synced quota controller\")\n\t}, period)\n}","line":{"from":433,"to":495}} {"id":100004553,"name":"printDiff","signature":"func printDiff(oldResources, newResources map[schema.GroupVersionResource]struct{}) string","file":"pkg/controller/resourcequota/resource_quota_controller.go","code":"// printDiff returns a human-readable summary of what resources were added and removed\nfunc printDiff(oldResources, newResources map[schema.GroupVersionResource]struct{}) string {\n\tremoved := sets.NewString()\n\tfor oldResource := range oldResources {\n\t\tif _, ok := newResources[oldResource]; !ok {\n\t\t\tremoved.Insert(fmt.Sprintf(\"%+v\", oldResource))\n\t\t}\n\t}\n\tadded := sets.NewString()\n\tfor newResource := range newResources {\n\t\tif _, ok := oldResources[newResource]; !ok {\n\t\t\tadded.Insert(fmt.Sprintf(\"%+v\", newResource))\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"added: %v, removed: %v\", added.List(), removed.List())\n}","line":{"from":497,"to":512}} {"id":100004554,"name":"waitForStopOrTimeout","signature":"func waitForStopOrTimeout(stopCh \u003c-chan struct{}, timeout time.Duration) \u003c-chan struct{}","file":"pkg/controller/resourcequota/resource_quota_controller.go","code":"// waitForStopOrTimeout returns a stop channel that closes when the provided stop channel closes or when the specified timeout is reached\nfunc waitForStopOrTimeout(stopCh \u003c-chan struct{}, timeout time.Duration) \u003c-chan struct{} {\n\tstopChWithTimeout := make(chan struct{})\n\tgo func() {\n\t\tdefer close(stopChWithTimeout)\n\t\tselect {\n\t\tcase \u003c-stopCh:\n\t\tcase \u003c-time.After(timeout):\n\t\t}\n\t}()\n\treturn stopChWithTimeout\n}","line":{"from":514,"to":525}} {"id":100004555,"name":"resyncMonitors","signature":"func (rq *Controller) resyncMonitors(ctx context.Context, resources map[schema.GroupVersionResource]struct{}) error","file":"pkg/controller/resourcequota/resource_quota_controller.go","code":"// resyncMonitors starts or stops quota monitors as needed to ensure that all\n// (and only) those resources present in the map are monitored.\nfunc (rq *Controller) resyncMonitors(ctx context.Context, resources map[schema.GroupVersionResource]struct{}) error {\n\tif rq.quotaMonitor == nil {\n\t\treturn nil\n\t}\n\n\tif err := rq.quotaMonitor.SyncMonitors(ctx, resources); err != nil {\n\t\treturn err\n\t}\n\trq.quotaMonitor.StartMonitors(ctx)\n\treturn nil\n}","line":{"from":527,"to":539}} {"id":100004556,"name":"GetQuotableResources","signature":"func GetQuotableResources(discoveryFunc NamespacedResourcesFunc) (map[schema.GroupVersionResource]struct{}, error)","file":"pkg/controller/resourcequota/resource_quota_controller.go","code":"// GetQuotableResources returns all resources that the quota system should recognize.\n// It requires a resource supports the following verbs: 'create','list','delete'\n// This function may return both results and an error. If that happens, it means that the discovery calls were only\n// partially successful. A decision about whether to proceed or not is left to the caller.\nfunc GetQuotableResources(discoveryFunc NamespacedResourcesFunc) (map[schema.GroupVersionResource]struct{}, error) {\n\tpossibleResources, discoveryErr := discoveryFunc()\n\tif discoveryErr != nil \u0026\u0026 len(possibleResources) == 0 {\n\t\treturn nil, fmt.Errorf(\"failed to discover resources: %v\", discoveryErr)\n\t}\n\tquotableResources := discovery.FilteredBy(discovery.SupportsAllVerbs{Verbs: []string{\"create\", \"list\", \"watch\", \"delete\"}}, possibleResources)\n\tquotableGroupVersionResources, err := discovery.GroupVersionResources(quotableResources)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse resources: %v\", err)\n\t}\n\t// return the original discovery error (if any) in addition to the list\n\treturn quotableGroupVersionResources, discoveryErr\n}","line":{"from":541,"to":557}} {"id":100004557,"name":"String","signature":"func (e eventType) String() string","file":"pkg/controller/resourcequota/resource_quota_monitor.go","code":"func (e eventType) String() string {\n\tswitch e {\n\tcase addEvent:\n\t\treturn \"add\"\n\tcase updateEvent:\n\t\treturn \"update\"\n\tcase deleteEvent:\n\t\treturn \"delete\"\n\tdefault:\n\t\treturn fmt.Sprintf(\"unknown(%d)\", int(e))\n\t}\n}","line":{"from":42,"to":53}} {"id":100004558,"name":"NewMonitor","signature":"func NewMonitor(informersStarted \u003c-chan struct{}, informerFactory informerfactory.InformerFactory, ignoredResources map[schema.GroupResource]struct{}, resyncPeriod controller.ResyncPeriodFunc, replenishmentFunc ReplenishmentFunc, registry quota.Registry) *QuotaMonitor","file":"pkg/controller/resourcequota/resource_quota_monitor.go","code":"// NewMonitor creates a new instance of a QuotaMonitor\nfunc NewMonitor(informersStarted \u003c-chan struct{}, informerFactory informerfactory.InformerFactory, ignoredResources map[schema.GroupResource]struct{}, resyncPeriod controller.ResyncPeriodFunc, replenishmentFunc ReplenishmentFunc, registry quota.Registry) *QuotaMonitor {\n\treturn \u0026QuotaMonitor{\n\t\tinformersStarted: informersStarted,\n\t\tinformerFactory: informerFactory,\n\t\tignoredResources: ignoredResources,\n\t\tresourceChanges: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"resource_quota_controller_resource_changes\"),\n\t\tresyncPeriod: resyncPeriod,\n\t\treplenishmentFunc: replenishmentFunc,\n\t\tregistry: registry,\n\t}\n}","line":{"from":106,"to":117}} {"id":100004559,"name":"Run","signature":"func (m *monitor) Run()","file":"pkg/controller/resourcequota/resource_quota_monitor.go","code":"// Run is intended to be called in a goroutine. Multiple calls of this is an\n// error.\nfunc (m *monitor) Run() {\n\tm.controller.Run(m.stopCh)\n}","line":{"from":128,"to":132}} {"id":100004560,"name":"controllerFor","signature":"func (qm *QuotaMonitor) controllerFor(ctx context.Context, resource schema.GroupVersionResource) (cache.Controller, error)","file":"pkg/controller/resourcequota/resource_quota_monitor.go","code":"func (qm *QuotaMonitor) controllerFor(ctx context.Context, resource schema.GroupVersionResource) (cache.Controller, error) {\n\tlogger := klog.FromContext(ctx)\n\n\thandlers := cache.ResourceEventHandlerFuncs{\n\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\tif qm.updateFilter != nil \u0026\u0026 qm.updateFilter(resource, oldObj, newObj) {\n\t\t\t\tevent := \u0026event{\n\t\t\t\t\teventType: updateEvent,\n\t\t\t\t\tobj: newObj,\n\t\t\t\t\toldObj: oldObj,\n\t\t\t\t\tgvr: resource,\n\t\t\t\t}\n\t\t\t\tqm.resourceChanges.Add(event)\n\t\t\t}\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\t// delta fifo may wrap the object in a cache.DeletedFinalStateUnknown, unwrap it\n\t\t\tif deletedFinalStateUnknown, ok := obj.(cache.DeletedFinalStateUnknown); ok {\n\t\t\t\tobj = deletedFinalStateUnknown.Obj\n\t\t\t}\n\t\t\tevent := \u0026event{\n\t\t\t\teventType: deleteEvent,\n\t\t\t\tobj: obj,\n\t\t\t\tgvr: resource,\n\t\t\t}\n\t\t\tqm.resourceChanges.Add(event)\n\t\t},\n\t}\n\tshared, err := qm.informerFactory.ForResource(resource)\n\tif err == nil {\n\t\tlogger.V(4).Info(\"QuotaMonitor using a shared informer\", \"resource\", resource.String())\n\t\tshared.Informer().AddEventHandlerWithResyncPeriod(handlers, qm.resyncPeriod())\n\t\treturn shared.Informer().GetController(), nil\n\t}\n\tlogger.V(4).Error(err, \"QuotaMonitor unable to use a shared informer\", \"resource\", resource.String())\n\n\t// TODO: if we can share storage with garbage collector, it may make sense to support other resources\n\t// until that time, aggregated api servers will have to run their own controller to reconcile their own quota.\n\treturn nil, fmt.Errorf(\"unable to monitor quota for resource %q\", resource.String())\n}","line":{"from":139,"to":178}} {"id":100004561,"name":"SyncMonitors","signature":"func (qm *QuotaMonitor) SyncMonitors(ctx context.Context, resources map[schema.GroupVersionResource]struct{}) error","file":"pkg/controller/resourcequota/resource_quota_monitor.go","code":"// SyncMonitors rebuilds the monitor set according to the supplied resources,\n// creating or deleting monitors as necessary. It will return any error\n// encountered, but will make an attempt to create a monitor for each resource\n// instead of immediately exiting on an error. It may be called before or after\n// Run. Monitors are NOT started as part of the sync. To ensure all existing\n// monitors are started, call StartMonitors.\nfunc (qm *QuotaMonitor) SyncMonitors(ctx context.Context, resources map[schema.GroupVersionResource]struct{}) error {\n\tlogger := klog.FromContext(ctx)\n\n\tqm.monitorLock.Lock()\n\tdefer qm.monitorLock.Unlock()\n\n\ttoRemove := qm.monitors\n\tif toRemove == nil {\n\t\ttoRemove = monitors{}\n\t}\n\tcurrent := monitors{}\n\tvar errs []error\n\tkept := 0\n\tadded := 0\n\tfor resource := range resources {\n\t\tif _, ok := qm.ignoredResources[resource.GroupResource()]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tif m, ok := toRemove[resource]; ok {\n\t\t\tcurrent[resource] = m\n\t\t\tdelete(toRemove, resource)\n\t\t\tkept++\n\t\t\tcontinue\n\t\t}\n\t\tc, err := qm.controllerFor(ctx, resource)\n\t\tif err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"couldn't start monitor for resource %q: %v\", resource, err))\n\t\t\tcontinue\n\t\t}\n\n\t\t// check if we need to create an evaluator for this resource (if none previously registered)\n\t\tevaluator := qm.registry.Get(resource.GroupResource())\n\t\tif evaluator == nil {\n\t\t\tlisterFunc := generic.ListerFuncForResourceFunc(qm.informerFactory.ForResource)\n\t\t\tlistResourceFunc := generic.ListResourceUsingListerFunc(listerFunc, resource)\n\t\t\tevaluator = generic.NewObjectCountEvaluator(resource.GroupResource(), listResourceFunc, \"\")\n\t\t\tqm.registry.Add(evaluator)\n\t\t\tlogger.Info(\"QuotaMonitor created object count evaluator\", \"resource\", resource.GroupResource())\n\t\t}\n\n\t\t// track the monitor\n\t\tcurrent[resource] = \u0026monitor{controller: c}\n\t\tadded++\n\t}\n\tqm.monitors = current\n\n\tfor _, monitor := range toRemove {\n\t\tif monitor.stopCh != nil {\n\t\t\tclose(monitor.stopCh)\n\t\t}\n\t}\n\n\tlogger.V(4).Info(\"quota synced monitors\", \"added\", added, \"kept\", kept, \"removed\", len(toRemove))\n\t// NewAggregate returns nil if errs is 0-length\n\treturn utilerrors.NewAggregate(errs)\n}","line":{"from":180,"to":241}} {"id":100004562,"name":"StartMonitors","signature":"func (qm *QuotaMonitor) StartMonitors(ctx context.Context)","file":"pkg/controller/resourcequota/resource_quota_monitor.go","code":"// StartMonitors ensures the current set of monitors are running. Any newly\n// started monitors will also cause shared informers to be started.\n//\n// If called before Run, StartMonitors does nothing (as there is no stop channel\n// to support monitor/informer execution).\nfunc (qm *QuotaMonitor) StartMonitors(ctx context.Context) {\n\tqm.monitorLock.Lock()\n\tdefer qm.monitorLock.Unlock()\n\n\tif !qm.running {\n\t\treturn\n\t}\n\n\t// we're waiting until after the informer start that happens once all the controllers are initialized. This ensures\n\t// that they don't get unexpected events on their work queues.\n\t\u003c-qm.informersStarted\n\n\tmonitors := qm.monitors\n\tstarted := 0\n\tfor _, monitor := range monitors {\n\t\tif monitor.stopCh == nil {\n\t\t\tmonitor.stopCh = make(chan struct{})\n\t\t\tqm.informerFactory.Start(qm.stopCh)\n\t\t\tgo monitor.Run()\n\t\t\tstarted++\n\t\t}\n\t}\n\tklog.FromContext(ctx).V(4).Info(\"QuotaMonitor finished starting monitors\", \"new\", started, \"total\", len(monitors))\n}","line":{"from":243,"to":271}} {"id":100004563,"name":"IsSynced","signature":"func (qm *QuotaMonitor) IsSynced(ctx context.Context) bool","file":"pkg/controller/resourcequota/resource_quota_monitor.go","code":"// IsSynced returns true if any monitors exist AND all those monitors'\n// controllers HasSynced functions return true. This means IsSynced could return\n// true at one time, and then later return false if all monitors were\n// reconstructed.\nfunc (qm *QuotaMonitor) IsSynced(ctx context.Context) bool {\n\tlogger := klog.FromContext(ctx)\n\n\tqm.monitorLock.RLock()\n\tdefer qm.monitorLock.RUnlock()\n\n\tif len(qm.monitors) == 0 {\n\t\tlogger.V(4).Info(\"quota monitor not synced: no monitors\")\n\t\treturn false\n\t}\n\n\tfor resource, monitor := range qm.monitors {\n\t\tif !monitor.controller.HasSynced() {\n\t\t\tlogger.V(4).Info(\"quota monitor not synced\", \"resource\", resource)\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":273,"to":295}} {"id":100004564,"name":"Run","signature":"func (qm *QuotaMonitor) Run(ctx context.Context)","file":"pkg/controller/resourcequota/resource_quota_monitor.go","code":"// Run sets the stop channel and starts monitor execution until stopCh is\n// closed. Any running monitors will be stopped before Run returns.\nfunc (qm *QuotaMonitor) Run(ctx context.Context) {\n\tdefer utilruntime.HandleCrash()\n\n\tlogger := klog.FromContext(ctx)\n\n\tlogger.Info(\"QuotaMonitor running\")\n\tdefer logger.Info(\"QuotaMonitor stopping\")\n\n\t// Set up the stop channel.\n\tqm.monitorLock.Lock()\n\tqm.stopCh = ctx.Done()\n\tqm.running = true\n\tqm.monitorLock.Unlock()\n\n\t// Start monitors and begin change processing until the stop channel is\n\t// closed.\n\tqm.StartMonitors(ctx)\n\n\t// The following workers are hanging forever until the queue is\n\t// shutted down, so we need to shut it down in a separate goroutine.\n\tgo func() {\n\t\tdefer utilruntime.HandleCrash()\n\t\tdefer qm.resourceChanges.ShutDown()\n\n\t\t\u003c-ctx.Done()\n\t}()\n\twait.UntilWithContext(ctx, qm.runProcessResourceChanges, 1*time.Second)\n\n\t// Stop any running monitors.\n\tqm.monitorLock.Lock()\n\tdefer qm.monitorLock.Unlock()\n\tmonitors := qm.monitors\n\tstopped := 0\n\tfor _, monitor := range monitors {\n\t\tif monitor.stopCh != nil {\n\t\t\tstopped++\n\t\t\tclose(monitor.stopCh)\n\t\t}\n\t}\n\tlogger.Info(\"QuotaMonitor stopped monitors\", \"stopped\", stopped, \"total\", len(monitors))\n}","line":{"from":297,"to":339}} {"id":100004565,"name":"runProcessResourceChanges","signature":"func (qm *QuotaMonitor) runProcessResourceChanges(ctx context.Context)","file":"pkg/controller/resourcequota/resource_quota_monitor.go","code":"func (qm *QuotaMonitor) runProcessResourceChanges(ctx context.Context) {\n\tfor qm.processResourceChanges(ctx) {\n\t}\n}","line":{"from":341,"to":344}} {"id":100004566,"name":"processResourceChanges","signature":"func (qm *QuotaMonitor) processResourceChanges(ctx context.Context) bool","file":"pkg/controller/resourcequota/resource_quota_monitor.go","code":"// Dequeueing an event from resourceChanges to process\nfunc (qm *QuotaMonitor) processResourceChanges(ctx context.Context) bool {\n\titem, quit := qm.resourceChanges.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer qm.resourceChanges.Done(item)\n\tevent, ok := item.(*event)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"expect a *event, got %v\", item))\n\t\treturn true\n\t}\n\tobj := event.obj\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"cannot access obj: %v\", err))\n\t\treturn true\n\t}\n\tklog.FromContext(ctx).V(4).Info(\"QuotaMonitor process object\",\n\t\t\"resource\", event.gvr.String(),\n\t\t\"namespace\", accessor.GetNamespace(),\n\t\t\"name\", accessor.GetName(),\n\t\t\"uid\", string(accessor.GetUID()),\n\t\t\"eventType\", event.eventType,\n\t)\n\tqm.replenishmentFunc(ctx, event.gvr.GroupResource(), accessor.GetNamespace())\n\treturn true\n}","line":{"from":346,"to":373}} {"id":100004567,"name":"Convert_v1alpha1_SAControllerConfiguration_To_config_SAControllerConfiguration","signature":"func Convert_v1alpha1_SAControllerConfiguration_To_config_SAControllerConfiguration(in *v1alpha1.SAControllerConfiguration, out *config.SAControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/serviceaccount/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_SAControllerConfiguration_To_config_SAControllerConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_SAControllerConfiguration_To_config_SAControllerConfiguration(in *v1alpha1.SAControllerConfiguration, out *config.SAControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_SAControllerConfiguration_To_config_SAControllerConfiguration(in, out, s)\n}","line":{"from":32,"to":35}} {"id":100004568,"name":"Convert_config_SAControllerConfiguration_To_v1alpha1_SAControllerConfiguration","signature":"func Convert_config_SAControllerConfiguration_To_v1alpha1_SAControllerConfiguration(in *config.SAControllerConfiguration, out *v1alpha1.SAControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/serviceaccount/config/v1alpha1/conversion.go","code":"// Convert_config_SAControllerConfiguration_To_v1alpha1_SAControllerConfiguration is an autogenerated conversion function.\nfunc Convert_config_SAControllerConfiguration_To_v1alpha1_SAControllerConfiguration(in *config.SAControllerConfiguration, out *v1alpha1.SAControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_SAControllerConfiguration_To_v1alpha1_SAControllerConfiguration(in, out, s)\n}","line":{"from":37,"to":40}} {"id":100004569,"name":"RecommendedDefaultSAControllerConfiguration","signature":"func RecommendedDefaultSAControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.SAControllerConfiguration)","file":"pkg/controller/serviceaccount/config/v1alpha1/defaults.go","code":"// RecommendedDefaultSAControllerConfiguration defaults a pointer to a\n// SAControllerConfiguration struct. This will set the recommended default\n// values, but they may be subject to change between API versions. This function\n// is intentionally not registered in the scheme as a \"normal\" `SetDefaults_Foo`\n// function to allow consumers of this type to set whatever defaults for their\n// embedded configs. Forcing consumers to use these defaults would be problematic\n// as defaulting in the scheme is done as part of the conversion, and there would\n// be no easy way to opt-out. Instead, if you want to use this defaulting method\n// run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDefaultSAControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.SAControllerConfiguration) {\n\tif obj.ConcurrentSATokenSyncs == 0 {\n\t\tobj.ConcurrentSATokenSyncs = 5\n\t}\n}","line":{"from":23,"to":36}} {"id":100004570,"name":"DefaultServiceAccountsControllerOptions","signature":"func DefaultServiceAccountsControllerOptions() ServiceAccountsControllerOptions","file":"pkg/controller/serviceaccount/serviceaccounts_controller.go","code":"// DefaultServiceAccountsControllerOptions returns the default options for creating a ServiceAccountsController.\nfunc DefaultServiceAccountsControllerOptions() ServiceAccountsControllerOptions {\n\treturn ServiceAccountsControllerOptions{\n\t\tServiceAccounts: []v1.ServiceAccount{\n\t\t\t{ObjectMeta: metav1.ObjectMeta{Name: \"default\"}},\n\t\t},\n\t}\n}","line":{"from":54,"to":61}} {"id":100004571,"name":"NewServiceAccountsController","signature":"func NewServiceAccountsController(saInformer coreinformers.ServiceAccountInformer, nsInformer coreinformers.NamespaceInformer, cl clientset.Interface, options ServiceAccountsControllerOptions) (*ServiceAccountsController, error)","file":"pkg/controller/serviceaccount/serviceaccounts_controller.go","code":"// NewServiceAccountsController returns a new *ServiceAccountsController.\nfunc NewServiceAccountsController(saInformer coreinformers.ServiceAccountInformer, nsInformer coreinformers.NamespaceInformer, cl clientset.Interface, options ServiceAccountsControllerOptions) (*ServiceAccountsController, error) {\n\te := \u0026ServiceAccountsController{\n\t\tclient: cl,\n\t\tserviceAccountsToEnsure: options.ServiceAccounts,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"serviceaccount\"),\n\t}\n\n\tsaHandler, _ := saInformer.Informer().AddEventHandlerWithResyncPeriod(cache.ResourceEventHandlerFuncs{\n\t\tDeleteFunc: e.serviceAccountDeleted,\n\t}, options.ServiceAccountResync)\n\te.saLister = saInformer.Lister()\n\te.saListerSynced = saHandler.HasSynced\n\n\tnsHandler, _ := nsInformer.Informer().AddEventHandlerWithResyncPeriod(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: e.namespaceAdded,\n\t\tUpdateFunc: e.namespaceUpdated,\n\t}, options.NamespaceResync)\n\te.nsLister = nsInformer.Lister()\n\te.nsListerSynced = nsHandler.HasSynced\n\n\te.syncHandler = e.syncNamespace\n\n\treturn e, nil\n}","line":{"from":63,"to":87}} {"id":100004572,"name":"Run","signature":"func (c *ServiceAccountsController) Run(ctx context.Context, workers int)","file":"pkg/controller/serviceaccount/serviceaccounts_controller.go","code":"// Run runs the ServiceAccountsController blocks until receiving signal from stopCh.\nfunc (c *ServiceAccountsController) Run(ctx context.Context, workers int) {\n\tdefer utilruntime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\n\tklog.FromContext(ctx).Info(\"Starting service account controller\")\n\tdefer klog.FromContext(ctx).Info(\"Shutting down service account controller\")\n\n\tif !cache.WaitForNamedCacheSync(\"service account\", ctx.Done(), c.saListerSynced, c.nsListerSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.UntilWithContext(ctx, c.runWorker, time.Second)\n\t}\n\n\t\u003c-ctx.Done()\n}","line":{"from":106,"to":123}} {"id":100004573,"name":"serviceAccountDeleted","signature":"func (c *ServiceAccountsController) serviceAccountDeleted(obj interface{})","file":"pkg/controller/serviceaccount/serviceaccounts_controller.go","code":"// serviceAccountDeleted reacts to a ServiceAccount deletion by recreating a default ServiceAccount in the namespace if needed\nfunc (c *ServiceAccountsController) serviceAccountDeleted(obj interface{}) {\n\tsa, ok := obj.(*v1.ServiceAccount)\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"Couldn't get object from tombstone %#v\", obj))\n\t\t\treturn\n\t\t}\n\t\tsa, ok = tombstone.Obj.(*v1.ServiceAccount)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"Tombstone contained object that is not a ServiceAccount %#v\", obj))\n\t\t\treturn\n\t\t}\n\t}\n\tc.queue.Add(sa.Namespace)\n}","line":{"from":125,"to":141}} {"id":100004574,"name":"namespaceAdded","signature":"func (c *ServiceAccountsController) namespaceAdded(obj interface{})","file":"pkg/controller/serviceaccount/serviceaccounts_controller.go","code":"// namespaceAdded reacts to a Namespace creation by creating a default ServiceAccount object\nfunc (c *ServiceAccountsController) namespaceAdded(obj interface{}) {\n\tnamespace := obj.(*v1.Namespace)\n\tc.queue.Add(namespace.Name)\n}","line":{"from":143,"to":147}} {"id":100004575,"name":"namespaceUpdated","signature":"func (c *ServiceAccountsController) namespaceUpdated(oldObj interface{}, newObj interface{})","file":"pkg/controller/serviceaccount/serviceaccounts_controller.go","code":"// namespaceUpdated reacts to a Namespace update (or re-list) by creating a default ServiceAccount in the namespace if needed\nfunc (c *ServiceAccountsController) namespaceUpdated(oldObj interface{}, newObj interface{}) {\n\tnewNamespace := newObj.(*v1.Namespace)\n\tc.queue.Add(newNamespace.Name)\n}","line":{"from":149,"to":153}} {"id":100004576,"name":"runWorker","signature":"func (c *ServiceAccountsController) runWorker(ctx context.Context)","file":"pkg/controller/serviceaccount/serviceaccounts_controller.go","code":"func (c *ServiceAccountsController) runWorker(ctx context.Context) {\n\tfor c.processNextWorkItem(ctx) {\n\t}\n}","line":{"from":155,"to":158}} {"id":100004577,"name":"processNextWorkItem","signature":"func (c *ServiceAccountsController) processNextWorkItem(ctx context.Context) bool","file":"pkg/controller/serviceaccount/serviceaccounts_controller.go","code":"// processNextWorkItem deals with one key off the queue. It returns false when it's time to quit.\nfunc (c *ServiceAccountsController) processNextWorkItem(ctx context.Context) bool {\n\tkey, quit := c.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.queue.Done(key)\n\n\terr := c.syncHandler(ctx, key.(string))\n\tif err == nil {\n\t\tc.queue.Forget(key)\n\t\treturn true\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"%v failed with : %v\", key, err))\n\tc.queue.AddRateLimited(key)\n\n\treturn true\n}","line":{"from":160,"to":178}} {"id":100004578,"name":"syncNamespace","signature":"func (c *ServiceAccountsController) syncNamespace(ctx context.Context, key string) error","file":"pkg/controller/serviceaccount/serviceaccounts_controller.go","code":"func (c *ServiceAccountsController) syncNamespace(ctx context.Context, key string) error {\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tklog.FromContext(ctx).V(4).Info(\"Finished syncing namespace\", \"namespace\", key, \"duration\", time.Since(startTime))\n\t}()\n\n\tns, err := c.nsLister.Get(key)\n\tif apierrors.IsNotFound(err) {\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tif ns.Status.Phase != v1.NamespaceActive {\n\t\t// If namespace is not active, we shouldn't try to create anything\n\t\treturn nil\n\t}\n\n\tcreateFailures := []error{}\n\tfor _, sa := range c.serviceAccountsToEnsure {\n\t\tswitch _, err := c.saLister.ServiceAccounts(ns.Name).Get(sa.Name); {\n\t\tcase err == nil:\n\t\t\tcontinue\n\t\tcase apierrors.IsNotFound(err):\n\t\tcase err != nil:\n\t\t\treturn err\n\t\t}\n\t\t// this is only safe because we never read it and we always write it\n\t\t// TODO eliminate this once the fake client can handle creation without NS\n\t\tsa.Namespace = ns.Name\n\n\t\tif _, err := c.client.CoreV1().ServiceAccounts(ns.Name).Create(ctx, \u0026sa, metav1.CreateOptions{}); err != nil \u0026\u0026 !apierrors.IsAlreadyExists(err) {\n\t\t\t// we can safely ignore terminating namespace errors\n\t\t\tif !apierrors.HasStatusCause(err, v1.NamespaceTerminatingCause) {\n\t\t\t\tcreateFailures = append(createFailures, err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn utilerrors.Flatten(utilerrors.NewAggregate(createFailures))\n}","line":{"from":179,"to":219}} {"id":100004579,"name":"NewGetterFromClient","signature":"func NewGetterFromClient(c clientset.Interface, secretLister v1listers.SecretLister, serviceAccountLister v1listers.ServiceAccountLister, podLister v1listers.PodLister) serviceaccount.ServiceAccountTokenGetter","file":"pkg/controller/serviceaccount/tokengetter.go","code":"// NewGetterFromClient returns a ServiceAccountTokenGetter that\n// uses the specified client to retrieve service accounts and secrets.\n// The client should NOT authenticate using a service account token\n// the returned getter will be used to retrieve, or recursion will result.\nfunc NewGetterFromClient(c clientset.Interface, secretLister v1listers.SecretLister, serviceAccountLister v1listers.ServiceAccountLister, podLister v1listers.PodLister) serviceaccount.ServiceAccountTokenGetter {\n\treturn clientGetter{c, secretLister, serviceAccountLister, podLister}\n}","line":{"from":36,"to":42}} {"id":100004580,"name":"GetServiceAccount","signature":"func (c clientGetter) GetServiceAccount(namespace, name string) (*v1.ServiceAccount, error)","file":"pkg/controller/serviceaccount/tokengetter.go","code":"func (c clientGetter) GetServiceAccount(namespace, name string) (*v1.ServiceAccount, error) {\n\tif serviceAccount, err := c.serviceAccountLister.ServiceAccounts(namespace).Get(name); err == nil {\n\t\treturn serviceAccount, nil\n\t}\n\treturn c.client.CoreV1().ServiceAccounts(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n}","line":{"from":44,"to":49}} {"id":100004581,"name":"GetPod","signature":"func (c clientGetter) GetPod(namespace, name string) (*v1.Pod, error)","file":"pkg/controller/serviceaccount/tokengetter.go","code":"func (c clientGetter) GetPod(namespace, name string) (*v1.Pod, error) {\n\tif pod, err := c.podLister.Pods(namespace).Get(name); err == nil {\n\t\treturn pod, nil\n\t}\n\treturn c.client.CoreV1().Pods(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n}","line":{"from":51,"to":56}} {"id":100004582,"name":"GetSecret","signature":"func (c clientGetter) GetSecret(namespace, name string) (*v1.Secret, error)","file":"pkg/controller/serviceaccount/tokengetter.go","code":"func (c clientGetter) GetSecret(namespace, name string) (*v1.Secret, error) {\n\tif secret, err := c.secretLister.Secrets(namespace).Get(name); err == nil {\n\t\treturn secret, nil\n\t}\n\treturn c.client.CoreV1().Secrets(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n}","line":{"from":58,"to":63}} {"id":100004583,"name":"NewTokensController","signature":"func NewTokensController(serviceAccounts informers.ServiceAccountInformer, secrets informers.SecretInformer, cl clientset.Interface, options TokensControllerOptions) (*TokensController, error)","file":"pkg/controller/serviceaccount/tokens_controller.go","code":"// NewTokensController returns a new *TokensController.\nfunc NewTokensController(serviceAccounts informers.ServiceAccountInformer, secrets informers.SecretInformer, cl clientset.Interface, options TokensControllerOptions) (*TokensController, error) {\n\tmaxRetries := options.MaxRetries\n\tif maxRetries == 0 {\n\t\tmaxRetries = 10\n\t}\n\n\te := \u0026TokensController{\n\t\tclient: cl,\n\t\ttoken: options.TokenGenerator,\n\t\trootCA: options.RootCA,\n\n\t\tsyncServiceAccountQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"serviceaccount_tokens_service\"),\n\t\tsyncSecretQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"serviceaccount_tokens_secret\"),\n\n\t\tmaxRetries: maxRetries,\n\t}\n\n\te.serviceAccounts = serviceAccounts.Lister()\n\te.serviceAccountSynced = serviceAccounts.Informer().HasSynced\n\tserviceAccounts.Informer().AddEventHandlerWithResyncPeriod(\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: e.queueServiceAccountSync,\n\t\t\tUpdateFunc: e.queueServiceAccountUpdateSync,\n\t\t\tDeleteFunc: e.queueServiceAccountSync,\n\t\t},\n\t\toptions.ServiceAccountResync,\n\t)\n\n\tsecretCache := secrets.Informer().GetIndexer()\n\te.updatedSecrets = cache.NewIntegerResourceVersionMutationCache(secretCache, secretCache, 60*time.Second, true)\n\te.secretSynced = secrets.Informer().HasSynced\n\tsecrets.Informer().AddEventHandlerWithResyncPeriod(\n\t\tcache.FilteringResourceEventHandler{\n\t\t\tFilterFunc: func(obj interface{}) bool {\n\t\t\t\tswitch t := obj.(type) {\n\t\t\t\tcase *v1.Secret:\n\t\t\t\t\treturn t.Type == v1.SecretTypeServiceAccountToken\n\t\t\t\tdefault:\n\t\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"object passed to %T that is not expected: %T\", e, obj))\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t},\n\t\t\tHandler: cache.ResourceEventHandlerFuncs{\n\t\t\t\tAddFunc: e.queueSecretSync,\n\t\t\t\tUpdateFunc: e.queueSecretUpdateSync,\n\t\t\t\tDeleteFunc: e.queueSecretSync,\n\t\t\t},\n\t\t},\n\t\toptions.SecretResync,\n\t)\n\n\treturn e, nil\n}","line":{"from":71,"to":124}} {"id":100004584,"name":"Run","signature":"func (e *TokensController) Run(ctx context.Context, workers int)","file":"pkg/controller/serviceaccount/tokens_controller.go","code":"// Run runs controller blocks until stopCh is closed\nfunc (e *TokensController) Run(ctx context.Context, workers int) {\n\t// Shut down queues\n\tdefer utilruntime.HandleCrash()\n\tdefer e.syncServiceAccountQueue.ShutDown()\n\tdefer e.syncSecretQueue.ShutDown()\n\n\tif !cache.WaitForNamedCacheSync(\"tokens\", ctx.Done(), e.serviceAccountSynced, e.secretSynced) {\n\t\treturn\n\t}\n\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(5).Info(\"Starting workers\")\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.UntilWithContext(ctx, e.syncServiceAccount, 0)\n\t\tgo wait.UntilWithContext(ctx, e.syncSecret, 0)\n\t}\n\t\u003c-ctx.Done()\n\tlogger.V(1).Info(\"Shutting down\")\n}","line":{"from":158,"to":177}} {"id":100004585,"name":"queueServiceAccountSync","signature":"func (e *TokensController) queueServiceAccountSync(obj interface{})","file":"pkg/controller/serviceaccount/tokens_controller.go","code":"func (e *TokensController) queueServiceAccountSync(obj interface{}) {\n\tif serviceAccount, ok := obj.(*v1.ServiceAccount); ok {\n\t\te.syncServiceAccountQueue.Add(makeServiceAccountKey(serviceAccount))\n\t}\n}","line":{"from":179,"to":183}} {"id":100004586,"name":"queueServiceAccountUpdateSync","signature":"func (e *TokensController) queueServiceAccountUpdateSync(oldObj interface{}, newObj interface{})","file":"pkg/controller/serviceaccount/tokens_controller.go","code":"func (e *TokensController) queueServiceAccountUpdateSync(oldObj interface{}, newObj interface{}) {\n\tif serviceAccount, ok := newObj.(*v1.ServiceAccount); ok {\n\t\te.syncServiceAccountQueue.Add(makeServiceAccountKey(serviceAccount))\n\t}\n}","line":{"from":185,"to":189}} {"id":100004587,"name":"retryOrForget","signature":"func (e *TokensController) retryOrForget(logger klog.Logger, queue workqueue.RateLimitingInterface, key interface{}, requeue bool)","file":"pkg/controller/serviceaccount/tokens_controller.go","code":"// complete optionally requeues key, then calls queue.Done(key)\nfunc (e *TokensController) retryOrForget(logger klog.Logger, queue workqueue.RateLimitingInterface, key interface{}, requeue bool) {\n\tif !requeue {\n\t\tqueue.Forget(key)\n\t\treturn\n\t}\n\n\trequeueCount := queue.NumRequeues(key)\n\tif requeueCount \u003c e.maxRetries {\n\t\tqueue.AddRateLimited(key)\n\t\treturn\n\t}\n\n\tlogger.V(4).Info(\"retried several times\", \"key\", key, \"count\", requeueCount)\n\tqueue.Forget(key)\n}","line":{"from":191,"to":206}} {"id":100004588,"name":"queueSecretSync","signature":"func (e *TokensController) queueSecretSync(obj interface{})","file":"pkg/controller/serviceaccount/tokens_controller.go","code":"func (e *TokensController) queueSecretSync(obj interface{}) {\n\tif secret, ok := obj.(*v1.Secret); ok {\n\t\te.syncSecretQueue.Add(makeSecretQueueKey(secret))\n\t}\n}","line":{"from":208,"to":212}} {"id":100004589,"name":"queueSecretUpdateSync","signature":"func (e *TokensController) queueSecretUpdateSync(oldObj interface{}, newObj interface{})","file":"pkg/controller/serviceaccount/tokens_controller.go","code":"func (e *TokensController) queueSecretUpdateSync(oldObj interface{}, newObj interface{}) {\n\tif secret, ok := newObj.(*v1.Secret); ok {\n\t\te.syncSecretQueue.Add(makeSecretQueueKey(secret))\n\t}\n}","line":{"from":214,"to":218}} {"id":100004590,"name":"syncServiceAccount","signature":"func (e *TokensController) syncServiceAccount(ctx context.Context)","file":"pkg/controller/serviceaccount/tokens_controller.go","code":"func (e *TokensController) syncServiceAccount(ctx context.Context) {\n\tlogger := klog.FromContext(ctx)\n\tkey, quit := e.syncServiceAccountQueue.Get()\n\tif quit {\n\t\treturn\n\t}\n\tdefer e.syncServiceAccountQueue.Done(key)\n\n\tretry := false\n\tdefer func() {\n\t\te.retryOrForget(logger, e.syncServiceAccountQueue, key, retry)\n\t}()\n\n\tsaInfo, err := parseServiceAccountKey(key)\n\tif err != nil {\n\t\tlogger.Error(err, \"Parsing service account key\")\n\t\treturn\n\t}\n\n\tsa, err := e.getServiceAccount(saInfo.namespace, saInfo.name, saInfo.uid, false)\n\tswitch {\n\tcase err != nil:\n\t\tlogger.Error(err, \"Getting service account\")\n\t\tretry = true\n\tcase sa == nil:\n\t\t// service account no longer exists, so delete related tokens\n\t\tlogger.V(4).Info(\"Service account deleted, removing tokens\", \"namespace\", saInfo.namespace, \"serviceaccount\", saInfo.name)\n\t\tsa = \u0026v1.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Namespace: saInfo.namespace, Name: saInfo.name, UID: saInfo.uid}}\n\t\tretry, err = e.deleteTokens(sa)\n\t\tif err != nil {\n\t\t\tlogger.Error(err, \"Error deleting serviceaccount tokens\", \"namespace\", saInfo.namespace, \"serviceaccount\", saInfo.name)\n\t\t}\n\t}\n}","line":{"from":220,"to":253}} {"id":100004591,"name":"syncSecret","signature":"func (e *TokensController) syncSecret(ctx context.Context)","file":"pkg/controller/serviceaccount/tokens_controller.go","code":"func (e *TokensController) syncSecret(ctx context.Context) {\n\tkey, quit := e.syncSecretQueue.Get()\n\tif quit {\n\t\treturn\n\t}\n\tdefer e.syncSecretQueue.Done(key)\n\n\tlogger := klog.FromContext(ctx)\n\t// Track whether or not we should retry this sync\n\tretry := false\n\tdefer func() {\n\t\te.retryOrForget(logger, e.syncSecretQueue, key, retry)\n\t}()\n\n\tsecretInfo, err := parseSecretQueueKey(key)\n\tif err != nil {\n\t\tlogger.Error(err, \"Parsing secret queue key\")\n\t\treturn\n\t}\n\n\tsecret, err := e.getSecret(secretInfo.namespace, secretInfo.name, secretInfo.uid, false)\n\tswitch {\n\tcase err != nil:\n\t\tlogger.Error(err, \"Getting secret\")\n\t\tretry = true\n\tcase secret == nil:\n\t\t// If the service account exists\n\t\tif sa, saErr := e.getServiceAccount(secretInfo.namespace, secretInfo.saName, secretInfo.saUID, false); saErr == nil \u0026\u0026 sa != nil {\n\t\t\t// secret no longer exists, so delete references to this secret from the service account\n\t\t\tif err := clientretry.RetryOnConflict(RemoveTokenBackoff, func() error {\n\t\t\t\treturn e.removeSecretReference(secretInfo.namespace, secretInfo.saName, secretInfo.saUID, secretInfo.name)\n\t\t\t}); err != nil {\n\t\t\t\tlogger.Error(err, \"Removing secret reference\")\n\t\t\t}\n\t\t}\n\tdefault:\n\t\t// Ensure service account exists\n\t\tsa, saErr := e.getServiceAccount(secretInfo.namespace, secretInfo.saName, secretInfo.saUID, true)\n\t\tswitch {\n\t\tcase saErr != nil:\n\t\t\tlogger.Error(saErr, \"Getting service account\")\n\t\t\tretry = true\n\t\tcase sa == nil:\n\t\t\t// Delete token\n\t\t\tlogger.V(4).Info(\"Service account does not exist, deleting token\", \"secret\", klog.KRef(secretInfo.namespace, secretInfo.name))\n\t\t\tif retriable, err := e.deleteToken(secretInfo.namespace, secretInfo.name, secretInfo.uid); err != nil {\n\t\t\t\tlogger.Error(err, \"Deleting serviceaccount token\", \"secret\", klog.KRef(secretInfo.namespace, secretInfo.name), \"serviceAccount\", klog.KRef(secretInfo.namespace, secretInfo.saName))\n\t\t\t\tretry = retriable\n\t\t\t}\n\t\tdefault:\n\t\t\t// Update token if needed\n\t\t\tif retriable, err := e.generateTokenIfNeeded(logger, sa, secret); err != nil {\n\t\t\t\tlogger.Error(err, \"Populating serviceaccount token\", \"secret\", klog.KRef(secretInfo.namespace, secretInfo.name), \"serviceAccount\", klog.KRef(secretInfo.namespace, secretInfo.saName))\n\t\t\t\tretry = retriable\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":255,"to":312}} {"id":100004592,"name":"deleteTokens","signature":"func (e *TokensController) deleteTokens(serviceAccount *v1.ServiceAccount) ( /*retry*/ bool, error)","file":"pkg/controller/serviceaccount/tokens_controller.go","code":"func (e *TokensController) deleteTokens(serviceAccount *v1.ServiceAccount) ( /*retry*/ bool, error) {\n\ttokens, err := e.listTokenSecrets(serviceAccount)\n\tif err != nil {\n\t\t// don't retry on cache lookup errors\n\t\treturn false, err\n\t}\n\tretry := false\n\terrs := []error{}\n\tfor _, token := range tokens {\n\t\tr, err := e.deleteToken(token.Namespace, token.Name, token.UID)\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t\tif r {\n\t\t\tretry = true\n\t\t}\n\t}\n\treturn retry, utilerrors.NewAggregate(errs)\n}","line":{"from":314,"to":332}} {"id":100004593,"name":"deleteToken","signature":"func (e *TokensController) deleteToken(ns, name string, uid types.UID) ( /*retry*/ bool, error)","file":"pkg/controller/serviceaccount/tokens_controller.go","code":"func (e *TokensController) deleteToken(ns, name string, uid types.UID) ( /*retry*/ bool, error) {\n\tvar opts metav1.DeleteOptions\n\tif len(uid) \u003e 0 {\n\t\topts.Preconditions = \u0026metav1.Preconditions{UID: \u0026uid}\n\t}\n\terr := e.client.CoreV1().Secrets(ns).Delete(context.TODO(), name, opts)\n\t// NotFound doesn't need a retry (it's already been deleted)\n\t// Conflict doesn't need a retry (the UID precondition failed)\n\tif err == nil || apierrors.IsNotFound(err) || apierrors.IsConflict(err) {\n\t\treturn false, nil\n\t}\n\t// Retry for any other error\n\treturn true, err\n}","line":{"from":334,"to":347}} {"id":100004594,"name":"secretUpdateNeeded","signature":"func (e *TokensController) secretUpdateNeeded(secret *v1.Secret) (bool, bool, bool)","file":"pkg/controller/serviceaccount/tokens_controller.go","code":"func (e *TokensController) secretUpdateNeeded(secret *v1.Secret) (bool, bool, bool) {\n\tcaData := secret.Data[v1.ServiceAccountRootCAKey]\n\tneedsCA := len(e.rootCA) \u003e 0 \u0026\u0026 !bytes.Equal(caData, e.rootCA)\n\n\tneedsNamespace := len(secret.Data[v1.ServiceAccountNamespaceKey]) == 0\n\n\ttokenData := secret.Data[v1.ServiceAccountTokenKey]\n\tneedsToken := len(tokenData) == 0\n\n\treturn needsCA, needsNamespace, needsToken\n}","line":{"from":349,"to":359}} {"id":100004595,"name":"generateTokenIfNeeded","signature":"func (e *TokensController) generateTokenIfNeeded(logger klog.Logger, serviceAccount *v1.ServiceAccount, cachedSecret *v1.Secret) ( /* retry */ bool, error)","file":"pkg/controller/serviceaccount/tokens_controller.go","code":"// generateTokenIfNeeded populates the token data for the given Secret if not already set\nfunc (e *TokensController) generateTokenIfNeeded(logger klog.Logger, serviceAccount *v1.ServiceAccount, cachedSecret *v1.Secret) ( /* retry */ bool, error) {\n\t// Check the cached secret to see if changes are needed\n\tif needsCA, needsNamespace, needsToken := e.secretUpdateNeeded(cachedSecret); !needsCA \u0026\u0026 !needsToken \u0026\u0026 !needsNamespace {\n\t\treturn false, nil\n\t}\n\n\t// We don't want to update the cache's copy of the secret\n\t// so add the token to a freshly retrieved copy of the secret\n\tsecrets := e.client.CoreV1().Secrets(cachedSecret.Namespace)\n\tliveSecret, err := secrets.Get(context.TODO(), cachedSecret.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\t// Retry for any error other than a NotFound\n\t\treturn !apierrors.IsNotFound(err), err\n\t}\n\tif liveSecret.ResourceVersion != cachedSecret.ResourceVersion {\n\t\t// our view of the secret is not up to date\n\t\t// we'll get notified of an update event later and get to try again\n\t\tlogger.V(2).Info(\"Secret is not up to date, skipping token population\", \"secret\", klog.KRef(liveSecret.Namespace, liveSecret.Name))\n\t\treturn false, nil\n\t}\n\n\tneedsCA, needsNamespace, needsToken := e.secretUpdateNeeded(liveSecret)\n\tif !needsCA \u0026\u0026 !needsToken \u0026\u0026 !needsNamespace {\n\t\treturn false, nil\n\t}\n\n\tif liveSecret.Annotations == nil {\n\t\tliveSecret.Annotations = map[string]string{}\n\t}\n\tif liveSecret.Data == nil {\n\t\tliveSecret.Data = map[string][]byte{}\n\t}\n\n\t// Set the CA\n\tif needsCA {\n\t\tliveSecret.Data[v1.ServiceAccountRootCAKey] = e.rootCA\n\t}\n\t// Set the namespace\n\tif needsNamespace {\n\t\tliveSecret.Data[v1.ServiceAccountNamespaceKey] = []byte(liveSecret.Namespace)\n\t}\n\n\t// Generate the token\n\tif needsToken {\n\t\ttoken, err := e.token.GenerateToken(serviceaccount.LegacyClaims(*serviceAccount, *liveSecret))\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tliveSecret.Data[v1.ServiceAccountTokenKey] = []byte(token)\n\t}\n\n\t// Set annotations\n\tliveSecret.Annotations[v1.ServiceAccountNameKey] = serviceAccount.Name\n\tliveSecret.Annotations[v1.ServiceAccountUIDKey] = string(serviceAccount.UID)\n\n\t// Save the secret\n\t_, err = secrets.Update(context.TODO(), liveSecret, metav1.UpdateOptions{})\n\tif apierrors.IsConflict(err) || apierrors.IsNotFound(err) {\n\t\t// if we got a Conflict error, the secret was updated by someone else, and we'll get an update notification later\n\t\t// if we got a NotFound error, the secret no longer exists, and we don't need to populate a token\n\t\treturn false, nil\n\t}\n\tif err != nil {\n\t\treturn true, err\n\t}\n\treturn false, nil\n}","line":{"from":361,"to":428}} {"id":100004596,"name":"removeSecretReference","signature":"func (e *TokensController) removeSecretReference(saNamespace string, saName string, saUID types.UID, secretName string) error","file":"pkg/controller/serviceaccount/tokens_controller.go","code":"// removeSecretReference updates the given ServiceAccount to remove a reference to the given secretName if needed.\nfunc (e *TokensController) removeSecretReference(saNamespace string, saName string, saUID types.UID, secretName string) error {\n\t// We don't want to update the cache's copy of the service account\n\t// so remove the secret from a freshly retrieved copy of the service account\n\tserviceAccounts := e.client.CoreV1().ServiceAccounts(saNamespace)\n\tserviceAccount, err := serviceAccounts.Get(context.TODO(), saName, metav1.GetOptions{})\n\t// Ignore NotFound errors when attempting to remove a reference\n\tif apierrors.IsNotFound(err) {\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Short-circuit if the UID doesn't match\n\tif len(saUID) \u003e 0 \u0026\u0026 saUID != serviceAccount.UID {\n\t\treturn nil\n\t}\n\n\t// Short-circuit if the secret is no longer referenced\n\tif !getSecretReferences(serviceAccount).Has(secretName) {\n\t\treturn nil\n\t}\n\n\t// Remove the secret\n\tsecrets := []v1.ObjectReference{}\n\tfor _, s := range serviceAccount.Secrets {\n\t\tif s.Name != secretName {\n\t\t\tsecrets = append(secrets, s)\n\t\t}\n\t}\n\tserviceAccount.Secrets = secrets\n\t_, err = serviceAccounts.Update(context.TODO(), serviceAccount, metav1.UpdateOptions{})\n\t// Ignore NotFound errors when attempting to remove a reference\n\tif apierrors.IsNotFound(err) {\n\t\treturn nil\n\t}\n\treturn err\n}","line":{"from":430,"to":468}} {"id":100004597,"name":"getServiceAccount","signature":"func (e *TokensController) getServiceAccount(ns string, name string, uid types.UID, fetchOnCacheMiss bool) (*v1.ServiceAccount, error)","file":"pkg/controller/serviceaccount/tokens_controller.go","code":"func (e *TokensController) getServiceAccount(ns string, name string, uid types.UID, fetchOnCacheMiss bool) (*v1.ServiceAccount, error) {\n\t// Look up in cache\n\tsa, err := e.serviceAccounts.ServiceAccounts(ns).Get(name)\n\tif err != nil \u0026\u0026 !apierrors.IsNotFound(err) {\n\t\treturn nil, err\n\t}\n\tif sa != nil {\n\t\t// Ensure UID matches if given\n\t\tif len(uid) == 0 || uid == sa.UID {\n\t\t\treturn sa, nil\n\t\t}\n\t}\n\n\tif !fetchOnCacheMiss {\n\t\treturn nil, nil\n\t}\n\n\t// Live lookup\n\tsa, err = e.client.CoreV1().ServiceAccounts(ns).Get(context.TODO(), name, metav1.GetOptions{})\n\tif apierrors.IsNotFound(err) {\n\t\treturn nil, nil\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Ensure UID matches if given\n\tif len(uid) == 0 || uid == sa.UID {\n\t\treturn sa, nil\n\t}\n\treturn nil, nil\n}","line":{"from":470,"to":500}} {"id":100004598,"name":"getSecret","signature":"func (e *TokensController) getSecret(ns string, name string, uid types.UID, fetchOnCacheMiss bool) (*v1.Secret, error)","file":"pkg/controller/serviceaccount/tokens_controller.go","code":"func (e *TokensController) getSecret(ns string, name string, uid types.UID, fetchOnCacheMiss bool) (*v1.Secret, error) {\n\t// Look up in cache\n\tobj, exists, err := e.updatedSecrets.GetByKey(makeCacheKey(ns, name))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif exists {\n\t\tsecret, ok := obj.(*v1.Secret)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"expected *v1.Secret, got %#v\", secret)\n\t\t}\n\t\t// Ensure UID matches if given\n\t\tif len(uid) == 0 || uid == secret.UID {\n\t\t\treturn secret, nil\n\t\t}\n\t}\n\n\tif !fetchOnCacheMiss {\n\t\treturn nil, nil\n\t}\n\n\t// Live lookup\n\tsecret, err := e.client.CoreV1().Secrets(ns).Get(context.TODO(), name, metav1.GetOptions{})\n\tif apierrors.IsNotFound(err) {\n\t\treturn nil, nil\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Ensure UID matches if given\n\tif len(uid) == 0 || uid == secret.UID {\n\t\treturn secret, nil\n\t}\n\treturn nil, nil\n}","line":{"from":502,"to":536}} {"id":100004599,"name":"listTokenSecrets","signature":"func (e *TokensController) listTokenSecrets(serviceAccount *v1.ServiceAccount) ([]*v1.Secret, error)","file":"pkg/controller/serviceaccount/tokens_controller.go","code":"// listTokenSecrets returns a list of all of the ServiceAccountToken secrets that\n// reference the given service account's name and uid\nfunc (e *TokensController) listTokenSecrets(serviceAccount *v1.ServiceAccount) ([]*v1.Secret, error) {\n\tnamespaceSecrets, err := e.updatedSecrets.ByIndex(\"namespace\", serviceAccount.Namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\titems := []*v1.Secret{}\n\tfor _, obj := range namespaceSecrets {\n\t\tsecret := obj.(*v1.Secret)\n\n\t\tif apiserverserviceaccount.IsServiceAccountToken(secret, serviceAccount) {\n\t\t\titems = append(items, secret)\n\t\t}\n\t}\n\treturn items, nil\n}","line":{"from":538,"to":555}} {"id":100004600,"name":"getSecretReferences","signature":"func getSecretReferences(serviceAccount *v1.ServiceAccount) sets.String","file":"pkg/controller/serviceaccount/tokens_controller.go","code":"func getSecretReferences(serviceAccount *v1.ServiceAccount) sets.String {\n\treferences := sets.NewString()\n\tfor _, secret := range serviceAccount.Secrets {\n\t\treferences.Insert(secret.Name)\n\t}\n\treturn references\n}","line":{"from":557,"to":563}} {"id":100004601,"name":"makeServiceAccountKey","signature":"func makeServiceAccountKey(sa *v1.ServiceAccount) interface{}","file":"pkg/controller/serviceaccount/tokens_controller.go","code":"func makeServiceAccountKey(sa *v1.ServiceAccount) interface{} {\n\treturn serviceAccountQueueKey{\n\t\tnamespace: sa.Namespace,\n\t\tname: sa.Name,\n\t\tuid: sa.UID,\n\t}\n}","line":{"from":574,"to":580}} {"id":100004602,"name":"parseServiceAccountKey","signature":"func parseServiceAccountKey(key interface{}) (serviceAccountQueueKey, error)","file":"pkg/controller/serviceaccount/tokens_controller.go","code":"func parseServiceAccountKey(key interface{}) (serviceAccountQueueKey, error) {\n\tqueueKey, ok := key.(serviceAccountQueueKey)\n\tif !ok || len(queueKey.namespace) == 0 || len(queueKey.name) == 0 || len(queueKey.uid) == 0 {\n\t\treturn serviceAccountQueueKey{}, fmt.Errorf(\"invalid serviceaccount key: %#v\", key)\n\t}\n\treturn queueKey, nil\n}","line":{"from":582,"to":588}} {"id":100004603,"name":"makeSecretQueueKey","signature":"func makeSecretQueueKey(secret *v1.Secret) interface{}","file":"pkg/controller/serviceaccount/tokens_controller.go","code":"func makeSecretQueueKey(secret *v1.Secret) interface{} {\n\treturn secretQueueKey{\n\t\tnamespace: secret.Namespace,\n\t\tname: secret.Name,\n\t\tuid: secret.UID,\n\t\tsaName: secret.Annotations[v1.ServiceAccountNameKey],\n\t\tsaUID: types.UID(secret.Annotations[v1.ServiceAccountUIDKey]),\n\t}\n}","line":{"from":602,"to":610}} {"id":100004604,"name":"parseSecretQueueKey","signature":"func parseSecretQueueKey(key interface{}) (secretQueueKey, error)","file":"pkg/controller/serviceaccount/tokens_controller.go","code":"func parseSecretQueueKey(key interface{}) (secretQueueKey, error) {\n\tqueueKey, ok := key.(secretQueueKey)\n\tif !ok || len(queueKey.namespace) == 0 || len(queueKey.name) == 0 || len(queueKey.uid) == 0 || len(queueKey.saName) == 0 {\n\t\treturn secretQueueKey{}, fmt.Errorf(\"invalid secret key: %#v\", key)\n\t}\n\treturn queueKey, nil\n}","line":{"from":612,"to":618}} {"id":100004605,"name":"makeCacheKey","signature":"func makeCacheKey(namespace, name string) string","file":"pkg/controller/serviceaccount/tokens_controller.go","code":"// produce the same key format as cache.MetaNamespaceKeyFunc\nfunc makeCacheKey(namespace, name string) string {\n\treturn namespace + \"/\" + name\n}","line":{"from":620,"to":623}} {"id":100004606,"name":"Convert_v1alpha1_StatefulSetControllerConfiguration_To_config_StatefulSetControllerConfiguration","signature":"func Convert_v1alpha1_StatefulSetControllerConfiguration_To_config_StatefulSetControllerConfiguration(in *v1alpha1.StatefulSetControllerConfiguration, out *statefulsetconfig.StatefulSetControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/statefulset/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_StatefulSetControllerConfiguration_To_config_StatefulSetControllerConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_StatefulSetControllerConfiguration_To_config_StatefulSetControllerConfiguration(in *v1alpha1.StatefulSetControllerConfiguration, out *statefulsetconfig.StatefulSetControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_StatefulSetControllerConfiguration_To_config_StatefulSetControllerConfiguration(in, out, s)\n}","line":{"from":32,"to":35}} {"id":100004607,"name":"Convert_config_StatefulSetControllerConfiguration_To_v1alpha1_StatefulSetControllerConfiguration","signature":"func Convert_config_StatefulSetControllerConfiguration_To_v1alpha1_StatefulSetControllerConfiguration(in *statefulsetconfig.StatefulSetControllerConfiguration, out *v1alpha1.StatefulSetControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/statefulset/config/v1alpha1/conversion.go","code":"// Convert_config_StatefulSetControllerConfiguration_To_v1alpha1_StatefulSetControllerConfiguration is an autogenerated conversion function.\nfunc Convert_config_StatefulSetControllerConfiguration_To_v1alpha1_StatefulSetControllerConfiguration(in *statefulsetconfig.StatefulSetControllerConfiguration, out *v1alpha1.StatefulSetControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_StatefulSetControllerConfiguration_To_v1alpha1_StatefulSetControllerConfiguration(in, out, s)\n}","line":{"from":37,"to":40}} {"id":100004608,"name":"RecommendedDefaultStatefulSetControllerConfiguration","signature":"func RecommendedDefaultStatefulSetControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.StatefulSetControllerConfiguration)","file":"pkg/controller/statefulset/config/v1alpha1/defaults.go","code":"// RecommendedDefaultStatefulSetControllerConfiguration defaults a pointer to a\n// StatefulSetControllerConfiguration struct. This will set the recommended default\n// values, but they may be subject to change between API versions. This function\n// is intentionally not registered in the scheme as a \"normal\" `SetDefaults_Foo`\n// function to allow consumers of this type to set whatever defaults for their\n// embedded configs. Forcing consumers to use these defaults would be problematic\n// as defaulting in the scheme is done as part of the conversion, and there would\n// be no easy way to opt-out. Instead, if you want to use this defaulting method\n// run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDefaultStatefulSetControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.StatefulSetControllerConfiguration) {\n\tif obj.ConcurrentStatefulSetSyncs == 0 {\n\t\tobj.ConcurrentStatefulSetSyncs = 5\n\t}\n}","line":{"from":23,"to":36}} {"id":100004609,"name":"NewStatefulPodControl","signature":"func NewStatefulPodControl(","file":"pkg/controller/statefulset/stateful_pod_control.go","code":"// NewStatefulPodControl constructs a StatefulPodControl using a realStatefulPodControlObjectManager with the given\n// clientset, listers and EventRecorder.\nfunc NewStatefulPodControl(\n\tclient clientset.Interface,\n\tpodLister corelisters.PodLister,\n\tclaimLister corelisters.PersistentVolumeClaimLister,\n\trecorder record.EventRecorder,\n) *StatefulPodControl {\n\treturn \u0026StatefulPodControl{\u0026realStatefulPodControlObjectManager{client, podLister, claimLister}, recorder}\n}","line":{"from":60,"to":69}} {"id":100004610,"name":"NewStatefulPodControlFromManager","signature":"func NewStatefulPodControlFromManager(om StatefulPodControlObjectManager, recorder record.EventRecorder) *StatefulPodControl","file":"pkg/controller/statefulset/stateful_pod_control.go","code":"// NewStatefulPodControlFromManager creates a StatefulPodControl using the given StatefulPodControlObjectManager and recorder.\nfunc NewStatefulPodControlFromManager(om StatefulPodControlObjectManager, recorder record.EventRecorder) *StatefulPodControl {\n\treturn \u0026StatefulPodControl{om, recorder}\n}","line":{"from":71,"to":74}} {"id":100004611,"name":"CreatePod","signature":"func (om *realStatefulPodControlObjectManager) CreatePod(ctx context.Context, pod *v1.Pod) error","file":"pkg/controller/statefulset/stateful_pod_control.go","code":"func (om *realStatefulPodControlObjectManager) CreatePod(ctx context.Context, pod *v1.Pod) error {\n\t_, err := om.client.CoreV1().Pods(pod.Namespace).Create(ctx, pod, metav1.CreateOptions{})\n\treturn err\n}","line":{"from":83,"to":86}} {"id":100004612,"name":"GetPod","signature":"func (om *realStatefulPodControlObjectManager) GetPod(namespace, podName string) (*v1.Pod, error)","file":"pkg/controller/statefulset/stateful_pod_control.go","code":"func (om *realStatefulPodControlObjectManager) GetPod(namespace, podName string) (*v1.Pod, error) {\n\treturn om.podLister.Pods(namespace).Get(podName)\n}","line":{"from":88,"to":90}} {"id":100004613,"name":"UpdatePod","signature":"func (om *realStatefulPodControlObjectManager) UpdatePod(pod *v1.Pod) error","file":"pkg/controller/statefulset/stateful_pod_control.go","code":"func (om *realStatefulPodControlObjectManager) UpdatePod(pod *v1.Pod) error {\n\t_, err := om.client.CoreV1().Pods(pod.Namespace).Update(context.TODO(), pod, metav1.UpdateOptions{})\n\treturn err\n}","line":{"from":92,"to":95}} {"id":100004614,"name":"DeletePod","signature":"func (om *realStatefulPodControlObjectManager) DeletePod(pod *v1.Pod) error","file":"pkg/controller/statefulset/stateful_pod_control.go","code":"func (om *realStatefulPodControlObjectManager) DeletePod(pod *v1.Pod) error {\n\treturn om.client.CoreV1().Pods(pod.Namespace).Delete(context.TODO(), pod.Name, metav1.DeleteOptions{})\n}","line":{"from":97,"to":99}} {"id":100004615,"name":"CreateClaim","signature":"func (om *realStatefulPodControlObjectManager) CreateClaim(claim *v1.PersistentVolumeClaim) error","file":"pkg/controller/statefulset/stateful_pod_control.go","code":"func (om *realStatefulPodControlObjectManager) CreateClaim(claim *v1.PersistentVolumeClaim) error {\n\t_, err := om.client.CoreV1().PersistentVolumeClaims(claim.Namespace).Create(context.TODO(), claim, metav1.CreateOptions{})\n\treturn err\n}","line":{"from":101,"to":104}} {"id":100004616,"name":"GetClaim","signature":"func (om *realStatefulPodControlObjectManager) GetClaim(namespace, claimName string) (*v1.PersistentVolumeClaim, error)","file":"pkg/controller/statefulset/stateful_pod_control.go","code":"func (om *realStatefulPodControlObjectManager) GetClaim(namespace, claimName string) (*v1.PersistentVolumeClaim, error) {\n\treturn om.claimLister.PersistentVolumeClaims(namespace).Get(claimName)\n}","line":{"from":106,"to":108}} {"id":100004617,"name":"UpdateClaim","signature":"func (om *realStatefulPodControlObjectManager) UpdateClaim(claim *v1.PersistentVolumeClaim) error","file":"pkg/controller/statefulset/stateful_pod_control.go","code":"func (om *realStatefulPodControlObjectManager) UpdateClaim(claim *v1.PersistentVolumeClaim) error {\n\t_, err := om.client.CoreV1().PersistentVolumeClaims(claim.Namespace).Update(context.TODO(), claim, metav1.UpdateOptions{})\n\treturn err\n}","line":{"from":110,"to":113}} {"id":100004618,"name":"CreateStatefulPod","signature":"func (spc *StatefulPodControl) CreateStatefulPod(ctx context.Context, set *apps.StatefulSet, pod *v1.Pod) error","file":"pkg/controller/statefulset/stateful_pod_control.go","code":"func (spc *StatefulPodControl) CreateStatefulPod(ctx context.Context, set *apps.StatefulSet, pod *v1.Pod) error {\n\t// Create the Pod's PVCs prior to creating the Pod\n\tif err := spc.createPersistentVolumeClaims(set, pod); err != nil {\n\t\tspc.recordPodEvent(\"create\", set, pod, err)\n\t\treturn err\n\t}\n\t// If we created the PVCs attempt to create the Pod\n\terr := spc.objectMgr.CreatePod(ctx, pod)\n\t// sink already exists errors\n\tif apierrors.IsAlreadyExists(err) {\n\t\treturn err\n\t}\n\tif utilfeature.DefaultFeatureGate.Enabled(features.StatefulSetAutoDeletePVC) {\n\t\t// Set PVC policy as much as is possible at this point.\n\t\tif err := spc.UpdatePodClaimForRetentionPolicy(ctx, set, pod); err != nil {\n\t\t\tspc.recordPodEvent(\"update\", set, pod, err)\n\t\t\treturn err\n\t\t}\n\t}\n\tspc.recordPodEvent(\"create\", set, pod, err)\n\treturn err\n}","line":{"from":115,"to":136}} {"id":100004619,"name":"UpdateStatefulPod","signature":"func (spc *StatefulPodControl) UpdateStatefulPod(ctx context.Context, set *apps.StatefulSet, pod *v1.Pod) error","file":"pkg/controller/statefulset/stateful_pod_control.go","code":"func (spc *StatefulPodControl) UpdateStatefulPod(ctx context.Context, set *apps.StatefulSet, pod *v1.Pod) error {\n\tattemptedUpdate := false\n\terr := retry.RetryOnConflict(retry.DefaultBackoff, func() error {\n\t\t// assume the Pod is consistent\n\t\tconsistent := true\n\t\t// if the Pod does not conform to its identity, update the identity and dirty the Pod\n\t\tif !identityMatches(set, pod) {\n\t\t\tupdateIdentity(set, pod)\n\t\t\tconsistent = false\n\t\t}\n\t\t// if the Pod does not conform to the StatefulSet's storage requirements, update the Pod's PVC's,\n\t\t// dirty the Pod, and create any missing PVCs\n\t\tif !storageMatches(set, pod) {\n\t\t\tupdateStorage(set, pod)\n\t\t\tconsistent = false\n\t\t\tif err := spc.createPersistentVolumeClaims(set, pod); err != nil {\n\t\t\t\tspc.recordPodEvent(\"update\", set, pod, err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.StatefulSetAutoDeletePVC) {\n\t\t\t// if the Pod's PVCs are not consistent with the StatefulSet's PVC deletion policy, update the PVC\n\t\t\t// and dirty the pod.\n\t\t\tif match, err := spc.ClaimsMatchRetentionPolicy(ctx, set, pod); err != nil {\n\t\t\t\tspc.recordPodEvent(\"update\", set, pod, err)\n\t\t\t\treturn err\n\t\t\t} else if !match {\n\t\t\t\tif err := spc.UpdatePodClaimForRetentionPolicy(ctx, set, pod); err != nil {\n\t\t\t\t\tspc.recordPodEvent(\"update\", set, pod, err)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tconsistent = false\n\t\t\t}\n\t\t}\n\n\t\t// if the Pod is not dirty, do nothing\n\t\tif consistent {\n\t\t\treturn nil\n\t\t}\n\n\t\tattemptedUpdate = true\n\t\t// commit the update, retrying on conflicts\n\n\t\tupdateErr := spc.objectMgr.UpdatePod(pod)\n\t\tif updateErr == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tif updated, err := spc.objectMgr.GetPod(set.Namespace, pod.Name); err == nil {\n\t\t\t// make a copy so we don't mutate the shared cache\n\t\t\tpod = updated.DeepCopy()\n\t\t} else {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"error getting updated Pod %s/%s: %w\", set.Namespace, pod.Name, err))\n\t\t}\n\n\t\treturn updateErr\n\t})\n\tif attemptedUpdate {\n\t\tspc.recordPodEvent(\"update\", set, pod, err)\n\t}\n\treturn err\n}","line":{"from":138,"to":199}} {"id":100004620,"name":"DeleteStatefulPod","signature":"func (spc *StatefulPodControl) DeleteStatefulPod(set *apps.StatefulSet, pod *v1.Pod) error","file":"pkg/controller/statefulset/stateful_pod_control.go","code":"func (spc *StatefulPodControl) DeleteStatefulPod(set *apps.StatefulSet, pod *v1.Pod) error {\n\terr := spc.objectMgr.DeletePod(pod)\n\tspc.recordPodEvent(\"delete\", set, pod, err)\n\treturn err\n}","line":{"from":201,"to":205}} {"id":100004621,"name":"ClaimsMatchRetentionPolicy","signature":"func (spc *StatefulPodControl) ClaimsMatchRetentionPolicy(ctx context.Context, set *apps.StatefulSet, pod *v1.Pod) (bool, error)","file":"pkg/controller/statefulset/stateful_pod_control.go","code":"// ClaimsMatchRetentionPolicy returns false if the PVCs for pod are not consistent with set's PVC deletion policy.\n// An error is returned if something is not consistent. This is expected if the pod is being otherwise updated,\n// but a problem otherwise (see usage of this method in UpdateStatefulPod).\nfunc (spc *StatefulPodControl) ClaimsMatchRetentionPolicy(ctx context.Context, set *apps.StatefulSet, pod *v1.Pod) (bool, error) {\n\tordinal := getOrdinal(pod)\n\ttemplates := set.Spec.VolumeClaimTemplates\n\tfor i := range templates {\n\t\tclaimName := getPersistentVolumeClaimName(set, \u0026templates[i], ordinal)\n\t\tclaim, err := spc.objectMgr.GetClaim(set.Namespace, claimName)\n\t\tswitch {\n\t\tcase apierrors.IsNotFound(err):\n\t\t\tklog.FromContext(ctx).V(4).Info(\"Expected claim missing, continuing to pick up in next iteration\", \"PVC\", klog.KObj(claim))\n\t\tcase err != nil:\n\t\t\treturn false, fmt.Errorf(\"Could not retrieve claim %s for %s when checking PVC deletion policy\", claimName, pod.Name)\n\t\tdefault:\n\t\t\tif !claimOwnerMatchesSetAndPod(claim, set, pod) {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn true, nil\n}","line":{"from":207,"to":228}} {"id":100004622,"name":"UpdatePodClaimForRetentionPolicy","signature":"func (spc *StatefulPodControl) UpdatePodClaimForRetentionPolicy(ctx context.Context, set *apps.StatefulSet, pod *v1.Pod) error","file":"pkg/controller/statefulset/stateful_pod_control.go","code":"// UpdatePodClaimForRetentionPolicy updates the PVCs used by pod to match the PVC deletion policy of set.\nfunc (spc *StatefulPodControl) UpdatePodClaimForRetentionPolicy(ctx context.Context, set *apps.StatefulSet, pod *v1.Pod) error {\n\tlogger := klog.FromContext(ctx)\n\tordinal := getOrdinal(pod)\n\ttemplates := set.Spec.VolumeClaimTemplates\n\tfor i := range templates {\n\t\tclaimName := getPersistentVolumeClaimName(set, \u0026templates[i], ordinal)\n\t\tclaim, err := spc.objectMgr.GetClaim(set.Namespace, claimName)\n\t\tswitch {\n\t\tcase apierrors.IsNotFound(err):\n\t\t\tlogger.V(4).Info(\"Expected claim missing, continuing to pick up in next iteration\", \"PVC\", klog.KObj(claim))\n\t\tcase err != nil:\n\t\t\treturn fmt.Errorf(\"Could not retrieve claim %s not found for %s when checking PVC deletion policy: %w\", claimName, pod.Name, err)\n\t\tdefault:\n\t\t\tif !claimOwnerMatchesSetAndPod(claim, set, pod) {\n\t\t\t\tclaim = claim.DeepCopy() // Make a copy so we don't mutate the shared cache.\n\t\t\t\tneedsUpdate := updateClaimOwnerRefForSetAndPod(claim, set, pod)\n\t\t\t\tif needsUpdate {\n\t\t\t\t\terr := spc.objectMgr.UpdateClaim(claim)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn fmt.Errorf(\"Could not update claim %s for delete policy ownerRefs: %w\", claimName, err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":230,"to":257}} {"id":100004623,"name":"PodClaimIsStale","signature":"func (spc *StatefulPodControl) PodClaimIsStale(set *apps.StatefulSet, pod *v1.Pod) (bool, error)","file":"pkg/controller/statefulset/stateful_pod_control.go","code":"// PodClaimIsStale returns true for a stale PVC that should block pod creation. If the scaling\n// policy is deletion, and a PVC has an ownerRef that does not match the pod, the PVC is stale. This\n// includes pods whose UID has not been created.\nfunc (spc *StatefulPodControl) PodClaimIsStale(set *apps.StatefulSet, pod *v1.Pod) (bool, error) {\n\tpolicy := getPersistentVolumeClaimRetentionPolicy(set)\n\tif policy.WhenScaled == apps.RetainPersistentVolumeClaimRetentionPolicyType {\n\t\t// PVCs are meant to be reused and so can't be stale.\n\t\treturn false, nil\n\t}\n\tfor _, claim := range getPersistentVolumeClaims(set, pod) {\n\t\tpvc, err := spc.objectMgr.GetClaim(claim.Namespace, claim.Name)\n\t\tswitch {\n\t\tcase apierrors.IsNotFound(err):\n\t\t\t// If the claim doesn't exist yet, it can't be stale.\n\t\t\tcontinue\n\t\tcase err != nil:\n\t\t\treturn false, err\n\t\tcase err == nil:\n\t\t\t// A claim is stale if it doesn't match the pod's UID, including if the pod has no UID.\n\t\t\tif hasStaleOwnerRef(pvc, pod) {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn false, nil\n}","line":{"from":259,"to":284}} {"id":100004624,"name":"recordPodEvent","signature":"func (spc *StatefulPodControl) recordPodEvent(verb string, set *apps.StatefulSet, pod *v1.Pod, err error)","file":"pkg/controller/statefulset/stateful_pod_control.go","code":"// recordPodEvent records an event for verb applied to a Pod in a StatefulSet. If err is nil the generated event will\n// have a reason of v1.EventTypeNormal. If err is not nil the generated event will have a reason of v1.EventTypeWarning.\nfunc (spc *StatefulPodControl) recordPodEvent(verb string, set *apps.StatefulSet, pod *v1.Pod, err error) {\n\tif err == nil {\n\t\treason := fmt.Sprintf(\"Successful%s\", strings.Title(verb))\n\t\tmessage := fmt.Sprintf(\"%s Pod %s in StatefulSet %s successful\",\n\t\t\tstrings.ToLower(verb), pod.Name, set.Name)\n\t\tspc.recorder.Event(set, v1.EventTypeNormal, reason, message)\n\t} else {\n\t\treason := fmt.Sprintf(\"Failed%s\", strings.Title(verb))\n\t\tmessage := fmt.Sprintf(\"%s Pod %s in StatefulSet %s failed error: %s\",\n\t\t\tstrings.ToLower(verb), pod.Name, set.Name, err)\n\t\tspc.recorder.Event(set, v1.EventTypeWarning, reason, message)\n\t}\n}","line":{"from":286,"to":300}} {"id":100004625,"name":"recordClaimEvent","signature":"func (spc *StatefulPodControl) recordClaimEvent(verb string, set *apps.StatefulSet, pod *v1.Pod, claim *v1.PersistentVolumeClaim, err error)","file":"pkg/controller/statefulset/stateful_pod_control.go","code":"// recordClaimEvent records an event for verb applied to the PersistentVolumeClaim of a Pod in a StatefulSet. If err is\n// nil the generated event will have a reason of v1.EventTypeNormal. If err is not nil the generated event will have a\n// reason of v1.EventTypeWarning.\nfunc (spc *StatefulPodControl) recordClaimEvent(verb string, set *apps.StatefulSet, pod *v1.Pod, claim *v1.PersistentVolumeClaim, err error) {\n\tif err == nil {\n\t\treason := fmt.Sprintf(\"Successful%s\", strings.Title(verb))\n\t\tmessage := fmt.Sprintf(\"%s Claim %s Pod %s in StatefulSet %s success\",\n\t\t\tstrings.ToLower(verb), claim.Name, pod.Name, set.Name)\n\t\tspc.recorder.Event(set, v1.EventTypeNormal, reason, message)\n\t} else {\n\t\treason := fmt.Sprintf(\"Failed%s\", strings.Title(verb))\n\t\tmessage := fmt.Sprintf(\"%s Claim %s for Pod %s in StatefulSet %s failed error: %s\",\n\t\t\tstrings.ToLower(verb), claim.Name, pod.Name, set.Name, err)\n\t\tspc.recorder.Event(set, v1.EventTypeWarning, reason, message)\n\t}\n}","line":{"from":302,"to":317}} {"id":100004626,"name":"createMissingPersistentVolumeClaims","signature":"func (spc *StatefulPodControl) createMissingPersistentVolumeClaims(ctx context.Context, set *apps.StatefulSet, pod *v1.Pod) error","file":"pkg/controller/statefulset/stateful_pod_control.go","code":"// createMissingPersistentVolumeClaims creates all of the required PersistentVolumeClaims for pod, and updates its retention policy\nfunc (spc *StatefulPodControl) createMissingPersistentVolumeClaims(ctx context.Context, set *apps.StatefulSet, pod *v1.Pod) error {\n\tif err := spc.createPersistentVolumeClaims(set, pod); err != nil {\n\t\treturn err\n\t}\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.StatefulSetAutoDeletePVC) {\n\t\t// Set PVC policy as much as is possible at this point.\n\t\tif err := spc.UpdatePodClaimForRetentionPolicy(ctx, set, pod); err != nil {\n\t\t\tspc.recordPodEvent(\"update\", set, pod, err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":319,"to":333}} {"id":100004627,"name":"createPersistentVolumeClaims","signature":"func (spc *StatefulPodControl) createPersistentVolumeClaims(set *apps.StatefulSet, pod *v1.Pod) error","file":"pkg/controller/statefulset/stateful_pod_control.go","code":"// createPersistentVolumeClaims creates all of the required PersistentVolumeClaims for pod, which must be a member of\n// set. If all of the claims for Pod are successfully created, the returned error is nil. If creation fails, this method\n// may be called again until no error is returned, indicating the PersistentVolumeClaims for pod are consistent with\n// set's Spec.\nfunc (spc *StatefulPodControl) createPersistentVolumeClaims(set *apps.StatefulSet, pod *v1.Pod) error {\n\tvar errs []error\n\tfor _, claim := range getPersistentVolumeClaims(set, pod) {\n\t\tpvc, err := spc.objectMgr.GetClaim(claim.Namespace, claim.Name)\n\t\tswitch {\n\t\tcase apierrors.IsNotFound(err):\n\t\t\terr := spc.objectMgr.CreateClaim(\u0026claim)\n\t\t\tif err != nil {\n\t\t\t\terrs = append(errs, fmt.Errorf(\"failed to create PVC %s: %s\", claim.Name, err))\n\t\t\t}\n\t\t\tif err == nil || !apierrors.IsAlreadyExists(err) {\n\t\t\t\tspc.recordClaimEvent(\"create\", set, pod, \u0026claim, err)\n\t\t\t}\n\t\tcase err != nil:\n\t\t\terrs = append(errs, fmt.Errorf(\"failed to retrieve PVC %s: %s\", claim.Name, err))\n\t\t\tspc.recordClaimEvent(\"create\", set, pod, \u0026claim, err)\n\t\tdefault:\n\t\t\tif pvc.DeletionTimestamp != nil {\n\t\t\t\terrs = append(errs, fmt.Errorf(\"pvc %s is being deleted\", claim.Name))\n\t\t\t}\n\t\t}\n\t\t// TODO: Check resource requirements and accessmodes, update if necessary\n\t}\n\treturn errorutils.NewAggregate(errs)\n}","line":{"from":335,"to":363}} {"id":100004628,"name":"NewStatefulSetController","signature":"func NewStatefulSetController(","file":"pkg/controller/statefulset/stateful_set.go","code":"// NewStatefulSetController creates a new statefulset controller.\nfunc NewStatefulSetController(\n\tctx context.Context,\n\tpodInformer coreinformers.PodInformer,\n\tsetInformer appsinformers.StatefulSetInformer,\n\tpvcInformer coreinformers.PersistentVolumeClaimInformer,\n\trevInformer appsinformers.ControllerRevisionInformer,\n\tkubeClient clientset.Interface,\n) *StatefulSetController {\n\tlogger := klog.FromContext(ctx)\n\teventBroadcaster := record.NewBroadcaster()\n\trecorder := eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"statefulset-controller\"})\n\tssc := \u0026StatefulSetController{\n\t\tkubeClient: kubeClient,\n\t\tcontrol: NewDefaultStatefulSetControl(\n\t\t\tNewStatefulPodControl(\n\t\t\t\tkubeClient,\n\t\t\t\tpodInformer.Lister(),\n\t\t\t\tpvcInformer.Lister(),\n\t\t\t\trecorder),\n\t\t\tNewRealStatefulSetStatusUpdater(kubeClient, setInformer.Lister()),\n\t\t\thistory.NewHistory(kubeClient, revInformer.Lister()),\n\t\t\trecorder,\n\t\t),\n\t\tpvcListerSynced: pvcInformer.Informer().HasSynced,\n\t\trevListerSynced: revInformer.Informer().HasSynced,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"statefulset\"),\n\t\tpodControl: controller.RealPodControl{KubeClient: kubeClient, Recorder: recorder},\n\n\t\teventBroadcaster: eventBroadcaster,\n\t}\n\n\tpodInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\t// lookup the statefulset and enqueue\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tssc.addPod(logger, obj)\n\t\t},\n\t\t// lookup current and old statefulset if labels changed\n\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\tssc.updatePod(logger, oldObj, newObj)\n\t\t},\n\t\t// lookup statefulset accounting for deletion tombstones\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tssc.deletePod(logger, obj)\n\t\t},\n\t})\n\tssc.podLister = podInformer.Lister()\n\tssc.podListerSynced = podInformer.Informer().HasSynced\n\n\tsetInformer.Informer().AddEventHandler(\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: ssc.enqueueStatefulSet,\n\t\t\tUpdateFunc: func(old, cur interface{}) {\n\t\t\t\toldPS := old.(*apps.StatefulSet)\n\t\t\t\tcurPS := cur.(*apps.StatefulSet)\n\t\t\t\tif oldPS.Status.Replicas != curPS.Status.Replicas {\n\t\t\t\t\tlogger.V(4).Info(\"Observed updated replica count for StatefulSet\", \"statefulSet\", klog.KObj(curPS), \"oldReplicas\", oldPS.Status.Replicas, \"newReplicas\", curPS.Status.Replicas)\n\t\t\t\t}\n\t\t\t\tssc.enqueueStatefulSet(cur)\n\t\t\t},\n\t\t\tDeleteFunc: ssc.enqueueStatefulSet,\n\t\t},\n\t)\n\tssc.setLister = setInformer.Lister()\n\tssc.setListerSynced = setInformer.Informer().HasSynced\n\n\t// TODO: Watch volumes\n\treturn ssc\n}","line":{"from":79,"to":147}} {"id":100004629,"name":"Run","signature":"func (ssc *StatefulSetController) Run(ctx context.Context, workers int)","file":"pkg/controller/statefulset/stateful_set.go","code":"// Run runs the statefulset controller.\nfunc (ssc *StatefulSetController) Run(ctx context.Context, workers int) {\n\tdefer utilruntime.HandleCrash()\n\n\t// Start events processing pipeline.\n\tssc.eventBroadcaster.StartStructuredLogging(0)\n\tssc.eventBroadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: ssc.kubeClient.CoreV1().Events(\"\")})\n\tdefer ssc.eventBroadcaster.Shutdown()\n\n\tdefer ssc.queue.ShutDown()\n\n\tlogger := klog.FromContext(ctx)\n\tlogger.Info(\"Starting stateful set controller\")\n\tdefer logger.Info(\"Shutting down statefulset controller\")\n\n\tif !cache.WaitForNamedCacheSync(\"stateful set\", ctx.Done(), ssc.podListerSynced, ssc.setListerSynced, ssc.pvcListerSynced, ssc.revListerSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.UntilWithContext(ctx, ssc.worker, time.Second)\n\t}\n\n\t\u003c-ctx.Done()\n}","line":{"from":149,"to":173}} {"id":100004630,"name":"addPod","signature":"func (ssc *StatefulSetController) addPod(logger klog.Logger, obj interface{})","file":"pkg/controller/statefulset/stateful_set.go","code":"// addPod adds the statefulset for the pod to the sync queue\nfunc (ssc *StatefulSetController) addPod(logger klog.Logger, obj interface{}) {\n\tpod := obj.(*v1.Pod)\n\n\tif pod.DeletionTimestamp != nil {\n\t\t// on a restart of the controller manager, it's possible a new pod shows up in a state that\n\t\t// is already pending deletion. Prevent the pod from being a creation observation.\n\t\tssc.deletePod(logger, pod)\n\t\treturn\n\t}\n\n\t// If it has a ControllerRef, that's all that matters.\n\tif controllerRef := metav1.GetControllerOf(pod); controllerRef != nil {\n\t\tset := ssc.resolveControllerRef(pod.Namespace, controllerRef)\n\t\tif set == nil {\n\t\t\treturn\n\t\t}\n\t\tlogger.V(4).Info(\"Pod created with labels\", \"pod\", klog.KObj(pod), \"labels\", pod.Labels)\n\t\tssc.enqueueStatefulSet(set)\n\t\treturn\n\t}\n\n\t// Otherwise, it's an orphan. Get a list of all matching controllers and sync\n\t// them to see if anyone wants to adopt it.\n\tsets := ssc.getStatefulSetsForPod(pod)\n\tif len(sets) == 0 {\n\t\treturn\n\t}\n\tlogger.V(4).Info(\"Orphan Pod created with labels\", \"pod\", klog.KObj(pod), \"labels\", pod.Labels)\n\tfor _, set := range sets {\n\t\tssc.enqueueStatefulSet(set)\n\t}\n}","line":{"from":175,"to":207}} {"id":100004631,"name":"updatePod","signature":"func (ssc *StatefulSetController) updatePod(logger klog.Logger, old, cur interface{})","file":"pkg/controller/statefulset/stateful_set.go","code":"// updatePod adds the statefulset for the current and old pods to the sync queue.\nfunc (ssc *StatefulSetController) updatePod(logger klog.Logger, old, cur interface{}) {\n\tcurPod := cur.(*v1.Pod)\n\toldPod := old.(*v1.Pod)\n\tif curPod.ResourceVersion == oldPod.ResourceVersion {\n\t\t// In the event of a re-list we may receive update events for all known pods.\n\t\t// Two different versions of the same pod will always have different RVs.\n\t\treturn\n\t}\n\n\tlabelChanged := !reflect.DeepEqual(curPod.Labels, oldPod.Labels)\n\n\tcurControllerRef := metav1.GetControllerOf(curPod)\n\toldControllerRef := metav1.GetControllerOf(oldPod)\n\tcontrollerRefChanged := !reflect.DeepEqual(curControllerRef, oldControllerRef)\n\tif controllerRefChanged \u0026\u0026 oldControllerRef != nil {\n\t\t// The ControllerRef was changed. Sync the old controller, if any.\n\t\tif set := ssc.resolveControllerRef(oldPod.Namespace, oldControllerRef); set != nil {\n\t\t\tssc.enqueueStatefulSet(set)\n\t\t}\n\t}\n\n\t// If it has a ControllerRef, that's all that matters.\n\tif curControllerRef != nil {\n\t\tset := ssc.resolveControllerRef(curPod.Namespace, curControllerRef)\n\t\tif set == nil {\n\t\t\treturn\n\t\t}\n\t\tlogger.V(4).Info(\"Pod objectMeta updated\", \"pod\", klog.KObj(curPod), \"oldObjectMeta\", oldPod.ObjectMeta, \"newObjectMeta\", curPod.ObjectMeta)\n\t\tssc.enqueueStatefulSet(set)\n\t\t// TODO: MinReadySeconds in the Pod will generate an Available condition to be added in\n\t\t// the Pod status which in turn will trigger a requeue of the owning replica set thus\n\t\t// having its status updated with the newly available replica.\n\t\tif !podutil.IsPodReady(oldPod) \u0026\u0026 podutil.IsPodReady(curPod) \u0026\u0026 set.Spec.MinReadySeconds \u003e 0 {\n\t\t\tlogger.V(2).Info(\"StatefulSet will be enqueued after minReadySeconds for availability check\", \"statefulSet\", klog.KObj(set), \"minReadySeconds\", set.Spec.MinReadySeconds)\n\t\t\t// Add a second to avoid milliseconds skew in AddAfter.\n\t\t\t// See https://github.com/kubernetes/kubernetes/issues/39785#issuecomment-279959133 for more info.\n\t\t\tssc.enqueueSSAfter(set, (time.Duration(set.Spec.MinReadySeconds)*time.Second)+time.Second)\n\t\t}\n\t\treturn\n\t}\n\n\t// Otherwise, it's an orphan. If anything changed, sync matching controllers\n\t// to see if anyone wants to adopt it now.\n\tif labelChanged || controllerRefChanged {\n\t\tsets := ssc.getStatefulSetsForPod(curPod)\n\t\tif len(sets) == 0 {\n\t\t\treturn\n\t\t}\n\t\tlogger.V(4).Info(\"Orphan Pod objectMeta updated\", \"pod\", klog.KObj(curPod), \"oldObjectMeta\", oldPod.ObjectMeta, \"newObjectMeta\", curPod.ObjectMeta)\n\t\tfor _, set := range sets {\n\t\t\tssc.enqueueStatefulSet(set)\n\t\t}\n\t}\n}","line":{"from":209,"to":263}} {"id":100004632,"name":"deletePod","signature":"func (ssc *StatefulSetController) deletePod(logger klog.Logger, obj interface{})","file":"pkg/controller/statefulset/stateful_set.go","code":"// deletePod enqueues the statefulset for the pod accounting for deletion tombstones.\nfunc (ssc *StatefulSetController) deletePod(logger klog.Logger, obj interface{}) {\n\tpod, ok := obj.(*v1.Pod)\n\n\t// When a delete is dropped, the relist will notice a pod in the store not\n\t// in the list, leading to the insertion of a tombstone object which contains\n\t// the deleted key/value. Note that this value might be stale.\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get object from tombstone %+v\", obj))\n\t\t\treturn\n\t\t}\n\t\tpod, ok = tombstone.Obj.(*v1.Pod)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"tombstone contained object that is not a pod %+v\", obj))\n\t\t\treturn\n\t\t}\n\t}\n\n\tcontrollerRef := metav1.GetControllerOf(pod)\n\tif controllerRef == nil {\n\t\t// No controller should care about orphans being deleted.\n\t\treturn\n\t}\n\tset := ssc.resolveControllerRef(pod.Namespace, controllerRef)\n\tif set == nil {\n\t\treturn\n\t}\n\tlogger.V(4).Info(\"Pod deleted.\", \"pod\", klog.KObj(pod), \"caller\", utilruntime.GetCaller())\n\tssc.enqueueStatefulSet(set)\n}","line":{"from":265,"to":296}} {"id":100004633,"name":"getPodsForStatefulSet","signature":"func (ssc *StatefulSetController) getPodsForStatefulSet(ctx context.Context, set *apps.StatefulSet, selector labels.Selector) ([]*v1.Pod, error)","file":"pkg/controller/statefulset/stateful_set.go","code":"// getPodsForStatefulSet returns the Pods that a given StatefulSet should manage.\n// It also reconciles ControllerRef by adopting/orphaning.\n//\n// NOTE: Returned Pods are pointers to objects from the cache.\n// If you need to modify one, you need to copy it first.\nfunc (ssc *StatefulSetController) getPodsForStatefulSet(ctx context.Context, set *apps.StatefulSet, selector labels.Selector) ([]*v1.Pod, error) {\n\t// List all pods to include the pods that don't match the selector anymore but\n\t// has a ControllerRef pointing to this StatefulSet.\n\tpods, err := ssc.podLister.Pods(set.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfilter := func(pod *v1.Pod) bool {\n\t\t// Only claim if it matches our StatefulSet name. Otherwise release/ignore.\n\t\treturn isMemberOf(set, pod)\n\t}\n\n\tcm := controller.NewPodControllerRefManager(ssc.podControl, set, selector, controllerKind, ssc.canAdoptFunc(ctx, set))\n\treturn cm.ClaimPods(ctx, pods, filter)\n}","line":{"from":298,"to":318}} {"id":100004634,"name":"canAdoptFunc","signature":"func (ssc *StatefulSetController) canAdoptFunc(ctx context.Context, set *apps.StatefulSet) func(ctx2 context.Context) error","file":"pkg/controller/statefulset/stateful_set.go","code":"// If any adoptions are attempted, we should first recheck for deletion with\n// an uncached quorum read sometime after listing Pods/ControllerRevisions (see #42639).\nfunc (ssc *StatefulSetController) canAdoptFunc(ctx context.Context, set *apps.StatefulSet) func(ctx2 context.Context) error {\n\treturn controller.RecheckDeletionTimestamp(func(ctx context.Context) (metav1.Object, error) {\n\t\tfresh, err := ssc.kubeClient.AppsV1().StatefulSets(set.Namespace).Get(ctx, set.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif fresh.UID != set.UID {\n\t\t\treturn nil, fmt.Errorf(\"original StatefulSet %v/%v is gone: got uid %v, wanted %v\", set.Namespace, set.Name, fresh.UID, set.UID)\n\t\t}\n\t\treturn fresh, nil\n\t})\n}","line":{"from":320,"to":333}} {"id":100004635,"name":"adoptOrphanRevisions","signature":"func (ssc *StatefulSetController) adoptOrphanRevisions(ctx context.Context, set *apps.StatefulSet) error","file":"pkg/controller/statefulset/stateful_set.go","code":"// adoptOrphanRevisions adopts any orphaned ControllerRevisions matched by set's Selector.\nfunc (ssc *StatefulSetController) adoptOrphanRevisions(ctx context.Context, set *apps.StatefulSet) error {\n\trevisions, err := ssc.control.ListRevisions(set)\n\tif err != nil {\n\t\treturn err\n\t}\n\torphanRevisions := make([]*apps.ControllerRevision, 0)\n\tfor i := range revisions {\n\t\tif metav1.GetControllerOf(revisions[i]) == nil {\n\t\t\torphanRevisions = append(orphanRevisions, revisions[i])\n\t\t}\n\t}\n\tif len(orphanRevisions) \u003e 0 {\n\t\tcanAdoptErr := ssc.canAdoptFunc(ctx, set)(ctx)\n\t\tif canAdoptErr != nil {\n\t\t\treturn fmt.Errorf(\"can't adopt ControllerRevisions: %v\", canAdoptErr)\n\t\t}\n\t\treturn ssc.control.AdoptOrphanRevisions(set, orphanRevisions)\n\t}\n\treturn nil\n}","line":{"from":335,"to":355}} {"id":100004636,"name":"getStatefulSetsForPod","signature":"func (ssc *StatefulSetController) getStatefulSetsForPod(pod *v1.Pod) []*apps.StatefulSet","file":"pkg/controller/statefulset/stateful_set.go","code":"// getStatefulSetsForPod returns a list of StatefulSets that potentially match\n// a given pod.\nfunc (ssc *StatefulSetController) getStatefulSetsForPod(pod *v1.Pod) []*apps.StatefulSet {\n\tsets, err := ssc.setLister.GetPodStatefulSets(pod)\n\tif err != nil {\n\t\treturn nil\n\t}\n\t// More than one set is selecting the same Pod\n\tif len(sets) \u003e 1 {\n\t\t// ControllerRef will ensure we don't do anything crazy, but more than one\n\t\t// item in this list nevertheless constitutes user error.\n\t\tsetNames := []string{}\n\t\tfor _, s := range sets {\n\t\t\tsetNames = append(setNames, s.Name)\n\t\t}\n\t\tutilruntime.HandleError(\n\t\t\tfmt.Errorf(\n\t\t\t\t\"user error: more than one StatefulSet is selecting pods with labels: %+v. Sets: %v\",\n\t\t\t\tpod.Labels, setNames))\n\t}\n\treturn sets\n}","line":{"from":357,"to":378}} {"id":100004637,"name":"resolveControllerRef","signature":"func (ssc *StatefulSetController) resolveControllerRef(namespace string, controllerRef *metav1.OwnerReference) *apps.StatefulSet","file":"pkg/controller/statefulset/stateful_set.go","code":"// resolveControllerRef returns the controller referenced by a ControllerRef,\n// or nil if the ControllerRef could not be resolved to a matching controller\n// of the correct Kind.\nfunc (ssc *StatefulSetController) resolveControllerRef(namespace string, controllerRef *metav1.OwnerReference) *apps.StatefulSet {\n\t// We can't look up by UID, so look up by Name and then verify UID.\n\t// Don't even try to look up by Name if it's the wrong Kind.\n\tif controllerRef.Kind != controllerKind.Kind {\n\t\treturn nil\n\t}\n\tset, err := ssc.setLister.StatefulSets(namespace).Get(controllerRef.Name)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tif set.UID != controllerRef.UID {\n\t\t// The controller we found with this Name is not the same one that the\n\t\t// ControllerRef points to.\n\t\treturn nil\n\t}\n\treturn set\n}","line":{"from":380,"to":399}} {"id":100004638,"name":"enqueueStatefulSet","signature":"func (ssc *StatefulSetController) enqueueStatefulSet(obj interface{})","file":"pkg/controller/statefulset/stateful_set.go","code":"// enqueueStatefulSet enqueues the given statefulset in the work queue.\nfunc (ssc *StatefulSetController) enqueueStatefulSet(obj interface{}) {\n\tkey, err := controller.KeyFunc(obj)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get key for object %+v: %v\", obj, err))\n\t\treturn\n\t}\n\tssc.queue.Add(key)\n}","line":{"from":401,"to":409}} {"id":100004639,"name":"enqueueSSAfter","signature":"func (ssc *StatefulSetController) enqueueSSAfter(ss *apps.StatefulSet, duration time.Duration)","file":"pkg/controller/statefulset/stateful_set.go","code":"// enqueueStatefulSet enqueues the given statefulset in the work queue after given time\nfunc (ssc *StatefulSetController) enqueueSSAfter(ss *apps.StatefulSet, duration time.Duration) {\n\tkey, err := controller.KeyFunc(ss)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get key for object %#v: %v\", ss, err))\n\t\treturn\n\t}\n\tssc.queue.AddAfter(key, duration)\n}","line":{"from":411,"to":419}} {"id":100004640,"name":"processNextWorkItem","signature":"func (ssc *StatefulSetController) processNextWorkItem(ctx context.Context) bool","file":"pkg/controller/statefulset/stateful_set.go","code":"// processNextWorkItem dequeues items, processes them, and marks them done. It enforces that the syncHandler is never\n// invoked concurrently with the same key.\nfunc (ssc *StatefulSetController) processNextWorkItem(ctx context.Context) bool {\n\tkey, quit := ssc.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer ssc.queue.Done(key)\n\tif err := ssc.sync(ctx, key.(string)); err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"error syncing StatefulSet %v, requeuing: %v\", key.(string), err))\n\t\tssc.queue.AddRateLimited(key)\n\t} else {\n\t\tssc.queue.Forget(key)\n\t}\n\treturn true\n}","line":{"from":421,"to":436}} {"id":100004641,"name":"worker","signature":"func (ssc *StatefulSetController) worker(ctx context.Context)","file":"pkg/controller/statefulset/stateful_set.go","code":"// worker runs a worker goroutine that invokes processNextWorkItem until the controller's queue is closed\nfunc (ssc *StatefulSetController) worker(ctx context.Context) {\n\tfor ssc.processNextWorkItem(ctx) {\n\t}\n}","line":{"from":438,"to":442}} {"id":100004642,"name":"sync","signature":"func (ssc *StatefulSetController) sync(ctx context.Context, key string) error","file":"pkg/controller/statefulset/stateful_set.go","code":"// sync syncs the given statefulset.\nfunc (ssc *StatefulSetController) sync(ctx context.Context, key string) error {\n\tstartTime := time.Now()\n\tlogger := klog.FromContext(ctx)\n\tdefer func() {\n\t\tlogger.V(4).Info(\"Finished syncing statefulset\", \"key\", key, \"time\", time.Since(startTime))\n\t}()\n\n\tnamespace, name, err := cache.SplitMetaNamespaceKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tset, err := ssc.setLister.StatefulSets(namespace).Get(name)\n\tif errors.IsNotFound(err) {\n\t\tlogger.Info(\"StatefulSet has been deleted\", \"key\", key)\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unable to retrieve StatefulSet %v from store: %v\", key, err))\n\t\treturn err\n\t}\n\n\tselector, err := metav1.LabelSelectorAsSelector(set.Spec.Selector)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"error converting StatefulSet %v selector: %v\", key, err))\n\t\t// This is a non-transient error, so don't retry.\n\t\treturn nil\n\t}\n\n\tif err := ssc.adoptOrphanRevisions(ctx, set); err != nil {\n\t\treturn err\n\t}\n\n\tpods, err := ssc.getPodsForStatefulSet(ctx, set, selector)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn ssc.syncStatefulSet(ctx, set, pods)\n}","line":{"from":444,"to":483}} {"id":100004643,"name":"syncStatefulSet","signature":"func (ssc *StatefulSetController) syncStatefulSet(ctx context.Context, set *apps.StatefulSet, pods []*v1.Pod) error","file":"pkg/controller/statefulset/stateful_set.go","code":"// syncStatefulSet syncs a tuple of (statefulset, []*v1.Pod).\nfunc (ssc *StatefulSetController) syncStatefulSet(ctx context.Context, set *apps.StatefulSet, pods []*v1.Pod) error {\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"Syncing StatefulSet with pods\", \"statefulSet\", klog.KObj(set), \"pods\", len(pods))\n\tvar status *apps.StatefulSetStatus\n\tvar err error\n\tstatus, err = ssc.control.UpdateStatefulSet(ctx, set, pods)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlogger.V(4).Info(\"Successfully synced StatefulSet\", \"statefulSet\", klog.KObj(set))\n\t// One more sync to handle the clock skew. This is also helping in requeuing right after status update\n\tif set.Spec.MinReadySeconds \u003e 0 \u0026\u0026 status != nil \u0026\u0026 status.AvailableReplicas != *set.Spec.Replicas {\n\t\tssc.enqueueSSAfter(set, time.Duration(set.Spec.MinReadySeconds)*time.Second)\n\t}\n\n\treturn nil\n}","line":{"from":485,"to":502}} {"id":100004644,"name":"NewDefaultStatefulSetControl","signature":"func NewDefaultStatefulSetControl(","file":"pkg/controller/statefulset/stateful_set_control.go","code":"// NewDefaultStatefulSetControl returns a new instance of the default implementation StatefulSetControlInterface that\n// implements the documented semantics for StatefulSets. podControl is the PodControlInterface used to create, update,\n// and delete Pods and to create PersistentVolumeClaims. statusUpdater is the StatefulSetStatusUpdaterInterface used\n// to update the status of StatefulSets. You should use an instance returned from NewRealStatefulPodControl() for any\n// scenario other than testing.\nfunc NewDefaultStatefulSetControl(\n\tpodControl *StatefulPodControl,\n\tstatusUpdater StatefulSetStatusUpdaterInterface,\n\tcontrollerHistory history.Interface,\n\trecorder record.EventRecorder) StatefulSetControlInterface {\n\treturn \u0026defaultStatefulSetControl{podControl, statusUpdater, controllerHistory, recorder}\n}","line":{"from":57,"to":68}} {"id":100004645,"name":"UpdateStatefulSet","signature":"func (ssc *defaultStatefulSetControl) UpdateStatefulSet(ctx context.Context, set *apps.StatefulSet, pods []*v1.Pod) (*apps.StatefulSetStatus, error)","file":"pkg/controller/statefulset/stateful_set_control.go","code":"// UpdateStatefulSet executes the core logic loop for a stateful set, applying the predictable and\n// consistent monotonic update strategy by default - scale up proceeds in ordinal order, no new pod\n// is created while any pod is unhealthy, and pods are terminated in descending order. The burst\n// strategy allows these constraints to be relaxed - pods will be created and deleted eagerly and\n// in no particular order. Clients using the burst strategy should be careful to ensure they\n// understand the consistency implications of having unpredictable numbers of pods available.\nfunc (ssc *defaultStatefulSetControl) UpdateStatefulSet(ctx context.Context, set *apps.StatefulSet, pods []*v1.Pod) (*apps.StatefulSetStatus, error) {\n\tset = set.DeepCopy() // set is modified when a new revision is created in performUpdate. Make a copy now to avoid mutation errors.\n\n\t// list all revisions and sort them\n\trevisions, err := ssc.ListRevisions(set)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thistory.SortControllerRevisions(revisions)\n\n\tcurrentRevision, updateRevision, status, err := ssc.performUpdate(ctx, set, pods, revisions)\n\tif err != nil {\n\t\terrs := []error{err}\n\t\tif agg, ok := err.(utilerrors.Aggregate); ok {\n\t\t\terrs = agg.Errors()\n\t\t}\n\t\treturn nil, utilerrors.NewAggregate(append(errs, ssc.truncateHistory(set, pods, revisions, currentRevision, updateRevision)))\n\t}\n\n\t// maintain the set's revision history limit\n\treturn status, ssc.truncateHistory(set, pods, revisions, currentRevision, updateRevision)\n}","line":{"from":77,"to":104}} {"id":100004646,"name":"performUpdate","signature":"func (ssc *defaultStatefulSetControl) performUpdate(","file":"pkg/controller/statefulset/stateful_set_control.go","code":"func (ssc *defaultStatefulSetControl) performUpdate(\n\tctx context.Context, set *apps.StatefulSet, pods []*v1.Pod, revisions []*apps.ControllerRevision) (*apps.ControllerRevision, *apps.ControllerRevision, *apps.StatefulSetStatus, error) {\n\tvar currentStatus *apps.StatefulSetStatus\n\tlogger := klog.FromContext(ctx)\n\t// get the current, and update revisions\n\tcurrentRevision, updateRevision, collisionCount, err := ssc.getStatefulSetRevisions(set, revisions)\n\tif err != nil {\n\t\treturn currentRevision, updateRevision, currentStatus, err\n\t}\n\n\t// perform the main update function and get the status\n\tcurrentStatus, err = ssc.updateStatefulSet(ctx, set, currentRevision, updateRevision, collisionCount, pods)\n\tif err != nil \u0026\u0026 currentStatus == nil {\n\t\treturn currentRevision, updateRevision, nil, err\n\t}\n\n\t// make sure to update the latest status even if there is an error with non-nil currentStatus\n\tstatusErr := ssc.updateStatefulSetStatus(ctx, set, currentStatus)\n\tif statusErr == nil {\n\t\tlogger.V(4).Info(\"Updated status\", \"statefulSet\", klog.KObj(set),\n\t\t\t\"replicas\", currentStatus.Replicas,\n\t\t\t\"readyReplicas\", currentStatus.ReadyReplicas,\n\t\t\t\"currentReplicas\", currentStatus.CurrentReplicas,\n\t\t\t\"updatedReplicas\", currentStatus.UpdatedReplicas)\n\t}\n\n\tswitch {\n\tcase err != nil \u0026\u0026 statusErr != nil:\n\t\tklog.ErrorS(statusErr, \"Could not update status\", \"statefulSet\", klog.KObj(set))\n\t\treturn currentRevision, updateRevision, currentStatus, err\n\tcase err != nil:\n\t\treturn currentRevision, updateRevision, currentStatus, err\n\tcase statusErr != nil:\n\t\treturn currentRevision, updateRevision, currentStatus, statusErr\n\t}\n\n\tlogger.V(4).Info(\"StatefulSet revisions\", \"statefulSet\", klog.KObj(set),\n\t\t\"currentRevision\", currentStatus.CurrentRevision,\n\t\t\"updateRevision\", currentStatus.UpdateRevision)\n\n\treturn currentRevision, updateRevision, currentStatus, nil\n}","line":{"from":106,"to":147}} {"id":100004647,"name":"ListRevisions","signature":"func (ssc *defaultStatefulSetControl) ListRevisions(set *apps.StatefulSet) ([]*apps.ControllerRevision, error)","file":"pkg/controller/statefulset/stateful_set_control.go","code":"func (ssc *defaultStatefulSetControl) ListRevisions(set *apps.StatefulSet) ([]*apps.ControllerRevision, error) {\n\tselector, err := metav1.LabelSelectorAsSelector(set.Spec.Selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ssc.controllerHistory.ListControllerRevisions(set, selector)\n}","line":{"from":149,"to":155}} {"id":100004648,"name":"AdoptOrphanRevisions","signature":"func (ssc *defaultStatefulSetControl) AdoptOrphanRevisions(","file":"pkg/controller/statefulset/stateful_set_control.go","code":"func (ssc *defaultStatefulSetControl) AdoptOrphanRevisions(\n\tset *apps.StatefulSet,\n\trevisions []*apps.ControllerRevision) error {\n\tfor i := range revisions {\n\t\tadopted, err := ssc.controllerHistory.AdoptControllerRevision(set, controllerKind, revisions[i])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\trevisions[i] = adopted\n\t}\n\treturn nil\n}","line":{"from":157,"to":168}} {"id":100004649,"name":"truncateHistory","signature":"func (ssc *defaultStatefulSetControl) truncateHistory(","file":"pkg/controller/statefulset/stateful_set_control.go","code":"// truncateHistory truncates any non-live ControllerRevisions in revisions from set's history. The UpdateRevision and\n// CurrentRevision in set's Status are considered to be live. Any revisions associated with the Pods in pods are also\n// considered to be live. Non-live revisions are deleted, starting with the revision with the lowest Revision, until\n// only RevisionHistoryLimit revisions remain. If the returned error is nil the operation was successful. This method\n// expects that revisions is sorted when supplied.\nfunc (ssc *defaultStatefulSetControl) truncateHistory(\n\tset *apps.StatefulSet,\n\tpods []*v1.Pod,\n\trevisions []*apps.ControllerRevision,\n\tcurrent *apps.ControllerRevision,\n\tupdate *apps.ControllerRevision) error {\n\thistory := make([]*apps.ControllerRevision, 0, len(revisions))\n\t// mark all live revisions\n\tlive := map[string]bool{}\n\tif current != nil {\n\t\tlive[current.Name] = true\n\t}\n\tif update != nil {\n\t\tlive[update.Name] = true\n\t}\n\tfor i := range pods {\n\t\tlive[getPodRevision(pods[i])] = true\n\t}\n\t// collect live revisions and historic revisions\n\tfor i := range revisions {\n\t\tif !live[revisions[i].Name] {\n\t\t\thistory = append(history, revisions[i])\n\t\t}\n\t}\n\thistoryLen := len(history)\n\thistoryLimit := int(*set.Spec.RevisionHistoryLimit)\n\tif historyLen \u003c= historyLimit {\n\t\treturn nil\n\t}\n\t// delete any non-live history to maintain the revision limit.\n\thistory = history[:(historyLen - historyLimit)]\n\tfor i := 0; i \u003c len(history); i++ {\n\t\tif err := ssc.controllerHistory.DeleteControllerRevision(history[i]); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":170,"to":212}} {"id":100004650,"name":"getStatefulSetRevisions","signature":"func (ssc *defaultStatefulSetControl) getStatefulSetRevisions(","file":"pkg/controller/statefulset/stateful_set_control.go","code":"// getStatefulSetRevisions returns the current and update ControllerRevisions for set. It also\n// returns a collision count that records the number of name collisions set saw when creating\n// new ControllerRevisions. This count is incremented on every name collision and is used in\n// building the ControllerRevision names for name collision avoidance. This method may create\n// a new revision, or modify the Revision of an existing revision if an update to set is detected.\n// This method expects that revisions is sorted when supplied.\nfunc (ssc *defaultStatefulSetControl) getStatefulSetRevisions(\n\tset *apps.StatefulSet,\n\trevisions []*apps.ControllerRevision) (*apps.ControllerRevision, *apps.ControllerRevision, int32, error) {\n\tvar currentRevision, updateRevision *apps.ControllerRevision\n\n\trevisionCount := len(revisions)\n\thistory.SortControllerRevisions(revisions)\n\n\t// Use a local copy of set.Status.CollisionCount to avoid modifying set.Status directly.\n\t// This copy is returned so the value gets carried over to set.Status in updateStatefulSet.\n\tvar collisionCount int32\n\tif set.Status.CollisionCount != nil {\n\t\tcollisionCount = *set.Status.CollisionCount\n\t}\n\n\t// create a new revision from the current set\n\tupdateRevision, err := newRevision(set, nextRevision(revisions), \u0026collisionCount)\n\tif err != nil {\n\t\treturn nil, nil, collisionCount, err\n\t}\n\n\t// find any equivalent revisions\n\tequalRevisions := history.FindEqualRevisions(revisions, updateRevision)\n\tequalCount := len(equalRevisions)\n\n\tif equalCount \u003e 0 \u0026\u0026 history.EqualRevision(revisions[revisionCount-1], equalRevisions[equalCount-1]) {\n\t\t// if the equivalent revision is immediately prior the update revision has not changed\n\t\tupdateRevision = revisions[revisionCount-1]\n\t} else if equalCount \u003e 0 {\n\t\t// if the equivalent revision is not immediately prior we will roll back by incrementing the\n\t\t// Revision of the equivalent revision\n\t\tupdateRevision, err = ssc.controllerHistory.UpdateControllerRevision(\n\t\t\tequalRevisions[equalCount-1],\n\t\t\tupdateRevision.Revision)\n\t\tif err != nil {\n\t\t\treturn nil, nil, collisionCount, err\n\t\t}\n\t} else {\n\t\t//if there is no equivalent revision we create a new one\n\t\tupdateRevision, err = ssc.controllerHistory.CreateControllerRevision(set, updateRevision, \u0026collisionCount)\n\t\tif err != nil {\n\t\t\treturn nil, nil, collisionCount, err\n\t\t}\n\t}\n\n\t// attempt to find the revision that corresponds to the current revision\n\tfor i := range revisions {\n\t\tif revisions[i].Name == set.Status.CurrentRevision {\n\t\t\tcurrentRevision = revisions[i]\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// if the current revision is nil we initialize the history by setting it to the update revision\n\tif currentRevision == nil {\n\t\tcurrentRevision = updateRevision\n\t}\n\n\treturn currentRevision, updateRevision, collisionCount, nil\n}","line":{"from":214,"to":279}} {"id":100004651,"name":"slowStartBatch","signature":"func slowStartBatch(initialBatchSize int, remaining int, fn func(int) (bool, error)) (int, error)","file":"pkg/controller/statefulset/stateful_set_control.go","code":"func slowStartBatch(initialBatchSize int, remaining int, fn func(int) (bool, error)) (int, error) {\n\tsuccesses := 0\n\tj := 0\n\tfor batchSize := integer.IntMin(remaining, initialBatchSize); batchSize \u003e 0; batchSize = integer.IntMin(integer.IntMin(2*batchSize, remaining), MaxBatchSize) {\n\t\terrCh := make(chan error, batchSize)\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(batchSize)\n\t\tfor i := 0; i \u003c batchSize; i++ {\n\t\t\tgo func(k int) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\t// Ignore the first parameter - relevant for monotonic only.\n\t\t\t\tif _, err := fn(k); err != nil {\n\t\t\t\t\terrCh \u003c- err\n\t\t\t\t}\n\t\t\t}(j)\n\t\t\tj++\n\t\t}\n\t\twg.Wait()\n\t\tsuccesses += batchSize - len(errCh)\n\t\tclose(errCh)\n\t\tif len(errCh) \u003e 0 {\n\t\t\terrs := make([]error, 0)\n\t\t\tfor err := range errCh {\n\t\t\t\terrs = append(errs, err)\n\t\t\t}\n\t\t\treturn successes, utilerrors.NewAggregate(errs)\n\t\t}\n\t\tremaining -= batchSize\n\t}\n\treturn successes, nil\n}","line":{"from":281,"to":311}} {"id":100004652,"name":"computeReplicaStatus","signature":"func computeReplicaStatus(pods []*v1.Pod, minReadySeconds int32, currentRevision, updateRevision *apps.ControllerRevision) replicaStatus","file":"pkg/controller/statefulset/stateful_set_control.go","code":"func computeReplicaStatus(pods []*v1.Pod, minReadySeconds int32, currentRevision, updateRevision *apps.ControllerRevision) replicaStatus {\n\tstatus := replicaStatus{}\n\tfor _, pod := range pods {\n\t\tif isCreated(pod) {\n\t\t\tstatus.replicas++\n\t\t}\n\n\t\t// count the number of running and ready replicas\n\t\tif isRunningAndReady(pod) {\n\t\t\tstatus.readyReplicas++\n\t\t\t// count the number of running and available replicas\n\t\t\tif isRunningAndAvailable(pod, minReadySeconds) {\n\t\t\t\tstatus.availableReplicas++\n\t\t\t}\n\n\t\t}\n\n\t\t// count the number of current and update replicas\n\t\tif isCreated(pod) \u0026\u0026 !isTerminating(pod) {\n\t\t\tif getPodRevision(pod) == currentRevision.Name {\n\t\t\t\tstatus.currentReplicas++\n\t\t\t}\n\t\t\tif getPodRevision(pod) == updateRevision.Name {\n\t\t\t\tstatus.updatedReplicas++\n\t\t\t}\n\t\t}\n\t}\n\treturn status\n}","line":{"from":321,"to":349}} {"id":100004653,"name":"updateStatus","signature":"func updateStatus(status *apps.StatefulSetStatus, minReadySeconds int32, currentRevision, updateRevision *apps.ControllerRevision, podLists ...[]*v1.Pod)","file":"pkg/controller/statefulset/stateful_set_control.go","code":"func updateStatus(status *apps.StatefulSetStatus, minReadySeconds int32, currentRevision, updateRevision *apps.ControllerRevision, podLists ...[]*v1.Pod) {\n\tstatus.Replicas = 0\n\tstatus.ReadyReplicas = 0\n\tstatus.AvailableReplicas = 0\n\tstatus.CurrentReplicas = 0\n\tstatus.UpdatedReplicas = 0\n\tfor _, list := range podLists {\n\t\treplicaStatus := computeReplicaStatus(list, minReadySeconds, currentRevision, updateRevision)\n\t\tstatus.Replicas += replicaStatus.replicas\n\t\tstatus.ReadyReplicas += replicaStatus.readyReplicas\n\t\tstatus.AvailableReplicas += replicaStatus.availableReplicas\n\t\tstatus.CurrentReplicas += replicaStatus.currentReplicas\n\t\tstatus.UpdatedReplicas += replicaStatus.updatedReplicas\n\t}\n}","line":{"from":351,"to":365}} {"id":100004654,"name":"processReplica","signature":"func (ssc *defaultStatefulSetControl) processReplica(","file":"pkg/controller/statefulset/stateful_set_control.go","code":"func (ssc *defaultStatefulSetControl) processReplica(\n\tctx context.Context,\n\tset *apps.StatefulSet,\n\tcurrentRevision *apps.ControllerRevision,\n\tupdateRevision *apps.ControllerRevision,\n\tcurrentSet *apps.StatefulSet,\n\tupdateSet *apps.StatefulSet,\n\tmonotonic bool,\n\treplicas []*v1.Pod,\n\ti int) (bool, error) {\n\tlogger := klog.FromContext(ctx)\n\t// delete and recreate failed pods\n\tif isFailed(replicas[i]) {\n\t\tssc.recorder.Eventf(set, v1.EventTypeWarning, \"RecreatingFailedPod\",\n\t\t\t\"StatefulSet %s/%s is recreating failed Pod %s\",\n\t\t\tset.Namespace,\n\t\t\tset.Name,\n\t\t\treplicas[i].Name)\n\t\tif err := ssc.podControl.DeleteStatefulPod(set, replicas[i]); err != nil {\n\t\t\treturn true, err\n\t\t}\n\t\treplicaOrd := i + getStartOrdinal(set)\n\t\treplicas[i] = newVersionedStatefulSetPod(\n\t\t\tcurrentSet,\n\t\t\tupdateSet,\n\t\t\tcurrentRevision.Name,\n\t\t\tupdateRevision.Name,\n\t\t\treplicaOrd)\n\t}\n\t// If we find a Pod that has not been created we create the Pod\n\tif !isCreated(replicas[i]) {\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.StatefulSetAutoDeletePVC) {\n\t\t\tif isStale, err := ssc.podControl.PodClaimIsStale(set, replicas[i]); err != nil {\n\t\t\t\treturn true, err\n\t\t\t} else if isStale {\n\t\t\t\t// If a pod has a stale PVC, no more work can be done this round.\n\t\t\t\treturn true, err\n\t\t\t}\n\t\t}\n\t\tif err := ssc.podControl.CreateStatefulPod(ctx, set, replicas[i]); err != nil {\n\t\t\treturn true, err\n\t\t}\n\t\tif monotonic {\n\t\t\t// if the set does not allow bursting, return immediately\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\t// If the Pod is in pending state then trigger PVC creation to create missing PVCs\n\tif isPending(replicas[i]) {\n\t\tlogger.V(4).Info(\n\t\t\t\"StatefulSet is triggering PVC creation for pending Pod\",\n\t\t\t\"statefulSet\", klog.KObj(set), \"pod\", klog.KObj(replicas[i]))\n\t\tif err := ssc.podControl.createMissingPersistentVolumeClaims(ctx, set, replicas[i]); err != nil {\n\t\t\treturn true, err\n\t\t}\n\t}\n\n\t// If we find a Pod that is currently terminating, we must wait until graceful deletion\n\t// completes before we continue to make progress.\n\tif isTerminating(replicas[i]) \u0026\u0026 monotonic {\n\t\tlogger.V(4).Info(\"StatefulSet is waiting for Pod to Terminate\",\n\t\t\t\"statefulSet\", klog.KObj(set), \"pod\", klog.KObj(replicas[i]))\n\t\treturn true, nil\n\t}\n\n\t// If we have a Pod that has been created but is not running and ready we can not make progress.\n\t// We must ensure that all for each Pod, when we create it, all of its predecessors, with respect to its\n\t// ordinal, are Running and Ready.\n\tif !isRunningAndReady(replicas[i]) \u0026\u0026 monotonic {\n\t\tlogger.V(4).Info(\"StatefulSet is waiting for Pod to be Running and Ready\",\n\t\t\t\"statefulSet\", klog.KObj(set), \"pod\", klog.KObj(replicas[i]))\n\t\treturn true, nil\n\t}\n\n\t// If we have a Pod that has been created but is not available we can not make progress.\n\t// We must ensure that all for each Pod, when we create it, all of its predecessors, with respect to its\n\t// ordinal, are Available.\n\tif !isRunningAndAvailable(replicas[i], set.Spec.MinReadySeconds) \u0026\u0026 monotonic {\n\t\tlogger.V(4).Info(\"StatefulSet is waiting for Pod to be Available\",\n\t\t\t\"statefulSet\", klog.KObj(set), \"pod\", klog.KObj(replicas[i]))\n\t\treturn true, nil\n\t}\n\n\t// Enforce the StatefulSet invariants\n\tretentionMatch := true\n\tif utilfeature.DefaultFeatureGate.Enabled(features.StatefulSetAutoDeletePVC) {\n\t\tvar err error\n\t\tretentionMatch, err = ssc.podControl.ClaimsMatchRetentionPolicy(ctx, updateSet, replicas[i])\n\t\t// An error is expected if the pod is not yet fully updated, and so return is treated as matching.\n\t\tif err != nil {\n\t\t\tretentionMatch = true\n\t\t}\n\t}\n\n\tif identityMatches(set, replicas[i]) \u0026\u0026 storageMatches(set, replicas[i]) \u0026\u0026 retentionMatch {\n\t\treturn false, nil\n\t}\n\n\t// Make a deep copy so we don't mutate the shared cache\n\treplica := replicas[i].DeepCopy()\n\tif err := ssc.podControl.UpdateStatefulPod(ctx, updateSet, replica); err != nil {\n\t\treturn true, err\n\t}\n\n\treturn false, nil\n}","line":{"from":367,"to":473}} {"id":100004655,"name":"processCondemned","signature":"func (ssc *defaultStatefulSetControl) processCondemned(ctx context.Context, set *apps.StatefulSet, firstUnhealthyPod *v1.Pod, monotonic bool, condemned []*v1.Pod, i int) (bool, error)","file":"pkg/controller/statefulset/stateful_set_control.go","code":"func (ssc *defaultStatefulSetControl) processCondemned(ctx context.Context, set *apps.StatefulSet, firstUnhealthyPod *v1.Pod, monotonic bool, condemned []*v1.Pod, i int) (bool, error) {\n\tlogger := klog.FromContext(ctx)\n\tif isTerminating(condemned[i]) {\n\t\t// if we are in monotonic mode, block and wait for terminating pods to expire\n\t\tif monotonic {\n\t\t\tlogger.V(4).Info(\"StatefulSet is waiting for Pod to Terminate prior to scale down\",\n\t\t\t\t\"statefulSet\", klog.KObj(set), \"pod\", klog.KObj(condemned[i]))\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t}\n\t// if we are in monotonic mode and the condemned target is not the first unhealthy Pod block\n\tif !isRunningAndReady(condemned[i]) \u0026\u0026 monotonic \u0026\u0026 condemned[i] != firstUnhealthyPod {\n\t\tlogger.V(4).Info(\"StatefulSet is waiting for Pod to be Running and Ready prior to scale down\",\n\t\t\t\"statefulSet\", klog.KObj(set), \"pod\", klog.KObj(firstUnhealthyPod))\n\t\treturn true, nil\n\t}\n\t// if we are in monotonic mode and the condemned target is not the first unhealthy Pod, block.\n\tif !isRunningAndAvailable(condemned[i], set.Spec.MinReadySeconds) \u0026\u0026 monotonic \u0026\u0026 condemned[i] != firstUnhealthyPod {\n\t\tlogger.V(4).Info(\"StatefulSet is waiting for Pod to be Available prior to scale down\",\n\t\t\t\"statefulSet\", klog.KObj(set), \"pod\", klog.KObj(firstUnhealthyPod))\n\t\treturn true, nil\n\t}\n\n\tlogger.V(2).Info(\"Pod of StatefulSet is terminating for scale down\",\n\t\t\"statefulSet\", klog.KObj(set), \"pod\", klog.KObj(condemned[i]))\n\treturn true, ssc.podControl.DeleteStatefulPod(set, condemned[i])\n}","line":{"from":475,"to":502}} {"id":100004656,"name":"runForAll","signature":"func runForAll(pods []*v1.Pod, fn func(i int) (bool, error), monotonic bool) (bool, error)","file":"pkg/controller/statefulset/stateful_set_control.go","code":"func runForAll(pods []*v1.Pod, fn func(i int) (bool, error), monotonic bool) (bool, error) {\n\tif monotonic {\n\t\tfor i := range pods {\n\t\t\tif shouldExit, err := fn(i); shouldExit || err != nil {\n\t\t\t\treturn true, err\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif _, err := slowStartBatch(1, len(pods), fn); err != nil {\n\t\t\treturn true, err\n\t\t}\n\t}\n\treturn false, nil\n}","line":{"from":504,"to":517}} {"id":100004657,"name":"updateStatefulSet","signature":"func (ssc *defaultStatefulSetControl) updateStatefulSet(","file":"pkg/controller/statefulset/stateful_set_control.go","code":"// updateStatefulSet performs the update function for a StatefulSet. This method creates, updates, and deletes Pods in\n// the set in order to conform the system to the target state for the set. The target state always contains\n// set.Spec.Replicas Pods with a Ready Condition. If the UpdateStrategy.Type for the set is\n// RollingUpdateStatefulSetStrategyType then all Pods in the set must be at set.Status.CurrentRevision.\n// If the UpdateStrategy.Type for the set is OnDeleteStatefulSetStrategyType, the target state implies nothing about\n// the revisions of Pods in the set. If the UpdateStrategy.Type for the set is PartitionStatefulSetStrategyType, then\n// all Pods with ordinal less than UpdateStrategy.Partition.Ordinal must be at Status.CurrentRevision and all other\n// Pods must be at Status.UpdateRevision. If the returned error is nil, the returned StatefulSetStatus is valid and the\n// update must be recorded. If the error is not nil, the method should be retried until successful.\nfunc (ssc *defaultStatefulSetControl) updateStatefulSet(\n\tctx context.Context,\n\tset *apps.StatefulSet,\n\tcurrentRevision *apps.ControllerRevision,\n\tupdateRevision *apps.ControllerRevision,\n\tcollisionCount int32,\n\tpods []*v1.Pod) (*apps.StatefulSetStatus, error) {\n\tlogger := klog.FromContext(ctx)\n\t// get the current and update revisions of the set.\n\tcurrentSet, err := ApplyRevision(set, currentRevision)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tupdateSet, err := ApplyRevision(set, updateRevision)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// set the generation, and revisions in the returned status\n\tstatus := apps.StatefulSetStatus{}\n\tstatus.ObservedGeneration = set.Generation\n\tstatus.CurrentRevision = currentRevision.Name\n\tstatus.UpdateRevision = updateRevision.Name\n\tstatus.CollisionCount = new(int32)\n\t*status.CollisionCount = collisionCount\n\n\tupdateStatus(\u0026status, set.Spec.MinReadySeconds, currentRevision, updateRevision, pods)\n\n\treplicaCount := int(*set.Spec.Replicas)\n\t// slice that will contain all Pods such that getStartOrdinal(set) \u003c= getOrdinal(pod) \u003c= getEndOrdinal(set)\n\treplicas := make([]*v1.Pod, replicaCount)\n\t// slice that will contain all Pods such that getOrdinal(pod) \u003c getStartOrdinal(set) OR getOrdinal(pod) \u003e getEndOrdinal(set)\n\tcondemned := make([]*v1.Pod, 0, len(pods))\n\tunhealthy := 0\n\tvar firstUnhealthyPod *v1.Pod\n\n\t// First we partition pods into two lists valid replicas and condemned Pods\n\tfor _, pod := range pods {\n\t\tif podInOrdinalRange(pod, set) {\n\t\t\t// if the ordinal of the pod is within the range of the current number of replicas,\n\t\t\t// insert it at the indirection of its ordinal\n\t\t\treplicas[getOrdinal(pod)-getStartOrdinal(set)] = pod\n\t\t} else if getOrdinal(pod) \u003e= 0 {\n\t\t\t// if the ordinal is valid, but not within the range add it to the condemned list\n\t\t\tcondemned = append(condemned, pod)\n\t\t}\n\t\t// If the ordinal could not be parsed (ord \u003c 0), ignore the Pod.\n\t}\n\n\t// for any empty indices in the sequence [0,set.Spec.Replicas) create a new Pod at the correct revision\n\tfor ord := getStartOrdinal(set); ord \u003c= getEndOrdinal(set); ord++ {\n\t\treplicaIdx := ord - getStartOrdinal(set)\n\t\tif replicas[replicaIdx] == nil {\n\t\t\treplicas[replicaIdx] = newVersionedStatefulSetPod(\n\t\t\t\tcurrentSet,\n\t\t\t\tupdateSet,\n\t\t\t\tcurrentRevision.Name,\n\t\t\t\tupdateRevision.Name, ord)\n\t\t}\n\t}\n\n\t// sort the condemned Pods by their ordinals\n\tsort.Sort(descendingOrdinal(condemned))\n\n\t// find the first unhealthy Pod\n\tfor i := range replicas {\n\t\tif !isHealthy(replicas[i]) {\n\t\t\tunhealthy++\n\t\t\tif firstUnhealthyPod == nil {\n\t\t\t\tfirstUnhealthyPod = replicas[i]\n\t\t\t}\n\t\t}\n\t}\n\n\t// or the first unhealthy condemned Pod (condemned are sorted in descending order for ease of use)\n\tfor i := len(condemned) - 1; i \u003e= 0; i-- {\n\t\tif !isHealthy(condemned[i]) {\n\t\t\tunhealthy++\n\t\t\tif firstUnhealthyPod == nil {\n\t\t\t\tfirstUnhealthyPod = condemned[i]\n\t\t\t}\n\t\t}\n\t}\n\n\tif unhealthy \u003e 0 {\n\t\tlogger.V(4).Info(\"StatefulSet has unhealthy Pods\", \"statefulSet\", klog.KObj(set), \"unhealthyReplicas\", unhealthy, \"pod\", klog.KObj(firstUnhealthyPod))\n\t}\n\n\t// If the StatefulSet is being deleted, don't do anything other than updating\n\t// status.\n\tif set.DeletionTimestamp != nil {\n\t\treturn \u0026status, nil\n\t}\n\n\tmonotonic := !allowsBurst(set)\n\n\t// First, process each living replica. Exit if we run into an error or something blocking in monotonic mode.\n\tprocessReplicaFn := func(i int) (bool, error) {\n\t\treturn ssc.processReplica(ctx, set, currentRevision, updateRevision, currentSet, updateSet, monotonic, replicas, i)\n\t}\n\tif shouldExit, err := runForAll(replicas, processReplicaFn, monotonic); shouldExit || err != nil {\n\t\tupdateStatus(\u0026status, set.Spec.MinReadySeconds, currentRevision, updateRevision, replicas, condemned)\n\t\treturn \u0026status, err\n\t}\n\n\t// Fix pod claims for condemned pods, if necessary.\n\tif utilfeature.DefaultFeatureGate.Enabled(features.StatefulSetAutoDeletePVC) {\n\t\tfixPodClaim := func(i int) (bool, error) {\n\t\t\tif matchPolicy, err := ssc.podControl.ClaimsMatchRetentionPolicy(ctx, updateSet, condemned[i]); err != nil {\n\t\t\t\treturn true, err\n\t\t\t} else if !matchPolicy {\n\t\t\t\tif err := ssc.podControl.UpdatePodClaimForRetentionPolicy(ctx, updateSet, condemned[i]); err != nil {\n\t\t\t\t\treturn true, err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false, nil\n\t\t}\n\t\tif shouldExit, err := runForAll(condemned, fixPodClaim, monotonic); shouldExit || err != nil {\n\t\t\tupdateStatus(\u0026status, set.Spec.MinReadySeconds, currentRevision, updateRevision, replicas, condemned)\n\t\t\treturn \u0026status, err\n\t\t}\n\t}\n\n\t// At this point, in monotonic mode all of the current Replicas are Running, Ready and Available,\n\t// and we can consider termination.\n\t// We will wait for all predecessors to be Running and Ready prior to attempting a deletion.\n\t// We will terminate Pods in a monotonically decreasing order.\n\t// Note that we do not resurrect Pods in this interval. Also note that scaling will take precedence over\n\t// updates.\n\tprocessCondemnedFn := func(i int) (bool, error) {\n\t\treturn ssc.processCondemned(ctx, set, firstUnhealthyPod, monotonic, condemned, i)\n\t}\n\tif shouldExit, err := runForAll(condemned, processCondemnedFn, monotonic); shouldExit || err != nil {\n\t\tupdateStatus(\u0026status, set.Spec.MinReadySeconds, currentRevision, updateRevision, replicas, condemned)\n\t\treturn \u0026status, err\n\t}\n\n\tupdateStatus(\u0026status, set.Spec.MinReadySeconds, currentRevision, updateRevision, replicas, condemned)\n\n\t// for the OnDelete strategy we short circuit. Pods will be updated when they are manually deleted.\n\tif set.Spec.UpdateStrategy.Type == apps.OnDeleteStatefulSetStrategyType {\n\t\treturn \u0026status, nil\n\t}\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.MaxUnavailableStatefulSet) {\n\t\treturn updateStatefulSetAfterInvariantEstablished(ctx,\n\t\t\tssc,\n\t\t\tset,\n\t\t\treplicas,\n\t\t\tupdateRevision,\n\t\t\tstatus,\n\t\t)\n\t}\n\n\t// we compute the minimum ordinal of the target sequence for a destructive update based on the strategy.\n\tupdateMin := 0\n\tif set.Spec.UpdateStrategy.RollingUpdate != nil {\n\t\tupdateMin = int(*set.Spec.UpdateStrategy.RollingUpdate.Partition)\n\t}\n\t// we terminate the Pod with the largest ordinal that does not match the update revision.\n\tfor target := len(replicas) - 1; target \u003e= updateMin; target-- {\n\n\t\t// delete the Pod if it is not already terminating and does not match the update revision.\n\t\tif getPodRevision(replicas[target]) != updateRevision.Name \u0026\u0026 !isTerminating(replicas[target]) {\n\t\t\tlogger.V(2).Info(\"Pod of StatefulSet is terminating for update\",\n\t\t\t\t\"statefulSet\", klog.KObj(set), \"pod\", klog.KObj(replicas[target]))\n\t\t\tif err := ssc.podControl.DeleteStatefulPod(set, replicas[target]); err != nil {\n\t\t\t\tif !errors.IsNotFound(err) {\n\t\t\t\t\treturn \u0026status, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tstatus.CurrentReplicas--\n\t\t\treturn \u0026status, err\n\t\t}\n\n\t\t// wait for unhealthy Pods on update\n\t\tif !isHealthy(replicas[target]) {\n\t\t\tlogger.V(4).Info(\"StatefulSet is waiting for Pod to update\",\n\t\t\t\t\"statefulSet\", klog.KObj(set), \"pod\", klog.KObj(replicas[target]))\n\t\t\treturn \u0026status, nil\n\t\t}\n\n\t}\n\treturn \u0026status, nil\n}","line":{"from":519,"to":712}} {"id":100004658,"name":"updateStatefulSetAfterInvariantEstablished","signature":"func updateStatefulSetAfterInvariantEstablished(","file":"pkg/controller/statefulset/stateful_set_control.go","code":"func updateStatefulSetAfterInvariantEstablished(\n\tctx context.Context,\n\tssc *defaultStatefulSetControl,\n\tset *apps.StatefulSet,\n\treplicas []*v1.Pod,\n\tupdateRevision *apps.ControllerRevision,\n\tstatus apps.StatefulSetStatus,\n) (*apps.StatefulSetStatus, error) {\n\n\tlogger := klog.FromContext(ctx)\n\treplicaCount := int(*set.Spec.Replicas)\n\n\t// we compute the minimum ordinal of the target sequence for a destructive update based on the strategy.\n\tupdateMin := 0\n\tmaxUnavailable := 1\n\tif set.Spec.UpdateStrategy.RollingUpdate != nil {\n\t\tupdateMin = int(*set.Spec.UpdateStrategy.RollingUpdate.Partition)\n\n\t\t// if the feature was enabled and then later disabled, MaxUnavailable may have a value\n\t\t// more than 1. Ignore the passed in value and Use maxUnavailable as 1 to enforce\n\t\t// expected behavior when feature gate is not enabled.\n\t\tvar err error\n\t\tmaxUnavailable, err = getStatefulSetMaxUnavailable(set.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable, replicaCount)\n\t\tif err != nil {\n\t\t\treturn \u0026status, err\n\t\t}\n\t}\n\n\t// Collect all targets in the range between getStartOrdinal(set) and getEndOrdinal(set). Count any targets in that range\n\t// that are unhealthy i.e. terminated or not running and ready as unavailable). Select the\n\t// (MaxUnavailable - Unavailable) Pods, in order with respect to their ordinal for termination. Delete\n\t// those pods and count the successful deletions. Update the status with the correct number of deletions.\n\tunavailablePods := 0\n\tfor target := len(replicas) - 1; target \u003e= 0; target-- {\n\t\tif !isHealthy(replicas[target]) {\n\t\t\tunavailablePods++\n\t\t}\n\t}\n\n\tif unavailablePods \u003e= maxUnavailable {\n\t\tlogger.V(2).Info(\"StatefulSet found unavailablePods, more than or equal to allowed maxUnavailable\",\n\t\t\t\"statefulSet\", klog.KObj(set),\n\t\t\t\"unavailablePods\", unavailablePods,\n\t\t\t\"maxUnavailable\", maxUnavailable)\n\t\treturn \u0026status, nil\n\t}\n\n\t// Now we need to delete MaxUnavailable- unavailablePods\n\t// start deleting one by one starting from the highest ordinal first\n\tpodsToDelete := maxUnavailable - unavailablePods\n\n\tdeletedPods := 0\n\tfor target := len(replicas) - 1; target \u003e= updateMin \u0026\u0026 deletedPods \u003c podsToDelete; target-- {\n\n\t\t// delete the Pod if it is healthy and the revision doesnt match the target\n\t\tif getPodRevision(replicas[target]) != updateRevision.Name \u0026\u0026 !isTerminating(replicas[target]) {\n\t\t\t// delete the Pod if it is healthy and the revision doesnt match the target\n\t\t\tlogger.V(2).Info(\"StatefulSet terminating Pod for update\",\n\t\t\t\t\"statefulSet\", klog.KObj(set),\n\t\t\t\t\"pod\", klog.KObj(replicas[target]))\n\t\t\tif err := ssc.podControl.DeleteStatefulPod(set, replicas[target]); err != nil {\n\t\t\t\tif !errors.IsNotFound(err) {\n\t\t\t\t\treturn \u0026status, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tdeletedPods++\n\t\t\tstatus.CurrentReplicas--\n\t\t}\n\t}\n\treturn \u0026status, nil\n}","line":{"from":714,"to":784}} {"id":100004659,"name":"updateStatefulSetStatus","signature":"func (ssc *defaultStatefulSetControl) updateStatefulSetStatus(","file":"pkg/controller/statefulset/stateful_set_control.go","code":"// updateStatefulSetStatus updates set's Status to be equal to status. If status indicates a complete update, it is\n// mutated to indicate completion. If status is semantically equivalent to set's Status no update is performed. If the\n// returned error is nil, the update is successful.\nfunc (ssc *defaultStatefulSetControl) updateStatefulSetStatus(\n\tctx context.Context,\n\tset *apps.StatefulSet,\n\tstatus *apps.StatefulSetStatus) error {\n\t// complete any in progress rolling update if necessary\n\tcompleteRollingUpdate(set, status)\n\n\t// if the status is not inconsistent do not perform an update\n\tif !inconsistentStatus(set, status) {\n\t\treturn nil\n\t}\n\n\t// copy set and update its status\n\tset = set.DeepCopy()\n\tif err := ssc.statusUpdater.UpdateStatefulSetStatus(ctx, set, status); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":786,"to":808}} {"id":100004660,"name":"NewRealStatefulSetStatusUpdater","signature":"func NewRealStatefulSetStatusUpdater(","file":"pkg/controller/statefulset/stateful_set_status_updater.go","code":"// NewRealStatefulSetStatusUpdater returns a StatefulSetStatusUpdaterInterface that updates the Status of a StatefulSet,\n// using the supplied client and setLister.\nfunc NewRealStatefulSetStatusUpdater(\n\tclient clientset.Interface,\n\tsetLister appslisters.StatefulSetLister) StatefulSetStatusUpdaterInterface {\n\treturn \u0026realStatefulSetStatusUpdater{client, setLister}\n}","line":{"from":39,"to":45}} {"id":100004661,"name":"UpdateStatefulSetStatus","signature":"func (ssu *realStatefulSetStatusUpdater) UpdateStatefulSetStatus(","file":"pkg/controller/statefulset/stateful_set_status_updater.go","code":"func (ssu *realStatefulSetStatusUpdater) UpdateStatefulSetStatus(\n\tctx context.Context,\n\tset *apps.StatefulSet,\n\tstatus *apps.StatefulSetStatus) error {\n\t// don't wait due to limited number of clients, but backoff after the default number of steps\n\treturn retry.RetryOnConflict(retry.DefaultRetry, func() error {\n\t\tset.Status = *status\n\t\t// TODO: This context.TODO should use a real context once we have RetryOnConflictWithContext\n\t\t_, updateErr := ssu.client.AppsV1().StatefulSets(set.Namespace).UpdateStatus(context.TODO(), set, metav1.UpdateOptions{})\n\t\tif updateErr == nil {\n\t\t\treturn nil\n\t\t}\n\t\tif updated, err := ssu.setLister.StatefulSets(set.Namespace).Get(set.Name); err == nil {\n\t\t\t// make a copy so we don't mutate the shared cache\n\t\t\tset = updated.DeepCopy()\n\t\t} else {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"error getting updated StatefulSet %s/%s from lister: %v\", set.Namespace, set.Name, err))\n\t\t}\n\n\t\treturn updateErr\n\t})\n}","line":{"from":52,"to":73}} {"id":100004662,"name":"Len","signature":"func (o overlappingStatefulSets) Len() int { return len(o) }","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"func (o overlappingStatefulSets) Len() int { return len(o) }","line":{"from":47,"to":47}} {"id":100004663,"name":"Swap","signature":"func (o overlappingStatefulSets) Swap(i, j int) { o[i], o[j] = o[j], o[i] }","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"func (o overlappingStatefulSets) Swap(i, j int) { o[i], o[j] = o[j], o[i] }","line":{"from":49,"to":49}} {"id":100004664,"name":"Less","signature":"func (o overlappingStatefulSets) Less(i, j int) bool","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"func (o overlappingStatefulSets) Less(i, j int) bool {\n\tif o[i].CreationTimestamp.Equal(\u0026o[j].CreationTimestamp) {\n\t\treturn o[i].Name \u003c o[j].Name\n\t}\n\treturn o[i].CreationTimestamp.Before(\u0026o[j].CreationTimestamp)\n}","line":{"from":51,"to":56}} {"id":100004665,"name":"getParentNameAndOrdinal","signature":"func getParentNameAndOrdinal(pod *v1.Pod) (string, int)","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// getParentNameAndOrdinal gets the name of pod's parent StatefulSet and pod's ordinal as extracted from its Name. If\n// the Pod was not created by a StatefulSet, its parent is considered to be empty string, and its ordinal is considered\n// to be -1.\nfunc getParentNameAndOrdinal(pod *v1.Pod) (string, int) {\n\tparent := \"\"\n\tordinal := -1\n\tsubMatches := statefulPodRegex.FindStringSubmatch(pod.Name)\n\tif len(subMatches) \u003c 3 {\n\t\treturn parent, ordinal\n\t}\n\tparent = subMatches[1]\n\tif i, err := strconv.ParseInt(subMatches[2], 10, 32); err == nil {\n\t\tordinal = int(i)\n\t}\n\treturn parent, ordinal\n}","line":{"from":61,"to":76}} {"id":100004666,"name":"getParentName","signature":"func getParentName(pod *v1.Pod) string","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// getParentName gets the name of pod's parent StatefulSet. If pod has not parent, the empty string is returned.\nfunc getParentName(pod *v1.Pod) string {\n\tparent, _ := getParentNameAndOrdinal(pod)\n\treturn parent\n}","line":{"from":78,"to":82}} {"id":100004667,"name":"getOrdinal","signature":"func getOrdinal(pod *v1.Pod) int","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// getOrdinal gets pod's ordinal. If pod has no ordinal, -1 is returned.\nfunc getOrdinal(pod *v1.Pod) int {\n\t_, ordinal := getParentNameAndOrdinal(pod)\n\treturn ordinal\n}","line":{"from":84,"to":88}} {"id":100004668,"name":"getStartOrdinal","signature":"func getStartOrdinal(set *apps.StatefulSet) int","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// getStartOrdinal gets the first possible ordinal (inclusive).\n// Returns spec.ordinals.start if spec.ordinals is set, otherwise returns 0.\nfunc getStartOrdinal(set *apps.StatefulSet) int {\n\tif utilfeature.DefaultFeatureGate.Enabled(features.StatefulSetStartOrdinal) {\n\t\tif set.Spec.Ordinals != nil {\n\t\t\treturn int(set.Spec.Ordinals.Start)\n\t\t}\n\t}\n\treturn 0\n}","line":{"from":90,"to":99}} {"id":100004669,"name":"getEndOrdinal","signature":"func getEndOrdinal(set *apps.StatefulSet) int","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// getEndOrdinal gets the last possible ordinal (inclusive).\nfunc getEndOrdinal(set *apps.StatefulSet) int {\n\treturn getStartOrdinal(set) + int(*set.Spec.Replicas) - 1\n}","line":{"from":101,"to":104}} {"id":100004670,"name":"podInOrdinalRange","signature":"func podInOrdinalRange(pod *v1.Pod, set *apps.StatefulSet) bool","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// podInOrdinalRange returns true if the pod ordinal is within the allowed\n// range of ordinals that this StatefulSet is set to control.\nfunc podInOrdinalRange(pod *v1.Pod, set *apps.StatefulSet) bool {\n\tordinal := getOrdinal(pod)\n\treturn ordinal \u003e= getStartOrdinal(set) \u0026\u0026 ordinal \u003c= getEndOrdinal(set)\n}","line":{"from":106,"to":111}} {"id":100004671,"name":"getPodName","signature":"func getPodName(set *apps.StatefulSet, ordinal int) string","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// getPodName gets the name of set's child Pod with an ordinal index of ordinal\nfunc getPodName(set *apps.StatefulSet, ordinal int) string {\n\treturn fmt.Sprintf(\"%s-%d\", set.Name, ordinal)\n}","line":{"from":113,"to":116}} {"id":100004672,"name":"getPersistentVolumeClaimName","signature":"func getPersistentVolumeClaimName(set *apps.StatefulSet, claim *v1.PersistentVolumeClaim, ordinal int) string","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// getPersistentVolumeClaimName gets the name of PersistentVolumeClaim for a Pod with an ordinal index of ordinal. claim\n// must be a PersistentVolumeClaim from set's VolumeClaims template.\nfunc getPersistentVolumeClaimName(set *apps.StatefulSet, claim *v1.PersistentVolumeClaim, ordinal int) string {\n\t// NOTE: This name format is used by the heuristics for zone spreading in ChooseZoneForVolume\n\treturn fmt.Sprintf(\"%s-%s-%d\", claim.Name, set.Name, ordinal)\n}","line":{"from":118,"to":123}} {"id":100004673,"name":"isMemberOf","signature":"func isMemberOf(set *apps.StatefulSet, pod *v1.Pod) bool","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// isMemberOf tests if pod is a member of set.\nfunc isMemberOf(set *apps.StatefulSet, pod *v1.Pod) bool {\n\treturn getParentName(pod) == set.Name\n}","line":{"from":125,"to":128}} {"id":100004674,"name":"identityMatches","signature":"func identityMatches(set *apps.StatefulSet, pod *v1.Pod) bool","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// identityMatches returns true if pod has a valid identity and network identity for a member of set.\nfunc identityMatches(set *apps.StatefulSet, pod *v1.Pod) bool {\n\tparent, ordinal := getParentNameAndOrdinal(pod)\n\treturn ordinal \u003e= 0 \u0026\u0026\n\t\tset.Name == parent \u0026\u0026\n\t\tpod.Name == getPodName(set, ordinal) \u0026\u0026\n\t\tpod.Namespace == set.Namespace \u0026\u0026\n\t\tpod.Labels[apps.StatefulSetPodNameLabel] == pod.Name\n}","line":{"from":130,"to":138}} {"id":100004675,"name":"storageMatches","signature":"func storageMatches(set *apps.StatefulSet, pod *v1.Pod) bool","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// storageMatches returns true if pod's Volumes cover the set of PersistentVolumeClaims\nfunc storageMatches(set *apps.StatefulSet, pod *v1.Pod) bool {\n\tordinal := getOrdinal(pod)\n\tif ordinal \u003c 0 {\n\t\treturn false\n\t}\n\tvolumes := make(map[string]v1.Volume, len(pod.Spec.Volumes))\n\tfor _, volume := range pod.Spec.Volumes {\n\t\tvolumes[volume.Name] = volume\n\t}\n\tfor _, claim := range set.Spec.VolumeClaimTemplates {\n\t\tvolume, found := volumes[claim.Name]\n\t\tif !found ||\n\t\t\tvolume.VolumeSource.PersistentVolumeClaim == nil ||\n\t\t\tvolume.VolumeSource.PersistentVolumeClaim.ClaimName !=\n\t\t\t\tgetPersistentVolumeClaimName(set, \u0026claim, ordinal) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":140,"to":160}} {"id":100004676,"name":"getPersistentVolumeClaimRetentionPolicy","signature":"func getPersistentVolumeClaimRetentionPolicy(set *apps.StatefulSet) apps.StatefulSetPersistentVolumeClaimRetentionPolicy","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// getPersistentVolumeClaimPolicy returns the PVC policy for a StatefulSet, returning a retain policy if the set policy is nil.\nfunc getPersistentVolumeClaimRetentionPolicy(set *apps.StatefulSet) apps.StatefulSetPersistentVolumeClaimRetentionPolicy {\n\tpolicy := apps.StatefulSetPersistentVolumeClaimRetentionPolicy{\n\t\tWhenDeleted: apps.RetainPersistentVolumeClaimRetentionPolicyType,\n\t\tWhenScaled: apps.RetainPersistentVolumeClaimRetentionPolicyType,\n\t}\n\tif set.Spec.PersistentVolumeClaimRetentionPolicy != nil {\n\t\tpolicy = *set.Spec.PersistentVolumeClaimRetentionPolicy\n\t}\n\treturn policy\n}","line":{"from":162,"to":172}} {"id":100004677,"name":"claimOwnerMatchesSetAndPod","signature":"func claimOwnerMatchesSetAndPod(claim *v1.PersistentVolumeClaim, set *apps.StatefulSet, pod *v1.Pod) bool","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// claimOwnerMatchesSetAndPod returns false if the ownerRefs of the claim are not set consistently with the\n// PVC deletion policy for the StatefulSet.\nfunc claimOwnerMatchesSetAndPod(claim *v1.PersistentVolumeClaim, set *apps.StatefulSet, pod *v1.Pod) bool {\n\tpolicy := getPersistentVolumeClaimRetentionPolicy(set)\n\tconst retain = apps.RetainPersistentVolumeClaimRetentionPolicyType\n\tconst delete = apps.DeletePersistentVolumeClaimRetentionPolicyType\n\tswitch {\n\tdefault:\n\t\tklog.Errorf(\"Unknown policy %v; treating as Retain\", set.Spec.PersistentVolumeClaimRetentionPolicy)\n\t\tfallthrough\n\tcase policy.WhenScaled == retain \u0026\u0026 policy.WhenDeleted == retain:\n\t\tif hasOwnerRef(claim, set) ||\n\t\t\thasOwnerRef(claim, pod) {\n\t\t\treturn false\n\t\t}\n\tcase policy.WhenScaled == retain \u0026\u0026 policy.WhenDeleted == delete:\n\t\tif !hasOwnerRef(claim, set) ||\n\t\t\thasOwnerRef(claim, pod) {\n\t\t\treturn false\n\t\t}\n\tcase policy.WhenScaled == delete \u0026\u0026 policy.WhenDeleted == retain:\n\t\tif hasOwnerRef(claim, set) {\n\t\t\treturn false\n\t\t}\n\t\tpodScaledDown := !podInOrdinalRange(pod, set)\n\t\tif podScaledDown != hasOwnerRef(claim, pod) {\n\t\t\treturn false\n\t\t}\n\tcase policy.WhenScaled == delete \u0026\u0026 policy.WhenDeleted == delete:\n\t\tpodScaledDown := !podInOrdinalRange(pod, set)\n\t\t// If a pod is scaled down, there should be no set ref and a pod ref;\n\t\t// if the pod is not scaled down it's the other way around.\n\t\tif podScaledDown == hasOwnerRef(claim, set) {\n\t\t\treturn false\n\t\t}\n\t\tif podScaledDown != hasOwnerRef(claim, pod) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":174,"to":214}} {"id":100004678,"name":"updateClaimOwnerRefForSetAndPod","signature":"func updateClaimOwnerRefForSetAndPod(claim *v1.PersistentVolumeClaim, set *apps.StatefulSet, pod *v1.Pod) bool","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// updateClaimOwnerRefForSetAndPod updates the ownerRefs for the claim according to the deletion policy of\n// the StatefulSet. Returns true if the claim was changed and should be updated and false otherwise.\nfunc updateClaimOwnerRefForSetAndPod(claim *v1.PersistentVolumeClaim, set *apps.StatefulSet, pod *v1.Pod) bool {\n\tneedsUpdate := false\n\t// Sometimes the version and kind are not set {pod,set}.TypeMeta. These are necessary for the ownerRef.\n\t// This is the case both in real clusters and the unittests.\n\t// TODO: there must be a better way to do this other than hardcoding the pod version?\n\tupdateMeta := func(tm *metav1.TypeMeta, kind string) {\n\t\tif tm.APIVersion == \"\" {\n\t\t\tif kind == \"StatefulSet\" {\n\t\t\t\ttm.APIVersion = \"apps/v1\"\n\t\t\t} else {\n\t\t\t\ttm.APIVersion = \"v1\"\n\t\t\t}\n\t\t}\n\t\tif tm.Kind == \"\" {\n\t\t\ttm.Kind = kind\n\t\t}\n\t}\n\tpodMeta := pod.TypeMeta\n\tupdateMeta(\u0026podMeta, \"Pod\")\n\tsetMeta := set.TypeMeta\n\tupdateMeta(\u0026setMeta, \"StatefulSet\")\n\tpolicy := getPersistentVolumeClaimRetentionPolicy(set)\n\tconst retain = apps.RetainPersistentVolumeClaimRetentionPolicyType\n\tconst delete = apps.DeletePersistentVolumeClaimRetentionPolicyType\n\tswitch {\n\tdefault:\n\t\tklog.Errorf(\"Unknown policy %v, treating as Retain\", set.Spec.PersistentVolumeClaimRetentionPolicy)\n\t\tfallthrough\n\tcase policy.WhenScaled == retain \u0026\u0026 policy.WhenDeleted == retain:\n\t\tneedsUpdate = removeOwnerRef(claim, set) || needsUpdate\n\t\tneedsUpdate = removeOwnerRef(claim, pod) || needsUpdate\n\tcase policy.WhenScaled == retain \u0026\u0026 policy.WhenDeleted == delete:\n\t\tneedsUpdate = setOwnerRef(claim, set, \u0026setMeta) || needsUpdate\n\t\tneedsUpdate = removeOwnerRef(claim, pod) || needsUpdate\n\tcase policy.WhenScaled == delete \u0026\u0026 policy.WhenDeleted == retain:\n\t\tneedsUpdate = removeOwnerRef(claim, set) || needsUpdate\n\t\tpodScaledDown := !podInOrdinalRange(pod, set)\n\t\tif podScaledDown {\n\t\t\tneedsUpdate = setOwnerRef(claim, pod, \u0026podMeta) || needsUpdate\n\t\t}\n\t\tif !podScaledDown {\n\t\t\tneedsUpdate = removeOwnerRef(claim, pod) || needsUpdate\n\t\t}\n\tcase policy.WhenScaled == delete \u0026\u0026 policy.WhenDeleted == delete:\n\t\tpodScaledDown := !podInOrdinalRange(pod, set)\n\t\tif podScaledDown {\n\t\t\tneedsUpdate = removeOwnerRef(claim, set) || needsUpdate\n\t\t\tneedsUpdate = setOwnerRef(claim, pod, \u0026podMeta) || needsUpdate\n\t\t}\n\t\tif !podScaledDown {\n\t\t\tneedsUpdate = setOwnerRef(claim, set, \u0026setMeta) || needsUpdate\n\t\t\tneedsUpdate = removeOwnerRef(claim, pod) || needsUpdate\n\t\t}\n\t}\n\treturn needsUpdate\n}","line":{"from":216,"to":273}} {"id":100004679,"name":"hasOwnerRef","signature":"func hasOwnerRef(target, owner metav1.Object) bool","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// hasOwnerRef returns true if target has an ownerRef to owner.\nfunc hasOwnerRef(target, owner metav1.Object) bool {\n\townerUID := owner.GetUID()\n\tfor _, ownerRef := range target.GetOwnerReferences() {\n\t\tif ownerRef.UID == ownerUID {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":275,"to":284}} {"id":100004680,"name":"hasStaleOwnerRef","signature":"func hasStaleOwnerRef(target, owner metav1.Object) bool","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// hasStaleOwnerRef returns true if target has a ref to owner that appears to be stale.\nfunc hasStaleOwnerRef(target, owner metav1.Object) bool {\n\tfor _, ownerRef := range target.GetOwnerReferences() {\n\t\tif ownerRef.Name == owner.GetName() \u0026\u0026 ownerRef.UID != owner.GetUID() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":286,"to":294}} {"id":100004681,"name":"setOwnerRef","signature":"func setOwnerRef(target, owner metav1.Object, ownerType *metav1.TypeMeta) bool","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// setOwnerRef adds owner to the ownerRefs of target, if necessary. Returns true if target needs to be\n// updated and false otherwise.\nfunc setOwnerRef(target, owner metav1.Object, ownerType *metav1.TypeMeta) bool {\n\tif hasOwnerRef(target, owner) {\n\t\treturn false\n\t}\n\townerRefs := append(\n\t\ttarget.GetOwnerReferences(),\n\t\tmetav1.OwnerReference{\n\t\t\tAPIVersion: ownerType.APIVersion,\n\t\t\tKind: ownerType.Kind,\n\t\t\tName: owner.GetName(),\n\t\t\tUID: owner.GetUID(),\n\t\t})\n\ttarget.SetOwnerReferences(ownerRefs)\n\treturn true\n}","line":{"from":296,"to":312}} {"id":100004682,"name":"removeOwnerRef","signature":"func removeOwnerRef(target, owner metav1.Object) bool","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// removeOwnerRef removes owner from the ownerRefs of target, if necessary. Returns true if target needs\n// to be updated and false otherwise.\nfunc removeOwnerRef(target, owner metav1.Object) bool {\n\tif !hasOwnerRef(target, owner) {\n\t\treturn false\n\t}\n\townerUID := owner.GetUID()\n\toldRefs := target.GetOwnerReferences()\n\tnewRefs := make([]metav1.OwnerReference, len(oldRefs)-1)\n\tskip := 0\n\tfor i := range oldRefs {\n\t\tif oldRefs[i].UID == ownerUID {\n\t\t\tskip = -1\n\t\t} else {\n\t\t\tnewRefs[i+skip] = oldRefs[i]\n\t\t}\n\t}\n\ttarget.SetOwnerReferences(newRefs)\n\treturn true\n}","line":{"from":314,"to":333}} {"id":100004683,"name":"getPersistentVolumeClaims","signature":"func getPersistentVolumeClaims(set *apps.StatefulSet, pod *v1.Pod) map[string]v1.PersistentVolumeClaim","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// getPersistentVolumeClaims gets a map of PersistentVolumeClaims to their template names, as defined in set. The\n// returned PersistentVolumeClaims are each constructed with a the name specific to the Pod. This name is determined\n// by getPersistentVolumeClaimName.\nfunc getPersistentVolumeClaims(set *apps.StatefulSet, pod *v1.Pod) map[string]v1.PersistentVolumeClaim {\n\tordinal := getOrdinal(pod)\n\ttemplates := set.Spec.VolumeClaimTemplates\n\tclaims := make(map[string]v1.PersistentVolumeClaim, len(templates))\n\tfor i := range templates {\n\t\tclaim := templates[i]\n\t\tclaim.Name = getPersistentVolumeClaimName(set, \u0026claim, ordinal)\n\t\tclaim.Namespace = set.Namespace\n\t\tif claim.Labels != nil {\n\t\t\tfor key, value := range set.Spec.Selector.MatchLabels {\n\t\t\t\tclaim.Labels[key] = value\n\t\t\t}\n\t\t} else {\n\t\t\tclaim.Labels = set.Spec.Selector.MatchLabels\n\t\t}\n\t\tclaims[templates[i].Name] = claim\n\t}\n\treturn claims\n}","line":{"from":335,"to":356}} {"id":100004684,"name":"updateStorage","signature":"func updateStorage(set *apps.StatefulSet, pod *v1.Pod)","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// updateStorage updates pod's Volumes to conform with the PersistentVolumeClaim of set's templates. If pod has\n// conflicting local Volumes these are replaced with Volumes that conform to the set's templates.\nfunc updateStorage(set *apps.StatefulSet, pod *v1.Pod) {\n\tcurrentVolumes := pod.Spec.Volumes\n\tclaims := getPersistentVolumeClaims(set, pod)\n\tnewVolumes := make([]v1.Volume, 0, len(claims))\n\tfor name, claim := range claims {\n\t\tnewVolumes = append(newVolumes, v1.Volume{\n\t\t\tName: name,\n\t\t\tVolumeSource: v1.VolumeSource{\n\t\t\t\tPersistentVolumeClaim: \u0026v1.PersistentVolumeClaimVolumeSource{\n\t\t\t\t\tClaimName: claim.Name,\n\t\t\t\t\t// TODO: Use source definition to set this value when we have one.\n\t\t\t\t\tReadOnly: false,\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t}\n\tfor i := range currentVolumes {\n\t\tif _, ok := claims[currentVolumes[i].Name]; !ok {\n\t\t\tnewVolumes = append(newVolumes, currentVolumes[i])\n\t\t}\n\t}\n\tpod.Spec.Volumes = newVolumes\n}","line":{"from":358,"to":382}} {"id":100004685,"name":"initIdentity","signature":"func initIdentity(set *apps.StatefulSet, pod *v1.Pod)","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"func initIdentity(set *apps.StatefulSet, pod *v1.Pod) {\n\tupdateIdentity(set, pod)\n\t// Set these immutable fields only on initial Pod creation, not updates.\n\tpod.Spec.Hostname = pod.Name\n\tpod.Spec.Subdomain = set.Spec.ServiceName\n}","line":{"from":384,"to":389}} {"id":100004686,"name":"updateIdentity","signature":"func updateIdentity(set *apps.StatefulSet, pod *v1.Pod)","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// updateIdentity updates pod's name, hostname, and subdomain, and StatefulSetPodNameLabel to conform to set's name\n// and headless service.\nfunc updateIdentity(set *apps.StatefulSet, pod *v1.Pod) {\n\tpod.Name = getPodName(set, getOrdinal(pod))\n\tpod.Namespace = set.Namespace\n\tif pod.Labels == nil {\n\t\tpod.Labels = make(map[string]string)\n\t}\n\tpod.Labels[apps.StatefulSetPodNameLabel] = pod.Name\n}","line":{"from":391,"to":400}} {"id":100004687,"name":"isRunningAndReady","signature":"func isRunningAndReady(pod *v1.Pod) bool","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// isRunningAndReady returns true if pod is in the PodRunning Phase, if it has a condition of PodReady.\nfunc isRunningAndReady(pod *v1.Pod) bool {\n\treturn pod.Status.Phase == v1.PodRunning \u0026\u0026 podutil.IsPodReady(pod)\n}","line":{"from":402,"to":405}} {"id":100004688,"name":"isRunningAndAvailable","signature":"func isRunningAndAvailable(pod *v1.Pod, minReadySeconds int32) bool","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"func isRunningAndAvailable(pod *v1.Pod, minReadySeconds int32) bool {\n\treturn podutil.IsPodAvailable(pod, minReadySeconds, metav1.Now())\n}","line":{"from":407,"to":409}} {"id":100004689,"name":"isCreated","signature":"func isCreated(pod *v1.Pod) bool","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// isCreated returns true if pod has been created and is maintained by the API server\nfunc isCreated(pod *v1.Pod) bool {\n\treturn pod.Status.Phase != \"\"\n}","line":{"from":411,"to":414}} {"id":100004690,"name":"isPending","signature":"func isPending(pod *v1.Pod) bool","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// isPending returns true if pod has a Phase of PodPending\nfunc isPending(pod *v1.Pod) bool {\n\treturn pod.Status.Phase == v1.PodPending\n}","line":{"from":416,"to":419}} {"id":100004691,"name":"isFailed","signature":"func isFailed(pod *v1.Pod) bool","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// isFailed returns true if pod has a Phase of PodFailed\nfunc isFailed(pod *v1.Pod) bool {\n\treturn pod.Status.Phase == v1.PodFailed\n}","line":{"from":421,"to":424}} {"id":100004692,"name":"isTerminating","signature":"func isTerminating(pod *v1.Pod) bool","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// isTerminating returns true if pod's DeletionTimestamp has been set\nfunc isTerminating(pod *v1.Pod) bool {\n\treturn pod.DeletionTimestamp != nil\n}","line":{"from":426,"to":429}} {"id":100004693,"name":"isHealthy","signature":"func isHealthy(pod *v1.Pod) bool","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// isHealthy returns true if pod is running and ready and has not been terminated\nfunc isHealthy(pod *v1.Pod) bool {\n\treturn isRunningAndReady(pod) \u0026\u0026 !isTerminating(pod)\n}","line":{"from":431,"to":434}} {"id":100004694,"name":"allowsBurst","signature":"func allowsBurst(set *apps.StatefulSet) bool","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// allowsBurst is true if the alpha burst annotation is set.\nfunc allowsBurst(set *apps.StatefulSet) bool {\n\treturn set.Spec.PodManagementPolicy == apps.ParallelPodManagement\n}","line":{"from":436,"to":439}} {"id":100004695,"name":"setPodRevision","signature":"func setPodRevision(pod *v1.Pod, revision string)","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// setPodRevision sets the revision of Pod to revision by adding the StatefulSetRevisionLabel\nfunc setPodRevision(pod *v1.Pod, revision string) {\n\tif pod.Labels == nil {\n\t\tpod.Labels = make(map[string]string)\n\t}\n\tpod.Labels[apps.StatefulSetRevisionLabel] = revision\n}","line":{"from":441,"to":447}} {"id":100004696,"name":"getPodRevision","signature":"func getPodRevision(pod *v1.Pod) string","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// getPodRevision gets the revision of Pod by inspecting the StatefulSetRevisionLabel. If pod has no revision the empty\n// string is returned.\nfunc getPodRevision(pod *v1.Pod) string {\n\tif pod.Labels == nil {\n\t\treturn \"\"\n\t}\n\treturn pod.Labels[apps.StatefulSetRevisionLabel]\n}","line":{"from":449,"to":456}} {"id":100004697,"name":"newStatefulSetPod","signature":"func newStatefulSetPod(set *apps.StatefulSet, ordinal int) *v1.Pod","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// newStatefulSetPod returns a new Pod conforming to the set's Spec with an identity generated from ordinal.\nfunc newStatefulSetPod(set *apps.StatefulSet, ordinal int) *v1.Pod {\n\tpod, _ := controller.GetPodFromTemplate(\u0026set.Spec.Template, set, metav1.NewControllerRef(set, controllerKind))\n\tpod.Name = getPodName(set, ordinal)\n\tinitIdentity(set, pod)\n\tupdateStorage(set, pod)\n\treturn pod\n}","line":{"from":458,"to":465}} {"id":100004698,"name":"newVersionedStatefulSetPod","signature":"func newVersionedStatefulSetPod(currentSet, updateSet *apps.StatefulSet, currentRevision, updateRevision string, ordinal int) *v1.Pod","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// newVersionedStatefulSetPod creates a new Pod for a StatefulSet. currentSet is the representation of the set at the\n// current revision. updateSet is the representation of the set at the updateRevision. currentRevision is the name of\n// the current revision. updateRevision is the name of the update revision. ordinal is the ordinal of the Pod. If the\n// returned error is nil, the returned Pod is valid.\nfunc newVersionedStatefulSetPod(currentSet, updateSet *apps.StatefulSet, currentRevision, updateRevision string, ordinal int) *v1.Pod {\n\tif currentSet.Spec.UpdateStrategy.Type == apps.RollingUpdateStatefulSetStrategyType \u0026\u0026\n\t\t(currentSet.Spec.UpdateStrategy.RollingUpdate == nil \u0026\u0026 ordinal \u003c (getStartOrdinal(currentSet)+int(currentSet.Status.CurrentReplicas))) ||\n\t\t(currentSet.Spec.UpdateStrategy.RollingUpdate != nil \u0026\u0026 ordinal \u003c (getStartOrdinal(currentSet)+int(*currentSet.Spec.UpdateStrategy.RollingUpdate.Partition))) {\n\t\tpod := newStatefulSetPod(currentSet, ordinal)\n\t\tsetPodRevision(pod, currentRevision)\n\t\treturn pod\n\t}\n\tpod := newStatefulSetPod(updateSet, ordinal)\n\tsetPodRevision(pod, updateRevision)\n\treturn pod\n}","line":{"from":467,"to":482}} {"id":100004699,"name":"Match","signature":"func Match(ss *apps.StatefulSet, history *apps.ControllerRevision) (bool, error)","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// Match check if the given StatefulSet's template matches the template stored in the given history.\nfunc Match(ss *apps.StatefulSet, history *apps.ControllerRevision) (bool, error) {\n\t// Encoding the set for the patch may update its GVK metadata, which causes data races if this\n\t// set is in an informer cache.\n\tclone := ss.DeepCopy()\n\tpatch, err := getPatch(clone)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn bytes.Equal(patch, history.Data.Raw), nil\n}","line":{"from":484,"to":494}} {"id":100004700,"name":"getPatch","signature":"func getPatch(set *apps.StatefulSet) ([]byte, error)","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// getPatch returns a strategic merge patch that can be applied to restore a StatefulSet to a\n// previous version. If the returned error is nil the patch is valid. The current state that we save is just the\n// PodSpecTemplate. We can modify this later to encompass more state (or less) and remain compatible with previously\n// recorded patches.\nfunc getPatch(set *apps.StatefulSet) ([]byte, error) {\n\tdata, err := runtime.Encode(patchCodec, set)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar raw map[string]interface{}\n\terr = json.Unmarshal(data, \u0026raw)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tobjCopy := make(map[string]interface{})\n\tspecCopy := make(map[string]interface{})\n\tspec := raw[\"spec\"].(map[string]interface{})\n\ttemplate := spec[\"template\"].(map[string]interface{})\n\tspecCopy[\"template\"] = template\n\ttemplate[\"$patch\"] = \"replace\"\n\tobjCopy[\"spec\"] = specCopy\n\tpatch, err := json.Marshal(objCopy)\n\treturn patch, err\n}","line":{"from":496,"to":519}} {"id":100004701,"name":"newRevision","signature":"func newRevision(set *apps.StatefulSet, revision int64, collisionCount *int32) (*apps.ControllerRevision, error)","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// newRevision creates a new ControllerRevision containing a patch that reapplies the target state of set.\n// The Revision of the returned ControllerRevision is set to revision. If the returned error is nil, the returned\n// ControllerRevision is valid. StatefulSet revisions are stored as patches that re-apply the current state of set\n// to a new StatefulSet using a strategic merge patch to replace the saved state of the new StatefulSet.\nfunc newRevision(set *apps.StatefulSet, revision int64, collisionCount *int32) (*apps.ControllerRevision, error) {\n\tpatch, err := getPatch(set)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcr, err := history.NewControllerRevision(set,\n\t\tcontrollerKind,\n\t\tset.Spec.Template.Labels,\n\t\truntime.RawExtension{Raw: patch},\n\t\trevision,\n\t\tcollisionCount)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif cr.ObjectMeta.Annotations == nil {\n\t\tcr.ObjectMeta.Annotations = make(map[string]string)\n\t}\n\tfor key, value := range set.Annotations {\n\t\tcr.ObjectMeta.Annotations[key] = value\n\t}\n\treturn cr, nil\n}","line":{"from":521,"to":546}} {"id":100004702,"name":"ApplyRevision","signature":"func ApplyRevision(set *apps.StatefulSet, revision *apps.ControllerRevision) (*apps.StatefulSet, error)","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// ApplyRevision returns a new StatefulSet constructed by restoring the state in revision to set. If the returned error\n// is nil, the returned StatefulSet is valid.\nfunc ApplyRevision(set *apps.StatefulSet, revision *apps.ControllerRevision) (*apps.StatefulSet, error) {\n\tclone := set.DeepCopy()\n\tpatched, err := strategicpatch.StrategicMergePatch([]byte(runtime.EncodeOrDie(patchCodec, clone)), revision.Data.Raw, clone)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trestoredSet := \u0026apps.StatefulSet{}\n\terr = json.Unmarshal(patched, restoredSet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn restoredSet, nil\n}","line":{"from":548,"to":562}} {"id":100004703,"name":"nextRevision","signature":"func nextRevision(revisions []*apps.ControllerRevision) int64","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// nextRevision finds the next valid revision number based on revisions. If the length of revisions\n// is 0 this is 1. Otherwise, it is 1 greater than the largest revision's Revision. This method\n// assumes that revisions has been sorted by Revision.\nfunc nextRevision(revisions []*apps.ControllerRevision) int64 {\n\tcount := len(revisions)\n\tif count \u003c= 0 {\n\t\treturn 1\n\t}\n\treturn revisions[count-1].Revision + 1\n}","line":{"from":564,"to":573}} {"id":100004704,"name":"inconsistentStatus","signature":"func inconsistentStatus(set *apps.StatefulSet, status *apps.StatefulSetStatus) bool","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// inconsistentStatus returns true if the ObservedGeneration of status is greater than set's\n// Generation or if any of the status's fields do not match those of set's status.\nfunc inconsistentStatus(set *apps.StatefulSet, status *apps.StatefulSetStatus) bool {\n\treturn status.ObservedGeneration \u003e set.Status.ObservedGeneration ||\n\t\tstatus.Replicas != set.Status.Replicas ||\n\t\tstatus.CurrentReplicas != set.Status.CurrentReplicas ||\n\t\tstatus.ReadyReplicas != set.Status.ReadyReplicas ||\n\t\tstatus.UpdatedReplicas != set.Status.UpdatedReplicas ||\n\t\tstatus.CurrentRevision != set.Status.CurrentRevision ||\n\t\tstatus.AvailableReplicas != set.Status.AvailableReplicas ||\n\t\tstatus.UpdateRevision != set.Status.UpdateRevision\n}","line":{"from":575,"to":586}} {"id":100004705,"name":"completeRollingUpdate","signature":"func completeRollingUpdate(set *apps.StatefulSet, status *apps.StatefulSetStatus)","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// completeRollingUpdate completes a rolling update when all of set's replica Pods have been updated\n// to the updateRevision. status's currentRevision is set to updateRevision and its' updateRevision\n// is set to the empty string. status's currentReplicas is set to updateReplicas and its updateReplicas\n// are set to 0.\nfunc completeRollingUpdate(set *apps.StatefulSet, status *apps.StatefulSetStatus) {\n\tif set.Spec.UpdateStrategy.Type == apps.RollingUpdateStatefulSetStrategyType \u0026\u0026\n\t\tstatus.UpdatedReplicas == status.Replicas \u0026\u0026\n\t\tstatus.ReadyReplicas == status.Replicas {\n\t\tstatus.CurrentReplicas = status.UpdatedReplicas\n\t\tstatus.CurrentRevision = status.UpdateRevision\n\t}\n}","line":{"from":588,"to":599}} {"id":100004706,"name":"Len","signature":"func (ao ascendingOrdinal) Len() int","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"func (ao ascendingOrdinal) Len() int {\n\treturn len(ao)\n}","line":{"from":606,"to":608}} {"id":100004707,"name":"Swap","signature":"func (ao ascendingOrdinal) Swap(i, j int)","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"func (ao ascendingOrdinal) Swap(i, j int) {\n\tao[i], ao[j] = ao[j], ao[i]\n}","line":{"from":610,"to":612}} {"id":100004708,"name":"Less","signature":"func (ao ascendingOrdinal) Less(i, j int) bool","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"func (ao ascendingOrdinal) Less(i, j int) bool {\n\treturn getOrdinal(ao[i]) \u003c getOrdinal(ao[j])\n}","line":{"from":614,"to":616}} {"id":100004709,"name":"Len","signature":"func (do descendingOrdinal) Len() int","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"func (do descendingOrdinal) Len() int {\n\treturn len(do)\n}","line":{"from":623,"to":625}} {"id":100004710,"name":"Swap","signature":"func (do descendingOrdinal) Swap(i, j int)","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"func (do descendingOrdinal) Swap(i, j int) {\n\tdo[i], do[j] = do[j], do[i]\n}","line":{"from":627,"to":629}} {"id":100004711,"name":"Less","signature":"func (do descendingOrdinal) Less(i, j int) bool","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"func (do descendingOrdinal) Less(i, j int) bool {\n\treturn getOrdinal(do[i]) \u003e getOrdinal(do[j])\n}","line":{"from":631,"to":633}} {"id":100004712,"name":"getStatefulSetMaxUnavailable","signature":"func getStatefulSetMaxUnavailable(maxUnavailable *intstr.IntOrString, replicaCount int) (int, error)","file":"pkg/controller/statefulset/stateful_set_utils.go","code":"// getStatefulSetMaxUnavailable calculates the real maxUnavailable number according to the replica count\n// and maxUnavailable from rollingUpdateStrategy. The number defaults to 1 if the maxUnavailable field is\n// not set, and it will be round down to at least 1 if the maxUnavailable value is a percentage.\n// Note that API validation has already guaranteed the maxUnavailable field to be \u003e1 if it is an integer\n// or 0% \u003c value \u003c= 100% if it is a percentage, so we don't have to consider other cases.\nfunc getStatefulSetMaxUnavailable(maxUnavailable *intstr.IntOrString, replicaCount int) (int, error) {\n\tmaxUnavailableNum, err := intstr.GetScaledValueFromIntOrPercent(intstr.ValueOrDefault(maxUnavailable, intstr.FromInt(1)), replicaCount, false)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\t// maxUnavailable might be zero for small percentage with round down.\n\t// So we have to enforce it not to be less than 1.\n\tif maxUnavailableNum \u003c 1 {\n\t\tmaxUnavailableNum = 1\n\t}\n\treturn maxUnavailableNum, nil\n}","line":{"from":635,"to":651}} {"id":100004713,"name":"NewStorageVersionGC","signature":"func NewStorageVersionGC(ctx context.Context, clientset kubernetes.Interface, leaseInformer coordinformers.LeaseInformer, storageVersionInformer apiserverinternalinformers.StorageVersionInformer) *Controller","file":"pkg/controller/storageversiongc/gc_controller.go","code":"// NewStorageVersionGC creates a new Controller.\nfunc NewStorageVersionGC(ctx context.Context, clientset kubernetes.Interface, leaseInformer coordinformers.LeaseInformer, storageVersionInformer apiserverinternalinformers.StorageVersionInformer) *Controller {\n\tc := \u0026Controller{\n\t\tkubeclientset: clientset,\n\t\tleaseLister: leaseInformer.Lister(),\n\t\tleasesSynced: leaseInformer.Informer().HasSynced,\n\t\tstorageVersionSynced: storageVersionInformer.Informer().HasSynced,\n\t\tleaseQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"storage_version_garbage_collector_leases\"),\n\t\tstorageVersionQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"storage_version_garbage_collector_storageversions\"),\n\t}\n\tlogger := klog.FromContext(ctx)\n\tleaseInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tc.onDeleteLease(logger, obj)\n\t\t},\n\t})\n\t// use the default resync period from the informer\n\tstorageVersionInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tc.onAddStorageVersion(logger, obj)\n\t\t},\n\t\tUpdateFunc: func(old, newObj interface{}) {\n\t\t\tc.onUpdateStorageVersion(logger, old, newObj)\n\t\t},\n\t})\n\n\treturn c\n}","line":{"from":57,"to":84}} {"id":100004714,"name":"Run","signature":"func (c *Controller) Run(ctx context.Context)","file":"pkg/controller/storageversiongc/gc_controller.go","code":"// Run starts one worker.\nfunc (c *Controller) Run(ctx context.Context) {\n\tlogger := klog.FromContext(ctx)\n\tdefer utilruntime.HandleCrash()\n\tdefer c.leaseQueue.ShutDown()\n\tdefer c.storageVersionQueue.ShutDown()\n\tdefer logger.Info(\"Shutting down storage version garbage collector\")\n\n\tlogger.Info(\"Starting storage version garbage collector\")\n\n\tif !cache.WaitForCacheSync(ctx.Done(), c.leasesSynced, c.storageVersionSynced) {\n\t\tutilruntime.HandleError(fmt.Errorf(\"timed out waiting for caches to sync\"))\n\t\treturn\n\t}\n\n\t// Identity lease deletion and storageversion update don't happen too often. Start one\n\t// worker for each of them.\n\t// runLeaseWorker handles legit identity lease deletion, while runStorageVersionWorker\n\t// handles storageversion creation/update with non-existing id. The latter should rarely\n\t// happen. It's okay for the two workers to conflict on update.\n\tgo wait.UntilWithContext(ctx, c.runLeaseWorker, time.Second)\n\tgo wait.UntilWithContext(ctx, c.runStorageVersionWorker, time.Second)\n\n\t\u003c-ctx.Done()\n}","line":{"from":86,"to":110}} {"id":100004715,"name":"runLeaseWorker","signature":"func (c *Controller) runLeaseWorker(ctx context.Context)","file":"pkg/controller/storageversiongc/gc_controller.go","code":"func (c *Controller) runLeaseWorker(ctx context.Context) {\n\tfor c.processNextLease(ctx) {\n\t}\n}","line":{"from":112,"to":115}} {"id":100004716,"name":"processNextLease","signature":"func (c *Controller) processNextLease(ctx context.Context) bool","file":"pkg/controller/storageversiongc/gc_controller.go","code":"func (c *Controller) processNextLease(ctx context.Context) bool {\n\tkey, quit := c.leaseQueue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.leaseQueue.Done(key)\n\n\terr := c.processDeletedLease(ctx, key.(string))\n\tif err == nil {\n\t\tc.leaseQueue.Forget(key)\n\t\treturn true\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"lease %v failed with: %v\", key, err))\n\tc.leaseQueue.AddRateLimited(key)\n\treturn true\n}","line":{"from":117,"to":133}} {"id":100004717,"name":"runStorageVersionWorker","signature":"func (c *Controller) runStorageVersionWorker(ctx context.Context)","file":"pkg/controller/storageversiongc/gc_controller.go","code":"func (c *Controller) runStorageVersionWorker(ctx context.Context) {\n\tfor c.processNextStorageVersion(ctx) {\n\t}\n}","line":{"from":135,"to":138}} {"id":100004718,"name":"processNextStorageVersion","signature":"func (c *Controller) processNextStorageVersion(ctx context.Context) bool","file":"pkg/controller/storageversiongc/gc_controller.go","code":"func (c *Controller) processNextStorageVersion(ctx context.Context) bool {\n\tkey, quit := c.storageVersionQueue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.storageVersionQueue.Done(key)\n\n\terr := c.syncStorageVersion(ctx, key.(string))\n\tif err == nil {\n\t\tc.storageVersionQueue.Forget(key)\n\t\treturn true\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"storage version %v failed with: %v\", key, err))\n\tc.storageVersionQueue.AddRateLimited(key)\n\treturn true\n}","line":{"from":140,"to":156}} {"id":100004719,"name":"processDeletedLease","signature":"func (c *Controller) processDeletedLease(ctx context.Context, name string) error","file":"pkg/controller/storageversiongc/gc_controller.go","code":"func (c *Controller) processDeletedLease(ctx context.Context, name string) error {\n\t_, err := c.kubeclientset.CoordinationV1().Leases(metav1.NamespaceSystem).Get(ctx, name, metav1.GetOptions{})\n\t// the lease isn't deleted, nothing we need to do here\n\tif err == nil {\n\t\treturn nil\n\t}\n\tif !apierrors.IsNotFound(err) {\n\t\treturn err\n\t}\n\t// the frequency of this call won't be too high because we only trigger on identity lease deletions\n\tstorageVersionList, err := c.kubeclientset.InternalV1alpha1().StorageVersions().List(ctx, metav1.ListOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar errors []error\n\tfor _, sv := range storageVersionList.Items {\n\t\tvar serverStorageVersions []apiserverinternalv1alpha1.ServerStorageVersion\n\t\thasStaleRecord := false\n\t\tfor _, ssv := range sv.Status.StorageVersions {\n\t\t\tif ssv.APIServerID == name {\n\t\t\t\thasStaleRecord = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tserverStorageVersions = append(serverStorageVersions, ssv)\n\t\t}\n\t\tif !hasStaleRecord {\n\t\t\tcontinue\n\t\t}\n\t\tif err := c.updateOrDeleteStorageVersion(ctx, \u0026sv, serverStorageVersions); err != nil {\n\t\t\terrors = append(errors, err)\n\t\t}\n\t}\n\n\treturn utilerrors.NewAggregate(errors)\n}","line":{"from":158,"to":193}} {"id":100004720,"name":"syncStorageVersion","signature":"func (c *Controller) syncStorageVersion(ctx context.Context, name string) error","file":"pkg/controller/storageversiongc/gc_controller.go","code":"func (c *Controller) syncStorageVersion(ctx context.Context, name string) error {\n\tsv, err := c.kubeclientset.InternalV1alpha1().StorageVersions().Get(ctx, name, metav1.GetOptions{})\n\tif apierrors.IsNotFound(err) {\n\t\t// The problematic storage version that was added/updated recently is gone.\n\t\t// Nothing we need to do here.\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\thasInvalidID := false\n\tvar serverStorageVersions []apiserverinternalv1alpha1.ServerStorageVersion\n\tfor _, v := range sv.Status.StorageVersions {\n\t\tlease, err := c.kubeclientset.CoordinationV1().Leases(metav1.NamespaceSystem).Get(ctx, v.APIServerID, metav1.GetOptions{})\n\t\tif err != nil || lease == nil || lease.Labels == nil ||\n\t\t\tlease.Labels[controlplane.IdentityLeaseComponentLabelKey] != controlplane.KubeAPIServer {\n\t\t\t// We cannot find a corresponding identity lease from apiserver as well.\n\t\t\t// We need to clean up this storage version.\n\t\t\thasInvalidID = true\n\t\t\tcontinue\n\t\t}\n\t\tserverStorageVersions = append(serverStorageVersions, v)\n\t}\n\tif !hasInvalidID {\n\t\treturn nil\n\t}\n\treturn c.updateOrDeleteStorageVersion(ctx, sv, serverStorageVersions)\n}","line":{"from":195,"to":223}} {"id":100004721,"name":"onAddStorageVersion","signature":"func (c *Controller) onAddStorageVersion(logger klog.Logger, obj interface{})","file":"pkg/controller/storageversiongc/gc_controller.go","code":"func (c *Controller) onAddStorageVersion(logger klog.Logger, obj interface{}) {\n\tcastObj := obj.(*apiserverinternalv1alpha1.StorageVersion)\n\tc.enqueueStorageVersion(logger, castObj)\n}","line":{"from":225,"to":228}} {"id":100004722,"name":"onUpdateStorageVersion","signature":"func (c *Controller) onUpdateStorageVersion(logger klog.Logger, oldObj, newObj interface{})","file":"pkg/controller/storageversiongc/gc_controller.go","code":"func (c *Controller) onUpdateStorageVersion(logger klog.Logger, oldObj, newObj interface{}) {\n\tcastNewObj := newObj.(*apiserverinternalv1alpha1.StorageVersion)\n\tc.enqueueStorageVersion(logger, castNewObj)\n}","line":{"from":230,"to":233}} {"id":100004723,"name":"enqueueStorageVersion","signature":"func (c *Controller) enqueueStorageVersion(logger klog.Logger, obj *apiserverinternalv1alpha1.StorageVersion)","file":"pkg/controller/storageversiongc/gc_controller.go","code":"// enqueueStorageVersion enqueues the storage version if it has entry for invalid apiserver\nfunc (c *Controller) enqueueStorageVersion(logger klog.Logger, obj *apiserverinternalv1alpha1.StorageVersion) {\n\tfor _, sv := range obj.Status.StorageVersions {\n\t\tlease, err := c.leaseLister.Leases(metav1.NamespaceSystem).Get(sv.APIServerID)\n\t\tif err != nil || lease == nil || lease.Labels == nil ||\n\t\t\tlease.Labels[controlplane.IdentityLeaseComponentLabelKey] != controlplane.KubeAPIServer {\n\t\t\t// we cannot find a corresponding identity lease in cache, enqueue the storageversion\n\t\t\tlogger.V(4).Info(\"Observed storage version with invalid apiserver entry\", \"objName\", obj.Name)\n\t\t\tc.storageVersionQueue.Add(obj.Name)\n\t\t\treturn\n\t\t}\n\t}\n}","line":{"from":235,"to":247}} {"id":100004724,"name":"onDeleteLease","signature":"func (c *Controller) onDeleteLease(logger klog.Logger, obj interface{})","file":"pkg/controller/storageversiongc/gc_controller.go","code":"func (c *Controller) onDeleteLease(logger klog.Logger, obj interface{}) {\n\tcastObj, ok := obj.(*coordinationv1.Lease)\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get object from tombstone %#v\", obj))\n\t\t\treturn\n\t\t}\n\t\tcastObj, ok = tombstone.Obj.(*coordinationv1.Lease)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"tombstone contained object that is not a Lease %#v\", obj))\n\t\t\treturn\n\t\t}\n\t}\n\n\tif castObj.Namespace == metav1.NamespaceSystem \u0026\u0026\n\t\tcastObj.Labels != nil \u0026\u0026\n\t\tcastObj.Labels[controlplane.IdentityLeaseComponentLabelKey] == controlplane.KubeAPIServer {\n\t\tlogger.V(4).Info(\"Observed lease deleted\", \"castObjName\", castObj.Name)\n\t\tc.enqueueLease(castObj)\n\t}\n}","line":{"from":249,"to":270}} {"id":100004725,"name":"enqueueLease","signature":"func (c *Controller) enqueueLease(obj *coordinationv1.Lease)","file":"pkg/controller/storageversiongc/gc_controller.go","code":"func (c *Controller) enqueueLease(obj *coordinationv1.Lease) {\n\tc.leaseQueue.Add(obj.Name)\n}","line":{"from":272,"to":274}} {"id":100004726,"name":"updateOrDeleteStorageVersion","signature":"func (c *Controller) updateOrDeleteStorageVersion(ctx context.Context, sv *apiserverinternalv1alpha1.StorageVersion, serverStorageVersions []apiserverinternalv1alpha1.ServerStorageVersion) error","file":"pkg/controller/storageversiongc/gc_controller.go","code":"func (c *Controller) updateOrDeleteStorageVersion(ctx context.Context, sv *apiserverinternalv1alpha1.StorageVersion, serverStorageVersions []apiserverinternalv1alpha1.ServerStorageVersion) error {\n\tif len(serverStorageVersions) == 0 {\n\t\treturn c.kubeclientset.InternalV1alpha1().StorageVersions().Delete(\n\t\t\tctx, sv.Name, metav1.DeleteOptions{})\n\t}\n\tsv.Status.StorageVersions = serverStorageVersions\n\tstorageversion.SetCommonEncodingVersion(sv)\n\t_, err := c.kubeclientset.InternalV1alpha1().StorageVersions().UpdateStatus(\n\t\tctx, sv, metav1.UpdateOptions{})\n\treturn err\n}","line":{"from":276,"to":286}} {"id":100004727,"name":"NewTTLController","signature":"func NewTTLController(ctx context.Context, nodeInformer informers.NodeInformer, kubeClient clientset.Interface) *Controller","file":"pkg/controller/ttl/ttl_controller.go","code":"// NewTTLController creates a new TTLController\nfunc NewTTLController(ctx context.Context, nodeInformer informers.NodeInformer, kubeClient clientset.Interface) *Controller {\n\tttlc := \u0026Controller{\n\t\tkubeClient: kubeClient,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"ttlcontroller\"),\n\t}\n\tlogger := klog.FromContext(ctx)\n\tnodeInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tttlc.addNode(logger, obj)\n\t\t},\n\t\tUpdateFunc: func(old, newObj interface{}) {\n\t\t\tttlc.updateNode(logger, old, newObj)\n\t\t},\n\t\tDeleteFunc: ttlc.deleteNode,\n\t})\n\n\tttlc.nodeStore = listers.NewNodeLister(nodeInformer.Informer().GetIndexer())\n\tttlc.hasSynced = nodeInformer.Informer().HasSynced\n\n\treturn ttlc\n}","line":{"from":80,"to":101}} {"id":100004728,"name":"Run","signature":"func (ttlc *Controller) Run(ctx context.Context, workers int)","file":"pkg/controller/ttl/ttl_controller.go","code":"// Run begins watching and syncing.\nfunc (ttlc *Controller) Run(ctx context.Context, workers int) {\n\tdefer utilruntime.HandleCrash()\n\tdefer ttlc.queue.ShutDown()\n\tlogger := klog.FromContext(ctx)\n\tlogger.Info(\"Starting TTL controller\")\n\tdefer logger.Info(\"Shutting down TTL controller\")\n\n\tif !cache.WaitForNamedCacheSync(\"TTL\", ctx.Done(), ttlc.hasSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.UntilWithContext(ctx, ttlc.worker, time.Second)\n\t}\n\n\t\u003c-ctx.Done()\n}","line":{"from":119,"to":136}} {"id":100004729,"name":"addNode","signature":"func (ttlc *Controller) addNode(logger klog.Logger, obj interface{})","file":"pkg/controller/ttl/ttl_controller.go","code":"func (ttlc *Controller) addNode(logger klog.Logger, obj interface{}) {\n\tnode, ok := obj.(*v1.Node)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unexpected object type: %v\", obj))\n\t\treturn\n\t}\n\n\tfunc() {\n\t\tttlc.lock.Lock()\n\t\tdefer ttlc.lock.Unlock()\n\t\tttlc.nodeCount++\n\t\tif ttlc.nodeCount \u003e ttlBoundaries[ttlc.boundaryStep].sizeMax {\n\t\t\tttlc.boundaryStep++\n\t\t\tttlc.desiredTTLSeconds = ttlBoundaries[ttlc.boundaryStep].ttlSeconds\n\t\t}\n\t}()\n\tttlc.enqueueNode(logger, node)\n}","line":{"from":138,"to":155}} {"id":100004730,"name":"updateNode","signature":"func (ttlc *Controller) updateNode(logger klog.Logger, _, newObj interface{})","file":"pkg/controller/ttl/ttl_controller.go","code":"func (ttlc *Controller) updateNode(logger klog.Logger, _, newObj interface{}) {\n\tnode, ok := newObj.(*v1.Node)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unexpected object type: %v\", newObj))\n\t\treturn\n\t}\n\t// Processing all updates of nodes guarantees that we will update\n\t// the ttl annotation, when cluster size changes.\n\t// We are relying on the fact that Kubelet is updating node status\n\t// every 10s (or generally every X seconds), which means that whenever\n\t// required, its ttl annotation should be updated within that period.\n\tttlc.enqueueNode(logger, node)\n}","line":{"from":157,"to":169}} {"id":100004731,"name":"deleteNode","signature":"func (ttlc *Controller) deleteNode(obj interface{})","file":"pkg/controller/ttl/ttl_controller.go","code":"func (ttlc *Controller) deleteNode(obj interface{}) {\n\t_, ok := obj.(*v1.Node)\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"unexpected object type: %v\", obj))\n\t\t\treturn\n\t\t}\n\t\t_, ok = tombstone.Obj.(*v1.Node)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"unexpected object types: %v\", obj))\n\t\t\treturn\n\t\t}\n\t}\n\n\tfunc() {\n\t\tttlc.lock.Lock()\n\t\tdefer ttlc.lock.Unlock()\n\t\tttlc.nodeCount--\n\t\tif ttlc.nodeCount \u003c ttlBoundaries[ttlc.boundaryStep].sizeMin {\n\t\t\tttlc.boundaryStep--\n\t\t\tttlc.desiredTTLSeconds = ttlBoundaries[ttlc.boundaryStep].ttlSeconds\n\t\t}\n\t}()\n\t// We are not processing the node, as it no longer exists.\n}","line":{"from":171,"to":196}} {"id":100004732,"name":"enqueueNode","signature":"func (ttlc *Controller) enqueueNode(logger klog.Logger, node *v1.Node)","file":"pkg/controller/ttl/ttl_controller.go","code":"func (ttlc *Controller) enqueueNode(logger klog.Logger, node *v1.Node) {\n\tkey, err := controller.KeyFunc(node)\n\tif err != nil {\n\t\tlogger.Error(nil, \"Couldn't get key for object\", \"object\", klog.KObj(node))\n\t\treturn\n\t}\n\tttlc.queue.Add(key)\n}","line":{"from":198,"to":205}} {"id":100004733,"name":"worker","signature":"func (ttlc *Controller) worker(ctx context.Context)","file":"pkg/controller/ttl/ttl_controller.go","code":"func (ttlc *Controller) worker(ctx context.Context) {\n\tfor ttlc.processItem(ctx) {\n\t}\n}","line":{"from":207,"to":210}} {"id":100004734,"name":"processItem","signature":"func (ttlc *Controller) processItem(ctx context.Context) bool","file":"pkg/controller/ttl/ttl_controller.go","code":"func (ttlc *Controller) processItem(ctx context.Context) bool {\n\tkey, quit := ttlc.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer ttlc.queue.Done(key)\n\n\terr := ttlc.updateNodeIfNeeded(ctx, key.(string))\n\tif err == nil {\n\t\tttlc.queue.Forget(key)\n\t\treturn true\n\t}\n\n\tttlc.queue.AddRateLimited(key)\n\tutilruntime.HandleError(err)\n\treturn true\n}","line":{"from":212,"to":228}} {"id":100004735,"name":"getDesiredTTLSeconds","signature":"func (ttlc *Controller) getDesiredTTLSeconds() int","file":"pkg/controller/ttl/ttl_controller.go","code":"func (ttlc *Controller) getDesiredTTLSeconds() int {\n\tttlc.lock.RLock()\n\tdefer ttlc.lock.RUnlock()\n\treturn ttlc.desiredTTLSeconds\n}","line":{"from":230,"to":234}} {"id":100004736,"name":"getIntFromAnnotation","signature":"func getIntFromAnnotation(ctx context.Context, node *v1.Node, annotationKey string) (int, bool)","file":"pkg/controller/ttl/ttl_controller.go","code":"func getIntFromAnnotation(ctx context.Context, node *v1.Node, annotationKey string) (int, bool) {\n\tif node.Annotations == nil {\n\t\treturn 0, false\n\t}\n\tannotationValue, ok := node.Annotations[annotationKey]\n\tif !ok {\n\t\treturn 0, false\n\t}\n\tintValue, err := strconv.Atoi(annotationValue)\n\tif err != nil {\n\t\tlogger := klog.FromContext(ctx)\n\t\tlogger.Info(\"Could not convert the value with annotation key for the node\", \"annotationValue\",\n\t\t\tannotationValue, \"annotationKey\", annotationKey, \"node\", klog.KObj(node))\n\t\treturn 0, false\n\t}\n\treturn intValue, true\n}","line":{"from":236,"to":252}} {"id":100004737,"name":"setIntAnnotation","signature":"func setIntAnnotation(node *v1.Node, annotationKey string, value int)","file":"pkg/controller/ttl/ttl_controller.go","code":"func setIntAnnotation(node *v1.Node, annotationKey string, value int) {\n\tif node.Annotations == nil {\n\t\tnode.Annotations = make(map[string]string)\n\t}\n\tnode.Annotations[annotationKey] = strconv.Itoa(value)\n}","line":{"from":254,"to":259}} {"id":100004738,"name":"patchNodeWithAnnotation","signature":"func (ttlc *Controller) patchNodeWithAnnotation(ctx context.Context, node *v1.Node, annotationKey string, value int) error","file":"pkg/controller/ttl/ttl_controller.go","code":"func (ttlc *Controller) patchNodeWithAnnotation(ctx context.Context, node *v1.Node, annotationKey string, value int) error {\n\toldData, err := json.Marshal(node)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsetIntAnnotation(node, annotationKey, value)\n\tnewData, err := json.Marshal(node)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpatchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, \u0026v1.Node{})\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = ttlc.kubeClient.CoreV1().Nodes().Patch(ctx, node.Name, types.StrategicMergePatchType, patchBytes, metav1.PatchOptions{})\n\tlogger := klog.FromContext(ctx)\n\tif err != nil {\n\t\tlogger.V(2).Info(\"Failed to change ttl annotation for node\", \"node\", klog.KObj(node), \"err\", err)\n\t\treturn err\n\t}\n\tlogger.V(2).Info(\"Changed ttl annotation\", \"node\", klog.KObj(node), \"TTL\", time.Duration(value)*time.Second)\n\treturn nil\n}","line":{"from":261,"to":283}} {"id":100004739,"name":"updateNodeIfNeeded","signature":"func (ttlc *Controller) updateNodeIfNeeded(ctx context.Context, key string) error","file":"pkg/controller/ttl/ttl_controller.go","code":"func (ttlc *Controller) updateNodeIfNeeded(ctx context.Context, key string) error {\n\tnode, err := ttlc.nodeStore.Get(key)\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\tdesiredTTL := ttlc.getDesiredTTLSeconds()\n\tcurrentTTL, ok := getIntFromAnnotation(ctx, node, v1.ObjectTTLAnnotationKey)\n\tif ok \u0026\u0026 currentTTL == desiredTTL {\n\t\treturn nil\n\t}\n\n\treturn ttlc.patchNodeWithAnnotation(ctx, node.DeepCopy(), v1.ObjectTTLAnnotationKey, desiredTTL)\n}","line":{"from":285,"to":301}} {"id":100004740,"name":"Convert_v1alpha1_TTLAfterFinishedControllerConfiguration_To_config_TTLAfterFinishedControllerConfiguration","signature":"func Convert_v1alpha1_TTLAfterFinishedControllerConfiguration_To_config_TTLAfterFinishedControllerConfiguration(in *v1alpha1.TTLAfterFinishedControllerConfiguration, out *config.TTLAfterFinishedControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/ttlafterfinished/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_TTLAfterFinishedControllerConfiguration_To_config_TTLAfterFinishedControllerConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_TTLAfterFinishedControllerConfiguration_To_config_TTLAfterFinishedControllerConfiguration(in *v1alpha1.TTLAfterFinishedControllerConfiguration, out *config.TTLAfterFinishedControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_TTLAfterFinishedControllerConfiguration_To_config_TTLAfterFinishedControllerConfiguration(in, out, s)\n}","line":{"from":32,"to":35}} {"id":100004741,"name":"Convert_config_TTLAfterFinishedControllerConfiguration_To_v1alpha1_TTLAfterFinishedControllerConfiguration","signature":"func Convert_config_TTLAfterFinishedControllerConfiguration_To_v1alpha1_TTLAfterFinishedControllerConfiguration(in *config.TTLAfterFinishedControllerConfiguration, out *v1alpha1.TTLAfterFinishedControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/ttlafterfinished/config/v1alpha1/conversion.go","code":"// Convert_config_TTLAfterFinishedControllerConfiguration_To_v1alpha1_TTLAfterFinishedControllerConfiguration is an autogenerated conversion function.\nfunc Convert_config_TTLAfterFinishedControllerConfiguration_To_v1alpha1_TTLAfterFinishedControllerConfiguration(in *config.TTLAfterFinishedControllerConfiguration, out *v1alpha1.TTLAfterFinishedControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_TTLAfterFinishedControllerConfiguration_To_v1alpha1_TTLAfterFinishedControllerConfiguration(in, out, s)\n}","line":{"from":37,"to":40}} {"id":100004742,"name":"RecommendedDefaultTTLAfterFinishedControllerConfiguration","signature":"func RecommendedDefaultTTLAfterFinishedControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.TTLAfterFinishedControllerConfiguration)","file":"pkg/controller/ttlafterfinished/config/v1alpha1/defaults.go","code":"// RecommendedDefaultTTLAfterFinishedControllerConfiguration defaults a pointer to a\n// TTLAfterFinishedControllerConfiguration struct. This will set the recommended default\n// values, but they may be subject to change between API versions. This function\n// is intentionally not registered in the scheme as a \"normal\" `SetDefaults_Foo`\n// function to allow consumers of this type to set whatever defaults for their\n// embedded configs. Forcing consumers to use these defaults would be problematic\n// as defaulting in the scheme is done as part of the conversion, and there would\n// be no easy way to opt-out. Instead, if you want to use this defaulting method\n// run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDefaultTTLAfterFinishedControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.TTLAfterFinishedControllerConfiguration) {\n\tif obj.ConcurrentTTLSyncs \u003c= 0 {\n\t\tobj.ConcurrentTTLSyncs = 5\n\t}\n}","line":{"from":23,"to":36}} {"id":100004743,"name":"Register","signature":"func Register()","file":"pkg/controller/ttlafterfinished/metrics/metrics.go","code":"// Register registers TTL after finished controller metrics.\nfunc Register() {\n\tregisterMetrics.Do(func() {\n\t\tlegacyregistry.MustRegister(JobDeletionDurationSeconds)\n\t})\n}","line":{"from":46,"to":51}} {"id":100004744,"name":"New","signature":"func New(ctx context.Context, jobInformer batchinformers.JobInformer, client clientset.Interface) *Controller","file":"pkg/controller/ttlafterfinished/ttlafterfinished_controller.go","code":"// New creates an instance of Controller\nfunc New(ctx context.Context, jobInformer batchinformers.JobInformer, client clientset.Interface) *Controller {\n\teventBroadcaster := record.NewBroadcaster()\n\teventBroadcaster.StartStructuredLogging(0)\n\teventBroadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: client.CoreV1().Events(\"\")})\n\n\tmetrics.Register()\n\n\ttc := \u0026Controller{\n\t\tclient: client,\n\t\trecorder: eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"ttl-after-finished-controller\"}),\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"ttl_jobs_to_delete\"),\n\t}\n\n\tlogger := klog.FromContext(ctx)\n\tjobInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\ttc.addJob(logger, obj)\n\t\t},\n\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\ttc.updateJob(logger, oldObj, newObj)\n\t\t},\n\t})\n\n\ttc.jLister = jobInformer.Lister()\n\ttc.jListerSynced = jobInformer.Informer().HasSynced\n\n\ttc.clock = clock.RealClock{}\n\n\treturn tc\n}","line":{"from":71,"to":101}} {"id":100004745,"name":"Run","signature":"func (tc *Controller) Run(ctx context.Context, workers int)","file":"pkg/controller/ttlafterfinished/ttlafterfinished_controller.go","code":"// Run starts the workers to clean up Jobs.\nfunc (tc *Controller) Run(ctx context.Context, workers int) {\n\tdefer utilruntime.HandleCrash()\n\tdefer tc.queue.ShutDown()\n\n\tlogger := klog.FromContext(ctx)\n\tlogger.Info(\"Starting TTL after finished controller\")\n\tdefer logger.Info(\"Shutting down TTL after finished controller\")\n\n\tif !cache.WaitForNamedCacheSync(\"TTL after finished\", ctx.Done(), tc.jListerSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.UntilWithContext(ctx, tc.worker, time.Second)\n\t}\n\n\t\u003c-ctx.Done()\n}","line":{"from":103,"to":121}} {"id":100004746,"name":"addJob","signature":"func (tc *Controller) addJob(logger klog.Logger, obj interface{})","file":"pkg/controller/ttlafterfinished/ttlafterfinished_controller.go","code":"func (tc *Controller) addJob(logger klog.Logger, obj interface{}) {\n\tjob := obj.(*batch.Job)\n\tlogger.V(4).Info(\"Adding job\", \"job\", klog.KObj(job))\n\n\tif job.DeletionTimestamp == nil \u0026\u0026 needsCleanup(job) {\n\t\ttc.enqueue(logger, job)\n\t}\n\n}","line":{"from":123,"to":131}} {"id":100004747,"name":"updateJob","signature":"func (tc *Controller) updateJob(logger klog.Logger, old, cur interface{})","file":"pkg/controller/ttlafterfinished/ttlafterfinished_controller.go","code":"func (tc *Controller) updateJob(logger klog.Logger, old, cur interface{}) {\n\tjob := cur.(*batch.Job)\n\tlogger.V(4).Info(\"Updating job\", \"job\", klog.KObj(job))\n\n\tif job.DeletionTimestamp == nil \u0026\u0026 needsCleanup(job) {\n\t\ttc.enqueue(logger, job)\n\t}\n}","line":{"from":133,"to":140}} {"id":100004748,"name":"enqueue","signature":"func (tc *Controller) enqueue(logger klog.Logger, job *batch.Job)","file":"pkg/controller/ttlafterfinished/ttlafterfinished_controller.go","code":"func (tc *Controller) enqueue(logger klog.Logger, job *batch.Job) {\n\tlogger.V(4).Info(\"Add job to cleanup\", \"job\", klog.KObj(job))\n\tkey, err := controller.KeyFunc(job)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get key for object %#v: %v\", job, err))\n\t\treturn\n\t}\n\n\ttc.queue.Add(key)\n}","line":{"from":142,"to":151}} {"id":100004749,"name":"enqueueAfter","signature":"func (tc *Controller) enqueueAfter(job *batch.Job, after time.Duration)","file":"pkg/controller/ttlafterfinished/ttlafterfinished_controller.go","code":"func (tc *Controller) enqueueAfter(job *batch.Job, after time.Duration) {\n\tkey, err := controller.KeyFunc(job)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get key for object %#v: %v\", job, err))\n\t\treturn\n\t}\n\n\ttc.queue.AddAfter(key, after)\n}","line":{"from":153,"to":161}} {"id":100004750,"name":"worker","signature":"func (tc *Controller) worker(ctx context.Context)","file":"pkg/controller/ttlafterfinished/ttlafterfinished_controller.go","code":"func (tc *Controller) worker(ctx context.Context) {\n\tfor tc.processNextWorkItem(ctx) {\n\t}\n}","line":{"from":163,"to":166}} {"id":100004751,"name":"processNextWorkItem","signature":"func (tc *Controller) processNextWorkItem(ctx context.Context) bool","file":"pkg/controller/ttlafterfinished/ttlafterfinished_controller.go","code":"func (tc *Controller) processNextWorkItem(ctx context.Context) bool {\n\tkey, quit := tc.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer tc.queue.Done(key)\n\n\terr := tc.processJob(ctx, key.(string))\n\ttc.handleErr(err, key)\n\n\treturn true\n}","line":{"from":168,"to":179}} {"id":100004752,"name":"handleErr","signature":"func (tc *Controller) handleErr(err error, key interface{})","file":"pkg/controller/ttlafterfinished/ttlafterfinished_controller.go","code":"func (tc *Controller) handleErr(err error, key interface{}) {\n\tif err == nil {\n\t\ttc.queue.Forget(key)\n\t\treturn\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"error cleaning up Job %v, will retry: %v\", key, err))\n\ttc.queue.AddRateLimited(key)\n}","line":{"from":181,"to":189}} {"id":100004753,"name":"processJob","signature":"func (tc *Controller) processJob(ctx context.Context, key string) error","file":"pkg/controller/ttlafterfinished/ttlafterfinished_controller.go","code":"// processJob will check the Job's state and TTL and delete the Job when it\n// finishes and its TTL after finished has expired. If the Job hasn't finished or\n// its TTL hasn't expired, it will be added to the queue after the TTL is expected\n// to expire.\n// This function is not meant to be invoked concurrently with the same key.\nfunc (tc *Controller) processJob(ctx context.Context, key string) error {\n\tnamespace, name, err := cache.SplitMetaNamespaceKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Ignore the Jobs that are already deleted or being deleted, or the ones that don't need clean up.\n\tjob, err := tc.jLister.Jobs(namespace).Get(name)\n\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"Checking if Job is ready for cleanup\", \"job\", klog.KRef(namespace, name))\n\n\tif errors.IsNotFound(err) {\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif expiredAt, err := tc.processTTL(logger, job); err != nil {\n\t\treturn err\n\t} else if expiredAt == nil {\n\t\treturn nil\n\t}\n\n\t// The Job's TTL is assumed to have expired, but the Job TTL might be stale.\n\t// Before deleting the Job, do a final sanity check.\n\t// If TTL is modified before we do this check, we cannot be sure if the TTL truly expires.\n\t// The latest Job may have a different UID, but it's fine because the checks will be run again.\n\tfresh, err := tc.client.BatchV1().Jobs(namespace).Get(ctx, name, metav1.GetOptions{})\n\tif errors.IsNotFound(err) {\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Use the latest Job TTL to see if the TTL truly expires.\n\texpiredAt, err := tc.processTTL(logger, fresh)\n\tif err != nil {\n\t\treturn err\n\t} else if expiredAt == nil {\n\t\treturn nil\n\t}\n\t// Cascade deletes the Jobs if TTL truly expires.\n\tpolicy := metav1.DeletePropagationForeground\n\toptions := metav1.DeleteOptions{\n\t\tPropagationPolicy: \u0026policy,\n\t\tPreconditions: \u0026metav1.Preconditions{UID: \u0026fresh.UID},\n\t}\n\tlogger.V(4).Info(\"Cleaning up Job\", \"job\", klog.KObj(fresh))\n\tif err := tc.client.BatchV1().Jobs(fresh.Namespace).Delete(ctx, fresh.Name, options); err != nil {\n\t\treturn err\n\t}\n\tmetrics.JobDeletionDurationSeconds.Observe(time.Since(*expiredAt).Seconds())\n\treturn nil\n}","line":{"from":191,"to":251}} {"id":100004754,"name":"processTTL","signature":"func (tc *Controller) processTTL(logger klog.Logger, job *batch.Job) (expiredAt *time.Time, err error)","file":"pkg/controller/ttlafterfinished/ttlafterfinished_controller.go","code":"// processTTL checks whether a given Job's TTL has expired, and add it to the queue after the TTL is expected to expire\n// if the TTL will expire later.\nfunc (tc *Controller) processTTL(logger klog.Logger, job *batch.Job) (expiredAt *time.Time, err error) {\n\n\t// We don't care about the Jobs that are going to be deleted, or the ones that don't need clean up.\n\tif job.DeletionTimestamp != nil || !needsCleanup(job) {\n\t\treturn nil, nil\n\t}\n\n\tnow := tc.clock.Now()\n\tt, e, err := timeLeft(logger, job, \u0026now)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// TTL has expired\n\tif *t \u003c= 0 {\n\t\treturn e, nil\n\t}\n\n\ttc.enqueueAfter(job, *t)\n\treturn nil, nil\n}","line":{"from":253,"to":275}} {"id":100004755,"name":"needsCleanup","signature":"func needsCleanup(j *batch.Job) bool","file":"pkg/controller/ttlafterfinished/ttlafterfinished_controller.go","code":"// needsCleanup checks whether a Job has finished and has a TTL set.\nfunc needsCleanup(j *batch.Job) bool {\n\treturn j.Spec.TTLSecondsAfterFinished != nil \u0026\u0026 jobutil.IsJobFinished(j)\n}","line":{"from":277,"to":280}} {"id":100004756,"name":"getFinishAndExpireTime","signature":"func getFinishAndExpireTime(j *batch.Job) (*time.Time, *time.Time, error)","file":"pkg/controller/ttlafterfinished/ttlafterfinished_controller.go","code":"func getFinishAndExpireTime(j *batch.Job) (*time.Time, *time.Time, error) {\n\tif !needsCleanup(j) {\n\t\treturn nil, nil, fmt.Errorf(\"job %s/%s should not be cleaned up\", j.Namespace, j.Name)\n\t}\n\tt, err := jobFinishTime(j)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tfinishAt := t.Time\n\texpireAt := finishAt.Add(time.Duration(*j.Spec.TTLSecondsAfterFinished) * time.Second)\n\treturn \u0026finishAt, \u0026expireAt, nil\n}","line":{"from":282,"to":293}} {"id":100004757,"name":"timeLeft","signature":"func timeLeft(logger klog.Logger, j *batch.Job, since *time.Time) (*time.Duration, *time.Time, error)","file":"pkg/controller/ttlafterfinished/ttlafterfinished_controller.go","code":"func timeLeft(logger klog.Logger, j *batch.Job, since *time.Time) (*time.Duration, *time.Time, error) {\n\tfinishAt, expireAt, err := getFinishAndExpireTime(j)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif finishAt.After(*since) {\n\t\tlogger.Info(\"Warning: Found Job finished in the future. This is likely due to time skew in the cluster. Job cleanup will be deferred.\", \"job\", klog.KObj(j))\n\t}\n\tremaining := expireAt.Sub(*since)\n\tlogger.V(4).Info(\"Found Job finished\", \"job\", klog.KObj(j), \"finishTime\", finishAt.UTC(), \"remainingTTL\", remaining, \"startTime\", since.UTC(), \"deadlineTTL\", expireAt.UTC())\n\treturn \u0026remaining, expireAt, nil\n}","line":{"from":295,"to":307}} {"id":100004758,"name":"jobFinishTime","signature":"func jobFinishTime(finishedJob *batch.Job) (metav1.Time, error)","file":"pkg/controller/ttlafterfinished/ttlafterfinished_controller.go","code":"// jobFinishTime takes an already finished Job and returns the time it finishes.\nfunc jobFinishTime(finishedJob *batch.Job) (metav1.Time, error) {\n\tfor _, c := range finishedJob.Status.Conditions {\n\t\tif (c.Type == batch.JobComplete || c.Type == batch.JobFailed) \u0026\u0026 c.Status == v1.ConditionTrue {\n\t\t\tfinishAt := c.LastTransitionTime\n\t\t\tif finishAt.IsZero() {\n\t\t\t\treturn metav1.Time{}, fmt.Errorf(\"unable to find the time when the Job %s/%s finished\", finishedJob.Namespace, finishedJob.Name)\n\t\t\t}\n\t\t\treturn c.LastTransitionTime, nil\n\t\t}\n\t}\n\n\t// This should never happen if the Jobs has finished\n\treturn metav1.Time{}, fmt.Errorf(\"unable to find the status of the finished Job %s/%s\", finishedJob.Namespace, finishedJob.Name)\n}","line":{"from":309,"to":323}} {"id":100004759,"name":"GetPodServiceMemberships","signature":"func GetPodServiceMemberships(serviceLister v1listers.ServiceLister, pod *v1.Pod) (sets.String, error)","file":"pkg/controller/util/endpoint/controller_utils.go","code":"// GetPodServiceMemberships returns a set of Service keys for Services that have\n// a selector matching the given pod.\nfunc GetPodServiceMemberships(serviceLister v1listers.ServiceLister, pod *v1.Pod) (sets.String, error) {\n\tset := sets.String{}\n\tservices, err := serviceLister.Services(pod.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn set, err\n\t}\n\n\tfor _, service := range services {\n\t\tif service.Spec.Selector == nil {\n\t\t\t// if the service has a nil selector this means selectors match nothing, not everything.\n\t\t\tcontinue\n\t\t}\n\t\tkey, err := controller.KeyFunc(service)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif labels.ValidatedSetSelector(service.Spec.Selector).Matches(labels.Set(pod.Labels)) {\n\t\t\tset.Insert(key)\n\t\t}\n\t}\n\treturn set, nil\n}","line":{"from":51,"to":74}} {"id":100004760,"name":"NewPortMapKey","signature":"func NewPortMapKey(endpointPorts []discovery.EndpointPort) PortMapKey","file":"pkg/controller/util/endpoint/controller_utils.go","code":"// NewPortMapKey generates a PortMapKey from endpoint ports.\nfunc NewPortMapKey(endpointPorts []discovery.EndpointPort) PortMapKey {\n\tsort.Sort(portsInOrder(endpointPorts))\n\treturn PortMapKey(DeepHashObjectToString(endpointPorts))\n}","line":{"from":79,"to":83}} {"id":100004761,"name":"DeepHashObjectToString","signature":"func DeepHashObjectToString(objectToWrite interface{}) string","file":"pkg/controller/util/endpoint/controller_utils.go","code":"// DeepHashObjectToString creates a unique hash string from a go object.\nfunc DeepHashObjectToString(objectToWrite interface{}) string {\n\thasher := md5.New()\n\thash.DeepHashObject(hasher, objectToWrite)\n\treturn hex.EncodeToString(hasher.Sum(nil)[0:])\n}","line":{"from":85,"to":90}} {"id":100004762,"name":"ShouldPodBeInEndpoints","signature":"func ShouldPodBeInEndpoints(pod *v1.Pod, includeTerminating bool) bool","file":"pkg/controller/util/endpoint/controller_utils.go","code":"// ShouldPodBeInEndpoints returns true if a specified pod should be in an\n// Endpoints or EndpointSlice resource. Terminating pods are only included if\n// includeTerminating is true.\nfunc ShouldPodBeInEndpoints(pod *v1.Pod, includeTerminating bool) bool {\n\t// \"Terminal\" describes when a Pod is complete (in a succeeded or failed phase).\n\t// This is distinct from the \"Terminating\" condition which represents when a Pod\n\t// is being terminated (metadata.deletionTimestamp is non nil).\n\tif podutil.IsPodTerminal(pod) {\n\t\treturn false\n\t}\n\n\tif len(pod.Status.PodIP) == 0 \u0026\u0026 len(pod.Status.PodIPs) == 0 {\n\t\treturn false\n\t}\n\n\tif !includeTerminating \u0026\u0026 pod.DeletionTimestamp != nil {\n\t\treturn false\n\t}\n\n\treturn true\n}","line":{"from":92,"to":112}} {"id":100004763,"name":"ShouldSetHostname","signature":"func ShouldSetHostname(pod *v1.Pod, svc *v1.Service) bool","file":"pkg/controller/util/endpoint/controller_utils.go","code":"// ShouldSetHostname returns true if the Hostname attribute should be set on an\n// Endpoints Address or EndpointSlice Endpoint.\nfunc ShouldSetHostname(pod *v1.Pod, svc *v1.Service) bool {\n\treturn len(pod.Spec.Hostname) \u003e 0 \u0026\u0026 pod.Spec.Subdomain == svc.Name \u0026\u0026 svc.Namespace == pod.Namespace\n}","line":{"from":114,"to":118}} {"id":100004764,"name":"podEndpointsChanged","signature":"func podEndpointsChanged(oldPod, newPod *v1.Pod) (bool, bool)","file":"pkg/controller/util/endpoint/controller_utils.go","code":"// podEndpointsChanged returns two boolean values. The first is true if the pod has\n// changed in a way that may change existing endpoints. The second value is true if the\n// pod has changed in a way that may affect which Services it matches.\nfunc podEndpointsChanged(oldPod, newPod *v1.Pod) (bool, bool) {\n\t// Check if the pod labels have changed, indicating a possible\n\t// change in the service membership\n\tlabelsChanged := false\n\tif !reflect.DeepEqual(newPod.Labels, oldPod.Labels) ||\n\t\t!hostNameAndDomainAreEqual(newPod, oldPod) {\n\t\tlabelsChanged = true\n\t}\n\n\t// If the pod's deletion timestamp is set, remove endpoint from ready address.\n\tif newPod.DeletionTimestamp != oldPod.DeletionTimestamp {\n\t\treturn true, labelsChanged\n\t}\n\t// If the pod's readiness has changed, the associated endpoint address\n\t// will move from the unready endpoints set to the ready endpoints.\n\t// So for the purposes of an endpoint, a readiness change on a pod\n\t// means we have a changed pod.\n\tif podutil.IsPodReady(oldPod) != podutil.IsPodReady(newPod) {\n\t\treturn true, labelsChanged\n\t}\n\n\t// Check if the pod IPs have changed\n\tif len(oldPod.Status.PodIPs) != len(newPod.Status.PodIPs) {\n\t\treturn true, labelsChanged\n\t}\n\tfor i := range oldPod.Status.PodIPs {\n\t\tif oldPod.Status.PodIPs[i].IP != newPod.Status.PodIPs[i].IP {\n\t\t\treturn true, labelsChanged\n\t\t}\n\t}\n\n\t// Endpoints may also reference a pod's Name, Namespace, UID, and NodeName, but\n\t// the first three are immutable, and NodeName is immutable once initially set,\n\t// which happens before the pod gets an IP.\n\n\treturn false, labelsChanged\n}","line":{"from":120,"to":159}} {"id":100004765,"name":"GetServicesToUpdateOnPodChange","signature":"func GetServicesToUpdateOnPodChange(serviceLister v1listers.ServiceLister, old, cur interface{}) sets.String","file":"pkg/controller/util/endpoint/controller_utils.go","code":"// GetServicesToUpdateOnPodChange returns a set of Service keys for Services\n// that have potentially been affected by a change to this pod.\nfunc GetServicesToUpdateOnPodChange(serviceLister v1listers.ServiceLister, old, cur interface{}) sets.String {\n\tnewPod := cur.(*v1.Pod)\n\toldPod := old.(*v1.Pod)\n\tif newPod.ResourceVersion == oldPod.ResourceVersion {\n\t\t// Periodic resync will send update events for all known pods.\n\t\t// Two different versions of the same pod will always have different RVs\n\t\treturn sets.String{}\n\t}\n\n\tpodChanged, labelsChanged := podEndpointsChanged(oldPod, newPod)\n\n\t// If both the pod and labels are unchanged, no update is needed\n\tif !podChanged \u0026\u0026 !labelsChanged {\n\t\treturn sets.String{}\n\t}\n\n\tservices, err := GetPodServiceMemberships(serviceLister, newPod)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unable to get pod %s/%s's service memberships: %v\", newPod.Namespace, newPod.Name, err))\n\t\treturn sets.String{}\n\t}\n\n\tif labelsChanged {\n\t\toldServices, err := GetPodServiceMemberships(serviceLister, oldPod)\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"unable to get pod %s/%s's service memberships: %v\", newPod.Namespace, newPod.Name, err))\n\t\t}\n\t\tservices = determineNeededServiceUpdates(oldServices, services, podChanged)\n\t}\n\n\treturn services\n}","line":{"from":161,"to":194}} {"id":100004766,"name":"GetPodFromDeleteAction","signature":"func GetPodFromDeleteAction(obj interface{}) *v1.Pod","file":"pkg/controller/util/endpoint/controller_utils.go","code":"// GetPodFromDeleteAction returns a pointer to a pod if one can be derived from\n// obj (could be a *v1.Pod, or a DeletionFinalStateUnknown marker item).\nfunc GetPodFromDeleteAction(obj interface{}) *v1.Pod {\n\tif pod, ok := obj.(*v1.Pod); ok {\n\t\t// Enqueue all the services that the pod used to be a member of.\n\t\t// This is the same thing we do when we add a pod.\n\t\treturn pod\n\t}\n\t// If we reached here it means the pod was deleted but its final state is unrecorded.\n\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get object from tombstone %#v\", obj))\n\t\treturn nil\n\t}\n\tpod, ok := tombstone.Obj.(*v1.Pod)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"tombstone contained object that is not a Pod: %#v\", obj))\n\t\treturn nil\n\t}\n\treturn pod\n}","line":{"from":196,"to":216}} {"id":100004767,"name":"hostNameAndDomainAreEqual","signature":"func hostNameAndDomainAreEqual(pod1, pod2 *v1.Pod) bool","file":"pkg/controller/util/endpoint/controller_utils.go","code":"func hostNameAndDomainAreEqual(pod1, pod2 *v1.Pod) bool {\n\treturn pod1.Spec.Hostname == pod2.Spec.Hostname \u0026\u0026\n\t\tpod1.Spec.Subdomain == pod2.Spec.Subdomain\n}","line":{"from":218,"to":221}} {"id":100004768,"name":"determineNeededServiceUpdates","signature":"func determineNeededServiceUpdates(oldServices, services sets.String, podChanged bool) sets.String","file":"pkg/controller/util/endpoint/controller_utils.go","code":"func determineNeededServiceUpdates(oldServices, services sets.String, podChanged bool) sets.String {\n\tif podChanged {\n\t\t// if the labels and pod changed, all services need to be updated\n\t\tservices = services.Union(oldServices)\n\t} else {\n\t\t// if only the labels changed, services not common to both the new\n\t\t// and old service set (the disjuntive union) need to be updated\n\t\tservices = services.Difference(oldServices).Union(oldServices.Difference(services))\n\t}\n\treturn services\n}","line":{"from":223,"to":233}} {"id":100004769,"name":"Len","signature":"func (sl portsInOrder) Len() int { return len(sl) }","file":"pkg/controller/util/endpoint/controller_utils.go","code":"func (sl portsInOrder) Len() int { return len(sl) }","line":{"from":238,"to":238}} {"id":100004770,"name":"Swap","signature":"func (sl portsInOrder) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] }","file":"pkg/controller/util/endpoint/controller_utils.go","code":"func (sl portsInOrder) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] }","line":{"from":239,"to":239}} {"id":100004771,"name":"Less","signature":"func (sl portsInOrder) Less(i, j int) bool","file":"pkg/controller/util/endpoint/controller_utils.go","code":"func (sl portsInOrder) Less(i, j int) bool {\n\th1 := DeepHashObjectToString(sl[i])\n\th2 := DeepHashObjectToString(sl[j])\n\treturn h1 \u003c h2\n}","line":{"from":240,"to":244}} {"id":100004772,"name":"EndpointsEqualBeyondHash","signature":"func EndpointsEqualBeyondHash(ep1, ep2 *discovery.Endpoint) bool","file":"pkg/controller/util/endpoint/controller_utils.go","code":"// EndpointsEqualBeyondHash returns true if endpoints have equal attributes\n// but excludes equality checks that would have already been covered with\n// endpoint hashing (see hashEndpoint func for more info) and ignores difference\n// in ResourceVersion of TargetRef.\nfunc EndpointsEqualBeyondHash(ep1, ep2 *discovery.Endpoint) bool {\n\tif stringPtrChanged(ep1.NodeName, ep2.NodeName) {\n\t\treturn false\n\t}\n\n\tif stringPtrChanged(ep1.Zone, ep2.Zone) {\n\t\treturn false\n\t}\n\n\tif boolPtrChanged(ep1.Conditions.Ready, ep2.Conditions.Ready) {\n\t\treturn false\n\t}\n\n\tif boolPtrChanged(ep1.Conditions.Serving, ep2.Conditions.Serving) {\n\t\treturn false\n\t}\n\n\tif boolPtrChanged(ep1.Conditions.Terminating, ep2.Conditions.Terminating) {\n\t\treturn false\n\t}\n\n\tif !semanticIgnoreResourceVersion.DeepEqual(ep1.TargetRef, ep2.TargetRef) {\n\t\treturn false\n\t}\n\n\treturn true\n}","line":{"from":246,"to":276}} {"id":100004773,"name":"boolPtrChanged","signature":"func boolPtrChanged(ptr1, ptr2 *bool) bool","file":"pkg/controller/util/endpoint/controller_utils.go","code":"// boolPtrChanged returns true if a set of bool pointers have different values.\nfunc boolPtrChanged(ptr1, ptr2 *bool) bool {\n\tif (ptr1 == nil) != (ptr2 == nil) {\n\t\treturn true\n\t}\n\tif ptr1 != nil \u0026\u0026 ptr2 != nil \u0026\u0026 *ptr1 != *ptr2 {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":278,"to":287}} {"id":100004774,"name":"stringPtrChanged","signature":"func stringPtrChanged(ptr1, ptr2 *string) bool","file":"pkg/controller/util/endpoint/controller_utils.go","code":"// stringPtrChanged returns true if a set of string pointers have different values.\nfunc stringPtrChanged(ptr1, ptr2 *string) bool {\n\tif (ptr1 == nil) != (ptr2 == nil) {\n\t\treturn true\n\t}\n\tif ptr1 != nil \u0026\u0026 ptr2 != nil \u0026\u0026 *ptr1 != *ptr2 {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":289,"to":298}} {"id":100004775,"name":"EndpointSubsetsEqualIgnoreResourceVersion","signature":"func EndpointSubsetsEqualIgnoreResourceVersion(subsets1, subsets2 []v1.EndpointSubset) bool","file":"pkg/controller/util/endpoint/controller_utils.go","code":"// EndpointSubsetsEqualIgnoreResourceVersion returns true if EndpointSubsets\n// have equal attributes but excludes ResourceVersion of Pod.\nfunc EndpointSubsetsEqualIgnoreResourceVersion(subsets1, subsets2 []v1.EndpointSubset) bool {\n\treturn semanticIgnoreResourceVersion.DeepEqual(subsets1, subsets2)\n}","line":{"from":300,"to":304}} {"id":100004776,"name":"NewTriggerTimeTracker","signature":"func NewTriggerTimeTracker() *TriggerTimeTracker","file":"pkg/controller/util/endpoint/trigger_time_tracker.go","code":"// NewTriggerTimeTracker creates a new instance of the TriggerTimeTracker.\nfunc NewTriggerTimeTracker() *TriggerTimeTracker {\n\treturn \u0026TriggerTimeTracker{\n\t\tServiceStates: make(map[ServiceKey]ServiceState),\n\t}\n}","line":{"from":47,"to":52}} {"id":100004777,"name":"ComputeEndpointLastChangeTriggerTime","signature":"func (t *TriggerTimeTracker) ComputeEndpointLastChangeTriggerTime(","file":"pkg/controller/util/endpoint/trigger_time_tracker.go","code":"// ComputeEndpointLastChangeTriggerTime updates the state of the Service/Endpoint\n// object being synced and returns the time that should be exported as the\n// EndpointsLastChangeTriggerTime annotation.\n//\n// If the method returns a 'zero' time the EndpointsLastChangeTriggerTime\n// annotation shouldn't be exported.\n//\n// Please note that this function may compute a wrong value if the same object\n// (pod/service) changes multiple times between two consecutive syncs.\n//\n// Important: This method is go-routing safe but only when called for different\n// keys. The method shouldn't be called concurrently for the same key! This\n// contract is fulfilled in the current implementation of the endpoint(slice)\n// controller.\nfunc (t *TriggerTimeTracker) ComputeEndpointLastChangeTriggerTime(\n\tnamespace string, service *v1.Service, pods []*v1.Pod) time.Time {\n\n\tkey := ServiceKey{Namespace: namespace, Name: service.Name}\n\t// As there won't be any concurrent calls for the same key, we need to guard\n\t// access only to the serviceStates map.\n\tt.mutex.Lock()\n\tstate, wasKnown := t.ServiceStates[key]\n\tt.mutex.Unlock()\n\n\t// Update the state before returning.\n\tdefer func() {\n\t\tt.mutex.Lock()\n\t\tt.ServiceStates[key] = state\n\t\tt.mutex.Unlock()\n\t}()\n\n\t// minChangedTriggerTime is the min trigger time of all trigger times that\n\t// have changed since the last sync.\n\tvar minChangedTriggerTime time.Time\n\tpodTriggerTimes := make(map[string]time.Time)\n\tfor _, pod := range pods {\n\t\tif podTriggerTime := getPodTriggerTime(pod); !podTriggerTime.IsZero() {\n\t\t\tpodTriggerTimes[pod.Name] = podTriggerTime\n\t\t\tif podTriggerTime.After(state.lastPodTriggerTimes[pod.Name]) {\n\t\t\t\t// Pod trigger time has changed since the last sync, update minChangedTriggerTime.\n\t\t\t\tminChangedTriggerTime = min(minChangedTriggerTime, podTriggerTime)\n\t\t\t}\n\t\t}\n\t}\n\tserviceTriggerTime := getServiceTriggerTime(service)\n\tif serviceTriggerTime.After(state.lastServiceTriggerTime) {\n\t\t// Service trigger time has changed since the last sync, update minChangedTriggerTime.\n\t\tminChangedTriggerTime = min(minChangedTriggerTime, serviceTriggerTime)\n\t}\n\n\tstate.lastPodTriggerTimes = podTriggerTimes\n\tstate.lastServiceTriggerTime = serviceTriggerTime\n\n\tif !wasKnown {\n\t\t// New Service, use Service creationTimestamp.\n\t\treturn service.CreationTimestamp.Time\n\t}\n\n\t// Regular update of endpoint objects, return min of changed trigger times.\n\treturn minChangedTriggerTime\n}","line":{"from":70,"to":130}} {"id":100004778,"name":"DeleteService","signature":"func (t *TriggerTimeTracker) DeleteService(namespace, name string)","file":"pkg/controller/util/endpoint/trigger_time_tracker.go","code":"// DeleteService deletes service state stored in this util.\nfunc (t *TriggerTimeTracker) DeleteService(namespace, name string) {\n\tkey := ServiceKey{Namespace: namespace, Name: name}\n\tt.mutex.Lock()\n\tdefer t.mutex.Unlock()\n\tdelete(t.ServiceStates, key)\n}","line":{"from":132,"to":138}} {"id":100004779,"name":"getPodTriggerTime","signature":"func getPodTriggerTime(pod *v1.Pod) (triggerTime time.Time)","file":"pkg/controller/util/endpoint/trigger_time_tracker.go","code":"// getPodTriggerTime returns the time of the pod change (trigger) that resulted\n// or will result in the endpoint object change.\nfunc getPodTriggerTime(pod *v1.Pod) (triggerTime time.Time) {\n\tif readyCondition := podutil.GetPodReadyCondition(pod.Status); readyCondition != nil {\n\t\ttriggerTime = readyCondition.LastTransitionTime.Time\n\t}\n\treturn triggerTime\n}","line":{"from":140,"to":147}} {"id":100004780,"name":"getServiceTriggerTime","signature":"func getServiceTriggerTime(service *v1.Service) (triggerTime time.Time)","file":"pkg/controller/util/endpoint/trigger_time_tracker.go","code":"// getServiceTriggerTime returns the time of the service change (trigger) that\n// resulted or will result in the endpoint change.\nfunc getServiceTriggerTime(service *v1.Service) (triggerTime time.Time) {\n\treturn service.CreationTimestamp.Time\n}","line":{"from":149,"to":153}} {"id":100004781,"name":"min","signature":"func min(currentMin, newValue time.Time) time.Time","file":"pkg/controller/util/endpoint/trigger_time_tracker.go","code":"// min returns minimum of the currentMin and newValue or newValue if the currentMin is not set.\nfunc min(currentMin, newValue time.Time) time.Time {\n\tif currentMin.IsZero() || newValue.Before(currentMin) {\n\t\treturn newValue\n\t}\n\treturn currentMin\n}","line":{"from":155,"to":161}} {"id":100004782,"name":"hashEndpoint","signature":"func hashEndpoint(endpoint *discovery.Endpoint) endpointHash","file":"pkg/controller/util/endpointslice/endpointset.go","code":"func hashEndpoint(endpoint *discovery.Endpoint) endpointHash {\n\tsort.Strings(endpoint.Addresses)\n\thashObj := endpointHashObj{Addresses: endpoint.Addresses}\n\tif endpoint.Hostname != nil {\n\t\thashObj.Hostname = *endpoint.Hostname\n\t}\n\tif endpoint.TargetRef != nil {\n\t\thashObj.Namespace = endpoint.TargetRef.Namespace\n\t\thashObj.Name = endpoint.TargetRef.Name\n\t}\n\n\treturn endpointHash(endpointutil.DeepHashObjectToString(hashObj))\n}","line":{"from":37,"to":49}} {"id":100004783,"name":"Insert","signature":"func (s EndpointSet) Insert(items ...*discovery.Endpoint) EndpointSet","file":"pkg/controller/util/endpointslice/endpointset.go","code":"// Insert adds items to the set.\nfunc (s EndpointSet) Insert(items ...*discovery.Endpoint) EndpointSet {\n\tfor _, item := range items {\n\t\ts[hashEndpoint(item)] = item\n\t}\n\treturn s\n}","line":{"from":54,"to":60}} {"id":100004784,"name":"Delete","signature":"func (s EndpointSet) Delete(items ...*discovery.Endpoint) EndpointSet","file":"pkg/controller/util/endpointslice/endpointset.go","code":"// Delete removes all items from the set.\nfunc (s EndpointSet) Delete(items ...*discovery.Endpoint) EndpointSet {\n\tfor _, item := range items {\n\t\tdelete(s, hashEndpoint(item))\n\t}\n\treturn s\n}","line":{"from":62,"to":68}} {"id":100004785,"name":"Has","signature":"func (s EndpointSet) Has(item *discovery.Endpoint) bool","file":"pkg/controller/util/endpointslice/endpointset.go","code":"// Has returns true if and only if item is contained in the set.\nfunc (s EndpointSet) Has(item *discovery.Endpoint) bool {\n\t_, contained := s[hashEndpoint(item)]\n\treturn contained\n}","line":{"from":70,"to":74}} {"id":100004786,"name":"Get","signature":"func (s EndpointSet) Get(item *discovery.Endpoint) *discovery.Endpoint","file":"pkg/controller/util/endpointslice/endpointset.go","code":"// Returns an endpoint matching the hash if contained in the set.\nfunc (s EndpointSet) Get(item *discovery.Endpoint) *discovery.Endpoint {\n\treturn s[hashEndpoint(item)]\n}","line":{"from":76,"to":79}} {"id":100004787,"name":"UnsortedList","signature":"func (s EndpointSet) UnsortedList() []*discovery.Endpoint","file":"pkg/controller/util/endpointslice/endpointset.go","code":"// UnsortedList returns the slice with contents in random order.\nfunc (s EndpointSet) UnsortedList() []*discovery.Endpoint {\n\tendpoints := make([]*discovery.Endpoint, 0, len(s))\n\tfor _, endpoint := range s {\n\t\tendpoints = append(endpoints, endpoint)\n\t}\n\treturn endpoints\n}","line":{"from":81,"to":88}} {"id":100004788,"name":"PopAny","signature":"func (s EndpointSet) PopAny() (*discovery.Endpoint, bool)","file":"pkg/controller/util/endpointslice/endpointset.go","code":"// Returns a single element from the set.\nfunc (s EndpointSet) PopAny() (*discovery.Endpoint, bool) {\n\tfor _, endpoint := range s {\n\t\ts.Delete(endpoint)\n\t\treturn endpoint, true\n\t}\n\treturn nil, false\n}","line":{"from":90,"to":97}} {"id":100004789,"name":"Len","signature":"func (s EndpointSet) Len() int","file":"pkg/controller/util/endpointslice/endpointset.go","code":"// Len returns the size of the set.\nfunc (s EndpointSet) Len() int {\n\treturn len(s)\n}","line":{"from":99,"to":102}} {"id":100004790,"name":"NewEndpointSliceTracker","signature":"func NewEndpointSliceTracker() *EndpointSliceTracker","file":"pkg/controller/util/endpointslice/endpointslice_tracker.go","code":"// NewEndpointSliceTracker creates and initializes a new endpointSliceTracker.\nfunc NewEndpointSliceTracker() *EndpointSliceTracker {\n\treturn \u0026EndpointSliceTracker{\n\t\tgenerationsByService: map[types.NamespacedName]GenerationsBySlice{},\n\t}\n}","line":{"from":47,"to":52}} {"id":100004791,"name":"Has","signature":"func (est *EndpointSliceTracker) Has(endpointSlice *discovery.EndpointSlice) bool","file":"pkg/controller/util/endpointslice/endpointslice_tracker.go","code":"// Has returns true if the endpointSliceTracker has a generation for the\n// provided EndpointSlice.\nfunc (est *EndpointSliceTracker) Has(endpointSlice *discovery.EndpointSlice) bool {\n\test.lock.Lock()\n\tdefer est.lock.Unlock()\n\n\tgfs, ok := est.GenerationsForSliceUnsafe(endpointSlice)\n\tif !ok {\n\t\treturn false\n\t}\n\t_, ok = gfs[endpointSlice.UID]\n\treturn ok\n}","line":{"from":54,"to":66}} {"id":100004792,"name":"ShouldSync","signature":"func (est *EndpointSliceTracker) ShouldSync(endpointSlice *discovery.EndpointSlice) bool","file":"pkg/controller/util/endpointslice/endpointslice_tracker.go","code":"// ShouldSync returns true if this endpointSliceTracker does not have a\n// generation for the provided EndpointSlice or it is greater than the\n// generation of the tracked EndpointSlice.\nfunc (est *EndpointSliceTracker) ShouldSync(endpointSlice *discovery.EndpointSlice) bool {\n\test.lock.Lock()\n\tdefer est.lock.Unlock()\n\n\tgfs, ok := est.GenerationsForSliceUnsafe(endpointSlice)\n\tif !ok {\n\t\treturn true\n\t}\n\tg, ok := gfs[endpointSlice.UID]\n\treturn !ok || endpointSlice.Generation \u003e g\n}","line":{"from":68,"to":81}} {"id":100004793,"name":"StaleSlices","signature":"func (est *EndpointSliceTracker) StaleSlices(service *v1.Service, endpointSlices []*discovery.EndpointSlice) bool","file":"pkg/controller/util/endpointslice/endpointslice_tracker.go","code":"// StaleSlices returns true if any of the following are true:\n// 1. One or more of the provided EndpointSlices have older generations than the\n// corresponding tracked ones.\n// 2. The tracker is expecting one or more of the provided EndpointSlices to be\n// deleted. (EndpointSlices that have already been marked for deletion are ignored here.)\n// 3. The tracker is tracking EndpointSlices that have not been provided.\nfunc (est *EndpointSliceTracker) StaleSlices(service *v1.Service, endpointSlices []*discovery.EndpointSlice) bool {\n\test.lock.Lock()\n\tdefer est.lock.Unlock()\n\n\tnn := types.NamespacedName{Name: service.Name, Namespace: service.Namespace}\n\tgfs, ok := est.generationsByService[nn]\n\tif !ok {\n\t\treturn false\n\t}\n\tprovidedSlices := map[types.UID]int64{}\n\tfor _, endpointSlice := range endpointSlices {\n\t\tprovidedSlices[endpointSlice.UID] = endpointSlice.Generation\n\t\tg, ok := gfs[endpointSlice.UID]\n\t\tif ok \u0026\u0026 (g == deletionExpected || g \u003e endpointSlice.Generation) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor uid, generation := range gfs {\n\t\tif generation == deletionExpected {\n\t\t\tcontinue\n\t\t}\n\t\t_, ok := providedSlices[uid]\n\t\tif !ok {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":83,"to":116}} {"id":100004794,"name":"Update","signature":"func (est *EndpointSliceTracker) Update(endpointSlice *discovery.EndpointSlice)","file":"pkg/controller/util/endpointslice/endpointslice_tracker.go","code":"// Update adds or updates the generation in this endpointSliceTracker for the\n// provided EndpointSlice.\nfunc (est *EndpointSliceTracker) Update(endpointSlice *discovery.EndpointSlice) {\n\test.lock.Lock()\n\tdefer est.lock.Unlock()\n\n\tgfs, ok := est.GenerationsForSliceUnsafe(endpointSlice)\n\n\tif !ok {\n\t\tgfs = GenerationsBySlice{}\n\t\test.generationsByService[getServiceNN(endpointSlice)] = gfs\n\t}\n\tgfs[endpointSlice.UID] = endpointSlice.Generation\n}","line":{"from":118,"to":131}} {"id":100004795,"name":"DeleteService","signature":"func (est *EndpointSliceTracker) DeleteService(namespace, name string)","file":"pkg/controller/util/endpointslice/endpointslice_tracker.go","code":"// DeleteService removes the set of generations tracked for the Service.\nfunc (est *EndpointSliceTracker) DeleteService(namespace, name string) {\n\test.lock.Lock()\n\tdefer est.lock.Unlock()\n\n\tserviceNN := types.NamespacedName{Name: name, Namespace: namespace}\n\tdelete(est.generationsByService, serviceNN)\n}","line":{"from":133,"to":140}} {"id":100004796,"name":"ExpectDeletion","signature":"func (est *EndpointSliceTracker) ExpectDeletion(endpointSlice *discovery.EndpointSlice)","file":"pkg/controller/util/endpointslice/endpointslice_tracker.go","code":"// ExpectDeletion sets the generation to deletionExpected in this\n// endpointSliceTracker for the provided EndpointSlice.\nfunc (est *EndpointSliceTracker) ExpectDeletion(endpointSlice *discovery.EndpointSlice) {\n\test.lock.Lock()\n\tdefer est.lock.Unlock()\n\n\tgfs, ok := est.GenerationsForSliceUnsafe(endpointSlice)\n\n\tif !ok {\n\t\tgfs = GenerationsBySlice{}\n\t\test.generationsByService[getServiceNN(endpointSlice)] = gfs\n\t}\n\tgfs[endpointSlice.UID] = deletionExpected\n}","line":{"from":142,"to":155}} {"id":100004797,"name":"HandleDeletion","signature":"func (est *EndpointSliceTracker) HandleDeletion(endpointSlice *discovery.EndpointSlice) bool","file":"pkg/controller/util/endpointslice/endpointslice_tracker.go","code":"// HandleDeletion removes the generation in this endpointSliceTracker for the\n// provided EndpointSlice. This returns true if the tracker expected this\n// EndpointSlice to be deleted and false if not.\nfunc (est *EndpointSliceTracker) HandleDeletion(endpointSlice *discovery.EndpointSlice) bool {\n\test.lock.Lock()\n\tdefer est.lock.Unlock()\n\n\tgfs, ok := est.GenerationsForSliceUnsafe(endpointSlice)\n\n\tif ok {\n\t\tg, ok := gfs[endpointSlice.UID]\n\t\tdelete(gfs, endpointSlice.UID)\n\t\tif ok \u0026\u0026 g != deletionExpected {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}","line":{"from":157,"to":175}} {"id":100004798,"name":"GenerationsForSliceUnsafe","signature":"func (est *EndpointSliceTracker) GenerationsForSliceUnsafe(endpointSlice *discovery.EndpointSlice) (GenerationsBySlice, bool)","file":"pkg/controller/util/endpointslice/endpointslice_tracker.go","code":"// GenerationsForSliceUnsafe returns the generations for the Service\n// corresponding to the provided EndpointSlice, and a bool to indicate if it\n// exists. A lock must be applied before calling this function.\nfunc (est *EndpointSliceTracker) GenerationsForSliceUnsafe(endpointSlice *discovery.EndpointSlice) (GenerationsBySlice, bool) {\n\tserviceNN := getServiceNN(endpointSlice)\n\tgenerations, ok := est.generationsByService[serviceNN]\n\treturn generations, ok\n}","line":{"from":177,"to":184}} {"id":100004799,"name":"getServiceNN","signature":"func getServiceNN(endpointSlice *discovery.EndpointSlice) types.NamespacedName","file":"pkg/controller/util/endpointslice/endpointslice_tracker.go","code":"// getServiceNN returns a namespaced name for the Service corresponding to the\n// provided EndpointSlice.\nfunc getServiceNN(endpointSlice *discovery.EndpointSlice) types.NamespacedName {\n\tserviceName, _ := endpointSlice.Labels[discovery.LabelServiceName]\n\treturn types.NamespacedName{Name: serviceName, Namespace: endpointSlice.Namespace}\n}","line":{"from":186,"to":191}} {"id":100004800,"name":"NewStaleInformerCache","signature":"func NewStaleInformerCache(msg string) *StaleInformerCache","file":"pkg/controller/util/endpointslice/errors.go","code":"// NewStaleInformerCache return StaleInformerCache with error mes\nfunc NewStaleInformerCache(msg string) *StaleInformerCache {\n\treturn \u0026StaleInformerCache{msg}\n}","line":{"from":25,"to":28}} {"id":100004801,"name":"Error","signature":"func (e *StaleInformerCache) Error() string { return e.msg }","file":"pkg/controller/util/endpointslice/errors.go","code":"func (e *StaleInformerCache) Error() string { return e.msg }","line":{"from":30,"to":30}} {"id":100004802,"name":"IsStaleInformerCacheErr","signature":"func IsStaleInformerCacheErr(err error) bool","file":"pkg/controller/util/endpointslice/errors.go","code":"func IsStaleInformerCacheErr(err error) bool {\n\t_, ok := err.(*StaleInformerCache)\n\treturn ok\n}","line":{"from":32,"to":35}} {"id":100004803,"name":"EndpointReady","signature":"func EndpointReady(endpoint discovery.Endpoint) bool","file":"pkg/controller/util/endpointslice/utils.go","code":"// EndpointReady returns true if an Endpoint has the Ready condition set to\n// true.\nfunc EndpointReady(endpoint discovery.Endpoint) bool {\n\treturn endpoint.Conditions.Ready != nil \u0026\u0026 *endpoint.Conditions.Ready\n}","line":{"from":23,"to":27}} {"id":100004804,"name":"DeletePods","signature":"func DeletePods(ctx context.Context, kubeClient clientset.Interface, pods []*v1.Pod, recorder record.EventRecorder, nodeName, nodeUID string, daemonStore appsv1listers.DaemonSetLister) (bool, error)","file":"pkg/controller/util/node/controller_utils.go","code":"// DeletePods will delete all pods from master running on given node,\n// and return true if any pods were deleted, or were found pending\n// deletion.\nfunc DeletePods(ctx context.Context, kubeClient clientset.Interface, pods []*v1.Pod, recorder record.EventRecorder, nodeName, nodeUID string, daemonStore appsv1listers.DaemonSetLister) (bool, error) {\n\tremaining := false\n\tvar updateErrList []error\n\tlogger := klog.FromContext(ctx)\n\n\tif len(pods) \u003e 0 {\n\t\tRecordNodeEvent(ctx, recorder, nodeName, nodeUID, v1.EventTypeNormal, \"DeletingAllPods\", fmt.Sprintf(\"Deleting all Pods from Node %v.\", nodeName))\n\t}\n\n\tfor i := range pods {\n\t\t// Defensive check, also needed for tests.\n\t\tif pods[i].Spec.NodeName != nodeName {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Pod will be modified, so making copy is required.\n\t\tpod := pods[i].DeepCopy()\n\t\t// Set reason and message in the pod object.\n\t\tif _, err := SetPodTerminationReason(ctx, kubeClient, pod, nodeName); err != nil {\n\t\t\tif apierrors.IsConflict(err) {\n\t\t\t\tupdateErrList = append(updateErrList,\n\t\t\t\t\tfmt.Errorf(\"update status failed for pod %q: %v\", format.Pod(pod), err))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\t// if the pod has already been marked for deletion, we still return true that there are remaining pods.\n\t\tif pod.DeletionGracePeriodSeconds != nil {\n\t\t\tremaining = true\n\t\t\tcontinue\n\t\t}\n\t\t// if the pod is managed by a daemonset, ignore it\n\t\tif _, err := daemonStore.GetPodDaemonSets(pod); err == nil {\n\t\t\t// No error means at least one daemonset was found\n\t\t\tcontinue\n\t\t}\n\n\t\tlogger.V(2).Info(\"Starting deletion of pod\", \"pod\", klog.KObj(pod))\n\t\trecorder.Eventf(pod, v1.EventTypeNormal, \"NodeControllerEviction\", \"Marking for deletion Pod %s from Node %s\", pod.Name, nodeName)\n\t\tif err := kubeClient.CoreV1().Pods(pod.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{}); err != nil {\n\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\t// NotFound error means that pod was already deleted.\n\t\t\t\t// There is nothing left to do with this pod.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn false, err\n\t\t}\n\t\tremaining = true\n\t}\n\n\tif len(updateErrList) \u003e 0 {\n\t\treturn false, utilerrors.NewAggregate(updateErrList)\n\t}\n\treturn remaining, nil\n}","line":{"from":42,"to":98}} {"id":100004805,"name":"SetPodTerminationReason","signature":"func SetPodTerminationReason(ctx context.Context, kubeClient clientset.Interface, pod *v1.Pod, nodeName string) (*v1.Pod, error)","file":"pkg/controller/util/node/controller_utils.go","code":"// SetPodTerminationReason attempts to set a reason and message in the\n// pod status, updates it in the apiserver, and returns an error if it\n// encounters one.\nfunc SetPodTerminationReason(ctx context.Context, kubeClient clientset.Interface, pod *v1.Pod, nodeName string) (*v1.Pod, error) {\n\tif pod.Status.Reason == nodepkg.NodeUnreachablePodReason {\n\t\treturn pod, nil\n\t}\n\n\tpod.Status.Reason = nodepkg.NodeUnreachablePodReason\n\tpod.Status.Message = fmt.Sprintf(nodepkg.NodeUnreachablePodMessage, nodeName, pod.Name)\n\n\tvar updatedPod *v1.Pod\n\tvar err error\n\tif updatedPod, err = kubeClient.CoreV1().Pods(pod.Namespace).UpdateStatus(ctx, pod, metav1.UpdateOptions{}); err != nil {\n\t\treturn nil, err\n\t}\n\treturn updatedPod, nil\n}","line":{"from":100,"to":117}} {"id":100004806,"name":"MarkPodsNotReady","signature":"func MarkPodsNotReady(ctx context.Context, kubeClient clientset.Interface, recorder record.EventRecorder, pods []*v1.Pod, nodeName string) error","file":"pkg/controller/util/node/controller_utils.go","code":"// MarkPodsNotReady updates ready status of given pods running on\n// given node from master return true if success\nfunc MarkPodsNotReady(ctx context.Context, kubeClient clientset.Interface, recorder record.EventRecorder, pods []*v1.Pod, nodeName string) error {\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(2).Info(\"Update ready status of pods on node\", \"node\", klog.KRef(\"\", nodeName))\n\n\terrs := []error{}\n\tfor i := range pods {\n\t\t// Defensive check, also needed for tests.\n\t\tif pods[i].Spec.NodeName != nodeName {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Pod will be modified, so making copy is required.\n\t\tpod := pods[i].DeepCopy()\n\t\tfor _, cond := range pod.Status.Conditions {\n\t\t\tif cond.Type != v1.PodReady {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcond.Status = v1.ConditionFalse\n\t\t\tif !utilpod.UpdatePodCondition(\u0026pod.Status, \u0026cond) {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tlogger.V(2).Info(\"Updating ready status of pod to false\", \"pod\", klog.KObj(pod))\n\t\t\tif _, err := kubeClient.CoreV1().Pods(pod.Namespace).UpdateStatus(ctx, pod, metav1.UpdateOptions{}); err != nil {\n\t\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\t\t// NotFound error means that pod was already deleted.\n\t\t\t\t\t// There is nothing left to do with this pod.\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tlogger.Info(\"Failed to update status for pod\", \"pod\", klog.KObj(pod), \"err\", err)\n\t\t\t\terrs = append(errs, err)\n\t\t\t}\n\t\t\t// record NodeNotReady event after updateStatus to make sure pod still exists\n\t\t\trecorder.Event(pod, v1.EventTypeWarning, \"NodeNotReady\", \"Node is not ready\")\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn utilerrors.NewAggregate(errs)\n}","line":{"from":119,"to":161}} {"id":100004807,"name":"RecordNodeEvent","signature":"func RecordNodeEvent(ctx context.Context, recorder record.EventRecorder, nodeName, nodeUID, eventtype, reason, event string)","file":"pkg/controller/util/node/controller_utils.go","code":"// RecordNodeEvent records a event related to a node.\nfunc RecordNodeEvent(ctx context.Context, recorder record.EventRecorder, nodeName, nodeUID, eventtype, reason, event string) {\n\tlogger := klog.FromContext(ctx)\n\tref := \u0026v1.ObjectReference{\n\t\tAPIVersion: \"v1\",\n\t\tKind: \"Node\",\n\t\tName: nodeName,\n\t\tUID: types.UID(nodeUID),\n\t\tNamespace: \"\",\n\t}\n\tlogger.V(2).Info(\"Recording event message for node\", \"event\", event, \"node\", klog.KRef(\"\", nodeName))\n\trecorder.Eventf(ref, eventtype, reason, \"Node %s event: %s\", nodeName, event)\n}","line":{"from":163,"to":175}} {"id":100004808,"name":"RecordNodeStatusChange","signature":"func RecordNodeStatusChange(recorder record.EventRecorder, node *v1.Node, newStatus string)","file":"pkg/controller/util/node/controller_utils.go","code":"// RecordNodeStatusChange records a event related to a node status change. (Common to lifecycle and ipam)\nfunc RecordNodeStatusChange(recorder record.EventRecorder, node *v1.Node, newStatus string) {\n\tref := \u0026v1.ObjectReference{\n\t\tAPIVersion: \"v1\",\n\t\tKind: \"Node\",\n\t\tName: node.Name,\n\t\tUID: node.UID,\n\t\tNamespace: \"\",\n\t}\n\tklog.V(2).InfoS(\"Recording status change event message for node\", \"status\", newStatus, \"node\", node.Name)\n\t// TODO: This requires a transaction, either both node status is updated\n\t// and event is recorded or neither should happen, see issue #6055.\n\trecorder.Eventf(ref, v1.EventTypeNormal, newStatus, \"Node %s status is now: %s\", node.Name, newStatus)\n}","line":{"from":177,"to":190}} {"id":100004809,"name":"SwapNodeControllerTaint","signature":"func SwapNodeControllerTaint(ctx context.Context, kubeClient clientset.Interface, taintsToAdd, taintsToRemove []*v1.Taint, node *v1.Node) bool","file":"pkg/controller/util/node/controller_utils.go","code":"// SwapNodeControllerTaint returns true in case of success and false\n// otherwise.\nfunc SwapNodeControllerTaint(ctx context.Context, kubeClient clientset.Interface, taintsToAdd, taintsToRemove []*v1.Taint, node *v1.Node) bool {\n\tlogger := klog.FromContext(ctx)\n\tfor _, taintToAdd := range taintsToAdd {\n\t\tnow := metav1.Now()\n\t\ttaintToAdd.TimeAdded = \u0026now\n\t}\n\n\terr := controller.AddOrUpdateTaintOnNode(ctx, kubeClient, node.Name, taintsToAdd...)\n\tif err != nil {\n\t\tutilruntime.HandleError(\n\t\t\tfmt.Errorf(\n\t\t\t\t\"unable to taint %+v unresponsive Node %q: %v\",\n\t\t\t\ttaintsToAdd,\n\t\t\t\tnode.Name,\n\t\t\t\terr))\n\t\treturn false\n\t}\n\tlogger.V(4).Info(\"Added taint to node\", \"taint\", taintsToAdd, \"node\", klog.KRef(\"\", node.Name))\n\n\terr = controller.RemoveTaintOffNode(ctx, kubeClient, node.Name, node, taintsToRemove...)\n\tif err != nil {\n\t\tutilruntime.HandleError(\n\t\t\tfmt.Errorf(\n\t\t\t\t\"unable to remove %+v unneeded taint from unresponsive Node %q: %v\",\n\t\t\t\ttaintsToRemove,\n\t\t\t\tnode.Name,\n\t\t\t\terr))\n\t\treturn false\n\t}\n\tlogger.V(4).Info(\"Made sure that node has no taint\", \"node\", klog.KRef(\"\", node.Name), \"taint\", taintsToRemove)\n\n\treturn true\n}","line":{"from":192,"to":226}} {"id":100004810,"name":"AddOrUpdateLabelsOnNode","signature":"func AddOrUpdateLabelsOnNode(ctx context.Context, kubeClient clientset.Interface, labelsToUpdate map[string]string, node *v1.Node) bool","file":"pkg/controller/util/node/controller_utils.go","code":"// AddOrUpdateLabelsOnNode updates the labels on the node and returns true on\n// success and false on failure.\nfunc AddOrUpdateLabelsOnNode(ctx context.Context, kubeClient clientset.Interface, labelsToUpdate map[string]string, node *v1.Node) bool {\n\tlogger := klog.FromContext(ctx)\n\tif err := controller.AddOrUpdateLabelsOnNode(kubeClient, node.Name, labelsToUpdate); err != nil {\n\t\tutilruntime.HandleError(\n\t\t\tfmt.Errorf(\n\t\t\t\t\"unable to update labels %+v for Node %q: %v\",\n\t\t\t\tlabelsToUpdate,\n\t\t\t\tnode.Name,\n\t\t\t\terr))\n\t\treturn false\n\t}\n\tlogger.V(4).Info(\"Updated labels to node\", \"label\", labelsToUpdate, \"node\", klog.KRef(\"\", node.Name))\n\treturn true\n}","line":{"from":228,"to":243}} {"id":100004811,"name":"CreateAddNodeHandler","signature":"func CreateAddNodeHandler(f func(node *v1.Node) error) func(obj interface{})","file":"pkg/controller/util/node/controller_utils.go","code":"// CreateAddNodeHandler creates an add node handler.\nfunc CreateAddNodeHandler(f func(node *v1.Node) error) func(obj interface{}) {\n\treturn func(originalObj interface{}) {\n\t\tnode := originalObj.(*v1.Node).DeepCopy()\n\t\tif err := f(node); err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"Error while processing Node Add: %v\", err))\n\t\t}\n\t}\n}","line":{"from":245,"to":253}} {"id":100004812,"name":"CreateUpdateNodeHandler","signature":"func CreateUpdateNodeHandler(f func(oldNode, newNode *v1.Node) error) func(oldObj, newObj interface{})","file":"pkg/controller/util/node/controller_utils.go","code":"// CreateUpdateNodeHandler creates a node update handler. (Common to lifecycle and ipam)\nfunc CreateUpdateNodeHandler(f func(oldNode, newNode *v1.Node) error) func(oldObj, newObj interface{}) {\n\treturn func(origOldObj, origNewObj interface{}) {\n\t\tnode := origNewObj.(*v1.Node).DeepCopy()\n\t\tprevNode := origOldObj.(*v1.Node).DeepCopy()\n\n\t\tif err := f(prevNode, node); err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"Error while processing Node Add/Delete: %v\", err))\n\t\t}\n\t}\n}","line":{"from":255,"to":265}} {"id":100004813,"name":"CreateDeleteNodeHandler","signature":"func CreateDeleteNodeHandler(f func(node *v1.Node) error) func(obj interface{})","file":"pkg/controller/util/node/controller_utils.go","code":"// CreateDeleteNodeHandler creates a delete node handler. (Common to lifecycle and ipam)\nfunc CreateDeleteNodeHandler(f func(node *v1.Node) error) func(obj interface{}) {\n\treturn func(originalObj interface{}) {\n\t\toriginalNode, isNode := originalObj.(*v1.Node)\n\t\t// We can get DeletedFinalStateUnknown instead of *v1.Node here and\n\t\t// we need to handle that correctly. #34692\n\t\tif !isNode {\n\t\t\tdeletedState, ok := originalObj.(cache.DeletedFinalStateUnknown)\n\t\t\tif !ok {\n\t\t\t\tklog.ErrorS(nil, \"Received unexpected object\", \"object\", originalObj)\n\t\t\t\treturn\n\t\t\t}\n\t\t\toriginalNode, ok = deletedState.Obj.(*v1.Node)\n\t\t\tif !ok {\n\t\t\t\tklog.ErrorS(nil, \"DeletedFinalStateUnknown contained non-Node object\", \"object\", deletedState.Obj)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tnode := originalNode.DeepCopy()\n\t\tif err := f(node); err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"Error while processing Node Add/Delete: %v\", err))\n\t\t}\n\t}\n}","line":{"from":267,"to":290}} {"id":100004814,"name":"GetNodeCondition","signature":"func GetNodeCondition(status *v1.NodeStatus, conditionType v1.NodeConditionType) (int, *v1.NodeCondition)","file":"pkg/controller/util/node/controller_utils.go","code":"// GetNodeCondition extracts the provided condition from the given status and returns that.\n// Returns nil and -1 if the condition is not present, and the index of the located condition.\nfunc GetNodeCondition(status *v1.NodeStatus, conditionType v1.NodeConditionType) (int, *v1.NodeCondition) {\n\tif status == nil {\n\t\treturn -1, nil\n\t}\n\tfor i := range status.Conditions {\n\t\tif status.Conditions[i].Type == conditionType {\n\t\t\treturn i, \u0026status.Conditions[i]\n\t\t}\n\t}\n\treturn -1, nil\n}","line":{"from":292,"to":304}} {"id":100004815,"name":"NewBiMultimap","signature":"func NewBiMultimap() *BiMultimap","file":"pkg/controller/util/selectors/bimultimap.go","code":"// NewBiMultimap creates a map.\nfunc NewBiMultimap() *BiMultimap {\n\treturn \u0026BiMultimap{\n\t\tlabeledObjects: make(map[Key]*labeledObject),\n\t\tselectingObjects: make(map[Key]*selectingObject),\n\t\tlabeledBySelecting: make(map[selectorKey]*labeledObjects),\n\t\tselectingByLabeled: make(map[labelsKey]*selectingObjects),\n\t}\n}","line":{"from":41,"to":49}} {"id":100004816,"name":"Parse","signature":"func Parse(s string) (key Key)","file":"pkg/controller/util/selectors/bimultimap.go","code":"// Parse turns a string in the format namespace/name into a Key.\nfunc Parse(s string) (key Key) {\n\tns := strings.SplitN(s, \"/\", 2)\n\tif len(ns) == 2 {\n\t\tkey.Namespace = ns[0]\n\t\tkey.Name = ns[1]\n\t} else {\n\t\tkey.Name = ns[0]\n\t}\n\treturn key\n}","line":{"from":57,"to":67}} {"id":100004817,"name":"String","signature":"func (k Key) String() string","file":"pkg/controller/util/selectors/bimultimap.go","code":"func (k Key) String() string {\n\treturn fmt.Sprintf(\"%v/%v\", k.Namespace, k.Name)\n}","line":{"from":69,"to":71}} {"id":100004818,"name":"Put","signature":"func (m *BiMultimap) Put(key Key, labels map[string]string)","file":"pkg/controller/util/selectors/bimultimap.go","code":"// Put inserts or updates an object and the incoming associations\n// based on the object labels.\nfunc (m *BiMultimap) Put(key Key, labels map[string]string) {\n\tm.mux.Lock()\n\tdefer m.mux.Unlock()\n\n\tlabelsKey := labelsKey{\n\t\tkey: pkglabels.Set(labels).String(),\n\t\tnamespace: key.Namespace,\n\t}\n\tif l, ok := m.labeledObjects[key]; ok {\n\t\t// Update labeled object.\n\t\tif labelsKey == l.labelsKey {\n\t\t\t// No change to labels.\n\t\t\treturn\n\t\t}\n\t\t// Delete before readding.\n\t\tm.delete(key)\n\t}\n\t// Add labeled object.\n\tlabels = copyLabels(labels)\n\tlabeledObject := \u0026labeledObject{\n\t\tkey: key,\n\t\tlabels: labels,\n\t\tlabelsKey: labelsKey,\n\t}\n\tm.labeledObjects[key] = labeledObject\n\t// Add associations.\n\tif _, ok := m.selectingByLabeled[labelsKey]; !ok {\n\t\t// Cache miss. Scan selecting objects.\n\t\tselecting := \u0026selectingObjects{\n\t\t\tobjects: make(map[Key]*selectingObject),\n\t\t}\n\t\tset := pkglabels.Set(labels)\n\t\tfor _, s := range m.selectingObjects {\n\t\t\tif s.key.Namespace != key.Namespace {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif s.selector.Matches(set) {\n\t\t\t\tselecting.objects[s.key] = s\n\t\t\t}\n\t\t}\n\t\t// Associate selecting with labeled.\n\t\tm.selectingByLabeled[labelsKey] = selecting\n\t}\n\tselecting := m.selectingByLabeled[labelsKey]\n\tselecting.refCount++\n\tfor _, sObject := range selecting.objects {\n\t\t// Associate labeled with selecting.\n\t\tlabeled := m.labeledBySelecting[sObject.selectorKey]\n\t\tlabeled.objects[labeledObject.key] = labeledObject\n\t}\n}","line":{"from":109,"to":161}} {"id":100004819,"name":"Delete","signature":"func (m *BiMultimap) Delete(key Key)","file":"pkg/controller/util/selectors/bimultimap.go","code":"// Delete removes a labeled object and incoming associations.\nfunc (m *BiMultimap) Delete(key Key) {\n\tm.mux.Lock()\n\tdefer m.mux.Unlock()\n\tm.delete(key)\n}","line":{"from":163,"to":168}} {"id":100004820,"name":"delete","signature":"func (m *BiMultimap) delete(key Key)","file":"pkg/controller/util/selectors/bimultimap.go","code":"func (m *BiMultimap) delete(key Key) {\n\tif _, ok := m.labeledObjects[key]; !ok {\n\t\t// Does not exist.\n\t\treturn\n\t}\n\tlabeledObject := m.labeledObjects[key]\n\tlabelsKey := labeledObject.labelsKey\n\tdefer delete(m.labeledObjects, key)\n\tif _, ok := m.selectingByLabeled[labelsKey]; !ok {\n\t\t// No associations.\n\t\treturn\n\t}\n\t// Remove associations.\n\tfor _, selectingObject := range m.selectingByLabeled[labelsKey].objects {\n\t\tselectorKey := selectingObject.selectorKey\n\t\t// Delete selectingObject to labeledObject association.\n\t\tdelete(m.labeledBySelecting[selectorKey].objects, key)\n\t}\n\tm.selectingByLabeled[labelsKey].refCount--\n\t// Garbage collect labeledObject to selectingObject associations.\n\tif m.selectingByLabeled[labelsKey].refCount == 0 {\n\t\tdelete(m.selectingByLabeled, labelsKey)\n\t}\n}","line":{"from":170,"to":193}} {"id":100004821,"name":"Exists","signature":"func (m *BiMultimap) Exists(key Key) bool","file":"pkg/controller/util/selectors/bimultimap.go","code":"// Exists returns true if the labeled object is present in the map.\nfunc (m *BiMultimap) Exists(key Key) bool {\n\tm.mux.Lock()\n\tdefer m.mux.Unlock()\n\n\t_, exists := m.labeledObjects[key]\n\treturn exists\n}","line":{"from":195,"to":202}} {"id":100004822,"name":"PutSelector","signature":"func (m *BiMultimap) PutSelector(key Key, selector pkglabels.Selector)","file":"pkg/controller/util/selectors/bimultimap.go","code":"// PutSelector inserts or updates an object with a selector. Associations\n// are created or updated based on the selector.\nfunc (m *BiMultimap) PutSelector(key Key, selector pkglabels.Selector) {\n\tm.mux.Lock()\n\tdefer m.mux.Unlock()\n\n\tselectorKey := selectorKey{\n\t\tkey: selector.String(),\n\t\tnamespace: key.Namespace,\n\t}\n\tif s, ok := m.selectingObjects[key]; ok {\n\t\t// Update selecting object.\n\t\tif selectorKey == s.selectorKey {\n\t\t\t// No change to selector.\n\t\t\treturn\n\t\t}\n\t\t// Delete before readding.\n\t\tm.deleteSelector(key)\n\t}\n\t// Add selecting object.\n\tselectingObject := \u0026selectingObject{\n\t\tkey: key,\n\t\tselector: selector,\n\t\tselectorKey: selectorKey,\n\t}\n\tm.selectingObjects[key] = selectingObject\n\t// Add associations.\n\tif _, ok := m.labeledBySelecting[selectorKey]; !ok {\n\t\t// Cache miss. Scan labeled objects.\n\t\tlabeled := \u0026labeledObjects{\n\t\t\tobjects: make(map[Key]*labeledObject),\n\t\t}\n\t\tfor _, l := range m.labeledObjects {\n\t\t\tif l.key.Namespace != key.Namespace {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tset := pkglabels.Set(l.labels)\n\t\t\tif selector.Matches(set) {\n\t\t\t\tlabeled.objects[l.key] = l\n\t\t\t}\n\t\t}\n\t\t// Associate labeled with selecting.\n\t\tm.labeledBySelecting[selectorKey] = labeled\n\t}\n\tlabeled := m.labeledBySelecting[selectorKey]\n\tlabeled.refCount++\n\tfor _, labeledObject := range labeled.objects {\n\t\t// Associate selecting with labeled.\n\t\tselecting := m.selectingByLabeled[labeledObject.labelsKey]\n\t\tselecting.objects[selectingObject.key] = selectingObject\n\t}\n}","line":{"from":204,"to":255}} {"id":100004823,"name":"DeleteSelector","signature":"func (m *BiMultimap) DeleteSelector(key Key)","file":"pkg/controller/util/selectors/bimultimap.go","code":"// DeleteSelector deletes a selecting object and associations created by its\n// selector.\nfunc (m *BiMultimap) DeleteSelector(key Key) {\n\tm.mux.Lock()\n\tdefer m.mux.Unlock()\n\tm.deleteSelector(key)\n}","line":{"from":257,"to":263}} {"id":100004824,"name":"deleteSelector","signature":"func (m *BiMultimap) deleteSelector(key Key)","file":"pkg/controller/util/selectors/bimultimap.go","code":"func (m *BiMultimap) deleteSelector(key Key) {\n\tif _, ok := m.selectingObjects[key]; !ok {\n\t\t// Does not exist.\n\t\treturn\n\t}\n\tselectingObject := m.selectingObjects[key]\n\tselectorKey := selectingObject.selectorKey\n\tdefer delete(m.selectingObjects, key)\n\tif _, ok := m.labeledBySelecting[selectorKey]; !ok {\n\t\t// No associations.\n\t\treturn\n\t}\n\t// Remove associations.\n\tfor _, labeledObject := range m.labeledBySelecting[selectorKey].objects {\n\t\tlabelsKey := labeledObject.labelsKey\n\t\t// Delete labeledObject to selectingObject association.\n\t\tdelete(m.selectingByLabeled[labelsKey].objects, key)\n\t}\n\tm.labeledBySelecting[selectorKey].refCount--\n\t// Garbage collect selectingObjects to labeledObject associations.\n\tif m.labeledBySelecting[selectorKey].refCount == 0 {\n\t\tdelete(m.labeledBySelecting, selectorKey)\n\t}\n}","line":{"from":265,"to":288}} {"id":100004825,"name":"SelectorExists","signature":"func (m *BiMultimap) SelectorExists(key Key) bool","file":"pkg/controller/util/selectors/bimultimap.go","code":"// SelectorExists returns true if the selecting object is present in the map.\nfunc (m *BiMultimap) SelectorExists(key Key) bool {\n\tm.mux.Lock()\n\tdefer m.mux.Unlock()\n\n\t_, exists := m.selectingObjects[key]\n\treturn exists\n}","line":{"from":290,"to":297}} {"id":100004826,"name":"KeepOnly","signature":"func (m *BiMultimap) KeepOnly(keys []Key)","file":"pkg/controller/util/selectors/bimultimap.go","code":"// KeepOnly retains only the specified labeled objects and deletes the\n// rest. Like calling Delete for all keys not specified.\nfunc (m *BiMultimap) KeepOnly(keys []Key) {\n\tm.mux.Lock()\n\tdefer m.mux.Unlock()\n\n\tkeyMap := make(map[Key]bool)\n\tfor _, k := range keys {\n\t\tkeyMap[k] = true\n\t}\n\tfor k := range m.labeledObjects {\n\t\tif !keyMap[k] {\n\t\t\tm.delete(k)\n\t\t}\n\t}\n}","line":{"from":299,"to":314}} {"id":100004827,"name":"KeepOnlySelectors","signature":"func (m *BiMultimap) KeepOnlySelectors(keys []Key)","file":"pkg/controller/util/selectors/bimultimap.go","code":"// KeepOnlySelectors retains only the specified selecting objects and\n// deletes the rest. Like calling DeleteSelector for all keys not\n// specified.\nfunc (m *BiMultimap) KeepOnlySelectors(keys []Key) {\n\tm.mux.Lock()\n\tdefer m.mux.Unlock()\n\n\tkeyMap := make(map[Key]bool)\n\tfor _, k := range keys {\n\t\tkeyMap[k] = true\n\t}\n\tfor k := range m.selectingObjects {\n\t\tif !keyMap[k] {\n\t\t\tm.deleteSelector(k)\n\t\t}\n\t}\n}","line":{"from":316,"to":332}} {"id":100004828,"name":"Select","signature":"func (m *BiMultimap) Select(key Key) (keys []Key, ok bool)","file":"pkg/controller/util/selectors/bimultimap.go","code":"// Select finds objects associated with a selecting object. If the\n// given key was found in the map `ok` will be true. Otherwise false.\nfunc (m *BiMultimap) Select(key Key) (keys []Key, ok bool) {\n\tm.mux.RLock()\n\tdefer m.mux.RUnlock()\n\n\tselectingObject, ok := m.selectingObjects[key]\n\tif !ok {\n\t\t// Does not exist.\n\t\treturn nil, false\n\t}\n\tkeys = make([]Key, 0)\n\tif labeled, ok := m.labeledBySelecting[selectingObject.selectorKey]; ok {\n\t\tfor _, labeledObject := range labeled.objects {\n\t\t\tkeys = append(keys, labeledObject.key)\n\t\t}\n\t}\n\treturn keys, true\n}","line":{"from":334,"to":352}} {"id":100004829,"name":"ReverseSelect","signature":"func (m *BiMultimap) ReverseSelect(key Key) (keys []Key, ok bool)","file":"pkg/controller/util/selectors/bimultimap.go","code":"// ReverseSelect finds objects selecting the given object. If the\n// given key was found in the map `ok` will be true. Otherwise false.\nfunc (m *BiMultimap) ReverseSelect(key Key) (keys []Key, ok bool) {\n\tm.mux.RLock()\n\tdefer m.mux.RUnlock()\n\n\tlabeledObject, ok := m.labeledObjects[key]\n\tif !ok {\n\t\t// Does not exist.\n\t\treturn []Key{}, false\n\t}\n\tkeys = make([]Key, 0)\n\tif selecting, ok := m.selectingByLabeled[labeledObject.labelsKey]; ok {\n\t\tfor _, selectingObject := range selecting.objects {\n\t\t\tkeys = append(keys, selectingObject.key)\n\t\t}\n\t}\n\treturn keys, true\n}","line":{"from":354,"to":372}} {"id":100004830,"name":"copyLabels","signature":"func copyLabels(labels map[string]string) map[string]string","file":"pkg/controller/util/selectors/bimultimap.go","code":"func copyLabels(labels map[string]string) map[string]string {\n\tl := make(map[string]string)\n\tfor k, v := range labels {\n\t\tl[k] = v\n\t}\n\treturn l\n}","line":{"from":374,"to":380}} {"id":100004831,"name":"NewAttachDetachController","signature":"func NewAttachDetachController(","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"// NewAttachDetachController returns a new instance of AttachDetachController.\nfunc NewAttachDetachController(\n\tlogger klog.Logger,\n\tkubeClient clientset.Interface,\n\tpodInformer coreinformers.PodInformer,\n\tnodeInformer coreinformers.NodeInformer,\n\tpvcInformer coreinformers.PersistentVolumeClaimInformer,\n\tpvInformer coreinformers.PersistentVolumeInformer,\n\tcsiNodeInformer storageinformersv1.CSINodeInformer,\n\tcsiDriverInformer storageinformersv1.CSIDriverInformer,\n\tvolumeAttachmentInformer storageinformersv1.VolumeAttachmentInformer,\n\tcloud cloudprovider.Interface,\n\tplugins []volume.VolumePlugin,\n\tprober volume.DynamicPluginProber,\n\tdisableReconciliationSync bool,\n\treconcilerSyncDuration time.Duration,\n\ttimerConfig TimerConfig,\n\tfilteredDialOptions *proxyutil.FilteredDialOptions) (AttachDetachController, error) {\n\n\tadc := \u0026attachDetachController{\n\t\tkubeClient: kubeClient,\n\t\tpvcLister: pvcInformer.Lister(),\n\t\tpvcsSynced: pvcInformer.Informer().HasSynced,\n\t\tpvLister: pvInformer.Lister(),\n\t\tpvsSynced: pvInformer.Informer().HasSynced,\n\t\tpodLister: podInformer.Lister(),\n\t\tpodsSynced: podInformer.Informer().HasSynced,\n\t\tpodIndexer: podInformer.Informer().GetIndexer(),\n\t\tnodeLister: nodeInformer.Lister(),\n\t\tnodesSynced: nodeInformer.Informer().HasSynced,\n\t\tcloud: cloud,\n\t\tpvcQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"pvcs\"),\n\t\tfilteredDialOptions: filteredDialOptions,\n\t}\n\n\tadc.csiNodeLister = csiNodeInformer.Lister()\n\tadc.csiNodeSynced = csiNodeInformer.Informer().HasSynced\n\n\tadc.csiDriverLister = csiDriverInformer.Lister()\n\tadc.csiDriversSynced = csiDriverInformer.Informer().HasSynced\n\n\tadc.volumeAttachmentLister = volumeAttachmentInformer.Lister()\n\tadc.volumeAttachmentSynced = volumeAttachmentInformer.Informer().HasSynced\n\n\tif err := adc.volumePluginMgr.InitPlugins(plugins, prober, adc); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not initialize volume plugins for Attach/Detach Controller: %w\", err)\n\t}\n\n\tadc.broadcaster = record.NewBroadcaster()\n\trecorder := adc.broadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"attachdetach-controller\"})\n\tblkutil := volumepathhandler.NewBlockVolumePathHandler()\n\n\tadc.desiredStateOfWorld = cache.NewDesiredStateOfWorld(\u0026adc.volumePluginMgr)\n\tadc.actualStateOfWorld = cache.NewActualStateOfWorld(\u0026adc.volumePluginMgr)\n\tadc.attacherDetacher =\n\t\toperationexecutor.NewOperationExecutor(operationexecutor.NewOperationGenerator(\n\t\t\tkubeClient,\n\t\t\t\u0026adc.volumePluginMgr,\n\t\t\trecorder,\n\t\t\tblkutil))\n\tadc.nodeStatusUpdater = statusupdater.NewNodeStatusUpdater(\n\t\tkubeClient, nodeInformer.Lister(), adc.actualStateOfWorld)\n\n\t// Default these to values in options\n\tadc.reconciler = reconciler.NewReconciler(\n\t\ttimerConfig.ReconcilerLoopPeriod,\n\t\ttimerConfig.ReconcilerMaxWaitForUnmountDuration,\n\t\treconcilerSyncDuration,\n\t\tdisableReconciliationSync,\n\t\tadc.desiredStateOfWorld,\n\t\tadc.actualStateOfWorld,\n\t\tadc.attacherDetacher,\n\t\tadc.nodeStatusUpdater,\n\t\tadc.nodeLister,\n\t\trecorder)\n\n\tcsiTranslator := csitrans.New()\n\tadc.intreeToCSITranslator = csiTranslator\n\tadc.csiMigratedPluginManager = csimigration.NewPluginManager(csiTranslator, utilfeature.DefaultFeatureGate)\n\n\tadc.desiredStateOfWorldPopulator = populator.NewDesiredStateOfWorldPopulator(\n\t\ttimerConfig.DesiredStateOfWorldPopulatorLoopSleepPeriod,\n\t\ttimerConfig.DesiredStateOfWorldPopulatorListPodsRetryDuration,\n\t\tpodInformer.Lister(),\n\t\tadc.desiredStateOfWorld,\n\t\t\u0026adc.volumePluginMgr,\n\t\tpvcInformer.Lister(),\n\t\tpvInformer.Lister(),\n\t\tadc.csiMigratedPluginManager,\n\t\tadc.intreeToCSITranslator)\n\n\tpodInformer.Informer().AddEventHandler(kcache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tadc.podAdd(logger, obj)\n\t\t},\n\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\tadc.podUpdate(logger, oldObj, newObj)\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tadc.podDelete(logger, obj)\n\t\t},\n\t})\n\n\t// This custom indexer will index pods by its PVC keys. Then we don't need\n\t// to iterate all pods every time to find pods which reference given PVC.\n\tif err := common.AddPodPVCIndexerIfNotPresent(adc.podIndexer); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not initialize attach detach controller: %w\", err)\n\t}\n\n\tnodeInformer.Informer().AddEventHandler(kcache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tadc.nodeAdd(logger, obj)\n\t\t},\n\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\tadc.nodeUpdate(logger, oldObj, newObj)\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tadc.nodeDelete(logger, obj)\n\t\t},\n\t})\n\n\tpvcInformer.Informer().AddEventHandler(kcache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tadc.enqueuePVC(obj)\n\t\t},\n\t\tUpdateFunc: func(old, new interface{}) {\n\t\t\tadc.enqueuePVC(new)\n\t\t},\n\t})\n\n\treturn adc, nil\n}","line":{"from":107,"to":238}} {"id":100004832,"name":"Run","signature":"func (adc *attachDetachController) Run(ctx context.Context)","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) Run(ctx context.Context) {\n\tdefer runtime.HandleCrash()\n\tdefer adc.pvcQueue.ShutDown()\n\n\t// Start events processing pipeline.\n\tadc.broadcaster.StartStructuredLogging(0)\n\tadc.broadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: adc.kubeClient.CoreV1().Events(\"\")})\n\tdefer adc.broadcaster.Shutdown()\n\n\tlogger := klog.FromContext(ctx)\n\tlogger.Info(\"Starting attach detach controller\")\n\tdefer logger.Info(\"Shutting down attach detach controller\")\n\n\tsynced := []kcache.InformerSynced{adc.podsSynced, adc.nodesSynced, adc.pvcsSynced, adc.pvsSynced}\n\tif adc.csiNodeSynced != nil {\n\t\tsynced = append(synced, adc.csiNodeSynced)\n\t}\n\tif adc.csiDriversSynced != nil {\n\t\tsynced = append(synced, adc.csiDriversSynced)\n\t}\n\tif adc.volumeAttachmentSynced != nil {\n\t\tsynced = append(synced, adc.volumeAttachmentSynced)\n\t}\n\n\tif !kcache.WaitForNamedCacheSync(\"attach detach\", ctx.Done(), synced...) {\n\t\treturn\n\t}\n\n\terr := adc.populateActualStateOfWorld(logger)\n\tif err != nil {\n\t\tlogger.Error(err, \"Error populating the actual state of world\")\n\t}\n\terr = adc.populateDesiredStateOfWorld(logger)\n\tif err != nil {\n\t\tlogger.Error(err, \"Error populating the desired state of world\")\n\t}\n\tgo adc.reconciler.Run(ctx)\n\tgo adc.desiredStateOfWorldPopulator.Run(ctx)\n\tgo wait.UntilWithContext(ctx, adc.pvcWorker, time.Second)\n\tmetrics.Register(adc.pvcLister,\n\t\tadc.pvLister,\n\t\tadc.podLister,\n\t\tadc.actualStateOfWorld,\n\t\tadc.desiredStateOfWorld,\n\t\t\u0026adc.volumePluginMgr,\n\t\tadc.csiMigratedPluginManager,\n\t\tadc.intreeToCSITranslator)\n\n\t\u003c-ctx.Done()\n}","line":{"from":333,"to":382}} {"id":100004833,"name":"populateActualStateOfWorld","signature":"func (adc *attachDetachController) populateActualStateOfWorld(logger klog.Logger) error","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) populateActualStateOfWorld(logger klog.Logger) error {\n\tlogger.V(5).Info(\"Populating ActualStateOfworld\")\n\tnodes, err := adc.nodeLister.List(labels.Everything())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, node := range nodes {\n\t\tnodeName := types.NodeName(node.Name)\n\t\tfor _, attachedVolume := range node.Status.VolumesAttached {\n\t\t\tuniqueName := attachedVolume.Name\n\t\t\t// The nil VolumeSpec is safe only in the case the volume is not in use by any pod.\n\t\t\t// In such a case it should be detached in the first reconciliation cycle and the\n\t\t\t// volume spec is not needed to detach a volume. If the volume is used by a pod, it\n\t\t\t// its spec can be: this would happen during in the populateDesiredStateOfWorld which\n\t\t\t// scans the pods and updates their volumes in the ActualStateOfWorld too.\n\t\t\terr = adc.actualStateOfWorld.MarkVolumeAsAttached(logger, uniqueName, nil /* VolumeSpec */, nodeName, attachedVolume.DevicePath)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Error(err, \"Failed to mark the volume as attached\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tadc.processVolumesInUse(logger, nodeName, node.Status.VolumesInUse)\n\t\t\tadc.addNodeToDswp(node, types.NodeName(node.Name))\n\t\t}\n\t}\n\terr = adc.processVolumeAttachments(logger)\n\tif err != nil {\n\t\tlogger.Error(err, \"Failed to process volume attachments\")\n\t}\n\treturn err\n}","line":{"from":384,"to":414}} {"id":100004834,"name":"getNodeVolumeDevicePath","signature":"func (adc *attachDetachController) getNodeVolumeDevicePath(","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) getNodeVolumeDevicePath(\n\tvolumeName v1.UniqueVolumeName, nodeName types.NodeName) (string, error) {\n\tvar devicePath string\n\tvar found bool\n\tnode, err := adc.nodeLister.Get(string(nodeName))\n\tif err != nil {\n\t\treturn devicePath, err\n\t}\n\tfor _, attachedVolume := range node.Status.VolumesAttached {\n\t\tif volumeName == attachedVolume.Name {\n\t\t\tdevicePath = attachedVolume.DevicePath\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\terr = fmt.Errorf(\"Volume %s not found on node %s\", volumeName, nodeName)\n\t}\n\n\treturn devicePath, err\n}","line":{"from":416,"to":436}} {"id":100004835,"name":"populateDesiredStateOfWorld","signature":"func (adc *attachDetachController) populateDesiredStateOfWorld(logger klog.Logger) error","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) populateDesiredStateOfWorld(logger klog.Logger) error {\n\tlogger.V(5).Info(\"Populating DesiredStateOfworld\")\n\n\tpods, err := adc.podLister.List(labels.Everything())\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, pod := range pods {\n\t\tpodToAdd := pod\n\t\tadc.podAdd(logger, podToAdd)\n\t\tfor _, podVolume := range podToAdd.Spec.Volumes {\n\t\t\tnodeName := types.NodeName(podToAdd.Spec.NodeName)\n\t\t\t// The volume specs present in the ActualStateOfWorld are nil, let's replace those\n\t\t\t// with the correct ones found on pods. The present in the ASW with no corresponding\n\t\t\t// pod will be detached and the spec is irrelevant.\n\t\t\tvolumeSpec, err := util.CreateVolumeSpec(logger, podVolume, podToAdd, nodeName, \u0026adc.volumePluginMgr, adc.pvcLister, adc.pvLister, adc.csiMigratedPluginManager, adc.intreeToCSITranslator)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Error(\n\t\t\t\t\terr,\n\t\t\t\t\t\"Error creating spec for volume of pod\",\n\t\t\t\t\t\"pod\", klog.KObj(podToAdd),\n\t\t\t\t\t\"volumeName\", podVolume.Name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tplugin, err := adc.volumePluginMgr.FindAttachablePluginBySpec(volumeSpec)\n\t\t\tif err != nil || plugin == nil {\n\t\t\t\tlogger.V(10).Info(\n\t\t\t\t\t\"Skipping volume for pod: it does not implement attacher interface\",\n\t\t\t\t\t\"pod\", klog.KObj(podToAdd),\n\t\t\t\t\t\"volumeName\", podVolume.Name,\n\t\t\t\t\t\"err\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvolumeName, err := volumeutil.GetUniqueVolumeNameFromSpec(plugin, volumeSpec)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Error(\n\t\t\t\t\terr,\n\t\t\t\t\t\"Failed to find unique name for volume of pod\",\n\t\t\t\t\t\"pod\", klog.KObj(podToAdd),\n\t\t\t\t\t\"volumeName\", podVolume.Name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tattachState := adc.actualStateOfWorld.GetAttachState(volumeName, nodeName)\n\t\t\tif attachState == cache.AttachStateAttached {\n\t\t\t\tlogger.V(10).Info(\"Volume is attached to node. Marking as attached in ActualStateOfWorld\",\n\t\t\t\t\t\"node\", klog.KRef(\"\", string(nodeName)),\n\t\t\t\t\t\"volumeName\", volumeName)\n\t\t\t\tdevicePath, err := adc.getNodeVolumeDevicePath(volumeName, nodeName)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Error(err, \"Failed to find device path\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\terr = adc.actualStateOfWorld.MarkVolumeAsAttached(logger, volumeName, volumeSpec, nodeName, devicePath)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Error(err, \"Failed to update volume spec for node\", \"node\", klog.KRef(\"\", string(nodeName)))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":438,"to":499}} {"id":100004836,"name":"podAdd","signature":"func (adc *attachDetachController) podAdd(logger klog.Logger, obj interface{})","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) podAdd(logger klog.Logger, obj interface{}) {\n\tpod, ok := obj.(*v1.Pod)\n\tif pod == nil || !ok {\n\t\treturn\n\t}\n\tif pod.Spec.NodeName == \"\" {\n\t\t// Ignore pods without NodeName, indicating they are not scheduled.\n\t\treturn\n\t}\n\n\tvolumeActionFlag := util.DetermineVolumeAction(\n\t\tpod,\n\t\tadc.desiredStateOfWorld,\n\t\ttrue /* default volume action */)\n\n\tutil.ProcessPodVolumes(logger, pod, volumeActionFlag, /* addVolumes */\n\t\tadc.desiredStateOfWorld, \u0026adc.volumePluginMgr, adc.pvcLister, adc.pvLister, adc.csiMigratedPluginManager, adc.intreeToCSITranslator)\n}","line":{"from":501,"to":518}} {"id":100004837,"name":"GetDesiredStateOfWorld","signature":"func (adc *attachDetachController) GetDesiredStateOfWorld() cache.DesiredStateOfWorld","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"// GetDesiredStateOfWorld returns desired state of world associated with controller\nfunc (adc *attachDetachController) GetDesiredStateOfWorld() cache.DesiredStateOfWorld {\n\treturn adc.desiredStateOfWorld\n}","line":{"from":520,"to":523}} {"id":100004838,"name":"podUpdate","signature":"func (adc *attachDetachController) podUpdate(logger klog.Logger, oldObj, newObj interface{})","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) podUpdate(logger klog.Logger, oldObj, newObj interface{}) {\n\tpod, ok := newObj.(*v1.Pod)\n\tif pod == nil || !ok {\n\t\treturn\n\t}\n\tif pod.Spec.NodeName == \"\" {\n\t\t// Ignore pods without NodeName, indicating they are not scheduled.\n\t\treturn\n\t}\n\n\tvolumeActionFlag := util.DetermineVolumeAction(\n\t\tpod,\n\t\tadc.desiredStateOfWorld,\n\t\ttrue /* default volume action */)\n\n\tutil.ProcessPodVolumes(logger, pod, volumeActionFlag, /* addVolumes */\n\t\tadc.desiredStateOfWorld, \u0026adc.volumePluginMgr, adc.pvcLister, adc.pvLister, adc.csiMigratedPluginManager, adc.intreeToCSITranslator)\n}","line":{"from":525,"to":542}} {"id":100004839,"name":"podDelete","signature":"func (adc *attachDetachController) podDelete(logger klog.Logger, obj interface{})","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) podDelete(logger klog.Logger, obj interface{}) {\n\tpod, ok := obj.(*v1.Pod)\n\tif pod == nil || !ok {\n\t\treturn\n\t}\n\n\tutil.ProcessPodVolumes(logger, pod, false, /* addVolumes */\n\t\tadc.desiredStateOfWorld, \u0026adc.volumePluginMgr, adc.pvcLister, adc.pvLister, adc.csiMigratedPluginManager, adc.intreeToCSITranslator)\n}","line":{"from":544,"to":552}} {"id":100004840,"name":"nodeAdd","signature":"func (adc *attachDetachController) nodeAdd(logger klog.Logger, obj interface{})","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) nodeAdd(logger klog.Logger, obj interface{}) {\n\tnode, ok := obj.(*v1.Node)\n\t// TODO: investigate if nodeName is empty then if we can return\n\t// kubernetes/kubernetes/issues/37777\n\tif node == nil || !ok {\n\t\treturn\n\t}\n\tnodeName := types.NodeName(node.Name)\n\tadc.nodeUpdate(logger, nil, obj)\n\t// kubernetes/kubernetes/issues/37586\n\t// This is to workaround the case when a node add causes to wipe out\n\t// the attached volumes field. This function ensures that we sync with\n\t// the actual status.\n\tadc.actualStateOfWorld.SetNodeStatusUpdateNeeded(logger, nodeName)\n}","line":{"from":554,"to":568}} {"id":100004841,"name":"nodeUpdate","signature":"func (adc *attachDetachController) nodeUpdate(logger klog.Logger, oldObj, newObj interface{})","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) nodeUpdate(logger klog.Logger, oldObj, newObj interface{}) {\n\tnode, ok := newObj.(*v1.Node)\n\t// TODO: investigate if nodeName is empty then if we can return\n\tif node == nil || !ok {\n\t\treturn\n\t}\n\n\tnodeName := types.NodeName(node.Name)\n\tadc.addNodeToDswp(node, nodeName)\n\tadc.processVolumesInUse(logger, nodeName, node.Status.VolumesInUse)\n}","line":{"from":570,"to":580}} {"id":100004842,"name":"nodeDelete","signature":"func (adc *attachDetachController) nodeDelete(logger klog.Logger, obj interface{})","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) nodeDelete(logger klog.Logger, obj interface{}) {\n\tnode, ok := obj.(*v1.Node)\n\tif node == nil || !ok {\n\t\treturn\n\t}\n\n\tnodeName := types.NodeName(node.Name)\n\tif err := adc.desiredStateOfWorld.DeleteNode(nodeName); err != nil {\n\t\t// This might happen during drain, but we still want it to appear in our logs\n\t\tlogger.Info(\"Error removing node from desired-state-of-world\", \"node\", klog.KObj(node), \"err\", err)\n\t}\n\n\tadc.processVolumesInUse(logger, nodeName, node.Status.VolumesInUse)\n}","line":{"from":582,"to":595}} {"id":100004843,"name":"enqueuePVC","signature":"func (adc *attachDetachController) enqueuePVC(obj interface{})","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) enqueuePVC(obj interface{}) {\n\tkey, err := kcache.DeletionHandlingMetaNamespaceKeyFunc(obj)\n\tif err != nil {\n\t\truntime.HandleError(fmt.Errorf(\"Couldn't get key for object %+v: %v\", obj, err))\n\t\treturn\n\t}\n\tadc.pvcQueue.Add(key)\n}","line":{"from":597,"to":604}} {"id":100004844,"name":"pvcWorker","signature":"func (adc *attachDetachController) pvcWorker(ctx context.Context)","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"// pvcWorker processes items from pvcQueue\nfunc (adc *attachDetachController) pvcWorker(ctx context.Context) {\n\tfor adc.processNextItem(klog.FromContext(ctx)) {\n\t}\n}","line":{"from":606,"to":610}} {"id":100004845,"name":"processNextItem","signature":"func (adc *attachDetachController) processNextItem(logger klog.Logger) bool","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) processNextItem(logger klog.Logger) bool {\n\tkeyObj, shutdown := adc.pvcQueue.Get()\n\tif shutdown {\n\t\treturn false\n\t}\n\tdefer adc.pvcQueue.Done(keyObj)\n\n\tif err := adc.syncPVCByKey(logger, keyObj.(string)); err != nil {\n\t\t// Rather than wait for a full resync, re-add the key to the\n\t\t// queue to be processed.\n\t\tadc.pvcQueue.AddRateLimited(keyObj)\n\t\truntime.HandleError(fmt.Errorf(\"Failed to sync pvc %q, will retry again: %v\", keyObj.(string), err))\n\t\treturn true\n\t}\n\n\t// Finally, if no error occurs we Forget this item so it does not\n\t// get queued again until another change happens.\n\tadc.pvcQueue.Forget(keyObj)\n\treturn true\n}","line":{"from":612,"to":631}} {"id":100004846,"name":"syncPVCByKey","signature":"func (adc *attachDetachController) syncPVCByKey(logger klog.Logger, key string) error","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) syncPVCByKey(logger klog.Logger, key string) error {\n\tlogger.V(5).Info(\"syncPVCByKey\", \"pvcKey\", key)\n\tnamespace, name, err := kcache.SplitMetaNamespaceKey(key)\n\tif err != nil {\n\t\tlogger.V(4).Info(\"Error getting namespace \u0026 name of pvc to get pvc from informer\", \"pvcKey\", key, \"err\", err)\n\t\treturn nil\n\t}\n\tpvc, err := adc.pvcLister.PersistentVolumeClaims(namespace).Get(name)\n\tif apierrors.IsNotFound(err) {\n\t\tlogger.V(4).Info(\"Error getting pvc from informer\", \"pvcKey\", key, \"err\", err)\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif pvc.Status.Phase != v1.ClaimBound || pvc.Spec.VolumeName == \"\" {\n\t\t// Skip unbound PVCs.\n\t\treturn nil\n\t}\n\n\tobjs, err := adc.podIndexer.ByIndex(common.PodPVCIndex, key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, obj := range objs {\n\t\tpod, ok := obj.(*v1.Pod)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\t// we are only interested in active pods with nodeName set\n\t\tif len(pod.Spec.NodeName) == 0 || volumeutil.IsPodTerminated(pod, pod.Status) {\n\t\t\tcontinue\n\t\t}\n\t\tvolumeActionFlag := util.DetermineVolumeAction(\n\t\t\tpod,\n\t\t\tadc.desiredStateOfWorld,\n\t\t\ttrue /* default volume action */)\n\n\t\tutil.ProcessPodVolumes(logger, pod, volumeActionFlag, /* addVolumes */\n\t\t\tadc.desiredStateOfWorld, \u0026adc.volumePluginMgr, adc.pvcLister, adc.pvLister, adc.csiMigratedPluginManager, adc.intreeToCSITranslator)\n\t}\n\treturn nil\n}","line":{"from":633,"to":676}} {"id":100004847,"name":"processVolumesInUse","signature":"func (adc *attachDetachController) processVolumesInUse(","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"// processVolumesInUse processes the list of volumes marked as \"in-use\"\n// according to the specified Node's Status.VolumesInUse and updates the\n// corresponding volume in the actual state of the world to indicate that it is\n// mounted.\nfunc (adc *attachDetachController) processVolumesInUse(\n\tlogger klog.Logger, nodeName types.NodeName, volumesInUse []v1.UniqueVolumeName) {\n\tlogger.V(4).Info(\"processVolumesInUse for node\", \"node\", klog.KRef(\"\", string(nodeName)))\n\tfor _, attachedVolume := range adc.actualStateOfWorld.GetAttachedVolumesForNode(nodeName) {\n\t\tmounted := false\n\t\tfor _, volumeInUse := range volumesInUse {\n\t\t\tif attachedVolume.VolumeName == volumeInUse {\n\t\t\t\tmounted = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\terr := adc.actualStateOfWorld.SetVolumeMountedByNode(logger, attachedVolume.VolumeName, nodeName, mounted)\n\t\tif err != nil {\n\t\t\tlogger.Info(\n\t\t\t\t\"SetVolumeMountedByNode returned an error\",\n\t\t\t\t\"node\", klog.KRef(\"\", string(nodeName)),\n\t\t\t\t\"volumeName\", attachedVolume.VolumeName,\n\t\t\t\t\"mounted\", mounted,\n\t\t\t\t\"err\", err)\n\t\t}\n\t}\n}","line":{"from":678,"to":703}} {"id":100004848,"name":"processVolumeAttachments","signature":"func (adc *attachDetachController) processVolumeAttachments(logger klog.Logger) error","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"// Process Volume-Attachment objects.\n// Should be called only after populating attached volumes in the ASW.\n// For each VA object, this function checks if its present in the ASW.\n// If not, adds the volume to ASW as an \"uncertain\" attachment.\n// In the reconciler, the logic checks if the volume is present in the DSW;\n//\n//\tif yes, the reconciler will attempt attach on the volume;\n//\tif not (could be a dangling attachment), the reconciler will detach this volume.\nfunc (adc *attachDetachController) processVolumeAttachments(logger klog.Logger) error {\n\tvas, err := adc.volumeAttachmentLister.List(labels.Everything())\n\tif err != nil {\n\t\tlogger.Error(err, \"Failed to list VolumeAttachment objects\")\n\t\treturn err\n\t}\n\tfor _, va := range vas {\n\t\tnodeName := types.NodeName(va.Spec.NodeName)\n\t\tpvName := va.Spec.Source.PersistentVolumeName\n\t\tif pvName == nil {\n\t\t\t// Currently VA objects are created for CSI volumes only. nil pvName is unexpected, generate a warning\n\t\t\tlogger.Info(\"Skipping the va as its pvName is nil\", \"node\", klog.KRef(\"\", string(nodeName)), \"vaName\", va.Name)\n\t\t\tcontinue\n\t\t}\n\t\tpv, err := adc.pvLister.Get(*pvName)\n\t\tif err != nil {\n\t\t\tlogger.Error(err, \"Unable to lookup pv object\", \"PV\", klog.KRef(\"\", *pvName))\n\t\t\tcontinue\n\t\t}\n\n\t\tvar plugin volume.AttachableVolumePlugin\n\t\tvolumeSpec := volume.NewSpecFromPersistentVolume(pv, false)\n\n\t\t// Consult csiMigratedPluginManager first before querying the plugins registered during runtime in volumePluginMgr.\n\t\t// In-tree plugins that provisioned PVs will not be registered anymore after migration to CSI, once the respective\n\t\t// feature gate is enabled.\n\t\tif inTreePluginName, err := adc.csiMigratedPluginManager.GetInTreePluginNameFromSpec(pv, nil); err == nil {\n\t\t\tif adc.csiMigratedPluginManager.IsMigrationEnabledForPlugin(inTreePluginName) {\n\t\t\t\t// PV is migrated and should be handled by the CSI plugin instead of the in-tree one\n\t\t\t\tplugin, _ = adc.volumePluginMgr.FindAttachablePluginByName(csi.CSIPluginName)\n\t\t\t\t// podNamespace is not needed here for Azurefile as the volumeName generated will be the same with or without podNamespace\n\t\t\t\tvolumeSpec, err = csimigration.TranslateInTreeSpecToCSI(volumeSpec, \"\" /* podNamespace */, adc.intreeToCSITranslator)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Error(err, \"Failed to translate intree volumeSpec to CSI volumeSpec for volume\", \"node\", klog.KRef(\"\", string(nodeName)), \"inTreePluginName\", inTreePluginName, \"vaName\", va.Name, \"PV\", klog.KRef(\"\", *pvName))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif plugin == nil {\n\t\t\tplugin, err = adc.volumePluginMgr.FindAttachablePluginBySpec(volumeSpec)\n\t\t\tif err != nil || plugin == nil {\n\t\t\t\t// Currently VA objects are created for CSI volumes only. nil plugin is unexpected, generate a warning\n\t\t\t\tlogger.Info(\"Skipping processing the volume on node, no attacher interface found\", \"node\", klog.KRef(\"\", string(nodeName)), \"PV\", klog.KRef(\"\", *pvName), \"err\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tvolumeName, err := volumeutil.GetUniqueVolumeNameFromSpec(plugin, volumeSpec)\n\t\tif err != nil {\n\t\t\tlogger.Error(err, \"Failed to find unique name for volume\", \"node\", klog.KRef(\"\", string(nodeName)), \"vaName\", va.Name, \"PV\", klog.KRef(\"\", *pvName))\n\t\t\tcontinue\n\t\t}\n\t\tattachState := adc.actualStateOfWorld.GetAttachState(volumeName, nodeName)\n\t\tif attachState == cache.AttachStateDetached {\n\t\t\tlogger.V(1).Info(\"Marking volume attachment as uncertain as volume is not attached\", \"node\", klog.KRef(\"\", string(nodeName)), \"volumeName\", volumeName, \"attachState\", attachState)\n\t\t\terr = adc.actualStateOfWorld.MarkVolumeAsUncertain(logger, volumeName, volumeSpec, nodeName)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Error(err, \"MarkVolumeAsUncertain fail to add the volume to ASW\", \"node\", klog.KRef(\"\", string(nodeName)), \"volumeName\", volumeName)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":705,"to":776}} {"id":100004849,"name":"CSINodeLister","signature":"func (adc *attachDetachController) CSINodeLister() storagelistersv1.CSINodeLister","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) CSINodeLister() storagelistersv1.CSINodeLister {\n\treturn adc.csiNodeLister\n}","line":{"from":781,"to":783}} {"id":100004850,"name":"CSIDriverLister","signature":"func (adc *attachDetachController) CSIDriverLister() storagelistersv1.CSIDriverLister","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) CSIDriverLister() storagelistersv1.CSIDriverLister {\n\treturn adc.csiDriverLister\n}","line":{"from":785,"to":787}} {"id":100004851,"name":"IsAttachDetachController","signature":"func (adc *attachDetachController) IsAttachDetachController() bool","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) IsAttachDetachController() bool {\n\treturn true\n}","line":{"from":789,"to":791}} {"id":100004852,"name":"VolumeAttachmentLister","signature":"func (adc *attachDetachController) VolumeAttachmentLister() storagelistersv1.VolumeAttachmentLister","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) VolumeAttachmentLister() storagelistersv1.VolumeAttachmentLister {\n\treturn adc.volumeAttachmentLister\n}","line":{"from":793,"to":795}} {"id":100004853,"name":"GetPluginDir","signature":"func (adc *attachDetachController) GetPluginDir(podUID string) string","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"// VolumeHost implementation\n// This is an unfortunate requirement of the current factoring of volume plugin\n// initializing code. It requires kubelet specific methods used by the mounting\n// code to be implemented by all initializers even if the initializer does not\n// do mounting (like this attach/detach controller).\n// Issue kubernetes/kubernetes/issues/14217 to fix this.\nfunc (adc *attachDetachController) GetPluginDir(podUID string) string {\n\treturn \"\"\n}","line":{"from":797,"to":805}} {"id":100004854,"name":"GetVolumeDevicePluginDir","signature":"func (adc *attachDetachController) GetVolumeDevicePluginDir(podUID string) string","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) GetVolumeDevicePluginDir(podUID string) string {\n\treturn \"\"\n}","line":{"from":807,"to":809}} {"id":100004855,"name":"GetPodsDir","signature":"func (adc *attachDetachController) GetPodsDir() string","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) GetPodsDir() string {\n\treturn \"\"\n}","line":{"from":811,"to":813}} {"id":100004856,"name":"GetPodVolumeDir","signature":"func (adc *attachDetachController) GetPodVolumeDir(podUID types.UID, pluginName, volumeName string) string","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) GetPodVolumeDir(podUID types.UID, pluginName, volumeName string) string {\n\treturn \"\"\n}","line":{"from":815,"to":817}} {"id":100004857,"name":"GetPodPluginDir","signature":"func (adc *attachDetachController) GetPodPluginDir(podUID types.UID, pluginName string) string","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) GetPodPluginDir(podUID types.UID, pluginName string) string {\n\treturn \"\"\n}","line":{"from":819,"to":821}} {"id":100004858,"name":"GetPodVolumeDeviceDir","signature":"func (adc *attachDetachController) GetPodVolumeDeviceDir(podUID types.UID, pluginName string) string","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) GetPodVolumeDeviceDir(podUID types.UID, pluginName string) string {\n\treturn \"\"\n}","line":{"from":823,"to":825}} {"id":100004859,"name":"GetKubeClient","signature":"func (adc *attachDetachController) GetKubeClient() clientset.Interface","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) GetKubeClient() clientset.Interface {\n\treturn adc.kubeClient\n}","line":{"from":827,"to":829}} {"id":100004860,"name":"NewWrapperMounter","signature":"func (adc *attachDetachController) NewWrapperMounter(volName string, spec volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error)","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) NewWrapperMounter(volName string, spec volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error) {\n\treturn nil, fmt.Errorf(\"NewWrapperMounter not supported by Attach/Detach controller's VolumeHost implementation\")\n}","line":{"from":831,"to":833}} {"id":100004861,"name":"NewWrapperUnmounter","signature":"func (adc *attachDetachController) NewWrapperUnmounter(volName string, spec volume.Spec, podUID types.UID) (volume.Unmounter, error)","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) NewWrapperUnmounter(volName string, spec volume.Spec, podUID types.UID) (volume.Unmounter, error) {\n\treturn nil, fmt.Errorf(\"NewWrapperUnmounter not supported by Attach/Detach controller's VolumeHost implementation\")\n}","line":{"from":835,"to":837}} {"id":100004862,"name":"GetCloudProvider","signature":"func (adc *attachDetachController) GetCloudProvider() cloudprovider.Interface","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) GetCloudProvider() cloudprovider.Interface {\n\treturn adc.cloud\n}","line":{"from":839,"to":841}} {"id":100004863,"name":"GetMounter","signature":"func (adc *attachDetachController) GetMounter(pluginName string) mount.Interface","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) GetMounter(pluginName string) mount.Interface {\n\treturn nil\n}","line":{"from":843,"to":845}} {"id":100004864,"name":"GetHostName","signature":"func (adc *attachDetachController) GetHostName() string","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) GetHostName() string {\n\treturn \"\"\n}","line":{"from":847,"to":849}} {"id":100004865,"name":"GetHostIP","signature":"func (adc *attachDetachController) GetHostIP() (net.IP, error)","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) GetHostIP() (net.IP, error) {\n\treturn nil, fmt.Errorf(\"GetHostIP() not supported by Attach/Detach controller's VolumeHost implementation\")\n}","line":{"from":851,"to":853}} {"id":100004866,"name":"GetNodeAllocatable","signature":"func (adc *attachDetachController) GetNodeAllocatable() (v1.ResourceList, error)","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) GetNodeAllocatable() (v1.ResourceList, error) {\n\treturn v1.ResourceList{}, nil\n}","line":{"from":855,"to":857}} {"id":100004867,"name":"GetAttachedVolumesFromNodeStatus","signature":"func (adc *attachDetachController) GetAttachedVolumesFromNodeStatus() (map[v1.UniqueVolumeName]string, error)","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) GetAttachedVolumesFromNodeStatus() (map[v1.UniqueVolumeName]string, error) {\n\treturn map[v1.UniqueVolumeName]string{}, nil\n}","line":{"from":859,"to":861}} {"id":100004868,"name":"GetSecretFunc","signature":"func (adc *attachDetachController) GetSecretFunc() func(namespace, name string) (*v1.Secret, error)","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) GetSecretFunc() func(namespace, name string) (*v1.Secret, error) {\n\treturn func(_, _ string) (*v1.Secret, error) {\n\t\treturn nil, fmt.Errorf(\"GetSecret unsupported in attachDetachController\")\n\t}\n}","line":{"from":863,"to":867}} {"id":100004869,"name":"GetConfigMapFunc","signature":"func (adc *attachDetachController) GetConfigMapFunc() func(namespace, name string) (*v1.ConfigMap, error)","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) GetConfigMapFunc() func(namespace, name string) (*v1.ConfigMap, error) {\n\treturn func(_, _ string) (*v1.ConfigMap, error) {\n\t\treturn nil, fmt.Errorf(\"GetConfigMap unsupported in attachDetachController\")\n\t}\n}","line":{"from":869,"to":873}} {"id":100004870,"name":"GetServiceAccountTokenFunc","signature":"func (adc *attachDetachController) GetServiceAccountTokenFunc() func(_, _ string, _ *authenticationv1.TokenRequest) (*authenticationv1.TokenRequest, error)","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) GetServiceAccountTokenFunc() func(_, _ string, _ *authenticationv1.TokenRequest) (*authenticationv1.TokenRequest, error) {\n\treturn func(_, _ string, _ *authenticationv1.TokenRequest) (*authenticationv1.TokenRequest, error) {\n\t\treturn nil, fmt.Errorf(\"GetServiceAccountToken unsupported in attachDetachController\")\n\t}\n}","line":{"from":875,"to":879}} {"id":100004871,"name":"DeleteServiceAccountTokenFunc","signature":"func (adc *attachDetachController) DeleteServiceAccountTokenFunc() func(types.UID)","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) DeleteServiceAccountTokenFunc() func(types.UID) {\n\treturn func(types.UID) {\n\t\tklog.ErrorS(nil, \"DeleteServiceAccountToken unsupported in attachDetachController\")\n\t}\n}","line":{"from":881,"to":885}} {"id":100004872,"name":"GetExec","signature":"func (adc *attachDetachController) GetExec(pluginName string) utilexec.Interface","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) GetExec(pluginName string) utilexec.Interface {\n\treturn utilexec.New()\n}","line":{"from":887,"to":889}} {"id":100004873,"name":"addNodeToDswp","signature":"func (adc *attachDetachController) addNodeToDswp(node *v1.Node, nodeName types.NodeName)","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) addNodeToDswp(node *v1.Node, nodeName types.NodeName) {\n\tif _, exists := node.Annotations[volumeutil.ControllerManagedAttachAnnotation]; exists {\n\t\tkeepTerminatedPodVolumes := false\n\n\t\tif t, ok := node.Annotations[volumeutil.KeepTerminatedPodVolumesAnnotation]; ok {\n\t\t\tkeepTerminatedPodVolumes = t == \"true\"\n\t\t}\n\n\t\t// Node specifies annotation indicating it should be managed by attach\n\t\t// detach controller. Add it to desired state of world.\n\t\tadc.desiredStateOfWorld.AddNode(nodeName, keepTerminatedPodVolumes)\n\t}\n}","line":{"from":891,"to":903}} {"id":100004874,"name":"GetNodeLabels","signature":"func (adc *attachDetachController) GetNodeLabels() (map[string]string, error)","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) GetNodeLabels() (map[string]string, error) {\n\treturn nil, fmt.Errorf(\"GetNodeLabels() unsupported in Attach/Detach controller\")\n}","line":{"from":905,"to":907}} {"id":100004875,"name":"GetNodeName","signature":"func (adc *attachDetachController) GetNodeName() types.NodeName","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) GetNodeName() types.NodeName {\n\treturn \"\"\n}","line":{"from":909,"to":911}} {"id":100004876,"name":"GetEventRecorder","signature":"func (adc *attachDetachController) GetEventRecorder() record.EventRecorder","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) GetEventRecorder() record.EventRecorder {\n\treturn nil\n}","line":{"from":913,"to":915}} {"id":100004877,"name":"GetSubpather","signature":"func (adc *attachDetachController) GetSubpather() subpath.Interface","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) GetSubpather() subpath.Interface {\n\t// Subpaths not needed in attachdetach controller\n\treturn nil\n}","line":{"from":917,"to":920}} {"id":100004878,"name":"GetFilteredDialOptions","signature":"func (adc *attachDetachController) GetFilteredDialOptions() *proxyutil.FilteredDialOptions","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) GetFilteredDialOptions() *proxyutil.FilteredDialOptions {\n\treturn adc.filteredDialOptions\n}","line":{"from":922,"to":924}} {"id":100004879,"name":"GetCSIDriverLister","signature":"func (adc *attachDetachController) GetCSIDriverLister() storagelistersv1.CSIDriverLister","file":"pkg/controller/volume/attachdetach/attach_detach_controller.go","code":"func (adc *attachDetachController) GetCSIDriverLister() storagelistersv1.CSIDriverLister {\n\treturn adc.csiDriverLister\n}","line":{"from":926,"to":928}} {"id":100004880,"name":"String","signature":"func (s AttachState) String() string","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"func (s AttachState) String() string {\n\treturn []string{\"Attached\", \"Uncertain\", \"Detached\"}[s]\n}","line":{"from":186,"to":188}} {"id":100004881,"name":"NewActualStateOfWorld","signature":"func NewActualStateOfWorld(volumePluginMgr *volume.VolumePluginMgr) ActualStateOfWorld","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"// NewActualStateOfWorld returns a new instance of ActualStateOfWorld.\nfunc NewActualStateOfWorld(volumePluginMgr *volume.VolumePluginMgr) ActualStateOfWorld {\n\treturn \u0026actualStateOfWorld{\n\t\tattachedVolumes: make(map[v1.UniqueVolumeName]attachedVolume),\n\t\tnodesToUpdateStatusFor: make(map[types.NodeName]nodeToUpdateStatusFor),\n\t\tvolumePluginMgr: volumePluginMgr,\n\t}\n}","line":{"from":190,"to":197}} {"id":100004882,"name":"MarkVolumeAsUncertain","signature":"func (asw *actualStateOfWorld) MarkVolumeAsUncertain(","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) MarkVolumeAsUncertain(\n\tlogger klog.Logger,\n\tuniqueName v1.UniqueVolumeName, volumeSpec *volume.Spec, nodeName types.NodeName) error {\n\n\t_, err := asw.AddVolumeNode(logger, uniqueName, volumeSpec, nodeName, \"\", false /* isAttached */)\n\treturn err\n}","line":{"from":280,"to":286}} {"id":100004883,"name":"MarkVolumeAsAttached","signature":"func (asw *actualStateOfWorld) MarkVolumeAsAttached(","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) MarkVolumeAsAttached(\n\tlogger klog.Logger,\n\tuniqueName v1.UniqueVolumeName, volumeSpec *volume.Spec, nodeName types.NodeName, devicePath string) error {\n\t_, err := asw.AddVolumeNode(logger, uniqueName, volumeSpec, nodeName, devicePath, true)\n\treturn err\n}","line":{"from":288,"to":293}} {"id":100004884,"name":"MarkVolumeAsDetached","signature":"func (asw *actualStateOfWorld) MarkVolumeAsDetached(","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) MarkVolumeAsDetached(\n\tvolumeName v1.UniqueVolumeName, nodeName types.NodeName) {\n\tasw.DeleteVolumeNode(volumeName, nodeName)\n}","line":{"from":295,"to":298}} {"id":100004885,"name":"RemoveVolumeFromReportAsAttached","signature":"func (asw *actualStateOfWorld) RemoveVolumeFromReportAsAttached(","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) RemoveVolumeFromReportAsAttached(\n\tvolumeName v1.UniqueVolumeName, nodeName types.NodeName) error {\n\tasw.Lock()\n\tdefer asw.Unlock()\n\treturn asw.removeVolumeFromReportAsAttached(volumeName, nodeName)\n}","line":{"from":300,"to":305}} {"id":100004886,"name":"AddVolumeToReportAsAttached","signature":"func (asw *actualStateOfWorld) AddVolumeToReportAsAttached(","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) AddVolumeToReportAsAttached(\n\tlogger klog.Logger,\n\tvolumeName v1.UniqueVolumeName, nodeName types.NodeName) {\n\tasw.Lock()\n\tdefer asw.Unlock()\n\tasw.addVolumeToReportAsAttached(logger, volumeName, nodeName)\n}","line":{"from":307,"to":313}} {"id":100004887,"name":"AddVolumeNode","signature":"func (asw *actualStateOfWorld) AddVolumeNode(","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) AddVolumeNode(\n\tlogger klog.Logger,\n\tuniqueName v1.UniqueVolumeName, volumeSpec *volume.Spec, nodeName types.NodeName, devicePath string, isAttached bool) (v1.UniqueVolumeName, error) {\n\tvolumeName := uniqueName\n\tif volumeName == \"\" {\n\t\tif volumeSpec == nil {\n\t\t\treturn volumeName, fmt.Errorf(\"volumeSpec cannot be nil if volumeName is empty\")\n\t\t}\n\t\tattachableVolumePlugin, err := asw.volumePluginMgr.FindAttachablePluginBySpec(volumeSpec)\n\t\tif err != nil || attachableVolumePlugin == nil {\n\t\t\tif attachableVolumePlugin == nil {\n\t\t\t\terr = fmt.Errorf(\"plugin do not support attachment\")\n\t\t\t}\n\t\t\treturn \"\", fmt.Errorf(\n\t\t\t\t\"failed to get AttachablePlugin from volumeSpec for volume %q err=%v\",\n\t\t\t\tvolumeSpec.Name(),\n\t\t\t\terr)\n\t\t}\n\n\t\tvolumeName, err = util.GetUniqueVolumeNameFromSpec(\n\t\t\tattachableVolumePlugin, volumeSpec)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\n\t\t\t\t\"failed to GetUniqueVolumeNameFromSpec for volumeSpec %q err=%v\",\n\t\t\t\tvolumeSpec.Name(),\n\t\t\t\terr)\n\t\t}\n\t}\n\n\tasw.Lock()\n\tdefer asw.Unlock()\n\n\tvolumeObj, volumeExists := asw.attachedVolumes[volumeName]\n\tif !volumeExists {\n\t\tvolumeObj = attachedVolume{\n\t\t\tvolumeName: volumeName,\n\t\t\tspec: volumeSpec,\n\t\t\tnodesAttachedTo: make(map[types.NodeName]nodeAttachedTo),\n\t\t\tdevicePath: devicePath,\n\t\t}\n\t} else {\n\t\t// If volume object already exists, it indicates that the information would be out of date.\n\t\t// Update the fields for volume object except the nodes attached to the volumes.\n\t\tvolumeObj.devicePath = devicePath\n\t\tvolumeObj.spec = volumeSpec\n\t\tlogger.V(2).Info(\"Volume is already added to attachedVolume list to node, update device path\",\n\t\t\t\"volumeName\", volumeName,\n\t\t\t\"node\", klog.KRef(\"\", string(nodeName)),\n\t\t\t\"devicePath\", devicePath)\n\t}\n\tnode, nodeExists := volumeObj.nodesAttachedTo[nodeName]\n\tif !nodeExists {\n\t\t// Create object if it doesn't exist.\n\t\tnode = nodeAttachedTo{\n\t\t\tnodeName: nodeName,\n\t\t\tmountedByNode: true, // Assume mounted, until proven otherwise\n\t\t\tattachedConfirmed: isAttached,\n\t\t\tdetachRequestedTime: time.Time{},\n\t\t}\n\t} else {\n\t\tnode.attachedConfirmed = isAttached\n\t\tlogger.V(5).Info(\"Volume is already added to attachedVolume list to the node\",\n\t\t\t\"volumeName\", volumeName,\n\t\t\t\"node\", klog.KRef(\"\", string(nodeName)),\n\t\t\t\"currentAttachState\", isAttached)\n\t}\n\n\tvolumeObj.nodesAttachedTo[nodeName] = node\n\tasw.attachedVolumes[volumeName] = volumeObj\n\n\tif isAttached {\n\t\tasw.addVolumeToReportAsAttached(logger, volumeName, nodeName)\n\t}\n\treturn volumeName, nil\n}","line":{"from":315,"to":389}} {"id":100004888,"name":"SetVolumeMountedByNode","signature":"func (asw *actualStateOfWorld) SetVolumeMountedByNode(","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) SetVolumeMountedByNode(\n\tlogger klog.Logger,\n\tvolumeName v1.UniqueVolumeName, nodeName types.NodeName, mounted bool) error {\n\tasw.Lock()\n\tdefer asw.Unlock()\n\n\tvolumeObj, nodeObj, err := asw.getNodeAndVolume(volumeName, nodeName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to SetVolumeMountedByNode with error: %v\", err)\n\t}\n\n\tnodeObj.mountedByNode = mounted\n\tvolumeObj.nodesAttachedTo[nodeName] = nodeObj\n\tlogger.V(4).Info(\"SetVolumeMountedByNode volume to the node\",\n\t\t\"node\", klog.KRef(\"\", string(nodeName)),\n\t\t\"volumeName\", volumeName,\n\t\t\"mounted\", mounted)\n\treturn nil\n}","line":{"from":391,"to":409}} {"id":100004889,"name":"ResetDetachRequestTime","signature":"func (asw *actualStateOfWorld) ResetDetachRequestTime(","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) ResetDetachRequestTime(\n\tlogger klog.Logger,\n\tvolumeName v1.UniqueVolumeName, nodeName types.NodeName) {\n\tasw.Lock()\n\tdefer asw.Unlock()\n\n\tvolumeObj, nodeObj, err := asw.getNodeAndVolume(volumeName, nodeName)\n\tif err != nil {\n\t\tlogger.Error(err, \"Failed to ResetDetachRequestTime with error\")\n\t\treturn\n\t}\n\tnodeObj.detachRequestedTime = time.Time{}\n\tvolumeObj.nodesAttachedTo[nodeName] = nodeObj\n}","line":{"from":411,"to":424}} {"id":100004890,"name":"SetDetachRequestTime","signature":"func (asw *actualStateOfWorld) SetDetachRequestTime(","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) SetDetachRequestTime(\n\tlogger klog.Logger,\n\tvolumeName v1.UniqueVolumeName, nodeName types.NodeName) (time.Duration, error) {\n\tasw.Lock()\n\tdefer asw.Unlock()\n\n\tvolumeObj, nodeObj, err := asw.getNodeAndVolume(volumeName, nodeName)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"failed to set detach request time with error: %v\", err)\n\t}\n\t// If there is no previous detach request, set it to the current time\n\tif nodeObj.detachRequestedTime.IsZero() {\n\t\tnodeObj.detachRequestedTime = time.Now()\n\t\tvolumeObj.nodesAttachedTo[nodeName] = nodeObj\n\t\tlogger.V(4).Info(\"Set detach request time to current time for volume on node\",\n\t\t\t\"node\", klog.KRef(\"\", string(nodeName)),\n\t\t\t\"volumeName\", volumeName)\n\t}\n\treturn time.Since(nodeObj.detachRequestedTime), nil\n}","line":{"from":426,"to":445}} {"id":100004891,"name":"getNodeAndVolume","signature":"func (asw *actualStateOfWorld) getNodeAndVolume(","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"// Get the volume and node object from actual state of world\n// This is an internal function and caller should acquire and release the lock\n//\n// Note that this returns disconnected objects, so if you change the volume object you must set it back with\n// `asw.attachedVolumes[volumeName]=volumeObj`.\n//\n// If you change the node object you must use `volumeObj.nodesAttachedTo[nodeName] = nodeObj`\n// This is correct, because if volumeObj is empty this function returns an error, and nodesAttachedTo\n// map is a reference type, and thus mutating the copy changes the original map.\nfunc (asw *actualStateOfWorld) getNodeAndVolume(\n\tvolumeName v1.UniqueVolumeName, nodeName types.NodeName) (attachedVolume, nodeAttachedTo, error) {\n\n\tvolumeObj, volumeExists := asw.attachedVolumes[volumeName]\n\tif volumeExists {\n\t\tnodeObj, nodeExists := volumeObj.nodesAttachedTo[nodeName]\n\t\tif nodeExists {\n\t\t\treturn volumeObj, nodeObj, nil\n\t\t}\n\t}\n\n\treturn attachedVolume{}, nodeAttachedTo{}, fmt.Errorf(\"volume %v is no longer attached to the node %q\",\n\t\tvolumeName,\n\t\tnodeName)\n}","line":{"from":447,"to":470}} {"id":100004892,"name":"removeVolumeFromReportAsAttached","signature":"func (asw *actualStateOfWorld) removeVolumeFromReportAsAttached(","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"// Remove the volumeName from the node's volumesToReportAsAttached list\n// This is an internal function and caller should acquire and release the lock\nfunc (asw *actualStateOfWorld) removeVolumeFromReportAsAttached(\n\tvolumeName v1.UniqueVolumeName, nodeName types.NodeName) error {\n\n\tnodeToUpdate, nodeToUpdateExists := asw.nodesToUpdateStatusFor[nodeName]\n\tif nodeToUpdateExists {\n\t\t_, nodeToUpdateVolumeExists :=\n\t\t\tnodeToUpdate.volumesToReportAsAttached[volumeName]\n\t\tif nodeToUpdateVolumeExists {\n\t\t\tnodeToUpdate.statusUpdateNeeded = true\n\t\t\tdelete(nodeToUpdate.volumesToReportAsAttached, volumeName)\n\t\t\tasw.nodesToUpdateStatusFor[nodeName] = nodeToUpdate\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"volume %q does not exist in volumesToReportAsAttached list or node %q does not exist in nodesToUpdateStatusFor list\",\n\t\tvolumeName,\n\t\tnodeName)\n\n}","line":{"from":472,"to":492}} {"id":100004893,"name":"addVolumeToReportAsAttached","signature":"func (asw *actualStateOfWorld) addVolumeToReportAsAttached(","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"// Add the volumeName to the node's volumesToReportAsAttached list\n// This is an internal function and caller should acquire and release the lock\nfunc (asw *actualStateOfWorld) addVolumeToReportAsAttached(\n\tlogger klog.Logger, volumeName v1.UniqueVolumeName, nodeName types.NodeName) {\n\t// In case the volume/node entry is no longer in attachedVolume list, skip the rest\n\tif _, _, err := asw.getNodeAndVolume(volumeName, nodeName); err != nil {\n\t\tlogger.V(4).Info(\"Volume is no longer attached to node\", \"node\", klog.KRef(\"\", string(nodeName)), \"volumeName\", volumeName)\n\t\treturn\n\t}\n\tnodeToUpdate, nodeToUpdateExists := asw.nodesToUpdateStatusFor[nodeName]\n\tif !nodeToUpdateExists {\n\t\t// Create object if it doesn't exist\n\t\tnodeToUpdate = nodeToUpdateStatusFor{\n\t\t\tnodeName: nodeName,\n\t\t\tstatusUpdateNeeded: true,\n\t\t\tvolumesToReportAsAttached: make(map[v1.UniqueVolumeName]v1.UniqueVolumeName),\n\t\t}\n\t\tasw.nodesToUpdateStatusFor[nodeName] = nodeToUpdate\n\t\tlogger.V(4).Info(\"Add new node to nodesToUpdateStatusFor\", \"node\", klog.KRef(\"\", string(nodeName)))\n\t}\n\t_, nodeToUpdateVolumeExists :=\n\t\tnodeToUpdate.volumesToReportAsAttached[volumeName]\n\tif !nodeToUpdateVolumeExists {\n\t\tnodeToUpdate.statusUpdateNeeded = true\n\t\tnodeToUpdate.volumesToReportAsAttached[volumeName] = volumeName\n\t\tasw.nodesToUpdateStatusFor[nodeName] = nodeToUpdate\n\t\tlogger.V(4).Info(\"Report volume as attached to node\", \"node\", klog.KRef(\"\", string(nodeName)), \"volumeName\", volumeName)\n\t}\n}","line":{"from":494,"to":522}} {"id":100004894,"name":"updateNodeStatusUpdateNeeded","signature":"func (asw *actualStateOfWorld) updateNodeStatusUpdateNeeded(nodeName types.NodeName, needed bool) error","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"// Update the flag statusUpdateNeeded to indicate whether node status is already updated or\n// needs to be updated again by the node status updater.\n// If the specified node does not exist in the nodesToUpdateStatusFor list, log the error and return\n// This is an internal function and caller should acquire and release the lock\nfunc (asw *actualStateOfWorld) updateNodeStatusUpdateNeeded(nodeName types.NodeName, needed bool) error {\n\tnodeToUpdate, nodeToUpdateExists := asw.nodesToUpdateStatusFor[nodeName]\n\tif !nodeToUpdateExists {\n\t\t// should not happen\n\t\terrMsg := fmt.Sprintf(\"Failed to set statusUpdateNeeded to needed %t, because nodeName=%q does not exist\",\n\t\t\tneeded, nodeName)\n\t\treturn fmt.Errorf(errMsg)\n\t}\n\n\tnodeToUpdate.statusUpdateNeeded = needed\n\tasw.nodesToUpdateStatusFor[nodeName] = nodeToUpdate\n\n\treturn nil\n}","line":{"from":524,"to":541}} {"id":100004895,"name":"SetNodeStatusUpdateNeeded","signature":"func (asw *actualStateOfWorld) SetNodeStatusUpdateNeeded(logger klog.Logger, nodeName types.NodeName)","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) SetNodeStatusUpdateNeeded(logger klog.Logger, nodeName types.NodeName) {\n\tasw.Lock()\n\tdefer asw.Unlock()\n\tif err := asw.updateNodeStatusUpdateNeeded(nodeName, true); err != nil {\n\t\tlogger.Info(\"Failed to update statusUpdateNeeded field in actual state of world\", \"err\", err)\n\t}\n}","line":{"from":543,"to":549}} {"id":100004896,"name":"DeleteVolumeNode","signature":"func (asw *actualStateOfWorld) DeleteVolumeNode(","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) DeleteVolumeNode(\n\tvolumeName v1.UniqueVolumeName, nodeName types.NodeName) {\n\tasw.Lock()\n\tdefer asw.Unlock()\n\n\tvolumeObj, volumeExists := asw.attachedVolumes[volumeName]\n\tif !volumeExists {\n\t\treturn\n\t}\n\n\t_, nodeExists := volumeObj.nodesAttachedTo[nodeName]\n\tif nodeExists {\n\t\tdelete(asw.attachedVolumes[volumeName].nodesAttachedTo, nodeName)\n\t}\n\n\tif len(volumeObj.nodesAttachedTo) == 0 {\n\t\tdelete(asw.attachedVolumes, volumeName)\n\t}\n\n\t// Remove volume from volumes to report as attached\n\tasw.removeVolumeFromReportAsAttached(volumeName, nodeName)\n}","line":{"from":551,"to":572}} {"id":100004897,"name":"GetAttachState","signature":"func (asw *actualStateOfWorld) GetAttachState(","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) GetAttachState(\n\tvolumeName v1.UniqueVolumeName, nodeName types.NodeName) AttachState {\n\tasw.RLock()\n\tdefer asw.RUnlock()\n\n\tvolumeObj, volumeExists := asw.attachedVolumes[volumeName]\n\tif volumeExists {\n\t\tif node, nodeExists := volumeObj.nodesAttachedTo[nodeName]; nodeExists {\n\t\t\tif node.attachedConfirmed {\n\t\t\t\treturn AttachStateAttached\n\t\t\t}\n\t\t\treturn AttachStateUncertain\n\t\t}\n\t}\n\n\treturn AttachStateDetached\n}","line":{"from":574,"to":590}} {"id":100004898,"name":"InitializeClaimSize","signature":"func (asw *actualStateOfWorld) InitializeClaimSize(logger klog.Logger, volumeName v1.UniqueVolumeName, claimSize *resource.Quantity)","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"// SetVolumeClaimSize sets size of the volume. But this function should not be used from attach_detach controller.\nfunc (asw *actualStateOfWorld) InitializeClaimSize(logger klog.Logger, volumeName v1.UniqueVolumeName, claimSize *resource.Quantity) {\n\tlogger.V(5).Info(\"no-op InitializeClaimSize call in attach-detach controller\")\n}","line":{"from":592,"to":595}} {"id":100004899,"name":"GetClaimSize","signature":"func (asw *actualStateOfWorld) GetClaimSize(volumeName v1.UniqueVolumeName) *resource.Quantity","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) GetClaimSize(volumeName v1.UniqueVolumeName) *resource.Quantity {\n\t// not needed in attach-detach controller\n\treturn nil\n}","line":{"from":597,"to":600}} {"id":100004900,"name":"GetAttachedVolumes","signature":"func (asw *actualStateOfWorld) GetAttachedVolumes() []AttachedVolume","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) GetAttachedVolumes() []AttachedVolume {\n\tasw.RLock()\n\tdefer asw.RUnlock()\n\n\tattachedVolumes := make([]AttachedVolume, 0 /* len */, len(asw.attachedVolumes) /* cap */)\n\tfor _, volumeObj := range asw.attachedVolumes {\n\t\tfor _, nodeObj := range volumeObj.nodesAttachedTo {\n\t\t\tattachedVolumes = append(\n\t\t\t\tattachedVolumes,\n\t\t\t\tgetAttachedVolume(\u0026volumeObj, \u0026nodeObj))\n\t\t}\n\t}\n\n\treturn attachedVolumes\n}","line":{"from":602,"to":616}} {"id":100004901,"name":"GetAttachedVolumesForNode","signature":"func (asw *actualStateOfWorld) GetAttachedVolumesForNode(","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) GetAttachedVolumesForNode(\n\tnodeName types.NodeName) []AttachedVolume {\n\tasw.RLock()\n\tdefer asw.RUnlock()\n\n\tattachedVolumes := make(\n\t\t[]AttachedVolume, 0 /* len */, len(asw.attachedVolumes) /* cap */)\n\tfor _, volumeObj := range asw.attachedVolumes {\n\t\tif nodeObj, nodeExists := volumeObj.nodesAttachedTo[nodeName]; nodeExists {\n\t\t\tattachedVolumes = append(\n\t\t\t\tattachedVolumes,\n\t\t\t\tgetAttachedVolume(\u0026volumeObj, \u0026nodeObj))\n\t\t}\n\t}\n\n\treturn attachedVolumes\n}","line":{"from":618,"to":634}} {"id":100004902,"name":"GetAttachedVolumesPerNode","signature":"func (asw *actualStateOfWorld) GetAttachedVolumesPerNode() map[types.NodeName][]operationexecutor.AttachedVolume","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) GetAttachedVolumesPerNode() map[types.NodeName][]operationexecutor.AttachedVolume {\n\tasw.RLock()\n\tdefer asw.RUnlock()\n\n\tattachedVolumesPerNode := make(map[types.NodeName][]operationexecutor.AttachedVolume)\n\tfor _, volumeObj := range asw.attachedVolumes {\n\t\tfor nodeName, nodeObj := range volumeObj.nodesAttachedTo {\n\t\t\tif nodeObj.attachedConfirmed {\n\t\t\t\tvolumes := attachedVolumesPerNode[nodeName]\n\t\t\t\tvolumes = append(volumes, getAttachedVolume(\u0026volumeObj, \u0026nodeObj).AttachedVolume)\n\t\t\t\tattachedVolumesPerNode[nodeName] = volumes\n\t\t\t}\n\t\t}\n\t}\n\n\treturn attachedVolumesPerNode\n}","line":{"from":636,"to":652}} {"id":100004903,"name":"GetNodesForAttachedVolume","signature":"func (asw *actualStateOfWorld) GetNodesForAttachedVolume(volumeName v1.UniqueVolumeName) []types.NodeName","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) GetNodesForAttachedVolume(volumeName v1.UniqueVolumeName) []types.NodeName {\n\tasw.RLock()\n\tdefer asw.RUnlock()\n\n\tvolumeObj, volumeExists := asw.attachedVolumes[volumeName]\n\tif !volumeExists || len(volumeObj.nodesAttachedTo) == 0 {\n\t\treturn []types.NodeName{}\n\t}\n\n\tnodes := []types.NodeName{}\n\tfor nodeName, nodesAttached := range volumeObj.nodesAttachedTo {\n\t\tif nodesAttached.attachedConfirmed {\n\t\t\tnodes = append(nodes, nodeName)\n\t\t}\n\t}\n\treturn nodes\n}","line":{"from":654,"to":670}} {"id":100004904,"name":"GetVolumesToReportAttached","signature":"func (asw *actualStateOfWorld) GetVolumesToReportAttached(logger klog.Logger) map[types.NodeName][]v1.AttachedVolume","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) GetVolumesToReportAttached(logger klog.Logger) map[types.NodeName][]v1.AttachedVolume {\n\tasw.Lock()\n\tdefer asw.Unlock()\n\n\tvolumesToReportAttached := make(map[types.NodeName][]v1.AttachedVolume)\n\tfor nodeName, nodeToUpdateObj := range asw.nodesToUpdateStatusFor {\n\t\tif nodeToUpdateObj.statusUpdateNeeded {\n\t\t\tvolumesToReportAttached[nodeToUpdateObj.nodeName] = asw.getAttachedVolumeFromUpdateObject(nodeToUpdateObj.volumesToReportAsAttached)\n\t\t}\n\t\t// When GetVolumesToReportAttached is called by node status updater, the current status\n\t\t// of this node will be updated, so set the flag statusUpdateNeeded to false indicating\n\t\t// the current status is already updated.\n\t\tif err := asw.updateNodeStatusUpdateNeeded(nodeName, false); err != nil {\n\t\t\tlogger.Error(err, \"Failed to update statusUpdateNeeded field when getting volumes\")\n\t\t}\n\t}\n\n\treturn volumesToReportAttached\n}","line":{"from":672,"to":690}} {"id":100004905,"name":"GetVolumesToReportAttachedForNode","signature":"func (asw *actualStateOfWorld) GetVolumesToReportAttachedForNode(logger klog.Logger, nodeName types.NodeName) (bool, []v1.AttachedVolume)","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) GetVolumesToReportAttachedForNode(logger klog.Logger, nodeName types.NodeName) (bool, []v1.AttachedVolume) {\n\tasw.Lock()\n\tdefer asw.Unlock()\n\n\tnodeToUpdateObj, ok := asw.nodesToUpdateStatusFor[nodeName]\n\tif !ok {\n\t\treturn false, nil\n\t}\n\tif !nodeToUpdateObj.statusUpdateNeeded {\n\t\treturn false, nil\n\t}\n\n\tvolumesToReportAttached := asw.getAttachedVolumeFromUpdateObject(nodeToUpdateObj.volumesToReportAsAttached)\n\t// When GetVolumesToReportAttached is called by node status updater, the current status\n\t// of this node will be updated, so set the flag statusUpdateNeeded to false indicating\n\t// the current status is already updated.\n\tif err := asw.updateNodeStatusUpdateNeeded(nodeName, false); err != nil {\n\t\tlogger.Error(err, \"Failed to update statusUpdateNeeded field when getting volumes\")\n\t}\n\n\treturn true, volumesToReportAttached\n}","line":{"from":692,"to":713}} {"id":100004906,"name":"GetNodesToUpdateStatusFor","signature":"func (asw *actualStateOfWorld) GetNodesToUpdateStatusFor() map[types.NodeName]nodeToUpdateStatusFor","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) GetNodesToUpdateStatusFor() map[types.NodeName]nodeToUpdateStatusFor {\n\treturn asw.nodesToUpdateStatusFor\n}","line":{"from":715,"to":717}} {"id":100004907,"name":"getAttachedVolumeFromUpdateObject","signature":"func (asw *actualStateOfWorld) getAttachedVolumeFromUpdateObject(volumesToReportAsAttached map[v1.UniqueVolumeName]v1.UniqueVolumeName) []v1.AttachedVolume","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) getAttachedVolumeFromUpdateObject(volumesToReportAsAttached map[v1.UniqueVolumeName]v1.UniqueVolumeName) []v1.AttachedVolume {\n\tvar attachedVolumes = make(\n\t\t[]v1.AttachedVolume,\n\t\t0,\n\t\tlen(volumesToReportAsAttached) /* len */)\n\tfor _, volume := range volumesToReportAsAttached {\n\t\tattachedVolumes = append(attachedVolumes,\n\t\t\tv1.AttachedVolume{\n\t\t\t\tName: volume,\n\t\t\t\tDevicePath: asw.attachedVolumes[volume].devicePath,\n\t\t\t})\n\t}\n\treturn attachedVolumes\n}","line":{"from":719,"to":732}} {"id":100004908,"name":"getAttachedVolume","signature":"func getAttachedVolume(","file":"pkg/controller/volume/attachdetach/cache/actual_state_of_world.go","code":"func getAttachedVolume(\n\tattachedVolume *attachedVolume,\n\tnodeAttachedTo *nodeAttachedTo) AttachedVolume {\n\treturn AttachedVolume{\n\t\tAttachedVolume: operationexecutor.AttachedVolume{\n\t\t\tVolumeName: attachedVolume.volumeName,\n\t\t\tVolumeSpec: attachedVolume.spec,\n\t\t\tNodeName: nodeAttachedTo.nodeName,\n\t\t\tDevicePath: attachedVolume.devicePath,\n\t\t\tPluginIsAttachable: true,\n\t\t},\n\t\tMountedByNode: nodeAttachedTo.mountedByNode,\n\t\tDetachRequestedTime: nodeAttachedTo.detachRequestedTime}\n}","line":{"from":734,"to":747}} {"id":100004909,"name":"NewDesiredStateOfWorld","signature":"func NewDesiredStateOfWorld(volumePluginMgr *volume.VolumePluginMgr) DesiredStateOfWorld","file":"pkg/controller/volume/attachdetach/cache/desired_state_of_world.go","code":"// NewDesiredStateOfWorld returns a new instance of DesiredStateOfWorld.\nfunc NewDesiredStateOfWorld(volumePluginMgr *volume.VolumePluginMgr) DesiredStateOfWorld {\n\treturn \u0026desiredStateOfWorld{\n\t\tnodesManaged: make(map[k8stypes.NodeName]nodeManaged),\n\t\tvolumePluginMgr: volumePluginMgr,\n\t}\n}","line":{"from":132,"to":138}} {"id":100004910,"name":"AddNode","signature":"func (dsw *desiredStateOfWorld) AddNode(nodeName k8stypes.NodeName, keepTerminatedPodVolumes bool)","file":"pkg/controller/volume/attachdetach/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) AddNode(nodeName k8stypes.NodeName, keepTerminatedPodVolumes bool) {\n\tdsw.Lock()\n\tdefer dsw.Unlock()\n\n\tif _, nodeExists := dsw.nodesManaged[nodeName]; !nodeExists {\n\t\tdsw.nodesManaged[nodeName] = nodeManaged{\n\t\t\tnodeName: nodeName,\n\t\t\tvolumesToAttach: make(map[v1.UniqueVolumeName]volumeToAttach),\n\t\t\tkeepTerminatedPodVolumes: keepTerminatedPodVolumes,\n\t\t}\n\t}\n}","line":{"from":198,"to":209}} {"id":100004911,"name":"AddPod","signature":"func (dsw *desiredStateOfWorld) AddPod(","file":"pkg/controller/volume/attachdetach/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) AddPod(\n\tpodName types.UniquePodName,\n\tpodToAdd *v1.Pod,\n\tvolumeSpec *volume.Spec,\n\tnodeName k8stypes.NodeName) (v1.UniqueVolumeName, error) {\n\tdsw.Lock()\n\tdefer dsw.Unlock()\n\n\tnodeObj, nodeExists := dsw.nodesManaged[nodeName]\n\tif !nodeExists {\n\t\treturn \"\", fmt.Errorf(\n\t\t\t\"no node with the name %q exists in the list of managed nodes\",\n\t\t\tnodeName)\n\t}\n\n\tattachableVolumePlugin, err := dsw.volumePluginMgr.FindAttachablePluginBySpec(volumeSpec)\n\tif err != nil || attachableVolumePlugin == nil {\n\t\tif attachableVolumePlugin == nil {\n\t\t\terr = fmt.Errorf(\"plugin do not support attachment\")\n\t\t}\n\t\treturn \"\", fmt.Errorf(\n\t\t\t\"failed to get AttachablePlugin from volumeSpec for volume %q err=%v\",\n\t\t\tvolumeSpec.Name(),\n\t\t\terr)\n\t}\n\n\tvolumeName, err := util.GetUniqueVolumeNameFromSpec(\n\t\tattachableVolumePlugin, volumeSpec)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\n\t\t\t\"failed to get UniqueVolumeName from volumeSpec for plugin=%q and volume=%q err=%v\",\n\t\t\tattachableVolumePlugin.GetPluginName(),\n\t\t\tvolumeSpec.Name(),\n\t\t\terr)\n\t}\n\n\tvolumeObj, volumeExists := nodeObj.volumesToAttach[volumeName]\n\tif !volumeExists {\n\t\tvolumeObj = volumeToAttach{\n\t\t\tmultiAttachErrorReported: false,\n\t\t\tvolumeName: volumeName,\n\t\t\tspec: volumeSpec,\n\t\t\tscheduledPods: make(map[types.UniquePodName]pod),\n\t\t}\n\t\tdsw.nodesManaged[nodeName].volumesToAttach[volumeName] = volumeObj\n\t}\n\tif _, podExists := volumeObj.scheduledPods[podName]; !podExists {\n\t\tdsw.nodesManaged[nodeName].volumesToAttach[volumeName].scheduledPods[podName] =\n\t\t\tpod{\n\t\t\t\tpodName: podName,\n\t\t\t\tpodObj: podToAdd,\n\t\t\t}\n\t}\n\n\treturn volumeName, nil\n}","line":{"from":211,"to":266}} {"id":100004912,"name":"DeleteNode","signature":"func (dsw *desiredStateOfWorld) DeleteNode(nodeName k8stypes.NodeName) error","file":"pkg/controller/volume/attachdetach/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) DeleteNode(nodeName k8stypes.NodeName) error {\n\tdsw.Lock()\n\tdefer dsw.Unlock()\n\n\tnodeObj, nodeExists := dsw.nodesManaged[nodeName]\n\tif !nodeExists {\n\t\treturn nil\n\t}\n\n\tif len(nodeObj.volumesToAttach) \u003e 0 {\n\t\treturn fmt.Errorf(\n\t\t\t\"failed to delete node %q from list of nodes managed by attach/detach controller--the node still contains %v volumes in its list of volumes to attach\",\n\t\t\tnodeName,\n\t\t\tlen(nodeObj.volumesToAttach))\n\t}\n\n\tdelete(\n\t\tdsw.nodesManaged,\n\t\tnodeName)\n\treturn nil\n}","line":{"from":268,"to":288}} {"id":100004913,"name":"DeletePod","signature":"func (dsw *desiredStateOfWorld) DeletePod(","file":"pkg/controller/volume/attachdetach/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) DeletePod(\n\tpodName types.UniquePodName,\n\tvolumeName v1.UniqueVolumeName,\n\tnodeName k8stypes.NodeName) {\n\tdsw.Lock()\n\tdefer dsw.Unlock()\n\n\tnodeObj, nodeExists := dsw.nodesManaged[nodeName]\n\tif !nodeExists {\n\t\treturn\n\t}\n\n\tvolumeObj, volumeExists := nodeObj.volumesToAttach[volumeName]\n\tif !volumeExists {\n\t\treturn\n\t}\n\tif _, podExists := volumeObj.scheduledPods[podName]; !podExists {\n\t\treturn\n\t}\n\n\tdelete(\n\t\tdsw.nodesManaged[nodeName].volumesToAttach[volumeName].scheduledPods,\n\t\tpodName)\n\n\tif len(volumeObj.scheduledPods) == 0 {\n\t\tdelete(\n\t\t\tdsw.nodesManaged[nodeName].volumesToAttach,\n\t\t\tvolumeName)\n\t}\n}","line":{"from":290,"to":319}} {"id":100004914,"name":"NodeExists","signature":"func (dsw *desiredStateOfWorld) NodeExists(nodeName k8stypes.NodeName) bool","file":"pkg/controller/volume/attachdetach/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) NodeExists(nodeName k8stypes.NodeName) bool {\n\tdsw.RLock()\n\tdefer dsw.RUnlock()\n\n\t_, nodeExists := dsw.nodesManaged[nodeName]\n\treturn nodeExists\n}","line":{"from":321,"to":327}} {"id":100004915,"name":"VolumeExists","signature":"func (dsw *desiredStateOfWorld) VolumeExists(","file":"pkg/controller/volume/attachdetach/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) VolumeExists(\n\tvolumeName v1.UniqueVolumeName, nodeName k8stypes.NodeName) bool {\n\tdsw.RLock()\n\tdefer dsw.RUnlock()\n\n\tnodeObj, nodeExists := dsw.nodesManaged[nodeName]\n\tif nodeExists {\n\t\tif _, volumeExists := nodeObj.volumesToAttach[volumeName]; volumeExists {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":329,"to":342}} {"id":100004916,"name":"SetMultiAttachError","signature":"func (dsw *desiredStateOfWorld) SetMultiAttachError(","file":"pkg/controller/volume/attachdetach/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) SetMultiAttachError(\n\tvolumeName v1.UniqueVolumeName,\n\tnodeName k8stypes.NodeName) {\n\tdsw.Lock()\n\tdefer dsw.Unlock()\n\n\tnodeObj, nodeExists := dsw.nodesManaged[nodeName]\n\tif nodeExists {\n\t\tif volumeObj, volumeExists := nodeObj.volumesToAttach[volumeName]; volumeExists {\n\t\t\tvolumeObj.multiAttachErrorReported = true\n\t\t\tdsw.nodesManaged[nodeName].volumesToAttach[volumeName] = volumeObj\n\t\t}\n\t}\n}","line":{"from":344,"to":357}} {"id":100004917,"name":"GetKeepTerminatedPodVolumesForNode","signature":"func (dsw *desiredStateOfWorld) GetKeepTerminatedPodVolumesForNode(nodeName k8stypes.NodeName) bool","file":"pkg/controller/volume/attachdetach/cache/desired_state_of_world.go","code":"// GetKeepTerminatedPodVolumesForNode determines if node wants volumes to be\n// mounted and attached for terminated pods\nfunc (dsw *desiredStateOfWorld) GetKeepTerminatedPodVolumesForNode(nodeName k8stypes.NodeName) bool {\n\tdsw.RLock()\n\tdefer dsw.RUnlock()\n\n\tif nodeName == \"\" {\n\t\treturn false\n\t}\n\tif node, ok := dsw.nodesManaged[nodeName]; ok {\n\t\treturn node.keepTerminatedPodVolumes\n\t}\n\treturn false\n}","line":{"from":359,"to":372}} {"id":100004918,"name":"GetVolumesToAttach","signature":"func (dsw *desiredStateOfWorld) GetVolumesToAttach() []VolumeToAttach","file":"pkg/controller/volume/attachdetach/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) GetVolumesToAttach() []VolumeToAttach {\n\tdsw.RLock()\n\tdefer dsw.RUnlock()\n\n\tvolumesToAttach := make([]VolumeToAttach, 0 /* len */, len(dsw.nodesManaged) /* cap */)\n\tfor nodeName, nodeObj := range dsw.nodesManaged {\n\t\tfor volumeName, volumeObj := range nodeObj.volumesToAttach {\n\t\t\tvolumesToAttach = append(volumesToAttach,\n\t\t\t\tVolumeToAttach{\n\t\t\t\t\tVolumeToAttach: operationexecutor.VolumeToAttach{\n\t\t\t\t\t\tMultiAttachErrorReported: volumeObj.multiAttachErrorReported,\n\t\t\t\t\t\tVolumeName: volumeName,\n\t\t\t\t\t\tVolumeSpec: volumeObj.spec,\n\t\t\t\t\t\tNodeName: nodeName,\n\t\t\t\t\t\tScheduledPods: getPodsFromMap(volumeObj.scheduledPods),\n\t\t\t\t\t}})\n\t\t}\n\t}\n\n\treturn volumesToAttach\n}","line":{"from":374,"to":394}} {"id":100004919,"name":"getPodsFromMap","signature":"func getPodsFromMap(podMap map[types.UniquePodName]pod) []*v1.Pod","file":"pkg/controller/volume/attachdetach/cache/desired_state_of_world.go","code":"// Construct a list of v1.Pod objects from the given pod map\nfunc getPodsFromMap(podMap map[types.UniquePodName]pod) []*v1.Pod {\n\tpods := make([]*v1.Pod, 0, len(podMap))\n\tfor _, pod := range podMap {\n\t\tpods = append(pods, pod.podObj)\n\t}\n\treturn pods\n}","line":{"from":396,"to":403}} {"id":100004920,"name":"GetPodToAdd","signature":"func (dsw *desiredStateOfWorld) GetPodToAdd() map[types.UniquePodName]PodToAdd","file":"pkg/controller/volume/attachdetach/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) GetPodToAdd() map[types.UniquePodName]PodToAdd {\n\tdsw.RLock()\n\tdefer dsw.RUnlock()\n\n\tpods := make(map[types.UniquePodName]PodToAdd)\n\tfor nodeName, nodeObj := range dsw.nodesManaged {\n\t\tfor volumeName, volumeObj := range nodeObj.volumesToAttach {\n\t\t\tfor podUID, pod := range volumeObj.scheduledPods {\n\t\t\t\tpods[podUID] = PodToAdd{\n\t\t\t\t\tPod: pod.podObj,\n\t\t\t\t\tVolumeName: volumeName,\n\t\t\t\t\tNodeName: nodeName,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn pods\n}","line":{"from":405,"to":422}} {"id":100004921,"name":"GetVolumePodsOnNodes","signature":"func (dsw *desiredStateOfWorld) GetVolumePodsOnNodes(nodes []k8stypes.NodeName, volumeName v1.UniqueVolumeName) []*v1.Pod","file":"pkg/controller/volume/attachdetach/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) GetVolumePodsOnNodes(nodes []k8stypes.NodeName, volumeName v1.UniqueVolumeName) []*v1.Pod {\n\tdsw.RLock()\n\tdefer dsw.RUnlock()\n\n\tpods := []*v1.Pod{}\n\tfor _, nodeName := range nodes {\n\t\tnode, ok := dsw.nodesManaged[nodeName]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tvolume, ok := node.volumesToAttach[volumeName]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, pod := range volume.scheduledPods {\n\t\t\tpods = append(pods, pod.podObj)\n\t\t}\n\t}\n\treturn pods\n}","line":{"from":424,"to":443}} {"id":100004922,"name":"Convert_v1alpha1_AttachDetachControllerConfiguration_To_config_AttachDetachControllerConfiguration","signature":"func Convert_v1alpha1_AttachDetachControllerConfiguration_To_config_AttachDetachControllerConfiguration(in *v1alpha1.AttachDetachControllerConfiguration, out *config.AttachDetachControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/volume/attachdetach/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_AttachDetachControllerConfiguration_To_config_AttachDetachControllerConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_AttachDetachControllerConfiguration_To_config_AttachDetachControllerConfiguration(in *v1alpha1.AttachDetachControllerConfiguration, out *config.AttachDetachControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_AttachDetachControllerConfiguration_To_config_AttachDetachControllerConfiguration(in, out, s)\n}","line":{"from":32,"to":35}} {"id":100004923,"name":"Convert_config_AttachDetachControllerConfiguration_To_v1alpha1_AttachDetachControllerConfiguration","signature":"func Convert_config_AttachDetachControllerConfiguration_To_v1alpha1_AttachDetachControllerConfiguration(in *config.AttachDetachControllerConfiguration, out *v1alpha1.AttachDetachControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/volume/attachdetach/config/v1alpha1/conversion.go","code":"// Convert_config_AttachDetachControllerConfiguration_To_v1alpha1_AttachDetachControllerConfiguration is an autogenerated conversion function.\nfunc Convert_config_AttachDetachControllerConfiguration_To_v1alpha1_AttachDetachControllerConfiguration(in *config.AttachDetachControllerConfiguration, out *v1alpha1.AttachDetachControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_AttachDetachControllerConfiguration_To_v1alpha1_AttachDetachControllerConfiguration(in, out, s)\n}","line":{"from":37,"to":40}} {"id":100004924,"name":"RecommendedDefaultAttachDetachControllerConfiguration","signature":"func RecommendedDefaultAttachDetachControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.AttachDetachControllerConfiguration)","file":"pkg/controller/volume/attachdetach/config/v1alpha1/defaults.go","code":"// RecommendedDefaultAttachDetachControllerConfiguration defaults a pointer to a\n// AttachDetachControllerConfiguration struct. This will set the recommended default\n// values, but they may be subject to change between API versions. This function\n// is intentionally not registered in the scheme as a \"normal\" `SetDefaults_Foo`\n// function to allow consumers of this type to set whatever defaults for their\n// embedded configs. Forcing consumers to use these defaults would be problematic\n// as defaulting in the scheme is done as part of the conversion, and there would\n// be no easy way to opt-out. Instead, if you want to use this defaulting method\n// run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDefaultAttachDetachControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.AttachDetachControllerConfiguration) {\n\tzero := metav1.Duration{}\n\tif obj.ReconcilerSyncLoopPeriod == zero {\n\t\tobj.ReconcilerSyncLoopPeriod = metav1.Duration{Duration: 60 * time.Second}\n\t}\n}","line":{"from":26,"to":40}} {"id":100004925,"name":"Register","signature":"func Register(pvcLister corelisters.PersistentVolumeClaimLister,","file":"pkg/controller/volume/attachdetach/metrics/metrics.go","code":"// Register registers metrics in A/D Controller.\nfunc Register(pvcLister corelisters.PersistentVolumeClaimLister,\n\tpvLister corelisters.PersistentVolumeLister,\n\tpodLister corelisters.PodLister,\n\tasw cache.ActualStateOfWorld,\n\tdsw cache.DesiredStateOfWorld,\n\tpluginMgr *volume.VolumePluginMgr,\n\tcsiMigratedPluginManager csimigration.PluginManager,\n\tintreeToCSITranslator csimigration.InTreeToCSITranslator) {\n\tregisterMetrics.Do(func() {\n\t\tlegacyregistry.CustomMustRegister(newAttachDetachStateCollector(pvcLister,\n\t\t\tpodLister,\n\t\t\tpvLister,\n\t\t\tasw,\n\t\t\tdsw,\n\t\t\tpluginMgr,\n\t\t\tcsiMigratedPluginManager,\n\t\t\tintreeToCSITranslator))\n\t\tlegacyregistry.MustRegister(forcedDetachMetricCounter)\n\t})\n}","line":{"from":60,"to":80}} {"id":100004926,"name":"add","signature":"func (v volumeCount) add(typeKey, counterKey string)","file":"pkg/controller/volume/attachdetach/metrics/metrics.go","code":"func (v volumeCount) add(typeKey, counterKey string) {\n\tcount, ok := v[typeKey]\n\tif !ok {\n\t\tcount = map[string]int64{}\n\t}\n\tcount[counterKey]++\n\tv[typeKey] = count\n}","line":{"from":103,"to":110}} {"id":100004927,"name":"newAttachDetachStateCollector","signature":"func newAttachDetachStateCollector(","file":"pkg/controller/volume/attachdetach/metrics/metrics.go","code":"func newAttachDetachStateCollector(\n\tpvcLister corelisters.PersistentVolumeClaimLister,\n\tpodLister corelisters.PodLister,\n\tpvLister corelisters.PersistentVolumeLister,\n\tasw cache.ActualStateOfWorld,\n\tdsw cache.DesiredStateOfWorld,\n\tpluginMgr *volume.VolumePluginMgr,\n\tcsiMigratedPluginManager csimigration.PluginManager,\n\tintreeToCSITranslator csimigration.InTreeToCSITranslator) *attachDetachStateCollector {\n\treturn \u0026attachDetachStateCollector{pvcLister: pvcLister, podLister: podLister, pvLister: pvLister, asw: asw, dsw: dsw, volumePluginMgr: pluginMgr, csiMigratedPluginManager: csiMigratedPluginManager, intreeToCSITranslator: intreeToCSITranslator}\n}","line":{"from":112,"to":122}} {"id":100004928,"name":"DescribeWithStability","signature":"func (collector *attachDetachStateCollector) DescribeWithStability(ch chan\u003c- *metrics.Desc)","file":"pkg/controller/volume/attachdetach/metrics/metrics.go","code":"func (collector *attachDetachStateCollector) DescribeWithStability(ch chan\u003c- *metrics.Desc) {\n\tch \u003c- inUseVolumeMetricDesc\n\tch \u003c- totalVolumesMetricDesc\n}","line":{"from":127,"to":130}} {"id":100004929,"name":"CollectWithStability","signature":"func (collector *attachDetachStateCollector) CollectWithStability(ch chan\u003c- metrics.Metric)","file":"pkg/controller/volume/attachdetach/metrics/metrics.go","code":"func (collector *attachDetachStateCollector) CollectWithStability(ch chan\u003c- metrics.Metric) {\n\tnodeVolumeMap := collector.getVolumeInUseCount(klog.TODO())\n\tfor nodeName, pluginCount := range nodeVolumeMap {\n\t\tfor pluginName, count := range pluginCount {\n\t\t\tch \u003c- metrics.NewLazyConstMetric(inUseVolumeMetricDesc,\n\t\t\t\tmetrics.GaugeValue,\n\t\t\t\tfloat64(count),\n\t\t\t\tstring(nodeName),\n\t\t\t\tpluginName)\n\t\t}\n\t}\n\n\tstateVolumeMap := collector.getTotalVolumesCount()\n\tfor stateName, pluginCount := range stateVolumeMap {\n\t\tfor pluginName, count := range pluginCount {\n\t\t\tch \u003c- metrics.NewLazyConstMetric(totalVolumesMetricDesc,\n\t\t\t\tmetrics.GaugeValue,\n\t\t\t\tfloat64(count),\n\t\t\t\tpluginName,\n\t\t\t\tstring(stateName))\n\t\t}\n\t}\n}","line":{"from":132,"to":154}} {"id":100004930,"name":"getVolumeInUseCount","signature":"func (collector *attachDetachStateCollector) getVolumeInUseCount(logger klog.Logger) volumeCount","file":"pkg/controller/volume/attachdetach/metrics/metrics.go","code":"func (collector *attachDetachStateCollector) getVolumeInUseCount(logger klog.Logger) volumeCount {\n\tpods, err := collector.podLister.List(labels.Everything())\n\tif err != nil {\n\t\tlogger.Error(errors.New(\"Error getting pod list\"), \"Get pod list failed\")\n\t\treturn nil\n\t}\n\n\tnodeVolumeMap := make(volumeCount)\n\tfor _, pod := range pods {\n\t\tif len(pod.Spec.Volumes) \u003c= 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif pod.Spec.NodeName == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, podVolume := range pod.Spec.Volumes {\n\t\t\tvolumeSpec, err := util.CreateVolumeSpec(logger, podVolume, pod, types.NodeName(pod.Spec.NodeName), collector.volumePluginMgr, collector.pvcLister, collector.pvLister, collector.csiMigratedPluginManager, collector.intreeToCSITranslator)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvolumePlugin, err := collector.volumePluginMgr.FindPluginBySpec(volumeSpec)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpluginName := volumeutil.GetFullQualifiedPluginNameForVolume(volumePlugin.GetPluginName(), volumeSpec)\n\t\t\tnodeVolumeMap.add(pod.Spec.NodeName, pluginName)\n\t\t}\n\t}\n\treturn nodeVolumeMap\n}","line":{"from":156,"to":186}} {"id":100004931,"name":"getTotalVolumesCount","signature":"func (collector *attachDetachStateCollector) getTotalVolumesCount() volumeCount","file":"pkg/controller/volume/attachdetach/metrics/metrics.go","code":"func (collector *attachDetachStateCollector) getTotalVolumesCount() volumeCount {\n\tstateVolumeMap := make(volumeCount)\n\tfor _, v := range collector.dsw.GetVolumesToAttach() {\n\t\tif plugin, err := collector.volumePluginMgr.FindPluginBySpec(v.VolumeSpec); err == nil {\n\t\t\tpluginName := pluginNameNotAvailable\n\t\t\tif plugin != nil {\n\t\t\t\tpluginName = volumeutil.GetFullQualifiedPluginNameForVolume(plugin.GetPluginName(), v.VolumeSpec)\n\t\t\t}\n\t\t\tstateVolumeMap.add(\"desired_state_of_world\", pluginName)\n\t\t}\n\t}\n\tfor _, v := range collector.asw.GetAttachedVolumes() {\n\t\tif plugin, err := collector.volumePluginMgr.FindPluginBySpec(v.VolumeSpec); err == nil {\n\t\t\tpluginName := pluginNameNotAvailable\n\t\t\tif plugin != nil {\n\t\t\t\tpluginName = volumeutil.GetFullQualifiedPluginNameForVolume(plugin.GetPluginName(), v.VolumeSpec)\n\t\t\t}\n\t\t\tstateVolumeMap.add(\"actual_state_of_world\", pluginName)\n\t\t}\n\t}\n\treturn stateVolumeMap\n}","line":{"from":188,"to":209}} {"id":100004932,"name":"RecordForcedDetachMetric","signature":"func RecordForcedDetachMetric()","file":"pkg/controller/volume/attachdetach/metrics/metrics.go","code":"// RecordForcedDetachMetric register a forced detach metric.\nfunc RecordForcedDetachMetric() {\n\tforcedDetachMetricCounter.Inc()\n}","line":{"from":211,"to":214}} {"id":100004933,"name":"NewDesiredStateOfWorldPopulator","signature":"func NewDesiredStateOfWorldPopulator(","file":"pkg/controller/volume/attachdetach/populator/desired_state_of_world_populator.go","code":"// NewDesiredStateOfWorldPopulator returns a new instance of DesiredStateOfWorldPopulator.\n// loopSleepDuration - the amount of time the populator loop sleeps between\n// successive executions\n//\n// podManager - the kubelet podManager that is the source of truth for the pods\n// that exist on this host\n//\n// desiredStateOfWorld - the cache to populate\nfunc NewDesiredStateOfWorldPopulator(\n\tloopSleepDuration time.Duration,\n\tlistPodsRetryDuration time.Duration,\n\tpodLister corelisters.PodLister,\n\tdesiredStateOfWorld cache.DesiredStateOfWorld,\n\tvolumePluginMgr *volume.VolumePluginMgr,\n\tpvcLister corelisters.PersistentVolumeClaimLister,\n\tpvLister corelisters.PersistentVolumeLister,\n\tcsiMigratedPluginManager csimigration.PluginManager,\n\tintreeToCSITranslator csimigration.InTreeToCSITranslator) DesiredStateOfWorldPopulator {\n\treturn \u0026desiredStateOfWorldPopulator{\n\t\tloopSleepDuration: loopSleepDuration,\n\t\tlistPodsRetryDuration: listPodsRetryDuration,\n\t\tpodLister: podLister,\n\t\tdesiredStateOfWorld: desiredStateOfWorld,\n\t\tvolumePluginMgr: volumePluginMgr,\n\t\tpvcLister: pvcLister,\n\t\tpvLister: pvLister,\n\t\tcsiMigratedPluginManager: csiMigratedPluginManager,\n\t\tintreeToCSITranslator: intreeToCSITranslator,\n\t}\n}","line":{"from":50,"to":79}} {"id":100004934,"name":"Run","signature":"func (dswp *desiredStateOfWorldPopulator) Run(ctx context.Context)","file":"pkg/controller/volume/attachdetach/populator/desired_state_of_world_populator.go","code":"func (dswp *desiredStateOfWorldPopulator) Run(ctx context.Context) {\n\twait.UntilWithContext(ctx, dswp.populatorLoopFunc(ctx), dswp.loopSleepDuration)\n}","line":{"from":94,"to":96}} {"id":100004935,"name":"populatorLoopFunc","signature":"func (dswp *desiredStateOfWorldPopulator) populatorLoopFunc(ctx context.Context) func(ctx context.Context)","file":"pkg/controller/volume/attachdetach/populator/desired_state_of_world_populator.go","code":"func (dswp *desiredStateOfWorldPopulator) populatorLoopFunc(ctx context.Context) func(ctx context.Context) {\n\treturn func(ctx context.Context) {\n\t\tlogger := klog.FromContext(ctx)\n\t\tdswp.findAndRemoveDeletedPods(logger)\n\n\t\t// findAndAddActivePods is called periodically, independently of the main\n\t\t// populator loop.\n\t\tif time.Since(dswp.timeOfLastListPods) \u003c dswp.listPodsRetryDuration {\n\t\t\tlogger.V(5).Info(\n\t\t\t\t\"Skipping findAndAddActivePods(). Not permitted until the retry time is reached\",\n\t\t\t\t\"retryTime\", dswp.timeOfLastListPods.Add(dswp.listPodsRetryDuration),\n\t\t\t\t\"retryDuration\", dswp.listPodsRetryDuration)\n\n\t\t\treturn\n\t\t}\n\t\tdswp.findAndAddActivePods(logger)\n\t}\n}","line":{"from":98,"to":115}} {"id":100004936,"name":"findAndRemoveDeletedPods","signature":"func (dswp *desiredStateOfWorldPopulator) findAndRemoveDeletedPods(logger klog.Logger)","file":"pkg/controller/volume/attachdetach/populator/desired_state_of_world_populator.go","code":"// Iterate through all pods in desired state of world, and remove if they no\n// longer exist in the informer\nfunc (dswp *desiredStateOfWorldPopulator) findAndRemoveDeletedPods(logger klog.Logger) {\n\tfor dswPodUID, dswPodToAdd := range dswp.desiredStateOfWorld.GetPodToAdd() {\n\t\tdswPodKey, err := kcache.MetaNamespaceKeyFunc(dswPodToAdd.Pod)\n\t\tif err != nil {\n\t\t\tlogger.Error(err, \"MetaNamespaceKeyFunc failed for pod\", \"podName\", dswPodKey, \"podUID\", dswPodUID)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Retrieve the pod object from pod informer with the namespace key\n\t\tnamespace, name, err := kcache.SplitMetaNamespaceKey(dswPodKey)\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"error splitting dswPodKey %q: %v\", dswPodKey, err))\n\t\t\tcontinue\n\t\t}\n\t\tinformerPod, err := dswp.podLister.Pods(namespace).Get(name)\n\t\tswitch {\n\t\tcase errors.IsNotFound(err):\n\t\t\t// if we can't find the pod, we need to delete it below\n\t\tcase err != nil:\n\t\t\tlogger.Error(err, \"podLister Get failed for pod\", \"podName\", dswPodKey, \"podUID\", dswPodUID)\n\t\t\tcontinue\n\t\tdefault:\n\t\t\tvolumeActionFlag := util.DetermineVolumeAction(\n\t\t\t\tinformerPod,\n\t\t\t\tdswp.desiredStateOfWorld,\n\t\t\t\ttrue /* default volume action */)\n\n\t\t\tif volumeActionFlag {\n\t\t\t\tinformerPodUID := volutil.GetUniquePodName(informerPod)\n\t\t\t\t// Check whether the unique identifier of the pod from dsw matches the one retrieved from pod informer\n\t\t\t\tif informerPodUID == dswPodUID {\n\t\t\t\t\tlogger.V(10).Info(\"Verified podfrom dsw exists in pod informer\", \"podName\", dswPodKey, \"podUID\", dswPodUID)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// the pod from dsw does not exist in pod informer, or it does not match the unique identifier retrieved\n\t\t// from the informer, delete it from dsw\n\t\tlogger.V(1).Info(\"Removing pod from dsw because it does not exist in pod informer\", \"podName\", dswPodKey, \"podUID\", dswPodUID)\n\t\tdswp.desiredStateOfWorld.DeletePod(dswPodUID, dswPodToAdd.VolumeName, dswPodToAdd.NodeName)\n\t}\n\n\t// check if the existing volumes changes its attachability\n\tfor _, volumeToAttach := range dswp.desiredStateOfWorld.GetVolumesToAttach() {\n\t\t// IsAttachableVolume() will result in a fetch of CSIDriver object if the volume plugin type is CSI.\n\t\t// The result is returned from CSIDriverLister which is from local cache. So this is not an expensive call.\n\t\tvolumeAttachable := volutil.IsAttachableVolume(volumeToAttach.VolumeSpec, dswp.volumePluginMgr)\n\t\tif !volumeAttachable {\n\t\t\tlogger.Info(\"Volume changes from attachable to non-attachable\", \"volumeName\", volumeToAttach.VolumeName)\n\t\t\tfor _, scheduledPod := range volumeToAttach.ScheduledPods {\n\t\t\t\tpodUID := volutil.GetUniquePodName(scheduledPod)\n\t\t\t\tdswp.desiredStateOfWorld.DeletePod(podUID, volumeToAttach.VolumeName, volumeToAttach.NodeName)\n\t\t\t\tlogger.V(4).Info(\"Removing podUID and volume on node from desired state of world\"+\n\t\t\t\t\t\" because of the change of volume attachability\", \"node\", klog.KRef(\"\", string(volumeToAttach.NodeName)), \"podUID\", podUID, \"volumeName\", volumeToAttach.VolumeName)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":117,"to":177}} {"id":100004937,"name":"findAndAddActivePods","signature":"func (dswp *desiredStateOfWorldPopulator) findAndAddActivePods(logger klog.Logger)","file":"pkg/controller/volume/attachdetach/populator/desired_state_of_world_populator.go","code":"func (dswp *desiredStateOfWorldPopulator) findAndAddActivePods(logger klog.Logger) {\n\tpods, err := dswp.podLister.List(labels.Everything())\n\tif err != nil {\n\t\tlogger.Error(err, \"PodLister List failed\")\n\t\treturn\n\t}\n\tdswp.timeOfLastListPods = time.Now()\n\n\tfor _, pod := range pods {\n\t\tif volutil.IsPodTerminated(pod, pod.Status) {\n\t\t\t// Do not add volumes for terminated pods\n\t\t\tcontinue\n\t\t}\n\t\tutil.ProcessPodVolumes(logger, pod, true,\n\t\t\tdswp.desiredStateOfWorld, dswp.volumePluginMgr, dswp.pvcLister, dswp.pvLister, dswp.csiMigratedPluginManager, dswp.intreeToCSITranslator)\n\n\t}\n\n}","line":{"from":179,"to":197}} {"id":100004938,"name":"NewReconciler","signature":"func NewReconciler(","file":"pkg/controller/volume/attachdetach/reconciler/reconciler.go","code":"// NewReconciler returns a new instance of Reconciler that waits loopPeriod\n// between successive executions.\n// loopPeriod is the amount of time the reconciler loop waits between\n// successive executions.\n// maxWaitForUnmountDuration is the max amount of time the reconciler will wait\n// for the volume to be safely unmounted, after this it will detach the volume\n// anyway (to handle crashed/unavailable nodes). If during this time the volume\n// becomes used by a new pod, the detach request will be aborted and the timer\n// cleared.\nfunc NewReconciler(\n\tloopPeriod time.Duration,\n\tmaxWaitForUnmountDuration time.Duration,\n\tsyncDuration time.Duration,\n\tdisableReconciliationSync bool,\n\tdesiredStateOfWorld cache.DesiredStateOfWorld,\n\tactualStateOfWorld cache.ActualStateOfWorld,\n\tattacherDetacher operationexecutor.OperationExecutor,\n\tnodeStatusUpdater statusupdater.NodeStatusUpdater,\n\tnodeLister corelisters.NodeLister,\n\trecorder record.EventRecorder) Reconciler {\n\treturn \u0026reconciler{\n\t\tloopPeriod: loopPeriod,\n\t\tmaxWaitForUnmountDuration: maxWaitForUnmountDuration,\n\t\tsyncDuration: syncDuration,\n\t\tdisableReconciliationSync: disableReconciliationSync,\n\t\tdesiredStateOfWorld: desiredStateOfWorld,\n\t\tactualStateOfWorld: actualStateOfWorld,\n\t\tattacherDetacher: attacherDetacher,\n\t\tnodeStatusUpdater: nodeStatusUpdater,\n\t\tnodeLister: nodeLister,\n\t\ttimeOfLastSync: time.Now(),\n\t\trecorder: recorder,\n\t}\n}","line":{"from":60,"to":93}} {"id":100004939,"name":"Run","signature":"func (rc *reconciler) Run(ctx context.Context)","file":"pkg/controller/volume/attachdetach/reconciler/reconciler.go","code":"func (rc *reconciler) Run(ctx context.Context) {\n\twait.UntilWithContext(ctx, rc.reconciliationLoopFunc(ctx), rc.loopPeriod)\n}","line":{"from":109,"to":111}} {"id":100004940,"name":"reconciliationLoopFunc","signature":"func (rc *reconciler) reconciliationLoopFunc(ctx context.Context) func(context.Context)","file":"pkg/controller/volume/attachdetach/reconciler/reconciler.go","code":"// reconciliationLoopFunc this can be disabled via cli option disableReconciliation.\n// It periodically checks whether the attached volumes from actual state\n// are still attached to the node and update the status if they are not.\nfunc (rc *reconciler) reconciliationLoopFunc(ctx context.Context) func(context.Context) {\n\treturn func(ctx context.Context) {\n\n\t\trc.reconcile(ctx)\n\t\tlogger := klog.FromContext(ctx)\n\t\tif rc.disableReconciliationSync {\n\t\t\tlogger.V(5).Info(\"Skipping reconciling attached volumes still attached since it is disabled via the command line\")\n\t\t} else if rc.syncDuration \u003c time.Second {\n\t\t\tlogger.V(5).Info(\"Skipping reconciling attached volumes still attached since it is set to less than one second via the command line\")\n\t\t} else if time.Since(rc.timeOfLastSync) \u003e rc.syncDuration {\n\t\t\tlogger.V(5).Info(\"Starting reconciling attached volumes still attached\")\n\t\t\trc.sync()\n\t\t}\n\t}\n}","line":{"from":113,"to":130}} {"id":100004941,"name":"sync","signature":"func (rc *reconciler) sync()","file":"pkg/controller/volume/attachdetach/reconciler/reconciler.go","code":"func (rc *reconciler) sync() {\n\tdefer rc.updateSyncTime()\n\trc.syncStates()\n}","line":{"from":132,"to":135}} {"id":100004942,"name":"updateSyncTime","signature":"func (rc *reconciler) updateSyncTime()","file":"pkg/controller/volume/attachdetach/reconciler/reconciler.go","code":"func (rc *reconciler) updateSyncTime() {\n\trc.timeOfLastSync = time.Now()\n}","line":{"from":137,"to":139}} {"id":100004943,"name":"syncStates","signature":"func (rc *reconciler) syncStates()","file":"pkg/controller/volume/attachdetach/reconciler/reconciler.go","code":"func (rc *reconciler) syncStates() {\n\tvolumesPerNode := rc.actualStateOfWorld.GetAttachedVolumesPerNode()\n\trc.attacherDetacher.VerifyVolumesAreAttached(volumesPerNode, rc.actualStateOfWorld)\n}","line":{"from":141,"to":144}} {"id":100004944,"name":"hasOutOfServiceTaint","signature":"func (rc *reconciler) hasOutOfServiceTaint(nodeName types.NodeName) (bool, error)","file":"pkg/controller/volume/attachdetach/reconciler/reconciler.go","code":"// hasOutOfServiceTaint returns true if the node has out-of-service taint present\n// and `NodeOutOfServiceVolumeDetach` feature gate is enabled.\nfunc (rc *reconciler) hasOutOfServiceTaint(nodeName types.NodeName) (bool, error) {\n\tif utilfeature.DefaultFeatureGate.Enabled(features.NodeOutOfServiceVolumeDetach) {\n\t\tnode, err := rc.nodeLister.Get(string(nodeName))\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\treturn taints.TaintKeyExists(node.Spec.Taints, v1.TaintNodeOutOfService), nil\n\t}\n\treturn false, nil\n}","line":{"from":146,"to":157}} {"id":100004945,"name":"nodeIsHealthy","signature":"func (rc *reconciler) nodeIsHealthy(nodeName types.NodeName) (bool, error)","file":"pkg/controller/volume/attachdetach/reconciler/reconciler.go","code":"// nodeIsHealthy returns true if the node looks healthy.\nfunc (rc *reconciler) nodeIsHealthy(nodeName types.NodeName) (bool, error) {\n\tnode, err := rc.nodeLister.Get(string(nodeName))\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn nodeutil.IsNodeReady(node), nil\n}","line":{"from":159,"to":166}} {"id":100004946,"name":"reconcile","signature":"func (rc *reconciler) reconcile(ctx context.Context)","file":"pkg/controller/volume/attachdetach/reconciler/reconciler.go","code":"func (rc *reconciler) reconcile(ctx context.Context) {\n\t// Detaches are triggered before attaches so that volumes referenced by\n\t// pods that are rescheduled to a different node are detached first.\n\n\t// Ensure volumes that should be detached are detached.\n\tlogger := klog.FromContext(ctx)\n\tfor _, attachedVolume := range rc.actualStateOfWorld.GetAttachedVolumes() {\n\t\tif !rc.desiredStateOfWorld.VolumeExists(\n\t\t\tattachedVolume.VolumeName, attachedVolume.NodeName) {\n\n\t\t\t// Check whether there already exist an operation pending, and don't even\n\t\t\t// try to start an operation if there is already one running.\n\t\t\t// This check must be done before we do any other checks, as otherwise the other checks\n\t\t\t// may pass while at the same time the volume leaves the pending state, resulting in\n\t\t\t// double detach attempts\n\t\t\t// The operation key format is different depending on whether the volume\n\t\t\t// allows multi attach across different nodes.\n\t\t\tif util.IsMultiAttachAllowed(attachedVolume.VolumeSpec) {\n\t\t\t\tif !rc.attacherDetacher.IsOperationSafeToRetry(attachedVolume.VolumeName, \"\" /* podName */, attachedVolume.NodeName, operationexecutor.DetachOperationName) {\n\t\t\t\t\tlogger.V(10).Info(\"Operation for volume is already running or still in exponential backoff for node. Can't start detach\", \"node\", klog.KRef(\"\", string(attachedVolume.NodeName)), \"volumeName\", attachedVolume.VolumeName)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif !rc.attacherDetacher.IsOperationSafeToRetry(attachedVolume.VolumeName, \"\" /* podName */, \"\" /* nodeName */, operationexecutor.DetachOperationName) {\n\t\t\t\t\tlogger.V(10).Info(\"Operation for volume is already running or still in exponential backoff in the cluster. Can't start detach for node\", \"node\", klog.KRef(\"\", string(attachedVolume.NodeName)), \"volumeName\", attachedVolume.VolumeName)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Because the detach operation updates the ActualStateOfWorld before\n\t\t\t// marking itself complete, it's possible for the volume to be removed\n\t\t\t// from the ActualStateOfWorld between the GetAttachedVolumes() check\n\t\t\t// and the IsOperationPending() check above.\n\t\t\t// Check the ActualStateOfWorld again to avoid issuing an unnecessary\n\t\t\t// detach.\n\t\t\t// See https://github.com/kubernetes/kubernetes/issues/93902\n\t\t\tattachState := rc.actualStateOfWorld.GetAttachState(attachedVolume.VolumeName, attachedVolume.NodeName)\n\t\t\tif attachState == cache.AttachStateDetached {\n\t\t\t\tlogger.V(5).Info(\"Volume detached--skipping\", \"volume\", attachedVolume)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Set the detach request time\n\t\t\telapsedTime, err := rc.actualStateOfWorld.SetDetachRequestTime(logger, attachedVolume.VolumeName, attachedVolume.NodeName)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Error(err, \"Cannot trigger detach because it fails to set detach request time with error\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Check whether timeout has reached the maximum waiting time\n\t\t\ttimeout := elapsedTime \u003e rc.maxWaitForUnmountDuration\n\n\t\t\tisHealthy, err := rc.nodeIsHealthy(attachedVolume.NodeName)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Error(err, \"Failed to get health of node\", \"node\", klog.KRef(\"\", string(attachedVolume.NodeName)))\n\t\t\t}\n\n\t\t\t// Force detach volumes from unhealthy nodes after maxWaitForUnmountDuration.\n\t\t\tforceDetach := !isHealthy \u0026\u0026 timeout\n\n\t\t\thasOutOfServiceTaint, err := rc.hasOutOfServiceTaint(attachedVolume.NodeName)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Error(err, \"Failed to get taint specs for node\", \"node\", klog.KRef(\"\", string(attachedVolume.NodeName)))\n\t\t\t}\n\n\t\t\t// Check whether volume is still mounted. Skip detach if it is still mounted unless force detach timeout\n\t\t\t// or the node has `node.kubernetes.io/out-of-service` taint.\n\t\t\tif attachedVolume.MountedByNode \u0026\u0026 !forceDetach \u0026\u0026 !hasOutOfServiceTaint {\n\t\t\t\tlogger.V(5).Info(\"Cannot detach volume because it is still mounted\", \"volume\", attachedVolume)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Before triggering volume detach, mark volume as detached and update the node status\n\t\t\t// If it fails to update node status, skip detach volume\n\t\t\t// If volume detach operation fails, the volume needs to be added back to report as attached so that node status\n\t\t\t// has the correct volume attachment information.\n\t\t\terr = rc.actualStateOfWorld.RemoveVolumeFromReportAsAttached(attachedVolume.VolumeName, attachedVolume.NodeName)\n\t\t\tif err != nil {\n\t\t\t\tlogger.V(5).Info(\"RemoveVolumeFromReportAsAttached failed while removing volume from node\",\n\t\t\t\t\t\"node\", klog.KRef(\"\", string(attachedVolume.NodeName)),\n\t\t\t\t\t\"volumeName\", attachedVolume.VolumeName,\n\t\t\t\t\t\"err\", err)\n\t\t\t}\n\n\t\t\t// Update Node Status to indicate volume is no longer safe to mount.\n\t\t\terr = rc.nodeStatusUpdater.UpdateNodeStatusForNode(logger, attachedVolume.NodeName)\n\t\t\tif err != nil {\n\t\t\t\t// Skip detaching this volume if unable to update node status\n\t\t\t\tlogger.Error(err, \"UpdateNodeStatusForNode failed while attempting to report volume as attached\", \"volume\", attachedVolume)\n\t\t\t\t// Add volume back to ReportAsAttached if UpdateNodeStatusForNode call failed so that node status updater will add it back to VolumeAttached list.\n\t\t\t\t// It is needed here too because DetachVolume is not call actually and we keep the data consistency for every reconcile.\n\t\t\t\trc.actualStateOfWorld.AddVolumeToReportAsAttached(logger, attachedVolume.VolumeName, attachedVolume.NodeName)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Trigger detach volume which requires verifying safe to detach step\n\t\t\t// If timeout is true, skip verifySafeToDetach check\n\t\t\t// If the node has node.kubernetes.io/out-of-service taint with NoExecute effect, skip verifySafeToDetach check\n\t\t\tlogger.V(5).Info(\"Starting attacherDetacher.DetachVolume\", \"volume\", attachedVolume)\n\t\t\tif hasOutOfServiceTaint {\n\t\t\t\tlogger.V(4).Info(\"node has out-of-service taint\", \"node\", klog.KRef(\"\", string(attachedVolume.NodeName)))\n\t\t\t}\n\t\t\tverifySafeToDetach := !(timeout || hasOutOfServiceTaint)\n\t\t\terr = rc.attacherDetacher.DetachVolume(logger, attachedVolume.AttachedVolume, verifySafeToDetach, rc.actualStateOfWorld)\n\t\t\tif err == nil {\n\t\t\t\tif !timeout {\n\t\t\t\t\tlogger.Info(\"attacherDetacher.DetachVolume started\", \"volume\", attachedVolume)\n\t\t\t\t} else {\n\t\t\t\t\tmetrics.RecordForcedDetachMetric()\n\t\t\t\t\tlogger.Info(\"attacherDetacher.DetachVolume started: this volume is not safe to detach, but maxWaitForUnmountDuration expired, force detaching\", \"duration\", rc.maxWaitForUnmountDuration, \"volume\", attachedVolume)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\t// Add volume back to ReportAsAttached if DetachVolume call failed so that node status updater will add it back to VolumeAttached list.\n\t\t\t\t// This function is also called during executing the volume detach operation in operation_generoator.\n\t\t\t\t// It is needed here too because DetachVolume call might fail before executing the actual operation in operation_executor (e.g., cannot find volume plugin etc.)\n\t\t\t\trc.actualStateOfWorld.AddVolumeToReportAsAttached(logger, attachedVolume.VolumeName, attachedVolume.NodeName)\n\n\t\t\t\tif !exponentialbackoff.IsExponentialBackoff(err) {\n\t\t\t\t\t// Ignore exponentialbackoff.IsExponentialBackoff errors, they are expected.\n\t\t\t\t\t// Log all other errors.\n\t\t\t\t\tlogger.Error(err, \"attacherDetacher.DetachVolume failed to start\", \"volume\", attachedVolume)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\trc.attachDesiredVolumes(logger)\n\n\t// Update Node Status\n\terr := rc.nodeStatusUpdater.UpdateNodeStatuses(logger)\n\tif err != nil {\n\t\tlogger.Info(\"UpdateNodeStatuses failed\", \"err\", err)\n\t}\n}","line":{"from":168,"to":301}} {"id":100004947,"name":"attachDesiredVolumes","signature":"func (rc *reconciler) attachDesiredVolumes(logger klog.Logger)","file":"pkg/controller/volume/attachdetach/reconciler/reconciler.go","code":"func (rc *reconciler) attachDesiredVolumes(logger klog.Logger) {\n\t// Ensure volumes that should be attached are attached.\n\tfor _, volumeToAttach := range rc.desiredStateOfWorld.GetVolumesToAttach() {\n\t\tif util.IsMultiAttachAllowed(volumeToAttach.VolumeSpec) {\n\t\t\t// Don't even try to start an operation if there is already one running for the given volume and node.\n\t\t\tif rc.attacherDetacher.IsOperationPending(volumeToAttach.VolumeName, \"\" /* podName */, volumeToAttach.NodeName) {\n\t\t\t\tlogger.V(10).Info(\"Operation for volume is already running for node. Can't start attach\", \"node\", klog.KRef(\"\", string(volumeToAttach.NodeName)), \"volumeName\", volumeToAttach.VolumeName)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else {\n\t\t\t// Don't even try to start an operation if there is already one running for the given volume\n\t\t\tif rc.attacherDetacher.IsOperationPending(volumeToAttach.VolumeName, \"\" /* podName */, \"\" /* nodeName */) {\n\t\t\t\tlogger.V(10).Info(\"Operation for volume is already running. Can't start attach for node\", \"node\", klog.KRef(\"\", string(volumeToAttach.NodeName)), \"volumeNames\", volumeToAttach.VolumeName)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\t// Because the attach operation updates the ActualStateOfWorld before\n\t\t// marking itself complete, IsOperationPending() must be checked before\n\t\t// GetAttachState() to guarantee the ActualStateOfWorld is\n\t\t// up-to-date when it's read.\n\t\t// See https://github.com/kubernetes/kubernetes/issues/93902\n\t\tattachState := rc.actualStateOfWorld.GetAttachState(volumeToAttach.VolumeName, volumeToAttach.NodeName)\n\t\tif attachState == cache.AttachStateAttached {\n\t\t\t// Volume/Node exists, touch it to reset detachRequestedTime\n\t\t\tlogger.V(10).Info(\"Volume attached--touching\", \"volume\", volumeToAttach)\n\t\t\trc.actualStateOfWorld.ResetDetachRequestTime(logger, volumeToAttach.VolumeName, volumeToAttach.NodeName)\n\t\t\tcontinue\n\t\t}\n\n\t\tif !util.IsMultiAttachAllowed(volumeToAttach.VolumeSpec) {\n\t\t\tnodes := rc.actualStateOfWorld.GetNodesForAttachedVolume(volumeToAttach.VolumeName)\n\t\t\tif len(nodes) \u003e 0 {\n\t\t\t\tif !volumeToAttach.MultiAttachErrorReported {\n\t\t\t\t\trc.reportMultiAttachError(logger, volumeToAttach, nodes)\n\t\t\t\t\trc.desiredStateOfWorld.SetMultiAttachError(volumeToAttach.VolumeName, volumeToAttach.NodeName)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\t// Volume/Node doesn't exist, spawn a goroutine to attach it\n\t\tlogger.V(5).Info(\"Starting attacherDetacher.AttachVolume\", \"volume\", volumeToAttach)\n\t\terr := rc.attacherDetacher.AttachVolume(logger, volumeToAttach.VolumeToAttach, rc.actualStateOfWorld)\n\t\tif err == nil {\n\t\t\tlogger.Info(\"attacherDetacher.AttachVolume started\", \"volumeName\", volumeToAttach.VolumeName, \"nodeName\", volumeToAttach.NodeName, \"scheduledPods\", klog.KObjSlice(volumeToAttach.ScheduledPods))\n\t\t}\n\t\tif err != nil \u0026\u0026 !exponentialbackoff.IsExponentialBackoff(err) {\n\t\t\t// Ignore exponentialbackoff.IsExponentialBackoff errors, they are expected.\n\t\t\t// Log all other errors.\n\t\t\tlogger.Error(err, \"attacherDetacher.AttachVolume failed to start\", \"volumeName\", volumeToAttach.VolumeName, \"nodeName\", volumeToAttach.NodeName, \"scheduledPods\", klog.KObjSlice(volumeToAttach.ScheduledPods))\n\t\t}\n\t}\n}","line":{"from":303,"to":356}} {"id":100004948,"name":"reportMultiAttachError","signature":"func (rc *reconciler) reportMultiAttachError(logger klog.Logger, volumeToAttach cache.VolumeToAttach, nodes []types.NodeName)","file":"pkg/controller/volume/attachdetach/reconciler/reconciler.go","code":"// reportMultiAttachError sends events and logs situation that a volume that\n// should be attached to a node is already attached to different node(s).\nfunc (rc *reconciler) reportMultiAttachError(logger klog.Logger, volumeToAttach cache.VolumeToAttach, nodes []types.NodeName) {\n\t// Filter out the current node from list of nodes where the volume is\n\t// attached.\n\t// Some methods need []string, some other needs []NodeName, collect both.\n\t// In theory, these arrays should have always only one element - the\n\t// controller does not allow more than one attachment. But use array just\n\t// in case...\n\totherNodes := []types.NodeName{}\n\totherNodesStr := []string{}\n\tfor _, node := range nodes {\n\t\tif node != volumeToAttach.NodeName {\n\t\t\totherNodes = append(otherNodes, node)\n\t\t\totherNodesStr = append(otherNodesStr, string(node))\n\t\t}\n\t}\n\n\t// Get list of pods that use the volume on the other nodes.\n\tpods := rc.desiredStateOfWorld.GetVolumePodsOnNodes(otherNodes, volumeToAttach.VolumeName)\n\tif len(pods) == 0 {\n\t\t// We did not find any pods that requests the volume. The pod must have been deleted already.\n\t\tsimpleMsg, _ := volumeToAttach.GenerateMsg(\"Multi-Attach error\", \"Volume is already exclusively attached to one node and can't be attached to another\")\n\t\tfor _, pod := range volumeToAttach.ScheduledPods {\n\t\t\trc.recorder.Eventf(pod, v1.EventTypeWarning, kevents.FailedAttachVolume, simpleMsg)\n\t\t}\n\t\t// Log detailed message to system admin\n\t\tlogger.Info(\"Multi-Attach error: volume is already exclusively attached and can't be attached to another node\", \"attachedTo\", otherNodesStr, \"volume\", volumeToAttach)\n\t\treturn\n\t}\n\n\t// There are pods that require the volume and run on another node. Typically\n\t// it's user error, e.g. a ReplicaSet uses a PVC and has \u003e1 replicas. Let\n\t// the user know what pods are blocking the volume.\n\tfor _, scheduledPod := range volumeToAttach.ScheduledPods {\n\t\t// Each scheduledPod must get a custom message. They can run in\n\t\t// different namespaces and user of a namespace should not see names of\n\t\t// pods in other namespaces.\n\t\tlocalPodNames := []string{} // Names of pods in scheduledPods's namespace\n\t\totherPods := 0 // Count of pods in other namespaces\n\t\tfor _, pod := range pods {\n\t\t\tif pod.Namespace == scheduledPod.Namespace {\n\t\t\t\tlocalPodNames = append(localPodNames, pod.Name)\n\t\t\t} else {\n\t\t\t\totherPods++\n\t\t\t}\n\t\t}\n\n\t\tvar msg string\n\t\tif len(localPodNames) \u003e 0 {\n\t\t\tmsg = fmt.Sprintf(\"Volume is already used by pod(s) %s\", strings.Join(localPodNames, \", \"))\n\t\t\tif otherPods \u003e 0 {\n\t\t\t\tmsg = fmt.Sprintf(\"%s and %d pod(s) in different namespaces\", msg, otherPods)\n\t\t\t}\n\t\t} else {\n\t\t\t// No local pods, there are pods only in different namespaces.\n\t\t\tmsg = fmt.Sprintf(\"Volume is already used by %d pod(s) in different namespaces\", otherPods)\n\t\t}\n\t\tsimpleMsg, _ := volumeToAttach.GenerateMsg(\"Multi-Attach error\", msg)\n\t\trc.recorder.Eventf(scheduledPod, v1.EventTypeWarning, kevents.FailedAttachVolume, simpleMsg)\n\t}\n\n\t// Log all pods for system admin\n\tlogger.Info(\"Multi-Attach error: volume is already used by pods\", \"pods\", klog.KObjSlice(pods), \"attachedTo\", otherNodesStr, \"volume\", volumeToAttach)\n}","line":{"from":358,"to":422}} {"id":100004949,"name":"NewNodeStatusUpdater","signature":"func NewNodeStatusUpdater(","file":"pkg/controller/volume/attachdetach/statusupdater/node_status_updater.go","code":"// NewNodeStatusUpdater returns a new instance of NodeStatusUpdater.\nfunc NewNodeStatusUpdater(\n\tkubeClient clientset.Interface,\n\tnodeLister corelisters.NodeLister,\n\tactualStateOfWorld cache.ActualStateOfWorld) NodeStatusUpdater {\n\treturn \u0026nodeStatusUpdater{\n\t\tactualStateOfWorld: actualStateOfWorld,\n\t\tnodeLister: nodeLister,\n\t\tkubeClient: kubeClient,\n\t}\n}","line":{"from":43,"to":53}} {"id":100004950,"name":"UpdateNodeStatuses","signature":"func (nsu *nodeStatusUpdater) UpdateNodeStatuses(logger klog.Logger) error","file":"pkg/controller/volume/attachdetach/statusupdater/node_status_updater.go","code":"func (nsu *nodeStatusUpdater) UpdateNodeStatuses(logger klog.Logger) error {\n\tvar nodeIssues int\n\t// TODO: investigate right behavior if nodeName is empty\n\t// kubernetes/kubernetes/issues/37777\n\tnodesToUpdate := nsu.actualStateOfWorld.GetVolumesToReportAttached(logger)\n\tfor nodeName, attachedVolumes := range nodesToUpdate {\n\t\terr := nsu.processNodeVolumes(logger, nodeName, attachedVolumes)\n\t\tif err != nil {\n\t\t\tnodeIssues += 1\n\t\t}\n\t}\n\tif nodeIssues \u003e 0 {\n\t\treturn fmt.Errorf(\"unable to update %d nodes\", nodeIssues)\n\t}\n\treturn nil\n}","line":{"from":61,"to":76}} {"id":100004951,"name":"UpdateNodeStatusForNode","signature":"func (nsu *nodeStatusUpdater) UpdateNodeStatusForNode(logger klog.Logger, nodeName types.NodeName) error","file":"pkg/controller/volume/attachdetach/statusupdater/node_status_updater.go","code":"func (nsu *nodeStatusUpdater) UpdateNodeStatusForNode(logger klog.Logger, nodeName types.NodeName) error {\n\tneedsUpdate, attachedVolumes := nsu.actualStateOfWorld.GetVolumesToReportAttachedForNode(logger, nodeName)\n\tif !needsUpdate {\n\t\treturn nil\n\t}\n\treturn nsu.processNodeVolumes(logger, nodeName, attachedVolumes)\n}","line":{"from":78,"to":84}} {"id":100004952,"name":"processNodeVolumes","signature":"func (nsu *nodeStatusUpdater) processNodeVolumes(logger klog.Logger, nodeName types.NodeName, attachedVolumes []v1.AttachedVolume) error","file":"pkg/controller/volume/attachdetach/statusupdater/node_status_updater.go","code":"func (nsu *nodeStatusUpdater) processNodeVolumes(logger klog.Logger, nodeName types.NodeName, attachedVolumes []v1.AttachedVolume) error {\n\tnodeObj, err := nsu.nodeLister.Get(string(nodeName))\n\tif errors.IsNotFound(err) {\n\t\t// If node does not exist, its status cannot be updated.\n\t\t// Do nothing so that there is no retry until node is created.\n\t\tlogger.V(2).Info(\n\t\t\t\"Could not update node status. Failed to find node in NodeInformer cache\", \"node\", klog.KRef(\"\", string(nodeName)), \"err\", err)\n\t\treturn nil\n\t} else if err != nil {\n\t\t// For all other errors, log error and reset flag statusUpdateNeeded\n\t\t// back to true to indicate this node status needs to be updated again.\n\t\tlogger.V(2).Info(\"Error retrieving nodes from node lister\", \"err\", err)\n\t\tnsu.actualStateOfWorld.SetNodeStatusUpdateNeeded(logger, nodeName)\n\t\treturn err\n\t}\n\n\terr = nsu.updateNodeStatus(logger, nodeName, nodeObj, attachedVolumes)\n\tif errors.IsNotFound(err) {\n\t\t// If node does not exist, its status cannot be updated.\n\t\t// Do nothing so that there is no retry until node is created.\n\t\tlogger.V(2).Info(\n\t\t\t\"Could not update node status, node does not exist - skipping\", \"node\", klog.KObj(nodeObj))\n\t\treturn nil\n\t} else if err != nil {\n\t\t// If update node status fails, reset flag statusUpdateNeeded back to true\n\t\t// to indicate this node status needs to be updated again\n\t\tnsu.actualStateOfWorld.SetNodeStatusUpdateNeeded(logger, nodeName)\n\n\t\tlogger.V(2).Info(\"Could not update node status; re-marking for update\", \"node\", klog.KObj(nodeObj), \"err\", err)\n\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":86,"to":119}} {"id":100004953,"name":"updateNodeStatus","signature":"func (nsu *nodeStatusUpdater) updateNodeStatus(logger klog.Logger, nodeName types.NodeName, nodeObj *v1.Node, attachedVolumes []v1.AttachedVolume) error","file":"pkg/controller/volume/attachdetach/statusupdater/node_status_updater.go","code":"func (nsu *nodeStatusUpdater) updateNodeStatus(logger klog.Logger, nodeName types.NodeName, nodeObj *v1.Node, attachedVolumes []v1.AttachedVolume) error {\n\tnode := nodeObj.DeepCopy()\n\tnode.Status.VolumesAttached = attachedVolumes\n\t_, patchBytes, err := nodeutil.PatchNodeStatus(nsu.kubeClient.CoreV1(), nodeName, nodeObj, node)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogger.V(4).Info(\"Updating status for node succeeded\", \"node\", klog.KObj(node), \"patchBytes\", patchBytes, \"attachedVolumes\", attachedVolumes)\n\treturn nil\n}","line":{"from":121,"to":131}} {"id":100004954,"name":"CreateVolumeSpec","signature":"func CreateVolumeSpec(logger klog.Logger, podVolume v1.Volume, pod *v1.Pod, nodeName types.NodeName, vpm *volume.VolumePluginMgr, pvcLister corelisters.PersistentVolumeClaimLister, pvLister corelisters.PersistentVolumeLister, csiMigratedPluginManager csimigration.PluginManager, csiTranslator csimigration.InTreeToCSITranslator) (*volume.Spec, error)","file":"pkg/controller/volume/attachdetach/util/util.go","code":"// CreateVolumeSpec creates and returns a mutatable volume.Spec object for the\n// specified volume. It dereference any PVC to get PV objects, if needed.\n// A volume.Spec that refers to an in-tree plugin spec is translated to refer\n// to a migrated CSI plugin spec if all conditions for CSI migration on a node\n// for the in-tree plugin is satisfied.\nfunc CreateVolumeSpec(logger klog.Logger, podVolume v1.Volume, pod *v1.Pod, nodeName types.NodeName, vpm *volume.VolumePluginMgr, pvcLister corelisters.PersistentVolumeClaimLister, pvLister corelisters.PersistentVolumeLister, csiMigratedPluginManager csimigration.PluginManager, csiTranslator csimigration.InTreeToCSITranslator) (*volume.Spec, error) {\n\tclaimName := \"\"\n\treadOnly := false\n\tif pvcSource := podVolume.VolumeSource.PersistentVolumeClaim; pvcSource != nil {\n\t\tclaimName = pvcSource.ClaimName\n\t\treadOnly = pvcSource.ReadOnly\n\t}\n\tisEphemeral := podVolume.VolumeSource.Ephemeral != nil\n\tif isEphemeral {\n\t\tclaimName = ephemeral.VolumeClaimName(pod, \u0026podVolume)\n\t}\n\tif claimName != \"\" {\n\t\tlogger.V(10).Info(\"Found PVC\", \"PVC\", klog.KRef(pod.Namespace, claimName))\n\n\t\t// If podVolume is a PVC, fetch the real PV behind the claim\n\t\tpvc, err := getPVCFromCache(pod.Namespace, claimName, pvcLister)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"error processing PVC %q/%q: %v\",\n\t\t\t\tpod.Namespace,\n\t\t\t\tclaimName,\n\t\t\t\terr)\n\t\t}\n\t\tif isEphemeral {\n\t\t\tif err := ephemeral.VolumeIsForPod(pod, pvc); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\tpvName, pvcUID := pvc.Spec.VolumeName, pvc.UID\n\t\tlogger.V(10).Info(\"Found bound PV for PVC\", \"PVC\", klog.KRef(pod.Namespace, claimName), \"pvcUID\", pvcUID, \"PV\", klog.KRef(\"\", pvName))\n\n\t\t// Fetch actual PV object\n\t\tvolumeSpec, err := getPVSpecFromCache(\n\t\t\tpvName, readOnly, pvcUID, pvLister)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"error processing PVC %q/%q: %v\",\n\t\t\t\tpod.Namespace,\n\t\t\t\tclaimName,\n\t\t\t\terr)\n\t\t}\n\n\t\tvolumeSpec, err = translateInTreeSpecToCSIIfNeeded(volumeSpec, nodeName, vpm, csiMigratedPluginManager, csiTranslator, pod.Namespace)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"error performing CSI migration checks and translation for PVC %q/%q: %v\",\n\t\t\t\tpod.Namespace,\n\t\t\t\tclaimName,\n\t\t\t\terr)\n\t\t}\n\n\t\tlogger.V(10).Info(\"Extracted volumeSpec from bound PV and PVC\", \"PVC\", klog.KRef(pod.Namespace, claimName), \"pvcUID\", pvcUID, \"PV\", klog.KRef(\"\", pvName), \"volumeSpecName\", volumeSpec.Name())\n\n\t\treturn volumeSpec, nil\n\t}\n\n\t// Do not return the original volume object, since it's from the shared\n\t// informer it may be mutated by another consumer.\n\tclonedPodVolume := podVolume.DeepCopy()\n\n\torigspec := volume.NewSpecFromVolume(clonedPodVolume)\n\tspec, err := translateInTreeSpecToCSIIfNeeded(origspec, nodeName, vpm, csiMigratedPluginManager, csiTranslator, pod.Namespace)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"error performing CSI migration checks and translation for inline volume %q: %v\",\n\t\t\tpodVolume.Name,\n\t\t\terr)\n\t}\n\treturn spec, nil\n}","line":{"from":36,"to":111}} {"id":100004955,"name":"getPVCFromCache","signature":"func getPVCFromCache(namespace string, name string, pvcLister corelisters.PersistentVolumeClaimLister) (*v1.PersistentVolumeClaim, error)","file":"pkg/controller/volume/attachdetach/util/util.go","code":"// getPVCFromCache fetches the PVC object with the given namespace and\n// name from the shared internal PVC store.\n// This method returns an error if a PVC object does not exist in the cache\n// with the given namespace/name.\n// This method returns an error if the PVC object's phase is not \"Bound\".\nfunc getPVCFromCache(namespace string, name string, pvcLister corelisters.PersistentVolumeClaimLister) (*v1.PersistentVolumeClaim, error) {\n\tpvc, err := pvcLister.PersistentVolumeClaims(namespace).Get(name)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to find PVC %s/%s in PVCInformer cache: %v\", namespace, name, err)\n\t}\n\n\tif pvc.Status.Phase != v1.ClaimBound || pvc.Spec.VolumeName == \"\" {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"PVC %s/%s has non-bound phase (%q) or empty pvc.Spec.VolumeName (%q)\",\n\t\t\tnamespace,\n\t\t\tname,\n\t\t\tpvc.Status.Phase,\n\t\t\tpvc.Spec.VolumeName)\n\t}\n\n\treturn pvc, nil\n}","line":{"from":113,"to":134}} {"id":100004956,"name":"getPVSpecFromCache","signature":"func getPVSpecFromCache(name string, pvcReadOnly bool, expectedClaimUID types.UID, pvLister corelisters.PersistentVolumeLister) (*volume.Spec, error)","file":"pkg/controller/volume/attachdetach/util/util.go","code":"// getPVSpecFromCache fetches the PV object with the given name from the shared\n// internal PV store and returns a volume.Spec representing it.\n// This method returns an error if a PV object does not exist in the cache with\n// the given name.\n// This method deep copies the PV object so the caller may use the returned\n// volume.Spec object without worrying about it mutating unexpectedly.\nfunc getPVSpecFromCache(name string, pvcReadOnly bool, expectedClaimUID types.UID, pvLister corelisters.PersistentVolumeLister) (*volume.Spec, error) {\n\tpv, err := pvLister.Get(name)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to find PV %q in PVInformer cache: %v\", name, err)\n\t}\n\n\tif pv.Spec.ClaimRef == nil {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"found PV object %q but it has a nil pv.Spec.ClaimRef indicating it is not yet bound to the claim\",\n\t\t\tname)\n\t}\n\n\tif pv.Spec.ClaimRef.UID != expectedClaimUID {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"found PV object %q but its pv.Spec.ClaimRef.UID (%q) does not point to claim.UID (%q)\",\n\t\t\tname,\n\t\t\tpv.Spec.ClaimRef.UID,\n\t\t\texpectedClaimUID)\n\t}\n\n\t// Do not return the object from the informer, since the store is shared it\n\t// may be mutated by another consumer.\n\tclonedPV := pv.DeepCopy()\n\n\treturn volume.NewSpecFromPersistentVolume(clonedPV, pvcReadOnly), nil\n}","line":{"from":136,"to":167}} {"id":100004957,"name":"DetermineVolumeAction","signature":"func DetermineVolumeAction(pod *v1.Pod, desiredStateOfWorld cache.DesiredStateOfWorld, defaultAction bool) bool","file":"pkg/controller/volume/attachdetach/util/util.go","code":"// DetermineVolumeAction returns true if volume and pod needs to be added to dswp\n// and it returns false if volume and pod needs to be removed from dswp\nfunc DetermineVolumeAction(pod *v1.Pod, desiredStateOfWorld cache.DesiredStateOfWorld, defaultAction bool) bool {\n\tif pod == nil || len(pod.Spec.Volumes) \u003c= 0 {\n\t\treturn defaultAction\n\t}\n\n\tif util.IsPodTerminated(pod, pod.Status) {\n\t\tnodeName := types.NodeName(pod.Spec.NodeName)\n\t\tkeepTerminatedPodVolume := desiredStateOfWorld.GetKeepTerminatedPodVolumesForNode(nodeName)\n\t\t// if pod is terminate we let kubelet policy dictate if volume\n\t\t// should be detached or not\n\t\treturn keepTerminatedPodVolume\n\t}\n\treturn defaultAction\n}","line":{"from":169,"to":184}} {"id":100004958,"name":"ProcessPodVolumes","signature":"func ProcessPodVolumes(logger klog.Logger, pod *v1.Pod, addVolumes bool, desiredStateOfWorld cache.DesiredStateOfWorld, volumePluginMgr *volume.VolumePluginMgr, pvcLister corelisters.PersistentVolumeClaimLister, pvLister corelisters.PersistentVolumeLister, csiMigratedPluginManager csimigration.PluginManager, csiTranslator csimigration.InTreeToCSITranslator)","file":"pkg/controller/volume/attachdetach/util/util.go","code":"// ProcessPodVolumes processes the volumes in the given pod and adds them to the\n// desired state of the world if addVolumes is true, otherwise it removes them.\nfunc ProcessPodVolumes(logger klog.Logger, pod *v1.Pod, addVolumes bool, desiredStateOfWorld cache.DesiredStateOfWorld, volumePluginMgr *volume.VolumePluginMgr, pvcLister corelisters.PersistentVolumeClaimLister, pvLister corelisters.PersistentVolumeLister, csiMigratedPluginManager csimigration.PluginManager, csiTranslator csimigration.InTreeToCSITranslator) {\n\tif pod == nil {\n\t\treturn\n\t}\n\tif len(pod.Spec.Volumes) \u003c= 0 {\n\t\tlogger.V(10).Info(\"Skipping processing of pod, it has no volumes\", \"pod\", klog.KObj(pod))\n\t\treturn\n\t}\n\n\tnodeName := types.NodeName(pod.Spec.NodeName)\n\tif nodeName == \"\" {\n\t\tlogger.V(10).Info(\"Skipping processing of pod, it is not scheduled to a node\", \"pod\", klog.KObj(pod))\n\t\treturn\n\t} else if !desiredStateOfWorld.NodeExists(nodeName) {\n\t\t// If the node the pod is scheduled to does not exist in the desired\n\t\t// state of the world data structure, that indicates the node is not\n\t\t// yet managed by the controller. Therefore, ignore the pod.\n\t\tlogger.V(4).Info(\"Skipping processing of pod, it is scheduled to node which is not managed by the controller\", \"node\", klog.KRef(\"\", string(nodeName)), \"pod\", klog.KObj(pod))\n\t\treturn\n\t}\n\n\t// Process volume spec for each volume defined in pod\n\tfor _, podVolume := range pod.Spec.Volumes {\n\t\tvolumeSpec, err := CreateVolumeSpec(logger, podVolume, pod, nodeName, volumePluginMgr, pvcLister, pvLister, csiMigratedPluginManager, csiTranslator)\n\t\tif err != nil {\n\t\t\tlogger.V(10).Info(\"Error processing volume for pod\", \"pod\", klog.KObj(pod), \"volumeName\", podVolume.Name, \"err\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tattachableVolumePlugin, err :=\n\t\t\tvolumePluginMgr.FindAttachablePluginBySpec(volumeSpec)\n\t\tif err != nil || attachableVolumePlugin == nil {\n\t\t\tlogger.V(10).Info(\"Skipping volume for pod, it does not implement attacher interface\", \"pod\", klog.KObj(pod), \"volumeName\", podVolume.Name, \"err\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tuniquePodName := util.GetUniquePodName(pod)\n\t\tif addVolumes {\n\t\t\t// Add volume to desired state of world\n\t\t\t_, err := desiredStateOfWorld.AddPod(\n\t\t\t\tuniquePodName, pod, volumeSpec, nodeName)\n\t\t\tif err != nil {\n\t\t\t\tlogger.V(10).Info(\"Failed to add volume for pod to desiredStateOfWorld\", \"pod\", klog.KObj(pod), \"volumeName\", podVolume.Name, \"err\", err)\n\t\t\t}\n\n\t\t} else {\n\t\t\t// Remove volume from desired state of world\n\t\t\tuniqueVolumeName, err := util.GetUniqueVolumeNameFromSpec(\n\t\t\t\tattachableVolumePlugin, volumeSpec)\n\t\t\tif err != nil {\n\t\t\t\tlogger.V(10).Info(\"Failed to delete volume for pod from desiredStateOfWorld. GetUniqueVolumeNameFromSpec failed\", \"pod\", klog.KObj(pod), \"volumeName\", podVolume.Name, \"err\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdesiredStateOfWorld.DeletePod(\n\t\t\t\tuniquePodName, uniqueVolumeName, nodeName)\n\t\t}\n\t}\n\treturn\n}","line":{"from":186,"to":246}} {"id":100004959,"name":"translateInTreeSpecToCSIIfNeeded","signature":"func translateInTreeSpecToCSIIfNeeded(spec *volume.Spec, nodeName types.NodeName, vpm *volume.VolumePluginMgr, csiMigratedPluginManager csimigration.PluginManager, csiTranslator csimigration.InTreeToCSITranslator, podNamespace string) (*volume.Spec, error)","file":"pkg/controller/volume/attachdetach/util/util.go","code":"func translateInTreeSpecToCSIIfNeeded(spec *volume.Spec, nodeName types.NodeName, vpm *volume.VolumePluginMgr, csiMigratedPluginManager csimigration.PluginManager, csiTranslator csimigration.InTreeToCSITranslator, podNamespace string) (*volume.Spec, error) {\n\ttranslatedSpec := spec\n\tmigratable, err := csiMigratedPluginManager.IsMigratable(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !migratable {\n\t\t// Jump out of translation fast so we don't check the node if the spec itself is not migratable\n\t\treturn spec, nil\n\t}\n\tmigrationSupportedOnNode, err := isCSIMigrationSupportedOnNode(nodeName, spec, vpm, csiMigratedPluginManager)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif migratable \u0026\u0026 migrationSupportedOnNode {\n\t\ttranslatedSpec, err = csimigration.TranslateInTreeSpecToCSI(spec, podNamespace, csiTranslator)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn translatedSpec, nil\n}","line":{"from":248,"to":269}} {"id":100004960,"name":"isCSIMigrationSupportedOnNode","signature":"func isCSIMigrationSupportedOnNode(nodeName types.NodeName, spec *volume.Spec, vpm *volume.VolumePluginMgr, csiMigratedPluginManager csimigration.PluginManager) (bool, error)","file":"pkg/controller/volume/attachdetach/util/util.go","code":"func isCSIMigrationSupportedOnNode(nodeName types.NodeName, spec *volume.Spec, vpm *volume.VolumePluginMgr, csiMigratedPluginManager csimigration.PluginManager) (bool, error) {\n\tpluginName, err := csiMigratedPluginManager.GetInTreePluginNameFromSpec(spec.PersistentVolume, spec.Volume)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif len(pluginName) == 0 {\n\t\t// Could not find a plugin name from translation directory, assume not translated\n\t\treturn false, nil\n\t}\n\n\tif csiMigratedPluginManager.IsMigrationCompleteForPlugin(pluginName) {\n\t\t// All nodes are expected to have migrated CSI plugin installed and\n\t\t// configured when CSI Migration Complete flag is enabled for a plugin.\n\t\t// CSI migration is supported even if there is version skew between\n\t\t// managers and node.\n\t\treturn true, nil\n\t}\n\n\tif len(nodeName) == 0 {\n\t\treturn false, errors.New(\"nodeName is empty\")\n\t}\n\n\tkubeClient := vpm.Host.GetKubeClient()\n\tif kubeClient == nil {\n\t\t// Don't handle the controller/kubelet version skew check and fallback\n\t\t// to just checking the feature gates. This can happen if\n\t\t// we are in a standalone (headless) Kubelet\n\t\treturn true, nil\n\t}\n\n\tadcHost, ok := vpm.Host.(volume.AttachDetachVolumeHost)\n\tif !ok {\n\t\t// Don't handle the controller/kubelet version skew check and fallback\n\t\t// to just checking the feature gates. This can happen if\n\t\t// \"enableControllerAttachDetach\" is set to true on kubelet\n\t\treturn true, nil\n\t}\n\n\tif adcHost.CSINodeLister() == nil {\n\t\treturn false, errors.New(\"could not find CSINodeLister in attachDetachController\")\n\t}\n\n\tcsiNode, err := adcHost.CSINodeLister().Get(string(nodeName))\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tann := csiNode.GetAnnotations()\n\tif ann == nil {\n\t\treturn false, nil\n\t}\n\n\tmpa := ann[v1.MigratedPluginsAnnotationKey]\n\ttok := strings.Split(mpa, \",\")\n\tmpaSet := sets.NewString(tok...)\n\n\tisMigratedOnNode := mpaSet.Has(pluginName)\n\n\treturn isMigratedOnNode, nil\n}","line":{"from":271,"to":331}} {"id":100004961,"name":"PodPVCIndexFunc","signature":"func PodPVCIndexFunc() func(obj interface{}) ([]string, error)","file":"pkg/controller/volume/common/common.go","code":"// PodPVCIndexFunc creates an index function that returns PVC keys (=\n// namespace/name) for given pod. This includes the PVCs\n// that might be created for generic ephemeral volumes.\nfunc PodPVCIndexFunc() func(obj interface{}) ([]string, error) {\n\treturn func(obj interface{}) ([]string, error) {\n\t\tpod, ok := obj.(*v1.Pod)\n\t\tif !ok {\n\t\t\treturn []string{}, nil\n\t\t}\n\t\tkeys := []string{}\n\t\tfor _, podVolume := range pod.Spec.Volumes {\n\t\t\tclaimName := \"\"\n\t\t\tif pvcSource := podVolume.VolumeSource.PersistentVolumeClaim; pvcSource != nil {\n\t\t\t\tclaimName = pvcSource.ClaimName\n\t\t\t} else if podVolume.VolumeSource.Ephemeral != nil {\n\t\t\t\tclaimName = ephemeral.VolumeClaimName(pod, \u0026podVolume)\n\t\t\t}\n\t\t\tif claimName != \"\" {\n\t\t\t\tkeys = append(keys, fmt.Sprintf(\"%s/%s\", pod.Namespace, claimName))\n\t\t\t}\n\t\t}\n\t\treturn keys, nil\n\t}\n}","line":{"from":32,"to":55}} {"id":100004962,"name":"AddPodPVCIndexerIfNotPresent","signature":"func AddPodPVCIndexerIfNotPresent(indexer cache.Indexer) error","file":"pkg/controller/volume/common/common.go","code":"// AddPodPVCIndexerIfNotPresent adds the PodPVCIndexFunc.\nfunc AddPodPVCIndexerIfNotPresent(indexer cache.Indexer) error {\n\treturn AddIndexerIfNotPresent(indexer, PodPVCIndex, PodPVCIndexFunc())\n}","line":{"from":57,"to":60}} {"id":100004963,"name":"AddIndexerIfNotPresent","signature":"func AddIndexerIfNotPresent(indexer cache.Indexer, indexName string, indexFunc cache.IndexFunc) error","file":"pkg/controller/volume/common/common.go","code":"// AddIndexerIfNotPresent adds the index function with the name into the cache indexer if not present\nfunc AddIndexerIfNotPresent(indexer cache.Indexer, indexName string, indexFunc cache.IndexFunc) error {\n\tindexers := indexer.GetIndexers()\n\tif _, ok := indexers[indexName]; ok {\n\t\treturn nil\n\t}\n\treturn indexer.AddIndexers(cache.Indexers{indexName: indexFunc})\n}","line":{"from":62,"to":69}} {"id":100004964,"name":"Convert_v1alpha1_EphemeralVolumeControllerConfiguration_To_config_EphemeralVolumeControllerConfiguration","signature":"func Convert_v1alpha1_EphemeralVolumeControllerConfiguration_To_config_EphemeralVolumeControllerConfiguration(in *v1alpha1.EphemeralVolumeControllerConfiguration, out *config.EphemeralVolumeControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/volume/ephemeral/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_EphemeralVolumeControllerConfiguration_To_config_EphemeralVolumeControllerConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_EphemeralVolumeControllerConfiguration_To_config_EphemeralVolumeControllerConfiguration(in *v1alpha1.EphemeralVolumeControllerConfiguration, out *config.EphemeralVolumeControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_EphemeralVolumeControllerConfiguration_To_config_EphemeralVolumeControllerConfiguration(in, out, s)\n}","line":{"from":32,"to":35}} {"id":100004965,"name":"Convert_config_EphemeralVolumeControllerConfiguration_To_v1alpha1_EphemeralVolumeControllerConfiguration","signature":"func Convert_config_EphemeralVolumeControllerConfiguration_To_v1alpha1_EphemeralVolumeControllerConfiguration(in *config.EphemeralVolumeControllerConfiguration, out *v1alpha1.EphemeralVolumeControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/volume/ephemeral/config/v1alpha1/conversion.go","code":"// Convert_config_EphemeralVolumeControllerConfiguration_To_v1alpha1_EphemeralVolumeControllerConfiguration is an autogenerated conversion function.\nfunc Convert_config_EphemeralVolumeControllerConfiguration_To_v1alpha1_EphemeralVolumeControllerConfiguration(in *config.EphemeralVolumeControllerConfiguration, out *v1alpha1.EphemeralVolumeControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_EphemeralVolumeControllerConfiguration_To_v1alpha1_EphemeralVolumeControllerConfiguration(in, out, s)\n}","line":{"from":37,"to":40}} {"id":100004966,"name":"RecommendedDefaultEphemeralVolumeControllerConfiguration","signature":"func RecommendedDefaultEphemeralVolumeControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.EphemeralVolumeControllerConfiguration)","file":"pkg/controller/volume/ephemeral/config/v1alpha1/defaults.go","code":"// RecommendedDefaultEphemeralVolumeControllerConfiguration defaults a pointer to a\n// EphemeralVolumeControllerConfiguration struct. This will set the recommended default\n// values, but they may be subject to change between API versions. This function\n// is intentionally not registered in the scheme as a \"normal\" `SetDefaults_Foo`\n// function to allow consumers of this type to set whatever defaults for their\n// embedded configs. Forcing consumers to use these defaults would be problematic\n// as defaulting in the scheme is done as part of the conversion, and there would\n// be no easy way to opt-out. Instead, if you want to use this defaulting method\n// run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDefaultEphemeralVolumeControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.EphemeralVolumeControllerConfiguration) {\n\tif obj.ConcurrentEphemeralVolumeSyncs == 0 {\n\t\tobj.ConcurrentEphemeralVolumeSyncs = 5\n\t}\n}","line":{"from":23,"to":36}} {"id":100004967,"name":"NewController","signature":"func NewController(","file":"pkg/controller/volume/ephemeral/controller.go","code":"// NewController creates an ephemeral volume controller.\nfunc NewController(\n\tkubeClient clientset.Interface,\n\tpodInformer coreinformers.PodInformer,\n\tpvcInformer coreinformers.PersistentVolumeClaimInformer) (Controller, error) {\n\n\tec := \u0026ephemeralController{\n\t\tkubeClient: kubeClient,\n\t\tpodLister: podInformer.Lister(),\n\t\tpodIndexer: podInformer.Informer().GetIndexer(),\n\t\tpodSynced: podInformer.Informer().HasSynced,\n\t\tpvcLister: pvcInformer.Lister(),\n\t\tpvcsSynced: pvcInformer.Informer().HasSynced,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"ephemeral_volume\"),\n\t}\n\n\tephemeralvolumemetrics.RegisterMetrics()\n\n\teventBroadcaster := record.NewBroadcaster()\n\teventBroadcaster.StartLogging(klog.Infof)\n\teventBroadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: kubeClient.CoreV1().Events(\"\")})\n\tec.recorder = eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"ephemeral_volume\"})\n\n\tpodInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: ec.enqueuePod,\n\t\t// The pod spec is immutable. Therefore the controller can ignore pod updates\n\t\t// because there cannot be any changes that have to be copied into the generated\n\t\t// PVC.\n\t\t// Deletion of the PVC is handled through the owner reference and garbage collection.\n\t\t// Therefore pod deletions also can be ignored.\n\t})\n\tpvcInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tDeleteFunc: ec.onPVCDelete,\n\t})\n\tif err := common.AddPodPVCIndexerIfNotPresent(ec.podIndexer); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not initialize pvc protection controller: %w\", err)\n\t}\n\n\treturn ec, nil\n}","line":{"from":77,"to":116}} {"id":100004968,"name":"enqueuePod","signature":"func (ec *ephemeralController) enqueuePod(obj interface{})","file":"pkg/controller/volume/ephemeral/controller.go","code":"func (ec *ephemeralController) enqueuePod(obj interface{}) {\n\tpod, ok := obj.(*v1.Pod)\n\tif !ok {\n\t\treturn\n\t}\n\n\t// Ignore pods which are already getting deleted.\n\tif pod.DeletionTimestamp != nil {\n\t\treturn\n\t}\n\n\tfor _, vol := range pod.Spec.Volumes {\n\t\tif vol.Ephemeral != nil {\n\t\t\t// It has at least one ephemeral inline volume, work on it.\n\t\t\tkey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(pod)\n\t\t\tif err != nil {\n\t\t\t\truntime.HandleError(fmt.Errorf(\"couldn't get key for object %#v: %v\", pod, err))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tec.queue.Add(key)\n\t\t\tbreak\n\t\t}\n\t}\n}","line":{"from":118,"to":141}} {"id":100004969,"name":"onPVCDelete","signature":"func (ec *ephemeralController) onPVCDelete(obj interface{})","file":"pkg/controller/volume/ephemeral/controller.go","code":"func (ec *ephemeralController) onPVCDelete(obj interface{}) {\n\tpvc, ok := obj.(*v1.PersistentVolumeClaim)\n\tif !ok {\n\t\treturn\n\t}\n\n\t// Someone deleted a PVC, either intentionally or\n\t// accidentally. If there is a pod referencing it because of\n\t// an ephemeral volume, then we should re-create the PVC.\n\t// The common indexer does some prefiltering for us by\n\t// limiting the list to those pods which reference\n\t// the PVC.\n\tobjs, err := ec.podIndexer.ByIndex(common.PodPVCIndex, fmt.Sprintf(\"%s/%s\", pvc.Namespace, pvc.Name))\n\tif err != nil {\n\t\truntime.HandleError(fmt.Errorf(\"listing pods from cache: %v\", err))\n\t\treturn\n\t}\n\tfor _, obj := range objs {\n\t\tec.enqueuePod(obj)\n\t}\n}","line":{"from":143,"to":163}} {"id":100004970,"name":"Run","signature":"func (ec *ephemeralController) Run(ctx context.Context, workers int)","file":"pkg/controller/volume/ephemeral/controller.go","code":"func (ec *ephemeralController) Run(ctx context.Context, workers int) {\n\tdefer runtime.HandleCrash()\n\tdefer ec.queue.ShutDown()\n\tlogger := klog.FromContext(ctx)\n\tlogger.Info(\"Starting ephemeral volume controller\")\n\tdefer logger.Info(\"Shutting down ephemeral volume controller\")\n\n\tif !cache.WaitForNamedCacheSync(\"ephemeral\", ctx.Done(), ec.podSynced, ec.pvcsSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.UntilWithContext(ctx, ec.runWorker, time.Second)\n\t}\n\n\t\u003c-ctx.Done()\n}","line":{"from":165,"to":181}} {"id":100004971,"name":"runWorker","signature":"func (ec *ephemeralController) runWorker(ctx context.Context)","file":"pkg/controller/volume/ephemeral/controller.go","code":"func (ec *ephemeralController) runWorker(ctx context.Context) {\n\tfor ec.processNextWorkItem(ctx) {\n\t}\n}","line":{"from":183,"to":186}} {"id":100004972,"name":"processNextWorkItem","signature":"func (ec *ephemeralController) processNextWorkItem(ctx context.Context) bool","file":"pkg/controller/volume/ephemeral/controller.go","code":"func (ec *ephemeralController) processNextWorkItem(ctx context.Context) bool {\n\tkey, shutdown := ec.queue.Get()\n\tif shutdown {\n\t\treturn false\n\t}\n\tdefer ec.queue.Done(key)\n\n\terr := ec.syncHandler(ctx, key.(string))\n\tif err == nil {\n\t\tec.queue.Forget(key)\n\t\treturn true\n\t}\n\n\truntime.HandleError(fmt.Errorf(\"%v failed with: %v\", key, err))\n\tec.queue.AddRateLimited(key)\n\n\treturn true\n}","line":{"from":188,"to":205}} {"id":100004973,"name":"syncHandler","signature":"func (ec *ephemeralController) syncHandler(ctx context.Context, key string) error","file":"pkg/controller/volume/ephemeral/controller.go","code":"// syncHandler is invoked for each pod which might need to be processed.\n// If an error is returned from this function, the pod will be requeued.\nfunc (ec *ephemeralController) syncHandler(ctx context.Context, key string) error {\n\tnamespace, name, err := cache.SplitMetaNamespaceKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpod, err := ec.podLister.Pods(namespace).Get(name)\n\tlogger := klog.FromContext(ctx)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\tlogger.V(5).Info(\"Ephemeral: nothing to do for pod, it is gone\", \"podKey\", key)\n\t\t\treturn nil\n\t\t}\n\t\tlogger.V(5).Info(\"Error getting pod from informer\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID, \"err\", err)\n\t\treturn err\n\t}\n\n\t// Ignore pods which are already getting deleted.\n\tif pod.DeletionTimestamp != nil {\n\t\tlogger.V(5).Info(\"Ephemeral: nothing to do for pod, it is marked for deletion\", \"podKey\", key)\n\t\treturn nil\n\t}\n\n\tfor _, vol := range pod.Spec.Volumes {\n\t\tif err := ec.handleVolume(ctx, pod, vol); err != nil {\n\t\t\tec.recorder.Event(pod, v1.EventTypeWarning, events.FailedBinding, fmt.Sprintf(\"ephemeral volume %s: %v\", vol.Name, err))\n\t\t\treturn fmt.Errorf(\"pod %s, ephemeral volume %s: %v\", key, vol.Name, err)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":207,"to":239}} {"id":100004974,"name":"handleVolume","signature":"func (ec *ephemeralController) handleVolume(ctx context.Context, pod *v1.Pod, vol v1.Volume) error","file":"pkg/controller/volume/ephemeral/controller.go","code":"// handleEphemeralVolume is invoked for each volume of a pod.\nfunc (ec *ephemeralController) handleVolume(ctx context.Context, pod *v1.Pod, vol v1.Volume) error {\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(5).Info(\"Ephemeral: checking volume\", \"volumeName\", vol.Name)\n\tif vol.Ephemeral == nil {\n\t\treturn nil\n\t}\n\n\tpvcName := ephemeral.VolumeClaimName(pod, \u0026vol)\n\tpvc, err := ec.pvcLister.PersistentVolumeClaims(pod.Namespace).Get(pvcName)\n\tif err != nil \u0026\u0026 !errors.IsNotFound(err) {\n\t\treturn err\n\t}\n\tif pvc != nil {\n\t\tif err := ephemeral.VolumeIsForPod(pod, pvc); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Already created, nothing more to do.\n\t\tlogger.V(5).Info(\"Ephemeral: PVC already created\", \"volumeName\", vol.Name, \"PVC\", klog.KObj(pvc))\n\t\treturn nil\n\t}\n\n\t// Create the PVC with pod as owner.\n\tisTrue := true\n\tpvc = \u0026v1.PersistentVolumeClaim{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: pvcName,\n\t\t\tOwnerReferences: []metav1.OwnerReference{\n\t\t\t\t{\n\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t\tKind: \"Pod\",\n\t\t\t\t\tName: pod.Name,\n\t\t\t\t\tUID: pod.UID,\n\t\t\t\t\tController: \u0026isTrue,\n\t\t\t\t\tBlockOwnerDeletion: \u0026isTrue,\n\t\t\t\t},\n\t\t\t},\n\t\t\tAnnotations: vol.Ephemeral.VolumeClaimTemplate.Annotations,\n\t\t\tLabels: vol.Ephemeral.VolumeClaimTemplate.Labels,\n\t\t},\n\t\tSpec: vol.Ephemeral.VolumeClaimTemplate.Spec,\n\t}\n\tephemeralvolumemetrics.EphemeralVolumeCreateAttempts.Inc()\n\t_, err = ec.kubeClient.CoreV1().PersistentVolumeClaims(pod.Namespace).Create(ctx, pvc, metav1.CreateOptions{})\n\tif err != nil {\n\t\tephemeralvolumemetrics.EphemeralVolumeCreateFailures.Inc()\n\t\treturn fmt.Errorf(\"create PVC %s: %v\", pvcName, err)\n\t}\n\treturn nil\n}","line":{"from":241,"to":290}} {"id":100004975,"name":"RegisterMetrics","signature":"func RegisterMetrics()","file":"pkg/controller/volume/ephemeral/metrics/metrics.go","code":"// RegisterMetrics registers EphemeralVolume metrics.\nfunc RegisterMetrics() {\n\tregisterMetrics.Do(func() {\n\t\tlegacyregistry.MustRegister(EphemeralVolumeCreateAttempts)\n\t\tlegacyregistry.MustRegister(EphemeralVolumeCreateFailures)\n\t})\n}","line":{"from":52,"to":58}} {"id":100004976,"name":"NewExpandController","signature":"func NewExpandController(","file":"pkg/controller/volume/expand/expand_controller.go","code":"// NewExpandController expands the pvs\nfunc NewExpandController(\n\tkubeClient clientset.Interface,\n\tpvcInformer coreinformers.PersistentVolumeClaimInformer,\n\tpvInformer coreinformers.PersistentVolumeInformer,\n\tcloud cloudprovider.Interface,\n\tplugins []volume.VolumePlugin,\n\ttranslator CSINameTranslator,\n\tcsiMigratedPluginManager csimigration.PluginManager,\n\tfilteredDialOptions *proxyutil.FilteredDialOptions) (ExpandController, error) {\n\n\texpc := \u0026expandController{\n\t\tkubeClient: kubeClient,\n\t\tcloud: cloud,\n\t\tpvcLister: pvcInformer.Lister(),\n\t\tpvcsSynced: pvcInformer.Informer().HasSynced,\n\t\tpvLister: pvInformer.Lister(),\n\t\tpvSynced: pvInformer.Informer().HasSynced,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"volume_expand\"),\n\t\ttranslator: translator,\n\t\tcsiMigratedPluginManager: csiMigratedPluginManager,\n\t\tfilteredDialOptions: filteredDialOptions,\n\t}\n\n\tif err := expc.volumePluginMgr.InitPlugins(plugins, nil, expc); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not initialize volume plugins for Expand Controller : %+v\", err)\n\t}\n\n\teventBroadcaster := record.NewBroadcaster()\n\teventBroadcaster.StartStructuredLogging(0)\n\teventBroadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: kubeClient.CoreV1().Events(\"\")})\n\texpc.recorder = eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"volume_expand\"})\n\tblkutil := volumepathhandler.NewBlockVolumePathHandler()\n\n\texpc.operationGenerator = operationexecutor.NewOperationGenerator(\n\t\tkubeClient,\n\t\t\u0026expc.volumePluginMgr,\n\t\texpc.recorder,\n\t\tblkutil)\n\n\tpvcInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: expc.enqueuePVC,\n\t\tUpdateFunc: func(old, new interface{}) {\n\t\t\toldPVC, ok := old.(*v1.PersistentVolumeClaim)\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\toldReq := oldPVC.Spec.Resources.Requests[v1.ResourceStorage]\n\t\t\toldCap := oldPVC.Status.Capacity[v1.ResourceStorage]\n\t\t\tnewPVC, ok := new.(*v1.PersistentVolumeClaim)\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tnewReq := newPVC.Spec.Resources.Requests[v1.ResourceStorage]\n\t\t\tnewCap := newPVC.Status.Capacity[v1.ResourceStorage]\n\t\t\t// PVC will be enqueued under 2 circumstances\n\t\t\t// 1. User has increased PVC's request capacity --\u003e volume needs to be expanded\n\t\t\t// 2. PVC status capacity has been expanded --\u003e claim's bound PV has likely recently gone through filesystem resize, so remove AnnPreResizeCapacity annotation from PV\n\t\t\tif newReq.Cmp(oldReq) \u003e 0 || newCap.Cmp(oldCap) \u003e 0 {\n\t\t\t\texpc.enqueuePVC(new)\n\t\t\t}\n\t\t},\n\t\tDeleteFunc: expc.enqueuePVC,\n\t})\n\n\treturn expc, nil\n}","line":{"from":107,"to":174}} {"id":100004977,"name":"enqueuePVC","signature":"func (expc *expandController) enqueuePVC(obj interface{})","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) enqueuePVC(obj interface{}) {\n\tpvc, ok := obj.(*v1.PersistentVolumeClaim)\n\tif !ok {\n\t\treturn\n\t}\n\n\tif pvc.Status.Phase == v1.ClaimBound {\n\t\tkey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(pvc)\n\t\tif err != nil {\n\t\t\truntime.HandleError(fmt.Errorf(\"couldn't get key for object %#v: %v\", pvc, err))\n\t\t\treturn\n\t\t}\n\t\texpc.queue.Add(key)\n\t}\n}","line":{"from":176,"to":190}} {"id":100004978,"name":"processNextWorkItem","signature":"func (expc *expandController) processNextWorkItem(ctx context.Context) bool","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) processNextWorkItem(ctx context.Context) bool {\n\tkey, shutdown := expc.queue.Get()\n\tif shutdown {\n\t\treturn false\n\t}\n\tdefer expc.queue.Done(key)\n\n\terr := expc.syncHandler(ctx, key.(string))\n\tif err == nil {\n\t\texpc.queue.Forget(key)\n\t\treturn true\n\t}\n\n\truntime.HandleError(fmt.Errorf(\"%v failed with : %v\", key, err))\n\texpc.queue.AddRateLimited(key)\n\n\treturn true\n}","line":{"from":192,"to":209}} {"id":100004979,"name":"syncHandler","signature":"func (expc *expandController) syncHandler(ctx context.Context, key string) error","file":"pkg/controller/volume/expand/expand_controller.go","code":"// syncHandler performs actual expansion of volume. If an error is returned\n// from this function - PVC will be requeued for resizing.\nfunc (expc *expandController) syncHandler(ctx context.Context, key string) error {\n\tnamespace, name, err := cache.SplitMetaNamespaceKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpvc, err := expc.pvcLister.PersistentVolumeClaims(namespace).Get(name)\n\tif errors.IsNotFound(err) {\n\t\treturn nil\n\t}\n\tlogger := klog.FromContext(ctx)\n\tif err != nil {\n\t\tlogger.V(5).Info(\"Error getting PVC from informer\", \"pvcKey\", key, \"err\", err)\n\t\treturn err\n\t}\n\n\tpv, err := expc.getPersistentVolume(ctx, pvc)\n\tif err != nil {\n\t\tlogger.V(5).Info(\"Error getting Persistent Volume for PVC from informer\", \"pvcKey\", key, \"pvcUID\", pvc.UID, \"err\", err)\n\t\treturn err\n\t}\n\n\tif pv.Spec.ClaimRef == nil || pvc.Namespace != pv.Spec.ClaimRef.Namespace || pvc.UID != pv.Spec.ClaimRef.UID {\n\t\terr := fmt.Errorf(\"persistent Volume is not bound to PVC being updated : %s\", key)\n\t\tlogger.V(4).Info(\"\", \"err\", err)\n\t\treturn err\n\t}\n\n\tpvcRequestSize := pvc.Spec.Resources.Requests[v1.ResourceStorage]\n\tpvcStatusSize := pvc.Status.Capacity[v1.ResourceStorage]\n\n\t// call expand operation only under two condition\n\t// 1. pvc's request size has been expanded and is larger than pvc's current status size\n\t// 2. pv has an pre-resize capacity annotation\n\tif pvcRequestSize.Cmp(pvcStatusSize) \u003c= 0 \u0026\u0026 !metav1.HasAnnotation(pv.ObjectMeta, util.AnnPreResizeCapacity) {\n\t\treturn nil\n\t}\n\n\tvolumeSpec := volume.NewSpecFromPersistentVolume(pv, false)\n\tmigratable, err := expc.csiMigratedPluginManager.IsMigratable(volumeSpec)\n\tif err != nil {\n\t\tlogger.V(4).Info(\"Failed to check CSI migration status for PVC with error\", \"pvcKey\", key, \"err\", err)\n\t\treturn nil\n\t}\n\t// handle CSI migration scenarios before invoking FindExpandablePluginBySpec for in-tree\n\tif migratable {\n\t\tinTreePluginName, err := expc.csiMigratedPluginManager.GetInTreePluginNameFromSpec(volumeSpec.PersistentVolume, volumeSpec.Volume)\n\t\tif err != nil {\n\t\t\tlogger.V(4).Info(\"Error getting in-tree plugin name from persistent volume\", \"volumeName\", volumeSpec.PersistentVolume.Name, \"err\", err)\n\t\t\treturn err\n\t\t}\n\n\t\tmsg := fmt.Sprintf(\"CSI migration enabled for %s; waiting for external resizer to expand the pvc\", inTreePluginName)\n\t\texpc.recorder.Event(pvc, v1.EventTypeNormal, events.ExternalExpanding, msg)\n\t\tcsiResizerName, err := expc.translator.GetCSINameFromInTreeName(inTreePluginName)\n\t\tif err != nil {\n\t\t\terrorMsg := fmt.Sprintf(\"error getting CSI driver name for pvc %s, with error %v\", key, err)\n\t\t\texpc.recorder.Event(pvc, v1.EventTypeWarning, events.ExternalExpanding, errorMsg)\n\t\t\treturn fmt.Errorf(errorMsg)\n\t\t}\n\n\t\tpvc, err := util.SetClaimResizer(pvc, csiResizerName, expc.kubeClient)\n\t\tif err != nil {\n\t\t\terrorMsg := fmt.Sprintf(\"error setting resizer annotation to pvc %s, with error %v\", key, err)\n\t\t\texpc.recorder.Event(pvc, v1.EventTypeWarning, events.ExternalExpanding, errorMsg)\n\t\t\treturn fmt.Errorf(errorMsg)\n\t\t}\n\t\treturn nil\n\t}\n\n\tvolumePlugin, err := expc.volumePluginMgr.FindExpandablePluginBySpec(volumeSpec)\n\tif err != nil || volumePlugin == nil {\n\t\tmsg := \"waiting for an external controller to expand this PVC\"\n\t\teventType := v1.EventTypeNormal\n\t\tif err != nil {\n\t\t\teventType = v1.EventTypeWarning\n\t\t}\n\t\texpc.recorder.Event(pvc, eventType, events.ExternalExpanding, msg)\n\t\tlogger.Info(\"Waiting for an external controller to expand the PVC\", \"pvcKey\", key, \"pvcUID\", pvc.UID)\n\t\t// If we are expecting that an external plugin will handle resizing this volume then\n\t\t// is no point in requeuing this PVC.\n\t\treturn nil\n\t}\n\n\tvolumeResizerName := volumePlugin.GetPluginName()\n\treturn expc.expand(logger, pvc, pv, volumeResizerName)\n}","line":{"from":211,"to":298}} {"id":100004980,"name":"expand","signature":"func (expc *expandController) expand(logger klog.Logger, pvc *v1.PersistentVolumeClaim, pv *v1.PersistentVolume, resizerName string) error","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) expand(logger klog.Logger, pvc *v1.PersistentVolumeClaim, pv *v1.PersistentVolume, resizerName string) error {\n\t// if node expand is complete and pv's annotation can be removed, remove the annotation from pv and return\n\tif expc.isNodeExpandComplete(logger, pvc, pv) \u0026\u0026 metav1.HasAnnotation(pv.ObjectMeta, util.AnnPreResizeCapacity) {\n\t\treturn util.DeleteAnnPreResizeCapacity(pv, expc.GetKubeClient())\n\t}\n\n\tvar generatedOptions volumetypes.GeneratedOperations\n\tvar err error\n\tif utilfeature.DefaultFeatureGate.Enabled(features.RecoverVolumeExpansionFailure) {\n\t\tgeneratedOptions, err = expc.operationGenerator.GenerateExpandAndRecoverVolumeFunc(pvc, pv, resizerName)\n\t\tif err != nil {\n\t\t\tlogger.Error(err, \"Error starting ExpandVolume for pvc\", \"PVC\", klog.KObj(pvc))\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tpvc, err := util.MarkResizeInProgressWithResizer(pvc, resizerName, expc.kubeClient)\n\t\tif err != nil {\n\t\t\tlogger.Error(err, \"Error setting PVC in progress with error\", \"PVC\", klog.KObj(pvc), \"err\", err)\n\t\t\treturn err\n\t\t}\n\n\t\tgeneratedOptions, err = expc.operationGenerator.GenerateExpandVolumeFunc(pvc, pv)\n\t\tif err != nil {\n\t\t\tlogger.Error(err, \"Error starting ExpandVolume for pvc with error\", \"PVC\", klog.KObj(pvc), \"err\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tlogger.V(5).Info(\"Starting ExpandVolume for volume\", \"volumeName\", util.GetPersistentVolumeClaimQualifiedName(pvc))\n\t_, detailedErr := generatedOptions.Run()\n\n\treturn detailedErr\n}","line":{"from":300,"to":332}} {"id":100004981,"name":"Run","signature":"func (expc *expandController) Run(ctx context.Context)","file":"pkg/controller/volume/expand/expand_controller.go","code":"// TODO make concurrency configurable (workers argument). previously, nestedpendingoperations spawned unlimited goroutines\nfunc (expc *expandController) Run(ctx context.Context) {\n\tdefer runtime.HandleCrash()\n\tdefer expc.queue.ShutDown()\n\tlogger := klog.FromContext(ctx)\n\tlogger.Info(\"Starting expand controller\")\n\tdefer logger.Info(\"Shutting down expand controller\")\n\n\tif !cache.WaitForNamedCacheSync(\"expand\", ctx.Done(), expc.pvcsSynced, expc.pvSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c defaultWorkerCount; i++ {\n\t\tgo wait.UntilWithContext(ctx, expc.runWorker, time.Second)\n\t}\n\n\t\u003c-ctx.Done()\n}","line":{"from":334,"to":351}} {"id":100004982,"name":"runWorker","signature":"func (expc *expandController) runWorker(ctx context.Context)","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) runWorker(ctx context.Context) {\n\tfor expc.processNextWorkItem(ctx) {\n\t}\n}","line":{"from":353,"to":356}} {"id":100004983,"name":"getPersistentVolume","signature":"func (expc *expandController) getPersistentVolume(ctx context.Context, pvc *v1.PersistentVolumeClaim) (*v1.PersistentVolume, error)","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) getPersistentVolume(ctx context.Context, pvc *v1.PersistentVolumeClaim) (*v1.PersistentVolume, error) {\n\tvolumeName := pvc.Spec.VolumeName\n\tpv, err := expc.kubeClient.CoreV1().PersistentVolumes().Get(ctx, volumeName, metav1.GetOptions{})\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get PV %q: %v\", volumeName, err)\n\t}\n\n\treturn pv.DeepCopy(), nil\n}","line":{"from":358,"to":367}} {"id":100004984,"name":"isNodeExpandComplete","signature":"func (expc *expandController) isNodeExpandComplete(logger klog.Logger, pvc *v1.PersistentVolumeClaim, pv *v1.PersistentVolume) bool","file":"pkg/controller/volume/expand/expand_controller.go","code":"// isNodeExpandComplete returns true if pvc.Status.Capacity \u003e= pv.Spec.Capacity\nfunc (expc *expandController) isNodeExpandComplete(logger klog.Logger, pvc *v1.PersistentVolumeClaim, pv *v1.PersistentVolume) bool {\n\tlogger.V(4).Info(\"pv and pvc capacity\", \"PV\", klog.KObj(pv), \"pvCapacity\", pv.Spec.Capacity[v1.ResourceStorage], \"PVC\", klog.KObj(pvc), \"pvcCapacity\", pvc.Status.Capacity[v1.ResourceStorage])\n\tpvcSpecCap := pvc.Spec.Resources.Requests.Storage()\n\tpvcStatusCap, pvCap := pvc.Status.Capacity[v1.ResourceStorage], pv.Spec.Capacity[v1.ResourceStorage]\n\n\t// since we allow shrinking volumes, we must compare both pvc status and capacity\n\t// with pv spec capacity.\n\tif pvcStatusCap.Cmp(*pvcSpecCap) \u003e= 0 \u0026\u0026 pvcStatusCap.Cmp(pvCap) \u003e= 0 {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":369,"to":381}} {"id":100004985,"name":"GetPluginDir","signature":"func (expc *expandController) GetPluginDir(pluginName string) string","file":"pkg/controller/volume/expand/expand_controller.go","code":"// Implementing VolumeHost interface\nfunc (expc *expandController) GetPluginDir(pluginName string) string {\n\treturn \"\"\n}","line":{"from":383,"to":386}} {"id":100004986,"name":"GetVolumeDevicePluginDir","signature":"func (expc *expandController) GetVolumeDevicePluginDir(pluginName string) string","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) GetVolumeDevicePluginDir(pluginName string) string {\n\treturn \"\"\n}","line":{"from":388,"to":390}} {"id":100004987,"name":"GetPodsDir","signature":"func (expc *expandController) GetPodsDir() string","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) GetPodsDir() string {\n\treturn \"\"\n}","line":{"from":392,"to":394}} {"id":100004988,"name":"GetPodVolumeDir","signature":"func (expc *expandController) GetPodVolumeDir(podUID types.UID, pluginName string, volumeName string) string","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) GetPodVolumeDir(podUID types.UID, pluginName string, volumeName string) string {\n\treturn \"\"\n}","line":{"from":396,"to":398}} {"id":100004989,"name":"GetPodVolumeDeviceDir","signature":"func (expc *expandController) GetPodVolumeDeviceDir(podUID types.UID, pluginName string) string","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) GetPodVolumeDeviceDir(podUID types.UID, pluginName string) string {\n\treturn \"\"\n}","line":{"from":400,"to":402}} {"id":100004990,"name":"GetPodPluginDir","signature":"func (expc *expandController) GetPodPluginDir(podUID types.UID, pluginName string) string","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) GetPodPluginDir(podUID types.UID, pluginName string) string {\n\treturn \"\"\n}","line":{"from":404,"to":406}} {"id":100004991,"name":"GetKubeClient","signature":"func (expc *expandController) GetKubeClient() clientset.Interface","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) GetKubeClient() clientset.Interface {\n\treturn expc.kubeClient\n}","line":{"from":408,"to":410}} {"id":100004992,"name":"NewWrapperMounter","signature":"func (expc *expandController) NewWrapperMounter(volName string, spec volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error)","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) NewWrapperMounter(volName string, spec volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error) {\n\treturn nil, fmt.Errorf(\"NewWrapperMounter not supported by expand controller's VolumeHost implementation\")\n}","line":{"from":412,"to":414}} {"id":100004993,"name":"NewWrapperUnmounter","signature":"func (expc *expandController) NewWrapperUnmounter(volName string, spec volume.Spec, podUID types.UID) (volume.Unmounter, error)","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) NewWrapperUnmounter(volName string, spec volume.Spec, podUID types.UID) (volume.Unmounter, error) {\n\treturn nil, fmt.Errorf(\"NewWrapperUnmounter not supported by expand controller's VolumeHost implementation\")\n}","line":{"from":416,"to":418}} {"id":100004994,"name":"GetCloudProvider","signature":"func (expc *expandController) GetCloudProvider() cloudprovider.Interface","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) GetCloudProvider() cloudprovider.Interface {\n\treturn expc.cloud\n}","line":{"from":420,"to":422}} {"id":100004995,"name":"GetMounter","signature":"func (expc *expandController) GetMounter(pluginName string) mount.Interface","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) GetMounter(pluginName string) mount.Interface {\n\treturn nil\n}","line":{"from":424,"to":426}} {"id":100004996,"name":"GetExec","signature":"func (expc *expandController) GetExec(pluginName string) utilexec.Interface","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) GetExec(pluginName string) utilexec.Interface {\n\treturn utilexec.New()\n}","line":{"from":428,"to":430}} {"id":100004997,"name":"GetHostName","signature":"func (expc *expandController) GetHostName() string","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) GetHostName() string {\n\treturn \"\"\n}","line":{"from":432,"to":434}} {"id":100004998,"name":"GetHostIP","signature":"func (expc *expandController) GetHostIP() (net.IP, error)","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) GetHostIP() (net.IP, error) {\n\treturn nil, fmt.Errorf(\"GetHostIP not supported by expand controller's VolumeHost implementation\")\n}","line":{"from":436,"to":438}} {"id":100004999,"name":"GetNodeAllocatable","signature":"func (expc *expandController) GetNodeAllocatable() (v1.ResourceList, error)","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) GetNodeAllocatable() (v1.ResourceList, error) {\n\treturn v1.ResourceList{}, nil\n}","line":{"from":440,"to":442}} {"id":100005000,"name":"GetSecretFunc","signature":"func (expc *expandController) GetSecretFunc() func(namespace, name string) (*v1.Secret, error)","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) GetSecretFunc() func(namespace, name string) (*v1.Secret, error) {\n\treturn func(_, _ string) (*v1.Secret, error) {\n\t\treturn nil, fmt.Errorf(\"GetSecret unsupported in expandController\")\n\t}\n}","line":{"from":444,"to":448}} {"id":100005001,"name":"GetConfigMapFunc","signature":"func (expc *expandController) GetConfigMapFunc() func(namespace, name string) (*v1.ConfigMap, error)","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) GetConfigMapFunc() func(namespace, name string) (*v1.ConfigMap, error) {\n\treturn func(_, _ string) (*v1.ConfigMap, error) {\n\t\treturn nil, fmt.Errorf(\"GetConfigMap unsupported in expandController\")\n\t}\n}","line":{"from":450,"to":454}} {"id":100005002,"name":"GetAttachedVolumesFromNodeStatus","signature":"func (expc *expandController) GetAttachedVolumesFromNodeStatus() (map[v1.UniqueVolumeName]string, error)","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) GetAttachedVolumesFromNodeStatus() (map[v1.UniqueVolumeName]string, error) {\n\treturn map[v1.UniqueVolumeName]string{}, nil\n}","line":{"from":456,"to":458}} {"id":100005003,"name":"GetServiceAccountTokenFunc","signature":"func (expc *expandController) GetServiceAccountTokenFunc() func(_, _ string, _ *authenticationv1.TokenRequest) (*authenticationv1.TokenRequest, error)","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) GetServiceAccountTokenFunc() func(_, _ string, _ *authenticationv1.TokenRequest) (*authenticationv1.TokenRequest, error) {\n\treturn func(_, _ string, _ *authenticationv1.TokenRequest) (*authenticationv1.TokenRequest, error) {\n\t\treturn nil, fmt.Errorf(\"GetServiceAccountToken unsupported in expandController\")\n\t}\n}","line":{"from":460,"to":464}} {"id":100005004,"name":"DeleteServiceAccountTokenFunc","signature":"func (expc *expandController) DeleteServiceAccountTokenFunc() func(types.UID)","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) DeleteServiceAccountTokenFunc() func(types.UID) {\n\treturn func(types.UID) {\n\t\tklog.ErrorS(nil, \"DeleteServiceAccountToken unsupported in expandController\")\n\t}\n}","line":{"from":466,"to":470}} {"id":100005005,"name":"GetNodeLabels","signature":"func (expc *expandController) GetNodeLabels() (map[string]string, error)","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) GetNodeLabels() (map[string]string, error) {\n\treturn nil, fmt.Errorf(\"GetNodeLabels unsupported in expandController\")\n}","line":{"from":472,"to":474}} {"id":100005006,"name":"GetNodeName","signature":"func (expc *expandController) GetNodeName() types.NodeName","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) GetNodeName() types.NodeName {\n\treturn \"\"\n}","line":{"from":476,"to":478}} {"id":100005007,"name":"GetEventRecorder","signature":"func (expc *expandController) GetEventRecorder() record.EventRecorder","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) GetEventRecorder() record.EventRecorder {\n\treturn expc.recorder\n}","line":{"from":480,"to":482}} {"id":100005008,"name":"GetSubpather","signature":"func (expc *expandController) GetSubpather() subpath.Interface","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) GetSubpather() subpath.Interface {\n\t// not needed for expand controller\n\treturn nil\n}","line":{"from":484,"to":487}} {"id":100005009,"name":"GetFilteredDialOptions","signature":"func (expc *expandController) GetFilteredDialOptions() *proxyutil.FilteredDialOptions","file":"pkg/controller/volume/expand/expand_controller.go","code":"func (expc *expandController) GetFilteredDialOptions() *proxyutil.FilteredDialOptions {\n\treturn expc.filteredDialOptions\n}","line":{"from":489,"to":491}} {"id":100005010,"name":"Convert_v1alpha1_PersistentVolumeBinderControllerConfiguration_To_config_PersistentVolumeBinderControllerConfiguration","signature":"func Convert_v1alpha1_PersistentVolumeBinderControllerConfiguration_To_config_PersistentVolumeBinderControllerConfiguration(in *v1alpha1.PersistentVolumeBinderControllerConfiguration, out *config.PersistentVolumeBinderControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/volume/persistentvolume/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_PersistentVolumeBinderControllerConfiguration_To_config_PersistentVolumeBinderControllerConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_PersistentVolumeBinderControllerConfiguration_To_config_PersistentVolumeBinderControllerConfiguration(in *v1alpha1.PersistentVolumeBinderControllerConfiguration, out *config.PersistentVolumeBinderControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_PersistentVolumeBinderControllerConfiguration_To_config_PersistentVolumeBinderControllerConfiguration(in, out, s)\n}","line":{"from":32,"to":35}} {"id":100005011,"name":"Convert_config_PersistentVolumeBinderControllerConfiguration_To_v1alpha1_PersistentVolumeBinderControllerConfiguration","signature":"func Convert_config_PersistentVolumeBinderControllerConfiguration_To_v1alpha1_PersistentVolumeBinderControllerConfiguration(in *config.PersistentVolumeBinderControllerConfiguration, out *v1alpha1.PersistentVolumeBinderControllerConfiguration, s conversion.Scope) error","file":"pkg/controller/volume/persistentvolume/config/v1alpha1/conversion.go","code":"// Convert_config_PersistentVolumeBinderControllerConfiguration_To_v1alpha1_PersistentVolumeBinderControllerConfiguration is an autogenerated conversion function.\nfunc Convert_config_PersistentVolumeBinderControllerConfiguration_To_v1alpha1_PersistentVolumeBinderControllerConfiguration(in *config.PersistentVolumeBinderControllerConfiguration, out *v1alpha1.PersistentVolumeBinderControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_PersistentVolumeBinderControllerConfiguration_To_v1alpha1_PersistentVolumeBinderControllerConfiguration(in, out, s)\n}","line":{"from":37,"to":40}} {"id":100005012,"name":"RecommendedDefaultPersistentVolumeBinderControllerConfiguration","signature":"func RecommendedDefaultPersistentVolumeBinderControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.PersistentVolumeBinderControllerConfiguration)","file":"pkg/controller/volume/persistentvolume/config/v1alpha1/defaults.go","code":"// RecommendedDefaultPersistentVolumeBinderControllerConfiguration defaults a pointer to a\n// PersistentVolumeBinderControllerConfiguration struct. This will set the recommended default\n// values, but they may be subject to change between API versions. This function\n// is intentionally not registered in the scheme as a \"normal\" `SetDefaults_Foo`\n// function to allow consumers of this type to set whatever defaults for their\n// embedded configs. Forcing consumers to use these defaults would be problematic\n// as defaulting in the scheme is done as part of the conversion, and there would\n// be no easy way to opt-out. Instead, if you want to use this defaulting method\n// run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDefaultPersistentVolumeBinderControllerConfiguration(obj *kubectrlmgrconfigv1alpha1.PersistentVolumeBinderControllerConfiguration) {\n\tzero := metav1.Duration{}\n\tif obj.PVClaimBinderSyncPeriod == zero {\n\t\tobj.PVClaimBinderSyncPeriod = metav1.Duration{Duration: 15 * time.Second}\n\t}\n\n\tif obj.VolumeHostAllowLocalLoopback == nil {\n\t\ttrueValue := true\n\t\tobj.VolumeHostAllowLocalLoopback = \u0026trueValue\n\t}\n\n\t// Use the default VolumeConfiguration options.\n\tRecommendedDefaultVolumeConfiguration(\u0026obj.VolumeConfiguration)\n}","line":{"from":27,"to":49}} {"id":100005013,"name":"RecommendedDefaultVolumeConfiguration","signature":"func RecommendedDefaultVolumeConfiguration(obj *kubectrlmgrconfigv1alpha1.VolumeConfiguration)","file":"pkg/controller/volume/persistentvolume/config/v1alpha1/defaults.go","code":"// RecommendedDefaultVolumeConfiguration defaults a pointer to a VolumeConfiguration\n// struct. This will set the recommended default values, but they may be subject to\n// change between API versions. This function is intentionally not registered in the\n// scheme as a \"normal\" `SetDefaults_Foo` function to allow consumers of this type to\n// set whatever defaults for their embedded configs. Forcing consumers to use these\n// defaults would be problematic as defaulting in the scheme is done as part of the\n// conversion, and there would be no easy way to opt-out. Instead, if you want to use\n// this defaulting method run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDefaultVolumeConfiguration(obj *kubectrlmgrconfigv1alpha1.VolumeConfiguration) {\n\tif obj.EnableHostPathProvisioning == nil {\n\t\tobj.EnableHostPathProvisioning = pointer.Bool(false)\n\t}\n\tif obj.EnableDynamicProvisioning == nil {\n\t\tobj.EnableDynamicProvisioning = pointer.Bool(true)\n\t}\n\tif obj.FlexVolumePluginDir == \"\" {\n\t\tobj.FlexVolumePluginDir = \"/usr/libexec/kubernetes/kubelet-plugins/volume/exec/\"\n\t}\n\t// Use the default PersistentVolumeRecyclerConfiguration options.\n\tRecommendedDefaultPersistentVolumeRecyclerConfiguration(\u0026obj.PersistentVolumeRecyclerConfiguration)\n}","line":{"from":51,"to":71}} {"id":100005014,"name":"RecommendedDefaultPersistentVolumeRecyclerConfiguration","signature":"func RecommendedDefaultPersistentVolumeRecyclerConfiguration(obj *kubectrlmgrconfigv1alpha1.PersistentVolumeRecyclerConfiguration)","file":"pkg/controller/volume/persistentvolume/config/v1alpha1/defaults.go","code":"// RecommendedDefaultPersistentVolumeRecyclerConfiguration defaults a pointer to a\n// PersistentVolumeRecyclerConfiguration struct. This will set the recommended default\n// values, but they may be subject to change between API versions. This function\n// is intentionally not registered in the scheme as a \"normal\" `SetDefaults_Foo`\n// function to allow consumers of this type to set whatever defaults for their\n// embedded configs. Forcing consumers to use these defaults would be problematic\n// as defaulting in the scheme is done as part of the conversion, and there would\n// be no easy way to opt-out. Instead, if you want to use this defaulting method\n// run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDefaultPersistentVolumeRecyclerConfiguration(obj *kubectrlmgrconfigv1alpha1.PersistentVolumeRecyclerConfiguration) {\n\tif obj.MaximumRetry == 0 {\n\t\tobj.MaximumRetry = 3\n\t}\n\tif obj.MinimumTimeoutNFS == 0 {\n\t\tobj.MinimumTimeoutNFS = 300\n\t}\n\tif obj.IncrementTimeoutNFS == 0 {\n\t\tobj.IncrementTimeoutNFS = 30\n\t}\n\tif obj.MinimumTimeoutHostPath == 0 {\n\t\tobj.MinimumTimeoutHostPath = 60\n\t}\n\tif obj.IncrementTimeoutHostPath == 0 {\n\t\tobj.IncrementTimeoutHostPath = 30\n\t}\n}","line":{"from":73,"to":98}} {"id":100005015,"name":"newPersistentVolumeOrderedIndex","signature":"func newPersistentVolumeOrderedIndex() persistentVolumeOrderedIndex","file":"pkg/controller/volume/persistentvolume/index.go","code":"func newPersistentVolumeOrderedIndex() persistentVolumeOrderedIndex {\n\treturn persistentVolumeOrderedIndex{cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{\"accessmodes\": accessModesIndexFunc})}\n}","line":{"from":36,"to":38}} {"id":100005016,"name":"accessModesIndexFunc","signature":"func accessModesIndexFunc(obj interface{}) ([]string, error)","file":"pkg/controller/volume/persistentvolume/index.go","code":"// accessModesIndexFunc is an indexing function that returns a persistent\n// volume's AccessModes as a string\nfunc accessModesIndexFunc(obj interface{}) ([]string, error) {\n\tif pv, ok := obj.(*v1.PersistentVolume); ok {\n\t\tmodes := v1helper.GetAccessModesAsString(pv.Spec.AccessModes)\n\t\treturn []string{modes}, nil\n\t}\n\treturn []string{\"\"}, fmt.Errorf(\"object is not a persistent volume: %v\", obj)\n}","line":{"from":40,"to":48}} {"id":100005017,"name":"listByAccessModes","signature":"func (pvIndex *persistentVolumeOrderedIndex) listByAccessModes(modes []v1.PersistentVolumeAccessMode) ([]*v1.PersistentVolume, error)","file":"pkg/controller/volume/persistentvolume/index.go","code":"// listByAccessModes returns all volumes with the given set of\n// AccessModeTypes. The list is unsorted!\nfunc (pvIndex *persistentVolumeOrderedIndex) listByAccessModes(modes []v1.PersistentVolumeAccessMode) ([]*v1.PersistentVolume, error) {\n\tpv := \u0026v1.PersistentVolume{\n\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\tAccessModes: modes,\n\t\t},\n\t}\n\n\tobjs, err := pvIndex.store.Index(\"accessmodes\", pv)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvolumes := make([]*v1.PersistentVolume, len(objs))\n\tfor i, obj := range objs {\n\t\tvolumes[i] = obj.(*v1.PersistentVolume)\n\t}\n\n\treturn volumes, nil\n}","line":{"from":50,"to":70}} {"id":100005018,"name":"findByClaim","signature":"func (pvIndex *persistentVolumeOrderedIndex) findByClaim(claim *v1.PersistentVolumeClaim, delayBinding bool) (*v1.PersistentVolume, error)","file":"pkg/controller/volume/persistentvolume/index.go","code":"// find returns the nearest PV from the ordered list or nil if a match is not found\nfunc (pvIndex *persistentVolumeOrderedIndex) findByClaim(claim *v1.PersistentVolumeClaim, delayBinding bool) (*v1.PersistentVolume, error) {\n\t// PVs are indexed by their access modes to allow easier searching. Each\n\t// index is the string representation of a set of access modes. There is a\n\t// finite number of possible sets and PVs will only be indexed in one of\n\t// them (whichever index matches the PV's modes).\n\t//\n\t// A request for resources will always specify its desired access modes.\n\t// Any matching PV must have at least that number of access modes, but it\n\t// can have more. For example, a user asks for ReadWriteOnce but a GCEPD\n\t// is available, which is ReadWriteOnce+ReadOnlyMany.\n\t//\n\t// Searches are performed against a set of access modes, so we can attempt\n\t// not only the exact matching modes but also potential matches (the GCEPD\n\t// example above).\n\tallPossibleModes := pvIndex.allPossibleMatchingAccessModes(claim.Spec.AccessModes)\n\n\tfor _, modes := range allPossibleModes {\n\t\tvolumes, err := pvIndex.listByAccessModes(modes)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tbestVol, err := volume.FindMatchingVolume(claim, volumes, nil /* node for topology binding*/, nil /* exclusion map */, delayBinding)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif bestVol != nil {\n\t\t\treturn bestVol, nil\n\t\t}\n\t}\n\treturn nil, nil\n}","line":{"from":72,"to":105}} {"id":100005019,"name":"findBestMatchForClaim","signature":"func (pvIndex *persistentVolumeOrderedIndex) findBestMatchForClaim(claim *v1.PersistentVolumeClaim, delayBinding bool) (*v1.PersistentVolume, error)","file":"pkg/controller/volume/persistentvolume/index.go","code":"// findBestMatchForClaim is a convenience method that finds a volume by the claim's AccessModes and requests for Storage\nfunc (pvIndex *persistentVolumeOrderedIndex) findBestMatchForClaim(claim *v1.PersistentVolumeClaim, delayBinding bool) (*v1.PersistentVolume, error) {\n\treturn pvIndex.findByClaim(claim, delayBinding)\n}","line":{"from":107,"to":110}} {"id":100005020,"name":"allPossibleMatchingAccessModes","signature":"func (pvIndex *persistentVolumeOrderedIndex) allPossibleMatchingAccessModes(requestedModes []v1.PersistentVolumeAccessMode) [][]v1.PersistentVolumeAccessMode","file":"pkg/controller/volume/persistentvolume/index.go","code":"// allPossibleMatchingAccessModes returns an array of AccessMode arrays that\n// can satisfy a user's requested modes.\n//\n// see comments in the Find func above regarding indexing.\n//\n// allPossibleMatchingAccessModes gets all stringified accessmodes from the\n// index and returns all those that contain at least all of the requested\n// mode.\n//\n// For example, assume the index contains 2 types of PVs where the stringified\n// accessmodes are:\n//\n// \"RWO,ROX\" -- some number of GCEPDs\n// \"RWO,ROX,RWX\" -- some number of NFS volumes\n//\n// A request for RWO could be satisfied by both sets of indexed volumes, so\n// allPossibleMatchingAccessModes returns:\n//\n//\t[][]v1.PersistentVolumeAccessMode {\n//\t []v1.PersistentVolumeAccessMode {\n//\t\t\t\tv1.ReadWriteOnce, v1.ReadOnlyMany,\n//\t\t\t},\n//\t []v1.PersistentVolumeAccessMode {\n//\t\t\t\tv1.ReadWriteOnce, v1.ReadOnlyMany, v1.ReadWriteMany,\n//\t\t\t},\n//\t}\n//\n// A request for RWX can be satisfied by only one set of indexed volumes, so\n// the return is:\n//\n//\t[][]v1.PersistentVolumeAccessMode {\n//\t []v1.PersistentVolumeAccessMode {\n//\t\t\t\tv1.ReadWriteOnce, v1.ReadOnlyMany, v1.ReadWriteMany,\n//\t\t\t},\n//\t}\n//\n// This func returns modes with ascending levels of modes to give the user\n// what is closest to what they actually asked for.\nfunc (pvIndex *persistentVolumeOrderedIndex) allPossibleMatchingAccessModes(requestedModes []v1.PersistentVolumeAccessMode) [][]v1.PersistentVolumeAccessMode {\n\tmatchedModes := [][]v1.PersistentVolumeAccessMode{}\n\tkeys := pvIndex.store.ListIndexFuncValues(\"accessmodes\")\n\tfor _, key := range keys {\n\t\tindexedModes := v1helper.GetAccessModesFromString(key)\n\t\tif util.ContainsAllAccessModes(indexedModes, requestedModes) {\n\t\t\tmatchedModes = append(matchedModes, indexedModes)\n\t\t}\n\t}\n\n\t// sort by the number of modes in each array with the fewest number of\n\t// modes coming first. this allows searching for volumes by the minimum\n\t// number of modes required of the possible matches.\n\tsort.Sort(byAccessModes{matchedModes})\n\treturn matchedModes\n}","line":{"from":112,"to":165}} {"id":100005021,"name":"Less","signature":"func (c byAccessModes) Less(i, j int) bool","file":"pkg/controller/volume/persistentvolume/index.go","code":"func (c byAccessModes) Less(i, j int) bool {\n\treturn len(c.modes[i]) \u003c len(c.modes[j])\n}","line":{"from":172,"to":174}} {"id":100005022,"name":"Swap","signature":"func (c byAccessModes) Swap(i, j int)","file":"pkg/controller/volume/persistentvolume/index.go","code":"func (c byAccessModes) Swap(i, j int) {\n\tc.modes[i], c.modes[j] = c.modes[j], c.modes[i]\n}","line":{"from":176,"to":178}} {"id":100005023,"name":"Len","signature":"func (c byAccessModes) Len() int","file":"pkg/controller/volume/persistentvolume/index.go","code":"func (c byAccessModes) Len() int {\n\treturn len(c.modes)\n}","line":{"from":180,"to":182}} {"id":100005024,"name":"claimToClaimKey","signature":"func claimToClaimKey(claim *v1.PersistentVolumeClaim) string","file":"pkg/controller/volume/persistentvolume/index.go","code":"func claimToClaimKey(claim *v1.PersistentVolumeClaim) string {\n\treturn fmt.Sprintf(\"%s/%s\", claim.Namespace, claim.Name)\n}","line":{"from":184,"to":186}} {"id":100005025,"name":"claimrefToClaimKey","signature":"func claimrefToClaimKey(claimref *v1.ObjectReference) string","file":"pkg/controller/volume/persistentvolume/index.go","code":"func claimrefToClaimKey(claimref *v1.ObjectReference) string {\n\treturn fmt.Sprintf(\"%s/%s\", claimref.Namespace, claimref.Name)\n}","line":{"from":188,"to":190}} {"id":100005026,"name":"Register","signature":"func Register(pvLister PVLister, pvcLister PVCLister, pluginMgr *volume.VolumePluginMgr)","file":"pkg/controller/volume/persistentvolume/metrics/metrics.go","code":"// Register all metrics for pv controller.\nfunc Register(pvLister PVLister, pvcLister PVCLister, pluginMgr *volume.VolumePluginMgr) {\n\tregisterMetrics.Do(func() {\n\t\tlegacyregistry.CustomMustRegister(newPVAndPVCCountCollector(pvLister, pvcLister, pluginMgr))\n\t\tlegacyregistry.MustRegister(volumeOperationErrorsMetric)\n\t\tlegacyregistry.MustRegister(retroactiveStorageClassMetric)\n\t\tlegacyregistry.MustRegister(retroactiveStorageClassErrorMetric)\n\t})\n}","line":{"from":63,"to":71}} {"id":100005027,"name":"newPVAndPVCCountCollector","signature":"func newPVAndPVCCountCollector(pvLister PVLister, pvcLister PVCLister, pluginMgr *volume.VolumePluginMgr) *pvAndPVCCountCollector","file":"pkg/controller/volume/persistentvolume/metrics/metrics.go","code":"func newPVAndPVCCountCollector(pvLister PVLister, pvcLister PVCLister, pluginMgr *volume.VolumePluginMgr) *pvAndPVCCountCollector {\n\treturn \u0026pvAndPVCCountCollector{pvLister: pvLister, pvcLister: pvcLister, pluginMgr: pluginMgr}\n}","line":{"from":73,"to":75}} {"id":100005028,"name":"add","signature":"func (v volumeCount) add(pluginName string, volumeMode string)","file":"pkg/controller/volume/persistentvolume/metrics/metrics.go","code":"func (v volumeCount) add(pluginName string, volumeMode string) {\n\tcount, ok := v[pluginName]\n\tif !ok {\n\t\tcount = map[string]int{}\n\t}\n\tcount[volumeMode]++\n\tv[pluginName] = count\n}","line":{"from":146,"to":153}} {"id":100005029,"name":"DescribeWithStability","signature":"func (collector *pvAndPVCCountCollector) DescribeWithStability(ch chan\u003c- *metrics.Desc)","file":"pkg/controller/volume/persistentvolume/metrics/metrics.go","code":"func (collector *pvAndPVCCountCollector) DescribeWithStability(ch chan\u003c- *metrics.Desc) {\n\tch \u003c- totalPVCountDesc\n\tch \u003c- boundPVCountDesc\n\tch \u003c- unboundPVCountDesc\n\tch \u003c- boundPVCCountDesc\n\tch \u003c- unboundPVCCountDesc\n}","line":{"from":155,"to":161}} {"id":100005030,"name":"CollectWithStability","signature":"func (collector *pvAndPVCCountCollector) CollectWithStability(ch chan\u003c- metrics.Metric)","file":"pkg/controller/volume/persistentvolume/metrics/metrics.go","code":"func (collector *pvAndPVCCountCollector) CollectWithStability(ch chan\u003c- metrics.Metric) {\n\tcollector.pvCollect(ch)\n\tcollector.pvcCollect(ch)\n}","line":{"from":163,"to":166}} {"id":100005031,"name":"getPVPluginName","signature":"func (collector *pvAndPVCCountCollector) getPVPluginName(pv *v1.PersistentVolume) string","file":"pkg/controller/volume/persistentvolume/metrics/metrics.go","code":"func (collector *pvAndPVCCountCollector) getPVPluginName(pv *v1.PersistentVolume) string {\n\tspec := volume.NewSpecFromPersistentVolume(pv, true)\n\tfullPluginName := pluginNameNotAvailable\n\tif plugin, err := collector.pluginMgr.FindPluginBySpec(spec); err == nil {\n\t\tfullPluginName = metricutil.GetFullQualifiedPluginNameForVolume(plugin.GetPluginName(), spec)\n\t}\n\treturn fullPluginName\n}","line":{"from":168,"to":175}} {"id":100005032,"name":"pvCollect","signature":"func (collector *pvAndPVCCountCollector) pvCollect(ch chan\u003c- metrics.Metric)","file":"pkg/controller/volume/persistentvolume/metrics/metrics.go","code":"func (collector *pvAndPVCCountCollector) pvCollect(ch chan\u003c- metrics.Metric) {\n\tboundNumberByStorageClass := make(map[string]int)\n\tunboundNumberByStorageClass := make(map[string]int)\n\ttotalCount := make(volumeCount)\n\tfor _, pvObj := range collector.pvLister.List() {\n\t\tpv, ok := pvObj.(*v1.PersistentVolume)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tpluginName := collector.getPVPluginName(pv)\n\t\ttotalCount.add(pluginName, string(*pv.Spec.VolumeMode))\n\t\tif pv.Status.Phase == v1.VolumeBound {\n\t\t\tboundNumberByStorageClass[pv.Spec.StorageClassName]++\n\t\t} else {\n\t\t\tunboundNumberByStorageClass[pv.Spec.StorageClassName]++\n\t\t}\n\t}\n\tfor storageClassName, number := range boundNumberByStorageClass {\n\t\tch \u003c- metrics.NewLazyConstMetric(\n\t\t\tboundPVCountDesc,\n\t\t\tmetrics.GaugeValue,\n\t\t\tfloat64(number),\n\t\t\tstorageClassName)\n\t}\n\tfor storageClassName, number := range unboundNumberByStorageClass {\n\t\tch \u003c- metrics.NewLazyConstMetric(\n\t\t\tunboundPVCountDesc,\n\t\t\tmetrics.GaugeValue,\n\t\t\tfloat64(number),\n\t\t\tstorageClassName)\n\t}\n\tfor pluginName, volumeModeCount := range totalCount {\n\t\tfor volumeMode, number := range volumeModeCount {\n\t\t\tch \u003c- metrics.NewLazyConstMetric(\n\t\t\t\ttotalPVCountDesc,\n\t\t\t\tmetrics.GaugeValue,\n\t\t\t\tfloat64(number),\n\t\t\t\tpluginName,\n\t\t\t\tvolumeMode)\n\t\t}\n\t}\n}","line":{"from":177,"to":218}} {"id":100005033,"name":"pvcCollect","signature":"func (collector *pvAndPVCCountCollector) pvcCollect(ch chan\u003c- metrics.Metric)","file":"pkg/controller/volume/persistentvolume/metrics/metrics.go","code":"func (collector *pvAndPVCCountCollector) pvcCollect(ch chan\u003c- metrics.Metric) {\n\tboundNumberByNamespace := make(map[string]int)\n\tunboundNumberByNamespace := make(map[string]int)\n\tfor _, pvcObj := range collector.pvcLister.List() {\n\t\tpvc, ok := pvcObj.(*v1.PersistentVolumeClaim)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tif pvc.Status.Phase == v1.ClaimBound {\n\t\t\tboundNumberByNamespace[pvc.Namespace]++\n\t\t} else {\n\t\t\tunboundNumberByNamespace[pvc.Namespace]++\n\t\t}\n\t}\n\tfor namespace, number := range boundNumberByNamespace {\n\t\tch \u003c- metrics.NewLazyConstMetric(\n\t\t\tboundPVCCountDesc,\n\t\t\tmetrics.GaugeValue,\n\t\t\tfloat64(number),\n\t\t\tnamespace)\n\t}\n\tfor namespace, number := range unboundNumberByNamespace {\n\t\tch \u003c- metrics.NewLazyConstMetric(\n\t\t\tunboundPVCCountDesc,\n\t\t\tmetrics.GaugeValue,\n\t\t\tfloat64(number),\n\t\t\tnamespace)\n\t}\n}","line":{"from":220,"to":248}} {"id":100005034,"name":"RecordRetroactiveStorageClassMetric","signature":"func RecordRetroactiveStorageClassMetric(success bool)","file":"pkg/controller/volume/persistentvolume/metrics/metrics.go","code":"// RecordRetroactiveStorageClassMetric increments only retroactive_storageclass_total\n// metric or both retroactive_storageclass_total and retroactive_storageclass_errors_total\n// if success is false.\nfunc RecordRetroactiveStorageClassMetric(success bool) {\n\tif !success {\n\t\tretroactiveStorageClassMetric.Inc()\n\t\tretroactiveStorageClassErrorMetric.Inc()\n\t} else {\n\t\tretroactiveStorageClassMetric.Inc()\n\t}\n}","line":{"from":250,"to":260}} {"id":100005035,"name":"RecordVolumeOperationErrorMetric","signature":"func RecordVolumeOperationErrorMetric(pluginName, opName string)","file":"pkg/controller/volume/persistentvolume/metrics/metrics.go","code":"// RecordVolumeOperationErrorMetric records error count into metric\n// volume_operation_total_errors for provisioning/deletion operations\nfunc RecordVolumeOperationErrorMetric(pluginName, opName string) {\n\tif pluginName == \"\" {\n\t\tpluginName = \"N/A\"\n\t}\n\tvolumeOperationErrorsMetric.WithLabelValues(pluginName, opName).Inc()\n}","line":{"from":262,"to":269}} {"id":100005036,"name":"newOperationTimestamp","signature":"func newOperationTimestamp(pluginName, operationName string) *operationTimestamp","file":"pkg/controller/volume/persistentvolume/metrics/metrics.go","code":"func newOperationTimestamp(pluginName, operationName string) *operationTimestamp {\n\treturn \u0026operationTimestamp{\n\t\tpluginName: pluginName,\n\t\toperation: operationName,\n\t\tstartTs: time.Now(),\n\t}\n}","line":{"from":278,"to":284}} {"id":100005037,"name":"NewOperationStartTimeCache","signature":"func NewOperationStartTimeCache() OperationStartTimeCache","file":"pkg/controller/volume/persistentvolume/metrics/metrics.go","code":"// NewOperationStartTimeCache creates a operation timestamp cache\nfunc NewOperationStartTimeCache() OperationStartTimeCache {\n\treturn OperationStartTimeCache{\n\t\tcache: sync.Map{}, // [string]operationTimestamp {}\n\t}\n}","line":{"from":291,"to":296}} {"id":100005038,"name":"AddIfNotExist","signature":"func (c *OperationStartTimeCache) AddIfNotExist(key, pluginName, operationName string)","file":"pkg/controller/volume/persistentvolume/metrics/metrics.go","code":"// AddIfNotExist returns directly if there exists an entry with the key. Otherwise, it\n// creates a new operation timestamp using operationName, pluginName, and current timestamp\n// and stores the operation timestamp with the key\nfunc (c *OperationStartTimeCache) AddIfNotExist(key, pluginName, operationName string) {\n\tts := newOperationTimestamp(pluginName, operationName)\n\tc.cache.LoadOrStore(key, ts)\n}","line":{"from":298,"to":304}} {"id":100005039,"name":"Delete","signature":"func (c *OperationStartTimeCache) Delete(key string)","file":"pkg/controller/volume/persistentvolume/metrics/metrics.go","code":"// Delete deletes a value for a key.\nfunc (c *OperationStartTimeCache) Delete(key string) {\n\tc.cache.Delete(key)\n}","line":{"from":306,"to":309}} {"id":100005040,"name":"Has","signature":"func (c *OperationStartTimeCache) Has(key string) bool","file":"pkg/controller/volume/persistentvolume/metrics/metrics.go","code":"// Has returns a bool value indicates the existence of a key in the cache\nfunc (c *OperationStartTimeCache) Has(key string) bool {\n\t_, exists := c.cache.Load(key)\n\treturn exists\n}","line":{"from":311,"to":315}} {"id":100005041,"name":"RecordMetric","signature":"func RecordMetric(key string, c *OperationStartTimeCache, err error)","file":"pkg/controller/volume/persistentvolume/metrics/metrics.go","code":"// RecordMetric records either an error count metric or a latency metric if there\n// exists a start timestamp entry in the cache. For a successful operation, i.e.,\n// err == nil, the corresponding timestamp entry will be removed from cache\nfunc RecordMetric(key string, c *OperationStartTimeCache, err error) {\n\tobj, exists := c.cache.Load(key)\n\tif !exists {\n\t\treturn\n\t}\n\tts, ok := obj.(*operationTimestamp)\n\tif !ok {\n\t\treturn\n\t}\n\tif err != nil {\n\t\tRecordVolumeOperationErrorMetric(ts.pluginName, ts.operation)\n\t} else {\n\t\ttimeTaken := time.Since(ts.startTs).Seconds()\n\t\tmetricutil.RecordOperationLatencyMetric(ts.pluginName, ts.operation, timeTaken)\n\t\t// end of this operation, remove the timestamp entry from cache\n\t\tc.Delete(key)\n\t}\n}","line":{"from":317,"to":337}} {"id":100005042,"name":"NewPersistentVolumeControllerOptions","signature":"func NewPersistentVolumeControllerOptions() PersistentVolumeControllerOptions","file":"pkg/controller/volume/persistentvolume/options/options.go","code":"// NewPersistentVolumeControllerOptions creates a new PersistentVolumeControllerOptions with\n// default values.\nfunc NewPersistentVolumeControllerOptions() PersistentVolumeControllerOptions {\n\treturn PersistentVolumeControllerOptions{\n\t\tPVClaimBinderSyncPeriod: 15 * time.Second,\n\t\tVolumeConfigFlags: VolumeConfigFlags{\n\t\t\t// default values here\n\t\t\tPersistentVolumeRecyclerMaximumRetry: 3,\n\t\t\tPersistentVolumeRecyclerMinimumTimeoutNFS: 300,\n\t\t\tPersistentVolumeRecyclerIncrementTimeoutNFS: 30,\n\t\t\tPersistentVolumeRecyclerMinimumTimeoutHostPath: 60,\n\t\t\tPersistentVolumeRecyclerIncrementTimeoutHostPath: 30,\n\t\t\tEnableHostPathProvisioning: false,\n\t\t\tEnableDynamicProvisioning: true,\n\t\t},\n\t}\n}","line":{"from":47,"to":63}} {"id":100005043,"name":"AddFlags","signature":"func (o *PersistentVolumeControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"pkg/controller/volume/persistentvolume/options/options.go","code":"// AddFlags adds flags related to PersistentVolumeControllerOptions to the specified FlagSet.\nfunc (o *PersistentVolumeControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tfs.DurationVar(\u0026o.PVClaimBinderSyncPeriod, \"pvclaimbinder-sync-period\", o.PVClaimBinderSyncPeriod,\n\t\t\"The period for syncing persistent volumes and persistent volume claims\")\n\tfs.StringVar(\u0026o.VolumeConfigFlags.PersistentVolumeRecyclerPodTemplateFilePathNFS,\n\t\t\"pv-recycler-pod-template-filepath-nfs\", o.VolumeConfigFlags.PersistentVolumeRecyclerPodTemplateFilePathNFS,\n\t\t\"The file path to a pod definition used as a template for NFS persistent volume recycling\")\n\tfs.IntVar(\u0026o.VolumeConfigFlags.PersistentVolumeRecyclerMinimumTimeoutNFS, \"pv-recycler-minimum-timeout-nfs\",\n\t\to.VolumeConfigFlags.PersistentVolumeRecyclerMinimumTimeoutNFS, \"The minimum ActiveDeadlineSeconds to use for an NFS Recycler pod\")\n\tfs.IntVar(\u0026o.VolumeConfigFlags.PersistentVolumeRecyclerIncrementTimeoutNFS, \"pv-recycler-increment-timeout-nfs\",\n\t\to.VolumeConfigFlags.PersistentVolumeRecyclerIncrementTimeoutNFS, \"the increment of time added per Gi to ActiveDeadlineSeconds for an NFS scrubber pod\")\n\tfs.StringVar(\u0026o.VolumeConfigFlags.PersistentVolumeRecyclerPodTemplateFilePathHostPath, \"pv-recycler-pod-template-filepath-hostpath\",\n\t\to.VolumeConfigFlags.PersistentVolumeRecyclerPodTemplateFilePathHostPath,\n\t\t\"The file path to a pod definition used as a template for HostPath persistent volume recycling. \"+\n\t\t\t\"This is for development and testing only and will not work in a multi-node cluster.\")\n\tfs.IntVar(\u0026o.VolumeConfigFlags.PersistentVolumeRecyclerMinimumTimeoutHostPath, \"pv-recycler-minimum-timeout-hostpath\",\n\t\to.VolumeConfigFlags.PersistentVolumeRecyclerMinimumTimeoutHostPath,\n\t\t\"The minimum ActiveDeadlineSeconds to use for a HostPath Recycler pod. This is for development and testing only and will not work in a multi-node cluster.\")\n\tfs.IntVar(\u0026o.VolumeConfigFlags.PersistentVolumeRecyclerIncrementTimeoutHostPath, \"pv-recycler-timeout-increment-hostpath\",\n\t\to.VolumeConfigFlags.PersistentVolumeRecyclerIncrementTimeoutHostPath,\n\t\t\"the increment of time added per Gi to ActiveDeadlineSeconds for a HostPath scrubber pod. \"+\n\t\t\t\"This is for development and testing only and will not work in a multi-node cluster.\")\n\tfs.IntVar(\u0026o.VolumeConfigFlags.PersistentVolumeRecyclerMaximumRetry, \"pv-recycler-maximum-retry\",\n\t\to.VolumeConfigFlags.PersistentVolumeRecyclerMaximumRetry,\n\t\t\"Maximum number of attempts to recycle or delete a persistent volume\")\n\tfs.BoolVar(\u0026o.VolumeConfigFlags.EnableHostPathProvisioning, \"enable-hostpath-provisioner\", o.VolumeConfigFlags.EnableHostPathProvisioning,\n\t\t\"Enable HostPath PV provisioning when running without a cloud provider. This allows testing and development of provisioning features. \"+\n\t\t\t\"HostPath provisioning is not supported in any way, won't work in a multi-node cluster, and should not be used for anything other than testing or development.\")\n\tfs.BoolVar(\u0026o.VolumeConfigFlags.EnableDynamicProvisioning, \"enable-dynamic-provisioning\", o.VolumeConfigFlags.EnableDynamicProvisioning,\n\t\t\"Enable dynamic provisioning for environments that support it.\")\n}","line":{"from":65,"to":95}} {"id":100005044,"name":"syncClaim","signature":"func (ctrl *PersistentVolumeController) syncClaim(ctx context.Context, claim *v1.PersistentVolumeClaim) error","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// syncClaim is the main controller method to decide what to do with a claim.\n// It's invoked by appropriate cache.Controller callbacks when a claim is\n// created, updated or periodically synced. We do not differentiate between\n// these events.\n// For easier readability, it was split into syncUnboundClaim and syncBoundClaim\n// methods.\nfunc (ctrl *PersistentVolumeController) syncClaim(ctx context.Context, claim *v1.PersistentVolumeClaim) error {\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"Synchronizing PersistentVolumeClaim\", \"PVC\", klog.KObj(claim), \"claimStatus\", getClaimStatusForLogging(claim))\n\n\t// Set correct \"migrated-to\" annotations on PVC and update in API server if\n\t// necessary\n\tnewClaim, err := ctrl.updateClaimMigrationAnnotations(ctx, claim)\n\tif err != nil {\n\t\t// Nothing was saved; we will fall back into the same\n\t\t// condition in the next call to this method\n\t\treturn err\n\t}\n\tclaim = newClaim\n\n\tif !metav1.HasAnnotation(claim.ObjectMeta, storagehelpers.AnnBindCompleted) {\n\t\treturn ctrl.syncUnboundClaim(ctx, claim)\n\t} else {\n\t\treturn ctrl.syncBoundClaim(ctx, claim)\n\t}\n}","line":{"from":248,"to":273}} {"id":100005045,"name":"checkVolumeSatisfyClaim","signature":"func checkVolumeSatisfyClaim(volume *v1.PersistentVolume, claim *v1.PersistentVolumeClaim) error","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// checkVolumeSatisfyClaim checks if the volume requested by the claim satisfies the requirements of the claim\nfunc checkVolumeSatisfyClaim(volume *v1.PersistentVolume, claim *v1.PersistentVolumeClaim) error {\n\trequestedQty := claim.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]\n\trequestedSize := requestedQty.Value()\n\n\t// check if PV's DeletionTimeStamp is set, if so, return error.\n\tif volume.ObjectMeta.DeletionTimestamp != nil {\n\t\treturn fmt.Errorf(\"the volume is marked for deletion %q\", volume.Name)\n\t}\n\n\tvolumeQty := volume.Spec.Capacity[v1.ResourceStorage]\n\tvolumeSize := volumeQty.Value()\n\tif volumeSize \u003c requestedSize {\n\t\treturn fmt.Errorf(\"requested PV is too small\")\n\t}\n\n\trequestedClass := storagehelpers.GetPersistentVolumeClaimClass(claim)\n\tif storagehelpers.GetPersistentVolumeClass(volume) != requestedClass {\n\t\treturn fmt.Errorf(\"storageClassName does not match\")\n\t}\n\n\tif storagehelpers.CheckVolumeModeMismatches(\u0026claim.Spec, \u0026volume.Spec) {\n\t\treturn fmt.Errorf(\"incompatible volumeMode\")\n\t}\n\n\tif !storagehelpers.CheckAccessModes(claim, volume) {\n\t\treturn fmt.Errorf(\"incompatible accessMode\")\n\t}\n\n\treturn nil\n}","line":{"from":275,"to":305}} {"id":100005046,"name":"emitEventForUnboundDelayBindingClaim","signature":"func (ctrl *PersistentVolumeController) emitEventForUnboundDelayBindingClaim(claim *v1.PersistentVolumeClaim) error","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// emitEventForUnboundDelayBindingClaim generates informative event for claim\n// if it's in delay binding mode and not bound yet.\nfunc (ctrl *PersistentVolumeController) emitEventForUnboundDelayBindingClaim(claim *v1.PersistentVolumeClaim) error {\n\treason := events.WaitForFirstConsumer\n\tmessage := \"waiting for first consumer to be created before binding\"\n\tpodNames, err := ctrl.findNonScheduledPodsByPVC(claim)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(podNames) \u003e 0 {\n\t\treason = events.WaitForPodScheduled\n\t\tif len(podNames) \u003e 1 {\n\t\t\t// Although only one pod is taken into account in\n\t\t\t// volume scheduling, more than one pods can reference\n\t\t\t// the PVC at the same time. We can't know which pod is\n\t\t\t// used in scheduling, all pods are included.\n\t\t\tmessage = fmt.Sprintf(\"waiting for pods %s to be scheduled\", strings.Join(podNames, \",\"))\n\t\t} else {\n\t\t\tmessage = fmt.Sprintf(\"waiting for pod %s to be scheduled\", podNames[0])\n\t\t}\n\t}\n\tctrl.eventRecorder.Event(claim, v1.EventTypeNormal, reason, message)\n\treturn nil\n}","line":{"from":307,"to":330}} {"id":100005047,"name":"syncUnboundClaim","signature":"func (ctrl *PersistentVolumeController) syncUnboundClaim(ctx context.Context, claim *v1.PersistentVolumeClaim) error","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// syncUnboundClaim is the main controller method to decide what to do with an\n// unbound claim.\nfunc (ctrl *PersistentVolumeController) syncUnboundClaim(ctx context.Context, claim *v1.PersistentVolumeClaim) error {\n\t// This is a new PVC that has not completed binding\n\t// OBSERVATION: pvc is \"Pending\"\n\tlogger := klog.FromContext(ctx)\n\tif claim.Spec.VolumeName == \"\" {\n\t\t// User did not care which PV they get.\n\t\tdelayBinding, err := storagehelpers.IsDelayBindingMode(claim, ctrl.classLister)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// [Unit test set 1]\n\t\tvolume, err := ctrl.volumes.findBestMatchForClaim(claim, delayBinding)\n\t\tif err != nil {\n\t\t\tlogger.V(2).Info(\"Synchronizing unbound PersistentVolumeClaim, Error finding PV for claim\", \"PVC\", klog.KObj(claim), \"err\", err)\n\t\t\treturn fmt.Errorf(\"error finding PV for claim %q: %w\", claimToClaimKey(claim), err)\n\t\t}\n\t\tif volume == nil {\n\t\t\tlogger.V(4).Info(\"Synchronizing unbound PersistentVolumeClaim, no volume found\", \"PVC\", klog.KObj(claim))\n\t\t\t// No PV could be found\n\t\t\t// OBSERVATION: pvc is \"Pending\", will retry\n\n\t\t\tif utilfeature.DefaultFeatureGate.Enabled(features.RetroactiveDefaultStorageClass) {\n\t\t\t\tlogger.V(4).Info(\"FeatureGate is enabled, attempting to assign storage class to unbound PersistentVolumeClaim\", \"featureGate\", features.RetroactiveDefaultStorageClass, \"PVC\", klog.KObj(claim))\n\t\t\t\tupdated, err := ctrl.assignDefaultStorageClass(ctx, claim)\n\t\t\t\tif err != nil {\n\t\t\t\t\tmetrics.RecordRetroactiveStorageClassMetric(false)\n\t\t\t\t\treturn fmt.Errorf(\"can't update PersistentVolumeClaim[%q]: %w\", claimToClaimKey(claim), err)\n\t\t\t\t}\n\t\t\t\tif updated {\n\t\t\t\t\tlogger.V(4).Info(\"PersistentVolumeClaim update successful, restarting claim sync\", \"PVC\", klog.KObj(claim))\n\t\t\t\t\tmetrics.RecordRetroactiveStorageClassMetric(true)\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tswitch {\n\t\t\tcase delayBinding \u0026\u0026 !storagehelpers.IsDelayBindingProvisioning(claim):\n\t\t\t\tif err = ctrl.emitEventForUnboundDelayBindingClaim(claim); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\tcase storagehelpers.GetPersistentVolumeClaimClass(claim) != \"\":\n\t\t\t\tif err = ctrl.provisionClaim(ctx, claim); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\tdefault:\n\t\t\t\tctrl.eventRecorder.Event(claim, v1.EventTypeNormal, events.FailedBinding, \"no persistent volumes available for this claim and no storage class is set\")\n\t\t\t}\n\n\t\t\t// Mark the claim as Pending and try to find a match in the next\n\t\t\t// periodic syncClaim\n\t\t\tif _, err = ctrl.updateClaimStatus(ctx, claim, v1.ClaimPending, nil); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t} else /* pv != nil */ {\n\t\t\t// Found a PV for this claim\n\t\t\t// OBSERVATION: pvc is \"Pending\", pv is \"Available\"\n\t\t\tclaimKey := claimToClaimKey(claim)\n\t\t\tlogger.V(4).Info(\"Synchronizing unbound PersistentVolumeClaim, volume found\", \"PVC\", klog.KObj(claim), \"volumeName\", volume.Name, \"volumeStatus\", getVolumeStatusForLogging(volume))\n\t\t\tif err = ctrl.bind(ctx, volume, claim); err != nil {\n\t\t\t\t// On any error saving the volume or the claim, subsequent\n\t\t\t\t// syncClaim will finish the binding.\n\t\t\t\t// record count error for provision if exists\n\t\t\t\t// timestamp entry will remain in cache until a success binding has happened\n\t\t\t\tmetrics.RecordMetric(claimKey, \u0026ctrl.operationTimestamps, err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// OBSERVATION: claim is \"Bound\", pv is \"Bound\"\n\t\t\t// if exists a timestamp entry in cache, record end to end provision latency and clean up cache\n\t\t\t// End of the provision + binding operation lifecycle, cache will be cleaned by \"RecordMetric\"\n\t\t\t// [Unit test 12-1, 12-2, 12-4]\n\t\t\tmetrics.RecordMetric(claimKey, \u0026ctrl.operationTimestamps, nil)\n\t\t\treturn nil\n\t\t}\n\t} else /* pvc.Spec.VolumeName != nil */ {\n\t\t// [Unit test set 2]\n\t\t// User asked for a specific PV.\n\t\tlogger.V(4).Info(\"Synchronizing unbound PersistentVolumeClaim, volume requested\", \"PVC\", klog.KObj(claim), \"volumeName\", claim.Spec.VolumeName)\n\t\tobj, found, err := ctrl.volumes.store.GetByKey(claim.Spec.VolumeName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !found {\n\t\t\t// User asked for a PV that does not exist.\n\t\t\t// OBSERVATION: pvc is \"Pending\"\n\t\t\t// Retry later.\n\t\t\tlogger.V(4).Info(\"Synchronizing unbound PersistentVolumeClaim, volume requested and not found, will try again next time\", \"PVC\", klog.KObj(claim), \"volumeName\", claim.Spec.VolumeName)\n\t\t\tif _, err = ctrl.updateClaimStatus(ctx, claim, v1.ClaimPending, nil); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t} else {\n\t\t\tvolume, ok := obj.(*v1.PersistentVolume)\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"cannot convert object from volume cache to volume %q!?: %+v\", claim.Spec.VolumeName, obj)\n\t\t\t}\n\t\t\tlogger.V(4).Info(\"Synchronizing unbound PersistentVolumeClaim, volume requested and found\", \"PVC\", klog.KObj(claim), \"volumeName\", claim.Spec.VolumeName, \"volumeStatus\", getVolumeStatusForLogging(volume))\n\t\t\tif volume.Spec.ClaimRef == nil {\n\t\t\t\t// User asked for a PV that is not claimed\n\t\t\t\t// OBSERVATION: pvc is \"Pending\", pv is \"Available\"\n\t\t\t\tlogger.V(4).Info(\"Synchronizing unbound PersistentVolumeClaim, volume is unbound, binding\", \"PVC\", klog.KObj(claim))\n\t\t\t\tif err = checkVolumeSatisfyClaim(volume, claim); err != nil {\n\t\t\t\t\tlogger.V(4).Info(\"Can't bind the claim to volume\", \"volumeName\", volume.Name, \"err\", err)\n\t\t\t\t\t// send an event\n\t\t\t\t\tmsg := fmt.Sprintf(\"Cannot bind to requested volume %q: %s\", volume.Name, err)\n\t\t\t\t\tctrl.eventRecorder.Event(claim, v1.EventTypeWarning, events.VolumeMismatch, msg)\n\t\t\t\t\t// volume does not satisfy the requirements of the claim\n\t\t\t\t\tif _, err = ctrl.updateClaimStatus(ctx, claim, v1.ClaimPending, nil); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t} else if err = ctrl.bind(ctx, volume, claim); err != nil {\n\t\t\t\t\t// On any error saving the volume or the claim, subsequent\n\t\t\t\t\t// syncClaim will finish the binding.\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t// OBSERVATION: pvc is \"Bound\", pv is \"Bound\"\n\t\t\t\treturn nil\n\t\t\t} else if storagehelpers.IsVolumeBoundToClaim(volume, claim) {\n\t\t\t\t// User asked for a PV that is claimed by this PVC\n\t\t\t\t// OBSERVATION: pvc is \"Pending\", pv is \"Bound\"\n\t\t\t\tlogger.V(4).Info(\"Synchronizing unbound PersistentVolumeClaim, volume already bound, finishing the binding\", \"PVC\", klog.KObj(claim))\n\n\t\t\t\t// Finish the volume binding by adding claim UID.\n\t\t\t\tif err = ctrl.bind(ctx, volume, claim); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t// OBSERVATION: pvc is \"Bound\", pv is \"Bound\"\n\t\t\t\treturn nil\n\t\t\t} else {\n\t\t\t\t// User asked for a PV that is claimed by someone else\n\t\t\t\t// OBSERVATION: pvc is \"Pending\", pv is \"Bound\"\n\t\t\t\tif !metav1.HasAnnotation(claim.ObjectMeta, storagehelpers.AnnBoundByController) {\n\t\t\t\t\tlogger.V(4).Info(\"Synchronizing unbound PersistentVolumeClaim, volume already bound to different claim by user, will retry later\", \"PVC\", klog.KObj(claim))\n\t\t\t\t\tclaimMsg := fmt.Sprintf(\"volume %q already bound to a different claim.\", volume.Name)\n\t\t\t\t\tctrl.eventRecorder.Event(claim, v1.EventTypeWarning, events.FailedBinding, claimMsg)\n\t\t\t\t\t// User asked for a specific PV, retry later\n\t\t\t\t\tif _, err = ctrl.updateClaimStatus(ctx, claim, v1.ClaimPending, nil); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t} else {\n\t\t\t\t\t// This should never happen because someone had to remove\n\t\t\t\t\t// AnnBindCompleted annotation on the claim.\n\t\t\t\t\tlogger.V(4).Info(\"Synchronizing unbound PersistentVolumeClaim, volume already bound to different claim by controller, THIS SHOULD NEVER HAPPEN\", \"PVC\", klog.KObj(claim), \"boundClaim\", klog.KRef(volume.Spec.ClaimRef.Namespace, volume.Spec.ClaimRef.Name))\n\t\t\t\t\tclaimMsg := fmt.Sprintf(\"volume %q already bound to a different claim.\", volume.Name)\n\t\t\t\t\tctrl.eventRecorder.Event(claim, v1.EventTypeWarning, events.FailedBinding, claimMsg)\n\n\t\t\t\t\treturn fmt.Errorf(\"invalid binding of claim %q to volume %q: volume already claimed by %q\", claimToClaimKey(claim), claim.Spec.VolumeName, claimrefToClaimKey(volume.Spec.ClaimRef))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":332,"to":488}} {"id":100005048,"name":"syncBoundClaim","signature":"func (ctrl *PersistentVolumeController) syncBoundClaim(ctx context.Context, claim *v1.PersistentVolumeClaim) error","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// syncBoundClaim is the main controller method to decide what to do with a\n// bound claim.\nfunc (ctrl *PersistentVolumeController) syncBoundClaim(ctx context.Context, claim *v1.PersistentVolumeClaim) error {\n\t// HasAnnotation(pvc, storagehelpers.AnnBindCompleted)\n\t// This PVC has previously been bound\n\t// OBSERVATION: pvc is not \"Pending\"\n\t// [Unit test set 3]\n\n\tlogger := klog.FromContext(ctx)\n\n\tif claim.Spec.VolumeName == \"\" {\n\t\t// Claim was bound before but not any more.\n\t\tif _, err := ctrl.updateClaimStatusWithEvent(ctx, claim, v1.ClaimLost, nil, v1.EventTypeWarning, \"ClaimLost\", \"Bound claim has lost reference to PersistentVolume. Data on the volume is lost!\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\tobj, found, err := ctrl.volumes.store.GetByKey(claim.Spec.VolumeName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !found {\n\t\t// Claim is bound to a non-existing volume.\n\t\tif _, err = ctrl.updateClaimStatusWithEvent(ctx, claim, v1.ClaimLost, nil, v1.EventTypeWarning, \"ClaimLost\", \"Bound claim has lost its PersistentVolume. Data on the volume is lost!\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t} else {\n\t\tvolume, ok := obj.(*v1.PersistentVolume)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"cannot convert object from volume cache to volume %q!?: %#v\", claim.Spec.VolumeName, obj)\n\t\t}\n\n\t\tlogger.V(4).Info(\"Synchronizing bound PersistentVolumeClaim, volume found\", \"PVC\", klog.KObj(claim), \"volumeName\", claim.Spec.VolumeName, \"volumeStatus\", getVolumeStatusForLogging(volume))\n\t\tif volume.Spec.ClaimRef == nil {\n\t\t\t// Claim is bound but volume has come unbound.\n\t\t\t// Or, a claim was bound and the controller has not received updated\n\t\t\t// volume yet. We can't distinguish these cases.\n\t\t\t// Bind the volume again and set all states to Bound.\n\t\t\tlogger.V(4).Info(\"Synchronizing bound PersistentVolumeClaim, volume is unbound, fixing\", \"PVC\", klog.KObj(claim))\n\t\t\tif err = ctrl.bind(ctx, volume, claim); err != nil {\n\t\t\t\t// Objects not saved, next syncPV or syncClaim will try again\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t} else if volume.Spec.ClaimRef.UID == claim.UID {\n\t\t\t// All is well\n\t\t\t// NOTE: syncPV can handle this so it can be left out.\n\t\t\t// NOTE: bind() call here will do nothing in most cases as\n\t\t\t// everything should be already set.\n\t\t\tlogger.V(4).Info(\"Synchronizing bound PersistentVolumeClaim, claim is already correctly bound\", \"PVC\", klog.KObj(claim))\n\t\t\tif err = ctrl.bind(ctx, volume, claim); err != nil {\n\t\t\t\t// Objects not saved, next syncPV or syncClaim will try again\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t} else {\n\t\t\t// Claim is bound but volume has a different claimant.\n\t\t\t// Set the claim phase to 'Lost', which is a terminal\n\t\t\t// phase.\n\t\t\tif _, err = ctrl.updateClaimStatusWithEvent(ctx, claim, v1.ClaimLost, nil, v1.EventTypeWarning, \"ClaimMisbound\", \"Two claims are bound to the same volume, this one is bound incorrectly\"); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n}","line":{"from":490,"to":556}} {"id":100005049,"name":"syncVolume","signature":"func (ctrl *PersistentVolumeController) syncVolume(ctx context.Context, volume *v1.PersistentVolume) error","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// syncVolume is the main controller method to decide what to do with a volume.\n// It's invoked by appropriate cache.Controller callbacks when a volume is\n// created, updated or periodically synced. We do not differentiate between\n// these events.\nfunc (ctrl *PersistentVolumeController) syncVolume(ctx context.Context, volume *v1.PersistentVolume) error {\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"Synchronizing PersistentVolume\", \"volumeName\", volume.Name, \"volumeStatus\", getVolumeStatusForLogging(volume))\n\t// Set correct \"migrated-to\" annotations and modify finalizers on PV and update in API server if\n\t// necessary\n\tnewVolume, err := ctrl.updateVolumeMigrationAnnotationsAndFinalizers(ctx, volume)\n\tif err != nil {\n\t\t// Nothing was saved; we will fall back into the same\n\t\t// condition in the next call to this method\n\t\treturn err\n\t}\n\tvolume = newVolume\n\n\t// [Unit test set 4]\n\tif volume.Spec.ClaimRef == nil {\n\t\t// Volume is unused\n\t\tlogger.V(4).Info(\"Synchronizing PersistentVolume, volume is unused\", \"volumeName\", volume.Name)\n\t\tif _, err := ctrl.updateVolumePhase(ctx, volume, v1.VolumeAvailable, \"\"); err != nil {\n\t\t\t// Nothing was saved; we will fall back into the same\n\t\t\t// condition in the next call to this method\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t} else /* pv.Spec.ClaimRef != nil */ {\n\t\t// Volume is bound to a claim.\n\t\tif volume.Spec.ClaimRef.UID == \"\" {\n\t\t\t// The PV is reserved for a PVC; that PVC has not yet been\n\t\t\t// bound to this PV; the PVC sync will handle it.\n\t\t\tlogger.V(4).Info(\"Synchronizing PersistentVolume, volume is pre-bound to claim\", \"PVC\", klog.KRef(volume.Spec.ClaimRef.Namespace, volume.Spec.ClaimRef.Name), \"volumeName\", volume.Name)\n\t\t\tif _, err := ctrl.updateVolumePhase(ctx, volume, v1.VolumeAvailable, \"\"); err != nil {\n\t\t\t\t// Nothing was saved; we will fall back into the same\n\t\t\t\t// condition in the next call to this method\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\tlogger.V(4).Info(\"Synchronizing PersistentVolume, volume is bound to claim\", \"PVC\", klog.KRef(volume.Spec.ClaimRef.Namespace, volume.Spec.ClaimRef.Name), \"volumeName\", volume.Name)\n\t\t// Get the PVC by _name_\n\t\tvar claim *v1.PersistentVolumeClaim\n\t\tclaimName := claimrefToClaimKey(volume.Spec.ClaimRef)\n\t\tobj, found, err := ctrl.claims.GetByKey(claimName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !found {\n\t\t\t// If the PV was created by an external PV provisioner or\n\t\t\t// bound by external PV binder (e.g. kube-scheduler), it's\n\t\t\t// possible under heavy load that the corresponding PVC is not synced to\n\t\t\t// controller local cache yet. So we need to double-check PVC in\n\t\t\t// 1) informer cache\n\t\t\t// 2) apiserver if not found in informer cache\n\t\t\t// to make sure we will not reclaim a PV wrongly.\n\t\t\t// Note that only non-released and non-failed volumes will be\n\t\t\t// updated to Released state when PVC does not exist.\n\t\t\tif volume.Status.Phase != v1.VolumeReleased \u0026\u0026 volume.Status.Phase != v1.VolumeFailed {\n\t\t\t\tobj, err = ctrl.claimLister.PersistentVolumeClaims(volume.Spec.ClaimRef.Namespace).Get(volume.Spec.ClaimRef.Name)\n\t\t\t\tif err != nil \u0026\u0026 !apierrors.IsNotFound(err) {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfound = !apierrors.IsNotFound(err)\n\t\t\t\tif !found {\n\t\t\t\t\tobj, err = ctrl.kubeClient.CoreV1().PersistentVolumeClaims(volume.Spec.ClaimRef.Namespace).Get(ctx, volume.Spec.ClaimRef.Name, metav1.GetOptions{})\n\t\t\t\t\tif err != nil \u0026\u0026 !apierrors.IsNotFound(err) {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tfound = !apierrors.IsNotFound(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tlogger.V(4).Info(\"Synchronizing PersistentVolume, claim not found\", \"PVC\", klog.KRef(volume.Spec.ClaimRef.Namespace, volume.Spec.ClaimRef.Name), \"volumeName\", volume.Name)\n\t\t\t// Fall through with claim = nil\n\t\t} else {\n\t\t\tvar ok bool\n\t\t\tclaim, ok = obj.(*v1.PersistentVolumeClaim)\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"cannot convert object from volume cache to volume %q!?: %#v\", claim.Spec.VolumeName, obj)\n\t\t\t}\n\t\t\tlogger.V(4).Info(\"Synchronizing PersistentVolume, claim found\", \"PVC\", klog.KRef(volume.Spec.ClaimRef.Namespace, volume.Spec.ClaimRef.Name), \"claimStatus\", getClaimStatusForLogging(claim), \"volumeName\", volume.Name)\n\t\t}\n\t\tif claim != nil \u0026\u0026 claim.UID != volume.Spec.ClaimRef.UID {\n\t\t\t// The claim that the PV was pointing to was deleted, and another\n\t\t\t// with the same name created.\n\t\t\t// in some cases, the cached claim is not the newest, and the volume.Spec.ClaimRef.UID is newer than cached.\n\t\t\t// so we should double check by calling apiserver and get the newest claim, then compare them.\n\t\t\tlogger.V(4).Info(\"Maybe cached claim is not the newest one, we should fetch it from apiserver\", \"PVC\", klog.KRef(volume.Spec.ClaimRef.Namespace, volume.Spec.ClaimRef.Name))\n\n\t\t\tclaim, err = ctrl.kubeClient.CoreV1().PersistentVolumeClaims(volume.Spec.ClaimRef.Namespace).Get(ctx, volume.Spec.ClaimRef.Name, metav1.GetOptions{})\n\t\t\tif err != nil \u0026\u0026 !apierrors.IsNotFound(err) {\n\t\t\t\treturn err\n\t\t\t} else if claim != nil {\n\t\t\t\t// Treat the volume as bound to a missing claim.\n\t\t\t\tif claim.UID != volume.Spec.ClaimRef.UID {\n\t\t\t\t\tlogger.V(4).Info(\"Synchronizing PersistentVolume, claim has a newer UID than pv.ClaimRef, the old one must have been deleted\", \"PVC\", klog.KRef(volume.Spec.ClaimRef.Namespace, volume.Spec.ClaimRef.Name), \"volumeName\", volume.Name)\n\t\t\t\t\tclaim = nil\n\t\t\t\t} else {\n\t\t\t\t\tlogger.V(4).Info(\"Synchronizing PersistentVolume, claim has a same UID with pv.ClaimRef\", \"PVC\", klog.KRef(volume.Spec.ClaimRef.Namespace, volume.Spec.ClaimRef.Name), \"volumeName\", volume.Name)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif claim == nil {\n\t\t\t// If we get into this block, the claim must have been deleted;\n\t\t\t// NOTE: reclaimVolume may either release the PV back into the pool or\n\t\t\t// recycle it or do nothing (retain)\n\n\t\t\t// Do not overwrite previous Failed state - let the user see that\n\t\t\t// something went wrong, while we still re-try to reclaim the\n\t\t\t// volume.\n\t\t\tif volume.Status.Phase != v1.VolumeReleased \u0026\u0026 volume.Status.Phase != v1.VolumeFailed {\n\t\t\t\t// Also, log this only once:\n\t\t\t\tlogger.V(2).Info(\"Volume is released and reclaim policy will be executed\", \"volumeName\", volume.Name, \"reclaimPolicy\", volume.Spec.PersistentVolumeReclaimPolicy)\n\t\t\t\tif volume, err = ctrl.updateVolumePhase(ctx, volume, v1.VolumeReleased, \"\"); err != nil {\n\t\t\t\t\t// Nothing was saved; we will fall back into the same condition\n\t\t\t\t\t// in the next call to this method\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err = ctrl.reclaimVolume(ctx, volume); err != nil {\n\t\t\t\t// Release failed, we will fall back into the same condition\n\t\t\t\t// in the next call to this method\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif volume.Spec.PersistentVolumeReclaimPolicy == v1.PersistentVolumeReclaimRetain {\n\t\t\t\t// volume is being retained, it references a claim that does not exist now.\n\t\t\t\tlogger.V(4).Info(\"PersistentVolume references a claim that is not found\", \"PVC\", klog.KRef(volume.Spec.ClaimRef.Namespace, volume.Spec.ClaimRef.Name), \"claimUID\", volume.Spec.ClaimRef.UID, \"volumeName\", volume.Name)\n\t\t\t}\n\t\t\treturn nil\n\t\t} else if claim.Spec.VolumeName == \"\" {\n\t\t\tif storagehelpers.CheckVolumeModeMismatches(\u0026claim.Spec, \u0026volume.Spec) {\n\t\t\t\t// Binding for the volume won't be called in syncUnboundClaim,\n\t\t\t\t// because findBestMatchForClaim won't return the volume due to volumeMode mismatch.\n\t\t\t\tvolumeMsg := fmt.Sprintf(\"Cannot bind PersistentVolume to requested PersistentVolumeClaim %q due to incompatible volumeMode.\", claim.Name)\n\t\t\t\tctrl.eventRecorder.Event(volume, v1.EventTypeWarning, events.VolumeMismatch, volumeMsg)\n\t\t\t\tclaimMsg := fmt.Sprintf(\"Cannot bind PersistentVolume %q to requested PersistentVolumeClaim due to incompatible volumeMode.\", volume.Name)\n\t\t\t\tctrl.eventRecorder.Event(claim, v1.EventTypeWarning, events.VolumeMismatch, claimMsg)\n\t\t\t\t// Skipping syncClaim\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif metav1.HasAnnotation(volume.ObjectMeta, storagehelpers.AnnBoundByController) {\n\t\t\t\t// The binding is not completed; let PVC sync handle it\n\t\t\t\tlogger.V(4).Info(\"Synchronizing PersistentVolume, volume not bound yet, waiting for syncClaim to fix it\", \"volumeName\", volume.Name)\n\t\t\t} else {\n\t\t\t\t// Dangling PV; try to re-establish the link in the PVC sync\n\t\t\t\tlogger.V(4).Info(\"Synchronizing PersistentVolume, volume was bound and got unbound (by user?), waiting for syncClaim to fix it\", \"volumeName\", volume.Name)\n\t\t\t}\n\t\t\t// In both cases, the volume is Bound and the claim is Pending.\n\t\t\t// Next syncClaim will fix it. To speed it up, we enqueue the claim\n\t\t\t// into the controller, which results in syncClaim to be called\n\t\t\t// shortly (and in the right worker goroutine).\n\t\t\t// This speeds up binding of provisioned volumes - provisioner saves\n\t\t\t// only the new PV and it expects that next syncClaim will bind the\n\t\t\t// claim to it.\n\t\t\tctrl.claimQueue.Add(claimToClaimKey(claim))\n\t\t\treturn nil\n\t\t} else if claim.Spec.VolumeName == volume.Name {\n\t\t\t// Volume is bound to a claim properly, update status if necessary\n\t\t\tlogger.V(4).Info(\"Synchronizing PersistentVolume, all is bound\", \"volumeName\", volume.Name)\n\t\t\tif _, err = ctrl.updateVolumePhase(ctx, volume, v1.VolumeBound, \"\"); err != nil {\n\t\t\t\t// Nothing was saved; we will fall back into the same\n\t\t\t\t// condition in the next call to this method\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t} else {\n\t\t\t// Volume is bound to a claim, but the claim is bound elsewhere\n\t\t\tif metav1.HasAnnotation(volume.ObjectMeta, storagehelpers.AnnDynamicallyProvisioned) \u0026\u0026 volume.Spec.PersistentVolumeReclaimPolicy == v1.PersistentVolumeReclaimDelete {\n\t\t\t\t// This volume was dynamically provisioned for this claim. The\n\t\t\t\t// claim got bound elsewhere, and thus this volume is not\n\t\t\t\t// needed. Delete it.\n\t\t\t\t// Mark the volume as Released for external deleters and to let\n\t\t\t\t// the user know. Don't overwrite existing Failed status!\n\t\t\t\tif volume.Status.Phase != v1.VolumeReleased \u0026\u0026 volume.Status.Phase != v1.VolumeFailed {\n\t\t\t\t\t// Also, log this only once:\n\t\t\t\t\tlogger.V(2).Info(\"Dynamically provisioned volume is released and it will be deleted\", \"volumeName\", volume.Name)\n\t\t\t\t\tif volume, err = ctrl.updateVolumePhase(ctx, volume, v1.VolumeReleased, \"\"); err != nil {\n\t\t\t\t\t\t// Nothing was saved; we will fall back into the same condition\n\t\t\t\t\t\t// in the next call to this method\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif err = ctrl.reclaimVolume(ctx, volume); err != nil {\n\t\t\t\t\t// Deletion failed, we will fall back into the same condition\n\t\t\t\t\t// in the next call to this method\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t} else {\n\t\t\t\t// Volume is bound to a claim, but the claim is bound elsewhere\n\t\t\t\t// and it's not dynamically provisioned.\n\t\t\t\tif metav1.HasAnnotation(volume.ObjectMeta, storagehelpers.AnnBoundByController) {\n\t\t\t\t\t// This is part of the normal operation of the controller; the\n\t\t\t\t\t// controller tried to use this volume for a claim but the claim\n\t\t\t\t\t// was fulfilled by another volume. We did this; fix it.\n\t\t\t\t\tlogger.V(4).Info(\"Synchronizing PersistentVolume, volume is bound by controller to a claim that is bound to another volume, unbinding\", \"volumeName\", volume.Name)\n\t\t\t\t\tif err = ctrl.unbindVolume(ctx, volume); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t} else {\n\t\t\t\t\t// The PV must have been created with this ptr; leave it alone.\n\t\t\t\t\tlogger.V(4).Info(\"Synchronizing PersistentVolume, volume is bound by user to a claim that is bound to another volume, waiting for the claim to get unbound\", \"volumeName\", volume.Name)\n\t\t\t\t\t// This just updates the volume phase and clears\n\t\t\t\t\t// volume.Spec.ClaimRef.UID. It leaves the volume pre-bound\n\t\t\t\t\t// to the claim.\n\t\t\t\t\tif err = ctrl.unbindVolume(ctx, volume); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":558,"to":776}} {"id":100005050,"name":"updateClaimStatus","signature":"func (ctrl *PersistentVolumeController) updateClaimStatus(ctx context.Context, claim *v1.PersistentVolumeClaim, phase v1.PersistentVolumeClaimPhase, volume *v1.PersistentVolume) (*v1.PersistentVolumeClaim, error)","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// updateClaimStatus saves new claim.Status to API server.\n// Parameters:\n//\n//\tclaim - claim to update\n//\tphase - phase to set\n//\tvolume - volume which Capacity is set into claim.Status.Capacity\nfunc (ctrl *PersistentVolumeController) updateClaimStatus(ctx context.Context, claim *v1.PersistentVolumeClaim, phase v1.PersistentVolumeClaimPhase, volume *v1.PersistentVolume) (*v1.PersistentVolumeClaim, error) {\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"Updating PersistentVolumeClaim status\", \"PVC\", klog.KObj(claim), \"setPhase\", phase)\n\n\tdirty := false\n\n\tclaimClone := claim.DeepCopy()\n\tif claim.Status.Phase != phase {\n\t\tclaimClone.Status.Phase = phase\n\t\tdirty = true\n\t}\n\n\tif volume == nil {\n\t\t// Need to reset AccessModes and Capacity\n\t\tif claim.Status.AccessModes != nil {\n\t\t\tclaimClone.Status.AccessModes = nil\n\t\t\tdirty = true\n\t\t}\n\t\tif claim.Status.Capacity != nil {\n\t\t\tclaimClone.Status.Capacity = nil\n\t\t\tdirty = true\n\t\t}\n\t} else {\n\t\t// Need to update AccessModes and Capacity\n\t\tif !reflect.DeepEqual(claim.Status.AccessModes, volume.Spec.AccessModes) {\n\t\t\tclaimClone.Status.AccessModes = volume.Spec.AccessModes\n\t\t\tdirty = true\n\t\t}\n\n\t\t// Update Capacity if the claim is becoming Bound, not if it was already.\n\t\t// A discrepancy can be intentional to mean that the PVC filesystem size\n\t\t// doesn't match the PV block device size, so don't clobber it\n\t\tif claim.Status.Phase != phase {\n\t\t\tvolumeCap, ok := volume.Spec.Capacity[v1.ResourceStorage]\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"PersistentVolume %q is without a storage capacity\", volume.Name)\n\t\t\t}\n\t\t\tclaimCap, ok := claim.Status.Capacity[v1.ResourceStorage]\n\t\t\t// If PV has a resize annotation, set the claim's request capacity\n\t\t\tif metav1.HasAnnotation(volume.ObjectMeta, util.AnnPreResizeCapacity) {\n\t\t\t\tlogger.V(2).Info(\"Volume requires filesystem resize: setting pvc status capacity\", \"PVC\", klog.KObj(claim), \"volumeName\", volume.Name, \"statusCapacity\", volume.ObjectMeta.Annotations[util.AnnPreResizeCapacity])\n\t\t\t\tpreQty, err := resource.ParseQuantity(volume.ObjectMeta.Annotations[util.AnnPreResizeCapacity])\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Info(\"Parsing pre-resize-capacity from PV failed\", \"volumeName\", volume.Name, \"err\", err)\n\t\t\t\t\tpreQty = volume.Spec.Capacity[v1.ResourceStorage]\n\t\t\t\t}\n\t\t\t\tif claimClone.Status.Capacity == nil {\n\t\t\t\t\tclaimClone.Status.Capacity = make(map[v1.ResourceName]resource.Quantity)\n\t\t\t\t}\n\t\t\t\tclaimClone.Status.Capacity[v1.ResourceStorage] = preQty\n\t\t\t\tdirty = true\n\t\t\t} else if !ok || volumeCap.Cmp(claimCap) != 0 {\n\t\t\t\tclaimClone.Status.Capacity = volume.Spec.Capacity\n\t\t\t\tdirty = true\n\t\t\t}\n\t\t}\n\t}\n\n\tif !dirty {\n\t\t// Nothing to do.\n\t\tlogger.V(4).Info(\"Updating PersistentVolumeClaim status, phase already set\", \"PVC\", klog.KObj(claim), \"phase\", phase)\n\t\treturn claim, nil\n\t}\n\n\tnewClaim, err := ctrl.kubeClient.CoreV1().PersistentVolumeClaims(claimClone.Namespace).UpdateStatus(ctx, claimClone, metav1.UpdateOptions{})\n\tif err != nil {\n\t\tlogger.V(4).Info(\"Updating PersistentVolumeClaim status, set phase failed\", \"PVC\", klog.KObj(claim), \"phase\", phase, \"err\", err)\n\t\treturn newClaim, err\n\t}\n\t_, err = ctrl.storeClaimUpdate(logger, newClaim)\n\tif err != nil {\n\t\tlogger.V(4).Info(\"Updating PersistentVolumeClaim status: cannot update internal cache\", \"PVC\", klog.KObj(claim), \"err\", err)\n\t\treturn newClaim, err\n\t}\n\tlogger.V(2).Info(\"Claim entered phase\", \"PVC\", klog.KObj(claim), \"phase\", phase)\n\treturn newClaim, nil\n}","line":{"from":778,"to":860}} {"id":100005051,"name":"updateClaimStatusWithEvent","signature":"func (ctrl *PersistentVolumeController) updateClaimStatusWithEvent(ctx context.Context, claim *v1.PersistentVolumeClaim, phase v1.PersistentVolumeClaimPhase, volume *v1.PersistentVolume, eventtype, reason, message string) (*v1.PersistentVolumeClaim, error)","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// updateClaimStatusWithEvent saves new claim.Status to API server and emits\n// given event on the claim. It saves the status and emits the event only when\n// the status has actually changed from the version saved in API server.\n// Parameters:\n//\n//\tclaim - claim to update\n//\tphase - phase to set\n//\tvolume - volume which Capacity is set into claim.Status.Capacity\n//\teventtype, reason, message - event to send, see EventRecorder.Event()\nfunc (ctrl *PersistentVolumeController) updateClaimStatusWithEvent(ctx context.Context, claim *v1.PersistentVolumeClaim, phase v1.PersistentVolumeClaimPhase, volume *v1.PersistentVolume, eventtype, reason, message string) (*v1.PersistentVolumeClaim, error) {\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"Updating updateClaimStatusWithEvent\", \"PVC\", klog.KObj(claim), \"setPhase\", phase)\n\tif claim.Status.Phase == phase {\n\t\t// Nothing to do.\n\t\tlogger.V(4).Info(\"Updating updateClaimStatusWithEvent, phase already set\", \"PVC\", klog.KObj(claim), \"phase\", phase)\n\t\treturn claim, nil\n\t}\n\n\tnewClaim, err := ctrl.updateClaimStatus(ctx, claim, phase, volume)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Emit the event only when the status change happens, not every time\n\t// syncClaim is called.\n\tlogger.V(3).Info(\"Claim changed status\", \"PVC\", klog.KObj(claim), \"phase\", phase, \"message\", message)\n\tctrl.eventRecorder.Event(newClaim, eventtype, reason, message)\n\n\treturn newClaim, nil\n}","line":{"from":862,"to":891}} {"id":100005052,"name":"updateVolumePhase","signature":"func (ctrl *PersistentVolumeController) updateVolumePhase(ctx context.Context, volume *v1.PersistentVolume, phase v1.PersistentVolumePhase, message string) (*v1.PersistentVolume, error)","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// updateVolumePhase saves new volume phase to API server.\nfunc (ctrl *PersistentVolumeController) updateVolumePhase(ctx context.Context, volume *v1.PersistentVolume, phase v1.PersistentVolumePhase, message string) (*v1.PersistentVolume, error) {\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"Updating PersistentVolume\", \"volumeName\", volume.Name, \"setPhase\", phase)\n\tif volume.Status.Phase == phase {\n\t\t// Nothing to do.\n\t\tlogger.V(4).Info(\"Updating PersistentVolume: phase already set\", \"volumeName\", volume.Name, \"phase\", phase)\n\t\treturn volume, nil\n\t}\n\n\tvolumeClone := volume.DeepCopy()\n\tvolumeClone.Status.Phase = phase\n\tvolumeClone.Status.Message = message\n\n\tnewVol, err := ctrl.kubeClient.CoreV1().PersistentVolumes().UpdateStatus(ctx, volumeClone, metav1.UpdateOptions{})\n\tif err != nil {\n\t\tlogger.V(4).Info(\"Updating PersistentVolume: set phase failed\", \"volumeName\", volume.Name, \"phase\", phase, \"err\", err)\n\t\treturn newVol, err\n\t}\n\t_, err = ctrl.storeVolumeUpdate(logger, newVol)\n\tif err != nil {\n\t\tlogger.V(4).Info(\"Updating PersistentVolume: cannot update internal cache\", \"volumeName\", volume.Name, \"err\", err)\n\t\treturn newVol, err\n\t}\n\tlogger.V(2).Info(\"Volume entered phase\", \"volumeName\", volume.Name, \"phase\", phase)\n\treturn newVol, err\n}","line":{"from":893,"to":919}} {"id":100005053,"name":"updateVolumePhaseWithEvent","signature":"func (ctrl *PersistentVolumeController) updateVolumePhaseWithEvent(ctx context.Context, volume *v1.PersistentVolume, phase v1.PersistentVolumePhase, eventtype, reason, message string) (*v1.PersistentVolume, error)","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// updateVolumePhaseWithEvent saves new volume phase to API server and emits\n// given event on the volume. It saves the phase and emits the event only when\n// the phase has actually changed from the version saved in API server.\nfunc (ctrl *PersistentVolumeController) updateVolumePhaseWithEvent(ctx context.Context, volume *v1.PersistentVolume, phase v1.PersistentVolumePhase, eventtype, reason, message string) (*v1.PersistentVolume, error) {\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"Updating updateVolumePhaseWithEvent\", \"volumeName\", volume.Name, \"setPhase\", phase)\n\tif volume.Status.Phase == phase {\n\t\t// Nothing to do.\n\t\tlogger.V(4).Info(\"Updating updateVolumePhaseWithEvent: phase already set\", \"volumeName\", volume.Name, \"phase\", phase)\n\t\treturn volume, nil\n\t}\n\n\tnewVol, err := ctrl.updateVolumePhase(ctx, volume, phase, message)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Emit the event only when the status change happens, not every time\n\t// syncClaim is called.\n\tlogger.V(3).Info(\"Volume changed status\", \"volumeName\", volume.Name, \"changedPhase\", phase, \"message\", message)\n\tctrl.eventRecorder.Event(newVol, eventtype, reason, message)\n\n\treturn newVol, nil\n}","line":{"from":921,"to":944}} {"id":100005054,"name":"assignDefaultStorageClass","signature":"func (ctrl *PersistentVolumeController) assignDefaultStorageClass(ctx context.Context, claim *v1.PersistentVolumeClaim) (bool, error)","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// assignDefaultStorageClass updates the claim storage class if there is any, the claim is updated to the API server.\n// Ignores claims that already have a storage class.\n// TODO: if resync is ever changed to a larger period, we might need to change how we set the default class on existing unbound claims\nfunc (ctrl *PersistentVolumeController) assignDefaultStorageClass(ctx context.Context, claim *v1.PersistentVolumeClaim) (bool, error) {\n\tlogger := klog.FromContext(ctx)\n\n\tif storagehelpers.GetPersistentVolumeClaimClass(claim) != \"\" {\n\t\treturn false, nil\n\t}\n\n\tclass, err := util.GetDefaultClass(ctrl.classLister)\n\tif err != nil {\n\t\t// It is safe to ignore errors here because it means we either could not list SCs or there is more than one default.\n\t\t// TODO: do not ignore errors after this PR is merged: https://github.com/kubernetes/kubernetes/pull/110559\n\t\tlogger.V(4).Info(\"Failed to get default storage class\", \"err\", err)\n\t\treturn false, nil\n\t} else if class == nil {\n\t\tlogger.V(4).Info(\"Can not assign storage class to PersistentVolumeClaim: default storage class not found\", \"PVC\", klog.KObj(claim))\n\t\treturn false, nil\n\t}\n\n\tlogger.V(4).Info(\"Assigning StorageClass to PersistentVolumeClaim\", \"PVC\", klog.KObj(claim), \"storageClassName\", class.Name)\n\tclaim.Spec.StorageClassName = \u0026class.Name\n\t_, err = ctrl.kubeClient.CoreV1().PersistentVolumeClaims(claim.GetNamespace()).Update(ctx, claim, metav1.UpdateOptions{})\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tlogger.V(4).Info(\"Successfully assigned StorageClass to PersistentVolumeClaim\", \"PVC\", klog.KObj(claim), \"storageClassName\", class.Name)\n\treturn true, nil\n}","line":{"from":946,"to":976}} {"id":100005055,"name":"bindVolumeToClaim","signature":"func (ctrl *PersistentVolumeController) bindVolumeToClaim(ctx context.Context, volume *v1.PersistentVolume, claim *v1.PersistentVolumeClaim) (*v1.PersistentVolume, error)","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// bindVolumeToClaim modifies given volume to be bound to a claim and saves it to\n// API server. The claim is not modified in this method!\nfunc (ctrl *PersistentVolumeController) bindVolumeToClaim(ctx context.Context, volume *v1.PersistentVolume, claim *v1.PersistentVolumeClaim) (*v1.PersistentVolume, error) {\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"Updating PersistentVolume: binding to claim\", \"PVC\", klog.KObj(claim), \"volumeName\", volume.Name)\n\n\tvolumeClone, dirty, err := storagehelpers.GetBindVolumeToClaim(volume, claim)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Save the volume only if something was changed\n\tif dirty {\n\t\treturn ctrl.updateBindVolumeToClaim(ctx, volumeClone, true)\n\t}\n\n\tlogger.V(4).Info(\"Updating PersistentVolume: already bound to claim\", \"PVC\", klog.KObj(claim), \"volumeName\", volume.Name)\n\treturn volume, nil\n}","line":{"from":978,"to":996}} {"id":100005056,"name":"updateBindVolumeToClaim","signature":"func (ctrl *PersistentVolumeController) updateBindVolumeToClaim(ctx context.Context, volumeClone *v1.PersistentVolume, updateCache bool) (*v1.PersistentVolume, error)","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// updateBindVolumeToClaim modifies given volume to be bound to a claim and saves it to\n// API server. The claim is not modified in this method!\nfunc (ctrl *PersistentVolumeController) updateBindVolumeToClaim(ctx context.Context, volumeClone *v1.PersistentVolume, updateCache bool) (*v1.PersistentVolume, error) {\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(2).Info(\"Claim bound to volume\", \"PVC\", klog.KRef(volumeClone.Spec.ClaimRef.Namespace, volumeClone.Spec.ClaimRef.Name), \"volumeName\", volumeClone.Name)\n\tnewVol, err := ctrl.kubeClient.CoreV1().PersistentVolumes().Update(ctx, volumeClone, metav1.UpdateOptions{})\n\tif err != nil {\n\t\tlogger.V(4).Info(\"Updating PersistentVolume: binding to claim failed\", \"PVC\", klog.KRef(volumeClone.Spec.ClaimRef.Namespace, volumeClone.Spec.ClaimRef.Name), \"volumeName\", volumeClone.Name, \"err\", err)\n\t\treturn newVol, err\n\t}\n\tif updateCache {\n\t\t_, err = ctrl.storeVolumeUpdate(logger, newVol)\n\t\tif err != nil {\n\t\t\tlogger.V(4).Info(\"Updating PersistentVolume: cannot update internal cache\", \"volumeName\", volumeClone.Name, \"err\", err)\n\t\t\treturn newVol, err\n\t\t}\n\t}\n\tlogger.V(4).Info(\"Updating PersistentVolume: bound to claim\", \"PVC\", klog.KRef(volumeClone.Spec.ClaimRef.Namespace, volumeClone.Spec.ClaimRef.Name), \"volumeName\", newVol.Name)\n\treturn newVol, nil\n}","line":{"from":998,"to":1017}} {"id":100005057,"name":"bindClaimToVolume","signature":"func (ctrl *PersistentVolumeController) bindClaimToVolume(ctx context.Context, claim *v1.PersistentVolumeClaim, volume *v1.PersistentVolume) (*v1.PersistentVolumeClaim, error)","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// bindClaimToVolume modifies the given claim to be bound to a volume and\n// saves it to API server. The volume is not modified in this method!\nfunc (ctrl *PersistentVolumeController) bindClaimToVolume(ctx context.Context, claim *v1.PersistentVolumeClaim, volume *v1.PersistentVolume) (*v1.PersistentVolumeClaim, error) {\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"Updating PersistentVolumeClaim: binding to volume\", \"PVC\", klog.KObj(claim), \"volumeName\", volume.Name)\n\n\tdirty := false\n\n\t// Check if the claim was already bound (either by controller or by user)\n\tshouldBind := false\n\tif volume.Name != claim.Spec.VolumeName {\n\t\tshouldBind = true\n\t}\n\n\t// The claim from method args can be pointing to watcher cache. We must not\n\t// modify these, therefore create a copy.\n\tclaimClone := claim.DeepCopy()\n\n\tif shouldBind {\n\t\tdirty = true\n\t\t// Bind the claim to the volume\n\t\tclaimClone.Spec.VolumeName = volume.Name\n\n\t\t// Set AnnBoundByController if it is not set yet\n\t\tif !metav1.HasAnnotation(claimClone.ObjectMeta, storagehelpers.AnnBoundByController) {\n\t\t\tmetav1.SetMetaDataAnnotation(\u0026claimClone.ObjectMeta, storagehelpers.AnnBoundByController, \"yes\")\n\t\t}\n\t}\n\n\t// Set AnnBindCompleted if it is not set yet\n\tif !metav1.HasAnnotation(claimClone.ObjectMeta, storagehelpers.AnnBindCompleted) {\n\t\tmetav1.SetMetaDataAnnotation(\u0026claimClone.ObjectMeta, storagehelpers.AnnBindCompleted, \"yes\")\n\t\tdirty = true\n\t}\n\n\tif dirty {\n\t\tlogger.V(2).Info(\"Volume bound to claim\", \"PVC\", klog.KObj(claim), \"volumeName\", volume.Name)\n\t\tnewClaim, err := ctrl.kubeClient.CoreV1().PersistentVolumeClaims(claim.Namespace).Update(ctx, claimClone, metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\tlogger.V(4).Info(\"Updating PersistentVolumeClaim: binding to volume failed\", \"PVC\", klog.KObj(claim), \"volumeName\", volume.Name, \"err\", err)\n\t\t\treturn newClaim, err\n\t\t}\n\t\t_, err = ctrl.storeClaimUpdate(logger, newClaim)\n\t\tif err != nil {\n\t\t\tlogger.V(4).Info(\"Updating PersistentVolumeClaim: cannot update internal cache\", \"PVC\", klog.KObj(claim), \"err\", err)\n\t\t\treturn newClaim, err\n\t\t}\n\t\tlogger.V(4).Info(\"Updating PersistentVolumeClaim: bound to volume\", \"PVC\", klog.KObj(claim), \"volumeName\", volume.Name)\n\t\treturn newClaim, nil\n\t}\n\n\tlogger.V(4).Info(\"Updating PersistentVolumeClaim: already bound to volume\", \"PVC\", klog.KObj(claim), \"volumeName\", volume.Name)\n\treturn claim, nil\n}","line":{"from":1019,"to":1072}} {"id":100005058,"name":"bind","signature":"func (ctrl *PersistentVolumeController) bind(ctx context.Context, volume *v1.PersistentVolume, claim *v1.PersistentVolumeClaim) error","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// bind saves binding information both to the volume and the claim and marks\n// both objects as Bound. Volume is saved first.\n// It returns on first error, it's up to the caller to implement some retry\n// mechanism.\nfunc (ctrl *PersistentVolumeController) bind(ctx context.Context, volume *v1.PersistentVolume, claim *v1.PersistentVolumeClaim) error {\n\tvar err error\n\t// use updateClaim/updatedVolume to keep the original claim/volume for\n\t// logging in error cases.\n\tvar updatedClaim *v1.PersistentVolumeClaim\n\tvar updatedVolume *v1.PersistentVolume\n\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"Binding volume to claim\", \"PVC\", klog.KObj(claim), \"volumeName\", volume.Name)\n\n\tif updatedVolume, err = ctrl.bindVolumeToClaim(ctx, volume, claim); err != nil {\n\t\tlogger.V(3).Info(\"Error binding volume to claim: failed saving the volume\", \"PVC\", klog.KObj(claim), \"volumeName\", volume.Name, \"err\", err)\n\t\treturn err\n\t}\n\tvolume = updatedVolume\n\n\tif updatedVolume, err = ctrl.updateVolumePhase(ctx, volume, v1.VolumeBound, \"\"); err != nil {\n\t\tlogger.V(3).Info(\"Error binding volume to claim: failed saving the volume status\", \"PVC\", klog.KObj(claim), \"volumeName\", volume.Name, \"err\", err)\n\t\treturn err\n\t}\n\tvolume = updatedVolume\n\n\tif updatedClaim, err = ctrl.bindClaimToVolume(ctx, claim, volume); err != nil {\n\t\tlogger.V(3).Info(\"Error binding volume to claim: failed saving the claim\", \"PVC\", klog.KObj(claim), \"volumeName\", volume.Name, \"err\", err)\n\t\treturn err\n\t}\n\tclaim = updatedClaim\n\n\tif updatedClaim, err = ctrl.updateClaimStatus(ctx, claim, v1.ClaimBound, volume); err != nil {\n\t\tlogger.V(3).Info(\"Error binding volume to claim: failed saving the claim status\", \"PVC\", klog.KObj(claim), \"volumeName\", volume.Name, \"err\", err)\n\t\treturn err\n\t}\n\tclaim = updatedClaim\n\n\tlogger.V(4).Info(\"Volume bound to claim\", \"PVC\", klog.KObj(claim), \"volumeName\", volume.Name)\n\tlogger.V(4).Info(\"Volume status after binding\", \"volumeName\", volume.Name, \"volumeStatus\", getVolumeStatusForLogging(volume))\n\tlogger.V(4).Info(\"Claim status after binding\", \"PVC\", klog.KObj(claim), \"claimStatus\", getClaimStatusForLogging(claim))\n\treturn nil\n}","line":{"from":1074,"to":1116}} {"id":100005059,"name":"unbindVolume","signature":"func (ctrl *PersistentVolumeController) unbindVolume(ctx context.Context, volume *v1.PersistentVolume) error","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// unbindVolume rolls back previous binding of the volume. This may be necessary\n// when two controllers bound two volumes to single claim - when we detect this,\n// only one binding succeeds and the second one must be rolled back.\n// This method updates both Spec and Status.\n// It returns on first error, it's up to the caller to implement some retry\n// mechanism.\nfunc (ctrl *PersistentVolumeController) unbindVolume(ctx context.Context, volume *v1.PersistentVolume) error {\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"Updating PersistentVolume: rolling back binding from claim\", \"PVC\", klog.KRef(volume.Spec.ClaimRef.Namespace, volume.Spec.ClaimRef.Name), \"volumeName\", volume.Name)\n\n\t// Save the PV only when any modification is necessary.\n\tvolumeClone := volume.DeepCopy()\n\n\tif metav1.HasAnnotation(volume.ObjectMeta, storagehelpers.AnnBoundByController) {\n\t\t// The volume was bound by the controller.\n\t\tvolumeClone.Spec.ClaimRef = nil\n\t\tdelete(volumeClone.Annotations, storagehelpers.AnnBoundByController)\n\t\tif len(volumeClone.Annotations) == 0 {\n\t\t\t// No annotations look better than empty annotation map (and it's easier\n\t\t\t// to test).\n\t\t\tvolumeClone.Annotations = nil\n\t\t}\n\t} else {\n\t\t// The volume was pre-bound by user. Clear only the binding UID.\n\t\tvolumeClone.Spec.ClaimRef.UID = \"\"\n\t}\n\n\tnewVol, err := ctrl.kubeClient.CoreV1().PersistentVolumes().Update(ctx, volumeClone, metav1.UpdateOptions{})\n\tif err != nil {\n\t\tlogger.V(4).Info(\"Updating PersistentVolume: rollback failed\", \"volumeName\", volume.Name, \"err\", err)\n\t\treturn err\n\t}\n\t_, err = ctrl.storeVolumeUpdate(logger, newVol)\n\tif err != nil {\n\t\tlogger.V(4).Info(\"Updating PersistentVolume: cannot update internal cache\", \"volumeName\", volume.Name, \"err\", err)\n\t\treturn err\n\t}\n\tlogger.V(4).Info(\"Updating PersistentVolume: rolled back\", \"volumeName\", newVol.Name)\n\n\t// Update the status\n\t_, err = ctrl.updateVolumePhase(ctx, newVol, v1.VolumeAvailable, \"\")\n\treturn err\n}","line":{"from":1118,"to":1160}} {"id":100005060,"name":"reclaimVolume","signature":"func (ctrl *PersistentVolumeController) reclaimVolume(ctx context.Context, volume *v1.PersistentVolume) error","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// reclaimVolume implements volume.Spec.PersistentVolumeReclaimPolicy and\n// starts appropriate reclaim action.\nfunc (ctrl *PersistentVolumeController) reclaimVolume(ctx context.Context, volume *v1.PersistentVolume) error {\n\tlogger := klog.FromContext(ctx)\n\tif migrated := volume.Annotations[storagehelpers.AnnMigratedTo]; len(migrated) \u003e 0 {\n\t\t// PV is Migrated. The PV controller should stand down and the external\n\t\t// provisioner will handle this PV\n\t\treturn nil\n\t}\n\tswitch volume.Spec.PersistentVolumeReclaimPolicy {\n\tcase v1.PersistentVolumeReclaimRetain:\n\t\tlogger.V(4).Info(\"ReclaimVolume: policy is Retain, nothing to do\", \"volumeName\", volume.Name)\n\n\tcase v1.PersistentVolumeReclaimRecycle:\n\t\tlogger.V(4).Info(\"ReclaimVolume: policy is Recycle\", \"volumeName\", volume.Name)\n\t\topName := fmt.Sprintf(\"recycle-%s[%s]\", volume.Name, string(volume.UID))\n\t\tctrl.scheduleOperation(logger, opName, func() error {\n\t\t\tctrl.recycleVolumeOperation(ctx, volume)\n\t\t\treturn nil\n\t\t})\n\n\tcase v1.PersistentVolumeReclaimDelete:\n\t\tlogger.V(4).Info(\"ReclaimVolume: policy is Delete\", \"volumeName\", volume.Name)\n\t\topName := fmt.Sprintf(\"delete-%s[%s]\", volume.Name, string(volume.UID))\n\t\t// create a start timestamp entry in cache for deletion operation if no one exists with\n\t\t// key = volume.Name, pluginName = provisionerName, operation = \"delete\"\n\t\tctrl.operationTimestamps.AddIfNotExist(volume.Name, ctrl.getProvisionerNameFromVolume(volume), \"delete\")\n\t\tctrl.scheduleOperation(logger, opName, func() error {\n\t\t\t_, err := ctrl.deleteVolumeOperation(ctx, volume)\n\t\t\tif err != nil {\n\t\t\t\t// only report error count to \"volume_operation_total_errors\"\n\t\t\t\t// latency reporting will happen when the volume get finally\n\t\t\t\t// deleted and a volume deleted event is captured\n\t\t\t\tmetrics.RecordMetric(volume.Name, \u0026ctrl.operationTimestamps, err)\n\t\t\t}\n\t\t\treturn err\n\t\t})\n\n\tdefault:\n\t\t// Unknown PersistentVolumeReclaimPolicy\n\t\tif _, err := ctrl.updateVolumePhaseWithEvent(ctx, volume, v1.VolumeFailed, v1.EventTypeWarning, \"VolumeUnknownReclaimPolicy\", \"Volume has unrecognized PersistentVolumeReclaimPolicy\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":1162,"to":1207}} {"id":100005061,"name":"recycleVolumeOperation","signature":"func (ctrl *PersistentVolumeController) recycleVolumeOperation(ctx context.Context, volume *v1.PersistentVolume)","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// recycleVolumeOperation recycles a volume. This method is running in\n// standalone goroutine and already has all necessary locks.\nfunc (ctrl *PersistentVolumeController) recycleVolumeOperation(ctx context.Context, volume *v1.PersistentVolume) {\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"RecycleVolumeOperation started\", \"volumeName\", volume.Name)\n\n\t// This method may have been waiting for a volume lock for some time.\n\t// Previous recycleVolumeOperation might just have saved an updated version,\n\t// so read current volume state now.\n\tnewVolume, err := ctrl.kubeClient.CoreV1().PersistentVolumes().Get(ctx, volume.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\tlogger.V(3).Info(\"Error reading persistent volume\", \"volumeName\", volume.Name, \"err\", err)\n\t\treturn\n\t}\n\tneedsReclaim, err := ctrl.isVolumeReleased(logger, newVolume)\n\tif err != nil {\n\t\tlogger.V(3).Info(\"Error reading claim for volume\", \"volumeName\", volume.Name, \"err\", err)\n\t\treturn\n\t}\n\tif !needsReclaim {\n\t\tlogger.V(3).Info(\"Volume no longer needs recycling, skipping\", \"volumeName\", volume.Name)\n\t\treturn\n\t}\n\tpods, used, err := ctrl.isVolumeUsed(newVolume)\n\tif err != nil {\n\t\tlogger.V(3).Info(\"Can't recycle volume\", \"volumeName\", volume.Name, \"err\", err)\n\t\treturn\n\t}\n\n\t// Verify the claim is in cache: if so, then it is a different PVC with the same name\n\t// since the volume is known to be released at this moment. The new (cached) PVC must use\n\t// a different PV -- we checked that the PV is unused in isVolumeReleased.\n\t// So the old PV is safe to be recycled.\n\tclaimName := claimrefToClaimKey(volume.Spec.ClaimRef)\n\t_, claimCached, err := ctrl.claims.GetByKey(claimName)\n\tif err != nil {\n\t\tlogger.V(3).Info(\"Error getting the claim from cache\", \"PVC\", klog.KRef(volume.Spec.ClaimRef.Namespace, volume.Spec.ClaimRef.Name))\n\t\treturn\n\t}\n\n\tif used \u0026\u0026 !claimCached {\n\t\tmsg := fmt.Sprintf(\"Volume is used by pods: %s\", strings.Join(pods, \",\"))\n\t\tlogger.V(3).Info(\"Can't recycle volume\", \"volumeName\", volume.Name, \"msg\", msg)\n\t\tctrl.eventRecorder.Event(volume, v1.EventTypeNormal, events.VolumeFailedRecycle, msg)\n\t\treturn\n\t}\n\n\t// Use the newest volume copy, this will save us from version conflicts on\n\t// saving.\n\tvolume = newVolume\n\n\t// Find a plugin.\n\tspec := vol.NewSpecFromPersistentVolume(volume, false)\n\tplugin, err := ctrl.volumePluginMgr.FindRecyclablePluginBySpec(spec)\n\tif err != nil {\n\t\t// No recycler found. Emit an event and mark the volume Failed.\n\t\tif _, err = ctrl.updateVolumePhaseWithEvent(ctx, volume, v1.VolumeFailed, v1.EventTypeWarning, events.VolumeFailedRecycle, \"No recycler plugin found for the volume!\"); err != nil {\n\t\t\tlogger.V(4).Info(\"RecycleVolumeOperation: failed to mark volume as failed\", \"volumeName\", volume.Name, \"err\", err)\n\t\t\t// Save failed, retry on the next deletion attempt\n\t\t\treturn\n\t\t}\n\t\t// Despite the volume being Failed, the controller will retry recycling\n\t\t// the volume in every syncVolume() call.\n\t\treturn\n\t}\n\n\t// Plugin found\n\trecorder := ctrl.newRecyclerEventRecorder(volume)\n\n\tif err = plugin.Recycle(volume.Name, spec, recorder); err != nil {\n\t\t// Recycler failed\n\t\tstrerr := fmt.Sprintf(\"Recycle failed: %s\", err)\n\t\tif _, err = ctrl.updateVolumePhaseWithEvent(ctx, volume, v1.VolumeFailed, v1.EventTypeWarning, events.VolumeFailedRecycle, strerr); err != nil {\n\t\t\tlogger.V(4).Info(\"RecycleVolumeOperation: failed to mark volume as failed\", \"volumeName\", volume.Name, \"err\", err)\n\t\t\t// Save failed, retry on the next deletion attempt\n\t\t\treturn\n\t\t}\n\t\t// Despite the volume being Failed, the controller will retry recycling\n\t\t// the volume in every syncVolume() call.\n\t\treturn\n\t}\n\n\tlogger.V(2).Info(\"Volume recycled\", \"volumeName\", volume.Name)\n\t// Send an event\n\tctrl.eventRecorder.Event(volume, v1.EventTypeNormal, events.VolumeRecycled, \"Volume recycled\")\n\t// Make the volume available again\n\tif err = ctrl.unbindVolume(ctx, volume); err != nil {\n\t\t// Oops, could not save the volume and therefore the controller will\n\t\t// recycle the volume again on next update. We _could_ maintain a cache\n\t\t// of \"recently recycled volumes\" and avoid unnecessary recycling, this\n\t\t// is left out as future optimization.\n\t\tlogger.V(3).Info(\"RecycleVolumeOperation: failed to make recycled volume 'Available', we will recycle the volume again\", \"volumeName\", volume.Name, \"err\", err)\n\t\treturn\n\t}\n}","line":{"from":1209,"to":1303}} {"id":100005062,"name":"deleteVolumeOperation","signature":"func (ctrl *PersistentVolumeController) deleteVolumeOperation(ctx context.Context, volume *v1.PersistentVolume) (string, error)","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// deleteVolumeOperation deletes a volume. This method is running in standalone\n// goroutine and already has all necessary locks.\nfunc (ctrl *PersistentVolumeController) deleteVolumeOperation(ctx context.Context, volume *v1.PersistentVolume) (string, error) {\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"DeleteVolumeOperation started\", \"volumeName\", volume.Name)\n\n\t// This method may have been waiting for a volume lock for some time.\n\t// Previous deleteVolumeOperation might just have saved an updated version, so\n\t// read current volume state now.\n\tnewVolume, err := ctrl.kubeClient.CoreV1().PersistentVolumes().Get(ctx, volume.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\tlogger.V(3).Info(\"Error reading persistent volume\", \"volumeName\", volume.Name, \"err\", err)\n\t\treturn \"\", nil\n\t}\n\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.HonorPVReclaimPolicy) {\n\t\tif newVolume.GetDeletionTimestamp() != nil {\n\t\t\tlogger.V(3).Info(\"Volume is already being deleted\", \"volumeName\", volume.Name)\n\t\t\treturn \"\", nil\n\t\t}\n\t}\n\tneedsReclaim, err := ctrl.isVolumeReleased(logger, newVolume)\n\tif err != nil {\n\t\tlogger.V(3).Info(\"Error reading claim for volume\", \"volumeName\", volume.Name, \"err\", err)\n\t\treturn \"\", nil\n\t}\n\tif !needsReclaim {\n\t\tlogger.V(3).Info(\"Volume no longer needs deletion, skipping\", \"volumeName\", volume.Name)\n\t\treturn \"\", nil\n\t}\n\n\tpluginName, deleted, err := ctrl.doDeleteVolume(ctx, volume)\n\tif err != nil {\n\t\t// Delete failed, update the volume and emit an event.\n\t\tlogger.V(3).Info(\"Deletion of volume failed\", \"volumeName\", volume.Name, \"err\", err)\n\t\tif volerr.IsDeletedVolumeInUse(err) {\n\t\t\t// The plugin needs more time, don't mark the volume as Failed\n\t\t\t// and send Normal event only\n\t\t\tctrl.eventRecorder.Event(volume, v1.EventTypeNormal, events.VolumeDelete, err.Error())\n\t\t} else {\n\t\t\t// The plugin failed, mark the volume as Failed and send Warning\n\t\t\t// event\n\t\t\tif _, err := ctrl.updateVolumePhaseWithEvent(ctx, volume, v1.VolumeFailed, v1.EventTypeWarning, events.VolumeFailedDelete, err.Error()); err != nil {\n\t\t\t\tlogger.V(4).Info(\"DeleteVolumeOperation: failed to mark volume as failed\", \"volumeName\", volume.Name, \"err\", err)\n\t\t\t\t// Save failed, retry on the next deletion attempt\n\t\t\t\treturn pluginName, err\n\t\t\t}\n\t\t}\n\n\t\t// Despite the volume being Failed, the controller will retry deleting\n\t\t// the volume in every syncVolume() call.\n\t\treturn pluginName, err\n\t}\n\tif !deleted {\n\t\t// The volume waits for deletion by an external plugin. Do nothing.\n\t\treturn pluginName, nil\n\t}\n\n\tlogger.V(4).Info(\"DeleteVolumeOperation: success\", \"volumeName\", volume.Name)\n\t// Delete the volume\n\tif err = ctrl.kubeClient.CoreV1().PersistentVolumes().Delete(ctx, volume.Name, metav1.DeleteOptions{}); err != nil {\n\t\t// Oops, could not delete the volume and therefore the controller will\n\t\t// try to delete the volume again on next update. We _could_ maintain a\n\t\t// cache of \"recently deleted volumes\" and avoid unnecessary deletion,\n\t\t// this is left out as future optimization.\n\t\tlogger.V(3).Info(\"Failed to delete volume from database\", \"volumeName\", volume.Name, \"err\", err)\n\t\treturn pluginName, nil\n\t}\n\treturn pluginName, nil\n}","line":{"from":1305,"to":1374}} {"id":100005063,"name":"isVolumeReleased","signature":"func (ctrl *PersistentVolumeController) isVolumeReleased(logger klog.Logger, volume *v1.PersistentVolume) (bool, error)","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// isVolumeReleased returns true if given volume is released and can be recycled\n// or deleted, based on its retain policy. I.e. the volume is bound to a claim\n// and the claim does not exist or exists and is bound to different volume.\nfunc (ctrl *PersistentVolumeController) isVolumeReleased(logger klog.Logger, volume *v1.PersistentVolume) (bool, error) {\n\t// A volume needs reclaim if it has ClaimRef and appropriate claim does not\n\t// exist.\n\tif volume.Spec.ClaimRef == nil {\n\t\tlogger.V(4).Info(\"isVolumeReleased: ClaimRef is nil\", \"volumeName\", volume.Name)\n\t\treturn false, nil\n\t}\n\tif volume.Spec.ClaimRef.UID == \"\" {\n\t\t// This is a volume bound by user and the controller has not finished\n\t\t// binding to the real claim yet.\n\t\tlogger.V(4).Info(\"isVolumeReleased: ClaimRef is not bound\", \"volumeName\", volume.Name)\n\t\treturn false, nil\n\t}\n\n\tvar claim *v1.PersistentVolumeClaim\n\tclaimName := claimrefToClaimKey(volume.Spec.ClaimRef)\n\tobj, found, err := ctrl.claims.GetByKey(claimName)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif !found {\n\t\t// Fall through with claim = nil\n\t} else {\n\t\tvar ok bool\n\t\tclaim, ok = obj.(*v1.PersistentVolumeClaim)\n\t\tif !ok {\n\t\t\treturn false, fmt.Errorf(\"cannot convert object from claim cache to claim!?: %#v\", obj)\n\t\t}\n\t}\n\tif claim != nil \u0026\u0026 claim.UID == volume.Spec.ClaimRef.UID {\n\t\t// the claim still exists and has the right UID\n\n\t\tif len(claim.Spec.VolumeName) \u003e 0 \u0026\u0026 claim.Spec.VolumeName != volume.Name {\n\t\t\t// the claim is bound to another PV, this PV *is* released\n\t\t\treturn true, nil\n\t\t}\n\n\t\tlogger.V(4).Info(\"isVolumeReleased: ClaimRef is still valid, volume is not released\", \"volumeName\", volume.Name)\n\t\treturn false, nil\n\t}\n\n\tlogger.V(2).Info(\"isVolumeReleased: volume is released\", \"volumeName\", volume.Name)\n\treturn true, nil\n}","line":{"from":1376,"to":1422}} {"id":100005064,"name":"findPodsByPVCKey","signature":"func (ctrl *PersistentVolumeController) findPodsByPVCKey(key string) ([]*v1.Pod, error)","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"func (ctrl *PersistentVolumeController) findPodsByPVCKey(key string) ([]*v1.Pod, error) {\n\tpods := []*v1.Pod{}\n\tobjs, err := ctrl.podIndexer.ByIndex(common.PodPVCIndex, key)\n\tif err != nil {\n\t\treturn pods, err\n\t}\n\tfor _, obj := range objs {\n\t\tpod, ok := obj.(*v1.Pod)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tpods = append(pods, pod)\n\t}\n\treturn pods, err\n}","line":{"from":1424,"to":1438}} {"id":100005065,"name":"isVolumeUsed","signature":"func (ctrl *PersistentVolumeController) isVolumeUsed(pv *v1.PersistentVolume) ([]string, bool, error)","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// isVolumeUsed returns list of active pods that use given PV.\nfunc (ctrl *PersistentVolumeController) isVolumeUsed(pv *v1.PersistentVolume) ([]string, bool, error) {\n\tif pv.Spec.ClaimRef == nil {\n\t\treturn nil, false, nil\n\t}\n\tpodNames := sets.NewString()\n\tpvcKey := fmt.Sprintf(\"%s/%s\", pv.Spec.ClaimRef.Namespace, pv.Spec.ClaimRef.Name)\n\tpods, err := ctrl.findPodsByPVCKey(pvcKey)\n\tif err != nil {\n\t\treturn nil, false, fmt.Errorf(\"error finding pods by pvc %q: %s\", pvcKey, err)\n\t}\n\tfor _, pod := range pods {\n\t\tif util.IsPodTerminated(pod, pod.Status) {\n\t\t\tcontinue\n\t\t}\n\t\tpodNames.Insert(pod.Namespace + \"/\" + pod.Name)\n\t}\n\treturn podNames.List(), podNames.Len() != 0, nil\n}","line":{"from":1440,"to":1458}} {"id":100005066,"name":"findNonScheduledPodsByPVC","signature":"func (ctrl *PersistentVolumeController) findNonScheduledPodsByPVC(pvc *v1.PersistentVolumeClaim) ([]string, error)","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// findNonScheduledPodsByPVC returns list of non-scheduled active pods that reference given PVC.\nfunc (ctrl *PersistentVolumeController) findNonScheduledPodsByPVC(pvc *v1.PersistentVolumeClaim) ([]string, error) {\n\tpvcKey := fmt.Sprintf(\"%s/%s\", pvc.Namespace, pvc.Name)\n\tpods, err := ctrl.findPodsByPVCKey(pvcKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpodNames := []string{}\n\tfor _, pod := range pods {\n\t\tif util.IsPodTerminated(pod, pod.Status) {\n\t\t\tcontinue\n\t\t}\n\t\tif len(pod.Spec.NodeName) == 0 {\n\t\t\tpodNames = append(podNames, pod.Name)\n\t\t}\n\t}\n\treturn podNames, nil\n}","line":{"from":1460,"to":1477}} {"id":100005067,"name":"doDeleteVolume","signature":"func (ctrl *PersistentVolumeController) doDeleteVolume(ctx context.Context, volume *v1.PersistentVolume) (string, bool, error)","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// doDeleteVolume finds appropriate delete plugin and deletes given volume, returning\n// the volume plugin name. Also, it returns 'true', when the volume was deleted and\n// 'false' when the volume cannot be deleted because the deleter is external. No\n// error should be reported in this case.\nfunc (ctrl *PersistentVolumeController) doDeleteVolume(ctx context.Context, volume *v1.PersistentVolume) (string, bool, error) {\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"doDeleteVolume\", \"volumeName\", volume.Name)\n\tvar err error\n\n\tplugin, err := ctrl.findDeletablePlugin(volume)\n\tif err != nil {\n\t\treturn \"\", false, err\n\t}\n\tif plugin == nil {\n\t\t// External deleter is requested, do nothing\n\t\tlogger.V(3).Info(\"External deleter for volume requested, ignoring\", \"volumeName\", volume.Name)\n\t\treturn \"\", false, nil\n\t}\n\n\t// Plugin found\n\tpluginName := plugin.GetPluginName()\n\tlogger.V(5).Info(\"Found a deleter plugin for volume\", \"pluginName\", pluginName, \"volumeName\", volume.Name)\n\tspec := vol.NewSpecFromPersistentVolume(volume, false)\n\tdeleter, err := plugin.NewDeleter(logger, spec)\n\tif err != nil {\n\t\t// Cannot create deleter\n\t\treturn pluginName, false, fmt.Errorf(\"failed to create deleter for volume %q: %w\", volume.Name, err)\n\t}\n\n\topComplete := util.OperationCompleteHook(pluginName, \"volume_delete\")\n\terr = deleter.Delete()\n\topComplete(volumetypes.CompleteFuncParam{Err: \u0026err})\n\tif err != nil {\n\t\t// Deleter failed\n\t\treturn pluginName, false, err\n\t}\n\tlogger.V(2).Info(\"Volume deleted\", \"volumeName\", volume.Name)\n\t// Remove in-tree delete finalizer on the PV as the volume has been deleted from the underlying storage\n\tif utilfeature.DefaultFeatureGate.Enabled(features.HonorPVReclaimPolicy) {\n\t\terr = ctrl.removeDeletionProtectionFinalizer(ctx, volume)\n\t\tif err != nil {\n\t\t\treturn pluginName, true, err\n\t\t}\n\t}\n\treturn pluginName, true, nil\n}","line":{"from":1479,"to":1524}} {"id":100005068,"name":"removeDeletionProtectionFinalizer","signature":"func (ctrl *PersistentVolumeController) removeDeletionProtectionFinalizer(ctx context.Context, volume *v1.PersistentVolume) error","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"func (ctrl *PersistentVolumeController) removeDeletionProtectionFinalizer(ctx context.Context, volume *v1.PersistentVolume) error {\n\tvar err error\n\tpvUpdateNeeded := false\n\t// Retrieve latest version\n\tlogger := klog.FromContext(ctx)\n\tnewVolume, err := ctrl.kubeClient.CoreV1().PersistentVolumes().Get(ctx, volume.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\tlogger.Error(err, \"Error reading persistent volume\", \"volumeName\", volume.Name)\n\t\treturn err\n\t}\n\tvolume = newVolume\n\tvolumeClone := volume.DeepCopy()\n\tpvFinalizers := volumeClone.Finalizers\n\tif pvFinalizers != nil \u0026\u0026 slice.ContainsString(pvFinalizers, storagehelpers.PVDeletionInTreeProtectionFinalizer, nil) {\n\t\tpvUpdateNeeded = true\n\t\tpvFinalizers = slice.RemoveString(pvFinalizers, storagehelpers.PVDeletionInTreeProtectionFinalizer, nil)\n\t}\n\tif pvUpdateNeeded {\n\t\tvolumeClone.SetFinalizers(pvFinalizers)\n\t\t_, err = ctrl.kubeClient.CoreV1().PersistentVolumes().Update(ctx, volumeClone, metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"persistent volume controller can't update finalizer: %v\", err)\n\t\t}\n\t\t_, err = ctrl.storeVolumeUpdate(logger, volumeClone)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"persistent Volume Controller can't anneal migration finalizer: %v\", err)\n\t\t}\n\t\tlogger.V(2).Info(\"PV in-tree protection finalizer removed from volume\", \"volumeName\", volume.Name)\n\t}\n\treturn nil\n}","line":{"from":1526,"to":1556}} {"id":100005069,"name":"provisionClaim","signature":"func (ctrl *PersistentVolumeController) provisionClaim(ctx context.Context, claim *v1.PersistentVolumeClaim) error","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// provisionClaim starts new asynchronous operation to provision a claim if\n// provisioning is enabled.\nfunc (ctrl *PersistentVolumeController) provisionClaim(ctx context.Context, claim *v1.PersistentVolumeClaim) error {\n\tif !ctrl.enableDynamicProvisioning {\n\t\treturn nil\n\t}\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"provisionClaim: started\", \"PVC\", klog.KObj(claim))\n\topName := fmt.Sprintf(\"provision-%s[%s]\", claimToClaimKey(claim), string(claim.UID))\n\tplugin, storageClass, err := ctrl.findProvisionablePlugin(claim)\n\t// findProvisionablePlugin does not return err for external provisioners\n\tif err != nil {\n\t\tctrl.eventRecorder.Event(claim, v1.EventTypeWarning, events.ProvisioningFailed, err.Error())\n\t\tlogger.Error(err, \"Error finding provisioning plugin for claim\", \"PVC\", klog.KObj(claim))\n\t\t// failed to find the requested provisioning plugin, directly return err for now.\n\t\t// controller will retry the provisioning in every syncUnboundClaim() call\n\t\t// retain the original behavior of returning nil from provisionClaim call\n\t\treturn nil\n\t}\n\tctrl.scheduleOperation(logger, opName, func() error {\n\t\t// create a start timestamp entry in cache for provision operation if no one exists with\n\t\t// key = claimKey, pluginName = provisionerName, operation = \"provision\"\n\t\tclaimKey := claimToClaimKey(claim)\n\t\tctrl.operationTimestamps.AddIfNotExist(claimKey, ctrl.getProvisionerName(plugin, storageClass), \"provision\")\n\t\tvar err error\n\t\tif plugin == nil {\n\t\t\t_, err = ctrl.provisionClaimOperationExternal(ctx, claim, storageClass)\n\t\t} else {\n\t\t\t_, err = ctrl.provisionClaimOperation(ctx, claim, plugin, storageClass)\n\t\t}\n\t\t// if error happened, record an error count metric\n\t\t// timestamp entry will remain in cache until a success binding has happened\n\t\tif err != nil {\n\t\t\tmetrics.RecordMetric(claimKey, \u0026ctrl.operationTimestamps, err)\n\t\t}\n\t\treturn err\n\t})\n\treturn nil\n}","line":{"from":1558,"to":1596}} {"id":100005070,"name":"provisionClaimOperation","signature":"func (ctrl *PersistentVolumeController) provisionClaimOperation(","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// provisionClaimOperation provisions a volume. This method is running in\n// standalone goroutine and already has all necessary locks.\nfunc (ctrl *PersistentVolumeController) provisionClaimOperation(\n\tctx context.Context,\n\tclaim *v1.PersistentVolumeClaim,\n\tplugin vol.ProvisionableVolumePlugin,\n\tstorageClass *storage.StorageClass) (string, error) {\n\tclaimClass := storagehelpers.GetPersistentVolumeClaimClass(claim)\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"provisionClaimOperation started\", \"PVC\", klog.KObj(claim), \"storageClassName\", claimClass)\n\n\t// called from provisionClaim(), in this case, plugin MUST NOT be nil\n\t// NOTE: checks on plugin/storageClass has been saved\n\tpluginName := plugin.GetPluginName()\n\tif pluginName != \"kubernetes.io/csi\" \u0026\u0026 claim.Spec.DataSource != nil {\n\t\t// Only CSI plugin can have a DataSource. Fail the operation\n\t\t// if Datasource in Claim is not nil and it is not a CSI plugin,\n\t\tstrerr := fmt.Sprintf(\"plugin %q is not a CSI plugin. Only CSI plugin can provision a claim with a datasource\", pluginName)\n\t\tlogger.V(2).Info(strerr)\n\t\tctrl.eventRecorder.Event(claim, v1.EventTypeWarning, events.ProvisioningFailed, strerr)\n\t\treturn pluginName, fmt.Errorf(strerr)\n\n\t}\n\tprovisionerName := storageClass.Provisioner\n\tlogger.V(4).Info(\"provisionClaimOperation\", \"PVC\", klog.KObj(claim), \"pluginName\", pluginName, \"provisionerName\", provisionerName)\n\n\t// Add provisioner annotation to be consistent with external provisioner workflow\n\tnewClaim, err := ctrl.setClaimProvisioner(ctx, claim, provisionerName)\n\tif err != nil {\n\t\t// Save failed, the controller will retry in the next sync\n\t\tlogger.V(2).Info(\"Error saving claim\", \"PVC\", klog.KObj(claim), \"err\", err)\n\t\treturn pluginName, err\n\t}\n\tclaim = newClaim\n\n\t// internal provisioning\n\n\t// A previous provisionClaimOperation may just have finished while we were waiting for\n\t// the locks. Check that PV (with deterministic name) hasn't been provisioned\n\t// yet.\n\n\tpvName := ctrl.getProvisionedVolumeNameForClaim(claim)\n\tvolume, err := ctrl.kubeClient.CoreV1().PersistentVolumes().Get(ctx, pvName, metav1.GetOptions{})\n\tif err != nil \u0026\u0026 !apierrors.IsNotFound(err) {\n\t\tlogger.V(3).Info(\"Error reading persistent volume\", \"PV\", klog.KRef(\"\", pvName), \"err\", err)\n\t\treturn pluginName, err\n\t}\n\tif err == nil \u0026\u0026 volume != nil {\n\t\t// Volume has been already provisioned, nothing to do.\n\t\tlogger.V(4).Info(\"provisionClaimOperation: volume already exists, skipping\", \"PVC\", klog.KObj(claim))\n\t\treturn pluginName, err\n\t}\n\n\t// Prepare a claimRef to the claim early (to fail before a volume is\n\t// provisioned)\n\tclaimRef, err := ref.GetReference(scheme.Scheme, claim)\n\tif err != nil {\n\t\tlogger.V(3).Info(\"Unexpected error getting claim reference\", \"err\", err)\n\t\treturn pluginName, err\n\t}\n\n\t// Gather provisioning options\n\ttags := make(map[string]string)\n\ttags[CloudVolumeCreatedForClaimNamespaceTag] = claim.Namespace\n\ttags[CloudVolumeCreatedForClaimNameTag] = claim.Name\n\ttags[CloudVolumeCreatedForVolumeNameTag] = pvName\n\n\toptions := vol.VolumeOptions{\n\t\tPersistentVolumeReclaimPolicy: *storageClass.ReclaimPolicy,\n\t\tMountOptions: storageClass.MountOptions,\n\t\tCloudTags: \u0026tags,\n\t\tClusterName: ctrl.clusterName,\n\t\tPVName: pvName,\n\t\tPVC: claim,\n\t\tParameters: storageClass.Parameters,\n\t}\n\n\t// Refuse to provision if the plugin doesn't support mount options, creation\n\t// of PV would be rejected by validation anyway\n\tif !plugin.SupportsMountOption() \u0026\u0026 len(options.MountOptions) \u003e 0 {\n\t\tstrerr := fmt.Sprintf(\"Mount options are not supported by the provisioner but StorageClass %q has mount options %v\", storageClass.Name, options.MountOptions)\n\t\tlogger.V(2).Info(\"Mount options are not supported by the provisioner but claim's StorageClass has mount options\", \"PVC\", klog.KObj(claim), \"storageClassName\", storageClass.Name, \"options\", options.MountOptions)\n\t\tctrl.eventRecorder.Event(claim, v1.EventTypeWarning, events.ProvisioningFailed, strerr)\n\t\treturn pluginName, fmt.Errorf(\"provisioner %q doesn't support mount options\", plugin.GetPluginName())\n\t}\n\n\t// Provision the volume\n\tprovisioner, err := plugin.NewProvisioner(logger, options)\n\tif err != nil {\n\t\tstrerr := fmt.Sprintf(\"Failed to create provisioner: %v\", err)\n\t\tlogger.V(2).Info(\"Failed to create provisioner for claim with StorageClass\", \"PVC\", klog.KObj(claim), \"storageClassName\", storageClass.Name, \"err\", err)\n\t\tctrl.eventRecorder.Event(claim, v1.EventTypeWarning, events.ProvisioningFailed, strerr)\n\t\treturn pluginName, err\n\t}\n\n\tvar selectedNode *v1.Node = nil\n\tif nodeName, ok := claim.Annotations[storagehelpers.AnnSelectedNode]; ok {\n\t\tselectedNode, err = ctrl.NodeLister.Get(nodeName)\n\t\tif err != nil {\n\t\t\tstrerr := fmt.Sprintf(\"Failed to get target node: %v\", err)\n\t\t\tlogger.V(3).Info(\"Unexpected error getting target node for claim\", \"node\", klog.KRef(\"\", nodeName), \"PVC\", klog.KObj(claim), \"err\", err)\n\t\t\tctrl.eventRecorder.Event(claim, v1.EventTypeWarning, events.ProvisioningFailed, strerr)\n\t\t\treturn pluginName, err\n\t\t}\n\t}\n\tallowedTopologies := storageClass.AllowedTopologies\n\n\topComplete := util.OperationCompleteHook(plugin.GetPluginName(), \"volume_provision\")\n\tvolume, err = provisioner.Provision(selectedNode, allowedTopologies)\n\topComplete(volumetypes.CompleteFuncParam{Err: \u0026err})\n\tif err != nil {\n\t\t// Other places of failure have nothing to do with VolumeScheduling,\n\t\t// so just let controller retry in the next sync. We'll only call func\n\t\t// rescheduleProvisioning here when the underlying provisioning actually failed.\n\t\tctrl.rescheduleProvisioning(ctx, claim)\n\n\t\tstrerr := fmt.Sprintf(\"Failed to provision volume with StorageClass %q: %v\", storageClass.Name, err)\n\t\tlogger.V(2).Info(\"Failed to provision volume for claim with StorageClass\", \"PVC\", klog.KObj(claim), \"storageClassName\", storageClass.Name, \"err\", err)\n\t\tctrl.eventRecorder.Event(claim, v1.EventTypeWarning, events.ProvisioningFailed, strerr)\n\t\treturn pluginName, err\n\t}\n\n\tlogger.V(3).Info(\"Volume for claim created\", \"PVC\", klog.KObj(claim), \"volumeName\", volume.Name)\n\n\t// Create Kubernetes PV object for the volume.\n\tif volume.Name == \"\" {\n\t\tvolume.Name = pvName\n\t}\n\t// Bind it to the claim\n\tvolume.Spec.ClaimRef = claimRef\n\tvolume.Status.Phase = v1.VolumeBound\n\tvolume.Spec.StorageClassName = claimClass\n\n\t// Add AnnBoundByController (used in deleting the volume)\n\tmetav1.SetMetaDataAnnotation(\u0026volume.ObjectMeta, storagehelpers.AnnBoundByController, \"yes\")\n\tmetav1.SetMetaDataAnnotation(\u0026volume.ObjectMeta, storagehelpers.AnnDynamicallyProvisioned, plugin.GetPluginName())\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.HonorPVReclaimPolicy) {\n\t\tif volume.Spec.PersistentVolumeReclaimPolicy == v1.PersistentVolumeReclaimDelete {\n\t\t\t// Add In-Tree protection finalizer here only when the reclaim policy is `Delete`\n\t\t\tvolume.SetFinalizers([]string{storagehelpers.PVDeletionInTreeProtectionFinalizer})\n\t\t}\n\t}\n\n\t// Try to create the PV object several times\n\tfor i := 0; i \u003c ctrl.createProvisionedPVRetryCount; i++ {\n\t\tlogger.V(4).Info(\"provisionClaimOperation: trying to save volume\", \"PVC\", klog.KObj(claim), \"volumeName\", volume.Name)\n\t\tvar newVol *v1.PersistentVolume\n\t\tif newVol, err = ctrl.kubeClient.CoreV1().PersistentVolumes().Create(ctx, volume, metav1.CreateOptions{}); err == nil || apierrors.IsAlreadyExists(err) {\n\t\t\t// Save succeeded.\n\t\t\tif err != nil {\n\t\t\t\tlogger.V(3).Info(\"Volume for claim already exists, reusing\", \"PVC\", klog.KObj(claim), \"volumeName\", volume.Name)\n\t\t\t\terr = nil\n\t\t\t} else {\n\t\t\t\tlogger.V(3).Info(\"Volume for claim saved\", \"PVC\", klog.KObj(claim), \"volumeName\", volume.Name)\n\n\t\t\t\t_, updateErr := ctrl.storeVolumeUpdate(logger, newVol)\n\t\t\t\tif updateErr != nil {\n\t\t\t\t\t// We will get an \"volume added\" event soon, this is not a big error\n\t\t\t\t\tlogger.V(4).Info(\"provisionClaimOperation: cannot update internal cache\", \"volumeName\", volume.Name, \"err\", updateErr)\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t// Save failed, try again after a while.\n\t\tlogger.V(3).Info(\"Failed to save volume for claim\", \"PVC\", klog.KObj(claim), \"volumeName\", volume.Name, \"err\", err)\n\t\ttime.Sleep(ctrl.createProvisionedPVInterval)\n\t}\n\n\tif err != nil {\n\t\t// Save failed. Now we have a storage asset outside of Kubernetes,\n\t\t// but we don't have appropriate PV object for it.\n\t\t// Emit some event here and try to delete the storage asset several\n\t\t// times.\n\t\tstrerr := fmt.Sprintf(\"Error creating provisioned PV object for claim %s: %v. Deleting the volume.\", claimToClaimKey(claim), err)\n\t\tlogger.V(3).Info(strerr)\n\t\tctrl.eventRecorder.Event(claim, v1.EventTypeWarning, events.ProvisioningFailed, strerr)\n\n\t\tvar deleteErr error\n\t\tvar deleted bool\n\t\tfor i := 0; i \u003c ctrl.createProvisionedPVRetryCount; i++ {\n\t\t\t_, deleted, deleteErr = ctrl.doDeleteVolume(ctx, volume)\n\t\t\tif deleteErr == nil \u0026\u0026 deleted {\n\t\t\t\t// Delete succeeded\n\t\t\t\tlogger.V(4).Info(\"provisionClaimOperation: cleaning volume succeeded\", \"PVC\", klog.KObj(claim), \"volumeName\", volume.Name)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif !deleted {\n\t\t\t\t// This is unreachable code, the volume was provisioned by an\n\t\t\t\t// internal plugin and therefore there MUST be an internal\n\t\t\t\t// plugin that deletes it.\n\t\t\t\tlogger.Error(nil, \"Error finding internal deleter for volume plugin\", \"plugin\", plugin.GetPluginName())\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// Delete failed, try again after a while.\n\t\t\tlogger.V(3).Info(\"Failed to delete volume\", \"volumeName\", volume.Name, \"err\", deleteErr)\n\t\t\ttime.Sleep(ctrl.createProvisionedPVInterval)\n\t\t}\n\n\t\tif deleteErr != nil {\n\t\t\t// Delete failed several times. There is an orphaned volume and there\n\t\t\t// is nothing we can do about it.\n\t\t\tstrerr := fmt.Sprintf(\"Error cleaning provisioned volume for claim %s: %v. Please delete manually.\", claimToClaimKey(claim), deleteErr)\n\t\t\tlogger.V(2).Info(strerr)\n\t\t\tctrl.eventRecorder.Event(claim, v1.EventTypeWarning, events.ProvisioningCleanupFailed, strerr)\n\t\t}\n\t} else {\n\t\tlogger.V(2).Info(\"Volume provisioned for claim\", \"PVC\", klog.KObj(claim), \"volumeName\", volume.Name)\n\t\tmsg := fmt.Sprintf(\"Successfully provisioned volume %s using %s\", volume.Name, plugin.GetPluginName())\n\t\tctrl.eventRecorder.Event(claim, v1.EventTypeNormal, events.ProvisioningSucceeded, msg)\n\t}\n\treturn pluginName, nil\n}","line":{"from":1598,"to":1810}} {"id":100005071,"name":"provisionClaimOperationExternal","signature":"func (ctrl *PersistentVolumeController) provisionClaimOperationExternal(","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// provisionClaimOperationExternal provisions a volume using external provisioner async-ly\n// This method will be running in a standalone go-routine scheduled in \"provisionClaim\"\nfunc (ctrl *PersistentVolumeController) provisionClaimOperationExternal(\n\tctx context.Context,\n\tclaim *v1.PersistentVolumeClaim,\n\tstorageClass *storage.StorageClass) (string, error) {\n\tclaimClass := storagehelpers.GetPersistentVolumeClaimClass(claim)\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"provisionClaimOperationExternal started\", \"PVC\", klog.KObj(claim), \"storageClassName\", claimClass)\n\t// Set provisionerName to external provisioner name by setClaimProvisioner\n\tvar err error\n\tprovisionerName := storageClass.Provisioner\n\tif ctrl.csiMigratedPluginManager.IsMigrationEnabledForPlugin(storageClass.Provisioner) {\n\t\t// update the provisioner name to use the migrated CSI plugin name\n\t\tprovisionerName, err = ctrl.translator.GetCSINameFromInTreeName(storageClass.Provisioner)\n\t\tif err != nil {\n\t\t\tstrerr := fmt.Sprintf(\"error getting CSI name for In tree plugin %s: %v\", storageClass.Provisioner, err)\n\t\t\tlogger.V(2).Info(strerr)\n\t\t\tctrl.eventRecorder.Event(claim, v1.EventTypeWarning, events.ProvisioningFailed, strerr)\n\t\t\treturn provisionerName, err\n\t\t}\n\t}\n\t// Add provisioner annotation so external provisioners know when to start\n\tnewClaim, err := ctrl.setClaimProvisioner(ctx, claim, provisionerName)\n\tif err != nil {\n\t\t// Save failed, the controller will retry in the next sync\n\t\tlogger.V(2).Info(\"Error saving claim\", \"PVC\", klog.KObj(claim), \"err\", err)\n\t\treturn provisionerName, err\n\t}\n\tclaim = newClaim\n\tmsg := fmt.Sprintf(\"waiting for a volume to be created, either by external provisioner %q or manually created by system administrator\", provisionerName)\n\t// External provisioner has been requested for provisioning the volume\n\t// Report an event and wait for external provisioner to finish\n\tctrl.eventRecorder.Event(claim, v1.EventTypeNormal, events.ExternalProvisioning, msg)\n\tlogger.V(3).Info(\"provisionClaimOperationExternal provisioning claim\", \"PVC\", klog.KObj(claim), \"msg\", msg)\n\t// return provisioner name here for metric reporting\n\treturn provisionerName, nil\n}","line":{"from":1812,"to":1849}} {"id":100005072,"name":"rescheduleProvisioning","signature":"func (ctrl *PersistentVolumeController) rescheduleProvisioning(ctx context.Context, claim *v1.PersistentVolumeClaim)","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// rescheduleProvisioning signal back to the scheduler to retry dynamic provisioning\n// by removing the AnnSelectedNode annotation\nfunc (ctrl *PersistentVolumeController) rescheduleProvisioning(ctx context.Context, claim *v1.PersistentVolumeClaim) {\n\tif _, ok := claim.Annotations[storagehelpers.AnnSelectedNode]; !ok {\n\t\t// Provisioning not triggered by the scheduler, skip\n\t\treturn\n\t}\n\n\t// The claim from method args can be pointing to watcher cache. We must not\n\t// modify these, therefore create a copy.\n\tnewClaim := claim.DeepCopy()\n\tdelete(newClaim.Annotations, storagehelpers.AnnSelectedNode)\n\t// Try to update the PVC object\n\tlogger := klog.FromContext(ctx)\n\tif _, err := ctrl.kubeClient.CoreV1().PersistentVolumeClaims(newClaim.Namespace).Update(ctx, newClaim, metav1.UpdateOptions{}); err != nil {\n\t\tlogger.V(4).Info(\"Failed to delete annotation 'storagehelpers.AnnSelectedNode' for PersistentVolumeClaim\", \"PVC\", klog.KObj(newClaim), \"err\", err)\n\t\treturn\n\t}\n\tif _, err := ctrl.storeClaimUpdate(logger, newClaim); err != nil {\n\t\t// We will get an \"claim updated\" event soon, this is not a big error\n\t\tlogger.V(4).Info(\"Updating PersistentVolumeClaim: cannot update internal cache\", \"PVC\", klog.KObj(newClaim), \"err\", err)\n\t}\n}","line":{"from":1851,"to":1873}} {"id":100005073,"name":"getProvisionedVolumeNameForClaim","signature":"func (ctrl *PersistentVolumeController) getProvisionedVolumeNameForClaim(claim *v1.PersistentVolumeClaim) string","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// getProvisionedVolumeNameForClaim returns PV.Name for the provisioned volume.\n// The name must be unique.\nfunc (ctrl *PersistentVolumeController) getProvisionedVolumeNameForClaim(claim *v1.PersistentVolumeClaim) string {\n\treturn \"pvc-\" + string(claim.UID)\n}","line":{"from":1875,"to":1879}} {"id":100005074,"name":"scheduleOperation","signature":"func (ctrl *PersistentVolumeController) scheduleOperation(logger klog.Logger, operationName string, operation func() error)","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// scheduleOperation starts given asynchronous operation on given volume. It\n// makes sure the operation is already not running.\nfunc (ctrl *PersistentVolumeController) scheduleOperation(logger klog.Logger, operationName string, operation func() error) {\n\tlogger.V(4).Info(\"scheduleOperation\", \"operationName\", operationName)\n\n\t// Poke test code that an operation is just about to get started.\n\tif ctrl.preOperationHook != nil {\n\t\tctrl.preOperationHook(operationName)\n\t}\n\n\terr := ctrl.runningOperations.Run(operationName, operation)\n\tif err != nil {\n\t\tswitch {\n\t\tcase goroutinemap.IsAlreadyExists(err):\n\t\t\tlogger.V(4).Info(\"Operation is already running, skipping\", \"operationName\", operationName)\n\t\tcase exponentialbackoff.IsExponentialBackoff(err):\n\t\t\tlogger.V(4).Info(\"Operation postponed due to exponential backoff\", \"operationName\", operationName)\n\t\tdefault:\n\t\t\tlogger.Error(err, \"Error scheduling operation\", \"operationName\", operationName)\n\t\t}\n\t}\n}","line":{"from":1881,"to":1902}} {"id":100005075,"name":"newRecyclerEventRecorder","signature":"func (ctrl *PersistentVolumeController) newRecyclerEventRecorder(volume *v1.PersistentVolume) recyclerclient.RecycleEventRecorder","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// newRecyclerEventRecorder returns a RecycleEventRecorder that sends all events\n// to given volume.\nfunc (ctrl *PersistentVolumeController) newRecyclerEventRecorder(volume *v1.PersistentVolume) recyclerclient.RecycleEventRecorder {\n\treturn func(eventtype, message string) {\n\t\tctrl.eventRecorder.Eventf(volume, eventtype, events.RecyclerPod, \"Recycler pod: %s\", message)\n\t}\n}","line":{"from":1904,"to":1910}} {"id":100005076,"name":"findProvisionablePlugin","signature":"func (ctrl *PersistentVolumeController) findProvisionablePlugin(claim *v1.PersistentVolumeClaim) (vol.ProvisionableVolumePlugin, *storage.StorageClass, error)","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// findProvisionablePlugin finds a provisioner plugin for a given claim.\n// It returns either the provisioning plugin or nil when an external\n// provisioner is requested.\nfunc (ctrl *PersistentVolumeController) findProvisionablePlugin(claim *v1.PersistentVolumeClaim) (vol.ProvisionableVolumePlugin, *storage.StorageClass, error) {\n\t// provisionClaim() which leads here is never called with claimClass==\"\", we\n\t// can save some checks.\n\tclaimClass := storagehelpers.GetPersistentVolumeClaimClass(claim)\n\tclass, err := ctrl.classLister.Get(claimClass)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Find a plugin for the class\n\tif ctrl.csiMigratedPluginManager.IsMigrationEnabledForPlugin(class.Provisioner) {\n\t\t// CSI migration scenario - do not depend on in-tree plugin\n\t\treturn nil, class, nil\n\t}\n\tplugin, err := ctrl.volumePluginMgr.FindProvisionablePluginByName(class.Provisioner)\n\tif err != nil {\n\t\tif !strings.HasPrefix(class.Provisioner, \"kubernetes.io/\") {\n\t\t\t// External provisioner is requested, do not report error\n\t\t\treturn nil, class, nil\n\t\t}\n\t\treturn nil, class, err\n\t}\n\treturn plugin, class, nil\n}","line":{"from":1912,"to":1938}} {"id":100005077,"name":"findDeletablePlugin","signature":"func (ctrl *PersistentVolumeController) findDeletablePlugin(volume *v1.PersistentVolume) (vol.DeletableVolumePlugin, error)","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// findDeletablePlugin finds a deleter plugin for a given volume. It returns\n// either the deleter plugin or nil when an external deleter is requested.\nfunc (ctrl *PersistentVolumeController) findDeletablePlugin(volume *v1.PersistentVolume) (vol.DeletableVolumePlugin, error) {\n\t// Find a plugin. Try to find the same plugin that provisioned the volume\n\tvar plugin vol.DeletableVolumePlugin\n\tif metav1.HasAnnotation(volume.ObjectMeta, storagehelpers.AnnDynamicallyProvisioned) {\n\t\tprovisionPluginName := volume.Annotations[storagehelpers.AnnDynamicallyProvisioned]\n\t\tif provisionPluginName != \"\" {\n\t\t\tplugin, err := ctrl.volumePluginMgr.FindDeletablePluginByName(provisionPluginName)\n\t\t\tif err != nil {\n\t\t\t\tif !strings.HasPrefix(provisionPluginName, \"kubernetes.io/\") {\n\t\t\t\t\t// External provisioner is requested, do not report error\n\t\t\t\t\treturn nil, nil\n\t\t\t\t}\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn plugin, nil\n\t\t}\n\t}\n\n\t// The plugin that provisioned the volume was not found or the volume\n\t// was not dynamically provisioned. Try to find a plugin by spec.\n\tspec := vol.NewSpecFromPersistentVolume(volume, false)\n\tplugin, err := ctrl.volumePluginMgr.FindDeletablePluginBySpec(spec)\n\tif err != nil {\n\t\t// No deleter found. Emit an event and mark the volume Failed.\n\t\treturn nil, fmt.Errorf(\"error getting deleter volume plugin for volume %q: %w\", volume.Name, err)\n\t}\n\treturn plugin, nil\n}","line":{"from":1940,"to":1969}} {"id":100005078,"name":"getProvisionerNameFromVolume","signature":"func (ctrl *PersistentVolumeController) getProvisionerNameFromVolume(volume *v1.PersistentVolume) string","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// obtain provisioner/deleter name for a volume\nfunc (ctrl *PersistentVolumeController) getProvisionerNameFromVolume(volume *v1.PersistentVolume) string {\n\tplugin, err := ctrl.findDeletablePlugin(volume)\n\tif err != nil {\n\t\treturn \"N/A\"\n\t}\n\tif plugin != nil {\n\t\treturn plugin.GetPluginName()\n\t}\n\t// If reached here, Either an external provisioner was used for provisioning\n\t// or a plugin has been migrated to CSI.\n\t// If an external provisioner was used, i.e., plugin == nil, instead of using\n\t// the AnnDynamicallyProvisioned annotation value, use the storageClass's Provisioner\n\t// field to avoid explosion of the metric in the cases like local storage provisioner\n\t// tagging a volume with arbitrary provisioner names\n\tstorageClass := storagehelpers.GetPersistentVolumeClass(volume)\n\tclass, err := ctrl.classLister.Get(storageClass)\n\tif err != nil {\n\t\treturn \"N/A\"\n\t}\n\tif ctrl.csiMigratedPluginManager.IsMigrationEnabledForPlugin(class.Provisioner) {\n\t\tprovisionerName, err := ctrl.translator.GetCSINameFromInTreeName(class.Provisioner)\n\t\tif err != nil {\n\t\t\treturn \"N/A\"\n\t\t}\n\t\treturn provisionerName\n\t}\n\treturn class.Provisioner\n}","line":{"from":1971,"to":1999}} {"id":100005079,"name":"getProvisionerName","signature":"func (ctrl *PersistentVolumeController) getProvisionerName(plugin vol.ProvisionableVolumePlugin, storageClass *storage.StorageClass) string","file":"pkg/controller/volume/persistentvolume/pv_controller.go","code":"// obtain plugin/external provisioner name from plugin and storage class for timestamp logging purposes\nfunc (ctrl *PersistentVolumeController) getProvisionerName(plugin vol.ProvisionableVolumePlugin, storageClass *storage.StorageClass) string {\n\t// non CSI-migrated in-tree plugin, returns the plugin's name\n\tif plugin != nil {\n\t\treturn plugin.GetPluginName()\n\t}\n\tif ctrl.csiMigratedPluginManager.IsMigrationEnabledForPlugin(storageClass.Provisioner) {\n\t\t// get the name of the CSI plugin that the in-tree storage class\n\t\t// provisioner has migrated to\n\t\tprovisionerName, err := ctrl.translator.GetCSINameFromInTreeName(storageClass.Provisioner)\n\t\tif err != nil {\n\t\t\treturn \"N/A\"\n\t\t}\n\t\treturn provisionerName\n\t}\n\treturn storageClass.Provisioner\n}","line":{"from":2001,"to":2017}} {"id":100005080,"name":"NewController","signature":"func NewController(ctx context.Context, p ControllerParameters) (*PersistentVolumeController, error)","file":"pkg/controller/volume/persistentvolume/pv_controller_base.go","code":"// NewController creates a new PersistentVolume controller\nfunc NewController(ctx context.Context, p ControllerParameters) (*PersistentVolumeController, error) {\n\teventRecorder := p.EventRecorder\n\tvar eventBroadcaster record.EventBroadcaster\n\tif eventRecorder == nil {\n\t\teventBroadcaster = record.NewBroadcaster()\n\t\teventRecorder = eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"persistentvolume-controller\"})\n\t}\n\n\tcontroller := \u0026PersistentVolumeController{\n\t\tvolumes: newPersistentVolumeOrderedIndex(),\n\t\tclaims: cache.NewStore(cache.DeletionHandlingMetaNamespaceKeyFunc),\n\t\tkubeClient: p.KubeClient,\n\t\teventBroadcaster: eventBroadcaster,\n\t\teventRecorder: eventRecorder,\n\t\trunningOperations: goroutinemap.NewGoRoutineMap(true /* exponentialBackOffOnError */),\n\t\tcloud: p.Cloud,\n\t\tenableDynamicProvisioning: p.EnableDynamicProvisioning,\n\t\tclusterName: p.ClusterName,\n\t\tcreateProvisionedPVRetryCount: createProvisionedPVRetryCount,\n\t\tcreateProvisionedPVInterval: createProvisionedPVInterval,\n\t\tclaimQueue: workqueue.NewNamed(\"claims\"),\n\t\tvolumeQueue: workqueue.NewNamed(\"volumes\"),\n\t\tresyncPeriod: p.SyncPeriod,\n\t\toperationTimestamps: metrics.NewOperationStartTimeCache(),\n\t}\n\n\t// Prober is nil because PV is not aware of Flexvolume.\n\tif err := controller.volumePluginMgr.InitPlugins(p.VolumePlugins, nil /* prober */, controller); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not initialize volume plugins for PersistentVolume Controller: %w\", err)\n\t}\n\n\tp.VolumeInformer.Informer().AddEventHandler(\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: func(obj interface{}) { controller.enqueueWork(ctx, controller.volumeQueue, obj) },\n\t\t\tUpdateFunc: func(oldObj, newObj interface{}) { controller.enqueueWork(ctx, controller.volumeQueue, newObj) },\n\t\t\tDeleteFunc: func(obj interface{}) { controller.enqueueWork(ctx, controller.volumeQueue, obj) },\n\t\t},\n\t)\n\tcontroller.volumeLister = p.VolumeInformer.Lister()\n\tcontroller.volumeListerSynced = p.VolumeInformer.Informer().HasSynced\n\n\tp.ClaimInformer.Informer().AddEventHandler(\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: func(obj interface{}) { controller.enqueueWork(ctx, controller.claimQueue, obj) },\n\t\t\tUpdateFunc: func(oldObj, newObj interface{}) { controller.enqueueWork(ctx, controller.claimQueue, newObj) },\n\t\t\tDeleteFunc: func(obj interface{}) { controller.enqueueWork(ctx, controller.claimQueue, obj) },\n\t\t},\n\t)\n\tcontroller.claimLister = p.ClaimInformer.Lister()\n\tcontroller.claimListerSynced = p.ClaimInformer.Informer().HasSynced\n\n\tcontroller.classLister = p.ClassInformer.Lister()\n\tcontroller.classListerSynced = p.ClassInformer.Informer().HasSynced\n\tcontroller.podLister = p.PodInformer.Lister()\n\tcontroller.podIndexer = p.PodInformer.Informer().GetIndexer()\n\tcontroller.podListerSynced = p.PodInformer.Informer().HasSynced\n\tcontroller.NodeLister = p.NodeInformer.Lister()\n\tcontroller.NodeListerSynced = p.NodeInformer.Informer().HasSynced\n\n\t// This custom indexer will index pods by its PVC keys. Then we don't need\n\t// to iterate all pods every time to find pods which reference given PVC.\n\tif err := common.AddPodPVCIndexerIfNotPresent(controller.podIndexer); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not initialize attach detach controller: %w\", err)\n\t}\n\n\tcsiTranslator := csitrans.New()\n\tcontroller.translator = csiTranslator\n\tcontroller.csiMigratedPluginManager = csimigration.NewPluginManager(csiTranslator, utilfeature.DefaultFeatureGate)\n\n\tcontroller.filteredDialOptions = p.FilteredDialOptions\n\n\treturn controller, nil\n}","line":{"from":81,"to":154}} {"id":100005081,"name":"initializeCaches","signature":"func (ctrl *PersistentVolumeController) initializeCaches(logger klog.Logger, volumeLister corelisters.PersistentVolumeLister, claimLister corelisters.PersistentVolumeClaimLister)","file":"pkg/controller/volume/persistentvolume/pv_controller_base.go","code":"// initializeCaches fills all controller caches with initial data from etcd in\n// order to have the caches already filled when first addClaim/addVolume to\n// perform initial synchronization of the controller.\nfunc (ctrl *PersistentVolumeController) initializeCaches(logger klog.Logger, volumeLister corelisters.PersistentVolumeLister, claimLister corelisters.PersistentVolumeClaimLister) {\n\tvolumeList, err := volumeLister.List(labels.Everything())\n\tif err != nil {\n\t\tlogger.Error(err, \"PersistentVolumeController can't initialize caches\")\n\t\treturn\n\t}\n\tfor _, volume := range volumeList {\n\t\tvolumeClone := volume.DeepCopy()\n\t\tif _, err = ctrl.storeVolumeUpdate(logger, volumeClone); err != nil {\n\t\t\tlogger.Error(err, \"Error updating volume cache\")\n\t\t}\n\t}\n\n\tclaimList, err := claimLister.List(labels.Everything())\n\tif err != nil {\n\t\tlogger.Error(err, \"PersistentVolumeController can't initialize caches\")\n\t\treturn\n\t}\n\tfor _, claim := range claimList {\n\t\tif _, err = ctrl.storeClaimUpdate(logger, claim.DeepCopy()); err != nil {\n\t\t\tlogger.Error(err, \"Error updating claim cache\")\n\t\t}\n\t}\n\tlogger.V(4).Info(\"Controller initialized\")\n}","line":{"from":156,"to":183}} {"id":100005082,"name":"enqueueWork","signature":"func (ctrl *PersistentVolumeController) enqueueWork(ctx context.Context, queue workqueue.Interface, obj interface{})","file":"pkg/controller/volume/persistentvolume/pv_controller_base.go","code":"// enqueueWork adds volume or claim to given work queue.\nfunc (ctrl *PersistentVolumeController) enqueueWork(ctx context.Context, queue workqueue.Interface, obj interface{}) {\n\t// Beware of \"xxx deleted\" events\n\tlogger := klog.FromContext(ctx)\n\tif unknown, ok := obj.(cache.DeletedFinalStateUnknown); ok \u0026\u0026 unknown.Obj != nil {\n\t\tobj = unknown.Obj\n\t}\n\tobjName, err := controller.KeyFunc(obj)\n\tif err != nil {\n\t\tlogger.Error(err, \"Failed to get key from object\")\n\t\treturn\n\t}\n\tlogger.V(5).Info(\"Enqueued for sync\", \"objName\", objName)\n\tqueue.Add(objName)\n}","line":{"from":185,"to":199}} {"id":100005083,"name":"storeVolumeUpdate","signature":"func (ctrl *PersistentVolumeController) storeVolumeUpdate(logger klog.Logger, volume interface{}) (bool, error)","file":"pkg/controller/volume/persistentvolume/pv_controller_base.go","code":"func (ctrl *PersistentVolumeController) storeVolumeUpdate(logger klog.Logger, volume interface{}) (bool, error) {\n\treturn storeObjectUpdate(logger, ctrl.volumes.store, volume, \"volume\")\n}","line":{"from":201,"to":203}} {"id":100005084,"name":"storeClaimUpdate","signature":"func (ctrl *PersistentVolumeController) storeClaimUpdate(logger klog.Logger, claim interface{}) (bool, error)","file":"pkg/controller/volume/persistentvolume/pv_controller_base.go","code":"func (ctrl *PersistentVolumeController) storeClaimUpdate(logger klog.Logger, claim interface{}) (bool, error) {\n\treturn storeObjectUpdate(logger, ctrl.claims, claim, \"claim\")\n}","line":{"from":205,"to":207}} {"id":100005085,"name":"updateVolume","signature":"func (ctrl *PersistentVolumeController) updateVolume(ctx context.Context, volume *v1.PersistentVolume)","file":"pkg/controller/volume/persistentvolume/pv_controller_base.go","code":"// updateVolume runs in worker thread and handles \"volume added\",\n// \"volume updated\" and \"periodic sync\" events.\nfunc (ctrl *PersistentVolumeController) updateVolume(ctx context.Context, volume *v1.PersistentVolume) {\n\t// Store the new volume version in the cache and do not process it if this\n\t// is an old version.\n\tlogger := klog.FromContext(ctx)\n\tnew, err := ctrl.storeVolumeUpdate(logger, volume)\n\tif err != nil {\n\t\tlogger.Error(err, \"\")\n\t}\n\tif !new {\n\t\treturn\n\t}\n\n\terr = ctrl.syncVolume(ctx, volume)\n\tif err != nil {\n\t\tif errors.IsConflict(err) {\n\t\t\t// Version conflict error happens quite often and the controller\n\t\t\t// recovers from it easily.\n\t\t\tlogger.V(3).Info(\"Could not sync volume\", \"volumeName\", volume.Name, \"err\", err)\n\t\t} else {\n\t\t\tlogger.Error(err, \"Could not sync volume\", \"volumeName\", volume.Name, \"err\", err)\n\t\t}\n\t}\n}","line":{"from":209,"to":233}} {"id":100005086,"name":"deleteVolume","signature":"func (ctrl *PersistentVolumeController) deleteVolume(ctx context.Context, volume *v1.PersistentVolume)","file":"pkg/controller/volume/persistentvolume/pv_controller_base.go","code":"// deleteVolume runs in worker thread and handles \"volume deleted\" event.\nfunc (ctrl *PersistentVolumeController) deleteVolume(ctx context.Context, volume *v1.PersistentVolume) {\n\tlogger := klog.FromContext(ctx)\n\tif err := ctrl.volumes.store.Delete(volume); err != nil {\n\t\tlogger.Error(err, \"Volume deletion encountered\", \"volumeName\", volume.Name)\n\t} else {\n\t\tlogger.V(4).Info(\"volume deleted\", \"volumeName\", volume.Name)\n\t}\n\t// record deletion metric if a deletion start timestamp is in the cache\n\t// the following calls will be a no-op if there is nothing for this volume in the cache\n\t// end of timestamp cache entry lifecycle, \"RecordMetric\" will do the clean\n\tmetrics.RecordMetric(volume.Name, \u0026ctrl.operationTimestamps, nil)\n\n\tif volume.Spec.ClaimRef == nil {\n\t\treturn\n\t}\n\t// sync the claim when its volume is deleted. Explicitly syncing the\n\t// claim here in response to volume deletion prevents the claim from\n\t// waiting until the next sync period for its Lost status.\n\tclaimKey := claimrefToClaimKey(volume.Spec.ClaimRef)\n\tlogger.V(5).Info(\"deleteVolume: scheduling sync of claim\", \"PVC\", klog.KRef(volume.Spec.ClaimRef.Namespace, volume.Spec.ClaimRef.Name), \"volumeName\", volume.Name)\n\tctrl.claimQueue.Add(claimKey)\n}","line":{"from":235,"to":257}} {"id":100005087,"name":"updateClaim","signature":"func (ctrl *PersistentVolumeController) updateClaim(ctx context.Context, claim *v1.PersistentVolumeClaim)","file":"pkg/controller/volume/persistentvolume/pv_controller_base.go","code":"// updateClaim runs in worker thread and handles \"claim added\",\n// \"claim updated\" and \"periodic sync\" events.\nfunc (ctrl *PersistentVolumeController) updateClaim(ctx context.Context, claim *v1.PersistentVolumeClaim) {\n\t// Store the new claim version in the cache and do not process it if this is\n\t// an old version.\n\tlogger := klog.FromContext(ctx)\n\tnew, err := ctrl.storeClaimUpdate(logger, claim)\n\tif err != nil {\n\t\tlogger.Error(err, \"\")\n\t}\n\tif !new {\n\t\treturn\n\t}\n\terr = ctrl.syncClaim(ctx, claim)\n\tif err != nil {\n\t\tif errors.IsConflict(err) {\n\t\t\t// Version conflict error happens quite often and the controller\n\t\t\t// recovers from it easily.\n\t\t\tlogger.V(3).Info(\"Could not sync claim\", \"PVC\", klog.KObj(claim), \"err\", err)\n\t\t} else {\n\t\t\tlogger.Error(err, \"Could not sync volume\", \"PVC\", klog.KObj(claim))\n\t\t}\n\t}\n}","line":{"from":259,"to":282}} {"id":100005088,"name":"deleteClaim","signature":"func (ctrl *PersistentVolumeController) deleteClaim(ctx context.Context, claim *v1.PersistentVolumeClaim)","file":"pkg/controller/volume/persistentvolume/pv_controller_base.go","code":"// Unit test [5-5] [5-6] [5-7]\n// deleteClaim runs in worker thread and handles \"claim deleted\" event.\nfunc (ctrl *PersistentVolumeController) deleteClaim(ctx context.Context, claim *v1.PersistentVolumeClaim) {\n\tlogger := klog.FromContext(ctx)\n\tif err := ctrl.claims.Delete(claim); err != nil {\n\t\tlogger.Error(err, \"Claim deletion encountered\", \"PVC\", klog.KObj(claim))\n\t}\n\tclaimKey := claimToClaimKey(claim)\n\tlogger.V(4).Info(\"Claim deleted\", \"PVC\", klog.KObj(claim))\n\t// clean any possible unfinished provision start timestamp from cache\n\t// Unit test [5-8] [5-9]\n\tctrl.operationTimestamps.Delete(claimKey)\n\n\tvolumeName := claim.Spec.VolumeName\n\tif volumeName == \"\" {\n\t\tlogger.V(5).Info(\"deleteClaim: volume not bound\", \"PVC\", klog.KObj(claim))\n\t\treturn\n\t}\n\n\t// sync the volume when its claim is deleted. Explicitly sync'ing the\n\t// volume here in response to claim deletion prevents the volume from\n\t// waiting until the next sync period for its Release.\n\tlogger.V(5).Info(\"deleteClaim: scheduling sync of volume\", \"PVC\", klog.KObj(claim), \"volumeName\", volumeName)\n\tctrl.volumeQueue.Add(volumeName)\n}","line":{"from":284,"to":308}} {"id":100005089,"name":"Run","signature":"func (ctrl *PersistentVolumeController) Run(ctx context.Context)","file":"pkg/controller/volume/persistentvolume/pv_controller_base.go","code":"// Run starts all of this controller's control loops\nfunc (ctrl *PersistentVolumeController) Run(ctx context.Context) {\n\tdefer utilruntime.HandleCrash()\n\tdefer ctrl.claimQueue.ShutDown()\n\tdefer ctrl.volumeQueue.ShutDown()\n\n\t// Start events processing pipeline.\n\tif ctrl.eventBroadcaster != nil {\n\t\tctrl.eventBroadcaster.StartStructuredLogging(0)\n\t\tctrl.eventBroadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: ctrl.kubeClient.CoreV1().Events(\"\")})\n\t\tdefer ctrl.eventBroadcaster.Shutdown()\n\t}\n\tlogger := klog.FromContext(ctx)\n\tlogger.Info(\"Starting persistent volume controller\")\n\tdefer logger.Info(\"Shutting down persistent volume controller\")\n\n\tif !cache.WaitForNamedCacheSync(\"persistent volume\", ctx.Done(), ctrl.volumeListerSynced, ctrl.claimListerSynced, ctrl.classListerSynced, ctrl.podListerSynced, ctrl.NodeListerSynced) {\n\t\treturn\n\t}\n\n\tctrl.initializeCaches(logger, ctrl.volumeLister, ctrl.claimLister)\n\n\tgo wait.Until(func() { ctrl.resync(ctx) }, ctrl.resyncPeriod, ctx.Done())\n\tgo wait.UntilWithContext(ctx, ctrl.volumeWorker, time.Second)\n\tgo wait.UntilWithContext(ctx, ctrl.claimWorker, time.Second)\n\n\tmetrics.Register(ctrl.volumes.store, ctrl.claims, \u0026ctrl.volumePluginMgr)\n\n\t\u003c-ctx.Done()\n}","line":{"from":310,"to":339}} {"id":100005090,"name":"updateClaimMigrationAnnotations","signature":"func (ctrl *PersistentVolumeController) updateClaimMigrationAnnotations(ctx context.Context,","file":"pkg/controller/volume/persistentvolume/pv_controller_base.go","code":"func (ctrl *PersistentVolumeController) updateClaimMigrationAnnotations(ctx context.Context,\n\tclaim *v1.PersistentVolumeClaim) (*v1.PersistentVolumeClaim, error) {\n\t// TODO: update[Claim|Volume]MigrationAnnotations can be optimized to not\n\t// copy the claim/volume if no modifications are required. Though this\n\t// requires some refactoring as well as an interesting change in the\n\t// semantics of the function which may be undesirable. If no copy is made\n\t// when no modifications are required this function could sometimes return a\n\t// copy of the volume and sometimes return a ref to the original\n\tclaimClone := claim.DeepCopy()\n\tlogger := klog.FromContext(ctx)\n\tmodified := updateMigrationAnnotations(logger, ctrl.csiMigratedPluginManager, ctrl.translator, claimClone.Annotations, true)\n\tif !modified {\n\t\treturn claimClone, nil\n\t}\n\tnewClaim, err := ctrl.kubeClient.CoreV1().PersistentVolumeClaims(claimClone.Namespace).Update(ctx, claimClone, metav1.UpdateOptions{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"persistent Volume Controller can't anneal migration annotations: %v\", err)\n\t}\n\t_, err = ctrl.storeClaimUpdate(logger, newClaim)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"persistent Volume Controller can't anneal migration annotations: %v\", err)\n\t}\n\treturn newClaim, nil\n}","line":{"from":341,"to":364}} {"id":100005091,"name":"updateVolumeMigrationAnnotationsAndFinalizers","signature":"func (ctrl *PersistentVolumeController) updateVolumeMigrationAnnotationsAndFinalizers(ctx context.Context,","file":"pkg/controller/volume/persistentvolume/pv_controller_base.go","code":"func (ctrl *PersistentVolumeController) updateVolumeMigrationAnnotationsAndFinalizers(ctx context.Context,\n\tvolume *v1.PersistentVolume) (*v1.PersistentVolume, error) {\n\tvolumeClone := volume.DeepCopy()\n\tlogger := klog.FromContext(ctx)\n\tannModified := updateMigrationAnnotations(logger, ctrl.csiMigratedPluginManager, ctrl.translator, volumeClone.Annotations, false)\n\tmodifiedFinalizers, finalizersModified := modifyDeletionFinalizers(logger, ctrl.csiMigratedPluginManager, volumeClone)\n\tif !annModified \u0026\u0026 !finalizersModified {\n\t\treturn volumeClone, nil\n\t}\n\tif finalizersModified {\n\t\tvolumeClone.ObjectMeta.SetFinalizers(modifiedFinalizers)\n\t}\n\tnewVol, err := ctrl.kubeClient.CoreV1().PersistentVolumes().Update(ctx, volumeClone, metav1.UpdateOptions{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"persistent Volume Controller can't anneal migration annotations or finalizer: %v\", err)\n\t}\n\t_, err = ctrl.storeVolumeUpdate(logger, newVol)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"persistent Volume Controller can't anneal migration annotations or finalizer: %v\", err)\n\t}\n\treturn newVol, nil\n}","line":{"from":366,"to":387}} {"id":100005092,"name":"modifyDeletionFinalizers","signature":"func modifyDeletionFinalizers(logger klog.Logger, cmpm CSIMigratedPluginManager, volume *v1.PersistentVolume) ([]string, bool)","file":"pkg/controller/volume/persistentvolume/pv_controller_base.go","code":"// modifyDeletionFinalizers updates the finalizers based on the reclaim policy and if it is a in-tree volume or not.\n// The in-tree PV deletion protection finalizer is only added if the reclaimPolicy associated with the PV is `Delete`.\n// The in-tree PV deletion protection finalizer is removed if the reclaimPolicy associated with the PV is `Retain` or\n// `Recycle`, removing the finalizer is necessary to reflect the recalimPolicy updates on the PV.\n// The method also removes any external PV Deletion Protection finalizers added on the PV, this represents CSI migration\n// rollback/disable scenarios.\nfunc modifyDeletionFinalizers(logger klog.Logger, cmpm CSIMigratedPluginManager, volume *v1.PersistentVolume) ([]string, bool) {\n\tmodified := false\n\tvar outFinalizers []string\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.HonorPVReclaimPolicy) {\n\t\treturn volume.Finalizers, false\n\t}\n\tif !metav1.HasAnnotation(volume.ObjectMeta, storagehelpers.AnnDynamicallyProvisioned) {\n\t\t// PV deletion protection finalizer is currently supported only for dynamically\n\t\t// provisioned volumes.\n\t\treturn volume.Finalizers, false\n\t}\n\tif volume.Finalizers != nil {\n\t\toutFinalizers = append(outFinalizers, volume.Finalizers...)\n\t}\n\tprovisioner := volume.Annotations[storagehelpers.AnnDynamicallyProvisioned]\n\tif cmpm.IsMigrationEnabledForPlugin(provisioner) {\n\t\t// Remove in-tree delete finalizer on the PV as migration is enabled.\n\t\tif slice.ContainsString(outFinalizers, storagehelpers.PVDeletionInTreeProtectionFinalizer, nil) {\n\t\t\toutFinalizers = slice.RemoveString(outFinalizers, storagehelpers.PVDeletionInTreeProtectionFinalizer, nil)\n\t\t\tmodified = true\n\t\t}\n\t\treturn outFinalizers, modified\n\t}\n\t// Check if it is a in-tree volume.\n\tif !strings.HasPrefix(provisioner, \"kubernetes.io/\") {\n\t\t// The provision plugin does not begin with known in-tree plugin volume prefix annotation.\n\t\treturn volume.Finalizers, false\n\t}\n\treclaimPolicy := volume.Spec.PersistentVolumeReclaimPolicy\n\t// Add back the in-tree PV deletion protection finalizer if does not already exists\n\tif reclaimPolicy == v1.PersistentVolumeReclaimDelete \u0026\u0026 !slice.ContainsString(outFinalizers, storagehelpers.PVDeletionInTreeProtectionFinalizer, nil) {\n\t\tlogger.V(4).Info(\"Adding in-tree pv deletion protection finalizer on volume\", \"volumeName\", volume.Name)\n\t\toutFinalizers = append(outFinalizers, storagehelpers.PVDeletionInTreeProtectionFinalizer)\n\t\tmodified = true\n\t} else if (reclaimPolicy == v1.PersistentVolumeReclaimRetain || reclaimPolicy == v1.PersistentVolumeReclaimRecycle) \u0026\u0026 slice.ContainsString(outFinalizers, storagehelpers.PVDeletionInTreeProtectionFinalizer, nil) {\n\t\t// Remove the in-tree PV deletion protection finalizer if the reclaim policy is 'Retain' or 'Recycle'\n\t\tlogger.V(4).Info(\"Removing in-tree pv deletion protection finalizer on volume\", \"volumeName\", volume.Name)\n\t\toutFinalizers = slice.RemoveString(outFinalizers, storagehelpers.PVDeletionInTreeProtectionFinalizer, nil)\n\t\tmodified = true\n\t}\n\t// Remove the external PV deletion protection finalizer\n\tif slice.ContainsString(outFinalizers, storagehelpers.PVDeletionProtectionFinalizer, nil) {\n\t\tlogger.V(4).Info(\"Removing external pv deletion protection finalizer on volume\", \"volumeName\", volume.Name)\n\t\toutFinalizers = slice.RemoveString(outFinalizers, storagehelpers.PVDeletionProtectionFinalizer, nil)\n\t\tmodified = true\n\t}\n\treturn outFinalizers, modified\n}","line":{"from":389,"to":442}} {"id":100005093,"name":"updateMigrationAnnotations","signature":"func updateMigrationAnnotations(logger klog.Logger, cmpm CSIMigratedPluginManager, translator CSINameTranslator, ann map[string]string, claim bool) bool","file":"pkg/controller/volume/persistentvolume/pv_controller_base.go","code":"// updateMigrationAnnotations takes an Annotations map and checks for a\n// provisioner name using the provisionerKey. It will then add a\n// \"pv.kubernetes.io/migrated-to\" annotation if migration with the CSI\n// driver name for that provisioner is \"on\" based on feature flags, it will also\n// remove the annotation is migration is \"off\" for that provisioner in rollback\n// scenarios. Returns true if the annotations map was modified and false otherwise.\nfunc updateMigrationAnnotations(logger klog.Logger, cmpm CSIMigratedPluginManager, translator CSINameTranslator, ann map[string]string, claim bool) bool {\n\tvar csiDriverName string\n\tvar err error\n\n\tif ann == nil {\n\t\t// No annotations so we can't get the provisioner and don't know whether\n\t\t// this is migrated - no change\n\t\treturn false\n\t}\n\tvar provisionerKey string\n\tif claim {\n\t\tprovisionerKey = storagehelpers.AnnStorageProvisioner\n\t} else {\n\t\tprovisionerKey = storagehelpers.AnnDynamicallyProvisioned\n\t}\n\tprovisioner, ok := ann[provisionerKey]\n\tif !ok {\n\t\tif claim {\n\t\t\t// Also check beta AnnStorageProvisioner annontation to make sure\n\t\t\tprovisioner, ok = ann[storagehelpers.AnnBetaStorageProvisioner]\n\t\t\tif !ok {\n\t\t\t\treturn false\n\t\t\t}\n\t\t} else {\n\t\t\t// Volume Statically provisioned.\n\t\t\treturn false\n\t\t}\n\t}\n\n\tmigratedToDriver := ann[storagehelpers.AnnMigratedTo]\n\tif cmpm.IsMigrationEnabledForPlugin(provisioner) {\n\t\tcsiDriverName, err = translator.GetCSINameFromInTreeName(provisioner)\n\t\tif err != nil {\n\t\t\tlogger.Error(err, \"Could not update volume migration annotations. Migration enabled for plugin but could not find corresponding driver name\", \"plugin\", provisioner)\n\t\t\treturn false\n\t\t}\n\t\tif migratedToDriver != csiDriverName {\n\t\t\tann[storagehelpers.AnnMigratedTo] = csiDriverName\n\t\t\treturn true\n\t\t}\n\t} else {\n\t\tif migratedToDriver != \"\" {\n\t\t\t// Migration annotation exists but the driver isn't migrated currently\n\t\t\tdelete(ann, storagehelpers.AnnMigratedTo)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":444,"to":498}} {"id":100005094,"name":"volumeWorker","signature":"func (ctrl *PersistentVolumeController) volumeWorker(ctx context.Context)","file":"pkg/controller/volume/persistentvolume/pv_controller_base.go","code":"// volumeWorker processes items from volumeQueue. It must run only once,\n// syncVolume is not assured to be reentrant.\nfunc (ctrl *PersistentVolumeController) volumeWorker(ctx context.Context) {\n\tlogger := klog.FromContext(ctx)\n\tworkFunc := func(ctx context.Context) bool {\n\t\tkeyObj, quit := ctrl.volumeQueue.Get()\n\t\tif quit {\n\t\t\treturn true\n\t\t}\n\t\tdefer ctrl.volumeQueue.Done(keyObj)\n\t\tkey := keyObj.(string)\n\t\tlogger.V(5).Info(\"volumeWorker\", \"volumeKey\", key)\n\n\t\t_, name, err := cache.SplitMetaNamespaceKey(key)\n\t\tif err != nil {\n\t\t\tlogger.V(4).Info(\"Error getting name of volume to get volume from informer\", \"volumeKey\", key, \"err\", err)\n\t\t\treturn false\n\t\t}\n\t\tvolume, err := ctrl.volumeLister.Get(name)\n\t\tif err == nil {\n\t\t\t// The volume still exists in informer cache, the event must have\n\t\t\t// been add/update/sync\n\t\t\tctrl.updateVolume(ctx, volume)\n\t\t\treturn false\n\t\t}\n\t\tif !errors.IsNotFound(err) {\n\t\t\tlogger.V(2).Info(\"Error getting volume from informer\", \"volumeKey\", key, \"err\", err)\n\t\t\treturn false\n\t\t}\n\n\t\t// The volume is not in informer cache, the event must have been\n\t\t// \"delete\"\n\t\tvolumeObj, found, err := ctrl.volumes.store.GetByKey(key)\n\t\tif err != nil {\n\t\t\tlogger.V(2).Info(\"Error getting volume from cache\", \"volumeKey\", key, \"err\", err)\n\t\t\treturn false\n\t\t}\n\t\tif !found {\n\t\t\t// The controller has already processed the delete event and\n\t\t\t// deleted the volume from its cache\n\t\t\tlogger.V(2).Info(\"Deletion of volume was already processed\", \"volumeKey\", key)\n\t\t\treturn false\n\t\t}\n\t\tvolume, ok := volumeObj.(*v1.PersistentVolume)\n\t\tif !ok {\n\t\t\tlogger.Error(nil, \"Expected volume, got\", \"obj\", volumeObj)\n\t\t\treturn false\n\t\t}\n\t\tctrl.deleteVolume(ctx, volume)\n\t\treturn false\n\t}\n\tfor {\n\t\tif quit := workFunc(ctx); quit {\n\t\t\tlogger.Info(\"Volume worker queue shutting down\")\n\t\t\treturn\n\t\t}\n\t}\n}","line":{"from":500,"to":557}} {"id":100005095,"name":"claimWorker","signature":"func (ctrl *PersistentVolumeController) claimWorker(ctx context.Context)","file":"pkg/controller/volume/persistentvolume/pv_controller_base.go","code":"// claimWorker processes items from claimQueue. It must run only once,\n// syncClaim is not reentrant.\nfunc (ctrl *PersistentVolumeController) claimWorker(ctx context.Context) {\n\tlogger := klog.FromContext(ctx)\n\tworkFunc := func() bool {\n\t\tkeyObj, quit := ctrl.claimQueue.Get()\n\t\tif quit {\n\t\t\treturn true\n\t\t}\n\t\tdefer ctrl.claimQueue.Done(keyObj)\n\t\tkey := keyObj.(string)\n\t\tlogger.V(5).Info(\"claimWorker\", \"claimKey\", key)\n\n\t\tnamespace, name, err := cache.SplitMetaNamespaceKey(key)\n\t\tif err != nil {\n\t\t\tlogger.V(4).Info(\"Error getting namespace \u0026 name of claim to get claim from informer\", \"claimKey\", key, \"err\", err)\n\t\t\treturn false\n\t\t}\n\t\tclaim, err := ctrl.claimLister.PersistentVolumeClaims(namespace).Get(name)\n\t\tif err == nil {\n\t\t\t// The claim still exists in informer cache, the event must have\n\t\t\t// been add/update/sync\n\t\t\tctrl.updateClaim(ctx, claim)\n\t\t\treturn false\n\t\t}\n\t\tif !errors.IsNotFound(err) {\n\t\t\tlogger.V(2).Info(\"Error getting claim from informer\", \"claimKey\", key, \"err\", err)\n\t\t\treturn false\n\t\t}\n\n\t\t// The claim is not in informer cache, the event must have been \"delete\"\n\t\tclaimObj, found, err := ctrl.claims.GetByKey(key)\n\t\tif err != nil {\n\t\t\tlogger.V(2).Info(\"Error getting claim from cache\", \"claimKey\", key, \"err\", err)\n\t\t\treturn false\n\t\t}\n\t\tif !found {\n\t\t\t// The controller has already processed the delete event and\n\t\t\t// deleted the claim from its cache\n\t\t\tlogger.V(2).Info(\"Deletion of claim was already processed\", \"claimKey\", key)\n\t\t\treturn false\n\t\t}\n\t\tclaim, ok := claimObj.(*v1.PersistentVolumeClaim)\n\t\tif !ok {\n\t\t\tlogger.Error(nil, \"Expected claim, got\", \"obj\", claimObj)\n\t\t\treturn false\n\t\t}\n\t\tctrl.deleteClaim(ctx, claim)\n\t\treturn false\n\t}\n\tfor {\n\t\tif quit := workFunc(); quit {\n\t\t\tlogger.Info(\"Claim worker queue shutting down\")\n\t\t\treturn\n\t\t}\n\t}\n}","line":{"from":559,"to":615}} {"id":100005096,"name":"resync","signature":"func (ctrl *PersistentVolumeController) resync(ctx context.Context)","file":"pkg/controller/volume/persistentvolume/pv_controller_base.go","code":"// resync supplements short resync period of shared informers - we don't want\n// all consumers of PV/PVC shared informer to have a short resync period,\n// therefore we do our own.\nfunc (ctrl *PersistentVolumeController) resync(ctx context.Context) {\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"Resyncing PV controller\")\n\n\tpvcs, err := ctrl.claimLister.List(labels.NewSelector())\n\tif err != nil {\n\t\tlogger.Info(\"Cannot list claims\", \"err\", err)\n\t\treturn\n\t}\n\tfor _, pvc := range pvcs {\n\t\tctrl.enqueueWork(ctx, ctrl.claimQueue, pvc)\n\t}\n\n\tpvs, err := ctrl.volumeLister.List(labels.NewSelector())\n\tif err != nil {\n\t\tlogger.Info(\"Cannot list persistent volumes\", \"err\", err)\n\t\treturn\n\t}\n\tfor _, pv := range pvs {\n\t\tctrl.enqueueWork(ctx, ctrl.volumeQueue, pv)\n\t}\n}","line":{"from":617,"to":641}} {"id":100005097,"name":"setClaimProvisioner","signature":"func (ctrl *PersistentVolumeController) setClaimProvisioner(ctx context.Context, claim *v1.PersistentVolumeClaim, provisionerName string) (*v1.PersistentVolumeClaim, error)","file":"pkg/controller/volume/persistentvolume/pv_controller_base.go","code":"// setClaimProvisioner saves\n// claim.Annotations[\"volume.kubernetes.io/storage-provisioner\"] = class.Provisioner\nfunc (ctrl *PersistentVolumeController) setClaimProvisioner(ctx context.Context, claim *v1.PersistentVolumeClaim, provisionerName string) (*v1.PersistentVolumeClaim, error) {\n\tif val, ok := claim.Annotations[storagehelpers.AnnStorageProvisioner]; ok \u0026\u0026 val == provisionerName {\n\t\t// annotation is already set, nothing to do\n\t\treturn claim, nil\n\t}\n\n\t// The volume from method args can be pointing to watcher cache. We must not\n\t// modify these, therefore create a copy.\n\tclaimClone := claim.DeepCopy()\n\t// TODO: remove the beta storage provisioner anno after the deprecation period\n\tlogger := klog.FromContext(ctx)\n\tmetav1.SetMetaDataAnnotation(\u0026claimClone.ObjectMeta, storagehelpers.AnnBetaStorageProvisioner, provisionerName)\n\tmetav1.SetMetaDataAnnotation(\u0026claimClone.ObjectMeta, storagehelpers.AnnStorageProvisioner, provisionerName)\n\tupdateMigrationAnnotations(logger, ctrl.csiMigratedPluginManager, ctrl.translator, claimClone.Annotations, true)\n\tnewClaim, err := ctrl.kubeClient.CoreV1().PersistentVolumeClaims(claim.Namespace).Update(ctx, claimClone, metav1.UpdateOptions{})\n\tif err != nil {\n\t\treturn newClaim, err\n\t}\n\t_, err = ctrl.storeClaimUpdate(logger, newClaim)\n\tif err != nil {\n\t\treturn newClaim, err\n\t}\n\treturn newClaim, nil\n}","line":{"from":643,"to":668}} {"id":100005098,"name":"getClaimStatusForLogging","signature":"func getClaimStatusForLogging(claim *v1.PersistentVolumeClaim) string","file":"pkg/controller/volume/persistentvolume/pv_controller_base.go","code":"func getClaimStatusForLogging(claim *v1.PersistentVolumeClaim) string {\n\tbound := metav1.HasAnnotation(claim.ObjectMeta, storagehelpers.AnnBindCompleted)\n\tboundByController := metav1.HasAnnotation(claim.ObjectMeta, storagehelpers.AnnBoundByController)\n\n\treturn fmt.Sprintf(\"phase: %s, bound to: %q, bindCompleted: %v, boundByController: %v\", claim.Status.Phase, claim.Spec.VolumeName, bound, boundByController)\n}","line":{"from":672,"to":677}} {"id":100005099,"name":"getVolumeStatusForLogging","signature":"func getVolumeStatusForLogging(volume *v1.PersistentVolume) string","file":"pkg/controller/volume/persistentvolume/pv_controller_base.go","code":"func getVolumeStatusForLogging(volume *v1.PersistentVolume) string {\n\tboundByController := metav1.HasAnnotation(volume.ObjectMeta, storagehelpers.AnnBoundByController)\n\tclaimName := \"\"\n\tif volume.Spec.ClaimRef != nil {\n\t\tclaimName = fmt.Sprintf(\"%s/%s (uid: %s)\", volume.Spec.ClaimRef.Namespace, volume.Spec.ClaimRef.Name, volume.Spec.ClaimRef.UID)\n\t}\n\treturn fmt.Sprintf(\"phase: %s, bound to: %q, boundByController: %v\", volume.Status.Phase, claimName, boundByController)\n}","line":{"from":679,"to":686}} {"id":100005100,"name":"storeObjectUpdate","signature":"func storeObjectUpdate(logger klog.Logger, store cache.Store, obj interface{}, className string) (bool, error)","file":"pkg/controller/volume/persistentvolume/pv_controller_base.go","code":"// storeObjectUpdate updates given cache with a new object version from Informer\n// callback (i.e. with events from etcd) or with an object modified by the\n// controller itself. Returns \"true\", if the cache was updated, false if the\n// object is an old version and should be ignored.\nfunc storeObjectUpdate(logger klog.Logger, store cache.Store, obj interface{}, className string) (bool, error) {\n\tobjName, err := controller.KeyFunc(obj)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"couldn't get key for object %+v: %w\", obj, err)\n\t}\n\toldObj, found, err := store.Get(obj)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"error finding %s %q in controller cache: %w\", className, objName, err)\n\t}\n\n\tobjAccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif !found {\n\t\t// This is a new object\n\t\tlogger.V(4).Info(\"storeObjectUpdate, adding obj\", \"storageClassName\", className, \"objName\", objName, \"resourceVersion\", objAccessor.GetResourceVersion())\n\t\tif err = store.Add(obj); err != nil {\n\t\t\treturn false, fmt.Errorf(\"error adding %s %q to controller cache: %w\", className, objName, err)\n\t\t}\n\t\treturn true, nil\n\t}\n\n\toldObjAccessor, err := meta.Accessor(oldObj)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tobjResourceVersion, err := strconv.ParseInt(objAccessor.GetResourceVersion(), 10, 64)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"error parsing ResourceVersion %q of %s %q: %s\", objAccessor.GetResourceVersion(), className, objName, err)\n\t}\n\toldObjResourceVersion, err := strconv.ParseInt(oldObjAccessor.GetResourceVersion(), 10, 64)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"error parsing old ResourceVersion %q of %s %q: %s\", oldObjAccessor.GetResourceVersion(), className, objName, err)\n\t}\n\n\t// Throw away only older version, let the same version pass - we do want to\n\t// get periodic sync events.\n\tif oldObjResourceVersion \u003e objResourceVersion {\n\t\tlogger.V(4).Info(\"storeObjectUpdate: ignoring obj\", \"storageClassName\", className, \"objName\", objName, \"resourceVersion\", objAccessor.GetResourceVersion())\n\t\treturn false, nil\n\t}\n\n\tlogger.V(4).Info(\"storeObjectUpdate updating obj with version\", \"storageClassName\", className, \"objName\", objName, \"resourceVersion\", objAccessor.GetResourceVersion())\n\tif err = store.Update(obj); err != nil {\n\t\treturn false, fmt.Errorf(\"error updating %s %q in controller cache: %w\", className, objName, err)\n\t}\n\treturn true, nil\n}","line":{"from":688,"to":741}} {"id":100005101,"name":"GetPluginDir","signature":"func (ctrl *PersistentVolumeController) GetPluginDir(pluginName string) string","file":"pkg/controller/volume/persistentvolume/volume_host.go","code":"func (ctrl *PersistentVolumeController) GetPluginDir(pluginName string) string {\n\treturn \"\"\n}","line":{"from":42,"to":44}} {"id":100005102,"name":"GetVolumeDevicePluginDir","signature":"func (ctrl *PersistentVolumeController) GetVolumeDevicePluginDir(pluginName string) string","file":"pkg/controller/volume/persistentvolume/volume_host.go","code":"func (ctrl *PersistentVolumeController) GetVolumeDevicePluginDir(pluginName string) string {\n\treturn \"\"\n}","line":{"from":46,"to":48}} {"id":100005103,"name":"GetPodsDir","signature":"func (ctrl *PersistentVolumeController) GetPodsDir() string","file":"pkg/controller/volume/persistentvolume/volume_host.go","code":"func (ctrl *PersistentVolumeController) GetPodsDir() string {\n\treturn \"\"\n}","line":{"from":50,"to":52}} {"id":100005104,"name":"GetPodVolumeDir","signature":"func (ctrl *PersistentVolumeController) GetPodVolumeDir(podUID types.UID, pluginName string, volumeName string) string","file":"pkg/controller/volume/persistentvolume/volume_host.go","code":"func (ctrl *PersistentVolumeController) GetPodVolumeDir(podUID types.UID, pluginName string, volumeName string) string {\n\treturn \"\"\n}","line":{"from":54,"to":56}} {"id":100005105,"name":"GetPodPluginDir","signature":"func (ctrl *PersistentVolumeController) GetPodPluginDir(podUID types.UID, pluginName string) string","file":"pkg/controller/volume/persistentvolume/volume_host.go","code":"func (ctrl *PersistentVolumeController) GetPodPluginDir(podUID types.UID, pluginName string) string {\n\treturn \"\"\n}","line":{"from":58,"to":60}} {"id":100005106,"name":"GetPodVolumeDeviceDir","signature":"func (ctrl *PersistentVolumeController) GetPodVolumeDeviceDir(ppodUID types.UID, pluginName string) string","file":"pkg/controller/volume/persistentvolume/volume_host.go","code":"func (ctrl *PersistentVolumeController) GetPodVolumeDeviceDir(ppodUID types.UID, pluginName string) string {\n\treturn \"\"\n}","line":{"from":62,"to":64}} {"id":100005107,"name":"GetKubeClient","signature":"func (ctrl *PersistentVolumeController) GetKubeClient() clientset.Interface","file":"pkg/controller/volume/persistentvolume/volume_host.go","code":"func (ctrl *PersistentVolumeController) GetKubeClient() clientset.Interface {\n\treturn ctrl.kubeClient\n}","line":{"from":66,"to":68}} {"id":100005108,"name":"NewWrapperMounter","signature":"func (ctrl *PersistentVolumeController) NewWrapperMounter(volName string, spec vol.Spec, pod *v1.Pod, opts vol.VolumeOptions) (vol.Mounter, error)","file":"pkg/controller/volume/persistentvolume/volume_host.go","code":"func (ctrl *PersistentVolumeController) NewWrapperMounter(volName string, spec vol.Spec, pod *v1.Pod, opts vol.VolumeOptions) (vol.Mounter, error) {\n\treturn nil, fmt.Errorf(\"PersistentVolumeController.NewWrapperMounter is not implemented\")\n}","line":{"from":70,"to":72}} {"id":100005109,"name":"NewWrapperUnmounter","signature":"func (ctrl *PersistentVolumeController) NewWrapperUnmounter(volName string, spec vol.Spec, podUID types.UID) (vol.Unmounter, error)","file":"pkg/controller/volume/persistentvolume/volume_host.go","code":"func (ctrl *PersistentVolumeController) NewWrapperUnmounter(volName string, spec vol.Spec, podUID types.UID) (vol.Unmounter, error) {\n\treturn nil, fmt.Errorf(\"PersistentVolumeController.NewWrapperMounter is not implemented\")\n}","line":{"from":74,"to":76}} {"id":100005110,"name":"GetCloudProvider","signature":"func (ctrl *PersistentVolumeController) GetCloudProvider() cloudprovider.Interface","file":"pkg/controller/volume/persistentvolume/volume_host.go","code":"func (ctrl *PersistentVolumeController) GetCloudProvider() cloudprovider.Interface {\n\treturn ctrl.cloud\n}","line":{"from":78,"to":80}} {"id":100005111,"name":"GetMounter","signature":"func (ctrl *PersistentVolumeController) GetMounter(pluginName string) mount.Interface","file":"pkg/controller/volume/persistentvolume/volume_host.go","code":"func (ctrl *PersistentVolumeController) GetMounter(pluginName string) mount.Interface {\n\treturn nil\n}","line":{"from":82,"to":84}} {"id":100005112,"name":"GetHostName","signature":"func (ctrl *PersistentVolumeController) GetHostName() string","file":"pkg/controller/volume/persistentvolume/volume_host.go","code":"func (ctrl *PersistentVolumeController) GetHostName() string {\n\treturn \"\"\n}","line":{"from":86,"to":88}} {"id":100005113,"name":"GetHostIP","signature":"func (ctrl *PersistentVolumeController) GetHostIP() (net.IP, error)","file":"pkg/controller/volume/persistentvolume/volume_host.go","code":"func (ctrl *PersistentVolumeController) GetHostIP() (net.IP, error) {\n\treturn nil, fmt.Errorf(\"PersistentVolumeController.GetHostIP() is not implemented\")\n}","line":{"from":90,"to":92}} {"id":100005114,"name":"GetNodeAllocatable","signature":"func (ctrl *PersistentVolumeController) GetNodeAllocatable() (v1.ResourceList, error)","file":"pkg/controller/volume/persistentvolume/volume_host.go","code":"func (ctrl *PersistentVolumeController) GetNodeAllocatable() (v1.ResourceList, error) {\n\treturn v1.ResourceList{}, nil\n}","line":{"from":94,"to":96}} {"id":100005115,"name":"GetAttachedVolumesFromNodeStatus","signature":"func (ctrl *PersistentVolumeController) GetAttachedVolumesFromNodeStatus() (map[v1.UniqueVolumeName]string, error)","file":"pkg/controller/volume/persistentvolume/volume_host.go","code":"func (ctrl *PersistentVolumeController) GetAttachedVolumesFromNodeStatus() (map[v1.UniqueVolumeName]string, error) {\n\treturn map[v1.UniqueVolumeName]string{}, nil\n}","line":{"from":98,"to":100}} {"id":100005116,"name":"GetSecretFunc","signature":"func (ctrl *PersistentVolumeController) GetSecretFunc() func(namespace, name string) (*v1.Secret, error)","file":"pkg/controller/volume/persistentvolume/volume_host.go","code":"func (ctrl *PersistentVolumeController) GetSecretFunc() func(namespace, name string) (*v1.Secret, error) {\n\treturn func(_, _ string) (*v1.Secret, error) {\n\t\treturn nil, fmt.Errorf(\"GetSecret unsupported in PersistentVolumeController\")\n\t}\n}","line":{"from":102,"to":106}} {"id":100005117,"name":"GetConfigMapFunc","signature":"func (ctrl *PersistentVolumeController) GetConfigMapFunc() func(namespace, name string) (*v1.ConfigMap, error)","file":"pkg/controller/volume/persistentvolume/volume_host.go","code":"func (ctrl *PersistentVolumeController) GetConfigMapFunc() func(namespace, name string) (*v1.ConfigMap, error) {\n\treturn func(_, _ string) (*v1.ConfigMap, error) {\n\t\treturn nil, fmt.Errorf(\"GetConfigMap unsupported in PersistentVolumeController\")\n\t}\n}","line":{"from":108,"to":112}} {"id":100005118,"name":"GetServiceAccountTokenFunc","signature":"func (ctrl *PersistentVolumeController) GetServiceAccountTokenFunc() func(_, _ string, _ *authenticationv1.TokenRequest) (*authenticationv1.TokenRequest, error)","file":"pkg/controller/volume/persistentvolume/volume_host.go","code":"func (ctrl *PersistentVolumeController) GetServiceAccountTokenFunc() func(_, _ string, _ *authenticationv1.TokenRequest) (*authenticationv1.TokenRequest, error) {\n\treturn func(_, _ string, _ *authenticationv1.TokenRequest) (*authenticationv1.TokenRequest, error) {\n\t\treturn nil, fmt.Errorf(\"GetServiceAccountToken unsupported in PersistentVolumeController\")\n\t}\n}","line":{"from":114,"to":118}} {"id":100005119,"name":"DeleteServiceAccountTokenFunc","signature":"func (ctrl *PersistentVolumeController) DeleteServiceAccountTokenFunc() func(types.UID)","file":"pkg/controller/volume/persistentvolume/volume_host.go","code":"func (ctrl *PersistentVolumeController) DeleteServiceAccountTokenFunc() func(types.UID) {\n\treturn func(types.UID) {\n\t\tklog.ErrorS(nil, \"DeleteServiceAccountToken unsupported in PersistentVolumeController\")\n\t}\n}","line":{"from":120,"to":124}} {"id":100005120,"name":"GetExec","signature":"func (adc *PersistentVolumeController) GetExec(pluginName string) utilexec.Interface","file":"pkg/controller/volume/persistentvolume/volume_host.go","code":"func (adc *PersistentVolumeController) GetExec(pluginName string) utilexec.Interface {\n\treturn utilexec.New()\n}","line":{"from":126,"to":128}} {"id":100005121,"name":"GetNodeLabels","signature":"func (ctrl *PersistentVolumeController) GetNodeLabels() (map[string]string, error)","file":"pkg/controller/volume/persistentvolume/volume_host.go","code":"func (ctrl *PersistentVolumeController) GetNodeLabels() (map[string]string, error) {\n\treturn nil, fmt.Errorf(\"GetNodeLabels() unsupported in PersistentVolumeController\")\n}","line":{"from":130,"to":132}} {"id":100005122,"name":"GetNodeName","signature":"func (ctrl *PersistentVolumeController) GetNodeName() types.NodeName","file":"pkg/controller/volume/persistentvolume/volume_host.go","code":"func (ctrl *PersistentVolumeController) GetNodeName() types.NodeName {\n\treturn \"\"\n}","line":{"from":134,"to":136}} {"id":100005123,"name":"GetEventRecorder","signature":"func (ctrl *PersistentVolumeController) GetEventRecorder() record.EventRecorder","file":"pkg/controller/volume/persistentvolume/volume_host.go","code":"func (ctrl *PersistentVolumeController) GetEventRecorder() record.EventRecorder {\n\treturn ctrl.eventRecorder\n}","line":{"from":138,"to":140}} {"id":100005124,"name":"GetSubpather","signature":"func (ctrl *PersistentVolumeController) GetSubpather() subpath.Interface","file":"pkg/controller/volume/persistentvolume/volume_host.go","code":"func (ctrl *PersistentVolumeController) GetSubpather() subpath.Interface {\n\t// No volume plugin needs Subpaths in PV controller.\n\treturn nil\n}","line":{"from":142,"to":145}} {"id":100005125,"name":"GetFilteredDialOptions","signature":"func (ctrl *PersistentVolumeController) GetFilteredDialOptions() *proxyutil.FilteredDialOptions","file":"pkg/controller/volume/persistentvolume/volume_host.go","code":"func (ctrl *PersistentVolumeController) GetFilteredDialOptions() *proxyutil.FilteredDialOptions {\n\treturn ctrl.filteredDialOptions\n}","line":{"from":147,"to":149}} {"id":100005126,"name":"IsDeletionCandidate","signature":"func IsDeletionCandidate(obj metav1.Object, finalizer string) bool","file":"pkg/controller/volume/protectionutil/utils.go","code":"// IsDeletionCandidate checks if object is candidate to be deleted\nfunc IsDeletionCandidate(obj metav1.Object, finalizer string) bool {\n\treturn obj.GetDeletionTimestamp() != nil \u0026\u0026 slice.ContainsString(obj.GetFinalizers(),\n\t\tfinalizer, nil)\n}","line":{"from":24,"to":28}} {"id":100005127,"name":"NeedToAddFinalizer","signature":"func NeedToAddFinalizer(obj metav1.Object, finalizer string) bool","file":"pkg/controller/volume/protectionutil/utils.go","code":"// NeedToAddFinalizer checks if need to add finalizer to object\nfunc NeedToAddFinalizer(obj metav1.Object, finalizer string) bool {\n\treturn obj.GetDeletionTimestamp() == nil \u0026\u0026 !slice.ContainsString(obj.GetFinalizers(),\n\t\tfinalizer, nil)\n}","line":{"from":30,"to":34}} {"id":100005128,"name":"NewPVCProtectionController","signature":"func NewPVCProtectionController(logger klog.Logger, pvcInformer coreinformers.PersistentVolumeClaimInformer, podInformer coreinformers.PodInformer, cl clientset.Interface) (*Controller, error)","file":"pkg/controller/volume/pvcprotection/pvc_protection_controller.go","code":"// NewPVCProtectionController returns a new instance of PVCProtectionController.\nfunc NewPVCProtectionController(logger klog.Logger, pvcInformer coreinformers.PersistentVolumeClaimInformer, podInformer coreinformers.PodInformer, cl clientset.Interface) (*Controller, error) {\n\te := \u0026Controller{\n\t\tclient: cl,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"pvcprotection\"),\n\t}\n\n\te.pvcLister = pvcInformer.Lister()\n\te.pvcListerSynced = pvcInformer.Informer().HasSynced\n\tpvcInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\te.pvcAddedUpdated(logger, obj)\n\t\t},\n\t\tUpdateFunc: func(old, new interface{}) {\n\t\t\te.pvcAddedUpdated(logger, new)\n\t\t},\n\t})\n\n\te.podLister = podInformer.Lister()\n\te.podListerSynced = podInformer.Informer().HasSynced\n\te.podIndexer = podInformer.Informer().GetIndexer()\n\tif err := common.AddIndexerIfNotPresent(e.podIndexer, common.PodPVCIndex, common.PodPVCIndexFunc()); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not initialize pvc protection controller: %w\", err)\n\t}\n\tpodInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\te.podAddedDeletedUpdated(logger, nil, obj, false)\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\te.podAddedDeletedUpdated(logger, nil, obj, true)\n\t\t},\n\t\tUpdateFunc: func(old, new interface{}) {\n\t\t\te.podAddedDeletedUpdated(logger, old, new, false)\n\t\t},\n\t})\n\n\treturn e, nil\n}","line":{"from":57,"to":94}} {"id":100005129,"name":"Run","signature":"func (c *Controller) Run(ctx context.Context, workers int)","file":"pkg/controller/volume/pvcprotection/pvc_protection_controller.go","code":"// Run runs the controller goroutines.\nfunc (c *Controller) Run(ctx context.Context, workers int) {\n\tdefer utilruntime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\n\tlogger := klog.FromContext(ctx)\n\tlogger.Info(\"Starting PVC protection controller\")\n\tdefer logger.Info(\"Shutting down PVC protection controller\")\n\n\tif !cache.WaitForNamedCacheSync(\"PVC protection\", ctx.Done(), c.pvcListerSynced, c.podListerSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.UntilWithContext(ctx, c.runWorker, time.Second)\n\t}\n\n\t\u003c-ctx.Done()\n}","line":{"from":96,"to":114}} {"id":100005130,"name":"runWorker","signature":"func (c *Controller) runWorker(ctx context.Context)","file":"pkg/controller/volume/pvcprotection/pvc_protection_controller.go","code":"func (c *Controller) runWorker(ctx context.Context) {\n\tfor c.processNextWorkItem(ctx) {\n\t}\n}","line":{"from":116,"to":119}} {"id":100005131,"name":"processNextWorkItem","signature":"func (c *Controller) processNextWorkItem(ctx context.Context) bool","file":"pkg/controller/volume/pvcprotection/pvc_protection_controller.go","code":"// processNextWorkItem deals with one pvcKey off the queue. It returns false when it's time to quit.\nfunc (c *Controller) processNextWorkItem(ctx context.Context) bool {\n\tpvcKey, quit := c.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.queue.Done(pvcKey)\n\n\tpvcNamespace, pvcName, err := cache.SplitMetaNamespaceKey(pvcKey.(string))\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"error parsing PVC key %q: %v\", pvcKey, err))\n\t\treturn true\n\t}\n\n\terr = c.processPVC(ctx, pvcNamespace, pvcName)\n\tif err == nil {\n\t\tc.queue.Forget(pvcKey)\n\t\treturn true\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"PVC %v failed with : %v\", pvcKey, err))\n\tc.queue.AddRateLimited(pvcKey)\n\n\treturn true\n}","line":{"from":121,"to":145}} {"id":100005132,"name":"processPVC","signature":"func (c *Controller) processPVC(ctx context.Context, pvcNamespace, pvcName string) error","file":"pkg/controller/volume/pvcprotection/pvc_protection_controller.go","code":"func (c *Controller) processPVC(ctx context.Context, pvcNamespace, pvcName string) error {\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"Processing PVC\", \"PVC\", klog.KRef(pvcNamespace, pvcName))\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tlogger.V(4).Info(\"Finished processing PVC\", \"PVC\", klog.KRef(pvcNamespace, pvcName), \"duration\", time.Since(startTime))\n\t}()\n\n\tpvc, err := c.pvcLister.PersistentVolumeClaims(pvcNamespace).Get(pvcName)\n\tif apierrors.IsNotFound(err) {\n\t\tlogger.V(4).Info(\"PVC not found, ignoring\", \"PVC\", klog.KRef(pvcNamespace, pvcName))\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif protectionutil.IsDeletionCandidate(pvc, volumeutil.PVCProtectionFinalizer) {\n\t\t// PVC should be deleted. Check if it's used and remove finalizer if\n\t\t// it's not.\n\t\tisUsed, err := c.isBeingUsed(ctx, pvc)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !isUsed {\n\t\t\treturn c.removeFinalizer(ctx, pvc)\n\t\t}\n\t\tlogger.V(2).Info(\"Keeping PVC because it is being used\", \"PVC\", klog.KObj(pvc))\n\t}\n\n\tif protectionutil.NeedToAddFinalizer(pvc, volumeutil.PVCProtectionFinalizer) {\n\t\t// PVC is not being deleted -\u003e it should have the finalizer. The\n\t\t// finalizer should be added by admission plugin, this is just to add\n\t\t// the finalizer to old PVCs that were created before the admission\n\t\t// plugin was enabled.\n\t\treturn c.addFinalizer(ctx, pvc)\n\t}\n\treturn nil\n}","line":{"from":147,"to":185}} {"id":100005133,"name":"addFinalizer","signature":"func (c *Controller) addFinalizer(ctx context.Context, pvc *v1.PersistentVolumeClaim) error","file":"pkg/controller/volume/pvcprotection/pvc_protection_controller.go","code":"func (c *Controller) addFinalizer(ctx context.Context, pvc *v1.PersistentVolumeClaim) error {\n\tclaimClone := pvc.DeepCopy()\n\tclaimClone.ObjectMeta.Finalizers = append(claimClone.ObjectMeta.Finalizers, volumeutil.PVCProtectionFinalizer)\n\t_, err := c.client.CoreV1().PersistentVolumeClaims(claimClone.Namespace).Update(ctx, claimClone, metav1.UpdateOptions{})\n\tlogger := klog.FromContext(ctx)\n\tif err != nil {\n\t\tlogger.Error(err, \"Error adding protection finalizer to PVC\", \"PVC\", klog.KObj(pvc))\n\t\treturn err\n\t}\n\tlogger.V(3).Info(\"Added protection finalizer to PVC\", \"PVC\", klog.KObj(pvc))\n\treturn nil\n}","line":{"from":187,"to":198}} {"id":100005134,"name":"removeFinalizer","signature":"func (c *Controller) removeFinalizer(ctx context.Context, pvc *v1.PersistentVolumeClaim) error","file":"pkg/controller/volume/pvcprotection/pvc_protection_controller.go","code":"func (c *Controller) removeFinalizer(ctx context.Context, pvc *v1.PersistentVolumeClaim) error {\n\tclaimClone := pvc.DeepCopy()\n\tclaimClone.ObjectMeta.Finalizers = slice.RemoveString(claimClone.ObjectMeta.Finalizers, volumeutil.PVCProtectionFinalizer, nil)\n\t_, err := c.client.CoreV1().PersistentVolumeClaims(claimClone.Namespace).Update(ctx, claimClone, metav1.UpdateOptions{})\n\tlogger := klog.FromContext(ctx)\n\tif err != nil {\n\t\tlogger.Error(err, \"Error removing protection finalizer from PVC\", \"PVC\", klog.KObj(pvc))\n\t\treturn err\n\t}\n\tlogger.V(3).Info(\"Removed protection finalizer from PVC\", \"PVC\", klog.KObj(pvc))\n\treturn nil\n}","line":{"from":200,"to":211}} {"id":100005135,"name":"isBeingUsed","signature":"func (c *Controller) isBeingUsed(ctx context.Context, pvc *v1.PersistentVolumeClaim) (bool, error)","file":"pkg/controller/volume/pvcprotection/pvc_protection_controller.go","code":"func (c *Controller) isBeingUsed(ctx context.Context, pvc *v1.PersistentVolumeClaim) (bool, error) {\n\t// Look for a Pod using pvc in the Informer's cache. If one is found the\n\t// correct decision to keep pvc is taken without doing an expensive live\n\t// list.\n\tlogger := klog.FromContext(ctx)\n\tif inUse, err := c.askInformer(logger, pvc); err != nil {\n\t\t// No need to return because a live list will follow.\n\t\tlogger.Error(err, \"\")\n\t} else if inUse {\n\t\treturn true, nil\n\t}\n\n\t// Even if no Pod using pvc was found in the Informer's cache it doesn't\n\t// mean such a Pod doesn't exist: it might just not be in the cache yet. To\n\t// be 100% confident that it is safe to delete pvc make sure no Pod is using\n\t// it among those returned by a live list.\n\treturn c.askAPIServer(ctx, pvc)\n}","line":{"from":213,"to":230}} {"id":100005136,"name":"askInformer","signature":"func (c *Controller) askInformer(logger klog.Logger, pvc *v1.PersistentVolumeClaim) (bool, error)","file":"pkg/controller/volume/pvcprotection/pvc_protection_controller.go","code":"func (c *Controller) askInformer(logger klog.Logger, pvc *v1.PersistentVolumeClaim) (bool, error) {\n\tlogger.V(4).Info(\"Looking for Pods using PVC in the Informer's cache\", \"PVC\", klog.KObj(pvc))\n\n\t// The indexer is used to find pods which might use the PVC.\n\tobjs, err := c.podIndexer.ByIndex(common.PodPVCIndex, fmt.Sprintf(\"%s/%s\", pvc.Namespace, pvc.Name))\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"cache-based list of pods failed while processing %s/%s: %s\", pvc.Namespace, pvc.Name, err.Error())\n\t}\n\tfor _, obj := range objs {\n\t\tpod, ok := obj.(*v1.Pod)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\t// We still need to look at each volume: that's redundant for volume.PersistentVolumeClaim,\n\t\t// but for volume.Ephemeral we need to be sure that this particular PVC is the one\n\t\t// created for the ephemeral volume.\n\t\tif c.podUsesPVC(logger, pod, pvc) {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\tlogger.V(4).Info(\"No Pod using PVC was found in the Informer's cache\", \"PVC\", klog.KObj(pvc))\n\treturn false, nil\n}","line":{"from":232,"to":256}} {"id":100005137,"name":"askAPIServer","signature":"func (c *Controller) askAPIServer(ctx context.Context, pvc *v1.PersistentVolumeClaim) (bool, error)","file":"pkg/controller/volume/pvcprotection/pvc_protection_controller.go","code":"func (c *Controller) askAPIServer(ctx context.Context, pvc *v1.PersistentVolumeClaim) (bool, error) {\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"Looking for Pods using PVC with a live list\", \"PVC\", klog.KObj(pvc))\n\n\tpodsList, err := c.client.CoreV1().Pods(pvc.Namespace).List(ctx, metav1.ListOptions{})\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"live list of pods failed: %s\", err.Error())\n\t}\n\n\tfor _, pod := range podsList.Items {\n\t\tif c.podUsesPVC(logger, \u0026pod, pvc) {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\tlogger.V(2).Info(\"PVC is unused\", \"PVC\", klog.KObj(pvc))\n\treturn false, nil\n}","line":{"from":258,"to":275}} {"id":100005138,"name":"podUsesPVC","signature":"func (c *Controller) podUsesPVC(logger klog.Logger, pod *v1.Pod, pvc *v1.PersistentVolumeClaim) bool","file":"pkg/controller/volume/pvcprotection/pvc_protection_controller.go","code":"func (c *Controller) podUsesPVC(logger klog.Logger, pod *v1.Pod, pvc *v1.PersistentVolumeClaim) bool {\n\t// Check whether pvc is used by pod only if pod is scheduled, because\n\t// kubelet sees pods after they have been scheduled and it won't allow\n\t// starting a pod referencing a PVC with a non-nil deletionTimestamp.\n\tif pod.Spec.NodeName != \"\" {\n\t\tfor _, volume := range pod.Spec.Volumes {\n\t\t\tif volume.PersistentVolumeClaim != nil \u0026\u0026 volume.PersistentVolumeClaim.ClaimName == pvc.Name ||\n\t\t\t\t!podIsShutDown(pod) \u0026\u0026 volume.Ephemeral != nil \u0026\u0026 ephemeral.VolumeClaimName(pod, \u0026volume) == pvc.Name \u0026\u0026 ephemeral.VolumeIsForPod(pod, pvc) == nil {\n\t\t\t\tlogger.V(2).Info(\"Pod uses PVC\", \"pod\", klog.KObj(pod), \"PVC\", klog.KObj(pvc))\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":277,"to":291}} {"id":100005139,"name":"podIsShutDown","signature":"func podIsShutDown(pod *v1.Pod) bool","file":"pkg/controller/volume/pvcprotection/pvc_protection_controller.go","code":"// podIsShutDown returns true if kubelet is done with the pod or\n// it was force-deleted.\nfunc podIsShutDown(pod *v1.Pod) bool {\n\t// A pod that has a deletionTimestamp and a zero\n\t// deletionGracePeriodSeconds\n\t// a) has been processed by kubelet and was set up for deletion\n\t// by the apiserver:\n\t// - canBeDeleted has verified that volumes were unpublished\n\t// https://github.com/kubernetes/kubernetes/blob/5404b5a28a2114299608bab00e4292960dd864a0/pkg/kubelet/kubelet_pods.go#L980\n\t// - deletionGracePeriodSeconds was set via a delete\n\t// with zero GracePeriodSeconds\n\t// https://github.com/kubernetes/kubernetes/blob/5404b5a28a2114299608bab00e4292960dd864a0/pkg/kubelet/status/status_manager.go#L580-L592\n\t// or\n\t// b) was force-deleted.\n\t//\n\t// It's now just waiting for garbage collection. We could wait\n\t// for it to actually get removed, but that may be blocked by\n\t// finalizers for the pod and thus get delayed.\n\t//\n\t// Worse, it is possible that there is a cyclic dependency\n\t// (pod finalizer waits for PVC to get removed, PVC protection\n\t// controller waits for pod to get removed). By considering\n\t// the PVC unused in this case, we allow the PVC to get\n\t// removed and break such a cycle.\n\t//\n\t// Therefore it is better to proceed with PVC removal,\n\t// which is safe (case a) and/or desirable (case b).\n\treturn pod.DeletionTimestamp != nil \u0026\u0026 pod.DeletionGracePeriodSeconds != nil \u0026\u0026 *pod.DeletionGracePeriodSeconds == 0\n}","line":{"from":293,"to":321}} {"id":100005140,"name":"pvcAddedUpdated","signature":"func (c *Controller) pvcAddedUpdated(logger klog.Logger, obj interface{})","file":"pkg/controller/volume/pvcprotection/pvc_protection_controller.go","code":"// pvcAddedUpdated reacts to pvc added/updated events\nfunc (c *Controller) pvcAddedUpdated(logger klog.Logger, obj interface{}) {\n\tpvc, ok := obj.(*v1.PersistentVolumeClaim)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"PVC informer returned non-PVC object: %#v\", obj))\n\t\treturn\n\t}\n\tkey, err := cache.MetaNamespaceKeyFunc(pvc)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get key for Persistent Volume Claim %#v: %v\", pvc, err))\n\t\treturn\n\t}\n\tlogger.V(4).Info(\"Got event on PVC\", \"pvc\", klog.KObj(pvc))\n\n\tif protectionutil.NeedToAddFinalizer(pvc, volumeutil.PVCProtectionFinalizer) || protectionutil.IsDeletionCandidate(pvc, volumeutil.PVCProtectionFinalizer) {\n\t\tc.queue.Add(key)\n\t}\n}","line":{"from":323,"to":340}} {"id":100005141,"name":"podAddedDeletedUpdated","signature":"func (c *Controller) podAddedDeletedUpdated(logger klog.Logger, old, new interface{}, deleted bool)","file":"pkg/controller/volume/pvcprotection/pvc_protection_controller.go","code":"// podAddedDeletedUpdated reacts to Pod events\nfunc (c *Controller) podAddedDeletedUpdated(logger klog.Logger, old, new interface{}, deleted bool) {\n\tif pod := c.parsePod(new); pod != nil {\n\t\tc.enqueuePVCs(logger, pod, deleted)\n\n\t\t// An update notification might mask the deletion of a pod X and the\n\t\t// following creation of a pod Y with the same namespaced name as X. If\n\t\t// that's the case X needs to be processed as well to handle the case\n\t\t// where it is blocking deletion of a PVC not referenced by Y, otherwise\n\t\t// such PVC will never be deleted.\n\t\tif oldPod := c.parsePod(old); oldPod != nil \u0026\u0026 oldPod.UID != pod.UID {\n\t\t\tc.enqueuePVCs(logger, oldPod, true)\n\t\t}\n\t}\n}","line":{"from":342,"to":356}} {"id":100005142,"name":"parsePod","signature":"func (*Controller) parsePod(obj interface{}) *v1.Pod","file":"pkg/controller/volume/pvcprotection/pvc_protection_controller.go","code":"func (*Controller) parsePod(obj interface{}) *v1.Pod {\n\tif obj == nil {\n\t\treturn nil\n\t}\n\tpod, ok := obj.(*v1.Pod)\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get object from tombstone %#v\", obj))\n\t\t\treturn nil\n\t\t}\n\t\tpod, ok = tombstone.Obj.(*v1.Pod)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"tombstone contained object that is not a Pod %#v\", obj))\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn pod\n}","line":{"from":358,"to":376}} {"id":100005143,"name":"enqueuePVCs","signature":"func (c *Controller) enqueuePVCs(logger klog.Logger, pod *v1.Pod, deleted bool)","file":"pkg/controller/volume/pvcprotection/pvc_protection_controller.go","code":"func (c *Controller) enqueuePVCs(logger klog.Logger, pod *v1.Pod, deleted bool) {\n\t// Filter out pods that can't help us to remove a finalizer on PVC\n\tif !deleted \u0026\u0026 !volumeutil.IsPodTerminated(pod, pod.Status) \u0026\u0026 pod.Spec.NodeName != \"\" {\n\t\treturn\n\t}\n\n\tlogger.V(4).Info(\"Enqueuing PVCs for Pod\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\n\t// Enqueue all PVCs that the pod uses\n\tfor _, volume := range pod.Spec.Volumes {\n\t\tswitch {\n\t\tcase volume.PersistentVolumeClaim != nil:\n\t\t\tc.queue.Add(pod.Namespace + \"/\" + volume.PersistentVolumeClaim.ClaimName)\n\t\tcase volume.Ephemeral != nil:\n\t\t\tc.queue.Add(pod.Namespace + \"/\" + ephemeral.VolumeClaimName(pod, \u0026volume))\n\t\t}\n\t}\n}","line":{"from":378,"to":395}} {"id":100005144,"name":"NewPVProtectionController","signature":"func NewPVProtectionController(logger klog.Logger, pvInformer coreinformers.PersistentVolumeInformer, cl clientset.Interface) *Controller","file":"pkg/controller/volume/pvprotection/pv_protection_controller.go","code":"// NewPVProtectionController returns a new *Controller.\nfunc NewPVProtectionController(logger klog.Logger, pvInformer coreinformers.PersistentVolumeInformer, cl clientset.Interface) *Controller {\n\te := \u0026Controller{\n\t\tclient: cl,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"pvprotection\"),\n\t}\n\n\te.pvLister = pvInformer.Lister()\n\te.pvListerSynced = pvInformer.Informer().HasSynced\n\tpvInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\te.pvAddedUpdated(logger, obj)\n\t\t},\n\t\tUpdateFunc: func(old, new interface{}) {\n\t\t\te.pvAddedUpdated(logger, new)\n\t\t},\n\t})\n\n\treturn e\n}","line":{"from":51,"to":70}} {"id":100005145,"name":"Run","signature":"func (c *Controller) Run(ctx context.Context, workers int)","file":"pkg/controller/volume/pvprotection/pv_protection_controller.go","code":"// Run runs the controller goroutines.\nfunc (c *Controller) Run(ctx context.Context, workers int) {\n\tdefer utilruntime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\n\tlogger := klog.FromContext(ctx)\n\tlogger.Info(\"Starting PV protection controller\")\n\tdefer logger.Info(\"Shutting down PV protection controller\")\n\n\tif !cache.WaitForNamedCacheSync(\"PV protection\", ctx.Done(), c.pvListerSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.UntilWithContext(ctx, c.runWorker, time.Second)\n\t}\n\n\t\u003c-ctx.Done()\n}","line":{"from":72,"to":90}} {"id":100005146,"name":"runWorker","signature":"func (c *Controller) runWorker(ctx context.Context)","file":"pkg/controller/volume/pvprotection/pv_protection_controller.go","code":"func (c *Controller) runWorker(ctx context.Context) {\n\tfor c.processNextWorkItem(ctx) {\n\t}\n}","line":{"from":92,"to":95}} {"id":100005147,"name":"processNextWorkItem","signature":"func (c *Controller) processNextWorkItem(ctx context.Context) bool","file":"pkg/controller/volume/pvprotection/pv_protection_controller.go","code":"// processNextWorkItem deals with one pvcKey off the queue. It returns false when it's time to quit.\nfunc (c *Controller) processNextWorkItem(ctx context.Context) bool {\n\tpvKey, quit := c.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.queue.Done(pvKey)\n\n\tpvName := pvKey.(string)\n\n\terr := c.processPV(ctx, pvName)\n\tif err == nil {\n\t\tc.queue.Forget(pvKey)\n\t\treturn true\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"PV %v failed with : %v\", pvKey, err))\n\tc.queue.AddRateLimited(pvKey)\n\n\treturn true\n}","line":{"from":97,"to":117}} {"id":100005148,"name":"processPV","signature":"func (c *Controller) processPV(ctx context.Context, pvName string) error","file":"pkg/controller/volume/pvprotection/pv_protection_controller.go","code":"func (c *Controller) processPV(ctx context.Context, pvName string) error {\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(4).Info(\"Processing PV\", \"PV\", klog.KRef(\"\", pvName))\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tlogger.V(4).Info(\"Finished processing PV\", \"PV\", klog.KRef(\"\", pvName), \"cost\", time.Since(startTime))\n\t}()\n\n\tpv, err := c.pvLister.Get(pvName)\n\tif apierrors.IsNotFound(err) {\n\t\tlogger.V(4).Info(\"PV not found, ignoring\", \"PV\", klog.KRef(\"\", pvName))\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif protectionutil.IsDeletionCandidate(pv, volumeutil.PVProtectionFinalizer) {\n\t\t// PV should be deleted. Check if it's used and remove finalizer if\n\t\t// it's not.\n\t\tisUsed := c.isBeingUsed(pv)\n\t\tif !isUsed {\n\t\t\treturn c.removeFinalizer(ctx, pv)\n\t\t}\n\t\tlogger.V(4).Info(\"Keeping PV because it is being used\", \"PV\", klog.KRef(\"\", pvName))\n\t}\n\n\tif protectionutil.NeedToAddFinalizer(pv, volumeutil.PVProtectionFinalizer) {\n\t\t// PV is not being deleted -\u003e it should have the finalizer. The\n\t\t// finalizer should be added by admission plugin, this is just to add\n\t\t// the finalizer to old PVs that were created before the admission\n\t\t// plugin was enabled.\n\t\treturn c.addFinalizer(ctx, pv)\n\t}\n\treturn nil\n}","line":{"from":119,"to":154}} {"id":100005149,"name":"addFinalizer","signature":"func (c *Controller) addFinalizer(ctx context.Context, pv *v1.PersistentVolume) error","file":"pkg/controller/volume/pvprotection/pv_protection_controller.go","code":"func (c *Controller) addFinalizer(ctx context.Context, pv *v1.PersistentVolume) error {\n\tpvClone := pv.DeepCopy()\n\tpvClone.ObjectMeta.Finalizers = append(pvClone.ObjectMeta.Finalizers, volumeutil.PVProtectionFinalizer)\n\t_, err := c.client.CoreV1().PersistentVolumes().Update(ctx, pvClone, metav1.UpdateOptions{})\n\tlogger := klog.FromContext(ctx)\n\tif err != nil {\n\t\tlogger.V(3).Info(\"Error adding protection finalizer to PV\", \"PV\", klog.KObj(pv), \"err\", err)\n\t\treturn err\n\t}\n\tlogger.V(3).Info(\"Added protection finalizer to PV\", \"PV\", klog.KObj(pv))\n\treturn nil\n}","line":{"from":156,"to":167}} {"id":100005150,"name":"removeFinalizer","signature":"func (c *Controller) removeFinalizer(ctx context.Context, pv *v1.PersistentVolume) error","file":"pkg/controller/volume/pvprotection/pv_protection_controller.go","code":"func (c *Controller) removeFinalizer(ctx context.Context, pv *v1.PersistentVolume) error {\n\tpvClone := pv.DeepCopy()\n\tpvClone.ObjectMeta.Finalizers = slice.RemoveString(pvClone.ObjectMeta.Finalizers, volumeutil.PVProtectionFinalizer, nil)\n\t_, err := c.client.CoreV1().PersistentVolumes().Update(ctx, pvClone, metav1.UpdateOptions{})\n\tlogger := klog.FromContext(ctx)\n\tif err != nil {\n\t\tlogger.V(3).Info(\"Error removing protection finalizer from PV\", \"PV\", klog.KObj(pv), \"err\", err)\n\t\treturn err\n\t}\n\tlogger.V(3).Info(\"Removed protection finalizer from PV\", \"PV\", klog.KObj(pv))\n\treturn nil\n}","line":{"from":169,"to":180}} {"id":100005151,"name":"isBeingUsed","signature":"func (c *Controller) isBeingUsed(pv *v1.PersistentVolume) bool","file":"pkg/controller/volume/pvprotection/pv_protection_controller.go","code":"func (c *Controller) isBeingUsed(pv *v1.PersistentVolume) bool {\n\t// check if PV is being bound to a PVC by its status\n\t// the status will be updated by PV controller\n\tif pv.Status.Phase == v1.VolumeBound {\n\t\t// the PV is being used now\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":182,"to":191}} {"id":100005152,"name":"pvAddedUpdated","signature":"func (c *Controller) pvAddedUpdated(logger klog.Logger, obj interface{})","file":"pkg/controller/volume/pvprotection/pv_protection_controller.go","code":"// pvAddedUpdated reacts to pv added/updated events\nfunc (c *Controller) pvAddedUpdated(logger klog.Logger, obj interface{}) {\n\tpv, ok := obj.(*v1.PersistentVolume)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"PV informer returned non-PV object: %#v\", obj))\n\t\treturn\n\t}\n\tlogger.V(4).Info(\"Got event on PV\", \"PV\", klog.KObj(pv))\n\n\tif protectionutil.NeedToAddFinalizer(pv, volumeutil.PVProtectionFinalizer) || protectionutil.IsDeletionCandidate(pv, volumeutil.PVProtectionFinalizer) {\n\t\tc.queue.Add(pv.Name)\n\t}\n}","line":{"from":193,"to":205}} {"id":100005153,"name":"createNamespaceIfNeeded","signature":"func createNamespaceIfNeeded(c corev1client.NamespacesGetter, ns string) error","file":"pkg/controlplane/client_util.go","code":"func createNamespaceIfNeeded(c corev1client.NamespacesGetter, ns string) error {\n\tif _, err := c.Namespaces().Get(context.TODO(), ns, metav1.GetOptions{}); err == nil {\n\t\t// the namespace already exists\n\t\treturn nil\n\t}\n\tnewNs := \u0026corev1.Namespace{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: ns,\n\t\t\tNamespace: \"\",\n\t\t},\n\t}\n\t_, err := c.Namespaces().Create(context.TODO(), newNs, metav1.CreateOptions{})\n\tif err != nil \u0026\u0026 errors.IsAlreadyExists(err) {\n\t\terr = nil\n\t}\n\treturn err\n}","line":{"from":27,"to":43}} {"id":100005154,"name":"NewBootstrapController","signature":"func (c *completedConfig) NewBootstrapController(legacyRESTStorage corerest.LegacyRESTStorage, client kubernetes.Interface) (*Controller, error)","file":"pkg/controlplane/controller.go","code":"// NewBootstrapController returns a controller for watching the core capabilities of the master\nfunc (c *completedConfig) NewBootstrapController(legacyRESTStorage corerest.LegacyRESTStorage, client kubernetes.Interface) (*Controller, error) {\n\t_, publicServicePort, err := c.GenericConfig.SecureServing.HostPort()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get listener address: %w\", err)\n\t}\n\n\t// The \"kubernetes.default\" Service is SingleStack based on the configured ServiceIPRange.\n\t// If the bootstrap controller reconcile the kubernetes.default Service and Endpoints, it must\n\t// guarantee that the Service ClusterIP and the associated Endpoints have the same IP family, or\n\t// it will not work for clients because of the IP family mismatch.\n\t// TODO: revisit for dual-stack https://github.com/kubernetes/enhancements/issues/2438\n\tif c.ExtraConfig.EndpointReconcilerType != reconcilers.NoneEndpointReconcilerType {\n\t\tif netutils.IsIPv4CIDR(\u0026c.ExtraConfig.ServiceIPRange) != netutils.IsIPv4(c.GenericConfig.PublicAddress) {\n\t\t\treturn nil, fmt.Errorf(\"service IP family %q must match public address family %q\", c.ExtraConfig.ServiceIPRange.String(), c.GenericConfig.PublicAddress.String())\n\t\t}\n\t}\n\n\treturn \u0026Controller{\n\t\tclient: client,\n\t\tinformers: c.ExtraConfig.VersionedInformers,\n\n\t\tEndpointReconciler: c.ExtraConfig.EndpointReconcilerConfig.Reconciler,\n\t\tEndpointInterval: c.ExtraConfig.EndpointReconcilerConfig.Interval,\n\n\t\tServiceClusterIPRegistry: legacyRESTStorage.ServiceClusterIPAllocator,\n\t\tServiceClusterIPRange: c.ExtraConfig.ServiceIPRange,\n\t\tSecondaryServiceClusterIPRegistry: legacyRESTStorage.SecondaryServiceClusterIPAllocator,\n\t\tSecondaryServiceClusterIPRange: c.ExtraConfig.SecondaryServiceIPRange,\n\n\t\tServiceClusterIPInterval: c.ExtraConfig.RepairServicesInterval,\n\n\t\tServiceNodePortRegistry: legacyRESTStorage.ServiceNodePortAllocator,\n\t\tServiceNodePortRange: c.ExtraConfig.ServiceNodePortRange,\n\t\tServiceNodePortInterval: c.ExtraConfig.RepairServicesInterval,\n\n\t\tPublicIP: c.GenericConfig.PublicAddress,\n\n\t\tServiceIP: c.ExtraConfig.APIServerServiceIP,\n\t\tServicePort: c.ExtraConfig.APIServerServicePort,\n\t\tPublicServicePort: publicServicePort,\n\t\tKubernetesServiceNodePort: c.ExtraConfig.KubernetesServiceNodePort,\n\t}, nil\n}","line":{"from":86,"to":129}} {"id":100005155,"name":"PostStartHook","signature":"func (c *Controller) PostStartHook(hookContext genericapiserver.PostStartHookContext) error","file":"pkg/controlplane/controller.go","code":"// PostStartHook initiates the core controller loops that must exist for bootstrapping.\nfunc (c *Controller) PostStartHook(hookContext genericapiserver.PostStartHookContext) error {\n\tc.Start()\n\treturn nil\n}","line":{"from":131,"to":135}} {"id":100005156,"name":"PreShutdownHook","signature":"func (c *Controller) PreShutdownHook() error","file":"pkg/controlplane/controller.go","code":"// PreShutdownHook triggers the actions needed to shut down the API Server cleanly.\nfunc (c *Controller) PreShutdownHook() error {\n\tc.Stop()\n\treturn nil\n}","line":{"from":137,"to":141}} {"id":100005157,"name":"Start","signature":"func (c *Controller) Start()","file":"pkg/controlplane/controller.go","code":"// Start begins the core controller loops that must exist for bootstrapping\n// a cluster.\nfunc (c *Controller) Start() {\n\tif c.runner != nil {\n\t\treturn\n\t}\n\n\t// Reconcile during first run removing itself until server is ready.\n\tendpointPorts := createEndpointPortSpec(c.PublicServicePort, \"https\")\n\tif err := c.EndpointReconciler.RemoveEndpoints(kubernetesServiceName, c.PublicIP, endpointPorts); err == nil {\n\t\tklog.Error(\"Found stale data, removed previous endpoints on kubernetes service, apiserver didn't exit successfully previously\")\n\t} else if !storage.IsNotFound(err) {\n\t\tklog.Errorf(\"Error removing old endpoints from kubernetes service: %v\", err)\n\t}\n\n\trepairNodePorts := portallocatorcontroller.NewRepair(c.ServiceNodePortInterval, c.client.CoreV1(), c.client.EventsV1(), c.ServiceNodePortRange, c.ServiceNodePortRegistry)\n\n\t// We start both repairClusterIPs and repairNodePorts to ensure repair\n\t// loops of ClusterIPs and NodePorts.\n\t// We run both repair loops using RunUntil public interface.\n\t// However, we want to fail liveness/readiness until the first\n\t// successful repair loop, so we basically pass appropriate\n\t// callbacks to RunUtil methods.\n\t// Additionally, we ensure that we don't wait for it for longer\n\t// than 1 minute for backward compatibility of failing the whole\n\t// apiserver if we can't repair them.\n\twg := sync.WaitGroup{}\n\twg.Add(1)\n\n\trunRepairNodePorts := func(stopCh chan struct{}) {\n\t\trepairNodePorts.RunUntil(wg.Done, stopCh)\n\t}\n\n\twg.Add(1)\n\tvar runRepairClusterIPs func(stopCh chan struct{})\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.MultiCIDRServiceAllocator) {\n\t\trepairClusterIPs := servicecontroller.NewRepair(c.ServiceClusterIPInterval,\n\t\t\tc.client.CoreV1(),\n\t\t\tc.client.EventsV1(),\n\t\t\t\u0026c.ServiceClusterIPRange,\n\t\t\tc.ServiceClusterIPRegistry,\n\t\t\t\u0026c.SecondaryServiceClusterIPRange,\n\t\t\tc.SecondaryServiceClusterIPRegistry)\n\t\trunRepairClusterIPs = func(stopCh chan struct{}) {\n\t\t\trepairClusterIPs.RunUntil(wg.Done, stopCh)\n\t\t}\n\t} else {\n\t\trepairClusterIPs := servicecontroller.NewRepairIPAddress(c.ServiceClusterIPInterval,\n\t\t\tc.client,\n\t\t\t\u0026c.ServiceClusterIPRange,\n\t\t\t\u0026c.SecondaryServiceClusterIPRange,\n\t\t\tc.informers.Core().V1().Services(),\n\t\t\tc.informers.Networking().V1alpha1().IPAddresses(),\n\t\t)\n\t\trunRepairClusterIPs = func(stopCh chan struct{}) {\n\t\t\trepairClusterIPs.RunUntil(wg.Done, stopCh)\n\t\t}\n\t}\n\tc.runner = async.NewRunner(c.RunKubernetesService, runRepairClusterIPs, runRepairNodePorts)\n\tc.runner.Start()\n\n\t// For backward compatibility, we ensure that if we never are able\n\t// to repair clusterIPs and/or nodeports, we not only fail the liveness\n\t// and/or readiness, but also explicitly fail.\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tdefer close(done)\n\t\twg.Wait()\n\t}()\n\tselect {\n\tcase \u003c-done:\n\tcase \u003c-time.After(time.Minute):\n\t\tklog.Fatalf(\"Unable to perform initial IP and Port allocation check\")\n\t}\n}","line":{"from":143,"to":217}} {"id":100005158,"name":"Stop","signature":"func (c *Controller) Stop()","file":"pkg/controlplane/controller.go","code":"// Stop cleans up this API Servers endpoint reconciliation leases so another master can take over more quickly.\nfunc (c *Controller) Stop() {\n\tif c.runner != nil {\n\t\tc.runner.Stop()\n\t}\n\tendpointPorts := createEndpointPortSpec(c.PublicServicePort, \"https\")\n\tfinishedReconciling := make(chan struct{})\n\tgo func() {\n\t\tdefer close(finishedReconciling)\n\t\tklog.Infof(\"Shutting down kubernetes service endpoint reconciler\")\n\t\tc.EndpointReconciler.StopReconciling()\n\t\tif err := c.EndpointReconciler.RemoveEndpoints(kubernetesServiceName, c.PublicIP, endpointPorts); err != nil {\n\t\t\tklog.Errorf(\"Unable to remove endpoints from kubernetes service: %v\", err)\n\t\t}\n\t\tc.EndpointReconciler.Destroy()\n\t}()\n\n\tselect {\n\tcase \u003c-finishedReconciling:\n\t\t// done\n\tcase \u003c-time.After(2 * c.EndpointInterval):\n\t\t// don't block server shutdown forever if we can't reach etcd to remove ourselves\n\t\tklog.Warning(\"RemoveEndpoints() timed out\")\n\t}\n}","line":{"from":219,"to":243}} {"id":100005159,"name":"RunKubernetesService","signature":"func (c *Controller) RunKubernetesService(ch chan struct{})","file":"pkg/controlplane/controller.go","code":"// RunKubernetesService periodically updates the kubernetes service\nfunc (c *Controller) RunKubernetesService(ch chan struct{}) {\n\t// wait until process is ready\n\twait.PollImmediateUntil(100*time.Millisecond, func() (bool, error) {\n\t\tvar code int\n\t\tc.client.CoreV1().RESTClient().Get().AbsPath(\"/readyz\").Do(context.TODO()).StatusCode(\u0026code)\n\t\treturn code == http.StatusOK, nil\n\t}, ch)\n\n\twait.NonSlidingUntil(func() {\n\t\t// Service definition is not reconciled after first\n\t\t// run, ports and type will be corrected only during\n\t\t// start.\n\t\tif err := c.UpdateKubernetesService(false); err != nil {\n\t\t\truntime.HandleError(fmt.Errorf(\"unable to sync kubernetes service: %v\", err))\n\t\t}\n\t}, c.EndpointInterval, ch)\n}","line":{"from":245,"to":262}} {"id":100005160,"name":"UpdateKubernetesService","signature":"func (c *Controller) UpdateKubernetesService(reconcile bool) error","file":"pkg/controlplane/controller.go","code":"// UpdateKubernetesService attempts to update the default Kube service.\nfunc (c *Controller) UpdateKubernetesService(reconcile bool) error {\n\t// Update service \u0026 endpoint records.\n\t// TODO: when it becomes possible to change this stuff,\n\t// stop polling and start watching.\n\t// TODO: add endpoints of all replicas, not just the elected master.\n\tif err := createNamespaceIfNeeded(c.client.CoreV1(), metav1.NamespaceDefault); err != nil {\n\t\treturn err\n\t}\n\n\tservicePorts, serviceType := createPortAndServiceSpec(c.ServicePort, c.PublicServicePort, c.KubernetesServiceNodePort, \"https\")\n\tif err := c.CreateOrUpdateMasterServiceIfNeeded(kubernetesServiceName, c.ServiceIP, servicePorts, serviceType, reconcile); err != nil {\n\t\treturn err\n\t}\n\tendpointPorts := createEndpointPortSpec(c.PublicServicePort, \"https\")\n\tif err := c.EndpointReconciler.ReconcileEndpoints(kubernetesServiceName, c.PublicIP, endpointPorts, reconcile); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":264,"to":283}} {"id":100005161,"name":"createPortAndServiceSpec","signature":"func createPortAndServiceSpec(servicePort int, targetServicePort int, nodePort int, servicePortName string) ([]corev1.ServicePort, corev1.ServiceType)","file":"pkg/controlplane/controller.go","code":"// createPortAndServiceSpec creates an array of service ports.\n// If the NodePort value is 0, just the servicePort is used, otherwise, a node port is exposed.\nfunc createPortAndServiceSpec(servicePort int, targetServicePort int, nodePort int, servicePortName string) ([]corev1.ServicePort, corev1.ServiceType) {\n\t// Use the Cluster IP type for the service port if NodePort isn't provided.\n\t// Otherwise, we will be binding the master service to a NodePort.\n\tservicePorts := []corev1.ServicePort{{\n\t\tProtocol: corev1.ProtocolTCP,\n\t\tPort: int32(servicePort),\n\t\tName: servicePortName,\n\t\tTargetPort: intstr.FromInt(targetServicePort),\n\t}}\n\tserviceType := corev1.ServiceTypeClusterIP\n\tif nodePort \u003e 0 {\n\t\tservicePorts[0].NodePort = int32(nodePort)\n\t\tserviceType = corev1.ServiceTypeNodePort\n\t}\n\treturn servicePorts, serviceType\n}","line":{"from":285,"to":302}} {"id":100005162,"name":"createEndpointPortSpec","signature":"func createEndpointPortSpec(endpointPort int, endpointPortName string) []corev1.EndpointPort","file":"pkg/controlplane/controller.go","code":"// createEndpointPortSpec creates the endpoint ports\nfunc createEndpointPortSpec(endpointPort int, endpointPortName string) []corev1.EndpointPort {\n\treturn []corev1.EndpointPort{{\n\t\tProtocol: corev1.ProtocolTCP,\n\t\tPort: int32(endpointPort),\n\t\tName: endpointPortName,\n\t}}\n}","line":{"from":304,"to":311}} {"id":100005163,"name":"CreateOrUpdateMasterServiceIfNeeded","signature":"func (c *Controller) CreateOrUpdateMasterServiceIfNeeded(serviceName string, serviceIP net.IP, servicePorts []corev1.ServicePort, serviceType corev1.ServiceType, reconcile bool) error","file":"pkg/controlplane/controller.go","code":"// CreateOrUpdateMasterServiceIfNeeded will create the specified service if it\n// doesn't already exist.\nfunc (c *Controller) CreateOrUpdateMasterServiceIfNeeded(serviceName string, serviceIP net.IP, servicePorts []corev1.ServicePort, serviceType corev1.ServiceType, reconcile bool) error {\n\tif s, err := c.client.CoreV1().Services(metav1.NamespaceDefault).Get(context.TODO(), serviceName, metav1.GetOptions{}); err == nil {\n\t\t// The service already exists.\n\t\tif reconcile {\n\t\t\tif svc, updated := getMasterServiceUpdateIfNeeded(s, servicePorts, serviceType); updated {\n\t\t\t\tklog.Warningf(\"Resetting master service %q to %#v\", serviceName, svc)\n\t\t\t\t_, err := c.client.CoreV1().Services(metav1.NamespaceDefault).Update(context.TODO(), svc, metav1.UpdateOptions{})\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\tsingleStack := corev1.IPFamilyPolicySingleStack\n\tsvc := \u0026corev1.Service{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: serviceName,\n\t\t\tNamespace: metav1.NamespaceDefault,\n\t\t\tLabels: map[string]string{\"provider\": \"kubernetes\", \"component\": \"apiserver\"},\n\t\t},\n\t\tSpec: corev1.ServiceSpec{\n\t\t\tPorts: servicePorts,\n\t\t\t// maintained by this code, not by the pod selector\n\t\t\tSelector: nil,\n\t\t\tClusterIP: serviceIP.String(),\n\t\t\tIPFamilyPolicy: \u0026singleStack,\n\t\t\tSessionAffinity: corev1.ServiceAffinityNone,\n\t\t\tType: serviceType,\n\t\t},\n\t}\n\n\t_, err := c.client.CoreV1().Services(metav1.NamespaceDefault).Create(context.TODO(), svc, metav1.CreateOptions{})\n\tif errors.IsAlreadyExists(err) {\n\t\treturn c.CreateOrUpdateMasterServiceIfNeeded(serviceName, serviceIP, servicePorts, serviceType, reconcile)\n\t}\n\treturn err\n}","line":{"from":313,"to":350}} {"id":100005164,"name":"getMasterServiceUpdateIfNeeded","signature":"func getMasterServiceUpdateIfNeeded(svc *corev1.Service, servicePorts []corev1.ServicePort, serviceType corev1.ServiceType) (s *corev1.Service, updated bool)","file":"pkg/controlplane/controller.go","code":"// getMasterServiceUpdateIfNeeded sets service attributes for the given apiserver service.\nfunc getMasterServiceUpdateIfNeeded(svc *corev1.Service, servicePorts []corev1.ServicePort, serviceType corev1.ServiceType) (s *corev1.Service, updated bool) {\n\t// Determine if the service is in the format we expect\n\t// (servicePorts are present and service type matches)\n\tformatCorrect := checkServiceFormat(svc, servicePorts, serviceType)\n\tif formatCorrect {\n\t\treturn svc, false\n\t}\n\tsvc.Spec.Ports = servicePorts\n\tsvc.Spec.Type = serviceType\n\treturn svc, true\n}","line":{"from":352,"to":363}} {"id":100005165,"name":"checkServiceFormat","signature":"func checkServiceFormat(s *corev1.Service, ports []corev1.ServicePort, serviceType corev1.ServiceType) (formatCorrect bool)","file":"pkg/controlplane/controller.go","code":"// Determine if the service is in the correct format\n// getMasterServiceUpdateIfNeeded expects (servicePorts are correct\n// and service type matches).\nfunc checkServiceFormat(s *corev1.Service, ports []corev1.ServicePort, serviceType corev1.ServiceType) (formatCorrect bool) {\n\tif s.Spec.Type != serviceType {\n\t\treturn false\n\t}\n\tif len(ports) != len(s.Spec.Ports) {\n\t\treturn false\n\t}\n\tfor i, port := range ports {\n\t\tif port != s.Spec.Ports[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":365,"to":381}} {"id":100005166,"name":"NewAPIServerLeaseGC","signature":"func NewAPIServerLeaseGC(clientset kubernetes.Interface, gcCheckPeriod time.Duration, leaseNamespace, leaseLabelSelector string) *Controller","file":"pkg/controlplane/controller/apiserverleasegc/gc_controller.go","code":"// NewAPIServerLeaseGC creates a new Controller.\nfunc NewAPIServerLeaseGC(clientset kubernetes.Interface, gcCheckPeriod time.Duration, leaseNamespace, leaseLabelSelector string) *Controller {\n\t// we construct our own informer because we need such a small subset of the information available.\n\t// Just one namespace with label selection.\n\tleaseInformer := informers.NewFilteredLeaseInformer(\n\t\tclientset,\n\t\tleaseNamespace,\n\t\t0,\n\t\tcache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},\n\t\tfunc(listOptions *metav1.ListOptions) {\n\t\t\tlistOptions.LabelSelector = leaseLabelSelector\n\t\t})\n\treturn \u0026Controller{\n\t\tkubeclientset: clientset,\n\t\tleaseLister: listers.NewLeaseLister(leaseInformer.GetIndexer()),\n\t\tleaseInformer: leaseInformer,\n\t\tleasesSynced: leaseInformer.HasSynced,\n\t\tleaseNamespace: leaseNamespace,\n\t\tgcCheckPeriod: gcCheckPeriod,\n\t}\n}","line":{"from":51,"to":71}} {"id":100005167,"name":"Run","signature":"func (c *Controller) Run(stopCh \u003c-chan struct{})","file":"pkg/controlplane/controller/apiserverleasegc/gc_controller.go","code":"// Run starts one worker.\nfunc (c *Controller) Run(stopCh \u003c-chan struct{}) {\n\tdefer utilruntime.HandleCrash()\n\tdefer klog.Infof(\"Shutting down apiserver lease garbage collector\")\n\n\tklog.Infof(\"Starting apiserver lease garbage collector\")\n\n\t// we have a personal informer that is narrowly scoped, start it.\n\tgo c.leaseInformer.Run(stopCh)\n\n\tif !cache.WaitForCacheSync(stopCh, c.leasesSynced) {\n\t\tutilruntime.HandleError(fmt.Errorf(\"timed out waiting for caches to sync\"))\n\t\treturn\n\t}\n\n\tgo wait.Until(c.gc, c.gcCheckPeriod, stopCh)\n\n\t\u003c-stopCh\n}","line":{"from":73,"to":91}} {"id":100005168,"name":"gc","signature":"func (c *Controller) gc()","file":"pkg/controlplane/controller/apiserverleasegc/gc_controller.go","code":"func (c *Controller) gc() {\n\tleases, err := c.leaseLister.Leases(c.leaseNamespace).List(labels.Everything())\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Error while listing apiserver leases\")\n\t\treturn\n\t}\n\tfor _, lease := range leases {\n\t\t// evaluate lease from cache\n\t\tif !isLeaseExpired(lease) {\n\t\t\tcontinue\n\t\t}\n\t\t// double check latest lease from apiserver before deleting\n\t\tlease, err := c.kubeclientset.CoordinationV1().Leases(c.leaseNamespace).Get(context.TODO(), lease.Name, metav1.GetOptions{})\n\t\tif err != nil \u0026\u0026 !errors.IsNotFound(err) {\n\t\t\tklog.ErrorS(err, \"Error getting lease\")\n\t\t\tcontinue\n\t\t}\n\t\tif errors.IsNotFound(err) || lease == nil {\n\t\t\t// In an HA cluster, this can happen if the lease was deleted\n\t\t\t// by the same GC controller in another apiserver, which is legit.\n\t\t\t// We don't expect other components to delete the lease.\n\t\t\tklog.V(4).InfoS(\"Cannot find apiserver lease\", \"err\", err)\n\t\t\tcontinue\n\t\t}\n\t\t// evaluate lease from apiserver\n\t\tif !isLeaseExpired(lease) {\n\t\t\tcontinue\n\t\t}\n\t\tif err := c.kubeclientset.CoordinationV1().Leases(c.leaseNamespace).Delete(\n\t\t\tcontext.TODO(), lease.Name, metav1.DeleteOptions{}); err != nil {\n\t\t\tif errors.IsNotFound(err) {\n\t\t\t\t// In an HA cluster, this can happen if the lease was deleted\n\t\t\t\t// by the same GC controller in another apiserver, which is legit.\n\t\t\t\t// We don't expect other components to delete the lease.\n\t\t\t\tklog.V(4).InfoS(\"Apiserver lease is gone already\", \"err\", err)\n\t\t\t} else {\n\t\t\t\tklog.ErrorS(err, \"Error deleting lease\")\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":93,"to":133}} {"id":100005169,"name":"isLeaseExpired","signature":"func isLeaseExpired(lease *v1.Lease) bool","file":"pkg/controlplane/controller/apiserverleasegc/gc_controller.go","code":"func isLeaseExpired(lease *v1.Lease) bool {\n\tcurrentTime := time.Now()\n\t// Leases created by the apiserver lease controller should have non-nil renew time\n\t// and lease duration set. Leases without these fields set are invalid and should\n\t// be GC'ed.\n\treturn lease.Spec.RenewTime == nil ||\n\t\tlease.Spec.LeaseDurationSeconds == nil ||\n\t\tlease.Spec.RenewTime.Add(time.Duration(*lease.Spec.LeaseDurationSeconds)*time.Second).Before(currentTime)\n}","line":{"from":135,"to":143}} {"id":100005170,"name":"NewClusterAuthenticationTrustController","signature":"func NewClusterAuthenticationTrustController(requiredAuthenticationData ClusterAuthenticationInfo, kubeClient kubernetes.Interface) *Controller","file":"pkg/controlplane/controller/clusterauthenticationtrust/cluster_authentication_trust_controller.go","code":"// NewClusterAuthenticationTrustController returns a controller that will maintain the kube-system configmap/extension-apiserver-authentication\n// that holds information about how to aggregated apiservers are recommended (but not required) to configure themselves.\nfunc NewClusterAuthenticationTrustController(requiredAuthenticationData ClusterAuthenticationInfo, kubeClient kubernetes.Interface) *Controller {\n\t// we construct our own informer because we need such a small subset of the information available. Just one namespace.\n\tkubeSystemConfigMapInformer := corev1informers.NewConfigMapInformer(kubeClient, configMapNamespace, 12*time.Hour, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc})\n\n\tc := \u0026Controller{\n\t\trequiredAuthenticationData: requiredAuthenticationData,\n\t\tconfigMapLister: corev1listers.NewConfigMapLister(kubeSystemConfigMapInformer.GetIndexer()),\n\t\tconfigMapClient: kubeClient.CoreV1(),\n\t\tnamespaceClient: kubeClient.CoreV1(),\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"cluster_authentication_trust_controller\"),\n\t\tpreRunCaches: []cache.InformerSynced{kubeSystemConfigMapInformer.HasSynced},\n\t\tkubeSystemConfigMapInformer: kubeSystemConfigMapInformer,\n\t}\n\n\tkubeSystemConfigMapInformer.AddEventHandler(cache.FilteringResourceEventHandler{\n\t\tFilterFunc: func(obj interface{}) bool {\n\t\t\tif cast, ok := obj.(*corev1.ConfigMap); ok {\n\t\t\t\treturn cast.Name == configMapName\n\t\t\t}\n\t\t\tif tombstone, ok := obj.(cache.DeletedFinalStateUnknown); ok {\n\t\t\t\tif cast, ok := tombstone.Obj.(*corev1.ConfigMap); ok {\n\t\t\t\t\treturn cast.Name == configMapName\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true // always return true just in case. The checks are fairly cheap\n\t\t},\n\t\tHandler: cache.ResourceEventHandlerFuncs{\n\t\t\t// we have a filter, so any time we're called, we may as well queue. We only ever check one configmap\n\t\t\t// so we don't have to be choosy about our key.\n\t\t\tAddFunc: func(obj interface{}) {\n\t\t\t\tc.queue.Add(keyFn())\n\t\t\t},\n\t\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\t\tc.queue.Add(keyFn())\n\t\t\t},\n\t\t\tDeleteFunc: func(obj interface{}) {\n\t\t\t\tc.queue.Add(keyFn())\n\t\t\t},\n\t\t},\n\t})\n\n\treturn c\n}","line":{"from":90,"to":134}} {"id":100005171,"name":"syncConfigMap","signature":"func (c *Controller) syncConfigMap() error","file":"pkg/controlplane/controller/clusterauthenticationtrust/cluster_authentication_trust_controller.go","code":"func (c *Controller) syncConfigMap() error {\n\toriginalAuthConfigMap, err := c.configMapLister.ConfigMaps(configMapNamespace).Get(configMapName)\n\tif apierrors.IsNotFound(err) {\n\t\toriginalAuthConfigMap = \u0026corev1.ConfigMap{\n\t\t\tObjectMeta: metav1.ObjectMeta{Namespace: configMapNamespace, Name: configMapName},\n\t\t}\n\t} else if err != nil {\n\t\treturn err\n\t}\n\t// keep the original to diff against later before updating\n\tauthConfigMap := originalAuthConfigMap.DeepCopy()\n\n\texistingAuthenticationInfo, err := getClusterAuthenticationInfoFor(originalAuthConfigMap.Data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcombinedInfo, err := combinedClusterAuthenticationInfo(existingAuthenticationInfo, c.requiredAuthenticationData)\n\tif err != nil {\n\t\treturn err\n\t}\n\tauthConfigMap.Data, err = getConfigMapDataFor(combinedInfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif equality.Semantic.DeepEqual(authConfigMap, originalAuthConfigMap) {\n\t\tklog.V(5).Info(\"no changes to configmap\")\n\t\treturn nil\n\t}\n\tklog.V(2).Infof(\"writing updated authentication info to %s configmaps/%s\", configMapNamespace, configMapName)\n\n\tif err := createNamespaceIfNeeded(c.namespaceClient, authConfigMap.Namespace); err != nil {\n\t\treturn err\n\t}\n\tif err := writeConfigMap(c.configMapClient, authConfigMap); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":136,"to":175}} {"id":100005172,"name":"createNamespaceIfNeeded","signature":"func createNamespaceIfNeeded(nsClient corev1client.NamespacesGetter, ns string) error","file":"pkg/controlplane/controller/clusterauthenticationtrust/cluster_authentication_trust_controller.go","code":"func createNamespaceIfNeeded(nsClient corev1client.NamespacesGetter, ns string) error {\n\tif _, err := nsClient.Namespaces().Get(context.TODO(), ns, metav1.GetOptions{}); err == nil {\n\t\t// the namespace already exists\n\t\treturn nil\n\t}\n\tnewNs := \u0026corev1.Namespace{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: ns,\n\t\t\tNamespace: \"\",\n\t\t},\n\t}\n\t_, err := nsClient.Namespaces().Create(context.TODO(), newNs, metav1.CreateOptions{})\n\tif err != nil \u0026\u0026 apierrors.IsAlreadyExists(err) {\n\t\terr = nil\n\t}\n\treturn err\n}","line":{"from":177,"to":193}} {"id":100005173,"name":"writeConfigMap","signature":"func writeConfigMap(configMapClient corev1client.ConfigMapsGetter, required *corev1.ConfigMap) error","file":"pkg/controlplane/controller/clusterauthenticationtrust/cluster_authentication_trust_controller.go","code":"func writeConfigMap(configMapClient corev1client.ConfigMapsGetter, required *corev1.ConfigMap) error {\n\t_, err := configMapClient.ConfigMaps(required.Namespace).Update(context.TODO(), required, metav1.UpdateOptions{})\n\tif apierrors.IsNotFound(err) {\n\t\t_, err := configMapClient.ConfigMaps(required.Namespace).Create(context.TODO(), required, metav1.CreateOptions{})\n\t\treturn err\n\t}\n\n\t// If the configmap is too big, clear the entire thing and count on this controller (or another one) to add the correct data back.\n\t// We return the original error which causes the controller to re-queue.\n\t// Too big means\n\t// 1. request is so big the generic request catcher finds it\n\t// 2. the content is so large that that the server sends a validation error \"Too long: must have at most 1048576 characters\"\n\tif apierrors.IsRequestEntityTooLargeError(err) || (apierrors.IsInvalid(err) \u0026\u0026 strings.Contains(err.Error(), \"Too long\")) {\n\t\tif deleteErr := configMapClient.ConfigMaps(required.Namespace).Delete(context.TODO(), required.Name, metav1.DeleteOptions{}); deleteErr != nil {\n\t\t\treturn deleteErr\n\t\t}\n\t\treturn err\n\t}\n\n\treturn err\n}","line":{"from":195,"to":215}} {"id":100005174,"name":"combinedClusterAuthenticationInfo","signature":"func combinedClusterAuthenticationInfo(lhs, rhs ClusterAuthenticationInfo) (ClusterAuthenticationInfo, error)","file":"pkg/controlplane/controller/clusterauthenticationtrust/cluster_authentication_trust_controller.go","code":"// combinedClusterAuthenticationInfo combines two sets of authentication information into a new one\nfunc combinedClusterAuthenticationInfo(lhs, rhs ClusterAuthenticationInfo) (ClusterAuthenticationInfo, error) {\n\tret := ClusterAuthenticationInfo{\n\t\tRequestHeaderAllowedNames: combineUniqueStringSlices(lhs.RequestHeaderAllowedNames, rhs.RequestHeaderAllowedNames),\n\t\tRequestHeaderExtraHeaderPrefixes: combineUniqueStringSlices(lhs.RequestHeaderExtraHeaderPrefixes, rhs.RequestHeaderExtraHeaderPrefixes),\n\t\tRequestHeaderGroupHeaders: combineUniqueStringSlices(lhs.RequestHeaderGroupHeaders, rhs.RequestHeaderGroupHeaders),\n\t\tRequestHeaderUsernameHeaders: combineUniqueStringSlices(lhs.RequestHeaderUsernameHeaders, rhs.RequestHeaderUsernameHeaders),\n\t}\n\n\tvar err error\n\tret.ClientCA, err = combineCertLists(lhs.ClientCA, rhs.ClientCA)\n\tif err != nil {\n\t\treturn ClusterAuthenticationInfo{}, err\n\t}\n\tret.RequestHeaderCA, err = combineCertLists(lhs.RequestHeaderCA, rhs.RequestHeaderCA)\n\tif err != nil {\n\t\treturn ClusterAuthenticationInfo{}, err\n\t}\n\n\treturn ret, nil\n}","line":{"from":217,"to":237}} {"id":100005175,"name":"getConfigMapDataFor","signature":"func getConfigMapDataFor(authenticationInfo ClusterAuthenticationInfo) (map[string]string, error)","file":"pkg/controlplane/controller/clusterauthenticationtrust/cluster_authentication_trust_controller.go","code":"func getConfigMapDataFor(authenticationInfo ClusterAuthenticationInfo) (map[string]string, error) {\n\tdata := map[string]string{}\n\tif authenticationInfo.ClientCA != nil {\n\t\tif caBytes := authenticationInfo.ClientCA.CurrentCABundleContent(); len(caBytes) \u003e 0 {\n\t\t\tdata[\"client-ca-file\"] = string(caBytes)\n\t\t}\n\t}\n\n\tif authenticationInfo.RequestHeaderCA == nil {\n\t\treturn data, nil\n\t}\n\n\tif caBytes := authenticationInfo.RequestHeaderCA.CurrentCABundleContent(); len(caBytes) \u003e 0 {\n\t\tvar err error\n\n\t\t// encoding errors aren't going to get better, so just fail on them.\n\t\tdata[\"requestheader-username-headers\"], err = jsonSerializeStringSlice(authenticationInfo.RequestHeaderUsernameHeaders.Value())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdata[\"requestheader-group-headers\"], err = jsonSerializeStringSlice(authenticationInfo.RequestHeaderGroupHeaders.Value())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdata[\"requestheader-extra-headers-prefix\"], err = jsonSerializeStringSlice(authenticationInfo.RequestHeaderExtraHeaderPrefixes.Value())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tdata[\"requestheader-client-ca-file\"] = string(caBytes)\n\t\tdata[\"requestheader-allowed-names\"], err = jsonSerializeStringSlice(authenticationInfo.RequestHeaderAllowedNames.Value())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn data, nil\n}","line":{"from":239,"to":276}} {"id":100005176,"name":"getClusterAuthenticationInfoFor","signature":"func getClusterAuthenticationInfoFor(data map[string]string) (ClusterAuthenticationInfo, error)","file":"pkg/controlplane/controller/clusterauthenticationtrust/cluster_authentication_trust_controller.go","code":"func getClusterAuthenticationInfoFor(data map[string]string) (ClusterAuthenticationInfo, error) {\n\tret := ClusterAuthenticationInfo{}\n\n\tvar err error\n\tret.RequestHeaderGroupHeaders, err = jsonDeserializeStringSlice(data[\"requestheader-group-headers\"])\n\tif err != nil {\n\t\treturn ClusterAuthenticationInfo{}, err\n\t}\n\tret.RequestHeaderExtraHeaderPrefixes, err = jsonDeserializeStringSlice(data[\"requestheader-extra-headers-prefix\"])\n\tif err != nil {\n\t\treturn ClusterAuthenticationInfo{}, err\n\t}\n\tret.RequestHeaderAllowedNames, err = jsonDeserializeStringSlice(data[\"requestheader-allowed-names\"])\n\tif err != nil {\n\t\treturn ClusterAuthenticationInfo{}, err\n\t}\n\tret.RequestHeaderUsernameHeaders, err = jsonDeserializeStringSlice(data[\"requestheader-username-headers\"])\n\tif err != nil {\n\t\treturn ClusterAuthenticationInfo{}, err\n\t}\n\n\tif caBundle := data[\"requestheader-client-ca-file\"]; len(caBundle) \u003e 0 {\n\t\tret.RequestHeaderCA, err = dynamiccertificates.NewStaticCAContent(\"existing\", []byte(caBundle))\n\t\tif err != nil {\n\t\t\treturn ClusterAuthenticationInfo{}, err\n\t\t}\n\t}\n\n\tif caBundle := data[\"client-ca-file\"]; len(caBundle) \u003e 0 {\n\t\tret.ClientCA, err = dynamiccertificates.NewStaticCAContent(\"existing\", []byte(caBundle))\n\t\tif err != nil {\n\t\t\treturn ClusterAuthenticationInfo{}, err\n\t\t}\n\t}\n\n\treturn ret, nil\n}","line":{"from":278,"to":314}} {"id":100005177,"name":"jsonSerializeStringSlice","signature":"func jsonSerializeStringSlice(in []string) (string, error)","file":"pkg/controlplane/controller/clusterauthenticationtrust/cluster_authentication_trust_controller.go","code":"func jsonSerializeStringSlice(in []string) (string, error) {\n\tout, err := json.Marshal(in)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(out), err\n}","line":{"from":316,"to":322}} {"id":100005178,"name":"jsonDeserializeStringSlice","signature":"func jsonDeserializeStringSlice(in string) (headerrequest.StringSliceProvider, error)","file":"pkg/controlplane/controller/clusterauthenticationtrust/cluster_authentication_trust_controller.go","code":"func jsonDeserializeStringSlice(in string) (headerrequest.StringSliceProvider, error) {\n\tif len(in) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tout := []string{}\n\tif err := json.Unmarshal([]byte(in), \u0026out); err != nil {\n\t\treturn nil, err\n\t}\n\treturn headerrequest.StaticStringSlice(out), nil\n}","line":{"from":324,"to":334}} {"id":100005179,"name":"combineUniqueStringSlices","signature":"func combineUniqueStringSlices(lhs, rhs headerrequest.StringSliceProvider) headerrequest.StringSliceProvider","file":"pkg/controlplane/controller/clusterauthenticationtrust/cluster_authentication_trust_controller.go","code":"func combineUniqueStringSlices(lhs, rhs headerrequest.StringSliceProvider) headerrequest.StringSliceProvider {\n\tret := []string{}\n\tpresent := sets.String{}\n\n\tif lhs != nil {\n\t\tfor _, curr := range lhs.Value() {\n\t\t\tif present.Has(curr) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tret = append(ret, curr)\n\t\t\tpresent.Insert(curr)\n\t\t}\n\t}\n\n\tif rhs != nil {\n\t\tfor _, curr := range rhs.Value() {\n\t\t\tif present.Has(curr) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tret = append(ret, curr)\n\t\t\tpresent.Insert(curr)\n\t\t}\n\t}\n\n\treturn headerrequest.StaticStringSlice(ret)\n}","line":{"from":336,"to":361}} {"id":100005180,"name":"combineCertLists","signature":"func combineCertLists(lhs, rhs dynamiccertificates.CAContentProvider) (dynamiccertificates.CAContentProvider, error)","file":"pkg/controlplane/controller/clusterauthenticationtrust/cluster_authentication_trust_controller.go","code":"func combineCertLists(lhs, rhs dynamiccertificates.CAContentProvider) (dynamiccertificates.CAContentProvider, error) {\n\tcertificates := []*x509.Certificate{}\n\n\tif lhs != nil {\n\t\tlhsCABytes := lhs.CurrentCABundleContent()\n\t\tlhsCAs, err := cert.ParseCertsPEM(lhsCABytes)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcertificates = append(certificates, lhsCAs...)\n\t}\n\tif rhs != nil {\n\t\trhsCABytes := rhs.CurrentCABundleContent()\n\t\trhsCAs, err := cert.ParseCertsPEM(rhsCABytes)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcertificates = append(certificates, rhsCAs...)\n\t}\n\n\tcertificates = filterExpiredCerts(certificates...)\n\n\tfinalCertificates := []*x509.Certificate{}\n\t// now check for duplicates. n^2, but super simple\n\tfor i := range certificates {\n\t\tfound := false\n\t\tfor j := range finalCertificates {\n\t\t\tif reflect.DeepEqual(certificates[i].Raw, finalCertificates[j].Raw) {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tfinalCertificates = append(finalCertificates, certificates[i])\n\t\t}\n\t}\n\n\tfinalCABytes, err := encodeCertificates(finalCertificates...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(finalCABytes) == 0 {\n\t\treturn nil, nil\n\t}\n\t// it makes sense for this list to be static because the combination of sources is only used just before writing and\n\t// is recalculated\n\treturn dynamiccertificates.NewStaticCAContent(\"combined\", finalCABytes)\n}","line":{"from":363,"to":411}} {"id":100005181,"name":"filterExpiredCerts","signature":"func filterExpiredCerts(certs ...*x509.Certificate) []*x509.Certificate","file":"pkg/controlplane/controller/clusterauthenticationtrust/cluster_authentication_trust_controller.go","code":"// filterExpiredCerts checks are all certificates in the bundle valid, i.e. they have not expired.\n// The function returns new bundle with only valid certificates or error if no valid certificate is found.\n// We allow five minutes of slack for NotAfter comparisons\nfunc filterExpiredCerts(certs ...*x509.Certificate) []*x509.Certificate {\n\tfiveMinutesAgo := time.Now().Add(-5 * time.Minute)\n\n\tvar validCerts []*x509.Certificate\n\tfor _, c := range certs {\n\t\tif c.NotAfter.After(fiveMinutesAgo) {\n\t\t\tvalidCerts = append(validCerts, c)\n\t\t}\n\t}\n\n\treturn validCerts\n}","line":{"from":413,"to":427}} {"id":100005182,"name":"Enqueue","signature":"func (c *Controller) Enqueue()","file":"pkg/controlplane/controller/clusterauthenticationtrust/cluster_authentication_trust_controller.go","code":"// Enqueue a method to allow separate control loops to cause the controller to trigger and reconcile content.\nfunc (c *Controller) Enqueue() {\n\tc.queue.Add(keyFn())\n}","line":{"from":429,"to":432}} {"id":100005183,"name":"Run","signature":"func (c *Controller) Run(ctx context.Context, workers int)","file":"pkg/controlplane/controller/clusterauthenticationtrust/cluster_authentication_trust_controller.go","code":"// Run the controller until stopped.\nfunc (c *Controller) Run(ctx context.Context, workers int) {\n\tdefer utilruntime.HandleCrash()\n\t// make sure the work queue is shutdown which will trigger workers to end\n\tdefer c.queue.ShutDown()\n\n\tklog.Infof(\"Starting cluster_authentication_trust_controller controller\")\n\tdefer klog.Infof(\"Shutting down cluster_authentication_trust_controller controller\")\n\n\t// we have a personal informer that is narrowly scoped, start it.\n\tgo c.kubeSystemConfigMapInformer.Run(ctx.Done())\n\n\t// wait for your secondary caches to fill before starting your work\n\tif !cache.WaitForNamedCacheSync(\"cluster_authentication_trust_controller\", ctx.Done(), c.preRunCaches...) {\n\t\treturn\n\t}\n\n\t// only run one worker\n\tgo wait.Until(c.runWorker, time.Second, ctx.Done())\n\n\t// checks are cheap. run once a minute just to be sure we stay in sync in case fsnotify fails again\n\t// start timer that rechecks every minute, just in case. this also serves to prime the controller quickly.\n\t_ = wait.PollImmediateUntil(1*time.Minute, func() (bool, error) {\n\t\tc.queue.Add(keyFn())\n\t\treturn false, nil\n\t}, ctx.Done())\n\n\t// wait until we're told to stop\n\t\u003c-ctx.Done()\n}","line":{"from":434,"to":463}} {"id":100005184,"name":"runWorker","signature":"func (c *Controller) runWorker()","file":"pkg/controlplane/controller/clusterauthenticationtrust/cluster_authentication_trust_controller.go","code":"func (c *Controller) runWorker() {\n\t// hot loop until we're told to stop. processNextWorkItem will automatically wait until there's work\n\t// available, so we don't worry about secondary waits\n\tfor c.processNextWorkItem() {\n\t}\n}","line":{"from":465,"to":470}} {"id":100005185,"name":"processNextWorkItem","signature":"func (c *Controller) processNextWorkItem() bool","file":"pkg/controlplane/controller/clusterauthenticationtrust/cluster_authentication_trust_controller.go","code":"// processNextWorkItem deals with one key off the queue. It returns false when it's time to quit.\nfunc (c *Controller) processNextWorkItem() bool {\n\t// pull the next work item from queue. It should be a key we use to lookup something in a cache\n\tkey, quit := c.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\t// you always have to indicate to the queue that you've completed a piece of work\n\tdefer c.queue.Done(key)\n\n\t// do your work on the key. This method will contains your \"do stuff\" logic\n\terr := c.syncConfigMap()\n\tif err == nil {\n\t\t// if you had no error, tell the queue to stop tracking history for your key. This will\n\t\t// reset things like failure counts for per-item rate limiting\n\t\tc.queue.Forget(key)\n\t\treturn true\n\t}\n\n\t// there was a failure so be sure to report it. This method allows for pluggable error handling\n\t// which can be used for things like cluster-monitoring\n\tutilruntime.HandleError(fmt.Errorf(\"%v failed with : %v\", key, err))\n\t// since we failed, we should requeue the item to work on later. This method will add a backoff\n\t// to avoid hotlooping on particular items (they're probably still not going to work right away)\n\t// and overall controller protection (everything I've done is broken, this controller needs to\n\t// calm down or it can starve other useful work) cases.\n\tc.queue.AddRateLimited(key)\n\n\treturn true\n}","line":{"from":472,"to":501}} {"id":100005186,"name":"keyFn","signature":"func keyFn() string","file":"pkg/controlplane/controller/clusterauthenticationtrust/cluster_authentication_trust_controller.go","code":"func keyFn() string {\n\t// this format matches DeletionHandlingMetaNamespaceKeyFunc for our single key\n\treturn configMapNamespace + \"/\" + configMapName\n}","line":{"from":503,"to":506}} {"id":100005187,"name":"encodeCertificates","signature":"func encodeCertificates(certs ...*x509.Certificate) ([]byte, error)","file":"pkg/controlplane/controller/clusterauthenticationtrust/cluster_authentication_trust_controller.go","code":"func encodeCertificates(certs ...*x509.Certificate) ([]byte, error) {\n\tb := bytes.Buffer{}\n\tfor _, cert := range certs {\n\t\tif err := pem.Encode(\u0026b, \u0026pem.Block{Type: \"CERTIFICATE\", Bytes: cert.Raw}); err != nil {\n\t\t\treturn []byte{}, err\n\t\t}\n\t}\n\treturn b.Bytes(), nil\n}","line":{"from":508,"to":516}} {"id":100005188,"name":"NewCRDRegistrationController","signature":"func NewCRDRegistrationController(crdinformer crdinformers.CustomResourceDefinitionInformer, apiServiceRegistration AutoAPIServiceRegistration) *crdRegistrationController","file":"pkg/controlplane/controller/crdregistration/crdregistration_controller.go","code":"// NewCRDRegistrationController returns a controller which will register CRD GroupVersions with the auto APIService registration\n// controller so they automatically stay in sync.\nfunc NewCRDRegistrationController(crdinformer crdinformers.CustomResourceDefinitionInformer, apiServiceRegistration AutoAPIServiceRegistration) *crdRegistrationController {\n\tc := \u0026crdRegistrationController{\n\t\tcrdLister: crdinformer.Lister(),\n\t\tcrdSynced: crdinformer.Informer().HasSynced,\n\t\tapiServiceRegistration: apiServiceRegistration,\n\t\tsyncedInitialSet: make(chan struct{}),\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"crd_autoregistration_controller\"),\n\t}\n\tc.syncHandler = c.handleVersionUpdate\n\n\tcrdinformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tcast := obj.(*apiextensionsv1.CustomResourceDefinition)\n\t\t\tc.enqueueCRD(cast)\n\t\t},\n\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\t// Enqueue both old and new object to make sure we remove and add appropriate API services.\n\t\t\t// The working queue will resolve any duplicates and only changes will stay in the queue.\n\t\t\tc.enqueueCRD(oldObj.(*apiextensionsv1.CustomResourceDefinition))\n\t\t\tc.enqueueCRD(newObj.(*apiextensionsv1.CustomResourceDefinition))\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tcast, ok := obj.(*apiextensionsv1.CustomResourceDefinition)\n\t\t\tif !ok {\n\t\t\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\t\t\tif !ok {\n\t\t\t\t\tklog.V(2).Infof(\"Couldn't get object from tombstone %#v\", obj)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcast, ok = tombstone.Obj.(*apiextensionsv1.CustomResourceDefinition)\n\t\t\t\tif !ok {\n\t\t\t\t\tklog.V(2).Infof(\"Tombstone contained unexpected object: %#v\", obj)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tc.enqueueCRD(cast)\n\t\t},\n\t})\n\n\treturn c\n}","line":{"from":62,"to":104}} {"id":100005189,"name":"Run","signature":"func (c *crdRegistrationController) Run(workers int, stopCh \u003c-chan struct{})","file":"pkg/controlplane/controller/crdregistration/crdregistration_controller.go","code":"func (c *crdRegistrationController) Run(workers int, stopCh \u003c-chan struct{}) {\n\tdefer utilruntime.HandleCrash()\n\t// make sure the work queue is shutdown which will trigger workers to end\n\tdefer c.queue.ShutDown()\n\n\tklog.Infof(\"Starting crd-autoregister controller\")\n\tdefer klog.Infof(\"Shutting down crd-autoregister controller\")\n\n\t// wait for your secondary caches to fill before starting your work\n\tif !cache.WaitForNamedCacheSync(\"crd-autoregister\", stopCh, c.crdSynced) {\n\t\treturn\n\t}\n\n\t// process each item in the list once\n\tif crds, err := c.crdLister.List(labels.Everything()); err != nil {\n\t\tutilruntime.HandleError(err)\n\t} else {\n\t\tfor _, crd := range crds {\n\t\t\tfor _, version := range crd.Spec.Versions {\n\t\t\t\tif err := c.syncHandler(schema.GroupVersion{Group: crd.Spec.Group, Version: version.Name}); err != nil {\n\t\t\t\t\tutilruntime.HandleError(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tclose(c.syncedInitialSet)\n\n\t// start up your worker threads based on workers. Some controllers have multiple kinds of workers\n\tfor i := 0; i \u003c workers; i++ {\n\t\t// runWorker will loop until \"something bad\" happens. The .Until will then rekick the worker\n\t\t// after one second\n\t\tgo wait.Until(c.runWorker, time.Second, stopCh)\n\t}\n\n\t// wait until we're told to stop\n\t\u003c-stopCh\n}","line":{"from":106,"to":142}} {"id":100005190,"name":"WaitForInitialSync","signature":"func (c *crdRegistrationController) WaitForInitialSync()","file":"pkg/controlplane/controller/crdregistration/crdregistration_controller.go","code":"// WaitForInitialSync blocks until the initial set of CRD resources has been processed\nfunc (c *crdRegistrationController) WaitForInitialSync() {\n\t\u003c-c.syncedInitialSet\n}","line":{"from":144,"to":147}} {"id":100005191,"name":"runWorker","signature":"func (c *crdRegistrationController) runWorker()","file":"pkg/controlplane/controller/crdregistration/crdregistration_controller.go","code":"func (c *crdRegistrationController) runWorker() {\n\t// hot loop until we're told to stop. processNextWorkItem will automatically wait until there's work\n\t// available, so we don't worry about secondary waits\n\tfor c.processNextWorkItem() {\n\t}\n}","line":{"from":149,"to":154}} {"id":100005192,"name":"processNextWorkItem","signature":"func (c *crdRegistrationController) processNextWorkItem() bool","file":"pkg/controlplane/controller/crdregistration/crdregistration_controller.go","code":"// processNextWorkItem deals with one key off the queue. It returns false when it's time to quit.\nfunc (c *crdRegistrationController) processNextWorkItem() bool {\n\t// pull the next work item from queue. It should be a key we use to lookup something in a cache\n\tkey, quit := c.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\t// you always have to indicate to the queue that you've completed a piece of work\n\tdefer c.queue.Done(key)\n\n\t// do your work on the key. This method will contains your \"do stuff\" logic\n\terr := c.syncHandler(key.(schema.GroupVersion))\n\tif err == nil {\n\t\t// if you had no error, tell the queue to stop tracking history for your key. This will\n\t\t// reset things like failure counts for per-item rate limiting\n\t\tc.queue.Forget(key)\n\t\treturn true\n\t}\n\n\t// there was a failure so be sure to report it. This method allows for pluggable error handling\n\t// which can be used for things like cluster-monitoring\n\tutilruntime.HandleError(fmt.Errorf(\"%v failed with : %v\", key, err))\n\t// since we failed, we should requeue the item to work on later. This method will add a backoff\n\t// to avoid hotlooping on particular items (they're probably still not going to work right away)\n\t// and overall controller protection (everything I've done is broken, this controller needs to\n\t// calm down or it can starve other useful work) cases.\n\tc.queue.AddRateLimited(key)\n\n\treturn true\n}","line":{"from":156,"to":185}} {"id":100005193,"name":"enqueueCRD","signature":"func (c *crdRegistrationController) enqueueCRD(crd *apiextensionsv1.CustomResourceDefinition)","file":"pkg/controlplane/controller/crdregistration/crdregistration_controller.go","code":"func (c *crdRegistrationController) enqueueCRD(crd *apiextensionsv1.CustomResourceDefinition) {\n\tfor _, version := range crd.Spec.Versions {\n\t\tc.queue.Add(schema.GroupVersion{Group: crd.Spec.Group, Version: version.Name})\n\t}\n}","line":{"from":187,"to":191}} {"id":100005194,"name":"handleVersionUpdate","signature":"func (c *crdRegistrationController) handleVersionUpdate(groupVersion schema.GroupVersion) error","file":"pkg/controlplane/controller/crdregistration/crdregistration_controller.go","code":"func (c *crdRegistrationController) handleVersionUpdate(groupVersion schema.GroupVersion) error {\n\tapiServiceName := groupVersion.Version + \".\" + groupVersion.Group\n\n\t// check all CRDs. There shouldn't that many, but if we have problems later we can index them\n\tcrds, err := c.crdLister.List(labels.Everything())\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, crd := range crds {\n\t\tif crd.Spec.Group != groupVersion.Group {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, version := range crd.Spec.Versions {\n\t\t\tif version.Name != groupVersion.Version || !version.Served {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tc.apiServiceRegistration.AddAPIServiceToSync(\u0026v1.APIService{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{Name: apiServiceName},\n\t\t\t\tSpec: v1.APIServiceSpec{\n\t\t\t\t\tGroup: groupVersion.Group,\n\t\t\t\t\tVersion: groupVersion.Version,\n\t\t\t\t\tGroupPriorityMinimum: 1000, // CRDs should have relatively low priority\n\t\t\t\t\tVersionPriority: 100, // CRDs will be sorted by kube-like versions like any other APIService with the same VersionPriority\n\t\t\t\t},\n\t\t\t})\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tc.apiServiceRegistration.RemoveAPIServiceToSync(apiServiceName)\n\treturn nil\n}","line":{"from":193,"to":225}} {"id":100005195,"name":"NewController","signature":"func NewController(cs kubernetes.Interface) *Controller","file":"pkg/controlplane/controller/legacytokentracking/controller.go","code":"// NewController returns a Controller struct.\nfunc NewController(cs kubernetes.Interface) *Controller {\n\treturn newController(cs, clock.RealClock{}, rate.NewLimiter(rate.Every(30*time.Minute), 1))\n}","line":{"from":76,"to":79}} {"id":100005196,"name":"newController","signature":"func newController(cs kubernetes.Interface, cl clock.Clock, limiter *rate.Limiter) *Controller","file":"pkg/controlplane/controller/legacytokentracking/controller.go","code":"func newController(cs kubernetes.Interface, cl clock.Clock, limiter *rate.Limiter) *Controller {\n\tinformer := corev1informers.NewFilteredConfigMapInformer(cs, metav1.NamespaceSystem, 12*time.Hour, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, func(options *metav1.ListOptions) {\n\t\toptions.FieldSelector = fields.OneTermEqualSelector(\"metadata.name\", ConfigMapName).String()\n\t})\n\n\tc := \u0026Controller{\n\t\tconfigMapClient: cs.CoreV1(),\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"legacy_token_tracking_controller\"),\n\t\tconfigMapInformer: informer,\n\t\tconfigMapCache: informer.GetIndexer(),\n\t\tconfigMapSynced: informer.HasSynced,\n\t\tenabled: utilfeature.DefaultFeatureGate.Enabled(kubefeatures.LegacyServiceAccountTokenTracking),\n\t\tcreationRatelimiter: limiter,\n\t\tclock: cl,\n\t}\n\n\tinformer.AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tc.enqueue()\n\t\t},\n\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\tc.enqueue()\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tc.enqueue()\n\t\t},\n\t})\n\n\treturn c\n}","line":{"from":81,"to":110}} {"id":100005197,"name":"enqueue","signature":"func (c *Controller) enqueue()","file":"pkg/controlplane/controller/legacytokentracking/controller.go","code":"func (c *Controller) enqueue() {\n\tc.queue.Add(queueKey)\n}","line":{"from":112,"to":114}} {"id":100005198,"name":"Run","signature":"func (c *Controller) Run(stopCh \u003c-chan struct{})","file":"pkg/controlplane/controller/legacytokentracking/controller.go","code":"// Run starts the controller sync loop.\nfunc (c *Controller) Run(stopCh \u003c-chan struct{}) {\n\tdefer utilruntime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\n\tklog.Info(\"Starting legacy_token_tracking_controller\")\n\tdefer klog.Infof(\"Shutting down legacy_token_tracking_controller\")\n\n\tgo c.configMapInformer.Run(stopCh)\n\tif !cache.WaitForNamedCacheSync(\"configmaps\", stopCh, c.configMapSynced) {\n\t\treturn\n\t}\n\n\tgo wait.Until(c.runWorker, time.Second, stopCh)\n\n\tc.queue.Add(queueKey)\n\n\t\u003c-stopCh\n\tklog.Info(\"Ending legacy_token_tracking_controller\")\n}","line":{"from":116,"to":135}} {"id":100005199,"name":"runWorker","signature":"func (c *Controller) runWorker()","file":"pkg/controlplane/controller/legacytokentracking/controller.go","code":"func (c *Controller) runWorker() {\n\tfor c.processNext() {\n\t}\n}","line":{"from":137,"to":140}} {"id":100005200,"name":"processNext","signature":"func (c *Controller) processNext() bool","file":"pkg/controlplane/controller/legacytokentracking/controller.go","code":"func (c *Controller) processNext() bool {\n\tkey, quit := c.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.queue.Done(key)\n\n\tif err := c.syncConfigMap(); err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"while syncing ConfigMap %q, err: %w\", key, err))\n\t\tc.queue.AddRateLimited(key)\n\t\treturn true\n\t}\n\tc.queue.Forget(key)\n\treturn true\n}","line":{"from":142,"to":156}} {"id":100005201,"name":"syncConfigMap","signature":"func (c *Controller) syncConfigMap() error","file":"pkg/controlplane/controller/legacytokentracking/controller.go","code":"func (c *Controller) syncConfigMap() error {\n\tobj, exists, err := c.configMapCache.GetByKey(queueKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnow := c.clock.Now()\n\tswitch {\n\tcase c.enabled:\n\t\tif !exists {\n\t\t\tr := c.creationRatelimiter.ReserveN(now, 1)\n\t\t\tif delay := r.DelayFrom(now); delay \u003e 0 {\n\t\t\t\tc.queue.AddAfter(queueKey, delay)\n\t\t\t\tr.CancelAt(now)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif _, err = c.configMapClient.ConfigMaps(metav1.NamespaceSystem).Create(context.TODO(), \u0026corev1.ConfigMap{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{Namespace: metav1.NamespaceSystem, Name: ConfigMapName},\n\t\t\t\tData: map[string]string{ConfigMapDataKey: now.UTC().Format(dateFormat)},\n\t\t\t}, metav1.CreateOptions{}); err != nil {\n\t\t\t\tif apierrors.IsAlreadyExists(err) {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\t// don't consume the creationRatelimiter for an unsuccessful attempt\n\t\t\t\tr.CancelAt(now)\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tconfigMap := obj.(*corev1.ConfigMap)\n\t\t\tif _, err = time.Parse(dateFormat, configMap.Data[ConfigMapDataKey]); err != nil {\n\t\t\t\tconfigMap := configMap.DeepCopy()\n\t\t\t\tconfigMap.Data[ConfigMapDataKey] = now.UTC().Format(dateFormat)\n\t\t\t\tif _, err = c.configMapClient.ConfigMaps(metav1.NamespaceSystem).Update(context.TODO(), configMap, metav1.UpdateOptions{}); err != nil {\n\t\t\t\t\tif apierrors.IsNotFound(err) || apierrors.IsConflict(err) {\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tcase !c.enabled:\n\t\tif exists \u0026\u0026 obj.(*corev1.ConfigMap).DeletionTimestamp == nil {\n\t\t\tif err := c.configMapClient.ConfigMaps(metav1.NamespaceSystem).Delete(context.TODO(), ConfigMapName, metav1.DeleteOptions{}); err != nil {\n\t\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":158,"to":211}} {"id":100005202,"name":"NewController","signature":"func NewController(clientset kubernetes.Interface, namespaceInformer coreinformers.NamespaceInformer) *Controller","file":"pkg/controlplane/controller/systemnamespaces/system_namespaces_controller.go","code":"// NewController creates a new Controller to ensure system namespaces exist.\nfunc NewController(clientset kubernetes.Interface, namespaceInformer coreinformers.NamespaceInformer) *Controller {\n\tsystemNamespaces := []string{metav1.NamespaceSystem, metav1.NamespacePublic, v1.NamespaceNodeLease, metav1.NamespaceDefault}\n\tinterval := 1 * time.Minute\n\n\treturn \u0026Controller{\n\t\tclient: clientset,\n\t\tnamespaceLister: namespaceInformer.Lister(),\n\t\tnamespaceSynced: namespaceInformer.Informer().HasSynced,\n\t\tsystemNamespaces: systemNamespaces,\n\t\tinterval: interval,\n\t}\n}","line":{"from":48,"to":60}} {"id":100005203,"name":"Run","signature":"func (c *Controller) Run(stopCh \u003c-chan struct{})","file":"pkg/controlplane/controller/systemnamespaces/system_namespaces_controller.go","code":"// Run starts one worker.\nfunc (c *Controller) Run(stopCh \u003c-chan struct{}) {\n\tdefer utilruntime.HandleCrash()\n\tdefer klog.Infof(\"Shutting down system namespaces controller\")\n\n\tklog.Infof(\"Starting system namespaces controller\")\n\n\tif !cache.WaitForCacheSync(stopCh, c.namespaceSynced) {\n\t\tutilruntime.HandleError(fmt.Errorf(\"timed out waiting for caches to sync\"))\n\t\treturn\n\t}\n\n\tgo wait.Until(c.sync, c.interval, stopCh)\n\n\t\u003c-stopCh\n}","line":{"from":62,"to":77}} {"id":100005204,"name":"sync","signature":"func (c *Controller) sync()","file":"pkg/controlplane/controller/systemnamespaces/system_namespaces_controller.go","code":"func (c *Controller) sync() {\n\t// Loop the system namespace list, and create them if they do not exist\n\tfor _, ns := range c.systemNamespaces {\n\t\tif err := c.createNamespaceIfNeeded(ns); err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"unable to create required kubernetes system Namespace %s: %v\", ns, err))\n\t\t}\n\t}\n}","line":{"from":79,"to":86}} {"id":100005205,"name":"createNamespaceIfNeeded","signature":"func (c *Controller) createNamespaceIfNeeded(ns string) error","file":"pkg/controlplane/controller/systemnamespaces/system_namespaces_controller.go","code":"func (c *Controller) createNamespaceIfNeeded(ns string) error {\n\tif _, err := c.namespaceLister.Get(ns); err == nil {\n\t\t// the namespace already exists\n\t\treturn nil\n\t}\n\tnewNs := \u0026v1.Namespace{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: ns,\n\t\t\tNamespace: \"\",\n\t\t},\n\t}\n\t_, err := c.client.CoreV1().Namespaces().Create(context.TODO(), newNs, metav1.CreateOptions{})\n\tif err != nil \u0026\u0026 errors.IsAlreadyExists(err) {\n\t\terr = nil\n\t}\n\treturn err\n}","line":{"from":88,"to":104}} {"id":100005206,"name":"createMasterCountReconciler","signature":"func (c *Config) createMasterCountReconciler() reconcilers.EndpointReconciler","file":"pkg/controlplane/instance.go","code":"func (c *Config) createMasterCountReconciler() reconcilers.EndpointReconciler {\n\tendpointClient := corev1client.NewForConfigOrDie(c.GenericConfig.LoopbackClientConfig)\n\tendpointSliceClient := discoveryclient.NewForConfigOrDie(c.GenericConfig.LoopbackClientConfig)\n\tendpointsAdapter := reconcilers.NewEndpointsAdapter(endpointClient, endpointSliceClient)\n\n\treturn reconcilers.NewMasterCountEndpointReconciler(c.ExtraConfig.MasterCount, endpointsAdapter)\n}","line":{"from":251,"to":257}} {"id":100005207,"name":"createNoneReconciler","signature":"func (c *Config) createNoneReconciler() reconcilers.EndpointReconciler","file":"pkg/controlplane/instance.go","code":"func (c *Config) createNoneReconciler() reconcilers.EndpointReconciler {\n\treturn reconcilers.NewNoneEndpointReconciler()\n}","line":{"from":259,"to":261}} {"id":100005208,"name":"createLeaseReconciler","signature":"func (c *Config) createLeaseReconciler() reconcilers.EndpointReconciler","file":"pkg/controlplane/instance.go","code":"func (c *Config) createLeaseReconciler() reconcilers.EndpointReconciler {\n\tendpointClient := corev1client.NewForConfigOrDie(c.GenericConfig.LoopbackClientConfig)\n\tendpointSliceClient := discoveryclient.NewForConfigOrDie(c.GenericConfig.LoopbackClientConfig)\n\tendpointsAdapter := reconcilers.NewEndpointsAdapter(endpointClient, endpointSliceClient)\n\n\tttl := c.ExtraConfig.MasterEndpointReconcileTTL\n\tconfig, err := c.ExtraConfig.StorageFactory.NewConfig(api.Resource(\"apiServerIPInfo\"))\n\tif err != nil {\n\t\tklog.Fatalf(\"Error creating storage factory config: %v\", err)\n\t}\n\tmasterLeases, err := reconcilers.NewLeases(config, \"/masterleases/\", ttl)\n\tif err != nil {\n\t\tklog.Fatalf(\"Error creating leases: %v\", err)\n\t}\n\n\treturn reconcilers.NewLeaseEndpointReconciler(endpointsAdapter, masterLeases)\n}","line":{"from":263,"to":279}} {"id":100005209,"name":"createEndpointReconciler","signature":"func (c *Config) createEndpointReconciler() reconcilers.EndpointReconciler","file":"pkg/controlplane/instance.go","code":"func (c *Config) createEndpointReconciler() reconcilers.EndpointReconciler {\n\tklog.Infof(\"Using reconciler: %v\", c.ExtraConfig.EndpointReconcilerType)\n\tswitch c.ExtraConfig.EndpointReconcilerType {\n\t// there are numerous test dependencies that depend on a default controller\n\tcase reconcilers.MasterCountReconcilerType:\n\t\treturn c.createMasterCountReconciler()\n\tcase \"\", reconcilers.LeaseEndpointReconcilerType:\n\t\treturn c.createLeaseReconciler()\n\tcase reconcilers.NoneEndpointReconcilerType:\n\t\treturn c.createNoneReconciler()\n\tdefault:\n\t\tklog.Fatalf(\"Reconciler not implemented: %v\", c.ExtraConfig.EndpointReconcilerType)\n\t}\n\treturn nil\n}","line":{"from":281,"to":295}} {"id":100005210,"name":"Complete","signature":"func (c *Config) Complete() CompletedConfig","file":"pkg/controlplane/instance.go","code":"// Complete fills in any fields not set that are required to have valid data. It's mutating the receiver.\nfunc (c *Config) Complete() CompletedConfig {\n\tcfg := completedConfig{\n\t\tc.GenericConfig.Complete(c.ExtraConfig.VersionedInformers),\n\t\t\u0026c.ExtraConfig,\n\t}\n\n\tserviceIPRange, apiServerServiceIP, err := ServiceIPRange(cfg.ExtraConfig.ServiceIPRange)\n\tif err != nil {\n\t\tklog.Fatalf(\"Error determining service IP ranges: %v\", err)\n\t}\n\tif cfg.ExtraConfig.ServiceIPRange.IP == nil {\n\t\tcfg.ExtraConfig.ServiceIPRange = serviceIPRange\n\t}\n\tif cfg.ExtraConfig.APIServerServiceIP == nil {\n\t\tcfg.ExtraConfig.APIServerServiceIP = apiServerServiceIP\n\t}\n\n\tdiscoveryAddresses := discovery.DefaultAddresses{DefaultAddress: cfg.GenericConfig.ExternalAddress}\n\tdiscoveryAddresses.CIDRRules = append(discoveryAddresses.CIDRRules,\n\t\tdiscovery.CIDRRule{IPRange: cfg.ExtraConfig.ServiceIPRange, Address: net.JoinHostPort(cfg.ExtraConfig.APIServerServiceIP.String(), strconv.Itoa(cfg.ExtraConfig.APIServerServicePort))})\n\tcfg.GenericConfig.DiscoveryAddresses = discoveryAddresses\n\n\tif cfg.ExtraConfig.ServiceNodePortRange.Size == 0 {\n\t\t// TODO: Currently no way to specify an empty range (do we need to allow this?)\n\t\t// We should probably allow this for clouds that don't require NodePort to do load-balancing (GCE)\n\t\t// but then that breaks the strict nestedness of ServiceType.\n\t\t// Review post-v1\n\t\tcfg.ExtraConfig.ServiceNodePortRange = kubeoptions.DefaultServiceNodePortRange\n\t\tklog.Infof(\"Node port range unspecified. Defaulting to %v.\", cfg.ExtraConfig.ServiceNodePortRange)\n\t}\n\n\tif cfg.ExtraConfig.EndpointReconcilerConfig.Interval == 0 {\n\t\tcfg.ExtraConfig.EndpointReconcilerConfig.Interval = DefaultEndpointReconcilerInterval\n\t}\n\n\tif cfg.ExtraConfig.MasterEndpointReconcileTTL == 0 {\n\t\tcfg.ExtraConfig.MasterEndpointReconcileTTL = DefaultEndpointReconcilerTTL\n\t}\n\n\tif cfg.ExtraConfig.EndpointReconcilerConfig.Reconciler == nil {\n\t\tcfg.ExtraConfig.EndpointReconcilerConfig.Reconciler = c.createEndpointReconciler()\n\t}\n\n\tif cfg.ExtraConfig.RepairServicesInterval == 0 {\n\t\tcfg.ExtraConfig.RepairServicesInterval = repairLoopInterval\n\t}\n\n\treturn CompletedConfig{\u0026cfg}\n}","line":{"from":297,"to":346}} {"id":100005211,"name":"New","signature":"func (c completedConfig) New(delegationTarget genericapiserver.DelegationTarget) (*Instance, error)","file":"pkg/controlplane/instance.go","code":"// New returns a new instance of Master from the given config.\n// Certain config fields will be set to a default value if unset.\n// Certain config fields must be specified, including:\n// KubeletClientConfig\nfunc (c completedConfig) New(delegationTarget genericapiserver.DelegationTarget) (*Instance, error) {\n\tif reflect.DeepEqual(c.ExtraConfig.KubeletClientConfig, kubeletclient.KubeletClientConfig{}) {\n\t\treturn nil, fmt.Errorf(\"Master.New() called with empty config.KubeletClientConfig\")\n\t}\n\n\ts, err := c.GenericConfig.New(\"kube-apiserver\", delegationTarget)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif c.ExtraConfig.EnableLogsSupport {\n\t\troutes.Logs{}.Install(s.Handler.GoRestfulContainer)\n\t}\n\n\t// Metadata and keys are expected to only change across restarts at present,\n\t// so we just marshal immediately and serve the cached JSON bytes.\n\tmd, err := serviceaccount.NewOpenIDMetadata(\n\t\tc.ExtraConfig.ServiceAccountIssuerURL,\n\t\tc.ExtraConfig.ServiceAccountJWKSURI,\n\t\tc.GenericConfig.ExternalAddress,\n\t\tc.ExtraConfig.ServiceAccountPublicKeys,\n\t)\n\tif err != nil {\n\t\t// If there was an error, skip installing the endpoints and log the\n\t\t// error, but continue on. We don't return the error because the\n\t\t// metadata responses require additional, backwards incompatible\n\t\t// validation of command-line options.\n\t\tmsg := fmt.Sprintf(\"Could not construct pre-rendered responses for\"+\n\t\t\t\" ServiceAccountIssuerDiscovery endpoints. Endpoints will not be\"+\n\t\t\t\" enabled. Error: %v\", err)\n\t\tif c.ExtraConfig.ServiceAccountIssuerURL != \"\" {\n\t\t\t// The user likely expects this feature to be enabled if issuer URL is\n\t\t\t// set and the feature gate is enabled. In the future, if there is no\n\t\t\t// longer a feature gate and issuer URL is not set, the user may not\n\t\t\t// expect this feature to be enabled. We log the former case as an Error\n\t\t\t// and the latter case as an Info.\n\t\t\tklog.Error(msg)\n\t\t} else {\n\t\t\tklog.Info(msg)\n\t\t}\n\t} else {\n\t\troutes.NewOpenIDMetadataServer(md.ConfigJSON, md.PublicKeysetJSON).\n\t\t\tInstall(s.Handler.GoRestfulContainer)\n\t}\n\n\tm := \u0026Instance{\n\t\tGenericAPIServer: s,\n\t\tClusterAuthenticationInfo: c.ExtraConfig.ClusterAuthenticationInfo,\n\t}\n\n\t// install legacy rest storage\n\n\tif err := m.InstallLegacyAPI(\u0026c, c.GenericConfig.RESTOptionsGetter); err != nil {\n\t\treturn nil, err\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(c.GenericConfig.LoopbackClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// TODO: update to a version that caches success but will recheck on failure, unlike memcache discovery\n\tdiscoveryClientForAdmissionRegistration := clientset.Discovery()\n\n\t// The order here is preserved in discovery.\n\t// If resources with identical names exist in more than one of these groups (e.g. \"deployments.apps\"\" and \"deployments.extensions\"),\n\t// the order of this list determines which group an unqualified resource name (e.g. \"deployments\") should prefer.\n\t// This priority order is used for local discovery, but it ends up aggregated in `k8s.io/kubernetes/cmd/kube-apiserver/app/aggregator.go\n\t// with specific priorities.\n\t// TODO: describe the priority all the way down in the RESTStorageProviders and plumb it back through the various discovery\n\t// handlers that we have.\n\trestStorageProviders := []RESTStorageProvider{\n\t\tapiserverinternalrest.StorageProvider{},\n\t\tauthenticationrest.RESTStorageProvider{Authenticator: c.GenericConfig.Authentication.Authenticator, APIAudiences: c.GenericConfig.Authentication.APIAudiences},\n\t\tauthorizationrest.RESTStorageProvider{Authorizer: c.GenericConfig.Authorization.Authorizer, RuleResolver: c.GenericConfig.RuleResolver},\n\t\tautoscalingrest.RESTStorageProvider{},\n\t\tbatchrest.RESTStorageProvider{},\n\t\tcertificatesrest.RESTStorageProvider{},\n\t\tcoordinationrest.RESTStorageProvider{},\n\t\tdiscoveryrest.StorageProvider{},\n\t\tnetworkingrest.RESTStorageProvider{},\n\t\tnoderest.RESTStorageProvider{},\n\t\tpolicyrest.RESTStorageProvider{},\n\t\trbacrest.RESTStorageProvider{Authorizer: c.GenericConfig.Authorization.Authorizer},\n\t\tschedulingrest.RESTStorageProvider{},\n\t\tstoragerest.RESTStorageProvider{},\n\t\tflowcontrolrest.RESTStorageProvider{InformerFactory: c.GenericConfig.SharedInformerFactory},\n\t\t// keep apps after extensions so legacy clients resolve the extensions versions of shared resource names.\n\t\t// See https://github.com/kubernetes/kubernetes/issues/42392\n\t\tappsrest.StorageProvider{},\n\t\tadmissionregistrationrest.RESTStorageProvider{Authorizer: c.GenericConfig.Authorization.Authorizer, DiscoveryClient: discoveryClientForAdmissionRegistration},\n\t\teventsrest.RESTStorageProvider{TTL: c.ExtraConfig.EventTTL},\n\t\tresourcerest.RESTStorageProvider{},\n\t}\n\tif err := m.InstallAPIs(c.ExtraConfig.APIResourceConfigSource, c.GenericConfig.RESTOptionsGetter, restStorageProviders...); err != nil {\n\t\treturn nil, err\n\t}\n\n\tm.GenericAPIServer.AddPostStartHookOrDie(\"start-cluster-authentication-info-controller\", func(hookContext genericapiserver.PostStartHookContext) error {\n\t\tkubeClient, err := kubernetes.NewForConfig(hookContext.LoopbackClientConfig)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcontroller := clusterauthenticationtrust.NewClusterAuthenticationTrustController(m.ClusterAuthenticationInfo, kubeClient)\n\n\t\t// generate a context from stopCh. This is to avoid modifying files which are relying on apiserver\n\t\t// TODO: See if we can pass ctx to the current method\n\t\tctx := wait.ContextForChannel(hookContext.StopCh)\n\n\t\t// prime values and start listeners\n\t\tif m.ClusterAuthenticationInfo.ClientCA != nil {\n\t\t\tm.ClusterAuthenticationInfo.ClientCA.AddListener(controller)\n\t\t\tif controller, ok := m.ClusterAuthenticationInfo.ClientCA.(dynamiccertificates.ControllerRunner); ok {\n\t\t\t\t// runonce to be sure that we have a value.\n\t\t\t\tif err := controller.RunOnce(ctx); err != nil {\n\t\t\t\t\truntime.HandleError(err)\n\t\t\t\t}\n\t\t\t\tgo controller.Run(ctx, 1)\n\t\t\t}\n\t\t}\n\t\tif m.ClusterAuthenticationInfo.RequestHeaderCA != nil {\n\t\t\tm.ClusterAuthenticationInfo.RequestHeaderCA.AddListener(controller)\n\t\t\tif controller, ok := m.ClusterAuthenticationInfo.RequestHeaderCA.(dynamiccertificates.ControllerRunner); ok {\n\t\t\t\t// runonce to be sure that we have a value.\n\t\t\t\tif err := controller.RunOnce(ctx); err != nil {\n\t\t\t\t\truntime.HandleError(err)\n\t\t\t\t}\n\t\t\t\tgo controller.Run(ctx, 1)\n\t\t\t}\n\t\t}\n\n\t\tgo controller.Run(ctx, 1)\n\t\treturn nil\n\t})\n\n\tif utilfeature.DefaultFeatureGate.Enabled(apiserverfeatures.APIServerIdentity) {\n\t\tm.GenericAPIServer.AddPostStartHookOrDie(\"start-kube-apiserver-identity-lease-controller\", func(hookContext genericapiserver.PostStartHookContext) error {\n\t\t\tkubeClient, err := kubernetes.NewForConfig(hookContext.LoopbackClientConfig)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// generate a context from stopCh. This is to avoid modifying files which are relying on apiserver\n\t\t\t// TODO: See if we can pass ctx to the current method\n\t\t\tctx := wait.ContextForChannel(hookContext.StopCh)\n\n\t\t\tleaseName := m.GenericAPIServer.APIServerID\n\t\t\tholderIdentity := m.GenericAPIServer.APIServerID + \"_\" + string(uuid.NewUUID())\n\n\t\t\tcontroller := lease.NewController(\n\t\t\t\tclock.RealClock{},\n\t\t\t\tkubeClient,\n\t\t\t\tholderIdentity,\n\t\t\t\tint32(IdentityLeaseDurationSeconds),\n\t\t\t\tnil,\n\t\t\t\tIdentityLeaseRenewIntervalPeriod,\n\t\t\t\tleaseName,\n\t\t\t\tmetav1.NamespaceSystem,\n\t\t\t\t// TODO: receive identity label value as a parameter when post start hook is moved to generic apiserver.\n\t\t\t\tlabelAPIServerHeartbeatFunc(KubeAPIServer))\n\t\t\tgo controller.Run(ctx)\n\t\t\treturn nil\n\t\t})\n\t\t// Labels for apiserver idenitiy leases switched from k8s.io/component=kube-apiserver to apiserver.kubernetes.io/identity=kube-apiserver.\n\t\t// For compatibility, garbage collect leases with both labels for at least 1 release\n\t\t// TODO: remove in Kubernetes 1.28\n\t\tm.GenericAPIServer.AddPostStartHookOrDie(\"start-deprecated-kube-apiserver-identity-lease-garbage-collector\", func(hookContext genericapiserver.PostStartHookContext) error {\n\t\t\tkubeClient, err := kubernetes.NewForConfig(hookContext.LoopbackClientConfig)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tgo apiserverleasegc.NewAPIServerLeaseGC(\n\t\t\t\tkubeClient,\n\t\t\t\tIdentityLeaseGCPeriod,\n\t\t\t\tmetav1.NamespaceSystem,\n\t\t\t\tDeprecatedKubeAPIServerIdentityLeaseLabelSelector,\n\t\t\t).Run(hookContext.StopCh)\n\t\t\treturn nil\n\t\t})\n\t\t// TODO: move this into generic apiserver and make the lease identity value configurable\n\t\tm.GenericAPIServer.AddPostStartHookOrDie(\"start-kube-apiserver-identity-lease-garbage-collector\", func(hookContext genericapiserver.PostStartHookContext) error {\n\t\t\tkubeClient, err := kubernetes.NewForConfig(hookContext.LoopbackClientConfig)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tgo apiserverleasegc.NewAPIServerLeaseGC(\n\t\t\t\tkubeClient,\n\t\t\t\tIdentityLeaseGCPeriod,\n\t\t\t\tmetav1.NamespaceSystem,\n\t\t\t\tKubeAPIServerIdentityLeaseLabelSelector,\n\t\t\t).Run(hookContext.StopCh)\n\t\t\treturn nil\n\t\t})\n\t}\n\n\tm.GenericAPIServer.AddPostStartHookOrDie(\"start-legacy-token-tracking-controller\", func(hookContext genericapiserver.PostStartHookContext) error {\n\t\tkubeClient, err := kubernetes.NewForConfig(hookContext.LoopbackClientConfig)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgo legacytokentracking.NewController(kubeClient).Run(hookContext.StopCh)\n\t\treturn nil\n\t})\n\n\treturn m, nil\n}","line":{"from":348,"to":557}} {"id":100005212,"name":"labelAPIServerHeartbeatFunc","signature":"func labelAPIServerHeartbeatFunc(identity string) lease.ProcessLeaseFunc","file":"pkg/controlplane/instance.go","code":"func labelAPIServerHeartbeatFunc(identity string) lease.ProcessLeaseFunc {\n\treturn func(lease *coordinationapiv1.Lease) error {\n\t\tif lease.Labels == nil {\n\t\t\tlease.Labels = map[string]string{}\n\t\t}\n\n\t\t// This label indiciates the identity of the lease object.\n\t\tlease.Labels[IdentityLeaseComponentLabelKey] = identity\n\n\t\thostname, err := os.Hostname()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// convenience label to easily map a lease object to a specific apiserver\n\t\tlease.Labels[apiv1.LabelHostname] = hostname\n\t\treturn nil\n\t}\n}","line":{"from":559,"to":577}} {"id":100005213,"name":"InstallLegacyAPI","signature":"func (m *Instance) InstallLegacyAPI(c *completedConfig, restOptionsGetter generic.RESTOptionsGetter) error","file":"pkg/controlplane/instance.go","code":"// InstallLegacyAPI will install the legacy APIs for the restStorageProviders if they are enabled.\nfunc (m *Instance) InstallLegacyAPI(c *completedConfig, restOptionsGetter generic.RESTOptionsGetter) error {\n\tlegacyRESTStorageProvider := corerest.LegacyRESTStorageProvider{\n\t\tStorageFactory: c.ExtraConfig.StorageFactory,\n\t\tProxyTransport: c.ExtraConfig.ProxyTransport,\n\t\tKubeletClientConfig: c.ExtraConfig.KubeletClientConfig,\n\t\tEventTTL: c.ExtraConfig.EventTTL,\n\t\tServiceIPRange: c.ExtraConfig.ServiceIPRange,\n\t\tSecondaryServiceIPRange: c.ExtraConfig.SecondaryServiceIPRange,\n\t\tServiceNodePortRange: c.ExtraConfig.ServiceNodePortRange,\n\t\tLoopbackClientConfig: c.GenericConfig.LoopbackClientConfig,\n\t\tServiceAccountIssuer: c.ExtraConfig.ServiceAccountIssuer,\n\t\tExtendExpiration: c.ExtraConfig.ExtendExpiration,\n\t\tServiceAccountMaxExpiration: c.ExtraConfig.ServiceAccountMaxExpiration,\n\t\tAPIAudiences: c.GenericConfig.Authentication.APIAudiences,\n\t\tInformers: c.ExtraConfig.VersionedInformers,\n\t}\n\tlegacyRESTStorage, apiGroupInfo, err := legacyRESTStorageProvider.NewLegacyRESTStorage(c.ExtraConfig.APIResourceConfigSource, restOptionsGetter)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error building core storage: %v\", err)\n\t}\n\tif len(apiGroupInfo.VersionedResourcesStorageMap) == 0 { // if all core storage is disabled, return.\n\t\treturn nil\n\t}\n\n\tcontrollerName := \"bootstrap-controller\"\n\tclient := kubernetes.NewForConfigOrDie(c.GenericConfig.LoopbackClientConfig)\n\t// Kubernetes clusters contains the following system namespaces:\n\t// kube-system, kube-node-lease, kube-public, default\n\tm.GenericAPIServer.AddPostStartHookOrDie(\"start-system-namespaces-controller\", func(hookContext genericapiserver.PostStartHookContext) error {\n\t\tgo systemnamespaces.NewController(client, c.ExtraConfig.VersionedInformers.Core().V1().Namespaces()).Run(hookContext.StopCh)\n\t\treturn nil\n\t})\n\n\tbootstrapController, err := c.NewBootstrapController(legacyRESTStorage, client)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating bootstrap controller: %v\", err)\n\t}\n\tm.GenericAPIServer.AddPostStartHookOrDie(controllerName, bootstrapController.PostStartHook)\n\tm.GenericAPIServer.AddPreShutdownHookOrDie(controllerName, bootstrapController.PreShutdownHook)\n\n\tif err := m.GenericAPIServer.InstallLegacyAPIGroup(genericapiserver.DefaultLegacyAPIPrefix, \u0026apiGroupInfo); err != nil {\n\t\treturn fmt.Errorf(\"error in registering group versions: %v\", err)\n\t}\n\treturn nil\n}","line":{"from":579,"to":624}} {"id":100005214,"name":"InstallAPIs","signature":"func (m *Instance) InstallAPIs(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter, restStorageProviders ...RESTStorageProvider) error","file":"pkg/controlplane/instance.go","code":"// InstallAPIs will install the APIs for the restStorageProviders if they are enabled.\nfunc (m *Instance) InstallAPIs(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter, restStorageProviders ...RESTStorageProvider) error {\n\tapiGroupsInfo := []*genericapiserver.APIGroupInfo{}\n\n\t// used later in the loop to filter the served resource by those that have expired.\n\tresourceExpirationEvaluator, err := genericapiserver.NewResourceExpirationEvaluator(*m.GenericAPIServer.Version)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, restStorageBuilder := range restStorageProviders {\n\t\tgroupName := restStorageBuilder.GroupName()\n\t\tapiGroupInfo, err := restStorageBuilder.NewRESTStorage(apiResourceConfigSource, restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"problem initializing API group %q : %v\", groupName, err)\n\t\t}\n\t\tif len(apiGroupInfo.VersionedResourcesStorageMap) == 0 {\n\t\t\t// If we have no storage for any resource configured, this API group is effectively disabled.\n\t\t\t// This can happen when an entire API group, version, or development-stage (alpha, beta, GA) is disabled.\n\t\t\tklog.Infof(\"API group %q is not enabled, skipping.\", groupName)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Remove resources that serving kinds that are removed.\n\t\t// We do this here so that we don't accidentally serve versions without resources or openapi information that for kinds we don't serve.\n\t\t// This is a spot above the construction of individual storage handlers so that no sig accidentally forgets to check.\n\t\tresourceExpirationEvaluator.RemoveDeletedKinds(groupName, apiGroupInfo.Scheme, apiGroupInfo.VersionedResourcesStorageMap)\n\t\tif len(apiGroupInfo.VersionedResourcesStorageMap) == 0 {\n\t\t\tklog.V(1).Infof(\"Removing API group %v because it is time to stop serving it because it has no versions per APILifecycle.\", groupName)\n\t\t\tcontinue\n\t\t}\n\n\t\tklog.V(1).Infof(\"Enabling API group %q.\", groupName)\n\n\t\tif postHookProvider, ok := restStorageBuilder.(genericapiserver.PostStartHookProvider); ok {\n\t\t\tname, hook, err := postHookProvider.PostStartHook()\n\t\t\tif err != nil {\n\t\t\t\tklog.Fatalf(\"Error building PostStartHook: %v\", err)\n\t\t\t}\n\t\t\tm.GenericAPIServer.AddPostStartHookOrDie(name, hook)\n\t\t}\n\n\t\tapiGroupsInfo = append(apiGroupsInfo, \u0026apiGroupInfo)\n\t}\n\n\tif err := m.GenericAPIServer.InstallAPIGroups(apiGroupsInfo...); err != nil {\n\t\treturn fmt.Errorf(\"error in registering group versions: %v\", err)\n\t}\n\treturn nil\n}","line":{"from":632,"to":681}} {"id":100005215,"name":"DefaultAPIResourceConfigSource","signature":"func DefaultAPIResourceConfigSource() *serverstorage.ResourceConfig","file":"pkg/controlplane/instance.go","code":"// DefaultAPIResourceConfigSource returns default configuration for an APIResource.\nfunc DefaultAPIResourceConfigSource() *serverstorage.ResourceConfig {\n\tret := serverstorage.NewResourceConfig()\n\t// NOTE: GroupVersions listed here will be enabled by default. Don't put alpha or beta versions in the list.\n\tret.EnableVersions(stableAPIGroupVersionsEnabledByDefault...)\n\n\t// disable alpha and beta versions explicitly so we have a full list of what's possible to serve\n\tret.DisableVersions(betaAPIGroupVersionsDisabledByDefault...)\n\tret.DisableVersions(alphaAPIGroupVersionsDisabledByDefault...)\n\n\t// enable the legacy beta resources that were present before stopped serving new beta APIs by default.\n\tret.EnableResources(legacyBetaEnabledByDefaultResources...)\n\n\treturn ret\n}","line":{"from":745,"to":759}} {"id":100005216,"name":"NewEndpointsAdapter","signature":"func NewEndpointsAdapter(endpointClient corev1client.EndpointsGetter, endpointSliceClient discoveryclient.EndpointSlicesGetter) EndpointsAdapter","file":"pkg/controlplane/reconcilers/endpointsadapter.go","code":"// NewEndpointsAdapter returns a new EndpointsAdapter.\nfunc NewEndpointsAdapter(endpointClient corev1client.EndpointsGetter, endpointSliceClient discoveryclient.EndpointSlicesGetter) EndpointsAdapter {\n\treturn EndpointsAdapter{\n\t\tendpointClient: endpointClient,\n\t\tendpointSliceClient: endpointSliceClient,\n\t}\n}","line":{"from":45,"to":51}} {"id":100005217,"name":"Get","signature":"func (adapter *EndpointsAdapter) Get(namespace, name string, getOpts metav1.GetOptions) (*corev1.Endpoints, error)","file":"pkg/controlplane/reconcilers/endpointsadapter.go","code":"// Get takes the name and namespace of the Endpoints resource, and returns a\n// corresponding Endpoints object if it exists, and an error if there is any.\nfunc (adapter *EndpointsAdapter) Get(namespace, name string, getOpts metav1.GetOptions) (*corev1.Endpoints, error) {\n\treturn adapter.endpointClient.Endpoints(namespace).Get(context.TODO(), name, getOpts)\n}","line":{"from":53,"to":57}} {"id":100005218,"name":"Create","signature":"func (adapter *EndpointsAdapter) Create(namespace string, endpoints *corev1.Endpoints) (*corev1.Endpoints, error)","file":"pkg/controlplane/reconcilers/endpointsadapter.go","code":"// Create accepts a namespace and Endpoints object and creates the Endpoints\n// object and matching EndpointSlice. The created Endpoints object or an error will be\n// returned.\nfunc (adapter *EndpointsAdapter) Create(namespace string, endpoints *corev1.Endpoints) (*corev1.Endpoints, error) {\n\tendpoints, err := adapter.endpointClient.Endpoints(namespace).Create(context.TODO(), endpoints, metav1.CreateOptions{})\n\tif err == nil {\n\t\terr = adapter.EnsureEndpointSliceFromEndpoints(namespace, endpoints)\n\t}\n\treturn endpoints, err\n}","line":{"from":59,"to":68}} {"id":100005219,"name":"Update","signature":"func (adapter *EndpointsAdapter) Update(namespace string, endpoints *corev1.Endpoints) (*corev1.Endpoints, error)","file":"pkg/controlplane/reconcilers/endpointsadapter.go","code":"// Update accepts a namespace and Endpoints object and updates it and its\n// matching EndpointSlice. The updated Endpoints object or an error will be returned.\nfunc (adapter *EndpointsAdapter) Update(namespace string, endpoints *corev1.Endpoints) (*corev1.Endpoints, error) {\n\tendpoints, err := adapter.endpointClient.Endpoints(namespace).Update(context.TODO(), endpoints, metav1.UpdateOptions{})\n\tif err == nil {\n\t\terr = adapter.EnsureEndpointSliceFromEndpoints(namespace, endpoints)\n\t}\n\treturn endpoints, err\n}","line":{"from":70,"to":78}} {"id":100005220,"name":"EnsureEndpointSliceFromEndpoints","signature":"func (adapter *EndpointsAdapter) EnsureEndpointSliceFromEndpoints(namespace string, endpoints *corev1.Endpoints) error","file":"pkg/controlplane/reconcilers/endpointsadapter.go","code":"// EnsureEndpointSliceFromEndpoints accepts a namespace and Endpoints resource\n// and creates or updates a corresponding EndpointSlice. An error will be returned\n// if it fails to sync the EndpointSlice.\nfunc (adapter *EndpointsAdapter) EnsureEndpointSliceFromEndpoints(namespace string, endpoints *corev1.Endpoints) error {\n\tendpointSlice := endpointSliceFromEndpoints(endpoints)\n\tcurrentEndpointSlice, err := adapter.endpointSliceClient.EndpointSlices(namespace).Get(context.TODO(), endpointSlice.Name, metav1.GetOptions{})\n\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\tif _, err = adapter.endpointSliceClient.EndpointSlices(namespace).Create(context.TODO(), endpointSlice, metav1.CreateOptions{}); errors.IsAlreadyExists(err) {\n\t\t\t\terr = nil\n\t\t\t}\n\t\t}\n\t\treturn err\n\t}\n\n\t// required for transition from IP to IPv4 address type.\n\tif currentEndpointSlice.AddressType != endpointSlice.AddressType {\n\t\terr = adapter.endpointSliceClient.EndpointSlices(namespace).Delete(context.TODO(), endpointSlice.Name, metav1.DeleteOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = adapter.endpointSliceClient.EndpointSlices(namespace).Create(context.TODO(), endpointSlice, metav1.CreateOptions{})\n\t\treturn err\n\t}\n\n\tif apiequality.Semantic.DeepEqual(currentEndpointSlice.Endpoints, endpointSlice.Endpoints) \u0026\u0026\n\t\tapiequality.Semantic.DeepEqual(currentEndpointSlice.Ports, endpointSlice.Ports) \u0026\u0026\n\t\tapiequality.Semantic.DeepEqual(currentEndpointSlice.Labels, endpointSlice.Labels) {\n\t\treturn nil\n\t}\n\n\t_, err = adapter.endpointSliceClient.EndpointSlices(namespace).Update(context.TODO(), endpointSlice, metav1.UpdateOptions{})\n\treturn err\n}","line":{"from":80,"to":114}} {"id":100005221,"name":"endpointSliceFromEndpoints","signature":"func endpointSliceFromEndpoints(endpoints *corev1.Endpoints) *discovery.EndpointSlice","file":"pkg/controlplane/reconcilers/endpointsadapter.go","code":"// endpointSliceFromEndpoints generates an EndpointSlice from an Endpoints\n// resource.\nfunc endpointSliceFromEndpoints(endpoints *corev1.Endpoints) *discovery.EndpointSlice {\n\tendpointSlice := \u0026discovery.EndpointSlice{}\n\tendpointSlice.Name = endpoints.Name\n\tendpointSlice.Namespace = endpoints.Namespace\n\tendpointSlice.Labels = map[string]string{discovery.LabelServiceName: endpoints.Name}\n\n\t// TODO: Add support for dual stack here (and in the rest of\n\t// EndpointsAdapter).\n\tendpointSlice.AddressType = discovery.AddressTypeIPv4\n\n\tif len(endpoints.Subsets) \u003e 0 {\n\t\tsubset := endpoints.Subsets[0]\n\t\tfor i := range subset.Ports {\n\t\t\tendpointSlice.Ports = append(endpointSlice.Ports, discovery.EndpointPort{\n\t\t\t\tPort: \u0026subset.Ports[i].Port,\n\t\t\t\tName: \u0026subset.Ports[i].Name,\n\t\t\t\tProtocol: \u0026subset.Ports[i].Protocol,\n\t\t\t})\n\t\t}\n\n\t\tif allAddressesIPv6(append(subset.Addresses, subset.NotReadyAddresses...)) {\n\t\t\tendpointSlice.AddressType = discovery.AddressTypeIPv6\n\t\t}\n\n\t\tendpointSlice.Endpoints = append(endpointSlice.Endpoints, getEndpointsFromAddresses(subset.Addresses, endpointSlice.AddressType, true)...)\n\t\tendpointSlice.Endpoints = append(endpointSlice.Endpoints, getEndpointsFromAddresses(subset.NotReadyAddresses, endpointSlice.AddressType, false)...)\n\t}\n\n\treturn endpointSlice\n}","line":{"from":116,"to":147}} {"id":100005222,"name":"getEndpointsFromAddresses","signature":"func getEndpointsFromAddresses(addresses []corev1.EndpointAddress, addressType discovery.AddressType, ready bool) []discovery.Endpoint","file":"pkg/controlplane/reconcilers/endpointsadapter.go","code":"// getEndpointsFromAddresses returns a list of Endpoints from addresses that\n// match the provided address type.\nfunc getEndpointsFromAddresses(addresses []corev1.EndpointAddress, addressType discovery.AddressType, ready bool) []discovery.Endpoint {\n\tendpoints := []discovery.Endpoint{}\n\tisIPv6AddressType := addressType == discovery.AddressTypeIPv6\n\n\tfor _, address := range addresses {\n\t\tif utilnet.IsIPv6String(address.IP) == isIPv6AddressType {\n\t\t\tendpoints = append(endpoints, endpointFromAddress(address, ready))\n\t\t}\n\t}\n\n\treturn endpoints\n}","line":{"from":149,"to":162}} {"id":100005223,"name":"endpointFromAddress","signature":"func endpointFromAddress(address corev1.EndpointAddress, ready bool) discovery.Endpoint","file":"pkg/controlplane/reconcilers/endpointsadapter.go","code":"// endpointFromAddress generates an Endpoint from an EndpointAddress resource.\nfunc endpointFromAddress(address corev1.EndpointAddress, ready bool) discovery.Endpoint {\n\tep := discovery.Endpoint{\n\t\tAddresses: []string{address.IP},\n\t\tConditions: discovery.EndpointConditions{Ready: \u0026ready},\n\t\tTargetRef: address.TargetRef,\n\t}\n\n\tif address.NodeName != nil {\n\t\tep.NodeName = address.NodeName\n\t}\n\n\treturn ep\n}","line":{"from":164,"to":177}} {"id":100005224,"name":"allAddressesIPv6","signature":"func allAddressesIPv6(addresses []corev1.EndpointAddress) bool","file":"pkg/controlplane/reconcilers/endpointsadapter.go","code":"// allAddressesIPv6 returns true if all provided addresses are IPv6.\nfunc allAddressesIPv6(addresses []corev1.EndpointAddress) bool {\n\tif len(addresses) == 0 {\n\t\treturn false\n\t}\n\n\tfor _, address := range addresses {\n\t\tif !utilnet.IsIPv6String(address.IP) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}","line":{"from":179,"to":192}} {"id":100005225,"name":"setSkipMirrorTrue","signature":"func setSkipMirrorTrue(e *corev1.Endpoints) bool","file":"pkg/controlplane/reconcilers/endpointsadapter.go","code":"// setSkipMirrorTrue sets endpointslice.kubernetes.io/skip-mirror to true. It\n// returns true if this has resulted in a change to the Endpoints resource.\nfunc setSkipMirrorTrue(e *corev1.Endpoints) bool {\n\tskipMirrorVal, ok := e.Labels[discovery.LabelSkipMirror]\n\tif !ok || skipMirrorVal != \"true\" {\n\t\tif e.Labels == nil {\n\t\t\te.Labels = map[string]string{}\n\t\t}\n\t\te.Labels[discovery.LabelSkipMirror] = \"true\"\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":194,"to":206}} {"id":100005226,"name":"NewMasterCountEndpointReconciler","signature":"func NewMasterCountEndpointReconciler(masterCount int, epAdapter EndpointsAdapter) EndpointReconciler","file":"pkg/controlplane/reconcilers/instancecount.go","code":"// NewMasterCountEndpointReconciler creates a new EndpointReconciler that reconciles based on a\n// specified expected number of masters.\nfunc NewMasterCountEndpointReconciler(masterCount int, epAdapter EndpointsAdapter) EndpointReconciler {\n\treturn \u0026masterCountEndpointReconciler{\n\t\tmasterCount: masterCount,\n\t\tepAdapter: epAdapter,\n\t}\n}","line":{"from":41,"to":48}} {"id":100005227,"name":"ReconcileEndpoints","signature":"func (r *masterCountEndpointReconciler) ReconcileEndpoints(serviceName string, ip net.IP, endpointPorts []corev1.EndpointPort, reconcilePorts bool) error","file":"pkg/controlplane/reconcilers/instancecount.go","code":"// ReconcileEndpoints sets the endpoints for the given apiserver service (ro or rw).\n// ReconcileEndpoints expects that the endpoints objects it manages will all be\n// managed only by ReconcileEndpoints; therefore, to understand this, you need only\n// understand the requirements and the body of this function.\n//\n// Requirements:\n// - All apiservers MUST use the same ports for their {rw, ro} services.\n// - All apiservers MUST use ReconcileEndpoints and only ReconcileEndpoints to manage the\n// endpoints for their {rw, ro} services.\n// - All apiservers MUST know and agree on the number of apiservers expected\n// to be running (c.masterCount).\n// - ReconcileEndpoints is called periodically from all apiservers.\nfunc (r *masterCountEndpointReconciler) ReconcileEndpoints(serviceName string, ip net.IP, endpointPorts []corev1.EndpointPort, reconcilePorts bool) error {\n\tr.reconcilingLock.Lock()\n\tdefer r.reconcilingLock.Unlock()\n\n\tif r.stopReconcilingCalled {\n\t\treturn nil\n\t}\n\n\te, err := r.epAdapter.Get(metav1.NamespaceDefault, serviceName, metav1.GetOptions{})\n\tif err != nil {\n\t\te = \u0026corev1.Endpoints{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: serviceName,\n\t\t\t\tNamespace: metav1.NamespaceDefault,\n\t\t\t},\n\t\t}\n\t}\n\n\t// Don't use the EndpointSliceMirroring controller to mirror this to\n\t// EndpointSlices. This may change in the future.\n\tskipMirrorChanged := setSkipMirrorTrue(e)\n\n\tif errors.IsNotFound(err) {\n\t\t// Simply create non-existing endpoints for the service.\n\t\te.Subsets = []corev1.EndpointSubset{{\n\t\t\tAddresses: []corev1.EndpointAddress{{IP: ip.String()}},\n\t\t\tPorts: endpointPorts,\n\t\t}}\n\t\t_, err = r.epAdapter.Create(metav1.NamespaceDefault, e)\n\t\treturn err\n\t}\n\n\t// First, determine if the endpoint is in the format we expect (one\n\t// subset, ports matching endpointPorts, N IP addresses).\n\tformatCorrect, ipCorrect, portsCorrect := checkEndpointSubsetFormat(e, ip.String(), endpointPorts, r.masterCount, reconcilePorts)\n\tif !formatCorrect {\n\t\t// Something is egregiously wrong, just re-make the endpoints record.\n\t\te.Subsets = []corev1.EndpointSubset{{\n\t\t\tAddresses: []corev1.EndpointAddress{{IP: ip.String()}},\n\t\t\tPorts: endpointPorts,\n\t\t}}\n\t\tklog.Warningf(\"Resetting endpoints for master service %q to %#v\", serviceName, e)\n\t\t_, err = r.epAdapter.Update(metav1.NamespaceDefault, e)\n\t\treturn err\n\t}\n\n\tif !skipMirrorChanged \u0026\u0026 ipCorrect \u0026\u0026 portsCorrect {\n\t\treturn r.epAdapter.EnsureEndpointSliceFromEndpoints(metav1.NamespaceDefault, e)\n\t}\n\tif !ipCorrect {\n\t\t// We *always* add our own IP address.\n\t\te.Subsets[0].Addresses = append(e.Subsets[0].Addresses, corev1.EndpointAddress{IP: ip.String()})\n\n\t\t// Lexicographic order is retained by this step.\n\t\te.Subsets = endpointsv1.RepackSubsets(e.Subsets)\n\n\t\t// If too many IP addresses, remove the ones lexicographically after our\n\t\t// own IP address. Given the requirements stated at the top of\n\t\t// this function, this should cause the list of IP addresses to\n\t\t// become eventually correct.\n\t\tif addrs := \u0026e.Subsets[0].Addresses; len(*addrs) \u003e r.masterCount {\n\t\t\t// addrs is a pointer because we're going to mutate it.\n\t\t\tfor i, addr := range *addrs {\n\t\t\t\tif addr.IP == ip.String() {\n\t\t\t\t\tfor len(*addrs) \u003e r.masterCount {\n\t\t\t\t\t\t// wrap around if necessary.\n\t\t\t\t\t\tremove := (i + 1) % len(*addrs)\n\t\t\t\t\t\t*addrs = append((*addrs)[:remove], (*addrs)[remove+1:]...)\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif !portsCorrect {\n\t\t// Reset ports.\n\t\te.Subsets[0].Ports = endpointPorts\n\t}\n\tklog.Warningf(\"Resetting endpoints for master service %q to %v\", serviceName, e)\n\t_, err = r.epAdapter.Update(metav1.NamespaceDefault, e)\n\treturn err\n}","line":{"from":50,"to":143}} {"id":100005228,"name":"RemoveEndpoints","signature":"func (r *masterCountEndpointReconciler) RemoveEndpoints(serviceName string, ip net.IP, endpointPorts []corev1.EndpointPort) error","file":"pkg/controlplane/reconcilers/instancecount.go","code":"func (r *masterCountEndpointReconciler) RemoveEndpoints(serviceName string, ip net.IP, endpointPorts []corev1.EndpointPort) error {\n\tr.reconcilingLock.Lock()\n\tdefer r.reconcilingLock.Unlock()\n\n\te, err := r.epAdapter.Get(metav1.NamespaceDefault, serviceName, metav1.GetOptions{})\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t// Endpoint doesn't exist\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\tif len(e.Subsets) == 0 {\n\t\t// no action is needed to remove the endpoint\n\t\treturn nil\n\t}\n\t// Remove our IP from the list of addresses\n\tnew := []corev1.EndpointAddress{}\n\tfor _, addr := range e.Subsets[0].Addresses {\n\t\tif addr.IP != ip.String() {\n\t\t\tnew = append(new, addr)\n\t\t}\n\t}\n\te.Subsets[0].Addresses = new\n\te.Subsets = endpointsv1.RepackSubsets(e.Subsets)\n\terr = retry.RetryOnConflict(retry.DefaultBackoff, func() error {\n\t\t_, err := r.epAdapter.Update(metav1.NamespaceDefault, e)\n\t\treturn err\n\t})\n\treturn err\n}","line":{"from":145,"to":176}} {"id":100005229,"name":"StopReconciling","signature":"func (r *masterCountEndpointReconciler) StopReconciling()","file":"pkg/controlplane/reconcilers/instancecount.go","code":"func (r *masterCountEndpointReconciler) StopReconciling() {\n\tr.reconcilingLock.Lock()\n\tdefer r.reconcilingLock.Unlock()\n\tr.stopReconcilingCalled = true\n}","line":{"from":178,"to":182}} {"id":100005230,"name":"Destroy","signature":"func (r *masterCountEndpointReconciler) Destroy()","file":"pkg/controlplane/reconcilers/instancecount.go","code":"func (r *masterCountEndpointReconciler) Destroy() {\n}","line":{"from":184,"to":185}} {"id":100005231,"name":"checkEndpointSubsetFormat","signature":"func checkEndpointSubsetFormat(e *corev1.Endpoints, ip string, ports []corev1.EndpointPort, count int, reconcilePorts bool) (formatCorrect bool, ipCorrect bool, portsCorrect bool)","file":"pkg/controlplane/reconcilers/instancecount.go","code":"// Determine if the endpoint is in the format ReconcileEndpoints expects.\n//\n// Return values:\n// - formatCorrect is true if exactly one subset is found.\n// - ipCorrect is true when current master's IP is found and the number\n// of addresses is less than or equal to the master count.\n// - portsCorrect is true when endpoint ports exactly match provided ports.\n// portsCorrect is only evaluated when reconcilePorts is set to true.\nfunc checkEndpointSubsetFormat(e *corev1.Endpoints, ip string, ports []corev1.EndpointPort, count int, reconcilePorts bool) (formatCorrect bool, ipCorrect bool, portsCorrect bool) {\n\tif len(e.Subsets) != 1 {\n\t\treturn false, false, false\n\t}\n\tsub := \u0026e.Subsets[0]\n\tportsCorrect = true\n\tif reconcilePorts {\n\t\tif len(sub.Ports) != len(ports) {\n\t\t\tportsCorrect = false\n\t\t}\n\t\tfor i, port := range ports {\n\t\t\tif len(sub.Ports) \u003c= i || port != sub.Ports[i] {\n\t\t\t\tportsCorrect = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tfor _, addr := range sub.Addresses {\n\t\tif addr.IP == ip {\n\t\t\tipCorrect = len(sub.Addresses) \u003c= count\n\t\t\tbreak\n\t\t}\n\t}\n\treturn true, ipCorrect, portsCorrect\n}","line":{"from":187,"to":219}} {"id":100005232,"name":"ListLeases","signature":"func (s *storageLeases) ListLeases() ([]string, error)","file":"pkg/controlplane/reconcilers/lease.go","code":"// ListLeases retrieves a list of the current master IPs from storage\nfunc (s *storageLeases) ListLeases() ([]string, error) {\n\tipInfoList := \u0026corev1.EndpointsList{}\n\tstorageOpts := storage.ListOptions{\n\t\tResourceVersion: \"0\",\n\t\tResourceVersionMatch: metav1.ResourceVersionMatchNotOlderThan,\n\t\tPredicate: storage.Everything,\n\t\tRecursive: true,\n\t}\n\tif err := s.storage.GetList(apirequest.NewDefaultContext(), s.baseKey, storageOpts, ipInfoList); err != nil {\n\t\treturn nil, err\n\t}\n\n\tipList := make([]string, 0, len(ipInfoList.Items))\n\tfor _, ip := range ipInfoList.Items {\n\t\tif len(ip.Subsets) \u003e 0 \u0026\u0026 len(ip.Subsets[0].Addresses) \u003e 0 \u0026\u0026 len(ip.Subsets[0].Addresses[0].IP) \u003e 0 {\n\t\t\tipList = append(ipList, ip.Subsets[0].Addresses[0].IP)\n\t\t}\n\t}\n\n\tklog.V(6).Infof(\"Current master IPs listed in storage are %v\", ipList)\n\n\treturn ipList, nil\n}","line":{"from":69,"to":92}} {"id":100005233,"name":"UpdateLease","signature":"func (s *storageLeases) UpdateLease(ip string) error","file":"pkg/controlplane/reconcilers/lease.go","code":"// UpdateLease resets the TTL on a master IP in storage\nfunc (s *storageLeases) UpdateLease(ip string) error {\n\tkey := path.Join(s.baseKey, ip)\n\treturn s.storage.GuaranteedUpdate(apirequest.NewDefaultContext(), key, \u0026corev1.Endpoints{}, true, nil, func(input kruntime.Object, respMeta storage.ResponseMeta) (kruntime.Object, *uint64, error) {\n\t\t// just make sure we've got the right IP set, and then refresh the TTL\n\t\texisting := input.(*corev1.Endpoints)\n\t\texisting.Subsets = []corev1.EndpointSubset{\n\t\t\t{\n\t\t\t\tAddresses: []corev1.EndpointAddress{{IP: ip}},\n\t\t\t},\n\t\t}\n\n\t\t// leaseTime needs to be in seconds\n\t\tleaseTime := uint64(s.leaseTime / time.Second)\n\n\t\t// NB: GuaranteedUpdate does not perform the store operation unless\n\t\t// something changed between load and store (not including resource\n\t\t// version), meaning we can't refresh the TTL without actually\n\t\t// changing a field.\n\t\texisting.Generation++\n\n\t\tklog.V(6).Infof(\"Resetting TTL on master IP %q listed in storage to %v\", ip, leaseTime)\n\n\t\treturn existing, \u0026leaseTime, nil\n\t}, nil)\n}","line":{"from":94,"to":119}} {"id":100005234,"name":"RemoveLease","signature":"func (s *storageLeases) RemoveLease(ip string) error","file":"pkg/controlplane/reconcilers/lease.go","code":"// RemoveLease removes the lease on a master IP in storage\nfunc (s *storageLeases) RemoveLease(ip string) error {\n\tkey := path.Join(s.baseKey, ip)\n\treturn s.storage.Delete(apirequest.NewDefaultContext(), key, \u0026corev1.Endpoints{}, nil, rest.ValidateAllObjectFunc, nil)\n}","line":{"from":121,"to":125}} {"id":100005235,"name":"Destroy","signature":"func (s *storageLeases) Destroy()","file":"pkg/controlplane/reconcilers/lease.go","code":"func (s *storageLeases) Destroy() {\n\ts.destroyFn()\n}","line":{"from":127,"to":129}} {"id":100005236,"name":"NewLeases","signature":"func NewLeases(config *storagebackend.ConfigForResource, baseKey string, leaseTime time.Duration) (Leases, error)","file":"pkg/controlplane/reconcilers/lease.go","code":"// NewLeases creates a new etcd-based Leases implementation.\nfunc NewLeases(config *storagebackend.ConfigForResource, baseKey string, leaseTime time.Duration) (Leases, error) {\n\tleaseStorage, destroyFn, err := storagefactory.Create(*config, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating storage factory: %v\", err)\n\t}\n\tvar once sync.Once\n\treturn \u0026storageLeases{\n\t\tstorage: leaseStorage,\n\t\tdestroyFn: func() { once.Do(destroyFn) },\n\t\tbaseKey: baseKey,\n\t\tleaseTime: leaseTime,\n\t}, nil\n}","line":{"from":131,"to":144}} {"id":100005237,"name":"NewLeaseEndpointReconciler","signature":"func NewLeaseEndpointReconciler(epAdapter EndpointsAdapter, masterLeases Leases) EndpointReconciler","file":"pkg/controlplane/reconcilers/lease.go","code":"// NewLeaseEndpointReconciler creates a new LeaseEndpoint reconciler\nfunc NewLeaseEndpointReconciler(epAdapter EndpointsAdapter, masterLeases Leases) EndpointReconciler {\n\treturn \u0026leaseEndpointReconciler{\n\t\tepAdapter: epAdapter,\n\t\tmasterLeases: masterLeases,\n\t\tstopReconcilingCalled: false,\n\t}\n}","line":{"from":153,"to":160}} {"id":100005238,"name":"ReconcileEndpoints","signature":"func (r *leaseEndpointReconciler) ReconcileEndpoints(serviceName string, ip net.IP, endpointPorts []corev1.EndpointPort, reconcilePorts bool) error","file":"pkg/controlplane/reconcilers/lease.go","code":"// ReconcileEndpoints lists keys in a special etcd directory.\n// Each key is expected to have a TTL of R+n, where R is the refresh interval\n// at which this function is called, and n is some small value. If an\n// apiserver goes down, it will fail to refresh its key's TTL and the key will\n// expire. ReconcileEndpoints will notice that the endpoints object is\n// different from the directory listing, and update the endpoints object\n// accordingly.\nfunc (r *leaseEndpointReconciler) ReconcileEndpoints(serviceName string, ip net.IP, endpointPorts []corev1.EndpointPort, reconcilePorts bool) error {\n\tr.reconcilingLock.Lock()\n\tdefer r.reconcilingLock.Unlock()\n\n\tif r.stopReconcilingCalled {\n\t\treturn nil\n\t}\n\n\t// Refresh the TTL on our key, independently of whether any error or\n\t// update conflict happens below. This makes sure that at least some of\n\t// the masters will add our endpoint.\n\tif err := r.masterLeases.UpdateLease(ip.String()); err != nil {\n\t\treturn err\n\t}\n\n\treturn r.doReconcile(serviceName, endpointPorts, reconcilePorts)\n}","line":{"from":162,"to":185}} {"id":100005239,"name":"doReconcile","signature":"func (r *leaseEndpointReconciler) doReconcile(serviceName string, endpointPorts []corev1.EndpointPort, reconcilePorts bool) error","file":"pkg/controlplane/reconcilers/lease.go","code":"func (r *leaseEndpointReconciler) doReconcile(serviceName string, endpointPorts []corev1.EndpointPort, reconcilePorts bool) error {\n\te, err := r.epAdapter.Get(corev1.NamespaceDefault, serviceName, metav1.GetOptions{})\n\tshouldCreate := false\n\tif err != nil {\n\t\tif !errors.IsNotFound(err) {\n\t\t\treturn err\n\t\t}\n\n\t\tshouldCreate = true\n\t\te = \u0026corev1.Endpoints{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: serviceName,\n\t\t\t\tNamespace: corev1.NamespaceDefault,\n\t\t\t},\n\t\t}\n\t}\n\n\t// ... and the list of master IP keys from etcd\n\tmasterIPs, err := r.masterLeases.ListLeases()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Since we just refreshed our own key, assume that zero endpoints\n\t// returned from storage indicates an issue or invalid state, and thus do\n\t// not update the endpoints list based on the result.\n\tif len(masterIPs) == 0 {\n\t\treturn fmt.Errorf(\"no master IPs were listed in storage, refusing to erase all endpoints for the kubernetes service\")\n\t}\n\n\t// Don't use the EndpointSliceMirroring controller to mirror this to\n\t// EndpointSlices. This may change in the future.\n\tskipMirrorChanged := setSkipMirrorTrue(e)\n\n\t// Next, we compare the current list of endpoints with the list of master IP keys\n\tformatCorrect, ipCorrect, portsCorrect := checkEndpointSubsetFormatWithLease(e, masterIPs, endpointPorts, reconcilePorts)\n\tif !skipMirrorChanged \u0026\u0026 formatCorrect \u0026\u0026 ipCorrect \u0026\u0026 portsCorrect {\n\t\treturn r.epAdapter.EnsureEndpointSliceFromEndpoints(corev1.NamespaceDefault, e)\n\t}\n\n\tif !formatCorrect {\n\t\t// Something is egregiously wrong, just re-make the endpoints record.\n\t\te.Subsets = []corev1.EndpointSubset{{\n\t\t\tAddresses: []corev1.EndpointAddress{},\n\t\t\tPorts: endpointPorts,\n\t\t}}\n\t}\n\n\tif !formatCorrect || !ipCorrect {\n\t\t// repopulate the addresses according to the expected IPs from etcd\n\t\te.Subsets[0].Addresses = make([]corev1.EndpointAddress, len(masterIPs))\n\t\tfor ind, ip := range masterIPs {\n\t\t\te.Subsets[0].Addresses[ind] = corev1.EndpointAddress{IP: ip}\n\t\t}\n\n\t\t// Lexicographic order is retained by this step.\n\t\te.Subsets = endpointsv1.RepackSubsets(e.Subsets)\n\t}\n\n\tif !portsCorrect {\n\t\t// Reset ports.\n\t\te.Subsets[0].Ports = endpointPorts\n\t}\n\n\tklog.Warningf(\"Resetting endpoints for master service %q to %v\", serviceName, masterIPs)\n\tif shouldCreate {\n\t\tif _, err = r.epAdapter.Create(corev1.NamespaceDefault, e); errors.IsAlreadyExists(err) {\n\t\t\terr = nil\n\t\t}\n\t} else {\n\t\t_, err = r.epAdapter.Update(corev1.NamespaceDefault, e)\n\t}\n\treturn err\n}","line":{"from":187,"to":260}} {"id":100005240,"name":"checkEndpointSubsetFormatWithLease","signature":"func checkEndpointSubsetFormatWithLease(e *corev1.Endpoints, expectedIPs []string, ports []corev1.EndpointPort, reconcilePorts bool) (formatCorrect bool, ipsCorrect bool, portsCorrect bool)","file":"pkg/controlplane/reconcilers/lease.go","code":"// checkEndpointSubsetFormatWithLease determines if the endpoint is in the\n// format ReconcileEndpoints expects when the controller is using leases.\n//\n// Return values:\n// - formatCorrect is true if exactly one subset is found.\n// - ipsCorrect when the addresses in the endpoints match the expected addresses list\n// - portsCorrect is true when endpoint ports exactly match provided ports.\n// portsCorrect is only evaluated when reconcilePorts is set to true.\nfunc checkEndpointSubsetFormatWithLease(e *corev1.Endpoints, expectedIPs []string, ports []corev1.EndpointPort, reconcilePorts bool) (formatCorrect bool, ipsCorrect bool, portsCorrect bool) {\n\tif len(e.Subsets) != 1 {\n\t\treturn false, false, false\n\t}\n\tsub := \u0026e.Subsets[0]\n\tportsCorrect = true\n\tif reconcilePorts {\n\t\tif len(sub.Ports) != len(ports) {\n\t\t\tportsCorrect = false\n\t\t} else {\n\t\t\tfor i, port := range ports {\n\t\t\t\tif port != sub.Ports[i] {\n\t\t\t\t\tportsCorrect = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tipsCorrect = true\n\tif len(sub.Addresses) != len(expectedIPs) {\n\t\tipsCorrect = false\n\t} else {\n\t\t// check the actual content of the addresses\n\t\t// present addrs is used as a set (the keys) and to indicate if a\n\t\t// value was already found (the values)\n\t\tpresentAddrs := make(map[string]bool, len(expectedIPs))\n\t\tfor _, ip := range expectedIPs {\n\t\t\tpresentAddrs[ip] = false\n\t\t}\n\n\t\t// uniqueness is assumed amongst all Addresses.\n\t\tfor _, addr := range sub.Addresses {\n\t\t\tif alreadySeen, ok := presentAddrs[addr.IP]; alreadySeen || !ok {\n\t\t\t\tipsCorrect = false\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tpresentAddrs[addr.IP] = true\n\t\t}\n\t}\n\n\treturn true, ipsCorrect, portsCorrect\n}","line":{"from":262,"to":313}} {"id":100005241,"name":"RemoveEndpoints","signature":"func (r *leaseEndpointReconciler) RemoveEndpoints(serviceName string, ip net.IP, endpointPorts []corev1.EndpointPort) error","file":"pkg/controlplane/reconcilers/lease.go","code":"func (r *leaseEndpointReconciler) RemoveEndpoints(serviceName string, ip net.IP, endpointPorts []corev1.EndpointPort) error {\n\tif err := r.masterLeases.RemoveLease(ip.String()); err != nil {\n\t\treturn err\n\t}\n\n\treturn r.doReconcile(serviceName, endpointPorts, true)\n}","line":{"from":315,"to":321}} {"id":100005242,"name":"StopReconciling","signature":"func (r *leaseEndpointReconciler) StopReconciling()","file":"pkg/controlplane/reconcilers/lease.go","code":"func (r *leaseEndpointReconciler) StopReconciling() {\n\tr.reconcilingLock.Lock()\n\tdefer r.reconcilingLock.Unlock()\n\tr.stopReconcilingCalled = true\n}","line":{"from":323,"to":327}} {"id":100005243,"name":"Destroy","signature":"func (r *leaseEndpointReconciler) Destroy()","file":"pkg/controlplane/reconcilers/lease.go","code":"func (r *leaseEndpointReconciler) Destroy() {\n\tr.masterLeases.Destroy()\n}","line":{"from":329,"to":331}} {"id":100005244,"name":"NewNoneEndpointReconciler","signature":"func NewNoneEndpointReconciler() EndpointReconciler","file":"pkg/controlplane/reconcilers/none.go","code":"// NewNoneEndpointReconciler creates a new EndpointReconciler that reconciles based on a\n// nothing. It is a no-op.\nfunc NewNoneEndpointReconciler() EndpointReconciler {\n\treturn \u0026noneEndpointReconciler{}\n}","line":{"from":29,"to":33}} {"id":100005245,"name":"ReconcileEndpoints","signature":"func (r *noneEndpointReconciler) ReconcileEndpoints(serviceName string, ip net.IP, endpointPorts []corev1.EndpointPort, reconcilePorts bool) error","file":"pkg/controlplane/reconcilers/none.go","code":"// ReconcileEndpoints noop reconcile\nfunc (r *noneEndpointReconciler) ReconcileEndpoints(serviceName string, ip net.IP, endpointPorts []corev1.EndpointPort, reconcilePorts bool) error {\n\treturn nil\n}","line":{"from":35,"to":38}} {"id":100005246,"name":"RemoveEndpoints","signature":"func (r *noneEndpointReconciler) RemoveEndpoints(serviceName string, ip net.IP, endpointPorts []corev1.EndpointPort) error","file":"pkg/controlplane/reconcilers/none.go","code":"// RemoveEndpoints noop reconcile\nfunc (r *noneEndpointReconciler) RemoveEndpoints(serviceName string, ip net.IP, endpointPorts []corev1.EndpointPort) error {\n\treturn nil\n}","line":{"from":40,"to":43}} {"id":100005247,"name":"StopReconciling","signature":"func (r *noneEndpointReconciler) StopReconciling()","file":"pkg/controlplane/reconcilers/none.go","code":"func (r *noneEndpointReconciler) StopReconciling() {\n}","line":{"from":45,"to":46}} {"id":100005248,"name":"Destroy","signature":"func (r *noneEndpointReconciler) Destroy()","file":"pkg/controlplane/reconcilers/none.go","code":"func (r *noneEndpointReconciler) Destroy() {\n}","line":{"from":48,"to":49}} {"id":100005249,"name":"Names","signature":"func (t Types) Names() []string","file":"pkg/controlplane/reconcilers/reconcilers.go","code":"// Names returns a slice of all the reconciler names\nfunc (t Types) Names() []string {\n\tstrs := make([]string, len(t))\n\tfor i, v := range t {\n\t\tstrs[i] = string(v)\n\t}\n\treturn strs\n}","line":{"from":71,"to":78}} {"id":100005250,"name":"ServiceIPRange","signature":"func ServiceIPRange(passedServiceClusterIPRange net.IPNet) (net.IPNet, net.IP, error)","file":"pkg/controlplane/services.go","code":"// ServiceIPRange checks if the serviceClusterIPRange flag is nil, raising a warning if so and\n// setting service ip range to the default value in kubeoptions.DefaultServiceIPCIDR\n// for now until the default is removed per the deprecation timeline guidelines.\n// Returns service ip range, api server service IP, and an error\nfunc ServiceIPRange(passedServiceClusterIPRange net.IPNet) (net.IPNet, net.IP, error) {\n\tserviceClusterIPRange := passedServiceClusterIPRange\n\tif passedServiceClusterIPRange.IP == nil {\n\t\tklog.Warningf(\"No CIDR for service cluster IPs specified. Default value which was %s is deprecated and will be removed in future releases. Please specify it using --service-cluster-ip-range on kube-apiserver.\", kubeoptions.DefaultServiceIPCIDR.String())\n\t\tserviceClusterIPRange = kubeoptions.DefaultServiceIPCIDR\n\t}\n\n\tsize := integer.Int64Min(utilnet.RangeSize(\u0026serviceClusterIPRange), 1\u003c\u003c16)\n\tif size \u003c 8 {\n\t\treturn net.IPNet{}, net.IP{}, fmt.Errorf(\"the service cluster IP range must be at least %d IP addresses\", 8)\n\t}\n\n\t// Select the first valid IP from ServiceClusterIPRange to use as the GenericAPIServer service IP.\n\tapiServerServiceIP, err := utilnet.GetIndexedIP(\u0026serviceClusterIPRange, 1)\n\tif err != nil {\n\t\treturn net.IPNet{}, net.IP{}, err\n\t}\n\tklog.V(4).Infof(\"Setting service IP to %q (read-write).\", apiServerServiceIP)\n\n\treturn serviceClusterIPRange, apiServerServiceIP, nil\n}","line":{"from":30,"to":54}} {"id":100005251,"name":"receiveChallengeFromLoginServer","signature":"func receiveChallengeFromLoginServer(serverAddress string) (*authDirective, error)","file":"pkg/credentialprovider/azure/azure_acr_helper.go","code":"func receiveChallengeFromLoginServer(serverAddress string) (*authDirective, error) {\n\tchallengeURL := url.URL{\n\t\tScheme: \"https\",\n\t\tHost: serverAddress,\n\t\tPath: \"v2/\",\n\t}\n\tvar err error\n\tvar r *http.Request\n\tr, err = http.NewRequest(\"GET\", challengeURL.String(), nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to construct request, got %v\", err)\n\t}\n\tr.Header.Add(userAgentHeader, userAgent)\n\n\tvar challenge *http.Response\n\tif challenge, err = client.Do(r); err != nil {\n\t\treturn nil, fmt.Errorf(\"error reaching registry endpoint %s, error: %s\", challengeURL.String(), err)\n\t}\n\tdefer challenge.Body.Close()\n\n\tif challenge.StatusCode != 401 {\n\t\treturn nil, fmt.Errorf(\"registry did not issue a valid AAD challenge, status: %d\", challenge.StatusCode)\n\t}\n\n\tvar authHeader []string\n\tvar ok bool\n\tif authHeader, ok = challenge.Header[\"Www-Authenticate\"]; !ok {\n\t\treturn nil, fmt.Errorf(\"challenge response does not contain header 'Www-Authenticate'\")\n\t}\n\n\tif len(authHeader) != 1 {\n\t\treturn nil, fmt.Errorf(\"registry did not issue a valid AAD challenge, authenticate header [%s]\",\n\t\t\tstrings.Join(authHeader, \", \"))\n\t}\n\n\tauthSections := strings.SplitN(authHeader[0], \" \", 2)\n\tauthType := strings.ToLower(authSections[0])\n\tvar authParams *map[string]string\n\tif authParams, err = parseAssignments(authSections[1]); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to understand the contents of Www-Authenticate header %s\", authSections[1])\n\t}\n\n\t// verify headers\n\tif !strings.EqualFold(\"Bearer\", authType) {\n\t\treturn nil, fmt.Errorf(\"Www-Authenticate: expected realm: Bearer, actual: %s\", authType)\n\t}\n\tif len((*authParams)[\"service\"]) == 0 {\n\t\treturn nil, fmt.Errorf(\"Www-Authenticate: missing header \\\"service\\\"\")\n\t}\n\tif len((*authParams)[\"realm\"]) == 0 {\n\t\treturn nil, fmt.Errorf(\"Www-Authenticate: missing header \\\"realm\\\"\")\n\t}\n\n\treturn \u0026authDirective{\n\t\tservice: (*authParams)[\"service\"],\n\t\trealm: (*authParams)[\"realm\"],\n\t}, nil\n}","line":{"from":87,"to":144}} {"id":100005252,"name":"performTokenExchange","signature":"func performTokenExchange(","file":"pkg/credentialprovider/azure/azure_acr_helper.go","code":"func performTokenExchange(\n\tserverAddress string,\n\tdirective *authDirective,\n\ttenant string,\n\taccessToken string) (string, error) {\n\tvar err error\n\tdata := url.Values{\n\t\t\"service\": []string{directive.service},\n\t\t\"grant_type\": []string{\"access_token_refresh_token\"},\n\t\t\"access_token\": []string{accessToken},\n\t\t\"refresh_token\": []string{accessToken},\n\t\t\"tenant\": []string{tenant},\n\t}\n\n\tvar realmURL *url.URL\n\tif realmURL, err = url.Parse(directive.realm); err != nil {\n\t\treturn \"\", fmt.Errorf(\"Www-Authenticate: invalid realm %s\", directive.realm)\n\t}\n\tauthEndpoint := fmt.Sprintf(\"%s://%s/oauth2/exchange\", realmURL.Scheme, realmURL.Host)\n\n\tdatac := data.Encode()\n\tvar r *http.Request\n\tr, err = http.NewRequest(\"POST\", authEndpoint, bytes.NewBufferString(datac))\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to construct request, got %v\", err)\n\t}\n\tr.Header.Add(userAgentHeader, userAgent)\n\tr.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\tr.Header.Add(\"Content-Length\", strconv.Itoa(len(datac)))\n\n\tvar exchange *http.Response\n\tif exchange, err = client.Do(r); err != nil {\n\t\treturn \"\", fmt.Errorf(\"Www-Authenticate: failed to reach auth url %s\", authEndpoint)\n\t}\n\n\tdefer exchange.Body.Close()\n\tif exchange.StatusCode != 200 {\n\t\treturn \"\", fmt.Errorf(\"Www-Authenticate: auth url %s responded with status code %d\", authEndpoint, exchange.StatusCode)\n\t}\n\n\tvar content []byte\n\tlimitedReader := \u0026io.LimitedReader{R: exchange.Body, N: maxReadLength}\n\tif content, err = ioutil.ReadAll(limitedReader); err != nil {\n\t\treturn \"\", fmt.Errorf(\"Www-Authenticate: error reading response from %s\", authEndpoint)\n\t}\n\n\tif limitedReader.N \u003c= 0 {\n\t\treturn \"\", errors.New(\"the read limit is reached\")\n\t}\n\n\tvar authResp acrAuthResponse\n\tif err = json.Unmarshal(content, \u0026authResp); err != nil {\n\t\treturn \"\", fmt.Errorf(\"Www-Authenticate: unable to read response %s\", content)\n\t}\n\n\treturn authResp.RefreshToken, nil\n}","line":{"from":146,"to":202}} {"id":100005253,"name":"parseAssignments","signature":"func parseAssignments(statements string) (*map[string]string, error)","file":"pkg/credentialprovider/azure/azure_acr_helper.go","code":"// Try and parse a string of assignments in the form of:\n// key1 = value1, key2 = \"value 2\", key3 = \"\"\n// Note: this method and handle quotes but does not handle escaping of quotes\nfunc parseAssignments(statements string) (*map[string]string, error) {\n\tvar cursor int\n\tresult := make(map[string]string)\n\tvar errorMsg = fmt.Errorf(\"malformed header value: %s\", statements)\n\tfor {\n\t\t// parse key\n\t\tequalIndex := nextOccurrence(statements, cursor, \"=\")\n\t\tif equalIndex == -1 {\n\t\t\treturn nil, errorMsg\n\t\t}\n\t\tkey := strings.TrimSpace(statements[cursor:equalIndex])\n\n\t\t// parse value\n\t\tcursor = nextNoneSpace(statements, equalIndex+1)\n\t\tif cursor == -1 {\n\t\t\treturn nil, errorMsg\n\t\t}\n\t\t// case: value is quoted\n\t\tif statements[cursor] == '\"' {\n\t\t\tcursor = cursor + 1\n\t\t\t// like I said, not handling escapes, but this will skip any comma that's\n\t\t\t// within the quotes which is somewhat more likely\n\t\t\tcloseQuoteIndex := nextOccurrence(statements, cursor, \"\\\"\")\n\t\t\tif closeQuoteIndex == -1 {\n\t\t\t\treturn nil, errorMsg\n\t\t\t}\n\t\t\tvalue := statements[cursor:closeQuoteIndex]\n\t\t\tresult[key] = value\n\n\t\t\tcommaIndex := nextNoneSpace(statements, closeQuoteIndex+1)\n\t\t\tif commaIndex == -1 {\n\t\t\t\t// no more comma, done\n\t\t\t\treturn \u0026result, nil\n\t\t\t} else if statements[commaIndex] != ',' {\n\t\t\t\t// expect comma immediately after close quote\n\t\t\t\treturn nil, errorMsg\n\t\t\t} else {\n\t\t\t\tcursor = commaIndex + 1\n\t\t\t}\n\t\t} else {\n\t\t\tcommaIndex := nextOccurrence(statements, cursor, \",\")\n\t\t\tendStatements := commaIndex == -1\n\t\t\tvar untrimmed string\n\t\t\tif endStatements {\n\t\t\t\tuntrimmed = statements[cursor:commaIndex]\n\t\t\t} else {\n\t\t\t\tuntrimmed = statements[cursor:]\n\t\t\t}\n\t\t\tvalue := strings.TrimSpace(untrimmed)\n\n\t\t\tif len(value) == 0 {\n\t\t\t\t// disallow empty value without quote\n\t\t\t\treturn nil, errorMsg\n\t\t\t}\n\n\t\t\tresult[key] = value\n\n\t\t\tif endStatements {\n\t\t\t\treturn \u0026result, nil\n\t\t\t}\n\t\t\tcursor = commaIndex + 1\n\t\t}\n\t}\n}","line":{"from":204,"to":270}} {"id":100005254,"name":"nextOccurrence","signature":"func nextOccurrence(str string, start int, sep string) int","file":"pkg/credentialprovider/azure/azure_acr_helper.go","code":"func nextOccurrence(str string, start int, sep string) int {\n\tif start \u003e= len(str) {\n\t\treturn -1\n\t}\n\toffset := strings.Index(str[start:], sep)\n\tif offset == -1 {\n\t\treturn -1\n\t}\n\treturn offset + start\n}","line":{"from":272,"to":281}} {"id":100005255,"name":"nextNoneSpace","signature":"func nextNoneSpace(str string, start int) int","file":"pkg/credentialprovider/azure/azure_acr_helper.go","code":"func nextNoneSpace(str string, start int) int {\n\tif start \u003e= len(str) {\n\t\treturn -1\n\t}\n\toffset := strings.IndexFunc(str[start:], func(c rune) bool { return !unicode.IsSpace(c) })\n\tif offset == -1 {\n\t\treturn -1\n\t}\n\treturn offset + start\n}","line":{"from":283,"to":292}} {"id":100005256,"name":"init","signature":"func init()","file":"pkg/credentialprovider/azure/azure_credentials.go","code":"// init registers the various means by which credentials may\n// be resolved on Azure.\nfunc init() {\n\tcredentialprovider.RegisterCredentialProvider(\n\t\t\"azure\",\n\t\tNewACRProvider(flagConfigFile),\n\t)\n}","line":{"from":59,"to":66}} {"id":100005257,"name":"stringKeyFunc","signature":"func stringKeyFunc(obj interface{}) (string, error)","file":"pkg/credentialprovider/azure/azure_credentials.go","code":"// stringKeyFunc returns the cache key as a string\nfunc stringKeyFunc(obj interface{}) (string, error) {\n\tkey := obj.(*cacheEntry).registry\n\treturn key, nil\n}","line":{"from":77,"to":81}} {"id":100005258,"name":"IsExpired","signature":"func (p *acrExpirationPolicy) IsExpired(entry *cache.TimestampedEntry) bool","file":"pkg/credentialprovider/azure/azure_credentials.go","code":"// IsExpired checks if the ACR credentials are expired.\nfunc (p *acrExpirationPolicy) IsExpired(entry *cache.TimestampedEntry) bool {\n\treturn time.Now().After(entry.Obj.(*cacheEntry).expiresAt)\n}","line":{"from":83,"to":86}} {"id":100005259,"name":"NewACRProvider","signature":"func NewACRProvider(configFile *string) credentialprovider.DockerConfigProvider","file":"pkg/credentialprovider/azure/azure_credentials.go","code":"// NewACRProvider parses the specified configFile and returns a DockerConfigProvider\nfunc NewACRProvider(configFile *string) credentialprovider.DockerConfigProvider {\n\treturn \u0026acrProvider{\n\t\tfile: configFile,\n\t\tcache: cache.NewExpirationStore(stringKeyFunc, \u0026acrExpirationPolicy{}),\n\t}\n}","line":{"from":93,"to":99}} {"id":100005260,"name":"parseConfig","signature":"func parseConfig(configReader io.Reader) (*auth.AzureAuthConfig, error)","file":"pkg/credentialprovider/azure/azure_credentials.go","code":"// ParseConfig returns a parsed configuration for an Azure cloudprovider config file\nfunc parseConfig(configReader io.Reader) (*auth.AzureAuthConfig, error) {\n\tvar config auth.AzureAuthConfig\n\n\tif configReader == nil {\n\t\treturn \u0026config, nil\n\t}\n\n\tlimitedReader := \u0026io.LimitedReader{R: configReader, N: maxReadLength}\n\tconfigContents, err := ioutil.ReadAll(limitedReader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif limitedReader.N \u003c= 0 {\n\t\treturn nil, errors.New(\"the read limit is reached\")\n\t}\n\terr = yaml.Unmarshal(configContents, \u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026config, nil\n}","line":{"from":109,"to":131}} {"id":100005261,"name":"loadConfig","signature":"func (a *acrProvider) loadConfig(rdr io.Reader) error","file":"pkg/credentialprovider/azure/azure_credentials.go","code":"func (a *acrProvider) loadConfig(rdr io.Reader) error {\n\tvar err error\n\ta.config, err = parseConfig(rdr)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to load azure credential file: %v\", err)\n\t}\n\n\ta.environment, err = auth.ParseAzureEnvironment(a.config.Cloud, a.config.ResourceManagerEndpoint, a.config.IdentitySystem)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":133,"to":146}} {"id":100005262,"name":"Enabled","signature":"func (a *acrProvider) Enabled() bool","file":"pkg/credentialprovider/azure/azure_credentials.go","code":"func (a *acrProvider) Enabled() bool {\n\tif a.file == nil || len(*a.file) == 0 {\n\t\tklog.V(5).Infof(\"Azure config unspecified, disabling\")\n\t\treturn false\n\t}\n\n\tif credentialprovider.AreLegacyCloudCredentialProvidersDisabled() {\n\t\twarnOnce.Do(func() {\n\t\t\tklog.V(4).Infof(\"Azure credential provider is now disabled. Please refer to sig-cloud-provider for guidance on external credential provider integration for Azure\")\n\t\t})\n\t\treturn false\n\t}\n\n\tf, err := os.Open(*a.file)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to load config from file: %s\", *a.file)\n\t\treturn false\n\t}\n\tdefer f.Close()\n\n\terr = a.loadConfig(f)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to load config from file: %s\", *a.file)\n\t\treturn false\n\t}\n\n\ta.servicePrincipalToken, err = auth.GetServicePrincipalToken(a.config, a.environment)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to create service principal token: %v\", err)\n\t}\n\treturn true\n}","line":{"from":148,"to":179}} {"id":100005263,"name":"getFromCache","signature":"func (a *acrProvider) getFromCache(loginServer string) (credentialprovider.DockerConfig, bool)","file":"pkg/credentialprovider/azure/azure_credentials.go","code":"// getFromCache attempts to get credentials from the cache\nfunc (a *acrProvider) getFromCache(loginServer string) (credentialprovider.DockerConfig, bool) {\n\tcfg := credentialprovider.DockerConfig{}\n\tobj, exists, err := a.cache.GetByKey(loginServer)\n\tif err != nil {\n\t\tklog.Errorf(\"error getting ACR credentials from cache: %v\", err)\n\t\treturn cfg, false\n\t}\n\tif !exists {\n\t\treturn cfg, false\n\t}\n\n\tentry := obj.(*cacheEntry)\n\tcfg[entry.registry] = entry.credentials\n\treturn cfg, true\n}","line":{"from":181,"to":196}} {"id":100005264,"name":"getFromACR","signature":"func (a *acrProvider) getFromACR(loginServer string) (credentialprovider.DockerConfig, error)","file":"pkg/credentialprovider/azure/azure_credentials.go","code":"// getFromACR gets credentials from ACR since they are not in the cache\nfunc (a *acrProvider) getFromACR(loginServer string) (credentialprovider.DockerConfig, error) {\n\tcfg := credentialprovider.DockerConfig{}\n\tcred, err := getACRDockerEntryFromARMToken(a, loginServer)\n\tif err != nil {\n\t\treturn cfg, err\n\t}\n\n\tentry := \u0026cacheEntry{\n\t\texpiresAt: time.Now().Add(10 * time.Minute),\n\t\tcredentials: *cred,\n\t\tregistry: loginServer,\n\t}\n\tif err := a.cache.Add(entry); err != nil {\n\t\treturn cfg, err\n\t}\n\tcfg[loginServer] = *cred\n\treturn cfg, nil\n}","line":{"from":198,"to":216}} {"id":100005265,"name":"Provide","signature":"func (a *acrProvider) Provide(image string) credentialprovider.DockerConfig","file":"pkg/credentialprovider/azure/azure_credentials.go","code":"func (a *acrProvider) Provide(image string) credentialprovider.DockerConfig {\n\tloginServer := a.parseACRLoginServerFromImage(image)\n\tif loginServer == \"\" {\n\t\tklog.V(2).Infof(\"image(%s) is not from ACR, return empty authentication\", image)\n\t\treturn credentialprovider.DockerConfig{}\n\t}\n\n\tcfg := credentialprovider.DockerConfig{}\n\tif a.config != nil \u0026\u0026 a.config.UseManagedIdentityExtension {\n\t\tvar exists bool\n\t\tcfg, exists = a.getFromCache(loginServer)\n\t\tif exists {\n\t\t\tklog.V(4).Infof(\"Got ACR credentials from cache for %s\", loginServer)\n\t\t} else {\n\t\t\tklog.V(2).Infof(\"unable to get ACR credentials from cache for %s, checking ACR API\", loginServer)\n\t\t\tvar err error\n\t\t\tcfg, err = a.getFromACR(loginServer)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"error getting credentials from ACR for %s %v\", loginServer, err)\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Add our entry for each of the supported container registry URLs\n\t\tfor _, url := range containerRegistryUrls {\n\t\t\tcred := \u0026credentialprovider.DockerConfigEntry{\n\t\t\t\tUsername: a.config.AADClientID,\n\t\t\t\tPassword: a.config.AADClientSecret,\n\t\t\t\tEmail: dummyRegistryEmail,\n\t\t\t}\n\t\t\tcfg[url] = *cred\n\t\t}\n\n\t\t// Handle the custom cloud case\n\t\t// In clouds where ACR is not yet deployed, the string will be empty\n\t\tif a.environment != nil \u0026\u0026 strings.Contains(a.environment.ContainerRegistryDNSSuffix, \".azurecr.\") {\n\t\t\tcustomAcrSuffix := \"*\" + a.environment.ContainerRegistryDNSSuffix\n\t\t\thasBeenAdded := false\n\t\t\tfor _, url := range containerRegistryUrls {\n\t\t\t\tif strings.EqualFold(url, customAcrSuffix) {\n\t\t\t\t\thasBeenAdded = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !hasBeenAdded {\n\t\t\t\tcred := \u0026credentialprovider.DockerConfigEntry{\n\t\t\t\t\tUsername: a.config.AADClientID,\n\t\t\t\t\tPassword: a.config.AADClientSecret,\n\t\t\t\t\tEmail: dummyRegistryEmail,\n\t\t\t\t}\n\t\t\t\tcfg[customAcrSuffix] = *cred\n\t\t\t}\n\t\t}\n\t}\n\n\t// add ACR anonymous repo support: use empty username and password for anonymous access\n\tdefaultConfigEntry := credentialprovider.DockerConfigEntry{\n\t\tUsername: \"\",\n\t\tPassword: \"\",\n\t\tEmail: dummyRegistryEmail,\n\t}\n\tcfg[\"*.azurecr.*\"] = defaultConfigEntry\n\treturn cfg\n}","line":{"from":218,"to":281}} {"id":100005266,"name":"getLoginServer","signature":"func getLoginServer(registry containerregistry.Registry) string","file":"pkg/credentialprovider/azure/azure_credentials.go","code":"func getLoginServer(registry containerregistry.Registry) string {\n\treturn *(*registry.RegistryProperties).LoginServer\n}","line":{"from":283,"to":285}} {"id":100005267,"name":"getACRDockerEntryFromARMToken","signature":"func getACRDockerEntryFromARMToken(a *acrProvider, loginServer string) (*credentialprovider.DockerConfigEntry, error)","file":"pkg/credentialprovider/azure/azure_credentials.go","code":"func getACRDockerEntryFromARMToken(a *acrProvider, loginServer string) (*credentialprovider.DockerConfigEntry, error) {\n\tif a.servicePrincipalToken == nil {\n\t\ttoken, err := auth.GetServicePrincipalToken(a.config, a.environment)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to create service principal token: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\ta.servicePrincipalToken = token\n\t} else {\n\t\t// Run EnsureFresh to make sure the token is valid and does not expire\n\t\tif err := a.servicePrincipalToken.EnsureFresh(); err != nil {\n\t\t\tklog.Errorf(\"Failed to ensure fresh service principal token: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tarmAccessToken := a.servicePrincipalToken.OAuthToken()\n\n\tklog.V(4).Infof(\"discovering auth redirects for: %s\", loginServer)\n\tdirective, err := receiveChallengeFromLoginServer(loginServer)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to receive challenge: %s\", err)\n\t\treturn nil, err\n\t}\n\n\tklog.V(4).Infof(\"exchanging an acr refresh_token\")\n\tregistryRefreshToken, err := performTokenExchange(\n\t\tloginServer, directive, a.config.TenantID, armAccessToken)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to perform token exchange: %s\", err)\n\t\treturn nil, err\n\t}\n\n\tklog.V(4).Infof(\"adding ACR docker config entry for: %s\", loginServer)\n\treturn \u0026credentialprovider.DockerConfigEntry{\n\t\tUsername: dockerTokenLoginUsernameGUID,\n\t\tPassword: registryRefreshToken,\n\t\tEmail: dummyRegistryEmail,\n\t}, nil\n}","line":{"from":287,"to":326}} {"id":100005268,"name":"parseACRLoginServerFromImage","signature":"func (a *acrProvider) parseACRLoginServerFromImage(image string) string","file":"pkg/credentialprovider/azure/azure_credentials.go","code":"// parseACRLoginServerFromImage takes image as parameter and returns login server of it.\n// Parameter `image` is expected in following format: foo.azurecr.io/bar/imageName:version\n// If the provided image is not an acr image, this function will return an empty string.\nfunc (a *acrProvider) parseACRLoginServerFromImage(image string) string {\n\tmatch := acrRE.FindAllString(image, -1)\n\tif len(match) == 1 {\n\t\treturn match[0]\n\t}\n\n\t// handle the custom cloud case\n\tif a != nil \u0026\u0026 a.environment != nil {\n\t\tcloudAcrSuffix := a.environment.ContainerRegistryDNSSuffix\n\t\tcloudAcrSuffixLength := len(cloudAcrSuffix)\n\t\tif cloudAcrSuffixLength \u003e 0 {\n\t\t\tcustomAcrSuffixIndex := strings.Index(image, cloudAcrSuffix)\n\t\t\tif customAcrSuffixIndex != -1 {\n\t\t\t\tendIndex := customAcrSuffixIndex + cloudAcrSuffixLength\n\t\t\t\treturn image[0:endIndex]\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\"\n}","line":{"from":328,"to":351}} {"id":100005269,"name":"SetPreferredDockercfgPath","signature":"func SetPreferredDockercfgPath(path string)","file":"pkg/credentialprovider/config.go","code":"// SetPreferredDockercfgPath set preferred docker config path\nfunc SetPreferredDockercfgPath(path string) {\n\tpreferredPathLock.Lock()\n\tdefer preferredPathLock.Unlock()\n\tpreferredPath = path\n}","line":{"from":73,"to":78}} {"id":100005270,"name":"GetPreferredDockercfgPath","signature":"func GetPreferredDockercfgPath() string","file":"pkg/credentialprovider/config.go","code":"// GetPreferredDockercfgPath get preferred docker config path\nfunc GetPreferredDockercfgPath() string {\n\tpreferredPathLock.Lock()\n\tdefer preferredPathLock.Unlock()\n\treturn preferredPath\n}","line":{"from":80,"to":85}} {"id":100005271,"name":"DefaultDockercfgPaths","signature":"func DefaultDockercfgPaths() []string","file":"pkg/credentialprovider/config.go","code":"// DefaultDockercfgPaths returns default search paths of .dockercfg\nfunc DefaultDockercfgPaths() []string {\n\treturn []string{GetPreferredDockercfgPath(), workingDirPath, homeDirPath, rootDirPath}\n}","line":{"from":87,"to":90}} {"id":100005272,"name":"DefaultDockerConfigJSONPaths","signature":"func DefaultDockerConfigJSONPaths() []string","file":"pkg/credentialprovider/config.go","code":"// DefaultDockerConfigJSONPaths returns default search paths of .docker/config.json\nfunc DefaultDockerConfigJSONPaths() []string {\n\treturn []string{GetPreferredDockercfgPath(), workingDirPath, homeJSONDirPath, rootJSONDirPath}\n}","line":{"from":92,"to":95}} {"id":100005273,"name":"ReadDockercfgFile","signature":"func ReadDockercfgFile(searchPaths []string) (cfg DockerConfig, err error)","file":"pkg/credentialprovider/config.go","code":"// ReadDockercfgFile attempts to read a legacy dockercfg file from the given paths.\n// if searchPaths is empty, the default paths are used.\nfunc ReadDockercfgFile(searchPaths []string) (cfg DockerConfig, err error) {\n\tif len(searchPaths) == 0 {\n\t\tsearchPaths = DefaultDockercfgPaths()\n\t}\n\n\tfor _, configPath := range searchPaths {\n\t\tabsDockerConfigFileLocation, err := filepath.Abs(filepath.Join(configPath, configFileName))\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"while trying to canonicalize %s: %v\", configPath, err)\n\t\t\tcontinue\n\t\t}\n\t\tklog.V(4).Infof(\"looking for .dockercfg at %s\", absDockerConfigFileLocation)\n\t\tcontents, err := ioutil.ReadFile(absDockerConfigFileLocation)\n\t\tif os.IsNotExist(err) {\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\tklog.V(4).Infof(\"while trying to read %s: %v\", absDockerConfigFileLocation, err)\n\t\t\tcontinue\n\t\t}\n\t\tcfg, err := ReadDockerConfigFileFromBytes(contents)\n\t\tif err != nil {\n\t\t\tklog.V(4).Infof(\"couldn't get the config from %q contents: %v\", absDockerConfigFileLocation, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tklog.V(4).Infof(\"found .dockercfg at %s\", absDockerConfigFileLocation)\n\t\treturn cfg, nil\n\n\t}\n\treturn nil, fmt.Errorf(\"couldn't find valid .dockercfg after checking in %v\", searchPaths)\n}","line":{"from":97,"to":130}} {"id":100005274,"name":"ReadDockerConfigJSONFile","signature":"func ReadDockerConfigJSONFile(searchPaths []string) (cfg DockerConfig, err error)","file":"pkg/credentialprovider/config.go","code":"// ReadDockerConfigJSONFile attempts to read a docker config.json file from the given paths.\n// if searchPaths is empty, the default paths are used.\nfunc ReadDockerConfigJSONFile(searchPaths []string) (cfg DockerConfig, err error) {\n\tif len(searchPaths) == 0 {\n\t\tsearchPaths = DefaultDockerConfigJSONPaths()\n\t}\n\tfor _, configPath := range searchPaths {\n\t\tabsDockerConfigFileLocation, err := filepath.Abs(filepath.Join(configPath, configJSONFileName))\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"while trying to canonicalize %s: %v\", configPath, err)\n\t\t\tcontinue\n\t\t}\n\t\tklog.V(4).Infof(\"looking for %s at %s\", configJSONFileName, absDockerConfigFileLocation)\n\t\tcfg, err = ReadSpecificDockerConfigJSONFile(absDockerConfigFileLocation)\n\t\tif err != nil {\n\t\t\tif !os.IsNotExist(err) {\n\t\t\t\tklog.V(4).Infof(\"while trying to read %s: %v\", absDockerConfigFileLocation, err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tklog.V(4).Infof(\"found valid %s at %s\", configJSONFileName, absDockerConfigFileLocation)\n\t\treturn cfg, nil\n\t}\n\treturn nil, fmt.Errorf(\"couldn't find valid %s after checking in %v\", configJSONFileName, searchPaths)\n\n}","line":{"from":132,"to":157}} {"id":100005275,"name":"ReadSpecificDockerConfigJSONFile","signature":"func ReadSpecificDockerConfigJSONFile(filePath string) (cfg DockerConfig, err error)","file":"pkg/credentialprovider/config.go","code":"// ReadSpecificDockerConfigJSONFile attempts to read docker configJSON from a given file path.\nfunc ReadSpecificDockerConfigJSONFile(filePath string) (cfg DockerConfig, err error) {\n\tvar contents []byte\n\n\tif contents, err = ioutil.ReadFile(filePath); err != nil {\n\t\treturn nil, err\n\t}\n\treturn readDockerConfigJSONFileFromBytes(contents)\n}","line":{"from":159,"to":167}} {"id":100005276,"name":"ReadDockerConfigFile","signature":"func ReadDockerConfigFile() (cfg DockerConfig, err error)","file":"pkg/credentialprovider/config.go","code":"// ReadDockerConfigFile read a docker config file from default path\nfunc ReadDockerConfigFile() (cfg DockerConfig, err error) {\n\tif cfg, err := ReadDockerConfigJSONFile(nil); err == nil {\n\t\treturn cfg, nil\n\t}\n\t// Can't find latest config file so check for the old one\n\treturn ReadDockercfgFile(nil)\n}","line":{"from":169,"to":176}} {"id":100005277,"name":"Error","signature":"func (he *HTTPError) Error() string","file":"pkg/credentialprovider/config.go","code":"// Error implements error\nfunc (he *HTTPError) Error() string {\n\treturn fmt.Sprintf(\"http status code: %d while fetching url %s\",\n\t\the.StatusCode, he.URL)\n}","line":{"from":184,"to":188}} {"id":100005278,"name":"ReadURL","signature":"func ReadURL(url string, client *http.Client, header *http.Header) (body []byte, err error)","file":"pkg/credentialprovider/config.go","code":"// ReadURL read contents from given url\nfunc ReadURL(url string, client *http.Client, header *http.Header) (body []byte, err error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif header != nil {\n\t\treq.Header = *header\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tklog.V(2).InfoS(\"Failed to read URL\", \"statusCode\", resp.StatusCode, \"URL\", url)\n\t\treturn nil, \u0026HTTPError{\n\t\t\tStatusCode: resp.StatusCode,\n\t\t\tURL: url,\n\t\t}\n\t}\n\n\tlimitedReader := \u0026io.LimitedReader{R: resp.Body, N: maxReadLength}\n\tcontents, err := ioutil.ReadAll(limitedReader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif limitedReader.N \u003c= 0 {\n\t\treturn nil, errors.New(\"the read limit is reached\")\n\t}\n\n\treturn contents, nil\n}","line":{"from":190,"to":224}} {"id":100005279,"name":"ReadDockerConfigFileFromBytes","signature":"func ReadDockerConfigFileFromBytes(contents []byte) (cfg DockerConfig, err error)","file":"pkg/credentialprovider/config.go","code":"// ReadDockerConfigFileFromBytes read a docker config file from the given bytes\nfunc ReadDockerConfigFileFromBytes(contents []byte) (cfg DockerConfig, err error) {\n\tif err = json.Unmarshal(contents, \u0026cfg); err != nil {\n\t\treturn nil, errors.New(\"error occurred while trying to unmarshal json\")\n\t}\n\treturn\n}","line":{"from":226,"to":232}} {"id":100005280,"name":"readDockerConfigJSONFileFromBytes","signature":"func readDockerConfigJSONFileFromBytes(contents []byte) (cfg DockerConfig, err error)","file":"pkg/credentialprovider/config.go","code":"func readDockerConfigJSONFileFromBytes(contents []byte) (cfg DockerConfig, err error) {\n\tvar cfgJSON DockerConfigJSON\n\tif err = json.Unmarshal(contents, \u0026cfgJSON); err != nil {\n\t\treturn nil, errors.New(\"error occurred while trying to unmarshal json\")\n\t}\n\tcfg = cfgJSON.Auths\n\treturn\n}","line":{"from":234,"to":241}} {"id":100005281,"name":"UnmarshalJSON","signature":"func (ident *DockerConfigEntry) UnmarshalJSON(data []byte) error","file":"pkg/credentialprovider/config.go","code":"// UnmarshalJSON implements the json.Unmarshaler interface.\nfunc (ident *DockerConfigEntry) UnmarshalJSON(data []byte) error {\n\tvar tmp dockerConfigEntryWithAuth\n\terr := json.Unmarshal(data, \u0026tmp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tident.Username = tmp.Username\n\tident.Password = tmp.Password\n\tident.Email = tmp.Email\n\n\tif len(tmp.Auth) == 0 {\n\t\treturn nil\n\t}\n\n\tident.Username, ident.Password, err = decodeDockerConfigFieldAuth(tmp.Auth)\n\treturn err\n}","line":{"from":256,"to":274}} {"id":100005282,"name":"MarshalJSON","signature":"func (ident DockerConfigEntry) MarshalJSON() ([]byte, error)","file":"pkg/credentialprovider/config.go","code":"// MarshalJSON implements the json.Marshaler interface.\nfunc (ident DockerConfigEntry) MarshalJSON() ([]byte, error) {\n\ttoEncode := dockerConfigEntryWithAuth{ident.Username, ident.Password, ident.Email, \"\"}\n\ttoEncode.Auth = encodeDockerConfigFieldAuth(ident.Username, ident.Password)\n\n\treturn json.Marshal(toEncode)\n}","line":{"from":276,"to":282}} {"id":100005283,"name":"decodeDockerConfigFieldAuth","signature":"func decodeDockerConfigFieldAuth(field string) (username, password string, err error)","file":"pkg/credentialprovider/config.go","code":"// decodeDockerConfigFieldAuth deserializes the \"auth\" field from dockercfg into a\n// username and a password. The format of the auth field is base64(\u003cusername\u003e:\u003cpassword\u003e).\nfunc decodeDockerConfigFieldAuth(field string) (username, password string, err error) {\n\n\tvar decoded []byte\n\n\t// StdEncoding can only decode padded string\n\t// RawStdEncoding can only decode unpadded string\n\tif strings.HasSuffix(strings.TrimSpace(field), \"=\") {\n\t\t// decode padded data\n\t\tdecoded, err = base64.StdEncoding.DecodeString(field)\n\t} else {\n\t\t// decode unpadded data\n\t\tdecoded, err = base64.RawStdEncoding.DecodeString(field)\n\t}\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tparts := strings.SplitN(string(decoded), \":\", 2)\n\tif len(parts) != 2 {\n\t\terr = fmt.Errorf(\"unable to parse auth field, must be formatted as base64(username:password)\")\n\t\treturn\n\t}\n\n\tusername = parts[0]\n\tpassword = parts[1]\n\n\treturn\n}","line":{"from":284,"to":314}} {"id":100005284,"name":"encodeDockerConfigFieldAuth","signature":"func encodeDockerConfigFieldAuth(username, password string) string","file":"pkg/credentialprovider/config.go","code":"func encodeDockerConfigFieldAuth(username, password string) string {\n\tfieldValue := username + \":\" + password\n\n\treturn base64.StdEncoding.EncodeToString([]byte(fieldValue))\n}","line":{"from":316,"to":320}} {"id":100005285,"name":"init","signature":"func init()","file":"pkg/credentialprovider/gcp/metadata.go","code":"// init registers the various means by which credentials may\n// be resolved on GCP.\nfunc init() {\n\ttr := utilnet.SetTransportDefaults(\u0026http.Transport{})\n\tmetadataHTTPClientTimeout := time.Second * 10\n\thttpClient := \u0026http.Client{\n\t\tTransport: tr,\n\t\tTimeout: metadataHTTPClientTimeout,\n\t}\n\tcredentialprovider.RegisterCredentialProvider(\"google-dockercfg\",\n\t\t\u0026credentialprovider.CachingDockerConfigProvider{\n\t\t\tProvider: \u0026DockerConfigKeyProvider{\n\t\t\t\tMetadataProvider: MetadataProvider{Client: httpClient},\n\t\t\t},\n\t\t\tLifetime: 60 * time.Second,\n\t\t})\n\n\tcredentialprovider.RegisterCredentialProvider(\"google-dockercfg-url\",\n\t\t\u0026credentialprovider.CachingDockerConfigProvider{\n\t\t\tProvider: \u0026DockerConfigURLKeyProvider{\n\t\t\t\tMetadataProvider: MetadataProvider{Client: httpClient},\n\t\t\t},\n\t\t\tLifetime: 60 * time.Second,\n\t\t})\n\n\tcredentialprovider.RegisterCredentialProvider(\"google-container-registry\",\n\t\t// Never cache this. The access token is already\n\t\t// cached by the metadata service.\n\t\t\u0026ContainerRegistryProvider{\n\t\t\tMetadataProvider: MetadataProvider{Client: httpClient},\n\t\t})\n}","line":{"from":61,"to":92}} {"id":100005286,"name":"onGCEVM","signature":"func onGCEVM() bool","file":"pkg/credentialprovider/gcp/metadata.go","code":"// Returns true if it finds a local GCE VM.\n// Looks at a product file that is an undocumented API.\nfunc onGCEVM() bool {\n\tvar name string\n\n\tif runtime.GOOS == \"windows\" {\n\t\tdata, err := exec.Command(\"wmic\", \"computersystem\", \"get\", \"model\").Output()\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\tfields := strings.Split(strings.TrimSpace(string(data)), \"\\r\\n\")\n\t\tif len(fields) != 2 {\n\t\t\tklog.V(2).Infof(\"Received unexpected value retrieving system model: %q\", string(data))\n\t\t\treturn false\n\t\t}\n\t\tname = fields[1]\n\t} else {\n\t\tdata, err := ioutil.ReadFile(gceProductNameFile)\n\t\tif err != nil {\n\t\t\tklog.V(2).Infof(\"Error while reading product_name: %v\", err)\n\t\t\treturn false\n\t\t}\n\t\tname = strings.TrimSpace(string(data))\n\t}\n\treturn name == \"Google\" || name == \"Google Compute Engine\"\n}","line":{"from":120,"to":145}} {"id":100005287,"name":"Enabled","signature":"func (g *MetadataProvider) Enabled() bool","file":"pkg/credentialprovider/gcp/metadata.go","code":"// Enabled implements DockerConfigProvider for all of the Google implementations.\nfunc (g *MetadataProvider) Enabled() bool {\n\tonGCE := onGCEVM()\n\tif !onGCE {\n\t\treturn false\n\t}\n\tif credentialprovider.AreLegacyCloudCredentialProvidersDisabled() {\n\t\twarnOnce.Do(func() {\n\t\t\tklog.V(4).Infof(\"GCP credential provider is now disabled. Please refer to sig-cloud-provider for guidance on external credential provider integration for GCP\")\n\t\t})\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":147,"to":160}} {"id":100005288,"name":"Provide","signature":"func (g *DockerConfigKeyProvider) Provide(image string) credentialprovider.DockerConfig","file":"pkg/credentialprovider/gcp/metadata.go","code":"// Provide implements DockerConfigProvider\nfunc (g *DockerConfigKeyProvider) Provide(image string) credentialprovider.DockerConfig {\n\treturn registryToDocker(gcpcredential.ProvideConfigKey(g.Client, image))\n}","line":{"from":162,"to":165}} {"id":100005289,"name":"Provide","signature":"func (g *DockerConfigURLKeyProvider) Provide(image string) credentialprovider.DockerConfig","file":"pkg/credentialprovider/gcp/metadata.go","code":"// Provide implements DockerConfigProvider\nfunc (g *DockerConfigURLKeyProvider) Provide(image string) credentialprovider.DockerConfig {\n\treturn registryToDocker(gcpcredential.ProvideURLKey(g.Client, image))\n}","line":{"from":167,"to":170}} {"id":100005290,"name":"runWithBackoff","signature":"func runWithBackoff(f func() ([]byte, error)) []byte","file":"pkg/credentialprovider/gcp/metadata.go","code":"// runWithBackoff runs input function `f` with an exponential backoff.\n// Note that this method can block indefinitely.\nfunc runWithBackoff(f func() ([]byte, error)) []byte {\n\tvar backoff = 100 * time.Millisecond\n\tconst maxBackoff = time.Minute\n\tfor {\n\t\tvalue, err := f()\n\t\tif err == nil {\n\t\t\treturn value\n\t\t}\n\t\ttime.Sleep(backoff)\n\t\tbackoff = backoff * 2\n\t\tif backoff \u003e maxBackoff {\n\t\t\tbackoff = maxBackoff\n\t\t}\n\t}\n}","line":{"from":172,"to":188}} {"id":100005291,"name":"Enabled","signature":"func (g *ContainerRegistryProvider) Enabled() bool","file":"pkg/credentialprovider/gcp/metadata.go","code":"// Enabled implements a special metadata-based check, which verifies the\n// storage scope is available on the GCE VM.\n// If running on a GCE VM, check if 'default' service account exists.\n// If it does not exist, assume that registry is not enabled.\n// If default service account exists, check if relevant scopes exist in the default service account.\n// The metadata service can become temporarily inaccesible. Hence all requests to the metadata\n// service will be retried until the metadata server returns a `200`.\n// It is expected that \"http://metadata.google.internal./computeMetadata/v1/instance/service-accounts/\" will return a `200`\n// and \"http://metadata.google.internal./computeMetadata/v1/instance/service-accounts/default/scopes\" will also return `200`.\n// More information on metadata service can be found here - https://cloud.google.com/compute/docs/storing-retrieving-metadata\nfunc (g *ContainerRegistryProvider) Enabled() bool {\n\tif !onGCEVM() {\n\t\treturn false\n\t}\n\n\tif credentialprovider.AreLegacyCloudCredentialProvidersDisabled() {\n\t\twarnOnce.Do(func() {\n\t\t\tklog.V(4).Infof(\"GCP credential provider is now disabled. Please refer to sig-cloud-provider for guidance on external credential provider integration for GCP\")\n\t\t})\n\t\treturn false\n\t}\n\n\t// Given that we are on GCE, we should keep retrying until the metadata server responds.\n\tvalue := runWithBackoff(func() ([]byte, error) {\n\t\tvalue, err := gcpcredential.ReadURL(serviceAccounts, g.Client, metadataHeader)\n\t\tif err != nil {\n\t\t\tklog.V(2).Infof(\"Failed to Get service accounts from gce metadata server: %v\", err)\n\t\t}\n\t\treturn value, err\n\t})\n\t// We expect the service account to return a list of account directories separated by newlines, e.g.,\n\t// sv-account-name1/\n\t// sv-account-name2/\n\t// ref: https://cloud.google.com/compute/docs/storing-retrieving-metadata\n\tdefaultServiceAccountExists := false\n\tfor _, sa := range strings.Split(string(value), \"\\n\") {\n\t\tif strings.TrimSpace(sa) == defaultServiceAccount {\n\t\t\tdefaultServiceAccountExists = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !defaultServiceAccountExists {\n\t\tklog.V(2).Infof(\"'default' service account does not exist. Found following service accounts: %q\", string(value))\n\t\treturn false\n\t}\n\turl := metadataScopes + \"?alt=json\"\n\tvalue = runWithBackoff(func() ([]byte, error) {\n\t\tvalue, err := gcpcredential.ReadURL(url, g.Client, metadataHeader)\n\t\tif err != nil {\n\t\t\tklog.V(2).Infof(\"Failed to Get scopes in default service account from gce metadata server: %v\", err)\n\t\t}\n\t\treturn value, err\n\t})\n\tvar scopes []string\n\tif err := json.Unmarshal(value, \u0026scopes); err != nil {\n\t\tklog.Errorf(\"Failed to unmarshal scopes: %v\", err)\n\t\treturn false\n\t}\n\tfor _, v := range scopes {\n\t\t// cloudPlatformScope implies storage scope.\n\t\tif strings.HasPrefix(v, StorageScopePrefix) || strings.HasPrefix(v, cloudPlatformScopePrefix) {\n\t\t\treturn true\n\t\t}\n\t}\n\tklog.Warningf(\"Google container registry is disabled, no storage scope is available: %s\", value)\n\treturn false\n}","line":{"from":190,"to":256}} {"id":100005292,"name":"Provide","signature":"func (g *ContainerRegistryProvider) Provide(image string) credentialprovider.DockerConfig","file":"pkg/credentialprovider/gcp/metadata.go","code":"// Provide implements DockerConfigProvider\nfunc (g *ContainerRegistryProvider) Provide(image string) credentialprovider.DockerConfig {\n\treturn registryToDocker(gcpcredential.ProvideContainerRegistry(g.Client, image))\n}","line":{"from":258,"to":261}} {"id":100005293,"name":"registryToDocker","signature":"func registryToDocker(registryConfig credentialconfig.RegistryConfig) credentialprovider.DockerConfig","file":"pkg/credentialprovider/gcp/metadata.go","code":"func registryToDocker(registryConfig credentialconfig.RegistryConfig) credentialprovider.DockerConfig {\n\tdockerConfig := credentialprovider.DockerConfig{}\n\tfor k, v := range registryConfig {\n\t\tdockerConfig[k] = credentialprovider.DockerConfigEntry{\n\t\t\tUsername: v.Username,\n\t\t\tPassword: v.Password,\n\t\t\tEmail: v.Email,\n\t\t}\n\t}\n\treturn dockerConfig\n}","line":{"from":263,"to":273}} {"id":100005294,"name":"Add","signature":"func (dk *BasicDockerKeyring) Add(cfg DockerConfig)","file":"pkg/credentialprovider/keyring.go","code":"// Add add some docker config in basic docker keyring\nfunc (dk *BasicDockerKeyring) Add(cfg DockerConfig) {\n\tif dk.index == nil {\n\t\tdk.index = make([]string, 0)\n\t\tdk.creds = make(map[string][]AuthConfig)\n\t}\n\tfor loc, ident := range cfg {\n\t\tcreds := AuthConfig{\n\t\t\tUsername: ident.Username,\n\t\t\tPassword: ident.Password,\n\t\t\tEmail: ident.Email,\n\t\t}\n\n\t\tvalue := loc\n\t\tif !strings.HasPrefix(value, \"https://\") \u0026\u0026 !strings.HasPrefix(value, \"http://\") {\n\t\t\tvalue = \"https://\" + value\n\t\t}\n\t\tparsed, err := url.Parse(value)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Entry %q in dockercfg invalid (%v), ignoring\", loc, err)\n\t\t\tcontinue\n\t\t}\n\n\t\t// The docker client allows exact matches:\n\t\t// foo.bar.com/namespace\n\t\t// Or hostname matches:\n\t\t// foo.bar.com\n\t\t// It also considers /v2/ and /v1/ equivalent to the hostname\n\t\t// See ResolveAuthConfig in docker/registry/auth.go.\n\t\teffectivePath := parsed.Path\n\t\tif strings.HasPrefix(effectivePath, \"/v2/\") || strings.HasPrefix(effectivePath, \"/v1/\") {\n\t\t\teffectivePath = effectivePath[3:]\n\t\t}\n\t\tvar key string\n\t\tif (len(effectivePath) \u003e 0) \u0026\u0026 (effectivePath != \"/\") {\n\t\t\tkey = parsed.Host + effectivePath\n\t\t} else {\n\t\t\tkey = parsed.Host\n\t\t}\n\t\tdk.creds[key] = append(dk.creds[key], creds)\n\t\tdk.index = append(dk.index, key)\n\t}\n\n\teliminateDupes := sets.NewString(dk.index...)\n\tdk.index = eliminateDupes.List()\n\n\t// Update the index used to identify which credentials to use for a given\n\t// image. The index is reverse-sorted so more specific paths are matched\n\t// first. For example, if for the given image \"gcr.io/etcd-development/etcd\",\n\t// credentials for \"quay.io/coreos\" should match before \"quay.io\".\n\tsort.Sort(sort.Reverse(sort.StringSlice(dk.index)))\n}","line":{"from":75,"to":126}} {"id":100005295,"name":"isDefaultRegistryMatch","signature":"func isDefaultRegistryMatch(image string) bool","file":"pkg/credentialprovider/keyring.go","code":"// isDefaultRegistryMatch determines whether the given image will\n// pull from the default registry (DockerHub) based on the\n// characteristics of its name.\nfunc isDefaultRegistryMatch(image string) bool {\n\tparts := strings.SplitN(image, \"/\", 2)\n\n\tif len(parts[0]) == 0 {\n\t\treturn false\n\t}\n\n\tif len(parts) == 1 {\n\t\t// e.g. library/ubuntu\n\t\treturn true\n\t}\n\n\tif parts[0] == \"docker.io\" || parts[0] == \"index.docker.io\" {\n\t\t// resolve docker.io/image and index.docker.io/image as default registry\n\t\treturn true\n\t}\n\n\t// From: http://blog.docker.com/2013/07/how-to-use-your-own-registry/\n\t// Docker looks for either a “.” (domain separator) or “:” (port separator)\n\t// to learn that the first part of the repository name is a location and not\n\t// a user name.\n\treturn !strings.ContainsAny(parts[0], \".:\")\n}","line":{"from":133,"to":158}} {"id":100005296,"name":"ParseSchemelessURL","signature":"func ParseSchemelessURL(schemelessURL string) (*url.URL, error)","file":"pkg/credentialprovider/keyring.go","code":"// ParseSchemelessURL parses a schemeless url and returns a url.URL\n// url.Parse require a scheme, but ours don't have schemes. Adding a\n// scheme to make url.Parse happy, then clear out the resulting scheme.\nfunc ParseSchemelessURL(schemelessURL string) (*url.URL, error) {\n\tparsed, err := url.Parse(\"https://\" + schemelessURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// clear out the resulting scheme\n\tparsed.Scheme = \"\"\n\treturn parsed, nil\n}","line":{"from":160,"to":171}} {"id":100005297,"name":"SplitURL","signature":"func SplitURL(url *url.URL) (parts []string, port string)","file":"pkg/credentialprovider/keyring.go","code":"// SplitURL splits the host name into parts, as well as the port\nfunc SplitURL(url *url.URL) (parts []string, port string) {\n\thost, port, err := net.SplitHostPort(url.Host)\n\tif err != nil {\n\t\t// could not parse port\n\t\thost, port = url.Host, \"\"\n\t}\n\treturn strings.Split(host, \".\"), port\n}","line":{"from":173,"to":181}} {"id":100005298,"name":"URLsMatchStr","signature":"func URLsMatchStr(glob string, target string) (bool, error)","file":"pkg/credentialprovider/keyring.go","code":"// URLsMatchStr is wrapper for URLsMatch, operating on strings instead of URLs.\nfunc URLsMatchStr(glob string, target string) (bool, error) {\n\tglobURL, err := ParseSchemelessURL(glob)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\ttargetURL, err := ParseSchemelessURL(target)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn URLsMatch(globURL, targetURL)\n}","line":{"from":183,"to":194}} {"id":100005299,"name":"URLsMatch","signature":"func URLsMatch(globURL *url.URL, targetURL *url.URL) (bool, error)","file":"pkg/credentialprovider/keyring.go","code":"// URLsMatch checks whether the given target url matches the glob url, which may have\n// glob wild cards in the host name.\n//\n// Examples:\n//\n//\tglobURL=*.docker.io, targetURL=blah.docker.io =\u003e match\n//\tglobURL=*.docker.io, targetURL=not.right.io =\u003e no match\n//\n// Note that we don't support wildcards in ports and paths yet.\nfunc URLsMatch(globURL *url.URL, targetURL *url.URL) (bool, error) {\n\tglobURLParts, globPort := SplitURL(globURL)\n\ttargetURLParts, targetPort := SplitURL(targetURL)\n\tif globPort != targetPort {\n\t\t// port doesn't match\n\t\treturn false, nil\n\t}\n\tif len(globURLParts) != len(targetURLParts) {\n\t\t// host name does not have the same number of parts\n\t\treturn false, nil\n\t}\n\tif !strings.HasPrefix(targetURL.Path, globURL.Path) {\n\t\t// the path of the credential must be a prefix\n\t\treturn false, nil\n\t}\n\tfor k, globURLPart := range globURLParts {\n\t\ttargetURLPart := targetURLParts[k]\n\t\tmatched, err := filepath.Match(globURLPart, targetURLPart)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif !matched {\n\t\t\t// glob mismatch for some part\n\t\t\treturn false, nil\n\t\t}\n\t}\n\t// everything matches\n\treturn true, nil\n}","line":{"from":196,"to":233}} {"id":100005300,"name":"Lookup","signature":"func (dk *BasicDockerKeyring) Lookup(image string) ([]AuthConfig, bool)","file":"pkg/credentialprovider/keyring.go","code":"// Lookup implements the DockerKeyring method for fetching credentials based on image name.\n// Multiple credentials may be returned if there are multiple potentially valid credentials\n// available. This allows for rotation.\nfunc (dk *BasicDockerKeyring) Lookup(image string) ([]AuthConfig, bool) {\n\t// range over the index as iterating over a map does not provide a predictable ordering\n\tret := []AuthConfig{}\n\tfor _, k := range dk.index {\n\t\t// both k and image are schemeless URLs because even though schemes are allowed\n\t\t// in the credential configurations, we remove them in Add.\n\t\tif matched, _ := URLsMatchStr(k, image); matched {\n\t\t\tret = append(ret, dk.creds[k]...)\n\t\t}\n\t}\n\n\tif len(ret) \u003e 0 {\n\t\treturn ret, true\n\t}\n\n\t// Use credentials for the default registry if provided, and appropriate\n\tif isDefaultRegistryMatch(image) {\n\t\tif auth, ok := dk.creds[defaultRegistryHost]; ok {\n\t\t\treturn auth, true\n\t\t}\n\t}\n\n\treturn []AuthConfig{}, false\n}","line":{"from":235,"to":261}} {"id":100005301,"name":"Lookup","signature":"func (dk *providersDockerKeyring) Lookup(image string) ([]AuthConfig, bool)","file":"pkg/credentialprovider/keyring.go","code":"// Lookup implements the DockerKeyring method for fetching credentials\n// based on image name.\nfunc (dk *providersDockerKeyring) Lookup(image string) ([]AuthConfig, bool) {\n\tkeyring := \u0026BasicDockerKeyring{}\n\n\tfor _, p := range dk.Providers {\n\t\tkeyring.Add(p.Provide(image))\n\t}\n\n\treturn keyring.Lookup(image)\n}","line":{"from":263,"to":273}} {"id":100005302,"name":"Lookup","signature":"func (f *FakeKeyring) Lookup(image string) ([]AuthConfig, bool)","file":"pkg/credentialprovider/keyring.go","code":"// Lookup implements the DockerKeyring method for fetching credentials based on image name\n// return fake auth and ok\nfunc (f *FakeKeyring) Lookup(image string) ([]AuthConfig, bool) {\n\treturn f.auth, f.ok\n}","line":{"from":281,"to":285}} {"id":100005303,"name":"Lookup","signature":"func (k UnionDockerKeyring) Lookup(image string) ([]AuthConfig, bool)","file":"pkg/credentialprovider/keyring.go","code":"// Lookup implements the DockerKeyring method for fetching credentials based on image name.\n// return each credentials\nfunc (k UnionDockerKeyring) Lookup(image string) ([]AuthConfig, bool) {\n\tauthConfigs := []AuthConfig{}\n\tfor _, subKeyring := range k {\n\t\tif subKeyring == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tcurrAuthResults, _ := subKeyring.Lookup(image)\n\t\tauthConfigs = append(authConfigs, currAuthResults...)\n\t}\n\n\treturn authConfigs, (len(authConfigs) \u003e 0)\n}","line":{"from":290,"to":304}} {"id":100005304,"name":"readCredentialProviderConfigFile","signature":"func readCredentialProviderConfigFile(configPath string) (*kubeletconfig.CredentialProviderConfig, error)","file":"pkg/credentialprovider/plugin/config.go","code":"// readCredentialProviderConfigFile receives a path to a config file and decodes it\n// into the internal CredentialProviderConfig type.\nfunc readCredentialProviderConfigFile(configPath string) (*kubeletconfig.CredentialProviderConfig, error) {\n\tif configPath == \"\" {\n\t\treturn nil, fmt.Errorf(\"credential provider config path is empty\")\n\t}\n\n\tdata, err := ioutil.ReadFile(configPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to read external registry credential provider configuration from %q: %w\", configPath, err)\n\t}\n\n\tconfig, err := decode(data)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error decoding config %s: %w\", configPath, err)\n\t}\n\n\treturn config, nil\n}","line":{"from":29,"to":47}} {"id":100005305,"name":"decode","signature":"func decode(data []byte) (*kubeletconfig.CredentialProviderConfig, error)","file":"pkg/credentialprovider/plugin/config.go","code":"// decode decodes data into the internal CredentialProviderConfig type.\nfunc decode(data []byte) (*kubeletconfig.CredentialProviderConfig, error) {\n\tobj, gvk, err := codecs.UniversalDecoder().Decode(data, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif gvk.Kind != \"CredentialProviderConfig\" {\n\t\treturn nil, fmt.Errorf(\"failed to decode %q (wrong Kind)\", gvk.Kind)\n\t}\n\n\tif gvk.Group != kubeletconfig.GroupName {\n\t\treturn nil, fmt.Errorf(\"failed to decode CredentialProviderConfig, unexpected Group: %s\", gvk.Group)\n\t}\n\n\tif internalConfig, ok := obj.(*kubeletconfig.CredentialProviderConfig); ok {\n\t\treturn internalConfig, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"unable to convert %T to *CredentialProviderConfig\", obj)\n}","line":{"from":49,"to":69}} {"id":100005306,"name":"validateCredentialProviderConfig","signature":"func validateCredentialProviderConfig(config *kubeletconfig.CredentialProviderConfig) field.ErrorList","file":"pkg/credentialprovider/plugin/config.go","code":"// validateCredentialProviderConfig validates CredentialProviderConfig.\nfunc validateCredentialProviderConfig(config *kubeletconfig.CredentialProviderConfig) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(config.Providers) == 0 {\n\t\tallErrs = append(allErrs, field.Required(field.NewPath(\"providers\"), \"at least 1 item in plugins is required\"))\n\t}\n\n\tfieldPath := field.NewPath(\"providers\")\n\tfor _, provider := range config.Providers {\n\t\tif strings.Contains(provider.Name, \"/\") {\n\t\t\tallErrs = append(allErrs, field.Invalid(fieldPath.Child(\"name\"), provider.Name, \"provider name cannot contain '/'\"))\n\t\t}\n\n\t\tif strings.Contains(provider.Name, \" \") {\n\t\t\tallErrs = append(allErrs, field.Invalid(fieldPath.Child(\"name\"), provider.Name, \"provider name cannot contain spaces\"))\n\t\t}\n\n\t\tif provider.Name == \".\" {\n\t\t\tallErrs = append(allErrs, field.Invalid(fieldPath.Child(\"name\"), provider.Name, \"provider name cannot be '.'\"))\n\t\t}\n\n\t\tif provider.Name == \"..\" {\n\t\t\tallErrs = append(allErrs, field.Invalid(fieldPath.Child(\"name\"), provider.Name, \"provider name cannot be '..'\"))\n\t\t}\n\n\t\tif provider.APIVersion == \"\" {\n\t\t\tallErrs = append(allErrs, field.Required(fieldPath.Child(\"apiVersion\"), \"apiVersion is required\"))\n\t\t} else if _, ok := apiVersions[provider.APIVersion]; !ok {\n\t\t\tvalidAPIVersions := []string{}\n\t\t\tfor apiVersion := range apiVersions {\n\t\t\t\tvalidAPIVersions = append(validAPIVersions, apiVersion)\n\t\t\t}\n\n\t\t\tallErrs = append(allErrs, field.NotSupported(fieldPath.Child(\"apiVersion\"), provider.APIVersion, validAPIVersions))\n\t\t}\n\n\t\tif len(provider.MatchImages) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(fieldPath.Child(\"matchImages\"), \"at least 1 item in matchImages is required\"))\n\t\t}\n\n\t\tfor _, matchImage := range provider.MatchImages {\n\t\t\tif _, err := credentialprovider.ParseSchemelessURL(matchImage); err != nil {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fieldPath.Child(\"matchImages\"), matchImage, fmt.Sprintf(\"match image is invalid: %s\", err.Error())))\n\t\t\t}\n\t\t}\n\n\t\tif provider.DefaultCacheDuration == nil {\n\t\t\tallErrs = append(allErrs, field.Required(fieldPath.Child(\"defaultCacheDuration\"), \"defaultCacheDuration is required\"))\n\t\t}\n\n\t\tif provider.DefaultCacheDuration != nil \u0026\u0026 provider.DefaultCacheDuration.Duration \u003c 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fieldPath.Child(\"defaultCacheDuration\"), provider.DefaultCacheDuration.Duration, \"defaultCacheDuration must be greater than or equal to 0\"))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":71,"to":128}} {"id":100005307,"name":"registerMetrics","signature":"func registerMetrics()","file":"pkg/credentialprovider/plugin/metrics.go","code":"// registerMetrics registers credential provider metrics.\nfunc registerMetrics() {\n\tregisterOnce.Do(func() {\n\t\tlegacyregistry.MustRegister(kubeletCredentialProviderPluginErrors)\n\t\tlegacyregistry.MustRegister(kubeletCredentialProviderPluginDuration)\n\t})\n}","line":{"from":55,"to":61}} {"id":100005308,"name":"init","signature":"func init()","file":"pkg/credentialprovider/plugin/plugin.go","code":"func init() {\n\tinstall.Install(scheme)\n\tkubeletconfig.AddToScheme(scheme)\n\tkubeletconfigv1alpha1.AddToScheme(scheme)\n\tkubeletconfigv1beta1.AddToScheme(scheme)\n\tkubeletconfigv1.AddToScheme(scheme)\n}","line":{"from":68,"to":74}} {"id":100005309,"name":"RegisterCredentialProviderPlugins","signature":"func RegisterCredentialProviderPlugins(pluginConfigFile, pluginBinDir string) error","file":"pkg/credentialprovider/plugin/plugin.go","code":"// RegisterCredentialProviderPlugins is called from kubelet to register external credential provider\n// plugins according to the CredentialProviderConfig config file.\nfunc RegisterCredentialProviderPlugins(pluginConfigFile, pluginBinDir string) error {\n\tif _, err := os.Stat(pluginBinDir); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn fmt.Errorf(\"plugin binary directory %s did not exist\", pluginBinDir)\n\t\t}\n\n\t\treturn fmt.Errorf(\"error inspecting binary directory %s: %w\", pluginBinDir, err)\n\t}\n\n\tcredentialProviderConfig, err := readCredentialProviderConfigFile(pluginConfigFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terrs := validateCredentialProviderConfig(credentialProviderConfig)\n\tif len(errs) \u003e 0 {\n\t\treturn fmt.Errorf(\"failed to validate credential provider config: %v\", errs.ToAggregate())\n\t}\n\n\t// Register metrics for credential providers\n\tregisterMetrics()\n\n\tfor _, provider := range credentialProviderConfig.Providers {\n\t\tpluginBin := filepath.Join(pluginBinDir, provider.Name)\n\t\tif _, err := os.Stat(pluginBin); err != nil {\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\treturn fmt.Errorf(\"plugin binary executable %s did not exist\", pluginBin)\n\t\t\t}\n\n\t\t\treturn fmt.Errorf(\"error inspecting binary executable %s: %w\", pluginBin, err)\n\t\t}\n\n\t\tplugin, err := newPluginProvider(pluginBinDir, provider)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error initializing plugin provider %s: %w\", provider.Name, err)\n\t\t}\n\n\t\tcredentialprovider.RegisterCredentialProvider(provider.Name, plugin)\n\t}\n\n\treturn nil\n}","line":{"from":76,"to":119}} {"id":100005310,"name":"newPluginProvider","signature":"func newPluginProvider(pluginBinDir string, provider kubeletconfig.CredentialProvider) (*pluginProvider, error)","file":"pkg/credentialprovider/plugin/plugin.go","code":"// newPluginProvider returns a new pluginProvider based on the credential provider config.\nfunc newPluginProvider(pluginBinDir string, provider kubeletconfig.CredentialProvider) (*pluginProvider, error) {\n\tmediaType := \"application/json\"\n\tinfo, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), mediaType)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unsupported media type %q\", mediaType)\n\t}\n\n\tgv, ok := apiVersions[provider.APIVersion]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid apiVersion: %q\", provider.APIVersion)\n\t}\n\n\tclock := clock.RealClock{}\n\n\treturn \u0026pluginProvider{\n\t\tclock: clock,\n\t\tmatchImages: provider.MatchImages,\n\t\tcache: cache.NewExpirationStore(cacheKeyFunc, \u0026cacheExpirationPolicy{clock: clock}),\n\t\tdefaultCacheDuration: provider.DefaultCacheDuration.Duration,\n\t\tlastCachePurge: clock.Now(),\n\t\tplugin: \u0026execPlugin{\n\t\t\tname: provider.Name,\n\t\t\tapiVersion: provider.APIVersion,\n\t\t\tencoder: codecs.EncoderForVersion(info.Serializer, gv),\n\t\t\tpluginBinDir: pluginBinDir,\n\t\t\targs: provider.Args,\n\t\t\tenvVars: provider.Env,\n\t\t\tenviron: os.Environ,\n\t\t},\n\t}, nil\n}","line":{"from":121,"to":152}} {"id":100005311,"name":"cacheKeyFunc","signature":"func cacheKeyFunc(obj interface{}) (string, error)","file":"pkg/credentialprovider/plugin/plugin.go","code":"// cacheKeyFunc extracts AuthEntry.MatchKey as the cache key function for the plugin provider.\nfunc cacheKeyFunc(obj interface{}) (string, error) {\n\tkey := obj.(*cacheEntry).key\n\treturn key, nil\n}","line":{"from":188,"to":192}} {"id":100005312,"name":"IsExpired","signature":"func (c *cacheExpirationPolicy) IsExpired(entry *cache.TimestampedEntry) bool","file":"pkg/credentialprovider/plugin/plugin.go","code":"// IsExpired returns true if the current time is after cacheEntry.expiresAt, which is determined by the\n// cache duration returned from the credential provider plugin response.\nfunc (c *cacheExpirationPolicy) IsExpired(entry *cache.TimestampedEntry) bool {\n\treturn c.clock.Now().After(entry.Obj.(*cacheEntry).expiresAt)\n}","line":{"from":199,"to":203}} {"id":100005313,"name":"Provide","signature":"func (p *pluginProvider) Provide(image string) credentialprovider.DockerConfig","file":"pkg/credentialprovider/plugin/plugin.go","code":"// Provide returns a credentialprovider.DockerConfig based on the credentials returned\n// from cache or the exec plugin.\nfunc (p *pluginProvider) Provide(image string) credentialprovider.DockerConfig {\n\tif !p.isImageAllowed(image) {\n\t\treturn credentialprovider.DockerConfig{}\n\t}\n\n\tcachedConfig, found, err := p.getCachedCredentials(image)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get cached docker config: %v\", err)\n\t\treturn credentialprovider.DockerConfig{}\n\t}\n\n\tif found {\n\t\treturn cachedConfig\n\t}\n\n\t// ExecPlugin is wrapped in single flight to exec plugin once for concurrent same image request.\n\t// The caveat here is we don't know cacheKeyType yet, so if cacheKeyType is registry/global and credentials saved in cache\n\t// on per registry/global basis then exec will be called for all requests if requests are made concurrently.\n\t// foo.bar.registry\n\t// foo.bar.registry/image1\n\t// foo.bar.registry/image2\n\tres, err, _ := p.group.Do(image, func() (interface{}, error) {\n\t\treturn p.plugin.ExecPlugin(context.Background(), image)\n\t})\n\n\tif err != nil {\n\t\tklog.Errorf(\"Failed getting credential from external registry credential provider: %v\", err)\n\t\treturn credentialprovider.DockerConfig{}\n\t}\n\n\tresponse, ok := res.(*credentialproviderapi.CredentialProviderResponse)\n\tif !ok {\n\t\tklog.Errorf(\"Invalid response type returned by external credential provider\")\n\t\treturn credentialprovider.DockerConfig{}\n\t}\n\n\tvar cacheKey string\n\tswitch cacheKeyType := response.CacheKeyType; cacheKeyType {\n\tcase credentialproviderapi.ImagePluginCacheKeyType:\n\t\tcacheKey = image\n\tcase credentialproviderapi.RegistryPluginCacheKeyType:\n\t\tregistry := parseRegistry(image)\n\t\tcacheKey = registry\n\tcase credentialproviderapi.GlobalPluginCacheKeyType:\n\t\tcacheKey = globalCacheKey\n\tdefault:\n\t\tklog.Errorf(\"credential provider plugin did not return a valid cacheKeyType: %q\", cacheKeyType)\n\t\treturn credentialprovider.DockerConfig{}\n\t}\n\n\tdockerConfig := make(credentialprovider.DockerConfig, len(response.Auth))\n\tfor matchImage, authConfig := range response.Auth {\n\t\tdockerConfig[matchImage] = credentialprovider.DockerConfigEntry{\n\t\t\tUsername: authConfig.Username,\n\t\t\tPassword: authConfig.Password,\n\t\t}\n\t}\n\n\t// cache duration was explicitly 0 so don't cache this response at all.\n\tif response.CacheDuration != nil \u0026\u0026 response.CacheDuration.Duration == 0 {\n\t\treturn dockerConfig\n\t}\n\n\tvar expiresAt time.Time\n\t// nil cache duration means use the default cache duration\n\tif response.CacheDuration == nil {\n\t\tif p.defaultCacheDuration == 0 {\n\t\t\treturn dockerConfig\n\t\t}\n\t\texpiresAt = p.clock.Now().Add(p.defaultCacheDuration)\n\t} else {\n\t\texpiresAt = p.clock.Now().Add(response.CacheDuration.Duration)\n\t}\n\n\tcachedEntry := \u0026cacheEntry{\n\t\tkey: cacheKey,\n\t\tcredentials: dockerConfig,\n\t\texpiresAt: expiresAt,\n\t}\n\n\tif err := p.cache.Add(cachedEntry); err != nil {\n\t\tklog.Errorf(\"Error adding auth entry to cache: %v\", err)\n\t}\n\n\treturn dockerConfig\n}","line":{"from":205,"to":292}} {"id":100005314,"name":"Enabled","signature":"func (p *pluginProvider) Enabled() bool","file":"pkg/credentialprovider/plugin/plugin.go","code":"// Enabled always returns true since registration of the plugin via kubelet implies it should be enabled.\nfunc (p *pluginProvider) Enabled() bool {\n\treturn true\n}","line":{"from":294,"to":297}} {"id":100005315,"name":"isImageAllowed","signature":"func (p *pluginProvider) isImageAllowed(image string) bool","file":"pkg/credentialprovider/plugin/plugin.go","code":"// isImageAllowed returns true if the image matches against the list of allowed matches by the plugin.\nfunc (p *pluginProvider) isImageAllowed(image string) bool {\n\tfor _, matchImage := range p.matchImages {\n\t\tif matched, _ := credentialprovider.URLsMatchStr(matchImage, image); matched {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":299,"to":308}} {"id":100005316,"name":"getCachedCredentials","signature":"func (p *pluginProvider) getCachedCredentials(image string) (credentialprovider.DockerConfig, bool, error)","file":"pkg/credentialprovider/plugin/plugin.go","code":"// getCachedCredentials returns a credentialprovider.DockerConfig if cached from the plugin.\nfunc (p *pluginProvider) getCachedCredentials(image string) (credentialprovider.DockerConfig, bool, error) {\n\tp.Lock()\n\tif p.clock.Now().After(p.lastCachePurge.Add(cachePurgeInterval)) {\n\t\t// NewExpirationCache purges expired entries when List() is called\n\t\t// The expired entry in the cache is removed only when Get or List called on it.\n\t\t// List() is called on some interval to remove those expired entries on which Get is never called.\n\t\t_ = p.cache.List()\n\t\tp.lastCachePurge = p.clock.Now()\n\t}\n\tp.Unlock()\n\n\tobj, found, err := p.cache.GetByKey(image)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\tif found {\n\t\treturn obj.(*cacheEntry).credentials, true, nil\n\t}\n\n\tregistry := parseRegistry(image)\n\tobj, found, err = p.cache.GetByKey(registry)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\tif found {\n\t\treturn obj.(*cacheEntry).credentials, true, nil\n\t}\n\n\tobj, found, err = p.cache.GetByKey(globalCacheKey)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\tif found {\n\t\treturn obj.(*cacheEntry).credentials, true, nil\n\t}\n\n\treturn nil, false, nil\n}","line":{"from":310,"to":351}} {"id":100005317,"name":"ExecPlugin","signature":"func (e *execPlugin) ExecPlugin(ctx context.Context, image string) (*credentialproviderapi.CredentialProviderResponse, error)","file":"pkg/credentialprovider/plugin/plugin.go","code":"// ExecPlugin executes the plugin binary with arguments and environment variables specified in CredentialProviderConfig:\n//\n//\t$ ENV_NAME=ENV_VALUE \u003cplugin-name\u003e args[0] args[1] \u003c\u003c\u003crequest\n//\n// The plugin is expected to receive the CredentialProviderRequest API via stdin from the kubelet and\n// return CredentialProviderResponse via stdout.\nfunc (e *execPlugin) ExecPlugin(ctx context.Context, image string) (*credentialproviderapi.CredentialProviderResponse, error) {\n\tklog.V(5).Infof(\"Getting image %s credentials from external exec plugin %s\", image, e.name)\n\n\tauthRequest := \u0026credentialproviderapi.CredentialProviderRequest{Image: image}\n\tdata, err := e.encodeRequest(authRequest)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to encode auth request: %w\", err)\n\t}\n\n\tstdout := \u0026bytes.Buffer{}\n\tstderr := \u0026bytes.Buffer{}\n\tstdin := bytes.NewBuffer(data)\n\n\t// Use a catch-all timeout of 1 minute for all exec-based plugins, this should leave enough\n\t// head room in case a plugin needs to retry a failed request while ensuring an exec plugin\n\t// does not run forever. In the future we may want this timeout to be tweakable from the plugin\n\t// config file.\n\tctx, cancel := context.WithTimeout(ctx, 1*time.Minute)\n\tdefer cancel()\n\n\tcmd := exec.CommandContext(ctx, filepath.Join(e.pluginBinDir, e.name), e.args...)\n\tcmd.Stdout, cmd.Stderr, cmd.Stdin = stdout, stderr, stdin\n\n\tvar configEnvVars []string\n\tfor _, v := range e.envVars {\n\t\tconfigEnvVars = append(configEnvVars, fmt.Sprintf(\"%s=%s\", v.Name, v.Value))\n\t}\n\n\t// Append current system environment variables, to the ones configured in the\n\t// credential provider file. Failing to do so may result in unsuccessful execution\n\t// of the provider binary, see https://github.com/kubernetes/kubernetes/issues/102750\n\t// also, this behaviour is inline with Credential Provider Config spec\n\tcmd.Env = mergeEnvVars(e.environ(), configEnvVars)\n\n\tif err = e.runPlugin(ctx, cmd, image); err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata = stdout.Bytes()\n\t// check that the response apiVersion matches what is expected\n\tgvk, err := json.DefaultMetaFactory.Interpret(data)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading GVK from response: %w\", err)\n\t}\n\n\tif gvk.GroupVersion().String() != e.apiVersion {\n\t\treturn nil, fmt.Errorf(\"apiVersion from credential plugin response did not match expected apiVersion:%s, actual apiVersion:%s\", e.apiVersion, gvk.GroupVersion().String())\n\t}\n\n\tresponse, err := e.decodeResponse(data)\n\tif err != nil {\n\t\t// err is explicitly not wrapped since it may contain credentials in the response.\n\t\treturn nil, errors.New(\"error decoding credential provider plugin response from stdout\")\n\t}\n\n\treturn response, nil\n}","line":{"from":372,"to":434}} {"id":100005318,"name":"runPlugin","signature":"func (e *execPlugin) runPlugin(ctx context.Context, cmd *exec.Cmd, image string) error","file":"pkg/credentialprovider/plugin/plugin.go","code":"func (e *execPlugin) runPlugin(ctx context.Context, cmd *exec.Cmd, image string) error {\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tkubeletCredentialProviderPluginDuration.WithLabelValues(e.name).Observe(time.Since(startTime).Seconds())\n\t}()\n\n\terr := cmd.Run()\n\tif ctx.Err() != nil {\n\t\tkubeletCredentialProviderPluginErrors.WithLabelValues(e.name).Inc()\n\t\treturn fmt.Errorf(\"error execing credential provider plugin %s for image %s: %w\", e.name, image, ctx.Err())\n\t}\n\tif err != nil {\n\t\tkubeletCredentialProviderPluginErrors.WithLabelValues(e.name).Inc()\n\t\treturn fmt.Errorf(\"error execing credential provider plugin %s for image %s: %w\", e.name, image, err)\n\t}\n\treturn nil\n}","line":{"from":436,"to":452}} {"id":100005319,"name":"encodeRequest","signature":"func (e *execPlugin) encodeRequest(request *credentialproviderapi.CredentialProviderRequest) ([]byte, error)","file":"pkg/credentialprovider/plugin/plugin.go","code":"// encodeRequest encodes the internal CredentialProviderRequest type into the v1alpha1 version in json\nfunc (e *execPlugin) encodeRequest(request *credentialproviderapi.CredentialProviderRequest) ([]byte, error) {\n\tdata, err := runtime.Encode(e.encoder, request)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error encoding request: %w\", err)\n\t}\n\n\treturn data, nil\n}","line":{"from":454,"to":462}} {"id":100005320,"name":"decodeResponse","signature":"func (e *execPlugin) decodeResponse(data []byte) (*credentialproviderapi.CredentialProviderResponse, error)","file":"pkg/credentialprovider/plugin/plugin.go","code":"// decodeResponse decodes data into the internal CredentialProviderResponse type\nfunc (e *execPlugin) decodeResponse(data []byte) (*credentialproviderapi.CredentialProviderResponse, error) {\n\tobj, gvk, err := codecs.UniversalDecoder().Decode(data, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif gvk.Kind != \"CredentialProviderResponse\" {\n\t\treturn nil, fmt.Errorf(\"failed to decode CredentialProviderResponse, unexpected Kind: %q\", gvk.Kind)\n\t}\n\n\tif gvk.Group != credentialproviderapi.GroupName {\n\t\treturn nil, fmt.Errorf(\"failed to decode CredentialProviderResponse, unexpected Group: %s\", gvk.Group)\n\t}\n\n\tif internalResponse, ok := obj.(*credentialproviderapi.CredentialProviderResponse); ok {\n\t\treturn internalResponse, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"unable to convert %T to *CredentialProviderResponse\", obj)\n}","line":{"from":464,"to":484}} {"id":100005321,"name":"parseRegistry","signature":"func parseRegistry(image string) string","file":"pkg/credentialprovider/plugin/plugin.go","code":"// parseRegistry extracts the registry hostname of an image (including port if specified).\nfunc parseRegistry(image string) string {\n\timageParts := strings.Split(image, \"/\")\n\treturn imageParts[0]\n}","line":{"from":486,"to":490}} {"id":100005322,"name":"mergeEnvVars","signature":"func mergeEnvVars(sysEnvVars, credProviderVars []string) []string","file":"pkg/credentialprovider/plugin/plugin.go","code":"// mergedEnvVars overlays system defined env vars with credential provider env vars,\n// it gives priority to the credential provider vars allowing user to override system\n// env vars\nfunc mergeEnvVars(sysEnvVars, credProviderVars []string) []string {\n\tmergedEnvVars := sysEnvVars\n\tfor _, credProviderVar := range credProviderVars {\n\t\tmergedEnvVars = append(mergedEnvVars, credProviderVar)\n\t}\n\treturn mergedEnvVars\n}","line":{"from":492,"to":501}} {"id":100005323,"name":"RegisterCredentialProvider","signature":"func RegisterCredentialProvider(name string, provider DockerConfigProvider)","file":"pkg/credentialprovider/plugins.go","code":"// RegisterCredentialProvider is called by provider implementations on\n// initialization to register themselves, like so:\n//\n//\tfunc init() {\n//\t \tRegisterCredentialProvider(\"name\", \u0026myProvider{...})\n//\t}\nfunc RegisterCredentialProvider(name string, provider DockerConfigProvider) {\n\tprovidersMutex.Lock()\n\tdefer providersMutex.Unlock()\n\t_, found := providers[name]\n\tif found {\n\t\tklog.Fatalf(\"Credential provider %q was registered twice\", name)\n\t}\n\tklog.V(4).Infof(\"Registered credential provider %q\", name)\n\tproviders[name] = provider\n}","line":{"from":33,"to":48}} {"id":100005324,"name":"AreLegacyCloudCredentialProvidersDisabled","signature":"func AreLegacyCloudCredentialProvidersDisabled() bool","file":"pkg/credentialprovider/plugins.go","code":"// AreLegacyCloudCredentialProvidersDisabled checks if the legacy in-tree cloud\n// credential providers have been disabled.\nfunc AreLegacyCloudCredentialProvidersDisabled() bool {\n\treturn utilfeature.DefaultFeatureGate.Enabled(features.DisableKubeletCloudCredentialProviders)\n}","line":{"from":50,"to":54}} {"id":100005325,"name":"NewDockerKeyring","signature":"func NewDockerKeyring() DockerKeyring","file":"pkg/credentialprovider/plugins.go","code":"// NewDockerKeyring creates a DockerKeyring to use for resolving credentials,\n// which draws from the set of registered credential providers.\nfunc NewDockerKeyring() DockerKeyring {\n\tkeyring := \u0026providersDockerKeyring{\n\t\tProviders: make([]DockerConfigProvider, 0),\n\t}\n\n\tkeys := reflect.ValueOf(providers).MapKeys()\n\tstringKeys := make([]string, len(keys))\n\tfor ix := range keys {\n\t\tstringKeys[ix] = keys[ix].String()\n\t}\n\tsort.Strings(stringKeys)\n\n\tfor _, key := range stringKeys {\n\t\tprovider := providers[key]\n\t\tif provider.Enabled() {\n\t\t\tklog.V(4).Infof(\"Registering credential provider: %v\", key)\n\t\t\tkeyring.Providers = append(keyring.Providers, provider)\n\t\t}\n\t}\n\n\treturn keyring\n}","line":{"from":56,"to":79}} {"id":100005326,"name":"init","signature":"func init()","file":"pkg/credentialprovider/provider.go","code":"// init registers our default provider, which simply reads the .dockercfg file.\nfunc init() {\n\tRegisterCredentialProvider(\".dockercfg\",\n\t\t\u0026CachingDockerConfigProvider{\n\t\t\tProvider: \u0026defaultDockerConfigProvider{},\n\t\t\tLifetime: 5 * time.Minute,\n\t\t})\n}","line":{"from":45,"to":52}} {"id":100005327,"name":"Enabled","signature":"func (d *defaultDockerConfigProvider) Enabled() bool","file":"pkg/credentialprovider/provider.go","code":"// Enabled implements dockerConfigProvider\nfunc (d *defaultDockerConfigProvider) Enabled() bool {\n\treturn true\n}","line":{"from":71,"to":74}} {"id":100005328,"name":"Provide","signature":"func (d *defaultDockerConfigProvider) Provide(image string) DockerConfig","file":"pkg/credentialprovider/provider.go","code":"// Provide implements dockerConfigProvider\nfunc (d *defaultDockerConfigProvider) Provide(image string) DockerConfig {\n\t// Read the standard Docker credentials from .dockercfg\n\tif cfg, err := ReadDockerConfigFile(); err == nil {\n\t\treturn cfg\n\t} else if !os.IsNotExist(err) {\n\t\tklog.V(2).Infof(\"Docker config file not found: %v\", err)\n\t}\n\treturn DockerConfig{}\n}","line":{"from":76,"to":85}} {"id":100005329,"name":"Enabled","signature":"func (d *CachingDockerConfigProvider) Enabled() bool","file":"pkg/credentialprovider/provider.go","code":"// Enabled implements dockerConfigProvider\nfunc (d *CachingDockerConfigProvider) Enabled() bool {\n\treturn d.Provider.Enabled()\n}","line":{"from":87,"to":90}} {"id":100005330,"name":"Provide","signature":"func (d *CachingDockerConfigProvider) Provide(image string) DockerConfig","file":"pkg/credentialprovider/provider.go","code":"// Provide implements dockerConfigProvider\nfunc (d *CachingDockerConfigProvider) Provide(image string) DockerConfig {\n\td.mu.Lock()\n\tdefer d.mu.Unlock()\n\n\t// If the cache hasn't expired, return our cache\n\tif time.Now().Before(d.expiration) {\n\t\treturn d.cacheDockerConfig\n\t}\n\n\tklog.V(2).Infof(\"Refreshing cache for provider: %v\", reflect.TypeOf(d.Provider).String())\n\tconfig := d.Provider.Provide(image)\n\tif d.ShouldCache == nil || d.ShouldCache(config) {\n\t\td.cacheDockerConfig = config\n\t\td.expiration = time.Now().Add(d.Lifetime)\n\t}\n\treturn config\n}","line":{"from":92,"to":109}} {"id":100005331,"name":"MakeDockerKeyring","signature":"func MakeDockerKeyring(passedSecrets []v1.Secret, defaultKeyring credentialprovider.DockerKeyring) (credentialprovider.DockerKeyring, error)","file":"pkg/credentialprovider/secrets/secrets.go","code":"// MakeDockerKeyring inspects the passedSecrets to see if they contain any DockerConfig secrets. If they do,\n// then a DockerKeyring is built based on every hit and unioned with the defaultKeyring.\n// If they do not, then the default keyring is returned\nfunc MakeDockerKeyring(passedSecrets []v1.Secret, defaultKeyring credentialprovider.DockerKeyring) (credentialprovider.DockerKeyring, error) {\n\tpassedCredentials := []credentialprovider.DockerConfig{}\n\tfor _, passedSecret := range passedSecrets {\n\t\tif dockerConfigJSONBytes, dockerConfigJSONExists := passedSecret.Data[v1.DockerConfigJsonKey]; (passedSecret.Type == v1.SecretTypeDockerConfigJson) \u0026\u0026 dockerConfigJSONExists \u0026\u0026 (len(dockerConfigJSONBytes) \u003e 0) {\n\t\t\tdockerConfigJSON := credentialprovider.DockerConfigJSON{}\n\t\t\tif err := json.Unmarshal(dockerConfigJSONBytes, \u0026dockerConfigJSON); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tpassedCredentials = append(passedCredentials, dockerConfigJSON.Auths)\n\t\t} else if dockercfgBytes, dockercfgExists := passedSecret.Data[v1.DockerConfigKey]; (passedSecret.Type == v1.SecretTypeDockercfg) \u0026\u0026 dockercfgExists \u0026\u0026 (len(dockercfgBytes) \u003e 0) {\n\t\t\tdockercfg := credentialprovider.DockerConfig{}\n\t\t\tif err := json.Unmarshal(dockercfgBytes, \u0026dockercfg); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tpassedCredentials = append(passedCredentials, dockercfg)\n\t\t}\n\t}\n\n\tif len(passedCredentials) \u003e 0 {\n\t\tbasicKeyring := \u0026credentialprovider.BasicDockerKeyring{}\n\t\tfor _, currCredentials := range passedCredentials {\n\t\t\tbasicKeyring.Add(currCredentials)\n\t\t}\n\t\treturn credentialprovider.UnionDockerKeyring{basicKeyring, defaultKeyring}, nil\n\t}\n\n\treturn defaultKeyring, nil\n}","line":{"from":26,"to":58}} {"id":100005332,"name":"init","signature":"func init()","file":"pkg/features/kube_features.go","code":"func init() {\n\truntime.Must(utilfeature.DefaultMutableFeatureGate.Add(defaultKubernetesFeatureGates))\n}","line":{"from":922,"to":924}} {"id":100005333,"name":"FormatMap","signature":"func FormatMap(m map[string]string) (fmtStr string)","file":"pkg/fieldpath/fieldpath.go","code":"// FormatMap formats map[string]string to a string.\nfunc FormatMap(m map[string]string) (fmtStr string) {\n\t// output with keys in sorted order to provide stable output\n\tkeys := make([]string, 0, len(m))\n\tvar grow int\n\tfor k, v := range m {\n\t\tkeys = append(keys, k)\n\t\t// why add 4: (for =, \\n, \" and \")\n\t\tgrow += len(k) + len(v) + 4\n\t}\n\tsort.Strings(keys)\n\t// allocate space to avoid expansion\n\tdst := make([]byte, 0, grow)\n\tfor _, key := range keys {\n\t\tif len(dst) \u003e 0 {\n\t\t\tdst = append(dst, '\\n')\n\t\t}\n\t\tdst = append(dst, key...)\n\t\tdst = append(dst, '=')\n\t\tdst = strconv.AppendQuote(dst, m[key])\n\t}\n\treturn string(dst)\n}","line":{"from":29,"to":51}} {"id":100005334,"name":"ExtractFieldPathAsString","signature":"func ExtractFieldPathAsString(obj interface{}, fieldPath string) (string, error)","file":"pkg/fieldpath/fieldpath.go","code":"// ExtractFieldPathAsString extracts the field from the given object\n// and returns it as a string. The object must be a pointer to an\n// API type.\nfunc ExtractFieldPathAsString(obj interface{}, fieldPath string) (string, error) {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif path, subscript, ok := SplitMaybeSubscriptedPath(fieldPath); ok {\n\t\tswitch path {\n\t\tcase \"metadata.annotations\":\n\t\t\tif errs := validation.IsQualifiedName(strings.ToLower(subscript)); len(errs) != 0 {\n\t\t\t\treturn \"\", fmt.Errorf(\"invalid key subscript in %s: %s\", fieldPath, strings.Join(errs, \";\"))\n\t\t\t}\n\t\t\treturn accessor.GetAnnotations()[subscript], nil\n\t\tcase \"metadata.labels\":\n\t\t\tif errs := validation.IsQualifiedName(subscript); len(errs) != 0 {\n\t\t\t\treturn \"\", fmt.Errorf(\"invalid key subscript in %s: %s\", fieldPath, strings.Join(errs, \";\"))\n\t\t\t}\n\t\t\treturn accessor.GetLabels()[subscript], nil\n\t\tdefault:\n\t\t\treturn \"\", fmt.Errorf(\"fieldPath %q does not support subscript\", fieldPath)\n\t\t}\n\t}\n\n\tswitch fieldPath {\n\tcase \"metadata.annotations\":\n\t\treturn FormatMap(accessor.GetAnnotations()), nil\n\tcase \"metadata.labels\":\n\t\treturn FormatMap(accessor.GetLabels()), nil\n\tcase \"metadata.name\":\n\t\treturn accessor.GetName(), nil\n\tcase \"metadata.namespace\":\n\t\treturn accessor.GetNamespace(), nil\n\tcase \"metadata.uid\":\n\t\treturn string(accessor.GetUID()), nil\n\t}\n\n\treturn \"\", fmt.Errorf(\"unsupported fieldPath: %v\", fieldPath)\n}","line":{"from":53,"to":93}} {"id":100005335,"name":"SplitMaybeSubscriptedPath","signature":"func SplitMaybeSubscriptedPath(fieldPath string) (string, string, bool)","file":"pkg/fieldpath/fieldpath.go","code":"// SplitMaybeSubscriptedPath checks whether the specified fieldPath is\n// subscripted, and\n// - if yes, this function splits the fieldPath into path and subscript, and\n// returns (path, subscript, true).\n// - if no, this function returns (fieldPath, \"\", false).\n//\n// Example inputs and outputs:\n//\n//\t\"metadata.annotations['myKey']\" --\u003e (\"metadata.annotations\", \"myKey\", true)\n//\t\"metadata.annotations['a[b]c']\" --\u003e (\"metadata.annotations\", \"a[b]c\", true)\n//\t\"metadata.labels['']\" --\u003e (\"metadata.labels\", \"\", true)\n//\t\"metadata.labels\" --\u003e (\"metadata.labels\", \"\", false)\nfunc SplitMaybeSubscriptedPath(fieldPath string) (string, string, bool) {\n\tif !strings.HasSuffix(fieldPath, \"']\") {\n\t\treturn fieldPath, \"\", false\n\t}\n\ts := strings.TrimSuffix(fieldPath, \"']\")\n\tparts := strings.SplitN(s, \"['\", 2)\n\tif len(parts) \u003c 2 {\n\t\treturn fieldPath, \"\", false\n\t}\n\tif len(parts[0]) == 0 {\n\t\treturn fieldPath, \"\", false\n\t}\n\treturn parts[0], parts[1], true\n}","line":{"from":95,"to":120}} {"id":100005336,"name":"New","signature":"func (c *Config) New(proxyTransport *http.Transport, egressSelector *egressselector.EgressSelector, serviceResolver webhook.ServiceResolver, tp trace.TracerProvider, schemaResolver resolver.SchemaResolver) ([]admission.PluginInitializer, genericapiserver.PostStartHookFunc, error)","file":"pkg/kubeapiserver/admission/config.go","code":"// New sets up the plugins and admission start hooks needed for admission\nfunc (c *Config) New(proxyTransport *http.Transport, egressSelector *egressselector.EgressSelector, serviceResolver webhook.ServiceResolver, tp trace.TracerProvider, schemaResolver resolver.SchemaResolver) ([]admission.PluginInitializer, genericapiserver.PostStartHookFunc, error) {\n\twebhookAuthResolverWrapper := webhook.NewDefaultAuthenticationInfoResolverWrapper(proxyTransport, egressSelector, c.LoopbackClientConfig, tp)\n\twebhookPluginInitializer := webhookinit.NewPluginInitializer(webhookAuthResolverWrapper, serviceResolver)\n\n\tvar cloudConfig []byte\n\tif c.CloudConfigFile != \"\" {\n\t\tvar err error\n\t\tcloudConfig, err = ioutil.ReadFile(c.CloudConfigFile)\n\t\tif err != nil {\n\t\t\tklog.Fatalf(\"Error reading from cloud configuration file %s: %#v\", c.CloudConfigFile, err)\n\t\t}\n\t}\n\tclientset, err := kubernetes.NewForConfig(c.LoopbackClientConfig)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdiscoveryClient := cacheddiscovery.NewMemCacheClient(clientset.Discovery())\n\tdiscoveryRESTMapper := restmapper.NewDeferredDiscoveryRESTMapper(discoveryClient)\n\tkubePluginInitializer := NewPluginInitializer(\n\t\tcloudConfig,\n\t\tdiscoveryRESTMapper,\n\t\tquotainstall.NewQuotaConfigurationForAdmission(),\n\t\tschemaResolver,\n\t)\n\n\tadmissionPostStartHook := func(context genericapiserver.PostStartHookContext) error {\n\t\tdiscoveryRESTMapper.Reset()\n\t\tgo utilwait.Until(discoveryRESTMapper.Reset, 30*time.Second, context.StopCh)\n\t\treturn nil\n\t}\n\n\treturn []admission.PluginInitializer{webhookPluginInitializer, kubePluginInitializer}, admissionPostStartHook, nil\n}","line":{"from":50,"to":83}} {"id":100005337,"name":"NewPluginInitializer","signature":"func NewPluginInitializer(","file":"pkg/kubeapiserver/admission/initializer.go","code":"// NewPluginInitializer constructs new instance of PluginInitializer\n// TODO: switch these parameters to use the builder pattern or just make them\n// all public, this construction method is pointless boilerplate.\nfunc NewPluginInitializer(\n\tcloudConfig []byte,\n\trestMapper meta.RESTMapper,\n\tquotaConfiguration quota.Configuration,\n\tschemaResolver resolver.SchemaResolver,\n) *PluginInitializer {\n\treturn \u0026PluginInitializer{\n\t\tcloudConfig: cloudConfig,\n\t\trestMapper: restMapper,\n\t\tquotaConfiguration: quotaConfiguration,\n\t\tschemaResolver: schemaResolver,\n\t}\n}","line":{"from":44,"to":59}} {"id":100005338,"name":"Initialize","signature":"func (i *PluginInitializer) Initialize(plugin admission.Interface)","file":"pkg/kubeapiserver/admission/initializer.go","code":"// Initialize checks the initialization interfaces implemented by each plugin\n// and provide the appropriate initialization data\nfunc (i *PluginInitializer) Initialize(plugin admission.Interface) {\n\tif wants, ok := plugin.(WantsCloudConfig); ok {\n\t\twants.SetCloudConfig(i.cloudConfig)\n\t}\n\n\tif wants, ok := plugin.(initializer.WantsRESTMapper); ok {\n\t\twants.SetRESTMapper(i.restMapper)\n\t}\n\n\tif wants, ok := plugin.(initializer.WantsQuotaConfiguration); ok {\n\t\twants.SetQuotaConfiguration(i.quotaConfiguration)\n\t}\n\n\tif wants, ok := plugin.(initializer.WantsSchemaResolver); ok {\n\t\twants.SetSchemaResolver(i.schemaResolver)\n\t}\n}","line":{"from":61,"to":79}} {"id":100005339,"name":"New","signature":"func (config Config) New() (authenticator.Request, *spec.SecurityDefinitions, error)","file":"pkg/kubeapiserver/authenticator/config.go","code":"// New returns an authenticator.Request or an error that supports the standard\n// Kubernetes authentication mechanisms.\nfunc (config Config) New() (authenticator.Request, *spec.SecurityDefinitions, error) {\n\tvar authenticators []authenticator.Request\n\tvar tokenAuthenticators []authenticator.Token\n\tsecurityDefinitions := spec.SecurityDefinitions{}\n\n\t// front-proxy, BasicAuth methods, local first, then remote\n\t// Add the front proxy authenticator if requested\n\tif config.RequestHeaderConfig != nil {\n\t\trequestHeaderAuthenticator := headerrequest.NewDynamicVerifyOptionsSecure(\n\t\t\tconfig.RequestHeaderConfig.CAContentProvider.VerifyOptions,\n\t\t\tconfig.RequestHeaderConfig.AllowedClientNames,\n\t\t\tconfig.RequestHeaderConfig.UsernameHeaders,\n\t\t\tconfig.RequestHeaderConfig.GroupHeaders,\n\t\t\tconfig.RequestHeaderConfig.ExtraHeaderPrefixes,\n\t\t)\n\t\tauthenticators = append(authenticators, authenticator.WrapAudienceAgnosticRequest(config.APIAudiences, requestHeaderAuthenticator))\n\t}\n\n\t// X509 methods\n\tif config.ClientCAContentProvider != nil {\n\t\tcertAuth := x509.NewDynamic(config.ClientCAContentProvider.VerifyOptions, x509.CommonNameUserConversion)\n\t\tauthenticators = append(authenticators, certAuth)\n\t}\n\n\t// Bearer token methods, local first, then remote\n\tif len(config.TokenAuthFile) \u003e 0 {\n\t\ttokenAuth, err := newAuthenticatorFromTokenFile(config.TokenAuthFile)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\ttokenAuthenticators = append(tokenAuthenticators, authenticator.WrapAudienceAgnosticToken(config.APIAudiences, tokenAuth))\n\t}\n\tif len(config.ServiceAccountKeyFiles) \u003e 0 {\n\t\tserviceAccountAuth, err := newLegacyServiceAccountAuthenticator(config.ServiceAccountKeyFiles, config.ServiceAccountLookup, config.APIAudiences, config.ServiceAccountTokenGetter, config.SecretsWriter)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\ttokenAuthenticators = append(tokenAuthenticators, serviceAccountAuth)\n\t}\n\tif len(config.ServiceAccountIssuers) \u003e 0 {\n\t\tserviceAccountAuth, err := newServiceAccountAuthenticator(config.ServiceAccountIssuers, config.ServiceAccountKeyFiles, config.APIAudiences, config.ServiceAccountTokenGetter)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\ttokenAuthenticators = append(tokenAuthenticators, serviceAccountAuth)\n\t}\n\tif config.BootstrapToken {\n\t\tif config.BootstrapTokenAuthenticator != nil {\n\t\t\t// TODO: This can sometimes be nil because of\n\t\t\ttokenAuthenticators = append(tokenAuthenticators, authenticator.WrapAudienceAgnosticToken(config.APIAudiences, config.BootstrapTokenAuthenticator))\n\t\t}\n\t}\n\t// NOTE(ericchiang): Keep the OpenID Connect after Service Accounts.\n\t//\n\t// Because both plugins verify JWTs whichever comes first in the union experiences\n\t// cache misses for all requests using the other. While the service account plugin\n\t// simply returns an error, the OpenID Connect plugin may query the provider to\n\t// update the keys, causing performance hits.\n\tif len(config.OIDCIssuerURL) \u003e 0 \u0026\u0026 len(config.OIDCClientID) \u003e 0 {\n\t\t// TODO(enj): wire up the Notifier and ControllerRunner bits when OIDC supports CA reload\n\t\tvar oidcCAContent oidc.CAContentProvider\n\t\tif len(config.OIDCCAFile) != 0 {\n\t\t\tvar oidcCAErr error\n\t\t\toidcCAContent, oidcCAErr = staticCAContentProviderFromFile(\"oidc-authenticator\", config.OIDCCAFile)\n\t\t\tif oidcCAErr != nil {\n\t\t\t\treturn nil, nil, oidcCAErr\n\t\t\t}\n\t\t}\n\n\t\toidcAuth, err := newAuthenticatorFromOIDCIssuerURL(oidc.Options{\n\t\t\tIssuerURL: config.OIDCIssuerURL,\n\t\t\tClientID: config.OIDCClientID,\n\t\t\tCAContentProvider: oidcCAContent,\n\t\t\tUsernameClaim: config.OIDCUsernameClaim,\n\t\t\tUsernamePrefix: config.OIDCUsernamePrefix,\n\t\t\tGroupsClaim: config.OIDCGroupsClaim,\n\t\t\tGroupsPrefix: config.OIDCGroupsPrefix,\n\t\t\tSupportedSigningAlgs: config.OIDCSigningAlgs,\n\t\t\tRequiredClaims: config.OIDCRequiredClaims,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\ttokenAuthenticators = append(tokenAuthenticators, authenticator.WrapAudienceAgnosticToken(config.APIAudiences, oidcAuth))\n\t}\n\tif len(config.WebhookTokenAuthnConfigFile) \u003e 0 {\n\t\twebhookTokenAuth, err := newWebhookTokenAuthenticator(config)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\ttokenAuthenticators = append(tokenAuthenticators, webhookTokenAuth)\n\t}\n\n\tif len(tokenAuthenticators) \u003e 0 {\n\t\t// Union the token authenticators\n\t\ttokenAuth := tokenunion.New(tokenAuthenticators...)\n\t\t// Optionally cache authentication results\n\t\tif config.TokenSuccessCacheTTL \u003e 0 || config.TokenFailureCacheTTL \u003e 0 {\n\t\t\ttokenAuth = tokencache.New(tokenAuth, true, config.TokenSuccessCacheTTL, config.TokenFailureCacheTTL)\n\t\t}\n\t\tauthenticators = append(authenticators, bearertoken.New(tokenAuth), websocket.NewProtocolAuthenticator(tokenAuth))\n\t\tsecurityDefinitions[\"BearerToken\"] = \u0026spec.SecurityScheme{\n\t\t\tSecuritySchemeProps: spec.SecuritySchemeProps{\n\t\t\t\tType: \"apiKey\",\n\t\t\t\tName: \"authorization\",\n\t\t\t\tIn: \"header\",\n\t\t\t\tDescription: \"Bearer Token authentication\",\n\t\t\t},\n\t\t}\n\t}\n\n\tif len(authenticators) == 0 {\n\t\tif config.Anonymous {\n\t\t\treturn anonymous.NewAuthenticator(), \u0026securityDefinitions, nil\n\t\t}\n\t\treturn nil, \u0026securityDefinitions, nil\n\t}\n\n\tauthenticator := union.New(authenticators...)\n\n\tauthenticator = group.NewAuthenticatedGroupAdder(authenticator)\n\n\tif config.Anonymous {\n\t\t// If the authenticator chain returns an error, return an error (don't consider a bad bearer token\n\t\t// or invalid username/password combination anonymous).\n\t\tauthenticator = union.NewFailOnError(authenticator, anonymous.NewAuthenticator())\n\t}\n\n\treturn authenticator, \u0026securityDefinitions, nil\n}","line":{"from":97,"to":229}} {"id":100005340,"name":"IsValidServiceAccountKeyFile","signature":"func IsValidServiceAccountKeyFile(file string) bool","file":"pkg/kubeapiserver/authenticator/config.go","code":"// IsValidServiceAccountKeyFile returns true if a valid public RSA key can be read from the given file\nfunc IsValidServiceAccountKeyFile(file string) bool {\n\t_, err := keyutil.PublicKeysFromFile(file)\n\treturn err == nil\n}","line":{"from":231,"to":235}} {"id":100005341,"name":"newAuthenticatorFromTokenFile","signature":"func newAuthenticatorFromTokenFile(tokenAuthFile string) (authenticator.Token, error)","file":"pkg/kubeapiserver/authenticator/config.go","code":"// newAuthenticatorFromTokenFile returns an authenticator.Token or an error\nfunc newAuthenticatorFromTokenFile(tokenAuthFile string) (authenticator.Token, error) {\n\ttokenAuthenticator, err := tokenfile.NewCSV(tokenAuthFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn tokenAuthenticator, nil\n}","line":{"from":237,"to":245}} {"id":100005342,"name":"newAuthenticatorFromOIDCIssuerURL","signature":"func newAuthenticatorFromOIDCIssuerURL(opts oidc.Options) (authenticator.Token, error)","file":"pkg/kubeapiserver/authenticator/config.go","code":"// newAuthenticatorFromOIDCIssuerURL returns an authenticator.Token or an error.\nfunc newAuthenticatorFromOIDCIssuerURL(opts oidc.Options) (authenticator.Token, error) {\n\tconst noUsernamePrefix = \"-\"\n\n\tif opts.UsernamePrefix == \"\" \u0026\u0026 opts.UsernameClaim != \"email\" {\n\t\t// Old behavior. If a usernamePrefix isn't provided, prefix all claims other than \"email\"\n\t\t// with the issuerURL.\n\t\t//\n\t\t// See https://github.com/kubernetes/kubernetes/issues/31380\n\t\topts.UsernamePrefix = opts.IssuerURL + \"#\"\n\t}\n\n\tif opts.UsernamePrefix == noUsernamePrefix {\n\t\t// Special value indicating usernames shouldn't be prefixed.\n\t\topts.UsernamePrefix = \"\"\n\t}\n\n\ttokenAuthenticator, err := oidc.New(opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn tokenAuthenticator, nil\n}","line":{"from":247,"to":270}} {"id":100005343,"name":"newLegacyServiceAccountAuthenticator","signature":"func newLegacyServiceAccountAuthenticator(keyfiles []string, lookup bool, apiAudiences authenticator.Audiences, serviceAccountGetter serviceaccount.ServiceAccountTokenGetter, secretsWriter typedv1core.SecretsGetter) (authenticator.Token, error)","file":"pkg/kubeapiserver/authenticator/config.go","code":"// newLegacyServiceAccountAuthenticator returns an authenticator.Token or an error\nfunc newLegacyServiceAccountAuthenticator(keyfiles []string, lookup bool, apiAudiences authenticator.Audiences, serviceAccountGetter serviceaccount.ServiceAccountTokenGetter, secretsWriter typedv1core.SecretsGetter) (authenticator.Token, error) {\n\tallPublicKeys := []interface{}{}\n\tfor _, keyfile := range keyfiles {\n\t\tpublicKeys, err := keyutil.PublicKeysFromFile(keyfile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tallPublicKeys = append(allPublicKeys, publicKeys...)\n\t}\n\tvalidator, err := serviceaccount.NewLegacyValidator(lookup, serviceAccountGetter, secretsWriter)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"while creating legacy validator, err: %w\", err)\n\t}\n\n\ttokenAuthenticator := serviceaccount.JWTTokenAuthenticator([]string{serviceaccount.LegacyIssuer}, allPublicKeys, apiAudiences, validator)\n\treturn tokenAuthenticator, nil\n}","line":{"from":272,"to":289}} {"id":100005344,"name":"newServiceAccountAuthenticator","signature":"func newServiceAccountAuthenticator(issuers []string, keyfiles []string, apiAudiences authenticator.Audiences, serviceAccountGetter serviceaccount.ServiceAccountTokenGetter) (authenticator.Token, error)","file":"pkg/kubeapiserver/authenticator/config.go","code":"// newServiceAccountAuthenticator returns an authenticator.Token or an error\nfunc newServiceAccountAuthenticator(issuers []string, keyfiles []string, apiAudiences authenticator.Audiences, serviceAccountGetter serviceaccount.ServiceAccountTokenGetter) (authenticator.Token, error) {\n\tallPublicKeys := []interface{}{}\n\tfor _, keyfile := range keyfiles {\n\t\tpublicKeys, err := keyutil.PublicKeysFromFile(keyfile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tallPublicKeys = append(allPublicKeys, publicKeys...)\n\t}\n\n\ttokenAuthenticator := serviceaccount.JWTTokenAuthenticator(issuers, allPublicKeys, apiAudiences, serviceaccount.NewValidator(serviceAccountGetter))\n\treturn tokenAuthenticator, nil\n}","line":{"from":291,"to":304}} {"id":100005345,"name":"newWebhookTokenAuthenticator","signature":"func newWebhookTokenAuthenticator(config Config) (authenticator.Token, error)","file":"pkg/kubeapiserver/authenticator/config.go","code":"func newWebhookTokenAuthenticator(config Config) (authenticator.Token, error) {\n\tif config.WebhookRetryBackoff == nil {\n\t\treturn nil, errors.New(\"retry backoff parameters for authentication webhook has not been specified\")\n\t}\n\n\tclientConfig, err := webhookutil.LoadKubeconfig(config.WebhookTokenAuthnConfigFile, config.CustomDial)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\twebhookTokenAuthenticator, err := webhook.New(clientConfig, config.WebhookTokenAuthnVersion, config.APIAudiences, *config.WebhookRetryBackoff)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn tokencache.New(webhookTokenAuthenticator, false, config.WebhookTokenAuthnCacheTTL, config.WebhookTokenAuthnCacheTTL), nil\n}","line":{"from":306,"to":321}} {"id":100005346,"name":"staticCAContentProviderFromFile","signature":"func staticCAContentProviderFromFile(purpose, filename string) (dynamiccertificates.CAContentProvider, error)","file":"pkg/kubeapiserver/authenticator/config.go","code":"func staticCAContentProviderFromFile(purpose, filename string) (dynamiccertificates.CAContentProvider, error) {\n\tfileBytes, err := os.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn dynamiccertificates.NewStaticCAContent(purpose, fileBytes)\n}","line":{"from":323,"to":330}} {"id":100005347,"name":"New","signature":"func (config Config) New() (authorizer.Authorizer, authorizer.RuleResolver, error)","file":"pkg/kubeapiserver/authorizer/config.go","code":"// New returns the right sort of union of multiple authorizer.Authorizer objects\n// based on the authorizationMode or an error.\nfunc (config Config) New() (authorizer.Authorizer, authorizer.RuleResolver, error) {\n\tif len(config.AuthorizationModes) == 0 {\n\t\treturn nil, nil, fmt.Errorf(\"at least one authorization mode must be passed\")\n\t}\n\n\tvar (\n\t\tauthorizers []authorizer.Authorizer\n\t\truleResolvers []authorizer.RuleResolver\n\t)\n\n\t// Add SystemPrivilegedGroup as an authorizing group\n\tsuperuserAuthorizer := authorizerfactory.NewPrivilegedGroups(user.SystemPrivilegedGroup)\n\tauthorizers = append(authorizers, superuserAuthorizer)\n\n\tfor _, authorizationMode := range config.AuthorizationModes {\n\t\t// Keep cases in sync with constant list in k8s.io/kubernetes/pkg/kubeapiserver/authorizer/modes/modes.go.\n\t\tswitch authorizationMode {\n\t\tcase modes.ModeNode:\n\t\t\tnode.RegisterMetrics()\n\t\t\tgraph := node.NewGraph()\n\t\t\tnode.AddGraphEventHandlers(\n\t\t\t\tgraph,\n\t\t\t\tconfig.VersionedInformerFactory.Core().V1().Nodes(),\n\t\t\t\tconfig.VersionedInformerFactory.Core().V1().Pods(),\n\t\t\t\tconfig.VersionedInformerFactory.Core().V1().PersistentVolumes(),\n\t\t\t\tconfig.VersionedInformerFactory.Storage().V1().VolumeAttachments(),\n\t\t\t)\n\t\t\tnodeAuthorizer := node.NewAuthorizer(graph, nodeidentifier.NewDefaultNodeIdentifier(), bootstrappolicy.NodeRules())\n\t\t\tauthorizers = append(authorizers, nodeAuthorizer)\n\t\t\truleResolvers = append(ruleResolvers, nodeAuthorizer)\n\n\t\tcase modes.ModeAlwaysAllow:\n\t\t\talwaysAllowAuthorizer := authorizerfactory.NewAlwaysAllowAuthorizer()\n\t\t\tauthorizers = append(authorizers, alwaysAllowAuthorizer)\n\t\t\truleResolvers = append(ruleResolvers, alwaysAllowAuthorizer)\n\t\tcase modes.ModeAlwaysDeny:\n\t\t\talwaysDenyAuthorizer := authorizerfactory.NewAlwaysDenyAuthorizer()\n\t\t\tauthorizers = append(authorizers, alwaysDenyAuthorizer)\n\t\t\truleResolvers = append(ruleResolvers, alwaysDenyAuthorizer)\n\t\tcase modes.ModeABAC:\n\t\t\tabacAuthorizer, err := abac.NewFromFile(config.PolicyFile)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\tauthorizers = append(authorizers, abacAuthorizer)\n\t\t\truleResolvers = append(ruleResolvers, abacAuthorizer)\n\t\tcase modes.ModeWebhook:\n\t\t\tif config.WebhookRetryBackoff == nil {\n\t\t\t\treturn nil, nil, errors.New(\"retry backoff parameters for authorization webhook has not been specified\")\n\t\t\t}\n\t\t\tclientConfig, err := webhookutil.LoadKubeconfig(config.WebhookConfigFile, config.CustomDial)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\twebhookAuthorizer, err := webhook.New(clientConfig,\n\t\t\t\tconfig.WebhookVersion,\n\t\t\t\tconfig.WebhookCacheAuthorizedTTL,\n\t\t\t\tconfig.WebhookCacheUnauthorizedTTL,\n\t\t\t\t*config.WebhookRetryBackoff,\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\tauthorizers = append(authorizers, webhookAuthorizer)\n\t\t\truleResolvers = append(ruleResolvers, webhookAuthorizer)\n\t\tcase modes.ModeRBAC:\n\t\t\trbacAuthorizer := rbac.New(\n\t\t\t\t\u0026rbac.RoleGetter{Lister: config.VersionedInformerFactory.Rbac().V1().Roles().Lister()},\n\t\t\t\t\u0026rbac.RoleBindingLister{Lister: config.VersionedInformerFactory.Rbac().V1().RoleBindings().Lister()},\n\t\t\t\t\u0026rbac.ClusterRoleGetter{Lister: config.VersionedInformerFactory.Rbac().V1().ClusterRoles().Lister()},\n\t\t\t\t\u0026rbac.ClusterRoleBindingLister{Lister: config.VersionedInformerFactory.Rbac().V1().ClusterRoleBindings().Lister()},\n\t\t\t)\n\t\t\tauthorizers = append(authorizers, rbacAuthorizer)\n\t\t\truleResolvers = append(ruleResolvers, rbacAuthorizer)\n\t\tdefault:\n\t\t\treturn nil, nil, fmt.Errorf(\"unknown authorization mode %s specified\", authorizationMode)\n\t\t}\n\t}\n\n\treturn union.New(authorizers...), union.NewRuleResolvers(ruleResolvers...), nil\n}","line":{"from":71,"to":153}} {"id":100005348,"name":"IsValidAuthorizationMode","signature":"func IsValidAuthorizationMode(authzMode string) bool","file":"pkg/kubeapiserver/authorizer/modes/modes.go","code":"// IsValidAuthorizationMode returns true if the given authorization mode is a valid one for the apiserver\nfunc IsValidAuthorizationMode(authzMode string) bool {\n\treturn sets.NewString(AuthorizationModeChoices...).Has(authzMode)\n}","line":{"from":39,"to":42}} {"id":100005349,"name":"DefaultWatchCacheSizes","signature":"func DefaultWatchCacheSizes() map[schema.GroupResource]int","file":"pkg/kubeapiserver/default_storage_factory_builder.go","code":"// DefaultWatchCacheSizes defines default resources for which watchcache\n// should be disabled.\nfunc DefaultWatchCacheSizes() map[schema.GroupResource]int {\n\treturn map[schema.GroupResource]int{\n\t\t{Resource: \"events\"}: 0,\n\t\t{Group: \"events.k8s.io\", Resource: \"events\"}: 0,\n\t}\n}","line":{"from":49,"to":56}} {"id":100005350,"name":"NewStorageFactoryConfig","signature":"func NewStorageFactoryConfig() *StorageFactoryConfig","file":"pkg/kubeapiserver/default_storage_factory_builder.go","code":"// NewStorageFactoryConfig returns a new StorageFactoryConfig set up with necessary resource overrides.\nfunc NewStorageFactoryConfig() *StorageFactoryConfig {\n\tresources := []schema.GroupVersionResource{\n\t\t// If a resource has to be stored in a version that is not the\n\t\t// latest, then it can be listed here. Usually this is the case\n\t\t// when a new version for a resource gets introduced and a\n\t\t// downgrade to an older apiserver that doesn't know the new\n\t\t// version still needs to be supported for one release.\n\t\t//\n\t\t// Example from Kubernetes 1.24 where csistoragecapacities had just\n\t\t// graduated to GA:\n\t\t//\n\t\t// TODO (https://github.com/kubernetes/kubernetes/issues/108451): remove the override in 1.25.\n\t\t// apisstorage.Resource(\"csistoragecapacities\").WithVersion(\"v1beta1\"),\n\t\tadmissionregistration.Resource(\"validatingadmissionpolicies\").WithVersion(\"v1alpha1\"),\n\t\tadmissionregistration.Resource(\"validatingadmissionpolicybindings\").WithVersion(\"v1alpha1\"),\n\t\tnetworking.Resource(\"clustercidrs\").WithVersion(\"v1alpha1\"),\n\t\tnetworking.Resource(\"ipaddresses\").WithVersion(\"v1alpha1\"),\n\t\tcertificates.Resource(\"clustertrustbundles\").WithVersion(\"v1alpha1\"),\n\t}\n\n\treturn \u0026StorageFactoryConfig{\n\t\tSerializer: legacyscheme.Codecs,\n\t\tDefaultResourceEncoding: serverstorage.NewDefaultResourceEncodingConfig(legacyscheme.Scheme),\n\t\tResourceEncodingOverrides: resources,\n\t}\n}","line":{"from":58,"to":84}} {"id":100005351,"name":"Complete","signature":"func (c *StorageFactoryConfig) Complete(etcdOptions *serveroptions.EtcdOptions) *completedStorageFactoryConfig","file":"pkg/kubeapiserver/default_storage_factory_builder.go","code":"// Complete completes the StorageFactoryConfig with provided etcdOptions returning completedStorageFactoryConfig.\n// This method mutates the receiver (StorageFactoryConfig). It must never mutate the inputs.\nfunc (c *StorageFactoryConfig) Complete(etcdOptions *serveroptions.EtcdOptions) *completedStorageFactoryConfig {\n\tc.StorageConfig = etcdOptions.StorageConfig\n\tc.DefaultStorageMediaType = etcdOptions.DefaultStorageMediaType\n\tc.EtcdServersOverrides = etcdOptions.EtcdServersOverrides\n\treturn \u0026completedStorageFactoryConfig{c}\n}","line":{"from":97,"to":104}} {"id":100005352,"name":"New","signature":"func (c *completedStorageFactoryConfig) New() (*serverstorage.DefaultStorageFactory, error)","file":"pkg/kubeapiserver/default_storage_factory_builder.go","code":"// New returns a new storage factory created from the completed storage factory configuration.\nfunc (c *completedStorageFactoryConfig) New() (*serverstorage.DefaultStorageFactory, error) {\n\tresourceEncodingConfig := resourceconfig.MergeResourceEncodingConfigs(c.DefaultResourceEncoding, c.ResourceEncodingOverrides)\n\tstorageFactory := serverstorage.NewDefaultStorageFactory(\n\t\tc.StorageConfig,\n\t\tc.DefaultStorageMediaType,\n\t\tc.Serializer,\n\t\tresourceEncodingConfig,\n\t\tc.APIResourceConfig,\n\t\tSpecialDefaultResourcePrefixes)\n\n\tstorageFactory.AddCohabitatingResources(networking.Resource(\"networkpolicies\"), extensions.Resource(\"networkpolicies\"))\n\tstorageFactory.AddCohabitatingResources(apps.Resource(\"deployments\"), extensions.Resource(\"deployments\"))\n\tstorageFactory.AddCohabitatingResources(apps.Resource(\"daemonsets\"), extensions.Resource(\"daemonsets\"))\n\tstorageFactory.AddCohabitatingResources(apps.Resource(\"replicasets\"), extensions.Resource(\"replicasets\"))\n\tstorageFactory.AddCohabitatingResources(api.Resource(\"events\"), events.Resource(\"events\"))\n\tstorageFactory.AddCohabitatingResources(api.Resource(\"replicationcontrollers\"), extensions.Resource(\"replicationcontrollers\")) // to make scale subresources equivalent\n\tstorageFactory.AddCohabitatingResources(policy.Resource(\"podsecuritypolicies\"), extensions.Resource(\"podsecuritypolicies\"))\n\tstorageFactory.AddCohabitatingResources(networking.Resource(\"ingresses\"), extensions.Resource(\"ingresses\"))\n\n\tfor _, override := range c.EtcdServersOverrides {\n\t\ttokens := strings.Split(override, \"#\")\n\t\tapiresource := strings.Split(tokens[0], \"/\")\n\n\t\tgroup := apiresource[0]\n\t\tresource := apiresource[1]\n\t\tgroupResource := schema.GroupResource{Group: group, Resource: resource}\n\n\t\tservers := strings.Split(tokens[1], \";\")\n\t\tstorageFactory.SetEtcdLocation(groupResource, servers)\n\t}\n\treturn storageFactory, nil\n}","line":{"from":114,"to":146}} {"id":100005353,"name":"NewAdmissionOptions","signature":"func NewAdmissionOptions() *AdmissionOptions","file":"pkg/kubeapiserver/options/admission.go","code":"// NewAdmissionOptions creates a new instance of AdmissionOptions\n// Note:\n//\n//\tIn addition it calls RegisterAllAdmissionPlugins to register\n//\tall kube-apiserver admission plugins.\n//\n//\tProvides the list of RecommendedPluginOrder that holds sane values\n//\tthat can be used by servers that don't care about admission chain.\n//\tServers that do care can overwrite/append that field after creation.\nfunc NewAdmissionOptions() *AdmissionOptions {\n\toptions := genericoptions.NewAdmissionOptions()\n\t// register all admission plugins\n\tRegisterAllAdmissionPlugins(options.Plugins)\n\t// set RecommendedPluginOrder\n\toptions.RecommendedPluginOrder = AllOrderedPlugins\n\t// set DefaultOffPlugins\n\toptions.DefaultOffPlugins = DefaultOffAdmissionPlugins()\n\n\treturn \u0026AdmissionOptions{\n\t\tGenericAdmission: options,\n\t}\n}","line":{"from":44,"to":65}} {"id":100005354,"name":"AddFlags","signature":"func (a *AdmissionOptions) AddFlags(fs *pflag.FlagSet)","file":"pkg/kubeapiserver/options/admission.go","code":"// AddFlags adds flags related to admission for kube-apiserver to the specified FlagSet\nfunc (a *AdmissionOptions) AddFlags(fs *pflag.FlagSet) {\n\tfs.StringSliceVar(\u0026a.PluginNames, \"admission-control\", a.PluginNames, \"\"+\n\t\t\"Admission is divided into two phases. \"+\n\t\t\"In the first phase, only mutating admission plugins run. \"+\n\t\t\"In the second phase, only validating admission plugins run. \"+\n\t\t\"The names in the below list may represent a validating plugin, a mutating plugin, or both. \"+\n\t\t\"The order of plugins in which they are passed to this flag does not matter. \"+\n\t\t\"Comma-delimited list of: \"+strings.Join(a.GenericAdmission.Plugins.Registered(), \", \")+\".\")\n\tfs.MarkDeprecated(\"admission-control\", \"Use --enable-admission-plugins or --disable-admission-plugins instead. Will be removed in a future version.\")\n\tfs.Lookup(\"admission-control\").Hidden = false\n\n\ta.GenericAdmission.AddFlags(fs)\n}","line":{"from":67,"to":80}} {"id":100005355,"name":"Validate","signature":"func (a *AdmissionOptions) Validate() []error","file":"pkg/kubeapiserver/options/admission.go","code":"// Validate verifies flags passed to kube-apiserver AdmissionOptions.\n// Kube-apiserver verifies PluginNames and then call generic AdmissionOptions.Validate.\nfunc (a *AdmissionOptions) Validate() []error {\n\tif a == nil {\n\t\treturn nil\n\t}\n\tvar errs []error\n\tif a.PluginNames != nil \u0026\u0026\n\t\t(a.GenericAdmission.EnablePlugins != nil || a.GenericAdmission.DisablePlugins != nil) {\n\t\terrs = append(errs, fmt.Errorf(\"admission-control and enable-admission-plugins/disable-admission-plugins flags are mutually exclusive\"))\n\t}\n\n\tregisteredPlugins := sets.NewString(a.GenericAdmission.Plugins.Registered()...)\n\tfor _, name := range a.PluginNames {\n\t\tif !registeredPlugins.Has(name) {\n\t\t\terrs = append(errs, fmt.Errorf(\"admission-control plugin %q is unknown\", name))\n\t\t}\n\t}\n\n\terrs = append(errs, a.GenericAdmission.Validate()...)\n\n\treturn errs\n}","line":{"from":82,"to":104}} {"id":100005356,"name":"ApplyTo","signature":"func (a *AdmissionOptions) ApplyTo(","file":"pkg/kubeapiserver/options/admission.go","code":"// ApplyTo adds the admission chain to the server configuration.\n// Kube-apiserver just call generic AdmissionOptions.ApplyTo.\nfunc (a *AdmissionOptions) ApplyTo(\n\tc *server.Config,\n\tinformers informers.SharedInformerFactory,\n\tkubeAPIServerClientConfig *rest.Config,\n\tfeatures featuregate.FeatureGate,\n\tpluginInitializers ...admission.PluginInitializer,\n) error {\n\tif a == nil {\n\t\treturn nil\n\t}\n\n\tif a.PluginNames != nil {\n\t\t// pass PluginNames to generic AdmissionOptions\n\t\ta.GenericAdmission.EnablePlugins, a.GenericAdmission.DisablePlugins = computePluginNames(a.PluginNames, a.GenericAdmission.RecommendedPluginOrder)\n\t}\n\n\treturn a.GenericAdmission.ApplyTo(c, informers, kubeAPIServerClientConfig, features, pluginInitializers...)\n}","line":{"from":106,"to":125}} {"id":100005357,"name":"computePluginNames","signature":"func computePluginNames(explicitlyEnabled []string, all []string) (enabled []string, disabled []string)","file":"pkg/kubeapiserver/options/admission.go","code":"// explicitly disable all plugins that are not in the enabled list\nfunc computePluginNames(explicitlyEnabled []string, all []string) (enabled []string, disabled []string) {\n\treturn explicitlyEnabled, sets.NewString(all...).Difference(sets.NewString(explicitlyEnabled...)).List()\n}","line":{"from":127,"to":130}} {"id":100005358,"name":"NewBuiltInAuthenticationOptions","signature":"func NewBuiltInAuthenticationOptions() *BuiltInAuthenticationOptions","file":"pkg/kubeapiserver/options/authentication.go","code":"// NewBuiltInAuthenticationOptions create a new BuiltInAuthenticationOptions, just set default token cache TTL\nfunc NewBuiltInAuthenticationOptions() *BuiltInAuthenticationOptions {\n\treturn \u0026BuiltInAuthenticationOptions{\n\t\tTokenSuccessCacheTTL: 10 * time.Second,\n\t\tTokenFailureCacheTTL: 0 * time.Second,\n\t}\n}","line":{"from":112,"to":118}} {"id":100005359,"name":"WithAll","signature":"func (o *BuiltInAuthenticationOptions) WithAll() *BuiltInAuthenticationOptions","file":"pkg/kubeapiserver/options/authentication.go","code":"// WithAll set default value for every build-in authentication option\nfunc (o *BuiltInAuthenticationOptions) WithAll() *BuiltInAuthenticationOptions {\n\treturn o.\n\t\tWithAnonymous().\n\t\tWithBootstrapToken().\n\t\tWithClientCert().\n\t\tWithOIDC().\n\t\tWithRequestHeader().\n\t\tWithServiceAccounts().\n\t\tWithTokenFile().\n\t\tWithWebHook()\n}","line":{"from":120,"to":131}} {"id":100005360,"name":"WithAnonymous","signature":"func (o *BuiltInAuthenticationOptions) WithAnonymous() *BuiltInAuthenticationOptions","file":"pkg/kubeapiserver/options/authentication.go","code":"// WithAnonymous set default value for anonymous authentication\nfunc (o *BuiltInAuthenticationOptions) WithAnonymous() *BuiltInAuthenticationOptions {\n\to.Anonymous = \u0026AnonymousAuthenticationOptions{Allow: true}\n\treturn o\n}","line":{"from":133,"to":137}} {"id":100005361,"name":"WithBootstrapToken","signature":"func (o *BuiltInAuthenticationOptions) WithBootstrapToken() *BuiltInAuthenticationOptions","file":"pkg/kubeapiserver/options/authentication.go","code":"// WithBootstrapToken set default value for bootstrap token authentication\nfunc (o *BuiltInAuthenticationOptions) WithBootstrapToken() *BuiltInAuthenticationOptions {\n\to.BootstrapToken = \u0026BootstrapTokenAuthenticationOptions{}\n\treturn o\n}","line":{"from":139,"to":143}} {"id":100005362,"name":"WithClientCert","signature":"func (o *BuiltInAuthenticationOptions) WithClientCert() *BuiltInAuthenticationOptions","file":"pkg/kubeapiserver/options/authentication.go","code":"// WithClientCert set default value for client cert\nfunc (o *BuiltInAuthenticationOptions) WithClientCert() *BuiltInAuthenticationOptions {\n\to.ClientCert = \u0026genericoptions.ClientCertAuthenticationOptions{}\n\treturn o\n}","line":{"from":145,"to":149}} {"id":100005363,"name":"WithOIDC","signature":"func (o *BuiltInAuthenticationOptions) WithOIDC() *BuiltInAuthenticationOptions","file":"pkg/kubeapiserver/options/authentication.go","code":"// WithOIDC set default value for OIDC authentication\nfunc (o *BuiltInAuthenticationOptions) WithOIDC() *BuiltInAuthenticationOptions {\n\to.OIDC = \u0026OIDCAuthenticationOptions{}\n\treturn o\n}","line":{"from":151,"to":155}} {"id":100005364,"name":"WithRequestHeader","signature":"func (o *BuiltInAuthenticationOptions) WithRequestHeader() *BuiltInAuthenticationOptions","file":"pkg/kubeapiserver/options/authentication.go","code":"// WithRequestHeader set default value for request header authentication\nfunc (o *BuiltInAuthenticationOptions) WithRequestHeader() *BuiltInAuthenticationOptions {\n\to.RequestHeader = \u0026genericoptions.RequestHeaderAuthenticationOptions{}\n\treturn o\n}","line":{"from":157,"to":161}} {"id":100005365,"name":"WithServiceAccounts","signature":"func (o *BuiltInAuthenticationOptions) WithServiceAccounts() *BuiltInAuthenticationOptions","file":"pkg/kubeapiserver/options/authentication.go","code":"// WithServiceAccounts set default value for service account authentication\nfunc (o *BuiltInAuthenticationOptions) WithServiceAccounts() *BuiltInAuthenticationOptions {\n\to.ServiceAccounts = \u0026ServiceAccountAuthenticationOptions{Lookup: true, ExtendExpiration: true}\n\treturn o\n}","line":{"from":163,"to":167}} {"id":100005366,"name":"WithTokenFile","signature":"func (o *BuiltInAuthenticationOptions) WithTokenFile() *BuiltInAuthenticationOptions","file":"pkg/kubeapiserver/options/authentication.go","code":"// WithTokenFile set default value for token file authentication\nfunc (o *BuiltInAuthenticationOptions) WithTokenFile() *BuiltInAuthenticationOptions {\n\to.TokenFile = \u0026TokenFileAuthenticationOptions{}\n\treturn o\n}","line":{"from":169,"to":173}} {"id":100005367,"name":"WithWebHook","signature":"func (o *BuiltInAuthenticationOptions) WithWebHook() *BuiltInAuthenticationOptions","file":"pkg/kubeapiserver/options/authentication.go","code":"// WithWebHook set default value for web hook authentication\nfunc (o *BuiltInAuthenticationOptions) WithWebHook() *BuiltInAuthenticationOptions {\n\to.WebHook = \u0026WebHookAuthenticationOptions{\n\t\tVersion: \"v1beta1\",\n\t\tCacheTTL: 2 * time.Minute,\n\t\tRetryBackoff: genericoptions.DefaultAuthWebhookRetryBackoff(),\n\t}\n\treturn o\n}","line":{"from":175,"to":183}} {"id":100005368,"name":"Validate","signature":"func (o *BuiltInAuthenticationOptions) Validate() []error","file":"pkg/kubeapiserver/options/authentication.go","code":"// Validate checks invalid config combination\nfunc (o *BuiltInAuthenticationOptions) Validate() []error {\n\tvar allErrors []error\n\n\tif o.OIDC != nil \u0026\u0026 (len(o.OIDC.IssuerURL) \u003e 0) != (len(o.OIDC.ClientID) \u003e 0) {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"oidc-issuer-url and oidc-client-id should be specified together\"))\n\t}\n\n\tif o.ServiceAccounts != nil \u0026\u0026 len(o.ServiceAccounts.Issuers) \u003e 0 {\n\t\tseen := make(map[string]bool)\n\t\tfor _, issuer := range o.ServiceAccounts.Issuers {\n\t\t\tif strings.Contains(issuer, \":\") {\n\t\t\t\tif _, err := url.Parse(issuer); err != nil {\n\t\t\t\t\tallErrors = append(allErrors, fmt.Errorf(\"service-account-issuer %q contained a ':' but was not a valid URL: %v\", issuer, err))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tif issuer == \"\" {\n\t\t\t\tallErrors = append(allErrors, fmt.Errorf(\"service-account-issuer should not be an empty string\"))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif seen[issuer] {\n\t\t\t\tallErrors = append(allErrors, fmt.Errorf(\"service-account-issuer %q is already specified\", issuer))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tseen[issuer] = true\n\t\t}\n\t}\n\n\tif o.ServiceAccounts != nil {\n\t\tif len(o.ServiceAccounts.Issuers) == 0 {\n\t\t\tallErrors = append(allErrors, errors.New(\"service-account-issuer is a required flag\"))\n\t\t}\n\t\tif len(o.ServiceAccounts.KeyFiles) == 0 {\n\t\t\tallErrors = append(allErrors, errors.New(\"service-account-key-file is a required flag\"))\n\t\t}\n\n\t\t// Validate the JWKS URI when it is explicitly set.\n\t\t// When unset, it is later derived from ExternalHost.\n\t\tif o.ServiceAccounts.JWKSURI != \"\" {\n\t\t\tif u, err := url.Parse(o.ServiceAccounts.JWKSURI); err != nil {\n\t\t\t\tallErrors = append(allErrors, fmt.Errorf(\"service-account-jwks-uri must be a valid URL: %v\", err))\n\t\t\t} else if u.Scheme != \"https\" {\n\t\t\t\tallErrors = append(allErrors, fmt.Errorf(\"service-account-jwks-uri requires https scheme, parsed as: %v\", u.String()))\n\t\t\t}\n\t\t}\n\t}\n\n\tif o.WebHook != nil {\n\t\tretryBackoff := o.WebHook.RetryBackoff\n\t\tif retryBackoff != nil \u0026\u0026 retryBackoff.Steps \u003c= 0 {\n\t\t\tallErrors = append(allErrors, fmt.Errorf(\"number of webhook retry attempts must be greater than 0, but is: %d\", retryBackoff.Steps))\n\t\t}\n\t}\n\n\tif o.RequestHeader != nil {\n\t\tallErrors = append(allErrors, o.RequestHeader.Validate()...)\n\t}\n\n\treturn allErrors\n}","line":{"from":185,"to":245}} {"id":100005369,"name":"AddFlags","signature":"func (o *BuiltInAuthenticationOptions) AddFlags(fs *pflag.FlagSet)","file":"pkg/kubeapiserver/options/authentication.go","code":"// AddFlags returns flags of authentication for a API Server\nfunc (o *BuiltInAuthenticationOptions) AddFlags(fs *pflag.FlagSet) {\n\tfs.StringSliceVar(\u0026o.APIAudiences, \"api-audiences\", o.APIAudiences, \"\"+\n\t\t\"Identifiers of the API. The service account token authenticator will validate that \"+\n\t\t\"tokens used against the API are bound to at least one of these audiences. If the \"+\n\t\t\"--service-account-issuer flag is configured and this flag is not, this field \"+\n\t\t\"defaults to a single element list containing the issuer URL.\")\n\n\tif o.Anonymous != nil {\n\t\tfs.BoolVar(\u0026o.Anonymous.Allow, \"anonymous-auth\", o.Anonymous.Allow, \"\"+\n\t\t\t\"Enables anonymous requests to the secure port of the API server. \"+\n\t\t\t\"Requests that are not rejected by another authentication method are treated as anonymous requests. \"+\n\t\t\t\"Anonymous requests have a username of system:anonymous, and a group name of system:unauthenticated.\")\n\t}\n\n\tif o.BootstrapToken != nil {\n\t\tfs.BoolVar(\u0026o.BootstrapToken.Enable, \"enable-bootstrap-token-auth\", o.BootstrapToken.Enable, \"\"+\n\t\t\t\"Enable to allow secrets of type 'bootstrap.kubernetes.io/token' in the 'kube-system' \"+\n\t\t\t\"namespace to be used for TLS bootstrapping authentication.\")\n\t}\n\n\tif o.ClientCert != nil {\n\t\to.ClientCert.AddFlags(fs)\n\t}\n\n\tif o.OIDC != nil {\n\t\tfs.StringVar(\u0026o.OIDC.IssuerURL, \"oidc-issuer-url\", o.OIDC.IssuerURL, \"\"+\n\t\t\t\"The URL of the OpenID issuer, only HTTPS scheme will be accepted. \"+\n\t\t\t\"If set, it will be used to verify the OIDC JSON Web Token (JWT).\")\n\n\t\tfs.StringVar(\u0026o.OIDC.ClientID, \"oidc-client-id\", o.OIDC.ClientID,\n\t\t\t\"The client ID for the OpenID Connect client, must be set if oidc-issuer-url is set.\")\n\n\t\tfs.StringVar(\u0026o.OIDC.CAFile, \"oidc-ca-file\", o.OIDC.CAFile, \"\"+\n\t\t\t\"If set, the OpenID server's certificate will be verified by one of the authorities \"+\n\t\t\t\"in the oidc-ca-file, otherwise the host's root CA set will be used.\")\n\n\t\tfs.StringVar(\u0026o.OIDC.UsernameClaim, \"oidc-username-claim\", \"sub\", \"\"+\n\t\t\t\"The OpenID claim to use as the user name. Note that claims other than the default ('sub') \"+\n\t\t\t\"is not guaranteed to be unique and immutable. This flag is experimental, please see \"+\n\t\t\t\"the authentication documentation for further details.\")\n\n\t\tfs.StringVar(\u0026o.OIDC.UsernamePrefix, \"oidc-username-prefix\", \"\", \"\"+\n\t\t\t\"If provided, all usernames will be prefixed with this value. If not provided, \"+\n\t\t\t\"username claims other than 'email' are prefixed by the issuer URL to avoid \"+\n\t\t\t\"clashes. To skip any prefixing, provide the value '-'.\")\n\n\t\tfs.StringVar(\u0026o.OIDC.GroupsClaim, \"oidc-groups-claim\", \"\", \"\"+\n\t\t\t\"If provided, the name of a custom OpenID Connect claim for specifying user groups. \"+\n\t\t\t\"The claim value is expected to be a string or array of strings. This flag is experimental, \"+\n\t\t\t\"please see the authentication documentation for further details.\")\n\n\t\tfs.StringVar(\u0026o.OIDC.GroupsPrefix, \"oidc-groups-prefix\", \"\", \"\"+\n\t\t\t\"If provided, all groups will be prefixed with this value to prevent conflicts with \"+\n\t\t\t\"other authentication strategies.\")\n\n\t\tfs.StringSliceVar(\u0026o.OIDC.SigningAlgs, \"oidc-signing-algs\", []string{\"RS256\"}, \"\"+\n\t\t\t\"Comma-separated list of allowed JOSE asymmetric signing algorithms. JWTs with a \"+\n\t\t\t\"supported 'alg' header values are: RS256, RS384, RS512, ES256, ES384, ES512, PS256, PS384, PS512. \"+\n\t\t\t\"Values are defined by RFC 7518 https://tools.ietf.org/html/rfc7518#section-3.1.\")\n\n\t\tfs.Var(cliflag.NewMapStringStringNoSplit(\u0026o.OIDC.RequiredClaims), \"oidc-required-claim\", \"\"+\n\t\t\t\"A key=value pair that describes a required claim in the ID Token. \"+\n\t\t\t\"If set, the claim is verified to be present in the ID Token with a matching value. \"+\n\t\t\t\"Repeat this flag to specify multiple claims.\")\n\t}\n\n\tif o.RequestHeader != nil {\n\t\to.RequestHeader.AddFlags(fs)\n\t}\n\n\tif o.ServiceAccounts != nil {\n\t\tfs.StringArrayVar(\u0026o.ServiceAccounts.KeyFiles, \"service-account-key-file\", o.ServiceAccounts.KeyFiles, \"\"+\n\t\t\t\"File containing PEM-encoded x509 RSA or ECDSA private or public keys, used to verify \"+\n\t\t\t\"ServiceAccount tokens. The specified file can contain multiple keys, and the flag can \"+\n\t\t\t\"be specified multiple times with different files. If unspecified, \"+\n\t\t\t\"--tls-private-key-file is used. Must be specified when \"+\n\t\t\t\"--service-account-signing-key-file is provided\")\n\n\t\tfs.BoolVar(\u0026o.ServiceAccounts.Lookup, \"service-account-lookup\", o.ServiceAccounts.Lookup,\n\t\t\t\"If true, validate ServiceAccount tokens exist in etcd as part of authentication.\")\n\n\t\tfs.StringArrayVar(\u0026o.ServiceAccounts.Issuers, \"service-account-issuer\", o.ServiceAccounts.Issuers, \"\"+\n\t\t\t\"Identifier of the service account token issuer. The issuer will assert this identifier \"+\n\t\t\t\"in \\\"iss\\\" claim of issued tokens. This value is a string or URI. If this option is not \"+\n\t\t\t\"a valid URI per the OpenID Discovery 1.0 spec, the ServiceAccountIssuerDiscovery feature \"+\n\t\t\t\"will remain disabled, even if the feature gate is set to true. It is highly recommended \"+\n\t\t\t\"that this value comply with the OpenID spec: https://openid.net/specs/openid-connect-discovery-1_0.html. \"+\n\t\t\t\"In practice, this means that service-account-issuer must be an https URL. It is also highly \"+\n\t\t\t\"recommended that this URL be capable of serving OpenID discovery documents at \"+\n\t\t\t\"{service-account-issuer}/.well-known/openid-configuration. \"+\n\t\t\t\"When this flag is specified multiple times, the first is used to generate tokens \"+\n\t\t\t\"and all are used to determine which issuers are accepted.\")\n\n\t\tfs.StringVar(\u0026o.ServiceAccounts.JWKSURI, \"service-account-jwks-uri\", o.ServiceAccounts.JWKSURI, \"\"+\n\t\t\t\"Overrides the URI for the JSON Web Key Set in the discovery doc served at \"+\n\t\t\t\"/.well-known/openid-configuration. This flag is useful if the discovery doc\"+\n\t\t\t\"and key set are served to relying parties from a URL other than the \"+\n\t\t\t\"API server's external (as auto-detected or overridden with external-hostname). \")\n\n\t\tfs.DurationVar(\u0026o.ServiceAccounts.MaxExpiration, \"service-account-max-token-expiration\", o.ServiceAccounts.MaxExpiration, \"\"+\n\t\t\t\"The maximum validity duration of a token created by the service account token issuer. If an otherwise valid \"+\n\t\t\t\"TokenRequest with a validity duration larger than this value is requested, a token will be issued with a validity duration of this value.\")\n\n\t\tfs.BoolVar(\u0026o.ServiceAccounts.ExtendExpiration, \"service-account-extend-token-expiration\", o.ServiceAccounts.ExtendExpiration, \"\"+\n\t\t\t\"Turns on projected service account expiration extension during token generation, \"+\n\t\t\t\"which helps safe transition from legacy token to bound service account token feature. \"+\n\t\t\t\"If this flag is enabled, admission injected tokens would be extended up to 1 year to \"+\n\t\t\t\"prevent unexpected failure during transition, ignoring value of service-account-max-token-expiration.\")\n\t}\n\n\tif o.TokenFile != nil {\n\t\tfs.StringVar(\u0026o.TokenFile.TokenFile, \"token-auth-file\", o.TokenFile.TokenFile, \"\"+\n\t\t\t\"If set, the file that will be used to secure the secure port of the API server \"+\n\t\t\t\"via token authentication.\")\n\t}\n\n\tif o.WebHook != nil {\n\t\tfs.StringVar(\u0026o.WebHook.ConfigFile, \"authentication-token-webhook-config-file\", o.WebHook.ConfigFile, \"\"+\n\t\t\t\"File with webhook configuration for token authentication in kubeconfig format. \"+\n\t\t\t\"The API server will query the remote service to determine authentication for bearer tokens.\")\n\n\t\tfs.StringVar(\u0026o.WebHook.Version, \"authentication-token-webhook-version\", o.WebHook.Version, \"\"+\n\t\t\t\"The API version of the authentication.k8s.io TokenReview to send to and expect from the webhook.\")\n\n\t\tfs.DurationVar(\u0026o.WebHook.CacheTTL, \"authentication-token-webhook-cache-ttl\", o.WebHook.CacheTTL,\n\t\t\t\"The duration to cache responses from the webhook token authenticator.\")\n\t}\n}","line":{"from":247,"to":375}} {"id":100005370,"name":"ToAuthenticationConfig","signature":"func (o *BuiltInAuthenticationOptions) ToAuthenticationConfig() (kubeauthenticator.Config, error)","file":"pkg/kubeapiserver/options/authentication.go","code":"// ToAuthenticationConfig convert BuiltInAuthenticationOptions to kubeauthenticator.Config\nfunc (o *BuiltInAuthenticationOptions) ToAuthenticationConfig() (kubeauthenticator.Config, error) {\n\tret := kubeauthenticator.Config{\n\t\tTokenSuccessCacheTTL: o.TokenSuccessCacheTTL,\n\t\tTokenFailureCacheTTL: o.TokenFailureCacheTTL,\n\t}\n\n\tif o.Anonymous != nil {\n\t\tret.Anonymous = o.Anonymous.Allow\n\t}\n\n\tif o.BootstrapToken != nil {\n\t\tret.BootstrapToken = o.BootstrapToken.Enable\n\t}\n\n\tif o.ClientCert != nil {\n\t\tvar err error\n\t\tret.ClientCAContentProvider, err = o.ClientCert.GetClientCAContentProvider()\n\t\tif err != nil {\n\t\t\treturn kubeauthenticator.Config{}, err\n\t\t}\n\t}\n\n\tif o.OIDC != nil {\n\t\tret.OIDCCAFile = o.OIDC.CAFile\n\t\tret.OIDCClientID = o.OIDC.ClientID\n\t\tret.OIDCGroupsClaim = o.OIDC.GroupsClaim\n\t\tret.OIDCGroupsPrefix = o.OIDC.GroupsPrefix\n\t\tret.OIDCIssuerURL = o.OIDC.IssuerURL\n\t\tret.OIDCUsernameClaim = o.OIDC.UsernameClaim\n\t\tret.OIDCUsernamePrefix = o.OIDC.UsernamePrefix\n\t\tret.OIDCSigningAlgs = o.OIDC.SigningAlgs\n\t\tret.OIDCRequiredClaims = o.OIDC.RequiredClaims\n\t}\n\n\tif o.RequestHeader != nil {\n\t\tvar err error\n\t\tret.RequestHeaderConfig, err = o.RequestHeader.ToAuthenticationRequestHeaderConfig()\n\t\tif err != nil {\n\t\t\treturn kubeauthenticator.Config{}, err\n\t\t}\n\t}\n\n\tret.APIAudiences = o.APIAudiences\n\tif o.ServiceAccounts != nil {\n\t\tif len(o.ServiceAccounts.Issuers) != 0 \u0026\u0026 len(o.APIAudiences) == 0 {\n\t\t\tret.APIAudiences = authenticator.Audiences(o.ServiceAccounts.Issuers)\n\t\t}\n\t\tret.ServiceAccountKeyFiles = o.ServiceAccounts.KeyFiles\n\t\tret.ServiceAccountIssuers = o.ServiceAccounts.Issuers\n\t\tret.ServiceAccountLookup = o.ServiceAccounts.Lookup\n\t}\n\n\tif o.TokenFile != nil {\n\t\tret.TokenAuthFile = o.TokenFile.TokenFile\n\t}\n\n\tif o.WebHook != nil {\n\t\tret.WebhookTokenAuthnConfigFile = o.WebHook.ConfigFile\n\t\tret.WebhookTokenAuthnVersion = o.WebHook.Version\n\t\tret.WebhookTokenAuthnCacheTTL = o.WebHook.CacheTTL\n\t\tret.WebhookRetryBackoff = o.WebHook.RetryBackoff\n\n\t\tif len(o.WebHook.ConfigFile) \u003e 0 \u0026\u0026 o.WebHook.CacheTTL \u003e 0 {\n\t\t\tif o.TokenSuccessCacheTTL \u003e 0 \u0026\u0026 o.WebHook.CacheTTL \u003c o.TokenSuccessCacheTTL {\n\t\t\t\tklog.Warningf(\"the webhook cache ttl of %s is shorter than the overall cache ttl of %s for successful token authentication attempts.\", o.WebHook.CacheTTL, o.TokenSuccessCacheTTL)\n\t\t\t}\n\t\t\tif o.TokenFailureCacheTTL \u003e 0 \u0026\u0026 o.WebHook.CacheTTL \u003c o.TokenFailureCacheTTL {\n\t\t\t\tklog.Warningf(\"the webhook cache ttl of %s is shorter than the overall cache ttl of %s for failed token authentication attempts.\", o.WebHook.CacheTTL, o.TokenFailureCacheTTL)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ret, nil\n}","line":{"from":377,"to":451}} {"id":100005371,"name":"ApplyTo","signature":"func (o *BuiltInAuthenticationOptions) ApplyTo(authInfo *genericapiserver.AuthenticationInfo, secureServing *genericapiserver.SecureServingInfo, egressSelector *egressselector.EgressSelector, openAPIConfig *openapicommon.Config, openAPIV3Config *openapicommon.Config, extclient kubernetes.Interface, versionedInformer informers.SharedInformerFactory) error","file":"pkg/kubeapiserver/options/authentication.go","code":"// ApplyTo requires already applied OpenAPIConfig and EgressSelector if present.\nfunc (o *BuiltInAuthenticationOptions) ApplyTo(authInfo *genericapiserver.AuthenticationInfo, secureServing *genericapiserver.SecureServingInfo, egressSelector *egressselector.EgressSelector, openAPIConfig *openapicommon.Config, openAPIV3Config *openapicommon.Config, extclient kubernetes.Interface, versionedInformer informers.SharedInformerFactory) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tif openAPIConfig == nil {\n\t\treturn errors.New(\"uninitialized OpenAPIConfig\")\n\t}\n\n\tauthenticatorConfig, err := o.ToAuthenticationConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif authenticatorConfig.ClientCAContentProvider != nil {\n\t\tif err = authInfo.ApplyClientCert(authenticatorConfig.ClientCAContentProvider, secureServing); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to load client CA file: %v\", err)\n\t\t}\n\t}\n\tif authenticatorConfig.RequestHeaderConfig != nil \u0026\u0026 authenticatorConfig.RequestHeaderConfig.CAContentProvider != nil {\n\t\tif err = authInfo.ApplyClientCert(authenticatorConfig.RequestHeaderConfig.CAContentProvider, secureServing); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to load client CA file: %v\", err)\n\t\t}\n\t}\n\n\tauthInfo.RequestHeaderConfig = authenticatorConfig.RequestHeaderConfig\n\tauthInfo.APIAudiences = o.APIAudiences\n\tif o.ServiceAccounts != nil \u0026\u0026 len(o.ServiceAccounts.Issuers) != 0 \u0026\u0026 len(o.APIAudiences) == 0 {\n\t\tauthInfo.APIAudiences = authenticator.Audiences(o.ServiceAccounts.Issuers)\n\t}\n\n\tauthenticatorConfig.ServiceAccountTokenGetter = serviceaccountcontroller.NewGetterFromClient(\n\t\textclient,\n\t\tversionedInformer.Core().V1().Secrets().Lister(),\n\t\tversionedInformer.Core().V1().ServiceAccounts().Lister(),\n\t\tversionedInformer.Core().V1().Pods().Lister(),\n\t)\n\tauthenticatorConfig.SecretsWriter = extclient.CoreV1()\n\n\tauthenticatorConfig.BootstrapTokenAuthenticator = bootstrap.NewTokenAuthenticator(\n\t\tversionedInformer.Core().V1().Secrets().Lister().Secrets(metav1.NamespaceSystem),\n\t)\n\n\tif egressSelector != nil {\n\t\tegressDialer, err := egressSelector.Lookup(egressselector.ControlPlane.AsNetworkContext())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tauthenticatorConfig.CustomDial = egressDialer\n\t}\n\n\tauthInfo.Authenticator, openAPIConfig.SecurityDefinitions, err = authenticatorConfig.New()\n\tif openAPIV3Config != nil {\n\t\topenAPIV3Config.SecurityDefinitions = openAPIConfig.SecurityDefinitions\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":453,"to":514}} {"id":100005372,"name":"ApplyAuthorization","signature":"func (o *BuiltInAuthenticationOptions) ApplyAuthorization(authorization *BuiltInAuthorizationOptions)","file":"pkg/kubeapiserver/options/authentication.go","code":"// ApplyAuthorization will conditionally modify the authentication options based on the authorization options\nfunc (o *BuiltInAuthenticationOptions) ApplyAuthorization(authorization *BuiltInAuthorizationOptions) {\n\tif o == nil || authorization == nil || o.Anonymous == nil {\n\t\treturn\n\t}\n\n\t// authorization ModeAlwaysAllow cannot be combined with AnonymousAuth.\n\t// in such a case the AnonymousAuth is stomped to false and you get a message\n\tif o.Anonymous.Allow \u0026\u0026 sets.NewString(authorization.Modes...).Has(authzmodes.ModeAlwaysAllow) {\n\t\tklog.Warningf(\"AnonymousAuth is not allowed with the AlwaysAllow authorizer. Resetting AnonymousAuth to false. You should use a different authorizer\")\n\t\to.Anonymous.Allow = false\n\t}\n}","line":{"from":516,"to":528}} {"id":100005373,"name":"NewBuiltInAuthorizationOptions","signature":"func NewBuiltInAuthorizationOptions() *BuiltInAuthorizationOptions","file":"pkg/kubeapiserver/options/authorization.go","code":"// NewBuiltInAuthorizationOptions create a BuiltInAuthorizationOptions with default value\nfunc NewBuiltInAuthorizationOptions() *BuiltInAuthorizationOptions {\n\treturn \u0026BuiltInAuthorizationOptions{\n\t\tModes: []string{authzmodes.ModeAlwaysAllow},\n\t\tWebhookVersion: \"v1beta1\",\n\t\tWebhookCacheAuthorizedTTL: 5 * time.Minute,\n\t\tWebhookCacheUnauthorizedTTL: 30 * time.Second,\n\t\tWebhookRetryBackoff: genericoptions.DefaultAuthWebhookRetryBackoff(),\n\t}\n}","line":{"from":48,"to":57}} {"id":100005374,"name":"Validate","signature":"func (o *BuiltInAuthorizationOptions) Validate() []error","file":"pkg/kubeapiserver/options/authorization.go","code":"// Validate checks invalid config combination\nfunc (o *BuiltInAuthorizationOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tvar allErrors []error\n\n\tif len(o.Modes) == 0 {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"at least one authorization-mode must be passed\"))\n\t}\n\n\tmodes := sets.NewString(o.Modes...)\n\tfor _, mode := range o.Modes {\n\t\tif !authzmodes.IsValidAuthorizationMode(mode) {\n\t\t\tallErrors = append(allErrors, fmt.Errorf(\"authorization-mode %q is not a valid mode\", mode))\n\t\t}\n\t\tif mode == authzmodes.ModeABAC \u0026\u0026 o.PolicyFile == \"\" {\n\t\t\tallErrors = append(allErrors, fmt.Errorf(\"authorization-mode ABAC's authorization policy file not passed\"))\n\t\t}\n\t\tif mode == authzmodes.ModeWebhook \u0026\u0026 o.WebhookConfigFile == \"\" {\n\t\t\tallErrors = append(allErrors, fmt.Errorf(\"authorization-mode Webhook's authorization config file not passed\"))\n\t\t}\n\t}\n\n\tif o.PolicyFile != \"\" \u0026\u0026 !modes.Has(authzmodes.ModeABAC) {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"cannot specify --authorization-policy-file without mode ABAC\"))\n\t}\n\n\tif o.WebhookConfigFile != \"\" \u0026\u0026 !modes.Has(authzmodes.ModeWebhook) {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"cannot specify --authorization-webhook-config-file without mode Webhook\"))\n\t}\n\n\tif len(o.Modes) != modes.Len() {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"authorization-mode %q has mode specified more than once\", o.Modes))\n\t}\n\n\tif o.WebhookRetryBackoff != nil \u0026\u0026 o.WebhookRetryBackoff.Steps \u003c= 0 {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"number of webhook retry attempts must be greater than 0, but is: %d\", o.WebhookRetryBackoff.Steps))\n\t}\n\n\treturn allErrors\n}","line":{"from":59,"to":100}} {"id":100005375,"name":"AddFlags","signature":"func (o *BuiltInAuthorizationOptions) AddFlags(fs *pflag.FlagSet)","file":"pkg/kubeapiserver/options/authorization.go","code":"// AddFlags returns flags of authorization for a API Server\nfunc (o *BuiltInAuthorizationOptions) AddFlags(fs *pflag.FlagSet) {\n\tfs.StringSliceVar(\u0026o.Modes, \"authorization-mode\", o.Modes, \"\"+\n\t\t\"Ordered list of plug-ins to do authorization on secure port. Comma-delimited list of: \"+\n\t\tstrings.Join(authzmodes.AuthorizationModeChoices, \",\")+\".\")\n\n\tfs.StringVar(\u0026o.PolicyFile, \"authorization-policy-file\", o.PolicyFile, \"\"+\n\t\t\"File with authorization policy in json line by line format, used with --authorization-mode=ABAC, on the secure port.\")\n\n\tfs.StringVar(\u0026o.WebhookConfigFile, \"authorization-webhook-config-file\", o.WebhookConfigFile, \"\"+\n\t\t\"File with webhook configuration in kubeconfig format, used with --authorization-mode=Webhook. \"+\n\t\t\"The API server will query the remote service to determine access on the API server's secure port.\")\n\n\tfs.StringVar(\u0026o.WebhookVersion, \"authorization-webhook-version\", o.WebhookVersion, \"\"+\n\t\t\"The API version of the authorization.k8s.io SubjectAccessReview to send to and expect from the webhook.\")\n\n\tfs.DurationVar(\u0026o.WebhookCacheAuthorizedTTL, \"authorization-webhook-cache-authorized-ttl\",\n\t\to.WebhookCacheAuthorizedTTL,\n\t\t\"The duration to cache 'authorized' responses from the webhook authorizer.\")\n\n\tfs.DurationVar(\u0026o.WebhookCacheUnauthorizedTTL,\n\t\t\"authorization-webhook-cache-unauthorized-ttl\", o.WebhookCacheUnauthorizedTTL,\n\t\t\"The duration to cache 'unauthorized' responses from the webhook authorizer.\")\n}","line":{"from":102,"to":125}} {"id":100005376,"name":"ToAuthorizationConfig","signature":"func (o *BuiltInAuthorizationOptions) ToAuthorizationConfig(versionedInformerFactory versionedinformers.SharedInformerFactory) authorizer.Config","file":"pkg/kubeapiserver/options/authorization.go","code":"// ToAuthorizationConfig convert BuiltInAuthorizationOptions to authorizer.Config\nfunc (o *BuiltInAuthorizationOptions) ToAuthorizationConfig(versionedInformerFactory versionedinformers.SharedInformerFactory) authorizer.Config {\n\treturn authorizer.Config{\n\t\tAuthorizationModes: o.Modes,\n\t\tPolicyFile: o.PolicyFile,\n\t\tWebhookConfigFile: o.WebhookConfigFile,\n\t\tWebhookVersion: o.WebhookVersion,\n\t\tWebhookCacheAuthorizedTTL: o.WebhookCacheAuthorizedTTL,\n\t\tWebhookCacheUnauthorizedTTL: o.WebhookCacheUnauthorizedTTL,\n\t\tVersionedInformerFactory: versionedInformerFactory,\n\t\tWebhookRetryBackoff: o.WebhookRetryBackoff,\n\t}\n}","line":{"from":127,"to":139}} {"id":100005377,"name":"NewCloudProviderOptions","signature":"func NewCloudProviderOptions() *CloudProviderOptions","file":"pkg/kubeapiserver/options/cloudprovider.go","code":"// NewCloudProviderOptions creates a default CloudProviderOptions\nfunc NewCloudProviderOptions() *CloudProviderOptions {\n\treturn \u0026CloudProviderOptions{}\n}","line":{"from":29,"to":32}} {"id":100005378,"name":"Validate","signature":"func (s *CloudProviderOptions) Validate() []error","file":"pkg/kubeapiserver/options/cloudprovider.go","code":"// Validate checks invalid config\nfunc (s *CloudProviderOptions) Validate() []error {\n\tallErrors := []error{}\n\treturn allErrors\n}","line":{"from":34,"to":38}} {"id":100005379,"name":"AddFlags","signature":"func (s *CloudProviderOptions) AddFlags(fs *pflag.FlagSet)","file":"pkg/kubeapiserver/options/cloudprovider.go","code":"// AddFlags returns flags of cloud provider for a API Server\nfunc (s *CloudProviderOptions) AddFlags(fs *pflag.FlagSet) {\n\tfs.StringVar(\u0026s.CloudProvider, \"cloud-provider\", s.CloudProvider,\n\t\t\"The provider for cloud services. Empty string for no provider.\")\n\n\tfs.StringVar(\u0026s.CloudConfigFile, \"cloud-config\", s.CloudConfigFile,\n\t\t\"The path to the cloud provider configuration file. Empty string for no configuration file.\")\n}","line":{"from":40,"to":47}} {"id":100005380,"name":"RegisterAllAdmissionPlugins","signature":"func RegisterAllAdmissionPlugins(plugins *admission.Plugins)","file":"pkg/kubeapiserver/options/plugins.go","code":"// RegisterAllAdmissionPlugins registers all admission plugins.\n// The order of registration is irrelevant, see AllOrderedPlugins for execution order.\nfunc RegisterAllAdmissionPlugins(plugins *admission.Plugins) {\n\tadmit.Register(plugins) // DEPRECATED as no real meaning\n\talwayspullimages.Register(plugins)\n\tantiaffinity.Register(plugins)\n\tdefaulttolerationseconds.Register(plugins)\n\tdefaultingressclass.Register(plugins)\n\tdenyserviceexternalips.Register(plugins)\n\tdeny.Register(plugins) // DEPRECATED as no real meaning\n\teventratelimit.Register(plugins)\n\textendedresourcetoleration.Register(plugins)\n\tgc.Register(plugins)\n\timagepolicy.Register(plugins)\n\tlimitranger.Register(plugins)\n\tautoprovision.Register(plugins)\n\texists.Register(plugins)\n\tnoderestriction.Register(plugins)\n\tnodetaint.Register(plugins)\n\tlabel.Register(plugins) // DEPRECATED, future PVs should not rely on labels for zone topology\n\tpodnodeselector.Register(plugins)\n\tpodtolerationrestriction.Register(plugins)\n\truntimeclass.Register(plugins)\n\tresourcequota.Register(plugins)\n\tpodsecurity.Register(plugins)\n\tpodpriority.Register(plugins)\n\tscdeny.Register(plugins)\n\tserviceaccount.Register(plugins)\n\tsetdefault.Register(plugins)\n\tresize.Register(plugins)\n\tstorageobjectinuseprotection.Register(plugins)\n\tcertapproval.Register(plugins)\n\tcertsigning.Register(plugins)\n\tctbattest.Register(plugins)\n\tcertsubjectrestriction.Register(plugins)\n}","line":{"from":109,"to":144}} {"id":100005381,"name":"DefaultOffAdmissionPlugins","signature":"func DefaultOffAdmissionPlugins() sets.String","file":"pkg/kubeapiserver/options/plugins.go","code":"// DefaultOffAdmissionPlugins get admission plugins off by default for kube-apiserver.\nfunc DefaultOffAdmissionPlugins() sets.String {\n\tdefaultOnPlugins := sets.NewString(\n\t\tlifecycle.PluginName, // NamespaceLifecycle\n\t\tlimitranger.PluginName, // LimitRanger\n\t\tserviceaccount.PluginName, // ServiceAccount\n\t\tsetdefault.PluginName, // DefaultStorageClass\n\t\tresize.PluginName, // PersistentVolumeClaimResize\n\t\tdefaulttolerationseconds.PluginName, // DefaultTolerationSeconds\n\t\tmutatingwebhook.PluginName, // MutatingAdmissionWebhook\n\t\tvalidatingwebhook.PluginName, // ValidatingAdmissionWebhook\n\t\tresourcequota.PluginName, // ResourceQuota\n\t\tstorageobjectinuseprotection.PluginName, // StorageObjectInUseProtection\n\t\tpodpriority.PluginName, // Priority\n\t\tnodetaint.PluginName, // TaintNodesByCondition\n\t\truntimeclass.PluginName, // RuntimeClass\n\t\tcertapproval.PluginName, // CertificateApproval\n\t\tcertsigning.PluginName, // CertificateSigning\n\t\tctbattest.PluginName, // ClusterTrustBundleAttest\n\t\tcertsubjectrestriction.PluginName, // CertificateSubjectRestriction\n\t\tdefaultingressclass.PluginName, // DefaultIngressClass\n\t\tpodsecurity.PluginName, // PodSecurity\n\t\tvalidatingadmissionpolicy.PluginName, // ValidatingAdmissionPolicy, only active when feature gate ValidatingAdmissionPolicy is enabled\n\t)\n\n\treturn sets.NewString(AllOrderedPlugins...).Difference(defaultOnPlugins)\n}","line":{"from":146,"to":172}} {"id":100005382,"name":"NewSecureServingOptions","signature":"func NewSecureServingOptions() *genericoptions.SecureServingOptionsWithLoopback","file":"pkg/kubeapiserver/options/serving.go","code":"// NewSecureServingOptions gives default values for the kube-apiserver which are not the options wanted by\n// \"normal\" API servers running on the platform\nfunc NewSecureServingOptions() *genericoptions.SecureServingOptionsWithLoopback {\n\to := genericoptions.SecureServingOptions{\n\t\tBindAddress: netutils.ParseIPSloppy(\"0.0.0.0\"),\n\t\tBindPort: 6443,\n\t\tRequired: true,\n\t\tServerCert: genericoptions.GeneratableKeyCert{\n\t\t\tPairName: \"apiserver\",\n\t\t\tCertDirectory: \"/var/run/kubernetes\",\n\t\t},\n\t}\n\treturn o.WithLoopback()\n}","line":{"from":25,"to":38}} {"id":100005383,"name":"NewConvertOptions","signature":"func NewConvertOptions(ioStreams genericclioptions.IOStreams) *ConvertOptions","file":"pkg/kubectl/cmd/convert/convert.go","code":"func NewConvertOptions(ioStreams genericclioptions.IOStreams) *ConvertOptions {\n\treturn \u0026ConvertOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"converted\").WithTypeSetter(scheme.Scheme).WithDefaultOutput(\"yaml\"),\n\t\tlocal: true,\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":79,"to":85}} {"id":100005384,"name":"NewCmdConvert","signature":"func NewCmdConvert(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"pkg/kubectl/cmd/convert/convert.go","code":"// NewCmdConvert creates a command object for the generic \"convert\" action, which\n// translates the config file into a given version.\nfunc NewCmdConvert(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewConvertOptions(ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"convert -f FILENAME\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Convert config files between different API versions\"),\n\t\tLong: convertLong,\n\t\tExample: convertExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd))\n\t\t\tcmdutil.CheckErr(o.RunConvert())\n\t\t},\n\t}\n\n\tcmd.Flags().BoolVar(\u0026o.local, \"local\", o.local, \"If true, convert will NOT try to contact api-server but run locally.\")\n\tcmd.Flags().StringVar(\u0026o.OutputVersion, \"output-version\", o.OutputVersion, i18n.T(\"Output the formatted object with the given group version (for ex: 'extensions/v1beta1').\"))\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddValidateFlags(cmd)\n\tcmdutil.AddFilenameOptionFlags(cmd, \u0026o.FilenameOptions, \"to need to get converted.\")\n\treturn cmd\n}","line":{"from":87,"to":111}} {"id":100005385,"name":"Complete","signature":"func (o *ConvertOptions) Complete(f cmdutil.Factory, cmd *cobra.Command) (err error)","file":"pkg/kubectl/cmd/convert/convert.go","code":"// Complete collects information required to run Convert command from command line.\nfunc (o *ConvertOptions) Complete(f cmdutil.Factory, cmd *cobra.Command) (err error) {\n\terr = o.FilenameOptions.RequireFilenameOrKustomize()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.builder = f.NewBuilder\n\n\to.Namespace, _, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.validator = func() (validation.Schema, error) {\n\t\tdirective, err := cmdutil.GetValidationDirective(cmd)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn f.Validator(directive)\n\t}\n\n\t// build the printer\n\to.Printer, err = o.PrintFlags.ToPrinter()\n\treturn err\n}","line":{"from":113,"to":137}} {"id":100005386,"name":"RunConvert","signature":"func (o *ConvertOptions) RunConvert() error","file":"pkg/kubectl/cmd/convert/convert.go","code":"// RunConvert implements the generic Convert command\nfunc (o *ConvertOptions) RunConvert() error {\n\tb := o.builder().\n\t\tWithScheme(scheme.Scheme).\n\t\tLocalParam(o.local)\n\tif !o.local {\n\t\tschema, err := o.validator()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tb.Schema(schema)\n\t}\n\n\tr := b.NamespaceParam(o.Namespace).\n\t\tContinueOnError().\n\t\tFilenameParam(false, \u0026o.FilenameOptions).\n\t\tFlatten().\n\t\tDo()\n\n\terr := r.Err()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsingleItemImplied := false\n\tinfos, err := r.IntoSingleItemImplied(\u0026singleItemImplied).Infos()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(infos) == 0 {\n\t\treturn fmt.Errorf(\"no objects passed to convert\")\n\t}\n\n\tvar specifiedOutputVersion schema.GroupVersion\n\tif len(o.OutputVersion) \u003e 0 {\n\t\tspecifiedOutputVersion, err = schema.ParseGroupVersion(o.OutputVersion)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tinternalEncoder := scheme.Codecs.LegacyCodec(scheme.Scheme.PrioritizedVersionsAllGroups()...)\n\tinternalVersionJSONEncoder := unstructured.NewJSONFallbackEncoder(internalEncoder)\n\tobjects, err := asVersionedObject(infos, !singleItemImplied, specifiedOutputVersion, internalVersionJSONEncoder)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn o.Printer.PrintObj(objects, o.Out)\n}","line":{"from":139,"to":189}} {"id":100005387,"name":"asVersionedObject","signature":"func asVersionedObject(infos []*resource.Info, forceList bool, specifiedOutputVersion schema.GroupVersion, encoder runtime.Encoder) (runtime.Object, error)","file":"pkg/kubectl/cmd/convert/convert.go","code":"// asVersionedObject converts a list of infos into a single object - either a List containing\n// the objects as children, or if only a single Object is present, as that object. The provided\n// version will be preferred as the conversion target, but the Object's mapping version will be\n// used if that version is not present.\nfunc asVersionedObject(infos []*resource.Info, forceList bool, specifiedOutputVersion schema.GroupVersion, encoder runtime.Encoder) (runtime.Object, error) {\n\tobjects, err := asVersionedObjects(infos, specifiedOutputVersion, encoder)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar object runtime.Object\n\tif len(objects) == 1 \u0026\u0026 !forceList {\n\t\tobject = objects[0]\n\t} else {\n\t\tobject = \u0026api.List{Items: objects}\n\t\ttargetVersions := []schema.GroupVersion{}\n\t\tif !specifiedOutputVersion.Empty() {\n\t\t\ttargetVersions = append(targetVersions, specifiedOutputVersion)\n\t\t}\n\t\ttargetVersions = append(targetVersions, schema.GroupVersion{Group: \"\", Version: \"v1\"})\n\n\t\tconverted, err := tryConvert(scheme.Scheme, object, targetVersions...)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tobject = converted\n\t}\n\n\tactualVersion := object.GetObjectKind().GroupVersionKind()\n\tif actualVersion.Version != specifiedOutputVersion.Version {\n\t\tdefaultVersionInfo := \"\"\n\t\tif len(actualVersion.Version) \u003e 0 {\n\t\t\tdefaultVersionInfo = fmt.Sprintf(\"Defaulting to %q\", actualVersion.Version)\n\t\t}\n\t\tklog.V(1).Infof(\"info: the output version specified is invalid. %s\\n\", defaultVersionInfo)\n\t}\n\treturn object, nil\n}","line":{"from":191,"to":228}} {"id":100005388,"name":"asVersionedObjects","signature":"func asVersionedObjects(infos []*resource.Info, specifiedOutputVersion schema.GroupVersion, encoder runtime.Encoder) ([]runtime.Object, error)","file":"pkg/kubectl/cmd/convert/convert.go","code":"// asVersionedObjects converts a list of infos into versioned objects. The provided\n// version will be preferred as the conversion target, but the Object's mapping version will be\n// used if that version is not present.\nfunc asVersionedObjects(infos []*resource.Info, specifiedOutputVersion schema.GroupVersion, encoder runtime.Encoder) ([]runtime.Object, error) {\n\tobjects := []runtime.Object{}\n\tfor _, info := range infos {\n\t\tif info.Object == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\ttargetVersions := []schema.GroupVersion{}\n\t\t// objects that are not part of api.Scheme must be converted to JSON\n\t\t// TODO: convert to map[string]interface{}, attach to runtime.Unknown?\n\t\tif !specifiedOutputVersion.Empty() {\n\t\t\tif _, _, err := scheme.Scheme.ObjectKinds(info.Object); runtime.IsNotRegisteredError(err) {\n\t\t\t\t// TODO: ideally this would encode to version, but we don't expose multiple codecs here.\n\t\t\t\tdata, err := runtime.Encode(encoder, info.Object)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\t// TODO: Set ContentEncoding and ContentType.\n\t\t\t\tobjects = append(objects, \u0026runtime.Unknown{Raw: data})\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttargetVersions = append(targetVersions, specifiedOutputVersion)\n\t\t} else {\n\t\t\tgvks, _, err := scheme.Scheme.ObjectKinds(info.Object)\n\t\t\tif err == nil {\n\t\t\t\tfor _, gvk := range gvks {\n\t\t\t\t\ttargetVersions = append(targetVersions, scheme.Scheme.PrioritizedVersionsForGroup(gvk.Group)...)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconverted, err := tryConvert(scheme.Scheme, info.Object, targetVersions...)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tobjects = append(objects, converted)\n\t}\n\treturn objects, nil\n}","line":{"from":230,"to":271}} {"id":100005389,"name":"tryConvert","signature":"func tryConvert(converter runtime.ObjectConvertor, object runtime.Object, versions ...schema.GroupVersion) (runtime.Object, error)","file":"pkg/kubectl/cmd/convert/convert.go","code":"// tryConvert attempts to convert the given object to the provided versions in order. This function assumes\n// the object is in internal version.\nfunc tryConvert(converter runtime.ObjectConvertor, object runtime.Object, versions ...schema.GroupVersion) (runtime.Object, error) {\n\tvar last error\n\tfor _, version := range versions {\n\t\tif version.Empty() {\n\t\t\treturn object, nil\n\t\t}\n\t\tobj, err := converter.ConvertToVersion(object, version)\n\t\tif err != nil {\n\t\t\tlast = err\n\t\t\tcontinue\n\t\t}\n\t\treturn obj, nil\n\t}\n\treturn nil, last\n}","line":{"from":273,"to":289}} {"id":100005390,"name":"newActiveDeadlineHandler","signature":"func newActiveDeadlineHandler(","file":"pkg/kubelet/active_deadline.go","code":"// newActiveDeadlineHandler returns an active deadline handler that can enforce pod active deadline\nfunc newActiveDeadlineHandler(\n\tpodStatusProvider status.PodStatusProvider,\n\trecorder record.EventRecorder,\n\tclock clock.Clock,\n) (*activeDeadlineHandler, error) {\n\n\t// check for all required fields\n\tif clock == nil || podStatusProvider == nil || recorder == nil {\n\t\treturn nil, fmt.Errorf(\"required arguments must not be nil: %v, %v, %v\", clock, podStatusProvider, recorder)\n\t}\n\treturn \u0026activeDeadlineHandler{\n\t\tclock: clock,\n\t\tpodStatusProvider: podStatusProvider,\n\t\trecorder: recorder,\n\t}, nil\n}","line":{"from":45,"to":61}} {"id":100005391,"name":"ShouldSync","signature":"func (m *activeDeadlineHandler) ShouldSync(pod *v1.Pod) bool","file":"pkg/kubelet/active_deadline.go","code":"// ShouldSync returns true if the pod is past its active deadline.\nfunc (m *activeDeadlineHandler) ShouldSync(pod *v1.Pod) bool {\n\treturn m.pastActiveDeadline(pod)\n}","line":{"from":63,"to":66}} {"id":100005392,"name":"ShouldEvict","signature":"func (m *activeDeadlineHandler) ShouldEvict(pod *v1.Pod) lifecycle.ShouldEvictResponse","file":"pkg/kubelet/active_deadline.go","code":"// ShouldEvict returns true if the pod is past its active deadline.\n// It dispatches an event that the pod should be evicted if it is past its deadline.\nfunc (m *activeDeadlineHandler) ShouldEvict(pod *v1.Pod) lifecycle.ShouldEvictResponse {\n\tif !m.pastActiveDeadline(pod) {\n\t\treturn lifecycle.ShouldEvictResponse{Evict: false}\n\t}\n\tm.recorder.Eventf(pod, v1.EventTypeNormal, reason, message)\n\treturn lifecycle.ShouldEvictResponse{Evict: true, Reason: reason, Message: message}\n}","line":{"from":68,"to":76}} {"id":100005393,"name":"pastActiveDeadline","signature":"func (m *activeDeadlineHandler) pastActiveDeadline(pod *v1.Pod) bool","file":"pkg/kubelet/active_deadline.go","code":"// pastActiveDeadline returns true if the pod has been active for more than its ActiveDeadlineSeconds\nfunc (m *activeDeadlineHandler) pastActiveDeadline(pod *v1.Pod) bool {\n\t// no active deadline was specified\n\tif pod.Spec.ActiveDeadlineSeconds == nil {\n\t\treturn false\n\t}\n\t// get the latest status to determine if it was started\n\tpodStatus, ok := m.podStatusProvider.GetPodStatus(pod.UID)\n\tif !ok {\n\t\tpodStatus = pod.Status\n\t}\n\t// we have no start time so just return\n\tif podStatus.StartTime.IsZero() {\n\t\treturn false\n\t}\n\t// determine if the deadline was exceeded\n\tstart := podStatus.StartTime.Time\n\tduration := m.clock.Since(start)\n\tallowedDuration := time.Duration(*pod.Spec.ActiveDeadlineSeconds) * time.Second\n\treturn duration \u003e= allowedDuration\n}","line":{"from":78,"to":98}} {"id":100005394,"name":"Funcs","signature":"func Funcs(codecs runtimeserializer.CodecFactory) []interface{}","file":"pkg/kubelet/apis/config/fuzzer/fuzzer.go","code":"// Funcs returns the fuzzer functions for the kubeletconfig apis.\nfunc Funcs(codecs runtimeserializer.CodecFactory) []interface{} {\n\treturn []interface{}{\n\t\t// provide non-empty values for fields with defaults, so the defaulter doesn't change values during round-trip\n\t\tfunc(obj *kubeletconfig.KubeletConfiguration, c fuzz.Continue) {\n\t\t\tc.FuzzNoCustom(obj)\n\t\t\tobj.EnableServer = true\n\t\t\tobj.Authentication.Anonymous.Enabled = true\n\t\t\tobj.Authentication.Webhook.Enabled = false\n\t\t\tobj.Authentication.Webhook.CacheTTL = metav1.Duration{Duration: 2 * time.Minute}\n\t\t\tobj.Authorization.Mode = kubeletconfig.KubeletAuthorizationModeAlwaysAllow\n\t\t\tobj.Authorization.Webhook.CacheAuthorizedTTL = metav1.Duration{Duration: 5 * time.Minute}\n\t\t\tobj.Authorization.Webhook.CacheUnauthorizedTTL = metav1.Duration{Duration: 30 * time.Second}\n\t\t\tobj.Address = \"0.0.0.0\"\n\t\t\tobj.VolumeStatsAggPeriod = metav1.Duration{Duration: time.Minute}\n\t\t\tobj.RuntimeRequestTimeout = metav1.Duration{Duration: 2 * time.Minute}\n\t\t\tobj.CPUCFSQuota = true\n\t\t\tobj.EventBurst = 10\n\t\t\tobj.EventRecordQPS = 5\n\t\t\tobj.EnableControllerAttachDetach = true\n\t\t\tobj.EnableDebuggingHandlers = true\n\t\t\tobj.EnableSystemLogQuery = false\n\t\t\tobj.FileCheckFrequency = metav1.Duration{Duration: 20 * time.Second}\n\t\t\tobj.HealthzBindAddress = \"127.0.0.1\"\n\t\t\tobj.HealthzPort = 10248\n\t\t\tobj.HTTPCheckFrequency = metav1.Duration{Duration: 20 * time.Second}\n\t\t\tobj.ImageMinimumGCAge = metav1.Duration{Duration: 2 * time.Minute}\n\t\t\tobj.ImageGCHighThresholdPercent = 85\n\t\t\tobj.ImageGCLowThresholdPercent = 80\n\t\t\tobj.KernelMemcgNotification = false\n\t\t\tobj.MaxOpenFiles = 1000000\n\t\t\tobj.MaxPods = 110\n\t\t\tobj.MemoryManagerPolicy = v1beta1.NoneMemoryManagerPolicy\n\t\t\tobj.PodPidsLimit = -1\n\t\t\tobj.NodeStatusUpdateFrequency = metav1.Duration{Duration: 10 * time.Second}\n\t\t\tobj.NodeStatusReportFrequency = metav1.Duration{Duration: time.Minute}\n\t\t\tobj.NodeLeaseDurationSeconds = 40\n\t\t\tobj.CPUManagerPolicy = \"none\"\n\t\t\tobj.CPUManagerPolicyOptions = make(map[string]string)\n\t\t\tobj.CPUManagerReconcilePeriod = obj.NodeStatusUpdateFrequency\n\t\t\tobj.NodeStatusMaxImages = 50\n\t\t\tobj.TopologyManagerPolicy = kubeletconfig.NoneTopologyManagerPolicy\n\t\t\tobj.TopologyManagerScope = kubeletconfig.ContainerTopologyManagerScope\n\t\t\tobj.TopologyManagerPolicyOptions = make(map[string]string)\n\t\t\tobj.QOSReserved = map[string]string{\n\t\t\t\t\"memory\": \"50%\",\n\t\t\t}\n\t\t\tobj.OOMScoreAdj = int32(qos.KubeletOOMScoreAdj)\n\t\t\tobj.Port = ports.KubeletPort\n\t\t\tobj.ReadOnlyPort = ports.KubeletReadOnlyPort\n\t\t\tobj.RegistryBurst = 10\n\t\t\tobj.RegistryPullQPS = 5\n\t\t\tobj.ResolverConfig = kubetypes.ResolvConfDefault\n\t\t\tobj.SerializeImagePulls = true\n\t\t\tobj.StreamingConnectionIdleTimeout = metav1.Duration{Duration: 4 * time.Hour}\n\t\t\tobj.SyncFrequency = metav1.Duration{Duration: 1 * time.Minute}\n\t\t\tobj.ContentType = \"application/vnd.kubernetes.protobuf\"\n\t\t\tobj.KubeAPIQPS = 50\n\t\t\tobj.KubeAPIBurst = 100\n\t\t\tobj.HairpinMode = v1beta1.PromiscuousBridge\n\t\t\tobj.EvictionHard = eviction.DefaultEvictionHard\n\t\t\tobj.EvictionPressureTransitionPeriod = metav1.Duration{Duration: 5 * time.Minute}\n\t\t\tobj.MakeIPTablesUtilChains = true\n\t\t\tobj.IPTablesMasqueradeBit = kubeletconfigv1beta1.DefaultIPTablesMasqueradeBit\n\t\t\tobj.IPTablesDropBit = kubeletconfigv1beta1.DefaultIPTablesDropBit\n\t\t\tobj.CgroupsPerQOS = true\n\t\t\tobj.CgroupDriver = \"cgroupfs\"\n\t\t\tobj.EnforceNodeAllocatable = kubeletconfigv1beta1.DefaultNodeAllocatableEnforcement\n\t\t\tobj.StaticPodURLHeader = make(map[string][]string)\n\t\t\tobj.ContainerLogMaxFiles = 5\n\t\t\tobj.ContainerLogMaxSize = \"10Mi\"\n\t\t\tobj.ConfigMapAndSecretChangeDetectionStrategy = \"Watch\"\n\t\t\tobj.AllowedUnsafeSysctls = []string{}\n\t\t\tobj.VolumePluginDir = kubeletconfigv1beta1.DefaultVolumePluginDir\n\t\t\tobj.ContainerRuntimeEndpoint = \"unix:///run/containerd/containerd.sock\"\n\n\t\t\tif obj.Logging.Format == \"\" {\n\t\t\t\tobj.Logging.Format = \"text\"\n\t\t\t}\n\t\t\tobj.EnableSystemLogHandler = true\n\t\t\tobj.MemoryThrottlingFactor = utilpointer.Float64(rand.Float64())\n\t\t\tobj.LocalStorageCapacityIsolation = true\n\t\t},\n\t}\n}","line":{"from":37,"to":121}} {"id":100005395,"name":"KubeletConfigurationPathRefs","signature":"func KubeletConfigurationPathRefs(kc *KubeletConfiguration) []*string","file":"pkg/kubelet/apis/config/helpers.go","code":"// KubeletConfigurationPathRefs returns pointers to all of the KubeletConfiguration fields that contain filepaths.\n// You might use this, for example, to resolve all relative paths against some common root before\n// passing the configuration to the application. This method must be kept up to date as new fields are added.\nfunc KubeletConfigurationPathRefs(kc *KubeletConfiguration) []*string {\n\tpaths := []*string{}\n\tpaths = append(paths, \u0026kc.StaticPodPath)\n\tpaths = append(paths, \u0026kc.Authentication.X509.ClientCAFile)\n\tpaths = append(paths, \u0026kc.TLSCertFile)\n\tpaths = append(paths, \u0026kc.TLSPrivateKeyFile)\n\tpaths = append(paths, \u0026kc.ResolverConfig)\n\tpaths = append(paths, \u0026kc.VolumePluginDir)\n\treturn paths\n}","line":{"from":19,"to":31}} {"id":100005396,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/kubelet/apis/config/register.go","code":"// addKnownTypes registers known types to the given scheme\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026KubeletConfiguration{},\n\t\t\u0026SerializedNodeConfigSource{},\n\t\t\u0026CredentialProviderConfig{},\n\t)\n\treturn nil\n}","line":{"from":37,"to":45}} {"id":100005397,"name":"NewSchemeAndCodecs","signature":"func NewSchemeAndCodecs(mutators ...serializer.CodecFactoryOptionsMutator) (*runtime.Scheme, *serializer.CodecFactory, error)","file":"pkg/kubelet/apis/config/scheme/scheme.go","code":"// NewSchemeAndCodecs is a utility function that returns a Scheme and CodecFactory\n// that understand the types in the kubeletconfig API group. Passing mutators allows\n// for adjusting the behavior of the CodecFactory, for example enable strict decoding.\nfunc NewSchemeAndCodecs(mutators ...serializer.CodecFactoryOptionsMutator) (*runtime.Scheme, *serializer.CodecFactory, error) {\n\tscheme := runtime.NewScheme()\n\tif err := kubeletconfig.AddToScheme(scheme); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif err := kubeletconfigv1beta1.AddToScheme(scheme); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif err := kubeletconfigv1.AddToScheme(scheme); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tcodecs := serializer.NewCodecFactory(scheme, mutators...)\n\treturn scheme, \u0026codecs, nil\n}","line":{"from":29,"to":45}} {"id":100005398,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *kruntime.Scheme) error","file":"pkg/kubelet/apis/config/v1beta1/defaults.go","code":"func addDefaultingFuncs(scheme *kruntime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":51,"to":53}} {"id":100005399,"name":"SetDefaults_KubeletConfiguration","signature":"func SetDefaults_KubeletConfiguration(obj *kubeletconfigv1beta1.KubeletConfiguration)","file":"pkg/kubelet/apis/config/v1beta1/defaults.go","code":"func SetDefaults_KubeletConfiguration(obj *kubeletconfigv1beta1.KubeletConfiguration) {\n\tif obj.EnableServer == nil {\n\t\tobj.EnableServer = utilpointer.Bool(true)\n\t}\n\tif obj.SyncFrequency == zeroDuration {\n\t\tobj.SyncFrequency = metav1.Duration{Duration: 1 * time.Minute}\n\t}\n\tif obj.FileCheckFrequency == zeroDuration {\n\t\tobj.FileCheckFrequency = metav1.Duration{Duration: 20 * time.Second}\n\t}\n\tif obj.HTTPCheckFrequency == zeroDuration {\n\t\tobj.HTTPCheckFrequency = metav1.Duration{Duration: 20 * time.Second}\n\t}\n\tif obj.Address == \"\" {\n\t\tobj.Address = \"0.0.0.0\"\n\t}\n\tif obj.Port == 0 {\n\t\tobj.Port = ports.KubeletPort\n\t}\n\tif obj.Authentication.Anonymous.Enabled == nil {\n\t\tobj.Authentication.Anonymous.Enabled = utilpointer.Bool(false)\n\t}\n\tif obj.Authentication.Webhook.Enabled == nil {\n\t\tobj.Authentication.Webhook.Enabled = utilpointer.Bool(true)\n\t}\n\tif obj.Authentication.Webhook.CacheTTL == zeroDuration {\n\t\tobj.Authentication.Webhook.CacheTTL = metav1.Duration{Duration: 2 * time.Minute}\n\t}\n\tif obj.Authorization.Mode == \"\" {\n\t\tobj.Authorization.Mode = kubeletconfigv1beta1.KubeletAuthorizationModeWebhook\n\t}\n\tif obj.Authorization.Webhook.CacheAuthorizedTTL == zeroDuration {\n\t\tobj.Authorization.Webhook.CacheAuthorizedTTL = metav1.Duration{Duration: 5 * time.Minute}\n\t}\n\tif obj.Authorization.Webhook.CacheUnauthorizedTTL == zeroDuration {\n\t\tobj.Authorization.Webhook.CacheUnauthorizedTTL = metav1.Duration{Duration: 30 * time.Second}\n\t}\n\tif obj.RegistryPullQPS == nil {\n\t\tobj.RegistryPullQPS = utilpointer.Int32(5)\n\t}\n\tif obj.RegistryBurst == 0 {\n\t\tobj.RegistryBurst = 10\n\t}\n\tif obj.EventRecordQPS == nil {\n\t\tobj.EventRecordQPS = utilpointer.Int32(50)\n\t}\n\tif obj.EventBurst == 0 {\n\t\tobj.EventBurst = 100\n\t}\n\tif obj.EnableDebuggingHandlers == nil {\n\t\tobj.EnableDebuggingHandlers = utilpointer.Bool(true)\n\t}\n\tif obj.HealthzPort == nil {\n\t\tobj.HealthzPort = utilpointer.Int32(10248)\n\t}\n\tif obj.HealthzBindAddress == \"\" {\n\t\tobj.HealthzBindAddress = \"127.0.0.1\"\n\t}\n\tif obj.OOMScoreAdj == nil {\n\t\tobj.OOMScoreAdj = utilpointer.Int32(int32(qos.KubeletOOMScoreAdj))\n\t}\n\tif obj.StreamingConnectionIdleTimeout == zeroDuration {\n\t\tobj.StreamingConnectionIdleTimeout = metav1.Duration{Duration: 4 * time.Hour}\n\t}\n\tif obj.NodeStatusReportFrequency == zeroDuration {\n\t\t// For backward compatibility, NodeStatusReportFrequency's default value is\n\t\t// set to NodeStatusUpdateFrequency if NodeStatusUpdateFrequency is set\n\t\t// explicitly.\n\t\tif obj.NodeStatusUpdateFrequency == zeroDuration {\n\t\t\tobj.NodeStatusReportFrequency = metav1.Duration{Duration: 5 * time.Minute}\n\t\t} else {\n\t\t\tobj.NodeStatusReportFrequency = obj.NodeStatusUpdateFrequency\n\t\t}\n\t}\n\tif obj.NodeStatusUpdateFrequency == zeroDuration {\n\t\tobj.NodeStatusUpdateFrequency = metav1.Duration{Duration: 10 * time.Second}\n\t}\n\tif obj.NodeLeaseDurationSeconds == 0 {\n\t\tobj.NodeLeaseDurationSeconds = 40\n\t}\n\tif obj.ImageMinimumGCAge == zeroDuration {\n\t\tobj.ImageMinimumGCAge = metav1.Duration{Duration: 2 * time.Minute}\n\t}\n\tif obj.ImageGCHighThresholdPercent == nil {\n\t\t// default is below docker's default dm.min_free_space of 90%\n\t\tobj.ImageGCHighThresholdPercent = utilpointer.Int32(85)\n\t}\n\tif obj.ImageGCLowThresholdPercent == nil {\n\t\tobj.ImageGCLowThresholdPercent = utilpointer.Int32(80)\n\t}\n\tif obj.VolumeStatsAggPeriod == zeroDuration {\n\t\tobj.VolumeStatsAggPeriod = metav1.Duration{Duration: time.Minute}\n\t}\n\tif obj.CgroupsPerQOS == nil {\n\t\tobj.CgroupsPerQOS = utilpointer.Bool(true)\n\t}\n\tif obj.CgroupDriver == \"\" {\n\t\tobj.CgroupDriver = \"cgroupfs\"\n\t}\n\tif obj.CPUManagerPolicy == \"\" {\n\t\tobj.CPUManagerPolicy = \"none\"\n\t}\n\tif obj.CPUManagerReconcilePeriod == zeroDuration {\n\t\t// Keep the same as default NodeStatusUpdateFrequency\n\t\tobj.CPUManagerReconcilePeriod = metav1.Duration{Duration: 10 * time.Second}\n\t}\n\tif obj.MemoryManagerPolicy == \"\" {\n\t\tobj.MemoryManagerPolicy = kubeletconfigv1beta1.NoneMemoryManagerPolicy\n\t}\n\tif obj.TopologyManagerPolicy == \"\" {\n\t\tobj.TopologyManagerPolicy = kubeletconfigv1beta1.NoneTopologyManagerPolicy\n\t}\n\tif obj.TopologyManagerScope == \"\" {\n\t\tobj.TopologyManagerScope = kubeletconfigv1beta1.ContainerTopologyManagerScope\n\t}\n\tif obj.RuntimeRequestTimeout == zeroDuration {\n\t\tobj.RuntimeRequestTimeout = metav1.Duration{Duration: 2 * time.Minute}\n\t}\n\tif obj.HairpinMode == \"\" {\n\t\tobj.HairpinMode = kubeletconfigv1beta1.PromiscuousBridge\n\t}\n\tif obj.MaxPods == 0 {\n\t\tobj.MaxPods = 110\n\t}\n\t// default nil or negative value to -1 (implies node allocatable pid limit)\n\tif obj.PodPidsLimit == nil || *obj.PodPidsLimit \u003c int64(0) {\n\t\tobj.PodPidsLimit = utilpointer.Int64(-1)\n\t}\n\n\tif obj.ResolverConfig == nil {\n\t\tobj.ResolverConfig = utilpointer.String(kubetypes.ResolvConfDefault)\n\t}\n\tif obj.CPUCFSQuota == nil {\n\t\tobj.CPUCFSQuota = utilpointer.Bool(true)\n\t}\n\tif obj.CPUCFSQuotaPeriod == nil {\n\t\tobj.CPUCFSQuotaPeriod = \u0026metav1.Duration{Duration: 100 * time.Millisecond}\n\t}\n\tif obj.NodeStatusMaxImages == nil {\n\t\tobj.NodeStatusMaxImages = utilpointer.Int32(50)\n\t}\n\tif obj.MaxOpenFiles == 0 {\n\t\tobj.MaxOpenFiles = 1000000\n\t}\n\tif obj.ContentType == \"\" {\n\t\tobj.ContentType = \"application/vnd.kubernetes.protobuf\"\n\t}\n\tif obj.KubeAPIQPS == nil {\n\t\tobj.KubeAPIQPS = utilpointer.Int32(50)\n\t}\n\tif obj.KubeAPIBurst == 0 {\n\t\tobj.KubeAPIBurst = 100\n\t}\n\tif obj.SerializeImagePulls == nil {\n\t\t// SerializeImagePulls is default to true when MaxParallelImagePulls\n\t\t// is not set, and false when MaxParallelImagePulls is set.\n\t\t// This is to save users from having to set both configs.\n\t\tif obj.MaxParallelImagePulls == nil || *obj.MaxParallelImagePulls \u003c 2 {\n\t\t\tobj.SerializeImagePulls = utilpointer.Bool(true)\n\t\t} else {\n\t\t\tobj.SerializeImagePulls = utilpointer.Bool(false)\n\t\t}\n\t}\n\tif obj.EvictionPressureTransitionPeriod == zeroDuration {\n\t\tobj.EvictionPressureTransitionPeriod = metav1.Duration{Duration: 5 * time.Minute}\n\t}\n\tif obj.EnableControllerAttachDetach == nil {\n\t\tobj.EnableControllerAttachDetach = utilpointer.Bool(true)\n\t}\n\tif obj.MakeIPTablesUtilChains == nil {\n\t\tobj.MakeIPTablesUtilChains = utilpointer.Bool(true)\n\t}\n\tif obj.IPTablesMasqueradeBit == nil {\n\t\tobj.IPTablesMasqueradeBit = utilpointer.Int32(DefaultIPTablesMasqueradeBit)\n\t}\n\tif obj.IPTablesDropBit == nil {\n\t\tobj.IPTablesDropBit = utilpointer.Int32(DefaultIPTablesDropBit)\n\t}\n\tif obj.FailSwapOn == nil {\n\t\tobj.FailSwapOn = utilpointer.Bool(true)\n\t}\n\tif obj.ContainerLogMaxSize == \"\" {\n\t\tobj.ContainerLogMaxSize = \"10Mi\"\n\t}\n\tif obj.ContainerLogMaxFiles == nil {\n\t\tobj.ContainerLogMaxFiles = utilpointer.Int32(5)\n\t}\n\tif obj.ConfigMapAndSecretChangeDetectionStrategy == \"\" {\n\t\tobj.ConfigMapAndSecretChangeDetectionStrategy = kubeletconfigv1beta1.WatchChangeDetectionStrategy\n\t}\n\tif obj.EnforceNodeAllocatable == nil {\n\t\tobj.EnforceNodeAllocatable = DefaultNodeAllocatableEnforcement\n\t}\n\tif obj.VolumePluginDir == \"\" {\n\t\tobj.VolumePluginDir = DefaultVolumePluginDir\n\t}\n\t// Use the Default LoggingConfiguration option\n\tlogsapi.SetRecommendedLoggingConfiguration(\u0026obj.Logging)\n\tif obj.EnableSystemLogHandler == nil {\n\t\tobj.EnableSystemLogHandler = utilpointer.Bool(true)\n\t}\n\tif obj.EnableProfilingHandler == nil {\n\t\tobj.EnableProfilingHandler = utilpointer.Bool(true)\n\t}\n\tif obj.EnableDebugFlagsHandler == nil {\n\t\tobj.EnableDebugFlagsHandler = utilpointer.Bool(true)\n\t}\n\tif obj.SeccompDefault == nil {\n\t\tobj.SeccompDefault = utilpointer.Bool(false)\n\t}\n\tif obj.MemoryThrottlingFactor == nil {\n\t\tobj.MemoryThrottlingFactor = utilpointer.Float64(DefaultMemoryThrottlingFactor)\n\t}\n\tif obj.RegisterNode == nil {\n\t\tobj.RegisterNode = utilpointer.Bool(true)\n\t}\n\tif obj.LocalStorageCapacityIsolation == nil {\n\t\tobj.LocalStorageCapacityIsolation = utilpointer.Bool(true)\n\t}\n\tif obj.ContainerRuntimeEndpoint == \"\" {\n\t\tobj.ContainerRuntimeEndpoint = \"unix:///run/containerd/containerd.sock\"\n\t}\n}","line":{"from":55,"to":277}} {"id":100005400,"name":"init","signature":"func init()","file":"pkg/kubelet/apis/config/v1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":38,"to":43}} {"id":100005401,"name":"ValidateKubeletConfiguration","signature":"func ValidateKubeletConfiguration(kc *kubeletconfig.KubeletConfiguration, featureGate featuregate.FeatureGate) error","file":"pkg/kubelet/apis/config/validation/validation.go","code":"// ValidateKubeletConfiguration validates `kc` and returns an error if it is invalid\nfunc ValidateKubeletConfiguration(kc *kubeletconfig.KubeletConfiguration, featureGate featuregate.FeatureGate) error {\n\tallErrors := []error{}\n\n\t// Make a local copy of the feature gates and combine it with the gates set by this configuration.\n\t// This allows us to validate the config against the set of gates it will actually run against.\n\tlocalFeatureGate := featureGate.DeepCopy()\n\tif err := localFeatureGate.SetFromMap(kc.FeatureGates); err != nil {\n\t\treturn err\n\t}\n\n\tif kc.NodeLeaseDurationSeconds \u003c= 0 {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: nodeLeaseDurationSeconds must be greater than 0\"))\n\t}\n\tif !kc.CgroupsPerQOS \u0026\u0026 len(kc.EnforceNodeAllocatable) \u003e 0 {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: enforceNodeAllocatable (--enforce-node-allocatable) is not supported unless cgroupsPerQOS (--cgroups-per-qos) is set to true\"))\n\t}\n\tif kc.SystemCgroups != \"\" \u0026\u0026 kc.CgroupRoot == \"\" {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: systemCgroups (--system-cgroups) was specified and cgroupRoot (--cgroup-root) was not specified\"))\n\t}\n\tif kc.EventBurst \u003c 0 {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: eventBurst (--event-burst) %v must not be a negative number\", kc.EventBurst))\n\t}\n\tif kc.EventRecordQPS \u003c 0 {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: eventRecordQPS (--event-qps) %v must not be a negative number\", kc.EventRecordQPS))\n\t}\n\tif kc.HealthzPort != 0 \u0026\u0026 utilvalidation.IsValidPortNum(int(kc.HealthzPort)) != nil {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: healthzPort (--healthz-port) %v must be between 1 and 65535, inclusive\", kc.HealthzPort))\n\t}\n\tif !localFeatureGate.Enabled(features.CPUCFSQuotaPeriod) \u0026\u0026 kc.CPUCFSQuotaPeriod != defaultCFSQuota {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: cpuCFSQuotaPeriod (--cpu-cfs-quota-period) %v requires feature gate CustomCPUCFSQuotaPeriod\", kc.CPUCFSQuotaPeriod))\n\t}\n\tif localFeatureGate.Enabled(features.CPUCFSQuotaPeriod) \u0026\u0026 utilvalidation.IsInRange(int(kc.CPUCFSQuotaPeriod.Duration), int(1*time.Millisecond), int(time.Second)) != nil {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: cpuCFSQuotaPeriod (--cpu-cfs-quota-period) %v must be between 1ms and 1sec, inclusive\", kc.CPUCFSQuotaPeriod))\n\t}\n\tif utilvalidation.IsInRange(int(kc.ImageGCHighThresholdPercent), 0, 100) != nil {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: imageGCHighThresholdPercent (--image-gc-high-threshold) %v must be between 0 and 100, inclusive\", kc.ImageGCHighThresholdPercent))\n\t}\n\tif utilvalidation.IsInRange(int(kc.ImageGCLowThresholdPercent), 0, 100) != nil {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: imageGCLowThresholdPercent (--image-gc-low-threshold) %v must be between 0 and 100, inclusive\", kc.ImageGCLowThresholdPercent))\n\t}\n\tif kc.ImageGCLowThresholdPercent \u003e= kc.ImageGCHighThresholdPercent {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: imageGCLowThresholdPercent (--image-gc-low-threshold) %v must be less than imageGCHighThresholdPercent (--image-gc-high-threshold) %v\", kc.ImageGCLowThresholdPercent, kc.ImageGCHighThresholdPercent))\n\t}\n\tif utilvalidation.IsInRange(int(kc.IPTablesDropBit), 0, 31) != nil {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: iptablesDropBit (--iptables-drop-bit) %v must be between 0 and 31, inclusive\", kc.IPTablesDropBit))\n\t}\n\tif utilvalidation.IsInRange(int(kc.IPTablesMasqueradeBit), 0, 31) != nil {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: iptablesMasqueradeBit (--iptables-masquerade-bit) %v must be between 0 and 31, inclusive\", kc.IPTablesMasqueradeBit))\n\t}\n\tif kc.KubeAPIBurst \u003c 0 {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: kubeAPIBurst (--kube-api-burst) %v must not be a negative number\", kc.KubeAPIBurst))\n\t}\n\tif kc.KubeAPIQPS \u003c 0 {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: kubeAPIQPS (--kube-api-qps) %v must not be a negative number\", kc.KubeAPIQPS))\n\t}\n\tif kc.NodeStatusMaxImages \u003c -1 {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: nodeStatusMaxImages (--node-status-max-images) %v must be -1 or greater\", kc.NodeStatusMaxImages))\n\t}\n\tif kc.MaxOpenFiles \u003c 0 {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: maxOpenFiles (--max-open-files) %v must not be a negative number\", kc.MaxOpenFiles))\n\t}\n\tif kc.MaxPods \u003c 0 {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: maxPods (--max-pods) %v must not be a negative number\", kc.MaxPods))\n\t}\n\tif utilvalidation.IsInRange(int(kc.OOMScoreAdj), -1000, 1000) != nil {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: oomScoreAdj (--oom-score-adj) %v must be between -1000 and 1000, inclusive\", kc.OOMScoreAdj))\n\t}\n\tif kc.PodsPerCore \u003c 0 {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: podsPerCore (--pods-per-core) %v must not be a negative number\", kc.PodsPerCore))\n\t}\n\tif utilvalidation.IsValidPortNum(int(kc.Port)) != nil {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: port (--port) %v must be between 1 and 65535, inclusive\", kc.Port))\n\t}\n\tif kc.ReadOnlyPort != 0 \u0026\u0026 utilvalidation.IsValidPortNum(int(kc.ReadOnlyPort)) != nil {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: readOnlyPort (--read-only-port) %v must be between 0 and 65535, inclusive\", kc.ReadOnlyPort))\n\t}\n\tif kc.RegistryBurst \u003c 0 {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: registryBurst (--registry-burst) %v must not be a negative number\", kc.RegistryBurst))\n\t}\n\tif kc.RegistryPullQPS \u003c 0 {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: registryPullQPS (--registry-qps) %v must not be a negative number\", kc.RegistryPullQPS))\n\t}\n\tif kc.MaxParallelImagePulls != nil \u0026\u0026 *kc.MaxParallelImagePulls \u003c 1 {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: maxParallelImagePulls %v must be a positive number\", *kc.MaxParallelImagePulls))\n\t}\n\tif kc.SerializeImagePulls \u0026\u0026 kc.MaxParallelImagePulls != nil \u0026\u0026 *kc.MaxParallelImagePulls \u003e 1 {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: maxParallelImagePulls cannot be larger than 1 unless SerializeImagePulls (--serialize-image-pulls) is set to false\"))\n\t}\n\tif kc.ServerTLSBootstrap \u0026\u0026 !localFeatureGate.Enabled(features.RotateKubeletServerCertificate) {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: serverTLSBootstrap %v requires feature gate RotateKubeletServerCertificate\", kc.ServerTLSBootstrap))\n\t}\n\n\tfor _, nodeTaint := range kc.RegisterWithTaints {\n\t\tif err := utiltaints.CheckTaintValidation(nodeTaint); err != nil {\n\t\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid taint: %v\", nodeTaint))\n\t\t}\n\t\tif nodeTaint.TimeAdded != nil {\n\t\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: taint.TimeAdded is not nil\"))\n\t\t}\n\t}\n\n\tswitch kc.TopologyManagerPolicy {\n\tcase kubeletconfig.NoneTopologyManagerPolicy:\n\tcase kubeletconfig.BestEffortTopologyManagerPolicy:\n\tcase kubeletconfig.RestrictedTopologyManagerPolicy:\n\tcase kubeletconfig.SingleNumaNodeTopologyManagerPolicy:\n\tdefault:\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: topologyManagerPolicy (--topology-manager-policy) %q must be one of: %q\", kc.TopologyManagerPolicy, []string{kubeletconfig.NoneTopologyManagerPolicy, kubeletconfig.BestEffortTopologyManagerPolicy, kubeletconfig.RestrictedTopologyManagerPolicy, kubeletconfig.SingleNumaNodeTopologyManagerPolicy}))\n\t}\n\n\tswitch kc.TopologyManagerScope {\n\tcase kubeletconfig.ContainerTopologyManagerScope:\n\tcase kubeletconfig.PodTopologyManagerScope:\n\tdefault:\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: topologyManagerScope (--topology-manager-scope) %q must be one of: %q, or %q\", kc.TopologyManagerScope, kubeletconfig.ContainerTopologyManagerScope, kubeletconfig.PodTopologyManagerScope))\n\t}\n\n\tif localFeatureGate.Enabled(features.GracefulNodeShutdown) {\n\t\tif kc.ShutdownGracePeriodCriticalPods.Duration \u003e kc.ShutdownGracePeriod.Duration {\n\t\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: shutdownGracePeriodCriticalPods %v must be \u003c= shutdownGracePeriod %v\", kc.ShutdownGracePeriodCriticalPods, kc.ShutdownGracePeriod))\n\t\t}\n\t\tif kc.ShutdownGracePeriod.Duration \u003c 0 || (kc.ShutdownGracePeriod.Duration \u003e 0 \u0026\u0026 kc.ShutdownGracePeriod.Duration \u003c time.Second) {\n\t\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: shutdownGracePeriod %v must be either zero or otherwise \u003e= 1 sec\", kc.ShutdownGracePeriod))\n\t\t}\n\t\tif kc.ShutdownGracePeriodCriticalPods.Duration \u003c 0 || (kc.ShutdownGracePeriodCriticalPods.Duration \u003e 0 \u0026\u0026 kc.ShutdownGracePeriodCriticalPods.Duration \u003c time.Second) {\n\t\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: shutdownGracePeriodCriticalPods %v must be either zero or otherwise \u003e= 1 sec\", kc.ShutdownGracePeriodCriticalPods))\n\t\t}\n\t}\n\tif (kc.ShutdownGracePeriod.Duration \u003e 0 || kc.ShutdownGracePeriodCriticalPods.Duration \u003e 0) \u0026\u0026 !localFeatureGate.Enabled(features.GracefulNodeShutdown) {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: specifying shutdownGracePeriod or shutdownGracePeriodCriticalPods requires feature gate GracefulNodeShutdown\"))\n\t}\n\tif localFeatureGate.Enabled(features.GracefulNodeShutdownBasedOnPodPriority) {\n\t\tif len(kc.ShutdownGracePeriodByPodPriority) != 0 \u0026\u0026 (kc.ShutdownGracePeriod.Duration \u003e 0 || kc.ShutdownGracePeriodCriticalPods.Duration \u003e 0) {\n\t\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: Cannot specify both shutdownGracePeriodByPodPriority and shutdownGracePeriod at the same time\"))\n\t\t}\n\t}\n\tif !localFeatureGate.Enabled(features.GracefulNodeShutdownBasedOnPodPriority) {\n\t\tif len(kc.ShutdownGracePeriodByPodPriority) != 0 {\n\t\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: Specifying shutdownGracePeriodByPodPriority requires feature gate GracefulNodeShutdownBasedOnPodPriority\"))\n\t\t}\n\t}\n\tif localFeatureGate.Enabled(features.NodeSwap) {\n\t\tswitch kc.MemorySwap.SwapBehavior {\n\t\tcase \"\":\n\t\tcase kubetypes.LimitedSwap:\n\t\tcase kubetypes.UnlimitedSwap:\n\t\tdefault:\n\t\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: memorySwap.swapBehavior %q must be one of: \\\"\\\", %q, or %q\", kc.MemorySwap.SwapBehavior, kubetypes.LimitedSwap, kubetypes.UnlimitedSwap))\n\t\t}\n\t}\n\tif !localFeatureGate.Enabled(features.NodeSwap) \u0026\u0026 kc.MemorySwap != (kubeletconfig.MemorySwapConfiguration{}) {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: memorySwap.swapBehavior cannot be set when NodeSwap feature flag is disabled\"))\n\t}\n\n\tfor _, val := range kc.EnforceNodeAllocatable {\n\t\tswitch val {\n\t\tcase kubetypes.NodeAllocatableEnforcementKey:\n\t\tcase kubetypes.SystemReservedEnforcementKey:\n\t\t\tif kc.SystemReservedCgroup == \"\" {\n\t\t\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: systemReservedCgroup (--system-reserved-cgroup) must be specified when %q contained in enforceNodeAllocatable (--enforce-node-allocatable)\", kubetypes.SystemReservedEnforcementKey))\n\t\t\t}\n\t\tcase kubetypes.KubeReservedEnforcementKey:\n\t\t\tif kc.KubeReservedCgroup == \"\" {\n\t\t\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: kubeReservedCgroup (--kube-reserved-cgroup) must be specified when %q contained in enforceNodeAllocatable (--enforce-node-allocatable)\", kubetypes.KubeReservedEnforcementKey))\n\t\t\t}\n\t\tcase kubetypes.NodeAllocatableNoneKey:\n\t\t\tif len(kc.EnforceNodeAllocatable) \u003e 1 {\n\t\t\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: enforceNodeAllocatable (--enforce-node-allocatable) may not contain additional enforcements when %q is specified\", kubetypes.NodeAllocatableNoneKey))\n\t\t\t}\n\t\tdefault:\n\t\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: option %q specified for enforceNodeAllocatable (--enforce-node-allocatable). Valid options are %q, %q, %q, or %q\",\n\t\t\t\tval, kubetypes.NodeAllocatableEnforcementKey, kubetypes.SystemReservedEnforcementKey, kubetypes.KubeReservedEnforcementKey, kubetypes.NodeAllocatableNoneKey))\n\t\t}\n\t}\n\tswitch kc.HairpinMode {\n\tcase kubeletconfig.HairpinNone:\n\tcase kubeletconfig.HairpinVeth:\n\tcase kubeletconfig.PromiscuousBridge:\n\tdefault:\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: option %q specified for hairpinMode (--hairpin-mode). Valid options are %q, %q or %q\",\n\t\t\tkc.HairpinMode, kubeletconfig.HairpinNone, kubeletconfig.HairpinVeth, kubeletconfig.PromiscuousBridge))\n\t}\n\tif kc.ReservedSystemCPUs != \"\" {\n\t\t// --reserved-cpus does not support --system-reserved-cgroup or --kube-reserved-cgroup\n\t\tif kc.SystemReservedCgroup != \"\" || kc.KubeReservedCgroup != \"\" {\n\t\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: can't use reservedSystemCPUs (--reserved-cpus) with systemReservedCgroup (--system-reserved-cgroup) or kubeReservedCgroup (--kube-reserved-cgroup)\"))\n\t\t}\n\t\tif _, err := cpuset.Parse(kc.ReservedSystemCPUs); err != nil {\n\t\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: unable to parse reservedSystemCPUs (--reserved-cpus) %v, error: %w\", kc.ReservedSystemCPUs, err))\n\t\t}\n\t}\n\n\tallErrors = append(allErrors, validateReservedMemoryConfiguration(kc)...)\n\n\tif err := validateKubeletOSConfiguration(kc); err != nil {\n\t\tallErrors = append(allErrors, err)\n\t}\n\tallErrors = append(allErrors, metrics.ValidateShowHiddenMetricsVersion(kc.ShowHiddenMetricsForVersion)...)\n\n\tif errs := logsapi.Validate(\u0026kc.Logging, localFeatureGate, field.NewPath(\"logging\")); len(errs) \u003e 0 {\n\t\tallErrors = append(allErrors, errs.ToAggregate().Errors()...)\n\t}\n\n\tif localFeatureGate.Enabled(features.KubeletTracing) {\n\t\tif errs := tracingapi.ValidateTracingConfiguration(kc.Tracing, localFeatureGate, field.NewPath(\"tracing\")); len(errs) \u003e 0 {\n\t\t\tallErrors = append(allErrors, errs.ToAggregate().Errors()...)\n\t\t}\n\t} else if kc.Tracing != nil {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: tracing should not be configured if KubeletTracing feature flag is disabled.\"))\n\t}\n\n\tif localFeatureGate.Enabled(features.MemoryQoS) \u0026\u0026 kc.MemoryThrottlingFactor == nil {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: memoryThrottlingFactor is required when MemoryQoS feature flag is enabled\"))\n\t}\n\tif kc.MemoryThrottlingFactor != nil \u0026\u0026 (*kc.MemoryThrottlingFactor \u003c= 0 || *kc.MemoryThrottlingFactor \u003e 1.0) {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: memoryThrottlingFactor %v must be greater than 0 and less than or equal to 1.0\", *kc.MemoryThrottlingFactor))\n\t}\n\n\tif kc.ContainerRuntimeEndpoint == \"\" {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: the containerRuntimeEndpoint was not specified or empty\"))\n\t}\n\n\tif kc.EnableSystemLogQuery \u0026\u0026 !localFeatureGate.Enabled(features.NodeLogQuery) {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid configuration: NodeLogQuery feature gate is required for enableSystemLogHandler\"))\n\t}\n\tif kc.EnableSystemLogQuery \u0026\u0026 !kc.EnableSystemLogHandler {\n\t\tallErrors = append(allErrors,\n\t\t\tfmt.Errorf(\"invalid configuration: enableSystemLogHandler is required for enableSystemLogQuery\"))\n\t}\n\n\treturn utilerrors.NewAggregate(allErrors)\n}","line":{"from":42,"to":274}} {"id":100005402,"name":"validateKubeletOSConfiguration","signature":"func validateKubeletOSConfiguration(kc *kubeletconfig.KubeletConfiguration) error","file":"pkg/kubelet/apis/config/validation/validation_others.go","code":"// validateKubeletOSConfiguration validates os specific kubelet configuration and returns an error if it is invalid.\nfunc validateKubeletOSConfiguration(kc *kubeletconfig.KubeletConfiguration) error {\n\treturn nil\n}","line":{"from":26,"to":29}} {"id":100005403,"name":"validateReservedMemoryConfiguration","signature":"func validateReservedMemoryConfiguration(kc *kubeletconfig.KubeletConfiguration) []error","file":"pkg/kubelet/apis/config/validation/validation_reserved_memory.go","code":"// validateReservedMemory validates the reserved memory configuration and returns an error if it is invalid.\nfunc validateReservedMemoryConfiguration(kc *kubeletconfig.KubeletConfiguration) []error {\n\tif len(kc.ReservedMemory) == 0 {\n\t\treturn nil\n\t}\n\n\tvar errors []error\n\n\tnumaTypeDuplicates := map[int32]map[v1.ResourceName]bool{}\n\tfor _, reservedMemory := range kc.ReservedMemory {\n\t\tnumaNode := reservedMemory.NumaNode\n\t\tif _, ok := numaTypeDuplicates[numaNode]; !ok {\n\t\t\tnumaTypeDuplicates[numaNode] = map[v1.ResourceName]bool{}\n\t\t}\n\n\t\tfor resourceName, q := range reservedMemory.Limits {\n\t\t\tif !reservedMemorySupportedLimit(resourceName) {\n\t\t\t\terrors = append(errors, fmt.Errorf(\"invalid configuration: the limit type %q for NUMA node %d is not supported, only %v is accepted\", resourceName, numaNode, []v1.ResourceName{v1.ResourceMemory, v1.ResourceHugePagesPrefix + \"\u003cHugePageSize\u003e\"}))\n\t\t\t}\n\n\t\t\t// validates that the limit has non-zero value\n\t\t\tif q.IsZero() {\n\t\t\t\terrors = append(errors, fmt.Errorf(\"invalid configuration: reserved memory may not be zero for NUMA node %d and resource %q\", numaNode, resourceName))\n\t\t\t}\n\n\t\t\t// validates that no duplication for NUMA node and limit type occurred\n\t\t\tif _, ok := numaTypeDuplicates[numaNode][resourceName]; ok {\n\t\t\t\terrors = append(errors, fmt.Errorf(\"invalid configuration: the reserved memory has a duplicate value for NUMA node %d and resource %q\", numaNode, resourceName))\n\t\t\t}\n\t\t\tnumaTypeDuplicates[numaNode][resourceName] = true\n\t\t}\n\t}\n\treturn errors\n}","line":{"from":27,"to":60}} {"id":100005404,"name":"reservedMemorySupportedLimit","signature":"func reservedMemorySupportedLimit(resourceName v1.ResourceName) bool","file":"pkg/kubelet/apis/config/validation/validation_reserved_memory.go","code":"func reservedMemorySupportedLimit(resourceName v1.ResourceName) bool {\n\treturn corev1helper.IsHugePageResourceName(resourceName) || resourceName == v1.ResourceMemory\n}","line":{"from":62,"to":64}} {"id":100005405,"name":"validateKubeletOSConfiguration","signature":"func validateKubeletOSConfiguration(kc *kubeletconfig.KubeletConfiguration) error","file":"pkg/kubelet/apis/config/validation/validation_windows.go","code":"// validateKubeletOSConfiguration validates os specific kubelet configuration and returns an error if it is invalid.\nfunc validateKubeletOSConfiguration(kc *kubeletconfig.KubeletConfiguration) error {\n\tmessage := \"invalid configuration: %v (%v) %v is not supported on Windows\"\n\tallErrors := []error{}\n\n\tif kc.CgroupsPerQOS {\n\t\tallErrors = append(allErrors, fmt.Errorf(message, \"CgroupsPerQOS\", \"--cgroups-per-qos\", kc.CgroupsPerQOS))\n\t}\n\n\tif len(kc.EnforceNodeAllocatable) \u003e 0 {\n\t\tallErrors = append(allErrors, fmt.Errorf(message, \"EnforceNodeAllocatable\", \"--enforce-node-allocatable\", kc.EnforceNodeAllocatable))\n\t}\n\n\treturn utilerrors.NewAggregate(allErrors)\n}","line":{"from":29,"to":43}} {"id":100005406,"name":"GetV1alpha1Client","signature":"func GetV1alpha1Client(socket string, connectionTimeout time.Duration, maxMsgSize int) (v1alpha1.PodResourcesListerClient, *grpc.ClientConn, error)","file":"pkg/kubelet/apis/podresources/client.go","code":"// GetV1alpha1Client returns a client for the PodResourcesLister grpc service\n// Note: This is deprecated\nfunc GetV1alpha1Client(socket string, connectionTimeout time.Duration, maxMsgSize int) (v1alpha1.PodResourcesListerClient, *grpc.ClientConn, error) {\n\taddr, dialer, err := util.GetAddressAndDialer(socket)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tctx, cancel := context.WithTimeout(context.Background(), connectionTimeout)\n\tdefer cancel()\n\n\tconn, err := grpc.DialContext(ctx, addr,\n\t\tgrpc.WithTransportCredentials(insecure.NewCredentials()),\n\t\tgrpc.WithContextDialer(dialer),\n\t\tgrpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(maxMsgSize)))\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"error dialing socket %s: %v\", socket, err)\n\t}\n\treturn v1alpha1.NewPodResourcesListerClient(conn), conn, nil\n}","line":{"from":35,"to":53}} {"id":100005407,"name":"GetV1Client","signature":"func GetV1Client(socket string, connectionTimeout time.Duration, maxMsgSize int) (v1.PodResourcesListerClient, *grpc.ClientConn, error)","file":"pkg/kubelet/apis/podresources/client.go","code":"// GetV1Client returns a client for the PodResourcesLister grpc service\nfunc GetV1Client(socket string, connectionTimeout time.Duration, maxMsgSize int) (v1.PodResourcesListerClient, *grpc.ClientConn, error) {\n\taddr, dialer, err := util.GetAddressAndDialer(socket)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tctx, cancel := context.WithTimeout(context.Background(), connectionTimeout)\n\tdefer cancel()\n\n\tconn, err := grpc.DialContext(ctx, addr,\n\t\tgrpc.WithTransportCredentials(insecure.NewCredentials()),\n\t\tgrpc.WithContextDialer(dialer),\n\t\tgrpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(maxMsgSize)))\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"error dialing socket %s: %v\", socket, err)\n\t}\n\treturn v1.NewPodResourcesListerClient(conn), conn, nil\n}","line":{"from":55,"to":72}} {"id":100005408,"name":"LimiterUnaryServerInterceptor","signature":"func LimiterUnaryServerInterceptor(limiter Limiter) grpc.UnaryServerInterceptor","file":"pkg/kubelet/apis/podresources/grpc/ratelimit.go","code":"// LimiterUnaryServerInterceptor returns a new unary server interceptors that performs request rate limiting.\nfunc LimiterUnaryServerInterceptor(limiter Limiter) grpc.UnaryServerInterceptor {\n\treturn func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {\n\t\tif !limiter.Allow() {\n\t\t\treturn nil, ErrorLimitExceeded\n\t\t}\n\t\treturn handler(ctx, req)\n\t}\n}","line":{"from":52,"to":60}} {"id":100005409,"name":"WithRateLimiter","signature":"func WithRateLimiter(qps, burstTokens int32) grpc.ServerOption","file":"pkg/kubelet/apis/podresources/grpc/ratelimit.go","code":"func WithRateLimiter(qps, burstTokens int32) grpc.ServerOption {\n\tqpsVal := gotimerate.Limit(qps)\n\tburstVal := int(burstTokens)\n\tklog.InfoS(\"Setting rate limiting for podresources endpoint\", \"qps\", qpsVal, \"burstTokens\", burstVal)\n\treturn grpc.UnaryInterceptor(LimiterUnaryServerInterceptor(gotimerate.NewLimiter(qpsVal, burstVal)))\n}","line":{"from":62,"to":67}} {"id":100005410,"name":"NewV1PodResourcesServer","signature":"func NewV1PodResourcesServer(providers PodResourcesProviders) v1.PodResourcesListerServer","file":"pkg/kubelet/apis/podresources/server_v1.go","code":"// NewV1PodResourcesServer returns a PodResourcesListerServer which lists pods provided by the PodsProvider\n// with device information provided by the DevicesProvider\nfunc NewV1PodResourcesServer(providers PodResourcesProviders) v1.PodResourcesListerServer {\n\treturn \u0026v1PodResourcesServer{\n\t\tpodsProvider: providers.Pods,\n\t\tdevicesProvider: providers.Devices,\n\t\tcpusProvider: providers.Cpus,\n\t\tmemoryProvider: providers.Memory,\n\t\tdynamicResourcesProvider: providers.DynamicResources,\n\t}\n}","line":{"from":39,"to":49}} {"id":100005411,"name":"List","signature":"func (p *v1PodResourcesServer) List(ctx context.Context, req *v1.ListPodResourcesRequest) (*v1.ListPodResourcesResponse, error)","file":"pkg/kubelet/apis/podresources/server_v1.go","code":"// List returns information about the resources assigned to pods on the node\nfunc (p *v1PodResourcesServer) List(ctx context.Context, req *v1.ListPodResourcesRequest) (*v1.ListPodResourcesResponse, error) {\n\tmetrics.PodResourcesEndpointRequestsTotalCount.WithLabelValues(\"v1\").Inc()\n\tmetrics.PodResourcesEndpointRequestsListCount.WithLabelValues(\"v1\").Inc()\n\n\tpods := p.podsProvider.GetPods()\n\tpodResources := make([]*v1.PodResources, len(pods))\n\tp.devicesProvider.UpdateAllocatedDevices()\n\n\tfor i, pod := range pods {\n\t\tpRes := v1.PodResources{\n\t\t\tName: pod.Name,\n\t\t\tNamespace: pod.Namespace,\n\t\t\tContainers: make([]*v1.ContainerResources, len(pod.Spec.Containers)),\n\t\t}\n\n\t\tfor j, container := range pod.Spec.Containers {\n\t\t\tpRes.Containers[j] = \u0026v1.ContainerResources{\n\t\t\t\tName: container.Name,\n\t\t\t\tDevices: p.devicesProvider.GetDevices(string(pod.UID), container.Name),\n\t\t\t\tCpuIds: p.cpusProvider.GetCPUs(string(pod.UID), container.Name),\n\t\t\t\tMemory: p.memoryProvider.GetMemory(string(pod.UID), container.Name),\n\t\t\t}\n\t\t\tif utilfeature.DefaultFeatureGate.Enabled(kubefeatures.KubeletPodResourcesDynamicResources) {\n\t\t\t\tpRes.Containers[j].DynamicResources = p.dynamicResourcesProvider.GetDynamicResources(pod, \u0026container)\n\t\t\t}\n\n\t\t}\n\t\tpodResources[i] = \u0026pRes\n\t}\n\n\treturn \u0026v1.ListPodResourcesResponse{\n\t\tPodResources: podResources,\n\t}, nil\n}","line":{"from":51,"to":85}} {"id":100005412,"name":"GetAllocatableResources","signature":"func (p *v1PodResourcesServer) GetAllocatableResources(ctx context.Context, req *v1.AllocatableResourcesRequest) (*v1.AllocatableResourcesResponse, error)","file":"pkg/kubelet/apis/podresources/server_v1.go","code":"// GetAllocatableResources returns information about all the resources known by the server - this more like the capacity, not like the current amount of free resources.\nfunc (p *v1PodResourcesServer) GetAllocatableResources(ctx context.Context, req *v1.AllocatableResourcesRequest) (*v1.AllocatableResourcesResponse, error) {\n\tmetrics.PodResourcesEndpointRequestsTotalCount.WithLabelValues(\"v1\").Inc()\n\tmetrics.PodResourcesEndpointRequestsGetAllocatableCount.WithLabelValues(\"v1\").Inc()\n\n\tif !utilfeature.DefaultFeatureGate.Enabled(kubefeatures.KubeletPodResourcesGetAllocatable) {\n\t\tmetrics.PodResourcesEndpointErrorsGetAllocatableCount.WithLabelValues(\"v1\").Inc()\n\t\treturn nil, fmt.Errorf(\"PodResources API GetAllocatableResources disabled\")\n\t}\n\n\treturn \u0026v1.AllocatableResourcesResponse{\n\t\tDevices: p.devicesProvider.GetAllocatableDevices(),\n\t\tCpuIds: p.cpusProvider.GetAllocatableCPUs(),\n\t\tMemory: p.memoryProvider.GetAllocatableMemory(),\n\t}, nil\n}","line":{"from":87,"to":102}} {"id":100005413,"name":"Get","signature":"func (p *v1PodResourcesServer) Get(ctx context.Context, req *v1.GetPodResourcesRequest) (*v1.GetPodResourcesResponse, error)","file":"pkg/kubelet/apis/podresources/server_v1.go","code":"// Get returns information about the resources assigned to a specific pod\nfunc (p *v1PodResourcesServer) Get(ctx context.Context, req *v1.GetPodResourcesRequest) (*v1.GetPodResourcesResponse, error) {\n\tmetrics.PodResourcesEndpointRequestsTotalCount.WithLabelValues(\"v1\").Inc()\n\tmetrics.PodResourcesEndpointRequestsGetCount.WithLabelValues(\"v1\").Inc()\n\n\tif !utilfeature.DefaultFeatureGate.Enabled(kubefeatures.KubeletPodResourcesGet) {\n\t\tmetrics.PodResourcesEndpointErrorsGetCount.WithLabelValues(\"v1\").Inc()\n\t\treturn nil, fmt.Errorf(\"PodResources API Get method disabled\")\n\t}\n\n\tpod, exist := p.podsProvider.GetPodByName(req.PodNamespace, req.PodName)\n\tif !exist {\n\t\tmetrics.PodResourcesEndpointErrorsGetCount.WithLabelValues(\"v1\").Inc()\n\t\treturn nil, fmt.Errorf(\"pod %s in namespace %s not found\", req.PodName, req.PodNamespace)\n\t}\n\n\tpodResources := \u0026v1.PodResources{\n\t\tName: pod.Name,\n\t\tNamespace: pod.Namespace,\n\t\tContainers: make([]*v1.ContainerResources, len(pod.Spec.Containers)),\n\t}\n\n\tfor i, container := range pod.Spec.Containers {\n\t\tpodResources.Containers[i] = \u0026v1.ContainerResources{\n\t\t\tName: container.Name,\n\t\t\tDevices: p.devicesProvider.GetDevices(string(pod.UID), container.Name),\n\t\t\tCpuIds: p.cpusProvider.GetCPUs(string(pod.UID), container.Name),\n\t\t\tMemory: p.memoryProvider.GetMemory(string(pod.UID), container.Name),\n\t\t}\n\t\tif utilfeature.DefaultFeatureGate.Enabled(kubefeatures.KubeletPodResourcesDynamicResources) {\n\t\t\tpodResources.Containers[i].DynamicResources = p.dynamicResourcesProvider.GetDynamicResources(pod, \u0026container)\n\t\t}\n\t}\n\n\tresponse := \u0026v1.GetPodResourcesResponse{\n\t\tPodResources: podResources,\n\t}\n\treturn response, nil\n}","line":{"from":104,"to":142}} {"id":100005414,"name":"NewV1alpha1PodResourcesServer","signature":"func NewV1alpha1PodResourcesServer(providers PodResourcesProviders) v1alpha1.PodResourcesListerServer","file":"pkg/kubelet/apis/podresources/server_v1alpha1.go","code":"// NewV1alpha1PodResourcesServer returns a PodResourcesListerServer which lists pods provided by the PodsProvider\n// with device information provided by the DevicesProvider\nfunc NewV1alpha1PodResourcesServer(providers PodResourcesProviders) v1alpha1.PodResourcesListerServer {\n\treturn \u0026v1alpha1PodResourcesServer{\n\t\tpodsProvider: providers.Pods,\n\t\tdevicesProvider: providers.Devices,\n\t}\n}","line":{"from":34,"to":41}} {"id":100005415,"name":"v1DevicesToAlphaV1","signature":"func v1DevicesToAlphaV1(alphaDevs []*v1.ContainerDevices) []*v1alpha1.ContainerDevices","file":"pkg/kubelet/apis/podresources/server_v1alpha1.go","code":"func v1DevicesToAlphaV1(alphaDevs []*v1.ContainerDevices) []*v1alpha1.ContainerDevices {\n\tvar devs []*v1alpha1.ContainerDevices\n\tfor _, alphaDev := range alphaDevs {\n\t\tdev := v1alpha1.ContainerDevices{\n\t\t\tResourceName: alphaDev.ResourceName,\n\t\t\tDeviceIds: alphaDev.DeviceIds,\n\t\t}\n\t\tdevs = append(devs, \u0026dev)\n\t}\n\n\treturn devs\n}","line":{"from":43,"to":54}} {"id":100005416,"name":"List","signature":"func (p *v1alpha1PodResourcesServer) List(ctx context.Context, req *v1alpha1.ListPodResourcesRequest) (*v1alpha1.ListPodResourcesResponse, error)","file":"pkg/kubelet/apis/podresources/server_v1alpha1.go","code":"// List returns information about the resources assigned to pods on the node\nfunc (p *v1alpha1PodResourcesServer) List(ctx context.Context, req *v1alpha1.ListPodResourcesRequest) (*v1alpha1.ListPodResourcesResponse, error) {\n\tmetrics.PodResourcesEndpointRequestsTotalCount.WithLabelValues(\"v1alpha1\").Inc()\n\tpods := p.podsProvider.GetPods()\n\tpodResources := make([]*v1alpha1.PodResources, len(pods))\n\tp.devicesProvider.UpdateAllocatedDevices()\n\n\tfor i, pod := range pods {\n\t\tpRes := v1alpha1.PodResources{\n\t\t\tName: pod.Name,\n\t\t\tNamespace: pod.Namespace,\n\t\t\tContainers: make([]*v1alpha1.ContainerResources, len(pod.Spec.Containers)),\n\t\t}\n\n\t\tfor j, container := range pod.Spec.Containers {\n\t\t\tpRes.Containers[j] = \u0026v1alpha1.ContainerResources{\n\t\t\t\tName: container.Name,\n\t\t\t\tDevices: v1DevicesToAlphaV1(p.devicesProvider.GetDevices(string(pod.UID), container.Name)),\n\t\t\t}\n\t\t}\n\t\tpodResources[i] = \u0026pRes\n\t}\n\n\treturn \u0026v1alpha1.ListPodResourcesResponse{\n\t\tPodResources: podResources,\n\t}, nil\n}","line":{"from":56,"to":82}} {"id":100005417,"name":"init","signature":"func init()","file":"pkg/kubelet/cadvisor/cadvisor_linux.go","code":"func init() {\n\t// Override cAdvisor flag defaults.\n\tflagOverrides := map[string]string{\n\t\t// Override the default cAdvisor housekeeping interval.\n\t\t\"housekeeping_interval\": defaultHousekeepingInterval.String(),\n\t\t// Disable event storage by default.\n\t\t\"event_storage_event_limit\": \"default=0\",\n\t\t\"event_storage_age_limit\": \"default=0\",\n\t}\n\tfor name, defaultValue := range flagOverrides {\n\t\tif f := flag.Lookup(name); f != nil {\n\t\t\tf.DefValue = defaultValue\n\t\t\tf.Value.Set(defaultValue)\n\t\t} else {\n\t\t\tklog.ErrorS(nil, \"Expected cAdvisor flag not found\", \"flag\", name)\n\t\t}\n\t}\n}","line":{"from":61,"to":78}} {"id":100005418,"name":"New","signature":"func New(imageFsInfoProvider ImageFsInfoProvider, rootPath string, cgroupRoots []string, usingLegacyStats, localStorageCapacityIsolation bool) (Interface, error)","file":"pkg/kubelet/cadvisor/cadvisor_linux.go","code":"// New creates a new cAdvisor Interface for linux systems.\nfunc New(imageFsInfoProvider ImageFsInfoProvider, rootPath string, cgroupRoots []string, usingLegacyStats, localStorageCapacityIsolation bool) (Interface, error) {\n\tsysFs := sysfs.NewRealSysFs()\n\n\tincludedMetrics := cadvisormetrics.MetricSet{\n\t\tcadvisormetrics.CpuUsageMetrics: struct{}{},\n\t\tcadvisormetrics.MemoryUsageMetrics: struct{}{},\n\t\tcadvisormetrics.CpuLoadMetrics: struct{}{},\n\t\tcadvisormetrics.DiskIOMetrics: struct{}{},\n\t\tcadvisormetrics.NetworkUsageMetrics: struct{}{},\n\t\tcadvisormetrics.AppMetrics: struct{}{},\n\t\tcadvisormetrics.ProcessMetrics: struct{}{},\n\t\tcadvisormetrics.OOMMetrics: struct{}{},\n\t}\n\n\tif usingLegacyStats || localStorageCapacityIsolation {\n\t\tincludedMetrics[cadvisormetrics.DiskUsageMetrics] = struct{}{}\n\t}\n\n\tduration := maxHousekeepingInterval\n\thousekeepingConfig := manager.HouskeepingConfig{\n\t\tInterval: \u0026duration,\n\t\tAllowDynamic: pointer.Bool(allowDynamicHousekeeping),\n\t}\n\n\t// Create the cAdvisor container manager.\n\tm, err := manager.New(memory.New(statsCacheDuration, nil), sysFs, housekeepingConfig, includedMetrics, http.DefaultClient, cgroupRoots, nil /* containerEnvMetadataWhiteList */, \"\" /* perfEventsFile */, time.Duration(0) /*resctrlInterval*/)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif _, err := os.Stat(rootPath); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tif err := os.MkdirAll(path.Clean(rootPath), 0750); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error creating root directory %q: %v\", rootPath, err)\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"failed to Stat %q: %v\", rootPath, err)\n\t\t}\n\t}\n\n\treturn \u0026cadvisorClient{\n\t\timageFsInfoProvider: imageFsInfoProvider,\n\t\trootPath: rootPath,\n\t\tManager: m,\n\t}, nil\n}","line":{"from":80,"to":126}} {"id":100005419,"name":"Start","signature":"func (cc *cadvisorClient) Start() error","file":"pkg/kubelet/cadvisor/cadvisor_linux.go","code":"func (cc *cadvisorClient) Start() error {\n\treturn cc.Manager.Start()\n}","line":{"from":128,"to":130}} {"id":100005420,"name":"ContainerInfo","signature":"func (cc *cadvisorClient) ContainerInfo(name string, req *cadvisorapi.ContainerInfoRequest) (*cadvisorapi.ContainerInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_linux.go","code":"func (cc *cadvisorClient) ContainerInfo(name string, req *cadvisorapi.ContainerInfoRequest) (*cadvisorapi.ContainerInfo, error) {\n\treturn cc.GetContainerInfo(name, req)\n}","line":{"from":132,"to":134}} {"id":100005421,"name":"ContainerInfoV2","signature":"func (cc *cadvisorClient) ContainerInfoV2(name string, options cadvisorapiv2.RequestOptions) (map[string]cadvisorapiv2.ContainerInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_linux.go","code":"func (cc *cadvisorClient) ContainerInfoV2(name string, options cadvisorapiv2.RequestOptions) (map[string]cadvisorapiv2.ContainerInfo, error) {\n\treturn cc.GetContainerInfoV2(name, options)\n}","line":{"from":136,"to":138}} {"id":100005422,"name":"VersionInfo","signature":"func (cc *cadvisorClient) VersionInfo() (*cadvisorapi.VersionInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_linux.go","code":"func (cc *cadvisorClient) VersionInfo() (*cadvisorapi.VersionInfo, error) {\n\treturn cc.GetVersionInfo()\n}","line":{"from":140,"to":142}} {"id":100005423,"name":"SubcontainerInfo","signature":"func (cc *cadvisorClient) SubcontainerInfo(name string, req *cadvisorapi.ContainerInfoRequest) (map[string]*cadvisorapi.ContainerInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_linux.go","code":"func (cc *cadvisorClient) SubcontainerInfo(name string, req *cadvisorapi.ContainerInfoRequest) (map[string]*cadvisorapi.ContainerInfo, error) {\n\tinfos, err := cc.SubcontainersInfo(name, req)\n\tif err != nil \u0026\u0026 len(infos) == 0 {\n\t\treturn nil, err\n\t}\n\n\tresult := make(map[string]*cadvisorapi.ContainerInfo, len(infos))\n\tfor _, info := range infos {\n\t\tresult[info.Name] = info\n\t}\n\treturn result, err\n}","line":{"from":144,"to":155}} {"id":100005424,"name":"MachineInfo","signature":"func (cc *cadvisorClient) MachineInfo() (*cadvisorapi.MachineInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_linux.go","code":"func (cc *cadvisorClient) MachineInfo() (*cadvisorapi.MachineInfo, error) {\n\treturn cc.GetMachineInfo()\n}","line":{"from":157,"to":159}} {"id":100005425,"name":"ImagesFsInfo","signature":"func (cc *cadvisorClient) ImagesFsInfo() (cadvisorapiv2.FsInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_linux.go","code":"func (cc *cadvisorClient) ImagesFsInfo() (cadvisorapiv2.FsInfo, error) {\n\tlabel, err := cc.imageFsInfoProvider.ImageFsInfoLabel()\n\tif err != nil {\n\t\treturn cadvisorapiv2.FsInfo{}, err\n\t}\n\treturn cc.getFsInfo(label)\n}","line":{"from":161,"to":167}} {"id":100005426,"name":"RootFsInfo","signature":"func (cc *cadvisorClient) RootFsInfo() (cadvisorapiv2.FsInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_linux.go","code":"func (cc *cadvisorClient) RootFsInfo() (cadvisorapiv2.FsInfo, error) {\n\treturn cc.GetDirFsInfo(cc.rootPath)\n}","line":{"from":169,"to":171}} {"id":100005427,"name":"getFsInfo","signature":"func (cc *cadvisorClient) getFsInfo(label string) (cadvisorapiv2.FsInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_linux.go","code":"func (cc *cadvisorClient) getFsInfo(label string) (cadvisorapiv2.FsInfo, error) {\n\tres, err := cc.GetFsInfo(label)\n\tif err != nil {\n\t\treturn cadvisorapiv2.FsInfo{}, err\n\t}\n\tif len(res) == 0 {\n\t\treturn cadvisorapiv2.FsInfo{}, fmt.Errorf(\"failed to find information for the filesystem labeled %q\", label)\n\t}\n\t// TODO(vmarmol): Handle this better when a label has more than one image filesystem.\n\tif len(res) \u003e 1 {\n\t\tklog.InfoS(\"More than one filesystem labeled. Only using the first one\", \"label\", label, \"fileSystem\", res)\n\t}\n\n\treturn res[0], nil\n}","line":{"from":173,"to":187}} {"id":100005428,"name":"WatchEvents","signature":"func (cc *cadvisorClient) WatchEvents(request *events.Request) (*events.EventChannel, error)","file":"pkg/kubelet/cadvisor/cadvisor_linux.go","code":"func (cc *cadvisorClient) WatchEvents(request *events.Request) (*events.EventChannel, error) {\n\treturn cc.WatchForEvents(request)\n}","line":{"from":189,"to":191}} {"id":100005429,"name":"New","signature":"func New(imageFsInfoProvider ImageFsInfoProvider, rootPath string, cgroupsRoots []string, usingLegacyStats, localStorageCapacityIsolation bool) (Interface, error)","file":"pkg/kubelet/cadvisor/cadvisor_unsupported.go","code":"// New creates a new cAdvisor Interface for unsupported systems.\nfunc New(imageFsInfoProvider ImageFsInfoProvider, rootPath string, cgroupsRoots []string, usingLegacyStats, localStorageCapacityIsolation bool) (Interface, error) {\n\treturn \u0026cadvisorUnsupported{}, nil\n}","line":{"from":35,"to":38}} {"id":100005430,"name":"Start","signature":"func (cu *cadvisorUnsupported) Start() error","file":"pkg/kubelet/cadvisor/cadvisor_unsupported.go","code":"func (cu *cadvisorUnsupported) Start() error {\n\treturn errUnsupported\n}","line":{"from":42,"to":44}} {"id":100005431,"name":"DockerContainer","signature":"func (cu *cadvisorUnsupported) DockerContainer(name string, req *cadvisorapi.ContainerInfoRequest) (cadvisorapi.ContainerInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_unsupported.go","code":"func (cu *cadvisorUnsupported) DockerContainer(name string, req *cadvisorapi.ContainerInfoRequest) (cadvisorapi.ContainerInfo, error) {\n\treturn cadvisorapi.ContainerInfo{}, errUnsupported\n}","line":{"from":46,"to":48}} {"id":100005432,"name":"ContainerInfo","signature":"func (cu *cadvisorUnsupported) ContainerInfo(name string, req *cadvisorapi.ContainerInfoRequest) (*cadvisorapi.ContainerInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_unsupported.go","code":"func (cu *cadvisorUnsupported) ContainerInfo(name string, req *cadvisorapi.ContainerInfoRequest) (*cadvisorapi.ContainerInfo, error) {\n\treturn nil, errUnsupported\n}","line":{"from":50,"to":52}} {"id":100005433,"name":"ContainerInfoV2","signature":"func (cu *cadvisorUnsupported) ContainerInfoV2(name string, options cadvisorapiv2.RequestOptions) (map[string]cadvisorapiv2.ContainerInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_unsupported.go","code":"func (cu *cadvisorUnsupported) ContainerInfoV2(name string, options cadvisorapiv2.RequestOptions) (map[string]cadvisorapiv2.ContainerInfo, error) {\n\treturn nil, errUnsupported\n}","line":{"from":54,"to":56}} {"id":100005434,"name":"GetRequestedContainersInfo","signature":"func (cu *cadvisorUnsupported) GetRequestedContainersInfo(containerName string, options cadvisorapiv2.RequestOptions) (map[string]*cadvisorapi.ContainerInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_unsupported.go","code":"func (cu *cadvisorUnsupported) GetRequestedContainersInfo(containerName string, options cadvisorapiv2.RequestOptions) (map[string]*cadvisorapi.ContainerInfo, error) {\n\treturn nil, errUnsupported\n}","line":{"from":58,"to":60}} {"id":100005435,"name":"SubcontainerInfo","signature":"func (cu *cadvisorUnsupported) SubcontainerInfo(name string, req *cadvisorapi.ContainerInfoRequest) (map[string]*cadvisorapi.ContainerInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_unsupported.go","code":"func (cu *cadvisorUnsupported) SubcontainerInfo(name string, req *cadvisorapi.ContainerInfoRequest) (map[string]*cadvisorapi.ContainerInfo, error) {\n\treturn nil, errUnsupported\n}","line":{"from":62,"to":64}} {"id":100005436,"name":"MachineInfo","signature":"func (cu *cadvisorUnsupported) MachineInfo() (*cadvisorapi.MachineInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_unsupported.go","code":"func (cu *cadvisorUnsupported) MachineInfo() (*cadvisorapi.MachineInfo, error) {\n\treturn nil, errUnsupported\n}","line":{"from":66,"to":68}} {"id":100005437,"name":"VersionInfo","signature":"func (cu *cadvisorUnsupported) VersionInfo() (*cadvisorapi.VersionInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_unsupported.go","code":"func (cu *cadvisorUnsupported) VersionInfo() (*cadvisorapi.VersionInfo, error) {\n\treturn nil, errUnsupported\n}","line":{"from":70,"to":72}} {"id":100005438,"name":"ImagesFsInfo","signature":"func (cu *cadvisorUnsupported) ImagesFsInfo() (cadvisorapiv2.FsInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_unsupported.go","code":"func (cu *cadvisorUnsupported) ImagesFsInfo() (cadvisorapiv2.FsInfo, error) {\n\treturn cadvisorapiv2.FsInfo{}, errUnsupported\n}","line":{"from":74,"to":76}} {"id":100005439,"name":"RootFsInfo","signature":"func (cu *cadvisorUnsupported) RootFsInfo() (cadvisorapiv2.FsInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_unsupported.go","code":"func (cu *cadvisorUnsupported) RootFsInfo() (cadvisorapiv2.FsInfo, error) {\n\treturn cadvisorapiv2.FsInfo{}, errUnsupported\n}","line":{"from":78,"to":80}} {"id":100005440,"name":"WatchEvents","signature":"func (cu *cadvisorUnsupported) WatchEvents(request *events.Request) (*events.EventChannel, error)","file":"pkg/kubelet/cadvisor/cadvisor_unsupported.go","code":"func (cu *cadvisorUnsupported) WatchEvents(request *events.Request) (*events.EventChannel, error) {\n\treturn nil, errUnsupported\n}","line":{"from":82,"to":84}} {"id":100005441,"name":"GetDirFsInfo","signature":"func (cu *cadvisorUnsupported) GetDirFsInfo(path string) (cadvisorapiv2.FsInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_unsupported.go","code":"func (cu *cadvisorUnsupported) GetDirFsInfo(path string) (cadvisorapiv2.FsInfo, error) {\n\treturn cadvisorapiv2.FsInfo{}, nil\n}","line":{"from":86,"to":88}} {"id":100005442,"name":"New","signature":"func New(imageFsInfoProvider ImageFsInfoProvider, rootPath string, cgroupRoots []string, usingLegacyStats, localStorageCapacityIsolation bool) (Interface, error)","file":"pkg/kubelet/cadvisor/cadvisor_windows.go","code":"// New creates a cAdvisor and exports its API on the specified port if port \u003e 0.\nfunc New(imageFsInfoProvider ImageFsInfoProvider, rootPath string, cgroupRoots []string, usingLegacyStats, localStorageCapacityIsolation bool) (Interface, error) {\n\tclient, err := winstats.NewPerfCounterClient()\n\treturn \u0026cadvisorClient{\n\t\trootPath: rootPath,\n\t\twinStatsClient: client,\n\t}, err\n}","line":{"from":36,"to":43}} {"id":100005443,"name":"Start","signature":"func (cu *cadvisorClient) Start() error","file":"pkg/kubelet/cadvisor/cadvisor_windows.go","code":"func (cu *cadvisorClient) Start() error {\n\treturn nil\n}","line":{"from":45,"to":47}} {"id":100005444,"name":"DockerContainer","signature":"func (cu *cadvisorClient) DockerContainer(name string, req *cadvisorapi.ContainerInfoRequest) (cadvisorapi.ContainerInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_windows.go","code":"func (cu *cadvisorClient) DockerContainer(name string, req *cadvisorapi.ContainerInfoRequest) (cadvisorapi.ContainerInfo, error) {\n\treturn cadvisorapi.ContainerInfo{}, nil\n}","line":{"from":49,"to":51}} {"id":100005445,"name":"ContainerInfo","signature":"func (cu *cadvisorClient) ContainerInfo(name string, req *cadvisorapi.ContainerInfoRequest) (*cadvisorapi.ContainerInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_windows.go","code":"func (cu *cadvisorClient) ContainerInfo(name string, req *cadvisorapi.ContainerInfoRequest) (*cadvisorapi.ContainerInfo, error) {\n\treturn \u0026cadvisorapi.ContainerInfo{}, nil\n}","line":{"from":53,"to":55}} {"id":100005446,"name":"ContainerInfoV2","signature":"func (cu *cadvisorClient) ContainerInfoV2(name string, options cadvisorapiv2.RequestOptions) (map[string]cadvisorapiv2.ContainerInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_windows.go","code":"// ContainerInfoV2 is only expected to be used for the root container. Returns info for all containers in the node.\nfunc (cu *cadvisorClient) ContainerInfoV2(name string, options cadvisorapiv2.RequestOptions) (map[string]cadvisorapiv2.ContainerInfo, error) {\n\treturn cu.winStatsClient.WinContainerInfos()\n}","line":{"from":57,"to":60}} {"id":100005447,"name":"GetRequestedContainersInfo","signature":"func (cu *cadvisorClient) GetRequestedContainersInfo(containerName string, options cadvisorapiv2.RequestOptions) (map[string]*cadvisorapi.ContainerInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_windows.go","code":"func (cu *cadvisorClient) GetRequestedContainersInfo(containerName string, options cadvisorapiv2.RequestOptions) (map[string]*cadvisorapi.ContainerInfo, error) {\n\treturn nil, nil\n}","line":{"from":62,"to":64}} {"id":100005448,"name":"SubcontainerInfo","signature":"func (cu *cadvisorClient) SubcontainerInfo(name string, req *cadvisorapi.ContainerInfoRequest) (map[string]*cadvisorapi.ContainerInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_windows.go","code":"func (cu *cadvisorClient) SubcontainerInfo(name string, req *cadvisorapi.ContainerInfoRequest) (map[string]*cadvisorapi.ContainerInfo, error) {\n\treturn nil, nil\n}","line":{"from":66,"to":68}} {"id":100005449,"name":"MachineInfo","signature":"func (cu *cadvisorClient) MachineInfo() (*cadvisorapi.MachineInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_windows.go","code":"func (cu *cadvisorClient) MachineInfo() (*cadvisorapi.MachineInfo, error) {\n\treturn cu.winStatsClient.WinMachineInfo()\n}","line":{"from":70,"to":72}} {"id":100005450,"name":"VersionInfo","signature":"func (cu *cadvisorClient) VersionInfo() (*cadvisorapi.VersionInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_windows.go","code":"func (cu *cadvisorClient) VersionInfo() (*cadvisorapi.VersionInfo, error) {\n\treturn cu.winStatsClient.WinVersionInfo()\n}","line":{"from":74,"to":76}} {"id":100005451,"name":"ImagesFsInfo","signature":"func (cu *cadvisorClient) ImagesFsInfo() (cadvisorapiv2.FsInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_windows.go","code":"func (cu *cadvisorClient) ImagesFsInfo() (cadvisorapiv2.FsInfo, error) {\n\treturn cadvisorapiv2.FsInfo{}, nil\n}","line":{"from":78,"to":80}} {"id":100005452,"name":"RootFsInfo","signature":"func (cu *cadvisorClient) RootFsInfo() (cadvisorapiv2.FsInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_windows.go","code":"func (cu *cadvisorClient) RootFsInfo() (cadvisorapiv2.FsInfo, error) {\n\treturn cu.GetDirFsInfo(cu.rootPath)\n}","line":{"from":82,"to":84}} {"id":100005453,"name":"WatchEvents","signature":"func (cu *cadvisorClient) WatchEvents(request *events.Request) (*events.EventChannel, error)","file":"pkg/kubelet/cadvisor/cadvisor_windows.go","code":"func (cu *cadvisorClient) WatchEvents(request *events.Request) (*events.EventChannel, error) {\n\treturn \u0026events.EventChannel{}, nil\n}","line":{"from":86,"to":88}} {"id":100005454,"name":"GetDirFsInfo","signature":"func (cu *cadvisorClient) GetDirFsInfo(path string) (cadvisorapiv2.FsInfo, error)","file":"pkg/kubelet/cadvisor/cadvisor_windows.go","code":"func (cu *cadvisorClient) GetDirFsInfo(path string) (cadvisorapiv2.FsInfo, error) {\n\treturn cu.winStatsClient.GetDirFsInfo(path)\n}","line":{"from":90,"to":92}} {"id":100005455,"name":"ImageFsInfoLabel","signature":"func (i *imageFsInfoProvider) ImageFsInfoLabel() (string, error)","file":"pkg/kubelet/cadvisor/helpers_linux.go","code":"// ImageFsInfoLabel returns the image fs label for the configured runtime.\n// For remote runtimes, it handles additional runtimes natively understood by cAdvisor.\nfunc (i *imageFsInfoProvider) ImageFsInfoLabel() (string, error) {\n\t// This is a temporary workaround to get stats for cri-o from cadvisor\n\t// and should be removed.\n\t// Related to https://github.com/kubernetes/kubernetes/issues/51798\n\tif i.runtimeEndpoint == CrioSocket || i.runtimeEndpoint == \"unix://\"+CrioSocket {\n\t\treturn cadvisorfs.LabelCrioImages, nil\n\t}\n\treturn \"\", fmt.Errorf(\"no imagefs label for configured runtime\")\n}","line":{"from":34,"to":44}} {"id":100005456,"name":"NewImageFsInfoProvider","signature":"func NewImageFsInfoProvider(runtimeEndpoint string) ImageFsInfoProvider","file":"pkg/kubelet/cadvisor/helpers_linux.go","code":"// NewImageFsInfoProvider returns a provider for the specified runtime configuration.\nfunc NewImageFsInfoProvider(runtimeEndpoint string) ImageFsInfoProvider {\n\treturn \u0026imageFsInfoProvider{runtimeEndpoint: runtimeEndpoint}\n}","line":{"from":46,"to":49}} {"id":100005457,"name":"ImageFsInfoLabel","signature":"func (i *unsupportedImageFsInfoProvider) ImageFsInfoLabel() (string, error)","file":"pkg/kubelet/cadvisor/helpers_unsupported.go","code":"// ImageFsInfoLabel returns the image fs label for the configured runtime.\n// For remote runtimes, it handles additional runtimes natively understood by cAdvisor.\nfunc (i *unsupportedImageFsInfoProvider) ImageFsInfoLabel() (string, error) {\n\treturn \"\", errors.New(\"unsupported\")\n}","line":{"from":26,"to":30}} {"id":100005458,"name":"NewImageFsInfoProvider","signature":"func NewImageFsInfoProvider(runtimeEndpoint string) ImageFsInfoProvider","file":"pkg/kubelet/cadvisor/helpers_unsupported.go","code":"// NewImageFsInfoProvider returns a provider for the specified runtime configuration.\nfunc NewImageFsInfoProvider(runtimeEndpoint string) ImageFsInfoProvider {\n\treturn \u0026unsupportedImageFsInfoProvider{}\n}","line":{"from":32,"to":35}} {"id":100005459,"name":"CapacityFromMachineInfo","signature":"func CapacityFromMachineInfo(info *cadvisorapi.MachineInfo) v1.ResourceList","file":"pkg/kubelet/cadvisor/util.go","code":"// CapacityFromMachineInfo returns the capacity of the resources from the machine info.\nfunc CapacityFromMachineInfo(info *cadvisorapi.MachineInfo) v1.ResourceList {\n\tc := v1.ResourceList{\n\t\tv1.ResourceCPU: *resource.NewMilliQuantity(\n\t\t\tint64(info.NumCores*1000),\n\t\t\tresource.DecimalSI),\n\t\tv1.ResourceMemory: *resource.NewQuantity(\n\t\t\tint64(info.MemoryCapacity),\n\t\t\tresource.BinarySI),\n\t}\n\n\t// if huge pages are enabled, we report them as a schedulable resource on the node\n\tfor _, hugepagesInfo := range info.HugePages {\n\t\tpageSizeBytes := int64(hugepagesInfo.PageSize * 1024)\n\t\thugePagesBytes := pageSizeBytes * int64(hugepagesInfo.NumPages)\n\t\tpageSizeQuantity := resource.NewQuantity(pageSizeBytes, resource.BinarySI)\n\t\tc[v1helper.HugePageResourceName(*pageSizeQuantity)] = *resource.NewQuantity(hugePagesBytes, resource.BinarySI)\n\t}\n\n\treturn c\n}","line":{"from":34,"to":54}} {"id":100005460,"name":"EphemeralStorageCapacityFromFsInfo","signature":"func EphemeralStorageCapacityFromFsInfo(info cadvisorapi2.FsInfo) v1.ResourceList","file":"pkg/kubelet/cadvisor/util.go","code":"// EphemeralStorageCapacityFromFsInfo returns the capacity of the ephemeral storage from the FsInfo.\nfunc EphemeralStorageCapacityFromFsInfo(info cadvisorapi2.FsInfo) v1.ResourceList {\n\tc := v1.ResourceList{\n\t\tv1.ResourceEphemeralStorage: *resource.NewQuantity(\n\t\t\tint64(info.Capacity),\n\t\t\tresource.BinarySI),\n\t}\n\treturn c\n}","line":{"from":56,"to":64}} {"id":100005461,"name":"UsingLegacyCadvisorStats","signature":"func UsingLegacyCadvisorStats(runtimeEndpoint string) bool","file":"pkg/kubelet/cadvisor/util.go","code":"// UsingLegacyCadvisorStats returns true if container stats are provided by cadvisor instead of through the CRI.\n// CRI integrations should get container metrics via CRI.\n// TODO: cri-o relies on cadvisor as a temporary workaround. The code should\n// be removed. Related issue:\n// https://github.com/kubernetes/kubernetes/issues/51798\nfunc UsingLegacyCadvisorStats(runtimeEndpoint string) bool {\n\treturn runtimeEndpoint == CrioSocket || runtimeEndpoint == \"unix://\"+CrioSocket\n}","line":{"from":66,"to":73}} {"id":100005462,"name":"LoadClientConfig","signature":"func LoadClientConfig(kubeconfigPath, bootstrapPath, certDir string) (certConfig, userConfig *restclient.Config, err error)","file":"pkg/kubelet/certificate/bootstrap/bootstrap.go","code":"// LoadClientConfig tries to load the appropriate client config for retrieving certs and for use by users.\n// If bootstrapPath is empty, only kubeconfigPath is checked. If bootstrap path is set and the contents\n// of kubeconfigPath are valid, both certConfig and userConfig will point to that file. Otherwise the\n// kubeconfigPath on disk is populated based on bootstrapPath but pointing to the location of the client cert\n// in certDir. This preserves the historical behavior of bootstrapping where on subsequent restarts the\n// most recent client cert is used to request new client certs instead of the initial token.\nfunc LoadClientConfig(kubeconfigPath, bootstrapPath, certDir string) (certConfig, userConfig *restclient.Config, err error) {\n\tif len(bootstrapPath) == 0 {\n\t\tclientConfig, err := loadRESTClientConfig(kubeconfigPath)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"unable to load kubeconfig: %v\", err)\n\t\t}\n\t\tklog.V(2).InfoS(\"No bootstrapping requested, will use kubeconfig\")\n\t\treturn clientConfig, restclient.CopyConfig(clientConfig), nil\n\t}\n\n\tstore, err := certificate.NewFileStore(\"kubelet-client\", certDir, certDir, \"\", \"\")\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"unable to build bootstrap cert store\")\n\t}\n\n\tok, err := isClientConfigStillValid(kubeconfigPath)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// use the current client config\n\tif ok {\n\t\tclientConfig, err := loadRESTClientConfig(kubeconfigPath)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"unable to load kubeconfig: %v\", err)\n\t\t}\n\t\tklog.V(2).InfoS(\"Current kubeconfig file contents are still valid, no bootstrap necessary\")\n\t\treturn clientConfig, restclient.CopyConfig(clientConfig), nil\n\t}\n\n\tbootstrapClientConfig, err := loadRESTClientConfig(bootstrapPath)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"unable to load bootstrap kubeconfig: %v\", err)\n\t}\n\n\tclientConfig := restclient.AnonymousClientConfig(bootstrapClientConfig)\n\tpemPath := store.CurrentPath()\n\tclientConfig.KeyFile = pemPath\n\tclientConfig.CertFile = pemPath\n\tif err := writeKubeconfigFromBootstrapping(clientConfig, kubeconfigPath, pemPath); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tklog.V(2).InfoS(\"Use the bootstrap credentials to request a cert, and set kubeconfig to point to the certificate dir\")\n\treturn bootstrapClientConfig, clientConfig, nil\n}","line":{"from":53,"to":103}} {"id":100005463,"name":"LoadClientCert","signature":"func LoadClientCert(ctx context.Context, kubeconfigPath, bootstrapPath, certDir string, nodeName types.NodeName) error","file":"pkg/kubelet/certificate/bootstrap/bootstrap.go","code":"// LoadClientCert requests a client cert for kubelet if the kubeconfigPath file does not exist.\n// The kubeconfig at bootstrapPath is used to request a client certificate from the API server.\n// On success, a kubeconfig file referencing the generated key and obtained certificate is written to kubeconfigPath.\n// The certificate and key file are stored in certDir.\nfunc LoadClientCert(ctx context.Context, kubeconfigPath, bootstrapPath, certDir string, nodeName types.NodeName) error {\n\t// Short-circuit if the kubeconfig file exists and is valid.\n\tok, err := isClientConfigStillValid(kubeconfigPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif ok {\n\t\tklog.V(2).InfoS(\"Kubeconfig exists and is valid, skipping bootstrap\", \"path\", kubeconfigPath)\n\t\treturn nil\n\t}\n\n\tklog.V(2).InfoS(\"Using bootstrap kubeconfig to generate TLS client cert, key and kubeconfig file\")\n\n\tbootstrapClientConfig, err := loadRESTClientConfig(bootstrapPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to load bootstrap kubeconfig: %v\", err)\n\t}\n\n\tbootstrapClient, err := clientset.NewForConfig(bootstrapClientConfig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to create certificates signing request client: %v\", err)\n\t}\n\n\tstore, err := certificate.NewFileStore(\"kubelet-client\", certDir, certDir, \"\", \"\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to build bootstrap cert store\")\n\t}\n\n\tvar keyData []byte\n\tif cert, err := store.Current(); err == nil {\n\t\tif cert.PrivateKey != nil {\n\t\t\tkeyData, err = keyutil.MarshalPrivateKeyToPEM(cert.PrivateKey)\n\t\t\tif err != nil {\n\t\t\t\tkeyData = nil\n\t\t\t}\n\t\t}\n\t}\n\t// Cache the private key in a separate file until CSR succeeds. This has to\n\t// be a separate file because store.CurrentPath() points to a symlink\n\t// managed by the store.\n\tprivKeyPath := filepath.Join(certDir, tmpPrivateKeyFile)\n\tif !verifyKeyData(keyData) {\n\t\tklog.V(2).InfoS(\"No valid private key and/or certificate found, reusing existing private key or creating a new one\")\n\t\t// Note: always call LoadOrGenerateKeyFile so that private key is\n\t\t// reused on next startup if CSR request fails.\n\t\tkeyData, _, err = keyutil.LoadOrGenerateKeyFile(privKeyPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := waitForServer(ctx, *bootstrapClientConfig, 1*time.Minute); err != nil {\n\t\tklog.InfoS(\"Error waiting for apiserver to come up\", \"err\", err)\n\t}\n\n\tcertData, err := requestNodeCertificate(ctx, bootstrapClient, keyData, nodeName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif _, err := store.Update(certData, keyData); err != nil {\n\t\treturn err\n\t}\n\tif err := os.Remove(privKeyPath); err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\tklog.V(2).InfoS(\"Failed cleaning up private key file\", \"path\", privKeyPath, \"err\", err)\n\t}\n\n\treturn writeKubeconfigFromBootstrapping(bootstrapClientConfig, kubeconfigPath, store.CurrentPath())\n}","line":{"from":105,"to":176}} {"id":100005464,"name":"writeKubeconfigFromBootstrapping","signature":"func writeKubeconfigFromBootstrapping(bootstrapClientConfig *restclient.Config, kubeconfigPath, pemPath string) error","file":"pkg/kubelet/certificate/bootstrap/bootstrap.go","code":"func writeKubeconfigFromBootstrapping(bootstrapClientConfig *restclient.Config, kubeconfigPath, pemPath string) error {\n\t// Get the CA data from the bootstrap client config.\n\tcaFile, caData := bootstrapClientConfig.CAFile, []byte{}\n\tif len(caFile) == 0 {\n\t\tcaData = bootstrapClientConfig.CAData\n\t}\n\n\t// Build resulting kubeconfig.\n\tkubeconfigData := clientcmdapi.Config{\n\t\t// Define a cluster stanza based on the bootstrap kubeconfig.\n\t\tClusters: map[string]*clientcmdapi.Cluster{\"default-cluster\": {\n\t\t\tServer: bootstrapClientConfig.Host,\n\t\t\tInsecureSkipTLSVerify: bootstrapClientConfig.Insecure,\n\t\t\tCertificateAuthority: caFile,\n\t\t\tCertificateAuthorityData: caData,\n\t\t}},\n\t\t// Define auth based on the obtained client cert.\n\t\tAuthInfos: map[string]*clientcmdapi.AuthInfo{\"default-auth\": {\n\t\t\tClientCertificate: pemPath,\n\t\t\tClientKey: pemPath,\n\t\t}},\n\t\t// Define a context that connects the auth info and cluster, and set it as the default\n\t\tContexts: map[string]*clientcmdapi.Context{\"default-context\": {\n\t\t\tCluster: \"default-cluster\",\n\t\t\tAuthInfo: \"default-auth\",\n\t\t\tNamespace: \"default\",\n\t\t}},\n\t\tCurrentContext: \"default-context\",\n\t}\n\n\t// Marshal to disk\n\treturn clientcmd.WriteToFile(kubeconfigData, kubeconfigPath)\n}","line":{"from":178,"to":210}} {"id":100005465,"name":"loadRESTClientConfig","signature":"func loadRESTClientConfig(kubeconfig string) (*restclient.Config, error)","file":"pkg/kubelet/certificate/bootstrap/bootstrap.go","code":"func loadRESTClientConfig(kubeconfig string) (*restclient.Config, error) {\n\t// Load structured kubeconfig data from the given path.\n\tloader := \u0026clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfig}\n\tloadedConfig, err := loader.Load()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Flatten the loaded data to a particular restclient.Config based on the current context.\n\treturn clientcmd.NewNonInteractiveClientConfig(\n\t\t*loadedConfig,\n\t\tloadedConfig.CurrentContext,\n\t\t\u0026clientcmd.ConfigOverrides{},\n\t\tloader,\n\t).ClientConfig()\n}","line":{"from":212,"to":226}} {"id":100005466,"name":"isClientConfigStillValid","signature":"func isClientConfigStillValid(kubeconfigPath string) (bool, error)","file":"pkg/kubelet/certificate/bootstrap/bootstrap.go","code":"// isClientConfigStillValid checks the provided kubeconfig to see if it has a valid\n// client certificate. It returns true if the kubeconfig is valid, or an error if bootstrapping\n// should stop immediately.\nfunc isClientConfigStillValid(kubeconfigPath string) (bool, error) {\n\t_, err := os.Stat(kubeconfigPath)\n\tif os.IsNotExist(err) {\n\t\treturn false, nil\n\t}\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"error reading existing bootstrap kubeconfig %s: %v\", kubeconfigPath, err)\n\t}\n\tbootstrapClientConfig, err := loadRESTClientConfig(kubeconfigPath)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unable to read existing bootstrap client config from %s: %v\", kubeconfigPath, err))\n\t\treturn false, nil\n\t}\n\ttransportConfig, err := bootstrapClientConfig.TransportConfig()\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unable to load transport configuration from existing bootstrap client config read from %s: %v\", kubeconfigPath, err))\n\t\treturn false, nil\n\t}\n\t// has side effect of populating transport config data fields\n\tif _, err := transport.TLSConfigFor(transportConfig); err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unable to load TLS configuration from existing bootstrap client config read from %s: %v\", kubeconfigPath, err))\n\t\treturn false, nil\n\t}\n\tcerts, err := certutil.ParseCertsPEM(transportConfig.TLS.CertData)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unable to load TLS certificates from existing bootstrap client config read from %s: %v\", kubeconfigPath, err))\n\t\treturn false, nil\n\t}\n\tif len(certs) == 0 {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unable to read TLS certificates from existing bootstrap client config read from %s: %v\", kubeconfigPath, err))\n\t\treturn false, nil\n\t}\n\tnow := time.Now()\n\tfor _, cert := range certs {\n\t\tif now.After(cert.NotAfter) {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"part of the existing bootstrap client certificate in %s is expired: %v\", kubeconfigPath, cert.NotAfter))\n\t\t\treturn false, nil\n\t\t}\n\t}\n\treturn true, nil\n}","line":{"from":228,"to":271}} {"id":100005467,"name":"verifyKeyData","signature":"func verifyKeyData(data []byte) bool","file":"pkg/kubelet/certificate/bootstrap/bootstrap.go","code":"// verifyKeyData returns true if the provided data appears to be a valid private key.\nfunc verifyKeyData(data []byte) bool {\n\tif len(data) == 0 {\n\t\treturn false\n\t}\n\t_, err := keyutil.ParsePrivateKeyPEM(data)\n\treturn err == nil\n}","line":{"from":273,"to":280}} {"id":100005468,"name":"waitForServer","signature":"func waitForServer(ctx context.Context, cfg restclient.Config, deadline time.Duration) error","file":"pkg/kubelet/certificate/bootstrap/bootstrap.go","code":"func waitForServer(ctx context.Context, cfg restclient.Config, deadline time.Duration) error {\n\tcfg.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\tcfg.Timeout = 1 * time.Second\n\tcli, err := restclient.UnversionedRESTClientFor(\u0026cfg)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't create client: %v\", err)\n\t}\n\n\tctx, cancel := context.WithTimeout(ctx, deadline)\n\tdefer cancel()\n\n\tvar connected bool\n\twait.JitterUntil(func() {\n\t\tif _, err := cli.Get().AbsPath(\"/healthz\").Do(ctx).Raw(); err != nil {\n\t\t\tklog.InfoS(\"Failed to connect to apiserver\", \"err\", err)\n\t\t\treturn\n\t\t}\n\t\tcancel()\n\t\tconnected = true\n\t}, 2*time.Second, 0.2, true, ctx.Done())\n\n\tif !connected {\n\t\treturn errors.New(\"timed out waiting to connect to apiserver\")\n\t}\n\treturn nil\n}","line":{"from":282,"to":307}} {"id":100005469,"name":"requestNodeCertificate","signature":"func requestNodeCertificate(ctx context.Context, client clientset.Interface, privateKeyData []byte, nodeName types.NodeName) (certData []byte, err error)","file":"pkg/kubelet/certificate/bootstrap/bootstrap.go","code":"// requestNodeCertificate will create a certificate signing request for a node\n// (Organization and CommonName for the CSR will be set as expected for node\n// certificates) and send it to API server, then it will watch the object's\n// status, once approved by API server, it will return the API server's issued\n// certificate (pem-encoded). If there is any errors, or the watch timeouts, it\n// will return an error. This is intended for use on nodes (kubelet and\n// kubeadm).\nfunc requestNodeCertificate(ctx context.Context, client clientset.Interface, privateKeyData []byte, nodeName types.NodeName) (certData []byte, err error) {\n\tsubject := \u0026pkix.Name{\n\t\tOrganization: []string{\"system:nodes\"},\n\t\tCommonName: \"system:node:\" + string(nodeName),\n\t}\n\n\tprivateKey, err := keyutil.ParsePrivateKeyPEM(privateKeyData)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid private key for certificate request: %v\", err)\n\t}\n\tcsrData, err := certutil.MakeCSR(privateKey, subject, nil, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to generate certificate request: %v\", err)\n\t}\n\n\tusages := []certificatesv1.KeyUsage{\n\t\tcertificatesv1.UsageDigitalSignature,\n\t\tcertificatesv1.UsageClientAuth,\n\t}\n\tif _, ok := privateKey.(*rsa.PrivateKey); ok {\n\t\tusages = append(usages, certificatesv1.UsageKeyEncipherment)\n\t}\n\n\t// The Signer interface contains the Public() method to get the public key.\n\tsigner, ok := privateKey.(crypto.Signer)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"private key does not implement crypto.Signer\")\n\t}\n\n\tname, err := digestedName(signer.Public(), subject, usages)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treqName, reqUID, err := csr.RequestCertificate(client, csrData, name, certificatesv1.KubeAPIServerClientKubeletSignerName, nil, usages, privateKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx, cancel := context.WithTimeout(ctx, 3600*time.Second)\n\tdefer cancel()\n\n\tklog.V(2).InfoS(\"Waiting for client certificate to be issued\")\n\treturn csr.WaitForCertificate(ctx, client, reqName, reqUID)\n}","line":{"from":309,"to":360}} {"id":100005470,"name":"digestedName","signature":"func digestedName(publicKey interface{}, subject *pkix.Name, usages []certificatesv1.KeyUsage) (string, error)","file":"pkg/kubelet/certificate/bootstrap/bootstrap.go","code":"// This digest should include all the relevant pieces of the CSR we care about.\n// We can't directly hash the serialized CSR because of random padding that we\n// regenerate every loop and we include usages which are not contained in the\n// CSR. This needs to be kept up to date as we add new fields to the node\n// certificates and with ensureCompatible.\nfunc digestedName(publicKey interface{}, subject *pkix.Name, usages []certificatesv1.KeyUsage) (string, error) {\n\thash := sha512.New512_256()\n\n\t// Here we make sure two different inputs can't write the same stream\n\t// to the hash. This delimiter is not in the base64.URLEncoding\n\t// alphabet so there is no way to have spill over collisions. Without\n\t// it 'CN:foo,ORG:bar' hashes to the same value as 'CN:foob,ORG:ar'\n\tconst delimiter = '|'\n\tencode := base64.RawURLEncoding.EncodeToString\n\n\twrite := func(data []byte) {\n\t\thash.Write([]byte(encode(data)))\n\t\thash.Write([]byte{delimiter})\n\t}\n\n\tpublicKeyData, err := x509.MarshalPKIXPublicKey(publicKey)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\twrite(publicKeyData)\n\n\twrite([]byte(subject.CommonName))\n\tfor _, v := range subject.Organization {\n\t\twrite([]byte(v))\n\t}\n\tfor _, v := range usages {\n\t\twrite([]byte(v))\n\t}\n\n\treturn fmt.Sprintf(\"node-csr-%s\", encode(hash.Sum(nil))), nil\n}","line":{"from":362,"to":397}} {"id":100005471,"name":"NewKubeletServerCertificateManager","signature":"func NewKubeletServerCertificateManager(kubeClient clientset.Interface, kubeCfg *kubeletconfig.KubeletConfiguration, nodeName types.NodeName, getAddresses func() []v1.NodeAddress, certDirectory string) (certificate.Manager, error)","file":"pkg/kubelet/certificate/kubelet.go","code":"// NewKubeletServerCertificateManager creates a certificate manager for the kubelet when retrieving a server certificate\n// or returns an error.\nfunc NewKubeletServerCertificateManager(kubeClient clientset.Interface, kubeCfg *kubeletconfig.KubeletConfiguration, nodeName types.NodeName, getAddresses func() []v1.NodeAddress, certDirectory string) (certificate.Manager, error) {\n\tvar clientsetFn certificate.ClientsetFunc\n\tif kubeClient != nil {\n\t\tclientsetFn = func(current *tls.Certificate) (clientset.Interface, error) {\n\t\t\treturn kubeClient, nil\n\t\t}\n\t}\n\tcertificateStore, err := certificate.NewFileStore(\n\t\t\"kubelet-server\",\n\t\tcertDirectory,\n\t\tcertDirectory,\n\t\tkubeCfg.TLSCertFile,\n\t\tkubeCfg.TLSPrivateKeyFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize server certificate store: %v\", err)\n\t}\n\tvar certificateRenewFailure = compbasemetrics.NewCounter(\n\t\t\u0026compbasemetrics.CounterOpts{\n\t\t\tSubsystem: metrics.KubeletSubsystem,\n\t\t\tName: \"server_expiration_renew_errors\",\n\t\t\tHelp: \"Counter of certificate renewal errors.\",\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t)\n\tlegacyregistry.MustRegister(certificateRenewFailure)\n\n\tcertificateRotationAge := compbasemetrics.NewHistogram(\n\t\t\u0026compbasemetrics.HistogramOpts{\n\t\t\tSubsystem: metrics.KubeletSubsystem,\n\t\t\tName: \"certificate_manager_server_rotation_seconds\",\n\t\t\tHelp: \"Histogram of the number of seconds the previous certificate lived before being rotated.\",\n\t\t\tBuckets: []float64{\n\t\t\t\t60, // 1 minute\n\t\t\t\t3600, // 1 hour\n\t\t\t\t14400, // 4 hours\n\t\t\t\t86400, // 1 day\n\t\t\t\t604800, // 1 week\n\t\t\t\t2592000, // 1 month\n\t\t\t\t7776000, // 3 months\n\t\t\t\t15552000, // 6 months\n\t\t\t\t31104000, // 1 year\n\t\t\t\t124416000, // 4 years\n\t\t\t},\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t)\n\tlegacyregistry.MustRegister(certificateRotationAge)\n\n\tgetTemplate := func() *x509.CertificateRequest {\n\t\thostnames, ips := addressesToHostnamesAndIPs(getAddresses())\n\t\t// don't return a template if we have no addresses to request for\n\t\tif len(hostnames) == 0 \u0026\u0026 len(ips) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\treturn \u0026x509.CertificateRequest{\n\t\t\tSubject: pkix.Name{\n\t\t\t\tCommonName: fmt.Sprintf(\"system:node:%s\", nodeName),\n\t\t\t\tOrganization: []string{\"system:nodes\"},\n\t\t\t},\n\t\t\tDNSNames: hostnames,\n\t\t\tIPAddresses: ips,\n\t\t}\n\t}\n\n\tm, err := certificate.NewManager(\u0026certificate.Config{\n\t\tClientsetFn: clientsetFn,\n\t\tGetTemplate: getTemplate,\n\t\tSignerName: certificates.KubeletServingSignerName,\n\t\tGetUsages: certificate.DefaultKubeletServingGetUsages,\n\t\tCertificateStore: certificateStore,\n\t\tCertificateRotation: certificateRotationAge,\n\t\tCertificateRenewFailure: certificateRenewFailure,\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize server certificate manager: %v\", err)\n\t}\n\tlegacyregistry.RawMustRegister(compbasemetrics.NewGaugeFunc(\n\t\t\u0026compbasemetrics.GaugeOpts{\n\t\t\tSubsystem: metrics.KubeletSubsystem,\n\t\t\tName: \"certificate_manager_server_ttl_seconds\",\n\t\t\tHelp: \"Gauge of the shortest TTL (time-to-live) of \" +\n\t\t\t\t\"the Kubelet's serving certificate. The value is in seconds \" +\n\t\t\t\t\"until certificate expiry (negative if already expired). If \" +\n\t\t\t\t\"serving certificate is invalid or unused, the value will \" +\n\t\t\t\t\"be +INF.\",\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\tfunc() float64 {\n\t\t\tif c := m.Current(); c != nil \u0026\u0026 c.Leaf != nil {\n\t\t\t\treturn math.Trunc(time.Until(c.Leaf.NotAfter).Seconds())\n\t\t\t}\n\t\t\treturn math.Inf(1)\n\t\t},\n\t))\n\treturn m, nil\n}","line":{"from":41,"to":138}} {"id":100005472,"name":"addressesToHostnamesAndIPs","signature":"func addressesToHostnamesAndIPs(addresses []v1.NodeAddress) (dnsNames []string, ips []net.IP)","file":"pkg/kubelet/certificate/kubelet.go","code":"func addressesToHostnamesAndIPs(addresses []v1.NodeAddress) (dnsNames []string, ips []net.IP) {\n\tseenDNSNames := map[string]bool{}\n\tseenIPs := map[string]bool{}\n\tfor _, address := range addresses {\n\t\tif len(address.Address) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch address.Type {\n\t\tcase v1.NodeHostName:\n\t\t\tif ip := netutils.ParseIPSloppy(address.Address); ip != nil {\n\t\t\t\tseenIPs[address.Address] = true\n\t\t\t} else {\n\t\t\t\tseenDNSNames[address.Address] = true\n\t\t\t}\n\t\tcase v1.NodeExternalIP, v1.NodeInternalIP:\n\t\t\tif ip := netutils.ParseIPSloppy(address.Address); ip != nil {\n\t\t\t\tseenIPs[address.Address] = true\n\t\t\t}\n\t\tcase v1.NodeExternalDNS, v1.NodeInternalDNS:\n\t\t\tseenDNSNames[address.Address] = true\n\t\t}\n\t}\n\n\tfor dnsName := range seenDNSNames {\n\t\tdnsNames = append(dnsNames, dnsName)\n\t}\n\tfor ip := range seenIPs {\n\t\tips = append(ips, netutils.ParseIPSloppy(ip))\n\t}\n\n\t// return in stable order\n\tsort.Strings(dnsNames)\n\tsort.Slice(ips, func(i, j int) bool { return ips[i].String() \u003c ips[j].String() })\n\n\treturn dnsNames, ips\n}","line":{"from":140,"to":176}} {"id":100005473,"name":"NewKubeletClientCertificateManager","signature":"func NewKubeletClientCertificateManager(","file":"pkg/kubelet/certificate/kubelet.go","code":"// NewKubeletClientCertificateManager sets up a certificate manager without a\n// client that can be used to sign new certificates (or rotate). If a CSR\n// client is set later, it may begin rotating/renewing the client cert.\nfunc NewKubeletClientCertificateManager(\n\tcertDirectory string,\n\tnodeName types.NodeName,\n\tbootstrapCertData []byte,\n\tbootstrapKeyData []byte,\n\tcertFile string,\n\tkeyFile string,\n\tclientsetFn certificate.ClientsetFunc,\n) (certificate.Manager, error) {\n\n\tcertificateStore, err := certificate.NewFileStore(\n\t\t\"kubelet-client\",\n\t\tcertDirectory,\n\t\tcertDirectory,\n\t\tcertFile,\n\t\tkeyFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize client certificate store: %v\", err)\n\t}\n\tvar certificateRenewFailure = compbasemetrics.NewCounter(\n\t\t\u0026compbasemetrics.CounterOpts{\n\t\t\tNamespace: metrics.KubeletSubsystem,\n\t\t\tSubsystem: \"certificate_manager\",\n\t\t\tName: \"client_expiration_renew_errors\",\n\t\t\tHelp: \"Counter of certificate renewal errors.\",\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t)\n\tlegacyregistry.Register(certificateRenewFailure)\n\n\tm, err := certificate.NewManager(\u0026certificate.Config{\n\t\tClientsetFn: clientsetFn,\n\t\tTemplate: \u0026x509.CertificateRequest{\n\t\t\tSubject: pkix.Name{\n\t\t\t\tCommonName: fmt.Sprintf(\"system:node:%s\", nodeName),\n\t\t\t\tOrganization: []string{\"system:nodes\"},\n\t\t\t},\n\t\t},\n\t\tSignerName: certificates.KubeAPIServerClientKubeletSignerName,\n\t\tGetUsages: certificate.DefaultKubeletClientGetUsages,\n\t\t// For backwards compatibility, the kubelet supports the ability to\n\t\t// provide a higher privileged certificate as initial data that will\n\t\t// then be rotated immediately. This code path is used by kubeadm on\n\t\t// the masters.\n\t\tBootstrapCertificatePEM: bootstrapCertData,\n\t\tBootstrapKeyPEM: bootstrapKeyData,\n\n\t\tCertificateStore: certificateStore,\n\t\tCertificateRenewFailure: certificateRenewFailure,\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize client certificate manager: %v\", err)\n\t}\n\n\treturn m, nil\n}","line":{"from":178,"to":236}} {"id":100005474,"name":"UpdateTransport","signature":"func UpdateTransport(stopCh \u003c-chan struct{}, clientConfig *restclient.Config, clientCertificateManager certificate.Manager, exitAfter time.Duration) (func(), error)","file":"pkg/kubelet/certificate/transport.go","code":"// UpdateTransport instruments a restconfig with a transport that dynamically uses\n// certificates provided by the manager for TLS client auth.\n//\n// The config must not already provide an explicit transport.\n//\n// The returned function allows forcefully closing all active connections.\n//\n// The returned transport periodically checks the manager to determine if the\n// certificate has changed. If it has, the transport shuts down all existing client\n// connections, forcing the client to re-handshake with the server and use the\n// new certificate.\n//\n// The exitAfter duration, if set, will terminate the current process if a certificate\n// is not available from the store (because it has been deleted on disk or is corrupt)\n// or if the certificate has expired and the server is responsive. This allows the\n// process parent or the bootstrap credentials an opportunity to retrieve a new initial\n// certificate.\n//\n// stopCh should be used to indicate when the transport is unused and doesn't need\n// to continue checking the manager.\nfunc UpdateTransport(stopCh \u003c-chan struct{}, clientConfig *restclient.Config, clientCertificateManager certificate.Manager, exitAfter time.Duration) (func(), error) {\n\treturn updateTransport(stopCh, 10*time.Second, clientConfig, clientCertificateManager, exitAfter)\n}","line":{"from":38,"to":60}} {"id":100005475,"name":"updateTransport","signature":"func updateTransport(stopCh \u003c-chan struct{}, period time.Duration, clientConfig *restclient.Config, clientCertificateManager certificate.Manager, exitAfter time.Duration) (func(), error)","file":"pkg/kubelet/certificate/transport.go","code":"// updateTransport is an internal method that exposes how often this method checks that the\n// client cert has changed.\nfunc updateTransport(stopCh \u003c-chan struct{}, period time.Duration, clientConfig *restclient.Config, clientCertificateManager certificate.Manager, exitAfter time.Duration) (func(), error) {\n\tif clientConfig.Transport != nil || clientConfig.Dial != nil {\n\t\treturn nil, fmt.Errorf(\"there is already a transport or dialer configured\")\n\t}\n\n\td := connrotation.NewDialer((\u0026net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}).DialContext)\n\n\tif clientCertificateManager != nil {\n\t\tif err := addCertRotation(stopCh, period, clientConfig, clientCertificateManager, exitAfter, d); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tclientConfig.Dial = d.DialContext\n\t}\n\n\treturn d.CloseAll, nil\n}","line":{"from":62,"to":80}} {"id":100005476,"name":"addCertRotation","signature":"func addCertRotation(stopCh \u003c-chan struct{}, period time.Duration, clientConfig *restclient.Config, clientCertificateManager certificate.Manager, exitAfter time.Duration, d *connrotation.Dialer) error","file":"pkg/kubelet/certificate/transport.go","code":"func addCertRotation(stopCh \u003c-chan struct{}, period time.Duration, clientConfig *restclient.Config, clientCertificateManager certificate.Manager, exitAfter time.Duration, d *connrotation.Dialer) error {\n\ttlsConfig, err := restclient.TLSConfigFor(clientConfig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to configure TLS for the rest client: %v\", err)\n\t}\n\tif tlsConfig == nil {\n\t\ttlsConfig = \u0026tls.Config{}\n\t}\n\n\ttlsConfig.Certificates = nil\n\ttlsConfig.GetClientCertificate = func(requestInfo *tls.CertificateRequestInfo) (*tls.Certificate, error) {\n\t\tcert := clientCertificateManager.Current()\n\t\tif cert == nil {\n\t\t\treturn \u0026tls.Certificate{Certificate: nil}, nil\n\t\t}\n\t\treturn cert, nil\n\t}\n\n\tlastCertAvailable := time.Now()\n\tlastCert := clientCertificateManager.Current()\n\n\tvar hasCert atomic.Bool\n\thasCert.Store(lastCert != nil)\n\n\tcheckLock := \u0026sync.Mutex{}\n\tcheckNewCertificateAndRotate := func() {\n\t\t// don't run concurrently\n\t\tcheckLock.Lock()\n\t\tdefer checkLock.Unlock()\n\n\t\tcurr := clientCertificateManager.Current()\n\n\t\tif exitAfter \u003e 0 {\n\t\t\tnow := time.Now()\n\t\t\tif curr == nil {\n\t\t\t\t// the certificate has been deleted from disk or is otherwise corrupt\n\t\t\t\tif now.After(lastCertAvailable.Add(exitAfter)) {\n\t\t\t\t\tif clientCertificateManager.ServerHealthy() {\n\t\t\t\t\t\tklog.ErrorS(nil, \"No valid client certificate is found and the server is responsive, exiting.\", \"lastCertificateAvailabilityTime\", lastCertAvailable, \"shutdownThreshold\", exitAfter)\n\t\t\t\t\t\tos.Exit(1)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tklog.ErrorS(nil, \"No valid client certificate is found but the server is not responsive. A restart may be necessary to retrieve new initial credentials.\", \"lastCertificateAvailabilityTime\", lastCertAvailable, \"shutdownThreshold\", exitAfter)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// the certificate is expired\n\t\t\t\tif now.After(curr.Leaf.NotAfter) {\n\t\t\t\t\tif clientCertificateManager.ServerHealthy() {\n\t\t\t\t\t\tklog.ErrorS(nil, \"The currently active client certificate has expired and the server is responsive, exiting.\")\n\t\t\t\t\t\tos.Exit(1)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tklog.ErrorS(nil, \"The currently active client certificate has expired, but the server is not responsive. A restart may be necessary to retrieve new initial credentials.\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlastCertAvailable = now\n\t\t\t}\n\t\t}\n\n\t\tif curr == nil || lastCert == curr {\n\t\t\t// Cert hasn't been rotated.\n\t\t\treturn\n\t\t}\n\t\tlastCert = curr\n\t\thasCert.Store(lastCert != nil)\n\n\t\tklog.InfoS(\"Certificate rotation detected, shutting down client connections to start using new credentials\")\n\t\t// The cert has been rotated. Close all existing connections to force the client\n\t\t// to reperform its TLS handshake with new cert.\n\t\t//\n\t\t// See: https://github.com/kubernetes-incubator/bootkube/pull/663#issuecomment-318506493\n\t\td.CloseAll()\n\t}\n\n\t// start long-term check\n\tgo wait.Until(checkNewCertificateAndRotate, period, stopCh)\n\n\tif !hasCert.Load() {\n\t\t// start a faster check until we get the initial certificate\n\t\tgo wait.PollUntil(time.Second, func() (bool, error) {\n\t\t\tcheckNewCertificateAndRotate()\n\t\t\treturn hasCert.Load(), nil\n\t\t}, stopCh)\n\t}\n\n\tclientConfig.Transport = utilnet.SetTransportDefaults(\u0026http.Transport{\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t\tTLSClientConfig: tlsConfig,\n\t\tMaxIdleConnsPerHost: 25,\n\t\tDialContext: d.DialContext,\n\t})\n\n\t// Zero out all existing TLS options since our new transport enforces them.\n\tclientConfig.CertData = nil\n\tclientConfig.KeyData = nil\n\tclientConfig.CertFile = \"\"\n\tclientConfig.KeyFile = \"\"\n\tclientConfig.CAData = nil\n\tclientConfig.CAFile = \"\"\n\tclientConfig.Insecure = false\n\tclientConfig.NextProtos = nil\n\n\treturn nil\n}","line":{"from":82,"to":185}} {"id":100005477,"name":"NewCheckpointManager","signature":"func NewCheckpointManager(checkpointDir string) (CheckpointManager, error)","file":"pkg/kubelet/checkpointmanager/checkpoint_manager.go","code":"// NewCheckpointManager returns a new instance of a checkpoint manager\nfunc NewCheckpointManager(checkpointDir string) (CheckpointManager, error) {\n\tfstore, err := utilstore.NewFileStore(checkpointDir, \u0026utilfs.DefaultFs{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026impl{path: checkpointDir, store: fstore}, nil\n}","line":{"from":55,"to":63}} {"id":100005478,"name":"CreateCheckpoint","signature":"func (manager *impl) CreateCheckpoint(checkpointKey string, checkpoint Checkpoint) error","file":"pkg/kubelet/checkpointmanager/checkpoint_manager.go","code":"// CreateCheckpoint persists checkpoint in CheckpointStore.\nfunc (manager *impl) CreateCheckpoint(checkpointKey string, checkpoint Checkpoint) error {\n\tmanager.mutex.Lock()\n\tdefer manager.mutex.Unlock()\n\tblob, err := checkpoint.MarshalCheckpoint()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn manager.store.Write(checkpointKey, blob)\n}","line":{"from":65,"to":74}} {"id":100005479,"name":"GetCheckpoint","signature":"func (manager *impl) GetCheckpoint(checkpointKey string, checkpoint Checkpoint) error","file":"pkg/kubelet/checkpointmanager/checkpoint_manager.go","code":"// GetCheckpoint retrieves checkpoint from CheckpointStore.\nfunc (manager *impl) GetCheckpoint(checkpointKey string, checkpoint Checkpoint) error {\n\tmanager.mutex.Lock()\n\tdefer manager.mutex.Unlock()\n\tblob, err := manager.store.Read(checkpointKey)\n\tif err != nil {\n\t\tif err == utilstore.ErrKeyNotFound {\n\t\t\treturn errors.ErrCheckpointNotFound\n\t\t}\n\t\treturn err\n\t}\n\terr = checkpoint.UnmarshalCheckpoint(blob)\n\tif err == nil {\n\t\terr = checkpoint.VerifyChecksum()\n\t}\n\treturn err\n}","line":{"from":76,"to":92}} {"id":100005480,"name":"RemoveCheckpoint","signature":"func (manager *impl) RemoveCheckpoint(checkpointKey string) error","file":"pkg/kubelet/checkpointmanager/checkpoint_manager.go","code":"// RemoveCheckpoint will not return error if checkpoint does not exist.\nfunc (manager *impl) RemoveCheckpoint(checkpointKey string) error {\n\tmanager.mutex.Lock()\n\tdefer manager.mutex.Unlock()\n\treturn manager.store.Delete(checkpointKey)\n}","line":{"from":94,"to":99}} {"id":100005481,"name":"ListCheckpoints","signature":"func (manager *impl) ListCheckpoints() ([]string, error)","file":"pkg/kubelet/checkpointmanager/checkpoint_manager.go","code":"// ListCheckpoints returns the list of existing checkpoints.\nfunc (manager *impl) ListCheckpoints() ([]string, error) {\n\tmanager.mutex.Lock()\n\tdefer manager.mutex.Unlock()\n\tkeys, err := manager.store.List()\n\tif err != nil {\n\t\treturn []string{}, fmt.Errorf(\"failed to list checkpoint store: %v\", err)\n\t}\n\treturn keys, nil\n}","line":{"from":101,"to":110}} {"id":100005482,"name":"Verify","signature":"func (cs Checksum) Verify(data interface{}) error","file":"pkg/kubelet/checkpointmanager/checksum/checksum.go","code":"// Verify verifies that passed checksum is same as calculated checksum\nfunc (cs Checksum) Verify(data interface{}) error {\n\tif cs != New(data) {\n\t\treturn errors.ErrCorruptCheckpoint\n\t}\n\treturn nil\n}","line":{"from":29,"to":35}} {"id":100005483,"name":"New","signature":"func New(data interface{}) Checksum","file":"pkg/kubelet/checkpointmanager/checksum/checksum.go","code":"// New returns the Checksum of checkpoint data\nfunc New(data interface{}) Checksum {\n\treturn Checksum(getChecksum(data))\n}","line":{"from":37,"to":40}} {"id":100005484,"name":"getChecksum","signature":"func getChecksum(data interface{}) uint64","file":"pkg/kubelet/checkpointmanager/checksum/checksum.go","code":"// Get returns calculated checksum of checkpoint data\nfunc getChecksum(data interface{}) uint64 {\n\thash := fnv.New32a()\n\thashutil.DeepHashObject(hash, data)\n\treturn uint64(hash.Sum32())\n}","line":{"from":42,"to":47}} {"id":100005485,"name":"MakeTransport","signature":"func MakeTransport(config *KubeletClientConfig) (http.RoundTripper, error)","file":"pkg/kubelet/client/kubelet_client.go","code":"// MakeTransport creates a secure RoundTripper for HTTP Transport.\nfunc MakeTransport(config *KubeletClientConfig) (http.RoundTripper, error) {\n\treturn makeTransport(config, false)\n}","line":{"from":78,"to":81}} {"id":100005486,"name":"MakeInsecureTransport","signature":"func MakeInsecureTransport(config *KubeletClientConfig) (http.RoundTripper, error)","file":"pkg/kubelet/client/kubelet_client.go","code":"// MakeInsecureTransport creates an insecure RoundTripper for HTTP Transport.\nfunc MakeInsecureTransport(config *KubeletClientConfig) (http.RoundTripper, error) {\n\treturn makeTransport(config, true)\n}","line":{"from":83,"to":86}} {"id":100005487,"name":"makeTransport","signature":"func makeTransport(config *KubeletClientConfig, insecureSkipTLSVerify bool) (http.RoundTripper, error)","file":"pkg/kubelet/client/kubelet_client.go","code":"// makeTransport creates a RoundTripper for HTTP Transport.\nfunc makeTransport(config *KubeletClientConfig, insecureSkipTLSVerify bool) (http.RoundTripper, error) {\n\t// do the insecureSkipTLSVerify on the pre-transport *before* we go get a potentially cached connection.\n\t// transportConfig always produces a new struct pointer.\n\ttransportConfig := config.transportConfig()\n\tif insecureSkipTLSVerify {\n\t\ttransportConfig.TLS.Insecure = true\n\t\ttransportConfig.TLS.CAFile = \"\" // we are only using files so we can ignore CAData\n\t}\n\n\tif config.Lookup != nil {\n\t\t// Assuming EgressSelector if SSHTunnel is not turned on.\n\t\t// We will not get a dialer if egress selector is disabled.\n\t\tnetworkContext := egressselector.Cluster.AsNetworkContext()\n\t\tdialer, err := config.Lookup(networkContext)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get context dialer for 'cluster': got %v\", err)\n\t\t}\n\t\tif dialer != nil {\n\t\t\ttransportConfig.DialHolder = \u0026transport.DialHolder{Dial: dialer}\n\t\t}\n\t}\n\treturn transport.New(transportConfig)\n}","line":{"from":88,"to":111}} {"id":100005488,"name":"transportConfig","signature":"func (c *KubeletClientConfig) transportConfig() *transport.Config","file":"pkg/kubelet/client/kubelet_client.go","code":"// transportConfig converts a client config to an appropriate transport config.\nfunc (c *KubeletClientConfig) transportConfig() *transport.Config {\n\tcfg := \u0026transport.Config{\n\t\tTLS: transport.TLSConfig{\n\t\t\tCAFile: c.TLSClientConfig.CAFile,\n\t\t\tCertFile: c.TLSClientConfig.CertFile,\n\t\t\tKeyFile: c.TLSClientConfig.KeyFile,\n\t\t\t// transport.loadTLSFiles would set this to true because we are only using files\n\t\t\t// it is clearer to set it explicitly here so we remember that this is happening\n\t\t\tReloadTLSFiles: true,\n\t\t},\n\t}\n\tif !cfg.HasCA() {\n\t\tcfg.TLS.Insecure = true\n\t}\n\treturn cfg\n}","line":{"from":113,"to":129}} {"id":100005489,"name":"Get","signature":"func (f NodeGetterFunc) Get(ctx context.Context, name string, options metav1.GetOptions) (*v1.Node, error)","file":"pkg/kubelet/client/kubelet_client.go","code":"// Get fetches information via NodeGetterFunc.\nfunc (f NodeGetterFunc) Get(ctx context.Context, name string, options metav1.GetOptions) (*v1.Node, error) {\n\treturn f(ctx, name, options)\n}","line":{"from":139,"to":142}} {"id":100005490,"name":"NewNodeConnectionInfoGetter","signature":"func NewNodeConnectionInfoGetter(nodes NodeGetter, config KubeletClientConfig) (ConnectionInfoGetter, error)","file":"pkg/kubelet/client/kubelet_client.go","code":"// NewNodeConnectionInfoGetter creates a new NodeConnectionInfoGetter.\nfunc NewNodeConnectionInfoGetter(nodes NodeGetter, config KubeletClientConfig) (ConnectionInfoGetter, error) {\n\ttransport, err := MakeTransport(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinsecureSkipTLSVerifyTransport, err := MakeInsecureTransport(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttypes := []v1.NodeAddressType{}\n\tfor _, t := range config.PreferredAddressTypes {\n\t\ttypes = append(types, v1.NodeAddressType(t))\n\t}\n\n\treturn \u0026NodeConnectionInfoGetter{\n\t\tnodes: nodes,\n\t\tscheme: \"https\",\n\t\tdefaultPort: int(config.Port),\n\t\ttransport: transport,\n\t\tinsecureSkipTLSVerifyTransport: insecureSkipTLSVerifyTransport,\n\n\t\tpreferredAddressTypes: types,\n\t}, nil\n}","line":{"from":160,"to":185}} {"id":100005491,"name":"GetConnectionInfo","signature":"func (k *NodeConnectionInfoGetter) GetConnectionInfo(ctx context.Context, nodeName types.NodeName) (*ConnectionInfo, error)","file":"pkg/kubelet/client/kubelet_client.go","code":"// GetConnectionInfo retrieves connection info from the status of a Node API object.\nfunc (k *NodeConnectionInfoGetter) GetConnectionInfo(ctx context.Context, nodeName types.NodeName) (*ConnectionInfo, error) {\n\tnode, err := k.nodes.Get(ctx, string(nodeName), metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Find a kubelet-reported address, using preferred address type\n\thost, err := nodeutil.GetPreferredNodeAddress(node, k.preferredAddressTypes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Use the kubelet-reported port, if present\n\tport := int(node.Status.DaemonEndpoints.KubeletEndpoint.Port)\n\tif port \u003c= 0 {\n\t\tport = k.defaultPort\n\t}\n\n\treturn \u0026ConnectionInfo{\n\t\tScheme: k.scheme,\n\t\tHostname: host,\n\t\tPort: strconv.Itoa(port),\n\t\tTransport: k.transport,\n\t\tInsecureSkipTLSVerifyTransport: k.insecureSkipTLSVerifyTransport,\n\t}, nil\n}","line":{"from":187,"to":213}} {"id":100005492,"name":"NewSyncManager","signature":"func NewSyncManager(cloud cloudprovider.Interface, nodeName types.NodeName, syncPeriod time.Duration) SyncManager","file":"pkg/kubelet/cloudresource/cloud_request_manager.go","code":"// NewSyncManager creates a manager responsible for collecting resources from a\n// cloud provider through requests that are sensitive to timeouts and hanging\nfunc NewSyncManager(cloud cloudprovider.Interface, nodeName types.NodeName, syncPeriod time.Duration) SyncManager {\n\treturn \u0026cloudResourceSyncManager{\n\t\tcloud: cloud,\n\t\tsyncPeriod: syncPeriod,\n\t\tnodeName: nodeName,\n\t\t// nodeAddressesMonitor is a monitor that guards a result (nodeAddresses,\n\t\t// nodeAddressesErr) of the sync loop under the condition that a result has\n\t\t// been saved at least once. The semantics here are:\n\t\t//\n\t\t// * Readers of the result will wait on the monitor until the first result\n\t\t// has been saved.\n\t\t// * The sync loop (i.e. the only writer), will signal all waiters every\n\t\t// time it updates the result.\n\t\tnodeAddressesMonitor: sync.NewCond(\u0026sync.Mutex{}),\n\t}\n}","line":{"from":54,"to":71}} {"id":100005493,"name":"NodeAddresses","signature":"func (m *cloudResourceSyncManager) NodeAddresses() ([]v1.NodeAddress, error)","file":"pkg/kubelet/cloudresource/cloud_request_manager.go","code":"// NodeAddresses waits for the first sync loop to run. If no successful syncs\n// have run, it will return the most recent error. If node addresses have been\n// synced successfully, it will return the list of node addresses from the most\n// recent successful sync.\nfunc (m *cloudResourceSyncManager) NodeAddresses() ([]v1.NodeAddress, error) {\n\tm.nodeAddressesMonitor.L.Lock()\n\tdefer m.nodeAddressesMonitor.L.Unlock()\n\t// wait until there is something\n\tfor {\n\t\tif addrs, err := m.nodeAddresses, m.nodeAddressesErr; len(addrs) \u003e 0 || err != nil {\n\t\t\treturn addrs, err\n\t\t}\n\t\tklog.V(5).InfoS(\"Waiting for cloud provider to provide node addresses\")\n\t\tm.nodeAddressesMonitor.Wait()\n\t}\n}","line":{"from":73,"to":88}} {"id":100005494,"name":"getNodeAddresses","signature":"func (m *cloudResourceSyncManager) getNodeAddresses() ([]v1.NodeAddress, error)","file":"pkg/kubelet/cloudresource/cloud_request_manager.go","code":"// getNodeAddresses calls the cloud provider to get a current list of node addresses.\nfunc (m *cloudResourceSyncManager) getNodeAddresses() ([]v1.NodeAddress, error) {\n\t// TODO(roberthbailey): Can we do this without having credentials to talk to\n\t// the cloud provider?\n\t// TODO(justinsb): We can if CurrentNodeName() was actually CurrentNode() and\n\t// returned an interface.\n\t// TODO: If IP addresses couldn't be fetched from the cloud provider, should\n\t// kubelet fallback on the other methods for getting the IP below?\n\tinstances, ok := m.cloud.Instances()\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to get instances from cloud provider\")\n\t}\n\treturn instances.NodeAddresses(context.TODO(), m.nodeName)\n}","line":{"from":90,"to":103}} {"id":100005495,"name":"syncNodeAddresses","signature":"func (m *cloudResourceSyncManager) syncNodeAddresses()","file":"pkg/kubelet/cloudresource/cloud_request_manager.go","code":"func (m *cloudResourceSyncManager) syncNodeAddresses() {\n\tklog.V(5).InfoS(\"Requesting node addresses from cloud provider for node\", \"nodeName\", m.nodeName)\n\n\taddrs, err := m.getNodeAddresses()\n\n\tm.nodeAddressesMonitor.L.Lock()\n\tdefer m.nodeAddressesMonitor.L.Unlock()\n\tdefer m.nodeAddressesMonitor.Broadcast()\n\n\tif err != nil {\n\t\tklog.V(2).InfoS(\"Node addresses from cloud provider for node not collected\", \"nodeName\", m.nodeName, \"err\", err)\n\n\t\tif len(m.nodeAddresses) \u003e 0 {\n\t\t\t// in the event that a sync loop fails when a previous sync had\n\t\t\t// succeeded, continue to use the old addresses.\n\t\t\treturn\n\t\t}\n\n\t\tm.nodeAddressesErr = fmt.Errorf(\"failed to get node address from cloud provider: %v\", err)\n\t\treturn\n\t}\n\n\tklog.V(5).InfoS(\"Node addresses from cloud provider for node collected\", \"nodeName\", m.nodeName)\n\tm.nodeAddressesErr = nil\n\tm.nodeAddresses = addrs\n}","line":{"from":105,"to":130}} {"id":100005496,"name":"Run","signature":"func (m *cloudResourceSyncManager) Run(stopCh \u003c-chan struct{})","file":"pkg/kubelet/cloudresource/cloud_request_manager.go","code":"// Run starts the cloud resource sync manager's sync loop.\nfunc (m *cloudResourceSyncManager) Run(stopCh \u003c-chan struct{}) {\n\twait.Until(m.syncNodeAddresses, m.syncPeriod, stopCh)\n}","line":{"from":132,"to":135}} {"id":100005497,"name":"Error","signature":"func (e *unexpectedAdmissionError) Error() string","file":"pkg/kubelet/cm/admission/errors.go","code":"func (e *unexpectedAdmissionError) Error() string {\n\treturn fmt.Sprintf(\"Allocate failed due to %v, which is unexpected\", e.Err)\n}","line":{"from":39,"to":41}} {"id":100005498,"name":"Type","signature":"func (e *unexpectedAdmissionError) Type() string","file":"pkg/kubelet/cm/admission/errors.go","code":"func (e *unexpectedAdmissionError) Type() string {\n\treturn ErrorReasonUnexpected\n}","line":{"from":43,"to":45}} {"id":100005499,"name":"GetPodAdmitResult","signature":"func GetPodAdmitResult(err error) lifecycle.PodAdmitResult","file":"pkg/kubelet/cm/admission/errors.go","code":"func GetPodAdmitResult(err error) lifecycle.PodAdmitResult {\n\tif err == nil {\n\t\treturn lifecycle.PodAdmitResult{Admit: true}\n\t}\n\n\tvar admissionErr Error\n\tif !errors.As(err, \u0026admissionErr) {\n\t\tadmissionErr = \u0026unexpectedAdmissionError{err}\n\t}\n\n\treturn lifecycle.PodAdmitResult{\n\t\tMessage: admissionErr.Error(),\n\t\tReason: admissionErr.Type(),\n\t\tAdmit: false,\n\t}\n}","line":{"from":47,"to":62}} {"id":100005500,"name":"NewCgroupName","signature":"func NewCgroupName(base CgroupName, components ...string) CgroupName","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"// NewCgroupName composes a new cgroup name.\n// Use RootCgroupName as base to start at the root.\n// This function does some basic check for invalid characters at the name.\nfunc NewCgroupName(base CgroupName, components ...string) CgroupName {\n\tfor _, component := range components {\n\t\t// Forbit using \"_\" in internal names. When remapping internal\n\t\t// names to systemd cgroup driver, we want to remap \"-\" =\u003e \"_\",\n\t\t// so we forbid \"_\" so that we can always reverse the mapping.\n\t\tif strings.Contains(component, \"/\") || strings.Contains(component, \"_\") {\n\t\t\tpanic(fmt.Errorf(\"invalid character in component [%q] of CgroupName\", component))\n\t\t}\n\t}\n\treturn CgroupName(append(append([]string{}, base...), components...))\n}","line":{"from":57,"to":70}} {"id":100005501,"name":"escapeSystemdCgroupName","signature":"func escapeSystemdCgroupName(part string) string","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"func escapeSystemdCgroupName(part string) string {\n\treturn strings.Replace(part, \"-\", \"_\", -1)\n}","line":{"from":72,"to":74}} {"id":100005502,"name":"unescapeSystemdCgroupName","signature":"func unescapeSystemdCgroupName(part string) string","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"func unescapeSystemdCgroupName(part string) string {\n\treturn strings.Replace(part, \"_\", \"-\", -1)\n}","line":{"from":76,"to":78}} {"id":100005503,"name":"ToSystemd","signature":"func (cgroupName CgroupName) ToSystemd() string","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"// cgroupName.ToSystemd converts the internal cgroup name to a systemd name.\n// For example, the name {\"kubepods\", \"burstable\", \"pod1234-abcd-5678-efgh\"} becomes\n// \"/kubepods.slice/kubepods-burstable.slice/kubepods-burstable-pod1234_abcd_5678_efgh.slice\"\n// This function always expands the systemd name into the cgroupfs form. If only\n// the last part is needed, use path.Base(...) on it to discard the rest.\nfunc (cgroupName CgroupName) ToSystemd() string {\n\tif len(cgroupName) == 0 || (len(cgroupName) == 1 \u0026\u0026 cgroupName[0] == \"\") {\n\t\treturn \"/\"\n\t}\n\tnewparts := []string{}\n\tfor _, part := range cgroupName {\n\t\tpart = escapeSystemdCgroupName(part)\n\t\tnewparts = append(newparts, part)\n\t}\n\n\tresult, err := cgroupsystemd.ExpandSlice(strings.Join(newparts, \"-\") + systemdSuffix)\n\tif err != nil {\n\t\t// Should never happen...\n\t\tpanic(fmt.Errorf(\"error converting cgroup name [%v] to systemd format: %v\", cgroupName, err))\n\t}\n\treturn result\n}","line":{"from":80,"to":101}} {"id":100005504,"name":"ParseSystemdToCgroupName","signature":"func ParseSystemdToCgroupName(name string) CgroupName","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"func ParseSystemdToCgroupName(name string) CgroupName {\n\tdriverName := path.Base(name)\n\tdriverName = strings.TrimSuffix(driverName, systemdSuffix)\n\tparts := strings.Split(driverName, \"-\")\n\tresult := []string{}\n\tfor _, part := range parts {\n\t\tresult = append(result, unescapeSystemdCgroupName(part))\n\t}\n\treturn CgroupName(result)\n}","line":{"from":103,"to":112}} {"id":100005505,"name":"ToCgroupfs","signature":"func (cgroupName CgroupName) ToCgroupfs() string","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"func (cgroupName CgroupName) ToCgroupfs() string {\n\treturn \"/\" + path.Join(cgroupName...)\n}","line":{"from":114,"to":116}} {"id":100005506,"name":"ParseCgroupfsToCgroupName","signature":"func ParseCgroupfsToCgroupName(name string) CgroupName","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"func ParseCgroupfsToCgroupName(name string) CgroupName {\n\tcomponents := strings.Split(strings.TrimPrefix(name, \"/\"), \"/\")\n\tif len(components) == 1 \u0026\u0026 components[0] == \"\" {\n\t\tcomponents = []string{}\n\t}\n\treturn CgroupName(components)\n}","line":{"from":118,"to":124}} {"id":100005507,"name":"IsSystemdStyleName","signature":"func IsSystemdStyleName(name string) bool","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"func IsSystemdStyleName(name string) bool {\n\treturn strings.HasSuffix(name, systemdSuffix)\n}","line":{"from":126,"to":128}} {"id":100005508,"name":"NewCgroupManager","signature":"func NewCgroupManager(cs *CgroupSubsystems, cgroupDriver string) CgroupManager","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"// NewCgroupManager is a factory method that returns a CgroupManager\nfunc NewCgroupManager(cs *CgroupSubsystems, cgroupDriver string) CgroupManager {\n\treturn \u0026cgroupManagerImpl{\n\t\tsubsystems: cs,\n\t\tuseSystemd: cgroupDriver == \"systemd\",\n\t}\n}","line":{"from":157,"to":163}} {"id":100005509,"name":"Name","signature":"func (m *cgroupManagerImpl) Name(name CgroupName) string","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"// Name converts the cgroup to the driver specific value in cgroupfs form.\n// This always returns a valid cgroupfs path even when systemd driver is in use!\nfunc (m *cgroupManagerImpl) Name(name CgroupName) string {\n\tif m.useSystemd {\n\t\treturn name.ToSystemd()\n\t}\n\treturn name.ToCgroupfs()\n}","line":{"from":165,"to":172}} {"id":100005510,"name":"CgroupName","signature":"func (m *cgroupManagerImpl) CgroupName(name string) CgroupName","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"// CgroupName converts the literal cgroupfs name on the host to an internal identifier.\nfunc (m *cgroupManagerImpl) CgroupName(name string) CgroupName {\n\tif m.useSystemd {\n\t\treturn ParseSystemdToCgroupName(name)\n\t}\n\treturn ParseCgroupfsToCgroupName(name)\n}","line":{"from":174,"to":180}} {"id":100005511,"name":"buildCgroupPaths","signature":"func (m *cgroupManagerImpl) buildCgroupPaths(name CgroupName) map[string]string","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"// buildCgroupPaths builds a path to each cgroup subsystem for the specified name.\nfunc (m *cgroupManagerImpl) buildCgroupPaths(name CgroupName) map[string]string {\n\tcgroupFsAdaptedName := m.Name(name)\n\tcgroupPaths := make(map[string]string, len(m.subsystems.MountPoints))\n\tfor key, val := range m.subsystems.MountPoints {\n\t\tcgroupPaths[key] = path.Join(val, cgroupFsAdaptedName)\n\t}\n\treturn cgroupPaths\n}","line":{"from":182,"to":190}} {"id":100005512,"name":"buildCgroupUnifiedPath","signature":"func (m *cgroupManagerImpl) buildCgroupUnifiedPath(name CgroupName) string","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"// buildCgroupUnifiedPath builds a path to the specified name.\nfunc (m *cgroupManagerImpl) buildCgroupUnifiedPath(name CgroupName) string {\n\tcgroupFsAdaptedName := m.Name(name)\n\treturn path.Join(cmutil.CgroupRoot, cgroupFsAdaptedName)\n}","line":{"from":192,"to":196}} {"id":100005513,"name":"libctCgroupConfig","signature":"func (m *cgroupManagerImpl) libctCgroupConfig(in *CgroupConfig, needResources bool) *libcontainerconfigs.Cgroup","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"// libctCgroupConfig converts CgroupConfig to libcontainer's Cgroup config.\nfunc (m *cgroupManagerImpl) libctCgroupConfig(in *CgroupConfig, needResources bool) *libcontainerconfigs.Cgroup {\n\tconfig := \u0026libcontainerconfigs.Cgroup{\n\t\tSystemd: m.useSystemd,\n\t}\n\tif needResources {\n\t\tconfig.Resources = m.toResources(in.ResourceParameters)\n\t} else {\n\t\tconfig.Resources = \u0026libcontainerconfigs.Resources{}\n\t}\n\n\tif !config.Systemd {\n\t\t// For fs cgroup manager, we can either set Path or Name and Parent.\n\t\t// Setting Path is easier.\n\t\tconfig.Path = in.Name.ToCgroupfs()\n\n\t\treturn config\n\t}\n\n\t// For systemd, we have to set Name and Parent, as they are needed to talk to systemd.\n\t// Setting Path is optional as it can be deduced from Name and Parent.\n\n\t// TODO(filbranden): This logic belongs in libcontainer/cgroup/systemd instead.\n\t// It should take a libcontainerconfigs.Cgroup.Path field (rather than Name and Parent)\n\t// and split it appropriately, using essentially the logic below.\n\t// This was done for cgroupfs in opencontainers/runc#497 but a counterpart\n\t// for systemd was never introduced.\n\tdir, base := path.Split(in.Name.ToSystemd())\n\tif dir == \"/\" {\n\t\tdir = \"-.slice\"\n\t} else {\n\t\tdir = path.Base(dir)\n\t}\n\tconfig.Parent = dir\n\tconfig.Name = base\n\n\treturn config\n}","line":{"from":198,"to":235}} {"id":100005514,"name":"Validate","signature":"func (m *cgroupManagerImpl) Validate(name CgroupName) error","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"// Validate checks if all subsystem cgroups already exist\nfunc (m *cgroupManagerImpl) Validate(name CgroupName) error {\n\tif libcontainercgroups.IsCgroup2UnifiedMode() {\n\t\tcgroupPath := m.buildCgroupUnifiedPath(name)\n\t\tneededControllers := getSupportedUnifiedControllers()\n\t\tenabledControllers, err := readUnifiedControllers(cgroupPath)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not read controllers for cgroup %q: %w\", name, err)\n\t\t}\n\t\tdifference := neededControllers.Difference(enabledControllers)\n\t\tif difference.Len() \u003e 0 {\n\t\t\treturn fmt.Errorf(\"cgroup %q has some missing controllers: %v\", name, strings.Join(difference.List(), \", \"))\n\t\t}\n\t\treturn nil // valid V2 cgroup\n\t}\n\n\t// Get map of all cgroup paths on the system for the particular cgroup\n\tcgroupPaths := m.buildCgroupPaths(name)\n\n\t// the presence of alternative control groups not known to runc confuses\n\t// the kubelet existence checks.\n\t// ideally, we would have a mechanism in runc to support Exists() logic\n\t// scoped to the set control groups it understands. this is being discussed\n\t// in https://github.com/opencontainers/runc/issues/1440\n\t// once resolved, we can remove this code.\n\tallowlistControllers := sets.NewString(\"cpu\", \"cpuacct\", \"cpuset\", \"memory\", \"systemd\", \"pids\")\n\n\tif _, ok := m.subsystems.MountPoints[\"hugetlb\"]; ok {\n\t\tallowlistControllers.Insert(\"hugetlb\")\n\t}\n\tvar missingPaths []string\n\t// If even one cgroup path doesn't exist, then the cgroup doesn't exist.\n\tfor controller, path := range cgroupPaths {\n\t\t// ignore mounts we don't care about\n\t\tif !allowlistControllers.Has(controller) {\n\t\t\tcontinue\n\t\t}\n\t\tif !libcontainercgroups.PathExists(path) {\n\t\t\tmissingPaths = append(missingPaths, path)\n\t\t}\n\t}\n\n\tif len(missingPaths) \u003e 0 {\n\t\treturn fmt.Errorf(\"cgroup %q has some missing paths: %v\", name, strings.Join(missingPaths, \", \"))\n\t}\n\n\treturn nil // valid V1 cgroup\n}","line":{"from":237,"to":284}} {"id":100005515,"name":"Exists","signature":"func (m *cgroupManagerImpl) Exists(name CgroupName) bool","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"// Exists checks if all subsystem cgroups already exist\nfunc (m *cgroupManagerImpl) Exists(name CgroupName) bool {\n\treturn m.Validate(name) == nil\n}","line":{"from":286,"to":289}} {"id":100005516,"name":"Destroy","signature":"func (m *cgroupManagerImpl) Destroy(cgroupConfig *CgroupConfig) error","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"// Destroy destroys the specified cgroup\nfunc (m *cgroupManagerImpl) Destroy(cgroupConfig *CgroupConfig) error {\n\tstart := time.Now()\n\tdefer func() {\n\t\tmetrics.CgroupManagerDuration.WithLabelValues(\"destroy\").Observe(metrics.SinceInSeconds(start))\n\t}()\n\n\tlibcontainerCgroupConfig := m.libctCgroupConfig(cgroupConfig, false)\n\tmanager, err := manager.New(libcontainerCgroupConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Delete cgroups using libcontainers Managers Destroy() method\n\tif err = manager.Destroy(); err != nil {\n\t\treturn fmt.Errorf(\"unable to destroy cgroup paths for cgroup %v : %v\", cgroupConfig.Name, err)\n\t}\n\n\treturn nil\n}","line":{"from":291,"to":310}} {"id":100005517,"name":"getCPUWeight","signature":"func getCPUWeight(cpuShares *uint64) uint64","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"// getCPUWeight converts from the range [2, 262144] to [1, 10000]\nfunc getCPUWeight(cpuShares *uint64) uint64 {\n\tif cpuShares == nil {\n\t\treturn 0\n\t}\n\tif *cpuShares \u003e= 262144 {\n\t\treturn 10000\n\t}\n\treturn 1 + ((*cpuShares-2)*9999)/262142\n}","line":{"from":312,"to":321}} {"id":100005518,"name":"readUnifiedControllers","signature":"func readUnifiedControllers(path string) (sets.String, error)","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"// readUnifiedControllers reads the controllers available at the specified cgroup\nfunc readUnifiedControllers(path string) (sets.String, error) {\n\tcontrollersFileContent, err := os.ReadFile(filepath.Join(path, \"cgroup.controllers\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcontrollers := strings.Fields(string(controllersFileContent))\n\treturn sets.NewString(controllers...), nil\n}","line":{"from":323,"to":331}} {"id":100005519,"name":"getSupportedUnifiedControllers","signature":"func getSupportedUnifiedControllers() sets.String","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"// getSupportedUnifiedControllers returns a set of supported controllers when running on cgroup v2\nfunc getSupportedUnifiedControllers() sets.String {\n\t// This is the set of controllers used by the Kubelet\n\tsupportedControllers := sets.NewString(\"cpu\", \"cpuset\", \"memory\", \"hugetlb\", \"pids\")\n\t// Memoize the set of controllers that are present in the root cgroup\n\tavailableRootControllersOnce.Do(func() {\n\t\tvar err error\n\t\tavailableRootControllers, err = readUnifiedControllers(cmutil.CgroupRoot)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"cannot read cgroup controllers at %s\", cmutil.CgroupRoot))\n\t\t}\n\t})\n\t// Return the set of controllers that are supported both by the Kubelet and by the kernel\n\treturn supportedControllers.Intersection(availableRootControllers)\n}","line":{"from":338,"to":352}} {"id":100005520,"name":"toResources","signature":"func (m *cgroupManagerImpl) toResources(resourceConfig *ResourceConfig) *libcontainerconfigs.Resources","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"func (m *cgroupManagerImpl) toResources(resourceConfig *ResourceConfig) *libcontainerconfigs.Resources {\n\tresources := \u0026libcontainerconfigs.Resources{\n\t\tSkipDevices: true,\n\t\tSkipFreezeOnSet: true,\n\t}\n\tif resourceConfig == nil {\n\t\treturn resources\n\t}\n\tif resourceConfig.Memory != nil {\n\t\tresources.Memory = *resourceConfig.Memory\n\t}\n\tif resourceConfig.CPUShares != nil {\n\t\tif libcontainercgroups.IsCgroup2UnifiedMode() {\n\t\t\tresources.CpuWeight = getCPUWeight(resourceConfig.CPUShares)\n\t\t} else {\n\t\t\tresources.CpuShares = *resourceConfig.CPUShares\n\t\t}\n\t}\n\tif resourceConfig.CPUQuota != nil {\n\t\tresources.CpuQuota = *resourceConfig.CPUQuota\n\t}\n\tif resourceConfig.CPUPeriod != nil {\n\t\tresources.CpuPeriod = *resourceConfig.CPUPeriod\n\t}\n\tif resourceConfig.PidsLimit != nil {\n\t\tresources.PidsLimit = *resourceConfig.PidsLimit\n\t}\n\n\tm.maybeSetHugetlb(resourceConfig, resources)\n\n\t// Ideally unified is used for all the resources when running on cgroup v2.\n\t// It doesn't make difference for the memory.max limit, but for e.g. the cpu controller\n\t// you can specify the correct setting without relying on the conversions performed by the OCI runtime.\n\tif resourceConfig.Unified != nil \u0026\u0026 libcontainercgroups.IsCgroup2UnifiedMode() {\n\t\tresources.Unified = make(map[string]string)\n\t\tfor k, v := range resourceConfig.Unified {\n\t\t\tresources.Unified[k] = v\n\t\t}\n\t}\n\treturn resources\n}","line":{"from":354,"to":394}} {"id":100005521,"name":"maybeSetHugetlb","signature":"func (m *cgroupManagerImpl) maybeSetHugetlb(resourceConfig *ResourceConfig, resources *libcontainerconfigs.Resources)","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"func (m *cgroupManagerImpl) maybeSetHugetlb(resourceConfig *ResourceConfig, resources *libcontainerconfigs.Resources) {\n\t// Check if hugetlb is supported.\n\tif libcontainercgroups.IsCgroup2UnifiedMode() {\n\t\tif !getSupportedUnifiedControllers().Has(\"hugetlb\") {\n\t\t\tklog.V(6).InfoS(\"Optional subsystem not supported: hugetlb\")\n\t\t\treturn\n\t\t}\n\t} else if _, ok := m.subsystems.MountPoints[\"hugetlb\"]; !ok {\n\t\tklog.V(6).InfoS(\"Optional subsystem not supported: hugetlb\")\n\t\treturn\n\t}\n\n\t// For each page size enumerated, set that value.\n\tpageSizes := sets.NewString()\n\tfor pageSize, limit := range resourceConfig.HugePageLimit {\n\t\tsizeString, err := v1helper.HugePageUnitSizeFromByteSize(pageSize)\n\t\tif err != nil {\n\t\t\tklog.InfoS(\"Invalid pageSize\", \"err\", err)\n\t\t\tcontinue\n\t\t}\n\t\tresources.HugetlbLimit = append(resources.HugetlbLimit, \u0026libcontainerconfigs.HugepageLimit{\n\t\t\tPagesize: sizeString,\n\t\t\tLimit: uint64(limit),\n\t\t})\n\t\tpageSizes.Insert(sizeString)\n\t}\n\t// for each page size omitted, limit to 0\n\tfor _, pageSize := range libcontainercgroups.HugePageSizes() {\n\t\tif pageSizes.Has(pageSize) {\n\t\t\tcontinue\n\t\t}\n\t\tresources.HugetlbLimit = append(resources.HugetlbLimit, \u0026libcontainerconfigs.HugepageLimit{\n\t\t\tPagesize: pageSize,\n\t\t\tLimit: uint64(0),\n\t\t})\n\t}\n}","line":{"from":396,"to":432}} {"id":100005522,"name":"Update","signature":"func (m *cgroupManagerImpl) Update(cgroupConfig *CgroupConfig) error","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"// Update updates the cgroup with the specified Cgroup Configuration\nfunc (m *cgroupManagerImpl) Update(cgroupConfig *CgroupConfig) error {\n\tstart := time.Now()\n\tdefer func() {\n\t\tmetrics.CgroupManagerDuration.WithLabelValues(\"update\").Observe(metrics.SinceInSeconds(start))\n\t}()\n\n\tlibcontainerCgroupConfig := m.libctCgroupConfig(cgroupConfig, true)\n\tmanager, err := manager.New(libcontainerCgroupConfig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create cgroup manager: %v\", err)\n\t}\n\treturn manager.Set(libcontainerCgroupConfig.Resources)\n}","line":{"from":434,"to":447}} {"id":100005523,"name":"Create","signature":"func (m *cgroupManagerImpl) Create(cgroupConfig *CgroupConfig) error","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"// Create creates the specified cgroup\nfunc (m *cgroupManagerImpl) Create(cgroupConfig *CgroupConfig) error {\n\tstart := time.Now()\n\tdefer func() {\n\t\tmetrics.CgroupManagerDuration.WithLabelValues(\"create\").Observe(metrics.SinceInSeconds(start))\n\t}()\n\n\tlibcontainerCgroupConfig := m.libctCgroupConfig(cgroupConfig, true)\n\tmanager, err := manager.New(libcontainerCgroupConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Apply(-1) is a hack to create the cgroup directories for each resource\n\t// subsystem. The function [cgroups.Manager.apply()] applies cgroup\n\t// configuration to the process with the specified pid.\n\t// It creates cgroup files for each subsystems and writes the pid\n\t// in the tasks file. We use the function to create all the required\n\t// cgroup files but not attach any \"real\" pid to the cgroup.\n\tif err := manager.Apply(-1); err != nil {\n\t\treturn err\n\t}\n\n\t// it may confuse why we call set after we do apply, but the issue is that runc\n\t// follows a similar pattern. it's needed to ensure cpu quota is set properly.\n\tif err := manager.Set(libcontainerCgroupConfig.Resources); err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"cgroup manager.Set failed: %w\", err))\n\t}\n\n\treturn nil\n}","line":{"from":449,"to":479}} {"id":100005524,"name":"Pids","signature":"func (m *cgroupManagerImpl) Pids(name CgroupName) []int","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"// Scans through all subsystems to find pids associated with specified cgroup.\nfunc (m *cgroupManagerImpl) Pids(name CgroupName) []int {\n\t// we need the driver specific name\n\tcgroupFsName := m.Name(name)\n\n\t// Get a list of processes that we need to kill\n\tpidsToKill := sets.NewInt()\n\tvar pids []int\n\tfor _, val := range m.subsystems.MountPoints {\n\t\tdir := path.Join(val, cgroupFsName)\n\t\t_, err := os.Stat(dir)\n\t\tif os.IsNotExist(err) {\n\t\t\t// The subsystem pod cgroup is already deleted\n\t\t\t// do nothing, continue\n\t\t\tcontinue\n\t\t}\n\t\t// Get a list of pids that are still charged to the pod's cgroup\n\t\tpids, err = getCgroupProcs(dir)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tpidsToKill.Insert(pids...)\n\n\t\t// WalkFunc which is called for each file and directory in the pod cgroup dir\n\t\tvisitor := func(path string, info os.FileInfo, err error) error {\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).InfoS(\"Cgroup manager encountered error scanning cgroup path\", \"path\", path, \"err\", err)\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t\tif !info.IsDir() {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tpids, err = getCgroupProcs(path)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).InfoS(\"Cgroup manager encountered error getting procs for cgroup path\", \"path\", path, \"err\", err)\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t\tpidsToKill.Insert(pids...)\n\t\t\treturn nil\n\t\t}\n\t\t// Walk through the pod cgroup directory to check if\n\t\t// container cgroups haven't been GCed yet. Get attached processes to\n\t\t// all such unwanted containers under the pod cgroup\n\t\tif err = filepath.Walk(dir, visitor); err != nil {\n\t\t\tklog.V(4).InfoS(\"Cgroup manager encountered error scanning pids for directory\", \"path\", dir, \"err\", err)\n\t\t}\n\t}\n\treturn pidsToKill.List()\n}","line":{"from":481,"to":529}} {"id":100005525,"name":"ReduceCPULimits","signature":"func (m *cgroupManagerImpl) ReduceCPULimits(cgroupName CgroupName) error","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"// ReduceCPULimits reduces the cgroup's cpu shares to the lowest possible value\nfunc (m *cgroupManagerImpl) ReduceCPULimits(cgroupName CgroupName) error {\n\t// Set lowest possible CpuShares value for the cgroup\n\tminimumCPUShares := uint64(MinShares)\n\tresources := \u0026ResourceConfig{\n\t\tCPUShares: \u0026minimumCPUShares,\n\t}\n\tcontainerConfig := \u0026CgroupConfig{\n\t\tName: cgroupName,\n\t\tResourceParameters: resources,\n\t}\n\treturn m.Update(containerConfig)\n}","line":{"from":531,"to":543}} {"id":100005526,"name":"MemoryUsage","signature":"func (m *cgroupManagerImpl) MemoryUsage(name CgroupName) (int64, error)","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"// MemoryUsage returns the current memory usage of the specified cgroup,\n// as read from cgroupfs.\nfunc (m *cgroupManagerImpl) MemoryUsage(name CgroupName) (int64, error) {\n\tvar path, file string\n\tif libcontainercgroups.IsCgroup2UnifiedMode() {\n\t\tpath = m.buildCgroupUnifiedPath(name)\n\t\tfile = \"memory.current\"\n\t} else {\n\t\tmp, ok := m.subsystems.MountPoints[\"memory\"]\n\t\tif !ok { // should not happen\n\t\t\treturn -1, errors.New(\"no cgroup v1 mountpoint for memory controller found\")\n\t\t}\n\t\tpath = mp + \"/\" + m.Name(name)\n\t\tfile = \"memory.usage_in_bytes\"\n\t}\n\tval, err := fscommon.GetCgroupParamUint(path, file)\n\treturn int64(val), err\n}","line":{"from":545,"to":562}} {"id":100005527,"name":"CpuSharesToCpuWeight","signature":"func CpuSharesToCpuWeight(cpuShares uint64) uint64","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"// Convert cgroup v1 cpu.shares value to cgroup v2 cpu.weight\n// https://github.com/kubernetes/enhancements/tree/master/keps/sig-node/2254-cgroup-v2#phase-1-convert-from-cgroups-v1-settings-to-v2\nfunc CpuSharesToCpuWeight(cpuShares uint64) uint64 {\n\treturn uint64((((cpuShares - 2) * 9999) / 262142) + 1)\n}","line":{"from":564,"to":568}} {"id":100005528,"name":"CpuWeightToCpuShares","signature":"func CpuWeightToCpuShares(cpuWeight uint64) uint64","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"// Convert cgroup v2 cpu.weight value to cgroup v1 cpu.shares\n// https://github.com/kubernetes/enhancements/tree/master/keps/sig-node/2254-cgroup-v2#phase-1-convert-from-cgroups-v1-settings-to-v2\nfunc CpuWeightToCpuShares(cpuWeight uint64) uint64 {\n\treturn uint64((((cpuWeight - 1) * 262142) / 9999) + 2)\n}","line":{"from":570,"to":574}} {"id":100005529,"name":"getCgroupv1CpuConfig","signature":"func getCgroupv1CpuConfig(cgroupPath string) (*ResourceConfig, error)","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"func getCgroupv1CpuConfig(cgroupPath string) (*ResourceConfig, error) {\n\tcpuQuotaStr, errQ := fscommon.GetCgroupParamString(cgroupPath, \"cpu.cfs_quota_us\")\n\tif errQ != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read CPU quota for cgroup %v: %v\", cgroupPath, errQ)\n\t}\n\tcpuQuota, errInt := strconv.ParseInt(cpuQuotaStr, 10, 64)\n\tif errInt != nil {\n\t\treturn nil, fmt.Errorf(\"failed to convert CPU quota as integer for cgroup %v: %v\", cgroupPath, errInt)\n\t}\n\tcpuPeriod, errP := fscommon.GetCgroupParamUint(cgroupPath, \"cpu.cfs_period_us\")\n\tif errP != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read CPU period for cgroup %v: %v\", cgroupPath, errP)\n\t}\n\tcpuShares, errS := fscommon.GetCgroupParamUint(cgroupPath, \"cpu.shares\")\n\tif errS != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read CPU shares for cgroup %v: %v\", cgroupPath, errS)\n\t}\n\treturn \u0026ResourceConfig{CPUShares: \u0026cpuShares, CPUQuota: \u0026cpuQuota, CPUPeriod: \u0026cpuPeriod}, nil\n}","line":{"from":576,"to":594}} {"id":100005530,"name":"getCgroupv2CpuConfig","signature":"func getCgroupv2CpuConfig(cgroupPath string) (*ResourceConfig, error)","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"func getCgroupv2CpuConfig(cgroupPath string) (*ResourceConfig, error) {\n\tvar cpuLimitStr, cpuPeriodStr string\n\tcpuLimitAndPeriod, err := fscommon.GetCgroupParamString(cgroupPath, \"cpu.max\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read cpu.max file for cgroup %v: %v\", cgroupPath, err)\n\t}\n\tnumItems, errScan := fmt.Sscanf(cpuLimitAndPeriod, \"%s %s\", \u0026cpuLimitStr, \u0026cpuPeriodStr)\n\tif errScan != nil || numItems != 2 {\n\t\treturn nil, fmt.Errorf(\"failed to correctly parse content of cpu.max file ('%s') for cgroup %v: %v\",\n\t\t\tcpuLimitAndPeriod, cgroupPath, errScan)\n\t}\n\tcpuLimit := int64(-1)\n\tif cpuLimitStr != Cgroup2MaxCpuLimit {\n\t\tcpuLimit, err = strconv.ParseInt(cpuLimitStr, 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to convert CPU limit as integer for cgroup %v: %v\", cgroupPath, err)\n\t\t}\n\t}\n\tcpuPeriod, errPeriod := strconv.ParseUint(cpuPeriodStr, 10, 64)\n\tif errPeriod != nil {\n\t\treturn nil, fmt.Errorf(\"failed to convert CPU period as integer for cgroup %v: %v\", cgroupPath, errPeriod)\n\t}\n\tcpuWeight, errWeight := fscommon.GetCgroupParamUint(cgroupPath, \"cpu.weight\")\n\tif errWeight != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read CPU weight for cgroup %v: %v\", cgroupPath, errWeight)\n\t}\n\tcpuShares := CpuWeightToCpuShares(cpuWeight)\n\treturn \u0026ResourceConfig{CPUShares: \u0026cpuShares, CPUQuota: \u0026cpuLimit, CPUPeriod: \u0026cpuPeriod}, nil\n}","line":{"from":596,"to":624}} {"id":100005531,"name":"getCgroupCpuConfig","signature":"func getCgroupCpuConfig(cgroupPath string) (*ResourceConfig, error)","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"func getCgroupCpuConfig(cgroupPath string) (*ResourceConfig, error) {\n\tif libcontainercgroups.IsCgroup2UnifiedMode() {\n\t\treturn getCgroupv2CpuConfig(cgroupPath)\n\t} else {\n\t\treturn getCgroupv1CpuConfig(cgroupPath)\n\t}\n}","line":{"from":626,"to":632}} {"id":100005532,"name":"getCgroupMemoryConfig","signature":"func getCgroupMemoryConfig(cgroupPath string) (*ResourceConfig, error)","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"func getCgroupMemoryConfig(cgroupPath string) (*ResourceConfig, error) {\n\tmemLimitFile := \"memory.limit_in_bytes\"\n\tif libcontainercgroups.IsCgroup2UnifiedMode() {\n\t\tmemLimitFile = \"memory.max\"\n\t}\n\tmemLimit, err := fscommon.GetCgroupParamUint(cgroupPath, memLimitFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read %s for cgroup %v: %v\", memLimitFile, cgroupPath, err)\n\t}\n\tmLim := int64(memLimit)\n\t//TODO(vinaykul,InPlacePodVerticalScaling): Add memory request support\n\treturn \u0026ResourceConfig{Memory: \u0026mLim}, nil\n\n}","line":{"from":634,"to":647}} {"id":100005533,"name":"GetCgroupConfig","signature":"func (m *cgroupManagerImpl) GetCgroupConfig(name CgroupName, resource v1.ResourceName) (*ResourceConfig, error)","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"// Get the resource config values applied to the cgroup for specified resource type\nfunc (m *cgroupManagerImpl) GetCgroupConfig(name CgroupName, resource v1.ResourceName) (*ResourceConfig, error) {\n\tcgroupPaths := m.buildCgroupPaths(name)\n\tcgroupResourcePath, found := cgroupPaths[string(resource)]\n\tif !found {\n\t\treturn nil, fmt.Errorf(\"failed to build %v cgroup fs path for cgroup %v\", resource, name)\n\t}\n\tswitch resource {\n\tcase v1.ResourceCPU:\n\t\treturn getCgroupCpuConfig(cgroupResourcePath)\n\tcase v1.ResourceMemory:\n\t\treturn getCgroupMemoryConfig(cgroupResourcePath)\n\t}\n\treturn nil, fmt.Errorf(\"unsupported resource %v for cgroup %v\", resource, name)\n}","line":{"from":649,"to":663}} {"id":100005534,"name":"setCgroupv1CpuConfig","signature":"func setCgroupv1CpuConfig(cgroupPath string, resourceConfig *ResourceConfig) error","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"func setCgroupv1CpuConfig(cgroupPath string, resourceConfig *ResourceConfig) error {\n\tvar cpuQuotaStr, cpuPeriodStr, cpuSharesStr string\n\tif resourceConfig.CPUQuota != nil {\n\t\tcpuQuotaStr = strconv.FormatInt(*resourceConfig.CPUQuota, 10)\n\t\tif err := os.WriteFile(filepath.Join(cgroupPath, \"cpu.cfs_quota_us\"), []byte(cpuQuotaStr), 0700); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to write %v to %v: %v\", cpuQuotaStr, cgroupPath, err)\n\t\t}\n\t}\n\tif resourceConfig.CPUPeriod != nil {\n\t\tcpuPeriodStr = strconv.FormatUint(*resourceConfig.CPUPeriod, 10)\n\t\tif err := os.WriteFile(filepath.Join(cgroupPath, \"cpu.cfs_period_us\"), []byte(cpuPeriodStr), 0700); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to write %v to %v: %v\", cpuPeriodStr, cgroupPath, err)\n\t\t}\n\t}\n\tif resourceConfig.CPUShares != nil {\n\t\tcpuSharesStr = strconv.FormatUint(*resourceConfig.CPUShares, 10)\n\t\tif err := os.WriteFile(filepath.Join(cgroupPath, \"cpu.shares\"), []byte(cpuSharesStr), 0700); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to write %v to %v: %v\", cpuSharesStr, cgroupPath, err)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":665,"to":686}} {"id":100005535,"name":"setCgroupv2CpuConfig","signature":"func setCgroupv2CpuConfig(cgroupPath string, resourceConfig *ResourceConfig) error","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"func setCgroupv2CpuConfig(cgroupPath string, resourceConfig *ResourceConfig) error {\n\tif resourceConfig.CPUQuota != nil {\n\t\tif resourceConfig.CPUPeriod == nil {\n\t\t\treturn fmt.Errorf(\"CpuPeriod must be specified in order to set CpuLimit\")\n\t\t}\n\t\tcpuLimitStr := Cgroup2MaxCpuLimit\n\t\tif *resourceConfig.CPUQuota \u003e -1 {\n\t\t\tcpuLimitStr = strconv.FormatInt(*resourceConfig.CPUQuota, 10)\n\t\t}\n\t\tcpuPeriodStr := strconv.FormatUint(*resourceConfig.CPUPeriod, 10)\n\t\tcpuMaxStr := fmt.Sprintf(\"%s %s\", cpuLimitStr, cpuPeriodStr)\n\t\tif err := os.WriteFile(filepath.Join(cgroupPath, \"cpu.max\"), []byte(cpuMaxStr), 0700); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to write %v to %v: %v\", cpuMaxStr, cgroupPath, err)\n\t\t}\n\t}\n\tif resourceConfig.CPUShares != nil {\n\t\tcpuWeight := CpuSharesToCpuWeight(*resourceConfig.CPUShares)\n\t\tcpuWeightStr := strconv.FormatUint(cpuWeight, 10)\n\t\tif err := os.WriteFile(filepath.Join(cgroupPath, \"cpu.weight\"), []byte(cpuWeightStr), 0700); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to write %v to %v: %v\", cpuWeightStr, cgroupPath, err)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":688,"to":711}} {"id":100005536,"name":"setCgroupCpuConfig","signature":"func setCgroupCpuConfig(cgroupPath string, resourceConfig *ResourceConfig) error","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"func setCgroupCpuConfig(cgroupPath string, resourceConfig *ResourceConfig) error {\n\tif libcontainercgroups.IsCgroup2UnifiedMode() {\n\t\treturn setCgroupv2CpuConfig(cgroupPath, resourceConfig)\n\t} else {\n\t\treturn setCgroupv1CpuConfig(cgroupPath, resourceConfig)\n\t}\n}","line":{"from":713,"to":719}} {"id":100005537,"name":"setCgroupMemoryConfig","signature":"func setCgroupMemoryConfig(cgroupPath string, resourceConfig *ResourceConfig) error","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"func setCgroupMemoryConfig(cgroupPath string, resourceConfig *ResourceConfig) error {\n\tmemLimitFile := \"memory.limit_in_bytes\"\n\tif libcontainercgroups.IsCgroup2UnifiedMode() {\n\t\tmemLimitFile = \"memory.max\"\n\t}\n\tmemLimit := strconv.FormatInt(*resourceConfig.Memory, 10)\n\tif err := os.WriteFile(filepath.Join(cgroupPath, memLimitFile), []byte(memLimit), 0700); err != nil {\n\t\treturn fmt.Errorf(\"failed to write %v to %v/%v: %v\", memLimit, cgroupPath, memLimitFile, err)\n\t}\n\t//TODO(vinaykul,InPlacePodVerticalScaling): Add memory request support\n\treturn nil\n}","line":{"from":721,"to":732}} {"id":100005538,"name":"SetCgroupConfig","signature":"func (m *cgroupManagerImpl) SetCgroupConfig(name CgroupName, resource v1.ResourceName, resourceConfig *ResourceConfig) error","file":"pkg/kubelet/cm/cgroup_manager_linux.go","code":"// Set resource config for the specified resource type on the cgroup\nfunc (m *cgroupManagerImpl) SetCgroupConfig(name CgroupName, resource v1.ResourceName, resourceConfig *ResourceConfig) error {\n\tcgroupPaths := m.buildCgroupPaths(name)\n\tcgroupResourcePath, found := cgroupPaths[string(resource)]\n\tif !found {\n\t\treturn fmt.Errorf(\"failed to build %v cgroup fs path for cgroup %v\", resource, name)\n\t}\n\tswitch resource {\n\tcase v1.ResourceCPU:\n\t\treturn setCgroupCpuConfig(cgroupResourcePath, resourceConfig)\n\tcase v1.ResourceMemory:\n\t\treturn setCgroupMemoryConfig(cgroupResourcePath, resourceConfig)\n\t}\n\treturn nil\n}","line":{"from":734,"to":748}} {"id":100005539,"name":"NewCgroupManager","signature":"func NewCgroupManager(_ interface{}) CgroupManager","file":"pkg/kubelet/cm/cgroup_manager_unsupported.go","code":"func NewCgroupManager(_ interface{}) CgroupManager {\n\treturn \u0026unsupportedCgroupManager{}\n}","line":{"from":40,"to":42}} {"id":100005540,"name":"Name","signature":"func (m *unsupportedCgroupManager) Name(_ CgroupName) string","file":"pkg/kubelet/cm/cgroup_manager_unsupported.go","code":"func (m *unsupportedCgroupManager) Name(_ CgroupName) string {\n\treturn \"\"\n}","line":{"from":44,"to":46}} {"id":100005541,"name":"Validate","signature":"func (m *unsupportedCgroupManager) Validate(_ CgroupName) error","file":"pkg/kubelet/cm/cgroup_manager_unsupported.go","code":"func (m *unsupportedCgroupManager) Validate(_ CgroupName) error {\n\treturn errNotSupported\n}","line":{"from":48,"to":50}} {"id":100005542,"name":"Exists","signature":"func (m *unsupportedCgroupManager) Exists(_ CgroupName) bool","file":"pkg/kubelet/cm/cgroup_manager_unsupported.go","code":"func (m *unsupportedCgroupManager) Exists(_ CgroupName) bool {\n\treturn false\n}","line":{"from":52,"to":54}} {"id":100005543,"name":"Destroy","signature":"func (m *unsupportedCgroupManager) Destroy(_ *CgroupConfig) error","file":"pkg/kubelet/cm/cgroup_manager_unsupported.go","code":"func (m *unsupportedCgroupManager) Destroy(_ *CgroupConfig) error {\n\treturn nil\n}","line":{"from":56,"to":58}} {"id":100005544,"name":"Update","signature":"func (m *unsupportedCgroupManager) Update(_ *CgroupConfig) error","file":"pkg/kubelet/cm/cgroup_manager_unsupported.go","code":"func (m *unsupportedCgroupManager) Update(_ *CgroupConfig) error {\n\treturn nil\n}","line":{"from":60,"to":62}} {"id":100005545,"name":"Create","signature":"func (m *unsupportedCgroupManager) Create(_ *CgroupConfig) error","file":"pkg/kubelet/cm/cgroup_manager_unsupported.go","code":"func (m *unsupportedCgroupManager) Create(_ *CgroupConfig) error {\n\treturn errNotSupported\n}","line":{"from":64,"to":66}} {"id":100005546,"name":"MemoryUsage","signature":"func (m *unsupportedCgroupManager) MemoryUsage(_ CgroupName) (int64, error)","file":"pkg/kubelet/cm/cgroup_manager_unsupported.go","code":"func (m *unsupportedCgroupManager) MemoryUsage(_ CgroupName) (int64, error) {\n\treturn -1, errNotSupported\n}","line":{"from":68,"to":70}} {"id":100005547,"name":"Pids","signature":"func (m *unsupportedCgroupManager) Pids(_ CgroupName) []int","file":"pkg/kubelet/cm/cgroup_manager_unsupported.go","code":"func (m *unsupportedCgroupManager) Pids(_ CgroupName) []int {\n\treturn nil\n}","line":{"from":72,"to":74}} {"id":100005548,"name":"CgroupName","signature":"func (m *unsupportedCgroupManager) CgroupName(name string) CgroupName","file":"pkg/kubelet/cm/cgroup_manager_unsupported.go","code":"func (m *unsupportedCgroupManager) CgroupName(name string) CgroupName {\n\treturn CgroupName([]string{})\n}","line":{"from":76,"to":78}} {"id":100005549,"name":"ReduceCPULimits","signature":"func (m *unsupportedCgroupManager) ReduceCPULimits(cgroupName CgroupName) error","file":"pkg/kubelet/cm/cgroup_manager_unsupported.go","code":"func (m *unsupportedCgroupManager) ReduceCPULimits(cgroupName CgroupName) error {\n\treturn nil\n}","line":{"from":80,"to":82}} {"id":100005550,"name":"GetCgroupConfig","signature":"func (m *unsupportedCgroupManager) GetCgroupConfig(name CgroupName, resource v1.ResourceName) (*ResourceConfig, error)","file":"pkg/kubelet/cm/cgroup_manager_unsupported.go","code":"func (m *unsupportedCgroupManager) GetCgroupConfig(name CgroupName, resource v1.ResourceName) (*ResourceConfig, error) {\n\treturn nil, errNotSupported\n}","line":{"from":84,"to":86}} {"id":100005551,"name":"SetCgroupConfig","signature":"func (m *unsupportedCgroupManager) SetCgroupConfig(name CgroupName, resource v1.ResourceName, resourceConfig *ResourceConfig) error","file":"pkg/kubelet/cm/cgroup_manager_unsupported.go","code":"func (m *unsupportedCgroupManager) SetCgroupConfig(name CgroupName, resource v1.ResourceName, resourceConfig *ResourceConfig) error {\n\treturn errNotSupported\n}","line":{"from":88,"to":90}} {"id":100005552,"name":"NewCgroupName","signature":"func NewCgroupName(base CgroupName, components ...string) CgroupName","file":"pkg/kubelet/cm/cgroup_manager_unsupported.go","code":"func NewCgroupName(base CgroupName, components ...string) CgroupName {\n\treturn append(append([]string{}, base...), components...)\n}","line":{"from":94,"to":96}} {"id":100005553,"name":"ToSystemd","signature":"func (cgroupName CgroupName) ToSystemd() string","file":"pkg/kubelet/cm/cgroup_manager_unsupported.go","code":"func (cgroupName CgroupName) ToSystemd() string {\n\treturn \"\"\n}","line":{"from":98,"to":100}} {"id":100005554,"name":"ParseSystemdToCgroupName","signature":"func ParseSystemdToCgroupName(name string) CgroupName","file":"pkg/kubelet/cm/cgroup_manager_unsupported.go","code":"func ParseSystemdToCgroupName(name string) CgroupName {\n\treturn nil\n}","line":{"from":102,"to":104}} {"id":100005555,"name":"ToCgroupfs","signature":"func (cgroupName CgroupName) ToCgroupfs() string","file":"pkg/kubelet/cm/cgroup_manager_unsupported.go","code":"func (cgroupName CgroupName) ToCgroupfs() string {\n\treturn \"\"\n}","line":{"from":106,"to":108}} {"id":100005556,"name":"ParseCgroupfsToCgroupName","signature":"func ParseCgroupfsToCgroupName(name string) CgroupName","file":"pkg/kubelet/cm/cgroup_manager_unsupported.go","code":"func ParseCgroupfsToCgroupName(name string) CgroupName {\n\treturn nil\n}","line":{"from":110,"to":112}} {"id":100005557,"name":"IsSystemdStyleName","signature":"func IsSystemdStyleName(name string) bool","file":"pkg/kubelet/cm/cgroup_manager_unsupported.go","code":"func IsSystemdStyleName(name string) bool {\n\treturn false\n}","line":{"from":114,"to":116}} {"id":100005558,"name":"parsePercentage","signature":"func parsePercentage(v string) (int64, error)","file":"pkg/kubelet/cm/container_manager.go","code":"// parsePercentage parses the percentage string to numeric value.\nfunc parsePercentage(v string) (int64, error) {\n\tif !strings.HasSuffix(v, \"%\") {\n\t\treturn 0, fmt.Errorf(\"percentage expected, got '%s'\", v)\n\t}\n\tpercentage, err := strconv.ParseInt(strings.TrimRight(v, \"%\"), 10, 0)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"invalid number in percentage '%s'\", v)\n\t}\n\tif percentage \u003c 0 || percentage \u003e 100 {\n\t\treturn 0, fmt.Errorf(\"percentage must be between 0 and 100\")\n\t}\n\treturn percentage, nil\n}","line":{"from":178,"to":191}} {"id":100005559,"name":"ParseQOSReserved","signature":"func ParseQOSReserved(m map[string]string) (*map[v1.ResourceName]int64, error)","file":"pkg/kubelet/cm/container_manager.go","code":"// ParseQOSReserved parses the --qos-reserve-requests option\nfunc ParseQOSReserved(m map[string]string) (*map[v1.ResourceName]int64, error) {\n\treservations := make(map[v1.ResourceName]int64)\n\tfor k, v := range m {\n\t\tswitch v1.ResourceName(k) {\n\t\t// Only memory resources are supported.\n\t\tcase v1.ResourceMemory:\n\t\t\tq, err := parsePercentage(v)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to parse percentage %q for %q resource: %w\", v, k, err)\n\t\t\t}\n\t\t\treservations[v1.ResourceName(k)] = q\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"cannot reserve %q resource\", k)\n\t\t}\n\t}\n\treturn \u0026reservations, nil\n}","line":{"from":193,"to":210}} {"id":100005560,"name":"containerDevicesFromResourceDeviceInstances","signature":"func containerDevicesFromResourceDeviceInstances(devs devicemanager.ResourceDeviceInstances) []*podresourcesapi.ContainerDevices","file":"pkg/kubelet/cm/container_manager.go","code":"func containerDevicesFromResourceDeviceInstances(devs devicemanager.ResourceDeviceInstances) []*podresourcesapi.ContainerDevices {\n\tvar respDevs []*podresourcesapi.ContainerDevices\n\n\tfor resourceName, resourceDevs := range devs {\n\t\tfor devID, dev := range resourceDevs {\n\t\t\ttopo := dev.GetTopology()\n\t\t\tif topo == nil {\n\t\t\t\t// Some device plugin do not report the topology information.\n\t\t\t\t// This is legal, so we report the devices anyway,\n\t\t\t\t// let the client decide what to do.\n\t\t\t\trespDevs = append(respDevs, \u0026podresourcesapi.ContainerDevices{\n\t\t\t\t\tResourceName: resourceName,\n\t\t\t\t\tDeviceIds: []string{devID},\n\t\t\t\t})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor _, node := range topo.GetNodes() {\n\t\t\t\trespDevs = append(respDevs, \u0026podresourcesapi.ContainerDevices{\n\t\t\t\t\tResourceName: resourceName,\n\t\t\t\t\tDeviceIds: []string{devID},\n\t\t\t\t\tTopology: \u0026podresourcesapi.TopologyInfo{\n\t\t\t\t\t\tNodes: []*podresourcesapi.NUMANode{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tID: node.GetID(),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn respDevs\n}","line":{"from":212,"to":246}} {"id":100005561,"name":"newSystemCgroups","signature":"func newSystemCgroups(containerName string) (*systemContainer, error)","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func newSystemCgroups(containerName string) (*systemContainer, error) {\n\tmanager, err := createManager(containerName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026systemContainer{\n\t\tname: containerName,\n\t\tmanager: manager,\n\t}, nil\n}","line":{"from":88,"to":97}} {"id":100005562,"name":"validateSystemRequirements","signature":"func validateSystemRequirements(mountUtil mount.Interface) (features, error)","file":"pkg/kubelet/cm/container_manager_linux.go","code":"// checks if the required cgroups subsystems are mounted.\n// As of now, only 'cpu' and 'memory' are required.\n// cpu quota is a soft requirement.\nfunc validateSystemRequirements(mountUtil mount.Interface) (features, error) {\n\tconst (\n\t\tcgroupMountType = \"cgroup\"\n\t\tlocalErr = \"system validation failed\"\n\t)\n\tvar (\n\t\tcpuMountPoint string\n\t\tf features\n\t)\n\tmountPoints, err := mountUtil.List()\n\tif err != nil {\n\t\treturn f, fmt.Errorf(\"%s - %v\", localErr, err)\n\t}\n\n\tif cgroups.IsCgroup2UnifiedMode() {\n\t\tf.cpuHardcapping = true\n\t\treturn f, nil\n\t}\n\n\texpectedCgroups := sets.NewString(\"cpu\", \"cpuacct\", \"cpuset\", \"memory\")\n\tfor _, mountPoint := range mountPoints {\n\t\tif mountPoint.Type == cgroupMountType {\n\t\t\tfor _, opt := range mountPoint.Opts {\n\t\t\t\tif expectedCgroups.Has(opt) {\n\t\t\t\t\texpectedCgroups.Delete(opt)\n\t\t\t\t}\n\t\t\t\tif opt == \"cpu\" {\n\t\t\t\t\tcpuMountPoint = mountPoint.Path\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif expectedCgroups.Len() \u003e 0 {\n\t\treturn f, fmt.Errorf(\"%s - Following Cgroup subsystem not mounted: %v\", localErr, expectedCgroups.List())\n\t}\n\n\t// Check if cpu quota is available.\n\t// CPU cgroup is required and so it expected to be mounted at this point.\n\tperiodExists, err := utilpath.Exists(utilpath.CheckFollowSymlink, path.Join(cpuMountPoint, \"cpu.cfs_period_us\"))\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to detect if CPU cgroup cpu.cfs_period_us is available\")\n\t}\n\tquotaExists, err := utilpath.Exists(utilpath.CheckFollowSymlink, path.Join(cpuMountPoint, \"cpu.cfs_quota_us\"))\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to detect if CPU cgroup cpu.cfs_quota_us is available\")\n\t}\n\tif quotaExists \u0026\u0026 periodExists {\n\t\tf.cpuHardcapping = true\n\t}\n\treturn f, nil\n}","line":{"from":143,"to":197}} {"id":100005563,"name":"NewContainerManager","signature":"func NewContainerManager(mountUtil mount.Interface, cadvisorInterface cadvisor.Interface, nodeConfig NodeConfig, failSwapOn bool, recorder record.EventRecorder, kubeClient clientset.Interface) (ContainerManager, error)","file":"pkg/kubelet/cm/container_manager_linux.go","code":"// TODO(vmarmol): Add limits to the system containers.\n// Takes the absolute name of the specified containers.\n// Empty container name disables use of the specified container.\nfunc NewContainerManager(mountUtil mount.Interface, cadvisorInterface cadvisor.Interface, nodeConfig NodeConfig, failSwapOn bool, recorder record.EventRecorder, kubeClient clientset.Interface) (ContainerManager, error) {\n\tsubsystems, err := GetCgroupSubsystems()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get mounted cgroup subsystems: %v\", err)\n\t}\n\n\tif failSwapOn {\n\t\t// Check whether swap is enabled. The Kubelet does not support running with swap enabled.\n\t\tswapFile := \"/proc/swaps\"\n\t\tswapData, err := os.ReadFile(swapFile)\n\t\tif err != nil {\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\tklog.InfoS(\"File does not exist, assuming that swap is disabled\", \"path\", swapFile)\n\t\t\t} else {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\tswapData = bytes.TrimSpace(swapData) // extra trailing \\n\n\t\t\tswapLines := strings.Split(string(swapData), \"\\n\")\n\n\t\t\t// If there is more than one line (table headers) in /proc/swaps, swap is enabled and we should\n\t\t\t// error out unless --fail-swap-on is set to false.\n\t\t\tif len(swapLines) \u003e 1 {\n\t\t\t\treturn nil, fmt.Errorf(\"running with swap on is not supported, please disable swap! or set --fail-swap-on flag to false. /proc/swaps contained: %v\", swapLines)\n\t\t\t}\n\t\t}\n\t}\n\n\tvar internalCapacity = v1.ResourceList{}\n\t// It is safe to invoke `MachineInfo` on cAdvisor before logically initializing cAdvisor here because\n\t// machine info is computed and cached once as part of cAdvisor object creation.\n\t// But `RootFsInfo` and `ImagesFsInfo` are not available at this moment so they will be called later during manager starts\n\tmachineInfo, err := cadvisorInterface.MachineInfo()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcapacity := cadvisor.CapacityFromMachineInfo(machineInfo)\n\tfor k, v := range capacity {\n\t\tinternalCapacity[k] = v\n\t}\n\tpidlimits, err := pidlimit.Stats()\n\tif err == nil \u0026\u0026 pidlimits != nil \u0026\u0026 pidlimits.MaxPID != nil {\n\t\tinternalCapacity[pidlimit.PIDs] = *resource.NewQuantity(\n\t\t\tint64(*pidlimits.MaxPID),\n\t\t\tresource.DecimalSI)\n\t}\n\n\t// Turn CgroupRoot from a string (in cgroupfs path format) to internal CgroupName\n\tcgroupRoot := ParseCgroupfsToCgroupName(nodeConfig.CgroupRoot)\n\tcgroupManager := NewCgroupManager(subsystems, nodeConfig.CgroupDriver)\n\t// Check if Cgroup-root actually exists on the node\n\tif nodeConfig.CgroupsPerQOS {\n\t\t// this does default to / when enabled, but this tests against regressions.\n\t\tif nodeConfig.CgroupRoot == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"invalid configuration: cgroups-per-qos was specified and cgroup-root was not specified. To enable the QoS cgroup hierarchy you need to specify a valid cgroup-root\")\n\t\t}\n\n\t\t// we need to check that the cgroup root actually exists for each subsystem\n\t\t// of note, we always use the cgroupfs driver when performing this check since\n\t\t// the input is provided in that format.\n\t\t// this is important because we do not want any name conversion to occur.\n\t\tif err := cgroupManager.Validate(cgroupRoot); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid configuration: %w\", err)\n\t\t}\n\t\tklog.InfoS(\"Container manager verified user specified cgroup-root exists\", \"cgroupRoot\", cgroupRoot)\n\t\t// Include the top level cgroup for enforcing node allocatable into cgroup-root.\n\t\t// This way, all sub modules can avoid having to understand the concept of node allocatable.\n\t\tcgroupRoot = NewCgroupName(cgroupRoot, defaultNodeAllocatableCgroupName)\n\t}\n\tklog.InfoS(\"Creating Container Manager object based on Node Config\", \"nodeConfig\", nodeConfig)\n\n\tqosContainerManager, err := NewQOSContainerManager(subsystems, cgroupRoot, nodeConfig, cgroupManager)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcm := \u0026containerManagerImpl{\n\t\tcadvisorInterface: cadvisorInterface,\n\t\tmountUtil: mountUtil,\n\t\tNodeConfig: nodeConfig,\n\t\tsubsystems: subsystems,\n\t\tcgroupManager: cgroupManager,\n\t\tcapacity: capacity,\n\t\tinternalCapacity: internalCapacity,\n\t\tcgroupRoot: cgroupRoot,\n\t\trecorder: recorder,\n\t\tqosContainerManager: qosContainerManager,\n\t}\n\n\tcm.topologyManager, err = topologymanager.NewManager(\n\t\tmachineInfo.Topology,\n\t\tnodeConfig.TopologyManagerPolicy,\n\t\tnodeConfig.TopologyManagerScope,\n\t\tnodeConfig.ExperimentalTopologyManagerPolicyOptions,\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tklog.InfoS(\"Creating device plugin manager\")\n\tcm.deviceManager, err = devicemanager.NewManagerImpl(machineInfo.Topology, cm.topologyManager)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcm.topologyManager.AddHintProvider(cm.deviceManager)\n\n\t// initialize DRA manager\n\tif utilfeature.DefaultFeatureGate.Enabled(kubefeatures.DynamicResourceAllocation) {\n\t\tklog.InfoS(\"Creating Dynamic Resource Allocation (DRA) manager\")\n\t\tcm.draManager, err = dra.NewManagerImpl(kubeClient, nodeConfig.KubeletRootDir)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Initialize CPU manager\n\tcm.cpuManager, err = cpumanager.NewManager(\n\t\tnodeConfig.CPUManagerPolicy,\n\t\tnodeConfig.CPUManagerPolicyOptions,\n\t\tnodeConfig.CPUManagerReconcilePeriod,\n\t\tmachineInfo,\n\t\tnodeConfig.NodeAllocatableConfig.ReservedSystemCPUs,\n\t\tcm.GetNodeAllocatableReservation(),\n\t\tnodeConfig.KubeletRootDir,\n\t\tcm.topologyManager,\n\t)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to initialize cpu manager\")\n\t\treturn nil, err\n\t}\n\tcm.topologyManager.AddHintProvider(cm.cpuManager)\n\n\tif utilfeature.DefaultFeatureGate.Enabled(kubefeatures.MemoryManager) {\n\t\tcm.memoryManager, err = memorymanager.NewManager(\n\t\t\tnodeConfig.ExperimentalMemoryManagerPolicy,\n\t\t\tmachineInfo,\n\t\t\tcm.GetNodeAllocatableReservation(),\n\t\t\tnodeConfig.ExperimentalMemoryManagerReservedMemory,\n\t\t\tnodeConfig.KubeletRootDir,\n\t\t\tcm.topologyManager,\n\t\t)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to initialize memory manager\")\n\t\t\treturn nil, err\n\t\t}\n\t\tcm.topologyManager.AddHintProvider(cm.memoryManager)\n\t}\n\n\treturn cm, nil\n}","line":{"from":199,"to":352}} {"id":100005564,"name":"NewPodContainerManager","signature":"func (cm *containerManagerImpl) NewPodContainerManager() PodContainerManager","file":"pkg/kubelet/cm/container_manager_linux.go","code":"// NewPodContainerManager is a factory method returns a PodContainerManager object\n// If qosCgroups are enabled then it returns the general pod container manager\n// otherwise it returns a no-op manager which essentially does nothing\nfunc (cm *containerManagerImpl) NewPodContainerManager() PodContainerManager {\n\tif cm.NodeConfig.CgroupsPerQOS {\n\t\treturn \u0026podContainerManagerImpl{\n\t\t\tqosContainersInfo: cm.GetQOSContainersInfo(),\n\t\t\tsubsystems: cm.subsystems,\n\t\t\tcgroupManager: cm.cgroupManager,\n\t\t\tpodPidsLimit: cm.PodPidsLimit,\n\t\t\tenforceCPULimits: cm.EnforceCPULimits,\n\t\t\t// cpuCFSQuotaPeriod is in microseconds. NodeConfig.CPUCFSQuotaPeriod is time.Duration (measured in nano seconds).\n\t\t\t// Convert (cm.CPUCFSQuotaPeriod) [nanoseconds] / time.Microsecond (1000) to get cpuCFSQuotaPeriod in microseconds.\n\t\t\tcpuCFSQuotaPeriod: uint64(cm.CPUCFSQuotaPeriod / time.Microsecond),\n\t\t}\n\t}\n\treturn \u0026podContainerManagerNoop{\n\t\tcgroupRoot: cm.cgroupRoot,\n\t}\n}","line":{"from":354,"to":373}} {"id":100005565,"name":"InternalContainerLifecycle","signature":"func (cm *containerManagerImpl) InternalContainerLifecycle() InternalContainerLifecycle","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func (cm *containerManagerImpl) InternalContainerLifecycle() InternalContainerLifecycle {\n\treturn \u0026internalContainerLifecycleImpl{cm.cpuManager, cm.memoryManager, cm.topologyManager}\n}","line":{"from":375,"to":377}} {"id":100005566,"name":"createManager","signature":"func createManager(containerName string) (cgroups.Manager, error)","file":"pkg/kubelet/cm/container_manager_linux.go","code":"// Create a cgroup container manager.\nfunc createManager(containerName string) (cgroups.Manager, error) {\n\tcg := \u0026configs.Cgroup{\n\t\tParent: \"/\",\n\t\tName: containerName,\n\t\tResources: \u0026configs.Resources{\n\t\t\tSkipDevices: true,\n\t\t},\n\t\tSystemd: false,\n\t}\n\n\treturn manager.New(cg)\n}","line":{"from":379,"to":391}} {"id":100005567,"name":"setupKernelTunables","signature":"func setupKernelTunables(option KernelTunableBehavior) error","file":"pkg/kubelet/cm/container_manager_linux.go","code":"// setupKernelTunables validates kernel tunable flags are set as expected\n// depending upon the specified option, it will either warn, error, or modify the kernel tunable flags\nfunc setupKernelTunables(option KernelTunableBehavior) error {\n\tdesiredState := map[string]int{\n\t\tutilsysctl.VMOvercommitMemory: utilsysctl.VMOvercommitMemoryAlways,\n\t\tutilsysctl.VMPanicOnOOM: utilsysctl.VMPanicOnOOMInvokeOOMKiller,\n\t\tutilsysctl.KernelPanic: utilsysctl.KernelPanicRebootTimeout,\n\t\tutilsysctl.KernelPanicOnOops: utilsysctl.KernelPanicOnOopsAlways,\n\t\tutilsysctl.RootMaxKeys: utilsysctl.RootMaxKeysSetting,\n\t\tutilsysctl.RootMaxBytes: utilsysctl.RootMaxBytesSetting,\n\t}\n\n\tsysctl := utilsysctl.New()\n\n\terrList := []error{}\n\tfor flag, expectedValue := range desiredState {\n\t\tval, err := sysctl.GetSysctl(flag)\n\t\tif err != nil {\n\t\t\terrList = append(errList, err)\n\t\t\tcontinue\n\t\t}\n\t\tif val == expectedValue {\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch option {\n\t\tcase KernelTunableError:\n\t\t\terrList = append(errList, fmt.Errorf(\"invalid kernel flag: %v, expected value: %v, actual value: %v\", flag, expectedValue, val))\n\t\tcase KernelTunableWarn:\n\t\t\tklog.V(2).InfoS(\"Invalid kernel flag\", \"flag\", flag, \"expectedValue\", expectedValue, \"actualValue\", val)\n\t\tcase KernelTunableModify:\n\t\t\tklog.V(2).InfoS(\"Updating kernel flag\", \"flag\", flag, \"expectedValue\", expectedValue, \"actualValue\", val)\n\t\t\terr = sysctl.SetSysctl(flag, expectedValue)\n\t\t\tif err != nil {\n\t\t\t\tif libcontaineruserns.RunningInUserNS() {\n\t\t\t\t\tif utilfeature.DefaultFeatureGate.Enabled(kubefeatures.KubeletInUserNamespace) {\n\t\t\t\t\t\tklog.V(2).InfoS(\"Updating kernel flag failed (running in UserNS, ignoring)\", \"flag\", flag, \"err\", err)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tklog.ErrorS(err, \"Updating kernel flag failed (Hint: enable KubeletInUserNamespace feature flag to ignore the error)\", \"flag\", flag)\n\t\t\t\t}\n\t\t\t\terrList = append(errList, err)\n\t\t\t}\n\t\t}\n\t}\n\treturn utilerrors.NewAggregate(errList)\n}","line":{"from":401,"to":447}} {"id":100005568,"name":"setupNode","signature":"func (cm *containerManagerImpl) setupNode(activePods ActivePodsFunc) error","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func (cm *containerManagerImpl) setupNode(activePods ActivePodsFunc) error {\n\tf, err := validateSystemRequirements(cm.mountUtil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !f.cpuHardcapping {\n\t\tcm.status.SoftRequirements = fmt.Errorf(\"CPU hardcapping unsupported\")\n\t}\n\tb := KernelTunableModify\n\tif cm.GetNodeConfig().ProtectKernelDefaults {\n\t\tb = KernelTunableError\n\t}\n\tif err := setupKernelTunables(b); err != nil {\n\t\treturn err\n\t}\n\n\t// Setup top level qos containers only if CgroupsPerQOS flag is specified as true\n\tif cm.NodeConfig.CgroupsPerQOS {\n\t\tif err := cm.createNodeAllocatableCgroups(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = cm.qosContainerManager.Start(cm.GetNodeAllocatableAbsolute, activePods)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to initialize top level QOS containers: %v\", err)\n\t\t}\n\t}\n\n\t// Enforce Node Allocatable (if required)\n\tif err := cm.enforceNodeAllocatableCgroups(); err != nil {\n\t\treturn err\n\t}\n\n\tsystemContainers := []*systemContainer{}\n\n\tif cm.SystemCgroupsName != \"\" {\n\t\tif cm.SystemCgroupsName == \"/\" {\n\t\t\treturn fmt.Errorf(\"system container cannot be root (\\\"/\\\")\")\n\t\t}\n\t\tcont, err := newSystemCgroups(cm.SystemCgroupsName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcont.ensureStateFunc = func(manager cgroups.Manager) error {\n\t\t\treturn ensureSystemCgroups(\"/\", manager)\n\t\t}\n\t\tsystemContainers = append(systemContainers, cont)\n\t}\n\n\tif cm.KubeletCgroupsName != \"\" {\n\t\tcont, err := newSystemCgroups(cm.KubeletCgroupsName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcont.ensureStateFunc = func(_ cgroups.Manager) error {\n\t\t\treturn ensureProcessInContainerWithOOMScore(os.Getpid(), int(cm.KubeletOOMScoreAdj), cont.manager)\n\t\t}\n\t\tsystemContainers = append(systemContainers, cont)\n\t} else {\n\t\tcm.periodicTasks = append(cm.periodicTasks, func() {\n\t\t\tif err := ensureProcessInContainerWithOOMScore(os.Getpid(), int(cm.KubeletOOMScoreAdj), nil); err != nil {\n\t\t\t\tklog.ErrorS(err, \"Failed to ensure process in container with oom score\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcont, err := getContainer(os.Getpid())\n\t\t\tif err != nil {\n\t\t\t\tklog.ErrorS(err, \"Failed to find cgroups of kubelet\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcm.Lock()\n\t\t\tdefer cm.Unlock()\n\n\t\t\tcm.KubeletCgroupsName = cont\n\t\t})\n\t}\n\n\tcm.systemContainers = systemContainers\n\treturn nil\n}","line":{"from":449,"to":527}} {"id":100005569,"name":"GetNodeConfig","signature":"func (cm *containerManagerImpl) GetNodeConfig() NodeConfig","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func (cm *containerManagerImpl) GetNodeConfig() NodeConfig {\n\tcm.RLock()\n\tdefer cm.RUnlock()\n\treturn cm.NodeConfig\n}","line":{"from":529,"to":533}} {"id":100005570,"name":"GetPodCgroupRoot","signature":"func (cm *containerManagerImpl) GetPodCgroupRoot() string","file":"pkg/kubelet/cm/container_manager_linux.go","code":"// GetPodCgroupRoot returns the literal cgroupfs value for the cgroup containing all pods.\nfunc (cm *containerManagerImpl) GetPodCgroupRoot() string {\n\treturn cm.cgroupManager.Name(cm.cgroupRoot)\n}","line":{"from":535,"to":538}} {"id":100005571,"name":"GetMountedSubsystems","signature":"func (cm *containerManagerImpl) GetMountedSubsystems() *CgroupSubsystems","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func (cm *containerManagerImpl) GetMountedSubsystems() *CgroupSubsystems {\n\treturn cm.subsystems\n}","line":{"from":540,"to":542}} {"id":100005572,"name":"GetQOSContainersInfo","signature":"func (cm *containerManagerImpl) GetQOSContainersInfo() QOSContainersInfo","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func (cm *containerManagerImpl) GetQOSContainersInfo() QOSContainersInfo {\n\treturn cm.qosContainerManager.GetQOSContainersInfo()\n}","line":{"from":544,"to":546}} {"id":100005573,"name":"UpdateQOSCgroups","signature":"func (cm *containerManagerImpl) UpdateQOSCgroups() error","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func (cm *containerManagerImpl) UpdateQOSCgroups() error {\n\treturn cm.qosContainerManager.UpdateCgroups()\n}","line":{"from":548,"to":550}} {"id":100005574,"name":"Status","signature":"func (cm *containerManagerImpl) Status() Status","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func (cm *containerManagerImpl) Status() Status {\n\tcm.RLock()\n\tdefer cm.RUnlock()\n\treturn cm.status\n}","line":{"from":552,"to":556}} {"id":100005575,"name":"Start","signature":"func (cm *containerManagerImpl) Start(node *v1.Node,","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func (cm *containerManagerImpl) Start(node *v1.Node,\n\tactivePods ActivePodsFunc,\n\tsourcesReady config.SourcesReady,\n\tpodStatusProvider status.PodStatusProvider,\n\truntimeService internalapi.RuntimeService,\n\tlocalStorageCapacityIsolation bool) error {\n\tctx := context.Background()\n\n\t// Initialize CPU manager\n\tcontainerMap := buildContainerMapFromRuntime(ctx, runtimeService)\n\terr := cm.cpuManager.Start(cpumanager.ActivePodsFunc(activePods), sourcesReady, podStatusProvider, runtimeService, containerMap)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"start cpu manager error: %v\", err)\n\t}\n\n\t// Initialize memory manager\n\tif utilfeature.DefaultFeatureGate.Enabled(kubefeatures.MemoryManager) {\n\t\tcontainerMap := buildContainerMapFromRuntime(ctx, runtimeService)\n\t\terr := cm.memoryManager.Start(memorymanager.ActivePodsFunc(activePods), sourcesReady, podStatusProvider, runtimeService, containerMap)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"start memory manager error: %v\", err)\n\t\t}\n\t}\n\n\t// cache the node Info including resource capacity and\n\t// allocatable of the node\n\tcm.nodeInfo = node\n\n\tif localStorageCapacityIsolation {\n\t\trootfs, err := cm.cadvisorInterface.RootFsInfo()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get rootfs info: %v\", err)\n\t\t}\n\t\tfor rName, rCap := range cadvisor.EphemeralStorageCapacityFromFsInfo(rootfs) {\n\t\t\tcm.capacity[rName] = rCap\n\t\t}\n\t}\n\n\t// Ensure that node allocatable configuration is valid.\n\tif err := cm.validateNodeAllocatable(); err != nil {\n\t\treturn err\n\t}\n\n\t// Setup the node\n\tif err := cm.setupNode(activePods); err != nil {\n\t\treturn err\n\t}\n\n\t// Don't run a background thread if there are no ensureStateFuncs.\n\thasEnsureStateFuncs := false\n\tfor _, cont := range cm.systemContainers {\n\t\tif cont.ensureStateFunc != nil {\n\t\t\thasEnsureStateFuncs = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif hasEnsureStateFuncs {\n\t\t// Run ensure state functions every minute.\n\t\tgo wait.Until(func() {\n\t\t\tfor _, cont := range cm.systemContainers {\n\t\t\t\tif cont.ensureStateFunc != nil {\n\t\t\t\t\tif err := cont.ensureStateFunc(cont.manager); err != nil {\n\t\t\t\t\t\tklog.InfoS(\"Failed to ensure state\", \"containerName\", cont.name, \"err\", err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}, time.Minute, wait.NeverStop)\n\n\t}\n\n\tif len(cm.periodicTasks) \u003e 0 {\n\t\tgo wait.Until(func() {\n\t\t\tfor _, task := range cm.periodicTasks {\n\t\t\t\tif task != nil {\n\t\t\t\t\ttask()\n\t\t\t\t}\n\t\t\t}\n\t\t}, 5*time.Minute, wait.NeverStop)\n\t}\n\n\t// Starts device manager.\n\tif err := cm.deviceManager.Start(devicemanager.ActivePodsFunc(activePods), sourcesReady); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":558,"to":644}} {"id":100005576,"name":"GetPluginRegistrationHandler","signature":"func (cm *containerManagerImpl) GetPluginRegistrationHandler() cache.PluginHandler","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func (cm *containerManagerImpl) GetPluginRegistrationHandler() cache.PluginHandler {\n\treturn cm.deviceManager.GetWatcherHandler()\n}","line":{"from":646,"to":648}} {"id":100005577,"name":"GetResources","signature":"func (cm *containerManagerImpl) GetResources(pod *v1.Pod, container *v1.Container) (*kubecontainer.RunContainerOptions, error)","file":"pkg/kubelet/cm/container_manager_linux.go","code":"// TODO: move the GetResources logic to PodContainerManager.\nfunc (cm *containerManagerImpl) GetResources(pod *v1.Pod, container *v1.Container) (*kubecontainer.RunContainerOptions, error) {\n\topts := \u0026kubecontainer.RunContainerOptions{}\n\tif utilfeature.DefaultFeatureGate.Enabled(kubefeatures.DynamicResourceAllocation) {\n\t\tresOpts, err := cm.draManager.GetResources(pod, container)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// NOTE: Passing CDI device names as annotations is a temporary solution\n\t\t// It will be removed after all runtimes are updated\n\t\t// to get CDI device names from the ContainerConfig.CDIDevices field\n\t\topts.Annotations = append(opts.Annotations, resOpts.Annotations...)\n\t\topts.CDIDevices = append(opts.CDIDevices, resOpts.CDIDevices...)\n\t}\n\t// Allocate should already be called during predicateAdmitHandler.Admit(),\n\t// just try to fetch device runtime information from cached state here\n\tdevOpts, err := cm.deviceManager.GetDeviceRunContainerOptions(pod, container)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if devOpts == nil {\n\t\treturn opts, nil\n\t}\n\topts.Devices = append(opts.Devices, devOpts.Devices...)\n\topts.Mounts = append(opts.Mounts, devOpts.Mounts...)\n\topts.Envs = append(opts.Envs, devOpts.Envs...)\n\topts.Annotations = append(opts.Annotations, devOpts.Annotations...)\n\treturn opts, nil\n}","line":{"from":650,"to":677}} {"id":100005578,"name":"UpdatePluginResources","signature":"func (cm *containerManagerImpl) UpdatePluginResources(node *schedulerframework.NodeInfo, attrs *lifecycle.PodAdmitAttributes) error","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func (cm *containerManagerImpl) UpdatePluginResources(node *schedulerframework.NodeInfo, attrs *lifecycle.PodAdmitAttributes) error {\n\treturn cm.deviceManager.UpdatePluginResources(node, attrs)\n}","line":{"from":679,"to":681}} {"id":100005579,"name":"GetAllocateResourcesPodAdmitHandler","signature":"func (cm *containerManagerImpl) GetAllocateResourcesPodAdmitHandler() lifecycle.PodAdmitHandler","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func (cm *containerManagerImpl) GetAllocateResourcesPodAdmitHandler() lifecycle.PodAdmitHandler {\n\treturn cm.topologyManager\n}","line":{"from":683,"to":685}} {"id":100005580,"name":"SystemCgroupsLimit","signature":"func (cm *containerManagerImpl) SystemCgroupsLimit() v1.ResourceList","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func (cm *containerManagerImpl) SystemCgroupsLimit() v1.ResourceList {\n\tcpuLimit := int64(0)\n\n\t// Sum up resources of all external containers.\n\tfor _, cont := range cm.systemContainers {\n\t\tcpuLimit += cont.cpuMillicores\n\t}\n\n\treturn v1.ResourceList{\n\t\tv1.ResourceCPU: *resource.NewMilliQuantity(\n\t\t\tcpuLimit,\n\t\t\tresource.DecimalSI),\n\t}\n}","line":{"from":687,"to":700}} {"id":100005581,"name":"buildContainerMapFromRuntime","signature":"func buildContainerMapFromRuntime(ctx context.Context, runtimeService internalapi.RuntimeService) containermap.ContainerMap","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func buildContainerMapFromRuntime(ctx context.Context, runtimeService internalapi.RuntimeService) containermap.ContainerMap {\n\tpodSandboxMap := make(map[string]string)\n\tpodSandboxList, _ := runtimeService.ListPodSandbox(ctx, nil)\n\tfor _, p := range podSandboxList {\n\t\tpodSandboxMap[p.Id] = p.Metadata.Uid\n\t}\n\n\tcontainerMap := containermap.NewContainerMap()\n\tcontainerList, _ := runtimeService.ListContainers(ctx, nil)\n\tfor _, c := range containerList {\n\t\tif _, exists := podSandboxMap[c.PodSandboxId]; !exists {\n\t\t\tklog.InfoS(\"No PodSandBox found for the container\", \"podSandboxId\", c.PodSandboxId, \"containerName\", c.Metadata.Name, \"containerId\", c.Id)\n\t\t\tcontinue\n\t\t}\n\t\tcontainerMap.Add(podSandboxMap[c.PodSandboxId], c.Metadata.Name, c.Id)\n\t}\n\n\treturn containerMap\n}","line":{"from":702,"to":720}} {"id":100005582,"name":"isProcessRunningInHost","signature":"func isProcessRunningInHost(pid int) (bool, error)","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func isProcessRunningInHost(pid int) (bool, error) {\n\t// Get init pid namespace.\n\tinitPidNs, err := os.Readlink(\"/proc/1/ns/pid\")\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"failed to find pid namespace of init process\")\n\t}\n\tklog.V(10).InfoS(\"Found init PID namespace\", \"namespace\", initPidNs)\n\tprocessPidNs, err := os.Readlink(fmt.Sprintf(\"/proc/%d/ns/pid\", pid))\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"failed to find pid namespace of process %q\", pid)\n\t}\n\tklog.V(10).InfoS(\"Process info\", \"pid\", pid, \"namespace\", processPidNs)\n\treturn initPidNs == processPidNs, nil\n}","line":{"from":722,"to":735}} {"id":100005583,"name":"ensureProcessInContainerWithOOMScore","signature":"func ensureProcessInContainerWithOOMScore(pid int, oomScoreAdj int, manager cgroups.Manager) error","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func ensureProcessInContainerWithOOMScore(pid int, oomScoreAdj int, manager cgroups.Manager) error {\n\tif runningInHost, err := isProcessRunningInHost(pid); err != nil {\n\t\t// Err on the side of caution. Avoid moving the docker daemon unless we are able to identify its context.\n\t\treturn err\n\t} else if !runningInHost {\n\t\t// Process is running inside a container. Don't touch that.\n\t\tklog.V(2).InfoS(\"PID is not running in the host namespace\", \"pid\", pid)\n\t\treturn nil\n\t}\n\n\tvar errs []error\n\tif manager != nil {\n\t\tcont, err := getContainer(pid)\n\t\tif err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"failed to find container of PID %d: %v\", pid, err))\n\t\t}\n\n\t\tname := \"\"\n\t\tcgroups, err := manager.GetCgroups()\n\t\tif err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"failed to get cgroups for %d: %v\", pid, err))\n\t\t} else {\n\t\t\tname = cgroups.Name\n\t\t}\n\n\t\tif cont != name {\n\t\t\terr = manager.Apply(pid)\n\t\t\tif err != nil {\n\t\t\t\terrs = append(errs, fmt.Errorf(\"failed to move PID %d (in %q) to %q: %v\", pid, cont, name, err))\n\t\t\t}\n\t\t}\n\t}\n\n\t// Also apply oom-score-adj to processes\n\toomAdjuster := oom.NewOOMAdjuster()\n\tklog.V(5).InfoS(\"Attempting to apply oom_score_adj to process\", \"oomScoreAdj\", oomScoreAdj, \"pid\", pid)\n\tif err := oomAdjuster.ApplyOOMScoreAdj(pid, oomScoreAdj); err != nil {\n\t\tklog.V(3).InfoS(\"Failed to apply oom_score_adj to process\", \"oomScoreAdj\", oomScoreAdj, \"pid\", pid, \"err\", err)\n\t\terrs = append(errs, fmt.Errorf(\"failed to apply oom score %d to PID %d: %v\", oomScoreAdj, pid, err))\n\t}\n\treturn utilerrors.NewAggregate(errs)\n}","line":{"from":737,"to":778}} {"id":100005584,"name":"getContainer","signature":"func getContainer(pid int) (string, error)","file":"pkg/kubelet/cm/container_manager_linux.go","code":"// getContainer returns the cgroup associated with the specified pid.\n// It enforces a unified hierarchy for memory and cpu cgroups.\n// On systemd environments, it uses the name=systemd cgroup for the specified pid.\nfunc getContainer(pid int) (string, error) {\n\tcgs, err := cgroups.ParseCgroupFile(fmt.Sprintf(\"/proc/%d/cgroup\", pid))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif cgroups.IsCgroup2UnifiedMode() {\n\t\tc, found := cgs[\"\"]\n\t\tif !found {\n\t\t\treturn \"\", cgroups.NewNotFoundError(\"unified\")\n\t\t}\n\t\treturn c, nil\n\t}\n\n\tcpu, found := cgs[\"cpu\"]\n\tif !found {\n\t\treturn \"\", cgroups.NewNotFoundError(\"cpu\")\n\t}\n\tmemory, found := cgs[\"memory\"]\n\tif !found {\n\t\treturn \"\", cgroups.NewNotFoundError(\"memory\")\n\t}\n\n\t// since we use this container for accounting, we need to ensure its a unified hierarchy.\n\tif cpu != memory {\n\t\treturn \"\", fmt.Errorf(\"cpu and memory cgroup hierarchy not unified. cpu: %s, memory: %s\", cpu, memory)\n\t}\n\n\t// on systemd, every pid is in a unified cgroup hierarchy (name=systemd as seen in systemd-cgls)\n\t// cpu and memory accounting is off by default, users may choose to enable it per unit or globally.\n\t// users could enable CPU and memory accounting globally via /etc/systemd/system.conf (DefaultCPUAccounting=true DefaultMemoryAccounting=true).\n\t// users could also enable CPU and memory accounting per unit via CPUAccounting=true and MemoryAccounting=true\n\t// we only warn if accounting is not enabled for CPU or memory so as to not break local development flows where kubelet is launched in a terminal.\n\t// for example, the cgroup for the user session will be something like /user.slice/user-X.slice/session-X.scope, but the cpu and memory\n\t// cgroup will be the closest ancestor where accounting is performed (most likely /) on systems that launch docker containers.\n\t// as a result, on those systems, you will not get cpu or memory accounting statistics for kubelet.\n\t// in addition, you would not get memory or cpu accounting for the runtime unless accounting was enabled on its unit (or globally).\n\tif systemd, found := cgs[\"name=systemd\"]; found {\n\t\tif systemd != cpu {\n\t\t\tklog.InfoS(\"CPUAccounting not enabled for process\", \"pid\", pid)\n\t\t}\n\t\tif systemd != memory {\n\t\t\tklog.InfoS(\"MemoryAccounting not enabled for process\", \"pid\", pid)\n\t\t}\n\t\treturn systemd, nil\n\t}\n\n\treturn cpu, nil\n}","line":{"from":780,"to":831}} {"id":100005585,"name":"ensureSystemCgroups","signature":"func ensureSystemCgroups(rootCgroupPath string, manager cgroups.Manager) error","file":"pkg/kubelet/cm/container_manager_linux.go","code":"// Ensures the system container is created and all non-kernel threads and process 1\n// without a container are moved to it.\n//\n// The reason of leaving kernel threads at root cgroup is that we don't want to tie the\n// execution of these threads with to-be defined /system quota and create priority inversions.\nfunc ensureSystemCgroups(rootCgroupPath string, manager cgroups.Manager) error {\n\t// Move non-kernel PIDs to the system container.\n\t// Only keep errors on latest attempt.\n\tvar finalErr error\n\tfor i := 0; i \u003c= 10; i++ {\n\t\tallPids, err := cmutil.GetPids(rootCgroupPath)\n\t\tif err != nil {\n\t\t\tfinalErr = fmt.Errorf(\"failed to list PIDs for root: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Remove kernel pids and other protected PIDs (pid 1, PIDs already in system \u0026 kubelet containers)\n\t\tpids := make([]int, 0, len(allPids))\n\t\tfor _, pid := range allPids {\n\t\t\tif pid == 1 || isKernelPid(pid) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tpids = append(pids, pid)\n\t\t}\n\n\t\t// Check if we have moved all the non-kernel PIDs.\n\t\tif len(pids) == 0 {\n\t\t\treturn nil\n\t\t}\n\n\t\tklog.V(3).InfoS(\"Moving non-kernel processes\", \"pids\", pids)\n\t\tfor _, pid := range pids {\n\t\t\terr := manager.Apply(pid)\n\t\t\tif err != nil {\n\t\t\t\tname := \"\"\n\t\t\t\tcgroups, err := manager.GetCgroups()\n\t\t\t\tif err == nil {\n\t\t\t\t\tname = cgroups.Name\n\t\t\t\t}\n\n\t\t\t\tfinalErr = fmt.Errorf(\"failed to move PID %d into the system container %q: %v\", pid, name, err)\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn finalErr\n}","line":{"from":833,"to":881}} {"id":100005586,"name":"isKernelPid","signature":"func isKernelPid(pid int) bool","file":"pkg/kubelet/cm/container_manager_linux.go","code":"// Determines whether the specified PID is a kernel PID.\nfunc isKernelPid(pid int) bool {\n\t// Kernel threads have no associated executable.\n\t_, err := os.Readlink(fmt.Sprintf(\"/proc/%d/exe\", pid))\n\treturn err != nil \u0026\u0026 os.IsNotExist(err)\n}","line":{"from":883,"to":888}} {"id":100005587,"name":"GetCapacity","signature":"func (cm *containerManagerImpl) GetCapacity(localStorageCapacityIsolation bool) v1.ResourceList","file":"pkg/kubelet/cm/container_manager_linux.go","code":"// GetCapacity returns node capacity data for \"cpu\", \"memory\", \"ephemeral-storage\", and \"huge-pages*\"\n// At present this method is only invoked when introspecting ephemeral storage\nfunc (cm *containerManagerImpl) GetCapacity(localStorageCapacityIsolation bool) v1.ResourceList {\n\tif localStorageCapacityIsolation {\n\t\t// We store allocatable ephemeral-storage in the capacity property once we Start() the container manager\n\t\tif _, ok := cm.capacity[v1.ResourceEphemeralStorage]; !ok {\n\t\t\t// If we haven't yet stored the capacity for ephemeral-storage, we can try to fetch it directly from cAdvisor,\n\t\t\tif cm.cadvisorInterface != nil {\n\t\t\t\trootfs, err := cm.cadvisorInterface.RootFsInfo()\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"Unable to get rootfs data from cAdvisor interface\")\n\t\t\t\t\t// If the rootfsinfo retrieval from cAdvisor fails for any reason, fallback to returning the capacity property with no ephemeral storage data\n\t\t\t\t\treturn cm.capacity\n\t\t\t\t}\n\t\t\t\t// We don't want to mutate cm.capacity here so we'll manually construct a v1.ResourceList from it,\n\t\t\t\t// and add ephemeral-storage\n\t\t\t\tcapacityWithEphemeralStorage := v1.ResourceList{}\n\t\t\t\tfor rName, rQuant := range cm.capacity {\n\t\t\t\t\tcapacityWithEphemeralStorage[rName] = rQuant\n\t\t\t\t}\n\t\t\t\tcapacityWithEphemeralStorage[v1.ResourceEphemeralStorage] = cadvisor.EphemeralStorageCapacityFromFsInfo(rootfs)[v1.ResourceEphemeralStorage]\n\t\t\t\treturn capacityWithEphemeralStorage\n\t\t\t}\n\t\t}\n\t}\n\treturn cm.capacity\n}","line":{"from":890,"to":916}} {"id":100005588,"name":"GetDevicePluginResourceCapacity","signature":"func (cm *containerManagerImpl) GetDevicePluginResourceCapacity() (v1.ResourceList, v1.ResourceList, []string)","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func (cm *containerManagerImpl) GetDevicePluginResourceCapacity() (v1.ResourceList, v1.ResourceList, []string) {\n\treturn cm.deviceManager.GetCapacity()\n}","line":{"from":918,"to":920}} {"id":100005589,"name":"GetDevices","signature":"func (cm *containerManagerImpl) GetDevices(podUID, containerName string) []*podresourcesapi.ContainerDevices","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func (cm *containerManagerImpl) GetDevices(podUID, containerName string) []*podresourcesapi.ContainerDevices {\n\treturn containerDevicesFromResourceDeviceInstances(cm.deviceManager.GetDevices(podUID, containerName))\n}","line":{"from":922,"to":924}} {"id":100005590,"name":"GetAllocatableDevices","signature":"func (cm *containerManagerImpl) GetAllocatableDevices() []*podresourcesapi.ContainerDevices","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func (cm *containerManagerImpl) GetAllocatableDevices() []*podresourcesapi.ContainerDevices {\n\treturn containerDevicesFromResourceDeviceInstances(cm.deviceManager.GetAllocatableDevices())\n}","line":{"from":926,"to":928}} {"id":100005591,"name":"int64Slice","signature":"func int64Slice(in []int) []int64","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func int64Slice(in []int) []int64 {\n\tout := make([]int64, len(in))\n\tfor i := range in {\n\t\tout[i] = int64(in[i])\n\t}\n\treturn out\n}","line":{"from":930,"to":936}} {"id":100005592,"name":"GetCPUs","signature":"func (cm *containerManagerImpl) GetCPUs(podUID, containerName string) []int64","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func (cm *containerManagerImpl) GetCPUs(podUID, containerName string) []int64 {\n\tif cm.cpuManager != nil {\n\t\treturn int64Slice(cm.cpuManager.GetExclusiveCPUs(podUID, containerName).UnsortedList())\n\t}\n\treturn []int64{}\n}","line":{"from":938,"to":943}} {"id":100005593,"name":"GetAllocatableCPUs","signature":"func (cm *containerManagerImpl) GetAllocatableCPUs() []int64","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func (cm *containerManagerImpl) GetAllocatableCPUs() []int64 {\n\tif cm.cpuManager != nil {\n\t\treturn int64Slice(cm.cpuManager.GetAllocatableCPUs().UnsortedList())\n\t}\n\treturn []int64{}\n}","line":{"from":945,"to":950}} {"id":100005594,"name":"GetMemory","signature":"func (cm *containerManagerImpl) GetMemory(podUID, containerName string) []*podresourcesapi.ContainerMemory","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func (cm *containerManagerImpl) GetMemory(podUID, containerName string) []*podresourcesapi.ContainerMemory {\n\tif cm.memoryManager == nil {\n\t\treturn []*podresourcesapi.ContainerMemory{}\n\t}\n\n\treturn containerMemoryFromBlock(cm.memoryManager.GetMemory(podUID, containerName))\n}","line":{"from":952,"to":958}} {"id":100005595,"name":"GetAllocatableMemory","signature":"func (cm *containerManagerImpl) GetAllocatableMemory() []*podresourcesapi.ContainerMemory","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func (cm *containerManagerImpl) GetAllocatableMemory() []*podresourcesapi.ContainerMemory {\n\tif cm.memoryManager == nil {\n\t\treturn []*podresourcesapi.ContainerMemory{}\n\t}\n\n\treturn containerMemoryFromBlock(cm.memoryManager.GetAllocatableMemory())\n}","line":{"from":960,"to":966}} {"id":100005596,"name":"GetDynamicResources","signature":"func (cm *containerManagerImpl) GetDynamicResources(pod *v1.Pod, container *v1.Container) []*podresourcesapi.DynamicResource","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func (cm *containerManagerImpl) GetDynamicResources(pod *v1.Pod, container *v1.Container) []*podresourcesapi.DynamicResource {\n\tif !utilfeature.DefaultFeatureGate.Enabled(kubefeatures.DynamicResourceAllocation) {\n\t\treturn []*podresourcesapi.DynamicResource{}\n\t}\n\n\tvar containerDynamicResources []*podresourcesapi.DynamicResource\n\tcontainerClaimInfos, err := cm.draManager.GetContainerClaimInfos(pod, container)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Unable to get container claim info state\")\n\t\treturn []*podresourcesapi.DynamicResource{}\n\t}\n\tfor _, containerClaimInfo := range containerClaimInfos {\n\t\tvar claimResources []*podresourcesapi.ClaimResource\n\t\t// TODO: Currently we maintain a list of ClaimResources, each of which contains\n\t\t// a set of CDIDevices from a different kubelet plugin. In the future we may want to\n\t\t// include the name of the kubelet plugin and/or other types of resources that are\n\t\t// not CDIDevices (assuming the DRAmanager supports this).\n\t\tfor _, klPluginCdiDevices := range containerClaimInfo.CDIDevices {\n\t\t\tvar cdiDevices []*podresourcesapi.CDIDevice\n\t\t\tfor _, cdiDevice := range klPluginCdiDevices {\n\t\t\t\tcdiDevices = append(cdiDevices, \u0026podresourcesapi.CDIDevice{Name: cdiDevice})\n\t\t\t}\n\t\t\tclaimResources = append(claimResources, \u0026podresourcesapi.ClaimResource{CDIDevices: cdiDevices})\n\t\t}\n\t\tcontainerDynamicResource := podresourcesapi.DynamicResource{\n\t\t\tClassName: containerClaimInfo.ClassName,\n\t\t\tClaimName: containerClaimInfo.ClaimName,\n\t\t\tClaimNamespace: containerClaimInfo.Namespace,\n\t\t\tClaimResources: claimResources,\n\t\t}\n\t\tcontainerDynamicResources = append(containerDynamicResources, \u0026containerDynamicResource)\n\t}\n\treturn containerDynamicResources\n}","line":{"from":968,"to":1001}} {"id":100005597,"name":"ShouldResetExtendedResourceCapacity","signature":"func (cm *containerManagerImpl) ShouldResetExtendedResourceCapacity() bool","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func (cm *containerManagerImpl) ShouldResetExtendedResourceCapacity() bool {\n\treturn cm.deviceManager.ShouldResetExtendedResourceCapacity()\n}","line":{"from":1003,"to":1005}} {"id":100005598,"name":"UpdateAllocatedDevices","signature":"func (cm *containerManagerImpl) UpdateAllocatedDevices()","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func (cm *containerManagerImpl) UpdateAllocatedDevices() {\n\tcm.deviceManager.UpdateAllocatedDevices()\n}","line":{"from":1007,"to":1009}} {"id":100005599,"name":"containerMemoryFromBlock","signature":"func containerMemoryFromBlock(blocks []memorymanagerstate.Block) []*podresourcesapi.ContainerMemory","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func containerMemoryFromBlock(blocks []memorymanagerstate.Block) []*podresourcesapi.ContainerMemory {\n\tvar containerMemories []*podresourcesapi.ContainerMemory\n\n\tfor _, b := range blocks {\n\t\tcontainerMemory := podresourcesapi.ContainerMemory{\n\t\t\tMemoryType: string(b.Type),\n\t\t\tSize_: b.Size,\n\t\t\tTopology: \u0026podresourcesapi.TopologyInfo{\n\t\t\t\tNodes: []*podresourcesapi.NUMANode{},\n\t\t\t},\n\t\t}\n\n\t\tfor _, numaNodeID := range b.NUMAAffinity {\n\t\t\tcontainerMemory.Topology.Nodes = append(containerMemory.Topology.Nodes, \u0026podresourcesapi.NUMANode{ID: int64(numaNodeID)})\n\t\t}\n\n\t\tcontainerMemories = append(containerMemories, \u0026containerMemory)\n\t}\n\n\treturn containerMemories\n}","line":{"from":1011,"to":1031}} {"id":100005600,"name":"PrepareDynamicResources","signature":"func (cm *containerManagerImpl) PrepareDynamicResources(pod *v1.Pod) error","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func (cm *containerManagerImpl) PrepareDynamicResources(pod *v1.Pod) error {\n\treturn cm.draManager.PrepareResources(pod)\n}","line":{"from":1033,"to":1035}} {"id":100005601,"name":"UnprepareDynamicResources","signature":"func (cm *containerManagerImpl) UnprepareDynamicResources(pod *v1.Pod) error","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func (cm *containerManagerImpl) UnprepareDynamicResources(pod *v1.Pod) error {\n\treturn cm.draManager.UnprepareResources(pod)\n}","line":{"from":1037,"to":1039}} {"id":100005602,"name":"PodMightNeedToUnprepareResources","signature":"func (cm *containerManagerImpl) PodMightNeedToUnprepareResources(UID types.UID) bool","file":"pkg/kubelet/cm/container_manager_linux.go","code":"func (cm *containerManagerImpl) PodMightNeedToUnprepareResources(UID types.UID) bool {\n\treturn cm.draManager.PodMightNeedToUnprepareResources(UID)\n}","line":{"from":1041,"to":1043}} {"id":100005603,"name":"Start","signature":"func (cm *containerManagerStub) Start(_ *v1.Node, _ ActivePodsFunc, _ config.SourcesReady, _ status.PodStatusProvider, _ internalapi.RuntimeService, _ bool) error","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) Start(_ *v1.Node, _ ActivePodsFunc, _ config.SourcesReady, _ status.PodStatusProvider, _ internalapi.RuntimeService, _ bool) error {\n\tklog.V(2).InfoS(\"Starting stub container manager\")\n\treturn nil\n}","line":{"from":47,"to":50}} {"id":100005604,"name":"SystemCgroupsLimit","signature":"func (cm *containerManagerStub) SystemCgroupsLimit() v1.ResourceList","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) SystemCgroupsLimit() v1.ResourceList {\n\treturn v1.ResourceList{}\n}","line":{"from":52,"to":54}} {"id":100005605,"name":"GetNodeConfig","signature":"func (cm *containerManagerStub) GetNodeConfig() NodeConfig","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) GetNodeConfig() NodeConfig {\n\treturn NodeConfig{}\n}","line":{"from":56,"to":58}} {"id":100005606,"name":"GetMountedSubsystems","signature":"func (cm *containerManagerStub) GetMountedSubsystems() *CgroupSubsystems","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) GetMountedSubsystems() *CgroupSubsystems {\n\treturn \u0026CgroupSubsystems{}\n}","line":{"from":60,"to":62}} {"id":100005607,"name":"GetQOSContainersInfo","signature":"func (cm *containerManagerStub) GetQOSContainersInfo() QOSContainersInfo","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) GetQOSContainersInfo() QOSContainersInfo {\n\treturn QOSContainersInfo{}\n}","line":{"from":64,"to":66}} {"id":100005608,"name":"UpdateQOSCgroups","signature":"func (cm *containerManagerStub) UpdateQOSCgroups() error","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) UpdateQOSCgroups() error {\n\treturn nil\n}","line":{"from":68,"to":70}} {"id":100005609,"name":"Status","signature":"func (cm *containerManagerStub) Status() Status","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) Status() Status {\n\treturn Status{}\n}","line":{"from":72,"to":74}} {"id":100005610,"name":"GetNodeAllocatableReservation","signature":"func (cm *containerManagerStub) GetNodeAllocatableReservation() v1.ResourceList","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) GetNodeAllocatableReservation() v1.ResourceList {\n\treturn nil\n}","line":{"from":76,"to":78}} {"id":100005611,"name":"GetCapacity","signature":"func (cm *containerManagerStub) GetCapacity(localStorageCapacityIsolation bool) v1.ResourceList","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) GetCapacity(localStorageCapacityIsolation bool) v1.ResourceList {\n\tif !localStorageCapacityIsolation {\n\t\treturn v1.ResourceList{}\n\t}\n\tc := v1.ResourceList{\n\t\tv1.ResourceEphemeralStorage: *resource.NewQuantity(\n\t\t\tint64(0),\n\t\t\tresource.BinarySI),\n\t}\n\treturn c\n}","line":{"from":80,"to":90}} {"id":100005612,"name":"GetPluginRegistrationHandler","signature":"func (cm *containerManagerStub) GetPluginRegistrationHandler() cache.PluginHandler","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) GetPluginRegistrationHandler() cache.PluginHandler {\n\treturn nil\n}","line":{"from":92,"to":94}} {"id":100005613,"name":"GetDevicePluginResourceCapacity","signature":"func (cm *containerManagerStub) GetDevicePluginResourceCapacity() (v1.ResourceList, v1.ResourceList, []string)","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) GetDevicePluginResourceCapacity() (v1.ResourceList, v1.ResourceList, []string) {\n\treturn cm.extendedPluginResources, cm.extendedPluginResources, []string{}\n}","line":{"from":96,"to":98}} {"id":100005614,"name":"GetPodCgroupConfig","signature":"func (m *podContainerManagerStub) GetPodCgroupConfig(_ *v1.Pod, _ v1.ResourceName) (*ResourceConfig, error)","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (m *podContainerManagerStub) GetPodCgroupConfig(_ *v1.Pod, _ v1.ResourceName) (*ResourceConfig, error) {\n\treturn nil, fmt.Errorf(\"not implemented\")\n}","line":{"from":100,"to":102}} {"id":100005615,"name":"SetPodCgroupConfig","signature":"func (m *podContainerManagerStub) SetPodCgroupConfig(_ *v1.Pod, _ v1.ResourceName, _ *ResourceConfig) error","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (m *podContainerManagerStub) SetPodCgroupConfig(_ *v1.Pod, _ v1.ResourceName, _ *ResourceConfig) error {\n\treturn fmt.Errorf(\"not implemented\")\n}","line":{"from":104,"to":106}} {"id":100005616,"name":"NewPodContainerManager","signature":"func (cm *containerManagerStub) NewPodContainerManager() PodContainerManager","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) NewPodContainerManager() PodContainerManager {\n\treturn \u0026podContainerManagerStub{}\n}","line":{"from":108,"to":110}} {"id":100005617,"name":"GetResources","signature":"func (cm *containerManagerStub) GetResources(pod *v1.Pod, container *v1.Container) (*kubecontainer.RunContainerOptions, error)","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) GetResources(pod *v1.Pod, container *v1.Container) (*kubecontainer.RunContainerOptions, error) {\n\treturn \u0026kubecontainer.RunContainerOptions{}, nil\n}","line":{"from":112,"to":114}} {"id":100005618,"name":"UpdatePluginResources","signature":"func (cm *containerManagerStub) UpdatePluginResources(*schedulerframework.NodeInfo, *lifecycle.PodAdmitAttributes) error","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) UpdatePluginResources(*schedulerframework.NodeInfo, *lifecycle.PodAdmitAttributes) error {\n\treturn nil\n}","line":{"from":116,"to":118}} {"id":100005619,"name":"InternalContainerLifecycle","signature":"func (cm *containerManagerStub) InternalContainerLifecycle() InternalContainerLifecycle","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) InternalContainerLifecycle() InternalContainerLifecycle {\n\treturn \u0026internalContainerLifecycleImpl{cpumanager.NewFakeManager(), memorymanager.NewFakeManager(), topologymanager.NewFakeManager()}\n}","line":{"from":120,"to":122}} {"id":100005620,"name":"GetPodCgroupRoot","signature":"func (cm *containerManagerStub) GetPodCgroupRoot() string","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) GetPodCgroupRoot() string {\n\treturn \"\"\n}","line":{"from":124,"to":126}} {"id":100005621,"name":"GetDevices","signature":"func (cm *containerManagerStub) GetDevices(_, _ string) []*podresourcesapi.ContainerDevices","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) GetDevices(_, _ string) []*podresourcesapi.ContainerDevices {\n\treturn nil\n}","line":{"from":128,"to":130}} {"id":100005622,"name":"GetAllocatableDevices","signature":"func (cm *containerManagerStub) GetAllocatableDevices() []*podresourcesapi.ContainerDevices","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) GetAllocatableDevices() []*podresourcesapi.ContainerDevices {\n\treturn nil\n}","line":{"from":132,"to":134}} {"id":100005623,"name":"ShouldResetExtendedResourceCapacity","signature":"func (cm *containerManagerStub) ShouldResetExtendedResourceCapacity() bool","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) ShouldResetExtendedResourceCapacity() bool {\n\treturn cm.shouldResetExtendedResourceCapacity\n}","line":{"from":136,"to":138}} {"id":100005624,"name":"GetAllocateResourcesPodAdmitHandler","signature":"func (cm *containerManagerStub) GetAllocateResourcesPodAdmitHandler() lifecycle.PodAdmitHandler","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) GetAllocateResourcesPodAdmitHandler() lifecycle.PodAdmitHandler {\n\treturn topologymanager.NewFakeManager()\n}","line":{"from":140,"to":142}} {"id":100005625,"name":"UpdateAllocatedDevices","signature":"func (cm *containerManagerStub) UpdateAllocatedDevices()","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) UpdateAllocatedDevices() {\n\treturn\n}","line":{"from":144,"to":146}} {"id":100005626,"name":"GetCPUs","signature":"func (cm *containerManagerStub) GetCPUs(_, _ string) []int64","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) GetCPUs(_, _ string) []int64 {\n\treturn nil\n}","line":{"from":148,"to":150}} {"id":100005627,"name":"GetAllocatableCPUs","signature":"func (cm *containerManagerStub) GetAllocatableCPUs() []int64","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) GetAllocatableCPUs() []int64 {\n\treturn nil\n}","line":{"from":152,"to":154}} {"id":100005628,"name":"GetMemory","signature":"func (cm *containerManagerStub) GetMemory(_, _ string) []*podresourcesapi.ContainerMemory","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) GetMemory(_, _ string) []*podresourcesapi.ContainerMemory {\n\treturn nil\n}","line":{"from":156,"to":158}} {"id":100005629,"name":"GetAllocatableMemory","signature":"func (cm *containerManagerStub) GetAllocatableMemory() []*podresourcesapi.ContainerMemory","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) GetAllocatableMemory() []*podresourcesapi.ContainerMemory {\n\treturn nil\n}","line":{"from":160,"to":162}} {"id":100005630,"name":"GetDynamicResources","signature":"func (cm *containerManagerStub) GetDynamicResources(pod *v1.Pod, container *v1.Container) []*podresourcesapi.DynamicResource","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) GetDynamicResources(pod *v1.Pod, container *v1.Container) []*podresourcesapi.DynamicResource {\n\treturn nil\n}","line":{"from":164,"to":166}} {"id":100005631,"name":"GetNodeAllocatableAbsolute","signature":"func (cm *containerManagerStub) GetNodeAllocatableAbsolute() v1.ResourceList","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) GetNodeAllocatableAbsolute() v1.ResourceList {\n\treturn nil\n}","line":{"from":168,"to":170}} {"id":100005632,"name":"PrepareDynamicResources","signature":"func (cm *containerManagerStub) PrepareDynamicResources(pod *v1.Pod) error","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) PrepareDynamicResources(pod *v1.Pod) error {\n\treturn nil\n}","line":{"from":172,"to":174}} {"id":100005633,"name":"UnprepareDynamicResources","signature":"func (cm *containerManagerStub) UnprepareDynamicResources(*v1.Pod) error","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) UnprepareDynamicResources(*v1.Pod) error {\n\treturn nil\n}","line":{"from":176,"to":178}} {"id":100005634,"name":"PodMightNeedToUnprepareResources","signature":"func (cm *containerManagerStub) PodMightNeedToUnprepareResources(UID types.UID) bool","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func (cm *containerManagerStub) PodMightNeedToUnprepareResources(UID types.UID) bool {\n\treturn false\n}","line":{"from":180,"to":182}} {"id":100005635,"name":"NewStubContainerManager","signature":"func NewStubContainerManager() ContainerManager","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func NewStubContainerManager() ContainerManager {\n\treturn \u0026containerManagerStub{shouldResetExtendedResourceCapacity: false}\n}","line":{"from":184,"to":186}} {"id":100005636,"name":"NewStubContainerManagerWithExtendedResource","signature":"func NewStubContainerManagerWithExtendedResource(shouldResetExtendedResourceCapacity bool) ContainerManager","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func NewStubContainerManagerWithExtendedResource(shouldResetExtendedResourceCapacity bool) ContainerManager {\n\treturn \u0026containerManagerStub{shouldResetExtendedResourceCapacity: shouldResetExtendedResourceCapacity}\n}","line":{"from":188,"to":190}} {"id":100005637,"name":"NewStubContainerManagerWithDevicePluginResource","signature":"func NewStubContainerManagerWithDevicePluginResource(extendedPluginResources v1.ResourceList) ContainerManager","file":"pkg/kubelet/cm/container_manager_stub.go","code":"func NewStubContainerManagerWithDevicePluginResource(extendedPluginResources v1.ResourceList) ContainerManager {\n\treturn \u0026containerManagerStub{\n\t\tshouldResetExtendedResourceCapacity: false,\n\t\textendedPluginResources: extendedPluginResources,\n\t}\n}","line":{"from":192,"to":197}} {"id":100005638,"name":"Start","signature":"func (unsupportedContainerManager) Start(_ *v1.Node, _ ActivePodsFunc, _ config.SourcesReady, _ status.PodStatusProvider, _ internalapi.RuntimeService, _ bool) error","file":"pkg/kubelet/cm/container_manager_unsupported.go","code":"func (unsupportedContainerManager) Start(_ *v1.Node, _ ActivePodsFunc, _ config.SourcesReady, _ status.PodStatusProvider, _ internalapi.RuntimeService, _ bool) error {\n\treturn fmt.Errorf(\"Container Manager is unsupported in this build\")\n}","line":{"from":42,"to":44}} {"id":100005639,"name":"NewContainerManager","signature":"func NewContainerManager(_ mount.Interface, _ cadvisor.Interface, _ NodeConfig, failSwapOn bool, recorder record.EventRecorder, kubeClient clientset.Interface) (ContainerManager, error)","file":"pkg/kubelet/cm/container_manager_unsupported.go","code":"func NewContainerManager(_ mount.Interface, _ cadvisor.Interface, _ NodeConfig, failSwapOn bool, recorder record.EventRecorder, kubeClient clientset.Interface) (ContainerManager, error) {\n\treturn \u0026unsupportedContainerManager{}, nil\n}","line":{"from":46,"to":48}} {"id":100005640,"name":"Admit","signature":"func (ra *noopWindowsResourceAllocator) Admit(attrs *lifecycle.PodAdmitAttributes) lifecycle.PodAdmitResult","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (ra *noopWindowsResourceAllocator) Admit(attrs *lifecycle.PodAdmitAttributes) lifecycle.PodAdmitResult {\n\treturn admission.GetPodAdmitResult(nil)\n}","line":{"from":67,"to":69}} {"id":100005641,"name":"Start","signature":"func (cm *containerManagerImpl) Start(node *v1.Node,","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) Start(node *v1.Node,\n\tactivePods ActivePodsFunc,\n\tsourcesReady config.SourcesReady,\n\tpodStatusProvider status.PodStatusProvider,\n\truntimeService internalapi.RuntimeService,\n\tlocalStorageCapacityIsolation bool) error {\n\tklog.V(2).InfoS(\"Starting Windows container manager\")\n\n\tif localStorageCapacityIsolation {\n\t\trootfs, err := cm.cadvisorInterface.RootFsInfo()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get rootfs info: %v\", err)\n\t\t}\n\t\tfor rName, rCap := range cadvisor.EphemeralStorageCapacityFromFsInfo(rootfs) {\n\t\t\tcm.capacity[rName] = rCap\n\t\t}\n\t}\n\n\t// Starts device manager.\n\tif err := cm.deviceManager.Start(devicemanager.ActivePodsFunc(activePods), sourcesReady); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":71,"to":95}} {"id":100005642,"name":"NewContainerManager","signature":"func NewContainerManager(mountUtil mount.Interface, cadvisorInterface cadvisor.Interface, nodeConfig NodeConfig, failSwapOn bool, recorder record.EventRecorder, kubeClient clientset.Interface) (ContainerManager, error)","file":"pkg/kubelet/cm/container_manager_windows.go","code":"// NewContainerManager creates windows container manager.\nfunc NewContainerManager(mountUtil mount.Interface, cadvisorInterface cadvisor.Interface, nodeConfig NodeConfig, failSwapOn bool, recorder record.EventRecorder, kubeClient clientset.Interface) (ContainerManager, error) {\n\t// It is safe to invoke `MachineInfo` on cAdvisor before logically initializing cAdvisor here because\n\t// machine info is computed and cached once as part of cAdvisor object creation.\n\t// But `RootFsInfo` and `ImagesFsInfo` are not available at this moment so they will be called later during manager starts\n\tmachineInfo, err := cadvisorInterface.MachineInfo()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcapacity := cadvisor.CapacityFromMachineInfo(machineInfo)\n\n\tcm := \u0026containerManagerImpl{\n\t\tcapacity: capacity,\n\t\tnodeConfig: nodeConfig,\n\t\tcadvisorInterface: cadvisorInterface,\n\t}\n\n\tcm.topologyManager = topologymanager.NewFakeManager()\n\n\tklog.InfoS(\"Creating device plugin manager\")\n\tcm.deviceManager, err = devicemanager.NewManagerImpl(nil, cm.topologyManager)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcm.topologyManager.AddHintProvider(cm.deviceManager)\n\n\treturn cm, nil\n}","line":{"from":97,"to":124}} {"id":100005643,"name":"SystemCgroupsLimit","signature":"func (cm *containerManagerImpl) SystemCgroupsLimit() v1.ResourceList","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) SystemCgroupsLimit() v1.ResourceList {\n\treturn v1.ResourceList{}\n}","line":{"from":126,"to":128}} {"id":100005644,"name":"GetNodeConfig","signature":"func (cm *containerManagerImpl) GetNodeConfig() NodeConfig","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) GetNodeConfig() NodeConfig {\n\treturn NodeConfig{}\n}","line":{"from":130,"to":132}} {"id":100005645,"name":"GetMountedSubsystems","signature":"func (cm *containerManagerImpl) GetMountedSubsystems() *CgroupSubsystems","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) GetMountedSubsystems() *CgroupSubsystems {\n\treturn \u0026CgroupSubsystems{}\n}","line":{"from":134,"to":136}} {"id":100005646,"name":"GetQOSContainersInfo","signature":"func (cm *containerManagerImpl) GetQOSContainersInfo() QOSContainersInfo","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) GetQOSContainersInfo() QOSContainersInfo {\n\treturn QOSContainersInfo{}\n}","line":{"from":138,"to":140}} {"id":100005647,"name":"UpdateQOSCgroups","signature":"func (cm *containerManagerImpl) UpdateQOSCgroups() error","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) UpdateQOSCgroups() error {\n\treturn nil\n}","line":{"from":142,"to":144}} {"id":100005648,"name":"Status","signature":"func (cm *containerManagerImpl) Status() Status","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) Status() Status {\n\treturn Status{}\n}","line":{"from":146,"to":148}} {"id":100005649,"name":"GetNodeAllocatableReservation","signature":"func (cm *containerManagerImpl) GetNodeAllocatableReservation() v1.ResourceList","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) GetNodeAllocatableReservation() v1.ResourceList {\n\tevictionReservation := hardEvictionReservation(cm.nodeConfig.HardEvictionThresholds, cm.capacity)\n\tresult := make(v1.ResourceList)\n\tfor k := range cm.capacity {\n\t\tvalue := resource.NewQuantity(0, resource.DecimalSI)\n\t\tif cm.nodeConfig.SystemReserved != nil {\n\t\t\tvalue.Add(cm.nodeConfig.SystemReserved[k])\n\t\t}\n\t\tif cm.nodeConfig.KubeReserved != nil {\n\t\t\tvalue.Add(cm.nodeConfig.KubeReserved[k])\n\t\t}\n\t\tif evictionReservation != nil {\n\t\t\tvalue.Add(evictionReservation[k])\n\t\t}\n\t\tif !value.IsZero() {\n\t\t\tresult[k] = *value\n\t\t}\n\t}\n\treturn result\n}","line":{"from":150,"to":169}} {"id":100005650,"name":"GetCapacity","signature":"func (cm *containerManagerImpl) GetCapacity(localStorageCapacityIsolation bool) v1.ResourceList","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) GetCapacity(localStorageCapacityIsolation bool) v1.ResourceList {\n\treturn cm.capacity\n}","line":{"from":171,"to":173}} {"id":100005651,"name":"GetPluginRegistrationHandler","signature":"func (cm *containerManagerImpl) GetPluginRegistrationHandler() cache.PluginHandler","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) GetPluginRegistrationHandler() cache.PluginHandler {\n\treturn cm.deviceManager.GetWatcherHandler()\n}","line":{"from":175,"to":177}} {"id":100005652,"name":"GetDevicePluginResourceCapacity","signature":"func (cm *containerManagerImpl) GetDevicePluginResourceCapacity() (v1.ResourceList, v1.ResourceList, []string)","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) GetDevicePluginResourceCapacity() (v1.ResourceList, v1.ResourceList, []string) {\n\treturn cm.deviceManager.GetCapacity()\n}","line":{"from":179,"to":181}} {"id":100005653,"name":"NewPodContainerManager","signature":"func (cm *containerManagerImpl) NewPodContainerManager() PodContainerManager","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) NewPodContainerManager() PodContainerManager {\n\treturn \u0026podContainerManagerStub{}\n}","line":{"from":183,"to":185}} {"id":100005654,"name":"GetResources","signature":"func (cm *containerManagerImpl) GetResources(pod *v1.Pod, container *v1.Container) (*kubecontainer.RunContainerOptions, error)","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) GetResources(pod *v1.Pod, container *v1.Container) (*kubecontainer.RunContainerOptions, error) {\n\topts := \u0026kubecontainer.RunContainerOptions{}\n\t// Allocate should already be called during predicateAdmitHandler.Admit(),\n\t// just try to fetch device runtime information from cached state here\n\tdevOpts, err := cm.deviceManager.GetDeviceRunContainerOptions(pod, container)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if devOpts == nil {\n\t\treturn opts, nil\n\t}\n\topts.Devices = append(opts.Devices, devOpts.Devices...)\n\topts.Mounts = append(opts.Mounts, devOpts.Mounts...)\n\topts.Envs = append(opts.Envs, devOpts.Envs...)\n\topts.Annotations = append(opts.Annotations, devOpts.Annotations...)\n\treturn opts, nil\n}","line":{"from":187,"to":202}} {"id":100005655,"name":"UpdatePluginResources","signature":"func (cm *containerManagerImpl) UpdatePluginResources(node *schedulerframework.NodeInfo, attrs *lifecycle.PodAdmitAttributes) error","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) UpdatePluginResources(node *schedulerframework.NodeInfo, attrs *lifecycle.PodAdmitAttributes) error {\n\treturn cm.deviceManager.UpdatePluginResources(node, attrs)\n}","line":{"from":204,"to":206}} {"id":100005656,"name":"InternalContainerLifecycle","signature":"func (cm *containerManagerImpl) InternalContainerLifecycle() InternalContainerLifecycle","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) InternalContainerLifecycle() InternalContainerLifecycle {\n\treturn \u0026internalContainerLifecycleImpl{cpumanager.NewFakeManager(), memorymanager.NewFakeManager(), topologymanager.NewFakeManager()}\n}","line":{"from":208,"to":210}} {"id":100005657,"name":"GetPodCgroupRoot","signature":"func (cm *containerManagerImpl) GetPodCgroupRoot() string","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) GetPodCgroupRoot() string {\n\treturn \"\"\n}","line":{"from":212,"to":214}} {"id":100005658,"name":"GetDevices","signature":"func (cm *containerManagerImpl) GetDevices(podUID, containerName string) []*podresourcesapi.ContainerDevices","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) GetDevices(podUID, containerName string) []*podresourcesapi.ContainerDevices {\n\treturn containerDevicesFromResourceDeviceInstances(cm.deviceManager.GetDevices(podUID, containerName))\n}","line":{"from":216,"to":218}} {"id":100005659,"name":"GetAllocatableDevices","signature":"func (cm *containerManagerImpl) GetAllocatableDevices() []*podresourcesapi.ContainerDevices","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) GetAllocatableDevices() []*podresourcesapi.ContainerDevices {\n\treturn nil\n}","line":{"from":220,"to":222}} {"id":100005660,"name":"ShouldResetExtendedResourceCapacity","signature":"func (cm *containerManagerImpl) ShouldResetExtendedResourceCapacity() bool","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) ShouldResetExtendedResourceCapacity() bool {\n\treturn cm.deviceManager.ShouldResetExtendedResourceCapacity()\n}","line":{"from":224,"to":226}} {"id":100005661,"name":"GetAllocateResourcesPodAdmitHandler","signature":"func (cm *containerManagerImpl) GetAllocateResourcesPodAdmitHandler() lifecycle.PodAdmitHandler","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) GetAllocateResourcesPodAdmitHandler() lifecycle.PodAdmitHandler {\n\treturn \u0026noopWindowsResourceAllocator{}\n}","line":{"from":228,"to":230}} {"id":100005662,"name":"UpdateAllocatedDevices","signature":"func (cm *containerManagerImpl) UpdateAllocatedDevices()","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) UpdateAllocatedDevices() {\n\treturn\n}","line":{"from":232,"to":234}} {"id":100005663,"name":"GetCPUs","signature":"func (cm *containerManagerImpl) GetCPUs(_, _ string) []int64","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) GetCPUs(_, _ string) []int64 {\n\treturn nil\n}","line":{"from":236,"to":238}} {"id":100005664,"name":"GetAllocatableCPUs","signature":"func (cm *containerManagerImpl) GetAllocatableCPUs() []int64","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) GetAllocatableCPUs() []int64 {\n\treturn nil\n}","line":{"from":240,"to":242}} {"id":100005665,"name":"GetMemory","signature":"func (cm *containerManagerImpl) GetMemory(_, _ string) []*podresourcesapi.ContainerMemory","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) GetMemory(_, _ string) []*podresourcesapi.ContainerMemory {\n\treturn nil\n}","line":{"from":244,"to":246}} {"id":100005666,"name":"GetAllocatableMemory","signature":"func (cm *containerManagerImpl) GetAllocatableMemory() []*podresourcesapi.ContainerMemory","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) GetAllocatableMemory() []*podresourcesapi.ContainerMemory {\n\treturn nil\n}","line":{"from":248,"to":250}} {"id":100005667,"name":"GetNodeAllocatableAbsolute","signature":"func (cm *containerManagerImpl) GetNodeAllocatableAbsolute() v1.ResourceList","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) GetNodeAllocatableAbsolute() v1.ResourceList {\n\treturn nil\n}","line":{"from":252,"to":254}} {"id":100005668,"name":"GetDynamicResources","signature":"func (cm *containerManagerImpl) GetDynamicResources(pod *v1.Pod, container *v1.Container) []*podresourcesapi.DynamicResource","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) GetDynamicResources(pod *v1.Pod, container *v1.Container) []*podresourcesapi.DynamicResource {\n\treturn nil\n}","line":{"from":256,"to":258}} {"id":100005669,"name":"PrepareDynamicResources","signature":"func (cm *containerManagerImpl) PrepareDynamicResources(pod *v1.Pod) error","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) PrepareDynamicResources(pod *v1.Pod) error {\n\treturn nil\n}","line":{"from":260,"to":262}} {"id":100005670,"name":"UnprepareDynamicResources","signature":"func (cm *containerManagerImpl) UnprepareDynamicResources(*v1.Pod) error","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) UnprepareDynamicResources(*v1.Pod) error {\n\treturn nil\n}","line":{"from":264,"to":266}} {"id":100005671,"name":"PodMightNeedToUnprepareResources","signature":"func (cm *containerManagerImpl) PodMightNeedToUnprepareResources(UID types.UID) bool","file":"pkg/kubelet/cm/container_manager_windows.go","code":"func (cm *containerManagerImpl) PodMightNeedToUnprepareResources(UID types.UID) bool {\n\treturn false\n}","line":{"from":268,"to":270}} {"id":100005672,"name":"NewContainerMap","signature":"func NewContainerMap() ContainerMap","file":"pkg/kubelet/cm/containermap/container_map.go","code":"// NewContainerMap creates a new ContainerMap struct\nfunc NewContainerMap() ContainerMap {\n\treturn make(ContainerMap)\n}","line":{"from":29,"to":32}} {"id":100005673,"name":"Add","signature":"func (cm ContainerMap) Add(podUID, containerName, containerID string)","file":"pkg/kubelet/cm/containermap/container_map.go","code":"// Add adds a mapping of (containerID)-\u003e(podUID, containerName) to the ContainerMap\nfunc (cm ContainerMap) Add(podUID, containerName, containerID string) {\n\tcm[containerID] = struct {\n\t\tpodUID string\n\t\tcontainerName string\n\t}{podUID, containerName}\n}","line":{"from":34,"to":40}} {"id":100005674,"name":"RemoveByContainerID","signature":"func (cm ContainerMap) RemoveByContainerID(containerID string)","file":"pkg/kubelet/cm/containermap/container_map.go","code":"// RemoveByContainerID removes a mapping of (containerID)-\u003e(podUID, containerName) from the ContainerMap\nfunc (cm ContainerMap) RemoveByContainerID(containerID string) {\n\tdelete(cm, containerID)\n}","line":{"from":42,"to":45}} {"id":100005675,"name":"RemoveByContainerRef","signature":"func (cm ContainerMap) RemoveByContainerRef(podUID, containerName string)","file":"pkg/kubelet/cm/containermap/container_map.go","code":"// RemoveByContainerRef removes a mapping of (containerID)-\u003e(podUID, containerName) from the ContainerMap\nfunc (cm ContainerMap) RemoveByContainerRef(podUID, containerName string) {\n\tcontainerID, err := cm.GetContainerID(podUID, containerName)\n\tif err == nil {\n\t\tcm.RemoveByContainerID(containerID)\n\t}\n}","line":{"from":47,"to":53}} {"id":100005676,"name":"GetContainerID","signature":"func (cm ContainerMap) GetContainerID(podUID, containerName string) (string, error)","file":"pkg/kubelet/cm/containermap/container_map.go","code":"// GetContainerID retrieves a ContainerID from the ContainerMap\nfunc (cm ContainerMap) GetContainerID(podUID, containerName string) (string, error) {\n\tfor key, val := range cm {\n\t\tif val.podUID == podUID \u0026\u0026 val.containerName == containerName {\n\t\t\treturn key, nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"container %s not in ContainerMap for pod %s\", containerName, podUID)\n}","line":{"from":55,"to":63}} {"id":100005677,"name":"GetContainerRef","signature":"func (cm ContainerMap) GetContainerRef(containerID string) (string, string, error)","file":"pkg/kubelet/cm/containermap/container_map.go","code":"// GetContainerRef retrieves a (podUID, containerName) pair from the ContainerMap\nfunc (cm ContainerMap) GetContainerRef(containerID string) (string, string, error) {\n\tif _, exists := cm[containerID]; !exists {\n\t\treturn \"\", \"\", fmt.Errorf(\"containerID %s not in ContainerMap\", containerID)\n\t}\n\treturn cm[containerID].podUID, cm[containerID].containerName, nil\n}","line":{"from":65,"to":71}} {"id":100005678,"name":"Visit","signature":"func (cm ContainerMap) Visit(visitor func(podUID, containerName, containerID string))","file":"pkg/kubelet/cm/containermap/container_map.go","code":"// Visit invoke visitor function to walks all of the entries in the container map\nfunc (cm ContainerMap) Visit(visitor func(podUID, containerName, containerID string)) {\n\tfor k, v := range cm {\n\t\tvisitor(v.podUID, v.containerName, k)\n\t}\n}","line":{"from":73,"to":78}} {"id":100005679,"name":"Clone","signature":"func (m mapIntInt) Clone() mapIntInt","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"func (m mapIntInt) Clone() mapIntInt {\n\tcp := make(mapIntInt, len(m))\n\tfor k, v := range m {\n\t\tcp[k] = v\n\t}\n\treturn cp\n}","line":{"from":41,"to":47}} {"id":100005680,"name":"Keys","signature":"func (m mapIntInt) Keys() []int","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"func (m mapIntInt) Keys() []int {\n\tvar keys []int\n\tfor k := range m {\n\t\tkeys = append(keys, k)\n\t}\n\treturn keys\n}","line":{"from":49,"to":55}} {"id":100005681,"name":"Values","signature":"func (m mapIntInt) Values(keys ...int) []int","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"func (m mapIntInt) Values(keys ...int) []int {\n\tif keys == nil {\n\t\tkeys = m.Keys()\n\t}\n\tvar values []int\n\tfor _, k := range keys {\n\t\tvalues = append(values, m[k])\n\t}\n\treturn values\n}","line":{"from":57,"to":66}} {"id":100005682,"name":"sum","signature":"func sum(xs []int) int","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"func sum(xs []int) int {\n\tvar s int\n\tfor _, x := range xs {\n\t\ts += x\n\t}\n\treturn s\n}","line":{"from":68,"to":74}} {"id":100005683,"name":"mean","signature":"func mean(xs []int) float64","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"func mean(xs []int) float64 {\n\tvar sum float64\n\tfor _, x := range xs {\n\t\tsum += float64(x)\n\t}\n\tm := sum / float64(len(xs))\n\treturn math.Round(m*1000) / 1000\n}","line":{"from":76,"to":83}} {"id":100005684,"name":"standardDeviation","signature":"func standardDeviation(xs []int) float64","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"func standardDeviation(xs []int) float64 {\n\tm := mean(xs)\n\tvar sum float64\n\tfor _, x := range xs {\n\t\tsum += (float64(x) - m) * (float64(x) - m)\n\t}\n\ts := math.Sqrt(sum / float64(len(xs)))\n\treturn math.Round(s*1000) / 1000\n}","line":{"from":85,"to":93}} {"id":100005685,"name":"min","signature":"func min(x, y int) int","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"func min(x, y int) int {\n\tif x \u003c y {\n\t\treturn x\n\t}\n\treturn y\n}","line":{"from":95,"to":100}} {"id":100005686,"name":"takeFullFirstLevel","signature":"func (n *numaFirst) takeFullFirstLevel()","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"// If NUMA nodes are higher in the memory hierarchy than sockets, then we take\n// from the set of NUMA Nodes as the first level.\nfunc (n *numaFirst) takeFullFirstLevel() {\n\tn.acc.takeFullNUMANodes()\n}","line":{"from":116,"to":120}} {"id":100005687,"name":"takeFullSecondLevel","signature":"func (n *numaFirst) takeFullSecondLevel()","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"// If NUMA nodes are higher in the memory hierarchy than sockets, then we take\n// from the set of sockets as the second level.\nfunc (n *numaFirst) takeFullSecondLevel() {\n\tn.acc.takeFullSockets()\n}","line":{"from":122,"to":126}} {"id":100005688,"name":"sortAvailableNUMANodes","signature":"func (n *numaFirst) sortAvailableNUMANodes() []int","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"// If NUMA nodes are higher in the memory hierarchy than sockets, then just\n// sort the NUMA nodes directly, and return them.\nfunc (n *numaFirst) sortAvailableNUMANodes() []int {\n\tnumas := n.acc.details.NUMANodes().UnsortedList()\n\tn.acc.sort(numas, n.acc.details.CPUsInNUMANodes)\n\treturn numas\n}","line":{"from":128,"to":134}} {"id":100005689,"name":"sortAvailableSockets","signature":"func (n *numaFirst) sortAvailableSockets() []int","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"// If NUMA nodes are higher in the memory hierarchy than sockets, then we need\n// to pull the set of sockets out of each sorted NUMA node, and accumulate the\n// partial order across them.\nfunc (n *numaFirst) sortAvailableSockets() []int {\n\tvar result []int\n\tfor _, numa := range n.sortAvailableNUMANodes() {\n\t\tsockets := n.acc.details.SocketsInNUMANodes(numa).UnsortedList()\n\t\tn.acc.sort(sockets, n.acc.details.CPUsInSockets)\n\t\tresult = append(result, sockets...)\n\t}\n\treturn result\n}","line":{"from":136,"to":147}} {"id":100005690,"name":"sortAvailableCores","signature":"func (n *numaFirst) sortAvailableCores() []int","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"// If NUMA nodes are higher in the memory hierarchy than sockets, then\n// cores sit directly below sockets in the memory hierarchy.\nfunc (n *numaFirst) sortAvailableCores() []int {\n\tvar result []int\n\tfor _, socket := range n.acc.sortAvailableSockets() {\n\t\tcores := n.acc.details.CoresInSockets(socket).UnsortedList()\n\t\tn.acc.sort(cores, n.acc.details.CPUsInCores)\n\t\tresult = append(result, cores...)\n\t}\n\treturn result\n}","line":{"from":149,"to":159}} {"id":100005691,"name":"takeFullFirstLevel","signature":"func (s *socketsFirst) takeFullFirstLevel()","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"// If sockets are higher in the memory hierarchy than NUMA nodes, then we take\n// from the set of sockets as the first level.\nfunc (s *socketsFirst) takeFullFirstLevel() {\n\ts.acc.takeFullSockets()\n}","line":{"from":161,"to":165}} {"id":100005692,"name":"takeFullSecondLevel","signature":"func (s *socketsFirst) takeFullSecondLevel()","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"// If sockets are higher in the memory hierarchy than NUMA nodes, then we take\n// from the set of NUMA Nodes as the second level.\nfunc (s *socketsFirst) takeFullSecondLevel() {\n\ts.acc.takeFullNUMANodes()\n}","line":{"from":167,"to":171}} {"id":100005693,"name":"sortAvailableNUMANodes","signature":"func (s *socketsFirst) sortAvailableNUMANodes() []int","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"// If sockets are higher in the memory hierarchy than NUMA nodes, then we need\n// to pull the set of NUMA nodes out of each sorted Socket, and accumulate the\n// partial order across them.\nfunc (s *socketsFirst) sortAvailableNUMANodes() []int {\n\tvar result []int\n\tfor _, socket := range s.sortAvailableSockets() {\n\t\tnumas := s.acc.details.NUMANodesInSockets(socket).UnsortedList()\n\t\ts.acc.sort(numas, s.acc.details.CPUsInNUMANodes)\n\t\tresult = append(result, numas...)\n\t}\n\treturn result\n}","line":{"from":173,"to":184}} {"id":100005694,"name":"sortAvailableSockets","signature":"func (s *socketsFirst) sortAvailableSockets() []int","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"// If sockets are higher in the memory hierarchy than NUMA nodes, then just\n// sort the sockets directly, and return them.\nfunc (s *socketsFirst) sortAvailableSockets() []int {\n\tsockets := s.acc.details.Sockets().UnsortedList()\n\ts.acc.sort(sockets, s.acc.details.CPUsInSockets)\n\treturn sockets\n}","line":{"from":186,"to":192}} {"id":100005695,"name":"sortAvailableCores","signature":"func (s *socketsFirst) sortAvailableCores() []int","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"// If sockets are higher in the memory hierarchy than NUMA nodes, then cores\n// sit directly below NUMA Nodes in the memory hierarchy.\nfunc (s *socketsFirst) sortAvailableCores() []int {\n\tvar result []int\n\tfor _, numa := range s.acc.sortAvailableNUMANodes() {\n\t\tcores := s.acc.details.CoresInNUMANodes(numa).UnsortedList()\n\t\ts.acc.sort(cores, s.acc.details.CPUsInCores)\n\t\tresult = append(result, cores...)\n\t}\n\treturn result\n}","line":{"from":194,"to":204}} {"id":100005696,"name":"newCPUAccumulator","signature":"func newCPUAccumulator(topo *topology.CPUTopology, availableCPUs cpuset.CPUSet, numCPUs int) *cpuAccumulator","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"func newCPUAccumulator(topo *topology.CPUTopology, availableCPUs cpuset.CPUSet, numCPUs int) *cpuAccumulator {\n\tacc := \u0026cpuAccumulator{\n\t\ttopo: topo,\n\t\tdetails: topo.CPUDetails.KeepOnly(availableCPUs),\n\t\tnumCPUsNeeded: numCPUs,\n\t\tresult: cpuset.New(),\n\t}\n\n\tif topo.NumSockets \u003e= topo.NumNUMANodes {\n\t\tacc.numaOrSocketsFirst = \u0026numaFirst{acc}\n\t} else {\n\t\tacc.numaOrSocketsFirst = \u0026socketsFirst{acc}\n\t}\n\n\treturn acc\n}","line":{"from":214,"to":229}} {"id":100005697,"name":"isNUMANodeFree","signature":"func (a *cpuAccumulator) isNUMANodeFree(numaID int) bool","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"// Returns true if the supplied NUMANode is fully available in `topoDetails`.\nfunc (a *cpuAccumulator) isNUMANodeFree(numaID int) bool {\n\treturn a.details.CPUsInNUMANodes(numaID).Size() == a.topo.CPUDetails.CPUsInNUMANodes(numaID).Size()\n}","line":{"from":231,"to":234}} {"id":100005698,"name":"isSocketFree","signature":"func (a *cpuAccumulator) isSocketFree(socketID int) bool","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"// Returns true if the supplied socket is fully available in `topoDetails`.\nfunc (a *cpuAccumulator) isSocketFree(socketID int) bool {\n\treturn a.details.CPUsInSockets(socketID).Size() == a.topo.CPUsPerSocket()\n}","line":{"from":236,"to":239}} {"id":100005699,"name":"isCoreFree","signature":"func (a *cpuAccumulator) isCoreFree(coreID int) bool","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"// Returns true if the supplied core is fully available in `topoDetails`.\nfunc (a *cpuAccumulator) isCoreFree(coreID int) bool {\n\treturn a.details.CPUsInCores(coreID).Size() == a.topo.CPUsPerCore()\n}","line":{"from":241,"to":244}} {"id":100005700,"name":"freeNUMANodes","signature":"func (a *cpuAccumulator) freeNUMANodes() []int","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"// Returns free NUMA Node IDs as a slice sorted by sortAvailableNUMANodes().\nfunc (a *cpuAccumulator) freeNUMANodes() []int {\n\tfree := []int{}\n\tfor _, numa := range a.sortAvailableNUMANodes() {\n\t\tif a.isNUMANodeFree(numa) {\n\t\t\tfree = append(free, numa)\n\t\t}\n\t}\n\treturn free\n}","line":{"from":246,"to":255}} {"id":100005701,"name":"freeSockets","signature":"func (a *cpuAccumulator) freeSockets() []int","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"// Returns free socket IDs as a slice sorted by sortAvailableSockets().\nfunc (a *cpuAccumulator) freeSockets() []int {\n\tfree := []int{}\n\tfor _, socket := range a.sortAvailableSockets() {\n\t\tif a.isSocketFree(socket) {\n\t\t\tfree = append(free, socket)\n\t\t}\n\t}\n\treturn free\n}","line":{"from":257,"to":266}} {"id":100005702,"name":"freeCores","signature":"func (a *cpuAccumulator) freeCores() []int","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"// Returns free core IDs as a slice sorted by sortAvailableCores().\nfunc (a *cpuAccumulator) freeCores() []int {\n\tfree := []int{}\n\tfor _, core := range a.sortAvailableCores() {\n\t\tif a.isCoreFree(core) {\n\t\t\tfree = append(free, core)\n\t\t}\n\t}\n\treturn free\n}","line":{"from":268,"to":277}} {"id":100005703,"name":"freeCPUs","signature":"func (a *cpuAccumulator) freeCPUs() []int","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"// Returns free CPU IDs as a slice sorted by sortAvailableCPUs().\nfunc (a *cpuAccumulator) freeCPUs() []int {\n\treturn a.sortAvailableCPUs()\n}","line":{"from":279,"to":282}} {"id":100005704,"name":"sort","signature":"func (a *cpuAccumulator) sort(ids []int, getCPUs func(ids ...int) cpuset.CPUSet)","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"// Sorts the provided list of NUMA nodes/sockets/cores/cpus referenced in 'ids'\n// by the number of available CPUs contained within them (smallest to largest).\n// The 'getCPU()' paramater defines the function that should be called to\n// retrieve the list of available CPUs for the type being referenced. If two\n// NUMA nodes/sockets/cores/cpus have the same number of available CPUs, they\n// are sorted in ascending order by their id.\nfunc (a *cpuAccumulator) sort(ids []int, getCPUs func(ids ...int) cpuset.CPUSet) {\n\tsort.Slice(ids,\n\t\tfunc(i, j int) bool {\n\t\t\tiCPUs := getCPUs(ids[i])\n\t\t\tjCPUs := getCPUs(ids[j])\n\t\t\tif iCPUs.Size() \u003c jCPUs.Size() {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif iCPUs.Size() \u003e jCPUs.Size() {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn ids[i] \u003c ids[j]\n\t\t})\n}","line":{"from":284,"to":303}} {"id":100005705,"name":"sortAvailableNUMANodes","signature":"func (a *cpuAccumulator) sortAvailableNUMANodes() []int","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"// Sort all NUMA nodes with free CPUs.\nfunc (a *cpuAccumulator) sortAvailableNUMANodes() []int {\n\treturn a.numaOrSocketsFirst.sortAvailableNUMANodes()\n}","line":{"from":305,"to":308}} {"id":100005706,"name":"sortAvailableSockets","signature":"func (a *cpuAccumulator) sortAvailableSockets() []int","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"// Sort all sockets with free CPUs.\nfunc (a *cpuAccumulator) sortAvailableSockets() []int {\n\treturn a.numaOrSocketsFirst.sortAvailableSockets()\n}","line":{"from":310,"to":313}} {"id":100005707,"name":"sortAvailableCores","signature":"func (a *cpuAccumulator) sortAvailableCores() []int","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"// Sort all cores with free CPUs:\nfunc (a *cpuAccumulator) sortAvailableCores() []int {\n\treturn a.numaOrSocketsFirst.sortAvailableCores()\n}","line":{"from":315,"to":318}} {"id":100005708,"name":"sortAvailableCPUs","signature":"func (a *cpuAccumulator) sortAvailableCPUs() []int","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"// Sort all available CPUs:\n// - First by core using sortAvailableCores().\n// - Then within each core, using the sort() algorithm defined above.\nfunc (a *cpuAccumulator) sortAvailableCPUs() []int {\n\tvar result []int\n\tfor _, core := range a.sortAvailableCores() {\n\t\tcpus := a.details.CPUsInCores(core).UnsortedList()\n\t\tsort.Ints(cpus)\n\t\tresult = append(result, cpus...)\n\t}\n\treturn result\n}","line":{"from":320,"to":331}} {"id":100005709,"name":"take","signature":"func (a *cpuAccumulator) take(cpus cpuset.CPUSet)","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"func (a *cpuAccumulator) take(cpus cpuset.CPUSet) {\n\ta.result = a.result.Union(cpus)\n\ta.details = a.details.KeepOnly(a.details.CPUs().Difference(a.result))\n\ta.numCPUsNeeded -= cpus.Size()\n}","line":{"from":333,"to":337}} {"id":100005710,"name":"takeFullNUMANodes","signature":"func (a *cpuAccumulator) takeFullNUMANodes()","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"func (a *cpuAccumulator) takeFullNUMANodes() {\n\tfor _, numa := range a.freeNUMANodes() {\n\t\tcpusInNUMANode := a.topo.CPUDetails.CPUsInNUMANodes(numa)\n\t\tif !a.needs(cpusInNUMANode.Size()) {\n\t\t\tcontinue\n\t\t}\n\t\tklog.V(4).InfoS(\"takeFullNUMANodes: claiming NUMA node\", \"numa\", numa)\n\t\ta.take(cpusInNUMANode)\n\t}\n}","line":{"from":339,"to":348}} {"id":100005711,"name":"takeFullSockets","signature":"func (a *cpuAccumulator) takeFullSockets()","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"func (a *cpuAccumulator) takeFullSockets() {\n\tfor _, socket := range a.freeSockets() {\n\t\tcpusInSocket := a.topo.CPUDetails.CPUsInSockets(socket)\n\t\tif !a.needs(cpusInSocket.Size()) {\n\t\t\tcontinue\n\t\t}\n\t\tklog.V(4).InfoS(\"takeFullSockets: claiming socket\", \"socket\", socket)\n\t\ta.take(cpusInSocket)\n\t}\n}","line":{"from":350,"to":359}} {"id":100005712,"name":"takeFullCores","signature":"func (a *cpuAccumulator) takeFullCores()","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"func (a *cpuAccumulator) takeFullCores() {\n\tfor _, core := range a.freeCores() {\n\t\tcpusInCore := a.topo.CPUDetails.CPUsInCores(core)\n\t\tif !a.needs(cpusInCore.Size()) {\n\t\t\tcontinue\n\t\t}\n\t\tklog.V(4).InfoS(\"takeFullCores: claiming core\", \"core\", core)\n\t\ta.take(cpusInCore)\n\t}\n}","line":{"from":361,"to":370}} {"id":100005713,"name":"takeRemainingCPUs","signature":"func (a *cpuAccumulator) takeRemainingCPUs()","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"func (a *cpuAccumulator) takeRemainingCPUs() {\n\tfor _, cpu := range a.sortAvailableCPUs() {\n\t\tklog.V(4).InfoS(\"takeRemainingCPUs: claiming CPU\", \"cpu\", cpu)\n\t\ta.take(cpuset.New(cpu))\n\t\tif a.isSatisfied() {\n\t\t\treturn\n\t\t}\n\t}\n}","line":{"from":372,"to":380}} {"id":100005714,"name":"rangeNUMANodesNeededToSatisfy","signature":"func (a *cpuAccumulator) rangeNUMANodesNeededToSatisfy(cpuGroupSize int) (int, int)","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"func (a *cpuAccumulator) rangeNUMANodesNeededToSatisfy(cpuGroupSize int) (int, int) {\n\t// Get the total number of NUMA nodes in the system.\n\tnumNUMANodes := a.topo.CPUDetails.NUMANodes().Size()\n\n\t// Get the total number of NUMA nodes that have CPUs available on them.\n\tnumNUMANodesAvailable := a.details.NUMANodes().Size()\n\n\t// Get the total number of CPUs in the system.\n\tnumCPUs := a.topo.CPUDetails.CPUs().Size()\n\n\t// Get the total number of 'cpuGroups' in the system.\n\tnumCPUGroups := (numCPUs-1)/cpuGroupSize + 1\n\n\t// Calculate the number of 'cpuGroups' per NUMA Node in the system (rounding up).\n\tnumCPUGroupsPerNUMANode := (numCPUGroups-1)/numNUMANodes + 1\n\n\t// Calculate the number of available 'cpuGroups' across all NUMA nodes as\n\t// well as the number of 'cpuGroups' that need to be allocated (rounding up).\n\tnumCPUGroupsNeeded := (a.numCPUsNeeded-1)/cpuGroupSize + 1\n\n\t// Calculate the minimum number of numa nodes required to satisfy the\n\t// allocation (rounding up).\n\tminNUMAs := (numCPUGroupsNeeded-1)/numCPUGroupsPerNUMANode + 1\n\n\t// Calculate the maximum number of numa nodes required to satisfy the allocation.\n\tmaxNUMAs := min(numCPUGroupsNeeded, numNUMANodesAvailable)\n\n\treturn minNUMAs, maxNUMAs\n}","line":{"from":382,"to":410}} {"id":100005715,"name":"needs","signature":"func (a *cpuAccumulator) needs(n int) bool","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"func (a *cpuAccumulator) needs(n int) bool {\n\treturn a.numCPUsNeeded \u003e= n\n}","line":{"from":412,"to":414}} {"id":100005716,"name":"isSatisfied","signature":"func (a *cpuAccumulator) isSatisfied() bool","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"func (a *cpuAccumulator) isSatisfied() bool {\n\treturn a.numCPUsNeeded \u003c 1\n}","line":{"from":416,"to":418}} {"id":100005717,"name":"isFailed","signature":"func (a *cpuAccumulator) isFailed() bool","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"func (a *cpuAccumulator) isFailed() bool {\n\treturn a.numCPUsNeeded \u003e a.details.CPUs().Size()\n}","line":{"from":420,"to":422}} {"id":100005718,"name":"iterateCombinations","signature":"func (a *cpuAccumulator) iterateCombinations(n []int, k int, f func([]int) LoopControl)","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"// iterateCombinations walks through all n-choose-k subsets of size k in n and\n// calls function 'f()' on each subset. For example, if n={0,1,2}, and k=2,\n// then f() will be called on the subsets {0,1}, {0,2}. and {1,2}. If f() ever\n// returns 'Break', we break early and exit the loop.\nfunc (a *cpuAccumulator) iterateCombinations(n []int, k int, f func([]int) LoopControl) {\n\tif k \u003c 1 {\n\t\treturn\n\t}\n\n\tvar helper func(n []int, k int, start int, accum []int, f func([]int) LoopControl) LoopControl\n\thelper = func(n []int, k int, start int, accum []int, f func([]int) LoopControl) LoopControl {\n\t\tif k == 0 {\n\t\t\treturn f(accum)\n\t\t}\n\t\tfor i := start; i \u003c= len(n)-k; i++ {\n\t\t\tcontrol := helper(n, k-1, i+1, append(accum, n[i]), f)\n\t\t\tif control == Break {\n\t\t\t\treturn Break\n\t\t\t}\n\t\t}\n\t\treturn Continue\n\t}\n\n\thelper(n, k, 0, []int{}, f)\n}","line":{"from":424,"to":448}} {"id":100005719,"name":"takeByTopologyNUMAPacked","signature":"func takeByTopologyNUMAPacked(topo *topology.CPUTopology, availableCPUs cpuset.CPUSet, numCPUs int) (cpuset.CPUSet, error)","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"func takeByTopologyNUMAPacked(topo *topology.CPUTopology, availableCPUs cpuset.CPUSet, numCPUs int) (cpuset.CPUSet, error) {\n\tacc := newCPUAccumulator(topo, availableCPUs, numCPUs)\n\tif acc.isSatisfied() {\n\t\treturn acc.result, nil\n\t}\n\tif acc.isFailed() {\n\t\treturn cpuset.New(), fmt.Errorf(\"not enough cpus available to satisfy request\")\n\t}\n\n\t// Algorithm: topology-aware best-fit\n\t// 1. Acquire whole NUMA nodes and sockets, if available and the container\n\t// requires at least a NUMA node or socket's-worth of CPUs. If NUMA\n\t// Nodes map to 1 or more sockets, pull from NUMA nodes first.\n\t// Otherwise pull from sockets first.\n\tacc.numaOrSocketsFirst.takeFullFirstLevel()\n\tif acc.isSatisfied() {\n\t\treturn acc.result, nil\n\t}\n\tacc.numaOrSocketsFirst.takeFullSecondLevel()\n\tif acc.isSatisfied() {\n\t\treturn acc.result, nil\n\t}\n\n\t// 2. Acquire whole cores, if available and the container requires at least\n\t// a core's-worth of CPUs.\n\tacc.takeFullCores()\n\tif acc.isSatisfied() {\n\t\treturn acc.result, nil\n\t}\n\n\t// 3. Acquire single threads, preferring to fill partially-allocated cores\n\t// on the same sockets as the whole cores we have already taken in this\n\t// allocation.\n\tacc.takeRemainingCPUs()\n\tif acc.isSatisfied() {\n\t\treturn acc.result, nil\n\t}\n\n\treturn cpuset.New(), fmt.Errorf(\"failed to allocate cpus\")\n}","line":{"from":450,"to":489}} {"id":100005720,"name":"takeByTopologyNUMADistributed","signature":"func takeByTopologyNUMADistributed(topo *topology.CPUTopology, availableCPUs cpuset.CPUSet, numCPUs int, cpuGroupSize int) (cpuset.CPUSet, error)","file":"pkg/kubelet/cm/cpumanager/cpu_assignment.go","code":"// takeByTopologyNUMADistributed returns a CPUSet of size 'numCPUs'.\n//\n// It generates this CPUset by allocating CPUs from 'availableCPUs' according\n// to the algorithm outlined in KEP-2902:\n//\n// https://github.com/kubernetes/enhancements/tree/e7f51ffbe2ee398ffd1fba4a6d854f276bfad9fb/keps/sig-node/2902-cpumanager-distribute-cpus-policy-option\n//\n// This algorithm evenly distribute CPUs across NUMA nodes in cases where more\n// than one NUMA node is required to satisfy the allocation. This is in\n// contrast to the takeByTopologyNUMAPacked algorithm, which attempts to 'pack'\n// CPUs onto NUMA nodes and fill them up before moving on to the next one.\n//\n// At a high-level this algorithm can be summarized as:\n//\n// For each NUMA single node:\n// - If all requested CPUs can be allocated from this NUMA node;\n// --\u003e Do the allocation by running takeByTopologyNUMAPacked() over the\n// available CPUs in that NUMA node and return\n//\n// Otherwise, for each pair of NUMA nodes:\n// - If the set of requested CPUs (modulo 2) can be evenly split across\n// the 2 NUMA nodes; AND\n// - Any remaining CPUs (after the modulo operation) can be striped across\n// some subset of the NUMA nodes;\n// --\u003e Do the allocation by running takeByTopologyNUMAPacked() over the\n// available CPUs in both NUMA nodes and return\n//\n// Otherwise, for each 3-tuple of NUMA nodes:\n// - If the set of requested CPUs (modulo 3) can be evenly distributed\n// across the 3 NUMA nodes; AND\n// - Any remaining CPUs (after the modulo operation) can be striped across\n// some subset of the NUMA nodes;\n// --\u003e Do the allocation by running takeByTopologyNUMAPacked() over the\n// available CPUs in all three NUMA nodes and return\n//\n// ...\n//\n// Otherwise, for the set of all NUMA nodes:\n// - If the set of requested CPUs (modulo NUM_NUMA_NODES) can be evenly\n// distributed across all NUMA nodes; AND\n// - Any remaining CPUs (after the modulo operation) can be striped across\n// some subset of the NUMA nodes;\n// --\u003e Do the allocation by running takeByTopologyNUMAPacked() over the\n// available CPUs in all NUMA nodes and return\n//\n// If none of the above conditions can be met, then resort back to a\n// best-effort fit of packing CPUs into NUMA nodes by calling\n// takeByTopologyNUMAPacked() over all available CPUs.\n//\n// NOTE: A \"balance score\" will be calculated to help find the best subset of\n// NUMA nodes to allocate any 'remainder' CPUs from (in cases where the total\n// number of CPUs to allocate cannot be evenly distributed across the chosen\n// set of NUMA nodes). This \"balance score\" is calculated as the standard\n// deviation of how many CPUs will be available on each NUMA node after all\n// evenly distributed and remainder CPUs are allocated. The subset with the\n// lowest \"balance score\" will receive the CPUs in order to keep the overall\n// allocation of CPUs as \"balanced\" as possible.\n//\n// NOTE: This algorithm has been generalized to take an additional\n// 'cpuGroupSize' parameter to ensure that CPUs are always allocated in groups\n// of size 'cpuGroupSize' according to the algorithm described above. This is\n// important, for example, to ensure that all CPUs (i.e. all hyperthreads) from\n// a single core are allocated together.\nfunc takeByTopologyNUMADistributed(topo *topology.CPUTopology, availableCPUs cpuset.CPUSet, numCPUs int, cpuGroupSize int) (cpuset.CPUSet, error) {\n\t// If the number of CPUs requested cannot be handed out in chunks of\n\t// 'cpuGroupSize', then we just call out the packing algorithm since we\n\t// can't distribute CPUs in this chunk size.\n\tif (numCPUs % cpuGroupSize) != 0 {\n\t\treturn takeByTopologyNUMAPacked(topo, availableCPUs, numCPUs)\n\t}\n\n\t// Otherwise build an accumulator to start allocating CPUs from.\n\tacc := newCPUAccumulator(topo, availableCPUs, numCPUs)\n\tif acc.isSatisfied() {\n\t\treturn acc.result, nil\n\t}\n\tif acc.isFailed() {\n\t\treturn cpuset.New(), fmt.Errorf(\"not enough cpus available to satisfy request\")\n\t}\n\n\t// Get the list of NUMA nodes represented by the set of CPUs in 'availableCPUs'.\n\tnumas := acc.sortAvailableNUMANodes()\n\n\t// Calculate the minimum and maximum possible number of NUMA nodes that\n\t// could satisfy this request. This is used to optimize how many iterations\n\t// of the loop we need to go through below.\n\tminNUMAs, maxNUMAs := acc.rangeNUMANodesNeededToSatisfy(cpuGroupSize)\n\n\t// Try combinations of 1,2,3,... NUMA nodes until we find a combination\n\t// where we can evenly distribute CPUs across them. To optimize things, we\n\t// don't always start at 1 and end at len(numas). Instead, we use the\n\t// values of 'minNUMAs' and 'maxNUMAs' calculated above.\n\tfor k := minNUMAs; k \u003c= maxNUMAs; k++ {\n\t\t// Iterate through the various n-choose-k NUMA node combinations,\n\t\t// looking for the combination of NUMA nodes that can best have CPUs\n\t\t// distributed across them.\n\t\tvar bestBalance float64 = math.MaxFloat64\n\t\tvar bestRemainder []int = nil\n\t\tvar bestCombo []int = nil\n\t\tacc.iterateCombinations(numas, k, func(combo []int) LoopControl {\n\t\t\t// If we've already found a combo with a balance of 0 in a\n\t\t\t// different iteration, then don't bother checking any others.\n\t\t\tif bestBalance == 0 {\n\t\t\t\treturn Break\n\t\t\t}\n\n\t\t\t// Check that this combination of NUMA nodes has enough CPUs to\n\t\t\t// satisfy the allocation overall.\n\t\t\tcpus := acc.details.CPUsInNUMANodes(combo...)\n\t\t\tif cpus.Size() \u003c numCPUs {\n\t\t\t\treturn Continue\n\t\t\t}\n\n\t\t\t// Check that CPUs can be handed out in groups of size\n\t\t\t// 'cpuGroupSize' across the NUMA nodes in this combo.\n\t\t\tnumCPUGroups := 0\n\t\t\tfor _, numa := range combo {\n\t\t\t\tnumCPUGroups += (acc.details.CPUsInNUMANodes(numa).Size() / cpuGroupSize)\n\t\t\t}\n\t\t\tif (numCPUGroups * cpuGroupSize) \u003c numCPUs {\n\t\t\t\treturn Continue\n\t\t\t}\n\n\t\t\t// Check that each NUMA node in this combination can allocate an\n\t\t\t// even distribution of CPUs in groups of size 'cpuGroupSize',\n\t\t\t// modulo some remainder.\n\t\t\tdistribution := (numCPUs / len(combo) / cpuGroupSize) * cpuGroupSize\n\t\t\tfor _, numa := range combo {\n\t\t\t\tcpus := acc.details.CPUsInNUMANodes(numa)\n\t\t\t\tif cpus.Size() \u003c distribution {\n\t\t\t\t\treturn Continue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Calculate how many CPUs will be available on each NUMA node in\n\t\t\t// the system after allocating an even distribution of CPU groups\n\t\t\t// of size 'cpuGroupSize' from each NUMA node in 'combo'. This will\n\t\t\t// be used in the \"balance score\" calculation to help decide if\n\t\t\t// this combo should ultimately be chosen.\n\t\t\tavailableAfterAllocation := make(mapIntInt, len(numas))\n\t\t\tfor _, numa := range numas {\n\t\t\t\tavailableAfterAllocation[numa] = acc.details.CPUsInNUMANodes(numa).Size()\n\t\t\t}\n\t\t\tfor _, numa := range combo {\n\t\t\t\tavailableAfterAllocation[numa] -= distribution\n\t\t\t}\n\n\t\t\t// Check if there are any remaining CPUs to distribute across the\n\t\t\t// NUMA nodes once CPUs have been evenly distributed in groups of\n\t\t\t// size 'cpuGroupSize'.\n\t\t\tremainder := numCPUs - (distribution * len(combo))\n\n\t\t\t// Get a list of NUMA nodes to consider pulling the remainder CPUs\n\t\t\t// from. This list excludes NUMA nodes that don't have at least\n\t\t\t// 'cpuGroupSize' CPUs available after being allocated\n\t\t\t// 'distribution' number of CPUs.\n\t\t\tvar remainderCombo []int\n\t\t\tfor _, numa := range combo {\n\t\t\t\tif availableAfterAllocation[numa] \u003e= cpuGroupSize {\n\t\t\t\t\tremainderCombo = append(remainderCombo, numa)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Declare a set of local variables to help track the \"balance\n\t\t\t// scores\" calculated when using different subsets of\n\t\t\t// 'remainderCombo' to allocate remainder CPUs from.\n\t\t\tvar bestLocalBalance float64 = math.MaxFloat64\n\t\t\tvar bestLocalRemainder []int = nil\n\n\t\t\t// If there aren't any remainder CPUs to allocate, then calculate\n\t\t\t// the \"balance score\" of this combo as the standard deviation of\n\t\t\t// the values contained in 'availableAfterAllocation'.\n\t\t\tif remainder == 0 {\n\t\t\t\tbestLocalBalance = standardDeviation(availableAfterAllocation.Values())\n\t\t\t\tbestLocalRemainder = nil\n\t\t\t}\n\n\t\t\t// Otherwise, find the best \"balance score\" when allocating the\n\t\t\t// remainder CPUs across different subsets of NUMA nodes in 'remainderCombo'.\n\t\t\t// These remainder CPUs are handed out in groups of size 'cpuGroupSize'.\n\t\t\t// We start from k=len(remainderCombo) and walk down to k=1 so that\n\t\t\t// we continue to distribute CPUs as much as possible across\n\t\t\t// multiple NUMA nodes.\n\t\t\tfor k := len(remainderCombo); remainder \u003e 0 \u0026\u0026 k \u003e= 1; k-- {\n\t\t\t\tacc.iterateCombinations(remainderCombo, k, func(subset []int) LoopControl {\n\t\t\t\t\t// Make a local copy of 'remainder'.\n\t\t\t\t\tremainder := remainder\n\n\t\t\t\t\t// Make a local copy of 'availableAfterAllocation'.\n\t\t\t\t\tavailableAfterAllocation := availableAfterAllocation.Clone()\n\n\t\t\t\t\t// If this subset is not capable of allocating all\n\t\t\t\t\t// remainder CPUs, continue to the next one.\n\t\t\t\t\tif sum(availableAfterAllocation.Values(subset...)) \u003c remainder {\n\t\t\t\t\t\treturn Continue\n\t\t\t\t\t}\n\n\t\t\t\t\t// For all NUMA nodes in 'subset', walk through them,\n\t\t\t\t\t// removing 'cpuGroupSize' number of CPUs from each\n\t\t\t\t\t// until all remainder CPUs have been accounted for.\n\t\t\t\t\tfor remainder \u003e 0 {\n\t\t\t\t\t\tfor _, numa := range subset {\n\t\t\t\t\t\t\tif remainder == 0 {\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif availableAfterAllocation[numa] \u003c cpuGroupSize {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tavailableAfterAllocation[numa] -= cpuGroupSize\n\t\t\t\t\t\t\tremainder -= cpuGroupSize\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Calculate the \"balance score\" as the standard deviation\n\t\t\t\t\t// of the number of CPUs available on all NUMA nodes in the\n\t\t\t\t\t// system after the remainder CPUs have been allocated\n\t\t\t\t\t// across 'subset' in groups of size 'cpuGroupSize'.\n\t\t\t\t\tbalance := standardDeviation(availableAfterAllocation.Values())\n\t\t\t\t\tif balance \u003c bestLocalBalance {\n\t\t\t\t\t\tbestLocalBalance = balance\n\t\t\t\t\t\tbestLocalRemainder = subset\n\t\t\t\t\t}\n\n\t\t\t\t\treturn Continue\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// If the best \"balance score\" for this combo is less than the\n\t\t\t// lowest \"balance score\" of all previous combos, then update this\n\t\t\t// combo (and remainder set) to be the best one found so far.\n\t\t\tif bestLocalBalance \u003c bestBalance {\n\t\t\t\tbestBalance = bestLocalBalance\n\t\t\t\tbestRemainder = bestLocalRemainder\n\t\t\t\tbestCombo = combo\n\t\t\t}\n\n\t\t\treturn Continue\n\t\t})\n\n\t\t// If we made it through all of the iterations above without finding a\n\t\t// combination of NUMA nodes that can properly balance CPU allocations,\n\t\t// then move on to the next larger set of NUMA node combinations.\n\t\tif bestCombo == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Otherwise, start allocating CPUs from the NUMA node combination\n\t\t// chosen. First allocate an even distribution of CPUs in groups of\n\t\t// size 'cpuGroupSize' from 'bestCombo'.\n\t\tdistribution := (numCPUs / len(bestCombo) / cpuGroupSize) * cpuGroupSize\n\t\tfor _, numa := range bestCombo {\n\t\t\tcpus, _ := takeByTopologyNUMAPacked(acc.topo, acc.details.CPUsInNUMANodes(numa), distribution)\n\t\t\tacc.take(cpus)\n\t\t}\n\n\t\t// Then allocate any remaining CPUs in groups of size 'cpuGroupSize'\n\t\t// from each NUMA node in the remainder set.\n\t\tremainder := numCPUs - (distribution * len(bestCombo))\n\t\tfor remainder \u003e 0 {\n\t\t\tfor _, numa := range bestRemainder {\n\t\t\t\tif remainder == 0 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif acc.details.CPUsInNUMANodes(numa).Size() \u003c cpuGroupSize {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tcpus, _ := takeByTopologyNUMAPacked(acc.topo, acc.details.CPUsInNUMANodes(numa), cpuGroupSize)\n\t\t\t\tacc.take(cpus)\n\t\t\t\tremainder -= cpuGroupSize\n\t\t\t}\n\t\t}\n\n\t\t// If we haven't allocated all of our CPUs at this point, then something\n\t\t// went wrong in our accounting and we should error out.\n\t\tif acc.numCPUsNeeded \u003e 0 {\n\t\t\treturn cpuset.New(), fmt.Errorf(\"accounting error, not enough CPUs allocated, remaining: %v\", acc.numCPUsNeeded)\n\t\t}\n\n\t\t// Likewise, if we have allocated too many CPUs at this point, then something\n\t\t// went wrong in our accounting and we should error out.\n\t\tif acc.numCPUsNeeded \u003c 0 {\n\t\t\treturn cpuset.New(), fmt.Errorf(\"accounting error, too many CPUs allocated, remaining: %v\", acc.numCPUsNeeded)\n\t\t}\n\n\t\t// Otherwise, return the result\n\t\treturn acc.result, nil\n\t}\n\n\t// If we never found a combination of NUMA nodes that we could properly\n\t// distribute CPUs across, fall back to the packing algorithm.\n\treturn takeByTopologyNUMAPacked(topo, availableCPUs, numCPUs)\n}","line":{"from":491,"to":782}} {"id":100005721,"name":"AddSource","signature":"func (s *sourcesReadyStub) AddSource(source string) {}","file":"pkg/kubelet/cm/cpumanager/cpu_manager.go","code":"func (s *sourcesReadyStub) AddSource(source string) {}","line":{"from":150,"to":150}} {"id":100005722,"name":"AllReady","signature":"func (s *sourcesReadyStub) AllReady() bool { return true }","file":"pkg/kubelet/cm/cpumanager/cpu_manager.go","code":"func (s *sourcesReadyStub) AllReady() bool { return true }","line":{"from":151,"to":151}} {"id":100005723,"name":"NewManager","signature":"func NewManager(cpuPolicyName string, cpuPolicyOptions map[string]string, reconcilePeriod time.Duration, machineInfo *cadvisorapi.MachineInfo, specificCPUs cpuset.CPUSet, nodeAllocatableReservation v1.ResourceList, stateFileDirectory string, affinity topologymanager.Store) (Manager, error)","file":"pkg/kubelet/cm/cpumanager/cpu_manager.go","code":"// NewManager creates new cpu manager based on provided policy\nfunc NewManager(cpuPolicyName string, cpuPolicyOptions map[string]string, reconcilePeriod time.Duration, machineInfo *cadvisorapi.MachineInfo, specificCPUs cpuset.CPUSet, nodeAllocatableReservation v1.ResourceList, stateFileDirectory string, affinity topologymanager.Store) (Manager, error) {\n\tvar topo *topology.CPUTopology\n\tvar policy Policy\n\tvar err error\n\n\tswitch policyName(cpuPolicyName) {\n\n\tcase PolicyNone:\n\t\tpolicy, err = NewNonePolicy(cpuPolicyOptions)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"new none policy error: %w\", err)\n\t\t}\n\n\tcase PolicyStatic:\n\t\ttopo, err = topology.Discover(machineInfo)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tklog.InfoS(\"Detected CPU topology\", \"topology\", topo)\n\n\t\treservedCPUs, ok := nodeAllocatableReservation[v1.ResourceCPU]\n\t\tif !ok {\n\t\t\t// The static policy cannot initialize without this information.\n\t\t\treturn nil, fmt.Errorf(\"[cpumanager] unable to determine reserved CPU resources for static policy\")\n\t\t}\n\t\tif reservedCPUs.IsZero() {\n\t\t\t// The static policy requires this to be nonzero. Zero CPU reservation\n\t\t\t// would allow the shared pool to be completely exhausted. At that point\n\t\t\t// either we would violate our guarantee of exclusivity or need to evict\n\t\t\t// any pod that has at least one container that requires zero CPUs.\n\t\t\t// See the comments in policy_static.go for more details.\n\t\t\treturn nil, fmt.Errorf(\"[cpumanager] the static policy requires systemreserved.cpu + kubereserved.cpu to be greater than zero\")\n\t\t}\n\n\t\t// Take the ceiling of the reservation, since fractional CPUs cannot be\n\t\t// exclusively allocated.\n\t\treservedCPUsFloat := float64(reservedCPUs.MilliValue()) / 1000\n\t\tnumReservedCPUs := int(math.Ceil(reservedCPUsFloat))\n\t\tpolicy, err = NewStaticPolicy(topo, numReservedCPUs, specificCPUs, affinity, cpuPolicyOptions)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"new static policy error: %w\", err)\n\t\t}\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown policy: \\\"%s\\\"\", cpuPolicyName)\n\t}\n\n\tmanager := \u0026manager{\n\t\tpolicy: policy,\n\t\treconcilePeriod: reconcilePeriod,\n\t\tlastUpdateState: state.NewMemoryState(),\n\t\ttopology: topo,\n\t\tnodeAllocatableReservation: nodeAllocatableReservation,\n\t\tstateFileDirectory: stateFileDirectory,\n\t}\n\tmanager.sourcesReady = \u0026sourcesReadyStub{}\n\treturn manager, nil\n}","line":{"from":153,"to":211}} {"id":100005724,"name":"Start","signature":"func (m *manager) Start(activePods ActivePodsFunc, sourcesReady config.SourcesReady, podStatusProvider status.PodStatusProvider, containerRuntime runtimeService, initialContainers containermap.ContainerMap) error","file":"pkg/kubelet/cm/cpumanager/cpu_manager.go","code":"func (m *manager) Start(activePods ActivePodsFunc, sourcesReady config.SourcesReady, podStatusProvider status.PodStatusProvider, containerRuntime runtimeService, initialContainers containermap.ContainerMap) error {\n\tklog.InfoS(\"Starting CPU manager\", \"policy\", m.policy.Name())\n\tklog.InfoS(\"Reconciling\", \"reconcilePeriod\", m.reconcilePeriod)\n\tm.sourcesReady = sourcesReady\n\tm.activePods = activePods\n\tm.podStatusProvider = podStatusProvider\n\tm.containerRuntime = containerRuntime\n\tm.containerMap = initialContainers\n\n\tstateImpl, err := state.NewCheckpointState(m.stateFileDirectory, cpuManagerStateFileName, m.policy.Name(), m.containerMap)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Could not initialize checkpoint manager, please drain node and remove policy state file\")\n\t\treturn err\n\t}\n\tm.state = stateImpl\n\n\terr = m.policy.Start(m.state)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Policy start error\")\n\t\treturn err\n\t}\n\n\tm.allocatableCPUs = m.policy.GetAllocatableCPUs(m.state)\n\n\tif m.policy.Name() == string(PolicyNone) {\n\t\treturn nil\n\t}\n\t// Periodically call m.reconcileState() to continue to keep the CPU sets of\n\t// all pods in sync with and guaranteed CPUs handed out among them.\n\tgo wait.Until(func() { m.reconcileState() }, m.reconcilePeriod, wait.NeverStop)\n\treturn nil\n}","line":{"from":213,"to":244}} {"id":100005725,"name":"Allocate","signature":"func (m *manager) Allocate(p *v1.Pod, c *v1.Container) error","file":"pkg/kubelet/cm/cpumanager/cpu_manager.go","code":"func (m *manager) Allocate(p *v1.Pod, c *v1.Container) error {\n\t// The pod is during the admission phase. We need to save the pod to avoid it\n\t// being cleaned before the admission ended\n\tm.setPodPendingAdmission(p)\n\n\t// Garbage collect any stranded resources before allocating CPUs.\n\tm.removeStaleState()\n\n\tm.Lock()\n\tdefer m.Unlock()\n\n\t// Call down into the policy to assign this container CPUs if required.\n\terr := m.policy.Allocate(m.state, p, c)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Allocate error\")\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":246,"to":265}} {"id":100005726,"name":"AddContainer","signature":"func (m *manager) AddContainer(pod *v1.Pod, container *v1.Container, containerID string)","file":"pkg/kubelet/cm/cpumanager/cpu_manager.go","code":"func (m *manager) AddContainer(pod *v1.Pod, container *v1.Container, containerID string) {\n\tm.Lock()\n\tdefer m.Unlock()\n\tif cset, exists := m.state.GetCPUSet(string(pod.UID), container.Name); exists {\n\t\tm.lastUpdateState.SetCPUSet(string(pod.UID), container.Name, cset)\n\t}\n\tm.containerMap.Add(string(pod.UID), container.Name, containerID)\n}","line":{"from":267,"to":274}} {"id":100005727,"name":"RemoveContainer","signature":"func (m *manager) RemoveContainer(containerID string) error","file":"pkg/kubelet/cm/cpumanager/cpu_manager.go","code":"func (m *manager) RemoveContainer(containerID string) error {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\terr := m.policyRemoveContainerByID(containerID)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"RemoveContainer error\")\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":276,"to":287}} {"id":100005728,"name":"policyRemoveContainerByID","signature":"func (m *manager) policyRemoveContainerByID(containerID string) error","file":"pkg/kubelet/cm/cpumanager/cpu_manager.go","code":"func (m *manager) policyRemoveContainerByID(containerID string) error {\n\tpodUID, containerName, err := m.containerMap.GetContainerRef(containerID)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\terr = m.policy.RemoveContainer(m.state, podUID, containerName)\n\tif err == nil {\n\t\tm.lastUpdateState.Delete(podUID, containerName)\n\t\tm.containerMap.RemoveByContainerID(containerID)\n\t}\n\n\treturn err\n}","line":{"from":289,"to":302}} {"id":100005729,"name":"policyRemoveContainerByRef","signature":"func (m *manager) policyRemoveContainerByRef(podUID string, containerName string) error","file":"pkg/kubelet/cm/cpumanager/cpu_manager.go","code":"func (m *manager) policyRemoveContainerByRef(podUID string, containerName string) error {\n\terr := m.policy.RemoveContainer(m.state, podUID, containerName)\n\tif err == nil {\n\t\tm.lastUpdateState.Delete(podUID, containerName)\n\t\tm.containerMap.RemoveByContainerRef(podUID, containerName)\n\t}\n\n\treturn err\n}","line":{"from":304,"to":312}} {"id":100005730,"name":"State","signature":"func (m *manager) State() state.Reader","file":"pkg/kubelet/cm/cpumanager/cpu_manager.go","code":"func (m *manager) State() state.Reader {\n\treturn m.state\n}","line":{"from":314,"to":316}} {"id":100005731,"name":"GetTopologyHints","signature":"func (m *manager) GetTopologyHints(pod *v1.Pod, container *v1.Container) map[string][]topologymanager.TopologyHint","file":"pkg/kubelet/cm/cpumanager/cpu_manager.go","code":"func (m *manager) GetTopologyHints(pod *v1.Pod, container *v1.Container) map[string][]topologymanager.TopologyHint {\n\t// The pod is during the admission phase. We need to save the pod to avoid it\n\t// being cleaned before the admission ended\n\tm.setPodPendingAdmission(pod)\n\t// Garbage collect any stranded resources before providing TopologyHints\n\tm.removeStaleState()\n\t// Delegate to active policy\n\treturn m.policy.GetTopologyHints(m.state, pod, container)\n}","line":{"from":318,"to":326}} {"id":100005732,"name":"GetPodTopologyHints","signature":"func (m *manager) GetPodTopologyHints(pod *v1.Pod) map[string][]topologymanager.TopologyHint","file":"pkg/kubelet/cm/cpumanager/cpu_manager.go","code":"func (m *manager) GetPodTopologyHints(pod *v1.Pod) map[string][]topologymanager.TopologyHint {\n\t// The pod is during the admission phase. We need to save the pod to avoid it\n\t// being cleaned before the admission ended\n\tm.setPodPendingAdmission(pod)\n\t// Garbage collect any stranded resources before providing TopologyHints\n\tm.removeStaleState()\n\t// Delegate to active policy\n\treturn m.policy.GetPodTopologyHints(m.state, pod)\n}","line":{"from":328,"to":336}} {"id":100005733,"name":"GetAllocatableCPUs","signature":"func (m *manager) GetAllocatableCPUs() cpuset.CPUSet","file":"pkg/kubelet/cm/cpumanager/cpu_manager.go","code":"func (m *manager) GetAllocatableCPUs() cpuset.CPUSet {\n\treturn m.allocatableCPUs.Clone()\n}","line":{"from":338,"to":340}} {"id":100005734,"name":"removeStaleState","signature":"func (m *manager) removeStaleState()","file":"pkg/kubelet/cm/cpumanager/cpu_manager.go","code":"func (m *manager) removeStaleState() {\n\t// Only once all sources are ready do we attempt to remove any stale state.\n\t// This ensures that the call to `m.activePods()` below will succeed with\n\t// the actual active pods list.\n\tif !m.sourcesReady.AllReady() {\n\t\treturn\n\t}\n\n\t// We grab the lock to ensure that no new containers will grab CPUs while\n\t// executing the code below. Without this lock, its possible that we end up\n\t// removing state that is newly added by an asynchronous call to\n\t// AddContainer() during the execution of this code.\n\tm.Lock()\n\tdefer m.Unlock()\n\n\t// Get the list of active pods.\n\tactiveAndAdmittedPods := m.activePods()\n\tif m.pendingAdmissionPod != nil {\n\t\tactiveAndAdmittedPods = append(activeAndAdmittedPods, m.pendingAdmissionPod)\n\t}\n\n\t// Build a list of (podUID, containerName) pairs for all containers in all active Pods.\n\tactiveContainers := make(map[string]map[string]struct{})\n\tfor _, pod := range activeAndAdmittedPods {\n\t\tactiveContainers[string(pod.UID)] = make(map[string]struct{})\n\t\tfor _, container := range append(pod.Spec.InitContainers, pod.Spec.Containers...) {\n\t\t\tactiveContainers[string(pod.UID)][container.Name] = struct{}{}\n\t\t}\n\t}\n\n\t// Loop through the CPUManager state. Remove any state for containers not\n\t// in the `activeContainers` list built above.\n\tassignments := m.state.GetCPUAssignments()\n\tfor podUID := range assignments {\n\t\tfor containerName := range assignments[podUID] {\n\t\t\tif _, ok := activeContainers[podUID][containerName]; !ok {\n\t\t\t\tklog.ErrorS(nil, \"RemoveStaleState: removing container\", \"podUID\", podUID, \"containerName\", containerName)\n\t\t\t\terr := m.policyRemoveContainerByRef(podUID, containerName)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"RemoveStaleState: failed to remove container\", \"podUID\", podUID, \"containerName\", containerName)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tm.containerMap.Visit(func(podUID, containerName, containerID string) {\n\t\tif _, ok := activeContainers[podUID][containerName]; !ok {\n\t\t\tklog.ErrorS(nil, \"RemoveStaleState: removing container\", \"podUID\", podUID, \"containerName\", containerName)\n\t\t\terr := m.policyRemoveContainerByRef(podUID, containerName)\n\t\t\tif err != nil {\n\t\t\t\tklog.ErrorS(err, \"RemoveStaleState: failed to remove container\", \"podUID\", podUID, \"containerName\", containerName)\n\t\t\t}\n\t\t}\n\t})\n}","line":{"from":348,"to":402}} {"id":100005735,"name":"reconcileState","signature":"func (m *manager) reconcileState() (success []reconciledContainer, failure []reconciledContainer)","file":"pkg/kubelet/cm/cpumanager/cpu_manager.go","code":"func (m *manager) reconcileState() (success []reconciledContainer, failure []reconciledContainer) {\n\tctx := context.Background()\n\tsuccess = []reconciledContainer{}\n\tfailure = []reconciledContainer{}\n\n\tm.removeStaleState()\n\tfor _, pod := range m.activePods() {\n\t\tpstatus, ok := m.podStatusProvider.GetPodStatus(pod.UID)\n\t\tif !ok {\n\t\t\tklog.V(4).InfoS(\"ReconcileState: skipping pod; status not found\", \"pod\", klog.KObj(pod))\n\t\t\tfailure = append(failure, reconciledContainer{pod.Name, \"\", \"\"})\n\t\t\tcontinue\n\t\t}\n\n\t\tallContainers := pod.Spec.InitContainers\n\t\tallContainers = append(allContainers, pod.Spec.Containers...)\n\t\tfor _, container := range allContainers {\n\t\t\tcontainerID, err := findContainerIDByName(\u0026pstatus, container.Name)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).InfoS(\"ReconcileState: skipping container; ID not found in pod status\", \"pod\", klog.KObj(pod), \"containerName\", container.Name, \"err\", err)\n\t\t\t\tfailure = append(failure, reconciledContainer{pod.Name, container.Name, \"\"})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcstatus, err := findContainerStatusByName(\u0026pstatus, container.Name)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).InfoS(\"ReconcileState: skipping container; container status not found in pod status\", \"pod\", klog.KObj(pod), \"containerName\", container.Name, \"err\", err)\n\t\t\t\tfailure = append(failure, reconciledContainer{pod.Name, container.Name, \"\"})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif cstatus.State.Waiting != nil ||\n\t\t\t\t(cstatus.State.Waiting == nil \u0026\u0026 cstatus.State.Running == nil \u0026\u0026 cstatus.State.Terminated == nil) {\n\t\t\t\tklog.V(4).InfoS(\"ReconcileState: skipping container; container still in the waiting state\", \"pod\", klog.KObj(pod), \"containerName\", container.Name, \"err\", err)\n\t\t\t\tfailure = append(failure, reconciledContainer{pod.Name, container.Name, \"\"})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tm.Lock()\n\t\t\tif cstatus.State.Terminated != nil {\n\t\t\t\t// The container is terminated but we can't call m.RemoveContainer()\n\t\t\t\t// here because it could remove the allocated cpuset for the container\n\t\t\t\t// which may be in the process of being restarted. That would result\n\t\t\t\t// in the container losing any exclusively-allocated CPUs that it\n\t\t\t\t// was allocated.\n\t\t\t\t_, _, err := m.containerMap.GetContainerRef(containerID)\n\t\t\t\tif err == nil {\n\t\t\t\t\tklog.V(4).InfoS(\"ReconcileState: ignoring terminated container\", \"pod\", klog.KObj(pod), \"containerID\", containerID)\n\t\t\t\t}\n\t\t\t\tm.Unlock()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Once we make it here we know we have a running container.\n\t\t\t// Idempotently add it to the containerMap incase it is missing.\n\t\t\t// This can happen after a kubelet restart, for example.\n\t\t\tm.containerMap.Add(string(pod.UID), container.Name, containerID)\n\t\t\tm.Unlock()\n\n\t\t\tcset := m.state.GetCPUSetOrDefault(string(pod.UID), container.Name)\n\t\t\tif cset.IsEmpty() {\n\t\t\t\t// NOTE: This should not happen outside of tests.\n\t\t\t\tklog.V(4).InfoS(\"ReconcileState: skipping container; assigned cpuset is empty\", \"pod\", klog.KObj(pod), \"containerName\", container.Name)\n\t\t\t\tfailure = append(failure, reconciledContainer{pod.Name, container.Name, containerID})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlcset := m.lastUpdateState.GetCPUSetOrDefault(string(pod.UID), container.Name)\n\t\t\tif !cset.Equals(lcset) {\n\t\t\t\tklog.V(4).InfoS(\"ReconcileState: updating container\", \"pod\", klog.KObj(pod), \"containerName\", container.Name, \"containerID\", containerID, \"cpuSet\", cset)\n\t\t\t\terr = m.updateContainerCPUSet(ctx, containerID, cset)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"ReconcileState: failed to update container\", \"pod\", klog.KObj(pod), \"containerName\", container.Name, \"containerID\", containerID, \"cpuSet\", cset)\n\t\t\t\t\tfailure = append(failure, reconciledContainer{pod.Name, container.Name, containerID})\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tm.lastUpdateState.SetCPUSet(string(pod.UID), container.Name, cset)\n\t\t\t}\n\t\t\tsuccess = append(success, reconciledContainer{pod.Name, container.Name, containerID})\n\t\t}\n\t}\n\treturn success, failure\n}","line":{"from":404,"to":486}} {"id":100005736,"name":"findContainerIDByName","signature":"func findContainerIDByName(status *v1.PodStatus, name string) (string, error)","file":"pkg/kubelet/cm/cpumanager/cpu_manager.go","code":"func findContainerIDByName(status *v1.PodStatus, name string) (string, error) {\n\tallStatuses := status.InitContainerStatuses\n\tallStatuses = append(allStatuses, status.ContainerStatuses...)\n\tfor _, container := range allStatuses {\n\t\tif container.Name == name \u0026\u0026 container.ContainerID != \"\" {\n\t\t\tcid := \u0026kubecontainer.ContainerID{}\n\t\t\terr := cid.ParseString(container.ContainerID)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\treturn cid.ID, nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"unable to find ID for container with name %v in pod status (it may not be running)\", name)\n}","line":{"from":488,"to":502}} {"id":100005737,"name":"findContainerStatusByName","signature":"func findContainerStatusByName(status *v1.PodStatus, name string) (*v1.ContainerStatus, error)","file":"pkg/kubelet/cm/cpumanager/cpu_manager.go","code":"func findContainerStatusByName(status *v1.PodStatus, name string) (*v1.ContainerStatus, error) {\n\tfor _, containerStatus := range append(status.InitContainerStatuses, status.ContainerStatuses...) {\n\t\tif containerStatus.Name == name {\n\t\t\treturn \u0026containerStatus, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"unable to find status for container with name %v in pod status (it may not be running)\", name)\n}","line":{"from":504,"to":511}} {"id":100005738,"name":"updateContainerCPUSet","signature":"func (m *manager) updateContainerCPUSet(ctx context.Context, containerID string, cpus cpuset.CPUSet) error","file":"pkg/kubelet/cm/cpumanager/cpu_manager.go","code":"func (m *manager) updateContainerCPUSet(ctx context.Context, containerID string, cpus cpuset.CPUSet) error {\n\t// TODO: Consider adding a `ResourceConfigForContainer` helper in\n\t// helpers_linux.go similar to what exists for pods.\n\t// It would be better to pass the full container resources here instead of\n\t// this patch-like partial resources.\n\treturn m.containerRuntime.UpdateContainerResources(\n\t\tctx,\n\t\tcontainerID,\n\t\t\u0026runtimeapi.ContainerResources{\n\t\t\tLinux: \u0026runtimeapi.LinuxContainerResources{\n\t\t\t\tCpusetCpus: cpus.String(),\n\t\t\t},\n\t\t})\n}","line":{"from":513,"to":526}} {"id":100005739,"name":"GetExclusiveCPUs","signature":"func (m *manager) GetExclusiveCPUs(podUID, containerName string) cpuset.CPUSet","file":"pkg/kubelet/cm/cpumanager/cpu_manager.go","code":"func (m *manager) GetExclusiveCPUs(podUID, containerName string) cpuset.CPUSet {\n\tif result, ok := m.state.GetCPUSet(podUID, containerName); ok {\n\t\treturn result\n\t}\n\n\treturn cpuset.CPUSet{}\n}","line":{"from":528,"to":534}} {"id":100005740,"name":"GetCPUAffinity","signature":"func (m *manager) GetCPUAffinity(podUID, containerName string) cpuset.CPUSet","file":"pkg/kubelet/cm/cpumanager/cpu_manager.go","code":"func (m *manager) GetCPUAffinity(podUID, containerName string) cpuset.CPUSet {\n\treturn m.state.GetCPUSetOrDefault(podUID, containerName)\n}","line":{"from":536,"to":538}} {"id":100005741,"name":"setPodPendingAdmission","signature":"func (m *manager) setPodPendingAdmission(pod *v1.Pod)","file":"pkg/kubelet/cm/cpumanager/cpu_manager.go","code":"func (m *manager) setPodPendingAdmission(pod *v1.Pod) {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tm.pendingAdmissionPod = pod\n}","line":{"from":540,"to":545}} {"id":100005742,"name":"NewNonePolicy","signature":"func NewNonePolicy(cpuPolicyOptions map[string]string) (Policy, error)","file":"pkg/kubelet/cm/cpumanager/policy_none.go","code":"// NewNonePolicy returns a cpuset manager policy that does nothing\nfunc NewNonePolicy(cpuPolicyOptions map[string]string) (Policy, error) {\n\tif len(cpuPolicyOptions) \u003e 0 {\n\t\treturn nil, fmt.Errorf(\"None policy: received unsupported options=%v\", cpuPolicyOptions)\n\t}\n\treturn \u0026nonePolicy{}, nil\n}","line":{"from":36,"to":42}} {"id":100005743,"name":"Name","signature":"func (p *nonePolicy) Name() string","file":"pkg/kubelet/cm/cpumanager/policy_none.go","code":"func (p *nonePolicy) Name() string {\n\treturn string(PolicyNone)\n}","line":{"from":44,"to":46}} {"id":100005744,"name":"Start","signature":"func (p *nonePolicy) Start(s state.State) error","file":"pkg/kubelet/cm/cpumanager/policy_none.go","code":"func (p *nonePolicy) Start(s state.State) error {\n\tklog.InfoS(\"None policy: Start\")\n\treturn nil\n}","line":{"from":48,"to":51}} {"id":100005745,"name":"Allocate","signature":"func (p *nonePolicy) Allocate(s state.State, pod *v1.Pod, container *v1.Container) error","file":"pkg/kubelet/cm/cpumanager/policy_none.go","code":"func (p *nonePolicy) Allocate(s state.State, pod *v1.Pod, container *v1.Container) error {\n\treturn nil\n}","line":{"from":53,"to":55}} {"id":100005746,"name":"RemoveContainer","signature":"func (p *nonePolicy) RemoveContainer(s state.State, podUID string, containerName string) error","file":"pkg/kubelet/cm/cpumanager/policy_none.go","code":"func (p *nonePolicy) RemoveContainer(s state.State, podUID string, containerName string) error {\n\treturn nil\n}","line":{"from":57,"to":59}} {"id":100005747,"name":"GetTopologyHints","signature":"func (p *nonePolicy) GetTopologyHints(s state.State, pod *v1.Pod, container *v1.Container) map[string][]topologymanager.TopologyHint","file":"pkg/kubelet/cm/cpumanager/policy_none.go","code":"func (p *nonePolicy) GetTopologyHints(s state.State, pod *v1.Pod, container *v1.Container) map[string][]topologymanager.TopologyHint {\n\treturn nil\n}","line":{"from":61,"to":63}} {"id":100005748,"name":"GetPodTopologyHints","signature":"func (p *nonePolicy) GetPodTopologyHints(s state.State, pod *v1.Pod) map[string][]topologymanager.TopologyHint","file":"pkg/kubelet/cm/cpumanager/policy_none.go","code":"func (p *nonePolicy) GetPodTopologyHints(s state.State, pod *v1.Pod) map[string][]topologymanager.TopologyHint {\n\treturn nil\n}","line":{"from":65,"to":67}} {"id":100005749,"name":"GetAllocatableCPUs","signature":"func (p *nonePolicy) GetAllocatableCPUs(m state.State) cpuset.CPUSet","file":"pkg/kubelet/cm/cpumanager/policy_none.go","code":"// Assignable CPUs are the ones that can be exclusively allocated to pods that meet the exclusivity requirement\n// (ie guaranteed QoS class and integral CPU request).\n// Assignability of CPUs as a concept is only applicable in case of static policy i.e. scenarios where workloads\n// CAN get exclusive access to core(s).\n// Hence, we return empty set here: no cpus are assignable according to above definition with this policy.\nfunc (p *nonePolicy) GetAllocatableCPUs(m state.State) cpuset.CPUSet {\n\treturn cpuset.New()\n}","line":{"from":69,"to":76}} {"id":100005750,"name":"CheckPolicyOptionAvailable","signature":"func CheckPolicyOptionAvailable(option string) error","file":"pkg/kubelet/cm/cpumanager/policy_options.go","code":"// CheckPolicyOptionAvailable verifies if the given option can be used depending on the Feature Gate Settings.\n// returns nil on success, or an error describing the failure on error.\nfunc CheckPolicyOptionAvailable(option string) error {\n\tif !alphaOptions.Has(option) \u0026\u0026 !betaOptions.Has(option) \u0026\u0026 !stableOptions.Has(option) {\n\t\treturn fmt.Errorf(\"unknown CPU Manager Policy option: %q\", option)\n\t}\n\n\tif alphaOptions.Has(option) \u0026\u0026 !utilfeature.DefaultFeatureGate.Enabled(kubefeatures.CPUManagerPolicyAlphaOptions) {\n\t\treturn fmt.Errorf(\"CPU Manager Policy Alpha-level Options not enabled, but option %q provided\", option)\n\t}\n\n\tif betaOptions.Has(option) \u0026\u0026 !utilfeature.DefaultFeatureGate.Enabled(kubefeatures.CPUManagerPolicyBetaOptions) {\n\t\treturn fmt.Errorf(\"CPU Manager Policy Beta-level Options not enabled, but option %q provided\", option)\n\t}\n\n\treturn nil\n}","line":{"from":48,"to":64}} {"id":100005751,"name":"NewStaticPolicyOptions","signature":"func NewStaticPolicyOptions(policyOptions map[string]string) (StaticPolicyOptions, error)","file":"pkg/kubelet/cm/cpumanager/policy_options.go","code":"// NewStaticPolicyOptions creates a StaticPolicyOptions struct from the user configuration.\nfunc NewStaticPolicyOptions(policyOptions map[string]string) (StaticPolicyOptions, error) {\n\topts := StaticPolicyOptions{}\n\tfor name, value := range policyOptions {\n\t\tif err := CheckPolicyOptionAvailable(name); err != nil {\n\t\t\treturn opts, err\n\t\t}\n\n\t\tswitch name {\n\t\tcase FullPCPUsOnlyOption:\n\t\t\toptValue, err := strconv.ParseBool(value)\n\t\t\tif err != nil {\n\t\t\t\treturn opts, fmt.Errorf(\"bad value for option %q: %w\", name, err)\n\t\t\t}\n\t\t\topts.FullPhysicalCPUsOnly = optValue\n\t\tcase DistributeCPUsAcrossNUMAOption:\n\t\t\toptValue, err := strconv.ParseBool(value)\n\t\t\tif err != nil {\n\t\t\t\treturn opts, fmt.Errorf(\"bad value for option %q: %w\", name, err)\n\t\t\t}\n\t\t\topts.DistributeCPUsAcrossNUMA = optValue\n\t\tcase AlignBySocketOption:\n\t\t\toptValue, err := strconv.ParseBool(value)\n\t\t\tif err != nil {\n\t\t\t\treturn opts, fmt.Errorf(\"bad value for option %q: %w\", name, err)\n\t\t\t}\n\t\t\topts.AlignBySocket = optValue\n\t\tdefault:\n\t\t\t// this should never be reached, we already detect unknown options,\n\t\t\t// but we keep it as further safety.\n\t\t\treturn opts, fmt.Errorf(\"unsupported cpumanager option: %q (%s)\", name, value)\n\t\t}\n\t}\n\treturn opts, nil\n}","line":{"from":85,"to":119}} {"id":100005752,"name":"ValidateStaticPolicyOptions","signature":"func ValidateStaticPolicyOptions(opts StaticPolicyOptions, topology *topology.CPUTopology, topologyManager topologymanager.Store) error","file":"pkg/kubelet/cm/cpumanager/policy_options.go","code":"// ValidateStaticPolicyOptions ensures that the requested policy options are compatible with the machine on which the CPUManager is running.\nfunc ValidateStaticPolicyOptions(opts StaticPolicyOptions, topology *topology.CPUTopology, topologyManager topologymanager.Store) error {\n\tif opts.AlignBySocket {\n\t\t// Not compatible with topology manager single-numa-node policy option.\n\t\tif topologyManager.GetPolicy().Name() == topologymanager.PolicySingleNumaNode {\n\t\t\treturn fmt.Errorf(\"Topolgy manager %s policy is incompatible with CPUManager %s policy option\", topologymanager.PolicySingleNumaNode, AlignBySocketOption)\n\t\t}\n\t\t// Not compatible with topology when number of sockets are more than number of NUMA nodes.\n\t\tif topology.NumSockets \u003e topology.NumNUMANodes {\n\t\t\treturn fmt.Errorf(\"Align by socket is not compatible with hardware where number of sockets are more than number of NUMA\")\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":121,"to":134}} {"id":100005753,"name":"Error","signature":"func (e SMTAlignmentError) Error() string","file":"pkg/kubelet/cm/cpumanager/policy_static.go","code":"func (e SMTAlignmentError) Error() string {\n\tif e.AvailablePhysicalCPUs \u003e 0 {\n\t\treturn fmt.Sprintf(\"SMT Alignment Error: not enough free physical CPUs: available physical CPUs = %d, requested CPUs = %d, CPUs per core = %d\", e.AvailablePhysicalCPUs, e.RequestedCPUs, e.CpusPerCore)\n\t}\n\treturn fmt.Sprintf(\"SMT Alignment Error: requested %d cpus not multiple cpus per core = %d\", e.RequestedCPUs, e.CpusPerCore)\n}","line":{"from":53,"to":58}} {"id":100005754,"name":"Type","signature":"func (e SMTAlignmentError) Type() string","file":"pkg/kubelet/cm/cpumanager/policy_static.go","code":"// Type returns human-readable type of this error. Used in the admission control to populate Admission Failure reason.\nfunc (e SMTAlignmentError) Type() string {\n\treturn ErrorSMTAlignment\n}","line":{"from":60,"to":63}} {"id":100005755,"name":"NewStaticPolicy","signature":"func NewStaticPolicy(topology *topology.CPUTopology, numReservedCPUs int, reservedCPUs cpuset.CPUSet, affinity topologymanager.Store, cpuPolicyOptions map[string]string) (Policy, error)","file":"pkg/kubelet/cm/cpumanager/policy_static.go","code":"// NewStaticPolicy returns a CPU manager policy that does not change CPU\n// assignments for exclusively pinned guaranteed containers after the main\n// container process starts.\nfunc NewStaticPolicy(topology *topology.CPUTopology, numReservedCPUs int, reservedCPUs cpuset.CPUSet, affinity topologymanager.Store, cpuPolicyOptions map[string]string) (Policy, error) {\n\topts, err := NewStaticPolicyOptions(cpuPolicyOptions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = ValidateStaticPolicyOptions(opts, topology, affinity)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tklog.InfoS(\"Static policy created with configuration\", \"options\", opts)\n\n\tpolicy := \u0026staticPolicy{\n\t\ttopology: topology,\n\t\taffinity: affinity,\n\t\tcpusToReuse: make(map[string]cpuset.CPUSet),\n\t\toptions: opts,\n\t}\n\n\tallCPUs := topology.CPUDetails.CPUs()\n\tvar reserved cpuset.CPUSet\n\tif reservedCPUs.Size() \u003e 0 {\n\t\treserved = reservedCPUs\n\t} else {\n\t\t// takeByTopology allocates CPUs associated with low-numbered cores from\n\t\t// allCPUs.\n\t\t//\n\t\t// For example: Given a system with 8 CPUs available and HT enabled,\n\t\t// if numReservedCPUs=2, then reserved={0,4}\n\t\treserved, _ = policy.takeByTopology(allCPUs, numReservedCPUs)\n\t}\n\n\tif reserved.Size() != numReservedCPUs {\n\t\terr := fmt.Errorf(\"[cpumanager] unable to reserve the required amount of CPUs (size of %s did not equal %d)\", reserved, numReservedCPUs)\n\t\treturn nil, err\n\t}\n\n\tvar reservedPhysicalCPUs cpuset.CPUSet\n\tfor _, cpu := range reserved.UnsortedList() {\n\t\tcore, err := topology.CPUCoreID(cpu)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"[cpumanager] unable to build the reserved physical CPUs from the reserved set: %w\", err)\n\t\t}\n\t\treservedPhysicalCPUs = reservedPhysicalCPUs.Union(topology.CPUDetails.CPUsInCores(core))\n\t}\n\n\tklog.InfoS(\"Reserved CPUs not available for exclusive assignment\", \"reservedSize\", reserved.Size(), \"reserved\", reserved, \"reservedPhysicalCPUs\", reservedPhysicalCPUs)\n\tpolicy.reservedCPUs = reserved\n\tpolicy.reservedPhysicalCPUs = reservedPhysicalCPUs\n\n\treturn policy, nil\n}","line":{"from":125,"to":179}} {"id":100005756,"name":"Name","signature":"func (p *staticPolicy) Name() string","file":"pkg/kubelet/cm/cpumanager/policy_static.go","code":"func (p *staticPolicy) Name() string {\n\treturn string(PolicyStatic)\n}","line":{"from":181,"to":183}} {"id":100005757,"name":"Start","signature":"func (p *staticPolicy) Start(s state.State) error","file":"pkg/kubelet/cm/cpumanager/policy_static.go","code":"func (p *staticPolicy) Start(s state.State) error {\n\tif err := p.validateState(s); err != nil {\n\t\tklog.ErrorS(err, \"Static policy invalid state, please drain node and remove policy state file\")\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":185,"to":191}} {"id":100005758,"name":"validateState","signature":"func (p *staticPolicy) validateState(s state.State) error","file":"pkg/kubelet/cm/cpumanager/policy_static.go","code":"func (p *staticPolicy) validateState(s state.State) error {\n\ttmpAssignments := s.GetCPUAssignments()\n\ttmpDefaultCPUset := s.GetDefaultCPUSet()\n\n\t// Default cpuset cannot be empty when assignments exist\n\tif tmpDefaultCPUset.IsEmpty() {\n\t\tif len(tmpAssignments) != 0 {\n\t\t\treturn fmt.Errorf(\"default cpuset cannot be empty\")\n\t\t}\n\t\t// state is empty initialize\n\t\tallCPUs := p.topology.CPUDetails.CPUs()\n\t\ts.SetDefaultCPUSet(allCPUs)\n\t\treturn nil\n\t}\n\n\t// State has already been initialized from file (is not empty)\n\t// 1. Check if the reserved cpuset is not part of default cpuset because:\n\t// - kube/system reserved have changed (increased) - may lead to some containers not being able to start\n\t// - user tampered with file\n\tif !p.reservedCPUs.Intersection(tmpDefaultCPUset).Equals(p.reservedCPUs) {\n\t\treturn fmt.Errorf(\"not all reserved cpus: \\\"%s\\\" are present in defaultCpuSet: \\\"%s\\\"\",\n\t\t\tp.reservedCPUs.String(), tmpDefaultCPUset.String())\n\t}\n\n\t// 2. Check if state for static policy is consistent\n\tfor pod := range tmpAssignments {\n\t\tfor container, cset := range tmpAssignments[pod] {\n\t\t\t// None of the cpu in DEFAULT cset should be in s.assignments\n\t\t\tif !tmpDefaultCPUset.Intersection(cset).IsEmpty() {\n\t\t\t\treturn fmt.Errorf(\"pod: %s, container: %s cpuset: \\\"%s\\\" overlaps with default cpuset \\\"%s\\\"\",\n\t\t\t\t\tpod, container, cset.String(), tmpDefaultCPUset.String())\n\t\t\t}\n\t\t}\n\t}\n\n\t// 3. It's possible that the set of available CPUs has changed since\n\t// the state was written. This can be due to for example\n\t// offlining a CPU when kubelet is not running. If this happens,\n\t// CPU manager will run into trouble when later it tries to\n\t// assign non-existent CPUs to containers. Validate that the\n\t// topology that was received during CPU manager startup matches with\n\t// the set of CPUs stored in the state.\n\ttotalKnownCPUs := tmpDefaultCPUset.Clone()\n\ttmpCPUSets := []cpuset.CPUSet{}\n\tfor pod := range tmpAssignments {\n\t\tfor _, cset := range tmpAssignments[pod] {\n\t\t\ttmpCPUSets = append(tmpCPUSets, cset)\n\t\t}\n\t}\n\ttotalKnownCPUs = totalKnownCPUs.Union(tmpCPUSets...)\n\tif !totalKnownCPUs.Equals(p.topology.CPUDetails.CPUs()) {\n\t\treturn fmt.Errorf(\"current set of available CPUs \\\"%s\\\" doesn't match with CPUs in state \\\"%s\\\"\",\n\t\t\tp.topology.CPUDetails.CPUs().String(), totalKnownCPUs.String())\n\t}\n\n\treturn nil\n}","line":{"from":193,"to":249}} {"id":100005759,"name":"GetAllocatableCPUs","signature":"func (p *staticPolicy) GetAllocatableCPUs(s state.State) cpuset.CPUSet","file":"pkg/kubelet/cm/cpumanager/policy_static.go","code":"// GetAllocatableCPUs returns the total set of CPUs available for allocation.\nfunc (p *staticPolicy) GetAllocatableCPUs(s state.State) cpuset.CPUSet {\n\treturn p.topology.CPUDetails.CPUs().Difference(p.reservedCPUs)\n}","line":{"from":251,"to":254}} {"id":100005760,"name":"GetAvailableCPUs","signature":"func (p *staticPolicy) GetAvailableCPUs(s state.State) cpuset.CPUSet","file":"pkg/kubelet/cm/cpumanager/policy_static.go","code":"// GetAvailableCPUs returns the set of unassigned CPUs minus the reserved set.\nfunc (p *staticPolicy) GetAvailableCPUs(s state.State) cpuset.CPUSet {\n\treturn s.GetDefaultCPUSet().Difference(p.reservedCPUs)\n}","line":{"from":256,"to":259}} {"id":100005761,"name":"GetAvailablePhysicalCPUs","signature":"func (p *staticPolicy) GetAvailablePhysicalCPUs(s state.State) cpuset.CPUSet","file":"pkg/kubelet/cm/cpumanager/policy_static.go","code":"func (p *staticPolicy) GetAvailablePhysicalCPUs(s state.State) cpuset.CPUSet {\n\treturn s.GetDefaultCPUSet().Difference(p.reservedPhysicalCPUs)\n}","line":{"from":261,"to":263}} {"id":100005762,"name":"updateCPUsToReuse","signature":"func (p *staticPolicy) updateCPUsToReuse(pod *v1.Pod, container *v1.Container, cset cpuset.CPUSet)","file":"pkg/kubelet/cm/cpumanager/policy_static.go","code":"func (p *staticPolicy) updateCPUsToReuse(pod *v1.Pod, container *v1.Container, cset cpuset.CPUSet) {\n\t// If pod entries to m.cpusToReuse other than the current pod exist, delete them.\n\tfor podUID := range p.cpusToReuse {\n\t\tif podUID != string(pod.UID) {\n\t\t\tdelete(p.cpusToReuse, podUID)\n\t\t}\n\t}\n\t// If no cpuset exists for cpusToReuse by this pod yet, create one.\n\tif _, ok := p.cpusToReuse[string(pod.UID)]; !ok {\n\t\tp.cpusToReuse[string(pod.UID)] = cpuset.New()\n\t}\n\t// Check if the container is an init container.\n\t// If so, add its cpuset to the cpuset of reusable CPUs for any new allocations.\n\tfor _, initContainer := range pod.Spec.InitContainers {\n\t\tif container.Name == initContainer.Name {\n\t\t\tp.cpusToReuse[string(pod.UID)] = p.cpusToReuse[string(pod.UID)].Union(cset)\n\t\t\treturn\n\t\t}\n\t}\n\t// Otherwise it is an app container.\n\t// Remove its cpuset from the cpuset of reusable CPUs for any new allocations.\n\tp.cpusToReuse[string(pod.UID)] = p.cpusToReuse[string(pod.UID)].Difference(cset)\n}","line":{"from":265,"to":287}} {"id":100005763,"name":"Allocate","signature":"func (p *staticPolicy) Allocate(s state.State, pod *v1.Pod, container *v1.Container) (rerr error)","file":"pkg/kubelet/cm/cpumanager/policy_static.go","code":"func (p *staticPolicy) Allocate(s state.State, pod *v1.Pod, container *v1.Container) (rerr error) {\n\tnumCPUs := p.guaranteedCPUs(pod, container)\n\tif numCPUs == 0 {\n\t\t// container belongs in the shared pool (nothing to do; use default cpuset)\n\t\treturn nil\n\t}\n\n\tklog.InfoS(\"Static policy: Allocate\", \"pod\", klog.KObj(pod), \"containerName\", container.Name)\n\t// container belongs in an exclusively allocated pool\n\tmetrics.CPUManagerPinningRequestsTotal.Inc()\n\tdefer func() {\n\t\tif rerr != nil {\n\t\t\tmetrics.CPUManagerPinningErrorsTotal.Inc()\n\t\t}\n\t}()\n\n\tif p.options.FullPhysicalCPUsOnly {\n\t\tCPUsPerCore := p.topology.CPUsPerCore()\n\t\tif (numCPUs % CPUsPerCore) != 0 {\n\t\t\t// Since CPU Manager has been enabled requesting strict SMT alignment, it means a guaranteed pod can only be admitted\n\t\t\t// if the CPU requested is a multiple of the number of virtual cpus per physical cores.\n\t\t\t// In case CPU request is not a multiple of the number of virtual cpus per physical cores the Pod will be put\n\t\t\t// in Failed state, with SMTAlignmentError as reason. Since the allocation happens in terms of physical cores\n\t\t\t// and the scheduler is responsible for ensuring that the workload goes to a node that has enough CPUs,\n\t\t\t// the pod would be placed on a node where there are enough physical cores available to be allocated.\n\t\t\t// Just like the behaviour in case of static policy, takeByTopology will try to first allocate CPUs from the same socket\n\t\t\t// and only in case the request cannot be sattisfied on a single socket, CPU allocation is done for a workload to occupy all\n\t\t\t// CPUs on a physical core. Allocation of individual threads would never have to occur.\n\t\t\treturn SMTAlignmentError{\n\t\t\t\tRequestedCPUs: numCPUs,\n\t\t\t\tCpusPerCore: CPUsPerCore,\n\t\t\t}\n\t\t}\n\n\t\tavailablePhysicalCPUs := p.GetAvailablePhysicalCPUs(s).Size()\n\n\t\t// It's legal to reserve CPUs which are not core siblings. In this case the CPU allocator can descend to single cores\n\t\t// when picking CPUs. This will void the guarantee of FullPhysicalCPUsOnly. To prevent this, we need to additionally consider\n\t\t// all the core siblings of the reserved CPUs as unavailable when computing the free CPUs, before to start the actual allocation.\n\t\t// This way, by construction all possible CPUs allocation whose number is multiple of the SMT level are now correct again.\n\t\tif numCPUs \u003e availablePhysicalCPUs {\n\t\t\treturn SMTAlignmentError{\n\t\t\t\tRequestedCPUs: numCPUs,\n\t\t\t\tCpusPerCore: CPUsPerCore,\n\t\t\t\tAvailablePhysicalCPUs: availablePhysicalCPUs,\n\t\t\t}\n\t\t}\n\t}\n\tif cpuset, ok := s.GetCPUSet(string(pod.UID), container.Name); ok {\n\t\tp.updateCPUsToReuse(pod, container, cpuset)\n\t\tklog.InfoS(\"Static policy: container already present in state, skipping\", \"pod\", klog.KObj(pod), \"containerName\", container.Name)\n\t\treturn nil\n\t}\n\n\t// Call Topology Manager to get the aligned socket affinity across all hint providers.\n\thint := p.affinity.GetAffinity(string(pod.UID), container.Name)\n\tklog.InfoS(\"Topology Affinity\", \"pod\", klog.KObj(pod), \"containerName\", container.Name, \"affinity\", hint)\n\n\t// Allocate CPUs according to the NUMA affinity contained in the hint.\n\tcpuset, err := p.allocateCPUs(s, numCPUs, hint.NUMANodeAffinity, p.cpusToReuse[string(pod.UID)])\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Unable to allocate CPUs\", \"pod\", klog.KObj(pod), \"containerName\", container.Name, \"numCPUs\", numCPUs)\n\t\treturn err\n\t}\n\ts.SetCPUSet(string(pod.UID), container.Name, cpuset)\n\tp.updateCPUsToReuse(pod, container, cpuset)\n\n\treturn nil\n}","line":{"from":289,"to":357}} {"id":100005764,"name":"getAssignedCPUsOfSiblings","signature":"func getAssignedCPUsOfSiblings(s state.State, podUID string, containerName string) cpuset.CPUSet","file":"pkg/kubelet/cm/cpumanager/policy_static.go","code":"// getAssignedCPUsOfSiblings returns assigned cpus of given container's siblings(all containers other than the given container) in the given pod `podUID`.\nfunc getAssignedCPUsOfSiblings(s state.State, podUID string, containerName string) cpuset.CPUSet {\n\tassignments := s.GetCPUAssignments()\n\tcset := cpuset.New()\n\tfor name, cpus := range assignments[podUID] {\n\t\tif containerName == name {\n\t\t\tcontinue\n\t\t}\n\t\tcset = cset.Union(cpus)\n\t}\n\treturn cset\n}","line":{"from":359,"to":370}} {"id":100005765,"name":"RemoveContainer","signature":"func (p *staticPolicy) RemoveContainer(s state.State, podUID string, containerName string) error","file":"pkg/kubelet/cm/cpumanager/policy_static.go","code":"func (p *staticPolicy) RemoveContainer(s state.State, podUID string, containerName string) error {\n\tklog.InfoS(\"Static policy: RemoveContainer\", \"podUID\", podUID, \"containerName\", containerName)\n\tcpusInUse := getAssignedCPUsOfSiblings(s, podUID, containerName)\n\tif toRelease, ok := s.GetCPUSet(podUID, containerName); ok {\n\t\ts.Delete(podUID, containerName)\n\t\t// Mutate the shared pool, adding released cpus.\n\t\ttoRelease = toRelease.Difference(cpusInUse)\n\t\ts.SetDefaultCPUSet(s.GetDefaultCPUSet().Union(toRelease))\n\t}\n\treturn nil\n}","line":{"from":372,"to":382}} {"id":100005766,"name":"allocateCPUs","signature":"func (p *staticPolicy) allocateCPUs(s state.State, numCPUs int, numaAffinity bitmask.BitMask, reusableCPUs cpuset.CPUSet) (cpuset.CPUSet, error)","file":"pkg/kubelet/cm/cpumanager/policy_static.go","code":"func (p *staticPolicy) allocateCPUs(s state.State, numCPUs int, numaAffinity bitmask.BitMask, reusableCPUs cpuset.CPUSet) (cpuset.CPUSet, error) {\n\tklog.InfoS(\"AllocateCPUs\", \"numCPUs\", numCPUs, \"socket\", numaAffinity)\n\n\tallocatableCPUs := p.GetAvailableCPUs(s).Union(reusableCPUs)\n\n\t// If there are aligned CPUs in numaAffinity, attempt to take those first.\n\tresult := cpuset.New()\n\tif numaAffinity != nil {\n\t\talignedCPUs := p.getAlignedCPUs(numaAffinity, allocatableCPUs)\n\n\t\tnumAlignedToAlloc := alignedCPUs.Size()\n\t\tif numCPUs \u003c numAlignedToAlloc {\n\t\t\tnumAlignedToAlloc = numCPUs\n\t\t}\n\n\t\talignedCPUs, err := p.takeByTopology(alignedCPUs, numAlignedToAlloc)\n\t\tif err != nil {\n\t\t\treturn cpuset.New(), err\n\t\t}\n\n\t\tresult = result.Union(alignedCPUs)\n\t}\n\n\t// Get any remaining CPUs from what's leftover after attempting to grab aligned ones.\n\tremainingCPUs, err := p.takeByTopology(allocatableCPUs.Difference(result), numCPUs-result.Size())\n\tif err != nil {\n\t\treturn cpuset.New(), err\n\t}\n\tresult = result.Union(remainingCPUs)\n\n\t// Remove allocated CPUs from the shared CPUSet.\n\ts.SetDefaultCPUSet(s.GetDefaultCPUSet().Difference(result))\n\n\tklog.InfoS(\"AllocateCPUs\", \"result\", result)\n\treturn result, nil\n}","line":{"from":384,"to":419}} {"id":100005767,"name":"guaranteedCPUs","signature":"func (p *staticPolicy) guaranteedCPUs(pod *v1.Pod, container *v1.Container) int","file":"pkg/kubelet/cm/cpumanager/policy_static.go","code":"func (p *staticPolicy) guaranteedCPUs(pod *v1.Pod, container *v1.Container) int {\n\tif v1qos.GetPodQOS(pod) != v1.PodQOSGuaranteed {\n\t\treturn 0\n\t}\n\tcpuQuantity := container.Resources.Requests[v1.ResourceCPU]\n\t// In-place pod resize feature makes Container.Resources field mutable for CPU \u0026 memory.\n\t// AllocatedResources holds the value of Container.Resources.Requests when the pod was admitted.\n\t// We should return this value because this is what kubelet agreed to allocate for the container\n\t// and the value configured with runtime.\n\tif utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) {\n\t\tif cs, ok := podutil.GetContainerStatus(pod.Status.ContainerStatuses, container.Name); ok {\n\t\t\tcpuQuantity = cs.AllocatedResources[v1.ResourceCPU]\n\t\t}\n\t}\n\tif cpuQuantity.Value()*1000 != cpuQuantity.MilliValue() {\n\t\treturn 0\n\t}\n\t// Safe downcast to do for all systems with \u003c 2.1 billion CPUs.\n\t// Per the language spec, `int` is guaranteed to be at least 32 bits wide.\n\t// https://golang.org/ref/spec#Numeric_types\n\treturn int(cpuQuantity.Value())\n}","line":{"from":421,"to":442}} {"id":100005768,"name":"podGuaranteedCPUs","signature":"func (p *staticPolicy) podGuaranteedCPUs(pod *v1.Pod) int","file":"pkg/kubelet/cm/cpumanager/policy_static.go","code":"func (p *staticPolicy) podGuaranteedCPUs(pod *v1.Pod) int {\n\t// The maximum of requested CPUs by init containers.\n\trequestedByInitContainers := 0\n\tfor _, container := range pod.Spec.InitContainers {\n\t\tif _, ok := container.Resources.Requests[v1.ResourceCPU]; !ok {\n\t\t\tcontinue\n\t\t}\n\t\trequestedCPU := p.guaranteedCPUs(pod, \u0026container)\n\t\tif requestedCPU \u003e requestedByInitContainers {\n\t\t\trequestedByInitContainers = requestedCPU\n\t\t}\n\t}\n\t// The sum of requested CPUs by app containers.\n\trequestedByAppContainers := 0\n\tfor _, container := range pod.Spec.Containers {\n\t\tif _, ok := container.Resources.Requests[v1.ResourceCPU]; !ok {\n\t\t\tcontinue\n\t\t}\n\t\trequestedByAppContainers += p.guaranteedCPUs(pod, \u0026container)\n\t}\n\n\tif requestedByInitContainers \u003e requestedByAppContainers {\n\t\treturn requestedByInitContainers\n\t}\n\treturn requestedByAppContainers\n}","line":{"from":444,"to":469}} {"id":100005769,"name":"takeByTopology","signature":"func (p *staticPolicy) takeByTopology(availableCPUs cpuset.CPUSet, numCPUs int) (cpuset.CPUSet, error)","file":"pkg/kubelet/cm/cpumanager/policy_static.go","code":"func (p *staticPolicy) takeByTopology(availableCPUs cpuset.CPUSet, numCPUs int) (cpuset.CPUSet, error) {\n\tif p.options.DistributeCPUsAcrossNUMA {\n\t\tcpuGroupSize := 1\n\t\tif p.options.FullPhysicalCPUsOnly {\n\t\t\tcpuGroupSize = p.topology.CPUsPerCore()\n\t\t}\n\t\treturn takeByTopologyNUMADistributed(p.topology, availableCPUs, numCPUs, cpuGroupSize)\n\t}\n\treturn takeByTopologyNUMAPacked(p.topology, availableCPUs, numCPUs)\n}","line":{"from":471,"to":480}} {"id":100005770,"name":"GetTopologyHints","signature":"func (p *staticPolicy) GetTopologyHints(s state.State, pod *v1.Pod, container *v1.Container) map[string][]topologymanager.TopologyHint","file":"pkg/kubelet/cm/cpumanager/policy_static.go","code":"func (p *staticPolicy) GetTopologyHints(s state.State, pod *v1.Pod, container *v1.Container) map[string][]topologymanager.TopologyHint {\n\t// Get a count of how many guaranteed CPUs have been requested.\n\trequested := p.guaranteedCPUs(pod, container)\n\n\t// Number of required CPUs is not an integer or a container is not part of the Guaranteed QoS class.\n\t// It will be treated by the TopologyManager as having no preference and cause it to ignore this\n\t// resource when considering pod alignment.\n\t// In terms of hints, this is equal to: TopologyHints[NUMANodeAffinity: nil, Preferred: true].\n\tif requested == 0 {\n\t\treturn nil\n\t}\n\n\t// Short circuit to regenerate the same hints if there are already\n\t// guaranteed CPUs allocated to the Container. This might happen after a\n\t// kubelet restart, for example.\n\tif allocated, exists := s.GetCPUSet(string(pod.UID), container.Name); exists {\n\t\tif allocated.Size() != requested {\n\t\t\tklog.ErrorS(nil, \"CPUs already allocated to container with different number than request\", \"pod\", klog.KObj(pod), \"containerName\", container.Name, \"requestedSize\", requested, \"allocatedSize\", allocated.Size())\n\t\t\t// An empty list of hints will be treated as a preference that cannot be satisfied.\n\t\t\t// In definition of hints this is equal to: TopologyHint[NUMANodeAffinity: nil, Preferred: false].\n\t\t\t// For all but the best-effort policy, the Topology Manager will throw a pod-admission error.\n\t\t\treturn map[string][]topologymanager.TopologyHint{\n\t\t\t\tstring(v1.ResourceCPU): {},\n\t\t\t}\n\t\t}\n\t\tklog.InfoS(\"Regenerating TopologyHints for CPUs already allocated\", \"pod\", klog.KObj(pod), \"containerName\", container.Name)\n\t\treturn map[string][]topologymanager.TopologyHint{\n\t\t\tstring(v1.ResourceCPU): p.generateCPUTopologyHints(allocated, cpuset.CPUSet{}, requested),\n\t\t}\n\t}\n\n\t// Get a list of available CPUs.\n\tavailable := p.GetAvailableCPUs(s)\n\n\t// Get a list of reusable CPUs (e.g. CPUs reused from initContainers).\n\t// It should be an empty CPUSet for a newly created pod.\n\treusable := p.cpusToReuse[string(pod.UID)]\n\n\t// Generate hints.\n\tcpuHints := p.generateCPUTopologyHints(available, reusable, requested)\n\tklog.InfoS(\"TopologyHints generated\", \"pod\", klog.KObj(pod), \"containerName\", container.Name, \"cpuHints\", cpuHints)\n\n\treturn map[string][]topologymanager.TopologyHint{\n\t\tstring(v1.ResourceCPU): cpuHints,\n\t}\n}","line":{"from":482,"to":527}} {"id":100005771,"name":"GetPodTopologyHints","signature":"func (p *staticPolicy) GetPodTopologyHints(s state.State, pod *v1.Pod) map[string][]topologymanager.TopologyHint","file":"pkg/kubelet/cm/cpumanager/policy_static.go","code":"func (p *staticPolicy) GetPodTopologyHints(s state.State, pod *v1.Pod) map[string][]topologymanager.TopologyHint {\n\t// Get a count of how many guaranteed CPUs have been requested by Pod.\n\trequested := p.podGuaranteedCPUs(pod)\n\n\t// Number of required CPUs is not an integer or a pod is not part of the Guaranteed QoS class.\n\t// It will be treated by the TopologyManager as having no preference and cause it to ignore this\n\t// resource when considering pod alignment.\n\t// In terms of hints, this is equal to: TopologyHints[NUMANodeAffinity: nil, Preferred: true].\n\tif requested == 0 {\n\t\treturn nil\n\t}\n\n\tassignedCPUs := cpuset.New()\n\tfor _, container := range append(pod.Spec.InitContainers, pod.Spec.Containers...) {\n\t\trequestedByContainer := p.guaranteedCPUs(pod, \u0026container)\n\t\t// Short circuit to regenerate the same hints if there are already\n\t\t// guaranteed CPUs allocated to the Container. This might happen after a\n\t\t// kubelet restart, for example.\n\t\tif allocated, exists := s.GetCPUSet(string(pod.UID), container.Name); exists {\n\t\t\tif allocated.Size() != requestedByContainer {\n\t\t\t\tklog.ErrorS(nil, \"CPUs already allocated to container with different number than request\", \"pod\", klog.KObj(pod), \"containerName\", container.Name, \"allocatedSize\", requested, \"requestedByContainer\", requestedByContainer, \"allocatedSize\", allocated.Size())\n\t\t\t\t// An empty list of hints will be treated as a preference that cannot be satisfied.\n\t\t\t\t// In definition of hints this is equal to: TopologyHint[NUMANodeAffinity: nil, Preferred: false].\n\t\t\t\t// For all but the best-effort policy, the Topology Manager will throw a pod-admission error.\n\t\t\t\treturn map[string][]topologymanager.TopologyHint{\n\t\t\t\t\tstring(v1.ResourceCPU): {},\n\t\t\t\t}\n\t\t\t}\n\t\t\t// A set of CPUs already assigned to containers in this pod\n\t\t\tassignedCPUs = assignedCPUs.Union(allocated)\n\t\t}\n\t}\n\tif assignedCPUs.Size() == requested {\n\t\tklog.InfoS(\"Regenerating TopologyHints for CPUs already allocated\", \"pod\", klog.KObj(pod))\n\t\treturn map[string][]topologymanager.TopologyHint{\n\t\t\tstring(v1.ResourceCPU): p.generateCPUTopologyHints(assignedCPUs, cpuset.CPUSet{}, requested),\n\t\t}\n\t}\n\n\t// Get a list of available CPUs.\n\tavailable := p.GetAvailableCPUs(s)\n\n\t// Get a list of reusable CPUs (e.g. CPUs reused from initContainers).\n\t// It should be an empty CPUSet for a newly created pod.\n\treusable := p.cpusToReuse[string(pod.UID)]\n\n\t// Ensure any CPUs already assigned to containers in this pod are included as part of the hint generation.\n\treusable = reusable.Union(assignedCPUs)\n\n\t// Generate hints.\n\tcpuHints := p.generateCPUTopologyHints(available, reusable, requested)\n\tklog.InfoS(\"TopologyHints generated\", \"pod\", klog.KObj(pod), \"cpuHints\", cpuHints)\n\n\treturn map[string][]topologymanager.TopologyHint{\n\t\tstring(v1.ResourceCPU): cpuHints,\n\t}\n}","line":{"from":529,"to":585}} {"id":100005772,"name":"generateCPUTopologyHints","signature":"func (p *staticPolicy) generateCPUTopologyHints(availableCPUs cpuset.CPUSet, reusableCPUs cpuset.CPUSet, request int) []topologymanager.TopologyHint","file":"pkg/kubelet/cm/cpumanager/policy_static.go","code":"// generateCPUtopologyHints generates a set of TopologyHints given the set of\n// available CPUs and the number of CPUs being requested.\n//\n// It follows the convention of marking all hints that have the same number of\n// bits set as the narrowest matching NUMANodeAffinity with 'Preferred: true', and\n// marking all others with 'Preferred: false'.\nfunc (p *staticPolicy) generateCPUTopologyHints(availableCPUs cpuset.CPUSet, reusableCPUs cpuset.CPUSet, request int) []topologymanager.TopologyHint {\n\t// Initialize minAffinitySize to include all NUMA Nodes.\n\tminAffinitySize := p.topology.CPUDetails.NUMANodes().Size()\n\n\t// Iterate through all combinations of numa nodes bitmask and build hints from them.\n\thints := []topologymanager.TopologyHint{}\n\tbitmask.IterateBitMasks(p.topology.CPUDetails.NUMANodes().List(), func(mask bitmask.BitMask) {\n\t\t// First, update minAffinitySize for the current request size.\n\t\tcpusInMask := p.topology.CPUDetails.CPUsInNUMANodes(mask.GetBits()...).Size()\n\t\tif cpusInMask \u003e= request \u0026\u0026 mask.Count() \u003c minAffinitySize {\n\t\t\tminAffinitySize = mask.Count()\n\t\t}\n\n\t\t// Then check to see if we have enough CPUs available on the current\n\t\t// numa node bitmask to satisfy the CPU request.\n\t\tnumMatching := 0\n\t\tfor _, c := range reusableCPUs.List() {\n\t\t\t// Disregard this mask if its NUMANode isn't part of it.\n\t\t\tif !mask.IsSet(p.topology.CPUDetails[c].NUMANodeID) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tnumMatching++\n\t\t}\n\n\t\t// Finally, check to see if enough available CPUs remain on the current\n\t\t// NUMA node combination to satisfy the CPU request.\n\t\tfor _, c := range availableCPUs.List() {\n\t\t\tif mask.IsSet(p.topology.CPUDetails[c].NUMANodeID) {\n\t\t\t\tnumMatching++\n\t\t\t}\n\t\t}\n\n\t\t// If they don't, then move onto the next combination.\n\t\tif numMatching \u003c request {\n\t\t\treturn\n\t\t}\n\n\t\t// Otherwise, create a new hint from the numa node bitmask and add it to the\n\t\t// list of hints. We set all hint preferences to 'false' on the first\n\t\t// pass through.\n\t\thints = append(hints, topologymanager.TopologyHint{\n\t\t\tNUMANodeAffinity: mask,\n\t\t\tPreferred: false,\n\t\t})\n\t})\n\n\t// Loop back through all hints and update the 'Preferred' field based on\n\t// counting the number of bits sets in the affinity mask and comparing it\n\t// to the minAffinitySize. Only those with an equal number of bits set (and\n\t// with a minimal set of numa nodes) will be considered preferred.\n\tfor i := range hints {\n\t\tif p.options.AlignBySocket \u0026\u0026 p.isHintSocketAligned(hints[i], minAffinitySize) {\n\t\t\thints[i].Preferred = true\n\t\t\tcontinue\n\t\t}\n\t\tif hints[i].NUMANodeAffinity.Count() == minAffinitySize {\n\t\t\thints[i].Preferred = true\n\t\t}\n\t}\n\n\treturn hints\n}","line":{"from":587,"to":654}} {"id":100005773,"name":"isHintSocketAligned","signature":"func (p *staticPolicy) isHintSocketAligned(hint topologymanager.TopologyHint, minAffinitySize int) bool","file":"pkg/kubelet/cm/cpumanager/policy_static.go","code":"// isHintSocketAligned function return true if numa nodes in hint are socket aligned.\nfunc (p *staticPolicy) isHintSocketAligned(hint topologymanager.TopologyHint, minAffinitySize int) bool {\n\tnumaNodesBitMask := hint.NUMANodeAffinity.GetBits()\n\tnumaNodesPerSocket := p.topology.NumNUMANodes / p.topology.NumSockets\n\tif numaNodesPerSocket == 0 {\n\t\treturn false\n\t}\n\t// minSockets refers to minimum number of socket required to satify allocation.\n\t// A hint is considered socket aligned if sockets across which numa nodes span is equal to minSockets\n\tminSockets := (minAffinitySize + numaNodesPerSocket - 1) / numaNodesPerSocket\n\treturn p.topology.CPUDetails.SocketsInNUMANodes(numaNodesBitMask...).Size() == minSockets\n}","line":{"from":656,"to":667}} {"id":100005774,"name":"getAlignedCPUs","signature":"func (p *staticPolicy) getAlignedCPUs(numaAffinity bitmask.BitMask, allocatableCPUs cpuset.CPUSet) cpuset.CPUSet","file":"pkg/kubelet/cm/cpumanager/policy_static.go","code":"// getAlignedCPUs return set of aligned CPUs based on numa affinity mask and configured policy options.\nfunc (p *staticPolicy) getAlignedCPUs(numaAffinity bitmask.BitMask, allocatableCPUs cpuset.CPUSet) cpuset.CPUSet {\n\talignedCPUs := cpuset.New()\n\tnumaBits := numaAffinity.GetBits()\n\n\t// If align-by-socket policy option is enabled, NUMA based hint is expanded to\n\t// socket aligned hint. It will ensure that first socket aligned available CPUs are\n\t// allocated before we try to find CPUs across socket to satisfy allocation request.\n\tif p.options.AlignBySocket {\n\t\tsocketBits := p.topology.CPUDetails.SocketsInNUMANodes(numaBits...).UnsortedList()\n\t\tfor _, socketID := range socketBits {\n\t\t\talignedCPUs = alignedCPUs.Union(allocatableCPUs.Intersection(p.topology.CPUDetails.CPUsInSockets(socketID)))\n\t\t}\n\t\treturn alignedCPUs\n\t}\n\n\tfor _, numaNodeID := range numaBits {\n\t\talignedCPUs = alignedCPUs.Union(allocatableCPUs.Intersection(p.topology.CPUDetails.CPUsInNUMANodes(numaNodeID)))\n\t}\n\n\treturn alignedCPUs\n}","line":{"from":669,"to":690}} {"id":100005775,"name":"NewCPUManagerCheckpoint","signature":"func NewCPUManagerCheckpoint() *CPUManagerCheckpoint","file":"pkg/kubelet/cm/cpumanager/state/checkpoint.go","code":"// NewCPUManagerCheckpoint returns an instance of Checkpoint\nfunc NewCPUManagerCheckpoint() *CPUManagerCheckpoint {\n\t//nolint:staticcheck // unexported-type-in-api user-facing error message\n\treturn newCPUManagerCheckpointV2()\n}","line":{"from":54,"to":58}} {"id":100005776,"name":"newCPUManagerCheckpointV1","signature":"func newCPUManagerCheckpointV1() *CPUManagerCheckpointV1","file":"pkg/kubelet/cm/cpumanager/state/checkpoint.go","code":"func newCPUManagerCheckpointV1() *CPUManagerCheckpointV1 {\n\treturn \u0026CPUManagerCheckpointV1{\n\t\tEntries: make(map[string]string),\n\t}\n}","line":{"from":60,"to":64}} {"id":100005777,"name":"newCPUManagerCheckpointV2","signature":"func newCPUManagerCheckpointV2() *CPUManagerCheckpointV2","file":"pkg/kubelet/cm/cpumanager/state/checkpoint.go","code":"func newCPUManagerCheckpointV2() *CPUManagerCheckpointV2 {\n\treturn \u0026CPUManagerCheckpointV2{\n\t\tEntries: make(map[string]map[string]string),\n\t}\n}","line":{"from":66,"to":70}} {"id":100005778,"name":"MarshalCheckpoint","signature":"func (cp *CPUManagerCheckpointV1) MarshalCheckpoint() ([]byte, error)","file":"pkg/kubelet/cm/cpumanager/state/checkpoint.go","code":"// MarshalCheckpoint returns marshalled checkpoint in v1 format\nfunc (cp *CPUManagerCheckpointV1) MarshalCheckpoint() ([]byte, error) {\n\t// make sure checksum wasn't set before so it doesn't affect output checksum\n\tcp.Checksum = 0\n\tcp.Checksum = checksum.New(cp)\n\treturn json.Marshal(*cp)\n}","line":{"from":72,"to":78}} {"id":100005779,"name":"MarshalCheckpoint","signature":"func (cp *CPUManagerCheckpointV2) MarshalCheckpoint() ([]byte, error)","file":"pkg/kubelet/cm/cpumanager/state/checkpoint.go","code":"// MarshalCheckpoint returns marshalled checkpoint in v2 format\nfunc (cp *CPUManagerCheckpointV2) MarshalCheckpoint() ([]byte, error) {\n\t// make sure checksum wasn't set before so it doesn't affect output checksum\n\tcp.Checksum = 0\n\tcp.Checksum = checksum.New(cp)\n\treturn json.Marshal(*cp)\n}","line":{"from":80,"to":86}} {"id":100005780,"name":"UnmarshalCheckpoint","signature":"func (cp *CPUManagerCheckpointV1) UnmarshalCheckpoint(blob []byte) error","file":"pkg/kubelet/cm/cpumanager/state/checkpoint.go","code":"// UnmarshalCheckpoint tries to unmarshal passed bytes to checkpoint in v1 format\nfunc (cp *CPUManagerCheckpointV1) UnmarshalCheckpoint(blob []byte) error {\n\treturn json.Unmarshal(blob, cp)\n}","line":{"from":88,"to":91}} {"id":100005781,"name":"UnmarshalCheckpoint","signature":"func (cp *CPUManagerCheckpointV2) UnmarshalCheckpoint(blob []byte) error","file":"pkg/kubelet/cm/cpumanager/state/checkpoint.go","code":"// UnmarshalCheckpoint tries to unmarshal passed bytes to checkpoint in v2 format\nfunc (cp *CPUManagerCheckpointV2) UnmarshalCheckpoint(blob []byte) error {\n\treturn json.Unmarshal(blob, cp)\n}","line":{"from":93,"to":96}} {"id":100005782,"name":"VerifyChecksum","signature":"func (cp *CPUManagerCheckpointV1) VerifyChecksum() error","file":"pkg/kubelet/cm/cpumanager/state/checkpoint.go","code":"// VerifyChecksum verifies that current checksum of checkpoint is valid in v1 format\nfunc (cp *CPUManagerCheckpointV1) VerifyChecksum() error {\n\tif cp.Checksum == 0 {\n\t\t// accept empty checksum for compatibility with old file backend\n\t\treturn nil\n\t}\n\n\tprinter := spew.ConfigState{\n\t\tIndent: \" \",\n\t\tSortKeys: true,\n\t\tDisableMethods: true,\n\t\tSpewKeys: true,\n\t}\n\n\tck := cp.Checksum\n\tcp.Checksum = 0\n\tobject := printer.Sprintf(\"%#v\", cp)\n\tobject = strings.Replace(object, \"CPUManagerCheckpointV1\", \"CPUManagerCheckpoint\", 1)\n\tcp.Checksum = ck\n\n\thash := fnv.New32a()\n\tprinter.Fprintf(hash, \"%v\", object)\n\tif cp.Checksum != checksum.Checksum(hash.Sum32()) {\n\t\treturn errors.ErrCorruptCheckpoint\n\t}\n\n\treturn nil\n}","line":{"from":98,"to":125}} {"id":100005783,"name":"VerifyChecksum","signature":"func (cp *CPUManagerCheckpointV2) VerifyChecksum() error","file":"pkg/kubelet/cm/cpumanager/state/checkpoint.go","code":"// VerifyChecksum verifies that current checksum of checkpoint is valid in v2 format\nfunc (cp *CPUManagerCheckpointV2) VerifyChecksum() error {\n\tif cp.Checksum == 0 {\n\t\t// accept empty checksum for compatibility with old file backend\n\t\treturn nil\n\t}\n\tck := cp.Checksum\n\tcp.Checksum = 0\n\terr := ck.Verify(cp)\n\tcp.Checksum = ck\n\treturn err\n}","line":{"from":127,"to":138}} {"id":100005784,"name":"Clone","signature":"func (as ContainerCPUAssignments) Clone() ContainerCPUAssignments","file":"pkg/kubelet/cm/cpumanager/state/state.go","code":"// Clone returns a copy of ContainerCPUAssignments\nfunc (as ContainerCPUAssignments) Clone() ContainerCPUAssignments {\n\tret := make(ContainerCPUAssignments)\n\tfor pod := range as {\n\t\tret[pod] = make(map[string]cpuset.CPUSet)\n\t\tfor container, cset := range as[pod] {\n\t\t\tret[pod][container] = cset\n\t\t}\n\t}\n\treturn ret\n}","line":{"from":26,"to":36}} {"id":100005785,"name":"NewCheckpointState","signature":"func NewCheckpointState(stateDir, checkpointName, policyName string, initialContainers containermap.ContainerMap) (State, error)","file":"pkg/kubelet/cm/cpumanager/state/state_checkpoint.go","code":"// NewCheckpointState creates new State for keeping track of cpu/pod assignment with checkpoint backend\nfunc NewCheckpointState(stateDir, checkpointName, policyName string, initialContainers containermap.ContainerMap) (State, error) {\n\tcheckpointManager, err := checkpointmanager.NewCheckpointManager(stateDir)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize checkpoint manager: %v\", err)\n\t}\n\tstateCheckpoint := \u0026stateCheckpoint{\n\t\tcache: NewMemoryState(),\n\t\tpolicyName: policyName,\n\t\tcheckpointManager: checkpointManager,\n\t\tcheckpointName: checkpointName,\n\t\tinitialContainers: initialContainers,\n\t}\n\n\tif err := stateCheckpoint.restoreState(); err != nil {\n\t\t//nolint:staticcheck // ST1005 user-facing error message\n\t\treturn nil, fmt.Errorf(\"could not restore state from checkpoint: %v, please drain this node and delete the CPU manager checkpoint file %q before restarting Kubelet\",\n\t\t\terr, filepath.Join(stateDir, checkpointName))\n\t}\n\n\treturn stateCheckpoint, nil\n}","line":{"from":42,"to":63}} {"id":100005786,"name":"migrateV1CheckpointToV2Checkpoint","signature":"func (sc *stateCheckpoint) migrateV1CheckpointToV2Checkpoint(src *CPUManagerCheckpointV1, dst *CPUManagerCheckpointV2) error","file":"pkg/kubelet/cm/cpumanager/state/state_checkpoint.go","code":"// migrateV1CheckpointToV2Checkpoint() converts checkpoints from the v1 format to the v2 format\nfunc (sc *stateCheckpoint) migrateV1CheckpointToV2Checkpoint(src *CPUManagerCheckpointV1, dst *CPUManagerCheckpointV2) error {\n\tif src.PolicyName != \"\" {\n\t\tdst.PolicyName = src.PolicyName\n\t}\n\tif src.DefaultCPUSet != \"\" {\n\t\tdst.DefaultCPUSet = src.DefaultCPUSet\n\t}\n\tfor containerID, cset := range src.Entries {\n\t\tpodUID, containerName, err := sc.initialContainers.GetContainerRef(containerID)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"containerID '%v' not found in initial containers list\", containerID)\n\t\t}\n\t\tif dst.Entries == nil {\n\t\t\tdst.Entries = make(map[string]map[string]string)\n\t\t}\n\t\tif _, exists := dst.Entries[podUID]; !exists {\n\t\t\tdst.Entries[podUID] = make(map[string]string)\n\t\t}\n\t\tdst.Entries[podUID][containerName] = cset\n\t}\n\treturn nil\n}","line":{"from":65,"to":87}} {"id":100005787,"name":"restoreState","signature":"func (sc *stateCheckpoint) restoreState() error","file":"pkg/kubelet/cm/cpumanager/state/state_checkpoint.go","code":"// restores state from a checkpoint and creates it if it doesn't exist\nfunc (sc *stateCheckpoint) restoreState() error {\n\tsc.mux.Lock()\n\tdefer sc.mux.Unlock()\n\tvar err error\n\n\tcheckpointV1 := newCPUManagerCheckpointV1()\n\tcheckpointV2 := newCPUManagerCheckpointV2()\n\n\tif err = sc.checkpointManager.GetCheckpoint(sc.checkpointName, checkpointV1); err != nil {\n\t\tcheckpointV1 = \u0026CPUManagerCheckpointV1{} // reset it back to 0\n\t\tif err = sc.checkpointManager.GetCheckpoint(sc.checkpointName, checkpointV2); err != nil {\n\t\t\tif err == errors.ErrCheckpointNotFound {\n\t\t\t\treturn sc.storeState()\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err = sc.migrateV1CheckpointToV2Checkpoint(checkpointV1, checkpointV2); err != nil {\n\t\treturn fmt.Errorf(\"error migrating v1 checkpoint state to v2 checkpoint state: %s\", err)\n\t}\n\n\tif sc.policyName != checkpointV2.PolicyName {\n\t\treturn fmt.Errorf(\"configured policy %q differs from state checkpoint policy %q\", sc.policyName, checkpointV2.PolicyName)\n\t}\n\n\tvar tmpDefaultCPUSet cpuset.CPUSet\n\tif tmpDefaultCPUSet, err = cpuset.Parse(checkpointV2.DefaultCPUSet); err != nil {\n\t\treturn fmt.Errorf(\"could not parse default cpu set %q: %v\", checkpointV2.DefaultCPUSet, err)\n\t}\n\n\tvar tmpContainerCPUSet cpuset.CPUSet\n\ttmpAssignments := ContainerCPUAssignments{}\n\tfor pod := range checkpointV2.Entries {\n\t\ttmpAssignments[pod] = make(map[string]cpuset.CPUSet)\n\t\tfor container, cpuString := range checkpointV2.Entries[pod] {\n\t\t\tif tmpContainerCPUSet, err = cpuset.Parse(cpuString); err != nil {\n\t\t\t\treturn fmt.Errorf(\"could not parse cpuset %q for container %q in pod %q: %v\", cpuString, container, pod, err)\n\t\t\t}\n\t\t\ttmpAssignments[pod][container] = tmpContainerCPUSet\n\t\t}\n\t}\n\n\tsc.cache.SetDefaultCPUSet(tmpDefaultCPUSet)\n\tsc.cache.SetCPUAssignments(tmpAssignments)\n\n\tklog.V(2).InfoS(\"State checkpoint: restored state from checkpoint\")\n\tklog.V(2).InfoS(\"State checkpoint: defaultCPUSet\", \"defaultCpuSet\", tmpDefaultCPUSet.String())\n\n\treturn nil\n}","line":{"from":89,"to":140}} {"id":100005788,"name":"storeState","signature":"func (sc *stateCheckpoint) storeState() error","file":"pkg/kubelet/cm/cpumanager/state/state_checkpoint.go","code":"// saves state to a checkpoint, caller is responsible for locking\nfunc (sc *stateCheckpoint) storeState() error {\n\tcheckpoint := NewCPUManagerCheckpoint()\n\tcheckpoint.PolicyName = sc.policyName\n\tcheckpoint.DefaultCPUSet = sc.cache.GetDefaultCPUSet().String()\n\n\tassignments := sc.cache.GetCPUAssignments()\n\tfor pod := range assignments {\n\t\tcheckpoint.Entries[pod] = make(map[string]string)\n\t\tfor container, cset := range assignments[pod] {\n\t\t\tcheckpoint.Entries[pod][container] = cset.String()\n\t\t}\n\t}\n\n\terr := sc.checkpointManager.CreateCheckpoint(sc.checkpointName, checkpoint)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to save checkpoint\")\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":142,"to":162}} {"id":100005789,"name":"GetCPUSet","signature":"func (sc *stateCheckpoint) GetCPUSet(podUID string, containerName string) (cpuset.CPUSet, bool)","file":"pkg/kubelet/cm/cpumanager/state/state_checkpoint.go","code":"// GetCPUSet returns current CPU set\nfunc (sc *stateCheckpoint) GetCPUSet(podUID string, containerName string) (cpuset.CPUSet, bool) {\n\tsc.mux.RLock()\n\tdefer sc.mux.RUnlock()\n\n\tres, ok := sc.cache.GetCPUSet(podUID, containerName)\n\treturn res, ok\n}","line":{"from":164,"to":171}} {"id":100005790,"name":"GetDefaultCPUSet","signature":"func (sc *stateCheckpoint) GetDefaultCPUSet() cpuset.CPUSet","file":"pkg/kubelet/cm/cpumanager/state/state_checkpoint.go","code":"// GetDefaultCPUSet returns default CPU set\nfunc (sc *stateCheckpoint) GetDefaultCPUSet() cpuset.CPUSet {\n\tsc.mux.RLock()\n\tdefer sc.mux.RUnlock()\n\n\treturn sc.cache.GetDefaultCPUSet()\n}","line":{"from":173,"to":179}} {"id":100005791,"name":"GetCPUSetOrDefault","signature":"func (sc *stateCheckpoint) GetCPUSetOrDefault(podUID string, containerName string) cpuset.CPUSet","file":"pkg/kubelet/cm/cpumanager/state/state_checkpoint.go","code":"// GetCPUSetOrDefault returns current CPU set, or default one if it wasn't changed\nfunc (sc *stateCheckpoint) GetCPUSetOrDefault(podUID string, containerName string) cpuset.CPUSet {\n\tsc.mux.RLock()\n\tdefer sc.mux.RUnlock()\n\n\treturn sc.cache.GetCPUSetOrDefault(podUID, containerName)\n}","line":{"from":181,"to":187}} {"id":100005792,"name":"GetCPUAssignments","signature":"func (sc *stateCheckpoint) GetCPUAssignments() ContainerCPUAssignments","file":"pkg/kubelet/cm/cpumanager/state/state_checkpoint.go","code":"// GetCPUAssignments returns current CPU to pod assignments\nfunc (sc *stateCheckpoint) GetCPUAssignments() ContainerCPUAssignments {\n\tsc.mux.RLock()\n\tdefer sc.mux.RUnlock()\n\n\treturn sc.cache.GetCPUAssignments()\n}","line":{"from":189,"to":195}} {"id":100005793,"name":"SetCPUSet","signature":"func (sc *stateCheckpoint) SetCPUSet(podUID string, containerName string, cset cpuset.CPUSet)","file":"pkg/kubelet/cm/cpumanager/state/state_checkpoint.go","code":"// SetCPUSet sets CPU set\nfunc (sc *stateCheckpoint) SetCPUSet(podUID string, containerName string, cset cpuset.CPUSet) {\n\tsc.mux.Lock()\n\tdefer sc.mux.Unlock()\n\tsc.cache.SetCPUSet(podUID, containerName, cset)\n\terr := sc.storeState()\n\tif err != nil {\n\t\tklog.InfoS(\"Store state to checkpoint error\", \"err\", err)\n\t}\n}","line":{"from":197,"to":206}} {"id":100005794,"name":"SetDefaultCPUSet","signature":"func (sc *stateCheckpoint) SetDefaultCPUSet(cset cpuset.CPUSet)","file":"pkg/kubelet/cm/cpumanager/state/state_checkpoint.go","code":"// SetDefaultCPUSet sets default CPU set\nfunc (sc *stateCheckpoint) SetDefaultCPUSet(cset cpuset.CPUSet) {\n\tsc.mux.Lock()\n\tdefer sc.mux.Unlock()\n\tsc.cache.SetDefaultCPUSet(cset)\n\terr := sc.storeState()\n\tif err != nil {\n\t\tklog.InfoS(\"Store state to checkpoint error\", \"err\", err)\n\t}\n}","line":{"from":208,"to":217}} {"id":100005795,"name":"SetCPUAssignments","signature":"func (sc *stateCheckpoint) SetCPUAssignments(a ContainerCPUAssignments)","file":"pkg/kubelet/cm/cpumanager/state/state_checkpoint.go","code":"// SetCPUAssignments sets CPU to pod assignments\nfunc (sc *stateCheckpoint) SetCPUAssignments(a ContainerCPUAssignments) {\n\tsc.mux.Lock()\n\tdefer sc.mux.Unlock()\n\tsc.cache.SetCPUAssignments(a)\n\terr := sc.storeState()\n\tif err != nil {\n\t\tklog.InfoS(\"Store state to checkpoint error\", \"err\", err)\n\t}\n}","line":{"from":219,"to":228}} {"id":100005796,"name":"Delete","signature":"func (sc *stateCheckpoint) Delete(podUID string, containerName string)","file":"pkg/kubelet/cm/cpumanager/state/state_checkpoint.go","code":"// Delete deletes assignment for specified pod\nfunc (sc *stateCheckpoint) Delete(podUID string, containerName string) {\n\tsc.mux.Lock()\n\tdefer sc.mux.Unlock()\n\tsc.cache.Delete(podUID, containerName)\n\terr := sc.storeState()\n\tif err != nil {\n\t\tklog.InfoS(\"Store state to checkpoint error\", \"err\", err)\n\t}\n}","line":{"from":230,"to":239}} {"id":100005797,"name":"ClearState","signature":"func (sc *stateCheckpoint) ClearState()","file":"pkg/kubelet/cm/cpumanager/state/state_checkpoint.go","code":"// ClearState clears the state and saves it in a checkpoint\nfunc (sc *stateCheckpoint) ClearState() {\n\tsc.mux.Lock()\n\tdefer sc.mux.Unlock()\n\tsc.cache.ClearState()\n\terr := sc.storeState()\n\tif err != nil {\n\t\tklog.InfoS(\"Store state to checkpoint error\", \"err\", err)\n\t}\n}","line":{"from":241,"to":250}} {"id":100005798,"name":"NewMemoryState","signature":"func NewMemoryState() State","file":"pkg/kubelet/cm/cpumanager/state/state_mem.go","code":"// NewMemoryState creates new State for keeping track of cpu/pod assignment\nfunc NewMemoryState() State {\n\tklog.InfoS(\"Initialized new in-memory state store\")\n\treturn \u0026stateMemory{\n\t\tassignments: ContainerCPUAssignments{},\n\t\tdefaultCPUSet: cpuset.New(),\n\t}\n}","line":{"from":34,"to":41}} {"id":100005799,"name":"GetCPUSet","signature":"func (s *stateMemory) GetCPUSet(podUID string, containerName string) (cpuset.CPUSet, bool)","file":"pkg/kubelet/cm/cpumanager/state/state_mem.go","code":"func (s *stateMemory) GetCPUSet(podUID string, containerName string) (cpuset.CPUSet, bool) {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tres, ok := s.assignments[podUID][containerName]\n\treturn res.Clone(), ok\n}","line":{"from":43,"to":49}} {"id":100005800,"name":"GetDefaultCPUSet","signature":"func (s *stateMemory) GetDefaultCPUSet() cpuset.CPUSet","file":"pkg/kubelet/cm/cpumanager/state/state_mem.go","code":"func (s *stateMemory) GetDefaultCPUSet() cpuset.CPUSet {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\treturn s.defaultCPUSet.Clone()\n}","line":{"from":51,"to":56}} {"id":100005801,"name":"GetCPUSetOrDefault","signature":"func (s *stateMemory) GetCPUSetOrDefault(podUID string, containerName string) cpuset.CPUSet","file":"pkg/kubelet/cm/cpumanager/state/state_mem.go","code":"func (s *stateMemory) GetCPUSetOrDefault(podUID string, containerName string) cpuset.CPUSet {\n\tif res, ok := s.GetCPUSet(podUID, containerName); ok {\n\t\treturn res\n\t}\n\treturn s.GetDefaultCPUSet()\n}","line":{"from":58,"to":63}} {"id":100005802,"name":"GetCPUAssignments","signature":"func (s *stateMemory) GetCPUAssignments() ContainerCPUAssignments","file":"pkg/kubelet/cm/cpumanager/state/state_mem.go","code":"func (s *stateMemory) GetCPUAssignments() ContainerCPUAssignments {\n\ts.RLock()\n\tdefer s.RUnlock()\n\treturn s.assignments.Clone()\n}","line":{"from":65,"to":69}} {"id":100005803,"name":"SetCPUSet","signature":"func (s *stateMemory) SetCPUSet(podUID string, containerName string, cset cpuset.CPUSet)","file":"pkg/kubelet/cm/cpumanager/state/state_mem.go","code":"func (s *stateMemory) SetCPUSet(podUID string, containerName string, cset cpuset.CPUSet) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tif _, ok := s.assignments[podUID]; !ok {\n\t\ts.assignments[podUID] = make(map[string]cpuset.CPUSet)\n\t}\n\n\ts.assignments[podUID][containerName] = cset\n\tklog.InfoS(\"Updated desired CPUSet\", \"podUID\", podUID, \"containerName\", containerName, \"cpuSet\", cset)\n}","line":{"from":71,"to":81}} {"id":100005804,"name":"SetDefaultCPUSet","signature":"func (s *stateMemory) SetDefaultCPUSet(cset cpuset.CPUSet)","file":"pkg/kubelet/cm/cpumanager/state/state_mem.go","code":"func (s *stateMemory) SetDefaultCPUSet(cset cpuset.CPUSet) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\ts.defaultCPUSet = cset\n\tklog.InfoS(\"Updated default CPUSet\", \"cpuSet\", cset)\n}","line":{"from":83,"to":89}} {"id":100005805,"name":"SetCPUAssignments","signature":"func (s *stateMemory) SetCPUAssignments(a ContainerCPUAssignments)","file":"pkg/kubelet/cm/cpumanager/state/state_mem.go","code":"func (s *stateMemory) SetCPUAssignments(a ContainerCPUAssignments) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\ts.assignments = a.Clone()\n\tklog.InfoS(\"Updated CPUSet assignments\", \"assignments\", a)\n}","line":{"from":91,"to":97}} {"id":100005806,"name":"Delete","signature":"func (s *stateMemory) Delete(podUID string, containerName string)","file":"pkg/kubelet/cm/cpumanager/state/state_mem.go","code":"func (s *stateMemory) Delete(podUID string, containerName string) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tdelete(s.assignments[podUID], containerName)\n\tif len(s.assignments[podUID]) == 0 {\n\t\tdelete(s.assignments, podUID)\n\t}\n\tklog.V(2).InfoS(\"Deleted CPUSet assignment\", \"podUID\", podUID, \"containerName\", containerName)\n}","line":{"from":99,"to":108}} {"id":100005807,"name":"ClearState","signature":"func (s *stateMemory) ClearState()","file":"pkg/kubelet/cm/cpumanager/state/state_mem.go","code":"func (s *stateMemory) ClearState() {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\ts.defaultCPUSet = cpuset.CPUSet{}\n\ts.assignments = make(ContainerCPUAssignments)\n\tklog.V(2).InfoS(\"Cleared state\")\n}","line":{"from":110,"to":117}} {"id":100005808,"name":"CPUsPerCore","signature":"func (topo *CPUTopology) CPUsPerCore() int","file":"pkg/kubelet/cm/cpumanager/topology/topology.go","code":"// CPUsPerCore returns the number of logical CPUs are associated with\n// each core.\nfunc (topo *CPUTopology) CPUsPerCore() int {\n\tif topo.NumCores == 0 {\n\t\treturn 0\n\t}\n\treturn topo.NumCPUs / topo.NumCores\n}","line":{"from":47,"to":54}} {"id":100005809,"name":"CPUsPerSocket","signature":"func (topo *CPUTopology) CPUsPerSocket() int","file":"pkg/kubelet/cm/cpumanager/topology/topology.go","code":"// CPUsPerSocket returns the number of logical CPUs are associated with\n// each socket.\nfunc (topo *CPUTopology) CPUsPerSocket() int {\n\tif topo.NumSockets == 0 {\n\t\treturn 0\n\t}\n\treturn topo.NumCPUs / topo.NumSockets\n}","line":{"from":56,"to":63}} {"id":100005810,"name":"CPUCoreID","signature":"func (topo *CPUTopology) CPUCoreID(cpu int) (int, error)","file":"pkg/kubelet/cm/cpumanager/topology/topology.go","code":"// CPUCoreID returns the physical core ID which the given logical CPU\n// belongs to.\nfunc (topo *CPUTopology) CPUCoreID(cpu int) (int, error) {\n\tinfo, ok := topo.CPUDetails[cpu]\n\tif !ok {\n\t\treturn -1, fmt.Errorf(\"unknown CPU ID: %d\", cpu)\n\t}\n\treturn info.CoreID, nil\n}","line":{"from":65,"to":73}} {"id":100005811,"name":"CPUSocketID","signature":"func (topo *CPUTopology) CPUSocketID(cpu int) (int, error)","file":"pkg/kubelet/cm/cpumanager/topology/topology.go","code":"// CPUCoreID returns the socket ID which the given logical CPU belongs to.\nfunc (topo *CPUTopology) CPUSocketID(cpu int) (int, error) {\n\tinfo, ok := topo.CPUDetails[cpu]\n\tif !ok {\n\t\treturn -1, fmt.Errorf(\"unknown CPU ID: %d\", cpu)\n\t}\n\treturn info.SocketID, nil\n}","line":{"from":75,"to":82}} {"id":100005812,"name":"CPUNUMANodeID","signature":"func (topo *CPUTopology) CPUNUMANodeID(cpu int) (int, error)","file":"pkg/kubelet/cm/cpumanager/topology/topology.go","code":"// CPUCoreID returns the NUMA node ID which the given logical CPU belongs to.\nfunc (topo *CPUTopology) CPUNUMANodeID(cpu int) (int, error) {\n\tinfo, ok := topo.CPUDetails[cpu]\n\tif !ok {\n\t\treturn -1, fmt.Errorf(\"unknown CPU ID: %d\", cpu)\n\t}\n\treturn info.NUMANodeID, nil\n}","line":{"from":84,"to":91}} {"id":100005813,"name":"KeepOnly","signature":"func (d CPUDetails) KeepOnly(cpus cpuset.CPUSet) CPUDetails","file":"pkg/kubelet/cm/cpumanager/topology/topology.go","code":"// KeepOnly returns a new CPUDetails object with only the supplied cpus.\nfunc (d CPUDetails) KeepOnly(cpus cpuset.CPUSet) CPUDetails {\n\tresult := CPUDetails{}\n\tfor cpu, info := range d {\n\t\tif cpus.Contains(cpu) {\n\t\t\tresult[cpu] = info\n\t\t}\n\t}\n\treturn result\n}","line":{"from":100,"to":109}} {"id":100005814,"name":"NUMANodes","signature":"func (d CPUDetails) NUMANodes() cpuset.CPUSet","file":"pkg/kubelet/cm/cpumanager/topology/topology.go","code":"// NUMANodes returns all of the NUMANode IDs associated with the CPUs in this\n// CPUDetails.\nfunc (d CPUDetails) NUMANodes() cpuset.CPUSet {\n\tvar numaNodeIDs []int\n\tfor _, info := range d {\n\t\tnumaNodeIDs = append(numaNodeIDs, info.NUMANodeID)\n\t}\n\treturn cpuset.New(numaNodeIDs...)\n}","line":{"from":111,"to":119}} {"id":100005815,"name":"NUMANodesInSockets","signature":"func (d CPUDetails) NUMANodesInSockets(ids ...int) cpuset.CPUSet","file":"pkg/kubelet/cm/cpumanager/topology/topology.go","code":"// NUMANodesInSockets returns all of the logical NUMANode IDs associated with\n// the given socket IDs in this CPUDetails.\nfunc (d CPUDetails) NUMANodesInSockets(ids ...int) cpuset.CPUSet {\n\tvar numaNodeIDs []int\n\tfor _, id := range ids {\n\t\tfor _, info := range d {\n\t\t\tif info.SocketID == id {\n\t\t\t\tnumaNodeIDs = append(numaNodeIDs, info.NUMANodeID)\n\t\t\t}\n\t\t}\n\t}\n\treturn cpuset.New(numaNodeIDs...)\n}","line":{"from":121,"to":133}} {"id":100005816,"name":"Sockets","signature":"func (d CPUDetails) Sockets() cpuset.CPUSet","file":"pkg/kubelet/cm/cpumanager/topology/topology.go","code":"// Sockets returns all of the socket IDs associated with the CPUs in this\n// CPUDetails.\nfunc (d CPUDetails) Sockets() cpuset.CPUSet {\n\tvar socketIDs []int\n\tfor _, info := range d {\n\t\tsocketIDs = append(socketIDs, info.SocketID)\n\t}\n\treturn cpuset.New(socketIDs...)\n}","line":{"from":135,"to":143}} {"id":100005817,"name":"CPUsInSockets","signature":"func (d CPUDetails) CPUsInSockets(ids ...int) cpuset.CPUSet","file":"pkg/kubelet/cm/cpumanager/topology/topology.go","code":"// CPUsInSockets returns all of the logical CPU IDs associated with the given\n// socket IDs in this CPUDetails.\nfunc (d CPUDetails) CPUsInSockets(ids ...int) cpuset.CPUSet {\n\tvar cpuIDs []int\n\tfor _, id := range ids {\n\t\tfor cpu, info := range d {\n\t\t\tif info.SocketID == id {\n\t\t\t\tcpuIDs = append(cpuIDs, cpu)\n\t\t\t}\n\t\t}\n\t}\n\treturn cpuset.New(cpuIDs...)\n}","line":{"from":145,"to":157}} {"id":100005818,"name":"SocketsInNUMANodes","signature":"func (d CPUDetails) SocketsInNUMANodes(ids ...int) cpuset.CPUSet","file":"pkg/kubelet/cm/cpumanager/topology/topology.go","code":"// SocketsInNUMANodes returns all of the logical Socket IDs associated with the\n// given NUMANode IDs in this CPUDetails.\nfunc (d CPUDetails) SocketsInNUMANodes(ids ...int) cpuset.CPUSet {\n\tvar socketIDs []int\n\tfor _, id := range ids {\n\t\tfor _, info := range d {\n\t\t\tif info.NUMANodeID == id {\n\t\t\t\tsocketIDs = append(socketIDs, info.SocketID)\n\t\t\t}\n\t\t}\n\t}\n\treturn cpuset.New(socketIDs...)\n}","line":{"from":159,"to":171}} {"id":100005819,"name":"Cores","signature":"func (d CPUDetails) Cores() cpuset.CPUSet","file":"pkg/kubelet/cm/cpumanager/topology/topology.go","code":"// Cores returns all of the core IDs associated with the CPUs in this\n// CPUDetails.\nfunc (d CPUDetails) Cores() cpuset.CPUSet {\n\tvar coreIDs []int\n\tfor _, info := range d {\n\t\tcoreIDs = append(coreIDs, info.CoreID)\n\t}\n\treturn cpuset.New(coreIDs...)\n}","line":{"from":173,"to":181}} {"id":100005820,"name":"CoresInNUMANodes","signature":"func (d CPUDetails) CoresInNUMANodes(ids ...int) cpuset.CPUSet","file":"pkg/kubelet/cm/cpumanager/topology/topology.go","code":"// CoresInNUMANodes returns all of the core IDs associated with the given\n// NUMANode IDs in this CPUDetails.\nfunc (d CPUDetails) CoresInNUMANodes(ids ...int) cpuset.CPUSet {\n\tvar coreIDs []int\n\tfor _, id := range ids {\n\t\tfor _, info := range d {\n\t\t\tif info.NUMANodeID == id {\n\t\t\t\tcoreIDs = append(coreIDs, info.CoreID)\n\t\t\t}\n\t\t}\n\t}\n\treturn cpuset.New(coreIDs...)\n}","line":{"from":183,"to":195}} {"id":100005821,"name":"CoresInSockets","signature":"func (d CPUDetails) CoresInSockets(ids ...int) cpuset.CPUSet","file":"pkg/kubelet/cm/cpumanager/topology/topology.go","code":"// CoresInSockets returns all of the core IDs associated with the given socket\n// IDs in this CPUDetails.\nfunc (d CPUDetails) CoresInSockets(ids ...int) cpuset.CPUSet {\n\tvar coreIDs []int\n\tfor _, id := range ids {\n\t\tfor _, info := range d {\n\t\t\tif info.SocketID == id {\n\t\t\t\tcoreIDs = append(coreIDs, info.CoreID)\n\t\t\t}\n\t\t}\n\t}\n\treturn cpuset.New(coreIDs...)\n}","line":{"from":197,"to":209}} {"id":100005822,"name":"CPUs","signature":"func (d CPUDetails) CPUs() cpuset.CPUSet","file":"pkg/kubelet/cm/cpumanager/topology/topology.go","code":"// CPUs returns all of the logical CPU IDs in this CPUDetails.\nfunc (d CPUDetails) CPUs() cpuset.CPUSet {\n\tvar cpuIDs []int\n\tfor cpuID := range d {\n\t\tcpuIDs = append(cpuIDs, cpuID)\n\t}\n\treturn cpuset.New(cpuIDs...)\n}","line":{"from":211,"to":218}} {"id":100005823,"name":"CPUsInNUMANodes","signature":"func (d CPUDetails) CPUsInNUMANodes(ids ...int) cpuset.CPUSet","file":"pkg/kubelet/cm/cpumanager/topology/topology.go","code":"// CPUsInNUMANodes returns all of the logical CPU IDs associated with the given\n// NUMANode IDs in this CPUDetails.\nfunc (d CPUDetails) CPUsInNUMANodes(ids ...int) cpuset.CPUSet {\n\tvar cpuIDs []int\n\tfor _, id := range ids {\n\t\tfor cpu, info := range d {\n\t\t\tif info.NUMANodeID == id {\n\t\t\t\tcpuIDs = append(cpuIDs, cpu)\n\t\t\t}\n\t\t}\n\t}\n\treturn cpuset.New(cpuIDs...)\n}","line":{"from":220,"to":232}} {"id":100005824,"name":"CPUsInCores","signature":"func (d CPUDetails) CPUsInCores(ids ...int) cpuset.CPUSet","file":"pkg/kubelet/cm/cpumanager/topology/topology.go","code":"// CPUsInCores returns all of the logical CPU IDs associated with the given\n// core IDs in this CPUDetails.\nfunc (d CPUDetails) CPUsInCores(ids ...int) cpuset.CPUSet {\n\tvar cpuIDs []int\n\tfor _, id := range ids {\n\t\tfor cpu, info := range d {\n\t\t\tif info.CoreID == id {\n\t\t\t\tcpuIDs = append(cpuIDs, cpu)\n\t\t\t}\n\t\t}\n\t}\n\treturn cpuset.New(cpuIDs...)\n}","line":{"from":234,"to":246}} {"id":100005825,"name":"Discover","signature":"func Discover(machineInfo *cadvisorapi.MachineInfo) (*CPUTopology, error)","file":"pkg/kubelet/cm/cpumanager/topology/topology.go","code":"// Discover returns CPUTopology based on cadvisor node info\nfunc Discover(machineInfo *cadvisorapi.MachineInfo) (*CPUTopology, error) {\n\tif machineInfo.NumCores == 0 {\n\t\treturn nil, fmt.Errorf(\"could not detect number of cpus\")\n\t}\n\n\tCPUDetails := CPUDetails{}\n\tnumPhysicalCores := 0\n\n\tfor _, node := range machineInfo.Topology {\n\t\tnumPhysicalCores += len(node.Cores)\n\t\tfor _, core := range node.Cores {\n\t\t\tif coreID, err := getUniqueCoreID(core.Threads); err == nil {\n\t\t\t\tfor _, cpu := range core.Threads {\n\t\t\t\t\tCPUDetails[cpu] = CPUInfo{\n\t\t\t\t\t\tCoreID: coreID,\n\t\t\t\t\t\tSocketID: core.SocketID,\n\t\t\t\t\t\tNUMANodeID: node.Id,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tklog.ErrorS(nil, \"Could not get unique coreID for socket\", \"socket\", core.SocketID, \"core\", core.Id, \"threads\", core.Threads)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \u0026CPUTopology{\n\t\tNumCPUs: machineInfo.NumCores,\n\t\tNumSockets: machineInfo.NumSockets,\n\t\tNumCores: numPhysicalCores,\n\t\tNumNUMANodes: CPUDetails.NUMANodes().Size(),\n\t\tCPUDetails: CPUDetails,\n\t}, nil\n}","line":{"from":248,"to":282}} {"id":100005826,"name":"getUniqueCoreID","signature":"func getUniqueCoreID(threads []int) (coreID int, err error)","file":"pkg/kubelet/cm/cpumanager/topology/topology.go","code":"// getUniqueCoreID computes coreId as the lowest cpuID\n// for a given Threads []int slice. This will assure that coreID's are\n// platform unique (opposite to what cAdvisor reports)\nfunc getUniqueCoreID(threads []int) (coreID int, err error) {\n\tif len(threads) == 0 {\n\t\treturn 0, fmt.Errorf(\"no cpus provided\")\n\t}\n\n\tif len(threads) != cpuset.New(threads...).Size() {\n\t\treturn 0, fmt.Errorf(\"cpus provided are not unique\")\n\t}\n\n\tmin := threads[0]\n\tfor _, thread := range threads[1:] {\n\t\tif thread \u003c min {\n\t\t\tmin = thread\n\t\t}\n\t}\n\n\treturn min, nil\n}","line":{"from":284,"to":304}} {"id":100005827,"name":"New","signature":"func New(cpus ...int) CPUSet","file":"pkg/kubelet/cm/cpuset/cpuset.go","code":"// New returns a new CPUSet containing the supplied elements.\nfunc New(cpus ...int) CPUSet {\n\ts := CPUSet{\n\t\telems: map[int]struct{}{},\n\t}\n\tfor _, c := range cpus {\n\t\ts.add(c)\n\t}\n\treturn s\n}","line":{"from":42,"to":51}} {"id":100005828,"name":"add","signature":"func (s CPUSet) add(elems ...int)","file":"pkg/kubelet/cm/cpuset/cpuset.go","code":"// add adds the supplied elements to the CPUSet.\n// It is intended for internal use only, since it mutates the CPUSet.\nfunc (s CPUSet) add(elems ...int) {\n\tfor _, elem := range elems {\n\t\ts.elems[elem] = struct{}{}\n\t}\n}","line":{"from":53,"to":59}} {"id":100005829,"name":"Size","signature":"func (s CPUSet) Size() int","file":"pkg/kubelet/cm/cpuset/cpuset.go","code":"// Size returns the number of elements in this set.\nfunc (s CPUSet) Size() int {\n\treturn len(s.elems)\n}","line":{"from":61,"to":64}} {"id":100005830,"name":"IsEmpty","signature":"func (s CPUSet) IsEmpty() bool","file":"pkg/kubelet/cm/cpuset/cpuset.go","code":"// IsEmpty returns true if there are zero elements in this set.\nfunc (s CPUSet) IsEmpty() bool {\n\treturn s.Size() == 0\n}","line":{"from":66,"to":69}} {"id":100005831,"name":"Contains","signature":"func (s CPUSet) Contains(cpu int) bool","file":"pkg/kubelet/cm/cpuset/cpuset.go","code":"// Contains returns true if the supplied element is present in this set.\nfunc (s CPUSet) Contains(cpu int) bool {\n\t_, found := s.elems[cpu]\n\treturn found\n}","line":{"from":71,"to":75}} {"id":100005832,"name":"Equals","signature":"func (s CPUSet) Equals(s2 CPUSet) bool","file":"pkg/kubelet/cm/cpuset/cpuset.go","code":"// Equals returns true if the supplied set contains exactly the same elements\n// as this set (s IsSubsetOf s2 and s2 IsSubsetOf s).\nfunc (s CPUSet) Equals(s2 CPUSet) bool {\n\treturn reflect.DeepEqual(s.elems, s2.elems)\n}","line":{"from":77,"to":81}} {"id":100005833,"name":"filter","signature":"func (s CPUSet) filter(predicate func(int) bool) CPUSet","file":"pkg/kubelet/cm/cpuset/cpuset.go","code":"// filter returns a new CPU set that contains all of the elements from this\n// set that match the supplied predicate, without mutating the source set.\nfunc (s CPUSet) filter(predicate func(int) bool) CPUSet {\n\tr := New()\n\tfor cpu := range s.elems {\n\t\tif predicate(cpu) {\n\t\t\tr.add(cpu)\n\t\t}\n\t}\n\treturn r\n}","line":{"from":83,"to":93}} {"id":100005834,"name":"IsSubsetOf","signature":"func (s CPUSet) IsSubsetOf(s2 CPUSet) bool","file":"pkg/kubelet/cm/cpuset/cpuset.go","code":"// IsSubsetOf returns true if the supplied set contains all the elements\nfunc (s CPUSet) IsSubsetOf(s2 CPUSet) bool {\n\tresult := true\n\tfor cpu := range s.elems {\n\t\tif !s2.Contains(cpu) {\n\t\t\tresult = false\n\t\t\tbreak\n\t\t}\n\t}\n\treturn result\n}","line":{"from":95,"to":105}} {"id":100005835,"name":"Union","signature":"func (s CPUSet) Union(s2 ...CPUSet) CPUSet","file":"pkg/kubelet/cm/cpuset/cpuset.go","code":"// Union returns a new CPU set that contains all of the elements from this\n// set and all of the elements from the supplied sets, without mutating\n// either source set.\nfunc (s CPUSet) Union(s2 ...CPUSet) CPUSet {\n\tr := New()\n\tfor cpu := range s.elems {\n\t\tr.add(cpu)\n\t}\n\tfor _, cs := range s2 {\n\t\tfor cpu := range cs.elems {\n\t\t\tr.add(cpu)\n\t\t}\n\t}\n\treturn r\n}","line":{"from":107,"to":121}} {"id":100005836,"name":"Intersection","signature":"func (s CPUSet) Intersection(s2 CPUSet) CPUSet","file":"pkg/kubelet/cm/cpuset/cpuset.go","code":"// Intersection returns a new CPU set that contains all of the elements\n// that are present in both this set and the supplied set, without mutating\n// either source set.\nfunc (s CPUSet) Intersection(s2 CPUSet) CPUSet {\n\treturn s.filter(func(cpu int) bool { return s2.Contains(cpu) })\n}","line":{"from":123,"to":128}} {"id":100005837,"name":"Difference","signature":"func (s CPUSet) Difference(s2 CPUSet) CPUSet","file":"pkg/kubelet/cm/cpuset/cpuset.go","code":"// Difference returns a new CPU set that contains all of the elements that\n// are present in this set and not the supplied set, without mutating either\n// source set.\nfunc (s CPUSet) Difference(s2 CPUSet) CPUSet {\n\treturn s.filter(func(cpu int) bool { return !s2.Contains(cpu) })\n}","line":{"from":130,"to":135}} {"id":100005838,"name":"List","signature":"func (s CPUSet) List() []int","file":"pkg/kubelet/cm/cpuset/cpuset.go","code":"// List returns a slice of integers that contains all elements from\n// this set. The list is sorted.\nfunc (s CPUSet) List() []int {\n\tresult := s.UnsortedList()\n\tsort.Ints(result)\n\treturn result\n}","line":{"from":137,"to":143}} {"id":100005839,"name":"UnsortedList","signature":"func (s CPUSet) UnsortedList() []int","file":"pkg/kubelet/cm/cpuset/cpuset.go","code":"// UnsortedList returns a slice of integers that contains all elements from\n// this set.\nfunc (s CPUSet) UnsortedList() []int {\n\tresult := make([]int, 0, len(s.elems))\n\tfor cpu := range s.elems {\n\t\tresult = append(result, cpu)\n\t}\n\treturn result\n}","line":{"from":145,"to":153}} {"id":100005840,"name":"String","signature":"func (s CPUSet) String() string","file":"pkg/kubelet/cm/cpuset/cpuset.go","code":"// String returns a new string representation of the elements in this CPU set\n// in canonical linux CPU list format.\n//\n// See: http://man7.org/linux/man-pages/man7/cpuset.7.html#FORMATS\nfunc (s CPUSet) String() string {\n\tif s.IsEmpty() {\n\t\treturn \"\"\n\t}\n\n\telems := s.List()\n\n\ttype rng struct {\n\t\tstart int\n\t\tend int\n\t}\n\n\tranges := []rng{{elems[0], elems[0]}}\n\n\tfor i := 1; i \u003c len(elems); i++ {\n\t\tlastRange := \u0026ranges[len(ranges)-1]\n\t\t// if this element is adjacent to the high end of the last range\n\t\tif elems[i] == lastRange.end+1 {\n\t\t\t// then extend the last range to include this element\n\t\t\tlastRange.end = elems[i]\n\t\t\tcontinue\n\t\t}\n\t\t// otherwise, start a new range beginning with this element\n\t\tranges = append(ranges, rng{elems[i], elems[i]})\n\t}\n\n\t// construct string from ranges\n\tvar result bytes.Buffer\n\tfor _, r := range ranges {\n\t\tif r.start == r.end {\n\t\t\tresult.WriteString(strconv.Itoa(r.start))\n\t\t} else {\n\t\t\tresult.WriteString(fmt.Sprintf(\"%d-%d\", r.start, r.end))\n\t\t}\n\t\tresult.WriteString(\",\")\n\t}\n\treturn strings.TrimRight(result.String(), \",\")\n}","line":{"from":155,"to":196}} {"id":100005841,"name":"Parse","signature":"func Parse(s string) (CPUSet, error)","file":"pkg/kubelet/cm/cpuset/cpuset.go","code":"// Parse CPUSet constructs a new CPU set from a Linux CPU list formatted string.\n//\n// See: http://man7.org/linux/man-pages/man7/cpuset.7.html#FORMATS\nfunc Parse(s string) (CPUSet, error) {\n\t// Handle empty string.\n\tif s == \"\" {\n\t\treturn New(), nil\n\t}\n\n\tresult := New()\n\n\t// Split CPU list string:\n\t// \"0-5,34,46-48\" =\u003e [\"0-5\", \"34\", \"46-48\"]\n\tranges := strings.Split(s, \",\")\n\n\tfor _, r := range ranges {\n\t\tboundaries := strings.SplitN(r, \"-\", 2)\n\t\tif len(boundaries) == 1 {\n\t\t\t// Handle ranges that consist of only one element like \"34\".\n\t\t\telem, err := strconv.Atoi(boundaries[0])\n\t\t\tif err != nil {\n\t\t\t\treturn New(), err\n\t\t\t}\n\t\t\tresult.add(elem)\n\t\t} else if len(boundaries) == 2 {\n\t\t\t// Handle multi-element ranges like \"0-5\".\n\t\t\tstart, err := strconv.Atoi(boundaries[0])\n\t\t\tif err != nil {\n\t\t\t\treturn New(), err\n\t\t\t}\n\t\t\tend, err := strconv.Atoi(boundaries[1])\n\t\t\tif err != nil {\n\t\t\t\treturn New(), err\n\t\t\t}\n\t\t\tif start \u003e end {\n\t\t\t\treturn New(), fmt.Errorf(\"invalid range %q (%d \u003e %d)\", r, start, end)\n\t\t\t}\n\t\t\t// start == end is acceptable (1-1 -\u003e 1)\n\n\t\t\t// Add all elements to the result.\n\t\t\t// e.g. \"0-5\", \"46-48\" =\u003e [0, 1, 2, 3, 4, 5, 46, 47, 48].\n\t\t\tfor e := start; e \u003c= end; e++ {\n\t\t\t\tresult.add(e)\n\t\t\t}\n\t\t}\n\t}\n\treturn result, nil\n}","line":{"from":198,"to":245}} {"id":100005842,"name":"Clone","signature":"func (s CPUSet) Clone() CPUSet","file":"pkg/kubelet/cm/cpuset/cpuset.go","code":"// Clone returns a copy of this CPU set.\nfunc (s CPUSet) Clone() CPUSet {\n\tr := New()\n\tfor elem := range s.elems {\n\t\tr.add(elem)\n\t}\n\treturn r\n}","line":{"from":247,"to":254}} {"id":100005843,"name":"NewDevicesPerNUMA","signature":"func NewDevicesPerNUMA() DevicesPerNUMA","file":"pkg/kubelet/cm/devicemanager/checkpoint/checkpoint.go","code":"// NewDevicesPerNUMA is a function that creates DevicesPerNUMA map\nfunc NewDevicesPerNUMA() DevicesPerNUMA {\n\treturn make(DevicesPerNUMA)\n}","line":{"from":59,"to":62}} {"id":100005844,"name":"Devices","signature":"func (dev DevicesPerNUMA) Devices() sets.String","file":"pkg/kubelet/cm/devicemanager/checkpoint/checkpoint.go","code":"// Devices is a function that returns all device ids for all NUMA nodes\n// and represent it as sets.String\nfunc (dev DevicesPerNUMA) Devices() sets.String {\n\tresult := sets.NewString()\n\n\tfor _, devs := range dev {\n\t\tresult.Insert(devs...)\n\t}\n\treturn result\n}","line":{"from":64,"to":73}} {"id":100005845,"name":"New","signature":"func New(devEntries []PodDevicesEntry, devices map[string][]string) DeviceManagerCheckpoint","file":"pkg/kubelet/cm/devicemanager/checkpoint/checkpoint.go","code":"// New returns an instance of Checkpoint - must be an alias for the most recent version\nfunc New(devEntries []PodDevicesEntry, devices map[string][]string) DeviceManagerCheckpoint {\n\treturn newV2(devEntries, devices)\n}","line":{"from":75,"to":78}} {"id":100005846,"name":"newV2","signature":"func newV2(devEntries []PodDevicesEntry, devices map[string][]string) DeviceManagerCheckpoint","file":"pkg/kubelet/cm/devicemanager/checkpoint/checkpoint.go","code":"func newV2(devEntries []PodDevicesEntry, devices map[string][]string) DeviceManagerCheckpoint {\n\treturn \u0026Data{\n\t\tData: checkpointData{\n\t\t\tPodDeviceEntries: devEntries,\n\t\t\tRegisteredDevices: devices,\n\t\t},\n\t}\n}","line":{"from":80,"to":87}} {"id":100005847,"name":"MarshalCheckpoint","signature":"func (cp *Data) MarshalCheckpoint() ([]byte, error)","file":"pkg/kubelet/cm/devicemanager/checkpoint/checkpoint.go","code":"// MarshalCheckpoint returns marshalled data\nfunc (cp *Data) MarshalCheckpoint() ([]byte, error) {\n\tcp.Checksum = checksum.New(cp.Data)\n\treturn json.Marshal(*cp)\n}","line":{"from":89,"to":93}} {"id":100005848,"name":"UnmarshalCheckpoint","signature":"func (cp *Data) UnmarshalCheckpoint(blob []byte) error","file":"pkg/kubelet/cm/devicemanager/checkpoint/checkpoint.go","code":"// UnmarshalCheckpoint returns unmarshalled data\nfunc (cp *Data) UnmarshalCheckpoint(blob []byte) error {\n\treturn json.Unmarshal(blob, cp)\n}","line":{"from":95,"to":98}} {"id":100005849,"name":"VerifyChecksum","signature":"func (cp *Data) VerifyChecksum() error","file":"pkg/kubelet/cm/devicemanager/checkpoint/checkpoint.go","code":"// VerifyChecksum verifies that passed checksum is same as calculated checksum\nfunc (cp *Data) VerifyChecksum() error {\n\treturn cp.Checksum.Verify(cp.Data)\n}","line":{"from":100,"to":103}} {"id":100005850,"name":"GetDataInLatestFormat","signature":"func (cp *Data) GetDataInLatestFormat() ([]PodDevicesEntry, map[string][]string)","file":"pkg/kubelet/cm/devicemanager/checkpoint/checkpoint.go","code":"// GetDataInLatestFormat returns device entries and registered devices in the *most recent*\n// checkpoint format, *not* in the original format stored on disk.\nfunc (cp *Data) GetDataInLatestFormat() ([]PodDevicesEntry, map[string][]string) {\n\treturn cp.Data.PodDeviceEntries, cp.Data.RegisteredDevices\n}","line":{"from":105,"to":109}} {"id":100005851,"name":"checksum","signature":"func (cp checkpointDataV1) checksum() checksum.Checksum","file":"pkg/kubelet/cm/devicemanager/checkpoint/checkpointv1.go","code":"// checksum compute the checksum using the same algorithms (and data type names) k8s 1.19 used.\n// We need this special code path to be able to correctly validate the checksum k8s 1.19 wrote.\n// credits to https://github.com/kubernetes/kubernetes/pull/102717/commits/353f93895118d2ffa2d59a29a1fbc225160ea1d6\nfunc (cp checkpointDataV1) checksum() checksum.Checksum {\n\tprinter := spew.ConfigState{\n\t\tIndent: \" \",\n\t\tSortKeys: true,\n\t\tDisableMethods: true,\n\t\tSpewKeys: true,\n\t}\n\n\tobject := printer.Sprintf(\"%#v\", cp)\n\tobject = strings.Replace(object, \"checkpointDataV1\", \"checkpointData\", 1)\n\tobject = strings.Replace(object, \"PodDevicesEntryV1\", \"PodDevicesEntry\", -1)\n\thash := fnv.New32a()\n\tprinter.Fprintf(hash, \"%v\", object)\n\treturn checksum.Checksum(hash.Sum32())\n}","line":{"from":47,"to":64}} {"id":100005852,"name":"NewV1","signature":"func NewV1(devEntries []PodDevicesEntryV1,","file":"pkg/kubelet/cm/devicemanager/checkpoint/checkpointv1.go","code":"// NewV1 returns an instance of Checkpoint, in V1 (k8s \u003c= 1.19) format.\n// Users should avoid creating checkpoints in formats different than the most recent one,\n// use the old formats only to validate existing checkpoint and convert them to most recent\n// format. The only exception should be test code.\nfunc NewV1(devEntries []PodDevicesEntryV1,\n\tdevices map[string][]string) DeviceManagerCheckpoint {\n\treturn \u0026DataV1{\n\t\tData: checkpointDataV1{\n\t\t\tPodDeviceEntries: devEntries,\n\t\t\tRegisteredDevices: devices,\n\t\t},\n\t}\n}","line":{"from":72,"to":84}} {"id":100005853,"name":"MarshalCheckpoint","signature":"func (cp *DataV1) MarshalCheckpoint() ([]byte, error)","file":"pkg/kubelet/cm/devicemanager/checkpoint/checkpointv1.go","code":"// MarshalCheckpoint is needed to implement the Checkpoint interface, but should not be called anymore\nfunc (cp *DataV1) MarshalCheckpoint() ([]byte, error) {\n\tklog.InfoS(\"Marshalling a device manager V1 checkpoint\")\n\tcp.Checksum = cp.Data.checksum()\n\treturn json.Marshal(*cp)\n}","line":{"from":86,"to":91}} {"id":100005854,"name":"UnmarshalCheckpoint","signature":"func (cp *DataV1) UnmarshalCheckpoint(blob []byte) error","file":"pkg/kubelet/cm/devicemanager/checkpoint/checkpointv1.go","code":"// UnmarshalCheckpoint returns unmarshalled data\nfunc (cp *DataV1) UnmarshalCheckpoint(blob []byte) error {\n\treturn json.Unmarshal(blob, cp)\n}","line":{"from":93,"to":96}} {"id":100005855,"name":"VerifyChecksum","signature":"func (cp *DataV1) VerifyChecksum() error","file":"pkg/kubelet/cm/devicemanager/checkpoint/checkpointv1.go","code":"// VerifyChecksum verifies that passed checksum is same as calculated checksum\nfunc (cp *DataV1) VerifyChecksum() error {\n\tif cp.Checksum != cp.Data.checksum() {\n\t\treturn errors.ErrCorruptCheckpoint\n\t}\n\treturn nil\n}","line":{"from":98,"to":104}} {"id":100005856,"name":"GetDataInLatestFormat","signature":"func (cp *DataV1) GetDataInLatestFormat() ([]PodDevicesEntry, map[string][]string)","file":"pkg/kubelet/cm/devicemanager/checkpoint/checkpointv1.go","code":"// GetDataInLatestFormat returns device entries and registered devices in the *most recent*\n// checkpoint format, *not* in the original format stored on disk.\nfunc (cp *DataV1) GetDataInLatestFormat() ([]PodDevicesEntry, map[string][]string) {\n\tvar podDevs []PodDevicesEntry\n\tfor _, entryV1 := range cp.Data.PodDeviceEntries {\n\t\tdevsPerNuma := NewDevicesPerNUMA()\n\t\t// no NUMA cell affinity was recorded. The only possible choice\n\t\t// is to set all the devices affine to node 0.\n\t\tdevsPerNuma[0] = entryV1.DeviceIDs\n\t\tpodDevs = append(podDevs, PodDevicesEntry{\n\t\t\tPodUID: entryV1.PodUID,\n\t\t\tContainerName: entryV1.ContainerName,\n\t\t\tResourceName: entryV1.ResourceName,\n\t\t\tDeviceIDs: devsPerNuma,\n\t\t\tAllocResp: entryV1.AllocResp,\n\t\t})\n\t}\n\treturn podDevs, cp.Data.RegisteredDevices\n}","line":{"from":106,"to":124}} {"id":100005857,"name":"newEndpointImpl","signature":"func newEndpointImpl(p plugin.DevicePlugin) *endpointImpl","file":"pkg/kubelet/cm/devicemanager/endpoint.go","code":"// newEndpointImpl creates a new endpoint for the given resourceName.\n// This is to be used during normal device plugin registration.\nfunc newEndpointImpl(p plugin.DevicePlugin) *endpointImpl {\n\treturn \u0026endpointImpl{\n\t\tapi: p.API(),\n\t\tresourceName: p.Resource(),\n\t}\n}","line":{"from":49,"to":56}} {"id":100005858,"name":"newStoppedEndpointImpl","signature":"func newStoppedEndpointImpl(resourceName string) *endpointImpl","file":"pkg/kubelet/cm/devicemanager/endpoint.go","code":"// newStoppedEndpointImpl creates a new endpoint for the given resourceName with stopTime set.\n// This is to be used during Kubelet restart, before the actual device plugin re-registers.\nfunc newStoppedEndpointImpl(resourceName string) *endpointImpl {\n\treturn \u0026endpointImpl{\n\t\tresourceName: resourceName,\n\t\tstopTime: time.Now(),\n\t}\n}","line":{"from":58,"to":65}} {"id":100005859,"name":"isStopped","signature":"func (e *endpointImpl) isStopped() bool","file":"pkg/kubelet/cm/devicemanager/endpoint.go","code":"func (e *endpointImpl) isStopped() bool {\n\te.mutex.Lock()\n\tdefer e.mutex.Unlock()\n\treturn !e.stopTime.IsZero()\n}","line":{"from":67,"to":71}} {"id":100005860,"name":"stopGracePeriodExpired","signature":"func (e *endpointImpl) stopGracePeriodExpired() bool","file":"pkg/kubelet/cm/devicemanager/endpoint.go","code":"func (e *endpointImpl) stopGracePeriodExpired() bool {\n\te.mutex.Lock()\n\tdefer e.mutex.Unlock()\n\treturn !e.stopTime.IsZero() \u0026\u0026 time.Since(e.stopTime) \u003e endpointStopGracePeriod\n}","line":{"from":73,"to":77}} {"id":100005861,"name":"setStopTime","signature":"func (e *endpointImpl) setStopTime(t time.Time)","file":"pkg/kubelet/cm/devicemanager/endpoint.go","code":"func (e *endpointImpl) setStopTime(t time.Time) {\n\te.mutex.Lock()\n\tdefer e.mutex.Unlock()\n\te.stopTime = t\n}","line":{"from":79,"to":83}} {"id":100005862,"name":"getPreferredAllocation","signature":"func (e *endpointImpl) getPreferredAllocation(available, mustInclude []string, size int) (*pluginapi.PreferredAllocationResponse, error)","file":"pkg/kubelet/cm/devicemanager/endpoint.go","code":"// getPreferredAllocation issues GetPreferredAllocation gRPC call to the device plugin.\nfunc (e *endpointImpl) getPreferredAllocation(available, mustInclude []string, size int) (*pluginapi.PreferredAllocationResponse, error) {\n\tif e.isStopped() {\n\t\treturn nil, fmt.Errorf(errEndpointStopped, e)\n\t}\n\treturn e.api.GetPreferredAllocation(context.Background(), \u0026pluginapi.PreferredAllocationRequest{\n\t\tContainerRequests: []*pluginapi.ContainerPreferredAllocationRequest{\n\t\t\t{\n\t\t\t\tAvailableDeviceIDs: available,\n\t\t\t\tMustIncludeDeviceIDs: mustInclude,\n\t\t\t\tAllocationSize: int32(size),\n\t\t\t},\n\t\t},\n\t})\n}","line":{"from":85,"to":99}} {"id":100005863,"name":"allocate","signature":"func (e *endpointImpl) allocate(devs []string) (*pluginapi.AllocateResponse, error)","file":"pkg/kubelet/cm/devicemanager/endpoint.go","code":"// allocate issues Allocate gRPC call to the device plugin.\nfunc (e *endpointImpl) allocate(devs []string) (*pluginapi.AllocateResponse, error) {\n\tif e.isStopped() {\n\t\treturn nil, fmt.Errorf(errEndpointStopped, e)\n\t}\n\treturn e.api.Allocate(context.Background(), \u0026pluginapi.AllocateRequest{\n\t\tContainerRequests: []*pluginapi.ContainerAllocateRequest{\n\t\t\t{DevicesIDs: devs},\n\t\t},\n\t})\n}","line":{"from":101,"to":111}} {"id":100005864,"name":"preStartContainer","signature":"func (e *endpointImpl) preStartContainer(devs []string) (*pluginapi.PreStartContainerResponse, error)","file":"pkg/kubelet/cm/devicemanager/endpoint.go","code":"// preStartContainer issues PreStartContainer gRPC call to the device plugin.\nfunc (e *endpointImpl) preStartContainer(devs []string) (*pluginapi.PreStartContainerResponse, error) {\n\tif e.isStopped() {\n\t\treturn nil, fmt.Errorf(errEndpointStopped, e)\n\t}\n\tctx, cancel := context.WithTimeout(context.Background(), pluginapi.KubeletPreStartContainerRPCTimeoutInSecs*time.Second)\n\tdefer cancel()\n\treturn e.api.PreStartContainer(ctx, \u0026pluginapi.PreStartContainerRequest{\n\t\tDevicesIDs: devs,\n\t})\n}","line":{"from":113,"to":123}} {"id":100005865,"name":"AddSource","signature":"func (s *sourcesReadyStub) AddSource(source string) {}","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"func (s *sourcesReadyStub) AddSource(source string) {}","line":{"from":112,"to":112}} {"id":100005866,"name":"AllReady","signature":"func (s *sourcesReadyStub) AllReady() bool { return true }","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"func (s *sourcesReadyStub) AllReady() bool { return true }","line":{"from":113,"to":113}} {"id":100005867,"name":"NewManagerImpl","signature":"func NewManagerImpl(topology []cadvisorapi.Node, topologyAffinityStore topologymanager.Store) (*ManagerImpl, error)","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"// NewManagerImpl creates a new manager.\nfunc NewManagerImpl(topology []cadvisorapi.Node, topologyAffinityStore topologymanager.Store) (*ManagerImpl, error) {\n\tsocketPath := pluginapi.KubeletSocket\n\tif runtime.GOOS == \"windows\" {\n\t\tsocketPath = os.Getenv(\"SYSTEMDRIVE\") + pluginapi.KubeletSocketWindows\n\t}\n\treturn newManagerImpl(socketPath, topology, topologyAffinityStore)\n}","line":{"from":115,"to":122}} {"id":100005868,"name":"newManagerImpl","signature":"func newManagerImpl(socketPath string, topology []cadvisorapi.Node, topologyAffinityStore topologymanager.Store) (*ManagerImpl, error)","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"func newManagerImpl(socketPath string, topology []cadvisorapi.Node, topologyAffinityStore topologymanager.Store) (*ManagerImpl, error) {\n\tklog.V(2).InfoS(\"Creating Device Plugin manager\", \"path\", socketPath)\n\n\tvar numaNodes []int\n\tfor _, node := range topology {\n\t\tnumaNodes = append(numaNodes, node.Id)\n\t}\n\n\tmanager := \u0026ManagerImpl{\n\t\tendpoints: make(map[string]endpointInfo),\n\n\t\tallDevices: NewResourceDeviceInstances(),\n\t\thealthyDevices: make(map[string]sets.String),\n\t\tunhealthyDevices: make(map[string]sets.String),\n\t\tallocatedDevices: make(map[string]sets.String),\n\t\tpodDevices: newPodDevices(),\n\t\tnumaNodes: numaNodes,\n\t\ttopologyAffinityStore: topologyAffinityStore,\n\t\tdevicesToReuse: make(PodReusableDevices),\n\t}\n\n\tserver, err := plugin.NewServer(socketPath, manager, manager)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create plugin server: %v\", err)\n\t}\n\n\tmanager.server = server\n\tmanager.checkpointdir, _ = filepath.Split(server.SocketPath())\n\n\t// The following structures are populated with real implementations in manager.Start()\n\t// Before that, initializes them to perform no-op operations.\n\tmanager.activePods = func() []*v1.Pod { return []*v1.Pod{} }\n\tmanager.sourcesReady = \u0026sourcesReadyStub{}\n\tcheckpointManager, err := checkpointmanager.NewCheckpointManager(manager.checkpointdir)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize checkpoint manager: %v\", err)\n\t}\n\tmanager.checkpointManager = checkpointManager\n\n\treturn manager, nil\n}","line":{"from":124,"to":164}} {"id":100005869,"name":"CleanupPluginDirectory","signature":"func (m *ManagerImpl) CleanupPluginDirectory(dir string) error","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"// CleanupPluginDirectory is to remove all existing unix sockets\n// from /var/lib/kubelet/device-plugins on Device Plugin Manager start\nfunc (m *ManagerImpl) CleanupPluginDirectory(dir string) error {\n\td, err := os.Open(dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer d.Close()\n\tnames, err := d.Readdirnames(-1)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar errs []error\n\tfor _, name := range names {\n\t\tfilePath := filepath.Join(dir, name)\n\t\tif filePath == m.checkpointFile() {\n\t\t\tcontinue\n\t\t}\n\t\t// TODO: Until the bug - https://github.com/golang/go/issues/33357 is fixed, os.stat wouldn't return the\n\t\t// right mode(socket) on windows. Hence deleting the file, without checking whether\n\t\t// its a socket, on windows.\n\t\tstat, err := os.Lstat(filePath)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to stat file\", \"path\", filePath)\n\t\t\tcontinue\n\t\t}\n\t\tif stat.IsDir() {\n\t\t\tcontinue\n\t\t}\n\t\terr = os.RemoveAll(filePath)\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t\tklog.ErrorS(err, \"Failed to remove file\", \"path\", filePath)\n\t\t\tcontinue\n\t\t}\n\t}\n\treturn errorsutil.NewAggregate(errs)\n}","line":{"from":166,"to":203}} {"id":100005870,"name":"PluginConnected","signature":"func (m *ManagerImpl) PluginConnected(resourceName string, p plugin.DevicePlugin) error","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"// PluginConnected is to connect a plugin to a new endpoint.\n// This is done as part of device plugin registration.\nfunc (m *ManagerImpl) PluginConnected(resourceName string, p plugin.DevicePlugin) error {\n\toptions, err := p.API().GetDevicePluginOptions(context.Background(), \u0026pluginapi.Empty{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get device plugin options: %v\", err)\n\t}\n\n\te := newEndpointImpl(p)\n\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\tm.endpoints[resourceName] = endpointInfo{e, options}\n\n\treturn nil\n}","line":{"from":205,"to":220}} {"id":100005871,"name":"PluginDisconnected","signature":"func (m *ManagerImpl) PluginDisconnected(resourceName string)","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"// PluginDisconnected is to disconnect a plugin from an endpoint.\n// This is done as part of device plugin deregistration.\nfunc (m *ManagerImpl) PluginDisconnected(resourceName string) {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\tif _, exists := m.endpoints[resourceName]; exists {\n\t\tm.markResourceUnhealthy(resourceName)\n\t\tklog.V(2).InfoS(\"Endpoint became unhealthy\", \"resourceName\", resourceName, \"endpoint\", m.endpoints[resourceName])\n\t}\n\n\tm.endpoints[resourceName].e.setStopTime(time.Now())\n}","line":{"from":222,"to":234}} {"id":100005872,"name":"PluginListAndWatchReceiver","signature":"func (m *ManagerImpl) PluginListAndWatchReceiver(resourceName string, resp *pluginapi.ListAndWatchResponse)","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"// PluginListAndWatchReceiver receives ListAndWatchResponse from a device plugin\n// and ensures that an upto date state (e.g. number of devices and device health)\n// is captured. Also, registered device and device to container allocation\n// information is checkpointed to the disk.\nfunc (m *ManagerImpl) PluginListAndWatchReceiver(resourceName string, resp *pluginapi.ListAndWatchResponse) {\n\tvar devices []pluginapi.Device\n\tfor _, d := range resp.Devices {\n\t\tdevices = append(devices, *d)\n\t}\n\tm.genericDeviceUpdateCallback(resourceName, devices)\n}","line":{"from":236,"to":246}} {"id":100005873,"name":"genericDeviceUpdateCallback","signature":"func (m *ManagerImpl) genericDeviceUpdateCallback(resourceName string, devices []pluginapi.Device)","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"func (m *ManagerImpl) genericDeviceUpdateCallback(resourceName string, devices []pluginapi.Device) {\n\tm.mutex.Lock()\n\tm.healthyDevices[resourceName] = sets.NewString()\n\tm.unhealthyDevices[resourceName] = sets.NewString()\n\tm.allDevices[resourceName] = make(map[string]pluginapi.Device)\n\tfor _, dev := range devices {\n\t\tm.allDevices[resourceName][dev.ID] = dev\n\t\tif dev.Health == pluginapi.Healthy {\n\t\t\tm.healthyDevices[resourceName].Insert(dev.ID)\n\t\t} else {\n\t\t\tm.unhealthyDevices[resourceName].Insert(dev.ID)\n\t\t}\n\t}\n\tm.mutex.Unlock()\n\tif err := m.writeCheckpoint(); err != nil {\n\t\tklog.ErrorS(err, \"Writing checkpoint encountered\")\n\t}\n}","line":{"from":248,"to":265}} {"id":100005874,"name":"GetWatcherHandler","signature":"func (m *ManagerImpl) GetWatcherHandler() cache.PluginHandler","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"// GetWatcherHandler returns the plugin handler\nfunc (m *ManagerImpl) GetWatcherHandler() cache.PluginHandler {\n\treturn m.server\n}","line":{"from":267,"to":270}} {"id":100005875,"name":"checkpointFile","signature":"func (m *ManagerImpl) checkpointFile() string","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"// checkpointFile returns device plugin checkpoint file path.\nfunc (m *ManagerImpl) checkpointFile() string {\n\treturn filepath.Join(m.checkpointdir, kubeletDeviceManagerCheckpoint)\n}","line":{"from":272,"to":275}} {"id":100005876,"name":"Start","signature":"func (m *ManagerImpl) Start(activePods ActivePodsFunc, sourcesReady config.SourcesReady) error","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"// Start starts the Device Plugin Manager and start initialization of\n// podDevices and allocatedDevices information from checkpointed state and\n// starts device plugin registration service.\nfunc (m *ManagerImpl) Start(activePods ActivePodsFunc, sourcesReady config.SourcesReady) error {\n\tklog.V(2).InfoS(\"Starting Device Plugin manager\")\n\n\tm.activePods = activePods\n\tm.sourcesReady = sourcesReady\n\n\t// Loads in allocatedDevices information from disk.\n\terr := m.readCheckpoint()\n\tif err != nil {\n\t\tklog.InfoS(\"Continue after failing to read checkpoint file. Device allocation info may NOT be up-to-date\", \"err\", err)\n\t}\n\n\treturn m.server.Start()\n}","line":{"from":277,"to":293}} {"id":100005877,"name":"Stop","signature":"func (m *ManagerImpl) Stop() error","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"// Stop is the function that can stop the plugin server.\n// Can be called concurrently, more than once, and is safe to call\n// without a prior Start.\nfunc (m *ManagerImpl) Stop() error {\n\treturn m.server.Stop()\n}","line":{"from":295,"to":300}} {"id":100005878,"name":"Allocate","signature":"func (m *ManagerImpl) Allocate(pod *v1.Pod, container *v1.Container) error","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"// Allocate is the call that you can use to allocate a set of devices\n// from the registered device plugins.\nfunc (m *ManagerImpl) Allocate(pod *v1.Pod, container *v1.Container) error {\n\t// The pod is during the admission phase. We need to save the pod to avoid it\n\t// being cleaned before the admission ended\n\tm.setPodPendingAdmission(pod)\n\n\tif _, ok := m.devicesToReuse[string(pod.UID)]; !ok {\n\t\tm.devicesToReuse[string(pod.UID)] = make(map[string]sets.String)\n\t}\n\t// If pod entries to m.devicesToReuse other than the current pod exist, delete them.\n\tfor podUID := range m.devicesToReuse {\n\t\tif podUID != string(pod.UID) {\n\t\t\tdelete(m.devicesToReuse, podUID)\n\t\t}\n\t}\n\t// Allocate resources for init containers first as we know the caller always loops\n\t// through init containers before looping through app containers. Should the caller\n\t// ever change those semantics, this logic will need to be amended.\n\tfor _, initContainer := range pod.Spec.InitContainers {\n\t\tif container.Name == initContainer.Name {\n\t\t\tif err := m.allocateContainerResources(pod, container, m.devicesToReuse[string(pod.UID)]); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tm.podDevices.addContainerAllocatedResources(string(pod.UID), container.Name, m.devicesToReuse[string(pod.UID)])\n\t\t\treturn nil\n\t\t}\n\t}\n\tif err := m.allocateContainerResources(pod, container, m.devicesToReuse[string(pod.UID)]); err != nil {\n\t\treturn err\n\t}\n\tm.podDevices.removeContainerAllocatedResources(string(pod.UID), container.Name, m.devicesToReuse[string(pod.UID)])\n\treturn nil\n}","line":{"from":302,"to":335}} {"id":100005879,"name":"UpdatePluginResources","signature":"func (m *ManagerImpl) UpdatePluginResources(node *schedulerframework.NodeInfo, attrs *lifecycle.PodAdmitAttributes) error","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"// UpdatePluginResources updates node resources based on devices already allocated to pods.\nfunc (m *ManagerImpl) UpdatePluginResources(node *schedulerframework.NodeInfo, attrs *lifecycle.PodAdmitAttributes) error {\n\tpod := attrs.Pod\n\n\t// quick return if no pluginResources requested\n\tif !m.podDevices.hasPod(string(pod.UID)) {\n\t\treturn nil\n\t}\n\n\tm.sanitizeNodeAllocatable(node)\n\treturn nil\n}","line":{"from":337,"to":348}} {"id":100005880,"name":"markResourceUnhealthy","signature":"func (m *ManagerImpl) markResourceUnhealthy(resourceName string)","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"func (m *ManagerImpl) markResourceUnhealthy(resourceName string) {\n\tklog.V(2).InfoS(\"Mark all resources Unhealthy for resource\", \"resourceName\", resourceName)\n\thealthyDevices := sets.NewString()\n\tif _, ok := m.healthyDevices[resourceName]; ok {\n\t\thealthyDevices = m.healthyDevices[resourceName]\n\t\tm.healthyDevices[resourceName] = sets.NewString()\n\t}\n\tif _, ok := m.unhealthyDevices[resourceName]; !ok {\n\t\tm.unhealthyDevices[resourceName] = sets.NewString()\n\t}\n\tm.unhealthyDevices[resourceName] = m.unhealthyDevices[resourceName].Union(healthyDevices)\n}","line":{"from":350,"to":361}} {"id":100005881,"name":"GetCapacity","signature":"func (m *ManagerImpl) GetCapacity() (v1.ResourceList, v1.ResourceList, []string)","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"// GetCapacity is expected to be called when Kubelet updates its node status.\n// The first returned variable contains the registered device plugin resource capacity.\n// The second returned variable contains the registered device plugin resource allocatable.\n// The third returned variable contains previously registered resources that are no longer active.\n// Kubelet uses this information to update resource capacity/allocatable in its node status.\n// After the call, device plugin can remove the inactive resources from its internal list as the\n// change is already reflected in Kubelet node status.\n// Note in the special case after Kubelet restarts, device plugin resource capacities can\n// temporarily drop to zero till corresponding device plugins re-register. This is OK because\n// cm.UpdatePluginResource() run during predicate Admit guarantees we adjust nodeinfo\n// capacity for already allocated pods so that they can continue to run. However, new pods\n// requiring device plugin resources will not be scheduled till device plugin re-registers.\nfunc (m *ManagerImpl) GetCapacity() (v1.ResourceList, v1.ResourceList, []string) {\n\tneedsUpdateCheckpoint := false\n\tvar capacity = v1.ResourceList{}\n\tvar allocatable = v1.ResourceList{}\n\tdeletedResources := sets.NewString()\n\tm.mutex.Lock()\n\tfor resourceName, devices := range m.healthyDevices {\n\t\teI, ok := m.endpoints[resourceName]\n\t\tif (ok \u0026\u0026 eI.e.stopGracePeriodExpired()) || !ok {\n\t\t\t// The resources contained in endpoints and (un)healthyDevices\n\t\t\t// should always be consistent. Otherwise, we run with the risk\n\t\t\t// of failing to garbage collect non-existing resources or devices.\n\t\t\tif !ok {\n\t\t\t\tklog.ErrorS(nil, \"Unexpected: healthyDevices and endpoints are out of sync\")\n\t\t\t}\n\t\t\tdelete(m.endpoints, resourceName)\n\t\t\tdelete(m.healthyDevices, resourceName)\n\t\t\tdeletedResources.Insert(resourceName)\n\t\t\tneedsUpdateCheckpoint = true\n\t\t} else {\n\t\t\tcapacity[v1.ResourceName(resourceName)] = *resource.NewQuantity(int64(devices.Len()), resource.DecimalSI)\n\t\t\tallocatable[v1.ResourceName(resourceName)] = *resource.NewQuantity(int64(devices.Len()), resource.DecimalSI)\n\t\t}\n\t}\n\tfor resourceName, devices := range m.unhealthyDevices {\n\t\teI, ok := m.endpoints[resourceName]\n\t\tif (ok \u0026\u0026 eI.e.stopGracePeriodExpired()) || !ok {\n\t\t\tif !ok {\n\t\t\t\tklog.ErrorS(nil, \"Unexpected: unhealthyDevices and endpoints are out of sync\")\n\t\t\t}\n\t\t\tdelete(m.endpoints, resourceName)\n\t\t\tdelete(m.unhealthyDevices, resourceName)\n\t\t\tdeletedResources.Insert(resourceName)\n\t\t\tneedsUpdateCheckpoint = true\n\t\t} else {\n\t\t\tcapacityCount := capacity[v1.ResourceName(resourceName)]\n\t\t\tunhealthyCount := *resource.NewQuantity(int64(devices.Len()), resource.DecimalSI)\n\t\t\tcapacityCount.Add(unhealthyCount)\n\t\t\tcapacity[v1.ResourceName(resourceName)] = capacityCount\n\t\t}\n\t}\n\tm.mutex.Unlock()\n\tif needsUpdateCheckpoint {\n\t\tif err := m.writeCheckpoint(); err != nil {\n\t\t\tklog.ErrorS(err, \"Error on writing checkpoint\")\n\t\t}\n\t}\n\treturn capacity, allocatable, deletedResources.UnsortedList()\n}","line":{"from":363,"to":423}} {"id":100005882,"name":"writeCheckpoint","signature":"func (m *ManagerImpl) writeCheckpoint() error","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"// Checkpoints device to container allocation information to disk.\nfunc (m *ManagerImpl) writeCheckpoint() error {\n\tm.mutex.Lock()\n\tregisteredDevs := make(map[string][]string)\n\tfor resource, devices := range m.healthyDevices {\n\t\tregisteredDevs[resource] = devices.UnsortedList()\n\t}\n\tdata := checkpoint.New(m.podDevices.toCheckpointData(),\n\t\tregisteredDevs)\n\tm.mutex.Unlock()\n\terr := m.checkpointManager.CreateCheckpoint(kubeletDeviceManagerCheckpoint, data)\n\tif err != nil {\n\t\terr2 := fmt.Errorf(\"failed to write checkpoint file %q: %v\", kubeletDeviceManagerCheckpoint, err)\n\t\tklog.InfoS(\"Failed to write checkpoint file\", \"err\", err)\n\t\treturn err2\n\t}\n\treturn nil\n}","line":{"from":425,"to":442}} {"id":100005883,"name":"readCheckpoint","signature":"func (m *ManagerImpl) readCheckpoint() error","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"// Reads device to container allocation information from disk, and populates\n// m.allocatedDevices accordingly.\nfunc (m *ManagerImpl) readCheckpoint() error {\n\t// the vast majority of time we restore a compatible checkpoint, so we try\n\t// the current version first. Trying to restore older format checkpoints is\n\t// relevant only in the kubelet upgrade flow, which happens once in a\n\t// (long) while.\n\tcp, err := m.getCheckpointV2()\n\tif err != nil {\n\t\tif err == errors.ErrCheckpointNotFound {\n\t\t\t// no point in trying anything else\n\t\t\tklog.InfoS(\"Failed to read data from checkpoint\", \"checkpoint\", kubeletDeviceManagerCheckpoint, \"err\", err)\n\t\t\treturn nil\n\t\t}\n\n\t\tvar errv1 error\n\t\t// one last try: maybe it's a old format checkpoint?\n\t\tcp, errv1 = m.getCheckpointV1()\n\t\tif errv1 != nil {\n\t\t\tklog.InfoS(\"Failed to read checkpoint V1 file\", \"err\", errv1)\n\t\t\t// intentionally return the parent error. We expect to restore V1 checkpoints\n\t\t\t// a tiny fraction of time, so what matters most is the current checkpoint read error.\n\t\t\treturn err\n\t\t}\n\t\tklog.InfoS(\"Read data from a V1 checkpoint\", \"checkpoint\", kubeletDeviceManagerCheckpoint)\n\t}\n\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\tpodDevices, registeredDevs := cp.GetDataInLatestFormat()\n\tm.podDevices.fromCheckpointData(podDevices)\n\tm.allocatedDevices = m.podDevices.devices()\n\tfor resource := range registeredDevs {\n\t\t// During start up, creates empty healthyDevices list so that the resource capacity\n\t\t// will stay zero till the corresponding device plugin re-registers.\n\t\tm.healthyDevices[resource] = sets.NewString()\n\t\tm.unhealthyDevices[resource] = sets.NewString()\n\t\tm.endpoints[resource] = endpointInfo{e: newStoppedEndpointImpl(resource), opts: nil}\n\t}\n\treturn nil\n}","line":{"from":444,"to":484}} {"id":100005884,"name":"getCheckpointV2","signature":"func (m *ManagerImpl) getCheckpointV2() (checkpoint.DeviceManagerCheckpoint, error)","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"func (m *ManagerImpl) getCheckpointV2() (checkpoint.DeviceManagerCheckpoint, error) {\n\tregisteredDevs := make(map[string][]string)\n\tdevEntries := make([]checkpoint.PodDevicesEntry, 0)\n\tcp := checkpoint.New(devEntries, registeredDevs)\n\terr := m.checkpointManager.GetCheckpoint(kubeletDeviceManagerCheckpoint, cp)\n\treturn cp, err\n}","line":{"from":486,"to":492}} {"id":100005885,"name":"getCheckpointV1","signature":"func (m *ManagerImpl) getCheckpointV1() (checkpoint.DeviceManagerCheckpoint, error)","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"func (m *ManagerImpl) getCheckpointV1() (checkpoint.DeviceManagerCheckpoint, error) {\n\tregisteredDevs := make(map[string][]string)\n\tdevEntries := make([]checkpoint.PodDevicesEntryV1, 0)\n\tcp := checkpoint.NewV1(devEntries, registeredDevs)\n\terr := m.checkpointManager.GetCheckpoint(kubeletDeviceManagerCheckpoint, cp)\n\treturn cp, err\n}","line":{"from":494,"to":500}} {"id":100005886,"name":"UpdateAllocatedDevices","signature":"func (m *ManagerImpl) UpdateAllocatedDevices()","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"// UpdateAllocatedDevices frees any Devices that are bound to terminated pods.\nfunc (m *ManagerImpl) UpdateAllocatedDevices() {\n\tif !m.sourcesReady.AllReady() {\n\t\treturn\n\t}\n\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\tactiveAndAdmittedPods := m.activePods()\n\tif m.pendingAdmissionPod != nil {\n\t\tactiveAndAdmittedPods = append(activeAndAdmittedPods, m.pendingAdmissionPod)\n\t}\n\n\tpodsToBeRemoved := m.podDevices.pods()\n\tfor _, pod := range activeAndAdmittedPods {\n\t\tpodsToBeRemoved.Delete(string(pod.UID))\n\t}\n\tif len(podsToBeRemoved) \u003c= 0 {\n\t\treturn\n\t}\n\tklog.V(3).InfoS(\"Pods to be removed\", \"podUIDs\", podsToBeRemoved.List())\n\tm.podDevices.delete(podsToBeRemoved.List())\n\t// Regenerated allocatedDevices after we update pod allocation information.\n\tm.allocatedDevices = m.podDevices.devices()\n}","line":{"from":502,"to":527}} {"id":100005887,"name":"devicesToAllocate","signature":"func (m *ManagerImpl) devicesToAllocate(podUID, contName, resource string, required int, reusableDevices sets.String) (sets.String, error)","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"// Returns list of device Ids we need to allocate with Allocate rpc call.\n// Returns empty list in case we don't need to issue the Allocate rpc call.\nfunc (m *ManagerImpl) devicesToAllocate(podUID, contName, resource string, required int, reusableDevices sets.String) (sets.String, error) {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\tneeded := required\n\t// Gets list of devices that have already been allocated.\n\t// This can happen if a container restarts for example.\n\tdevices := m.podDevices.containerDevices(podUID, contName, resource)\n\tif devices != nil {\n\t\tklog.V(3).InfoS(\"Found pre-allocated devices for resource on pod\", \"resourceName\", resource, \"containerName\", contName, \"podUID\", string(podUID), \"devices\", devices.List())\n\t\tneeded = needed - devices.Len()\n\t\t// A pod's resource is not expected to change once admitted by the API server,\n\t\t// so just fail loudly here. We can revisit this part if this no longer holds.\n\t\tif needed != 0 {\n\t\t\treturn nil, fmt.Errorf(\"pod %q container %q changed request for resource %q from %d to %d\", string(podUID), contName, resource, devices.Len(), required)\n\t\t}\n\t}\n\n\tklog.V(3).InfoS(\"Need devices to allocate for pod\", \"deviceNumber\", needed, \"resourceName\", resource, \"podUID\", string(podUID), \"containerName\", contName)\n\thealthyDevices, hasRegistered := m.healthyDevices[resource]\n\n\t// Check if resource registered with devicemanager\n\tif !hasRegistered {\n\t\treturn nil, fmt.Errorf(\"cannot allocate unregistered device %s\", resource)\n\t}\n\n\t// Check if registered resource has healthy devices\n\tif healthyDevices.Len() == 0 {\n\t\treturn nil, fmt.Errorf(\"no healthy devices present; cannot allocate unhealthy devices %s\", resource)\n\t}\n\n\t// Check if all the previously allocated devices are healthy\n\tif !healthyDevices.IsSuperset(devices) {\n\t\treturn nil, fmt.Errorf(\"previously allocated devices are no longer healthy; cannot allocate unhealthy devices %s\", resource)\n\t}\n\n\tif needed == 0 {\n\t\t// No change, no work.\n\t\treturn nil, nil\n\t}\n\n\t// Declare the list of allocated devices.\n\t// This will be populated and returned below.\n\tallocated := sets.NewString()\n\n\t// Create a closure to help with device allocation\n\t// Returns 'true' once no more devices need to be allocated.\n\tallocateRemainingFrom := func(devices sets.String) bool {\n\t\tfor device := range devices.Difference(allocated) {\n\t\t\tm.allocatedDevices[resource].Insert(device)\n\t\t\tallocated.Insert(device)\n\t\t\tneeded--\n\t\t\tif needed == 0 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\t// Needs to allocate additional devices.\n\tif m.allocatedDevices[resource] == nil {\n\t\tm.allocatedDevices[resource] = sets.NewString()\n\t}\n\n\t// Allocates from reusableDevices list first.\n\tif allocateRemainingFrom(reusableDevices) {\n\t\treturn allocated, nil\n\t}\n\n\t// Gets Devices in use.\n\tdevicesInUse := m.allocatedDevices[resource]\n\t// Gets Available devices.\n\tavailable := m.healthyDevices[resource].Difference(devicesInUse)\n\tif available.Len() \u003c needed {\n\t\treturn nil, fmt.Errorf(\"requested number of devices unavailable for %s. Requested: %d, Available: %d\", resource, needed, available.Len())\n\t}\n\n\t// Filters available Devices based on NUMA affinity.\n\taligned, unaligned, noAffinity := m.filterByAffinity(podUID, contName, resource, available)\n\n\t// If we can allocate all remaining devices from the set of aligned ones, then\n\t// give the plugin the chance to influence which ones to allocate from that set.\n\tif needed \u003c aligned.Len() {\n\t\t// First allocate from the preferred devices list (if available).\n\t\tpreferred, err := m.callGetPreferredAllocationIfAvailable(podUID, contName, resource, aligned.Union(allocated), allocated, required)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif allocateRemainingFrom(preferred.Intersection(aligned)) {\n\t\t\treturn allocated, nil\n\t\t}\n\t\t// Then fallback to allocate from the aligned set if no preferred list\n\t\t// is returned (or not enough devices are returned in that list).\n\t\tif allocateRemainingFrom(aligned) {\n\t\t\treturn allocated, nil\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"unexpectedly allocated less resources than required. Requested: %d, Got: %d\", required, required-needed)\n\t}\n\n\t// If we can't allocate all remaining devices from the set of aligned ones,\n\t// then start by first allocating all of the aligned devices (to ensure\n\t// that the alignment guaranteed by the TopologyManager is honored).\n\tif allocateRemainingFrom(aligned) {\n\t\treturn allocated, nil\n\t}\n\n\t// Then give the plugin the chance to influence the decision on any\n\t// remaining devices to allocate.\n\tpreferred, err := m.callGetPreferredAllocationIfAvailable(podUID, contName, resource, available.Union(allocated), allocated, required)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif allocateRemainingFrom(preferred.Intersection(available)) {\n\t\treturn allocated, nil\n\t}\n\n\t// Finally, if the plugin did not return a preferred allocation (or didn't\n\t// return a large enough one), then fall back to allocating the remaining\n\t// devices from the 'unaligned' and 'noAffinity' sets.\n\tif allocateRemainingFrom(unaligned) {\n\t\treturn allocated, nil\n\t}\n\tif allocateRemainingFrom(noAffinity) {\n\t\treturn allocated, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"unexpectedly allocated less resources than required. Requested: %d, Got: %d\", required, required-needed)\n}","line":{"from":529,"to":658}} {"id":100005888,"name":"filterByAffinity","signature":"func (m *ManagerImpl) filterByAffinity(podUID, contName, resource string, available sets.String) (sets.String, sets.String, sets.String)","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"func (m *ManagerImpl) filterByAffinity(podUID, contName, resource string, available sets.String) (sets.String, sets.String, sets.String) {\n\t// If alignment information is not available, just pass the available list back.\n\thint := m.topologyAffinityStore.GetAffinity(podUID, contName)\n\tif !m.deviceHasTopologyAlignment(resource) || hint.NUMANodeAffinity == nil {\n\t\treturn sets.NewString(), sets.NewString(), available\n\t}\n\n\t// Build a map of NUMA Nodes to the devices associated with them. A\n\t// device may be associated to multiple NUMA nodes at the same time. If an\n\t// available device does not have any NUMA Nodes associated with it, add it\n\t// to a list of NUMA Nodes for the fake NUMANode -1.\n\tperNodeDevices := make(map[int]sets.String)\n\tfor d := range available {\n\t\tif m.allDevices[resource][d].Topology == nil || len(m.allDevices[resource][d].Topology.Nodes) == 0 {\n\t\t\tif _, ok := perNodeDevices[nodeWithoutTopology]; !ok {\n\t\t\t\tperNodeDevices[nodeWithoutTopology] = sets.NewString()\n\t\t\t}\n\t\t\tperNodeDevices[nodeWithoutTopology].Insert(d)\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, node := range m.allDevices[resource][d].Topology.Nodes {\n\t\t\tif _, ok := perNodeDevices[int(node.ID)]; !ok {\n\t\t\t\tperNodeDevices[int(node.ID)] = sets.NewString()\n\t\t\t}\n\t\t\tperNodeDevices[int(node.ID)].Insert(d)\n\t\t}\n\t}\n\n\t// Get a flat list of all of the nodes associated with available devices.\n\tvar nodes []int\n\tfor node := range perNodeDevices {\n\t\tnodes = append(nodes, node)\n\t}\n\n\t// Sort the list of nodes by:\n\t// 1) Nodes contained in the 'hint's affinity set\n\t// 2) Nodes not contained in the 'hint's affinity set\n\t// 3) The fake NUMANode of -1 (assuming it is included in the list)\n\t// Within each of the groups above, sort the nodes by how many devices they contain\n\tsort.Slice(nodes, func(i, j int) bool {\n\t\t// If one or the other of nodes[i] or nodes[j] is in the 'hint's affinity set\n\t\tif hint.NUMANodeAffinity.IsSet(nodes[i]) \u0026\u0026 hint.NUMANodeAffinity.IsSet(nodes[j]) {\n\t\t\treturn perNodeDevices[nodes[i]].Len() \u003c perNodeDevices[nodes[j]].Len()\n\t\t}\n\t\tif hint.NUMANodeAffinity.IsSet(nodes[i]) {\n\t\t\treturn true\n\t\t}\n\t\tif hint.NUMANodeAffinity.IsSet(nodes[j]) {\n\t\t\treturn false\n\t\t}\n\n\t\t// If one or the other of nodes[i] or nodes[j] is the fake NUMA node -1 (they can't both be)\n\t\tif nodes[i] == nodeWithoutTopology {\n\t\t\treturn false\n\t\t}\n\t\tif nodes[j] == nodeWithoutTopology {\n\t\t\treturn true\n\t\t}\n\n\t\t// Otherwise both nodes[i] and nodes[j] are real NUMA nodes that are not in the 'hint's' affinity list.\n\t\treturn perNodeDevices[nodes[i]].Len() \u003c perNodeDevices[nodes[j]].Len()\n\t})\n\n\t// Generate three sorted lists of devices. Devices in the first list come\n\t// from valid NUMA Nodes contained in the affinity mask. Devices in the\n\t// second list come from valid NUMA Nodes not in the affinity mask. Devices\n\t// in the third list come from devices with no NUMA Node association (i.e.\n\t// those mapped to the fake NUMA Node -1). Because we loop through the\n\t// sorted list of NUMA nodes in order, within each list, devices are sorted\n\t// by their connection to NUMA Nodes with more devices on them.\n\tvar fromAffinity []string\n\tvar notFromAffinity []string\n\tvar withoutTopology []string\n\tfor d := range available {\n\t\t// Since the same device may be associated with multiple NUMA Nodes. We\n\t\t// need to be careful not to add each device to multiple lists. The\n\t\t// logic below ensures this by breaking after the first NUMA node that\n\t\t// has the device is encountered.\n\t\tfor _, n := range nodes {\n\t\t\tif perNodeDevices[n].Has(d) {\n\t\t\t\tif n == nodeWithoutTopology {\n\t\t\t\t\twithoutTopology = append(withoutTopology, d)\n\t\t\t\t} else if hint.NUMANodeAffinity.IsSet(n) {\n\t\t\t\t\tfromAffinity = append(fromAffinity, d)\n\t\t\t\t} else {\n\t\t\t\t\tnotFromAffinity = append(notFromAffinity, d)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return all three lists containing the full set of devices across them.\n\treturn sets.NewString(fromAffinity...), sets.NewString(notFromAffinity...), sets.NewString(withoutTopology...)\n}","line":{"from":660,"to":755}} {"id":100005889,"name":"allocateContainerResources","signature":"func (m *ManagerImpl) allocateContainerResources(pod *v1.Pod, container *v1.Container, devicesToReuse map[string]sets.String) error","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"// allocateContainerResources attempts to allocate all of required device\n// plugin resources for the input container, issues an Allocate rpc request\n// for each new device resource requirement, processes their AllocateResponses,\n// and updates the cached containerDevices on success.\nfunc (m *ManagerImpl) allocateContainerResources(pod *v1.Pod, container *v1.Container, devicesToReuse map[string]sets.String) error {\n\tpodUID := string(pod.UID)\n\tcontName := container.Name\n\tallocatedDevicesUpdated := false\n\tneedsUpdateCheckpoint := false\n\t// Extended resources are not allowed to be overcommitted.\n\t// Since device plugin advertises extended resources,\n\t// therefore Requests must be equal to Limits and iterating\n\t// over the Limits should be sufficient.\n\tfor k, v := range container.Resources.Limits {\n\t\tresource := string(k)\n\t\tneeded := int(v.Value())\n\t\tklog.V(3).InfoS(\"Looking for needed resources\", \"needed\", needed, \"resourceName\", resource)\n\t\tif !m.isDevicePluginResource(resource) {\n\t\t\tcontinue\n\t\t}\n\t\t// Updates allocatedDevices to garbage collect any stranded resources\n\t\t// before doing the device plugin allocation.\n\t\tif !allocatedDevicesUpdated {\n\t\t\tm.UpdateAllocatedDevices()\n\t\t\tallocatedDevicesUpdated = true\n\t\t}\n\t\tallocDevices, err := m.devicesToAllocate(podUID, contName, resource, needed, devicesToReuse[resource])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif allocDevices == nil || len(allocDevices) \u003c= 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tneedsUpdateCheckpoint = true\n\n\t\tstartRPCTime := time.Now()\n\t\t// Manager.Allocate involves RPC calls to device plugin, which\n\t\t// could be heavy-weight. Therefore we want to perform this operation outside\n\t\t// mutex lock. Note if Allocate call fails, we may leave container resources\n\t\t// partially allocated for the failed container. We rely on UpdateAllocatedDevices()\n\t\t// to garbage collect these resources later. Another side effect is that if\n\t\t// we have X resource A and Y resource B in total, and two containers, container1\n\t\t// and container2 both require X resource A and Y resource B. Both allocation\n\t\t// requests may fail if we serve them in mixed order.\n\t\t// TODO: may revisit this part later if we see inefficient resource allocation\n\t\t// in real use as the result of this. Should also consider to parallelize device\n\t\t// plugin Allocate grpc calls if it becomes common that a container may require\n\t\t// resources from multiple device plugins.\n\t\tm.mutex.Lock()\n\t\teI, ok := m.endpoints[resource]\n\t\tm.mutex.Unlock()\n\t\tif !ok {\n\t\t\tm.mutex.Lock()\n\t\t\tm.allocatedDevices = m.podDevices.devices()\n\t\t\tm.mutex.Unlock()\n\t\t\treturn fmt.Errorf(\"unknown Device Plugin %s\", resource)\n\t\t}\n\n\t\tdevs := allocDevices.UnsortedList()\n\t\t// TODO: refactor this part of code to just append a ContainerAllocationRequest\n\t\t// in a passed in AllocateRequest pointer, and issues a single Allocate call per pod.\n\t\tklog.V(3).InfoS(\"Making allocation request for device plugin\", \"devices\", devs, \"resourceName\", resource)\n\t\tresp, err := eI.e.allocate(devs)\n\t\tmetrics.DevicePluginAllocationDuration.WithLabelValues(resource).Observe(metrics.SinceInSeconds(startRPCTime))\n\t\tif err != nil {\n\t\t\t// In case of allocation failure, we want to restore m.allocatedDevices\n\t\t\t// to the actual allocated state from m.podDevices.\n\t\t\tm.mutex.Lock()\n\t\t\tm.allocatedDevices = m.podDevices.devices()\n\t\t\tm.mutex.Unlock()\n\t\t\treturn err\n\t\t}\n\n\t\tif len(resp.ContainerResponses) == 0 {\n\t\t\treturn fmt.Errorf(\"no containers return in allocation response %v\", resp)\n\t\t}\n\n\t\tallocDevicesWithNUMA := checkpoint.NewDevicesPerNUMA()\n\t\t// Update internal cached podDevices state.\n\t\tm.mutex.Lock()\n\t\tfor dev := range allocDevices {\n\t\t\tif m.allDevices[resource][dev].Topology == nil || len(m.allDevices[resource][dev].Topology.Nodes) == 0 {\n\t\t\t\tallocDevicesWithNUMA[nodeWithoutTopology] = append(allocDevicesWithNUMA[nodeWithoutTopology], dev)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor idx := range m.allDevices[resource][dev].Topology.Nodes {\n\t\t\t\tnode := m.allDevices[resource][dev].Topology.Nodes[idx]\n\t\t\t\tallocDevicesWithNUMA[node.ID] = append(allocDevicesWithNUMA[node.ID], dev)\n\t\t\t}\n\t\t}\n\t\tm.mutex.Unlock()\n\t\tm.podDevices.insert(podUID, contName, resource, allocDevicesWithNUMA, resp.ContainerResponses[0])\n\t}\n\n\tif needsUpdateCheckpoint {\n\t\treturn m.writeCheckpoint()\n\t}\n\n\treturn nil\n}","line":{"from":757,"to":857}} {"id":100005890,"name":"checkPodActive","signature":"func (m *ManagerImpl) checkPodActive(pod *v1.Pod) bool","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"// checkPodActive checks if the given pod is still in activePods list\nfunc (m *ManagerImpl) checkPodActive(pod *v1.Pod) bool {\n\tactivePods := m.activePods()\n\tfor _, activePod := range activePods {\n\t\tif activePod.UID == pod.UID {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":859,"to":869}} {"id":100005891,"name":"GetDeviceRunContainerOptions","signature":"func (m *ManagerImpl) GetDeviceRunContainerOptions(pod *v1.Pod, container *v1.Container) (*DeviceRunContainerOptions, error)","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"// GetDeviceRunContainerOptions checks whether we have cached containerDevices\n// for the passed-in \u003cpod, container\u003e and returns its DeviceRunContainerOptions\n// for the found one. An empty struct is returned in case no cached state is found.\nfunc (m *ManagerImpl) GetDeviceRunContainerOptions(pod *v1.Pod, container *v1.Container) (*DeviceRunContainerOptions, error) {\n\tpodUID := string(pod.UID)\n\tcontName := container.Name\n\tneedsReAllocate := false\n\tfor k, v := range container.Resources.Limits {\n\t\tresource := string(k)\n\t\tif !m.isDevicePluginResource(resource) || v.Value() == 0 {\n\t\t\tcontinue\n\t\t}\n\t\terr := m.callPreStartContainerIfNeeded(podUID, contName, resource)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif !m.checkPodActive(pod) {\n\t\t\tklog.ErrorS(nil, \"pod deleted from activePods, skip to reAllocate\", \"podUID\", podUID)\n\t\t\tcontinue\n\t\t}\n\n\t\t// This is a device plugin resource yet we don't have cached\n\t\t// resource state. This is likely due to a race during node\n\t\t// restart. We re-issue allocate request to cover this race.\n\t\tif m.podDevices.containerDevices(podUID, contName, resource) == nil {\n\t\t\tneedsReAllocate = true\n\t\t}\n\t}\n\tif needsReAllocate {\n\t\tklog.V(2).InfoS(\"Needs to re-allocate device plugin resources for pod\", \"pod\", klog.KObj(pod), \"containerName\", container.Name)\n\t\tif err := m.Allocate(pod, container); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn m.podDevices.deviceRunContainerOptions(string(pod.UID), container.Name), nil\n}","line":{"from":871,"to":907}} {"id":100005892,"name":"callPreStartContainerIfNeeded","signature":"func (m *ManagerImpl) callPreStartContainerIfNeeded(podUID, contName, resource string) error","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"// callPreStartContainerIfNeeded issues PreStartContainer grpc call for device plugin resource\n// with PreStartRequired option set.\nfunc (m *ManagerImpl) callPreStartContainerIfNeeded(podUID, contName, resource string) error {\n\tm.mutex.Lock()\n\teI, ok := m.endpoints[resource]\n\tif !ok {\n\t\tm.mutex.Unlock()\n\t\treturn fmt.Errorf(\"endpoint not found in cache for a registered resource: %s\", resource)\n\t}\n\n\tif eI.opts == nil || !eI.opts.PreStartRequired {\n\t\tm.mutex.Unlock()\n\t\tklog.V(4).InfoS(\"Plugin options indicate to skip PreStartContainer for resource\", \"resourceName\", resource)\n\t\treturn nil\n\t}\n\n\tdevices := m.podDevices.containerDevices(podUID, contName, resource)\n\tif devices == nil {\n\t\tm.mutex.Unlock()\n\t\treturn fmt.Errorf(\"no devices found allocated in local cache for pod %s, container %s, resource %s\", string(podUID), contName, resource)\n\t}\n\n\tm.mutex.Unlock()\n\tdevs := devices.UnsortedList()\n\tklog.V(4).InfoS(\"Issuing a PreStartContainer call for container\", \"containerName\", contName, \"podUID\", string(podUID))\n\t_, err := eI.e.preStartContainer(devs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"device plugin PreStartContainer rpc failed with err: %v\", err)\n\t}\n\t// TODO: Add metrics support for init RPC\n\treturn nil\n}","line":{"from":909,"to":940}} {"id":100005893,"name":"callGetPreferredAllocationIfAvailable","signature":"func (m *ManagerImpl) callGetPreferredAllocationIfAvailable(podUID, contName, resource string, available, mustInclude sets.String, size int) (sets.String, error)","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"// callGetPreferredAllocationIfAvailable issues GetPreferredAllocation grpc\n// call for device plugin resource with GetPreferredAllocationAvailable option set.\nfunc (m *ManagerImpl) callGetPreferredAllocationIfAvailable(podUID, contName, resource string, available, mustInclude sets.String, size int) (sets.String, error) {\n\teI, ok := m.endpoints[resource]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"endpoint not found in cache for a registered resource: %s\", resource)\n\t}\n\n\tif eI.opts == nil || !eI.opts.GetPreferredAllocationAvailable {\n\t\tklog.V(4).InfoS(\"Plugin options indicate to skip GetPreferredAllocation for resource\", \"resourceName\", resource)\n\t\treturn nil, nil\n\t}\n\n\tm.mutex.Unlock()\n\tklog.V(4).InfoS(\"Issuing a GetPreferredAllocation call for container\", \"containerName\", contName, \"podUID\", string(podUID))\n\tresp, err := eI.e.getPreferredAllocation(available.UnsortedList(), mustInclude.UnsortedList(), size)\n\tm.mutex.Lock()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"device plugin GetPreferredAllocation rpc failed with err: %v\", err)\n\t}\n\tif resp != nil \u0026\u0026 len(resp.ContainerResponses) \u003e 0 {\n\t\treturn sets.NewString(resp.ContainerResponses[0].DeviceIDs...), nil\n\t}\n\treturn sets.NewString(), nil\n}","line":{"from":942,"to":966}} {"id":100005894,"name":"sanitizeNodeAllocatable","signature":"func (m *ManagerImpl) sanitizeNodeAllocatable(node *schedulerframework.NodeInfo)","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"// sanitizeNodeAllocatable scans through allocatedDevices in the device manager\n// and if necessary, updates allocatableResource in nodeInfo to at least equal to\n// the allocated capacity. This allows pods that have already been scheduled on\n// the node to pass GeneralPredicates admission checking even upon device plugin failure.\nfunc (m *ManagerImpl) sanitizeNodeAllocatable(node *schedulerframework.NodeInfo) {\n\tvar newAllocatableResource *schedulerframework.Resource\n\tallocatableResource := node.Allocatable\n\tif allocatableResource.ScalarResources == nil {\n\t\tallocatableResource.ScalarResources = make(map[v1.ResourceName]int64)\n\t}\n\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\tfor resource, devices := range m.allocatedDevices {\n\t\tneeded := devices.Len()\n\t\tquant, ok := allocatableResource.ScalarResources[v1.ResourceName(resource)]\n\t\tif ok \u0026\u0026 int(quant) \u003e= needed {\n\t\t\tcontinue\n\t\t}\n\t\t// Needs to update nodeInfo.AllocatableResource to make sure\n\t\t// NodeInfo.allocatableResource at least equal to the capacity already allocated.\n\t\tif newAllocatableResource == nil {\n\t\t\tnewAllocatableResource = allocatableResource.Clone()\n\t\t}\n\t\tnewAllocatableResource.ScalarResources[v1.ResourceName(resource)] = int64(needed)\n\t}\n\tif newAllocatableResource != nil {\n\t\tnode.Allocatable = newAllocatableResource\n\t}\n}","line":{"from":968,"to":997}} {"id":100005895,"name":"isDevicePluginResource","signature":"func (m *ManagerImpl) isDevicePluginResource(resource string) bool","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"func (m *ManagerImpl) isDevicePluginResource(resource string) bool {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\t_, registeredResource := m.healthyDevices[resource]\n\t_, allocatedResource := m.allocatedDevices[resource]\n\t// Return true if this is either an active device plugin resource or\n\t// a resource we have previously allocated.\n\tif registeredResource || allocatedResource {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":999,"to":1010}} {"id":100005896,"name":"GetAllocatableDevices","signature":"func (m *ManagerImpl) GetAllocatableDevices() ResourceDeviceInstances","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"// GetAllocatableDevices returns information about all the healthy devices known to the manager\nfunc (m *ManagerImpl) GetAllocatableDevices() ResourceDeviceInstances {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\tresp := m.allDevices.Filter(m.healthyDevices)\n\tklog.V(4).InfoS(\"GetAllocatableDevices\", \"known\", len(m.allDevices), \"allocatable\", len(resp))\n\treturn resp\n}","line":{"from":1012,"to":1019}} {"id":100005897,"name":"GetDevices","signature":"func (m *ManagerImpl) GetDevices(podUID, containerName string) ResourceDeviceInstances","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"// GetDevices returns the devices used by the specified container\nfunc (m *ManagerImpl) GetDevices(podUID, containerName string) ResourceDeviceInstances {\n\treturn m.podDevices.getContainerDevices(podUID, containerName)\n}","line":{"from":1021,"to":1024}} {"id":100005898,"name":"ShouldResetExtendedResourceCapacity","signature":"func (m *ManagerImpl) ShouldResetExtendedResourceCapacity() bool","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"// ShouldResetExtendedResourceCapacity returns whether the extended resources should be zeroed or not,\n// depending on whether the node has been recreated. Absence of the checkpoint file strongly indicates the node\n// has been recreated.\nfunc (m *ManagerImpl) ShouldResetExtendedResourceCapacity() bool {\n\tcheckpoints, err := m.checkpointManager.ListCheckpoints()\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn len(checkpoints) == 0\n}","line":{"from":1026,"to":1035}} {"id":100005899,"name":"setPodPendingAdmission","signature":"func (m *ManagerImpl) setPodPendingAdmission(pod *v1.Pod)","file":"pkg/kubelet/cm/devicemanager/manager.go","code":"func (m *ManagerImpl) setPodPendingAdmission(pod *v1.Pod) {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\tm.pendingAdmissionPod = pod\n}","line":{"from":1037,"to":1042}} {"id":100005900,"name":"NewPluginClient","signature":"func NewPluginClient(r string, socketPath string, h ClientHandler) Client","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/client.go","code":"// NewPluginClient returns an initialized device plugin client.\nfunc NewPluginClient(r string, socketPath string, h ClientHandler) Client {\n\treturn \u0026client{\n\t\tresource: r,\n\t\tsocket: socketPath,\n\t\thandler: h,\n\t}\n}","line":{"from":56,"to":63}} {"id":100005901,"name":"Connect","signature":"func (c *client) Connect() error","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/client.go","code":"// Connect is for establishing a gRPC connection between device manager and device plugin.\nfunc (c *client) Connect() error {\n\tclient, conn, err := dial(c.socket)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Unable to connect to device plugin client with socket path\", \"path\", c.socket)\n\t\treturn err\n\t}\n\tc.grpc = conn\n\tc.client = client\n\treturn c.handler.PluginConnected(c.resource, c)\n}","line":{"from":65,"to":75}} {"id":100005902,"name":"Run","signature":"func (c *client) Run()","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/client.go","code":"// Run is for running the device plugin gRPC client.\nfunc (c *client) Run() {\n\tstream, err := c.client.ListAndWatch(context.Background(), \u0026api.Empty{})\n\tif err != nil {\n\t\tklog.ErrorS(err, \"ListAndWatch ended unexpectedly for device plugin\", \"resource\", c.resource)\n\t\treturn\n\t}\n\n\tfor {\n\t\tresponse, err := stream.Recv()\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"ListAndWatch ended unexpectedly for device plugin\", \"resource\", c.resource)\n\t\t\treturn\n\t\t}\n\t\tklog.V(2).InfoS(\"State pushed for device plugin\", \"resource\", c.resource, \"resourceCapacity\", len(response.Devices))\n\t\tc.handler.PluginListAndWatchReceiver(c.resource, response)\n\t}\n}","line":{"from":77,"to":94}} {"id":100005903,"name":"Disconnect","signature":"func (c *client) Disconnect() error","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/client.go","code":"// Disconnect is for closing gRPC connection between device manager and device plugin.\nfunc (c *client) Disconnect() error {\n\tc.mutex.Lock()\n\tif c.grpc != nil {\n\t\tif err := c.grpc.Close(); err != nil {\n\t\t\tklog.V(2).ErrorS(err, \"Failed to close grcp connection\", \"resource\", c.Resource())\n\t\t}\n\t\tc.grpc = nil\n\t}\n\tc.mutex.Unlock()\n\tc.handler.PluginDisconnected(c.resource)\n\treturn nil\n}","line":{"from":96,"to":108}} {"id":100005904,"name":"Resource","signature":"func (c *client) Resource() string","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/client.go","code":"func (c *client) Resource() string {\n\treturn c.resource\n}","line":{"from":110,"to":112}} {"id":100005905,"name":"API","signature":"func (c *client) API() api.DevicePluginClient","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/client.go","code":"func (c *client) API() api.DevicePluginClient {\n\treturn c.client\n}","line":{"from":114,"to":116}} {"id":100005906,"name":"SocketPath","signature":"func (c *client) SocketPath() string","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/client.go","code":"func (c *client) SocketPath() string {\n\treturn c.socket\n}","line":{"from":118,"to":120}} {"id":100005907,"name":"dial","signature":"func dial(unixSocketPath string) (api.DevicePluginClient, *grpc.ClientConn, error)","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/client.go","code":"// dial establishes the gRPC communication with the registered device plugin. https://godoc.org/google.golang.org/grpc#Dial\nfunc dial(unixSocketPath string) (api.DevicePluginClient, *grpc.ClientConn, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\n\tc, err := grpc.DialContext(ctx, unixSocketPath,\n\t\tgrpc.WithAuthority(\"localhost\"),\n\t\tgrpc.WithTransportCredentials(insecure.NewCredentials()),\n\t\tgrpc.WithBlock(),\n\t\tgrpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) {\n\t\t\treturn (\u0026net.Dialer{}).DialContext(ctx, \"unix\", addr)\n\t\t}),\n\t)\n\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(errFailedToDialDevicePlugin+\" %v\", err)\n\t}\n\n\treturn api.NewDevicePluginClient(c), c, nil\n}","line":{"from":122,"to":141}} {"id":100005908,"name":"GetPluginHandler","signature":"func (s *server) GetPluginHandler() cache.PluginHandler","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/handler.go","code":"func (s *server) GetPluginHandler() cache.PluginHandler {\n\tif f, err := os.Create(s.socketDir + \"DEPRECATION\"); err != nil {\n\t\tklog.ErrorS(err, \"Failed to create deprecation file at socket dir\", \"path\", s.socketDir)\n\t} else {\n\t\tf.Close()\n\t\tklog.V(4).InfoS(\"Created deprecation file\", \"path\", f.Name())\n\t}\n\treturn s\n}","line":{"from":30,"to":38}} {"id":100005909,"name":"RegisterPlugin","signature":"func (s *server) RegisterPlugin(pluginName string, endpoint string, versions []string) error","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/handler.go","code":"func (s *server) RegisterPlugin(pluginName string, endpoint string, versions []string) error {\n\tklog.V(2).InfoS(\"Registering plugin at endpoint\", \"plugin\", pluginName, \"endpoint\", endpoint)\n\treturn s.connectClient(pluginName, endpoint)\n}","line":{"from":40,"to":43}} {"id":100005910,"name":"DeRegisterPlugin","signature":"func (s *server) DeRegisterPlugin(pluginName string)","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/handler.go","code":"func (s *server) DeRegisterPlugin(pluginName string) {\n\tklog.V(2).InfoS(\"Deregistering plugin\", \"plugin\", pluginName)\n\tclient := s.getClient(pluginName)\n\tif client != nil {\n\t\ts.disconnectClient(pluginName, client)\n\t}\n}","line":{"from":45,"to":51}} {"id":100005911,"name":"ValidatePlugin","signature":"func (s *server) ValidatePlugin(pluginName string, endpoint string, versions []string) error","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/handler.go","code":"func (s *server) ValidatePlugin(pluginName string, endpoint string, versions []string) error {\n\tklog.V(2).InfoS(\"Got plugin at endpoint with versions\", \"plugin\", pluginName, \"endpoint\", endpoint, \"versions\", versions)\n\n\tif !s.isVersionCompatibleWithPlugin(versions...) {\n\t\treturn fmt.Errorf(\"manager version, %s, is not among plugin supported versions %v\", api.Version, versions)\n\t}\n\n\tif !v1helper.IsExtendedResourceName(core.ResourceName(pluginName)) {\n\t\treturn fmt.Errorf(\"invalid name of device plugin socket: %s\", fmt.Sprintf(errInvalidResourceName, pluginName))\n\t}\n\n\treturn nil\n}","line":{"from":53,"to":65}} {"id":100005912,"name":"connectClient","signature":"func (s *server) connectClient(name string, socketPath string) error","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/handler.go","code":"func (s *server) connectClient(name string, socketPath string) error {\n\tc := NewPluginClient(name, socketPath, s.chandler)\n\n\ts.registerClient(name, c)\n\tif err := c.Connect(); err != nil {\n\t\ts.deregisterClient(name)\n\t\tklog.ErrorS(err, \"Failed to connect to new client\", \"resource\", name)\n\t\treturn err\n\t}\n\n\tgo func() {\n\t\ts.runClient(name, c)\n\t}()\n\n\treturn nil\n}","line":{"from":67,"to":82}} {"id":100005913,"name":"disconnectClient","signature":"func (s *server) disconnectClient(name string, c Client) error","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/handler.go","code":"func (s *server) disconnectClient(name string, c Client) error {\n\ts.deregisterClient(name)\n\treturn c.Disconnect()\n}","line":{"from":84,"to":87}} {"id":100005914,"name":"registerClient","signature":"func (s *server) registerClient(name string, c Client)","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/handler.go","code":"func (s *server) registerClient(name string, c Client) {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\ts.clients[name] = c\n\tklog.V(2).InfoS(\"Registered client\", \"name\", name)\n}","line":{"from":89,"to":95}} {"id":100005915,"name":"deregisterClient","signature":"func (s *server) deregisterClient(name string)","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/handler.go","code":"func (s *server) deregisterClient(name string) {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tdelete(s.clients, name)\n\tklog.V(2).InfoS(\"Deregistered client\", \"name\", name)\n}","line":{"from":97,"to":103}} {"id":100005916,"name":"runClient","signature":"func (s *server) runClient(name string, c Client)","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/handler.go","code":"func (s *server) runClient(name string, c Client) {\n\tc.Run()\n\n\tc = s.getClient(name)\n\tif c == nil {\n\t\treturn\n\t}\n\n\tif err := s.disconnectClient(name, c); err != nil {\n\t\tklog.V(2).InfoS(\"Unable to disconnect client\", \"resource\", name, \"client\", c, \"err\", err)\n\t}\n}","line":{"from":105,"to":116}} {"id":100005917,"name":"getClient","signature":"func (s *server) getClient(name string) Client","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/handler.go","code":"func (s *server) getClient(name string) Client {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\treturn s.clients[name]\n}","line":{"from":118,"to":122}} {"id":100005918,"name":"NewServer","signature":"func NewServer(socketPath string, rh RegistrationHandler, ch ClientHandler) (Server, error)","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/server.go","code":"// NewServer returns an initialized device plugin registration server.\nfunc NewServer(socketPath string, rh RegistrationHandler, ch ClientHandler) (Server, error) {\n\tif socketPath == \"\" || !filepath.IsAbs(socketPath) {\n\t\treturn nil, fmt.Errorf(errBadSocket+\" %s\", socketPath)\n\t}\n\n\tdir, name := filepath.Split(socketPath)\n\n\tklog.V(2).InfoS(\"Creating device plugin registration server\", \"version\", api.Version, \"socket\", socketPath)\n\ts := \u0026server{\n\t\tsocketName: name,\n\t\tsocketDir: dir,\n\t\trhandler: rh,\n\t\tchandler: ch,\n\t\tclients: make(map[string]Client),\n\t}\n\n\treturn s, nil\n}","line":{"from":58,"to":76}} {"id":100005919,"name":"Start","signature":"func (s *server) Start() error","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/server.go","code":"func (s *server) Start() error {\n\tklog.V(2).InfoS(\"Starting device plugin registration server\")\n\n\tif err := os.MkdirAll(s.socketDir, 0750); err != nil {\n\t\tklog.ErrorS(err, \"Failed to create the device plugin socket directory\", \"directory\", s.socketDir)\n\t\treturn err\n\t}\n\n\tif selinux.GetEnabled() {\n\t\tif err := selinux.SetFileLabel(s.socketDir, config.KubeletPluginsDirSELinuxLabel); err != nil {\n\t\t\tklog.InfoS(\"Unprivileged containerized plugins might not work. Could not set selinux context on socket dir\", \"path\", s.socketDir, \"err\", err)\n\t\t}\n\t}\n\n\t// For now we leave cleanup of the *entire* directory up to the Handler\n\t// (even though we should in theory be able to just wipe the whole directory)\n\t// because the Handler stores its checkpoint file (amongst others) in here.\n\tif err := s.rhandler.CleanupPluginDirectory(s.socketDir); err != nil {\n\t\tklog.ErrorS(err, \"Failed to cleanup the device plugin directory\", \"directory\", s.socketDir)\n\t\treturn err\n\t}\n\n\tln, err := net.Listen(\"unix\", s.SocketPath())\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to listen to socket while starting device plugin registry\")\n\t\treturn err\n\t}\n\n\ts.wg.Add(1)\n\ts.grpc = grpc.NewServer([]grpc.ServerOption{}...)\n\n\tapi.RegisterRegistrationServer(s.grpc, s)\n\tgo func() {\n\t\tdefer s.wg.Done()\n\t\ts.grpc.Serve(ln)\n\t}()\n\n\treturn nil\n}","line":{"from":78,"to":116}} {"id":100005920,"name":"Stop","signature":"func (s *server) Stop() error","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/server.go","code":"func (s *server) Stop() error {\n\ts.visitClients(func(r string, c Client) {\n\t\tif err := s.disconnectClient(r, c); err != nil {\n\t\t\tklog.InfoS(\"Error disconnecting device plugin client\", \"resourceName\", r, \"err\", err)\n\t\t}\n\t})\n\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tif s.grpc == nil {\n\t\treturn nil\n\t}\n\n\ts.grpc.Stop()\n\ts.wg.Wait()\n\ts.grpc = nil\n\n\treturn nil\n}","line":{"from":118,"to":137}} {"id":100005921,"name":"SocketPath","signature":"func (s *server) SocketPath() string","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/server.go","code":"func (s *server) SocketPath() string {\n\treturn filepath.Join(s.socketDir, s.socketName)\n}","line":{"from":139,"to":141}} {"id":100005922,"name":"Register","signature":"func (s *server) Register(ctx context.Context, r *api.RegisterRequest) (*api.Empty, error)","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/server.go","code":"func (s *server) Register(ctx context.Context, r *api.RegisterRequest) (*api.Empty, error) {\n\tklog.InfoS(\"Got registration request from device plugin with resource\", \"resourceName\", r.ResourceName)\n\tmetrics.DevicePluginRegistrationCount.WithLabelValues(r.ResourceName).Inc()\n\n\tif !s.isVersionCompatibleWithPlugin(r.Version) {\n\t\terr := fmt.Errorf(errUnsupportedVersion, r.Version, api.SupportedVersions)\n\t\tklog.InfoS(\"Bad registration request from device plugin with resource\", \"resourceName\", r.ResourceName, \"err\", err)\n\t\treturn \u0026api.Empty{}, err\n\t}\n\n\tif !v1helper.IsExtendedResourceName(core.ResourceName(r.ResourceName)) {\n\t\terr := fmt.Errorf(errInvalidResourceName, r.ResourceName)\n\t\tklog.InfoS(\"Bad registration request from device plugin\", \"err\", err)\n\t\treturn \u0026api.Empty{}, err\n\t}\n\n\tif err := s.connectClient(r.ResourceName, filepath.Join(s.socketDir, r.Endpoint)); err != nil {\n\t\tklog.InfoS(\"Error connecting to device plugin client\", \"err\", err)\n\t\treturn \u0026api.Empty{}, err\n\t}\n\n\treturn \u0026api.Empty{}, nil\n}","line":{"from":143,"to":165}} {"id":100005923,"name":"isVersionCompatibleWithPlugin","signature":"func (s *server) isVersionCompatibleWithPlugin(versions ...string) bool","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/server.go","code":"func (s *server) isVersionCompatibleWithPlugin(versions ...string) bool {\n\t// TODO(vikasc): Currently this is fine as we only have a single supported version. When we do need to support\n\t// multiple versions in the future, we may need to extend this function to return a supported version.\n\t// E.g., say kubelet supports v1beta1 and v1beta2, and we get v1alpha1 and v1beta1 from a device plugin,\n\t// this function should return v1beta1\n\tfor _, version := range versions {\n\t\tfor _, supportedVersion := range api.SupportedVersions {\n\t\t\tif version == supportedVersion {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":167,"to":180}} {"id":100005924,"name":"visitClients","signature":"func (s *server) visitClients(visit func(r string, c Client))","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/server.go","code":"func (s *server) visitClients(visit func(r string, c Client)) {\n\ts.mutex.Lock()\n\tfor r, c := range s.clients {\n\t\ts.mutex.Unlock()\n\t\tvisit(r, c)\n\t\ts.mutex.Lock()\n\t}\n\ts.mutex.Unlock()\n}","line":{"from":182,"to":190}} {"id":100005925,"name":"defaultGetPreferredAllocFunc","signature":"func defaultGetPreferredAllocFunc(r *pluginapi.PreferredAllocationRequest, devs map[string]pluginapi.Device) (*pluginapi.PreferredAllocationResponse, error)","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/stub.go","code":"func defaultGetPreferredAllocFunc(r *pluginapi.PreferredAllocationRequest, devs map[string]pluginapi.Device) (*pluginapi.PreferredAllocationResponse, error) {\n\tvar response pluginapi.PreferredAllocationResponse\n\n\treturn \u0026response, nil\n}","line":{"from":64,"to":68}} {"id":100005926,"name":"defaultAllocFunc","signature":"func defaultAllocFunc(r *pluginapi.AllocateRequest, devs map[string]pluginapi.Device) (*pluginapi.AllocateResponse, error)","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/stub.go","code":"func defaultAllocFunc(r *pluginapi.AllocateRequest, devs map[string]pluginapi.Device) (*pluginapi.AllocateResponse, error) {\n\tvar response pluginapi.AllocateResponse\n\n\treturn \u0026response, nil\n}","line":{"from":73,"to":77}} {"id":100005927,"name":"NewDevicePluginStub","signature":"func NewDevicePluginStub(devs []*pluginapi.Device, socket string, name string, preStartContainerFlag bool, getPreferredAllocationFlag bool) *Stub","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/stub.go","code":"// NewDevicePluginStub returns an initialized DevicePlugin Stub.\nfunc NewDevicePluginStub(devs []*pluginapi.Device, socket string, name string, preStartContainerFlag bool, getPreferredAllocationFlag bool) *Stub {\n\treturn \u0026Stub{\n\t\tdevs: devs,\n\t\tsocket: socket,\n\t\tresourceName: name,\n\t\tpreStartContainerFlag: preStartContainerFlag,\n\t\tgetPreferredAllocationFlag: getPreferredAllocationFlag,\n\n\t\tstop: make(chan interface{}),\n\t\tupdate: make(chan []*pluginapi.Device),\n\n\t\tallocFunc: defaultAllocFunc,\n\t\tgetPreferredAllocFunc: defaultGetPreferredAllocFunc,\n\t}\n}","line":{"from":79,"to":94}} {"id":100005928,"name":"SetGetPreferredAllocFunc","signature":"func (m *Stub) SetGetPreferredAllocFunc(f stubGetPreferredAllocFunc)","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/stub.go","code":"// SetGetPreferredAllocFunc sets allocFunc of the device plugin\nfunc (m *Stub) SetGetPreferredAllocFunc(f stubGetPreferredAllocFunc) {\n\tm.getPreferredAllocFunc = f\n}","line":{"from":96,"to":99}} {"id":100005929,"name":"SetAllocFunc","signature":"func (m *Stub) SetAllocFunc(f stubAllocFunc)","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/stub.go","code":"// SetAllocFunc sets allocFunc of the device plugin\nfunc (m *Stub) SetAllocFunc(f stubAllocFunc) {\n\tm.allocFunc = f\n}","line":{"from":101,"to":104}} {"id":100005930,"name":"Start","signature":"func (m *Stub) Start() error","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/stub.go","code":"// Start starts the gRPC server of the device plugin. Can only\n// be called once.\nfunc (m *Stub) Start() error {\n\terr := m.cleanup()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsock, err := net.Listen(\"unix\", m.socket)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm.wg.Add(1)\n\tm.server = grpc.NewServer([]grpc.ServerOption{}...)\n\tpluginapi.RegisterDevicePluginServer(m.server, m)\n\twatcherapi.RegisterRegistrationServer(m.server, m)\n\n\tgo func() {\n\t\tdefer m.wg.Done()\n\t\tm.server.Serve(sock)\n\t}()\n\n\tvar lastDialErr error\n\twait.PollImmediate(1*time.Second, 10*time.Second, func() (bool, error) {\n\t\tvar conn *grpc.ClientConn\n\t\t_, conn, lastDialErr = dial(m.socket)\n\t\tif lastDialErr != nil {\n\t\t\treturn false, nil\n\t\t}\n\t\tconn.Close()\n\t\treturn true, nil\n\t})\n\tif lastDialErr != nil {\n\t\treturn lastDialErr\n\t}\n\n\tklog.InfoS(\"Starting to serve on socket\", \"socket\", m.socket)\n\treturn nil\n}","line":{"from":106,"to":145}} {"id":100005931,"name":"Stop","signature":"func (m *Stub) Stop() error","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/stub.go","code":"// Stop stops the gRPC server. Can be called without a prior Start\n// and more than once. Not safe to be called concurrently by different\n// goroutines!\nfunc (m *Stub) Stop() error {\n\tif m.server == nil {\n\t\treturn nil\n\t}\n\tm.server.Stop()\n\tm.wg.Wait()\n\tm.server = nil\n\tclose(m.stop) // This prevents re-starting the server.\n\n\treturn m.cleanup()\n}","line":{"from":147,"to":160}} {"id":100005932,"name":"GetInfo","signature":"func (m *Stub) GetInfo(ctx context.Context, req *watcherapi.InfoRequest) (*watcherapi.PluginInfo, error)","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/stub.go","code":"// GetInfo is the RPC which return pluginInfo\nfunc (m *Stub) GetInfo(ctx context.Context, req *watcherapi.InfoRequest) (*watcherapi.PluginInfo, error) {\n\tklog.InfoS(\"GetInfo\")\n\treturn \u0026watcherapi.PluginInfo{\n\t\tType: watcherapi.DevicePlugin,\n\t\tName: m.resourceName,\n\t\tEndpoint: m.endpoint,\n\t\tSupportedVersions: []string{pluginapi.Version}}, nil\n}","line":{"from":162,"to":170}} {"id":100005933,"name":"NotifyRegistrationStatus","signature":"func (m *Stub) NotifyRegistrationStatus(ctx context.Context, status *watcherapi.RegistrationStatus) (*watcherapi.RegistrationStatusResponse, error)","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/stub.go","code":"// NotifyRegistrationStatus receives the registration notification from watcher\nfunc (m *Stub) NotifyRegistrationStatus(ctx context.Context, status *watcherapi.RegistrationStatus) (*watcherapi.RegistrationStatusResponse, error) {\n\tif m.registrationStatus != nil {\n\t\tm.registrationStatus \u003c- *status\n\t}\n\tif !status.PluginRegistered {\n\t\tklog.InfoS(\"Registration failed\", \"err\", status.Error)\n\t}\n\treturn \u0026watcherapi.RegistrationStatusResponse{}, nil\n}","line":{"from":172,"to":181}} {"id":100005934,"name":"Register","signature":"func (m *Stub) Register(kubeletEndpoint, resourceName string, pluginSockDir string) error","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/stub.go","code":"// Register registers the device plugin for the given resourceName with Kubelet.\nfunc (m *Stub) Register(kubeletEndpoint, resourceName string, pluginSockDir string) error {\n\tif pluginSockDir != \"\" {\n\t\tif _, err := os.Stat(pluginSockDir + \"DEPRECATION\"); err == nil {\n\t\t\tklog.InfoS(\"Deprecation file found. Skip registration\")\n\t\t\treturn nil\n\t\t}\n\t}\n\tklog.InfoS(\"Deprecation file not found. Invoke registration\")\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\n\tconn, err := grpc.DialContext(ctx, kubeletEndpoint,\n\t\tgrpc.WithTransportCredentials(insecure.NewCredentials()),\n\t\tgrpc.WithBlock(),\n\t\tgrpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) {\n\t\t\treturn (\u0026net.Dialer{}).DialContext(ctx, \"unix\", addr)\n\t\t}))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\tclient := pluginapi.NewRegistrationClient(conn)\n\treqt := \u0026pluginapi.RegisterRequest{\n\t\tVersion: pluginapi.Version,\n\t\tEndpoint: filepath.Base(m.socket),\n\t\tResourceName: resourceName,\n\t\tOptions: \u0026pluginapi.DevicePluginOptions{\n\t\t\tPreStartRequired: m.preStartContainerFlag,\n\t\t\tGetPreferredAllocationAvailable: m.getPreferredAllocationFlag,\n\t\t},\n\t}\n\n\t_, err = client.Register(context.Background(), reqt)\n\treturn err\n}","line":{"from":183,"to":218}} {"id":100005935,"name":"GetDevicePluginOptions","signature":"func (m *Stub) GetDevicePluginOptions(ctx context.Context, e *pluginapi.Empty) (*pluginapi.DevicePluginOptions, error)","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/stub.go","code":"// GetDevicePluginOptions returns DevicePluginOptions settings for the device plugin.\nfunc (m *Stub) GetDevicePluginOptions(ctx context.Context, e *pluginapi.Empty) (*pluginapi.DevicePluginOptions, error) {\n\toptions := \u0026pluginapi.DevicePluginOptions{\n\t\tPreStartRequired: m.preStartContainerFlag,\n\t\tGetPreferredAllocationAvailable: m.getPreferredAllocationFlag,\n\t}\n\treturn options, nil\n}","line":{"from":220,"to":227}} {"id":100005936,"name":"PreStartContainer","signature":"func (m *Stub) PreStartContainer(ctx context.Context, r *pluginapi.PreStartContainerRequest) (*pluginapi.PreStartContainerResponse, error)","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/stub.go","code":"// PreStartContainer resets the devices received\nfunc (m *Stub) PreStartContainer(ctx context.Context, r *pluginapi.PreStartContainerRequest) (*pluginapi.PreStartContainerResponse, error) {\n\tklog.InfoS(\"PreStartContainer\", \"request\", r)\n\treturn \u0026pluginapi.PreStartContainerResponse{}, nil\n}","line":{"from":229,"to":233}} {"id":100005937,"name":"ListAndWatch","signature":"func (m *Stub) ListAndWatch(e *pluginapi.Empty, s pluginapi.DevicePlugin_ListAndWatchServer) error","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/stub.go","code":"// ListAndWatch lists devices and update that list according to the Update call\nfunc (m *Stub) ListAndWatch(e *pluginapi.Empty, s pluginapi.DevicePlugin_ListAndWatchServer) error {\n\tklog.InfoS(\"ListAndWatch\")\n\n\ts.Send(\u0026pluginapi.ListAndWatchResponse{Devices: m.devs})\n\n\tfor {\n\t\tselect {\n\t\tcase \u003c-m.stop:\n\t\t\treturn nil\n\t\tcase updated := \u003c-m.update:\n\t\t\ts.Send(\u0026pluginapi.ListAndWatchResponse{Devices: updated})\n\t\t}\n\t}\n}","line":{"from":235,"to":249}} {"id":100005938,"name":"Update","signature":"func (m *Stub) Update(devs []*pluginapi.Device)","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/stub.go","code":"// Update allows the device plugin to send new devices through ListAndWatch\nfunc (m *Stub) Update(devs []*pluginapi.Device) {\n\tm.update \u003c- devs\n}","line":{"from":251,"to":254}} {"id":100005939,"name":"GetPreferredAllocation","signature":"func (m *Stub) GetPreferredAllocation(ctx context.Context, r *pluginapi.PreferredAllocationRequest) (*pluginapi.PreferredAllocationResponse, error)","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/stub.go","code":"// GetPreferredAllocation gets the preferred allocation from a set of available devices\nfunc (m *Stub) GetPreferredAllocation(ctx context.Context, r *pluginapi.PreferredAllocationRequest) (*pluginapi.PreferredAllocationResponse, error) {\n\tklog.InfoS(\"GetPreferredAllocation\", \"request\", r)\n\n\tdevs := make(map[string]pluginapi.Device)\n\n\tfor _, dev := range m.devs {\n\t\tdevs[dev.ID] = *dev\n\t}\n\n\treturn m.getPreferredAllocFunc(r, devs)\n}","line":{"from":256,"to":267}} {"id":100005940,"name":"Allocate","signature":"func (m *Stub) Allocate(ctx context.Context, r *pluginapi.AllocateRequest) (*pluginapi.AllocateResponse, error)","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/stub.go","code":"// Allocate does a mock allocation\nfunc (m *Stub) Allocate(ctx context.Context, r *pluginapi.AllocateRequest) (*pluginapi.AllocateResponse, error) {\n\tklog.InfoS(\"Allocate\", \"request\", r)\n\n\tdevs := make(map[string]pluginapi.Device)\n\n\tfor _, dev := range m.devs {\n\t\tdevs[dev.ID] = *dev\n\t}\n\n\treturn m.allocFunc(r, devs)\n}","line":{"from":269,"to":280}} {"id":100005941,"name":"cleanup","signature":"func (m *Stub) cleanup() error","file":"pkg/kubelet/cm/devicemanager/plugin/v1beta1/stub.go","code":"func (m *Stub) cleanup() error {\n\tif err := os.Remove(m.socket); err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":282,"to":288}} {"id":100005942,"name":"newPodDevices","signature":"func newPodDevices() *podDevices","file":"pkg/kubelet/cm/devicemanager/pod_devices.go","code":"// NewPodDevices is a function that returns object of podDevices type with its own guard\n// RWMutex and a map where key is a pod UID and value contains\n// container devices information of type containerDevices.\nfunc newPodDevices() *podDevices {\n\treturn \u0026podDevices{devs: make(map[string]containerDevices)}\n}","line":{"from":44,"to":49}} {"id":100005943,"name":"pods","signature":"func (pdev *podDevices) pods() sets.String","file":"pkg/kubelet/cm/devicemanager/pod_devices.go","code":"func (pdev *podDevices) pods() sets.String {\n\tpdev.RLock()\n\tdefer pdev.RUnlock()\n\tret := sets.NewString()\n\tfor k := range pdev.devs {\n\t\tret.Insert(k)\n\t}\n\treturn ret\n}","line":{"from":51,"to":59}} {"id":100005944,"name":"size","signature":"func (pdev *podDevices) size() int","file":"pkg/kubelet/cm/devicemanager/pod_devices.go","code":"func (pdev *podDevices) size() int {\n\tpdev.RLock()\n\tdefer pdev.RUnlock()\n\treturn len(pdev.devs)\n}","line":{"from":61,"to":65}} {"id":100005945,"name":"hasPod","signature":"func (pdev *podDevices) hasPod(podUID string) bool","file":"pkg/kubelet/cm/devicemanager/pod_devices.go","code":"func (pdev *podDevices) hasPod(podUID string) bool {\n\tpdev.RLock()\n\tdefer pdev.RUnlock()\n\t_, podExists := pdev.devs[podUID]\n\treturn podExists\n}","line":{"from":67,"to":72}} {"id":100005946,"name":"insert","signature":"func (pdev *podDevices) insert(podUID, contName, resource string, devices checkpoint.DevicesPerNUMA, resp *pluginapi.ContainerAllocateResponse)","file":"pkg/kubelet/cm/devicemanager/pod_devices.go","code":"func (pdev *podDevices) insert(podUID, contName, resource string, devices checkpoint.DevicesPerNUMA, resp *pluginapi.ContainerAllocateResponse) {\n\tpdev.Lock()\n\tdefer pdev.Unlock()\n\tif _, podExists := pdev.devs[podUID]; !podExists {\n\t\tpdev.devs[podUID] = make(containerDevices)\n\t}\n\tif _, contExists := pdev.devs[podUID][contName]; !contExists {\n\t\tpdev.devs[podUID][contName] = make(resourceAllocateInfo)\n\t}\n\tpdev.devs[podUID][contName][resource] = deviceAllocateInfo{\n\t\tdeviceIds: devices,\n\t\tallocResp: resp,\n\t}\n}","line":{"from":74,"to":87}} {"id":100005947,"name":"delete","signature":"func (pdev *podDevices) delete(pods []string)","file":"pkg/kubelet/cm/devicemanager/pod_devices.go","code":"func (pdev *podDevices) delete(pods []string) {\n\tpdev.Lock()\n\tdefer pdev.Unlock()\n\tfor _, uid := range pods {\n\t\tdelete(pdev.devs, uid)\n\t}\n}","line":{"from":89,"to":95}} {"id":100005948,"name":"podDevices","signature":"func (pdev *podDevices) podDevices(podUID, resource string) sets.String","file":"pkg/kubelet/cm/devicemanager/pod_devices.go","code":"// Returns list of device Ids allocated to the given pod for the given resource.\n// Returns nil if we don't have cached state for the given \u003cpodUID, resource\u003e.\nfunc (pdev *podDevices) podDevices(podUID, resource string) sets.String {\n\tpdev.RLock()\n\tdefer pdev.RUnlock()\n\n\tret := sets.NewString()\n\tfor contName := range pdev.devs[podUID] {\n\t\tret = ret.Union(pdev.containerDevices(podUID, contName, resource))\n\t}\n\treturn ret\n}","line":{"from":97,"to":108}} {"id":100005949,"name":"containerDevices","signature":"func (pdev *podDevices) containerDevices(podUID, contName, resource string) sets.String","file":"pkg/kubelet/cm/devicemanager/pod_devices.go","code":"// Returns list of device Ids allocated to the given container for the given resource.\n// Returns nil if we don't have cached state for the given \u003cpodUID, contName, resource\u003e.\nfunc (pdev *podDevices) containerDevices(podUID, contName, resource string) sets.String {\n\tpdev.RLock()\n\tdefer pdev.RUnlock()\n\tif _, podExists := pdev.devs[podUID]; !podExists {\n\t\treturn nil\n\t}\n\tif _, contExists := pdev.devs[podUID][contName]; !contExists {\n\t\treturn nil\n\t}\n\tdevs, resourceExists := pdev.devs[podUID][contName][resource]\n\tif !resourceExists {\n\t\treturn nil\n\t}\n\treturn devs.deviceIds.Devices()\n}","line":{"from":110,"to":126}} {"id":100005950,"name":"addContainerAllocatedResources","signature":"func (pdev *podDevices) addContainerAllocatedResources(podUID, contName string, allocatedResources map[string]sets.String)","file":"pkg/kubelet/cm/devicemanager/pod_devices.go","code":"// Populates allocatedResources with the device resources allocated to the specified \u003cpodUID, contName\u003e.\nfunc (pdev *podDevices) addContainerAllocatedResources(podUID, contName string, allocatedResources map[string]sets.String) {\n\tpdev.RLock()\n\tdefer pdev.RUnlock()\n\tcontainers, exists := pdev.devs[podUID]\n\tif !exists {\n\t\treturn\n\t}\n\tresources, exists := containers[contName]\n\tif !exists {\n\t\treturn\n\t}\n\tfor resource, devices := range resources {\n\t\tallocatedResources[resource] = allocatedResources[resource].Union(devices.deviceIds.Devices())\n\t}\n}","line":{"from":128,"to":143}} {"id":100005951,"name":"removeContainerAllocatedResources","signature":"func (pdev *podDevices) removeContainerAllocatedResources(podUID, contName string, allocatedResources map[string]sets.String)","file":"pkg/kubelet/cm/devicemanager/pod_devices.go","code":"// Removes the device resources allocated to the specified \u003cpodUID, contName\u003e from allocatedResources.\nfunc (pdev *podDevices) removeContainerAllocatedResources(podUID, contName string, allocatedResources map[string]sets.String) {\n\tpdev.RLock()\n\tdefer pdev.RUnlock()\n\tcontainers, exists := pdev.devs[podUID]\n\tif !exists {\n\t\treturn\n\t}\n\tresources, exists := containers[contName]\n\tif !exists {\n\t\treturn\n\t}\n\tfor resource, devices := range resources {\n\t\tallocatedResources[resource] = allocatedResources[resource].Difference(devices.deviceIds.Devices())\n\t}\n}","line":{"from":145,"to":160}} {"id":100005952,"name":"devices","signature":"func (pdev *podDevices) devices() map[string]sets.String","file":"pkg/kubelet/cm/devicemanager/pod_devices.go","code":"// Returns all of devices allocated to the pods being tracked, keyed by resourceName.\nfunc (pdev *podDevices) devices() map[string]sets.String {\n\tret := make(map[string]sets.String)\n\tpdev.RLock()\n\tdefer pdev.RUnlock()\n\tfor _, containerDevices := range pdev.devs {\n\t\tfor _, resources := range containerDevices {\n\t\t\tfor resource, devices := range resources {\n\t\t\t\tif _, exists := ret[resource]; !exists {\n\t\t\t\t\tret[resource] = sets.NewString()\n\t\t\t\t}\n\t\t\t\tif devices.allocResp != nil {\n\t\t\t\t\tret[resource] = ret[resource].Union(devices.deviceIds.Devices())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn ret\n}","line":{"from":162,"to":180}} {"id":100005953,"name":"toCheckpointData","signature":"func (pdev *podDevices) toCheckpointData() []checkpoint.PodDevicesEntry","file":"pkg/kubelet/cm/devicemanager/pod_devices.go","code":"// Turns podDevices to checkpointData.\nfunc (pdev *podDevices) toCheckpointData() []checkpoint.PodDevicesEntry {\n\tvar data []checkpoint.PodDevicesEntry\n\tpdev.RLock()\n\tdefer pdev.RUnlock()\n\tfor podUID, containerDevices := range pdev.devs {\n\t\tfor conName, resources := range containerDevices {\n\t\t\tfor resource, devices := range resources {\n\t\t\t\tif devices.allocResp == nil {\n\t\t\t\t\tklog.ErrorS(nil, \"Can't marshal allocResp, allocation response is missing\", \"podUID\", podUID, \"containerName\", conName, \"resourceName\", resource)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tallocResp, err := devices.allocResp.Marshal()\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"Can't marshal allocResp\", \"podUID\", podUID, \"containerName\", conName, \"resourceName\", resource)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tdata = append(data, checkpoint.PodDevicesEntry{\n\t\t\t\t\tPodUID: podUID,\n\t\t\t\t\tContainerName: conName,\n\t\t\t\t\tResourceName: resource,\n\t\t\t\t\tDeviceIDs: devices.deviceIds,\n\t\t\t\t\tAllocResp: allocResp})\n\t\t\t}\n\t\t}\n\t}\n\treturn data\n}","line":{"from":182,"to":210}} {"id":100005954,"name":"fromCheckpointData","signature":"func (pdev *podDevices) fromCheckpointData(data []checkpoint.PodDevicesEntry)","file":"pkg/kubelet/cm/devicemanager/pod_devices.go","code":"// Populates podDevices from the passed in checkpointData.\nfunc (pdev *podDevices) fromCheckpointData(data []checkpoint.PodDevicesEntry) {\n\tfor _, entry := range data {\n\t\tklog.V(2).InfoS(\"Get checkpoint entry\",\n\t\t\t\"podUID\", entry.PodUID, \"containerName\", entry.ContainerName,\n\t\t\t\"resourceName\", entry.ResourceName, \"deviceIDs\", entry.DeviceIDs, \"allocated\", entry.AllocResp)\n\t\tallocResp := \u0026pluginapi.ContainerAllocateResponse{}\n\t\terr := allocResp.Unmarshal(entry.AllocResp)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Can't unmarshal allocResp\", \"podUID\", entry.PodUID, \"containerName\", entry.ContainerName, \"resourceName\", entry.ResourceName)\n\t\t\tcontinue\n\t\t}\n\t\tpdev.insert(entry.PodUID, entry.ContainerName, entry.ResourceName, entry.DeviceIDs, allocResp)\n\t}\n}","line":{"from":212,"to":226}} {"id":100005955,"name":"deviceRunContainerOptions","signature":"func (pdev *podDevices) deviceRunContainerOptions(podUID, contName string) *DeviceRunContainerOptions","file":"pkg/kubelet/cm/devicemanager/pod_devices.go","code":"// Returns combined container runtime settings to consume the container's allocated devices.\nfunc (pdev *podDevices) deviceRunContainerOptions(podUID, contName string) *DeviceRunContainerOptions {\n\tpdev.RLock()\n\tdefer pdev.RUnlock()\n\n\tcontainers, exists := pdev.devs[podUID]\n\tif !exists {\n\t\treturn nil\n\t}\n\tresources, exists := containers[contName]\n\tif !exists {\n\t\treturn nil\n\t}\n\topts := \u0026DeviceRunContainerOptions{}\n\t// Maps to detect duplicate settings.\n\tdevsMap := make(map[string]string)\n\tmountsMap := make(map[string]string)\n\tenvsMap := make(map[string]string)\n\tannotationsMap := make(map[string]string)\n\t// Loops through AllocationResponses of all cached device resources.\n\tfor _, devices := range resources {\n\t\tresp := devices.allocResp\n\t\t// Each Allocate response has the following artifacts.\n\t\t// Environment variables\n\t\t// Mount points\n\t\t// Device files\n\t\t// Container annotations\n\t\t// These artifacts are per resource per container.\n\t\t// Updates RunContainerOptions.Envs.\n\t\tfor k, v := range resp.Envs {\n\t\t\tif e, ok := envsMap[k]; ok {\n\t\t\t\tklog.V(4).InfoS(\"Skip existing env\", \"envKey\", k, \"envValue\", v)\n\t\t\t\tif e != v {\n\t\t\t\t\tklog.ErrorS(nil, \"Environment variable has conflicting setting\", \"envKey\", k, \"expected\", v, \"got\", e)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tklog.V(4).InfoS(\"Add env\", \"envKey\", k, \"envValue\", v)\n\t\t\tenvsMap[k] = v\n\t\t\topts.Envs = append(opts.Envs, kubecontainer.EnvVar{Name: k, Value: v})\n\t\t}\n\n\t\t// Updates RunContainerOptions.Devices.\n\t\tfor _, dev := range resp.Devices {\n\t\t\tif d, ok := devsMap[dev.ContainerPath]; ok {\n\t\t\t\tklog.V(4).InfoS(\"Skip existing device\", \"containerPath\", dev.ContainerPath, \"hostPath\", dev.HostPath)\n\t\t\t\tif d != dev.HostPath {\n\t\t\t\t\tklog.ErrorS(nil, \"Container device has conflicting mapping host devices\",\n\t\t\t\t\t\t\"containerPath\", dev.ContainerPath, \"got\", d, \"expected\", dev.HostPath)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tklog.V(4).InfoS(\"Add device\", \"containerPath\", dev.ContainerPath, \"hostPath\", dev.HostPath)\n\t\t\tdevsMap[dev.ContainerPath] = dev.HostPath\n\t\t\topts.Devices = append(opts.Devices, kubecontainer.DeviceInfo{\n\t\t\t\tPathOnHost: dev.HostPath,\n\t\t\t\tPathInContainer: dev.ContainerPath,\n\t\t\t\tPermissions: dev.Permissions,\n\t\t\t})\n\t\t}\n\n\t\t// Updates RunContainerOptions.Mounts.\n\t\tfor _, mount := range resp.Mounts {\n\t\t\tif m, ok := mountsMap[mount.ContainerPath]; ok {\n\t\t\t\tklog.V(4).InfoS(\"Skip existing mount\", \"containerPath\", mount.ContainerPath, \"hostPath\", mount.HostPath)\n\t\t\t\tif m != mount.HostPath {\n\t\t\t\t\tklog.ErrorS(nil, \"Container mount has conflicting mapping host mounts\",\n\t\t\t\t\t\t\"containerPath\", mount.ContainerPath, \"conflictingPath\", m, \"hostPath\", mount.HostPath)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tklog.V(4).InfoS(\"Add mount\", \"containerPath\", mount.ContainerPath, \"hostPath\", mount.HostPath)\n\t\t\tmountsMap[mount.ContainerPath] = mount.HostPath\n\t\t\topts.Mounts = append(opts.Mounts, kubecontainer.Mount{\n\t\t\t\tName: mount.ContainerPath,\n\t\t\t\tContainerPath: mount.ContainerPath,\n\t\t\t\tHostPath: mount.HostPath,\n\t\t\t\tReadOnly: mount.ReadOnly,\n\t\t\t\t// TODO: This may need to be part of Device plugin API.\n\t\t\t\tSELinuxRelabel: false,\n\t\t\t})\n\t\t}\n\n\t\t// Updates for Annotations\n\t\tfor k, v := range resp.Annotations {\n\t\t\tif e, ok := annotationsMap[k]; ok {\n\t\t\t\tklog.V(4).InfoS(\"Skip existing annotation\", \"annotationKey\", k, \"annotationValue\", v)\n\t\t\t\tif e != v {\n\t\t\t\t\tklog.ErrorS(nil, \"Annotation has conflicting setting\", \"annotationKey\", k, \"expected\", e, \"got\", v)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tklog.V(4).InfoS(\"Add annotation\", \"annotationKey\", k, \"annotationValue\", v)\n\t\t\tannotationsMap[k] = v\n\t\t\topts.Annotations = append(opts.Annotations, kubecontainer.Annotation{Name: k, Value: v})\n\t\t}\n\t}\n\treturn opts\n}","line":{"from":228,"to":326}} {"id":100005956,"name":"getContainerDevices","signature":"func (pdev *podDevices) getContainerDevices(podUID, contName string) ResourceDeviceInstances","file":"pkg/kubelet/cm/devicemanager/pod_devices.go","code":"// getContainerDevices returns the devices assigned to the provided container for all ResourceNames\nfunc (pdev *podDevices) getContainerDevices(podUID, contName string) ResourceDeviceInstances {\n\tpdev.RLock()\n\tdefer pdev.RUnlock()\n\n\tif _, podExists := pdev.devs[podUID]; !podExists {\n\t\treturn nil\n\t}\n\tif _, contExists := pdev.devs[podUID][contName]; !contExists {\n\t\treturn nil\n\t}\n\tresDev := NewResourceDeviceInstances()\n\tfor resource, allocateInfo := range pdev.devs[podUID][contName] {\n\t\tif len(allocateInfo.deviceIds) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tdevicePluginMap := make(map[string]pluginapi.Device)\n\t\tfor numaid, devlist := range allocateInfo.deviceIds {\n\t\t\tfor _, devID := range devlist {\n\t\t\t\tvar topology *pluginapi.TopologyInfo\n\t\t\t\tif numaid != nodeWithoutTopology {\n\t\t\t\t\tNUMANodes := []*pluginapi.NUMANode{{ID: numaid}}\n\t\t\t\t\tif pDev, ok := devicePluginMap[devID]; ok \u0026\u0026 pDev.Topology != nil {\n\t\t\t\t\t\tif nodes := pDev.Topology.GetNodes(); nodes != nil {\n\t\t\t\t\t\t\tNUMANodes = append(NUMANodes, nodes...)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// ID and Healthy are not relevant here.\n\t\t\t\t\ttopology = \u0026pluginapi.TopologyInfo{Nodes: NUMANodes}\n\t\t\t\t}\n\t\t\t\tdevicePluginMap[devID] = pluginapi.Device{\n\t\t\t\t\tTopology: topology,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tresDev[resource] = devicePluginMap\n\t}\n\treturn resDev\n}","line":{"from":328,"to":367}} {"id":100005957,"name":"NewResourceDeviceInstances","signature":"func NewResourceDeviceInstances() ResourceDeviceInstances","file":"pkg/kubelet/cm/devicemanager/pod_devices.go","code":"// NewResourceDeviceInstances returns a new ResourceDeviceInstances\nfunc NewResourceDeviceInstances() ResourceDeviceInstances {\n\treturn make(ResourceDeviceInstances)\n}","line":{"from":375,"to":378}} {"id":100005958,"name":"Clone","signature":"func (rdev ResourceDeviceInstances) Clone() ResourceDeviceInstances","file":"pkg/kubelet/cm/devicemanager/pod_devices.go","code":"// Clone returns a clone of ResourceDeviceInstances\nfunc (rdev ResourceDeviceInstances) Clone() ResourceDeviceInstances {\n\tclone := NewResourceDeviceInstances()\n\tfor resourceName, resourceDevs := range rdev {\n\t\tclone[resourceName] = make(map[string]pluginapi.Device)\n\t\tfor devID, dev := range resourceDevs {\n\t\t\tclone[resourceName][devID] = dev\n\t\t}\n\t}\n\treturn clone\n}","line":{"from":380,"to":390}} {"id":100005959,"name":"Filter","signature":"func (rdev ResourceDeviceInstances) Filter(cond map[string]sets.String) ResourceDeviceInstances","file":"pkg/kubelet/cm/devicemanager/pod_devices.go","code":"// Filter takes a condition set expressed as map[string]sets.String and returns a new\n// ResourceDeviceInstances with only the devices matching the condition set.\nfunc (rdev ResourceDeviceInstances) Filter(cond map[string]sets.String) ResourceDeviceInstances {\n\tfiltered := NewResourceDeviceInstances()\n\tfor resourceName, filterIDs := range cond {\n\t\tif _, exists := rdev[resourceName]; !exists {\n\t\t\tcontinue\n\t\t}\n\t\tfiltered[resourceName] = DeviceInstances{}\n\t\tfor instanceID, instance := range rdev[resourceName] {\n\t\t\tif filterIDs.Has(instanceID) {\n\t\t\t\tfiltered[resourceName][instanceID] = instance\n\t\t\t}\n\t\t}\n\t}\n\treturn filtered\n}","line":{"from":392,"to":408}} {"id":100005960,"name":"GetTopologyHints","signature":"func (m *ManagerImpl) GetTopologyHints(pod *v1.Pod, container *v1.Container) map[string][]topologymanager.TopologyHint","file":"pkg/kubelet/cm/devicemanager/topology_hints.go","code":"// GetTopologyHints implements the TopologyManager HintProvider Interface which\n// ensures the Device Manager is consulted when Topology Aware Hints for each\n// container are created.\nfunc (m *ManagerImpl) GetTopologyHints(pod *v1.Pod, container *v1.Container) map[string][]topologymanager.TopologyHint {\n\t// The pod is during the admission phase. We need to save the pod to avoid it\n\t// being cleaned before the admission ended\n\tm.setPodPendingAdmission(pod)\n\n\t// Garbage collect any stranded device resources before providing TopologyHints\n\tm.UpdateAllocatedDevices()\n\n\t// Loop through all device resources and generate TopologyHints for them..\n\tdeviceHints := make(map[string][]topologymanager.TopologyHint)\n\taccumulatedResourceRequests := m.getContainerDeviceRequest(container)\n\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\tfor resource, requested := range accumulatedResourceRequests {\n\t\t// Only consider devices that actually contain topology information.\n\t\tif aligned := m.deviceHasTopologyAlignment(resource); !aligned {\n\t\t\tklog.InfoS(\"Resource does not have a topology preference\", \"resource\", resource)\n\t\t\tdeviceHints[resource] = nil\n\t\t\tcontinue\n\t\t}\n\n\t\t// Short circuit to regenerate the same hints if there are already\n\t\t// devices allocated to the Container. This might happen after a\n\t\t// kubelet restart, for example.\n\t\tallocated := m.podDevices.containerDevices(string(pod.UID), container.Name, resource)\n\t\tif allocated.Len() \u003e 0 {\n\t\t\tif allocated.Len() != requested {\n\t\t\t\tklog.ErrorS(nil, \"Resource already allocated to pod with different number than request\", \"resource\", resource, \"pod\", klog.KObj(pod), \"containerName\", container.Name, \"request\", requested, \"allocated\", allocated.Len())\n\t\t\t\tdeviceHints[resource] = []topologymanager.TopologyHint{}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tklog.InfoS(\"Regenerating TopologyHints for resource already allocated to pod\", \"resource\", resource, \"pod\", klog.KObj(pod), \"containerName\", container.Name)\n\t\t\tdeviceHints[resource] = m.generateDeviceTopologyHints(resource, allocated, sets.String{}, requested)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Get the list of available devices, for which TopologyHints should be generated.\n\t\tavailable := m.getAvailableDevices(resource)\n\t\treusable := m.devicesToReuse[string(pod.UID)][resource]\n\t\tif available.Union(reusable).Len() \u003c requested {\n\t\t\tklog.ErrorS(nil, \"Unable to generate topology hints: requested number of devices unavailable\", \"resource\", resource, \"request\", requested, \"available\", available.Union(reusable).Len())\n\t\t\tdeviceHints[resource] = []topologymanager.TopologyHint{}\n\t\t\tcontinue\n\t\t}\n\n\t\t// Generate TopologyHints for this resource given the current\n\t\t// request size and the list of available devices.\n\t\tdeviceHints[resource] = m.generateDeviceTopologyHints(resource, available, reusable, requested)\n\t}\n\n\treturn deviceHints\n}","line":{"from":30,"to":85}} {"id":100005961,"name":"GetPodTopologyHints","signature":"func (m *ManagerImpl) GetPodTopologyHints(pod *v1.Pod) map[string][]topologymanager.TopologyHint","file":"pkg/kubelet/cm/devicemanager/topology_hints.go","code":"// GetPodTopologyHints implements the topologymanager.HintProvider Interface which\n// ensures the Device Manager is consulted when Topology Aware Hints for Pod are created.\nfunc (m *ManagerImpl) GetPodTopologyHints(pod *v1.Pod) map[string][]topologymanager.TopologyHint {\n\t// The pod is during the admission phase. We need to save the pod to avoid it\n\t// being cleaned before the admission ended\n\tm.setPodPendingAdmission(pod)\n\n\t// Garbage collect any stranded device resources before providing TopologyHints\n\tm.UpdateAllocatedDevices()\n\n\tdeviceHints := make(map[string][]topologymanager.TopologyHint)\n\taccumulatedResourceRequests := m.getPodDeviceRequest(pod)\n\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\tfor resource, requested := range accumulatedResourceRequests {\n\t\t// Only consider devices that actually contain topology information.\n\t\tif aligned := m.deviceHasTopologyAlignment(resource); !aligned {\n\t\t\tklog.InfoS(\"Resource does not have a topology preference\", \"resource\", resource)\n\t\t\tdeviceHints[resource] = nil\n\t\t\tcontinue\n\t\t}\n\n\t\t// Short circuit to regenerate the same hints if there are already\n\t\t// devices allocated to the Pod. This might happen after a\n\t\t// kubelet restart, for example.\n\t\tallocated := m.podDevices.podDevices(string(pod.UID), resource)\n\t\tif allocated.Len() \u003e 0 {\n\t\t\tif allocated.Len() != requested {\n\t\t\t\tklog.ErrorS(nil, \"Resource already allocated to pod with different number than request\", \"resource\", resource, \"pod\", klog.KObj(pod), \"request\", requested, \"allocated\", allocated.Len())\n\t\t\t\tdeviceHints[resource] = []topologymanager.TopologyHint{}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tklog.InfoS(\"Regenerating TopologyHints for resource already allocated to pod\", \"resource\", resource, \"pod\", klog.KObj(pod))\n\t\t\tdeviceHints[resource] = m.generateDeviceTopologyHints(resource, allocated, sets.String{}, requested)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Get the list of available devices, for which TopologyHints should be generated.\n\t\tavailable := m.getAvailableDevices(resource)\n\t\tif available.Len() \u003c requested {\n\t\t\tklog.ErrorS(nil, \"Unable to generate topology hints: requested number of devices unavailable\", \"resource\", resource, \"request\", requested, \"available\", available.Len())\n\t\t\tdeviceHints[resource] = []topologymanager.TopologyHint{}\n\t\t\tcontinue\n\t\t}\n\n\t\t// Generate TopologyHints for this resource given the current\n\t\t// request size and the list of available devices.\n\t\tdeviceHints[resource] = m.generateDeviceTopologyHints(resource, available, sets.String{}, requested)\n\t}\n\n\treturn deviceHints\n}","line":{"from":87,"to":139}} {"id":100005962,"name":"deviceHasTopologyAlignment","signature":"func (m *ManagerImpl) deviceHasTopologyAlignment(resource string) bool","file":"pkg/kubelet/cm/devicemanager/topology_hints.go","code":"func (m *ManagerImpl) deviceHasTopologyAlignment(resource string) bool {\n\t// If any device has Topology NUMANodes available, we assume they care about alignment.\n\tfor _, device := range m.allDevices[resource] {\n\t\tif device.Topology != nil \u0026\u0026 len(device.Topology.Nodes) \u003e 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":141,"to":149}} {"id":100005963,"name":"getAvailableDevices","signature":"func (m *ManagerImpl) getAvailableDevices(resource string) sets.String","file":"pkg/kubelet/cm/devicemanager/topology_hints.go","code":"func (m *ManagerImpl) getAvailableDevices(resource string) sets.String {\n\t// Strip all devices in use from the list of healthy ones.\n\treturn m.healthyDevices[resource].Difference(m.allocatedDevices[resource])\n}","line":{"from":151,"to":154}} {"id":100005964,"name":"generateDeviceTopologyHints","signature":"func (m *ManagerImpl) generateDeviceTopologyHints(resource string, available sets.String, reusable sets.String, request int) []topologymanager.TopologyHint","file":"pkg/kubelet/cm/devicemanager/topology_hints.go","code":"func (m *ManagerImpl) generateDeviceTopologyHints(resource string, available sets.String, reusable sets.String, request int) []topologymanager.TopologyHint {\n\t// Initialize minAffinitySize to include all NUMA Nodes\n\tminAffinitySize := len(m.numaNodes)\n\n\t// Iterate through all combinations of NUMA Nodes and build hints from them.\n\thints := []topologymanager.TopologyHint{}\n\tbitmask.IterateBitMasks(m.numaNodes, func(mask bitmask.BitMask) {\n\t\t// First, update minAffinitySize for the current request size.\n\t\tdevicesInMask := 0\n\t\tfor _, device := range m.allDevices[resource] {\n\t\t\tif mask.AnySet(m.getNUMANodeIds(device.Topology)) {\n\t\t\t\tdevicesInMask++\n\t\t\t}\n\t\t}\n\t\tif devicesInMask \u003e= request \u0026\u0026 mask.Count() \u003c minAffinitySize {\n\t\t\tminAffinitySize = mask.Count()\n\t\t}\n\n\t\t// Then check to see if all of the reusable devices are part of the bitmask.\n\t\tnumMatching := 0\n\t\tfor d := range reusable {\n\t\t\t// Skip the device if it doesn't specify any topology info.\n\t\t\tif m.allDevices[resource][d].Topology == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Otherwise disregard this mask if its NUMANode isn't part of it.\n\t\t\tif !mask.AnySet(m.getNUMANodeIds(m.allDevices[resource][d].Topology)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tnumMatching++\n\t\t}\n\n\t\t// Finally, check to see if enough available devices remain on the\n\t\t// current NUMA node combination to satisfy the device request.\n\t\tfor d := range available {\n\t\t\tif mask.AnySet(m.getNUMANodeIds(m.allDevices[resource][d].Topology)) {\n\t\t\t\tnumMatching++\n\t\t\t}\n\t\t}\n\n\t\t// If they don't, then move onto the next combination.\n\t\tif numMatching \u003c request {\n\t\t\treturn\n\t\t}\n\n\t\t// Otherwise, create a new hint from the NUMA mask and add it to the\n\t\t// list of hints. We set all hint preferences to 'false' on the first\n\t\t// pass through.\n\t\thints = append(hints, topologymanager.TopologyHint{\n\t\t\tNUMANodeAffinity: mask,\n\t\t\tPreferred: false,\n\t\t})\n\t})\n\n\t// Loop back through all hints and update the 'Preferred' field based on\n\t// counting the number of bits sets in the affinity mask and comparing it\n\t// to the minAffinity. Only those with an equal number of bits set will be\n\t// considered preferred.\n\tfor i := range hints {\n\t\tif hints[i].NUMANodeAffinity.Count() == minAffinitySize {\n\t\t\thints[i].Preferred = true\n\t\t}\n\t}\n\n\treturn hints\n}","line":{"from":156,"to":221}} {"id":100005965,"name":"getNUMANodeIds","signature":"func (m *ManagerImpl) getNUMANodeIds(topology *pluginapi.TopologyInfo) []int","file":"pkg/kubelet/cm/devicemanager/topology_hints.go","code":"func (m *ManagerImpl) getNUMANodeIds(topology *pluginapi.TopologyInfo) []int {\n\tif topology == nil {\n\t\treturn nil\n\t}\n\tvar ids []int\n\tfor _, n := range topology.Nodes {\n\t\tids = append(ids, int(n.ID))\n\t}\n\treturn ids\n}","line":{"from":223,"to":232}} {"id":100005966,"name":"getPodDeviceRequest","signature":"func (m *ManagerImpl) getPodDeviceRequest(pod *v1.Pod) map[string]int","file":"pkg/kubelet/cm/devicemanager/topology_hints.go","code":"func (m *ManagerImpl) getPodDeviceRequest(pod *v1.Pod) map[string]int {\n\t// for these device plugin resources, requests == limits\n\tlimits := resource.PodLimits(pod, resource.PodResourcesOptions{\n\t\tExcludeOverhead: true,\n\t})\n\tpodRequests := make(map[string]int)\n\tfor resourceName, quantity := range limits {\n\t\tif !m.isDevicePluginResource(string(resourceName)) {\n\t\t\tcontinue\n\t\t}\n\t\tpodRequests[string(resourceName)] = int(quantity.Value())\n\t}\n\treturn podRequests\n}","line":{"from":234,"to":247}} {"id":100005967,"name":"getContainerDeviceRequest","signature":"func (m *ManagerImpl) getContainerDeviceRequest(container *v1.Container) map[string]int","file":"pkg/kubelet/cm/devicemanager/topology_hints.go","code":"func (m *ManagerImpl) getContainerDeviceRequest(container *v1.Container) map[string]int {\n\tcontainerRequests := make(map[string]int)\n\tfor resourceObj, requestedObj := range container.Resources.Limits {\n\t\tresource := string(resourceObj)\n\t\trequested := int(requestedObj.Value())\n\t\tif !m.isDevicePluginResource(resource) {\n\t\t\tcontinue\n\t\t}\n\t\tcontainerRequests[resource] = requested\n\t}\n\treturn containerRequests\n}","line":{"from":249,"to":260}} {"id":100005968,"name":"generateCDIAnnotations","signature":"func generateCDIAnnotations(","file":"pkg/kubelet/cm/dra/cdi.go","code":"// generate container annotations using CDI UpdateAnnotations API.\nfunc generateCDIAnnotations(\n\tclaimUID types.UID,\n\tdriverName string,\n\tcdiDevices []string,\n) ([]kubecontainer.Annotation, error) {\n\tannotations, err := updateAnnotations(map[string]string{}, driverName, string(claimUID), cdiDevices)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't generate CDI annotations: %+v\", err)\n\t}\n\n\tkubeAnnotations := []kubecontainer.Annotation{}\n\tfor key, value := range annotations {\n\t\tkubeAnnotations = append(kubeAnnotations, kubecontainer.Annotation{Name: key, Value: value})\n\t}\n\n\treturn kubeAnnotations, nil\n}","line":{"from":42,"to":59}} {"id":100005969,"name":"updateAnnotations","signature":"func updateAnnotations(annotations map[string]string, plugin string, deviceID string, devices []string) (map[string]string, error)","file":"pkg/kubelet/cm/dra/cdi.go","code":"// updateAnnotations updates annotations with a plugin-specific CDI device\n// injection request for the given devices. Upon any error a non-nil error\n// is returned and annotations are left intact. By convention plugin should\n// be in the format of \"vendor.device-type\".\nfunc updateAnnotations(annotations map[string]string, plugin string, deviceID string, devices []string) (map[string]string, error) {\n\tkey, err := annotationKey(plugin, deviceID)\n\tif err != nil {\n\t\treturn annotations, fmt.Errorf(\"CDI annotation failed: %v\", err)\n\t}\n\tif _, ok := annotations[key]; ok {\n\t\treturn annotations, fmt.Errorf(\"CDI annotation failed, key %q used\", key)\n\t}\n\tvalue, err := annotationValue(devices)\n\tif err != nil {\n\t\treturn annotations, fmt.Errorf(\"CDI annotation failed: %v\", err)\n\t}\n\n\tif annotations == nil {\n\t\tannotations = make(map[string]string)\n\t}\n\tannotations[key] = value\n\n\treturn annotations, nil\n}","line":{"from":61,"to":84}} {"id":100005970,"name":"annotationKey","signature":"func annotationKey(pluginName, deviceID string) (string, error)","file":"pkg/kubelet/cm/dra/cdi.go","code":"// annotationKey returns a unique annotation key for an device allocation\n// by a K8s device plugin. pluginName should be in the format of\n// \"vendor.device-type\". deviceID is the ID of the device the plugin is\n// allocating. It is used to make sure that the generated key is unique\n// even if multiple allocations by a single plugin needs to be annotated.\nfunc annotationKey(pluginName, deviceID string) (string, error) {\n\tconst maxNameLen = 63\n\n\tif pluginName == \"\" {\n\t\treturn \"\", errors.New(\"invalid plugin name, empty\")\n\t}\n\tif deviceID == \"\" {\n\t\treturn \"\", errors.New(\"invalid deviceID, empty\")\n\t}\n\n\tname := pluginName + \"_\" + strings.ReplaceAll(deviceID, \"/\", \"_\")\n\n\tif len(name) \u003e maxNameLen {\n\t\treturn \"\", fmt.Errorf(\"invalid plugin+deviceID %q, too long\", name)\n\t}\n\n\tif c := rune(name[0]); !isAlphaNumeric(c) {\n\t\treturn \"\", fmt.Errorf(\"invalid name %q, first '%c' should be alphanumeric\", name, c)\n\t}\n\tif len(name) \u003e 2 {\n\t\tfor _, c := range name[1 : len(name)-1] {\n\t\t\tswitch {\n\t\t\tcase isAlphaNumeric(c):\n\t\t\tcase c == '_' || c == '-' || c == '.':\n\t\t\tdefault:\n\t\t\t\treturn \"\", fmt.Errorf(\"invalid name %q, invalid charcter '%c'\", name, c)\n\t\t\t}\n\t\t}\n\t}\n\tif c := rune(name[len(name)-1]); !isAlphaNumeric(c) {\n\t\treturn \"\", fmt.Errorf(\"invalid name %q, last '%c' should be alphanumeric\", name, c)\n\t}\n\n\treturn annotationPrefix + name, nil\n}","line":{"from":86,"to":125}} {"id":100005971,"name":"annotationValue","signature":"func annotationValue(devices []string) (string, error)","file":"pkg/kubelet/cm/dra/cdi.go","code":"// annotationValue returns an annotation value for the given devices.\nfunc annotationValue(devices []string) (string, error) {\n\tvalue, sep := \"\", \"\"\n\tfor _, d := range devices {\n\t\tif _, _, _, err := parseQualifiedName(d); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tvalue += sep + d\n\t\tsep = \",\"\n\t}\n\n\treturn value, nil\n}","line":{"from":127,"to":139}} {"id":100005972,"name":"parseQualifiedName","signature":"func parseQualifiedName(device string) (string, string, string, error)","file":"pkg/kubelet/cm/dra/cdi.go","code":"// parseQualifiedName splits a qualified name into device vendor, class,\n// and name. If the device fails to parse as a qualified name, or if any\n// of the split components fail to pass syntax validation, vendor and\n// class are returned as empty, together with the verbatim input as the\n// name and an error describing the reason for failure.\nfunc parseQualifiedName(device string) (string, string, string, error) {\n\tvendor, class, name := parseDevice(device)\n\n\tif vendor == \"\" {\n\t\treturn \"\", \"\", device, fmt.Errorf(\"unqualified device %q, missing vendor\", device)\n\t}\n\tif class == \"\" {\n\t\treturn \"\", \"\", device, fmt.Errorf(\"unqualified device %q, missing class\", device)\n\t}\n\tif name == \"\" {\n\t\treturn \"\", \"\", device, fmt.Errorf(\"unqualified device %q, missing device name\", device)\n\t}\n\n\tif err := validateVendorName(vendor); err != nil {\n\t\treturn \"\", \"\", device, fmt.Errorf(\"invalid device %q: %v\", device, err)\n\t}\n\tif err := validateClassName(class); err != nil {\n\t\treturn \"\", \"\", device, fmt.Errorf(\"invalid device %q: %v\", device, err)\n\t}\n\tif err := validateDeviceName(name); err != nil {\n\t\treturn \"\", \"\", device, fmt.Errorf(\"invalid device %q: %v\", device, err)\n\t}\n\n\treturn vendor, class, name, nil\n}","line":{"from":141,"to":170}} {"id":100005973,"name":"parseDevice","signature":"func parseDevice(device string) (string, string, string)","file":"pkg/kubelet/cm/dra/cdi.go","code":"// parseDevice tries to split a device name into vendor, class, and name.\n// If this fails, for instance in the case of unqualified device names,\n// parseDevice returns an empty vendor and class together with name set\n// to the verbatim input.\nfunc parseDevice(device string) (string, string, string) {\n\tif device == \"\" || device[0] == '/' {\n\t\treturn \"\", \"\", device\n\t}\n\n\tparts := strings.SplitN(device, \"=\", 2)\n\tif len(parts) != 2 || parts[0] == \"\" || parts[1] == \"\" {\n\t\treturn \"\", \"\", device\n\t}\n\n\tname := parts[1]\n\tvendor, class := parseQualifier(parts[0])\n\tif vendor == \"\" {\n\t\treturn \"\", \"\", device\n\t}\n\n\treturn vendor, class, name\n}","line":{"from":172,"to":193}} {"id":100005974,"name":"parseQualifier","signature":"func parseQualifier(kind string) (string, string)","file":"pkg/kubelet/cm/dra/cdi.go","code":"// parseQualifier splits a device qualifier into vendor and class.\n// The syntax for a device qualifier is\n//\n//\t\"\u003cvendor\u003e/\u003cclass\u003e\"\n//\n// If parsing fails, an empty vendor and the class set to the\n// verbatim input is returned.\nfunc parseQualifier(kind string) (string, string) {\n\tparts := strings.SplitN(kind, \"/\", 2)\n\tif len(parts) != 2 || parts[0] == \"\" || parts[1] == \"\" {\n\t\treturn \"\", kind\n\t}\n\treturn parts[0], parts[1]\n}","line":{"from":195,"to":208}} {"id":100005975,"name":"validateVendorName","signature":"func validateVendorName(vendor string) error","file":"pkg/kubelet/cm/dra/cdi.go","code":"// validateVendorName checks the validity of a vendor name.\n// A vendor name may contain the following ASCII characters:\n// - upper- and lowercase letters ('A'-'Z', 'a'-'z')\n// - digits ('0'-'9')\n// - underscore, dash, and dot ('_', '-', and '.')\nfunc validateVendorName(vendor string) error {\n\tif vendor == \"\" {\n\t\treturn fmt.Errorf(\"invalid (empty) vendor name\")\n\t}\n\tif !isLetter(rune(vendor[0])) {\n\t\treturn fmt.Errorf(\"invalid vendor %q, should start with letter\", vendor)\n\t}\n\tfor _, c := range string(vendor[1 : len(vendor)-1]) {\n\t\tswitch {\n\t\tcase isAlphaNumeric(c):\n\t\tcase c == '_' || c == '-' || c == '.':\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"invalid character '%c' in vendor name %q\",\n\t\t\t\tc, vendor)\n\t\t}\n\t}\n\tif !isAlphaNumeric(rune(vendor[len(vendor)-1])) {\n\t\treturn fmt.Errorf(\"invalid vendor %q, should end with a letter or digit\", vendor)\n\t}\n\n\treturn nil\n}","line":{"from":210,"to":236}} {"id":100005976,"name":"validateClassName","signature":"func validateClassName(class string) error","file":"pkg/kubelet/cm/dra/cdi.go","code":"// validateClassName checks the validity of class name.\n// A class name may contain the following ASCII characters:\n// - upper- and lowercase letters ('A'-'Z', 'a'-'z')\n// - digits ('0'-'9')\n// - underscore and dash ('_', '-')\nfunc validateClassName(class string) error {\n\tif class == \"\" {\n\t\treturn fmt.Errorf(\"invalid (empty) device class\")\n\t}\n\tif !isLetter(rune(class[0])) {\n\t\treturn fmt.Errorf(\"invalid class %q, should start with letter\", class)\n\t}\n\tfor _, c := range string(class[1 : len(class)-1]) {\n\t\tswitch {\n\t\tcase isAlphaNumeric(c):\n\t\tcase c == '_' || c == '-':\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"invalid character '%c' in device class %q\",\n\t\t\t\tc, class)\n\t\t}\n\t}\n\tif !isAlphaNumeric(rune(class[len(class)-1])) {\n\t\treturn fmt.Errorf(\"invalid class %q, should end with a letter or digit\", class)\n\t}\n\treturn nil\n}","line":{"from":238,"to":263}} {"id":100005977,"name":"validateDeviceName","signature":"func validateDeviceName(name string) error","file":"pkg/kubelet/cm/dra/cdi.go","code":"// validateDeviceName checks the validity of a device name.\n// A device name may contain the following ASCII characters:\n// - upper- and lowercase letters ('A'-'Z', 'a'-'z')\n// - digits ('0'-'9')\n// - underscore, dash, dot, colon ('_', '-', '.', ':')\nfunc validateDeviceName(name string) error {\n\tif name == \"\" {\n\t\treturn fmt.Errorf(\"invalid (empty) device name\")\n\t}\n\tif !isAlphaNumeric(rune(name[0])) {\n\t\treturn fmt.Errorf(\"invalid class %q, should start with a letter or digit\", name)\n\t}\n\tif len(name) == 1 {\n\t\treturn nil\n\t}\n\tfor _, c := range string(name[1 : len(name)-1]) {\n\t\tswitch {\n\t\tcase isAlphaNumeric(c):\n\t\tcase c == '_' || c == '-' || c == '.' || c == ':':\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"invalid character '%c' in device name %q\",\n\t\t\t\tc, name)\n\t\t}\n\t}\n\tif !isAlphaNumeric(rune(name[len(name)-1])) {\n\t\treturn fmt.Errorf(\"invalid name %q, should end with a letter or digit\", name)\n\t}\n\treturn nil\n}","line":{"from":265,"to":293}} {"id":100005978,"name":"isLetter","signature":"func isLetter(c rune) bool","file":"pkg/kubelet/cm/dra/cdi.go","code":"func isLetter(c rune) bool {\n\treturn ('A' \u003c= c \u0026\u0026 c \u003c= 'Z') || ('a' \u003c= c \u0026\u0026 c \u003c= 'z')\n}","line":{"from":295,"to":297}} {"id":100005979,"name":"isDigit","signature":"func isDigit(c rune) bool","file":"pkg/kubelet/cm/dra/cdi.go","code":"func isDigit(c rune) bool {\n\treturn '0' \u003c= c \u0026\u0026 c \u003c= '9'\n}","line":{"from":299,"to":301}} {"id":100005980,"name":"isAlphaNumeric","signature":"func isAlphaNumeric(c rune) bool","file":"pkg/kubelet/cm/dra/cdi.go","code":"func isAlphaNumeric(c rune) bool {\n\treturn isLetter(c) || isDigit(c)\n}","line":{"from":303,"to":305}} {"id":100005981,"name":"addPodReference","signature":"func (info *ClaimInfo) addPodReference(podUID types.UID)","file":"pkg/kubelet/cm/dra/claiminfo.go","code":"func (info *ClaimInfo) addPodReference(podUID types.UID) {\n\tinfo.Lock()\n\tdefer info.Unlock()\n\n\tinfo.PodUIDs.Insert(string(podUID))\n}","line":{"from":39,"to":44}} {"id":100005982,"name":"deletePodReference","signature":"func (info *ClaimInfo) deletePodReference(podUID types.UID)","file":"pkg/kubelet/cm/dra/claiminfo.go","code":"func (info *ClaimInfo) deletePodReference(podUID types.UID) {\n\tinfo.Lock()\n\tdefer info.Unlock()\n\n\tinfo.PodUIDs.Delete(string(podUID))\n}","line":{"from":46,"to":51}} {"id":100005983,"name":"addCDIDevices","signature":"func (info *ClaimInfo) addCDIDevices(pluginName string, cdiDevices []string) error","file":"pkg/kubelet/cm/dra/claiminfo.go","code":"func (info *ClaimInfo) addCDIDevices(pluginName string, cdiDevices []string) error {\n\tinfo.Lock()\n\tdefer info.Unlock()\n\n\t// NOTE: Passing CDI device names as annotations is a temporary solution\n\t// It will be removed after all runtimes are updated\n\t// to get CDI device names from the ContainerConfig.CDIDevices field\n\tannotations, err := generateCDIAnnotations(info.ClaimUID, info.DriverName, cdiDevices)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to generate container annotations, err: %+v\", err)\n\t}\n\n\tif info.CDIDevices == nil {\n\t\tinfo.CDIDevices = make(map[string][]string)\n\t}\n\n\tinfo.CDIDevices[pluginName] = cdiDevices\n\tinfo.annotations = append(info.annotations, annotations...)\n\n\treturn nil\n}","line":{"from":53,"to":73}} {"id":100005984,"name":"newClaimInfo","signature":"func newClaimInfo(driverName, className string, claimUID types.UID, claimName, namespace string, podUIDs sets.Set[string]) *ClaimInfo","file":"pkg/kubelet/cm/dra/claiminfo.go","code":"func newClaimInfo(driverName, className string, claimUID types.UID, claimName, namespace string, podUIDs sets.Set[string]) *ClaimInfo {\n\tclaimInfoState := state.ClaimInfoState{\n\t\tDriverName: driverName,\n\t\tClassName: className,\n\t\tClaimUID: claimUID,\n\t\tClaimName: claimName,\n\t\tNamespace: namespace,\n\t\tPodUIDs: podUIDs,\n\t}\n\tclaimInfo := ClaimInfo{\n\t\tClaimInfoState: claimInfoState,\n\t}\n\treturn \u0026claimInfo\n}","line":{"from":82,"to":95}} {"id":100005985,"name":"newClaimInfoCache","signature":"func newClaimInfoCache(stateDir, checkpointName string) (*claimInfoCache, error)","file":"pkg/kubelet/cm/dra/claiminfo.go","code":"// newClaimInfoCache is a function that returns an instance of the claimInfoCache.\nfunc newClaimInfoCache(stateDir, checkpointName string) (*claimInfoCache, error) {\n\tstateImpl, err := state.NewCheckpointState(stateDir, checkpointName)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not initialize checkpoint manager, please drain node and remove dra state file, err: %+v\", err)\n\t}\n\n\tcurState, err := stateImpl.GetOrCreate()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error calling GetOrCreate() on checkpoint state: %v\", err)\n\t}\n\n\tcache := \u0026claimInfoCache{\n\t\tstate: stateImpl,\n\t\tclaimInfo: make(map[string]*ClaimInfo),\n\t}\n\n\tfor _, entry := range curState {\n\t\tinfo := newClaimInfo(\n\t\t\tentry.DriverName,\n\t\t\tentry.ClassName,\n\t\t\tentry.ClaimUID,\n\t\t\tentry.ClaimName,\n\t\t\tentry.Namespace,\n\t\t\tentry.PodUIDs,\n\t\t)\n\t\tfor pluginName, cdiDevices := range entry.CDIDevices {\n\t\t\terr := info.addCDIDevices(pluginName, cdiDevices)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to add CDIDevices to claimInfo %+v: %+v\", info, err)\n\t\t\t}\n\t\t}\n\t\tcache.add(info)\n\t}\n\n\treturn cache, nil\n}","line":{"from":97,"to":133}} {"id":100005986,"name":"add","signature":"func (cache *claimInfoCache) add(res *ClaimInfo)","file":"pkg/kubelet/cm/dra/claiminfo.go","code":"func (cache *claimInfoCache) add(res *ClaimInfo) {\n\tcache.Lock()\n\tdefer cache.Unlock()\n\n\tcache.claimInfo[res.ClaimName+res.Namespace] = res\n}","line":{"from":135,"to":140}} {"id":100005987,"name":"get","signature":"func (cache *claimInfoCache) get(claimName, namespace string) *ClaimInfo","file":"pkg/kubelet/cm/dra/claiminfo.go","code":"func (cache *claimInfoCache) get(claimName, namespace string) *ClaimInfo {\n\tcache.RLock()\n\tdefer cache.RUnlock()\n\n\treturn cache.claimInfo[claimName+namespace]\n}","line":{"from":142,"to":147}} {"id":100005988,"name":"delete","signature":"func (cache *claimInfoCache) delete(claimName, namespace string)","file":"pkg/kubelet/cm/dra/claiminfo.go","code":"func (cache *claimInfoCache) delete(claimName, namespace string) {\n\tcache.Lock()\n\tdefer cache.Unlock()\n\n\tdelete(cache.claimInfo, claimName+namespace)\n}","line":{"from":149,"to":154}} {"id":100005989,"name":"hasPodReference","signature":"func (cache *claimInfoCache) hasPodReference(UID types.UID) bool","file":"pkg/kubelet/cm/dra/claiminfo.go","code":"// hasPodReference checks if there is at least one claim\n// that is referenced by the pod with the given UID\n// This function is used indirectly by the status manager\n// to check if pod can enter termination status\nfunc (cache *claimInfoCache) hasPodReference(UID types.UID) bool {\n\tcache.RLock()\n\tdefer cache.RUnlock()\n\n\tfor _, claimInfo := range cache.claimInfo {\n\t\tif claimInfo.PodUIDs.Has(string(UID)) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":156,"to":171}} {"id":100005990,"name":"syncToCheckpoint","signature":"func (cache *claimInfoCache) syncToCheckpoint() error","file":"pkg/kubelet/cm/dra/claiminfo.go","code":"func (cache *claimInfoCache) syncToCheckpoint() error {\n\tcache.RLock()\n\tdefer cache.RUnlock()\n\n\tclaimInfoStateList := make(state.ClaimInfoStateList, 0, len(cache.claimInfo))\n\tfor _, infoClaim := range cache.claimInfo {\n\t\tclaimInfoStateList = append(claimInfoStateList, infoClaim.ClaimInfoState)\n\t}\n\n\treturn cache.state.Store(claimInfoStateList)\n}","line":{"from":173,"to":183}} {"id":100005991,"name":"NewManagerImpl","signature":"func NewManagerImpl(kubeClient clientset.Interface, stateFileDirectory string) (*ManagerImpl, error)","file":"pkg/kubelet/cm/dra/manager.go","code":"// NewManagerImpl creates a new manager.\nfunc NewManagerImpl(kubeClient clientset.Interface, stateFileDirectory string) (*ManagerImpl, error) {\n\tklog.V(2).InfoS(\"Creating DRA manager\")\n\n\tclaimInfoCache, err := newClaimInfoCache(stateFileDirectory, draManagerStateFileName)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create claimInfo cache: %+v\", err)\n\t}\n\n\tmanager := \u0026ManagerImpl{\n\t\tcache: claimInfoCache,\n\t\tkubeClient: kubeClient,\n\t}\n\n\treturn manager, nil\n}","line":{"from":47,"to":62}} {"id":100005992,"name":"PrepareResources","signature":"func (m *ManagerImpl) PrepareResources(pod *v1.Pod) error","file":"pkg/kubelet/cm/dra/manager.go","code":"// PrepareResources attempts to prepare all of the required resource\n// plugin resources for the input container, issue an NodePrepareResource rpc request\n// for each new resource requirement, process their responses and update the cached\n// containerResources on success.\nfunc (m *ManagerImpl) PrepareResources(pod *v1.Pod) error {\n\t// Process resources for each resource claim referenced by container\n\tfor _, container := range append(pod.Spec.InitContainers, pod.Spec.Containers...) {\n\t\tfor range container.Resources.Claims {\n\t\t\tfor i := range pod.Spec.ResourceClaims {\n\t\t\t\tclaimName := resourceclaim.Name(pod, \u0026pod.Spec.ResourceClaims[i])\n\t\t\t\tklog.V(3).InfoS(\"Processing resource\", \"claim\", claimName, \"pod\", pod.Name)\n\n\t\t\t\t// Resource is already prepared, add pod UID to it\n\t\t\t\tif claimInfo := m.cache.get(claimName, pod.Namespace); claimInfo != nil {\n\t\t\t\t\t// We delay checkpointing of this change until this call\n\t\t\t\t\t// returns successfully. It is OK to do this because we\n\t\t\t\t\t// will only return successfully from this call if the\n\t\t\t\t\t// checkpoint has succeeded. That means if the kubelet is\n\t\t\t\t\t// ever restarted before this checkpoint succeeds, the pod\n\t\t\t\t\t// whose resources are being prepared would never have\n\t\t\t\t\t// started, so it's OK (actually correct) to not include it\n\t\t\t\t\t// in the cache.\n\t\t\t\t\tclaimInfo.addPodReference(pod.UID)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Query claim object from the API server\n\t\t\t\tresourceClaim, err := m.kubeClient.ResourceV1alpha2().ResourceClaims(pod.Namespace).Get(\n\t\t\t\t\tcontext.TODO(),\n\t\t\t\t\tclaimName,\n\t\t\t\t\tmetav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"failed to fetch ResourceClaim %s referenced by pod %s: %+v\", claimName, pod.Name, err)\n\t\t\t\t}\n\n\t\t\t\t// Check if pod is in the ReservedFor for the claim\n\t\t\t\tif !resourceclaim.IsReservedForPod(pod, resourceClaim) {\n\t\t\t\t\treturn fmt.Errorf(\"pod %s(%s) is not allowed to use resource claim %s(%s)\",\n\t\t\t\t\t\tpod.Name, pod.UID, claimName, resourceClaim.UID)\n\t\t\t\t}\n\n\t\t\t\t// Grab the allocation.resourceHandles. If there are no\n\t\t\t\t// allocation.resourceHandles, create a single resourceHandle with no\n\t\t\t\t// content. This will trigger processing of this claim by a single\n\t\t\t\t// kubelet plugin whose name matches resourceClaim.Status.DriverName.\n\t\t\t\tresourceHandles := resourceClaim.Status.Allocation.ResourceHandles\n\t\t\t\tif len(resourceHandles) == 0 {\n\t\t\t\t\tresourceHandles = make([]resourcev1alpha2.ResourceHandle, 1)\n\t\t\t\t}\n\n\t\t\t\t// Create a claimInfo object to store the relevant claim info.\n\t\t\t\tclaimInfo := newClaimInfo(\n\t\t\t\t\tresourceClaim.Status.DriverName,\n\t\t\t\t\tresourceClaim.Spec.ResourceClassName,\n\t\t\t\t\tresourceClaim.UID,\n\t\t\t\t\tresourceClaim.Name,\n\t\t\t\t\tresourceClaim.Namespace,\n\t\t\t\t\tsets.New(string(pod.UID)),\n\t\t\t\t)\n\n\t\t\t\t// Walk through each resourceHandle\n\t\t\t\tfor _, resourceHandle := range resourceHandles {\n\t\t\t\t\t// If no DriverName is provided in the resourceHandle, we\n\t\t\t\t\t// use the DriverName from the status\n\t\t\t\t\tpluginName := resourceHandle.DriverName\n\t\t\t\t\tif pluginName == \"\" {\n\t\t\t\t\t\tpluginName = resourceClaim.Status.DriverName\n\t\t\t\t\t}\n\n\t\t\t\t\t// Call NodePrepareResource RPC for each resourceHandle\n\t\t\t\t\tclient, err := dra.NewDRAPluginClient(pluginName)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn fmt.Errorf(\"failed to get DRA Plugin client for plugin name %s, err=%+v\", pluginName, err)\n\t\t\t\t\t}\n\t\t\t\t\tresponse, err := client.NodePrepareResource(\n\t\t\t\t\t\tcontext.Background(),\n\t\t\t\t\t\tresourceClaim.Namespace,\n\t\t\t\t\t\tresourceClaim.UID,\n\t\t\t\t\t\tresourceClaim.Name,\n\t\t\t\t\t\tresourceHandle.Data)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn fmt.Errorf(\"NodePrepareResource failed, claim UID: %s, claim name: %s, resource handle: %s, err: %+v\",\n\t\t\t\t\t\t\tresourceClaim.UID, resourceClaim.Name, resourceHandle.Data, err)\n\t\t\t\t\t}\n\t\t\t\t\tklog.V(3).InfoS(\"NodePrepareResource succeeded\", \"pluginName\", pluginName, \"response\", response)\n\n\t\t\t\t\t// Add the CDI Devices returned by NodePrepareResource to\n\t\t\t\t\t// the claimInfo object.\n\t\t\t\t\terr = claimInfo.addCDIDevices(pluginName, response.CdiDevices)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn fmt.Errorf(\"failed to add CDIDevices to claimInfo %+v: %+v\", claimInfo, err)\n\t\t\t\t\t}\n\n\t\t\t\t\t// TODO: We (re)add the claimInfo object to the cache and\n\t\t\t\t\t// sync it to the checkpoint *after* the\n\t\t\t\t\t// NodePrepareResource call has completed. This will cause\n\t\t\t\t\t// issues if the kubelet gets restarted between\n\t\t\t\t\t// NodePrepareResource and syncToCheckpoint. It will result\n\t\t\t\t\t// in not calling NodeUnprepareResource for this claim\n\t\t\t\t\t// because no claimInfo will be synced back to the cache\n\t\t\t\t\t// for it after the restart. We need to resolve this issue\n\t\t\t\t\t// before moving to beta.\n\t\t\t\t\tm.cache.add(claimInfo)\n\n\t\t\t\t\t// Checkpoint to reduce redundant calls to\n\t\t\t\t\t// NodePrepareResource() after a kubelet restart.\n\t\t\t\t\terr = m.cache.syncToCheckpoint()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn fmt.Errorf(\"failed to checkpoint claimInfo state, err: %+v\", err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// Checkpoint to capture all of the previous addPodReference() calls.\n\terr := m.cache.syncToCheckpoint()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to checkpoint claimInfo state, err: %+v\", err)\n\t}\n\treturn nil\n}","line":{"from":64,"to":184}} {"id":100005993,"name":"GetResources","signature":"func (m *ManagerImpl) GetResources(pod *v1.Pod, container *v1.Container) (*ContainerInfo, error)","file":"pkg/kubelet/cm/dra/manager.go","code":"// GetResources gets a ContainerInfo object from the claimInfo cache.\n// This information is used by the caller to update a container config.\nfunc (m *ManagerImpl) GetResources(pod *v1.Pod, container *v1.Container) (*ContainerInfo, error) {\n\tannotations := []kubecontainer.Annotation{}\n\tcdiDevices := []kubecontainer.CDIDevice{}\n\n\tfor i, podResourceClaim := range pod.Spec.ResourceClaims {\n\t\tclaimName := resourceclaim.Name(pod, \u0026pod.Spec.ResourceClaims[i])\n\n\t\tfor _, claim := range container.Resources.Claims {\n\t\t\tif podResourceClaim.Name != claim.Name {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tclaimInfo := m.cache.get(claimName, pod.Namespace)\n\t\t\tif claimInfo == nil {\n\t\t\t\treturn nil, fmt.Errorf(\"unable to get resource for namespace: %s, claim: %s\", pod.Namespace, claimName)\n\t\t\t}\n\n\t\t\tklog.V(3).InfoS(\"Add resource annotations\", \"claim\", claimName, \"annotations\", claimInfo.annotations)\n\t\t\tannotations = append(annotations, claimInfo.annotations...)\n\t\t\tfor _, devices := range claimInfo.CDIDevices {\n\t\t\t\tfor _, device := range devices {\n\t\t\t\t\tcdiDevices = append(cdiDevices, kubecontainer.CDIDevice{Name: device})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \u0026ContainerInfo{Annotations: annotations, CDIDevices: cdiDevices}, nil\n}","line":{"from":186,"to":216}} {"id":100005994,"name":"UnprepareResources","signature":"func (m *ManagerImpl) UnprepareResources(pod *v1.Pod) error","file":"pkg/kubelet/cm/dra/manager.go","code":"// UnprepareResources calls a plugin's NodeUnprepareResource API for each resource claim owned by a pod.\n// This function is idempotent and may be called multiple times against the same pod.\n// As such, calls to the underlying NodeUnprepareResource API are skipped for claims that have\n// already been successfully unprepared.\nfunc (m *ManagerImpl) UnprepareResources(pod *v1.Pod) error {\n\t// Call NodeUnprepareResource RPC for every resource claim referenced by the pod\n\tfor i := range pod.Spec.ResourceClaims {\n\t\tclaimName := resourceclaim.Name(pod, \u0026pod.Spec.ResourceClaims[i])\n\t\tclaimInfo := m.cache.get(claimName, pod.Namespace)\n\n\t\t// Skip calling NodeUnprepareResource if claim info is not cached\n\t\tif claimInfo == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Skip calling NodeUnprepareResource if other pods are still referencing it\n\t\tif len(claimInfo.PodUIDs) \u003e 1 {\n\t\t\t// We delay checkpointing of this change until this call returns successfully.\n\t\t\t// It is OK to do this because we will only return successfully from this call if\n\t\t\t// the checkpoint has succeeded. That means if the kubelet is ever restarted\n\t\t\t// before this checkpoint succeeds, we will simply call into this (idempotent)\n\t\t\t// function again.\n\t\t\tclaimInfo.deletePodReference(pod.UID)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Query claim object from the API server\n\t\tresourceClaim, err := m.kubeClient.ResourceV1alpha2().ResourceClaims(pod.Namespace).Get(\n\t\t\tcontext.TODO(),\n\t\t\tclaimName,\n\t\t\tmetav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to fetch ResourceClaim %s referenced by pod %s: %+v\", claimName, pod.Name, err)\n\t\t}\n\n\t\t// Grab the allocation.resourceHandles. If there are no\n\t\t// allocation.resourceHandles, create a single resourceHandle with no\n\t\t// content. This will trigger processing of this claim by a single\n\t\t// kubelet plugin whose name matches resourceClaim.Status.DriverName.\n\t\tresourceHandles := resourceClaim.Status.Allocation.ResourceHandles\n\t\tif len(resourceHandles) == 0 {\n\t\t\tresourceHandles = make([]resourcev1alpha2.ResourceHandle, 1)\n\t\t}\n\n\t\t// Loop through all plugins and call NodeUnprepareResource only for the\n\t\t// last pod that references the claim\n\t\tfor _, resourceHandle := range resourceHandles {\n\t\t\t// If no DriverName is provided in the resourceHandle, we\n\t\t\t// use the DriverName from the status\n\t\t\tpluginName := resourceHandle.DriverName\n\t\t\tif pluginName == \"\" {\n\t\t\t\tpluginName = claimInfo.DriverName\n\t\t\t}\n\n\t\t\t// Call NodeUnprepareResource RPC for each resourceHandle\n\t\t\tclient, err := dra.NewDRAPluginClient(pluginName)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to get DRA Plugin client for plugin name %s, err=%+v\", pluginName, err)\n\t\t\t}\n\t\t\tresponse, err := client.NodeUnprepareResource(\n\t\t\t\tcontext.Background(),\n\t\t\t\tclaimInfo.Namespace,\n\t\t\t\tclaimInfo.ClaimUID,\n\t\t\t\tclaimInfo.ClaimName,\n\t\t\t\tresourceHandle.Data)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"NodeUnprepareResource failed, pod: %s, claim UID: %s, claim name: %s, CDI devices: %s, err: %+v\",\n\t\t\t\t\tpod.Name, claimInfo.ClaimUID, claimInfo.ClaimName, claimInfo.CDIDevices, err)\n\t\t\t}\n\t\t\tklog.V(3).InfoS(\"NodeUnprepareResource succeeded\", \"response\", response)\n\t\t}\n\n\t\t// Delete last pod UID only if all NodeUnprepareResource calls succeed.\n\t\t// This ensures that the status manager doesn't enter termination status\n\t\t// for the pod. This logic is implemented in\n\t\t// m.PodMightNeedToUnprepareResources and claimInfo.hasPodReference.\n\t\tclaimInfo.deletePodReference(pod.UID)\n\t\tm.cache.delete(claimInfo.ClaimName, pod.Namespace)\n\n\t\t// Checkpoint to reduce redundant calls to NodeUnPrepareResource() after a kubelet restart.\n\t\terr = m.cache.syncToCheckpoint()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to checkpoint claimInfo state, err: %+v\", err)\n\t\t}\n\t}\n\t// Checkpoint to capture all of the previous deletePodReference() calls.\n\terr := m.cache.syncToCheckpoint()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to checkpoint claimInfo state, err: %+v\", err)\n\t}\n\treturn nil\n}","line":{"from":218,"to":310}} {"id":100005995,"name":"PodMightNeedToUnprepareResources","signature":"func (m *ManagerImpl) PodMightNeedToUnprepareResources(UID types.UID) bool","file":"pkg/kubelet/cm/dra/manager.go","code":"// PodMightNeedToUnprepareResources returns true if the pod might need to\n// unprepare resources\nfunc (m *ManagerImpl) PodMightNeedToUnprepareResources(UID types.UID) bool {\n\treturn m.cache.hasPodReference(UID)\n}","line":{"from":312,"to":316}} {"id":100005996,"name":"GetContainerClaimInfos","signature":"func (m *ManagerImpl) GetContainerClaimInfos(pod *v1.Pod, container *v1.Container) ([]*ClaimInfo, error)","file":"pkg/kubelet/cm/dra/manager.go","code":"// GetCongtainerClaimInfos gets Container's ClaimInfo\nfunc (m *ManagerImpl) GetContainerClaimInfos(pod *v1.Pod, container *v1.Container) ([]*ClaimInfo, error) {\n\tclaimInfos := make([]*ClaimInfo, 0, len(pod.Spec.ResourceClaims))\n\n\tfor i, podResourceClaim := range pod.Spec.ResourceClaims {\n\t\tclaimName := resourceclaim.Name(pod, \u0026pod.Spec.ResourceClaims[i])\n\n\t\tfor _, claim := range container.Resources.Claims {\n\t\t\tif podResourceClaim.Name != claim.Name {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tclaimInfo := m.cache.get(claimName, pod.Namespace)\n\t\t\tif claimInfo == nil {\n\t\t\t\treturn nil, fmt.Errorf(\"unable to get resource for namespace: %s, claim: %s\", pod.Namespace, claimName)\n\t\t\t}\n\t\t\tclaimInfos = append(claimInfos, claimInfo)\n\t\t}\n\t}\n\treturn claimInfos, nil\n}","line":{"from":318,"to":337}} {"id":100005997,"name":"newV1NodeClient","signature":"func newV1NodeClient(addr draAddr) (nodeClient drapbv1.NodeClient, closer io.Closer, err error)","file":"pkg/kubelet/cm/dra/plugin/client.go","code":"// newV1NodeClient creates a new NodeClient with the internally used gRPC\n// connection set up. It also returns a closer which must be called to close\n// the gRPC connection when the NodeClient is not used anymore.\n// This is the default implementation for the nodeV1ClientCreator, used in\n// newDRAPluginClient.\nfunc newV1NodeClient(addr draAddr) (nodeClient drapbv1.NodeClient, closer io.Closer, err error) {\n\tvar conn *grpc.ClientConn\n\n\tconn, err = newGrpcConn(addr)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn drapbv1.NewNodeClient(conn), conn, nil\n}","line":{"from":73,"to":87}} {"id":100005998,"name":"NewDRAPluginClient","signature":"func NewDRAPluginClient(pluginName string) (Client, error)","file":"pkg/kubelet/cm/dra/plugin/client.go","code":"func NewDRAPluginClient(pluginName string) (Client, error) {\n\tif pluginName == \"\" {\n\t\treturn nil, fmt.Errorf(\"plugin name is empty\")\n\t}\n\n\texistingPlugin := draPlugins.Get(pluginName)\n\tif existingPlugin == nil {\n\t\treturn nil, fmt.Errorf(\"plugin name %s not found in the list of registered DRA plugins\", pluginName)\n\t}\n\n\treturn \u0026draPluginClient{\n\t\tpluginName: pluginName,\n\t\taddr: draAddr(existingPlugin.endpoint),\n\t\tnodeV1ClientCreator: newV1NodeClient,\n\t}, nil\n}","line":{"from":89,"to":104}} {"id":100005999,"name":"NodePrepareResource","signature":"func (r *draPluginClient) NodePrepareResource(","file":"pkg/kubelet/cm/dra/plugin/client.go","code":"func (r *draPluginClient) NodePrepareResource(\n\tctx context.Context,\n\tnamespace string,\n\tclaimUID types.UID,\n\tclaimName string,\n\tresourceHandle string,\n) (*drapbv1.NodePrepareResourceResponse, error) {\n\tklog.V(4).InfoS(\n\t\tlog(\"calling NodePrepareResource rpc\"),\n\t\t\"namespace\", namespace,\n\t\t\"claimUID\", claimUID,\n\t\t\"claimName\", claimName,\n\t\t\"resourceHandle\", resourceHandle)\n\n\tif r.nodeV1ClientCreator == nil {\n\t\treturn nil, errors.New(\"failed to call NodePrepareResource. nodeV1ClientCreator is nil\")\n\t}\n\n\tnodeClient, closer, err := r.nodeV1ClientCreator(r.addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer closer.Close()\n\n\treq := \u0026drapbv1.NodePrepareResourceRequest{\n\t\tNamespace: namespace,\n\t\tClaimUid: string(claimUID),\n\t\tClaimName: claimName,\n\t\tResourceHandle: resourceHandle,\n\t}\n\n\tctx, cancel := context.WithTimeout(ctx, PluginClientTimeout)\n\tdefer cancel()\n\n\treturn nodeClient.NodePrepareResource(ctx, req)\n}","line":{"from":106,"to":141}} {"id":100006000,"name":"NodeUnprepareResource","signature":"func (r *draPluginClient) NodeUnprepareResource(","file":"pkg/kubelet/cm/dra/plugin/client.go","code":"func (r *draPluginClient) NodeUnprepareResource(\n\tctx context.Context,\n\tnamespace string,\n\tclaimUID types.UID,\n\tclaimName string,\n\tresourceHandle string,\n) (*drapbv1.NodeUnprepareResourceResponse, error) {\n\tklog.V(4).InfoS(\n\t\tlog(\"calling NodeUnprepareResource rpc\"),\n\t\t\"namespace\", namespace,\n\t\t\"claimUID\", claimUID,\n\t\t\"claimname\", claimName,\n\t\t\"resourceHandle\", resourceHandle)\n\n\tif r.nodeV1ClientCreator == nil {\n\t\treturn nil, errors.New(\"nodeV1ClientCreate is nil\")\n\t}\n\n\tnodeClient, closer, err := r.nodeV1ClientCreator(r.addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer closer.Close()\n\n\treq := \u0026drapbv1.NodeUnprepareResourceRequest{\n\t\tNamespace: namespace,\n\t\tClaimUid: string(claimUID),\n\t\tClaimName: claimName,\n\t\tResourceHandle: resourceHandle,\n\t}\n\n\tctx, cancel := context.WithTimeout(ctx, PluginClientTimeout)\n\tdefer cancel()\n\n\treturn nodeClient.NodeUnprepareResource(ctx, req)\n}","line":{"from":143,"to":178}} {"id":100006001,"name":"newGrpcConn","signature":"func newGrpcConn(addr draAddr) (*grpc.ClientConn, error)","file":"pkg/kubelet/cm/dra/plugin/client.go","code":"func newGrpcConn(addr draAddr) (*grpc.ClientConn, error) {\n\tnetwork := \"unix\"\n\tklog.V(4).InfoS(log(\"creating new gRPC connection\"), \"protocol\", network, \"endpoint\", addr)\n\n\treturn grpc.Dial(\n\t\tstring(addr),\n\t\tgrpc.WithTransportCredentials(insecure.NewCredentials()),\n\t\tgrpc.WithContextDialer(func(ctx context.Context, target string) (net.Conn, error) {\n\t\t\treturn (\u0026net.Dialer{}).DialContext(ctx, network, target)\n\t\t}),\n\t)\n}","line":{"from":180,"to":191}} {"id":100006002,"name":"NewRegistrationHandler","signature":"func NewRegistrationHandler() *RegistrationHandler","file":"pkg/kubelet/cm/dra/plugin/plugin.go","code":"// NewPluginHandler returns new registration handler.\nfunc NewRegistrationHandler() *RegistrationHandler {\n\treturn \u0026RegistrationHandler{}\n}","line":{"from":40,"to":43}} {"id":100006003,"name":"RegisterPlugin","signature":"func (h *RegistrationHandler) RegisterPlugin(pluginName string, endpoint string, versions []string) error","file":"pkg/kubelet/cm/dra/plugin/plugin.go","code":"// RegisterPlugin is called when a plugin can be registered.\nfunc (h *RegistrationHandler) RegisterPlugin(pluginName string, endpoint string, versions []string) error {\n\tklog.InfoS(\"Register new DRA plugin\", \"name\", pluginName, \"endpoint\", endpoint)\n\n\thighestSupportedVersion, err := h.validateVersions(\"RegisterPlugin\", pluginName, versions)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Storing endpoint of newly registered DRA Plugin into the map, where plugin name will be the key\n\t// all other DRA components will be able to get the actual socket of DRA plugins by its name.\n\tdraPlugins.Set(pluginName, \u0026Plugin{\n\t\tendpoint: endpoint,\n\t\thighestSupportedVersion: highestSupportedVersion,\n\t})\n\n\treturn nil\n}","line":{"from":45,"to":62}} {"id":100006004,"name":"highestSupportedVersion","signature":"func highestSupportedVersion(versions []string) (*utilversion.Version, error)","file":"pkg/kubelet/cm/dra/plugin/plugin.go","code":"// Return the highest supported version.\nfunc highestSupportedVersion(versions []string) (*utilversion.Version, error) {\n\tif len(versions) == 0 {\n\t\treturn nil, errors.New(log(\"DRA plugin reporting empty array for supported versions\"))\n\t}\n\n\tvar highestSupportedVersion *utilversion.Version\n\n\tvar theErr error\n\n\tfor i := len(versions) - 1; i \u003e= 0; i-- {\n\t\tcurrentHighestVer, err := utilversion.ParseGeneric(versions[i])\n\t\tif err != nil {\n\t\t\ttheErr = err\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif currentHighestVer.Major() \u003e 1 {\n\t\t\t// DRA currently only has version 1.x\n\t\t\tcontinue\n\t\t}\n\n\t\tif highestSupportedVersion == nil || highestSupportedVersion.LessThan(currentHighestVer) {\n\t\t\thighestSupportedVersion = currentHighestVer\n\t\t}\n\t}\n\n\tif highestSupportedVersion == nil {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"could not find a highest supported version from versions (%v) reported by this plugin: %+v\",\n\t\t\tversions, theErr)\n\t}\n\n\tif highestSupportedVersion.Major() != 1 {\n\t\treturn nil, fmt.Errorf(\"highest supported version reported by plugin is %v, must be v1.x\", highestSupportedVersion)\n\t}\n\n\treturn highestSupportedVersion, nil\n}","line":{"from":64,"to":103}} {"id":100006005,"name":"validateVersions","signature":"func (h *RegistrationHandler) validateVersions(","file":"pkg/kubelet/cm/dra/plugin/plugin.go","code":"func (h *RegistrationHandler) validateVersions(\n\tcallerName string,\n\tpluginName string,\n\tversions []string,\n) (*utilversion.Version, error) {\n\tif len(versions) == 0 {\n\t\treturn nil, errors.New(\n\t\t\tlog(\n\t\t\t\t\"%s for DRA plugin %q failed. Plugin returned an empty list for supported versions\",\n\t\t\t\tcallerName,\n\t\t\t\tpluginName,\n\t\t\t),\n\t\t)\n\t}\n\n\t// Validate version\n\tnewPluginHighestVersion, err := highestSupportedVersion(versions)\n\tif err != nil {\n\t\treturn nil, errors.New(\n\t\t\tlog(\n\t\t\t\t\"%s for DRA plugin %q failed. None of the versions specified %q are supported. err=%v\",\n\t\t\t\tcallerName,\n\t\t\t\tpluginName,\n\t\t\t\tversions,\n\t\t\t\terr,\n\t\t\t),\n\t\t)\n\t}\n\n\texistingPlugin := draPlugins.Get(pluginName)\n\tif existingPlugin != nil {\n\t\tif !existingPlugin.highestSupportedVersion.LessThan(newPluginHighestVersion) {\n\t\t\treturn nil, errors.New(\n\t\t\t\tlog(\n\t\t\t\t\t\"%s for DRA plugin %q failed. Another plugin with the same name is already registered with a higher supported version: %q\",\n\t\t\t\t\tcallerName,\n\t\t\t\t\tpluginName,\n\t\t\t\t\texistingPlugin.highestSupportedVersion,\n\t\t\t\t),\n\t\t\t)\n\t\t}\n\t}\n\n\treturn newPluginHighestVersion, nil\n}","line":{"from":105,"to":149}} {"id":100006006,"name":"unregisterPlugin","signature":"func unregisterPlugin(pluginName string)","file":"pkg/kubelet/cm/dra/plugin/plugin.go","code":"func unregisterPlugin(pluginName string) {\n\tdraPlugins.Delete(pluginName)\n}","line":{"from":151,"to":153}} {"id":100006007,"name":"DeRegisterPlugin","signature":"func (h *RegistrationHandler) DeRegisterPlugin(pluginName string)","file":"pkg/kubelet/cm/dra/plugin/plugin.go","code":"// DeRegisterPlugin is called when a plugin has removed its socket,\n// signaling it is no longer available.\nfunc (h *RegistrationHandler) DeRegisterPlugin(pluginName string) {\n\tklog.InfoS(\"DeRegister DRA plugin\", \"name\", pluginName)\n\tunregisterPlugin(pluginName)\n}","line":{"from":155,"to":160}} {"id":100006008,"name":"ValidatePlugin","signature":"func (h *RegistrationHandler) ValidatePlugin(pluginName string, endpoint string, versions []string) error","file":"pkg/kubelet/cm/dra/plugin/plugin.go","code":"// ValidatePlugin is called by kubelet's plugin watcher upon detection\n// of a new registration socket opened by DRA plugin.\nfunc (h *RegistrationHandler) ValidatePlugin(pluginName string, endpoint string, versions []string) error {\n\tklog.InfoS(\"Validate DRA plugin\", \"name\", pluginName, \"endpoint\", endpoint, \"versions\", strings.Join(versions, \",\"))\n\n\t_, err := h.validateVersions(\"ValidatePlugin\", pluginName, versions)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"validation failed for DRA plugin %s at endpoint %s: %+v\", pluginName, endpoint, err)\n\t}\n\n\treturn err\n}","line":{"from":162,"to":173}} {"id":100006009,"name":"log","signature":"func log(msg string, parts ...interface{}) string","file":"pkg/kubelet/cm/dra/plugin/plugin.go","code":"// log prepends log string with `kubernetes.io/dra`.\nfunc log(msg string, parts ...interface{}) string {\n\treturn fmt.Sprintf(fmt.Sprintf(\"%s: %s\", DRAPluginName, msg), parts...)\n}","line":{"from":175,"to":178}} {"id":100006010,"name":"Get","signature":"func (s *PluginsStore) Get(pluginName string) *Plugin","file":"pkg/kubelet/cm/dra/plugin/plugins_store.go","code":"// Get lets you retrieve a DRA Plugin by name.\n// This method is protected by a mutex.\nfunc (s *PluginsStore) Get(pluginName string) *Plugin {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\treturn s.store[pluginName]\n}","line":{"from":38,"to":45}} {"id":100006011,"name":"Set","signature":"func (s *PluginsStore) Set(pluginName string, plugin *Plugin)","file":"pkg/kubelet/cm/dra/plugin/plugins_store.go","code":"// Set lets you save a DRA Plugin to the list and give it a specific name.\n// This method is protected by a mutex.\nfunc (s *PluginsStore) Set(pluginName string, plugin *Plugin) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tif s.store == nil {\n\t\ts.store = make(map[string]*Plugin)\n\t}\n\n\ts.store[pluginName] = plugin\n}","line":{"from":47,"to":58}} {"id":100006012,"name":"Delete","signature":"func (s *PluginsStore) Delete(pluginName string)","file":"pkg/kubelet/cm/dra/plugin/plugins_store.go","code":"// Delete lets you delete a DRA Plugin by name.\n// This method is protected by a mutex.\nfunc (s *PluginsStore) Delete(pluginName string) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tdelete(s.store, pluginName)\n}","line":{"from":60,"to":67}} {"id":100006013,"name":"Clear","signature":"func (s *PluginsStore) Clear()","file":"pkg/kubelet/cm/dra/plugin/plugins_store.go","code":"// Clear deletes all entries in the store.\n// This methiod is protected by a mutex.\nfunc (s *PluginsStore) Clear() {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\ts.store = make(map[string]*Plugin)\n}","line":{"from":69,"to":76}} {"id":100006014,"name":"NewDRAManagerCheckpoint","signature":"func NewDRAManagerCheckpoint() *DRAManagerCheckpoint","file":"pkg/kubelet/cm/dra/state/checkpoint.go","code":"// NewDRAManagerCheckpoint returns an instance of Checkpoint\nfunc NewDRAManagerCheckpoint() *DRAManagerCheckpoint {\n\treturn \u0026DRAManagerCheckpoint{\n\t\tVersion: checkpointVersion,\n\t\tEntries: ClaimInfoStateList{},\n\t}\n}","line":{"from":40,"to":46}} {"id":100006015,"name":"MarshalCheckpoint","signature":"func (dc *DRAManagerCheckpoint) MarshalCheckpoint() ([]byte, error)","file":"pkg/kubelet/cm/dra/state/checkpoint.go","code":"// MarshalCheckpoint returns marshalled checkpoint\nfunc (dc *DRAManagerCheckpoint) MarshalCheckpoint() ([]byte, error) {\n\t// make sure checksum wasn't set before so it doesn't affect output checksum\n\tdc.Checksum = 0\n\tdc.Checksum = checksum.New(dc)\n\treturn json.Marshal(*dc)\n}","line":{"from":48,"to":54}} {"id":100006016,"name":"UnmarshalCheckpoint","signature":"func (dc *DRAManagerCheckpoint) UnmarshalCheckpoint(blob []byte) error","file":"pkg/kubelet/cm/dra/state/checkpoint.go","code":"// UnmarshalCheckpoint tries to unmarshal passed bytes to checkpoint\nfunc (dc *DRAManagerCheckpoint) UnmarshalCheckpoint(blob []byte) error {\n\treturn json.Unmarshal(blob, dc)\n}","line":{"from":56,"to":59}} {"id":100006017,"name":"VerifyChecksum","signature":"func (dc *DRAManagerCheckpoint) VerifyChecksum() error","file":"pkg/kubelet/cm/dra/state/checkpoint.go","code":"// VerifyChecksum verifies that current checksum of checkpoint is valid\nfunc (dc *DRAManagerCheckpoint) VerifyChecksum() error {\n\tck := dc.Checksum\n\tdc.Checksum = 0\n\terr := ck.Verify(dc)\n\tdc.Checksum = ck\n\treturn err\n}","line":{"from":61,"to":68}} {"id":100006018,"name":"NewCheckpointState","signature":"func NewCheckpointState(stateDir, checkpointName string) (*stateCheckpoint, error)","file":"pkg/kubelet/cm/dra/state/state_checkpoint.go","code":"// NewCheckpointState creates new State for keeping track of claim info with checkpoint backend\nfunc NewCheckpointState(stateDir, checkpointName string) (*stateCheckpoint, error) {\n\tcheckpointManager, err := checkpointmanager.NewCheckpointManager(stateDir)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize checkpoint manager: %v\", err)\n\t}\n\tstateCheckpoint := \u0026stateCheckpoint{\n\t\tcheckpointManager: checkpointManager,\n\t\tcheckpointName: checkpointName,\n\t}\n\n\treturn stateCheckpoint, nil\n}","line":{"from":68,"to":80}} {"id":100006019,"name":"GetOrCreate","signature":"func (sc *stateCheckpoint) GetOrCreate() (ClaimInfoStateList, error)","file":"pkg/kubelet/cm/dra/state/state_checkpoint.go","code":"// get state from a checkpoint and creates it if it doesn't exist\nfunc (sc *stateCheckpoint) GetOrCreate() (ClaimInfoStateList, error) {\n\tsc.Lock()\n\tdefer sc.Unlock()\n\n\tcheckpoint := NewDRAManagerCheckpoint()\n\terr := sc.checkpointManager.GetCheckpoint(sc.checkpointName, checkpoint)\n\tif err == errors.ErrCheckpointNotFound {\n\t\tsc.store(ClaimInfoStateList{})\n\t\treturn ClaimInfoStateList{}, nil\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get checkpoint %v: %v\", sc.checkpointName, err)\n\t}\n\n\treturn checkpoint.Entries, nil\n}","line":{"from":82,"to":98}} {"id":100006020,"name":"Store","signature":"func (sc *stateCheckpoint) Store(claimInfoStateList ClaimInfoStateList) error","file":"pkg/kubelet/cm/dra/state/state_checkpoint.go","code":"// saves state to a checkpoint\nfunc (sc *stateCheckpoint) Store(claimInfoStateList ClaimInfoStateList) error {\n\tsc.Lock()\n\tdefer sc.Unlock()\n\n\treturn sc.store(claimInfoStateList)\n}","line":{"from":100,"to":106}} {"id":100006021,"name":"store","signature":"func (sc *stateCheckpoint) store(claimInfoStateList ClaimInfoStateList) error","file":"pkg/kubelet/cm/dra/state/state_checkpoint.go","code":"// saves state to a checkpoint, caller is responsible for locking\nfunc (sc *stateCheckpoint) store(claimInfoStateList ClaimInfoStateList) error {\n\tcheckpoint := NewDRAManagerCheckpoint()\n\tcheckpoint.Entries = claimInfoStateList\n\n\terr := sc.checkpointManager.CreateCheckpoint(sc.checkpointName, checkpoint)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not save checkpoint %s: %v\", sc.checkpointName, err)\n\t}\n\treturn nil\n}","line":{"from":108,"to":118}} {"id":100006022,"name":"hardEvictionReservation","signature":"func hardEvictionReservation(thresholds []evictionapi.Threshold, capacity v1.ResourceList) v1.ResourceList","file":"pkg/kubelet/cm/helpers.go","code":"// hardEvictionReservation returns a resourcelist that includes reservation of resources based on hard eviction thresholds.\nfunc hardEvictionReservation(thresholds []evictionapi.Threshold, capacity v1.ResourceList) v1.ResourceList {\n\tif len(thresholds) == 0 {\n\t\treturn nil\n\t}\n\tret := v1.ResourceList{}\n\tfor _, threshold := range thresholds {\n\t\tif threshold.Operator != evictionapi.OpLessThan {\n\t\t\tcontinue\n\t\t}\n\t\tswitch threshold.Signal {\n\t\tcase evictionapi.SignalMemoryAvailable:\n\t\t\tmemoryCapacity := capacity[v1.ResourceMemory]\n\t\t\tvalue := evictionapi.GetThresholdQuantity(threshold.Value, \u0026memoryCapacity)\n\t\t\tret[v1.ResourceMemory] = *value\n\t\tcase evictionapi.SignalNodeFsAvailable:\n\t\t\tstorageCapacity := capacity[v1.ResourceEphemeralStorage]\n\t\t\tvalue := evictionapi.GetThresholdQuantity(threshold.Value, \u0026storageCapacity)\n\t\t\tret[v1.ResourceEphemeralStorage] = *value\n\t\t}\n\t}\n\treturn ret\n}","line":{"from":24,"to":46}} {"id":100006023,"name":"MilliCPUToQuota","signature":"func MilliCPUToQuota(milliCPU int64, period int64) (quota int64)","file":"pkg/kubelet/cm/helpers_linux.go","code":"// MilliCPUToQuota converts milliCPU to CFS quota and period values.\n// Input parameters and resulting value is number of microseconds.\nfunc MilliCPUToQuota(milliCPU int64, period int64) (quota int64) {\n\t// CFS quota is measured in two values:\n\t// - cfs_period_us=100ms (the amount of time to measure usage across given by period)\n\t// - cfs_quota=20ms (the amount of cpu time allowed to be used across a period)\n\t// so in the above example, you are limited to 20% of a single CPU\n\t// for multi-cpu environments, you just scale equivalent amounts\n\t// see https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt for details\n\n\tif milliCPU == 0 {\n\t\treturn\n\t}\n\n\tif !utilfeature.DefaultFeatureGate.Enabled(kubefeatures.CPUCFSQuotaPeriod) {\n\t\tperiod = QuotaPeriod\n\t}\n\n\t// we then convert your milliCPU to a value normalized over a period\n\tquota = (milliCPU * period) / MilliCPUToCPU\n\n\t// quota needs to be a minimum of 1ms.\n\tif quota \u003c MinQuotaPeriod {\n\t\tquota = MinQuotaPeriod\n\t}\n\treturn\n}","line":{"from":56,"to":82}} {"id":100006024,"name":"MilliCPUToShares","signature":"func MilliCPUToShares(milliCPU int64) uint64","file":"pkg/kubelet/cm/helpers_linux.go","code":"// MilliCPUToShares converts the milliCPU to CFS shares.\nfunc MilliCPUToShares(milliCPU int64) uint64 {\n\tif milliCPU == 0 {\n\t\t// Docker converts zero milliCPU to unset, which maps to kernel default\n\t\t// for unset: 1024. Return 2 here to really match kernel default for\n\t\t// zero milliCPU.\n\t\treturn MinShares\n\t}\n\t// Conceptually (milliCPU / milliCPUToCPU) * sharesPerCPU, but factored to improve rounding.\n\tshares := (milliCPU * SharesPerCPU) / MilliCPUToCPU\n\tif shares \u003c MinShares {\n\t\treturn MinShares\n\t}\n\tif shares \u003e MaxShares {\n\t\treturn MaxShares\n\t}\n\treturn uint64(shares)\n}","line":{"from":84,"to":101}} {"id":100006025,"name":"HugePageLimits","signature":"func HugePageLimits(resourceList v1.ResourceList) map[int64]int64","file":"pkg/kubelet/cm/helpers_linux.go","code":"// HugePageLimits converts the API representation to a map\n// from huge page size (in bytes) to huge page limit (in bytes).\nfunc HugePageLimits(resourceList v1.ResourceList) map[int64]int64 {\n\thugePageLimits := map[int64]int64{}\n\tfor k, v := range resourceList {\n\t\tif v1helper.IsHugePageResourceName(k) {\n\t\t\tpageSize, _ := v1helper.HugePageSizeFromResourceName(k)\n\t\t\tif value, exists := hugePageLimits[pageSize.Value()]; exists {\n\t\t\t\thugePageLimits[pageSize.Value()] = value + v.Value()\n\t\t\t} else {\n\t\t\t\thugePageLimits[pageSize.Value()] = v.Value()\n\t\t\t}\n\t\t}\n\t}\n\treturn hugePageLimits\n}","line":{"from":103,"to":118}} {"id":100006026,"name":"ResourceConfigForPod","signature":"func ResourceConfigForPod(pod *v1.Pod, enforceCPULimits bool, cpuPeriod uint64, enforceMemoryQoS bool) *ResourceConfig","file":"pkg/kubelet/cm/helpers_linux.go","code":"// ResourceConfigForPod takes the input pod and outputs the cgroup resource config.\nfunc ResourceConfigForPod(pod *v1.Pod, enforceCPULimits bool, cpuPeriod uint64, enforceMemoryQoS bool) *ResourceConfig {\n\tinPlacePodVerticalScalingEnabled := utilfeature.DefaultFeatureGate.Enabled(kubefeatures.InPlacePodVerticalScaling)\n\t// sum requests and limits.\n\treqs := resource.PodRequests(pod, resource.PodResourcesOptions{\n\t\tInPlacePodVerticalScalingEnabled: inPlacePodVerticalScalingEnabled,\n\t})\n\t// track if limits were applied for each resource.\n\tmemoryLimitsDeclared := true\n\tcpuLimitsDeclared := true\n\n\tlimits := resource.PodLimits(pod, resource.PodResourcesOptions{\n\t\tInPlacePodVerticalScalingEnabled: inPlacePodVerticalScalingEnabled,\n\t\tContainerFn: func(res v1.ResourceList, containerType podutil.ContainerType) {\n\t\t\tif res.Cpu().IsZero() {\n\t\t\t\tcpuLimitsDeclared = false\n\t\t\t}\n\t\t\tif res.Memory().IsZero() {\n\t\t\t\tmemoryLimitsDeclared = false\n\t\t\t}\n\t\t},\n\t})\n\t// map hugepage pagesize (bytes) to limits (bytes)\n\thugePageLimits := HugePageLimits(reqs)\n\n\tcpuRequests := int64(0)\n\tcpuLimits := int64(0)\n\tmemoryLimits := int64(0)\n\tif request, found := reqs[v1.ResourceCPU]; found {\n\t\tcpuRequests = request.MilliValue()\n\t}\n\tif limit, found := limits[v1.ResourceCPU]; found {\n\t\tcpuLimits = limit.MilliValue()\n\t}\n\tif limit, found := limits[v1.ResourceMemory]; found {\n\t\tmemoryLimits = limit.Value()\n\t}\n\n\t// convert to CFS values\n\tcpuShares := MilliCPUToShares(cpuRequests)\n\tcpuQuota := MilliCPUToQuota(cpuLimits, int64(cpuPeriod))\n\n\t// quota is not capped when cfs quota is disabled\n\tif !enforceCPULimits {\n\t\tcpuQuota = int64(-1)\n\t}\n\n\t// determine the qos class\n\tqosClass := v1qos.GetPodQOS(pod)\n\n\t// build the result\n\tresult := \u0026ResourceConfig{}\n\tif qosClass == v1.PodQOSGuaranteed {\n\t\tresult.CPUShares = \u0026cpuShares\n\t\tresult.CPUQuota = \u0026cpuQuota\n\t\tresult.CPUPeriod = \u0026cpuPeriod\n\t\tresult.Memory = \u0026memoryLimits\n\t} else if qosClass == v1.PodQOSBurstable {\n\t\tresult.CPUShares = \u0026cpuShares\n\t\tif cpuLimitsDeclared {\n\t\t\tresult.CPUQuota = \u0026cpuQuota\n\t\t\tresult.CPUPeriod = \u0026cpuPeriod\n\t\t}\n\t\tif memoryLimitsDeclared {\n\t\t\tresult.Memory = \u0026memoryLimits\n\t\t}\n\t} else {\n\t\tshares := uint64(MinShares)\n\t\tresult.CPUShares = \u0026shares\n\t}\n\tresult.HugePageLimit = hugePageLimits\n\n\tif enforceMemoryQoS {\n\t\tmemoryMin := int64(0)\n\t\tif request, found := reqs[v1.ResourceMemory]; found {\n\t\t\tmemoryMin = request.Value()\n\t\t}\n\t\tif memoryMin \u003e 0 {\n\t\t\tresult.Unified = map[string]string{\n\t\t\t\tMemoryMin: strconv.FormatInt(memoryMin, 10),\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result\n}","line":{"from":120,"to":205}} {"id":100006027,"name":"getCgroupSubsystemsV1","signature":"func getCgroupSubsystemsV1() (*CgroupSubsystems, error)","file":"pkg/kubelet/cm/helpers_linux.go","code":"// getCgroupSubsystemsV1 returns information about the mounted cgroup v1 subsystems\nfunc getCgroupSubsystemsV1() (*CgroupSubsystems, error) {\n\t// get all cgroup mounts.\n\tallCgroups, err := libcontainercgroups.GetCgroupMounts(true)\n\tif err != nil {\n\t\treturn \u0026CgroupSubsystems{}, err\n\t}\n\tif len(allCgroups) == 0 {\n\t\treturn \u0026CgroupSubsystems{}, fmt.Errorf(\"failed to find cgroup mounts\")\n\t}\n\tmountPoints := make(map[string]string, len(allCgroups))\n\tfor _, mount := range allCgroups {\n\t\t// BEFORE kubelet used a random mount point per cgroups subsystem;\n\t\t// NOW more deterministic: kubelet use mount point with shortest path;\n\t\t// FUTURE is bright with clear expectation determined in doc.\n\t\t// ref. issue: https://github.com/kubernetes/kubernetes/issues/95488\n\n\t\tfor _, subsystem := range mount.Subsystems {\n\t\t\tprevious := mountPoints[subsystem]\n\t\t\tif previous == \"\" || len(mount.Mountpoint) \u003c len(previous) {\n\t\t\t\tmountPoints[subsystem] = mount.Mountpoint\n\t\t\t}\n\t\t}\n\t}\n\treturn \u0026CgroupSubsystems{\n\t\tMounts: allCgroups,\n\t\tMountPoints: mountPoints,\n\t}, nil\n}","line":{"from":207,"to":235}} {"id":100006028,"name":"getCgroupSubsystemsV2","signature":"func getCgroupSubsystemsV2() (*CgroupSubsystems, error)","file":"pkg/kubelet/cm/helpers_linux.go","code":"// getCgroupSubsystemsV2 returns information about the enabled cgroup v2 subsystems\nfunc getCgroupSubsystemsV2() (*CgroupSubsystems, error) {\n\tcontrollers, err := libcontainercgroups.GetAllSubsystems()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmounts := []libcontainercgroups.Mount{}\n\tmountPoints := make(map[string]string, len(controllers))\n\tfor _, controller := range controllers {\n\t\tmountPoints[controller] = util.CgroupRoot\n\t\tm := libcontainercgroups.Mount{\n\t\t\tMountpoint: util.CgroupRoot,\n\t\t\tRoot: util.CgroupRoot,\n\t\t\tSubsystems: []string{controller},\n\t\t}\n\t\tmounts = append(mounts, m)\n\t}\n\n\treturn \u0026CgroupSubsystems{\n\t\tMounts: mounts,\n\t\tMountPoints: mountPoints,\n\t}, nil\n}","line":{"from":237,"to":260}} {"id":100006029,"name":"GetCgroupSubsystems","signature":"func GetCgroupSubsystems() (*CgroupSubsystems, error)","file":"pkg/kubelet/cm/helpers_linux.go","code":"// GetCgroupSubsystems returns information about the mounted cgroup subsystems\nfunc GetCgroupSubsystems() (*CgroupSubsystems, error) {\n\tif libcontainercgroups.IsCgroup2UnifiedMode() {\n\t\treturn getCgroupSubsystemsV2()\n\t}\n\n\treturn getCgroupSubsystemsV1()\n}","line":{"from":262,"to":269}} {"id":100006030,"name":"getCgroupProcs","signature":"func getCgroupProcs(dir string) ([]int, error)","file":"pkg/kubelet/cm/helpers_linux.go","code":"// getCgroupProcs takes a cgroup directory name as an argument\n// reads through the cgroup's procs file and returns a list of tgid's.\n// It returns an empty list if a procs file doesn't exists\nfunc getCgroupProcs(dir string) ([]int, error) {\n\tprocsFile := filepath.Join(dir, \"cgroup.procs\")\n\tf, err := os.Open(procsFile)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\t// The procsFile does not exist, So no pids attached to this directory\n\t\t\treturn []int{}, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\ts := bufio.NewScanner(f)\n\tout := []int{}\n\tfor s.Scan() {\n\t\tif t := s.Text(); t != \"\" {\n\t\t\tpid, err := strconv.Atoi(t)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected line in %v; could not convert to pid: %v\", procsFile, err)\n\t\t\t}\n\t\t\tout = append(out, pid)\n\t\t}\n\t}\n\treturn out, nil\n}","line":{"from":271,"to":298}} {"id":100006031,"name":"GetPodCgroupNameSuffix","signature":"func GetPodCgroupNameSuffix(podUID types.UID) string","file":"pkg/kubelet/cm/helpers_linux.go","code":"// GetPodCgroupNameSuffix returns the last element of the pod CgroupName identifier\nfunc GetPodCgroupNameSuffix(podUID types.UID) string {\n\treturn podCgroupNamePrefix + string(podUID)\n}","line":{"from":300,"to":303}} {"id":100006032,"name":"NodeAllocatableRoot","signature":"func NodeAllocatableRoot(cgroupRoot string, cgroupsPerQOS bool, cgroupDriver string) string","file":"pkg/kubelet/cm/helpers_linux.go","code":"// NodeAllocatableRoot returns the literal cgroup path for the node allocatable cgroup\nfunc NodeAllocatableRoot(cgroupRoot string, cgroupsPerQOS bool, cgroupDriver string) string {\n\tnodeAllocatableRoot := ParseCgroupfsToCgroupName(cgroupRoot)\n\tif cgroupsPerQOS {\n\t\tnodeAllocatableRoot = NewCgroupName(nodeAllocatableRoot, defaultNodeAllocatableCgroupName)\n\t}\n\tif cgroupDriver == \"systemd\" {\n\t\treturn nodeAllocatableRoot.ToSystemd()\n\t}\n\treturn nodeAllocatableRoot.ToCgroupfs()\n}","line":{"from":305,"to":315}} {"id":100006033,"name":"GetKubeletContainer","signature":"func GetKubeletContainer(kubeletCgroups string) (string, error)","file":"pkg/kubelet/cm/helpers_linux.go","code":"// GetKubeletContainer returns the cgroup the kubelet will use\nfunc GetKubeletContainer(kubeletCgroups string) (string, error) {\n\tif kubeletCgroups == \"\" {\n\t\tcont, err := getContainer(os.Getpid())\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn cont, nil\n\t}\n\treturn kubeletCgroups, nil\n}","line":{"from":317,"to":327}} {"id":100006034,"name":"MilliCPUToQuota","signature":"func MilliCPUToQuota(milliCPU, period int64) int64","file":"pkg/kubelet/cm/helpers_unsupported.go","code":"// MilliCPUToQuota converts milliCPU and period to CFS quota values.\nfunc MilliCPUToQuota(milliCPU, period int64) int64 {\n\treturn 0\n}","line":{"from":38,"to":41}} {"id":100006035,"name":"MilliCPUToShares","signature":"func MilliCPUToShares(milliCPU int64) int64","file":"pkg/kubelet/cm/helpers_unsupported.go","code":"// MilliCPUToShares converts the milliCPU to CFS shares.\nfunc MilliCPUToShares(milliCPU int64) int64 {\n\treturn 0\n}","line":{"from":43,"to":46}} {"id":100006036,"name":"ResourceConfigForPod","signature":"func ResourceConfigForPod(pod *v1.Pod, enforceCPULimit bool, cpuPeriod uint64, enforceMemoryQoS bool) *ResourceConfig","file":"pkg/kubelet/cm/helpers_unsupported.go","code":"// ResourceConfigForPod takes the input pod and outputs the cgroup resource config.\nfunc ResourceConfigForPod(pod *v1.Pod, enforceCPULimit bool, cpuPeriod uint64, enforceMemoryQoS bool) *ResourceConfig {\n\treturn nil\n}","line":{"from":48,"to":51}} {"id":100006037,"name":"GetCgroupSubsystems","signature":"func GetCgroupSubsystems() (*CgroupSubsystems, error)","file":"pkg/kubelet/cm/helpers_unsupported.go","code":"// GetCgroupSubsystems returns information about the mounted cgroup subsystems\nfunc GetCgroupSubsystems() (*CgroupSubsystems, error) {\n\treturn nil, nil\n}","line":{"from":53,"to":56}} {"id":100006038,"name":"getCgroupProcs","signature":"func getCgroupProcs(dir string) ([]int, error)","file":"pkg/kubelet/cm/helpers_unsupported.go","code":"func getCgroupProcs(dir string) ([]int, error) {\n\treturn nil, nil\n}","line":{"from":58,"to":60}} {"id":100006039,"name":"GetPodCgroupNameSuffix","signature":"func GetPodCgroupNameSuffix(podUID types.UID) string","file":"pkg/kubelet/cm/helpers_unsupported.go","code":"// GetPodCgroupNameSuffix returns the last element of the pod CgroupName identifier\nfunc GetPodCgroupNameSuffix(podUID types.UID) string {\n\treturn \"\"\n}","line":{"from":62,"to":65}} {"id":100006040,"name":"NodeAllocatableRoot","signature":"func NodeAllocatableRoot(cgroupRoot string, cgroupsPerQOS bool, cgroupDriver string) string","file":"pkg/kubelet/cm/helpers_unsupported.go","code":"// NodeAllocatableRoot returns the literal cgroup path for the node allocatable cgroup\nfunc NodeAllocatableRoot(cgroupRoot string, cgroupsPerQOS bool, cgroupDriver string) string {\n\treturn \"\"\n}","line":{"from":67,"to":70}} {"id":100006041,"name":"GetKubeletContainer","signature":"func GetKubeletContainer(kubeletCgroups string) (string, error)","file":"pkg/kubelet/cm/helpers_unsupported.go","code":"// GetKubeletContainer returns the cgroup the kubelet will use\nfunc GetKubeletContainer(kubeletCgroups string) (string, error) {\n\treturn \"\", nil\n}","line":{"from":72,"to":75}} {"id":100006042,"name":"PreStartContainer","signature":"func (i *internalContainerLifecycleImpl) PreStartContainer(pod *v1.Pod, container *v1.Container, containerID string) error","file":"pkg/kubelet/cm/internal_container_lifecycle.go","code":"func (i *internalContainerLifecycleImpl) PreStartContainer(pod *v1.Pod, container *v1.Container, containerID string) error {\n\tif i.cpuManager != nil {\n\t\ti.cpuManager.AddContainer(pod, container, containerID)\n\t}\n\n\tif i.memoryManager != nil {\n\t\ti.memoryManager.AddContainer(pod, container, containerID)\n\t}\n\n\ti.topologyManager.AddContainer(pod, container, containerID)\n\n\treturn nil\n}","line":{"from":40,"to":52}} {"id":100006043,"name":"PostStopContainer","signature":"func (i *internalContainerLifecycleImpl) PostStopContainer(containerID string) error","file":"pkg/kubelet/cm/internal_container_lifecycle.go","code":"func (i *internalContainerLifecycleImpl) PostStopContainer(containerID string) error {\n\treturn i.topologyManager.RemoveContainer(containerID)\n}","line":{"from":54,"to":56}} {"id":100006044,"name":"PreCreateContainer","signature":"func (i *internalContainerLifecycleImpl) PreCreateContainer(pod *v1.Pod, container *v1.Container, containerConfig *runtimeapi.ContainerConfig) error","file":"pkg/kubelet/cm/internal_container_lifecycle_linux.go","code":"func (i *internalContainerLifecycleImpl) PreCreateContainer(pod *v1.Pod, container *v1.Container, containerConfig *runtimeapi.ContainerConfig) error {\n\tif i.cpuManager != nil {\n\t\tallocatedCPUs := i.cpuManager.GetCPUAffinity(string(pod.UID), container.Name)\n\t\tif !allocatedCPUs.IsEmpty() {\n\t\t\tcontainerConfig.Linux.Resources.CpusetCpus = allocatedCPUs.String()\n\t\t}\n\t}\n\n\tif i.memoryManager != nil {\n\t\tnumaNodes := i.memoryManager.GetMemoryNUMANodes(pod, container)\n\t\tif numaNodes.Len() \u003e 0 {\n\t\t\tvar affinity []string\n\t\t\tfor _, numaNode := range numaNodes.List() {\n\t\t\t\taffinity = append(affinity, strconv.Itoa(numaNode))\n\t\t\t}\n\t\t\tcontainerConfig.Linux.Resources.CpusetMems = strings.Join(affinity, \",\")\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":30,"to":50}} {"id":100006045,"name":"PreCreateContainer","signature":"func (i *internalContainerLifecycleImpl) PreCreateContainer(pod *v1.Pod, container *v1.Container, containerConfig *runtimeapi.ContainerConfig) error","file":"pkg/kubelet/cm/internal_container_lifecycle_unsupported.go","code":"func (i *internalContainerLifecycleImpl) PreCreateContainer(pod *v1.Pod, container *v1.Container, containerConfig *runtimeapi.ContainerConfig) error {\n\treturn nil\n}","line":{"from":27,"to":29}} {"id":100006046,"name":"PreCreateContainer","signature":"func (i *internalContainerLifecycleImpl) PreCreateContainer(pod *v1.Pod, container *v1.Container, containerConfig *runtimeapi.ContainerConfig) error","file":"pkg/kubelet/cm/internal_container_lifecycle_windows.go","code":"func (i *internalContainerLifecycleImpl) PreCreateContainer(pod *v1.Pod, container *v1.Container, containerConfig *runtimeapi.ContainerConfig) error {\n\treturn nil\n}","line":{"from":27,"to":29}} {"id":100006047,"name":"AddSource","signature":"func (s *sourcesReadyStub) AddSource(source string) {}","file":"pkg/kubelet/cm/memorymanager/memory_manager.go","code":"func (s *sourcesReadyStub) AddSource(source string) {}","line":{"from":52,"to":52}} {"id":100006048,"name":"AllReady","signature":"func (s *sourcesReadyStub) AllReady() bool { return true }","file":"pkg/kubelet/cm/memorymanager/memory_manager.go","code":"func (s *sourcesReadyStub) AllReady() bool { return true }","line":{"from":53,"to":53}} {"id":100006049,"name":"NewManager","signature":"func NewManager(policyName string, machineInfo *cadvisorapi.MachineInfo, nodeAllocatableReservation v1.ResourceList, reservedMemory []kubeletconfig.MemoryReservation, stateFileDirectory string, affinity topologymanager.Store) (Manager, error)","file":"pkg/kubelet/cm/memorymanager/memory_manager.go","code":"// NewManager returns new instance of the memory manager\nfunc NewManager(policyName string, machineInfo *cadvisorapi.MachineInfo, nodeAllocatableReservation v1.ResourceList, reservedMemory []kubeletconfig.MemoryReservation, stateFileDirectory string, affinity topologymanager.Store) (Manager, error) {\n\tvar policy Policy\n\n\tswitch policyType(policyName) {\n\n\tcase policyTypeNone:\n\t\tpolicy = NewPolicyNone()\n\n\tcase policyTypeStatic:\n\t\tsystemReserved, err := getSystemReservedMemory(machineInfo, nodeAllocatableReservation, reservedMemory)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tpolicy, err = NewPolicyStatic(machineInfo, systemReserved, affinity)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown policy: \\\"%s\\\"\", policyName)\n\t}\n\n\tmanager := \u0026manager{\n\t\tpolicy: policy,\n\t\tstateFileDirectory: stateFileDirectory,\n\t}\n\tmanager.sourcesReady = \u0026sourcesReadyStub{}\n\treturn manager, nil\n}","line":{"from":135,"to":165}} {"id":100006050,"name":"Start","signature":"func (m *manager) Start(activePods ActivePodsFunc, sourcesReady config.SourcesReady, podStatusProvider status.PodStatusProvider, containerRuntime runtimeService, initialContainers containermap.ContainerMap) error","file":"pkg/kubelet/cm/memorymanager/memory_manager.go","code":"// Start starts the memory manager under the kubelet and calls policy start\nfunc (m *manager) Start(activePods ActivePodsFunc, sourcesReady config.SourcesReady, podStatusProvider status.PodStatusProvider, containerRuntime runtimeService, initialContainers containermap.ContainerMap) error {\n\tklog.InfoS(\"Starting memorymanager\", \"policy\", m.policy.Name())\n\tm.sourcesReady = sourcesReady\n\tm.activePods = activePods\n\tm.podStatusProvider = podStatusProvider\n\tm.containerRuntime = containerRuntime\n\tm.containerMap = initialContainers\n\n\tstateImpl, err := state.NewCheckpointState(m.stateFileDirectory, memoryManagerStateFileName, m.policy.Name())\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Could not initialize checkpoint manager, please drain node and remove policy state file\")\n\t\treturn err\n\t}\n\tm.state = stateImpl\n\n\terr = m.policy.Start(m.state)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Policy start error\")\n\t\treturn err\n\t}\n\n\tm.allocatableMemory = m.policy.GetAllocatableMemory(m.state)\n\n\treturn nil\n}","line":{"from":167,"to":192}} {"id":100006051,"name":"AddContainer","signature":"func (m *manager) AddContainer(pod *v1.Pod, container *v1.Container, containerID string)","file":"pkg/kubelet/cm/memorymanager/memory_manager.go","code":"// AddContainer saves the value of requested memory for the guaranteed pod under the state and set memory affinity according to the topolgy manager\nfunc (m *manager) AddContainer(pod *v1.Pod, container *v1.Container, containerID string) {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tm.containerMap.Add(string(pod.UID), container.Name, containerID)\n\n\t// Since we know that each init container always runs to completion before\n\t// the next container starts, we can safely remove references to any previously\n\t// started init containers. This will free up the memory from these init containers\n\t// for use in other pods. If the current container happens to be an init container,\n\t// we skip deletion of it until the next container is added, and this is called again.\n\tfor _, initContainer := range pod.Spec.InitContainers {\n\t\tif initContainer.Name == container.Name {\n\t\t\tbreak\n\t\t}\n\n\t\tm.policyRemoveContainerByRef(string(pod.UID), initContainer.Name)\n\t}\n}","line":{"from":194,"to":213}} {"id":100006052,"name":"GetMemoryNUMANodes","signature":"func (m *manager) GetMemoryNUMANodes(pod *v1.Pod, container *v1.Container) sets.Int","file":"pkg/kubelet/cm/memorymanager/memory_manager.go","code":"// GetMemoryNUMANodes provides NUMA nodes that used to allocate the container memory\nfunc (m *manager) GetMemoryNUMANodes(pod *v1.Pod, container *v1.Container) sets.Int {\n\t// Get NUMA node affinity of blocks assigned to the container during Allocate()\n\tnumaNodes := sets.NewInt()\n\tfor _, block := range m.state.GetMemoryBlocks(string(pod.UID), container.Name) {\n\t\tfor _, nodeID := range block.NUMAAffinity {\n\t\t\t// avoid nodes duplication when hugepages and memory blocks pinned to the same NUMA node\n\t\t\tnumaNodes.Insert(nodeID)\n\t\t}\n\t}\n\n\tif numaNodes.Len() == 0 {\n\t\tklog.V(5).InfoS(\"No allocation is available\", \"pod\", klog.KObj(pod), \"containerName\", container.Name)\n\t\treturn nil\n\t}\n\n\tklog.InfoS(\"Memory affinity\", \"pod\", klog.KObj(pod), \"containerName\", container.Name, \"numaNodes\", numaNodes)\n\treturn numaNodes\n}","line":{"from":215,"to":233}} {"id":100006053,"name":"Allocate","signature":"func (m *manager) Allocate(pod *v1.Pod, container *v1.Container) error","file":"pkg/kubelet/cm/memorymanager/memory_manager.go","code":"// Allocate is called to pre-allocate memory resources during Pod admission.\nfunc (m *manager) Allocate(pod *v1.Pod, container *v1.Container) error {\n\t// The pod is during the admission phase. We need to save the pod to avoid it\n\t// being cleaned before the admission ended\n\tm.setPodPendingAdmission(pod)\n\n\t// Garbage collect any stranded resources before allocation\n\tm.removeStaleState()\n\n\tm.Lock()\n\tdefer m.Unlock()\n\n\t// Call down into the policy to assign this container memory if required.\n\tif err := m.policy.Allocate(m.state, pod, container); err != nil {\n\t\tklog.ErrorS(err, \"Allocate error\")\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":235,"to":253}} {"id":100006054,"name":"RemoveContainer","signature":"func (m *manager) RemoveContainer(containerID string) error","file":"pkg/kubelet/cm/memorymanager/memory_manager.go","code":"// RemoveContainer removes the container from the state\nfunc (m *manager) RemoveContainer(containerID string) error {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\t// if error appears it means container entry already does not exist under the container map\n\tpodUID, containerName, err := m.containerMap.GetContainerRef(containerID)\n\tif err != nil {\n\t\tklog.InfoS(\"Failed to get container from container map\", \"containerID\", containerID, \"err\", err)\n\t\treturn nil\n\t}\n\n\tm.policyRemoveContainerByRef(podUID, containerName)\n\n\treturn nil\n}","line":{"from":255,"to":270}} {"id":100006055,"name":"State","signature":"func (m *manager) State() state.Reader","file":"pkg/kubelet/cm/memorymanager/memory_manager.go","code":"// State returns the state of the manager\nfunc (m *manager) State() state.Reader {\n\treturn m.state\n}","line":{"from":272,"to":275}} {"id":100006056,"name":"GetPodTopologyHints","signature":"func (m *manager) GetPodTopologyHints(pod *v1.Pod) map[string][]topologymanager.TopologyHint","file":"pkg/kubelet/cm/memorymanager/memory_manager.go","code":"// GetPodTopologyHints returns the topology hints for the topology manager\nfunc (m *manager) GetPodTopologyHints(pod *v1.Pod) map[string][]topologymanager.TopologyHint {\n\t// The pod is during the admission phase. We need to save the pod to avoid it\n\t// being cleaned before the admission ended\n\tm.setPodPendingAdmission(pod)\n\n\t// Garbage collect any stranded resources before providing TopologyHints\n\tm.removeStaleState()\n\t// Delegate to active policy\n\treturn m.policy.GetPodTopologyHints(m.state, pod)\n}","line":{"from":277,"to":287}} {"id":100006057,"name":"GetTopologyHints","signature":"func (m *manager) GetTopologyHints(pod *v1.Pod, container *v1.Container) map[string][]topologymanager.TopologyHint","file":"pkg/kubelet/cm/memorymanager/memory_manager.go","code":"// GetTopologyHints returns the topology hints for the topology manager\nfunc (m *manager) GetTopologyHints(pod *v1.Pod, container *v1.Container) map[string][]topologymanager.TopologyHint {\n\t// The pod is during the admission phase. We need to save the pod to avoid it\n\t// being cleaned before the admission ended\n\tm.setPodPendingAdmission(pod)\n\n\t// Garbage collect any stranded resources before providing TopologyHints\n\tm.removeStaleState()\n\t// Delegate to active policy\n\treturn m.policy.GetTopologyHints(m.state, pod, container)\n}","line":{"from":289,"to":299}} {"id":100006058,"name":"removeStaleState","signature":"func (m *manager) removeStaleState()","file":"pkg/kubelet/cm/memorymanager/memory_manager.go","code":"// TODO: move the method to the upper level, to re-use it under the CPU and memory managers\nfunc (m *manager) removeStaleState() {\n\t// Only once all sources are ready do we attempt to remove any stale state.\n\t// This ensures that the call to `m.activePods()` below will succeed with\n\t// the actual active pods list.\n\tif !m.sourcesReady.AllReady() {\n\t\treturn\n\t}\n\n\t// We grab the lock to ensure that no new containers will grab memory block while\n\t// executing the code below. Without this lock, its possible that we end up\n\t// removing state that is newly added by an asynchronous call to\n\t// AddContainer() during the execution of this code.\n\tm.Lock()\n\tdefer m.Unlock()\n\n\t// Get the list of admitted and active pods.\n\tactiveAndAdmittedPods := m.activePods()\n\tif m.pendingAdmissionPod != nil {\n\t\tactiveAndAdmittedPods = append(activeAndAdmittedPods, m.pendingAdmissionPod)\n\t}\n\n\t// Build a list of (podUID, containerName) pairs for all containers in all active Pods.\n\tactiveContainers := make(map[string]map[string]struct{})\n\tfor _, pod := range activeAndAdmittedPods {\n\t\tactiveContainers[string(pod.UID)] = make(map[string]struct{})\n\t\tfor _, container := range append(pod.Spec.InitContainers, pod.Spec.Containers...) {\n\t\t\tactiveContainers[string(pod.UID)][container.Name] = struct{}{}\n\t\t}\n\t}\n\n\t// Loop through the MemoryManager state. Remove any state for containers not\n\t// in the `activeContainers` list built above.\n\tassignments := m.state.GetMemoryAssignments()\n\tfor podUID := range assignments {\n\t\tfor containerName := range assignments[podUID] {\n\t\t\tif _, ok := activeContainers[podUID][containerName]; !ok {\n\t\t\t\tklog.InfoS(\"RemoveStaleState removing state\", \"podUID\", podUID, \"containerName\", containerName)\n\t\t\t\tm.policyRemoveContainerByRef(podUID, containerName)\n\t\t\t}\n\t\t}\n\t}\n\n\tm.containerMap.Visit(func(podUID, containerName, containerID string) {\n\t\tif _, ok := activeContainers[podUID][containerName]; !ok {\n\t\t\tklog.InfoS(\"RemoveStaleState removing state\", \"podUID\", podUID, \"containerName\", containerName)\n\t\t\tm.policyRemoveContainerByRef(podUID, containerName)\n\t\t}\n\t})\n}","line":{"from":301,"to":350}} {"id":100006059,"name":"policyRemoveContainerByRef","signature":"func (m *manager) policyRemoveContainerByRef(podUID string, containerName string)","file":"pkg/kubelet/cm/memorymanager/memory_manager.go","code":"func (m *manager) policyRemoveContainerByRef(podUID string, containerName string) {\n\tm.policy.RemoveContainer(m.state, podUID, containerName)\n\tm.containerMap.RemoveByContainerRef(podUID, containerName)\n}","line":{"from":352,"to":355}} {"id":100006060,"name":"getTotalMemoryTypeReserved","signature":"func getTotalMemoryTypeReserved(machineInfo *cadvisorapi.MachineInfo, reservedMemory []kubeletconfig.MemoryReservation) (map[v1.ResourceName]resource.Quantity, error)","file":"pkg/kubelet/cm/memorymanager/memory_manager.go","code":"func getTotalMemoryTypeReserved(machineInfo *cadvisorapi.MachineInfo, reservedMemory []kubeletconfig.MemoryReservation) (map[v1.ResourceName]resource.Quantity, error) {\n\ttotalMemoryType := map[v1.ResourceName]resource.Quantity{}\n\n\tnumaNodes := map[int]bool{}\n\tfor _, numaNode := range machineInfo.Topology {\n\t\tnumaNodes[numaNode.Id] = true\n\t}\n\n\tfor _, reservation := range reservedMemory {\n\t\tif !numaNodes[int(reservation.NumaNode)] {\n\t\t\treturn nil, fmt.Errorf(\"the reserved memory configuration references a NUMA node %d that does not exist on this machine\", reservation.NumaNode)\n\t\t}\n\n\t\tfor resourceName, q := range reservation.Limits {\n\t\t\tif value, ok := totalMemoryType[resourceName]; ok {\n\t\t\t\tq.Add(value)\n\t\t\t}\n\t\t\ttotalMemoryType[resourceName] = q\n\t\t}\n\t}\n\n\treturn totalMemoryType, nil\n}","line":{"from":357,"to":379}} {"id":100006061,"name":"validateReservedMemory","signature":"func validateReservedMemory(machineInfo *cadvisorapi.MachineInfo, nodeAllocatableReservation v1.ResourceList, reservedMemory []kubeletconfig.MemoryReservation) error","file":"pkg/kubelet/cm/memorymanager/memory_manager.go","code":"func validateReservedMemory(machineInfo *cadvisorapi.MachineInfo, nodeAllocatableReservation v1.ResourceList, reservedMemory []kubeletconfig.MemoryReservation) error {\n\ttotalMemoryType, err := getTotalMemoryTypeReserved(machineInfo, reservedMemory)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcommonMemoryTypeSet := make(map[v1.ResourceName]bool)\n\tfor resourceType := range totalMemoryType {\n\t\tcommonMemoryTypeSet[resourceType] = true\n\t}\n\n\tfor resourceType := range nodeAllocatableReservation {\n\t\tif !(corev1helper.IsHugePageResourceName(resourceType) || resourceType == v1.ResourceMemory) {\n\t\t\tcontinue\n\t\t}\n\t\tcommonMemoryTypeSet[resourceType] = true\n\t}\n\n\tfor resourceType := range commonMemoryTypeSet {\n\t\tnodeAllocatableMemory := resource.NewQuantity(0, resource.DecimalSI)\n\t\tif memValue, set := nodeAllocatableReservation[resourceType]; set {\n\t\t\tnodeAllocatableMemory.Add(memValue)\n\t\t}\n\n\t\treservedMemory := resource.NewQuantity(0, resource.DecimalSI)\n\t\tif memValue, set := totalMemoryType[resourceType]; set {\n\t\t\treservedMemory.Add(memValue)\n\t\t}\n\n\t\tif !(*nodeAllocatableMemory).Equal(*reservedMemory) {\n\t\t\treturn fmt.Errorf(\"the total amount %q of type %q is not equal to the value %q determined by Node Allocatable feature\", reservedMemory.String(), resourceType, nodeAllocatableMemory.String())\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":381,"to":416}} {"id":100006062,"name":"convertReserved","signature":"func convertReserved(machineInfo *cadvisorapi.MachineInfo, reservedMemory []kubeletconfig.MemoryReservation) (systemReservedMemory, error)","file":"pkg/kubelet/cm/memorymanager/memory_manager.go","code":"func convertReserved(machineInfo *cadvisorapi.MachineInfo, reservedMemory []kubeletconfig.MemoryReservation) (systemReservedMemory, error) {\n\treservedMemoryConverted := make(map[int]map[v1.ResourceName]uint64)\n\tfor _, node := range machineInfo.Topology {\n\t\treservedMemoryConverted[node.Id] = make(map[v1.ResourceName]uint64)\n\t}\n\n\tfor _, reservation := range reservedMemory {\n\t\tfor resourceName, q := range reservation.Limits {\n\t\t\tval, success := q.AsInt64()\n\t\t\tif !success {\n\t\t\t\treturn nil, fmt.Errorf(\"could not covert a variable of type Quantity to int64\")\n\t\t\t}\n\t\t\treservedMemoryConverted[int(reservation.NumaNode)][resourceName] = uint64(val)\n\t\t}\n\t}\n\n\treturn reservedMemoryConverted, nil\n}","line":{"from":418,"to":435}} {"id":100006063,"name":"getSystemReservedMemory","signature":"func getSystemReservedMemory(machineInfo *cadvisorapi.MachineInfo, nodeAllocatableReservation v1.ResourceList, reservedMemory []kubeletconfig.MemoryReservation) (systemReservedMemory, error)","file":"pkg/kubelet/cm/memorymanager/memory_manager.go","code":"func getSystemReservedMemory(machineInfo *cadvisorapi.MachineInfo, nodeAllocatableReservation v1.ResourceList, reservedMemory []kubeletconfig.MemoryReservation) (systemReservedMemory, error) {\n\tif err := validateReservedMemory(machineInfo, nodeAllocatableReservation, reservedMemory); err != nil {\n\t\treturn nil, err\n\t}\n\n\treservedMemoryConverted, err := convertReserved(machineInfo, reservedMemory)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn reservedMemoryConverted, nil\n}","line":{"from":437,"to":448}} {"id":100006064,"name":"GetAllocatableMemory","signature":"func (m *manager) GetAllocatableMemory() []state.Block","file":"pkg/kubelet/cm/memorymanager/memory_manager.go","code":"// GetAllocatableMemory returns the amount of allocatable memory for each NUMA node\nfunc (m *manager) GetAllocatableMemory() []state.Block {\n\treturn m.allocatableMemory\n}","line":{"from":450,"to":453}} {"id":100006065,"name":"GetMemory","signature":"func (m *manager) GetMemory(podUID, containerName string) []state.Block","file":"pkg/kubelet/cm/memorymanager/memory_manager.go","code":"// GetMemory returns the memory allocated by a container from NUMA nodes\nfunc (m *manager) GetMemory(podUID, containerName string) []state.Block {\n\treturn m.state.GetMemoryBlocks(podUID, containerName)\n}","line":{"from":455,"to":458}} {"id":100006066,"name":"setPodPendingAdmission","signature":"func (m *manager) setPodPendingAdmission(pod *v1.Pod)","file":"pkg/kubelet/cm/memorymanager/memory_manager.go","code":"func (m *manager) setPodPendingAdmission(pod *v1.Pod) {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tm.pendingAdmissionPod = pod\n}","line":{"from":460,"to":465}} {"id":100006067,"name":"NewPolicyNone","signature":"func NewPolicyNone() Policy","file":"pkg/kubelet/cm/memorymanager/policy_none.go","code":"// NewPolicyNone returns new none policy instance\nfunc NewPolicyNone() Policy {\n\treturn \u0026none{}\n}","line":{"from":33,"to":36}} {"id":100006068,"name":"Name","signature":"func (p *none) Name() string","file":"pkg/kubelet/cm/memorymanager/policy_none.go","code":"func (p *none) Name() string {\n\treturn string(policyTypeNone)\n}","line":{"from":38,"to":40}} {"id":100006069,"name":"Start","signature":"func (p *none) Start(s state.State) error","file":"pkg/kubelet/cm/memorymanager/policy_none.go","code":"func (p *none) Start(s state.State) error {\n\treturn nil\n}","line":{"from":42,"to":44}} {"id":100006070,"name":"Allocate","signature":"func (p *none) Allocate(s state.State, pod *v1.Pod, container *v1.Container) error","file":"pkg/kubelet/cm/memorymanager/policy_none.go","code":"// Allocate call is idempotent\nfunc (p *none) Allocate(s state.State, pod *v1.Pod, container *v1.Container) error {\n\treturn nil\n}","line":{"from":46,"to":49}} {"id":100006071,"name":"RemoveContainer","signature":"func (p *none) RemoveContainer(s state.State, podUID string, containerName string)","file":"pkg/kubelet/cm/memorymanager/policy_none.go","code":"// RemoveContainer call is idempotent\nfunc (p *none) RemoveContainer(s state.State, podUID string, containerName string) {\n}","line":{"from":51,"to":53}} {"id":100006072,"name":"GetTopologyHints","signature":"func (p *none) GetTopologyHints(s state.State, pod *v1.Pod, container *v1.Container) map[string][]topologymanager.TopologyHint","file":"pkg/kubelet/cm/memorymanager/policy_none.go","code":"// GetTopologyHints implements the topologymanager.HintProvider Interface\n// and is consulted to achieve NUMA aware resource alignment among this\n// and other resource controllers.\nfunc (p *none) GetTopologyHints(s state.State, pod *v1.Pod, container *v1.Container) map[string][]topologymanager.TopologyHint {\n\treturn nil\n}","line":{"from":55,"to":60}} {"id":100006073,"name":"GetPodTopologyHints","signature":"func (p *none) GetPodTopologyHints(s state.State, pod *v1.Pod) map[string][]topologymanager.TopologyHint","file":"pkg/kubelet/cm/memorymanager/policy_none.go","code":"// GetPodTopologyHints implements the topologymanager.HintProvider Interface\n// and is consulted to achieve NUMA aware resource alignment among this\n// and other resource controllers.\nfunc (p *none) GetPodTopologyHints(s state.State, pod *v1.Pod) map[string][]topologymanager.TopologyHint {\n\treturn nil\n}","line":{"from":62,"to":67}} {"id":100006074,"name":"GetAllocatableMemory","signature":"func (p *none) GetAllocatableMemory(s state.State) []state.Block","file":"pkg/kubelet/cm/memorymanager/policy_none.go","code":"// GetAllocatableMemory returns the amount of allocatable memory for each NUMA node\nfunc (p *none) GetAllocatableMemory(s state.State) []state.Block {\n\treturn []state.Block{}\n}","line":{"from":69,"to":72}} {"id":100006075,"name":"NewPolicyStatic","signature":"func NewPolicyStatic(machineInfo *cadvisorapi.MachineInfo, reserved systemReservedMemory, affinity topologymanager.Store) (Policy, error)","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"// NewPolicyStatic returns new static policy instance\nfunc NewPolicyStatic(machineInfo *cadvisorapi.MachineInfo, reserved systemReservedMemory, affinity topologymanager.Store) (Policy, error) {\n\tvar totalSystemReserved uint64\n\tfor _, node := range reserved {\n\t\tif _, ok := node[v1.ResourceMemory]; !ok {\n\t\t\tcontinue\n\t\t}\n\t\ttotalSystemReserved += node[v1.ResourceMemory]\n\t}\n\n\t// check if we have some reserved memory for the system\n\tif totalSystemReserved \u003c= 0 {\n\t\treturn nil, fmt.Errorf(\"[memorymanager] you should specify the system reserved memory\")\n\t}\n\n\treturn \u0026staticPolicy{\n\t\tmachineInfo: machineInfo,\n\t\tsystemReserved: reserved,\n\t\taffinity: affinity,\n\t\tinitContainersReusableMemory: reusableMemory{},\n\t}, nil\n}","line":{"from":58,"to":79}} {"id":100006076,"name":"Name","signature":"func (p *staticPolicy) Name() string","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"func (p *staticPolicy) Name() string {\n\treturn string(policyTypeStatic)\n}","line":{"from":81,"to":83}} {"id":100006077,"name":"Start","signature":"func (p *staticPolicy) Start(s state.State) error","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"func (p *staticPolicy) Start(s state.State) error {\n\tif err := p.validateState(s); err != nil {\n\t\tklog.ErrorS(err, \"Invalid state, please drain node and remove policy state file\")\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":85,"to":91}} {"id":100006078,"name":"Allocate","signature":"func (p *staticPolicy) Allocate(s state.State, pod *v1.Pod, container *v1.Container) error","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"// Allocate call is idempotent\nfunc (p *staticPolicy) Allocate(s state.State, pod *v1.Pod, container *v1.Container) error {\n\t// allocate the memory only for guaranteed pods\n\tif v1qos.GetPodQOS(pod) != v1.PodQOSGuaranteed {\n\t\treturn nil\n\t}\n\n\tpodUID := string(pod.UID)\n\tklog.InfoS(\"Allocate\", \"pod\", klog.KObj(pod), \"containerName\", container.Name)\n\tif blocks := s.GetMemoryBlocks(podUID, container.Name); blocks != nil {\n\t\tp.updatePodReusableMemory(pod, container, blocks)\n\n\t\tklog.InfoS(\"Container already present in state, skipping\", \"pod\", klog.KObj(pod), \"containerName\", container.Name)\n\t\treturn nil\n\t}\n\n\t// Call Topology Manager to get the aligned affinity across all hint providers.\n\thint := p.affinity.GetAffinity(podUID, container.Name)\n\tklog.InfoS(\"Got topology affinity\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID, \"containerName\", container.Name, \"hint\", hint)\n\n\trequestedResources, err := getRequestedResources(pod, container)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmachineState := s.GetMachineState()\n\tbestHint := \u0026hint\n\t// topology manager returned the hint with NUMA affinity nil\n\t// we should use the default NUMA affinity calculated the same way as for the topology manager\n\tif hint.NUMANodeAffinity == nil {\n\t\tdefaultHint, err := p.getDefaultHint(machineState, pod, requestedResources)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif !defaultHint.Preferred \u0026\u0026 bestHint.Preferred {\n\t\t\treturn fmt.Errorf(\"[memorymanager] failed to find the default preferred hint\")\n\t\t}\n\t\tbestHint = defaultHint\n\t}\n\n\t// topology manager returns the hint that does not satisfy completely the container request\n\t// we should extend this hint to the one who will satisfy the request and include the current hint\n\tif !isAffinitySatisfyRequest(machineState, bestHint.NUMANodeAffinity, requestedResources) {\n\t\textendedHint, err := p.extendTopologyManagerHint(machineState, pod, requestedResources, bestHint.NUMANodeAffinity)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif !extendedHint.Preferred \u0026\u0026 bestHint.Preferred {\n\t\t\treturn fmt.Errorf(\"[memorymanager] failed to find the extended preferred hint\")\n\t\t}\n\t\tbestHint = extendedHint\n\t}\n\n\tvar containerBlocks []state.Block\n\tmaskBits := bestHint.NUMANodeAffinity.GetBits()\n\tfor resourceName, requestedSize := range requestedResources {\n\t\t// update memory blocks\n\t\tcontainerBlocks = append(containerBlocks, state.Block{\n\t\t\tNUMAAffinity: maskBits,\n\t\t\tSize: requestedSize,\n\t\t\tType: resourceName,\n\t\t})\n\n\t\tpodReusableMemory := p.getPodReusableMemory(pod, bestHint.NUMANodeAffinity, resourceName)\n\t\tif podReusableMemory \u003e= requestedSize {\n\t\t\trequestedSize = 0\n\t\t} else {\n\t\t\trequestedSize -= podReusableMemory\n\t\t}\n\n\t\t// Update nodes memory state\n\t\tp.updateMachineState(machineState, maskBits, resourceName, requestedSize)\n\t}\n\n\tp.updatePodReusableMemory(pod, container, containerBlocks)\n\n\ts.SetMachineState(machineState)\n\ts.SetMemoryBlocks(podUID, container.Name, containerBlocks)\n\n\t// update init containers memory blocks to reflect the fact that we re-used init containers memory\n\t// it is possible that the size of the init container memory block will have 0 value, when all memory\n\t// allocated for it was re-used\n\t// we only do this so that the sum(memory_for_all_containers) == total amount of allocated memory to the pod, even\n\t// though the final state here doesn't accurately reflect what was (in reality) allocated to each container\n\t// TODO: we should refactor our state structs to reflect the amount of the re-used memory\n\tp.updateInitContainersMemoryBlocks(s, pod, container, containerBlocks)\n\n\treturn nil\n}","line":{"from":93,"to":183}} {"id":100006079,"name":"updateMachineState","signature":"func (p *staticPolicy) updateMachineState(machineState state.NUMANodeMap, numaAffinity []int, resourceName v1.ResourceName, requestedSize uint64)","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"func (p *staticPolicy) updateMachineState(machineState state.NUMANodeMap, numaAffinity []int, resourceName v1.ResourceName, requestedSize uint64) {\n\tfor _, nodeID := range numaAffinity {\n\t\tmachineState[nodeID].NumberOfAssignments++\n\t\tmachineState[nodeID].Cells = numaAffinity\n\n\t\t// we need to continue to update all affinity mask nodes\n\t\tif requestedSize == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\t// update the node memory state\n\t\tnodeResourceMemoryState := machineState[nodeID].MemoryMap[resourceName]\n\t\tif nodeResourceMemoryState.Free \u003c= 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\t// the node has enough memory to satisfy the request\n\t\tif nodeResourceMemoryState.Free \u003e= requestedSize {\n\t\t\tnodeResourceMemoryState.Reserved += requestedSize\n\t\t\tnodeResourceMemoryState.Free -= requestedSize\n\t\t\trequestedSize = 0\n\t\t\tcontinue\n\t\t}\n\n\t\t// the node does not have enough memory, use the node remaining memory and move to the next node\n\t\trequestedSize -= nodeResourceMemoryState.Free\n\t\tnodeResourceMemoryState.Reserved += nodeResourceMemoryState.Free\n\t\tnodeResourceMemoryState.Free = 0\n\t}\n}","line":{"from":185,"to":214}} {"id":100006080,"name":"getPodReusableMemory","signature":"func (p *staticPolicy) getPodReusableMemory(pod *v1.Pod, numaAffinity bitmask.BitMask, resourceName v1.ResourceName) uint64","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"func (p *staticPolicy) getPodReusableMemory(pod *v1.Pod, numaAffinity bitmask.BitMask, resourceName v1.ResourceName) uint64 {\n\tpodReusableMemory, ok := p.initContainersReusableMemory[string(pod.UID)]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\tnumaReusableMemory, ok := podReusableMemory[numaAffinity.String()]\n\tif !ok {\n\t\treturn 0\n\t}\n\n\treturn numaReusableMemory[resourceName]\n}","line":{"from":216,"to":228}} {"id":100006081,"name":"RemoveContainer","signature":"func (p *staticPolicy) RemoveContainer(s state.State, podUID string, containerName string)","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"// RemoveContainer call is idempotent\nfunc (p *staticPolicy) RemoveContainer(s state.State, podUID string, containerName string) {\n\tblocks := s.GetMemoryBlocks(podUID, containerName)\n\tif blocks == nil {\n\t\treturn\n\t}\n\n\tklog.InfoS(\"RemoveContainer\", \"podUID\", podUID, \"containerName\", containerName)\n\ts.Delete(podUID, containerName)\n\n\t// Mutate machine memory state to update free and reserved memory\n\tmachineState := s.GetMachineState()\n\tfor _, b := range blocks {\n\t\treleasedSize := b.Size\n\t\tfor _, nodeID := range b.NUMAAffinity {\n\t\t\tmachineState[nodeID].NumberOfAssignments--\n\n\t\t\t// once we do not have any memory allocations on this node, clear node groups\n\t\t\tif machineState[nodeID].NumberOfAssignments == 0 {\n\t\t\t\tmachineState[nodeID].Cells = []int{nodeID}\n\t\t\t}\n\n\t\t\t// we still need to pass over all NUMA node under the affinity mask to update them\n\t\t\tif releasedSize == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tnodeResourceMemoryState := machineState[nodeID].MemoryMap[b.Type]\n\n\t\t\t// if the node does not have reserved memory to free, continue to the next node\n\t\t\tif nodeResourceMemoryState.Reserved == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// the reserved memory smaller than the amount of the memory that should be released\n\t\t\t// release as much as possible and move to the next node\n\t\t\tif nodeResourceMemoryState.Reserved \u003c releasedSize {\n\t\t\t\treleasedSize -= nodeResourceMemoryState.Reserved\n\t\t\t\tnodeResourceMemoryState.Free += nodeResourceMemoryState.Reserved\n\t\t\t\tnodeResourceMemoryState.Reserved = 0\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// the reserved memory big enough to satisfy the released memory\n\t\t\tnodeResourceMemoryState.Free += releasedSize\n\t\t\tnodeResourceMemoryState.Reserved -= releasedSize\n\t\t\treleasedSize = 0\n\t\t}\n\t}\n\n\ts.SetMachineState(machineState)\n}","line":{"from":230,"to":281}} {"id":100006082,"name":"regenerateHints","signature":"func regenerateHints(pod *v1.Pod, ctn *v1.Container, ctnBlocks []state.Block, reqRsrc map[v1.ResourceName]uint64) map[string][]topologymanager.TopologyHint","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"func regenerateHints(pod *v1.Pod, ctn *v1.Container, ctnBlocks []state.Block, reqRsrc map[v1.ResourceName]uint64) map[string][]topologymanager.TopologyHint {\n\thints := map[string][]topologymanager.TopologyHint{}\n\tfor resourceName := range reqRsrc {\n\t\thints[string(resourceName)] = []topologymanager.TopologyHint{}\n\t}\n\n\tif len(ctnBlocks) != len(reqRsrc) {\n\t\tklog.ErrorS(nil, \"The number of requested resources by the container differs from the number of memory blocks\", \"containerName\", ctn.Name)\n\t\treturn nil\n\t}\n\n\tfor _, b := range ctnBlocks {\n\t\tif _, ok := reqRsrc[b.Type]; !ok {\n\t\t\tklog.ErrorS(nil, \"Container requested resources do not have resource of this type\", \"containerName\", ctn.Name, \"type\", b.Type)\n\t\t\treturn nil\n\t\t}\n\n\t\tif b.Size != reqRsrc[b.Type] {\n\t\t\tklog.ErrorS(nil, \"Memory already allocated with different numbers than requested\", \"podUID\", pod.UID, \"type\", b.Type, \"containerName\", ctn.Name, \"requestedResource\", reqRsrc[b.Type], \"allocatedSize\", b.Size)\n\t\t\treturn nil\n\t\t}\n\n\t\tcontainerNUMAAffinity, err := bitmask.NewBitMask(b.NUMAAffinity...)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to generate NUMA bitmask\")\n\t\t\treturn nil\n\t\t}\n\n\t\tklog.InfoS(\"Regenerating TopologyHints, resource was already allocated to pod\", \"resourceName\", b.Type, \"pod\", klog.KObj(pod), \"podUID\", pod.UID, \"containerName\", ctn.Name)\n\t\thints[string(b.Type)] = append(hints[string(b.Type)], topologymanager.TopologyHint{\n\t\t\tNUMANodeAffinity: containerNUMAAffinity,\n\t\t\tPreferred: true,\n\t\t})\n\t}\n\treturn hints\n}","line":{"from":283,"to":318}} {"id":100006083,"name":"getPodRequestedResources","signature":"func getPodRequestedResources(pod *v1.Pod) (map[v1.ResourceName]uint64, error)","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"func getPodRequestedResources(pod *v1.Pod) (map[v1.ResourceName]uint64, error) {\n\treqRsrcsByInitCtrs := make(map[v1.ResourceName]uint64)\n\treqRsrcsByAppCtrs := make(map[v1.ResourceName]uint64)\n\n\tfor _, ctr := range pod.Spec.InitContainers {\n\t\treqRsrcs, err := getRequestedResources(pod, \u0026ctr)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor rsrcName, qty := range reqRsrcs {\n\t\t\tif _, ok := reqRsrcsByInitCtrs[rsrcName]; !ok {\n\t\t\t\treqRsrcsByInitCtrs[rsrcName] = uint64(0)\n\t\t\t}\n\n\t\t\tif reqRsrcs[rsrcName] \u003e reqRsrcsByInitCtrs[rsrcName] {\n\t\t\t\treqRsrcsByInitCtrs[rsrcName] = qty\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, ctr := range pod.Spec.Containers {\n\t\treqRsrcs, err := getRequestedResources(pod, \u0026ctr)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor rsrcName, qty := range reqRsrcs {\n\t\t\tif _, ok := reqRsrcsByAppCtrs[rsrcName]; !ok {\n\t\t\t\treqRsrcsByAppCtrs[rsrcName] = uint64(0)\n\t\t\t}\n\n\t\t\treqRsrcsByAppCtrs[rsrcName] += qty\n\t\t}\n\t}\n\n\tfor rsrcName := range reqRsrcsByAppCtrs {\n\t\tif reqRsrcsByInitCtrs[rsrcName] \u003e reqRsrcsByAppCtrs[rsrcName] {\n\t\t\treqRsrcsByAppCtrs[rsrcName] = reqRsrcsByInitCtrs[rsrcName]\n\t\t}\n\t}\n\treturn reqRsrcsByAppCtrs, nil\n}","line":{"from":320,"to":362}} {"id":100006084,"name":"GetPodTopologyHints","signature":"func (p *staticPolicy) GetPodTopologyHints(s state.State, pod *v1.Pod) map[string][]topologymanager.TopologyHint","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"func (p *staticPolicy) GetPodTopologyHints(s state.State, pod *v1.Pod) map[string][]topologymanager.TopologyHint {\n\tif v1qos.GetPodQOS(pod) != v1.PodQOSGuaranteed {\n\t\treturn nil\n\t}\n\n\treqRsrcs, err := getPodRequestedResources(pod)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to get pod requested resources\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\t\treturn nil\n\t}\n\n\tfor _, ctn := range append(pod.Spec.InitContainers, pod.Spec.Containers...) {\n\t\tcontainerBlocks := s.GetMemoryBlocks(string(pod.UID), ctn.Name)\n\t\t// Short circuit to regenerate the same hints if there are already\n\t\t// memory allocated for the container. This might happen after a\n\t\t// kubelet restart, for example.\n\t\tif containerBlocks != nil {\n\t\t\treturn regenerateHints(pod, \u0026ctn, containerBlocks, reqRsrcs)\n\t\t}\n\t}\n\n\t// the pod topology hints calculated only once for all containers, so no need to pass re-usable state\n\treturn p.calculateHints(s.GetMachineState(), pod, reqRsrcs)\n}","line":{"from":364,"to":387}} {"id":100006085,"name":"GetTopologyHints","signature":"func (p *staticPolicy) GetTopologyHints(s state.State, pod *v1.Pod, container *v1.Container) map[string][]topologymanager.TopologyHint","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"// GetTopologyHints implements the topologymanager.HintProvider Interface\n// and is consulted to achieve NUMA aware resource alignment among this\n// and other resource controllers.\nfunc (p *staticPolicy) GetTopologyHints(s state.State, pod *v1.Pod, container *v1.Container) map[string][]topologymanager.TopologyHint {\n\tif v1qos.GetPodQOS(pod) != v1.PodQOSGuaranteed {\n\t\treturn nil\n\t}\n\n\trequestedResources, err := getRequestedResources(pod, container)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to get container requested resources\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID, \"containerName\", container.Name)\n\t\treturn nil\n\t}\n\n\tcontainerBlocks := s.GetMemoryBlocks(string(pod.UID), container.Name)\n\t// Short circuit to regenerate the same hints if there are already\n\t// memory allocated for the container. This might happen after a\n\t// kubelet restart, for example.\n\tif containerBlocks != nil {\n\t\treturn regenerateHints(pod, container, containerBlocks, requestedResources)\n\t}\n\n\treturn p.calculateHints(s.GetMachineState(), pod, requestedResources)\n}","line":{"from":389,"to":412}} {"id":100006086,"name":"getRequestedResources","signature":"func getRequestedResources(pod *v1.Pod, container *v1.Container) (map[v1.ResourceName]uint64, error)","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"func getRequestedResources(pod *v1.Pod, container *v1.Container) (map[v1.ResourceName]uint64, error) {\n\trequestedResources := map[v1.ResourceName]uint64{}\n\tresources := container.Resources.Requests\n\t// In-place pod resize feature makes Container.Resources field mutable for CPU \u0026 memory.\n\t// AllocatedResources holds the value of Container.Resources.Requests when the pod was admitted.\n\t// We should return this value because this is what kubelet agreed to allocate for the container\n\t// and the value configured with runtime.\n\tif utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) {\n\t\tif cs, ok := podutil.GetContainerStatus(pod.Status.ContainerStatuses, container.Name); ok {\n\t\t\tresources = cs.AllocatedResources\n\t\t}\n\t}\n\tfor resourceName, quantity := range resources {\n\t\tif resourceName != v1.ResourceMemory \u0026\u0026 !corehelper.IsHugePageResourceName(resourceName) {\n\t\t\tcontinue\n\t\t}\n\t\trequestedSize, succeed := quantity.AsInt64()\n\t\tif !succeed {\n\t\t\treturn nil, fmt.Errorf(\"[memorymanager] failed to represent quantity as int64\")\n\t\t}\n\t\trequestedResources[resourceName] = uint64(requestedSize)\n\t}\n\treturn requestedResources, nil\n}","line":{"from":414,"to":437}} {"id":100006087,"name":"calculateHints","signature":"func (p *staticPolicy) calculateHints(machineState state.NUMANodeMap, pod *v1.Pod, requestedResources map[v1.ResourceName]uint64) map[string][]topologymanager.TopologyHint","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"func (p *staticPolicy) calculateHints(machineState state.NUMANodeMap, pod *v1.Pod, requestedResources map[v1.ResourceName]uint64) map[string][]topologymanager.TopologyHint {\n\tvar numaNodes []int\n\tfor n := range machineState {\n\t\tnumaNodes = append(numaNodes, n)\n\t}\n\tsort.Ints(numaNodes)\n\n\t// Initialize minAffinitySize to include all NUMA Cells.\n\tminAffinitySize := len(numaNodes)\n\n\thints := map[string][]topologymanager.TopologyHint{}\n\tbitmask.IterateBitMasks(numaNodes, func(mask bitmask.BitMask) {\n\t\tmaskBits := mask.GetBits()\n\t\tsingleNUMAHint := len(maskBits) == 1\n\n\t\ttotalFreeSize := map[v1.ResourceName]uint64{}\n\t\ttotalAllocatableSize := map[v1.ResourceName]uint64{}\n\t\t// calculate total free and allocatable memory for the node mask\n\t\tfor _, nodeID := range maskBits {\n\t\t\tfor resourceName := range requestedResources {\n\t\t\t\tif _, ok := totalFreeSize[resourceName]; !ok {\n\t\t\t\t\ttotalFreeSize[resourceName] = 0\n\t\t\t\t}\n\t\t\t\ttotalFreeSize[resourceName] += machineState[nodeID].MemoryMap[resourceName].Free\n\n\t\t\t\tif _, ok := totalAllocatableSize[resourceName]; !ok {\n\t\t\t\t\ttotalAllocatableSize[resourceName] = 0\n\t\t\t\t}\n\t\t\t\ttotalAllocatableSize[resourceName] += machineState[nodeID].MemoryMap[resourceName].Allocatable\n\t\t\t}\n\t\t}\n\n\t\t// verify that for all memory types the node mask has enough allocatable resources\n\t\tfor resourceName, requestedSize := range requestedResources {\n\t\t\tif totalAllocatableSize[resourceName] \u003c requestedSize {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t// set the minimum amount of NUMA nodes that can satisfy the container resources requests\n\t\tif mask.Count() \u003c minAffinitySize {\n\t\t\tminAffinitySize = mask.Count()\n\t\t}\n\n\t\t// the node already in group with another node, it can not be used for the single NUMA node allocation\n\t\tif singleNUMAHint \u0026\u0026 len(machineState[maskBits[0]].Cells) \u003e 1 {\n\t\t\treturn\n\t\t}\n\n\t\tfor _, nodeID := range maskBits {\n\t\t\t// the node already used for the memory allocation\n\t\t\tif !singleNUMAHint \u0026\u0026 machineState[nodeID].NumberOfAssignments \u003e 0 {\n\t\t\t\t// the node used for the single NUMA memory allocation, it can not be used for the multi NUMA node allocation\n\t\t\t\tif len(machineState[nodeID].Cells) == 1 {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// the node already used with different group of nodes, it can not be use with in the current hint\n\t\t\t\tif !areGroupsEqual(machineState[nodeID].Cells, maskBits) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// verify that for all memory types the node mask has enough free resources\n\t\tfor resourceName, requestedSize := range requestedResources {\n\t\t\tpodReusableMemory := p.getPodReusableMemory(pod, mask, resourceName)\n\t\t\tif totalFreeSize[resourceName]+podReusableMemory \u003c requestedSize {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t// add the node mask as topology hint for all memory types\n\t\tfor resourceName := range requestedResources {\n\t\t\tif _, ok := hints[string(resourceName)]; !ok {\n\t\t\t\thints[string(resourceName)] = []topologymanager.TopologyHint{}\n\t\t\t}\n\t\t\thints[string(resourceName)] = append(hints[string(resourceName)], topologymanager.TopologyHint{\n\t\t\t\tNUMANodeAffinity: mask,\n\t\t\t\tPreferred: false,\n\t\t\t})\n\t\t}\n\t})\n\n\t// update hints preferred according to multiNUMAGroups, in case when it wasn't provided, the default\n\t// behaviour to prefer the minimal amount of NUMA nodes will be used\n\tfor resourceName := range requestedResources {\n\t\tfor i, hint := range hints[string(resourceName)] {\n\t\t\thints[string(resourceName)][i].Preferred = p.isHintPreferred(hint.NUMANodeAffinity.GetBits(), minAffinitySize)\n\t\t}\n\t}\n\n\treturn hints\n}","line":{"from":439,"to":532}} {"id":100006088,"name":"isHintPreferred","signature":"func (p *staticPolicy) isHintPreferred(maskBits []int, minAffinitySize int) bool","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"func (p *staticPolicy) isHintPreferred(maskBits []int, minAffinitySize int) bool {\n\treturn len(maskBits) == minAffinitySize\n}","line":{"from":534,"to":536}} {"id":100006089,"name":"areGroupsEqual","signature":"func areGroupsEqual(group1, group2 []int) bool","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"func areGroupsEqual(group1, group2 []int) bool {\n\tsort.Ints(group1)\n\tsort.Ints(group2)\n\n\tif len(group1) != len(group2) {\n\t\treturn false\n\t}\n\n\tfor i, elm := range group1 {\n\t\tif group2[i] != elm {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":538,"to":552}} {"id":100006090,"name":"validateState","signature":"func (p *staticPolicy) validateState(s state.State) error","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"func (p *staticPolicy) validateState(s state.State) error {\n\tmachineState := s.GetMachineState()\n\tmemoryAssignments := s.GetMemoryAssignments()\n\n\tif len(machineState) == 0 {\n\t\t// Machine state cannot be empty when assignments exist\n\t\tif len(memoryAssignments) != 0 {\n\t\t\treturn fmt.Errorf(\"[memorymanager] machine state can not be empty when it has memory assignments\")\n\t\t}\n\n\t\tdefaultMachineState := p.getDefaultMachineState()\n\t\ts.SetMachineState(defaultMachineState)\n\n\t\treturn nil\n\t}\n\n\t// calculate all memory assigned to containers\n\texpectedMachineState := p.getDefaultMachineState()\n\tfor pod, container := range memoryAssignments {\n\t\tfor containerName, blocks := range container {\n\t\t\tfor _, b := range blocks {\n\t\t\t\trequestedSize := b.Size\n\t\t\t\tfor _, nodeID := range b.NUMAAffinity {\n\t\t\t\t\tnodeState, ok := expectedMachineState[nodeID]\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn fmt.Errorf(\"[memorymanager] (pod: %s, container: %s) the memory assignment uses the NUMA that does not exist\", pod, containerName)\n\t\t\t\t\t}\n\n\t\t\t\t\tnodeState.NumberOfAssignments++\n\t\t\t\t\tnodeState.Cells = b.NUMAAffinity\n\n\t\t\t\t\tmemoryState, ok := nodeState.MemoryMap[b.Type]\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn fmt.Errorf(\"[memorymanager] (pod: %s, container: %s) the memory assignment uses memory resource that does not exist\", pod, containerName)\n\t\t\t\t\t}\n\n\t\t\t\t\tif requestedSize == 0 {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\t// this node does not have enough memory continue to the next one\n\t\t\t\t\tif memoryState.Free \u003c= 0 {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\t// the node has enough memory to satisfy the request\n\t\t\t\t\tif memoryState.Free \u003e= requestedSize {\n\t\t\t\t\t\tmemoryState.Reserved += requestedSize\n\t\t\t\t\t\tmemoryState.Free -= requestedSize\n\t\t\t\t\t\trequestedSize = 0\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\t// the node does not have enough memory, use the node remaining memory and move to the next node\n\t\t\t\t\trequestedSize -= memoryState.Free\n\t\t\t\t\tmemoryState.Reserved += memoryState.Free\n\t\t\t\t\tmemoryState.Free = 0\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// State has already been initialized from file (is not empty)\n\t// Validate that total size, system reserved and reserved memory not changed, it can happen, when:\n\t// - adding or removing physical memory bank from the node\n\t// - change of kubelet system-reserved, kube-reserved or pre-reserved-memory-zone parameters\n\tif !areMachineStatesEqual(machineState, expectedMachineState) {\n\t\treturn fmt.Errorf(\"[memorymanager] the expected machine state is different from the real one\")\n\t}\n\n\treturn nil\n}","line":{"from":554,"to":625}} {"id":100006091,"name":"areMachineStatesEqual","signature":"func areMachineStatesEqual(ms1, ms2 state.NUMANodeMap) bool","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"func areMachineStatesEqual(ms1, ms2 state.NUMANodeMap) bool {\n\tif len(ms1) != len(ms2) {\n\t\tklog.ErrorS(nil, \"Node states are different\", \"lengthNode1\", len(ms1), \"lengthNode2\", len(ms2))\n\t\treturn false\n\t}\n\n\tfor nodeID, nodeState1 := range ms1 {\n\t\tnodeState2, ok := ms2[nodeID]\n\t\tif !ok {\n\t\t\tklog.ErrorS(nil, \"Node state does not have node ID\", \"nodeID\", nodeID)\n\t\t\treturn false\n\t\t}\n\n\t\tif nodeState1.NumberOfAssignments != nodeState2.NumberOfAssignments {\n\t\t\tklog.ErrorS(nil, \"Node states number of assignments are different\", \"assignment1\", nodeState1.NumberOfAssignments, \"assignment2\", nodeState2.NumberOfAssignments)\n\t\t\treturn false\n\t\t}\n\n\t\tif !areGroupsEqual(nodeState1.Cells, nodeState2.Cells) {\n\t\t\tklog.ErrorS(nil, \"Node states groups are different\", \"stateNode1\", nodeState1.Cells, \"stateNode2\", nodeState2.Cells)\n\t\t\treturn false\n\t\t}\n\n\t\tif len(nodeState1.MemoryMap) != len(nodeState2.MemoryMap) {\n\t\t\tklog.ErrorS(nil, \"Node states memory map have different lengths\", \"lengthNode1\", len(nodeState1.MemoryMap), \"lengthNode2\", len(nodeState2.MemoryMap))\n\t\t\treturn false\n\t\t}\n\n\t\tfor resourceName, memoryState1 := range nodeState1.MemoryMap {\n\t\t\tmemoryState2, ok := nodeState2.MemoryMap[resourceName]\n\t\t\tif !ok {\n\t\t\t\tklog.ErrorS(nil, \"Memory state does not have resource\", \"resource\", resourceName)\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tif !reflect.DeepEqual(*memoryState1, *memoryState2) {\n\t\t\t\tklog.ErrorS(nil, \"Memory states for the NUMA node and resource are different\", \"node\", nodeID, \"resource\", resourceName, \"memoryState1\", *memoryState1, \"memoryState2\", *memoryState2)\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}","line":{"from":627,"to":669}} {"id":100006092,"name":"getDefaultMachineState","signature":"func (p *staticPolicy) getDefaultMachineState() state.NUMANodeMap","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"func (p *staticPolicy) getDefaultMachineState() state.NUMANodeMap {\n\tdefaultMachineState := state.NUMANodeMap{}\n\tnodeHugepages := map[int]uint64{}\n\tfor _, node := range p.machineInfo.Topology {\n\t\tdefaultMachineState[node.Id] = \u0026state.NUMANodeState{\n\t\t\tNumberOfAssignments: 0,\n\t\t\tMemoryMap: map[v1.ResourceName]*state.MemoryTable{},\n\t\t\tCells: []int{node.Id},\n\t\t}\n\n\t\t// fill memory table with huge pages values\n\t\tfor _, hugepage := range node.HugePages {\n\t\t\thugepageQuantity := resource.NewQuantity(int64(hugepage.PageSize)*1024, resource.BinarySI)\n\t\t\tresourceName := corehelper.HugePageResourceName(*hugepageQuantity)\n\t\t\tsystemReserved := p.getResourceSystemReserved(node.Id, resourceName)\n\t\t\ttotalHugepagesSize := hugepage.NumPages * hugepage.PageSize * 1024\n\t\t\tallocatable := totalHugepagesSize - systemReserved\n\t\t\tdefaultMachineState[node.Id].MemoryMap[resourceName] = \u0026state.MemoryTable{\n\t\t\t\tAllocatable: allocatable,\n\t\t\t\tFree: allocatable,\n\t\t\t\tReserved: 0,\n\t\t\t\tSystemReserved: systemReserved,\n\t\t\t\tTotalMemSize: totalHugepagesSize,\n\t\t\t}\n\t\t\tif _, ok := nodeHugepages[node.Id]; !ok {\n\t\t\t\tnodeHugepages[node.Id] = 0\n\t\t\t}\n\t\t\tnodeHugepages[node.Id] += totalHugepagesSize\n\t\t}\n\n\t\t// fill memory table with regular memory values\n\t\tsystemReserved := p.getResourceSystemReserved(node.Id, v1.ResourceMemory)\n\n\t\tallocatable := node.Memory - systemReserved\n\t\t// remove memory allocated by hugepages\n\t\tif allocatedByHugepages, ok := nodeHugepages[node.Id]; ok {\n\t\t\tallocatable -= allocatedByHugepages\n\t\t}\n\t\tdefaultMachineState[node.Id].MemoryMap[v1.ResourceMemory] = \u0026state.MemoryTable{\n\t\t\tAllocatable: allocatable,\n\t\t\tFree: allocatable,\n\t\t\tReserved: 0,\n\t\t\tSystemReserved: systemReserved,\n\t\t\tTotalMemSize: node.Memory,\n\t\t}\n\t}\n\treturn defaultMachineState\n}","line":{"from":671,"to":718}} {"id":100006093,"name":"getResourceSystemReserved","signature":"func (p *staticPolicy) getResourceSystemReserved(nodeID int, resourceName v1.ResourceName) uint64","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"func (p *staticPolicy) getResourceSystemReserved(nodeID int, resourceName v1.ResourceName) uint64 {\n\tvar systemReserved uint64\n\tif nodeSystemReserved, ok := p.systemReserved[nodeID]; ok {\n\t\tif nodeMemorySystemReserved, ok := nodeSystemReserved[resourceName]; ok {\n\t\t\tsystemReserved = nodeMemorySystemReserved\n\t\t}\n\t}\n\treturn systemReserved\n}","line":{"from":720,"to":728}} {"id":100006094,"name":"getDefaultHint","signature":"func (p *staticPolicy) getDefaultHint(machineState state.NUMANodeMap, pod *v1.Pod, requestedResources map[v1.ResourceName]uint64) (*topologymanager.TopologyHint, error)","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"func (p *staticPolicy) getDefaultHint(machineState state.NUMANodeMap, pod *v1.Pod, requestedResources map[v1.ResourceName]uint64) (*topologymanager.TopologyHint, error) {\n\thints := p.calculateHints(machineState, pod, requestedResources)\n\tif len(hints) \u003c 1 {\n\t\treturn nil, fmt.Errorf(\"[memorymanager] failed to get the default NUMA affinity, no NUMA nodes with enough memory is available\")\n\t}\n\n\t// hints for all memory types should be the same, so we will check hints only for regular memory type\n\treturn findBestHint(hints[string(v1.ResourceMemory)]), nil\n}","line":{"from":730,"to":738}} {"id":100006095,"name":"isAffinitySatisfyRequest","signature":"func isAffinitySatisfyRequest(machineState state.NUMANodeMap, mask bitmask.BitMask, requestedResources map[v1.ResourceName]uint64) bool","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"func isAffinitySatisfyRequest(machineState state.NUMANodeMap, mask bitmask.BitMask, requestedResources map[v1.ResourceName]uint64) bool {\n\ttotalFreeSize := map[v1.ResourceName]uint64{}\n\tfor _, nodeID := range mask.GetBits() {\n\t\tfor resourceName := range requestedResources {\n\t\t\tif _, ok := totalFreeSize[resourceName]; !ok {\n\t\t\t\ttotalFreeSize[resourceName] = 0\n\t\t\t}\n\t\t\ttotalFreeSize[resourceName] += machineState[nodeID].MemoryMap[resourceName].Free\n\t\t}\n\t}\n\n\t// verify that for all memory types the node mask has enough resources\n\tfor resourceName, requestedSize := range requestedResources {\n\t\tif totalFreeSize[resourceName] \u003c requestedSize {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}","line":{"from":740,"to":759}} {"id":100006096,"name":"extendTopologyManagerHint","signature":"func (p *staticPolicy) extendTopologyManagerHint(machineState state.NUMANodeMap, pod *v1.Pod, requestedResources map[v1.ResourceName]uint64, mask bitmask.BitMask) (*topologymanager.TopologyHint, error)","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"// extendTopologyManagerHint extends the topology manager hint, in case when it does not satisfy to the container request\n// the topology manager uses bitwise AND to merge all topology hints into the best one, so in case of the restricted policy,\n// it possible that we will get the subset of hint that we provided to the topology manager, in this case we want to extend\n// it to the original one\nfunc (p *staticPolicy) extendTopologyManagerHint(machineState state.NUMANodeMap, pod *v1.Pod, requestedResources map[v1.ResourceName]uint64, mask bitmask.BitMask) (*topologymanager.TopologyHint, error) {\n\thints := p.calculateHints(machineState, pod, requestedResources)\n\n\tvar filteredHints []topologymanager.TopologyHint\n\t// hints for all memory types should be the same, so we will check hints only for regular memory type\n\tfor _, hint := range hints[string(v1.ResourceMemory)] {\n\t\taffinityBits := hint.NUMANodeAffinity.GetBits()\n\t\t// filter all hints that does not include currentHint\n\t\tif isHintInGroup(mask.GetBits(), affinityBits) {\n\t\t\tfilteredHints = append(filteredHints, hint)\n\t\t}\n\t}\n\n\tif len(filteredHints) \u003c 1 {\n\t\treturn nil, fmt.Errorf(\"[memorymanager] failed to find NUMA nodes to extend the current topology hint\")\n\t}\n\n\t// try to find the preferred hint with the minimal number of NUMA nodes, relevant for the restricted policy\n\treturn findBestHint(filteredHints), nil\n}","line":{"from":761,"to":784}} {"id":100006097,"name":"isHintInGroup","signature":"func isHintInGroup(hint []int, group []int) bool","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"func isHintInGroup(hint []int, group []int) bool {\n\tsort.Ints(hint)\n\tsort.Ints(group)\n\n\thintIndex := 0\n\tfor i := range group {\n\t\tif hintIndex == len(hint) {\n\t\t\treturn true\n\t\t}\n\n\t\tif group[i] != hint[hintIndex] {\n\t\t\tcontinue\n\t\t}\n\t\thintIndex++\n\t}\n\n\treturn hintIndex == len(hint)\n}","line":{"from":786,"to":803}} {"id":100006098,"name":"findBestHint","signature":"func findBestHint(hints []topologymanager.TopologyHint) *topologymanager.TopologyHint","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"func findBestHint(hints []topologymanager.TopologyHint) *topologymanager.TopologyHint {\n\t// try to find the preferred hint with the minimal number of NUMA nodes, relevant for the restricted policy\n\tbestHint := topologymanager.TopologyHint{}\n\tfor _, hint := range hints {\n\t\tif bestHint.NUMANodeAffinity == nil {\n\t\t\tbestHint = hint\n\t\t\tcontinue\n\t\t}\n\n\t\t// preferred of the current hint is true, when the extendedHint preferred is false\n\t\tif hint.Preferred \u0026\u0026 !bestHint.Preferred {\n\t\t\tbestHint = hint\n\t\t\tcontinue\n\t\t}\n\n\t\t// both hints has the same preferred value, but the current hint has less NUMA nodes than the extended one\n\t\tif hint.Preferred == bestHint.Preferred \u0026\u0026 hint.NUMANodeAffinity.IsNarrowerThan(bestHint.NUMANodeAffinity) {\n\t\t\tbestHint = hint\n\t\t}\n\t}\n\treturn \u0026bestHint\n}","line":{"from":805,"to":826}} {"id":100006099,"name":"GetAllocatableMemory","signature":"func (p *staticPolicy) GetAllocatableMemory(s state.State) []state.Block","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"// GetAllocatableMemory returns the amount of allocatable memory for each NUMA node\nfunc (p *staticPolicy) GetAllocatableMemory(s state.State) []state.Block {\n\tvar allocatableMemory []state.Block\n\tmachineState := s.GetMachineState()\n\tfor numaNodeID, numaNodeState := range machineState {\n\t\tfor resourceName, memoryTable := range numaNodeState.MemoryMap {\n\t\t\tif memoryTable.Allocatable == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tblock := state.Block{\n\t\t\t\tNUMAAffinity: []int{numaNodeID},\n\t\t\t\tType: resourceName,\n\t\t\t\tSize: memoryTable.Allocatable,\n\t\t\t}\n\t\t\tallocatableMemory = append(allocatableMemory, block)\n\t\t}\n\t}\n\treturn allocatableMemory\n}","line":{"from":828,"to":847}} {"id":100006100,"name":"updatePodReusableMemory","signature":"func (p *staticPolicy) updatePodReusableMemory(pod *v1.Pod, container *v1.Container, memoryBlocks []state.Block)","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"func (p *staticPolicy) updatePodReusableMemory(pod *v1.Pod, container *v1.Container, memoryBlocks []state.Block) {\n\tpodUID := string(pod.UID)\n\n\t// If pod entries to m.initContainersReusableMemory other than the current pod exist, delete them.\n\tfor uid := range p.initContainersReusableMemory {\n\t\tif podUID != uid {\n\t\t\tdelete(p.initContainersReusableMemory, uid)\n\t\t}\n\t}\n\n\tif isInitContainer(pod, container) {\n\t\tif _, ok := p.initContainersReusableMemory[podUID]; !ok {\n\t\t\tp.initContainersReusableMemory[podUID] = map[string]map[v1.ResourceName]uint64{}\n\t\t}\n\n\t\tfor _, block := range memoryBlocks {\n\t\t\tblockBitMask, _ := bitmask.NewBitMask(block.NUMAAffinity...)\n\t\t\tblockBitMaskString := blockBitMask.String()\n\n\t\t\tif _, ok := p.initContainersReusableMemory[podUID][blockBitMaskString]; !ok {\n\t\t\t\tp.initContainersReusableMemory[podUID][blockBitMaskString] = map[v1.ResourceName]uint64{}\n\t\t\t}\n\n\t\t\tif blockReusableMemory := p.initContainersReusableMemory[podUID][blockBitMaskString][block.Type]; block.Size \u003e blockReusableMemory {\n\t\t\t\tp.initContainersReusableMemory[podUID][blockBitMaskString][block.Type] = block.Size\n\t\t\t}\n\t\t}\n\n\t\treturn\n\t}\n\n\t// update re-usable memory once it used by the app container\n\tfor _, block := range memoryBlocks {\n\t\tblockBitMask, _ := bitmask.NewBitMask(block.NUMAAffinity...)\n\t\tif podReusableMemory := p.getPodReusableMemory(pod, blockBitMask, block.Type); podReusableMemory != 0 {\n\t\t\tif block.Size \u003e= podReusableMemory {\n\t\t\t\tp.initContainersReusableMemory[podUID][blockBitMask.String()][block.Type] = 0\n\t\t\t} else {\n\t\t\t\tp.initContainersReusableMemory[podUID][blockBitMask.String()][block.Type] -= block.Size\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":849,"to":891}} {"id":100006101,"name":"updateInitContainersMemoryBlocks","signature":"func (p *staticPolicy) updateInitContainersMemoryBlocks(s state.State, pod *v1.Pod, container *v1.Container, containerMemoryBlocks []state.Block)","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"func (p *staticPolicy) updateInitContainersMemoryBlocks(s state.State, pod *v1.Pod, container *v1.Container, containerMemoryBlocks []state.Block) {\n\tpodUID := string(pod.UID)\n\n\tfor _, containerBlock := range containerMemoryBlocks {\n\t\tblockSize := containerBlock.Size\n\t\tfor _, initContainer := range pod.Spec.InitContainers {\n\t\t\t// we do not want to continue updates once we reach the current container\n\t\t\tif initContainer.Name == container.Name {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif blockSize == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tinitContainerBlocks := s.GetMemoryBlocks(podUID, initContainer.Name)\n\t\t\tif len(initContainerBlocks) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor i := range initContainerBlocks {\n\t\t\t\tinitContainerBlock := \u0026initContainerBlocks[i]\n\t\t\t\tif initContainerBlock.Size == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif initContainerBlock.Type != containerBlock.Type {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif !isNUMAAffinitiesEqual(initContainerBlock.NUMAAffinity, containerBlock.NUMAAffinity) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif initContainerBlock.Size \u003e blockSize {\n\t\t\t\t\tinitContainerBlock.Size -= blockSize\n\t\t\t\t\tblockSize = 0\n\t\t\t\t} else {\n\t\t\t\t\tblockSize -= initContainerBlock.Size\n\t\t\t\t\tinitContainerBlock.Size = 0\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ts.SetMemoryBlocks(podUID, initContainer.Name, initContainerBlocks)\n\t\t}\n\t}\n}","line":{"from":893,"to":939}} {"id":100006102,"name":"isInitContainer","signature":"func isInitContainer(pod *v1.Pod, container *v1.Container) bool","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"func isInitContainer(pod *v1.Pod, container *v1.Container) bool {\n\tfor _, initContainer := range pod.Spec.InitContainers {\n\t\tif initContainer.Name == container.Name {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":941,"to":949}} {"id":100006103,"name":"isNUMAAffinitiesEqual","signature":"func isNUMAAffinitiesEqual(numaAffinity1, numaAffinity2 []int) bool","file":"pkg/kubelet/cm/memorymanager/policy_static.go","code":"func isNUMAAffinitiesEqual(numaAffinity1, numaAffinity2 []int) bool {\n\tbitMask1, err := bitmask.NewBitMask(numaAffinity1...)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"failed to create bit mask\", \"numaAffinity1\", numaAffinity1)\n\t\treturn false\n\t}\n\n\tbitMask2, err := bitmask.NewBitMask(numaAffinity2...)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"failed to create bit mask\", \"numaAffinity2\", numaAffinity2)\n\t\treturn false\n\t}\n\n\treturn bitMask1.IsEqual(bitMask2)\n}","line":{"from":951,"to":965}} {"id":100006104,"name":"NewMemoryManagerCheckpoint","signature":"func NewMemoryManagerCheckpoint() *MemoryManagerCheckpoint","file":"pkg/kubelet/cm/memorymanager/state/checkpoint.go","code":"// NewMemoryManagerCheckpoint returns an instance of Checkpoint\nfunc NewMemoryManagerCheckpoint() *MemoryManagerCheckpoint {\n\t//nolint:staticcheck // unexported-type-in-api user-facing error message\n\treturn \u0026MemoryManagerCheckpoint{\n\t\tEntries: ContainerMemoryAssignments{},\n\t\tMachineState: NUMANodeMap{},\n\t}\n}","line":{"from":36,"to":43}} {"id":100006105,"name":"MarshalCheckpoint","signature":"func (mp *MemoryManagerCheckpoint) MarshalCheckpoint() ([]byte, error)","file":"pkg/kubelet/cm/memorymanager/state/checkpoint.go","code":"// MarshalCheckpoint returns marshalled checkpoint\nfunc (mp *MemoryManagerCheckpoint) MarshalCheckpoint() ([]byte, error) {\n\t// make sure checksum wasn't set before so it doesn't affect output checksum\n\tmp.Checksum = 0\n\tmp.Checksum = checksum.New(mp)\n\treturn json.Marshal(*mp)\n}","line":{"from":45,"to":51}} {"id":100006106,"name":"UnmarshalCheckpoint","signature":"func (mp *MemoryManagerCheckpoint) UnmarshalCheckpoint(blob []byte) error","file":"pkg/kubelet/cm/memorymanager/state/checkpoint.go","code":"// UnmarshalCheckpoint tries to unmarshal passed bytes to checkpoint\nfunc (mp *MemoryManagerCheckpoint) UnmarshalCheckpoint(blob []byte) error {\n\treturn json.Unmarshal(blob, mp)\n}","line":{"from":53,"to":56}} {"id":100006107,"name":"VerifyChecksum","signature":"func (mp *MemoryManagerCheckpoint) VerifyChecksum() error","file":"pkg/kubelet/cm/memorymanager/state/checkpoint.go","code":"// VerifyChecksum verifies that current checksum of checkpoint is valid\nfunc (mp *MemoryManagerCheckpoint) VerifyChecksum() error {\n\tck := mp.Checksum\n\tmp.Checksum = 0\n\terr := ck.Verify(mp)\n\tmp.Checksum = ck\n\treturn err\n}","line":{"from":58,"to":65}} {"id":100006108,"name":"Clone","signature":"func (nm NUMANodeMap) Clone() NUMANodeMap","file":"pkg/kubelet/cm/memorymanager/state/state.go","code":"// Clone returns a copy of NUMANodeMap\nfunc (nm NUMANodeMap) Clone() NUMANodeMap {\n\tclone := make(NUMANodeMap)\n\tfor node, s := range nm {\n\t\tif s == nil {\n\t\t\tclone[node] = nil\n\t\t\tcontinue\n\t\t}\n\n\t\tclone[node] = \u0026NUMANodeState{}\n\t\tclone[node].NumberOfAssignments = s.NumberOfAssignments\n\t\tclone[node].Cells = append([]int{}, s.Cells...)\n\n\t\tif s.MemoryMap == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tclone[node].MemoryMap = map[v1.ResourceName]*MemoryTable{}\n\t\tfor memoryType, memoryTable := range s.MemoryMap {\n\t\t\tclone[node].MemoryMap[memoryType] = \u0026MemoryTable{\n\t\t\t\tAllocatable: memoryTable.Allocatable,\n\t\t\t\tFree: memoryTable.Free,\n\t\t\t\tReserved: memoryTable.Reserved,\n\t\t\t\tSystemReserved: memoryTable.SystemReserved,\n\t\t\t\tTotalMemSize: memoryTable.TotalMemSize,\n\t\t\t}\n\t\t}\n\t}\n\treturn clone\n}","line":{"from":49,"to":78}} {"id":100006109,"name":"Clone","signature":"func (as ContainerMemoryAssignments) Clone() ContainerMemoryAssignments","file":"pkg/kubelet/cm/memorymanager/state/state.go","code":"// Clone returns a copy of ContainerMemoryAssignments\nfunc (as ContainerMemoryAssignments) Clone() ContainerMemoryAssignments {\n\tclone := make(ContainerMemoryAssignments)\n\tfor pod := range as {\n\t\tclone[pod] = make(map[string][]Block)\n\t\tfor container, blocks := range as[pod] {\n\t\t\tclone[pod][container] = append([]Block{}, blocks...)\n\t\t}\n\t}\n\treturn clone\n}","line":{"from":91,"to":101}} {"id":100006110,"name":"NewCheckpointState","signature":"func NewCheckpointState(stateDir, checkpointName, policyName string) (State, error)","file":"pkg/kubelet/cm/memorymanager/state/state_checkpoint.go","code":"// NewCheckpointState creates new State for keeping track of memory/pod assignment with checkpoint backend\nfunc NewCheckpointState(stateDir, checkpointName, policyName string) (State, error) {\n\tcheckpointManager, err := checkpointmanager.NewCheckpointManager(stateDir)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize checkpoint manager: %v\", err)\n\t}\n\tstateCheckpoint := \u0026stateCheckpoint{\n\t\tcache: NewMemoryState(),\n\t\tpolicyName: policyName,\n\t\tcheckpointManager: checkpointManager,\n\t\tcheckpointName: checkpointName,\n\t}\n\n\tif err := stateCheckpoint.restoreState(); err != nil {\n\t\t//nolint:staticcheck // ST1005 user-facing error message\n\t\treturn nil, fmt.Errorf(\"could not restore state from checkpoint: %v, please drain this node and delete the memory manager checkpoint file %q before restarting Kubelet\",\n\t\t\terr, filepath.Join(stateDir, checkpointName))\n\t}\n\n\treturn stateCheckpoint, nil\n}","line":{"from":39,"to":59}} {"id":100006111,"name":"restoreState","signature":"func (sc *stateCheckpoint) restoreState() error","file":"pkg/kubelet/cm/memorymanager/state/state_checkpoint.go","code":"// restores state from a checkpoint and creates it if it doesn't exist\nfunc (sc *stateCheckpoint) restoreState() error {\n\tsc.Lock()\n\tdefer sc.Unlock()\n\tvar err error\n\n\tcheckpoint := NewMemoryManagerCheckpoint()\n\tif err = sc.checkpointManager.GetCheckpoint(sc.checkpointName, checkpoint); err != nil {\n\t\tif err == errors.ErrCheckpointNotFound {\n\t\t\treturn sc.storeState()\n\t\t}\n\t\treturn err\n\t}\n\n\tif sc.policyName != checkpoint.PolicyName {\n\t\treturn fmt.Errorf(\"[memorymanager] configured policy %q differs from state checkpoint policy %q\", sc.policyName, checkpoint.PolicyName)\n\t}\n\n\tsc.cache.SetMachineState(checkpoint.MachineState)\n\tsc.cache.SetMemoryAssignments(checkpoint.Entries)\n\n\tklog.V(2).InfoS(\"State checkpoint: restored state from checkpoint\")\n\n\treturn nil\n}","line":{"from":61,"to":85}} {"id":100006112,"name":"storeState","signature":"func (sc *stateCheckpoint) storeState() error","file":"pkg/kubelet/cm/memorymanager/state/state_checkpoint.go","code":"// saves state to a checkpoint, caller is responsible for locking\nfunc (sc *stateCheckpoint) storeState() error {\n\tcheckpoint := NewMemoryManagerCheckpoint()\n\tcheckpoint.PolicyName = sc.policyName\n\tcheckpoint.MachineState = sc.cache.GetMachineState()\n\tcheckpoint.Entries = sc.cache.GetMemoryAssignments()\n\n\terr := sc.checkpointManager.CreateCheckpoint(sc.checkpointName, checkpoint)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Could not save checkpoint\")\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":87,"to":100}} {"id":100006113,"name":"GetMachineState","signature":"func (sc *stateCheckpoint) GetMachineState() NUMANodeMap","file":"pkg/kubelet/cm/memorymanager/state/state_checkpoint.go","code":"// GetMemoryState returns Memory Map stored in the State\nfunc (sc *stateCheckpoint) GetMachineState() NUMANodeMap {\n\tsc.RLock()\n\tdefer sc.RUnlock()\n\n\treturn sc.cache.GetMachineState()\n}","line":{"from":102,"to":108}} {"id":100006114,"name":"GetMemoryBlocks","signature":"func (sc *stateCheckpoint) GetMemoryBlocks(podUID string, containerName string) []Block","file":"pkg/kubelet/cm/memorymanager/state/state_checkpoint.go","code":"// GetMemoryBlocks returns memory assignments of a container\nfunc (sc *stateCheckpoint) GetMemoryBlocks(podUID string, containerName string) []Block {\n\tsc.RLock()\n\tdefer sc.RUnlock()\n\n\treturn sc.cache.GetMemoryBlocks(podUID, containerName)\n}","line":{"from":110,"to":116}} {"id":100006115,"name":"GetMemoryAssignments","signature":"func (sc *stateCheckpoint) GetMemoryAssignments() ContainerMemoryAssignments","file":"pkg/kubelet/cm/memorymanager/state/state_checkpoint.go","code":"// GetMemoryAssignments returns ContainerMemoryAssignments\nfunc (sc *stateCheckpoint) GetMemoryAssignments() ContainerMemoryAssignments {\n\tsc.RLock()\n\tdefer sc.RUnlock()\n\n\treturn sc.cache.GetMemoryAssignments()\n}","line":{"from":118,"to":124}} {"id":100006116,"name":"SetMachineState","signature":"func (sc *stateCheckpoint) SetMachineState(memoryMap NUMANodeMap)","file":"pkg/kubelet/cm/memorymanager/state/state_checkpoint.go","code":"// SetMachineState stores NUMANodeMap in State\nfunc (sc *stateCheckpoint) SetMachineState(memoryMap NUMANodeMap) {\n\tsc.Lock()\n\tdefer sc.Unlock()\n\n\tsc.cache.SetMachineState(memoryMap)\n\terr := sc.storeState()\n\tif err != nil {\n\t\tklog.InfoS(\"Store state to checkpoint error\", \"err\", err)\n\t}\n}","line":{"from":126,"to":136}} {"id":100006117,"name":"SetMemoryBlocks","signature":"func (sc *stateCheckpoint) SetMemoryBlocks(podUID string, containerName string, blocks []Block)","file":"pkg/kubelet/cm/memorymanager/state/state_checkpoint.go","code":"// SetMemoryBlocks stores memory assignments of container\nfunc (sc *stateCheckpoint) SetMemoryBlocks(podUID string, containerName string, blocks []Block) {\n\tsc.Lock()\n\tdefer sc.Unlock()\n\n\tsc.cache.SetMemoryBlocks(podUID, containerName, blocks)\n\terr := sc.storeState()\n\tif err != nil {\n\t\tklog.InfoS(\"Store state to checkpoint error\", \"err\", err)\n\t}\n}","line":{"from":138,"to":148}} {"id":100006118,"name":"SetMemoryAssignments","signature":"func (sc *stateCheckpoint) SetMemoryAssignments(assignments ContainerMemoryAssignments)","file":"pkg/kubelet/cm/memorymanager/state/state_checkpoint.go","code":"// SetMemoryAssignments sets ContainerMemoryAssignments by using the passed parameter\nfunc (sc *stateCheckpoint) SetMemoryAssignments(assignments ContainerMemoryAssignments) {\n\tsc.Lock()\n\tdefer sc.Unlock()\n\n\tsc.cache.SetMemoryAssignments(assignments)\n\terr := sc.storeState()\n\tif err != nil {\n\t\tklog.InfoS(\"Store state to checkpoint error\", \"err\", err)\n\t}\n}","line":{"from":150,"to":160}} {"id":100006119,"name":"Delete","signature":"func (sc *stateCheckpoint) Delete(podUID string, containerName string)","file":"pkg/kubelet/cm/memorymanager/state/state_checkpoint.go","code":"// Delete deletes corresponding Blocks from ContainerMemoryAssignments\nfunc (sc *stateCheckpoint) Delete(podUID string, containerName string) {\n\tsc.Lock()\n\tdefer sc.Unlock()\n\n\tsc.cache.Delete(podUID, containerName)\n\terr := sc.storeState()\n\tif err != nil {\n\t\tklog.InfoS(\"Store state to checkpoint error\", \"err\", err)\n\t}\n}","line":{"from":162,"to":172}} {"id":100006120,"name":"ClearState","signature":"func (sc *stateCheckpoint) ClearState()","file":"pkg/kubelet/cm/memorymanager/state/state_checkpoint.go","code":"// ClearState clears machineState and ContainerMemoryAssignments\nfunc (sc *stateCheckpoint) ClearState() {\n\tsc.Lock()\n\tdefer sc.Unlock()\n\n\tsc.cache.ClearState()\n\terr := sc.storeState()\n\tif err != nil {\n\t\tklog.InfoS(\"Store state to checkpoint error\", \"err\", err)\n\t}\n}","line":{"from":174,"to":184}} {"id":100006121,"name":"NewMemoryState","signature":"func NewMemoryState() State","file":"pkg/kubelet/cm/memorymanager/state/state_mem.go","code":"// NewMemoryState creates new State for keeping track of cpu/pod assignment\nfunc NewMemoryState() State {\n\tklog.InfoS(\"Initializing new in-memory state store\")\n\treturn \u0026stateMemory{\n\t\tassignments: ContainerMemoryAssignments{},\n\t\tmachineState: NUMANodeMap{},\n\t}\n}","line":{"from":33,"to":40}} {"id":100006122,"name":"GetMachineState","signature":"func (s *stateMemory) GetMachineState() NUMANodeMap","file":"pkg/kubelet/cm/memorymanager/state/state_mem.go","code":"// GetMemoryState returns Memory Map stored in the State\nfunc (s *stateMemory) GetMachineState() NUMANodeMap {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\treturn s.machineState.Clone()\n}","line":{"from":42,"to":48}} {"id":100006123,"name":"GetMemoryBlocks","signature":"func (s *stateMemory) GetMemoryBlocks(podUID string, containerName string) []Block","file":"pkg/kubelet/cm/memorymanager/state/state_mem.go","code":"// GetMemoryBlocks returns memory assignments of a container\nfunc (s *stateMemory) GetMemoryBlocks(podUID string, containerName string) []Block {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tif res, ok := s.assignments[podUID][containerName]; ok {\n\t\treturn append([]Block{}, res...)\n\t}\n\treturn nil\n}","line":{"from":50,"to":59}} {"id":100006124,"name":"GetMemoryAssignments","signature":"func (s *stateMemory) GetMemoryAssignments() ContainerMemoryAssignments","file":"pkg/kubelet/cm/memorymanager/state/state_mem.go","code":"// GetMemoryAssignments returns ContainerMemoryAssignments\nfunc (s *stateMemory) GetMemoryAssignments() ContainerMemoryAssignments {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\treturn s.assignments.Clone()\n}","line":{"from":61,"to":67}} {"id":100006125,"name":"SetMachineState","signature":"func (s *stateMemory) SetMachineState(nodeMap NUMANodeMap)","file":"pkg/kubelet/cm/memorymanager/state/state_mem.go","code":"// SetMachineState stores NUMANodeMap in State\nfunc (s *stateMemory) SetMachineState(nodeMap NUMANodeMap) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\ts.machineState = nodeMap.Clone()\n\tklog.InfoS(\"Updated machine memory state\")\n}","line":{"from":69,"to":76}} {"id":100006126,"name":"SetMemoryBlocks","signature":"func (s *stateMemory) SetMemoryBlocks(podUID string, containerName string, blocks []Block)","file":"pkg/kubelet/cm/memorymanager/state/state_mem.go","code":"// SetMemoryBlocks stores memory assignments of container\nfunc (s *stateMemory) SetMemoryBlocks(podUID string, containerName string, blocks []Block) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tif _, ok := s.assignments[podUID]; !ok {\n\t\ts.assignments[podUID] = map[string][]Block{}\n\t}\n\n\ts.assignments[podUID][containerName] = append([]Block{}, blocks...)\n\tklog.InfoS(\"Updated memory state\", \"podUID\", podUID, \"containerName\", containerName)\n}","line":{"from":78,"to":89}} {"id":100006127,"name":"SetMemoryAssignments","signature":"func (s *stateMemory) SetMemoryAssignments(assignments ContainerMemoryAssignments)","file":"pkg/kubelet/cm/memorymanager/state/state_mem.go","code":"// SetMemoryAssignments sets ContainerMemoryAssignments by using the passed parameter\nfunc (s *stateMemory) SetMemoryAssignments(assignments ContainerMemoryAssignments) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\ts.assignments = assignments.Clone()\n}","line":{"from":91,"to":97}} {"id":100006128,"name":"Delete","signature":"func (s *stateMemory) Delete(podUID string, containerName string)","file":"pkg/kubelet/cm/memorymanager/state/state_mem.go","code":"// Delete deletes corresponding Blocks from ContainerMemoryAssignments\nfunc (s *stateMemory) Delete(podUID string, containerName string) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tif _, ok := s.assignments[podUID]; !ok {\n\t\treturn\n\t}\n\n\tdelete(s.assignments[podUID], containerName)\n\tif len(s.assignments[podUID]) == 0 {\n\t\tdelete(s.assignments, podUID)\n\t}\n\tklog.V(2).InfoS(\"Deleted memory assignment\", \"podUID\", podUID, \"containerName\", containerName)\n}","line":{"from":99,"to":113}} {"id":100006129,"name":"ClearState","signature":"func (s *stateMemory) ClearState()","file":"pkg/kubelet/cm/memorymanager/state/state_mem.go","code":"// ClearState clears machineState and ContainerMemoryAssignments\nfunc (s *stateMemory) ClearState() {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\ts.machineState = NUMANodeMap{}\n\ts.assignments = make(ContainerMemoryAssignments)\n\tklog.V(2).InfoS(\"Cleared state\")\n}","line":{"from":115,"to":123}} {"id":100006130,"name":"createNodeAllocatableCgroups","signature":"func (cm *containerManagerImpl) createNodeAllocatableCgroups() error","file":"pkg/kubelet/cm/node_container_manager_linux.go","code":"// createNodeAllocatableCgroups creates Node Allocatable Cgroup when CgroupsPerQOS flag is specified as true\nfunc (cm *containerManagerImpl) createNodeAllocatableCgroups() error {\n\tnodeAllocatable := cm.internalCapacity\n\t// Use Node Allocatable limits instead of capacity if the user requested enforcing node allocatable.\n\tnc := cm.NodeConfig.NodeAllocatableConfig\n\tif cm.CgroupsPerQOS \u0026\u0026 nc.EnforceNodeAllocatable.Has(kubetypes.NodeAllocatableEnforcementKey) {\n\t\tnodeAllocatable = cm.getNodeAllocatableInternalAbsolute()\n\t}\n\n\tcgroupConfig := \u0026CgroupConfig{\n\t\tName: cm.cgroupRoot,\n\t\t// The default limits for cpu shares can be very low which can lead to CPU starvation for pods.\n\t\tResourceParameters: getCgroupConfig(nodeAllocatable),\n\t}\n\tif cm.cgroupManager.Exists(cgroupConfig.Name) {\n\t\treturn nil\n\t}\n\tif err := cm.cgroupManager.Create(cgroupConfig); err != nil {\n\t\tklog.ErrorS(err, \"Failed to create cgroup\", \"cgroupName\", cm.cgroupRoot)\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":43,"to":65}} {"id":100006131,"name":"enforceNodeAllocatableCgroups","signature":"func (cm *containerManagerImpl) enforceNodeAllocatableCgroups() error","file":"pkg/kubelet/cm/node_container_manager_linux.go","code":"// enforceNodeAllocatableCgroups enforce Node Allocatable Cgroup settings.\nfunc (cm *containerManagerImpl) enforceNodeAllocatableCgroups() error {\n\tnc := cm.NodeConfig.NodeAllocatableConfig\n\n\t// We need to update limits on node allocatable cgroup no matter what because\n\t// default cpu shares on cgroups are low and can cause cpu starvation.\n\tnodeAllocatable := cm.internalCapacity\n\t// Use Node Allocatable limits instead of capacity if the user requested enforcing node allocatable.\n\tif cm.CgroupsPerQOS \u0026\u0026 nc.EnforceNodeAllocatable.Has(kubetypes.NodeAllocatableEnforcementKey) {\n\t\tnodeAllocatable = cm.getNodeAllocatableInternalAbsolute()\n\t}\n\n\tklog.V(4).InfoS(\"Attempting to enforce Node Allocatable\", \"config\", nc)\n\n\tcgroupConfig := \u0026CgroupConfig{\n\t\tName: cm.cgroupRoot,\n\t\tResourceParameters: getCgroupConfig(nodeAllocatable),\n\t}\n\n\t// Using ObjectReference for events as the node maybe not cached; refer to #42701 for detail.\n\tnodeRef := \u0026v1.ObjectReference{\n\t\tKind: \"Node\",\n\t\tName: cm.nodeInfo.Name,\n\t\tUID: types.UID(cm.nodeInfo.Name),\n\t\tNamespace: \"\",\n\t}\n\n\t// If Node Allocatable is enforced on a node that has not been drained or is updated on an existing node to a lower value,\n\t// existing memory usage across pods might be higher than current Node Allocatable Memory Limits.\n\t// Pod Evictions are expected to bring down memory usage to below Node Allocatable limits.\n\t// Until evictions happen retry cgroup updates.\n\t// Update limits on non root cgroup-root to be safe since the default limits for CPU can be too low.\n\t// Check if cgroupRoot is set to a non-empty value (empty would be the root container)\n\tif len(cm.cgroupRoot) \u003e 0 {\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\terr := cm.cgroupManager.Update(cgroupConfig)\n\t\t\t\tif err == nil {\n\t\t\t\t\tcm.recorder.Event(nodeRef, v1.EventTypeNormal, events.SuccessfulNodeAllocatableEnforcement, \"Updated Node Allocatable limit across pods\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tmessage := fmt.Sprintf(\"Failed to update Node Allocatable Limits %q: %v\", cm.cgroupRoot, err)\n\t\t\t\tcm.recorder.Event(nodeRef, v1.EventTypeWarning, events.FailedNodeAllocatableEnforcement, message)\n\t\t\t\ttime.Sleep(time.Minute)\n\t\t\t}\n\t\t}()\n\t}\n\t// Now apply kube reserved and system reserved limits if required.\n\tif nc.EnforceNodeAllocatable.Has(kubetypes.SystemReservedEnforcementKey) {\n\t\tklog.V(2).InfoS(\"Enforcing system reserved on cgroup\", \"cgroupName\", nc.SystemReservedCgroupName, \"limits\", nc.SystemReserved)\n\t\tif err := enforceExistingCgroup(cm.cgroupManager, cm.cgroupManager.CgroupName(nc.SystemReservedCgroupName), nc.SystemReserved); err != nil {\n\t\t\tmessage := fmt.Sprintf(\"Failed to enforce System Reserved Cgroup Limits on %q: %v\", nc.SystemReservedCgroupName, err)\n\t\t\tcm.recorder.Event(nodeRef, v1.EventTypeWarning, events.FailedNodeAllocatableEnforcement, message)\n\t\t\treturn fmt.Errorf(message)\n\t\t}\n\t\tcm.recorder.Eventf(nodeRef, v1.EventTypeNormal, events.SuccessfulNodeAllocatableEnforcement, \"Updated limits on system reserved cgroup %v\", nc.SystemReservedCgroupName)\n\t}\n\tif nc.EnforceNodeAllocatable.Has(kubetypes.KubeReservedEnforcementKey) {\n\t\tklog.V(2).InfoS(\"Enforcing kube reserved on cgroup\", \"cgroupName\", nc.KubeReservedCgroupName, \"limits\", nc.KubeReserved)\n\t\tif err := enforceExistingCgroup(cm.cgroupManager, cm.cgroupManager.CgroupName(nc.KubeReservedCgroupName), nc.KubeReserved); err != nil {\n\t\t\tmessage := fmt.Sprintf(\"Failed to enforce Kube Reserved Cgroup Limits on %q: %v\", nc.KubeReservedCgroupName, err)\n\t\t\tcm.recorder.Event(nodeRef, v1.EventTypeWarning, events.FailedNodeAllocatableEnforcement, message)\n\t\t\treturn fmt.Errorf(message)\n\t\t}\n\t\tcm.recorder.Eventf(nodeRef, v1.EventTypeNormal, events.SuccessfulNodeAllocatableEnforcement, \"Updated limits on kube reserved cgroup %v\", nc.KubeReservedCgroupName)\n\t}\n\treturn nil\n}","line":{"from":67,"to":134}} {"id":100006132,"name":"enforceExistingCgroup","signature":"func enforceExistingCgroup(cgroupManager CgroupManager, cName CgroupName, rl v1.ResourceList) error","file":"pkg/kubelet/cm/node_container_manager_linux.go","code":"// enforceExistingCgroup updates the limits `rl` on existing cgroup `cName` using `cgroupManager` interface.\nfunc enforceExistingCgroup(cgroupManager CgroupManager, cName CgroupName, rl v1.ResourceList) error {\n\trp := getCgroupConfig(rl)\n\tif rp == nil {\n\t\treturn fmt.Errorf(\"%q cgroup is not configured properly\", cName)\n\t}\n\n\t// Enforce MemoryQoS for cgroups of kube-reserved/system-reserved. For more information,\n\t// see https://github.com/kubernetes/enhancements/tree/master/keps/sig-node/2570-memory-qos\n\tif utilfeature.DefaultFeatureGate.Enabled(kubefeatures.MemoryQoS) {\n\t\tif rp.Memory != nil {\n\t\t\tif rp.Unified == nil {\n\t\t\t\trp.Unified = make(map[string]string)\n\t\t\t}\n\t\t\trp.Unified[MemoryMin] = strconv.FormatInt(*rp.Memory, 10)\n\t\t}\n\t}\n\n\tcgroupConfig := \u0026CgroupConfig{\n\t\tName: cName,\n\t\tResourceParameters: rp,\n\t}\n\tklog.V(4).InfoS(\"Enforcing limits on cgroup\", \"cgroupName\", cName, \"cpuShares\", cgroupConfig.ResourceParameters.CPUShares, \"memory\", cgroupConfig.ResourceParameters.Memory, \"pidsLimit\", cgroupConfig.ResourceParameters.PidsLimit)\n\tif err := cgroupManager.Validate(cgroupConfig.Name); err != nil {\n\t\treturn err\n\t}\n\tif err := cgroupManager.Update(cgroupConfig); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":136,"to":166}} {"id":100006133,"name":"getCgroupConfig","signature":"func getCgroupConfig(rl v1.ResourceList) *ResourceConfig","file":"pkg/kubelet/cm/node_container_manager_linux.go","code":"// getCgroupConfig returns a ResourceConfig object that can be used to create or update cgroups via CgroupManager interface.\nfunc getCgroupConfig(rl v1.ResourceList) *ResourceConfig {\n\t// TODO(vishh): Set CPU Quota if necessary.\n\tif rl == nil {\n\t\treturn nil\n\t}\n\tvar rc ResourceConfig\n\tif q, exists := rl[v1.ResourceMemory]; exists {\n\t\t// Memory is defined in bytes.\n\t\tval := q.Value()\n\t\trc.Memory = \u0026val\n\t}\n\tif q, exists := rl[v1.ResourceCPU]; exists {\n\t\t// CPU is defined in milli-cores.\n\t\tval := MilliCPUToShares(q.MilliValue())\n\t\trc.CPUShares = \u0026val\n\t}\n\tif q, exists := rl[pidlimit.PIDs]; exists {\n\t\tval := q.Value()\n\t\trc.PidsLimit = \u0026val\n\t}\n\trc.HugePageLimit = HugePageLimits(rl)\n\n\treturn \u0026rc\n}","line":{"from":168,"to":192}} {"id":100006134,"name":"GetNodeAllocatableAbsolute","signature":"func (cm *containerManagerImpl) GetNodeAllocatableAbsolute() v1.ResourceList","file":"pkg/kubelet/cm/node_container_manager_linux.go","code":"// GetNodeAllocatableAbsolute returns the absolute value of Node Allocatable which is primarily useful for enforcement.\n// Note that not all resources that are available on the node are included in the returned list of resources.\n// Returns a ResourceList.\nfunc (cm *containerManagerImpl) GetNodeAllocatableAbsolute() v1.ResourceList {\n\treturn cm.getNodeAllocatableAbsoluteImpl(cm.capacity)\n}","line":{"from":194,"to":199}} {"id":100006135,"name":"getNodeAllocatableAbsoluteImpl","signature":"func (cm *containerManagerImpl) getNodeAllocatableAbsoluteImpl(capacity v1.ResourceList) v1.ResourceList","file":"pkg/kubelet/cm/node_container_manager_linux.go","code":"func (cm *containerManagerImpl) getNodeAllocatableAbsoluteImpl(capacity v1.ResourceList) v1.ResourceList {\n\tresult := make(v1.ResourceList)\n\tfor k, v := range capacity {\n\t\tvalue := v.DeepCopy()\n\t\tif cm.NodeConfig.SystemReserved != nil {\n\t\t\tvalue.Sub(cm.NodeConfig.SystemReserved[k])\n\t\t}\n\t\tif cm.NodeConfig.KubeReserved != nil {\n\t\t\tvalue.Sub(cm.NodeConfig.KubeReserved[k])\n\t\t}\n\t\tif value.Sign() \u003c 0 {\n\t\t\t// Negative Allocatable resources don't make sense.\n\t\t\tvalue.Set(0)\n\t\t}\n\t\tresult[k] = value\n\t}\n\treturn result\n}","line":{"from":201,"to":218}} {"id":100006136,"name":"getNodeAllocatableInternalAbsolute","signature":"func (cm *containerManagerImpl) getNodeAllocatableInternalAbsolute() v1.ResourceList","file":"pkg/kubelet/cm/node_container_manager_linux.go","code":"// getNodeAllocatableInternalAbsolute is similar to getNodeAllocatableAbsolute except that\n// it also includes internal resources (currently process IDs). It is intended for setting\n// up top level cgroups only.\nfunc (cm *containerManagerImpl) getNodeAllocatableInternalAbsolute() v1.ResourceList {\n\treturn cm.getNodeAllocatableAbsoluteImpl(cm.internalCapacity)\n}","line":{"from":220,"to":225}} {"id":100006137,"name":"GetNodeAllocatableReservation","signature":"func (cm *containerManagerImpl) GetNodeAllocatableReservation() v1.ResourceList","file":"pkg/kubelet/cm/node_container_manager_linux.go","code":"// GetNodeAllocatableReservation returns amount of compute or storage resource that have to be reserved on this node from scheduling.\nfunc (cm *containerManagerImpl) GetNodeAllocatableReservation() v1.ResourceList {\n\tevictionReservation := hardEvictionReservation(cm.HardEvictionThresholds, cm.capacity)\n\tresult := make(v1.ResourceList)\n\tfor k := range cm.capacity {\n\t\tvalue := resource.NewQuantity(0, resource.DecimalSI)\n\t\tif cm.NodeConfig.SystemReserved != nil {\n\t\t\tvalue.Add(cm.NodeConfig.SystemReserved[k])\n\t\t}\n\t\tif cm.NodeConfig.KubeReserved != nil {\n\t\t\tvalue.Add(cm.NodeConfig.KubeReserved[k])\n\t\t}\n\t\tif evictionReservation != nil {\n\t\t\tvalue.Add(evictionReservation[k])\n\t\t}\n\t\tif !value.IsZero() {\n\t\t\tresult[k] = *value\n\t\t}\n\t}\n\treturn result\n}","line":{"from":227,"to":247}} {"id":100006138,"name":"validateNodeAllocatable","signature":"func (cm *containerManagerImpl) validateNodeAllocatable() error","file":"pkg/kubelet/cm/node_container_manager_linux.go","code":"// validateNodeAllocatable ensures that the user specified Node Allocatable Configuration doesn't reserve more than the node capacity.\n// Returns error if the configuration is invalid, nil otherwise.\nfunc (cm *containerManagerImpl) validateNodeAllocatable() error {\n\tvar errors []string\n\tnar := cm.GetNodeAllocatableReservation()\n\tfor k, v := range nar {\n\t\tvalue := cm.capacity[k].DeepCopy()\n\t\tvalue.Sub(v)\n\n\t\tif value.Sign() \u003c 0 {\n\t\t\terrors = append(errors, fmt.Sprintf(\"Resource %q has an allocatable of %v, capacity of %v\", k, v, value))\n\t\t}\n\t}\n\n\tif len(errors) \u003e 0 {\n\t\treturn fmt.Errorf(\"invalid Node Allocatable configuration. %s\", strings.Join(errors, \" \"))\n\t}\n\treturn nil\n}","line":{"from":249,"to":267}} {"id":100006139,"name":"Exists","signature":"func (m *podContainerManagerImpl) Exists(pod *v1.Pod) bool","file":"pkg/kubelet/cm/pod_container_manager_linux.go","code":"// Exists checks if the pod's cgroup already exists\nfunc (m *podContainerManagerImpl) Exists(pod *v1.Pod) bool {\n\tpodContainerName, _ := m.GetPodContainerName(pod)\n\treturn m.cgroupManager.Exists(podContainerName)\n}","line":{"from":63,"to":67}} {"id":100006140,"name":"EnsureExists","signature":"func (m *podContainerManagerImpl) EnsureExists(pod *v1.Pod) error","file":"pkg/kubelet/cm/pod_container_manager_linux.go","code":"// EnsureExists takes a pod as argument and makes sure that\n// pod cgroup exists if qos cgroup hierarchy flag is enabled.\n// If the pod level container doesn't already exist it is created.\nfunc (m *podContainerManagerImpl) EnsureExists(pod *v1.Pod) error {\n\t// check if container already exist\n\talreadyExists := m.Exists(pod)\n\tif !alreadyExists {\n\t\tenforceMemoryQoS := false\n\t\tif utilfeature.DefaultFeatureGate.Enabled(kubefeatures.MemoryQoS) \u0026\u0026\n\t\t\tlibcontainercgroups.IsCgroup2UnifiedMode() {\n\t\t\tenforceMemoryQoS = true\n\t\t}\n\t\t// Create the pod container\n\t\tpodContainerName, _ := m.GetPodContainerName(pod)\n\t\tcontainerConfig := \u0026CgroupConfig{\n\t\t\tName: podContainerName,\n\t\t\tResourceParameters: ResourceConfigForPod(pod, m.enforceCPULimits, m.cpuCFSQuotaPeriod, enforceMemoryQoS),\n\t\t}\n\t\tif m.podPidsLimit \u003e 0 {\n\t\t\tcontainerConfig.ResourceParameters.PidsLimit = \u0026m.podPidsLimit\n\t\t}\n\t\tif enforceMemoryQoS {\n\t\t\tklog.V(4).InfoS(\"MemoryQoS config for pod\", \"pod\", klog.KObj(pod), \"unified\", containerConfig.ResourceParameters.Unified)\n\t\t}\n\t\tif err := m.cgroupManager.Create(containerConfig); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create container for %v : %v\", podContainerName, err)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":69,"to":98}} {"id":100006141,"name":"GetPodContainerName","signature":"func (m *podContainerManagerImpl) GetPodContainerName(pod *v1.Pod) (CgroupName, string)","file":"pkg/kubelet/cm/pod_container_manager_linux.go","code":"// GetPodContainerName returns the CgroupName identifier, and its literal cgroupfs form on the host.\nfunc (m *podContainerManagerImpl) GetPodContainerName(pod *v1.Pod) (CgroupName, string) {\n\tpodQOS := v1qos.GetPodQOS(pod)\n\t// Get the parent QOS container name\n\tvar parentContainer CgroupName\n\tswitch podQOS {\n\tcase v1.PodQOSGuaranteed:\n\t\tparentContainer = m.qosContainersInfo.Guaranteed\n\tcase v1.PodQOSBurstable:\n\t\tparentContainer = m.qosContainersInfo.Burstable\n\tcase v1.PodQOSBestEffort:\n\t\tparentContainer = m.qosContainersInfo.BestEffort\n\t}\n\tpodContainer := GetPodCgroupNameSuffix(pod.UID)\n\n\t// Get the absolute path of the cgroup\n\tcgroupName := NewCgroupName(parentContainer, podContainer)\n\t// Get the literal cgroupfs name\n\tcgroupfsName := m.cgroupManager.Name(cgroupName)\n\n\treturn cgroupName, cgroupfsName\n}","line":{"from":100,"to":121}} {"id":100006142,"name":"GetPodCgroupMemoryUsage","signature":"func (m *podContainerManagerImpl) GetPodCgroupMemoryUsage(pod *v1.Pod) (uint64, error)","file":"pkg/kubelet/cm/pod_container_manager_linux.go","code":"func (m *podContainerManagerImpl) GetPodCgroupMemoryUsage(pod *v1.Pod) (uint64, error) {\n\tpodCgroupName, _ := m.GetPodContainerName(pod)\n\tmemUsage, err := m.cgroupManager.MemoryUsage(podCgroupName)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn uint64(memUsage), nil\n}","line":{"from":123,"to":130}} {"id":100006143,"name":"GetPodCgroupConfig","signature":"func (m *podContainerManagerImpl) GetPodCgroupConfig(pod *v1.Pod, resource v1.ResourceName) (*ResourceConfig, error)","file":"pkg/kubelet/cm/pod_container_manager_linux.go","code":"func (m *podContainerManagerImpl) GetPodCgroupConfig(pod *v1.Pod, resource v1.ResourceName) (*ResourceConfig, error) {\n\tpodCgroupName, _ := m.GetPodContainerName(pod)\n\treturn m.cgroupManager.GetCgroupConfig(podCgroupName, resource)\n}","line":{"from":132,"to":135}} {"id":100006144,"name":"SetPodCgroupConfig","signature":"func (m *podContainerManagerImpl) SetPodCgroupConfig(pod *v1.Pod, resource v1.ResourceName, resourceConfig *ResourceConfig) error","file":"pkg/kubelet/cm/pod_container_manager_linux.go","code":"func (m *podContainerManagerImpl) SetPodCgroupConfig(pod *v1.Pod, resource v1.ResourceName, resourceConfig *ResourceConfig) error {\n\tpodCgroupName, _ := m.GetPodContainerName(pod)\n\treturn m.cgroupManager.SetCgroupConfig(podCgroupName, resource, resourceConfig)\n}","line":{"from":137,"to":140}} {"id":100006145,"name":"killOnePid","signature":"func (m *podContainerManagerImpl) killOnePid(pid int) error","file":"pkg/kubelet/cm/pod_container_manager_linux.go","code":"// Kill one process ID\nfunc (m *podContainerManagerImpl) killOnePid(pid int) error {\n\t// os.FindProcess never returns an error on POSIX\n\t// https://go-review.googlesource.com/c/go/+/19093\n\tp, _ := os.FindProcess(pid)\n\tif err := p.Kill(); err != nil {\n\t\t// If the process already exited, that's fine.\n\t\tif errors.Is(err, os.ErrProcessDone) {\n\t\t\tklog.V(3).InfoS(\"Process no longer exists\", \"pid\", pid)\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":142,"to":156}} {"id":100006146,"name":"tryKillingCgroupProcesses","signature":"func (m *podContainerManagerImpl) tryKillingCgroupProcesses(podCgroup CgroupName) error","file":"pkg/kubelet/cm/pod_container_manager_linux.go","code":"// Scan through the whole cgroup directory and kill all processes either\n// attached to the pod cgroup or to a container cgroup under the pod cgroup\nfunc (m *podContainerManagerImpl) tryKillingCgroupProcesses(podCgroup CgroupName) error {\n\tpidsToKill := m.cgroupManager.Pids(podCgroup)\n\t// No pids charged to the terminated pod cgroup return\n\tif len(pidsToKill) == 0 {\n\t\treturn nil\n\t}\n\n\tvar errlist []error\n\t// os.Kill often errors out,\n\t// We try killing all the pids multiple times\n\tremoved := map[int]bool{}\n\tfor i := 0; i \u003c 5; i++ {\n\t\tif i != 0 {\n\t\t\tklog.V(3).InfoS(\"Attempt failed to kill all unwanted process from cgroup, retrying\", \"attempt\", i, \"cgroupName\", podCgroup)\n\t\t}\n\t\terrlist = []error{}\n\t\tfor _, pid := range pidsToKill {\n\t\t\tif _, ok := removed[pid]; ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tklog.V(3).InfoS(\"Attempting to kill process from cgroup\", \"pid\", pid, \"cgroupName\", podCgroup)\n\t\t\tif err := m.killOnePid(pid); err != nil {\n\t\t\t\tklog.V(3).InfoS(\"Failed to kill process from cgroup\", \"pid\", pid, \"cgroupName\", podCgroup, \"err\", err)\n\t\t\t\terrlist = append(errlist, err)\n\t\t\t} else {\n\t\t\t\tremoved[pid] = true\n\t\t\t}\n\t\t}\n\t\tif len(errlist) == 0 {\n\t\t\tklog.V(3).InfoS(\"Successfully killed all unwanted processes from cgroup\", \"cgroupName\", podCgroup)\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn utilerrors.NewAggregate(errlist)\n}","line":{"from":158,"to":194}} {"id":100006147,"name":"Destroy","signature":"func (m *podContainerManagerImpl) Destroy(podCgroup CgroupName) error","file":"pkg/kubelet/cm/pod_container_manager_linux.go","code":"// Destroy destroys the pod container cgroup paths\nfunc (m *podContainerManagerImpl) Destroy(podCgroup CgroupName) error {\n\t// Try killing all the processes attached to the pod cgroup\n\tif err := m.tryKillingCgroupProcesses(podCgroup); err != nil {\n\t\tklog.InfoS(\"Failed to kill all the processes attached to cgroup\", \"cgroupName\", podCgroup, \"err\", err)\n\t\treturn fmt.Errorf(\"failed to kill all the processes attached to the %v cgroups : %v\", podCgroup, err)\n\t}\n\n\t// Now its safe to remove the pod's cgroup\n\tcontainerConfig := \u0026CgroupConfig{\n\t\tName: podCgroup,\n\t\tResourceParameters: \u0026ResourceConfig{},\n\t}\n\tif err := m.cgroupManager.Destroy(containerConfig); err != nil {\n\t\tklog.InfoS(\"Failed to delete cgroup paths\", \"cgroupName\", podCgroup, \"err\", err)\n\t\treturn fmt.Errorf(\"failed to delete cgroup paths for %v : %v\", podCgroup, err)\n\t}\n\treturn nil\n}","line":{"from":196,"to":214}} {"id":100006148,"name":"ReduceCPULimits","signature":"func (m *podContainerManagerImpl) ReduceCPULimits(podCgroup CgroupName) error","file":"pkg/kubelet/cm/pod_container_manager_linux.go","code":"// ReduceCPULimits reduces the CPU CFS values to the minimum amount of shares.\nfunc (m *podContainerManagerImpl) ReduceCPULimits(podCgroup CgroupName) error {\n\treturn m.cgroupManager.ReduceCPULimits(podCgroup)\n}","line":{"from":216,"to":219}} {"id":100006149,"name":"IsPodCgroup","signature":"func (m *podContainerManagerImpl) IsPodCgroup(cgroupfs string) (bool, types.UID)","file":"pkg/kubelet/cm/pod_container_manager_linux.go","code":"// IsPodCgroup returns true if the literal cgroupfs name corresponds to a pod\nfunc (m *podContainerManagerImpl) IsPodCgroup(cgroupfs string) (bool, types.UID) {\n\t// convert the literal cgroupfs form to the driver specific value\n\tcgroupName := m.cgroupManager.CgroupName(cgroupfs)\n\tqosContainersList := [3]CgroupName{m.qosContainersInfo.BestEffort, m.qosContainersInfo.Burstable, m.qosContainersInfo.Guaranteed}\n\tbasePath := \"\"\n\tfor _, qosContainerName := range qosContainersList {\n\t\t// a pod cgroup is a direct child of a qos node, so check if its a match\n\t\tif len(cgroupName) == len(qosContainerName)+1 {\n\t\t\tbasePath = cgroupName[len(qosContainerName)]\n\t\t}\n\t}\n\tif basePath == \"\" {\n\t\treturn false, types.UID(\"\")\n\t}\n\tif !strings.HasPrefix(basePath, podCgroupNamePrefix) {\n\t\treturn false, types.UID(\"\")\n\t}\n\tparts := strings.Split(basePath, podCgroupNamePrefix)\n\tif len(parts) != 2 {\n\t\treturn false, types.UID(\"\")\n\t}\n\treturn true, types.UID(parts[1])\n}","line":{"from":221,"to":244}} {"id":100006150,"name":"GetAllPodsFromCgroups","signature":"func (m *podContainerManagerImpl) GetAllPodsFromCgroups() (map[types.UID]CgroupName, error)","file":"pkg/kubelet/cm/pod_container_manager_linux.go","code":"// GetAllPodsFromCgroups scans through all the subsystems of pod cgroups\n// Get list of pods whose cgroup still exist on the cgroup mounts\nfunc (m *podContainerManagerImpl) GetAllPodsFromCgroups() (map[types.UID]CgroupName, error) {\n\t// Map for storing all the found pods on the disk\n\tfoundPods := make(map[types.UID]CgroupName)\n\tqosContainersList := [3]CgroupName{m.qosContainersInfo.BestEffort, m.qosContainersInfo.Burstable, m.qosContainersInfo.Guaranteed}\n\t// Scan through all the subsystem mounts\n\t// and through each QoS cgroup directory for each subsystem mount\n\t// If a pod cgroup exists in even a single subsystem mount\n\t// we will attempt to delete it\n\tfor _, val := range m.subsystems.MountPoints {\n\t\tfor _, qosContainerName := range qosContainersList {\n\t\t\t// get the subsystems QoS cgroup absolute name\n\t\t\tqcConversion := m.cgroupManager.Name(qosContainerName)\n\t\t\tqc := path.Join(val, qcConversion)\n\t\t\tdirInfo, err := os.ReadDir(qc)\n\t\t\tif err != nil {\n\t\t\t\tif os.IsNotExist(err) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\treturn nil, fmt.Errorf(\"failed to read the cgroup directory %v : %v\", qc, err)\n\t\t\t}\n\t\t\tfor i := range dirInfo {\n\t\t\t\t// its not a directory, so continue on...\n\t\t\t\tif !dirInfo[i].IsDir() {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// convert the concrete cgroupfs name back to an internal identifier\n\t\t\t\t// this is needed to handle path conversion for systemd environments.\n\t\t\t\t// we pass the fully qualified path so decoding can work as expected\n\t\t\t\t// since systemd encodes the path in each segment.\n\t\t\t\tcgroupfsPath := path.Join(qcConversion, dirInfo[i].Name())\n\t\t\t\tinternalPath := m.cgroupManager.CgroupName(cgroupfsPath)\n\t\t\t\t// we only care about base segment of the converted path since that\n\t\t\t\t// is what we are reading currently to know if it is a pod or not.\n\t\t\t\tbasePath := internalPath[len(internalPath)-1]\n\t\t\t\tif !strings.Contains(basePath, podCgroupNamePrefix) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// we then split the name on the pod prefix to determine the uid\n\t\t\t\tparts := strings.Split(basePath, podCgroupNamePrefix)\n\t\t\t\t// the uid is missing, so we log the unexpected cgroup not of form pod\u003cuid\u003e\n\t\t\t\tif len(parts) != 2 {\n\t\t\t\t\tklog.InfoS(\"Pod cgroup manager ignored unexpected cgroup because it is not a pod\", \"path\", cgroupfsPath)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tpodUID := parts[1]\n\t\t\t\tfoundPods[types.UID(podUID)] = internalPath\n\t\t\t}\n\t\t}\n\t}\n\treturn foundPods, nil\n}","line":{"from":246,"to":298}} {"id":100006151,"name":"Exists","signature":"func (m *podContainerManagerNoop) Exists(_ *v1.Pod) bool","file":"pkg/kubelet/cm/pod_container_manager_linux.go","code":"func (m *podContainerManagerNoop) Exists(_ *v1.Pod) bool {\n\treturn true\n}","line":{"from":312,"to":314}} {"id":100006152,"name":"EnsureExists","signature":"func (m *podContainerManagerNoop) EnsureExists(_ *v1.Pod) error","file":"pkg/kubelet/cm/pod_container_manager_linux.go","code":"func (m *podContainerManagerNoop) EnsureExists(_ *v1.Pod) error {\n\treturn nil\n}","line":{"from":316,"to":318}} {"id":100006153,"name":"GetPodContainerName","signature":"func (m *podContainerManagerNoop) GetPodContainerName(_ *v1.Pod) (CgroupName, string)","file":"pkg/kubelet/cm/pod_container_manager_linux.go","code":"func (m *podContainerManagerNoop) GetPodContainerName(_ *v1.Pod) (CgroupName, string) {\n\treturn m.cgroupRoot, \"\"\n}","line":{"from":320,"to":322}} {"id":100006154,"name":"GetPodContainerNameForDriver","signature":"func (m *podContainerManagerNoop) GetPodContainerNameForDriver(_ *v1.Pod) string","file":"pkg/kubelet/cm/pod_container_manager_linux.go","code":"func (m *podContainerManagerNoop) GetPodContainerNameForDriver(_ *v1.Pod) string {\n\treturn \"\"\n}","line":{"from":324,"to":326}} {"id":100006155,"name":"Destroy","signature":"func (m *podContainerManagerNoop) Destroy(_ CgroupName) error","file":"pkg/kubelet/cm/pod_container_manager_linux.go","code":"// Destroy destroys the pod container cgroup paths\nfunc (m *podContainerManagerNoop) Destroy(_ CgroupName) error {\n\treturn nil\n}","line":{"from":328,"to":331}} {"id":100006156,"name":"ReduceCPULimits","signature":"func (m *podContainerManagerNoop) ReduceCPULimits(_ CgroupName) error","file":"pkg/kubelet/cm/pod_container_manager_linux.go","code":"func (m *podContainerManagerNoop) ReduceCPULimits(_ CgroupName) error {\n\treturn nil\n}","line":{"from":333,"to":335}} {"id":100006157,"name":"GetAllPodsFromCgroups","signature":"func (m *podContainerManagerNoop) GetAllPodsFromCgroups() (map[types.UID]CgroupName, error)","file":"pkg/kubelet/cm/pod_container_manager_linux.go","code":"func (m *podContainerManagerNoop) GetAllPodsFromCgroups() (map[types.UID]CgroupName, error) {\n\treturn nil, nil\n}","line":{"from":337,"to":339}} {"id":100006158,"name":"IsPodCgroup","signature":"func (m *podContainerManagerNoop) IsPodCgroup(cgroupfs string) (bool, types.UID)","file":"pkg/kubelet/cm/pod_container_manager_linux.go","code":"func (m *podContainerManagerNoop) IsPodCgroup(cgroupfs string) (bool, types.UID) {\n\treturn false, types.UID(\"\")\n}","line":{"from":341,"to":343}} {"id":100006159,"name":"GetPodCgroupMemoryUsage","signature":"func (m *podContainerManagerNoop) GetPodCgroupMemoryUsage(_ *v1.Pod) (uint64, error)","file":"pkg/kubelet/cm/pod_container_manager_linux.go","code":"func (m *podContainerManagerNoop) GetPodCgroupMemoryUsage(_ *v1.Pod) (uint64, error) {\n\treturn 0, nil\n}","line":{"from":345,"to":347}} {"id":100006160,"name":"GetPodCgroupConfig","signature":"func (m *podContainerManagerNoop) GetPodCgroupConfig(_ *v1.Pod, _ v1.ResourceName) (*ResourceConfig, error)","file":"pkg/kubelet/cm/pod_container_manager_linux.go","code":"func (m *podContainerManagerNoop) GetPodCgroupConfig(_ *v1.Pod, _ v1.ResourceName) (*ResourceConfig, error) {\n\treturn nil, nil\n}","line":{"from":349,"to":351}} {"id":100006161,"name":"SetPodCgroupConfig","signature":"func (m *podContainerManagerNoop) SetPodCgroupConfig(_ *v1.Pod, _ v1.ResourceName, _ *ResourceConfig) error","file":"pkg/kubelet/cm/pod_container_manager_linux.go","code":"func (m *podContainerManagerNoop) SetPodCgroupConfig(_ *v1.Pod, _ v1.ResourceName, _ *ResourceConfig) error {\n\treturn nil\n}","line":{"from":353,"to":355}} {"id":100006162,"name":"Exists","signature":"func (m *podContainerManagerStub) Exists(_ *v1.Pod) bool","file":"pkg/kubelet/cm/pod_container_manager_stub.go","code":"func (m *podContainerManagerStub) Exists(_ *v1.Pod) bool {\n\treturn true\n}","line":{"from":29,"to":31}} {"id":100006163,"name":"EnsureExists","signature":"func (m *podContainerManagerStub) EnsureExists(_ *v1.Pod) error","file":"pkg/kubelet/cm/pod_container_manager_stub.go","code":"func (m *podContainerManagerStub) EnsureExists(_ *v1.Pod) error {\n\treturn nil\n}","line":{"from":33,"to":35}} {"id":100006164,"name":"GetPodContainerName","signature":"func (m *podContainerManagerStub) GetPodContainerName(_ *v1.Pod) (CgroupName, string)","file":"pkg/kubelet/cm/pod_container_manager_stub.go","code":"func (m *podContainerManagerStub) GetPodContainerName(_ *v1.Pod) (CgroupName, string) {\n\treturn nil, \"\"\n}","line":{"from":37,"to":39}} {"id":100006165,"name":"Destroy","signature":"func (m *podContainerManagerStub) Destroy(_ CgroupName) error","file":"pkg/kubelet/cm/pod_container_manager_stub.go","code":"func (m *podContainerManagerStub) Destroy(_ CgroupName) error {\n\treturn nil\n}","line":{"from":41,"to":43}} {"id":100006166,"name":"ReduceCPULimits","signature":"func (m *podContainerManagerStub) ReduceCPULimits(_ CgroupName) error","file":"pkg/kubelet/cm/pod_container_manager_stub.go","code":"func (m *podContainerManagerStub) ReduceCPULimits(_ CgroupName) error {\n\treturn nil\n}","line":{"from":45,"to":47}} {"id":100006167,"name":"GetAllPodsFromCgroups","signature":"func (m *podContainerManagerStub) GetAllPodsFromCgroups() (map[types.UID]CgroupName, error)","file":"pkg/kubelet/cm/pod_container_manager_stub.go","code":"func (m *podContainerManagerStub) GetAllPodsFromCgroups() (map[types.UID]CgroupName, error) {\n\treturn nil, nil\n}","line":{"from":49,"to":51}} {"id":100006168,"name":"IsPodCgroup","signature":"func (m *podContainerManagerStub) IsPodCgroup(cgroupfs string) (bool, types.UID)","file":"pkg/kubelet/cm/pod_container_manager_stub.go","code":"func (m *podContainerManagerStub) IsPodCgroup(cgroupfs string) (bool, types.UID) {\n\treturn false, types.UID(\"\")\n}","line":{"from":53,"to":55}} {"id":100006169,"name":"GetPodCgroupMemoryUsage","signature":"func (m *podContainerManagerStub) GetPodCgroupMemoryUsage(_ *v1.Pod) (uint64, error)","file":"pkg/kubelet/cm/pod_container_manager_stub.go","code":"func (m *podContainerManagerStub) GetPodCgroupMemoryUsage(_ *v1.Pod) (uint64, error) {\n\treturn 0, nil\n}","line":{"from":57,"to":59}} {"id":100006170,"name":"GetPodCgroupMemoryLimit","signature":"func (m *podContainerManagerStub) GetPodCgroupMemoryLimit(_ *v1.Pod) (uint64, error)","file":"pkg/kubelet/cm/pod_container_manager_stub.go","code":"func (m *podContainerManagerStub) GetPodCgroupMemoryLimit(_ *v1.Pod) (uint64, error) {\n\treturn 0, nil\n}","line":{"from":61,"to":63}} {"id":100006171,"name":"GetPodCgroupCpuLimit","signature":"func (m *podContainerManagerStub) GetPodCgroupCpuLimit(_ *v1.Pod) (int64, uint64, uint64, error)","file":"pkg/kubelet/cm/pod_container_manager_stub.go","code":"func (m *podContainerManagerStub) GetPodCgroupCpuLimit(_ *v1.Pod) (int64, uint64, uint64, error) {\n\treturn 0, 0, 0, nil\n}","line":{"from":65,"to":67}} {"id":100006172,"name":"SetPodCgroupMemoryLimit","signature":"func (m *podContainerManagerStub) SetPodCgroupMemoryLimit(_ *v1.Pod, _ int64) error","file":"pkg/kubelet/cm/pod_container_manager_stub.go","code":"func (m *podContainerManagerStub) SetPodCgroupMemoryLimit(_ *v1.Pod, _ int64) error {\n\treturn nil\n}","line":{"from":69,"to":71}} {"id":100006173,"name":"SetPodCgroupCpuLimit","signature":"func (m *podContainerManagerStub) SetPodCgroupCpuLimit(_ *v1.Pod, _ *int64, _, _ *uint64) error","file":"pkg/kubelet/cm/pod_container_manager_stub.go","code":"func (m *podContainerManagerStub) SetPodCgroupCpuLimit(_ *v1.Pod, _ *int64, _, _ *uint64) error {\n\treturn nil\n}","line":{"from":73,"to":75}} {"id":100006174,"name":"NewQOSContainerManager","signature":"func NewQOSContainerManager(subsystems *CgroupSubsystems, cgroupRoot CgroupName, nodeConfig NodeConfig, cgroupManager CgroupManager) (QOSContainerManager, error)","file":"pkg/kubelet/cm/qos_container_manager_linux.go","code":"func NewQOSContainerManager(subsystems *CgroupSubsystems, cgroupRoot CgroupName, nodeConfig NodeConfig, cgroupManager CgroupManager) (QOSContainerManager, error) {\n\tif !nodeConfig.CgroupsPerQOS {\n\t\treturn \u0026qosContainerManagerNoop{\n\t\t\tcgroupRoot: cgroupRoot,\n\t\t}, nil\n\t}\n\n\treturn \u0026qosContainerManagerImpl{\n\t\tsubsystems: subsystems,\n\t\tcgroupManager: cgroupManager,\n\t\tcgroupRoot: cgroupRoot,\n\t\tqosReserved: nodeConfig.QOSReserved,\n\t}, nil\n}","line":{"from":63,"to":76}} {"id":100006175,"name":"GetQOSContainersInfo","signature":"func (m *qosContainerManagerImpl) GetQOSContainersInfo() QOSContainersInfo","file":"pkg/kubelet/cm/qos_container_manager_linux.go","code":"func (m *qosContainerManagerImpl) GetQOSContainersInfo() QOSContainersInfo {\n\treturn m.qosContainersInfo\n}","line":{"from":78,"to":80}} {"id":100006176,"name":"Start","signature":"func (m *qosContainerManagerImpl) Start(getNodeAllocatable func() v1.ResourceList, activePods ActivePodsFunc) error","file":"pkg/kubelet/cm/qos_container_manager_linux.go","code":"func (m *qosContainerManagerImpl) Start(getNodeAllocatable func() v1.ResourceList, activePods ActivePodsFunc) error {\n\tcm := m.cgroupManager\n\trootContainer := m.cgroupRoot\n\tif !cm.Exists(rootContainer) {\n\t\treturn fmt.Errorf(\"root container %v doesn't exist\", rootContainer)\n\t}\n\n\t// Top level for Qos containers are created only for Burstable\n\t// and Best Effort classes\n\tqosClasses := map[v1.PodQOSClass]CgroupName{\n\t\tv1.PodQOSBurstable: NewCgroupName(rootContainer, strings.ToLower(string(v1.PodQOSBurstable))),\n\t\tv1.PodQOSBestEffort: NewCgroupName(rootContainer, strings.ToLower(string(v1.PodQOSBestEffort))),\n\t}\n\n\t// Create containers for both qos classes\n\tfor qosClass, containerName := range qosClasses {\n\t\tresourceParameters := \u0026ResourceConfig{}\n\t\t// the BestEffort QoS class has a statically configured minShares value\n\t\tif qosClass == v1.PodQOSBestEffort {\n\t\t\tminShares := uint64(MinShares)\n\t\t\tresourceParameters.CPUShares = \u0026minShares\n\t\t}\n\n\t\t// containerConfig object stores the cgroup specifications\n\t\tcontainerConfig := \u0026CgroupConfig{\n\t\t\tName: containerName,\n\t\t\tResourceParameters: resourceParameters,\n\t\t}\n\n\t\t// for each enumerated huge page size, the qos tiers are unbounded\n\t\tm.setHugePagesUnbounded(containerConfig)\n\n\t\t// check if it exists\n\t\tif !cm.Exists(containerName) {\n\t\t\tif err := cm.Create(containerConfig); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to create top level %v QOS cgroup : %v\", qosClass, err)\n\t\t\t}\n\t\t} else {\n\t\t\t// to ensure we actually have the right state, we update the config on startup\n\t\t\tif err := cm.Update(containerConfig); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to update top level %v QOS cgroup : %v\", qosClass, err)\n\t\t\t}\n\t\t}\n\t}\n\t// Store the top level qos container names\n\tm.qosContainersInfo = QOSContainersInfo{\n\t\tGuaranteed: rootContainer,\n\t\tBurstable: qosClasses[v1.PodQOSBurstable],\n\t\tBestEffort: qosClasses[v1.PodQOSBestEffort],\n\t}\n\tm.getNodeAllocatable = getNodeAllocatable\n\tm.activePods = activePods\n\n\t// update qos cgroup tiers on startup and in periodic intervals\n\t// to ensure desired state is in sync with actual state.\n\tgo wait.Until(func() {\n\t\terr := m.UpdateCgroups()\n\t\tif err != nil {\n\t\t\tklog.InfoS(\"Failed to reserve QoS requests\", \"err\", err)\n\t\t}\n\t}, periodicQOSCgroupUpdateInterval, wait.NeverStop)\n\n\treturn nil\n}","line":{"from":82,"to":145}} {"id":100006177,"name":"setHugePagesUnbounded","signature":"func (m *qosContainerManagerImpl) setHugePagesUnbounded(cgroupConfig *CgroupConfig) error","file":"pkg/kubelet/cm/qos_container_manager_linux.go","code":"// setHugePagesUnbounded ensures hugetlb is effectively unbounded\nfunc (m *qosContainerManagerImpl) setHugePagesUnbounded(cgroupConfig *CgroupConfig) error {\n\thugePageLimit := map[int64]int64{}\n\tfor _, pageSize := range libcontainercgroups.HugePageSizes() {\n\t\tpageSizeBytes, err := units.RAMInBytes(pageSize)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thugePageLimit[pageSizeBytes] = int64(1 \u003c\u003c 62)\n\t}\n\tcgroupConfig.ResourceParameters.HugePageLimit = hugePageLimit\n\treturn nil\n}","line":{"from":147,"to":159}} {"id":100006178,"name":"setHugePagesConfig","signature":"func (m *qosContainerManagerImpl) setHugePagesConfig(configs map[v1.PodQOSClass]*CgroupConfig) error","file":"pkg/kubelet/cm/qos_container_manager_linux.go","code":"func (m *qosContainerManagerImpl) setHugePagesConfig(configs map[v1.PodQOSClass]*CgroupConfig) error {\n\tfor _, v := range configs {\n\t\tif err := m.setHugePagesUnbounded(v); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":161,"to":168}} {"id":100006179,"name":"setCPUCgroupConfig","signature":"func (m *qosContainerManagerImpl) setCPUCgroupConfig(configs map[v1.PodQOSClass]*CgroupConfig) error","file":"pkg/kubelet/cm/qos_container_manager_linux.go","code":"func (m *qosContainerManagerImpl) setCPUCgroupConfig(configs map[v1.PodQOSClass]*CgroupConfig) error {\n\tpods := m.activePods()\n\tburstablePodCPURequest := int64(0)\n\treuseReqs := make(v1.ResourceList, 4)\n\tfor i := range pods {\n\t\tpod := pods[i]\n\t\tqosClass := v1qos.GetPodQOS(pod)\n\t\tif qosClass != v1.PodQOSBurstable {\n\t\t\t// we only care about the burstable qos tier\n\t\t\tcontinue\n\t\t}\n\t\treq := resource.PodRequests(pod, resource.PodResourcesOptions{Reuse: reuseReqs})\n\t\tif request, found := req[v1.ResourceCPU]; found {\n\t\t\tburstablePodCPURequest += request.MilliValue()\n\t\t}\n\t}\n\n\t// make sure best effort is always 2 shares\n\tbestEffortCPUShares := uint64(MinShares)\n\tconfigs[v1.PodQOSBestEffort].ResourceParameters.CPUShares = \u0026bestEffortCPUShares\n\n\t// set burstable shares based on current observe state\n\tburstableCPUShares := MilliCPUToShares(burstablePodCPURequest)\n\tconfigs[v1.PodQOSBurstable].ResourceParameters.CPUShares = \u0026burstableCPUShares\n\treturn nil\n}","line":{"from":170,"to":195}} {"id":100006180,"name":"getQoSMemoryRequests","signature":"func (m *qosContainerManagerImpl) getQoSMemoryRequests() map[v1.PodQOSClass]int64","file":"pkg/kubelet/cm/qos_container_manager_linux.go","code":"// getQoSMemoryRequests sums and returns the memory request of all pods for\n// guaranteed and burstable qos classes.\nfunc (m *qosContainerManagerImpl) getQoSMemoryRequests() map[v1.PodQOSClass]int64 {\n\tqosMemoryRequests := map[v1.PodQOSClass]int64{\n\t\tv1.PodQOSGuaranteed: 0,\n\t\tv1.PodQOSBurstable: 0,\n\t}\n\n\t// Sum the pod limits for pods in each QOS class\n\tpods := m.activePods()\n\treuseReqs := make(v1.ResourceList, 4)\n\tfor _, pod := range pods {\n\t\tpodMemoryRequest := int64(0)\n\t\tqosClass := v1qos.GetPodQOS(pod)\n\t\tif qosClass == v1.PodQOSBestEffort {\n\t\t\t// limits are not set for Best Effort pods\n\t\t\tcontinue\n\t\t}\n\t\treq := resource.PodRequests(pod, resource.PodResourcesOptions{Reuse: reuseReqs})\n\t\tif request, found := req[v1.ResourceMemory]; found {\n\t\t\tpodMemoryRequest += request.Value()\n\t\t}\n\t\tqosMemoryRequests[qosClass] += podMemoryRequest\n\t}\n\n\treturn qosMemoryRequests\n}","line":{"from":197,"to":223}} {"id":100006181,"name":"setMemoryReserve","signature":"func (m *qosContainerManagerImpl) setMemoryReserve(configs map[v1.PodQOSClass]*CgroupConfig, percentReserve int64)","file":"pkg/kubelet/cm/qos_container_manager_linux.go","code":"// setMemoryReserve sums the memory limits of all pods in a QOS class,\n// calculates QOS class memory limits, and set those limits in the\n// CgroupConfig for each QOS class.\nfunc (m *qosContainerManagerImpl) setMemoryReserve(configs map[v1.PodQOSClass]*CgroupConfig, percentReserve int64) {\n\tqosMemoryRequests := m.getQoSMemoryRequests()\n\n\tresources := m.getNodeAllocatable()\n\tallocatableResource, ok := resources[v1.ResourceMemory]\n\tif !ok {\n\t\tklog.V(2).InfoS(\"Allocatable memory value could not be determined, not setting QoS memory limits\")\n\t\treturn\n\t}\n\tallocatable := allocatableResource.Value()\n\tif allocatable == 0 {\n\t\tklog.V(2).InfoS(\"Allocatable memory reported as 0, might be in standalone mode, not setting QoS memory limits\")\n\t\treturn\n\t}\n\n\tfor qos, limits := range qosMemoryRequests {\n\t\tklog.V(2).InfoS(\"QoS pod memory limit\", \"qos\", qos, \"limits\", limits, \"percentReserve\", percentReserve)\n\t}\n\n\t// Calculate QOS memory limits\n\tburstableLimit := allocatable - (qosMemoryRequests[v1.PodQOSGuaranteed] * percentReserve / 100)\n\tbestEffortLimit := burstableLimit - (qosMemoryRequests[v1.PodQOSBurstable] * percentReserve / 100)\n\tconfigs[v1.PodQOSBurstable].ResourceParameters.Memory = \u0026burstableLimit\n\tconfigs[v1.PodQOSBestEffort].ResourceParameters.Memory = \u0026bestEffortLimit\n}","line":{"from":225,"to":252}} {"id":100006182,"name":"retrySetMemoryReserve","signature":"func (m *qosContainerManagerImpl) retrySetMemoryReserve(configs map[v1.PodQOSClass]*CgroupConfig, percentReserve int64)","file":"pkg/kubelet/cm/qos_container_manager_linux.go","code":"// retrySetMemoryReserve checks for any QoS cgroups over the limit\n// that was attempted to be set in the first Update() and adjusts\n// their memory limit to the usage to prevent further growth.\nfunc (m *qosContainerManagerImpl) retrySetMemoryReserve(configs map[v1.PodQOSClass]*CgroupConfig, percentReserve int64) {\n\t// Unreclaimable memory usage may already exceeded the desired limit\n\t// Attempt to set the limit near the current usage to put pressure\n\t// on the cgroup and prevent further growth.\n\tfor qos, config := range configs {\n\t\tusage, err := m.cgroupManager.MemoryUsage(config.Name)\n\t\tif err != nil {\n\t\t\tklog.V(2).InfoS(\"Failed to get resource stats\", \"err\", err)\n\t\t\treturn\n\t\t}\n\n\t\t// Because there is no good way to determine of the original Update()\n\t\t// on the memory resource was successful, we determine failure of the\n\t\t// first attempt by checking if the usage is above the limit we attempt\n\t\t// to set. If it is, we assume the first attempt to set the limit failed\n\t\t// and try again setting the limit to the usage. Otherwise we leave\n\t\t// the CgroupConfig as is.\n\t\tif configs[qos].ResourceParameters.Memory != nil \u0026\u0026 usage \u003e *configs[qos].ResourceParameters.Memory {\n\t\t\tconfigs[qos].ResourceParameters.Memory = \u0026usage\n\t\t}\n\t}\n}","line":{"from":254,"to":278}} {"id":100006183,"name":"setMemoryQoS","signature":"func (m *qosContainerManagerImpl) setMemoryQoS(configs map[v1.PodQOSClass]*CgroupConfig)","file":"pkg/kubelet/cm/qos_container_manager_linux.go","code":"// setMemoryQoS sums the memory requests of all pods in the Burstable class,\n// and set the sum memory as the memory.min in the Unified field of CgroupConfig.\nfunc (m *qosContainerManagerImpl) setMemoryQoS(configs map[v1.PodQOSClass]*CgroupConfig) {\n\tqosMemoryRequests := m.getQoSMemoryRequests()\n\n\t// Calculate the memory.min:\n\t// for burstable(/kubepods/burstable): sum of all burstable pods\n\t// for guaranteed(/kubepods): sum of all guaranteed and burstable pods\n\tburstableMin := qosMemoryRequests[v1.PodQOSBurstable]\n\tguaranteedMin := qosMemoryRequests[v1.PodQOSGuaranteed] + burstableMin\n\n\tif burstableMin \u003e 0 {\n\t\tif configs[v1.PodQOSBurstable].ResourceParameters.Unified == nil {\n\t\t\tconfigs[v1.PodQOSBurstable].ResourceParameters.Unified = make(map[string]string)\n\t\t}\n\t\tconfigs[v1.PodQOSBurstable].ResourceParameters.Unified[MemoryMin] = strconv.FormatInt(burstableMin, 10)\n\t\tklog.V(4).InfoS(\"MemoryQoS config for qos\", \"qos\", v1.PodQOSBurstable, \"memoryMin\", burstableMin)\n\t}\n\n\tif guaranteedMin \u003e 0 {\n\t\tif configs[v1.PodQOSGuaranteed].ResourceParameters.Unified == nil {\n\t\t\tconfigs[v1.PodQOSGuaranteed].ResourceParameters.Unified = make(map[string]string)\n\t\t}\n\t\tconfigs[v1.PodQOSGuaranteed].ResourceParameters.Unified[MemoryMin] = strconv.FormatInt(guaranteedMin, 10)\n\t\tklog.V(4).InfoS(\"MemoryQoS config for qos\", \"qos\", v1.PodQOSGuaranteed, \"memoryMin\", guaranteedMin)\n\t}\n}","line":{"from":280,"to":306}} {"id":100006184,"name":"UpdateCgroups","signature":"func (m *qosContainerManagerImpl) UpdateCgroups() error","file":"pkg/kubelet/cm/qos_container_manager_linux.go","code":"func (m *qosContainerManagerImpl) UpdateCgroups() error {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tqosConfigs := map[v1.PodQOSClass]*CgroupConfig{\n\t\tv1.PodQOSGuaranteed: {\n\t\t\tName: m.qosContainersInfo.Guaranteed,\n\t\t\tResourceParameters: \u0026ResourceConfig{},\n\t\t},\n\t\tv1.PodQOSBurstable: {\n\t\t\tName: m.qosContainersInfo.Burstable,\n\t\t\tResourceParameters: \u0026ResourceConfig{},\n\t\t},\n\t\tv1.PodQOSBestEffort: {\n\t\t\tName: m.qosContainersInfo.BestEffort,\n\t\t\tResourceParameters: \u0026ResourceConfig{},\n\t\t},\n\t}\n\n\t// update the qos level cgroup settings for cpu shares\n\tif err := m.setCPUCgroupConfig(qosConfigs); err != nil {\n\t\treturn err\n\t}\n\n\t// update the qos level cgroup settings for huge pages (ensure they remain unbounded)\n\tif err := m.setHugePagesConfig(qosConfigs); err != nil {\n\t\treturn err\n\t}\n\n\t// update the qos level cgrougs v2 settings of memory qos if feature enabled\n\tif utilfeature.DefaultFeatureGate.Enabled(kubefeatures.MemoryQoS) \u0026\u0026\n\t\tlibcontainercgroups.IsCgroup2UnifiedMode() {\n\t\tm.setMemoryQoS(qosConfigs)\n\t}\n\n\tif utilfeature.DefaultFeatureGate.Enabled(kubefeatures.QOSReserved) {\n\t\tfor resource, percentReserve := range m.qosReserved {\n\t\t\tswitch resource {\n\t\t\tcase v1.ResourceMemory:\n\t\t\t\tm.setMemoryReserve(qosConfigs, percentReserve)\n\t\t\t}\n\t\t}\n\n\t\tupdateSuccess := true\n\t\tfor _, config := range qosConfigs {\n\t\t\terr := m.cgroupManager.Update(config)\n\t\t\tif err != nil {\n\t\t\t\tupdateSuccess = false\n\t\t\t}\n\t\t}\n\t\tif updateSuccess {\n\t\t\tklog.V(4).InfoS(\"Updated QoS cgroup configuration\")\n\t\t\treturn nil\n\t\t}\n\n\t\t// If the resource can adjust the ResourceConfig to increase likelihood of\n\t\t// success, call the adjustment function here. Otherwise, the Update() will\n\t\t// be called again with the same values.\n\t\tfor resource, percentReserve := range m.qosReserved {\n\t\t\tswitch resource {\n\t\t\tcase v1.ResourceMemory:\n\t\t\t\tm.retrySetMemoryReserve(qosConfigs, percentReserve)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, config := range qosConfigs {\n\t\terr := m.cgroupManager.Update(config)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to update QoS cgroup configuration\")\n\t\t\treturn err\n\t\t}\n\t}\n\n\tklog.V(4).InfoS(\"Updated QoS cgroup configuration\")\n\treturn nil\n}","line":{"from":308,"to":384}} {"id":100006185,"name":"GetQOSContainersInfo","signature":"func (m *qosContainerManagerNoop) GetQOSContainersInfo() QOSContainersInfo","file":"pkg/kubelet/cm/qos_container_manager_linux.go","code":"func (m *qosContainerManagerNoop) GetQOSContainersInfo() QOSContainersInfo {\n\treturn QOSContainersInfo{}\n}","line":{"from":392,"to":394}} {"id":100006186,"name":"Start","signature":"func (m *qosContainerManagerNoop) Start(_ func() v1.ResourceList, _ ActivePodsFunc) error","file":"pkg/kubelet/cm/qos_container_manager_linux.go","code":"func (m *qosContainerManagerNoop) Start(_ func() v1.ResourceList, _ ActivePodsFunc) error {\n\treturn nil\n}","line":{"from":396,"to":398}} {"id":100006187,"name":"UpdateCgroups","signature":"func (m *qosContainerManagerNoop) UpdateCgroups() error","file":"pkg/kubelet/cm/qos_container_manager_linux.go","code":"func (m *qosContainerManagerNoop) UpdateCgroups() error {\n\treturn nil\n}","line":{"from":400,"to":402}} {"id":100006188,"name":"NewEmptyBitMask","signature":"func NewEmptyBitMask() BitMask","file":"pkg/kubelet/cm/topologymanager/bitmask/bitmask.go","code":"// NewEmptyBitMask creates a new, empty BitMask\nfunc NewEmptyBitMask() BitMask {\n\ts := bitMask(0)\n\treturn \u0026s\n}","line":{"from":47,"to":51}} {"id":100006189,"name":"NewBitMask","signature":"func NewBitMask(bits ...int) (BitMask, error)","file":"pkg/kubelet/cm/topologymanager/bitmask/bitmask.go","code":"// NewBitMask creates a new BitMask\nfunc NewBitMask(bits ...int) (BitMask, error) {\n\ts := bitMask(0)\n\terr := (\u0026s).Add(bits...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026s, nil\n}","line":{"from":53,"to":61}} {"id":100006190,"name":"Add","signature":"func (s *bitMask) Add(bits ...int) error","file":"pkg/kubelet/cm/topologymanager/bitmask/bitmask.go","code":"// Add adds the bits with topology affinity to the BitMask\nfunc (s *bitMask) Add(bits ...int) error {\n\tmask := *s\n\tfor _, i := range bits {\n\t\tif i \u003c 0 || i \u003e= 64 {\n\t\t\treturn fmt.Errorf(\"bit number must be in range 0-63\")\n\t\t}\n\t\tmask |= 1 \u003c\u003c uint64(i)\n\t}\n\t*s = mask\n\treturn nil\n}","line":{"from":63,"to":74}} {"id":100006191,"name":"Remove","signature":"func (s *bitMask) Remove(bits ...int) error","file":"pkg/kubelet/cm/topologymanager/bitmask/bitmask.go","code":"// Remove removes specified bits from BitMask\nfunc (s *bitMask) Remove(bits ...int) error {\n\tmask := *s\n\tfor _, i := range bits {\n\t\tif i \u003c 0 || i \u003e= 64 {\n\t\t\treturn fmt.Errorf(\"bit number must be in range 0-63\")\n\t\t}\n\t\tmask \u0026^= 1 \u003c\u003c uint64(i)\n\t}\n\t*s = mask\n\treturn nil\n}","line":{"from":76,"to":87}} {"id":100006192,"name":"And","signature":"func (s *bitMask) And(masks ...BitMask)","file":"pkg/kubelet/cm/topologymanager/bitmask/bitmask.go","code":"// And performs and operation on all bits in masks\nfunc (s *bitMask) And(masks ...BitMask) {\n\tfor _, m := range masks {\n\t\t*s \u0026= *m.(*bitMask)\n\t}\n}","line":{"from":89,"to":94}} {"id":100006193,"name":"Or","signature":"func (s *bitMask) Or(masks ...BitMask)","file":"pkg/kubelet/cm/topologymanager/bitmask/bitmask.go","code":"// Or performs or operation on all bits in masks\nfunc (s *bitMask) Or(masks ...BitMask) {\n\tfor _, m := range masks {\n\t\t*s |= *m.(*bitMask)\n\t}\n}","line":{"from":96,"to":101}} {"id":100006194,"name":"Clear","signature":"func (s *bitMask) Clear()","file":"pkg/kubelet/cm/topologymanager/bitmask/bitmask.go","code":"// Clear resets all bits in mask to zero\nfunc (s *bitMask) Clear() {\n\t*s = 0\n}","line":{"from":103,"to":106}} {"id":100006195,"name":"Fill","signature":"func (s *bitMask) Fill()","file":"pkg/kubelet/cm/topologymanager/bitmask/bitmask.go","code":"// Fill sets all bits in mask to one\nfunc (s *bitMask) Fill() {\n\t*s = bitMask(^uint64(0))\n}","line":{"from":108,"to":111}} {"id":100006196,"name":"IsEmpty","signature":"func (s *bitMask) IsEmpty() bool","file":"pkg/kubelet/cm/topologymanager/bitmask/bitmask.go","code":"// IsEmpty checks mask to see if all bits are zero\nfunc (s *bitMask) IsEmpty() bool {\n\treturn *s == 0\n}","line":{"from":113,"to":116}} {"id":100006197,"name":"IsSet","signature":"func (s *bitMask) IsSet(bit int) bool","file":"pkg/kubelet/cm/topologymanager/bitmask/bitmask.go","code":"// IsSet checks bit in mask to see if bit is set to one\nfunc (s *bitMask) IsSet(bit int) bool {\n\tif bit \u003c 0 || bit \u003e= 64 {\n\t\treturn false\n\t}\n\treturn (*s \u0026 (1 \u003c\u003c uint64(bit))) \u003e 0\n}","line":{"from":118,"to":124}} {"id":100006198,"name":"AnySet","signature":"func (s *bitMask) AnySet(bits []int) bool","file":"pkg/kubelet/cm/topologymanager/bitmask/bitmask.go","code":"// AnySet checks bit in mask to see if any provided bit is set to one\nfunc (s *bitMask) AnySet(bits []int) bool {\n\tfor _, b := range bits {\n\t\tif s.IsSet(b) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":126,"to":134}} {"id":100006199,"name":"IsEqual","signature":"func (s *bitMask) IsEqual(mask BitMask) bool","file":"pkg/kubelet/cm/topologymanager/bitmask/bitmask.go","code":"// IsEqual checks if masks are equal\nfunc (s *bitMask) IsEqual(mask BitMask) bool {\n\treturn *s == *mask.(*bitMask)\n}","line":{"from":136,"to":139}} {"id":100006200,"name":"IsNarrowerThan","signature":"func (s *bitMask) IsNarrowerThan(mask BitMask) bool","file":"pkg/kubelet/cm/topologymanager/bitmask/bitmask.go","code":"// IsNarrowerThan checks if one mask is narrower than another.\n//\n// A mask is said to be \"narrower\" than another if it has lets bits set. If the\n// same number of bits are set in both masks, then the mask with more\n// lower-numbered bits set wins out.\nfunc (s *bitMask) IsNarrowerThan(mask BitMask) bool {\n\tif s.Count() == mask.Count() {\n\t\treturn s.IsLessThan(mask)\n\t}\n\treturn s.Count() \u003c mask.Count()\n}","line":{"from":141,"to":151}} {"id":100006201,"name":"IsLessThan","signature":"func (s *bitMask) IsLessThan(mask BitMask) bool","file":"pkg/kubelet/cm/topologymanager/bitmask/bitmask.go","code":"// IsLessThan checks which bitmask has more lower-numbered bits set.\nfunc (s *bitMask) IsLessThan(mask BitMask) bool {\n\treturn *s \u003c *mask.(*bitMask)\n}","line":{"from":153,"to":156}} {"id":100006202,"name":"IsGreaterThan","signature":"func (s *bitMask) IsGreaterThan(mask BitMask) bool","file":"pkg/kubelet/cm/topologymanager/bitmask/bitmask.go","code":"// IsGreaterThan checks which bitmask has more higher-numbered bits set.\nfunc (s *bitMask) IsGreaterThan(mask BitMask) bool {\n\treturn *s \u003e *mask.(*bitMask)\n}","line":{"from":158,"to":161}} {"id":100006203,"name":"String","signature":"func (s *bitMask) String() string","file":"pkg/kubelet/cm/topologymanager/bitmask/bitmask.go","code":"// String converts mask to string\nfunc (s *bitMask) String() string {\n\tgrouping := 2\n\tfor shift := 64 - grouping; shift \u003e 0; shift -= grouping {\n\t\tif *s \u003e (1 \u003c\u003c uint(shift)) {\n\t\t\treturn fmt.Sprintf(\"%0\"+strconv.Itoa(shift+grouping)+\"b\", *s)\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"%0\"+strconv.Itoa(grouping)+\"b\", *s)\n}","line":{"from":163,"to":172}} {"id":100006204,"name":"Count","signature":"func (s *bitMask) Count() int","file":"pkg/kubelet/cm/topologymanager/bitmask/bitmask.go","code":"// Count counts number of bits in mask set to one\nfunc (s *bitMask) Count() int {\n\treturn bits.OnesCount64(uint64(*s))\n}","line":{"from":174,"to":177}} {"id":100006205,"name":"GetBits","signature":"func (s *bitMask) GetBits() []int","file":"pkg/kubelet/cm/topologymanager/bitmask/bitmask.go","code":"// Getbits returns each bit number with bits set to one\nfunc (s *bitMask) GetBits() []int {\n\tvar bits []int\n\tfor i := uint64(0); i \u003c 64; i++ {\n\t\tif (*s \u0026 (1 \u003c\u003c i)) \u003e 0 {\n\t\t\tbits = append(bits, int(i))\n\t\t}\n\t}\n\treturn bits\n}","line":{"from":179,"to":188}} {"id":100006206,"name":"And","signature":"func And(first BitMask, masks ...BitMask) BitMask","file":"pkg/kubelet/cm/topologymanager/bitmask/bitmask.go","code":"// And is a package level implementation of 'and' between first and masks\nfunc And(first BitMask, masks ...BitMask) BitMask {\n\ts := *first.(*bitMask)\n\ts.And(masks...)\n\treturn \u0026s\n}","line":{"from":190,"to":195}} {"id":100006207,"name":"Or","signature":"func Or(first BitMask, masks ...BitMask) BitMask","file":"pkg/kubelet/cm/topologymanager/bitmask/bitmask.go","code":"// Or is a package level implementation of 'or' between first and masks\nfunc Or(first BitMask, masks ...BitMask) BitMask {\n\ts := *first.(*bitMask)\n\ts.Or(masks...)\n\treturn \u0026s\n}","line":{"from":197,"to":202}} {"id":100006208,"name":"IterateBitMasks","signature":"func IterateBitMasks(bits []int, callback func(BitMask))","file":"pkg/kubelet/cm/topologymanager/bitmask/bitmask.go","code":"// IterateBitMasks iterates all possible masks from a list of bits,\n// issuing a callback on each mask.\nfunc IterateBitMasks(bits []int, callback func(BitMask)) {\n\tvar iterate func(bits, accum []int, size int)\n\titerate = func(bits, accum []int, size int) {\n\t\tif len(accum) == size {\n\t\t\tmask, _ := NewBitMask(accum...)\n\t\t\tcallback(mask)\n\t\t\treturn\n\t\t}\n\t\tfor i := range bits {\n\t\t\titerate(bits[i+1:], append(accum, bits[i]), size)\n\t\t}\n\t}\n\n\tfor i := 1; i \u003c= len(bits); i++ {\n\t\titerate(bits, []int{}, i)\n\t}\n}","line":{"from":204,"to":222}} {"id":100006209,"name":"NewNUMAInfo","signature":"func NewNUMAInfo(topology []cadvisorapi.Node, opts PolicyOptions) (*NUMAInfo, error)","file":"pkg/kubelet/cm/topologymanager/numa_info.go","code":"func NewNUMAInfo(topology []cadvisorapi.Node, opts PolicyOptions) (*NUMAInfo, error) {\n\tvar numaNodes []int\n\tdistances := map[int][]uint64{}\n\tfor _, node := range topology {\n\t\tnumaNodes = append(numaNodes, node.Id)\n\n\t\tvar nodeDistance []uint64\n\t\tif opts.PreferClosestNUMA {\n\t\t\tnodeDistance = node.Distances\n\t\t\tif nodeDistance == nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error getting NUMA distances from cadvisor\")\n\t\t\t}\n\t\t}\n\t\tdistances[node.Id] = nodeDistance\n\t}\n\n\tnumaInfo := \u0026NUMAInfo{\n\t\tNodes: numaNodes,\n\t\tNUMADistances: distances,\n\t}\n\n\treturn numaInfo, nil\n}","line":{"from":33,"to":55}} {"id":100006210,"name":"Narrowest","signature":"func (n *NUMAInfo) Narrowest(m1 bitmask.BitMask, m2 bitmask.BitMask) bitmask.BitMask","file":"pkg/kubelet/cm/topologymanager/numa_info.go","code":"func (n *NUMAInfo) Narrowest(m1 bitmask.BitMask, m2 bitmask.BitMask) bitmask.BitMask {\n\tif m1.IsNarrowerThan(m2) {\n\t\treturn m1\n\t}\n\treturn m2\n}","line":{"from":57,"to":62}} {"id":100006211,"name":"Closest","signature":"func (n *NUMAInfo) Closest(m1 bitmask.BitMask, m2 bitmask.BitMask) bitmask.BitMask","file":"pkg/kubelet/cm/topologymanager/numa_info.go","code":"func (n *NUMAInfo) Closest(m1 bitmask.BitMask, m2 bitmask.BitMask) bitmask.BitMask {\n\t// If the length of both bitmasks aren't the same, choose the one that is narrowest.\n\tif m1.Count() != m2.Count() {\n\t\treturn n.Narrowest(m1, m2)\n\t}\n\n\tm1Distance := n.NUMADistances.CalculateAverageFor(m1)\n\tm2Distance := n.NUMADistances.CalculateAverageFor(m2)\n\t// If average distance is the same, take bitmask with more lower-number bits set.\n\tif m1Distance == m2Distance {\n\t\tif m1.IsLessThan(m2) {\n\t\t\treturn m1\n\t\t}\n\t\treturn m2\n\t}\n\n\t// Otherwise, return the bitmask with the shortest average distance between NUMA nodes.\n\tif m1Distance \u003c m2Distance {\n\t\treturn m1\n\t}\n\n\treturn m2\n}","line":{"from":64,"to":86}} {"id":100006212,"name":"DefaultAffinityMask","signature":"func (n NUMAInfo) DefaultAffinityMask() bitmask.BitMask","file":"pkg/kubelet/cm/topologymanager/numa_info.go","code":"func (n NUMAInfo) DefaultAffinityMask() bitmask.BitMask {\n\tdefaultAffinity, _ := bitmask.NewBitMask(n.Nodes...)\n\treturn defaultAffinity\n}","line":{"from":88,"to":91}} {"id":100006213,"name":"CalculateAverageFor","signature":"func (d NUMADistances) CalculateAverageFor(bm bitmask.BitMask) float64","file":"pkg/kubelet/cm/topologymanager/numa_info.go","code":"func (d NUMADistances) CalculateAverageFor(bm bitmask.BitMask) float64 {\n\t// This should never happen, but just in case make sure we do not divide by zero.\n\tif bm.Count() == 0 {\n\t\treturn 0\n\t}\n\n\tvar count float64 = 0\n\tvar sum float64 = 0\n\tfor _, node1 := range bm.GetBits() {\n\t\tfor _, node2 := range bm.GetBits() {\n\t\t\tsum += float64(d[node1][node2])\n\t\t\tcount++\n\t\t}\n\t}\n\n\treturn sum / count\n}","line":{"from":93,"to":109}} {"id":100006214,"name":"mergePermutation","signature":"func mergePermutation(defaultAffinity bitmask.BitMask, permutation []TopologyHint) TopologyHint","file":"pkg/kubelet/cm/topologymanager/policy.go","code":"// Merge a TopologyHints permutation to a single hint by performing a bitwise-AND\n// of their affinity masks. The hint shall be preferred if all hits in the permutation\n// are preferred.\nfunc mergePermutation(defaultAffinity bitmask.BitMask, permutation []TopologyHint) TopologyHint {\n\t// Get the NUMANodeAffinity from each hint in the permutation and see if any\n\t// of them encode unpreferred allocations.\n\tpreferred := true\n\tvar numaAffinities []bitmask.BitMask\n\tfor _, hint := range permutation {\n\t\t// Only consider hints that have an actual NUMANodeAffinity set.\n\t\tif hint.NUMANodeAffinity != nil {\n\t\t\tnumaAffinities = append(numaAffinities, hint.NUMANodeAffinity)\n\t\t\t// Only mark preferred if all affinities are equal.\n\t\t\tif !hint.NUMANodeAffinity.IsEqual(numaAffinities[0]) {\n\t\t\t\tpreferred = false\n\t\t\t}\n\t\t}\n\t\t// Only mark preferred if all affinities are preferred.\n\t\tif !hint.Preferred {\n\t\t\tpreferred = false\n\t\t}\n\t}\n\n\t// Merge the affinities using a bitwise-and operation.\n\tmergedAffinity := bitmask.And(defaultAffinity, numaAffinities...)\n\t// Build a mergedHint from the merged affinity mask, setting preferred as\n\t// appropriate based on the logic above.\n\treturn TopologyHint{mergedAffinity, preferred}\n}","line":{"from":33,"to":61}} {"id":100006215,"name":"filterProvidersHints","signature":"func filterProvidersHints(providersHints []map[string][]TopologyHint) [][]TopologyHint","file":"pkg/kubelet/cm/topologymanager/policy.go","code":"func filterProvidersHints(providersHints []map[string][]TopologyHint) [][]TopologyHint {\n\t// Loop through all hint providers and save an accumulated list of the\n\t// hints returned by each hint provider. If no hints are provided, assume\n\t// that provider has no preference for topology-aware allocation.\n\tvar allProviderHints [][]TopologyHint\n\tfor _, hints := range providersHints {\n\t\t// If hints is nil, insert a single, preferred any-numa hint into allProviderHints.\n\t\tif len(hints) == 0 {\n\t\t\tklog.InfoS(\"Hint Provider has no preference for NUMA affinity with any resource\")\n\t\t\tallProviderHints = append(allProviderHints, []TopologyHint{{nil, true}})\n\t\t\tcontinue\n\t\t}\n\n\t\t// Otherwise, accumulate the hints for each resource type into allProviderHints.\n\t\tfor resource := range hints {\n\t\t\tif hints[resource] == nil {\n\t\t\t\tklog.InfoS(\"Hint Provider has no preference for NUMA affinity with resource\", \"resource\", resource)\n\t\t\t\tallProviderHints = append(allProviderHints, []TopologyHint{{nil, true}})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif len(hints[resource]) == 0 {\n\t\t\t\tklog.InfoS(\"Hint Provider has no possible NUMA affinities for resource\", \"resource\", resource)\n\t\t\t\tallProviderHints = append(allProviderHints, []TopologyHint{{nil, false}})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tallProviderHints = append(allProviderHints, hints[resource])\n\t\t}\n\t}\n\treturn allProviderHints\n}","line":{"from":63,"to":94}} {"id":100006216,"name":"narrowestHint","signature":"func narrowestHint(hints []TopologyHint) *TopologyHint","file":"pkg/kubelet/cm/topologymanager/policy.go","code":"func narrowestHint(hints []TopologyHint) *TopologyHint {\n\tif len(hints) == 0 {\n\t\treturn nil\n\t}\n\tvar narrowestHint *TopologyHint\n\tfor i := range hints {\n\t\tif hints[i].NUMANodeAffinity == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif narrowestHint == nil {\n\t\t\tnarrowestHint = \u0026hints[i]\n\t\t}\n\t\tif hints[i].NUMANodeAffinity.IsNarrowerThan(narrowestHint.NUMANodeAffinity) {\n\t\t\tnarrowestHint = \u0026hints[i]\n\t\t}\n\t}\n\treturn narrowestHint\n}","line":{"from":96,"to":113}} {"id":100006217,"name":"maxOfMinAffinityCounts","signature":"func maxOfMinAffinityCounts(filteredHints [][]TopologyHint) int","file":"pkg/kubelet/cm/topologymanager/policy.go","code":"func maxOfMinAffinityCounts(filteredHints [][]TopologyHint) int {\n\tmaxOfMinCount := 0\n\tfor _, resourceHints := range filteredHints {\n\t\tnarrowestHint := narrowestHint(resourceHints)\n\t\tif narrowestHint == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif narrowestHint.NUMANodeAffinity.Count() \u003e maxOfMinCount {\n\t\t\tmaxOfMinCount = narrowestHint.NUMANodeAffinity.Count()\n\t\t}\n\t}\n\treturn maxOfMinCount\n}","line":{"from":115,"to":127}} {"id":100006218,"name":"NewHintMerger","signature":"func NewHintMerger(numaInfo *NUMAInfo, hints [][]TopologyHint, policyName string, opts PolicyOptions) HintMerger","file":"pkg/kubelet/cm/topologymanager/policy.go","code":"func NewHintMerger(numaInfo *NUMAInfo, hints [][]TopologyHint, policyName string, opts PolicyOptions) HintMerger {\n\tcompareNumaAffinityMasks := func(current, candidate *TopologyHint) *TopologyHint {\n\t\t// If current and candidate bitmasks are the same, prefer current hint.\n\t\tif candidate.NUMANodeAffinity.IsEqual(current.NUMANodeAffinity) {\n\t\t\treturn current\n\t\t}\n\n\t\t// Otherwise compare the hints, based on the policy options provided\n\t\tvar best bitmask.BitMask\n\t\tif (policyName != PolicySingleNumaNode) \u0026\u0026 opts.PreferClosestNUMA {\n\t\t\tbest = numaInfo.Closest(current.NUMANodeAffinity, candidate.NUMANodeAffinity)\n\t\t} else {\n\t\t\tbest = numaInfo.Narrowest(current.NUMANodeAffinity, candidate.NUMANodeAffinity)\n\t\t}\n\t\tif best.IsEqual(current.NUMANodeAffinity) {\n\t\t\treturn current\n\t\t}\n\t\treturn candidate\n\t}\n\n\tmerger := HintMerger{\n\t\tNUMAInfo: numaInfo,\n\t\tHints: hints,\n\t\tBestNonPreferredAffinityCount: maxOfMinAffinityCounts(hints),\n\t\tCompareNUMAAffinityMasks: compareNumaAffinityMasks,\n\t}\n\n\treturn merger\n}","line":{"from":142,"to":170}} {"id":100006219,"name":"compare","signature":"func (m HintMerger) compare(current *TopologyHint, candidate *TopologyHint) *TopologyHint","file":"pkg/kubelet/cm/topologymanager/policy.go","code":"func (m HintMerger) compare(current *TopologyHint, candidate *TopologyHint) *TopologyHint {\n\t// Only consider candidates that result in a NUMANodeAffinity \u003e 0 to\n\t// replace the current bestHint.\n\tif candidate.NUMANodeAffinity.Count() == 0 {\n\t\treturn current\n\t}\n\n\t// If no current bestHint is set, return the candidate as the bestHint.\n\tif current == nil {\n\t\treturn candidate\n\t}\n\n\t// If the current bestHint is non-preferred and the candidate hint is\n\t// preferred, always choose the preferred hint over the non-preferred one.\n\tif !current.Preferred \u0026\u0026 candidate.Preferred {\n\t\treturn candidate\n\t}\n\n\t// If the current bestHint is preferred and the candidate hint is\n\t// non-preferred, never update the bestHint, regardless of how\n\t// the candidate hint's affinity mask compares to the current\n\t// hint's affinity mask.\n\tif current.Preferred \u0026\u0026 !candidate.Preferred {\n\t\treturn current\n\t}\n\n\t// If the current bestHint and the candidate hint are both preferred,\n\t// then only consider fitter NUMANodeAffinity\n\tif current.Preferred \u0026\u0026 candidate.Preferred {\n\t\treturn m.CompareNUMAAffinityMasks(current, candidate)\n\n\t}\n\n\t// The only case left is if the current best bestHint and the candidate\n\t// hint are both non-preferred. In this case, try and find a hint whose\n\t// affinity count is as close to (but not higher than) the\n\t// bestNonPreferredAffinityCount as possible. To do this we need to\n\t// consider the following cases and react accordingly:\n\t//\n\t// 1. current.NUMANodeAffinity.Count() \u003e bestNonPreferredAffinityCount\n\t// 2. current.NUMANodeAffinity.Count() == bestNonPreferredAffinityCount\n\t// 3. current.NUMANodeAffinity.Count() \u003c bestNonPreferredAffinityCount\n\t//\n\t// For case (1), the current bestHint is larger than the\n\t// bestNonPreferredAffinityCount, so updating to fitter mergeHint\n\t// is preferred over staying where we are.\n\t//\n\t// For case (2), the current bestHint is equal to the\n\t// bestNonPreferredAffinityCount, so we would like to stick with what\n\t// we have *unless* the candidate hint is also equal to\n\t// bestNonPreferredAffinityCount and it is fitter.\n\t//\n\t// For case (3), the current bestHint is less than\n\t// bestNonPreferredAffinityCount, so we would like to creep back up to\n\t// bestNonPreferredAffinityCount as close as we can. There are three\n\t// cases to consider here:\n\t//\n\t// 3a. candidate.NUMANodeAffinity.Count() \u003e bestNonPreferredAffinityCount\n\t// 3b. candidate.NUMANodeAffinity.Count() == bestNonPreferredAffinityCount\n\t// 3c. candidate.NUMANodeAffinity.Count() \u003c bestNonPreferredAffinityCount\n\t//\n\t// For case (3a), we just want to stick with the current bestHint\n\t// because choosing a new hint that is greater than\n\t// bestNonPreferredAffinityCount would be counter-productive.\n\t//\n\t// For case (3b), we want to immediately update bestHint to the\n\t// candidate hint, making it now equal to bestNonPreferredAffinityCount.\n\t//\n\t// For case (3c), we know that *both* the current bestHint and the\n\t// candidate hint are less than bestNonPreferredAffinityCount, so we\n\t// want to choose one that brings us back up as close to\n\t// bestNonPreferredAffinityCount as possible. There are three cases to\n\t// consider here:\n\t//\n\t// 3ca. candidate.NUMANodeAffinity.Count() \u003e current.NUMANodeAffinity.Count()\n\t// 3cb. candidate.NUMANodeAffinity.Count() \u003c current.NUMANodeAffinity.Count()\n\t// 3cc. candidate.NUMANodeAffinity.Count() == current.NUMANodeAffinity.Count()\n\t//\n\t// For case (3ca), we want to immediately update bestHint to the\n\t// candidate hint because that will bring us closer to the (higher)\n\t// value of bestNonPreferredAffinityCount.\n\t//\n\t// For case (3cb), we want to stick with the current bestHint because\n\t// choosing the candidate hint would strictly move us further away from\n\t// the bestNonPreferredAffinityCount.\n\t//\n\t// Finally, for case (3cc), we know that the current bestHint and the\n\t// candidate hint are equal, so we simply choose the fitter of the 2.\n\n\t// Case 1\n\tif current.NUMANodeAffinity.Count() \u003e m.BestNonPreferredAffinityCount {\n\t\treturn m.CompareNUMAAffinityMasks(current, candidate)\n\t}\n\t// Case 2\n\tif current.NUMANodeAffinity.Count() == m.BestNonPreferredAffinityCount {\n\t\tif candidate.NUMANodeAffinity.Count() != m.BestNonPreferredAffinityCount {\n\t\t\treturn current\n\t\t}\n\t\treturn m.CompareNUMAAffinityMasks(current, candidate)\n\t}\n\t// Case 3a\n\tif candidate.NUMANodeAffinity.Count() \u003e m.BestNonPreferredAffinityCount {\n\t\treturn current\n\t}\n\t// Case 3b\n\tif candidate.NUMANodeAffinity.Count() == m.BestNonPreferredAffinityCount {\n\t\treturn candidate\n\t}\n\n\t// Case 3ca\n\tif candidate.NUMANodeAffinity.Count() \u003e current.NUMANodeAffinity.Count() {\n\t\treturn candidate\n\t}\n\t// Case 3cb\n\tif candidate.NUMANodeAffinity.Count() \u003c current.NUMANodeAffinity.Count() {\n\t\treturn current\n\t}\n\n\t// Case 3cc\n\treturn m.CompareNUMAAffinityMasks(current, candidate)\n\n}","line":{"from":172,"to":293}} {"id":100006220,"name":"Merge","signature":"func (m HintMerger) Merge() TopologyHint","file":"pkg/kubelet/cm/topologymanager/policy.go","code":"func (m HintMerger) Merge() TopologyHint {\n\tdefaultAffinity := m.NUMAInfo.DefaultAffinityMask()\n\n\tvar bestHint *TopologyHint\n\titerateAllProviderTopologyHints(m.Hints, func(permutation []TopologyHint) {\n\t\t// Get the NUMANodeAffinity from each hint in the permutation and see if any\n\t\t// of them encode unpreferred allocations.\n\t\tmergedHint := mergePermutation(defaultAffinity, permutation)\n\n\t\t// Compare the current bestHint with the candidate mergedHint and\n\t\t// update bestHint if appropriate.\n\t\tbestHint = m.compare(bestHint, \u0026mergedHint)\n\t})\n\n\tif bestHint == nil {\n\t\tbestHint = \u0026TopologyHint{defaultAffinity, false}\n\t}\n\n\treturn *bestHint\n}","line":{"from":295,"to":314}} {"id":100006221,"name":"iterateAllProviderTopologyHints","signature":"func iterateAllProviderTopologyHints(allProviderHints [][]TopologyHint, callback func([]TopologyHint))","file":"pkg/kubelet/cm/topologymanager/policy.go","code":"// Iterate over all permutations of hints in 'allProviderHints [][]TopologyHint'.\n//\n// This procedure is implemented as a recursive function over the set of hints\n// in 'allproviderHints[i]'. It applies the function 'callback' to each\n// permutation as it is found. It is the equivalent of:\n//\n// for i := 0; i \u003c len(providerHints[0]); i++\n//\n//\tfor j := 0; j \u003c len(providerHints[1]); j++\n//\t for k := 0; k \u003c len(providerHints[2]); k++\n//\t ...\n//\t for z := 0; z \u003c len(providerHints[-1]); z++\n//\t permutation := []TopologyHint{\n//\t providerHints[0][i],\n//\t providerHints[1][j],\n//\t providerHints[2][k],\n//\t ...\n//\t providerHints[-1][z]\n//\t }\n//\t callback(permutation)\nfunc iterateAllProviderTopologyHints(allProviderHints [][]TopologyHint, callback func([]TopologyHint)) {\n\t// Internal helper function to accumulate the permutation before calling the callback.\n\tvar iterate func(i int, accum []TopologyHint)\n\titerate = func(i int, accum []TopologyHint) {\n\t\t// Base case: we have looped through all providers and have a full permutation.\n\t\tif i == len(allProviderHints) {\n\t\t\tcallback(accum)\n\t\t\treturn\n\t\t}\n\n\t\t// Loop through all hints for provider 'i', and recurse to build the\n\t\t// permutation of this hint with all hints from providers 'i++'.\n\t\tfor j := range allProviderHints[i] {\n\t\t\titerate(i+1, append(accum, allProviderHints[i][j]))\n\t\t}\n\t}\n\titerate(0, []TopologyHint{})\n}","line":{"from":316,"to":353}} {"id":100006222,"name":"NewBestEffortPolicy","signature":"func NewBestEffortPolicy(numaInfo *NUMAInfo, opts PolicyOptions) Policy","file":"pkg/kubelet/cm/topologymanager/policy_best_effort.go","code":"// NewBestEffortPolicy returns best-effort policy.\nfunc NewBestEffortPolicy(numaInfo *NUMAInfo, opts PolicyOptions) Policy {\n\treturn \u0026bestEffortPolicy{numaInfo: numaInfo, opts: opts}\n}","line":{"from":30,"to":33}} {"id":100006223,"name":"Name","signature":"func (p *bestEffortPolicy) Name() string","file":"pkg/kubelet/cm/topologymanager/policy_best_effort.go","code":"func (p *bestEffortPolicy) Name() string {\n\treturn PolicyBestEffort\n}","line":{"from":35,"to":37}} {"id":100006224,"name":"canAdmitPodResult","signature":"func (p *bestEffortPolicy) canAdmitPodResult(hint *TopologyHint) bool","file":"pkg/kubelet/cm/topologymanager/policy_best_effort.go","code":"func (p *bestEffortPolicy) canAdmitPodResult(hint *TopologyHint) bool {\n\treturn true\n}","line":{"from":39,"to":41}} {"id":100006225,"name":"Merge","signature":"func (p *bestEffortPolicy) Merge(providersHints []map[string][]TopologyHint) (TopologyHint, bool)","file":"pkg/kubelet/cm/topologymanager/policy_best_effort.go","code":"func (p *bestEffortPolicy) Merge(providersHints []map[string][]TopologyHint) (TopologyHint, bool) {\n\tfilteredHints := filterProvidersHints(providersHints)\n\tmerger := NewHintMerger(p.numaInfo, filteredHints, p.Name(), p.opts)\n\tbestHint := merger.Merge()\n\tadmit := p.canAdmitPodResult(\u0026bestHint)\n\treturn bestHint, admit\n}","line":{"from":43,"to":49}} {"id":100006226,"name":"NewNonePolicy","signature":"func NewNonePolicy() Policy","file":"pkg/kubelet/cm/topologymanager/policy_none.go","code":"// NewNonePolicy returns none policy.\nfunc NewNonePolicy() Policy {\n\treturn \u0026nonePolicy{}\n}","line":{"from":26,"to":29}} {"id":100006227,"name":"Name","signature":"func (p *nonePolicy) Name() string","file":"pkg/kubelet/cm/topologymanager/policy_none.go","code":"func (p *nonePolicy) Name() string {\n\treturn PolicyNone\n}","line":{"from":31,"to":33}} {"id":100006228,"name":"canAdmitPodResult","signature":"func (p *nonePolicy) canAdmitPodResult(hint *TopologyHint) bool","file":"pkg/kubelet/cm/topologymanager/policy_none.go","code":"func (p *nonePolicy) canAdmitPodResult(hint *TopologyHint) bool {\n\treturn true\n}","line":{"from":35,"to":37}} {"id":100006229,"name":"Merge","signature":"func (p *nonePolicy) Merge(providersHints []map[string][]TopologyHint) (TopologyHint, bool)","file":"pkg/kubelet/cm/topologymanager/policy_none.go","code":"func (p *nonePolicy) Merge(providersHints []map[string][]TopologyHint) (TopologyHint, bool) {\n\treturn TopologyHint{}, p.canAdmitPodResult(nil)\n}","line":{"from":39,"to":41}} {"id":100006230,"name":"CheckPolicyOptionAvailable","signature":"func CheckPolicyOptionAvailable(option string) error","file":"pkg/kubelet/cm/topologymanager/policy_options.go","code":"func CheckPolicyOptionAvailable(option string) error {\n\tif !alphaOptions.Has(option) \u0026\u0026 !betaOptions.Has(option) \u0026\u0026 !stableOptions.Has(option) {\n\t\treturn fmt.Errorf(\"unknown Topology Manager Policy option: %q\", option)\n\t}\n\n\tif alphaOptions.Has(option) \u0026\u0026 !utilfeature.DefaultFeatureGate.Enabled(kubefeatures.TopologyManagerPolicyAlphaOptions) {\n\t\treturn fmt.Errorf(\"Topology Manager Policy Alpha-level Options not enabled, but option %q provided\", option)\n\t}\n\n\tif betaOptions.Has(option) \u0026\u0026 !utilfeature.DefaultFeatureGate.Enabled(kubefeatures.TopologyManagerPolicyBetaOptions) {\n\t\treturn fmt.Errorf(\"Topology Manager Policy Beta-level Options not enabled, but option %q provided\", option)\n\t}\n\n\treturn nil\n}","line":{"from":40,"to":54}} {"id":100006231,"name":"NewPolicyOptions","signature":"func NewPolicyOptions(policyOptions map[string]string) (PolicyOptions, error)","file":"pkg/kubelet/cm/topologymanager/policy_options.go","code":"func NewPolicyOptions(policyOptions map[string]string) (PolicyOptions, error) {\n\topts := PolicyOptions{}\n\tfor name, value := range policyOptions {\n\t\tif err := CheckPolicyOptionAvailable(name); err != nil {\n\t\t\treturn opts, err\n\t\t}\n\n\t\tswitch name {\n\t\tcase PreferClosestNUMANodes:\n\t\t\toptValue, err := strconv.ParseBool(value)\n\t\t\tif err != nil {\n\t\t\t\treturn opts, fmt.Errorf(\"bad value for option %q: %w\", name, err)\n\t\t\t}\n\t\t\topts.PreferClosestNUMA = optValue\n\t\tdefault:\n\t\t\t// this should never be reached, we already detect unknown options,\n\t\t\t// but we keep it as further safety.\n\t\t\treturn opts, fmt.Errorf(\"unsupported topologymanager option: %q (%s)\", name, value)\n\t\t}\n\t}\n\treturn opts, nil\n}","line":{"from":60,"to":81}} {"id":100006232,"name":"NewRestrictedPolicy","signature":"func NewRestrictedPolicy(numaInfo *NUMAInfo, opts PolicyOptions) Policy","file":"pkg/kubelet/cm/topologymanager/policy_restricted.go","code":"// NewRestrictedPolicy returns restricted policy.\nfunc NewRestrictedPolicy(numaInfo *NUMAInfo, opts PolicyOptions) Policy {\n\treturn \u0026restrictedPolicy{bestEffortPolicy{numaInfo: numaInfo, opts: opts}}\n}","line":{"from":28,"to":31}} {"id":100006233,"name":"Name","signature":"func (p *restrictedPolicy) Name() string","file":"pkg/kubelet/cm/topologymanager/policy_restricted.go","code":"func (p *restrictedPolicy) Name() string {\n\treturn PolicyRestricted\n}","line":{"from":33,"to":35}} {"id":100006234,"name":"canAdmitPodResult","signature":"func (p *restrictedPolicy) canAdmitPodResult(hint *TopologyHint) bool","file":"pkg/kubelet/cm/topologymanager/policy_restricted.go","code":"func (p *restrictedPolicy) canAdmitPodResult(hint *TopologyHint) bool {\n\treturn hint.Preferred\n}","line":{"from":37,"to":39}} {"id":100006235,"name":"Merge","signature":"func (p *restrictedPolicy) Merge(providersHints []map[string][]TopologyHint) (TopologyHint, bool)","file":"pkg/kubelet/cm/topologymanager/policy_restricted.go","code":"func (p *restrictedPolicy) Merge(providersHints []map[string][]TopologyHint) (TopologyHint, bool) {\n\tfilteredHints := filterProvidersHints(providersHints)\n\tmerger := NewHintMerger(p.numaInfo, filteredHints, p.Name(), p.opts)\n\tbestHint := merger.Merge()\n\tadmit := p.canAdmitPodResult(\u0026bestHint)\n\treturn bestHint, admit\n}","line":{"from":41,"to":47}} {"id":100006236,"name":"NewSingleNumaNodePolicy","signature":"func NewSingleNumaNodePolicy(numaInfo *NUMAInfo, opts PolicyOptions) Policy","file":"pkg/kubelet/cm/topologymanager/policy_single_numa_node.go","code":"// NewSingleNumaNodePolicy returns single-numa-node policy.\nfunc NewSingleNumaNodePolicy(numaInfo *NUMAInfo, opts PolicyOptions) Policy {\n\treturn \u0026singleNumaNodePolicy{numaInfo: numaInfo, opts: opts}\n}","line":{"from":30,"to":33}} {"id":100006237,"name":"Name","signature":"func (p *singleNumaNodePolicy) Name() string","file":"pkg/kubelet/cm/topologymanager/policy_single_numa_node.go","code":"func (p *singleNumaNodePolicy) Name() string {\n\treturn PolicySingleNumaNode\n}","line":{"from":35,"to":37}} {"id":100006238,"name":"canAdmitPodResult","signature":"func (p *singleNumaNodePolicy) canAdmitPodResult(hint *TopologyHint) bool","file":"pkg/kubelet/cm/topologymanager/policy_single_numa_node.go","code":"func (p *singleNumaNodePolicy) canAdmitPodResult(hint *TopologyHint) bool {\n\treturn hint.Preferred\n}","line":{"from":39,"to":41}} {"id":100006239,"name":"filterSingleNumaHints","signature":"func filterSingleNumaHints(allResourcesHints [][]TopologyHint) [][]TopologyHint","file":"pkg/kubelet/cm/topologymanager/policy_single_numa_node.go","code":"// Return hints that have valid bitmasks with exactly one bit set.\nfunc filterSingleNumaHints(allResourcesHints [][]TopologyHint) [][]TopologyHint {\n\tvar filteredResourcesHints [][]TopologyHint\n\tfor _, oneResourceHints := range allResourcesHints {\n\t\tvar filtered []TopologyHint\n\t\tfor _, hint := range oneResourceHints {\n\t\t\tif hint.NUMANodeAffinity == nil \u0026\u0026 hint.Preferred {\n\t\t\t\tfiltered = append(filtered, hint)\n\t\t\t}\n\t\t\tif hint.NUMANodeAffinity != nil \u0026\u0026 hint.NUMANodeAffinity.Count() == 1 \u0026\u0026 hint.Preferred {\n\t\t\t\tfiltered = append(filtered, hint)\n\t\t\t}\n\t\t}\n\t\tfilteredResourcesHints = append(filteredResourcesHints, filtered)\n\t}\n\treturn filteredResourcesHints\n}","line":{"from":43,"to":59}} {"id":100006240,"name":"Merge","signature":"func (p *singleNumaNodePolicy) Merge(providersHints []map[string][]TopologyHint) (TopologyHint, bool)","file":"pkg/kubelet/cm/topologymanager/policy_single_numa_node.go","code":"func (p *singleNumaNodePolicy) Merge(providersHints []map[string][]TopologyHint) (TopologyHint, bool) {\n\tfilteredHints := filterProvidersHints(providersHints)\n\t// Filter to only include don't cares and hints with a single NUMA node.\n\tsingleNumaHints := filterSingleNumaHints(filteredHints)\n\n\tmerger := NewHintMerger(p.numaInfo, singleNumaHints, p.Name(), p.opts)\n\tbestHint := merger.Merge()\n\n\tif bestHint.NUMANodeAffinity.IsEqual(p.numaInfo.DefaultAffinityMask()) {\n\t\tbestHint = TopologyHint{nil, bestHint.Preferred}\n\t}\n\n\tadmit := p.canAdmitPodResult(\u0026bestHint)\n\treturn bestHint, admit\n}","line":{"from":61,"to":75}} {"id":100006241,"name":"Name","signature":"func (s *scope) Name() string","file":"pkg/kubelet/cm/topologymanager/scope.go","code":"func (s *scope) Name() string {\n\treturn s.name\n}","line":{"from":68,"to":70}} {"id":100006242,"name":"getTopologyHints","signature":"func (s *scope) getTopologyHints(podUID string, containerName string) TopologyHint","file":"pkg/kubelet/cm/topologymanager/scope.go","code":"func (s *scope) getTopologyHints(podUID string, containerName string) TopologyHint {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\treturn s.podTopologyHints[podUID][containerName]\n}","line":{"from":72,"to":76}} {"id":100006243,"name":"setTopologyHints","signature":"func (s *scope) setTopologyHints(podUID string, containerName string, th TopologyHint)","file":"pkg/kubelet/cm/topologymanager/scope.go","code":"func (s *scope) setTopologyHints(podUID string, containerName string, th TopologyHint) {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tif s.podTopologyHints[podUID] == nil {\n\t\ts.podTopologyHints[podUID] = make(map[string]TopologyHint)\n\t}\n\ts.podTopologyHints[podUID][containerName] = th\n}","line":{"from":78,"to":86}} {"id":100006244,"name":"GetAffinity","signature":"func (s *scope) GetAffinity(podUID string, containerName string) TopologyHint","file":"pkg/kubelet/cm/topologymanager/scope.go","code":"func (s *scope) GetAffinity(podUID string, containerName string) TopologyHint {\n\treturn s.getTopologyHints(podUID, containerName)\n}","line":{"from":88,"to":90}} {"id":100006245,"name":"GetPolicy","signature":"func (s *scope) GetPolicy() Policy","file":"pkg/kubelet/cm/topologymanager/scope.go","code":"func (s *scope) GetPolicy() Policy {\n\treturn s.policy\n}","line":{"from":92,"to":94}} {"id":100006246,"name":"AddHintProvider","signature":"func (s *scope) AddHintProvider(h HintProvider)","file":"pkg/kubelet/cm/topologymanager/scope.go","code":"func (s *scope) AddHintProvider(h HintProvider) {\n\ts.hintProviders = append(s.hintProviders, h)\n}","line":{"from":96,"to":98}} {"id":100006247,"name":"AddContainer","signature":"func (s *scope) AddContainer(pod *v1.Pod, container *v1.Container, containerID string)","file":"pkg/kubelet/cm/topologymanager/scope.go","code":"// It would be better to implement this function in topologymanager instead of scope\n// but topologymanager do not track mapping anymore\nfunc (s *scope) AddContainer(pod *v1.Pod, container *v1.Container, containerID string) {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\ts.podMap.Add(string(pod.UID), container.Name, containerID)\n}","line":{"from":100,"to":107}} {"id":100006248,"name":"RemoveContainer","signature":"func (s *scope) RemoveContainer(containerID string) error","file":"pkg/kubelet/cm/topologymanager/scope.go","code":"// It would be better to implement this function in topologymanager instead of scope\n// but topologymanager do not track mapping anymore\nfunc (s *scope) RemoveContainer(containerID string) error {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tklog.InfoS(\"RemoveContainer\", \"containerID\", containerID)\n\t// Get the podUID and containerName associated with the containerID to be removed and remove it\n\tpodUIDString, containerName, err := s.podMap.GetContainerRef(containerID)\n\tif err != nil {\n\t\treturn nil\n\t}\n\ts.podMap.RemoveByContainerID(containerID)\n\n\t// In cases where a container has been restarted, it's possible that the same podUID and\n\t// containerName are already associated with a *different* containerID now. Only remove\n\t// the TopologyHints associated with that podUID and containerName if this is not true\n\tif _, err := s.podMap.GetContainerID(podUIDString, containerName); err != nil {\n\t\tdelete(s.podTopologyHints[podUIDString], containerName)\n\t\tif len(s.podTopologyHints[podUIDString]) == 0 {\n\t\t\tdelete(s.podTopologyHints, podUIDString)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":109,"to":134}} {"id":100006249,"name":"admitPolicyNone","signature":"func (s *scope) admitPolicyNone(pod *v1.Pod) lifecycle.PodAdmitResult","file":"pkg/kubelet/cm/topologymanager/scope.go","code":"func (s *scope) admitPolicyNone(pod *v1.Pod) lifecycle.PodAdmitResult {\n\tfor _, container := range append(pod.Spec.InitContainers, pod.Spec.Containers...) {\n\t\terr := s.allocateAlignedResources(pod, \u0026container)\n\t\tif err != nil {\n\t\t\treturn admission.GetPodAdmitResult(err)\n\t\t}\n\t}\n\treturn admission.GetPodAdmitResult(nil)\n}","line":{"from":136,"to":144}} {"id":100006250,"name":"allocateAlignedResources","signature":"func (s *scope) allocateAlignedResources(pod *v1.Pod, container *v1.Container) error","file":"pkg/kubelet/cm/topologymanager/scope.go","code":"// It would be better to implement this function in topologymanager instead of scope\n// but topologymanager do not track providers anymore\nfunc (s *scope) allocateAlignedResources(pod *v1.Pod, container *v1.Container) error {\n\tfor _, provider := range s.hintProviders {\n\t\terr := provider.Allocate(pod, container)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":146,"to":156}} {"id":100006251,"name":"NewContainerScope","signature":"func NewContainerScope(policy Policy) Scope","file":"pkg/kubelet/cm/topologymanager/scope_container.go","code":"// NewContainerScope returns a container scope.\nfunc NewContainerScope(policy Policy) Scope {\n\treturn \u0026containerScope{\n\t\tscope{\n\t\t\tname: containerTopologyScope,\n\t\t\tpodTopologyHints: podTopologyHints{},\n\t\t\tpolicy: policy,\n\t\t\tpodMap: containermap.NewContainerMap(),\n\t\t},\n\t}\n}","line":{"from":35,"to":45}} {"id":100006252,"name":"Admit","signature":"func (s *containerScope) Admit(pod *v1.Pod) lifecycle.PodAdmitResult","file":"pkg/kubelet/cm/topologymanager/scope_container.go","code":"func (s *containerScope) Admit(pod *v1.Pod) lifecycle.PodAdmitResult {\n\t// Exception - Policy : none\n\tif s.policy.Name() == PolicyNone {\n\t\treturn s.admitPolicyNone(pod)\n\t}\n\n\tfor _, container := range append(pod.Spec.InitContainers, pod.Spec.Containers...) {\n\t\tbestHint, admit := s.calculateAffinity(pod, \u0026container)\n\t\tklog.InfoS(\"Best TopologyHint\", \"bestHint\", bestHint, \"pod\", klog.KObj(pod), \"containerName\", container.Name)\n\n\t\tif !admit {\n\t\t\tmetrics.TopologyManagerAdmissionErrorsTotal.Inc()\n\t\t\treturn admission.GetPodAdmitResult(\u0026TopologyAffinityError{})\n\t\t}\n\t\tklog.InfoS(\"Topology Affinity\", \"bestHint\", bestHint, \"pod\", klog.KObj(pod), \"containerName\", container.Name)\n\t\ts.setTopologyHints(string(pod.UID), container.Name, bestHint)\n\n\t\terr := s.allocateAlignedResources(pod, \u0026container)\n\t\tif err != nil {\n\t\t\tmetrics.TopologyManagerAdmissionErrorsTotal.Inc()\n\t\t\treturn admission.GetPodAdmitResult(err)\n\t\t}\n\t}\n\treturn admission.GetPodAdmitResult(nil)\n}","line":{"from":47,"to":71}} {"id":100006253,"name":"accumulateProvidersHints","signature":"func (s *containerScope) accumulateProvidersHints(pod *v1.Pod, container *v1.Container) []map[string][]TopologyHint","file":"pkg/kubelet/cm/topologymanager/scope_container.go","code":"func (s *containerScope) accumulateProvidersHints(pod *v1.Pod, container *v1.Container) []map[string][]TopologyHint {\n\tvar providersHints []map[string][]TopologyHint\n\n\tfor _, provider := range s.hintProviders {\n\t\t// Get the TopologyHints for a Container from a provider.\n\t\thints := provider.GetTopologyHints(pod, container)\n\t\tprovidersHints = append(providersHints, hints)\n\t\tklog.InfoS(\"TopologyHints\", \"hints\", hints, \"pod\", klog.KObj(pod), \"containerName\", container.Name)\n\t}\n\treturn providersHints\n}","line":{"from":73,"to":83}} {"id":100006254,"name":"calculateAffinity","signature":"func (s *containerScope) calculateAffinity(pod *v1.Pod, container *v1.Container) (TopologyHint, bool)","file":"pkg/kubelet/cm/topologymanager/scope_container.go","code":"func (s *containerScope) calculateAffinity(pod *v1.Pod, container *v1.Container) (TopologyHint, bool) {\n\tprovidersHints := s.accumulateProvidersHints(pod, container)\n\tbestHint, admit := s.policy.Merge(providersHints)\n\tklog.InfoS(\"ContainerTopologyHint\", \"bestHint\", bestHint)\n\treturn bestHint, admit\n}","line":{"from":85,"to":90}} {"id":100006255,"name":"NewPodScope","signature":"func NewPodScope(policy Policy) Scope","file":"pkg/kubelet/cm/topologymanager/scope_pod.go","code":"// NewPodScope returns a pod scope.\nfunc NewPodScope(policy Policy) Scope {\n\treturn \u0026podScope{\n\t\tscope{\n\t\t\tname: podTopologyScope,\n\t\t\tpodTopologyHints: podTopologyHints{},\n\t\t\tpolicy: policy,\n\t\t\tpodMap: containermap.NewContainerMap(),\n\t\t},\n\t}\n}","line":{"from":35,"to":45}} {"id":100006256,"name":"Admit","signature":"func (s *podScope) Admit(pod *v1.Pod) lifecycle.PodAdmitResult","file":"pkg/kubelet/cm/topologymanager/scope_pod.go","code":"func (s *podScope) Admit(pod *v1.Pod) lifecycle.PodAdmitResult {\n\t// Exception - Policy : none\n\tif s.policy.Name() == PolicyNone {\n\t\treturn s.admitPolicyNone(pod)\n\t}\n\n\tbestHint, admit := s.calculateAffinity(pod)\n\tklog.InfoS(\"Best TopologyHint\", \"bestHint\", bestHint, \"pod\", klog.KObj(pod))\n\tif !admit {\n\t\tmetrics.TopologyManagerAdmissionErrorsTotal.Inc()\n\t\treturn admission.GetPodAdmitResult(\u0026TopologyAffinityError{})\n\t}\n\n\tfor _, container := range append(pod.Spec.InitContainers, pod.Spec.Containers...) {\n\t\tklog.InfoS(\"Topology Affinity\", \"bestHint\", bestHint, \"pod\", klog.KObj(pod), \"containerName\", container.Name)\n\t\ts.setTopologyHints(string(pod.UID), container.Name, bestHint)\n\n\t\terr := s.allocateAlignedResources(pod, \u0026container)\n\t\tif err != nil {\n\t\t\tmetrics.TopologyManagerAdmissionErrorsTotal.Inc()\n\t\t\treturn admission.GetPodAdmitResult(err)\n\t\t}\n\t}\n\treturn admission.GetPodAdmitResult(nil)\n}","line":{"from":47,"to":71}} {"id":100006257,"name":"accumulateProvidersHints","signature":"func (s *podScope) accumulateProvidersHints(pod *v1.Pod) []map[string][]TopologyHint","file":"pkg/kubelet/cm/topologymanager/scope_pod.go","code":"func (s *podScope) accumulateProvidersHints(pod *v1.Pod) []map[string][]TopologyHint {\n\tvar providersHints []map[string][]TopologyHint\n\n\tfor _, provider := range s.hintProviders {\n\t\t// Get the TopologyHints for a Pod from a provider.\n\t\thints := provider.GetPodTopologyHints(pod)\n\t\tprovidersHints = append(providersHints, hints)\n\t\tklog.InfoS(\"TopologyHints\", \"hints\", hints, \"pod\", klog.KObj(pod))\n\t}\n\treturn providersHints\n}","line":{"from":73,"to":83}} {"id":100006258,"name":"calculateAffinity","signature":"func (s *podScope) calculateAffinity(pod *v1.Pod) (TopologyHint, bool)","file":"pkg/kubelet/cm/topologymanager/scope_pod.go","code":"func (s *podScope) calculateAffinity(pod *v1.Pod) (TopologyHint, bool) {\n\tprovidersHints := s.accumulateProvidersHints(pod)\n\tbestHint, admit := s.policy.Merge(providersHints)\n\tklog.InfoS(\"PodTopologyHint\", \"bestHint\", bestHint)\n\treturn bestHint, admit\n}","line":{"from":85,"to":90}} {"id":100006259,"name":"Error","signature":"func (e TopologyAffinityError) Error() string","file":"pkg/kubelet/cm/topologymanager/topology_manager.go","code":"func (e TopologyAffinityError) Error() string {\n\treturn \"Resources cannot be allocated with Topology locality\"\n}","line":{"from":48,"to":50}} {"id":100006260,"name":"Type","signature":"func (e TopologyAffinityError) Type() string","file":"pkg/kubelet/cm/topologymanager/topology_manager.go","code":"func (e TopologyAffinityError) Type() string {\n\treturn ErrorTopologyAffinity\n}","line":{"from":52,"to":54}} {"id":100006261,"name":"IsEqual","signature":"func (th *TopologyHint) IsEqual(topologyHint TopologyHint) bool","file":"pkg/kubelet/cm/topologymanager/topology_manager.go","code":"// IsEqual checks if TopologyHint are equal\nfunc (th *TopologyHint) IsEqual(topologyHint TopologyHint) bool {\n\tif th.Preferred == topologyHint.Preferred {\n\t\tif th.NUMANodeAffinity == nil || topologyHint.NUMANodeAffinity == nil {\n\t\t\treturn th.NUMANodeAffinity == topologyHint.NUMANodeAffinity\n\t\t}\n\t\treturn th.NUMANodeAffinity.IsEqual(topologyHint.NUMANodeAffinity)\n\t}\n\treturn false\n}","line":{"from":111,"to":120}} {"id":100006262,"name":"LessThan","signature":"func (th *TopologyHint) LessThan(other TopologyHint) bool","file":"pkg/kubelet/cm/topologymanager/topology_manager.go","code":"// LessThan checks if TopologyHint `a` is less than TopologyHint `b`\n// this means that either `a` is a preferred hint and `b` is not\n// or `a` NUMANodeAffinity attribute is narrower than `b` NUMANodeAffinity attribute.\nfunc (th *TopologyHint) LessThan(other TopologyHint) bool {\n\tif th.Preferred != other.Preferred {\n\t\treturn th.Preferred\n\t}\n\treturn th.NUMANodeAffinity.IsNarrowerThan(other.NUMANodeAffinity)\n}","line":{"from":122,"to":130}} {"id":100006263,"name":"NewManager","signature":"func NewManager(topology []cadvisorapi.Node, topologyPolicyName string, topologyScopeName string, topologyPolicyOptions map[string]string) (Manager, error)","file":"pkg/kubelet/cm/topologymanager/topology_manager.go","code":"// NewManager creates a new TopologyManager based on provided policy and scope\nfunc NewManager(topology []cadvisorapi.Node, topologyPolicyName string, topologyScopeName string, topologyPolicyOptions map[string]string) (Manager, error) {\n\tklog.InfoS(\"Creating topology manager with policy per scope\", \"topologyPolicyName\", topologyPolicyName, \"topologyScopeName\", topologyScopeName)\n\n\topts, err := NewPolicyOptions(topologyPolicyOptions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnumaInfo, err := NewNUMAInfo(topology, opts)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot discover NUMA topology: %w\", err)\n\t}\n\n\tif topologyPolicyName != PolicyNone \u0026\u0026 len(numaInfo.Nodes) \u003e maxAllowableNUMANodes {\n\t\treturn nil, fmt.Errorf(\"unsupported on machines with more than %v NUMA Nodes\", maxAllowableNUMANodes)\n\t}\n\n\tvar policy Policy\n\tswitch topologyPolicyName {\n\n\tcase PolicyNone:\n\t\tpolicy = NewNonePolicy()\n\n\tcase PolicyBestEffort:\n\t\tpolicy = NewBestEffortPolicy(numaInfo, opts)\n\n\tcase PolicyRestricted:\n\t\tpolicy = NewRestrictedPolicy(numaInfo, opts)\n\n\tcase PolicySingleNumaNode:\n\t\tpolicy = NewSingleNumaNodePolicy(numaInfo, opts)\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown policy: \\\"%s\\\"\", topologyPolicyName)\n\t}\n\n\tvar scope Scope\n\tswitch topologyScopeName {\n\n\tcase containerTopologyScope:\n\t\tscope = NewContainerScope(policy)\n\n\tcase podTopologyScope:\n\t\tscope = NewPodScope(policy)\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown scope: \\\"%s\\\"\", topologyScopeName)\n\t}\n\n\tmanager := \u0026manager{\n\t\tscope: scope,\n\t}\n\n\treturn manager, nil\n}","line":{"from":134,"to":189}} {"id":100006264,"name":"GetAffinity","signature":"func (m *manager) GetAffinity(podUID string, containerName string) TopologyHint","file":"pkg/kubelet/cm/topologymanager/topology_manager.go","code":"func (m *manager) GetAffinity(podUID string, containerName string) TopologyHint {\n\treturn m.scope.GetAffinity(podUID, containerName)\n}","line":{"from":191,"to":193}} {"id":100006265,"name":"GetPolicy","signature":"func (m *manager) GetPolicy() Policy","file":"pkg/kubelet/cm/topologymanager/topology_manager.go","code":"func (m *manager) GetPolicy() Policy {\n\treturn m.scope.GetPolicy()\n}","line":{"from":195,"to":197}} {"id":100006266,"name":"AddHintProvider","signature":"func (m *manager) AddHintProvider(h HintProvider)","file":"pkg/kubelet/cm/topologymanager/topology_manager.go","code":"func (m *manager) AddHintProvider(h HintProvider) {\n\tm.scope.AddHintProvider(h)\n}","line":{"from":199,"to":201}} {"id":100006267,"name":"AddContainer","signature":"func (m *manager) AddContainer(pod *v1.Pod, container *v1.Container, containerID string)","file":"pkg/kubelet/cm/topologymanager/topology_manager.go","code":"func (m *manager) AddContainer(pod *v1.Pod, container *v1.Container, containerID string) {\n\tm.scope.AddContainer(pod, container, containerID)\n}","line":{"from":203,"to":205}} {"id":100006268,"name":"RemoveContainer","signature":"func (m *manager) RemoveContainer(containerID string) error","file":"pkg/kubelet/cm/topologymanager/topology_manager.go","code":"func (m *manager) RemoveContainer(containerID string) error {\n\treturn m.scope.RemoveContainer(containerID)\n}","line":{"from":207,"to":209}} {"id":100006269,"name":"Admit","signature":"func (m *manager) Admit(attrs *lifecycle.PodAdmitAttributes) lifecycle.PodAdmitResult","file":"pkg/kubelet/cm/topologymanager/topology_manager.go","code":"func (m *manager) Admit(attrs *lifecycle.PodAdmitAttributes) lifecycle.PodAdmitResult {\n\tklog.InfoS(\"Topology Admit Handler\")\n\tmetrics.TopologyManagerAdmissionRequestsTotal.Inc()\n\n\tstartTime := time.Now()\n\tpodAdmitResult := m.scope.Admit(attrs.Pod)\n\tmetrics.TopologyManagerAdmissionDuration.Observe(float64(time.Since(startTime).Milliseconds()))\n\n\treturn podAdmitResult\n}","line":{"from":211,"to":220}} {"id":100006270,"name":"GetPids","signature":"func GetPids(cgroupPath string) ([]int, error)","file":"pkg/kubelet/cm/util/cgroups_linux.go","code":"// GetPids gets pids of the desired cgroup\n// Forked from opencontainers/runc/libcontainer/cgroup/fs.Manager.GetPids()\nfunc GetPids(cgroupPath string) ([]int, error) {\n\tdir := \"\"\n\n\tif libcontainercgroups.IsCgroup2UnifiedMode() {\n\t\tpath, err := filepath.Rel(\"/\", cgroupPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdir = filepath.Join(CgroupRoot, path)\n\t} else {\n\t\tvar err error\n\t\tdir, err = getCgroupV1Path(cgroupPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn libcontainercgroups.GetPids(dir)\n}","line":{"from":31,"to":50}} {"id":100006271,"name":"getCgroupV1Path","signature":"func getCgroupV1Path(cgroupPath string) (string, error)","file":"pkg/kubelet/cm/util/cgroups_linux.go","code":"// getCgroupV1Path gets the file path to the \"devices\" subsystem of the desired cgroup.\n// cgroupPath is the path in the cgroup hierarchy.\nfunc getCgroupV1Path(cgroupPath string) (string, error) {\n\tcgroupPath = libcontainerutils.CleanPath(cgroupPath)\n\n\tmnt, root, err := libcontainercgroups.FindCgroupMountpointAndRoot(cgroupPath, \"devices\")\n\t// If we didn't mount the subsystem, there is no point we make the path.\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// If the cgroup name/path is absolute do not look relative to the cgroup of the init process.\n\tif filepath.IsAbs(cgroupPath) {\n\t\t// Sometimes subsystems can be mounted together as 'cpu,cpuacct'.\n\t\treturn filepath.Join(root, mnt, cgroupPath), nil\n\t}\n\n\tparentPath, err := getCgroupV1ParentPath(mnt, root)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn filepath.Join(parentPath, cgroupPath), nil\n}","line":{"from":52,"to":75}} {"id":100006272,"name":"getCgroupV1ParentPath","signature":"func getCgroupV1ParentPath(mountpoint, root string) (string, error)","file":"pkg/kubelet/cm/util/cgroups_linux.go","code":"// getCgroupV1ParentPath gets the parent filepath to this cgroup, for resolving relative cgroup paths.\nfunc getCgroupV1ParentPath(mountpoint, root string) (string, error) {\n\t// Use GetThisCgroupDir instead of GetInitCgroupDir, because the creating\n\t// process could in container and shared pid namespace with host, and\n\t// /proc/1/cgroup could point to whole other world of cgroups.\n\tinitPath, err := libcontainercgroups.GetOwnCgroup(\"devices\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// This is needed for nested containers, because in /proc/self/cgroup we\n\t// see paths from host, which don't exist in container.\n\trelDir, err := filepath.Rel(root, initPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Join(mountpoint, relDir), nil\n}","line":{"from":77,"to":93}} {"id":100006273,"name":"GetPids","signature":"func GetPids(cgroupPath string) ([]int, error)","file":"pkg/kubelet/cm/util/cgroups_unsupported.go","code":"// GetPids gets pids of the desired cgroup\nfunc GetPids(cgroupPath string) ([]int, error) {\n\treturn nil, nil\n}","line":{"from":22,"to":25}} {"id":100006274,"name":"NewSourceApiserver","signature":"func NewSourceApiserver(c clientset.Interface, nodeName types.NodeName, nodeHasSynced func() bool, updates chan\u003c- interface{})","file":"pkg/kubelet/config/apiserver.go","code":"// NewSourceApiserver creates a config source that watches and pulls from the apiserver.\nfunc NewSourceApiserver(c clientset.Interface, nodeName types.NodeName, nodeHasSynced func() bool, updates chan\u003c- interface{}) {\n\tlw := cache.NewListWatchFromClient(c.CoreV1().RESTClient(), \"pods\", metav1.NamespaceAll, fields.OneTermEqualSelector(\"spec.nodeName\", string(nodeName)))\n\n\t// The Reflector responsible for watching pods at the apiserver should be run only after\n\t// the node sync with the apiserver has completed.\n\tklog.InfoS(\"Waiting for node sync before watching apiserver pods\")\n\tgo func() {\n\t\tfor {\n\t\t\tif nodeHasSynced() {\n\t\t\t\tklog.V(4).InfoS(\"node sync completed\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(WaitForAPIServerSyncPeriod)\n\t\t\tklog.V(4).InfoS(\"node sync has not completed yet\")\n\t\t}\n\t\tklog.InfoS(\"Watching apiserver\")\n\t\tnewSourceApiserverFromLW(lw, updates)\n\t}()\n}","line":{"from":36,"to":55}} {"id":100006275,"name":"newSourceApiserverFromLW","signature":"func newSourceApiserverFromLW(lw cache.ListerWatcher, updates chan\u003c- interface{})","file":"pkg/kubelet/config/apiserver.go","code":"// newSourceApiserverFromLW holds creates a config source that watches and pulls from the apiserver.\nfunc newSourceApiserverFromLW(lw cache.ListerWatcher, updates chan\u003c- interface{}) {\n\tsend := func(objs []interface{}) {\n\t\tvar pods []*v1.Pod\n\t\tfor _, o := range objs {\n\t\t\tpods = append(pods, o.(*v1.Pod))\n\t\t}\n\t\tupdates \u003c- kubetypes.PodUpdate{Pods: pods, Op: kubetypes.SET, Source: kubetypes.ApiserverSource}\n\t}\n\tr := cache.NewReflector(lw, \u0026v1.Pod{}, cache.NewUndeltaStore(send, cache.MetaNamespaceKeyFunc), 0)\n\tgo r.Run(wait.NeverStop)\n}","line":{"from":57,"to":68}} {"id":100006276,"name":"generatePodName","signature":"func generatePodName(name string, nodeName types.NodeName) string","file":"pkg/kubelet/config/common.go","code":"// Generate a pod name that is unique among nodes by appending the nodeName.\nfunc generatePodName(name string, nodeName types.NodeName) string {\n\treturn fmt.Sprintf(\"%s-%s\", name, strings.ToLower(string(nodeName)))\n}","line":{"from":51,"to":54}} {"id":100006277,"name":"applyDefaults","signature":"func applyDefaults(pod *api.Pod, source string, isFile bool, nodeName types.NodeName) error","file":"pkg/kubelet/config/common.go","code":"func applyDefaults(pod *api.Pod, source string, isFile bool, nodeName types.NodeName) error {\n\tif len(pod.UID) == 0 {\n\t\thasher := md5.New()\n\t\thash.DeepHashObject(hasher, pod)\n\t\t// DeepHashObject resets the hash, so we should write the pod source\n\t\t// information AFTER it.\n\t\tif isFile {\n\t\t\tfmt.Fprintf(hasher, \"host:%s\", nodeName)\n\t\t\tfmt.Fprintf(hasher, \"file:%s\", source)\n\t\t} else {\n\t\t\tfmt.Fprintf(hasher, \"url:%s\", source)\n\t\t}\n\t\tpod.UID = types.UID(hex.EncodeToString(hasher.Sum(nil)[0:]))\n\t\tklog.V(5).InfoS(\"Generated UID\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID, \"source\", source)\n\t}\n\n\tpod.Name = generatePodName(pod.Name, nodeName)\n\tklog.V(5).InfoS(\"Generated pod name\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID, \"source\", source)\n\n\tif pod.Namespace == \"\" {\n\t\tpod.Namespace = metav1.NamespaceDefault\n\t}\n\tklog.V(5).InfoS(\"Set namespace for pod\", \"pod\", klog.KObj(pod), \"source\", source)\n\n\t// Set the Host field to indicate this pod is scheduled on the current node.\n\tpod.Spec.NodeName = string(nodeName)\n\n\tif pod.Annotations == nil {\n\t\tpod.Annotations = make(map[string]string)\n\t}\n\t// The generated UID is the hash of the file.\n\tpod.Annotations[kubetypes.ConfigHashAnnotationKey] = string(pod.UID)\n\n\tif isFile {\n\t\t// Applying the default Taint tolerations to static pods,\n\t\t// so they are not evicted when there are node problems.\n\t\thelper.AddOrUpdateTolerationInPod(pod, \u0026api.Toleration{\n\t\t\tOperator: \"Exists\",\n\t\t\tEffect: api.TaintEffectNoExecute,\n\t\t})\n\t}\n\n\t// Set the default status to pending.\n\tpod.Status.Phase = api.PodPending\n\treturn nil\n}","line":{"from":56,"to":101}} {"id":100006278,"name":"tryDecodeSinglePod","signature":"func tryDecodeSinglePod(data []byte, defaultFn defaultFunc) (parsed bool, pod *v1.Pod, err error)","file":"pkg/kubelet/config/common.go","code":"// tryDecodeSinglePod takes data and tries to extract valid Pod config information from it.\nfunc tryDecodeSinglePod(data []byte, defaultFn defaultFunc) (parsed bool, pod *v1.Pod, err error) {\n\t// JSON is valid YAML, so this should work for everything.\n\tjson, err := utilyaml.ToJSON(data)\n\tif err != nil {\n\t\treturn false, nil, err\n\t}\n\tobj, err := runtime.Decode(legacyscheme.Codecs.UniversalDecoder(), json)\n\tif err != nil {\n\t\treturn false, pod, err\n\t}\n\n\tnewPod, ok := obj.(*api.Pod)\n\t// Check whether the object could be converted to single pod.\n\tif !ok {\n\t\treturn false, pod, fmt.Errorf(\"invalid pod: %#v\", obj)\n\t}\n\n\t// Apply default values and validate the pod.\n\tif err = defaultFn(newPod); err != nil {\n\t\treturn true, pod, err\n\t}\n\tif errs := validation.ValidatePodCreate(newPod, validation.PodValidationOptions{}); len(errs) \u003e 0 {\n\t\treturn true, pod, fmt.Errorf(\"invalid pod: %v\", errs)\n\t}\n\tv1Pod := \u0026v1.Pod{}\n\tif err := k8s_api_v1.Convert_core_Pod_To_v1_Pod(newPod, v1Pod, nil); err != nil {\n\t\tklog.ErrorS(err, \"Pod failed to convert to v1\", \"pod\", klog.KObj(newPod))\n\t\treturn true, nil, err\n\t}\n\treturn true, v1Pod, nil\n}","line":{"from":105,"to":136}} {"id":100006279,"name":"tryDecodePodList","signature":"func tryDecodePodList(data []byte, defaultFn defaultFunc) (parsed bool, pods v1.PodList, err error)","file":"pkg/kubelet/config/common.go","code":"func tryDecodePodList(data []byte, defaultFn defaultFunc) (parsed bool, pods v1.PodList, err error) {\n\tobj, err := runtime.Decode(legacyscheme.Codecs.UniversalDecoder(), data)\n\tif err != nil {\n\t\treturn false, pods, err\n\t}\n\n\tnewPods, ok := obj.(*api.PodList)\n\t// Check whether the object could be converted to list of pods.\n\tif !ok {\n\t\terr = fmt.Errorf(\"invalid pods list: %#v\", obj)\n\t\treturn false, pods, err\n\t}\n\n\t// Apply default values and validate pods.\n\tfor i := range newPods.Items {\n\t\tnewPod := \u0026newPods.Items[i]\n\t\tif err = defaultFn(newPod); err != nil {\n\t\t\treturn true, pods, err\n\t\t}\n\t\tif errs := validation.ValidatePodCreate(newPod, validation.PodValidationOptions{}); len(errs) \u003e 0 {\n\t\t\terr = fmt.Errorf(\"invalid pod: %v\", errs)\n\t\t\treturn true, pods, err\n\t\t}\n\t}\n\tv1Pods := \u0026v1.PodList{}\n\tif err := k8s_api_v1.Convert_core_PodList_To_v1_PodList(newPods, v1Pods, nil); err != nil {\n\t\treturn true, pods, err\n\t}\n\treturn true, *v1Pods, err\n}","line":{"from":138,"to":167}} {"id":100006280,"name":"NewPodConfig","signature":"func NewPodConfig(mode PodConfigNotificationMode, recorder record.EventRecorder, startupSLIObserver podStartupSLIObserver) *PodConfig","file":"pkg/kubelet/config/config.go","code":"// NewPodConfig creates an object that can merge many configuration sources into a stream\n// of normalized updates to a pod configuration.\nfunc NewPodConfig(mode PodConfigNotificationMode, recorder record.EventRecorder, startupSLIObserver podStartupSLIObserver) *PodConfig {\n\tupdates := make(chan kubetypes.PodUpdate, 50)\n\tstorage := newPodStorage(updates, mode, recorder, startupSLIObserver)\n\tpodConfig := \u0026PodConfig{\n\t\tpods: storage,\n\t\tmux: config.NewMux(storage),\n\t\tupdates: updates,\n\t\tsources: sets.String{},\n\t}\n\treturn podConfig\n}","line":{"from":74,"to":86}} {"id":100006281,"name":"Channel","signature":"func (c *PodConfig) Channel(ctx context.Context, source string) chan\u003c- interface{}","file":"pkg/kubelet/config/config.go","code":"// Channel creates or returns a config source channel. The channel\n// only accepts PodUpdates\nfunc (c *PodConfig) Channel(ctx context.Context, source string) chan\u003c- interface{} {\n\tc.sourcesLock.Lock()\n\tdefer c.sourcesLock.Unlock()\n\tc.sources.Insert(source)\n\treturn c.mux.ChannelWithContext(ctx, source)\n}","line":{"from":88,"to":95}} {"id":100006282,"name":"SeenAllSources","signature":"func (c *PodConfig) SeenAllSources(seenSources sets.String) bool","file":"pkg/kubelet/config/config.go","code":"// SeenAllSources returns true if seenSources contains all sources in the\n// config, and also this config has received a SET message from each source.\nfunc (c *PodConfig) SeenAllSources(seenSources sets.String) bool {\n\tif c.pods == nil {\n\t\treturn false\n\t}\n\tc.sourcesLock.Lock()\n\tdefer c.sourcesLock.Unlock()\n\tklog.V(5).InfoS(\"Looking for sources, have seen\", \"sources\", c.sources.List(), \"seenSources\", seenSources)\n\treturn seenSources.HasAll(c.sources.List()...) \u0026\u0026 c.pods.seenSources(c.sources.List()...)\n}","line":{"from":97,"to":107}} {"id":100006283,"name":"Updates","signature":"func (c *PodConfig) Updates() \u003c-chan kubetypes.PodUpdate","file":"pkg/kubelet/config/config.go","code":"// Updates returns a channel of updates to the configuration, properly denormalized.\nfunc (c *PodConfig) Updates() \u003c-chan kubetypes.PodUpdate {\n\treturn c.updates\n}","line":{"from":109,"to":112}} {"id":100006284,"name":"Sync","signature":"func (c *PodConfig) Sync()","file":"pkg/kubelet/config/config.go","code":"// Sync requests the full configuration be delivered to the update channel.\nfunc (c *PodConfig) Sync() {\n\tc.pods.Sync()\n}","line":{"from":114,"to":117}} {"id":100006285,"name":"newPodStorage","signature":"func newPodStorage(updates chan\u003c- kubetypes.PodUpdate, mode PodConfigNotificationMode, recorder record.EventRecorder, startupSLIObserver podStartupSLIObserver) *podStorage","file":"pkg/kubelet/config/config.go","code":"// TODO: PodConfigNotificationMode could be handled by a listener to the updates channel\n// in the future, especially with multiple listeners.\n// TODO: allow initialization of the current state of the store with snapshotted version.\nfunc newPodStorage(updates chan\u003c- kubetypes.PodUpdate, mode PodConfigNotificationMode, recorder record.EventRecorder, startupSLIObserver podStartupSLIObserver) *podStorage {\n\treturn \u0026podStorage{\n\t\tpods: make(map[string]map[types.UID]*v1.Pod),\n\t\tmode: mode,\n\t\tupdates: updates,\n\t\tsourcesSeen: sets.String{},\n\t\trecorder: recorder,\n\t\tstartupSLIObserver: startupSLIObserver,\n\t}\n}","line":{"from":144,"to":156}} {"id":100006286,"name":"Merge","signature":"func (s *podStorage) Merge(source string, change interface{}) error","file":"pkg/kubelet/config/config.go","code":"// Merge normalizes a set of incoming changes from different sources into a map of all Pods\n// and ensures that redundant changes are filtered out, and then pushes zero or more minimal\n// updates onto the update channel. Ensures that updates are delivered in order.\nfunc (s *podStorage) Merge(source string, change interface{}) error {\n\ts.updateLock.Lock()\n\tdefer s.updateLock.Unlock()\n\n\tseenBefore := s.sourcesSeen.Has(source)\n\tadds, updates, deletes, removes, reconciles := s.merge(source, change)\n\tfirstSet := !seenBefore \u0026\u0026 s.sourcesSeen.Has(source)\n\n\t// deliver update notifications\n\tswitch s.mode {\n\tcase PodConfigNotificationIncremental:\n\t\tif len(removes.Pods) \u003e 0 {\n\t\t\ts.updates \u003c- *removes\n\t\t}\n\t\tif len(adds.Pods) \u003e 0 {\n\t\t\ts.updates \u003c- *adds\n\t\t}\n\t\tif len(updates.Pods) \u003e 0 {\n\t\t\ts.updates \u003c- *updates\n\t\t}\n\t\tif len(deletes.Pods) \u003e 0 {\n\t\t\ts.updates \u003c- *deletes\n\t\t}\n\t\tif firstSet \u0026\u0026 len(adds.Pods) == 0 \u0026\u0026 len(updates.Pods) == 0 \u0026\u0026 len(deletes.Pods) == 0 {\n\t\t\t// Send an empty update when first seeing the source and there are\n\t\t\t// no ADD or UPDATE or DELETE pods from the source. This signals kubelet that\n\t\t\t// the source is ready.\n\t\t\ts.updates \u003c- *adds\n\t\t}\n\t\t// Only add reconcile support here, because kubelet doesn't support Snapshot update now.\n\t\tif len(reconciles.Pods) \u003e 0 {\n\t\t\ts.updates \u003c- *reconciles\n\t\t}\n\n\tcase PodConfigNotificationSnapshotAndUpdates:\n\t\tif len(removes.Pods) \u003e 0 || len(adds.Pods) \u003e 0 || firstSet {\n\t\t\ts.updates \u003c- kubetypes.PodUpdate{Pods: s.MergedState().([]*v1.Pod), Op: kubetypes.SET, Source: source}\n\t\t}\n\t\tif len(updates.Pods) \u003e 0 {\n\t\t\ts.updates \u003c- *updates\n\t\t}\n\t\tif len(deletes.Pods) \u003e 0 {\n\t\t\ts.updates \u003c- *deletes\n\t\t}\n\n\tcase PodConfigNotificationSnapshot:\n\t\tif len(updates.Pods) \u003e 0 || len(deletes.Pods) \u003e 0 || len(adds.Pods) \u003e 0 || len(removes.Pods) \u003e 0 || firstSet {\n\t\t\ts.updates \u003c- kubetypes.PodUpdate{Pods: s.MergedState().([]*v1.Pod), Op: kubetypes.SET, Source: source}\n\t\t}\n\n\tcase PodConfigNotificationUnknown:\n\t\tfallthrough\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unsupported PodConfigNotificationMode: %#v\", s.mode))\n\t}\n\n\treturn nil\n}","line":{"from":158,"to":218}} {"id":100006287,"name":"merge","signature":"func (s *podStorage) merge(source string, change interface{}) (adds, updates, deletes, removes, reconciles *kubetypes.PodUpdate)","file":"pkg/kubelet/config/config.go","code":"func (s *podStorage) merge(source string, change interface{}) (adds, updates, deletes, removes, reconciles *kubetypes.PodUpdate) {\n\ts.podLock.Lock()\n\tdefer s.podLock.Unlock()\n\n\taddPods := []*v1.Pod{}\n\tupdatePods := []*v1.Pod{}\n\tdeletePods := []*v1.Pod{}\n\tremovePods := []*v1.Pod{}\n\treconcilePods := []*v1.Pod{}\n\n\tpods := s.pods[source]\n\tif pods == nil {\n\t\tpods = make(map[types.UID]*v1.Pod)\n\t}\n\n\t// updatePodFunc is the local function which updates the pod cache *oldPods* with new pods *newPods*.\n\t// After updated, new pod will be stored in the pod cache *pods*.\n\t// Notice that *pods* and *oldPods* could be the same cache.\n\tupdatePodsFunc := func(newPods []*v1.Pod, oldPods, pods map[types.UID]*v1.Pod) {\n\t\tfiltered := filterInvalidPods(newPods, source, s.recorder)\n\t\tfor _, ref := range filtered {\n\t\t\t// Annotate the pod with the source before any comparison.\n\t\t\tif ref.Annotations == nil {\n\t\t\t\tref.Annotations = make(map[string]string)\n\t\t\t}\n\t\t\tref.Annotations[kubetypes.ConfigSourceAnnotationKey] = source\n\t\t\t// ignore static pods\n\t\t\tif !kubetypes.IsStaticPod(ref) {\n\t\t\t\ts.startupSLIObserver.ObservedPodOnWatch(ref, time.Now())\n\t\t\t}\n\t\t\tif existing, found := oldPods[ref.UID]; found {\n\t\t\t\tpods[ref.UID] = existing\n\t\t\t\tneedUpdate, needReconcile, needGracefulDelete := checkAndUpdatePod(existing, ref)\n\t\t\t\tif needUpdate {\n\t\t\t\t\tupdatePods = append(updatePods, existing)\n\t\t\t\t} else if needReconcile {\n\t\t\t\t\treconcilePods = append(reconcilePods, existing)\n\t\t\t\t} else if needGracefulDelete {\n\t\t\t\t\tdeletePods = append(deletePods, existing)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\trecordFirstSeenTime(ref)\n\t\t\tpods[ref.UID] = ref\n\t\t\taddPods = append(addPods, ref)\n\t\t}\n\t}\n\n\tupdate := change.(kubetypes.PodUpdate)\n\tswitch update.Op {\n\tcase kubetypes.ADD, kubetypes.UPDATE, kubetypes.DELETE:\n\t\tif update.Op == kubetypes.ADD {\n\t\t\tklog.V(4).InfoS(\"Adding new pods from source\", \"source\", source, \"pods\", klog.KObjSlice(update.Pods))\n\t\t} else if update.Op == kubetypes.DELETE {\n\t\t\tklog.V(4).InfoS(\"Gracefully deleting pods from source\", \"source\", source, \"pods\", klog.KObjSlice(update.Pods))\n\t\t} else {\n\t\t\tklog.V(4).InfoS(\"Updating pods from source\", \"source\", source, \"pods\", klog.KObjSlice(update.Pods))\n\t\t}\n\t\tupdatePodsFunc(update.Pods, pods, pods)\n\n\tcase kubetypes.REMOVE:\n\t\tklog.V(4).InfoS(\"Removing pods from source\", \"source\", source, \"pods\", klog.KObjSlice(update.Pods))\n\t\tfor _, value := range update.Pods {\n\t\t\tif existing, found := pods[value.UID]; found {\n\t\t\t\t// this is a delete\n\t\t\t\tdelete(pods, value.UID)\n\t\t\t\tremovePods = append(removePods, existing)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// this is a no-op\n\t\t}\n\n\tcase kubetypes.SET:\n\t\tklog.V(4).InfoS(\"Setting pods for source\", \"source\", source)\n\t\ts.markSourceSet(source)\n\t\t// Clear the old map entries by just creating a new map\n\t\toldPods := pods\n\t\tpods = make(map[types.UID]*v1.Pod)\n\t\tupdatePodsFunc(update.Pods, oldPods, pods)\n\t\tfor uid, existing := range oldPods {\n\t\t\tif _, found := pods[uid]; !found {\n\t\t\t\t// this is a delete\n\t\t\t\tremovePods = append(removePods, existing)\n\t\t\t}\n\t\t}\n\n\tdefault:\n\t\tklog.InfoS(\"Received invalid update type\", \"type\", update)\n\n\t}\n\n\ts.pods[source] = pods\n\n\tadds = \u0026kubetypes.PodUpdate{Op: kubetypes.ADD, Pods: copyPods(addPods), Source: source}\n\tupdates = \u0026kubetypes.PodUpdate{Op: kubetypes.UPDATE, Pods: copyPods(updatePods), Source: source}\n\tdeletes = \u0026kubetypes.PodUpdate{Op: kubetypes.DELETE, Pods: copyPods(deletePods), Source: source}\n\tremoves = \u0026kubetypes.PodUpdate{Op: kubetypes.REMOVE, Pods: copyPods(removePods), Source: source}\n\treconciles = \u0026kubetypes.PodUpdate{Op: kubetypes.RECONCILE, Pods: copyPods(reconcilePods), Source: source}\n\n\treturn adds, updates, deletes, removes, reconciles\n}","line":{"from":220,"to":320}} {"id":100006288,"name":"markSourceSet","signature":"func (s *podStorage) markSourceSet(source string)","file":"pkg/kubelet/config/config.go","code":"func (s *podStorage) markSourceSet(source string) {\n\ts.sourcesSeenLock.Lock()\n\tdefer s.sourcesSeenLock.Unlock()\n\ts.sourcesSeen.Insert(source)\n}","line":{"from":322,"to":326}} {"id":100006289,"name":"seenSources","signature":"func (s *podStorage) seenSources(sources ...string) bool","file":"pkg/kubelet/config/config.go","code":"func (s *podStorage) seenSources(sources ...string) bool {\n\ts.sourcesSeenLock.RLock()\n\tdefer s.sourcesSeenLock.RUnlock()\n\treturn s.sourcesSeen.HasAll(sources...)\n}","line":{"from":328,"to":332}} {"id":100006290,"name":"filterInvalidPods","signature":"func filterInvalidPods(pods []*v1.Pod, source string, recorder record.EventRecorder) (filtered []*v1.Pod)","file":"pkg/kubelet/config/config.go","code":"func filterInvalidPods(pods []*v1.Pod, source string, recorder record.EventRecorder) (filtered []*v1.Pod) {\n\tnames := sets.String{}\n\tfor i, pod := range pods {\n\t\t// Pods from each source are assumed to have passed validation individually.\n\t\t// This function only checks if there is any naming conflict.\n\t\tname := kubecontainer.GetPodFullName(pod)\n\t\tif names.Has(name) {\n\t\t\tklog.InfoS(\"Pod failed validation due to duplicate pod name, ignoring\", \"index\", i, \"pod\", klog.KObj(pod), \"source\", source)\n\t\t\trecorder.Eventf(pod, v1.EventTypeWarning, events.FailedValidation, \"Error validating pod %s from %s due to duplicate pod name %q, ignoring\", format.Pod(pod), source, pod.Name)\n\t\t\tcontinue\n\t\t} else {\n\t\t\tnames.Insert(name)\n\t\t}\n\n\t\tfiltered = append(filtered, pod)\n\t}\n\treturn\n}","line":{"from":334,"to":351}} {"id":100006291,"name":"isLocalAnnotationKey","signature":"func isLocalAnnotationKey(key string) bool","file":"pkg/kubelet/config/config.go","code":"func isLocalAnnotationKey(key string) bool {\n\tfor _, localKey := range localAnnotations {\n\t\tif key == localKey {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":360,"to":367}} {"id":100006292,"name":"isAnnotationMapEqual","signature":"func isAnnotationMapEqual(existingMap, candidateMap map[string]string) bool","file":"pkg/kubelet/config/config.go","code":"// isAnnotationMapEqual returns true if the existing annotation Map is equal to candidate except\n// for local annotations.\nfunc isAnnotationMapEqual(existingMap, candidateMap map[string]string) bool {\n\tif candidateMap == nil {\n\t\tcandidateMap = make(map[string]string)\n\t}\n\tfor k, v := range candidateMap {\n\t\tif isLocalAnnotationKey(k) {\n\t\t\tcontinue\n\t\t}\n\t\tif existingValue, ok := existingMap[k]; ok \u0026\u0026 existingValue == v {\n\t\t\tcontinue\n\t\t}\n\t\treturn false\n\t}\n\tfor k := range existingMap {\n\t\tif isLocalAnnotationKey(k) {\n\t\t\tcontinue\n\t\t}\n\t\t// stale entry in existing map.\n\t\tif _, exists := candidateMap[k]; !exists {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":369,"to":394}} {"id":100006293,"name":"recordFirstSeenTime","signature":"func recordFirstSeenTime(pod *v1.Pod)","file":"pkg/kubelet/config/config.go","code":"// recordFirstSeenTime records the first seen time of this pod.\nfunc recordFirstSeenTime(pod *v1.Pod) {\n\tklog.V(4).InfoS(\"Receiving a new pod\", \"pod\", klog.KObj(pod))\n\tpod.Annotations[kubetypes.ConfigFirstSeenAnnotationKey] = kubetypes.NewTimestamp().GetString()\n}","line":{"from":396,"to":400}} {"id":100006294,"name":"updateAnnotations","signature":"func updateAnnotations(existing, ref *v1.Pod)","file":"pkg/kubelet/config/config.go","code":"// updateAnnotations returns an Annotation map containing the api annotation map plus\n// locally managed annotations\nfunc updateAnnotations(existing, ref *v1.Pod) {\n\tannotations := make(map[string]string, len(ref.Annotations)+len(localAnnotations))\n\tfor k, v := range ref.Annotations {\n\t\tannotations[k] = v\n\t}\n\tfor _, k := range localAnnotations {\n\t\tif v, ok := existing.Annotations[k]; ok {\n\t\t\tannotations[k] = v\n\t\t}\n\t}\n\texisting.Annotations = annotations\n}","line":{"from":402,"to":415}} {"id":100006295,"name":"podsDifferSemantically","signature":"func podsDifferSemantically(existing, ref *v1.Pod) bool","file":"pkg/kubelet/config/config.go","code":"func podsDifferSemantically(existing, ref *v1.Pod) bool {\n\tif reflect.DeepEqual(existing.Spec, ref.Spec) \u0026\u0026\n\t\treflect.DeepEqual(existing.Labels, ref.Labels) \u0026\u0026\n\t\treflect.DeepEqual(existing.DeletionTimestamp, ref.DeletionTimestamp) \u0026\u0026\n\t\treflect.DeepEqual(existing.DeletionGracePeriodSeconds, ref.DeletionGracePeriodSeconds) \u0026\u0026\n\t\tisAnnotationMapEqual(existing.Annotations, ref.Annotations) {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":417,"to":426}} {"id":100006296,"name":"checkAndUpdatePod","signature":"func checkAndUpdatePod(existing, ref *v1.Pod) (needUpdate, needReconcile, needGracefulDelete bool)","file":"pkg/kubelet/config/config.go","code":"// checkAndUpdatePod updates existing, and:\n// - if ref makes a meaningful change, returns needUpdate=true\n// - if ref makes a meaningful change, and this change is graceful deletion, returns needGracefulDelete=true\n// - if ref makes no meaningful change, but changes the pod status, returns needReconcile=true\n// - else return all false\n// Now, needUpdate, needGracefulDelete and needReconcile should never be both true\nfunc checkAndUpdatePod(existing, ref *v1.Pod) (needUpdate, needReconcile, needGracefulDelete bool) {\n\n\t// 1. this is a reconcile\n\t// TODO: it would be better to update the whole object and only preserve certain things\n\t// like the source annotation or the UID (to ensure safety)\n\tif !podsDifferSemantically(existing, ref) {\n\t\t// this is not an update\n\t\t// Only check reconcile when it is not an update, because if the pod is going to\n\t\t// be updated, an extra reconcile is unnecessary\n\t\tif !reflect.DeepEqual(existing.Status, ref.Status) {\n\t\t\t// Pod with changed pod status needs reconcile, because kubelet should\n\t\t\t// be the source of truth of pod status.\n\t\t\texisting.Status = ref.Status\n\t\t\tneedReconcile = true\n\t\t}\n\t\treturn\n\t}\n\n\t// Overwrite the first-seen time with the existing one. This is our own\n\t// internal annotation, there is no need to update.\n\tref.Annotations[kubetypes.ConfigFirstSeenAnnotationKey] = existing.Annotations[kubetypes.ConfigFirstSeenAnnotationKey]\n\n\texisting.Spec = ref.Spec\n\texisting.Labels = ref.Labels\n\texisting.DeletionTimestamp = ref.DeletionTimestamp\n\texisting.DeletionGracePeriodSeconds = ref.DeletionGracePeriodSeconds\n\texisting.Status = ref.Status\n\tupdateAnnotations(existing, ref)\n\n\t// 2. this is an graceful delete\n\tif ref.DeletionTimestamp != nil {\n\t\tneedGracefulDelete = true\n\t} else {\n\t\t// 3. this is an update\n\t\tneedUpdate = true\n\t}\n\n\treturn\n}","line":{"from":428,"to":472}} {"id":100006297,"name":"Sync","signature":"func (s *podStorage) Sync()","file":"pkg/kubelet/config/config.go","code":"// Sync sends a copy of the current state through the update channel.\nfunc (s *podStorage) Sync() {\n\ts.updateLock.Lock()\n\tdefer s.updateLock.Unlock()\n\ts.updates \u003c- kubetypes.PodUpdate{Pods: s.MergedState().([]*v1.Pod), Op: kubetypes.SET, Source: kubetypes.AllSource}\n}","line":{"from":474,"to":479}} {"id":100006298,"name":"MergedState","signature":"func (s *podStorage) MergedState() interface{}","file":"pkg/kubelet/config/config.go","code":"// Object implements config.Accessor\nfunc (s *podStorage) MergedState() interface{} {\n\ts.podLock.RLock()\n\tdefer s.podLock.RUnlock()\n\tpods := make([]*v1.Pod, 0)\n\tfor _, sourcePods := range s.pods {\n\t\tfor _, podRef := range sourcePods {\n\t\t\tpods = append(pods, podRef.DeepCopy())\n\t\t}\n\t}\n\treturn pods\n}","line":{"from":481,"to":492}} {"id":100006299,"name":"copyPods","signature":"func copyPods(sourcePods []*v1.Pod) []*v1.Pod","file":"pkg/kubelet/config/config.go","code":"func copyPods(sourcePods []*v1.Pod) []*v1.Pod {\n\tpods := []*v1.Pod{}\n\tfor _, source := range sourcePods {\n\t\t// Use a deep copy here just in case\n\t\tpods = append(pods, source.DeepCopy())\n\t}\n\treturn pods\n}","line":{"from":494,"to":501}} {"id":100006300,"name":"NewSourceFile","signature":"func NewSourceFile(path string, nodeName types.NodeName, period time.Duration, updates chan\u003c- interface{})","file":"pkg/kubelet/config/file.go","code":"// NewSourceFile watches a config file for changes.\nfunc NewSourceFile(path string, nodeName types.NodeName, period time.Duration, updates chan\u003c- interface{}) {\n\t// \"github.com/sigma/go-inotify\" requires a path without trailing \"/\"\n\tpath = strings.TrimRight(path, string(os.PathSeparator))\n\n\tconfig := newSourceFile(path, nodeName, period, updates)\n\tklog.V(1).InfoS(\"Watching path\", \"path\", path)\n\tconfig.run()\n}","line":{"from":62,"to":70}} {"id":100006301,"name":"newSourceFile","signature":"func newSourceFile(path string, nodeName types.NodeName, period time.Duration, updates chan\u003c- interface{}) *sourceFile","file":"pkg/kubelet/config/file.go","code":"func newSourceFile(path string, nodeName types.NodeName, period time.Duration, updates chan\u003c- interface{}) *sourceFile {\n\tsend := func(objs []interface{}) {\n\t\tvar pods []*v1.Pod\n\t\tfor _, o := range objs {\n\t\t\tpods = append(pods, o.(*v1.Pod))\n\t\t}\n\t\tupdates \u003c- kubetypes.PodUpdate{Pods: pods, Op: kubetypes.SET, Source: kubetypes.FileSource}\n\t}\n\tstore := cache.NewUndeltaStore(send, cache.MetaNamespaceKeyFunc)\n\treturn \u0026sourceFile{\n\t\tpath: path,\n\t\tnodeName: nodeName,\n\t\tperiod: period,\n\t\tstore: store,\n\t\tfileKeyMapping: map[string]string{},\n\t\tupdates: updates,\n\t\twatchEvents: make(chan *watchEvent, eventBufferLen),\n\t}\n}","line":{"from":72,"to":90}} {"id":100006302,"name":"run","signature":"func (s *sourceFile) run()","file":"pkg/kubelet/config/file.go","code":"func (s *sourceFile) run() {\n\tlistTicker := time.NewTicker(s.period)\n\n\tgo func() {\n\t\t// Read path immediately to speed up startup.\n\t\tif err := s.listConfig(); err != nil {\n\t\t\tklog.ErrorS(err, \"Unable to read config path\", \"path\", s.path)\n\t\t}\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase \u003c-listTicker.C:\n\t\t\t\tif err := s.listConfig(); err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"Unable to read config path\", \"path\", s.path)\n\t\t\t\t}\n\t\t\tcase e := \u003c-s.watchEvents:\n\t\t\t\tif err := s.consumeWatchEvent(e); err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"Unable to process watch event\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\ts.startWatch()\n}","line":{"from":92,"to":115}} {"id":100006303,"name":"applyDefaults","signature":"func (s *sourceFile) applyDefaults(pod *api.Pod, source string) error","file":"pkg/kubelet/config/file.go","code":"func (s *sourceFile) applyDefaults(pod *api.Pod, source string) error {\n\treturn applyDefaults(pod, source, true, s.nodeName)\n}","line":{"from":117,"to":119}} {"id":100006304,"name":"listConfig","signature":"func (s *sourceFile) listConfig() error","file":"pkg/kubelet/config/file.go","code":"func (s *sourceFile) listConfig() error {\n\tpath := s.path\n\tstatInfo, err := os.Stat(path)\n\tif err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn err\n\t\t}\n\t\t// Emit an update with an empty PodList to allow FileSource to be marked as seen\n\t\ts.updates \u003c- kubetypes.PodUpdate{Pods: []*v1.Pod{}, Op: kubetypes.SET, Source: kubetypes.FileSource}\n\t\treturn fmt.Errorf(\"path does not exist, ignoring\")\n\t}\n\n\tswitch {\n\tcase statInfo.Mode().IsDir():\n\t\tpods, err := s.extractFromDir(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(pods) == 0 {\n\t\t\t// Emit an update with an empty PodList to allow FileSource to be marked as seen\n\t\t\ts.updates \u003c- kubetypes.PodUpdate{Pods: pods, Op: kubetypes.SET, Source: kubetypes.FileSource}\n\t\t\treturn nil\n\t\t}\n\t\treturn s.replaceStore(pods...)\n\n\tcase statInfo.Mode().IsRegular():\n\t\tpod, err := s.extractFromFile(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn s.replaceStore(pod)\n\n\tdefault:\n\t\treturn fmt.Errorf(\"path is not a directory or file\")\n\t}\n}","line":{"from":121,"to":156}} {"id":100006305,"name":"extractFromDir","signature":"func (s *sourceFile) extractFromDir(name string) ([]*v1.Pod, error)","file":"pkg/kubelet/config/file.go","code":"// Get as many pod manifests as we can from a directory. Return an error if and only if something\n// prevented us from reading anything at all. Do not return an error if only some files\n// were problematic.\nfunc (s *sourceFile) extractFromDir(name string) ([]*v1.Pod, error) {\n\tdirents, err := filepath.Glob(filepath.Join(name, \"[^.]*\"))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"glob failed: %v\", err)\n\t}\n\n\tpods := make([]*v1.Pod, 0, len(dirents))\n\tif len(dirents) == 0 {\n\t\treturn pods, nil\n\t}\n\n\tsort.Strings(dirents)\n\tfor _, path := range dirents {\n\t\tstatInfo, err := os.Stat(path)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Could not get metadata\", \"path\", path)\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch {\n\t\tcase statInfo.Mode().IsDir():\n\t\t\tklog.ErrorS(nil, \"Provided manifest path is a directory, not recursing into manifest path\", \"path\", path)\n\t\tcase statInfo.Mode().IsRegular():\n\t\t\tpod, err := s.extractFromFile(path)\n\t\t\tif err != nil {\n\t\t\t\tif !os.IsNotExist(err) {\n\t\t\t\t\tklog.ErrorS(err, \"Could not process manifest file\", \"path\", path)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tpods = append(pods, pod)\n\t\t\t}\n\t\tdefault:\n\t\t\tklog.ErrorS(nil, \"Manifest path is not a directory or file\", \"path\", path, \"mode\", statInfo.Mode())\n\t\t}\n\t}\n\treturn pods, nil\n}","line":{"from":158,"to":197}} {"id":100006306,"name":"extractFromFile","signature":"func (s *sourceFile) extractFromFile(filename string) (pod *v1.Pod, err error)","file":"pkg/kubelet/config/file.go","code":"// extractFromFile parses a file for Pod configuration information.\nfunc (s *sourceFile) extractFromFile(filename string) (pod *v1.Pod, err error) {\n\tklog.V(3).InfoS(\"Reading config file\", \"path\", filename)\n\tdefer func() {\n\t\tif err == nil \u0026\u0026 pod != nil {\n\t\t\tobjKey, keyErr := cache.MetaNamespaceKeyFunc(pod)\n\t\t\tif keyErr != nil {\n\t\t\t\terr = keyErr\n\t\t\t\treturn\n\t\t\t}\n\t\t\ts.fileKeyMapping[filename] = objKey\n\t\t}\n\t}()\n\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\treturn pod, err\n\t}\n\tdefer file.Close()\n\n\tdata, err := utilio.ReadAtMost(file, maxConfigLength)\n\tif err != nil {\n\t\treturn pod, err\n\t}\n\n\tdefaultFn := func(pod *api.Pod) error {\n\t\treturn s.applyDefaults(pod, filename)\n\t}\n\n\tparsed, pod, podErr := tryDecodeSinglePod(data, defaultFn)\n\tif parsed {\n\t\tif podErr != nil {\n\t\t\treturn pod, podErr\n\t\t}\n\t\treturn pod, nil\n\t}\n\n\treturn pod, fmt.Errorf(\"%v: couldn't parse as pod(%v), please check config file\", filename, podErr)\n}","line":{"from":199,"to":237}} {"id":100006307,"name":"replaceStore","signature":"func (s *sourceFile) replaceStore(pods ...*v1.Pod) (err error)","file":"pkg/kubelet/config/file.go","code":"func (s *sourceFile) replaceStore(pods ...*v1.Pod) (err error) {\n\tobjs := []interface{}{}\n\tfor _, pod := range pods {\n\t\tobjs = append(objs, pod)\n\t}\n\treturn s.store.Replace(objs, \"\")\n}","line":{"from":239,"to":245}} {"id":100006308,"name":"Error","signature":"func (e *retryableError) Error() string","file":"pkg/kubelet/config/file_linux.go","code":"func (e *retryableError) Error() string {\n\treturn e.message\n}","line":{"from":47,"to":49}} {"id":100006309,"name":"startWatch","signature":"func (s *sourceFile) startWatch()","file":"pkg/kubelet/config/file_linux.go","code":"func (s *sourceFile) startWatch() {\n\tbackOff := flowcontrol.NewBackOff(retryPeriod, maxRetryPeriod)\n\tbackOffID := \"watch\"\n\n\tgo wait.Forever(func() {\n\t\tif backOff.IsInBackOffSinceUpdate(backOffID, time.Now()) {\n\t\t\treturn\n\t\t}\n\n\t\tif err := s.doWatch(); err != nil {\n\t\t\tklog.ErrorS(err, \"Unable to read config path\", \"path\", s.path)\n\t\t\tif _, retryable := err.(*retryableError); !retryable {\n\t\t\t\tbackOff.Next(backOffID, time.Now())\n\t\t\t}\n\t\t}\n\t}, retryPeriod)\n}","line":{"from":51,"to":67}} {"id":100006310,"name":"doWatch","signature":"func (s *sourceFile) doWatch() error","file":"pkg/kubelet/config/file_linux.go","code":"func (s *sourceFile) doWatch() error {\n\t_, err := os.Stat(s.path)\n\tif err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn err\n\t\t}\n\t\t// Emit an update with an empty PodList to allow FileSource to be marked as seen\n\t\ts.updates \u003c- kubetypes.PodUpdate{Pods: []*v1.Pod{}, Op: kubetypes.SET, Source: kubetypes.FileSource}\n\t\treturn \u0026retryableError{\"path does not exist, ignoring\"}\n\t}\n\n\tw, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to create inotify: %v\", err)\n\t}\n\tdefer w.Close()\n\n\terr = w.Add(s.path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to create inotify for path %q: %v\", s.path, err)\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase event := \u003c-w.Events:\n\t\t\tif err = s.produceWatchEvent(\u0026event); err != nil {\n\t\t\t\treturn fmt.Errorf(\"error while processing inotify event (%+v): %v\", event, err)\n\t\t\t}\n\t\tcase err = \u003c-w.Errors:\n\t\t\treturn fmt.Errorf(\"error while watching %q: %v\", s.path, err)\n\t\t}\n\t}\n}","line":{"from":69,"to":101}} {"id":100006311,"name":"produceWatchEvent","signature":"func (s *sourceFile) produceWatchEvent(e *fsnotify.Event) error","file":"pkg/kubelet/config/file_linux.go","code":"func (s *sourceFile) produceWatchEvent(e *fsnotify.Event) error {\n\t// Ignore file start with dots\n\tif strings.HasPrefix(filepath.Base(e.Name), \".\") {\n\t\tklog.V(4).InfoS(\"Ignored pod manifest, because it starts with dots\", \"eventName\", e.Name)\n\t\treturn nil\n\t}\n\tvar eventType podEventType\n\tswitch {\n\tcase (e.Op \u0026 fsnotify.Create) \u003e 0:\n\t\teventType = podAdd\n\tcase (e.Op \u0026 fsnotify.Write) \u003e 0:\n\t\teventType = podModify\n\tcase (e.Op \u0026 fsnotify.Chmod) \u003e 0:\n\t\teventType = podModify\n\tcase (e.Op \u0026 fsnotify.Remove) \u003e 0:\n\t\teventType = podDelete\n\tcase (e.Op \u0026 fsnotify.Rename) \u003e 0:\n\t\teventType = podDelete\n\tdefault:\n\t\t// Ignore rest events\n\t\treturn nil\n\t}\n\n\ts.watchEvents \u003c- \u0026watchEvent{e.Name, eventType}\n\treturn nil\n}","line":{"from":103,"to":128}} {"id":100006312,"name":"consumeWatchEvent","signature":"func (s *sourceFile) consumeWatchEvent(e *watchEvent) error","file":"pkg/kubelet/config/file_linux.go","code":"func (s *sourceFile) consumeWatchEvent(e *watchEvent) error {\n\tswitch e.eventType {\n\tcase podAdd, podModify:\n\t\tpod, err := s.extractFromFile(e.fileName)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"can't process config file %q: %v\", e.fileName, err)\n\t\t}\n\t\treturn s.store.Add(pod)\n\tcase podDelete:\n\t\tif objKey, keyExist := s.fileKeyMapping[e.fileName]; keyExist {\n\t\t\tpod, podExist, err := s.store.GetByKey(objKey)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t} else if !podExist {\n\t\t\t\treturn fmt.Errorf(\"the pod with key %s doesn't exist in cache\", objKey)\n\t\t\t} else {\n\t\t\t\tif err = s.store.Delete(pod); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"failed to remove deleted pod from cache: %v\", err)\n\t\t\t\t}\n\t\t\t\tdelete(s.fileKeyMapping, e.fileName)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":130,"to":154}} {"id":100006313,"name":"startWatch","signature":"func (s *sourceFile) startWatch()","file":"pkg/kubelet/config/file_unsupported.go","code":"func (s *sourceFile) startWatch() {\n\tklog.ErrorS(nil, \"Watching source file is unsupported in this build\")\n}","line":{"from":28,"to":30}} {"id":100006314,"name":"consumeWatchEvent","signature":"func (s *sourceFile) consumeWatchEvent(e *watchEvent) error","file":"pkg/kubelet/config/file_unsupported.go","code":"func (s *sourceFile) consumeWatchEvent(e *watchEvent) error {\n\treturn fmt.Errorf(\"consuming watch event is unsupported in this build\")\n}","line":{"from":32,"to":34}} {"id":100006315,"name":"AddFlags","signature":"func (s *ContainerRuntimeOptions) AddFlags(fs *pflag.FlagSet)","file":"pkg/kubelet/config/flags.go","code":"// AddFlags adds flags to the container runtime, according to ContainerRuntimeOptions.\nfunc (s *ContainerRuntimeOptions) AddFlags(fs *pflag.FlagSet) {\n\t// General settings.\n\tfs.StringVar(\u0026s.RuntimeCgroups, \"runtime-cgroups\", s.RuntimeCgroups, \"Optional absolute name of cgroups to create and run the runtime in.\")\n\tfs.StringVar(\u0026s.PodSandboxImage, \"pod-infra-container-image\", s.PodSandboxImage, fmt.Sprintf(\"Specified image will not be pruned by the image garbage collector. CRI implementations have their own configuration to set this image.\"))\n\tfs.MarkDeprecated(\"pod-infra-container-image\", \"will be removed in a future release. Image garbage collector will get sandbox image information from CRI.\")\n\n\t// Image credential provider settings.\n\tfs.StringVar(\u0026s.ImageCredentialProviderConfigFile, \"image-credential-provider-config\", s.ImageCredentialProviderConfigFile, \"The path to the credential provider plugin config file.\")\n\tfs.StringVar(\u0026s.ImageCredentialProviderBinDir, \"image-credential-provider-bin-dir\", s.ImageCredentialProviderBinDir, \"The path to the directory where credential provider plugin binaries are located.\")\n}","line":{"from":49,"to":59}} {"id":100006316,"name":"NewSourceURL","signature":"func NewSourceURL(url string, header http.Header, nodeName types.NodeName, period time.Duration, updates chan\u003c- interface{})","file":"pkg/kubelet/config/http.go","code":"// NewSourceURL specifies the URL where to read the Pod configuration from, then watches it for changes.\nfunc NewSourceURL(url string, header http.Header, nodeName types.NodeName, period time.Duration, updates chan\u003c- interface{}) {\n\tconfig := \u0026sourceURL{\n\t\turl: url,\n\t\theader: header,\n\t\tnodeName: nodeName,\n\t\tupdates: updates,\n\t\tdata: nil,\n\t\t// Timing out requests leads to retries. This client is only used to\n\t\t// read the manifest URL passed to kubelet.\n\t\tclient: \u0026http.Client{Timeout: 10 * time.Second},\n\t}\n\tklog.V(1).InfoS(\"Watching URL\", \"URL\", url)\n\tgo wait.Until(config.run, period, wait.NeverStop)\n}","line":{"from":45,"to":59}} {"id":100006317,"name":"run","signature":"func (s *sourceURL) run()","file":"pkg/kubelet/config/http.go","code":"func (s *sourceURL) run() {\n\tif err := s.extractFromURL(); err != nil {\n\t\t// Don't log this multiple times per minute. The first few entries should be\n\t\t// enough to get the point across.\n\t\tif s.failureLogs \u003c 3 {\n\t\t\tklog.InfoS(\"Failed to read pods from URL\", \"err\", err)\n\t\t} else if s.failureLogs == 3 {\n\t\t\tklog.InfoS(\"Failed to read pods from URL. Dropping verbosity of this message to V(4)\", \"err\", err)\n\t\t} else {\n\t\t\tklog.V(4).InfoS(\"Failed to read pods from URL\", \"err\", err)\n\t\t}\n\t\ts.failureLogs++\n\t} else {\n\t\tif s.failureLogs \u003e 0 {\n\t\t\tklog.InfoS(\"Successfully read pods from URL\")\n\t\t\ts.failureLogs = 0\n\t\t}\n\t}\n}","line":{"from":61,"to":79}} {"id":100006318,"name":"applyDefaults","signature":"func (s *sourceURL) applyDefaults(pod *api.Pod) error","file":"pkg/kubelet/config/http.go","code":"func (s *sourceURL) applyDefaults(pod *api.Pod) error {\n\treturn applyDefaults(pod, s.url, false, s.nodeName)\n}","line":{"from":81,"to":83}} {"id":100006319,"name":"extractFromURL","signature":"func (s *sourceURL) extractFromURL() error","file":"pkg/kubelet/config/http.go","code":"func (s *sourceURL) extractFromURL() error {\n\treq, err := http.NewRequest(\"GET\", s.url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header = s.header\n\tresp, err := s.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tdata, err := utilio.ReadAtMost(resp.Body, maxConfigLength)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"%v: %v\", s.url, resp.Status)\n\t}\n\tif len(data) == 0 {\n\t\t// Emit an update with an empty PodList to allow HTTPSource to be marked as seen\n\t\ts.updates \u003c- kubetypes.PodUpdate{Pods: []*v1.Pod{}, Op: kubetypes.SET, Source: kubetypes.HTTPSource}\n\t\treturn fmt.Errorf(\"zero-length data received from %v\", s.url)\n\t}\n\t// Short circuit if the data has not changed since the last time it was read.\n\tif bytes.Equal(data, s.data) {\n\t\treturn nil\n\t}\n\ts.data = data\n\n\t// First try as it is a single pod.\n\tparsed, pod, singlePodErr := tryDecodeSinglePod(data, s.applyDefaults)\n\tif parsed {\n\t\tif singlePodErr != nil {\n\t\t\t// It parsed but could not be used.\n\t\t\treturn singlePodErr\n\t\t}\n\t\ts.updates \u003c- kubetypes.PodUpdate{Pods: []*v1.Pod{pod}, Op: kubetypes.SET, Source: kubetypes.HTTPSource}\n\t\treturn nil\n\t}\n\n\t// That didn't work, so try a list of pods.\n\tparsed, podList, multiPodErr := tryDecodePodList(data, s.applyDefaults)\n\tif parsed {\n\t\tif multiPodErr != nil {\n\t\t\t// It parsed but could not be used.\n\t\t\treturn multiPodErr\n\t\t}\n\t\tpods := make([]*v1.Pod, 0, len(podList.Items))\n\t\tfor i := range podList.Items {\n\t\t\tpods = append(pods, \u0026podList.Items[i])\n\t\t}\n\t\ts.updates \u003c- kubetypes.PodUpdate{Pods: pods, Op: kubetypes.SET, Source: kubetypes.HTTPSource}\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"%v: received '%v', but couldn't parse as \"+\n\t\t\"single (%v) or multiple pods (%v)\",\n\t\ts.url, string(data), singlePodErr, multiPodErr)\n}","line":{"from":85,"to":143}} {"id":100006320,"name":"NewSourcesReady","signature":"func NewSourcesReady(sourcesReadyFn SourcesReadyFn) SourcesReady","file":"pkg/kubelet/config/sources.go","code":"// NewSourcesReady returns a SourcesReady with the specified function.\nfunc NewSourcesReady(sourcesReadyFn SourcesReadyFn) SourcesReady {\n\treturn \u0026sourcesImpl{\n\t\tsourcesSeen: sets.NewString(),\n\t\tsourcesReadyFn: sourcesReadyFn,\n\t}\n}","line":{"from":37,"to":43}} {"id":100006321,"name":"AddSource","signature":"func (s *sourcesImpl) AddSource(source string)","file":"pkg/kubelet/config/sources.go","code":"// Add adds the specified source to the set of sources managed.\nfunc (s *sourcesImpl) AddSource(source string) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\ts.sourcesSeen.Insert(source)\n}","line":{"from":55,"to":60}} {"id":100006322,"name":"AllReady","signature":"func (s *sourcesImpl) AllReady() bool","file":"pkg/kubelet/config/sources.go","code":"// AllReady returns true if each configured source is ready.\nfunc (s *sourcesImpl) AllReady() bool {\n\ts.lock.RLock()\n\tdefer s.lock.RUnlock()\n\treturn s.sourcesReadyFn(s.sourcesSeen)\n}","line":{"from":62,"to":67}} {"id":100006323,"name":"NewSimpleConfigMapManager","signature":"func NewSimpleConfigMapManager(kubeClient clientset.Interface) Manager","file":"pkg/kubelet/configmap/configmap_manager.go","code":"// NewSimpleConfigMapManager creates a new ConfigMapManager instance.\nfunc NewSimpleConfigMapManager(kubeClient clientset.Interface) Manager {\n\treturn \u0026simpleConfigMapManager{kubeClient: kubeClient}\n}","line":{"from":59,"to":62}} {"id":100006324,"name":"GetConfigMap","signature":"func (s *simpleConfigMapManager) GetConfigMap(namespace, name string) (*v1.ConfigMap, error)","file":"pkg/kubelet/configmap/configmap_manager.go","code":"func (s *simpleConfigMapManager) GetConfigMap(namespace, name string) (*v1.ConfigMap, error) {\n\treturn s.kubeClient.CoreV1().ConfigMaps(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n}","line":{"from":64,"to":66}} {"id":100006325,"name":"RegisterPod","signature":"func (s *simpleConfigMapManager) RegisterPod(pod *v1.Pod)","file":"pkg/kubelet/configmap/configmap_manager.go","code":"func (s *simpleConfigMapManager) RegisterPod(pod *v1.Pod) {\n}","line":{"from":68,"to":69}} {"id":100006326,"name":"UnregisterPod","signature":"func (s *simpleConfigMapManager) UnregisterPod(pod *v1.Pod)","file":"pkg/kubelet/configmap/configmap_manager.go","code":"func (s *simpleConfigMapManager) UnregisterPod(pod *v1.Pod) {\n}","line":{"from":71,"to":72}} {"id":100006327,"name":"GetConfigMap","signature":"func (c *configMapManager) GetConfigMap(namespace, name string) (*v1.ConfigMap, error)","file":"pkg/kubelet/configmap/configmap_manager.go","code":"func (c *configMapManager) GetConfigMap(namespace, name string) (*v1.ConfigMap, error) {\n\tobject, err := c.manager.GetObject(namespace, name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif configmap, ok := object.(*v1.ConfigMap); ok {\n\t\treturn configmap, nil\n\t}\n\treturn nil, fmt.Errorf(\"unexpected object type: %v\", object)\n}","line":{"from":82,"to":91}} {"id":100006328,"name":"RegisterPod","signature":"func (c *configMapManager) RegisterPod(pod *v1.Pod)","file":"pkg/kubelet/configmap/configmap_manager.go","code":"func (c *configMapManager) RegisterPod(pod *v1.Pod) {\n\tc.manager.RegisterPod(pod)\n}","line":{"from":93,"to":95}} {"id":100006329,"name":"UnregisterPod","signature":"func (c *configMapManager) UnregisterPod(pod *v1.Pod)","file":"pkg/kubelet/configmap/configmap_manager.go","code":"func (c *configMapManager) UnregisterPod(pod *v1.Pod) {\n\tc.manager.UnregisterPod(pod)\n}","line":{"from":97,"to":99}} {"id":100006330,"name":"getConfigMapNames","signature":"func getConfigMapNames(pod *v1.Pod) sets.String","file":"pkg/kubelet/configmap/configmap_manager.go","code":"func getConfigMapNames(pod *v1.Pod) sets.String {\n\tresult := sets.NewString()\n\tpodutil.VisitPodConfigmapNames(pod, func(name string) bool {\n\t\tresult.Insert(name)\n\t\treturn true\n\t})\n\treturn result\n}","line":{"from":101,"to":108}} {"id":100006331,"name":"NewCachingConfigMapManager","signature":"func NewCachingConfigMapManager(kubeClient clientset.Interface, getTTL manager.GetObjectTTLFunc) Manager","file":"pkg/kubelet/configmap/configmap_manager.go","code":"// NewCachingConfigMapManager creates a manager that keeps a cache of all configmaps\n// necessary for registered pods.\n// It implement the following logic:\n// - whenever a pod is create or updated, the cached versions of all configmaps\n// are invalidated\n// - every GetObject() call tries to fetch the value from local cache; if it is\n// not there, invalidated or too old, we fetch it from apiserver and refresh the\n// value in cache; otherwise it is just fetched from cache\nfunc NewCachingConfigMapManager(kubeClient clientset.Interface, getTTL manager.GetObjectTTLFunc) Manager {\n\tgetConfigMap := func(namespace, name string, opts metav1.GetOptions) (runtime.Object, error) {\n\t\treturn kubeClient.CoreV1().ConfigMaps(namespace).Get(context.TODO(), name, opts)\n\t}\n\tconfigMapStore := manager.NewObjectStore(getConfigMap, clock.RealClock{}, getTTL, defaultTTL)\n\treturn \u0026configMapManager{\n\t\tmanager: manager.NewCacheBasedManager(configMapStore, getConfigMapNames),\n\t}\n}","line":{"from":114,"to":130}} {"id":100006332,"name":"NewWatchingConfigMapManager","signature":"func NewWatchingConfigMapManager(kubeClient clientset.Interface, resyncInterval time.Duration) Manager","file":"pkg/kubelet/configmap/configmap_manager.go","code":"// NewWatchingConfigMapManager creates a manager that keeps a cache of all configmaps\n// necessary for registered pods.\n// It implements the following logic:\n// - whenever a pod is created or updated, we start individual watches for all\n// referenced objects that aren't referenced from other registered pods\n// - every GetObject() returns a value from local cache propagated via watches\nfunc NewWatchingConfigMapManager(kubeClient clientset.Interface, resyncInterval time.Duration) Manager {\n\tlistConfigMap := func(namespace string, opts metav1.ListOptions) (runtime.Object, error) {\n\t\treturn kubeClient.CoreV1().ConfigMaps(namespace).List(context.TODO(), opts)\n\t}\n\twatchConfigMap := func(namespace string, opts metav1.ListOptions) (watch.Interface, error) {\n\t\treturn kubeClient.CoreV1().ConfigMaps(namespace).Watch(context.TODO(), opts)\n\t}\n\tnewConfigMap := func() runtime.Object {\n\t\treturn \u0026v1.ConfigMap{}\n\t}\n\tisImmutable := func(object runtime.Object) bool {\n\t\tif configMap, ok := object.(*v1.ConfigMap); ok {\n\t\t\treturn configMap.Immutable != nil \u0026\u0026 *configMap.Immutable\n\t\t}\n\t\treturn false\n\t}\n\tgr := corev1.Resource(\"configmap\")\n\treturn \u0026configMapManager{\n\t\tmanager: manager.NewWatchBasedManager(listConfigMap, watchConfigMap, newConfigMap, isImmutable, gr, resyncInterval, getConfigMapNames),\n\t}\n}","line":{"from":132,"to":158}} {"id":100006333,"name":"NewCache","signature":"func NewCache() Cache","file":"pkg/kubelet/container/cache.go","code":"// NewCache creates a pod cache.\nfunc NewCache() Cache {\n\treturn \u0026cache{pods: map[types.UID]*data{}, subscribers: map[types.UID][]*subRecord{}}\n}","line":{"from":81,"to":84}} {"id":100006334,"name":"Get","signature":"func (c *cache) Get(id types.UID) (*PodStatus, error)","file":"pkg/kubelet/container/cache.go","code":"// Get returns the PodStatus for the pod; callers are expected not to\n// modify the objects returned.\nfunc (c *cache) Get(id types.UID) (*PodStatus, error) {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\td := c.get(id)\n\treturn d.status, d.err\n}","line":{"from":86,"to":93}} {"id":100006335,"name":"GetNewerThan","signature":"func (c *cache) GetNewerThan(id types.UID, minTime time.Time) (*PodStatus, error)","file":"pkg/kubelet/container/cache.go","code":"func (c *cache) GetNewerThan(id types.UID, minTime time.Time) (*PodStatus, error) {\n\tch := c.subscribe(id, minTime)\n\td := \u003c-ch\n\treturn d.status, d.err\n}","line":{"from":95,"to":99}} {"id":100006336,"name":"Set","signature":"func (c *cache) Set(id types.UID, status *PodStatus, err error, timestamp time.Time) (updated bool)","file":"pkg/kubelet/container/cache.go","code":"// Set sets the PodStatus for the pod only if the data is newer than the cache\nfunc (c *cache) Set(id types.UID, status *PodStatus, err error, timestamp time.Time) (updated bool) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.EventedPLEG) {\n\t\t// Set the value in the cache only if it's not present already\n\t\t// or the timestamp in the cache is older than the current update timestamp\n\t\tif cachedVal, ok := c.pods[id]; ok \u0026\u0026 cachedVal.modified.After(timestamp) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tc.pods[id] = \u0026data{status: status, err: err, modified: timestamp}\n\tc.notify(id, timestamp)\n\treturn true\n}","line":{"from":101,"to":117}} {"id":100006337,"name":"Delete","signature":"func (c *cache) Delete(id types.UID)","file":"pkg/kubelet/container/cache.go","code":"// Delete removes the entry of the pod.\nfunc (c *cache) Delete(id types.UID) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tdelete(c.pods, id)\n}","line":{"from":119,"to":124}} {"id":100006338,"name":"UpdateTime","signature":"func (c *cache) UpdateTime(timestamp time.Time)","file":"pkg/kubelet/container/cache.go","code":"// UpdateTime modifies the global timestamp of the cache and notify\n// subscribers if needed.\nfunc (c *cache) UpdateTime(timestamp time.Time) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tc.timestamp = \u0026timestamp\n\t// Notify all the subscribers if the condition is met.\n\tfor id := range c.subscribers {\n\t\tc.notify(id, *c.timestamp)\n\t}\n}","line":{"from":126,"to":136}} {"id":100006339,"name":"makeDefaultData","signature":"func makeDefaultData(id types.UID) *data","file":"pkg/kubelet/container/cache.go","code":"func makeDefaultData(id types.UID) *data {\n\treturn \u0026data{status: \u0026PodStatus{ID: id}, err: nil}\n}","line":{"from":138,"to":140}} {"id":100006340,"name":"get","signature":"func (c *cache) get(id types.UID) *data","file":"pkg/kubelet/container/cache.go","code":"func (c *cache) get(id types.UID) *data {\n\td, ok := c.pods[id]\n\tif !ok {\n\t\t// Cache should store *all* pod/container information known by the\n\t\t// container runtime. A cache miss indicates that there are no states\n\t\t// regarding the pod last time we queried the container runtime.\n\t\t// What this *really* means is that there are no visible pod/containers\n\t\t// associated with this pod. Simply return an default (mostly empty)\n\t\t// PodStatus to reflect this.\n\t\treturn makeDefaultData(id)\n\t}\n\treturn d\n}","line":{"from":142,"to":154}} {"id":100006341,"name":"getIfNewerThan","signature":"func (c *cache) getIfNewerThan(id types.UID, minTime time.Time) *data","file":"pkg/kubelet/container/cache.go","code":"// getIfNewerThan returns the data it is newer than the given time.\n// Otherwise, it returns nil. The caller should acquire the lock.\nfunc (c *cache) getIfNewerThan(id types.UID, minTime time.Time) *data {\n\td, ok := c.pods[id]\n\tif utilfeature.DefaultFeatureGate.Enabled(features.EventedPLEG) {\n\t\t// Evented PLEG has CREATED, STARTED, STOPPED and DELETED events\n\t\t// However if the container creation fails for some reason there is no\n\t\t// CRI event received by the kubelet and that pod will get stuck a\n\t\t// GetNewerThan call in the pod workers. This is reproducible with\n\t\t// the node e2e test,\n\t\t// https://github.com/kubernetes/kubernetes/blob/83415e5c9e6e59a3d60a148160490560af2178a1/test/e2e_node/pod_hostnamefqdn_test.go#L161\n\t\t// which forces failure during pod creation. This issue also exists in\n\t\t// Generic PLEG but since it updates global timestamp periodically\n\t\t// the GetNewerThan call gets unstuck.\n\n\t\t// During node e2e tests, it was observed this change does not have any\n\t\t// adverse impact on the behaviour of the Generic PLEG as well.\n\t\tswitch {\n\t\tcase !ok:\n\t\t\treturn makeDefaultData(id)\n\t\tcase ok \u0026\u0026 (d.modified.After(minTime) || (c.timestamp != nil \u0026\u0026 c.timestamp.After(minTime))):\n\t\t\treturn d\n\t\tdefault:\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tglobalTimestampIsNewer := (c.timestamp != nil \u0026\u0026 c.timestamp.After(minTime))\n\tif !ok \u0026\u0026 globalTimestampIsNewer {\n\t\t// Status is not cached, but the global timestamp is newer than\n\t\t// minTime, return the default status.\n\t\treturn makeDefaultData(id)\n\t}\n\tif ok \u0026\u0026 (d.modified.After(minTime) || globalTimestampIsNewer) {\n\t\t// Status is cached, return status if either of the following is true.\n\t\t// * status was modified after minTime\n\t\t// * the global timestamp of the cache is newer than minTime.\n\t\treturn d\n\t}\n\t// The pod status is not ready.\n\treturn nil\n}","line":{"from":156,"to":197}} {"id":100006342,"name":"notify","signature":"func (c *cache) notify(id types.UID, timestamp time.Time)","file":"pkg/kubelet/container/cache.go","code":"// notify sends notifications for pod with the given id, if the requirements\n// are met. Note that the caller should acquire the lock.\nfunc (c *cache) notify(id types.UID, timestamp time.Time) {\n\tlist, ok := c.subscribers[id]\n\tif !ok {\n\t\t// No one to notify.\n\t\treturn\n\t}\n\tnewList := []*subRecord{}\n\tfor i, r := range list {\n\t\tif timestamp.Before(r.time) {\n\t\t\t// Doesn't meet the time requirement; keep the record.\n\t\t\tnewList = append(newList, list[i])\n\t\t\tcontinue\n\t\t}\n\t\tr.ch \u003c- c.get(id)\n\t\tclose(r.ch)\n\t}\n\tif len(newList) == 0 {\n\t\tdelete(c.subscribers, id)\n\t} else {\n\t\tc.subscribers[id] = newList\n\t}\n}","line":{"from":199,"to":222}} {"id":100006343,"name":"subscribe","signature":"func (c *cache) subscribe(id types.UID, timestamp time.Time) chan *data","file":"pkg/kubelet/container/cache.go","code":"func (c *cache) subscribe(id types.UID, timestamp time.Time) chan *data {\n\tch := make(chan *data, 1)\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\td := c.getIfNewerThan(id, timestamp)\n\tif d != nil {\n\t\t// If the cache entry is ready, send the data and return immediately.\n\t\tch \u003c- d\n\t\treturn ch\n\t}\n\t// Add the subscription record.\n\tc.subscribers[id] = append(c.subscribers[id], \u0026subRecord{time: timestamp, ch: ch})\n\treturn ch\n}","line":{"from":224,"to":237}} {"id":100006344,"name":"NewContainerGC","signature":"func NewContainerGC(runtime Runtime, policy GCPolicy, sourcesReadyProvider SourcesReadyProvider) (GC, error)","file":"pkg/kubelet/container/container_gc.go","code":"// NewContainerGC creates a new instance of GC with the specified policy.\nfunc NewContainerGC(runtime Runtime, policy GCPolicy, sourcesReadyProvider SourcesReadyProvider) (GC, error) {\n\tif policy.MinAge \u003c 0 {\n\t\treturn nil, fmt.Errorf(\"invalid minimum garbage collection age: %v\", policy.MinAge)\n\t}\n\n\treturn \u0026realContainerGC{\n\t\truntime: runtime,\n\t\tpolicy: policy,\n\t\tsourcesReadyProvider: sourcesReadyProvider,\n\t}, nil\n}","line":{"from":68,"to":79}} {"id":100006345,"name":"GarbageCollect","signature":"func (cgc *realContainerGC) GarbageCollect(ctx context.Context) error","file":"pkg/kubelet/container/container_gc.go","code":"func (cgc *realContainerGC) GarbageCollect(ctx context.Context) error {\n\treturn cgc.runtime.GarbageCollect(ctx, cgc.policy, cgc.sourcesReadyProvider.AllReady(), false)\n}","line":{"from":81,"to":83}} {"id":100006346,"name":"DeleteAllUnusedContainers","signature":"func (cgc *realContainerGC) DeleteAllUnusedContainers(ctx context.Context) error","file":"pkg/kubelet/container/container_gc.go","code":"func (cgc *realContainerGC) DeleteAllUnusedContainers(ctx context.Context) error {\n\tklog.InfoS(\"Attempting to delete unused containers\")\n\treturn cgc.runtime.GarbageCollect(ctx, cgc.policy, cgc.sourcesReadyProvider.AllReady(), true)\n}","line":{"from":85,"to":88}} {"id":100006347,"name":"ShouldContainerBeRestarted","signature":"func ShouldContainerBeRestarted(container *v1.Container, pod *v1.Pod, podStatus *PodStatus) bool","file":"pkg/kubelet/container/helpers.go","code":"// ShouldContainerBeRestarted checks whether a container needs to be restarted.\n// TODO(yifan): Think about how to refactor this.\nfunc ShouldContainerBeRestarted(container *v1.Container, pod *v1.Pod, podStatus *PodStatus) bool {\n\t// Once a pod has been marked deleted, it should not be restarted\n\tif pod.DeletionTimestamp != nil {\n\t\treturn false\n\t}\n\t// Get latest container status.\n\tstatus := podStatus.FindContainerStatusByName(container.Name)\n\t// If the container was never started before, we should start it.\n\t// NOTE(random-liu): If all historical containers were GC'd, we'll also return true here.\n\tif status == nil {\n\t\treturn true\n\t}\n\t// Check whether container is running\n\tif status.State == ContainerStateRunning {\n\t\treturn false\n\t}\n\t// Always restart container in the unknown, or in the created state.\n\tif status.State == ContainerStateUnknown || status.State == ContainerStateCreated {\n\t\treturn true\n\t}\n\t// Check RestartPolicy for dead container\n\tif pod.Spec.RestartPolicy == v1.RestartPolicyNever {\n\t\tklog.V(4).InfoS(\"Already ran container, do nothing\", \"pod\", klog.KObj(pod), \"containerName\", container.Name)\n\t\treturn false\n\t}\n\tif pod.Spec.RestartPolicy == v1.RestartPolicyOnFailure {\n\t\t// Check the exit code.\n\t\tif status.ExitCode == 0 {\n\t\t\tklog.V(4).InfoS(\"Already successfully ran container, do nothing\", \"pod\", klog.KObj(pod), \"containerName\", container.Name)\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":71,"to":106}} {"id":100006348,"name":"HashContainer","signature":"func HashContainer(container *v1.Container) uint64","file":"pkg/kubelet/container/helpers.go","code":"// HashContainer returns the hash of the container. It is used to compare\n// the running container with its desired spec.\n// Note: remember to update hashValues in container_hash_test.go as well.\nfunc HashContainer(container *v1.Container) uint64 {\n\thash := fnv.New32a()\n\t// Omit nil or empty field when calculating hash value\n\t// Please see https://github.com/kubernetes/kubernetes/issues/53644\n\tcontainerJSON, _ := json.Marshal(container)\n\thashutil.DeepHashObject(hash, containerJSON)\n\treturn uint64(hash.Sum32())\n}","line":{"from":108,"to":118}} {"id":100006349,"name":"HashContainerWithoutResources","signature":"func HashContainerWithoutResources(container *v1.Container) uint64","file":"pkg/kubelet/container/helpers.go","code":"// HashContainerWithoutResources returns the hash of the container with Resources field zero'd out.\nfunc HashContainerWithoutResources(container *v1.Container) uint64 {\n\t// InPlacePodVerticalScaling enables mutable Resources field.\n\t// Changes to this field may not require container restart depending on policy.\n\t// Compute hash over fields besides the Resources field\n\t// NOTE: This is needed during alpha and beta so that containers using Resources but\n\t// not subject to In-place resize are not unexpectedly restarted when\n\t// InPlacePodVerticalScaling feature-gate is toggled.\n\t//TODO(vinaykul,InPlacePodVerticalScaling): Remove this in GA+1 and make HashContainerWithoutResources to become Hash.\n\thashWithoutResources := fnv.New32a()\n\tcontainerCopy := container.DeepCopy()\n\tcontainerCopy.Resources = v1.ResourceRequirements{}\n\tcontainerJSON, _ := json.Marshal(containerCopy)\n\thashutil.DeepHashObject(hashWithoutResources, containerJSON)\n\treturn uint64(hashWithoutResources.Sum32())\n}","line":{"from":120,"to":135}} {"id":100006350,"name":"envVarsToMap","signature":"func envVarsToMap(envs []EnvVar) map[string]string","file":"pkg/kubelet/container/helpers.go","code":"// envVarsToMap constructs a map of environment name to value from a slice\n// of env vars.\nfunc envVarsToMap(envs []EnvVar) map[string]string {\n\tresult := map[string]string{}\n\tfor _, env := range envs {\n\t\tresult[env.Name] = env.Value\n\t}\n\treturn result\n}","line":{"from":137,"to":145}} {"id":100006351,"name":"v1EnvVarsToMap","signature":"func v1EnvVarsToMap(envs []v1.EnvVar) map[string]string","file":"pkg/kubelet/container/helpers.go","code":"// v1EnvVarsToMap constructs a map of environment name to value from a slice\n// of env vars.\nfunc v1EnvVarsToMap(envs []v1.EnvVar) map[string]string {\n\tresult := map[string]string{}\n\tfor _, env := range envs {\n\t\tresult[env.Name] = env.Value\n\t}\n\n\treturn result\n}","line":{"from":147,"to":156}} {"id":100006352,"name":"ExpandContainerCommandOnlyStatic","signature":"func ExpandContainerCommandOnlyStatic(containerCommand []string, envs []v1.EnvVar) (command []string)","file":"pkg/kubelet/container/helpers.go","code":"// ExpandContainerCommandOnlyStatic substitutes only static environment variable values from the\n// container environment definitions. This does *not* include valueFrom substitutions.\n// TODO: callers should use ExpandContainerCommandAndArgs with a fully resolved list of environment.\nfunc ExpandContainerCommandOnlyStatic(containerCommand []string, envs []v1.EnvVar) (command []string) {\n\tmapping := expansion.MappingFuncFor(v1EnvVarsToMap(envs))\n\tif len(containerCommand) != 0 {\n\t\tfor _, cmd := range containerCommand {\n\t\t\tcommand = append(command, expansion.Expand(cmd, mapping))\n\t\t}\n\t}\n\treturn command\n}","line":{"from":158,"to":169}} {"id":100006353,"name":"ExpandContainerVolumeMounts","signature":"func ExpandContainerVolumeMounts(mount v1.VolumeMount, envs []EnvVar) (string, error)","file":"pkg/kubelet/container/helpers.go","code":"// ExpandContainerVolumeMounts expands the subpath of the given VolumeMount by replacing variable references with the values of given EnvVar.\nfunc ExpandContainerVolumeMounts(mount v1.VolumeMount, envs []EnvVar) (string, error) {\n\n\tenvmap := envVarsToMap(envs)\n\tmissingKeys := sets.NewString()\n\texpanded := expansion.Expand(mount.SubPathExpr, func(key string) string {\n\t\tvalue, ok := envmap[key]\n\t\tif !ok || len(value) == 0 {\n\t\t\tmissingKeys.Insert(key)\n\t\t}\n\t\treturn value\n\t})\n\n\tif len(missingKeys) \u003e 0 {\n\t\treturn \"\", fmt.Errorf(\"missing value for %s\", strings.Join(missingKeys.List(), \", \"))\n\t}\n\treturn expanded, nil\n}","line":{"from":171,"to":188}} {"id":100006354,"name":"ExpandContainerCommandAndArgs","signature":"func ExpandContainerCommandAndArgs(container *v1.Container, envs []EnvVar) (command []string, args []string)","file":"pkg/kubelet/container/helpers.go","code":"// ExpandContainerCommandAndArgs expands the given Container's command by replacing variable references `with the values of given EnvVar.\nfunc ExpandContainerCommandAndArgs(container *v1.Container, envs []EnvVar) (command []string, args []string) {\n\tmapping := expansion.MappingFuncFor(envVarsToMap(envs))\n\n\tif len(container.Command) != 0 {\n\t\tfor _, cmd := range container.Command {\n\t\t\tcommand = append(command, expansion.Expand(cmd, mapping))\n\t\t}\n\t}\n\n\tif len(container.Args) != 0 {\n\t\tfor _, arg := range container.Args {\n\t\t\targs = append(args, expansion.Expand(arg, mapping))\n\t\t}\n\t}\n\n\treturn command, args\n}","line":{"from":190,"to":207}} {"id":100006355,"name":"FilterEventRecorder","signature":"func FilterEventRecorder(recorder record.EventRecorder) record.EventRecorder","file":"pkg/kubelet/container/helpers.go","code":"// FilterEventRecorder creates an event recorder to record object's event except implicitly required container's, like infra container.\nfunc FilterEventRecorder(recorder record.EventRecorder) record.EventRecorder {\n\treturn \u0026innerEventRecorder{\n\t\trecorder: recorder,\n\t}\n}","line":{"from":209,"to":214}} {"id":100006356,"name":"shouldRecordEvent","signature":"func (irecorder *innerEventRecorder) shouldRecordEvent(object runtime.Object) (*v1.ObjectReference, bool)","file":"pkg/kubelet/container/helpers.go","code":"func (irecorder *innerEventRecorder) shouldRecordEvent(object runtime.Object) (*v1.ObjectReference, bool) {\n\tif ref, ok := object.(*v1.ObjectReference); ok {\n\t\t// this check is needed AFTER the cast. See https://github.com/kubernetes/kubernetes/issues/95552\n\t\tif ref == nil {\n\t\t\treturn nil, false\n\t\t}\n\t\tif !strings.HasPrefix(ref.FieldPath, ImplicitContainerPrefix) {\n\t\t\treturn ref, true\n\t\t}\n\t}\n\treturn nil, false\n}","line":{"from":220,"to":231}} {"id":100006357,"name":"Event","signature":"func (irecorder *innerEventRecorder) Event(object runtime.Object, eventtype, reason, message string)","file":"pkg/kubelet/container/helpers.go","code":"func (irecorder *innerEventRecorder) Event(object runtime.Object, eventtype, reason, message string) {\n\tif ref, ok := irecorder.shouldRecordEvent(object); ok {\n\t\tirecorder.recorder.Event(ref, eventtype, reason, message)\n\t}\n}","line":{"from":233,"to":237}} {"id":100006358,"name":"Eventf","signature":"func (irecorder *innerEventRecorder) Eventf(object runtime.Object, eventtype, reason, messageFmt string, args ...interface{})","file":"pkg/kubelet/container/helpers.go","code":"func (irecorder *innerEventRecorder) Eventf(object runtime.Object, eventtype, reason, messageFmt string, args ...interface{}) {\n\tif ref, ok := irecorder.shouldRecordEvent(object); ok {\n\t\tirecorder.recorder.Eventf(ref, eventtype, reason, messageFmt, args...)\n\t}\n\n}","line":{"from":239,"to":244}} {"id":100006359,"name":"AnnotatedEventf","signature":"func (irecorder *innerEventRecorder) AnnotatedEventf(object runtime.Object, annotations map[string]string, eventtype, reason, messageFmt string, args ...interface{})","file":"pkg/kubelet/container/helpers.go","code":"func (irecorder *innerEventRecorder) AnnotatedEventf(object runtime.Object, annotations map[string]string, eventtype, reason, messageFmt string, args ...interface{}) {\n\tif ref, ok := irecorder.shouldRecordEvent(object); ok {\n\t\tirecorder.recorder.AnnotatedEventf(ref, annotations, eventtype, reason, messageFmt, args...)\n\t}\n\n}","line":{"from":246,"to":251}} {"id":100006360,"name":"IsHostNetworkPod","signature":"func IsHostNetworkPod(pod *v1.Pod) bool","file":"pkg/kubelet/container/helpers.go","code":"// IsHostNetworkPod returns whether the host networking requested for the given Pod.\n// Pod must not be nil.\nfunc IsHostNetworkPod(pod *v1.Pod) bool {\n\treturn pod.Spec.HostNetwork\n}","line":{"from":253,"to":257}} {"id":100006361,"name":"ConvertPodStatusToRunningPod","signature":"func ConvertPodStatusToRunningPod(runtimeName string, podStatus *PodStatus) Pod","file":"pkg/kubelet/container/helpers.go","code":"// ConvertPodStatusToRunningPod returns Pod given PodStatus and container runtime string.\n// TODO(random-liu): Convert PodStatus to running Pod, should be deprecated soon\nfunc ConvertPodStatusToRunningPod(runtimeName string, podStatus *PodStatus) Pod {\n\trunningPod := Pod{\n\t\tID: podStatus.ID,\n\t\tName: podStatus.Name,\n\t\tNamespace: podStatus.Namespace,\n\t}\n\tfor _, containerStatus := range podStatus.ContainerStatuses {\n\t\tif containerStatus.State != ContainerStateRunning {\n\t\t\tcontinue\n\t\t}\n\t\tcontainer := \u0026Container{\n\t\t\tID: containerStatus.ID,\n\t\t\tName: containerStatus.Name,\n\t\t\tImage: containerStatus.Image,\n\t\t\tImageID: containerStatus.ImageID,\n\t\t\tHash: containerStatus.Hash,\n\t\t\tHashWithoutResources: containerStatus.HashWithoutResources,\n\t\t\tState: containerStatus.State,\n\t\t}\n\t\trunningPod.Containers = append(runningPod.Containers, container)\n\t}\n\n\t// Populate sandboxes in kubecontainer.Pod\n\tfor _, sandbox := range podStatus.SandboxStatuses {\n\t\trunningPod.Sandboxes = append(runningPod.Sandboxes, \u0026Container{\n\t\t\tID: ContainerID{Type: runtimeName, ID: sandbox.Id},\n\t\t\tState: SandboxToContainerState(sandbox.State),\n\t\t})\n\t}\n\treturn runningPod\n}","line":{"from":259,"to":291}} {"id":100006362,"name":"SandboxToContainerState","signature":"func SandboxToContainerState(state runtimeapi.PodSandboxState) State","file":"pkg/kubelet/container/helpers.go","code":"// SandboxToContainerState converts runtimeapi.PodSandboxState to\n// kubecontainer.State.\n// This is only needed because we need to return sandboxes as if they were\n// kubecontainer.Containers to avoid substantial changes to PLEG.\n// TODO: Remove this once it becomes obsolete.\nfunc SandboxToContainerState(state runtimeapi.PodSandboxState) State {\n\tswitch state {\n\tcase runtimeapi.PodSandboxState_SANDBOX_READY:\n\t\treturn ContainerStateRunning\n\tcase runtimeapi.PodSandboxState_SANDBOX_NOTREADY:\n\t\treturn ContainerStateExited\n\t}\n\treturn ContainerStateUnknown\n}","line":{"from":293,"to":306}} {"id":100006363,"name":"GetContainerSpec","signature":"func GetContainerSpec(pod *v1.Pod, containerName string) *v1.Container","file":"pkg/kubelet/container/helpers.go","code":"// GetContainerSpec gets the container spec by containerName.\nfunc GetContainerSpec(pod *v1.Pod, containerName string) *v1.Container {\n\tvar containerSpec *v1.Container\n\tpodutil.VisitContainers(\u0026pod.Spec, podutil.AllFeatureEnabledContainers(), func(c *v1.Container, containerType podutil.ContainerType) bool {\n\t\tif containerName == c.Name {\n\t\t\tcontainerSpec = c\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t})\n\treturn containerSpec\n}","line":{"from":308,"to":319}} {"id":100006364,"name":"HasPrivilegedContainer","signature":"func HasPrivilegedContainer(pod *v1.Pod) bool","file":"pkg/kubelet/container/helpers.go","code":"// HasPrivilegedContainer returns true if any of the containers in the pod are privileged.\nfunc HasPrivilegedContainer(pod *v1.Pod) bool {\n\tvar hasPrivileged bool\n\tpodutil.VisitContainers(\u0026pod.Spec, podutil.AllFeatureEnabledContainers(), func(c *v1.Container, containerType podutil.ContainerType) bool {\n\t\tif c.SecurityContext != nil \u0026\u0026 c.SecurityContext.Privileged != nil \u0026\u0026 *c.SecurityContext.Privileged {\n\t\t\thasPrivileged = true\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t})\n\treturn hasPrivileged\n}","line":{"from":321,"to":332}} {"id":100006365,"name":"HasWindowsHostProcessContainer","signature":"func HasWindowsHostProcessContainer(pod *v1.Pod) bool","file":"pkg/kubelet/container/helpers.go","code":"// HasWindowsHostProcessContainer returns true if any of the containers in a pod are HostProcess containers.\nfunc HasWindowsHostProcessContainer(pod *v1.Pod) bool {\n\tvar hasHostProcess bool\n\tpodutil.VisitContainers(\u0026pod.Spec, podutil.AllFeatureEnabledContainers(), func(c *v1.Container, containerType podutil.ContainerType) bool {\n\t\tif sc.HasWindowsHostProcessRequest(pod, c) {\n\t\t\thasHostProcess = true\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t})\n\n\treturn hasHostProcess\n}","line":{"from":334,"to":346}} {"id":100006366,"name":"AllContainersAreWindowsHostProcess","signature":"func AllContainersAreWindowsHostProcess(pod *v1.Pod) bool","file":"pkg/kubelet/container/helpers.go","code":"// AllContainersAreWindowsHostProcess returns true if all containers in a pod are HostProcess containers.\nfunc AllContainersAreWindowsHostProcess(pod *v1.Pod) bool {\n\tallHostProcess := true\n\tpodutil.VisitContainers(\u0026pod.Spec, podutil.AllFeatureEnabledContainers(), func(c *v1.Container, containerType podutil.ContainerType) bool {\n\t\tif !sc.HasWindowsHostProcessRequest(pod, c) {\n\t\t\tallHostProcess = false\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t})\n\n\treturn allHostProcess\n}","line":{"from":348,"to":360}} {"id":100006367,"name":"MakePortMappings","signature":"func MakePortMappings(container *v1.Container) (ports []PortMapping)","file":"pkg/kubelet/container/helpers.go","code":"// MakePortMappings creates internal port mapping from api port mapping.\nfunc MakePortMappings(container *v1.Container) (ports []PortMapping) {\n\tnames := make(map[string]struct{})\n\tfor _, p := range container.Ports {\n\t\tpm := PortMapping{\n\t\t\tHostPort: int(p.HostPort),\n\t\t\tContainerPort: int(p.ContainerPort),\n\t\t\tProtocol: p.Protocol,\n\t\t\tHostIP: p.HostIP,\n\t\t}\n\n\t\t// We need to determine the address family this entry applies to. We do this to ensure\n\t\t// duplicate containerPort / protocol rules work across different address families.\n\t\t// https://github.com/kubernetes/kubernetes/issues/82373\n\t\tfamily := \"any\"\n\t\tif p.HostIP != \"\" {\n\t\t\tif utilsnet.IsIPv6String(p.HostIP) {\n\t\t\t\tfamily = \"v6\"\n\t\t\t} else {\n\t\t\t\tfamily = \"v4\"\n\t\t\t}\n\t\t}\n\n\t\tvar name = p.Name\n\t\tif name == \"\" {\n\t\t\tname = fmt.Sprintf(\"%s-%s-%s:%d:%d\", family, p.Protocol, p.HostIP, p.ContainerPort, p.HostPort)\n\t\t}\n\n\t\t// Protect against a port name being used more than once in a container.\n\t\tif _, ok := names[name]; ok {\n\t\t\tklog.InfoS(\"Port name conflicted, it is defined more than once\", \"portName\", name)\n\t\t\tcontinue\n\t\t}\n\t\tports = append(ports, pm)\n\t\tnames[name] = struct{}{}\n\t}\n\treturn\n}","line":{"from":362,"to":399}} {"id":100006368,"name":"MkdirAll","signature":"func (RealOS) MkdirAll(path string, perm os.FileMode) error","file":"pkg/kubelet/container/os.go","code":"// MkdirAll will call os.MkdirAll to create a directory.\nfunc (RealOS) MkdirAll(path string, perm os.FileMode) error {\n\treturn os.MkdirAll(path, perm)\n}","line":{"from":48,"to":51}} {"id":100006369,"name":"Symlink","signature":"func (RealOS) Symlink(oldname string, newname string) error","file":"pkg/kubelet/container/os.go","code":"// Symlink will call os.Symlink to create a symbolic link.\nfunc (RealOS) Symlink(oldname string, newname string) error {\n\treturn os.Symlink(oldname, newname)\n}","line":{"from":53,"to":56}} {"id":100006370,"name":"Stat","signature":"func (RealOS) Stat(path string) (os.FileInfo, error)","file":"pkg/kubelet/container/os.go","code":"// Stat will call os.Stat to get the FileInfo for a given path\nfunc (RealOS) Stat(path string) (os.FileInfo, error) {\n\treturn os.Stat(path)\n}","line":{"from":58,"to":61}} {"id":100006371,"name":"Remove","signature":"func (RealOS) Remove(path string) error","file":"pkg/kubelet/container/os.go","code":"// Remove will call os.Remove to remove the path.\nfunc (RealOS) Remove(path string) error {\n\treturn os.Remove(path)\n}","line":{"from":63,"to":66}} {"id":100006372,"name":"RemoveAll","signature":"func (RealOS) RemoveAll(path string) error","file":"pkg/kubelet/container/os.go","code":"// RemoveAll will call os.RemoveAll to remove the path and its children.\nfunc (RealOS) RemoveAll(path string) error {\n\treturn os.RemoveAll(path)\n}","line":{"from":68,"to":71}} {"id":100006373,"name":"Create","signature":"func (RealOS) Create(path string) (*os.File, error)","file":"pkg/kubelet/container/os.go","code":"// Create will call os.Create to create and return a file\n// at path.\nfunc (RealOS) Create(path string) (*os.File, error) {\n\treturn os.Create(path)\n}","line":{"from":73,"to":77}} {"id":100006374,"name":"Chmod","signature":"func (RealOS) Chmod(path string, perm os.FileMode) error","file":"pkg/kubelet/container/os.go","code":"// Chmod will change the permissions on the specified path or return\n// an error.\nfunc (RealOS) Chmod(path string, perm os.FileMode) error {\n\treturn os.Chmod(path, perm)\n}","line":{"from":79,"to":83}} {"id":100006375,"name":"Hostname","signature":"func (RealOS) Hostname() (name string, err error)","file":"pkg/kubelet/container/os.go","code":"// Hostname will call os.Hostname to return the hostname.\nfunc (RealOS) Hostname() (name string, err error) {\n\treturn os.Hostname()\n}","line":{"from":85,"to":88}} {"id":100006376,"name":"Chtimes","signature":"func (RealOS) Chtimes(path string, atime time.Time, mtime time.Time) error","file":"pkg/kubelet/container/os.go","code":"// Chtimes will call os.Chtimes to change the atime and mtime of the path\nfunc (RealOS) Chtimes(path string, atime time.Time, mtime time.Time) error {\n\treturn os.Chtimes(path, atime, mtime)\n}","line":{"from":90,"to":93}} {"id":100006377,"name":"Pipe","signature":"func (RealOS) Pipe() (r *os.File, w *os.File, err error)","file":"pkg/kubelet/container/os.go","code":"// Pipe will call os.Pipe to return a connected pair of pipe.\nfunc (RealOS) Pipe() (r *os.File, w *os.File, err error) {\n\treturn os.Pipe()\n}","line":{"from":95,"to":98}} {"id":100006378,"name":"ReadDir","signature":"func (RealOS) ReadDir(dirname string) ([]os.DirEntry, error)","file":"pkg/kubelet/container/os.go","code":"// ReadDir will call os.ReadDir to return the files under the directory.\nfunc (RealOS) ReadDir(dirname string) ([]os.DirEntry, error) {\n\treturn os.ReadDir(dirname)\n}","line":{"from":100,"to":103}} {"id":100006379,"name":"Glob","signature":"func (RealOS) Glob(pattern string) ([]string, error)","file":"pkg/kubelet/container/os.go","code":"// Glob will call filepath.Glob to return the names of all files matching\n// pattern.\nfunc (RealOS) Glob(pattern string) ([]string, error) {\n\treturn filepath.Glob(pattern)\n}","line":{"from":105,"to":109}} {"id":100006380,"name":"Open","signature":"func (RealOS) Open(name string) (*os.File, error)","file":"pkg/kubelet/container/os.go","code":"// Open will call os.Open to return the file.\nfunc (RealOS) Open(name string) (*os.File, error) {\n\treturn os.Open(name)\n}","line":{"from":111,"to":114}} {"id":100006381,"name":"OpenFile","signature":"func (RealOS) OpenFile(name string, flag int, perm os.FileMode) (*os.File, error)","file":"pkg/kubelet/container/os.go","code":"// OpenFile will call os.OpenFile to return the file.\nfunc (RealOS) OpenFile(name string, flag int, perm os.FileMode) (*os.File, error) {\n\treturn os.OpenFile(name, flag, perm)\n}","line":{"from":116,"to":119}} {"id":100006382,"name":"Rename","signature":"func (RealOS) Rename(oldpath, newpath string) error","file":"pkg/kubelet/container/os.go","code":"// Rename will call os.Rename to rename a file.\nfunc (RealOS) Rename(oldpath, newpath string) error {\n\treturn os.Rename(oldpath, newpath)\n}","line":{"from":121,"to":124}} {"id":100006383,"name":"GenerateContainerRef","signature":"func GenerateContainerRef(pod *v1.Pod, container *v1.Container) (*v1.ObjectReference, error)","file":"pkg/kubelet/container/ref.go","code":"// GenerateContainerRef returns an *v1.ObjectReference which references the given container\n// within the given pod. Returns an error if the reference can't be constructed or the\n// container doesn't actually belong to the pod.\nfunc GenerateContainerRef(pod *v1.Pod, container *v1.Container) (*v1.ObjectReference, error) {\n\tfieldPath, err := fieldPath(pod, container)\n\tif err != nil {\n\t\t// TODO: figure out intelligent way to refer to containers that we implicitly\n\t\t// start (like the pod infra container). This is not a good way, ugh.\n\t\tfieldPath = ImplicitContainerPrefix + container.Name\n\t}\n\tref, err := ref.GetPartialReference(legacyscheme.Scheme, pod, fieldPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ref, nil\n}","line":{"from":30,"to":45}} {"id":100006384,"name":"fieldPath","signature":"func fieldPath(pod *v1.Pod, container *v1.Container) (string, error)","file":"pkg/kubelet/container/ref.go","code":"// fieldPath returns a fieldPath locating container within pod.\n// Returns an error if the container isn't part of the pod.\nfunc fieldPath(pod *v1.Pod, container *v1.Container) (string, error) {\n\tfor i := range pod.Spec.Containers {\n\t\there := \u0026pod.Spec.Containers[i]\n\t\tif here.Name == container.Name {\n\t\t\tif here.Name == \"\" {\n\t\t\t\treturn fmt.Sprintf(\"spec.containers[%d]\", i), nil\n\t\t\t}\n\t\t\treturn fmt.Sprintf(\"spec.containers{%s}\", here.Name), nil\n\t\t}\n\t}\n\tfor i := range pod.Spec.InitContainers {\n\t\there := \u0026pod.Spec.InitContainers[i]\n\t\tif here.Name == container.Name {\n\t\t\tif here.Name == \"\" {\n\t\t\t\treturn fmt.Sprintf(\"spec.initContainers[%d]\", i), nil\n\t\t\t}\n\t\t\treturn fmt.Sprintf(\"spec.initContainers{%s}\", here.Name), nil\n\t\t}\n\t}\n\tfor i := range pod.Spec.EphemeralContainers {\n\t\there := \u0026pod.Spec.EphemeralContainers[i]\n\t\tif here.Name == container.Name {\n\t\t\tif here.Name == \"\" {\n\t\t\t\treturn fmt.Sprintf(\"spec.ephemeralContainers[%d]\", i), nil\n\t\t\t}\n\t\t\treturn fmt.Sprintf(\"spec.ephemeralContainers{%s}\", here.Name), nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"container %q not found in pod %s/%s\", container.Name, pod.Namespace, pod.Name)\n}","line":{"from":47,"to":78}} {"id":100006385,"name":"BuildContainerID","signature":"func BuildContainerID(typ, ID string) ContainerID","file":"pkg/kubelet/container/runtime.go","code":"// BuildContainerID returns the ContainerID given type and id.\nfunc BuildContainerID(typ, ID string) ContainerID {\n\treturn ContainerID{Type: typ, ID: ID}\n}","line":{"from":213,"to":216}} {"id":100006386,"name":"ParseContainerID","signature":"func ParseContainerID(containerID string) ContainerID","file":"pkg/kubelet/container/runtime.go","code":"// ParseContainerID is a convenience method for creating a ContainerID from an ID string.\nfunc ParseContainerID(containerID string) ContainerID {\n\tvar id ContainerID\n\tif err := id.ParseString(containerID); err != nil {\n\t\tklog.ErrorS(err, \"Parsing containerID failed\")\n\t}\n\treturn id\n}","line":{"from":218,"to":225}} {"id":100006387,"name":"ParseString","signature":"func (c *ContainerID) ParseString(data string) error","file":"pkg/kubelet/container/runtime.go","code":"// ParseString converts given string into ContainerID\nfunc (c *ContainerID) ParseString(data string) error {\n\t// Trim the quotes and split the type and ID.\n\tparts := strings.Split(strings.Trim(data, \"\\\"\"), \"://\")\n\tif len(parts) != 2 {\n\t\treturn fmt.Errorf(\"invalid container ID: %q\", data)\n\t}\n\tc.Type, c.ID = parts[0], parts[1]\n\treturn nil\n}","line":{"from":227,"to":236}} {"id":100006388,"name":"String","signature":"func (c *ContainerID) String() string","file":"pkg/kubelet/container/runtime.go","code":"func (c *ContainerID) String() string {\n\treturn fmt.Sprintf(\"%s://%s\", c.Type, c.ID)\n}","line":{"from":238,"to":240}} {"id":100006389,"name":"IsEmpty","signature":"func (c *ContainerID) IsEmpty() bool","file":"pkg/kubelet/container/runtime.go","code":"// IsEmpty returns whether given ContainerID is empty.\nfunc (c *ContainerID) IsEmpty() bool {\n\treturn *c == ContainerID{}\n}","line":{"from":242,"to":245}} {"id":100006390,"name":"MarshalJSON","signature":"func (c *ContainerID) MarshalJSON() ([]byte, error)","file":"pkg/kubelet/container/runtime.go","code":"// MarshalJSON formats a given ContainerID into a byte array.\nfunc (c *ContainerID) MarshalJSON() ([]byte, error) {\n\treturn []byte(fmt.Sprintf(\"%q\", c.String())), nil\n}","line":{"from":247,"to":250}} {"id":100006391,"name":"UnmarshalJSON","signature":"func (c *ContainerID) UnmarshalJSON(data []byte) error","file":"pkg/kubelet/container/runtime.go","code":"// UnmarshalJSON parses ContainerID from a given array of bytes.\nfunc (c *ContainerID) UnmarshalJSON(data []byte) error {\n\treturn c.ParseString(string(data))\n}","line":{"from":252,"to":255}} {"id":100006392,"name":"FindContainerStatusByName","signature":"func (podStatus *PodStatus) FindContainerStatusByName(containerName string) *Status","file":"pkg/kubelet/container/runtime.go","code":"// FindContainerStatusByName returns container status in the pod status with the given name.\n// When there are multiple containers' statuses with the same name, the first match will be returned.\nfunc (podStatus *PodStatus) FindContainerStatusByName(containerName string) *Status {\n\tfor _, containerStatus := range podStatus.ContainerStatuses {\n\t\tif containerStatus.Name == containerName {\n\t\t\treturn containerStatus\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":365,"to":374}} {"id":100006393,"name":"GetRunningContainerStatuses","signature":"func (podStatus *PodStatus) GetRunningContainerStatuses() []*Status","file":"pkg/kubelet/container/runtime.go","code":"// GetRunningContainerStatuses returns container status of all the running containers in a pod\nfunc (podStatus *PodStatus) GetRunningContainerStatuses() []*Status {\n\trunningContainerStatuses := []*Status{}\n\tfor _, containerStatus := range podStatus.ContainerStatuses {\n\t\tif containerStatus.State == ContainerStateRunning {\n\t\t\trunningContainerStatuses = append(runningContainerStatuses, containerStatus)\n\t\t}\n\t}\n\treturn runningContainerStatuses\n}","line":{"from":376,"to":385}} {"id":100006394,"name":"GetRuntimeCondition","signature":"func (r *RuntimeStatus) GetRuntimeCondition(t RuntimeConditionType) *RuntimeCondition","file":"pkg/kubelet/container/runtime.go","code":"// GetRuntimeCondition gets a specified runtime condition from the runtime status.\nfunc (r *RuntimeStatus) GetRuntimeCondition(t RuntimeConditionType) *RuntimeCondition {\n\tfor i := range r.Conditions {\n\t\tc := \u0026r.Conditions[i]\n\t\tif c.Type == t {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":527,"to":536}} {"id":100006395,"name":"String","signature":"func (r *RuntimeStatus) String() string","file":"pkg/kubelet/container/runtime.go","code":"// String formats the runtime status into human readable string.\nfunc (r *RuntimeStatus) String() string {\n\tvar ss []string\n\tfor _, c := range r.Conditions {\n\t\tss = append(ss, c.String())\n\t}\n\treturn fmt.Sprintf(\"Runtime Conditions: %s\", strings.Join(ss, \", \"))\n}","line":{"from":538,"to":545}} {"id":100006396,"name":"String","signature":"func (c *RuntimeCondition) String() string","file":"pkg/kubelet/container/runtime.go","code":"// String formats the runtime condition into human readable string.\nfunc (c *RuntimeCondition) String() string {\n\treturn fmt.Sprintf(\"%s=%t reason:%s message:%s\", c.Type, c.Status, c.Reason, c.Message)\n}","line":{"from":559,"to":562}} {"id":100006397,"name":"FindPodByID","signature":"func (p Pods) FindPodByID(podUID types.UID) Pod","file":"pkg/kubelet/container/runtime.go","code":"// FindPodByID finds and returns a pod in the pod list by UID. It will return an empty pod\n// if not found.\nfunc (p Pods) FindPodByID(podUID types.UID) Pod {\n\tfor i := range p {\n\t\tif p[i].ID == podUID {\n\t\t\treturn *p[i]\n\t\t}\n\t}\n\treturn Pod{}\n}","line":{"from":567,"to":576}} {"id":100006398,"name":"FindPodByFullName","signature":"func (p Pods) FindPodByFullName(podFullName string) Pod","file":"pkg/kubelet/container/runtime.go","code":"// FindPodByFullName finds and returns a pod in the pod list by the full name.\n// It will return an empty pod if not found.\nfunc (p Pods) FindPodByFullName(podFullName string) Pod {\n\tfor i := range p {\n\t\tif BuildPodFullName(p[i].Name, p[i].Namespace) == podFullName {\n\t\t\treturn *p[i]\n\t\t}\n\t}\n\treturn Pod{}\n}","line":{"from":578,"to":587}} {"id":100006399,"name":"FindPod","signature":"func (p Pods) FindPod(podFullName string, podUID types.UID) Pod","file":"pkg/kubelet/container/runtime.go","code":"// FindPod combines FindPodByID and FindPodByFullName, it finds and returns a pod in the\n// pod list either by the full name or the pod ID. It will return an empty pod\n// if not found.\nfunc (p Pods) FindPod(podFullName string, podUID types.UID) Pod {\n\tif len(podFullName) \u003e 0 {\n\t\treturn p.FindPodByFullName(podFullName)\n\t}\n\treturn p.FindPodByID(podUID)\n}","line":{"from":589,"to":597}} {"id":100006400,"name":"FindContainerByName","signature":"func (p *Pod) FindContainerByName(containerName string) *Container","file":"pkg/kubelet/container/runtime.go","code":"// FindContainerByName returns a container in the pod with the given name.\n// When there are multiple containers with the same name, the first match will\n// be returned.\nfunc (p *Pod) FindContainerByName(containerName string) *Container {\n\tfor _, c := range p.Containers {\n\t\tif c.Name == containerName {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":599,"to":609}} {"id":100006401,"name":"FindContainerByID","signature":"func (p *Pod) FindContainerByID(id ContainerID) *Container","file":"pkg/kubelet/container/runtime.go","code":"// FindContainerByID returns a container in the pod with the given ContainerID.\nfunc (p *Pod) FindContainerByID(id ContainerID) *Container {\n\tfor _, c := range p.Containers {\n\t\tif c.ID == id {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":611,"to":619}} {"id":100006402,"name":"FindSandboxByID","signature":"func (p *Pod) FindSandboxByID(id ContainerID) *Container","file":"pkg/kubelet/container/runtime.go","code":"// FindSandboxByID returns a sandbox in the pod with the given ContainerID.\nfunc (p *Pod) FindSandboxByID(id ContainerID) *Container {\n\tfor _, c := range p.Sandboxes {\n\t\tif c.ID == id {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":621,"to":629}} {"id":100006403,"name":"ToAPIPod","signature":"func (p *Pod) ToAPIPod() *v1.Pod","file":"pkg/kubelet/container/runtime.go","code":"// ToAPIPod converts Pod to v1.Pod. Note that if a field in v1.Pod has no\n// corresponding field in Pod, the field would not be populated.\nfunc (p *Pod) ToAPIPod() *v1.Pod {\n\tvar pod v1.Pod\n\tpod.UID = p.ID\n\tpod.Name = p.Name\n\tpod.Namespace = p.Namespace\n\n\tfor _, c := range p.Containers {\n\t\tvar container v1.Container\n\t\tcontainer.Name = c.Name\n\t\tcontainer.Image = c.Image\n\t\tpod.Spec.Containers = append(pod.Spec.Containers, container)\n\t}\n\treturn \u0026pod\n}","line":{"from":631,"to":646}} {"id":100006404,"name":"IsEmpty","signature":"func (p *Pod) IsEmpty() bool","file":"pkg/kubelet/container/runtime.go","code":"// IsEmpty returns true if the pod is empty.\nfunc (p *Pod) IsEmpty() bool {\n\treturn reflect.DeepEqual(p, \u0026Pod{})\n}","line":{"from":648,"to":651}} {"id":100006405,"name":"GetPodFullName","signature":"func GetPodFullName(pod *v1.Pod) string","file":"pkg/kubelet/container/runtime.go","code":"// GetPodFullName returns a name that uniquely identifies a pod.\nfunc GetPodFullName(pod *v1.Pod) string {\n\t// Use underscore as the delimiter because it is not allowed in pod name\n\t// (DNS subdomain format), while allowed in the container name format.\n\treturn pod.Name + \"_\" + pod.Namespace\n}","line":{"from":653,"to":658}} {"id":100006406,"name":"BuildPodFullName","signature":"func BuildPodFullName(name, namespace string) string","file":"pkg/kubelet/container/runtime.go","code":"// BuildPodFullName builds the pod full name from pod name and namespace.\nfunc BuildPodFullName(name, namespace string) string {\n\treturn name + \"_\" + namespace\n}","line":{"from":660,"to":663}} {"id":100006407,"name":"ParsePodFullName","signature":"func ParsePodFullName(podFullName string) (string, string, error)","file":"pkg/kubelet/container/runtime.go","code":"// ParsePodFullName parsed the pod full name.\nfunc ParsePodFullName(podFullName string) (string, string, error) {\n\tparts := strings.Split(podFullName, \"_\")\n\tif len(parts) != 2 || parts[0] == \"\" || parts[1] == \"\" {\n\t\treturn \"\", \"\", fmt.Errorf(\"failed to parse the pod full name %q\", podFullName)\n\t}\n\treturn parts[0], parts[1], nil\n}","line":{"from":665,"to":672}} {"id":100006408,"name":"Len","signature":"func (s SortContainerStatusesByCreationTime) Len() int { return len(s) }","file":"pkg/kubelet/container/runtime.go","code":"func (s SortContainerStatusesByCreationTime) Len() int { return len(s) }","line":{"from":681,"to":681}} {"id":100006409,"name":"Swap","signature":"func (s SortContainerStatusesByCreationTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","file":"pkg/kubelet/container/runtime.go","code":"func (s SortContainerStatusesByCreationTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","line":{"from":682,"to":682}} {"id":100006410,"name":"Less","signature":"func (s SortContainerStatusesByCreationTime) Less(i, j int) bool","file":"pkg/kubelet/container/runtime.go","code":"func (s SortContainerStatusesByCreationTime) Less(i, j int) bool {\n\treturn s[i].CreatedAt.Before(s[j].CreatedAt)\n}","line":{"from":683,"to":685}} {"id":100006411,"name":"NewRuntimeCache","signature":"func NewRuntimeCache(getter podsGetter, cachePeriod time.Duration) (RuntimeCache, error)","file":"pkg/kubelet/container/runtime_cache.go","code":"// NewRuntimeCache creates a container runtime cache.\nfunc NewRuntimeCache(getter podsGetter, cachePeriod time.Duration) (RuntimeCache, error) {\n\treturn \u0026runtimeCache{\n\t\tgetter: getter,\n\t\tcachePeriod: cachePeriod,\n\t}, nil\n}","line":{"from":36,"to":42}} {"id":100006412,"name":"GetPods","signature":"func (r *runtimeCache) GetPods(ctx context.Context) ([]*Pod, error)","file":"pkg/kubelet/container/runtime_cache.go","code":"// GetPods returns the cached pods if they are not outdated; otherwise, it\n// retrieves the latest pods and return them.\nfunc (r *runtimeCache) GetPods(ctx context.Context) ([]*Pod, error) {\n\tr.Lock()\n\tdefer r.Unlock()\n\tif time.Since(r.cacheTime) \u003e r.cachePeriod {\n\t\tif err := r.updateCache(ctx); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn r.pods, nil\n}","line":{"from":60,"to":71}} {"id":100006413,"name":"ForceUpdateIfOlder","signature":"func (r *runtimeCache) ForceUpdateIfOlder(ctx context.Context, minExpectedCacheTime time.Time) error","file":"pkg/kubelet/container/runtime_cache.go","code":"func (r *runtimeCache) ForceUpdateIfOlder(ctx context.Context, minExpectedCacheTime time.Time) error {\n\tr.Lock()\n\tdefer r.Unlock()\n\tif r.cacheTime.Before(minExpectedCacheTime) {\n\t\treturn r.updateCache(ctx)\n\t}\n\treturn nil\n}","line":{"from":73,"to":80}} {"id":100006414,"name":"updateCache","signature":"func (r *runtimeCache) updateCache(ctx context.Context) error","file":"pkg/kubelet/container/runtime_cache.go","code":"func (r *runtimeCache) updateCache(ctx context.Context) error {\n\tpods, timestamp, err := r.getPodsWithTimestamp(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.pods, r.cacheTime = pods, timestamp\n\treturn nil\n}","line":{"from":82,"to":89}} {"id":100006415,"name":"getPodsWithTimestamp","signature":"func (r *runtimeCache) getPodsWithTimestamp(ctx context.Context) ([]*Pod, time.Time, error)","file":"pkg/kubelet/container/runtime_cache.go","code":"// getPodsWithTimestamp records a timestamp and retrieves pods from the getter.\nfunc (r *runtimeCache) getPodsWithTimestamp(ctx context.Context) ([]*Pod, time.Time, error) {\n\t// Always record the timestamp before getting the pods to avoid stale pods.\n\ttimestamp := time.Now()\n\tpods, err := r.getter.GetPods(ctx, false)\n\treturn pods, timestamp, err\n}","line":{"from":91,"to":97}} {"id":100006416,"name":"NewSyncResult","signature":"func NewSyncResult(action SyncAction, target interface{}) *SyncResult","file":"pkg/kubelet/container/sync_result.go","code":"// NewSyncResult generates new SyncResult with specific Action and Target\nfunc NewSyncResult(action SyncAction, target interface{}) *SyncResult {\n\treturn \u0026SyncResult{Action: action, Target: target}\n}","line":{"from":87,"to":90}} {"id":100006417,"name":"Fail","signature":"func (r *SyncResult) Fail(err error, msg string)","file":"pkg/kubelet/container/sync_result.go","code":"// Fail fails the SyncResult with specific error and message\nfunc (r *SyncResult) Fail(err error, msg string) {\n\tr.Error, r.Message = err, msg\n}","line":{"from":92,"to":95}} {"id":100006418,"name":"AddSyncResult","signature":"func (p *PodSyncResult) AddSyncResult(result ...*SyncResult)","file":"pkg/kubelet/container/sync_result.go","code":"// AddSyncResult adds multiple SyncResult to current PodSyncResult\nfunc (p *PodSyncResult) AddSyncResult(result ...*SyncResult) {\n\tp.SyncResults = append(p.SyncResults, result...)\n}","line":{"from":105,"to":108}} {"id":100006419,"name":"AddPodSyncResult","signature":"func (p *PodSyncResult) AddPodSyncResult(result PodSyncResult)","file":"pkg/kubelet/container/sync_result.go","code":"// AddPodSyncResult merges a PodSyncResult to current one\nfunc (p *PodSyncResult) AddPodSyncResult(result PodSyncResult) {\n\tp.AddSyncResult(result.SyncResults...)\n\tp.SyncError = result.SyncError\n}","line":{"from":110,"to":114}} {"id":100006420,"name":"Fail","signature":"func (p *PodSyncResult) Fail(err error)","file":"pkg/kubelet/container/sync_result.go","code":"// Fail fails the PodSyncResult with an error occurred in SyncPod() and KillPod() itself\nfunc (p *PodSyncResult) Fail(err error) {\n\tp.SyncError = err\n}","line":{"from":116,"to":119}} {"id":100006421,"name":"Error","signature":"func (p *PodSyncResult) Error() error","file":"pkg/kubelet/container/sync_result.go","code":"// Error returns an error summarizing all the errors in PodSyncResult\nfunc (p *PodSyncResult) Error() error {\n\terrlist := []error{}\n\tif p.SyncError != nil {\n\t\terrlist = append(errlist, fmt.Errorf(\"failed to SyncPod: %v\", p.SyncError))\n\t}\n\tfor _, result := range p.SyncResults {\n\t\tif result.Error != nil {\n\t\t\terrlist = append(errlist, fmt.Errorf(\"failed to %q for %q with %v: %q\", result.Action, result.Target,\n\t\t\t\tresult.Error, result.Message))\n\t\t}\n\t}\n\treturn utilerrors.NewAggregate(errlist)\n}","line":{"from":121,"to":134}} {"id":100006422,"name":"NewRemoteImageService","signature":"func NewRemoteImageService(endpoint string, connectionTimeout time.Duration, tp trace.TracerProvider) (internalapi.ImageManagerService, error)","file":"pkg/kubelet/cri/remote/remote_image.go","code":"// NewRemoteImageService creates a new internalapi.ImageManagerService.\nfunc NewRemoteImageService(endpoint string, connectionTimeout time.Duration, tp trace.TracerProvider) (internalapi.ImageManagerService, error) {\n\tklog.V(3).InfoS(\"Connecting to image service\", \"endpoint\", endpoint)\n\taddr, dialer, err := util.GetAddressAndDialer(endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), connectionTimeout)\n\tdefer cancel()\n\n\tdialOpts := []grpc.DialOption{}\n\tdialOpts = append(dialOpts,\n\t\tgrpc.WithTransportCredentials(insecure.NewCredentials()),\n\t\tgrpc.WithContextDialer(dialer),\n\t\tgrpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(maxMsgSize)))\n\tif utilfeature.DefaultFeatureGate.Enabled(features.KubeletTracing) {\n\t\ttracingOpts := []otelgrpc.Option{\n\t\t\totelgrpc.WithPropagators(tracing.Propagators()),\n\t\t\totelgrpc.WithTracerProvider(tp),\n\t\t}\n\t\t// Even if there is no TracerProvider, the otelgrpc still handles context propagation.\n\t\t// See https://github.com/open-telemetry/opentelemetry-go/tree/main/example/passthrough\n\t\tdialOpts = append(dialOpts,\n\t\t\tgrpc.WithUnaryInterceptor(otelgrpc.UnaryClientInterceptor(tracingOpts...)),\n\t\t\tgrpc.WithStreamInterceptor(otelgrpc.StreamClientInterceptor(tracingOpts...)))\n\t}\n\n\tconn, err := grpc.DialContext(ctx, addr, dialOpts...)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Connect remote image service failed\", \"address\", addr)\n\t\treturn nil, err\n\t}\n\n\tservice := \u0026remoteImageService{timeout: connectionTimeout}\n\tif err := service.validateServiceConnection(ctx, conn, endpoint); err != nil {\n\t\treturn nil, fmt.Errorf(\"validate service connection: %w\", err)\n\t}\n\n\treturn service, nil\n\n}","line":{"from":45,"to":86}} {"id":100006423,"name":"validateServiceConnection","signature":"func (r *remoteImageService) validateServiceConnection(ctx context.Context, conn *grpc.ClientConn, endpoint string) error","file":"pkg/kubelet/cri/remote/remote_image.go","code":"// validateServiceConnection tries to connect to the remote image service by\n// using the CRI v1 API version and fails if that's not possible.\nfunc (r *remoteImageService) validateServiceConnection(ctx context.Context, conn *grpc.ClientConn, endpoint string) error {\n\tklog.V(4).InfoS(\"Validating the CRI v1 API image version\")\n\tr.imageClient = runtimeapi.NewImageServiceClient(conn)\n\n\tif _, err := r.imageClient.ImageFsInfo(ctx, \u0026runtimeapi.ImageFsInfoRequest{}); err != nil {\n\t\treturn fmt.Errorf(\"validate CRI v1 image API for endpoint %q: %w\", endpoint, err)\n\t}\n\n\tklog.V(2).InfoS(\"Validated CRI v1 image API\")\n\treturn nil\n}","line":{"from":88,"to":100}} {"id":100006424,"name":"ListImages","signature":"func (r *remoteImageService) ListImages(ctx context.Context, filter *runtimeapi.ImageFilter) ([]*runtimeapi.Image, error)","file":"pkg/kubelet/cri/remote/remote_image.go","code":"// ListImages lists available images.\nfunc (r *remoteImageService) ListImages(ctx context.Context, filter *runtimeapi.ImageFilter) ([]*runtimeapi.Image, error) {\n\tctx, cancel := context.WithTimeout(ctx, r.timeout)\n\tdefer cancel()\n\n\treturn r.listImagesV1(ctx, filter)\n}","line":{"from":102,"to":108}} {"id":100006425,"name":"listImagesV1","signature":"func (r *remoteImageService) listImagesV1(ctx context.Context, filter *runtimeapi.ImageFilter) ([]*runtimeapi.Image, error)","file":"pkg/kubelet/cri/remote/remote_image.go","code":"func (r *remoteImageService) listImagesV1(ctx context.Context, filter *runtimeapi.ImageFilter) ([]*runtimeapi.Image, error) {\n\tresp, err := r.imageClient.ListImages(ctx, \u0026runtimeapi.ListImagesRequest{\n\t\tFilter: filter,\n\t})\n\tif err != nil {\n\t\tklog.ErrorS(err, \"ListImages with filter from image service failed\", \"filter\", filter)\n\t\treturn nil, err\n\t}\n\n\treturn resp.Images, nil\n}","line":{"from":110,"to":120}} {"id":100006426,"name":"ImageStatus","signature":"func (r *remoteImageService) ImageStatus(ctx context.Context, image *runtimeapi.ImageSpec, verbose bool) (*runtimeapi.ImageStatusResponse, error)","file":"pkg/kubelet/cri/remote/remote_image.go","code":"// ImageStatus returns the status of the image.\nfunc (r *remoteImageService) ImageStatus(ctx context.Context, image *runtimeapi.ImageSpec, verbose bool) (*runtimeapi.ImageStatusResponse, error) {\n\tctx, cancel := context.WithTimeout(ctx, r.timeout)\n\tdefer cancel()\n\n\treturn r.imageStatusV1(ctx, image, verbose)\n}","line":{"from":122,"to":128}} {"id":100006427,"name":"imageStatusV1","signature":"func (r *remoteImageService) imageStatusV1(ctx context.Context, image *runtimeapi.ImageSpec, verbose bool) (*runtimeapi.ImageStatusResponse, error)","file":"pkg/kubelet/cri/remote/remote_image.go","code":"func (r *remoteImageService) imageStatusV1(ctx context.Context, image *runtimeapi.ImageSpec, verbose bool) (*runtimeapi.ImageStatusResponse, error) {\n\tresp, err := r.imageClient.ImageStatus(ctx, \u0026runtimeapi.ImageStatusRequest{\n\t\tImage: image,\n\t\tVerbose: verbose,\n\t})\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Get ImageStatus from image service failed\", \"image\", image.Image)\n\t\treturn nil, err\n\t}\n\n\tif resp.Image != nil {\n\t\tif resp.Image.Id == \"\" || resp.Image.Size_ == 0 {\n\t\t\terrorMessage := fmt.Sprintf(\"Id or size of image %q is not set\", image.Image)\n\t\t\terr := errors.New(errorMessage)\n\t\t\tklog.ErrorS(err, \"ImageStatus failed\", \"image\", image.Image)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn resp, nil\n}","line":{"from":130,"to":150}} {"id":100006428,"name":"PullImage","signature":"func (r *remoteImageService) PullImage(ctx context.Context, image *runtimeapi.ImageSpec, auth *runtimeapi.AuthConfig, podSandboxConfig *runtimeapi.PodSandboxConfig) (string, error)","file":"pkg/kubelet/cri/remote/remote_image.go","code":"// PullImage pulls an image with authentication config.\nfunc (r *remoteImageService) PullImage(ctx context.Context, image *runtimeapi.ImageSpec, auth *runtimeapi.AuthConfig, podSandboxConfig *runtimeapi.PodSandboxConfig) (string, error) {\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\treturn r.pullImageV1(ctx, image, auth, podSandboxConfig)\n}","line":{"from":152,"to":158}} {"id":100006429,"name":"pullImageV1","signature":"func (r *remoteImageService) pullImageV1(ctx context.Context, image *runtimeapi.ImageSpec, auth *runtimeapi.AuthConfig, podSandboxConfig *runtimeapi.PodSandboxConfig) (string, error)","file":"pkg/kubelet/cri/remote/remote_image.go","code":"func (r *remoteImageService) pullImageV1(ctx context.Context, image *runtimeapi.ImageSpec, auth *runtimeapi.AuthConfig, podSandboxConfig *runtimeapi.PodSandboxConfig) (string, error) {\n\tresp, err := r.imageClient.PullImage(ctx, \u0026runtimeapi.PullImageRequest{\n\t\tImage: image,\n\t\tAuth: auth,\n\t\tSandboxConfig: podSandboxConfig,\n\t})\n\tif err != nil {\n\t\tklog.ErrorS(err, \"PullImage from image service failed\", \"image\", image.Image)\n\t\treturn \"\", err\n\t}\n\n\tif resp.ImageRef == \"\" {\n\t\tklog.ErrorS(errors.New(\"PullImage failed\"), \"ImageRef of image is not set\", \"image\", image.Image)\n\t\terrorMessage := fmt.Sprintf(\"imageRef of image %q is not set\", image.Image)\n\t\treturn \"\", errors.New(errorMessage)\n\t}\n\n\treturn resp.ImageRef, nil\n}","line":{"from":160,"to":178}} {"id":100006430,"name":"RemoveImage","signature":"func (r *remoteImageService) RemoveImage(ctx context.Context, image *runtimeapi.ImageSpec) (err error)","file":"pkg/kubelet/cri/remote/remote_image.go","code":"// RemoveImage removes the image.\nfunc (r *remoteImageService) RemoveImage(ctx context.Context, image *runtimeapi.ImageSpec) (err error) {\n\tctx, cancel := context.WithTimeout(ctx, r.timeout)\n\tdefer cancel()\n\n\tif _, err = r.imageClient.RemoveImage(ctx, \u0026runtimeapi.RemoveImageRequest{\n\t\tImage: image,\n\t}); err != nil {\n\t\tklog.ErrorS(err, \"RemoveImage from image service failed\", \"image\", image.Image)\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":180,"to":193}} {"id":100006431,"name":"ImageFsInfo","signature":"func (r *remoteImageService) ImageFsInfo(ctx context.Context) ([]*runtimeapi.FilesystemUsage, error)","file":"pkg/kubelet/cri/remote/remote_image.go","code":"// ImageFsInfo returns information of the filesystem that is used to store images.\nfunc (r *remoteImageService) ImageFsInfo(ctx context.Context) ([]*runtimeapi.FilesystemUsage, error) {\n\t// Do not set timeout, because `ImageFsInfo` takes time.\n\t// TODO(random-liu): Should we assume runtime should cache the result, and set timeout here?\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\treturn r.imageFsInfoV1(ctx)\n}","line":{"from":195,"to":203}} {"id":100006432,"name":"imageFsInfoV1","signature":"func (r *remoteImageService) imageFsInfoV1(ctx context.Context) ([]*runtimeapi.FilesystemUsage, error)","file":"pkg/kubelet/cri/remote/remote_image.go","code":"func (r *remoteImageService) imageFsInfoV1(ctx context.Context) ([]*runtimeapi.FilesystemUsage, error) {\n\tresp, err := r.imageClient.ImageFsInfo(ctx, \u0026runtimeapi.ImageFsInfoRequest{})\n\tif err != nil {\n\t\tklog.ErrorS(err, \"ImageFsInfo from image service failed\")\n\t\treturn nil, err\n\t}\n\treturn resp.GetImageFilesystems(), nil\n}","line":{"from":205,"to":212}} {"id":100006433,"name":"NewRemoteRuntimeService","signature":"func NewRemoteRuntimeService(endpoint string, connectionTimeout time.Duration, tp trace.TracerProvider) (internalapi.RuntimeService, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// NewRemoteRuntimeService creates a new internalapi.RuntimeService.\nfunc NewRemoteRuntimeService(endpoint string, connectionTimeout time.Duration, tp trace.TracerProvider) (internalapi.RuntimeService, error) {\n\tklog.V(3).InfoS(\"Connecting to runtime service\", \"endpoint\", endpoint)\n\taddr, dialer, err := util.GetAddressAndDialer(endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tctx, cancel := context.WithTimeout(context.Background(), connectionTimeout)\n\tdefer cancel()\n\n\tdialOpts := []grpc.DialOption{}\n\tdialOpts = append(dialOpts,\n\t\tgrpc.WithTransportCredentials(insecure.NewCredentials()),\n\t\tgrpc.WithContextDialer(dialer),\n\t\tgrpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(maxMsgSize)))\n\tif utilfeature.DefaultFeatureGate.Enabled(features.KubeletTracing) {\n\t\ttracingOpts := []otelgrpc.Option{\n\t\t\totelgrpc.WithPropagators(tracing.Propagators()),\n\t\t\totelgrpc.WithTracerProvider(tp),\n\t\t}\n\t\t// Even if there is no TracerProvider, the otelgrpc still handles context propagation.\n\t\t// See https://github.com/open-telemetry/opentelemetry-go/tree/main/example/passthrough\n\t\tdialOpts = append(dialOpts,\n\t\t\tgrpc.WithUnaryInterceptor(otelgrpc.UnaryClientInterceptor(tracingOpts...)),\n\t\t\tgrpc.WithStreamInterceptor(otelgrpc.StreamClientInterceptor(tracingOpts...)))\n\t}\n\tconn, err := grpc.DialContext(ctx, addr, dialOpts...)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Connect remote runtime failed\", \"address\", addr)\n\t\treturn nil, err\n\t}\n\n\tservice := \u0026remoteRuntimeService{\n\t\ttimeout: connectionTimeout,\n\t\tlogReduction: logreduction.NewLogReduction(identicalErrorDelay),\n\t}\n\n\tif err := service.validateServiceConnection(ctx, conn, endpoint); err != nil {\n\t\treturn nil, fmt.Errorf(\"validate service connection: %w\", err)\n\t}\n\n\treturn service, nil\n}","line":{"from":72,"to":114}} {"id":100006434,"name":"validateServiceConnection","signature":"func (r *remoteRuntimeService) validateServiceConnection(ctx context.Context, conn *grpc.ClientConn, endpoint string) error","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// validateServiceConnection tries to connect to the remote runtime service by\n// using the CRI v1 API version and fails if that's not possible.\nfunc (r *remoteRuntimeService) validateServiceConnection(ctx context.Context, conn *grpc.ClientConn, endpoint string) error {\n\tklog.V(4).InfoS(\"Validating the CRI v1 API runtime version\")\n\tr.runtimeClient = runtimeapi.NewRuntimeServiceClient(conn)\n\n\tif _, err := r.runtimeClient.Version(ctx, \u0026runtimeapi.VersionRequest{}); err != nil {\n\t\treturn fmt.Errorf(\"validate CRI v1 runtime API for endpoint %q: %w\", endpoint, err)\n\t}\n\n\tklog.V(2).InfoS(\"Validated CRI v1 runtime API\")\n\treturn nil\n}","line":{"from":116,"to":128}} {"id":100006435,"name":"Version","signature":"func (r *remoteRuntimeService) Version(ctx context.Context, apiVersion string) (*runtimeapi.VersionResponse, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// Version returns the runtime name, runtime version and runtime API version.\nfunc (r *remoteRuntimeService) Version(ctx context.Context, apiVersion string) (*runtimeapi.VersionResponse, error) {\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] Version\", \"apiVersion\", apiVersion, \"timeout\", r.timeout)\n\n\tctx, cancel := context.WithTimeout(ctx, r.timeout)\n\tdefer cancel()\n\n\treturn r.versionV1(ctx, apiVersion)\n}","line":{"from":130,"to":138}} {"id":100006436,"name":"versionV1","signature":"func (r *remoteRuntimeService) versionV1(ctx context.Context, apiVersion string) (*runtimeapi.VersionResponse, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"func (r *remoteRuntimeService) versionV1(ctx context.Context, apiVersion string) (*runtimeapi.VersionResponse, error) {\n\ttypedVersion, err := r.runtimeClient.Version(ctx, \u0026runtimeapi.VersionRequest{\n\t\tVersion: apiVersion,\n\t})\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Version from runtime service failed\")\n\t\treturn nil, err\n\t}\n\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] Version Response\", \"apiVersion\", typedVersion)\n\n\tif typedVersion.Version == \"\" || typedVersion.RuntimeName == \"\" || typedVersion.RuntimeApiVersion == \"\" || typedVersion.RuntimeVersion == \"\" {\n\t\treturn nil, fmt.Errorf(\"not all fields are set in VersionResponse (%q)\", *typedVersion)\n\t}\n\n\treturn typedVersion, err\n}","line":{"from":140,"to":156}} {"id":100006437,"name":"RunPodSandbox","signature":"func (r *remoteRuntimeService) RunPodSandbox(ctx context.Context, config *runtimeapi.PodSandboxConfig, runtimeHandler string) (string, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// RunPodSandbox creates and starts a pod-level sandbox. Runtimes should ensure\n// the sandbox is in ready state.\nfunc (r *remoteRuntimeService) RunPodSandbox(ctx context.Context, config *runtimeapi.PodSandboxConfig, runtimeHandler string) (string, error) {\n\t// Use 2 times longer timeout for sandbox operation (4 mins by default)\n\t// TODO: Make the pod sandbox timeout configurable.\n\ttimeout := r.timeout * 2\n\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] RunPodSandbox\", \"config\", config, \"runtimeHandler\", runtimeHandler, \"timeout\", timeout)\n\n\tctx, cancel := context.WithTimeout(ctx, timeout)\n\tdefer cancel()\n\n\tresp, err := r.runtimeClient.RunPodSandbox(ctx, \u0026runtimeapi.RunPodSandboxRequest{\n\t\tConfig: config,\n\t\tRuntimeHandler: runtimeHandler,\n\t})\n\n\tif err != nil {\n\t\tklog.ErrorS(err, \"RunPodSandbox from runtime service failed\")\n\t\treturn \"\", err\n\t}\n\n\tpodSandboxID := resp.PodSandboxId\n\n\tif podSandboxID == \"\" {\n\t\terrorMessage := fmt.Sprintf(\"PodSandboxId is not set for sandbox %q\", config.Metadata)\n\t\terr := errors.New(errorMessage)\n\t\tklog.ErrorS(err, \"RunPodSandbox failed\")\n\t\treturn \"\", err\n\t}\n\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] RunPodSandbox Response\", \"podSandboxID\", podSandboxID)\n\n\treturn podSandboxID, nil\n}","line":{"from":158,"to":192}} {"id":100006438,"name":"StopPodSandbox","signature":"func (r *remoteRuntimeService) StopPodSandbox(ctx context.Context, podSandBoxID string) (err error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// StopPodSandbox stops the sandbox. If there are any running containers in the\n// sandbox, they should be forced to termination.\nfunc (r *remoteRuntimeService) StopPodSandbox(ctx context.Context, podSandBoxID string) (err error) {\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] StopPodSandbox\", \"podSandboxID\", podSandBoxID, \"timeout\", r.timeout)\n\n\tctx, cancel := context.WithTimeout(ctx, r.timeout)\n\tdefer cancel()\n\n\tif _, err := r.runtimeClient.StopPodSandbox(ctx, \u0026runtimeapi.StopPodSandboxRequest{\n\t\tPodSandboxId: podSandBoxID,\n\t}); err != nil {\n\t\tklog.ErrorS(err, \"StopPodSandbox from runtime service failed\", \"podSandboxID\", podSandBoxID)\n\t\treturn err\n\t}\n\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] StopPodSandbox Response\", \"podSandboxID\", podSandBoxID)\n\n\treturn nil\n}","line":{"from":194,"to":212}} {"id":100006439,"name":"RemovePodSandbox","signature":"func (r *remoteRuntimeService) RemovePodSandbox(ctx context.Context, podSandBoxID string) (err error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// RemovePodSandbox removes the sandbox. If there are any containers in the\n// sandbox, they should be forcibly removed.\nfunc (r *remoteRuntimeService) RemovePodSandbox(ctx context.Context, podSandBoxID string) (err error) {\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] RemovePodSandbox\", \"podSandboxID\", podSandBoxID, \"timeout\", r.timeout)\n\tctx, cancel := context.WithTimeout(ctx, r.timeout)\n\tdefer cancel()\n\n\tif _, err := r.runtimeClient.RemovePodSandbox(ctx, \u0026runtimeapi.RemovePodSandboxRequest{\n\t\tPodSandboxId: podSandBoxID,\n\t}); err != nil {\n\t\tklog.ErrorS(err, \"RemovePodSandbox from runtime service failed\", \"podSandboxID\", podSandBoxID)\n\t\treturn err\n\t}\n\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] RemovePodSandbox Response\", \"podSandboxID\", podSandBoxID)\n\n\treturn nil\n}","line":{"from":214,"to":231}} {"id":100006440,"name":"PodSandboxStatus","signature":"func (r *remoteRuntimeService) PodSandboxStatus(ctx context.Context, podSandBoxID string, verbose bool) (*runtimeapi.PodSandboxStatusResponse, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// PodSandboxStatus returns the status of the PodSandbox.\nfunc (r *remoteRuntimeService) PodSandboxStatus(ctx context.Context, podSandBoxID string, verbose bool) (*runtimeapi.PodSandboxStatusResponse, error) {\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] PodSandboxStatus\", \"podSandboxID\", podSandBoxID, \"timeout\", r.timeout)\n\tctx, cancel := context.WithTimeout(ctx, r.timeout)\n\tdefer cancel()\n\n\treturn r.podSandboxStatusV1(ctx, podSandBoxID, verbose)\n}","line":{"from":233,"to":240}} {"id":100006441,"name":"podSandboxStatusV1","signature":"func (r *remoteRuntimeService) podSandboxStatusV1(ctx context.Context, podSandBoxID string, verbose bool) (*runtimeapi.PodSandboxStatusResponse, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"func (r *remoteRuntimeService) podSandboxStatusV1(ctx context.Context, podSandBoxID string, verbose bool) (*runtimeapi.PodSandboxStatusResponse, error) {\n\tresp, err := r.runtimeClient.PodSandboxStatus(ctx, \u0026runtimeapi.PodSandboxStatusRequest{\n\t\tPodSandboxId: podSandBoxID,\n\t\tVerbose: verbose,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] PodSandboxStatus Response\", \"podSandboxID\", podSandBoxID, \"status\", resp.Status)\n\n\tstatus := resp.Status\n\tif resp.Status != nil {\n\t\tif err := verifySandboxStatus(status); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn resp, nil\n}","line":{"from":242,"to":261}} {"id":100006442,"name":"ListPodSandbox","signature":"func (r *remoteRuntimeService) ListPodSandbox(ctx context.Context, filter *runtimeapi.PodSandboxFilter) ([]*runtimeapi.PodSandbox, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// ListPodSandbox returns a list of PodSandboxes.\nfunc (r *remoteRuntimeService) ListPodSandbox(ctx context.Context, filter *runtimeapi.PodSandboxFilter) ([]*runtimeapi.PodSandbox, error) {\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] ListPodSandbox\", \"filter\", filter, \"timeout\", r.timeout)\n\tctx, cancel := context.WithTimeout(ctx, r.timeout)\n\tdefer cancel()\n\n\treturn r.listPodSandboxV1(ctx, filter)\n}","line":{"from":263,"to":270}} {"id":100006443,"name":"listPodSandboxV1","signature":"func (r *remoteRuntimeService) listPodSandboxV1(ctx context.Context, filter *runtimeapi.PodSandboxFilter) ([]*runtimeapi.PodSandbox, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"func (r *remoteRuntimeService) listPodSandboxV1(ctx context.Context, filter *runtimeapi.PodSandboxFilter) ([]*runtimeapi.PodSandbox, error) {\n\tresp, err := r.runtimeClient.ListPodSandbox(ctx, \u0026runtimeapi.ListPodSandboxRequest{\n\t\tFilter: filter,\n\t})\n\tif err != nil {\n\t\tklog.ErrorS(err, \"ListPodSandbox with filter from runtime service failed\", \"filter\", filter)\n\t\treturn nil, err\n\t}\n\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] ListPodSandbox Response\", \"filter\", filter, \"items\", resp.Items)\n\n\treturn resp.Items, nil\n}","line":{"from":272,"to":284}} {"id":100006444,"name":"CreateContainer","signature":"func (r *remoteRuntimeService) CreateContainer(ctx context.Context, podSandBoxID string, config *runtimeapi.ContainerConfig, sandboxConfig *runtimeapi.PodSandboxConfig) (string, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// CreateContainer creates a new container in the specified PodSandbox.\nfunc (r *remoteRuntimeService) CreateContainer(ctx context.Context, podSandBoxID string, config *runtimeapi.ContainerConfig, sandboxConfig *runtimeapi.PodSandboxConfig) (string, error) {\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] CreateContainer\", \"podSandboxID\", podSandBoxID, \"timeout\", r.timeout)\n\tctx, cancel := context.WithTimeout(ctx, r.timeout)\n\tdefer cancel()\n\n\treturn r.createContainerV1(ctx, podSandBoxID, config, sandboxConfig)\n}","line":{"from":286,"to":293}} {"id":100006445,"name":"createContainerV1","signature":"func (r *remoteRuntimeService) createContainerV1(ctx context.Context, podSandBoxID string, config *runtimeapi.ContainerConfig, sandboxConfig *runtimeapi.PodSandboxConfig) (string, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"func (r *remoteRuntimeService) createContainerV1(ctx context.Context, podSandBoxID string, config *runtimeapi.ContainerConfig, sandboxConfig *runtimeapi.PodSandboxConfig) (string, error) {\n\tresp, err := r.runtimeClient.CreateContainer(ctx, \u0026runtimeapi.CreateContainerRequest{\n\t\tPodSandboxId: podSandBoxID,\n\t\tConfig: config,\n\t\tSandboxConfig: sandboxConfig,\n\t})\n\tif err != nil {\n\t\tklog.ErrorS(err, \"CreateContainer in sandbox from runtime service failed\", \"podSandboxID\", podSandBoxID)\n\t\treturn \"\", err\n\t}\n\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] CreateContainer\", \"podSandboxID\", podSandBoxID, \"containerID\", resp.ContainerId)\n\tif resp.ContainerId == \"\" {\n\t\terrorMessage := fmt.Sprintf(\"ContainerId is not set for container %q\", config.Metadata)\n\t\terr := errors.New(errorMessage)\n\t\tklog.ErrorS(err, \"CreateContainer failed\")\n\t\treturn \"\", err\n\t}\n\n\treturn resp.ContainerId, nil\n}","line":{"from":295,"to":315}} {"id":100006446,"name":"StartContainer","signature":"func (r *remoteRuntimeService) StartContainer(ctx context.Context, containerID string) (err error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// StartContainer starts the container.\nfunc (r *remoteRuntimeService) StartContainer(ctx context.Context, containerID string) (err error) {\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] StartContainer\", \"containerID\", containerID, \"timeout\", r.timeout)\n\tctx, cancel := context.WithTimeout(ctx, r.timeout)\n\tdefer cancel()\n\n\tif _, err := r.runtimeClient.StartContainer(ctx, \u0026runtimeapi.StartContainerRequest{\n\t\tContainerId: containerID,\n\t}); err != nil {\n\t\tklog.ErrorS(err, \"StartContainer from runtime service failed\", \"containerID\", containerID)\n\t\treturn err\n\t}\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] StartContainer Response\", \"containerID\", containerID)\n\n\treturn nil\n}","line":{"from":317,"to":332}} {"id":100006447,"name":"StopContainer","signature":"func (r *remoteRuntimeService) StopContainer(ctx context.Context, containerID string, timeout int64) (err error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// StopContainer stops a running container with a grace period (i.e., timeout).\nfunc (r *remoteRuntimeService) StopContainer(ctx context.Context, containerID string, timeout int64) (err error) {\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] StopContainer\", \"containerID\", containerID, \"timeout\", timeout)\n\t// Use timeout + default timeout (2 minutes) as timeout to leave extra time\n\t// for SIGKILL container and request latency.\n\tt := r.timeout + time.Duration(timeout)*time.Second\n\tctx, cancel := context.WithTimeout(ctx, t)\n\tdefer cancel()\n\n\tr.logReduction.ClearID(containerID)\n\n\tif _, err := r.runtimeClient.StopContainer(ctx, \u0026runtimeapi.StopContainerRequest{\n\t\tContainerId: containerID,\n\t\tTimeout: timeout,\n\t}); err != nil {\n\t\tklog.ErrorS(err, \"StopContainer from runtime service failed\", \"containerID\", containerID)\n\t\treturn err\n\t}\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] StopContainer Response\", \"containerID\", containerID)\n\n\treturn nil\n}","line":{"from":334,"to":355}} {"id":100006448,"name":"RemoveContainer","signature":"func (r *remoteRuntimeService) RemoveContainer(ctx context.Context, containerID string) (err error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// RemoveContainer removes the container. If the container is running, the container\n// should be forced to removal.\nfunc (r *remoteRuntimeService) RemoveContainer(ctx context.Context, containerID string) (err error) {\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] RemoveContainer\", \"containerID\", containerID, \"timeout\", r.timeout)\n\tctx, cancel := context.WithTimeout(ctx, r.timeout)\n\tdefer cancel()\n\n\tr.logReduction.ClearID(containerID)\n\tif _, err := r.runtimeClient.RemoveContainer(ctx, \u0026runtimeapi.RemoveContainerRequest{\n\t\tContainerId: containerID,\n\t}); err != nil {\n\t\tklog.ErrorS(err, \"RemoveContainer from runtime service failed\", \"containerID\", containerID)\n\t\treturn err\n\t}\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] RemoveContainer Response\", \"containerID\", containerID)\n\n\treturn nil\n}","line":{"from":357,"to":374}} {"id":100006449,"name":"ListContainers","signature":"func (r *remoteRuntimeService) ListContainers(ctx context.Context, filter *runtimeapi.ContainerFilter) ([]*runtimeapi.Container, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// ListContainers lists containers by filters.\nfunc (r *remoteRuntimeService) ListContainers(ctx context.Context, filter *runtimeapi.ContainerFilter) ([]*runtimeapi.Container, error) {\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] ListContainers\", \"filter\", filter, \"timeout\", r.timeout)\n\tctx, cancel := context.WithTimeout(ctx, r.timeout)\n\tdefer cancel()\n\n\treturn r.listContainersV1(ctx, filter)\n}","line":{"from":376,"to":383}} {"id":100006450,"name":"listContainersV1","signature":"func (r *remoteRuntimeService) listContainersV1(ctx context.Context, filter *runtimeapi.ContainerFilter) ([]*runtimeapi.Container, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"func (r *remoteRuntimeService) listContainersV1(ctx context.Context, filter *runtimeapi.ContainerFilter) ([]*runtimeapi.Container, error) {\n\tresp, err := r.runtimeClient.ListContainers(ctx, \u0026runtimeapi.ListContainersRequest{\n\t\tFilter: filter,\n\t})\n\tif err != nil {\n\t\tklog.ErrorS(err, \"ListContainers with filter from runtime service failed\", \"filter\", filter)\n\t\treturn nil, err\n\t}\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] ListContainers Response\", \"filter\", filter, \"containers\", resp.Containers)\n\n\treturn resp.Containers, nil\n}","line":{"from":385,"to":396}} {"id":100006451,"name":"ContainerStatus","signature":"func (r *remoteRuntimeService) ContainerStatus(ctx context.Context, containerID string, verbose bool) (*runtimeapi.ContainerStatusResponse, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// ContainerStatus returns the container status.\nfunc (r *remoteRuntimeService) ContainerStatus(ctx context.Context, containerID string, verbose bool) (*runtimeapi.ContainerStatusResponse, error) {\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] ContainerStatus\", \"containerID\", containerID, \"timeout\", r.timeout)\n\tctx, cancel := context.WithTimeout(ctx, r.timeout)\n\tdefer cancel()\n\n\treturn r.containerStatusV1(ctx, containerID, verbose)\n}","line":{"from":398,"to":405}} {"id":100006452,"name":"containerStatusV1","signature":"func (r *remoteRuntimeService) containerStatusV1(ctx context.Context, containerID string, verbose bool) (*runtimeapi.ContainerStatusResponse, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"func (r *remoteRuntimeService) containerStatusV1(ctx context.Context, containerID string, verbose bool) (*runtimeapi.ContainerStatusResponse, error) {\n\tresp, err := r.runtimeClient.ContainerStatus(ctx, \u0026runtimeapi.ContainerStatusRequest{\n\t\tContainerId: containerID,\n\t\tVerbose: verbose,\n\t})\n\tif err != nil {\n\t\t// Don't spam the log with endless messages about the same failure.\n\t\tif r.logReduction.ShouldMessageBePrinted(err.Error(), containerID) {\n\t\t\tklog.ErrorS(err, \"ContainerStatus from runtime service failed\", \"containerID\", containerID)\n\t\t}\n\t\treturn nil, err\n\t}\n\tr.logReduction.ClearID(containerID)\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] ContainerStatus Response\", \"containerID\", containerID, \"status\", resp.Status)\n\n\tstatus := resp.Status\n\tif resp.Status != nil {\n\t\tif err := verifyContainerStatus(status); err != nil {\n\t\t\tklog.ErrorS(err, \"verify ContainerStatus failed\", \"containerID\", containerID)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn resp, nil\n}","line":{"from":407,"to":431}} {"id":100006453,"name":"UpdateContainerResources","signature":"func (r *remoteRuntimeService) UpdateContainerResources(ctx context.Context, containerID string, resources *runtimeapi.ContainerResources) (err error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// UpdateContainerResources updates a containers resource config\nfunc (r *remoteRuntimeService) UpdateContainerResources(ctx context.Context, containerID string, resources *runtimeapi.ContainerResources) (err error) {\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] UpdateContainerResources\", \"containerID\", containerID, \"timeout\", r.timeout)\n\tctx, cancel := context.WithTimeout(ctx, r.timeout)\n\tdefer cancel()\n\n\tif _, err := r.runtimeClient.UpdateContainerResources(ctx, \u0026runtimeapi.UpdateContainerResourcesRequest{\n\t\tContainerId: containerID,\n\t\tLinux: resources.GetLinux(),\n\t\tWindows: resources.GetWindows(),\n\t}); err != nil {\n\t\tklog.ErrorS(err, \"UpdateContainerResources from runtime service failed\", \"containerID\", containerID)\n\t\treturn err\n\t}\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] UpdateContainerResources Response\", \"containerID\", containerID)\n\n\treturn nil\n}","line":{"from":433,"to":450}} {"id":100006454,"name":"ExecSync","signature":"func (r *remoteRuntimeService) ExecSync(ctx context.Context, containerID string, cmd []string, timeout time.Duration) (stdout []byte, stderr []byte, err error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// ExecSync executes a command in the container, and returns the stdout output.\n// If command exits with a non-zero exit code, an error is returned.\nfunc (r *remoteRuntimeService) ExecSync(ctx context.Context, containerID string, cmd []string, timeout time.Duration) (stdout []byte, stderr []byte, err error) {\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] ExecSync\", \"containerID\", containerID, \"timeout\", timeout)\n\t// Do not set timeout when timeout is 0.\n\tvar cancel context.CancelFunc\n\tif timeout != 0 {\n\t\t// Use timeout + default timeout (2 minutes) as timeout to leave some time for\n\t\t// the runtime to do cleanup.\n\t\tctx, cancel = context.WithTimeout(ctx, r.timeout+timeout)\n\t} else {\n\t\tctx, cancel = context.WithCancel(ctx)\n\t}\n\tdefer cancel()\n\n\treturn r.execSyncV1(ctx, containerID, cmd, timeout)\n}","line":{"from":452,"to":468}} {"id":100006455,"name":"execSyncV1","signature":"func (r *remoteRuntimeService) execSyncV1(ctx context.Context, containerID string, cmd []string, timeout time.Duration) (stdout []byte, stderr []byte, err error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"func (r *remoteRuntimeService) execSyncV1(ctx context.Context, containerID string, cmd []string, timeout time.Duration) (stdout []byte, stderr []byte, err error) {\n\ttimeoutSeconds := int64(timeout.Seconds())\n\treq := \u0026runtimeapi.ExecSyncRequest{\n\t\tContainerId: containerID,\n\t\tCmd: cmd,\n\t\tTimeout: timeoutSeconds,\n\t}\n\tresp, err := r.runtimeClient.ExecSync(ctx, req)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"ExecSync cmd from runtime service failed\", \"containerID\", containerID, \"cmd\", cmd)\n\n\t\t// interpret DeadlineExceeded gRPC errors as timedout probes\n\t\tif status.Code(err) == codes.DeadlineExceeded {\n\t\t\terr = exec.NewTimeoutError(fmt.Errorf(\"command %q timed out\", strings.Join(cmd, \" \")), timeout)\n\t\t}\n\n\t\treturn nil, nil, err\n\t}\n\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] ExecSync Response\", \"containerID\", containerID, \"exitCode\", resp.ExitCode)\n\terr = nil\n\tif resp.ExitCode != 0 {\n\t\terr = utilexec.CodeExitError{\n\t\t\tErr: fmt.Errorf(\"command '%s' exited with %d: %s\", strings.Join(cmd, \" \"), resp.ExitCode, resp.Stderr),\n\t\t\tCode: int(resp.ExitCode),\n\t\t}\n\t}\n\n\treturn resp.Stdout, resp.Stderr, err\n}","line":{"from":470,"to":499}} {"id":100006456,"name":"Exec","signature":"func (r *remoteRuntimeService) Exec(ctx context.Context, req *runtimeapi.ExecRequest) (*runtimeapi.ExecResponse, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// Exec prepares a streaming endpoint to execute a command in the container, and returns the address.\nfunc (r *remoteRuntimeService) Exec(ctx context.Context, req *runtimeapi.ExecRequest) (*runtimeapi.ExecResponse, error) {\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] Exec\", \"timeout\", r.timeout)\n\tctx, cancel := context.WithTimeout(ctx, r.timeout)\n\tdefer cancel()\n\n\treturn r.execV1(ctx, req)\n}","line":{"from":501,"to":508}} {"id":100006457,"name":"execV1","signature":"func (r *remoteRuntimeService) execV1(ctx context.Context, req *runtimeapi.ExecRequest) (*runtimeapi.ExecResponse, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"func (r *remoteRuntimeService) execV1(ctx context.Context, req *runtimeapi.ExecRequest) (*runtimeapi.ExecResponse, error) {\n\tresp, err := r.runtimeClient.Exec(ctx, req)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Exec cmd from runtime service failed\", \"containerID\", req.ContainerId, \"cmd\", req.Cmd)\n\t\treturn nil, err\n\t}\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] Exec Response\")\n\n\tif resp.Url == \"\" {\n\t\terrorMessage := \"URL is not set\"\n\t\terr := errors.New(errorMessage)\n\t\tklog.ErrorS(err, \"Exec failed\")\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}","line":{"from":510,"to":526}} {"id":100006458,"name":"Attach","signature":"func (r *remoteRuntimeService) Attach(ctx context.Context, req *runtimeapi.AttachRequest) (*runtimeapi.AttachResponse, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// Attach prepares a streaming endpoint to attach to a running container, and returns the address.\nfunc (r *remoteRuntimeService) Attach(ctx context.Context, req *runtimeapi.AttachRequest) (*runtimeapi.AttachResponse, error) {\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] Attach\", \"containerID\", req.ContainerId, \"timeout\", r.timeout)\n\tctx, cancel := context.WithTimeout(ctx, r.timeout)\n\tdefer cancel()\n\n\treturn r.attachV1(ctx, req)\n}","line":{"from":528,"to":535}} {"id":100006459,"name":"attachV1","signature":"func (r *remoteRuntimeService) attachV1(ctx context.Context, req *runtimeapi.AttachRequest) (*runtimeapi.AttachResponse, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"func (r *remoteRuntimeService) attachV1(ctx context.Context, req *runtimeapi.AttachRequest) (*runtimeapi.AttachResponse, error) {\n\tresp, err := r.runtimeClient.Attach(ctx, req)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Attach container from runtime service failed\", \"containerID\", req.ContainerId)\n\t\treturn nil, err\n\t}\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] Attach Response\", \"containerID\", req.ContainerId)\n\n\tif resp.Url == \"\" {\n\t\terrorMessage := \"URL is not set\"\n\t\terr := errors.New(errorMessage)\n\t\tklog.ErrorS(err, \"Attach failed\")\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}","line":{"from":537,"to":552}} {"id":100006460,"name":"PortForward","signature":"func (r *remoteRuntimeService) PortForward(ctx context.Context, req *runtimeapi.PortForwardRequest) (*runtimeapi.PortForwardResponse, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// PortForward prepares a streaming endpoint to forward ports from a PodSandbox, and returns the address.\nfunc (r *remoteRuntimeService) PortForward(ctx context.Context, req *runtimeapi.PortForwardRequest) (*runtimeapi.PortForwardResponse, error) {\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] PortForward\", \"podSandboxID\", req.PodSandboxId, \"port\", req.Port, \"timeout\", r.timeout)\n\tctx, cancel := context.WithTimeout(ctx, r.timeout)\n\tdefer cancel()\n\n\treturn r.portForwardV1(ctx, req)\n}","line":{"from":554,"to":561}} {"id":100006461,"name":"portForwardV1","signature":"func (r *remoteRuntimeService) portForwardV1(ctx context.Context, req *runtimeapi.PortForwardRequest) (*runtimeapi.PortForwardResponse, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"func (r *remoteRuntimeService) portForwardV1(ctx context.Context, req *runtimeapi.PortForwardRequest) (*runtimeapi.PortForwardResponse, error) {\n\tresp, err := r.runtimeClient.PortForward(ctx, req)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"PortForward from runtime service failed\", \"podSandboxID\", req.PodSandboxId)\n\t\treturn nil, err\n\t}\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] PortForward Response\", \"podSandboxID\", req.PodSandboxId)\n\n\tif resp.Url == \"\" {\n\t\terrorMessage := \"URL is not set\"\n\t\terr := errors.New(errorMessage)\n\t\tklog.ErrorS(err, \"PortForward failed\")\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}","line":{"from":563,"to":579}} {"id":100006462,"name":"UpdateRuntimeConfig","signature":"func (r *remoteRuntimeService) UpdateRuntimeConfig(ctx context.Context, runtimeConfig *runtimeapi.RuntimeConfig) (err error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// UpdateRuntimeConfig updates the config of a runtime service. The only\n// update payload currently supported is the pod CIDR assigned to a node,\n// and the runtime service just proxies it down to the network plugin.\nfunc (r *remoteRuntimeService) UpdateRuntimeConfig(ctx context.Context, runtimeConfig *runtimeapi.RuntimeConfig) (err error) {\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] UpdateRuntimeConfig\", \"runtimeConfig\", runtimeConfig, \"timeout\", r.timeout)\n\tctx, cancel := context.WithTimeout(ctx, r.timeout)\n\tdefer cancel()\n\n\t// Response doesn't contain anything of interest. This translates to an\n\t// Event notification to the network plugin, which can't fail, so we're\n\t// really looking to surface destination unreachable.\n\tif _, err := r.runtimeClient.UpdateRuntimeConfig(ctx, \u0026runtimeapi.UpdateRuntimeConfigRequest{\n\t\tRuntimeConfig: runtimeConfig,\n\t}); err != nil {\n\t\treturn err\n\t}\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] UpdateRuntimeConfig Response\", \"runtimeConfig\", runtimeConfig)\n\n\treturn nil\n}","line":{"from":581,"to":600}} {"id":100006463,"name":"Status","signature":"func (r *remoteRuntimeService) Status(ctx context.Context, verbose bool) (*runtimeapi.StatusResponse, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// Status returns the status of the runtime.\nfunc (r *remoteRuntimeService) Status(ctx context.Context, verbose bool) (*runtimeapi.StatusResponse, error) {\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] Status\", \"timeout\", r.timeout)\n\tctx, cancel := context.WithTimeout(ctx, r.timeout)\n\tdefer cancel()\n\n\treturn r.statusV1(ctx, verbose)\n}","line":{"from":602,"to":609}} {"id":100006464,"name":"statusV1","signature":"func (r *remoteRuntimeService) statusV1(ctx context.Context, verbose bool) (*runtimeapi.StatusResponse, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"func (r *remoteRuntimeService) statusV1(ctx context.Context, verbose bool) (*runtimeapi.StatusResponse, error) {\n\tresp, err := r.runtimeClient.Status(ctx, \u0026runtimeapi.StatusRequest{\n\t\tVerbose: verbose,\n\t})\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Status from runtime service failed\")\n\t\treturn nil, err\n\t}\n\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] Status Response\", \"status\", resp.Status)\n\n\tif resp.Status == nil || len(resp.Status.Conditions) \u003c 2 {\n\t\terrorMessage := \"RuntimeReady or NetworkReady condition are not set\"\n\t\terr := errors.New(errorMessage)\n\t\tklog.ErrorS(err, \"Status failed\")\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}","line":{"from":611,"to":630}} {"id":100006465,"name":"ContainerStats","signature":"func (r *remoteRuntimeService) ContainerStats(ctx context.Context, containerID string) (*runtimeapi.ContainerStats, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// ContainerStats returns the stats of the container.\nfunc (r *remoteRuntimeService) ContainerStats(ctx context.Context, containerID string) (*runtimeapi.ContainerStats, error) {\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] ContainerStats\", \"containerID\", containerID, \"timeout\", r.timeout)\n\tctx, cancel := context.WithTimeout(ctx, r.timeout)\n\tdefer cancel()\n\n\treturn r.containerStatsV1(ctx, containerID)\n}","line":{"from":632,"to":639}} {"id":100006466,"name":"containerStatsV1","signature":"func (r *remoteRuntimeService) containerStatsV1(ctx context.Context, containerID string) (*runtimeapi.ContainerStats, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"func (r *remoteRuntimeService) containerStatsV1(ctx context.Context, containerID string) (*runtimeapi.ContainerStats, error) {\n\tresp, err := r.runtimeClient.ContainerStats(ctx, \u0026runtimeapi.ContainerStatsRequest{\n\t\tContainerId: containerID,\n\t})\n\tif err != nil {\n\t\tif r.logReduction.ShouldMessageBePrinted(err.Error(), containerID) {\n\t\t\tklog.ErrorS(err, \"ContainerStats from runtime service failed\", \"containerID\", containerID)\n\t\t}\n\t\treturn nil, err\n\t}\n\tr.logReduction.ClearID(containerID)\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] ContainerStats Response\", \"containerID\", containerID, \"stats\", resp.GetStats())\n\n\treturn resp.GetStats(), nil\n}","line":{"from":641,"to":655}} {"id":100006467,"name":"ListContainerStats","signature":"func (r *remoteRuntimeService) ListContainerStats(ctx context.Context, filter *runtimeapi.ContainerStatsFilter) ([]*runtimeapi.ContainerStats, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// ListContainerStats returns the list of ContainerStats given the filter.\nfunc (r *remoteRuntimeService) ListContainerStats(ctx context.Context, filter *runtimeapi.ContainerStatsFilter) ([]*runtimeapi.ContainerStats, error) {\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] ListContainerStats\", \"filter\", filter)\n\t// Do not set timeout, because writable layer stats collection takes time.\n\t// TODO(random-liu): Should we assume runtime should cache the result, and set timeout here?\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\treturn r.listContainerStatsV1(ctx, filter)\n}","line":{"from":657,"to":666}} {"id":100006468,"name":"listContainerStatsV1","signature":"func (r *remoteRuntimeService) listContainerStatsV1(ctx context.Context, filter *runtimeapi.ContainerStatsFilter) ([]*runtimeapi.ContainerStats, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"func (r *remoteRuntimeService) listContainerStatsV1(ctx context.Context, filter *runtimeapi.ContainerStatsFilter) ([]*runtimeapi.ContainerStats, error) {\n\tresp, err := r.runtimeClient.ListContainerStats(ctx, \u0026runtimeapi.ListContainerStatsRequest{\n\t\tFilter: filter,\n\t})\n\tif err != nil {\n\t\tklog.ErrorS(err, \"ListContainerStats with filter from runtime service failed\", \"filter\", filter)\n\t\treturn nil, err\n\t}\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] ListContainerStats Response\", \"filter\", filter, \"stats\", resp.GetStats())\n\n\treturn resp.GetStats(), nil\n}","line":{"from":668,"to":679}} {"id":100006469,"name":"PodSandboxStats","signature":"func (r *remoteRuntimeService) PodSandboxStats(ctx context.Context, podSandboxID string) (*runtimeapi.PodSandboxStats, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// PodSandboxStats returns the stats of the pod.\nfunc (r *remoteRuntimeService) PodSandboxStats(ctx context.Context, podSandboxID string) (*runtimeapi.PodSandboxStats, error) {\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] PodSandboxStats\", \"podSandboxID\", podSandboxID, \"timeout\", r.timeout)\n\tctx, cancel := context.WithTimeout(ctx, r.timeout)\n\tdefer cancel()\n\n\treturn r.podSandboxStatsV1(ctx, podSandboxID)\n}","line":{"from":681,"to":688}} {"id":100006470,"name":"podSandboxStatsV1","signature":"func (r *remoteRuntimeService) podSandboxStatsV1(ctx context.Context, podSandboxID string) (*runtimeapi.PodSandboxStats, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"func (r *remoteRuntimeService) podSandboxStatsV1(ctx context.Context, podSandboxID string) (*runtimeapi.PodSandboxStats, error) {\n\tresp, err := r.runtimeClient.PodSandboxStats(ctx, \u0026runtimeapi.PodSandboxStatsRequest{\n\t\tPodSandboxId: podSandboxID,\n\t})\n\tif err != nil {\n\t\tif r.logReduction.ShouldMessageBePrinted(err.Error(), podSandboxID) {\n\t\t\tklog.ErrorS(err, \"PodSandbox from runtime service failed\", \"podSandboxID\", podSandboxID)\n\t\t}\n\t\treturn nil, err\n\t}\n\tr.logReduction.ClearID(podSandboxID)\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] PodSandbox Response\", \"podSandboxID\", podSandboxID, \"stats\", resp.GetStats())\n\n\treturn resp.GetStats(), nil\n}","line":{"from":690,"to":704}} {"id":100006471,"name":"ListPodSandboxStats","signature":"func (r *remoteRuntimeService) ListPodSandboxStats(ctx context.Context, filter *runtimeapi.PodSandboxStatsFilter) ([]*runtimeapi.PodSandboxStats, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// ListPodSandboxStats returns the list of pod sandbox stats given the filter\nfunc (r *remoteRuntimeService) ListPodSandboxStats(ctx context.Context, filter *runtimeapi.PodSandboxStatsFilter) ([]*runtimeapi.PodSandboxStats, error) {\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] ListPodSandboxStats\", \"filter\", filter)\n\t// Set timeout, because runtimes are able to cache disk stats results\n\tctx, cancel := context.WithTimeout(ctx, r.timeout)\n\tdefer cancel()\n\n\treturn r.listPodSandboxStatsV1(ctx, filter)\n}","line":{"from":706,"to":714}} {"id":100006472,"name":"listPodSandboxStatsV1","signature":"func (r *remoteRuntimeService) listPodSandboxStatsV1(ctx context.Context, filter *runtimeapi.PodSandboxStatsFilter) ([]*runtimeapi.PodSandboxStats, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"func (r *remoteRuntimeService) listPodSandboxStatsV1(ctx context.Context, filter *runtimeapi.PodSandboxStatsFilter) ([]*runtimeapi.PodSandboxStats, error) {\n\tresp, err := r.runtimeClient.ListPodSandboxStats(ctx, \u0026runtimeapi.ListPodSandboxStatsRequest{\n\t\tFilter: filter,\n\t})\n\tif err != nil {\n\t\tklog.ErrorS(err, \"ListPodSandboxStats with filter from runtime service failed\", \"filter\", filter)\n\t\treturn nil, err\n\t}\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] ListPodSandboxStats Response\", \"filter\", filter, \"stats\", resp.GetStats())\n\n\treturn resp.GetStats(), nil\n}","line":{"from":716,"to":727}} {"id":100006473,"name":"ReopenContainerLog","signature":"func (r *remoteRuntimeService) ReopenContainerLog(ctx context.Context, containerID string) (err error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// ReopenContainerLog reopens the container log file.\nfunc (r *remoteRuntimeService) ReopenContainerLog(ctx context.Context, containerID string) (err error) {\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] ReopenContainerLog\", \"containerID\", containerID, \"timeout\", r.timeout)\n\tctx, cancel := context.WithTimeout(ctx, r.timeout)\n\tdefer cancel()\n\n\tif _, err := r.runtimeClient.ReopenContainerLog(ctx, \u0026runtimeapi.ReopenContainerLogRequest{ContainerId: containerID}); err != nil {\n\t\tklog.ErrorS(err, \"ReopenContainerLog from runtime service failed\", \"containerID\", containerID)\n\t\treturn err\n\t}\n\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] ReopenContainerLog Response\", \"containerID\", containerID)\n\treturn nil\n}","line":{"from":729,"to":742}} {"id":100006474,"name":"CheckpointContainer","signature":"func (r *remoteRuntimeService) CheckpointContainer(ctx context.Context, options *runtimeapi.CheckpointContainerRequest) error","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// CheckpointContainer triggers a checkpoint of the given CheckpointContainerRequest\nfunc (r *remoteRuntimeService) CheckpointContainer(ctx context.Context, options *runtimeapi.CheckpointContainerRequest) error {\n\tklog.V(10).InfoS(\n\t\t\"[RemoteRuntimeService] CheckpointContainer\",\n\t\t\"options\",\n\t\toptions,\n\t)\n\tif options == nil {\n\t\treturn errors.New(\"CheckpointContainer requires non-nil CheckpointRestoreOptions parameter\")\n\t}\n\tif options.Timeout \u003c 0 {\n\t\treturn errors.New(\"CheckpointContainer requires the timeout value to be \u003e 0\")\n\t}\n\n\tctx, cancel := func(ctx context.Context) (context.Context, context.CancelFunc) {\n\t\tdefaultTimeout := int64(r.timeout / time.Second)\n\t\tif options.Timeout \u003e defaultTimeout {\n\t\t\t// The user requested a specific timeout, let's use that if it\n\t\t\t// is larger than the CRI default.\n\t\t\treturn context.WithTimeout(ctx, time.Duration(options.Timeout)*time.Second)\n\t\t}\n\t\t// If the user requested a timeout less than the\n\t\t// CRI default, let's use the CRI default.\n\t\toptions.Timeout = defaultTimeout\n\t\treturn context.WithTimeout(ctx, r.timeout)\n\t}(ctx)\n\tdefer cancel()\n\n\t_, err := r.runtimeClient.CheckpointContainer(\n\t\tctx,\n\t\toptions,\n\t)\n\n\tif err != nil {\n\t\tklog.ErrorS(\n\t\t\terr,\n\t\t\t\"CheckpointContainer from runtime service failed\",\n\t\t\t\"containerID\",\n\t\t\toptions.ContainerId,\n\t\t)\n\t\treturn err\n\t}\n\tklog.V(10).InfoS(\n\t\t\"[RemoteRuntimeService] CheckpointContainer Response\",\n\t\t\"containerID\",\n\t\toptions.ContainerId,\n\t)\n\n\treturn nil\n}","line":{"from":744,"to":793}} {"id":100006475,"name":"GetContainerEvents","signature":"func (r *remoteRuntimeService) GetContainerEvents(containerEventsCh chan *runtimeapi.ContainerEventResponse) error","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"func (r *remoteRuntimeService) GetContainerEvents(containerEventsCh chan *runtimeapi.ContainerEventResponse) error {\n\tcontainerEventsStreamingClient, err := r.runtimeClient.GetContainerEvents(context.Background(), \u0026runtimeapi.GetEventsRequest{})\n\tif err != nil {\n\t\tklog.ErrorS(err, \"GetContainerEvents failed to get streaming client\")\n\t\treturn err\n\t}\n\n\t// The connection is successfully established and we have a streaming client ready for use.\n\tmetrics.EventedPLEGConn.Inc()\n\n\tfor {\n\t\tresp, err := containerEventsStreamingClient.Recv()\n\t\tif err == io.EOF {\n\t\t\tklog.ErrorS(err, \"container events stream is closed\")\n\t\t\treturn err\n\t\t}\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"failed to receive streaming container event\")\n\t\t\treturn err\n\t\t}\n\t\tif resp != nil {\n\t\t\tcontainerEventsCh \u003c- resp\n\t\t\tklog.V(4).InfoS(\"container event received\", \"resp\", resp)\n\t\t}\n\t}\n}","line":{"from":795,"to":820}} {"id":100006476,"name":"ListMetricDescriptors","signature":"func (r *remoteRuntimeService) ListMetricDescriptors(ctx context.Context) ([]*runtimeapi.MetricDescriptor, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// ListMetricDescriptors gets the descriptors for the metrics that will be returned in ListPodSandboxMetrics.\nfunc (r *remoteRuntimeService) ListMetricDescriptors(ctx context.Context) ([]*runtimeapi.MetricDescriptor, error) {\n\tctx, cancel := context.WithTimeout(ctx, r.timeout)\n\tdefer cancel()\n\n\tresp, err := r.runtimeClient.ListMetricDescriptors(ctx, \u0026runtimeapi.ListMetricDescriptorsRequest{})\n\tif err != nil {\n\t\tklog.ErrorS(err, \"ListMetricDescriptors from runtime service failed\")\n\t\treturn nil, err\n\t}\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] ListMetricDescriptors Response\", \"stats\", resp.GetDescriptors())\n\n\treturn resp.GetDescriptors(), nil\n}","line":{"from":822,"to":835}} {"id":100006477,"name":"ListPodSandboxMetrics","signature":"func (r *remoteRuntimeService) ListPodSandboxMetrics(ctx context.Context) ([]*runtimeapi.PodSandboxMetrics, error)","file":"pkg/kubelet/cri/remote/remote_runtime.go","code":"// ListPodSandboxMetrics retrieves the metrics for all pod sandboxes.\nfunc (r *remoteRuntimeService) ListPodSandboxMetrics(ctx context.Context) ([]*runtimeapi.PodSandboxMetrics, error) {\n\tctx, cancel := context.WithTimeout(ctx, r.timeout)\n\tdefer cancel()\n\n\tresp, err := r.runtimeClient.ListPodSandboxMetrics(ctx, \u0026runtimeapi.ListPodSandboxMetricsRequest{})\n\tif err != nil {\n\t\tklog.ErrorS(err, \"ListPodSandboxMetrics from runtime service failed\")\n\t\treturn nil, err\n\t}\n\tklog.V(10).InfoS(\"[RemoteRuntimeService] ListPodSandboxMetrics Response\", \"stats\", resp.GetPodMetrics())\n\n\treturn resp.GetPodMetrics(), nil\n}","line":{"from":837,"to":850}} {"id":100006478,"name":"verifySandboxStatus","signature":"func verifySandboxStatus(status *runtimeapi.PodSandboxStatus) error","file":"pkg/kubelet/cri/remote/utils.go","code":"// verifySandboxStatus verified whether all required fields are set in PodSandboxStatus.\nfunc verifySandboxStatus(status *runtimeapi.PodSandboxStatus) error {\n\tif status.Id == \"\" {\n\t\treturn fmt.Errorf(\"status.Id is not set\")\n\t}\n\n\tif status.Metadata == nil {\n\t\treturn fmt.Errorf(\"status.Metadata is not set\")\n\t}\n\n\tmetadata := status.Metadata\n\tif metadata.Name == \"\" || metadata.Namespace == \"\" || metadata.Uid == \"\" {\n\t\treturn fmt.Errorf(\"metadata.Name, metadata.Namespace or metadata.Uid is not in metadata %q\", metadata)\n\t}\n\n\tif status.CreatedAt == 0 {\n\t\treturn fmt.Errorf(\"status.CreatedAt is not set\")\n\t}\n\n\treturn nil\n}","line":{"from":29,"to":49}} {"id":100006479,"name":"verifyContainerStatus","signature":"func verifyContainerStatus(status *runtimeapi.ContainerStatus) error","file":"pkg/kubelet/cri/remote/utils.go","code":"// verifyContainerStatus verified whether all required fields are set in ContainerStatus.\nfunc verifyContainerStatus(status *runtimeapi.ContainerStatus) error {\n\tif status.Id == \"\" {\n\t\treturn fmt.Errorf(\"status.Id is not set\")\n\t}\n\n\tif status.Metadata == nil {\n\t\treturn fmt.Errorf(\"status.Metadata is not set\")\n\t}\n\n\tmetadata := status.Metadata\n\tif metadata.Name == \"\" {\n\t\treturn fmt.Errorf(\"metadata.Name is not in metadata %q\", metadata)\n\t}\n\n\tif status.CreatedAt == 0 {\n\t\treturn fmt.Errorf(\"status.CreatedAt is not set\")\n\t}\n\n\tif status.Image == nil || status.Image.Image == \"\" {\n\t\treturn fmt.Errorf(\"status.Image is not set\")\n\t}\n\n\tif status.ImageRef == \"\" {\n\t\treturn fmt.Errorf(\"status.ImageRef is not set\")\n\t}\n\n\treturn nil\n}","line":{"from":51,"to":79}} {"id":100006480,"name":"NewErrorTooManyInFlight","signature":"func NewErrorTooManyInFlight() error","file":"pkg/kubelet/cri/streaming/errors.go","code":"// NewErrorTooManyInFlight creates an error for exceeding the maximum number of in-flight requests.\nfunc NewErrorTooManyInFlight() error {\n\treturn grpcstatus.Error(codes.ResourceExhausted, \"maximum number of in-flight requests exceeded\")\n}","line":{"from":27,"to":30}} {"id":100006481,"name":"WriteError","signature":"func WriteError(err error, w http.ResponseWriter) error","file":"pkg/kubelet/cri/streaming/errors.go","code":"// WriteError translates a CRI streaming error into an appropriate HTTP response.\nfunc WriteError(err error, w http.ResponseWriter) error {\n\ts, _ := grpcstatus.FromError(err)\n\tvar status int\n\tswitch s.Code() {\n\tcase codes.NotFound:\n\t\tstatus = http.StatusNotFound\n\tcase codes.ResourceExhausted:\n\t\t// We only expect to hit this if there is a DoS, so we just wait the full TTL.\n\t\t// If this is ever hit in steady-state operations, consider increasing the maxInFlight requests,\n\t\t// or plumbing through the time to next expiration.\n\t\tw.Header().Set(\"Retry-After\", strconv.Itoa(int(cacheTTL.Seconds())))\n\t\tstatus = http.StatusTooManyRequests\n\tdefault:\n\t\tstatus = http.StatusInternalServerError\n\t}\n\tw.WriteHeader(status)\n\t_, writeErr := w.Write([]byte(err.Error()))\n\treturn writeErr\n}","line":{"from":32,"to":51}} {"id":100006482,"name":"handleHTTPStreams","signature":"func handleHTTPStreams(req *http.Request, w http.ResponseWriter, portForwarder PortForwarder, podName string, uid types.UID, supportedPortForwardProtocols []string, idleTimeout, streamCreationTimeout time.Duration) error","file":"pkg/kubelet/cri/streaming/portforward/httpstream.go","code":"func handleHTTPStreams(req *http.Request, w http.ResponseWriter, portForwarder PortForwarder, podName string, uid types.UID, supportedPortForwardProtocols []string, idleTimeout, streamCreationTimeout time.Duration) error {\n\t_, err := httpstream.Handshake(req, w, supportedPortForwardProtocols)\n\t// negotiated protocol isn't currently used server side, but could be in the future\n\tif err != nil {\n\t\t// Handshake writes the error to the client\n\t\treturn err\n\t}\n\tstreamChan := make(chan httpstream.Stream, 1)\n\n\tklog.V(5).InfoS(\"Upgrading port forward response\")\n\tupgrader := spdy.NewResponseUpgrader()\n\tconn := upgrader.UpgradeResponse(w, req, httpStreamReceived(streamChan))\n\tif conn == nil {\n\t\treturn errors.New(\"unable to upgrade httpstream connection\")\n\t}\n\tdefer conn.Close()\n\n\tklog.V(5).InfoS(\"Connection setting port forwarding streaming connection idle timeout\", \"connection\", conn, \"idleTimeout\", idleTimeout)\n\tconn.SetIdleTimeout(idleTimeout)\n\n\th := \u0026httpStreamHandler{\n\t\tconn: conn,\n\t\tstreamChan: streamChan,\n\t\tstreamPairs: make(map[string]*httpStreamPair),\n\t\tstreamCreationTimeout: streamCreationTimeout,\n\t\tpod: podName,\n\t\tuid: uid,\n\t\tforwarder: portForwarder,\n\t}\n\th.run()\n\n\treturn nil\n}","line":{"from":37,"to":69}} {"id":100006483,"name":"httpStreamReceived","signature":"func httpStreamReceived(streams chan httpstream.Stream) func(httpstream.Stream, \u003c-chan struct{}) error","file":"pkg/kubelet/cri/streaming/portforward/httpstream.go","code":"// httpStreamReceived is the httpstream.NewStreamHandler for port\n// forward streams. It checks each stream's port and stream type headers,\n// rejecting any streams that with missing or invalid values. Each valid\n// stream is sent to the streams channel.\nfunc httpStreamReceived(streams chan httpstream.Stream) func(httpstream.Stream, \u003c-chan struct{}) error {\n\treturn func(stream httpstream.Stream, replySent \u003c-chan struct{}) error {\n\t\t// make sure it has a valid port header\n\t\tportString := stream.Headers().Get(api.PortHeader)\n\t\tif len(portString) == 0 {\n\t\t\treturn fmt.Errorf(\"%q header is required\", api.PortHeader)\n\t\t}\n\t\tport, err := strconv.ParseUint(portString, 10, 16)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to parse %q as a port: %v\", portString, err)\n\t\t}\n\t\tif port \u003c 1 {\n\t\t\treturn fmt.Errorf(\"port %q must be \u003e 0\", portString)\n\t\t}\n\n\t\t// make sure it has a valid stream type header\n\t\tstreamType := stream.Headers().Get(api.StreamType)\n\t\tif len(streamType) == 0 {\n\t\t\treturn fmt.Errorf(\"%q header is required\", api.StreamType)\n\t\t}\n\t\tif streamType != api.StreamTypeError \u0026\u0026 streamType != api.StreamTypeData {\n\t\t\treturn fmt.Errorf(\"invalid stream type %q\", streamType)\n\t\t}\n\n\t\tstreams \u003c- stream\n\t\treturn nil\n\t}\n}","line":{"from":71,"to":102}} {"id":100006484,"name":"getStreamPair","signature":"func (h *httpStreamHandler) getStreamPair(requestID string) (*httpStreamPair, bool)","file":"pkg/kubelet/cri/streaming/portforward/httpstream.go","code":"// getStreamPair returns a httpStreamPair for requestID. This creates a\n// new pair if one does not yet exist for the requestID. The returned bool is\n// true if the pair was created.\nfunc (h *httpStreamHandler) getStreamPair(requestID string) (*httpStreamPair, bool) {\n\th.streamPairsLock.Lock()\n\tdefer h.streamPairsLock.Unlock()\n\n\tif p, ok := h.streamPairs[requestID]; ok {\n\t\tklog.V(5).InfoS(\"Connection request found existing stream pair\", \"connection\", h.conn, \"request\", requestID)\n\t\treturn p, false\n\t}\n\n\tklog.V(5).InfoS(\"Connection request creating new stream pair\", \"connection\", h.conn, \"request\", requestID)\n\n\tp := newPortForwardPair(requestID)\n\th.streamPairs[requestID] = p\n\n\treturn p, true\n}","line":{"from":117,"to":135}} {"id":100006485,"name":"monitorStreamPair","signature":"func (h *httpStreamHandler) monitorStreamPair(p *httpStreamPair, timeout \u003c-chan time.Time)","file":"pkg/kubelet/cri/streaming/portforward/httpstream.go","code":"// monitorStreamPair waits for the pair to receive both its error and data\n// streams, or for the timeout to expire (whichever happens first), and then\n// removes the pair.\nfunc (h *httpStreamHandler) monitorStreamPair(p *httpStreamPair, timeout \u003c-chan time.Time) {\n\tselect {\n\tcase \u003c-timeout:\n\t\terr := fmt.Errorf(\"(conn=%v, request=%s) timed out waiting for streams\", h.conn, p.requestID)\n\t\tutilruntime.HandleError(err)\n\t\tp.printError(err.Error())\n\tcase \u003c-p.complete:\n\t\tklog.V(5).InfoS(\"Connection request successfully received error and data streams\", \"connection\", h.conn, \"request\", p.requestID)\n\t}\n\th.removeStreamPair(p.requestID)\n}","line":{"from":137,"to":150}} {"id":100006486,"name":"hasStreamPair","signature":"func (h *httpStreamHandler) hasStreamPair(requestID string) bool","file":"pkg/kubelet/cri/streaming/portforward/httpstream.go","code":"// hasStreamPair returns a bool indicating if a stream pair for requestID\n// exists.\nfunc (h *httpStreamHandler) hasStreamPair(requestID string) bool {\n\th.streamPairsLock.RLock()\n\tdefer h.streamPairsLock.RUnlock()\n\n\t_, ok := h.streamPairs[requestID]\n\treturn ok\n}","line":{"from":152,"to":160}} {"id":100006487,"name":"removeStreamPair","signature":"func (h *httpStreamHandler) removeStreamPair(requestID string)","file":"pkg/kubelet/cri/streaming/portforward/httpstream.go","code":"// removeStreamPair removes the stream pair identified by requestID from streamPairs.\nfunc (h *httpStreamHandler) removeStreamPair(requestID string) {\n\th.streamPairsLock.Lock()\n\tdefer h.streamPairsLock.Unlock()\n\n\tif h.conn != nil {\n\t\tpair := h.streamPairs[requestID]\n\t\th.conn.RemoveStreams(pair.dataStream, pair.errorStream)\n\t}\n\tdelete(h.streamPairs, requestID)\n}","line":{"from":162,"to":172}} {"id":100006488,"name":"requestID","signature":"func (h *httpStreamHandler) requestID(stream httpstream.Stream) string","file":"pkg/kubelet/cri/streaming/portforward/httpstream.go","code":"// requestID returns the request id for stream.\nfunc (h *httpStreamHandler) requestID(stream httpstream.Stream) string {\n\trequestID := stream.Headers().Get(api.PortForwardRequestIDHeader)\n\tif len(requestID) == 0 {\n\t\tklog.V(5).InfoS(\"Connection stream received without requestID header\", \"connection\", h.conn)\n\t\t// If we get here, it's because the connection came from an older client\n\t\t// that isn't generating the request id header\n\t\t// (https://github.com/kubernetes/kubernetes/blob/843134885e7e0b360eb5441e85b1410a8b1a7a0c/pkg/client/unversioned/portforward/portforward.go#L258-L287)\n\t\t//\n\t\t// This is a best-effort attempt at supporting older clients.\n\t\t//\n\t\t// When there aren't concurrent new forwarded connections, each connection\n\t\t// will have a pair of streams (data, error), and the stream IDs will be\n\t\t// consecutive odd numbers, e.g. 1 and 3 for the first connection. Convert\n\t\t// the stream ID into a pseudo-request id by taking the stream type and\n\t\t// using id = stream.Identifier() when the stream type is error,\n\t\t// and id = stream.Identifier() - 2 when it's data.\n\t\t//\n\t\t// NOTE: this only works when there are not concurrent new streams from\n\t\t// multiple forwarded connections; it's a best-effort attempt at supporting\n\t\t// old clients that don't generate request ids. If there are concurrent\n\t\t// new connections, it's possible that 1 connection gets streams whose IDs\n\t\t// are not consecutive (e.g. 5 and 9 instead of 5 and 7).\n\t\tstreamType := stream.Headers().Get(api.StreamType)\n\t\tswitch streamType {\n\t\tcase api.StreamTypeError:\n\t\t\trequestID = strconv.Itoa(int(stream.Identifier()))\n\t\tcase api.StreamTypeData:\n\t\t\trequestID = strconv.Itoa(int(stream.Identifier()) - 2)\n\t\t}\n\n\t\tklog.V(5).InfoS(\"Connection automatically assigning request ID from stream type and stream ID\", \"connection\", h.conn, \"request\", requestID, \"streamType\", streamType, \"stream\", stream.Identifier())\n\t}\n\treturn requestID\n}","line":{"from":174,"to":208}} {"id":100006489,"name":"run","signature":"func (h *httpStreamHandler) run()","file":"pkg/kubelet/cri/streaming/portforward/httpstream.go","code":"// run is the main loop for the httpStreamHandler. It processes new\n// streams, invoking portForward for each complete stream pair. The loop exits\n// when the httpstream.Connection is closed.\nfunc (h *httpStreamHandler) run() {\n\tklog.V(5).InfoS(\"Connection waiting for port forward streams\", \"connection\", h.conn)\nLoop:\n\tfor {\n\t\tselect {\n\t\tcase \u003c-h.conn.CloseChan():\n\t\t\tklog.V(5).InfoS(\"Connection upgraded connection closed\", \"connection\", h.conn)\n\t\t\tbreak Loop\n\t\tcase stream := \u003c-h.streamChan:\n\t\t\trequestID := h.requestID(stream)\n\t\t\tstreamType := stream.Headers().Get(api.StreamType)\n\t\t\tklog.V(5).InfoS(\"Connection request received new type of stream\", \"connection\", h.conn, \"request\", requestID, \"streamType\", streamType)\n\n\t\t\tp, created := h.getStreamPair(requestID)\n\t\t\tif created {\n\t\t\t\tgo h.monitorStreamPair(p, time.After(h.streamCreationTimeout))\n\t\t\t}\n\t\t\tif complete, err := p.add(stream); err != nil {\n\t\t\t\tmsg := fmt.Sprintf(\"error processing stream for request %s: %v\", requestID, err)\n\t\t\t\tutilruntime.HandleError(errors.New(msg))\n\t\t\t\tp.printError(msg)\n\t\t\t} else if complete {\n\t\t\t\tgo h.portForward(p)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":210,"to":239}} {"id":100006490,"name":"portForward","signature":"func (h *httpStreamHandler) portForward(p *httpStreamPair)","file":"pkg/kubelet/cri/streaming/portforward/httpstream.go","code":"// portForward invokes the httpStreamHandler's forwarder.PortForward\n// function for the given stream pair.\nfunc (h *httpStreamHandler) portForward(p *httpStreamPair) {\n\tctx := context.Background()\n\tdefer p.dataStream.Close()\n\tdefer p.errorStream.Close()\n\n\tportString := p.dataStream.Headers().Get(api.PortHeader)\n\tport, _ := strconv.ParseInt(portString, 10, 32)\n\n\tklog.V(5).InfoS(\"Connection request invoking forwarder.PortForward for port\", \"connection\", h.conn, \"request\", p.requestID, \"port\", portString)\n\terr := h.forwarder.PortForward(ctx, h.pod, h.uid, int32(port), p.dataStream)\n\tklog.V(5).InfoS(\"Connection request done invoking forwarder.PortForward for port\", \"connection\", h.conn, \"request\", p.requestID, \"port\", portString)\n\n\tif err != nil {\n\t\tmsg := fmt.Errorf(\"error forwarding port %d to pod %s, uid %v: %v\", port, h.pod, h.uid, err)\n\t\tutilruntime.HandleError(msg)\n\t\tfmt.Fprint(p.errorStream, msg.Error())\n\t}\n}","line":{"from":241,"to":260}} {"id":100006491,"name":"newPortForwardPair","signature":"func newPortForwardPair(requestID string) *httpStreamPair","file":"pkg/kubelet/cri/streaming/portforward/httpstream.go","code":"// newPortForwardPair creates a new httpStreamPair.\nfunc newPortForwardPair(requestID string) *httpStreamPair {\n\treturn \u0026httpStreamPair{\n\t\trequestID: requestID,\n\t\tcomplete: make(chan struct{}),\n\t}\n}","line":{"from":272,"to":278}} {"id":100006492,"name":"add","signature":"func (p *httpStreamPair) add(stream httpstream.Stream) (bool, error)","file":"pkg/kubelet/cri/streaming/portforward/httpstream.go","code":"// add adds the stream to the httpStreamPair. If the pair already\n// contains a stream for the new stream's type, an error is returned. add\n// returns true if both the data and error streams for this pair have been\n// received.\nfunc (p *httpStreamPair) add(stream httpstream.Stream) (bool, error) {\n\tp.lock.Lock()\n\tdefer p.lock.Unlock()\n\n\tswitch stream.Headers().Get(api.StreamType) {\n\tcase api.StreamTypeError:\n\t\tif p.errorStream != nil {\n\t\t\treturn false, errors.New(\"error stream already assigned\")\n\t\t}\n\t\tp.errorStream = stream\n\tcase api.StreamTypeData:\n\t\tif p.dataStream != nil {\n\t\t\treturn false, errors.New(\"data stream already assigned\")\n\t\t}\n\t\tp.dataStream = stream\n\t}\n\n\tcomplete := p.errorStream != nil \u0026\u0026 p.dataStream != nil\n\tif complete {\n\t\tclose(p.complete)\n\t}\n\treturn complete, nil\n}","line":{"from":280,"to":306}} {"id":100006493,"name":"printError","signature":"func (p *httpStreamPair) printError(s string)","file":"pkg/kubelet/cri/streaming/portforward/httpstream.go","code":"// printError writes s to p.errorStream if p.errorStream has been set.\nfunc (p *httpStreamPair) printError(s string) {\n\tp.lock.RLock()\n\tdefer p.lock.RUnlock()\n\tif p.errorStream != nil {\n\t\tfmt.Fprint(p.errorStream, s)\n\t}\n}","line":{"from":308,"to":315}} {"id":100006494,"name":"ServePortForward","signature":"func ServePortForward(w http.ResponseWriter, req *http.Request, portForwarder PortForwarder, podName string, uid types.UID, portForwardOptions *V4Options, idleTimeout time.Duration, streamCreationTimeout time.Duration, supportedProtocols []string)","file":"pkg/kubelet/cri/streaming/portforward/portforward.go","code":"// ServePortForward handles a port forwarding request. A single request is\n// kept alive as long as the client is still alive and the connection has not\n// been timed out due to idleness. This function handles multiple forwarded\n// connections; i.e., multiple `curl http://localhost:8888/` requests will be\n// handled by a single invocation of ServePortForward.\nfunc ServePortForward(w http.ResponseWriter, req *http.Request, portForwarder PortForwarder, podName string, uid types.UID, portForwardOptions *V4Options, idleTimeout time.Duration, streamCreationTimeout time.Duration, supportedProtocols []string) {\n\tvar err error\n\tif wsstream.IsWebSocketRequest(req) {\n\t\terr = handleWebSocketStreams(req, w, portForwarder, podName, uid, portForwardOptions, supportedProtocols, idleTimeout, streamCreationTimeout)\n\t} else {\n\t\terr = handleHTTPStreams(req, w, portForwarder, podName, uid, supportedProtocols, idleTimeout, streamCreationTimeout)\n\t}\n\n\tif err != nil {\n\t\truntime.HandleError(err)\n\t\treturn\n\t}\n}","line":{"from":37,"to":54}} {"id":100006495,"name":"NewV4Options","signature":"func NewV4Options(req *http.Request) (*V4Options, error)","file":"pkg/kubelet/cri/streaming/portforward/websocket.go","code":"// NewV4Options creates a new options from the Request.\nfunc NewV4Options(req *http.Request) (*V4Options, error) {\n\tif !wsstream.IsWebSocketRequest(req) {\n\t\treturn \u0026V4Options{}, nil\n\t}\n\n\tportStrings := req.URL.Query()[api.PortHeader]\n\tif len(portStrings) == 0 {\n\t\treturn nil, fmt.Errorf(\"query parameter %q is required\", api.PortHeader)\n\t}\n\n\tports := make([]int32, 0, len(portStrings))\n\tfor _, portString := range portStrings {\n\t\tif len(portString) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"query parameter %q cannot be empty\", api.PortHeader)\n\t\t}\n\t\tfor _, p := range strings.Split(portString, \",\") {\n\t\t\tport, err := strconv.ParseUint(p, 10, 16)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"unable to parse %q as a port: %v\", portString, err)\n\t\t\t}\n\t\t\tif port \u003c 1 {\n\t\t\t\treturn nil, fmt.Errorf(\"port %q must be \u003e 0\", portString)\n\t\t\t}\n\t\t\tports = append(ports, int32(port))\n\t\t}\n\t}\n\n\treturn \u0026V4Options{\n\t\tPorts: ports,\n\t}, nil\n}","line":{"from":55,"to":86}} {"id":100006496,"name":"BuildV4Options","signature":"func BuildV4Options(ports []int32) (*V4Options, error)","file":"pkg/kubelet/cri/streaming/portforward/websocket.go","code":"// BuildV4Options returns a V4Options based on the given information.\nfunc BuildV4Options(ports []int32) (*V4Options, error) {\n\treturn \u0026V4Options{Ports: ports}, nil\n}","line":{"from":88,"to":91}} {"id":100006497,"name":"handleWebSocketStreams","signature":"func handleWebSocketStreams(req *http.Request, w http.ResponseWriter, portForwarder PortForwarder, podName string, uid types.UID, opts *V4Options, supportedPortForwardProtocols []string, idleTimeout, streamCreationTimeout time.Duration) error","file":"pkg/kubelet/cri/streaming/portforward/websocket.go","code":"// handleWebSocketStreams handles requests to forward ports to a pod via\n// a PortForwarder. A pair of streams are created per port (DATA n,\n// ERROR n+1). The associated port is written to each stream as a unsigned 16\n// bit integer in little endian format.\nfunc handleWebSocketStreams(req *http.Request, w http.ResponseWriter, portForwarder PortForwarder, podName string, uid types.UID, opts *V4Options, supportedPortForwardProtocols []string, idleTimeout, streamCreationTimeout time.Duration) error {\n\tchannels := make([]wsstream.ChannelType, 0, len(opts.Ports)*2)\n\tfor i := 0; i \u003c len(opts.Ports); i++ {\n\t\tchannels = append(channels, wsstream.ReadWriteChannel, wsstream.WriteChannel)\n\t}\n\tconn := wsstream.NewConn(map[string]wsstream.ChannelProtocolConfig{\n\t\t\"\": {\n\t\t\tBinary: true,\n\t\t\tChannels: channels,\n\t\t},\n\t\tv4BinaryWebsocketProtocol: {\n\t\t\tBinary: true,\n\t\t\tChannels: channels,\n\t\t},\n\t\tv4Base64WebsocketProtocol: {\n\t\t\tBinary: false,\n\t\t\tChannels: channels,\n\t\t},\n\t})\n\tconn.SetIdleTimeout(idleTimeout)\n\t_, streams, err := conn.Open(responsewriter.GetOriginal(w), req)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"unable to upgrade websocket connection: %v\", err)\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\tstreamPairs := make([]*websocketStreamPair, len(opts.Ports))\n\tfor i := range streamPairs {\n\t\tstreamPair := websocketStreamPair{\n\t\t\tport: opts.Ports[i],\n\t\t\tdataStream: streams[i*2+dataChannel],\n\t\t\terrorStream: streams[i*2+errorChannel],\n\t\t}\n\t\tstreamPairs[i] = \u0026streamPair\n\n\t\tportBytes := make([]byte, 2)\n\t\t// port is always positive so conversion is allowable\n\t\tbinary.LittleEndian.PutUint16(portBytes, uint16(streamPair.port))\n\t\tstreamPair.dataStream.Write(portBytes)\n\t\tstreamPair.errorStream.Write(portBytes)\n\t}\n\th := \u0026websocketStreamHandler{\n\t\tconn: conn,\n\t\tstreamPairs: streamPairs,\n\t\tpod: podName,\n\t\tuid: uid,\n\t\tforwarder: portForwarder,\n\t}\n\th.run()\n\n\treturn nil\n}","line":{"from":93,"to":148}} {"id":100006498,"name":"run","signature":"func (h *websocketStreamHandler) run()","file":"pkg/kubelet/cri/streaming/portforward/websocket.go","code":"// run invokes the websocketStreamHandler's forwarder.PortForward\n// function for the given stream pair.\nfunc (h *websocketStreamHandler) run() {\n\twg := sync.WaitGroup{}\n\twg.Add(len(h.streamPairs))\n\n\tfor _, pair := range h.streamPairs {\n\t\tp := pair\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\th.portForward(p)\n\t\t}()\n\t}\n\n\twg.Wait()\n}","line":{"from":168,"to":183}} {"id":100006499,"name":"portForward","signature":"func (h *websocketStreamHandler) portForward(p *websocketStreamPair)","file":"pkg/kubelet/cri/streaming/portforward/websocket.go","code":"func (h *websocketStreamHandler) portForward(p *websocketStreamPair) {\n\tctx := context.Background()\n\tdefer p.dataStream.Close()\n\tdefer p.errorStream.Close()\n\n\tklog.V(5).InfoS(\"Connection invoking forwarder.PortForward for port\", \"connection\", h.conn, \"port\", p.port)\n\terr := h.forwarder.PortForward(ctx, h.pod, h.uid, p.port, p.dataStream)\n\tklog.V(5).InfoS(\"Connection done invoking forwarder.PortForward for port\", \"connection\", h.conn, \"port\", p.port)\n\n\tif err != nil {\n\t\tmsg := fmt.Errorf(\"error forwarding port %d to pod %s, uid %v: %v\", p.port, h.pod, h.uid, err)\n\t\truntime.HandleError(msg)\n\t\tfmt.Fprint(p.errorStream, msg.Error())\n\t}\n}","line":{"from":185,"to":199}} {"id":100006500,"name":"ServeAttach","signature":"func ServeAttach(w http.ResponseWriter, req *http.Request, attacher Attacher, podName string, uid types.UID, container string, streamOpts *Options, idleTimeout, streamCreationTimeout time.Duration, supportedProtocols []string)","file":"pkg/kubelet/cri/streaming/remotecommand/attach.go","code":"// ServeAttach handles requests to attach to a container. After creating/receiving the required\n// streams, it delegates the actual attaching to attacher.\nfunc ServeAttach(w http.ResponseWriter, req *http.Request, attacher Attacher, podName string, uid types.UID, container string, streamOpts *Options, idleTimeout, streamCreationTimeout time.Duration, supportedProtocols []string) {\n\tctx, ok := createStreams(req, w, streamOpts, supportedProtocols, idleTimeout, streamCreationTimeout)\n\tif !ok {\n\t\t// error is handled by createStreams\n\t\treturn\n\t}\n\tdefer ctx.conn.Close()\n\n\terr := attacher.AttachContainer(req.Context(), podName, uid, container, ctx.stdinStream, ctx.stdoutStream, ctx.stderrStream, ctx.tty, ctx.resizeChan)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"error attaching to container: %v\", err)\n\t\truntime.HandleError(err)\n\t\tctx.writeStatus(apierrors.NewInternalError(err))\n\t} else {\n\t\tctx.writeStatus(\u0026apierrors.StatusError{ErrStatus: metav1.Status{\n\t\t\tStatus: metav1.StatusSuccess,\n\t\t}})\n\t}\n}","line":{"from":40,"to":60}} {"id":100006501,"name":"ServeExec","signature":"func ServeExec(w http.ResponseWriter, req *http.Request, executor Executor, podName string, uid types.UID, container string, cmd []string, streamOpts *Options, idleTimeout, streamCreationTimeout time.Duration, supportedProtocols []string)","file":"pkg/kubelet/cri/streaming/remotecommand/exec.go","code":"// ServeExec handles requests to execute a command in a container. After\n// creating/receiving the required streams, it delegates the actual execution\n// to the executor.\nfunc ServeExec(w http.ResponseWriter, req *http.Request, executor Executor, podName string, uid types.UID, container string, cmd []string, streamOpts *Options, idleTimeout, streamCreationTimeout time.Duration, supportedProtocols []string) {\n\tctx, ok := createStreams(req, w, streamOpts, supportedProtocols, idleTimeout, streamCreationTimeout)\n\tif !ok {\n\t\t// error is handled by createStreams\n\t\treturn\n\t}\n\tdefer ctx.conn.Close()\n\n\terr := executor.ExecInContainer(req.Context(), podName, uid, container, cmd, ctx.stdinStream, ctx.stdoutStream, ctx.stderrStream, ctx.tty, ctx.resizeChan, 0)\n\tif err != nil {\n\t\tif exitErr, ok := err.(utilexec.ExitError); ok \u0026\u0026 exitErr.Exited() {\n\t\t\trc := exitErr.ExitStatus()\n\t\t\tctx.writeStatus(\u0026apierrors.StatusError{ErrStatus: metav1.Status{\n\t\t\t\tStatus: metav1.StatusFailure,\n\t\t\t\tReason: remotecommandconsts.NonZeroExitCodeReason,\n\t\t\t\tDetails: \u0026metav1.StatusDetails{\n\t\t\t\t\tCauses: []metav1.StatusCause{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tType: remotecommandconsts.ExitCodeCauseType,\n\t\t\t\t\t\t\tMessage: fmt.Sprintf(\"%d\", rc),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tMessage: fmt.Sprintf(\"command terminated with non-zero exit code: %v\", exitErr),\n\t\t\t}})\n\t\t} else {\n\t\t\terr = fmt.Errorf(\"error executing command in container: %v\", err)\n\t\t\truntime.HandleError(err)\n\t\t\tctx.writeStatus(apierrors.NewInternalError(err))\n\t\t}\n\t} else {\n\t\tctx.writeStatus(\u0026apierrors.StatusError{ErrStatus: metav1.Status{\n\t\t\tStatus: metav1.StatusSuccess,\n\t\t}})\n\t}\n}","line":{"from":42,"to":80}} {"id":100006502,"name":"NewOptions","signature":"func NewOptions(req *http.Request) (*Options, error)","file":"pkg/kubelet/cri/streaming/remotecommand/httpstream.go","code":"// NewOptions creates a new Options from the Request.\nfunc NewOptions(req *http.Request) (*Options, error) {\n\ttty := req.FormValue(api.ExecTTYParam) == \"1\"\n\tstdin := req.FormValue(api.ExecStdinParam) == \"1\"\n\tstdout := req.FormValue(api.ExecStdoutParam) == \"1\"\n\tstderr := req.FormValue(api.ExecStderrParam) == \"1\"\n\tif tty \u0026\u0026 stderr {\n\t\t// TODO: make this an error before we reach this method\n\t\tklog.V(4).InfoS(\"Access to exec with tty and stderr is not supported, bypassing stderr\")\n\t\tstderr = false\n\t}\n\n\tif !stdin \u0026\u0026 !stdout \u0026\u0026 !stderr {\n\t\treturn nil, fmt.Errorf(\"you must specify at least 1 of stdin, stdout, stderr\")\n\t}\n\n\treturn \u0026Options{\n\t\tStdin: stdin,\n\t\tStdout: stdout,\n\t\tStderr: stderr,\n\t\tTTY: tty,\n\t}, nil\n}","line":{"from":49,"to":71}} {"id":100006503,"name":"waitStreamReply","signature":"func waitStreamReply(replySent \u003c-chan struct{}, notify chan\u003c- struct{}, stop \u003c-chan struct{})","file":"pkg/kubelet/cri/streaming/remotecommand/httpstream.go","code":"// waitStreamReply waits until either replySent or stop is closed. If replySent is closed, it sends\n// an empty struct to the notify channel.\nfunc waitStreamReply(replySent \u003c-chan struct{}, notify chan\u003c- struct{}, stop \u003c-chan struct{}) {\n\tselect {\n\tcase \u003c-replySent:\n\t\tnotify \u003c- struct{}{}\n\tcase \u003c-stop:\n\t}\n}","line":{"from":95,"to":103}} {"id":100006504,"name":"createStreams","signature":"func createStreams(req *http.Request, w http.ResponseWriter, opts *Options, supportedStreamProtocols []string, idleTimeout, streamCreationTimeout time.Duration) (*connectionContext, bool)","file":"pkg/kubelet/cri/streaming/remotecommand/httpstream.go","code":"func createStreams(req *http.Request, w http.ResponseWriter, opts *Options, supportedStreamProtocols []string, idleTimeout, streamCreationTimeout time.Duration) (*connectionContext, bool) {\n\tvar ctx *connectionContext\n\tvar ok bool\n\tif wsstream.IsWebSocketRequest(req) {\n\t\tctx, ok = createWebSocketStreams(req, w, opts, idleTimeout)\n\t} else {\n\t\tctx, ok = createHTTPStreamStreams(req, w, opts, supportedStreamProtocols, idleTimeout, streamCreationTimeout)\n\t}\n\tif !ok {\n\t\treturn nil, false\n\t}\n\n\tif ctx.resizeStream != nil {\n\t\tctx.resizeChan = make(chan remotecommand.TerminalSize)\n\t\tgo handleResizeEvents(ctx.resizeStream, ctx.resizeChan)\n\t}\n\n\treturn ctx, true\n}","line":{"from":105,"to":123}} {"id":100006505,"name":"createHTTPStreamStreams","signature":"func createHTTPStreamStreams(req *http.Request, w http.ResponseWriter, opts *Options, supportedStreamProtocols []string, idleTimeout, streamCreationTimeout time.Duration) (*connectionContext, bool)","file":"pkg/kubelet/cri/streaming/remotecommand/httpstream.go","code":"func createHTTPStreamStreams(req *http.Request, w http.ResponseWriter, opts *Options, supportedStreamProtocols []string, idleTimeout, streamCreationTimeout time.Duration) (*connectionContext, bool) {\n\tprotocol, err := httpstream.Handshake(req, w, supportedStreamProtocols)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn nil, false\n\t}\n\n\tstreamCh := make(chan streamAndReply)\n\n\tupgrader := spdy.NewResponseUpgrader()\n\tconn := upgrader.UpgradeResponse(w, req, func(stream httpstream.Stream, replySent \u003c-chan struct{}) error {\n\t\tstreamCh \u003c- streamAndReply{Stream: stream, replySent: replySent}\n\t\treturn nil\n\t})\n\t// from this point on, we can no longer call methods on response\n\tif conn == nil {\n\t\t// The upgrader is responsible for notifying the client of any errors that\n\t\t// occurred during upgrading. All we can do is return here at this point\n\t\t// if we weren't successful in upgrading.\n\t\treturn nil, false\n\t}\n\n\tconn.SetIdleTimeout(idleTimeout)\n\n\tvar handler protocolHandler\n\tswitch protocol {\n\tcase remotecommandconsts.StreamProtocolV4Name:\n\t\thandler = \u0026v4ProtocolHandler{}\n\tcase remotecommandconsts.StreamProtocolV3Name:\n\t\thandler = \u0026v3ProtocolHandler{}\n\tcase remotecommandconsts.StreamProtocolV2Name:\n\t\thandler = \u0026v2ProtocolHandler{}\n\tcase \"\":\n\t\tklog.V(4).InfoS(\"Client did not request protocol negotiation. Falling back\", \"protocol\", remotecommandconsts.StreamProtocolV1Name)\n\t\tfallthrough\n\tcase remotecommandconsts.StreamProtocolV1Name:\n\t\thandler = \u0026v1ProtocolHandler{}\n\t}\n\n\t// count the streams client asked for, starting with 1\n\texpectedStreams := 1\n\tif opts.Stdin {\n\t\texpectedStreams++\n\t}\n\tif opts.Stdout {\n\t\texpectedStreams++\n\t}\n\tif opts.Stderr {\n\t\texpectedStreams++\n\t}\n\tif opts.TTY \u0026\u0026 handler.supportsTerminalResizing() {\n\t\texpectedStreams++\n\t}\n\n\texpired := time.NewTimer(streamCreationTimeout)\n\tdefer expired.Stop()\n\n\tctx, err := handler.waitForStreams(streamCh, expectedStreams, expired.C)\n\tif err != nil {\n\t\truntime.HandleError(err)\n\t\treturn nil, false\n\t}\n\n\tctx.conn = conn\n\tctx.tty = opts.TTY\n\n\treturn ctx, true\n}","line":{"from":125,"to":192}} {"id":100006506,"name":"waitForStreams","signature":"func (*v4ProtocolHandler) waitForStreams(streams \u003c-chan streamAndReply, expectedStreams int, expired \u003c-chan time.Time) (*connectionContext, error)","file":"pkg/kubelet/cri/streaming/remotecommand/httpstream.go","code":"func (*v4ProtocolHandler) waitForStreams(streams \u003c-chan streamAndReply, expectedStreams int, expired \u003c-chan time.Time) (*connectionContext, error) {\n\tctx := \u0026connectionContext{}\n\treceivedStreams := 0\n\treplyChan := make(chan struct{})\n\tstop := make(chan struct{})\n\tdefer close(stop)\nWaitForStreams:\n\tfor {\n\t\tselect {\n\t\tcase stream := \u003c-streams:\n\t\t\tstreamType := stream.Headers().Get(api.StreamType)\n\t\t\tswitch streamType {\n\t\t\tcase api.StreamTypeError:\n\t\t\t\tctx.writeStatus = v4WriteStatusFunc(stream) // write json errors\n\t\t\t\tgo waitStreamReply(stream.replySent, replyChan, stop)\n\t\t\tcase api.StreamTypeStdin:\n\t\t\t\tctx.stdinStream = stream\n\t\t\t\tgo waitStreamReply(stream.replySent, replyChan, stop)\n\t\t\tcase api.StreamTypeStdout:\n\t\t\t\tctx.stdoutStream = stream\n\t\t\t\tgo waitStreamReply(stream.replySent, replyChan, stop)\n\t\t\tcase api.StreamTypeStderr:\n\t\t\t\tctx.stderrStream = stream\n\t\t\t\tgo waitStreamReply(stream.replySent, replyChan, stop)\n\t\t\tcase api.StreamTypeResize:\n\t\t\t\tctx.resizeStream = stream\n\t\t\t\tgo waitStreamReply(stream.replySent, replyChan, stop)\n\t\t\tdefault:\n\t\t\t\truntime.HandleError(fmt.Errorf(\"unexpected stream type: %q\", streamType))\n\t\t\t}\n\t\tcase \u003c-replyChan:\n\t\t\treceivedStreams++\n\t\t\tif receivedStreams == expectedStreams {\n\t\t\t\tbreak WaitForStreams\n\t\t\t}\n\t\tcase \u003c-expired:\n\t\t\t// TODO find a way to return the error to the user. Maybe use a separate\n\t\t\t// stream to report errors?\n\t\t\treturn nil, errors.New(\"timed out waiting for client to create streams\")\n\t\t}\n\t}\n\n\treturn ctx, nil\n}","line":{"from":207,"to":250}} {"id":100006507,"name":"supportsTerminalResizing","signature":"func (*v4ProtocolHandler) supportsTerminalResizing() bool { return true }","file":"pkg/kubelet/cri/streaming/remotecommand/httpstream.go","code":"// supportsTerminalResizing returns true because v4ProtocolHandler supports it\nfunc (*v4ProtocolHandler) supportsTerminalResizing() bool { return true }","line":{"from":252,"to":253}} {"id":100006508,"name":"waitForStreams","signature":"func (*v3ProtocolHandler) waitForStreams(streams \u003c-chan streamAndReply, expectedStreams int, expired \u003c-chan time.Time) (*connectionContext, error)","file":"pkg/kubelet/cri/streaming/remotecommand/httpstream.go","code":"func (*v3ProtocolHandler) waitForStreams(streams \u003c-chan streamAndReply, expectedStreams int, expired \u003c-chan time.Time) (*connectionContext, error) {\n\tctx := \u0026connectionContext{}\n\treceivedStreams := 0\n\treplyChan := make(chan struct{})\n\tstop := make(chan struct{})\n\tdefer close(stop)\nWaitForStreams:\n\tfor {\n\t\tselect {\n\t\tcase stream := \u003c-streams:\n\t\t\tstreamType := stream.Headers().Get(api.StreamType)\n\t\t\tswitch streamType {\n\t\t\tcase api.StreamTypeError:\n\t\t\t\tctx.writeStatus = v1WriteStatusFunc(stream)\n\t\t\t\tgo waitStreamReply(stream.replySent, replyChan, stop)\n\t\t\tcase api.StreamTypeStdin:\n\t\t\t\tctx.stdinStream = stream\n\t\t\t\tgo waitStreamReply(stream.replySent, replyChan, stop)\n\t\t\tcase api.StreamTypeStdout:\n\t\t\t\tctx.stdoutStream = stream\n\t\t\t\tgo waitStreamReply(stream.replySent, replyChan, stop)\n\t\t\tcase api.StreamTypeStderr:\n\t\t\t\tctx.stderrStream = stream\n\t\t\t\tgo waitStreamReply(stream.replySent, replyChan, stop)\n\t\t\tcase api.StreamTypeResize:\n\t\t\t\tctx.resizeStream = stream\n\t\t\t\tgo waitStreamReply(stream.replySent, replyChan, stop)\n\t\t\tdefault:\n\t\t\t\truntime.HandleError(fmt.Errorf(\"unexpected stream type: %q\", streamType))\n\t\t\t}\n\t\tcase \u003c-replyChan:\n\t\t\treceivedStreams++\n\t\t\tif receivedStreams == expectedStreams {\n\t\t\t\tbreak WaitForStreams\n\t\t\t}\n\t\tcase \u003c-expired:\n\t\t\t// TODO find a way to return the error to the user. Maybe use a separate\n\t\t\t// stream to report errors?\n\t\t\treturn nil, errors.New(\"timed out waiting for client to create streams\")\n\t\t}\n\t}\n\n\treturn ctx, nil\n}","line":{"from":258,"to":301}} {"id":100006509,"name":"supportsTerminalResizing","signature":"func (*v3ProtocolHandler) supportsTerminalResizing() bool { return true }","file":"pkg/kubelet/cri/streaming/remotecommand/httpstream.go","code":"// supportsTerminalResizing returns true because v3ProtocolHandler supports it\nfunc (*v3ProtocolHandler) supportsTerminalResizing() bool { return true }","line":{"from":303,"to":304}} {"id":100006510,"name":"waitForStreams","signature":"func (*v2ProtocolHandler) waitForStreams(streams \u003c-chan streamAndReply, expectedStreams int, expired \u003c-chan time.Time) (*connectionContext, error)","file":"pkg/kubelet/cri/streaming/remotecommand/httpstream.go","code":"func (*v2ProtocolHandler) waitForStreams(streams \u003c-chan streamAndReply, expectedStreams int, expired \u003c-chan time.Time) (*connectionContext, error) {\n\tctx := \u0026connectionContext{}\n\treceivedStreams := 0\n\treplyChan := make(chan struct{})\n\tstop := make(chan struct{})\n\tdefer close(stop)\nWaitForStreams:\n\tfor {\n\t\tselect {\n\t\tcase stream := \u003c-streams:\n\t\t\tstreamType := stream.Headers().Get(api.StreamType)\n\t\t\tswitch streamType {\n\t\t\tcase api.StreamTypeError:\n\t\t\t\tctx.writeStatus = v1WriteStatusFunc(stream)\n\t\t\t\tgo waitStreamReply(stream.replySent, replyChan, stop)\n\t\t\tcase api.StreamTypeStdin:\n\t\t\t\tctx.stdinStream = stream\n\t\t\t\tgo waitStreamReply(stream.replySent, replyChan, stop)\n\t\t\tcase api.StreamTypeStdout:\n\t\t\t\tctx.stdoutStream = stream\n\t\t\t\tgo waitStreamReply(stream.replySent, replyChan, stop)\n\t\t\tcase api.StreamTypeStderr:\n\t\t\t\tctx.stderrStream = stream\n\t\t\t\tgo waitStreamReply(stream.replySent, replyChan, stop)\n\t\t\tdefault:\n\t\t\t\truntime.HandleError(fmt.Errorf(\"unexpected stream type: %q\", streamType))\n\t\t\t}\n\t\tcase \u003c-replyChan:\n\t\t\treceivedStreams++\n\t\t\tif receivedStreams == expectedStreams {\n\t\t\t\tbreak WaitForStreams\n\t\t\t}\n\t\tcase \u003c-expired:\n\t\t\t// TODO find a way to return the error to the user. Maybe use a separate\n\t\t\t// stream to report errors?\n\t\t\treturn nil, errors.New(\"timed out waiting for client to create streams\")\n\t\t}\n\t}\n\n\treturn ctx, nil\n}","line":{"from":309,"to":349}} {"id":100006511,"name":"supportsTerminalResizing","signature":"func (*v2ProtocolHandler) supportsTerminalResizing() bool { return false }","file":"pkg/kubelet/cri/streaming/remotecommand/httpstream.go","code":"// supportsTerminalResizing returns false because v2ProtocolHandler doesn't support it.\nfunc (*v2ProtocolHandler) supportsTerminalResizing() bool { return false }","line":{"from":351,"to":352}} {"id":100006512,"name":"waitForStreams","signature":"func (*v1ProtocolHandler) waitForStreams(streams \u003c-chan streamAndReply, expectedStreams int, expired \u003c-chan time.Time) (*connectionContext, error)","file":"pkg/kubelet/cri/streaming/remotecommand/httpstream.go","code":"func (*v1ProtocolHandler) waitForStreams(streams \u003c-chan streamAndReply, expectedStreams int, expired \u003c-chan time.Time) (*connectionContext, error) {\n\tctx := \u0026connectionContext{}\n\treceivedStreams := 0\n\treplyChan := make(chan struct{})\n\tstop := make(chan struct{})\n\tdefer close(stop)\nWaitForStreams:\n\tfor {\n\t\tselect {\n\t\tcase stream := \u003c-streams:\n\t\t\tstreamType := stream.Headers().Get(api.StreamType)\n\t\t\tswitch streamType {\n\t\t\tcase api.StreamTypeError:\n\t\t\t\tctx.writeStatus = v1WriteStatusFunc(stream)\n\n\t\t\t\t// This defer statement shouldn't be here, but due to previous refactoring, it ended up in\n\t\t\t\t// here. This is what 1.0.x kubelets do, so we're retaining that behavior. This is fixed in\n\t\t\t\t// the v2ProtocolHandler.\n\t\t\t\tdefer stream.Reset()\n\n\t\t\t\tgo waitStreamReply(stream.replySent, replyChan, stop)\n\t\t\tcase api.StreamTypeStdin:\n\t\t\t\tctx.stdinStream = stream\n\t\t\t\tgo waitStreamReply(stream.replySent, replyChan, stop)\n\t\t\tcase api.StreamTypeStdout:\n\t\t\t\tctx.stdoutStream = stream\n\t\t\t\tgo waitStreamReply(stream.replySent, replyChan, stop)\n\t\t\tcase api.StreamTypeStderr:\n\t\t\t\tctx.stderrStream = stream\n\t\t\t\tgo waitStreamReply(stream.replySent, replyChan, stop)\n\t\t\tdefault:\n\t\t\t\truntime.HandleError(fmt.Errorf(\"unexpected stream type: %q\", streamType))\n\t\t\t}\n\t\tcase \u003c-replyChan:\n\t\t\treceivedStreams++\n\t\t\tif receivedStreams == expectedStreams {\n\t\t\t\tbreak WaitForStreams\n\t\t\t}\n\t\tcase \u003c-expired:\n\t\t\t// TODO find a way to return the error to the user. Maybe use a separate\n\t\t\t// stream to report errors?\n\t\t\treturn nil, errors.New(\"timed out waiting for client to create streams\")\n\t\t}\n\t}\n\n\tif ctx.stdinStream != nil {\n\t\tctx.stdinStream.Close()\n\t}\n\n\treturn ctx, nil\n}","line":{"from":357,"to":407}} {"id":100006513,"name":"supportsTerminalResizing","signature":"func (*v1ProtocolHandler) supportsTerminalResizing() bool { return false }","file":"pkg/kubelet/cri/streaming/remotecommand/httpstream.go","code":"// supportsTerminalResizing returns false because v1ProtocolHandler doesn't support it.\nfunc (*v1ProtocolHandler) supportsTerminalResizing() bool { return false }","line":{"from":409,"to":410}} {"id":100006514,"name":"handleResizeEvents","signature":"func handleResizeEvents(stream io.Reader, channel chan\u003c- remotecommand.TerminalSize)","file":"pkg/kubelet/cri/streaming/remotecommand/httpstream.go","code":"func handleResizeEvents(stream io.Reader, channel chan\u003c- remotecommand.TerminalSize) {\n\tdefer runtime.HandleCrash()\n\tdefer close(channel)\n\n\tdecoder := json.NewDecoder(stream)\n\tfor {\n\t\tsize := remotecommand.TerminalSize{}\n\t\tif err := decoder.Decode(\u0026size); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tchannel \u003c- size\n\t}\n}","line":{"from":412,"to":424}} {"id":100006515,"name":"v1WriteStatusFunc","signature":"func v1WriteStatusFunc(stream io.Writer) func(status *apierrors.StatusError) error","file":"pkg/kubelet/cri/streaming/remotecommand/httpstream.go","code":"func v1WriteStatusFunc(stream io.Writer) func(status *apierrors.StatusError) error {\n\treturn func(status *apierrors.StatusError) error {\n\t\tif status.Status().Status == metav1.StatusSuccess {\n\t\t\treturn nil // send error messages\n\t\t}\n\t\t_, err := stream.Write([]byte(status.Error()))\n\t\treturn err\n\t}\n}","line":{"from":426,"to":434}} {"id":100006516,"name":"v4WriteStatusFunc","signature":"func v4WriteStatusFunc(stream io.Writer) func(status *apierrors.StatusError) error","file":"pkg/kubelet/cri/streaming/remotecommand/httpstream.go","code":"// v4WriteStatusFunc returns a WriteStatusFunc that marshals a given api Status\n// as json in the error channel.\nfunc v4WriteStatusFunc(stream io.Writer) func(status *apierrors.StatusError) error {\n\treturn func(status *apierrors.StatusError) error {\n\t\tbs, err := json.Marshal(status.Status())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = stream.Write(bs)\n\t\treturn err\n\t}\n}","line":{"from":436,"to":447}} {"id":100006517,"name":"createChannels","signature":"func createChannels(opts *Options) []wsstream.ChannelType","file":"pkg/kubelet/cri/streaming/remotecommand/websocket.go","code":"// createChannels returns the standard channel types for a shell connection (STDIN 0, STDOUT 1, STDERR 2)\n// along with the approximate duplex value. It also creates the error (3) and resize (4) channels.\nfunc createChannels(opts *Options) []wsstream.ChannelType {\n\t// open the requested channels, and always open the error channel\n\tchannels := make([]wsstream.ChannelType, 5)\n\tchannels[stdinChannel] = readChannel(opts.Stdin)\n\tchannels[stdoutChannel] = writeChannel(opts.Stdout)\n\tchannels[stderrChannel] = writeChannel(opts.Stderr)\n\tchannels[errorChannel] = wsstream.WriteChannel\n\tchannels[resizeChannel] = wsstream.ReadChannel\n\treturn channels\n}","line":{"from":42,"to":53}} {"id":100006518,"name":"readChannel","signature":"func readChannel(real bool) wsstream.ChannelType","file":"pkg/kubelet/cri/streaming/remotecommand/websocket.go","code":"// readChannel returns wsstream.ReadChannel if real is true, or wsstream.IgnoreChannel.\nfunc readChannel(real bool) wsstream.ChannelType {\n\tif real {\n\t\treturn wsstream.ReadChannel\n\t}\n\treturn wsstream.IgnoreChannel\n}","line":{"from":55,"to":61}} {"id":100006519,"name":"writeChannel","signature":"func writeChannel(real bool) wsstream.ChannelType","file":"pkg/kubelet/cri/streaming/remotecommand/websocket.go","code":"// writeChannel returns wsstream.WriteChannel if real is true, or wsstream.IgnoreChannel.\nfunc writeChannel(real bool) wsstream.ChannelType {\n\tif real {\n\t\treturn wsstream.WriteChannel\n\t}\n\treturn wsstream.IgnoreChannel\n}","line":{"from":63,"to":69}} {"id":100006520,"name":"createWebSocketStreams","signature":"func createWebSocketStreams(req *http.Request, w http.ResponseWriter, opts *Options, idleTimeout time.Duration) (*connectionContext, bool)","file":"pkg/kubelet/cri/streaming/remotecommand/websocket.go","code":"// createWebSocketStreams returns a connectionContext containing the websocket connection and\n// streams needed to perform an exec or an attach.\nfunc createWebSocketStreams(req *http.Request, w http.ResponseWriter, opts *Options, idleTimeout time.Duration) (*connectionContext, bool) {\n\tchannels := createChannels(opts)\n\tconn := wsstream.NewConn(map[string]wsstream.ChannelProtocolConfig{\n\t\t\"\": {\n\t\t\tBinary: true,\n\t\t\tChannels: channels,\n\t\t},\n\t\tpreV4BinaryWebsocketProtocol: {\n\t\t\tBinary: true,\n\t\t\tChannels: channels,\n\t\t},\n\t\tpreV4Base64WebsocketProtocol: {\n\t\t\tBinary: false,\n\t\t\tChannels: channels,\n\t\t},\n\t\tv4BinaryWebsocketProtocol: {\n\t\t\tBinary: true,\n\t\t\tChannels: channels,\n\t\t},\n\t\tv4Base64WebsocketProtocol: {\n\t\t\tBinary: false,\n\t\t\tChannels: channels,\n\t\t},\n\t})\n\tconn.SetIdleTimeout(idleTimeout)\n\tnegotiatedProtocol, streams, err := conn.Open(responsewriter.GetOriginal(w), req)\n\tif err != nil {\n\t\truntime.HandleError(fmt.Errorf(\"unable to upgrade websocket connection: %v\", err))\n\t\treturn nil, false\n\t}\n\n\t// Send an empty message to the lowest writable channel to notify the client the connection is established\n\t// TODO: make generic to SPDY and WebSockets and do it outside of this method?\n\tswitch {\n\tcase opts.Stdout:\n\t\tstreams[stdoutChannel].Write([]byte{})\n\tcase opts.Stderr:\n\t\tstreams[stderrChannel].Write([]byte{})\n\tdefault:\n\t\tstreams[errorChannel].Write([]byte{})\n\t}\n\n\tctx := \u0026connectionContext{\n\t\tconn: conn,\n\t\tstdinStream: streams[stdinChannel],\n\t\tstdoutStream: streams[stdoutChannel],\n\t\tstderrStream: streams[stderrChannel],\n\t\ttty: opts.TTY,\n\t\tresizeStream: streams[resizeChannel],\n\t}\n\n\tswitch negotiatedProtocol {\n\tcase v4BinaryWebsocketProtocol, v4Base64WebsocketProtocol:\n\t\tctx.writeStatus = v4WriteStatusFunc(streams[errorChannel])\n\tdefault:\n\t\tctx.writeStatus = v1WriteStatusFunc(streams[errorChannel])\n\t}\n\n\treturn ctx, true\n}","line":{"from":71,"to":132}} {"id":100006521,"name":"newRequestCache","signature":"func newRequestCache() *requestCache","file":"pkg/kubelet/cri/streaming/request_cache.go","code":"func newRequestCache() *requestCache {\n\treturn \u0026requestCache{\n\t\tclock: clock.RealClock{},\n\t\tll: list.New(),\n\t\ttokens: make(map[string]*list.Element),\n\t}\n}","line":{"from":64,"to":70}} {"id":100006522,"name":"Insert","signature":"func (c *requestCache) Insert(req request) (token string, err error)","file":"pkg/kubelet/cri/streaming/request_cache.go","code":"// Insert the given request into the cache and returns the token used for fetching it out.\nfunc (c *requestCache) Insert(req request) (token string, err error) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\t// Remove expired entries.\n\tc.gc()\n\t// If the cache is full, reject the request.\n\tif c.ll.Len() == maxInFlight {\n\t\treturn \"\", NewErrorTooManyInFlight()\n\t}\n\ttoken, err = c.uniqueToken()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tele := c.ll.PushFront(\u0026cacheEntry{token, req, c.clock.Now().Add(cacheTTL)})\n\n\tc.tokens[token] = ele\n\treturn token, nil\n}","line":{"from":72,"to":91}} {"id":100006523,"name":"Consume","signature":"func (c *requestCache) Consume(token string) (req request, found bool)","file":"pkg/kubelet/cri/streaming/request_cache.go","code":"// Consume the token (remove it from the cache) and return the cached request, if found.\nfunc (c *requestCache) Consume(token string) (req request, found bool) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tele, ok := c.tokens[token]\n\tif !ok {\n\t\treturn nil, false\n\t}\n\tc.ll.Remove(ele)\n\tdelete(c.tokens, token)\n\n\tentry := ele.Value.(*cacheEntry)\n\tif c.clock.Now().After(entry.expireTime) {\n\t\t// Entry already expired.\n\t\treturn nil, false\n\t}\n\treturn entry.req, true\n}","line":{"from":93,"to":110}} {"id":100006524,"name":"uniqueToken","signature":"func (c *requestCache) uniqueToken() (string, error)","file":"pkg/kubelet/cri/streaming/request_cache.go","code":"// uniqueToken generates a random URL-safe token and ensures uniqueness.\nfunc (c *requestCache) uniqueToken() (string, error) {\n\tconst maxTries = 10\n\t// Number of bytes to be tokenLen when base64 encoded.\n\ttokenSize := math.Ceil(float64(tokenLen) * 6 / 8)\n\trawToken := make([]byte, int(tokenSize))\n\tfor i := 0; i \u003c maxTries; i++ {\n\t\tif _, err := rand.Read(rawToken); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tencoded := base64.RawURLEncoding.EncodeToString(rawToken)\n\t\ttoken := encoded[:tokenLen]\n\t\t// If it's unique, return it. Otherwise retry.\n\t\tif _, exists := c.tokens[encoded]; !exists {\n\t\t\treturn token, nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"failed to generate unique token\")\n}","line":{"from":112,"to":130}} {"id":100006525,"name":"gc","signature":"func (c *requestCache) gc()","file":"pkg/kubelet/cri/streaming/request_cache.go","code":"// Must be write-locked prior to calling.\nfunc (c *requestCache) gc() {\n\tnow := c.clock.Now()\n\tfor c.ll.Len() \u003e 0 {\n\t\toldest := c.ll.Back()\n\t\tentry := oldest.Value.(*cacheEntry)\n\t\tif !now.After(entry.expireTime) {\n\t\t\treturn\n\t\t}\n\n\t\t// Oldest value is expired; remove it.\n\t\tc.ll.Remove(oldest)\n\t\tdelete(c.tokens, entry.token)\n\t}\n}","line":{"from":132,"to":146}} {"id":100006526,"name":"NewServer","signature":"func NewServer(config Config, runtime Runtime) (Server, error)","file":"pkg/kubelet/cri/streaming/server.go","code":"// NewServer creates a new Server for stream requests.\n// TODO(tallclair): Add auth(n/z) interface \u0026 handling.\nfunc NewServer(config Config, runtime Runtime) (Server, error) {\n\ts := \u0026server{\n\t\tconfig: config,\n\t\truntime: \u0026criAdapter{runtime},\n\t\tcache: newRequestCache(),\n\t}\n\n\tif s.config.BaseURL == nil {\n\t\ts.config.BaseURL = \u0026url.URL{\n\t\t\tScheme: \"http\",\n\t\t\tHost: s.config.Addr,\n\t\t}\n\t\tif s.config.TLSConfig != nil {\n\t\t\ts.config.BaseURL.Scheme = \"https\"\n\t\t}\n\t}\n\n\tws := \u0026restful.WebService{}\n\tendpoints := []struct {\n\t\tpath string\n\t\thandler restful.RouteFunction\n\t}{\n\t\t{\"/exec/{token}\", s.serveExec},\n\t\t{\"/attach/{token}\", s.serveAttach},\n\t\t{\"/portforward/{token}\", s.servePortForward},\n\t}\n\t// If serving relative to a base path, set that here.\n\tpathPrefix := path.Dir(s.config.BaseURL.Path)\n\tfor _, e := range endpoints {\n\t\tfor _, method := range []string{\"GET\", \"POST\"} {\n\t\t\tws.Route(ws.\n\t\t\t\tMethod(method).\n\t\t\t\tPath(path.Join(pathPrefix, e.path)).\n\t\t\t\tTo(e.handler))\n\t\t}\n\t}\n\thandler := restful.NewContainer()\n\thandler.Add(ws)\n\ts.handler = handler\n\ts.server = \u0026http.Server{\n\t\tAddr: s.config.Addr,\n\t\tHandler: s.handler,\n\t\tTLSConfig: s.config.TLSConfig,\n\t}\n\n\treturn s, nil\n}","line":{"from":107,"to":155}} {"id":100006527,"name":"validateExecRequest","signature":"func validateExecRequest(req *runtimeapi.ExecRequest) error","file":"pkg/kubelet/cri/streaming/server.go","code":"func validateExecRequest(req *runtimeapi.ExecRequest) error {\n\tif req.ContainerId == \"\" {\n\t\treturn status.Errorf(codes.InvalidArgument, \"missing required container_id\")\n\t}\n\tif req.Tty \u0026\u0026 req.Stderr {\n\t\t// If TTY is set, stderr cannot be true because multiplexing is not\n\t\t// supported.\n\t\treturn status.Errorf(codes.InvalidArgument, \"tty and stderr cannot both be true\")\n\t}\n\tif !req.Stdin \u0026\u0026 !req.Stdout \u0026\u0026 !req.Stderr {\n\t\treturn status.Errorf(codes.InvalidArgument, \"one of stdin, stdout, or stderr must be set\")\n\t}\n\treturn nil\n}","line":{"from":165,"to":178}} {"id":100006528,"name":"GetExec","signature":"func (s *server) GetExec(req *runtimeapi.ExecRequest) (*runtimeapi.ExecResponse, error)","file":"pkg/kubelet/cri/streaming/server.go","code":"func (s *server) GetExec(req *runtimeapi.ExecRequest) (*runtimeapi.ExecResponse, error) {\n\tif err := validateExecRequest(req); err != nil {\n\t\treturn nil, err\n\t}\n\ttoken, err := s.cache.Insert(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026runtimeapi.ExecResponse{\n\t\tUrl: s.buildURL(\"exec\", token),\n\t}, nil\n}","line":{"from":180,"to":191}} {"id":100006529,"name":"validateAttachRequest","signature":"func validateAttachRequest(req *runtimeapi.AttachRequest) error","file":"pkg/kubelet/cri/streaming/server.go","code":"func validateAttachRequest(req *runtimeapi.AttachRequest) error {\n\tif req.ContainerId == \"\" {\n\t\treturn status.Errorf(codes.InvalidArgument, \"missing required container_id\")\n\t}\n\tif req.Tty \u0026\u0026 req.Stderr {\n\t\t// If TTY is set, stderr cannot be true because multiplexing is not\n\t\t// supported.\n\t\treturn status.Errorf(codes.InvalidArgument, \"tty and stderr cannot both be true\")\n\t}\n\tif !req.Stdin \u0026\u0026 !req.Stdout \u0026\u0026 !req.Stderr {\n\t\treturn status.Errorf(codes.InvalidArgument, \"one of stdin, stdout, and stderr must be set\")\n\t}\n\treturn nil\n}","line":{"from":193,"to":206}} {"id":100006530,"name":"GetAttach","signature":"func (s *server) GetAttach(req *runtimeapi.AttachRequest) (*runtimeapi.AttachResponse, error)","file":"pkg/kubelet/cri/streaming/server.go","code":"func (s *server) GetAttach(req *runtimeapi.AttachRequest) (*runtimeapi.AttachResponse, error) {\n\tif err := validateAttachRequest(req); err != nil {\n\t\treturn nil, err\n\t}\n\ttoken, err := s.cache.Insert(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026runtimeapi.AttachResponse{\n\t\tUrl: s.buildURL(\"attach\", token),\n\t}, nil\n}","line":{"from":208,"to":219}} {"id":100006531,"name":"GetPortForward","signature":"func (s *server) GetPortForward(req *runtimeapi.PortForwardRequest) (*runtimeapi.PortForwardResponse, error)","file":"pkg/kubelet/cri/streaming/server.go","code":"func (s *server) GetPortForward(req *runtimeapi.PortForwardRequest) (*runtimeapi.PortForwardResponse, error) {\n\tif req.PodSandboxId == \"\" {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"missing required pod_sandbox_id\")\n\t}\n\ttoken, err := s.cache.Insert(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026runtimeapi.PortForwardResponse{\n\t\tUrl: s.buildURL(\"portforward\", token),\n\t}, nil\n}","line":{"from":221,"to":232}} {"id":100006532,"name":"Start","signature":"func (s *server) Start(stayUp bool) error","file":"pkg/kubelet/cri/streaming/server.go","code":"func (s *server) Start(stayUp bool) error {\n\tif !stayUp {\n\t\t// TODO(tallclair): Implement this.\n\t\treturn errors.New(\"stayUp=false is not yet implemented\")\n\t}\n\n\tlistener, err := net.Listen(\"tcp\", s.config.Addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Use the actual address as baseURL host. This handles the \"0\" port case.\n\ts.config.BaseURL.Host = listener.Addr().String()\n\tif s.config.TLSConfig != nil {\n\t\treturn s.server.ServeTLS(listener, \"\", \"\") // Use certs from TLSConfig.\n\t}\n\treturn s.server.Serve(listener)\n}","line":{"from":234,"to":250}} {"id":100006533,"name":"Stop","signature":"func (s *server) Stop() error","file":"pkg/kubelet/cri/streaming/server.go","code":"func (s *server) Stop() error {\n\treturn s.server.Close()\n}","line":{"from":252,"to":254}} {"id":100006534,"name":"ServeHTTP","signature":"func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request)","file":"pkg/kubelet/cri/streaming/server.go","code":"func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ts.handler.ServeHTTP(w, r)\n}","line":{"from":256,"to":258}} {"id":100006535,"name":"buildURL","signature":"func (s *server) buildURL(method, token string) string","file":"pkg/kubelet/cri/streaming/server.go","code":"func (s *server) buildURL(method, token string) string {\n\treturn s.config.BaseURL.ResolveReference(\u0026url.URL{\n\t\tPath: path.Join(method, token),\n\t}).String()\n}","line":{"from":260,"to":264}} {"id":100006536,"name":"serveExec","signature":"func (s *server) serveExec(req *restful.Request, resp *restful.Response)","file":"pkg/kubelet/cri/streaming/server.go","code":"func (s *server) serveExec(req *restful.Request, resp *restful.Response) {\n\ttoken := req.PathParameter(\"token\")\n\tcachedRequest, ok := s.cache.Consume(token)\n\tif !ok {\n\t\thttp.NotFound(resp.ResponseWriter, req.Request)\n\t\treturn\n\t}\n\texec, ok := cachedRequest.(*runtimeapi.ExecRequest)\n\tif !ok {\n\t\thttp.NotFound(resp.ResponseWriter, req.Request)\n\t\treturn\n\t}\n\n\tstreamOpts := \u0026remotecommandserver.Options{\n\t\tStdin: exec.Stdin,\n\t\tStdout: exec.Stdout,\n\t\tStderr: exec.Stderr,\n\t\tTTY: exec.Tty,\n\t}\n\n\tremotecommandserver.ServeExec(\n\t\tresp.ResponseWriter,\n\t\treq.Request,\n\t\ts.runtime,\n\t\t\"\", // unused: podName\n\t\t\"\", // unusued: podUID\n\t\texec.ContainerId,\n\t\texec.Cmd,\n\t\tstreamOpts,\n\t\ts.config.StreamIdleTimeout,\n\t\ts.config.StreamCreationTimeout,\n\t\ts.config.SupportedRemoteCommandProtocols)\n}","line":{"from":266,"to":298}} {"id":100006537,"name":"serveAttach","signature":"func (s *server) serveAttach(req *restful.Request, resp *restful.Response)","file":"pkg/kubelet/cri/streaming/server.go","code":"func (s *server) serveAttach(req *restful.Request, resp *restful.Response) {\n\ttoken := req.PathParameter(\"token\")\n\tcachedRequest, ok := s.cache.Consume(token)\n\tif !ok {\n\t\thttp.NotFound(resp.ResponseWriter, req.Request)\n\t\treturn\n\t}\n\tattach, ok := cachedRequest.(*runtimeapi.AttachRequest)\n\tif !ok {\n\t\thttp.NotFound(resp.ResponseWriter, req.Request)\n\t\treturn\n\t}\n\n\tstreamOpts := \u0026remotecommandserver.Options{\n\t\tStdin: attach.Stdin,\n\t\tStdout: attach.Stdout,\n\t\tStderr: attach.Stderr,\n\t\tTTY: attach.Tty,\n\t}\n\tremotecommandserver.ServeAttach(\n\t\tresp.ResponseWriter,\n\t\treq.Request,\n\t\ts.runtime,\n\t\t\"\", // unused: podName\n\t\t\"\", // unusued: podUID\n\t\tattach.ContainerId,\n\t\tstreamOpts,\n\t\ts.config.StreamIdleTimeout,\n\t\ts.config.StreamCreationTimeout,\n\t\ts.config.SupportedRemoteCommandProtocols)\n}","line":{"from":300,"to":330}} {"id":100006538,"name":"servePortForward","signature":"func (s *server) servePortForward(req *restful.Request, resp *restful.Response)","file":"pkg/kubelet/cri/streaming/server.go","code":"func (s *server) servePortForward(req *restful.Request, resp *restful.Response) {\n\ttoken := req.PathParameter(\"token\")\n\tcachedRequest, ok := s.cache.Consume(token)\n\tif !ok {\n\t\thttp.NotFound(resp.ResponseWriter, req.Request)\n\t\treturn\n\t}\n\tpf, ok := cachedRequest.(*runtimeapi.PortForwardRequest)\n\tif !ok {\n\t\thttp.NotFound(resp.ResponseWriter, req.Request)\n\t\treturn\n\t}\n\n\tportForwardOptions, err := portforward.BuildV4Options(pf.Port)\n\tif err != nil {\n\t\tresp.WriteError(http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tportforward.ServePortForward(\n\t\tresp.ResponseWriter,\n\t\treq.Request,\n\t\ts.runtime,\n\t\tpf.PodSandboxId,\n\t\t\"\", // unused: podUID\n\t\tportForwardOptions,\n\t\ts.config.StreamIdleTimeout,\n\t\ts.config.StreamCreationTimeout,\n\t\ts.config.SupportedPortForwardProtocols)\n}","line":{"from":332,"to":361}} {"id":100006539,"name":"ExecInContainer","signature":"func (a *criAdapter) ExecInContainer(ctx context.Context, podName string, podUID types.UID, container string, cmd []string, in io.Reader, out, err io.WriteCloser, tty bool, resize \u003c-chan remotecommand.TerminalSize, timeout time.Duration) error","file":"pkg/kubelet/cri/streaming/server.go","code":"func (a *criAdapter) ExecInContainer(ctx context.Context, podName string, podUID types.UID, container string, cmd []string, in io.Reader, out, err io.WriteCloser, tty bool, resize \u003c-chan remotecommand.TerminalSize, timeout time.Duration) error {\n\treturn a.Runtime.Exec(ctx, container, cmd, in, out, err, tty, resize)\n}","line":{"from":373,"to":375}} {"id":100006540,"name":"AttachContainer","signature":"func (a *criAdapter) AttachContainer(ctx context.Context, podName string, podUID types.UID, container string, in io.Reader, out, err io.WriteCloser, tty bool, resize \u003c-chan remotecommand.TerminalSize) error","file":"pkg/kubelet/cri/streaming/server.go","code":"func (a *criAdapter) AttachContainer(ctx context.Context, podName string, podUID types.UID, container string, in io.Reader, out, err io.WriteCloser, tty bool, resize \u003c-chan remotecommand.TerminalSize) error {\n\treturn a.Runtime.Attach(ctx, container, in, out, err, tty, resize)\n}","line":{"from":377,"to":379}} {"id":100006541,"name":"PortForward","signature":"func (a *criAdapter) PortForward(ctx context.Context, podName string, podUID types.UID, port int32, stream io.ReadWriteCloser) error","file":"pkg/kubelet/cri/streaming/server.go","code":"func (a *criAdapter) PortForward(ctx context.Context, podName string, podUID types.UID, port int32, stream io.ReadWriteCloser) error {\n\treturn a.Runtime.PortForward(ctx, podName, port, stream)\n}","line":{"from":381,"to":383}} {"id":100006542,"name":"FromServices","signature":"func FromServices(services []*v1.Service) []v1.EnvVar","file":"pkg/kubelet/envvars/envvars.go","code":"// FromServices builds environment variables that a container is started with,\n// which tell the container where to find the services it may need, which are\n// provided as an argument.\nfunc FromServices(services []*v1.Service) []v1.EnvVar {\n\tvar result []v1.EnvVar\n\tfor i := range services {\n\t\tservice := services[i]\n\n\t\t// ignore services where ClusterIP is \"None\" or empty\n\t\t// the services passed to this method should be pre-filtered\n\t\t// only services that have the cluster IP set should be included here\n\t\tif !v1helper.IsServiceIPSet(service) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Host\n\t\tname := makeEnvVariableName(service.Name) + \"_SERVICE_HOST\"\n\t\tresult = append(result, v1.EnvVar{Name: name, Value: service.Spec.ClusterIP})\n\t\t// First port - give it the backwards-compatible name\n\t\tname = makeEnvVariableName(service.Name) + \"_SERVICE_PORT\"\n\t\tresult = append(result, v1.EnvVar{Name: name, Value: strconv.Itoa(int(service.Spec.Ports[0].Port))})\n\t\t// All named ports (only the first may be unnamed, checked in validation)\n\t\tfor i := range service.Spec.Ports {\n\t\t\tsp := \u0026service.Spec.Ports[i]\n\t\t\tif sp.Name != \"\" {\n\t\t\t\tpn := name + \"_\" + makeEnvVariableName(sp.Name)\n\t\t\t\tresult = append(result, v1.EnvVar{Name: pn, Value: strconv.Itoa(int(sp.Port))})\n\t\t\t}\n\t\t}\n\t\t// Docker-compatible vars.\n\t\tresult = append(result, makeLinkVariables(service)...)\n\t}\n\treturn result\n}","line":{"from":29,"to":62}} {"id":100006543,"name":"makeEnvVariableName","signature":"func makeEnvVariableName(str string) string","file":"pkg/kubelet/envvars/envvars.go","code":"func makeEnvVariableName(str string) string {\n\t// TODO: If we simplify to \"all names are DNS1123Subdomains\" this\n\t// will need two tweaks:\n\t// 1) Handle leading digits\n\t// 2) Handle dots\n\treturn strings.ToUpper(strings.Replace(str, \"-\", \"_\", -1))\n}","line":{"from":64,"to":70}} {"id":100006544,"name":"makeLinkVariables","signature":"func makeLinkVariables(service *v1.Service) []v1.EnvVar","file":"pkg/kubelet/envvars/envvars.go","code":"func makeLinkVariables(service *v1.Service) []v1.EnvVar {\n\tprefix := makeEnvVariableName(service.Name)\n\tall := []v1.EnvVar{}\n\tfor i := range service.Spec.Ports {\n\t\tsp := \u0026service.Spec.Ports[i]\n\n\t\tprotocol := string(v1.ProtocolTCP)\n\t\tif sp.Protocol != \"\" {\n\t\t\tprotocol = string(sp.Protocol)\n\t\t}\n\n\t\thostPort := net.JoinHostPort(service.Spec.ClusterIP, strconv.Itoa(int(sp.Port)))\n\n\t\tif i == 0 {\n\t\t\t// Docker special-cases the first port.\n\t\t\tall = append(all, v1.EnvVar{\n\t\t\t\tName: prefix + \"_PORT\",\n\t\t\t\tValue: fmt.Sprintf(\"%s://%s\", strings.ToLower(protocol), hostPort),\n\t\t\t})\n\t\t}\n\t\tportPrefix := fmt.Sprintf(\"%s_PORT_%d_%s\", prefix, sp.Port, strings.ToUpper(protocol))\n\t\tall = append(all, []v1.EnvVar{\n\t\t\t{\n\t\t\t\tName: portPrefix,\n\t\t\t\tValue: fmt.Sprintf(\"%s://%s\", strings.ToLower(protocol), hostPort),\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: portPrefix + \"_PROTO\",\n\t\t\t\tValue: strings.ToLower(protocol),\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: portPrefix + \"_PORT\",\n\t\t\t\tValue: strconv.Itoa(int(sp.Port)),\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: portPrefix + \"_ADDR\",\n\t\t\t\tValue: service.Spec.ClusterIP,\n\t\t\t},\n\t\t}...)\n\t}\n\treturn all\n}","line":{"from":72,"to":113}} {"id":100006545,"name":"GetThresholdQuantity","signature":"func GetThresholdQuantity(value ThresholdValue, capacity *resource.Quantity) *resource.Quantity","file":"pkg/kubelet/eviction/api/types.go","code":"// GetThresholdQuantity returns the expected quantity value for a thresholdValue\nfunc GetThresholdQuantity(value ThresholdValue, capacity *resource.Quantity) *resource.Quantity {\n\tif value.Quantity != nil {\n\t\tres := value.Quantity.DeepCopy()\n\t\treturn \u0026res\n\t}\n\treturn resource.NewQuantity(int64(float64(capacity.Value())*float64(value.Percentage)), resource.BinarySI)\n}","line":{"from":94,"to":101}} {"id":100006546,"name":"NewManager","signature":"func NewManager(","file":"pkg/kubelet/eviction/eviction_manager.go","code":"// NewManager returns a configured Manager and an associated admission handler to enforce eviction configuration.\nfunc NewManager(\n\tsummaryProvider stats.SummaryProvider,\n\tconfig Config,\n\tkillPodFunc KillPodFunc,\n\tmirrorPodFunc MirrorPodFunc,\n\timageGC ImageGC,\n\tcontainerGC ContainerGC,\n\trecorder record.EventRecorder,\n\tnodeRef *v1.ObjectReference,\n\tclock clock.WithTicker,\n\tlocalStorageCapacityIsolation bool,\n) (Manager, lifecycle.PodAdmitHandler) {\n\tmanager := \u0026managerImpl{\n\t\tclock: clock,\n\t\tkillPodFunc: killPodFunc,\n\t\tmirrorPodFunc: mirrorPodFunc,\n\t\timageGC: imageGC,\n\t\tcontainerGC: containerGC,\n\t\tconfig: config,\n\t\trecorder: recorder,\n\t\tsummaryProvider: summaryProvider,\n\t\tnodeRef: nodeRef,\n\t\tnodeConditionsLastObservedAt: nodeConditionsObservedAt{},\n\t\tthresholdsFirstObservedAt: thresholdsObservedAt{},\n\t\tdedicatedImageFs: nil,\n\t\tthresholdNotifiers: []ThresholdNotifier{},\n\t\tlocalStorageCapacityIsolation: localStorageCapacityIsolation,\n\t}\n\treturn manager, manager\n}","line":{"from":110,"to":140}} {"id":100006547,"name":"Admit","signature":"func (m *managerImpl) Admit(attrs *lifecycle.PodAdmitAttributes) lifecycle.PodAdmitResult","file":"pkg/kubelet/eviction/eviction_manager.go","code":"// Admit rejects a pod if its not safe to admit for node stability.\nfunc (m *managerImpl) Admit(attrs *lifecycle.PodAdmitAttributes) lifecycle.PodAdmitResult {\n\tm.RLock()\n\tdefer m.RUnlock()\n\tif len(m.nodeConditions) == 0 {\n\t\treturn lifecycle.PodAdmitResult{Admit: true}\n\t}\n\t// Admit Critical pods even under resource pressure since they are required for system stability.\n\t// https://github.com/kubernetes/kubernetes/issues/40573 has more details.\n\tif kubelettypes.IsCriticalPod(attrs.Pod) {\n\t\treturn lifecycle.PodAdmitResult{Admit: true}\n\t}\n\n\t// Conditions other than memory pressure reject all pods\n\tnodeOnlyHasMemoryPressureCondition := hasNodeCondition(m.nodeConditions, v1.NodeMemoryPressure) \u0026\u0026 len(m.nodeConditions) == 1\n\tif nodeOnlyHasMemoryPressureCondition {\n\t\tnotBestEffort := v1.PodQOSBestEffort != v1qos.GetPodQOS(attrs.Pod)\n\t\tif notBestEffort {\n\t\t\treturn lifecycle.PodAdmitResult{Admit: true}\n\t\t}\n\n\t\t// When node has memory pressure, check BestEffort Pod's toleration:\n\t\t// admit it if tolerates memory pressure taint, fail for other tolerations, e.g. DiskPressure.\n\t\tif corev1helpers.TolerationsTolerateTaint(attrs.Pod.Spec.Tolerations, \u0026v1.Taint{\n\t\t\tKey: v1.TaintNodeMemoryPressure,\n\t\t\tEffect: v1.TaintEffectNoSchedule,\n\t\t}) {\n\t\t\treturn lifecycle.PodAdmitResult{Admit: true}\n\t\t}\n\t}\n\n\t// reject pods when under memory pressure (if pod is best effort), or if under disk pressure.\n\tklog.InfoS(\"Failed to admit pod to node\", \"pod\", klog.KObj(attrs.Pod), \"nodeCondition\", m.nodeConditions)\n\treturn lifecycle.PodAdmitResult{\n\t\tAdmit: false,\n\t\tReason: Reason,\n\t\tMessage: fmt.Sprintf(nodeConditionMessageFmt, m.nodeConditions),\n\t}\n}","line":{"from":142,"to":180}} {"id":100006548,"name":"Start","signature":"func (m *managerImpl) Start(diskInfoProvider DiskInfoProvider, podFunc ActivePodsFunc, podCleanedUpFunc PodCleanedUpFunc, monitoringInterval time.Duration)","file":"pkg/kubelet/eviction/eviction_manager.go","code":"// Start starts the control loop to observe and response to low compute resources.\nfunc (m *managerImpl) Start(diskInfoProvider DiskInfoProvider, podFunc ActivePodsFunc, podCleanedUpFunc PodCleanedUpFunc, monitoringInterval time.Duration) {\n\tthresholdHandler := func(message string) {\n\t\tklog.InfoS(message)\n\t\tm.synchronize(diskInfoProvider, podFunc)\n\t}\n\tif m.config.KernelMemcgNotification {\n\t\tfor _, threshold := range m.config.Thresholds {\n\t\t\tif threshold.Signal == evictionapi.SignalMemoryAvailable || threshold.Signal == evictionapi.SignalAllocatableMemoryAvailable {\n\t\t\t\tnotifier, err := NewMemoryThresholdNotifier(threshold, m.config.PodCgroupRoot, \u0026CgroupNotifierFactory{}, thresholdHandler)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.InfoS(\"Eviction manager: failed to create memory threshold notifier\", \"err\", err)\n\t\t\t\t} else {\n\t\t\t\t\tgo notifier.Start()\n\t\t\t\t\tm.thresholdNotifiers = append(m.thresholdNotifiers, notifier)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// start the eviction manager monitoring\n\tgo func() {\n\t\tfor {\n\t\t\tif evictedPods := m.synchronize(diskInfoProvider, podFunc); evictedPods != nil {\n\t\t\t\tklog.InfoS(\"Eviction manager: pods evicted, waiting for pod to be cleaned up\", \"pods\", klog.KObjSlice(evictedPods))\n\t\t\t\tm.waitForPodsCleanup(podCleanedUpFunc, evictedPods)\n\t\t\t} else {\n\t\t\t\ttime.Sleep(monitoringInterval)\n\t\t\t}\n\t\t}\n\t}()\n}","line":{"from":182,"to":212}} {"id":100006549,"name":"IsUnderMemoryPressure","signature":"func (m *managerImpl) IsUnderMemoryPressure() bool","file":"pkg/kubelet/eviction/eviction_manager.go","code":"// IsUnderMemoryPressure returns true if the node is under memory pressure.\nfunc (m *managerImpl) IsUnderMemoryPressure() bool {\n\tm.RLock()\n\tdefer m.RUnlock()\n\treturn hasNodeCondition(m.nodeConditions, v1.NodeMemoryPressure)\n}","line":{"from":214,"to":219}} {"id":100006550,"name":"IsUnderDiskPressure","signature":"func (m *managerImpl) IsUnderDiskPressure() bool","file":"pkg/kubelet/eviction/eviction_manager.go","code":"// IsUnderDiskPressure returns true if the node is under disk pressure.\nfunc (m *managerImpl) IsUnderDiskPressure() bool {\n\tm.RLock()\n\tdefer m.RUnlock()\n\treturn hasNodeCondition(m.nodeConditions, v1.NodeDiskPressure)\n}","line":{"from":221,"to":226}} {"id":100006551,"name":"IsUnderPIDPressure","signature":"func (m *managerImpl) IsUnderPIDPressure() bool","file":"pkg/kubelet/eviction/eviction_manager.go","code":"// IsUnderPIDPressure returns true if the node is under PID pressure.\nfunc (m *managerImpl) IsUnderPIDPressure() bool {\n\tm.RLock()\n\tdefer m.RUnlock()\n\treturn hasNodeCondition(m.nodeConditions, v1.NodePIDPressure)\n}","line":{"from":228,"to":233}} {"id":100006552,"name":"synchronize","signature":"func (m *managerImpl) synchronize(diskInfoProvider DiskInfoProvider, podFunc ActivePodsFunc) []*v1.Pod","file":"pkg/kubelet/eviction/eviction_manager.go","code":"// synchronize is the main control loop that enforces eviction thresholds.\n// Returns the pod that was killed, or nil if no pod was killed.\nfunc (m *managerImpl) synchronize(diskInfoProvider DiskInfoProvider, podFunc ActivePodsFunc) []*v1.Pod {\n\tctx := context.Background()\n\t// if we have nothing to do, just return\n\tthresholds := m.config.Thresholds\n\tif len(thresholds) == 0 \u0026\u0026 !m.localStorageCapacityIsolation {\n\t\treturn nil\n\t}\n\n\tklog.V(3).InfoS(\"Eviction manager: synchronize housekeeping\")\n\t// build the ranking functions (if not yet known)\n\t// TODO: have a function in cadvisor that lets us know if global housekeeping has completed\n\tif m.dedicatedImageFs == nil {\n\t\thasImageFs, ok := diskInfoProvider.HasDedicatedImageFs(ctx)\n\t\tif ok != nil {\n\t\t\treturn nil\n\t\t}\n\t\tm.dedicatedImageFs = \u0026hasImageFs\n\t\tm.signalToRankFunc = buildSignalToRankFunc(hasImageFs)\n\t\tm.signalToNodeReclaimFuncs = buildSignalToNodeReclaimFuncs(m.imageGC, m.containerGC, hasImageFs)\n\t}\n\n\tactivePods := podFunc()\n\tupdateStats := true\n\tsummary, err := m.summaryProvider.Get(ctx, updateStats)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Eviction manager: failed to get summary stats\")\n\t\treturn nil\n\t}\n\n\tif m.clock.Since(m.thresholdsLastUpdated) \u003e notifierRefreshInterval {\n\t\tm.thresholdsLastUpdated = m.clock.Now()\n\t\tfor _, notifier := range m.thresholdNotifiers {\n\t\t\tif err := notifier.UpdateThreshold(summary); err != nil {\n\t\t\t\tklog.InfoS(\"Eviction manager: failed to update notifier\", \"notifier\", notifier.Description(), \"err\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\t// make observations and get a function to derive pod usage stats relative to those observations.\n\tobservations, statsFunc := makeSignalObservations(summary)\n\tdebugLogObservations(\"observations\", observations)\n\n\t// determine the set of thresholds met independent of grace period\n\tthresholds = thresholdsMet(thresholds, observations, false)\n\tdebugLogThresholdsWithObservation(\"thresholds - ignoring grace period\", thresholds, observations)\n\n\t// determine the set of thresholds previously met that have not yet satisfied the associated min-reclaim\n\tif len(m.thresholdsMet) \u003e 0 {\n\t\tthresholdsNotYetResolved := thresholdsMet(m.thresholdsMet, observations, true)\n\t\tthresholds = mergeThresholds(thresholds, thresholdsNotYetResolved)\n\t}\n\tdebugLogThresholdsWithObservation(\"thresholds - reclaim not satisfied\", thresholds, observations)\n\n\t// track when a threshold was first observed\n\tnow := m.clock.Now()\n\tthresholdsFirstObservedAt := thresholdsFirstObservedAt(thresholds, m.thresholdsFirstObservedAt, now)\n\n\t// the set of node conditions that are triggered by currently observed thresholds\n\tnodeConditions := nodeConditions(thresholds)\n\tif len(nodeConditions) \u003e 0 {\n\t\tklog.V(3).InfoS(\"Eviction manager: node conditions - observed\", \"nodeCondition\", nodeConditions)\n\t}\n\n\t// track when a node condition was last observed\n\tnodeConditionsLastObservedAt := nodeConditionsLastObservedAt(nodeConditions, m.nodeConditionsLastObservedAt, now)\n\n\t// node conditions report true if it has been observed within the transition period window\n\tnodeConditions = nodeConditionsObservedSince(nodeConditionsLastObservedAt, m.config.PressureTransitionPeriod, now)\n\tif len(nodeConditions) \u003e 0 {\n\t\tklog.V(3).InfoS(\"Eviction manager: node conditions - transition period not met\", \"nodeCondition\", nodeConditions)\n\t}\n\n\t// determine the set of thresholds we need to drive eviction behavior (i.e. all grace periods are met)\n\tthresholds = thresholdsMetGracePeriod(thresholdsFirstObservedAt, now)\n\tdebugLogThresholdsWithObservation(\"thresholds - grace periods satisfied\", thresholds, observations)\n\n\t// update internal state\n\tm.Lock()\n\tm.nodeConditions = nodeConditions\n\tm.thresholdsFirstObservedAt = thresholdsFirstObservedAt\n\tm.nodeConditionsLastObservedAt = nodeConditionsLastObservedAt\n\tm.thresholdsMet = thresholds\n\n\t// determine the set of thresholds whose stats have been updated since the last sync\n\tthresholds = thresholdsUpdatedStats(thresholds, observations, m.lastObservations)\n\tdebugLogThresholdsWithObservation(\"thresholds - updated stats\", thresholds, observations)\n\n\tm.lastObservations = observations\n\tm.Unlock()\n\n\t// evict pods if there is a resource usage violation from local volume temporary storage\n\t// If eviction happens in localStorageEviction function, skip the rest of eviction action\n\tif m.localStorageCapacityIsolation {\n\t\tif evictedPods := m.localStorageEviction(activePods, statsFunc); len(evictedPods) \u003e 0 {\n\t\t\treturn evictedPods\n\t\t}\n\t}\n\n\tif len(thresholds) == 0 {\n\t\tklog.V(3).InfoS(\"Eviction manager: no resources are starved\")\n\t\treturn nil\n\t}\n\n\t// rank the thresholds by eviction priority\n\tsort.Sort(byEvictionPriority(thresholds))\n\tthresholdToReclaim, resourceToReclaim, foundAny := getReclaimableThreshold(thresholds)\n\tif !foundAny {\n\t\treturn nil\n\t}\n\tklog.InfoS(\"Eviction manager: attempting to reclaim\", \"resourceName\", resourceToReclaim)\n\n\t// record an event about the resources we are now attempting to reclaim via eviction\n\tm.recorder.Eventf(m.nodeRef, v1.EventTypeWarning, \"EvictionThresholdMet\", \"Attempting to reclaim %s\", resourceToReclaim)\n\n\t// check if there are node-level resources we can reclaim to reduce pressure before evicting end-user pods.\n\tif m.reclaimNodeLevelResources(ctx, thresholdToReclaim.Signal, resourceToReclaim) {\n\t\tklog.InfoS(\"Eviction manager: able to reduce resource pressure without evicting pods.\", \"resourceName\", resourceToReclaim)\n\t\treturn nil\n\t}\n\n\tklog.InfoS(\"Eviction manager: must evict pod(s) to reclaim\", \"resourceName\", resourceToReclaim)\n\n\t// rank the pods for eviction\n\trank, ok := m.signalToRankFunc[thresholdToReclaim.Signal]\n\tif !ok {\n\t\tklog.ErrorS(nil, \"Eviction manager: no ranking function for signal\", \"threshold\", thresholdToReclaim.Signal)\n\t\treturn nil\n\t}\n\n\t// the only candidates viable for eviction are those pods that had anything running.\n\tif len(activePods) == 0 {\n\t\tklog.ErrorS(nil, \"Eviction manager: eviction thresholds have been met, but no pods are active to evict\")\n\t\treturn nil\n\t}\n\n\t// rank the running pods for eviction for the specified resource\n\trank(activePods, statsFunc)\n\n\tklog.InfoS(\"Eviction manager: pods ranked for eviction\", \"pods\", klog.KObjSlice(activePods))\n\n\t//record age of metrics for met thresholds that we are using for evictions.\n\tfor _, t := range thresholds {\n\t\ttimeObserved := observations[t.Signal].time\n\t\tif !timeObserved.IsZero() {\n\t\t\tmetrics.EvictionStatsAge.WithLabelValues(string(t.Signal)).Observe(metrics.SinceInSeconds(timeObserved.Time))\n\t\t}\n\t}\n\n\t// we kill at most a single pod during each eviction interval\n\tfor i := range activePods {\n\t\tpod := activePods[i]\n\t\tgracePeriodOverride := int64(0)\n\t\tif !isHardEvictionThreshold(thresholdToReclaim) {\n\t\t\tgracePeriodOverride = m.config.MaxPodGracePeriodSeconds\n\t\t}\n\t\tmessage, annotations := evictionMessage(resourceToReclaim, pod, statsFunc, thresholds, observations)\n\t\tvar condition *v1.PodCondition\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.PodDisruptionConditions) {\n\t\t\tcondition = \u0026v1.PodCondition{\n\t\t\t\tType: v1.DisruptionTarget,\n\t\t\t\tStatus: v1.ConditionTrue,\n\t\t\t\tReason: v1.PodReasonTerminationByKubelet,\n\t\t\t\tMessage: message,\n\t\t\t}\n\t\t}\n\t\tif m.evictPod(pod, gracePeriodOverride, message, annotations, condition) {\n\t\t\tmetrics.Evictions.WithLabelValues(string(thresholdToReclaim.Signal)).Inc()\n\t\t\treturn []*v1.Pod{pod}\n\t\t}\n\t}\n\tklog.InfoS(\"Eviction manager: unable to evict any pods from the node\")\n\treturn nil\n}","line":{"from":235,"to":409}} {"id":100006553,"name":"waitForPodsCleanup","signature":"func (m *managerImpl) waitForPodsCleanup(podCleanedUpFunc PodCleanedUpFunc, pods []*v1.Pod)","file":"pkg/kubelet/eviction/eviction_manager.go","code":"func (m *managerImpl) waitForPodsCleanup(podCleanedUpFunc PodCleanedUpFunc, pods []*v1.Pod) {\n\ttimeout := m.clock.NewTimer(podCleanupTimeout)\n\tdefer timeout.Stop()\n\tticker := m.clock.NewTicker(podCleanupPollFreq)\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase \u003c-timeout.C():\n\t\t\tklog.InfoS(\"Eviction manager: timed out waiting for pods to be cleaned up\", \"pods\", klog.KObjSlice(pods))\n\t\t\treturn\n\t\tcase \u003c-ticker.C():\n\t\t\tfor i, pod := range pods {\n\t\t\t\tif !podCleanedUpFunc(pod) {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif i == len(pods)-1 {\n\t\t\t\t\tklog.InfoS(\"Eviction manager: pods successfully cleaned up\", \"pods\", klog.KObjSlice(pods))\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":411,"to":433}} {"id":100006554,"name":"reclaimNodeLevelResources","signature":"func (m *managerImpl) reclaimNodeLevelResources(ctx context.Context, signalToReclaim evictionapi.Signal, resourceToReclaim v1.ResourceName) bool","file":"pkg/kubelet/eviction/eviction_manager.go","code":"// reclaimNodeLevelResources attempts to reclaim node level resources. returns true if thresholds were satisfied and no pod eviction is required.\nfunc (m *managerImpl) reclaimNodeLevelResources(ctx context.Context, signalToReclaim evictionapi.Signal, resourceToReclaim v1.ResourceName) bool {\n\tnodeReclaimFuncs := m.signalToNodeReclaimFuncs[signalToReclaim]\n\tfor _, nodeReclaimFunc := range nodeReclaimFuncs {\n\t\t// attempt to reclaim the pressured resource.\n\t\tif err := nodeReclaimFunc(ctx); err != nil {\n\t\t\tklog.InfoS(\"Eviction manager: unexpected error when attempting to reduce resource pressure\", \"resourceName\", resourceToReclaim, \"err\", err)\n\t\t}\n\n\t}\n\tif len(nodeReclaimFuncs) \u003e 0 {\n\t\tsummary, err := m.summaryProvider.Get(ctx, true)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Eviction manager: failed to get summary stats after resource reclaim\")\n\t\t\treturn false\n\t\t}\n\n\t\t// make observations and get a function to derive pod usage stats relative to those observations.\n\t\tobservations, _ := makeSignalObservations(summary)\n\t\tdebugLogObservations(\"observations after resource reclaim\", observations)\n\n\t\t// evaluate all thresholds independently of their grace period to see if with\n\t\t// the new observations, we think we have met min reclaim goals\n\t\tthresholds := thresholdsMet(m.config.Thresholds, observations, true)\n\t\tdebugLogThresholdsWithObservation(\"thresholds after resource reclaim - ignoring grace period\", thresholds, observations)\n\n\t\tif len(thresholds) == 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":435,"to":466}} {"id":100006555,"name":"localStorageEviction","signature":"func (m *managerImpl) localStorageEviction(pods []*v1.Pod, statsFunc statsFunc) []*v1.Pod","file":"pkg/kubelet/eviction/eviction_manager.go","code":"// localStorageEviction checks the EmptyDir volume usage for each pod and determine whether it exceeds the specified limit and needs\n// to be evicted. It also checks every container in the pod, if the container overlay usage exceeds the limit, the pod will be evicted too.\nfunc (m *managerImpl) localStorageEviction(pods []*v1.Pod, statsFunc statsFunc) []*v1.Pod {\n\tevicted := []*v1.Pod{}\n\tfor _, pod := range pods {\n\t\tpodStats, ok := statsFunc(pod)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tif m.emptyDirLimitEviction(podStats, pod) {\n\t\t\tevicted = append(evicted, pod)\n\t\t\tcontinue\n\t\t}\n\n\t\tif m.podEphemeralStorageLimitEviction(podStats, pod) {\n\t\t\tevicted = append(evicted, pod)\n\t\t\tcontinue\n\t\t}\n\n\t\tif m.containerEphemeralStorageLimitEviction(podStats, pod) {\n\t\t\tevicted = append(evicted, pod)\n\t\t}\n\t}\n\n\treturn evicted\n}","line":{"from":468,"to":494}} {"id":100006556,"name":"emptyDirLimitEviction","signature":"func (m *managerImpl) emptyDirLimitEviction(podStats statsapi.PodStats, pod *v1.Pod) bool","file":"pkg/kubelet/eviction/eviction_manager.go","code":"func (m *managerImpl) emptyDirLimitEviction(podStats statsapi.PodStats, pod *v1.Pod) bool {\n\tpodVolumeUsed := make(map[string]*resource.Quantity)\n\tfor _, volume := range podStats.VolumeStats {\n\t\tpodVolumeUsed[volume.Name] = resource.NewQuantity(int64(*volume.UsedBytes), resource.BinarySI)\n\t}\n\tfor i := range pod.Spec.Volumes {\n\t\tsource := \u0026pod.Spec.Volumes[i].VolumeSource\n\t\tif source.EmptyDir != nil {\n\t\t\tsize := source.EmptyDir.SizeLimit\n\t\t\tused := podVolumeUsed[pod.Spec.Volumes[i].Name]\n\t\t\tif used != nil \u0026\u0026 size != nil \u0026\u0026 size.Sign() == 1 \u0026\u0026 used.Cmp(*size) \u003e 0 {\n\t\t\t\t// the emptyDir usage exceeds the size limit, evict the pod\n\t\t\t\tif m.evictPod(pod, 0, fmt.Sprintf(emptyDirMessageFmt, pod.Spec.Volumes[i].Name, size.String()), nil, nil) {\n\t\t\t\t\tmetrics.Evictions.WithLabelValues(signalEmptyDirFsLimit).Inc()\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":496,"to":518}} {"id":100006557,"name":"podEphemeralStorageLimitEviction","signature":"func (m *managerImpl) podEphemeralStorageLimitEviction(podStats statsapi.PodStats, pod *v1.Pod) bool","file":"pkg/kubelet/eviction/eviction_manager.go","code":"func (m *managerImpl) podEphemeralStorageLimitEviction(podStats statsapi.PodStats, pod *v1.Pod) bool {\n\tpodLimits := resourcehelper.PodLimits(pod, resourcehelper.PodResourcesOptions{})\n\t_, found := podLimits[v1.ResourceEphemeralStorage]\n\tif !found {\n\t\treturn false\n\t}\n\n\t// pod stats api summarizes ephemeral storage usage (container, emptyDir, host[etc-hosts, logs])\n\tpodEphemeralStorageTotalUsage := \u0026resource.Quantity{}\n\tif podStats.EphemeralStorage != nil \u0026\u0026 podStats.EphemeralStorage.UsedBytes != nil {\n\t\tpodEphemeralStorageTotalUsage = resource.NewQuantity(int64(*podStats.EphemeralStorage.UsedBytes), resource.BinarySI)\n\t}\n\tpodEphemeralStorageLimit := podLimits[v1.ResourceEphemeralStorage]\n\tif podEphemeralStorageTotalUsage.Cmp(podEphemeralStorageLimit) \u003e 0 {\n\t\t// the total usage of pod exceeds the total size limit of containers, evict the pod\n\t\tmessage := fmt.Sprintf(podEphemeralStorageMessageFmt, podEphemeralStorageLimit.String())\n\t\tif m.evictPod(pod, 0, message, nil, nil) {\n\t\t\tmetrics.Evictions.WithLabelValues(signalEphemeralPodFsLimit).Inc()\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\treturn false\n}","line":{"from":520,"to":543}} {"id":100006558,"name":"containerEphemeralStorageLimitEviction","signature":"func (m *managerImpl) containerEphemeralStorageLimitEviction(podStats statsapi.PodStats, pod *v1.Pod) bool","file":"pkg/kubelet/eviction/eviction_manager.go","code":"func (m *managerImpl) containerEphemeralStorageLimitEviction(podStats statsapi.PodStats, pod *v1.Pod) bool {\n\tthresholdsMap := make(map[string]*resource.Quantity)\n\tfor _, container := range pod.Spec.Containers {\n\t\tephemeralLimit := container.Resources.Limits.StorageEphemeral()\n\t\tif ephemeralLimit != nil \u0026\u0026 ephemeralLimit.Value() != 0 {\n\t\t\tthresholdsMap[container.Name] = ephemeralLimit\n\t\t}\n\t}\n\n\tfor _, containerStat := range podStats.Containers {\n\t\tcontainerUsed := diskUsage(containerStat.Logs)\n\t\tif !*m.dedicatedImageFs {\n\t\t\tcontainerUsed.Add(*diskUsage(containerStat.Rootfs))\n\t\t}\n\n\t\tif ephemeralStorageThreshold, ok := thresholdsMap[containerStat.Name]; ok {\n\t\t\tif ephemeralStorageThreshold.Cmp(*containerUsed) \u003c 0 {\n\t\t\t\tif m.evictPod(pod, 0, fmt.Sprintf(containerEphemeralStorageMessageFmt, containerStat.Name, ephemeralStorageThreshold.String()), nil, nil) {\n\t\t\t\t\tmetrics.Evictions.WithLabelValues(signalEphemeralContainerFsLimit).Inc()\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":545,"to":571}} {"id":100006559,"name":"evictPod","signature":"func (m *managerImpl) evictPod(pod *v1.Pod, gracePeriodOverride int64, evictMsg string, annotations map[string]string, condition *v1.PodCondition) bool","file":"pkg/kubelet/eviction/eviction_manager.go","code":"func (m *managerImpl) evictPod(pod *v1.Pod, gracePeriodOverride int64, evictMsg string, annotations map[string]string, condition *v1.PodCondition) bool {\n\t// If the pod is marked as critical and static, and support for critical pod annotations is enabled,\n\t// do not evict such pods. Static pods are not re-admitted after evictions.\n\t// https://github.com/kubernetes/kubernetes/issues/40573 has more details.\n\tif kubelettypes.IsCriticalPod(pod) {\n\t\tklog.ErrorS(nil, \"Eviction manager: cannot evict a critical pod\", \"pod\", klog.KObj(pod))\n\t\treturn false\n\t}\n\t// record that we are evicting the pod\n\tm.recorder.AnnotatedEventf(pod, annotations, v1.EventTypeWarning, Reason, evictMsg)\n\t// this is a blocking call and should only return when the pod and its containers are killed.\n\tklog.V(3).InfoS(\"Evicting pod\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID, \"message\", evictMsg)\n\terr := m.killPodFunc(pod, true, \u0026gracePeriodOverride, func(status *v1.PodStatus) {\n\t\tstatus.Phase = v1.PodFailed\n\t\tstatus.Reason = Reason\n\t\tstatus.Message = evictMsg\n\t\tif condition != nil {\n\t\t\tpodutil.UpdatePodCondition(status, condition)\n\t\t}\n\t})\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Eviction manager: pod failed to evict\", \"pod\", klog.KObj(pod))\n\t} else {\n\t\tklog.InfoS(\"Eviction manager: pod is evicted successfully\", \"pod\", klog.KObj(pod))\n\t}\n\treturn true\n}","line":{"from":573,"to":599}} {"id":100006560,"name":"init","signature":"func init()","file":"pkg/kubelet/eviction/helpers.go","code":"func init() {\n\t// map eviction signals to node conditions\n\tsignalToNodeCondition = map[evictionapi.Signal]v1.NodeConditionType{}\n\tsignalToNodeCondition[evictionapi.SignalMemoryAvailable] = v1.NodeMemoryPressure\n\tsignalToNodeCondition[evictionapi.SignalAllocatableMemoryAvailable] = v1.NodeMemoryPressure\n\tsignalToNodeCondition[evictionapi.SignalImageFsAvailable] = v1.NodeDiskPressure\n\tsignalToNodeCondition[evictionapi.SignalNodeFsAvailable] = v1.NodeDiskPressure\n\tsignalToNodeCondition[evictionapi.SignalImageFsInodesFree] = v1.NodeDiskPressure\n\tsignalToNodeCondition[evictionapi.SignalNodeFsInodesFree] = v1.NodeDiskPressure\n\tsignalToNodeCondition[evictionapi.SignalPIDAvailable] = v1.NodePIDPressure\n\n\t// map signals to resources (and vice-versa)\n\tsignalToResource = map[evictionapi.Signal]v1.ResourceName{}\n\tsignalToResource[evictionapi.SignalMemoryAvailable] = v1.ResourceMemory\n\tsignalToResource[evictionapi.SignalAllocatableMemoryAvailable] = v1.ResourceMemory\n\tsignalToResource[evictionapi.SignalImageFsAvailable] = v1.ResourceEphemeralStorage\n\tsignalToResource[evictionapi.SignalImageFsInodesFree] = resourceInodes\n\tsignalToResource[evictionapi.SignalNodeFsAvailable] = v1.ResourceEphemeralStorage\n\tsignalToResource[evictionapi.SignalNodeFsInodesFree] = resourceInodes\n\tsignalToResource[evictionapi.SignalPIDAvailable] = resourcePids\n}","line":{"from":77,"to":97}} {"id":100006561,"name":"validSignal","signature":"func validSignal(signal evictionapi.Signal) bool","file":"pkg/kubelet/eviction/helpers.go","code":"// validSignal returns true if the signal is supported.\nfunc validSignal(signal evictionapi.Signal) bool {\n\t_, found := signalToResource[signal]\n\treturn found\n}","line":{"from":99,"to":103}} {"id":100006562,"name":"getReclaimableThreshold","signature":"func getReclaimableThreshold(thresholds []evictionapi.Threshold) (evictionapi.Threshold, v1.ResourceName, bool)","file":"pkg/kubelet/eviction/helpers.go","code":"// getReclaimableThreshold finds the threshold and resource to reclaim\nfunc getReclaimableThreshold(thresholds []evictionapi.Threshold) (evictionapi.Threshold, v1.ResourceName, bool) {\n\tfor _, thresholdToReclaim := range thresholds {\n\t\tif resourceToReclaim, ok := signalToResource[thresholdToReclaim.Signal]; ok {\n\t\t\treturn thresholdToReclaim, resourceToReclaim, true\n\t\t}\n\t\tklog.V(3).InfoS(\"Eviction manager: threshold was crossed, but reclaim is not implemented for this threshold.\", \"threshold\", thresholdToReclaim.Signal)\n\t}\n\treturn evictionapi.Threshold{}, \"\", false\n}","line":{"from":105,"to":114}} {"id":100006563,"name":"ParseThresholdConfig","signature":"func ParseThresholdConfig(allocatableConfig []string, evictionHard, evictionSoft, evictionSoftGracePeriod, evictionMinimumReclaim map[string]string) ([]evictionapi.Threshold, error)","file":"pkg/kubelet/eviction/helpers.go","code":"// ParseThresholdConfig parses the flags for thresholds.\nfunc ParseThresholdConfig(allocatableConfig []string, evictionHard, evictionSoft, evictionSoftGracePeriod, evictionMinimumReclaim map[string]string) ([]evictionapi.Threshold, error) {\n\tresults := []evictionapi.Threshold{}\n\thardThresholds, err := parseThresholdStatements(evictionHard)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresults = append(results, hardThresholds...)\n\tsoftThresholds, err := parseThresholdStatements(evictionSoft)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgracePeriods, err := parseGracePeriods(evictionSoftGracePeriod)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tminReclaims, err := parseMinimumReclaims(evictionMinimumReclaim)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor i := range softThresholds {\n\t\tsignal := softThresholds[i].Signal\n\t\tperiod, found := gracePeriods[signal]\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"grace period must be specified for the soft eviction threshold %v\", signal)\n\t\t}\n\t\tsoftThresholds[i].GracePeriod = period\n\t}\n\tresults = append(results, softThresholds...)\n\tfor i := range results {\n\t\tif minReclaim, ok := minReclaims[results[i].Signal]; ok {\n\t\t\tresults[i].MinReclaim = \u0026minReclaim\n\t\t}\n\t}\n\tfor _, key := range allocatableConfig {\n\t\tif key == kubetypes.NodeAllocatableEnforcementKey {\n\t\t\tresults = addAllocatableThresholds(results)\n\t\t\tbreak\n\t\t}\n\t}\n\treturn results, nil\n}","line":{"from":116,"to":157}} {"id":100006564,"name":"addAllocatableThresholds","signature":"func addAllocatableThresholds(thresholds []evictionapi.Threshold) []evictionapi.Threshold","file":"pkg/kubelet/eviction/helpers.go","code":"func addAllocatableThresholds(thresholds []evictionapi.Threshold) []evictionapi.Threshold {\n\tadditionalThresholds := []evictionapi.Threshold{}\n\tfor _, threshold := range thresholds {\n\t\tif threshold.Signal == evictionapi.SignalMemoryAvailable \u0026\u0026 isHardEvictionThreshold(threshold) {\n\t\t\t// Copy the SignalMemoryAvailable to SignalAllocatableMemoryAvailable\n\t\t\tadditionalThresholds = append(additionalThresholds, evictionapi.Threshold{\n\t\t\t\tSignal: evictionapi.SignalAllocatableMemoryAvailable,\n\t\t\t\tOperator: threshold.Operator,\n\t\t\t\tValue: threshold.Value,\n\t\t\t\tMinReclaim: threshold.MinReclaim,\n\t\t\t})\n\t\t}\n\t}\n\treturn append(append([]evictionapi.Threshold{}, thresholds...), additionalThresholds...)\n}","line":{"from":159,"to":173}} {"id":100006565,"name":"parseThresholdStatements","signature":"func parseThresholdStatements(statements map[string]string) ([]evictionapi.Threshold, error)","file":"pkg/kubelet/eviction/helpers.go","code":"// parseThresholdStatements parses the input statements into a list of Threshold objects.\nfunc parseThresholdStatements(statements map[string]string) ([]evictionapi.Threshold, error) {\n\tif len(statements) == 0 {\n\t\treturn nil, nil\n\t}\n\tresults := []evictionapi.Threshold{}\n\tfor signal, val := range statements {\n\t\tresult, err := parseThresholdStatement(evictionapi.Signal(signal), val)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif result != nil {\n\t\t\tresults = append(results, *result)\n\t\t}\n\t}\n\treturn results, nil\n}","line":{"from":175,"to":191}} {"id":100006566,"name":"parseThresholdStatement","signature":"func parseThresholdStatement(signal evictionapi.Signal, val string) (*evictionapi.Threshold, error)","file":"pkg/kubelet/eviction/helpers.go","code":"// parseThresholdStatement parses a threshold statement and returns a threshold,\n// or nil if the threshold should be ignored.\nfunc parseThresholdStatement(signal evictionapi.Signal, val string) (*evictionapi.Threshold, error) {\n\tif !validSignal(signal) {\n\t\treturn nil, fmt.Errorf(unsupportedEvictionSignal, signal)\n\t}\n\toperator := evictionapi.OpForSignal[signal]\n\tif strings.HasSuffix(val, \"%\") {\n\t\t// ignore 0% and 100%\n\t\tif val == \"0%\" || val == \"100%\" {\n\t\t\treturn nil, nil\n\t\t}\n\t\tpercentage, err := parsePercentage(val)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif percentage \u003c 0 {\n\t\t\treturn nil, fmt.Errorf(\"eviction percentage threshold %v must be \u003e= 0%%: %s\", signal, val)\n\t\t}\n\t\t// percentage is a float and should not be greater than 1 (100%)\n\t\tif percentage \u003e 1 {\n\t\t\treturn nil, fmt.Errorf(\"eviction percentage threshold %v must be \u003c= 100%%: %s\", signal, val)\n\t\t}\n\t\treturn \u0026evictionapi.Threshold{\n\t\t\tSignal: signal,\n\t\t\tOperator: operator,\n\t\t\tValue: evictionapi.ThresholdValue{\n\t\t\t\tPercentage: percentage,\n\t\t\t},\n\t\t}, nil\n\t}\n\tquantity, err := resource.ParseQuantity(val)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif quantity.Sign() \u003c 0 || quantity.IsZero() {\n\t\treturn nil, fmt.Errorf(\"eviction threshold %v must be positive: %s\", signal, \u0026quantity)\n\t}\n\treturn \u0026evictionapi.Threshold{\n\t\tSignal: signal,\n\t\tOperator: operator,\n\t\tValue: evictionapi.ThresholdValue{\n\t\t\tQuantity: \u0026quantity,\n\t\t},\n\t}, nil\n}","line":{"from":193,"to":238}} {"id":100006567,"name":"parsePercentage","signature":"func parsePercentage(input string) (float32, error)","file":"pkg/kubelet/eviction/helpers.go","code":"// parsePercentage parses a string representing a percentage value\nfunc parsePercentage(input string) (float32, error) {\n\tvalue, err := strconv.ParseFloat(strings.TrimRight(input, \"%\"), 32)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn float32(value) / 100, nil\n}","line":{"from":240,"to":247}} {"id":100006568,"name":"parseGracePeriods","signature":"func parseGracePeriods(statements map[string]string) (map[evictionapi.Signal]time.Duration, error)","file":"pkg/kubelet/eviction/helpers.go","code":"// parseGracePeriods parses the grace period statements\nfunc parseGracePeriods(statements map[string]string) (map[evictionapi.Signal]time.Duration, error) {\n\tif len(statements) == 0 {\n\t\treturn nil, nil\n\t}\n\tresults := map[evictionapi.Signal]time.Duration{}\n\tfor signal, val := range statements {\n\t\tsignal := evictionapi.Signal(signal)\n\t\tif !validSignal(signal) {\n\t\t\treturn nil, fmt.Errorf(unsupportedEvictionSignal, signal)\n\t\t}\n\t\tgracePeriod, err := time.ParseDuration(val)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif gracePeriod \u003c 0 {\n\t\t\treturn nil, fmt.Errorf(\"invalid eviction grace period specified: %v, must be a positive value\", val)\n\t\t}\n\t\tresults[signal] = gracePeriod\n\t}\n\treturn results, nil\n}","line":{"from":249,"to":270}} {"id":100006569,"name":"parseMinimumReclaims","signature":"func parseMinimumReclaims(statements map[string]string) (map[evictionapi.Signal]evictionapi.ThresholdValue, error)","file":"pkg/kubelet/eviction/helpers.go","code":"// parseMinimumReclaims parses the minimum reclaim statements\nfunc parseMinimumReclaims(statements map[string]string) (map[evictionapi.Signal]evictionapi.ThresholdValue, error) {\n\tif len(statements) == 0 {\n\t\treturn nil, nil\n\t}\n\tresults := map[evictionapi.Signal]evictionapi.ThresholdValue{}\n\tfor signal, val := range statements {\n\t\tsignal := evictionapi.Signal(signal)\n\t\tif !validSignal(signal) {\n\t\t\treturn nil, fmt.Errorf(unsupportedEvictionSignal, signal)\n\t\t}\n\t\tif strings.HasSuffix(val, \"%\") {\n\t\t\tpercentage, err := parsePercentage(val)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif percentage \u003c= 0 {\n\t\t\t\treturn nil, fmt.Errorf(\"eviction percentage minimum reclaim %v must be positive: %s\", signal, val)\n\t\t\t}\n\t\t\tresults[signal] = evictionapi.ThresholdValue{\n\t\t\t\tPercentage: percentage,\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tquantity, err := resource.ParseQuantity(val)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif quantity.Sign() \u003c 0 {\n\t\t\treturn nil, fmt.Errorf(\"negative eviction minimum reclaim specified for %v\", signal)\n\t\t}\n\t\tresults[signal] = evictionapi.ThresholdValue{\n\t\t\tQuantity: \u0026quantity,\n\t\t}\n\t}\n\treturn results, nil\n}","line":{"from":272,"to":308}} {"id":100006570,"name":"diskUsage","signature":"func diskUsage(fsStats *statsapi.FsStats) *resource.Quantity","file":"pkg/kubelet/eviction/helpers.go","code":"// diskUsage converts used bytes into a resource quantity.\nfunc diskUsage(fsStats *statsapi.FsStats) *resource.Quantity {\n\tif fsStats == nil || fsStats.UsedBytes == nil {\n\t\treturn \u0026resource.Quantity{Format: resource.BinarySI}\n\t}\n\tusage := int64(*fsStats.UsedBytes)\n\treturn resource.NewQuantity(usage, resource.BinarySI)\n}","line":{"from":310,"to":317}} {"id":100006571,"name":"inodeUsage","signature":"func inodeUsage(fsStats *statsapi.FsStats) *resource.Quantity","file":"pkg/kubelet/eviction/helpers.go","code":"// inodeUsage converts inodes consumed into a resource quantity.\nfunc inodeUsage(fsStats *statsapi.FsStats) *resource.Quantity {\n\tif fsStats == nil || fsStats.InodesUsed == nil {\n\t\treturn \u0026resource.Quantity{Format: resource.DecimalSI}\n\t}\n\tusage := int64(*fsStats.InodesUsed)\n\treturn resource.NewQuantity(usage, resource.DecimalSI)\n}","line":{"from":319,"to":326}} {"id":100006572,"name":"memoryUsage","signature":"func memoryUsage(memStats *statsapi.MemoryStats) *resource.Quantity","file":"pkg/kubelet/eviction/helpers.go","code":"// memoryUsage converts working set into a resource quantity.\nfunc memoryUsage(memStats *statsapi.MemoryStats) *resource.Quantity {\n\tif memStats == nil || memStats.WorkingSetBytes == nil {\n\t\treturn \u0026resource.Quantity{Format: resource.BinarySI}\n\t}\n\tusage := int64(*memStats.WorkingSetBytes)\n\treturn resource.NewQuantity(usage, resource.BinarySI)\n}","line":{"from":328,"to":335}} {"id":100006573,"name":"processUsage","signature":"func processUsage(processStats *statsapi.ProcessStats) uint64","file":"pkg/kubelet/eviction/helpers.go","code":"// processUsage converts working set into a process count.\nfunc processUsage(processStats *statsapi.ProcessStats) uint64 {\n\tif processStats == nil || processStats.ProcessCount == nil {\n\t\treturn 0\n\t}\n\tusage := uint64(*processStats.ProcessCount)\n\treturn usage\n}","line":{"from":337,"to":344}} {"id":100006574,"name":"localVolumeNames","signature":"func localVolumeNames(pod *v1.Pod) []string","file":"pkg/kubelet/eviction/helpers.go","code":"// localVolumeNames returns the set of volumes for the pod that are local\n// TODO: summary API should report what volumes consume local storage rather than hard-code here.\nfunc localVolumeNames(pod *v1.Pod) []string {\n\tresult := []string{}\n\tfor _, volume := range pod.Spec.Volumes {\n\t\tif volume.HostPath != nil ||\n\t\t\tvolumeutils.IsLocalEphemeralVolume(volume) {\n\t\t\tresult = append(result, volume.Name)\n\t\t}\n\t}\n\treturn result\n}","line":{"from":346,"to":357}} {"id":100006575,"name":"containerUsage","signature":"func containerUsage(podStats statsapi.PodStats, statsToMeasure []fsStatsType) v1.ResourceList","file":"pkg/kubelet/eviction/helpers.go","code":"// containerUsage aggregates container disk usage and inode consumption for the specified stats to measure.\nfunc containerUsage(podStats statsapi.PodStats, statsToMeasure []fsStatsType) v1.ResourceList {\n\tdisk := resource.Quantity{Format: resource.BinarySI}\n\tinodes := resource.Quantity{Format: resource.DecimalSI}\n\tfor _, container := range podStats.Containers {\n\t\tif hasFsStatsType(statsToMeasure, fsStatsRoot) {\n\t\t\tdisk.Add(*diskUsage(container.Rootfs))\n\t\t\tinodes.Add(*inodeUsage(container.Rootfs))\n\t\t}\n\t\tif hasFsStatsType(statsToMeasure, fsStatsLogs) {\n\t\t\tdisk.Add(*diskUsage(container.Logs))\n\t\t\tinodes.Add(*inodeUsage(container.Logs))\n\t\t}\n\t}\n\treturn v1.ResourceList{\n\t\tv1.ResourceEphemeralStorage: disk,\n\t\tresourceInodes: inodes,\n\t}\n}","line":{"from":359,"to":377}} {"id":100006576,"name":"podLocalVolumeUsage","signature":"func podLocalVolumeUsage(volumeNames []string, podStats statsapi.PodStats) v1.ResourceList","file":"pkg/kubelet/eviction/helpers.go","code":"// podLocalVolumeUsage aggregates pod local volumes disk usage and inode consumption for the specified stats to measure.\nfunc podLocalVolumeUsage(volumeNames []string, podStats statsapi.PodStats) v1.ResourceList {\n\tdisk := resource.Quantity{Format: resource.BinarySI}\n\tinodes := resource.Quantity{Format: resource.DecimalSI}\n\tfor _, volumeName := range volumeNames {\n\t\tfor _, volumeStats := range podStats.VolumeStats {\n\t\t\tif volumeStats.Name == volumeName {\n\t\t\t\tdisk.Add(*diskUsage(\u0026volumeStats.FsStats))\n\t\t\t\tinodes.Add(*inodeUsage(\u0026volumeStats.FsStats))\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn v1.ResourceList{\n\t\tv1.ResourceEphemeralStorage: disk,\n\t\tresourceInodes: inodes,\n\t}\n}","line":{"from":379,"to":396}} {"id":100006577,"name":"podDiskUsage","signature":"func podDiskUsage(podStats statsapi.PodStats, pod *v1.Pod, statsToMeasure []fsStatsType) (v1.ResourceList, error)","file":"pkg/kubelet/eviction/helpers.go","code":"// podDiskUsage aggregates pod disk usage and inode consumption for the specified stats to measure.\nfunc podDiskUsage(podStats statsapi.PodStats, pod *v1.Pod, statsToMeasure []fsStatsType) (v1.ResourceList, error) {\n\tdisk := resource.Quantity{Format: resource.BinarySI}\n\tinodes := resource.Quantity{Format: resource.DecimalSI}\n\n\tcontainerUsageList := containerUsage(podStats, statsToMeasure)\n\tdisk.Add(containerUsageList[v1.ResourceEphemeralStorage])\n\tinodes.Add(containerUsageList[resourceInodes])\n\n\tif hasFsStatsType(statsToMeasure, fsStatsLocalVolumeSource) {\n\t\tvolumeNames := localVolumeNames(pod)\n\t\tpodLocalVolumeUsageList := podLocalVolumeUsage(volumeNames, podStats)\n\t\tdisk.Add(podLocalVolumeUsageList[v1.ResourceEphemeralStorage])\n\t\tinodes.Add(podLocalVolumeUsageList[resourceInodes])\n\t}\n\treturn v1.ResourceList{\n\t\tv1.ResourceEphemeralStorage: disk,\n\t\tresourceInodes: inodes,\n\t}, nil\n}","line":{"from":398,"to":417}} {"id":100006578,"name":"formatThreshold","signature":"func formatThreshold(threshold evictionapi.Threshold) string","file":"pkg/kubelet/eviction/helpers.go","code":"// formatThreshold formats a threshold for logging.\nfunc formatThreshold(threshold evictionapi.Threshold) string {\n\treturn fmt.Sprintf(\"threshold(signal=%v, operator=%v, value=%v, gracePeriod=%v)\", threshold.Signal, threshold.Operator, evictionapi.ThresholdValue(threshold.Value), threshold.GracePeriod)\n}","line":{"from":419,"to":422}} {"id":100006579,"name":"cachedStatsFunc","signature":"func cachedStatsFunc(podStats []statsapi.PodStats) statsFunc","file":"pkg/kubelet/eviction/helpers.go","code":"// cachedStatsFunc returns a statsFunc based on the provided pod stats.\nfunc cachedStatsFunc(podStats []statsapi.PodStats) statsFunc {\n\tuid2PodStats := map[string]statsapi.PodStats{}\n\tfor i := range podStats {\n\t\tuid2PodStats[podStats[i].PodRef.UID] = podStats[i]\n\t}\n\treturn func(pod *v1.Pod) (statsapi.PodStats, bool) {\n\t\tstats, found := uid2PodStats[string(pod.UID)]\n\t\treturn stats, found\n\t}\n}","line":{"from":424,"to":434}} {"id":100006580,"name":"Sort","signature":"func (ms *multiSorter) Sort(pods []*v1.Pod)","file":"pkg/kubelet/eviction/helpers.go","code":"// Sort sorts the argument slice according to the less functions passed to OrderedBy.\nfunc (ms *multiSorter) Sort(pods []*v1.Pod) {\n\tms.pods = pods\n\tsort.Sort(ms)\n}","line":{"from":449,"to":453}} {"id":100006581,"name":"orderedBy","signature":"func orderedBy(cmp ...cmpFunc) *multiSorter","file":"pkg/kubelet/eviction/helpers.go","code":"// OrderedBy returns a Sorter that sorts using the cmp functions, in order.\n// Call its Sort method to sort the data.\nfunc orderedBy(cmp ...cmpFunc) *multiSorter {\n\treturn \u0026multiSorter{\n\t\tcmp: cmp,\n\t}\n}","line":{"from":455,"to":461}} {"id":100006582,"name":"Len","signature":"func (ms *multiSorter) Len() int","file":"pkg/kubelet/eviction/helpers.go","code":"// Len is part of sort.Interface.\nfunc (ms *multiSorter) Len() int {\n\treturn len(ms.pods)\n}","line":{"from":463,"to":466}} {"id":100006583,"name":"Swap","signature":"func (ms *multiSorter) Swap(i, j int)","file":"pkg/kubelet/eviction/helpers.go","code":"// Swap is part of sort.Interface.\nfunc (ms *multiSorter) Swap(i, j int) {\n\tms.pods[i], ms.pods[j] = ms.pods[j], ms.pods[i]\n}","line":{"from":468,"to":471}} {"id":100006584,"name":"Less","signature":"func (ms *multiSorter) Less(i, j int) bool","file":"pkg/kubelet/eviction/helpers.go","code":"// Less is part of sort.Interface.\nfunc (ms *multiSorter) Less(i, j int) bool {\n\tp1, p2 := ms.pods[i], ms.pods[j]\n\tvar k int\n\tfor k = 0; k \u003c len(ms.cmp)-1; k++ {\n\t\tcmpResult := ms.cmp[k](p1, p2)\n\t\t// p1 is less than p2\n\t\tif cmpResult \u003c 0 {\n\t\t\treturn true\n\t\t}\n\t\t// p1 is greater than p2\n\t\tif cmpResult \u003e 0 {\n\t\t\treturn false\n\t\t}\n\t\t// we don't know yet\n\t}\n\t// the last cmp func is the final decider\n\treturn ms.cmp[k](p1, p2) \u003c 0\n}","line":{"from":473,"to":491}} {"id":100006585,"name":"priority","signature":"func priority(p1, p2 *v1.Pod) int","file":"pkg/kubelet/eviction/helpers.go","code":"// priority compares pods by Priority, if priority is enabled.\nfunc priority(p1, p2 *v1.Pod) int {\n\tpriority1 := corev1helpers.PodPriority(p1)\n\tpriority2 := corev1helpers.PodPriority(p2)\n\tif priority1 == priority2 {\n\t\treturn 0\n\t}\n\tif priority1 \u003e priority2 {\n\t\treturn 1\n\t}\n\treturn -1\n}","line":{"from":493,"to":504}} {"id":100006586,"name":"exceedMemoryRequests","signature":"func exceedMemoryRequests(stats statsFunc) cmpFunc","file":"pkg/kubelet/eviction/helpers.go","code":"// exceedMemoryRequests compares whether or not pods' memory usage exceeds their requests\nfunc exceedMemoryRequests(stats statsFunc) cmpFunc {\n\treturn func(p1, p2 *v1.Pod) int {\n\t\tp1Stats, p1Found := stats(p1)\n\t\tp2Stats, p2Found := stats(p2)\n\t\tif !p1Found || !p2Found {\n\t\t\t// prioritize evicting the pod for which no stats were found\n\t\t\treturn cmpBool(!p1Found, !p2Found)\n\t\t}\n\n\t\tp1Memory := memoryUsage(p1Stats.Memory)\n\t\tp2Memory := memoryUsage(p2Stats.Memory)\n\t\tp1ExceedsRequests := p1Memory.Cmp(v1resource.GetResourceRequestQuantity(p1, v1.ResourceMemory)) == 1\n\t\tp2ExceedsRequests := p2Memory.Cmp(v1resource.GetResourceRequestQuantity(p2, v1.ResourceMemory)) == 1\n\t\t// prioritize evicting the pod which exceeds its requests\n\t\treturn cmpBool(p1ExceedsRequests, p2ExceedsRequests)\n\t}\n}","line":{"from":506,"to":523}} {"id":100006587,"name":"memory","signature":"func memory(stats statsFunc) cmpFunc","file":"pkg/kubelet/eviction/helpers.go","code":"// memory compares pods by largest consumer of memory relative to request.\nfunc memory(stats statsFunc) cmpFunc {\n\treturn func(p1, p2 *v1.Pod) int {\n\t\tp1Stats, p1Found := stats(p1)\n\t\tp2Stats, p2Found := stats(p2)\n\t\tif !p1Found || !p2Found {\n\t\t\t// prioritize evicting the pod for which no stats were found\n\t\t\treturn cmpBool(!p1Found, !p2Found)\n\t\t}\n\n\t\t// adjust p1, p2 usage relative to the request (if any)\n\t\tp1Memory := memoryUsage(p1Stats.Memory)\n\t\tp1Request := v1resource.GetResourceRequestQuantity(p1, v1.ResourceMemory)\n\t\tp1Memory.Sub(p1Request)\n\n\t\tp2Memory := memoryUsage(p2Stats.Memory)\n\t\tp2Request := v1resource.GetResourceRequestQuantity(p2, v1.ResourceMemory)\n\t\tp2Memory.Sub(p2Request)\n\n\t\t// prioritize evicting the pod which has the larger consumption of memory\n\t\treturn p2Memory.Cmp(*p1Memory)\n\t}\n}","line":{"from":525,"to":547}} {"id":100006588,"name":"process","signature":"func process(stats statsFunc) cmpFunc","file":"pkg/kubelet/eviction/helpers.go","code":"// process compares pods by largest consumer of process number relative to request.\nfunc process(stats statsFunc) cmpFunc {\n\treturn func(p1, p2 *v1.Pod) int {\n\t\tp1Stats, p1Found := stats(p1)\n\t\tp2Stats, p2Found := stats(p2)\n\t\tif !p1Found || !p2Found {\n\t\t\t// prioritize evicting the pod for which no stats were found\n\t\t\treturn cmpBool(!p1Found, !p2Found)\n\t\t}\n\n\t\tp1Process := processUsage(p1Stats.ProcessStats)\n\t\tp2Process := processUsage(p2Stats.ProcessStats)\n\t\t// prioritize evicting the pod which has the larger consumption of process\n\t\treturn int(p2Process - p1Process)\n\t}\n}","line":{"from":549,"to":564}} {"id":100006589,"name":"exceedDiskRequests","signature":"func exceedDiskRequests(stats statsFunc, fsStatsToMeasure []fsStatsType, diskResource v1.ResourceName) cmpFunc","file":"pkg/kubelet/eviction/helpers.go","code":"// exceedDiskRequests compares whether or not pods' disk usage exceeds their requests\nfunc exceedDiskRequests(stats statsFunc, fsStatsToMeasure []fsStatsType, diskResource v1.ResourceName) cmpFunc {\n\treturn func(p1, p2 *v1.Pod) int {\n\t\tp1Stats, p1Found := stats(p1)\n\t\tp2Stats, p2Found := stats(p2)\n\t\tif !p1Found || !p2Found {\n\t\t\t// prioritize evicting the pod for which no stats were found\n\t\t\treturn cmpBool(!p1Found, !p2Found)\n\t\t}\n\n\t\tp1Usage, p1Err := podDiskUsage(p1Stats, p1, fsStatsToMeasure)\n\t\tp2Usage, p2Err := podDiskUsage(p2Stats, p2, fsStatsToMeasure)\n\t\tif p1Err != nil || p2Err != nil {\n\t\t\t// prioritize evicting the pod which had an error getting stats\n\t\t\treturn cmpBool(p1Err != nil, p2Err != nil)\n\t\t}\n\n\t\tp1Disk := p1Usage[diskResource]\n\t\tp2Disk := p2Usage[diskResource]\n\t\tp1ExceedsRequests := p1Disk.Cmp(v1resource.GetResourceRequestQuantity(p1, diskResource)) == 1\n\t\tp2ExceedsRequests := p2Disk.Cmp(v1resource.GetResourceRequestQuantity(p2, diskResource)) == 1\n\t\t// prioritize evicting the pod which exceeds its requests\n\t\treturn cmpBool(p1ExceedsRequests, p2ExceedsRequests)\n\t}\n}","line":{"from":566,"to":590}} {"id":100006590,"name":"disk","signature":"func disk(stats statsFunc, fsStatsToMeasure []fsStatsType, diskResource v1.ResourceName) cmpFunc","file":"pkg/kubelet/eviction/helpers.go","code":"// disk compares pods by largest consumer of disk relative to request for the specified disk resource.\nfunc disk(stats statsFunc, fsStatsToMeasure []fsStatsType, diskResource v1.ResourceName) cmpFunc {\n\treturn func(p1, p2 *v1.Pod) int {\n\t\tp1Stats, p1Found := stats(p1)\n\t\tp2Stats, p2Found := stats(p2)\n\t\tif !p1Found || !p2Found {\n\t\t\t// prioritize evicting the pod for which no stats were found\n\t\t\treturn cmpBool(!p1Found, !p2Found)\n\t\t}\n\t\tp1Usage, p1Err := podDiskUsage(p1Stats, p1, fsStatsToMeasure)\n\t\tp2Usage, p2Err := podDiskUsage(p2Stats, p2, fsStatsToMeasure)\n\t\tif p1Err != nil || p2Err != nil {\n\t\t\t// prioritize evicting the pod which had an error getting stats\n\t\t\treturn cmpBool(p1Err != nil, p2Err != nil)\n\t\t}\n\n\t\t// adjust p1, p2 usage relative to the request (if any)\n\t\tp1Disk := p1Usage[diskResource]\n\t\tp2Disk := p2Usage[diskResource]\n\t\tp1Request := v1resource.GetResourceRequestQuantity(p1, v1.ResourceEphemeralStorage)\n\t\tp1Disk.Sub(p1Request)\n\t\tp2Request := v1resource.GetResourceRequestQuantity(p2, v1.ResourceEphemeralStorage)\n\t\tp2Disk.Sub(p2Request)\n\t\t// prioritize evicting the pod which has the larger consumption of disk\n\t\treturn p2Disk.Cmp(p1Disk)\n\t}\n}","line":{"from":592,"to":618}} {"id":100006591,"name":"cmpBool","signature":"func cmpBool(a, b bool) int","file":"pkg/kubelet/eviction/helpers.go","code":"// cmpBool compares booleans, placing true before false\nfunc cmpBool(a, b bool) int {\n\tif a == b {\n\t\treturn 0\n\t}\n\tif !b {\n\t\treturn -1\n\t}\n\treturn 1\n}","line":{"from":620,"to":629}} {"id":100006592,"name":"rankMemoryPressure","signature":"func rankMemoryPressure(pods []*v1.Pod, stats statsFunc)","file":"pkg/kubelet/eviction/helpers.go","code":"// rankMemoryPressure orders the input pods for eviction in response to memory pressure.\n// It ranks by whether or not the pod's usage exceeds its requests, then by priority, and\n// finally by memory usage above requests.\nfunc rankMemoryPressure(pods []*v1.Pod, stats statsFunc) {\n\torderedBy(exceedMemoryRequests(stats), priority, memory(stats)).Sort(pods)\n}","line":{"from":631,"to":636}} {"id":100006593,"name":"rankPIDPressure","signature":"func rankPIDPressure(pods []*v1.Pod, stats statsFunc)","file":"pkg/kubelet/eviction/helpers.go","code":"// rankPIDPressure orders the input pods by priority in response to PID pressure.\nfunc rankPIDPressure(pods []*v1.Pod, stats statsFunc) {\n\torderedBy(priority, process(stats)).Sort(pods)\n}","line":{"from":638,"to":641}} {"id":100006594,"name":"rankDiskPressureFunc","signature":"func rankDiskPressureFunc(fsStatsToMeasure []fsStatsType, diskResource v1.ResourceName) rankFunc","file":"pkg/kubelet/eviction/helpers.go","code":"// rankDiskPressureFunc returns a rankFunc that measures the specified fs stats.\nfunc rankDiskPressureFunc(fsStatsToMeasure []fsStatsType, diskResource v1.ResourceName) rankFunc {\n\treturn func(pods []*v1.Pod, stats statsFunc) {\n\t\torderedBy(exceedDiskRequests(stats, fsStatsToMeasure, diskResource), priority, disk(stats, fsStatsToMeasure, diskResource)).Sort(pods)\n\t}\n}","line":{"from":643,"to":648}} {"id":100006595,"name":"Len","signature":"func (a byEvictionPriority) Len() int { return len(a) }","file":"pkg/kubelet/eviction/helpers.go","code":"func (a byEvictionPriority) Len() int { return len(a) }","line":{"from":653,"to":653}} {"id":100006596,"name":"Swap","signature":"func (a byEvictionPriority) Swap(i, j int) { a[i], a[j] = a[j], a[i] }","file":"pkg/kubelet/eviction/helpers.go","code":"func (a byEvictionPriority) Swap(i, j int) { a[i], a[j] = a[j], a[i] }","line":{"from":654,"to":654}} {"id":100006597,"name":"Less","signature":"func (a byEvictionPriority) Less(i, j int) bool","file":"pkg/kubelet/eviction/helpers.go","code":"// Less ranks memory before all other resources, and ranks thresholds with no resource to reclaim last\nfunc (a byEvictionPriority) Less(i, j int) bool {\n\t_, jSignalHasResource := signalToResource[a[j].Signal]\n\treturn a[i].Signal == evictionapi.SignalMemoryAvailable || a[i].Signal == evictionapi.SignalAllocatableMemoryAvailable || !jSignalHasResource\n}","line":{"from":656,"to":660}} {"id":100006598,"name":"makeSignalObservations","signature":"func makeSignalObservations(summary *statsapi.Summary) (signalObservations, statsFunc)","file":"pkg/kubelet/eviction/helpers.go","code":"// makeSignalObservations derives observations using the specified summary provider.\nfunc makeSignalObservations(summary *statsapi.Summary) (signalObservations, statsFunc) {\n\t// build the function to work against for pod stats\n\tstatsFunc := cachedStatsFunc(summary.Pods)\n\t// build an evaluation context for current eviction signals\n\tresult := signalObservations{}\n\n\tif memory := summary.Node.Memory; memory != nil \u0026\u0026 memory.AvailableBytes != nil \u0026\u0026 memory.WorkingSetBytes != nil {\n\t\tresult[evictionapi.SignalMemoryAvailable] = signalObservation{\n\t\t\tavailable: resource.NewQuantity(int64(*memory.AvailableBytes), resource.BinarySI),\n\t\t\tcapacity: resource.NewQuantity(int64(*memory.AvailableBytes+*memory.WorkingSetBytes), resource.BinarySI),\n\t\t\ttime: memory.Time,\n\t\t}\n\t}\n\tif allocatableContainer, err := getSysContainer(summary.Node.SystemContainers, statsapi.SystemContainerPods); err != nil {\n\t\tklog.ErrorS(err, \"Eviction manager: failed to construct signal\", \"signal\", evictionapi.SignalAllocatableMemoryAvailable)\n\t} else {\n\t\tif memory := allocatableContainer.Memory; memory != nil \u0026\u0026 memory.AvailableBytes != nil \u0026\u0026 memory.WorkingSetBytes != nil {\n\t\t\tresult[evictionapi.SignalAllocatableMemoryAvailable] = signalObservation{\n\t\t\t\tavailable: resource.NewQuantity(int64(*memory.AvailableBytes), resource.BinarySI),\n\t\t\t\tcapacity: resource.NewQuantity(int64(*memory.AvailableBytes+*memory.WorkingSetBytes), resource.BinarySI),\n\t\t\t\ttime: memory.Time,\n\t\t\t}\n\t\t}\n\t}\n\tif nodeFs := summary.Node.Fs; nodeFs != nil {\n\t\tif nodeFs.AvailableBytes != nil \u0026\u0026 nodeFs.CapacityBytes != nil {\n\t\t\tresult[evictionapi.SignalNodeFsAvailable] = signalObservation{\n\t\t\t\tavailable: resource.NewQuantity(int64(*nodeFs.AvailableBytes), resource.BinarySI),\n\t\t\t\tcapacity: resource.NewQuantity(int64(*nodeFs.CapacityBytes), resource.BinarySI),\n\t\t\t\ttime: nodeFs.Time,\n\t\t\t}\n\t\t}\n\t\tif nodeFs.InodesFree != nil \u0026\u0026 nodeFs.Inodes != nil {\n\t\t\tresult[evictionapi.SignalNodeFsInodesFree] = signalObservation{\n\t\t\t\tavailable: resource.NewQuantity(int64(*nodeFs.InodesFree), resource.DecimalSI),\n\t\t\t\tcapacity: resource.NewQuantity(int64(*nodeFs.Inodes), resource.DecimalSI),\n\t\t\t\ttime: nodeFs.Time,\n\t\t\t}\n\t\t}\n\t}\n\tif summary.Node.Runtime != nil {\n\t\tif imageFs := summary.Node.Runtime.ImageFs; imageFs != nil {\n\t\t\tif imageFs.AvailableBytes != nil \u0026\u0026 imageFs.CapacityBytes != nil {\n\t\t\t\tresult[evictionapi.SignalImageFsAvailable] = signalObservation{\n\t\t\t\t\tavailable: resource.NewQuantity(int64(*imageFs.AvailableBytes), resource.BinarySI),\n\t\t\t\t\tcapacity: resource.NewQuantity(int64(*imageFs.CapacityBytes), resource.BinarySI),\n\t\t\t\t\ttime: imageFs.Time,\n\t\t\t\t}\n\t\t\t\tif imageFs.InodesFree != nil \u0026\u0026 imageFs.Inodes != nil {\n\t\t\t\t\tresult[evictionapi.SignalImageFsInodesFree] = signalObservation{\n\t\t\t\t\t\tavailable: resource.NewQuantity(int64(*imageFs.InodesFree), resource.DecimalSI),\n\t\t\t\t\t\tcapacity: resource.NewQuantity(int64(*imageFs.Inodes), resource.DecimalSI),\n\t\t\t\t\t\ttime: imageFs.Time,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif rlimit := summary.Node.Rlimit; rlimit != nil {\n\t\tif rlimit.NumOfRunningProcesses != nil \u0026\u0026 rlimit.MaxPID != nil {\n\t\t\tavailable := int64(*rlimit.MaxPID) - int64(*rlimit.NumOfRunningProcesses)\n\t\t\tresult[evictionapi.SignalPIDAvailable] = signalObservation{\n\t\t\t\tavailable: resource.NewQuantity(available, resource.DecimalSI),\n\t\t\t\tcapacity: resource.NewQuantity(int64(*rlimit.MaxPID), resource.DecimalSI),\n\t\t\t\ttime: rlimit.Time,\n\t\t\t}\n\t\t}\n\t}\n\treturn result, statsFunc\n}","line":{"from":662,"to":732}} {"id":100006599,"name":"getSysContainer","signature":"func getSysContainer(sysContainers []statsapi.ContainerStats, name string) (*statsapi.ContainerStats, error)","file":"pkg/kubelet/eviction/helpers.go","code":"func getSysContainer(sysContainers []statsapi.ContainerStats, name string) (*statsapi.ContainerStats, error) {\n\tfor _, cont := range sysContainers {\n\t\tif cont.Name == name {\n\t\t\treturn \u0026cont, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"system container %q not found in metrics\", name)\n}","line":{"from":734,"to":741}} {"id":100006600,"name":"thresholdsMet","signature":"func thresholdsMet(thresholds []evictionapi.Threshold, observations signalObservations, enforceMinReclaim bool) []evictionapi.Threshold","file":"pkg/kubelet/eviction/helpers.go","code":"// thresholdsMet returns the set of thresholds that were met independent of grace period\nfunc thresholdsMet(thresholds []evictionapi.Threshold, observations signalObservations, enforceMinReclaim bool) []evictionapi.Threshold {\n\tresults := []evictionapi.Threshold{}\n\tfor i := range thresholds {\n\t\tthreshold := thresholds[i]\n\t\tobserved, found := observations[threshold.Signal]\n\t\tif !found {\n\t\t\tklog.InfoS(\"Eviction manager: no observation found for eviction signal\", \"signal\", threshold.Signal)\n\t\t\tcontinue\n\t\t}\n\t\t// determine if we have met the specified threshold\n\t\tthresholdMet := false\n\t\tquantity := evictionapi.GetThresholdQuantity(threshold.Value, observed.capacity)\n\t\t// if enforceMinReclaim is specified, we compare relative to value - minreclaim\n\t\tif enforceMinReclaim \u0026\u0026 threshold.MinReclaim != nil {\n\t\t\tquantity.Add(*evictionapi.GetThresholdQuantity(*threshold.MinReclaim, observed.capacity))\n\t\t}\n\t\tthresholdResult := quantity.Cmp(*observed.available)\n\t\tswitch threshold.Operator {\n\t\tcase evictionapi.OpLessThan:\n\t\t\tthresholdMet = thresholdResult \u003e 0\n\t\t}\n\t\tif thresholdMet {\n\t\t\tresults = append(results, threshold)\n\t\t}\n\t}\n\treturn results\n}","line":{"from":743,"to":770}} {"id":100006601,"name":"debugLogObservations","signature":"func debugLogObservations(logPrefix string, observations signalObservations)","file":"pkg/kubelet/eviction/helpers.go","code":"func debugLogObservations(logPrefix string, observations signalObservations) {\n\tklogV := klog.V(3)\n\tif !klogV.Enabled() {\n\t\treturn\n\t}\n\tfor k, v := range observations {\n\t\tif !v.time.IsZero() {\n\t\t\tklogV.InfoS(\"Eviction manager:\", \"log\", logPrefix, \"signal\", k, \"resourceName\", signalToResource[k], \"available\", v.available, \"capacity\", v.capacity, \"time\", v.time)\n\t\t} else {\n\t\t\tklogV.InfoS(\"Eviction manager:\", \"log\", logPrefix, \"signal\", k, \"resourceName\", signalToResource[k], \"available\", v.available, \"capacity\", v.capacity)\n\t\t}\n\t}\n}","line":{"from":772,"to":784}} {"id":100006602,"name":"debugLogThresholdsWithObservation","signature":"func debugLogThresholdsWithObservation(logPrefix string, thresholds []evictionapi.Threshold, observations signalObservations)","file":"pkg/kubelet/eviction/helpers.go","code":"func debugLogThresholdsWithObservation(logPrefix string, thresholds []evictionapi.Threshold, observations signalObservations) {\n\tklogV := klog.V(3)\n\tif !klogV.Enabled() {\n\t\treturn\n\t}\n\tfor i := range thresholds {\n\t\tthreshold := thresholds[i]\n\t\tobserved, found := observations[threshold.Signal]\n\t\tif found {\n\t\t\tquantity := evictionapi.GetThresholdQuantity(threshold.Value, observed.capacity)\n\t\t\tklogV.InfoS(\"Eviction manager: threshold observed resource\", \"log\", logPrefix, \"signal\", threshold.Signal, \"resourceName\", signalToResource[threshold.Signal], \"quantity\", quantity, \"available\", observed.available)\n\t\t} else {\n\t\t\tklogV.InfoS(\"Eviction manager: threshold had no observation\", \"log\", logPrefix, \"signal\", threshold.Signal)\n\t\t}\n\t}\n}","line":{"from":786,"to":801}} {"id":100006603,"name":"thresholdsUpdatedStats","signature":"func thresholdsUpdatedStats(thresholds []evictionapi.Threshold, observations, lastObservations signalObservations) []evictionapi.Threshold","file":"pkg/kubelet/eviction/helpers.go","code":"func thresholdsUpdatedStats(thresholds []evictionapi.Threshold, observations, lastObservations signalObservations) []evictionapi.Threshold {\n\tresults := []evictionapi.Threshold{}\n\tfor i := range thresholds {\n\t\tthreshold := thresholds[i]\n\t\tobserved, found := observations[threshold.Signal]\n\t\tif !found {\n\t\t\tklog.InfoS(\"Eviction manager: no observation found for eviction signal\", \"signal\", threshold.Signal)\n\t\t\tcontinue\n\t\t}\n\t\tlast, found := lastObservations[threshold.Signal]\n\t\tif !found || observed.time.IsZero() || observed.time.After(last.time.Time) {\n\t\t\tresults = append(results, threshold)\n\t\t}\n\t}\n\treturn results\n}","line":{"from":803,"to":818}} {"id":100006604,"name":"thresholdsFirstObservedAt","signature":"func thresholdsFirstObservedAt(thresholds []evictionapi.Threshold, lastObservedAt thresholdsObservedAt, now time.Time) thresholdsObservedAt","file":"pkg/kubelet/eviction/helpers.go","code":"// thresholdsFirstObservedAt merges the input set of thresholds with the previous observation to determine when active set of thresholds were initially met.\nfunc thresholdsFirstObservedAt(thresholds []evictionapi.Threshold, lastObservedAt thresholdsObservedAt, now time.Time) thresholdsObservedAt {\n\tresults := thresholdsObservedAt{}\n\tfor i := range thresholds {\n\t\tobservedAt, found := lastObservedAt[thresholds[i]]\n\t\tif !found {\n\t\t\tobservedAt = now\n\t\t}\n\t\tresults[thresholds[i]] = observedAt\n\t}\n\treturn results\n}","line":{"from":820,"to":831}} {"id":100006605,"name":"thresholdsMetGracePeriod","signature":"func thresholdsMetGracePeriod(observedAt thresholdsObservedAt, now time.Time) []evictionapi.Threshold","file":"pkg/kubelet/eviction/helpers.go","code":"// thresholdsMetGracePeriod returns the set of thresholds that have satisfied associated grace period\nfunc thresholdsMetGracePeriod(observedAt thresholdsObservedAt, now time.Time) []evictionapi.Threshold {\n\tresults := []evictionapi.Threshold{}\n\tfor threshold, at := range observedAt {\n\t\tduration := now.Sub(at)\n\t\tif duration \u003c threshold.GracePeriod {\n\t\t\tklog.V(2).InfoS(\"Eviction manager: eviction criteria not yet met\", \"threshold\", formatThreshold(threshold), \"duration\", duration)\n\t\t\tcontinue\n\t\t}\n\t\tresults = append(results, threshold)\n\t}\n\treturn results\n}","line":{"from":833,"to":845}} {"id":100006606,"name":"nodeConditions","signature":"func nodeConditions(thresholds []evictionapi.Threshold) []v1.NodeConditionType","file":"pkg/kubelet/eviction/helpers.go","code":"// nodeConditions returns the set of node conditions associated with a threshold\nfunc nodeConditions(thresholds []evictionapi.Threshold) []v1.NodeConditionType {\n\tresults := []v1.NodeConditionType{}\n\tfor _, threshold := range thresholds {\n\t\tif nodeCondition, found := signalToNodeCondition[threshold.Signal]; found {\n\t\t\tif !hasNodeCondition(results, nodeCondition) {\n\t\t\t\tresults = append(results, nodeCondition)\n\t\t\t}\n\t\t}\n\t}\n\treturn results\n}","line":{"from":847,"to":858}} {"id":100006607,"name":"nodeConditionsLastObservedAt","signature":"func nodeConditionsLastObservedAt(nodeConditions []v1.NodeConditionType, lastObservedAt nodeConditionsObservedAt, now time.Time) nodeConditionsObservedAt","file":"pkg/kubelet/eviction/helpers.go","code":"// nodeConditionsLastObservedAt merges the input with the previous observation to determine when a condition was most recently met.\nfunc nodeConditionsLastObservedAt(nodeConditions []v1.NodeConditionType, lastObservedAt nodeConditionsObservedAt, now time.Time) nodeConditionsObservedAt {\n\tresults := nodeConditionsObservedAt{}\n\t// the input conditions were observed \"now\"\n\tfor i := range nodeConditions {\n\t\tresults[nodeConditions[i]] = now\n\t}\n\t// the conditions that were not observed now are merged in with their old time\n\tfor key, value := range lastObservedAt {\n\t\t_, found := results[key]\n\t\tif !found {\n\t\t\tresults[key] = value\n\t\t}\n\t}\n\treturn results\n}","line":{"from":860,"to":875}} {"id":100006608,"name":"nodeConditionsObservedSince","signature":"func nodeConditionsObservedSince(observedAt nodeConditionsObservedAt, period time.Duration, now time.Time) []v1.NodeConditionType","file":"pkg/kubelet/eviction/helpers.go","code":"// nodeConditionsObservedSince returns the set of conditions that have been observed within the specified period\nfunc nodeConditionsObservedSince(observedAt nodeConditionsObservedAt, period time.Duration, now time.Time) []v1.NodeConditionType {\n\tresults := []v1.NodeConditionType{}\n\tfor nodeCondition, at := range observedAt {\n\t\tduration := now.Sub(at)\n\t\tif duration \u003c period {\n\t\t\tresults = append(results, nodeCondition)\n\t\t}\n\t}\n\treturn results\n}","line":{"from":877,"to":887}} {"id":100006609,"name":"hasFsStatsType","signature":"func hasFsStatsType(inputs []fsStatsType, item fsStatsType) bool","file":"pkg/kubelet/eviction/helpers.go","code":"// hasFsStatsType returns true if the fsStat is in the input list\nfunc hasFsStatsType(inputs []fsStatsType, item fsStatsType) bool {\n\tfor _, input := range inputs {\n\t\tif input == item {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":889,"to":897}} {"id":100006610,"name":"hasNodeCondition","signature":"func hasNodeCondition(inputs []v1.NodeConditionType, item v1.NodeConditionType) bool","file":"pkg/kubelet/eviction/helpers.go","code":"// hasNodeCondition returns true if the node condition is in the input list\nfunc hasNodeCondition(inputs []v1.NodeConditionType, item v1.NodeConditionType) bool {\n\tfor _, input := range inputs {\n\t\tif input == item {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":899,"to":907}} {"id":100006611,"name":"mergeThresholds","signature":"func mergeThresholds(inputsA []evictionapi.Threshold, inputsB []evictionapi.Threshold) []evictionapi.Threshold","file":"pkg/kubelet/eviction/helpers.go","code":"// mergeThresholds will merge both threshold lists eliminating duplicates.\nfunc mergeThresholds(inputsA []evictionapi.Threshold, inputsB []evictionapi.Threshold) []evictionapi.Threshold {\n\tresults := inputsA\n\tfor _, threshold := range inputsB {\n\t\tif !hasThreshold(results, threshold) {\n\t\t\tresults = append(results, threshold)\n\t\t}\n\t}\n\treturn results\n}","line":{"from":909,"to":918}} {"id":100006612,"name":"hasThreshold","signature":"func hasThreshold(inputs []evictionapi.Threshold, item evictionapi.Threshold) bool","file":"pkg/kubelet/eviction/helpers.go","code":"// hasThreshold returns true if the threshold is in the input list\nfunc hasThreshold(inputs []evictionapi.Threshold, item evictionapi.Threshold) bool {\n\tfor _, input := range inputs {\n\t\tif input.GracePeriod == item.GracePeriod \u0026\u0026 input.Operator == item.Operator \u0026\u0026 input.Signal == item.Signal \u0026\u0026 compareThresholdValue(input.Value, item.Value) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":920,"to":928}} {"id":100006613,"name":"compareThresholdValue","signature":"func compareThresholdValue(a evictionapi.ThresholdValue, b evictionapi.ThresholdValue) bool","file":"pkg/kubelet/eviction/helpers.go","code":"// compareThresholdValue returns true if the two thresholdValue objects are logically the same\nfunc compareThresholdValue(a evictionapi.ThresholdValue, b evictionapi.ThresholdValue) bool {\n\tif a.Quantity != nil {\n\t\tif b.Quantity == nil {\n\t\t\treturn false\n\t\t}\n\t\treturn a.Quantity.Cmp(*b.Quantity) == 0\n\t}\n\tif b.Quantity != nil {\n\t\treturn false\n\t}\n\treturn a.Percentage == b.Percentage\n}","line":{"from":930,"to":942}} {"id":100006614,"name":"isHardEvictionThreshold","signature":"func isHardEvictionThreshold(threshold evictionapi.Threshold) bool","file":"pkg/kubelet/eviction/helpers.go","code":"// isHardEvictionThreshold returns true if eviction should immediately occur\nfunc isHardEvictionThreshold(threshold evictionapi.Threshold) bool {\n\treturn threshold.GracePeriod == time.Duration(0)\n}","line":{"from":944,"to":947}} {"id":100006615,"name":"isAllocatableEvictionThreshold","signature":"func isAllocatableEvictionThreshold(threshold evictionapi.Threshold) bool","file":"pkg/kubelet/eviction/helpers.go","code":"func isAllocatableEvictionThreshold(threshold evictionapi.Threshold) bool {\n\treturn threshold.Signal == evictionapi.SignalAllocatableMemoryAvailable\n}","line":{"from":949,"to":951}} {"id":100006616,"name":"buildSignalToRankFunc","signature":"func buildSignalToRankFunc(withImageFs bool) map[evictionapi.Signal]rankFunc","file":"pkg/kubelet/eviction/helpers.go","code":"// buildSignalToRankFunc returns ranking functions associated with resources\nfunc buildSignalToRankFunc(withImageFs bool) map[evictionapi.Signal]rankFunc {\n\tsignalToRankFunc := map[evictionapi.Signal]rankFunc{\n\t\tevictionapi.SignalMemoryAvailable: rankMemoryPressure,\n\t\tevictionapi.SignalAllocatableMemoryAvailable: rankMemoryPressure,\n\t\tevictionapi.SignalPIDAvailable: rankPIDPressure,\n\t}\n\t// usage of an imagefs is optional\n\tif withImageFs {\n\t\t// with an imagefs, nodefs pod rank func for eviction only includes logs and local volumes\n\t\tsignalToRankFunc[evictionapi.SignalNodeFsAvailable] = rankDiskPressureFunc([]fsStatsType{fsStatsLogs, fsStatsLocalVolumeSource}, v1.ResourceEphemeralStorage)\n\t\tsignalToRankFunc[evictionapi.SignalNodeFsInodesFree] = rankDiskPressureFunc([]fsStatsType{fsStatsLogs, fsStatsLocalVolumeSource}, resourceInodes)\n\t\t// with an imagefs, imagefs pod rank func for eviction only includes rootfs\n\t\tsignalToRankFunc[evictionapi.SignalImageFsAvailable] = rankDiskPressureFunc([]fsStatsType{fsStatsRoot}, v1.ResourceEphemeralStorage)\n\t\tsignalToRankFunc[evictionapi.SignalImageFsInodesFree] = rankDiskPressureFunc([]fsStatsType{fsStatsRoot}, resourceInodes)\n\t} else {\n\t\t// without an imagefs, nodefs pod rank func for eviction looks at all fs stats.\n\t\t// since imagefs and nodefs share a common device, they share common ranking functions.\n\t\tsignalToRankFunc[evictionapi.SignalNodeFsAvailable] = rankDiskPressureFunc([]fsStatsType{fsStatsRoot, fsStatsLogs, fsStatsLocalVolumeSource}, v1.ResourceEphemeralStorage)\n\t\tsignalToRankFunc[evictionapi.SignalNodeFsInodesFree] = rankDiskPressureFunc([]fsStatsType{fsStatsRoot, fsStatsLogs, fsStatsLocalVolumeSource}, resourceInodes)\n\t\tsignalToRankFunc[evictionapi.SignalImageFsAvailable] = rankDiskPressureFunc([]fsStatsType{fsStatsRoot, fsStatsLogs, fsStatsLocalVolumeSource}, v1.ResourceEphemeralStorage)\n\t\tsignalToRankFunc[evictionapi.SignalImageFsInodesFree] = rankDiskPressureFunc([]fsStatsType{fsStatsRoot, fsStatsLogs, fsStatsLocalVolumeSource}, resourceInodes)\n\t}\n\treturn signalToRankFunc\n}","line":{"from":953,"to":977}} {"id":100006617,"name":"PodIsEvicted","signature":"func PodIsEvicted(podStatus v1.PodStatus) bool","file":"pkg/kubelet/eviction/helpers.go","code":"// PodIsEvicted returns true if the reported pod status is due to an eviction.\nfunc PodIsEvicted(podStatus v1.PodStatus) bool {\n\treturn podStatus.Phase == v1.PodFailed \u0026\u0026 podStatus.Reason == Reason\n}","line":{"from":979,"to":982}} {"id":100006618,"name":"buildSignalToNodeReclaimFuncs","signature":"func buildSignalToNodeReclaimFuncs(imageGC ImageGC, containerGC ContainerGC, withImageFs bool) map[evictionapi.Signal]nodeReclaimFuncs","file":"pkg/kubelet/eviction/helpers.go","code":"// buildSignalToNodeReclaimFuncs returns reclaim functions associated with resources.\nfunc buildSignalToNodeReclaimFuncs(imageGC ImageGC, containerGC ContainerGC, withImageFs bool) map[evictionapi.Signal]nodeReclaimFuncs {\n\tsignalToReclaimFunc := map[evictionapi.Signal]nodeReclaimFuncs{}\n\t// usage of an imagefs is optional\n\tif withImageFs {\n\t\t// with an imagefs, nodefs pressure should just delete logs\n\t\tsignalToReclaimFunc[evictionapi.SignalNodeFsAvailable] = nodeReclaimFuncs{}\n\t\tsignalToReclaimFunc[evictionapi.SignalNodeFsInodesFree] = nodeReclaimFuncs{}\n\t\t// with an imagefs, imagefs pressure should delete unused images\n\t\tsignalToReclaimFunc[evictionapi.SignalImageFsAvailable] = nodeReclaimFuncs{containerGC.DeleteAllUnusedContainers, imageGC.DeleteUnusedImages}\n\t\tsignalToReclaimFunc[evictionapi.SignalImageFsInodesFree] = nodeReclaimFuncs{containerGC.DeleteAllUnusedContainers, imageGC.DeleteUnusedImages}\n\t} else {\n\t\t// without an imagefs, nodefs pressure should delete logs, and unused images\n\t\t// since imagefs and nodefs share a common device, they share common reclaim functions\n\t\tsignalToReclaimFunc[evictionapi.SignalNodeFsAvailable] = nodeReclaimFuncs{containerGC.DeleteAllUnusedContainers, imageGC.DeleteUnusedImages}\n\t\tsignalToReclaimFunc[evictionapi.SignalNodeFsInodesFree] = nodeReclaimFuncs{containerGC.DeleteAllUnusedContainers, imageGC.DeleteUnusedImages}\n\t\tsignalToReclaimFunc[evictionapi.SignalImageFsAvailable] = nodeReclaimFuncs{containerGC.DeleteAllUnusedContainers, imageGC.DeleteUnusedImages}\n\t\tsignalToReclaimFunc[evictionapi.SignalImageFsInodesFree] = nodeReclaimFuncs{containerGC.DeleteAllUnusedContainers, imageGC.DeleteUnusedImages}\n\t}\n\treturn signalToReclaimFunc\n}","line":{"from":984,"to":1004}} {"id":100006619,"name":"evictionMessage","signature":"func evictionMessage(resourceToReclaim v1.ResourceName, pod *v1.Pod, stats statsFunc, thresholds []evictionapi.Threshold, observations signalObservations) (message string, annotations map[string]string)","file":"pkg/kubelet/eviction/helpers.go","code":"// evictionMessage constructs a useful message about why an eviction occurred, and annotations to provide metadata about the eviction\nfunc evictionMessage(resourceToReclaim v1.ResourceName, pod *v1.Pod, stats statsFunc, thresholds []evictionapi.Threshold, observations signalObservations) (message string, annotations map[string]string) {\n\tannotations = make(map[string]string)\n\tmessage = fmt.Sprintf(nodeLowMessageFmt, resourceToReclaim)\n\tquantity, available := getThresholdMetInfo(resourceToReclaim, thresholds, observations)\n\tif quantity != nil \u0026\u0026 available != nil {\n\t\tmessage += fmt.Sprintf(thresholdMetMessageFmt, quantity, available)\n\t}\n\tcontainers := []string{}\n\tcontainerUsage := []string{}\n\tpodStats, ok := stats(pod)\n\tif !ok {\n\t\treturn\n\t}\n\tfor _, containerStats := range podStats.Containers {\n\t\tfor _, container := range pod.Spec.Containers {\n\t\t\tif container.Name == containerStats.Name {\n\t\t\t\trequests := container.Resources.Requests[resourceToReclaim]\n\t\t\t\tif utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) \u0026\u0026\n\t\t\t\t\t(resourceToReclaim == v1.ResourceMemory || resourceToReclaim == v1.ResourceCPU) {\n\t\t\t\t\tif cs, ok := podutil.GetContainerStatus(pod.Status.ContainerStatuses, container.Name); ok {\n\t\t\t\t\t\trequests = cs.AllocatedResources[resourceToReclaim]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tvar usage *resource.Quantity\n\t\t\t\tswitch resourceToReclaim {\n\t\t\t\tcase v1.ResourceEphemeralStorage:\n\t\t\t\t\tif containerStats.Rootfs != nil \u0026\u0026 containerStats.Rootfs.UsedBytes != nil \u0026\u0026 containerStats.Logs != nil \u0026\u0026 containerStats.Logs.UsedBytes != nil {\n\t\t\t\t\t\tusage = resource.NewQuantity(int64(*containerStats.Rootfs.UsedBytes+*containerStats.Logs.UsedBytes), resource.BinarySI)\n\t\t\t\t\t}\n\t\t\t\tcase v1.ResourceMemory:\n\t\t\t\t\tif containerStats.Memory != nil \u0026\u0026 containerStats.Memory.WorkingSetBytes != nil {\n\t\t\t\t\t\tusage = resource.NewQuantity(int64(*containerStats.Memory.WorkingSetBytes), resource.BinarySI)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif usage != nil \u0026\u0026 usage.Cmp(requests) \u003e 0 {\n\t\t\t\t\tmessage += fmt.Sprintf(containerMessageFmt, container.Name, usage.String(), requests.String(), resourceToReclaim)\n\t\t\t\t\tcontainers = append(containers, container.Name)\n\t\t\t\t\tcontainerUsage = append(containerUsage, usage.String())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tannotations[OffendingContainersKey] = strings.Join(containers, \",\")\n\tannotations[OffendingContainersUsageKey] = strings.Join(containerUsage, \",\")\n\tannotations[StarvedResourceKey] = string(resourceToReclaim)\n\treturn\n}","line":{"from":1006,"to":1053}} {"id":100006620,"name":"getThresholdMetInfo","signature":"func getThresholdMetInfo(resourceToReclaim v1.ResourceName, thresholds []evictionapi.Threshold, observations signalObservations) (quantity *resource.Quantity, available *resource.Quantity)","file":"pkg/kubelet/eviction/helpers.go","code":"// getThresholdMetInfo get the threshold quantity and available for the resource resourceToReclaim\nfunc getThresholdMetInfo(resourceToReclaim v1.ResourceName, thresholds []evictionapi.Threshold, observations signalObservations) (quantity *resource.Quantity, available *resource.Quantity) {\n\tfor i := range thresholds {\n\t\tthreshold := thresholds[i]\n\t\tif signalToResource[threshold.Signal] == resourceToReclaim {\n\t\t\tobserved, found := observations[threshold.Signal]\n\t\t\tif found {\n\t\t\t\tquantity := evictionapi.GetThresholdQuantity(threshold.Value, observed.capacity)\n\t\t\t\treturn quantity, observed.available\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, nil\n}","line":{"from":1055,"to":1068}} {"id":100006621,"name":"NewMemoryThresholdNotifier","signature":"func NewMemoryThresholdNotifier(threshold evictionapi.Threshold, cgroupRoot string, factory NotifierFactory, handler func(string)) (ThresholdNotifier, error)","file":"pkg/kubelet/eviction/memory_threshold_notifier.go","code":"// NewMemoryThresholdNotifier creates a ThresholdNotifier which is designed to respond to the given threshold.\n// UpdateThreshold must be called once before the threshold will be active.\nfunc NewMemoryThresholdNotifier(threshold evictionapi.Threshold, cgroupRoot string, factory NotifierFactory, handler func(string)) (ThresholdNotifier, error) {\n\tcgroups, err := cm.GetCgroupSubsystems()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcgpath, found := cgroups.MountPoints[\"memory\"]\n\tif !found || len(cgpath) == 0 {\n\t\treturn nil, fmt.Errorf(\"memory cgroup mount point not found\")\n\t}\n\tif isAllocatableEvictionThreshold(threshold) {\n\t\t// for allocatable thresholds, point the cgroup notifier at the allocatable cgroup\n\t\tcgpath += cgroupRoot\n\t}\n\treturn \u0026memoryThresholdNotifier{\n\t\tthreshold: threshold,\n\t\tcgroupPath: cgpath,\n\t\tevents: make(chan struct{}),\n\t\thandler: handler,\n\t\tfactory: factory,\n\t}, nil\n}","line":{"from":49,"to":71}} {"id":100006622,"name":"Start","signature":"func (m *memoryThresholdNotifier) Start()","file":"pkg/kubelet/eviction/memory_threshold_notifier.go","code":"func (m *memoryThresholdNotifier) Start() {\n\tklog.InfoS(\"Eviction manager: created memoryThresholdNotifier\", \"notifier\", m.Description())\n\tfor range m.events {\n\t\tm.handler(fmt.Sprintf(\"eviction manager: %s crossed\", m.Description()))\n\t}\n}","line":{"from":73,"to":78}} {"id":100006623,"name":"UpdateThreshold","signature":"func (m *memoryThresholdNotifier) UpdateThreshold(summary *statsapi.Summary) error","file":"pkg/kubelet/eviction/memory_threshold_notifier.go","code":"func (m *memoryThresholdNotifier) UpdateThreshold(summary *statsapi.Summary) error {\n\tmemoryStats := summary.Node.Memory\n\tif isAllocatableEvictionThreshold(m.threshold) {\n\t\tallocatableContainer, err := getSysContainer(summary.Node.SystemContainers, statsapi.SystemContainerPods)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmemoryStats = allocatableContainer.Memory\n\t}\n\tif memoryStats == nil || memoryStats.UsageBytes == nil || memoryStats.WorkingSetBytes == nil || memoryStats.AvailableBytes == nil {\n\t\treturn fmt.Errorf(\"summary was incomplete. Expected MemoryStats and all subfields to be non-nil, but got %+v\", memoryStats)\n\t}\n\t// Set threshold on usage to capacity - eviction_hard + inactive_file,\n\t// since we want to be notified when working_set = capacity - eviction_hard\n\tinactiveFile := resource.NewQuantity(int64(*memoryStats.UsageBytes-*memoryStats.WorkingSetBytes), resource.BinarySI)\n\tcapacity := resource.NewQuantity(int64(*memoryStats.AvailableBytes+*memoryStats.WorkingSetBytes), resource.BinarySI)\n\tevictionThresholdQuantity := evictionapi.GetThresholdQuantity(m.threshold.Value, capacity)\n\tmemcgThreshold := capacity.DeepCopy()\n\tmemcgThreshold.Sub(*evictionThresholdQuantity)\n\tmemcgThreshold.Add(*inactiveFile)\n\n\tklog.V(3).InfoS(\"Eviction manager: setting notifier to capacity\", \"notifier\", m.Description(), \"capacity\", memcgThreshold.String())\n\tif m.notifier != nil {\n\t\tm.notifier.Stop()\n\t}\n\tnewNotifier, err := m.factory.NewCgroupNotifier(m.cgroupPath, memoryUsageAttribute, memcgThreshold.Value())\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.notifier = newNotifier\n\tgo m.notifier.Start(m.events)\n\treturn nil\n}","line":{"from":80,"to":112}} {"id":100006624,"name":"Description","signature":"func (m *memoryThresholdNotifier) Description() string","file":"pkg/kubelet/eviction/memory_threshold_notifier.go","code":"func (m *memoryThresholdNotifier) Description() string {\n\tvar hard, allocatable string\n\tif isHardEvictionThreshold(m.threshold) {\n\t\thard = \"hard \"\n\t} else {\n\t\thard = \"soft \"\n\t}\n\tif isAllocatableEvictionThreshold(m.threshold) {\n\t\tallocatable = \"allocatable \"\n\t}\n\treturn fmt.Sprintf(\"%s%smemory eviction threshold\", hard, allocatable)\n}","line":{"from":114,"to":125}} {"id":100006625,"name":"NewCgroupNotifier","signature":"func (n *CgroupNotifierFactory) NewCgroupNotifier(path, attribute string, threshold int64) (CgroupNotifier, error)","file":"pkg/kubelet/eviction/memory_threshold_notifier.go","code":"// NewCgroupNotifier implements the NotifierFactory interface\nfunc (n *CgroupNotifierFactory) NewCgroupNotifier(path, attribute string, threshold int64) (CgroupNotifier, error) {\n\treturn NewCgroupNotifier(path, attribute, threshold)\n}","line":{"from":132,"to":135}} {"id":100006626,"name":"NewCgroupNotifier","signature":"func NewCgroupNotifier(path, attribute string, threshold int64) (CgroupNotifier, error)","file":"pkg/kubelet/eviction/threshold_notifier_linux.go","code":"// NewCgroupNotifier returns a linuxCgroupNotifier, which performs cgroup control operations required\n// to receive notifications from the cgroup when the threshold is crossed in either direction.\nfunc NewCgroupNotifier(path, attribute string, threshold int64) (CgroupNotifier, error) {\n\t// cgroupv2 does not support monitoring cgroup memory thresholds using cgroup.event_control.\n\t// Instead long term, on cgroupv2 kubelet should rely on combining usage of memory.low on root pods cgroup with inotify notifications on memory.events and or PSI pressure.\n\t// For now, let's return a fake \"disabled\" cgroup notifier on cgroupv2.\n\t// https://github.com/kubernetes/kubernetes/issues/106331\n\tif libcontainercgroups.IsCgroup2UnifiedMode() {\n\t\treturn \u0026disabledThresholdNotifier{}, nil\n\t}\n\n\tvar watchfd, eventfd, epfd, controlfd int\n\tvar err error\n\twatchfd, err = unix.Open(fmt.Sprintf(\"%s/%s\", path, attribute), unix.O_RDONLY|unix.O_CLOEXEC, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer unix.Close(watchfd)\n\tcontrolfd, err = unix.Open(fmt.Sprintf(\"%s/cgroup.event_control\", path), unix.O_WRONLY|unix.O_CLOEXEC, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer unix.Close(controlfd)\n\teventfd, err = unix.Eventfd(0, unix.EFD_CLOEXEC)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif eventfd \u003c 0 {\n\t\terr = fmt.Errorf(\"eventfd call failed\")\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\t// Close eventfd if we get an error later in initialization\n\t\tif err != nil {\n\t\t\tunix.Close(eventfd)\n\t\t}\n\t}()\n\tepfd, err = unix.EpollCreate1(unix.EPOLL_CLOEXEC)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif epfd \u003c 0 {\n\t\terr = fmt.Errorf(\"EpollCreate1 call failed\")\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\t// Close epfd if we get an error later in initialization\n\t\tif err != nil {\n\t\t\tunix.Close(epfd)\n\t\t}\n\t}()\n\tconfig := fmt.Sprintf(\"%d %d %d\", eventfd, watchfd, threshold)\n\t_, err = unix.Write(controlfd, []byte(config))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026linuxCgroupNotifier{\n\t\teventfd: eventfd,\n\t\tepfd: epfd,\n\t\tstop: make(chan struct{}),\n\t}, nil\n}","line":{"from":47,"to":108}} {"id":100006627,"name":"Start","signature":"func (n *linuxCgroupNotifier) Start(eventCh chan\u003c- struct{})","file":"pkg/kubelet/eviction/threshold_notifier_linux.go","code":"func (n *linuxCgroupNotifier) Start(eventCh chan\u003c- struct{}) {\n\terr := unix.EpollCtl(n.epfd, unix.EPOLL_CTL_ADD, n.eventfd, \u0026unix.EpollEvent{\n\t\tFd: int32(n.eventfd),\n\t\tEvents: unix.EPOLLIN,\n\t})\n\tif err != nil {\n\t\tklog.InfoS(\"Eviction manager: error adding epoll eventfd\", \"err\", err)\n\t\treturn\n\t}\n\tbuf := make([]byte, eventSize)\n\tfor {\n\t\tselect {\n\t\tcase \u003c-n.stop:\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\t\tevent, err := wait(n.epfd, n.eventfd, notifierRefreshInterval)\n\t\tif err != nil {\n\t\t\tklog.InfoS(\"Eviction manager: error while waiting for memcg events\", \"err\", err)\n\t\t\treturn\n\t\t} else if !event {\n\t\t\t// Timeout on wait. This is expected if the threshold was not crossed\n\t\t\tcontinue\n\t\t}\n\t\t// Consume the event from the eventfd\n\t\t_, err = unix.Read(n.eventfd, buf)\n\t\tif err != nil {\n\t\t\tklog.InfoS(\"Eviction manager: error reading memcg events\", \"err\", err)\n\t\t\treturn\n\t\t}\n\t\teventCh \u003c- struct{}{}\n\t}\n}","line":{"from":110,"to":142}} {"id":100006628,"name":"wait","signature":"func wait(epfd, eventfd int, timeout time.Duration) (bool, error)","file":"pkg/kubelet/eviction/threshold_notifier_linux.go","code":"// wait waits up to notifierRefreshInterval for an event on the Epoll FD for the\n// eventfd we are concerned about. It returns an error if one occurs, and true\n// if the consumer should read from the eventfd.\nfunc wait(epfd, eventfd int, timeout time.Duration) (bool, error) {\n\tevents := make([]unix.EpollEvent, numFdEvents+1)\n\ttimeoutMS := int(timeout / time.Millisecond)\n\tn, err := unix.EpollWait(epfd, events, timeoutMS)\n\tif n == -1 {\n\t\tif err == unix.EINTR {\n\t\t\t// Interrupt, ignore the error\n\t\t\treturn false, nil\n\t\t}\n\t\treturn false, err\n\t}\n\tif n == 0 {\n\t\t// Timeout\n\t\treturn false, nil\n\t}\n\tif n \u003e numFdEvents {\n\t\treturn false, fmt.Errorf(\"epoll_wait returned more events than we know what to do with\")\n\t}\n\tfor _, event := range events[:n] {\n\t\tif event.Fd == int32(eventfd) {\n\t\t\tif event.Events\u0026unix.EPOLLHUP != 0 || event.Events\u0026unix.EPOLLERR != 0 || event.Events\u0026unix.EPOLLIN != 0 {\n\t\t\t\t// EPOLLHUP: should not happen, but if it does, treat it as a wakeup.\n\n\t\t\t\t// EPOLLERR: If an error is waiting on the file descriptor, we should pretend\n\t\t\t\t// something is ready to read, and let unix.Read pick up the error.\n\n\t\t\t\t// EPOLLIN: There is data to read.\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\t}\n\t// An event occurred that we don't care about.\n\treturn false, nil\n}","line":{"from":144,"to":180}} {"id":100006629,"name":"Stop","signature":"func (n *linuxCgroupNotifier) Stop()","file":"pkg/kubelet/eviction/threshold_notifier_linux.go","code":"func (n *linuxCgroupNotifier) Stop() {\n\tn.stopLock.Lock()\n\tdefer n.stopLock.Unlock()\n\tselect {\n\tcase \u003c-n.stop:\n\t\t// the linuxCgroupNotifier is already stopped\n\t\treturn\n\tdefault:\n\t}\n\tunix.Close(n.eventfd)\n\tunix.Close(n.epfd)\n\tclose(n.stop)\n}","line":{"from":182,"to":194}} {"id":100006630,"name":"Start","signature":"func (*disabledThresholdNotifier) Start(_ chan\u003c- struct{}) {}","file":"pkg/kubelet/eviction/threshold_notifier_linux.go","code":"func (*disabledThresholdNotifier) Start(_ chan\u003c- struct{}) {}","line":{"from":199,"to":199}} {"id":100006631,"name":"Stop","signature":"func (*disabledThresholdNotifier) Stop() {}","file":"pkg/kubelet/eviction/threshold_notifier_linux.go","code":"func (*disabledThresholdNotifier) Stop() {}","line":{"from":200,"to":200}} {"id":100006632,"name":"NewCgroupNotifier","signature":"func NewCgroupNotifier(path, attribute string, threshold int64) (CgroupNotifier, error)","file":"pkg/kubelet/eviction/threshold_notifier_unsupported.go","code":"// NewCgroupNotifier creates a cgroup notifier that does nothing because cgroups do not exist on non-linux systems.\nfunc NewCgroupNotifier(path, attribute string, threshold int64) (CgroupNotifier, error) {\n\tklog.V(5).InfoS(\"cgroup notifications not supported\")\n\treturn \u0026unsupportedThresholdNotifier{}, nil\n}","line":{"from":24,"to":28}} {"id":100006633,"name":"Start","signature":"func (*unsupportedThresholdNotifier) Start(_ chan\u003c- struct{}) {}","file":"pkg/kubelet/eviction/threshold_notifier_unsupported.go","code":"func (*unsupportedThresholdNotifier) Start(_ chan\u003c- struct{}) {}","line":{"from":32,"to":32}} {"id":100006634,"name":"Stop","signature":"func (*unsupportedThresholdNotifier) Stop() {}","file":"pkg/kubelet/eviction/threshold_notifier_unsupported.go","code":"func (*unsupportedThresholdNotifier) Stop() {}","line":{"from":34,"to":34}} {"id":100006635,"name":"throttleImagePulling","signature":"func throttleImagePulling(imageService kubecontainer.ImageService, qps float32, burst int) kubecontainer.ImageService","file":"pkg/kubelet/images/helpers.go","code":"// throttleImagePulling wraps kubecontainer.ImageService to throttle image\n// pulling based on the given QPS and burst limits. If QPS is zero, defaults\n// to no throttling.\nfunc throttleImagePulling(imageService kubecontainer.ImageService, qps float32, burst int) kubecontainer.ImageService {\n\tif qps == 0.0 {\n\t\treturn imageService\n\t}\n\treturn \u0026throttledImageService{\n\t\tImageService: imageService,\n\t\tlimiter: flowcontrol.NewTokenBucketRateLimiter(qps, burst),\n\t}\n}","line":{"from":29,"to":40}} {"id":100006636,"name":"PullImage","signature":"func (ts throttledImageService) PullImage(ctx context.Context, image kubecontainer.ImageSpec, secrets []v1.Secret, podSandboxConfig *runtimeapi.PodSandboxConfig) (string, error)","file":"pkg/kubelet/images/helpers.go","code":"func (ts throttledImageService) PullImage(ctx context.Context, image kubecontainer.ImageSpec, secrets []v1.Secret, podSandboxConfig *runtimeapi.PodSandboxConfig) (string, error) {\n\tif ts.limiter.TryAccept() {\n\t\treturn ts.ImageService.PullImage(ctx, image, secrets, podSandboxConfig)\n\t}\n\treturn \"\", fmt.Errorf(\"pull QPS exceeded\")\n}","line":{"from":47,"to":52}} {"id":100006637,"name":"set","signature":"func (i *imageCache) set(images []container.Image)","file":"pkg/kubelet/images/image_gc_manager.go","code":"// set sorts the input list and updates image cache.\n// 'i' takes ownership of the list, you should not reference the list again\n// after calling this function.\nfunc (i *imageCache) set(images []container.Image) {\n\ti.Lock()\n\tdefer i.Unlock()\n\t// The image list needs to be sorted when it gets read and used in\n\t// setNodeStatusImages. We sort the list on write instead of on read,\n\t// because the image cache is more often read than written\n\tsort.Sort(sliceutils.ByImageSize(images))\n\ti.images = images\n}","line":{"from":124,"to":135}} {"id":100006638,"name":"get","signature":"func (i *imageCache) get() []container.Image","file":"pkg/kubelet/images/image_gc_manager.go","code":"// get gets image list from image cache.\n// NOTE: The caller of get() should not do mutating operations on the\n// returned list that could cause data race against other readers (e.g.\n// in-place sorting the returned list)\nfunc (i *imageCache) get() []container.Image {\n\ti.Lock()\n\tdefer i.Unlock()\n\treturn i.images\n}","line":{"from":137,"to":145}} {"id":100006639,"name":"NewImageGCManager","signature":"func NewImageGCManager(runtime container.Runtime, statsProvider StatsProvider, recorder record.EventRecorder, nodeRef *v1.ObjectReference, policy ImageGCPolicy, sandboxImage string, tracerProvider trace.TracerProvider) (ImageGCManager, error)","file":"pkg/kubelet/images/image_gc_manager.go","code":"// NewImageGCManager instantiates a new ImageGCManager object.\nfunc NewImageGCManager(runtime container.Runtime, statsProvider StatsProvider, recorder record.EventRecorder, nodeRef *v1.ObjectReference, policy ImageGCPolicy, sandboxImage string, tracerProvider trace.TracerProvider) (ImageGCManager, error) {\n\t// Validate policy.\n\tif policy.HighThresholdPercent \u003c 0 || policy.HighThresholdPercent \u003e 100 {\n\t\treturn nil, fmt.Errorf(\"invalid HighThresholdPercent %d, must be in range [0-100]\", policy.HighThresholdPercent)\n\t}\n\tif policy.LowThresholdPercent \u003c 0 || policy.LowThresholdPercent \u003e 100 {\n\t\treturn nil, fmt.Errorf(\"invalid LowThresholdPercent %d, must be in range [0-100]\", policy.LowThresholdPercent)\n\t}\n\tif policy.LowThresholdPercent \u003e policy.HighThresholdPercent {\n\t\treturn nil, fmt.Errorf(\"LowThresholdPercent %d can not be higher than HighThresholdPercent %d\", policy.LowThresholdPercent, policy.HighThresholdPercent)\n\t}\n\ttracer := tracerProvider.Tracer(instrumentationScope)\n\tim := \u0026realImageGCManager{\n\t\truntime: runtime,\n\t\tpolicy: policy,\n\t\timageRecords: make(map[string]*imageRecord),\n\t\tstatsProvider: statsProvider,\n\t\trecorder: recorder,\n\t\tnodeRef: nodeRef,\n\t\tinitialized: false,\n\t\tsandboxImage: sandboxImage,\n\t\ttracer: tracer,\n\t}\n\n\treturn im, nil\n}","line":{"from":162,"to":188}} {"id":100006640,"name":"Start","signature":"func (im *realImageGCManager) Start()","file":"pkg/kubelet/images/image_gc_manager.go","code":"func (im *realImageGCManager) Start() {\n\tctx := context.Background()\n\tgo wait.Until(func() {\n\t\t// Initial detection make detected time \"unknown\" in the past.\n\t\tvar ts time.Time\n\t\tif im.initialized {\n\t\t\tts = time.Now()\n\t\t}\n\t\t_, err := im.detectImages(ctx, ts)\n\t\tif err != nil {\n\t\t\tklog.InfoS(\"Failed to monitor images\", \"err\", err)\n\t\t} else {\n\t\t\tim.initialized = true\n\t\t}\n\t}, 5*time.Minute, wait.NeverStop)\n\n\t// Start a goroutine periodically updates image cache.\n\tgo wait.Until(func() {\n\t\timages, err := im.runtime.ListImages(ctx)\n\t\tif err != nil {\n\t\t\tklog.InfoS(\"Failed to update image list\", \"err\", err)\n\t\t} else {\n\t\t\tim.imageCache.set(images)\n\t\t}\n\t}, 30*time.Second, wait.NeverStop)\n\n}","line":{"from":190,"to":216}} {"id":100006641,"name":"GetImageList","signature":"func (im *realImageGCManager) GetImageList() ([]container.Image, error)","file":"pkg/kubelet/images/image_gc_manager.go","code":"// Get a list of images on this node\nfunc (im *realImageGCManager) GetImageList() ([]container.Image, error) {\n\treturn im.imageCache.get(), nil\n}","line":{"from":218,"to":221}} {"id":100006642,"name":"detectImages","signature":"func (im *realImageGCManager) detectImages(ctx context.Context, detectTime time.Time) (sets.String, error)","file":"pkg/kubelet/images/image_gc_manager.go","code":"func (im *realImageGCManager) detectImages(ctx context.Context, detectTime time.Time) (sets.String, error) {\n\timagesInUse := sets.NewString()\n\n\t// Always consider the container runtime pod sandbox image in use\n\timageRef, err := im.runtime.GetImageRef(ctx, container.ImageSpec{Image: im.sandboxImage})\n\tif err == nil \u0026\u0026 imageRef != \"\" {\n\t\timagesInUse.Insert(imageRef)\n\t}\n\n\timages, err := im.runtime.ListImages(ctx)\n\tif err != nil {\n\t\treturn imagesInUse, err\n\t}\n\tpods, err := im.runtime.GetPods(ctx, true)\n\tif err != nil {\n\t\treturn imagesInUse, err\n\t}\n\n\t// Make a set of images in use by containers.\n\tfor _, pod := range pods {\n\t\tfor _, container := range pod.Containers {\n\t\t\tklog.V(5).InfoS(\"Container uses image\", \"pod\", klog.KRef(pod.Namespace, pod.Name), \"containerName\", container.Name, \"containerImage\", container.Image, \"imageID\", container.ImageID)\n\t\t\timagesInUse.Insert(container.ImageID)\n\t\t}\n\t}\n\n\t// Add new images and record those being used.\n\tnow := time.Now()\n\tcurrentImages := sets.NewString()\n\tim.imageRecordsLock.Lock()\n\tdefer im.imageRecordsLock.Unlock()\n\tfor _, image := range images {\n\t\tklog.V(5).InfoS(\"Adding image ID to currentImages\", \"imageID\", image.ID)\n\t\tcurrentImages.Insert(image.ID)\n\n\t\t// New image, set it as detected now.\n\t\tif _, ok := im.imageRecords[image.ID]; !ok {\n\t\t\tklog.V(5).InfoS(\"Image ID is new\", \"imageID\", image.ID)\n\t\t\tim.imageRecords[image.ID] = \u0026imageRecord{\n\t\t\t\tfirstDetected: detectTime,\n\t\t\t}\n\t\t}\n\n\t\t// Set last used time to now if the image is being used.\n\t\tif isImageUsed(image.ID, imagesInUse) {\n\t\t\tklog.V(5).InfoS(\"Setting Image ID lastUsed\", \"imageID\", image.ID, \"lastUsed\", now)\n\t\t\tim.imageRecords[image.ID].lastUsed = now\n\t\t}\n\n\t\tklog.V(5).InfoS(\"Image ID has size\", \"imageID\", image.ID, \"size\", image.Size)\n\t\tim.imageRecords[image.ID].size = image.Size\n\n\t\tklog.V(5).InfoS(\"Image ID is pinned\", \"imageID\", image.ID, \"pinned\", image.Pinned)\n\t\tim.imageRecords[image.ID].pinned = image.Pinned\n\t}\n\n\t// Remove old images from our records.\n\tfor image := range im.imageRecords {\n\t\tif !currentImages.Has(image) {\n\t\t\tklog.V(5).InfoS(\"Image ID is no longer present; removing from imageRecords\", \"imageID\", image)\n\t\t\tdelete(im.imageRecords, image)\n\t\t}\n\t}\n\n\treturn imagesInUse, nil\n}","line":{"from":223,"to":288}} {"id":100006643,"name":"GarbageCollect","signature":"func (im *realImageGCManager) GarbageCollect(ctx context.Context) error","file":"pkg/kubelet/images/image_gc_manager.go","code":"func (im *realImageGCManager) GarbageCollect(ctx context.Context) error {\n\tctx, otelSpan := im.tracer.Start(ctx, \"Images/GarbageCollect\")\n\tdefer otelSpan.End()\n\t// Get disk usage on disk holding images.\n\tfsStats, err := im.statsProvider.ImageFsStats(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar capacity, available int64\n\tif fsStats.CapacityBytes != nil {\n\t\tcapacity = int64(*fsStats.CapacityBytes)\n\t}\n\tif fsStats.AvailableBytes != nil {\n\t\tavailable = int64(*fsStats.AvailableBytes)\n\t}\n\n\tif available \u003e capacity {\n\t\tklog.InfoS(\"Availability is larger than capacity\", \"available\", available, \"capacity\", capacity)\n\t\tavailable = capacity\n\t}\n\n\t// Check valid capacity.\n\tif capacity == 0 {\n\t\terr := goerrors.New(\"invalid capacity 0 on image filesystem\")\n\t\tim.recorder.Eventf(im.nodeRef, v1.EventTypeWarning, events.InvalidDiskCapacity, err.Error())\n\t\treturn err\n\t}\n\n\t// If over the max threshold, free enough to place us at the lower threshold.\n\tusagePercent := 100 - int(available*100/capacity)\n\tif usagePercent \u003e= im.policy.HighThresholdPercent {\n\t\tamountToFree := capacity*int64(100-im.policy.LowThresholdPercent)/100 - available\n\t\tklog.InfoS(\"Disk usage on image filesystem is over the high threshold, trying to free bytes down to the low threshold\", \"usage\", usagePercent, \"highThreshold\", im.policy.HighThresholdPercent, \"amountToFree\", amountToFree, \"lowThreshold\", im.policy.LowThresholdPercent)\n\t\tfreed, err := im.freeSpace(ctx, amountToFree, time.Now())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif freed \u003c amountToFree {\n\t\t\terr := fmt.Errorf(\"Failed to garbage collect required amount of images. Attempted to free %d bytes, but only found %d bytes eligible to free.\", amountToFree, freed)\n\t\t\tim.recorder.Eventf(im.nodeRef, v1.EventTypeWarning, events.FreeDiskSpaceFailed, err.Error())\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":290,"to":337}} {"id":100006644,"name":"DeleteUnusedImages","signature":"func (im *realImageGCManager) DeleteUnusedImages(ctx context.Context) error","file":"pkg/kubelet/images/image_gc_manager.go","code":"func (im *realImageGCManager) DeleteUnusedImages(ctx context.Context) error {\n\tklog.InfoS(\"Attempting to delete unused images\")\n\t_, err := im.freeSpace(ctx, math.MaxInt64, time.Now())\n\treturn err\n}","line":{"from":339,"to":343}} {"id":100006645,"name":"freeSpace","signature":"func (im *realImageGCManager) freeSpace(ctx context.Context, bytesToFree int64, freeTime time.Time) (int64, error)","file":"pkg/kubelet/images/image_gc_manager.go","code":"// Tries to free bytesToFree worth of images on the disk.\n//\n// Returns the number of bytes free and an error if any occurred. The number of\n// bytes freed is always returned.\n// Note that error may be nil and the number of bytes free may be less\n// than bytesToFree.\nfunc (im *realImageGCManager) freeSpace(ctx context.Context, bytesToFree int64, freeTime time.Time) (int64, error) {\n\timagesInUse, err := im.detectImages(ctx, freeTime)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tim.imageRecordsLock.Lock()\n\tdefer im.imageRecordsLock.Unlock()\n\n\t// Get all images in eviction order.\n\timages := make([]evictionInfo, 0, len(im.imageRecords))\n\tfor image, record := range im.imageRecords {\n\t\tif isImageUsed(image, imagesInUse) {\n\t\t\tklog.V(5).InfoS(\"Image ID is being used\", \"imageID\", image)\n\t\t\tcontinue\n\t\t}\n\t\t// Check if image is pinned, prevent garbage collection\n\t\tif record.pinned {\n\t\t\tklog.V(5).InfoS(\"Image is pinned, skipping garbage collection\", \"imageID\", image)\n\t\t\tcontinue\n\n\t\t}\n\t\timages = append(images, evictionInfo{\n\t\t\tid: image,\n\t\t\timageRecord: *record,\n\t\t})\n\t}\n\tsort.Sort(byLastUsedAndDetected(images))\n\n\t// Delete unused images until we've freed up enough space.\n\tvar deletionErrors []error\n\tspaceFreed := int64(0)\n\tfor _, image := range images {\n\t\tklog.V(5).InfoS(\"Evaluating image ID for possible garbage collection\", \"imageID\", image.id)\n\t\t// Images that are currently in used were given a newer lastUsed.\n\t\tif image.lastUsed.Equal(freeTime) || image.lastUsed.After(freeTime) {\n\t\t\tklog.V(5).InfoS(\"Image ID was used too recently, not eligible for garbage collection\", \"imageID\", image.id, \"lastUsed\", image.lastUsed, \"freeTime\", freeTime)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Avoid garbage collect the image if the image is not old enough.\n\t\t// In such a case, the image may have just been pulled down, and will be used by a container right away.\n\n\t\tif freeTime.Sub(image.firstDetected) \u003c im.policy.MinAge {\n\t\t\tklog.V(5).InfoS(\"Image ID's age is less than the policy's minAge, not eligible for garbage collection\", \"imageID\", image.id, \"age\", freeTime.Sub(image.firstDetected), \"minAge\", im.policy.MinAge)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Remove image. Continue despite errors.\n\t\tklog.InfoS(\"Removing image to free bytes\", \"imageID\", image.id, \"size\", image.size)\n\t\terr := im.runtime.RemoveImage(ctx, container.ImageSpec{Image: image.id})\n\t\tif err != nil {\n\t\t\tdeletionErrors = append(deletionErrors, err)\n\t\t\tcontinue\n\t\t}\n\t\tdelete(im.imageRecords, image.id)\n\t\tspaceFreed += image.size\n\n\t\tif spaceFreed \u003e= bytesToFree {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif len(deletionErrors) \u003e 0 {\n\t\treturn spaceFreed, fmt.Errorf(\"wanted to free %d bytes, but freed %d bytes space with errors in image deletion: %v\", bytesToFree, spaceFreed, errors.NewAggregate(deletionErrors))\n\t}\n\treturn spaceFreed, nil\n}","line":{"from":345,"to":418}} {"id":100006646,"name":"Len","signature":"func (ev byLastUsedAndDetected) Len() int { return len(ev) }","file":"pkg/kubelet/images/image_gc_manager.go","code":"func (ev byLastUsedAndDetected) Len() int { return len(ev) }","line":{"from":427,"to":427}} {"id":100006647,"name":"Swap","signature":"func (ev byLastUsedAndDetected) Swap(i, j int) { ev[i], ev[j] = ev[j], ev[i] }","file":"pkg/kubelet/images/image_gc_manager.go","code":"func (ev byLastUsedAndDetected) Swap(i, j int) { ev[i], ev[j] = ev[j], ev[i] }","line":{"from":428,"to":428}} {"id":100006648,"name":"Less","signature":"func (ev byLastUsedAndDetected) Less(i, j int) bool","file":"pkg/kubelet/images/image_gc_manager.go","code":"func (ev byLastUsedAndDetected) Less(i, j int) bool {\n\t// Sort by last used, break ties by detected.\n\tif ev[i].lastUsed.Equal(ev[j].lastUsed) {\n\t\treturn ev[i].firstDetected.Before(ev[j].firstDetected)\n\t}\n\treturn ev[i].lastUsed.Before(ev[j].lastUsed)\n}","line":{"from":429,"to":435}} {"id":100006649,"name":"isImageUsed","signature":"func isImageUsed(imageID string, imagesInUse sets.String) bool","file":"pkg/kubelet/images/image_gc_manager.go","code":"func isImageUsed(imageID string, imagesInUse sets.String) bool {\n\t// Check the image ID.\n\tif _, ok := imagesInUse[imageID]; ok {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":437,"to":443}} {"id":100006650,"name":"NewImageManager","signature":"func NewImageManager(recorder record.EventRecorder, imageService kubecontainer.ImageService, imageBackOff *flowcontrol.Backoff, serialized bool, maxParallelImagePulls *int32, qps float32, burst int, podPullingTimeRecorder ImagePodPullingTimeRecorder) ImageManager","file":"pkg/kubelet/images/image_manager.go","code":"// NewImageManager instantiates a new ImageManager object.\nfunc NewImageManager(recorder record.EventRecorder, imageService kubecontainer.ImageService, imageBackOff *flowcontrol.Backoff, serialized bool, maxParallelImagePulls *int32, qps float32, burst int, podPullingTimeRecorder ImagePodPullingTimeRecorder) ImageManager {\n\timageService = throttleImagePulling(imageService, qps, burst)\n\n\tvar puller imagePuller\n\tif serialized {\n\t\tpuller = newSerialImagePuller(imageService)\n\t} else {\n\t\tpuller = newParallelImagePuller(imageService, maxParallelImagePulls)\n\t}\n\treturn \u0026imageManager{\n\t\trecorder: recorder,\n\t\timageService: imageService,\n\t\tbackOff: imageBackOff,\n\t\tpuller: puller,\n\t\tpodPullingTimeRecorder: podPullingTimeRecorder,\n\t}\n}","line":{"from":54,"to":71}} {"id":100006651,"name":"shouldPullImage","signature":"func shouldPullImage(container *v1.Container, imagePresent bool) bool","file":"pkg/kubelet/images/image_manager.go","code":"// shouldPullImage returns whether we should pull an image according to\n// the presence and pull policy of the image.\nfunc shouldPullImage(container *v1.Container, imagePresent bool) bool {\n\tif container.ImagePullPolicy == v1.PullNever {\n\t\treturn false\n\t}\n\n\tif container.ImagePullPolicy == v1.PullAlways ||\n\t\t(container.ImagePullPolicy == v1.PullIfNotPresent \u0026\u0026 (!imagePresent)) {\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":73,"to":86}} {"id":100006652,"name":"logIt","signature":"func (m *imageManager) logIt(ref *v1.ObjectReference, eventtype, event, prefix, msg string, logFn func(args ...interface{}))","file":"pkg/kubelet/images/image_manager.go","code":"// records an event using ref, event msg. log to glog using prefix, msg, logFn\nfunc (m *imageManager) logIt(ref *v1.ObjectReference, eventtype, event, prefix, msg string, logFn func(args ...interface{})) {\n\tif ref != nil {\n\t\tm.recorder.Event(ref, eventtype, event, msg)\n\t} else {\n\t\tlogFn(fmt.Sprint(prefix, \" \", msg))\n\t}\n}","line":{"from":88,"to":95}} {"id":100006653,"name":"EnsureImageExists","signature":"func (m *imageManager) EnsureImageExists(ctx context.Context, pod *v1.Pod, container *v1.Container, pullSecrets []v1.Secret, podSandboxConfig *runtimeapi.PodSandboxConfig) (string, string, error)","file":"pkg/kubelet/images/image_manager.go","code":"// EnsureImageExists pulls the image for the specified pod and container, and returns\n// (imageRef, error message, error).\nfunc (m *imageManager) EnsureImageExists(ctx context.Context, pod *v1.Pod, container *v1.Container, pullSecrets []v1.Secret, podSandboxConfig *runtimeapi.PodSandboxConfig) (string, string, error) {\n\tlogPrefix := fmt.Sprintf(\"%s/%s/%s\", pod.Namespace, pod.Name, container.Image)\n\tref, err := kubecontainer.GenerateContainerRef(pod, container)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Couldn't make a ref to pod\", \"pod\", klog.KObj(pod), \"containerName\", container.Name)\n\t}\n\n\t// If the image contains no tag or digest, a default tag should be applied.\n\timage, err := applyDefaultImageTag(container.Image)\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"Failed to apply default image tag %q: %v\", container.Image, err)\n\t\tm.logIt(ref, v1.EventTypeWarning, events.FailedToInspectImage, logPrefix, msg, klog.Warning)\n\t\treturn \"\", msg, ErrInvalidImageName\n\t}\n\n\tvar podAnnotations []kubecontainer.Annotation\n\tfor k, v := range pod.GetAnnotations() {\n\t\tpodAnnotations = append(podAnnotations, kubecontainer.Annotation{\n\t\t\tName: k,\n\t\t\tValue: v,\n\t\t})\n\t}\n\n\tspec := kubecontainer.ImageSpec{\n\t\tImage: image,\n\t\tAnnotations: podAnnotations,\n\t}\n\timageRef, err := m.imageService.GetImageRef(ctx, spec)\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"Failed to inspect image %q: %v\", container.Image, err)\n\t\tm.logIt(ref, v1.EventTypeWarning, events.FailedToInspectImage, logPrefix, msg, klog.Warning)\n\t\treturn \"\", msg, ErrImageInspect\n\t}\n\n\tpresent := imageRef != \"\"\n\tif !shouldPullImage(container, present) {\n\t\tif present {\n\t\t\tmsg := fmt.Sprintf(\"Container image %q already present on machine\", container.Image)\n\t\t\tm.logIt(ref, v1.EventTypeNormal, events.PulledImage, logPrefix, msg, klog.Info)\n\t\t\treturn imageRef, \"\", nil\n\t\t}\n\t\tmsg := fmt.Sprintf(\"Container image %q is not present with pull policy of Never\", container.Image)\n\t\tm.logIt(ref, v1.EventTypeWarning, events.ErrImageNeverPullPolicy, logPrefix, msg, klog.Warning)\n\t\treturn \"\", msg, ErrImageNeverPull\n\t}\n\n\tbackOffKey := fmt.Sprintf(\"%s_%s\", pod.UID, container.Image)\n\tif m.backOff.IsInBackOffSinceUpdate(backOffKey, m.backOff.Clock.Now()) {\n\t\tmsg := fmt.Sprintf(\"Back-off pulling image %q\", container.Image)\n\t\tm.logIt(ref, v1.EventTypeNormal, events.BackOffPullImage, logPrefix, msg, klog.Info)\n\t\treturn \"\", msg, ErrImagePullBackOff\n\t}\n\tm.podPullingTimeRecorder.RecordImageStartedPulling(pod.UID)\n\tm.logIt(ref, v1.EventTypeNormal, events.PullingImage, logPrefix, fmt.Sprintf(\"Pulling image %q\", container.Image), klog.Info)\n\tstartTime := time.Now()\n\tpullChan := make(chan pullResult)\n\tm.puller.pullImage(ctx, spec, pullSecrets, pullChan, podSandboxConfig)\n\timagePullResult := \u003c-pullChan\n\tif imagePullResult.err != nil {\n\t\tm.logIt(ref, v1.EventTypeWarning, events.FailedToPullImage, logPrefix, fmt.Sprintf(\"Failed to pull image %q: %v\", container.Image, imagePullResult.err), klog.Warning)\n\t\tm.backOff.Next(backOffKey, m.backOff.Clock.Now())\n\t\tif imagePullResult.err == ErrRegistryUnavailable {\n\t\t\tmsg := fmt.Sprintf(\"image pull failed for %s because the registry is unavailable.\", container.Image)\n\t\t\treturn \"\", msg, imagePullResult.err\n\t\t}\n\n\t\treturn \"\", imagePullResult.err.Error(), ErrImagePull\n\t}\n\tm.podPullingTimeRecorder.RecordImageFinishedPulling(pod.UID)\n\tm.logIt(ref, v1.EventTypeNormal, events.PulledImage, logPrefix, fmt.Sprintf(\"Successfully pulled image %q in %v (%v including waiting)\", container.Image, imagePullResult.pullDuration, time.Since(startTime)), klog.Info)\n\tm.backOff.GC()\n\treturn imagePullResult.imageRef, \"\", nil\n}","line":{"from":97,"to":171}} {"id":100006654,"name":"applyDefaultImageTag","signature":"func applyDefaultImageTag(image string) (string, error)","file":"pkg/kubelet/images/image_manager.go","code":"// applyDefaultImageTag parses a docker image string, if it doesn't contain any tag or digest,\n// a default tag will be applied.\nfunc applyDefaultImageTag(image string) (string, error) {\n\tnamed, err := dockerref.ParseNormalizedNamed(image)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"couldn't parse image reference %q: %v\", image, err)\n\t}\n\t_, isTagged := named.(dockerref.Tagged)\n\t_, isDigested := named.(dockerref.Digested)\n\tif !isTagged \u0026\u0026 !isDigested {\n\t\t// we just concatenate the image name with the default tag here instead\n\t\t// of using dockerref.WithTag(named, ...) because that would cause the\n\t\t// image to be fully qualified as docker.io/$name if it's a short name\n\t\t// (e.g. just busybox). We don't want that to happen to keep the CRI\n\t\t// agnostic wrt image names and default hostnames.\n\t\timage = image + \":latest\"\n\t}\n\treturn image, nil\n}","line":{"from":173,"to":191}} {"id":100006655,"name":"newParallelImagePuller","signature":"func newParallelImagePuller(imageService kubecontainer.ImageService, maxParallelImagePulls *int32) imagePuller","file":"pkg/kubelet/images/puller.go","code":"func newParallelImagePuller(imageService kubecontainer.ImageService, maxParallelImagePulls *int32) imagePuller {\n\tif maxParallelImagePulls == nil || *maxParallelImagePulls \u003c 1 {\n\t\treturn \u0026parallelImagePuller{imageService, nil}\n\t}\n\treturn \u0026parallelImagePuller{imageService, make(chan struct{}, *maxParallelImagePulls)}\n}","line":{"from":46,"to":51}} {"id":100006656,"name":"pullImage","signature":"func (pip *parallelImagePuller) pullImage(ctx context.Context, spec kubecontainer.ImageSpec, pullSecrets []v1.Secret, pullChan chan\u003c- pullResult, podSandboxConfig *runtimeapi.PodSandboxConfig)","file":"pkg/kubelet/images/puller.go","code":"func (pip *parallelImagePuller) pullImage(ctx context.Context, spec kubecontainer.ImageSpec, pullSecrets []v1.Secret, pullChan chan\u003c- pullResult, podSandboxConfig *runtimeapi.PodSandboxConfig) {\n\tgo func() {\n\t\tif pip.tokens != nil {\n\t\t\tpip.tokens \u003c- struct{}{}\n\t\t\tdefer func() { \u003c-pip.tokens }()\n\t\t}\n\t\tstartTime := time.Now()\n\t\timageRef, err := pip.imageService.PullImage(ctx, spec, pullSecrets, podSandboxConfig)\n\t\tpullChan \u003c- pullResult{\n\t\t\timageRef: imageRef,\n\t\t\terr: err,\n\t\t\tpullDuration: time.Since(startTime),\n\t\t}\n\t}()\n}","line":{"from":53,"to":67}} {"id":100006657,"name":"newSerialImagePuller","signature":"func newSerialImagePuller(imageService kubecontainer.ImageService) imagePuller","file":"pkg/kubelet/images/puller.go","code":"func newSerialImagePuller(imageService kubecontainer.ImageService) imagePuller {\n\timagePuller := \u0026serialImagePuller{imageService, make(chan *imagePullRequest, maxImagePullRequests)}\n\tgo wait.Until(imagePuller.processImagePullRequests, time.Second, wait.NeverStop)\n\treturn imagePuller\n}","line":{"from":77,"to":81}} {"id":100006658,"name":"pullImage","signature":"func (sip *serialImagePuller) pullImage(ctx context.Context, spec kubecontainer.ImageSpec, pullSecrets []v1.Secret, pullChan chan\u003c- pullResult, podSandboxConfig *runtimeapi.PodSandboxConfig)","file":"pkg/kubelet/images/puller.go","code":"func (sip *serialImagePuller) pullImage(ctx context.Context, spec kubecontainer.ImageSpec, pullSecrets []v1.Secret, pullChan chan\u003c- pullResult, podSandboxConfig *runtimeapi.PodSandboxConfig) {\n\tsip.pullRequests \u003c- \u0026imagePullRequest{\n\t\tctx: ctx,\n\t\tspec: spec,\n\t\tpullSecrets: pullSecrets,\n\t\tpullChan: pullChan,\n\t\tpodSandboxConfig: podSandboxConfig,\n\t}\n}","line":{"from":91,"to":99}} {"id":100006659,"name":"processImagePullRequests","signature":"func (sip *serialImagePuller) processImagePullRequests()","file":"pkg/kubelet/images/puller.go","code":"func (sip *serialImagePuller) processImagePullRequests() {\n\tfor pullRequest := range sip.pullRequests {\n\t\tstartTime := time.Now()\n\t\timageRef, err := sip.imageService.PullImage(pullRequest.ctx, pullRequest.spec, pullRequest.pullSecrets, pullRequest.podSandboxConfig)\n\t\tpullRequest.pullChan \u003c- pullResult{\n\t\t\timageRef: imageRef,\n\t\t\terr: err,\n\t\t\tpullDuration: time.Since(startTime),\n\t\t}\n\t}\n}","line":{"from":101,"to":111}} {"id":100006660,"name":"getContainerEtcHostsPath","signature":"func getContainerEtcHostsPath() string","file":"pkg/kubelet/kubelet.go","code":"func getContainerEtcHostsPath() string {\n\tif sysruntime.GOOS == \"windows\" {\n\t\treturn windowsEtcHostsPath\n\t}\n\treturn linuxEtcHostsPath\n}","line":{"from":212,"to":217}} {"id":100006661,"name":"makePodSourceConfig","signature":"func makePodSourceConfig(kubeCfg *kubeletconfiginternal.KubeletConfiguration, kubeDeps *Dependencies, nodeName types.NodeName, nodeHasSynced func() bool) (*config.PodConfig, error)","file":"pkg/kubelet/kubelet.go","code":"// makePodSourceConfig creates a config.PodConfig from the given\n// KubeletConfiguration or returns an error.\nfunc makePodSourceConfig(kubeCfg *kubeletconfiginternal.KubeletConfiguration, kubeDeps *Dependencies, nodeName types.NodeName, nodeHasSynced func() bool) (*config.PodConfig, error) {\n\tmanifestURLHeader := make(http.Header)\n\tif len(kubeCfg.StaticPodURLHeader) \u003e 0 {\n\t\tfor k, v := range kubeCfg.StaticPodURLHeader {\n\t\t\tfor i := range v {\n\t\t\t\tmanifestURLHeader.Add(k, v[i])\n\t\t\t}\n\t\t}\n\t}\n\n\t// source of all configuration\n\tcfg := config.NewPodConfig(config.PodConfigNotificationIncremental, kubeDeps.Recorder, kubeDeps.PodStartupLatencyTracker)\n\n\t// TODO: it needs to be replaced by a proper context in the future\n\tctx := context.TODO()\n\n\t// define file config source\n\tif kubeCfg.StaticPodPath != \"\" {\n\t\tklog.InfoS(\"Adding static pod path\", \"path\", kubeCfg.StaticPodPath)\n\t\tconfig.NewSourceFile(kubeCfg.StaticPodPath, nodeName, kubeCfg.FileCheckFrequency.Duration, cfg.Channel(ctx, kubetypes.FileSource))\n\t}\n\n\t// define url config source\n\tif kubeCfg.StaticPodURL != \"\" {\n\t\tklog.InfoS(\"Adding pod URL with HTTP header\", \"URL\", kubeCfg.StaticPodURL, \"header\", manifestURLHeader)\n\t\tconfig.NewSourceURL(kubeCfg.StaticPodURL, manifestURLHeader, nodeName, kubeCfg.HTTPCheckFrequency.Duration, cfg.Channel(ctx, kubetypes.HTTPSource))\n\t}\n\n\tif kubeDeps.KubeClient != nil {\n\t\tklog.InfoS(\"Adding apiserver pod source\")\n\t\tconfig.NewSourceApiserver(kubeDeps.KubeClient, nodeName, nodeHasSynced, cfg.Channel(ctx, kubetypes.ApiserverSource))\n\t}\n\treturn cfg, nil\n}","line":{"from":278,"to":313}} {"id":100006662,"name":"PreInitRuntimeService","signature":"func PreInitRuntimeService(kubeCfg *kubeletconfiginternal.KubeletConfiguration, kubeDeps *Dependencies) error","file":"pkg/kubelet/kubelet.go","code":"// PreInitRuntimeService will init runtime service before RunKubelet.\nfunc PreInitRuntimeService(kubeCfg *kubeletconfiginternal.KubeletConfiguration, kubeDeps *Dependencies) error {\n\tremoteImageEndpoint := kubeCfg.ImageServiceEndpoint\n\tif remoteImageEndpoint == \"\" \u0026\u0026 kubeCfg.ContainerRuntimeEndpoint != \"\" {\n\t\tremoteImageEndpoint = kubeCfg.ContainerRuntimeEndpoint\n\t}\n\tvar err error\n\tif kubeDeps.RemoteRuntimeService, err = remote.NewRemoteRuntimeService(kubeCfg.ContainerRuntimeEndpoint, kubeCfg.RuntimeRequestTimeout.Duration, kubeDeps.TracerProvider); err != nil {\n\t\treturn err\n\t}\n\tif kubeDeps.RemoteImageService, err = remote.NewRemoteImageService(remoteImageEndpoint, kubeCfg.RuntimeRequestTimeout.Duration, kubeDeps.TracerProvider); err != nil {\n\t\treturn err\n\t}\n\n\tkubeDeps.useLegacyCadvisorStats = cadvisor.UsingLegacyCadvisorStats(kubeCfg.ContainerRuntimeEndpoint)\n\n\treturn nil\n}","line":{"from":315,"to":332}} {"id":100006663,"name":"NewMainKubelet","signature":"func NewMainKubelet(kubeCfg *kubeletconfiginternal.KubeletConfiguration,","file":"pkg/kubelet/kubelet.go","code":"// NewMainKubelet instantiates a new Kubelet object along with all the required internal modules.\n// No initialization of Kubelet and its modules should happen here.\nfunc NewMainKubelet(kubeCfg *kubeletconfiginternal.KubeletConfiguration,\n\tkubeDeps *Dependencies,\n\tcrOptions *config.ContainerRuntimeOptions,\n\thostname string,\n\thostnameOverridden bool,\n\tnodeName types.NodeName,\n\tnodeIPs []net.IP,\n\tproviderID string,\n\tcloudProvider string,\n\tcertDirectory string,\n\trootDirectory string,\n\timageCredentialProviderConfigFile string,\n\timageCredentialProviderBinDir string,\n\tregisterNode bool,\n\tregisterWithTaints []v1.Taint,\n\tallowedUnsafeSysctls []string,\n\texperimentalMounterPath string,\n\tkernelMemcgNotification bool,\n\texperimentalNodeAllocatableIgnoreEvictionThreshold bool,\n\tminimumGCAge metav1.Duration,\n\tmaxPerPodContainerCount int32,\n\tmaxContainerCount int32,\n\tregisterSchedulable bool,\n\tkeepTerminatedPodVolumes bool,\n\tnodeLabels map[string]string,\n\tnodeStatusMaxImages int32,\n\tseccompDefault bool,\n) (*Kubelet, error) {\n\tctx := context.Background()\n\tlogger := klog.TODO()\n\n\tif rootDirectory == \"\" {\n\t\treturn nil, fmt.Errorf(\"invalid root directory %q\", rootDirectory)\n\t}\n\tif kubeCfg.SyncFrequency.Duration \u003c= 0 {\n\t\treturn nil, fmt.Errorf(\"invalid sync frequency %d\", kubeCfg.SyncFrequency.Duration)\n\t}\n\n\tif kubeCfg.MakeIPTablesUtilChains {\n\t\tif kubeCfg.IPTablesMasqueradeBit \u003e 31 || kubeCfg.IPTablesMasqueradeBit \u003c 0 {\n\t\t\treturn nil, fmt.Errorf(\"iptables-masquerade-bit is not valid. Must be within [0, 31]\")\n\t\t}\n\t\tif kubeCfg.IPTablesDropBit \u003e 31 || kubeCfg.IPTablesDropBit \u003c 0 {\n\t\t\treturn nil, fmt.Errorf(\"iptables-drop-bit is not valid. Must be within [0, 31]\")\n\t\t}\n\t\tif kubeCfg.IPTablesDropBit == kubeCfg.IPTablesMasqueradeBit {\n\t\t\treturn nil, fmt.Errorf(\"iptables-masquerade-bit and iptables-drop-bit must be different\")\n\t\t}\n\t}\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.DisableCloudProviders) \u0026\u0026 cloudprovider.IsDeprecatedInternal(cloudProvider) {\n\t\tcloudprovider.DisableWarningForProvider(cloudProvider)\n\t\treturn nil, fmt.Errorf(\"cloud provider %q was specified, but built-in cloud providers are disabled. Please set --cloud-provider=external and migrate to an external cloud provider\", cloudProvider)\n\t}\n\n\tvar nodeHasSynced cache.InformerSynced\n\tvar nodeLister corelisters.NodeLister\n\n\t// If kubeClient == nil, we are running in standalone mode (i.e. no API servers)\n\t// If not nil, we are running as part of a cluster and should sync w/API\n\tif kubeDeps.KubeClient != nil {\n\t\tkubeInformers := informers.NewSharedInformerFactoryWithOptions(kubeDeps.KubeClient, 0, informers.WithTweakListOptions(func(options *metav1.ListOptions) {\n\t\t\toptions.FieldSelector = fields.Set{metav1.ObjectNameField: string(nodeName)}.String()\n\t\t}))\n\t\tnodeLister = kubeInformers.Core().V1().Nodes().Lister()\n\t\tnodeHasSynced = func() bool {\n\t\t\treturn kubeInformers.Core().V1().Nodes().Informer().HasSynced()\n\t\t}\n\t\tkubeInformers.Start(wait.NeverStop)\n\t\tklog.InfoS(\"Attempting to sync node with API server\")\n\t} else {\n\t\t// we don't have a client to sync!\n\t\tnodeIndexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{})\n\t\tnodeLister = corelisters.NewNodeLister(nodeIndexer)\n\t\tnodeHasSynced = func() bool { return true }\n\t\tklog.InfoS(\"Kubelet is running in standalone mode, will skip API server sync\")\n\t}\n\n\tif kubeDeps.PodConfig == nil {\n\t\tvar err error\n\t\tkubeDeps.PodConfig, err = makePodSourceConfig(kubeCfg, kubeDeps, nodeName, nodeHasSynced)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tcontainerGCPolicy := kubecontainer.GCPolicy{\n\t\tMinAge: minimumGCAge.Duration,\n\t\tMaxPerPodContainer: int(maxPerPodContainerCount),\n\t\tMaxContainers: int(maxContainerCount),\n\t}\n\n\tdaemonEndpoints := \u0026v1.NodeDaemonEndpoints{\n\t\tKubeletEndpoint: v1.DaemonEndpoint{Port: kubeCfg.Port},\n\t}\n\n\timageGCPolicy := images.ImageGCPolicy{\n\t\tMinAge: kubeCfg.ImageMinimumGCAge.Duration,\n\t\tHighThresholdPercent: int(kubeCfg.ImageGCHighThresholdPercent),\n\t\tLowThresholdPercent: int(kubeCfg.ImageGCLowThresholdPercent),\n\t}\n\n\tenforceNodeAllocatable := kubeCfg.EnforceNodeAllocatable\n\tif experimentalNodeAllocatableIgnoreEvictionThreshold {\n\t\t// Do not provide kubeCfg.EnforceNodeAllocatable to eviction threshold parsing if we are not enforcing Evictions\n\t\tenforceNodeAllocatable = []string{}\n\t}\n\tthresholds, err := eviction.ParseThresholdConfig(enforceNodeAllocatable, kubeCfg.EvictionHard, kubeCfg.EvictionSoft, kubeCfg.EvictionSoftGracePeriod, kubeCfg.EvictionMinimumReclaim)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tevictionConfig := eviction.Config{\n\t\tPressureTransitionPeriod: kubeCfg.EvictionPressureTransitionPeriod.Duration,\n\t\tMaxPodGracePeriodSeconds: int64(kubeCfg.EvictionMaxPodGracePeriod),\n\t\tThresholds: thresholds,\n\t\tKernelMemcgNotification: kernelMemcgNotification,\n\t\tPodCgroupRoot: kubeDeps.ContainerManager.GetPodCgroupRoot(),\n\t}\n\n\tvar serviceLister corelisters.ServiceLister\n\tvar serviceHasSynced cache.InformerSynced\n\tif kubeDeps.KubeClient != nil {\n\t\tkubeInformers := informers.NewSharedInformerFactory(kubeDeps.KubeClient, 0)\n\t\tserviceLister = kubeInformers.Core().V1().Services().Lister()\n\t\tserviceHasSynced = kubeInformers.Core().V1().Services().Informer().HasSynced\n\t\tkubeInformers.Start(wait.NeverStop)\n\t} else {\n\t\tserviceIndexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc})\n\t\tserviceLister = corelisters.NewServiceLister(serviceIndexer)\n\t\tserviceHasSynced = func() bool { return true }\n\t}\n\n\t// construct a node reference used for events\n\tnodeRef := \u0026v1.ObjectReference{\n\t\tKind: \"Node\",\n\t\tName: string(nodeName),\n\t\tUID: types.UID(nodeName),\n\t\tNamespace: \"\",\n\t}\n\n\toomWatcher, err := oomwatcher.NewWatcher(kubeDeps.Recorder)\n\tif err != nil {\n\t\tif libcontaineruserns.RunningInUserNS() {\n\t\t\tif utilfeature.DefaultFeatureGate.Enabled(features.KubeletInUserNamespace) {\n\t\t\t\t// oomwatcher.NewWatcher returns \"open /dev/kmsg: operation not permitted\" error,\n\t\t\t\t// when running in a user namespace with sysctl value `kernel.dmesg_restrict=1`.\n\t\t\t\tklog.V(2).InfoS(\"Failed to create an oomWatcher (running in UserNS, ignoring)\", \"err\", err)\n\t\t\t\toomWatcher = nil\n\t\t\t} else {\n\t\t\t\tklog.ErrorS(err, \"Failed to create an oomWatcher (running in UserNS, Hint: enable KubeletInUserNamespace feature flag to ignore the error)\")\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tclusterDNS := make([]net.IP, 0, len(kubeCfg.ClusterDNS))\n\tfor _, ipEntry := range kubeCfg.ClusterDNS {\n\t\tip := netutils.ParseIPSloppy(ipEntry)\n\t\tif ip == nil {\n\t\t\tklog.InfoS(\"Invalid clusterDNS IP\", \"IP\", ipEntry)\n\t\t} else {\n\t\t\tclusterDNS = append(clusterDNS, ip)\n\t\t}\n\t}\n\n\t// A TLS transport is needed to make HTTPS-based container lifecycle requests,\n\t// but we do not have the information necessary to do TLS verification.\n\t//\n\t// This client must not be modified to include credentials, because it is\n\t// critical that credentials not leak from the client to arbitrary hosts.\n\tinsecureContainerLifecycleHTTPClient := \u0026http.Client{}\n\tif utilfeature.DefaultFeatureGate.Enabled(features.ConsistentHTTPGetHandlers) {\n\t\tinsecureTLSTransport := \u0026http.Transport{\n\t\t\tTLSClientConfig: \u0026tls.Config{InsecureSkipVerify: true},\n\t\t}\n\t\tinsecureContainerLifecycleHTTPClient.Transport = insecureTLSTransport\n\t\tinsecureContainerLifecycleHTTPClient.CheckRedirect = httpprobe.RedirectChecker(false)\n\t}\n\n\ttracer := kubeDeps.TracerProvider.Tracer(instrumentationScope)\n\n\tklet := \u0026Kubelet{\n\t\thostname: hostname,\n\t\thostnameOverridden: hostnameOverridden,\n\t\tnodeName: nodeName,\n\t\tkubeClient: kubeDeps.KubeClient,\n\t\theartbeatClient: kubeDeps.HeartbeatClient,\n\t\tonRepeatedHeartbeatFailure: kubeDeps.OnHeartbeatFailure,\n\t\trootDirectory: filepath.Clean(rootDirectory),\n\t\tresyncInterval: kubeCfg.SyncFrequency.Duration,\n\t\tsourcesReady: config.NewSourcesReady(kubeDeps.PodConfig.SeenAllSources),\n\t\tregisterNode: registerNode,\n\t\tregisterWithTaints: registerWithTaints,\n\t\tregisterSchedulable: registerSchedulable,\n\t\tdnsConfigurer: dns.NewConfigurer(kubeDeps.Recorder, nodeRef, nodeIPs, clusterDNS, kubeCfg.ClusterDomain, kubeCfg.ResolverConfig),\n\t\tserviceLister: serviceLister,\n\t\tserviceHasSynced: serviceHasSynced,\n\t\tnodeLister: nodeLister,\n\t\tnodeHasSynced: nodeHasSynced,\n\t\tstreamingConnectionIdleTimeout: kubeCfg.StreamingConnectionIdleTimeout.Duration,\n\t\trecorder: kubeDeps.Recorder,\n\t\tcadvisor: kubeDeps.CAdvisorInterface,\n\t\tcloud: kubeDeps.Cloud,\n\t\texternalCloudProvider: cloudprovider.IsExternal(cloudProvider),\n\t\tproviderID: providerID,\n\t\tnodeRef: nodeRef,\n\t\tnodeLabels: nodeLabels,\n\t\tnodeStatusUpdateFrequency: kubeCfg.NodeStatusUpdateFrequency.Duration,\n\t\tnodeStatusReportFrequency: kubeCfg.NodeStatusReportFrequency.Duration,\n\t\tos: kubeDeps.OSInterface,\n\t\toomWatcher: oomWatcher,\n\t\tcgroupsPerQOS: kubeCfg.CgroupsPerQOS,\n\t\tcgroupRoot: kubeCfg.CgroupRoot,\n\t\tmounter: kubeDeps.Mounter,\n\t\thostutil: kubeDeps.HostUtil,\n\t\tsubpather: kubeDeps.Subpather,\n\t\tmaxPods: int(kubeCfg.MaxPods),\n\t\tpodsPerCore: int(kubeCfg.PodsPerCore),\n\t\tsyncLoopMonitor: atomic.Value{},\n\t\tdaemonEndpoints: daemonEndpoints,\n\t\tcontainerManager: kubeDeps.ContainerManager,\n\t\tnodeIPs: nodeIPs,\n\t\tnodeIPValidator: validateNodeIP,\n\t\tclock: clock.RealClock{},\n\t\tenableControllerAttachDetach: kubeCfg.EnableControllerAttachDetach,\n\t\tmakeIPTablesUtilChains: kubeCfg.MakeIPTablesUtilChains,\n\t\tiptablesMasqueradeBit: int(kubeCfg.IPTablesMasqueradeBit),\n\t\tiptablesDropBit: int(kubeCfg.IPTablesDropBit),\n\t\texperimentalHostUserNamespaceDefaulting: utilfeature.DefaultFeatureGate.Enabled(features.ExperimentalHostUserNamespaceDefaultingGate),\n\t\tkeepTerminatedPodVolumes: keepTerminatedPodVolumes,\n\t\tnodeStatusMaxImages: nodeStatusMaxImages,\n\t\ttracer: tracer,\n\t}\n\n\tif klet.cloud != nil {\n\t\tklet.cloudResourceSyncManager = cloudresource.NewSyncManager(klet.cloud, nodeName, klet.nodeStatusUpdateFrequency)\n\t}\n\n\tvar secretManager secret.Manager\n\tvar configMapManager configmap.Manager\n\tif klet.kubeClient != nil {\n\t\tswitch kubeCfg.ConfigMapAndSecretChangeDetectionStrategy {\n\t\tcase kubeletconfiginternal.WatchChangeDetectionStrategy:\n\t\t\tsecretManager = secret.NewWatchingSecretManager(klet.kubeClient, klet.resyncInterval)\n\t\t\tconfigMapManager = configmap.NewWatchingConfigMapManager(klet.kubeClient, klet.resyncInterval)\n\t\tcase kubeletconfiginternal.TTLCacheChangeDetectionStrategy:\n\t\t\tsecretManager = secret.NewCachingSecretManager(\n\t\t\t\tklet.kubeClient, manager.GetObjectTTLFromNodeFunc(klet.GetNode))\n\t\t\tconfigMapManager = configmap.NewCachingConfigMapManager(\n\t\t\t\tklet.kubeClient, manager.GetObjectTTLFromNodeFunc(klet.GetNode))\n\t\tcase kubeletconfiginternal.GetChangeDetectionStrategy:\n\t\t\tsecretManager = secret.NewSimpleSecretManager(klet.kubeClient)\n\t\t\tconfigMapManager = configmap.NewSimpleConfigMapManager(klet.kubeClient)\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown configmap and secret manager mode: %v\", kubeCfg.ConfigMapAndSecretChangeDetectionStrategy)\n\t\t}\n\n\t\tklet.secretManager = secretManager\n\t\tklet.configMapManager = configMapManager\n\t}\n\n\tif klet.experimentalHostUserNamespaceDefaulting {\n\t\tklog.InfoS(\"Experimental host user namespace defaulting is enabled\")\n\t}\n\n\tmachineInfo, err := klet.cadvisor.MachineInfo()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Avoid collector collects it as a timestamped metric\n\t// See PR #95210 and #97006 for more details.\n\tmachineInfo.Timestamp = time.Time{}\n\tklet.setCachedMachineInfo(machineInfo)\n\n\timageBackOff := flowcontrol.NewBackOff(backOffPeriod, MaxContainerBackOff)\n\n\tklet.livenessManager = proberesults.NewManager()\n\tklet.readinessManager = proberesults.NewManager()\n\tklet.startupManager = proberesults.NewManager()\n\tklet.podCache = kubecontainer.NewCache()\n\n\t// podManager is also responsible for keeping secretManager and configMapManager contents up-to-date.\n\tmirrorPodClient := kubepod.NewBasicMirrorClient(klet.kubeClient, string(nodeName), nodeLister)\n\tklet.podManager = kubepod.NewBasicPodManager(mirrorPodClient)\n\n\tklet.statusManager = status.NewManager(klet.kubeClient, klet.podManager, klet, kubeDeps.PodStartupLatencyTracker, klet.getRootDir())\n\n\tklet.resourceAnalyzer = serverstats.NewResourceAnalyzer(klet, kubeCfg.VolumeStatsAggPeriod.Duration, kubeDeps.Recorder)\n\n\tklet.runtimeService = kubeDeps.RemoteRuntimeService\n\n\tif kubeDeps.KubeClient != nil {\n\t\tklet.runtimeClassManager = runtimeclass.NewManager(kubeDeps.KubeClient)\n\t}\n\n\t// setup containerLogManager for CRI container runtime\n\tcontainerLogManager, err := logs.NewContainerLogManager(\n\t\tklet.runtimeService,\n\t\tkubeDeps.OSInterface,\n\t\tkubeCfg.ContainerLogMaxSize,\n\t\tint(kubeCfg.ContainerLogMaxFiles),\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize container log manager: %v\", err)\n\t}\n\tklet.containerLogManager = containerLogManager\n\n\tklet.reasonCache = NewReasonCache()\n\tklet.workQueue = queue.NewBasicWorkQueue(klet.clock)\n\tklet.podWorkers = newPodWorkers(\n\t\tklet,\n\t\tkubeDeps.Recorder,\n\t\tklet.workQueue,\n\t\tklet.resyncInterval,\n\t\tbackOffPeriod,\n\t\tklet.podCache,\n\t)\n\n\truntime, err := kuberuntime.NewKubeGenericRuntimeManager(\n\t\tkubecontainer.FilterEventRecorder(kubeDeps.Recorder),\n\t\tklet.livenessManager,\n\t\tklet.readinessManager,\n\t\tklet.startupManager,\n\t\trootDirectory,\n\t\tmachineInfo,\n\t\tklet.podWorkers,\n\t\tkubeDeps.OSInterface,\n\t\tklet,\n\t\tinsecureContainerLifecycleHTTPClient,\n\t\timageBackOff,\n\t\tkubeCfg.SerializeImagePulls,\n\t\tkubeCfg.MaxParallelImagePulls,\n\t\tfloat32(kubeCfg.RegistryPullQPS),\n\t\tint(kubeCfg.RegistryBurst),\n\t\timageCredentialProviderConfigFile,\n\t\timageCredentialProviderBinDir,\n\t\tkubeCfg.CPUCFSQuota,\n\t\tkubeCfg.CPUCFSQuotaPeriod,\n\t\tkubeDeps.RemoteRuntimeService,\n\t\tkubeDeps.RemoteImageService,\n\t\tkubeDeps.ContainerManager,\n\t\tklet.containerLogManager,\n\t\tklet.runtimeClassManager,\n\t\tseccompDefault,\n\t\tkubeCfg.MemorySwap.SwapBehavior,\n\t\tkubeDeps.ContainerManager.GetNodeAllocatableAbsolute,\n\t\t*kubeCfg.MemoryThrottlingFactor,\n\t\tkubeDeps.PodStartupLatencyTracker,\n\t\tkubeDeps.TracerProvider,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tklet.containerRuntime = runtime\n\tklet.streamingRuntime = runtime\n\tklet.runner = runtime\n\n\truntimeCache, err := kubecontainer.NewRuntimeCache(klet.containerRuntime, runtimeCacheRefreshPeriod)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tklet.runtimeCache = runtimeCache\n\n\t// common provider to get host file system usage associated with a pod managed by kubelet\n\thostStatsProvider := stats.NewHostStatsProvider(kubecontainer.RealOS{}, func(podUID types.UID) string {\n\t\treturn getEtcHostsPath(klet.getPodDir(podUID))\n\t})\n\tif kubeDeps.useLegacyCadvisorStats {\n\t\tklet.StatsProvider = stats.NewCadvisorStatsProvider(\n\t\t\tklet.cadvisor,\n\t\t\tklet.resourceAnalyzer,\n\t\t\tklet.podManager,\n\t\t\tklet.runtimeCache,\n\t\t\tklet.containerRuntime,\n\t\t\tklet.statusManager,\n\t\t\thostStatsProvider)\n\t} else {\n\t\tklet.StatsProvider = stats.NewCRIStatsProvider(\n\t\t\tklet.cadvisor,\n\t\t\tklet.resourceAnalyzer,\n\t\t\tklet.podManager,\n\t\t\tklet.runtimeCache,\n\t\t\tkubeDeps.RemoteRuntimeService,\n\t\t\tkubeDeps.RemoteImageService,\n\t\t\thostStatsProvider,\n\t\t\tutilfeature.DefaultFeatureGate.Enabled(features.PodAndContainerStatsFromCRI))\n\t}\n\n\teventChannel := make(chan *pleg.PodLifecycleEvent, plegChannelCapacity)\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.EventedPLEG) {\n\t\t// adjust Generic PLEG relisting period and threshold to higher value when Evented PLEG is turned on\n\t\tgenericRelistDuration := \u0026pleg.RelistDuration{\n\t\t\tRelistPeriod: eventedPlegRelistPeriod,\n\t\t\tRelistThreshold: eventedPlegRelistThreshold,\n\t\t}\n\t\tklet.pleg = pleg.NewGenericPLEG(klet.containerRuntime, eventChannel, genericRelistDuration, klet.podCache, clock.RealClock{})\n\t\t// In case Evented PLEG has to fall back on Generic PLEG due to an error,\n\t\t// Evented PLEG should be able to reset the Generic PLEG relisting duration\n\t\t// to the default value.\n\t\teventedRelistDuration := \u0026pleg.RelistDuration{\n\t\t\tRelistPeriod: genericPlegRelistPeriod,\n\t\t\tRelistThreshold: genericPlegRelistThreshold,\n\t\t}\n\t\tklet.eventedPleg = pleg.NewEventedPLEG(klet.containerRuntime, klet.runtimeService, eventChannel,\n\t\t\tklet.podCache, klet.pleg, eventedPlegMaxStreamRetries, eventedRelistDuration, clock.RealClock{})\n\t} else {\n\t\tgenericRelistDuration := \u0026pleg.RelistDuration{\n\t\t\tRelistPeriod: genericPlegRelistPeriod,\n\t\t\tRelistThreshold: genericPlegRelistThreshold,\n\t\t}\n\t\tklet.pleg = pleg.NewGenericPLEG(klet.containerRuntime, eventChannel, genericRelistDuration, klet.podCache, clock.RealClock{})\n\t}\n\n\tklet.runtimeState = newRuntimeState(maxWaitForContainerRuntime)\n\tklet.runtimeState.addHealthCheck(\"PLEG\", klet.pleg.Healthy)\n\tif utilfeature.DefaultFeatureGate.Enabled(features.EventedPLEG) {\n\t\tklet.runtimeState.addHealthCheck(\"EventedPLEG\", klet.eventedPleg.Healthy)\n\t}\n\tif _, err := klet.updatePodCIDR(ctx, kubeCfg.PodCIDR); err != nil {\n\t\tklog.ErrorS(err, \"Pod CIDR update failed\")\n\t}\n\n\t// setup containerGC\n\tcontainerGC, err := kubecontainer.NewContainerGC(klet.containerRuntime, containerGCPolicy, klet.sourcesReady)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tklet.containerGC = containerGC\n\tklet.containerDeletor = newPodContainerDeletor(klet.containerRuntime, integer.IntMax(containerGCPolicy.MaxPerPodContainer, minDeadContainerInPod))\n\n\t// setup imageManager\n\timageManager, err := images.NewImageGCManager(klet.containerRuntime, klet.StatsProvider, kubeDeps.Recorder, nodeRef, imageGCPolicy, crOptions.PodSandboxImage, kubeDeps.TracerProvider)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize image manager: %v\", err)\n\t}\n\tklet.imageManager = imageManager\n\n\tif kubeCfg.ServerTLSBootstrap \u0026\u0026 kubeDeps.TLSOptions != nil \u0026\u0026 utilfeature.DefaultFeatureGate.Enabled(features.RotateKubeletServerCertificate) {\n\t\tklet.serverCertificateManager, err = kubeletcertificate.NewKubeletServerCertificateManager(klet.kubeClient, kubeCfg, klet.nodeName, klet.getLastObservedNodeAddresses, certDirectory)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to initialize certificate manager: %v\", err)\n\t\t}\n\t\tkubeDeps.TLSOptions.Config.GetCertificate = func(*tls.ClientHelloInfo) (*tls.Certificate, error) {\n\t\t\tcert := klet.serverCertificateManager.Current()\n\t\t\tif cert == nil {\n\t\t\t\treturn nil, fmt.Errorf(\"no serving certificate available for the kubelet\")\n\t\t\t}\n\t\t\treturn cert, nil\n\t\t}\n\t}\n\n\tif kubeDeps.ProbeManager != nil {\n\t\tklet.probeManager = kubeDeps.ProbeManager\n\t} else {\n\t\tklet.probeManager = prober.NewManager(\n\t\t\tklet.statusManager,\n\t\t\tklet.livenessManager,\n\t\t\tklet.readinessManager,\n\t\t\tklet.startupManager,\n\t\t\tklet.runner,\n\t\t\tkubeDeps.Recorder)\n\t}\n\n\ttokenManager := token.NewManager(kubeDeps.KubeClient)\n\n\t// NewInitializedVolumePluginMgr initializes some storageErrors on the Kubelet runtimeState (in csi_plugin.go init)\n\t// which affects node ready status. This function must be called before Kubelet is initialized so that the Node\n\t// ReadyState is accurate with the storage state.\n\tklet.volumePluginMgr, err =\n\t\tNewInitializedVolumePluginMgr(klet, secretManager, configMapManager, tokenManager, kubeDeps.VolumePlugins, kubeDeps.DynamicPluginProber)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tklet.pluginManager = pluginmanager.NewPluginManager(\n\t\tklet.getPluginsRegistrationDir(), /* sockDir */\n\t\tkubeDeps.Recorder,\n\t)\n\n\t// If the experimentalMounterPathFlag is set, we do not want to\n\t// check node capabilities since the mount path is not the default\n\tif len(experimentalMounterPath) != 0 {\n\t\t// Replace the nameserver in containerized-mounter's rootfs/etc/resolv.conf with kubelet.ClusterDNS\n\t\t// so that service name could be resolved\n\t\tklet.dnsConfigurer.SetupDNSinContainerizedMounter(experimentalMounterPath)\n\t}\n\n\t// setup volumeManager\n\tklet.volumeManager = volumemanager.NewVolumeManager(\n\t\tkubeCfg.EnableControllerAttachDetach,\n\t\tnodeName,\n\t\tklet.podManager,\n\t\tklet.podWorkers,\n\t\tklet.kubeClient,\n\t\tklet.volumePluginMgr,\n\t\tklet.containerRuntime,\n\t\tkubeDeps.Mounter,\n\t\tkubeDeps.HostUtil,\n\t\tklet.getPodsDir(),\n\t\tkubeDeps.Recorder,\n\t\tkeepTerminatedPodVolumes,\n\t\tvolumepathhandler.NewBlockVolumePathHandler())\n\n\tklet.backOff = flowcontrol.NewBackOff(backOffPeriod, MaxContainerBackOff)\n\n\t// setup eviction manager\n\tevictionManager, evictionAdmitHandler := eviction.NewManager(klet.resourceAnalyzer, evictionConfig,\n\t\tkillPodNow(klet.podWorkers, kubeDeps.Recorder), klet.podManager.GetMirrorPodByPod, klet.imageManager, klet.containerGC, kubeDeps.Recorder, nodeRef, klet.clock, kubeCfg.LocalStorageCapacityIsolation)\n\n\tklet.evictionManager = evictionManager\n\tklet.admitHandlers.AddPodAdmitHandler(evictionAdmitHandler)\n\n\t// Safe, allowed sysctls can always be used as unsafe sysctls in the spec.\n\t// Hence, we concatenate those two lists.\n\tsafeAndUnsafeSysctls := append(sysctl.SafeSysctlAllowlist(), allowedUnsafeSysctls...)\n\tsysctlsAllowlist, err := sysctl.NewAllowlist(safeAndUnsafeSysctls)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tklet.admitHandlers.AddPodAdmitHandler(sysctlsAllowlist)\n\n\t// enable active deadline handler\n\tactiveDeadlineHandler, err := newActiveDeadlineHandler(klet.statusManager, kubeDeps.Recorder, klet.clock)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tklet.AddPodSyncLoopHandler(activeDeadlineHandler)\n\tklet.AddPodSyncHandler(activeDeadlineHandler)\n\n\tklet.admitHandlers.AddPodAdmitHandler(klet.containerManager.GetAllocateResourcesPodAdmitHandler())\n\n\tcriticalPodAdmissionHandler := preemption.NewCriticalPodAdmissionHandler(klet.GetActivePods, killPodNow(klet.podWorkers, kubeDeps.Recorder), kubeDeps.Recorder)\n\tklet.admitHandlers.AddPodAdmitHandler(lifecycle.NewPredicateAdmitHandler(klet.getNodeAnyWay, criticalPodAdmissionHandler, klet.containerManager.UpdatePluginResources))\n\t// apply functional Option's\n\tfor _, opt := range kubeDeps.Options {\n\t\topt(klet)\n\t}\n\n\tif sysruntime.GOOS == \"linux\" {\n\t\t// AppArmor is a Linux kernel security module and it does not support other operating systems.\n\t\tklet.appArmorValidator = apparmor.NewValidator()\n\t\tklet.softAdmitHandlers.AddPodAdmitHandler(lifecycle.NewAppArmorAdmitHandler(klet.appArmorValidator))\n\t}\n\n\tleaseDuration := time.Duration(kubeCfg.NodeLeaseDurationSeconds) * time.Second\n\trenewInterval := time.Duration(float64(leaseDuration) * nodeLeaseRenewIntervalFraction)\n\tklet.nodeLeaseController = lease.NewController(\n\t\tklet.clock,\n\t\tklet.heartbeatClient,\n\t\tstring(klet.nodeName),\n\t\tkubeCfg.NodeLeaseDurationSeconds,\n\t\tklet.onRepeatedHeartbeatFailure,\n\t\trenewInterval,\n\t\tstring(klet.nodeName),\n\t\tv1.NamespaceNodeLease,\n\t\tutil.SetNodeOwnerFunc(klet.heartbeatClient, string(klet.nodeName)))\n\n\t// setup node shutdown manager\n\tshutdownManager, shutdownAdmitHandler := nodeshutdown.NewManager(\u0026nodeshutdown.Config{\n\t\tLogger: logger,\n\t\tProbeManager: klet.probeManager,\n\t\tRecorder: kubeDeps.Recorder,\n\t\tNodeRef: nodeRef,\n\t\tGetPodsFunc: klet.GetActivePods,\n\t\tKillPodFunc: killPodNow(klet.podWorkers, kubeDeps.Recorder),\n\t\tSyncNodeStatusFunc: klet.syncNodeStatus,\n\t\tShutdownGracePeriodRequested: kubeCfg.ShutdownGracePeriod.Duration,\n\t\tShutdownGracePeriodCriticalPods: kubeCfg.ShutdownGracePeriodCriticalPods.Duration,\n\t\tShutdownGracePeriodByPodPriority: kubeCfg.ShutdownGracePeriodByPodPriority,\n\t\tStateDirectory: rootDirectory,\n\t})\n\tklet.shutdownManager = shutdownManager\n\tklet.usernsManager, err = userns.MakeUserNsManager(klet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tklet.admitHandlers.AddPodAdmitHandler(shutdownAdmitHandler)\n\n\t// Finally, put the most recent version of the config on the Kubelet, so\n\t// people can see how it was configured.\n\tklet.kubeletConfiguration = *kubeCfg\n\n\t// Generating the status funcs should be the last thing we do,\n\t// since this relies on the rest of the Kubelet having been constructed.\n\tklet.setNodeStatusFuncs = klet.defaultNodeStatusFuncs()\n\n\treturn klet, nil\n}","line":{"from":334,"to":925}} {"id":100006664,"name":"ListPodStats","signature":"func (kl *Kubelet) ListPodStats(ctx context.Context) ([]statsapi.PodStats, error)","file":"pkg/kubelet/kubelet.go","code":"// ListPodStats is delegated to StatsProvider, which implements stats.Provider interface\nfunc (kl *Kubelet) ListPodStats(ctx context.Context) ([]statsapi.PodStats, error) {\n\treturn kl.StatsProvider.ListPodStats(ctx)\n}","line":{"from":1267,"to":1270}} {"id":100006665,"name":"ListPodCPUAndMemoryStats","signature":"func (kl *Kubelet) ListPodCPUAndMemoryStats(ctx context.Context) ([]statsapi.PodStats, error)","file":"pkg/kubelet/kubelet.go","code":"// ListPodCPUAndMemoryStats is delegated to StatsProvider, which implements stats.Provider interface\nfunc (kl *Kubelet) ListPodCPUAndMemoryStats(ctx context.Context) ([]statsapi.PodStats, error) {\n\treturn kl.StatsProvider.ListPodCPUAndMemoryStats(ctx)\n}","line":{"from":1272,"to":1275}} {"id":100006666,"name":"ListPodStatsAndUpdateCPUNanoCoreUsage","signature":"func (kl *Kubelet) ListPodStatsAndUpdateCPUNanoCoreUsage(ctx context.Context) ([]statsapi.PodStats, error)","file":"pkg/kubelet/kubelet.go","code":"// ListPodStatsAndUpdateCPUNanoCoreUsage is delegated to StatsProvider, which implements stats.Provider interface\nfunc (kl *Kubelet) ListPodStatsAndUpdateCPUNanoCoreUsage(ctx context.Context) ([]statsapi.PodStats, error) {\n\treturn kl.StatsProvider.ListPodStatsAndUpdateCPUNanoCoreUsage(ctx)\n}","line":{"from":1277,"to":1280}} {"id":100006667,"name":"ImageFsStats","signature":"func (kl *Kubelet) ImageFsStats(ctx context.Context) (*statsapi.FsStats, error)","file":"pkg/kubelet/kubelet.go","code":"// ImageFsStats is delegated to StatsProvider, which implements stats.Provider interface\nfunc (kl *Kubelet) ImageFsStats(ctx context.Context) (*statsapi.FsStats, error) {\n\treturn kl.StatsProvider.ImageFsStats(ctx)\n}","line":{"from":1282,"to":1285}} {"id":100006668,"name":"GetCgroupStats","signature":"func (kl *Kubelet) GetCgroupStats(cgroupName string, updateStats bool) (*statsapi.ContainerStats, *statsapi.NetworkStats, error)","file":"pkg/kubelet/kubelet.go","code":"// GetCgroupStats is delegated to StatsProvider, which implements stats.Provider interface\nfunc (kl *Kubelet) GetCgroupStats(cgroupName string, updateStats bool) (*statsapi.ContainerStats, *statsapi.NetworkStats, error) {\n\treturn kl.StatsProvider.GetCgroupStats(cgroupName, updateStats)\n}","line":{"from":1287,"to":1290}} {"id":100006669,"name":"GetCgroupCPUAndMemoryStats","signature":"func (kl *Kubelet) GetCgroupCPUAndMemoryStats(cgroupName string, updateStats bool) (*statsapi.ContainerStats, error)","file":"pkg/kubelet/kubelet.go","code":"// GetCgroupCPUAndMemoryStats is delegated to StatsProvider, which implements stats.Provider interface\nfunc (kl *Kubelet) GetCgroupCPUAndMemoryStats(cgroupName string, updateStats bool) (*statsapi.ContainerStats, error) {\n\treturn kl.StatsProvider.GetCgroupCPUAndMemoryStats(cgroupName, updateStats)\n}","line":{"from":1292,"to":1295}} {"id":100006670,"name":"RootFsStats","signature":"func (kl *Kubelet) RootFsStats() (*statsapi.FsStats, error)","file":"pkg/kubelet/kubelet.go","code":"// RootFsStats is delegated to StatsProvider, which implements stats.Provider interface\nfunc (kl *Kubelet) RootFsStats() (*statsapi.FsStats, error) {\n\treturn kl.StatsProvider.RootFsStats()\n}","line":{"from":1297,"to":1300}} {"id":100006671,"name":"GetContainerInfo","signature":"func (kl *Kubelet) GetContainerInfo(ctx context.Context, podFullName string, uid types.UID, containerName string, req *cadvisorapi.ContainerInfoRequest) (*cadvisorapi.ContainerInfo, error)","file":"pkg/kubelet/kubelet.go","code":"// GetContainerInfo is delegated to StatsProvider, which implements stats.Provider interface\nfunc (kl *Kubelet) GetContainerInfo(ctx context.Context, podFullName string, uid types.UID, containerName string, req *cadvisorapi.ContainerInfoRequest) (*cadvisorapi.ContainerInfo, error) {\n\treturn kl.StatsProvider.GetContainerInfo(ctx, podFullName, uid, containerName, req)\n}","line":{"from":1302,"to":1305}} {"id":100006672,"name":"GetRawContainerInfo","signature":"func (kl *Kubelet) GetRawContainerInfo(containerName string, req *cadvisorapi.ContainerInfoRequest, subcontainers bool) (map[string]*cadvisorapi.ContainerInfo, error)","file":"pkg/kubelet/kubelet.go","code":"// GetRawContainerInfo is delegated to StatsProvider, which implements stats.Provider interface\nfunc (kl *Kubelet) GetRawContainerInfo(containerName string, req *cadvisorapi.ContainerInfoRequest, subcontainers bool) (map[string]*cadvisorapi.ContainerInfo, error) {\n\treturn kl.StatsProvider.GetRawContainerInfo(containerName, req, subcontainers)\n}","line":{"from":1307,"to":1310}} {"id":100006673,"name":"RlimitStats","signature":"func (kl *Kubelet) RlimitStats() (*statsapi.RlimitStats, error)","file":"pkg/kubelet/kubelet.go","code":"// RlimitStats is delegated to StatsProvider, which implements stats.Provider interface\nfunc (kl *Kubelet) RlimitStats() (*statsapi.RlimitStats, error) {\n\treturn kl.StatsProvider.RlimitStats()\n}","line":{"from":1312,"to":1315}} {"id":100006674,"name":"setupDataDirs","signature":"func (kl *Kubelet) setupDataDirs() error","file":"pkg/kubelet/kubelet.go","code":"// setupDataDirs creates:\n// 1. the root directory\n// 2. the pods directory\n// 3. the plugins directory\n// 4. the pod-resources directory\n// 5. the checkpoint directory\nfunc (kl *Kubelet) setupDataDirs() error {\n\tif cleanedRoot := filepath.Clean(kl.rootDirectory); cleanedRoot != kl.rootDirectory {\n\t\treturn fmt.Errorf(\"rootDirectory not in canonical form: expected %s, was %s\", cleanedRoot, kl.rootDirectory)\n\t}\n\tpluginRegistrationDir := kl.getPluginsRegistrationDir()\n\tpluginsDir := kl.getPluginsDir()\n\tif err := os.MkdirAll(kl.getRootDir(), 0750); err != nil {\n\t\treturn fmt.Errorf(\"error creating root directory: %v\", err)\n\t}\n\tif err := kl.hostutil.MakeRShared(kl.getRootDir()); err != nil {\n\t\treturn fmt.Errorf(\"error configuring root directory: %v\", err)\n\t}\n\tif err := os.MkdirAll(kl.getPodsDir(), 0750); err != nil {\n\t\treturn fmt.Errorf(\"error creating pods directory: %v\", err)\n\t}\n\tif err := os.MkdirAll(kl.getPluginsDir(), 0750); err != nil {\n\t\treturn fmt.Errorf(\"error creating plugins directory: %v\", err)\n\t}\n\tif err := os.MkdirAll(kl.getPluginsRegistrationDir(), 0750); err != nil {\n\t\treturn fmt.Errorf(\"error creating plugins registry directory: %v\", err)\n\t}\n\tif err := os.MkdirAll(kl.getPodResourcesDir(), 0750); err != nil {\n\t\treturn fmt.Errorf(\"error creating podresources directory: %v\", err)\n\t}\n\tif utilfeature.DefaultFeatureGate.Enabled(features.ContainerCheckpoint) {\n\t\tif err := os.MkdirAll(kl.getCheckpointsDir(), 0700); err != nil {\n\t\t\treturn fmt.Errorf(\"error creating checkpoint directory: %v\", err)\n\t\t}\n\t}\n\tif selinux.GetEnabled() {\n\t\terr := selinux.SetFileLabel(pluginRegistrationDir, config.KubeletPluginsDirSELinuxLabel)\n\t\tif err != nil {\n\t\t\tklog.InfoS(\"Unprivileged containerized plugins might not work, could not set selinux context on plugin registration dir\", \"path\", pluginRegistrationDir, \"err\", err)\n\t\t}\n\t\terr = selinux.SetFileLabel(pluginsDir, config.KubeletPluginsDirSELinuxLabel)\n\t\tif err != nil {\n\t\t\tklog.InfoS(\"Unprivileged containerized plugins might not work, could not set selinux context on plugins dir\", \"path\", pluginsDir, \"err\", err)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":1317,"to":1363}} {"id":100006675,"name":"StartGarbageCollection","signature":"func (kl *Kubelet) StartGarbageCollection()","file":"pkg/kubelet/kubelet.go","code":"// StartGarbageCollection starts garbage collection threads.\nfunc (kl *Kubelet) StartGarbageCollection() {\n\tloggedContainerGCFailure := false\n\tgo wait.Until(func() {\n\t\tctx := context.Background()\n\t\tif err := kl.containerGC.GarbageCollect(ctx); err != nil {\n\t\t\tklog.ErrorS(err, \"Container garbage collection failed\")\n\t\t\tkl.recorder.Eventf(kl.nodeRef, v1.EventTypeWarning, events.ContainerGCFailed, err.Error())\n\t\t\tloggedContainerGCFailure = true\n\t\t} else {\n\t\t\tvar vLevel klog.Level = 4\n\t\t\tif loggedContainerGCFailure {\n\t\t\t\tvLevel = 1\n\t\t\t\tloggedContainerGCFailure = false\n\t\t\t}\n\n\t\t\tklog.V(vLevel).InfoS(\"Container garbage collection succeeded\")\n\t\t}\n\t}, ContainerGCPeriod, wait.NeverStop)\n\n\t// when the high threshold is set to 100, stub the image GC manager\n\tif kl.kubeletConfiguration.ImageGCHighThresholdPercent == 100 {\n\t\tklog.V(2).InfoS(\"ImageGCHighThresholdPercent is set 100, Disable image GC\")\n\t\treturn\n\t}\n\n\tprevImageGCFailed := false\n\tgo wait.Until(func() {\n\t\tctx := context.Background()\n\t\tif err := kl.imageManager.GarbageCollect(ctx); err != nil {\n\t\t\tif prevImageGCFailed {\n\t\t\t\tklog.ErrorS(err, \"Image garbage collection failed multiple times in a row\")\n\t\t\t\t// Only create an event for repeated failures\n\t\t\t\tkl.recorder.Eventf(kl.nodeRef, v1.EventTypeWarning, events.ImageGCFailed, err.Error())\n\t\t\t} else {\n\t\t\t\tklog.ErrorS(err, \"Image garbage collection failed once. Stats initialization may not have completed yet\")\n\t\t\t}\n\t\t\tprevImageGCFailed = true\n\t\t} else {\n\t\t\tvar vLevel klog.Level = 4\n\t\t\tif prevImageGCFailed {\n\t\t\t\tvLevel = 1\n\t\t\t\tprevImageGCFailed = false\n\t\t\t}\n\n\t\t\tklog.V(vLevel).InfoS(\"Image garbage collection succeeded\")\n\t\t}\n\t}, ImageGCPeriod, wait.NeverStop)\n}","line":{"from":1365,"to":1413}} {"id":100006676,"name":"initializeModules","signature":"func (kl *Kubelet) initializeModules() error","file":"pkg/kubelet/kubelet.go","code":"// initializeModules will initialize internal modules that do not require the container runtime to be up.\n// Note that the modules here must not depend on modules that are not initialized here.\nfunc (kl *Kubelet) initializeModules() error {\n\t// Prometheus metrics.\n\tmetrics.Register(\n\t\tcollectors.NewVolumeStatsCollector(kl),\n\t\tcollectors.NewLogMetricsCollector(kl.StatsProvider.ListPodStats),\n\t)\n\tmetrics.SetNodeName(kl.nodeName)\n\tservermetrics.Register()\n\n\t// Setup filesystem directories.\n\tif err := kl.setupDataDirs(); err != nil {\n\t\treturn err\n\t}\n\n\t// If the container logs directory does not exist, create it.\n\tif _, err := os.Stat(ContainerLogsDir); err != nil {\n\t\tif err := kl.os.MkdirAll(ContainerLogsDir, 0755); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create directory %q: %v\", ContainerLogsDir, err)\n\t\t}\n\t}\n\n\t// Start the image manager.\n\tkl.imageManager.Start()\n\n\t// Start the certificate manager if it was enabled.\n\tif kl.serverCertificateManager != nil {\n\t\tkl.serverCertificateManager.Start()\n\t}\n\n\t// Start out of memory watcher.\n\tif kl.oomWatcher != nil {\n\t\tif err := kl.oomWatcher.Start(kl.nodeRef); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to start OOM watcher: %w\", err)\n\t\t}\n\t}\n\n\t// Start resource analyzer\n\tkl.resourceAnalyzer.Start()\n\n\treturn nil\n}","line":{"from":1415,"to":1457}} {"id":100006677,"name":"initializeRuntimeDependentModules","signature":"func (kl *Kubelet) initializeRuntimeDependentModules()","file":"pkg/kubelet/kubelet.go","code":"// initializeRuntimeDependentModules will initialize internal modules that require the container runtime to be up.\nfunc (kl *Kubelet) initializeRuntimeDependentModules() {\n\tif err := kl.cadvisor.Start(); err != nil {\n\t\t// Fail kubelet and rely on the babysitter to retry starting kubelet.\n\t\tklog.ErrorS(err, \"Failed to start cAdvisor\")\n\t\tos.Exit(1)\n\t}\n\n\t// trigger on-demand stats collection once so that we have capacity information for ephemeral storage.\n\t// ignore any errors, since if stats collection is not successful, the container manager will fail to start below.\n\tkl.StatsProvider.GetCgroupStats(\"/\", true)\n\t// Start container manager.\n\tnode, err := kl.getNodeAnyWay()\n\tif err != nil {\n\t\t// Fail kubelet and rely on the babysitter to retry starting kubelet.\n\t\tklog.ErrorS(err, \"Kubelet failed to get node info\")\n\t\tos.Exit(1)\n\t}\n\t// containerManager must start after cAdvisor because it needs filesystem capacity information\n\tif err := kl.containerManager.Start(node, kl.GetActivePods, kl.sourcesReady, kl.statusManager, kl.runtimeService, kl.supportLocalStorageCapacityIsolation()); err != nil {\n\t\t// Fail kubelet and rely on the babysitter to retry starting kubelet.\n\t\tklog.ErrorS(err, \"Failed to start ContainerManager\")\n\t\tos.Exit(1)\n\t}\n\t// eviction manager must start after cadvisor because it needs to know if the container runtime has a dedicated imagefs\n\tkl.evictionManager.Start(kl.StatsProvider, kl.GetActivePods, kl.PodIsFinished, evictionMonitoringPeriod)\n\n\t// container log manager must start after container runtime is up to retrieve information from container runtime\n\t// and inform container to reopen log file after log rotation.\n\tkl.containerLogManager.Start()\n\t// Adding Registration Callback function for CSI Driver\n\tkl.pluginManager.AddHandler(pluginwatcherapi.CSIPlugin, plugincache.PluginHandler(csi.PluginHandler))\n\t// Adding Registration Callback function for DRA Plugin\n\tif utilfeature.DefaultFeatureGate.Enabled(features.DynamicResourceAllocation) {\n\t\tkl.pluginManager.AddHandler(pluginwatcherapi.DRAPlugin, plugincache.PluginHandler(draplugin.NewRegistrationHandler()))\n\t}\n\t// Adding Registration Callback function for Device Manager\n\tkl.pluginManager.AddHandler(pluginwatcherapi.DevicePlugin, kl.containerManager.GetPluginRegistrationHandler())\n\n\t// Start the plugin manager\n\tklog.V(4).InfoS(\"Starting plugin manager\")\n\tgo kl.pluginManager.Run(kl.sourcesReady, wait.NeverStop)\n\n\terr = kl.shutdownManager.Start()\n\tif err != nil {\n\t\t// The shutdown manager is not critical for kubelet, so log failure, but don't block Kubelet startup if there was a failure starting it.\n\t\tklog.ErrorS(err, \"Failed to start node shutdown manager\")\n\t}\n}","line":{"from":1459,"to":1507}} {"id":100006678,"name":"Run","signature":"func (kl *Kubelet) Run(updates \u003c-chan kubetypes.PodUpdate)","file":"pkg/kubelet/kubelet.go","code":"// Run starts the kubelet reacting to config updates\nfunc (kl *Kubelet) Run(updates \u003c-chan kubetypes.PodUpdate) {\n\tctx := context.Background()\n\tif kl.logServer == nil {\n\t\tfile := http.FileServer(http.Dir(nodeLogDir))\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.NodeLogQuery) \u0026\u0026 kl.kubeletConfiguration.EnableSystemLogQuery {\n\t\t\tkl.logServer = http.StripPrefix(\"/logs/\", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\t\t\tif nlq, errs := newNodeLogQuery(req.URL.Query()); len(errs) \u003e 0 {\n\t\t\t\t\thttp.Error(w, errs.ToAggregate().Error(), http.StatusBadRequest)\n\t\t\t\t\treturn\n\t\t\t\t} else if nlq != nil {\n\t\t\t\t\tif req.URL.Path != \"/\" \u0026\u0026 req.URL.Path != \"\" {\n\t\t\t\t\t\thttp.Error(w, \"path not allowed in query mode\", http.StatusNotAcceptable)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tif errs := nlq.validate(); len(errs) \u003e 0 {\n\t\t\t\t\t\thttp.Error(w, errs.ToAggregate().Error(), http.StatusNotAcceptable)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\t// Validation ensures that the request does not query services and files at the same time\n\t\t\t\t\tif len(nlq.Services) \u003e 0 {\n\t\t\t\t\t\tjournal.ServeHTTP(w, req)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\t// Validation ensures that the request does not explicitly query multiple files at the same time\n\t\t\t\t\tif len(nlq.Files) == 1 {\n\t\t\t\t\t\t// Account for the \\ being used on Windows clients\n\t\t\t\t\t\treq.URL.Path = filepath.ToSlash(nlq.Files[0])\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Fall back in case the caller is directly trying to query a file\n\t\t\t\t// Example: kubectl get --raw /api/v1/nodes/$name/proxy/logs/foo.log\n\t\t\t\tfile.ServeHTTP(w, req)\n\t\t\t}))\n\t\t} else {\n\t\t\tkl.logServer = http.StripPrefix(\"/logs/\", file)\n\t\t}\n\t}\n\tif kl.kubeClient == nil {\n\t\tklog.InfoS(\"No API server defined - no node status update will be sent\")\n\t}\n\n\t// Start the cloud provider sync manager\n\tif kl.cloudResourceSyncManager != nil {\n\t\tgo kl.cloudResourceSyncManager.Run(wait.NeverStop)\n\t}\n\n\tif err := kl.initializeModules(); err != nil {\n\t\tkl.recorder.Eventf(kl.nodeRef, v1.EventTypeWarning, events.KubeletSetupFailed, err.Error())\n\t\tklog.ErrorS(err, \"Failed to initialize internal modules\")\n\t\tos.Exit(1)\n\t}\n\n\t// Start volume manager\n\tgo kl.volumeManager.Run(kl.sourcesReady, wait.NeverStop)\n\n\tif kl.kubeClient != nil {\n\t\t// Start two go-routines to update the status.\n\t\t//\n\t\t// The first will report to the apiserver every nodeStatusUpdateFrequency and is aimed to provide regular status intervals,\n\t\t// while the second is used to provide a more timely status update during initialization and runs an one-shot update to the apiserver\n\t\t// once the node becomes ready, then exits afterwards.\n\t\t//\n\t\t// Introduce some small jittering to ensure that over time the requests won't start\n\t\t// accumulating at approximately the same time from the set of nodes due to priority and\n\t\t// fairness effect.\n\t\tgo wait.JitterUntil(kl.syncNodeStatus, kl.nodeStatusUpdateFrequency, 0.04, true, wait.NeverStop)\n\t\tgo kl.fastStatusUpdateOnce()\n\n\t\t// start syncing lease\n\t\tgo kl.nodeLeaseController.Run(context.Background())\n\t}\n\tgo wait.Until(kl.updateRuntimeUp, 5*time.Second, wait.NeverStop)\n\n\t// Set up iptables util rules\n\tif kl.makeIPTablesUtilChains {\n\t\tkl.initNetworkUtil()\n\t}\n\n\t// Start component sync loops.\n\tkl.statusManager.Start()\n\n\t// Start syncing RuntimeClasses if enabled.\n\tif kl.runtimeClassManager != nil {\n\t\tkl.runtimeClassManager.Start(wait.NeverStop)\n\t}\n\n\t// Start the pod lifecycle event generator.\n\tkl.pleg.Start()\n\n\t// Start eventedPLEG only if EventedPLEG feature gate is enabled.\n\tif utilfeature.DefaultFeatureGate.Enabled(features.EventedPLEG) {\n\t\tkl.eventedPleg.Start()\n\t}\n\n\tkl.syncLoop(ctx, updates, kl)\n}","line":{"from":1509,"to":1605}} {"id":100006679,"name":"SyncPod","signature":"func (kl *Kubelet) SyncPod(_ context.Context, updateType kubetypes.SyncPodType, pod, mirrorPod *v1.Pod, podStatus *kubecontainer.PodStatus) (isTerminal bool, err error)","file":"pkg/kubelet/kubelet.go","code":"// SyncPod is the transaction script for the sync of a single pod (setting up)\n// a pod. This method is reentrant and expected to converge a pod towards the\n// desired state of the spec. The reverse (teardown) is handled in\n// SyncTerminatingPod and SyncTerminatedPod. If SyncPod exits without error,\n// then the pod runtime state is in sync with the desired configuration state\n// (pod is running). If SyncPod exits with a transient error, the next\n// invocation of SyncPod is expected to make progress towards reaching the\n// desired state. SyncPod exits with isTerminal when the pod was detected to\n// have reached a terminal lifecycle phase due to container exits (for\n// RestartNever or RestartOnFailure) and the next method invoked will be\n// SyncTerminatingPod. If the pod terminates for any other reason, SyncPod\n// will receive a context cancellation and should exit as soon as possible.\n//\n// Arguments:\n//\n// updateType - whether this is a create (first time) or an update, should\n// only be used for metrics since this method must be reentrant\n//\n// pod - the pod that is being set up\n//\n// mirrorPod - the mirror pod known to the kubelet for this pod, if any\n//\n// podStatus - the most recent pod status observed for this pod which can\n// be used to determine the set of actions that should be taken during\n// this loop of SyncPod\n//\n// The workflow is:\n// - If the pod is being created, record pod worker start latency\n// - Call generateAPIPodStatus to prepare an v1.PodStatus for the pod\n// - If the pod is being seen as running for the first time, record pod\n// start latency\n// - Update the status of the pod in the status manager\n// - Stop the pod's containers if it should not be running due to soft\n// admission\n// - Ensure any background tracking for a runnable pod is started\n// - Create a mirror pod if the pod is a static pod, and does not\n// already have a mirror pod\n// - Create the data directories for the pod if they do not exist\n// - Wait for volumes to attach/mount\n// - Fetch the pull secrets for the pod\n// - Call the container runtime's SyncPod callback\n// - Update the traffic shaping for the pod's ingress and egress limits\n//\n// If any step of this workflow errors, the error is returned, and is repeated\n// on the next SyncPod call.\n//\n// This operation writes all events that are dispatched in order to provide\n// the most accurate information possible about an error situation to aid debugging.\n// Callers should not write an event if this operation returns an error.\nfunc (kl *Kubelet) SyncPod(_ context.Context, updateType kubetypes.SyncPodType, pod, mirrorPod *v1.Pod, podStatus *kubecontainer.PodStatus) (isTerminal bool, err error) {\n\t// TODO(#113606): connect this with the incoming context parameter, which comes from the pod worker.\n\t// Currently, using that context causes test failures.\n\tctx, otelSpan := kl.tracer.Start(context.TODO(), \"syncPod\", trace.WithAttributes(\n\t\tattribute.String(\"k8s.pod.uid\", string(pod.UID)),\n\t\tattribute.String(\"k8s.pod\", klog.KObj(pod).String()),\n\t\tattribute.String(\"k8s.pod.name\", pod.Name),\n\t\tattribute.String(\"k8s.pod.update_type\", updateType.String()),\n\t\tattribute.String(\"k8s.namespace.name\", pod.Namespace),\n\t))\n\tklog.V(4).InfoS(\"SyncPod enter\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\tdefer func() {\n\t\tklog.V(4).InfoS(\"SyncPod exit\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID, \"isTerminal\", isTerminal)\n\t\totelSpan.End()\n\t}()\n\n\t// Latency measurements for the main workflow are relative to the\n\t// first time the pod was seen by kubelet.\n\tvar firstSeenTime time.Time\n\tif firstSeenTimeStr, ok := pod.Annotations[kubetypes.ConfigFirstSeenAnnotationKey]; ok {\n\t\tfirstSeenTime = kubetypes.ConvertToTimestamp(firstSeenTimeStr).Get()\n\t}\n\n\t// Record pod worker start latency if being created\n\t// TODO: make pod workers record their own latencies\n\tif updateType == kubetypes.SyncPodCreate {\n\t\tif !firstSeenTime.IsZero() {\n\t\t\t// This is the first time we are syncing the pod. Record the latency\n\t\t\t// since kubelet first saw the pod if firstSeenTime is set.\n\t\t\tmetrics.PodWorkerStartDuration.Observe(metrics.SinceInSeconds(firstSeenTime))\n\t\t} else {\n\t\t\tklog.V(3).InfoS(\"First seen time not recorded for pod\",\n\t\t\t\t\"podUID\", pod.UID,\n\t\t\t\t\"pod\", klog.KObj(pod))\n\t\t}\n\t}\n\n\t// Generate final API pod status with pod and status manager status\n\tapiPodStatus := kl.generateAPIPodStatus(pod, podStatus, false)\n\t// The pod IP may be changed in generateAPIPodStatus if the pod is using host network. (See #24576)\n\t// TODO(random-liu): After writing pod spec into container labels, check whether pod is using host network, and\n\t// set pod IP to hostIP directly in runtime.GetPodStatus\n\tpodStatus.IPs = make([]string, 0, len(apiPodStatus.PodIPs))\n\tfor _, ipInfo := range apiPodStatus.PodIPs {\n\t\tpodStatus.IPs = append(podStatus.IPs, ipInfo.IP)\n\t}\n\tif len(podStatus.IPs) == 0 \u0026\u0026 len(apiPodStatus.PodIP) \u003e 0 {\n\t\tpodStatus.IPs = []string{apiPodStatus.PodIP}\n\t}\n\n\t// If the pod is terminal, we don't need to continue to setup the pod\n\tif apiPodStatus.Phase == v1.PodSucceeded || apiPodStatus.Phase == v1.PodFailed {\n\t\tkl.statusManager.SetPodStatus(pod, apiPodStatus)\n\t\tisTerminal = true\n\t\treturn isTerminal, nil\n\t}\n\n\t// If the pod should not be running, we request the pod's containers be stopped. This is not the same\n\t// as termination (we want to stop the pod, but potentially restart it later if soft admission allows\n\t// it later). Set the status and phase appropriately\n\trunnable := kl.canRunPod(pod)\n\tif !runnable.Admit {\n\t\t// Pod is not runnable; and update the Pod and Container statuses to why.\n\t\tif apiPodStatus.Phase != v1.PodFailed \u0026\u0026 apiPodStatus.Phase != v1.PodSucceeded {\n\t\t\tapiPodStatus.Phase = v1.PodPending\n\t\t}\n\t\tapiPodStatus.Reason = runnable.Reason\n\t\tapiPodStatus.Message = runnable.Message\n\t\t// Waiting containers are not creating.\n\t\tconst waitingReason = \"Blocked\"\n\t\tfor _, cs := range apiPodStatus.InitContainerStatuses {\n\t\t\tif cs.State.Waiting != nil {\n\t\t\t\tcs.State.Waiting.Reason = waitingReason\n\t\t\t}\n\t\t}\n\t\tfor _, cs := range apiPodStatus.ContainerStatuses {\n\t\t\tif cs.State.Waiting != nil {\n\t\t\t\tcs.State.Waiting.Reason = waitingReason\n\t\t\t}\n\t\t}\n\t}\n\n\t// Record the time it takes for the pod to become running\n\t// since kubelet first saw the pod if firstSeenTime is set.\n\texistingStatus, ok := kl.statusManager.GetPodStatus(pod.UID)\n\tif !ok || existingStatus.Phase == v1.PodPending \u0026\u0026 apiPodStatus.Phase == v1.PodRunning \u0026\u0026\n\t\t!firstSeenTime.IsZero() {\n\t\tmetrics.PodStartDuration.Observe(metrics.SinceInSeconds(firstSeenTime))\n\t}\n\n\tkl.statusManager.SetPodStatus(pod, apiPodStatus)\n\n\t// Pods that are not runnable must be stopped - return a typed error to the pod worker\n\tif !runnable.Admit {\n\t\tklog.V(2).InfoS(\"Pod is not runnable and must have running containers stopped\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID, \"message\", runnable.Message)\n\t\tvar syncErr error\n\t\tp := kubecontainer.ConvertPodStatusToRunningPod(kl.getRuntime().Type(), podStatus)\n\t\tif err := kl.killPod(ctx, pod, p, nil); err != nil {\n\t\t\tkl.recorder.Eventf(pod, v1.EventTypeWarning, events.FailedToKillPod, \"error killing pod: %v\", err)\n\t\t\tsyncErr = fmt.Errorf(\"error killing pod: %v\", err)\n\t\t\tutilruntime.HandleError(syncErr)\n\t\t} else {\n\t\t\t// There was no error killing the pod, but the pod cannot be run.\n\t\t\t// Return an error to signal that the sync loop should back off.\n\t\t\tsyncErr = fmt.Errorf(\"pod cannot be run: %s\", runnable.Message)\n\t\t}\n\t\treturn false, syncErr\n\t}\n\n\t// If the network plugin is not ready, only start the pod if it uses the host network\n\tif err := kl.runtimeState.networkErrors(); err != nil \u0026\u0026 !kubecontainer.IsHostNetworkPod(pod) {\n\t\tkl.recorder.Eventf(pod, v1.EventTypeWarning, events.NetworkNotReady, \"%s: %v\", NetworkNotReadyErrorMsg, err)\n\t\treturn false, fmt.Errorf(\"%s: %v\", NetworkNotReadyErrorMsg, err)\n\t}\n\n\t// ensure the kubelet knows about referenced secrets or configmaps used by the pod\n\tif !kl.podWorkers.IsPodTerminationRequested(pod.UID) {\n\t\tif kl.secretManager != nil {\n\t\t\tkl.secretManager.RegisterPod(pod)\n\t\t}\n\t\tif kl.configMapManager != nil {\n\t\t\tkl.configMapManager.RegisterPod(pod)\n\t\t}\n\t}\n\n\t// Create Cgroups for the pod and apply resource parameters\n\t// to them if cgroups-per-qos flag is enabled.\n\tpcm := kl.containerManager.NewPodContainerManager()\n\t// If pod has already been terminated then we need not create\n\t// or update the pod's cgroup\n\t// TODO: once context cancellation is added this check can be removed\n\tif !kl.podWorkers.IsPodTerminationRequested(pod.UID) {\n\t\t// When the kubelet is restarted with the cgroups-per-qos\n\t\t// flag enabled, all the pod's running containers\n\t\t// should be killed intermittently and brought back up\n\t\t// under the qos cgroup hierarchy.\n\t\t// Check if this is the pod's first sync\n\t\tfirstSync := true\n\t\tfor _, containerStatus := range apiPodStatus.ContainerStatuses {\n\t\t\tif containerStatus.State.Running != nil {\n\t\t\t\tfirstSync = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\t// Don't kill containers in pod if pod's cgroups already\n\t\t// exists or the pod is running for the first time\n\t\tpodKilled := false\n\t\tif !pcm.Exists(pod) \u0026\u0026 !firstSync {\n\t\t\tp := kubecontainer.ConvertPodStatusToRunningPod(kl.getRuntime().Type(), podStatus)\n\t\t\tif err := kl.killPod(ctx, pod, p, nil); err == nil {\n\t\t\t\tpodKilled = true\n\t\t\t} else {\n\t\t\t\tklog.ErrorS(err, \"KillPod failed\", \"pod\", klog.KObj(pod), \"podStatus\", podStatus)\n\t\t\t}\n\t\t}\n\t\t// Create and Update pod's Cgroups\n\t\t// Don't create cgroups for run once pod if it was killed above\n\t\t// The current policy is not to restart the run once pods when\n\t\t// the kubelet is restarted with the new flag as run once pods are\n\t\t// expected to run only once and if the kubelet is restarted then\n\t\t// they are not expected to run again.\n\t\t// We don't create and apply updates to cgroup if its a run once pod and was killed above\n\t\tif !(podKilled \u0026\u0026 pod.Spec.RestartPolicy == v1.RestartPolicyNever) {\n\t\t\tif !pcm.Exists(pod) {\n\t\t\t\tif err := kl.containerManager.UpdateQOSCgroups(); err != nil {\n\t\t\t\t\tklog.V(2).InfoS(\"Failed to update QoS cgroups while syncing pod\", \"pod\", klog.KObj(pod), \"err\", err)\n\t\t\t\t}\n\t\t\t\tif err := pcm.EnsureExists(pod); err != nil {\n\t\t\t\t\tkl.recorder.Eventf(pod, v1.EventTypeWarning, events.FailedToCreatePodContainer, \"unable to ensure pod container exists: %v\", err)\n\t\t\t\t\treturn false, fmt.Errorf(\"failed to ensure that the pod: %v cgroups exist and are correctly applied: %v\", pod.UID, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Create Mirror Pod for Static Pod if it doesn't already exist\n\tif kubetypes.IsStaticPod(pod) {\n\t\tdeleted := false\n\t\tif mirrorPod != nil {\n\t\t\tif mirrorPod.DeletionTimestamp != nil || !kl.podManager.IsMirrorPodOf(mirrorPod, pod) {\n\t\t\t\t// The mirror pod is semantically different from the static pod. Remove\n\t\t\t\t// it. The mirror pod will get recreated later.\n\t\t\t\tklog.InfoS(\"Trying to delete pod\", \"pod\", klog.KObj(pod), \"podUID\", mirrorPod.ObjectMeta.UID)\n\t\t\t\tpodFullName := kubecontainer.GetPodFullName(pod)\n\t\t\t\tvar err error\n\t\t\t\tdeleted, err = kl.podManager.DeleteMirrorPod(podFullName, \u0026mirrorPod.ObjectMeta.UID)\n\t\t\t\tif deleted {\n\t\t\t\t\tklog.InfoS(\"Deleted mirror pod because it is outdated\", \"pod\", klog.KObj(mirrorPod))\n\t\t\t\t} else if err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"Failed deleting mirror pod\", \"pod\", klog.KObj(mirrorPod))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif mirrorPod == nil || deleted {\n\t\t\tnode, err := kl.GetNode()\n\t\t\tif err != nil || node.DeletionTimestamp != nil {\n\t\t\t\tklog.V(4).InfoS(\"No need to create a mirror pod, since node has been removed from the cluster\", \"node\", klog.KRef(\"\", string(kl.nodeName)))\n\t\t\t} else {\n\t\t\t\tklog.V(4).InfoS(\"Creating a mirror pod for static pod\", \"pod\", klog.KObj(pod))\n\t\t\t\tif err := kl.podManager.CreateMirrorPod(pod); err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"Failed creating a mirror pod for\", \"pod\", klog.KObj(pod))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Make data directories for the pod\n\tif err := kl.makePodDataDirs(pod); err != nil {\n\t\tkl.recorder.Eventf(pod, v1.EventTypeWarning, events.FailedToMakePodDataDirectories, \"error making pod data directories: %v\", err)\n\t\tklog.ErrorS(err, \"Unable to make pod data directories for pod\", \"pod\", klog.KObj(pod))\n\t\treturn false, err\n\t}\n\n\t// Volume manager will not mount volumes for terminating pods\n\t// TODO: once context cancellation is added this check can be removed\n\tif !kl.podWorkers.IsPodTerminationRequested(pod.UID) {\n\t\t// Wait for volumes to attach/mount\n\t\tif err := kl.volumeManager.WaitForAttachAndMount(pod); err != nil {\n\t\t\tkl.recorder.Eventf(pod, v1.EventTypeWarning, events.FailedMountVolume, \"Unable to attach or mount volumes: %v\", err)\n\t\t\tklog.ErrorS(err, \"Unable to attach or mount volumes for pod; skipping pod\", \"pod\", klog.KObj(pod))\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\t// Fetch the pull secrets for the pod\n\tpullSecrets := kl.getPullSecretsForPod(pod)\n\n\t// Ensure the pod is being probed\n\tkl.probeManager.AddPod(pod)\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) {\n\t\t// Handle pod resize here instead of doing it in HandlePodUpdates because\n\t\t// this conveniently retries any Deferred resize requests\n\t\t// TODO(vinaykul,InPlacePodVerticalScaling): Investigate doing this in HandlePodUpdates + periodic SyncLoop scan\n\t\t// See: https://github.com/kubernetes/kubernetes/pull/102884#discussion_r663160060\n\t\tif kl.podWorkers.CouldHaveRunningContainers(pod.UID) \u0026\u0026 !kubetypes.IsStaticPod(pod) {\n\t\t\tpod = kl.handlePodResourcesResize(pod)\n\t\t}\n\t}\n\n\t// Call the container runtime's SyncPod callback\n\tresult := kl.containerRuntime.SyncPod(ctx, pod, podStatus, pullSecrets, kl.backOff)\n\tkl.reasonCache.Update(pod.UID, result)\n\tif err := result.Error(); err != nil {\n\t\t// Do not return error if the only failures were pods in backoff\n\t\tfor _, r := range result.SyncResults {\n\t\t\tif r.Error != kubecontainer.ErrCrashLoopBackOff \u0026\u0026 r.Error != images.ErrImagePullBackOff {\n\t\t\t\t// Do not record an event here, as we keep all event logging for sync pod failures\n\t\t\t\t// local to container runtime, so we get better errors.\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}\n\n\t\treturn false, nil\n\t}\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) \u0026\u0026 isPodResizeInProgress(pod, \u0026apiPodStatus) {\n\t\t// While resize is in progress, periodically call PLEG to update pod cache\n\t\trunningPod := kubecontainer.ConvertPodStatusToRunningPod(kl.getRuntime().Type(), podStatus)\n\t\tif err, _ := kl.pleg.UpdateCache(\u0026runningPod, pod.UID); err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to update pod cache\", \"pod\", klog.KObj(pod))\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\treturn false, nil\n}","line":{"from":1607,"to":1922}} {"id":100006680,"name":"SyncTerminatingPod","signature":"func (kl *Kubelet) SyncTerminatingPod(_ context.Context, pod *v1.Pod, podStatus *kubecontainer.PodStatus, gracePeriod *int64, podStatusFn func(*v1.PodStatus)) error","file":"pkg/kubelet/kubelet.go","code":"// SyncTerminatingPod is expected to terminate all running containers in a pod. Once this method\n// returns without error, the pod is considered to be terminated and it will be safe to clean up any\n// pod state that is tied to the lifetime of running containers. The next method invoked will be\n// SyncTerminatedPod. This method is expected to return with the grace period provided and the\n// provided context may be cancelled if the duration is exceeded. The method may also be interrupted\n// with a context cancellation if the grace period is shortened by the user or the kubelet (such as\n// during eviction). This method is not guaranteed to be called if a pod is force deleted from the\n// configuration and the kubelet is restarted - SyncTerminatingRuntimePod handles those orphaned\n// pods.\nfunc (kl *Kubelet) SyncTerminatingPod(_ context.Context, pod *v1.Pod, podStatus *kubecontainer.PodStatus, gracePeriod *int64, podStatusFn func(*v1.PodStatus)) error {\n\t// TODO(#113606): connect this with the incoming context parameter, which comes from the pod worker.\n\t// Currently, using that context causes test failures.\n\tctx, otelSpan := kl.tracer.Start(context.Background(), \"syncTerminatingPod\", trace.WithAttributes(\n\t\tattribute.String(\"k8s.pod.uid\", string(pod.UID)),\n\t\tattribute.String(\"k8s.pod\", klog.KObj(pod).String()),\n\t\tattribute.String(\"k8s.pod.name\", pod.Name),\n\t\tattribute.String(\"k8s.namespace.name\", pod.Namespace),\n\t))\n\tdefer otelSpan.End()\n\tklog.V(4).InfoS(\"SyncTerminatingPod enter\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\tdefer klog.V(4).InfoS(\"SyncTerminatingPod exit\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\n\tapiPodStatus := kl.generateAPIPodStatus(pod, podStatus, false)\n\tif podStatusFn != nil {\n\t\tpodStatusFn(\u0026apiPodStatus)\n\t}\n\tkl.statusManager.SetPodStatus(pod, apiPodStatus)\n\n\tif gracePeriod != nil {\n\t\tklog.V(4).InfoS(\"Pod terminating with grace period\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID, \"gracePeriod\", *gracePeriod)\n\t} else {\n\t\tklog.V(4).InfoS(\"Pod terminating with grace period\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID, \"gracePeriod\", nil)\n\t}\n\n\tkl.probeManager.StopLivenessAndStartup(pod)\n\n\tp := kubecontainer.ConvertPodStatusToRunningPod(kl.getRuntime().Type(), podStatus)\n\tif err := kl.killPod(ctx, pod, p, gracePeriod); err != nil {\n\t\tkl.recorder.Eventf(pod, v1.EventTypeWarning, events.FailedToKillPod, \"error killing pod: %v\", err)\n\t\t// there was an error killing the pod, so we return that error directly\n\t\tutilruntime.HandleError(err)\n\t\treturn err\n\t}\n\n\t// Once the containers are stopped, we can stop probing for liveness and readiness.\n\t// TODO: once a pod is terminal, certain probes (liveness exec) could be stopped immediately after\n\t// the detection of a container shutdown or (for readiness) after the first failure. Tracked as\n\t// https://github.com/kubernetes/kubernetes/issues/107894 although may not be worth optimizing.\n\tkl.probeManager.RemovePod(pod)\n\n\t// Guard against consistency issues in KillPod implementations by checking that there are no\n\t// running containers. This method is invoked infrequently so this is effectively free and can\n\t// catch race conditions introduced by callers updating pod status out of order.\n\t// TODO: have KillPod return the terminal status of stopped containers and write that into the\n\t// cache immediately\n\tpodStatus, err := kl.containerRuntime.GetPodStatus(ctx, pod.UID, pod.Name, pod.Namespace)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Unable to read pod status prior to final pod termination\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\t\treturn err\n\t}\n\tvar runningContainers []string\n\ttype container struct {\n\t\tName string\n\t\tState string\n\t\tExitCode int\n\t\tFinishedAt string\n\t}\n\tvar containers []container\n\tklogV := klog.V(4)\n\tklogVEnabled := klogV.Enabled()\n\tfor _, s := range podStatus.ContainerStatuses {\n\t\tif s.State == kubecontainer.ContainerStateRunning {\n\t\t\trunningContainers = append(runningContainers, s.ID.String())\n\t\t}\n\t\tif klogVEnabled {\n\t\t\tcontainers = append(containers, container{Name: s.Name, State: string(s.State), ExitCode: s.ExitCode, FinishedAt: s.FinishedAt.UTC().Format(time.RFC3339Nano)})\n\t\t}\n\t}\n\tif klogVEnabled {\n\t\tsort.Slice(containers, func(i, j int) bool { return containers[i].Name \u003c containers[j].Name })\n\t\tklog.V(4).InfoS(\"Post-termination container state\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID, \"containers\", containers)\n\t}\n\tif len(runningContainers) \u003e 0 {\n\t\treturn fmt.Errorf(\"detected running containers after a successful KillPod, CRI violation: %v\", runningContainers)\n\t}\n\n\t// NOTE: resources must be unprepared AFTER all containers have stopped\n\t// and BEFORE the pod status is changed on the API server\n\t// to avoid race conditions with the resource deallocation code in kubernetes core.\n\tif utilfeature.DefaultFeatureGate.Enabled(features.DynamicResourceAllocation) {\n\t\tif err := kl.UnprepareDynamicResources(pod); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Compute and update the status in cache once the pods are no longer running.\n\t// The computation is done here to ensure the pod status used for it contains\n\t// information about the container end states (including exit codes) - when\n\t// SyncTerminatedPod is called the containers may already be removed.\n\tapiPodStatus = kl.generateAPIPodStatus(pod, podStatus, true)\n\tkl.statusManager.SetPodStatus(pod, apiPodStatus)\n\n\t// we have successfully stopped all containers, the pod is terminating, our status is \"done\"\n\tklog.V(4).InfoS(\"Pod termination stopped all running containers\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\n\treturn nil\n}","line":{"from":1924,"to":2030}} {"id":100006681,"name":"SyncTerminatingRuntimePod","signature":"func (kl *Kubelet) SyncTerminatingRuntimePod(_ context.Context, runningPod *kubecontainer.Pod) error","file":"pkg/kubelet/kubelet.go","code":"// SyncTerminatingRuntimePod is expected to terminate running containers in a pod that we have no\n// configuration for. Once this method returns without error, any remaining local state can be safely\n// cleaned up by background processes in each subsystem. Unlike syncTerminatingPod, we lack\n// knowledge of the full pod spec and so cannot perform lifecycle related operations, only ensure\n// that the remnant of the running pod is terminated and allow garbage collection to proceed. We do\n// not update the status of the pod because with the source of configuration removed, we have no\n// place to send that status.\nfunc (kl *Kubelet) SyncTerminatingRuntimePod(_ context.Context, runningPod *kubecontainer.Pod) error {\n\t// TODO(#113606): connect this with the incoming context parameter, which comes from the pod worker.\n\t// Currently, using that context causes test failures.\n\tctx := context.Background()\n\tpod := runningPod.ToAPIPod()\n\tklog.V(4).InfoS(\"SyncTerminatingRuntimePod enter\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\tdefer klog.V(4).InfoS(\"SyncTerminatingRuntimePod exit\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\n\t// we kill the pod directly since we have lost all other information about the pod.\n\tklog.V(4).InfoS(\"Orphaned running pod terminating without grace period\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\t// TODO: this should probably be zero, to bypass any waiting (needs fixes in container runtime)\n\tgracePeriod := int64(1)\n\tif err := kl.killPod(ctx, pod, *runningPod, \u0026gracePeriod); err != nil {\n\t\tkl.recorder.Eventf(pod, v1.EventTypeWarning, events.FailedToKillPod, \"error killing pod: %v\", err)\n\t\t// there was an error killing the pod, so we return that error directly\n\t\tutilruntime.HandleError(err)\n\t\treturn err\n\t}\n\tklog.V(4).InfoS(\"Pod termination stopped all running orphaned containers\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\treturn nil\n}","line":{"from":2032,"to":2059}} {"id":100006682,"name":"SyncTerminatedPod","signature":"func (kl *Kubelet) SyncTerminatedPod(ctx context.Context, pod *v1.Pod, podStatus *kubecontainer.PodStatus) error","file":"pkg/kubelet/kubelet.go","code":"// SyncTerminatedPod cleans up a pod that has terminated (has no running containers).\n// The invocations in this call are expected to tear down all pod resources.\n// When this method exits the pod is expected to be ready for cleanup. This method\n// reduces the latency of pod cleanup but is not guaranteed to get called in all scenarios.\n//\n// Because the kubelet has no local store of information, all actions in this method that modify\n// on-disk state must be reentrant and be garbage collected by HandlePodCleanups or a separate loop.\n// This typically occurs when a pod is force deleted from configuration (local disk or API) and the\n// kubelet restarts in the middle of the action.\nfunc (kl *Kubelet) SyncTerminatedPod(ctx context.Context, pod *v1.Pod, podStatus *kubecontainer.PodStatus) error {\n\t_, otelSpan := kl.tracer.Start(context.Background(), \"syncTerminatedPod\", trace.WithAttributes(\n\t\tattribute.String(\"k8s.pod.uid\", string(pod.UID)),\n\t\tattribute.String(\"k8s.pod\", klog.KObj(pod).String()),\n\t\tattribute.String(\"k8s.pod.name\", pod.Name),\n\t\tattribute.String(\"k8s.namespace.name\", pod.Namespace),\n\t))\n\tdefer otelSpan.End()\n\tklog.V(4).InfoS(\"SyncTerminatedPod enter\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\tdefer klog.V(4).InfoS(\"SyncTerminatedPod exit\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\n\t// generate the final status of the pod\n\t// TODO: should we simply fold this into TerminatePod? that would give a single pod update\n\tapiPodStatus := kl.generateAPIPodStatus(pod, podStatus, true)\n\n\tkl.statusManager.SetPodStatus(pod, apiPodStatus)\n\n\t// volumes are unmounted after the pod worker reports ShouldPodRuntimeBeRemoved (which is satisfied\n\t// before syncTerminatedPod is invoked)\n\tif err := kl.volumeManager.WaitForUnmount(pod); err != nil {\n\t\treturn err\n\t}\n\tklog.V(4).InfoS(\"Pod termination unmounted volumes\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\n\tif !kl.keepTerminatedPodVolumes {\n\t\t// This waiting loop relies on the background cleanup which starts after pod workers respond\n\t\t// true for ShouldPodRuntimeBeRemoved, which happens after `SyncTerminatingPod` is completed.\n\t\tif err := wait.PollUntilContextCancel(ctx, 100*time.Millisecond, true, func(ctx context.Context) (bool, error) {\n\t\t\tvolumesExist := kl.podVolumesExist(pod.UID)\n\t\t\tif volumesExist {\n\t\t\t\tklog.V(3).InfoS(\"Pod is terminated, but some volumes have not been cleaned up\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\t\t\t}\n\t\t\treturn !volumesExist, nil\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tklog.V(3).InfoS(\"Pod termination cleaned up volume paths\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\t}\n\n\t// After volume unmount is complete, let the secret and configmap managers know we're done with this pod\n\tif kl.secretManager != nil {\n\t\tkl.secretManager.UnregisterPod(pod)\n\t}\n\tif kl.configMapManager != nil {\n\t\tkl.configMapManager.UnregisterPod(pod)\n\t}\n\n\t// Note: we leave pod containers to be reclaimed in the background since dockershim requires the\n\t// container for retrieving logs and we want to make sure logs are available until the pod is\n\t// physically deleted.\n\n\t// remove any cgroups in the hierarchy for pods that are no longer running.\n\tif kl.cgroupsPerQOS {\n\t\tpcm := kl.containerManager.NewPodContainerManager()\n\t\tname, _ := pcm.GetPodContainerName(pod)\n\t\tif err := pcm.Destroy(name); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tklog.V(4).InfoS(\"Pod termination removed cgroups\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\t}\n\n\tkl.usernsManager.Release(pod.UID)\n\n\t// mark the final pod status\n\tkl.statusManager.TerminatePod(pod)\n\tklog.V(4).InfoS(\"Pod is terminated and will need no more status updates\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\n\treturn nil\n}","line":{"from":2061,"to":2138}} {"id":100006683,"name":"getPodsToSync","signature":"func (kl *Kubelet) getPodsToSync() []*v1.Pod","file":"pkg/kubelet/kubelet.go","code":"// Get pods which should be resynchronized. Currently, the following pod should be resynchronized:\n// - pod whose work is ready.\n// - internal modules that request sync of a pod.\nfunc (kl *Kubelet) getPodsToSync() []*v1.Pod {\n\tallPods := kl.podManager.GetPods()\n\tpodUIDs := kl.workQueue.GetWork()\n\tpodUIDSet := sets.NewString()\n\tfor _, podUID := range podUIDs {\n\t\tpodUIDSet.Insert(string(podUID))\n\t}\n\tvar podsToSync []*v1.Pod\n\tfor _, pod := range allPods {\n\t\tif podUIDSet.Has(string(pod.UID)) {\n\t\t\t// The work of the pod is ready\n\t\t\tpodsToSync = append(podsToSync, pod)\n\t\t\tcontinue\n\t\t}\n\t\tfor _, podSyncLoopHandler := range kl.PodSyncLoopHandlers {\n\t\t\tif podSyncLoopHandler.ShouldSync(pod) {\n\t\t\t\tpodsToSync = append(podsToSync, pod)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn podsToSync\n}","line":{"from":2140,"to":2165}} {"id":100006684,"name":"deletePod","signature":"func (kl *Kubelet) deletePod(pod *v1.Pod) error","file":"pkg/kubelet/kubelet.go","code":"// deletePod deletes the pod from the internal state of the kubelet by:\n// 1. stopping the associated pod worker asynchronously\n// 2. signaling to kill the pod by sending on the podKillingCh channel\n//\n// deletePod returns an error if not all sources are ready or the pod is not\n// found in the runtime cache.\nfunc (kl *Kubelet) deletePod(pod *v1.Pod) error {\n\tif pod == nil {\n\t\treturn fmt.Errorf(\"deletePod does not allow nil pod\")\n\t}\n\tif !kl.sourcesReady.AllReady() {\n\t\t// If the sources aren't ready, skip deletion, as we may accidentally delete pods\n\t\t// for sources that haven't reported yet.\n\t\treturn fmt.Errorf(\"skipping delete because sources aren't ready yet\")\n\t}\n\tklog.V(3).InfoS(\"Pod has been deleted and must be killed\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\tkl.podWorkers.UpdatePod(UpdatePodOptions{\n\t\tPod: pod,\n\t\tUpdateType: kubetypes.SyncPodKill,\n\t})\n\t// We leave the volume/directory cleanup to the periodic cleanup routine.\n\treturn nil\n}","line":{"from":2167,"to":2189}} {"id":100006685,"name":"rejectPod","signature":"func (kl *Kubelet) rejectPod(pod *v1.Pod, reason, message string)","file":"pkg/kubelet/kubelet.go","code":"// rejectPod records an event about the pod with the given reason and message,\n// and updates the pod to the failed phase in the status manage.\nfunc (kl *Kubelet) rejectPod(pod *v1.Pod, reason, message string) {\n\tkl.recorder.Eventf(pod, v1.EventTypeWarning, reason, message)\n\tkl.statusManager.SetPodStatus(pod, v1.PodStatus{\n\t\tPhase: v1.PodFailed,\n\t\tReason: reason,\n\t\tMessage: \"Pod was rejected: \" + message})\n}","line":{"from":2191,"to":2199}} {"id":100006686,"name":"canAdmitPod","signature":"func (kl *Kubelet) canAdmitPod(pods []*v1.Pod, pod *v1.Pod) (bool, string, string)","file":"pkg/kubelet/kubelet.go","code":"// canAdmitPod determines if a pod can be admitted, and gives a reason if it\n// cannot. \"pod\" is new pod, while \"pods\" are all admitted pods\n// The function returns a boolean value indicating whether the pod\n// can be admitted, a brief single-word reason and a message explaining why\n// the pod cannot be admitted.\nfunc (kl *Kubelet) canAdmitPod(pods []*v1.Pod, pod *v1.Pod) (bool, string, string) {\n\t// the kubelet will invoke each pod admit handler in sequence\n\t// if any handler rejects, the pod is rejected.\n\t// TODO: move out of disk check into a pod admitter\n\t// TODO: out of resource eviction should have a pod admitter call-out\n\tattrs := \u0026lifecycle.PodAdmitAttributes{Pod: pod, OtherPods: pods}\n\tif utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) {\n\t\t// Use allocated resources values from checkpoint store (source of truth) to determine fit\n\t\totherPods := make([]*v1.Pod, 0, len(pods))\n\t\tfor _, p := range pods {\n\t\t\top := p.DeepCopy()\n\t\t\tfor _, c := range op.Spec.Containers {\n\t\t\t\tallocatedResources, found := kl.statusManager.GetContainerResourceAllocation(string(p.UID), c.Name)\n\t\t\t\tif c.Resources.Requests != nil \u0026\u0026 found {\n\t\t\t\t\tc.Resources.Requests[v1.ResourceCPU] = allocatedResources[v1.ResourceCPU]\n\t\t\t\t\tc.Resources.Requests[v1.ResourceMemory] = allocatedResources[v1.ResourceMemory]\n\t\t\t\t}\n\t\t\t}\n\t\t\totherPods = append(otherPods, op)\n\t\t}\n\t\tattrs.OtherPods = otherPods\n\t}\n\tfor _, podAdmitHandler := range kl.admitHandlers {\n\t\tif result := podAdmitHandler.Admit(attrs); !result.Admit {\n\t\t\treturn false, result.Reason, result.Message\n\t\t}\n\t}\n\n\treturn true, \"\", \"\"\n}","line":{"from":2201,"to":2235}} {"id":100006687,"name":"canRunPod","signature":"func (kl *Kubelet) canRunPod(pod *v1.Pod) lifecycle.PodAdmitResult","file":"pkg/kubelet/kubelet.go","code":"func (kl *Kubelet) canRunPod(pod *v1.Pod) lifecycle.PodAdmitResult {\n\tattrs := \u0026lifecycle.PodAdmitAttributes{Pod: pod}\n\t// Get \"OtherPods\". Rejected pods are failed, so only include admitted pods that are alive.\n\tattrs.OtherPods = kl.GetActivePods()\n\n\tfor _, handler := range kl.softAdmitHandlers {\n\t\tif result := handler.Admit(attrs); !result.Admit {\n\t\t\treturn result\n\t\t}\n\t}\n\n\treturn lifecycle.PodAdmitResult{Admit: true}\n}","line":{"from":2237,"to":2249}} {"id":100006688,"name":"syncLoop","signature":"func (kl *Kubelet) syncLoop(ctx context.Context, updates \u003c-chan kubetypes.PodUpdate, handler SyncHandler)","file":"pkg/kubelet/kubelet.go","code":"// syncLoop is the main loop for processing changes. It watches for changes from\n// three channels (file, apiserver, and http) and creates a union of them. For\n// any new change seen, will run a sync against desired state and running state. If\n// no changes are seen to the configuration, will synchronize the last known desired\n// state every sync-frequency seconds. Never returns.\nfunc (kl *Kubelet) syncLoop(ctx context.Context, updates \u003c-chan kubetypes.PodUpdate, handler SyncHandler) {\n\tklog.InfoS(\"Starting kubelet main sync loop\")\n\t// The syncTicker wakes up kubelet to checks if there are any pod workers\n\t// that need to be sync'd. A one-second period is sufficient because the\n\t// sync interval is defaulted to 10s.\n\tsyncTicker := time.NewTicker(time.Second)\n\tdefer syncTicker.Stop()\n\thousekeepingTicker := time.NewTicker(housekeepingPeriod)\n\tdefer housekeepingTicker.Stop()\n\tplegCh := kl.pleg.Watch()\n\tconst (\n\t\tbase = 100 * time.Millisecond\n\t\tmax = 5 * time.Second\n\t\tfactor = 2\n\t)\n\tduration := base\n\t// Responsible for checking limits in resolv.conf\n\t// The limits do not have anything to do with individual pods\n\t// Since this is called in syncLoop, we don't need to call it anywhere else\n\tif kl.dnsConfigurer != nil \u0026\u0026 kl.dnsConfigurer.ResolverConfig != \"\" {\n\t\tkl.dnsConfigurer.CheckLimitsForResolvConf()\n\t}\n\n\tfor {\n\t\tif err := kl.runtimeState.runtimeErrors(); err != nil {\n\t\t\tklog.ErrorS(err, \"Skipping pod synchronization\")\n\t\t\t// exponential backoff\n\t\t\ttime.Sleep(duration)\n\t\t\tduration = time.Duration(math.Min(float64(max), factor*float64(duration)))\n\t\t\tcontinue\n\t\t}\n\t\t// reset backoff if we have a success\n\t\tduration = base\n\n\t\tkl.syncLoopMonitor.Store(kl.clock.Now())\n\t\tif !kl.syncLoopIteration(ctx, updates, handler, syncTicker.C, housekeepingTicker.C, plegCh) {\n\t\t\tbreak\n\t\t}\n\t\tkl.syncLoopMonitor.Store(kl.clock.Now())\n\t}\n}","line":{"from":2251,"to":2296}} {"id":100006689,"name":"syncLoopIteration","signature":"func (kl *Kubelet) syncLoopIteration(ctx context.Context, configCh \u003c-chan kubetypes.PodUpdate, handler SyncHandler,","file":"pkg/kubelet/kubelet.go","code":"// syncLoopIteration reads from various channels and dispatches pods to the\n// given handler.\n//\n// Arguments:\n// 1. configCh: a channel to read config events from\n// 2. handler: the SyncHandler to dispatch pods to\n// 3. syncCh: a channel to read periodic sync events from\n// 4. housekeepingCh: a channel to read housekeeping events from\n// 5. plegCh: a channel to read PLEG updates from\n//\n// Events are also read from the kubelet liveness manager's update channel.\n//\n// The workflow is to read from one of the channels, handle that event, and\n// update the timestamp in the sync loop monitor.\n//\n// Here is an appropriate place to note that despite the syntactical\n// similarity to the switch statement, the case statements in a select are\n// evaluated in a pseudorandom order if there are multiple channels ready to\n// read from when the select is evaluated. In other words, case statements\n// are evaluated in random order, and you can not assume that the case\n// statements evaluate in order if multiple channels have events.\n//\n// With that in mind, in truly no particular order, the different channels\n// are handled as follows:\n//\n// - configCh: dispatch the pods for the config change to the appropriate\n// handler callback for the event type\n// - plegCh: update the runtime cache; sync pod\n// - syncCh: sync all pods waiting for sync\n// - housekeepingCh: trigger cleanup of pods\n// - health manager: sync pods that have failed or in which one or more\n// containers have failed health checks\nfunc (kl *Kubelet) syncLoopIteration(ctx context.Context, configCh \u003c-chan kubetypes.PodUpdate, handler SyncHandler,\n\tsyncCh \u003c-chan time.Time, housekeepingCh \u003c-chan time.Time, plegCh \u003c-chan *pleg.PodLifecycleEvent) bool {\n\tselect {\n\tcase u, open := \u003c-configCh:\n\t\t// Update from a config source; dispatch it to the right handler\n\t\t// callback.\n\t\tif !open {\n\t\t\tklog.ErrorS(nil, \"Update channel is closed, exiting the sync loop\")\n\t\t\treturn false\n\t\t}\n\n\t\tswitch u.Op {\n\t\tcase kubetypes.ADD:\n\t\t\tklog.V(2).InfoS(\"SyncLoop ADD\", \"source\", u.Source, \"pods\", klog.KObjSlice(u.Pods))\n\t\t\t// After restarting, kubelet will get all existing pods through\n\t\t\t// ADD as if they are new pods. These pods will then go through the\n\t\t\t// admission process and *may* be rejected. This can be resolved\n\t\t\t// once we have checkpointing.\n\t\t\thandler.HandlePodAdditions(u.Pods)\n\t\tcase kubetypes.UPDATE:\n\t\t\tklog.V(2).InfoS(\"SyncLoop UPDATE\", \"source\", u.Source, \"pods\", klog.KObjSlice(u.Pods))\n\t\t\thandler.HandlePodUpdates(u.Pods)\n\t\tcase kubetypes.REMOVE:\n\t\t\tklog.V(2).InfoS(\"SyncLoop REMOVE\", \"source\", u.Source, \"pods\", klog.KObjSlice(u.Pods))\n\t\t\thandler.HandlePodRemoves(u.Pods)\n\t\tcase kubetypes.RECONCILE:\n\t\t\tklog.V(4).InfoS(\"SyncLoop RECONCILE\", \"source\", u.Source, \"pods\", klog.KObjSlice(u.Pods))\n\t\t\thandler.HandlePodReconcile(u.Pods)\n\t\tcase kubetypes.DELETE:\n\t\t\tklog.V(2).InfoS(\"SyncLoop DELETE\", \"source\", u.Source, \"pods\", klog.KObjSlice(u.Pods))\n\t\t\t// DELETE is treated as a UPDATE because of graceful deletion.\n\t\t\thandler.HandlePodUpdates(u.Pods)\n\t\tcase kubetypes.SET:\n\t\t\t// TODO: Do we want to support this?\n\t\t\tklog.ErrorS(nil, \"Kubelet does not support snapshot update\")\n\t\tdefault:\n\t\t\tklog.ErrorS(nil, \"Invalid operation type received\", \"operation\", u.Op)\n\t\t}\n\n\t\tkl.sourcesReady.AddSource(u.Source)\n\n\tcase e := \u003c-plegCh:\n\t\tif isSyncPodWorthy(e) {\n\t\t\t// PLEG event for a pod; sync it.\n\t\t\tif pod, ok := kl.podManager.GetPodByUID(e.ID); ok {\n\t\t\t\tklog.V(2).InfoS(\"SyncLoop (PLEG): event for pod\", \"pod\", klog.KObj(pod), \"event\", e)\n\t\t\t\thandler.HandlePodSyncs([]*v1.Pod{pod})\n\t\t\t} else {\n\t\t\t\t// If the pod no longer exists, ignore the event.\n\t\t\t\tklog.V(4).InfoS(\"SyncLoop (PLEG): pod does not exist, ignore irrelevant event\", \"event\", e)\n\t\t\t}\n\t\t}\n\n\t\tif e.Type == pleg.ContainerDied {\n\t\t\tif containerID, ok := e.Data.(string); ok {\n\t\t\t\tkl.cleanUpContainersInPod(e.ID, containerID)\n\t\t\t}\n\t\t}\n\tcase \u003c-syncCh:\n\t\t// Sync pods waiting for sync\n\t\tpodsToSync := kl.getPodsToSync()\n\t\tif len(podsToSync) == 0 {\n\t\t\tbreak\n\t\t}\n\t\tklog.V(4).InfoS(\"SyncLoop (SYNC) pods\", \"total\", len(podsToSync), \"pods\", klog.KObjSlice(podsToSync))\n\t\thandler.HandlePodSyncs(podsToSync)\n\tcase update := \u003c-kl.livenessManager.Updates():\n\t\tif update.Result == proberesults.Failure {\n\t\t\thandleProbeSync(kl, update, handler, \"liveness\", \"unhealthy\")\n\t\t}\n\tcase update := \u003c-kl.readinessManager.Updates():\n\t\tready := update.Result == proberesults.Success\n\t\tkl.statusManager.SetContainerReadiness(update.PodUID, update.ContainerID, ready)\n\n\t\tstatus := \"\"\n\t\tif ready {\n\t\t\tstatus = \"ready\"\n\t\t}\n\t\thandleProbeSync(kl, update, handler, \"readiness\", status)\n\tcase update := \u003c-kl.startupManager.Updates():\n\t\tstarted := update.Result == proberesults.Success\n\t\tkl.statusManager.SetContainerStartup(update.PodUID, update.ContainerID, started)\n\n\t\tstatus := \"unhealthy\"\n\t\tif started {\n\t\t\tstatus = \"started\"\n\t\t}\n\t\thandleProbeSync(kl, update, handler, \"startup\", status)\n\tcase \u003c-housekeepingCh:\n\t\tif !kl.sourcesReady.AllReady() {\n\t\t\t// If the sources aren't ready or volume manager has not yet synced the states,\n\t\t\t// skip housekeeping, as we may accidentally delete pods from unready sources.\n\t\t\tklog.V(4).InfoS(\"SyncLoop (housekeeping, skipped): sources aren't ready yet\")\n\t\t} else {\n\t\t\tstart := time.Now()\n\t\t\tklog.V(4).InfoS(\"SyncLoop (housekeeping)\")\n\t\t\tif err := handler.HandlePodCleanups(ctx); err != nil {\n\t\t\t\tklog.ErrorS(err, \"Failed cleaning pods\")\n\t\t\t}\n\t\t\tduration := time.Since(start)\n\t\t\tif duration \u003e housekeepingWarningDuration {\n\t\t\t\tklog.ErrorS(fmt.Errorf(\"housekeeping took too long\"), \"Housekeeping took longer than expected\", \"expected\", housekeepingWarningDuration, \"actual\", duration.Round(time.Millisecond))\n\t\t\t}\n\t\t\tklog.V(4).InfoS(\"SyncLoop (housekeeping) end\", \"duration\", duration.Round(time.Millisecond))\n\t\t}\n\t}\n\treturn true\n}","line":{"from":2298,"to":2437}} {"id":100006690,"name":"handleProbeSync","signature":"func handleProbeSync(kl *Kubelet, update proberesults.Update, handler SyncHandler, probe, status string)","file":"pkg/kubelet/kubelet.go","code":"func handleProbeSync(kl *Kubelet, update proberesults.Update, handler SyncHandler, probe, status string) {\n\t// We should not use the pod from manager, because it is never updated after initialization.\n\tpod, ok := kl.podManager.GetPodByUID(update.PodUID)\n\tif !ok {\n\t\t// If the pod no longer exists, ignore the update.\n\t\tklog.V(4).InfoS(\"SyncLoop (probe): ignore irrelevant update\", \"probe\", probe, \"status\", status, \"update\", update)\n\t\treturn\n\t}\n\tklog.V(1).InfoS(\"SyncLoop (probe)\", \"probe\", probe, \"status\", status, \"pod\", klog.KObj(pod))\n\thandler.HandlePodSyncs([]*v1.Pod{pod})\n}","line":{"from":2439,"to":2449}} {"id":100006691,"name":"dispatchWork","signature":"func (kl *Kubelet) dispatchWork(pod *v1.Pod, syncType kubetypes.SyncPodType, mirrorPod *v1.Pod, start time.Time)","file":"pkg/kubelet/kubelet.go","code":"// dispatchWork starts the asynchronous sync of the pod in a pod worker.\n// If the pod has completed termination, dispatchWork will perform no action.\nfunc (kl *Kubelet) dispatchWork(pod *v1.Pod, syncType kubetypes.SyncPodType, mirrorPod *v1.Pod, start time.Time) {\n\t// Run the sync in an async worker.\n\tkl.podWorkers.UpdatePod(UpdatePodOptions{\n\t\tPod: pod,\n\t\tMirrorPod: mirrorPod,\n\t\tUpdateType: syncType,\n\t\tStartTime: start,\n\t})\n\t// Note the number of containers for new pods.\n\tif syncType == kubetypes.SyncPodCreate {\n\t\tmetrics.ContainersPerPodCount.Observe(float64(len(pod.Spec.Containers)))\n\t}\n}","line":{"from":2451,"to":2465}} {"id":100006692,"name":"handleMirrorPod","signature":"func (kl *Kubelet) handleMirrorPod(mirrorPod *v1.Pod, start time.Time)","file":"pkg/kubelet/kubelet.go","code":"// TODO: handle mirror pods in a separate component (issue #17251)\nfunc (kl *Kubelet) handleMirrorPod(mirrorPod *v1.Pod, start time.Time) {\n\t// Mirror pod ADD/UPDATE/DELETE operations are considered an UPDATE to the\n\t// corresponding static pod. Send update to the pod worker if the static\n\t// pod exists.\n\tif pod, ok := kl.podManager.GetPodByMirrorPod(mirrorPod); ok {\n\t\tkl.dispatchWork(pod, kubetypes.SyncPodUpdate, mirrorPod, start)\n\t}\n}","line":{"from":2467,"to":2475}} {"id":100006693,"name":"HandlePodAdditions","signature":"func (kl *Kubelet) HandlePodAdditions(pods []*v1.Pod)","file":"pkg/kubelet/kubelet.go","code":"// HandlePodAdditions is the callback in SyncHandler for pods being added from\n// a config source.\nfunc (kl *Kubelet) HandlePodAdditions(pods []*v1.Pod) {\n\tstart := kl.clock.Now()\n\tsort.Sort(sliceutils.PodsByCreationTime(pods))\n\tif utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) {\n\t\tkl.podResizeMutex.Lock()\n\t\tdefer kl.podResizeMutex.Unlock()\n\t}\n\tfor _, pod := range pods {\n\t\texistingPods := kl.podManager.GetPods()\n\t\t// Always add the pod to the pod manager. Kubelet relies on the pod\n\t\t// manager as the source of truth for the desired state. If a pod does\n\t\t// not exist in the pod manager, it means that it has been deleted in\n\t\t// the apiserver and no action (other than cleanup) is required.\n\t\tkl.podManager.AddPod(pod)\n\n\t\tif kubetypes.IsMirrorPod(pod) {\n\t\t\tkl.handleMirrorPod(pod, start)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Only go through the admission process if the pod is not requested\n\t\t// for termination by another part of the kubelet. If the pod is already\n\t\t// using resources (previously admitted), the pod worker is going to be\n\t\t// shutting it down. If the pod hasn't started yet, we know that when\n\t\t// the pod worker is invoked it will also avoid setting up the pod, so\n\t\t// we simply avoid doing any work.\n\t\tif !kl.podWorkers.IsPodTerminationRequested(pod.UID) {\n\t\t\t// We failed pods that we rejected, so activePods include all admitted\n\t\t\t// pods that are alive.\n\t\t\tactivePods := kl.filterOutInactivePods(existingPods)\n\n\t\t\tif utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) {\n\t\t\t\t// To handle kubelet restarts, test pod admissibility using AllocatedResources values\n\t\t\t\t// (for cpu \u0026 memory) from checkpoint store. If found, that is the source of truth.\n\t\t\t\tpodCopy := pod.DeepCopy()\n\t\t\t\tfor _, c := range podCopy.Spec.Containers {\n\t\t\t\t\tallocatedResources, found := kl.statusManager.GetContainerResourceAllocation(string(pod.UID), c.Name)\n\t\t\t\t\tif c.Resources.Requests != nil \u0026\u0026 found {\n\t\t\t\t\t\tc.Resources.Requests[v1.ResourceCPU] = allocatedResources[v1.ResourceCPU]\n\t\t\t\t\t\tc.Resources.Requests[v1.ResourceMemory] = allocatedResources[v1.ResourceMemory]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Check if we can admit the pod; if not, reject it.\n\t\t\t\tif ok, reason, message := kl.canAdmitPod(activePods, podCopy); !ok {\n\t\t\t\t\tkl.rejectPod(pod, reason, message)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// For new pod, checkpoint the resource values at which the Pod has been admitted\n\t\t\t\tif err := kl.statusManager.SetPodAllocation(podCopy); err != nil {\n\t\t\t\t\t//TODO(vinaykul,InPlacePodVerticalScaling): Can we recover from this in some way? Investigate\n\t\t\t\t\tklog.ErrorS(err, \"SetPodAllocation failed\", \"pod\", klog.KObj(pod))\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Check if we can admit the pod; if not, reject it.\n\t\t\t\tif ok, reason, message := kl.canAdmitPod(activePods, pod); !ok {\n\t\t\t\t\tkl.rejectPod(pod, reason, message)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tmirrorPod, _ := kl.podManager.GetMirrorPodByPod(pod)\n\t\tkl.dispatchWork(pod, kubetypes.SyncPodCreate, mirrorPod, start)\n\t}\n}","line":{"from":2477,"to":2542}} {"id":100006694,"name":"HandlePodUpdates","signature":"func (kl *Kubelet) HandlePodUpdates(pods []*v1.Pod)","file":"pkg/kubelet/kubelet.go","code":"// HandlePodUpdates is the callback in the SyncHandler interface for pods\n// being updated from a config source.\nfunc (kl *Kubelet) HandlePodUpdates(pods []*v1.Pod) {\n\tstart := kl.clock.Now()\n\tfor _, pod := range pods {\n\t\tkl.podManager.UpdatePod(pod)\n\t\tif kubetypes.IsMirrorPod(pod) {\n\t\t\tkl.handleMirrorPod(pod, start)\n\t\t\tcontinue\n\t\t}\n\t\tmirrorPod, _ := kl.podManager.GetMirrorPodByPod(pod)\n\t\tkl.dispatchWork(pod, kubetypes.SyncPodUpdate, mirrorPod, start)\n\t}\n}","line":{"from":2544,"to":2557}} {"id":100006695,"name":"HandlePodRemoves","signature":"func (kl *Kubelet) HandlePodRemoves(pods []*v1.Pod)","file":"pkg/kubelet/kubelet.go","code":"// HandlePodRemoves is the callback in the SyncHandler interface for pods\n// being removed from a config source.\nfunc (kl *Kubelet) HandlePodRemoves(pods []*v1.Pod) {\n\tstart := kl.clock.Now()\n\tfor _, pod := range pods {\n\t\tkl.podManager.DeletePod(pod)\n\t\tif kubetypes.IsMirrorPod(pod) {\n\t\t\tkl.handleMirrorPod(pod, start)\n\t\t\tcontinue\n\t\t}\n\t\t// Deletion is allowed to fail because the periodic cleanup routine\n\t\t// will trigger deletion again.\n\t\tif err := kl.deletePod(pod); err != nil {\n\t\t\tklog.V(2).InfoS(\"Failed to delete pod\", \"pod\", klog.KObj(pod), \"err\", err)\n\t\t}\n\t}\n}","line":{"from":2559,"to":2575}} {"id":100006696,"name":"HandlePodReconcile","signature":"func (kl *Kubelet) HandlePodReconcile(pods []*v1.Pod)","file":"pkg/kubelet/kubelet.go","code":"// HandlePodReconcile is the callback in the SyncHandler interface for pods\n// that should be reconciled.\nfunc (kl *Kubelet) HandlePodReconcile(pods []*v1.Pod) {\n\tstart := kl.clock.Now()\n\tfor _, pod := range pods {\n\t\t// Update the pod in pod manager, status manager will do periodically reconcile according\n\t\t// to the pod manager.\n\t\tkl.podManager.UpdatePod(pod)\n\n\t\t// Reconcile Pod \"Ready\" condition if necessary. Trigger sync pod for reconciliation.\n\t\tif status.NeedToReconcilePodReadiness(pod) {\n\t\t\tmirrorPod, _ := kl.podManager.GetMirrorPodByPod(pod)\n\t\t\tkl.dispatchWork(pod, kubetypes.SyncPodSync, mirrorPod, start)\n\t\t}\n\n\t\t// After an evicted pod is synced, all dead containers in the pod can be removed.\n\t\tif eviction.PodIsEvicted(pod.Status) {\n\t\t\tif podStatus, err := kl.podCache.Get(pod.UID); err == nil {\n\t\t\t\tkl.containerDeletor.deleteContainersInPod(\"\", podStatus, true)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":2577,"to":2599}} {"id":100006697,"name":"HandlePodSyncs","signature":"func (kl *Kubelet) HandlePodSyncs(pods []*v1.Pod)","file":"pkg/kubelet/kubelet.go","code":"// HandlePodSyncs is the callback in the syncHandler interface for pods\n// that should be dispatched to pod workers for sync.\nfunc (kl *Kubelet) HandlePodSyncs(pods []*v1.Pod) {\n\tstart := kl.clock.Now()\n\tfor _, pod := range pods {\n\t\tmirrorPod, _ := kl.podManager.GetMirrorPodByPod(pod)\n\t\tkl.dispatchWork(pod, kubetypes.SyncPodSync, mirrorPod, start)\n\t}\n}","line":{"from":2601,"to":2609}} {"id":100006698,"name":"isPodResizeInProgress","signature":"func isPodResizeInProgress(pod *v1.Pod, podStatus *v1.PodStatus) bool","file":"pkg/kubelet/kubelet.go","code":"func isPodResizeInProgress(pod *v1.Pod, podStatus *v1.PodStatus) bool {\n\tfor _, c := range pod.Spec.Containers {\n\t\tif cs, ok := podutil.GetContainerStatus(podStatus.ContainerStatuses, c.Name); ok {\n\t\t\tif cs.Resources == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif diff.ObjectDiff(c.Resources.Limits, cs.Resources.Limits) != \"\" ||\n\t\t\t\tdiff.ObjectDiff(cs.AllocatedResources, cs.Resources.Requests) != \"\" {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":2611,"to":2624}} {"id":100006699,"name":"canResizePod","signature":"func (kl *Kubelet) canResizePod(pod *v1.Pod) (bool, *v1.Pod, v1.PodResizeStatus)","file":"pkg/kubelet/kubelet.go","code":"func (kl *Kubelet) canResizePod(pod *v1.Pod) (bool, *v1.Pod, v1.PodResizeStatus) {\n\tvar otherActivePods []*v1.Pod\n\n\tnode, err := kl.getNodeAnyWay()\n\tif err != nil {\n\t\tklog.ErrorS(err, \"getNodeAnyway function failed\")\n\t\treturn false, nil, \"\"\n\t}\n\tpodCopy := pod.DeepCopy()\n\tcpuAvailable := node.Status.Allocatable.Cpu().MilliValue()\n\tmemAvailable := node.Status.Allocatable.Memory().Value()\n\tcpuRequests := resource.GetResourceRequest(podCopy, v1.ResourceCPU)\n\tmemRequests := resource.GetResourceRequest(podCopy, v1.ResourceMemory)\n\tif cpuRequests \u003e cpuAvailable || memRequests \u003e memAvailable {\n\t\tklog.V(3).InfoS(\"Resize is not feasible as request exceeds allocatable node resources\", \"pod\", podCopy.Name)\n\t\treturn false, podCopy, v1.PodResizeStatusInfeasible\n\t}\n\n\t// Treat the existing pod needing resize as a new pod with desired resources seeking admit.\n\t// If desired resources don't fit, pod continues to run with currently allocated resources.\n\tactivePods := kl.GetActivePods()\n\tfor _, p := range activePods {\n\t\tif p.UID != pod.UID {\n\t\t\totherActivePods = append(otherActivePods, p)\n\t\t}\n\t}\n\n\tif ok, failReason, failMessage := kl.canAdmitPod(otherActivePods, podCopy); !ok {\n\t\t// Log reason and return. Let the next sync iteration retry the resize\n\t\tklog.V(3).InfoS(\"Resize cannot be accommodated\", \"pod\", podCopy.Name, \"reason\", failReason, \"message\", failMessage)\n\t\treturn false, podCopy, v1.PodResizeStatusDeferred\n\t}\n\n\tfor _, container := range podCopy.Spec.Containers {\n\t\tidx, found := podutil.GetIndexOfContainerStatus(podCopy.Status.ContainerStatuses, container.Name)\n\t\tif found {\n\t\t\tfor rName, rQuantity := range container.Resources.Requests {\n\t\t\t\tpodCopy.Status.ContainerStatuses[idx].AllocatedResources[rName] = rQuantity\n\t\t\t}\n\t\t}\n\t}\n\treturn true, podCopy, v1.PodResizeStatusInProgress\n}","line":{"from":2626,"to":2668}} {"id":100006700,"name":"handlePodResourcesResize","signature":"func (kl *Kubelet) handlePodResourcesResize(pod *v1.Pod) *v1.Pod","file":"pkg/kubelet/kubelet.go","code":"func (kl *Kubelet) handlePodResourcesResize(pod *v1.Pod) *v1.Pod {\n\tif pod.Status.Phase != v1.PodRunning {\n\t\treturn pod\n\t}\n\tpodResized := false\n\tfor _, container := range pod.Spec.Containers {\n\t\tif len(container.Resources.Requests) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tcontainerStatus, found := podutil.GetContainerStatus(pod.Status.ContainerStatuses, container.Name)\n\t\tif !found {\n\t\t\tklog.V(5).InfoS(\"ContainerStatus not found\", \"pod\", pod.Name, \"container\", container.Name)\n\t\t\tbreak\n\t\t}\n\t\tif len(containerStatus.AllocatedResources) != len(container.Resources.Requests) {\n\t\t\tklog.V(5).InfoS(\"ContainerStatus.AllocatedResources length mismatch\", \"pod\", pod.Name, \"container\", container.Name)\n\t\t\tbreak\n\t\t}\n\t\tif len(diff.ObjectDiff(container.Resources.Requests, containerStatus.AllocatedResources)) \u003e 0 {\n\t\t\tpodResized = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !podResized {\n\t\treturn pod\n\t}\n\n\tkl.podResizeMutex.Lock()\n\tdefer kl.podResizeMutex.Unlock()\n\tfit, updatedPod, resizeStatus := kl.canResizePod(pod)\n\tif updatedPod == nil {\n\t\treturn pod\n\t}\n\tif fit {\n\t\t// Update pod resource allocation checkpoint\n\t\tif err := kl.statusManager.SetPodAllocation(updatedPod); err != nil {\n\t\t\t//TODO(vinaykul,InPlacePodVerticalScaling): Can we recover from this in some way? Investigate\n\t\t\tklog.ErrorS(err, \"SetPodAllocation failed\", \"pod\", klog.KObj(updatedPod))\n\t\t\treturn pod\n\t\t}\n\t}\n\tif resizeStatus != \"\" {\n\t\t// Save resize decision to checkpoint\n\t\tif err := kl.statusManager.SetPodResizeStatus(updatedPod.UID, resizeStatus); err != nil {\n\t\t\t//TODO(vinaykul,InPlacePodVerticalScaling): Can we recover from this in some way? Investigate\n\t\t\tklog.ErrorS(err, \"SetPodResizeStatus failed\", \"pod\", klog.KObj(updatedPod))\n\t\t\treturn pod\n\t\t}\n\t\tupdatedPod.Status.Resize = resizeStatus\n\t}\n\tkl.podManager.UpdatePod(updatedPod)\n\tkl.statusManager.SetPodStatus(updatedPod, updatedPod.Status)\n\treturn updatedPod\n}","line":{"from":2670,"to":2723}} {"id":100006701,"name":"LatestLoopEntryTime","signature":"func (kl *Kubelet) LatestLoopEntryTime() time.Time","file":"pkg/kubelet/kubelet.go","code":"// LatestLoopEntryTime returns the last time in the sync loop monitor.\nfunc (kl *Kubelet) LatestLoopEntryTime() time.Time {\n\tval := kl.syncLoopMonitor.Load()\n\tif val == nil {\n\t\treturn time.Time{}\n\t}\n\treturn val.(time.Time)\n}","line":{"from":2725,"to":2732}} {"id":100006702,"name":"updateRuntimeUp","signature":"func (kl *Kubelet) updateRuntimeUp()","file":"pkg/kubelet/kubelet.go","code":"// updateRuntimeUp calls the container runtime status callback, initializing\n// the runtime dependent modules when the container runtime first comes up,\n// and returns an error if the status check fails. If the status check is OK,\n// update the container runtime uptime in the kubelet runtimeState.\nfunc (kl *Kubelet) updateRuntimeUp() {\n\tkl.updateRuntimeMux.Lock()\n\tdefer kl.updateRuntimeMux.Unlock()\n\tctx := context.Background()\n\n\ts, err := kl.containerRuntime.Status(ctx)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Container runtime sanity check failed\")\n\t\treturn\n\t}\n\tif s == nil {\n\t\tklog.ErrorS(nil, \"Container runtime status is nil\")\n\t\treturn\n\t}\n\t// Periodically log the whole runtime status for debugging.\n\tklog.V(4).InfoS(\"Container runtime status\", \"status\", s)\n\tklogErrorS := klog.ErrorS\n\tif !kl.containerRuntimeReadyExpected {\n\t\tklogErrorS = klog.V(4).ErrorS\n\t}\n\tnetworkReady := s.GetRuntimeCondition(kubecontainer.NetworkReady)\n\tif networkReady == nil || !networkReady.Status {\n\t\tklogErrorS(nil, \"Container runtime network not ready\", \"networkReady\", networkReady)\n\t\tkl.runtimeState.setNetworkState(fmt.Errorf(\"container runtime network not ready: %v\", networkReady))\n\t} else {\n\t\t// Set nil if the container runtime network is ready.\n\t\tkl.runtimeState.setNetworkState(nil)\n\t}\n\t// information in RuntimeReady condition will be propagated to NodeReady condition.\n\truntimeReady := s.GetRuntimeCondition(kubecontainer.RuntimeReady)\n\t// If RuntimeReady is not set or is false, report an error.\n\tif runtimeReady == nil || !runtimeReady.Status {\n\t\tklogErrorS(nil, \"Container runtime not ready\", \"runtimeReady\", runtimeReady)\n\t\tkl.runtimeState.setRuntimeState(fmt.Errorf(\"container runtime not ready: %v\", runtimeReady))\n\t\treturn\n\t}\n\tkl.runtimeState.setRuntimeState(nil)\n\tkl.oneTimeInitializer.Do(kl.initializeRuntimeDependentModules)\n\tkl.runtimeState.setRuntimeSync(kl.clock.Now())\n}","line":{"from":2734,"to":2777}} {"id":100006703,"name":"GetConfiguration","signature":"func (kl *Kubelet) GetConfiguration() kubeletconfiginternal.KubeletConfiguration","file":"pkg/kubelet/kubelet.go","code":"// GetConfiguration returns the KubeletConfiguration used to configure the kubelet.\nfunc (kl *Kubelet) GetConfiguration() kubeletconfiginternal.KubeletConfiguration {\n\treturn kl.kubeletConfiguration\n}","line":{"from":2779,"to":2782}} {"id":100006704,"name":"BirthCry","signature":"func (kl *Kubelet) BirthCry()","file":"pkg/kubelet/kubelet.go","code":"// BirthCry sends an event that the kubelet has started up.\nfunc (kl *Kubelet) BirthCry() {\n\t// Make an event that kubelet restarted.\n\tkl.recorder.Eventf(kl.nodeRef, v1.EventTypeNormal, events.StartingKubelet, \"Starting kubelet.\")\n}","line":{"from":2784,"to":2788}} {"id":100006705,"name":"ResyncInterval","signature":"func (kl *Kubelet) ResyncInterval() time.Duration","file":"pkg/kubelet/kubelet.go","code":"// ResyncInterval returns the interval used for periodic syncs.\nfunc (kl *Kubelet) ResyncInterval() time.Duration {\n\treturn kl.resyncInterval\n}","line":{"from":2790,"to":2793}} {"id":100006706,"name":"ListenAndServe","signature":"func (kl *Kubelet) ListenAndServe(kubeCfg *kubeletconfiginternal.KubeletConfiguration, tlsOptions *server.TLSOptions,","file":"pkg/kubelet/kubelet.go","code":"// ListenAndServe runs the kubelet HTTP server.\nfunc (kl *Kubelet) ListenAndServe(kubeCfg *kubeletconfiginternal.KubeletConfiguration, tlsOptions *server.TLSOptions,\n\tauth server.AuthInterface, tp trace.TracerProvider) {\n\tserver.ListenAndServeKubeletServer(kl, kl.resourceAnalyzer, kubeCfg, tlsOptions, auth, tp)\n}","line":{"from":2795,"to":2799}} {"id":100006707,"name":"ListenAndServeReadOnly","signature":"func (kl *Kubelet) ListenAndServeReadOnly(address net.IP, port uint)","file":"pkg/kubelet/kubelet.go","code":"// ListenAndServeReadOnly runs the kubelet HTTP server in read-only mode.\nfunc (kl *Kubelet) ListenAndServeReadOnly(address net.IP, port uint) {\n\tserver.ListenAndServeKubeletReadOnlyServer(kl, kl.resourceAnalyzer, address, port)\n}","line":{"from":2801,"to":2804}} {"id":100006708,"name":"ListenAndServePodResources","signature":"func (kl *Kubelet) ListenAndServePodResources()","file":"pkg/kubelet/kubelet.go","code":"// ListenAndServePodResources runs the kubelet podresources grpc service\nfunc (kl *Kubelet) ListenAndServePodResources() {\n\tsocket, err := util.LocalEndpoint(kl.getPodResourcesDir(), podresources.Socket)\n\tif err != nil {\n\t\tklog.V(2).InfoS(\"Failed to get local endpoint for PodResources endpoint\", \"err\", err)\n\t\treturn\n\t}\n\n\tproviders := podresources.PodResourcesProviders{\n\t\tPods: kl.podManager,\n\t\tDevices: kl.containerManager,\n\t\tCpus: kl.containerManager,\n\t\tMemory: kl.containerManager,\n\t\tDynamicResources: kl.containerManager,\n\t}\n\n\tserver.ListenAndServePodResources(socket, providers)\n}","line":{"from":2806,"to":2823}} {"id":100006709,"name":"cleanUpContainersInPod","signature":"func (kl *Kubelet) cleanUpContainersInPod(podID types.UID, exitedContainerID string)","file":"pkg/kubelet/kubelet.go","code":"// Delete the eligible dead container instances in a pod. Depending on the configuration, the latest dead containers may be kept around.\nfunc (kl *Kubelet) cleanUpContainersInPod(podID types.UID, exitedContainerID string) {\n\tif podStatus, err := kl.podCache.Get(podID); err == nil {\n\t\t// When an evicted or deleted pod has already synced, all containers can be removed.\n\t\tremoveAll := kl.podWorkers.ShouldPodContentBeRemoved(podID)\n\t\tkl.containerDeletor.deleteContainersInPod(exitedContainerID, podStatus, removeAll)\n\t}\n}","line":{"from":2825,"to":2832}} {"id":100006710,"name":"fastStatusUpdateOnce","signature":"func (kl *Kubelet) fastStatusUpdateOnce()","file":"pkg/kubelet/kubelet.go","code":"// fastStatusUpdateOnce starts a loop that checks if the current state of kubelet + container runtime\n// would be able to turn the node ready, and sync the ready state to the apiserver as soon as possible.\n// Function returns after the node status update after such event, or when the node is already ready.\n// Function is executed only during Kubelet start which improves latency to ready node by updating\n// kubelet state, runtime status and node statuses ASAP.\nfunc (kl *Kubelet) fastStatusUpdateOnce() {\n\tctx := context.Background()\n\tstart := kl.clock.Now()\n\tstopCh := make(chan struct{})\n\n\t// Keep trying to make fast node status update until either timeout is reached or an update is successful.\n\twait.Until(func() {\n\t\t// fastNodeStatusUpdate returns true when it succeeds or when the grace period has expired\n\t\t// (status was not updated within nodeReadyGracePeriod and the second argument below gets true),\n\t\t// then we close the channel and abort the loop.\n\t\tif kl.fastNodeStatusUpdate(ctx, kl.clock.Since(start) \u003e= nodeReadyGracePeriod) {\n\t\t\tclose(stopCh)\n\t\t}\n\t}, 100*time.Millisecond, stopCh)\n}","line":{"from":2834,"to":2853}} {"id":100006711,"name":"CheckpointContainer","signature":"func (kl *Kubelet) CheckpointContainer(","file":"pkg/kubelet/kubelet.go","code":"// CheckpointContainer tries to checkpoint a container. The parameters are used to\n// look up the specified container. If the container specified by the given parameters\n// cannot be found an error is returned. If the container is found the container\n// engine will be asked to checkpoint the given container into the kubelet's default\n// checkpoint directory.\nfunc (kl *Kubelet) CheckpointContainer(\n\tctx context.Context,\n\tpodUID types.UID,\n\tpodFullName,\n\tcontainerName string,\n\toptions *runtimeapi.CheckpointContainerRequest,\n) error {\n\tcontainer, err := kl.findContainer(ctx, podFullName, podUID, containerName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif container == nil {\n\t\treturn fmt.Errorf(\"container %v not found\", containerName)\n\t}\n\n\toptions.Location = filepath.Join(\n\t\tkl.getCheckpointsDir(),\n\t\tfmt.Sprintf(\n\t\t\t\"checkpoint-%s-%s-%s.tar\",\n\t\t\tpodFullName,\n\t\t\tcontainerName,\n\t\t\ttime.Now().Format(time.RFC3339),\n\t\t),\n\t)\n\n\toptions.ContainerId = string(container.ID.ID)\n\n\tif err := kl.containerRuntime.CheckpointContainer(ctx, options); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":2855,"to":2892}} {"id":100006712,"name":"ListMetricDescriptors","signature":"func (kl *Kubelet) ListMetricDescriptors(ctx context.Context) ([]*runtimeapi.MetricDescriptor, error)","file":"pkg/kubelet/kubelet.go","code":"// ListMetricDescriptors gets the descriptors for the metrics that will be returned in ListPodSandboxMetrics.\nfunc (kl *Kubelet) ListMetricDescriptors(ctx context.Context) ([]*runtimeapi.MetricDescriptor, error) {\n\treturn kl.containerRuntime.ListMetricDescriptors(ctx)\n}","line":{"from":2894,"to":2897}} {"id":100006713,"name":"ListPodSandboxMetrics","signature":"func (kl *Kubelet) ListPodSandboxMetrics(ctx context.Context) ([]*runtimeapi.PodSandboxMetrics, error)","file":"pkg/kubelet/kubelet.go","code":"// ListPodSandboxMetrics retrieves the metrics for all pod sandboxes.\nfunc (kl *Kubelet) ListPodSandboxMetrics(ctx context.Context) ([]*runtimeapi.PodSandboxMetrics, error) {\n\treturn kl.containerRuntime.ListPodSandboxMetrics(ctx)\n}","line":{"from":2899,"to":2902}} {"id":100006714,"name":"supportLocalStorageCapacityIsolation","signature":"func (kl *Kubelet) supportLocalStorageCapacityIsolation() bool","file":"pkg/kubelet/kubelet.go","code":"func (kl *Kubelet) supportLocalStorageCapacityIsolation() bool {\n\treturn kl.GetConfiguration().LocalStorageCapacityIsolation\n}","line":{"from":2904,"to":2906}} {"id":100006715,"name":"isSyncPodWorthy","signature":"func isSyncPodWorthy(event *pleg.PodLifecycleEvent) bool","file":"pkg/kubelet/kubelet.go","code":"// isSyncPodWorthy filters out events that are not worthy of pod syncing\nfunc isSyncPodWorthy(event *pleg.PodLifecycleEvent) bool {\n\t// ContainerRemoved doesn't affect pod state\n\treturn event.Type != pleg.ContainerRemoved\n}","line":{"from":2908,"to":2912}} {"id":100006716,"name":"PrepareDynamicResources","signature":"func (kl *Kubelet) PrepareDynamicResources(pod *v1.Pod) error","file":"pkg/kubelet/kubelet.go","code":"// PrepareDynamicResources calls the container Manager PrepareDynamicResources API\n// This method implements the RuntimeHelper interface\nfunc (kl *Kubelet) PrepareDynamicResources(pod *v1.Pod) error {\n\treturn kl.containerManager.PrepareDynamicResources(pod)\n}","line":{"from":2914,"to":2918}} {"id":100006717,"name":"UnprepareDynamicResources","signature":"func (kl *Kubelet) UnprepareDynamicResources(pod *v1.Pod) error","file":"pkg/kubelet/kubelet.go","code":"// UnprepareDynamicResources calls the container Manager UnprepareDynamicResources API\n// This method implements the RuntimeHelper interface\nfunc (kl *Kubelet) UnprepareDynamicResources(pod *v1.Pod) error {\n\treturn kl.containerManager.UnprepareDynamicResources(pod)\n}","line":{"from":2920,"to":2924}} {"id":100006718,"name":"getRootDir","signature":"func (kl *Kubelet) getRootDir() string","file":"pkg/kubelet/kubelet_getters.go","code":"// getRootDir returns the full path to the directory under which kubelet can\n// store data. These functions are useful to pass interfaces to other modules\n// that may need to know where to write data without getting a whole kubelet\n// instance.\nfunc (kl *Kubelet) getRootDir() string {\n\treturn kl.rootDirectory\n}","line":{"from":43,"to":49}} {"id":100006719,"name":"getPodsDir","signature":"func (kl *Kubelet) getPodsDir() string","file":"pkg/kubelet/kubelet_getters.go","code":"// getPodsDir returns the full path to the directory under which pod\n// directories are created.\nfunc (kl *Kubelet) getPodsDir() string {\n\treturn filepath.Join(kl.getRootDir(), config.DefaultKubeletPodsDirName)\n}","line":{"from":51,"to":55}} {"id":100006720,"name":"getPluginsDir","signature":"func (kl *Kubelet) getPluginsDir() string","file":"pkg/kubelet/kubelet_getters.go","code":"// getPluginsDir returns the full path to the directory under which plugin\n// directories are created. Plugins can use these directories for data that\n// they need to persist. Plugins should create subdirectories under this named\n// after their own names.\nfunc (kl *Kubelet) getPluginsDir() string {\n\treturn filepath.Join(kl.getRootDir(), config.DefaultKubeletPluginsDirName)\n}","line":{"from":57,"to":63}} {"id":100006721,"name":"getPluginsRegistrationDir","signature":"func (kl *Kubelet) getPluginsRegistrationDir() string","file":"pkg/kubelet/kubelet_getters.go","code":"// getPluginsRegistrationDir returns the full path to the directory under which\n// plugins socket should be placed to be registered.\n// More information is available about plugin registration in the pluginwatcher\n// module\nfunc (kl *Kubelet) getPluginsRegistrationDir() string {\n\treturn filepath.Join(kl.getRootDir(), config.DefaultKubeletPluginsRegistrationDirName)\n}","line":{"from":65,"to":71}} {"id":100006722,"name":"getPluginDir","signature":"func (kl *Kubelet) getPluginDir(pluginName string) string","file":"pkg/kubelet/kubelet_getters.go","code":"// getPluginDir returns a data directory name for a given plugin name.\n// Plugins can use these directories to store data that they need to persist.\n// For per-pod plugin data, see getPodPluginDir.\nfunc (kl *Kubelet) getPluginDir(pluginName string) string {\n\treturn filepath.Join(kl.getPluginsDir(), pluginName)\n}","line":{"from":73,"to":78}} {"id":100006723,"name":"getCheckpointsDir","signature":"func (kl *Kubelet) getCheckpointsDir() string","file":"pkg/kubelet/kubelet_getters.go","code":"// getCheckpointsDir returns a data directory name for checkpoints.\n// Checkpoints can be stored in this directory for further use.\nfunc (kl *Kubelet) getCheckpointsDir() string {\n\treturn filepath.Join(kl.getRootDir(), config.DefaultKubeletCheckpointsDirName)\n}","line":{"from":80,"to":84}} {"id":100006724,"name":"getVolumeDevicePluginsDir","signature":"func (kl *Kubelet) getVolumeDevicePluginsDir() string","file":"pkg/kubelet/kubelet_getters.go","code":"// getVolumeDevicePluginsDir returns the full path to the directory under which plugin\n// directories are created. Plugins can use these directories for data that\n// they need to persist. Plugins should create subdirectories under this named\n// after their own names.\nfunc (kl *Kubelet) getVolumeDevicePluginsDir() string {\n\treturn filepath.Join(kl.getRootDir(), config.DefaultKubeletPluginsDirName)\n}","line":{"from":86,"to":92}} {"id":100006725,"name":"getVolumeDevicePluginDir","signature":"func (kl *Kubelet) getVolumeDevicePluginDir(pluginName string) string","file":"pkg/kubelet/kubelet_getters.go","code":"// getVolumeDevicePluginDir returns a data directory name for a given plugin name.\n// Plugins can use these directories to store data that they need to persist.\n// For per-pod plugin data, see getVolumeDevicePluginsDir.\nfunc (kl *Kubelet) getVolumeDevicePluginDir(pluginName string) string {\n\treturn filepath.Join(kl.getVolumeDevicePluginsDir(), pluginName, config.DefaultKubeletVolumeDevicesDirName)\n}","line":{"from":94,"to":99}} {"id":100006726,"name":"GetPodDir","signature":"func (kl *Kubelet) GetPodDir(podUID types.UID) string","file":"pkg/kubelet/kubelet_getters.go","code":"// GetPodDir returns the full path to the per-pod data directory for the\n// specified pod. This directory may not exist if the pod does not exist.\nfunc (kl *Kubelet) GetPodDir(podUID types.UID) string {\n\treturn kl.getPodDir(podUID)\n}","line":{"from":101,"to":105}} {"id":100006727,"name":"ListPodsFromDisk","signature":"func (kl *Kubelet) ListPodsFromDisk() ([]types.UID, error)","file":"pkg/kubelet/kubelet_getters.go","code":"// ListPodsFromDisk gets a list of pods that have data directories.\nfunc (kl *Kubelet) ListPodsFromDisk() ([]types.UID, error) {\n\treturn kl.listPodsFromDisk()\n}","line":{"from":107,"to":110}} {"id":100006728,"name":"getPodDir","signature":"func (kl *Kubelet) getPodDir(podUID types.UID) string","file":"pkg/kubelet/kubelet_getters.go","code":"// getPodDir returns the full path to the per-pod directory for the pod with\n// the given UID.\nfunc (kl *Kubelet) getPodDir(podUID types.UID) string {\n\treturn filepath.Join(kl.getPodsDir(), string(podUID))\n}","line":{"from":112,"to":116}} {"id":100006729,"name":"getPodVolumeSubpathsDir","signature":"func (kl *Kubelet) getPodVolumeSubpathsDir(podUID types.UID) string","file":"pkg/kubelet/kubelet_getters.go","code":"// getPodVolumesSubpathsDir returns the full path to the per-pod subpaths directory under\n// which subpath volumes are created for the specified pod. This directory may not\n// exist if the pod does not exist or subpaths are not specified.\nfunc (kl *Kubelet) getPodVolumeSubpathsDir(podUID types.UID) string {\n\treturn filepath.Join(kl.getPodDir(podUID), config.DefaultKubeletVolumeSubpathsDirName)\n}","line":{"from":118,"to":123}} {"id":100006730,"name":"getPodVolumesDir","signature":"func (kl *Kubelet) getPodVolumesDir(podUID types.UID) string","file":"pkg/kubelet/kubelet_getters.go","code":"// getPodVolumesDir returns the full path to the per-pod data directory under\n// which volumes are created for the specified pod. This directory may not\n// exist if the pod does not exist.\nfunc (kl *Kubelet) getPodVolumesDir(podUID types.UID) string {\n\treturn filepath.Join(kl.getPodDir(podUID), config.DefaultKubeletVolumesDirName)\n}","line":{"from":125,"to":130}} {"id":100006731,"name":"getPodVolumeDir","signature":"func (kl *Kubelet) getPodVolumeDir(podUID types.UID, pluginName string, volumeName string) string","file":"pkg/kubelet/kubelet_getters.go","code":"// getPodVolumeDir returns the full path to the directory which represents the\n// named volume under the named plugin for specified pod. This directory may not\n// exist if the pod does not exist.\nfunc (kl *Kubelet) getPodVolumeDir(podUID types.UID, pluginName string, volumeName string) string {\n\treturn filepath.Join(kl.getPodVolumesDir(podUID), pluginName, volumeName)\n}","line":{"from":132,"to":137}} {"id":100006732,"name":"getPodVolumeDevicesDir","signature":"func (kl *Kubelet) getPodVolumeDevicesDir(podUID types.UID) string","file":"pkg/kubelet/kubelet_getters.go","code":"// getPodVolumeDevicesDir returns the full path to the per-pod data directory under\n// which volumes are created for the specified pod. This directory may not\n// exist if the pod does not exist.\nfunc (kl *Kubelet) getPodVolumeDevicesDir(podUID types.UID) string {\n\treturn filepath.Join(kl.getPodDir(podUID), config.DefaultKubeletVolumeDevicesDirName)\n}","line":{"from":139,"to":144}} {"id":100006733,"name":"getPodVolumeDeviceDir","signature":"func (kl *Kubelet) getPodVolumeDeviceDir(podUID types.UID, pluginName string) string","file":"pkg/kubelet/kubelet_getters.go","code":"// getPodVolumeDeviceDir returns the full path to the directory which represents the\n// named plugin for specified pod. This directory may not exist if the pod does not exist.\nfunc (kl *Kubelet) getPodVolumeDeviceDir(podUID types.UID, pluginName string) string {\n\treturn filepath.Join(kl.getPodVolumeDevicesDir(podUID), pluginName)\n}","line":{"from":146,"to":150}} {"id":100006734,"name":"getPodPluginsDir","signature":"func (kl *Kubelet) getPodPluginsDir(podUID types.UID) string","file":"pkg/kubelet/kubelet_getters.go","code":"// getPodPluginsDir returns the full path to the per-pod data directory under\n// which plugins may store data for the specified pod. This directory may not\n// exist if the pod does not exist.\nfunc (kl *Kubelet) getPodPluginsDir(podUID types.UID) string {\n\treturn filepath.Join(kl.getPodDir(podUID), config.DefaultKubeletPluginsDirName)\n}","line":{"from":152,"to":157}} {"id":100006735,"name":"getPodPluginDir","signature":"func (kl *Kubelet) getPodPluginDir(podUID types.UID, pluginName string) string","file":"pkg/kubelet/kubelet_getters.go","code":"// getPodPluginDir returns a data directory name for a given plugin name for a\n// given pod UID. Plugins can use these directories to store data that they\n// need to persist. For non-per-pod plugin data, see getPluginDir.\nfunc (kl *Kubelet) getPodPluginDir(podUID types.UID, pluginName string) string {\n\treturn filepath.Join(kl.getPodPluginsDir(podUID), pluginName)\n}","line":{"from":159,"to":164}} {"id":100006736,"name":"getPodContainerDir","signature":"func (kl *Kubelet) getPodContainerDir(podUID types.UID, ctrName string) string","file":"pkg/kubelet/kubelet_getters.go","code":"// getPodContainerDir returns the full path to the per-pod data directory under\n// which container data is held for the specified pod. This directory may not\n// exist if the pod or container does not exist.\nfunc (kl *Kubelet) getPodContainerDir(podUID types.UID, ctrName string) string {\n\treturn filepath.Join(kl.getPodDir(podUID), config.DefaultKubeletContainersDirName, ctrName)\n}","line":{"from":166,"to":171}} {"id":100006737,"name":"getPodResourcesDir","signature":"func (kl *Kubelet) getPodResourcesDir() string","file":"pkg/kubelet/kubelet_getters.go","code":"// getPodResourcesSocket returns the full path to the directory containing the pod resources socket\nfunc (kl *Kubelet) getPodResourcesDir() string {\n\treturn filepath.Join(kl.getRootDir(), config.DefaultKubeletPodResourcesDirName)\n}","line":{"from":173,"to":176}} {"id":100006738,"name":"GetPods","signature":"func (kl *Kubelet) GetPods() []*v1.Pod","file":"pkg/kubelet/kubelet_getters.go","code":"// GetPods returns all pods bound to the kubelet and their spec, and the mirror\n// pods.\nfunc (kl *Kubelet) GetPods() []*v1.Pod {\n\tpods := kl.podManager.GetPods()\n\t// a kubelet running without apiserver requires an additional\n\t// update of the static pod status. See #57106\n\tfor i, p := range pods {\n\t\tif kubelettypes.IsStaticPod(p) {\n\t\t\tif status, ok := kl.statusManager.GetPodStatus(p.UID); ok {\n\t\t\t\tklog.V(2).InfoS(\"Pod status updated\", \"pod\", klog.KObj(p), \"status\", status.Phase)\n\t\t\t\t// do not mutate the cache\n\t\t\t\tp = p.DeepCopy()\n\t\t\t\tp.Status = status\n\t\t\t\tpods[i] = p\n\t\t\t}\n\t\t}\n\t}\n\treturn pods\n}","line":{"from":178,"to":196}} {"id":100006739,"name":"GetRunningPods","signature":"func (kl *Kubelet) GetRunningPods(ctx context.Context) ([]*v1.Pod, error)","file":"pkg/kubelet/kubelet_getters.go","code":"// GetRunningPods returns all pods running on kubelet from looking at the\n// container runtime cache. This function converts kubecontainer.Pod to\n// v1.Pod, so only the fields that exist in both kubecontainer.Pod and\n// v1.Pod are considered meaningful.\nfunc (kl *Kubelet) GetRunningPods(ctx context.Context) ([]*v1.Pod, error) {\n\tpods, err := kl.runtimeCache.GetPods(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapiPods := make([]*v1.Pod, 0, len(pods))\n\tfor _, pod := range pods {\n\t\tapiPods = append(apiPods, pod.ToAPIPod())\n\t}\n\treturn apiPods, nil\n}","line":{"from":198,"to":213}} {"id":100006740,"name":"GetPodByFullName","signature":"func (kl *Kubelet) GetPodByFullName(podFullName string) (*v1.Pod, bool)","file":"pkg/kubelet/kubelet_getters.go","code":"// GetPodByFullName gets the pod with the given 'full' name, which\n// incorporates the namespace as well as whether the pod was found.\nfunc (kl *Kubelet) GetPodByFullName(podFullName string) (*v1.Pod, bool) {\n\treturn kl.podManager.GetPodByFullName(podFullName)\n}","line":{"from":215,"to":219}} {"id":100006741,"name":"GetPodByName","signature":"func (kl *Kubelet) GetPodByName(namespace, name string) (*v1.Pod, bool)","file":"pkg/kubelet/kubelet_getters.go","code":"// GetPodByName provides the first pod that matches namespace and name, as well\n// as whether the pod was found.\nfunc (kl *Kubelet) GetPodByName(namespace, name string) (*v1.Pod, bool) {\n\treturn kl.podManager.GetPodByName(namespace, name)\n}","line":{"from":221,"to":225}} {"id":100006742,"name":"GetPodByCgroupfs","signature":"func (kl *Kubelet) GetPodByCgroupfs(cgroupfs string) (*v1.Pod, bool)","file":"pkg/kubelet/kubelet_getters.go","code":"// GetPodByCgroupfs provides the pod that maps to the specified cgroup, as well\n// as whether the pod was found.\nfunc (kl *Kubelet) GetPodByCgroupfs(cgroupfs string) (*v1.Pod, bool) {\n\tpcm := kl.containerManager.NewPodContainerManager()\n\tif result, podUID := pcm.IsPodCgroup(cgroupfs); result {\n\t\treturn kl.podManager.GetPodByUID(podUID)\n\t}\n\treturn nil, false\n}","line":{"from":227,"to":235}} {"id":100006743,"name":"GetHostname","signature":"func (kl *Kubelet) GetHostname() string","file":"pkg/kubelet/kubelet_getters.go","code":"// GetHostname Returns the hostname as the kubelet sees it.\nfunc (kl *Kubelet) GetHostname() string {\n\treturn kl.hostname\n}","line":{"from":237,"to":240}} {"id":100006744,"name":"getRuntime","signature":"func (kl *Kubelet) getRuntime() kubecontainer.Runtime","file":"pkg/kubelet/kubelet_getters.go","code":"// getRuntime returns the current Runtime implementation in use by the kubelet.\nfunc (kl *Kubelet) getRuntime() kubecontainer.Runtime {\n\treturn kl.containerRuntime\n}","line":{"from":242,"to":245}} {"id":100006745,"name":"GetNode","signature":"func (kl *Kubelet) GetNode() (*v1.Node, error)","file":"pkg/kubelet/kubelet_getters.go","code":"// GetNode returns the node info for the configured node name of this Kubelet.\nfunc (kl *Kubelet) GetNode() (*v1.Node, error) {\n\tif kl.kubeClient == nil {\n\t\treturn kl.initialNode(context.TODO())\n\t}\n\treturn kl.nodeLister.Get(string(kl.nodeName))\n}","line":{"from":247,"to":253}} {"id":100006746,"name":"getNodeAnyWay","signature":"func (kl *Kubelet) getNodeAnyWay() (*v1.Node, error)","file":"pkg/kubelet/kubelet_getters.go","code":"// getNodeAnyWay() must return a *v1.Node which is required by RunGeneralPredicates().\n// The *v1.Node is obtained as follows:\n// Return kubelet's nodeInfo for this node, except on error or if in standalone mode,\n// in which case return a manufactured nodeInfo representing a node with no pods,\n// zero capacity, and the default labels.\nfunc (kl *Kubelet) getNodeAnyWay() (*v1.Node, error) {\n\tif kl.kubeClient != nil {\n\t\tif n, err := kl.nodeLister.Get(string(kl.nodeName)); err == nil {\n\t\t\treturn n, nil\n\t\t}\n\t}\n\treturn kl.initialNode(context.TODO())\n}","line":{"from":255,"to":267}} {"id":100006747,"name":"GetNodeConfig","signature":"func (kl *Kubelet) GetNodeConfig() cm.NodeConfig","file":"pkg/kubelet/kubelet_getters.go","code":"// GetNodeConfig returns the container manager node config.\nfunc (kl *Kubelet) GetNodeConfig() cm.NodeConfig {\n\treturn kl.containerManager.GetNodeConfig()\n}","line":{"from":269,"to":272}} {"id":100006748,"name":"GetPodCgroupRoot","signature":"func (kl *Kubelet) GetPodCgroupRoot() string","file":"pkg/kubelet/kubelet_getters.go","code":"// GetPodCgroupRoot returns the listeral cgroupfs value for the cgroup containing all pods\nfunc (kl *Kubelet) GetPodCgroupRoot() string {\n\treturn kl.containerManager.GetPodCgroupRoot()\n}","line":{"from":274,"to":277}} {"id":100006749,"name":"GetHostIPs","signature":"func (kl *Kubelet) GetHostIPs() ([]net.IP, error)","file":"pkg/kubelet/kubelet_getters.go","code":"// GetHostIPs returns host IPs or nil in case of error.\nfunc (kl *Kubelet) GetHostIPs() ([]net.IP, error) {\n\tnode, err := kl.GetNode()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot get node: %v\", err)\n\t}\n\treturn utilnode.GetNodeHostIPs(node)\n}","line":{"from":279,"to":286}} {"id":100006750,"name":"getHostIPsAnyWay","signature":"func (kl *Kubelet) getHostIPsAnyWay() ([]net.IP, error)","file":"pkg/kubelet/kubelet_getters.go","code":"// getHostIPsAnyWay attempts to return the host IPs from kubelet's nodeInfo, or\n// the initialNode.\nfunc (kl *Kubelet) getHostIPsAnyWay() ([]net.IP, error) {\n\tnode, err := kl.getNodeAnyWay()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn utilnode.GetNodeHostIPs(node)\n}","line":{"from":288,"to":296}} {"id":100006751,"name":"GetExtraSupplementalGroupsForPod","signature":"func (kl *Kubelet) GetExtraSupplementalGroupsForPod(pod *v1.Pod) []int64","file":"pkg/kubelet/kubelet_getters.go","code":"// GetExtraSupplementalGroupsForPod returns a list of the extra\n// supplemental groups for the Pod. These extra supplemental groups come\n// from annotations on persistent volumes that the pod depends on.\nfunc (kl *Kubelet) GetExtraSupplementalGroupsForPod(pod *v1.Pod) []int64 {\n\treturn kl.volumeManager.GetExtraSupplementalGroupsForPod(pod)\n}","line":{"from":298,"to":303}} {"id":100006752,"name":"getPodVolumePathListFromDisk","signature":"func (kl *Kubelet) getPodVolumePathListFromDisk(podUID types.UID) ([]string, error)","file":"pkg/kubelet/kubelet_getters.go","code":"// getPodVolumePathListFromDisk returns a list of the volume paths by reading the\n// volume directories for the given pod from the disk.\nfunc (kl *Kubelet) getPodVolumePathListFromDisk(podUID types.UID) ([]string, error) {\n\tvolumes := []string{}\n\tpodVolDir := kl.getPodVolumesDir(podUID)\n\n\tif pathExists, pathErr := mount.PathExists(podVolDir); pathErr != nil {\n\t\treturn volumes, fmt.Errorf(\"error checking if path %q exists: %v\", podVolDir, pathErr)\n\t} else if !pathExists {\n\t\tklog.V(6).InfoS(\"Path does not exist\", \"path\", podVolDir)\n\t\treturn volumes, nil\n\t}\n\n\tvolumePluginDirs, err := os.ReadDir(podVolDir)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Could not read directory\", \"path\", podVolDir)\n\t\treturn volumes, err\n\t}\n\tfor _, volumePluginDir := range volumePluginDirs {\n\t\tvolumePluginName := volumePluginDir.Name()\n\t\tvolumePluginPath := filepath.Join(podVolDir, volumePluginName)\n\t\tvolumeDirs, err := utilpath.ReadDirNoStat(volumePluginPath)\n\t\tif err != nil {\n\t\t\treturn volumes, fmt.Errorf(\"could not read directory %s: %v\", volumePluginPath, err)\n\t\t}\n\t\tunescapePluginName := utilstrings.UnescapeQualifiedName(volumePluginName)\n\n\t\tif unescapePluginName != csi.CSIPluginName {\n\t\t\tfor _, volumeDir := range volumeDirs {\n\t\t\t\tvolumes = append(volumes, filepath.Join(volumePluginPath, volumeDir))\n\t\t\t}\n\t\t} else {\n\t\t\t// For CSI volumes, the mounted volume path has an extra sub path \"/mount\", so also add it\n\t\t\t// to the list if the mounted path exists.\n\t\t\tfor _, volumeDir := range volumeDirs {\n\t\t\t\tpath := filepath.Join(volumePluginPath, volumeDir)\n\t\t\t\tcsimountpath := csi.GetCSIMounterPath(path)\n\t\t\t\tif pathExists, _ := mount.PathExists(csimountpath); pathExists {\n\t\t\t\t\tvolumes = append(volumes, csimountpath)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn volumes, nil\n}","line":{"from":305,"to":349}} {"id":100006753,"name":"getMountedVolumePathListFromDisk","signature":"func (kl *Kubelet) getMountedVolumePathListFromDisk(podUID types.UID) ([]string, error)","file":"pkg/kubelet/kubelet_getters.go","code":"func (kl *Kubelet) getMountedVolumePathListFromDisk(podUID types.UID) ([]string, error) {\n\tmountedVolumes := []string{}\n\tvolumePaths, err := kl.getPodVolumePathListFromDisk(podUID)\n\tif err != nil {\n\t\treturn mountedVolumes, err\n\t}\n\t// Only use IsLikelyNotMountPoint to check might not cover all cases. For CSI volumes that\n\t// either: 1) don't mount or 2) bind mount in the rootfs, the mount check will not work as expected.\n\t// We plan to remove this mountpoint check as a condition before deleting pods since it is\n\t// not reliable and the condition might be different for different types of volumes. But it requires\n\t// a reliable way to clean up unused volume dir to avoid problems during pod deletion. See discussion in issue #74650\n\tfor _, volumePath := range volumePaths {\n\t\tisNotMount, err := kl.mounter.IsLikelyNotMountPoint(volumePath)\n\t\tif err != nil {\n\t\t\treturn mountedVolumes, fmt.Errorf(\"fail to check mount point %q: %v\", volumePath, err)\n\t\t}\n\t\tif !isNotMount {\n\t\t\tmountedVolumes = append(mountedVolumes, volumePath)\n\t\t}\n\t}\n\treturn mountedVolumes, nil\n}","line":{"from":351,"to":372}} {"id":100006754,"name":"getPodVolumeSubpathListFromDisk","signature":"func (kl *Kubelet) getPodVolumeSubpathListFromDisk(podUID types.UID) ([]string, error)","file":"pkg/kubelet/kubelet_getters.go","code":"// getPodVolumeSubpathListFromDisk returns a list of the volume-subpath paths by reading the\n// subpath directories for the given pod from the disk.\nfunc (kl *Kubelet) getPodVolumeSubpathListFromDisk(podUID types.UID) ([]string, error) {\n\tvolumes := []string{}\n\tpodSubpathsDir := kl.getPodVolumeSubpathsDir(podUID)\n\n\tif pathExists, pathErr := mount.PathExists(podSubpathsDir); pathErr != nil {\n\t\treturn nil, fmt.Errorf(\"error checking if path %q exists: %v\", podSubpathsDir, pathErr)\n\t} else if !pathExists {\n\t\treturn volumes, nil\n\t}\n\n\t// Explicitly walks /\u003cvolume\u003e/\u003ccontainer name\u003e/\u003csubPathIndex\u003e\n\tvolumePluginDirs, err := os.ReadDir(podSubpathsDir)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Could not read directory\", \"path\", podSubpathsDir)\n\t\treturn volumes, err\n\t}\n\tfor _, volumePluginDir := range volumePluginDirs {\n\t\tvolumePluginName := volumePluginDir.Name()\n\t\tvolumePluginPath := filepath.Join(podSubpathsDir, volumePluginName)\n\t\tcontainerDirs, err := os.ReadDir(volumePluginPath)\n\t\tif err != nil {\n\t\t\treturn volumes, fmt.Errorf(\"could not read directory %s: %v\", volumePluginPath, err)\n\t\t}\n\t\tfor _, containerDir := range containerDirs {\n\t\t\tcontainerName := containerDir.Name()\n\t\t\tcontainerPath := filepath.Join(volumePluginPath, containerName)\n\t\t\t// Switch to ReadDirNoStat at the subPathIndex level to prevent issues with stat'ing\n\t\t\t// mount points that may not be responsive\n\t\t\tsubPaths, err := utilpath.ReadDirNoStat(containerPath)\n\t\t\tif err != nil {\n\t\t\t\treturn volumes, fmt.Errorf(\"could not read directory %s: %v\", containerPath, err)\n\t\t\t}\n\t\t\tfor _, subPathDir := range subPaths {\n\t\t\t\tvolumes = append(volumes, filepath.Join(containerPath, subPathDir))\n\t\t\t}\n\t\t}\n\t}\n\treturn volumes, nil\n}","line":{"from":374,"to":414}} {"id":100006755,"name":"GetRequestedContainersInfo","signature":"func (kl *Kubelet) GetRequestedContainersInfo(containerName string, options cadvisorv2.RequestOptions) (map[string]*cadvisorapiv1.ContainerInfo, error)","file":"pkg/kubelet/kubelet_getters.go","code":"// GetRequestedContainersInfo returns container info.\nfunc (kl *Kubelet) GetRequestedContainersInfo(containerName string, options cadvisorv2.RequestOptions) (map[string]*cadvisorapiv1.ContainerInfo, error) {\n\treturn kl.cadvisor.GetRequestedContainersInfo(containerName, options)\n}","line":{"from":416,"to":419}} {"id":100006756,"name":"GetVersionInfo","signature":"func (kl *Kubelet) GetVersionInfo() (*cadvisorapiv1.VersionInfo, error)","file":"pkg/kubelet/kubelet_getters.go","code":"// GetVersionInfo returns information about the version of cAdvisor in use.\nfunc (kl *Kubelet) GetVersionInfo() (*cadvisorapiv1.VersionInfo, error) {\n\treturn kl.cadvisor.VersionInfo()\n}","line":{"from":421,"to":424}} {"id":100006757,"name":"GetCachedMachineInfo","signature":"func (kl *Kubelet) GetCachedMachineInfo() (*cadvisorapiv1.MachineInfo, error)","file":"pkg/kubelet/kubelet_getters.go","code":"// GetCachedMachineInfo assumes that the machine info can't change without a reboot\nfunc (kl *Kubelet) GetCachedMachineInfo() (*cadvisorapiv1.MachineInfo, error) {\n\tkl.machineInfoLock.RLock()\n\tdefer kl.machineInfoLock.RUnlock()\n\treturn kl.machineInfo, nil\n}","line":{"from":426,"to":431}} {"id":100006758,"name":"setCachedMachineInfo","signature":"func (kl *Kubelet) setCachedMachineInfo(info *cadvisorapiv1.MachineInfo)","file":"pkg/kubelet/kubelet_getters.go","code":"func (kl *Kubelet) setCachedMachineInfo(info *cadvisorapiv1.MachineInfo) {\n\tkl.machineInfoLock.Lock()\n\tdefer kl.machineInfoLock.Unlock()\n\tkl.machineInfo = info\n}","line":{"from":433,"to":437}} {"id":100006759,"name":"providerRequiresNetworkingConfiguration","signature":"func (kl *Kubelet) providerRequiresNetworkingConfiguration() bool","file":"pkg/kubelet/kubelet_network.go","code":"// providerRequiresNetworkingConfiguration returns whether the cloud provider\n// requires special networking configuration.\nfunc (kl *Kubelet) providerRequiresNetworkingConfiguration() bool {\n\t// TODO: We should have a mechanism to say whether native cloud provider\n\t// is used or whether we are using overlay networking. We should return\n\t// true for cloud providers if they implement Routes() interface and\n\t// we are not using overlay networking.\n\tif kl.cloud == nil || kl.cloud.ProviderName() != \"gce\" {\n\t\treturn false\n\t}\n\t_, supported := kl.cloud.Routes()\n\treturn supported\n}","line":{"from":28,"to":40}} {"id":100006760,"name":"updatePodCIDR","signature":"func (kl *Kubelet) updatePodCIDR(ctx context.Context, cidr string) (bool, error)","file":"pkg/kubelet/kubelet_network.go","code":"// updatePodCIDR updates the pod CIDR in the runtime state if it is different\n// from the current CIDR. Return true if pod CIDR is actually changed.\nfunc (kl *Kubelet) updatePodCIDR(ctx context.Context, cidr string) (bool, error) {\n\tkl.updatePodCIDRMux.Lock()\n\tdefer kl.updatePodCIDRMux.Unlock()\n\n\tpodCIDR := kl.runtimeState.podCIDR()\n\n\tif podCIDR == cidr {\n\t\treturn false, nil\n\t}\n\n\t// kubelet -\u003e generic runtime -\u003e runtime shim -\u003e network plugin\n\t// docker/non-cri implementations have a passthrough UpdatePodCIDR\n\tif err := kl.getRuntime().UpdatePodCIDR(ctx, cidr); err != nil {\n\t\t// If updatePodCIDR would fail, theoretically pod CIDR could not change.\n\t\t// But it is better to be on the safe side to still return true here.\n\t\treturn true, fmt.Errorf(\"failed to update pod CIDR: %v\", err)\n\t}\n\tklog.InfoS(\"Updating Pod CIDR\", \"originalPodCIDR\", podCIDR, \"newPodCIDR\", cidr)\n\tkl.runtimeState.setPodCIDR(cidr)\n\treturn true, nil\n}","line":{"from":42,"to":64}} {"id":100006761,"name":"GetPodDNS","signature":"func (kl *Kubelet) GetPodDNS(pod *v1.Pod) (*runtimeapi.DNSConfig, error)","file":"pkg/kubelet/kubelet_network.go","code":"// GetPodDNS returns DNS settings for the pod.\n// This function is defined in kubecontainer.RuntimeHelper interface so we\n// have to implement it.\nfunc (kl *Kubelet) GetPodDNS(pod *v1.Pod) (*runtimeapi.DNSConfig, error) {\n\treturn kl.dnsConfigurer.GetPodDNS(pod)\n}","line":{"from":66,"to":71}} {"id":100006762,"name":"initNetworkUtil","signature":"func (kl *Kubelet) initNetworkUtil()","file":"pkg/kubelet/kubelet_network_linux.go","code":"func (kl *Kubelet) initNetworkUtil() {\n\texec := utilexec.New()\n\tiptClients := []utiliptables.Interface{\n\t\tutiliptables.New(exec, utiliptables.ProtocolIPv4),\n\t\tutiliptables.New(exec, utiliptables.ProtocolIPv6),\n\t}\n\n\tfor i := range iptClients {\n\t\tiptClient := iptClients[i]\n\t\tif kl.syncIPTablesRules(iptClient) {\n\t\t\tklog.InfoS(\"Initialized iptables rules.\", \"protocol\", iptClient.Protocol())\n\t\t\tgo iptClient.Monitor(\n\t\t\t\tutiliptables.Chain(\"KUBE-KUBELET-CANARY\"),\n\t\t\t\t[]utiliptables.Table{utiliptables.TableMangle, utiliptables.TableNAT, utiliptables.TableFilter},\n\t\t\t\tfunc() { kl.syncIPTablesRules(iptClient) },\n\t\t\t\t1*time.Minute, wait.NeverStop,\n\t\t\t)\n\t\t} else {\n\t\t\tklog.InfoS(\"Failed to initialize iptables rules; some functionality may be missing.\", \"protocol\", iptClient.Protocol())\n\t\t}\n\t}\n}","line":{"from":53,"to":74}} {"id":100006763,"name":"syncIPTablesRules","signature":"func (kl *Kubelet) syncIPTablesRules(iptClient utiliptables.Interface) bool","file":"pkg/kubelet/kubelet_network_linux.go","code":"// syncIPTablesRules ensures the KUBE-IPTABLES-HINT chain exists, and the martian packet\n// protection rule is installed. If the IPTablesOwnershipCleanup feature gate is disabled\n// it will also synchronize additional deprecated iptables rules.\nfunc (kl *Kubelet) syncIPTablesRules(iptClient utiliptables.Interface) bool {\n\t// Create hint chain so other components can see whether we are using iptables-legacy\n\t// or iptables-nft.\n\tif _, err := iptClient.EnsureChain(utiliptables.TableMangle, KubeIPTablesHintChain); err != nil {\n\t\tklog.ErrorS(err, \"Failed to ensure that iptables hint chain exists\")\n\t\treturn false\n\t}\n\n\tif !iptClient.IsIPv6() { // ipv6 doesn't have this issue\n\t\t// Set up the KUBE-FIREWALL chain and martian packet protection rule.\n\t\t// (See below.)\n\t\tif _, err := iptClient.EnsureChain(utiliptables.TableFilter, KubeFirewallChain); err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to ensure that filter table KUBE-FIREWALL chain exists\")\n\t\t\treturn false\n\t\t}\n\n\t\tif _, err := iptClient.EnsureRule(utiliptables.Prepend, utiliptables.TableFilter, utiliptables.ChainOutput, \"-j\", string(KubeFirewallChain)); err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to ensure that OUTPUT chain jumps to KUBE-FIREWALL\")\n\t\t\treturn false\n\t\t}\n\t\tif _, err := iptClient.EnsureRule(utiliptables.Prepend, utiliptables.TableFilter, utiliptables.ChainInput, \"-j\", string(KubeFirewallChain)); err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to ensure that INPUT chain jumps to KUBE-FIREWALL\")\n\t\t\treturn false\n\t\t}\n\n\t\t// Kube-proxy's use of `route_localnet` to enable NodePorts on localhost\n\t\t// creates a security hole (https://issue.k8s.io/90259) which this\n\t\t// iptables rule mitigates. This rule should have been added to\n\t\t// kube-proxy, but it mistakenly ended up in kubelet instead, and we are\n\t\t// keeping it in kubelet for now in case other third-party components\n\t\t// depend on it.\n\t\tif _, err := iptClient.EnsureRule(utiliptables.Append, utiliptables.TableFilter, KubeFirewallChain,\n\t\t\t\"-m\", \"comment\", \"--comment\", \"block incoming localnet connections\",\n\t\t\t\"--dst\", \"127.0.0.0/8\",\n\t\t\t\"!\", \"--src\", \"127.0.0.0/8\",\n\t\t\t\"-m\", \"conntrack\",\n\t\t\t\"!\", \"--ctstate\", \"RELATED,ESTABLISHED,DNAT\",\n\t\t\t\"-j\", \"DROP\"); err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to ensure rule to drop invalid localhost packets in filter table KUBE-FIREWALL chain\")\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.IPTablesOwnershipCleanup) {\n\t\tok := kl.syncIPTablesRulesDeprecated(iptClient)\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}","line":{"from":76,"to":130}} {"id":100006764,"name":"syncIPTablesRulesDeprecated","signature":"func (kl *Kubelet) syncIPTablesRulesDeprecated(iptClient utiliptables.Interface) bool","file":"pkg/kubelet/kubelet_network_linux.go","code":"// syncIPTablesRulesDeprecated ensures deprecated iptables rules are present:\n// 1. In nat table, KUBE-MARK-DROP rule to mark connections for dropping\n// Marked connection will be drop on INPUT/OUTPUT Chain in filter table\n// 2. In nat table, KUBE-MARK-MASQ rule to mark connections for SNAT\n// Marked connection will get SNAT on POSTROUTING Chain in nat table\nfunc (kl *Kubelet) syncIPTablesRulesDeprecated(iptClient utiliptables.Interface) bool {\n\t// Setup KUBE-MARK-DROP rules\n\tdropMark := getIPTablesMark(kl.iptablesDropBit)\n\tif _, err := iptClient.EnsureChain(utiliptables.TableNAT, KubeMarkDropChain); err != nil {\n\t\tklog.ErrorS(err, \"Failed to ensure that KUBE-MARK-DROP chain exists\")\n\t\treturn false\n\t}\n\tif _, err := iptClient.EnsureRule(utiliptables.Append, utiliptables.TableNAT, KubeMarkDropChain, \"-j\", \"MARK\", \"--or-mark\", dropMark); err != nil {\n\t\tklog.ErrorS(err, \"Failed to ensure that KUBE-MARK-DROP rule exists\")\n\t\treturn false\n\t}\n\tif _, err := iptClient.EnsureChain(utiliptables.TableFilter, KubeFirewallChain); err != nil {\n\t\tklog.ErrorS(err, \"Failed to ensure that KUBE-FIREWALL chain exists\")\n\t\treturn false\n\t}\n\tif _, err := iptClient.EnsureRule(utiliptables.Append, utiliptables.TableFilter, KubeFirewallChain,\n\t\t\"-m\", \"comment\", \"--comment\", \"kubernetes firewall for dropping marked packets\",\n\t\t\"-m\", \"mark\", \"--mark\", fmt.Sprintf(\"%s/%s\", dropMark, dropMark),\n\t\t\"-j\", \"DROP\"); err != nil {\n\t\tklog.ErrorS(err, \"Failed to ensure that KUBE-FIREWALL rule exists\")\n\t\treturn false\n\t}\n\n\t// Setup KUBE-MARK-MASQ rules\n\tmasqueradeMark := getIPTablesMark(kl.iptablesMasqueradeBit)\n\tif _, err := iptClient.EnsureChain(utiliptables.TableNAT, KubeMarkMasqChain); err != nil {\n\t\tklog.ErrorS(err, \"Failed to ensure that KUBE-MARK-MASQ chain exists\")\n\t\treturn false\n\t}\n\tif _, err := iptClient.EnsureChain(utiliptables.TableNAT, KubePostroutingChain); err != nil {\n\t\tklog.ErrorS(err, \"Failed to ensure that KUBE-POSTROUTING chain exists\")\n\t\treturn false\n\t}\n\tif _, err := iptClient.EnsureRule(utiliptables.Append, utiliptables.TableNAT, KubeMarkMasqChain, \"-j\", \"MARK\", \"--or-mark\", masqueradeMark); err != nil {\n\t\tklog.ErrorS(err, \"Failed to ensure that KUBE-MARK-MASQ rule exists\")\n\t\treturn false\n\t}\n\tif _, err := iptClient.EnsureRule(utiliptables.Prepend, utiliptables.TableNAT, utiliptables.ChainPostrouting,\n\t\t\"-m\", \"comment\", \"--comment\", \"kubernetes postrouting rules\", \"-j\", string(KubePostroutingChain)); err != nil {\n\t\tklog.ErrorS(err, \"Failed to ensure that POSTROUTING chain jumps to KUBE-POSTROUTING\")\n\t\treturn false\n\t}\n\n\t// Set up KUBE-POSTROUTING to unmark and masquerade marked packets\n\t// NB: THIS MUST MATCH the corresponding code in the iptables and ipvs\n\t// modes of kube-proxy\n\tif _, err := iptClient.EnsureRule(utiliptables.Append, utiliptables.TableNAT, KubePostroutingChain,\n\t\t\"-m\", \"mark\", \"!\", \"--mark\", fmt.Sprintf(\"%s/%s\", masqueradeMark, masqueradeMark),\n\t\t\"-j\", \"RETURN\"); err != nil {\n\t\tklog.ErrorS(err, \"Failed to ensure first masquerading rule exists\")\n\t\treturn false\n\t}\n\t// Clear the mark to avoid re-masquerading if the packet re-traverses the network stack.\n\t// We know the mark bit is currently set so we can use --xor-mark to clear it (without needing\n\t// to Sprintf another bitmask).\n\tif _, err := iptClient.EnsureRule(utiliptables.Append, utiliptables.TableNAT, KubePostroutingChain,\n\t\t\"-j\", \"MARK\", \"--xor-mark\", masqueradeMark); err != nil {\n\t\tklog.ErrorS(err, \"Failed to ensure second masquerading rule exists\")\n\t\treturn false\n\t}\n\tmasqRule := []string{\n\t\t\"-m\", \"comment\", \"--comment\", \"kubernetes service traffic requiring SNAT\",\n\t\t\"-j\", \"MASQUERADE\",\n\t}\n\tif iptClient.HasRandomFully() {\n\t\tmasqRule = append(masqRule, \"--random-fully\")\n\t}\n\tif _, err := iptClient.EnsureRule(utiliptables.Append, utiliptables.TableNAT, KubePostroutingChain, masqRule...); err != nil {\n\t\tklog.ErrorS(err, \"Failed to ensure third masquerading rule exists\")\n\t\treturn false\n\t}\n\n\treturn true\n}","line":{"from":132,"to":210}} {"id":100006765,"name":"getIPTablesMark","signature":"func getIPTablesMark(bit int) string","file":"pkg/kubelet/kubelet_network_linux.go","code":"// getIPTablesMark returns the fwmark given the bit\nfunc getIPTablesMark(bit int) string {\n\tvalue := 1 \u003c\u003c uint(bit)\n\treturn fmt.Sprintf(\"%#08x\", value)\n}","line":{"from":212,"to":216}} {"id":100006766,"name":"initNetworkUtil","signature":"func (kl *Kubelet) initNetworkUtil() {}","file":"pkg/kubelet/kubelet_network_others.go","code":"// Do nothing.\nfunc (kl *Kubelet) initNetworkUtil() {}","line":{"from":22,"to":23}} {"id":100006767,"name":"registerWithAPIServer","signature":"func (kl *Kubelet) registerWithAPIServer()","file":"pkg/kubelet/kubelet_node_status.go","code":"// registerWithAPIServer registers the node with the cluster master. It is safe\n// to call multiple times, but not concurrently (kl.registrationCompleted is\n// not locked).\nfunc (kl *Kubelet) registerWithAPIServer() {\n\tif kl.registrationCompleted {\n\t\treturn\n\t}\n\tstep := 100 * time.Millisecond\n\n\tfor {\n\t\ttime.Sleep(step)\n\t\tstep = step * 2\n\t\tif step \u003e= 7*time.Second {\n\t\t\tstep = 7 * time.Second\n\t\t}\n\n\t\tnode, err := kl.initialNode(context.TODO())\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Unable to construct v1.Node object for kubelet\")\n\t\t\tcontinue\n\t\t}\n\n\t\tklog.InfoS(\"Attempting to register node\", \"node\", klog.KObj(node))\n\t\tregistered := kl.tryRegisterWithAPIServer(node)\n\t\tif registered {\n\t\t\tklog.InfoS(\"Successfully registered node\", \"node\", klog.KObj(node))\n\t\t\tkl.registrationCompleted = true\n\t\t\treturn\n\t\t}\n\t}\n}","line":{"from":48,"to":78}} {"id":100006768,"name":"tryRegisterWithAPIServer","signature":"func (kl *Kubelet) tryRegisterWithAPIServer(node *v1.Node) bool","file":"pkg/kubelet/kubelet_node_status.go","code":"// tryRegisterWithAPIServer makes an attempt to register the given node with\n// the API server, returning a boolean indicating whether the attempt was\n// successful. If a node with the same name already exists, it reconciles the\n// value of the annotation for controller-managed attach-detach of attachable\n// persistent volumes for the node.\nfunc (kl *Kubelet) tryRegisterWithAPIServer(node *v1.Node) bool {\n\t_, err := kl.kubeClient.CoreV1().Nodes().Create(context.TODO(), node, metav1.CreateOptions{})\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tif !apierrors.IsAlreadyExists(err) {\n\t\tklog.ErrorS(err, \"Unable to register node with API server\", \"node\", klog.KObj(node))\n\t\treturn false\n\t}\n\n\texistingNode, err := kl.kubeClient.CoreV1().Nodes().Get(context.TODO(), string(kl.nodeName), metav1.GetOptions{})\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Unable to register node with API server, error getting existing node\", \"node\", klog.KObj(node))\n\t\treturn false\n\t}\n\tif existingNode == nil {\n\t\tklog.InfoS(\"Unable to register node with API server, no node instance returned\", \"node\", klog.KObj(node))\n\t\treturn false\n\t}\n\n\toriginalNode := existingNode.DeepCopy()\n\n\tklog.InfoS(\"Node was previously registered\", \"node\", klog.KObj(node))\n\n\t// Edge case: the node was previously registered; reconcile\n\t// the value of the controller-managed attach-detach\n\t// annotation.\n\trequiresUpdate := kl.reconcileCMADAnnotationWithExistingNode(node, existingNode)\n\trequiresUpdate = kl.updateDefaultLabels(node, existingNode) || requiresUpdate\n\trequiresUpdate = kl.reconcileExtendedResource(node, existingNode) || requiresUpdate\n\trequiresUpdate = kl.reconcileHugePageResource(node, existingNode) || requiresUpdate\n\tif requiresUpdate {\n\t\tif _, _, err := nodeutil.PatchNodeStatus(kl.kubeClient.CoreV1(), types.NodeName(kl.nodeName), originalNode, existingNode); err != nil {\n\t\t\tklog.ErrorS(err, \"Unable to reconcile node with API server,error updating node\", \"node\", klog.KObj(node))\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}","line":{"from":80,"to":125}} {"id":100006769,"name":"reconcileHugePageResource","signature":"func (kl *Kubelet) reconcileHugePageResource(initialNode, existingNode *v1.Node) bool","file":"pkg/kubelet/kubelet_node_status.go","code":"// reconcileHugePageResource will update huge page capacity for each page size and remove huge page sizes no longer supported\nfunc (kl *Kubelet) reconcileHugePageResource(initialNode, existingNode *v1.Node) bool {\n\trequiresUpdate := updateDefaultResources(initialNode, existingNode)\n\tsupportedHugePageResources := sets.String{}\n\n\tfor resourceName := range initialNode.Status.Capacity {\n\t\tif !v1helper.IsHugePageResourceName(resourceName) {\n\t\t\tcontinue\n\t\t}\n\t\tsupportedHugePageResources.Insert(string(resourceName))\n\n\t\tinitialCapacity := initialNode.Status.Capacity[resourceName]\n\t\tinitialAllocatable := initialNode.Status.Allocatable[resourceName]\n\n\t\tcapacity, resourceIsSupported := existingNode.Status.Capacity[resourceName]\n\t\tallocatable := existingNode.Status.Allocatable[resourceName]\n\n\t\t// Add or update capacity if it the size was previously unsupported or has changed\n\t\tif !resourceIsSupported || capacity.Cmp(initialCapacity) != 0 {\n\t\t\texistingNode.Status.Capacity[resourceName] = initialCapacity.DeepCopy()\n\t\t\trequiresUpdate = true\n\t\t}\n\n\t\t// Add or update allocatable if it the size was previously unsupported or has changed\n\t\tif !resourceIsSupported || allocatable.Cmp(initialAllocatable) != 0 {\n\t\t\texistingNode.Status.Allocatable[resourceName] = initialAllocatable.DeepCopy()\n\t\t\trequiresUpdate = true\n\t\t}\n\n\t}\n\n\tfor resourceName := range existingNode.Status.Capacity {\n\t\tif !v1helper.IsHugePageResourceName(resourceName) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// If huge page size no longer is supported, we remove it from the node\n\t\tif !supportedHugePageResources.Has(string(resourceName)) {\n\t\t\tdelete(existingNode.Status.Capacity, resourceName)\n\t\t\tdelete(existingNode.Status.Allocatable, resourceName)\n\t\t\tklog.InfoS(\"Removing huge page resource which is no longer supported\", \"resourceName\", resourceName)\n\t\t\trequiresUpdate = true\n\t\t}\n\t}\n\treturn requiresUpdate\n}","line":{"from":127,"to":172}} {"id":100006770,"name":"reconcileExtendedResource","signature":"func (kl *Kubelet) reconcileExtendedResource(initialNode, node *v1.Node) bool","file":"pkg/kubelet/kubelet_node_status.go","code":"// Zeros out extended resource capacity during reconciliation.\nfunc (kl *Kubelet) reconcileExtendedResource(initialNode, node *v1.Node) bool {\n\trequiresUpdate := updateDefaultResources(initialNode, node)\n\t// Check with the device manager to see if node has been recreated, in which case extended resources should be zeroed until they are available\n\tif kl.containerManager.ShouldResetExtendedResourceCapacity() {\n\t\tfor k := range node.Status.Capacity {\n\t\t\tif v1helper.IsExtendedResourceName(k) {\n\t\t\t\tklog.InfoS(\"Zero out resource capacity in existing node\", \"resourceName\", k, \"node\", klog.KObj(node))\n\t\t\t\tnode.Status.Capacity[k] = *resource.NewQuantity(int64(0), resource.DecimalSI)\n\t\t\t\tnode.Status.Allocatable[k] = *resource.NewQuantity(int64(0), resource.DecimalSI)\n\t\t\t\trequiresUpdate = true\n\t\t\t}\n\t\t}\n\t}\n\treturn requiresUpdate\n}","line":{"from":174,"to":189}} {"id":100006771,"name":"updateDefaultResources","signature":"func updateDefaultResources(initialNode, existingNode *v1.Node) bool","file":"pkg/kubelet/kubelet_node_status.go","code":"// updateDefaultResources will set the default resources on the existing node according to the initial node\nfunc updateDefaultResources(initialNode, existingNode *v1.Node) bool {\n\trequiresUpdate := false\n\tif existingNode.Status.Capacity == nil {\n\t\tif initialNode.Status.Capacity != nil {\n\t\t\texistingNode.Status.Capacity = initialNode.Status.Capacity.DeepCopy()\n\t\t\trequiresUpdate = true\n\t\t} else {\n\t\t\texistingNode.Status.Capacity = make(map[v1.ResourceName]resource.Quantity)\n\t\t}\n\t}\n\n\tif existingNode.Status.Allocatable == nil {\n\t\tif initialNode.Status.Allocatable != nil {\n\t\t\texistingNode.Status.Allocatable = initialNode.Status.Allocatable.DeepCopy()\n\t\t\trequiresUpdate = true\n\t\t} else {\n\t\t\texistingNode.Status.Allocatable = make(map[v1.ResourceName]resource.Quantity)\n\t\t}\n\t}\n\treturn requiresUpdate\n}","line":{"from":191,"to":212}} {"id":100006772,"name":"updateDefaultLabels","signature":"func (kl *Kubelet) updateDefaultLabels(initialNode, existingNode *v1.Node) bool","file":"pkg/kubelet/kubelet_node_status.go","code":"// updateDefaultLabels will set the default labels on the node\nfunc (kl *Kubelet) updateDefaultLabels(initialNode, existingNode *v1.Node) bool {\n\tdefaultLabels := []string{\n\t\tv1.LabelHostname,\n\t\tv1.LabelTopologyZone,\n\t\tv1.LabelTopologyRegion,\n\t\tv1.LabelFailureDomainBetaZone,\n\t\tv1.LabelFailureDomainBetaRegion,\n\t\tv1.LabelInstanceTypeStable,\n\t\tv1.LabelInstanceType,\n\t\tv1.LabelOSStable,\n\t\tv1.LabelArchStable,\n\t\tv1.LabelWindowsBuild,\n\t\tkubeletapis.LabelOS,\n\t\tkubeletapis.LabelArch,\n\t}\n\n\tneedsUpdate := false\n\tif existingNode.Labels == nil {\n\t\texistingNode.Labels = make(map[string]string)\n\t}\n\t//Set default labels but make sure to not set labels with empty values\n\tfor _, label := range defaultLabels {\n\t\tif _, hasInitialValue := initialNode.Labels[label]; !hasInitialValue {\n\t\t\tcontinue\n\t\t}\n\n\t\tif existingNode.Labels[label] != initialNode.Labels[label] {\n\t\t\texistingNode.Labels[label] = initialNode.Labels[label]\n\t\t\tneedsUpdate = true\n\t\t}\n\n\t\tif existingNode.Labels[label] == \"\" {\n\t\t\tdelete(existingNode.Labels, label)\n\t\t}\n\t}\n\n\treturn needsUpdate\n}","line":{"from":214,"to":252}} {"id":100006773,"name":"reconcileCMADAnnotationWithExistingNode","signature":"func (kl *Kubelet) reconcileCMADAnnotationWithExistingNode(node, existingNode *v1.Node) bool","file":"pkg/kubelet/kubelet_node_status.go","code":"// reconcileCMADAnnotationWithExistingNode reconciles the controller-managed\n// attach-detach annotation on a new node and the existing node, returning\n// whether the existing node must be updated.\nfunc (kl *Kubelet) reconcileCMADAnnotationWithExistingNode(node, existingNode *v1.Node) bool {\n\tvar (\n\t\texistingCMAAnnotation = existingNode.Annotations[volutil.ControllerManagedAttachAnnotation]\n\t\tnewCMAAnnotation, newSet = node.Annotations[volutil.ControllerManagedAttachAnnotation]\n\t)\n\n\tif newCMAAnnotation == existingCMAAnnotation {\n\t\treturn false\n\t}\n\n\t// If the just-constructed node and the existing node do\n\t// not have the same value, update the existing node with\n\t// the correct value of the annotation.\n\tif !newSet {\n\t\tklog.InfoS(\"Controller attach-detach setting changed to false; updating existing Node\")\n\t\tdelete(existingNode.Annotations, volutil.ControllerManagedAttachAnnotation)\n\t} else {\n\t\tklog.InfoS(\"Controller attach-detach setting changed to true; updating existing Node\")\n\t\tif existingNode.Annotations == nil {\n\t\t\texistingNode.Annotations = make(map[string]string)\n\t\t}\n\t\texistingNode.Annotations[volutil.ControllerManagedAttachAnnotation] = newCMAAnnotation\n\t}\n\n\treturn true\n}","line":{"from":254,"to":282}} {"id":100006774,"name":"initialNode","signature":"func (kl *Kubelet) initialNode(ctx context.Context) (*v1.Node, error)","file":"pkg/kubelet/kubelet_node_status.go","code":"// initialNode constructs the initial v1.Node for this Kubelet, incorporating node\n// labels, information from the cloud provider, and Kubelet configuration.\nfunc (kl *Kubelet) initialNode(ctx context.Context) (*v1.Node, error) {\n\tnode := \u0026v1.Node{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: string(kl.nodeName),\n\t\t\tLabels: map[string]string{\n\t\t\t\tv1.LabelHostname: kl.hostname,\n\t\t\t\tv1.LabelOSStable: goruntime.GOOS,\n\t\t\t\tv1.LabelArchStable: goruntime.GOARCH,\n\t\t\t\tkubeletapis.LabelOS: goruntime.GOOS,\n\t\t\t\tkubeletapis.LabelArch: goruntime.GOARCH,\n\t\t\t},\n\t\t},\n\t\tSpec: v1.NodeSpec{\n\t\t\tUnschedulable: !kl.registerSchedulable,\n\t\t},\n\t}\n\tosLabels, err := getOSSpecificLabels()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor label, value := range osLabels {\n\t\tnode.Labels[label] = value\n\t}\n\n\tnodeTaints := make([]v1.Taint, len(kl.registerWithTaints))\n\tcopy(nodeTaints, kl.registerWithTaints)\n\tunschedulableTaint := v1.Taint{\n\t\tKey: v1.TaintNodeUnschedulable,\n\t\tEffect: v1.TaintEffectNoSchedule,\n\t}\n\n\t// Taint node with TaintNodeUnschedulable when initializing\n\t// node to avoid race condition; refer to #63897 for more detail.\n\tif node.Spec.Unschedulable \u0026\u0026\n\t\t!taintutil.TaintExists(nodeTaints, \u0026unschedulableTaint) {\n\t\tnodeTaints = append(nodeTaints, unschedulableTaint)\n\t}\n\n\tif kl.externalCloudProvider {\n\t\ttaint := v1.Taint{\n\t\t\tKey: cloudproviderapi.TaintExternalCloudProvider,\n\t\t\tValue: \"true\",\n\t\t\tEffect: v1.TaintEffectNoSchedule,\n\t\t}\n\n\t\tnodeTaints = append(nodeTaints, taint)\n\t}\n\tif len(nodeTaints) \u003e 0 {\n\t\tnode.Spec.Taints = nodeTaints\n\t}\n\t// Initially, set NodeNetworkUnavailable to true.\n\tif kl.providerRequiresNetworkingConfiguration() {\n\t\tnode.Status.Conditions = append(node.Status.Conditions, v1.NodeCondition{\n\t\t\tType: v1.NodeNetworkUnavailable,\n\t\t\tStatus: v1.ConditionTrue,\n\t\t\tReason: \"NoRouteCreated\",\n\t\t\tMessage: \"Node created without a route\",\n\t\t\tLastTransitionTime: metav1.NewTime(kl.clock.Now()),\n\t\t})\n\t}\n\n\tif kl.enableControllerAttachDetach {\n\t\tif node.Annotations == nil {\n\t\t\tnode.Annotations = make(map[string]string)\n\t\t}\n\n\t\tklog.V(2).InfoS(\"Setting node annotation to enable volume controller attach/detach\")\n\t\tnode.Annotations[volutil.ControllerManagedAttachAnnotation] = \"true\"\n\t} else {\n\t\tklog.V(2).InfoS(\"Controller attach/detach is disabled for this node; Kubelet will attach and detach volumes\")\n\t}\n\n\tif kl.keepTerminatedPodVolumes {\n\t\tif node.Annotations == nil {\n\t\t\tnode.Annotations = make(map[string]string)\n\t\t}\n\t\tklog.V(2).InfoS(\"Setting node annotation to keep pod volumes of terminated pods attached to the node\")\n\t\tnode.Annotations[volutil.KeepTerminatedPodVolumesAnnotation] = \"true\"\n\t}\n\n\t// @question: should this be place after the call to the cloud provider? which also applies labels\n\tfor k, v := range kl.nodeLabels {\n\t\tif cv, found := node.ObjectMeta.Labels[k]; found {\n\t\t\tklog.InfoS(\"the node label will overwrite default setting\", \"labelKey\", k, \"labelValue\", v, \"default\", cv)\n\t\t}\n\t\tnode.ObjectMeta.Labels[k] = v\n\t}\n\n\tif kl.providerID != \"\" {\n\t\tnode.Spec.ProviderID = kl.providerID\n\t}\n\n\tif kl.cloud != nil {\n\t\tinstances, ok := kl.cloud.Instances()\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"failed to get instances from cloud provider\")\n\t\t}\n\n\t\t// TODO: We can't assume that the node has credentials to talk to the\n\t\t// cloudprovider from arbitrary nodes. At most, we should talk to a\n\t\t// local metadata server here.\n\t\tvar err error\n\t\tif node.Spec.ProviderID == \"\" {\n\t\t\tnode.Spec.ProviderID, err = cloudprovider.GetInstanceProviderID(ctx, kl.cloud, kl.nodeName)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\tinstanceType, err := instances.InstanceType(ctx, kl.nodeName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif instanceType != \"\" {\n\t\t\tklog.InfoS(\"Adding label from cloud provider\", \"labelKey\", v1.LabelInstanceType, \"labelValue\", instanceType)\n\t\t\tnode.ObjectMeta.Labels[v1.LabelInstanceType] = instanceType\n\t\t\tklog.InfoS(\"Adding node label from cloud provider\", \"labelKey\", v1.LabelInstanceTypeStable, \"labelValue\", instanceType)\n\t\t\tnode.ObjectMeta.Labels[v1.LabelInstanceTypeStable] = instanceType\n\t\t}\n\t\t// If the cloud has zone information, label the node with the zone information\n\t\tzones, ok := kl.cloud.Zones()\n\t\tif ok {\n\t\t\tzone, err := zones.GetZone(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to get zone from cloud provider: %v\", err)\n\t\t\t}\n\t\t\tif zone.FailureDomain != \"\" {\n\t\t\t\tklog.InfoS(\"Adding node label from cloud provider\", \"labelKey\", v1.LabelFailureDomainBetaZone, \"labelValue\", zone.FailureDomain)\n\t\t\t\tnode.ObjectMeta.Labels[v1.LabelFailureDomainBetaZone] = zone.FailureDomain\n\t\t\t\tklog.InfoS(\"Adding node label from cloud provider\", \"labelKey\", v1.LabelTopologyZone, \"labelValue\", zone.FailureDomain)\n\t\t\t\tnode.ObjectMeta.Labels[v1.LabelTopologyZone] = zone.FailureDomain\n\t\t\t}\n\t\t\tif zone.Region != \"\" {\n\t\t\t\tklog.InfoS(\"Adding node label from cloud provider\", \"labelKey\", v1.LabelFailureDomainBetaRegion, \"labelValue\", zone.Region)\n\t\t\t\tnode.ObjectMeta.Labels[v1.LabelFailureDomainBetaRegion] = zone.Region\n\t\t\t\tklog.InfoS(\"Adding node label from cloud provider\", \"labelKey\", v1.LabelTopologyRegion, \"labelValue\", zone.Region)\n\t\t\t\tnode.ObjectMeta.Labels[v1.LabelTopologyRegion] = zone.Region\n\t\t\t}\n\t\t}\n\t}\n\n\tkl.setNodeStatus(ctx, node)\n\n\treturn node, nil\n}","line":{"from":284,"to":430}} {"id":100006775,"name":"fastNodeStatusUpdate","signature":"func (kl *Kubelet) fastNodeStatusUpdate(ctx context.Context, timeout bool) (completed bool)","file":"pkg/kubelet/kubelet_node_status.go","code":"// fastNodeStatusUpdate is a \"lightweight\" version of syncNodeStatus which doesn't hit the\n// apiserver except for the final run, to be called by fastStatusUpdateOnce in each loop.\n// It holds the same lock as syncNodeStatus and is thread-safe when called concurrently with\n// syncNodeStatus. Its return value indicates whether the loop running it should exit\n// (final run), and it also sets kl.containerRuntimeReadyExpected.\nfunc (kl *Kubelet) fastNodeStatusUpdate(ctx context.Context, timeout bool) (completed bool) {\n\tkl.syncNodeStatusMux.Lock()\n\tdefer func() {\n\t\tkl.syncNodeStatusMux.Unlock()\n\n\t\tif completed {\n\t\t\t// containerRuntimeReadyExpected is read by updateRuntimeUp().\n\t\t\t// Not going for a more granular mutex as this path runs only once.\n\t\t\tkl.updateRuntimeMux.Lock()\n\t\t\tdefer kl.updateRuntimeMux.Unlock()\n\t\t\tkl.containerRuntimeReadyExpected = true\n\t\t}\n\t}()\n\n\tif timeout {\n\t\tklog.ErrorS(nil, \"Node not becoming ready in time after startup\")\n\t\treturn true\n\t}\n\n\toriginalNode, err := kl.GetNode()\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Error getting the current node from lister\")\n\t\treturn false\n\t}\n\n\treadyIdx, originalNodeReady := nodeutil.GetNodeCondition(\u0026originalNode.Status, v1.NodeReady)\n\tif readyIdx == -1 {\n\t\tklog.ErrorS(nil, \"Node does not have NodeReady condition\", \"originalNode\", originalNode)\n\t\treturn false\n\t}\n\n\tif originalNodeReady.Status == v1.ConditionTrue {\n\t\treturn true\n\t}\n\n\t// This is in addition to the regular syncNodeStatus logic so we can get the container runtime status earlier.\n\t// This function itself has a mutex and it doesn't recursively call fastNodeStatusUpdate or syncNodeStatus.\n\tkl.updateRuntimeUp()\n\n\tnode, changed := kl.updateNode(ctx, originalNode)\n\n\tif !changed {\n\t\t// We don't do markVolumesFromNode(node) here and leave it to the regular syncNodeStatus().\n\t\treturn false\n\t}\n\n\treadyIdx, nodeReady := nodeutil.GetNodeCondition(\u0026node.Status, v1.NodeReady)\n\tif readyIdx == -1 {\n\t\tklog.ErrorS(nil, \"Node does not have NodeReady condition\", \"node\", node)\n\t\treturn false\n\t}\n\n\tif nodeReady.Status == v1.ConditionFalse {\n\t\treturn false\n\t}\n\n\tklog.InfoS(\"Fast updating node status as it just became ready\")\n\tif _, err := kl.patchNodeStatus(originalNode, node); err != nil {\n\t\t// The originalNode is probably stale, but we know that the current state of kubelet would turn\n\t\t// the node to be ready. Retry using syncNodeStatus() which fetches from the apiserver.\n\t\tklog.ErrorS(err, \"Error updating node status, will retry with syncNodeStatus\")\n\n\t\t// The reversed kl.syncNodeStatusMux.Unlock/Lock() below to allow kl.syncNodeStatus() execution.\n\t\tkl.syncNodeStatusMux.Unlock()\n\t\tkl.syncNodeStatus()\n\t\t// This lock action is unnecessary if we add a flag to check in the defer before unlocking it,\n\t\t// but having it here makes the logic a bit easier to read.\n\t\tkl.syncNodeStatusMux.Lock()\n\t}\n\n\t// We don't do markVolumesFromNode(node) here and leave it to the regular syncNodeStatus().\n\treturn true\n}","line":{"from":432,"to":509}} {"id":100006776,"name":"syncNodeStatus","signature":"func (kl *Kubelet) syncNodeStatus()","file":"pkg/kubelet/kubelet_node_status.go","code":"// syncNodeStatus should be called periodically from a goroutine.\n// It synchronizes node status to master if there is any change or enough time\n// passed from the last sync, registering the kubelet first if necessary.\nfunc (kl *Kubelet) syncNodeStatus() {\n\tkl.syncNodeStatusMux.Lock()\n\tdefer kl.syncNodeStatusMux.Unlock()\n\tctx := context.Background()\n\n\tif kl.kubeClient == nil || kl.heartbeatClient == nil {\n\t\treturn\n\t}\n\tif kl.registerNode {\n\t\t// This will exit immediately if it doesn't need to do anything.\n\t\tkl.registerWithAPIServer()\n\t}\n\tif err := kl.updateNodeStatus(ctx); err != nil {\n\t\tklog.ErrorS(err, \"Unable to update node status\")\n\t}\n}","line":{"from":511,"to":529}} {"id":100006777,"name":"updateNodeStatus","signature":"func (kl *Kubelet) updateNodeStatus(ctx context.Context) error","file":"pkg/kubelet/kubelet_node_status.go","code":"// updateNodeStatus updates node status to master with retries if there is any\n// change or enough time passed from the last sync.\nfunc (kl *Kubelet) updateNodeStatus(ctx context.Context) error {\n\tklog.V(5).InfoS(\"Updating node status\")\n\tfor i := 0; i \u003c nodeStatusUpdateRetry; i++ {\n\t\tif err := kl.tryUpdateNodeStatus(ctx, i); err != nil {\n\t\t\tif i \u003e 0 \u0026\u0026 kl.onRepeatedHeartbeatFailure != nil {\n\t\t\t\tkl.onRepeatedHeartbeatFailure()\n\t\t\t}\n\t\t\tklog.ErrorS(err, \"Error updating node status, will retry\")\n\t\t} else {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"update node status exceeds retry count\")\n}","line":{"from":531,"to":546}} {"id":100006778,"name":"tryUpdateNodeStatus","signature":"func (kl *Kubelet) tryUpdateNodeStatus(ctx context.Context, tryNumber int) error","file":"pkg/kubelet/kubelet_node_status.go","code":"// tryUpdateNodeStatus tries to update node status to master if there is any\n// change or enough time passed from the last sync.\nfunc (kl *Kubelet) tryUpdateNodeStatus(ctx context.Context, tryNumber int) error {\n\t// In large clusters, GET and PUT operations on Node objects coming\n\t// from here are the majority of load on apiserver and etcd.\n\t// To reduce the load on etcd, we are serving GET operations from\n\t// apiserver cache (the data might be slightly delayed but it doesn't\n\t// seem to cause more conflict - the delays are pretty small).\n\t// If it result in a conflict, all retries are served directly from etcd.\n\topts := metav1.GetOptions{}\n\tif tryNumber == 0 {\n\t\tutil.FromApiserverCache(\u0026opts)\n\t}\n\toriginalNode, err := kl.heartbeatClient.CoreV1().Nodes().Get(ctx, string(kl.nodeName), opts)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting node %q: %v\", kl.nodeName, err)\n\t}\n\tif originalNode == nil {\n\t\treturn fmt.Errorf(\"nil %q node object\", kl.nodeName)\n\t}\n\n\tnode, changed := kl.updateNode(ctx, originalNode)\n\tshouldPatchNodeStatus := changed || kl.clock.Since(kl.lastStatusReportTime) \u003e= kl.nodeStatusReportFrequency\n\n\tif !shouldPatchNodeStatus {\n\t\tkl.markVolumesFromNode(node)\n\t\treturn nil\n\t}\n\n\tupdatedNode, err := kl.patchNodeStatus(originalNode, node)\n\tif err == nil {\n\t\tkl.markVolumesFromNode(updatedNode)\n\t}\n\treturn err\n}","line":{"from":548,"to":582}} {"id":100006779,"name":"updateNode","signature":"func (kl *Kubelet) updateNode(ctx context.Context, originalNode *v1.Node) (*v1.Node, bool)","file":"pkg/kubelet/kubelet_node_status.go","code":"// updateNode creates a copy of originalNode and runs update logic on it.\n// It returns the updated node object and a bool indicating if anything has been changed.\nfunc (kl *Kubelet) updateNode(ctx context.Context, originalNode *v1.Node) (*v1.Node, bool) {\n\tnode := originalNode.DeepCopy()\n\n\tpodCIDRChanged := false\n\tif len(node.Spec.PodCIDRs) != 0 {\n\t\t// Pod CIDR could have been updated before, so we cannot rely on\n\t\t// node.Spec.PodCIDR being non-empty. We also need to know if pod CIDR is\n\t\t// actually changed.\n\t\tvar err error\n\t\tpodCIDRs := strings.Join(node.Spec.PodCIDRs, \",\")\n\t\tif podCIDRChanged, err = kl.updatePodCIDR(ctx, podCIDRs); err != nil {\n\t\t\tklog.ErrorS(err, \"Error updating pod CIDR\")\n\t\t}\n\t}\n\n\tareRequiredLabelsNotPresent := false\n\tosName, osLabelExists := node.Labels[v1.LabelOSStable]\n\tif !osLabelExists || osName != goruntime.GOOS {\n\t\tif len(node.Labels) == 0 {\n\t\t\tnode.Labels = make(map[string]string)\n\t\t}\n\t\tnode.Labels[v1.LabelOSStable] = goruntime.GOOS\n\t\tareRequiredLabelsNotPresent = true\n\t}\n\t// Set the arch if there is a mismatch\n\tarch, archLabelExists := node.Labels[v1.LabelArchStable]\n\tif !archLabelExists || arch != goruntime.GOARCH {\n\t\tif len(node.Labels) == 0 {\n\t\t\tnode.Labels = make(map[string]string)\n\t\t}\n\t\tnode.Labels[v1.LabelArchStable] = goruntime.GOARCH\n\t\tareRequiredLabelsNotPresent = true\n\t}\n\n\tkl.setNodeStatus(ctx, node)\n\n\tchanged := podCIDRChanged || nodeStatusHasChanged(\u0026originalNode.Status, \u0026node.Status) || areRequiredLabelsNotPresent\n\treturn node, changed\n}","line":{"from":584,"to":624}} {"id":100006780,"name":"patchNodeStatus","signature":"func (kl *Kubelet) patchNodeStatus(originalNode, node *v1.Node) (*v1.Node, error)","file":"pkg/kubelet/kubelet_node_status.go","code":"// patchNodeStatus patches node on the API server based on originalNode.\n// It returns any potential error, or an updatedNode and refreshes the state of kubelet when successful.\nfunc (kl *Kubelet) patchNodeStatus(originalNode, node *v1.Node) (*v1.Node, error) {\n\t// Patch the current status on the API server\n\tupdatedNode, _, err := nodeutil.PatchNodeStatus(kl.heartbeatClient.CoreV1(), types.NodeName(kl.nodeName), originalNode, node)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkl.lastStatusReportTime = kl.clock.Now()\n\tkl.setLastObservedNodeAddresses(updatedNode.Status.Addresses)\n\treturn updatedNode, nil\n}","line":{"from":626,"to":637}} {"id":100006781,"name":"markVolumesFromNode","signature":"func (kl *Kubelet) markVolumesFromNode(node *v1.Node)","file":"pkg/kubelet/kubelet_node_status.go","code":"// markVolumesFromNode updates volumeManager with VolumesInUse status from node.\n//\n// In the case of node status update being unnecessary, call with the fetched node.\n// We must mark the volumes as ReportedInUse in volume manager's dsw even\n// if no changes were made to the node status (no volumes were added or removed\n// from the VolumesInUse list).\n//\n// The reason is that on a kubelet restart, the volume manager's dsw is\n// repopulated and the volume ReportedInUse is initialized to false, while the\n// VolumesInUse list from the Node object still contains the state from the\n// previous kubelet instantiation.\n//\n// Once the volumes are added to the dsw, the ReportedInUse field needs to be\n// synced from the VolumesInUse list in the Node.Status.\n//\n// The MarkVolumesAsReportedInUse() call cannot be performed in dsw directly\n// because it does not have access to the Node object.\n// This also cannot be populated on node status manager init because the volume\n// may not have been added to dsw at that time.\n//\n// Or, after a successful node status update, call with updatedNode returned from\n// the patch call, to mark the volumeInUse as reportedInUse to indicate\n// those volumes are already updated in the node's status\nfunc (kl *Kubelet) markVolumesFromNode(node *v1.Node) {\n\tkl.volumeManager.MarkVolumesAsReportedInUse(node.Status.VolumesInUse)\n}","line":{"from":639,"to":664}} {"id":100006782,"name":"recordNodeStatusEvent","signature":"func (kl *Kubelet) recordNodeStatusEvent(eventType, event string)","file":"pkg/kubelet/kubelet_node_status.go","code":"// recordNodeStatusEvent records an event of the given type with the given\n// message for the node.\nfunc (kl *Kubelet) recordNodeStatusEvent(eventType, event string) {\n\tklog.V(2).InfoS(\"Recording event message for node\", \"node\", klog.KRef(\"\", string(kl.nodeName)), \"event\", event)\n\tkl.recorder.Eventf(kl.nodeRef, eventType, event, \"Node %s status is now: %s\", kl.nodeName, event)\n}","line":{"from":666,"to":671}} {"id":100006783,"name":"recordEvent","signature":"func (kl *Kubelet) recordEvent(eventType, event, message string)","file":"pkg/kubelet/kubelet_node_status.go","code":"// recordEvent records an event for this node, the Kubelet's nodeRef is passed to the recorder\nfunc (kl *Kubelet) recordEvent(eventType, event, message string) {\n\tkl.recorder.Eventf(kl.nodeRef, eventType, event, message)\n}","line":{"from":673,"to":676}} {"id":100006784,"name":"recordNodeSchedulableEvent","signature":"func (kl *Kubelet) recordNodeSchedulableEvent(ctx context.Context, node *v1.Node) error","file":"pkg/kubelet/kubelet_node_status.go","code":"// record if node schedulable change.\nfunc (kl *Kubelet) recordNodeSchedulableEvent(ctx context.Context, node *v1.Node) error {\n\tkl.lastNodeUnschedulableLock.Lock()\n\tdefer kl.lastNodeUnschedulableLock.Unlock()\n\tif kl.lastNodeUnschedulable != node.Spec.Unschedulable {\n\t\tif node.Spec.Unschedulable {\n\t\t\tkl.recordNodeStatusEvent(v1.EventTypeNormal, events.NodeNotSchedulable)\n\t\t} else {\n\t\t\tkl.recordNodeStatusEvent(v1.EventTypeNormal, events.NodeSchedulable)\n\t\t}\n\t\tkl.lastNodeUnschedulable = node.Spec.Unschedulable\n\t}\n\treturn nil\n}","line":{"from":678,"to":691}} {"id":100006785,"name":"setNodeStatus","signature":"func (kl *Kubelet) setNodeStatus(ctx context.Context, node *v1.Node)","file":"pkg/kubelet/kubelet_node_status.go","code":"// setNodeStatus fills in the Status fields of the given Node, overwriting\n// any fields that are currently set.\n// TODO(madhusudancs): Simplify the logic for setting node conditions and\n// refactor the node status condition code out to a different file.\nfunc (kl *Kubelet) setNodeStatus(ctx context.Context, node *v1.Node) {\n\tfor i, f := range kl.setNodeStatusFuncs {\n\t\tklog.V(5).InfoS(\"Setting node status condition code\", \"position\", i, \"node\", klog.KObj(node))\n\t\tif err := f(ctx, node); err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to set some node status fields\", \"node\", klog.KObj(node))\n\t\t}\n\t}\n}","line":{"from":693,"to":704}} {"id":100006786,"name":"setLastObservedNodeAddresses","signature":"func (kl *Kubelet) setLastObservedNodeAddresses(addresses []v1.NodeAddress)","file":"pkg/kubelet/kubelet_node_status.go","code":"func (kl *Kubelet) setLastObservedNodeAddresses(addresses []v1.NodeAddress) {\n\tkl.lastObservedNodeAddressesMux.Lock()\n\tdefer kl.lastObservedNodeAddressesMux.Unlock()\n\tkl.lastObservedNodeAddresses = addresses\n}","line":{"from":706,"to":710}} {"id":100006787,"name":"getLastObservedNodeAddresses","signature":"func (kl *Kubelet) getLastObservedNodeAddresses() []v1.NodeAddress","file":"pkg/kubelet/kubelet_node_status.go","code":"func (kl *Kubelet) getLastObservedNodeAddresses() []v1.NodeAddress {\n\tkl.lastObservedNodeAddressesMux.RLock()\n\tdefer kl.lastObservedNodeAddressesMux.RUnlock()\n\treturn kl.lastObservedNodeAddresses\n}","line":{"from":711,"to":715}} {"id":100006788,"name":"defaultNodeStatusFuncs","signature":"func (kl *Kubelet) defaultNodeStatusFuncs() []func(context.Context, *v1.Node) error","file":"pkg/kubelet/kubelet_node_status.go","code":"// defaultNodeStatusFuncs is a factory that generates the default set of\n// setNodeStatus funcs\nfunc (kl *Kubelet) defaultNodeStatusFuncs() []func(context.Context, *v1.Node) error {\n\t// if cloud is not nil, we expect the cloud resource sync manager to exist\n\tvar nodeAddressesFunc func() ([]v1.NodeAddress, error)\n\tif kl.cloud != nil {\n\t\tnodeAddressesFunc = kl.cloudResourceSyncManager.NodeAddresses\n\t}\n\tvar validateHostFunc func() error\n\tif kl.appArmorValidator != nil {\n\t\tvalidateHostFunc = kl.appArmorValidator.ValidateHost\n\t}\n\tvar setters []func(ctx context.Context, n *v1.Node) error\n\tsetters = append(setters,\n\t\tnodestatus.NodeAddress(kl.nodeIPs, kl.nodeIPValidator, kl.hostname, kl.hostnameOverridden, kl.externalCloudProvider, kl.cloud, nodeAddressesFunc),\n\t\tnodestatus.MachineInfo(string(kl.nodeName), kl.maxPods, kl.podsPerCore, kl.GetCachedMachineInfo, kl.containerManager.GetCapacity,\n\t\t\tkl.containerManager.GetDevicePluginResourceCapacity, kl.containerManager.GetNodeAllocatableReservation, kl.recordEvent, kl.supportLocalStorageCapacityIsolation()),\n\t\tnodestatus.VersionInfo(kl.cadvisor.VersionInfo, kl.containerRuntime.Type, kl.containerRuntime.Version),\n\t\tnodestatus.DaemonEndpoints(kl.daemonEndpoints),\n\t\tnodestatus.Images(kl.nodeStatusMaxImages, kl.imageManager.GetImageList),\n\t\tnodestatus.GoRuntime(),\n\t)\n\t// Volume limits\n\tsetters = append(setters, nodestatus.VolumeLimits(kl.volumePluginMgr.ListVolumePluginWithLimits))\n\n\tsetters = append(setters,\n\t\tnodestatus.MemoryPressureCondition(kl.clock.Now, kl.evictionManager.IsUnderMemoryPressure, kl.recordNodeStatusEvent),\n\t\tnodestatus.DiskPressureCondition(kl.clock.Now, kl.evictionManager.IsUnderDiskPressure, kl.recordNodeStatusEvent),\n\t\tnodestatus.PIDPressureCondition(kl.clock.Now, kl.evictionManager.IsUnderPIDPressure, kl.recordNodeStatusEvent),\n\t\tnodestatus.ReadyCondition(kl.clock.Now, kl.runtimeState.runtimeErrors, kl.runtimeState.networkErrors, kl.runtimeState.storageErrors,\n\t\t\tvalidateHostFunc, kl.containerManager.Status, kl.shutdownManager.ShutdownStatus, kl.recordNodeStatusEvent, kl.supportLocalStorageCapacityIsolation()),\n\t\tnodestatus.VolumesInUse(kl.volumeManager.ReconcilerStatesHasBeenSynced, kl.volumeManager.GetVolumesInUse),\n\t\t// TODO(mtaufen): I decided not to move this setter for now, since all it does is send an event\n\t\t// and record state back to the Kubelet runtime object. In the future, I'd like to isolate\n\t\t// these side-effects by decoupling the decisions to send events and partial status recording\n\t\t// from the Node setters.\n\t\tkl.recordNodeSchedulableEvent,\n\t)\n\treturn setters\n}","line":{"from":717,"to":756}} {"id":100006789,"name":"validateNodeIP","signature":"func validateNodeIP(nodeIP net.IP) error","file":"pkg/kubelet/kubelet_node_status.go","code":"// Validate given node IP belongs to the current host\nfunc validateNodeIP(nodeIP net.IP) error {\n\t// Honor IP limitations set in setNodeStatus()\n\tif nodeIP.To4() == nil \u0026\u0026 nodeIP.To16() == nil {\n\t\treturn fmt.Errorf(\"nodeIP must be a valid IP address\")\n\t}\n\tif nodeIP.IsLoopback() {\n\t\treturn fmt.Errorf(\"nodeIP can't be loopback address\")\n\t}\n\tif nodeIP.IsMulticast() {\n\t\treturn fmt.Errorf(\"nodeIP can't be a multicast address\")\n\t}\n\tif nodeIP.IsLinkLocalUnicast() {\n\t\treturn fmt.Errorf(\"nodeIP can't be a link-local unicast address\")\n\t}\n\tif nodeIP.IsUnspecified() {\n\t\treturn fmt.Errorf(\"nodeIP can't be an all zeros address\")\n\t}\n\n\taddrs, err := net.InterfaceAddrs()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, addr := range addrs {\n\t\tvar ip net.IP\n\t\tswitch v := addr.(type) {\n\t\tcase *net.IPNet:\n\t\t\tip = v.IP\n\t\tcase *net.IPAddr:\n\t\t\tip = v.IP\n\t\t}\n\t\tif ip != nil \u0026\u0026 ip.Equal(nodeIP) {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"node IP: %q not found in the host's network interfaces\", nodeIP.String())\n}","line":{"from":758,"to":794}} {"id":100006790,"name":"nodeStatusHasChanged","signature":"func nodeStatusHasChanged(originalStatus *v1.NodeStatus, status *v1.NodeStatus) bool","file":"pkg/kubelet/kubelet_node_status.go","code":"// nodeStatusHasChanged compares the original node and current node's status and\n// returns true if any change happens. The heartbeat timestamp is ignored.\nfunc nodeStatusHasChanged(originalStatus *v1.NodeStatus, status *v1.NodeStatus) bool {\n\tif originalStatus == nil \u0026\u0026 status == nil {\n\t\treturn false\n\t}\n\tif originalStatus == nil || status == nil {\n\t\treturn true\n\t}\n\n\t// Compare node conditions here because we need to ignore the heartbeat timestamp.\n\tif nodeConditionsHaveChanged(originalStatus.Conditions, status.Conditions) {\n\t\treturn true\n\t}\n\n\t// Compare other fields of NodeStatus.\n\toriginalStatusCopy := originalStatus.DeepCopy()\n\tstatusCopy := status.DeepCopy()\n\toriginalStatusCopy.Conditions = nil\n\tstatusCopy.Conditions = nil\n\treturn !apiequality.Semantic.DeepEqual(originalStatusCopy, statusCopy)\n}","line":{"from":796,"to":817}} {"id":100006791,"name":"nodeConditionsHaveChanged","signature":"func nodeConditionsHaveChanged(originalConditions []v1.NodeCondition, conditions []v1.NodeCondition) bool","file":"pkg/kubelet/kubelet_node_status.go","code":"// nodeConditionsHaveChanged compares the original node and current node's\n// conditions and returns true if any change happens. The heartbeat timestamp is\n// ignored.\nfunc nodeConditionsHaveChanged(originalConditions []v1.NodeCondition, conditions []v1.NodeCondition) bool {\n\tif len(originalConditions) != len(conditions) {\n\t\treturn true\n\t}\n\n\toriginalConditionsCopy := make([]v1.NodeCondition, 0, len(originalConditions))\n\toriginalConditionsCopy = append(originalConditionsCopy, originalConditions...)\n\tconditionsCopy := make([]v1.NodeCondition, 0, len(conditions))\n\tconditionsCopy = append(conditionsCopy, conditions...)\n\n\tsort.SliceStable(originalConditionsCopy, func(i, j int) bool { return originalConditionsCopy[i].Type \u003c originalConditionsCopy[j].Type })\n\tsort.SliceStable(conditionsCopy, func(i, j int) bool { return conditionsCopy[i].Type \u003c conditionsCopy[j].Type })\n\n\treplacedheartbeatTime := metav1.Time{}\n\tfor i := range conditionsCopy {\n\t\toriginalConditionsCopy[i].LastHeartbeatTime = replacedheartbeatTime\n\t\tconditionsCopy[i].LastHeartbeatTime = replacedheartbeatTime\n\t\tif !apiequality.Semantic.DeepEqual(\u0026originalConditionsCopy[i], \u0026conditionsCopy[i]) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":819,"to":844}} {"id":100006792,"name":"getOSSpecificLabels","signature":"func getOSSpecificLabels() (map[string]string, error)","file":"pkg/kubelet/kubelet_node_status_others.go","code":"func getOSSpecificLabels() (map[string]string, error) {\n\treturn nil, nil\n}","line":{"from":22,"to":24}} {"id":100006793,"name":"getOSSpecificLabels","signature":"func getOSSpecificLabels() (map[string]string, error)","file":"pkg/kubelet/kubelet_node_status_windows.go","code":"func getOSSpecificLabels() (map[string]string, error) {\n\tosInfo, err := winstats.GetOSInfo()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn map[string]string{v1.LabelWindowsBuild: osInfo.GetBuild()}, nil\n}","line":{"from":27,"to":34}} {"id":100006794,"name":"listPodsFromDisk","signature":"func (kl *Kubelet) listPodsFromDisk() ([]types.UID, error)","file":"pkg/kubelet/kubelet_pods.go","code":"// Get a list of pods that have data directories.\nfunc (kl *Kubelet) listPodsFromDisk() ([]types.UID, error) {\n\tpodInfos, err := os.ReadDir(kl.getPodsDir())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpods := []types.UID{}\n\tfor i := range podInfos {\n\t\tif podInfos[i].IsDir() {\n\t\t\tpods = append(pods, types.UID(podInfos[i].Name()))\n\t\t}\n\t}\n\treturn pods, nil\n}","line":{"from":82,"to":95}} {"id":100006795,"name":"GetActivePods","signature":"func (kl *Kubelet) GetActivePods() []*v1.Pod","file":"pkg/kubelet/kubelet_pods.go","code":"// GetActivePods returns pods that have been admitted to the kubelet that\n// are not fully terminated. This is mapped to the \"desired state\" of the\n// kubelet - what pods should be running.\n//\n// WARNING: Currently this list does not include pods that have been force\n// deleted but may still be terminating, which means resources assigned to\n// those pods during admission may still be in use. See\n// https://github.com/kubernetes/kubernetes/issues/104824\nfunc (kl *Kubelet) GetActivePods() []*v1.Pod {\n\tallPods := kl.podManager.GetPods()\n\tactivePods := kl.filterOutInactivePods(allPods)\n\treturn activePods\n}","line":{"from":97,"to":109}} {"id":100006796,"name":"makeBlockVolumes","signature":"func (kl *Kubelet) makeBlockVolumes(pod *v1.Pod, container *v1.Container, podVolumes kubecontainer.VolumeMap, blkutil volumepathhandler.BlockVolumePathHandler) ([]kubecontainer.DeviceInfo, error)","file":"pkg/kubelet/kubelet_pods.go","code":"// makeBlockVolumes maps the raw block devices specified in the path of the container\n// Experimental\nfunc (kl *Kubelet) makeBlockVolumes(pod *v1.Pod, container *v1.Container, podVolumes kubecontainer.VolumeMap, blkutil volumepathhandler.BlockVolumePathHandler) ([]kubecontainer.DeviceInfo, error) {\n\tvar devices []kubecontainer.DeviceInfo\n\tfor _, device := range container.VolumeDevices {\n\t\t// check path is absolute\n\t\tif !filepath.IsAbs(device.DevicePath) {\n\t\t\treturn nil, fmt.Errorf(\"error DevicePath `%s` must be an absolute path\", device.DevicePath)\n\t\t}\n\t\tvol, ok := podVolumes[device.Name]\n\t\tif !ok || vol.BlockVolumeMapper == nil {\n\t\t\tklog.ErrorS(nil, \"Block volume cannot be satisfied for container, because the volume is missing or the volume mapper is nil\", \"containerName\", container.Name, \"device\", device)\n\t\t\treturn nil, fmt.Errorf(\"cannot find volume %q to pass into container %q\", device.Name, container.Name)\n\t\t}\n\t\t// Get a symbolic link associated to a block device under pod device path\n\t\tdirPath, volName := vol.BlockVolumeMapper.GetPodDeviceMapPath()\n\t\tsymlinkPath := filepath.Join(dirPath, volName)\n\t\tif islinkExist, checkErr := blkutil.IsSymlinkExist(symlinkPath); checkErr != nil {\n\t\t\treturn nil, checkErr\n\t\t} else if islinkExist {\n\t\t\t// Check readOnly in PVCVolumeSource and set read only permission if it's true.\n\t\t\tpermission := \"mrw\"\n\t\t\tif vol.ReadOnly {\n\t\t\t\tpermission = \"r\"\n\t\t\t}\n\t\t\tklog.V(4).InfoS(\"Device will be attached to container in the corresponding path on host\", \"containerName\", container.Name, \"path\", symlinkPath)\n\t\t\tdevices = append(devices, kubecontainer.DeviceInfo{PathOnHost: symlinkPath, PathInContainer: device.DevicePath, Permissions: permission})\n\t\t}\n\t}\n\n\treturn devices, nil\n}","line":{"from":111,"to":142}} {"id":100006797,"name":"shouldMountHostsFile","signature":"func shouldMountHostsFile(pod *v1.Pod, podIPs []string) bool","file":"pkg/kubelet/kubelet_pods.go","code":"// shouldMountHostsFile checks if the nodes /etc/hosts should be mounted\n// Kubernetes only mounts on /etc/hosts if:\n// - container is not an infrastructure (pause) container\n// - container is not already mounting on /etc/hosts\n// Kubernetes will not mount /etc/hosts if:\n// - when the Pod sandbox is being created, its IP is still unknown. Hence, PodIP will not have been set.\n// - Windows pod contains a hostProcess container\nfunc shouldMountHostsFile(pod *v1.Pod, podIPs []string) bool {\n\tshouldMount := len(podIPs) \u003e 0\n\tif runtime.GOOS == \"windows\" {\n\t\treturn shouldMount \u0026\u0026 !kubecontainer.HasWindowsHostProcessContainer(pod)\n\t}\n\treturn shouldMount\n}","line":{"from":144,"to":157}} {"id":100006798,"name":"makeMounts","signature":"func makeMounts(pod *v1.Pod, podDir string, container *v1.Container, hostName, hostDomain string, podIPs []string, podVolumes kubecontainer.VolumeMap, hu hostutil.HostUtils, subpather subpath.Interface, expandEnvs []kubecontainer.EnvVar) ([]kubecontainer.Mount, func(), error)","file":"pkg/kubelet/kubelet_pods.go","code":"// makeMounts determines the mount points for the given container.\nfunc makeMounts(pod *v1.Pod, podDir string, container *v1.Container, hostName, hostDomain string, podIPs []string, podVolumes kubecontainer.VolumeMap, hu hostutil.HostUtils, subpather subpath.Interface, expandEnvs []kubecontainer.EnvVar) ([]kubecontainer.Mount, func(), error) {\n\tmountEtcHostsFile := shouldMountHostsFile(pod, podIPs)\n\tklog.V(3).InfoS(\"Creating hosts mount for container\", \"pod\", klog.KObj(pod), \"containerName\", container.Name, \"podIPs\", podIPs, \"path\", mountEtcHostsFile)\n\tmounts := []kubecontainer.Mount{}\n\tvar cleanupAction func()\n\tfor i, mount := range container.VolumeMounts {\n\t\t// do not mount /etc/hosts if container is already mounting on the path\n\t\tmountEtcHostsFile = mountEtcHostsFile \u0026\u0026 (mount.MountPath != etcHostsPath)\n\t\tvol, ok := podVolumes[mount.Name]\n\t\tif !ok || vol.Mounter == nil {\n\t\t\tklog.ErrorS(nil, \"Mount cannot be satisfied for the container, because the volume is missing or the volume mounter (vol.Mounter) is nil\",\n\t\t\t\t\"containerName\", container.Name, \"ok\", ok, \"volumeMounter\", mount)\n\t\t\treturn nil, cleanupAction, fmt.Errorf(\"cannot find volume %q to mount into container %q\", mount.Name, container.Name)\n\t\t}\n\n\t\trelabelVolume := false\n\t\t// If the volume supports SELinux and it has not been\n\t\t// relabeled already and it is not a read-only volume,\n\t\t// relabel it and mark it as labeled\n\t\tif vol.Mounter.GetAttributes().Managed \u0026\u0026 vol.Mounter.GetAttributes().SELinuxRelabel \u0026\u0026 !vol.SELinuxLabeled {\n\t\t\tvol.SELinuxLabeled = true\n\t\t\trelabelVolume = true\n\t\t}\n\t\thostPath, err := volumeutil.GetPath(vol.Mounter)\n\t\tif err != nil {\n\t\t\treturn nil, cleanupAction, err\n\t\t}\n\n\t\tsubPath := mount.SubPath\n\t\tif mount.SubPathExpr != \"\" {\n\t\t\tsubPath, err = kubecontainer.ExpandContainerVolumeMounts(mount, expandEnvs)\n\n\t\t\tif err != nil {\n\t\t\t\treturn nil, cleanupAction, err\n\t\t\t}\n\t\t}\n\n\t\tif subPath != \"\" {\n\t\t\tif filepath.IsAbs(subPath) {\n\t\t\t\treturn nil, cleanupAction, fmt.Errorf(\"error SubPath `%s` must not be an absolute path\", subPath)\n\t\t\t}\n\n\t\t\terr = volumevalidation.ValidatePathNoBacksteps(subPath)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, cleanupAction, fmt.Errorf(\"unable to provision SubPath `%s`: %v\", subPath, err)\n\t\t\t}\n\n\t\t\tvolumePath := hostPath\n\t\t\thostPath = filepath.Join(volumePath, subPath)\n\n\t\t\tif subPathExists, err := hu.PathExists(hostPath); err != nil {\n\t\t\t\tklog.ErrorS(nil, \"Could not determine if subPath exists, will not attempt to change its permissions\", \"path\", hostPath)\n\t\t\t} else if !subPathExists {\n\t\t\t\t// Create the sub path now because if it's auto-created later when referenced, it may have an\n\t\t\t\t// incorrect ownership and mode. For example, the sub path directory must have at least g+rwx\n\t\t\t\t// when the pod specifies an fsGroup, and if the directory is not created here, Docker will\n\t\t\t\t// later auto-create it with the incorrect mode 0750\n\t\t\t\t// Make extra care not to escape the volume!\n\t\t\t\tperm, err := hu.GetMode(volumePath)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, cleanupAction, err\n\t\t\t\t}\n\t\t\t\tif err := subpather.SafeMakeDir(subPath, volumePath, perm); err != nil {\n\t\t\t\t\t// Don't pass detailed error back to the user because it could give information about host filesystem\n\t\t\t\t\tklog.ErrorS(err, \"Failed to create subPath directory for volumeMount of the container\", \"containerName\", container.Name, \"volumeMountName\", mount.Name)\n\t\t\t\t\treturn nil, cleanupAction, fmt.Errorf(\"failed to create subPath directory for volumeMount %q of container %q\", mount.Name, container.Name)\n\t\t\t\t}\n\t\t\t}\n\t\t\thostPath, cleanupAction, err = subpather.PrepareSafeSubpath(subpath.Subpath{\n\t\t\t\tVolumeMountIndex: i,\n\t\t\t\tPath: hostPath,\n\t\t\t\tVolumeName: vol.InnerVolumeSpecName,\n\t\t\t\tVolumePath: volumePath,\n\t\t\t\tPodDir: podDir,\n\t\t\t\tContainerName: container.Name,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\t// Don't pass detailed error back to the user because it could give information about host filesystem\n\t\t\t\tklog.ErrorS(err, \"Failed to prepare subPath for volumeMount of the container\", \"containerName\", container.Name, \"volumeMountName\", mount.Name)\n\t\t\t\treturn nil, cleanupAction, fmt.Errorf(\"failed to prepare subPath for volumeMount %q of container %q\", mount.Name, container.Name)\n\t\t\t}\n\t\t}\n\n\t\t// Docker Volume Mounts fail on Windows if it is not of the form C:/\n\t\tif volumeutil.IsWindowsLocalPath(runtime.GOOS, hostPath) {\n\t\t\thostPath = volumeutil.MakeAbsolutePath(runtime.GOOS, hostPath)\n\t\t}\n\n\t\tcontainerPath := mount.MountPath\n\t\t// IsAbs returns false for UNC path/SMB shares/named pipes in Windows. So check for those specifically and skip MakeAbsolutePath\n\t\tif !volumeutil.IsWindowsUNCPath(runtime.GOOS, containerPath) \u0026\u0026 !filepath.IsAbs(containerPath) {\n\t\t\tcontainerPath = volumeutil.MakeAbsolutePath(runtime.GOOS, containerPath)\n\t\t}\n\n\t\tpropagation, err := translateMountPropagation(mount.MountPropagation)\n\t\tif err != nil {\n\t\t\treturn nil, cleanupAction, err\n\t\t}\n\t\tklog.V(5).InfoS(\"Mount has propagation\", \"pod\", klog.KObj(pod), \"containerName\", container.Name, \"volumeMountName\", mount.Name, \"propagation\", propagation)\n\t\tmustMountRO := vol.Mounter.GetAttributes().ReadOnly\n\n\t\tmounts = append(mounts, kubecontainer.Mount{\n\t\t\tName: mount.Name,\n\t\t\tContainerPath: containerPath,\n\t\t\tHostPath: hostPath,\n\t\t\tReadOnly: mount.ReadOnly || mustMountRO,\n\t\t\tSELinuxRelabel: relabelVolume,\n\t\t\tPropagation: propagation,\n\t\t})\n\t}\n\tif mountEtcHostsFile {\n\t\thostAliases := pod.Spec.HostAliases\n\t\thostsMount, err := makeHostsMount(podDir, podIPs, hostName, hostDomain, hostAliases, pod.Spec.HostNetwork)\n\t\tif err != nil {\n\t\t\treturn nil, cleanupAction, err\n\t\t}\n\t\tmounts = append(mounts, *hostsMount)\n\t}\n\treturn mounts, cleanupAction, nil\n}","line":{"from":159,"to":279}} {"id":100006799,"name":"translateMountPropagation","signature":"func translateMountPropagation(mountMode *v1.MountPropagationMode) (runtimeapi.MountPropagation, error)","file":"pkg/kubelet/kubelet_pods.go","code":"// translateMountPropagation transforms v1.MountPropagationMode to\n// runtimeapi.MountPropagation.\nfunc translateMountPropagation(mountMode *v1.MountPropagationMode) (runtimeapi.MountPropagation, error) {\n\tif runtime.GOOS == \"windows\" {\n\t\t// Windows containers doesn't support mount propagation, use private for it.\n\t\t// Refer https://docs.docker.com/storage/bind-mounts/#configure-bind-propagation.\n\t\treturn runtimeapi.MountPropagation_PROPAGATION_PRIVATE, nil\n\t}\n\n\tswitch {\n\tcase mountMode == nil:\n\t\t// PRIVATE is the default\n\t\treturn runtimeapi.MountPropagation_PROPAGATION_PRIVATE, nil\n\tcase *mountMode == v1.MountPropagationHostToContainer:\n\t\treturn runtimeapi.MountPropagation_PROPAGATION_HOST_TO_CONTAINER, nil\n\tcase *mountMode == v1.MountPropagationBidirectional:\n\t\treturn runtimeapi.MountPropagation_PROPAGATION_BIDIRECTIONAL, nil\n\tcase *mountMode == v1.MountPropagationNone:\n\t\treturn runtimeapi.MountPropagation_PROPAGATION_PRIVATE, nil\n\tdefault:\n\t\treturn 0, fmt.Errorf(\"invalid MountPropagation mode: %q\", *mountMode)\n\t}\n}","line":{"from":281,"to":303}} {"id":100006800,"name":"getEtcHostsPath","signature":"func getEtcHostsPath(podDir string) string","file":"pkg/kubelet/kubelet_pods.go","code":"// getEtcHostsPath returns the full host-side path to a pod's generated /etc/hosts file\nfunc getEtcHostsPath(podDir string) string {\n\thostsFilePath := filepath.Join(podDir, \"etc-hosts\")\n\t// Volume Mounts fail on Windows if it is not of the form C:/\n\treturn volumeutil.MakeAbsolutePath(runtime.GOOS, hostsFilePath)\n}","line":{"from":305,"to":310}} {"id":100006801,"name":"makeHostsMount","signature":"func makeHostsMount(podDir string, podIPs []string, hostName, hostDomainName string, hostAliases []v1.HostAlias, useHostNetwork bool) (*kubecontainer.Mount, error)","file":"pkg/kubelet/kubelet_pods.go","code":"// makeHostsMount makes the mountpoint for the hosts file that the containers\n// in a pod are injected with. podIPs is provided instead of podIP as podIPs\n// are present even if dual-stack feature flag is not enabled.\nfunc makeHostsMount(podDir string, podIPs []string, hostName, hostDomainName string, hostAliases []v1.HostAlias, useHostNetwork bool) (*kubecontainer.Mount, error) {\n\thostsFilePath := getEtcHostsPath(podDir)\n\tif err := ensureHostsFile(hostsFilePath, podIPs, hostName, hostDomainName, hostAliases, useHostNetwork); err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026kubecontainer.Mount{\n\t\tName: \"k8s-managed-etc-hosts\",\n\t\tContainerPath: etcHostsPath,\n\t\tHostPath: hostsFilePath,\n\t\tReadOnly: false,\n\t\tSELinuxRelabel: true,\n\t}, nil\n}","line":{"from":312,"to":327}} {"id":100006802,"name":"ensureHostsFile","signature":"func ensureHostsFile(fileName string, hostIPs []string, hostName, hostDomainName string, hostAliases []v1.HostAlias, useHostNetwork bool) error","file":"pkg/kubelet/kubelet_pods.go","code":"// ensureHostsFile ensures that the given host file has an up-to-date ip, host\n// name, and domain name.\nfunc ensureHostsFile(fileName string, hostIPs []string, hostName, hostDomainName string, hostAliases []v1.HostAlias, useHostNetwork bool) error {\n\tvar hostsFileContent []byte\n\tvar err error\n\n\tif useHostNetwork {\n\t\t// if Pod is using host network, read hosts file from the node's filesystem.\n\t\t// `etcHostsPath` references the location of the hosts file on the node.\n\t\t// `/etc/hosts` for *nix systems.\n\t\thostsFileContent, err = nodeHostsFileContent(etcHostsPath, hostAliases)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t// if Pod is not using host network, create a managed hosts file with Pod IP and other information.\n\t\thostsFileContent = managedHostsFileContent(hostIPs, hostName, hostDomainName, hostAliases)\n\t}\n\n\treturn os.WriteFile(fileName, hostsFileContent, 0644)\n}","line":{"from":329,"to":349}} {"id":100006803,"name":"nodeHostsFileContent","signature":"func nodeHostsFileContent(hostsFilePath string, hostAliases []v1.HostAlias) ([]byte, error)","file":"pkg/kubelet/kubelet_pods.go","code":"// nodeHostsFileContent reads the content of node's hosts file.\nfunc nodeHostsFileContent(hostsFilePath string, hostAliases []v1.HostAlias) ([]byte, error) {\n\thostsFileContent, err := os.ReadFile(hostsFilePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(managedHostsHeaderWithHostNetwork)\n\tbuffer.Write(hostsFileContent)\n\tbuffer.Write(hostsEntriesFromHostAliases(hostAliases))\n\treturn buffer.Bytes(), nil\n}","line":{"from":351,"to":362}} {"id":100006804,"name":"managedHostsFileContent","signature":"func managedHostsFileContent(hostIPs []string, hostName, hostDomainName string, hostAliases []v1.HostAlias) []byte","file":"pkg/kubelet/kubelet_pods.go","code":"// managedHostsFileContent generates the content of the managed etc hosts based on Pod IPs and other\n// information.\nfunc managedHostsFileContent(hostIPs []string, hostName, hostDomainName string, hostAliases []v1.HostAlias) []byte {\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(managedHostsHeader)\n\tbuffer.WriteString(\"127.0.0.1\\tlocalhost\\n\") // ipv4 localhost\n\tbuffer.WriteString(\"::1\\tlocalhost ip6-localhost ip6-loopback\\n\") // ipv6 localhost\n\tbuffer.WriteString(\"fe00::0\\tip6-localnet\\n\")\n\tbuffer.WriteString(\"fe00::0\\tip6-mcastprefix\\n\")\n\tbuffer.WriteString(\"fe00::1\\tip6-allnodes\\n\")\n\tbuffer.WriteString(\"fe00::2\\tip6-allrouters\\n\")\n\tif len(hostDomainName) \u003e 0 {\n\t\t// host entry generated for all IPs in podIPs\n\t\t// podIPs field is populated for clusters even\n\t\t// dual-stack feature flag is not enabled.\n\t\tfor _, hostIP := range hostIPs {\n\t\t\tbuffer.WriteString(fmt.Sprintf(\"%s\\t%s.%s\\t%s\\n\", hostIP, hostName, hostDomainName, hostName))\n\t\t}\n\t} else {\n\t\tfor _, hostIP := range hostIPs {\n\t\t\tbuffer.WriteString(fmt.Sprintf(\"%s\\t%s\\n\", hostIP, hostName))\n\t\t}\n\t}\n\tbuffer.Write(hostsEntriesFromHostAliases(hostAliases))\n\treturn buffer.Bytes()\n}","line":{"from":364,"to":389}} {"id":100006805,"name":"hostsEntriesFromHostAliases","signature":"func hostsEntriesFromHostAliases(hostAliases []v1.HostAlias) []byte","file":"pkg/kubelet/kubelet_pods.go","code":"func hostsEntriesFromHostAliases(hostAliases []v1.HostAlias) []byte {\n\tif len(hostAliases) == 0 {\n\t\treturn []byte{}\n\t}\n\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"\\n\")\n\tbuffer.WriteString(\"# Entries added by HostAliases.\\n\")\n\t// for each IP, write all aliases onto single line in hosts file\n\tfor _, hostAlias := range hostAliases {\n\t\tbuffer.WriteString(fmt.Sprintf(\"%s\\t%s\\n\", hostAlias.IP, strings.Join(hostAlias.Hostnames, \"\\t\")))\n\t}\n\treturn buffer.Bytes()\n}","line":{"from":391,"to":404}} {"id":100006806,"name":"truncatePodHostnameIfNeeded","signature":"func truncatePodHostnameIfNeeded(podName, hostname string) (string, error)","file":"pkg/kubelet/kubelet_pods.go","code":"// truncatePodHostnameIfNeeded truncates the pod hostname if it's longer than 63 chars.\nfunc truncatePodHostnameIfNeeded(podName, hostname string) (string, error) {\n\t// Cap hostname at 63 chars (specification is 64bytes which is 63 chars and the null terminating char).\n\tconst hostnameMaxLen = 63\n\tif len(hostname) \u003c= hostnameMaxLen {\n\t\treturn hostname, nil\n\t}\n\ttruncated := hostname[:hostnameMaxLen]\n\tklog.ErrorS(nil, \"Hostname for pod was too long, truncated it\", \"podName\", podName, \"hostnameMaxLen\", hostnameMaxLen, \"truncatedHostname\", truncated)\n\t// hostname should not end with '-' or '.'\n\ttruncated = strings.TrimRight(truncated, \"-.\")\n\tif len(truncated) == 0 {\n\t\t// This should never happen.\n\t\treturn \"\", fmt.Errorf(\"hostname for pod %q was invalid: %q\", podName, hostname)\n\t}\n\treturn truncated, nil\n}","line":{"from":406,"to":422}} {"id":100006807,"name":"GetOrCreateUserNamespaceMappings","signature":"func (kl *Kubelet) GetOrCreateUserNamespaceMappings(pod *v1.Pod) (*runtimeapi.UserNamespace, error)","file":"pkg/kubelet/kubelet_pods.go","code":"// GetOrCreateUserNamespaceMappings returns the configuration for the sandbox user namespace\nfunc (kl *Kubelet) GetOrCreateUserNamespaceMappings(pod *v1.Pod) (*runtimeapi.UserNamespace, error) {\n\treturn kl.usernsManager.GetOrCreateUserNamespaceMappings(pod)\n}","line":{"from":424,"to":427}} {"id":100006808,"name":"GeneratePodHostNameAndDomain","signature":"func (kl *Kubelet) GeneratePodHostNameAndDomain(pod *v1.Pod) (string, string, error)","file":"pkg/kubelet/kubelet_pods.go","code":"// GeneratePodHostNameAndDomain creates a hostname and domain name for a pod,\n// given that pod's spec and annotations or returns an error.\nfunc (kl *Kubelet) GeneratePodHostNameAndDomain(pod *v1.Pod) (string, string, error) {\n\tclusterDomain := kl.dnsConfigurer.ClusterDomain\n\n\thostname := pod.Name\n\tif len(pod.Spec.Hostname) \u003e 0 {\n\t\tif msgs := utilvalidation.IsDNS1123Label(pod.Spec.Hostname); len(msgs) != 0 {\n\t\t\treturn \"\", \"\", fmt.Errorf(\"pod Hostname %q is not a valid DNS label: %s\", pod.Spec.Hostname, strings.Join(msgs, \";\"))\n\t\t}\n\t\thostname = pod.Spec.Hostname\n\t}\n\n\thostname, err := truncatePodHostnameIfNeeded(pod.Name, hostname)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\thostDomain := \"\"\n\tif len(pod.Spec.Subdomain) \u003e 0 {\n\t\tif msgs := utilvalidation.IsDNS1123Label(pod.Spec.Subdomain); len(msgs) != 0 {\n\t\t\treturn \"\", \"\", fmt.Errorf(\"pod Subdomain %q is not a valid DNS label: %s\", pod.Spec.Subdomain, strings.Join(msgs, \";\"))\n\t\t}\n\t\thostDomain = fmt.Sprintf(\"%s.%s.svc.%s\", pod.Spec.Subdomain, pod.Namespace, clusterDomain)\n\t}\n\n\treturn hostname, hostDomain, nil\n}","line":{"from":429,"to":456}} {"id":100006809,"name":"GetPodCgroupParent","signature":"func (kl *Kubelet) GetPodCgroupParent(pod *v1.Pod) string","file":"pkg/kubelet/kubelet_pods.go","code":"// GetPodCgroupParent gets pod cgroup parent from container manager.\nfunc (kl *Kubelet) GetPodCgroupParent(pod *v1.Pod) string {\n\tpcm := kl.containerManager.NewPodContainerManager()\n\t_, cgroupParent := pcm.GetPodContainerName(pod)\n\treturn cgroupParent\n}","line":{"from":458,"to":463}} {"id":100006810,"name":"GenerateRunContainerOptions","signature":"func (kl *Kubelet) GenerateRunContainerOptions(ctx context.Context, pod *v1.Pod, container *v1.Container, podIP string, podIPs []string) (*kubecontainer.RunContainerOptions, func(), error)","file":"pkg/kubelet/kubelet_pods.go","code":"// GenerateRunContainerOptions generates the RunContainerOptions, which can be used by\n// the container runtime to set parameters for launching a container.\nfunc (kl *Kubelet) GenerateRunContainerOptions(ctx context.Context, pod *v1.Pod, container *v1.Container, podIP string, podIPs []string) (*kubecontainer.RunContainerOptions, func(), error) {\n\topts, err := kl.containerManager.GetResources(pod, container)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\t// The value of hostname is the short host name and it is sent to makeMounts to create /etc/hosts file.\n\thostname, hostDomainName, err := kl.GeneratePodHostNameAndDomain(pod)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\t// nodename will be equals to hostname if SetHostnameAsFQDN is nil or false. If SetHostnameFQDN\n\t// is true and hostDomainName is defined, nodename will be the FQDN (hostname.hostDomainName)\n\tnodename, err := util.GetNodenameForKernel(hostname, hostDomainName, pod.Spec.SetHostnameAsFQDN)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\topts.Hostname = nodename\n\tpodName := volumeutil.GetUniquePodName(pod)\n\tvolumes := kl.volumeManager.GetMountedVolumesForPod(podName)\n\n\tblkutil := volumepathhandler.NewBlockVolumePathHandler()\n\tblkVolumes, err := kl.makeBlockVolumes(pod, container, volumes, blkutil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\topts.Devices = append(opts.Devices, blkVolumes...)\n\n\tenvs, err := kl.makeEnvironmentVariables(pod, container, podIP, podIPs)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\topts.Envs = append(opts.Envs, envs...)\n\n\t// only podIPs is sent to makeMounts, as podIPs is populated even if dual-stack feature flag is not enabled.\n\tmounts, cleanupAction, err := makeMounts(pod, kl.getPodDir(pod.UID), container, hostname, hostDomainName, podIPs, volumes, kl.hostutil, kl.subpather, opts.Envs)\n\tif err != nil {\n\t\treturn nil, cleanupAction, err\n\t}\n\topts.Mounts = append(opts.Mounts, mounts...)\n\n\t// adding TerminationMessagePath on Windows is only allowed if ContainerD is used. Individual files cannot\n\t// be mounted as volumes using Docker for Windows.\n\tif len(container.TerminationMessagePath) != 0 {\n\t\tp := kl.getPodContainerDir(pod.UID, container.Name)\n\t\tif err := os.MkdirAll(p, 0750); err != nil {\n\t\t\tklog.ErrorS(err, \"Error on creating dir\", \"path\", p)\n\t\t} else {\n\t\t\topts.PodContainerDir = p\n\t\t}\n\t}\n\n\t// only do this check if the experimental behavior is enabled, otherwise allow it to default to false\n\tif kl.experimentalHostUserNamespaceDefaulting {\n\t\topts.EnableHostUserNamespace = kl.enableHostUserNamespace(ctx, pod)\n\t}\n\n\treturn opts, cleanupAction, nil\n}","line":{"from":465,"to":524}} {"id":100006811,"name":"getServiceEnvVarMap","signature":"func (kl *Kubelet) getServiceEnvVarMap(ns string, enableServiceLinks bool) (map[string]string, error)","file":"pkg/kubelet/kubelet_pods.go","code":"// getServiceEnvVarMap makes a map[string]string of env vars for services a\n// pod in namespace ns should see.\nfunc (kl *Kubelet) getServiceEnvVarMap(ns string, enableServiceLinks bool) (map[string]string, error) {\n\tvar (\n\t\tserviceMap = make(map[string]*v1.Service)\n\t\tm = make(map[string]string)\n\t)\n\n\t// Get all service resources from the master (via a cache),\n\t// and populate them into service environment variables.\n\tif kl.serviceLister == nil {\n\t\t// Kubelets without masters (e.g. plain GCE ContainerVM) don't set env vars.\n\t\treturn m, nil\n\t}\n\tservices, err := kl.serviceLister.List(labels.Everything())\n\tif err != nil {\n\t\treturn m, fmt.Errorf(\"failed to list services when setting up env vars\")\n\t}\n\n\t// project the services in namespace ns onto the master services\n\tfor i := range services {\n\t\tservice := services[i]\n\t\t// ignore services where ClusterIP is \"None\" or empty\n\t\tif !v1helper.IsServiceIPSet(service) {\n\t\t\tcontinue\n\t\t}\n\t\tserviceName := service.Name\n\n\t\t// We always want to add environment variabled for master services\n\t\t// from the default namespace, even if enableServiceLinks is false.\n\t\t// We also add environment variables for other services in the same\n\t\t// namespace, if enableServiceLinks is true.\n\t\tif service.Namespace == metav1.NamespaceDefault \u0026\u0026 masterServices.Has(serviceName) {\n\t\t\tif _, exists := serviceMap[serviceName]; !exists {\n\t\t\t\tserviceMap[serviceName] = service\n\t\t\t}\n\t\t} else if service.Namespace == ns \u0026\u0026 enableServiceLinks {\n\t\t\tserviceMap[serviceName] = service\n\t\t}\n\t}\n\n\tmappedServices := []*v1.Service{}\n\tfor key := range serviceMap {\n\t\tmappedServices = append(mappedServices, serviceMap[key])\n\t}\n\n\tfor _, e := range envvars.FromServices(mappedServices) {\n\t\tm[e.Name] = e.Value\n\t}\n\treturn m, nil\n}","line":{"from":528,"to":578}} {"id":100006812,"name":"makeEnvironmentVariables","signature":"func (kl *Kubelet) makeEnvironmentVariables(pod *v1.Pod, container *v1.Container, podIP string, podIPs []string) ([]kubecontainer.EnvVar, error)","file":"pkg/kubelet/kubelet_pods.go","code":"// Make the environment variables for a pod in the given namespace.\nfunc (kl *Kubelet) makeEnvironmentVariables(pod *v1.Pod, container *v1.Container, podIP string, podIPs []string) ([]kubecontainer.EnvVar, error) {\n\tif pod.Spec.EnableServiceLinks == nil {\n\t\treturn nil, fmt.Errorf(\"nil pod.spec.enableServiceLinks encountered, cannot construct envvars\")\n\t}\n\n\t// If the pod originates from the kube-api, when we know that the kube-apiserver is responding and the kubelet's credentials are valid.\n\t// Knowing this, it is reasonable to wait until the service lister has synchronized at least once before attempting to build\n\t// a service env var map. This doesn't present the race below from happening entirely, but it does prevent the \"obvious\"\n\t// failure case of services simply not having completed a list operation that can reasonably be expected to succeed.\n\t// One common case this prevents is a kubelet restart reading pods before services and some pod not having the\n\t// KUBERNETES_SERVICE_HOST injected because we didn't wait a short time for services to sync before proceeding.\n\t// The KUBERNETES_SERVICE_HOST link is special because it is unconditionally injected into pods and is read by the\n\t// in-cluster-config for pod clients\n\tif !kubetypes.IsStaticPod(pod) \u0026\u0026 !kl.serviceHasSynced() {\n\t\treturn nil, fmt.Errorf(\"services have not yet been read at least once, cannot construct envvars\")\n\t}\n\n\tvar result []kubecontainer.EnvVar\n\t// Note: These are added to the docker Config, but are not included in the checksum computed\n\t// by kubecontainer.HashContainer(...). That way, we can still determine whether an\n\t// v1.Container is already running by its hash. (We don't want to restart a container just\n\t// because some service changed.)\n\t//\n\t// Note that there is a race between Kubelet seeing the pod and kubelet seeing the service.\n\t// To avoid this users can: (1) wait between starting a service and starting; or (2) detect\n\t// missing service env var and exit and be restarted; or (3) use DNS instead of env vars\n\t// and keep trying to resolve the DNS name of the service (recommended).\n\tserviceEnv, err := kl.getServiceEnvVarMap(pod.Namespace, *pod.Spec.EnableServiceLinks)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\n\tvar (\n\t\tconfigMaps = make(map[string]*v1.ConfigMap)\n\t\tsecrets = make(map[string]*v1.Secret)\n\t\ttmpEnv = make(map[string]string)\n\t)\n\n\t// Env will override EnvFrom variables.\n\t// Process EnvFrom first then allow Env to replace existing values.\n\tfor _, envFrom := range container.EnvFrom {\n\t\tswitch {\n\t\tcase envFrom.ConfigMapRef != nil:\n\t\t\tcm := envFrom.ConfigMapRef\n\t\t\tname := cm.Name\n\t\t\tconfigMap, ok := configMaps[name]\n\t\t\tif !ok {\n\t\t\t\tif kl.kubeClient == nil {\n\t\t\t\t\treturn result, fmt.Errorf(\"couldn't get configMap %v/%v, no kubeClient defined\", pod.Namespace, name)\n\t\t\t\t}\n\t\t\t\toptional := cm.Optional != nil \u0026\u0026 *cm.Optional\n\t\t\t\tconfigMap, err = kl.configMapManager.GetConfigMap(pod.Namespace, name)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif errors.IsNotFound(err) \u0026\u0026 optional {\n\t\t\t\t\t\t// ignore error when marked optional\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\treturn result, err\n\t\t\t\t}\n\t\t\t\tconfigMaps[name] = configMap\n\t\t\t}\n\n\t\t\tinvalidKeys := []string{}\n\t\t\tfor k, v := range configMap.Data {\n\t\t\t\tif len(envFrom.Prefix) \u003e 0 {\n\t\t\t\t\tk = envFrom.Prefix + k\n\t\t\t\t}\n\t\t\t\tif errMsgs := utilvalidation.IsEnvVarName(k); len(errMsgs) != 0 {\n\t\t\t\t\tinvalidKeys = append(invalidKeys, k)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\ttmpEnv[k] = v\n\t\t\t}\n\t\t\tif len(invalidKeys) \u003e 0 {\n\t\t\t\tsort.Strings(invalidKeys)\n\t\t\t\tkl.recorder.Eventf(pod, v1.EventTypeWarning, \"InvalidEnvironmentVariableNames\", \"Keys [%s] from the EnvFrom configMap %s/%s were skipped since they are considered invalid environment variable names.\", strings.Join(invalidKeys, \", \"), pod.Namespace, name)\n\t\t\t}\n\t\tcase envFrom.SecretRef != nil:\n\t\t\ts := envFrom.SecretRef\n\t\t\tname := s.Name\n\t\t\tsecret, ok := secrets[name]\n\t\t\tif !ok {\n\t\t\t\tif kl.kubeClient == nil {\n\t\t\t\t\treturn result, fmt.Errorf(\"couldn't get secret %v/%v, no kubeClient defined\", pod.Namespace, name)\n\t\t\t\t}\n\t\t\t\toptional := s.Optional != nil \u0026\u0026 *s.Optional\n\t\t\t\tsecret, err = kl.secretManager.GetSecret(pod.Namespace, name)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif errors.IsNotFound(err) \u0026\u0026 optional {\n\t\t\t\t\t\t// ignore error when marked optional\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\treturn result, err\n\t\t\t\t}\n\t\t\t\tsecrets[name] = secret\n\t\t\t}\n\n\t\t\tinvalidKeys := []string{}\n\t\t\tfor k, v := range secret.Data {\n\t\t\t\tif len(envFrom.Prefix) \u003e 0 {\n\t\t\t\t\tk = envFrom.Prefix + k\n\t\t\t\t}\n\t\t\t\tif errMsgs := utilvalidation.IsEnvVarName(k); len(errMsgs) != 0 {\n\t\t\t\t\tinvalidKeys = append(invalidKeys, k)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\ttmpEnv[k] = string(v)\n\t\t\t}\n\t\t\tif len(invalidKeys) \u003e 0 {\n\t\t\t\tsort.Strings(invalidKeys)\n\t\t\t\tkl.recorder.Eventf(pod, v1.EventTypeWarning, \"InvalidEnvironmentVariableNames\", \"Keys [%s] from the EnvFrom secret %s/%s were skipped since they are considered invalid environment variable names.\", strings.Join(invalidKeys, \", \"), pod.Namespace, name)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Determine the final values of variables:\n\t//\n\t// 1. Determine the final value of each variable:\n\t// a. If the variable's Value is set, expand the `$(var)` references to other\n\t// variables in the .Value field; the sources of variables are the declared\n\t// variables of the container and the service environment variables\n\t// b. If a source is defined for an environment variable, resolve the source\n\t// 2. Create the container's environment in the order variables are declared\n\t// 3. Add remaining service environment vars\n\tvar (\n\t\tmappingFunc = expansion.MappingFuncFor(tmpEnv, serviceEnv)\n\t)\n\tfor _, envVar := range container.Env {\n\t\truntimeVal := envVar.Value\n\t\tif runtimeVal != \"\" {\n\t\t\t// Step 1a: expand variable references\n\t\t\truntimeVal = expansion.Expand(runtimeVal, mappingFunc)\n\t\t} else if envVar.ValueFrom != nil {\n\t\t\t// Step 1b: resolve alternate env var sources\n\t\t\tswitch {\n\t\t\tcase envVar.ValueFrom.FieldRef != nil:\n\t\t\t\truntimeVal, err = kl.podFieldSelectorRuntimeValue(envVar.ValueFrom.FieldRef, pod, podIP, podIPs)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn result, err\n\t\t\t\t}\n\t\t\tcase envVar.ValueFrom.ResourceFieldRef != nil:\n\t\t\t\tdefaultedPod, defaultedContainer, err := kl.defaultPodLimitsForDownwardAPI(pod, container)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn result, err\n\t\t\t\t}\n\t\t\t\truntimeVal, err = containerResourceRuntimeValue(envVar.ValueFrom.ResourceFieldRef, defaultedPod, defaultedContainer)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn result, err\n\t\t\t\t}\n\t\t\tcase envVar.ValueFrom.ConfigMapKeyRef != nil:\n\t\t\t\tcm := envVar.ValueFrom.ConfigMapKeyRef\n\t\t\t\tname := cm.Name\n\t\t\t\tkey := cm.Key\n\t\t\t\toptional := cm.Optional != nil \u0026\u0026 *cm.Optional\n\t\t\t\tconfigMap, ok := configMaps[name]\n\t\t\t\tif !ok {\n\t\t\t\t\tif kl.kubeClient == nil {\n\t\t\t\t\t\treturn result, fmt.Errorf(\"couldn't get configMap %v/%v, no kubeClient defined\", pod.Namespace, name)\n\t\t\t\t\t}\n\t\t\t\t\tconfigMap, err = kl.configMapManager.GetConfigMap(pod.Namespace, name)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tif errors.IsNotFound(err) \u0026\u0026 optional {\n\t\t\t\t\t\t\t// ignore error when marked optional\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn result, err\n\t\t\t\t\t}\n\t\t\t\t\tconfigMaps[name] = configMap\n\t\t\t\t}\n\t\t\t\truntimeVal, ok = configMap.Data[key]\n\t\t\t\tif !ok {\n\t\t\t\t\tif optional {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\treturn result, fmt.Errorf(\"couldn't find key %v in ConfigMap %v/%v\", key, pod.Namespace, name)\n\t\t\t\t}\n\t\t\tcase envVar.ValueFrom.SecretKeyRef != nil:\n\t\t\t\ts := envVar.ValueFrom.SecretKeyRef\n\t\t\t\tname := s.Name\n\t\t\t\tkey := s.Key\n\t\t\t\toptional := s.Optional != nil \u0026\u0026 *s.Optional\n\t\t\t\tsecret, ok := secrets[name]\n\t\t\t\tif !ok {\n\t\t\t\t\tif kl.kubeClient == nil {\n\t\t\t\t\t\treturn result, fmt.Errorf(\"couldn't get secret %v/%v, no kubeClient defined\", pod.Namespace, name)\n\t\t\t\t\t}\n\t\t\t\t\tsecret, err = kl.secretManager.GetSecret(pod.Namespace, name)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tif errors.IsNotFound(err) \u0026\u0026 optional {\n\t\t\t\t\t\t\t// ignore error when marked optional\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn result, err\n\t\t\t\t\t}\n\t\t\t\t\tsecrets[name] = secret\n\t\t\t\t}\n\t\t\t\truntimeValBytes, ok := secret.Data[key]\n\t\t\t\tif !ok {\n\t\t\t\t\tif optional {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\treturn result, fmt.Errorf(\"couldn't find key %v in Secret %v/%v\", key, pod.Namespace, name)\n\t\t\t\t}\n\t\t\t\truntimeVal = string(runtimeValBytes)\n\t\t\t}\n\t\t}\n\n\t\ttmpEnv[envVar.Name] = runtimeVal\n\t}\n\n\t// Append the env vars\n\tfor k, v := range tmpEnv {\n\t\tresult = append(result, kubecontainer.EnvVar{Name: k, Value: v})\n\t}\n\n\t// Append remaining service env vars.\n\tfor k, v := range serviceEnv {\n\t\t// Accesses apiserver+Pods.\n\t\t// So, the master may set service env vars, or kubelet may. In case both are doing\n\t\t// it, we skip the key from the kubelet-generated ones so we don't have duplicate\n\t\t// env vars.\n\t\t// TODO: remove this next line once all platforms use apiserver+Pods.\n\t\tif _, present := tmpEnv[k]; !present {\n\t\t\tresult = append(result, kubecontainer.EnvVar{Name: k, Value: v})\n\t\t}\n\t}\n\treturn result, nil\n}","line":{"from":580,"to":808}} {"id":100006813,"name":"podFieldSelectorRuntimeValue","signature":"func (kl *Kubelet) podFieldSelectorRuntimeValue(fs *v1.ObjectFieldSelector, pod *v1.Pod, podIP string, podIPs []string) (string, error)","file":"pkg/kubelet/kubelet_pods.go","code":"// podFieldSelectorRuntimeValue returns the runtime value of the given\n// selector for a pod.\nfunc (kl *Kubelet) podFieldSelectorRuntimeValue(fs *v1.ObjectFieldSelector, pod *v1.Pod, podIP string, podIPs []string) (string, error) {\n\tinternalFieldPath, _, err := podshelper.ConvertDownwardAPIFieldLabel(fs.APIVersion, fs.FieldPath, \"\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// make podIPs order match node IP family preference #97979\n\tpodIPs = kl.sortPodIPs(podIPs)\n\tif len(podIPs) \u003e 0 {\n\t\tpodIP = podIPs[0]\n\t}\n\n\tswitch internalFieldPath {\n\tcase \"spec.nodeName\":\n\t\treturn pod.Spec.NodeName, nil\n\tcase \"spec.serviceAccountName\":\n\t\treturn pod.Spec.ServiceAccountName, nil\n\tcase \"status.hostIP\":\n\t\thostIPs, err := kl.getHostIPsAnyWay()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn hostIPs[0].String(), nil\n\tcase \"status.podIP\":\n\t\treturn podIP, nil\n\tcase \"status.podIPs\":\n\t\treturn strings.Join(podIPs, \",\"), nil\n\t}\n\treturn fieldpath.ExtractFieldPathAsString(pod, internalFieldPath)\n}","line":{"from":810,"to":841}} {"id":100006814,"name":"containerResourceRuntimeValue","signature":"func containerResourceRuntimeValue(fs *v1.ResourceFieldSelector, pod *v1.Pod, container *v1.Container) (string, error)","file":"pkg/kubelet/kubelet_pods.go","code":"// containerResourceRuntimeValue returns the value of the provided container resource\nfunc containerResourceRuntimeValue(fs *v1.ResourceFieldSelector, pod *v1.Pod, container *v1.Container) (string, error) {\n\tcontainerName := fs.ContainerName\n\tif len(containerName) == 0 {\n\t\treturn resource.ExtractContainerResourceValue(fs, container)\n\t}\n\treturn resource.ExtractResourceValueByContainerName(fs, pod, containerName)\n}","line":{"from":843,"to":850}} {"id":100006815,"name":"killPod","signature":"func (kl *Kubelet) killPod(ctx context.Context, pod *v1.Pod, p kubecontainer.Pod, gracePeriodOverride *int64) error","file":"pkg/kubelet/kubelet_pods.go","code":"// killPod instructs the container runtime to kill the pod. This method requires that\n// the pod status contains the result of the last syncPod, otherwise it may fail to\n// terminate newly created containers and sandboxes.\nfunc (kl *Kubelet) killPod(ctx context.Context, pod *v1.Pod, p kubecontainer.Pod, gracePeriodOverride *int64) error {\n\t// Call the container runtime KillPod method which stops all known running containers of the pod\n\tif err := kl.containerRuntime.KillPod(ctx, pod, p, gracePeriodOverride); err != nil {\n\t\treturn err\n\t}\n\tif err := kl.containerManager.UpdateQOSCgroups(); err != nil {\n\t\tklog.V(2).InfoS(\"Failed to update QoS cgroups while killing pod\", \"err\", err)\n\t}\n\treturn nil\n}","line":{"from":852,"to":864}} {"id":100006816,"name":"makePodDataDirs","signature":"func (kl *Kubelet) makePodDataDirs(pod *v1.Pod) error","file":"pkg/kubelet/kubelet_pods.go","code":"// makePodDataDirs creates the dirs for the pod datas.\nfunc (kl *Kubelet) makePodDataDirs(pod *v1.Pod) error {\n\tuid := pod.UID\n\tif err := os.MkdirAll(kl.getPodDir(uid), 0750); err != nil \u0026\u0026 !os.IsExist(err) {\n\t\treturn err\n\t}\n\tif err := os.MkdirAll(kl.getPodVolumesDir(uid), 0750); err != nil \u0026\u0026 !os.IsExist(err) {\n\t\treturn err\n\t}\n\tif err := os.MkdirAll(kl.getPodPluginsDir(uid), 0750); err != nil \u0026\u0026 !os.IsExist(err) {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":866,"to":879}} {"id":100006817,"name":"getPullSecretsForPod","signature":"func (kl *Kubelet) getPullSecretsForPod(pod *v1.Pod) []v1.Secret","file":"pkg/kubelet/kubelet_pods.go","code":"// getPullSecretsForPod inspects the Pod and retrieves the referenced pull\n// secrets.\nfunc (kl *Kubelet) getPullSecretsForPod(pod *v1.Pod) []v1.Secret {\n\tpullSecrets := []v1.Secret{}\n\n\tfor _, secretRef := range pod.Spec.ImagePullSecrets {\n\t\tif len(secretRef.Name) == 0 {\n\t\t\t// API validation permitted entries with empty names (https://issue.k8s.io/99454#issuecomment-787838112).\n\t\t\t// Ignore to avoid unnecessary warnings.\n\t\t\tcontinue\n\t\t}\n\t\tsecret, err := kl.secretManager.GetSecret(pod.Namespace, secretRef.Name)\n\t\tif err != nil {\n\t\t\tklog.InfoS(\"Unable to retrieve pull secret, the image pull may not succeed.\", \"pod\", klog.KObj(pod), \"secret\", klog.KObj(secret), \"err\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tpullSecrets = append(pullSecrets, *secret)\n\t}\n\n\treturn pullSecrets\n}","line":{"from":881,"to":902}} {"id":100006818,"name":"PodCouldHaveRunningContainers","signature":"func (kl *Kubelet) PodCouldHaveRunningContainers(pod *v1.Pod) bool","file":"pkg/kubelet/kubelet_pods.go","code":"// PodCouldHaveRunningContainers returns true if the pod with the given UID could still have running\n// containers. This returns false if the pod has not yet been started or the pod is unknown.\nfunc (kl *Kubelet) PodCouldHaveRunningContainers(pod *v1.Pod) bool {\n\tif kl.podWorkers.CouldHaveRunningContainers(pod.UID) {\n\t\treturn true\n\t}\n\n\t// Check if pod might need to unprepare resources before termination\n\t// NOTE: This is a temporary solution. This call is here to avoid changing\n\t// status manager and its tests.\n\t// TODO: extend PodDeletionSafetyProvider interface and implement it\n\t// in a separate Kubelet method.\n\tif utilfeature.DefaultFeatureGate.Enabled(features.DynamicResourceAllocation) {\n\t\tif kl.containerManager.PodMightNeedToUnprepareResources(pod.UID) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":904,"to":922}} {"id":100006819,"name":"PodIsFinished","signature":"func (kl *Kubelet) PodIsFinished(pod *v1.Pod) bool","file":"pkg/kubelet/kubelet_pods.go","code":"// PodIsFinished returns true if SyncTerminatedPod is finished, ie.\n// all required node-level resources that a pod was consuming have\n// been reclaimed by the kubelet.\nfunc (kl *Kubelet) PodIsFinished(pod *v1.Pod) bool {\n\treturn kl.podWorkers.ShouldPodBeFinished(pod.UID)\n}","line":{"from":924,"to":929}} {"id":100006820,"name":"filterOutInactivePods","signature":"func (kl *Kubelet) filterOutInactivePods(pods []*v1.Pod) []*v1.Pod","file":"pkg/kubelet/kubelet_pods.go","code":"// filterOutInactivePods returns pods that are not in a terminal phase\n// or are known to be fully terminated. This method should only be used\n// when the set of pods being filtered is upstream of the pod worker, i.e.\n// the pods the pod manager is aware of.\nfunc (kl *Kubelet) filterOutInactivePods(pods []*v1.Pod) []*v1.Pod {\n\tfilteredPods := make([]*v1.Pod, 0, len(pods))\n\tfor _, p := range pods {\n\t\t// if a pod is fully terminated by UID, it should be excluded from the\n\t\t// list of pods\n\t\tif kl.podWorkers.IsPodKnownTerminated(p.UID) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// terminal pods are considered inactive UNLESS they are actively terminating\n\t\tif kl.isAdmittedPodTerminal(p) \u0026\u0026 !kl.podWorkers.IsPodTerminationRequested(p.UID) {\n\t\t\tcontinue\n\t\t}\n\n\t\tfilteredPods = append(filteredPods, p)\n\t}\n\treturn filteredPods\n}","line":{"from":931,"to":952}} {"id":100006821,"name":"isAdmittedPodTerminal","signature":"func (kl *Kubelet) isAdmittedPodTerminal(pod *v1.Pod) bool","file":"pkg/kubelet/kubelet_pods.go","code":"// isAdmittedPodTerminal returns true if the provided config source pod is in\n// a terminal phase, or if the Kubelet has already indicated the pod has reached\n// a terminal phase but the config source has not accepted it yet. This method\n// should only be used within the pod configuration loops that notify the pod\n// worker, other components should treat the pod worker as authoritative.\nfunc (kl *Kubelet) isAdmittedPodTerminal(pod *v1.Pod) bool {\n\t// pods are considered inactive if the config source has observed a\n\t// terminal phase (if the Kubelet recorded that the pod reached a terminal\n\t// phase the pod should never be restarted)\n\tif pod.Status.Phase == v1.PodSucceeded || pod.Status.Phase == v1.PodFailed {\n\t\treturn true\n\t}\n\t// a pod that has been marked terminal within the Kubelet is considered\n\t// inactive (may have been rejected by Kubelet admision)\n\tif status, ok := kl.statusManager.GetPodStatus(pod.UID); ok {\n\t\tif status.Phase == v1.PodSucceeded || status.Phase == v1.PodFailed {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":954,"to":974}} {"id":100006822,"name":"removeOrphanedPodStatuses","signature":"func (kl *Kubelet) removeOrphanedPodStatuses(pods []*v1.Pod, mirrorPods []*v1.Pod)","file":"pkg/kubelet/kubelet_pods.go","code":"// removeOrphanedPodStatuses removes obsolete entries in podStatus where\n// the pod is no longer considered bound to this node.\nfunc (kl *Kubelet) removeOrphanedPodStatuses(pods []*v1.Pod, mirrorPods []*v1.Pod) {\n\tpodUIDs := make(map[types.UID]bool)\n\tfor _, pod := range pods {\n\t\tpodUIDs[pod.UID] = true\n\t}\n\tfor _, pod := range mirrorPods {\n\t\tpodUIDs[pod.UID] = true\n\t}\n\tkl.statusManager.RemoveOrphanedStatuses(podUIDs)\n}","line":{"from":976,"to":987}} {"id":100006823,"name":"deleteOrphanedMirrorPods","signature":"func (kl *Kubelet) deleteOrphanedMirrorPods()","file":"pkg/kubelet/kubelet_pods.go","code":"// deleteOrphanedMirrorPods checks whether pod killer has done with orphaned mirror pod.\n// If pod killing is done, podManager.DeleteMirrorPod() is called to delete mirror pod\n// from the API server\nfunc (kl *Kubelet) deleteOrphanedMirrorPods() {\n\tmirrorPods := kl.podManager.GetOrphanedMirrorPodNames()\n\tfor _, podFullname := range mirrorPods {\n\t\tif !kl.podWorkers.IsPodForMirrorPodTerminatingByFullName(podFullname) {\n\t\t\t_, err := kl.podManager.DeleteMirrorPod(podFullname, nil)\n\t\t\tif err != nil {\n\t\t\t\tklog.ErrorS(err, \"Encountered error when deleting mirror pod\", \"podName\", podFullname)\n\t\t\t} else {\n\t\t\t\tklog.V(3).InfoS(\"Deleted mirror pod\", \"podName\", podFullname)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":989,"to":1004}} {"id":100006824,"name":"HandlePodCleanups","signature":"func (kl *Kubelet) HandlePodCleanups(ctx context.Context) error","file":"pkg/kubelet/kubelet_pods.go","code":"// HandlePodCleanups performs a series of cleanup work, including terminating\n// pod workers, killing unwanted pods, and removing orphaned volumes/pod\n// directories. No config changes are sent to pod workers while this method\n// is executing which means no new pods can appear. After this method completes\n// the desired state of the kubelet should be reconciled with the actual state\n// in the pod worker and other pod-related components.\n//\n// This function is executed by the main sync loop, so it must execute quickly\n// and all nested calls should be asynchronous. Any slow reconciliation actions\n// should be performed by other components (like the volume manager). The duration\n// of this call is the minimum latency for static pods to be restarted if they\n// are updated with a fixed UID (most should use a dynamic UID), and no config\n// updates are delivered to the pod workers while this method is running.\nfunc (kl *Kubelet) HandlePodCleanups(ctx context.Context) error {\n\t// The kubelet lacks checkpointing, so we need to introspect the set of pods\n\t// in the cgroup tree prior to inspecting the set of pods in our pod manager.\n\t// this ensures our view of the cgroup tree does not mistakenly observe pods\n\t// that are added after the fact...\n\tvar (\n\t\tcgroupPods map[types.UID]cm.CgroupName\n\t\terr error\n\t)\n\tif kl.cgroupsPerQOS {\n\t\tpcm := kl.containerManager.NewPodContainerManager()\n\t\tcgroupPods, err = pcm.GetAllPodsFromCgroups()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get list of pods that still exist on cgroup mounts: %v\", err)\n\t\t}\n\t}\n\n\tallPods, mirrorPods := kl.podManager.GetPodsAndMirrorPods()\n\tactivePods := kl.filterOutInactivePods(allPods)\n\tallRegularPods, allStaticPods := splitPodsByStatic(allPods)\n\tactiveRegularPods, activeStaticPods := splitPodsByStatic(activePods)\n\tmetrics.DesiredPodCount.WithLabelValues(\"\").Set(float64(len(allRegularPods)))\n\tmetrics.DesiredPodCount.WithLabelValues(\"true\").Set(float64(len(allStaticPods)))\n\tmetrics.ActivePodCount.WithLabelValues(\"\").Set(float64(len(activeRegularPods)))\n\tmetrics.ActivePodCount.WithLabelValues(\"true\").Set(float64(len(activeStaticPods)))\n\tmetrics.MirrorPodCount.Set(float64(len(mirrorPods)))\n\n\t// Pod phase progresses monotonically. Once a pod has reached a final state,\n\t// it should never leave regardless of the restart policy. The statuses\n\t// of such pods should not be changed, and there is no need to sync them.\n\t// TODO: the logic here does not handle two cases:\n\t// 1. If the containers were removed immediately after they died, kubelet\n\t// may fail to generate correct statuses, let alone filtering correctly.\n\t// 2. If kubelet restarted before writing the terminated status for a pod\n\t// to the apiserver, it could still restart the terminated pod (even\n\t// though the pod was not considered terminated by the apiserver).\n\t// These two conditions could be alleviated by checkpointing kubelet.\n\n\t// Stop the workers for terminated pods not in the config source\n\tklog.V(3).InfoS(\"Clean up pod workers for terminated pods\")\n\tworkingPods := kl.podWorkers.SyncKnownPods(allPods)\n\n\t// Reconcile: At this point the pod workers have been pruned to the set of\n\t// desired pods. Pods that must be restarted due to UID reuse, or leftover\n\t// pods from previous runs, are not known to the pod worker.\n\n\tallPodsByUID := make(map[types.UID]*v1.Pod)\n\tfor _, pod := range allPods {\n\t\tallPodsByUID[pod.UID] = pod\n\t}\n\n\t// Identify the set of pods that have workers, which should be all pods\n\t// from config that are not terminated, as well as any terminating pods\n\t// that have already been removed from config. Pods that are terminating\n\t// will be added to possiblyRunningPods, to prevent overly aggressive\n\t// cleanup of pod cgroups.\n\tstringIfTrue := func(t bool) string {\n\t\tif t {\n\t\t\treturn \"true\"\n\t\t}\n\t\treturn \"\"\n\t}\n\trunningPods := make(map[types.UID]sets.Empty)\n\tpossiblyRunningPods := make(map[types.UID]sets.Empty)\n\tfor uid, sync := range workingPods {\n\t\tswitch sync.State {\n\t\tcase SyncPod:\n\t\t\trunningPods[uid] = struct{}{}\n\t\t\tpossiblyRunningPods[uid] = struct{}{}\n\t\tcase TerminatingPod:\n\t\t\tpossiblyRunningPods[uid] = struct{}{}\n\t\tdefault:\n\t\t}\n\t}\n\n\t// Retrieve the list of running containers from the runtime to perform cleanup.\n\t// We need the latest state to avoid delaying restarts of static pods that reuse\n\t// a UID.\n\tif err := kl.runtimeCache.ForceUpdateIfOlder(ctx, kl.clock.Now()); err != nil {\n\t\tklog.ErrorS(err, \"Error listing containers\")\n\t\treturn err\n\t}\n\trunningRuntimePods, err := kl.runtimeCache.GetPods(ctx)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Error listing containers\")\n\t\treturn err\n\t}\n\n\t// Stop probing pods that are not running\n\tklog.V(3).InfoS(\"Clean up probes for terminated pods\")\n\tkl.probeManager.CleanupPods(possiblyRunningPods)\n\n\t// Remove orphaned pod statuses not in the total list of known config pods\n\tklog.V(3).InfoS(\"Clean up orphaned pod statuses\")\n\tkl.removeOrphanedPodStatuses(allPods, mirrorPods)\n\n\t// Remove orphaned pod user namespace allocations (if any).\n\tklog.V(3).InfoS(\"Clean up orphaned pod user namespace allocations\")\n\tif err = kl.usernsManager.CleanupOrphanedPodUsernsAllocations(allPods, runningRuntimePods); err != nil {\n\t\tklog.ErrorS(err, \"Failed cleaning up orphaned pod user namespaces allocations\")\n\t}\n\n\t// Remove orphaned volumes from pods that are known not to have any\n\t// containers. Note that we pass all pods (including terminated pods) to\n\t// the function, so that we don't remove volumes associated with terminated\n\t// but not yet deleted pods.\n\t// TODO: this method could more aggressively cleanup terminated pods\n\t// in the future (volumes, mount dirs, logs, and containers could all be\n\t// better separated)\n\tklog.V(3).InfoS(\"Clean up orphaned pod directories\")\n\terr = kl.cleanupOrphanedPodDirs(allPods, runningRuntimePods)\n\tif err != nil {\n\t\t// We want all cleanup tasks to be run even if one of them failed. So\n\t\t// we just log an error here and continue other cleanup tasks.\n\t\t// This also applies to the other clean up tasks.\n\t\tklog.ErrorS(err, \"Failed cleaning up orphaned pod directories\")\n\t}\n\n\t// Remove any orphaned mirror pods (mirror pods are tracked by name via the\n\t// pod worker)\n\tklog.V(3).InfoS(\"Clean up orphaned mirror pods\")\n\tkl.deleteOrphanedMirrorPods()\n\n\t// At this point, the pod worker is aware of which pods are not desired (SyncKnownPods).\n\t// We now look through the set of active pods for those that the pod worker is not aware of\n\t// and deliver an update. The most common reason a pod is not known is because the pod was\n\t// deleted and recreated with the same UID while the pod worker was driving its lifecycle (very\n\t// very rare for API pods, common for static pods with fixed UIDs). Containers that may still\n\t// be running from a previous execution must be reconciled by the pod worker's sync method.\n\t// We must use active pods because that is the set of admitted pods (podManager includes pods\n\t// that will never be run, and statusManager tracks already rejected pods).\n\tvar restartCount, restartCountStatic int\n\tfor _, desiredPod := range activePods {\n\t\tif _, knownPod := workingPods[desiredPod.UID]; knownPod {\n\t\t\tcontinue\n\t\t}\n\n\t\tklog.V(3).InfoS(\"Pod will be restarted because it is in the desired set and not known to the pod workers (likely due to UID reuse)\", \"podUID\", desiredPod.UID)\n\t\tisStatic := kubetypes.IsStaticPod(desiredPod)\n\t\tmirrorPod, _ := kl.podManager.GetMirrorPodByPod(desiredPod)\n\t\tkl.podWorkers.UpdatePod(UpdatePodOptions{\n\t\t\tUpdateType: kubetypes.SyncPodCreate,\n\t\t\tPod: desiredPod,\n\t\t\tMirrorPod: mirrorPod,\n\t\t})\n\n\t\t// the desired pod is now known as well\n\t\tworkingPods[desiredPod.UID] = PodWorkerSync{State: SyncPod, HasConfig: true, Static: isStatic}\n\t\tif isStatic {\n\t\t\t// restartable static pods are the normal case\n\t\t\trestartCountStatic++\n\t\t} else {\n\t\t\t// almost certainly means shenanigans, as API pods should never have the same UID after being deleted and recreated\n\t\t\t// unless there is a major API violation\n\t\t\trestartCount++\n\t\t}\n\t}\n\tmetrics.RestartedPodTotal.WithLabelValues(\"true\").Add(float64(restartCountStatic))\n\tmetrics.RestartedPodTotal.WithLabelValues(\"\").Add(float64(restartCount))\n\n\t// Complete termination of deleted pods that are not runtime pods (don't have\n\t// running containers), are terminal, and are not known to pod workers.\n\t// An example is pods rejected during kubelet admission that have never\n\t// started before (i.e. does not have an orphaned pod).\n\t// Adding the pods with SyncPodKill to pod workers allows to proceed with\n\t// force-deletion of such pods, yet preventing re-entry of the routine in the\n\t// next invocation of HandlePodCleanups.\n\tfor _, pod := range kl.filterTerminalPodsToDelete(allPods, runningRuntimePods, workingPods) {\n\t\tklog.V(3).InfoS(\"Handling termination and deletion of the pod to pod workers\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\t\tkl.podWorkers.UpdatePod(UpdatePodOptions{\n\t\t\tUpdateType: kubetypes.SyncPodKill,\n\t\t\tPod: pod,\n\t\t})\n\t}\n\n\t// Finally, terminate any pods that are observed in the runtime but not present in the list of\n\t// known running pods from config. If we do terminate running runtime pods that will happen\n\t// asynchronously in the background and those will be processed in the next invocation of\n\t// HandlePodCleanups.\n\tvar orphanCount int\n\tfor _, runningPod := range runningRuntimePods {\n\t\t// If there are orphaned pod resources in CRI that are unknown to the pod worker, terminate them\n\t\t// now. Since housekeeping is exclusive to other pod worker updates, we know that no pods have\n\t\t// been added to the pod worker in the meantime. Note that pods that are not visible in the runtime\n\t\t// but which were previously known are terminated by SyncKnownPods().\n\t\t_, knownPod := workingPods[runningPod.ID]\n\t\tif !knownPod {\n\t\t\tone := int64(1)\n\t\t\tkillPodOptions := \u0026KillPodOptions{\n\t\t\t\tPodTerminationGracePeriodSecondsOverride: \u0026one,\n\t\t\t}\n\t\t\tklog.V(2).InfoS(\"Clean up containers for orphaned pod we had not seen before\", \"podUID\", runningPod.ID, \"killPodOptions\", killPodOptions)\n\t\t\tkl.podWorkers.UpdatePod(UpdatePodOptions{\n\t\t\t\tUpdateType: kubetypes.SyncPodKill,\n\t\t\t\tRunningPod: runningPod,\n\t\t\t\tKillPodOptions: killPodOptions,\n\t\t\t})\n\n\t\t\t// the running pod is now known as well\n\t\t\tworkingPods[runningPod.ID] = PodWorkerSync{State: TerminatingPod, Orphan: true}\n\t\t\torphanCount++\n\t\t}\n\t}\n\tmetrics.OrphanedRuntimePodTotal.Add(float64(orphanCount))\n\n\t// Now that we have recorded any terminating pods, and added new pods that should be running,\n\t// record a summary here. Not all possible combinations of PodWorkerSync values are valid.\n\tcounts := make(map[PodWorkerSync]int)\n\tfor _, sync := range workingPods {\n\t\tcounts[sync]++\n\t}\n\tfor validSync, configState := range map[PodWorkerSync]string{\n\t\t{HasConfig: true, Static: true}: \"desired\",\n\t\t{HasConfig: true, Static: false}: \"desired\",\n\t\t{Orphan: true, HasConfig: true, Static: true}: \"orphan\",\n\t\t{Orphan: true, HasConfig: true, Static: false}: \"orphan\",\n\t\t{Orphan: true, HasConfig: false}: \"runtime_only\",\n\t} {\n\t\tfor _, state := range []PodWorkerState{SyncPod, TerminatingPod, TerminatedPod} {\n\t\t\tvalidSync.State = state\n\t\t\tcount := counts[validSync]\n\t\t\tdelete(counts, validSync)\n\t\t\tstaticString := stringIfTrue(validSync.Static)\n\t\t\tif !validSync.HasConfig {\n\t\t\t\tstaticString = \"unknown\"\n\t\t\t}\n\t\t\tmetrics.WorkingPodCount.WithLabelValues(state.String(), configState, staticString).Set(float64(count))\n\t\t}\n\t}\n\tif len(counts) \u003e 0 {\n\t\t// in case a combination is lost\n\t\tklog.V(3).InfoS(\"Programmer error, did not report a kubelet_working_pods metric for a value returned by SyncKnownPods\", \"counts\", counts)\n\t}\n\n\t// Remove any cgroups in the hierarchy for pods that are definitely no longer\n\t// running (not in the container runtime).\n\tif kl.cgroupsPerQOS {\n\t\tpcm := kl.containerManager.NewPodContainerManager()\n\t\tklog.V(3).InfoS(\"Clean up orphaned pod cgroups\")\n\t\tkl.cleanupOrphanedPodCgroups(pcm, cgroupPods, possiblyRunningPods)\n\t}\n\n\t// Cleanup any backoff entries.\n\tkl.backOff.GC()\n\n\treturn nil\n}","line":{"from":1006,"to":1265}} {"id":100006825,"name":"filterTerminalPodsToDelete","signature":"func (kl *Kubelet) filterTerminalPodsToDelete(allPods []*v1.Pod, runningRuntimePods []*kubecontainer.Pod, workingPods map[types.UID]PodWorkerSync) map[types.UID]*v1.Pod","file":"pkg/kubelet/kubelet_pods.go","code":"// filterTerminalPodsToDelete returns terminal pods which are ready to be\n// deleted by the status manager, but are not in pod workers.\n// First, the check for deletionTimestamp is a performance optimization as we\n// don't need to do anything with terminal pods without deletionTimestamp.\n// Second, the check for terminal pods is to avoid race conditions of triggering\n// deletion on Pending pods which are not yet added to pod workers.\n// Third, the check to skip pods known to pod workers is that the lifecycle of\n// such pods is already handled by pod workers.\n// Finally, we skip runtime pods as their termination is handled separately in\n// the HandlePodCleanups routine.\nfunc (kl *Kubelet) filterTerminalPodsToDelete(allPods []*v1.Pod, runningRuntimePods []*kubecontainer.Pod, workingPods map[types.UID]PodWorkerSync) map[types.UID]*v1.Pod {\n\tterminalPodsToDelete := make(map[types.UID]*v1.Pod)\n\tfor _, pod := range allPods {\n\t\tif pod.DeletionTimestamp == nil {\n\t\t\t// skip pods which don't have a deletion timestamp\n\t\t\tcontinue\n\t\t}\n\t\tif !podutil.IsPodPhaseTerminal(pod.Status.Phase) {\n\t\t\t// skip the non-terminal pods\n\t\t\tcontinue\n\t\t}\n\t\tif _, knownPod := workingPods[pod.UID]; knownPod {\n\t\t\t// skip pods known to pod workers\n\t\t\tcontinue\n\t\t}\n\t\tterminalPodsToDelete[pod.UID] = pod\n\t}\n\tfor _, runningRuntimePod := range runningRuntimePods {\n\t\t// skip running runtime pods - they are handled by a dedicated routine\n\t\t// which terminates the containers\n\t\tdelete(terminalPodsToDelete, runningRuntimePod.ID)\n\t}\n\treturn terminalPodsToDelete\n}","line":{"from":1267,"to":1300}} {"id":100006826,"name":"splitPodsByStatic","signature":"func splitPodsByStatic(pods []*v1.Pod) (regular, static []*v1.Pod)","file":"pkg/kubelet/kubelet_pods.go","code":"// splitPodsByStatic separates a list of desired pods from the pod manager into\n// regular or static pods. Mirror pods are not valid config sources (a mirror pod\n// being created cannot cause the Kubelet to start running a static pod) and are\n// excluded.\nfunc splitPodsByStatic(pods []*v1.Pod) (regular, static []*v1.Pod) {\n\tregular, static = make([]*v1.Pod, 0, len(pods)), make([]*v1.Pod, 0, len(pods))\n\tfor _, pod := range pods {\n\t\tif kubetypes.IsMirrorPod(pod) {\n\t\t\tcontinue\n\t\t}\n\t\tif kubetypes.IsStaticPod(pod) {\n\t\t\tstatic = append(static, pod)\n\t\t} else {\n\t\t\tregular = append(regular, pod)\n\t\t}\n\t}\n\treturn regular, static\n}","line":{"from":1302,"to":1319}} {"id":100006827,"name":"validateContainerLogStatus","signature":"func (kl *Kubelet) validateContainerLogStatus(podName string, podStatus *v1.PodStatus, containerName string, previous bool) (containerID kubecontainer.ContainerID, err error)","file":"pkg/kubelet/kubelet_pods.go","code":"// validateContainerLogStatus returns the container ID for the desired container to retrieve logs for, based on the state\n// of the container. The previous flag will only return the logs for the last terminated container, otherwise, the current\n// running container is preferred over a previous termination. If info about the container is not available then a specific\n// error is returned to the end user.\nfunc (kl *Kubelet) validateContainerLogStatus(podName string, podStatus *v1.PodStatus, containerName string, previous bool) (containerID kubecontainer.ContainerID, err error) {\n\tvar cID string\n\n\tcStatus, found := podutil.GetContainerStatus(podStatus.ContainerStatuses, containerName)\n\tif !found {\n\t\tcStatus, found = podutil.GetContainerStatus(podStatus.InitContainerStatuses, containerName)\n\t}\n\tif !found {\n\t\tcStatus, found = podutil.GetContainerStatus(podStatus.EphemeralContainerStatuses, containerName)\n\t}\n\tif !found {\n\t\treturn kubecontainer.ContainerID{}, fmt.Errorf(\"container %q in pod %q is not available\", containerName, podName)\n\t}\n\tlastState := cStatus.LastTerminationState\n\twaiting, running, terminated := cStatus.State.Waiting, cStatus.State.Running, cStatus.State.Terminated\n\n\tswitch {\n\tcase previous:\n\t\tif lastState.Terminated == nil || lastState.Terminated.ContainerID == \"\" {\n\t\t\treturn kubecontainer.ContainerID{}, fmt.Errorf(\"previous terminated container %q in pod %q not found\", containerName, podName)\n\t\t}\n\t\tcID = lastState.Terminated.ContainerID\n\n\tcase running != nil:\n\t\tcID = cStatus.ContainerID\n\n\tcase terminated != nil:\n\t\t// in cases where the next container didn't start, terminated.ContainerID will be empty, so get logs from the lastState.Terminated.\n\t\tif terminated.ContainerID == \"\" {\n\t\t\tif lastState.Terminated != nil \u0026\u0026 lastState.Terminated.ContainerID != \"\" {\n\t\t\t\tcID = lastState.Terminated.ContainerID\n\t\t\t} else {\n\t\t\t\treturn kubecontainer.ContainerID{}, fmt.Errorf(\"container %q in pod %q is terminated\", containerName, podName)\n\t\t\t}\n\t\t} else {\n\t\t\tcID = terminated.ContainerID\n\t\t}\n\n\tcase lastState.Terminated != nil:\n\t\tif lastState.Terminated.ContainerID == \"\" {\n\t\t\treturn kubecontainer.ContainerID{}, fmt.Errorf(\"container %q in pod %q is terminated\", containerName, podName)\n\t\t}\n\t\tcID = lastState.Terminated.ContainerID\n\n\tcase waiting != nil:\n\t\t// output some info for the most common pending failures\n\t\tswitch reason := waiting.Reason; reason {\n\t\tcase images.ErrImagePull.Error():\n\t\t\treturn kubecontainer.ContainerID{}, fmt.Errorf(\"container %q in pod %q is waiting to start: image can't be pulled\", containerName, podName)\n\t\tcase images.ErrImagePullBackOff.Error():\n\t\t\treturn kubecontainer.ContainerID{}, fmt.Errorf(\"container %q in pod %q is waiting to start: trying and failing to pull image\", containerName, podName)\n\t\tdefault:\n\t\t\treturn kubecontainer.ContainerID{}, fmt.Errorf(\"container %q in pod %q is waiting to start: %v\", containerName, podName, reason)\n\t\t}\n\tdefault:\n\t\t// unrecognized state\n\t\treturn kubecontainer.ContainerID{}, fmt.Errorf(\"container %q in pod %q is waiting to start - no logs yet\", containerName, podName)\n\t}\n\n\treturn kubecontainer.ParseContainerID(cID), nil\n}","line":{"from":1321,"to":1385}} {"id":100006828,"name":"GetKubeletContainerLogs","signature":"func (kl *Kubelet) GetKubeletContainerLogs(ctx context.Context, podFullName, containerName string, logOptions *v1.PodLogOptions, stdout, stderr io.Writer) error","file":"pkg/kubelet/kubelet_pods.go","code":"// GetKubeletContainerLogs returns logs from the container\n// TODO: this method is returning logs of random container attempts, when it should be returning the most recent attempt\n// or all of them.\nfunc (kl *Kubelet) GetKubeletContainerLogs(ctx context.Context, podFullName, containerName string, logOptions *v1.PodLogOptions, stdout, stderr io.Writer) error {\n\t// Pod workers periodically write status to statusManager. If status is not\n\t// cached there, something is wrong (or kubelet just restarted and hasn't\n\t// caught up yet). Just assume the pod is not ready yet.\n\tname, namespace, err := kubecontainer.ParsePodFullName(podFullName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to parse pod full name %q: %v\", podFullName, err)\n\t}\n\n\tpod, ok := kl.GetPodByName(namespace, name)\n\tif !ok {\n\t\treturn fmt.Errorf(\"pod %q cannot be found - no logs available\", name)\n\t}\n\n\tpodUID := pod.UID\n\tif mirrorPod, ok := kl.podManager.GetMirrorPodByPod(pod); ok {\n\t\tpodUID = mirrorPod.UID\n\t}\n\tpodStatus, found := kl.statusManager.GetPodStatus(podUID)\n\tif !found {\n\t\t// If there is no cached status, use the status from the\n\t\t// apiserver. This is useful if kubelet has recently been\n\t\t// restarted.\n\t\tpodStatus = pod.Status\n\t}\n\n\t// TODO: Consolidate the logic here with kuberuntime.GetContainerLogs, here we convert container name to containerID,\n\t// but inside kuberuntime we convert container id back to container name and restart count.\n\t// TODO: After separate container log lifecycle management, we should get log based on the existing log files\n\t// instead of container status.\n\tcontainerID, err := kl.validateContainerLogStatus(pod.Name, \u0026podStatus, containerName, logOptions.Previous)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Do a zero-byte write to stdout before handing off to the container runtime.\n\t// This ensures at least one Write call is made to the writer when copying starts,\n\t// even if we then block waiting for log output from the container.\n\tif _, err := stdout.Write([]byte{}); err != nil {\n\t\treturn err\n\t}\n\n\treturn kl.containerRuntime.GetContainerLogs(ctx, pod, containerID, logOptions, stdout, stderr)\n}","line":{"from":1387,"to":1433}} {"id":100006829,"name":"getPhase","signature":"func getPhase(pod *v1.Pod, info []v1.ContainerStatus, podIsTerminal bool) v1.PodPhase","file":"pkg/kubelet/kubelet_pods.go","code":"// getPhase returns the phase of a pod given its container info.\nfunc getPhase(pod *v1.Pod, info []v1.ContainerStatus, podIsTerminal bool) v1.PodPhase {\n\tspec := pod.Spec\n\tpendingInitialization := 0\n\tfailedInitialization := 0\n\tfor _, container := range spec.InitContainers {\n\t\tcontainerStatus, ok := podutil.GetContainerStatus(info, container.Name)\n\t\tif !ok {\n\t\t\tpendingInitialization++\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch {\n\t\tcase containerStatus.State.Running != nil:\n\t\t\tpendingInitialization++\n\t\tcase containerStatus.State.Terminated != nil:\n\t\t\tif containerStatus.State.Terminated.ExitCode != 0 {\n\t\t\t\tfailedInitialization++\n\t\t\t}\n\t\tcase containerStatus.State.Waiting != nil:\n\t\t\tif containerStatus.LastTerminationState.Terminated != nil {\n\t\t\t\tif containerStatus.LastTerminationState.Terminated.ExitCode != 0 {\n\t\t\t\t\tfailedInitialization++\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tpendingInitialization++\n\t\t\t}\n\t\tdefault:\n\t\t\tpendingInitialization++\n\t\t}\n\t}\n\n\tunknown := 0\n\trunning := 0\n\twaiting := 0\n\tstopped := 0\n\tsucceeded := 0\n\tfor _, container := range spec.Containers {\n\t\tcontainerStatus, ok := podutil.GetContainerStatus(info, container.Name)\n\t\tif !ok {\n\t\t\tunknown++\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch {\n\t\tcase containerStatus.State.Running != nil:\n\t\t\trunning++\n\t\tcase containerStatus.State.Terminated != nil:\n\t\t\tstopped++\n\t\t\tif containerStatus.State.Terminated.ExitCode == 0 {\n\t\t\t\tsucceeded++\n\t\t\t}\n\t\tcase containerStatus.State.Waiting != nil:\n\t\t\tif containerStatus.LastTerminationState.Terminated != nil {\n\t\t\t\tstopped++\n\t\t\t} else {\n\t\t\t\twaiting++\n\t\t\t}\n\t\tdefault:\n\t\t\tunknown++\n\t\t}\n\t}\n\n\tif failedInitialization \u003e 0 \u0026\u0026 spec.RestartPolicy == v1.RestartPolicyNever {\n\t\treturn v1.PodFailed\n\t}\n\n\tswitch {\n\tcase pendingInitialization \u003e 0:\n\t\tfallthrough\n\tcase waiting \u003e 0:\n\t\tklog.V(5).InfoS(\"Pod waiting \u003e 0, pending\")\n\t\t// One or more containers has not been started\n\t\treturn v1.PodPending\n\tcase running \u003e 0 \u0026\u0026 unknown == 0:\n\t\t// All containers have been started, and at least\n\t\t// one container is running\n\t\treturn v1.PodRunning\n\tcase running == 0 \u0026\u0026 stopped \u003e 0 \u0026\u0026 unknown == 0:\n\t\t// The pod is terminal so its containers won't be restarted regardless\n\t\t// of the restart policy.\n\t\tif podIsTerminal {\n\t\t\t// TODO(#116484): Also assign terminal phase to static pods.\n\t\t\tif !kubetypes.IsStaticPod(pod) {\n\t\t\t\t// All containers are terminated in success\n\t\t\t\tif stopped == succeeded {\n\t\t\t\t\treturn v1.PodSucceeded\n\t\t\t\t}\n\t\t\t\t// There is at least one failure\n\t\t\t\treturn v1.PodFailed\n\t\t\t}\n\t\t}\n\t\t// All containers are terminated\n\t\tif spec.RestartPolicy == v1.RestartPolicyAlways {\n\t\t\t// All containers are in the process of restarting\n\t\t\treturn v1.PodRunning\n\t\t}\n\t\tif stopped == succeeded {\n\t\t\t// RestartPolicy is not Always, and all\n\t\t\t// containers are terminated in success\n\t\t\treturn v1.PodSucceeded\n\t\t}\n\t\tif spec.RestartPolicy == v1.RestartPolicyNever {\n\t\t\t// RestartPolicy is Never, and all containers are\n\t\t\t// terminated with at least one in failure\n\t\t\treturn v1.PodFailed\n\t\t}\n\t\t// RestartPolicy is OnFailure, and at least one in failure\n\t\t// and in the process of restarting\n\t\treturn v1.PodRunning\n\tdefault:\n\t\tklog.V(5).InfoS(\"Pod default case, pending\")\n\t\treturn v1.PodPending\n\t}\n}","line":{"from":1435,"to":1549}} {"id":100006830,"name":"determinePodResizeStatus","signature":"func (kl *Kubelet) determinePodResizeStatus(pod *v1.Pod, podStatus *v1.PodStatus) v1.PodResizeStatus","file":"pkg/kubelet/kubelet_pods.go","code":"func (kl *Kubelet) determinePodResizeStatus(pod *v1.Pod, podStatus *v1.PodStatus) v1.PodResizeStatus {\n\tvar podResizeStatus v1.PodResizeStatus\n\tspecStatusDiffer := false\n\tfor _, c := range pod.Spec.Containers {\n\t\tif cs, ok := podutil.GetContainerStatus(podStatus.ContainerStatuses, c.Name); ok {\n\t\t\tif cs.Resources != nil \u0026\u0026 diff.ObjectDiff(c.Resources, *cs.Resources) != \"\" {\n\t\t\t\tspecStatusDiffer = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif !specStatusDiffer {\n\t\t// Clear last resize state from checkpoint\n\t\tif err := kl.statusManager.SetPodResizeStatus(pod.UID, \"\"); err != nil {\n\t\t\tklog.ErrorS(err, \"SetPodResizeStatus failed\", \"pod\", pod.Name)\n\t\t}\n\t} else {\n\t\tif resizeStatus, found := kl.statusManager.GetPodResizeStatus(string(pod.UID)); found {\n\t\t\tpodResizeStatus = resizeStatus\n\t\t}\n\t}\n\treturn podResizeStatus\n}","line":{"from":1551,"to":1573}} {"id":100006831,"name":"generateAPIPodStatus","signature":"func (kl *Kubelet) generateAPIPodStatus(pod *v1.Pod, podStatus *kubecontainer.PodStatus, podIsTerminal bool) v1.PodStatus","file":"pkg/kubelet/kubelet_pods.go","code":"// generateAPIPodStatus creates the final API pod status for a pod, given the\n// internal pod status. This method should only be called from within sync*Pod methods.\nfunc (kl *Kubelet) generateAPIPodStatus(pod *v1.Pod, podStatus *kubecontainer.PodStatus, podIsTerminal bool) v1.PodStatus {\n\tklog.V(3).InfoS(\"Generating pod status\", \"podIsTerminal\", podIsTerminal, \"pod\", klog.KObj(pod))\n\t// use the previous pod status, or the api status, as the basis for this pod\n\toldPodStatus, found := kl.statusManager.GetPodStatus(pod.UID)\n\tif !found {\n\t\toldPodStatus = pod.Status\n\t}\n\ts := kl.convertStatusToAPIStatus(pod, podStatus, oldPodStatus)\n\tif utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) {\n\t\ts.Resize = kl.determinePodResizeStatus(pod, s)\n\t}\n\t// calculate the next phase and preserve reason\n\tallStatus := append(append([]v1.ContainerStatus{}, s.ContainerStatuses...), s.InitContainerStatuses...)\n\ts.Phase = getPhase(pod, allStatus, podIsTerminal)\n\tklog.V(4).InfoS(\"Got phase for pod\", \"pod\", klog.KObj(pod), \"oldPhase\", oldPodStatus.Phase, \"phase\", s.Phase)\n\n\t// Perform a three-way merge between the statuses from the status manager,\n\t// runtime, and generated status to ensure terminal status is correctly set.\n\tif s.Phase != v1.PodFailed \u0026\u0026 s.Phase != v1.PodSucceeded {\n\t\tswitch {\n\t\tcase oldPodStatus.Phase == v1.PodFailed || oldPodStatus.Phase == v1.PodSucceeded:\n\t\t\tklog.V(4).InfoS(\"Status manager phase was terminal, updating phase to match\", \"pod\", klog.KObj(pod), \"phase\", oldPodStatus.Phase)\n\t\t\ts.Phase = oldPodStatus.Phase\n\t\tcase pod.Status.Phase == v1.PodFailed || pod.Status.Phase == v1.PodSucceeded:\n\t\t\tklog.V(4).InfoS(\"API phase was terminal, updating phase to match\", \"pod\", klog.KObj(pod), \"phase\", pod.Status.Phase)\n\t\t\ts.Phase = pod.Status.Phase\n\t\t}\n\t}\n\n\tif s.Phase == oldPodStatus.Phase {\n\t\t// preserve the reason and message which is associated with the phase\n\t\ts.Reason = oldPodStatus.Reason\n\t\ts.Message = oldPodStatus.Message\n\t\tif len(s.Reason) == 0 {\n\t\t\ts.Reason = pod.Status.Reason\n\t\t}\n\t\tif len(s.Message) == 0 {\n\t\t\ts.Message = pod.Status.Message\n\t\t}\n\t}\n\n\t// check if an internal module has requested the pod is evicted and override the reason and message\n\tfor _, podSyncHandler := range kl.PodSyncHandlers {\n\t\tif result := podSyncHandler.ShouldEvict(pod); result.Evict {\n\t\t\ts.Phase = v1.PodFailed\n\t\t\ts.Reason = result.Reason\n\t\t\ts.Message = result.Message\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// pods are not allowed to transition out of terminal phases\n\tif pod.Status.Phase == v1.PodFailed || pod.Status.Phase == v1.PodSucceeded {\n\t\t// API server shows terminal phase; transitions are not allowed\n\t\tif s.Phase != pod.Status.Phase {\n\t\t\tklog.ErrorS(nil, \"Pod attempted illegal phase transition\", \"pod\", klog.KObj(pod), \"originalStatusPhase\", pod.Status.Phase, \"apiStatusPhase\", s.Phase, \"apiStatus\", s)\n\t\t\t// Force back to phase from the API server\n\t\t\ts.Phase = pod.Status.Phase\n\t\t}\n\t}\n\n\t// ensure the probe managers have up to date status for containers\n\tkl.probeManager.UpdatePodStatus(pod.UID, s)\n\n\t// preserve all conditions not owned by the kubelet\n\ts.Conditions = make([]v1.PodCondition, 0, len(pod.Status.Conditions)+1)\n\tfor _, c := range pod.Status.Conditions {\n\t\tif !kubetypes.PodConditionByKubelet(c.Type) {\n\t\t\ts.Conditions = append(s.Conditions, c)\n\t\t}\n\t}\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.PodDisruptionConditions) {\n\t\t// copy over the pod disruption conditions from state which is already\n\t\t// updated during the eviciton (due to either node resource pressure or\n\t\t// node graceful shutdown). We do not re-generate the conditions based\n\t\t// on the container statuses as they are added based on one-time events.\n\t\tcType := v1.DisruptionTarget\n\t\tif _, condition := podutil.GetPodConditionFromList(oldPodStatus.Conditions, cType); condition != nil {\n\t\t\ts.Conditions = utilpod.ReplaceOrAppendPodCondition(s.Conditions, condition)\n\t\t}\n\t}\n\n\t// set all Kubelet-owned conditions\n\tif utilfeature.DefaultFeatureGate.Enabled(features.PodHasNetworkCondition) {\n\t\ts.Conditions = append(s.Conditions, status.GeneratePodHasNetworkCondition(pod, podStatus))\n\t}\n\ts.Conditions = append(s.Conditions, status.GeneratePodInitializedCondition(\u0026pod.Spec, s.InitContainerStatuses, s.Phase))\n\ts.Conditions = append(s.Conditions, status.GeneratePodReadyCondition(\u0026pod.Spec, s.Conditions, s.ContainerStatuses, s.Phase))\n\ts.Conditions = append(s.Conditions, status.GenerateContainersReadyCondition(\u0026pod.Spec, s.ContainerStatuses, s.Phase))\n\ts.Conditions = append(s.Conditions, v1.PodCondition{\n\t\tType: v1.PodScheduled,\n\t\tStatus: v1.ConditionTrue,\n\t})\n\t// set HostIP and initialize PodIP/PodIPs for host network pods\n\tif kl.kubeClient != nil {\n\t\thostIPs, err := kl.getHostIPsAnyWay()\n\t\tif err != nil {\n\t\t\tklog.V(4).InfoS(\"Cannot get host IPs\", \"err\", err)\n\t\t} else {\n\t\t\ts.HostIP = hostIPs[0].String()\n\t\t\t// HostNetwork Pods inherit the node IPs as PodIPs. They are immutable once set,\n\t\t\t// other than that if the node becomes dual-stack, we add the secondary IP.\n\t\t\tif kubecontainer.IsHostNetworkPod(pod) {\n\t\t\t\t// Primary IP is not set\n\t\t\t\tif s.PodIP == \"\" {\n\t\t\t\t\ts.PodIP = hostIPs[0].String()\n\t\t\t\t\ts.PodIPs = []v1.PodIP{{IP: s.PodIP}}\n\t\t\t\t}\n\t\t\t\t// Secondary IP is not set #105320\n\t\t\t\tif len(hostIPs) == 2 \u0026\u0026 len(s.PodIPs) == 1 {\n\t\t\t\t\ts.PodIPs = append(s.PodIPs, v1.PodIP{IP: hostIPs[1].String()})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn *s\n}","line":{"from":1575,"to":1695}} {"id":100006832,"name":"sortPodIPs","signature":"func (kl *Kubelet) sortPodIPs(podIPs []string) []string","file":"pkg/kubelet/kubelet_pods.go","code":"// sortPodIPs return the PodIPs sorted and truncated by the cluster IP family preference.\n// The runtime pod status may have an arbitrary number of IPs, in an arbitrary order.\n// PodIPs are obtained by: func (m *kubeGenericRuntimeManager) determinePodSandboxIPs()\n// Pick out the first returned IP of the same IP family as the node IP\n// first, followed by the first IP of the opposite IP family (if any)\n// and use them for the Pod.Status.PodIPs and the Downward API environment variables\nfunc (kl *Kubelet) sortPodIPs(podIPs []string) []string {\n\tips := make([]string, 0, 2)\n\tvar validPrimaryIP, validSecondaryIP func(ip string) bool\n\tif len(kl.nodeIPs) == 0 || utilnet.IsIPv4(kl.nodeIPs[0]) {\n\t\tvalidPrimaryIP = utilnet.IsIPv4String\n\t\tvalidSecondaryIP = utilnet.IsIPv6String\n\t} else {\n\t\tvalidPrimaryIP = utilnet.IsIPv6String\n\t\tvalidSecondaryIP = utilnet.IsIPv4String\n\t}\n\tfor _, ip := range podIPs {\n\t\tif validPrimaryIP(ip) {\n\t\t\tips = append(ips, ip)\n\t\t\tbreak\n\t\t}\n\t}\n\tfor _, ip := range podIPs {\n\t\tif validSecondaryIP(ip) {\n\t\t\tips = append(ips, ip)\n\t\t\tbreak\n\t\t}\n\t}\n\treturn ips\n}","line":{"from":1697,"to":1726}} {"id":100006833,"name":"convertStatusToAPIStatus","signature":"func (kl *Kubelet) convertStatusToAPIStatus(pod *v1.Pod, podStatus *kubecontainer.PodStatus, oldPodStatus v1.PodStatus) *v1.PodStatus","file":"pkg/kubelet/kubelet_pods.go","code":"// convertStatusToAPIStatus initialize an api PodStatus for the given pod from\n// the given internal pod status and the previous state of the pod from the API.\n// It is purely transformative and does not alter the kubelet state at all.\nfunc (kl *Kubelet) convertStatusToAPIStatus(pod *v1.Pod, podStatus *kubecontainer.PodStatus, oldPodStatus v1.PodStatus) *v1.PodStatus {\n\tvar apiPodStatus v1.PodStatus\n\n\t// copy pod status IPs to avoid race conditions with PodStatus #102806\n\tpodIPs := make([]string, len(podStatus.IPs))\n\tcopy(podIPs, podStatus.IPs)\n\n\t// make podIPs order match node IP family preference #97979\n\tpodIPs = kl.sortPodIPs(podIPs)\n\tfor _, ip := range podIPs {\n\t\tapiPodStatus.PodIPs = append(apiPodStatus.PodIPs, v1.PodIP{IP: ip})\n\t}\n\tif len(apiPodStatus.PodIPs) \u003e 0 {\n\t\tapiPodStatus.PodIP = apiPodStatus.PodIPs[0].IP\n\t}\n\n\t// set status for Pods created on versions of kube older than 1.6\n\tapiPodStatus.QOSClass = v1qos.GetPodQOS(pod)\n\n\tapiPodStatus.ContainerStatuses = kl.convertToAPIContainerStatuses(\n\t\tpod, podStatus,\n\t\toldPodStatus.ContainerStatuses,\n\t\tpod.Spec.Containers,\n\t\tlen(pod.Spec.InitContainers) \u003e 0,\n\t\tfalse,\n\t)\n\tapiPodStatus.InitContainerStatuses = kl.convertToAPIContainerStatuses(\n\t\tpod, podStatus,\n\t\toldPodStatus.InitContainerStatuses,\n\t\tpod.Spec.InitContainers,\n\t\tlen(pod.Spec.InitContainers) \u003e 0,\n\t\ttrue,\n\t)\n\tvar ecSpecs []v1.Container\n\tfor i := range pod.Spec.EphemeralContainers {\n\t\tecSpecs = append(ecSpecs, v1.Container(pod.Spec.EphemeralContainers[i].EphemeralContainerCommon))\n\t}\n\n\t// #80875: By now we've iterated podStatus 3 times. We could refactor this to make a single\n\t// pass through podStatus.ContainerStatuses\n\tapiPodStatus.EphemeralContainerStatuses = kl.convertToAPIContainerStatuses(\n\t\tpod, podStatus,\n\t\toldPodStatus.EphemeralContainerStatuses,\n\t\tecSpecs,\n\t\tlen(pod.Spec.InitContainers) \u003e 0,\n\t\tfalse,\n\t)\n\n\treturn \u0026apiPodStatus\n}","line":{"from":1728,"to":1780}} {"id":100006834,"name":"convertToAPIContainerStatuses","signature":"func (kl *Kubelet) convertToAPIContainerStatuses(pod *v1.Pod, podStatus *kubecontainer.PodStatus, previousStatus []v1.ContainerStatus, containers []v1.Container, hasInitContainers, isInitContainer bool) []v1.ContainerStatus","file":"pkg/kubelet/kubelet_pods.go","code":"// convertToAPIContainerStatuses converts the given internal container\n// statuses into API container statuses.\nfunc (kl *Kubelet) convertToAPIContainerStatuses(pod *v1.Pod, podStatus *kubecontainer.PodStatus, previousStatus []v1.ContainerStatus, containers []v1.Container, hasInitContainers, isInitContainer bool) []v1.ContainerStatus {\n\tconvertContainerStatus := func(cs *kubecontainer.Status, oldStatus *v1.ContainerStatus) *v1.ContainerStatus {\n\t\tcid := cs.ID.String()\n\t\tstatus := \u0026v1.ContainerStatus{\n\t\t\tName: cs.Name,\n\t\t\tRestartCount: int32(cs.RestartCount),\n\t\t\tImage: cs.Image,\n\t\t\tImageID: cs.ImageID,\n\t\t\tContainerID: cid,\n\t\t}\n\t\tswitch {\n\t\tcase cs.State == kubecontainer.ContainerStateRunning:\n\t\t\tstatus.State.Running = \u0026v1.ContainerStateRunning{StartedAt: metav1.NewTime(cs.StartedAt)}\n\t\tcase cs.State == kubecontainer.ContainerStateCreated:\n\t\t\t// containers that are created but not running are \"waiting to be running\"\n\t\t\tstatus.State.Waiting = \u0026v1.ContainerStateWaiting{}\n\t\tcase cs.State == kubecontainer.ContainerStateExited:\n\t\t\tstatus.State.Terminated = \u0026v1.ContainerStateTerminated{\n\t\t\t\tExitCode: int32(cs.ExitCode),\n\t\t\t\tReason: cs.Reason,\n\t\t\t\tMessage: cs.Message,\n\t\t\t\tStartedAt: metav1.NewTime(cs.StartedAt),\n\t\t\t\tFinishedAt: metav1.NewTime(cs.FinishedAt),\n\t\t\t\tContainerID: cid,\n\t\t\t}\n\n\t\tcase cs.State == kubecontainer.ContainerStateUnknown \u0026\u0026\n\t\t\toldStatus != nil \u0026\u0026 // we have an old status\n\t\t\toldStatus.State.Running != nil: // our previous status was running\n\t\t\t// if this happens, then we know that this container was previously running and isn't anymore (assuming the CRI isn't failing to return running containers).\n\t\t\t// you can imagine this happening in cases where a container failed and the kubelet didn't ask about it in time to see the result.\n\t\t\t// in this case, the container should not to into waiting state immediately because that can make cases like runonce pods actually run\n\t\t\t// twice. \"container never ran\" is different than \"container ran and failed\". This is handled differently in the kubelet\n\t\t\t// and it is handled differently in higher order logic like crashloop detection and handling\n\t\t\tstatus.State.Terminated = \u0026v1.ContainerStateTerminated{\n\t\t\t\tReason: \"ContainerStatusUnknown\",\n\t\t\t\tMessage: \"The container could not be located when the pod was terminated\",\n\t\t\t\tExitCode: 137, // this code indicates an error\n\t\t\t}\n\t\t\t// the restart count normally comes from the CRI (see near the top of this method), but since this is being added explicitly\n\t\t\t// for the case where the CRI did not return a status, we need to manually increment the restart count to be accurate.\n\t\t\tstatus.RestartCount = oldStatus.RestartCount + 1\n\n\t\tdefault:\n\t\t\t// this collapses any unknown state to container waiting. If any container is waiting, then the pod status moves to pending even if it is running.\n\t\t\t// if I'm reading this correctly, then any failure to read status on any container results in the entire pod going pending even if the containers\n\t\t\t// are actually running.\n\t\t\t// see https://github.com/kubernetes/kubernetes/blob/5d1b3e26af73dde33ecb6a3e69fb5876ceab192f/pkg/kubelet/kuberuntime/kuberuntime_container.go#L497 to\n\t\t\t// https://github.com/kubernetes/kubernetes/blob/8976e3620f8963e72084971d9d4decbd026bf49f/pkg/kubelet/kuberuntime/helpers.go#L58-L71\n\t\t\t// and interpreted here https://github.com/kubernetes/kubernetes/blob/b27e78f590a0d43e4a23ca3b2bf1739ca4c6e109/pkg/kubelet/kubelet_pods.go#L1434-L1439\n\t\t\tstatus.State.Waiting = \u0026v1.ContainerStateWaiting{}\n\t\t}\n\t\treturn status\n\t}\n\n\tconvertContainerStatusResources := func(cName string, status *v1.ContainerStatus, cStatus *kubecontainer.Status, oldStatuses map[string]v1.ContainerStatus) *v1.ResourceRequirements {\n\t\tvar requests, limits v1.ResourceList\n\t\t// oldStatus should always exist if container is running\n\t\toldStatus, oldStatusFound := oldStatuses[cName]\n\t\t// Initialize limits/requests from container's spec upon transition to Running state\n\t\t// For cpu \u0026 memory, values queried from runtime via CRI always supercedes spec values\n\t\t// For ephemeral-storage, a running container's status.limit/request equals spec.limit/request\n\t\tdetermineResource := func(rName v1.ResourceName, v1ContainerResource, oldStatusResource, resource v1.ResourceList) {\n\t\t\tif oldStatusFound {\n\t\t\t\tif oldStatus.State.Running == nil || status.ContainerID != oldStatus.ContainerID {\n\t\t\t\t\tif r, exists := v1ContainerResource[rName]; exists {\n\t\t\t\t\t\tresource[rName] = r.DeepCopy()\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif oldStatusResource != nil {\n\t\t\t\t\t\tif r, exists := oldStatusResource[rName]; exists {\n\t\t\t\t\t\t\tresource[rName] = r.DeepCopy()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcontainer := kubecontainer.GetContainerSpec(pod, cName)\n\t\t// AllocatedResources values come from checkpoint. It is the source-of-truth.\n\t\tfound := false\n\t\tstatus.AllocatedResources, found = kl.statusManager.GetContainerResourceAllocation(string(pod.UID), cName)\n\t\tif !(container.Resources.Requests == nil \u0026\u0026 container.Resources.Limits == nil) \u0026\u0026 !found {\n\t\t\t// Log error and fallback to AllocatedResources in oldStatus if it exists\n\t\t\tklog.ErrorS(nil, \"resource allocation not found in checkpoint store\", \"pod\", pod.Name, \"container\", cName)\n\t\t\tif oldStatusFound {\n\t\t\t\tstatus.AllocatedResources = oldStatus.AllocatedResources\n\t\t\t}\n\t\t}\n\t\tif oldStatus.Resources == nil {\n\t\t\toldStatus.Resources = \u0026v1.ResourceRequirements{}\n\t\t}\n\t\t// Convert Limits\n\t\tif container.Resources.Limits != nil {\n\t\t\tlimits = make(v1.ResourceList)\n\t\t\tif cStatus.Resources != nil \u0026\u0026 cStatus.Resources.CPULimit != nil {\n\t\t\t\tlimits[v1.ResourceCPU] = cStatus.Resources.CPULimit.DeepCopy()\n\t\t\t} else {\n\t\t\t\tdetermineResource(v1.ResourceCPU, container.Resources.Limits, oldStatus.Resources.Limits, limits)\n\t\t\t}\n\t\t\tif cStatus.Resources != nil \u0026\u0026 cStatus.Resources.MemoryLimit != nil {\n\t\t\t\tlimits[v1.ResourceMemory] = cStatus.Resources.MemoryLimit.DeepCopy()\n\t\t\t} else {\n\t\t\t\tdetermineResource(v1.ResourceMemory, container.Resources.Limits, oldStatus.Resources.Limits, limits)\n\t\t\t}\n\t\t\tif ephemeralStorage, found := container.Resources.Limits[v1.ResourceEphemeralStorage]; found {\n\t\t\t\tlimits[v1.ResourceEphemeralStorage] = ephemeralStorage.DeepCopy()\n\t\t\t}\n\t\t}\n\t\t// Convert Requests\n\t\tif status.AllocatedResources != nil {\n\t\t\trequests = make(v1.ResourceList)\n\t\t\tif cStatus.Resources != nil \u0026\u0026 cStatus.Resources.CPURequest != nil {\n\t\t\t\trequests[v1.ResourceCPU] = cStatus.Resources.CPURequest.DeepCopy()\n\t\t\t} else {\n\t\t\t\tdetermineResource(v1.ResourceCPU, status.AllocatedResources, oldStatus.Resources.Requests, requests)\n\t\t\t}\n\t\t\tif memory, found := status.AllocatedResources[v1.ResourceMemory]; found {\n\t\t\t\trequests[v1.ResourceMemory] = memory.DeepCopy()\n\t\t\t}\n\t\t\tif ephemeralStorage, found := status.AllocatedResources[v1.ResourceEphemeralStorage]; found {\n\t\t\t\trequests[v1.ResourceEphemeralStorage] = ephemeralStorage.DeepCopy()\n\t\t\t}\n\t\t}\n\t\t//TODO(vinaykul,derekwaynecarr,InPlacePodVerticalScaling): Update this to include extended resources in\n\t\t// addition to CPU, memory, ephemeral storage. Add test case for extended resources.\n\t\tresources := \u0026v1.ResourceRequirements{\n\t\t\tLimits: limits,\n\t\t\tRequests: requests,\n\t\t}\n\t\treturn resources\n\t}\n\n\t// Fetch old containers statuses from old pod status.\n\toldStatuses := make(map[string]v1.ContainerStatus, len(containers))\n\tfor _, status := range previousStatus {\n\t\toldStatuses[status.Name] = status\n\t}\n\n\t// Set all container statuses to default waiting state\n\tstatuses := make(map[string]*v1.ContainerStatus, len(containers))\n\tdefaultWaitingState := v1.ContainerState{Waiting: \u0026v1.ContainerStateWaiting{Reason: ContainerCreating}}\n\tif hasInitContainers {\n\t\tdefaultWaitingState = v1.ContainerState{Waiting: \u0026v1.ContainerStateWaiting{Reason: PodInitializing}}\n\t}\n\n\tfor _, container := range containers {\n\t\tstatus := \u0026v1.ContainerStatus{\n\t\t\tName: container.Name,\n\t\t\tImage: container.Image,\n\t\t\tState: defaultWaitingState,\n\t\t}\n\t\toldStatus, found := oldStatuses[container.Name]\n\t\tif found {\n\t\t\tif oldStatus.State.Terminated != nil {\n\t\t\t\tstatus = \u0026oldStatus\n\t\t\t} else {\n\t\t\t\t// Apply some values from the old statuses as the default values.\n\t\t\t\tstatus.RestartCount = oldStatus.RestartCount\n\t\t\t\tstatus.LastTerminationState = oldStatus.LastTerminationState\n\t\t\t}\n\t\t}\n\t\tstatuses[container.Name] = status\n\t}\n\n\tfor _, container := range containers {\n\t\tfound := false\n\t\tfor _, cStatus := range podStatus.ContainerStatuses {\n\t\t\tif container.Name == cStatus.Name {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif found {\n\t\t\tcontinue\n\t\t}\n\t\t// if no container is found, then assuming it should be waiting seems plausible, but the status code requires\n\t\t// that a previous termination be present. If we're offline long enough or something removed the container, then\n\t\t// the previous termination may not be present. This next code block ensures that if the container was previously running\n\t\t// then when that container status disappears, we can infer that it terminated even if we don't know the status code.\n\t\t// By setting the lasttermination state we are able to leave the container status waiting and present more accurate\n\t\t// data via the API.\n\n\t\toldStatus, ok := oldStatuses[container.Name]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tif oldStatus.State.Terminated != nil {\n\t\t\t// if the old container status was terminated, the lasttermination status is correct\n\t\t\tcontinue\n\t\t}\n\t\tif oldStatus.State.Running == nil {\n\t\t\t// if the old container status isn't running, then waiting is an appropriate status and we have nothing to do\n\t\t\tcontinue\n\t\t}\n\n\t\t// If we're here, we know the pod was previously running, but doesn't have a terminated status. We will check now to\n\t\t// see if it's in a pending state.\n\t\tstatus := statuses[container.Name]\n\t\t// If the status we're about to write indicates the default, the Waiting status will force this pod back into Pending.\n\t\t// That isn't true, we know the pod was previously running.\n\t\tisDefaultWaitingStatus := status.State.Waiting != nil \u0026\u0026 status.State.Waiting.Reason == ContainerCreating\n\t\tif hasInitContainers {\n\t\t\tisDefaultWaitingStatus = status.State.Waiting != nil \u0026\u0026 status.State.Waiting.Reason == PodInitializing\n\t\t}\n\t\tif !isDefaultWaitingStatus {\n\t\t\t// the status was written, don't override\n\t\t\tcontinue\n\t\t}\n\t\tif status.LastTerminationState.Terminated != nil {\n\t\t\t// if we already have a termination state, nothing to do\n\t\t\tcontinue\n\t\t}\n\n\t\t// setting this value ensures that we show as stopped here, not as waiting:\n\t\t// https://github.com/kubernetes/kubernetes/blob/90c9f7b3e198e82a756a68ffeac978a00d606e55/pkg/kubelet/kubelet_pods.go#L1440-L1445\n\t\t// This prevents the pod from becoming pending\n\t\tstatus.LastTerminationState.Terminated = \u0026v1.ContainerStateTerminated{\n\t\t\tReason: \"ContainerStatusUnknown\",\n\t\t\tMessage: \"The container could not be located when the pod was deleted. The container used to be Running\",\n\t\t\tExitCode: 137,\n\t\t}\n\n\t\t// If the pod was not deleted, then it's been restarted. Increment restart count.\n\t\tif pod.DeletionTimestamp == nil {\n\t\t\tstatus.RestartCount += 1\n\t\t}\n\n\t\tstatuses[container.Name] = status\n\t}\n\n\t// Copy the slice before sorting it\n\tcontainerStatusesCopy := make([]*kubecontainer.Status, len(podStatus.ContainerStatuses))\n\tcopy(containerStatusesCopy, podStatus.ContainerStatuses)\n\n\t// Make the latest container status comes first.\n\tsort.Sort(sort.Reverse(kubecontainer.SortContainerStatusesByCreationTime(containerStatusesCopy)))\n\t// Set container statuses according to the statuses seen in pod status\n\tcontainerSeen := map[string]int{}\n\tfor _, cStatus := range containerStatusesCopy {\n\t\tcName := cStatus.Name\n\t\tif _, ok := statuses[cName]; !ok {\n\t\t\t// This would also ignore the infra container.\n\t\t\tcontinue\n\t\t}\n\t\tif containerSeen[cName] \u003e= 2 {\n\t\t\tcontinue\n\t\t}\n\t\tvar oldStatusPtr *v1.ContainerStatus\n\t\tif oldStatus, ok := oldStatuses[cName]; ok {\n\t\t\toldStatusPtr = \u0026oldStatus\n\t\t}\n\t\tstatus := convertContainerStatus(cStatus, oldStatusPtr)\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) {\n\t\t\tif status.State.Running != nil {\n\t\t\t\tstatus.Resources = convertContainerStatusResources(cName, status, cStatus, oldStatuses)\n\t\t\t}\n\t\t}\n\t\tif containerSeen[cName] == 0 {\n\t\t\tstatuses[cName] = status\n\t\t} else {\n\t\t\tstatuses[cName].LastTerminationState = status.State\n\t\t}\n\t\tcontainerSeen[cName] = containerSeen[cName] + 1\n\t}\n\n\t// Handle the containers failed to be started, which should be in Waiting state.\n\tfor _, container := range containers {\n\t\tif isInitContainer {\n\t\t\t// If the init container is terminated with exit code 0, it won't be restarted.\n\t\t\t// TODO(random-liu): Handle this in a cleaner way.\n\t\t\ts := podStatus.FindContainerStatusByName(container.Name)\n\t\t\tif s != nil \u0026\u0026 s.State == kubecontainer.ContainerStateExited \u0026\u0026 s.ExitCode == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\t// If a container should be restarted in next syncpod, it is *Waiting*.\n\t\tif !kubecontainer.ShouldContainerBeRestarted(\u0026container, pod, podStatus) {\n\t\t\tcontinue\n\t\t}\n\t\tstatus := statuses[container.Name]\n\t\treason, ok := kl.reasonCache.Get(pod.UID, container.Name)\n\t\tif !ok {\n\t\t\t// In fact, we could also apply Waiting state here, but it is less informative,\n\t\t\t// and the container will be restarted soon, so we prefer the original state here.\n\t\t\t// Note that with the current implementation of ShouldContainerBeRestarted the original state here\n\t\t\t// could be:\n\t\t\t// * Waiting: There is no associated historical container and start failure reason record.\n\t\t\t// * Terminated: The container is terminated.\n\t\t\tcontinue\n\t\t}\n\t\tif status.State.Terminated != nil {\n\t\t\tstatus.LastTerminationState = status.State\n\t\t}\n\t\tstatus.State = v1.ContainerState{\n\t\t\tWaiting: \u0026v1.ContainerStateWaiting{\n\t\t\t\tReason: reason.Err.Error(),\n\t\t\t\tMessage: reason.Message,\n\t\t\t},\n\t\t}\n\t\tstatuses[container.Name] = status\n\t}\n\n\t// Sort the container statuses since clients of this interface expect the list\n\t// of containers in a pod has a deterministic order.\n\tif isInitContainer {\n\t\treturn kubetypes.SortStatusesOfInitContainers(pod, statuses)\n\t}\n\tcontainerStatuses := make([]v1.ContainerStatus, 0, len(statuses))\n\tfor _, status := range statuses {\n\t\tcontainerStatuses = append(containerStatuses, *status)\n\t}\n\n\tsort.Sort(kubetypes.SortedContainerStatuses(containerStatuses))\n\treturn containerStatuses\n}","line":{"from":1782,"to":2098}} {"id":100006835,"name":"ServeLogs","signature":"func (kl *Kubelet) ServeLogs(w http.ResponseWriter, req *http.Request)","file":"pkg/kubelet/kubelet_pods.go","code":"// ServeLogs returns logs of current machine.\nfunc (kl *Kubelet) ServeLogs(w http.ResponseWriter, req *http.Request) {\n\t// TODO: allowlist logs we are willing to serve\n\tkl.logServer.ServeHTTP(w, req)\n}","line":{"from":2100,"to":2104}} {"id":100006836,"name":"findContainer","signature":"func (kl *Kubelet) findContainer(ctx context.Context, podFullName string, podUID types.UID, containerName string) (*kubecontainer.Container, error)","file":"pkg/kubelet/kubelet_pods.go","code":"// findContainer finds and returns the container with the given pod ID, full name, and container name.\n// It returns nil if not found.\nfunc (kl *Kubelet) findContainer(ctx context.Context, podFullName string, podUID types.UID, containerName string) (*kubecontainer.Container, error) {\n\tpods, err := kl.containerRuntime.GetPods(ctx, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Resolve and type convert back again.\n\t// We need the static pod UID but the kubecontainer API works with types.UID.\n\tpodUID = types.UID(kl.podManager.TranslatePodUID(podUID))\n\tpod := kubecontainer.Pods(pods).FindPod(podFullName, podUID)\n\treturn pod.FindContainerByName(containerName), nil\n}","line":{"from":2106,"to":2118}} {"id":100006837,"name":"RunInContainer","signature":"func (kl *Kubelet) RunInContainer(ctx context.Context, podFullName string, podUID types.UID, containerName string, cmd []string) ([]byte, error)","file":"pkg/kubelet/kubelet_pods.go","code":"// RunInContainer runs a command in a container, returns the combined stdout, stderr as an array of bytes\nfunc (kl *Kubelet) RunInContainer(ctx context.Context, podFullName string, podUID types.UID, containerName string, cmd []string) ([]byte, error) {\n\tcontainer, err := kl.findContainer(ctx, podFullName, podUID, containerName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif container == nil {\n\t\treturn nil, fmt.Errorf(\"container not found (%q)\", containerName)\n\t}\n\t// TODO(tallclair): Pass a proper timeout value.\n\treturn kl.runner.RunInContainer(ctx, container.ID, cmd, 0)\n}","line":{"from":2120,"to":2131}} {"id":100006838,"name":"GetExec","signature":"func (kl *Kubelet) GetExec(ctx context.Context, podFullName string, podUID types.UID, containerName string, cmd []string, streamOpts remotecommandserver.Options) (*url.URL, error)","file":"pkg/kubelet/kubelet_pods.go","code":"// GetExec gets the URL the exec will be served from, or nil if the Kubelet will serve it.\nfunc (kl *Kubelet) GetExec(ctx context.Context, podFullName string, podUID types.UID, containerName string, cmd []string, streamOpts remotecommandserver.Options) (*url.URL, error) {\n\tcontainer, err := kl.findContainer(ctx, podFullName, podUID, containerName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif container == nil {\n\t\treturn nil, fmt.Errorf(\"container not found (%q)\", containerName)\n\t}\n\treturn kl.streamingRuntime.GetExec(ctx, container.ID, cmd, streamOpts.Stdin, streamOpts.Stdout, streamOpts.Stderr, streamOpts.TTY)\n}","line":{"from":2133,"to":2143}} {"id":100006839,"name":"GetAttach","signature":"func (kl *Kubelet) GetAttach(ctx context.Context, podFullName string, podUID types.UID, containerName string, streamOpts remotecommandserver.Options) (*url.URL, error)","file":"pkg/kubelet/kubelet_pods.go","code":"// GetAttach gets the URL the attach will be served from, or nil if the Kubelet will serve it.\nfunc (kl *Kubelet) GetAttach(ctx context.Context, podFullName string, podUID types.UID, containerName string, streamOpts remotecommandserver.Options) (*url.URL, error) {\n\tcontainer, err := kl.findContainer(ctx, podFullName, podUID, containerName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif container == nil {\n\t\treturn nil, fmt.Errorf(\"container %s not found in pod %s\", containerName, podFullName)\n\t}\n\n\t// The TTY setting for attach must match the TTY setting in the initial container configuration,\n\t// since whether the process is running in a TTY cannot be changed after it has started. We\n\t// need the api.Pod to get the TTY status.\n\tpod, found := kl.GetPodByFullName(podFullName)\n\tif !found || (string(podUID) != \"\" \u0026\u0026 pod.UID != podUID) {\n\t\treturn nil, fmt.Errorf(\"pod %s not found\", podFullName)\n\t}\n\tcontainerSpec := kubecontainer.GetContainerSpec(pod, containerName)\n\tif containerSpec == nil {\n\t\treturn nil, fmt.Errorf(\"container %s not found in pod %s\", containerName, podFullName)\n\t}\n\ttty := containerSpec.TTY\n\n\treturn kl.streamingRuntime.GetAttach(ctx, container.ID, streamOpts.Stdin, streamOpts.Stdout, streamOpts.Stderr, tty)\n}","line":{"from":2145,"to":2169}} {"id":100006840,"name":"GetPortForward","signature":"func (kl *Kubelet) GetPortForward(ctx context.Context, podName, podNamespace string, podUID types.UID, portForwardOpts portforward.V4Options) (*url.URL, error)","file":"pkg/kubelet/kubelet_pods.go","code":"// GetPortForward gets the URL the port-forward will be served from, or nil if the Kubelet will serve it.\nfunc (kl *Kubelet) GetPortForward(ctx context.Context, podName, podNamespace string, podUID types.UID, portForwardOpts portforward.V4Options) (*url.URL, error) {\n\tpods, err := kl.containerRuntime.GetPods(ctx, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Resolve and type convert back again.\n\t// We need the static pod UID but the kubecontainer API works with types.UID.\n\tpodUID = types.UID(kl.podManager.TranslatePodUID(podUID))\n\tpodFullName := kubecontainer.BuildPodFullName(podName, podNamespace)\n\tpod := kubecontainer.Pods(pods).FindPod(podFullName, podUID)\n\tif pod.IsEmpty() {\n\t\treturn nil, fmt.Errorf(\"pod not found (%q)\", podFullName)\n\t}\n\n\treturn kl.streamingRuntime.GetPortForward(ctx, podName, podNamespace, podUID, portForwardOpts.Ports)\n}","line":{"from":2171,"to":2187}} {"id":100006841,"name":"cleanupOrphanedPodCgroups","signature":"func (kl *Kubelet) cleanupOrphanedPodCgroups(pcm cm.PodContainerManager, cgroupPods map[types.UID]cm.CgroupName, possiblyRunningPods map[types.UID]sets.Empty)","file":"pkg/kubelet/kubelet_pods.go","code":"// cleanupOrphanedPodCgroups removes cgroups that should no longer exist.\n// it reconciles the cached state of cgroupPods with the specified list of runningPods\nfunc (kl *Kubelet) cleanupOrphanedPodCgroups(pcm cm.PodContainerManager, cgroupPods map[types.UID]cm.CgroupName, possiblyRunningPods map[types.UID]sets.Empty) {\n\t// Iterate over all the found pods to verify if they should be running\n\tfor uid, val := range cgroupPods {\n\t\t// if the pod is in the running set, its not a candidate for cleanup\n\t\tif _, ok := possiblyRunningPods[uid]; ok {\n\t\t\tcontinue\n\t\t}\n\n\t\t// If volumes have not been unmounted/detached, do not delete the cgroup\n\t\t// so any memory backed volumes don't have their charges propagated to the\n\t\t// parent croup. If the volumes still exist, reduce the cpu shares for any\n\t\t// process in the cgroup to the minimum value while we wait. if the kubelet\n\t\t// is configured to keep terminated volumes, we will delete the cgroup and not block.\n\t\tif podVolumesExist := kl.podVolumesExist(uid); podVolumesExist \u0026\u0026 !kl.keepTerminatedPodVolumes {\n\t\t\tklog.V(3).InfoS(\"Orphaned pod found, but volumes not yet removed. Reducing cpu to minimum\", \"podUID\", uid)\n\t\t\tif err := pcm.ReduceCPULimits(val); err != nil {\n\t\t\t\tklog.InfoS(\"Failed to reduce cpu time for pod pending volume cleanup\", \"podUID\", uid, \"err\", err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tklog.V(3).InfoS(\"Orphaned pod found, removing pod cgroups\", \"podUID\", uid)\n\t\t// Destroy all cgroups of pod that should not be running,\n\t\t// by first killing all the attached processes to these cgroups.\n\t\t// We ignore errors thrown by the method, as the housekeeping loop would\n\t\t// again try to delete these unwanted pod cgroups\n\t\tgo pcm.Destroy(val)\n\t}\n}","line":{"from":2189,"to":2218}} {"id":100006842,"name":"enableHostUserNamespace","signature":"func (kl *Kubelet) enableHostUserNamespace(ctx context.Context, pod *v1.Pod) bool","file":"pkg/kubelet/kubelet_pods.go","code":"// enableHostUserNamespace determines if the host user namespace should be used by the container runtime.\n// Returns true if the pod is using a host pid, pic, or network namespace, the pod is using a non-namespaced\n// capability, the pod contains a privileged container, or the pod has a host path volume.\n//\n// NOTE: when if a container shares any namespace with another container it must also share the user namespace\n// or it will not have the correct capabilities in the namespace. This means that host user namespace\n// is enabled per pod, not per container.\nfunc (kl *Kubelet) enableHostUserNamespace(ctx context.Context, pod *v1.Pod) bool {\n\tif kubecontainer.HasPrivilegedContainer(pod) || hasHostNamespace(pod) ||\n\t\thasHostVolume(pod) || hasNonNamespacedCapability(pod) || kl.hasHostMountPVC(ctx, pod) {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":2220,"to":2233}} {"id":100006843,"name":"hasNonNamespacedCapability","signature":"func hasNonNamespacedCapability(pod *v1.Pod) bool","file":"pkg/kubelet/kubelet_pods.go","code":"// hasNonNamespacedCapability returns true if MKNOD, SYS_TIME, or SYS_MODULE is requested for any container.\nfunc hasNonNamespacedCapability(pod *v1.Pod) bool {\n\tfor _, c := range pod.Spec.Containers {\n\t\tif c.SecurityContext != nil \u0026\u0026 c.SecurityContext.Capabilities != nil {\n\t\t\tfor _, cap := range c.SecurityContext.Capabilities.Add {\n\t\t\t\tif cap == \"MKNOD\" || cap == \"SYS_TIME\" || cap == \"SYS_MODULE\" {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":2235,"to":2248}} {"id":100006844,"name":"hasHostVolume","signature":"func hasHostVolume(pod *v1.Pod) bool","file":"pkg/kubelet/kubelet_pods.go","code":"// hasHostVolume returns true if the pod spec has a HostPath volume.\nfunc hasHostVolume(pod *v1.Pod) bool {\n\tfor _, v := range pod.Spec.Volumes {\n\t\tif v.HostPath != nil {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":2250,"to":2258}} {"id":100006845,"name":"hasHostNamespace","signature":"func hasHostNamespace(pod *v1.Pod) bool","file":"pkg/kubelet/kubelet_pods.go","code":"// hasHostNamespace returns true if hostIPC, hostNetwork, or hostPID are set to true.\nfunc hasHostNamespace(pod *v1.Pod) bool {\n\tif pod.Spec.SecurityContext == nil {\n\t\treturn false\n\t}\n\treturn pod.Spec.HostIPC || pod.Spec.HostNetwork || pod.Spec.HostPID\n}","line":{"from":2260,"to":2266}} {"id":100006846,"name":"hasHostMountPVC","signature":"func (kl *Kubelet) hasHostMountPVC(ctx context.Context, pod *v1.Pod) bool","file":"pkg/kubelet/kubelet_pods.go","code":"// hasHostMountPVC returns true if a PVC is referencing a HostPath volume.\nfunc (kl *Kubelet) hasHostMountPVC(ctx context.Context, pod *v1.Pod) bool {\n\tfor _, volume := range pod.Spec.Volumes {\n\t\tpvcName := \"\"\n\t\tswitch {\n\t\tcase volume.PersistentVolumeClaim != nil:\n\t\t\tpvcName = volume.PersistentVolumeClaim.ClaimName\n\t\tcase volume.Ephemeral != nil:\n\t\t\tpvcName = ephemeral.VolumeClaimName(pod, \u0026volume)\n\t\tdefault:\n\t\t\tcontinue\n\t\t}\n\t\tpvc, err := kl.kubeClient.CoreV1().PersistentVolumeClaims(pod.Namespace).Get(ctx, pvcName, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\tklog.InfoS(\"Unable to retrieve pvc\", \"pvc\", klog.KRef(pod.Namespace, pvcName), \"err\", err)\n\t\t\tcontinue\n\t\t}\n\t\tif pvc != nil {\n\t\t\treferencedVolume, err := kl.kubeClient.CoreV1().PersistentVolumes().Get(ctx, pvc.Spec.VolumeName, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\tklog.InfoS(\"Unable to retrieve pv\", \"pvName\", pvc.Spec.VolumeName, \"err\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif referencedVolume != nil \u0026\u0026 referencedVolume.Spec.HostPath != nil {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":2268,"to":2297}} {"id":100006847,"name":"defaultPodLimitsForDownwardAPI","signature":"func (kl *Kubelet) defaultPodLimitsForDownwardAPI(pod *v1.Pod, container *v1.Container) (*v1.Pod, *v1.Container, error)","file":"pkg/kubelet/kubelet_resources.go","code":"// defaultPodLimitsForDownwardAPI copies the input pod, and optional container,\n// and applies default resource limits. it returns a copy of the input pod,\n// and a copy of the input container (if specified) with default limits\n// applied. if a container has no limit specified, it will default the limit to\n// the node allocatable.\n// TODO: if/when we have pod level resources, we need to update this function\n// to use those limits instead of node allocatable.\nfunc (kl *Kubelet) defaultPodLimitsForDownwardAPI(pod *v1.Pod, container *v1.Container) (*v1.Pod, *v1.Container, error) {\n\tif pod == nil {\n\t\treturn nil, nil, fmt.Errorf(\"invalid input, pod cannot be nil\")\n\t}\n\n\tnode, err := kl.getNodeAnyWay()\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to find node object, expected a node\")\n\t}\n\tallocatable := node.Status.Allocatable\n\tklog.InfoS(\"Allocatable\", \"allocatable\", allocatable)\n\toutputPod := pod.DeepCopy()\n\tfor idx := range outputPod.Spec.Containers {\n\t\tresource.MergeContainerResourceLimits(\u0026outputPod.Spec.Containers[idx], allocatable)\n\t}\n\n\tvar outputContainer *v1.Container\n\tif container != nil {\n\t\toutputContainer = container.DeepCopy()\n\t\tresource.MergeContainerResourceLimits(outputContainer, allocatable)\n\t}\n\treturn outputPod, outputContainer, nil\n}","line":{"from":28,"to":57}} {"id":100006848,"name":"ServeHTTP","signature":"func (journalServer) ServeHTTP(w http.ResponseWriter, req *http.Request)","file":"pkg/kubelet/kubelet_server_journal.go","code":"// ServeHTTP translates HTTP query parameters into arguments to be passed\n// to journalctl on the current system. It supports content-encoding of\n// gzip to reduce total content size.\nfunc (journalServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tvar out io.Writer = w\n\n\tnlq, errs := newNodeLogQuery(req.URL.Query())\n\tif len(errs) \u003e 0 {\n\t\thttp.Error(w, errs.ToAggregate().Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// TODO: Also set a response header that indicates how the request's query was resolved,\n\t// e.g. \"kube-log-source: journal://foobar?arg1=value\" or \"kube-log-source: file:///var/log/foobar.log\"\n\tw.Header().Set(\"Content-Type\", \"text/plain;charset=UTF-8\")\n\tif req.Header.Get(\"Accept-Encoding\") == \"gzip\" {\n\t\tw.Header().Set(\"Content-Encoding\", \"gzip\")\n\n\t\tgz, err := gzip.NewWriterLevel(out, gzip.BestSpeed)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(w, \"\\nfailed to get gzip writer: %v\\n\", err)\n\t\t\treturn\n\t\t}\n\t\tdefer gz.Close()\n\t\tout = gz\n\t}\n\tnlq.Copy(out)\n}","line":{"from":64,"to":91}} {"id":100006849,"name":"newNodeLogQuery","signature":"func newNodeLogQuery(query url.Values) (*nodeLogQuery, field.ErrorList)","file":"pkg/kubelet/kubelet_server_journal.go","code":"// newNodeLogQuery parses query values and converts all known options into nodeLogQuery\nfunc newNodeLogQuery(query url.Values) (*nodeLogQuery, field.ErrorList) {\n\tallErrs := field.ErrorList{}\n\tvar nlq nodeLogQuery\n\tvar err error\n\n\tqueries, ok := query[\"query\"]\n\tif len(queries) \u003e 0 {\n\t\tfor _, q := range queries {\n\t\t\t// The presence of / or \\ is a hint that the query is for a log file. If the query is for foo.log without a\n\t\t\t// slash prefix, the heuristics will still return the file contents.\n\t\t\tif strings.ContainsAny(q, `/\\`) {\n\t\t\t\tnlq.Files = append(nlq.Files, q)\n\t\t\t} else if strings.TrimSpace(q) != \"\" { // Prevent queries with just spaces\n\t\t\t\tnlq.Services = append(nlq.Services, q)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Prevent specifying an empty or blank space query.\n\t// Example: kubectl get --raw /api/v1/nodes/$node/proxy/logs?query=\" \"\n\tif ok \u0026\u0026 (len(nlq.Files) == 0 \u0026\u0026 len(nlq.Services) == 0) {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"query\"), queries, \"query cannot be empty\"))\n\t}\n\n\tvar sinceTime time.Time\n\tsinceTimeValue := query.Get(\"sinceTime\")\n\tif len(sinceTimeValue) \u003e 0 {\n\t\tsinceTime, err = time.Parse(time.RFC3339, sinceTimeValue)\n\t\tif err != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"sinceTime\"), sinceTimeValue, \"invalid time format\"))\n\t\t} else {\n\t\t\tnlq.SinceTime = \u0026sinceTime\n\t\t}\n\t}\n\n\tvar untilTime time.Time\n\tuntilTimeValue := query.Get(\"untilTime\")\n\tif len(untilTimeValue) \u003e 0 {\n\t\tuntilTime, err = time.Parse(time.RFC3339, untilTimeValue)\n\t\tif err != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"untilTime\"), untilTimeValue, \"invalid time format\"))\n\t\t} else {\n\t\t\tnlq.UntilTime = \u0026untilTime\n\t\t}\n\t}\n\n\tvar boot int\n\tbootValue := query.Get(\"boot\")\n\tif len(bootValue) \u003e 0 {\n\t\tboot, err = strconv.Atoi(bootValue)\n\t\tif err != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"boot\"), bootValue, err.Error()))\n\t\t} else {\n\t\t\tnlq.Boot = \u0026boot\n\t\t}\n\t}\n\n\tvar tailLines int\n\ttailLinesValue := query.Get(\"tailLines\")\n\tif len(tailLinesValue) \u003e 0 {\n\t\ttailLines, err = strconv.Atoi(tailLinesValue)\n\t\tif err != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"tailLines\"), tailLinesValue, err.Error()))\n\t\t} else {\n\t\t\tnlq.TailLines = \u0026tailLines\n\t\t}\n\t}\n\n\tpattern := query.Get(\"pattern\")\n\tif len(pattern) \u003e 0 {\n\t\tnlq.Pattern = pattern\n\t}\n\n\tif len(allErrs) \u003e 0 {\n\t\treturn nil, allErrs\n\t}\n\n\tif reflect.DeepEqual(nlq, nodeLogQuery{}) {\n\t\treturn nil, allErrs\n\t}\n\n\treturn \u0026nlq, allErrs\n}","line":{"from":119,"to":202}} {"id":100006850,"name":"validateServices","signature":"func validateServices(services []string) field.ErrorList","file":"pkg/kubelet/kubelet_server_journal.go","code":"func validateServices(services []string) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tfor _, s := range services {\n\t\tif err := safeServiceName(s); err != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"query\"), s, err.Error()))\n\t\t}\n\t}\n\n\tif len(services) \u003e maxServices {\n\t\tallErrs = append(allErrs, field.TooMany(field.NewPath(\"query\"), len(services), maxServices))\n\t}\n\treturn allErrs\n}","line":{"from":204,"to":217}} {"id":100006851,"name":"validate","signature":"func (n *nodeLogQuery) validate() field.ErrorList","file":"pkg/kubelet/kubelet_server_journal.go","code":"func (n *nodeLogQuery) validate() field.ErrorList {\n\tallErrs := validateServices(n.Services)\n\tswitch {\n\tcase len(n.Files) == 0 \u0026\u0026 len(n.Services) == 0:\n\t\tallErrs = append(allErrs, field.Required(field.NewPath(\"query\"), \"cannot be empty with options\"))\n\tcase len(n.Files) \u003e 0 \u0026\u0026 len(n.Services) \u003e 0:\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"query\"), fmt.Sprintf(\"%v, %v\", n.Files, n.Services),\n\t\t\t\"cannot specify a file and service\"))\n\tcase len(n.Files) \u003e 1:\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"query\"), n.Files, \"cannot specify more than one file\"))\n\tcase len(n.Files) == 1 \u0026\u0026 n.options != (options{}):\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"query\"), n.Files, \"cannot specify file with options\"))\n\tcase len(n.Files) == 1:\n\t\tif fullLogFilename, err := securejoin.SecureJoin(nodeLogDir, n.Files[0]); err != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"query\"), n.Files, err.Error()))\n\t\t} else if _, err := os.Stat(fullLogFilename); err != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"query\"), n.Files, err.Error()))\n\t\t}\n\t}\n\n\tif n.SinceTime != nil \u0026\u0026 n.UntilTime != nil \u0026\u0026 (n.SinceTime.After(*n.UntilTime)) {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"untilTime\"), n.UntilTime, \"must be after `sinceTime`\"))\n\t}\n\n\tif n.Boot != nil \u0026\u0026 runtime.GOOS == \"windows\" {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"boot\"), *n.Boot, \"boot is not supported on Windows\"))\n\t}\n\n\tif n.Boot != nil \u0026\u0026 *n.Boot \u003e 0 {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"boot\"), *n.Boot, \"must be less than 1\"))\n\t}\n\n\tif n.TailLines != nil {\n\t\tif err := utilvalidation.IsInRange((int)(*n.TailLines), 0, maxTailLines); err != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"tailLines\"), *n.TailLines, err[0]))\n\t\t}\n\t}\n\n\tif _, err := syntax.Parse(n.Pattern, syntax.Perl); err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"pattern\"), n.Pattern, err.Error()))\n\t}\n\n\treturn allErrs\n}","line":{"from":219,"to":262}} {"id":100006852,"name":"Copy","signature":"func (n *nodeLogQuery) Copy(w io.Writer)","file":"pkg/kubelet/kubelet_server_journal.go","code":"// Copy streams the contents of the OS specific logging command executed with the current args to the provided\n// writer. If an error occurs a line is written to the output.\nfunc (n *nodeLogQuery) Copy(w io.Writer) {\n\t// set the deadline to the maximum across both runs\n\tctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(30*time.Second))\n\tdefer cancel()\n\tboot := int(0)\n\tif n.Boot != nil {\n\t\tboot = *n.Boot\n\t}\n\tn.copyForBoot(ctx, w, boot)\n}","line":{"from":264,"to":275}} {"id":100006853,"name":"copyForBoot","signature":"func (n *nodeLogQuery) copyForBoot(ctx context.Context, w io.Writer, previousBoot int)","file":"pkg/kubelet/kubelet_server_journal.go","code":"// copyForBoot invokes the OS specific logging command with the provided args\nfunc (n *nodeLogQuery) copyForBoot(ctx context.Context, w io.Writer, previousBoot int) {\n\tif ctx.Err() != nil {\n\t\treturn\n\t}\n\tnativeLoggers, fileLoggers := n.splitNativeVsFileLoggers(ctx)\n\tif len(nativeLoggers) \u003e 0 {\n\t\tn.copyServiceLogs(ctx, w, nativeLoggers, previousBoot)\n\t}\n\n\tif len(fileLoggers) \u003e 0 \u0026\u0026 n.options != (options{}) {\n\t\tfmt.Fprintf(w, \"\\noptions present and query resolved to log files for %v\\ntry without specifying options\\n\",\n\t\t\tfileLoggers)\n\t\treturn\n\t}\n\n\tif len(fileLoggers) \u003e 0 {\n\t\tcopyFileLogs(ctx, w, fileLoggers)\n\t}\n}","line":{"from":277,"to":296}} {"id":100006854,"name":"splitNativeVsFileLoggers","signature":"func (n *nodeLogQuery) splitNativeVsFileLoggers(ctx context.Context) ([]string, []string)","file":"pkg/kubelet/kubelet_server_journal.go","code":"// splitNativeVsFileLoggers checks if each service logs to native OS logs or to a file and returns a list of services\n// that log natively vs maybe to a file\nfunc (n *nodeLogQuery) splitNativeVsFileLoggers(ctx context.Context) ([]string, []string) {\n\tvar nativeLoggers []string\n\tvar fileLoggers []string\n\n\tfor _, service := range n.Services {\n\t\t// Check the journalctl output to figure if the service is using journald or not. This is not needed in the\n\t\t// Get-WinEvent case as the command returns an error if a service is not logging to the Application provider.\n\t\tif checkForNativeLogger(ctx, service) {\n\t\t\tnativeLoggers = append(nativeLoggers, service)\n\t\t} else {\n\t\t\tfileLoggers = append(fileLoggers, service)\n\t\t}\n\t}\n\treturn nativeLoggers, fileLoggers\n}","line":{"from":298,"to":314}} {"id":100006855,"name":"copyServiceLogs","signature":"func (n *nodeLogQuery) copyServiceLogs(ctx context.Context, w io.Writer, services []string, previousBoot int)","file":"pkg/kubelet/kubelet_server_journal.go","code":"// copyServiceLogs invokes journalctl or Get-WinEvent with the provided args. Note that\n// services are explicitly passed here to account for the heuristics.\nfunc (n *nodeLogQuery) copyServiceLogs(ctx context.Context, w io.Writer, services []string, previousBoot int) {\n\tcmdStr, args, err := getLoggingCmd(n, services)\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"\\nfailed to get logging cmd: %v\\n\", err)\n\t\treturn\n\t}\n\tcmd := exec.CommandContext(ctx, cmdStr, args...)\n\tcmd.Stdout = w\n\tcmd.Stderr = w\n\n\tif err := cmd.Run(); err != nil {\n\t\tif _, ok := err.(*exec.ExitError); ok {\n\t\t\treturn\n\t\t}\n\t\tif previousBoot == 0 {\n\t\t\tfmt.Fprintf(w, \"\\nerror: journal output not available\\n\")\n\t\t}\n\t}\n}","line":{"from":316,"to":336}} {"id":100006856,"name":"copyFileLogs","signature":"func copyFileLogs(ctx context.Context, w io.Writer, services []string)","file":"pkg/kubelet/kubelet_server_journal.go","code":"// copyFileLogs loops over all the services and attempts to collect the file logs of each service\nfunc copyFileLogs(ctx context.Context, w io.Writer, services []string) {\n\tif ctx.Err() != nil {\n\t\tfmt.Fprintf(w, \"\\ncontext error: %v\\n\", ctx.Err())\n\t\treturn\n\t}\n\n\tfor _, service := range services {\n\t\theuristicsCopyFileLogs(ctx, w, service)\n\t}\n}","line":{"from":338,"to":348}} {"id":100006857,"name":"heuristicsCopyFileLogs","signature":"func heuristicsCopyFileLogs(ctx context.Context, w io.Writer, service string)","file":"pkg/kubelet/kubelet_server_journal.go","code":"// heuristicsCopyFileLogs attempts to collect logs from either\n// /var/log/service\n// /var/log/service.log or\n// /var/log/service/service.log or\n// in that order stopping on first success.\nfunc heuristicsCopyFileLogs(ctx context.Context, w io.Writer, service string) {\n\tlogFileNames := [3]string{\n\t\tfmt.Sprintf(\"%s\", service),\n\t\tfmt.Sprintf(\"%s.log\", service),\n\t\tfmt.Sprintf(\"%s/%s.log\", service, service),\n\t}\n\n\tvar err error\n\tfor _, logFileName := range logFileNames {\n\t\tvar logFile string\n\t\tlogFile, err = securejoin.SecureJoin(nodeLogDir, logFileName)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\terr = heuristicsCopyFileLog(ctx, w, logFile)\n\t\tif err == nil {\n\t\t\tbreak\n\t\t} else if errors.Is(err, os.ErrNotExist) {\n\t\t\tcontinue\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif err != nil {\n\t\t// If the last error was file not found it implies that no log file was found for the service\n\t\tif errors.Is(err, os.ErrNotExist) {\n\t\t\tfmt.Fprintf(w, \"\\nlog not found for %s\\n\", service)\n\t\t\treturn\n\t\t}\n\t\tfmt.Fprintf(w, \"\\nerror getting log for %s: %v\\n\", service, err)\n\t}\n}","line":{"from":350,"to":387}} {"id":100006858,"name":"Read","signature":"func (r *readerCtx) Read(p []byte) (n int, err error)","file":"pkg/kubelet/kubelet_server_journal.go","code":"func (r *readerCtx) Read(p []byte) (n int, err error) {\n\tif err := r.ctx.Err(); err != nil {\n\t\treturn 0, err\n\t}\n\treturn r.Reader.Read(p)\n}","line":{"from":395,"to":400}} {"id":100006859,"name":"newReaderCtx","signature":"func newReaderCtx(ctx context.Context, r io.Reader) io.Reader","file":"pkg/kubelet/kubelet_server_journal.go","code":"// newReaderCtx gets a context-aware io.Reader\nfunc newReaderCtx(ctx context.Context, r io.Reader) io.Reader {\n\treturn \u0026readerCtx{\n\t\tctx: ctx,\n\t\tReader: r,\n\t}\n}","line":{"from":402,"to":408}} {"id":100006860,"name":"heuristicsCopyFileLog","signature":"func heuristicsCopyFileLog(ctx context.Context, w io.Writer, logFile string) error","file":"pkg/kubelet/kubelet_server_journal.go","code":"// heuristicsCopyFileLog returns the contents of the given logFile\nfunc heuristicsCopyFileLog(ctx context.Context, w io.Writer, logFile string) error {\n\tfInfo, err := os.Stat(logFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// This is to account for the heuristics where logs for service foo\n\t// could be in /var/log/foo/\n\tif fInfo.IsDir() {\n\t\treturn os.ErrNotExist\n\t}\n\n\tf, err := os.Open(logFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tif _, err := io.Copy(w, newReaderCtx(ctx, f)); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":410,"to":432}} {"id":100006861,"name":"safeServiceName","signature":"func safeServiceName(s string) error","file":"pkg/kubelet/kubelet_server_journal.go","code":"func safeServiceName(s string) error {\n\t// Max length of a service name is 256 across supported OSes\n\tif len(s) \u003e maxServiceLength {\n\t\treturn fmt.Errorf(\"length must be less than 100\")\n\t}\n\n\tif reServiceNameUnsafeCharacters.MatchString(s) {\n\t\treturn fmt.Errorf(\"input contains unsupported characters\")\n\t}\n\treturn nil\n}","line":{"from":434,"to":444}} {"id":100006862,"name":"getLoggingCmd","signature":"func getLoggingCmd(n *nodeLogQuery, services []string) (string, []string, error)","file":"pkg/kubelet/kubelet_server_journal_linux.go","code":"// getLoggingCmd returns the journalctl cmd and arguments for the given nodeLogQuery and boot. Note that\n// services are explicitly passed here to account for the heuristics\nfunc getLoggingCmd(n *nodeLogQuery, services []string) (string, []string, error) {\n\targs := []string{\n\t\t\"--utc\",\n\t\t\"--no-pager\",\n\t\t\"--output=short-precise\",\n\t}\n\tif n.SinceTime != nil {\n\t\targs = append(args, fmt.Sprintf(\"--since=%s\", n.SinceTime.Format(dateLayout)))\n\t}\n\tif n.UntilTime != nil {\n\t\targs = append(args, fmt.Sprintf(\"--until=%s\", n.SinceTime.Format(dateLayout)))\n\t}\n\tif n.TailLines != nil {\n\t\targs = append(args, \"--pager-end\", fmt.Sprintf(\"--lines=%d\", *n.TailLines))\n\t}\n\tfor _, service := range services {\n\t\tif len(service) \u003e 0 {\n\t\t\targs = append(args, \"--unit=\"+service)\n\t\t}\n\t}\n\tif len(n.Pattern) \u003e 0 {\n\t\targs = append(args, \"--grep=\"+n.Pattern)\n\t}\n\n\tif n.Boot != nil {\n\t\targs = append(args, \"--boot\", fmt.Sprintf(\"%d\", *n.Boot))\n\t}\n\n\treturn \"journalctl\", args, nil\n}","line":{"from":28,"to":59}} {"id":100006863,"name":"checkForNativeLogger","signature":"func checkForNativeLogger(ctx context.Context, service string) bool","file":"pkg/kubelet/kubelet_server_journal_linux.go","code":"// checkForNativeLogger checks journalctl output for a service\nfunc checkForNativeLogger(ctx context.Context, service string) bool {\n\t// This will return all the journald units\n\tcmd := exec.CommandContext(ctx, \"journalctl\", []string{\"--field\", \"_SYSTEMD_UNIT\"}...)\n\toutput, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\t// Returning false to allow checking if the service is logging to a file\n\t\treturn false\n\t}\n\n\t// journalctl won't return an error if we try to fetch logs for a non-existent service,\n\t// hence we search for it in the list of services known to journalctl\n\treturn strings.Contains(string(output), service+\".service\")\n}","line":{"from":61,"to":74}} {"id":100006864,"name":"getLoggingCmd","signature":"func getLoggingCmd(n *nodeLogQuery, services []string) (string, []string, error)","file":"pkg/kubelet/kubelet_server_journal_others.go","code":"// getLoggingCmd on unsupported operating systems returns the echo command and a warning message (as strings)\nfunc getLoggingCmd(n *nodeLogQuery, services []string) (string, []string, error) {\n\treturn \"\", []string{}, errors.New(\"Operating System Not Supported\")\n}","line":{"from":26,"to":29}} {"id":100006865,"name":"checkForNativeLogger","signature":"func checkForNativeLogger(ctx context.Context, service string) bool","file":"pkg/kubelet/kubelet_server_journal_others.go","code":"// checkForNativeLogger on unsupported operating systems returns false\nfunc checkForNativeLogger(ctx context.Context, service string) bool {\n\treturn false\n}","line":{"from":31,"to":34}} {"id":100006866,"name":"getLoggingCmd","signature":"func getLoggingCmd(n *nodeLogQuery, services []string) (string, []string, error)","file":"pkg/kubelet/kubelet_server_journal_windows.go","code":"// getLoggingCmd returns the powershell cmd and arguments for the given nodeLogQuery and boot\nfunc getLoggingCmd(n *nodeLogQuery, services []string) (string, []string, error) {\n\targs := []string{\n\t\t\"-NonInteractive\",\n\t\t\"-ExecutionPolicy\", \"Bypass\",\n\t\t\"-Command\",\n\t}\n\n\tpsCmd := \"Get-WinEvent -FilterHashtable @{LogName='Application'\"\n\tif n.SinceTime != nil {\n\t\tpsCmd += fmt.Sprintf(\"; StartTime='%s'\", n.SinceTime.Format(dateLayout))\n\t}\n\tif n.UntilTime != nil {\n\t\tpsCmd += fmt.Sprintf(\"; EndTime='%s'\", n.UntilTime.Format(dateLayout))\n\t}\n\tvar providers []string\n\tfor _, service := range services {\n\t\tif len(service) \u003e 0 {\n\t\t\tproviders = append(providers, \"'\"+service+\"'\")\n\t\t}\n\t}\n\tif len(providers) \u003e 0 {\n\t\tpsCmd += fmt.Sprintf(\"; ProviderName=%s\", strings.Join(providers, \",\"))\n\t}\n\tpsCmd += \"}\"\n\tif n.TailLines != nil {\n\t\tpsCmd += fmt.Sprintf(\" -MaxEvents %d\", *n.TailLines)\n\t}\n\tpsCmd += \" | Sort-Object TimeCreated\"\n\tif len(n.Pattern) \u003e 0 {\n\t\tpsCmd += fmt.Sprintf(\" | Where-Object -Property Message -Match '%s'\", n.Pattern)\n\t}\n\tpsCmd += \" | Format-Table -AutoSize -Wrap\"\n\n\targs = append(args, psCmd)\n\n\treturn powershellExe, args, nil\n}","line":{"from":30,"to":67}} {"id":100006867,"name":"checkForNativeLogger","signature":"func checkForNativeLogger(ctx context.Context, service string) bool","file":"pkg/kubelet/kubelet_server_journal_windows.go","code":"// checkForNativeLogger always returns true for Windows\nfunc checkForNativeLogger(ctx context.Context, service string) bool {\n\tcmd := exec.CommandContext(ctx, powershellExe, []string{\n\t\t\"-NonInteractive\", \"-ExecutionPolicy\", \"Bypass\", \"-Command\",\n\t\tfmt.Sprintf(\"Get-WinEvent -ListProvider %s | Format-Table -AutoSize\", service)}...)\n\n\t_, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\t// Get-WinEvent will return ExitError if the service is not listed as a provider\n\t\tif _, ok := err.(*exec.ExitError); ok {\n\t\t\treturn false\n\t\t}\n\t\t// Other errors imply that CombinedOutput failed before the command was executed,\n\t\t// so lets to get the logs using Get-WinEvent at the call site instead of assuming\n\t\t// the service is logging to a file\n\t}\n\treturn true\n}","line":{"from":69,"to":86}} {"id":100006868,"name":"ListVolumesForPod","signature":"func (kl *Kubelet) ListVolumesForPod(podUID types.UID) (map[string]volume.Volume, bool)","file":"pkg/kubelet/kubelet_volumes.go","code":"// ListVolumesForPod returns a map of the mounted volumes for the given pod.\n// The key in the map is the OuterVolumeSpecName (i.e. pod.Spec.Volumes[x].Name)\nfunc (kl *Kubelet) ListVolumesForPod(podUID types.UID) (map[string]volume.Volume, bool) {\n\tvolumesToReturn := make(map[string]volume.Volume)\n\tpodVolumes := kl.volumeManager.GetMountedVolumesForPod(\n\t\tvolumetypes.UniquePodName(podUID))\n\tfor outerVolumeSpecName, volume := range podVolumes {\n\t\t// TODO: volume.Mounter could be nil if volume object is recovered\n\t\t// from reconciler's sync state process. PR 33616 will fix this problem\n\t\t// to create Mounter object when recovering volume state.\n\t\tif volume.Mounter == nil {\n\t\t\tcontinue\n\t\t}\n\t\tvolumesToReturn[outerVolumeSpecName] = volume.Mounter\n\t}\n\n\treturn volumesToReturn, len(volumesToReturn) \u003e 0\n}","line":{"from":37,"to":54}} {"id":100006869,"name":"ListBlockVolumesForPod","signature":"func (kl *Kubelet) ListBlockVolumesForPod(podUID types.UID) (map[string]volume.BlockVolume, bool)","file":"pkg/kubelet/kubelet_volumes.go","code":"// ListBlockVolumesForPod returns a map of the mounted volumes for the given\n// pod. The key in the map is the OuterVolumeSpecName (i.e.\n// pod.Spec.Volumes[x].Name)\nfunc (kl *Kubelet) ListBlockVolumesForPod(podUID types.UID) (map[string]volume.BlockVolume, bool) {\n\tvolumesToReturn := make(map[string]volume.BlockVolume)\n\tpodVolumes := kl.volumeManager.GetMountedVolumesForPod(\n\t\tvolumetypes.UniquePodName(podUID))\n\tfor outerVolumeSpecName, volume := range podVolumes {\n\t\t// TODO: volume.Mounter could be nil if volume object is recovered\n\t\t// from reconciler's sync state process. PR 33616 will fix this problem\n\t\t// to create Mounter object when recovering volume state.\n\t\tif volume.BlockVolumeMapper == nil {\n\t\t\tcontinue\n\t\t}\n\t\tvolumesToReturn[outerVolumeSpecName] = volume.BlockVolumeMapper\n\t}\n\n\treturn volumesToReturn, len(volumesToReturn) \u003e 0\n}","line":{"from":56,"to":74}} {"id":100006870,"name":"podVolumesExist","signature":"func (kl *Kubelet) podVolumesExist(podUID types.UID) bool","file":"pkg/kubelet/kubelet_volumes.go","code":"// podVolumesExist checks with the volume manager and returns true any of the\n// pods for the specified volume are mounted or are uncertain.\nfunc (kl *Kubelet) podVolumesExist(podUID types.UID) bool {\n\tif mountedVolumes :=\n\t\tkl.volumeManager.GetPossiblyMountedVolumesForPod(\n\t\t\tvolumetypes.UniquePodName(podUID)); len(mountedVolumes) \u003e 0 {\n\t\treturn true\n\t}\n\t// TODO: This checks pod volume paths and whether they are mounted. If checking returns error, podVolumesExist will return true\n\t// which means we consider volumes might exist and requires further checking.\n\t// There are some volume plugins such as flexvolume might not have mounts. See issue #61229\n\tvolumePaths, err := kl.getMountedVolumePathListFromDisk(podUID)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Pod found, but error occurred during checking mounted volumes from disk\", \"podUID\", podUID)\n\t\treturn true\n\t}\n\tif len(volumePaths) \u003e 0 {\n\t\tklog.V(4).InfoS(\"Pod found, but volumes are still mounted on disk\", \"podUID\", podUID, \"paths\", volumePaths)\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":76,"to":98}} {"id":100006871,"name":"newVolumeMounterFromPlugins","signature":"func (kl *Kubelet) newVolumeMounterFromPlugins(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error)","file":"pkg/kubelet/kubelet_volumes.go","code":"// newVolumeMounterFromPlugins attempts to find a plugin by volume spec, pod\n// and volume options and then creates a Mounter.\n// Returns a valid mounter or an error.\nfunc (kl *Kubelet) newVolumeMounterFromPlugins(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error) {\n\tplugin, err := kl.volumePluginMgr.FindPluginBySpec(spec)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't use volume plugins for %s: %v\", spec.Name(), err)\n\t}\n\tphysicalMounter, err := plugin.NewMounter(spec, pod, opts)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to instantiate mounter for volume: %s using plugin: %s with a root cause: %v\", spec.Name(), plugin.GetPluginName(), err)\n\t}\n\tklog.V(10).InfoS(\"Using volume plugin for mount\", \"volumePluginName\", plugin.GetPluginName(), \"volumeName\", spec.Name())\n\treturn physicalMounter, nil\n}","line":{"from":100,"to":114}} {"id":100006872,"name":"removeOrphanedPodVolumeDirs","signature":"func (kl *Kubelet) removeOrphanedPodVolumeDirs(uid types.UID) []error","file":"pkg/kubelet/kubelet_volumes.go","code":"// removeOrphanedPodVolumeDirs attempts to remove the pod volumes directory and\n// its subdirectories. There should be no files left under normal conditions\n// when this is called, so it effectively does a recursive rmdir instead of\n// RemoveAll to ensure it only removes directories and not regular files.\nfunc (kl *Kubelet) removeOrphanedPodVolumeDirs(uid types.UID) []error {\n\torphanVolumeErrors := []error{}\n\n\t// If there are still volume directories, attempt to rmdir them\n\tvolumePaths, err := kl.getPodVolumePathListFromDisk(uid)\n\tif err != nil {\n\t\torphanVolumeErrors = append(orphanVolumeErrors, fmt.Errorf(\"orphaned pod %q found, but error occurred during reading volume dir from disk: %v\", uid, err))\n\t\treturn orphanVolumeErrors\n\t}\n\tif len(volumePaths) \u003e 0 {\n\t\tfor _, volumePath := range volumePaths {\n\t\t\tif err := syscall.Rmdir(volumePath); err != nil {\n\t\t\t\torphanVolumeErrors = append(orphanVolumeErrors, fmt.Errorf(\"orphaned pod %q found, but failed to rmdir() volume at path %v: %v\", uid, volumePath, err))\n\t\t\t} else {\n\t\t\t\tklog.InfoS(\"Cleaned up orphaned volume from pod\", \"podUID\", uid, \"path\", volumePath)\n\t\t\t}\n\t\t}\n\t}\n\n\t// If there are any volume-subpaths, attempt to rmdir them\n\tsubpathVolumePaths, err := kl.getPodVolumeSubpathListFromDisk(uid)\n\tif err != nil {\n\t\torphanVolumeErrors = append(orphanVolumeErrors, fmt.Errorf(\"orphaned pod %q found, but error occurred during reading of volume-subpaths dir from disk: %v\", uid, err))\n\t\treturn orphanVolumeErrors\n\t}\n\tif len(subpathVolumePaths) \u003e 0 {\n\t\tfor _, subpathVolumePath := range subpathVolumePaths {\n\t\t\tif err := syscall.Rmdir(subpathVolumePath); err != nil {\n\t\t\t\torphanVolumeErrors = append(orphanVolumeErrors, fmt.Errorf(\"orphaned pod %q found, but failed to rmdir() subpath at path %v: %v\", uid, subpathVolumePath, err))\n\t\t\t} else {\n\t\t\t\tklog.InfoS(\"Cleaned up orphaned volume subpath from pod\", \"podUID\", uid, \"path\", subpathVolumePath)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Remove any remaining subdirectories along with the volumes directory itself.\n\t// Fail if any regular files are encountered.\n\tpodVolDir := kl.getPodVolumesDir(uid)\n\tif err := removeall.RemoveDirsOneFilesystem(kl.mounter, podVolDir); err != nil {\n\t\torphanVolumeErrors = append(orphanVolumeErrors, fmt.Errorf(\"orphaned pod %q found, but error occurred when trying to remove the volumes dir: %v\", uid, err))\n\t} else {\n\t\tklog.InfoS(\"Cleaned up orphaned pod volumes dir\", \"podUID\", uid, \"path\", podVolDir)\n\t}\n\n\treturn orphanVolumeErrors\n}","line":{"from":116,"to":165}} {"id":100006873,"name":"cleanupOrphanedPodDirs","signature":"func (kl *Kubelet) cleanupOrphanedPodDirs(pods []*v1.Pod, runningPods []*kubecontainer.Pod) error","file":"pkg/kubelet/kubelet_volumes.go","code":"// cleanupOrphanedPodDirs removes the volumes of pods that should not be\n// running and that have no containers running. Note that we roll up logs here since it runs in the main loop.\nfunc (kl *Kubelet) cleanupOrphanedPodDirs(pods []*v1.Pod, runningPods []*kubecontainer.Pod) error {\n\tallPods := sets.NewString()\n\tfor _, pod := range pods {\n\t\tallPods.Insert(string(pod.UID))\n\t}\n\tfor _, pod := range runningPods {\n\t\tallPods.Insert(string(pod.ID))\n\t}\n\n\tfound, err := kl.listPodsFromDisk()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\torphanRemovalErrors := []error{}\n\torphanVolumeErrors := []error{}\n\tvar totalPods, errorPods int\n\n\tfor _, uid := range found {\n\t\tif allPods.Has(string(uid)) {\n\t\t\tcontinue\n\t\t}\n\n\t\ttotalPods++\n\n\t\t// If volumes have not been unmounted/detached, do not delete directory.\n\t\t// Doing so may result in corruption of data.\n\t\t// TODO: getMountedVolumePathListFromDisk() call may be redundant with\n\t\t// kl.getPodVolumePathListFromDisk(). Can this be cleaned up?\n\t\tif podVolumesExist := kl.podVolumesExist(uid); podVolumesExist {\n\t\t\terrorPods++\n\t\t\tklog.V(3).InfoS(\"Orphaned pod found, but volumes are not cleaned up\", \"podUID\", uid)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Attempt to remove the pod volumes directory and its subdirs\n\t\tpodVolumeErrors := kl.removeOrphanedPodVolumeDirs(uid)\n\t\tif len(podVolumeErrors) \u003e 0 {\n\t\t\terrorPods++\n\t\t\torphanVolumeErrors = append(orphanVolumeErrors, podVolumeErrors...)\n\t\t\t// Not all volumes were removed, so don't clean up the pod directory yet. It is likely\n\t\t\t// that there are still mountpoints or files left which could cause removal of the pod\n\t\t\t// directory to fail below.\n\t\t\t// Errors for all removal operations have already been recorded, so don't add another\n\t\t\t// one here.\n\t\t\tcontinue\n\t\t}\n\n\t\t// Call RemoveAllOneFilesystem for remaining subdirs under the pod directory\n\t\tpodDir := kl.getPodDir(uid)\n\t\tpodSubdirs, err := os.ReadDir(podDir)\n\t\tif err != nil {\n\t\t\terrorPods++\n\t\t\tklog.ErrorS(err, \"Could not read directory\", \"path\", podDir)\n\t\t\torphanRemovalErrors = append(orphanRemovalErrors, fmt.Errorf(\"orphaned pod %q found, but error occurred during reading the pod dir from disk: %v\", uid, err))\n\t\t\tcontinue\n\t\t}\n\n\t\tvar cleanupFailed bool\n\t\tfor _, podSubdir := range podSubdirs {\n\t\t\tpodSubdirName := podSubdir.Name()\n\t\t\tpodSubdirPath := filepath.Join(podDir, podSubdirName)\n\t\t\t// Never attempt RemoveAllOneFilesystem on the volumes directory,\n\t\t\t// as this could lead to data loss in some situations. The volumes\n\t\t\t// directory should have been removed by removeOrphanedPodVolumeDirs.\n\t\t\tif podSubdirName == \"volumes\" {\n\t\t\t\tcleanupFailed = true\n\t\t\t\terr := fmt.Errorf(\"volumes subdir was found after it was removed\")\n\t\t\t\tklog.ErrorS(err, \"Orphaned pod found, but failed to remove volumes subdir\", \"podUID\", uid, \"path\", podSubdirPath)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := removeall.RemoveAllOneFilesystem(kl.mounter, podSubdirPath); err != nil {\n\t\t\t\tcleanupFailed = true\n\t\t\t\tklog.ErrorS(err, \"Failed to remove orphaned pod subdir\", \"podUID\", uid, \"path\", podSubdirPath)\n\t\t\t\torphanRemovalErrors = append(orphanRemovalErrors, fmt.Errorf(\"orphaned pod %q found, but error occurred when trying to remove subdir %q: %v\", uid, podSubdirPath, err))\n\t\t\t}\n\t\t}\n\n\t\t// Rmdir the pod dir, which should be empty if everything above was successful\n\t\tklog.V(3).InfoS(\"Orphaned pod found, removing\", \"podUID\", uid)\n\t\tif err := syscall.Rmdir(podDir); err != nil {\n\t\t\tcleanupFailed = true\n\t\t\tklog.ErrorS(err, \"Failed to remove orphaned pod dir\", \"podUID\", uid)\n\t\t\torphanRemovalErrors = append(orphanRemovalErrors, fmt.Errorf(\"orphaned pod %q found, but error occurred when trying to remove the pod directory: %v\", uid, err))\n\t\t}\n\t\tif cleanupFailed {\n\t\t\terrorPods++\n\t\t}\n\t}\n\n\tlogSpew := func(errs []error) {\n\t\tif len(errs) \u003e 0 {\n\t\t\tklog.ErrorS(errs[0], \"There were many similar errors. Turn up verbosity to see them.\", \"numErrs\", len(errs))\n\t\t\tfor _, err := range errs {\n\t\t\t\tklog.V(5).InfoS(\"Orphan pod\", \"err\", err)\n\t\t\t}\n\t\t}\n\t}\n\tlogSpew(orphanVolumeErrors)\n\tlogSpew(orphanRemovalErrors)\n\tmetrics.OrphanPodCleanedVolumes.Set(float64(totalPods))\n\tmetrics.OrphanPodCleanedVolumesErrors.Set(float64(errorPods))\n\treturn utilerrors.NewAggregate(orphanRemovalErrors)\n}","line":{"from":167,"to":272}} {"id":100006874,"name":"NewFsLoader","signature":"func NewFsLoader(fs utilfs.Filesystem, kubeletFile string) (Loader, error)","file":"pkg/kubelet/kubeletconfig/configfiles/configfiles.go","code":"// NewFsLoader returns a Loader that loads a KubeletConfiguration from the `kubeletFile`\nfunc NewFsLoader(fs utilfs.Filesystem, kubeletFile string) (Loader, error) {\n\t_, kubeletCodecs, err := kubeletscheme.NewSchemeAndCodecs(serializer.EnableStrict)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026fsLoader{\n\t\tfs: fs,\n\t\tkubeletCodecs: kubeletCodecs,\n\t\tkubeletFile: kubeletFile,\n\t}, nil\n}","line":{"from":46,"to":58}} {"id":100006875,"name":"Load","signature":"func (loader *fsLoader) Load() (*kubeletconfig.KubeletConfiguration, error)","file":"pkg/kubelet/kubeletconfig/configfiles/configfiles.go","code":"func (loader *fsLoader) Load() (*kubeletconfig.KubeletConfiguration, error) {\n\tdata, err := loader.fs.ReadFile(loader.kubeletFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read kubelet config file %q, error: %v\", loader.kubeletFile, err)\n\t}\n\n\t// no configuration is an error, some parameters are required\n\tif len(data) == 0 {\n\t\treturn nil, fmt.Errorf(\"kubelet config file %q was empty\", loader.kubeletFile)\n\t}\n\n\tkc, err := utilcodec.DecodeKubeletConfiguration(loader.kubeletCodecs, data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// make all paths absolute\n\tresolveRelativePaths(kubeletconfig.KubeletConfigurationPathRefs(kc), filepath.Dir(loader.kubeletFile))\n\treturn kc, nil\n}","line":{"from":60,"to":79}} {"id":100006876,"name":"resolveRelativePaths","signature":"func resolveRelativePaths(paths []*string, root string)","file":"pkg/kubelet/kubeletconfig/configfiles/configfiles.go","code":"// resolveRelativePaths makes relative paths absolute by resolving them against `root`\nfunc resolveRelativePaths(paths []*string, root string) {\n\tfor _, path := range paths {\n\t\t// leave empty paths alone, \"no path\" is a valid input\n\t\t// do not attempt to resolve paths that are already absolute\n\t\tif len(*path) \u003e 0 \u0026\u0026 !filepath.IsAbs(*path) {\n\t\t\t*path = filepath.Join(root, *path)\n\t\t}\n\t}\n}","line":{"from":81,"to":90}} {"id":100006877,"name":"EncodeKubeletConfig","signature":"func EncodeKubeletConfig(internal *kubeletconfig.KubeletConfiguration, targetVersion schema.GroupVersion) ([]byte, error)","file":"pkg/kubelet/kubeletconfig/util/codec/codec.go","code":"// EncodeKubeletConfig encodes an internal KubeletConfiguration to an external YAML representation.\nfunc EncodeKubeletConfig(internal *kubeletconfig.KubeletConfiguration, targetVersion schema.GroupVersion) ([]byte, error) {\n\tencoder, err := NewKubeletconfigYAMLEncoder(targetVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// encoder will convert to external version\n\tdata, err := runtime.Encode(encoder, internal)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}","line":{"from":36,"to":48}} {"id":100006878,"name":"NewKubeletconfigYAMLEncoder","signature":"func NewKubeletconfigYAMLEncoder(targetVersion schema.GroupVersion) (runtime.Encoder, error)","file":"pkg/kubelet/kubeletconfig/util/codec/codec.go","code":"// NewKubeletconfigYAMLEncoder returns an encoder that can write objects in the kubeletconfig API group to YAML.\nfunc NewKubeletconfigYAMLEncoder(targetVersion schema.GroupVersion) (runtime.Encoder, error) {\n\t_, codecs, err := scheme.NewSchemeAndCodecs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmediaType := \"application/yaml\"\n\tinfo, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), mediaType)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unsupported media type %q\", mediaType)\n\t}\n\treturn codecs.EncoderForVersion(info.Serializer, targetVersion), nil\n}","line":{"from":50,"to":62}} {"id":100006879,"name":"DecodeKubeletConfiguration","signature":"func DecodeKubeletConfiguration(kubeletCodecs *serializer.CodecFactory, data []byte) (*kubeletconfig.KubeletConfiguration, error)","file":"pkg/kubelet/kubeletconfig/util/codec/codec.go","code":"// DecodeKubeletConfiguration decodes a serialized KubeletConfiguration to the internal type.\nfunc DecodeKubeletConfiguration(kubeletCodecs *serializer.CodecFactory, data []byte) (*kubeletconfig.KubeletConfiguration, error) {\n\tvar (\n\t\tobj runtime.Object\n\t\tgvk *schema.GroupVersionKind\n\t)\n\n\t// The UniversalDecoder runs defaulting and returns the internal type by default.\n\tobj, gvk, err := kubeletCodecs.UniversalDecoder().Decode(data, nil, nil)\n\tif err != nil {\n\t\t// Try strict decoding first. If that fails decode with a lenient\n\t\t// decoder, which has only v1beta1 registered, and log a warning.\n\t\t// The lenient path is to be dropped when support for v1beta1 is dropped.\n\t\tif !runtime.IsStrictDecodingError(err) {\n\t\t\treturn nil, fmt.Errorf(\"failed to decode: %w\", err)\n\t\t}\n\n\t\tvar lenientErr error\n\t\t_, lenientCodecs, lenientErr := codec.NewLenientSchemeAndCodecs(\n\t\t\tkubeletconfig.AddToScheme,\n\t\t\tkubeletconfigv1beta1.AddToScheme,\n\t\t)\n\n\t\tif lenientErr != nil {\n\t\t\treturn nil, lenientErr\n\t\t}\n\n\t\tobj, gvk, lenientErr = lenientCodecs.UniversalDecoder().Decode(data, nil, nil)\n\t\tif lenientErr != nil {\n\t\t\t// Lenient decoding failed with the current version, return the\n\t\t\t// original strict error.\n\t\t\treturn nil, fmt.Errorf(\"failed lenient decoding: %v\", err)\n\t\t}\n\t\t// Continue with the v1beta1 object that was decoded leniently, but emit a warning.\n\t\tklog.InfoS(\"Using lenient decoding as strict decoding failed\", \"err\", err)\n\t}\n\n\tinternalKC, ok := obj.(*kubeletconfig.KubeletConfiguration)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to cast object to KubeletConfiguration, unexpected type: %v\", gvk)\n\t}\n\n\treturn internalKC, nil\n}","line":{"from":64,"to":107}} {"id":100006880,"name":"FileExists","signature":"func FileExists(fs utilfs.Filesystem, path string) (bool, error)","file":"pkg/kubelet/kubeletconfig/util/files/files.go","code":"// FileExists returns true if a regular file exists at `path`, false if `path` does not exist, otherwise an error\nfunc FileExists(fs utilfs.Filesystem, path string) (bool, error) {\n\tif info, err := fs.Stat(path); err == nil {\n\t\tif info.Mode().IsRegular() {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, fmt.Errorf(\"expected regular file at %q, but mode is %q\", path, info.Mode().String())\n\t} else if os.IsNotExist(err) {\n\t\treturn false, nil\n\t} else {\n\t\treturn false, err\n\t}\n}","line":{"from":32,"to":44}} {"id":100006881,"name":"EnsureFile","signature":"func EnsureFile(fs utilfs.Filesystem, path string) error","file":"pkg/kubelet/kubeletconfig/util/files/files.go","code":"// EnsureFile ensures that a regular file exists at `path`, and if it must create the file any\n// necessary parent directories will also be created and the new file will be empty.\nfunc EnsureFile(fs utilfs.Filesystem, path string) error {\n\t// if file exists, don't change it, but do report any unexpected errors\n\tif ok, err := FileExists(fs, path); ok || err != nil {\n\t\treturn err\n\t} // Assert: file does not exist\n\n\t// create any necessary parents\n\terr := fs.MkdirAll(filepath.Dir(path), defaultPerm)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// create the file\n\tfile, err := fs.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// close the file, since we don't intend to use it yet\n\treturn file.Close()\n}","line":{"from":46,"to":67}} {"id":100006882,"name":"WriteTmpFile","signature":"func WriteTmpFile(fs utilfs.Filesystem, path string, data []byte) (tmpPath string, retErr error)","file":"pkg/kubelet/kubeletconfig/util/files/files.go","code":"// WriteTmpFile creates a temporary file at `path`, writes `data` into it, and fsyncs the file\n// Expects the parent directory to exist.\nfunc WriteTmpFile(fs utilfs.Filesystem, path string, data []byte) (tmpPath string, retErr error) {\n\tdir := filepath.Dir(path)\n\tprefix := tmpTag + filepath.Base(path)\n\n\t// create the tmp file\n\ttmpFile, err := fs.TempFile(dir, prefix)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer func() {\n\t\t// close the file, return the close error only if there haven't been any other errors\n\t\tif err := tmpFile.Close(); retErr == nil {\n\t\t\tretErr = err\n\t\t}\n\t\t// if there was an error writing, syncing, or closing, delete the temporary file and return the error\n\t\tif retErr != nil {\n\t\t\tif err := fs.Remove(tmpPath); err != nil {\n\t\t\t\tretErr = fmt.Errorf(\"attempted to remove temporary file %q after error %v, but failed due to error: %v\", tmpPath, retErr, err)\n\t\t\t}\n\t\t\ttmpPath = \"\"\n\t\t}\n\t}()\n\n\t// Name() will be an absolute path when using utilfs.DefaultFS, because ioutil.TempFile passes\n\t// an absolute path to os.Open, and we ensure similar behavior in utilfs.FakeFS for testing.\n\ttmpPath = tmpFile.Name()\n\n\t// write data\n\tif _, err := tmpFile.Write(data); err != nil {\n\t\treturn tmpPath, err\n\t}\n\t// sync file, to ensure it's written in case a hard reset happens\n\treturn tmpPath, tmpFile.Sync()\n}","line":{"from":69,"to":104}} {"id":100006883,"name":"ReplaceFile","signature":"func ReplaceFile(fs utilfs.Filesystem, path string, data []byte) error","file":"pkg/kubelet/kubeletconfig/util/files/files.go","code":"// ReplaceFile replaces the contents of the file at `path` with `data` by writing to a tmp file in the same\n// dir as `path` and renaming the tmp file over `path`. The file does not have to exist to use ReplaceFile,\n// but the parent directory must exist.\n// Note ReplaceFile calls fsync.\nfunc ReplaceFile(fs utilfs.Filesystem, path string, data []byte) error {\n\t// write data to a temporary file\n\ttmpPath, err := WriteTmpFile(fs, path, data)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// rename over existing file\n\treturn fs.Rename(tmpPath, path)\n}","line":{"from":106,"to":118}} {"id":100006884,"name":"DirExists","signature":"func DirExists(fs utilfs.Filesystem, path string) (bool, error)","file":"pkg/kubelet/kubeletconfig/util/files/files.go","code":"// DirExists returns true if a directory exists at `path`, false if `path` does not exist, otherwise an error\nfunc DirExists(fs utilfs.Filesystem, path string) (bool, error) {\n\tif info, err := fs.Stat(path); err == nil {\n\t\tif info.IsDir() {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, fmt.Errorf(\"expected dir at %q, but mode is %q\", path, info.Mode().String())\n\t} else if os.IsNotExist(err) {\n\t\treturn false, nil\n\t} else {\n\t\treturn false, err\n\t}\n}","line":{"from":120,"to":132}} {"id":100006885,"name":"EnsureDir","signature":"func EnsureDir(fs utilfs.Filesystem, path string) error","file":"pkg/kubelet/kubeletconfig/util/files/files.go","code":"// EnsureDir ensures that a directory exists at `path`, and if it must create the directory any\n// necessary parent directories will also be created and the new directory will be empty.\nfunc EnsureDir(fs utilfs.Filesystem, path string) error {\n\t// if dir exists, don't change it, but do report any unexpected errors\n\tif ok, err := DirExists(fs, path); ok || err != nil {\n\t\treturn err\n\t} // Assert: dir does not exist\n\n\t// create the dir\n\treturn fs.MkdirAll(path, defaultPerm)\n}","line":{"from":134,"to":144}} {"id":100006886,"name":"WriteTempDir","signature":"func WriteTempDir(fs utilfs.Filesystem, path string, files map[string]string) (tmpPath string, retErr error)","file":"pkg/kubelet/kubeletconfig/util/files/files.go","code":"// WriteTempDir creates a temporary dir at `path`, writes `files` into it, and fsyncs all the files\n// The keys of `files` represent file names. These names must not:\n// - be empty\n// - be a path that contains more than the base name of a file (e.g. foo/bar is invalid, as is /bar)\n// - match `.` or `..` exactly\n// - be longer than 255 characters\n// The above validation rules are based on atomic_writer.go, though in this case are more restrictive\n// because we only allow a flat hierarchy.\nfunc WriteTempDir(fs utilfs.Filesystem, path string, files map[string]string) (tmpPath string, retErr error) {\n\t// validate the filename keys; for now we only allow a flat keyset\n\tfor name := range files {\n\t\t// invalidate empty names\n\t\tif name == \"\" {\n\t\t\treturn \"\", fmt.Errorf(\"invalid file key: must not be empty: %q\", name)\n\t\t}\n\t\t// invalidate: foo/bar and /bar\n\t\tif name != filepath.Base(name) {\n\t\t\treturn \"\", fmt.Errorf(\"invalid file key %q, only base names are allowed\", name)\n\t\t}\n\t\t// invalidate `.` and `..`\n\t\tif name == \".\" || name == \"..\" {\n\t\t\treturn \"\", fmt.Errorf(\"invalid file key, may not be '.' or '..'\")\n\t\t}\n\t\t// invalidate length \u003e 255 characters\n\t\tif len(name) \u003e 255 {\n\t\t\treturn \"\", fmt.Errorf(\"invalid file key %q, must be less than 255 characters\", name)\n\t\t}\n\t}\n\n\t// write the temp directory in parent dir and return path to the tmp directory\n\tdir := filepath.Dir(path)\n\tprefix := tmpTag + filepath.Base(path)\n\n\t// create the tmp dir\n\tvar err error\n\ttmpPath, err = fs.TempDir(dir, prefix)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// be sure to clean up if there was an error\n\tdefer func() {\n\t\tif retErr != nil {\n\t\t\tif err := fs.RemoveAll(tmpPath); err != nil {\n\t\t\t\tretErr = fmt.Errorf(\"attempted to remove temporary directory %q after error %v, but failed due to error: %v\", tmpPath, retErr, err)\n\t\t\t}\n\t\t}\n\t}()\n\t// write data\n\tfor name, data := range files {\n\t\t// create the file\n\t\tfile, err := fs.Create(filepath.Join(tmpPath, name))\n\t\tif err != nil {\n\t\t\treturn tmpPath, err\n\t\t}\n\t\t// be sure to close the file when we're done\n\t\tdefer func() {\n\t\t\t// close the file when we're done, don't overwrite primary retErr if close fails\n\t\t\tif err := file.Close(); retErr == nil {\n\t\t\t\tretErr = err\n\t\t\t}\n\t\t}()\n\t\t// write the file\n\t\tif _, err := file.Write([]byte(data)); err != nil {\n\t\t\treturn tmpPath, err\n\t\t}\n\t\t// sync the file, to ensure it's written in case a hard reset happens\n\t\tif err := file.Sync(); err != nil {\n\t\t\treturn tmpPath, err\n\t\t}\n\t}\n\treturn tmpPath, nil\n}","line":{"from":146,"to":217}} {"id":100006887,"name":"ReplaceDir","signature":"func ReplaceDir(fs utilfs.Filesystem, path string, files map[string]string) error","file":"pkg/kubelet/kubeletconfig/util/files/files.go","code":"// ReplaceDir replaces the contents of the dir at `path` with `files` by writing to a tmp dir in the same\n// dir as `path` and renaming the tmp dir over `path`. The dir does not have to exist to use ReplaceDir.\nfunc ReplaceDir(fs utilfs.Filesystem, path string, files map[string]string) error {\n\t// write data to a temporary directory\n\ttmpPath, err := WriteTempDir(fs, path, files)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// rename over target directory\n\treturn fs.Rename(tmpPath, path)\n}","line":{"from":219,"to":229}} {"id":100006888,"name":"toKubeContainerImageSpec","signature":"func toKubeContainerImageSpec(image *runtimeapi.Image) kubecontainer.ImageSpec","file":"pkg/kubelet/kuberuntime/convert.go","code":"func toKubeContainerImageSpec(image *runtimeapi.Image) kubecontainer.ImageSpec {\n\tvar annotations []kubecontainer.Annotation\n\n\tif image.Spec != nil \u0026\u0026 len(image.Spec.Annotations) \u003e 0 {\n\t\tannotationKeys := make([]string, 0, len(image.Spec.Annotations))\n\t\tfor k := range image.Spec.Annotations {\n\t\t\tannotationKeys = append(annotationKeys, k)\n\t\t}\n\t\tsort.Strings(annotationKeys)\n\t\tfor _, k := range annotationKeys {\n\t\t\tannotations = append(annotations, kubecontainer.Annotation{\n\t\t\t\tName: k,\n\t\t\t\tValue: image.Spec.Annotations[k],\n\t\t\t})\n\t\t}\n\t}\n\n\treturn kubecontainer.ImageSpec{\n\t\tImage: image.Id,\n\t\tAnnotations: annotations,\n\t}\n}","line":{"from":28,"to":49}} {"id":100006889,"name":"toRuntimeAPIImageSpec","signature":"func toRuntimeAPIImageSpec(imageSpec kubecontainer.ImageSpec) *runtimeapi.ImageSpec","file":"pkg/kubelet/kuberuntime/convert.go","code":"func toRuntimeAPIImageSpec(imageSpec kubecontainer.ImageSpec) *runtimeapi.ImageSpec {\n\tvar annotations = make(map[string]string)\n\tif imageSpec.Annotations != nil {\n\t\tfor _, a := range imageSpec.Annotations {\n\t\t\tannotations[a.Name] = a.Value\n\t\t}\n\t}\n\treturn \u0026runtimeapi.ImageSpec{\n\t\tImage: imageSpec.Image,\n\t\tAnnotations: annotations,\n\t}\n}","line":{"from":51,"to":62}} {"id":100006890,"name":"Len","signature":"func (b podsByID) Len() int { return len(b) }","file":"pkg/kubelet/kuberuntime/helpers.go","code":"func (b podsByID) Len() int { return len(b) }","line":{"from":35,"to":35}} {"id":100006891,"name":"Swap","signature":"func (b podsByID) Swap(i, j int) { b[i], b[j] = b[j], b[i] }","file":"pkg/kubelet/kuberuntime/helpers.go","code":"func (b podsByID) Swap(i, j int) { b[i], b[j] = b[j], b[i] }","line":{"from":36,"to":36}} {"id":100006892,"name":"Less","signature":"func (b podsByID) Less(i, j int) bool { return b[i].ID \u003c b[j].ID }","file":"pkg/kubelet/kuberuntime/helpers.go","code":"func (b podsByID) Less(i, j int) bool { return b[i].ID \u003c b[j].ID }","line":{"from":37,"to":37}} {"id":100006893,"name":"Len","signature":"func (b containersByID) Len() int { return len(b) }","file":"pkg/kubelet/kuberuntime/helpers.go","code":"func (b containersByID) Len() int { return len(b) }","line":{"from":41,"to":41}} {"id":100006894,"name":"Swap","signature":"func (b containersByID) Swap(i, j int) { b[i], b[j] = b[j], b[i] }","file":"pkg/kubelet/kuberuntime/helpers.go","code":"func (b containersByID) Swap(i, j int) { b[i], b[j] = b[j], b[i] }","line":{"from":42,"to":42}} {"id":100006895,"name":"Less","signature":"func (b containersByID) Less(i, j int) bool { return b[i].ID.ID \u003c b[j].ID.ID }","file":"pkg/kubelet/kuberuntime/helpers.go","code":"func (b containersByID) Less(i, j int) bool { return b[i].ID.ID \u003c b[j].ID.ID }","line":{"from":43,"to":43}} {"id":100006896,"name":"Len","signature":"func (p podSandboxByCreated) Len() int { return len(p) }","file":"pkg/kubelet/kuberuntime/helpers.go","code":"func (p podSandboxByCreated) Len() int { return len(p) }","line":{"from":48,"to":48}} {"id":100006897,"name":"Swap","signature":"func (p podSandboxByCreated) Swap(i, j int) { p[i], p[j] = p[j], p[i] }","file":"pkg/kubelet/kuberuntime/helpers.go","code":"func (p podSandboxByCreated) Swap(i, j int) { p[i], p[j] = p[j], p[i] }","line":{"from":49,"to":49}} {"id":100006898,"name":"Less","signature":"func (p podSandboxByCreated) Less(i, j int) bool { return p[i].CreatedAt \u003e p[j].CreatedAt }","file":"pkg/kubelet/kuberuntime/helpers.go","code":"func (p podSandboxByCreated) Less(i, j int) bool { return p[i].CreatedAt \u003e p[j].CreatedAt }","line":{"from":50,"to":50}} {"id":100006899,"name":"Len","signature":"func (c containerStatusByCreated) Len() int { return len(c) }","file":"pkg/kubelet/kuberuntime/helpers.go","code":"func (c containerStatusByCreated) Len() int { return len(c) }","line":{"from":54,"to":54}} {"id":100006900,"name":"Swap","signature":"func (c containerStatusByCreated) Swap(i, j int) { c[i], c[j] = c[j], c[i] }","file":"pkg/kubelet/kuberuntime/helpers.go","code":"func (c containerStatusByCreated) Swap(i, j int) { c[i], c[j] = c[j], c[i] }","line":{"from":55,"to":55}} {"id":100006901,"name":"Less","signature":"func (c containerStatusByCreated) Less(i, j int) bool { return c[i].CreatedAt.After(c[j].CreatedAt) }","file":"pkg/kubelet/kuberuntime/helpers.go","code":"func (c containerStatusByCreated) Less(i, j int) bool { return c[i].CreatedAt.After(c[j].CreatedAt) }","line":{"from":56,"to":56}} {"id":100006902,"name":"toKubeContainerState","signature":"func toKubeContainerState(state runtimeapi.ContainerState) kubecontainer.State","file":"pkg/kubelet/kuberuntime/helpers.go","code":"// toKubeContainerState converts runtimeapi.ContainerState to kubecontainer.State.\nfunc toKubeContainerState(state runtimeapi.ContainerState) kubecontainer.State {\n\tswitch state {\n\tcase runtimeapi.ContainerState_CONTAINER_CREATED:\n\t\treturn kubecontainer.ContainerStateCreated\n\tcase runtimeapi.ContainerState_CONTAINER_RUNNING:\n\t\treturn kubecontainer.ContainerStateRunning\n\tcase runtimeapi.ContainerState_CONTAINER_EXITED:\n\t\treturn kubecontainer.ContainerStateExited\n\tcase runtimeapi.ContainerState_CONTAINER_UNKNOWN:\n\t\treturn kubecontainer.ContainerStateUnknown\n\t}\n\n\treturn kubecontainer.ContainerStateUnknown\n}","line":{"from":58,"to":72}} {"id":100006903,"name":"toRuntimeProtocol","signature":"func toRuntimeProtocol(protocol v1.Protocol) runtimeapi.Protocol","file":"pkg/kubelet/kuberuntime/helpers.go","code":"// toRuntimeProtocol converts v1.Protocol to runtimeapi.Protocol.\nfunc toRuntimeProtocol(protocol v1.Protocol) runtimeapi.Protocol {\n\tswitch protocol {\n\tcase v1.ProtocolTCP:\n\t\treturn runtimeapi.Protocol_TCP\n\tcase v1.ProtocolUDP:\n\t\treturn runtimeapi.Protocol_UDP\n\tcase v1.ProtocolSCTP:\n\t\treturn runtimeapi.Protocol_SCTP\n\t}\n\n\tklog.InfoS(\"Unknown protocol, defaulting to TCP\", \"protocol\", protocol)\n\treturn runtimeapi.Protocol_TCP\n}","line":{"from":74,"to":87}} {"id":100006904,"name":"toKubeContainer","signature":"func (m *kubeGenericRuntimeManager) toKubeContainer(c *runtimeapi.Container) (*kubecontainer.Container, error)","file":"pkg/kubelet/kuberuntime/helpers.go","code":"// toKubeContainer converts runtimeapi.Container to kubecontainer.Container.\nfunc (m *kubeGenericRuntimeManager) toKubeContainer(c *runtimeapi.Container) (*kubecontainer.Container, error) {\n\tif c == nil || c.Id == \"\" || c.Image == nil {\n\t\treturn nil, fmt.Errorf(\"unable to convert a nil pointer to a runtime container\")\n\t}\n\n\tannotatedInfo := getContainerInfoFromAnnotations(c.Annotations)\n\treturn \u0026kubecontainer.Container{\n\t\tID: kubecontainer.ContainerID{Type: m.runtimeName, ID: c.Id},\n\t\tName: c.GetMetadata().GetName(),\n\t\tImageID: c.ImageRef,\n\t\tImage: c.Image.Image,\n\t\tHash: annotatedInfo.Hash,\n\t\tHashWithoutResources: annotatedInfo.HashWithoutResources,\n\t\tState: toKubeContainerState(c.State),\n\t}, nil\n}","line":{"from":89,"to":105}} {"id":100006905,"name":"sandboxToKubeContainer","signature":"func (m *kubeGenericRuntimeManager) sandboxToKubeContainer(s *runtimeapi.PodSandbox) (*kubecontainer.Container, error)","file":"pkg/kubelet/kuberuntime/helpers.go","code":"// sandboxToKubeContainer converts runtimeapi.PodSandbox to kubecontainer.Container.\n// This is only needed because we need to return sandboxes as if they were\n// kubecontainer.Containers to avoid substantial changes to PLEG.\n// TODO: Remove this once it becomes obsolete.\nfunc (m *kubeGenericRuntimeManager) sandboxToKubeContainer(s *runtimeapi.PodSandbox) (*kubecontainer.Container, error) {\n\tif s == nil || s.Id == \"\" {\n\t\treturn nil, fmt.Errorf(\"unable to convert a nil pointer to a runtime container\")\n\t}\n\n\treturn \u0026kubecontainer.Container{\n\t\tID: kubecontainer.ContainerID{Type: m.runtimeName, ID: s.Id},\n\t\tState: kubecontainer.SandboxToContainerState(s.State),\n\t}, nil\n}","line":{"from":107,"to":120}} {"id":100006906,"name":"getImageUser","signature":"func (m *kubeGenericRuntimeManager) getImageUser(ctx context.Context, image string) (*int64, string, error)","file":"pkg/kubelet/kuberuntime/helpers.go","code":"// getImageUser gets uid or user name that will run the command(s) from image. The function\n// guarantees that only one of them is set.\nfunc (m *kubeGenericRuntimeManager) getImageUser(ctx context.Context, image string) (*int64, string, error) {\n\tresp, err := m.imageService.ImageStatus(ctx, \u0026runtimeapi.ImageSpec{Image: image}, false)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\timageStatus := resp.GetImage()\n\n\tif imageStatus != nil {\n\t\tif imageStatus.Uid != nil {\n\t\t\treturn \u0026imageStatus.GetUid().Value, \"\", nil\n\t\t}\n\n\t\tif imageStatus.Username != \"\" {\n\t\t\treturn nil, imageStatus.Username, nil\n\t\t}\n\t}\n\n\t// If non of them is set, treat it as root.\n\treturn new(int64), \"\", nil\n}","line":{"from":122,"to":143}} {"id":100006907,"name":"isInitContainerFailed","signature":"func isInitContainerFailed(status *kubecontainer.Status) bool","file":"pkg/kubelet/kuberuntime/helpers.go","code":"// isInitContainerFailed returns true under the following conditions:\n// 1. container has exited and exitcode is not zero.\n// 2. container is in unknown state.\n// 3. container gets OOMKilled.\nfunc isInitContainerFailed(status *kubecontainer.Status) bool {\n\t// When oomkilled occurs, init container should be considered as a failure.\n\tif status.Reason == \"OOMKilled\" {\n\t\treturn true\n\t}\n\n\tif status.State == kubecontainer.ContainerStateExited \u0026\u0026 status.ExitCode != 0 {\n\t\treturn true\n\t}\n\n\tif status.State == kubecontainer.ContainerStateUnknown {\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":145,"to":164}} {"id":100006908,"name":"getStableKey","signature":"func getStableKey(pod *v1.Pod, container *v1.Container) string","file":"pkg/kubelet/kuberuntime/helpers.go","code":"// getStableKey generates a key (string) to uniquely identify a\n// (pod, container) tuple. The key should include the content of the\n// container, so that any change to the container generates a new key.\nfunc getStableKey(pod *v1.Pod, container *v1.Container) string {\n\thash := strconv.FormatUint(kubecontainer.HashContainer(container), 16)\n\treturn fmt.Sprintf(\"%s_%s_%s_%s_%s\", pod.Name, pod.Namespace, string(pod.UID), container.Name, hash)\n}","line":{"from":166,"to":172}} {"id":100006909,"name":"buildContainerLogsPath","signature":"func buildContainerLogsPath(containerName string, restartCount int) string","file":"pkg/kubelet/kuberuntime/helpers.go","code":"// buildContainerLogsPath builds log path for container relative to pod logs directory.\nfunc buildContainerLogsPath(containerName string, restartCount int) string {\n\treturn filepath.Join(containerName, fmt.Sprintf(\"%d.log\", restartCount))\n}","line":{"from":177,"to":180}} {"id":100006910,"name":"BuildContainerLogsDirectory","signature":"func BuildContainerLogsDirectory(podNamespace, podName string, podUID types.UID, containerName string) string","file":"pkg/kubelet/kuberuntime/helpers.go","code":"// BuildContainerLogsDirectory builds absolute log directory path for a container in pod.\nfunc BuildContainerLogsDirectory(podNamespace, podName string, podUID types.UID, containerName string) string {\n\treturn filepath.Join(BuildPodLogsDirectory(podNamespace, podName, podUID), containerName)\n}","line":{"from":182,"to":185}} {"id":100006911,"name":"BuildPodLogsDirectory","signature":"func BuildPodLogsDirectory(podNamespace, podName string, podUID types.UID) string","file":"pkg/kubelet/kuberuntime/helpers.go","code":"// BuildPodLogsDirectory builds absolute log directory path for a pod sandbox.\nfunc BuildPodLogsDirectory(podNamespace, podName string, podUID types.UID) string {\n\treturn filepath.Join(podLogsRootDirectory, strings.Join([]string{podNamespace, podName,\n\t\tstring(podUID)}, logPathDelimiter))\n}","line":{"from":187,"to":191}} {"id":100006912,"name":"parsePodUIDFromLogsDirectory","signature":"func parsePodUIDFromLogsDirectory(name string) types.UID","file":"pkg/kubelet/kuberuntime/helpers.go","code":"// parsePodUIDFromLogsDirectory parses pod logs directory name and returns the pod UID.\n// It supports both the old pod log directory /var/log/pods/UID, and the new pod log\n// directory /var/log/pods/NAMESPACE_NAME_UID.\nfunc parsePodUIDFromLogsDirectory(name string) types.UID {\n\tparts := strings.Split(name, logPathDelimiter)\n\treturn types.UID(parts[len(parts)-1])\n}","line":{"from":193,"to":199}} {"id":100006913,"name":"toKubeRuntimeStatus","signature":"func toKubeRuntimeStatus(status *runtimeapi.RuntimeStatus) *kubecontainer.RuntimeStatus","file":"pkg/kubelet/kuberuntime/helpers.go","code":"// toKubeRuntimeStatus converts the runtimeapi.RuntimeStatus to kubecontainer.RuntimeStatus.\nfunc toKubeRuntimeStatus(status *runtimeapi.RuntimeStatus) *kubecontainer.RuntimeStatus {\n\tconditions := []kubecontainer.RuntimeCondition{}\n\tfor _, c := range status.GetConditions() {\n\t\tconditions = append(conditions, kubecontainer.RuntimeCondition{\n\t\t\tType: kubecontainer.RuntimeConditionType(c.Type),\n\t\t\tStatus: c.Status,\n\t\t\tReason: c.Reason,\n\t\t\tMessage: c.Message,\n\t\t})\n\t}\n\treturn \u0026kubecontainer.RuntimeStatus{Conditions: conditions}\n}","line":{"from":201,"to":213}} {"id":100006914,"name":"fieldProfile","signature":"func fieldProfile(scmp *v1.SeccompProfile, profileRootPath string, fallbackToRuntimeDefault bool) (string, error)","file":"pkg/kubelet/kuberuntime/helpers.go","code":"func fieldProfile(scmp *v1.SeccompProfile, profileRootPath string, fallbackToRuntimeDefault bool) (string, error) {\n\tif scmp == nil {\n\t\tif fallbackToRuntimeDefault {\n\t\t\treturn v1.SeccompProfileRuntimeDefault, nil\n\t\t}\n\t\treturn \"\", nil\n\t}\n\tif scmp.Type == v1.SeccompProfileTypeRuntimeDefault {\n\t\treturn v1.SeccompProfileRuntimeDefault, nil\n\t}\n\tif scmp.Type == v1.SeccompProfileTypeLocalhost {\n\t\tif scmp.LocalhostProfile != nil \u0026\u0026 len(*scmp.LocalhostProfile) \u003e 0 {\n\t\t\tfname := filepath.Join(profileRootPath, *scmp.LocalhostProfile)\n\t\t\treturn v1.SeccompLocalhostProfileNamePrefix + fname, nil\n\t\t} else {\n\t\t\treturn \"\", fmt.Errorf(\"localhostProfile must be set if seccompProfile type is Localhost.\")\n\t\t}\n\t}\n\tif scmp.Type == v1.SeccompProfileTypeUnconfined {\n\t\treturn v1.SeccompProfileNameUnconfined, nil\n\t}\n\n\tif fallbackToRuntimeDefault {\n\t\treturn v1.SeccompProfileRuntimeDefault, nil\n\t}\n\treturn \"\", nil\n}","line":{"from":215,"to":241}} {"id":100006915,"name":"getSeccompProfilePath","signature":"func (m *kubeGenericRuntimeManager) getSeccompProfilePath(annotations map[string]string, containerName string,","file":"pkg/kubelet/kuberuntime/helpers.go","code":"func (m *kubeGenericRuntimeManager) getSeccompProfilePath(annotations map[string]string, containerName string,\n\tpodSecContext *v1.PodSecurityContext, containerSecContext *v1.SecurityContext, fallbackToRuntimeDefault bool) (string, error) {\n\t// container fields are applied first\n\tif containerSecContext != nil \u0026\u0026 containerSecContext.SeccompProfile != nil {\n\t\treturn fieldProfile(containerSecContext.SeccompProfile, m.seccompProfileRoot, fallbackToRuntimeDefault)\n\t}\n\n\t// when container seccomp is not defined, try to apply from pod field\n\tif podSecContext != nil \u0026\u0026 podSecContext.SeccompProfile != nil {\n\t\treturn fieldProfile(podSecContext.SeccompProfile, m.seccompProfileRoot, fallbackToRuntimeDefault)\n\t}\n\n\tif fallbackToRuntimeDefault {\n\t\treturn v1.SeccompProfileRuntimeDefault, nil\n\t}\n\n\treturn \"\", nil\n}","line":{"from":243,"to":260}} {"id":100006916,"name":"fieldSeccompProfile","signature":"func fieldSeccompProfile(scmp *v1.SeccompProfile, profileRootPath string, fallbackToRuntimeDefault bool) (*runtimeapi.SecurityProfile, error)","file":"pkg/kubelet/kuberuntime/helpers.go","code":"func fieldSeccompProfile(scmp *v1.SeccompProfile, profileRootPath string, fallbackToRuntimeDefault bool) (*runtimeapi.SecurityProfile, error) {\n\tif scmp == nil {\n\t\tif fallbackToRuntimeDefault {\n\t\t\treturn \u0026runtimeapi.SecurityProfile{\n\t\t\t\tProfileType: runtimeapi.SecurityProfile_RuntimeDefault,\n\t\t\t}, nil\n\t\t}\n\t\treturn \u0026runtimeapi.SecurityProfile{\n\t\t\tProfileType: runtimeapi.SecurityProfile_Unconfined,\n\t\t}, nil\n\t}\n\tif scmp.Type == v1.SeccompProfileTypeRuntimeDefault {\n\t\treturn \u0026runtimeapi.SecurityProfile{\n\t\t\tProfileType: runtimeapi.SecurityProfile_RuntimeDefault,\n\t\t}, nil\n\t}\n\tif scmp.Type == v1.SeccompProfileTypeLocalhost {\n\t\tif scmp.LocalhostProfile != nil \u0026\u0026 len(*scmp.LocalhostProfile) \u003e 0 {\n\t\t\tfname := filepath.Join(profileRootPath, *scmp.LocalhostProfile)\n\t\t\treturn \u0026runtimeapi.SecurityProfile{\n\t\t\t\tProfileType: runtimeapi.SecurityProfile_Localhost,\n\t\t\t\tLocalhostRef: fname,\n\t\t\t}, nil\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"localhostProfile must be set if seccompProfile type is Localhost.\")\n\t\t}\n\t}\n\treturn \u0026runtimeapi.SecurityProfile{\n\t\tProfileType: runtimeapi.SecurityProfile_Unconfined,\n\t}, nil\n}","line":{"from":262,"to":292}} {"id":100006917,"name":"getSeccompProfile","signature":"func (m *kubeGenericRuntimeManager) getSeccompProfile(annotations map[string]string, containerName string,","file":"pkg/kubelet/kuberuntime/helpers.go","code":"func (m *kubeGenericRuntimeManager) getSeccompProfile(annotations map[string]string, containerName string,\n\tpodSecContext *v1.PodSecurityContext, containerSecContext *v1.SecurityContext, fallbackToRuntimeDefault bool) (*runtimeapi.SecurityProfile, error) {\n\t// container fields are applied first\n\tif containerSecContext != nil \u0026\u0026 containerSecContext.SeccompProfile != nil {\n\t\treturn fieldSeccompProfile(containerSecContext.SeccompProfile, m.seccompProfileRoot, fallbackToRuntimeDefault)\n\t}\n\n\t// when container seccomp is not defined, try to apply from pod field\n\tif podSecContext != nil \u0026\u0026 podSecContext.SeccompProfile != nil {\n\t\treturn fieldSeccompProfile(podSecContext.SeccompProfile, m.seccompProfileRoot, fallbackToRuntimeDefault)\n\t}\n\n\tif fallbackToRuntimeDefault {\n\t\treturn \u0026runtimeapi.SecurityProfile{\n\t\t\tProfileType: runtimeapi.SecurityProfile_RuntimeDefault,\n\t\t}, nil\n\t}\n\n\treturn \u0026runtimeapi.SecurityProfile{\n\t\tProfileType: runtimeapi.SecurityProfile_Unconfined,\n\t}, nil\n}","line":{"from":294,"to":315}} {"id":100006918,"name":"milliCPUToQuota","signature":"func milliCPUToQuota(milliCPU int64, period int64) (quota int64)","file":"pkg/kubelet/kuberuntime/helpers_linux.go","code":"// milliCPUToQuota converts milliCPU to CFS quota and period values\n// Input parameters and resulting value is number of microseconds.\nfunc milliCPUToQuota(milliCPU int64, period int64) (quota int64) {\n\t// CFS quota is measured in two values:\n\t// - cfs_period_us=100ms (the amount of time to measure usage across)\n\t// - cfs_quota=20ms (the amount of cpu time allowed to be used across a period)\n\t// so in the above example, you are limited to 20% of a single CPU\n\t// for multi-cpu environments, you just scale equivalent amounts\n\t// see https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt for details\n\tif milliCPU == 0 {\n\t\treturn\n\t}\n\n\t// we then convert your milliCPU to a value normalized over a period\n\tquota = (milliCPU * period) / milliCPUToCPU\n\n\t// quota needs to be a minimum of 1ms.\n\tif quota \u003c minQuotaPeriod {\n\t\tquota = minQuotaPeriod\n\t}\n\n\treturn\n}","line":{"from":38,"to":60}} {"id":100006919,"name":"sharesToMilliCPU","signature":"func sharesToMilliCPU(shares int64) int64","file":"pkg/kubelet/kuberuntime/helpers_linux.go","code":"// sharesToMilliCPU converts CpuShares (cpu.shares) to milli-CPU value\n// TODO(vinaykul,InPlacePodVerticalScaling): Address issue that sets min req/limit to 2m/10m before beta\n// See: https://github.com/kubernetes/kubernetes/pull/102884#discussion_r662552642\nfunc sharesToMilliCPU(shares int64) int64 {\n\tmilliCPU := int64(0)\n\tif shares \u003e= int64(cm.MinShares) {\n\t\tmilliCPU = int64(math.Ceil(float64(shares*milliCPUToCPU) / float64(cm.SharesPerCPU)))\n\t}\n\treturn milliCPU\n}","line":{"from":62,"to":71}} {"id":100006920,"name":"quotaToMilliCPU","signature":"func quotaToMilliCPU(quota int64, period int64) int64","file":"pkg/kubelet/kuberuntime/helpers_linux.go","code":"// quotaToMilliCPU converts cpu.cfs_quota_us and cpu.cfs_period_us to milli-CPU value\nfunc quotaToMilliCPU(quota int64, period int64) int64 {\n\tif quota == -1 {\n\t\treturn int64(0)\n\t}\n\treturn (quota * milliCPUToCPU) / period\n}","line":{"from":73,"to":79}} {"id":100006921,"name":"newInstrumentedRuntimeService","signature":"func newInstrumentedRuntimeService(service internalapi.RuntimeService) internalapi.RuntimeService","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"// Creates an instrumented RuntimeInterface from an existing RuntimeService.\nfunc newInstrumentedRuntimeService(service internalapi.RuntimeService) internalapi.RuntimeService {\n\treturn \u0026instrumentedRuntimeService{service: service}\n}","line":{"from":34,"to":37}} {"id":100006922,"name":"newInstrumentedImageManagerService","signature":"func newInstrumentedImageManagerService(service internalapi.ImageManagerService) internalapi.ImageManagerService","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"// Creates an instrumented ImageManagerService from an existing ImageManagerService.\nfunc newInstrumentedImageManagerService(service internalapi.ImageManagerService) internalapi.ImageManagerService {\n\treturn \u0026instrumentedImageManagerService{service: service}\n}","line":{"from":45,"to":48}} {"id":100006923,"name":"recordOperation","signature":"func recordOperation(operation string, start time.Time)","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"// recordOperation records the duration of the operation.\nfunc recordOperation(operation string, start time.Time) {\n\tmetrics.RuntimeOperations.WithLabelValues(operation).Inc()\n\tmetrics.RuntimeOperationsDuration.WithLabelValues(operation).Observe(metrics.SinceInSeconds(start))\n}","line":{"from":50,"to":54}} {"id":100006924,"name":"recordError","signature":"func recordError(operation string, err error)","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"// recordError records error for metric if an error occurred.\nfunc recordError(operation string, err error) {\n\tif err != nil {\n\t\tmetrics.RuntimeOperationsErrors.WithLabelValues(operation).Inc()\n\t}\n}","line":{"from":56,"to":61}} {"id":100006925,"name":"Version","signature":"func (in instrumentedRuntimeService) Version(ctx context.Context, apiVersion string) (*runtimeapi.VersionResponse, error)","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) Version(ctx context.Context, apiVersion string) (*runtimeapi.VersionResponse, error) {\n\tconst operation = \"version\"\n\tdefer recordOperation(operation, time.Now())\n\n\tout, err := in.service.Version(ctx, apiVersion)\n\trecordError(operation, err)\n\treturn out, err\n}","line":{"from":63,"to":70}} {"id":100006926,"name":"Status","signature":"func (in instrumentedRuntimeService) Status(ctx context.Context, verbose bool) (*runtimeapi.StatusResponse, error)","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) Status(ctx context.Context, verbose bool) (*runtimeapi.StatusResponse, error) {\n\tconst operation = \"status\"\n\tdefer recordOperation(operation, time.Now())\n\n\tout, err := in.service.Status(ctx, verbose)\n\trecordError(operation, err)\n\treturn out, err\n}","line":{"from":72,"to":79}} {"id":100006927,"name":"CreateContainer","signature":"func (in instrumentedRuntimeService) CreateContainer(ctx context.Context, podSandboxID string, config *runtimeapi.ContainerConfig, sandboxConfig *runtimeapi.PodSandboxConfig) (string, error)","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) CreateContainer(ctx context.Context, podSandboxID string, config *runtimeapi.ContainerConfig, sandboxConfig *runtimeapi.PodSandboxConfig) (string, error) {\n\tconst operation = \"create_container\"\n\tdefer recordOperation(operation, time.Now())\n\n\tout, err := in.service.CreateContainer(ctx, podSandboxID, config, sandboxConfig)\n\trecordError(operation, err)\n\treturn out, err\n}","line":{"from":81,"to":88}} {"id":100006928,"name":"StartContainer","signature":"func (in instrumentedRuntimeService) StartContainer(ctx context.Context, containerID string) error","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) StartContainer(ctx context.Context, containerID string) error {\n\tconst operation = \"start_container\"\n\tdefer recordOperation(operation, time.Now())\n\n\terr := in.service.StartContainer(ctx, containerID)\n\trecordError(operation, err)\n\treturn err\n}","line":{"from":90,"to":97}} {"id":100006929,"name":"StopContainer","signature":"func (in instrumentedRuntimeService) StopContainer(ctx context.Context, containerID string, timeout int64) error","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) StopContainer(ctx context.Context, containerID string, timeout int64) error {\n\tconst operation = \"stop_container\"\n\tdefer recordOperation(operation, time.Now())\n\n\terr := in.service.StopContainer(ctx, containerID, timeout)\n\trecordError(operation, err)\n\treturn err\n}","line":{"from":99,"to":106}} {"id":100006930,"name":"RemoveContainer","signature":"func (in instrumentedRuntimeService) RemoveContainer(ctx context.Context, containerID string) error","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) RemoveContainer(ctx context.Context, containerID string) error {\n\tconst operation = \"remove_container\"\n\tdefer recordOperation(operation, time.Now())\n\n\terr := in.service.RemoveContainer(ctx, containerID)\n\trecordError(operation, err)\n\treturn err\n}","line":{"from":108,"to":115}} {"id":100006931,"name":"ListContainers","signature":"func (in instrumentedRuntimeService) ListContainers(ctx context.Context, filter *runtimeapi.ContainerFilter) ([]*runtimeapi.Container, error)","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) ListContainers(ctx context.Context, filter *runtimeapi.ContainerFilter) ([]*runtimeapi.Container, error) {\n\tconst operation = \"list_containers\"\n\tdefer recordOperation(operation, time.Now())\n\n\tout, err := in.service.ListContainers(ctx, filter)\n\trecordError(operation, err)\n\treturn out, err\n}","line":{"from":117,"to":124}} {"id":100006932,"name":"ContainerStatus","signature":"func (in instrumentedRuntimeService) ContainerStatus(ctx context.Context, containerID string, verbose bool) (*runtimeapi.ContainerStatusResponse, error)","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) ContainerStatus(ctx context.Context, containerID string, verbose bool) (*runtimeapi.ContainerStatusResponse, error) {\n\tconst operation = \"container_status\"\n\tdefer recordOperation(operation, time.Now())\n\n\tout, err := in.service.ContainerStatus(ctx, containerID, verbose)\n\trecordError(operation, err)\n\treturn out, err\n}","line":{"from":126,"to":133}} {"id":100006933,"name":"UpdateContainerResources","signature":"func (in instrumentedRuntimeService) UpdateContainerResources(ctx context.Context, containerID string, resources *runtimeapi.ContainerResources) error","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) UpdateContainerResources(ctx context.Context, containerID string, resources *runtimeapi.ContainerResources) error {\n\tconst operation = \"update_container\"\n\tdefer recordOperation(operation, time.Now())\n\n\terr := in.service.UpdateContainerResources(ctx, containerID, resources)\n\trecordError(operation, err)\n\treturn err\n}","line":{"from":135,"to":142}} {"id":100006934,"name":"ReopenContainerLog","signature":"func (in instrumentedRuntimeService) ReopenContainerLog(ctx context.Context, containerID string) error","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) ReopenContainerLog(ctx context.Context, containerID string) error {\n\tconst operation = \"reopen_container_log\"\n\tdefer recordOperation(operation, time.Now())\n\n\terr := in.service.ReopenContainerLog(ctx, containerID)\n\trecordError(operation, err)\n\treturn err\n}","line":{"from":144,"to":151}} {"id":100006935,"name":"ExecSync","signature":"func (in instrumentedRuntimeService) ExecSync(ctx context.Context, containerID string, cmd []string, timeout time.Duration) ([]byte, []byte, error)","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) ExecSync(ctx context.Context, containerID string, cmd []string, timeout time.Duration) ([]byte, []byte, error) {\n\tconst operation = \"exec_sync\"\n\tdefer recordOperation(operation, time.Now())\n\n\tstdout, stderr, err := in.service.ExecSync(ctx, containerID, cmd, timeout)\n\trecordError(operation, err)\n\treturn stdout, stderr, err\n}","line":{"from":153,"to":160}} {"id":100006936,"name":"Exec","signature":"func (in instrumentedRuntimeService) Exec(ctx context.Context, req *runtimeapi.ExecRequest) (*runtimeapi.ExecResponse, error)","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) Exec(ctx context.Context, req *runtimeapi.ExecRequest) (*runtimeapi.ExecResponse, error) {\n\tconst operation = \"exec\"\n\tdefer recordOperation(operation, time.Now())\n\n\tresp, err := in.service.Exec(ctx, req)\n\trecordError(operation, err)\n\treturn resp, err\n}","line":{"from":162,"to":169}} {"id":100006937,"name":"Attach","signature":"func (in instrumentedRuntimeService) Attach(ctx context.Context, req *runtimeapi.AttachRequest) (*runtimeapi.AttachResponse, error)","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) Attach(ctx context.Context, req *runtimeapi.AttachRequest) (*runtimeapi.AttachResponse, error) {\n\tconst operation = \"attach\"\n\tdefer recordOperation(operation, time.Now())\n\n\tresp, err := in.service.Attach(ctx, req)\n\trecordError(operation, err)\n\treturn resp, err\n}","line":{"from":171,"to":178}} {"id":100006938,"name":"RunPodSandbox","signature":"func (in instrumentedRuntimeService) RunPodSandbox(ctx context.Context, config *runtimeapi.PodSandboxConfig, runtimeHandler string) (string, error)","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) RunPodSandbox(ctx context.Context, config *runtimeapi.PodSandboxConfig, runtimeHandler string) (string, error) {\n\tconst operation = \"run_podsandbox\"\n\tstartTime := time.Now()\n\tdefer recordOperation(operation, startTime)\n\tdefer metrics.RunPodSandboxDuration.WithLabelValues(runtimeHandler).Observe(metrics.SinceInSeconds(startTime))\n\n\tout, err := in.service.RunPodSandbox(ctx, config, runtimeHandler)\n\trecordError(operation, err)\n\tif err != nil {\n\t\tmetrics.RunPodSandboxErrors.WithLabelValues(runtimeHandler).Inc()\n\t}\n\treturn out, err\n}","line":{"from":180,"to":192}} {"id":100006939,"name":"StopPodSandbox","signature":"func (in instrumentedRuntimeService) StopPodSandbox(ctx context.Context, podSandboxID string) error","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) StopPodSandbox(ctx context.Context, podSandboxID string) error {\n\tconst operation = \"stop_podsandbox\"\n\tdefer recordOperation(operation, time.Now())\n\n\terr := in.service.StopPodSandbox(ctx, podSandboxID)\n\trecordError(operation, err)\n\treturn err\n}","line":{"from":194,"to":201}} {"id":100006940,"name":"RemovePodSandbox","signature":"func (in instrumentedRuntimeService) RemovePodSandbox(ctx context.Context, podSandboxID string) error","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) RemovePodSandbox(ctx context.Context, podSandboxID string) error {\n\tconst operation = \"remove_podsandbox\"\n\tdefer recordOperation(operation, time.Now())\n\n\terr := in.service.RemovePodSandbox(ctx, podSandboxID)\n\trecordError(operation, err)\n\treturn err\n}","line":{"from":203,"to":210}} {"id":100006941,"name":"PodSandboxStatus","signature":"func (in instrumentedRuntimeService) PodSandboxStatus(ctx context.Context, podSandboxID string, verbose bool) (*runtimeapi.PodSandboxStatusResponse, error)","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) PodSandboxStatus(ctx context.Context, podSandboxID string, verbose bool) (*runtimeapi.PodSandboxStatusResponse, error) {\n\tconst operation = \"podsandbox_status\"\n\tdefer recordOperation(operation, time.Now())\n\n\tout, err := in.service.PodSandboxStatus(ctx, podSandboxID, verbose)\n\trecordError(operation, err)\n\treturn out, err\n}","line":{"from":212,"to":219}} {"id":100006942,"name":"ListPodSandbox","signature":"func (in instrumentedRuntimeService) ListPodSandbox(ctx context.Context, filter *runtimeapi.PodSandboxFilter) ([]*runtimeapi.PodSandbox, error)","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) ListPodSandbox(ctx context.Context, filter *runtimeapi.PodSandboxFilter) ([]*runtimeapi.PodSandbox, error) {\n\tconst operation = \"list_podsandbox\"\n\tdefer recordOperation(operation, time.Now())\n\n\tout, err := in.service.ListPodSandbox(ctx, filter)\n\trecordError(operation, err)\n\treturn out, err\n}","line":{"from":221,"to":228}} {"id":100006943,"name":"ContainerStats","signature":"func (in instrumentedRuntimeService) ContainerStats(ctx context.Context, containerID string) (*runtimeapi.ContainerStats, error)","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) ContainerStats(ctx context.Context, containerID string) (*runtimeapi.ContainerStats, error) {\n\tconst operation = \"container_stats\"\n\tdefer recordOperation(operation, time.Now())\n\n\tout, err := in.service.ContainerStats(ctx, containerID)\n\trecordError(operation, err)\n\treturn out, err\n}","line":{"from":230,"to":237}} {"id":100006944,"name":"ListContainerStats","signature":"func (in instrumentedRuntimeService) ListContainerStats(ctx context.Context, filter *runtimeapi.ContainerStatsFilter) ([]*runtimeapi.ContainerStats, error)","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) ListContainerStats(ctx context.Context, filter *runtimeapi.ContainerStatsFilter) ([]*runtimeapi.ContainerStats, error) {\n\tconst operation = \"list_container_stats\"\n\tdefer recordOperation(operation, time.Now())\n\n\tout, err := in.service.ListContainerStats(ctx, filter)\n\trecordError(operation, err)\n\treturn out, err\n}","line":{"from":239,"to":246}} {"id":100006945,"name":"PodSandboxStats","signature":"func (in instrumentedRuntimeService) PodSandboxStats(ctx context.Context, podSandboxID string) (*runtimeapi.PodSandboxStats, error)","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) PodSandboxStats(ctx context.Context, podSandboxID string) (*runtimeapi.PodSandboxStats, error) {\n\tconst operation = \"podsandbox_stats\"\n\tdefer recordOperation(operation, time.Now())\n\n\tout, err := in.service.PodSandboxStats(ctx, podSandboxID)\n\trecordError(operation, err)\n\treturn out, err\n}","line":{"from":248,"to":255}} {"id":100006946,"name":"ListPodSandboxStats","signature":"func (in instrumentedRuntimeService) ListPodSandboxStats(ctx context.Context, filter *runtimeapi.PodSandboxStatsFilter) ([]*runtimeapi.PodSandboxStats, error)","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) ListPodSandboxStats(ctx context.Context, filter *runtimeapi.PodSandboxStatsFilter) ([]*runtimeapi.PodSandboxStats, error) {\n\tconst operation = \"list_podsandbox_stats\"\n\tdefer recordOperation(operation, time.Now())\n\n\tout, err := in.service.ListPodSandboxStats(ctx, filter)\n\trecordError(operation, err)\n\treturn out, err\n}","line":{"from":257,"to":264}} {"id":100006947,"name":"PortForward","signature":"func (in instrumentedRuntimeService) PortForward(ctx context.Context, req *runtimeapi.PortForwardRequest) (*runtimeapi.PortForwardResponse, error)","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) PortForward(ctx context.Context, req *runtimeapi.PortForwardRequest) (*runtimeapi.PortForwardResponse, error) {\n\tconst operation = \"port_forward\"\n\tdefer recordOperation(operation, time.Now())\n\n\tresp, err := in.service.PortForward(ctx, req)\n\trecordError(operation, err)\n\treturn resp, err\n}","line":{"from":266,"to":273}} {"id":100006948,"name":"UpdateRuntimeConfig","signature":"func (in instrumentedRuntimeService) UpdateRuntimeConfig(ctx context.Context, runtimeConfig *runtimeapi.RuntimeConfig) error","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) UpdateRuntimeConfig(ctx context.Context, runtimeConfig *runtimeapi.RuntimeConfig) error {\n\tconst operation = \"update_runtime_config\"\n\tdefer recordOperation(operation, time.Now())\n\n\terr := in.service.UpdateRuntimeConfig(ctx, runtimeConfig)\n\trecordError(operation, err)\n\treturn err\n}","line":{"from":275,"to":282}} {"id":100006949,"name":"ListImages","signature":"func (in instrumentedImageManagerService) ListImages(ctx context.Context, filter *runtimeapi.ImageFilter) ([]*runtimeapi.Image, error)","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedImageManagerService) ListImages(ctx context.Context, filter *runtimeapi.ImageFilter) ([]*runtimeapi.Image, error) {\n\tconst operation = \"list_images\"\n\tdefer recordOperation(operation, time.Now())\n\n\tout, err := in.service.ListImages(ctx, filter)\n\trecordError(operation, err)\n\treturn out, err\n}","line":{"from":284,"to":291}} {"id":100006950,"name":"ImageStatus","signature":"func (in instrumentedImageManagerService) ImageStatus(ctx context.Context, image *runtimeapi.ImageSpec, verbose bool) (*runtimeapi.ImageStatusResponse, error)","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedImageManagerService) ImageStatus(ctx context.Context, image *runtimeapi.ImageSpec, verbose bool) (*runtimeapi.ImageStatusResponse, error) {\n\tconst operation = \"image_status\"\n\tdefer recordOperation(operation, time.Now())\n\n\tout, err := in.service.ImageStatus(ctx, image, verbose)\n\trecordError(operation, err)\n\treturn out, err\n}","line":{"from":293,"to":300}} {"id":100006951,"name":"PullImage","signature":"func (in instrumentedImageManagerService) PullImage(ctx context.Context, image *runtimeapi.ImageSpec, auth *runtimeapi.AuthConfig, podSandboxConfig *runtimeapi.PodSandboxConfig) (string, error)","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedImageManagerService) PullImage(ctx context.Context, image *runtimeapi.ImageSpec, auth *runtimeapi.AuthConfig, podSandboxConfig *runtimeapi.PodSandboxConfig) (string, error) {\n\tconst operation = \"pull_image\"\n\tdefer recordOperation(operation, time.Now())\n\n\timageRef, err := in.service.PullImage(ctx, image, auth, podSandboxConfig)\n\trecordError(operation, err)\n\treturn imageRef, err\n}","line":{"from":302,"to":309}} {"id":100006952,"name":"RemoveImage","signature":"func (in instrumentedImageManagerService) RemoveImage(ctx context.Context, image *runtimeapi.ImageSpec) error","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedImageManagerService) RemoveImage(ctx context.Context, image *runtimeapi.ImageSpec) error {\n\tconst operation = \"remove_image\"\n\tdefer recordOperation(operation, time.Now())\n\n\terr := in.service.RemoveImage(ctx, image)\n\trecordError(operation, err)\n\treturn err\n}","line":{"from":311,"to":318}} {"id":100006953,"name":"ImageFsInfo","signature":"func (in instrumentedImageManagerService) ImageFsInfo(ctx context.Context) ([]*runtimeapi.FilesystemUsage, error)","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedImageManagerService) ImageFsInfo(ctx context.Context) ([]*runtimeapi.FilesystemUsage, error) {\n\tconst operation = \"image_fs_info\"\n\tdefer recordOperation(operation, time.Now())\n\n\tfsInfo, err := in.service.ImageFsInfo(ctx)\n\trecordError(operation, err)\n\treturn fsInfo, nil\n}","line":{"from":320,"to":327}} {"id":100006954,"name":"CheckpointContainer","signature":"func (in instrumentedRuntimeService) CheckpointContainer(ctx context.Context, options *runtimeapi.CheckpointContainerRequest) error","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) CheckpointContainer(ctx context.Context, options *runtimeapi.CheckpointContainerRequest) error {\n\tconst operation = \"checkpoint_container\"\n\tdefer recordOperation(operation, time.Now())\n\n\terr := in.service.CheckpointContainer(ctx, options)\n\trecordError(operation, err)\n\treturn err\n}","line":{"from":329,"to":336}} {"id":100006955,"name":"GetContainerEvents","signature":"func (in instrumentedRuntimeService) GetContainerEvents(containerEventsCh chan *runtimeapi.ContainerEventResponse) error","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) GetContainerEvents(containerEventsCh chan *runtimeapi.ContainerEventResponse) error {\n\tconst operation = \"get_container_events\"\n\tdefer recordOperation(operation, time.Now())\n\n\terr := in.service.GetContainerEvents(containerEventsCh)\n\trecordError(operation, err)\n\treturn err\n}","line":{"from":338,"to":345}} {"id":100006956,"name":"ListMetricDescriptors","signature":"func (in instrumentedRuntimeService) ListMetricDescriptors(ctx context.Context) ([]*runtimeapi.MetricDescriptor, error)","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) ListMetricDescriptors(ctx context.Context) ([]*runtimeapi.MetricDescriptor, error) {\n\tconst operation = \"list_metric_descriptors\"\n\tdefer recordOperation(operation, time.Now())\n\n\tout, err := in.service.ListMetricDescriptors(ctx)\n\trecordError(operation, err)\n\treturn out, err\n}","line":{"from":347,"to":354}} {"id":100006957,"name":"ListPodSandboxMetrics","signature":"func (in instrumentedRuntimeService) ListPodSandboxMetrics(ctx context.Context) ([]*runtimeapi.PodSandboxMetrics, error)","file":"pkg/kubelet/kuberuntime/instrumented_services.go","code":"func (in instrumentedRuntimeService) ListPodSandboxMetrics(ctx context.Context) ([]*runtimeapi.PodSandboxMetrics, error) {\n\tconst operation = \"list_podsandbox_metrics\"\n\tdefer recordOperation(operation, time.Now())\n\n\tout, err := in.service.ListPodSandboxMetrics(ctx)\n\trecordError(operation, err)\n\treturn out, err\n}","line":{"from":356,"to":363}} {"id":100006958,"name":"recordContainerEvent","signature":"func (m *kubeGenericRuntimeManager) recordContainerEvent(pod *v1.Pod, container *v1.Container, containerID, eventType, reason, message string, args ...interface{})","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// recordContainerEvent should be used by the runtime manager for all container related events.\n// it has sanity checks to ensure that we do not write events that can abuse our masters.\n// in particular, it ensures that a containerID never appears in an event message as that\n// is prone to causing a lot of distinct events that do not count well.\n// it replaces any reference to a containerID with the containerName which is stable, and is what users know.\nfunc (m *kubeGenericRuntimeManager) recordContainerEvent(pod *v1.Pod, container *v1.Container, containerID, eventType, reason, message string, args ...interface{}) {\n\tref, err := kubecontainer.GenerateContainerRef(pod, container)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Can't make a container ref\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID, \"containerName\", container.Name)\n\t\treturn\n\t}\n\teventMessage := message\n\tif len(args) \u003e 0 {\n\t\teventMessage = fmt.Sprintf(message, args...)\n\t}\n\t// this is a hack, but often the error from the runtime includes the containerID\n\t// which kills our ability to deduplicate events. this protection makes a huge\n\t// difference in the number of unique events\n\tif containerID != \"\" {\n\t\teventMessage = strings.Replace(eventMessage, containerID, container.Name, -1)\n\t}\n\tm.recorder.Event(ref, eventType, reason, eventMessage)\n}","line":{"from":74,"to":96}} {"id":100006959,"name":"containerStartSpec","signature":"func containerStartSpec(c *v1.Container) *startSpec","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"func containerStartSpec(c *v1.Container) *startSpec {\n\treturn \u0026startSpec{container: c}\n}","line":{"from":106,"to":108}} {"id":100006960,"name":"ephemeralContainerStartSpec","signature":"func ephemeralContainerStartSpec(ec *v1.EphemeralContainer) *startSpec","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"func ephemeralContainerStartSpec(ec *v1.EphemeralContainer) *startSpec {\n\treturn \u0026startSpec{\n\t\tcontainer: (*v1.Container)(\u0026ec.EphemeralContainerCommon),\n\t\tephemeralContainer: ec,\n\t}\n}","line":{"from":110,"to":115}} {"id":100006961,"name":"getTargetID","signature":"func (s *startSpec) getTargetID(podStatus *kubecontainer.PodStatus) (*kubecontainer.ContainerID, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// getTargetID returns the kubecontainer.ContainerID for ephemeral container namespace\n// targeting. The target is stored as EphemeralContainer.TargetContainerName, which must be\n// resolved to a ContainerID using podStatus. The target container must already exist, which\n// usually isn't a problem since ephemeral containers aren't allowed at pod creation time.\nfunc (s *startSpec) getTargetID(podStatus *kubecontainer.PodStatus) (*kubecontainer.ContainerID, error) {\n\tif s.ephemeralContainer == nil || s.ephemeralContainer.TargetContainerName == \"\" {\n\t\treturn nil, nil\n\t}\n\n\ttargetStatus := podStatus.FindContainerStatusByName(s.ephemeralContainer.TargetContainerName)\n\tif targetStatus == nil {\n\t\treturn nil, fmt.Errorf(\"unable to find target container %v\", s.ephemeralContainer.TargetContainerName)\n\t}\n\n\treturn \u0026targetStatus.ID, nil\n}","line":{"from":117,"to":132}} {"id":100006962,"name":"calcRestartCountByLogDir","signature":"func calcRestartCountByLogDir(path string) (int, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"func calcRestartCountByLogDir(path string) (int, error) {\n\t// if the path doesn't exist then it's not an error\n\tif _, err := os.Stat(path); err != nil {\n\t\treturn 0, nil\n\t}\n\trestartCount := int(0)\n\tfiles, err := os.ReadDir(path)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif len(files) == 0 {\n\t\treturn 0, nil\n\t}\n\trestartCountLogFileRegex := regexp.MustCompile(`^(\\d+)\\.log(\\..*)?`)\n\tfor _, file := range files {\n\t\tif file.IsDir() {\n\t\t\tcontinue\n\t\t}\n\t\tmatches := restartCountLogFileRegex.FindStringSubmatch(file.Name())\n\t\tif len(matches) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tcount, err := strconv.Atoi(matches[1])\n\t\tif err != nil {\n\t\t\t// unlikely kubelet created this file,\n\t\t\t// likely custom file with random numbers as a name\n\t\t\tcontinue\n\t\t}\n\t\tcount++\n\t\tif count \u003e restartCount {\n\t\t\trestartCount = count\n\t\t}\n\t}\n\treturn restartCount, nil\n}","line":{"from":134,"to":168}} {"id":100006963,"name":"startContainer","signature":"func (m *kubeGenericRuntimeManager) startContainer(ctx context.Context, podSandboxID string, podSandboxConfig *runtimeapi.PodSandboxConfig, spec *startSpec, pod *v1.Pod, podStatus *kubecontainer.PodStatus, pullSecrets []v1.Secret, podIP string, podIPs []string) (string, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// startContainer starts a container and returns a message indicates why it is failed on error.\n// It starts the container through the following steps:\n// * pull the image\n// * create the container\n// * start the container\n// * run the post start lifecycle hooks (if applicable)\nfunc (m *kubeGenericRuntimeManager) startContainer(ctx context.Context, podSandboxID string, podSandboxConfig *runtimeapi.PodSandboxConfig, spec *startSpec, pod *v1.Pod, podStatus *kubecontainer.PodStatus, pullSecrets []v1.Secret, podIP string, podIPs []string) (string, error) {\n\tcontainer := spec.container\n\n\t// Step 1: pull the image.\n\timageRef, msg, err := m.imagePuller.EnsureImageExists(ctx, pod, container, pullSecrets, podSandboxConfig)\n\tif err != nil {\n\t\ts, _ := grpcstatus.FromError(err)\n\t\tm.recordContainerEvent(pod, container, \"\", v1.EventTypeWarning, events.FailedToCreateContainer, \"Error: %v\", s.Message())\n\t\treturn msg, err\n\t}\n\n\t// Step 2: create the container.\n\t// For a new container, the RestartCount should be 0\n\trestartCount := 0\n\tcontainerStatus := podStatus.FindContainerStatusByName(container.Name)\n\tif containerStatus != nil {\n\t\trestartCount = containerStatus.RestartCount + 1\n\t} else {\n\t\t// The container runtime keeps state on container statuses and\n\t\t// what the container restart count is. When nodes are rebooted\n\t\t// some container runtimes clear their state which causes the\n\t\t// restartCount to be reset to 0. This causes the logfile to\n\t\t// start at 0.log, which either overwrites or appends to the\n\t\t// already existing log.\n\t\t//\n\t\t// We are checking to see if the log directory exists, and find\n\t\t// the latest restartCount by checking the log name -\n\t\t// {restartCount}.log - and adding 1 to it.\n\t\tlogDir := BuildContainerLogsDirectory(pod.Namespace, pod.Name, pod.UID, container.Name)\n\t\trestartCount, err = calcRestartCountByLogDir(logDir)\n\t\tif err != nil {\n\t\t\tklog.InfoS(\"Cannot calculate restartCount from the log directory\", \"logDir\", logDir, \"err\", err)\n\t\t\trestartCount = 0\n\t\t}\n\t}\n\n\ttarget, err := spec.getTargetID(podStatus)\n\tif err != nil {\n\t\ts, _ := grpcstatus.FromError(err)\n\t\tm.recordContainerEvent(pod, container, \"\", v1.EventTypeWarning, events.FailedToCreateContainer, \"Error: %v\", s.Message())\n\t\treturn s.Message(), ErrCreateContainerConfig\n\t}\n\n\tcontainerConfig, cleanupAction, err := m.generateContainerConfig(ctx, container, pod, restartCount, podIP, imageRef, podIPs, target)\n\tif cleanupAction != nil {\n\t\tdefer cleanupAction()\n\t}\n\tif err != nil {\n\t\ts, _ := grpcstatus.FromError(err)\n\t\tm.recordContainerEvent(pod, container, \"\", v1.EventTypeWarning, events.FailedToCreateContainer, \"Error: %v\", s.Message())\n\t\treturn s.Message(), ErrCreateContainerConfig\n\t}\n\n\terr = m.internalLifecycle.PreCreateContainer(pod, container, containerConfig)\n\tif err != nil {\n\t\ts, _ := grpcstatus.FromError(err)\n\t\tm.recordContainerEvent(pod, container, \"\", v1.EventTypeWarning, events.FailedToCreateContainer, \"Internal PreCreateContainer hook failed: %v\", s.Message())\n\t\treturn s.Message(), ErrPreCreateHook\n\t}\n\n\tcontainerID, err := m.runtimeService.CreateContainer(ctx, podSandboxID, containerConfig, podSandboxConfig)\n\tif err != nil {\n\t\ts, _ := grpcstatus.FromError(err)\n\t\tm.recordContainerEvent(pod, container, containerID, v1.EventTypeWarning, events.FailedToCreateContainer, \"Error: %v\", s.Message())\n\t\treturn s.Message(), ErrCreateContainer\n\t}\n\terr = m.internalLifecycle.PreStartContainer(pod, container, containerID)\n\tif err != nil {\n\t\ts, _ := grpcstatus.FromError(err)\n\t\tm.recordContainerEvent(pod, container, containerID, v1.EventTypeWarning, events.FailedToStartContainer, \"Internal PreStartContainer hook failed: %v\", s.Message())\n\t\treturn s.Message(), ErrPreStartHook\n\t}\n\tm.recordContainerEvent(pod, container, containerID, v1.EventTypeNormal, events.CreatedContainer, fmt.Sprintf(\"Created container %s\", container.Name))\n\n\t// Step 3: start the container.\n\terr = m.runtimeService.StartContainer(ctx, containerID)\n\tif err != nil {\n\t\ts, _ := grpcstatus.FromError(err)\n\t\tm.recordContainerEvent(pod, container, containerID, v1.EventTypeWarning, events.FailedToStartContainer, \"Error: %v\", s.Message())\n\t\treturn s.Message(), kubecontainer.ErrRunContainer\n\t}\n\tm.recordContainerEvent(pod, container, containerID, v1.EventTypeNormal, events.StartedContainer, fmt.Sprintf(\"Started container %s\", container.Name))\n\n\t// Symlink container logs to the legacy container log location for cluster logging\n\t// support.\n\t// TODO(random-liu): Remove this after cluster logging supports CRI container log path.\n\tcontainerMeta := containerConfig.GetMetadata()\n\tsandboxMeta := podSandboxConfig.GetMetadata()\n\tlegacySymlink := legacyLogSymlink(containerID, containerMeta.Name, sandboxMeta.Name,\n\t\tsandboxMeta.Namespace)\n\tcontainerLog := filepath.Join(podSandboxConfig.LogDirectory, containerConfig.LogPath)\n\t// only create legacy symlink if containerLog path exists (or the error is not IsNotExist).\n\t// Because if containerLog path does not exist, only dangling legacySymlink is created.\n\t// This dangling legacySymlink is later removed by container gc, so it does not make sense\n\t// to create it in the first place. it happens when journald logging driver is used with docker.\n\tif _, err := m.osInterface.Stat(containerLog); !os.IsNotExist(err) {\n\t\tif err := m.osInterface.Symlink(containerLog, legacySymlink); err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to create legacy symbolic link\", \"path\", legacySymlink,\n\t\t\t\t\"containerID\", containerID, \"containerLogPath\", containerLog)\n\t\t}\n\t}\n\n\t// Step 4: execute the post start hook.\n\tif container.Lifecycle != nil \u0026\u0026 container.Lifecycle.PostStart != nil {\n\t\tkubeContainerID := kubecontainer.ContainerID{\n\t\t\tType: m.runtimeName,\n\t\t\tID: containerID,\n\t\t}\n\t\tmsg, handlerErr := m.runner.Run(ctx, kubeContainerID, pod, container, container.Lifecycle.PostStart)\n\t\tif handlerErr != nil {\n\t\t\tklog.ErrorS(handlerErr, \"Failed to execute PostStartHook\", \"pod\", klog.KObj(pod),\n\t\t\t\t\"podUID\", pod.UID, \"containerName\", container.Name, \"containerID\", kubeContainerID.String())\n\t\t\t// do not record the message in the event so that secrets won't leak from the server.\n\t\t\tm.recordContainerEvent(pod, container, kubeContainerID.ID, v1.EventTypeWarning, events.FailedPostStartHook, \"PostStartHook failed\")\n\t\t\tif err := m.killContainer(ctx, pod, kubeContainerID, container.Name, \"FailedPostStartHook\", reasonFailedPostStartHook, nil); err != nil {\n\t\t\t\tklog.ErrorS(err, \"Failed to kill container\", \"pod\", klog.KObj(pod),\n\t\t\t\t\t\"podUID\", pod.UID, \"containerName\", container.Name, \"containerID\", kubeContainerID.String())\n\t\t\t}\n\t\t\treturn msg, ErrPostStartHook\n\t\t}\n\t}\n\n\treturn \"\", nil\n}","line":{"from":170,"to":299}} {"id":100006964,"name":"generateContainerConfig","signature":"func (m *kubeGenericRuntimeManager) generateContainerConfig(ctx context.Context, container *v1.Container, pod *v1.Pod, restartCount int, podIP, imageRef string, podIPs []string, nsTarget *kubecontainer.ContainerID) (*runtimeapi.ContainerConfig, func(), error)","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// generateContainerConfig generates container config for kubelet runtime v1.\nfunc (m *kubeGenericRuntimeManager) generateContainerConfig(ctx context.Context, container *v1.Container, pod *v1.Pod, restartCount int, podIP, imageRef string, podIPs []string, nsTarget *kubecontainer.ContainerID) (*runtimeapi.ContainerConfig, func(), error) {\n\topts, cleanupAction, err := m.runtimeHelper.GenerateRunContainerOptions(ctx, pod, container, podIP, podIPs)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tuid, username, err := m.getImageUser(ctx, container.Image)\n\tif err != nil {\n\t\treturn nil, cleanupAction, err\n\t}\n\n\t// Verify RunAsNonRoot. Non-root verification only supports numeric user.\n\tif err := verifyRunAsNonRoot(pod, container, uid, username); err != nil {\n\t\treturn nil, cleanupAction, err\n\t}\n\n\tcommand, args := kubecontainer.ExpandContainerCommandAndArgs(container, opts.Envs)\n\tlogDir := BuildContainerLogsDirectory(pod.Namespace, pod.Name, pod.UID, container.Name)\n\terr = m.osInterface.MkdirAll(logDir, 0755)\n\tif err != nil {\n\t\treturn nil, cleanupAction, fmt.Errorf(\"create container log directory for container %s failed: %v\", container.Name, err)\n\t}\n\tcontainerLogsPath := buildContainerLogsPath(container.Name, restartCount)\n\trestartCountUint32 := uint32(restartCount)\n\tconfig := \u0026runtimeapi.ContainerConfig{\n\t\tMetadata: \u0026runtimeapi.ContainerMetadata{\n\t\t\tName: container.Name,\n\t\t\tAttempt: restartCountUint32,\n\t\t},\n\t\tImage: \u0026runtimeapi.ImageSpec{Image: imageRef},\n\t\tCommand: command,\n\t\tArgs: args,\n\t\tWorkingDir: container.WorkingDir,\n\t\tLabels: newContainerLabels(container, pod),\n\t\tAnnotations: newContainerAnnotations(container, pod, restartCount, opts),\n\t\tDevices: makeDevices(opts),\n\t\tCDIDevices: makeCDIDevices(opts),\n\t\tMounts: m.makeMounts(opts, container),\n\t\tLogPath: containerLogsPath,\n\t\tStdin: container.Stdin,\n\t\tStdinOnce: container.StdinOnce,\n\t\tTty: container.TTY,\n\t}\n\n\t// set platform specific configurations.\n\tif err := m.applyPlatformSpecificContainerConfig(config, container, pod, uid, username, nsTarget); err != nil {\n\t\treturn nil, cleanupAction, err\n\t}\n\n\t// set environment variables\n\tenvs := make([]*runtimeapi.KeyValue, len(opts.Envs))\n\tfor idx := range opts.Envs {\n\t\te := opts.Envs[idx]\n\t\tenvs[idx] = \u0026runtimeapi.KeyValue{\n\t\t\tKey: e.Name,\n\t\t\tValue: e.Value,\n\t\t}\n\t}\n\tconfig.Envs = envs\n\n\treturn config, cleanupAction, nil\n}","line":{"from":301,"to":363}} {"id":100006965,"name":"updateContainerResources","signature":"func (m *kubeGenericRuntimeManager) updateContainerResources(pod *v1.Pod, container *v1.Container, containerID kubecontainer.ContainerID) error","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"func (m *kubeGenericRuntimeManager) updateContainerResources(pod *v1.Pod, container *v1.Container, containerID kubecontainer.ContainerID) error {\n\tcontainerResources := m.generateContainerResources(pod, container)\n\tif containerResources == nil {\n\t\treturn fmt.Errorf(\"container %q updateContainerResources failed: cannot generate resources config\", containerID.String())\n\t}\n\tctx := context.Background()\n\terr := m.runtimeService.UpdateContainerResources(ctx, containerID.ID, containerResources)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"UpdateContainerResources failed\", \"container\", containerID.String())\n\t}\n\treturn err\n}","line":{"from":365,"to":376}} {"id":100006966,"name":"makeDevices","signature":"func makeDevices(opts *kubecontainer.RunContainerOptions) []*runtimeapi.Device","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// makeDevices generates container devices for kubelet runtime v1.\nfunc makeDevices(opts *kubecontainer.RunContainerOptions) []*runtimeapi.Device {\n\tdevices := make([]*runtimeapi.Device, len(opts.Devices))\n\n\tfor idx := range opts.Devices {\n\t\tdevice := opts.Devices[idx]\n\t\tdevices[idx] = \u0026runtimeapi.Device{\n\t\t\tHostPath: device.PathOnHost,\n\t\t\tContainerPath: device.PathInContainer,\n\t\t\tPermissions: device.Permissions,\n\t\t}\n\t}\n\n\treturn devices\n}","line":{"from":378,"to":392}} {"id":100006967,"name":"makeCDIDevices","signature":"func makeCDIDevices(opts *kubecontainer.RunContainerOptions) []*runtimeapi.CDIDevice","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// makeCDIDevices generates container CDIDevices for kubelet runtime v1.\nfunc makeCDIDevices(opts *kubecontainer.RunContainerOptions) []*runtimeapi.CDIDevice {\n\tdevices := make([]*runtimeapi.CDIDevice, len(opts.CDIDevices))\n\n\tfor i, device := range opts.CDIDevices {\n\t\tdevices[i] = \u0026runtimeapi.CDIDevice{\n\t\t\tName: device.Name,\n\t\t}\n\t}\n\n\treturn devices\n}","line":{"from":394,"to":405}} {"id":100006968,"name":"makeMounts","signature":"func (m *kubeGenericRuntimeManager) makeMounts(opts *kubecontainer.RunContainerOptions, container *v1.Container) []*runtimeapi.Mount","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// makeMounts generates container volume mounts for kubelet runtime v1.\nfunc (m *kubeGenericRuntimeManager) makeMounts(opts *kubecontainer.RunContainerOptions, container *v1.Container) []*runtimeapi.Mount {\n\tvolumeMounts := []*runtimeapi.Mount{}\n\n\tfor idx := range opts.Mounts {\n\t\tv := opts.Mounts[idx]\n\t\tselinuxRelabel := v.SELinuxRelabel \u0026\u0026 selinux.GetEnabled()\n\t\tmount := \u0026runtimeapi.Mount{\n\t\t\tHostPath: v.HostPath,\n\t\t\tContainerPath: v.ContainerPath,\n\t\t\tReadonly: v.ReadOnly,\n\t\t\tSelinuxRelabel: selinuxRelabel,\n\t\t\tPropagation: v.Propagation,\n\t\t}\n\n\t\tvolumeMounts = append(volumeMounts, mount)\n\t}\n\n\t// The reason we create and mount the log file in here (not in kubelet) is because\n\t// the file's location depends on the ID of the container, and we need to create and\n\t// mount the file before actually starting the container.\n\tif opts.PodContainerDir != \"\" \u0026\u0026 len(container.TerminationMessagePath) != 0 {\n\t\t// Because the PodContainerDir contains pod uid and container name which is unique enough,\n\t\t// here we just add a random id to make the path unique for different instances\n\t\t// of the same container.\n\t\tcid := makeUID()\n\t\tcontainerLogPath := filepath.Join(opts.PodContainerDir, cid)\n\t\tfs, err := m.osInterface.Create(containerLogPath)\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"error on creating termination-log file %q: %v\", containerLogPath, err))\n\t\t} else {\n\t\t\tfs.Close()\n\n\t\t\t// Chmod is needed because os.Create() ends up calling\n\t\t\t// open(2) to create the file, so the final mode used is \"mode \u0026\n\t\t\t// ~umask\". But we want to make sure the specified mode is used\n\t\t\t// in the file no matter what the umask is.\n\t\t\tif err := m.osInterface.Chmod(containerLogPath, 0666); err != nil {\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"unable to set termination-log file permissions %q: %v\", containerLogPath, err))\n\t\t\t}\n\n\t\t\t// Volume Mounts fail on Windows if it is not of the form C:/\n\t\t\tcontainerLogPath = volumeutil.MakeAbsolutePath(goruntime.GOOS, containerLogPath)\n\t\t\tterminationMessagePath := volumeutil.MakeAbsolutePath(goruntime.GOOS, container.TerminationMessagePath)\n\t\t\tselinuxRelabel := selinux.GetEnabled()\n\t\t\tvolumeMounts = append(volumeMounts, \u0026runtimeapi.Mount{\n\t\t\t\tHostPath: containerLogPath,\n\t\t\t\tContainerPath: terminationMessagePath,\n\t\t\t\tSelinuxRelabel: selinuxRelabel,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn volumeMounts\n}","line":{"from":407,"to":461}} {"id":100006969,"name":"getKubeletContainers","signature":"func (m *kubeGenericRuntimeManager) getKubeletContainers(ctx context.Context, allContainers bool) ([]*runtimeapi.Container, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// getKubeletContainers lists containers managed by kubelet.\n// The boolean parameter specifies whether returns all containers including\n// those already exited and dead containers (used for garbage collection).\nfunc (m *kubeGenericRuntimeManager) getKubeletContainers(ctx context.Context, allContainers bool) ([]*runtimeapi.Container, error) {\n\tfilter := \u0026runtimeapi.ContainerFilter{}\n\tif !allContainers {\n\t\tfilter.State = \u0026runtimeapi.ContainerStateValue{\n\t\t\tState: runtimeapi.ContainerState_CONTAINER_RUNNING,\n\t\t}\n\t}\n\n\tcontainers, err := m.runtimeService.ListContainers(ctx, filter)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"ListContainers failed\")\n\t\treturn nil, err\n\t}\n\n\treturn containers, nil\n}","line":{"from":463,"to":481}} {"id":100006970,"name":"makeUID","signature":"func makeUID() string","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// makeUID returns a randomly generated string.\nfunc makeUID() string {\n\treturn fmt.Sprintf(\"%08x\", rand.Uint32())\n}","line":{"from":483,"to":486}} {"id":100006971,"name":"getTerminationMessage","signature":"func getTerminationMessage(status *runtimeapi.ContainerStatus, terminationMessagePath string, fallbackToLogs bool) (string, bool)","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// getTerminationMessage looks on the filesystem for the provided termination message path, returning a limited\n// amount of those bytes, or returns true if the logs should be checked.\nfunc getTerminationMessage(status *runtimeapi.ContainerStatus, terminationMessagePath string, fallbackToLogs bool) (string, bool) {\n\tif len(terminationMessagePath) == 0 {\n\t\treturn \"\", fallbackToLogs\n\t}\n\t// Volume Mounts fail on Windows if it is not of the form C:/\n\tterminationMessagePath = volumeutil.MakeAbsolutePath(goruntime.GOOS, terminationMessagePath)\n\tfor _, mount := range status.Mounts {\n\t\tif mount.ContainerPath != terminationMessagePath {\n\t\t\tcontinue\n\t\t}\n\t\tpath := mount.HostPath\n\t\tdata, _, err := tail.ReadAtMost(path, kubecontainer.MaxContainerTerminationMessageLength)\n\t\tif err != nil {\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\treturn \"\", fallbackToLogs\n\t\t\t}\n\t\t\treturn fmt.Sprintf(\"Error on reading termination log %s: %v\", path, err), false\n\t\t}\n\t\treturn string(data), (fallbackToLogs \u0026\u0026 len(data) == 0)\n\t}\n\treturn \"\", fallbackToLogs\n}","line":{"from":488,"to":511}} {"id":100006972,"name":"readLastStringFromContainerLogs","signature":"func (m *kubeGenericRuntimeManager) readLastStringFromContainerLogs(path string) string","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// readLastStringFromContainerLogs attempts to read up to the max log length from the end of the CRI log represented\n// by path. It reads up to max log lines.\nfunc (m *kubeGenericRuntimeManager) readLastStringFromContainerLogs(path string) string {\n\tvalue := int64(kubecontainer.MaxContainerTerminationMessageLogLines)\n\tbuf, _ := circbuf.NewBuffer(kubecontainer.MaxContainerTerminationMessageLogLength)\n\tif err := m.ReadLogs(context.Background(), path, \"\", \u0026v1.PodLogOptions{TailLines: \u0026value}, buf, buf); err != nil {\n\t\treturn fmt.Sprintf(\"Error on reading termination message from logs: %v\", err)\n\t}\n\treturn buf.String()\n}","line":{"from":513,"to":522}} {"id":100006973,"name":"convertToKubeContainerStatus","signature":"func (m *kubeGenericRuntimeManager) convertToKubeContainerStatus(status *runtimeapi.ContainerStatus) (cStatus *kubecontainer.Status)","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"func (m *kubeGenericRuntimeManager) convertToKubeContainerStatus(status *runtimeapi.ContainerStatus) (cStatus *kubecontainer.Status) {\n\tcStatus = toKubeContainerStatus(status, m.runtimeName)\n\tif status.State == runtimeapi.ContainerState_CONTAINER_EXITED {\n\t\t// Populate the termination message if needed.\n\t\tannotatedInfo := getContainerInfoFromAnnotations(status.Annotations)\n\t\t// If a container cannot even be started, it certainly does not have logs, so no need to fallbackToLogs.\n\t\tfallbackToLogs := annotatedInfo.TerminationMessagePolicy == v1.TerminationMessageFallbackToLogsOnError \u0026\u0026\n\t\t\tcStatus.ExitCode != 0 \u0026\u0026 cStatus.Reason != \"ContainerCannotRun\"\n\t\ttMessage, checkLogs := getTerminationMessage(status, annotatedInfo.TerminationMessagePath, fallbackToLogs)\n\t\tif checkLogs {\n\t\t\ttMessage = m.readLastStringFromContainerLogs(status.GetLogPath())\n\t\t}\n\t\t// Enrich the termination message written by the application is not empty\n\t\tif len(tMessage) != 0 {\n\t\t\tif len(cStatus.Message) != 0 {\n\t\t\t\tcStatus.Message += \": \"\n\t\t\t}\n\t\t\tcStatus.Message += tMessage\n\t\t}\n\t}\n\treturn cStatus\n}","line":{"from":524,"to":545}} {"id":100006974,"name":"getPodContainerStatuses","signature":"func (m *kubeGenericRuntimeManager) getPodContainerStatuses(ctx context.Context, uid kubetypes.UID, name, namespace string) ([]*kubecontainer.Status, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// getPodContainerStatuses gets all containers' statuses for the pod.\nfunc (m *kubeGenericRuntimeManager) getPodContainerStatuses(ctx context.Context, uid kubetypes.UID, name, namespace string) ([]*kubecontainer.Status, error) {\n\t// Select all containers of the given pod.\n\tcontainers, err := m.runtimeService.ListContainers(ctx, \u0026runtimeapi.ContainerFilter{\n\t\tLabelSelector: map[string]string{types.KubernetesPodUIDLabel: string(uid)},\n\t})\n\tif err != nil {\n\t\tklog.ErrorS(err, \"ListContainers error\")\n\t\treturn nil, err\n\t}\n\n\tstatuses := []*kubecontainer.Status{}\n\t// TODO: optimization: set maximum number of containers per container name to examine.\n\tfor _, c := range containers {\n\t\tresp, err := m.runtimeService.ContainerStatus(ctx, c.Id, false)\n\t\t// Between List (ListContainers) and check (ContainerStatus) another thread might remove a container, and that is normal.\n\t\t// The previous call (ListContainers) never fails due to a pod container not existing.\n\t\t// Therefore, this method should not either, but instead act as if the previous call failed,\n\t\t// which means the error should be ignored.\n\t\tif crierror.IsNotFound(err) {\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\t// Merely log this here; GetPodStatus will actually report the error out.\n\t\t\tklog.V(4).InfoS(\"ContainerStatus return error\", \"containerID\", c.Id, \"err\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tstatus := resp.GetStatus()\n\t\tif status == nil {\n\t\t\treturn nil, remote.ErrContainerStatusNil\n\t\t}\n\t\tcStatus := m.convertToKubeContainerStatus(status)\n\t\tstatuses = append(statuses, cStatus)\n\t}\n\n\tsort.Sort(containerStatusByCreated(statuses))\n\treturn statuses, nil\n}","line":{"from":547,"to":584}} {"id":100006975,"name":"toKubeContainerStatus","signature":"func toKubeContainerStatus(status *runtimeapi.ContainerStatus, runtimeName string) *kubecontainer.Status","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"func toKubeContainerStatus(status *runtimeapi.ContainerStatus, runtimeName string) *kubecontainer.Status {\n\tannotatedInfo := getContainerInfoFromAnnotations(status.Annotations)\n\tlabeledInfo := getContainerInfoFromLabels(status.Labels)\n\tvar cStatusResources *kubecontainer.ContainerResources\n\tif utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) {\n\t\t// If runtime reports cpu \u0026 memory resources info, add it to container status\n\t\tcStatusResources = toKubeContainerResources(status.Resources)\n\t}\n\tcStatus := \u0026kubecontainer.Status{\n\t\tID: kubecontainer.ContainerID{\n\t\t\tType: runtimeName,\n\t\t\tID: status.Id,\n\t\t},\n\t\tName: labeledInfo.ContainerName,\n\t\tImage: status.Image.Image,\n\t\tImageID: status.ImageRef,\n\t\tHash: annotatedInfo.Hash,\n\t\tHashWithoutResources: annotatedInfo.HashWithoutResources,\n\t\tRestartCount: annotatedInfo.RestartCount,\n\t\tState: toKubeContainerState(status.State),\n\t\tCreatedAt: time.Unix(0, status.CreatedAt),\n\t\tResources: cStatusResources,\n\t}\n\n\tif status.State != runtimeapi.ContainerState_CONTAINER_CREATED {\n\t\t// If container is not in the created state, we have tried and\n\t\t// started the container. Set the StartedAt time.\n\t\tcStatus.StartedAt = time.Unix(0, status.StartedAt)\n\t}\n\tif status.State == runtimeapi.ContainerState_CONTAINER_EXITED {\n\t\tcStatus.Reason = status.Reason\n\t\tcStatus.Message = status.Message\n\t\tcStatus.ExitCode = int(status.ExitCode)\n\t\tcStatus.FinishedAt = time.Unix(0, status.FinishedAt)\n\t}\n\treturn cStatus\n}","line":{"from":586,"to":622}} {"id":100006976,"name":"executePreStopHook","signature":"func (m *kubeGenericRuntimeManager) executePreStopHook(ctx context.Context, pod *v1.Pod, containerID kubecontainer.ContainerID, containerSpec *v1.Container, gracePeriod int64) int64","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// executePreStopHook runs the pre-stop lifecycle hooks if applicable and returns the duration it takes.\nfunc (m *kubeGenericRuntimeManager) executePreStopHook(ctx context.Context, pod *v1.Pod, containerID kubecontainer.ContainerID, containerSpec *v1.Container, gracePeriod int64) int64 {\n\tklog.V(3).InfoS(\"Running preStop hook\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID, \"containerName\", containerSpec.Name, \"containerID\", containerID.String())\n\n\tstart := metav1.Now()\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tdefer close(done)\n\t\tdefer utilruntime.HandleCrash()\n\t\tif _, err := m.runner.Run(ctx, containerID, pod, containerSpec, containerSpec.Lifecycle.PreStop); err != nil {\n\t\t\tklog.ErrorS(err, \"PreStop hook failed\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID,\n\t\t\t\t\"containerName\", containerSpec.Name, \"containerID\", containerID.String())\n\t\t\t// do not record the message in the event so that secrets won't leak from the server.\n\t\t\tm.recordContainerEvent(pod, containerSpec, containerID.ID, v1.EventTypeWarning, events.FailedPreStopHook, \"PreStopHook failed\")\n\t\t}\n\t}()\n\n\tselect {\n\tcase \u003c-time.After(time.Duration(gracePeriod) * time.Second):\n\t\tklog.V(2).InfoS(\"PreStop hook not completed in grace period\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID,\n\t\t\t\"containerName\", containerSpec.Name, \"containerID\", containerID.String(), \"gracePeriod\", gracePeriod)\n\tcase \u003c-done:\n\t\tklog.V(3).InfoS(\"PreStop hook completed\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID,\n\t\t\t\"containerName\", containerSpec.Name, \"containerID\", containerID.String())\n\t}\n\n\treturn int64(metav1.Now().Sub(start.Time).Seconds())\n}","line":{"from":624,"to":651}} {"id":100006977,"name":"restoreSpecsFromContainerLabels","signature":"func (m *kubeGenericRuntimeManager) restoreSpecsFromContainerLabels(ctx context.Context, containerID kubecontainer.ContainerID) (*v1.Pod, *v1.Container, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// restoreSpecsFromContainerLabels restores all information needed for killing a container. In some\n// case we may not have pod and container spec when killing a container, e.g. pod is deleted during\n// kubelet restart.\n// To solve this problem, we've already written necessary information into container labels. Here we\n// just need to retrieve them from container labels and restore the specs.\n// TODO(random-liu): Add a node e2e test to test this behaviour.\n// TODO(random-liu): Change the lifecycle handler to just accept information needed, so that we can\n// just pass the needed function not create the fake object.\nfunc (m *kubeGenericRuntimeManager) restoreSpecsFromContainerLabels(ctx context.Context, containerID kubecontainer.ContainerID) (*v1.Pod, *v1.Container, error) {\n\tvar pod *v1.Pod\n\tvar container *v1.Container\n\tresp, err := m.runtimeService.ContainerStatus(ctx, containerID.ID, false)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\ts := resp.GetStatus()\n\tif s == nil {\n\t\treturn nil, nil, remote.ErrContainerStatusNil\n\t}\n\n\tl := getContainerInfoFromLabels(s.Labels)\n\ta := getContainerInfoFromAnnotations(s.Annotations)\n\t// Notice that the followings are not full spec. The container killing code should not use\n\t// un-restored fields.\n\tpod = \u0026v1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tUID: l.PodUID,\n\t\t\tName: l.PodName,\n\t\t\tNamespace: l.PodNamespace,\n\t\t\tDeletionGracePeriodSeconds: a.PodDeletionGracePeriod,\n\t\t},\n\t\tSpec: v1.PodSpec{\n\t\t\tTerminationGracePeriodSeconds: a.PodTerminationGracePeriod,\n\t\t},\n\t}\n\tcontainer = \u0026v1.Container{\n\t\tName: l.ContainerName,\n\t\tPorts: a.ContainerPorts,\n\t\tTerminationMessagePath: a.TerminationMessagePath,\n\t}\n\tif a.PreStopHandler != nil {\n\t\tcontainer.Lifecycle = \u0026v1.Lifecycle{\n\t\t\tPreStop: a.PreStopHandler,\n\t\t}\n\t}\n\treturn pod, container, nil\n}","line":{"from":653,"to":699}} {"id":100006978,"name":"killContainer","signature":"func (m *kubeGenericRuntimeManager) killContainer(ctx context.Context, pod *v1.Pod, containerID kubecontainer.ContainerID, containerName string, message string, reason containerKillReason, gracePeriodOverride *int64) error","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// killContainer kills a container through the following steps:\n// * Run the pre-stop lifecycle hooks (if applicable).\n// * Stop the container.\nfunc (m *kubeGenericRuntimeManager) killContainer(ctx context.Context, pod *v1.Pod, containerID kubecontainer.ContainerID, containerName string, message string, reason containerKillReason, gracePeriodOverride *int64) error {\n\tvar containerSpec *v1.Container\n\tif pod != nil {\n\t\tif containerSpec = kubecontainer.GetContainerSpec(pod, containerName); containerSpec == nil {\n\t\t\treturn fmt.Errorf(\"failed to get containerSpec %q (id=%q) in pod %q when killing container for reason %q\",\n\t\t\t\tcontainerName, containerID.String(), format.Pod(pod), message)\n\t\t}\n\t} else {\n\t\t// Restore necessary information if one of the specs is nil.\n\t\trestoredPod, restoredContainer, err := m.restoreSpecsFromContainerLabels(ctx, containerID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpod, containerSpec = restoredPod, restoredContainer\n\t}\n\n\t// From this point, pod and container must be non-nil.\n\tgracePeriod := setTerminationGracePeriod(pod, containerSpec, containerName, containerID, reason)\n\n\tif len(message) == 0 {\n\t\tmessage = fmt.Sprintf(\"Stopping container %s\", containerSpec.Name)\n\t}\n\tm.recordContainerEvent(pod, containerSpec, containerID.ID, v1.EventTypeNormal, events.KillingContainer, message)\n\n\t// Run the pre-stop lifecycle hooks if applicable and if there is enough time to run it\n\tif containerSpec.Lifecycle != nil \u0026\u0026 containerSpec.Lifecycle.PreStop != nil \u0026\u0026 gracePeriod \u003e 0 {\n\t\tgracePeriod = gracePeriod - m.executePreStopHook(ctx, pod, containerID, containerSpec, gracePeriod)\n\t}\n\t// always give containers a minimal shutdown window to avoid unnecessary SIGKILLs\n\tif gracePeriod \u003c minimumGracePeriodInSeconds {\n\t\tgracePeriod = minimumGracePeriodInSeconds\n\t}\n\tif gracePeriodOverride != nil {\n\t\tgracePeriod = *gracePeriodOverride\n\t\tklog.V(3).InfoS(\"Killing container with a grace period override\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID,\n\t\t\t\"containerName\", containerName, \"containerID\", containerID.String(), \"gracePeriod\", gracePeriod)\n\t}\n\n\tklog.V(2).InfoS(\"Killing container with a grace period\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID,\n\t\t\"containerName\", containerName, \"containerID\", containerID.String(), \"gracePeriod\", gracePeriod)\n\n\terr := m.runtimeService.StopContainer(ctx, containerID.ID, gracePeriod)\n\tif err != nil \u0026\u0026 !crierror.IsNotFound(err) {\n\t\tklog.ErrorS(err, \"Container termination failed with gracePeriod\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID,\n\t\t\t\"containerName\", containerName, \"containerID\", containerID.String(), \"gracePeriod\", gracePeriod)\n\t\treturn err\n\t}\n\tklog.V(3).InfoS(\"Container exited normally\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID,\n\t\t\"containerName\", containerName, \"containerID\", containerID.String())\n\n\treturn nil\n}","line":{"from":701,"to":755}} {"id":100006979,"name":"killContainersWithSyncResult","signature":"func (m *kubeGenericRuntimeManager) killContainersWithSyncResult(ctx context.Context, pod *v1.Pod, runningPod kubecontainer.Pod, gracePeriodOverride *int64) (syncResults []*kubecontainer.SyncResult)","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// killContainersWithSyncResult kills all pod's containers with sync results.\nfunc (m *kubeGenericRuntimeManager) killContainersWithSyncResult(ctx context.Context, pod *v1.Pod, runningPod kubecontainer.Pod, gracePeriodOverride *int64) (syncResults []*kubecontainer.SyncResult) {\n\tcontainerResults := make(chan *kubecontainer.SyncResult, len(runningPod.Containers))\n\twg := sync.WaitGroup{}\n\n\twg.Add(len(runningPod.Containers))\n\tfor _, container := range runningPod.Containers {\n\t\tgo func(container *kubecontainer.Container) {\n\t\t\tdefer utilruntime.HandleCrash()\n\t\t\tdefer wg.Done()\n\n\t\t\tkillContainerResult := kubecontainer.NewSyncResult(kubecontainer.KillContainer, container.Name)\n\t\t\tif err := m.killContainer(ctx, pod, container.ID, container.Name, \"\", reasonUnknown, gracePeriodOverride); err != nil {\n\t\t\t\tkillContainerResult.Fail(kubecontainer.ErrKillContainer, err.Error())\n\t\t\t\t// Use runningPod for logging as the pod passed in could be *nil*.\n\t\t\t\tklog.ErrorS(err, \"Kill container failed\", \"pod\", klog.KRef(runningPod.Namespace, runningPod.Name), \"podUID\", runningPod.ID,\n\t\t\t\t\t\"containerName\", container.Name, \"containerID\", container.ID)\n\t\t\t}\n\t\t\tcontainerResults \u003c- killContainerResult\n\t\t}(container)\n\t}\n\twg.Wait()\n\tclose(containerResults)\n\n\tfor containerResult := range containerResults {\n\t\tsyncResults = append(syncResults, containerResult)\n\t}\n\treturn\n}","line":{"from":757,"to":785}} {"id":100006980,"name":"pruneInitContainersBeforeStart","signature":"func (m *kubeGenericRuntimeManager) pruneInitContainersBeforeStart(ctx context.Context, pod *v1.Pod, podStatus *kubecontainer.PodStatus)","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// pruneInitContainersBeforeStart ensures that before we begin creating init\n// containers, we have reduced the number of outstanding init containers still\n// present. This reduces load on the container garbage collector by only\n// preserving the most recent terminated init container.\nfunc (m *kubeGenericRuntimeManager) pruneInitContainersBeforeStart(ctx context.Context, pod *v1.Pod, podStatus *kubecontainer.PodStatus) {\n\t// only the last execution of each init container should be preserved, and only preserve it if it is in the\n\t// list of init containers to keep.\n\tinitContainerNames := sets.NewString()\n\tfor _, container := range pod.Spec.InitContainers {\n\t\tinitContainerNames.Insert(container.Name)\n\t}\n\tfor name := range initContainerNames {\n\t\tcount := 0\n\t\tfor _, status := range podStatus.ContainerStatuses {\n\t\t\tif status.Name != name ||\n\t\t\t\t(status.State != kubecontainer.ContainerStateExited \u0026\u0026\n\t\t\t\t\tstatus.State != kubecontainer.ContainerStateUnknown) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Remove init containers in unknown state. It should have\n\t\t\t// been stopped before pruneInitContainersBeforeStart is\n\t\t\t// called.\n\t\t\tcount++\n\t\t\t// keep the first init container for this name\n\t\t\tif count == 1 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// prune all other init containers that match this container name\n\t\t\tklog.V(4).InfoS(\"Removing init container\", \"containerName\", status.Name, \"containerID\", status.ID.ID, \"count\", count)\n\t\t\tif err := m.removeContainer(ctx, status.ID.ID); err != nil {\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"failed to remove pod init container %q: %v; Skipping pod %q\", status.Name, err, format.Pod(pod)))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":787,"to":822}} {"id":100006981,"name":"purgeInitContainers","signature":"func (m *kubeGenericRuntimeManager) purgeInitContainers(ctx context.Context, pod *v1.Pod, podStatus *kubecontainer.PodStatus)","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// Remove all init containers. Note that this function does not check the state\n// of the container because it assumes all init containers have been stopped\n// before the call happens.\nfunc (m *kubeGenericRuntimeManager) purgeInitContainers(ctx context.Context, pod *v1.Pod, podStatus *kubecontainer.PodStatus) {\n\tinitContainerNames := sets.NewString()\n\tfor _, container := range pod.Spec.InitContainers {\n\t\tinitContainerNames.Insert(container.Name)\n\t}\n\tfor name := range initContainerNames {\n\t\tcount := 0\n\t\tfor _, status := range podStatus.ContainerStatuses {\n\t\t\tif status.Name != name {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcount++\n\t\t\t// Purge all init containers that match this container name\n\t\t\tklog.V(4).InfoS(\"Removing init container\", \"containerName\", status.Name, \"containerID\", status.ID.ID, \"count\", count)\n\t\t\tif err := m.removeContainer(ctx, status.ID.ID); err != nil {\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"failed to remove pod init container %q: %v; Skipping pod %q\", status.Name, err, format.Pod(pod)))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":824,"to":847}} {"id":100006982,"name":"findNextInitContainerToRun","signature":"func findNextInitContainerToRun(pod *v1.Pod, podStatus *kubecontainer.PodStatus) (status *kubecontainer.Status, next *v1.Container, done bool)","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// findNextInitContainerToRun returns the status of the last failed container, the\n// index of next init container to start, or done if there are no further init containers.\n// Status is only returned if an init container is failed, in which case next will\n// point to the current container.\nfunc findNextInitContainerToRun(pod *v1.Pod, podStatus *kubecontainer.PodStatus) (status *kubecontainer.Status, next *v1.Container, done bool) {\n\tif len(pod.Spec.InitContainers) == 0 {\n\t\treturn nil, nil, true\n\t}\n\n\t// If any of the main containers have status and are Running, then all init containers must\n\t// have been executed at some point in the past. However, they could have been removed\n\t// from the container runtime now, and if we proceed, it would appear as if they\n\t// never ran and will re-execute improperly.\n\tfor i := range pod.Spec.Containers {\n\t\tcontainer := \u0026pod.Spec.Containers[i]\n\t\tstatus := podStatus.FindContainerStatusByName(container.Name)\n\t\tif status != nil \u0026\u0026 status.State == kubecontainer.ContainerStateRunning {\n\t\t\treturn nil, nil, true\n\t\t}\n\t}\n\n\t// If there are failed containers, return the status of the last failed one.\n\tfor i := len(pod.Spec.InitContainers) - 1; i \u003e= 0; i-- {\n\t\tcontainer := \u0026pod.Spec.InitContainers[i]\n\t\tstatus := podStatus.FindContainerStatusByName(container.Name)\n\t\tif status != nil \u0026\u0026 isInitContainerFailed(status) {\n\t\t\treturn status, container, false\n\t\t}\n\t}\n\n\t// There are no failed containers now.\n\tfor i := len(pod.Spec.InitContainers) - 1; i \u003e= 0; i-- {\n\t\tcontainer := \u0026pod.Spec.InitContainers[i]\n\t\tstatus := podStatus.FindContainerStatusByName(container.Name)\n\t\tif status == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// container is still running, return not done.\n\t\tif status.State == kubecontainer.ContainerStateRunning {\n\t\t\treturn nil, nil, false\n\t\t}\n\n\t\tif status.State == kubecontainer.ContainerStateExited {\n\t\t\t// all init containers successful\n\t\t\tif i == (len(pod.Spec.InitContainers) - 1) {\n\t\t\t\treturn nil, nil, true\n\t\t\t}\n\n\t\t\t// all containers up to i successful, go to i+1\n\t\t\treturn nil, \u0026pod.Spec.InitContainers[i+1], false\n\t\t}\n\t}\n\n\treturn nil, \u0026pod.Spec.InitContainers[0], false\n}","line":{"from":849,"to":904}} {"id":100006983,"name":"GetContainerLogs","signature":"func (m *kubeGenericRuntimeManager) GetContainerLogs(ctx context.Context, pod *v1.Pod, containerID kubecontainer.ContainerID, logOptions *v1.PodLogOptions, stdout, stderr io.Writer) (err error)","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// GetContainerLogs returns logs of a specific container.\nfunc (m *kubeGenericRuntimeManager) GetContainerLogs(ctx context.Context, pod *v1.Pod, containerID kubecontainer.ContainerID, logOptions *v1.PodLogOptions, stdout, stderr io.Writer) (err error) {\n\tresp, err := m.runtimeService.ContainerStatus(ctx, containerID.ID, false)\n\tif err != nil {\n\t\tklog.V(4).InfoS(\"Failed to get container status\", \"containerID\", containerID.String(), \"err\", err)\n\t\treturn fmt.Errorf(\"unable to retrieve container logs for %v\", containerID.String())\n\t}\n\tstatus := resp.GetStatus()\n\tif status == nil {\n\t\treturn remote.ErrContainerStatusNil\n\t}\n\treturn m.ReadLogs(ctx, status.GetLogPath(), containerID.ID, logOptions, stdout, stderr)\n}","line":{"from":906,"to":918}} {"id":100006984,"name":"GetExec","signature":"func (m *kubeGenericRuntimeManager) GetExec(ctx context.Context, id kubecontainer.ContainerID, cmd []string, stdin, stdout, stderr, tty bool) (*url.URL, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// GetExec gets the endpoint the runtime will serve the exec request from.\nfunc (m *kubeGenericRuntimeManager) GetExec(ctx context.Context, id kubecontainer.ContainerID, cmd []string, stdin, stdout, stderr, tty bool) (*url.URL, error) {\n\treq := \u0026runtimeapi.ExecRequest{\n\t\tContainerId: id.ID,\n\t\tCmd: cmd,\n\t\tTty: tty,\n\t\tStdin: stdin,\n\t\tStdout: stdout,\n\t\tStderr: stderr,\n\t}\n\tresp, err := m.runtimeService.Exec(ctx, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn url.Parse(resp.Url)\n}","line":{"from":920,"to":936}} {"id":100006985,"name":"GetAttach","signature":"func (m *kubeGenericRuntimeManager) GetAttach(ctx context.Context, id kubecontainer.ContainerID, stdin, stdout, stderr, tty bool) (*url.URL, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// GetAttach gets the endpoint the runtime will serve the attach request from.\nfunc (m *kubeGenericRuntimeManager) GetAttach(ctx context.Context, id kubecontainer.ContainerID, stdin, stdout, stderr, tty bool) (*url.URL, error) {\n\treq := \u0026runtimeapi.AttachRequest{\n\t\tContainerId: id.ID,\n\t\tStdin: stdin,\n\t\tStdout: stdout,\n\t\tStderr: stderr,\n\t\tTty: tty,\n\t}\n\tresp, err := m.runtimeService.Attach(ctx, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn url.Parse(resp.Url)\n}","line":{"from":938,"to":952}} {"id":100006986,"name":"RunInContainer","signature":"func (m *kubeGenericRuntimeManager) RunInContainer(ctx context.Context, id kubecontainer.ContainerID, cmd []string, timeout time.Duration) ([]byte, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// RunInContainer synchronously executes the command in the container, and returns the output.\nfunc (m *kubeGenericRuntimeManager) RunInContainer(ctx context.Context, id kubecontainer.ContainerID, cmd []string, timeout time.Duration) ([]byte, error) {\n\tstdout, stderr, err := m.runtimeService.ExecSync(ctx, id.ID, cmd, timeout)\n\t// NOTE(tallclair): This does not correctly interleave stdout \u0026 stderr, but should be sufficient\n\t// for logging purposes. A combined output option will need to be added to the ExecSyncRequest\n\t// if more precise output ordering is ever required.\n\treturn append(stdout, stderr...), err\n}","line":{"from":954,"to":961}} {"id":100006987,"name":"removeContainer","signature":"func (m *kubeGenericRuntimeManager) removeContainer(ctx context.Context, containerID string) error","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// removeContainer removes the container and the container logs.\n// Notice that we remove the container logs first, so that container will not be removed if\n// container logs are failed to be removed, and kubelet will retry this later. This guarantees\n// that container logs to be removed with the container.\n// Notice that we assume that the container should only be removed in non-running state, and\n// it will not write container logs anymore in that state.\nfunc (m *kubeGenericRuntimeManager) removeContainer(ctx context.Context, containerID string) error {\n\tklog.V(4).InfoS(\"Removing container\", \"containerID\", containerID)\n\t// Call internal container post-stop lifecycle hook.\n\tif err := m.internalLifecycle.PostStopContainer(containerID); err != nil {\n\t\treturn err\n\t}\n\n\t// Remove the container log.\n\t// TODO: Separate log and container lifecycle management.\n\tif err := m.removeContainerLog(ctx, containerID); err != nil {\n\t\treturn err\n\t}\n\t// Remove the container.\n\treturn m.runtimeService.RemoveContainer(ctx, containerID)\n}","line":{"from":963,"to":983}} {"id":100006988,"name":"removeContainerLog","signature":"func (m *kubeGenericRuntimeManager) removeContainerLog(ctx context.Context, containerID string) error","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// removeContainerLog removes the container log.\nfunc (m *kubeGenericRuntimeManager) removeContainerLog(ctx context.Context, containerID string) error {\n\t// Use log manager to remove rotated logs.\n\terr := m.logManager.Clean(ctx, containerID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresp, err := m.runtimeService.ContainerStatus(ctx, containerID, false)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get container status %q: %v\", containerID, err)\n\t}\n\tstatus := resp.GetStatus()\n\tif status == nil {\n\t\treturn remote.ErrContainerStatusNil\n\t}\n\t// Remove the legacy container log symlink.\n\t// TODO(random-liu): Remove this after cluster logging supports CRI container log path.\n\tlabeledInfo := getContainerInfoFromLabels(status.Labels)\n\tlegacySymlink := legacyLogSymlink(containerID, labeledInfo.ContainerName, labeledInfo.PodName,\n\t\tlabeledInfo.PodNamespace)\n\tif err := m.osInterface.Remove(legacySymlink); err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"failed to remove container %q log legacy symbolic link %q: %v\",\n\t\t\tcontainerID, legacySymlink, err)\n\t}\n\treturn nil\n}","line":{"from":985,"to":1011}} {"id":100006989,"name":"DeleteContainer","signature":"func (m *kubeGenericRuntimeManager) DeleteContainer(ctx context.Context, containerID kubecontainer.ContainerID) error","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// DeleteContainer removes a container.\nfunc (m *kubeGenericRuntimeManager) DeleteContainer(ctx context.Context, containerID kubecontainer.ContainerID) error {\n\treturn m.removeContainer(ctx, containerID.ID)\n}","line":{"from":1013,"to":1016}} {"id":100006990,"name":"setTerminationGracePeriod","signature":"func setTerminationGracePeriod(pod *v1.Pod, containerSpec *v1.Container, containerName string, containerID kubecontainer.ContainerID, reason containerKillReason) int64","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"// setTerminationGracePeriod determines the grace period to use when killing a container\nfunc setTerminationGracePeriod(pod *v1.Pod, containerSpec *v1.Container, containerName string, containerID kubecontainer.ContainerID, reason containerKillReason) int64 {\n\tgracePeriod := int64(minimumGracePeriodInSeconds)\n\tswitch {\n\tcase pod.DeletionGracePeriodSeconds != nil:\n\t\treturn *pod.DeletionGracePeriodSeconds\n\tcase pod.Spec.TerminationGracePeriodSeconds != nil:\n\t\tswitch reason {\n\t\tcase reasonStartupProbe:\n\t\t\tif isProbeTerminationGracePeriodSecondsSet(pod, containerSpec, containerSpec.StartupProbe, containerName, containerID, \"StartupProbe\") {\n\t\t\t\treturn *containerSpec.StartupProbe.TerminationGracePeriodSeconds\n\t\t\t}\n\t\tcase reasonLivenessProbe:\n\t\t\tif isProbeTerminationGracePeriodSecondsSet(pod, containerSpec, containerSpec.LivenessProbe, containerName, containerID, \"LivenessProbe\") {\n\t\t\t\treturn *containerSpec.LivenessProbe.TerminationGracePeriodSeconds\n\t\t\t}\n\t\t}\n\t\treturn *pod.Spec.TerminationGracePeriodSeconds\n\t}\n\treturn gracePeriod\n}","line":{"from":1018,"to":1038}} {"id":100006991,"name":"isProbeTerminationGracePeriodSecondsSet","signature":"func isProbeTerminationGracePeriodSecondsSet(pod *v1.Pod, containerSpec *v1.Container, probe *v1.Probe, containerName string, containerID kubecontainer.ContainerID, probeType string) bool","file":"pkg/kubelet/kuberuntime/kuberuntime_container.go","code":"func isProbeTerminationGracePeriodSecondsSet(pod *v1.Pod, containerSpec *v1.Container, probe *v1.Probe, containerName string, containerID kubecontainer.ContainerID, probeType string) bool {\n\tif probe != nil \u0026\u0026 probe.TerminationGracePeriodSeconds != nil {\n\t\tif *probe.TerminationGracePeriodSeconds \u003e *pod.Spec.TerminationGracePeriodSeconds {\n\t\t\tklog.V(4).InfoS(\"Using probe-level grace period that is greater than the pod-level grace period\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID, \"containerName\", containerName, \"containerID\", containerID.String(), \"probeType\", probeType, \"probeGracePeriod\", *probe.TerminationGracePeriodSeconds, \"podGracePeriod\", *pod.Spec.TerminationGracePeriodSeconds)\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":1040,"to":1048}} {"id":100006992,"name":"applyPlatformSpecificContainerConfig","signature":"func (m *kubeGenericRuntimeManager) applyPlatformSpecificContainerConfig(config *runtimeapi.ContainerConfig, container *v1.Container, pod *v1.Pod, uid *int64, username string, nsTarget *kubecontainer.ContainerID) error","file":"pkg/kubelet/kuberuntime/kuberuntime_container_linux.go","code":"// applyPlatformSpecificContainerConfig applies platform specific configurations to runtimeapi.ContainerConfig.\nfunc (m *kubeGenericRuntimeManager) applyPlatformSpecificContainerConfig(config *runtimeapi.ContainerConfig, container *v1.Container, pod *v1.Pod, uid *int64, username string, nsTarget *kubecontainer.ContainerID) error {\n\tenforceMemoryQoS := false\n\t// Set memory.min and memory.high if MemoryQoS enabled with cgroups v2\n\tif utilfeature.DefaultFeatureGate.Enabled(kubefeatures.MemoryQoS) \u0026\u0026\n\t\tlibcontainercgroups.IsCgroup2UnifiedMode() {\n\t\tenforceMemoryQoS = true\n\t}\n\tcl, err := m.generateLinuxContainerConfig(container, pod, uid, username, nsTarget, enforceMemoryQoS)\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfig.Linux = cl\n\n\tif utilfeature.DefaultFeatureGate.Enabled(kubefeatures.UserNamespacesStatelessPodsSupport) {\n\t\tif cl.SecurityContext.NamespaceOptions.UsernsOptions != nil {\n\t\t\tfor _, mount := range config.Mounts {\n\t\t\t\tmount.UidMappings = cl.SecurityContext.NamespaceOptions.UsernsOptions.Uids\n\t\t\t\tmount.GidMappings = cl.SecurityContext.NamespaceOptions.UsernsOptions.Gids\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":44,"to":67}} {"id":100006993,"name":"generateLinuxContainerConfig","signature":"func (m *kubeGenericRuntimeManager) generateLinuxContainerConfig(container *v1.Container, pod *v1.Pod, uid *int64, username string, nsTarget *kubecontainer.ContainerID, enforceMemoryQoS bool) (*runtimeapi.LinuxContainerConfig, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_container_linux.go","code":"// generateLinuxContainerConfig generates linux container config for kubelet runtime v1.\nfunc (m *kubeGenericRuntimeManager) generateLinuxContainerConfig(container *v1.Container, pod *v1.Pod, uid *int64, username string, nsTarget *kubecontainer.ContainerID, enforceMemoryQoS bool) (*runtimeapi.LinuxContainerConfig, error) {\n\tsc, err := m.determineEffectiveSecurityContext(pod, container, uid, username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlc := \u0026runtimeapi.LinuxContainerConfig{\n\t\tResources: m.generateLinuxContainerResources(pod, container, enforceMemoryQoS),\n\t\tSecurityContext: sc,\n\t}\n\n\tif nsTarget != nil \u0026\u0026 lc.SecurityContext.NamespaceOptions.Pid == runtimeapi.NamespaceMode_CONTAINER {\n\t\tlc.SecurityContext.NamespaceOptions.Pid = runtimeapi.NamespaceMode_TARGET\n\t\tlc.SecurityContext.NamespaceOptions.TargetId = nsTarget.ID\n\t}\n\n\treturn lc, nil\n}","line":{"from":69,"to":86}} {"id":100006994,"name":"generateLinuxContainerResources","signature":"func (m *kubeGenericRuntimeManager) generateLinuxContainerResources(pod *v1.Pod, container *v1.Container, enforceMemoryQoS bool) *runtimeapi.LinuxContainerResources","file":"pkg/kubelet/kuberuntime/kuberuntime_container_linux.go","code":"// generateLinuxContainerResources generates linux container resources config for runtime\nfunc (m *kubeGenericRuntimeManager) generateLinuxContainerResources(pod *v1.Pod, container *v1.Container, enforceMemoryQoS bool) *runtimeapi.LinuxContainerResources {\n\t// set linux container resources\n\tvar cpuRequest *resource.Quantity\n\tif _, cpuRequestExists := container.Resources.Requests[v1.ResourceCPU]; cpuRequestExists {\n\t\tcpuRequest = container.Resources.Requests.Cpu()\n\t}\n\tlcr := m.calculateLinuxResources(cpuRequest, container.Resources.Limits.Cpu(), container.Resources.Limits.Memory())\n\n\tlcr.OomScoreAdj = int64(qos.GetContainerOOMScoreAdjust(pod, container,\n\t\tint64(m.machineInfo.MemoryCapacity)))\n\n\tlcr.HugepageLimits = GetHugepageLimitsFromResources(container.Resources)\n\n\tif utilfeature.DefaultFeatureGate.Enabled(kubefeatures.NodeSwap) {\n\t\t// NOTE(ehashman): Behaviour is defined in the opencontainers runtime spec:\n\t\t// https://github.com/opencontainers/runtime-spec/blob/1c3f411f041711bbeecf35ff7e93461ea6789220/config-linux.md#memory\n\t\tswitch m.memorySwapBehavior {\n\t\tcase kubelettypes.UnlimitedSwap:\n\t\t\t// -1 = unlimited swap\n\t\t\tlcr.MemorySwapLimitInBytes = -1\n\t\tcase kubelettypes.LimitedSwap:\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\t// memorySwapLimit = total permitted memory+swap; if equal to memory limit, =\u003e 0 swap above memory limit\n\t\t\t// Some swapping is still possible.\n\t\t\t// Note that if memory limit is 0, memory swap limit is ignored.\n\t\t\tlcr.MemorySwapLimitInBytes = lcr.MemoryLimitInBytes\n\t\t}\n\t}\n\n\t// Set memory.min and memory.high to enforce MemoryQoS\n\tif enforceMemoryQoS {\n\t\tunified := map[string]string{}\n\t\tmemoryRequest := container.Resources.Requests.Memory().Value()\n\t\tmemoryLimit := container.Resources.Limits.Memory().Value()\n\t\tif memoryRequest != 0 {\n\t\t\tunified[cm.MemoryMin] = strconv.FormatInt(memoryRequest, 10)\n\t\t}\n\n\t\t// Guaranteed pods by their QoS definition requires that memory request equals memory limit and cpu request must equal cpu limit.\n\t\t// Here, we only check from memory perspective. Hence MemoryQoS feature is disabled on those QoS pods by not setting memory.high.\n\t\tif memoryRequest != memoryLimit {\n\t\t\t// The formula for memory.high for container cgroup is modified in Alpha stage of the feature in K8s v1.27.\n\t\t\t// It will be set based on formula:\n\t\t\t// `memory.high=floor[(requests.memory + memory throttling factor * (limits.memory or node allocatable memory - requests.memory))/pageSize] * pageSize`\n\t\t\t// where default value of memory throttling factor is set to 0.9\n\t\t\t// More info: https://git.k8s.io/enhancements/keps/sig-node/2570-memory-qos\n\t\t\tmemoryHigh := int64(0)\n\t\t\tif memoryLimit != 0 {\n\t\t\t\tmemoryHigh = int64(math.Floor(\n\t\t\t\t\tfloat64(memoryRequest)+\n\t\t\t\t\t\t(float64(memoryLimit)-float64(memoryRequest))*float64(m.memoryThrottlingFactor))/float64(defaultPageSize)) * defaultPageSize\n\t\t\t} else {\n\t\t\t\tallocatable := m.getNodeAllocatable()\n\t\t\t\tallocatableMemory, ok := allocatable[v1.ResourceMemory]\n\t\t\t\tif ok \u0026\u0026 allocatableMemory.Value() \u003e 0 {\n\t\t\t\t\tmemoryHigh = int64(math.Floor(\n\t\t\t\t\t\tfloat64(memoryRequest)+\n\t\t\t\t\t\t\t(float64(allocatableMemory.Value())-float64(memoryRequest))*float64(m.memoryThrottlingFactor))/float64(defaultPageSize)) * defaultPageSize\n\t\t\t\t}\n\t\t\t}\n\t\t\tif memoryHigh != 0 \u0026\u0026 memoryHigh \u003e memoryRequest {\n\t\t\t\tunified[cm.MemoryHigh] = strconv.FormatInt(memoryHigh, 10)\n\t\t\t}\n\t\t}\n\t\tif len(unified) \u003e 0 {\n\t\t\tif lcr.Unified == nil {\n\t\t\t\tlcr.Unified = unified\n\t\t\t} else {\n\t\t\t\tfor k, v := range unified {\n\t\t\t\t\tlcr.Unified[k] = v\n\t\t\t\t}\n\t\t\t}\n\t\t\tklog.V(4).InfoS(\"MemoryQoS config for container\", \"pod\", klog.KObj(pod), \"containerName\", container.Name, \"unified\", unified)\n\t\t}\n\t}\n\n\treturn lcr\n}","line":{"from":88,"to":167}} {"id":100006995,"name":"generateContainerResources","signature":"func (m *kubeGenericRuntimeManager) generateContainerResources(pod *v1.Pod, container *v1.Container) *runtimeapi.ContainerResources","file":"pkg/kubelet/kuberuntime/kuberuntime_container_linux.go","code":"// generateContainerResources generates platform specific (linux) container resources config for runtime\nfunc (m *kubeGenericRuntimeManager) generateContainerResources(pod *v1.Pod, container *v1.Container) *runtimeapi.ContainerResources {\n\tenforceMemoryQoS := false\n\t// Set memory.min and memory.high if MemoryQoS enabled with cgroups v2\n\tif utilfeature.DefaultFeatureGate.Enabled(kubefeatures.MemoryQoS) \u0026\u0026\n\t\tlibcontainercgroups.IsCgroup2UnifiedMode() {\n\t\tenforceMemoryQoS = true\n\t}\n\treturn \u0026runtimeapi.ContainerResources{\n\t\tLinux: m.generateLinuxContainerResources(pod, container, enforceMemoryQoS),\n\t}\n}","line":{"from":169,"to":180}} {"id":100006996,"name":"calculateLinuxResources","signature":"func (m *kubeGenericRuntimeManager) calculateLinuxResources(cpuRequest, cpuLimit, memoryLimit *resource.Quantity) *runtimeapi.LinuxContainerResources","file":"pkg/kubelet/kuberuntime/kuberuntime_container_linux.go","code":"// calculateLinuxResources will create the linuxContainerResources type based on the provided CPU and memory resource requests, limits\nfunc (m *kubeGenericRuntimeManager) calculateLinuxResources(cpuRequest, cpuLimit, memoryLimit *resource.Quantity) *runtimeapi.LinuxContainerResources {\n\tresources := runtimeapi.LinuxContainerResources{}\n\tvar cpuShares int64\n\n\tmemLimit := memoryLimit.Value()\n\n\t// If request is not specified, but limit is, we want request to default to limit.\n\t// API server does this for new containers, but we repeat this logic in Kubelet\n\t// for containers running on existing Kubernetes clusters.\n\tif cpuRequest == nil \u0026\u0026 cpuLimit != nil {\n\t\tcpuShares = int64(cm.MilliCPUToShares(cpuLimit.MilliValue()))\n\t} else {\n\t\t// if cpuRequest.Amount is nil, then MilliCPUToShares will return the minimal number\n\t\t// of CPU shares.\n\t\tcpuShares = int64(cm.MilliCPUToShares(cpuRequest.MilliValue()))\n\t}\n\tresources.CpuShares = cpuShares\n\tif memLimit != 0 {\n\t\tresources.MemoryLimitInBytes = memLimit\n\t}\n\n\tif m.cpuCFSQuota {\n\t\t// if cpuLimit.Amount is nil, then the appropriate default value is returned\n\t\t// to allow full usage of cpu resource.\n\t\tcpuPeriod := int64(quotaPeriod)\n\t\tif utilfeature.DefaultFeatureGate.Enabled(kubefeatures.CPUCFSQuotaPeriod) {\n\t\t\t// kubeGenericRuntimeManager.cpuCFSQuotaPeriod is provided in time.Duration,\n\t\t\t// but we need to convert it to number of microseconds which is used by kernel.\n\t\t\tcpuPeriod = int64(m.cpuCFSQuotaPeriod.Duration / time.Microsecond)\n\t\t}\n\t\tcpuQuota := milliCPUToQuota(cpuLimit.MilliValue(), cpuPeriod)\n\t\tresources.CpuQuota = cpuQuota\n\t\tresources.CpuPeriod = cpuPeriod\n\t}\n\n\treturn \u0026resources\n}","line":{"from":182,"to":219}} {"id":100006997,"name":"GetHugepageLimitsFromResources","signature":"func GetHugepageLimitsFromResources(resources v1.ResourceRequirements) []*runtimeapi.HugepageLimit","file":"pkg/kubelet/kuberuntime/kuberuntime_container_linux.go","code":"// GetHugepageLimitsFromResources returns limits of each hugepages from resources.\nfunc GetHugepageLimitsFromResources(resources v1.ResourceRequirements) []*runtimeapi.HugepageLimit {\n\tvar hugepageLimits []*runtimeapi.HugepageLimit\n\n\t// For each page size, limit to 0.\n\tfor _, pageSize := range libcontainercgroups.HugePageSizes() {\n\t\thugepageLimits = append(hugepageLimits, \u0026runtimeapi.HugepageLimit{\n\t\t\tPageSize: pageSize,\n\t\t\tLimit: uint64(0),\n\t\t})\n\t}\n\n\trequiredHugepageLimits := map[string]uint64{}\n\tfor resourceObj, amountObj := range resources.Limits {\n\t\tif !v1helper.IsHugePageResourceName(resourceObj) {\n\t\t\tcontinue\n\t\t}\n\n\t\tpageSize, err := v1helper.HugePageSizeFromResourceName(resourceObj)\n\t\tif err != nil {\n\t\t\tklog.InfoS(\"Failed to get hugepage size from resource\", \"object\", resourceObj, \"err\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tsizeString, err := v1helper.HugePageUnitSizeFromByteSize(pageSize.Value())\n\t\tif err != nil {\n\t\t\tklog.InfoS(\"Size is invalid\", \"object\", resourceObj, \"err\", err)\n\t\t\tcontinue\n\t\t}\n\t\trequiredHugepageLimits[sizeString] = uint64(amountObj.Value())\n\t}\n\n\tfor _, hugepageLimit := range hugepageLimits {\n\t\tif limit, exists := requiredHugepageLimits[hugepageLimit.PageSize]; exists {\n\t\t\thugepageLimit.Limit = limit\n\t\t}\n\t}\n\n\treturn hugepageLimits\n}","line":{"from":221,"to":260}} {"id":100006998,"name":"toKubeContainerResources","signature":"func toKubeContainerResources(statusResources *runtimeapi.ContainerResources) *kubecontainer.ContainerResources","file":"pkg/kubelet/kuberuntime/kuberuntime_container_linux.go","code":"func toKubeContainerResources(statusResources *runtimeapi.ContainerResources) *kubecontainer.ContainerResources {\n\tvar cStatusResources *kubecontainer.ContainerResources\n\truntimeStatusResources := statusResources.GetLinux()\n\tif runtimeStatusResources != nil {\n\t\tvar cpuLimit, memLimit, cpuRequest *resource.Quantity\n\t\tif runtimeStatusResources.CpuPeriod \u003e 0 {\n\t\t\tmilliCPU := quotaToMilliCPU(runtimeStatusResources.CpuQuota, runtimeStatusResources.CpuPeriod)\n\t\t\tif milliCPU \u003e 0 {\n\t\t\t\tcpuLimit = resource.NewMilliQuantity(milliCPU, resource.DecimalSI)\n\t\t\t}\n\t\t}\n\t\tif runtimeStatusResources.CpuShares \u003e 0 {\n\t\t\tmilliCPU := sharesToMilliCPU(runtimeStatusResources.CpuShares)\n\t\t\tif milliCPU \u003e 0 {\n\t\t\t\tcpuRequest = resource.NewMilliQuantity(milliCPU, resource.DecimalSI)\n\t\t\t}\n\t\t}\n\t\tif runtimeStatusResources.MemoryLimitInBytes \u003e 0 {\n\t\t\tmemLimit = resource.NewQuantity(runtimeStatusResources.MemoryLimitInBytes, resource.BinarySI)\n\t\t}\n\t\tif cpuLimit != nil || memLimit != nil || cpuRequest != nil {\n\t\t\tcStatusResources = \u0026kubecontainer.ContainerResources{\n\t\t\t\tCPULimit: cpuLimit,\n\t\t\t\tCPURequest: cpuRequest,\n\t\t\t\tMemoryLimit: memLimit,\n\t\t\t}\n\t\t}\n\t}\n\treturn cStatusResources\n}","line":{"from":262,"to":291}} {"id":100006999,"name":"applyPlatformSpecificContainerConfig","signature":"func (m *kubeGenericRuntimeManager) applyPlatformSpecificContainerConfig(config *runtimeapi.ContainerConfig, container *v1.Container, pod *v1.Pod, uid *int64, username string, nsTarget *kubecontainer.ContainerID) error","file":"pkg/kubelet/kuberuntime/kuberuntime_container_unsupported.go","code":"// applyPlatformSpecificContainerConfig applies platform specific configurations to runtimeapi.ContainerConfig.\nfunc (m *kubeGenericRuntimeManager) applyPlatformSpecificContainerConfig(config *runtimeapi.ContainerConfig, container *v1.Container, pod *v1.Pod, uid *int64, username string, nsTarget *kubecontainer.ContainerID) error {\n\treturn nil\n}","line":{"from":28,"to":31}} {"id":100007000,"name":"generateContainerResources","signature":"func (m *kubeGenericRuntimeManager) generateContainerResources(pod *v1.Pod, container *v1.Container) *runtimeapi.ContainerResources","file":"pkg/kubelet/kuberuntime/kuberuntime_container_unsupported.go","code":"// generateContainerResources generates platform specific container resources config for runtime\nfunc (m *kubeGenericRuntimeManager) generateContainerResources(pod *v1.Pod, container *v1.Container) *runtimeapi.ContainerResources {\n\treturn nil\n}","line":{"from":33,"to":36}} {"id":100007001,"name":"toKubeContainerResources","signature":"func toKubeContainerResources(statusResources *runtimeapi.ContainerResources) *kubecontainer.ContainerResources","file":"pkg/kubelet/kuberuntime/kuberuntime_container_unsupported.go","code":"func toKubeContainerResources(statusResources *runtimeapi.ContainerResources) *kubecontainer.ContainerResources {\n\treturn nil\n}","line":{"from":38,"to":40}} {"id":100007002,"name":"applyPlatformSpecificContainerConfig","signature":"func (m *kubeGenericRuntimeManager) applyPlatformSpecificContainerConfig(config *runtimeapi.ContainerConfig, container *v1.Container, pod *v1.Pod, uid *int64, username string, _ *kubecontainer.ContainerID) error","file":"pkg/kubelet/kuberuntime/kuberuntime_container_windows.go","code":"// applyPlatformSpecificContainerConfig applies platform specific configurations to runtimeapi.ContainerConfig.\nfunc (m *kubeGenericRuntimeManager) applyPlatformSpecificContainerConfig(config *runtimeapi.ContainerConfig, container *v1.Container, pod *v1.Pod, uid *int64, username string, _ *kubecontainer.ContainerID) error {\n\twindowsConfig, err := m.generateWindowsContainerConfig(container, pod, uid, username)\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfig.Windows = windowsConfig\n\n\treturn nil\n}","line":{"from":32,"to":41}} {"id":100007003,"name":"generateContainerResources","signature":"func (m *kubeGenericRuntimeManager) generateContainerResources(pod *v1.Pod, container *v1.Container) *runtimeapi.ContainerResources","file":"pkg/kubelet/kuberuntime/kuberuntime_container_windows.go","code":"// generateContainerResources generates platform specific (windows) container resources config for runtime\nfunc (m *kubeGenericRuntimeManager) generateContainerResources(pod *v1.Pod, container *v1.Container) *runtimeapi.ContainerResources {\n\t//TODO: Add windows support\n\treturn nil\n}","line":{"from":43,"to":47}} {"id":100007004,"name":"generateWindowsContainerConfig","signature":"func (m *kubeGenericRuntimeManager) generateWindowsContainerConfig(container *v1.Container, pod *v1.Pod, uid *int64, username string) (*runtimeapi.WindowsContainerConfig, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_container_windows.go","code":"// generateWindowsContainerConfig generates windows container config for kubelet runtime v1.\n// Refer https://git.k8s.io/design-proposals-archive/node/cri-windows.md.\nfunc (m *kubeGenericRuntimeManager) generateWindowsContainerConfig(container *v1.Container, pod *v1.Pod, uid *int64, username string) (*runtimeapi.WindowsContainerConfig, error) {\n\twc := \u0026runtimeapi.WindowsContainerConfig{\n\t\tResources: \u0026runtimeapi.WindowsContainerResources{},\n\t\tSecurityContext: \u0026runtimeapi.WindowsContainerSecurityContext{},\n\t}\n\n\tcpuLimit := container.Resources.Limits.Cpu()\n\tif !cpuLimit.IsZero() {\n\t\t// Since Kubernetes doesn't have any notion of weight in the Pod/Container API, only limits/reserves, then applying CpuMaximum only\n\t\t// will better follow the intent of the user. At one point CpuWeights were set, but this prevented limits from having any effect.\n\n\t\t// There are 3 parts to how this works:\n\t\t// Part one - Windows kernel\n\t\t// cpuMaximum is documented at https://docs.microsoft.com/en-us/virtualization/windowscontainers/manage-containers/resource-controls\n\t\t// the range and how it relates to number of CPUs is at https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-jobobject_cpu_rate_control_information\n\t\t// For process isolation, these are applied to the job object setting JOB_OBJECT_CPU_RATE_CONTROL_ENABLE, which can be set to either\n\t\t// JOB_OBJECT_CPU_RATE_CONTROL_WEIGHT_BASED or JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP. This is why the settings are mutually exclusive.\n\t\t// Part two - Docker (doc: https://docs.docker.com/engine/api/v1.30)\n\t\t// If both CpuWeight and CpuMaximum are passed to Docker, then it sets\n\t\t// JOB_OBJECT_CPU_RATE_CONTROL_ENABLE = JOB_OBJECT_CPU_RATE_CONTROL_WEIGHT_BASED ignoring CpuMaximum.\n\t\t// Option a: Set HostConfig.CpuPercent. The units are whole percent of the total CPU capacity of the system, meaning the resolution\n\t\t// is different based on the number of cores.\n\t\t// Option b: Set HostConfig.NanoCpus integer \u003cint64\u003e - CPU quota in units of 10e-9 CPUs. Moby scales this to the Windows job object\n\t\t// resolution of 1-10000, so it's higher resolution than option a.\n\t\t// src: https://github.com/moby/moby/blob/10866714412aea1bb587d1ad14b2ce1ba4cf4308/daemon/oci_windows.go#L426\n\t\t// Part three - CRI \u0026 ContainerD's implementation\n\t\t// The kubelet sets these directly on CGroups in Linux, but needs to pass them across CRI on Windows.\n\t\t// There is an existing cpu_maximum field, with a range of percent * 100, so 1-10000. This is different from Docker, but consistent with OCI\n\t\t// https://github.com/kubernetes/kubernetes/blob/56d1c3b96d0a544130a82caad33dd57629b8a7f8/staging/src/k8s.io/cri-api/pkg/apis/runtime/v1/api.proto#L681-L682\n\t\t// https://github.com/opencontainers/runtime-spec/blob/ad53dcdc39f1f7f7472b10aa0a45648fe4865496/config-windows.md#cpu\n\t\t// If both CpuWeight and CpuMaximum are set - ContainerD catches this invalid case and returns an error instead.\n\t\twc.Resources.CpuMaximum = calculateCPUMaximum(cpuLimit, int64(winstats.ProcessorCount()))\n\t}\n\n\t// The processor resource controls are mutually exclusive on\n\t// Windows Server Containers, the order of precedence is\n\t// CPUCount first, then CPUMaximum.\n\tif wc.Resources.CpuCount \u003e 0 {\n\t\tif wc.Resources.CpuMaximum \u003e 0 {\n\t\t\twc.Resources.CpuMaximum = 0\n\t\t\tklog.InfoS(\"Mutually exclusive options: CPUCount priority \u003e CPUMaximum priority on Windows Server Containers. CPUMaximum should be ignored\")\n\t\t}\n\t}\n\n\tmemoryLimit := container.Resources.Limits.Memory().Value()\n\tif memoryLimit != 0 {\n\t\twc.Resources.MemoryLimitInBytes = memoryLimit\n\t}\n\n\t// setup security context\n\teffectiveSc := securitycontext.DetermineEffectiveSecurityContext(pod, container)\n\n\tif username != \"\" {\n\t\twc.SecurityContext.RunAsUsername = username\n\t}\n\tif effectiveSc.WindowsOptions != nil \u0026\u0026\n\t\teffectiveSc.WindowsOptions.GMSACredentialSpec != nil {\n\t\twc.SecurityContext.CredentialSpec = *effectiveSc.WindowsOptions.GMSACredentialSpec\n\t}\n\n\t// override with Windows options if present\n\tif effectiveSc.WindowsOptions != nil \u0026\u0026 effectiveSc.WindowsOptions.RunAsUserName != nil {\n\t\twc.SecurityContext.RunAsUsername = *effectiveSc.WindowsOptions.RunAsUserName\n\t}\n\n\tif securitycontext.HasWindowsHostProcessRequest(pod, container) {\n\t\twc.SecurityContext.HostProcess = true\n\t}\n\n\treturn wc, nil\n}","line":{"from":49,"to":121}} {"id":100007005,"name":"calculateCPUMaximum","signature":"func calculateCPUMaximum(cpuLimit *resource.Quantity, cpuCount int64) int64","file":"pkg/kubelet/kuberuntime/kuberuntime_container_windows.go","code":"// calculateCPUMaximum calculates the maximum CPU given a limit and a number of cpus while ensuring it's in range [1,10000].\nfunc calculateCPUMaximum(cpuLimit *resource.Quantity, cpuCount int64) int64 {\n\tcpuMaximum := 10 * cpuLimit.MilliValue() / cpuCount\n\n\t// ensure cpuMaximum is in range [1, 10000].\n\tif cpuMaximum \u003c 1 {\n\t\tcpuMaximum = 1\n\t} else if cpuMaximum \u003e 10000 {\n\t\tcpuMaximum = 10000\n\t}\n\treturn cpuMaximum\n}","line":{"from":123,"to":134}} {"id":100007006,"name":"toKubeContainerResources","signature":"func toKubeContainerResources(statusResources *runtimeapi.ContainerResources) *kubecontainer.ContainerResources","file":"pkg/kubelet/kuberuntime/kuberuntime_container_windows.go","code":"func toKubeContainerResources(statusResources *runtimeapi.ContainerResources) *kubecontainer.ContainerResources {\n\t//TODO: Add windows support\n\treturn nil\n}","line":{"from":136,"to":139}} {"id":100007007,"name":"newContainerGC","signature":"func newContainerGC(client internalapi.RuntimeService, podStateProvider podStateProvider, manager *kubeGenericRuntimeManager, tracer trace.Tracer) *containerGC","file":"pkg/kubelet/kuberuntime/kuberuntime_gc.go","code":"// NewContainerGC creates a new containerGC.\nfunc newContainerGC(client internalapi.RuntimeService, podStateProvider podStateProvider, manager *kubeGenericRuntimeManager, tracer trace.Tracer) *containerGC {\n\treturn \u0026containerGC{\n\t\tclient: client,\n\t\tmanager: manager,\n\t\tpodStateProvider: podStateProvider,\n\t\ttracer: tracer,\n\t}\n}","line":{"from":45,"to":53}} {"id":100007008,"name":"NumContainers","signature":"func (cu containersByEvictUnit) NumContainers() int","file":"pkg/kubelet/kuberuntime/kuberuntime_gc.go","code":"// NumContainers returns the number of containers in this map.\nfunc (cu containersByEvictUnit) NumContainers() int {\n\tnum := 0\n\tfor key := range cu {\n\t\tnum += len(cu[key])\n\t}\n\treturn num\n}","line":{"from":89,"to":96}} {"id":100007009,"name":"NumEvictUnits","signature":"func (cu containersByEvictUnit) NumEvictUnits() int","file":"pkg/kubelet/kuberuntime/kuberuntime_gc.go","code":"// NumEvictUnits returns the number of pod in this map.\nfunc (cu containersByEvictUnit) NumEvictUnits() int {\n\treturn len(cu)\n}","line":{"from":98,"to":101}} {"id":100007010,"name":"Len","signature":"func (a byCreated) Len() int { return len(a) }","file":"pkg/kubelet/kuberuntime/kuberuntime_gc.go","code":"func (a byCreated) Len() int { return len(a) }","line":{"from":106,"to":106}} {"id":100007011,"name":"Swap","signature":"func (a byCreated) Swap(i, j int) { a[i], a[j] = a[j], a[i] }","file":"pkg/kubelet/kuberuntime/kuberuntime_gc.go","code":"func (a byCreated) Swap(i, j int) { a[i], a[j] = a[j], a[i] }","line":{"from":107,"to":107}} {"id":100007012,"name":"Less","signature":"func (a byCreated) Less(i, j int) bool { return a[i].createTime.After(a[j].createTime) }","file":"pkg/kubelet/kuberuntime/kuberuntime_gc.go","code":"func (a byCreated) Less(i, j int) bool { return a[i].createTime.After(a[j].createTime) }","line":{"from":108,"to":108}} {"id":100007013,"name":"Len","signature":"func (a sandboxByCreated) Len() int { return len(a) }","file":"pkg/kubelet/kuberuntime/kuberuntime_gc.go","code":"func (a sandboxByCreated) Len() int { return len(a) }","line":{"from":113,"to":113}} {"id":100007014,"name":"Swap","signature":"func (a sandboxByCreated) Swap(i, j int) { a[i], a[j] = a[j], a[i] }","file":"pkg/kubelet/kuberuntime/kuberuntime_gc.go","code":"func (a sandboxByCreated) Swap(i, j int) { a[i], a[j] = a[j], a[i] }","line":{"from":114,"to":114}} {"id":100007015,"name":"Less","signature":"func (a sandboxByCreated) Less(i, j int) bool { return a[i].createTime.After(a[j].createTime) }","file":"pkg/kubelet/kuberuntime/kuberuntime_gc.go","code":"func (a sandboxByCreated) Less(i, j int) bool { return a[i].createTime.After(a[j].createTime) }","line":{"from":115,"to":115}} {"id":100007016,"name":"enforceMaxContainersPerEvictUnit","signature":"func (cgc *containerGC) enforceMaxContainersPerEvictUnit(ctx context.Context, evictUnits containersByEvictUnit, MaxContainers int)","file":"pkg/kubelet/kuberuntime/kuberuntime_gc.go","code":"// enforceMaxContainersPerEvictUnit enforces MaxPerPodContainer for each evictUnit.\nfunc (cgc *containerGC) enforceMaxContainersPerEvictUnit(ctx context.Context, evictUnits containersByEvictUnit, MaxContainers int) {\n\tfor key := range evictUnits {\n\t\ttoRemove := len(evictUnits[key]) - MaxContainers\n\n\t\tif toRemove \u003e 0 {\n\t\t\tevictUnits[key] = cgc.removeOldestN(ctx, evictUnits[key], toRemove)\n\t\t}\n\t}\n}","line":{"from":117,"to":126}} {"id":100007017,"name":"removeOldestN","signature":"func (cgc *containerGC) removeOldestN(ctx context.Context, containers []containerGCInfo, toRemove int) []containerGCInfo","file":"pkg/kubelet/kuberuntime/kuberuntime_gc.go","code":"// removeOldestN removes the oldest toRemove containers and returns the resulting slice.\nfunc (cgc *containerGC) removeOldestN(ctx context.Context, containers []containerGCInfo, toRemove int) []containerGCInfo {\n\t// Remove from oldest to newest (last to first).\n\tnumToKeep := len(containers) - toRemove\n\tif numToKeep \u003e 0 {\n\t\tsort.Sort(byCreated(containers))\n\t}\n\tfor i := len(containers) - 1; i \u003e= numToKeep; i-- {\n\t\tif containers[i].unknown {\n\t\t\t// Containers in known state could be running, we should try\n\t\t\t// to stop it before removal.\n\t\t\tid := kubecontainer.ContainerID{\n\t\t\t\tType: cgc.manager.runtimeName,\n\t\t\t\tID: containers[i].id,\n\t\t\t}\n\t\t\tmessage := \"Container is in unknown state, try killing it before removal\"\n\t\t\tif err := cgc.manager.killContainer(ctx, nil, id, containers[i].name, message, reasonUnknown, nil); err != nil {\n\t\t\t\tklog.ErrorS(err, \"Failed to stop container\", \"containerID\", containers[i].id)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif err := cgc.manager.removeContainer(ctx, containers[i].id); err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to remove container\", \"containerID\", containers[i].id)\n\t\t}\n\t}\n\n\t// Assume we removed the containers so that we're not too aggressive.\n\treturn containers[:numToKeep]\n}","line":{"from":128,"to":156}} {"id":100007018,"name":"removeOldestNSandboxes","signature":"func (cgc *containerGC) removeOldestNSandboxes(ctx context.Context, sandboxes []sandboxGCInfo, toRemove int)","file":"pkg/kubelet/kuberuntime/kuberuntime_gc.go","code":"// removeOldestNSandboxes removes the oldest inactive toRemove sandboxes and\n// returns the resulting slice.\nfunc (cgc *containerGC) removeOldestNSandboxes(ctx context.Context, sandboxes []sandboxGCInfo, toRemove int) {\n\tnumToKeep := len(sandboxes) - toRemove\n\tif numToKeep \u003e 0 {\n\t\tsort.Sort(sandboxByCreated(sandboxes))\n\t}\n\t// Remove from oldest to newest (last to first).\n\tfor i := len(sandboxes) - 1; i \u003e= numToKeep; i-- {\n\t\tif !sandboxes[i].active {\n\t\t\tcgc.removeSandbox(ctx, sandboxes[i].id)\n\t\t}\n\t}\n}","line":{"from":158,"to":171}} {"id":100007019,"name":"removeSandbox","signature":"func (cgc *containerGC) removeSandbox(ctx context.Context, sandboxID string)","file":"pkg/kubelet/kuberuntime/kuberuntime_gc.go","code":"// removeSandbox removes the sandbox by sandboxID.\nfunc (cgc *containerGC) removeSandbox(ctx context.Context, sandboxID string) {\n\tklog.V(4).InfoS(\"Removing sandbox\", \"sandboxID\", sandboxID)\n\t// In normal cases, kubelet should've already called StopPodSandbox before\n\t// GC kicks in. To guard against the rare cases where this is not true, try\n\t// stopping the sandbox before removing it.\n\tif err := cgc.client.StopPodSandbox(ctx, sandboxID); err != nil {\n\t\tklog.ErrorS(err, \"Failed to stop sandbox before removing\", \"sandboxID\", sandboxID)\n\t\treturn\n\t}\n\tif err := cgc.client.RemovePodSandbox(ctx, sandboxID); err != nil {\n\t\tklog.ErrorS(err, \"Failed to remove sandbox\", \"sandboxID\", sandboxID)\n\t}\n}","line":{"from":173,"to":186}} {"id":100007020,"name":"evictableContainers","signature":"func (cgc *containerGC) evictableContainers(ctx context.Context, minAge time.Duration) (containersByEvictUnit, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_gc.go","code":"// evictableContainers gets all containers that are evictable. Evictable containers are: not running\n// and created more than MinAge ago.\nfunc (cgc *containerGC) evictableContainers(ctx context.Context, minAge time.Duration) (containersByEvictUnit, error) {\n\tcontainers, err := cgc.manager.getKubeletContainers(ctx, true)\n\tif err != nil {\n\t\treturn containersByEvictUnit{}, err\n\t}\n\n\tevictUnits := make(containersByEvictUnit)\n\tnewestGCTime := time.Now().Add(-minAge)\n\tfor _, container := range containers {\n\t\t// Prune out running containers.\n\t\tif container.State == runtimeapi.ContainerState_CONTAINER_RUNNING {\n\t\t\tcontinue\n\t\t}\n\n\t\tcreatedAt := time.Unix(0, container.CreatedAt)\n\t\tif newestGCTime.Before(createdAt) {\n\t\t\tcontinue\n\t\t}\n\n\t\tlabeledInfo := getContainerInfoFromLabels(container.Labels)\n\t\tcontainerInfo := containerGCInfo{\n\t\t\tid: container.Id,\n\t\t\tname: container.Metadata.Name,\n\t\t\tcreateTime: createdAt,\n\t\t\tunknown: container.State == runtimeapi.ContainerState_CONTAINER_UNKNOWN,\n\t\t}\n\t\tkey := evictUnit{\n\t\t\tuid: labeledInfo.PodUID,\n\t\t\tname: containerInfo.name,\n\t\t}\n\t\tevictUnits[key] = append(evictUnits[key], containerInfo)\n\t}\n\n\treturn evictUnits, nil\n}","line":{"from":188,"to":224}} {"id":100007021,"name":"evictContainers","signature":"func (cgc *containerGC) evictContainers(ctx context.Context, gcPolicy kubecontainer.GCPolicy, allSourcesReady bool, evictNonDeletedPods bool) error","file":"pkg/kubelet/kuberuntime/kuberuntime_gc.go","code":"// evict all containers that are evictable\nfunc (cgc *containerGC) evictContainers(ctx context.Context, gcPolicy kubecontainer.GCPolicy, allSourcesReady bool, evictNonDeletedPods bool) error {\n\t// Separate containers by evict units.\n\tevictUnits, err := cgc.evictableContainers(ctx, gcPolicy.MinAge)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Remove deleted pod containers if all sources are ready.\n\tif allSourcesReady {\n\t\tfor key, unit := range evictUnits {\n\t\t\tif cgc.podStateProvider.ShouldPodContentBeRemoved(key.uid) || (evictNonDeletedPods \u0026\u0026 cgc.podStateProvider.ShouldPodRuntimeBeRemoved(key.uid)) {\n\t\t\t\tcgc.removeOldestN(ctx, unit, len(unit)) // Remove all.\n\t\t\t\tdelete(evictUnits, key)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Enforce max containers per evict unit.\n\tif gcPolicy.MaxPerPodContainer \u003e= 0 {\n\t\tcgc.enforceMaxContainersPerEvictUnit(ctx, evictUnits, gcPolicy.MaxPerPodContainer)\n\t}\n\n\t// Enforce max total number of containers.\n\tif gcPolicy.MaxContainers \u003e= 0 \u0026\u0026 evictUnits.NumContainers() \u003e gcPolicy.MaxContainers {\n\t\t// Leave an equal number of containers per evict unit (min: 1).\n\t\tnumContainersPerEvictUnit := gcPolicy.MaxContainers / evictUnits.NumEvictUnits()\n\t\tif numContainersPerEvictUnit \u003c 1 {\n\t\t\tnumContainersPerEvictUnit = 1\n\t\t}\n\t\tcgc.enforceMaxContainersPerEvictUnit(ctx, evictUnits, numContainersPerEvictUnit)\n\n\t\t// If we still need to evict, evict oldest first.\n\t\tnumContainers := evictUnits.NumContainers()\n\t\tif numContainers \u003e gcPolicy.MaxContainers {\n\t\t\tflattened := make([]containerGCInfo, 0, numContainers)\n\t\t\tfor key := range evictUnits {\n\t\t\t\tflattened = append(flattened, evictUnits[key]...)\n\t\t\t}\n\t\t\tsort.Sort(byCreated(flattened))\n\n\t\t\tcgc.removeOldestN(ctx, flattened, numContainers-gcPolicy.MaxContainers)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":226,"to":271}} {"id":100007022,"name":"evictSandboxes","signature":"func (cgc *containerGC) evictSandboxes(ctx context.Context, evictNonDeletedPods bool) error","file":"pkg/kubelet/kuberuntime/kuberuntime_gc.go","code":"// evictSandboxes remove all evictable sandboxes. An evictable sandbox must\n// meet the following requirements:\n// 1. not in ready state\n// 2. contains no containers.\n// 3. belong to a non-existent (i.e., already removed) pod, or is not the\n// most recently created sandbox for the pod.\nfunc (cgc *containerGC) evictSandboxes(ctx context.Context, evictNonDeletedPods bool) error {\n\tcontainers, err := cgc.manager.getKubeletContainers(ctx, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsandboxes, err := cgc.manager.getKubeletSandboxes(ctx, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// collect all the PodSandboxId of container\n\tsandboxIDs := sets.NewString()\n\tfor _, container := range containers {\n\t\tsandboxIDs.Insert(container.PodSandboxId)\n\t}\n\n\tsandboxesByPod := make(sandboxesByPodUID)\n\tfor _, sandbox := range sandboxes {\n\t\tpodUID := types.UID(sandbox.Metadata.Uid)\n\t\tsandboxInfo := sandboxGCInfo{\n\t\t\tid: sandbox.Id,\n\t\t\tcreateTime: time.Unix(0, sandbox.CreatedAt),\n\t\t}\n\n\t\t// Set ready sandboxes to be active.\n\t\tif sandbox.State == runtimeapi.PodSandboxState_SANDBOX_READY {\n\t\t\tsandboxInfo.active = true\n\t\t}\n\n\t\t// Set sandboxes that still have containers to be active.\n\t\tif sandboxIDs.Has(sandbox.Id) {\n\t\t\tsandboxInfo.active = true\n\t\t}\n\n\t\tsandboxesByPod[podUID] = append(sandboxesByPod[podUID], sandboxInfo)\n\t}\n\n\tfor podUID, sandboxes := range sandboxesByPod {\n\t\tif cgc.podStateProvider.ShouldPodContentBeRemoved(podUID) || (evictNonDeletedPods \u0026\u0026 cgc.podStateProvider.ShouldPodRuntimeBeRemoved(podUID)) {\n\t\t\t// Remove all evictable sandboxes if the pod has been removed.\n\t\t\t// Note that the latest dead sandbox is also removed if there is\n\t\t\t// already an active one.\n\t\t\tcgc.removeOldestNSandboxes(ctx, sandboxes, len(sandboxes))\n\t\t} else {\n\t\t\t// Keep latest one if the pod still exists.\n\t\t\tcgc.removeOldestNSandboxes(ctx, sandboxes, len(sandboxes)-1)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":273,"to":329}} {"id":100007023,"name":"evictPodLogsDirectories","signature":"func (cgc *containerGC) evictPodLogsDirectories(ctx context.Context, allSourcesReady bool) error","file":"pkg/kubelet/kuberuntime/kuberuntime_gc.go","code":"// evictPodLogsDirectories evicts all evictable pod logs directories. Pod logs directories\n// are evictable if there are no corresponding pods.\nfunc (cgc *containerGC) evictPodLogsDirectories(ctx context.Context, allSourcesReady bool) error {\n\tosInterface := cgc.manager.osInterface\n\tif allSourcesReady {\n\t\t// Only remove pod logs directories when all sources are ready.\n\t\tdirs, err := osInterface.ReadDir(podLogsRootDirectory)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to read podLogsRootDirectory %q: %v\", podLogsRootDirectory, err)\n\t\t}\n\t\tfor _, dir := range dirs {\n\t\t\tname := dir.Name()\n\t\t\tpodUID := parsePodUIDFromLogsDirectory(name)\n\t\t\tif !cgc.podStateProvider.ShouldPodContentBeRemoved(podUID) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tklog.V(4).InfoS(\"Removing pod logs\", \"podUID\", podUID)\n\t\t\terr := osInterface.RemoveAll(filepath.Join(podLogsRootDirectory, name))\n\t\t\tif err != nil {\n\t\t\t\tklog.ErrorS(err, \"Failed to remove pod logs directory\", \"path\", name)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Remove dead container log symlinks.\n\t// TODO(random-liu): Remove this after cluster logging supports CRI container log path.\n\tlogSymlinks, _ := osInterface.Glob(filepath.Join(legacyContainerLogsDir, fmt.Sprintf(\"*.%s\", legacyLogSuffix)))\n\tfor _, logSymlink := range logSymlinks {\n\t\tif _, err := osInterface.Stat(logSymlink); os.IsNotExist(err) {\n\t\t\tif containerID, err := getContainerIDFromLegacyLogSymlink(logSymlink); err == nil {\n\t\t\t\tresp, err := cgc.manager.runtimeService.ContainerStatus(ctx, containerID, false)\n\t\t\t\tif err != nil {\n\t\t\t\t\t// TODO: we should handle container not found (i.e. container was deleted) case differently\n\t\t\t\t\t// once https://github.com/kubernetes/kubernetes/issues/63336 is resolved\n\t\t\t\t\tklog.InfoS(\"Error getting ContainerStatus for containerID\", \"containerID\", containerID, \"err\", err)\n\t\t\t\t} else {\n\t\t\t\t\tstatus := resp.GetStatus()\n\t\t\t\t\tif status == nil {\n\t\t\t\t\t\tklog.V(4).InfoS(\"Container status is nil\")\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif status.State != runtimeapi.ContainerState_CONTAINER_EXITED {\n\t\t\t\t\t\t// Here is how container log rotation works (see containerLogManager#rotateLatestLog):\n\t\t\t\t\t\t//\n\t\t\t\t\t\t// 1. rename current log to rotated log file whose filename contains current timestamp (fmt.Sprintf(\"%s.%s\", log, timestamp))\n\t\t\t\t\t\t// 2. reopen the container log\n\t\t\t\t\t\t// 3. if #2 fails, rename rotated log file back to container log\n\t\t\t\t\t\t//\n\t\t\t\t\t\t// There is small but indeterministic amount of time during which log file doesn't exist (between steps #1 and #2, between #1 and #3).\n\t\t\t\t\t\t// Hence the symlink may be deemed unhealthy during that period.\n\t\t\t\t\t\t// See https://github.com/kubernetes/kubernetes/issues/52172\n\t\t\t\t\t\t//\n\t\t\t\t\t\t// We only remove unhealthy symlink for dead containers\n\t\t\t\t\t\tklog.V(5).InfoS(\"Container is still running, not removing symlink\", \"containerID\", containerID, \"path\", logSymlink)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tklog.V(4).InfoS(\"Unable to obtain container ID\", \"err\", err)\n\t\t\t}\n\t\t\terr := osInterface.Remove(logSymlink)\n\t\t\tif err != nil {\n\t\t\t\tklog.ErrorS(err, \"Failed to remove container log dead symlink\", \"path\", logSymlink)\n\t\t\t} else {\n\t\t\t\tklog.V(4).InfoS(\"Removed symlink\", \"path\", logSymlink)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":331,"to":400}} {"id":100007024,"name":"GarbageCollect","signature":"func (cgc *containerGC) GarbageCollect(ctx context.Context, gcPolicy kubecontainer.GCPolicy, allSourcesReady bool, evictNonDeletedPods bool) error","file":"pkg/kubelet/kuberuntime/kuberuntime_gc.go","code":"// GarbageCollect removes dead containers using the specified container gc policy.\n// Note that gc policy is not applied to sandboxes. Sandboxes are only removed when they are\n// not ready and containing no containers.\n//\n// GarbageCollect consists of the following steps:\n// * gets evictable containers which are not active and created more than gcPolicy.MinAge ago.\n// * removes oldest dead containers for each pod by enforcing gcPolicy.MaxPerPodContainer.\n// * removes oldest dead containers by enforcing gcPolicy.MaxContainers.\n// * gets evictable sandboxes which are not ready and contains no containers.\n// * removes evictable sandboxes.\nfunc (cgc *containerGC) GarbageCollect(ctx context.Context, gcPolicy kubecontainer.GCPolicy, allSourcesReady bool, evictNonDeletedPods bool) error {\n\tctx, otelSpan := cgc.tracer.Start(ctx, \"Containers/GarbageCollect\")\n\tdefer otelSpan.End()\n\terrors := []error{}\n\t// Remove evictable containers\n\tif err := cgc.evictContainers(ctx, gcPolicy, allSourcesReady, evictNonDeletedPods); err != nil {\n\t\terrors = append(errors, err)\n\t}\n\n\t// Remove sandboxes with zero containers\n\tif err := cgc.evictSandboxes(ctx, evictNonDeletedPods); err != nil {\n\t\terrors = append(errors, err)\n\t}\n\n\t// Remove pod sandbox log directory\n\tif err := cgc.evictPodLogsDirectories(ctx, allSourcesReady); err != nil {\n\t\terrors = append(errors, err)\n\t}\n\treturn utilerrors.NewAggregate(errors)\n}","line":{"from":402,"to":431}} {"id":100007025,"name":"PullImage","signature":"func (m *kubeGenericRuntimeManager) PullImage(ctx context.Context, image kubecontainer.ImageSpec, pullSecrets []v1.Secret, podSandboxConfig *runtimeapi.PodSandboxConfig) (string, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_image.go","code":"// PullImage pulls an image from the network to local storage using the supplied\n// secrets if necessary.\nfunc (m *kubeGenericRuntimeManager) PullImage(ctx context.Context, image kubecontainer.ImageSpec, pullSecrets []v1.Secret, podSandboxConfig *runtimeapi.PodSandboxConfig) (string, error) {\n\timg := image.Image\n\trepoToPull, _, _, err := parsers.ParseImageName(img)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tkeyring, err := credentialprovidersecrets.MakeDockerKeyring(pullSecrets, m.keyring)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\timgSpec := toRuntimeAPIImageSpec(image)\n\n\tcreds, withCredentials := keyring.Lookup(repoToPull)\n\tif !withCredentials {\n\t\tklog.V(3).InfoS(\"Pulling image without credentials\", \"image\", img)\n\n\t\timageRef, err := m.imageService.PullImage(ctx, imgSpec, nil, podSandboxConfig)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to pull image\", \"image\", img)\n\t\t\treturn \"\", err\n\t\t}\n\n\t\treturn imageRef, nil\n\t}\n\n\tvar pullErrs []error\n\tfor _, currentCreds := range creds {\n\t\tauth := \u0026runtimeapi.AuthConfig{\n\t\t\tUsername: currentCreds.Username,\n\t\t\tPassword: currentCreds.Password,\n\t\t\tAuth: currentCreds.Auth,\n\t\t\tServerAddress: currentCreds.ServerAddress,\n\t\t\tIdentityToken: currentCreds.IdentityToken,\n\t\t\tRegistryToken: currentCreds.RegistryToken,\n\t\t}\n\n\t\timageRef, err := m.imageService.PullImage(ctx, imgSpec, auth, podSandboxConfig)\n\t\t// If there was no error, return success\n\t\tif err == nil {\n\t\t\treturn imageRef, nil\n\t\t}\n\n\t\tpullErrs = append(pullErrs, err)\n\t}\n\n\treturn \"\", utilerrors.NewAggregate(pullErrs)\n}","line":{"from":31,"to":81}} {"id":100007026,"name":"GetImageRef","signature":"func (m *kubeGenericRuntimeManager) GetImageRef(ctx context.Context, image kubecontainer.ImageSpec) (string, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_image.go","code":"// GetImageRef gets the ID of the image which has already been in\n// the local storage. It returns (\"\", nil) if the image isn't in the local storage.\nfunc (m *kubeGenericRuntimeManager) GetImageRef(ctx context.Context, image kubecontainer.ImageSpec) (string, error) {\n\tresp, err := m.imageService.ImageStatus(ctx, toRuntimeAPIImageSpec(image), false)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to get image status\", \"image\", image.Image)\n\t\treturn \"\", err\n\t}\n\tif resp.Image == nil {\n\t\treturn \"\", nil\n\t}\n\treturn resp.Image.Id, nil\n}","line":{"from":83,"to":95}} {"id":100007027,"name":"ListImages","signature":"func (m *kubeGenericRuntimeManager) ListImages(ctx context.Context) ([]kubecontainer.Image, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_image.go","code":"// ListImages gets all images currently on the machine.\nfunc (m *kubeGenericRuntimeManager) ListImages(ctx context.Context) ([]kubecontainer.Image, error) {\n\tvar images []kubecontainer.Image\n\n\tallImages, err := m.imageService.ListImages(ctx, nil)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to list images\")\n\t\treturn nil, err\n\t}\n\n\tfor _, img := range allImages {\n\t\timages = append(images, kubecontainer.Image{\n\t\t\tID: img.Id,\n\t\t\tSize: int64(img.Size_),\n\t\t\tRepoTags: img.RepoTags,\n\t\t\tRepoDigests: img.RepoDigests,\n\t\t\tSpec: toKubeContainerImageSpec(img),\n\t\t})\n\t}\n\n\treturn images, nil\n}","line":{"from":97,"to":118}} {"id":100007028,"name":"RemoveImage","signature":"func (m *kubeGenericRuntimeManager) RemoveImage(ctx context.Context, image kubecontainer.ImageSpec) error","file":"pkg/kubelet/kuberuntime/kuberuntime_image.go","code":"// RemoveImage removes the specified image.\nfunc (m *kubeGenericRuntimeManager) RemoveImage(ctx context.Context, image kubecontainer.ImageSpec) error {\n\terr := m.imageService.RemoveImage(ctx, \u0026runtimeapi.ImageSpec{Image: image.Image})\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to remove image\", \"image\", image.Image)\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":120,"to":129}} {"id":100007029,"name":"ImageStats","signature":"func (m *kubeGenericRuntimeManager) ImageStats(ctx context.Context) (*kubecontainer.ImageStats, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_image.go","code":"// ImageStats returns the statistics of the image.\n// Notice that current logic doesn't really work for images which share layers (e.g. docker image),\n// this is a known issue, and we'll address this by getting imagefs stats directly from CRI.\n// TODO: Get imagefs stats directly from CRI.\nfunc (m *kubeGenericRuntimeManager) ImageStats(ctx context.Context) (*kubecontainer.ImageStats, error) {\n\tallImages, err := m.imageService.ListImages(ctx, nil)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to list images\")\n\t\treturn nil, err\n\t}\n\tstats := \u0026kubecontainer.ImageStats{}\n\tfor _, img := range allImages {\n\t\tstats.TotalStorageBytes += img.Size_\n\t}\n\treturn stats, nil\n}","line":{"from":131,"to":146}} {"id":100007030,"name":"ReadLogs","signature":"func (m *kubeGenericRuntimeManager) ReadLogs(ctx context.Context, path, containerID string, apiOpts *v1.PodLogOptions, stdout, stderr io.Writer) error","file":"pkg/kubelet/kuberuntime/kuberuntime_logs.go","code":"// ReadLogs read the container log and redirect into stdout and stderr.\n// Note that containerID is only needed when following the log, or else\n// just pass in empty string \"\".\nfunc (m *kubeGenericRuntimeManager) ReadLogs(ctx context.Context, path, containerID string, apiOpts *v1.PodLogOptions, stdout, stderr io.Writer) error {\n\t// Convert v1.PodLogOptions into internal log options.\n\topts := logs.NewLogOptions(apiOpts, time.Now())\n\n\treturn logs.ReadLogs(ctx, path, containerID, opts, m.runtimeService, stdout, stderr)\n}","line":{"from":28,"to":36}} {"id":100007031,"name":"NewKubeGenericRuntimeManager","signature":"func NewKubeGenericRuntimeManager(","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"// NewKubeGenericRuntimeManager creates a new kubeGenericRuntimeManager\nfunc NewKubeGenericRuntimeManager(\n\trecorder record.EventRecorder,\n\tlivenessManager proberesults.Manager,\n\treadinessManager proberesults.Manager,\n\tstartupManager proberesults.Manager,\n\trootDirectory string,\n\tmachineInfo *cadvisorapi.MachineInfo,\n\tpodStateProvider podStateProvider,\n\tosInterface kubecontainer.OSInterface,\n\truntimeHelper kubecontainer.RuntimeHelper,\n\tinsecureContainerLifecycleHTTPClient types.HTTPDoer,\n\timageBackOff *flowcontrol.Backoff,\n\tserializeImagePulls bool,\n\tmaxParallelImagePulls *int32,\n\timagePullQPS float32,\n\timagePullBurst int,\n\timageCredentialProviderConfigFile string,\n\timageCredentialProviderBinDir string,\n\tcpuCFSQuota bool,\n\tcpuCFSQuotaPeriod metav1.Duration,\n\truntimeService internalapi.RuntimeService,\n\timageService internalapi.ImageManagerService,\n\tcontainerManager cm.ContainerManager,\n\tlogManager logs.ContainerLogManager,\n\truntimeClassManager *runtimeclass.Manager,\n\tseccompDefault bool,\n\tmemorySwapBehavior string,\n\tgetNodeAllocatable func() v1.ResourceList,\n\tmemoryThrottlingFactor float64,\n\tpodPullingTimeRecorder images.ImagePodPullingTimeRecorder,\n\ttracerProvider trace.TracerProvider,\n) (KubeGenericRuntime, error) {\n\tctx := context.Background()\n\truntimeService = newInstrumentedRuntimeService(runtimeService)\n\timageService = newInstrumentedImageManagerService(imageService)\n\ttracer := tracerProvider.Tracer(instrumentationScope)\n\tkubeRuntimeManager := \u0026kubeGenericRuntimeManager{\n\t\trecorder: recorder,\n\t\tcpuCFSQuota: cpuCFSQuota,\n\t\tcpuCFSQuotaPeriod: cpuCFSQuotaPeriod,\n\t\tseccompProfileRoot: filepath.Join(rootDirectory, \"seccomp\"),\n\t\tlivenessManager: livenessManager,\n\t\treadinessManager: readinessManager,\n\t\tstartupManager: startupManager,\n\t\tmachineInfo: machineInfo,\n\t\tosInterface: osInterface,\n\t\truntimeHelper: runtimeHelper,\n\t\truntimeService: runtimeService,\n\t\timageService: imageService,\n\t\tcontainerManager: containerManager,\n\t\tinternalLifecycle: containerManager.InternalContainerLifecycle(),\n\t\tlogManager: logManager,\n\t\truntimeClassManager: runtimeClassManager,\n\t\tlogReduction: logreduction.NewLogReduction(identicalErrorDelay),\n\t\tseccompDefault: seccompDefault,\n\t\tmemorySwapBehavior: memorySwapBehavior,\n\t\tgetNodeAllocatable: getNodeAllocatable,\n\t\tmemoryThrottlingFactor: memoryThrottlingFactor,\n\t}\n\n\ttypedVersion, err := kubeRuntimeManager.getTypedVersion(ctx)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Get runtime version failed\")\n\t\treturn nil, err\n\t}\n\n\t// Only matching kubeRuntimeAPIVersion is supported now\n\t// TODO: Runtime API machinery is under discussion at https://github.com/kubernetes/kubernetes/issues/28642\n\tif typedVersion.Version != kubeRuntimeAPIVersion {\n\t\tklog.ErrorS(err, \"This runtime api version is not supported\",\n\t\t\t\"apiVersion\", typedVersion.Version,\n\t\t\t\"supportedAPIVersion\", kubeRuntimeAPIVersion)\n\t\treturn nil, ErrVersionNotSupported\n\t}\n\n\tkubeRuntimeManager.runtimeName = typedVersion.RuntimeName\n\tklog.InfoS(\"Container runtime initialized\",\n\t\t\"containerRuntime\", typedVersion.RuntimeName,\n\t\t\"version\", typedVersion.RuntimeVersion,\n\t\t\"apiVersion\", typedVersion.RuntimeApiVersion)\n\n\t// If the container logs directory does not exist, create it.\n\t// TODO: create podLogsRootDirectory at kubelet.go when kubelet is refactored to\n\t// new runtime interface\n\tif _, err := osInterface.Stat(podLogsRootDirectory); os.IsNotExist(err) {\n\t\tif err := osInterface.MkdirAll(podLogsRootDirectory, 0755); err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to create pod log directory\", \"path\", podLogsRootDirectory)\n\t\t}\n\t}\n\n\tif imageCredentialProviderConfigFile != \"\" || imageCredentialProviderBinDir != \"\" {\n\t\tif err := plugin.RegisterCredentialProviderPlugins(imageCredentialProviderConfigFile, imageCredentialProviderBinDir); err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to register CRI auth plugins\")\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\tkubeRuntimeManager.keyring = credentialprovider.NewDockerKeyring()\n\n\tkubeRuntimeManager.imagePuller = images.NewImageManager(\n\t\tkubecontainer.FilterEventRecorder(recorder),\n\t\tkubeRuntimeManager,\n\t\timageBackOff,\n\t\tserializeImagePulls,\n\t\tmaxParallelImagePulls,\n\t\timagePullQPS,\n\t\timagePullBurst,\n\t\tpodPullingTimeRecorder)\n\tkubeRuntimeManager.runner = lifecycle.NewHandlerRunner(insecureContainerLifecycleHTTPClient, kubeRuntimeManager, kubeRuntimeManager, recorder)\n\tkubeRuntimeManager.containerGC = newContainerGC(runtimeService, podStateProvider, kubeRuntimeManager, tracer)\n\tkubeRuntimeManager.podStateProvider = podStateProvider\n\n\tkubeRuntimeManager.versionCache = cache.NewObjectCache(\n\t\tfunc() (interface{}, error) {\n\t\t\treturn kubeRuntimeManager.getTypedVersion(ctx)\n\t\t},\n\t\tversionCacheTTL,\n\t)\n\n\treturn kubeRuntimeManager, nil\n}","line":{"from":180,"to":300}} {"id":100007032,"name":"Type","signature":"func (m *kubeGenericRuntimeManager) Type() string","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"// Type returns the type of the container runtime.\nfunc (m *kubeGenericRuntimeManager) Type() string {\n\treturn m.runtimeName\n}","line":{"from":302,"to":305}} {"id":100007033,"name":"newRuntimeVersion","signature":"func newRuntimeVersion(version string) (*utilversion.Version, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"func newRuntimeVersion(version string) (*utilversion.Version, error) {\n\tif ver, err := utilversion.ParseSemantic(version); err == nil {\n\t\treturn ver, err\n\t}\n\treturn utilversion.ParseGeneric(version)\n}","line":{"from":307,"to":312}} {"id":100007034,"name":"getTypedVersion","signature":"func (m *kubeGenericRuntimeManager) getTypedVersion(ctx context.Context) (*runtimeapi.VersionResponse, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"func (m *kubeGenericRuntimeManager) getTypedVersion(ctx context.Context) (*runtimeapi.VersionResponse, error) {\n\ttypedVersion, err := m.runtimeService.Version(ctx, kubeRuntimeAPIVersion)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"get remote runtime typed version failed: %v\", err)\n\t}\n\treturn typedVersion, nil\n}","line":{"from":314,"to":320}} {"id":100007035,"name":"Version","signature":"func (m *kubeGenericRuntimeManager) Version(ctx context.Context) (kubecontainer.Version, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"// Version returns the version information of the container runtime.\nfunc (m *kubeGenericRuntimeManager) Version(ctx context.Context) (kubecontainer.Version, error) {\n\ttypedVersion, err := m.getTypedVersion(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newRuntimeVersion(typedVersion.RuntimeVersion)\n}","line":{"from":322,"to":330}} {"id":100007036,"name":"APIVersion","signature":"func (m *kubeGenericRuntimeManager) APIVersion() (kubecontainer.Version, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"// APIVersion returns the cached API version information of the container\n// runtime. Implementation is expected to update this cache periodically.\n// This may be different from the runtime engine's version.\nfunc (m *kubeGenericRuntimeManager) APIVersion() (kubecontainer.Version, error) {\n\tversionObject, err := m.versionCache.Get(m.machineInfo.MachineID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttypedVersion := versionObject.(*runtimeapi.VersionResponse)\n\n\treturn newRuntimeVersion(typedVersion.RuntimeApiVersion)\n}","line":{"from":332,"to":343}} {"id":100007037,"name":"Status","signature":"func (m *kubeGenericRuntimeManager) Status(ctx context.Context) (*kubecontainer.RuntimeStatus, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"// Status returns the status of the runtime. An error is returned if the Status\n// function itself fails, nil otherwise.\nfunc (m *kubeGenericRuntimeManager) Status(ctx context.Context) (*kubecontainer.RuntimeStatus, error) {\n\tresp, err := m.runtimeService.Status(ctx, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.GetStatus() == nil {\n\t\treturn nil, errors.New(\"runtime status is nil\")\n\t}\n\treturn toKubeRuntimeStatus(resp.GetStatus()), nil\n}","line":{"from":345,"to":356}} {"id":100007038,"name":"GetPods","signature":"func (m *kubeGenericRuntimeManager) GetPods(ctx context.Context, all bool) ([]*kubecontainer.Pod, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"// GetPods returns a list of containers grouped by pods. The boolean parameter\n// specifies whether the runtime returns all containers including those already\n// exited and dead containers (used for garbage collection).\nfunc (m *kubeGenericRuntimeManager) GetPods(ctx context.Context, all bool) ([]*kubecontainer.Pod, error) {\n\tpods := make(map[kubetypes.UID]*kubecontainer.Pod)\n\tsandboxes, err := m.getKubeletSandboxes(ctx, all)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor i := range sandboxes {\n\t\ts := sandboxes[i]\n\t\tif s.Metadata == nil {\n\t\t\tklog.V(4).InfoS(\"Sandbox does not have metadata\", \"sandbox\", s)\n\t\t\tcontinue\n\t\t}\n\t\tpodUID := kubetypes.UID(s.Metadata.Uid)\n\t\tif _, ok := pods[podUID]; !ok {\n\t\t\tpods[podUID] = \u0026kubecontainer.Pod{\n\t\t\t\tID: podUID,\n\t\t\t\tName: s.Metadata.Name,\n\t\t\t\tNamespace: s.Metadata.Namespace,\n\t\t\t}\n\t\t}\n\t\tp := pods[podUID]\n\t\tconverted, err := m.sandboxToKubeContainer(s)\n\t\tif err != nil {\n\t\t\tklog.V(4).InfoS(\"Convert sandbox of pod failed\", \"runtimeName\", m.runtimeName, \"sandbox\", s, \"podUID\", podUID, \"err\", err)\n\t\t\tcontinue\n\t\t}\n\t\tp.Sandboxes = append(p.Sandboxes, converted)\n\t\tp.CreatedAt = uint64(s.GetCreatedAt())\n\t}\n\n\tcontainers, err := m.getKubeletContainers(ctx, all)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor i := range containers {\n\t\tc := containers[i]\n\t\tif c.Metadata == nil {\n\t\t\tklog.V(4).InfoS(\"Container does not have metadata\", \"container\", c)\n\t\t\tcontinue\n\t\t}\n\n\t\tlabelledInfo := getContainerInfoFromLabels(c.Labels)\n\t\tpod, found := pods[labelledInfo.PodUID]\n\t\tif !found {\n\t\t\tpod = \u0026kubecontainer.Pod{\n\t\t\t\tID: labelledInfo.PodUID,\n\t\t\t\tName: labelledInfo.PodName,\n\t\t\t\tNamespace: labelledInfo.PodNamespace,\n\t\t\t}\n\t\t\tpods[labelledInfo.PodUID] = pod\n\t\t}\n\n\t\tconverted, err := m.toKubeContainer(c)\n\t\tif err != nil {\n\t\t\tklog.V(4).InfoS(\"Convert container of pod failed\", \"runtimeName\", m.runtimeName, \"container\", c, \"podUID\", labelledInfo.PodUID, \"err\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tpod.Containers = append(pod.Containers, converted)\n\t}\n\n\t// Convert map to list.\n\tvar result []*kubecontainer.Pod\n\tfor _, pod := range pods {\n\t\tresult = append(result, pod)\n\t}\n\n\t// There are scenarios where multiple pods are running in parallel having\n\t// the same name, because one of them have not been fully terminated yet.\n\t// To avoid unexpected behavior on container name based search (for example\n\t// by calling *Kubelet.findContainer() without specifying a pod ID), we now\n\t// return the list of pods ordered by their creation time.\n\tsort.SliceStable(result, func(i, j int) bool {\n\t\treturn result[i].CreatedAt \u003e result[j].CreatedAt\n\t})\n\tklog.V(4).InfoS(\"Retrieved pods from runtime\", \"all\", all)\n\treturn result, nil\n}","line":{"from":358,"to":438}} {"id":100007039,"name":"containerChanged","signature":"func containerChanged(container *v1.Container, containerStatus *kubecontainer.Status) (uint64, uint64, bool)","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"func containerChanged(container *v1.Container, containerStatus *kubecontainer.Status) (uint64, uint64, bool) {\n\texpectedHash := kubecontainer.HashContainer(container)\n\treturn expectedHash, containerStatus.Hash, containerStatus.Hash != expectedHash\n}","line":{"from":515,"to":518}} {"id":100007040,"name":"shouldRestartOnFailure","signature":"func shouldRestartOnFailure(pod *v1.Pod) bool","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"func shouldRestartOnFailure(pod *v1.Pod) bool {\n\treturn pod.Spec.RestartPolicy != v1.RestartPolicyNever\n}","line":{"from":520,"to":522}} {"id":100007041,"name":"containerSucceeded","signature":"func containerSucceeded(c *v1.Container, podStatus *kubecontainer.PodStatus) bool","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"func containerSucceeded(c *v1.Container, podStatus *kubecontainer.PodStatus) bool {\n\tcStatus := podStatus.FindContainerStatusByName(c.Name)\n\tif cStatus == nil || cStatus.State == kubecontainer.ContainerStateRunning {\n\t\treturn false\n\t}\n\treturn cStatus.ExitCode == 0\n}","line":{"from":524,"to":530}} {"id":100007042,"name":"isInPlacePodVerticalScalingAllowed","signature":"func isInPlacePodVerticalScalingAllowed(pod *v1.Pod) bool","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"func isInPlacePodVerticalScalingAllowed(pod *v1.Pod) bool {\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) {\n\t\treturn false\n\t}\n\tif types.IsStaticPod(pod) {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":532,"to":540}} {"id":100007043,"name":"computePodResizeAction","signature":"func (m *kubeGenericRuntimeManager) computePodResizeAction(pod *v1.Pod, containerIdx int, kubeContainerStatus *kubecontainer.Status, changes *podActions) bool","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"func (m *kubeGenericRuntimeManager) computePodResizeAction(pod *v1.Pod, containerIdx int, kubeContainerStatus *kubecontainer.Status, changes *podActions) bool {\n\tcontainer := pod.Spec.Containers[containerIdx]\n\tif container.Resources.Limits == nil || len(pod.Status.ContainerStatuses) == 0 {\n\t\treturn true\n\t}\n\n\t// Determine if the *running* container needs resource update by comparing v1.Spec.Resources (desired)\n\t// with v1.Status.Resources / runtime.Status.Resources (last known actual).\n\t// Proceed only when kubelet has accepted the resize a.k.a v1.Spec.Resources.Requests == v1.Status.AllocatedResources.\n\t// Skip if runtime containerID doesn't match pod.Status containerID (container is restarting)\n\tapiContainerStatus, exists := podutil.GetContainerStatus(pod.Status.ContainerStatuses, container.Name)\n\tif !exists || apiContainerStatus.State.Running == nil || apiContainerStatus.Resources == nil ||\n\t\tkubeContainerStatus.State != kubecontainer.ContainerStateRunning ||\n\t\tkubeContainerStatus.ID.String() != apiContainerStatus.ContainerID ||\n\t\tlen(diff.ObjectDiff(container.Resources.Requests, apiContainerStatus.AllocatedResources)) != 0 {\n\t\treturn true\n\t}\n\n\tdesiredMemoryLimit := container.Resources.Limits.Memory().Value()\n\tdesiredCPULimit := container.Resources.Limits.Cpu().MilliValue()\n\tdesiredCPURequest := container.Resources.Requests.Cpu().MilliValue()\n\tcurrentMemoryLimit := apiContainerStatus.Resources.Limits.Memory().Value()\n\tcurrentCPULimit := apiContainerStatus.Resources.Limits.Cpu().MilliValue()\n\tcurrentCPURequest := apiContainerStatus.Resources.Requests.Cpu().MilliValue()\n\t// Runtime container status resources (from CRI), if set, supercedes v1(api) container status resrouces.\n\tif kubeContainerStatus.Resources != nil {\n\t\tif kubeContainerStatus.Resources.MemoryLimit != nil {\n\t\t\tcurrentMemoryLimit = kubeContainerStatus.Resources.MemoryLimit.Value()\n\t\t}\n\t\tif kubeContainerStatus.Resources.CPULimit != nil {\n\t\t\tcurrentCPULimit = kubeContainerStatus.Resources.CPULimit.MilliValue()\n\t\t}\n\t\tif kubeContainerStatus.Resources.CPURequest != nil {\n\t\t\tcurrentCPURequest = kubeContainerStatus.Resources.CPURequest.MilliValue()\n\t\t}\n\t}\n\n\t// Note: cgroup doesn't support memory request today, so we don't compare that. If canAdmitPod called during\n\t// handlePodResourcesResize finds 'fit', then desiredMemoryRequest == currentMemoryRequest.\n\tif desiredMemoryLimit == currentMemoryLimit \u0026\u0026 desiredCPULimit == currentCPULimit \u0026\u0026 desiredCPURequest == currentCPURequest {\n\t\treturn true\n\t}\n\n\tdesiredResources := containerResources{\n\t\tmemoryLimit: desiredMemoryLimit,\n\t\tmemoryRequest: apiContainerStatus.AllocatedResources.Memory().Value(),\n\t\tcpuLimit: desiredCPULimit,\n\t\tcpuRequest: desiredCPURequest,\n\t}\n\tcurrentResources := containerResources{\n\t\tmemoryLimit: currentMemoryLimit,\n\t\tmemoryRequest: apiContainerStatus.Resources.Requests.Memory().Value(),\n\t\tcpuLimit: currentCPULimit,\n\t\tcpuRequest: currentCPURequest,\n\t}\n\n\tresizePolicy := make(map[v1.ResourceName]v1.ResourceResizeRestartPolicy)\n\tfor _, pol := range container.ResizePolicy {\n\t\tresizePolicy[pol.ResourceName] = pol.RestartPolicy\n\t}\n\tdetermineContainerResize := func(rName v1.ResourceName, specValue, statusValue int64) (resize, restart bool) {\n\t\tif specValue == statusValue {\n\t\t\treturn false, false\n\t\t}\n\t\tif resizePolicy[rName] == v1.RestartContainer {\n\t\t\treturn true, true\n\t\t}\n\t\treturn true, false\n\t}\n\tmarkContainerForUpdate := func(rName v1.ResourceName, specValue, statusValue int64) {\n\t\tcUpdateInfo := containerToUpdateInfo{\n\t\t\tapiContainerIdx: containerIdx,\n\t\t\tkubeContainerID: kubeContainerStatus.ID,\n\t\t\tdesiredContainerResources: desiredResources,\n\t\t\tcurrentContainerResources: \u0026currentResources,\n\t\t}\n\t\t// Order the container updates such that resource decreases are applied before increases\n\t\tswitch {\n\t\tcase specValue \u003e statusValue: // append\n\t\t\tchanges.ContainersToUpdate[rName] = append(changes.ContainersToUpdate[rName], cUpdateInfo)\n\t\tcase specValue \u003c statusValue: // prepend\n\t\t\tchanges.ContainersToUpdate[rName] = append(changes.ContainersToUpdate[rName], containerToUpdateInfo{})\n\t\t\tcopy(changes.ContainersToUpdate[rName][1:], changes.ContainersToUpdate[rName])\n\t\t\tchanges.ContainersToUpdate[rName][0] = cUpdateInfo\n\t\t}\n\t}\n\tresizeMemLim, restartMemLim := determineContainerResize(v1.ResourceMemory, desiredMemoryLimit, currentMemoryLimit)\n\tresizeCPULim, restartCPULim := determineContainerResize(v1.ResourceCPU, desiredCPULimit, currentCPULimit)\n\tresizeCPUReq, restartCPUReq := determineContainerResize(v1.ResourceCPU, desiredCPURequest, currentCPURequest)\n\tif restartCPULim || restartCPUReq || restartMemLim {\n\t\t// resize policy requires this container to restart\n\t\tchanges.ContainersToKill[kubeContainerStatus.ID] = containerToKillInfo{\n\t\t\tname: kubeContainerStatus.Name,\n\t\t\tcontainer: \u0026pod.Spec.Containers[containerIdx],\n\t\t\tmessage: fmt.Sprintf(\"Container %s resize requires restart\", container.Name),\n\t\t}\n\t\tchanges.ContainersToStart = append(changes.ContainersToStart, containerIdx)\n\t\tchanges.UpdatePodResources = true\n\t\treturn false\n\t} else {\n\t\tif resizeMemLim {\n\t\t\tmarkContainerForUpdate(v1.ResourceMemory, desiredMemoryLimit, currentMemoryLimit)\n\t\t}\n\t\tif resizeCPULim {\n\t\t\tmarkContainerForUpdate(v1.ResourceCPU, desiredCPULimit, currentCPULimit)\n\t\t} else if resizeCPUReq {\n\t\t\tmarkContainerForUpdate(v1.ResourceCPU, desiredCPURequest, currentCPURequest)\n\t\t}\n\t}\n\treturn true\n}","line":{"from":542,"to":652}} {"id":100007044,"name":"doPodResizeAction","signature":"func (m *kubeGenericRuntimeManager) doPodResizeAction(pod *v1.Pod, podStatus *kubecontainer.PodStatus, podContainerChanges podActions, result kubecontainer.PodSyncResult)","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"func (m *kubeGenericRuntimeManager) doPodResizeAction(pod *v1.Pod, podStatus *kubecontainer.PodStatus, podContainerChanges podActions, result kubecontainer.PodSyncResult) {\n\tpcm := m.containerManager.NewPodContainerManager()\n\t//TODO(vinaykul,InPlacePodVerticalScaling): Figure out best way to get enforceMemoryQoS value (parameter #4 below) in platform-agnostic way\n\tpodResources := cm.ResourceConfigForPod(pod, m.cpuCFSQuota, uint64((m.cpuCFSQuotaPeriod.Duration)/time.Microsecond), false)\n\tif podResources == nil {\n\t\tklog.ErrorS(nil, \"Unable to get resource configuration\", \"pod\", pod.Name)\n\t\tresult.Fail(fmt.Errorf(\"Unable to get resource configuration processing resize for pod %s\", pod.Name))\n\t\treturn\n\t}\n\tsetPodCgroupConfig := func(rName v1.ResourceName, setLimitValue bool) error {\n\t\tvar err error\n\t\tswitch rName {\n\t\tcase v1.ResourceCPU:\n\t\t\tpodCpuResources := \u0026cm.ResourceConfig{CPUPeriod: podResources.CPUPeriod}\n\t\t\tif setLimitValue == true {\n\t\t\t\tpodCpuResources.CPUQuota = podResources.CPUQuota\n\t\t\t} else {\n\t\t\t\tpodCpuResources.CPUShares = podResources.CPUShares\n\t\t\t}\n\t\t\terr = pcm.SetPodCgroupConfig(pod, rName, podCpuResources)\n\t\tcase v1.ResourceMemory:\n\t\t\terr = pcm.SetPodCgroupConfig(pod, rName, podResources)\n\t\t}\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to set cgroup config\", \"resource\", rName, \"pod\", pod.Name)\n\t\t}\n\t\treturn err\n\t}\n\t// Memory and CPU are updated separately because memory resizes may be ordered differently than CPU resizes.\n\t// If resize results in net pod resource increase, set pod cgroup config before resizing containers.\n\t// If resize results in net pod resource decrease, set pod cgroup config after resizing containers.\n\t// If an error occurs at any point, abort. Let future syncpod iterations retry the unfinished stuff.\n\tresizeContainers := func(rName v1.ResourceName, currPodCgLimValue, newPodCgLimValue, currPodCgReqValue, newPodCgReqValue int64) error {\n\t\tvar err error\n\t\tif newPodCgLimValue \u003e currPodCgLimValue {\n\t\t\tif err = setPodCgroupConfig(rName, true); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif newPodCgReqValue \u003e currPodCgReqValue {\n\t\t\tif err = setPodCgroupConfig(rName, false); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif len(podContainerChanges.ContainersToUpdate[rName]) \u003e 0 {\n\t\t\tif err = m.updatePodContainerResources(pod, rName, podContainerChanges.ContainersToUpdate[rName]); err != nil {\n\t\t\t\tklog.ErrorS(err, \"updatePodContainerResources failed\", \"pod\", format.Pod(pod), \"resource\", rName)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif newPodCgLimValue \u003c currPodCgLimValue {\n\t\t\terr = setPodCgroupConfig(rName, true)\n\t\t}\n\t\tif newPodCgReqValue \u003c currPodCgReqValue {\n\t\t\tif err = setPodCgroupConfig(rName, false); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn err\n\t}\n\tif len(podContainerChanges.ContainersToUpdate[v1.ResourceMemory]) \u003e 0 || podContainerChanges.UpdatePodResources {\n\t\tif podResources.Memory == nil {\n\t\t\tklog.ErrorS(nil, \"podResources.Memory is nil\", \"pod\", pod.Name)\n\t\t\tresult.Fail(fmt.Errorf(\"podResources.Memory is nil for pod %s\", pod.Name))\n\t\t\treturn\n\t\t}\n\t\tcurrentPodMemoryConfig, err := pcm.GetPodCgroupConfig(pod, v1.ResourceMemory)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"GetPodCgroupConfig for memory failed\", \"pod\", pod.Name)\n\t\t\tresult.Fail(err)\n\t\t\treturn\n\t\t}\n\t\tcurrentPodMemoryUsage, err := pcm.GetPodCgroupMemoryUsage(pod)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"GetPodCgroupMemoryUsage failed\", \"pod\", pod.Name)\n\t\t\tresult.Fail(err)\n\t\t\treturn\n\t\t}\n\t\tif currentPodMemoryUsage \u003e= uint64(*podResources.Memory) {\n\t\t\tklog.ErrorS(nil, \"Aborting attempt to set pod memory limit less than current memory usage\", \"pod\", pod.Name)\n\t\t\tresult.Fail(fmt.Errorf(\"Aborting attempt to set pod memory limit less than current memory usage for pod %s\", pod.Name))\n\t\t\treturn\n\t\t}\n\t\tif errResize := resizeContainers(v1.ResourceMemory, int64(*currentPodMemoryConfig.Memory), *podResources.Memory, 0, 0); errResize != nil {\n\t\t\tresult.Fail(errResize)\n\t\t\treturn\n\t\t}\n\t}\n\tif len(podContainerChanges.ContainersToUpdate[v1.ResourceCPU]) \u003e 0 || podContainerChanges.UpdatePodResources {\n\t\tif podResources.CPUQuota == nil || podResources.CPUShares == nil {\n\t\t\tklog.ErrorS(nil, \"podResources.CPUQuota or podResources.CPUShares is nil\", \"pod\", pod.Name)\n\t\t\tresult.Fail(fmt.Errorf(\"podResources.CPUQuota or podResources.CPUShares is nil for pod %s\", pod.Name))\n\t\t\treturn\n\t\t}\n\t\tcurrentPodCpuConfig, err := pcm.GetPodCgroupConfig(pod, v1.ResourceCPU)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"GetPodCgroupConfig for CPU failed\", \"pod\", pod.Name)\n\t\t\tresult.Fail(err)\n\t\t\treturn\n\t\t}\n\t\tif errResize := resizeContainers(v1.ResourceCPU, *currentPodCpuConfig.CPUQuota, *podResources.CPUQuota,\n\t\t\tint64(*currentPodCpuConfig.CPUShares), int64(*podResources.CPUShares)); errResize != nil {\n\t\t\tresult.Fail(errResize)\n\t\t\treturn\n\t\t}\n\t}\n}","line":{"from":654,"to":760}} {"id":100007045,"name":"updatePodContainerResources","signature":"func (m *kubeGenericRuntimeManager) updatePodContainerResources(pod *v1.Pod, resourceName v1.ResourceName, containersToUpdate []containerToUpdateInfo) error","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"func (m *kubeGenericRuntimeManager) updatePodContainerResources(pod *v1.Pod, resourceName v1.ResourceName, containersToUpdate []containerToUpdateInfo) error {\n\tklog.V(5).InfoS(\"Updating container resources\", \"pod\", klog.KObj(pod))\n\n\tfor _, cInfo := range containersToUpdate {\n\t\tcontainer := pod.Spec.Containers[cInfo.apiContainerIdx].DeepCopy()\n\t\t// If updating memory limit, use most recently configured CPU request and limit values.\n\t\t// If updating CPU request and limit, use most recently configured memory request and limit values.\n\t\tswitch resourceName {\n\t\tcase v1.ResourceMemory:\n\t\t\tcontainer.Resources.Limits = v1.ResourceList{\n\t\t\t\tv1.ResourceCPU: *resource.NewMilliQuantity(cInfo.currentContainerResources.cpuLimit, resource.DecimalSI),\n\t\t\t\tv1.ResourceMemory: *resource.NewQuantity(cInfo.desiredContainerResources.memoryLimit, resource.BinarySI),\n\t\t\t}\n\t\t\tcontainer.Resources.Requests = v1.ResourceList{\n\t\t\t\tv1.ResourceCPU: *resource.NewMilliQuantity(cInfo.currentContainerResources.cpuRequest, resource.DecimalSI),\n\t\t\t\tv1.ResourceMemory: *resource.NewQuantity(cInfo.desiredContainerResources.memoryRequest, resource.BinarySI),\n\t\t\t}\n\t\tcase v1.ResourceCPU:\n\t\t\tcontainer.Resources.Limits = v1.ResourceList{\n\t\t\t\tv1.ResourceCPU: *resource.NewMilliQuantity(cInfo.desiredContainerResources.cpuLimit, resource.DecimalSI),\n\t\t\t\tv1.ResourceMemory: *resource.NewQuantity(cInfo.currentContainerResources.memoryLimit, resource.BinarySI),\n\t\t\t}\n\t\t\tcontainer.Resources.Requests = v1.ResourceList{\n\t\t\t\tv1.ResourceCPU: *resource.NewMilliQuantity(cInfo.desiredContainerResources.cpuRequest, resource.DecimalSI),\n\t\t\t\tv1.ResourceMemory: *resource.NewQuantity(cInfo.currentContainerResources.memoryRequest, resource.BinarySI),\n\t\t\t}\n\t\t}\n\t\tif err := m.updateContainerResources(pod, container, cInfo.kubeContainerID); err != nil {\n\t\t\t// Log error and abort as container updates need to succeed in the order determined by computePodResizeAction.\n\t\t\t// The recovery path is for SyncPod to keep retrying at later times until it succeeds.\n\t\t\tklog.ErrorS(err, \"updateContainerResources failed\", \"container\", container.Name, \"cID\", cInfo.kubeContainerID,\n\t\t\t\t\"pod\", format.Pod(pod), \"resourceName\", resourceName)\n\t\t\treturn err\n\t\t}\n\t\t// If UpdateContainerResources is error-free, it means desired values for 'resourceName' was accepted by runtime.\n\t\t// So we update currentContainerResources for 'resourceName', which is our view of most recently configured resources.\n\t\t// Note: We can't rely on GetPodStatus as runtime may lag in actuating the resource values it just accepted.\n\t\tswitch resourceName {\n\t\tcase v1.ResourceMemory:\n\t\t\tcInfo.currentContainerResources.memoryLimit = cInfo.desiredContainerResources.memoryLimit\n\t\t\tcInfo.currentContainerResources.memoryRequest = cInfo.desiredContainerResources.memoryRequest\n\t\tcase v1.ResourceCPU:\n\t\t\tcInfo.currentContainerResources.cpuLimit = cInfo.desiredContainerResources.cpuLimit\n\t\t\tcInfo.currentContainerResources.cpuRequest = cInfo.desiredContainerResources.cpuRequest\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":762,"to":809}} {"id":100007046,"name":"computePodActions","signature":"func (m *kubeGenericRuntimeManager) computePodActions(ctx context.Context, pod *v1.Pod, podStatus *kubecontainer.PodStatus) podActions","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"// computePodActions checks whether the pod spec has changed and returns the changes if true.\nfunc (m *kubeGenericRuntimeManager) computePodActions(ctx context.Context, pod *v1.Pod, podStatus *kubecontainer.PodStatus) podActions {\n\tklog.V(5).InfoS(\"Syncing Pod\", \"pod\", klog.KObj(pod))\n\n\tcreatePodSandbox, attempt, sandboxID := runtimeutil.PodSandboxChanged(pod, podStatus)\n\tchanges := podActions{\n\t\tKillPod: createPodSandbox,\n\t\tCreateSandbox: createPodSandbox,\n\t\tSandboxID: sandboxID,\n\t\tAttempt: attempt,\n\t\tContainersToStart: []int{},\n\t\tContainersToKill: make(map[kubecontainer.ContainerID]containerToKillInfo),\n\t}\n\n\t// If we need to (re-)create the pod sandbox, everything will need to be\n\t// killed and recreated, and init containers should be purged.\n\tif createPodSandbox {\n\t\tif !shouldRestartOnFailure(pod) \u0026\u0026 attempt != 0 \u0026\u0026 len(podStatus.ContainerStatuses) != 0 {\n\t\t\t// Should not restart the pod, just return.\n\t\t\t// we should not create a sandbox for a pod if it is already done.\n\t\t\t// if all containers are done and should not be started, there is no need to create a new sandbox.\n\t\t\t// this stops confusing logs on pods whose containers all have exit codes, but we recreate a sandbox before terminating it.\n\t\t\t//\n\t\t\t// If ContainerStatuses is empty, we assume that we've never\n\t\t\t// successfully created any containers. In this case, we should\n\t\t\t// retry creating the sandbox.\n\t\t\tchanges.CreateSandbox = false\n\t\t\treturn changes\n\t\t}\n\n\t\t// Get the containers to start, excluding the ones that succeeded if RestartPolicy is OnFailure.\n\t\tvar containersToStart []int\n\t\tfor idx, c := range pod.Spec.Containers {\n\t\t\tif pod.Spec.RestartPolicy == v1.RestartPolicyOnFailure \u0026\u0026 containerSucceeded(\u0026c, podStatus) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcontainersToStart = append(containersToStart, idx)\n\t\t}\n\t\t// We should not create a sandbox for a Pod if initialization is done and there is no container to start.\n\t\tif len(containersToStart) == 0 {\n\t\t\t_, _, done := findNextInitContainerToRun(pod, podStatus)\n\t\t\tif done {\n\t\t\t\tchanges.CreateSandbox = false\n\t\t\t\treturn changes\n\t\t\t}\n\t\t}\n\n\t\tif len(pod.Spec.InitContainers) != 0 {\n\t\t\t// Pod has init containers, return the first one.\n\t\t\tchanges.NextInitContainerToStart = \u0026pod.Spec.InitContainers[0]\n\t\t\treturn changes\n\t\t}\n\t\tchanges.ContainersToStart = containersToStart\n\t\treturn changes\n\t}\n\n\t// Ephemeral containers may be started even if initialization is not yet complete.\n\tfor i := range pod.Spec.EphemeralContainers {\n\t\tc := (*v1.Container)(\u0026pod.Spec.EphemeralContainers[i].EphemeralContainerCommon)\n\n\t\t// Ephemeral Containers are never restarted\n\t\tif podStatus.FindContainerStatusByName(c.Name) == nil {\n\t\t\tchanges.EphemeralContainersToStart = append(changes.EphemeralContainersToStart, i)\n\t\t}\n\t}\n\n\t// Check initialization progress.\n\tinitLastStatus, next, done := findNextInitContainerToRun(pod, podStatus)\n\tif !done {\n\t\tif next != nil {\n\t\t\tinitFailed := initLastStatus != nil \u0026\u0026 isInitContainerFailed(initLastStatus)\n\t\t\tif initFailed \u0026\u0026 !shouldRestartOnFailure(pod) {\n\t\t\t\tchanges.KillPod = true\n\t\t\t} else {\n\t\t\t\t// Always try to stop containers in unknown state first.\n\t\t\t\tif initLastStatus != nil \u0026\u0026 initLastStatus.State == kubecontainer.ContainerStateUnknown {\n\t\t\t\t\tchanges.ContainersToKill[initLastStatus.ID] = containerToKillInfo{\n\t\t\t\t\t\tname: next.Name,\n\t\t\t\t\t\tcontainer: next,\n\t\t\t\t\t\tmessage: fmt.Sprintf(\"Init container is in %q state, try killing it before restart\",\n\t\t\t\t\t\t\tinitLastStatus.State),\n\t\t\t\t\t\treason: reasonUnknown,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tchanges.NextInitContainerToStart = next\n\t\t\t}\n\t\t}\n\t\t// Initialization failed or still in progress. Skip inspecting non-init\n\t\t// containers.\n\t\treturn changes\n\t}\n\n\tif isInPlacePodVerticalScalingAllowed(pod) {\n\t\tchanges.ContainersToUpdate = make(map[v1.ResourceName][]containerToUpdateInfo)\n\t\tlatestPodStatus, err := m.GetPodStatus(ctx, podStatus.ID, pod.Name, pod.Namespace)\n\t\tif err == nil {\n\t\t\tpodStatus = latestPodStatus\n\t\t}\n\t}\n\n\t// Number of running containers to keep.\n\tkeepCount := 0\n\t// check the status of containers.\n\tfor idx, container := range pod.Spec.Containers {\n\t\tcontainerStatus := podStatus.FindContainerStatusByName(container.Name)\n\n\t\t// Call internal container post-stop lifecycle hook for any non-running container so that any\n\t\t// allocated cpus are released immediately. If the container is restarted, cpus will be re-allocated\n\t\t// to it.\n\t\tif containerStatus != nil \u0026\u0026 containerStatus.State != kubecontainer.ContainerStateRunning {\n\t\t\tif err := m.internalLifecycle.PostStopContainer(containerStatus.ID.ID); err != nil {\n\t\t\t\tklog.ErrorS(err, \"Internal container post-stop lifecycle hook failed for container in pod with error\",\n\t\t\t\t\t\"containerName\", container.Name, \"pod\", klog.KObj(pod))\n\t\t\t}\n\t\t}\n\n\t\t// If container does not exist, or is not running, check whether we\n\t\t// need to restart it.\n\t\tif containerStatus == nil || containerStatus.State != kubecontainer.ContainerStateRunning {\n\t\t\tif kubecontainer.ShouldContainerBeRestarted(\u0026container, pod, podStatus) {\n\t\t\t\tklog.V(3).InfoS(\"Container of pod is not in the desired state and shall be started\", \"containerName\", container.Name, \"pod\", klog.KObj(pod))\n\t\t\t\tchanges.ContainersToStart = append(changes.ContainersToStart, idx)\n\t\t\t\tif containerStatus != nil \u0026\u0026 containerStatus.State == kubecontainer.ContainerStateUnknown {\n\t\t\t\t\t// If container is in unknown state, we don't know whether it\n\t\t\t\t\t// is actually running or not, always try killing it before\n\t\t\t\t\t// restart to avoid having 2 running instances of the same container.\n\t\t\t\t\tchanges.ContainersToKill[containerStatus.ID] = containerToKillInfo{\n\t\t\t\t\t\tname: containerStatus.Name,\n\t\t\t\t\t\tcontainer: \u0026pod.Spec.Containers[idx],\n\t\t\t\t\t\tmessage: fmt.Sprintf(\"Container is in %q state, try killing it before restart\",\n\t\t\t\t\t\t\tcontainerStatus.State),\n\t\t\t\t\t\treason: reasonUnknown,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\t// The container is running, but kill the container if any of the following condition is met.\n\t\tvar message string\n\t\tvar reason containerKillReason\n\t\trestart := shouldRestartOnFailure(pod)\n\t\t// Do not restart if only the Resources field has changed with InPlacePodVerticalScaling enabled\n\t\tif _, _, changed := containerChanged(\u0026container, containerStatus); changed \u0026\u0026\n\t\t\t(!isInPlacePodVerticalScalingAllowed(pod) ||\n\t\t\t\tkubecontainer.HashContainerWithoutResources(\u0026container) != containerStatus.HashWithoutResources) {\n\t\t\tmessage = fmt.Sprintf(\"Container %s definition changed\", container.Name)\n\t\t\t// Restart regardless of the restart policy because the container\n\t\t\t// spec changed.\n\t\t\trestart = true\n\t\t} else if liveness, found := m.livenessManager.Get(containerStatus.ID); found \u0026\u0026 liveness == proberesults.Failure {\n\t\t\t// If the container failed the liveness probe, we should kill it.\n\t\t\tmessage = fmt.Sprintf(\"Container %s failed liveness probe\", container.Name)\n\t\t\treason = reasonLivenessProbe\n\t\t} else if startup, found := m.startupManager.Get(containerStatus.ID); found \u0026\u0026 startup == proberesults.Failure {\n\t\t\t// If the container failed the startup probe, we should kill it.\n\t\t\tmessage = fmt.Sprintf(\"Container %s failed startup probe\", container.Name)\n\t\t\treason = reasonStartupProbe\n\t\t} else if isInPlacePodVerticalScalingAllowed(pod) \u0026\u0026 !m.computePodResizeAction(pod, idx, containerStatus, \u0026changes) {\n\t\t\t// computePodResizeAction updates 'changes' if resize policy requires restarting this container\n\t\t\tcontinue\n\t\t} else {\n\t\t\t// Keep the container.\n\t\t\tkeepCount++\n\t\t\tcontinue\n\t\t}\n\n\t\t// We need to kill the container, but if we also want to restart the\n\t\t// container afterwards, make the intent clear in the message. Also do\n\t\t// not kill the entire pod since we expect container to be running eventually.\n\t\tif restart {\n\t\t\tmessage = fmt.Sprintf(\"%s, will be restarted\", message)\n\t\t\tchanges.ContainersToStart = append(changes.ContainersToStart, idx)\n\t\t}\n\n\t\tchanges.ContainersToKill[containerStatus.ID] = containerToKillInfo{\n\t\t\tname: containerStatus.Name,\n\t\t\tcontainer: \u0026pod.Spec.Containers[idx],\n\t\t\tmessage: message,\n\t\t\treason: reason,\n\t\t}\n\t\tklog.V(2).InfoS(\"Message for Container of pod\", \"containerName\", container.Name, \"containerStatusID\", containerStatus.ID, \"pod\", klog.KObj(pod), \"containerMessage\", message)\n\t}\n\n\tif keepCount == 0 \u0026\u0026 len(changes.ContainersToStart) == 0 {\n\t\tchanges.KillPod = true\n\t}\n\n\treturn changes\n}","line":{"from":811,"to":999}} {"id":100007047,"name":"SyncPod","signature":"func (m *kubeGenericRuntimeManager) SyncPod(ctx context.Context, pod *v1.Pod, podStatus *kubecontainer.PodStatus, pullSecrets []v1.Secret, backOff *flowcontrol.Backoff) (result kubecontainer.PodSyncResult)","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"// SyncPod syncs the running pod into the desired pod by executing following steps:\n//\n// 1. Compute sandbox and container changes.\n// 2. Kill pod sandbox if necessary.\n// 3. Kill any containers that should not be running.\n// 4. Create sandbox if necessary.\n// 5. Create ephemeral containers.\n// 6. Create init containers.\n// 7. Resize running containers (if InPlacePodVerticalScaling==true)\n// 8. Create normal containers.\nfunc (m *kubeGenericRuntimeManager) SyncPod(ctx context.Context, pod *v1.Pod, podStatus *kubecontainer.PodStatus, pullSecrets []v1.Secret, backOff *flowcontrol.Backoff) (result kubecontainer.PodSyncResult) {\n\t// Step 1: Compute sandbox and container changes.\n\tpodContainerChanges := m.computePodActions(ctx, pod, podStatus)\n\tklog.V(3).InfoS(\"computePodActions got for pod\", \"podActions\", podContainerChanges, \"pod\", klog.KObj(pod))\n\tif podContainerChanges.CreateSandbox {\n\t\tref, err := ref.GetReference(legacyscheme.Scheme, pod)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Couldn't make a ref to pod\", \"pod\", klog.KObj(pod))\n\t\t}\n\t\tif podContainerChanges.SandboxID != \"\" {\n\t\t\tm.recorder.Eventf(ref, v1.EventTypeNormal, events.SandboxChanged, \"Pod sandbox changed, it will be killed and re-created.\")\n\t\t} else {\n\t\t\tklog.V(4).InfoS(\"SyncPod received new pod, will create a sandbox for it\", \"pod\", klog.KObj(pod))\n\t\t}\n\t}\n\n\t// Step 2: Kill the pod if the sandbox has changed.\n\tif podContainerChanges.KillPod {\n\t\tif podContainerChanges.CreateSandbox {\n\t\t\tklog.V(4).InfoS(\"Stopping PodSandbox for pod, will start new one\", \"pod\", klog.KObj(pod))\n\t\t} else {\n\t\t\tklog.V(4).InfoS(\"Stopping PodSandbox for pod, because all other containers are dead\", \"pod\", klog.KObj(pod))\n\t\t}\n\n\t\tkillResult := m.killPodWithSyncResult(ctx, pod, kubecontainer.ConvertPodStatusToRunningPod(m.runtimeName, podStatus), nil)\n\t\tresult.AddPodSyncResult(killResult)\n\t\tif killResult.Error() != nil {\n\t\t\tklog.ErrorS(killResult.Error(), \"killPodWithSyncResult failed\")\n\t\t\treturn\n\t\t}\n\n\t\tif podContainerChanges.CreateSandbox {\n\t\t\tm.purgeInitContainers(ctx, pod, podStatus)\n\t\t}\n\t} else {\n\t\t// Step 3: kill any running containers in this pod which are not to keep.\n\t\tfor containerID, containerInfo := range podContainerChanges.ContainersToKill {\n\t\t\tklog.V(3).InfoS(\"Killing unwanted container for pod\", \"containerName\", containerInfo.name, \"containerID\", containerID, \"pod\", klog.KObj(pod))\n\t\t\tkillContainerResult := kubecontainer.NewSyncResult(kubecontainer.KillContainer, containerInfo.name)\n\t\t\tresult.AddSyncResult(killContainerResult)\n\t\t\tif err := m.killContainer(ctx, pod, containerID, containerInfo.name, containerInfo.message, containerInfo.reason, nil); err != nil {\n\t\t\t\tkillContainerResult.Fail(kubecontainer.ErrKillContainer, err.Error())\n\t\t\t\tklog.ErrorS(err, \"killContainer for pod failed\", \"containerName\", containerInfo.name, \"containerID\", containerID, \"pod\", klog.KObj(pod))\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\t// Keep terminated init containers fairly aggressively controlled\n\t// This is an optimization because container removals are typically handled\n\t// by container garbage collector.\n\tm.pruneInitContainersBeforeStart(ctx, pod, podStatus)\n\n\t// We pass the value of the PRIMARY podIP and list of podIPs down to\n\t// generatePodSandboxConfig and generateContainerConfig, which in turn\n\t// passes it to various other functions, in order to facilitate functionality\n\t// that requires this value (hosts file and downward API) and avoid races determining\n\t// the pod IP in cases where a container requires restart but the\n\t// podIP isn't in the status manager yet. The list of podIPs is used to\n\t// generate the hosts file.\n\t//\n\t// We default to the IPs in the passed-in pod status, and overwrite them if the\n\t// sandbox needs to be (re)started.\n\tvar podIPs []string\n\tif podStatus != nil {\n\t\tpodIPs = podStatus.IPs\n\t}\n\n\t// Step 4: Create a sandbox for the pod if necessary.\n\tpodSandboxID := podContainerChanges.SandboxID\n\tif podContainerChanges.CreateSandbox {\n\t\tvar msg string\n\t\tvar err error\n\n\t\tklog.V(4).InfoS(\"Creating PodSandbox for pod\", \"pod\", klog.KObj(pod))\n\t\tmetrics.StartedPodsTotal.Inc()\n\t\tcreateSandboxResult := kubecontainer.NewSyncResult(kubecontainer.CreatePodSandbox, format.Pod(pod))\n\t\tresult.AddSyncResult(createSandboxResult)\n\n\t\t// ConvertPodSysctlsVariableToDotsSeparator converts sysctl variable\n\t\t// in the Pod.Spec.SecurityContext.Sysctls slice into a dot as a separator.\n\t\t// runc uses the dot as the separator to verify whether the sysctl variable\n\t\t// is correct in a separate namespace, so when using the slash as the sysctl\n\t\t// variable separator, runc returns an error: \"sysctl is not in a separate kernel namespace\"\n\t\t// and the podSandBox cannot be successfully created. Therefore, before calling runc,\n\t\t// we need to convert the sysctl variable, the dot is used as a separator to separate the kernel namespace.\n\t\t// When runc supports slash as sysctl separator, this function can no longer be used.\n\t\tsysctl.ConvertPodSysctlsVariableToDotsSeparator(pod.Spec.SecurityContext)\n\n\t\t// Prepare resources allocated by the Dynammic Resource Allocation feature for the pod\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.DynamicResourceAllocation) {\n\t\t\tif m.runtimeHelper.PrepareDynamicResources(pod) != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tpodSandboxID, msg, err = m.createPodSandbox(ctx, pod, podContainerChanges.Attempt)\n\t\tif err != nil {\n\t\t\t// createPodSandbox can return an error from CNI, CSI,\n\t\t\t// or CRI if the Pod has been deleted while the POD is\n\t\t\t// being created. If the pod has been deleted then it's\n\t\t\t// not a real error.\n\t\t\t//\n\t\t\t// SyncPod can still be running when we get here, which\n\t\t\t// means the PodWorker has not acked the deletion.\n\t\t\tif m.podStateProvider.IsPodTerminationRequested(pod.UID) {\n\t\t\t\tklog.V(4).InfoS(\"Pod was deleted and sandbox failed to be created\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tmetrics.StartedPodsErrorsTotal.Inc()\n\t\t\tcreateSandboxResult.Fail(kubecontainer.ErrCreatePodSandbox, msg)\n\t\t\tklog.ErrorS(err, \"CreatePodSandbox for pod failed\", \"pod\", klog.KObj(pod))\n\t\t\tref, referr := ref.GetReference(legacyscheme.Scheme, pod)\n\t\t\tif referr != nil {\n\t\t\t\tklog.ErrorS(referr, \"Couldn't make a ref to pod\", \"pod\", klog.KObj(pod))\n\t\t\t}\n\t\t\tm.recorder.Eventf(ref, v1.EventTypeWarning, events.FailedCreatePodSandBox, \"Failed to create pod sandbox: %v\", err)\n\t\t\treturn\n\t\t}\n\t\tklog.V(4).InfoS(\"Created PodSandbox for pod\", \"podSandboxID\", podSandboxID, \"pod\", klog.KObj(pod))\n\n\t\tresp, err := m.runtimeService.PodSandboxStatus(ctx, podSandboxID, false)\n\t\tif err != nil {\n\t\t\tref, referr := ref.GetReference(legacyscheme.Scheme, pod)\n\t\t\tif referr != nil {\n\t\t\t\tklog.ErrorS(referr, \"Couldn't make a ref to pod\", \"pod\", klog.KObj(pod))\n\t\t\t}\n\t\t\tm.recorder.Eventf(ref, v1.EventTypeWarning, events.FailedStatusPodSandBox, \"Unable to get pod sandbox status: %v\", err)\n\t\t\tklog.ErrorS(err, \"Failed to get pod sandbox status; Skipping pod\", \"pod\", klog.KObj(pod))\n\t\t\tresult.Fail(err)\n\t\t\treturn\n\t\t}\n\t\tif resp.GetStatus() == nil {\n\t\t\tresult.Fail(errors.New(\"pod sandbox status is nil\"))\n\t\t\treturn\n\t\t}\n\n\t\t// If we ever allow updating a pod from non-host-network to\n\t\t// host-network, we may use a stale IP.\n\t\tif !kubecontainer.IsHostNetworkPod(pod) {\n\t\t\t// Overwrite the podIPs passed in the pod status, since we just started the pod sandbox.\n\t\t\tpodIPs = m.determinePodSandboxIPs(pod.Namespace, pod.Name, resp.GetStatus())\n\t\t\tklog.V(4).InfoS(\"Determined the ip for pod after sandbox changed\", \"IPs\", podIPs, \"pod\", klog.KObj(pod))\n\t\t}\n\t}\n\n\t// the start containers routines depend on pod ip(as in primary pod ip)\n\t// instead of trying to figure out if we have 0 \u003c len(podIPs)\n\t// everytime, we short circuit it here\n\tpodIP := \"\"\n\tif len(podIPs) != 0 {\n\t\tpodIP = podIPs[0]\n\t}\n\n\t// Get podSandboxConfig for containers to start.\n\tconfigPodSandboxResult := kubecontainer.NewSyncResult(kubecontainer.ConfigPodSandbox, podSandboxID)\n\tresult.AddSyncResult(configPodSandboxResult)\n\tpodSandboxConfig, err := m.generatePodSandboxConfig(pod, podContainerChanges.Attempt)\n\tif err != nil {\n\t\tmessage := fmt.Sprintf(\"GeneratePodSandboxConfig for pod %q failed: %v\", format.Pod(pod), err)\n\t\tklog.ErrorS(err, \"GeneratePodSandboxConfig for pod failed\", \"pod\", klog.KObj(pod))\n\t\tconfigPodSandboxResult.Fail(kubecontainer.ErrConfigPodSandbox, message)\n\t\treturn\n\t}\n\n\t// Helper containing boilerplate common to starting all types of containers.\n\t// typeName is a description used to describe this type of container in log messages,\n\t// currently: \"container\", \"init container\" or \"ephemeral container\"\n\t// metricLabel is the label used to describe this type of container in monitoring metrics.\n\t// currently: \"container\", \"init_container\" or \"ephemeral_container\"\n\tstart := func(ctx context.Context, typeName, metricLabel string, spec *startSpec) error {\n\t\tstartContainerResult := kubecontainer.NewSyncResult(kubecontainer.StartContainer, spec.container.Name)\n\t\tresult.AddSyncResult(startContainerResult)\n\n\t\tisInBackOff, msg, err := m.doBackOff(pod, spec.container, podStatus, backOff)\n\t\tif isInBackOff {\n\t\t\tstartContainerResult.Fail(err, msg)\n\t\t\tklog.V(4).InfoS(\"Backing Off restarting container in pod\", \"containerType\", typeName, \"container\", spec.container, \"pod\", klog.KObj(pod))\n\t\t\treturn err\n\t\t}\n\n\t\tmetrics.StartedContainersTotal.WithLabelValues(metricLabel).Inc()\n\t\tif sc.HasWindowsHostProcessRequest(pod, spec.container) {\n\t\t\tmetrics.StartedHostProcessContainersTotal.WithLabelValues(metricLabel).Inc()\n\t\t}\n\t\tklog.V(4).InfoS(\"Creating container in pod\", \"containerType\", typeName, \"container\", spec.container, \"pod\", klog.KObj(pod))\n\t\t// NOTE (aramase) podIPs are populated for single stack and dual stack clusters. Send only podIPs.\n\t\tif msg, err := m.startContainer(ctx, podSandboxID, podSandboxConfig, spec, pod, podStatus, pullSecrets, podIP, podIPs); err != nil {\n\t\t\t// startContainer() returns well-defined error codes that have reasonable cardinality for metrics and are\n\t\t\t// useful to cluster administrators to distinguish \"server errors\" from \"user errors\".\n\t\t\tmetrics.StartedContainersErrorsTotal.WithLabelValues(metricLabel, err.Error()).Inc()\n\t\t\tif sc.HasWindowsHostProcessRequest(pod, spec.container) {\n\t\t\t\tmetrics.StartedHostProcessContainersErrorsTotal.WithLabelValues(metricLabel, err.Error()).Inc()\n\t\t\t}\n\t\t\tstartContainerResult.Fail(err, msg)\n\t\t\t// known errors that are logged in other places are logged at higher levels here to avoid\n\t\t\t// repetitive log spam\n\t\t\tswitch {\n\t\t\tcase err == images.ErrImagePullBackOff:\n\t\t\t\tklog.V(3).InfoS(\"Container start failed in pod\", \"containerType\", typeName, \"container\", spec.container, \"pod\", klog.KObj(pod), \"containerMessage\", msg, \"err\", err)\n\t\t\tdefault:\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"%v %+v start failed in pod %v: %v: %s\", typeName, spec.container, format.Pod(pod), err, msg))\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\n\t// Step 5: start ephemeral containers\n\t// These are started \"prior\" to init containers to allow running ephemeral containers even when there\n\t// are errors starting an init container. In practice init containers will start first since ephemeral\n\t// containers cannot be specified on pod creation.\n\tfor _, idx := range podContainerChanges.EphemeralContainersToStart {\n\t\tstart(ctx, \"ephemeral container\", metrics.EphemeralContainer, ephemeralContainerStartSpec(\u0026pod.Spec.EphemeralContainers[idx]))\n\t}\n\n\t// Step 6: start the init container.\n\tif container := podContainerChanges.NextInitContainerToStart; container != nil {\n\t\t// Start the next init container.\n\t\tif err := start(ctx, \"init container\", metrics.InitContainer, containerStartSpec(container)); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\t// Successfully started the container; clear the entry in the failure\n\t\tklog.V(4).InfoS(\"Completed init container for pod\", \"containerName\", container.Name, \"pod\", klog.KObj(pod))\n\t}\n\n\t// Step 7: For containers in podContainerChanges.ContainersToUpdate[CPU,Memory] list, invoke UpdateContainerResources\n\tif isInPlacePodVerticalScalingAllowed(pod) {\n\t\tif len(podContainerChanges.ContainersToUpdate) \u003e 0 || podContainerChanges.UpdatePodResources {\n\t\t\tm.doPodResizeAction(pod, podStatus, podContainerChanges, result)\n\t\t}\n\t}\n\n\t// Step 8: start containers in podContainerChanges.ContainersToStart.\n\tfor _, idx := range podContainerChanges.ContainersToStart {\n\t\tstart(ctx, \"container\", metrics.Container, containerStartSpec(\u0026pod.Spec.Containers[idx]))\n\t}\n\n\treturn\n}","line":{"from":1001,"to":1252}} {"id":100007048,"name":"doBackOff","signature":"func (m *kubeGenericRuntimeManager) doBackOff(pod *v1.Pod, container *v1.Container, podStatus *kubecontainer.PodStatus, backOff *flowcontrol.Backoff) (bool, string, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"// If a container is still in backoff, the function will return a brief backoff error and\n// a detailed error message.\nfunc (m *kubeGenericRuntimeManager) doBackOff(pod *v1.Pod, container *v1.Container, podStatus *kubecontainer.PodStatus, backOff *flowcontrol.Backoff) (bool, string, error) {\n\tvar cStatus *kubecontainer.Status\n\tfor _, c := range podStatus.ContainerStatuses {\n\t\tif c.Name == container.Name \u0026\u0026 c.State == kubecontainer.ContainerStateExited {\n\t\t\tcStatus = c\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif cStatus == nil {\n\t\treturn false, \"\", nil\n\t}\n\n\tklog.V(3).InfoS(\"Checking backoff for container in pod\", \"containerName\", container.Name, \"pod\", klog.KObj(pod))\n\t// Use the finished time of the latest exited container as the start point to calculate whether to do back-off.\n\tts := cStatus.FinishedAt\n\t// backOff requires a unique key to identify the container.\n\tkey := getStableKey(pod, container)\n\tif backOff.IsInBackOffSince(key, ts) {\n\t\tif containerRef, err := kubecontainer.GenerateContainerRef(pod, container); err == nil {\n\t\t\tm.recorder.Eventf(containerRef, v1.EventTypeWarning, events.BackOffStartContainer,\n\t\t\t\tfmt.Sprintf(\"Back-off restarting failed container %s in pod %s\", container.Name, format.Pod(pod)))\n\t\t}\n\t\terr := fmt.Errorf(\"back-off %s restarting failed container=%s pod=%s\", backOff.Get(key), container.Name, format.Pod(pod))\n\t\tklog.V(3).InfoS(\"Back-off restarting failed container\", \"err\", err.Error())\n\t\treturn true, err.Error(), kubecontainer.ErrCrashLoopBackOff\n\t}\n\n\tbackOff.Next(key, ts)\n\treturn false, \"\", nil\n}","line":{"from":1254,"to":1286}} {"id":100007049,"name":"KillPod","signature":"func (m *kubeGenericRuntimeManager) KillPod(ctx context.Context, pod *v1.Pod, runningPod kubecontainer.Pod, gracePeriodOverride *int64) error","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"// KillPod kills all the containers of a pod. Pod may be nil, running pod must not be.\n// gracePeriodOverride if specified allows the caller to override the pod default grace period.\n// only hard kill paths are allowed to specify a gracePeriodOverride in the kubelet in order to not corrupt user data.\n// it is useful when doing SIGKILL for hard eviction scenarios, or max grace period during soft eviction scenarios.\nfunc (m *kubeGenericRuntimeManager) KillPod(ctx context.Context, pod *v1.Pod, runningPod kubecontainer.Pod, gracePeriodOverride *int64) error {\n\terr := m.killPodWithSyncResult(ctx, pod, runningPod, gracePeriodOverride)\n\treturn err.Error()\n}","line":{"from":1288,"to":1295}} {"id":100007050,"name":"killPodWithSyncResult","signature":"func (m *kubeGenericRuntimeManager) killPodWithSyncResult(ctx context.Context, pod *v1.Pod, runningPod kubecontainer.Pod, gracePeriodOverride *int64) (result kubecontainer.PodSyncResult)","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"// killPodWithSyncResult kills a runningPod and returns SyncResult.\n// Note: The pod passed in could be *nil* when kubelet restarted.\nfunc (m *kubeGenericRuntimeManager) killPodWithSyncResult(ctx context.Context, pod *v1.Pod, runningPod kubecontainer.Pod, gracePeriodOverride *int64) (result kubecontainer.PodSyncResult) {\n\tkillContainerResults := m.killContainersWithSyncResult(ctx, pod, runningPod, gracePeriodOverride)\n\tfor _, containerResult := range killContainerResults {\n\t\tresult.AddSyncResult(containerResult)\n\t}\n\n\t// stop sandbox, the sandbox will be removed in GarbageCollect\n\tkillSandboxResult := kubecontainer.NewSyncResult(kubecontainer.KillPodSandbox, runningPod.ID)\n\tresult.AddSyncResult(killSandboxResult)\n\t// Stop all sandboxes belongs to same pod\n\tfor _, podSandbox := range runningPod.Sandboxes {\n\t\tif err := m.runtimeService.StopPodSandbox(ctx, podSandbox.ID.ID); err != nil \u0026\u0026 !crierror.IsNotFound(err) {\n\t\t\tkillSandboxResult.Fail(kubecontainer.ErrKillPodSandbox, err.Error())\n\t\t\tklog.ErrorS(nil, \"Failed to stop sandbox\", \"podSandboxID\", podSandbox.ID)\n\t\t}\n\t}\n\n\treturn\n}","line":{"from":1297,"to":1317}} {"id":100007051,"name":"GeneratePodStatus","signature":"func (m *kubeGenericRuntimeManager) GeneratePodStatus(event *runtimeapi.ContainerEventResponse) (*kubecontainer.PodStatus, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"func (m *kubeGenericRuntimeManager) GeneratePodStatus(event *runtimeapi.ContainerEventResponse) (*kubecontainer.PodStatus, error) {\n\tpodIPs := m.determinePodSandboxIPs(event.PodSandboxStatus.Metadata.Namespace, event.PodSandboxStatus.Metadata.Name, event.PodSandboxStatus)\n\n\tkubeContainerStatuses := []*kubecontainer.Status{}\n\tfor _, status := range event.ContainersStatuses {\n\t\tkubeContainerStatuses = append(kubeContainerStatuses, m.convertToKubeContainerStatus(status))\n\t}\n\n\tsort.Sort(containerStatusByCreated(kubeContainerStatuses))\n\n\treturn \u0026kubecontainer.PodStatus{\n\t\tID: kubetypes.UID(event.PodSandboxStatus.Metadata.Uid),\n\t\tName: event.PodSandboxStatus.Metadata.Name,\n\t\tNamespace: event.PodSandboxStatus.Metadata.Namespace,\n\t\tIPs: podIPs,\n\t\tSandboxStatuses: []*runtimeapi.PodSandboxStatus{event.PodSandboxStatus},\n\t\tContainerStatuses: kubeContainerStatuses,\n\t}, nil\n}","line":{"from":1319,"to":1337}} {"id":100007052,"name":"GetPodStatus","signature":"func (m *kubeGenericRuntimeManager) GetPodStatus(ctx context.Context, uid kubetypes.UID, name, namespace string) (*kubecontainer.PodStatus, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"// GetPodStatus retrieves the status of the pod, including the\n// information of all containers in the pod that are visible in Runtime.\nfunc (m *kubeGenericRuntimeManager) GetPodStatus(ctx context.Context, uid kubetypes.UID, name, namespace string) (*kubecontainer.PodStatus, error) {\n\t// Now we retain restart count of container as a container label. Each time a container\n\t// restarts, pod will read the restart count from the registered dead container, increment\n\t// it to get the new restart count, and then add a label with the new restart count on\n\t// the newly started container.\n\t// However, there are some limitations of this method:\n\t//\t1. When all dead containers were garbage collected, the container status could\n\t//\tnot get the historical value and would be *inaccurate*. Fortunately, the chance\n\t//\tis really slim.\n\t//\t2. When working with old version containers which have no restart count label,\n\t//\twe can only assume their restart count is 0.\n\t// Anyhow, we only promised \"best-effort\" restart count reporting, we can just ignore\n\t// these limitations now.\n\t// TODO: move this comment to SyncPod.\n\tpodSandboxIDs, err := m.getSandboxIDByPodUID(ctx, uid, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpod := \u0026v1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tUID: uid,\n\t\t},\n\t}\n\n\tpodFullName := format.Pod(pod)\n\n\tklog.V(4).InfoS(\"getSandboxIDByPodUID got sandbox IDs for pod\", \"podSandboxID\", podSandboxIDs, \"pod\", klog.KObj(pod))\n\n\tsandboxStatuses := []*runtimeapi.PodSandboxStatus{}\n\tcontainerStatuses := []*kubecontainer.Status{}\n\tvar timestamp time.Time\n\n\tpodIPs := []string{}\n\tfor idx, podSandboxID := range podSandboxIDs {\n\t\tresp, err := m.runtimeService.PodSandboxStatus(ctx, podSandboxID, false)\n\t\t// Between List (getSandboxIDByPodUID) and check (PodSandboxStatus) another thread might remove a container, and that is normal.\n\t\t// The previous call (getSandboxIDByPodUID) never fails due to a pod sandbox not existing.\n\t\t// Therefore, this method should not either, but instead act as if the previous call failed,\n\t\t// which means the error should be ignored.\n\t\tif crierror.IsNotFound(err) {\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"PodSandboxStatus of sandbox for pod\", \"podSandboxID\", podSandboxID, \"pod\", klog.KObj(pod))\n\t\t\treturn nil, err\n\t\t}\n\t\tif resp.GetStatus() == nil {\n\t\t\treturn nil, errors.New(\"pod sandbox status is nil\")\n\n\t\t}\n\t\tsandboxStatuses = append(sandboxStatuses, resp.Status)\n\t\t// Only get pod IP from latest sandbox\n\t\tif idx == 0 \u0026\u0026 resp.Status.State == runtimeapi.PodSandboxState_SANDBOX_READY {\n\t\t\tpodIPs = m.determinePodSandboxIPs(namespace, name, resp.Status)\n\t\t}\n\n\t\tif idx == 0 \u0026\u0026 utilfeature.DefaultFeatureGate.Enabled(features.EventedPLEG) {\n\t\t\tif resp.Timestamp == 0 {\n\t\t\t\t// If the Evented PLEG is enabled in the kubelet, but not in the runtime\n\t\t\t\t// then the pod status we get will not have the timestamp set.\n\t\t\t\t// e.g. CI job 'pull-kubernetes-e2e-gce-alpha-features' will runs with\n\t\t\t\t// features gate enabled, which includes Evented PLEG, but uses the\n\t\t\t\t// runtime without Evented PLEG support.\n\t\t\t\tklog.V(4).InfoS(\"Runtime does not set pod status timestamp\", \"pod\", klog.KObj(pod))\n\t\t\t\tcontainerStatuses, err = m.getPodContainerStatuses(ctx, uid, name, namespace)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif m.logReduction.ShouldMessageBePrinted(err.Error(), podFullName) {\n\t\t\t\t\t\tklog.ErrorS(err, \"getPodContainerStatuses for pod failed\", \"pod\", klog.KObj(pod))\n\t\t\t\t\t}\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Get the statuses of all containers visible to the pod and\n\t\t\t\t// timestamp from sandboxStatus.\n\t\t\t\ttimestamp = time.Unix(resp.Timestamp, 0)\n\t\t\t\tfor _, cs := range resp.ContainersStatuses {\n\t\t\t\t\tcStatus := m.convertToKubeContainerStatus(cs)\n\t\t\t\t\tcontainerStatuses = append(containerStatuses, cStatus)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.EventedPLEG) {\n\t\t// Get statuses of all containers visible in the pod.\n\t\tcontainerStatuses, err = m.getPodContainerStatuses(ctx, uid, name, namespace)\n\t\tif err != nil {\n\t\t\tif m.logReduction.ShouldMessageBePrinted(err.Error(), podFullName) {\n\t\t\t\tklog.ErrorS(err, \"getPodContainerStatuses for pod failed\", \"pod\", klog.KObj(pod))\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tm.logReduction.ClearID(podFullName)\n\treturn \u0026kubecontainer.PodStatus{\n\t\tID: uid,\n\t\tName: name,\n\t\tNamespace: namespace,\n\t\tIPs: podIPs,\n\t\tSandboxStatuses: sandboxStatuses,\n\t\tContainerStatuses: containerStatuses,\n\t\tTimeStamp: timestamp,\n\t}, nil\n}","line":{"from":1339,"to":1448}} {"id":100007053,"name":"GarbageCollect","signature":"func (m *kubeGenericRuntimeManager) GarbageCollect(ctx context.Context, gcPolicy kubecontainer.GCPolicy, allSourcesReady bool, evictNonDeletedPods bool) error","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"// GarbageCollect removes dead containers using the specified container gc policy.\nfunc (m *kubeGenericRuntimeManager) GarbageCollect(ctx context.Context, gcPolicy kubecontainer.GCPolicy, allSourcesReady bool, evictNonDeletedPods bool) error {\n\treturn m.containerGC.GarbageCollect(ctx, gcPolicy, allSourcesReady, evictNonDeletedPods)\n}","line":{"from":1450,"to":1453}} {"id":100007054,"name":"UpdatePodCIDR","signature":"func (m *kubeGenericRuntimeManager) UpdatePodCIDR(ctx context.Context, podCIDR string) error","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"// UpdatePodCIDR is just a passthrough method to update the runtimeConfig of the shim\n// with the podCIDR supplied by the kubelet.\nfunc (m *kubeGenericRuntimeManager) UpdatePodCIDR(ctx context.Context, podCIDR string) error {\n\t// TODO(#35531): do we really want to write a method on this manager for each\n\t// field of the config?\n\tklog.InfoS(\"Updating runtime config through cri with podcidr\", \"CIDR\", podCIDR)\n\treturn m.runtimeService.UpdateRuntimeConfig(ctx,\n\t\t\u0026runtimeapi.RuntimeConfig{\n\t\t\tNetworkConfig: \u0026runtimeapi.NetworkConfig{\n\t\t\t\tPodCidr: podCIDR,\n\t\t\t},\n\t\t})\n}","line":{"from":1455,"to":1467}} {"id":100007055,"name":"CheckpointContainer","signature":"func (m *kubeGenericRuntimeManager) CheckpointContainer(ctx context.Context, options *runtimeapi.CheckpointContainerRequest) error","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"func (m *kubeGenericRuntimeManager) CheckpointContainer(ctx context.Context, options *runtimeapi.CheckpointContainerRequest) error {\n\treturn m.runtimeService.CheckpointContainer(ctx, options)\n}","line":{"from":1469,"to":1471}} {"id":100007056,"name":"ListMetricDescriptors","signature":"func (m *kubeGenericRuntimeManager) ListMetricDescriptors(ctx context.Context) ([]*runtimeapi.MetricDescriptor, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"func (m *kubeGenericRuntimeManager) ListMetricDescriptors(ctx context.Context) ([]*runtimeapi.MetricDescriptor, error) {\n\treturn m.runtimeService.ListMetricDescriptors(ctx)\n}","line":{"from":1473,"to":1475}} {"id":100007057,"name":"ListPodSandboxMetrics","signature":"func (m *kubeGenericRuntimeManager) ListPodSandboxMetrics(ctx context.Context) ([]*runtimeapi.PodSandboxMetrics, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_manager.go","code":"func (m *kubeGenericRuntimeManager) ListPodSandboxMetrics(ctx context.Context) ([]*runtimeapi.PodSandboxMetrics, error) {\n\treturn m.runtimeService.ListPodSandboxMetrics(ctx)\n}","line":{"from":1477,"to":1479}} {"id":100007058,"name":"createPodSandbox","signature":"func (m *kubeGenericRuntimeManager) createPodSandbox(ctx context.Context, pod *v1.Pod, attempt uint32) (string, string, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_sandbox.go","code":"// createPodSandbox creates a pod sandbox and returns (podSandBoxID, message, error).\nfunc (m *kubeGenericRuntimeManager) createPodSandbox(ctx context.Context, pod *v1.Pod, attempt uint32) (string, string, error) {\n\tpodSandboxConfig, err := m.generatePodSandboxConfig(pod, attempt)\n\tif err != nil {\n\t\tmessage := fmt.Sprintf(\"Failed to generate sandbox config for pod %q: %v\", format.Pod(pod), err)\n\t\tklog.ErrorS(err, \"Failed to generate sandbox config for pod\", \"pod\", klog.KObj(pod))\n\t\treturn \"\", message, err\n\t}\n\n\t// Create pod logs directory\n\terr = m.osInterface.MkdirAll(podSandboxConfig.LogDirectory, 0755)\n\tif err != nil {\n\t\tmessage := fmt.Sprintf(\"Failed to create log directory for pod %q: %v\", format.Pod(pod), err)\n\t\tklog.ErrorS(err, \"Failed to create log directory for pod\", \"pod\", klog.KObj(pod))\n\t\treturn \"\", message, err\n\t}\n\n\truntimeHandler := \"\"\n\tif m.runtimeClassManager != nil {\n\t\truntimeHandler, err = m.runtimeClassManager.LookupRuntimeHandler(pod.Spec.RuntimeClassName)\n\t\tif err != nil {\n\t\t\tmessage := fmt.Sprintf(\"Failed to create sandbox for pod %q: %v\", format.Pod(pod), err)\n\t\t\treturn \"\", message, err\n\t\t}\n\t\tif runtimeHandler != \"\" {\n\t\t\tklog.V(2).InfoS(\"Running pod with runtime handler\", \"pod\", klog.KObj(pod), \"runtimeHandler\", runtimeHandler)\n\t\t}\n\t}\n\n\tpodSandBoxID, err := m.runtimeService.RunPodSandbox(ctx, podSandboxConfig, runtimeHandler)\n\tif err != nil {\n\t\tmessage := fmt.Sprintf(\"Failed to create sandbox for pod %q: %v\", format.Pod(pod), err)\n\t\tklog.ErrorS(err, \"Failed to create sandbox for pod\", \"pod\", klog.KObj(pod))\n\t\treturn \"\", message, err\n\t}\n\n\treturn podSandBoxID, \"\", nil\n}","line":{"from":40,"to":77}} {"id":100007059,"name":"generatePodSandboxConfig","signature":"func (m *kubeGenericRuntimeManager) generatePodSandboxConfig(pod *v1.Pod, attempt uint32) (*runtimeapi.PodSandboxConfig, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_sandbox.go","code":"// generatePodSandboxConfig generates pod sandbox config from v1.Pod.\nfunc (m *kubeGenericRuntimeManager) generatePodSandboxConfig(pod *v1.Pod, attempt uint32) (*runtimeapi.PodSandboxConfig, error) {\n\t// TODO: deprecating podsandbox resource requirements in favor of the pod level cgroup\n\t// Refer https://github.com/kubernetes/kubernetes/issues/29871\n\tpodUID := string(pod.UID)\n\tpodSandboxConfig := \u0026runtimeapi.PodSandboxConfig{\n\t\tMetadata: \u0026runtimeapi.PodSandboxMetadata{\n\t\t\tName: pod.Name,\n\t\t\tNamespace: pod.Namespace,\n\t\t\tUid: podUID,\n\t\t\tAttempt: attempt,\n\t\t},\n\t\tLabels: newPodLabels(pod),\n\t\tAnnotations: newPodAnnotations(pod),\n\t}\n\n\tdnsConfig, err := m.runtimeHelper.GetPodDNS(pod)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpodSandboxConfig.DnsConfig = dnsConfig\n\n\tif !kubecontainer.IsHostNetworkPod(pod) {\n\t\t// TODO: Add domain support in new runtime interface\n\t\tpodHostname, podDomain, err := m.runtimeHelper.GeneratePodHostNameAndDomain(pod)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpodHostname, err = util.GetNodenameForKernel(podHostname, podDomain, pod.Spec.SetHostnameAsFQDN)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpodSandboxConfig.Hostname = podHostname\n\t}\n\n\tlogDir := BuildPodLogsDirectory(pod.Namespace, pod.Name, pod.UID)\n\tpodSandboxConfig.LogDirectory = logDir\n\n\tportMappings := []*runtimeapi.PortMapping{}\n\tfor _, c := range pod.Spec.Containers {\n\t\tcontainerPortMappings := kubecontainer.MakePortMappings(\u0026c)\n\n\t\tfor idx := range containerPortMappings {\n\t\t\tport := containerPortMappings[idx]\n\t\t\thostPort := int32(port.HostPort)\n\t\t\tcontainerPort := int32(port.ContainerPort)\n\t\t\tprotocol := toRuntimeProtocol(port.Protocol)\n\t\t\tportMappings = append(portMappings, \u0026runtimeapi.PortMapping{\n\t\t\t\tHostIp: port.HostIP,\n\t\t\t\tHostPort: hostPort,\n\t\t\t\tContainerPort: containerPort,\n\t\t\t\tProtocol: protocol,\n\t\t\t})\n\t\t}\n\n\t}\n\tif len(portMappings) \u003e 0 {\n\t\tpodSandboxConfig.PortMappings = portMappings\n\t}\n\n\tlc, err := m.generatePodSandboxLinuxConfig(pod)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpodSandboxConfig.Linux = lc\n\n\tif runtime.GOOS == \"windows\" {\n\t\twc, err := m.generatePodSandboxWindowsConfig(pod)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpodSandboxConfig.Windows = wc\n\t}\n\n\t// Update config to include overhead, sandbox level resources\n\tif err := m.applySandboxResources(pod, podSandboxConfig); err != nil {\n\t\treturn nil, err\n\t}\n\treturn podSandboxConfig, nil\n}","line":{"from":79,"to":158}} {"id":100007060,"name":"generatePodSandboxLinuxConfig","signature":"func (m *kubeGenericRuntimeManager) generatePodSandboxLinuxConfig(pod *v1.Pod) (*runtimeapi.LinuxPodSandboxConfig, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_sandbox.go","code":"// generatePodSandboxLinuxConfig generates LinuxPodSandboxConfig from v1.Pod.\n// We've to call PodSandboxLinuxConfig always irrespective of the underlying OS as securityContext is not part of\n// podSandboxConfig. It is currently part of LinuxPodSandboxConfig. In future, if we have securityContext pulled out\n// in podSandboxConfig we should be able to use it.\nfunc (m *kubeGenericRuntimeManager) generatePodSandboxLinuxConfig(pod *v1.Pod) (*runtimeapi.LinuxPodSandboxConfig, error) {\n\tcgroupParent := m.runtimeHelper.GetPodCgroupParent(pod)\n\tlc := \u0026runtimeapi.LinuxPodSandboxConfig{\n\t\tCgroupParent: cgroupParent,\n\t\tSecurityContext: \u0026runtimeapi.LinuxSandboxSecurityContext{\n\t\t\tPrivileged: kubecontainer.HasPrivilegedContainer(pod),\n\n\t\t\t// Forcing sandbox to run as `runtime/default` allow users to\n\t\t\t// use least privileged seccomp profiles at pod level. Issue #84623\n\t\t\tSeccomp: \u0026runtimeapi.SecurityProfile{\n\t\t\t\tProfileType: runtimeapi.SecurityProfile_RuntimeDefault,\n\t\t\t},\n\t\t},\n\t}\n\n\tsysctls := make(map[string]string)\n\tif pod.Spec.SecurityContext != nil {\n\t\tfor _, c := range pod.Spec.SecurityContext.Sysctls {\n\t\t\tsysctls[c.Name] = c.Value\n\t\t}\n\t}\n\n\tlc.Sysctls = sysctls\n\n\tif pod.Spec.SecurityContext != nil {\n\t\tsc := pod.Spec.SecurityContext\n\t\tif sc.RunAsUser != nil \u0026\u0026 runtime.GOOS != \"windows\" {\n\t\t\tlc.SecurityContext.RunAsUser = \u0026runtimeapi.Int64Value{Value: int64(*sc.RunAsUser)}\n\t\t}\n\t\tif sc.RunAsGroup != nil \u0026\u0026 runtime.GOOS != \"windows\" {\n\t\t\tlc.SecurityContext.RunAsGroup = \u0026runtimeapi.Int64Value{Value: int64(*sc.RunAsGroup)}\n\t\t}\n\t\tnamespaceOptions, err := runtimeutil.NamespacesForPod(pod, m.runtimeHelper)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlc.SecurityContext.NamespaceOptions = namespaceOptions\n\n\t\tif sc.FSGroup != nil \u0026\u0026 runtime.GOOS != \"windows\" {\n\t\t\tlc.SecurityContext.SupplementalGroups = append(lc.SecurityContext.SupplementalGroups, int64(*sc.FSGroup))\n\t\t}\n\t\tif groups := m.runtimeHelper.GetExtraSupplementalGroupsForPod(pod); len(groups) \u003e 0 {\n\t\t\tlc.SecurityContext.SupplementalGroups = append(lc.SecurityContext.SupplementalGroups, groups...)\n\t\t}\n\t\tif sc.SupplementalGroups != nil {\n\t\t\tfor _, sg := range sc.SupplementalGroups {\n\t\t\t\tlc.SecurityContext.SupplementalGroups = append(lc.SecurityContext.SupplementalGroups, int64(sg))\n\t\t\t}\n\t\t}\n\t\tif sc.SELinuxOptions != nil \u0026\u0026 runtime.GOOS != \"windows\" {\n\t\t\tlc.SecurityContext.SelinuxOptions = \u0026runtimeapi.SELinuxOption{\n\t\t\t\tUser: sc.SELinuxOptions.User,\n\t\t\t\tRole: sc.SELinuxOptions.Role,\n\t\t\t\tType: sc.SELinuxOptions.Type,\n\t\t\t\tLevel: sc.SELinuxOptions.Level,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn lc, nil\n}","line":{"from":160,"to":224}} {"id":100007061,"name":"generatePodSandboxWindowsConfig","signature":"func (m *kubeGenericRuntimeManager) generatePodSandboxWindowsConfig(pod *v1.Pod) (*runtimeapi.WindowsPodSandboxConfig, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_sandbox.go","code":"// generatePodSandboxWindowsConfig generates WindowsPodSandboxConfig from v1.Pod.\n// On Windows this will get called in addition to LinuxPodSandboxConfig because not all relevant fields have been added to\n// WindowsPodSandboxConfig at this time.\nfunc (m *kubeGenericRuntimeManager) generatePodSandboxWindowsConfig(pod *v1.Pod) (*runtimeapi.WindowsPodSandboxConfig, error) {\n\twc := \u0026runtimeapi.WindowsPodSandboxConfig{\n\t\tSecurityContext: \u0026runtimeapi.WindowsSandboxSecurityContext{},\n\t}\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.WindowsHostNetwork) {\n\t\twc.SecurityContext.NamespaceOptions = \u0026runtimeapi.WindowsNamespaceOption{}\n\t\tif kubecontainer.IsHostNetworkPod(pod) {\n\t\t\twc.SecurityContext.NamespaceOptions.Network = runtimeapi.NamespaceMode_NODE\n\t\t} else {\n\t\t\twc.SecurityContext.NamespaceOptions.Network = runtimeapi.NamespaceMode_POD\n\t\t}\n\t}\n\n\t// If all of the containers in a pod are HostProcess containers, set the pod's HostProcess field\n\t// explicitly because the container runtime requires this information at sandbox creation time.\n\tif kubecontainer.HasWindowsHostProcessContainer(pod) {\n\t\t// At present Windows all containers in a Windows pod must be HostProcess containers\n\t\t// and HostNetwork is required to be set.\n\t\tif !kubecontainer.AllContainersAreWindowsHostProcess(pod) {\n\t\t\treturn nil, fmt.Errorf(\"pod must not contain both HostProcess and non-HostProcess containers\")\n\t\t}\n\n\t\tif !kubecontainer.IsHostNetworkPod(pod) {\n\t\t\treturn nil, fmt.Errorf(\"hostNetwork is required if Pod contains HostProcess containers\")\n\t\t}\n\n\t\twc.SecurityContext.HostProcess = true\n\t}\n\n\tsc := pod.Spec.SecurityContext\n\tif sc == nil || sc.WindowsOptions == nil {\n\t\treturn wc, nil\n\t}\n\n\two := sc.WindowsOptions\n\tif wo.GMSACredentialSpec != nil {\n\t\twc.SecurityContext.CredentialSpec = *wo.GMSACredentialSpec\n\t}\n\n\tif wo.RunAsUserName != nil {\n\t\twc.SecurityContext.RunAsUsername = *wo.RunAsUserName\n\t}\n\n\tif kubecontainer.HasWindowsHostProcessContainer(pod) {\n\n\t\tif wo.HostProcess != nil \u0026\u0026 !*wo.HostProcess {\n\t\t\treturn nil, fmt.Errorf(\"pod must not contain any HostProcess containers if Pod's WindowsOptions.HostProcess is set to false\")\n\t\t}\n\t}\n\n\treturn wc, nil\n}","line":{"from":226,"to":281}} {"id":100007062,"name":"getKubeletSandboxes","signature":"func (m *kubeGenericRuntimeManager) getKubeletSandboxes(ctx context.Context, all bool) ([]*runtimeapi.PodSandbox, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_sandbox.go","code":"// getKubeletSandboxes lists all (or just the running) sandboxes managed by kubelet.\nfunc (m *kubeGenericRuntimeManager) getKubeletSandboxes(ctx context.Context, all bool) ([]*runtimeapi.PodSandbox, error) {\n\tvar filter *runtimeapi.PodSandboxFilter\n\tif !all {\n\t\treadyState := runtimeapi.PodSandboxState_SANDBOX_READY\n\t\tfilter = \u0026runtimeapi.PodSandboxFilter{\n\t\t\tState: \u0026runtimeapi.PodSandboxStateValue{\n\t\t\t\tState: readyState,\n\t\t\t},\n\t\t}\n\t}\n\n\tresp, err := m.runtimeService.ListPodSandbox(ctx, filter)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to list pod sandboxes\")\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}","line":{"from":283,"to":302}} {"id":100007063,"name":"determinePodSandboxIPs","signature":"func (m *kubeGenericRuntimeManager) determinePodSandboxIPs(podNamespace, podName string, podSandbox *runtimeapi.PodSandboxStatus) []string","file":"pkg/kubelet/kuberuntime/kuberuntime_sandbox.go","code":"// determinePodSandboxIP determines the IP addresses of the given pod sandbox.\nfunc (m *kubeGenericRuntimeManager) determinePodSandboxIPs(podNamespace, podName string, podSandbox *runtimeapi.PodSandboxStatus) []string {\n\tpodIPs := make([]string, 0)\n\tif podSandbox.Network == nil {\n\t\tklog.InfoS(\"Pod Sandbox status doesn't have network information, cannot report IPs\", \"pod\", klog.KRef(podNamespace, podName))\n\t\treturn podIPs\n\t}\n\n\t// ip could be an empty string if runtime is not responsible for the\n\t// IP (e.g., host networking).\n\n\t// pick primary IP\n\tif len(podSandbox.Network.Ip) != 0 {\n\t\tif netutils.ParseIPSloppy(podSandbox.Network.Ip) == nil {\n\t\t\tklog.InfoS(\"Pod Sandbox reported an unparseable primary IP\", \"pod\", klog.KRef(podNamespace, podName), \"IP\", podSandbox.Network.Ip)\n\t\t\treturn nil\n\t\t}\n\t\tpodIPs = append(podIPs, podSandbox.Network.Ip)\n\t}\n\n\t// pick additional ips, if cri reported them\n\tfor _, podIP := range podSandbox.Network.AdditionalIps {\n\t\tif nil == netutils.ParseIPSloppy(podIP.Ip) {\n\t\t\tklog.InfoS(\"Pod Sandbox reported an unparseable additional IP\", \"pod\", klog.KRef(podNamespace, podName), \"IP\", podIP.Ip)\n\t\t\treturn nil\n\t\t}\n\t\tpodIPs = append(podIPs, podIP.Ip)\n\t}\n\n\treturn podIPs\n}","line":{"from":304,"to":334}} {"id":100007064,"name":"getSandboxIDByPodUID","signature":"func (m *kubeGenericRuntimeManager) getSandboxIDByPodUID(ctx context.Context, podUID kubetypes.UID, state *runtimeapi.PodSandboxState) ([]string, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_sandbox.go","code":"// getPodSandboxID gets the sandbox id by podUID and returns ([]sandboxID, error).\n// Param state could be nil in order to get all sandboxes belonging to same pod.\nfunc (m *kubeGenericRuntimeManager) getSandboxIDByPodUID(ctx context.Context, podUID kubetypes.UID, state *runtimeapi.PodSandboxState) ([]string, error) {\n\tfilter := \u0026runtimeapi.PodSandboxFilter{\n\t\tLabelSelector: map[string]string{types.KubernetesPodUIDLabel: string(podUID)},\n\t}\n\tif state != nil {\n\t\tfilter.State = \u0026runtimeapi.PodSandboxStateValue{\n\t\t\tState: *state,\n\t\t}\n\t}\n\tsandboxes, err := m.runtimeService.ListPodSandbox(ctx, filter)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to list sandboxes for pod\", \"podUID\", podUID)\n\t\treturn nil, err\n\t}\n\n\tif len(sandboxes) == 0 {\n\t\treturn nil, nil\n\t}\n\n\t// Sort with newest first.\n\tsandboxIDs := make([]string, len(sandboxes))\n\tsort.Sort(podSandboxByCreated(sandboxes))\n\tfor i, s := range sandboxes {\n\t\tsandboxIDs[i] = s.Id\n\t}\n\n\treturn sandboxIDs, nil\n}","line":{"from":336,"to":365}} {"id":100007065,"name":"GetPortForward","signature":"func (m *kubeGenericRuntimeManager) GetPortForward(ctx context.Context, podName, podNamespace string, podUID kubetypes.UID, ports []int32) (*url.URL, error)","file":"pkg/kubelet/kuberuntime/kuberuntime_sandbox.go","code":"// GetPortForward gets the endpoint the runtime will serve the port-forward request from.\nfunc (m *kubeGenericRuntimeManager) GetPortForward(ctx context.Context, podName, podNamespace string, podUID kubetypes.UID, ports []int32) (*url.URL, error) {\n\tsandboxIDs, err := m.getSandboxIDByPodUID(ctx, podUID, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to find sandboxID for pod %s: %v\", format.PodDesc(podName, podNamespace, podUID), err)\n\t}\n\tif len(sandboxIDs) == 0 {\n\t\treturn nil, fmt.Errorf(\"failed to find sandboxID for pod %s\", format.PodDesc(podName, podNamespace, podUID))\n\t}\n\treq := \u0026runtimeapi.PortForwardRequest{\n\t\tPodSandboxId: sandboxIDs[0],\n\t\tPort: ports,\n\t}\n\tresp, err := m.runtimeService.PortForward(ctx, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn url.Parse(resp.Url)\n}","line":{"from":367,"to":385}} {"id":100007066,"name":"convertOverheadToLinuxResources","signature":"func (m *kubeGenericRuntimeManager) convertOverheadToLinuxResources(pod *v1.Pod) *runtimeapi.LinuxContainerResources","file":"pkg/kubelet/kuberuntime/kuberuntime_sandbox_linux.go","code":"func (m *kubeGenericRuntimeManager) convertOverheadToLinuxResources(pod *v1.Pod) *runtimeapi.LinuxContainerResources {\n\tresources := \u0026runtimeapi.LinuxContainerResources{}\n\tif pod.Spec.Overhead != nil {\n\t\tcpu := pod.Spec.Overhead.Cpu()\n\t\tmemory := pod.Spec.Overhead.Memory()\n\n\t\t// For overhead, we do not differentiate between requests and limits. Treat this overhead\n\t\t// as \"guaranteed\", with requests == limits\n\t\tresources = m.calculateLinuxResources(cpu, cpu, memory)\n\t}\n\n\treturn resources\n}","line":{"from":30,"to":42}} {"id":100007067,"name":"calculateSandboxResources","signature":"func (m *kubeGenericRuntimeManager) calculateSandboxResources(pod *v1.Pod) *runtimeapi.LinuxContainerResources","file":"pkg/kubelet/kuberuntime/kuberuntime_sandbox_linux.go","code":"func (m *kubeGenericRuntimeManager) calculateSandboxResources(pod *v1.Pod) *runtimeapi.LinuxContainerResources {\n\topts := resourcehelper.PodResourcesOptions{\n\t\tExcludeOverhead: true,\n\t}\n\treq := resourcehelper.PodRequests(pod, opts)\n\tlim := resourcehelper.PodLimits(pod, opts)\n\tvar cpuRequest *resource.Quantity\n\tif _, cpuRequestExists := req[v1.ResourceCPU]; cpuRequestExists {\n\t\tcpuRequest = req.Cpu()\n\t}\n\treturn m.calculateLinuxResources(cpuRequest, lim.Cpu(), lim.Memory())\n}","line":{"from":44,"to":55}} {"id":100007068,"name":"applySandboxResources","signature":"func (m *kubeGenericRuntimeManager) applySandboxResources(pod *v1.Pod, config *runtimeapi.PodSandboxConfig) error","file":"pkg/kubelet/kuberuntime/kuberuntime_sandbox_linux.go","code":"func (m *kubeGenericRuntimeManager) applySandboxResources(pod *v1.Pod, config *runtimeapi.PodSandboxConfig) error {\n\n\tif config.Linux == nil {\n\t\treturn nil\n\t}\n\tconfig.Linux.Resources = m.calculateSandboxResources(pod)\n\tconfig.Linux.Overhead = m.convertOverheadToLinuxResources(pod)\n\n\treturn nil\n}","line":{"from":57,"to":66}} {"id":100007069,"name":"applySandboxResources","signature":"func (m *kubeGenericRuntimeManager) applySandboxResources(pod *v1.Pod, config *runtimeapi.PodSandboxConfig) error","file":"pkg/kubelet/kuberuntime/kuberuntime_sandbox_unsupported.go","code":"func (m *kubeGenericRuntimeManager) applySandboxResources(pod *v1.Pod, config *runtimeapi.PodSandboxConfig) error {\n\treturn nil\n}","line":{"from":27,"to":29}} {"id":100007070,"name":"applySandboxResources","signature":"func (m *kubeGenericRuntimeManager) applySandboxResources(pod *v1.Pod, config *runtimeapi.PodSandboxConfig) error","file":"pkg/kubelet/kuberuntime/kuberuntime_sandbox_windows.go","code":"func (m *kubeGenericRuntimeManager) applySandboxResources(pod *v1.Pod, config *runtimeapi.PodSandboxConfig) error {\n\treturn nil\n}","line":{"from":27,"to":29}} {"id":100007071,"name":"newPodLabels","signature":"func newPodLabels(pod *v1.Pod) map[string]string","file":"pkg/kubelet/kuberuntime/labels.go","code":"// newPodLabels creates pod labels from v1.Pod.\nfunc newPodLabels(pod *v1.Pod) map[string]string {\n\tlabels := map[string]string{}\n\n\t// Get labels from v1.Pod\n\tfor k, v := range pod.Labels {\n\t\tlabels[k] = v\n\t}\n\n\tlabels[types.KubernetesPodNameLabel] = pod.Name\n\tlabels[types.KubernetesPodNamespaceLabel] = pod.Namespace\n\tlabels[types.KubernetesPodUIDLabel] = string(pod.UID)\n\n\treturn labels\n}","line":{"from":78,"to":92}} {"id":100007072,"name":"newPodAnnotations","signature":"func newPodAnnotations(pod *v1.Pod) map[string]string","file":"pkg/kubelet/kuberuntime/labels.go","code":"// newPodAnnotations creates pod annotations from v1.Pod.\nfunc newPodAnnotations(pod *v1.Pod) map[string]string {\n\treturn pod.Annotations\n}","line":{"from":94,"to":97}} {"id":100007073,"name":"newContainerLabels","signature":"func newContainerLabels(container *v1.Container, pod *v1.Pod) map[string]string","file":"pkg/kubelet/kuberuntime/labels.go","code":"// newContainerLabels creates container labels from v1.Container and v1.Pod.\nfunc newContainerLabels(container *v1.Container, pod *v1.Pod) map[string]string {\n\tlabels := map[string]string{}\n\tlabels[types.KubernetesPodNameLabel] = pod.Name\n\tlabels[types.KubernetesPodNamespaceLabel] = pod.Namespace\n\tlabels[types.KubernetesPodUIDLabel] = string(pod.UID)\n\tlabels[types.KubernetesContainerNameLabel] = container.Name\n\n\treturn labels\n}","line":{"from":99,"to":108}} {"id":100007074,"name":"newContainerAnnotations","signature":"func newContainerAnnotations(container *v1.Container, pod *v1.Pod, restartCount int, opts *kubecontainer.RunContainerOptions) map[string]string","file":"pkg/kubelet/kuberuntime/labels.go","code":"// newContainerAnnotations creates container annotations from v1.Container and v1.Pod.\nfunc newContainerAnnotations(container *v1.Container, pod *v1.Pod, restartCount int, opts *kubecontainer.RunContainerOptions) map[string]string {\n\tannotations := map[string]string{}\n\n\t// Kubelet always overrides device plugin annotations if they are conflicting\n\tfor _, a := range opts.Annotations {\n\t\tannotations[a.Name] = a.Value\n\t}\n\n\tannotations[containerHashLabel] = strconv.FormatUint(kubecontainer.HashContainer(container), 16)\n\tif utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) {\n\t\tannotations[containerHashWithoutResourcesLabel] = strconv.FormatUint(kubecontainer.HashContainerWithoutResources(container), 16)\n\t}\n\tannotations[containerRestartCountLabel] = strconv.Itoa(restartCount)\n\tannotations[containerTerminationMessagePathLabel] = container.TerminationMessagePath\n\tannotations[containerTerminationMessagePolicyLabel] = string(container.TerminationMessagePolicy)\n\n\tif pod.DeletionGracePeriodSeconds != nil {\n\t\tannotations[podDeletionGracePeriodLabel] = strconv.FormatInt(*pod.DeletionGracePeriodSeconds, 10)\n\t}\n\tif pod.Spec.TerminationGracePeriodSeconds != nil {\n\t\tannotations[podTerminationGracePeriodLabel] = strconv.FormatInt(*pod.Spec.TerminationGracePeriodSeconds, 10)\n\t}\n\n\tif container.Lifecycle != nil \u0026\u0026 container.Lifecycle.PreStop != nil {\n\t\t// Using json encoding so that the PreStop handler object is readable after writing as a label\n\t\trawPreStop, err := json.Marshal(container.Lifecycle.PreStop)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Unable to marshal lifecycle PreStop handler for container\", \"containerName\", container.Name, \"pod\", klog.KObj(pod))\n\t\t} else {\n\t\t\tannotations[containerPreStopHandlerLabel] = string(rawPreStop)\n\t\t}\n\t}\n\n\tif len(container.Ports) \u003e 0 {\n\t\trawContainerPorts, err := json.Marshal(container.Ports)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Unable to marshal container ports for container\", \"containerName\", container.Name, \"pod\", klog.KObj(pod))\n\t\t} else {\n\t\t\tannotations[containerPortsLabel] = string(rawContainerPorts)\n\t\t}\n\t}\n\n\treturn annotations\n}","line":{"from":110,"to":154}} {"id":100007075,"name":"getPodSandboxInfoFromLabels","signature":"func getPodSandboxInfoFromLabels(labels map[string]string) *labeledPodSandboxInfo","file":"pkg/kubelet/kuberuntime/labels.go","code":"// getPodSandboxInfoFromLabels gets labeledPodSandboxInfo from labels.\nfunc getPodSandboxInfoFromLabels(labels map[string]string) *labeledPodSandboxInfo {\n\tpodSandboxInfo := \u0026labeledPodSandboxInfo{\n\t\tLabels: make(map[string]string),\n\t\tPodName: getStringValueFromLabel(labels, types.KubernetesPodNameLabel),\n\t\tPodNamespace: getStringValueFromLabel(labels, types.KubernetesPodNamespaceLabel),\n\t\tPodUID: kubetypes.UID(getStringValueFromLabel(labels, types.KubernetesPodUIDLabel)),\n\t}\n\n\t// Remain only labels from v1.Pod\n\tfor k, v := range labels {\n\t\tif k != types.KubernetesPodNameLabel \u0026\u0026 k != types.KubernetesPodNamespaceLabel \u0026\u0026 k != types.KubernetesPodUIDLabel {\n\t\t\tpodSandboxInfo.Labels[k] = v\n\t\t}\n\t}\n\n\treturn podSandboxInfo\n}","line":{"from":156,"to":173}} {"id":100007076,"name":"getPodSandboxInfoFromAnnotations","signature":"func getPodSandboxInfoFromAnnotations(annotations map[string]string) *annotatedPodSandboxInfo","file":"pkg/kubelet/kuberuntime/labels.go","code":"// getPodSandboxInfoFromAnnotations gets annotatedPodSandboxInfo from annotations.\nfunc getPodSandboxInfoFromAnnotations(annotations map[string]string) *annotatedPodSandboxInfo {\n\treturn \u0026annotatedPodSandboxInfo{\n\t\tAnnotations: annotations,\n\t}\n}","line":{"from":175,"to":180}} {"id":100007077,"name":"getContainerInfoFromLabels","signature":"func getContainerInfoFromLabels(labels map[string]string) *labeledContainerInfo","file":"pkg/kubelet/kuberuntime/labels.go","code":"// getContainerInfoFromLabels gets labeledContainerInfo from labels.\nfunc getContainerInfoFromLabels(labels map[string]string) *labeledContainerInfo {\n\treturn \u0026labeledContainerInfo{\n\t\tPodName: getStringValueFromLabel(labels, types.KubernetesPodNameLabel),\n\t\tPodNamespace: getStringValueFromLabel(labels, types.KubernetesPodNamespaceLabel),\n\t\tPodUID: kubetypes.UID(getStringValueFromLabel(labels, types.KubernetesPodUIDLabel)),\n\t\tContainerName: getStringValueFromLabel(labels, types.KubernetesContainerNameLabel),\n\t}\n}","line":{"from":182,"to":190}} {"id":100007078,"name":"getContainerInfoFromAnnotations","signature":"func getContainerInfoFromAnnotations(annotations map[string]string) *annotatedContainerInfo","file":"pkg/kubelet/kuberuntime/labels.go","code":"// getContainerInfoFromAnnotations gets annotatedContainerInfo from annotations.\nfunc getContainerInfoFromAnnotations(annotations map[string]string) *annotatedContainerInfo {\n\tvar err error\n\tcontainerInfo := \u0026annotatedContainerInfo{\n\t\tTerminationMessagePath: getStringValueFromLabel(annotations, containerTerminationMessagePathLabel),\n\t\tTerminationMessagePolicy: v1.TerminationMessagePolicy(getStringValueFromLabel(annotations, containerTerminationMessagePolicyLabel)),\n\t}\n\n\tif containerInfo.Hash, err = getUint64ValueFromLabel(annotations, containerHashLabel); err != nil {\n\t\tklog.ErrorS(err, \"Unable to get label value from annotations\", \"label\", containerHashLabel, \"annotations\", annotations)\n\t}\n\tif utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) {\n\t\tif containerInfo.HashWithoutResources, err = getUint64ValueFromLabel(annotations, containerHashWithoutResourcesLabel); err != nil {\n\t\t\tklog.ErrorS(err, \"Unable to get label value from annotations\", \"label\", containerHashWithoutResourcesLabel, \"annotations\", annotations)\n\t\t}\n\t}\n\tif containerInfo.RestartCount, err = getIntValueFromLabel(annotations, containerRestartCountLabel); err != nil {\n\t\tklog.ErrorS(err, \"Unable to get label value from annotations\", \"label\", containerRestartCountLabel, \"annotations\", annotations)\n\t}\n\tif containerInfo.PodDeletionGracePeriod, err = getInt64PointerFromLabel(annotations, podDeletionGracePeriodLabel); err != nil {\n\t\tklog.ErrorS(err, \"Unable to get label value from annotations\", \"label\", podDeletionGracePeriodLabel, \"annotations\", annotations)\n\t}\n\tif containerInfo.PodTerminationGracePeriod, err = getInt64PointerFromLabel(annotations, podTerminationGracePeriodLabel); err != nil {\n\t\tklog.ErrorS(err, \"Unable to get label value from annotations\", \"label\", podTerminationGracePeriodLabel, \"annotations\", annotations)\n\t}\n\n\tpreStopHandler := \u0026v1.LifecycleHandler{}\n\tif found, err := getJSONObjectFromLabel(annotations, containerPreStopHandlerLabel, preStopHandler); err != nil {\n\t\tklog.ErrorS(err, \"Unable to get label value from annotations\", \"label\", containerPreStopHandlerLabel, \"annotations\", annotations)\n\t} else if found {\n\t\tcontainerInfo.PreStopHandler = preStopHandler\n\t}\n\n\tcontainerPorts := []v1.ContainerPort{}\n\tif found, err := getJSONObjectFromLabel(annotations, containerPortsLabel, \u0026containerPorts); err != nil {\n\t\tklog.ErrorS(err, \"Unable to get label value from annotations\", \"label\", containerPortsLabel, \"annotations\", annotations)\n\t} else if found {\n\t\tcontainerInfo.ContainerPorts = containerPorts\n\t}\n\n\treturn containerInfo\n}","line":{"from":192,"to":233}} {"id":100007079,"name":"getStringValueFromLabel","signature":"func getStringValueFromLabel(labels map[string]string, label string) string","file":"pkg/kubelet/kuberuntime/labels.go","code":"func getStringValueFromLabel(labels map[string]string, label string) string {\n\tif value, found := labels[label]; found {\n\t\treturn value\n\t}\n\t// Do not report error, because there should be many old containers without label now.\n\tklog.V(3).InfoS(\"Container doesn't have requested label, it may be an old or invalid container\", \"label\", label)\n\t// Return empty string \"\" for these containers, the caller will get value by other ways.\n\treturn \"\"\n}","line":{"from":235,"to":243}} {"id":100007080,"name":"getIntValueFromLabel","signature":"func getIntValueFromLabel(labels map[string]string, label string) (int, error)","file":"pkg/kubelet/kuberuntime/labels.go","code":"func getIntValueFromLabel(labels map[string]string, label string) (int, error) {\n\tif strValue, found := labels[label]; found {\n\t\tintValue, err := strconv.Atoi(strValue)\n\t\tif err != nil {\n\t\t\t// This really should not happen. Just set value to 0 to handle this abnormal case\n\t\t\treturn 0, err\n\t\t}\n\t\treturn intValue, nil\n\t}\n\t// Do not report error, because there should be many old containers without label now.\n\tklog.V(3).InfoS(\"Container doesn't have requested label, it may be an old or invalid container\", \"label\", label)\n\t// Just set the value to 0\n\treturn 0, nil\n}","line":{"from":245,"to":258}} {"id":100007081,"name":"getUint64ValueFromLabel","signature":"func getUint64ValueFromLabel(labels map[string]string, label string) (uint64, error)","file":"pkg/kubelet/kuberuntime/labels.go","code":"func getUint64ValueFromLabel(labels map[string]string, label string) (uint64, error) {\n\tif strValue, found := labels[label]; found {\n\t\tintValue, err := strconv.ParseUint(strValue, 16, 64)\n\t\tif err != nil {\n\t\t\t// This really should not happen. Just set value to 0 to handle this abnormal case\n\t\t\treturn 0, err\n\t\t}\n\t\treturn intValue, nil\n\t}\n\t// Do not report error, because there should be many old containers without label now.\n\tklog.V(3).InfoS(\"Container doesn't have requested label, it may be an old or invalid container\", \"label\", label)\n\t// Just set the value to 0\n\treturn 0, nil\n}","line":{"from":260,"to":273}} {"id":100007082,"name":"getInt64PointerFromLabel","signature":"func getInt64PointerFromLabel(labels map[string]string, label string) (*int64, error)","file":"pkg/kubelet/kuberuntime/labels.go","code":"func getInt64PointerFromLabel(labels map[string]string, label string) (*int64, error) {\n\tif strValue, found := labels[label]; found {\n\t\tint64Value, err := strconv.ParseInt(strValue, 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn \u0026int64Value, nil\n\t}\n\t// If the label is not found, return pointer nil.\n\treturn nil, nil\n}","line":{"from":275,"to":285}} {"id":100007083,"name":"getJSONObjectFromLabel","signature":"func getJSONObjectFromLabel(labels map[string]string, label string, value interface{}) (bool, error)","file":"pkg/kubelet/kuberuntime/labels.go","code":"// getJSONObjectFromLabel returns a bool value indicating whether an object is found.\nfunc getJSONObjectFromLabel(labels map[string]string, label string, value interface{}) (bool, error) {\n\tif strValue, found := labels[label]; found {\n\t\terr := json.Unmarshal([]byte(strValue), value)\n\t\treturn found, err\n\t}\n\t// If the label is not found, return not found.\n\treturn false, nil\n}","line":{"from":287,"to":295}} {"id":100007084,"name":"legacyLogSymlink","signature":"func legacyLogSymlink(containerID string, containerName, podName, podNamespace string) string","file":"pkg/kubelet/kuberuntime/legacy.go","code":"// legacyLogSymlink composes the legacy container log path. It is only used for legacy cluster\n// logging support.\nfunc legacyLogSymlink(containerID string, containerName, podName, podNamespace string) string {\n\treturn logSymlink(legacyContainerLogsDir, kubecontainer.BuildPodFullName(podName, podNamespace),\n\t\tcontainerName, containerID)\n}","line":{"from":41,"to":46}} {"id":100007085,"name":"getContainerIDFromLegacyLogSymlink","signature":"func getContainerIDFromLegacyLogSymlink(logSymlink string) (string, error)","file":"pkg/kubelet/kuberuntime/legacy.go","code":"// getContainerIDFromLegacyLogSymlink returns error if container Id cannot be parsed\nfunc getContainerIDFromLegacyLogSymlink(logSymlink string) (string, error) {\n\tparts := strings.Split(logSymlink, \"-\")\n\tif len(parts) == 0 {\n\t\treturn \"\", fmt.Errorf(\"unable to find separator in %q\", logSymlink)\n\t}\n\tcontainerIDWithSuffix := parts[len(parts)-1]\n\tsuffix := fmt.Sprintf(\".%s\", legacyLogSuffix)\n\tif !strings.HasSuffix(containerIDWithSuffix, suffix) {\n\t\treturn \"\", fmt.Errorf(\"%q doesn't end with %q\", logSymlink, suffix)\n\t}\n\tcontainerIDWithoutSuffix := strings.TrimSuffix(containerIDWithSuffix, suffix)\n\t// container can be retrieved with container Id as short as 6 characters\n\tif len(containerIDWithoutSuffix) \u003c 6 {\n\t\treturn \"\", fmt.Errorf(\"container Id %q is too short\", containerIDWithoutSuffix)\n\t}\n\treturn containerIDWithoutSuffix, nil\n}","line":{"from":48,"to":65}} {"id":100007086,"name":"logSymlink","signature":"func logSymlink(containerLogsDir, podFullName, containerName, containerID string) string","file":"pkg/kubelet/kuberuntime/legacy.go","code":"func logSymlink(containerLogsDir, podFullName, containerName, containerID string) string {\n\tsuffix := fmt.Sprintf(\".%s\", legacyLogSuffix)\n\tlogPath := fmt.Sprintf(\"%s_%s-%s\", podFullName, containerName, containerID)\n\t// Length of a filename cannot exceed 255 characters in ext4 on Linux.\n\tif len(logPath) \u003e ext4MaxFileNameLen-len(suffix) {\n\t\tlogPath = logPath[:ext4MaxFileNameLen-len(suffix)]\n\t}\n\treturn filepath.Join(containerLogsDir, logPath+suffix)\n}","line":{"from":67,"to":75}} {"id":100007087,"name":"reset","signature":"func (l *logMessage) reset()","file":"pkg/kubelet/kuberuntime/logs/logs.go","code":"// reset resets the log to nil.\nfunc (l *logMessage) reset() {\n\tl.timestamp = time.Time{}\n\tl.stream = \"\"\n\tl.log = nil\n}","line":{"from":77,"to":82}} {"id":100007088,"name":"NewLogOptions","signature":"func NewLogOptions(apiOpts *v1.PodLogOptions, now time.Time) *LogOptions","file":"pkg/kubelet/kuberuntime/logs/logs.go","code":"// NewLogOptions convert the v1.PodLogOptions to CRI internal LogOptions.\nfunc NewLogOptions(apiOpts *v1.PodLogOptions, now time.Time) *LogOptions {\n\topts := \u0026LogOptions{\n\t\ttail: -1, // -1 by default which means read all logs.\n\t\tbytes: -1, // -1 by default which means read all logs.\n\t\tfollow: apiOpts.Follow,\n\t\ttimestamp: apiOpts.Timestamps,\n\t}\n\tif apiOpts.TailLines != nil {\n\t\topts.tail = *apiOpts.TailLines\n\t}\n\tif apiOpts.LimitBytes != nil {\n\t\topts.bytes = *apiOpts.LimitBytes\n\t}\n\tif apiOpts.SinceSeconds != nil {\n\t\topts.since = now.Add(-time.Duration(*apiOpts.SinceSeconds) * time.Second)\n\t}\n\tif apiOpts.SinceTime != nil \u0026\u0026 apiOpts.SinceTime.After(opts.since) {\n\t\topts.since = apiOpts.SinceTime.Time\n\t}\n\treturn opts\n}","line":{"from":93,"to":114}} {"id":100007089,"name":"parseCRILog","signature":"func parseCRILog(log []byte, msg *logMessage) error","file":"pkg/kubelet/kuberuntime/logs/logs.go","code":"// parseCRILog parses logs in CRI log format. CRI Log format example:\n//\n//\t2016-10-06T00:17:09.669794202Z stdout P log content 1\n//\t2016-10-06T00:17:09.669794203Z stderr F log content 2\nfunc parseCRILog(log []byte, msg *logMessage) error {\n\tvar err error\n\t// Parse timestamp\n\tidx := bytes.Index(log, delimiter)\n\tif idx \u003c 0 {\n\t\treturn fmt.Errorf(\"timestamp is not found\")\n\t}\n\tmsg.timestamp, err = time.Parse(timeFormatIn, string(log[:idx]))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unexpected timestamp format %q: %v\", timeFormatIn, err)\n\t}\n\n\t// Parse stream type\n\tlog = log[idx+1:]\n\tidx = bytes.Index(log, delimiter)\n\tif idx \u003c 0 {\n\t\treturn fmt.Errorf(\"stream type is not found\")\n\t}\n\tmsg.stream = runtimeapi.LogStreamType(log[:idx])\n\tif msg.stream != runtimeapi.Stdout \u0026\u0026 msg.stream != runtimeapi.Stderr {\n\t\treturn fmt.Errorf(\"unexpected stream type %q\", msg.stream)\n\t}\n\n\t// Parse log tag\n\tlog = log[idx+1:]\n\tidx = bytes.Index(log, delimiter)\n\tif idx \u003c 0 {\n\t\treturn fmt.Errorf(\"log tag is not found\")\n\t}\n\t// Keep this forward compatible.\n\ttags := bytes.Split(log[:idx], tagDelimiter)\n\tpartial := runtimeapi.LogTag(tags[0]) == runtimeapi.LogTagPartial\n\t// Trim the tailing new line if this is a partial line.\n\tif partial \u0026\u0026 len(log) \u003e 0 \u0026\u0026 log[len(log)-1] == '\\n' {\n\t\tlog = log[:len(log)-1]\n\t}\n\n\t// Get log content\n\tmsg.log = log[idx+1:]\n\n\treturn nil\n}","line":{"from":125,"to":170}} {"id":100007090,"name":"parseDockerJSONLog","signature":"func parseDockerJSONLog(log []byte, msg *logMessage) error","file":"pkg/kubelet/kuberuntime/logs/logs.go","code":"// parseDockerJSONLog parses logs in Docker JSON log format. Docker JSON log format\n// example:\n//\n//\t{\"log\":\"content 1\",\"stream\":\"stdout\",\"time\":\"2016-10-20T18:39:20.57606443Z\"}\n//\t{\"log\":\"content 2\",\"stream\":\"stderr\",\"time\":\"2016-10-20T18:39:20.57606444Z\"}\nfunc parseDockerJSONLog(log []byte, msg *logMessage) error {\n\tvar l = \u0026jsonLog{}\n\n\t// TODO: JSON decoding is fairly expensive, we should evaluate this.\n\tif err := json.Unmarshal(log, l); err != nil {\n\t\treturn fmt.Errorf(\"failed with %v to unmarshal log %q\", err, l)\n\t}\n\tmsg.timestamp = l.Created\n\tmsg.stream = runtimeapi.LogStreamType(l.Stream)\n\tmsg.log = []byte(l.Log)\n\treturn nil\n}","line":{"from":184,"to":200}} {"id":100007091,"name":"getParseFunc","signature":"func getParseFunc(log []byte) (parseFunc, error)","file":"pkg/kubelet/kuberuntime/logs/logs.go","code":"// getParseFunc returns proper parse function based on the sample log line passed in.\nfunc getParseFunc(log []byte) (parseFunc, error) {\n\tfor _, p := range parseFuncs {\n\t\tif err := p(log, \u0026logMessage{}); err == nil {\n\t\t\treturn p, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"unsupported log format: %q\", log)\n}","line":{"from":202,"to":210}} {"id":100007092,"name":"newLogWriter","signature":"func newLogWriter(stdout io.Writer, stderr io.Writer, opts *LogOptions) *logWriter","file":"pkg/kubelet/kuberuntime/logs/logs.go","code":"func newLogWriter(stdout io.Writer, stderr io.Writer, opts *LogOptions) *logWriter {\n\tw := \u0026logWriter{\n\t\tstdout: stdout,\n\t\tstderr: stderr,\n\t\topts: opts,\n\t\tremain: math.MaxInt64, // initialize it as infinity\n\t}\n\tif opts.bytes \u003e= 0 {\n\t\tw.remain = opts.bytes\n\t}\n\treturn w\n}","line":{"from":226,"to":237}} {"id":100007093,"name":"write","signature":"func (w *logWriter) write(msg *logMessage, addPrefix bool) error","file":"pkg/kubelet/kuberuntime/logs/logs.go","code":"// writeLogs writes logs into stdout, stderr.\nfunc (w *logWriter) write(msg *logMessage, addPrefix bool) error {\n\tif msg.timestamp.Before(w.opts.since) {\n\t\t// Skip the line because it's older than since\n\t\treturn nil\n\t}\n\tline := msg.log\n\tif w.opts.timestamp \u0026\u0026 addPrefix {\n\t\tprefix := append([]byte(msg.timestamp.Format(timeFormatOut)), delimiter[0])\n\t\tline = append(prefix, line...)\n\t}\n\t// If the line is longer than the remaining bytes, cut it.\n\tif int64(len(line)) \u003e w.remain {\n\t\tline = line[:w.remain]\n\t}\n\t// Get the proper stream to write to.\n\tvar stream io.Writer\n\tswitch msg.stream {\n\tcase runtimeapi.Stdout:\n\t\tstream = w.stdout\n\tcase runtimeapi.Stderr:\n\t\tstream = w.stderr\n\tdefault:\n\t\treturn fmt.Errorf(\"unexpected stream type %q\", msg.stream)\n\t}\n\tn, err := stream.Write(line)\n\tw.remain -= int64(n)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// If the line has not been fully written, return errShortWrite\n\tif n \u003c len(line) {\n\t\treturn errShortWrite\n\t}\n\t// If there are no more bytes left, return errMaximumWrite\n\tif w.remain \u003c= 0 {\n\t\treturn errMaximumWrite\n\t}\n\treturn nil\n}","line":{"from":239,"to":278}} {"id":100007094,"name":"ReadLogs","signature":"func ReadLogs(ctx context.Context, path, containerID string, opts *LogOptions, runtimeService internalapi.RuntimeService, stdout, stderr io.Writer) error","file":"pkg/kubelet/kuberuntime/logs/logs.go","code":"// ReadLogs read the container log and redirect into stdout and stderr.\n// Note that containerID is only needed when following the log, or else\n// just pass in empty string \"\".\nfunc ReadLogs(ctx context.Context, path, containerID string, opts *LogOptions, runtimeService internalapi.RuntimeService, stdout, stderr io.Writer) error {\n\t// fsnotify has different behavior for symlinks in different platform,\n\t// for example it follows symlink on Linux, but not on Windows,\n\t// so we explicitly resolve symlinks before reading the logs.\n\t// There shouldn't be security issue because the container log\n\t// path is owned by kubelet and the container runtime.\n\tevaluated, err := filepath.EvalSymlinks(path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to try resolving symlinks in path %q: %v\", path, err)\n\t}\n\tpath = evaluated\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to open log file %q: %v\", path, err)\n\t}\n\tdefer f.Close()\n\n\t// Search start point based on tail line.\n\tstart, err := tail.FindTailLineStartIndex(f, opts.tail)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to tail %d lines of log file %q: %v\", opts.tail, path, err)\n\t}\n\tif _, err := f.Seek(start, io.SeekStart); err != nil {\n\t\treturn fmt.Errorf(\"failed to seek %d in log file %q: %v\", start, path, err)\n\t}\n\n\tlimitedMode := (opts.tail \u003e= 0) \u0026\u0026 (!opts.follow)\n\tlimitedNum := opts.tail\n\t// Start parsing the logs.\n\tr := bufio.NewReader(f)\n\t// Do not create watcher here because it is not needed if `Follow` is false.\n\tvar watcher *fsnotify.Watcher\n\tvar parse parseFunc\n\tvar stop bool\n\tisNewLine := true\n\tfound := true\n\twriter := newLogWriter(stdout, stderr, opts)\n\tmsg := \u0026logMessage{}\n\tfor {\n\t\tif stop || (limitedMode \u0026\u0026 limitedNum == 0) {\n\t\t\tklog.V(2).InfoS(\"Finished parsing log file\", \"path\", path)\n\t\t\treturn nil\n\t\t}\n\t\tl, err := r.ReadBytes(eol[0])\n\t\tif err != nil {\n\t\t\tif err != io.EOF { // This is an real error\n\t\t\t\treturn fmt.Errorf(\"failed to read log file %q: %v\", path, err)\n\t\t\t}\n\t\t\tif opts.follow {\n\t\t\t\t// The container is not running, we got to the end of the log.\n\t\t\t\tif !found {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\t// Reset seek so that if this is an incomplete line,\n\t\t\t\t// it will be read again.\n\t\t\t\tif _, err := f.Seek(-int64(len(l)), io.SeekCurrent); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"failed to reset seek in log file %q: %v\", path, err)\n\t\t\t\t}\n\t\t\t\tif watcher == nil {\n\t\t\t\t\t// Initialize the watcher if it has not been initialized yet.\n\t\t\t\t\tif watcher, err = fsnotify.NewWatcher(); err != nil {\n\t\t\t\t\t\treturn fmt.Errorf(\"failed to create fsnotify watcher: %v\", err)\n\t\t\t\t\t}\n\t\t\t\t\tdefer watcher.Close()\n\t\t\t\t\tif err := watcher.Add(f.Name()); err != nil {\n\t\t\t\t\t\treturn fmt.Errorf(\"failed to watch file %q: %v\", f.Name(), err)\n\t\t\t\t\t}\n\t\t\t\t\t// If we just created the watcher, try again to read as we might have missed\n\t\t\t\t\t// the event.\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tvar recreated bool\n\t\t\t\t// Wait until the next log change.\n\t\t\t\tfound, recreated, err = waitLogs(ctx, containerID, watcher, runtimeService)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif recreated {\n\t\t\t\t\tnewF, err := os.Open(path)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tif os.IsNotExist(err) {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn fmt.Errorf(\"failed to open log file %q: %v\", path, err)\n\t\t\t\t\t}\n\t\t\t\t\tdefer newF.Close()\n\t\t\t\t\tf.Close()\n\t\t\t\t\tif err := watcher.Remove(f.Name()); err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\t\t\t\t\tklog.ErrorS(err, \"Failed to remove file watch\", \"path\", f.Name())\n\t\t\t\t\t}\n\t\t\t\t\tf = newF\n\t\t\t\t\tif err := watcher.Add(f.Name()); err != nil {\n\t\t\t\t\t\treturn fmt.Errorf(\"failed to watch file %q: %v\", f.Name(), err)\n\t\t\t\t\t}\n\t\t\t\t\tr = bufio.NewReader(f)\n\t\t\t\t}\n\t\t\t\t// If the container exited consume data until the next EOF\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Should stop after writing the remaining content.\n\t\t\tstop = true\n\t\t\tif len(l) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tklog.InfoS(\"Incomplete line in log file\", \"path\", path, \"line\", l)\n\t\t}\n\t\tif parse == nil {\n\t\t\t// Initialize the log parsing function.\n\t\t\tparse, err = getParseFunc(l)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to get parse function: %v\", err)\n\t\t\t}\n\t\t}\n\t\t// Parse the log line.\n\t\tmsg.reset()\n\t\tif err := parse(l, msg); err != nil {\n\t\t\tklog.ErrorS(err, \"Failed when parsing line in log file\", \"path\", path, \"line\", l)\n\t\t\tcontinue\n\t\t}\n\t\t// Write the log line into the stream.\n\t\tif err := writer.write(msg, isNewLine); err != nil {\n\t\t\tif err == errMaximumWrite {\n\t\t\t\tklog.V(2).InfoS(\"Finished parsing log file, hit bytes limit\", \"path\", path, \"limit\", opts.bytes)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tklog.ErrorS(err, \"Failed when writing line to log file\", \"path\", path, \"line\", msg)\n\t\t\treturn err\n\t\t}\n\t\tif limitedMode {\n\t\t\tlimitedNum--\n\t\t}\n\t\tif len(msg.log) \u003e 0 {\n\t\t\tisNewLine = msg.log[len(msg.log)-1] == eol[0]\n\t\t} else {\n\t\t\tisNewLine = true\n\t\t}\n\t}\n}","line":{"from":280,"to":420}} {"id":100007095,"name":"isContainerRunning","signature":"func isContainerRunning(ctx context.Context, id string, r internalapi.RuntimeService) (bool, error)","file":"pkg/kubelet/kuberuntime/logs/logs.go","code":"func isContainerRunning(ctx context.Context, id string, r internalapi.RuntimeService) (bool, error) {\n\tresp, err := r.ContainerStatus(ctx, id, false)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tstatus := resp.GetStatus()\n\tif status == nil {\n\t\treturn false, remote.ErrContainerStatusNil\n\t}\n\t// Only keep following container log when it is running.\n\tif status.State != runtimeapi.ContainerState_CONTAINER_RUNNING {\n\t\tklog.V(5).InfoS(\"Container is not running\", \"containerId\", id, \"state\", status.State)\n\t\t// Do not return error because it's normal that the container stops\n\t\t// during waiting.\n\t\treturn false, nil\n\t}\n\treturn true, nil\n}","line":{"from":422,"to":439}} {"id":100007096,"name":"waitLogs","signature":"func waitLogs(ctx context.Context, id string, w *fsnotify.Watcher, runtimeService internalapi.RuntimeService) (bool, bool, error)","file":"pkg/kubelet/kuberuntime/logs/logs.go","code":"// waitLogs wait for the next log write. It returns two booleans and an error. The first boolean\n// indicates whether a new log is found; the second boolean if the log file was recreated;\n// the error is error happens during waiting new logs.\nfunc waitLogs(ctx context.Context, id string, w *fsnotify.Watcher, runtimeService internalapi.RuntimeService) (bool, bool, error) {\n\t// no need to wait if the pod is not running\n\tif running, err := isContainerRunning(ctx, id, runtimeService); !running {\n\t\treturn false, false, err\n\t}\n\terrRetry := 5\n\tfor {\n\t\tselect {\n\t\tcase \u003c-ctx.Done():\n\t\t\treturn false, false, fmt.Errorf(\"context cancelled\")\n\t\tcase e := \u003c-w.Events:\n\t\t\tswitch e.Op {\n\t\t\tcase fsnotify.Write:\n\t\t\t\treturn true, false, nil\n\t\t\tcase fsnotify.Create:\n\t\t\t\tfallthrough\n\t\t\tcase fsnotify.Rename:\n\t\t\t\tfallthrough\n\t\t\tcase fsnotify.Remove:\n\t\t\t\tfallthrough\n\t\t\tcase fsnotify.Chmod:\n\t\t\t\treturn true, true, nil\n\t\t\tdefault:\n\t\t\t\tklog.ErrorS(nil, \"Received unexpected fsnotify event, retrying\", \"event\", e)\n\t\t\t}\n\t\tcase err := \u003c-w.Errors:\n\t\t\tklog.ErrorS(err, \"Received fsnotify watch error, retrying unless no more retries left\", \"retries\", errRetry)\n\t\t\tif errRetry == 0 {\n\t\t\t\treturn false, false, err\n\t\t\t}\n\t\t\terrRetry--\n\t\tcase \u003c-time.After(logForceCheckPeriod):\n\t\t\treturn true, false, nil\n\t\t}\n\t}\n}","line":{"from":441,"to":479}} {"id":100007097,"name":"determineEffectiveSecurityContext","signature":"func (m *kubeGenericRuntimeManager) determineEffectiveSecurityContext(pod *v1.Pod, container *v1.Container, uid *int64, username string) (*runtimeapi.LinuxContainerSecurityContext, error)","file":"pkg/kubelet/kuberuntime/security_context.go","code":"// determineEffectiveSecurityContext gets container's security context from v1.Pod and v1.Container.\nfunc (m *kubeGenericRuntimeManager) determineEffectiveSecurityContext(pod *v1.Pod, container *v1.Container, uid *int64, username string) (*runtimeapi.LinuxContainerSecurityContext, error) {\n\teffectiveSc := securitycontext.DetermineEffectiveSecurityContext(pod, container)\n\tsynthesized := convertToRuntimeSecurityContext(effectiveSc)\n\tif synthesized == nil {\n\t\tsynthesized = \u0026runtimeapi.LinuxContainerSecurityContext{\n\t\t\tMaskedPaths: securitycontext.ConvertToRuntimeMaskedPaths(effectiveSc.ProcMount),\n\t\t\tReadonlyPaths: securitycontext.ConvertToRuntimeReadonlyPaths(effectiveSc.ProcMount),\n\t\t}\n\t}\n\n\t// TODO: Deprecated, remove after we switch to Seccomp field\n\t// set SeccompProfilePath.\n\tvar err error\n\tsynthesized.SeccompProfilePath, err = m.getSeccompProfilePath(pod.Annotations, container.Name, pod.Spec.SecurityContext, container.SecurityContext, m.seccompDefault)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsynthesized.Seccomp, err = m.getSeccompProfile(pod.Annotations, container.Name, pod.Spec.SecurityContext, container.SecurityContext, m.seccompDefault)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// set ApparmorProfile.\n\tsynthesized.ApparmorProfile = apparmor.GetProfileNameFromPodAnnotations(pod.Annotations, container.Name)\n\n\t// set RunAsUser.\n\tif synthesized.RunAsUser == nil {\n\t\tif uid != nil {\n\t\t\tsynthesized.RunAsUser = \u0026runtimeapi.Int64Value{Value: *uid}\n\t\t}\n\t\tsynthesized.RunAsUsername = username\n\t}\n\n\t// set namespace options and supplemental groups.\n\tnamespaceOptions, err := runtimeutil.NamespacesForPod(pod, m.runtimeHelper)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsynthesized.NamespaceOptions = namespaceOptions\n\tpodSc := pod.Spec.SecurityContext\n\tif podSc != nil {\n\t\tif podSc.FSGroup != nil {\n\t\t\tsynthesized.SupplementalGroups = append(synthesized.SupplementalGroups, int64(*podSc.FSGroup))\n\t\t}\n\n\t\tif podSc.SupplementalGroups != nil {\n\t\t\tfor _, sg := range podSc.SupplementalGroups {\n\t\t\t\tsynthesized.SupplementalGroups = append(synthesized.SupplementalGroups, int64(sg))\n\t\t\t}\n\t\t}\n\t}\n\tif groups := m.runtimeHelper.GetExtraSupplementalGroupsForPod(pod); len(groups) \u003e 0 {\n\t\tsynthesized.SupplementalGroups = append(synthesized.SupplementalGroups, groups...)\n\t}\n\n\tsynthesized.NoNewPrivs = securitycontext.AddNoNewPrivileges(effectiveSc)\n\n\tsynthesized.MaskedPaths = securitycontext.ConvertToRuntimeMaskedPaths(effectiveSc.ProcMount)\n\tsynthesized.ReadonlyPaths = securitycontext.ConvertToRuntimeReadonlyPaths(effectiveSc.ProcMount)\n\n\treturn synthesized, nil\n}","line":{"from":27,"to":90}} {"id":100007098,"name":"convertToRuntimeSecurityContext","signature":"func convertToRuntimeSecurityContext(securityContext *v1.SecurityContext) *runtimeapi.LinuxContainerSecurityContext","file":"pkg/kubelet/kuberuntime/security_context.go","code":"// convertToRuntimeSecurityContext converts v1.SecurityContext to runtimeapi.SecurityContext.\nfunc convertToRuntimeSecurityContext(securityContext *v1.SecurityContext) *runtimeapi.LinuxContainerSecurityContext {\n\tif securityContext == nil {\n\t\treturn nil\n\t}\n\n\tsc := \u0026runtimeapi.LinuxContainerSecurityContext{\n\t\tCapabilities: convertToRuntimeCapabilities(securityContext.Capabilities),\n\t\tSelinuxOptions: convertToRuntimeSELinuxOption(securityContext.SELinuxOptions),\n\t}\n\tif securityContext.RunAsUser != nil {\n\t\tsc.RunAsUser = \u0026runtimeapi.Int64Value{Value: int64(*securityContext.RunAsUser)}\n\t}\n\tif securityContext.RunAsGroup != nil {\n\t\tsc.RunAsGroup = \u0026runtimeapi.Int64Value{Value: int64(*securityContext.RunAsGroup)}\n\t}\n\tif securityContext.Privileged != nil {\n\t\tsc.Privileged = *securityContext.Privileged\n\t}\n\tif securityContext.ReadOnlyRootFilesystem != nil {\n\t\tsc.ReadonlyRootfs = *securityContext.ReadOnlyRootFilesystem\n\t}\n\n\treturn sc\n}","line":{"from":92,"to":116}} {"id":100007099,"name":"convertToRuntimeSELinuxOption","signature":"func convertToRuntimeSELinuxOption(opts *v1.SELinuxOptions) *runtimeapi.SELinuxOption","file":"pkg/kubelet/kuberuntime/security_context.go","code":"// convertToRuntimeSELinuxOption converts v1.SELinuxOptions to runtimeapi.SELinuxOption.\nfunc convertToRuntimeSELinuxOption(opts *v1.SELinuxOptions) *runtimeapi.SELinuxOption {\n\tif opts == nil {\n\t\treturn nil\n\t}\n\n\treturn \u0026runtimeapi.SELinuxOption{\n\t\tUser: opts.User,\n\t\tRole: opts.Role,\n\t\tType: opts.Type,\n\t\tLevel: opts.Level,\n\t}\n}","line":{"from":118,"to":130}} {"id":100007100,"name":"convertToRuntimeCapabilities","signature":"func convertToRuntimeCapabilities(opts *v1.Capabilities) *runtimeapi.Capability","file":"pkg/kubelet/kuberuntime/security_context.go","code":"// convertToRuntimeCapabilities converts v1.Capabilities to runtimeapi.Capability.\nfunc convertToRuntimeCapabilities(opts *v1.Capabilities) *runtimeapi.Capability {\n\tif opts == nil {\n\t\treturn nil\n\t}\n\n\tcapabilities := \u0026runtimeapi.Capability{\n\t\tAddCapabilities: make([]string, len(opts.Add)),\n\t\tDropCapabilities: make([]string, len(opts.Drop)),\n\t}\n\tfor index, value := range opts.Add {\n\t\tcapabilities.AddCapabilities[index] = string(value)\n\t}\n\tfor index, value := range opts.Drop {\n\t\tcapabilities.DropCapabilities[index] = string(value)\n\t}\n\n\treturn capabilities\n}","line":{"from":132,"to":150}} {"id":100007101,"name":"verifyRunAsNonRoot","signature":"func verifyRunAsNonRoot(pod *v1.Pod, container *v1.Container, uid *int64, username string) error","file":"pkg/kubelet/kuberuntime/security_context_others.go","code":"// verifyRunAsNonRoot verifies RunAsNonRoot.\nfunc verifyRunAsNonRoot(pod *v1.Pod, container *v1.Container, uid *int64, username string) error {\n\teffectiveSc := securitycontext.DetermineEffectiveSecurityContext(pod, container)\n\t// If the option is not set, or if running as root is allowed, return nil.\n\tif effectiveSc == nil || effectiveSc.RunAsNonRoot == nil || !*effectiveSc.RunAsNonRoot {\n\t\treturn nil\n\t}\n\n\tif effectiveSc.RunAsUser != nil {\n\t\tif *effectiveSc.RunAsUser == 0 {\n\t\t\treturn fmt.Errorf(\"container's runAsUser breaks non-root policy (pod: %q, container: %s)\", format.Pod(pod), container.Name)\n\t\t}\n\t\treturn nil\n\t}\n\n\tswitch {\n\tcase uid != nil \u0026\u0026 *uid == 0:\n\t\treturn fmt.Errorf(\"container has runAsNonRoot and image will run as root (pod: %q, container: %s)\", format.Pod(pod), container.Name)\n\tcase uid == nil \u0026\u0026 len(username) \u003e 0:\n\t\treturn fmt.Errorf(\"container has runAsNonRoot and image has non-numeric user (%s), cannot verify user is non-root (pod: %q, container: %s)\", username, format.Pod(pod), container.Name)\n\tdefault:\n\t\treturn nil\n\t}\n}","line":{"from":30,"to":53}} {"id":100007102,"name":"verifyRunAsNonRoot","signature":"func verifyRunAsNonRoot(pod *v1.Pod, container *v1.Container, uid *int64, username string) error","file":"pkg/kubelet/kuberuntime/security_context_windows.go","code":"// verifyRunAsNonRoot verifies RunAsNonRoot on windows.\n// https://github.com/kubernetes/enhancements/tree/master/keps/sig-windows/116-windows-node-support#v1container\n// Windows does not have a root user, we cannot judge the root identity of the windows container by the way to judge the root(uid=0) of the linux container.\n// According to the discussion of sig-windows, at present, we assume that ContainerAdministrator is the windows container root user,\n// and then optimize this logic according to the best time.\n// https://docs.google.com/document/d/1Tjxzjjuy4SQsFSUVXZbvqVb64hjNAG5CQX8bK7Yda9w\n// note: usernames on Windows are NOT case sensitive!\nfunc verifyRunAsNonRoot(pod *v1.Pod, container *v1.Container, uid *int64, username string) error {\n\teffectiveSc := securitycontext.DetermineEffectiveSecurityContext(pod, container)\n\t// If the option is not set, or if running as root is allowed, return nil.\n\tif effectiveSc == nil || effectiveSc.RunAsNonRoot == nil || !*effectiveSc.RunAsNonRoot {\n\t\treturn nil\n\t}\n\tif effectiveSc.RunAsUser != nil {\n\t\tklog.InfoS(\"Windows container does not support SecurityContext.RunAsUser, please use SecurityContext.WindowsOptions\",\n\t\t\t\"pod\", klog.KObj(pod), \"containerName\", container.Name)\n\t}\n\tif effectiveSc.SELinuxOptions != nil {\n\t\tklog.InfoS(\"Windows container does not support SecurityContext.SELinuxOptions, please use SecurityContext.WindowsOptions\",\n\t\t\t\"pod\", klog.KObj(pod), \"containerName\", container.Name)\n\t}\n\tif effectiveSc.RunAsGroup != nil {\n\t\tklog.InfoS(\"Windows container does not support SecurityContext.RunAsGroup\", \"pod\", klog.KObj(pod), \"containerName\", container.Name)\n\t}\n\t// Verify that if runAsUserName is set for the pod and/or container that it is not set to 'ContainerAdministrator'\n\tif effectiveSc.WindowsOptions != nil {\n\t\tif effectiveSc.WindowsOptions.RunAsUserName != nil {\n\t\t\tif strings.EqualFold(*effectiveSc.WindowsOptions.RunAsUserName, windowsRootUserName) {\n\t\t\t\treturn fmt.Errorf(\"container's runAsUserName (%s) which will be regarded as root identity and will break non-root policy (pod: %q, container: %s)\", *effectiveSc.WindowsOptions.RunAsUserName, format.Pod(pod), container.Name)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\t// Verify that if runAsUserName is NOT set for the pod and/or container that the default user for the container image is not set to 'ContainerAdministrator'\n\tif len(username) \u003e 0 \u0026\u0026 strings.EqualFold(username, windowsRootUserName) {\n\t\treturn fmt.Errorf(\"container's runAsUser (%s) which will be regarded as root identity and will break non-root policy (pod: %q, container: %s)\", username, format.Pod(pod), container.Name)\n\t}\n\treturn nil\n}","line":{"from":35,"to":73}} {"id":100007103,"name":"PodSandboxChanged","signature":"func PodSandboxChanged(pod *v1.Pod, podStatus *kubecontainer.PodStatus) (bool, uint32, string)","file":"pkg/kubelet/kuberuntime/util/util.go","code":"// PodSandboxChanged checks whether the spec of the pod is changed and returns\n// (changed, new attempt, original sandboxID if exist).\nfunc PodSandboxChanged(pod *v1.Pod, podStatus *kubecontainer.PodStatus) (bool, uint32, string) {\n\tif len(podStatus.SandboxStatuses) == 0 {\n\t\tklog.V(2).InfoS(\"No sandbox for pod can be found. Need to start a new one\", \"pod\", klog.KObj(pod))\n\t\treturn true, 0, \"\"\n\t}\n\n\treadySandboxCount := 0\n\tfor _, s := range podStatus.SandboxStatuses {\n\t\tif s.State == runtimeapi.PodSandboxState_SANDBOX_READY {\n\t\t\treadySandboxCount++\n\t\t}\n\t}\n\n\t// Needs to create a new sandbox when readySandboxCount \u003e 1 or the ready sandbox is not the latest one.\n\tsandboxStatus := podStatus.SandboxStatuses[0]\n\tif readySandboxCount \u003e 1 {\n\t\tklog.V(2).InfoS(\"Multiple sandboxes are ready for Pod. Need to reconcile them\", \"pod\", klog.KObj(pod))\n\t\treturn true, sandboxStatus.Metadata.Attempt + 1, sandboxStatus.Id\n\t}\n\tif sandboxStatus.State != runtimeapi.PodSandboxState_SANDBOX_READY {\n\t\tklog.V(2).InfoS(\"No ready sandbox for pod can be found. Need to start a new one\", \"pod\", klog.KObj(pod))\n\t\treturn true, sandboxStatus.Metadata.Attempt + 1, sandboxStatus.Id\n\t}\n\n\t// Needs to create a new sandbox when network namespace changed.\n\tif sandboxStatus.GetLinux().GetNamespaces().GetOptions().GetNetwork() != NetworkNamespaceForPod(pod) {\n\t\tklog.V(2).InfoS(\"Sandbox for pod has changed. Need to start a new one\", \"pod\", klog.KObj(pod))\n\t\treturn true, sandboxStatus.Metadata.Attempt + 1, \"\"\n\t}\n\n\t// Needs to create a new sandbox when the sandbox does not have an IP address.\n\tif !kubecontainer.IsHostNetworkPod(pod) \u0026\u0026 sandboxStatus.Network != nil \u0026\u0026 sandboxStatus.Network.Ip == \"\" {\n\t\tklog.V(2).InfoS(\"Sandbox for pod has no IP address. Need to start a new one\", \"pod\", klog.KObj(pod))\n\t\treturn true, sandboxStatus.Metadata.Attempt + 1, sandboxStatus.Id\n\t}\n\n\treturn false, sandboxStatus.Metadata.Attempt, sandboxStatus.Id\n}","line":{"from":26,"to":65}} {"id":100007104,"name":"IpcNamespaceForPod","signature":"func IpcNamespaceForPod(pod *v1.Pod) runtimeapi.NamespaceMode","file":"pkg/kubelet/kuberuntime/util/util.go","code":"// IpcNamespaceForPod returns the runtimeapi.NamespaceMode\n// for the IPC namespace of a pod\nfunc IpcNamespaceForPod(pod *v1.Pod) runtimeapi.NamespaceMode {\n\tif pod != nil \u0026\u0026 pod.Spec.HostIPC {\n\t\treturn runtimeapi.NamespaceMode_NODE\n\t}\n\treturn runtimeapi.NamespaceMode_POD\n}","line":{"from":67,"to":74}} {"id":100007105,"name":"NetworkNamespaceForPod","signature":"func NetworkNamespaceForPod(pod *v1.Pod) runtimeapi.NamespaceMode","file":"pkg/kubelet/kuberuntime/util/util.go","code":"// NetworkNamespaceForPod returns the runtimeapi.NamespaceMode\n// for the network namespace of a pod\nfunc NetworkNamespaceForPod(pod *v1.Pod) runtimeapi.NamespaceMode {\n\tif pod != nil \u0026\u0026 pod.Spec.HostNetwork {\n\t\treturn runtimeapi.NamespaceMode_NODE\n\t}\n\treturn runtimeapi.NamespaceMode_POD\n}","line":{"from":76,"to":83}} {"id":100007106,"name":"PidNamespaceForPod","signature":"func PidNamespaceForPod(pod *v1.Pod) runtimeapi.NamespaceMode","file":"pkg/kubelet/kuberuntime/util/util.go","code":"// PidNamespaceForPod returns the runtimeapi.NamespaceMode\n// for the PID namespace of a pod\nfunc PidNamespaceForPod(pod *v1.Pod) runtimeapi.NamespaceMode {\n\tif pod != nil {\n\t\tif pod.Spec.HostPID {\n\t\t\treturn runtimeapi.NamespaceMode_NODE\n\t\t}\n\t\tif pod.Spec.ShareProcessNamespace != nil \u0026\u0026 *pod.Spec.ShareProcessNamespace {\n\t\t\treturn runtimeapi.NamespaceMode_POD\n\t\t}\n\t}\n\t// Note that PID does not default to the zero value for v1.Pod\n\treturn runtimeapi.NamespaceMode_CONTAINER\n}","line":{"from":85,"to":98}} {"id":100007107,"name":"NamespacesForPod","signature":"func NamespacesForPod(pod *v1.Pod, runtimeHelper kubecontainer.RuntimeHelper) (*runtimeapi.NamespaceOption, error)","file":"pkg/kubelet/kuberuntime/util/util.go","code":"// namespacesForPod returns the runtimeapi.NamespaceOption for a given pod.\n// An empty or nil pod can be used to get the namespace defaults for v1.Pod.\nfunc NamespacesForPod(pod *v1.Pod, runtimeHelper kubecontainer.RuntimeHelper) (*runtimeapi.NamespaceOption, error) {\n\tuserNs, err := runtimeHelper.GetOrCreateUserNamespaceMappings(pod)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026runtimeapi.NamespaceOption{\n\t\tIpc: IpcNamespaceForPod(pod),\n\t\tNetwork: NetworkNamespaceForPod(pod),\n\t\tPid: PidNamespaceForPod(pod),\n\t\tUsernsOptions: userNs,\n\t}, nil\n}","line":{"from":100,"to":114}} {"id":100007108,"name":"NewAdmissionFailureHandlerStub","signature":"func NewAdmissionFailureHandlerStub() *AdmissionFailureHandlerStub","file":"pkg/kubelet/lifecycle/admission_failure_handler_stub.go","code":"// NewAdmissionFailureHandlerStub returns an instance of AdmissionFailureHandlerStub.\nfunc NewAdmissionFailureHandlerStub() *AdmissionFailureHandlerStub {\n\treturn \u0026AdmissionFailureHandlerStub{}\n}","line":{"from":29,"to":32}} {"id":100007109,"name":"HandleAdmissionFailure","signature":"func (n *AdmissionFailureHandlerStub) HandleAdmissionFailure(admitPod *v1.Pod, failureReasons []PredicateFailureReason) ([]PredicateFailureReason, error)","file":"pkg/kubelet/lifecycle/admission_failure_handler_stub.go","code":"// HandleAdmissionFailure simply passes admission rejection on, with no special handling.\nfunc (n *AdmissionFailureHandlerStub) HandleAdmissionFailure(admitPod *v1.Pod, failureReasons []PredicateFailureReason) ([]PredicateFailureReason, error) {\n\treturn failureReasons, nil\n}","line":{"from":34,"to":37}} {"id":100007110,"name":"NewHandlerRunner","signature":"func NewHandlerRunner(httpDoer kubetypes.HTTPDoer, commandRunner kubecontainer.CommandRunner, containerManager podStatusProvider, eventRecorder record.EventRecorder) kubecontainer.HandlerRunner","file":"pkg/kubelet/lifecycle/handlers.go","code":"// NewHandlerRunner returns a configured lifecycle handler for a container.\nfunc NewHandlerRunner(httpDoer kubetypes.HTTPDoer, commandRunner kubecontainer.CommandRunner, containerManager podStatusProvider, eventRecorder record.EventRecorder) kubecontainer.HandlerRunner {\n\treturn \u0026handlerRunner{\n\t\thttpDoer: httpDoer,\n\t\tcommandRunner: commandRunner,\n\t\tcontainerManager: containerManager,\n\t\teventRecorder: eventRecorder,\n\t}\n}","line":{"from":60,"to":68}} {"id":100007111,"name":"Run","signature":"func (hr *handlerRunner) Run(ctx context.Context, containerID kubecontainer.ContainerID, pod *v1.Pod, container *v1.Container, handler *v1.LifecycleHandler) (string, error)","file":"pkg/kubelet/lifecycle/handlers.go","code":"func (hr *handlerRunner) Run(ctx context.Context, containerID kubecontainer.ContainerID, pod *v1.Pod, container *v1.Container, handler *v1.LifecycleHandler) (string, error) {\n\tswitch {\n\tcase handler.Exec != nil:\n\t\tvar msg string\n\t\t// TODO(tallclair): Pass a proper timeout value.\n\t\toutput, err := hr.commandRunner.RunInContainer(ctx, containerID, handler.Exec.Command, 0)\n\t\tif err != nil {\n\t\t\tmsg = fmt.Sprintf(\"Exec lifecycle hook (%v) for Container %q in Pod %q failed - error: %v, message: %q\", handler.Exec.Command, container.Name, format.Pod(pod), err, string(output))\n\t\t\tklog.V(1).ErrorS(err, \"Exec lifecycle hook for Container in Pod failed\", \"execCommand\", handler.Exec.Command, \"containerName\", container.Name, \"pod\", klog.KObj(pod), \"message\", string(output))\n\t\t}\n\t\treturn msg, err\n\tcase handler.HTTPGet != nil:\n\t\terr := hr.runHTTPHandler(ctx, pod, container, handler, hr.eventRecorder)\n\t\tvar msg string\n\t\tif err != nil {\n\t\t\tmsg = fmt.Sprintf(\"HTTP lifecycle hook (%s) for Container %q in Pod %q failed - error: %v\", handler.HTTPGet.Path, container.Name, format.Pod(pod), err)\n\t\t\tklog.V(1).ErrorS(err, \"HTTP lifecycle hook for Container in Pod failed\", \"path\", handler.HTTPGet.Path, \"containerName\", container.Name, \"pod\", klog.KObj(pod))\n\t\t}\n\t\treturn msg, err\n\tdefault:\n\t\terr := fmt.Errorf(\"invalid handler: %v\", handler)\n\t\tmsg := fmt.Sprintf(\"Cannot run handler: %v\", err)\n\t\tklog.ErrorS(err, \"Cannot run handler\")\n\t\treturn msg, err\n\t}\n}","line":{"from":70,"to":95}} {"id":100007112,"name":"resolvePort","signature":"func resolvePort(portReference intstr.IntOrString, container *v1.Container) (int, error)","file":"pkg/kubelet/lifecycle/handlers.go","code":"// resolvePort attempts to turn an IntOrString port reference into a concrete port number.\n// If portReference has an int value, it is treated as a literal, and simply returns that value.\n// If portReference is a string, an attempt is first made to parse it as an integer. If that fails,\n// an attempt is made to find a port with the same name in the container spec.\n// If a port with the same name is found, it's ContainerPort value is returned. If no matching\n// port is found, an error is returned.\nfunc resolvePort(portReference intstr.IntOrString, container *v1.Container) (int, error) {\n\tif portReference.Type == intstr.Int {\n\t\treturn portReference.IntValue(), nil\n\t}\n\tportName := portReference.StrVal\n\tport, err := strconv.Atoi(portName)\n\tif err == nil {\n\t\treturn port, nil\n\t}\n\tfor _, portSpec := range container.Ports {\n\t\tif portSpec.Name == portName {\n\t\t\treturn int(portSpec.ContainerPort), nil\n\t\t}\n\t}\n\treturn -1, fmt.Errorf(\"couldn't find port: %v in %v\", portReference, container)\n}","line":{"from":97,"to":118}} {"id":100007113,"name":"runHTTPHandler","signature":"func (hr *handlerRunner) runHTTPHandler(ctx context.Context, pod *v1.Pod, container *v1.Container, handler *v1.LifecycleHandler, eventRecorder record.EventRecorder) error","file":"pkg/kubelet/lifecycle/handlers.go","code":"func (hr *handlerRunner) runHTTPHandler(ctx context.Context, pod *v1.Pod, container *v1.Container, handler *v1.LifecycleHandler, eventRecorder record.EventRecorder) error {\n\thost := handler.HTTPGet.Host\n\tpodIP := host\n\tif len(host) == 0 {\n\t\tstatus, err := hr.containerManager.GetPodStatus(ctx, pod.UID, pod.Name, pod.Namespace)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Unable to get pod info, event handlers may be invalid.\", \"pod\", klog.KObj(pod))\n\t\t\treturn err\n\t\t}\n\t\tif len(status.IPs) == 0 {\n\t\t\treturn fmt.Errorf(\"failed to find networking container: %v\", status)\n\t\t}\n\t\thost = status.IPs[0]\n\t\tpodIP = host\n\t}\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.ConsistentHTTPGetHandlers) {\n\t\treq, err := httpprobe.NewRequestForHTTPGetAction(handler.HTTPGet, container, podIP, \"lifecycle\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresp, err := hr.httpDoer.Do(req)\n\t\tdiscardHTTPRespBody(resp)\n\n\t\tif isHTTPResponseError(err) {\n\t\t\tklog.V(1).ErrorS(err, \"HTTPS request to lifecycle hook got HTTP response, retrying with HTTP.\", \"pod\", klog.KObj(pod), \"host\", req.URL.Host)\n\n\t\t\treq := req.Clone(context.Background())\n\t\t\treq.URL.Scheme = \"http\"\n\t\t\treq.Header.Del(\"Authorization\")\n\t\t\tresp, httpErr := hr.httpDoer.Do(req)\n\n\t\t\t// clear err since the fallback succeeded\n\t\t\tif httpErr == nil {\n\t\t\t\tmetrics.LifecycleHandlerHTTPFallbacks.Inc()\n\t\t\t\tif eventRecorder != nil {\n\t\t\t\t\t// report the fallback with an event\n\t\t\t\t\teventRecorder.Event(pod, v1.EventTypeWarning, \"LifecycleHTTPFallback\", fmt.Sprintf(\"request to HTTPS lifecycle hook %s got HTTP response, retry with HTTP succeeded\", req.URL.Host))\n\t\t\t\t}\n\t\t\t\terr = nil\n\t\t\t}\n\t\t\tdiscardHTTPRespBody(resp)\n\t\t}\n\t\treturn err\n\t}\n\n\t// Deprecated code path.\n\tvar port int\n\tif handler.HTTPGet.Port.Type == intstr.String \u0026\u0026 len(handler.HTTPGet.Port.StrVal) == 0 {\n\t\tport = 80\n\t} else {\n\t\tvar err error\n\t\tport, err = resolvePort(handler.HTTPGet.Port, container)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\turl := fmt.Sprintf(\"http://%s/%s\", net.JoinHostPort(host, strconv.Itoa(port)), handler.HTTPGet.Path)\n\treq, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresp, err := hr.httpDoer.Do(req)\n\n\tdiscardHTTPRespBody(resp)\n\treturn err\n}","line":{"from":120,"to":187}} {"id":100007114,"name":"discardHTTPRespBody","signature":"func discardHTTPRespBody(resp *http.Response)","file":"pkg/kubelet/lifecycle/handlers.go","code":"func discardHTTPRespBody(resp *http.Response) {\n\tif resp == nil {\n\t\treturn\n\t}\n\n\t// Ensure the response body is fully read and closed\n\t// before we reconnect, so that we reuse the same TCP\n\t// connection.\n\tdefer resp.Body.Close()\n\n\tif resp.ContentLength \u003c= maxRespBodyLength {\n\t\tio.Copy(io.Discard, \u0026io.LimitedReader{R: resp.Body, N: maxRespBodyLength})\n\t}\n}","line":{"from":189,"to":202}} {"id":100007115,"name":"NewAppArmorAdmitHandler","signature":"func NewAppArmorAdmitHandler(validator apparmor.Validator) PodAdmitHandler","file":"pkg/kubelet/lifecycle/handlers.go","code":"// NewAppArmorAdmitHandler returns a PodAdmitHandler which is used to evaluate\n// if a pod can be admitted from the perspective of AppArmor.\nfunc NewAppArmorAdmitHandler(validator apparmor.Validator) PodAdmitHandler {\n\treturn \u0026appArmorAdmitHandler{\n\t\tValidator: validator,\n\t}\n}","line":{"from":204,"to":210}} {"id":100007116,"name":"Admit","signature":"func (a *appArmorAdmitHandler) Admit(attrs *PodAdmitAttributes) PodAdmitResult","file":"pkg/kubelet/lifecycle/handlers.go","code":"func (a *appArmorAdmitHandler) Admit(attrs *PodAdmitAttributes) PodAdmitResult {\n\t// If the pod is already running or terminated, no need to recheck AppArmor.\n\tif attrs.Pod.Status.Phase != v1.PodPending {\n\t\treturn PodAdmitResult{Admit: true}\n\t}\n\n\terr := a.Validate(attrs.Pod)\n\tif err == nil {\n\t\treturn PodAdmitResult{Admit: true}\n\t}\n\treturn PodAdmitResult{\n\t\tAdmit: false,\n\t\tReason: \"AppArmor\",\n\t\tMessage: fmt.Sprintf(\"Cannot enforce AppArmor: %v\", err),\n\t}\n}","line":{"from":216,"to":231}} {"id":100007117,"name":"isHTTPResponseError","signature":"func isHTTPResponseError(err error) bool","file":"pkg/kubelet/lifecycle/handlers.go","code":"func isHTTPResponseError(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\turlErr := \u0026url.Error{}\n\tif !errors.As(err, \u0026urlErr) {\n\t\treturn false\n\t}\n\treturn strings.Contains(urlErr.Err.Error(), \"server gave HTTP response to HTTPS client\")\n}","line":{"from":233,"to":242}} {"id":100007118,"name":"AddPodAdmitHandler","signature":"func (handlers *PodAdmitHandlers) AddPodAdmitHandler(a PodAdmitHandler)","file":"pkg/kubelet/lifecycle/interfaces.go","code":"// AddPodAdmitHandler adds the specified observer.\nfunc (handlers *PodAdmitHandlers) AddPodAdmitHandler(a PodAdmitHandler) {\n\t*handlers = append(*handlers, a)\n}","line":{"from":103,"to":106}} {"id":100007119,"name":"AddPodSyncLoopHandler","signature":"func (handlers *PodSyncLoopHandlers) AddPodSyncLoopHandler(a PodSyncLoopHandler)","file":"pkg/kubelet/lifecycle/interfaces.go","code":"// AddPodSyncLoopHandler adds the specified observer.\nfunc (handlers *PodSyncLoopHandlers) AddPodSyncLoopHandler(a PodSyncLoopHandler) {\n\t*handlers = append(*handlers, a)\n}","line":{"from":111,"to":114}} {"id":100007120,"name":"AddPodSyncHandler","signature":"func (handlers *PodSyncHandlers) AddPodSyncHandler(a PodSyncHandler)","file":"pkg/kubelet/lifecycle/interfaces.go","code":"// AddPodSyncHandler adds the specified handler.\nfunc (handlers *PodSyncHandlers) AddPodSyncHandler(a PodSyncHandler) {\n\t*handlers = append(*handlers, a)\n}","line":{"from":119,"to":122}} {"id":100007121,"name":"NewPredicateAdmitHandler","signature":"func NewPredicateAdmitHandler(getNodeAnyWayFunc getNodeAnyWayFuncType, admissionFailureHandler AdmissionFailureHandler, pluginResourceUpdateFunc pluginResourceUpdateFuncType) PodAdmitHandler","file":"pkg/kubelet/lifecycle/predicate.go","code":"// NewPredicateAdmitHandler returns a PodAdmitHandler which is used to evaluates\n// if a pod can be admitted from the perspective of predicates.\nfunc NewPredicateAdmitHandler(getNodeAnyWayFunc getNodeAnyWayFuncType, admissionFailureHandler AdmissionFailureHandler, pluginResourceUpdateFunc pluginResourceUpdateFuncType) PodAdmitHandler {\n\treturn \u0026predicateAdmitHandler{\n\t\tgetNodeAnyWayFunc,\n\t\tpluginResourceUpdateFunc,\n\t\tadmissionFailureHandler,\n\t}\n}","line":{"from":51,"to":59}} {"id":100007122,"name":"Admit","signature":"func (w *predicateAdmitHandler) Admit(attrs *PodAdmitAttributes) PodAdmitResult","file":"pkg/kubelet/lifecycle/predicate.go","code":"func (w *predicateAdmitHandler) Admit(attrs *PodAdmitAttributes) PodAdmitResult {\n\tnode, err := w.getNodeAnyWayFunc()\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Cannot get Node info\")\n\t\treturn PodAdmitResult{\n\t\t\tAdmit: false,\n\t\t\tReason: \"InvalidNodeInfo\",\n\t\t\tMessage: \"Kubelet cannot get node info.\",\n\t\t}\n\t}\n\tadmitPod := attrs.Pod\n\tpods := attrs.OtherPods\n\tnodeInfo := schedulerframework.NewNodeInfo(pods...)\n\tnodeInfo.SetNode(node)\n\t// ensure the node has enough plugin resources for that required in pods\n\tif err = w.pluginResourceUpdateFunc(nodeInfo, attrs); err != nil {\n\t\tmessage := fmt.Sprintf(\"Update plugin resources failed due to %v, which is unexpected.\", err)\n\t\tklog.InfoS(\"Failed to admit pod\", \"pod\", klog.KObj(admitPod), \"message\", message)\n\t\treturn PodAdmitResult{\n\t\t\tAdmit: false,\n\t\t\tReason: \"UnexpectedAdmissionError\",\n\t\t\tMessage: message,\n\t\t}\n\t}\n\n\t// Remove the requests of the extended resources that are missing in the\n\t// node info. This is required to support cluster-level resources, which\n\t// are extended resources unknown to nodes.\n\t//\n\t// Caveat: If a pod was manually bound to a node (e.g., static pod) where a\n\t// node-level extended resource it requires is not found, then kubelet will\n\t// not fail admission while it should. This issue will be addressed with\n\t// the Resource Class API in the future.\n\tpodWithoutMissingExtendedResources := removeMissingExtendedResources(admitPod, nodeInfo)\n\n\treasons := generalFilter(podWithoutMissingExtendedResources, nodeInfo)\n\tfit := len(reasons) == 0\n\tif !fit {\n\t\treasons, err = w.admissionFailureHandler.HandleAdmissionFailure(admitPod, reasons)\n\t\tfit = len(reasons) == 0 \u0026\u0026 err == nil\n\t\tif err != nil {\n\t\t\tmessage := fmt.Sprintf(\"Unexpected error while attempting to recover from admission failure: %v\", err)\n\t\t\tklog.InfoS(\"Failed to admit pod, unexpected error while attempting to recover from admission failure\", \"pod\", klog.KObj(admitPod), \"err\", err)\n\t\t\treturn PodAdmitResult{\n\t\t\t\tAdmit: fit,\n\t\t\t\tReason: \"UnexpectedAdmissionError\",\n\t\t\t\tMessage: message,\n\t\t\t}\n\t\t}\n\t}\n\tif !fit {\n\t\tvar reason string\n\t\tvar message string\n\t\tif len(reasons) == 0 {\n\t\t\tmessage = fmt.Sprint(\"GeneralPredicates failed due to unknown reason, which is unexpected.\")\n\t\t\tklog.InfoS(\"Failed to admit pod: GeneralPredicates failed due to unknown reason, which is unexpected\", \"pod\", klog.KObj(admitPod))\n\t\t\treturn PodAdmitResult{\n\t\t\t\tAdmit: fit,\n\t\t\t\tReason: \"UnknownReason\",\n\t\t\t\tMessage: message,\n\t\t\t}\n\t\t}\n\t\t// If there are failed predicates, we only return the first one as a reason.\n\t\tr := reasons[0]\n\t\tswitch re := r.(type) {\n\t\tcase *PredicateFailureError:\n\t\t\treason = re.PredicateName\n\t\t\tmessage = re.Error()\n\t\t\tklog.V(2).InfoS(\"Predicate failed on Pod\", \"pod\", klog.KObj(admitPod), \"err\", message)\n\t\tcase *InsufficientResourceError:\n\t\t\treason = fmt.Sprintf(\"OutOf%s\", re.ResourceName)\n\t\t\tmessage = re.Error()\n\t\t\tklog.V(2).InfoS(\"Predicate failed on Pod\", \"pod\", klog.KObj(admitPod), \"err\", message)\n\t\tdefault:\n\t\t\treason = \"UnexpectedPredicateFailureType\"\n\t\t\tmessage = fmt.Sprintf(\"GeneralPredicates failed due to %v, which is unexpected.\", r)\n\t\t\tklog.InfoS(\"Failed to admit pod\", \"pod\", klog.KObj(admitPod), \"err\", message)\n\t\t}\n\t\treturn PodAdmitResult{\n\t\t\tAdmit: fit,\n\t\t\tReason: reason,\n\t\t\tMessage: message,\n\t\t}\n\t}\n\tif rejectPodAdmissionBasedOnOSSelector(admitPod, node) {\n\t\treturn PodAdmitResult{\n\t\t\tAdmit: false,\n\t\t\tReason: \"PodOSSelectorNodeLabelDoesNotMatch\",\n\t\t\tMessage: \"Failed to admit pod as the `kubernetes.io/os` label doesn't match node label\",\n\t\t}\n\t}\n\t// By this time, node labels should have been synced, this helps in identifying the pod with the usage.\n\tif rejectPodAdmissionBasedOnOSField(admitPod) {\n\t\treturn PodAdmitResult{\n\t\t\tAdmit: false,\n\t\t\tReason: \"PodOSNotSupported\",\n\t\t\tMessage: \"Failed to admit pod as the OS field doesn't match node OS\",\n\t\t}\n\t}\n\treturn PodAdmitResult{\n\t\tAdmit: true,\n\t}\n}","line":{"from":61,"to":163}} {"id":100007123,"name":"rejectPodAdmissionBasedOnOSSelector","signature":"func rejectPodAdmissionBasedOnOSSelector(pod *v1.Pod, node *v1.Node) bool","file":"pkg/kubelet/lifecycle/predicate.go","code":"// rejectPodAdmissionBasedOnOSSelector rejects pod if it's nodeSelector doesn't match\n// We expect the kubelet status reconcile which happens every 10sec to update the node labels if there is a mismatch.\nfunc rejectPodAdmissionBasedOnOSSelector(pod *v1.Pod, node *v1.Node) bool {\n\tlabels := node.Labels\n\tosName, osLabelExists := labels[v1.LabelOSStable]\n\tif !osLabelExists || osName != runtime.GOOS {\n\t\tif len(labels) == 0 {\n\t\t\tlabels = make(map[string]string)\n\t\t}\n\t\tlabels[v1.LabelOSStable] = runtime.GOOS\n\t}\n\tpodLabelSelector, podOSLabelExists := pod.Labels[v1.LabelOSStable]\n\tif !podOSLabelExists {\n\t\t// If the labelselector didn't exist, let's keep the current behavior as is\n\t\treturn false\n\t} else if podOSLabelExists \u0026\u0026 podLabelSelector != labels[v1.LabelOSStable] {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":165,"to":184}} {"id":100007124,"name":"rejectPodAdmissionBasedOnOSField","signature":"func rejectPodAdmissionBasedOnOSField(pod *v1.Pod) bool","file":"pkg/kubelet/lifecycle/predicate.go","code":"// rejectPodAdmissionBasedOnOSField rejects pods if their OS field doesn't match runtime.GOOS.\n// TODO: Relax this restriction when we start supporting LCOW in kubernetes where podOS may not match\n// node's OS.\nfunc rejectPodAdmissionBasedOnOSField(pod *v1.Pod) bool {\n\tif pod.Spec.OS == nil {\n\t\treturn false\n\t}\n\t// If the pod OS doesn't match runtime.GOOS return false\n\treturn string(pod.Spec.OS.Name) != runtime.GOOS\n}","line":{"from":186,"to":195}} {"id":100007125,"name":"removeMissingExtendedResources","signature":"func removeMissingExtendedResources(pod *v1.Pod, nodeInfo *schedulerframework.NodeInfo) *v1.Pod","file":"pkg/kubelet/lifecycle/predicate.go","code":"func removeMissingExtendedResources(pod *v1.Pod, nodeInfo *schedulerframework.NodeInfo) *v1.Pod {\n\tpodCopy := pod.DeepCopy()\n\tfor i, c := range pod.Spec.Containers {\n\t\t// We only handle requests in Requests but not Limits because the\n\t\t// PodFitsResources predicate, to which the result pod will be passed,\n\t\t// does not use Limits.\n\t\tpodCopy.Spec.Containers[i].Resources.Requests = make(v1.ResourceList)\n\t\tfor rName, rQuant := range c.Resources.Requests {\n\t\t\tif v1helper.IsExtendedResourceName(rName) {\n\t\t\t\tif _, found := nodeInfo.Allocatable.ScalarResources[rName]; !found {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tpodCopy.Spec.Containers[i].Resources.Requests[rName] = rQuant\n\t\t}\n\t}\n\treturn podCopy\n}","line":{"from":197,"to":214}} {"id":100007126,"name":"Error","signature":"func (e *InsufficientResourceError) Error() string","file":"pkg/kubelet/lifecycle/predicate.go","code":"func (e *InsufficientResourceError) Error() string {\n\treturn fmt.Sprintf(\"Node didn't have enough resource: %s, requested: %d, used: %d, capacity: %d\",\n\t\te.ResourceName, e.Requested, e.Used, e.Capacity)\n}","line":{"from":225,"to":228}} {"id":100007127,"name":"GetReason","signature":"func (e *InsufficientResourceError) GetReason() string","file":"pkg/kubelet/lifecycle/predicate.go","code":"// GetReason returns the reason of the InsufficientResourceError.\nfunc (e *InsufficientResourceError) GetReason() string {\n\treturn fmt.Sprintf(\"Insufficient %v\", e.ResourceName)\n}","line":{"from":235,"to":238}} {"id":100007128,"name":"GetInsufficientAmount","signature":"func (e *InsufficientResourceError) GetInsufficientAmount() int64","file":"pkg/kubelet/lifecycle/predicate.go","code":"// GetInsufficientAmount returns the amount of the insufficient resource of the error.\nfunc (e *InsufficientResourceError) GetInsufficientAmount() int64 {\n\treturn e.Requested - (e.Capacity - e.Used)\n}","line":{"from":240,"to":243}} {"id":100007129,"name":"Error","signature":"func (e *PredicateFailureError) Error() string","file":"pkg/kubelet/lifecycle/predicate.go","code":"func (e *PredicateFailureError) Error() string {\n\treturn fmt.Sprintf(\"Predicate %s failed\", e.PredicateName)\n}","line":{"from":251,"to":253}} {"id":100007130,"name":"GetReason","signature":"func (e *PredicateFailureError) GetReason() string","file":"pkg/kubelet/lifecycle/predicate.go","code":"// GetReason returns the reason of the PredicateFailureError.\nfunc (e *PredicateFailureError) GetReason() string {\n\treturn e.PredicateDesc\n}","line":{"from":255,"to":258}} {"id":100007131,"name":"generalFilter","signature":"func generalFilter(pod *v1.Pod, nodeInfo *schedulerframework.NodeInfo) []PredicateFailureReason","file":"pkg/kubelet/lifecycle/predicate.go","code":"// generalFilter checks a group of filterings that the kubelet cares about.\nfunc generalFilter(pod *v1.Pod, nodeInfo *schedulerframework.NodeInfo) []PredicateFailureReason {\n\tadmissionResults := scheduler.AdmissionCheck(pod, nodeInfo, true)\n\tvar reasons []PredicateFailureReason\n\tfor _, r := range admissionResults {\n\t\tif r.InsufficientResource != nil {\n\t\t\treasons = append(reasons, \u0026InsufficientResourceError{\n\t\t\t\tResourceName: r.InsufficientResource.ResourceName,\n\t\t\t\tRequested: r.InsufficientResource.Requested,\n\t\t\t\tUsed: r.InsufficientResource.Used,\n\t\t\t\tCapacity: r.InsufficientResource.Capacity,\n\t\t\t})\n\t\t} else {\n\t\t\treasons = append(reasons, \u0026PredicateFailureError{r.Name, r.Reason})\n\t\t}\n\t}\n\n\t// Check taint/toleration except for static pods\n\tif !types.IsStaticPod(pod) {\n\t\t_, isUntolerated := corev1.FindMatchingUntoleratedTaint(nodeInfo.Node().Spec.Taints, pod.Spec.Tolerations, func(t *v1.Taint) bool {\n\t\t\t// Kubelet is only interested in the NoExecute taint.\n\t\t\treturn t.Effect == v1.TaintEffectNoExecute\n\t\t})\n\t\tif isUntolerated {\n\t\t\treasons = append(reasons, \u0026PredicateFailureError{tainttoleration.Name, tainttoleration.ErrReasonNotMatch})\n\t\t}\n\t}\n\n\treturn reasons\n}","line":{"from":260,"to":289}} {"id":100007132,"name":"GetAllLogs","signature":"func GetAllLogs(log string) ([]string, error)","file":"pkg/kubelet/logs/container_log_manager.go","code":"// GetAllLogs gets all inuse (rotated/compressed) logs for a specific container log.\n// Returned logs are sorted in oldest to newest order.\n// TODO(#59902): Leverage this function to support log rotation in `kubectl logs`.\nfunc GetAllLogs(log string) ([]string, error) {\n\t// pattern is used to match all rotated files.\n\tpattern := fmt.Sprintf(\"%s.*\", log)\n\tlogs, err := filepath.Glob(pattern)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to list all log files with pattern %q: %v\", pattern, err)\n\t}\n\tinuse, _ := filterUnusedLogs(logs)\n\tsort.Strings(inuse)\n\treturn append(inuse, log), nil\n}","line":{"from":76,"to":89}} {"id":100007133,"name":"Close","signature":"func (rc *compressReadCloser) Close() error","file":"pkg/kubelet/logs/container_log_manager.go","code":"func (rc *compressReadCloser) Close() error {\n\tferr := rc.f.Close()\n\trerr := rc.Reader.Close()\n\tif ferr != nil {\n\t\treturn ferr\n\t}\n\tif rerr != nil {\n\t\treturn rerr\n\t}\n\treturn nil\n}","line":{"from":97,"to":107}} {"id":100007134,"name":"UncompressLog","signature":"func UncompressLog(log string) (_ io.ReadCloser, retErr error)","file":"pkg/kubelet/logs/container_log_manager.go","code":"// UncompressLog compresses a compressed log and return a readcloser for the\n// stream of the uncompressed content.\n// TODO(#59902): Leverage this function to support log rotation in `kubectl logs`.\nfunc UncompressLog(log string) (_ io.ReadCloser, retErr error) {\n\tif !strings.HasSuffix(log, compressSuffix) {\n\t\treturn nil, fmt.Errorf(\"log is not compressed\")\n\t}\n\tf, err := os.Open(log)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open log: %v\", err)\n\t}\n\tdefer func() {\n\t\tif retErr != nil {\n\t\t\tf.Close()\n\t\t}\n\t}()\n\tr, err := gzip.NewReader(f)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create gzip reader: %v\", err)\n\t}\n\treturn \u0026compressReadCloser{f: f, Reader: r}, nil\n}","line":{"from":109,"to":130}} {"id":100007135,"name":"parseMaxSize","signature":"func parseMaxSize(size string) (int64, error)","file":"pkg/kubelet/logs/container_log_manager.go","code":"// parseMaxSize parses quantity string to int64 max size in bytes.\nfunc parseMaxSize(size string) (int64, error) {\n\tquantity, err := resource.ParseQuantity(size)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tmaxSize, ok := quantity.AsInt64()\n\tif !ok {\n\t\treturn 0, fmt.Errorf(\"invalid max log size\")\n\t}\n\treturn maxSize, nil\n}","line":{"from":132,"to":143}} {"id":100007136,"name":"NewContainerLogManager","signature":"func NewContainerLogManager(runtimeService internalapi.RuntimeService, osInterface kubecontainer.OSInterface, maxSize string, maxFiles int) (ContainerLogManager, error)","file":"pkg/kubelet/logs/container_log_manager.go","code":"// NewContainerLogManager creates a new container log manager.\nfunc NewContainerLogManager(runtimeService internalapi.RuntimeService, osInterface kubecontainer.OSInterface, maxSize string, maxFiles int) (ContainerLogManager, error) {\n\tif maxFiles \u003c= 1 {\n\t\treturn nil, fmt.Errorf(\"invalid MaxFiles %d, must be \u003e 1\", maxFiles)\n\t}\n\tparsedMaxSize, err := parseMaxSize(maxSize)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse container log max size %q: %v\", maxSize, err)\n\t}\n\t// Negative number means to disable container log rotation\n\tif parsedMaxSize \u003c 0 {\n\t\treturn NewStubContainerLogManager(), nil\n\t}\n\t// policy LogRotatePolicy\n\treturn \u0026containerLogManager{\n\t\tosInterface: osInterface,\n\t\truntimeService: runtimeService,\n\t\tpolicy: LogRotatePolicy{\n\t\t\tMaxSize: parsedMaxSize,\n\t\t\tMaxFiles: maxFiles,\n\t\t},\n\t\tclock: clock.RealClock{},\n\t\tmutex: sync.Mutex{},\n\t}, nil\n}","line":{"from":153,"to":177}} {"id":100007137,"name":"Start","signature":"func (c *containerLogManager) Start()","file":"pkg/kubelet/logs/container_log_manager.go","code":"// Start the container log manager.\nfunc (c *containerLogManager) Start() {\n\tctx := context.Background()\n\t// Start a goroutine periodically does container log rotation.\n\tgo wait.Forever(func() {\n\t\tif err := c.rotateLogs(ctx); err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to rotate container logs\")\n\t\t}\n\t}, logMonitorPeriod)\n}","line":{"from":179,"to":188}} {"id":100007138,"name":"Clean","signature":"func (c *containerLogManager) Clean(ctx context.Context, containerID string) error","file":"pkg/kubelet/logs/container_log_manager.go","code":"// Clean removes all logs of specified container (including rotated one).\nfunc (c *containerLogManager) Clean(ctx context.Context, containerID string) error {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tresp, err := c.runtimeService.ContainerStatus(ctx, containerID, false)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get container status %q: %v\", containerID, err)\n\t}\n\tif resp.GetStatus() == nil {\n\t\treturn fmt.Errorf(\"container status is nil for %q\", containerID)\n\t}\n\tpattern := fmt.Sprintf(\"%s*\", resp.GetStatus().GetLogPath())\n\tlogs, err := c.osInterface.Glob(pattern)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to list all log files with pattern %q: %v\", pattern, err)\n\t}\n\n\tfor _, l := range logs {\n\t\tif err := c.osInterface.Remove(l); err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\t\treturn fmt.Errorf(\"failed to remove container %q log %q: %v\", containerID, l, err)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":190,"to":214}} {"id":100007139,"name":"rotateLogs","signature":"func (c *containerLogManager) rotateLogs(ctx context.Context) error","file":"pkg/kubelet/logs/container_log_manager.go","code":"func (c *containerLogManager) rotateLogs(ctx context.Context) error {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\t// TODO(#59998): Use kubelet pod cache.\n\tcontainers, err := c.runtimeService.ListContainers(ctx, \u0026runtimeapi.ContainerFilter{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to list containers: %v\", err)\n\t}\n\t// NOTE(random-liu): Figure out whether we need to rotate container logs in parallel.\n\tfor _, container := range containers {\n\t\t// Only rotate logs for running containers. Non-running containers won't\n\t\t// generate new output, it doesn't make sense to keep an empty latest log.\n\t\tif container.GetState() != runtimeapi.ContainerState_CONTAINER_RUNNING {\n\t\t\tcontinue\n\t\t}\n\t\tid := container.GetId()\n\t\t// Note that we should not block log rotate for an error of a single container.\n\t\tresp, err := c.runtimeService.ContainerStatus(ctx, id, false)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to get container status\", \"containerID\", id)\n\t\t\tcontinue\n\t\t}\n\t\tif resp.GetStatus() == nil {\n\t\t\tklog.ErrorS(err, \"Container status is nil\", \"containerID\", id)\n\t\t\tcontinue\n\t\t}\n\t\tpath := resp.GetStatus().GetLogPath()\n\t\tinfo, err := c.osInterface.Stat(path)\n\t\tif err != nil {\n\t\t\tif !os.IsNotExist(err) {\n\t\t\t\tklog.ErrorS(err, \"Failed to stat container log\", \"path\", path)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// In rotateLatestLog, there are several cases that we may\n\t\t\t// lose original container log after ReopenContainerLog fails.\n\t\t\t// We try to recover it by reopening container log.\n\t\t\tif err := c.runtimeService.ReopenContainerLog(ctx, id); err != nil {\n\t\t\t\tklog.ErrorS(err, \"Container log doesn't exist, reopen container log failed\", \"containerID\", id, \"path\", path)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// The container log should be recovered.\n\t\t\tinfo, err = c.osInterface.Stat(path)\n\t\t\tif err != nil {\n\t\t\t\tklog.ErrorS(err, \"Failed to stat container log after reopen\", \"path\", path)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif info.Size() \u003c c.policy.MaxSize {\n\t\t\tcontinue\n\t\t}\n\t\t// Perform log rotation.\n\t\tif err := c.rotateLog(ctx, id, path); err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to rotate log for container\", \"path\", path, \"containerID\", id)\n\t\t\tcontinue\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":216,"to":273}} {"id":100007140,"name":"rotateLog","signature":"func (c *containerLogManager) rotateLog(ctx context.Context, id, log string) error","file":"pkg/kubelet/logs/container_log_manager.go","code":"func (c *containerLogManager) rotateLog(ctx context.Context, id, log string) error {\n\t// pattern is used to match all rotated files.\n\tpattern := fmt.Sprintf(\"%s.*\", log)\n\tlogs, err := filepath.Glob(pattern)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to list all log files with pattern %q: %v\", pattern, err)\n\t}\n\n\tlogs, err = c.cleanupUnusedLogs(logs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to cleanup logs: %v\", err)\n\t}\n\n\tlogs, err = c.removeExcessLogs(logs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to remove excess logs: %v\", err)\n\t}\n\n\t// Compress uncompressed log files.\n\tfor _, l := range logs {\n\t\tif strings.HasSuffix(l, compressSuffix) {\n\t\t\tcontinue\n\t\t}\n\t\tif err := c.compressLog(l); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to compress log %q: %v\", l, err)\n\t\t}\n\t}\n\n\tif err := c.rotateLatestLog(ctx, id, log); err != nil {\n\t\treturn fmt.Errorf(\"failed to rotate log %q: %v\", log, err)\n\t}\n\n\treturn nil\n}","line":{"from":275,"to":308}} {"id":100007141,"name":"cleanupUnusedLogs","signature":"func (c *containerLogManager) cleanupUnusedLogs(logs []string) ([]string, error)","file":"pkg/kubelet/logs/container_log_manager.go","code":"// cleanupUnusedLogs cleans up temporary or unused log files generated by previous log rotation\n// failure.\nfunc (c *containerLogManager) cleanupUnusedLogs(logs []string) ([]string, error) {\n\tinuse, unused := filterUnusedLogs(logs)\n\tfor _, l := range unused {\n\t\tif err := c.osInterface.Remove(l); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to remove unused log %q: %v\", l, err)\n\t\t}\n\t}\n\treturn inuse, nil\n}","line":{"from":310,"to":320}} {"id":100007142,"name":"filterUnusedLogs","signature":"func filterUnusedLogs(logs []string) (inuse []string, unused []string)","file":"pkg/kubelet/logs/container_log_manager.go","code":"// filterUnusedLogs splits logs into 2 groups, the 1st group is in used logs,\n// the second group is unused logs.\nfunc filterUnusedLogs(logs []string) (inuse []string, unused []string) {\n\tfor _, l := range logs {\n\t\tif isInUse(l, logs) {\n\t\t\tinuse = append(inuse, l)\n\t\t} else {\n\t\t\tunused = append(unused, l)\n\t\t}\n\t}\n\treturn inuse, unused\n}","line":{"from":322,"to":333}} {"id":100007143,"name":"isInUse","signature":"func isInUse(l string, logs []string) bool","file":"pkg/kubelet/logs/container_log_manager.go","code":"// isInUse checks whether a container log file is still inuse.\nfunc isInUse(l string, logs []string) bool {\n\t// All temporary files are not in use.\n\tif strings.HasSuffix(l, tmpSuffix) {\n\t\treturn false\n\t}\n\t// All compressed logs are in use.\n\tif strings.HasSuffix(l, compressSuffix) {\n\t\treturn true\n\t}\n\t// Files has already been compressed are not in use.\n\tfor _, another := range logs {\n\t\tif l+compressSuffix == another {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":335,"to":352}} {"id":100007144,"name":"removeExcessLogs","signature":"func (c *containerLogManager) removeExcessLogs(logs []string) ([]string, error)","file":"pkg/kubelet/logs/container_log_manager.go","code":"// removeExcessLogs removes old logs to make sure there are only at most MaxFiles log files.\nfunc (c *containerLogManager) removeExcessLogs(logs []string) ([]string, error) {\n\t// Sort log files in oldest to newest order.\n\tsort.Strings(logs)\n\t// Container will create a new log file, and we'll rotate the latest log file.\n\t// Other than those 2 files, we can have at most MaxFiles-2 rotated log files.\n\t// Keep MaxFiles-2 files by removing old files.\n\t// We should remove from oldest to newest, so as not to break ongoing `kubectl logs`.\n\tmaxRotatedFiles := c.policy.MaxFiles - 2\n\tif maxRotatedFiles \u003c 0 {\n\t\tmaxRotatedFiles = 0\n\t}\n\ti := 0\n\tfor ; i \u003c len(logs)-maxRotatedFiles; i++ {\n\t\tif err := c.osInterface.Remove(logs[i]); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to remove old log %q: %v\", logs[i], err)\n\t\t}\n\t}\n\tlogs = logs[i:]\n\treturn logs, nil\n}","line":{"from":354,"to":374}} {"id":100007145,"name":"compressLog","signature":"func (c *containerLogManager) compressLog(log string) error","file":"pkg/kubelet/logs/container_log_manager.go","code":"// compressLog compresses a log to log.gz with gzip.\nfunc (c *containerLogManager) compressLog(log string) error {\n\tr, err := c.osInterface.Open(log)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to open log %q: %v\", log, err)\n\t}\n\tdefer r.Close()\n\ttmpLog := log + tmpSuffix\n\tf, err := c.osInterface.OpenFile(tmpLog, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create temporary log %q: %v\", tmpLog, err)\n\t}\n\tdefer func() {\n\t\t// Best effort cleanup of tmpLog.\n\t\tc.osInterface.Remove(tmpLog)\n\t}()\n\tdefer f.Close()\n\tw := gzip.NewWriter(f)\n\tdefer w.Close()\n\tif _, err := io.Copy(w, r); err != nil {\n\t\treturn fmt.Errorf(\"failed to compress %q to %q: %v\", log, tmpLog, err)\n\t}\n\t// The archive needs to be closed before renaming, otherwise an error will occur on Windows.\n\tw.Close()\n\tf.Close()\n\tcompressedLog := log + compressSuffix\n\tif err := c.osInterface.Rename(tmpLog, compressedLog); err != nil {\n\t\treturn fmt.Errorf(\"failed to rename %q to %q: %v\", tmpLog, compressedLog, err)\n\t}\n\t// Remove old log file.\n\tr.Close()\n\tif err := c.osInterface.Remove(log); err != nil {\n\t\treturn fmt.Errorf(\"failed to remove log %q after compress: %v\", log, err)\n\t}\n\treturn nil\n}","line":{"from":376,"to":411}} {"id":100007146,"name":"rotateLatestLog","signature":"func (c *containerLogManager) rotateLatestLog(ctx context.Context, id, log string) error","file":"pkg/kubelet/logs/container_log_manager.go","code":"// rotateLatestLog rotates latest log without compression, so that container can still write\n// and fluentd can finish reading.\nfunc (c *containerLogManager) rotateLatestLog(ctx context.Context, id, log string) error {\n\ttimestamp := c.clock.Now().Format(timestampFormat)\n\trotated := fmt.Sprintf(\"%s.%s\", log, timestamp)\n\tif err := c.osInterface.Rename(log, rotated); err != nil {\n\t\treturn fmt.Errorf(\"failed to rotate log %q to %q: %v\", log, rotated, err)\n\t}\n\tif err := c.runtimeService.ReopenContainerLog(ctx, id); err != nil {\n\t\t// Rename the rotated log back, so that we can try rotating it again\n\t\t// next round.\n\t\t// If kubelet gets restarted at this point, we'll lose original log.\n\t\tif renameErr := c.osInterface.Rename(rotated, log); renameErr != nil {\n\t\t\t// This shouldn't happen.\n\t\t\t// Report an error if this happens, because we will lose original\n\t\t\t// log.\n\t\t\tklog.ErrorS(renameErr, \"Failed to rename rotated log\", \"rotatedLog\", rotated, \"newLog\", log, \"containerID\", id)\n\t\t}\n\t\treturn fmt.Errorf(\"failed to reopen container log %q: %v\", id, err)\n\t}\n\treturn nil\n}","line":{"from":413,"to":434}} {"id":100007147,"name":"Start","signature":"func (*containerLogManagerStub) Start() {}","file":"pkg/kubelet/logs/container_log_manager_stub.go","code":"func (*containerLogManagerStub) Start() {}","line":{"from":23,"to":23}} {"id":100007148,"name":"Clean","signature":"func (*containerLogManagerStub) Clean(ctx context.Context, containerID string) error","file":"pkg/kubelet/logs/container_log_manager_stub.go","code":"func (*containerLogManagerStub) Clean(ctx context.Context, containerID string) error {\n\treturn nil\n}","line":{"from":25,"to":27}} {"id":100007149,"name":"NewStubContainerLogManager","signature":"func NewStubContainerLogManager() ContainerLogManager","file":"pkg/kubelet/logs/container_log_manager_stub.go","code":"// NewStubContainerLogManager returns an empty ContainerLogManager which does nothing.\nfunc NewStubContainerLogManager() ContainerLogManager {\n\treturn \u0026containerLogManagerStub{}\n}","line":{"from":29,"to":32}} {"id":100007150,"name":"NewCRIMetricsCollector","signature":"func NewCRIMetricsCollector(ctx context.Context, listPodSandboxMetricsFn func(context.Context) ([]*runtimeapi.PodSandboxMetrics, error), listMetricDescriptorsFn func(context.Context) ([]*runtimeapi.MetricDescriptor, error)) metrics.StableCollector","file":"pkg/kubelet/metrics/collectors/cri_metrics.go","code":"// NewCRIMetricsCollector implements the metrics.Collector interface\nfunc NewCRIMetricsCollector(ctx context.Context, listPodSandboxMetricsFn func(context.Context) ([]*runtimeapi.PodSandboxMetrics, error), listMetricDescriptorsFn func(context.Context) ([]*runtimeapi.MetricDescriptor, error)) metrics.StableCollector {\n\tdescs, err := listMetricDescriptorsFn(ctx)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Error reading MetricDescriptors\")\n\t\treturn \u0026criMetricsCollector{\n\t\t\tlistPodSandboxMetricsFn: listPodSandboxMetricsFn,\n\t\t}\n\t}\n\tc := \u0026criMetricsCollector{\n\t\tlistPodSandboxMetricsFn: listPodSandboxMetricsFn,\n\t\tdescriptors: make(map[string]*metrics.Desc, len(descs)),\n\t}\n\n\tfor _, desc := range descs {\n\t\tc.descriptors[desc.Name] = criDescToProm(desc)\n\t}\n\n\treturn c\n}","line":{"from":40,"to":59}} {"id":100007151,"name":"DescribeWithStability","signature":"func (c *criMetricsCollector) DescribeWithStability(ch chan\u003c- *metrics.Desc)","file":"pkg/kubelet/metrics/collectors/cri_metrics.go","code":"// Describe implements the metrics.DescribeWithStability interface.\nfunc (c *criMetricsCollector) DescribeWithStability(ch chan\u003c- *metrics.Desc) {\n\tfor _, desc := range c.descriptors {\n\t\tch \u003c- desc\n\t}\n}","line":{"from":61,"to":66}} {"id":100007152,"name":"CollectWithStability","signature":"func (c *criMetricsCollector) CollectWithStability(ch chan\u003c- metrics.Metric)","file":"pkg/kubelet/metrics/collectors/cri_metrics.go","code":"// Collect implements the metrics.CollectWithStability interface.\n// TODO(haircommander): would it be better if these were processed async?\nfunc (c *criMetricsCollector) CollectWithStability(ch chan\u003c- metrics.Metric) {\n\tpodMetrics, err := c.listPodSandboxMetricsFn(context.Background())\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to get pod metrics\")\n\t\treturn\n\t}\n\n\tfor _, podMetric := range podMetrics {\n\t\tfor _, metric := range podMetric.GetMetrics() {\n\t\t\tpromMetric, err := c.criMetricToProm(metric)\n\t\t\tif err == nil {\n\t\t\t\tch \u003c- promMetric\n\t\t\t}\n\t\t}\n\t\tfor _, ctrMetric := range podMetric.GetContainerMetrics() {\n\t\t\tfor _, metric := range ctrMetric.GetMetrics() {\n\t\t\t\tpromMetric, err := c.criMetricToProm(metric)\n\t\t\t\tif err == nil {\n\t\t\t\t\tch \u003c- promMetric\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":68,"to":93}} {"id":100007153,"name":"criDescToProm","signature":"func criDescToProm(m *runtimeapi.MetricDescriptor) *metrics.Desc","file":"pkg/kubelet/metrics/collectors/cri_metrics.go","code":"func criDescToProm(m *runtimeapi.MetricDescriptor) *metrics.Desc {\n\t// Labels in the translation are variableLabels, as opposed to constant labels.\n\t// This is because the values of the labels will be different for each container.\n\treturn metrics.NewDesc(m.Name, m.Help, m.LabelKeys, nil, metrics.INTERNAL, \"\")\n}","line":{"from":95,"to":99}} {"id":100007154,"name":"criMetricToProm","signature":"func (c *criMetricsCollector) criMetricToProm(m *runtimeapi.Metric) (metrics.Metric, error)","file":"pkg/kubelet/metrics/collectors/cri_metrics.go","code":"func (c *criMetricsCollector) criMetricToProm(m *runtimeapi.Metric) (metrics.Metric, error) {\n\tdesc, ok := c.descriptors[m.Name]\n\tif !ok {\n\t\terr := fmt.Errorf(\"error converting CRI Metric to prometheus format\")\n\t\tklog.V(5).ErrorS(err, \"Descriptor not present in pre-populated list of descriptors\", \"name\", m.Name)\n\t\treturn nil, err\n\t}\n\n\ttyp := criTypeToProm[m.MetricType]\n\n\tpm, err := metrics.NewConstMetric(desc, typ, float64(m.GetValue().Value), m.LabelValues...)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Error getting CRI prometheus metric\", \"descriptor\", desc.String())\n\t\treturn nil, err\n\t}\n\t// If Timestamp is 0, then the runtime did not cache the result.\n\t// In this case, a cached result is a metric that was collected ahead of time,\n\t// as opposed to on-demand.\n\t// If the metric was requested as needed, then Timestamp==0.\n\tif m.Timestamp == 0 {\n\t\treturn pm, nil\n\t}\n\treturn metrics.NewLazyMetricWithTimestamp(time.Unix(0, m.Timestamp), pm), nil\n}","line":{"from":101,"to":124}} {"id":100007155,"name":"NewLogMetricsCollector","signature":"func NewLogMetricsCollector(podStats func(ctx context.Context) ([]statsapi.PodStats, error)) metrics.StableCollector","file":"pkg/kubelet/metrics/collectors/log_metrics.go","code":"// NewLogMetricsCollector implements the metrics.StableCollector interface and\n// exposes metrics about container's log volume size.\nfunc NewLogMetricsCollector(podStats func(ctx context.Context) ([]statsapi.PodStats, error)) metrics.StableCollector {\n\treturn \u0026logMetricsCollector{\n\t\tpodStats: podStats,\n\t}\n}","line":{"from":51,"to":57}} {"id":100007156,"name":"DescribeWithStability","signature":"func (c *logMetricsCollector) DescribeWithStability(ch chan\u003c- *metrics.Desc)","file":"pkg/kubelet/metrics/collectors/log_metrics.go","code":"// DescribeWithStability implements the metrics.StableCollector interface.\nfunc (c *logMetricsCollector) DescribeWithStability(ch chan\u003c- *metrics.Desc) {\n\tch \u003c- descLogSize\n}","line":{"from":59,"to":62}} {"id":100007157,"name":"CollectWithStability","signature":"func (c *logMetricsCollector) CollectWithStability(ch chan\u003c- metrics.Metric)","file":"pkg/kubelet/metrics/collectors/log_metrics.go","code":"// CollectWithStability implements the metrics.StableCollector interface.\nfunc (c *logMetricsCollector) CollectWithStability(ch chan\u003c- metrics.Metric) {\n\tpodStats, err := c.podStats(context.Background())\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to get pod stats\")\n\t\treturn\n\t}\n\n\tfor _, ps := range podStats {\n\t\tfor _, c := range ps.Containers {\n\t\t\tif c.Logs != nil \u0026\u0026 c.Logs.UsedBytes != nil {\n\t\t\t\tch \u003c- metrics.NewLazyConstMetric(\n\t\t\t\t\tdescLogSize,\n\t\t\t\t\tmetrics.GaugeValue,\n\t\t\t\t\tfloat64(*c.Logs.UsedBytes),\n\t\t\t\t\tps.PodRef.UID,\n\t\t\t\t\tps.PodRef.Namespace,\n\t\t\t\t\tps.PodRef.Name,\n\t\t\t\t\tc.Name,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":64,"to":87}} {"id":100007158,"name":"NewResourceMetricsCollector","signature":"func NewResourceMetricsCollector(provider stats.SummaryProvider) metrics.StableCollector","file":"pkg/kubelet/metrics/collectors/resource_metrics.go","code":"// NewResourceMetricsCollector returns a metrics.StableCollector which exports resource metrics\nfunc NewResourceMetricsCollector(provider stats.SummaryProvider) metrics.StableCollector {\n\treturn \u0026resourceMetricsCollector{\n\t\tprovider: provider,\n\t}\n}","line":{"from":87,"to":92}} {"id":100007159,"name":"DescribeWithStability","signature":"func (rc *resourceMetricsCollector) DescribeWithStability(ch chan\u003c- *metrics.Desc)","file":"pkg/kubelet/metrics/collectors/resource_metrics.go","code":"// DescribeWithStability implements metrics.StableCollector\nfunc (rc *resourceMetricsCollector) DescribeWithStability(ch chan\u003c- *metrics.Desc) {\n\tch \u003c- nodeCPUUsageDesc\n\tch \u003c- nodeMemoryUsageDesc\n\tch \u003c- containerStartTimeDesc\n\tch \u003c- containerCPUUsageDesc\n\tch \u003c- containerMemoryUsageDesc\n\tch \u003c- podCPUUsageDesc\n\tch \u003c- podMemoryUsageDesc\n\tch \u003c- resourceScrapeResultDesc\n}","line":{"from":103,"to":113}} {"id":100007160,"name":"CollectWithStability","signature":"func (rc *resourceMetricsCollector) CollectWithStability(ch chan\u003c- metrics.Metric)","file":"pkg/kubelet/metrics/collectors/resource_metrics.go","code":"// CollectWithStability implements metrics.StableCollector\n// Since new containers are frequently created and removed, using the Gauge would\n// leak metric collectors for containers or pods that no longer exist. Instead, implement\n// custom collector in a way that only collects metrics for active containers.\nfunc (rc *resourceMetricsCollector) CollectWithStability(ch chan\u003c- metrics.Metric) {\n\tctx := context.Background()\n\tvar errorCount float64\n\tdefer func() {\n\t\tch \u003c- metrics.NewLazyConstMetric(resourceScrapeResultDesc, metrics.GaugeValue, errorCount)\n\t}()\n\tstatsSummary, err := rc.provider.GetCPUAndMemoryStats(ctx)\n\tif err != nil {\n\t\terrorCount = 1\n\t\tklog.ErrorS(err, \"Error getting summary for resourceMetric prometheus endpoint\")\n\t\treturn\n\t}\n\n\trc.collectNodeCPUMetrics(ch, statsSummary.Node)\n\trc.collectNodeMemoryMetrics(ch, statsSummary.Node)\n\n\tfor _, pod := range statsSummary.Pods {\n\t\tfor _, container := range pod.Containers {\n\t\t\trc.collectContainerStartTime(ch, pod, container)\n\t\t\trc.collectContainerCPUMetrics(ch, pod, container)\n\t\t\trc.collectContainerMemoryMetrics(ch, pod, container)\n\t\t}\n\t\trc.collectPodCPUMetrics(ch, pod)\n\t\trc.collectPodMemoryMetrics(ch, pod)\n\t}\n}","line":{"from":115,"to":144}} {"id":100007161,"name":"collectNodeCPUMetrics","signature":"func (rc *resourceMetricsCollector) collectNodeCPUMetrics(ch chan\u003c- metrics.Metric, s summary.NodeStats)","file":"pkg/kubelet/metrics/collectors/resource_metrics.go","code":"func (rc *resourceMetricsCollector) collectNodeCPUMetrics(ch chan\u003c- metrics.Metric, s summary.NodeStats) {\n\tif s.CPU == nil || s.CPU.UsageCoreNanoSeconds == nil {\n\t\treturn\n\t}\n\n\tch \u003c- metrics.NewLazyMetricWithTimestamp(s.CPU.Time.Time,\n\t\tmetrics.NewLazyConstMetric(nodeCPUUsageDesc, metrics.CounterValue, float64(*s.CPU.UsageCoreNanoSeconds)/float64(time.Second)))\n}","line":{"from":146,"to":153}} {"id":100007162,"name":"collectNodeMemoryMetrics","signature":"func (rc *resourceMetricsCollector) collectNodeMemoryMetrics(ch chan\u003c- metrics.Metric, s summary.NodeStats)","file":"pkg/kubelet/metrics/collectors/resource_metrics.go","code":"func (rc *resourceMetricsCollector) collectNodeMemoryMetrics(ch chan\u003c- metrics.Metric, s summary.NodeStats) {\n\tif s.Memory == nil || s.Memory.WorkingSetBytes == nil {\n\t\treturn\n\t}\n\n\tch \u003c- metrics.NewLazyMetricWithTimestamp(s.Memory.Time.Time,\n\t\tmetrics.NewLazyConstMetric(nodeMemoryUsageDesc, metrics.GaugeValue, float64(*s.Memory.WorkingSetBytes)))\n}","line":{"from":155,"to":162}} {"id":100007163,"name":"collectContainerStartTime","signature":"func (rc *resourceMetricsCollector) collectContainerStartTime(ch chan\u003c- metrics.Metric, pod summary.PodStats, s summary.ContainerStats)","file":"pkg/kubelet/metrics/collectors/resource_metrics.go","code":"func (rc *resourceMetricsCollector) collectContainerStartTime(ch chan\u003c- metrics.Metric, pod summary.PodStats, s summary.ContainerStats) {\n\tif s.StartTime.Unix() \u003c= 0 {\n\t\treturn\n\t}\n\n\tch \u003c- metrics.NewLazyMetricWithTimestamp(s.StartTime.Time,\n\t\tmetrics.NewLazyConstMetric(containerStartTimeDesc, metrics.GaugeValue, float64(s.StartTime.UnixNano())/float64(time.Second), s.Name, pod.PodRef.Name, pod.PodRef.Namespace))\n}","line":{"from":164,"to":171}} {"id":100007164,"name":"collectContainerCPUMetrics","signature":"func (rc *resourceMetricsCollector) collectContainerCPUMetrics(ch chan\u003c- metrics.Metric, pod summary.PodStats, s summary.ContainerStats)","file":"pkg/kubelet/metrics/collectors/resource_metrics.go","code":"func (rc *resourceMetricsCollector) collectContainerCPUMetrics(ch chan\u003c- metrics.Metric, pod summary.PodStats, s summary.ContainerStats) {\n\tif s.CPU == nil || s.CPU.UsageCoreNanoSeconds == nil {\n\t\treturn\n\t}\n\n\tch \u003c- metrics.NewLazyMetricWithTimestamp(s.CPU.Time.Time,\n\t\tmetrics.NewLazyConstMetric(containerCPUUsageDesc, metrics.CounterValue,\n\t\t\tfloat64(*s.CPU.UsageCoreNanoSeconds)/float64(time.Second), s.Name, pod.PodRef.Name, pod.PodRef.Namespace))\n}","line":{"from":173,"to":181}} {"id":100007165,"name":"collectContainerMemoryMetrics","signature":"func (rc *resourceMetricsCollector) collectContainerMemoryMetrics(ch chan\u003c- metrics.Metric, pod summary.PodStats, s summary.ContainerStats)","file":"pkg/kubelet/metrics/collectors/resource_metrics.go","code":"func (rc *resourceMetricsCollector) collectContainerMemoryMetrics(ch chan\u003c- metrics.Metric, pod summary.PodStats, s summary.ContainerStats) {\n\tif s.Memory == nil || s.Memory.WorkingSetBytes == nil {\n\t\treturn\n\t}\n\n\tch \u003c- metrics.NewLazyMetricWithTimestamp(s.Memory.Time.Time,\n\t\tmetrics.NewLazyConstMetric(containerMemoryUsageDesc, metrics.GaugeValue,\n\t\t\tfloat64(*s.Memory.WorkingSetBytes), s.Name, pod.PodRef.Name, pod.PodRef.Namespace))\n}","line":{"from":183,"to":191}} {"id":100007166,"name":"collectPodCPUMetrics","signature":"func (rc *resourceMetricsCollector) collectPodCPUMetrics(ch chan\u003c- metrics.Metric, pod summary.PodStats)","file":"pkg/kubelet/metrics/collectors/resource_metrics.go","code":"func (rc *resourceMetricsCollector) collectPodCPUMetrics(ch chan\u003c- metrics.Metric, pod summary.PodStats) {\n\tif pod.CPU == nil || pod.CPU.UsageCoreNanoSeconds == nil {\n\t\treturn\n\t}\n\n\tch \u003c- metrics.NewLazyMetricWithTimestamp(pod.CPU.Time.Time,\n\t\tmetrics.NewLazyConstMetric(podCPUUsageDesc, metrics.CounterValue,\n\t\t\tfloat64(*pod.CPU.UsageCoreNanoSeconds)/float64(time.Second), pod.PodRef.Name, pod.PodRef.Namespace))\n}","line":{"from":193,"to":201}} {"id":100007167,"name":"collectPodMemoryMetrics","signature":"func (rc *resourceMetricsCollector) collectPodMemoryMetrics(ch chan\u003c- metrics.Metric, pod summary.PodStats)","file":"pkg/kubelet/metrics/collectors/resource_metrics.go","code":"func (rc *resourceMetricsCollector) collectPodMemoryMetrics(ch chan\u003c- metrics.Metric, pod summary.PodStats) {\n\tif pod.Memory == nil || pod.Memory.WorkingSetBytes == nil {\n\t\treturn\n\t}\n\n\tch \u003c- metrics.NewLazyMetricWithTimestamp(pod.Memory.Time.Time,\n\t\tmetrics.NewLazyConstMetric(podMemoryUsageDesc, metrics.GaugeValue,\n\t\t\tfloat64(*pod.Memory.WorkingSetBytes), pod.PodRef.Name, pod.PodRef.Namespace))\n}","line":{"from":203,"to":211}} {"id":100007168,"name":"NewVolumeStatsCollector","signature":"func NewVolumeStatsCollector(statsProvider serverstats.Provider) metrics.StableCollector","file":"pkg/kubelet/metrics/collectors/volume_stats.go","code":"// NewVolumeStatsCollector creates a volume stats metrics.StableCollector.\nfunc NewVolumeStatsCollector(statsProvider serverstats.Provider) metrics.StableCollector {\n\treturn \u0026volumeStatsCollector{statsProvider: statsProvider}\n}","line":{"from":83,"to":86}} {"id":100007169,"name":"DescribeWithStability","signature":"func (collector *volumeStatsCollector) DescribeWithStability(ch chan\u003c- *metrics.Desc)","file":"pkg/kubelet/metrics/collectors/volume_stats.go","code":"// DescribeWithStability implements the metrics.StableCollector interface.\nfunc (collector *volumeStatsCollector) DescribeWithStability(ch chan\u003c- *metrics.Desc) {\n\tch \u003c- volumeStatsCapacityBytesDesc\n\tch \u003c- volumeStatsAvailableBytesDesc\n\tch \u003c- volumeStatsUsedBytesDesc\n\tch \u003c- volumeStatsInodesDesc\n\tch \u003c- volumeStatsInodesFreeDesc\n\tch \u003c- volumeStatsInodesUsedDesc\n\tch \u003c- volumeStatsHealthAbnormalDesc\n}","line":{"from":88,"to":97}} {"id":100007170,"name":"CollectWithStability","signature":"func (collector *volumeStatsCollector) CollectWithStability(ch chan\u003c- metrics.Metric)","file":"pkg/kubelet/metrics/collectors/volume_stats.go","code":"// CollectWithStability implements the metrics.StableCollector interface.\nfunc (collector *volumeStatsCollector) CollectWithStability(ch chan\u003c- metrics.Metric) {\n\tctx := context.Background()\n\tpodStats, err := collector.statsProvider.ListPodStats(ctx)\n\tif err != nil {\n\t\treturn\n\t}\n\taddGauge := func(desc *metrics.Desc, pvcRef *stats.PVCReference, v float64, lv ...string) {\n\t\tlv = append([]string{pvcRef.Namespace, pvcRef.Name}, lv...)\n\t\tch \u003c- metrics.NewLazyConstMetric(desc, metrics.GaugeValue, v, lv...)\n\t}\n\tallPVCs := sets.String{}\n\tfor _, podStat := range podStats {\n\t\tif podStat.VolumeStats == nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, volumeStat := range podStat.VolumeStats {\n\t\t\tpvcRef := volumeStat.PVCRef\n\t\t\tif pvcRef == nil {\n\t\t\t\t// ignore if no PVC reference\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpvcUniqStr := pvcRef.Namespace + \"/\" + pvcRef.Name\n\t\t\tif allPVCs.Has(pvcUniqStr) {\n\t\t\t\t// ignore if already collected\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\taddGauge(volumeStatsCapacityBytesDesc, pvcRef, float64(*volumeStat.CapacityBytes))\n\t\t\taddGauge(volumeStatsAvailableBytesDesc, pvcRef, float64(*volumeStat.AvailableBytes))\n\t\t\taddGauge(volumeStatsUsedBytesDesc, pvcRef, float64(*volumeStat.UsedBytes))\n\t\t\taddGauge(volumeStatsInodesDesc, pvcRef, float64(*volumeStat.Inodes))\n\t\t\taddGauge(volumeStatsInodesFreeDesc, pvcRef, float64(*volumeStat.InodesFree))\n\t\t\taddGauge(volumeStatsInodesUsedDesc, pvcRef, float64(*volumeStat.InodesUsed))\n\t\t\tif volumeStat.VolumeHealthStats != nil {\n\t\t\t\taddGauge(volumeStatsHealthAbnormalDesc, pvcRef, convertBoolToFloat64(volumeStat.VolumeHealthStats.Abnormal))\n\t\t\t}\n\t\t\tallPVCs.Insert(pvcUniqStr)\n\t\t}\n\t}\n}","line":{"from":99,"to":138}} {"id":100007171,"name":"convertBoolToFloat64","signature":"func convertBoolToFloat64(boolVal bool) float64","file":"pkg/kubelet/metrics/collectors/volume_stats.go","code":"func convertBoolToFloat64(boolVal bool) float64 {\n\tif boolVal {\n\t\treturn 1\n\t}\n\n\treturn 0\n}","line":{"from":140,"to":146}} {"id":100007172,"name":"Register","signature":"func Register(collectors ...metrics.StableCollector)","file":"pkg/kubelet/metrics/metrics.go","code":"// Register registers all metrics.\nfunc Register(collectors ...metrics.StableCollector) {\n\t// Register the metrics.\n\tregisterMetrics.Do(func() {\n\t\tlegacyregistry.MustRegister(NodeName)\n\t\tlegacyregistry.MustRegister(PodWorkerDuration)\n\t\tlegacyregistry.MustRegister(PodStartDuration)\n\t\tlegacyregistry.MustRegister(PodStartSLIDuration)\n\t\tlegacyregistry.MustRegister(CgroupManagerDuration)\n\t\tlegacyregistry.MustRegister(PodWorkerStartDuration)\n\t\tlegacyregistry.MustRegister(PodStatusSyncDuration)\n\t\tlegacyregistry.MustRegister(ContainersPerPodCount)\n\t\tlegacyregistry.MustRegister(PLEGRelistDuration)\n\t\tlegacyregistry.MustRegister(PLEGDiscardEvents)\n\t\tlegacyregistry.MustRegister(PLEGRelistInterval)\n\t\tlegacyregistry.MustRegister(PLEGLastSeen)\n\t\tlegacyregistry.MustRegister(EventedPLEGConnErr)\n\t\tlegacyregistry.MustRegister(EventedPLEGConn)\n\t\tlegacyregistry.MustRegister(EventedPLEGConnLatency)\n\t\tlegacyregistry.MustRegister(RuntimeOperations)\n\t\tlegacyregistry.MustRegister(RuntimeOperationsDuration)\n\t\tlegacyregistry.MustRegister(RuntimeOperationsErrors)\n\t\tlegacyregistry.MustRegister(Evictions)\n\t\tlegacyregistry.MustRegister(EvictionStatsAge)\n\t\tlegacyregistry.MustRegister(Preemptions)\n\t\tlegacyregistry.MustRegister(DevicePluginRegistrationCount)\n\t\tlegacyregistry.MustRegister(DevicePluginAllocationDuration)\n\t\tlegacyregistry.MustRegister(RunningContainerCount)\n\t\tlegacyregistry.MustRegister(RunningPodCount)\n\t\tlegacyregistry.MustRegister(DesiredPodCount)\n\t\tlegacyregistry.MustRegister(ActivePodCount)\n\t\tlegacyregistry.MustRegister(MirrorPodCount)\n\t\tlegacyregistry.MustRegister(WorkingPodCount)\n\t\tlegacyregistry.MustRegister(OrphanedRuntimePodTotal)\n\t\tlegacyregistry.MustRegister(RestartedPodTotal)\n\t\tlegacyregistry.MustRegister(ManagedEphemeralContainers)\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.KubeletPodResources) {\n\t\t\tlegacyregistry.MustRegister(PodResourcesEndpointRequestsTotalCount)\n\n\t\t\tif utilfeature.DefaultFeatureGate.Enabled(features.KubeletPodResourcesGetAllocatable) {\n\t\t\t\tlegacyregistry.MustRegister(PodResourcesEndpointRequestsListCount)\n\t\t\t\tlegacyregistry.MustRegister(PodResourcesEndpointRequestsGetAllocatableCount)\n\t\t\t\tlegacyregistry.MustRegister(PodResourcesEndpointErrorsListCount)\n\t\t\t\tlegacyregistry.MustRegister(PodResourcesEndpointErrorsGetAllocatableCount)\n\t\t\t}\n\t\t\tif utilfeature.DefaultFeatureGate.Enabled(features.KubeletPodResourcesGet) {\n\t\t\t\tlegacyregistry.MustRegister(PodResourcesEndpointRequestsGetCount)\n\t\t\t\tlegacyregistry.MustRegister(PodResourcesEndpointErrorsGetCount)\n\t\t\t}\n\t\t}\n\t\tlegacyregistry.MustRegister(StartedPodsTotal)\n\t\tlegacyregistry.MustRegister(StartedPodsErrorsTotal)\n\t\tlegacyregistry.MustRegister(StartedContainersTotal)\n\t\tlegacyregistry.MustRegister(StartedContainersErrorsTotal)\n\t\tlegacyregistry.MustRegister(StartedHostProcessContainersTotal)\n\t\tlegacyregistry.MustRegister(StartedHostProcessContainersErrorsTotal)\n\t\tlegacyregistry.MustRegister(RunPodSandboxDuration)\n\t\tlegacyregistry.MustRegister(RunPodSandboxErrors)\n\t\tlegacyregistry.MustRegister(CPUManagerPinningRequestsTotal)\n\t\tlegacyregistry.MustRegister(CPUManagerPinningErrorsTotal)\n\t\tlegacyregistry.MustRegister(TopologyManagerAdmissionRequestsTotal)\n\t\tlegacyregistry.MustRegister(TopologyManagerAdmissionErrorsTotal)\n\t\tlegacyregistry.MustRegister(TopologyManagerAdmissionDuration)\n\t\tlegacyregistry.MustRegister(OrphanPodCleanedVolumes)\n\t\tlegacyregistry.MustRegister(OrphanPodCleanedVolumesErrors)\n\n\t\tfor _, collector := range collectors {\n\t\t\tlegacyregistry.CustomMustRegister(collector)\n\t\t}\n\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.GracefulNodeShutdown) \u0026\u0026\n\t\t\tutilfeature.DefaultFeatureGate.Enabled(features.GracefulNodeShutdownBasedOnPodPriority) {\n\t\t\tlegacyregistry.MustRegister(GracefulShutdownStartTime)\n\t\t\tlegacyregistry.MustRegister(GracefulShutdownEndTime)\n\t\t}\n\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.ConsistentHTTPGetHandlers) {\n\t\t\tlegacyregistry.MustRegister(LifecycleHandlerHTTPFallbacks)\n\t\t}\n\t})\n}","line":{"from":743,"to":823}} {"id":100007173,"name":"GetGather","signature":"func GetGather() metrics.Gatherer","file":"pkg/kubelet/metrics/metrics.go","code":"// GetGather returns the gatherer. It used by test case outside current package.\nfunc GetGather() metrics.Gatherer {\n\treturn legacyregistry.DefaultGatherer\n}","line":{"from":825,"to":828}} {"id":100007174,"name":"SinceInSeconds","signature":"func SinceInSeconds(start time.Time) float64","file":"pkg/kubelet/metrics/metrics.go","code":"// SinceInSeconds gets the time since the specified start in seconds.\nfunc SinceInSeconds(start time.Time) float64 {\n\treturn time.Since(start).Seconds()\n}","line":{"from":830,"to":833}} {"id":100007175,"name":"SetNodeName","signature":"func SetNodeName(name types.NodeName)","file":"pkg/kubelet/metrics/metrics.go","code":"// SetNodeName sets the NodeName Gauge to 1.\nfunc SetNodeName(name types.NodeName) {\n\tNodeName.WithLabelValues(string(name)).Set(1)\n}","line":{"from":835,"to":838}} {"id":100007176,"name":"NewConfigurer","signature":"func NewConfigurer(recorder record.EventRecorder, nodeRef *v1.ObjectReference, nodeIPs []net.IP, clusterDNS []net.IP, clusterDomain, resolverConfig string) *Configurer","file":"pkg/kubelet/network/dns/dns.go","code":"// NewConfigurer returns a DNS configurer for launching pods.\nfunc NewConfigurer(recorder record.EventRecorder, nodeRef *v1.ObjectReference, nodeIPs []net.IP, clusterDNS []net.IP, clusterDomain, resolverConfig string) *Configurer {\n\treturn \u0026Configurer{\n\t\trecorder: recorder,\n\t\tgetHostDNSConfig: getHostDNSConfig,\n\t\tnodeRef: nodeRef,\n\t\tnodeIPs: nodeIPs,\n\t\tclusterDNS: clusterDNS,\n\t\tClusterDomain: clusterDomain,\n\t\tResolverConfig: resolverConfig,\n\t}\n}","line":{"from":77,"to":88}} {"id":100007177,"name":"omitDuplicates","signature":"func omitDuplicates(strs []string) []string","file":"pkg/kubelet/network/dns/dns.go","code":"func omitDuplicates(strs []string) []string {\n\tuniqueStrs := make(map[string]bool)\n\n\tvar ret []string\n\tfor _, str := range strs {\n\t\tif !uniqueStrs[str] {\n\t\t\tret = append(ret, str)\n\t\t\tuniqueStrs[str] = true\n\t\t}\n\t}\n\treturn ret\n}","line":{"from":90,"to":101}} {"id":100007178,"name":"formDNSSearchFitsLimits","signature":"func (c *Configurer) formDNSSearchFitsLimits(composedSearch []string, pod *v1.Pod) []string","file":"pkg/kubelet/network/dns/dns.go","code":"func (c *Configurer) formDNSSearchFitsLimits(composedSearch []string, pod *v1.Pod) []string {\n\tlimitsExceeded := false\n\n\tmaxDNSSearchPaths, maxDNSSearchListChars := validation.MaxDNSSearchPathsLegacy, validation.MaxDNSSearchListCharsLegacy\n\tif utilfeature.DefaultFeatureGate.Enabled(features.ExpandedDNSConfig) {\n\t\tmaxDNSSearchPaths, maxDNSSearchListChars = validation.MaxDNSSearchPathsExpanded, validation.MaxDNSSearchListCharsExpanded\n\t}\n\n\tif len(composedSearch) \u003e maxDNSSearchPaths {\n\t\tcomposedSearch = composedSearch[:maxDNSSearchPaths]\n\t\tlimitsExceeded = true\n\t}\n\n\t// In some DNS resolvers(e.g. glibc 2.28), DNS resolving causes abort() if there is a\n\t// search path exceeding 255 characters. We have to filter them out.\n\tl := 0\n\tfor _, search := range composedSearch {\n\t\tif len(search) \u003e utilvalidation.DNS1123SubdomainMaxLength {\n\t\t\tlimitsExceeded = true\n\t\t\tcontinue\n\t\t}\n\t\tcomposedSearch[l] = search\n\t\tl++\n\t}\n\tcomposedSearch = composedSearch[:l]\n\n\tif resolvSearchLineStrLen := len(strings.Join(composedSearch, \" \")); resolvSearchLineStrLen \u003e maxDNSSearchListChars {\n\t\tcutDomainsNum := 0\n\t\tcutDomainsLen := 0\n\t\tfor i := len(composedSearch) - 1; i \u003e= 0; i-- {\n\t\t\tcutDomainsLen += len(composedSearch[i]) + 1\n\t\t\tcutDomainsNum++\n\n\t\t\tif (resolvSearchLineStrLen - cutDomainsLen) \u003c= maxDNSSearchListChars {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tcomposedSearch = composedSearch[:(len(composedSearch) - cutDomainsNum)]\n\t\tlimitsExceeded = true\n\t}\n\n\tif limitsExceeded {\n\t\terr := fmt.Errorf(\"Search Line limits were exceeded, some search paths have been omitted, the applied search line is: %s\", strings.Join(composedSearch, \" \"))\n\t\tc.recorder.Event(pod, v1.EventTypeWarning, \"DNSConfigForming\", err.Error())\n\t\tklog.ErrorS(err, \"Search Line limits exceeded\")\n\t}\n\treturn composedSearch\n}","line":{"from":103,"to":151}} {"id":100007179,"name":"formDNSNameserversFitsLimits","signature":"func (c *Configurer) formDNSNameserversFitsLimits(nameservers []string, pod *v1.Pod) []string","file":"pkg/kubelet/network/dns/dns.go","code":"func (c *Configurer) formDNSNameserversFitsLimits(nameservers []string, pod *v1.Pod) []string {\n\tif len(nameservers) \u003e validation.MaxDNSNameservers {\n\t\tnameservers = nameservers[0:validation.MaxDNSNameservers]\n\t\terr := fmt.Errorf(\"Nameserver limits were exceeded, some nameservers have been omitted, the applied nameserver line is: %s\", strings.Join(nameservers, \" \"))\n\t\tc.recorder.Event(pod, v1.EventTypeWarning, \"DNSConfigForming\", err.Error())\n\t\tklog.ErrorS(err, \"Nameserver limits exceeded\")\n\t}\n\treturn nameservers\n}","line":{"from":153,"to":161}} {"id":100007180,"name":"formDNSConfigFitsLimits","signature":"func (c *Configurer) formDNSConfigFitsLimits(dnsConfig *runtimeapi.DNSConfig, pod *v1.Pod) *runtimeapi.DNSConfig","file":"pkg/kubelet/network/dns/dns.go","code":"func (c *Configurer) formDNSConfigFitsLimits(dnsConfig *runtimeapi.DNSConfig, pod *v1.Pod) *runtimeapi.DNSConfig {\n\tdnsConfig.Servers = c.formDNSNameserversFitsLimits(dnsConfig.Servers, pod)\n\tdnsConfig.Searches = c.formDNSSearchFitsLimits(dnsConfig.Searches, pod)\n\treturn dnsConfig\n}","line":{"from":163,"to":167}} {"id":100007181,"name":"generateSearchesForDNSClusterFirst","signature":"func (c *Configurer) generateSearchesForDNSClusterFirst(hostSearch []string, pod *v1.Pod) []string","file":"pkg/kubelet/network/dns/dns.go","code":"func (c *Configurer) generateSearchesForDNSClusterFirst(hostSearch []string, pod *v1.Pod) []string {\n\tif c.ClusterDomain == \"\" {\n\t\treturn hostSearch\n\t}\n\n\tnsSvcDomain := fmt.Sprintf(\"%s.svc.%s\", pod.Namespace, c.ClusterDomain)\n\tsvcDomain := fmt.Sprintf(\"svc.%s\", c.ClusterDomain)\n\tclusterSearch := []string{nsSvcDomain, svcDomain, c.ClusterDomain}\n\n\treturn omitDuplicates(append(clusterSearch, hostSearch...))\n}","line":{"from":169,"to":179}} {"id":100007182,"name":"CheckLimitsForResolvConf","signature":"func (c *Configurer) CheckLimitsForResolvConf()","file":"pkg/kubelet/network/dns/dns.go","code":"// CheckLimitsForResolvConf checks limits in resolv.conf.\nfunc (c *Configurer) CheckLimitsForResolvConf() {\n\tf, err := os.Open(c.ResolverConfig)\n\tif err != nil {\n\t\tc.recorder.Event(c.nodeRef, v1.EventTypeWarning, \"CheckLimitsForResolvConf\", err.Error())\n\t\tklog.V(4).InfoS(\"Check limits for resolv.conf failed at file open\", \"err\", err)\n\t\treturn\n\t}\n\tdefer f.Close()\n\n\t_, hostSearch, _, err := parseResolvConf(f)\n\tif err != nil {\n\t\tc.recorder.Event(c.nodeRef, v1.EventTypeWarning, \"CheckLimitsForResolvConf\", err.Error())\n\t\tklog.V(4).InfoS(\"Check limits for resolv.conf failed at parse resolv.conf\", \"err\", err)\n\t\treturn\n\t}\n\n\tdomainCountLimit, maxDNSSearchListChars := validation.MaxDNSSearchPathsLegacy, validation.MaxDNSSearchListCharsLegacy\n\tif utilfeature.DefaultFeatureGate.Enabled(features.ExpandedDNSConfig) {\n\t\tdomainCountLimit, maxDNSSearchListChars = validation.MaxDNSSearchPathsExpanded, validation.MaxDNSSearchListCharsExpanded\n\t}\n\n\tif c.ClusterDomain != \"\" {\n\t\tdomainCountLimit -= 3\n\t}\n\n\tif len(hostSearch) \u003e domainCountLimit {\n\t\tlog := fmt.Sprintf(\"Resolv.conf file '%s' contains search line consisting of more than %d domains!\", c.ResolverConfig, domainCountLimit)\n\t\tc.recorder.Event(c.nodeRef, v1.EventTypeWarning, \"CheckLimitsForResolvConf\", log)\n\t\tklog.V(4).InfoS(\"Check limits for resolv.conf failed\", \"eventlog\", log)\n\t\treturn\n\t}\n\n\tfor _, search := range hostSearch {\n\t\tif len(search) \u003e utilvalidation.DNS1123SubdomainMaxLength {\n\t\t\tlog := fmt.Sprintf(\"Resolv.conf file %q contains a search path which length is more than allowed %d chars!\", c.ResolverConfig, utilvalidation.DNS1123SubdomainMaxLength)\n\t\t\tc.recorder.Event(c.nodeRef, v1.EventTypeWarning, \"CheckLimitsForResolvConf\", log)\n\t\t\tklog.V(4).InfoS(\"Check limits for resolv.conf failed\", \"eventlog\", log)\n\t\t\treturn\n\t\t}\n\t}\n\n\tif len(strings.Join(hostSearch, \" \")) \u003e maxDNSSearchListChars {\n\t\tlog := fmt.Sprintf(\"Resolv.conf file '%s' contains search line which length is more than allowed %d chars!\", c.ResolverConfig, maxDNSSearchListChars)\n\t\tc.recorder.Event(c.nodeRef, v1.EventTypeWarning, \"CheckLimitsForResolvConf\", log)\n\t\tklog.V(4).InfoS(\"Check limits for resolv.conf failed\", \"eventlog\", log)\n\t\treturn\n\t}\n}","line":{"from":181,"to":229}} {"id":100007183,"name":"parseResolvConf","signature":"func parseResolvConf(reader io.Reader) (nameservers []string, searches []string, options []string, err error)","file":"pkg/kubelet/network/dns/dns.go","code":"// parseResolvConf reads a resolv.conf file from the given reader, and parses\n// it into nameservers, searches and options, possibly returning an error.\nfunc parseResolvConf(reader io.Reader) (nameservers []string, searches []string, options []string, err error) {\n\tfile, err := utilio.ReadAtMost(reader, maxResolvConfLength)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// Lines of the form \"nameserver 1.2.3.4\" accumulate.\n\tnameservers = []string{}\n\n\t// Lines of the form \"search example.com\" overrule - last one wins.\n\tsearches = []string{}\n\n\t// Lines of the form \"option ndots:5 attempts:2\" overrule - last one wins.\n\t// Each option is recorded as an element in the array.\n\toptions = []string{}\n\n\tvar allErrors []error\n\tlines := strings.Split(string(file), \"\\n\")\n\tfor l := range lines {\n\t\ttrimmed := strings.TrimSpace(lines[l])\n\t\tif strings.HasPrefix(trimmed, \"#\") {\n\t\t\tcontinue\n\t\t}\n\t\tfields := strings.Fields(trimmed)\n\t\tif len(fields) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif fields[0] == \"nameserver\" {\n\t\t\tif len(fields) \u003e= 2 {\n\t\t\t\tnameservers = append(nameservers, fields[1])\n\t\t\t} else {\n\t\t\t\tallErrors = append(allErrors, fmt.Errorf(\"nameserver list is empty \"))\n\t\t\t}\n\t\t}\n\t\tif fields[0] == \"search\" {\n\t\t\t// Normalise search fields so the same domain with and without trailing dot will only count once, to avoid hitting search validation limits.\n\t\t\tsearches = []string{}\n\t\t\tfor _, s := range fields[1:] {\n\t\t\t\tif s != \".\" {\n\t\t\t\t\tsearches = append(searches, strings.TrimSuffix(s, \".\"))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif fields[0] == \"options\" {\n\t\t\toptions = appendOptions(options, fields[1:]...)\n\t\t}\n\t}\n\n\treturn nameservers, searches, options, utilerrors.NewAggregate(allErrors)\n}","line":{"from":231,"to":282}} {"id":100007184,"name":"getDNSConfig","signature":"func getDNSConfig(resolverConfigFile string) (*runtimeapi.DNSConfig, error)","file":"pkg/kubelet/network/dns/dns.go","code":"// Reads a resolv.conf-like file and returns the DNS config options from it.\n// Returns an empty DNSConfig if the given resolverConfigFile is an empty string.\nfunc getDNSConfig(resolverConfigFile string) (*runtimeapi.DNSConfig, error) {\n\tvar hostDNS, hostSearch, hostOptions []string\n\t// Get host DNS settings\n\tif resolverConfigFile != \"\" {\n\t\tf, err := os.Open(resolverConfigFile)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Could not open resolv conf file.\")\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer f.Close()\n\n\t\thostDNS, hostSearch, hostOptions, err = parseResolvConf(f)\n\t\tif err != nil {\n\t\t\terr := fmt.Errorf(\"Encountered error while parsing resolv conf file. Error: %w\", err)\n\t\t\tklog.ErrorS(err, \"Could not parse resolv conf file.\")\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn \u0026runtimeapi.DNSConfig{\n\t\tServers: hostDNS,\n\t\tSearches: hostSearch,\n\t\tOptions: hostOptions,\n\t}, nil\n}","line":{"from":284,"to":309}} {"id":100007185,"name":"getPodDNSType","signature":"func getPodDNSType(pod *v1.Pod) (podDNSType, error)","file":"pkg/kubelet/network/dns/dns.go","code":"func getPodDNSType(pod *v1.Pod) (podDNSType, error) {\n\tdnsPolicy := pod.Spec.DNSPolicy\n\tswitch dnsPolicy {\n\tcase v1.DNSNone:\n\t\treturn podDNSNone, nil\n\tcase v1.DNSClusterFirstWithHostNet:\n\t\treturn podDNSCluster, nil\n\tcase v1.DNSClusterFirst:\n\t\tif !kubecontainer.IsHostNetworkPod(pod) {\n\t\t\treturn podDNSCluster, nil\n\t\t}\n\t\t// Fallback to DNSDefault for pod on hostnetwork.\n\t\tfallthrough\n\tcase v1.DNSDefault:\n\t\treturn podDNSHost, nil\n\t}\n\t// This should not happen as kube-apiserver should have rejected\n\t// invalid dnsPolicy.\n\treturn podDNSCluster, fmt.Errorf(\"invalid DNSPolicy=%v\", dnsPolicy)\n}","line":{"from":311,"to":330}} {"id":100007186,"name":"mergeDNSOptions","signature":"func mergeDNSOptions(existingDNSConfigOptions []string, dnsConfigOptions []v1.PodDNSConfigOption) []string","file":"pkg/kubelet/network/dns/dns.go","code":"// mergeDNSOptions merges DNS options. If duplicated, entries given by PodDNSConfigOption will\n// overwrite the existing ones.\nfunc mergeDNSOptions(existingDNSConfigOptions []string, dnsConfigOptions []v1.PodDNSConfigOption) []string {\n\toptionsMap := make(map[string]string)\n\tfor _, op := range existingDNSConfigOptions {\n\t\tif index := strings.Index(op, \":\"); index != -1 {\n\t\t\toptionsMap[op[:index]] = op[index+1:]\n\t\t} else {\n\t\t\toptionsMap[op] = \"\"\n\t\t}\n\t}\n\tfor _, op := range dnsConfigOptions {\n\t\tif op.Value != nil {\n\t\t\toptionsMap[op.Name] = *op.Value\n\t\t} else {\n\t\t\toptionsMap[op.Name] = \"\"\n\t\t}\n\t}\n\t// Reconvert DNS options into a string array.\n\toptions := []string{}\n\tfor opName, opValue := range optionsMap {\n\t\top := opName\n\t\tif opValue != \"\" {\n\t\t\top = op + \":\" + opValue\n\t\t}\n\t\toptions = append(options, op)\n\t}\n\treturn options\n}","line":{"from":332,"to":360}} {"id":100007187,"name":"appendOptions","signature":"func appendOptions(options []string, newOption ...string) []string","file":"pkg/kubelet/network/dns/dns.go","code":"// appendOptions appends options to the given list, but does not add duplicates.\n// append option will overwrite the previous one either in new line or in the same line.\nfunc appendOptions(options []string, newOption ...string) []string {\n\tvar optionMap = make(map[string]string)\n\tfor _, option := range options {\n\t\toptName := strings.Split(option, \":\")[0]\n\t\toptionMap[optName] = option\n\t}\n\tfor _, option := range newOption {\n\t\toptName := strings.Split(option, \":\")[0]\n\t\toptionMap[optName] = option\n\t}\n\n\toptions = []string{}\n\tfor _, v := range optionMap {\n\t\toptions = append(options, v)\n\t}\n\treturn options\n}","line":{"from":362,"to":380}} {"id":100007188,"name":"appendDNSConfig","signature":"func appendDNSConfig(existingDNSConfig *runtimeapi.DNSConfig, dnsConfig *v1.PodDNSConfig) *runtimeapi.DNSConfig","file":"pkg/kubelet/network/dns/dns.go","code":"// appendDNSConfig appends DNS servers, search paths and options given by\n// PodDNSConfig to the existing DNS config. Duplicated entries will be merged.\n// This assumes existingDNSConfig and dnsConfig are not nil.\nfunc appendDNSConfig(existingDNSConfig *runtimeapi.DNSConfig, dnsConfig *v1.PodDNSConfig) *runtimeapi.DNSConfig {\n\texistingDNSConfig.Servers = omitDuplicates(append(existingDNSConfig.Servers, dnsConfig.Nameservers...))\n\texistingDNSConfig.Searches = omitDuplicates(append(existingDNSConfig.Searches, dnsConfig.Searches...))\n\texistingDNSConfig.Options = mergeDNSOptions(existingDNSConfig.Options, dnsConfig.Options)\n\treturn existingDNSConfig\n}","line":{"from":382,"to":390}} {"id":100007189,"name":"GetPodDNS","signature":"func (c *Configurer) GetPodDNS(pod *v1.Pod) (*runtimeapi.DNSConfig, error)","file":"pkg/kubelet/network/dns/dns.go","code":"// GetPodDNS returns DNS settings for the pod.\nfunc (c *Configurer) GetPodDNS(pod *v1.Pod) (*runtimeapi.DNSConfig, error) {\n\tdnsConfig, err := c.getHostDNSConfig(c.ResolverConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdnsType, err := getPodDNSType(pod)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to get DNS type for pod. Falling back to DNSClusterFirst policy.\", \"pod\", klog.KObj(pod))\n\t\tdnsType = podDNSCluster\n\t}\n\tswitch dnsType {\n\tcase podDNSNone:\n\t\t// DNSNone should use empty DNS settings as the base.\n\t\tdnsConfig = \u0026runtimeapi.DNSConfig{}\n\tcase podDNSCluster:\n\t\tif len(c.clusterDNS) != 0 {\n\t\t\t// For a pod with DNSClusterFirst policy, the cluster DNS server is\n\t\t\t// the only nameserver configured for the pod. The cluster DNS server\n\t\t\t// itself will forward queries to other nameservers that is configured\n\t\t\t// to use, in case the cluster DNS server cannot resolve the DNS query\n\t\t\t// itself.\n\t\t\tdnsConfig.Servers = []string{}\n\t\t\tfor _, ip := range c.clusterDNS {\n\t\t\t\tdnsConfig.Servers = append(dnsConfig.Servers, ip.String())\n\t\t\t}\n\t\t\tdnsConfig.Searches = c.generateSearchesForDNSClusterFirst(dnsConfig.Searches, pod)\n\t\t\tdnsConfig.Options = defaultDNSOptions\n\t\t\tbreak\n\t\t}\n\t\t// clusterDNS is not known. Pod with ClusterDNSFirst Policy cannot be created.\n\t\tnodeErrorMsg := fmt.Sprintf(\"kubelet does not have ClusterDNS IP configured and cannot create Pod using %q policy. Falling back to %q policy.\", v1.DNSClusterFirst, v1.DNSDefault)\n\t\tc.recorder.Eventf(c.nodeRef, v1.EventTypeWarning, \"MissingClusterDNS\", nodeErrorMsg)\n\t\tc.recorder.Eventf(pod, v1.EventTypeWarning, \"MissingClusterDNS\", \"pod: %q. %s\", format.Pod(pod), nodeErrorMsg)\n\t\t// Fallback to DNSDefault.\n\t\tfallthrough\n\tcase podDNSHost:\n\t\t// When the kubelet --resolv-conf flag is set to the empty string, use\n\t\t// DNS settings that override the docker default (which is to use\n\t\t// /etc/resolv.conf) and effectively disable DNS lookups. According to\n\t\t// the bind documentation, the behavior of the DNS client library when\n\t\t// \"nameservers\" are not specified is to \"use the nameserver on the\n\t\t// local machine\". A nameserver setting of localhost is equivalent to\n\t\t// this documented behavior.\n\t\tif c.ResolverConfig == \"\" {\n\t\t\tfor _, nodeIP := range c.nodeIPs {\n\t\t\t\tif utilnet.IsIPv6(nodeIP) {\n\t\t\t\t\tdnsConfig.Servers = append(dnsConfig.Servers, \"::1\")\n\t\t\t\t} else {\n\t\t\t\t\tdnsConfig.Servers = append(dnsConfig.Servers, \"127.0.0.1\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(dnsConfig.Servers) == 0 {\n\t\t\t\tdnsConfig.Servers = append(dnsConfig.Servers, \"127.0.0.1\")\n\t\t\t}\n\t\t\tdnsConfig.Searches = []string{\".\"}\n\t\t}\n\t}\n\n\tif pod.Spec.DNSConfig != nil {\n\t\tdnsConfig = appendDNSConfig(dnsConfig, pod.Spec.DNSConfig)\n\t}\n\treturn c.formDNSConfigFitsLimits(dnsConfig, pod), nil\n}","line":{"from":392,"to":456}} {"id":100007190,"name":"SetupDNSinContainerizedMounter","signature":"func (c *Configurer) SetupDNSinContainerizedMounter(mounterPath string)","file":"pkg/kubelet/network/dns/dns.go","code":"// SetupDNSinContainerizedMounter replaces the nameserver in containerized-mounter's rootfs/etc/resolv.conf with kubelet.ClusterDNS\nfunc (c *Configurer) SetupDNSinContainerizedMounter(mounterPath string) {\n\tresolvePath := filepath.Join(strings.TrimSuffix(mounterPath, \"/mounter\"), \"rootfs\", \"etc\", \"resolv.conf\")\n\tdnsString := \"\"\n\tfor _, dns := range c.clusterDNS {\n\t\tdnsString = dnsString + fmt.Sprintf(\"nameserver %s\\n\", dns)\n\t}\n\tif c.ResolverConfig != \"\" {\n\t\tf, err := os.Open(c.ResolverConfig)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Could not open resolverConf file\")\n\t\t} else {\n\t\t\tdefer f.Close()\n\t\t\t_, hostSearch, _, err := parseResolvConf(f)\n\t\t\tif err != nil {\n\t\t\t\tklog.ErrorS(err, \"Error for parsing the resolv.conf file\")\n\t\t\t} else {\n\t\t\t\tdnsString = dnsString + \"search\"\n\t\t\t\tfor _, search := range hostSearch {\n\t\t\t\t\tdnsString = dnsString + fmt.Sprintf(\" %s\", search)\n\t\t\t\t}\n\t\t\t\tdnsString = dnsString + \"\\n\"\n\t\t\t}\n\t\t}\n\t}\n\tif err := os.WriteFile(resolvePath, []byte(dnsString), 0600); err != nil {\n\t\tklog.ErrorS(err, \"Could not write dns nameserver in the file\", \"path\", resolvePath)\n\t}\n}","line":{"from":458,"to":486}} {"id":100007191,"name":"fileExists","signature":"func fileExists(filename string) (bool, error)","file":"pkg/kubelet/network/dns/dns_windows.go","code":"func fileExists(filename string) (bool, error) {\n\tstat, err := os.Stat(filename)\n\tif os.IsNotExist(err) {\n\t\treturn false, nil\n\t}\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn stat.Mode().IsRegular(), nil\n}","line":{"from":67,"to":77}} {"id":100007192,"name":"getHostDNSConfig","signature":"func getHostDNSConfig(resolverConfig string) (*runtimeapi.DNSConfig, error)","file":"pkg/kubelet/network/dns/dns_windows.go","code":"func getHostDNSConfig(resolverConfig string) (*runtimeapi.DNSConfig, error) {\n\tif resolverConfig == \"\" {\n\t\t// This handles \"\" by returning defaults.\n\t\treturn getDNSConfig(resolverConfig)\n\t}\n\n\tisFile, err := fileExists(resolverConfig)\n\tif err != nil {\n\t\terr = fmt.Errorf(`Unexpected error while getting os.Stat for \"%s\" resolver config. Error: %w`, resolverConfig, err)\n\t\tklog.ErrorS(err, \"Cannot get host DNS Configuration.\")\n\t\treturn nil, err\n\t}\n\tif isFile {\n\t\t// Get the DNS config from a resolv.conf-like file.\n\t\treturn getDNSConfig(resolverConfig)\n\t}\n\n\tif resolverConfig != hostResolvConf {\n\t\terr := fmt.Errorf(`Unexpected resolver config value: \"%s\". Expected \"\", \"%s\", or a path to an existing resolv.conf file.`, resolverConfig, hostResolvConf)\n\t\tklog.ErrorS(err, \"Cannot get host DNS Configuration.\")\n\t\treturn nil, err\n\t}\n\n\t// If we get here, the resolverConfig == hostResolvConf and that is not actually a file, so\n\t// it means to use the host settings.\n\t// Get host DNS settings\n\thostDNS, err := getDNSServerList()\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Could not get the host's DNS Server List. Error: %w\", err)\n\t\tklog.ErrorS(err, \"Encountered error while getting host's DNS Server List.\")\n\t\treturn nil, err\n\t}\n\thostSearch, err := getDNSSuffixList()\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Could not get the host's DNS Suffix List. Error: %w\", err)\n\t\tklog.ErrorS(err, \"Encountered error while getting host's DNS Suffix List.\")\n\t\treturn nil, err\n\t}\n\treturn \u0026runtimeapi.DNSConfig{\n\t\tServers: hostDNS,\n\t\tSearches: hostSearch,\n\t}, nil\n}","line":{"from":79,"to":121}} {"id":100007193,"name":"elemInList","signature":"func elemInList(elem string, list []string) bool","file":"pkg/kubelet/network/dns/dns_windows.go","code":"func elemInList(elem string, list []string) bool {\n\tfor _, e := range list {\n\t\tif e == elem {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":123,"to":130}} {"id":100007194,"name":"getRegistryStringValue","signature":"func getRegistryStringValue(reg, key string) (string, error)","file":"pkg/kubelet/network/dns/dns_windows.go","code":"func getRegistryStringValue(reg, key string) (string, error) {\n\tregKey, err := registry.OpenKey(registry.LOCAL_MACHINE, reg, registry.QUERY_VALUE)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer regKey.Close()\n\n\tregValue, _, err := regKey.GetStringValue(key)\n\treturn regValue, err\n}","line":{"from":132,"to":141}} {"id":100007195,"name":"getDNSSuffixList","signature":"func getDNSSuffixList() ([]string, error)","file":"pkg/kubelet/network/dns/dns_windows.go","code":"// getDNSSuffixList reads DNS config file and returns the list of configured DNS suffixes\nfunc getDNSSuffixList() ([]string, error) {\n\t// We start with the general suffix list that apply to all network connections.\n\tallSuffixes := []string{}\n\tsuffixes, err := getRegistryStringValue(netRegistry, \"SearchList\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tallSuffixes = strings.Split(suffixes, \",\")\n\n\t// Then we append the network-specific DNS suffix lists.\n\tregKey, err := registry.OpenKey(registry.LOCAL_MACHINE, netIfacesRegistry, registry.ENUMERATE_SUB_KEYS)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer regKey.Close()\n\n\tifaces, err := regKey.ReadSubKeyNames(0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, iface := range ifaces {\n\t\tsuffixes, err := getRegistryStringValue(fmt.Sprintf(\"%s\\\\%s\", netIfacesRegistry, iface), \"SearchList\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif suffixes == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, suffix := range strings.Split(suffixes, \",\") {\n\t\t\tif !elemInList(suffix, allSuffixes) {\n\t\t\t\tallSuffixes = append(allSuffixes, suffix)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allSuffixes, nil\n}","line":{"from":143,"to":180}} {"id":100007196,"name":"getNetworkParams","signature":"func getNetworkParams() (*FixedInfo, error)","file":"pkg/kubelet/network/dns/dns_windows.go","code":"func getNetworkParams() (*FixedInfo, error) {\n\t// We don't know how big we should make the byte buffer, but the call will tell us by\n\t// setting the size afterwards.\n\tvar size int = 1\n\tbuffer := make([]byte, 1)\n\tret, _, err := procGetNetworkParams.Call(\n\t\tuintptr(unsafe.Pointer(\u0026buffer[0])),\n\t\tuintptr(unsafe.Pointer(\u0026size)),\n\t)\n\tif ret != uintptr(syscall.ERROR_BUFFER_OVERFLOW) {\n\t\terr = fmt.Errorf(\"Unexpected return value %d from GetNetworkParams. Expected: %d. Error: %w\", ret, syscall.ERROR_BUFFER_OVERFLOW, err)\n\t\treturn nil, err\n\t}\n\n\tbuffer = make([]byte, size)\n\tret, _, err = procGetNetworkParams.Call(\n\t\tuintptr(unsafe.Pointer(\u0026buffer[0])),\n\t\tuintptr(unsafe.Pointer(\u0026size)),\n\t)\n\tif ret != 0 {\n\t\terr = fmt.Errorf(\"Unexpected return value %d from GetNetworkParams. Expected: 0. Error: %w\", ret, err)\n\t\treturn nil, err\n\t}\n\n\tinfo := (*FixedInfo)(unsafe.Pointer(\u0026buffer[0]))\n\treturn info, nil\n}","line":{"from":182,"to":208}} {"id":100007197,"name":"getDNSServerList","signature":"func getDNSServerList() ([]string, error)","file":"pkg/kubelet/network/dns/dns_windows.go","code":"func getDNSServerList() ([]string, error) {\n\tdnsServerList := []string{}\n\tfixedInfo, err := getNetworkParams()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlist := \u0026(fixedInfo.DNSServerList)\n\tfor list != nil {\n\t\tdnsServer := strings.TrimRight(string(list.IpAddress.String[:]), \"\\x00\")\n\t\tdnsServerList = append(dnsServerList, dnsServer)\n\t\tlist = list.Next\n\t}\n\treturn dnsServerList, nil\n}","line":{"from":210,"to":224}} {"id":100007198,"name":"Admit","signature":"func (managerStub) Admit(attrs *lifecycle.PodAdmitAttributes) lifecycle.PodAdmitResult","file":"pkg/kubelet/nodeshutdown/nodeshutdown_manager.go","code":"// Admit returns a fake Pod admission which always returns true\nfunc (managerStub) Admit(attrs *lifecycle.PodAdmitAttributes) lifecycle.PodAdmitResult {\n\treturn lifecycle.PodAdmitResult{Admit: true}\n}","line":{"from":58,"to":61}} {"id":100007199,"name":"Start","signature":"func (managerStub) Start() error","file":"pkg/kubelet/nodeshutdown/nodeshutdown_manager.go","code":"// Start is a no-op always returning nil for non linux platforms.\nfunc (managerStub) Start() error {\n\treturn nil\n}","line":{"from":63,"to":66}} {"id":100007200,"name":"ShutdownStatus","signature":"func (managerStub) ShutdownStatus() error","file":"pkg/kubelet/nodeshutdown/nodeshutdown_manager.go","code":"// ShutdownStatus is a no-op always returning nil for non linux platforms.\nfunc (managerStub) ShutdownStatus() error {\n\treturn nil\n}","line":{"from":68,"to":71}} {"id":100007201,"name":"NewManager","signature":"func NewManager(conf *Config) (Manager, lifecycle.PodAdmitHandler)","file":"pkg/kubelet/nodeshutdown/nodeshutdown_manager_linux.go","code":"// NewManager returns a new node shutdown manager.\nfunc NewManager(conf *Config) (Manager, lifecycle.PodAdmitHandler) {\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.GracefulNodeShutdown) {\n\t\tm := managerStub{}\n\t\treturn m, m\n\t}\n\n\tshutdownGracePeriodByPodPriority := conf.ShutdownGracePeriodByPodPriority\n\t// Migration from the original configuration\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.GracefulNodeShutdownBasedOnPodPriority) ||\n\t\tlen(shutdownGracePeriodByPodPriority) == 0 {\n\t\tshutdownGracePeriodByPodPriority = migrateConfig(conf.ShutdownGracePeriodRequested, conf.ShutdownGracePeriodCriticalPods)\n\t}\n\n\t// Disable if the configuration is empty\n\tif len(shutdownGracePeriodByPodPriority) == 0 {\n\t\tm := managerStub{}\n\t\treturn m, m\n\t}\n\n\t// Sort by priority from low to high\n\tsort.Slice(shutdownGracePeriodByPodPriority, func(i, j int) bool {\n\t\treturn shutdownGracePeriodByPodPriority[i].Priority \u003c shutdownGracePeriodByPodPriority[j].Priority\n\t})\n\n\tif conf.Clock == nil {\n\t\tconf.Clock = clock.RealClock{}\n\t}\n\tmanager := \u0026managerImpl{\n\t\tlogger: conf.Logger,\n\t\tprobeManager: conf.ProbeManager,\n\t\trecorder: conf.Recorder,\n\t\tnodeRef: conf.NodeRef,\n\t\tgetPods: conf.GetPodsFunc,\n\t\tkillPodFunc: conf.KillPodFunc,\n\t\tsyncNodeStatus: conf.SyncNodeStatusFunc,\n\t\tshutdownGracePeriodByPodPriority: shutdownGracePeriodByPodPriority,\n\t\tclock: conf.Clock,\n\t\tenableMetrics: utilfeature.DefaultFeatureGate.Enabled(features.GracefulNodeShutdownBasedOnPodPriority),\n\t\tstorage: localStorage{\n\t\t\tPath: filepath.Join(conf.StateDirectory, localStorageStateFile),\n\t\t},\n\t}\n\tmanager.logger.Info(\"Creating node shutdown manager\",\n\t\t\"shutdownGracePeriodRequested\", conf.ShutdownGracePeriodRequested,\n\t\t\"shutdownGracePeriodCriticalPods\", conf.ShutdownGracePeriodCriticalPods,\n\t\t\"shutdownGracePeriodByPodPriority\", shutdownGracePeriodByPodPriority,\n\t)\n\treturn manager, manager\n}","line":{"from":94,"to":143}} {"id":100007202,"name":"Admit","signature":"func (m *managerImpl) Admit(attrs *lifecycle.PodAdmitAttributes) lifecycle.PodAdmitResult","file":"pkg/kubelet/nodeshutdown/nodeshutdown_manager_linux.go","code":"// Admit rejects all pods if node is shutting\nfunc (m *managerImpl) Admit(attrs *lifecycle.PodAdmitAttributes) lifecycle.PodAdmitResult {\n\tnodeShuttingDown := m.ShutdownStatus() != nil\n\n\tif nodeShuttingDown {\n\t\treturn lifecycle.PodAdmitResult{\n\t\t\tAdmit: false,\n\t\t\tReason: nodeShutdownNotAdmittedReason,\n\t\t\tMessage: nodeShutdownNotAdmittedMessage,\n\t\t}\n\t}\n\treturn lifecycle.PodAdmitResult{Admit: true}\n}","line":{"from":145,"to":157}} {"id":100007203,"name":"setMetrics","signature":"func (m *managerImpl) setMetrics()","file":"pkg/kubelet/nodeshutdown/nodeshutdown_manager_linux.go","code":"// setMetrics sets the metrics for the node shutdown manager.\nfunc (m *managerImpl) setMetrics() {\n\tif m.enableMetrics \u0026\u0026 m.storage != nil {\n\t\tsta := state{}\n\t\terr := m.storage.Load(\u0026sta)\n\t\tif err != nil {\n\t\t\tm.logger.Error(err, \"Failed to load graceful shutdown state\")\n\t\t} else {\n\t\t\tif !sta.StartTime.IsZero() {\n\t\t\t\tmetrics.GracefulShutdownStartTime.Set(timestamp(sta.StartTime))\n\t\t\t}\n\t\t\tif !sta.EndTime.IsZero() {\n\t\t\t\tmetrics.GracefulShutdownEndTime.Set(timestamp(sta.EndTime))\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":159,"to":175}} {"id":100007204,"name":"Start","signature":"func (m *managerImpl) Start() error","file":"pkg/kubelet/nodeshutdown/nodeshutdown_manager_linux.go","code":"// Start starts the node shutdown manager and will start watching the node for shutdown events.\nfunc (m *managerImpl) Start() error {\n\tstop, err := m.start()\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo func() {\n\t\tfor {\n\t\t\tif stop != nil {\n\t\t\t\t\u003c-stop\n\t\t\t}\n\n\t\t\ttime.Sleep(dbusReconnectPeriod)\n\t\t\tm.logger.V(1).Info(\"Restarting watch for node shutdown events\")\n\t\t\tstop, err = m.start()\n\t\t\tif err != nil {\n\t\t\t\tm.logger.Error(err, \"Unable to watch the node for shutdown events\")\n\t\t\t}\n\t\t}\n\t}()\n\n\tm.setMetrics()\n\treturn nil\n}","line":{"from":177,"to":200}} {"id":100007205,"name":"start","signature":"func (m *managerImpl) start() (chan struct{}, error)","file":"pkg/kubelet/nodeshutdown/nodeshutdown_manager_linux.go","code":"func (m *managerImpl) start() (chan struct{}, error) {\n\tsystemBus, err := systemDbus()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tm.dbusCon = systemBus\n\n\tcurrentInhibitDelay, err := m.dbusCon.CurrentInhibitDelay()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// If the logind's InhibitDelayMaxUSec as configured in (logind.conf) is less than periodRequested, attempt to update the value to periodRequested.\n\tif periodRequested := m.periodRequested(); periodRequested \u003e currentInhibitDelay {\n\t\terr := m.dbusCon.OverrideInhibitDelay(periodRequested)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to override inhibit delay by shutdown manager: %v\", err)\n\t\t}\n\n\t\terr = m.dbusCon.ReloadLogindConf()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Read the current inhibitDelay again, if the override was successful, currentInhibitDelay will be equal to shutdownGracePeriodRequested.\n\t\tupdatedInhibitDelay, err := m.dbusCon.CurrentInhibitDelay()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif periodRequested \u003e updatedInhibitDelay {\n\t\t\treturn nil, fmt.Errorf(\"node shutdown manager was unable to update logind InhibitDelayMaxSec to %v (ShutdownGracePeriod), current value of InhibitDelayMaxSec (%v) is less than requested ShutdownGracePeriod\", periodRequested, updatedInhibitDelay)\n\t\t}\n\t}\n\n\terr = m.aquireInhibitLock()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tevents, err := m.dbusCon.MonitorShutdown()\n\tif err != nil {\n\t\treleaseErr := m.dbusCon.ReleaseInhibitLock(m.inhibitLock)\n\t\tif releaseErr != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed releasing inhibitLock: %v and failed monitoring shutdown: %v\", releaseErr, err)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"failed to monitor shutdown: %v\", err)\n\t}\n\n\tstop := make(chan struct{})\n\tgo func() {\n\t\t// Monitor for shutdown events. This follows the logind Inhibit Delay pattern described on https://www.freedesktop.org/wiki/Software/systemd/inhibit/\n\t\t// 1. When shutdown manager starts, an inhibit lock is taken.\n\t\t// 2. When shutdown(true) event is received, process the shutdown and release the inhibit lock.\n\t\t// 3. When shutdown(false) event is received, this indicates a previous shutdown was cancelled. In this case, acquire the inhibit lock again.\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase isShuttingDown, ok := \u003c-events:\n\t\t\t\tif !ok {\n\t\t\t\t\tm.logger.Error(err, \"Ended to watching the node for shutdown events\")\n\t\t\t\t\tclose(stop)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tm.logger.V(1).Info(\"Shutdown manager detected new shutdown event, isNodeShuttingDownNow\", \"event\", isShuttingDown)\n\n\t\t\t\tvar shutdownType string\n\t\t\t\tif isShuttingDown {\n\t\t\t\t\tshutdownType = \"shutdown\"\n\t\t\t\t} else {\n\t\t\t\t\tshutdownType = \"cancelled\"\n\t\t\t\t}\n\t\t\t\tm.logger.V(1).Info(\"Shutdown manager detected new shutdown event\", \"event\", shutdownType)\n\t\t\t\tif isShuttingDown {\n\t\t\t\t\tm.recorder.Event(m.nodeRef, v1.EventTypeNormal, kubeletevents.NodeShutdown, \"Shutdown manager detected shutdown event\")\n\t\t\t\t} else {\n\t\t\t\t\tm.recorder.Event(m.nodeRef, v1.EventTypeNormal, kubeletevents.NodeShutdown, \"Shutdown manager detected shutdown cancellation\")\n\t\t\t\t}\n\n\t\t\t\tm.nodeShuttingDownMutex.Lock()\n\t\t\t\tm.nodeShuttingDownNow = isShuttingDown\n\t\t\t\tm.nodeShuttingDownMutex.Unlock()\n\n\t\t\t\tif isShuttingDown {\n\t\t\t\t\t// Update node status and ready condition\n\t\t\t\t\tgo m.syncNodeStatus()\n\n\t\t\t\t\tm.processShutdownEvent()\n\t\t\t\t} else {\n\t\t\t\t\tm.aquireInhibitLock()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\treturn stop, nil\n}","line":{"from":202,"to":296}} {"id":100007206,"name":"aquireInhibitLock","signature":"func (m *managerImpl) aquireInhibitLock() error","file":"pkg/kubelet/nodeshutdown/nodeshutdown_manager_linux.go","code":"func (m *managerImpl) aquireInhibitLock() error {\n\tlock, err := m.dbusCon.InhibitShutdown()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif m.inhibitLock != 0 {\n\t\tm.dbusCon.ReleaseInhibitLock(m.inhibitLock)\n\t}\n\tm.inhibitLock = lock\n\treturn nil\n}","line":{"from":298,"to":308}} {"id":100007207,"name":"ShutdownStatus","signature":"func (m *managerImpl) ShutdownStatus() error","file":"pkg/kubelet/nodeshutdown/nodeshutdown_manager_linux.go","code":"// ShutdownStatus will return an error if the node is currently shutting down.\nfunc (m *managerImpl) ShutdownStatus() error {\n\tm.nodeShuttingDownMutex.Lock()\n\tdefer m.nodeShuttingDownMutex.Unlock()\n\n\tif m.nodeShuttingDownNow {\n\t\treturn fmt.Errorf(\"node is shutting down\")\n\t}\n\treturn nil\n}","line":{"from":310,"to":319}} {"id":100007208,"name":"processShutdownEvent","signature":"func (m *managerImpl) processShutdownEvent() error","file":"pkg/kubelet/nodeshutdown/nodeshutdown_manager_linux.go","code":"func (m *managerImpl) processShutdownEvent() error {\n\tm.logger.V(1).Info(\"Shutdown manager processing shutdown event\")\n\tactivePods := m.getPods()\n\n\tdefer func() {\n\t\tm.dbusCon.ReleaseInhibitLock(m.inhibitLock)\n\t\tm.logger.V(1).Info(\"Shutdown manager completed processing shutdown event, node will shutdown shortly\")\n\t}()\n\n\tif m.enableMetrics \u0026\u0026 m.storage != nil {\n\t\tstartTime := time.Now()\n\t\terr := m.storage.Store(state{\n\t\t\tStartTime: startTime,\n\t\t})\n\t\tif err != nil {\n\t\t\tm.logger.Error(err, \"Failed to store graceful shutdown state\")\n\t\t}\n\t\tmetrics.GracefulShutdownStartTime.Set(timestamp(startTime))\n\t\tmetrics.GracefulShutdownEndTime.Set(0)\n\n\t\tdefer func() {\n\t\t\tendTime := time.Now()\n\t\t\terr := m.storage.Store(state{\n\t\t\t\tStartTime: startTime,\n\t\t\t\tEndTime: endTime,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tm.logger.Error(err, \"Failed to store graceful shutdown state\")\n\t\t\t}\n\t\t\tmetrics.GracefulShutdownStartTime.Set(timestamp(endTime))\n\t\t}()\n\t}\n\n\tgroups := groupByPriority(m.shutdownGracePeriodByPodPriority, activePods)\n\tfor _, group := range groups {\n\t\t// If there are no pods in a particular range,\n\t\t// then do not wait for pods in that priority range.\n\t\tif len(group.Pods) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(len(group.Pods))\n\t\tfor _, pod := range group.Pods {\n\t\t\tgo func(pod *v1.Pod, group podShutdownGroup) {\n\t\t\t\tdefer wg.Done()\n\n\t\t\t\tgracePeriodOverride := group.ShutdownGracePeriodSeconds\n\n\t\t\t\t// If the pod's spec specifies a termination gracePeriod which is less than the gracePeriodOverride calculated, use the pod spec termination gracePeriod.\n\t\t\t\tif pod.Spec.TerminationGracePeriodSeconds != nil \u0026\u0026 *pod.Spec.TerminationGracePeriodSeconds \u003c= gracePeriodOverride {\n\t\t\t\t\tgracePeriodOverride = *pod.Spec.TerminationGracePeriodSeconds\n\t\t\t\t}\n\n\t\t\t\tm.logger.V(1).Info(\"Shutdown manager killing pod with gracePeriod\", \"pod\", klog.KObj(pod), \"gracePeriod\", gracePeriodOverride)\n\n\t\t\t\tif err := m.killPodFunc(pod, false, \u0026gracePeriodOverride, func(status *v1.PodStatus) {\n\t\t\t\t\t// set the pod status to failed (unless it was already in a successful terminal phase)\n\t\t\t\t\tif status.Phase != v1.PodSucceeded {\n\t\t\t\t\t\tstatus.Phase = v1.PodFailed\n\t\t\t\t\t}\n\t\t\t\t\tstatus.Message = nodeShutdownMessage\n\t\t\t\t\tstatus.Reason = nodeShutdownReason\n\t\t\t\t\tif utilfeature.DefaultFeatureGate.Enabled(features.PodDisruptionConditions) {\n\t\t\t\t\t\tpodutil.UpdatePodCondition(status, \u0026v1.PodCondition{\n\t\t\t\t\t\t\tType: v1.DisruptionTarget,\n\t\t\t\t\t\t\tStatus: v1.ConditionTrue,\n\t\t\t\t\t\t\tReason: v1.PodReasonTerminationByKubelet,\n\t\t\t\t\t\t\tMessage: nodeShutdownMessage,\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}); err != nil {\n\t\t\t\t\tm.logger.V(1).Info(\"Shutdown manager failed killing pod\", \"pod\", klog.KObj(pod), \"err\", err)\n\t\t\t\t} else {\n\t\t\t\t\tm.logger.V(1).Info(\"Shutdown manager finished killing pod\", \"pod\", klog.KObj(pod))\n\t\t\t\t}\n\t\t\t}(pod, group)\n\t\t}\n\n\t\tvar (\n\t\t\tdoneCh = make(chan struct{})\n\t\t\ttimer = m.clock.NewTimer(time.Duration(group.ShutdownGracePeriodSeconds) * time.Second)\n\t\t)\n\t\tgo func() {\n\t\t\tdefer close(doneCh)\n\t\t\twg.Wait()\n\t\t}()\n\n\t\tselect {\n\t\tcase \u003c-doneCh:\n\t\t\ttimer.Stop()\n\t\tcase \u003c-timer.C():\n\t\t\tm.logger.V(1).Info(\"Shutdown manager pod killing time out\", \"gracePeriod\", group.ShutdownGracePeriodSeconds, \"priority\", group.Priority)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":321,"to":418}} {"id":100007209,"name":"periodRequested","signature":"func (m *managerImpl) periodRequested() time.Duration","file":"pkg/kubelet/nodeshutdown/nodeshutdown_manager_linux.go","code":"func (m *managerImpl) periodRequested() time.Duration {\n\tvar sum int64\n\tfor _, period := range m.shutdownGracePeriodByPodPriority {\n\t\tsum += period.ShutdownGracePeriodSeconds\n\t}\n\treturn time.Duration(sum) * time.Second\n}","line":{"from":420,"to":426}} {"id":100007210,"name":"migrateConfig","signature":"func migrateConfig(shutdownGracePeriodRequested, shutdownGracePeriodCriticalPods time.Duration) []kubeletconfig.ShutdownGracePeriodByPodPriority","file":"pkg/kubelet/nodeshutdown/nodeshutdown_manager_linux.go","code":"func migrateConfig(shutdownGracePeriodRequested, shutdownGracePeriodCriticalPods time.Duration) []kubeletconfig.ShutdownGracePeriodByPodPriority {\n\tif shutdownGracePeriodRequested == 0 {\n\t\treturn nil\n\t}\n\tdefaultPriority := shutdownGracePeriodRequested - shutdownGracePeriodCriticalPods\n\tif defaultPriority \u003c 0 {\n\t\treturn nil\n\t}\n\tcriticalPriority := shutdownGracePeriodRequested - defaultPriority\n\tif criticalPriority \u003c 0 {\n\t\treturn nil\n\t}\n\treturn []kubeletconfig.ShutdownGracePeriodByPodPriority{\n\t\t{\n\t\t\tPriority: scheduling.DefaultPriorityWhenNoDefaultClassExists,\n\t\t\tShutdownGracePeriodSeconds: int64(defaultPriority / time.Second),\n\t\t},\n\t\t{\n\t\t\tPriority: scheduling.SystemCriticalPriority,\n\t\t\tShutdownGracePeriodSeconds: int64(criticalPriority / time.Second),\n\t\t},\n\t}\n}","line":{"from":428,"to":450}} {"id":100007211,"name":"groupByPriority","signature":"func groupByPriority(shutdownGracePeriodByPodPriority []kubeletconfig.ShutdownGracePeriodByPodPriority, pods []*v1.Pod) []podShutdownGroup","file":"pkg/kubelet/nodeshutdown/nodeshutdown_manager_linux.go","code":"func groupByPriority(shutdownGracePeriodByPodPriority []kubeletconfig.ShutdownGracePeriodByPodPriority, pods []*v1.Pod) []podShutdownGroup {\n\tgroups := make([]podShutdownGroup, 0, len(shutdownGracePeriodByPodPriority))\n\tfor _, period := range shutdownGracePeriodByPodPriority {\n\t\tgroups = append(groups, podShutdownGroup{\n\t\t\tShutdownGracePeriodByPodPriority: period,\n\t\t})\n\t}\n\n\tfor _, pod := range pods {\n\t\tvar priority int32\n\t\tif pod.Spec.Priority != nil {\n\t\t\tpriority = *pod.Spec.Priority\n\t\t}\n\n\t\t// Find the group index according to the priority.\n\t\tindex := sort.Search(len(groups), func(i int) bool {\n\t\t\treturn groups[i].Priority \u003e= priority\n\t\t})\n\n\t\t// 1. Those higher than the highest priority default to the highest priority\n\t\t// 2. Those lower than the lowest priority default to the lowest priority\n\t\t// 3. Those boundary priority default to the lower priority\n\t\t// if priority of pod is:\n\t\t// groups[index-1].Priority \u003c= pod priority \u003c groups[index].Priority\n\t\t// in which case we want to pick lower one (i.e index-1)\n\t\tif index == len(groups) {\n\t\t\tindex = len(groups) - 1\n\t\t} else if index \u003c 0 {\n\t\t\tindex = 0\n\t\t} else if index \u003e 0 \u0026\u0026 groups[index].Priority \u003e priority {\n\t\t\tindex--\n\t\t}\n\n\t\tgroups[index].Pods = append(groups[index].Pods, pod)\n\t}\n\treturn groups\n}","line":{"from":452,"to":488}} {"id":100007212,"name":"NewManager","signature":"func NewManager(conf *Config) (Manager, lifecycle.PodAdmitHandler)","file":"pkg/kubelet/nodeshutdown/nodeshutdown_manager_others.go","code":"// NewManager returns a fake node shutdown manager for non linux platforms.\nfunc NewManager(conf *Config) (Manager, lifecycle.PodAdmitHandler) {\n\tm := managerStub{}\n\treturn m, m\n}","line":{"from":26,"to":30}} {"id":100007213,"name":"Store","signature":"func (l localStorage) Store(data interface{}) (err error)","file":"pkg/kubelet/nodeshutdown/storage.go","code":"func (l localStorage) Store(data interface{}) (err error) {\n\tb, err := json.Marshal(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn atomicWrite(l.Path, b, 0644)\n}","line":{"from":36,"to":42}} {"id":100007214,"name":"Load","signature":"func (l localStorage) Load(data interface{}) (err error)","file":"pkg/kubelet/nodeshutdown/storage.go","code":"func (l localStorage) Load(data interface{}) (err error) {\n\tb, err := os.ReadFile(l.Path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\treturn json.Unmarshal(b, data)\n}","line":{"from":44,"to":53}} {"id":100007215,"name":"timestamp","signature":"func timestamp(t time.Time) float64","file":"pkg/kubelet/nodeshutdown/storage.go","code":"func timestamp(t time.Time) float64 {\n\tif t.IsZero() {\n\t\treturn 0\n\t}\n\treturn float64(t.Unix())\n}","line":{"from":55,"to":60}} {"id":100007216,"name":"atomicWrite","signature":"func atomicWrite(filename string, data []byte, perm os.FileMode) error","file":"pkg/kubelet/nodeshutdown/storage.go","code":"// atomicWrite atomically writes data to a file specified by filename.\nfunc atomicWrite(filename string, data []byte, perm os.FileMode) error {\n\tf, err := os.CreateTemp(filepath.Dir(filename), \".tmp-\"+filepath.Base(filename))\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.Chmod(f.Name(), perm)\n\tif err != nil {\n\t\tf.Close()\n\t\treturn err\n\t}\n\tn, err := f.Write(data)\n\tif err != nil {\n\t\tf.Close()\n\t\treturn err\n\t}\n\tif n \u003c len(data) {\n\t\tf.Close()\n\t\treturn io.ErrShortWrite\n\t}\n\tif err := f.Sync(); err != nil {\n\t\tf.Close()\n\t\treturn err\n\t}\n\tif err := f.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn os.Rename(f.Name(), filename)\n}","line":{"from":67,"to":95}} {"id":100007217,"name":"NewDBusCon","signature":"func NewDBusCon() (*DBusCon, error)","file":"pkg/kubelet/nodeshutdown/systemd/inhibit_linux.go","code":"func NewDBusCon() (*DBusCon, error) {\n\tconn, err := dbus.SystemBus()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026DBusCon{\n\t\tSystemBus: conn,\n\t}, nil\n}","line":{"from":50,"to":59}} {"id":100007218,"name":"CurrentInhibitDelay","signature":"func (bus *DBusCon) CurrentInhibitDelay() (time.Duration, error)","file":"pkg/kubelet/nodeshutdown/systemd/inhibit_linux.go","code":"// CurrentInhibitDelay returns the current delay inhibitor timeout value as configured in logind.conf(5).\n// see https://www.freedesktop.org/software/systemd/man/logind.conf.html for more details.\nfunc (bus *DBusCon) CurrentInhibitDelay() (time.Duration, error) {\n\tobj := bus.SystemBus.Object(logindService, logindObject)\n\tres, err := obj.GetProperty(logindInterface + \".InhibitDelayMaxUSec\")\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"failed reading InhibitDelayMaxUSec property from logind: %w\", err)\n\t}\n\n\tdelay, ok := res.Value().(uint64)\n\tif !ok {\n\t\treturn 0, fmt.Errorf(\"InhibitDelayMaxUSec from logind is not a uint64 as expected\")\n\t}\n\n\t// InhibitDelayMaxUSec is in microseconds\n\tduration := time.Duration(delay) * time.Microsecond\n\treturn duration, nil\n}","line":{"from":64,"to":81}} {"id":100007219,"name":"InhibitShutdown","signature":"func (bus *DBusCon) InhibitShutdown() (InhibitLock, error)","file":"pkg/kubelet/nodeshutdown/systemd/inhibit_linux.go","code":"// InhibitShutdown creates an systemd inhibitor by calling logind's Inhibt() and returns the inhibitor lock\n// see https://www.freedesktop.org/wiki/Software/systemd/inhibit/ for more details.\nfunc (bus *DBusCon) InhibitShutdown() (InhibitLock, error) {\n\tobj := bus.SystemBus.Object(logindService, logindObject)\n\twhat := \"shutdown\"\n\twho := \"kubelet\"\n\twhy := \"Kubelet needs time to handle node shutdown\"\n\tmode := \"delay\"\n\n\tcall := obj.Call(\"org.freedesktop.login1.Manager.Inhibit\", 0, what, who, why, mode)\n\tif call.Err != nil {\n\t\treturn InhibitLock(0), fmt.Errorf(\"failed creating systemd inhibitor: %w\", call.Err)\n\t}\n\n\tvar fd uint32\n\terr := call.Store(\u0026fd)\n\tif err != nil {\n\t\treturn InhibitLock(0), fmt.Errorf(\"failed storing inhibit lock file descriptor: %w\", err)\n\t}\n\n\treturn InhibitLock(fd), nil\n}","line":{"from":83,"to":104}} {"id":100007220,"name":"ReleaseInhibitLock","signature":"func (bus *DBusCon) ReleaseInhibitLock(lock InhibitLock) error","file":"pkg/kubelet/nodeshutdown/systemd/inhibit_linux.go","code":"// ReleaseInhibitLock will release the underlying inhibit lock which will cause the shutdown to start.\nfunc (bus *DBusCon) ReleaseInhibitLock(lock InhibitLock) error {\n\terr := syscall.Close(int(lock))\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to close systemd inhibitor lock: %w\", err)\n\t}\n\n\treturn nil\n}","line":{"from":106,"to":115}} {"id":100007221,"name":"ReloadLogindConf","signature":"func (bus *DBusCon) ReloadLogindConf() error","file":"pkg/kubelet/nodeshutdown/systemd/inhibit_linux.go","code":"// ReloadLogindConf uses dbus to send a SIGHUP to the systemd-logind service causing logind to reload it's configuration.\nfunc (bus *DBusCon) ReloadLogindConf() error {\n\tsystemdService := \"org.freedesktop.systemd1\"\n\tsystemdObject := \"/org/freedesktop/systemd1\"\n\tsystemdInterface := \"org.freedesktop.systemd1.Manager\"\n\n\tobj := bus.SystemBus.Object(systemdService, dbus.ObjectPath(systemdObject))\n\tunit := \"systemd-logind.service\"\n\twho := \"all\"\n\tvar signal int32 = 1 // SIGHUP\n\n\tcall := obj.Call(systemdInterface+\".KillUnit\", 0, unit, who, signal)\n\tif call.Err != nil {\n\t\treturn fmt.Errorf(\"unable to reload logind conf: %w\", call.Err)\n\t}\n\n\treturn nil\n}","line":{"from":117,"to":134}} {"id":100007222,"name":"MonitorShutdown","signature":"func (bus *DBusCon) MonitorShutdown() (\u003c-chan bool, error)","file":"pkg/kubelet/nodeshutdown/systemd/inhibit_linux.go","code":"// MonitorShutdown detects the a node shutdown by watching for \"PrepareForShutdown\" logind events.\n// see https://www.freedesktop.org/wiki/Software/systemd/inhibit/ for more details.\nfunc (bus *DBusCon) MonitorShutdown() (\u003c-chan bool, error) {\n\terr := bus.SystemBus.AddMatchSignal(dbus.WithMatchInterface(logindInterface), dbus.WithMatchMember(\"PrepareForShutdown\"), dbus.WithMatchObjectPath(\"/org/freedesktop/login1\"))\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbusChan := make(chan *dbus.Signal, 1)\n\tbus.SystemBus.Signal(busChan)\n\n\tshutdownChan := make(chan bool, 1)\n\n\tgo func() {\n\t\tfor {\n\t\t\tevent, ok := \u003c-busChan\n\t\t\tif !ok {\n\t\t\t\tclose(shutdownChan)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif event == nil || len(event.Body) == 0 {\n\t\t\t\tklog.ErrorS(nil, \"Failed obtaining shutdown event, PrepareForShutdown event was empty\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tshutdownActive, ok := event.Body[0].(bool)\n\t\t\tif !ok {\n\t\t\t\tklog.ErrorS(nil, \"Failed obtaining shutdown event, PrepareForShutdown event was not bool type as expected\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tshutdownChan \u003c- shutdownActive\n\t\t}\n\t}()\n\n\treturn shutdownChan, nil\n}","line":{"from":136,"to":171}} {"id":100007223,"name":"OverrideInhibitDelay","signature":"func (bus *DBusCon) OverrideInhibitDelay(inhibitDelayMax time.Duration) error","file":"pkg/kubelet/nodeshutdown/systemd/inhibit_linux.go","code":"// OverrideInhibitDelay writes a config file to logind overriding InhibitDelayMaxSec to the value desired.\nfunc (bus *DBusCon) OverrideInhibitDelay(inhibitDelayMax time.Duration) error {\n\terr := os.MkdirAll(logindConfigDirectory, 0755)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed creating %v directory: %w\", logindConfigDirectory, err)\n\t}\n\n\t// This attempts to set the `InhibitDelayMaxUSec` dbus property of logind which is MaxInhibitDelay measured in microseconds.\n\t// The corresponding logind config file property is named `InhibitDelayMaxSec` and is measured in seconds which is set via logind.conf config.\n\t// Refer to https://www.freedesktop.org/software/systemd/man/logind.conf.html for more details.\n\n\tinhibitOverride := fmt.Sprintf(`# Kubelet logind override\n[Login]\nInhibitDelayMaxSec=%.0f\n`, inhibitDelayMax.Seconds())\n\n\tlogindOverridePath := filepath.Join(logindConfigDirectory, kubeletLogindConf)\n\tif err := os.WriteFile(logindOverridePath, []byte(inhibitOverride), 0644); err != nil {\n\t\treturn fmt.Errorf(\"failed writing logind shutdown inhibit override file %v: %w\", logindOverridePath, err)\n\t}\n\n\treturn nil\n}","line":{"from":178,"to":200}} {"id":100007224,"name":"NodeAddress","signature":"func NodeAddress(nodeIPs []net.IP, // typically Kubelet.nodeIPs","file":"pkg/kubelet/nodestatus/setters.go","code":"// NodeAddress returns a Setter that updates address-related information on the node.\nfunc NodeAddress(nodeIPs []net.IP, // typically Kubelet.nodeIPs\n\tvalidateNodeIPFunc func(net.IP) error, // typically Kubelet.nodeIPValidator\n\thostname string, // typically Kubelet.hostname\n\thostnameOverridden bool, // was the hostname force set?\n\texternalCloudProvider bool, // typically Kubelet.externalCloudProvider\n\tcloud cloudprovider.Interface, // typically Kubelet.cloud\n\tnodeAddressesFunc func() ([]v1.NodeAddress, error), // typically Kubelet.cloudResourceSyncManager.NodeAddresses\n) Setter {\n\tvar nodeIP, secondaryNodeIP net.IP\n\tif len(nodeIPs) \u003e 0 {\n\t\tnodeIP = nodeIPs[0]\n\t}\n\tpreferIPv4 := nodeIP == nil || nodeIP.To4() != nil\n\tisPreferredIPFamily := func(ip net.IP) bool { return (ip.To4() != nil) == preferIPv4 }\n\tnodeIPSpecified := nodeIP != nil \u0026\u0026 !nodeIP.IsUnspecified()\n\n\tif len(nodeIPs) \u003e 1 {\n\t\tsecondaryNodeIP = nodeIPs[1]\n\t}\n\tsecondaryNodeIPSpecified := secondaryNodeIP != nil \u0026\u0026 !secondaryNodeIP.IsUnspecified()\n\n\treturn func(ctx context.Context, node *v1.Node) error {\n\t\tif nodeIPSpecified {\n\t\t\tif err := validateNodeIPFunc(nodeIP); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to validate nodeIP: %v\", err)\n\t\t\t}\n\t\t\tklog.V(4).InfoS(\"Using node IP\", \"IP\", nodeIP.String())\n\t\t}\n\t\tif secondaryNodeIPSpecified {\n\t\t\tif err := validateNodeIPFunc(secondaryNodeIP); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to validate secondaryNodeIP: %v\", err)\n\t\t\t}\n\t\t\tklog.V(4).InfoS(\"Using secondary node IP\", \"IP\", secondaryNodeIP.String())\n\t\t}\n\n\t\tif (externalCloudProvider || cloud != nil) \u0026\u0026 nodeIPSpecified {\n\t\t\t// Annotate the Node object with nodeIP for external cloud provider.\n\t\t\t//\n\t\t\t// We do this even when external CCM is not configured to cover a situation\n\t\t\t// during migration from legacy to external CCM: when CCM is running the\n\t\t\t// node controller in the cluster but kubelet is still running the in-tree\n\t\t\t// provider. Adding this annotation in all cases ensures that while\n\t\t\t// Addresses flap between the competing controllers, they at least flap\n\t\t\t// consistently.\n\t\t\t//\n\t\t\t// We do not add the annotation in the case where there is no cloud\n\t\t\t// controller at all, as we don't expect to migrate these clusters to use an\n\t\t\t// external CCM.\n\t\t\tif node.ObjectMeta.Annotations == nil {\n\t\t\t\tnode.ObjectMeta.Annotations = make(map[string]string)\n\t\t\t}\n\t\t\tannotation := nodeIP.String()\n\t\t\tif secondaryNodeIPSpecified {\n\t\t\t\tannotation += \",\" + secondaryNodeIP.String()\n\t\t\t}\n\t\t\tnode.ObjectMeta.Annotations[cloudproviderapi.AnnotationAlphaProvidedIPAddr] = annotation\n\t\t} else if node.ObjectMeta.Annotations != nil {\n\t\t\t// Clean up stale annotations if no longer using a cloud provider or\n\t\t\t// no longer overriding node IP.\n\t\t\tdelete(node.ObjectMeta.Annotations, cloudproviderapi.AnnotationAlphaProvidedIPAddr)\n\t\t}\n\n\t\tif externalCloudProvider {\n\t\t\t// If --cloud-provider=external and node address is already set,\n\t\t\t// then we return early because provider set addresses should take precedence.\n\t\t\t// Otherwise, we try to look up the node IP and let the cloud provider override it later\n\t\t\t// This should alleviate a lot of the bootstrapping issues with out-of-tree providers\n\t\t\tif len(node.Status.Addresses) \u003e 0 {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\tif cloud != nil {\n\t\t\tcloudNodeAddresses, err := nodeAddressesFunc()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tnodeAddresses, err := cloudprovidernodeutil.GetNodeAddressesFromNodeIPLegacy(nodeIP, cloudNodeAddresses)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tswitch {\n\t\t\tcase len(cloudNodeAddresses) == 0:\n\t\t\t\t// the cloud provider didn't specify any addresses\n\t\t\t\tnodeAddresses = append(nodeAddresses, v1.NodeAddress{Type: v1.NodeHostName, Address: hostname})\n\n\t\t\tcase !hasAddressType(cloudNodeAddresses, v1.NodeHostName) \u0026\u0026 hasAddressValue(cloudNodeAddresses, hostname):\n\t\t\t\t// the cloud provider didn't specify an address of type Hostname,\n\t\t\t\t// but the auto-detected hostname matched an address reported by the cloud provider,\n\t\t\t\t// so we can add it and count on the value being verifiable via cloud provider metadata\n\t\t\t\tnodeAddresses = append(nodeAddresses, v1.NodeAddress{Type: v1.NodeHostName, Address: hostname})\n\n\t\t\tcase hostnameOverridden:\n\t\t\t\t// the hostname was force-set via flag/config.\n\t\t\t\t// this means the hostname might not be able to be validated via cloud provider metadata,\n\t\t\t\t// but was a choice by the kubelet deployer we should honor\n\t\t\t\tvar existingHostnameAddress *v1.NodeAddress\n\t\t\t\tfor i := range nodeAddresses {\n\t\t\t\t\tif nodeAddresses[i].Type == v1.NodeHostName {\n\t\t\t\t\t\texistingHostnameAddress = \u0026nodeAddresses[i]\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif existingHostnameAddress == nil {\n\t\t\t\t\t// no existing Hostname address found, add it\n\t\t\t\t\tklog.InfoS(\"Adding overridden hostname to cloudprovider-reported addresses\", \"hostname\", hostname)\n\t\t\t\t\tnodeAddresses = append(nodeAddresses, v1.NodeAddress{Type: v1.NodeHostName, Address: hostname})\n\t\t\t\t} else if existingHostnameAddress.Address != hostname {\n\t\t\t\t\t// override the Hostname address reported by the cloud provider\n\t\t\t\t\tklog.InfoS(\"Replacing cloudprovider-reported hostname with overridden hostname\", \"cloudProviderHostname\", existingHostnameAddress.Address, \"overriddenHostname\", hostname)\n\t\t\t\t\texistingHostnameAddress.Address = hostname\n\t\t\t\t}\n\t\t\t}\n\t\t\tnode.Status.Addresses = nodeAddresses\n\t\t} else if nodeIPSpecified \u0026\u0026 secondaryNodeIPSpecified {\n\t\t\tnode.Status.Addresses = []v1.NodeAddress{\n\t\t\t\t{Type: v1.NodeInternalIP, Address: nodeIP.String()},\n\t\t\t\t{Type: v1.NodeInternalIP, Address: secondaryNodeIP.String()},\n\t\t\t\t{Type: v1.NodeHostName, Address: hostname},\n\t\t\t}\n\t\t} else {\n\t\t\tvar ipAddr net.IP\n\t\t\tvar err error\n\n\t\t\t// 1) Use nodeIP if set (and not \"0.0.0.0\"/\"::\")\n\t\t\t// 2) If the user has specified an IP to HostnameOverride, use it\n\t\t\t// 3) Lookup the IP from node name by DNS\n\t\t\t// 4) Try to get the IP from the network interface used as default gateway\n\t\t\t//\n\t\t\t// For steps 3 and 4, IPv4 addresses are preferred to IPv6 addresses\n\t\t\t// unless nodeIP is \"::\", in which case it is reversed.\n\t\t\tif nodeIPSpecified {\n\t\t\t\tipAddr = nodeIP\n\t\t\t} else if addr := netutils.ParseIPSloppy(hostname); addr != nil {\n\t\t\t\tipAddr = addr\n\t\t\t} else {\n\t\t\t\tvar addrs []net.IP\n\t\t\t\taddrs, _ = net.LookupIP(node.Name)\n\t\t\t\tfor _, addr := range addrs {\n\t\t\t\t\tif err = validateNodeIPFunc(addr); err == nil {\n\t\t\t\t\t\tif isPreferredIPFamily(addr) {\n\t\t\t\t\t\t\tipAddr = addr\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t} else if ipAddr == nil {\n\t\t\t\t\t\t\tipAddr = addr\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif ipAddr == nil {\n\t\t\t\t\tipAddr, err = utilnet.ResolveBindAddress(nodeIP)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ipAddr == nil {\n\t\t\t\t// We tried everything we could, but the IP address wasn't fetchable; error out\n\t\t\t\treturn fmt.Errorf(\"can't get ip address of node %s. error: %v\", node.Name, err)\n\t\t\t}\n\t\t\tnode.Status.Addresses = []v1.NodeAddress{\n\t\t\t\t{Type: v1.NodeInternalIP, Address: ipAddr.String()},\n\t\t\t\t{Type: v1.NodeHostName, Address: hostname},\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n}","line":{"from":60,"to":228}} {"id":100007225,"name":"hasAddressType","signature":"func hasAddressType(addresses []v1.NodeAddress, addressType v1.NodeAddressType) bool","file":"pkg/kubelet/nodestatus/setters.go","code":"func hasAddressType(addresses []v1.NodeAddress, addressType v1.NodeAddressType) bool {\n\tfor _, address := range addresses {\n\t\tif address.Type == addressType {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":230,"to":237}} {"id":100007226,"name":"hasAddressValue","signature":"func hasAddressValue(addresses []v1.NodeAddress, addressValue string) bool","file":"pkg/kubelet/nodestatus/setters.go","code":"func hasAddressValue(addresses []v1.NodeAddress, addressValue string) bool {\n\tfor _, address := range addresses {\n\t\tif address.Address == addressValue {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":238,"to":245}} {"id":100007227,"name":"MachineInfo","signature":"func MachineInfo(nodeName string,","file":"pkg/kubelet/nodestatus/setters.go","code":"// MachineInfo returns a Setter that updates machine-related information on the node.\nfunc MachineInfo(nodeName string,\n\tmaxPods int,\n\tpodsPerCore int,\n\tmachineInfoFunc func() (*cadvisorapiv1.MachineInfo, error), // typically Kubelet.GetCachedMachineInfo\n\tcapacityFunc func(localStorageCapacityIsolation bool) v1.ResourceList, // typically Kubelet.containerManager.GetCapacity\n\tdevicePluginResourceCapacityFunc func() (v1.ResourceList, v1.ResourceList, []string), // typically Kubelet.containerManager.GetDevicePluginResourceCapacity\n\tnodeAllocatableReservationFunc func() v1.ResourceList, // typically Kubelet.containerManager.GetNodeAllocatableReservation\n\trecordEventFunc func(eventType, event, message string), // typically Kubelet.recordEvent\n\tlocalStorageCapacityIsolation bool,\n) Setter {\n\treturn func(ctx context.Context, node *v1.Node) error {\n\t\t// Note: avoid blindly overwriting the capacity in case opaque\n\t\t// resources are being advertised.\n\t\tif node.Status.Capacity == nil {\n\t\t\tnode.Status.Capacity = v1.ResourceList{}\n\t\t}\n\n\t\tvar devicePluginAllocatable v1.ResourceList\n\t\tvar devicePluginCapacity v1.ResourceList\n\t\tvar removedDevicePlugins []string\n\n\t\t// TODO: Post NotReady if we cannot get MachineInfo from cAdvisor. This needs to start\n\t\t// cAdvisor locally, e.g. for test-cmd.sh, and in integration test.\n\t\tinfo, err := machineInfoFunc()\n\t\tif err != nil {\n\t\t\t// TODO(roberthbailey): This is required for test-cmd.sh to pass.\n\t\t\t// See if the test should be updated instead.\n\t\t\tnode.Status.Capacity[v1.ResourceCPU] = *resource.NewMilliQuantity(0, resource.DecimalSI)\n\t\t\tnode.Status.Capacity[v1.ResourceMemory] = resource.MustParse(\"0Gi\")\n\t\t\tnode.Status.Capacity[v1.ResourcePods] = *resource.NewQuantity(int64(maxPods), resource.DecimalSI)\n\t\t\tklog.ErrorS(err, \"Error getting machine info\")\n\t\t} else {\n\t\t\tnode.Status.NodeInfo.MachineID = info.MachineID\n\t\t\tnode.Status.NodeInfo.SystemUUID = info.SystemUUID\n\n\t\t\tfor rName, rCap := range cadvisor.CapacityFromMachineInfo(info) {\n\t\t\t\tnode.Status.Capacity[rName] = rCap\n\t\t\t}\n\n\t\t\tif podsPerCore \u003e 0 {\n\t\t\t\tnode.Status.Capacity[v1.ResourcePods] = *resource.NewQuantity(\n\t\t\t\t\tint64(math.Min(float64(info.NumCores*podsPerCore), float64(maxPods))), resource.DecimalSI)\n\t\t\t} else {\n\t\t\t\tnode.Status.Capacity[v1.ResourcePods] = *resource.NewQuantity(\n\t\t\t\t\tint64(maxPods), resource.DecimalSI)\n\t\t\t}\n\n\t\t\tif node.Status.NodeInfo.BootID != \"\" \u0026\u0026\n\t\t\t\tnode.Status.NodeInfo.BootID != info.BootID {\n\t\t\t\t// TODO: This requires a transaction, either both node status is updated\n\t\t\t\t// and event is recorded or neither should happen, see issue #6055.\n\t\t\t\trecordEventFunc(v1.EventTypeWarning, events.NodeRebooted,\n\t\t\t\t\tfmt.Sprintf(\"Node %s has been rebooted, boot id: %s\", nodeName, info.BootID))\n\t\t\t}\n\t\t\tnode.Status.NodeInfo.BootID = info.BootID\n\n\t\t\t// TODO: all the node resources should use ContainerManager.GetCapacity instead of deriving the\n\t\t\t// capacity for every node status request\n\t\t\tinitialCapacity := capacityFunc(localStorageCapacityIsolation)\n\t\t\tif initialCapacity != nil {\n\t\t\t\tif v, exists := initialCapacity[v1.ResourceEphemeralStorage]; exists {\n\t\t\t\t\tnode.Status.Capacity[v1.ResourceEphemeralStorage] = v\n\t\t\t\t}\n\t\t\t}\n\t\t\t//}\n\n\t\t\tdevicePluginCapacity, devicePluginAllocatable, removedDevicePlugins = devicePluginResourceCapacityFunc()\n\t\t\tfor k, v := range devicePluginCapacity {\n\t\t\t\tif old, ok := node.Status.Capacity[k]; !ok || old.Value() != v.Value() {\n\t\t\t\t\tklog.V(2).InfoS(\"Updated capacity for device plugin\", \"plugin\", k, \"capacity\", v.Value())\n\t\t\t\t}\n\t\t\t\tnode.Status.Capacity[k] = v\n\t\t\t}\n\n\t\t\tfor _, removedResource := range removedDevicePlugins {\n\t\t\t\tklog.V(2).InfoS(\"Set capacity for removed resource to 0 on device removal\", \"device\", removedResource)\n\t\t\t\t// Set the capacity of the removed resource to 0 instead of\n\t\t\t\t// removing the resource from the node status. This is to indicate\n\t\t\t\t// that the resource is managed by device plugin and had been\n\t\t\t\t// registered before.\n\t\t\t\t//\n\t\t\t\t// This is required to differentiate the device plugin managed\n\t\t\t\t// resources and the cluster-level resources, which are absent in\n\t\t\t\t// node status.\n\t\t\t\tnode.Status.Capacity[v1.ResourceName(removedResource)] = *resource.NewQuantity(int64(0), resource.DecimalSI)\n\t\t\t}\n\t\t}\n\n\t\t// Set Allocatable.\n\t\tif node.Status.Allocatable == nil {\n\t\t\tnode.Status.Allocatable = make(v1.ResourceList)\n\t\t}\n\t\t// Remove extended resources from allocatable that are no longer\n\t\t// present in capacity.\n\t\tfor k := range node.Status.Allocatable {\n\t\t\t_, found := node.Status.Capacity[k]\n\t\t\tif !found \u0026\u0026 v1helper.IsExtendedResourceName(k) {\n\t\t\t\tdelete(node.Status.Allocatable, k)\n\t\t\t}\n\t\t}\n\t\tallocatableReservation := nodeAllocatableReservationFunc()\n\t\tfor k, v := range node.Status.Capacity {\n\t\t\tvalue := v.DeepCopy()\n\t\t\tif res, exists := allocatableReservation[k]; exists {\n\t\t\t\tvalue.Sub(res)\n\t\t\t}\n\t\t\tif value.Sign() \u003c 0 {\n\t\t\t\t// Negative Allocatable resources don't make sense.\n\t\t\t\tvalue.Set(0)\n\t\t\t}\n\t\t\tnode.Status.Allocatable[k] = value\n\t\t}\n\n\t\tfor k, v := range devicePluginAllocatable {\n\t\t\tif old, ok := node.Status.Allocatable[k]; !ok || old.Value() != v.Value() {\n\t\t\t\tklog.V(2).InfoS(\"Updated allocatable\", \"device\", k, \"allocatable\", v.Value())\n\t\t\t}\n\t\t\tnode.Status.Allocatable[k] = v\n\t\t}\n\t\t// for every huge page reservation, we need to remove it from allocatable memory\n\t\tfor k, v := range node.Status.Capacity {\n\t\t\tif v1helper.IsHugePageResourceName(k) {\n\t\t\t\tallocatableMemory := node.Status.Allocatable[v1.ResourceMemory]\n\t\t\t\tvalue := v.DeepCopy()\n\t\t\t\tallocatableMemory.Sub(value)\n\t\t\t\tif allocatableMemory.Sign() \u003c 0 {\n\t\t\t\t\t// Negative Allocatable resources don't make sense.\n\t\t\t\t\tallocatableMemory.Set(0)\n\t\t\t\t}\n\t\t\t\tnode.Status.Allocatable[v1.ResourceMemory] = allocatableMemory\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n}","line":{"from":247,"to":382}} {"id":100007228,"name":"VersionInfo","signature":"func VersionInfo(versionInfoFunc func() (*cadvisorapiv1.VersionInfo, error), // typically Kubelet.cadvisor.VersionInfo","file":"pkg/kubelet/nodestatus/setters.go","code":"// VersionInfo returns a Setter that updates version-related information on the node.\nfunc VersionInfo(versionInfoFunc func() (*cadvisorapiv1.VersionInfo, error), // typically Kubelet.cadvisor.VersionInfo\n\truntimeTypeFunc func() string, // typically Kubelet.containerRuntime.Type\n\truntimeVersionFunc func(ctx context.Context) (kubecontainer.Version, error), // typically Kubelet.containerRuntime.Version\n) Setter {\n\treturn func(ctx context.Context, node *v1.Node) error {\n\t\tverinfo, err := versionInfoFunc()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error getting version info: %v\", err)\n\t\t}\n\n\t\tnode.Status.NodeInfo.KernelVersion = verinfo.KernelVersion\n\t\tnode.Status.NodeInfo.OSImage = verinfo.ContainerOsVersion\n\n\t\truntimeVersion := \"Unknown\"\n\t\tif runtimeVer, err := runtimeVersionFunc(ctx); err == nil {\n\t\t\truntimeVersion = runtimeVer.String()\n\t\t}\n\t\tnode.Status.NodeInfo.ContainerRuntimeVersion = fmt.Sprintf(\"%s://%s\", runtimeTypeFunc(), runtimeVersion)\n\n\t\tnode.Status.NodeInfo.KubeletVersion = version.Get().String()\n\t\t// TODO: kube-proxy might be different version from kubelet in the future\n\t\tnode.Status.NodeInfo.KubeProxyVersion = version.Get().String()\n\t\treturn nil\n\t}\n}","line":{"from":384,"to":409}} {"id":100007229,"name":"DaemonEndpoints","signature":"func DaemonEndpoints(daemonEndpoints *v1.NodeDaemonEndpoints) Setter","file":"pkg/kubelet/nodestatus/setters.go","code":"// DaemonEndpoints returns a Setter that updates the daemon endpoints on the node.\nfunc DaemonEndpoints(daemonEndpoints *v1.NodeDaemonEndpoints) Setter {\n\treturn func(ctx context.Context, node *v1.Node) error {\n\t\tnode.Status.DaemonEndpoints = *daemonEndpoints\n\t\treturn nil\n\t}\n}","line":{"from":411,"to":417}} {"id":100007230,"name":"Images","signature":"func Images(nodeStatusMaxImages int32,","file":"pkg/kubelet/nodestatus/setters.go","code":"// Images returns a Setter that updates the images on the node.\n// imageListFunc is expected to return a list of images sorted in descending order by image size.\n// nodeStatusMaxImages is ignored if set to -1.\nfunc Images(nodeStatusMaxImages int32,\n\timageListFunc func() ([]kubecontainer.Image, error), // typically Kubelet.imageManager.GetImageList\n) Setter {\n\treturn func(ctx context.Context, node *v1.Node) error {\n\t\t// Update image list of this node\n\t\tvar imagesOnNode []v1.ContainerImage\n\t\tcontainerImages, err := imageListFunc()\n\t\tif err != nil {\n\t\t\tnode.Status.Images = imagesOnNode\n\t\t\treturn fmt.Errorf(\"error getting image list: %v\", err)\n\t\t}\n\t\t// we expect imageListFunc to return a sorted list, so we just need to truncate\n\t\tif int(nodeStatusMaxImages) \u003e -1 \u0026\u0026\n\t\t\tint(nodeStatusMaxImages) \u003c len(containerImages) {\n\t\t\tcontainerImages = containerImages[0:nodeStatusMaxImages]\n\t\t}\n\n\t\tfor _, image := range containerImages {\n\t\t\t// make a copy to avoid modifying slice members of the image items in the list\n\t\t\tnames := append([]string{}, image.RepoDigests...)\n\t\t\tnames = append(names, image.RepoTags...)\n\t\t\t// Report up to MaxNamesPerImageInNodeStatus names per image.\n\t\t\tif len(names) \u003e MaxNamesPerImageInNodeStatus {\n\t\t\t\tnames = names[0:MaxNamesPerImageInNodeStatus]\n\t\t\t}\n\t\t\timagesOnNode = append(imagesOnNode, v1.ContainerImage{\n\t\t\t\tNames: names,\n\t\t\t\tSizeBytes: image.Size,\n\t\t\t})\n\t\t}\n\n\t\tnode.Status.Images = imagesOnNode\n\t\treturn nil\n\t}\n}","line":{"from":419,"to":456}} {"id":100007231,"name":"GoRuntime","signature":"func GoRuntime() Setter","file":"pkg/kubelet/nodestatus/setters.go","code":"// GoRuntime returns a Setter that sets GOOS and GOARCH on the node.\nfunc GoRuntime() Setter {\n\treturn func(ctx context.Context, node *v1.Node) error {\n\t\tnode.Status.NodeInfo.OperatingSystem = goruntime.GOOS\n\t\tnode.Status.NodeInfo.Architecture = goruntime.GOARCH\n\t\treturn nil\n\t}\n}","line":{"from":458,"to":465}} {"id":100007232,"name":"ReadyCondition","signature":"func ReadyCondition(","file":"pkg/kubelet/nodestatus/setters.go","code":"// ReadyCondition returns a Setter that updates the v1.NodeReady condition on the node.\nfunc ReadyCondition(\n\tnowFunc func() time.Time, // typically Kubelet.clock.Now\n\truntimeErrorsFunc func() error, // typically Kubelet.runtimeState.runtimeErrors\n\tnetworkErrorsFunc func() error, // typically Kubelet.runtimeState.networkErrors\n\tstorageErrorsFunc func() error, // typically Kubelet.runtimeState.storageErrors\n\tappArmorValidateHostFunc func() error, // typically Kubelet.appArmorValidator.ValidateHost, might be nil depending on whether there was an appArmorValidator\n\tcmStatusFunc func() cm.Status, // typically Kubelet.containerManager.Status\n\tnodeShutdownManagerErrorsFunc func() error, // typically kubelet.shutdownManager.errors.\n\trecordEventFunc func(eventType, event string), // typically Kubelet.recordNodeStatusEvent\n\tlocalStorageCapacityIsolation bool,\n) Setter {\n\treturn func(ctx context.Context, node *v1.Node) error {\n\t\t// NOTE(aaronlevy): NodeReady condition needs to be the last in the list of node conditions.\n\t\t// This is due to an issue with version skewed kubelet and master components.\n\t\t// ref: https://github.com/kubernetes/kubernetes/issues/16961\n\t\tcurrentTime := metav1.NewTime(nowFunc())\n\t\tnewNodeReadyCondition := v1.NodeCondition{\n\t\t\tType: v1.NodeReady,\n\t\t\tStatus: v1.ConditionTrue,\n\t\t\tReason: \"KubeletReady\",\n\t\t\tMessage: \"kubelet is posting ready status\",\n\t\t\tLastHeartbeatTime: currentTime,\n\t\t}\n\t\terrs := []error{runtimeErrorsFunc(), networkErrorsFunc(), storageErrorsFunc(), nodeShutdownManagerErrorsFunc()}\n\t\trequiredCapacities := []v1.ResourceName{v1.ResourceCPU, v1.ResourceMemory, v1.ResourcePods}\n\t\tif localStorageCapacityIsolation {\n\t\t\trequiredCapacities = append(requiredCapacities, v1.ResourceEphemeralStorage)\n\t\t}\n\t\tmissingCapacities := []string{}\n\t\tfor _, resource := range requiredCapacities {\n\t\t\tif _, found := node.Status.Capacity[resource]; !found {\n\t\t\t\tmissingCapacities = append(missingCapacities, string(resource))\n\t\t\t}\n\t\t}\n\t\tif len(missingCapacities) \u003e 0 {\n\t\t\terrs = append(errs, fmt.Errorf(\"missing node capacity for resources: %s\", strings.Join(missingCapacities, \", \")))\n\t\t}\n\t\tif aggregatedErr := errors.NewAggregate(errs); aggregatedErr != nil {\n\t\t\tnewNodeReadyCondition = v1.NodeCondition{\n\t\t\t\tType: v1.NodeReady,\n\t\t\t\tStatus: v1.ConditionFalse,\n\t\t\t\tReason: \"KubeletNotReady\",\n\t\t\t\tMessage: aggregatedErr.Error(),\n\t\t\t\tLastHeartbeatTime: currentTime,\n\t\t\t}\n\t\t}\n\t\t// Append AppArmor status if it's enabled.\n\t\t// TODO(tallclair): This is a temporary message until node feature reporting is added.\n\t\tif appArmorValidateHostFunc != nil \u0026\u0026 newNodeReadyCondition.Status == v1.ConditionTrue {\n\t\t\tif err := appArmorValidateHostFunc(); err == nil {\n\t\t\t\tnewNodeReadyCondition.Message = fmt.Sprintf(\"%s. AppArmor enabled\", newNodeReadyCondition.Message)\n\t\t\t}\n\t\t}\n\n\t\t// Record any soft requirements that were not met in the container manager.\n\t\tstatus := cmStatusFunc()\n\t\tif status.SoftRequirements != nil {\n\t\t\tnewNodeReadyCondition.Message = fmt.Sprintf(\"%s. WARNING: %s\", newNodeReadyCondition.Message, status.SoftRequirements.Error())\n\t\t}\n\n\t\treadyConditionUpdated := false\n\t\tneedToRecordEvent := false\n\t\tfor i := range node.Status.Conditions {\n\t\t\tif node.Status.Conditions[i].Type == v1.NodeReady {\n\t\t\t\tif node.Status.Conditions[i].Status == newNodeReadyCondition.Status {\n\t\t\t\t\tnewNodeReadyCondition.LastTransitionTime = node.Status.Conditions[i].LastTransitionTime\n\t\t\t\t} else {\n\t\t\t\t\tnewNodeReadyCondition.LastTransitionTime = currentTime\n\t\t\t\t\tneedToRecordEvent = true\n\t\t\t\t}\n\t\t\t\tnode.Status.Conditions[i] = newNodeReadyCondition\n\t\t\t\treadyConditionUpdated = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !readyConditionUpdated {\n\t\t\tnewNodeReadyCondition.LastTransitionTime = currentTime\n\t\t\tnode.Status.Conditions = append(node.Status.Conditions, newNodeReadyCondition)\n\t\t}\n\t\tif needToRecordEvent {\n\t\t\tif newNodeReadyCondition.Status == v1.ConditionTrue {\n\t\t\t\trecordEventFunc(v1.EventTypeNormal, events.NodeReady)\n\t\t\t} else {\n\t\t\t\trecordEventFunc(v1.EventTypeNormal, events.NodeNotReady)\n\t\t\t\tklog.InfoS(\"Node became not ready\", \"node\", klog.KObj(node), \"condition\", newNodeReadyCondition)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n}","line":{"from":467,"to":557}} {"id":100007233,"name":"MemoryPressureCondition","signature":"func MemoryPressureCondition(nowFunc func() time.Time, // typically Kubelet.clock.Now","file":"pkg/kubelet/nodestatus/setters.go","code":"// MemoryPressureCondition returns a Setter that updates the v1.NodeMemoryPressure condition on the node.\nfunc MemoryPressureCondition(nowFunc func() time.Time, // typically Kubelet.clock.Now\n\tpressureFunc func() bool, // typically Kubelet.evictionManager.IsUnderMemoryPressure\n\trecordEventFunc func(eventType, event string), // typically Kubelet.recordNodeStatusEvent\n) Setter {\n\treturn func(ctx context.Context, node *v1.Node) error {\n\t\tcurrentTime := metav1.NewTime(nowFunc())\n\t\tvar condition *v1.NodeCondition\n\n\t\t// Check if NodeMemoryPressure condition already exists and if it does, just pick it up for update.\n\t\tfor i := range node.Status.Conditions {\n\t\t\tif node.Status.Conditions[i].Type == v1.NodeMemoryPressure {\n\t\t\t\tcondition = \u0026node.Status.Conditions[i]\n\t\t\t}\n\t\t}\n\n\t\tnewCondition := false\n\t\t// If the NodeMemoryPressure condition doesn't exist, create one\n\t\tif condition == nil {\n\t\t\tcondition = \u0026v1.NodeCondition{\n\t\t\t\tType: v1.NodeMemoryPressure,\n\t\t\t\tStatus: v1.ConditionUnknown,\n\t\t\t}\n\t\t\t// cannot be appended to node.Status.Conditions here because it gets\n\t\t\t// copied to the slice. So if we append to the slice here none of the\n\t\t\t// updates we make below are reflected in the slice.\n\t\t\tnewCondition = true\n\t\t}\n\n\t\t// Update the heartbeat time\n\t\tcondition.LastHeartbeatTime = currentTime\n\n\t\t// Note: The conditions below take care of the case when a new NodeMemoryPressure condition is\n\t\t// created and as well as the case when the condition already exists. When a new condition\n\t\t// is created its status is set to v1.ConditionUnknown which matches either\n\t\t// condition.Status != v1.ConditionTrue or\n\t\t// condition.Status != v1.ConditionFalse in the conditions below depending on whether\n\t\t// the kubelet is under memory pressure or not.\n\t\tif pressureFunc() {\n\t\t\tif condition.Status != v1.ConditionTrue {\n\t\t\t\tcondition.Status = v1.ConditionTrue\n\t\t\t\tcondition.Reason = \"KubeletHasInsufficientMemory\"\n\t\t\t\tcondition.Message = \"kubelet has insufficient memory available\"\n\t\t\t\tcondition.LastTransitionTime = currentTime\n\t\t\t\trecordEventFunc(v1.EventTypeNormal, \"NodeHasInsufficientMemory\")\n\t\t\t}\n\t\t} else if condition.Status != v1.ConditionFalse {\n\t\t\tcondition.Status = v1.ConditionFalse\n\t\t\tcondition.Reason = \"KubeletHasSufficientMemory\"\n\t\t\tcondition.Message = \"kubelet has sufficient memory available\"\n\t\t\tcondition.LastTransitionTime = currentTime\n\t\t\trecordEventFunc(v1.EventTypeNormal, \"NodeHasSufficientMemory\")\n\t\t}\n\n\t\tif newCondition {\n\t\t\tnode.Status.Conditions = append(node.Status.Conditions, *condition)\n\t\t}\n\t\treturn nil\n\t}\n}","line":{"from":559,"to":618}} {"id":100007234,"name":"PIDPressureCondition","signature":"func PIDPressureCondition(nowFunc func() time.Time, // typically Kubelet.clock.Now","file":"pkg/kubelet/nodestatus/setters.go","code":"// PIDPressureCondition returns a Setter that updates the v1.NodePIDPressure condition on the node.\nfunc PIDPressureCondition(nowFunc func() time.Time, // typically Kubelet.clock.Now\n\tpressureFunc func() bool, // typically Kubelet.evictionManager.IsUnderPIDPressure\n\trecordEventFunc func(eventType, event string), // typically Kubelet.recordNodeStatusEvent\n) Setter {\n\treturn func(ctx context.Context, node *v1.Node) error {\n\t\tcurrentTime := metav1.NewTime(nowFunc())\n\t\tvar condition *v1.NodeCondition\n\n\t\t// Check if NodePIDPressure condition already exists and if it does, just pick it up for update.\n\t\tfor i := range node.Status.Conditions {\n\t\t\tif node.Status.Conditions[i].Type == v1.NodePIDPressure {\n\t\t\t\tcondition = \u0026node.Status.Conditions[i]\n\t\t\t}\n\t\t}\n\n\t\tnewCondition := false\n\t\t// If the NodePIDPressure condition doesn't exist, create one\n\t\tif condition == nil {\n\t\t\tcondition = \u0026v1.NodeCondition{\n\t\t\t\tType: v1.NodePIDPressure,\n\t\t\t\tStatus: v1.ConditionUnknown,\n\t\t\t}\n\t\t\t// cannot be appended to node.Status.Conditions here because it gets\n\t\t\t// copied to the slice. So if we append to the slice here none of the\n\t\t\t// updates we make below are reflected in the slice.\n\t\t\tnewCondition = true\n\t\t}\n\n\t\t// Update the heartbeat time\n\t\tcondition.LastHeartbeatTime = currentTime\n\n\t\t// Note: The conditions below take care of the case when a new NodePIDPressure condition is\n\t\t// created and as well as the case when the condition already exists. When a new condition\n\t\t// is created its status is set to v1.ConditionUnknown which matches either\n\t\t// condition.Status != v1.ConditionTrue or\n\t\t// condition.Status != v1.ConditionFalse in the conditions below depending on whether\n\t\t// the kubelet is under PID pressure or not.\n\t\tif pressureFunc() {\n\t\t\tif condition.Status != v1.ConditionTrue {\n\t\t\t\tcondition.Status = v1.ConditionTrue\n\t\t\t\tcondition.Reason = \"KubeletHasInsufficientPID\"\n\t\t\t\tcondition.Message = \"kubelet has insufficient PID available\"\n\t\t\t\tcondition.LastTransitionTime = currentTime\n\t\t\t\trecordEventFunc(v1.EventTypeNormal, \"NodeHasInsufficientPID\")\n\t\t\t}\n\t\t} else if condition.Status != v1.ConditionFalse {\n\t\t\tcondition.Status = v1.ConditionFalse\n\t\t\tcondition.Reason = \"KubeletHasSufficientPID\"\n\t\t\tcondition.Message = \"kubelet has sufficient PID available\"\n\t\t\tcondition.LastTransitionTime = currentTime\n\t\t\trecordEventFunc(v1.EventTypeNormal, \"NodeHasSufficientPID\")\n\t\t}\n\n\t\tif newCondition {\n\t\t\tnode.Status.Conditions = append(node.Status.Conditions, *condition)\n\t\t}\n\t\treturn nil\n\t}\n}","line":{"from":620,"to":679}} {"id":100007235,"name":"DiskPressureCondition","signature":"func DiskPressureCondition(nowFunc func() time.Time, // typically Kubelet.clock.Now","file":"pkg/kubelet/nodestatus/setters.go","code":"// DiskPressureCondition returns a Setter that updates the v1.NodeDiskPressure condition on the node.\nfunc DiskPressureCondition(nowFunc func() time.Time, // typically Kubelet.clock.Now\n\tpressureFunc func() bool, // typically Kubelet.evictionManager.IsUnderDiskPressure\n\trecordEventFunc func(eventType, event string), // typically Kubelet.recordNodeStatusEvent\n) Setter {\n\treturn func(ctx context.Context, node *v1.Node) error {\n\t\tcurrentTime := metav1.NewTime(nowFunc())\n\t\tvar condition *v1.NodeCondition\n\n\t\t// Check if NodeDiskPressure condition already exists and if it does, just pick it up for update.\n\t\tfor i := range node.Status.Conditions {\n\t\t\tif node.Status.Conditions[i].Type == v1.NodeDiskPressure {\n\t\t\t\tcondition = \u0026node.Status.Conditions[i]\n\t\t\t}\n\t\t}\n\n\t\tnewCondition := false\n\t\t// If the NodeDiskPressure condition doesn't exist, create one\n\t\tif condition == nil {\n\t\t\tcondition = \u0026v1.NodeCondition{\n\t\t\t\tType: v1.NodeDiskPressure,\n\t\t\t\tStatus: v1.ConditionUnknown,\n\t\t\t}\n\t\t\t// cannot be appended to node.Status.Conditions here because it gets\n\t\t\t// copied to the slice. So if we append to the slice here none of the\n\t\t\t// updates we make below are reflected in the slice.\n\t\t\tnewCondition = true\n\t\t}\n\n\t\t// Update the heartbeat time\n\t\tcondition.LastHeartbeatTime = currentTime\n\n\t\t// Note: The conditions below take care of the case when a new NodeDiskPressure condition is\n\t\t// created and as well as the case when the condition already exists. When a new condition\n\t\t// is created its status is set to v1.ConditionUnknown which matches either\n\t\t// condition.Status != v1.ConditionTrue or\n\t\t// condition.Status != v1.ConditionFalse in the conditions below depending on whether\n\t\t// the kubelet is under disk pressure or not.\n\t\tif pressureFunc() {\n\t\t\tif condition.Status != v1.ConditionTrue {\n\t\t\t\tcondition.Status = v1.ConditionTrue\n\t\t\t\tcondition.Reason = \"KubeletHasDiskPressure\"\n\t\t\t\tcondition.Message = \"kubelet has disk pressure\"\n\t\t\t\tcondition.LastTransitionTime = currentTime\n\t\t\t\trecordEventFunc(v1.EventTypeNormal, \"NodeHasDiskPressure\")\n\t\t\t}\n\t\t} else if condition.Status != v1.ConditionFalse {\n\t\t\tcondition.Status = v1.ConditionFalse\n\t\t\tcondition.Reason = \"KubeletHasNoDiskPressure\"\n\t\t\tcondition.Message = \"kubelet has no disk pressure\"\n\t\t\tcondition.LastTransitionTime = currentTime\n\t\t\trecordEventFunc(v1.EventTypeNormal, \"NodeHasNoDiskPressure\")\n\t\t}\n\n\t\tif newCondition {\n\t\t\tnode.Status.Conditions = append(node.Status.Conditions, *condition)\n\t\t}\n\t\treturn nil\n\t}\n}","line":{"from":681,"to":740}} {"id":100007236,"name":"VolumesInUse","signature":"func VolumesInUse(syncedFunc func() bool, // typically Kubelet.volumeManager.ReconcilerStatesHasBeenSynced","file":"pkg/kubelet/nodestatus/setters.go","code":"// VolumesInUse returns a Setter that updates the volumes in use on the node.\nfunc VolumesInUse(syncedFunc func() bool, // typically Kubelet.volumeManager.ReconcilerStatesHasBeenSynced\n\tvolumesInUseFunc func() []v1.UniqueVolumeName, // typically Kubelet.volumeManager.GetVolumesInUse\n) Setter {\n\treturn func(ctx context.Context, node *v1.Node) error {\n\t\t// Make sure to only update node status after reconciler starts syncing up states\n\t\tif syncedFunc() {\n\t\t\tnode.Status.VolumesInUse = volumesInUseFunc()\n\t\t}\n\t\treturn nil\n\t}\n}","line":{"from":742,"to":753}} {"id":100007237,"name":"VolumeLimits","signature":"func VolumeLimits(volumePluginListFunc func() []volume.VolumePluginWithAttachLimits, // typically Kubelet.volumePluginMgr.ListVolumePluginWithLimits","file":"pkg/kubelet/nodestatus/setters.go","code":"// VolumeLimits returns a Setter that updates the volume limits on the node.\nfunc VolumeLimits(volumePluginListFunc func() []volume.VolumePluginWithAttachLimits, // typically Kubelet.volumePluginMgr.ListVolumePluginWithLimits\n) Setter {\n\treturn func(ctx context.Context, node *v1.Node) error {\n\t\tif node.Status.Capacity == nil {\n\t\t\tnode.Status.Capacity = v1.ResourceList{}\n\t\t}\n\t\tif node.Status.Allocatable == nil {\n\t\t\tnode.Status.Allocatable = v1.ResourceList{}\n\t\t}\n\n\t\tpluginWithLimits := volumePluginListFunc()\n\t\tfor _, volumePlugin := range pluginWithLimits {\n\t\t\tattachLimits, err := volumePlugin.GetVolumeLimits()\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).InfoS(\"Skipping volume limits for volume plugin\", \"plugin\", volumePlugin.GetPluginName())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor limitKey, value := range attachLimits {\n\t\t\t\tnode.Status.Capacity[v1.ResourceName(limitKey)] = *resource.NewQuantity(value, resource.DecimalSI)\n\t\t\t\tnode.Status.Allocatable[v1.ResourceName(limitKey)] = *resource.NewQuantity(value, resource.DecimalSI)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n}","line":{"from":755,"to":780}} {"id":100007238,"name":"NewWatcher","signature":"func NewWatcher(recorder record.EventRecorder) (Watcher, error)","file":"pkg/kubelet/oom/oom_watcher_linux.go","code":"// NewWatcher creates and initializes a OOMWatcher backed by Cadvisor as\n// the oom streamer.\nfunc NewWatcher(recorder record.EventRecorder) (Watcher, error) {\n\t// for test purpose\n\t_, ok := recorder.(*record.FakeRecorder)\n\tif ok {\n\t\treturn nil, nil\n\t}\n\n\toomStreamer, err := oomparser.New()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twatcher := \u0026realWatcher{\n\t\trecorder: recorder,\n\t\toomStreamer: oomStreamer,\n\t}\n\n\treturn watcher, nil\n}","line":{"from":46,"to":66}} {"id":100007239,"name":"Start","signature":"func (ow *realWatcher) Start(ref *v1.ObjectReference) error","file":"pkg/kubelet/oom/oom_watcher_linux.go","code":"// Start watches for system oom's and records an event for every system oom encountered.\nfunc (ow *realWatcher) Start(ref *v1.ObjectReference) error {\n\toutStream := make(chan *oomparser.OomInstance, 10)\n\tgo ow.oomStreamer.StreamOoms(outStream)\n\n\tgo func() {\n\t\tdefer runtime.HandleCrash()\n\n\t\tfor event := range outStream {\n\t\t\tif event.VictimContainerName == recordEventContainerName {\n\t\t\t\tklog.V(1).InfoS(\"Got sys oom event\", \"event\", event)\n\t\t\t\teventMsg := \"System OOM encountered\"\n\t\t\t\tif event.ProcessName != \"\" \u0026\u0026 event.Pid != 0 {\n\t\t\t\t\teventMsg = fmt.Sprintf(\"%s, victim process: %s, pid: %d\", eventMsg, event.ProcessName, event.Pid)\n\t\t\t\t}\n\t\t\t\tow.recorder.Eventf(ref, v1.EventTypeWarning, systemOOMEvent, eventMsg)\n\t\t\t}\n\t\t}\n\t\tklog.ErrorS(nil, \"Unexpectedly stopped receiving OOM notifications\")\n\t}()\n\treturn nil\n}","line":{"from":73,"to":94}} {"id":100007240,"name":"NewWatcher","signature":"func NewWatcher(_ record.EventRecorder) (Watcher, error)","file":"pkg/kubelet/oom/oom_watcher_unsupported.go","code":"// NewWatcher creates a fake one here\nfunc NewWatcher(_ record.EventRecorder) (Watcher, error) {\n\treturn \u0026oomWatcherUnsupported{}, nil\n}","line":{"from":31,"to":34}} {"id":100007241,"name":"Start","signature":"func (ow *oomWatcherUnsupported) Start(_ *v1.ObjectReference) error","file":"pkg/kubelet/oom/oom_watcher_unsupported.go","code":"func (ow *oomWatcherUnsupported) Start(_ *v1.ObjectReference) error {\n\treturn nil\n}","line":{"from":36,"to":38}} {"id":100007242,"name":"isEventedPLEGInUse","signature":"func isEventedPLEGInUse() bool","file":"pkg/kubelet/pleg/evented.go","code":"// isEventedPLEGInUse indicates whether Evented PLEG is in use. Even after enabling\n// the Evented PLEG feature gate, there could be several reasons it may not be in use.\n// e.g. Streaming data issues from the runtime or the runtime does not implement the\n// container events stream.\nfunc isEventedPLEGInUse() bool {\n\teventedPLEGUsageMu.Lock()\n\tdefer eventedPLEGUsageMu.Unlock()\n\treturn eventedPLEGUsage\n}","line":{"from":44,"to":52}} {"id":100007243,"name":"setEventedPLEGUsage","signature":"func setEventedPLEGUsage(enable bool)","file":"pkg/kubelet/pleg/evented.go","code":"// setEventedPLEGUsage should only be accessed from\n// Start/Stop of Evented PLEG.\nfunc setEventedPLEGUsage(enable bool) {\n\teventedPLEGUsageMu.RLock()\n\tdefer eventedPLEGUsageMu.RUnlock()\n\teventedPLEGUsage = enable\n}","line":{"from":54,"to":60}} {"id":100007244,"name":"NewEventedPLEG","signature":"func NewEventedPLEG(runtime kubecontainer.Runtime, runtimeService internalapi.RuntimeService, eventChannel chan *PodLifecycleEvent,","file":"pkg/kubelet/pleg/evented.go","code":"// NewEventedPLEG instantiates a new EventedPLEG object and return it.\nfunc NewEventedPLEG(runtime kubecontainer.Runtime, runtimeService internalapi.RuntimeService, eventChannel chan *PodLifecycleEvent,\n\tcache kubecontainer.Cache, genericPleg PodLifecycleEventGenerator, eventedPlegMaxStreamRetries int,\n\trelistDuration *RelistDuration, clock clock.Clock) PodLifecycleEventGenerator {\n\treturn \u0026EventedPLEG{\n\t\truntime: runtime,\n\t\truntimeService: runtimeService,\n\t\teventChannel: eventChannel,\n\t\tcache: cache,\n\t\tgenericPleg: genericPleg,\n\t\teventedPlegMaxStreamRetries: eventedPlegMaxStreamRetries,\n\t\trelistDuration: relistDuration,\n\t\tclock: clock,\n\t}\n}","line":{"from":87,"to":101}} {"id":100007245,"name":"Watch","signature":"func (e *EventedPLEG) Watch() chan *PodLifecycleEvent","file":"pkg/kubelet/pleg/evented.go","code":"// Watch returns a channel from which the subscriber can receive PodLifecycleEvent events.\nfunc (e *EventedPLEG) Watch() chan *PodLifecycleEvent {\n\treturn e.eventChannel\n}","line":{"from":103,"to":106}} {"id":100007246,"name":"Relist","signature":"func (e *EventedPLEG) Relist()","file":"pkg/kubelet/pleg/evented.go","code":"// Relist relists all containers using GenericPLEG\nfunc (e *EventedPLEG) Relist() {\n\te.genericPleg.Relist()\n}","line":{"from":108,"to":111}} {"id":100007247,"name":"Start","signature":"func (e *EventedPLEG) Start()","file":"pkg/kubelet/pleg/evented.go","code":"// Start starts the Evented PLEG\nfunc (e *EventedPLEG) Start() {\n\te.runningMu.Lock()\n\tdefer e.runningMu.Unlock()\n\tif isEventedPLEGInUse() {\n\t\treturn\n\t}\n\tsetEventedPLEGUsage(true)\n\te.stopCh = make(chan struct{})\n\te.stopCacheUpdateCh = make(chan struct{})\n\tgo wait.Until(e.watchEventsChannel, 0, e.stopCh)\n\tgo wait.Until(e.updateGlobalCache, globalCacheUpdatePeriod, e.stopCacheUpdateCh)\n}","line":{"from":113,"to":125}} {"id":100007248,"name":"Stop","signature":"func (e *EventedPLEG) Stop()","file":"pkg/kubelet/pleg/evented.go","code":"// Stop stops the Evented PLEG\nfunc (e *EventedPLEG) Stop() {\n\te.runningMu.Lock()\n\tdefer e.runningMu.Unlock()\n\tif !isEventedPLEGInUse() {\n\t\treturn\n\t}\n\tsetEventedPLEGUsage(false)\n\tclose(e.stopCh)\n\tclose(e.stopCacheUpdateCh)\n}","line":{"from":127,"to":137}} {"id":100007249,"name":"updateGlobalCache","signature":"func (e *EventedPLEG) updateGlobalCache()","file":"pkg/kubelet/pleg/evented.go","code":"// In case the Evented PLEG experiences undetectable issues in the underlying\n// GRPC connection there is a remote chance the pod might get stuck in a\n// given state while it has progressed in its life cycle. This function will be\n// called periodically to update the global timestamp of the cache so that those\n// pods stuck at GetNewerThan in pod workers will get unstuck.\nfunc (e *EventedPLEG) updateGlobalCache() {\n\te.cache.UpdateTime(time.Now())\n}","line":{"from":139,"to":146}} {"id":100007250,"name":"Update","signature":"func (e *EventedPLEG) Update(relistDuration *RelistDuration)","file":"pkg/kubelet/pleg/evented.go","code":"// Update the relisting period and threshold\nfunc (e *EventedPLEG) Update(relistDuration *RelistDuration) {\n\te.genericPleg.Update(relistDuration)\n}","line":{"from":148,"to":151}} {"id":100007251,"name":"Healthy","signature":"func (e *EventedPLEG) Healthy() (bool, error)","file":"pkg/kubelet/pleg/evented.go","code":"// Healthy check if PLEG work properly.\nfunc (e *EventedPLEG) Healthy() (bool, error) {\n\t// GenericPLEG is declared unhealthy when relisting time is more\n\t// than the relistThreshold. In case EventedPLEG is turned on,\n\t// relistingPeriod and relistingThreshold are adjusted to higher\n\t// values. So the health check of Generic PLEG should check\n\t// the adjusted values of relistingPeriod and relistingThreshold.\n\n\t// EventedPLEG is declared unhealthy only if eventChannel is out of capacity.\n\tif len(e.eventChannel) == cap(e.eventChannel) {\n\t\treturn false, fmt.Errorf(\"EventedPLEG: pleg event channel capacity is full with %v events\", len(e.eventChannel))\n\t}\n\n\ttimestamp := e.clock.Now()\n\tmetrics.PLEGLastSeen.Set(float64(timestamp.Unix()))\n\treturn true, nil\n}","line":{"from":153,"to":169}} {"id":100007252,"name":"watchEventsChannel","signature":"func (e *EventedPLEG) watchEventsChannel()","file":"pkg/kubelet/pleg/evented.go","code":"func (e *EventedPLEG) watchEventsChannel() {\n\tcontainerEventsResponseCh := make(chan *runtimeapi.ContainerEventResponse, cap(e.eventChannel))\n\tdefer close(containerEventsResponseCh)\n\n\t// Get the container events from the runtime.\n\tgo func() {\n\t\tnumAttempts := 0\n\t\tfor {\n\t\t\tif numAttempts \u003e= e.eventedPlegMaxStreamRetries {\n\t\t\t\tif isEventedPLEGInUse() {\n\t\t\t\t\t// Fall back to Generic PLEG relisting since Evented PLEG is not working.\n\t\t\t\t\tklog.V(4).InfoS(\"Fall back to Generic PLEG relisting since Evented PLEG is not working\")\n\t\t\t\t\te.Stop()\n\t\t\t\t\te.genericPleg.Stop() // Stop the existing Generic PLEG which runs with longer relisting period when Evented PLEG is in use.\n\t\t\t\t\te.Update(e.relistDuration) // Update the relisting period to the default value for the Generic PLEG.\n\t\t\t\t\te.genericPleg.Start()\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\terr := e.runtimeService.GetContainerEvents(containerEventsResponseCh)\n\t\t\tif err != nil {\n\t\t\t\tmetrics.EventedPLEGConnErr.Inc()\n\t\t\t\tnumAttempts++\n\t\t\t\te.Relist() // Force a relist to get the latest container and pods running metric.\n\t\t\t\tklog.V(4).InfoS(\"Evented PLEG: Failed to get container events, retrying: \", \"err\", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\tif isEventedPLEGInUse() {\n\t\te.processCRIEvents(containerEventsResponseCh)\n\t}\n}","line":{"from":171,"to":204}} {"id":100007253,"name":"processCRIEvents","signature":"func (e *EventedPLEG) processCRIEvents(containerEventsResponseCh chan *runtimeapi.ContainerEventResponse)","file":"pkg/kubelet/pleg/evented.go","code":"func (e *EventedPLEG) processCRIEvents(containerEventsResponseCh chan *runtimeapi.ContainerEventResponse) {\n\tfor event := range containerEventsResponseCh {\n\t\t// Ignore the event if PodSandboxStatus is nil.\n\t\t// This might happen under some race condition where the podSandbox has\n\t\t// been deleted, and therefore container runtime couldn't find the\n\t\t// podSandbox for the container when generating the event.\n\t\t// It is safe to ignore because\n\t\t// a) a event would have been received for the sandbox deletion,\n\t\t// b) in worst case, a relist will eventually sync the pod status.\n\t\t// TODO(#114371): Figure out a way to handle this case instead of ignoring.\n\t\tif event.PodSandboxStatus == nil || event.PodSandboxStatus.Metadata == nil {\n\t\t\tklog.ErrorS(nil, \"Evented PLEG: received ContainerEventResponse with nil PodSandboxStatus or PodSandboxStatus.Metadata\", \"containerEventResponse\", event)\n\t\t\tcontinue\n\t\t}\n\n\t\tpodID := types.UID(event.PodSandboxStatus.Metadata.Uid)\n\t\tshouldSendPLEGEvent := false\n\n\t\tstatus, err := e.runtime.GeneratePodStatus(event)\n\t\tif err != nil {\n\t\t\t// nolint:logcheck // Not using the result of klog.V inside the\n\t\t\t// if branch is okay, we just use it to determine whether the\n\t\t\t// additional \"podStatus\" key and its value should be added.\n\t\t\tif klog.V(6).Enabled() {\n\t\t\t\tklog.ErrorS(err, \"Evented PLEG: error generating pod status from the received event\", \"podUID\", podID, \"podStatus\", status)\n\t\t\t} else {\n\t\t\t\tklog.ErrorS(err, \"Evented PLEG: error generating pod status from the received event\", \"podUID\", podID, \"podStatus\", status)\n\t\t\t}\n\t\t} else {\n\t\t\tif klogV := klog.V(6); klogV.Enabled() {\n\t\t\t\tklogV.InfoS(\"Evented PLEG: Generated pod status from the received event\", \"podUID\", podID, \"podStatus\", status)\n\t\t\t} else {\n\t\t\t\tklog.V(4).InfoS(\"Evented PLEG: Generated pod status from the received event\", \"podUID\", podID)\n\t\t\t}\n\t\t\t// Preserve the pod IP across cache updates if the new IP is empty.\n\t\t\t// When a pod is torn down, kubelet may race with PLEG and retrieve\n\t\t\t// a pod status after network teardown, but the kubernetes API expects\n\t\t\t// the completed pod's IP to be available after the pod is dead.\n\t\t\tstatus.IPs = e.getPodIPs(podID, status)\n\t\t}\n\n\t\te.updateRunningPodMetric(status)\n\t\te.updateRunningContainerMetric(status)\n\t\te.updateLatencyMetric(event)\n\n\t\tif event.ContainerEventType == runtimeapi.ContainerEventType_CONTAINER_DELETED_EVENT {\n\t\t\tfor _, sandbox := range status.SandboxStatuses {\n\t\t\t\tif sandbox.Id == event.ContainerId {\n\t\t\t\t\t// When the CONTAINER_DELETED_EVENT is received by the kubelet,\n\t\t\t\t\t// the runtime has indicated that the container has been removed\n\t\t\t\t\t// by the runtime and hence, it must be removed from the cache\n\t\t\t\t\t// of kubelet too.\n\t\t\t\t\te.cache.Delete(podID)\n\t\t\t\t}\n\t\t\t}\n\t\t\tshouldSendPLEGEvent = true\n\t\t} else {\n\t\t\tif e.cache.Set(podID, status, err, time.Unix(event.GetCreatedAt(), 0)) {\n\t\t\t\tshouldSendPLEGEvent = true\n\t\t\t}\n\t\t}\n\n\t\tif shouldSendPLEGEvent {\n\t\t\te.processCRIEvent(event)\n\t\t}\n\t}\n}","line":{"from":206,"to":272}} {"id":100007254,"name":"processCRIEvent","signature":"func (e *EventedPLEG) processCRIEvent(event *runtimeapi.ContainerEventResponse)","file":"pkg/kubelet/pleg/evented.go","code":"func (e *EventedPLEG) processCRIEvent(event *runtimeapi.ContainerEventResponse) {\n\tswitch event.ContainerEventType {\n\tcase runtimeapi.ContainerEventType_CONTAINER_STOPPED_EVENT:\n\t\te.sendPodLifecycleEvent(\u0026PodLifecycleEvent{ID: types.UID(event.PodSandboxStatus.Metadata.Uid), Type: ContainerDied, Data: event.ContainerId})\n\t\tklog.V(4).InfoS(\"Received Container Stopped Event\", \"event\", event.String())\n\tcase runtimeapi.ContainerEventType_CONTAINER_CREATED_EVENT:\n\t\t// We only need to update the pod status on container create.\n\t\t// But we don't have to generate any PodLifeCycleEvent. Container creation related\n\t\t// PodLifeCycleEvent is ignored by the existing Generic PLEG as well.\n\t\t// https://github.com/kubernetes/kubernetes/blob/24753aa8a4df8d10bfd6330e0f29186000c018be/pkg/kubelet/pleg/generic.go#L88 and\n\t\t// https://github.com/kubernetes/kubernetes/blob/24753aa8a4df8d10bfd6330e0f29186000c018be/pkg/kubelet/pleg/generic.go#L273\n\t\tklog.V(4).InfoS(\"Received Container Created Event\", \"event\", event.String())\n\tcase runtimeapi.ContainerEventType_CONTAINER_STARTED_EVENT:\n\t\te.sendPodLifecycleEvent(\u0026PodLifecycleEvent{ID: types.UID(event.PodSandboxStatus.Metadata.Uid), Type: ContainerStarted, Data: event.ContainerId})\n\t\tklog.V(4).InfoS(\"Received Container Started Event\", \"event\", event.String())\n\tcase runtimeapi.ContainerEventType_CONTAINER_DELETED_EVENT:\n\t\t// In case the pod is deleted it is safe to generate both ContainerDied and ContainerRemoved events, just like in the case of\n\t\t// Generic PLEG. https://github.com/kubernetes/kubernetes/blob/24753aa8a4df8d10bfd6330e0f29186000c018be/pkg/kubelet/pleg/generic.go#L169\n\t\te.sendPodLifecycleEvent(\u0026PodLifecycleEvent{ID: types.UID(event.PodSandboxStatus.Metadata.Uid), Type: ContainerDied, Data: event.ContainerId})\n\t\te.sendPodLifecycleEvent(\u0026PodLifecycleEvent{ID: types.UID(event.PodSandboxStatus.Metadata.Uid), Type: ContainerRemoved, Data: event.ContainerId})\n\t\tklog.V(4).InfoS(\"Received Container Deleted Event\", \"event\", event)\n\t}\n}","line":{"from":274,"to":296}} {"id":100007255,"name":"getPodIPs","signature":"func (e *EventedPLEG) getPodIPs(pid types.UID, status *kubecontainer.PodStatus) []string","file":"pkg/kubelet/pleg/evented.go","code":"func (e *EventedPLEG) getPodIPs(pid types.UID, status *kubecontainer.PodStatus) []string {\n\tif len(status.IPs) != 0 {\n\t\treturn status.IPs\n\t}\n\n\toldStatus, err := e.cache.Get(pid)\n\tif err != nil || len(oldStatus.IPs) == 0 {\n\t\treturn nil\n\t}\n\n\tfor _, sandboxStatus := range status.SandboxStatuses {\n\t\t// If at least one sandbox is ready, then use this status update's pod IP\n\t\tif sandboxStatus.State == runtimeapi.PodSandboxState_SANDBOX_READY {\n\t\t\treturn status.IPs\n\t\t}\n\t}\n\n\t// For pods with no ready containers or sandboxes (like exited pods)\n\t// use the old status' pod IP\n\treturn oldStatus.IPs\n}","line":{"from":298,"to":318}} {"id":100007256,"name":"sendPodLifecycleEvent","signature":"func (e *EventedPLEG) sendPodLifecycleEvent(event *PodLifecycleEvent)","file":"pkg/kubelet/pleg/evented.go","code":"func (e *EventedPLEG) sendPodLifecycleEvent(event *PodLifecycleEvent) {\n\tselect {\n\tcase e.eventChannel \u003c- event:\n\tdefault:\n\t\t// record how many events were discarded due to channel out of capacity\n\t\tmetrics.PLEGDiscardEvents.Inc()\n\t\tklog.ErrorS(nil, \"Evented PLEG: Event channel is full, discarded pod lifecycle event\")\n\t}\n}","line":{"from":320,"to":328}} {"id":100007257,"name":"getPodSandboxState","signature":"func getPodSandboxState(podStatus *kubecontainer.PodStatus) kubecontainer.State","file":"pkg/kubelet/pleg/evented.go","code":"func getPodSandboxState(podStatus *kubecontainer.PodStatus) kubecontainer.State {\n\t// increase running pod count when cache doesn't contain podID\n\tvar sandboxId string\n\tfor _, sandbox := range podStatus.SandboxStatuses {\n\t\tsandboxId = sandbox.Id\n\t\t// pod must contain only one sandbox\n\t\tbreak\n\t}\n\n\tfor _, containerStatus := range podStatus.ContainerStatuses {\n\t\tif containerStatus.ID.ID == sandboxId {\n\t\t\tif containerStatus.State == kubecontainer.ContainerStateRunning {\n\t\t\t\treturn containerStatus.State\n\t\t\t}\n\t\t}\n\t}\n\treturn kubecontainer.ContainerStateExited\n}","line":{"from":330,"to":347}} {"id":100007258,"name":"updateRunningPodMetric","signature":"func (e *EventedPLEG) updateRunningPodMetric(podStatus *kubecontainer.PodStatus)","file":"pkg/kubelet/pleg/evented.go","code":"func (e *EventedPLEG) updateRunningPodMetric(podStatus *kubecontainer.PodStatus) {\n\tcachedPodStatus, err := e.cache.Get(podStatus.ID)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Evented PLEG: Get cache\", \"podID\", podStatus.ID)\n\t}\n\t// cache miss condition: The pod status object will have empty state if missed in cache\n\tif len(cachedPodStatus.SandboxStatuses) \u003c 1 {\n\t\tsandboxState := getPodSandboxState(podStatus)\n\t\tif sandboxState == kubecontainer.ContainerStateRunning {\n\t\t\tmetrics.RunningPodCount.Inc()\n\t\t}\n\t} else {\n\t\toldSandboxState := getPodSandboxState(cachedPodStatus)\n\t\tcurrentSandboxState := getPodSandboxState(podStatus)\n\n\t\tif oldSandboxState == kubecontainer.ContainerStateRunning \u0026\u0026 currentSandboxState != kubecontainer.ContainerStateRunning {\n\t\t\tmetrics.RunningPodCount.Dec()\n\t\t} else if oldSandboxState != kubecontainer.ContainerStateRunning \u0026\u0026 currentSandboxState == kubecontainer.ContainerStateRunning {\n\t\t\tmetrics.RunningPodCount.Inc()\n\t\t}\n\t}\n}","line":{"from":349,"to":370}} {"id":100007259,"name":"getContainerStateCount","signature":"func getContainerStateCount(podStatus *kubecontainer.PodStatus) map[kubecontainer.State]int","file":"pkg/kubelet/pleg/evented.go","code":"func getContainerStateCount(podStatus *kubecontainer.PodStatus) map[kubecontainer.State]int {\n\tcontainerStateCount := make(map[kubecontainer.State]int)\n\tfor _, container := range podStatus.ContainerStatuses {\n\t\tcontainerStateCount[container.State]++\n\t}\n\treturn containerStateCount\n}","line":{"from":372,"to":378}} {"id":100007260,"name":"updateRunningContainerMetric","signature":"func (e *EventedPLEG) updateRunningContainerMetric(podStatus *kubecontainer.PodStatus)","file":"pkg/kubelet/pleg/evented.go","code":"func (e *EventedPLEG) updateRunningContainerMetric(podStatus *kubecontainer.PodStatus) {\n\tcachedPodStatus, err := e.cache.Get(podStatus.ID)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Evented PLEG: Get cache\", \"podID\", podStatus.ID)\n\t}\n\n\t// cache miss condition: The pod status object will have empty state if missed in cache\n\tif len(cachedPodStatus.SandboxStatuses) \u003c 1 {\n\t\tcontainerStateCount := getContainerStateCount(podStatus)\n\t\tfor state, count := range containerStateCount {\n\t\t\t// add currently obtained count\n\t\t\tmetrics.RunningContainerCount.WithLabelValues(string(state)).Add(float64(count))\n\t\t}\n\t} else {\n\t\toldContainerStateCount := getContainerStateCount(cachedPodStatus)\n\t\tcurrentContainerStateCount := getContainerStateCount(podStatus)\n\n\t\t// old and new set of container states may vary;\n\t\t// get a unique set of container states combining both\n\t\tcontainerStates := make(map[kubecontainer.State]bool)\n\t\tfor state := range oldContainerStateCount {\n\t\t\tcontainerStates[state] = true\n\t\t}\n\t\tfor state := range currentContainerStateCount {\n\t\t\tcontainerStates[state] = true\n\t\t}\n\n\t\t// update the metric via difference of old and current counts\n\t\tfor state := range containerStates {\n\t\t\tdiff := currentContainerStateCount[state] - oldContainerStateCount[state]\n\t\t\tmetrics.RunningContainerCount.WithLabelValues(string(state)).Add(float64(diff))\n\t\t}\n\t}\n}","line":{"from":380,"to":413}} {"id":100007261,"name":"updateLatencyMetric","signature":"func (e *EventedPLEG) updateLatencyMetric(event *runtimeapi.ContainerEventResponse)","file":"pkg/kubelet/pleg/evented.go","code":"func (e *EventedPLEG) updateLatencyMetric(event *runtimeapi.ContainerEventResponse) {\n\tduration := time.Duration(time.Now().UnixNano()-event.CreatedAt) * time.Nanosecond\n\tmetrics.EventedPLEGConnLatency.Observe(duration.Seconds())\n}","line":{"from":415,"to":418}} {"id":100007262,"name":"UpdateCache","signature":"func (e *EventedPLEG) UpdateCache(pod *kubecontainer.Pod, pid types.UID) (error, bool)","file":"pkg/kubelet/pleg/evented.go","code":"func (e *EventedPLEG) UpdateCache(pod *kubecontainer.Pod, pid types.UID) (error, bool) {\n\treturn fmt.Errorf(\"not implemented\"), false\n}","line":{"from":420,"to":422}} {"id":100007263,"name":"convertState","signature":"func convertState(state kubecontainer.State) plegContainerState","file":"pkg/kubelet/pleg/generic.go","code":"func convertState(state kubecontainer.State) plegContainerState {\n\tswitch state {\n\tcase kubecontainer.ContainerStateCreated:\n\t\t// kubelet doesn't use the \"created\" state yet, hence convert it to \"unknown\".\n\t\treturn plegContainerUnknown\n\tcase kubecontainer.ContainerStateRunning:\n\t\treturn plegContainerRunning\n\tcase kubecontainer.ContainerStateExited:\n\t\treturn plegContainerExited\n\tcase kubecontainer.ContainerStateUnknown:\n\t\treturn plegContainerUnknown\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unrecognized container state: %v\", state))\n\t}\n}","line":{"from":95,"to":109}} {"id":100007264,"name":"NewGenericPLEG","signature":"func NewGenericPLEG(runtime kubecontainer.Runtime, eventChannel chan *PodLifecycleEvent,","file":"pkg/kubelet/pleg/generic.go","code":"// NewGenericPLEG instantiates a new GenericPLEG object and return it.\nfunc NewGenericPLEG(runtime kubecontainer.Runtime, eventChannel chan *PodLifecycleEvent,\n\trelistDuration *RelistDuration, cache kubecontainer.Cache,\n\tclock clock.Clock) PodLifecycleEventGenerator {\n\treturn \u0026GenericPLEG{\n\t\trelistDuration: relistDuration,\n\t\truntime: runtime,\n\t\teventChannel: eventChannel,\n\t\tpodRecords: make(podRecords),\n\t\tcache: cache,\n\t\tclock: clock,\n\t}\n}","line":{"from":118,"to":130}} {"id":100007265,"name":"Watch","signature":"func (g *GenericPLEG) Watch() chan *PodLifecycleEvent","file":"pkg/kubelet/pleg/generic.go","code":"// Watch returns a channel from which the subscriber can receive PodLifecycleEvent\n// events.\n// TODO: support multiple subscribers.\nfunc (g *GenericPLEG) Watch() chan *PodLifecycleEvent {\n\treturn g.eventChannel\n}","line":{"from":132,"to":137}} {"id":100007266,"name":"Start","signature":"func (g *GenericPLEG) Start()","file":"pkg/kubelet/pleg/generic.go","code":"// Start spawns a goroutine to relist periodically.\nfunc (g *GenericPLEG) Start() {\n\tg.runningMu.Lock()\n\tdefer g.runningMu.Unlock()\n\tif !g.isRunning {\n\t\tg.isRunning = true\n\t\tg.stopCh = make(chan struct{})\n\t\tgo wait.Until(g.Relist, g.relistDuration.RelistPeriod, g.stopCh)\n\t}\n}","line":{"from":139,"to":148}} {"id":100007267,"name":"Stop","signature":"func (g *GenericPLEG) Stop()","file":"pkg/kubelet/pleg/generic.go","code":"func (g *GenericPLEG) Stop() {\n\tg.runningMu.Lock()\n\tdefer g.runningMu.Unlock()\n\tif g.isRunning {\n\t\tclose(g.stopCh)\n\t\tg.isRunning = false\n\t}\n}","line":{"from":150,"to":157}} {"id":100007268,"name":"Update","signature":"func (g *GenericPLEG) Update(relistDuration *RelistDuration)","file":"pkg/kubelet/pleg/generic.go","code":"func (g *GenericPLEG) Update(relistDuration *RelistDuration) {\n\tg.relistDuration = relistDuration\n}","line":{"from":159,"to":161}} {"id":100007269,"name":"Healthy","signature":"func (g *GenericPLEG) Healthy() (bool, error)","file":"pkg/kubelet/pleg/generic.go","code":"// Healthy check if PLEG work properly.\n// relistThreshold is the maximum interval between two relist.\nfunc (g *GenericPLEG) Healthy() (bool, error) {\n\trelistTime := g.getRelistTime()\n\tif relistTime.IsZero() {\n\t\treturn false, fmt.Errorf(\"pleg has yet to be successful\")\n\t}\n\t// Expose as metric so you can alert on `time()-pleg_last_seen_seconds \u003e nn`\n\tmetrics.PLEGLastSeen.Set(float64(relistTime.Unix()))\n\telapsed := g.clock.Since(relistTime)\n\tif elapsed \u003e g.relistDuration.RelistThreshold {\n\t\treturn false, fmt.Errorf(\"pleg was last seen active %v ago; threshold is %v\", elapsed, g.relistDuration.RelistThreshold)\n\t}\n\treturn true, nil\n}","line":{"from":163,"to":177}} {"id":100007270,"name":"generateEvents","signature":"func generateEvents(podID types.UID, cid string, oldState, newState plegContainerState) []*PodLifecycleEvent","file":"pkg/kubelet/pleg/generic.go","code":"func generateEvents(podID types.UID, cid string, oldState, newState plegContainerState) []*PodLifecycleEvent {\n\tif newState == oldState {\n\t\treturn nil\n\t}\n\n\tklog.V(4).InfoS(\"GenericPLEG\", \"podUID\", podID, \"containerID\", cid, \"oldState\", oldState, \"newState\", newState)\n\tswitch newState {\n\tcase plegContainerRunning:\n\t\treturn []*PodLifecycleEvent{{ID: podID, Type: ContainerStarted, Data: cid}}\n\tcase plegContainerExited:\n\t\treturn []*PodLifecycleEvent{{ID: podID, Type: ContainerDied, Data: cid}}\n\tcase plegContainerUnknown:\n\t\treturn []*PodLifecycleEvent{{ID: podID, Type: ContainerChanged, Data: cid}}\n\tcase plegContainerNonExistent:\n\t\tswitch oldState {\n\t\tcase plegContainerExited:\n\t\t\t// We already reported that the container died before.\n\t\t\treturn []*PodLifecycleEvent{{ID: podID, Type: ContainerRemoved, Data: cid}}\n\t\tdefault:\n\t\t\treturn []*PodLifecycleEvent{{ID: podID, Type: ContainerDied, Data: cid}, {ID: podID, Type: ContainerRemoved, Data: cid}}\n\t\t}\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unrecognized container state: %v\", newState))\n\t}\n}","line":{"from":179,"to":203}} {"id":100007271,"name":"getRelistTime","signature":"func (g *GenericPLEG) getRelistTime() time.Time","file":"pkg/kubelet/pleg/generic.go","code":"func (g *GenericPLEG) getRelistTime() time.Time {\n\tval := g.relistTime.Load()\n\tif val == nil {\n\t\treturn time.Time{}\n\t}\n\treturn val.(time.Time)\n}","line":{"from":205,"to":211}} {"id":100007272,"name":"updateRelistTime","signature":"func (g *GenericPLEG) updateRelistTime(timestamp time.Time)","file":"pkg/kubelet/pleg/generic.go","code":"func (g *GenericPLEG) updateRelistTime(timestamp time.Time) {\n\tg.relistTime.Store(timestamp)\n}","line":{"from":213,"to":215}} {"id":100007273,"name":"Relist","signature":"func (g *GenericPLEG) Relist()","file":"pkg/kubelet/pleg/generic.go","code":"// Relist queries the container runtime for list of pods/containers, compare\n// with the internal pods/containers, and generates events accordingly.\nfunc (g *GenericPLEG) Relist() {\n\tg.relistLock.Lock()\n\tdefer g.relistLock.Unlock()\n\n\tctx := context.Background()\n\tklog.V(5).InfoS(\"GenericPLEG: Relisting\")\n\n\tif lastRelistTime := g.getRelistTime(); !lastRelistTime.IsZero() {\n\t\tmetrics.PLEGRelistInterval.Observe(metrics.SinceInSeconds(lastRelistTime))\n\t}\n\n\ttimestamp := g.clock.Now()\n\tdefer func() {\n\t\tmetrics.PLEGRelistDuration.Observe(metrics.SinceInSeconds(timestamp))\n\t}()\n\n\t// Get all the pods.\n\tpodList, err := g.runtime.GetPods(ctx, true)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"GenericPLEG: Unable to retrieve pods\")\n\t\treturn\n\t}\n\n\tg.updateRelistTime(timestamp)\n\n\tpods := kubecontainer.Pods(podList)\n\t// update running pod and container count\n\tupdateRunningPodAndContainerMetrics(pods)\n\tg.podRecords.setCurrent(pods)\n\n\t// Compare the old and the current pods, and generate events.\n\teventsByPodID := map[types.UID][]*PodLifecycleEvent{}\n\tfor pid := range g.podRecords {\n\t\toldPod := g.podRecords.getOld(pid)\n\t\tpod := g.podRecords.getCurrent(pid)\n\t\t// Get all containers in the old and the new pod.\n\t\tallContainers := getContainersFromPods(oldPod, pod)\n\t\tfor _, container := range allContainers {\n\t\t\tevents := computeEvents(oldPod, pod, \u0026container.ID)\n\t\t\tfor _, e := range events {\n\t\t\t\tupdateEvents(eventsByPodID, e)\n\t\t\t}\n\t\t}\n\t}\n\n\tvar needsReinspection map[types.UID]*kubecontainer.Pod\n\tif g.cacheEnabled() {\n\t\tneedsReinspection = make(map[types.UID]*kubecontainer.Pod)\n\t}\n\n\t// If there are events associated with a pod, we should update the\n\t// podCache.\n\tfor pid, events := range eventsByPodID {\n\t\tpod := g.podRecords.getCurrent(pid)\n\t\tif g.cacheEnabled() {\n\t\t\t// updateCache() will inspect the pod and update the cache. If an\n\t\t\t// error occurs during the inspection, we want PLEG to retry again\n\t\t\t// in the next relist. To achieve this, we do not update the\n\t\t\t// associated podRecord of the pod, so that the change will be\n\t\t\t// detect again in the next relist.\n\t\t\t// TODO: If many pods changed during the same relist period,\n\t\t\t// inspecting the pod and getting the PodStatus to update the cache\n\t\t\t// serially may take a while. We should be aware of this and\n\t\t\t// parallelize if needed.\n\t\t\tif err, updated := g.updateCache(ctx, pod, pid); err != nil {\n\t\t\t\t// Rely on updateCache calling GetPodStatus to log the actual error.\n\t\t\t\tklog.V(4).ErrorS(err, \"PLEG: Ignoring events for pod\", \"pod\", klog.KRef(pod.Namespace, pod.Name))\n\n\t\t\t\t// make sure we try to reinspect the pod during the next relisting\n\t\t\t\tneedsReinspection[pid] = pod\n\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\t// this pod was in the list to reinspect and we did so because it had events, so remove it\n\t\t\t\t// from the list (we don't want the reinspection code below to inspect it a second time in\n\t\t\t\t// this relist execution)\n\t\t\t\tdelete(g.podsToReinspect, pid)\n\t\t\t\tif utilfeature.DefaultFeatureGate.Enabled(features.EventedPLEG) {\n\t\t\t\t\tif !updated {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Update the internal storage and send out the events.\n\t\tg.podRecords.update(pid)\n\n\t\t// Map from containerId to exit code; used as a temporary cache for lookup\n\t\tcontainerExitCode := make(map[string]int)\n\n\t\tfor i := range events {\n\t\t\t// Filter out events that are not reliable and no other components use yet.\n\t\t\tif events[i].Type == ContainerChanged {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase g.eventChannel \u003c- events[i]:\n\t\t\tdefault:\n\t\t\t\tmetrics.PLEGDiscardEvents.Inc()\n\t\t\t\tklog.ErrorS(nil, \"Event channel is full, discard this relist() cycle event\")\n\t\t\t}\n\t\t\t// Log exit code of containers when they finished in a particular event\n\t\t\tif events[i].Type == ContainerDied {\n\t\t\t\t// Fill up containerExitCode map for ContainerDied event when first time appeared\n\t\t\t\tif len(containerExitCode) == 0 \u0026\u0026 pod != nil \u0026\u0026 g.cache != nil {\n\t\t\t\t\t// Get updated podStatus\n\t\t\t\t\tstatus, err := g.cache.Get(pod.ID)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tfor _, containerStatus := range status.ContainerStatuses {\n\t\t\t\t\t\t\tcontainerExitCode[containerStatus.ID.ID] = containerStatus.ExitCode\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif containerID, ok := events[i].Data.(string); ok {\n\t\t\t\t\tif exitCode, ok := containerExitCode[containerID]; ok \u0026\u0026 pod != nil {\n\t\t\t\t\t\tklog.V(2).InfoS(\"Generic (PLEG): container finished\", \"podID\", pod.ID, \"containerID\", containerID, \"exitCode\", exitCode)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif g.cacheEnabled() {\n\t\t// reinspect any pods that failed inspection during the previous relist\n\t\tif len(g.podsToReinspect) \u003e 0 {\n\t\t\tklog.V(5).InfoS(\"GenericPLEG: Reinspecting pods that previously failed inspection\")\n\t\t\tfor pid, pod := range g.podsToReinspect {\n\t\t\t\tif err, _ := g.updateCache(ctx, pod, pid); err != nil {\n\t\t\t\t\t// Rely on updateCache calling GetPodStatus to log the actual error.\n\t\t\t\t\tklog.V(5).ErrorS(err, \"PLEG: pod failed reinspection\", \"pod\", klog.KRef(pod.Namespace, pod.Name))\n\t\t\t\t\tneedsReinspection[pid] = pod\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Update the cache timestamp. This needs to happen *after*\n\t\t// all pods have been properly updated in the cache.\n\t\tg.cache.UpdateTime(timestamp)\n\t}\n\n\t// make sure we retain the list of pods that need reinspecting the next time relist is called\n\tg.podsToReinspect = needsReinspection\n}","line":{"from":217,"to":361}} {"id":100007274,"name":"getContainersFromPods","signature":"func getContainersFromPods(pods ...*kubecontainer.Pod) []*kubecontainer.Container","file":"pkg/kubelet/pleg/generic.go","code":"func getContainersFromPods(pods ...*kubecontainer.Pod) []*kubecontainer.Container {\n\tcidSet := sets.NewString()\n\tvar containers []*kubecontainer.Container\n\tfillCidSet := func(cs []*kubecontainer.Container) {\n\t\tfor _, c := range cs {\n\t\t\tcid := c.ID.ID\n\t\t\tif cidSet.Has(cid) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcidSet.Insert(cid)\n\t\t\tcontainers = append(containers, c)\n\t\t}\n\t}\n\n\tfor _, p := range pods {\n\t\tif p == nil {\n\t\t\tcontinue\n\t\t}\n\t\tfillCidSet(p.Containers)\n\t\t// Update sandboxes as containers\n\t\t// TODO: keep track of sandboxes explicitly.\n\t\tfillCidSet(p.Sandboxes)\n\t}\n\treturn containers\n}","line":{"from":363,"to":387}} {"id":100007275,"name":"computeEvents","signature":"func computeEvents(oldPod, newPod *kubecontainer.Pod, cid *kubecontainer.ContainerID) []*PodLifecycleEvent","file":"pkg/kubelet/pleg/generic.go","code":"func computeEvents(oldPod, newPod *kubecontainer.Pod, cid *kubecontainer.ContainerID) []*PodLifecycleEvent {\n\tvar pid types.UID\n\tif oldPod != nil {\n\t\tpid = oldPod.ID\n\t} else if newPod != nil {\n\t\tpid = newPod.ID\n\t}\n\toldState := getContainerState(oldPod, cid)\n\tnewState := getContainerState(newPod, cid)\n\treturn generateEvents(pid, cid.ID, oldState, newState)\n}","line":{"from":389,"to":399}} {"id":100007276,"name":"cacheEnabled","signature":"func (g *GenericPLEG) cacheEnabled() bool","file":"pkg/kubelet/pleg/generic.go","code":"func (g *GenericPLEG) cacheEnabled() bool {\n\treturn g.cache != nil\n}","line":{"from":401,"to":403}} {"id":100007277,"name":"getPodIPs","signature":"func (g *GenericPLEG) getPodIPs(pid types.UID, status *kubecontainer.PodStatus) []string","file":"pkg/kubelet/pleg/generic.go","code":"// getPodIP preserves an older cached status' pod IP if the new status has no pod IPs\n// and its sandboxes have exited\nfunc (g *GenericPLEG) getPodIPs(pid types.UID, status *kubecontainer.PodStatus) []string {\n\tif len(status.IPs) != 0 {\n\t\treturn status.IPs\n\t}\n\n\toldStatus, err := g.cache.Get(pid)\n\tif err != nil || len(oldStatus.IPs) == 0 {\n\t\treturn nil\n\t}\n\n\tfor _, sandboxStatus := range status.SandboxStatuses {\n\t\t// If at least one sandbox is ready, then use this status update's pod IP\n\t\tif sandboxStatus.State == runtimeapi.PodSandboxState_SANDBOX_READY {\n\t\t\treturn status.IPs\n\t\t}\n\t}\n\n\t// For pods with no ready containers or sandboxes (like exited pods)\n\t// use the old status' pod IP\n\treturn oldStatus.IPs\n}","line":{"from":405,"to":427}} {"id":100007278,"name":"updateCache","signature":"func (g *GenericPLEG) updateCache(ctx context.Context, pod *kubecontainer.Pod, pid types.UID) (error, bool)","file":"pkg/kubelet/pleg/generic.go","code":"// updateCache tries to update the pod status in the kubelet cache and returns true if the\n// pod status was actually updated in the cache. It will return false if the pod status\n// was ignored by the cache.\nfunc (g *GenericPLEG) updateCache(ctx context.Context, pod *kubecontainer.Pod, pid types.UID) (error, bool) {\n\tif pod == nil {\n\t\t// The pod is missing in the current relist. This means that\n\t\t// the pod has no visible (active or inactive) containers.\n\t\tklog.V(4).InfoS(\"PLEG: Delete status for pod\", \"podUID\", string(pid))\n\t\tg.cache.Delete(pid)\n\t\treturn nil, true\n\t}\n\n\tg.podCacheMutex.Lock()\n\tdefer g.podCacheMutex.Unlock()\n\ttimestamp := g.clock.Now()\n\n\tstatus, err := g.runtime.GetPodStatus(ctx, pod.ID, pod.Name, pod.Namespace)\n\tif err != nil {\n\t\t// nolint:logcheck // Not using the result of klog.V inside the\n\t\t// if branch is okay, we just use it to determine whether the\n\t\t// additional \"podStatus\" key and its value should be added.\n\t\tif klog.V(6).Enabled() {\n\t\t\tklog.ErrorS(err, \"PLEG: Write status\", \"pod\", klog.KRef(pod.Namespace, pod.Name), \"podStatus\", status)\n\t\t} else {\n\t\t\tklog.ErrorS(err, \"PLEG: Write status\", \"pod\", klog.KRef(pod.Namespace, pod.Name))\n\t\t}\n\t} else {\n\t\tif klogV := klog.V(6); klogV.Enabled() {\n\t\t\tklogV.InfoS(\"PLEG: Write status\", \"pod\", klog.KRef(pod.Namespace, pod.Name), \"podStatus\", status)\n\t\t} else {\n\t\t\tklog.V(4).InfoS(\"PLEG: Write status\", \"pod\", klog.KRef(pod.Namespace, pod.Name))\n\t\t}\n\t\t// Preserve the pod IP across cache updates if the new IP is empty.\n\t\t// When a pod is torn down, kubelet may race with PLEG and retrieve\n\t\t// a pod status after network teardown, but the kubernetes API expects\n\t\t// the completed pod's IP to be available after the pod is dead.\n\t\tstatus.IPs = g.getPodIPs(pid, status)\n\t}\n\n\t// When we use Generic PLEG only, the PodStatus is saved in the cache without\n\t// any validation of the existing status against the current timestamp.\n\t// This works well when there is only Generic PLEG setting the PodStatus in the cache however,\n\t// if we have multiple entities, such as Evented PLEG, while trying to set the PodStatus in the\n\t// cache we may run into the racy timestamps given each of them were to calculate the timestamps\n\t// in their respective execution flow. While Generic PLEG calculates this timestamp and gets\n\t// the PodStatus, we can only calculate the corresponding timestamp in\n\t// Evented PLEG after the event has been received by the Kubelet.\n\t// For more details refer to:\n\t// https://github.com/kubernetes/enhancements/tree/master/keps/sig-node/3386-kubelet-evented-pleg#timestamp-of-the-pod-status\n\tif utilfeature.DefaultFeatureGate.Enabled(features.EventedPLEG) \u0026\u0026 isEventedPLEGInUse() {\n\t\ttimestamp = status.TimeStamp\n\t}\n\n\treturn err, g.cache.Set(pod.ID, status, err, timestamp)\n}","line":{"from":429,"to":483}} {"id":100007279,"name":"UpdateCache","signature":"func (g *GenericPLEG) UpdateCache(pod *kubecontainer.Pod, pid types.UID) (error, bool)","file":"pkg/kubelet/pleg/generic.go","code":"func (g *GenericPLEG) UpdateCache(pod *kubecontainer.Pod, pid types.UID) (error, bool) {\n\tctx := context.Background()\n\tif !g.cacheEnabled() {\n\t\treturn fmt.Errorf(\"pod cache disabled\"), false\n\t}\n\tif pod == nil {\n\t\treturn fmt.Errorf(\"pod cannot be nil\"), false\n\t}\n\treturn g.updateCache(ctx, pod, pid)\n}","line":{"from":485,"to":494}} {"id":100007280,"name":"updateEvents","signature":"func updateEvents(eventsByPodID map[types.UID][]*PodLifecycleEvent, e *PodLifecycleEvent)","file":"pkg/kubelet/pleg/generic.go","code":"func updateEvents(eventsByPodID map[types.UID][]*PodLifecycleEvent, e *PodLifecycleEvent) {\n\tif e == nil {\n\t\treturn\n\t}\n\teventsByPodID[e.ID] = append(eventsByPodID[e.ID], e)\n}","line":{"from":496,"to":501}} {"id":100007281,"name":"getContainerState","signature":"func getContainerState(pod *kubecontainer.Pod, cid *kubecontainer.ContainerID) plegContainerState","file":"pkg/kubelet/pleg/generic.go","code":"func getContainerState(pod *kubecontainer.Pod, cid *kubecontainer.ContainerID) plegContainerState {\n\t// Default to the non-existent state.\n\tstate := plegContainerNonExistent\n\tif pod == nil {\n\t\treturn state\n\t}\n\tc := pod.FindContainerByID(*cid)\n\tif c != nil {\n\t\treturn convertState(c.State)\n\t}\n\t// Search through sandboxes too.\n\tc = pod.FindSandboxByID(*cid)\n\tif c != nil {\n\t\treturn convertState(c.State)\n\t}\n\n\treturn state\n}","line":{"from":503,"to":520}} {"id":100007282,"name":"updateRunningPodAndContainerMetrics","signature":"func updateRunningPodAndContainerMetrics(pods []*kubecontainer.Pod)","file":"pkg/kubelet/pleg/generic.go","code":"func updateRunningPodAndContainerMetrics(pods []*kubecontainer.Pod) {\n\trunningSandboxNum := 0\n\t// intermediate map to store the count of each \"container_state\"\n\tcontainerStateCount := make(map[string]int)\n\n\tfor _, pod := range pods {\n\t\tcontainers := pod.Containers\n\t\tfor _, container := range containers {\n\t\t\t// update the corresponding \"container_state\" in map to set value for the gaugeVec metrics\n\t\t\tcontainerStateCount[string(container.State)]++\n\t\t}\n\n\t\tsandboxes := pod.Sandboxes\n\n\t\tfor _, sandbox := range sandboxes {\n\t\t\tif sandbox.State == kubecontainer.ContainerStateRunning {\n\t\t\t\trunningSandboxNum++\n\t\t\t\t// every pod should only have one running sandbox\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tfor key, value := range containerStateCount {\n\t\tmetrics.RunningContainerCount.WithLabelValues(key).Set(float64(value))\n\t}\n\n\t// Set the number of running pods in the parameter\n\tmetrics.RunningPodCount.Set(float64(runningSandboxNum))\n}","line":{"from":522,"to":550}} {"id":100007283,"name":"getOld","signature":"func (pr podRecords) getOld(id types.UID) *kubecontainer.Pod","file":"pkg/kubelet/pleg/generic.go","code":"func (pr podRecords) getOld(id types.UID) *kubecontainer.Pod {\n\tr, ok := pr[id]\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn r.old\n}","line":{"from":552,"to":558}} {"id":100007284,"name":"getCurrent","signature":"func (pr podRecords) getCurrent(id types.UID) *kubecontainer.Pod","file":"pkg/kubelet/pleg/generic.go","code":"func (pr podRecords) getCurrent(id types.UID) *kubecontainer.Pod {\n\tr, ok := pr[id]\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn r.current\n}","line":{"from":560,"to":566}} {"id":100007285,"name":"setCurrent","signature":"func (pr podRecords) setCurrent(pods []*kubecontainer.Pod)","file":"pkg/kubelet/pleg/generic.go","code":"func (pr podRecords) setCurrent(pods []*kubecontainer.Pod) {\n\tfor i := range pr {\n\t\tpr[i].current = nil\n\t}\n\tfor _, pod := range pods {\n\t\tif r, ok := pr[pod.ID]; ok {\n\t\t\tr.current = pod\n\t\t} else {\n\t\t\tpr[pod.ID] = \u0026podRecord{current: pod}\n\t\t}\n\t}\n}","line":{"from":568,"to":579}} {"id":100007286,"name":"update","signature":"func (pr podRecords) update(id types.UID)","file":"pkg/kubelet/pleg/generic.go","code":"func (pr podRecords) update(id types.UID) {\n\tr, ok := pr[id]\n\tif !ok {\n\t\treturn\n\t}\n\tpr.updateInternal(id, r)\n}","line":{"from":581,"to":587}} {"id":100007287,"name":"updateInternal","signature":"func (pr podRecords) updateInternal(id types.UID, r *podRecord)","file":"pkg/kubelet/pleg/generic.go","code":"func (pr podRecords) updateInternal(id types.UID, r *podRecord) {\n\tif r.current == nil {\n\t\t// Pod no longer exists; delete the entry.\n\t\tdelete(pr, id)\n\t\treturn\n\t}\n\tr.old = r.current\n\tr.current = nil\n}","line":{"from":589,"to":597}} {"id":100007288,"name":"NewActualStateOfWorld","signature":"func NewActualStateOfWorld() ActualStateOfWorld","file":"pkg/kubelet/pluginmanager/cache/actual_state_of_world.go","code":"// NewActualStateOfWorld returns a new instance of ActualStateOfWorld\nfunc NewActualStateOfWorld() ActualStateOfWorld {\n\treturn \u0026actualStateOfWorld{\n\t\tsocketFileToInfo: make(map[string]PluginInfo),\n\t}\n}","line":{"from":61,"to":66}} {"id":100007289,"name":"AddPlugin","signature":"func (asw *actualStateOfWorld) AddPlugin(pluginInfo PluginInfo) error","file":"pkg/kubelet/pluginmanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) AddPlugin(pluginInfo PluginInfo) error {\n\tasw.Lock()\n\tdefer asw.Unlock()\n\n\tif pluginInfo.SocketPath == \"\" {\n\t\treturn fmt.Errorf(\"socket path is empty\")\n\t}\n\tif _, ok := asw.socketFileToInfo[pluginInfo.SocketPath]; ok {\n\t\tklog.V(2).InfoS(\"Plugin exists in actual state cache\", \"path\", pluginInfo.SocketPath)\n\t}\n\tasw.socketFileToInfo[pluginInfo.SocketPath] = pluginInfo\n\treturn nil\n}","line":{"from":86,"to":98}} {"id":100007290,"name":"RemovePlugin","signature":"func (asw *actualStateOfWorld) RemovePlugin(socketPath string)","file":"pkg/kubelet/pluginmanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) RemovePlugin(socketPath string) {\n\tasw.Lock()\n\tdefer asw.Unlock()\n\n\tdelete(asw.socketFileToInfo, socketPath)\n}","line":{"from":100,"to":105}} {"id":100007291,"name":"GetRegisteredPlugins","signature":"func (asw *actualStateOfWorld) GetRegisteredPlugins() []PluginInfo","file":"pkg/kubelet/pluginmanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) GetRegisteredPlugins() []PluginInfo {\n\tasw.RLock()\n\tdefer asw.RUnlock()\n\n\tcurrentPlugins := []PluginInfo{}\n\tfor _, pluginInfo := range asw.socketFileToInfo {\n\t\tcurrentPlugins = append(currentPlugins, pluginInfo)\n\t}\n\treturn currentPlugins\n}","line":{"from":107,"to":116}} {"id":100007292,"name":"PluginExistsWithCorrectTimestamp","signature":"func (asw *actualStateOfWorld) PluginExistsWithCorrectTimestamp(pluginInfo PluginInfo) bool","file":"pkg/kubelet/pluginmanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) PluginExistsWithCorrectTimestamp(pluginInfo PluginInfo) bool {\n\tasw.RLock()\n\tdefer asw.RUnlock()\n\n\t// We need to check both if the socket file path exists, and the timestamp\n\t// matches the given plugin (from the desired state cache) timestamp\n\tactualStatePlugin, exists := asw.socketFileToInfo[pluginInfo.SocketPath]\n\treturn exists \u0026\u0026 (actualStatePlugin.Timestamp == pluginInfo.Timestamp)\n}","line":{"from":118,"to":126}} {"id":100007293,"name":"NewDesiredStateOfWorld","signature":"func NewDesiredStateOfWorld() DesiredStateOfWorld","file":"pkg/kubelet/pluginmanager/cache/desired_state_of_world.go","code":"// NewDesiredStateOfWorld returns a new instance of DesiredStateOfWorld.\nfunc NewDesiredStateOfWorld() DesiredStateOfWorld {\n\treturn \u0026desiredStateOfWorld{\n\t\tsocketFileToInfo: make(map[string]PluginInfo),\n\t}\n}","line":{"from":55,"to":60}} {"id":100007294,"name":"generatePluginMsgDetailed","signature":"func generatePluginMsgDetailed(prefixMsg, suffixMsg, socketPath, details string) (detailedMsg string)","file":"pkg/kubelet/pluginmanager/cache/desired_state_of_world.go","code":"// Generate a detailed error msg for logs\nfunc generatePluginMsgDetailed(prefixMsg, suffixMsg, socketPath, details string) (detailedMsg string) {\n\treturn fmt.Sprintf(\"%v for plugin at %q %v %v\", prefixMsg, socketPath, details, suffixMsg)\n}","line":{"from":72,"to":75}} {"id":100007295,"name":"generatePluginMsg","signature":"func generatePluginMsg(prefixMsg, suffixMsg, socketPath, details string) (simpleMsg, detailedMsg string)","file":"pkg/kubelet/pluginmanager/cache/desired_state_of_world.go","code":"// Generate a simplified error msg for events and a detailed error msg for logs\nfunc generatePluginMsg(prefixMsg, suffixMsg, socketPath, details string) (simpleMsg, detailedMsg string) {\n\tsimpleMsg = fmt.Sprintf(\"%v for plugin at %q %v\", prefixMsg, socketPath, suffixMsg)\n\treturn simpleMsg, generatePluginMsgDetailed(prefixMsg, suffixMsg, socketPath, details)\n}","line":{"from":77,"to":81}} {"id":100007296,"name":"GenerateMsgDetailed","signature":"func (plugin *PluginInfo) GenerateMsgDetailed(prefixMsg, suffixMsg string) (detailedMsg string)","file":"pkg/kubelet/pluginmanager/cache/desired_state_of_world.go","code":"// GenerateMsgDetailed returns detailed msgs for plugins to register\n// that can be used in logs.\n// The msg format follows the pattern \"\u003cprefixMsg\u003e \u003cplugin details\u003e \u003csuffixMsg\u003e\"\nfunc (plugin *PluginInfo) GenerateMsgDetailed(prefixMsg, suffixMsg string) (detailedMsg string) {\n\tdetailedStr := fmt.Sprintf(\"(plugin details: %v)\", plugin)\n\treturn generatePluginMsgDetailed(prefixMsg, suffixMsg, plugin.SocketPath, detailedStr)\n}","line":{"from":83,"to":89}} {"id":100007297,"name":"GenerateMsg","signature":"func (plugin *PluginInfo) GenerateMsg(prefixMsg, suffixMsg string) (simpleMsg, detailedMsg string)","file":"pkg/kubelet/pluginmanager/cache/desired_state_of_world.go","code":"// GenerateMsg returns simple and detailed msgs for plugins to register\n// that is user friendly and a detailed msg that can be used in logs.\n// The msg format follows the pattern \"\u003cprefixMsg\u003e \u003cplugin details\u003e \u003csuffixMsg\u003e\".\nfunc (plugin *PluginInfo) GenerateMsg(prefixMsg, suffixMsg string) (simpleMsg, detailedMsg string) {\n\tdetailedStr := fmt.Sprintf(\"(plugin details: %v)\", plugin)\n\treturn generatePluginMsg(prefixMsg, suffixMsg, plugin.SocketPath, detailedStr)\n}","line":{"from":91,"to":97}} {"id":100007298,"name":"GenerateErrorDetailed","signature":"func (plugin *PluginInfo) GenerateErrorDetailed(prefixMsg string, err error) (detailedErr error)","file":"pkg/kubelet/pluginmanager/cache/desired_state_of_world.go","code":"// GenerateErrorDetailed returns detailed errors for plugins to register\n// that can be used in logs.\n// The msg format follows the pattern \"\u003cprefixMsg\u003e \u003cplugin details\u003e: \u003cerr\u003e \",\nfunc (plugin *PluginInfo) GenerateErrorDetailed(prefixMsg string, err error) (detailedErr error) {\n\treturn fmt.Errorf(plugin.GenerateMsgDetailed(prefixMsg, errSuffix(err)))\n}","line":{"from":99,"to":104}} {"id":100007299,"name":"GenerateError","signature":"func (plugin *PluginInfo) GenerateError(prefixMsg string, err error) (simpleErr, detailedErr error)","file":"pkg/kubelet/pluginmanager/cache/desired_state_of_world.go","code":"// GenerateError returns simple and detailed errors for plugins to register\n// that is user friendly and a detailed error that can be used in logs.\n// The msg format follows the pattern \"\u003cprefixMsg\u003e \u003cplugin details\u003e: \u003cerr\u003e \".\nfunc (plugin *PluginInfo) GenerateError(prefixMsg string, err error) (simpleErr, detailedErr error) {\n\tsimpleMsg, detailedMsg := plugin.GenerateMsg(prefixMsg, errSuffix(err))\n\treturn fmt.Errorf(simpleMsg), fmt.Errorf(detailedMsg)\n}","line":{"from":106,"to":112}} {"id":100007300,"name":"errSuffix","signature":"func errSuffix(err error) string","file":"pkg/kubelet/pluginmanager/cache/desired_state_of_world.go","code":"// Generates an error string with the format \": \u003cerr\u003e\" if err exists\nfunc errSuffix(err error) string {\n\terrStr := \"\"\n\tif err != nil {\n\t\terrStr = fmt.Sprintf(\": %v\", err)\n\t}\n\treturn errStr\n}","line":{"from":114,"to":121}} {"id":100007301,"name":"AddOrUpdatePlugin","signature":"func (dsw *desiredStateOfWorld) AddOrUpdatePlugin(socketPath string) error","file":"pkg/kubelet/pluginmanager/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) AddOrUpdatePlugin(socketPath string) error {\n\tdsw.Lock()\n\tdefer dsw.Unlock()\n\n\tif socketPath == \"\" {\n\t\treturn fmt.Errorf(\"socket path is empty\")\n\t}\n\tif _, ok := dsw.socketFileToInfo[socketPath]; ok {\n\t\tklog.V(2).InfoS(\"Plugin exists in desired state cache, timestamp will be updated\", \"path\", socketPath)\n\t}\n\n\t// Update the PluginInfo object.\n\t// Note that we only update the timestamp in the desired state of world, not the actual state of world\n\t// because in the reconciler, we need to check if the plugin in the actual state of world is the same\n\t// version as the plugin in the desired state of world\n\tdsw.socketFileToInfo[socketPath] = PluginInfo{\n\t\tSocketPath: socketPath,\n\t\tTimestamp: time.Now(),\n\t}\n\treturn nil\n}","line":{"from":123,"to":143}} {"id":100007302,"name":"RemovePlugin","signature":"func (dsw *desiredStateOfWorld) RemovePlugin(socketPath string)","file":"pkg/kubelet/pluginmanager/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) RemovePlugin(socketPath string) {\n\tdsw.Lock()\n\tdefer dsw.Unlock()\n\n\tdelete(dsw.socketFileToInfo, socketPath)\n}","line":{"from":145,"to":150}} {"id":100007303,"name":"GetPluginsToRegister","signature":"func (dsw *desiredStateOfWorld) GetPluginsToRegister() []PluginInfo","file":"pkg/kubelet/pluginmanager/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) GetPluginsToRegister() []PluginInfo {\n\tdsw.RLock()\n\tdefer dsw.RUnlock()\n\n\tpluginsToRegister := []PluginInfo{}\n\tfor _, pluginInfo := range dsw.socketFileToInfo {\n\t\tpluginsToRegister = append(pluginsToRegister, pluginInfo)\n\t}\n\treturn pluginsToRegister\n}","line":{"from":152,"to":161}} {"id":100007304,"name":"PluginExists","signature":"func (dsw *desiredStateOfWorld) PluginExists(socketPath string) bool","file":"pkg/kubelet/pluginmanager/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) PluginExists(socketPath string) bool {\n\tdsw.RLock()\n\tdefer dsw.RUnlock()\n\n\t_, exists := dsw.socketFileToInfo[socketPath]\n\treturn exists\n}","line":{"from":163,"to":169}} {"id":100007305,"name":"add","signature":"func (pc pluginCount) add(state, pluginName string)","file":"pkg/kubelet/pluginmanager/metrics/metrics.go","code":"func (pc pluginCount) add(state, pluginName string) {\n\tcount, ok := pc[state]\n\tif !ok {\n\t\tcount = map[string]int64{}\n\t}\n\tcount[pluginName]++\n\tpc[state] = count\n}","line":{"from":48,"to":55}} {"id":100007306,"name":"Register","signature":"func Register(asw cache.ActualStateOfWorld, dsw cache.DesiredStateOfWorld)","file":"pkg/kubelet/pluginmanager/metrics/metrics.go","code":"// Register registers Plugin Manager metrics.\nfunc Register(asw cache.ActualStateOfWorld, dsw cache.DesiredStateOfWorld) {\n\tregisterMetrics.Do(func() {\n\t\tlegacyregistry.CustomMustRegister(\u0026totalPluginsCollector{asw: asw, dsw: dsw})\n\t})\n}","line":{"from":57,"to":62}} {"id":100007307,"name":"DescribeWithStability","signature":"func (c *totalPluginsCollector) DescribeWithStability(ch chan\u003c- *metrics.Desc)","file":"pkg/kubelet/pluginmanager/metrics/metrics.go","code":"// DescribeWithStability implements the metrics.StableCollector interface.\nfunc (c *totalPluginsCollector) DescribeWithStability(ch chan\u003c- *metrics.Desc) {\n\tch \u003c- totalPluginsDesc\n}","line":{"from":73,"to":76}} {"id":100007308,"name":"CollectWithStability","signature":"func (c *totalPluginsCollector) CollectWithStability(ch chan\u003c- metrics.Metric)","file":"pkg/kubelet/pluginmanager/metrics/metrics.go","code":"// CollectWithStability implements the metrics.StableCollector interface.\nfunc (c *totalPluginsCollector) CollectWithStability(ch chan\u003c- metrics.Metric) {\n\tfor stateName, pluginCount := range c.getPluginCount() {\n\t\tfor socketPath, count := range pluginCount {\n\t\t\tch \u003c- metrics.NewLazyConstMetric(totalPluginsDesc,\n\t\t\t\tmetrics.GaugeValue,\n\t\t\t\tfloat64(count),\n\t\t\t\tsocketPath,\n\t\t\t\tstateName)\n\t\t}\n\t}\n}","line":{"from":78,"to":89}} {"id":100007309,"name":"getPluginCount","signature":"func (c *totalPluginsCollector) getPluginCount() pluginCount","file":"pkg/kubelet/pluginmanager/metrics/metrics.go","code":"func (c *totalPluginsCollector) getPluginCount() pluginCount {\n\tcounter := make(pluginCount)\n\tfor _, registeredPlugin := range c.asw.GetRegisteredPlugins() {\n\t\tsocketPath := registeredPlugin.SocketPath\n\t\tcounter.add(\"actual_state_of_world\", socketPath)\n\t}\n\n\tfor _, pluginToRegister := range c.dsw.GetPluginsToRegister() {\n\t\tsocketPath := pluginToRegister.SocketPath\n\t\tcounter.add(\"desired_state_of_world\", socketPath)\n\t}\n\treturn counter\n}","line":{"from":91,"to":103}} {"id":100007310,"name":"NewOperationExecutor","signature":"func NewOperationExecutor(","file":"pkg/kubelet/pluginmanager/operationexecutor/operation_executor.go","code":"// NewOperationExecutor returns a new instance of OperationExecutor.\nfunc NewOperationExecutor(\n\toperationGenerator OperationGenerator) OperationExecutor {\n\n\treturn \u0026operationExecutor{\n\t\tpendingOperations: goroutinemap.NewGoRoutineMap(true /* exponentialBackOffOnError */),\n\t\toperationGenerator: operationGenerator,\n\t}\n}","line":{"from":55,"to":63}} {"id":100007311,"name":"IsOperationPending","signature":"func (oe *operationExecutor) IsOperationPending(socketPath string) bool","file":"pkg/kubelet/pluginmanager/operationexecutor/operation_executor.go","code":"func (oe *operationExecutor) IsOperationPending(socketPath string) bool {\n\treturn oe.pendingOperations.IsOperationPending(socketPath)\n}","line":{"from":91,"to":93}} {"id":100007312,"name":"RegisterPlugin","signature":"func (oe *operationExecutor) RegisterPlugin(","file":"pkg/kubelet/pluginmanager/operationexecutor/operation_executor.go","code":"func (oe *operationExecutor) RegisterPlugin(\n\tsocketPath string,\n\ttimestamp time.Time,\n\tpluginHandlers map[string]cache.PluginHandler,\n\tactualStateOfWorld ActualStateOfWorldUpdater) error {\n\tgeneratedOperation :=\n\t\toe.operationGenerator.GenerateRegisterPluginFunc(socketPath, timestamp, pluginHandlers, actualStateOfWorld)\n\n\treturn oe.pendingOperations.Run(\n\t\tsocketPath, generatedOperation)\n}","line":{"from":95,"to":105}} {"id":100007313,"name":"UnregisterPlugin","signature":"func (oe *operationExecutor) UnregisterPlugin(","file":"pkg/kubelet/pluginmanager/operationexecutor/operation_executor.go","code":"func (oe *operationExecutor) UnregisterPlugin(\n\tpluginInfo cache.PluginInfo,\n\tactualStateOfWorld ActualStateOfWorldUpdater) error {\n\tgeneratedOperation :=\n\t\toe.operationGenerator.GenerateUnregisterPluginFunc(pluginInfo, actualStateOfWorld)\n\n\treturn oe.pendingOperations.Run(\n\t\tpluginInfo.SocketPath, generatedOperation)\n}","line":{"from":107,"to":115}} {"id":100007314,"name":"NewOperationGenerator","signature":"func NewOperationGenerator(recorder record.EventRecorder) OperationGenerator","file":"pkg/kubelet/pluginmanager/operationexecutor/operation_generator.go","code":"// NewOperationGenerator is returns instance of operationGenerator\nfunc NewOperationGenerator(recorder record.EventRecorder) OperationGenerator {\n\n\treturn \u0026operationGenerator{\n\t\trecorder: recorder,\n\t}\n}","line":{"from":52,"to":58}} {"id":100007315,"name":"GenerateRegisterPluginFunc","signature":"func (og *operationGenerator) GenerateRegisterPluginFunc(","file":"pkg/kubelet/pluginmanager/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) GenerateRegisterPluginFunc(\n\tsocketPath string,\n\ttimestamp time.Time,\n\tpluginHandlers map[string]cache.PluginHandler,\n\tactualStateOfWorldUpdater ActualStateOfWorldUpdater) func() error {\n\n\tregisterPluginFunc := func() error {\n\t\tclient, conn, err := dial(socketPath, dialTimeoutDuration)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"RegisterPlugin error -- dial failed at socket %s, err: %v\", socketPath, err)\n\t\t}\n\t\tdefer conn.Close()\n\n\t\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\t\tdefer cancel()\n\n\t\tinfoResp, err := client.GetInfo(ctx, \u0026registerapi.InfoRequest{})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"RegisterPlugin error -- failed to get plugin info using RPC GetInfo at socket %s, err: %v\", socketPath, err)\n\t\t}\n\n\t\thandler, ok := pluginHandlers[infoResp.Type]\n\t\tif !ok {\n\t\t\tif err := og.notifyPlugin(client, false, fmt.Sprintf(\"RegisterPlugin error -- no handler registered for plugin type: %s at socket %s\", infoResp.Type, socketPath)); err != nil {\n\t\t\t\treturn fmt.Errorf(\"RegisterPlugin error -- failed to send error at socket %s, err: %v\", socketPath, err)\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"RegisterPlugin error -- no handler registered for plugin type: %s at socket %s\", infoResp.Type, socketPath)\n\t\t}\n\n\t\tif infoResp.Endpoint == \"\" {\n\t\t\tinfoResp.Endpoint = socketPath\n\t\t}\n\t\tif err := handler.ValidatePlugin(infoResp.Name, infoResp.Endpoint, infoResp.SupportedVersions); err != nil {\n\t\t\tif err = og.notifyPlugin(client, false, fmt.Sprintf(\"RegisterPlugin error -- plugin validation failed with err: %v\", err)); err != nil {\n\t\t\t\treturn fmt.Errorf(\"RegisterPlugin error -- failed to send error at socket %s, err: %v\", socketPath, err)\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"RegisterPlugin error -- pluginHandler.ValidatePluginFunc failed\")\n\t\t}\n\t\t// We add the plugin to the actual state of world cache before calling a plugin consumer's Register handle\n\t\t// so that if we receive a delete event during Register Plugin, we can process it as a DeRegister call.\n\t\terr = actualStateOfWorldUpdater.AddPlugin(cache.PluginInfo{\n\t\t\tSocketPath: socketPath,\n\t\t\tTimestamp: timestamp,\n\t\t\tHandler: handler,\n\t\t\tName: infoResp.Name,\n\t\t})\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"RegisterPlugin error -- failed to add plugin\", \"path\", socketPath)\n\t\t}\n\t\tif err := handler.RegisterPlugin(infoResp.Name, infoResp.Endpoint, infoResp.SupportedVersions); err != nil {\n\t\t\treturn og.notifyPlugin(client, false, fmt.Sprintf(\"RegisterPlugin error -- plugin registration failed with err: %v\", err))\n\t\t}\n\n\t\t// Notify is called after register to guarantee that even if notify throws an error Register will always be called after validate\n\t\tif err := og.notifyPlugin(client, true, \"\"); err != nil {\n\t\t\treturn fmt.Errorf(\"RegisterPlugin error -- failed to send registration status at socket %s, err: %v\", socketPath, err)\n\t\t}\n\t\treturn nil\n\t}\n\treturn registerPluginFunc\n}","line":{"from":75,"to":135}} {"id":100007316,"name":"GenerateUnregisterPluginFunc","signature":"func (og *operationGenerator) GenerateUnregisterPluginFunc(","file":"pkg/kubelet/pluginmanager/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) GenerateUnregisterPluginFunc(\n\tpluginInfo cache.PluginInfo,\n\tactualStateOfWorldUpdater ActualStateOfWorldUpdater) func() error {\n\n\tunregisterPluginFunc := func() error {\n\t\tif pluginInfo.Handler == nil {\n\t\t\treturn fmt.Errorf(\"UnregisterPlugin error -- failed to get plugin handler for %s\", pluginInfo.SocketPath)\n\t\t}\n\t\t// We remove the plugin to the actual state of world cache before calling a plugin consumer's Unregister handle\n\t\t// so that if we receive a register event during Register Plugin, we can process it as a Register call.\n\t\tactualStateOfWorldUpdater.RemovePlugin(pluginInfo.SocketPath)\n\n\t\tpluginInfo.Handler.DeRegisterPlugin(pluginInfo.Name)\n\n\t\tklog.V(4).InfoS(\"DeRegisterPlugin called\", \"pluginName\", pluginInfo.Name, \"pluginHandler\", pluginInfo.Handler)\n\t\treturn nil\n\t}\n\treturn unregisterPluginFunc\n}","line":{"from":137,"to":155}} {"id":100007317,"name":"notifyPlugin","signature":"func (og *operationGenerator) notifyPlugin(client registerapi.RegistrationClient, registered bool, errStr string) error","file":"pkg/kubelet/pluginmanager/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) notifyPlugin(client registerapi.RegistrationClient, registered bool, errStr string) error {\n\tctx, cancel := context.WithTimeout(context.Background(), notifyTimeoutDuration)\n\tdefer cancel()\n\n\tstatus := \u0026registerapi.RegistrationStatus{\n\t\tPluginRegistered: registered,\n\t\tError: errStr,\n\t}\n\n\tif _, err := client.NotifyRegistrationStatus(ctx, status); err != nil {\n\t\treturn fmt.Errorf(\"%s: %w\", errStr, err)\n\t}\n\n\tif errStr != \"\" {\n\t\treturn errors.New(errStr)\n\t}\n\n\treturn nil\n}","line":{"from":157,"to":175}} {"id":100007318,"name":"dial","signature":"func dial(unixSocketPath string, timeout time.Duration) (registerapi.RegistrationClient, *grpc.ClientConn, error)","file":"pkg/kubelet/pluginmanager/operationexecutor/operation_generator.go","code":"// Dial establishes the gRPC communication with the picked up plugin socket. https://godoc.org/google.golang.org/grpc#Dial\nfunc dial(unixSocketPath string, timeout time.Duration) (registerapi.RegistrationClient, *grpc.ClientConn, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\tdefer cancel()\n\n\tc, err := grpc.DialContext(ctx, unixSocketPath,\n\t\tgrpc.WithTransportCredentials(insecure.NewCredentials()),\n\t\tgrpc.WithBlock(),\n\t\tgrpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) {\n\t\t\treturn (\u0026net.Dialer{}).DialContext(ctx, \"unix\", addr)\n\t\t}),\n\t)\n\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to dial socket %s, err: %v\", unixSocketPath, err)\n\t}\n\n\treturn registerapi.NewRegistrationClient(c), c, nil\n}","line":{"from":177,"to":195}} {"id":100007319,"name":"NewPluginManager","signature":"func NewPluginManager(","file":"pkg/kubelet/pluginmanager/plugin_manager.go","code":"// NewPluginManager returns a new concrete instance implementing the\n// PluginManager interface.\nfunc NewPluginManager(\n\tsockDir string,\n\trecorder record.EventRecorder) PluginManager {\n\tasw := cache.NewActualStateOfWorld()\n\tdsw := cache.NewDesiredStateOfWorld()\n\treconciler := reconciler.NewReconciler(\n\t\toperationexecutor.NewOperationExecutor(\n\t\t\toperationexecutor.NewOperationGenerator(\n\t\t\t\trecorder,\n\t\t\t),\n\t\t),\n\t\tloopSleepDuration,\n\t\tdsw,\n\t\tasw,\n\t)\n\n\tpm := \u0026pluginManager{\n\t\tdesiredStateOfWorldPopulator: pluginwatcher.NewWatcher(\n\t\t\tsockDir,\n\t\t\tdsw,\n\t\t),\n\t\treconciler: reconciler,\n\t\tdesiredStateOfWorld: dsw,\n\t\tactualStateOfWorld: asw,\n\t}\n\treturn pm\n}","line":{"from":52,"to":80}} {"id":100007320,"name":"Run","signature":"func (pm *pluginManager) Run(sourcesReady config.SourcesReady, stopCh \u003c-chan struct{})","file":"pkg/kubelet/pluginmanager/plugin_manager.go","code":"func (pm *pluginManager) Run(sourcesReady config.SourcesReady, stopCh \u003c-chan struct{}) {\n\tdefer runtime.HandleCrash()\n\n\tif err := pm.desiredStateOfWorldPopulator.Start(stopCh); err != nil {\n\t\tklog.ErrorS(err, \"The desired_state_of_world populator (plugin watcher) starts failed!\")\n\t\treturn\n\t}\n\n\tklog.V(2).InfoS(\"The desired_state_of_world populator (plugin watcher) starts\")\n\n\tklog.InfoS(\"Starting Kubelet Plugin Manager\")\n\tgo pm.reconciler.Run(stopCh)\n\n\tmetrics.Register(pm.actualStateOfWorld, pm.desiredStateOfWorld)\n\t\u003c-stopCh\n\tklog.InfoS(\"Shutting down Kubelet Plugin Manager\")\n}","line":{"from":108,"to":124}} {"id":100007321,"name":"AddHandler","signature":"func (pm *pluginManager) AddHandler(pluginType string, handler cache.PluginHandler)","file":"pkg/kubelet/pluginmanager/plugin_manager.go","code":"func (pm *pluginManager) AddHandler(pluginType string, handler cache.PluginHandler) {\n\tpm.reconciler.AddHandler(pluginType, handler)\n}","line":{"from":126,"to":128}} {"id":100007322,"name":"NewWatcher","signature":"func NewWatcher(sockDir string, desiredStateOfWorld cache.DesiredStateOfWorld) *Watcher","file":"pkg/kubelet/pluginmanager/pluginwatcher/plugin_watcher.go","code":"// NewWatcher provides a new watcher for socket registration\nfunc NewWatcher(sockDir string, desiredStateOfWorld cache.DesiredStateOfWorld) *Watcher {\n\treturn \u0026Watcher{\n\t\tpath: sockDir,\n\t\tfs: \u0026utilfs.DefaultFs{},\n\t\tdesiredStateOfWorld: desiredStateOfWorld,\n\t}\n}","line":{"from":40,"to":47}} {"id":100007323,"name":"Start","signature":"func (w *Watcher) Start(stopCh \u003c-chan struct{}) error","file":"pkg/kubelet/pluginmanager/pluginwatcher/plugin_watcher.go","code":"// Start watches for the creation and deletion of plugin sockets at the path\nfunc (w *Watcher) Start(stopCh \u003c-chan struct{}) error {\n\tklog.V(2).InfoS(\"Plugin Watcher Start\", \"path\", w.path)\n\n\t// Creating the directory to be watched if it doesn't exist yet,\n\t// and walks through the directory to discover the existing plugins.\n\tif err := w.init(); err != nil {\n\t\treturn err\n\t}\n\n\tfsWatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to start plugin fsWatcher, err: %v\", err)\n\t}\n\tw.fsWatcher = fsWatcher\n\n\t// Traverse plugin dir and add filesystem watchers before starting the plugin processing goroutine.\n\tif err := w.traversePluginDir(w.path); err != nil {\n\t\tklog.ErrorS(err, \"Failed to traverse plugin socket path\", \"path\", w.path)\n\t}\n\n\tgo func(fsWatcher *fsnotify.Watcher) {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event := \u003c-fsWatcher.Events:\n\t\t\t\t//TODO: Handle errors by taking corrective measures\n\t\t\t\tif event.Has(fsnotify.Create) {\n\t\t\t\t\terr := w.handleCreateEvent(event)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tklog.ErrorS(err, \"Error when handling create event\", \"event\", event)\n\t\t\t\t\t}\n\t\t\t\t} else if event.Has(fsnotify.Remove) {\n\t\t\t\t\tw.handleDeleteEvent(event)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\tcase err := \u003c-fsWatcher.Errors:\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"FsWatcher received error\")\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\tcase \u003c-stopCh:\n\t\t\t\tw.fsWatcher.Close()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}(fsWatcher)\n\n\treturn nil\n}","line":{"from":49,"to":97}} {"id":100007324,"name":"init","signature":"func (w *Watcher) init() error","file":"pkg/kubelet/pluginmanager/pluginwatcher/plugin_watcher.go","code":"func (w *Watcher) init() error {\n\tklog.V(4).InfoS(\"Ensuring Plugin directory\", \"path\", w.path)\n\n\tif err := w.fs.MkdirAll(w.path, 0755); err != nil {\n\t\treturn fmt.Errorf(\"error (re-)creating root %s: %v\", w.path, err)\n\t}\n\n\treturn nil\n}","line":{"from":99,"to":107}} {"id":100007325,"name":"traversePluginDir","signature":"func (w *Watcher) traversePluginDir(dir string) error","file":"pkg/kubelet/pluginmanager/pluginwatcher/plugin_watcher.go","code":"// Walks through the plugin directory discover any existing plugin sockets.\n// Ignore all errors except root dir not being walkable\nfunc (w *Watcher) traversePluginDir(dir string) error {\n\t// watch the new dir\n\terr := w.fsWatcher.Add(dir)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to watch %s, err: %v\", w.path, err)\n\t}\n\t// traverse existing children in the dir\n\treturn w.fs.Walk(dir, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\tif path == dir {\n\t\t\t\treturn fmt.Errorf(\"error accessing path: %s error: %v\", path, err)\n\t\t\t}\n\n\t\t\tklog.ErrorS(err, \"Error accessing path\", \"path\", path)\n\t\t\treturn nil\n\t\t}\n\n\t\t// do not call fsWatcher.Add twice on the root dir to avoid potential problems.\n\t\tif path == dir {\n\t\t\treturn nil\n\t\t}\n\n\t\tmode := info.Mode()\n\t\tif mode.IsDir() {\n\t\t\tif err := w.fsWatcher.Add(path); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to watch %s, err: %v\", path, err)\n\t\t\t}\n\t\t} else if isSocket, _ := util.IsUnixDomainSocket(path); isSocket {\n\t\t\tevent := fsnotify.Event{\n\t\t\t\tName: path,\n\t\t\t\tOp: fsnotify.Create,\n\t\t\t}\n\t\t\t//TODO: Handle errors by taking corrective measures\n\t\t\tif err := w.handleCreateEvent(event); err != nil {\n\t\t\t\tklog.ErrorS(err, \"Error when handling create\", \"event\", event)\n\t\t\t}\n\t\t} else {\n\t\t\tklog.V(5).InfoS(\"Ignoring file\", \"path\", path, \"mode\", mode)\n\t\t}\n\n\t\treturn nil\n\t})\n}","line":{"from":109,"to":153}} {"id":100007326,"name":"handleCreateEvent","signature":"func (w *Watcher) handleCreateEvent(event fsnotify.Event) error","file":"pkg/kubelet/pluginmanager/pluginwatcher/plugin_watcher.go","code":"// Handle filesystem notify event.\n// Files names:\n// - MUST NOT start with a '.'\nfunc (w *Watcher) handleCreateEvent(event fsnotify.Event) error {\n\tklog.V(6).InfoS(\"Handling create event\", \"event\", event)\n\n\tfi, err := getStat(event)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"stat file %s failed: %v\", event.Name, err)\n\t}\n\n\tif strings.HasPrefix(fi.Name(), \".\") {\n\t\tklog.V(5).InfoS(\"Ignoring file (starts with '.')\", \"path\", fi.Name())\n\t\treturn nil\n\t}\n\n\tif !fi.IsDir() {\n\t\tisSocket, err := util.IsUnixDomainSocket(util.NormalizePath(event.Name))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to determine if file: %s is a unix domain socket: %v\", event.Name, err)\n\t\t}\n\t\tif !isSocket {\n\t\t\tklog.V(5).InfoS(\"Ignoring non socket file\", \"path\", fi.Name())\n\t\t\treturn nil\n\t\t}\n\n\t\treturn w.handlePluginRegistration(event.Name)\n\t}\n\n\treturn w.traversePluginDir(event.Name)\n}","line":{"from":155,"to":185}} {"id":100007327,"name":"handlePluginRegistration","signature":"func (w *Watcher) handlePluginRegistration(socketPath string) error","file":"pkg/kubelet/pluginmanager/pluginwatcher/plugin_watcher.go","code":"func (w *Watcher) handlePluginRegistration(socketPath string) error {\n\tsocketPath = getSocketPath(socketPath)\n\t// Update desired state of world list of plugins\n\t// If the socket path does exist in the desired world cache, there's still\n\t// a possibility that it has been deleted and recreated again before it is\n\t// removed from the desired world cache, so we still need to call AddOrUpdatePlugin\n\t// in this case to update the timestamp\n\tklog.V(2).InfoS(\"Adding socket path or updating timestamp to desired state cache\", \"path\", socketPath)\n\terr := w.desiredStateOfWorld.AddOrUpdatePlugin(socketPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error adding socket path %s or updating timestamp to desired state cache: %v\", socketPath, err)\n\t}\n\treturn nil\n}","line":{"from":187,"to":200}} {"id":100007328,"name":"handleDeleteEvent","signature":"func (w *Watcher) handleDeleteEvent(event fsnotify.Event)","file":"pkg/kubelet/pluginmanager/pluginwatcher/plugin_watcher.go","code":"func (w *Watcher) handleDeleteEvent(event fsnotify.Event) {\n\tklog.V(6).InfoS(\"Handling delete event\", \"event\", event)\n\n\tsocketPath := event.Name\n\tklog.V(2).InfoS(\"Removing socket path from desired state cache\", \"path\", socketPath)\n\tw.desiredStateOfWorld.RemovePlugin(socketPath)\n}","line":{"from":202,"to":208}} {"id":100007329,"name":"getStat","signature":"func getStat(event fsnotify.Event) (os.FileInfo, error)","file":"pkg/kubelet/pluginmanager/pluginwatcher/plugin_watcher_others.go","code":"func getStat(event fsnotify.Event) (os.FileInfo, error) {\n\treturn os.Stat(event.Name)\n}","line":{"from":28,"to":30}} {"id":100007330,"name":"getSocketPath","signature":"func getSocketPath(socketPath string) string","file":"pkg/kubelet/pluginmanager/pluginwatcher/plugin_watcher_others.go","code":"func getSocketPath(socketPath string) string {\n\treturn socketPath\n}","line":{"from":32,"to":34}} {"id":100007331,"name":"getStat","signature":"func getStat(event fsnotify.Event) (os.FileInfo, error)","file":"pkg/kubelet/pluginmanager/pluginwatcher/plugin_watcher_windows.go","code":"func getStat(event fsnotify.Event) (os.FileInfo, error) {\n\tfi, err := os.Stat(event.Name)\n\t// TODO: This is a workaround for Windows 20H2 issue for os.Stat(). Please see\n\t// microsoft/Windows-Containers#97 for details.\n\t// Once the issue is resvolved, the following os.Lstat() is not needed.\n\tif err != nil {\n\t\tfi, err = os.Lstat(event.Name)\n\t}\n\n\treturn fi, err\n}","line":{"from":28,"to":38}} {"id":100007332,"name":"NewReconciler","signature":"func NewReconciler(","file":"pkg/kubelet/pluginmanager/reconciler/reconciler.go","code":"// NewReconciler returns a new instance of Reconciler.\n//\n// operationExecutor - used to trigger register/unregister operations safely\n// (prevents more than one operation from being triggered on the same\n// socket path)\n//\n// loopSleepDuration - the amount of time the reconciler loop sleeps between\n// successive executions\n//\n// desiredStateOfWorld - cache containing the desired state of the world\n//\n// actualStateOfWorld - cache containing the actual state of the world\nfunc NewReconciler(\n\toperationExecutor operationexecutor.OperationExecutor,\n\tloopSleepDuration time.Duration,\n\tdesiredStateOfWorld cache.DesiredStateOfWorld,\n\tactualStateOfWorld cache.ActualStateOfWorld) Reconciler {\n\treturn \u0026reconciler{\n\t\toperationExecutor: operationExecutor,\n\t\tloopSleepDuration: loopSleepDuration,\n\t\tdesiredStateOfWorld: desiredStateOfWorld,\n\t\tactualStateOfWorld: actualStateOfWorld,\n\t\thandlers: make(map[string]cache.PluginHandler),\n\t}\n}","line":{"from":48,"to":72}} {"id":100007333,"name":"Run","signature":"func (rc *reconciler) Run(stopCh \u003c-chan struct{})","file":"pkg/kubelet/pluginmanager/reconciler/reconciler.go","code":"func (rc *reconciler) Run(stopCh \u003c-chan struct{}) {\n\twait.Until(func() {\n\t\trc.reconcile()\n\t},\n\t\trc.loopSleepDuration,\n\t\tstopCh)\n}","line":{"from":85,"to":91}} {"id":100007334,"name":"AddHandler","signature":"func (rc *reconciler) AddHandler(pluginType string, pluginHandler cache.PluginHandler)","file":"pkg/kubelet/pluginmanager/reconciler/reconciler.go","code":"func (rc *reconciler) AddHandler(pluginType string, pluginHandler cache.PluginHandler) {\n\trc.Lock()\n\tdefer rc.Unlock()\n\n\trc.handlers[pluginType] = pluginHandler\n}","line":{"from":93,"to":98}} {"id":100007335,"name":"getHandlers","signature":"func (rc *reconciler) getHandlers() map[string]cache.PluginHandler","file":"pkg/kubelet/pluginmanager/reconciler/reconciler.go","code":"func (rc *reconciler) getHandlers() map[string]cache.PluginHandler {\n\trc.RLock()\n\tdefer rc.RUnlock()\n\n\tvar copyHandlers = make(map[string]cache.PluginHandler)\n\tfor pluginType, handler := range rc.handlers {\n\t\tcopyHandlers[pluginType] = handler\n\t}\n\treturn copyHandlers\n}","line":{"from":100,"to":109}} {"id":100007336,"name":"reconcile","signature":"func (rc *reconciler) reconcile()","file":"pkg/kubelet/pluginmanager/reconciler/reconciler.go","code":"func (rc *reconciler) reconcile() {\n\t// Unregisterations are triggered before registrations\n\n\t// Ensure plugins that should be unregistered are unregistered.\n\tfor _, registeredPlugin := range rc.actualStateOfWorld.GetRegisteredPlugins() {\n\t\tunregisterPlugin := false\n\t\tif !rc.desiredStateOfWorld.PluginExists(registeredPlugin.SocketPath) {\n\t\t\tunregisterPlugin = true\n\t\t} else {\n\t\t\t// We also need to unregister the plugins that exist in both actual state of world\n\t\t\t// and desired state of world cache, but the timestamps don't match.\n\t\t\t// Iterate through desired state of world plugins and see if there's any plugin\n\t\t\t// with the same socket path but different timestamp.\n\t\t\tfor _, dswPlugin := range rc.desiredStateOfWorld.GetPluginsToRegister() {\n\t\t\t\tif dswPlugin.SocketPath == registeredPlugin.SocketPath \u0026\u0026 dswPlugin.Timestamp != registeredPlugin.Timestamp {\n\t\t\t\t\tklog.V(5).InfoS(\"An updated version of plugin has been found, unregistering the plugin first before reregistering\", \"plugin\", registeredPlugin)\n\t\t\t\t\tunregisterPlugin = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif unregisterPlugin {\n\t\t\tklog.V(5).InfoS(\"Starting operationExecutor.UnregisterPlugin\", \"plugin\", registeredPlugin)\n\t\t\terr := rc.operationExecutor.UnregisterPlugin(registeredPlugin, rc.actualStateOfWorld)\n\t\t\tif err != nil \u0026\u0026\n\t\t\t\t!goroutinemap.IsAlreadyExists(err) \u0026\u0026\n\t\t\t\t!exponentialbackoff.IsExponentialBackoff(err) {\n\t\t\t\t// Ignore goroutinemap.IsAlreadyExists and exponentialbackoff.IsExponentialBackoff errors, they are expected.\n\t\t\t\t// Log all other errors.\n\t\t\t\tklog.ErrorS(err, \"OperationExecutor.UnregisterPlugin failed\", \"plugin\", registeredPlugin)\n\t\t\t}\n\t\t\tif err == nil {\n\t\t\t\tklog.V(1).InfoS(\"OperationExecutor.UnregisterPlugin started\", \"plugin\", registeredPlugin)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Ensure plugins that should be registered are registered\n\tfor _, pluginToRegister := range rc.desiredStateOfWorld.GetPluginsToRegister() {\n\t\tif !rc.actualStateOfWorld.PluginExistsWithCorrectTimestamp(pluginToRegister) {\n\t\t\tklog.V(5).InfoS(\"Starting operationExecutor.RegisterPlugin\", \"plugin\", pluginToRegister)\n\t\t\terr := rc.operationExecutor.RegisterPlugin(pluginToRegister.SocketPath, pluginToRegister.Timestamp, rc.getHandlers(), rc.actualStateOfWorld)\n\t\t\tif err != nil \u0026\u0026\n\t\t\t\t!goroutinemap.IsAlreadyExists(err) \u0026\u0026\n\t\t\t\t!exponentialbackoff.IsExponentialBackoff(err) {\n\t\t\t\t// Ignore goroutinemap.IsAlreadyExists and exponentialbackoff.IsExponentialBackoff errors, they are expected.\n\t\t\t\tklog.ErrorS(err, \"OperationExecutor.RegisterPlugin failed\", \"plugin\", pluginToRegister)\n\t\t\t}\n\t\t\tif err == nil {\n\t\t\t\tklog.V(1).InfoS(\"OperationExecutor.RegisterPlugin started\", \"plugin\", pluginToRegister)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":111,"to":165}} {"id":100007337,"name":"NewBasicMirrorClient","signature":"func NewBasicMirrorClient(apiserverClient clientset.Interface, nodeName string, nodeGetter nodeGetter) MirrorClient","file":"pkg/kubelet/pod/mirror_client.go","code":"// NewBasicMirrorClient returns a new MirrorClient.\nfunc NewBasicMirrorClient(apiserverClient clientset.Interface, nodeName string, nodeGetter nodeGetter) MirrorClient {\n\treturn \u0026basicMirrorClient{\n\t\tapiserverClient: apiserverClient,\n\t\tnodeName: nodeName,\n\t\tnodeGetter: nodeGetter,\n\t}\n}","line":{"from":60,"to":67}} {"id":100007338,"name":"CreateMirrorPod","signature":"func (mc *basicMirrorClient) CreateMirrorPod(pod *v1.Pod) error","file":"pkg/kubelet/pod/mirror_client.go","code":"func (mc *basicMirrorClient) CreateMirrorPod(pod *v1.Pod) error {\n\tif mc.apiserverClient == nil {\n\t\treturn nil\n\t}\n\t// Make a copy of the pod.\n\tcopyPod := *pod\n\tcopyPod.Annotations = make(map[string]string)\n\n\tfor k, v := range pod.Annotations {\n\t\tcopyPod.Annotations[k] = v\n\t}\n\thash := getPodHash(pod)\n\tcopyPod.Annotations[kubetypes.ConfigMirrorAnnotationKey] = hash\n\n\t// With the MirrorPodNodeRestriction feature, mirror pods are required to have an owner reference\n\t// to the owning node.\n\t// See https://git.k8s.io/enhancements/keps/sig-auth/1314-node-restriction-pods/README.md\n\tnodeUID, err := mc.getNodeUID()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get node UID: %v\", err)\n\t}\n\tcontroller := true\n\tcopyPod.OwnerReferences = []metav1.OwnerReference{{\n\t\tAPIVersion: v1.SchemeGroupVersion.String(),\n\t\tKind: \"Node\",\n\t\tName: mc.nodeName,\n\t\tUID: nodeUID,\n\t\tController: \u0026controller,\n\t}}\n\n\tapiPod, err := mc.apiserverClient.CoreV1().Pods(copyPod.Namespace).Create(context.TODO(), \u0026copyPod, metav1.CreateOptions{})\n\tif err != nil \u0026\u0026 apierrors.IsAlreadyExists(err) {\n\t\t// Check if the existing pod is the same as the pod we want to create.\n\t\tif h, ok := apiPod.Annotations[kubetypes.ConfigMirrorAnnotationKey]; ok \u0026\u0026 h == hash {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn err\n}","line":{"from":69,"to":107}} {"id":100007339,"name":"DeleteMirrorPod","signature":"func (mc *basicMirrorClient) DeleteMirrorPod(podFullName string, uid *types.UID) (bool, error)","file":"pkg/kubelet/pod/mirror_client.go","code":"// DeleteMirrorPod deletes a mirror pod.\n// It takes the full name of the pod and optionally a UID. If the UID\n// is non-nil, the pod is deleted only if its UID matches the supplied UID.\n// It returns whether the pod was actually deleted, and any error returned\n// while parsing the name of the pod.\n// Non-existence of the pod or UID mismatch is not treated as an error; the\n// routine simply returns false in that case.\nfunc (mc *basicMirrorClient) DeleteMirrorPod(podFullName string, uid *types.UID) (bool, error) {\n\tif mc.apiserverClient == nil {\n\t\treturn false, nil\n\t}\n\tname, namespace, err := kubecontainer.ParsePodFullName(podFullName)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to parse a pod full name\", \"podFullName\", podFullName)\n\t\treturn false, err\n\t}\n\n\tvar uidValue types.UID\n\tif uid != nil {\n\t\tuidValue = *uid\n\t}\n\tklog.V(2).InfoS(\"Deleting a mirror pod\", \"pod\", klog.KRef(namespace, name), \"podUID\", uidValue)\n\n\tvar GracePeriodSeconds int64\n\tif err := mc.apiserverClient.CoreV1().Pods(namespace).Delete(context.TODO(), name, metav1.DeleteOptions{GracePeriodSeconds: \u0026GracePeriodSeconds, Preconditions: \u0026metav1.Preconditions{UID: uid}}); err != nil {\n\t\t// Unfortunately, there's no generic error for failing a precondition\n\t\tif !(apierrors.IsNotFound(err) || apierrors.IsConflict(err)) {\n\t\t\t// We should return the error here, but historically this routine does\n\t\t\t// not return an error unless it can't parse the pod name\n\t\t\tklog.ErrorS(err, \"Failed deleting a mirror pod\", \"pod\", klog.KRef(namespace, name))\n\t\t}\n\t\treturn false, nil\n\t}\n\treturn true, nil\n}","line":{"from":109,"to":143}} {"id":100007340,"name":"getNodeUID","signature":"func (mc *basicMirrorClient) getNodeUID() (types.UID, error)","file":"pkg/kubelet/pod/mirror_client.go","code":"func (mc *basicMirrorClient) getNodeUID() (types.UID, error) {\n\tnode, err := mc.nodeGetter.Get(mc.nodeName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif node.UID == \"\" {\n\t\treturn \"\", fmt.Errorf(\"UID unset for node %s\", mc.nodeName)\n\t}\n\treturn node.UID, nil\n}","line":{"from":145,"to":154}} {"id":100007341,"name":"getHashFromMirrorPod","signature":"func getHashFromMirrorPod(pod *v1.Pod) (string, bool)","file":"pkg/kubelet/pod/mirror_client.go","code":"func getHashFromMirrorPod(pod *v1.Pod) (string, bool) {\n\thash, ok := pod.Annotations[kubetypes.ConfigMirrorAnnotationKey]\n\treturn hash, ok\n}","line":{"from":156,"to":159}} {"id":100007342,"name":"getPodHash","signature":"func getPodHash(pod *v1.Pod) string","file":"pkg/kubelet/pod/mirror_client.go","code":"func getPodHash(pod *v1.Pod) string {\n\t// The annotation exists for all static pods.\n\treturn pod.Annotations[kubetypes.ConfigHashAnnotationKey]\n}","line":{"from":161,"to":164}} {"id":100007343,"name":"NewBasicPodManager","signature":"func NewBasicPodManager(client MirrorClient) Manager","file":"pkg/kubelet/pod/pod_manager.go","code":"// NewBasicPodManager returns a functional Manager.\nfunc NewBasicPodManager(client MirrorClient) Manager {\n\tpm := \u0026basicManager{}\n\tpm.MirrorClient = client\n\tpm.SetPods(nil)\n\treturn pm\n}","line":{"from":120,"to":126}} {"id":100007344,"name":"SetPods","signature":"func (pm *basicManager) SetPods(newPods []*v1.Pod)","file":"pkg/kubelet/pod/pod_manager.go","code":"// Set the internal pods based on the new pods.\nfunc (pm *basicManager) SetPods(newPods []*v1.Pod) {\n\tpm.lock.Lock()\n\tdefer pm.lock.Unlock()\n\n\tpm.podByUID = make(map[kubetypes.ResolvedPodUID]*v1.Pod)\n\tpm.podByFullName = make(map[string]*v1.Pod)\n\tpm.mirrorPodByUID = make(map[kubetypes.MirrorPodUID]*v1.Pod)\n\tpm.mirrorPodByFullName = make(map[string]*v1.Pod)\n\tpm.translationByUID = make(map[kubetypes.MirrorPodUID]kubetypes.ResolvedPodUID)\n\n\tpm.updatePodsInternal(newPods...)\n}","line":{"from":128,"to":140}} {"id":100007345,"name":"AddPod","signature":"func (pm *basicManager) AddPod(pod *v1.Pod)","file":"pkg/kubelet/pod/pod_manager.go","code":"func (pm *basicManager) AddPod(pod *v1.Pod) {\n\tpm.UpdatePod(pod)\n}","line":{"from":142,"to":144}} {"id":100007346,"name":"UpdatePod","signature":"func (pm *basicManager) UpdatePod(pod *v1.Pod)","file":"pkg/kubelet/pod/pod_manager.go","code":"func (pm *basicManager) UpdatePod(pod *v1.Pod) {\n\tpm.lock.Lock()\n\tdefer pm.lock.Unlock()\n\tpm.updatePodsInternal(pod)\n}","line":{"from":146,"to":150}} {"id":100007347,"name":"updateMetrics","signature":"func updateMetrics(oldPod, newPod *v1.Pod)","file":"pkg/kubelet/pod/pod_manager.go","code":"// updateMetrics updates the metrics surfaced by the pod manager.\n// oldPod or newPod may be nil to signify creation or deletion.\nfunc updateMetrics(oldPod, newPod *v1.Pod) {\n\tvar numEC int\n\tif oldPod != nil {\n\t\tnumEC -= len(oldPod.Spec.EphemeralContainers)\n\t}\n\tif newPod != nil {\n\t\tnumEC += len(newPod.Spec.EphemeralContainers)\n\t}\n\tif numEC != 0 {\n\t\tmetrics.ManagedEphemeralContainers.Add(float64(numEC))\n\t}\n}","line":{"from":152,"to":165}} {"id":100007348,"name":"updatePodsInternal","signature":"func (pm *basicManager) updatePodsInternal(pods ...*v1.Pod)","file":"pkg/kubelet/pod/pod_manager.go","code":"// updatePodsInternal replaces the given pods in the current state of the\n// manager, updating the various indices. The caller is assumed to hold the\n// lock.\nfunc (pm *basicManager) updatePodsInternal(pods ...*v1.Pod) {\n\tfor _, pod := range pods {\n\t\tpodFullName := kubecontainer.GetPodFullName(pod)\n\t\t// This logic relies on a static pod and its mirror to have the same name.\n\t\t// It is safe to type convert here due to the IsMirrorPod guard.\n\t\tif kubetypes.IsMirrorPod(pod) {\n\t\t\tmirrorPodUID := kubetypes.MirrorPodUID(pod.UID)\n\t\t\tpm.mirrorPodByUID[mirrorPodUID] = pod\n\t\t\tpm.mirrorPodByFullName[podFullName] = pod\n\t\t\tif p, ok := pm.podByFullName[podFullName]; ok {\n\t\t\t\tpm.translationByUID[mirrorPodUID] = kubetypes.ResolvedPodUID(p.UID)\n\t\t\t}\n\t\t} else {\n\t\t\tresolvedPodUID := kubetypes.ResolvedPodUID(pod.UID)\n\t\t\tupdateMetrics(pm.podByUID[resolvedPodUID], pod)\n\t\t\tpm.podByUID[resolvedPodUID] = pod\n\t\t\tpm.podByFullName[podFullName] = pod\n\t\t\tif mirror, ok := pm.mirrorPodByFullName[podFullName]; ok {\n\t\t\t\tpm.translationByUID[kubetypes.MirrorPodUID(mirror.UID)] = resolvedPodUID\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":167,"to":192}} {"id":100007349,"name":"DeletePod","signature":"func (pm *basicManager) DeletePod(pod *v1.Pod)","file":"pkg/kubelet/pod/pod_manager.go","code":"func (pm *basicManager) DeletePod(pod *v1.Pod) {\n\tupdateMetrics(pod, nil)\n\tpm.lock.Lock()\n\tdefer pm.lock.Unlock()\n\tpodFullName := kubecontainer.GetPodFullName(pod)\n\t// It is safe to type convert here due to the IsMirrorPod guard.\n\tif kubetypes.IsMirrorPod(pod) {\n\t\tmirrorPodUID := kubetypes.MirrorPodUID(pod.UID)\n\t\tdelete(pm.mirrorPodByUID, mirrorPodUID)\n\t\tdelete(pm.mirrorPodByFullName, podFullName)\n\t\tdelete(pm.translationByUID, mirrorPodUID)\n\t} else {\n\t\tdelete(pm.podByUID, kubetypes.ResolvedPodUID(pod.UID))\n\t\tdelete(pm.podByFullName, podFullName)\n\t}\n}","line":{"from":194,"to":209}} {"id":100007350,"name":"GetPods","signature":"func (pm *basicManager) GetPods() []*v1.Pod","file":"pkg/kubelet/pod/pod_manager.go","code":"func (pm *basicManager) GetPods() []*v1.Pod {\n\tpm.lock.RLock()\n\tdefer pm.lock.RUnlock()\n\treturn podsMapToPods(pm.podByUID)\n}","line":{"from":211,"to":215}} {"id":100007351,"name":"GetPodsAndMirrorPods","signature":"func (pm *basicManager) GetPodsAndMirrorPods() ([]*v1.Pod, []*v1.Pod)","file":"pkg/kubelet/pod/pod_manager.go","code":"func (pm *basicManager) GetPodsAndMirrorPods() ([]*v1.Pod, []*v1.Pod) {\n\tpm.lock.RLock()\n\tdefer pm.lock.RUnlock()\n\tpods := podsMapToPods(pm.podByUID)\n\tmirrorPods := mirrorPodsMapToMirrorPods(pm.mirrorPodByUID)\n\treturn pods, mirrorPods\n}","line":{"from":217,"to":223}} {"id":100007352,"name":"GetPodByUID","signature":"func (pm *basicManager) GetPodByUID(uid types.UID) (*v1.Pod, bool)","file":"pkg/kubelet/pod/pod_manager.go","code":"func (pm *basicManager) GetPodByUID(uid types.UID) (*v1.Pod, bool) {\n\tpm.lock.RLock()\n\tdefer pm.lock.RUnlock()\n\tpod, ok := pm.podByUID[kubetypes.ResolvedPodUID(uid)] // Safe conversion, map only holds non-mirrors.\n\treturn pod, ok\n}","line":{"from":225,"to":230}} {"id":100007353,"name":"GetPodByName","signature":"func (pm *basicManager) GetPodByName(namespace, name string) (*v1.Pod, bool)","file":"pkg/kubelet/pod/pod_manager.go","code":"func (pm *basicManager) GetPodByName(namespace, name string) (*v1.Pod, bool) {\n\tpodFullName := kubecontainer.BuildPodFullName(name, namespace)\n\treturn pm.GetPodByFullName(podFullName)\n}","line":{"from":232,"to":235}} {"id":100007354,"name":"GetPodByFullName","signature":"func (pm *basicManager) GetPodByFullName(podFullName string) (*v1.Pod, bool)","file":"pkg/kubelet/pod/pod_manager.go","code":"func (pm *basicManager) GetPodByFullName(podFullName string) (*v1.Pod, bool) {\n\tpm.lock.RLock()\n\tdefer pm.lock.RUnlock()\n\tpod, ok := pm.podByFullName[podFullName]\n\treturn pod, ok\n}","line":{"from":237,"to":242}} {"id":100007355,"name":"TranslatePodUID","signature":"func (pm *basicManager) TranslatePodUID(uid types.UID) kubetypes.ResolvedPodUID","file":"pkg/kubelet/pod/pod_manager.go","code":"func (pm *basicManager) TranslatePodUID(uid types.UID) kubetypes.ResolvedPodUID {\n\t// It is safe to type convert to a resolved UID because type conversion is idempotent.\n\tif uid == \"\" {\n\t\treturn kubetypes.ResolvedPodUID(uid)\n\t}\n\n\tpm.lock.RLock()\n\tdefer pm.lock.RUnlock()\n\tif translated, ok := pm.translationByUID[kubetypes.MirrorPodUID(uid)]; ok {\n\t\treturn translated\n\t}\n\treturn kubetypes.ResolvedPodUID(uid)\n}","line":{"from":244,"to":256}} {"id":100007356,"name":"GetUIDTranslations","signature":"func (pm *basicManager) GetUIDTranslations() (podToMirror map[kubetypes.ResolvedPodUID]kubetypes.MirrorPodUID,","file":"pkg/kubelet/pod/pod_manager.go","code":"func (pm *basicManager) GetUIDTranslations() (podToMirror map[kubetypes.ResolvedPodUID]kubetypes.MirrorPodUID,\n\tmirrorToPod map[kubetypes.MirrorPodUID]kubetypes.ResolvedPodUID) {\n\tpm.lock.RLock()\n\tdefer pm.lock.RUnlock()\n\n\tpodToMirror = make(map[kubetypes.ResolvedPodUID]kubetypes.MirrorPodUID, len(pm.translationByUID))\n\tmirrorToPod = make(map[kubetypes.MirrorPodUID]kubetypes.ResolvedPodUID, len(pm.translationByUID))\n\t// Insert empty translation mapping for all static pods.\n\tfor uid, pod := range pm.podByUID {\n\t\tif !kubetypes.IsStaticPod(pod) {\n\t\t\tcontinue\n\t\t}\n\t\tpodToMirror[uid] = \"\"\n\t}\n\t// Fill in translations. Notice that if there is no mirror pod for a\n\t// static pod, its uid will be translated into empty string \"\". This\n\t// is WAI, from the caller side we can know that the static pod doesn't\n\t// have a corresponding mirror pod instead of using static pod uid directly.\n\tfor k, v := range pm.translationByUID {\n\t\tmirrorToPod[k] = v\n\t\tpodToMirror[v] = k\n\t}\n\treturn podToMirror, mirrorToPod\n}","line":{"from":258,"to":281}} {"id":100007357,"name":"GetOrphanedMirrorPodNames","signature":"func (pm *basicManager) GetOrphanedMirrorPodNames() []string","file":"pkg/kubelet/pod/pod_manager.go","code":"func (pm *basicManager) GetOrphanedMirrorPodNames() []string {\n\tpm.lock.RLock()\n\tdefer pm.lock.RUnlock()\n\tvar podFullNames []string\n\tfor podFullName := range pm.mirrorPodByFullName {\n\t\tif _, ok := pm.podByFullName[podFullName]; !ok {\n\t\t\tpodFullNames = append(podFullNames, podFullName)\n\t\t}\n\t}\n\treturn podFullNames\n}","line":{"from":283,"to":293}} {"id":100007358,"name":"IsMirrorPodOf","signature":"func (pm *basicManager) IsMirrorPodOf(mirrorPod, pod *v1.Pod) bool","file":"pkg/kubelet/pod/pod_manager.go","code":"func (pm *basicManager) IsMirrorPodOf(mirrorPod, pod *v1.Pod) bool {\n\t// Check name and namespace first.\n\tif pod.Name != mirrorPod.Name || pod.Namespace != mirrorPod.Namespace {\n\t\treturn false\n\t}\n\thash, ok := getHashFromMirrorPod(mirrorPod)\n\tif !ok {\n\t\treturn false\n\t}\n\treturn hash == getPodHash(pod)\n}","line":{"from":295,"to":305}} {"id":100007359,"name":"podsMapToPods","signature":"func podsMapToPods(UIDMap map[kubetypes.ResolvedPodUID]*v1.Pod) []*v1.Pod","file":"pkg/kubelet/pod/pod_manager.go","code":"func podsMapToPods(UIDMap map[kubetypes.ResolvedPodUID]*v1.Pod) []*v1.Pod {\n\tpods := make([]*v1.Pod, 0, len(UIDMap))\n\tfor _, pod := range UIDMap {\n\t\tpods = append(pods, pod)\n\t}\n\treturn pods\n}","line":{"from":307,"to":313}} {"id":100007360,"name":"mirrorPodsMapToMirrorPods","signature":"func mirrorPodsMapToMirrorPods(UIDMap map[kubetypes.MirrorPodUID]*v1.Pod) []*v1.Pod","file":"pkg/kubelet/pod/pod_manager.go","code":"func mirrorPodsMapToMirrorPods(UIDMap map[kubetypes.MirrorPodUID]*v1.Pod) []*v1.Pod {\n\tpods := make([]*v1.Pod, 0, len(UIDMap))\n\tfor _, pod := range UIDMap {\n\t\tpods = append(pods, pod)\n\t}\n\treturn pods\n}","line":{"from":315,"to":321}} {"id":100007361,"name":"GetMirrorPodByPod","signature":"func (pm *basicManager) GetMirrorPodByPod(pod *v1.Pod) (*v1.Pod, bool)","file":"pkg/kubelet/pod/pod_manager.go","code":"func (pm *basicManager) GetMirrorPodByPod(pod *v1.Pod) (*v1.Pod, bool) {\n\tpm.lock.RLock()\n\tdefer pm.lock.RUnlock()\n\tmirrorPod, ok := pm.mirrorPodByFullName[kubecontainer.GetPodFullName(pod)]\n\treturn mirrorPod, ok\n}","line":{"from":323,"to":328}} {"id":100007362,"name":"GetPodByMirrorPod","signature":"func (pm *basicManager) GetPodByMirrorPod(mirrorPod *v1.Pod) (*v1.Pod, bool)","file":"pkg/kubelet/pod/pod_manager.go","code":"func (pm *basicManager) GetPodByMirrorPod(mirrorPod *v1.Pod) (*v1.Pod, bool) {\n\tpm.lock.RLock()\n\tdefer pm.lock.RUnlock()\n\tpod, ok := pm.podByFullName[kubecontainer.GetPodFullName(mirrorPod)]\n\treturn pod, ok\n}","line":{"from":330,"to":335}} {"id":100007363,"name":"Len","signature":"func (a containerStatusbyCreatedList) Len() int { return len(a) }","file":"pkg/kubelet/pod_container_deletor.go","code":"func (a containerStatusbyCreatedList) Len() int { return len(a) }","line":{"from":41,"to":41}} {"id":100007364,"name":"Swap","signature":"func (a containerStatusbyCreatedList) Swap(i, j int) { a[i], a[j] = a[j], a[i] }","file":"pkg/kubelet/pod_container_deletor.go","code":"func (a containerStatusbyCreatedList) Swap(i, j int) { a[i], a[j] = a[j], a[i] }","line":{"from":42,"to":42}} {"id":100007365,"name":"Less","signature":"func (a containerStatusbyCreatedList) Less(i, j int) bool","file":"pkg/kubelet/pod_container_deletor.go","code":"func (a containerStatusbyCreatedList) Less(i, j int) bool {\n\treturn a[i].CreatedAt.After(a[j].CreatedAt)\n}","line":{"from":43,"to":45}} {"id":100007366,"name":"newPodContainerDeletor","signature":"func newPodContainerDeletor(runtime kubecontainer.Runtime, containersToKeep int) *podContainerDeletor","file":"pkg/kubelet/pod_container_deletor.go","code":"func newPodContainerDeletor(runtime kubecontainer.Runtime, containersToKeep int) *podContainerDeletor {\n\tbuffer := make(chan kubecontainer.ContainerID, containerDeletorBufferLimit)\n\tgo wait.Until(func() {\n\t\tfor {\n\t\t\tid := \u003c-buffer\n\t\t\tif err := runtime.DeleteContainer(context.Background(), id); err != nil {\n\t\t\t\tklog.InfoS(\"DeleteContainer returned error\", \"containerID\", id, \"err\", err)\n\t\t\t}\n\t\t}\n\t}, 0, wait.NeverStop)\n\n\treturn \u0026podContainerDeletor{\n\t\tworker: buffer,\n\t\tcontainersToKeep: containersToKeep,\n\t}\n}","line":{"from":47,"to":62}} {"id":100007367,"name":"getContainersToDeleteInPod","signature":"func getContainersToDeleteInPod(filterContainerID string, podStatus *kubecontainer.PodStatus, containersToKeep int) containerStatusbyCreatedList","file":"pkg/kubelet/pod_container_deletor.go","code":"// getContainersToDeleteInPod returns the exited containers in a pod whose name matches the name inferred from filterContainerId (if not empty), ordered by the creation time from the latest to the earliest.\n// If filterContainerID is empty, all dead containers in the pod are returned.\nfunc getContainersToDeleteInPod(filterContainerID string, podStatus *kubecontainer.PodStatus, containersToKeep int) containerStatusbyCreatedList {\n\tmatchedContainer := func(filterContainerId string, podStatus *kubecontainer.PodStatus) *kubecontainer.Status {\n\t\tif filterContainerId == \"\" {\n\t\t\treturn nil\n\t\t}\n\t\tfor _, containerStatus := range podStatus.ContainerStatuses {\n\t\t\tif containerStatus.ID.ID == filterContainerId {\n\t\t\t\treturn containerStatus\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}(filterContainerID, podStatus)\n\n\tif filterContainerID != \"\" \u0026\u0026 matchedContainer == nil {\n\t\tklog.InfoS(\"Container not found in pod's containers\", \"containerID\", filterContainerID)\n\t\treturn containerStatusbyCreatedList{}\n\t}\n\n\t// Find the exited containers whose name matches the name of the container with id being filterContainerId\n\tvar candidates containerStatusbyCreatedList\n\tfor _, containerStatus := range podStatus.ContainerStatuses {\n\t\tif containerStatus.State != kubecontainer.ContainerStateExited {\n\t\t\tcontinue\n\t\t}\n\t\tif matchedContainer == nil || matchedContainer.Name == containerStatus.Name {\n\t\t\tcandidates = append(candidates, containerStatus)\n\t\t}\n\t}\n\n\tif len(candidates) \u003c= containersToKeep {\n\t\treturn containerStatusbyCreatedList{}\n\t}\n\tsort.Sort(candidates)\n\treturn candidates[containersToKeep:]\n}","line":{"from":64,"to":100}} {"id":100007368,"name":"deleteContainersInPod","signature":"func (p *podContainerDeletor) deleteContainersInPod(filterContainerID string, podStatus *kubecontainer.PodStatus, removeAll bool)","file":"pkg/kubelet/pod_container_deletor.go","code":"// deleteContainersInPod issues container deletion requests for containers selected by getContainersToDeleteInPod.\nfunc (p *podContainerDeletor) deleteContainersInPod(filterContainerID string, podStatus *kubecontainer.PodStatus, removeAll bool) {\n\tcontainersToKeep := p.containersToKeep\n\tif removeAll {\n\t\tcontainersToKeep = 0\n\t\tfilterContainerID = \"\"\n\t}\n\n\tfor _, candidate := range getContainersToDeleteInPod(filterContainerID, podStatus, containersToKeep) {\n\t\tselect {\n\t\tcase p.worker \u003c- candidate.ID:\n\t\tdefault:\n\t\t\tklog.InfoS(\"Failed to issue the request to remove container\", \"containerID\", candidate.ID)\n\t\t}\n\t}\n}","line":{"from":102,"to":117}} {"id":100007369,"name":"String","signature":"func (state PodWorkerState) String() string","file":"pkg/kubelet/pod_workers.go","code":"func (state PodWorkerState) String() string {\n\tswitch state {\n\tcase SyncPod:\n\t\treturn \"sync\"\n\tcase TerminatingPod:\n\t\treturn \"terminating\"\n\tcase TerminatedPod:\n\t\treturn \"terminated\"\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"the state %d is not defined\", state))\n\t}\n}","line":{"from":105,"to":116}} {"id":100007370,"name":"newPodSyncerFuncs","signature":"func newPodSyncerFuncs(s podSyncer) podSyncerFuncs","file":"pkg/kubelet/pod_workers.go","code":"func newPodSyncerFuncs(s podSyncer) podSyncerFuncs {\n\treturn podSyncerFuncs{\n\t\tsyncPod: s.SyncPod,\n\t\tsyncTerminatingPod: s.SyncTerminatingPod,\n\t\tsyncTerminatingRuntimePod: s.SyncTerminatingRuntimePod,\n\t\tsyncTerminatedPod: s.SyncTerminatedPod,\n\t}\n}","line":{"from":285,"to":292}} {"id":100007371,"name":"SyncPod","signature":"func (f podSyncerFuncs) SyncPod(ctx context.Context, updateType kubetypes.SyncPodType, pod *v1.Pod, mirrorPod *v1.Pod, podStatus *kubecontainer.PodStatus) (bool, error)","file":"pkg/kubelet/pod_workers.go","code":"func (f podSyncerFuncs) SyncPod(ctx context.Context, updateType kubetypes.SyncPodType, pod *v1.Pod, mirrorPod *v1.Pod, podStatus *kubecontainer.PodStatus) (bool, error) {\n\treturn f.syncPod(ctx, updateType, pod, mirrorPod, podStatus)\n}","line":{"from":296,"to":298}} {"id":100007372,"name":"SyncTerminatingPod","signature":"func (f podSyncerFuncs) SyncTerminatingPod(ctx context.Context, pod *v1.Pod, podStatus *kubecontainer.PodStatus, gracePeriod *int64, podStatusFn func(*v1.PodStatus)) error","file":"pkg/kubelet/pod_workers.go","code":"func (f podSyncerFuncs) SyncTerminatingPod(ctx context.Context, pod *v1.Pod, podStatus *kubecontainer.PodStatus, gracePeriod *int64, podStatusFn func(*v1.PodStatus)) error {\n\treturn f.syncTerminatingPod(ctx, pod, podStatus, gracePeriod, podStatusFn)\n}","line":{"from":299,"to":301}} {"id":100007373,"name":"SyncTerminatingRuntimePod","signature":"func (f podSyncerFuncs) SyncTerminatingRuntimePod(ctx context.Context, runningPod *kubecontainer.Pod) error","file":"pkg/kubelet/pod_workers.go","code":"func (f podSyncerFuncs) SyncTerminatingRuntimePod(ctx context.Context, runningPod *kubecontainer.Pod) error {\n\treturn f.syncTerminatingRuntimePod(ctx, runningPod)\n}","line":{"from":302,"to":304}} {"id":100007374,"name":"SyncTerminatedPod","signature":"func (f podSyncerFuncs) SyncTerminatedPod(ctx context.Context, pod *v1.Pod, podStatus *kubecontainer.PodStatus) error","file":"pkg/kubelet/pod_workers.go","code":"func (f podSyncerFuncs) SyncTerminatedPod(ctx context.Context, pod *v1.Pod, podStatus *kubecontainer.PodStatus) error {\n\treturn f.syncTerminatedPod(ctx, pod, podStatus)\n}","line":{"from":305,"to":307}} {"id":100007375,"name":"IsWorking","signature":"func (s *podSyncStatus) IsWorking() bool { return s.working }","file":"pkg/kubelet/pod_workers.go","code":"func (s *podSyncStatus) IsWorking() bool { return s.working }","line":{"from":405,"to":405}} {"id":100007376,"name":"IsTerminationRequested","signature":"func (s *podSyncStatus) IsTerminationRequested() bool { return !s.terminatingAt.IsZero() }","file":"pkg/kubelet/pod_workers.go","code":"func (s *podSyncStatus) IsTerminationRequested() bool { return !s.terminatingAt.IsZero() }","line":{"from":406,"to":406}} {"id":100007377,"name":"IsTerminationStarted","signature":"func (s *podSyncStatus) IsTerminationStarted() bool { return s.startedTerminating }","file":"pkg/kubelet/pod_workers.go","code":"func (s *podSyncStatus) IsTerminationStarted() bool { return s.startedTerminating }","line":{"from":407,"to":407}} {"id":100007378,"name":"IsTerminated","signature":"func (s *podSyncStatus) IsTerminated() bool { return !s.terminatedAt.IsZero() }","file":"pkg/kubelet/pod_workers.go","code":"func (s *podSyncStatus) IsTerminated() bool { return !s.terminatedAt.IsZero() }","line":{"from":408,"to":408}} {"id":100007379,"name":"IsFinished","signature":"func (s *podSyncStatus) IsFinished() bool { return s.finished }","file":"pkg/kubelet/pod_workers.go","code":"func (s *podSyncStatus) IsFinished() bool { return s.finished }","line":{"from":409,"to":409}} {"id":100007380,"name":"IsEvicted","signature":"func (s *podSyncStatus) IsEvicted() bool { return s.evicted }","file":"pkg/kubelet/pod_workers.go","code":"func (s *podSyncStatus) IsEvicted() bool { return s.evicted }","line":{"from":410,"to":410}} {"id":100007381,"name":"IsDeleted","signature":"func (s *podSyncStatus) IsDeleted() bool { return s.deleted }","file":"pkg/kubelet/pod_workers.go","code":"func (s *podSyncStatus) IsDeleted() bool { return s.deleted }","line":{"from":411,"to":411}} {"id":100007382,"name":"IsStarted","signature":"func (s *podSyncStatus) IsStarted() bool { return !s.startedAt.IsZero() }","file":"pkg/kubelet/pod_workers.go","code":"func (s *podSyncStatus) IsStarted() bool { return !s.startedAt.IsZero() }","line":{"from":412,"to":412}} {"id":100007383,"name":"WorkType","signature":"func (s *podSyncStatus) WorkType() PodWorkerState","file":"pkg/kubelet/pod_workers.go","code":"// WorkType returns this pods' current state of the pod in pod lifecycle state machine.\nfunc (s *podSyncStatus) WorkType() PodWorkerState {\n\tif s.IsTerminated() {\n\t\treturn TerminatedPod\n\t}\n\tif s.IsTerminationRequested() {\n\t\treturn TerminatingPod\n\t}\n\treturn SyncPod\n}","line":{"from":414,"to":423}} {"id":100007384,"name":"mergeLastUpdate","signature":"func (s *podSyncStatus) mergeLastUpdate(other UpdatePodOptions)","file":"pkg/kubelet/pod_workers.go","code":"// mergeLastUpdate records the most recent state from a new update. Pod and MirrorPod are\n// incremented. KillPodOptions is accumulated. If RunningPod is set, Pod is synthetic and\n// will *not* be used as the last pod state unless no previous pod state exists (because\n// the pod worker may be responsible for terminating a pod from a previous run of the\n// kubelet where no config state is visible). The contents of activeUpdate are used as the\n// source of truth for components downstream of the pod workers.\nfunc (s *podSyncStatus) mergeLastUpdate(other UpdatePodOptions) {\n\topts := s.activeUpdate\n\tif opts == nil {\n\t\topts = \u0026UpdatePodOptions{}\n\t\ts.activeUpdate = opts\n\t}\n\n\t// UpdatePodOptions states (and UpdatePod enforces) that either Pod or RunningPod\n\t// is set, and we wish to preserve the most recent Pod we have observed, so only\n\t// overwrite our Pod when we have no Pod or when RunningPod is nil.\n\tif opts.Pod == nil || other.RunningPod == nil {\n\t\topts.Pod = other.Pod\n\t}\n\t// running pods will not persist but will be remembered for replay\n\topts.RunningPod = other.RunningPod\n\t// if mirrorPod was not provided, remember the last one for replay\n\tif other.MirrorPod != nil {\n\t\topts.MirrorPod = other.MirrorPod\n\t}\n\t// accumulate kill pod options\n\tif other.KillPodOptions != nil {\n\t\topts.KillPodOptions = \u0026KillPodOptions{}\n\t\tif other.KillPodOptions.Evict {\n\t\t\topts.KillPodOptions.Evict = true\n\t\t}\n\t\tif override := other.KillPodOptions.PodTerminationGracePeriodSecondsOverride; override != nil {\n\t\t\tvalue := *override\n\t\t\topts.KillPodOptions.PodTerminationGracePeriodSecondsOverride = \u0026value\n\t\t}\n\t}\n\t// StartTime is not copied - that is purely for tracking latency of config propagation\n\t// from kubelet to pod worker.\n}","line":{"from":425,"to":463}} {"id":100007385,"name":"newPodWorkers","signature":"func newPodWorkers(","file":"pkg/kubelet/pod_workers.go","code":"func newPodWorkers(\n\tpodSyncer podSyncer,\n\trecorder record.EventRecorder,\n\tworkQueue queue.WorkQueue,\n\tresyncInterval, backOffPeriod time.Duration,\n\tpodCache kubecontainer.Cache,\n) PodWorkers {\n\treturn \u0026podWorkers{\n\t\tpodSyncStatuses: map[types.UID]*podSyncStatus{},\n\t\tpodUpdates: map[types.UID]chan struct{}{},\n\t\tstartedStaticPodsByFullname: map[string]types.UID{},\n\t\twaitingToStartStaticPodsByFullname: map[string][]types.UID{},\n\t\tpodSyncer: podSyncer,\n\t\trecorder: recorder,\n\t\tworkQueue: workQueue,\n\t\tresyncInterval: resyncInterval,\n\t\tbackOffPeriod: backOffPeriod,\n\t\tpodCache: podCache,\n\t\tclock: clock.RealClock{},\n\t}\n}","line":{"from":600,"to":620}} {"id":100007386,"name":"IsPodKnownTerminated","signature":"func (p *podWorkers) IsPodKnownTerminated(uid types.UID) bool","file":"pkg/kubelet/pod_workers.go","code":"func (p *podWorkers) IsPodKnownTerminated(uid types.UID) bool {\n\tp.podLock.Lock()\n\tdefer p.podLock.Unlock()\n\tif status, ok := p.podSyncStatuses[uid]; ok {\n\t\treturn status.IsTerminated()\n\t}\n\t// if the pod is not known, we return false (pod worker is not aware of it)\n\treturn false\n}","line":{"from":622,"to":630}} {"id":100007387,"name":"CouldHaveRunningContainers","signature":"func (p *podWorkers) CouldHaveRunningContainers(uid types.UID) bool","file":"pkg/kubelet/pod_workers.go","code":"func (p *podWorkers) CouldHaveRunningContainers(uid types.UID) bool {\n\tp.podLock.Lock()\n\tdefer p.podLock.Unlock()\n\tif status, ok := p.podSyncStatuses[uid]; ok {\n\t\treturn !status.IsTerminated()\n\t}\n\t// once all pods are synced, any pod without sync status is known to not be running.\n\treturn !p.podsSynced\n}","line":{"from":632,"to":640}} {"id":100007388,"name":"ShouldPodBeFinished","signature":"func (p *podWorkers) ShouldPodBeFinished(uid types.UID) bool","file":"pkg/kubelet/pod_workers.go","code":"func (p *podWorkers) ShouldPodBeFinished(uid types.UID) bool {\n\tp.podLock.Lock()\n\tdefer p.podLock.Unlock()\n\tif status, ok := p.podSyncStatuses[uid]; ok {\n\t\treturn status.IsFinished()\n\t}\n\t// once all pods are synced, any pod without sync status is assumed to\n\t// have SyncTerminatedPod finished.\n\treturn p.podsSynced\n}","line":{"from":642,"to":651}} {"id":100007389,"name":"IsPodTerminationRequested","signature":"func (p *podWorkers) IsPodTerminationRequested(uid types.UID) bool","file":"pkg/kubelet/pod_workers.go","code":"func (p *podWorkers) IsPodTerminationRequested(uid types.UID) bool {\n\tp.podLock.Lock()\n\tdefer p.podLock.Unlock()\n\tif status, ok := p.podSyncStatuses[uid]; ok {\n\t\t// the pod may still be setting up at this point.\n\t\treturn status.IsTerminationRequested()\n\t}\n\t// an unknown pod is considered not to be terminating (use ShouldPodContainersBeTerminating in\n\t// cleanup loops to avoid failing to cleanup pods that have already been removed from config)\n\treturn false\n}","line":{"from":653,"to":663}} {"id":100007390,"name":"ShouldPodContainersBeTerminating","signature":"func (p *podWorkers) ShouldPodContainersBeTerminating(uid types.UID) bool","file":"pkg/kubelet/pod_workers.go","code":"func (p *podWorkers) ShouldPodContainersBeTerminating(uid types.UID) bool {\n\tp.podLock.Lock()\n\tdefer p.podLock.Unlock()\n\tif status, ok := p.podSyncStatuses[uid]; ok {\n\t\t// we wait until the pod worker goroutine observes the termination, which means syncPod will not\n\t\t// be executed again, which means no new containers can be started\n\t\treturn status.IsTerminationStarted()\n\t}\n\t// once we've synced, if the pod isn't known to the workers we should be tearing them\n\t// down\n\treturn p.podsSynced\n}","line":{"from":665,"to":676}} {"id":100007391,"name":"ShouldPodRuntimeBeRemoved","signature":"func (p *podWorkers) ShouldPodRuntimeBeRemoved(uid types.UID) bool","file":"pkg/kubelet/pod_workers.go","code":"func (p *podWorkers) ShouldPodRuntimeBeRemoved(uid types.UID) bool {\n\tp.podLock.Lock()\n\tdefer p.podLock.Unlock()\n\tif status, ok := p.podSyncStatuses[uid]; ok {\n\t\treturn status.IsTerminated()\n\t}\n\t// a pod that hasn't been sent to the pod worker yet should have no runtime components once we have\n\t// synced all content.\n\treturn p.podsSynced\n}","line":{"from":678,"to":687}} {"id":100007392,"name":"ShouldPodContentBeRemoved","signature":"func (p *podWorkers) ShouldPodContentBeRemoved(uid types.UID) bool","file":"pkg/kubelet/pod_workers.go","code":"func (p *podWorkers) ShouldPodContentBeRemoved(uid types.UID) bool {\n\tp.podLock.Lock()\n\tdefer p.podLock.Unlock()\n\tif status, ok := p.podSyncStatuses[uid]; ok {\n\t\treturn status.IsEvicted() || (status.IsDeleted() \u0026\u0026 status.IsTerminated())\n\t}\n\t// a pod that hasn't been sent to the pod worker yet should have no content on disk once we have\n\t// synced all content.\n\treturn p.podsSynced\n}","line":{"from":689,"to":698}} {"id":100007393,"name":"IsPodForMirrorPodTerminatingByFullName","signature":"func (p *podWorkers) IsPodForMirrorPodTerminatingByFullName(podFullName string) bool","file":"pkg/kubelet/pod_workers.go","code":"func (p *podWorkers) IsPodForMirrorPodTerminatingByFullName(podFullName string) bool {\n\tp.podLock.Lock()\n\tdefer p.podLock.Unlock()\n\tuid, started := p.startedStaticPodsByFullname[podFullName]\n\tif !started {\n\t\treturn false\n\t}\n\tstatus, exists := p.podSyncStatuses[uid]\n\tif !exists {\n\t\treturn false\n\t}\n\tif !status.IsTerminationRequested() || status.IsTerminated() {\n\t\treturn false\n\t}\n\n\treturn true\n}","line":{"from":700,"to":716}} {"id":100007394,"name":"isPodStatusCacheTerminal","signature":"func isPodStatusCacheTerminal(status *kubecontainer.PodStatus) bool","file":"pkg/kubelet/pod_workers.go","code":"func isPodStatusCacheTerminal(status *kubecontainer.PodStatus) bool {\n\trunningContainers := 0\n\trunningSandboxes := 0\n\tfor _, container := range status.ContainerStatuses {\n\t\tif container.State == kubecontainer.ContainerStateRunning {\n\t\t\trunningContainers++\n\t\t}\n\t}\n\tfor _, sb := range status.SandboxStatuses {\n\t\tif sb.State == runtimeapi.PodSandboxState_SANDBOX_READY {\n\t\t\trunningSandboxes++\n\t\t}\n\t}\n\treturn runningContainers == 0 \u0026\u0026 runningSandboxes == 0\n}","line":{"from":718,"to":732}} {"id":100007395,"name":"UpdatePod","signature":"func (p *podWorkers) UpdatePod(options UpdatePodOptions)","file":"pkg/kubelet/pod_workers.go","code":"// UpdatePod carries a configuration change or termination state to a pod. A pod is either runnable,\n// terminating, or terminated, and will transition to terminating if: deleted on the apiserver,\n// discovered to have a terminal phase (Succeeded or Failed), or evicted by the kubelet.\nfunc (p *podWorkers) UpdatePod(options UpdatePodOptions) {\n\t// Handle when the pod is an orphan (no config) and we only have runtime status by running only\n\t// the terminating part of the lifecycle. A running pod contains only a minimal set of information\n\t// about the pod\n\tvar isRuntimePod bool\n\tvar uid types.UID\n\tvar name, ns string\n\tif runningPod := options.RunningPod; runningPod != nil {\n\t\tif options.Pod == nil {\n\t\t\t// the sythetic pod created here is used only as a placeholder and not tracked\n\t\t\tif options.UpdateType != kubetypes.SyncPodKill {\n\t\t\t\tklog.InfoS(\"Pod update is ignored, runtime pods can only be killed\", \"pod\", klog.KRef(runningPod.Namespace, runningPod.Name), \"podUID\", runningPod.ID, \"updateType\", options.UpdateType)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tuid, ns, name = runningPod.ID, runningPod.Namespace, runningPod.Name\n\t\t\tisRuntimePod = true\n\t\t} else {\n\t\t\toptions.RunningPod = nil\n\t\t\tuid, ns, name = options.Pod.UID, options.Pod.Namespace, options.Pod.Name\n\t\t\tklog.InfoS(\"Pod update included RunningPod which is only valid when Pod is not specified\", \"pod\", klog.KRef(ns, name), \"podUID\", uid, \"updateType\", options.UpdateType)\n\t\t}\n\t} else {\n\t\tuid, ns, name = options.Pod.UID, options.Pod.Namespace, options.Pod.Name\n\t}\n\n\tp.podLock.Lock()\n\tdefer p.podLock.Unlock()\n\n\t// decide what to do with this pod - we are either setting it up, tearing it down, or ignoring it\n\tvar firstTime bool\n\tnow := p.clock.Now()\n\tstatus, ok := p.podSyncStatuses[uid]\n\tif !ok {\n\t\tklog.V(4).InfoS(\"Pod is being synced for the first time\", \"pod\", klog.KRef(ns, name), \"podUID\", uid, \"updateType\", options.UpdateType)\n\t\tfirstTime = true\n\t\tstatus = \u0026podSyncStatus{\n\t\t\tsyncedAt: now,\n\t\t\tfullname: kubecontainer.BuildPodFullName(name, ns),\n\t\t}\n\t\t// if this pod is being synced for the first time, we need to make sure it is an active pod\n\t\tif options.Pod != nil \u0026\u0026 (options.Pod.Status.Phase == v1.PodFailed || options.Pod.Status.Phase == v1.PodSucceeded) {\n\t\t\t// Check to see if the pod is not running and the pod is terminal; if this succeeds then record in the podWorker that it is terminated.\n\t\t\t// This is needed because after a kubelet restart, we need to ensure terminal pods will NOT be considered active in Pod Admission. See http://issues.k8s.io/105523\n\t\t\t// However, `filterOutInactivePods`, considers pods that are actively terminating as active. As a result, `IsPodKnownTerminated()` needs to return true and thus `terminatedAt` needs to be set.\n\t\t\tif statusCache, err := p.podCache.Get(uid); err == nil {\n\t\t\t\tif isPodStatusCacheTerminal(statusCache) {\n\t\t\t\t\t// At this point we know:\n\t\t\t\t\t// (1) The pod is terminal based on the config source.\n\t\t\t\t\t// (2) The pod is terminal based on the runtime cache.\n\t\t\t\t\t// This implies that this pod had already completed `SyncTerminatingPod` sometime in the past. The pod is likely being synced for the first time due to a kubelet restart.\n\t\t\t\t\t// These pods need to complete SyncTerminatedPod to ensure that all resources are cleaned and that the status manager makes the final status updates for the pod.\n\t\t\t\t\t// As a result, set finished: false, to ensure a Terminated event will be sent and `SyncTerminatedPod` will run.\n\t\t\t\t\tstatus = \u0026podSyncStatus{\n\t\t\t\t\t\tterminatedAt: now,\n\t\t\t\t\t\tterminatingAt: now,\n\t\t\t\t\t\tsyncedAt: now,\n\t\t\t\t\t\tstartedTerminating: true,\n\t\t\t\t\t\tfinished: false,\n\t\t\t\t\t\tfullname: kubecontainer.BuildPodFullName(name, ns),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tp.podSyncStatuses[uid] = status\n\t}\n\n\t// RunningPods represent an unknown pod execution and don't contain pod spec information\n\t// sufficient to perform any action other than termination. If we received a RunningPod\n\t// after a real pod has already been provided, use the most recent spec instead. Also,\n\t// once we observe a runtime pod we must drive it to completion, even if we weren't the\n\t// ones who started it.\n\tpod := options.Pod\n\tif isRuntimePod {\n\t\tstatus.observedRuntime = true\n\t\tswitch {\n\t\tcase status.pendingUpdate != nil \u0026\u0026 status.pendingUpdate.Pod != nil:\n\t\t\tpod = status.pendingUpdate.Pod\n\t\t\toptions.Pod = pod\n\t\t\toptions.RunningPod = nil\n\t\tcase status.activeUpdate != nil \u0026\u0026 status.activeUpdate.Pod != nil:\n\t\t\tpod = status.activeUpdate.Pod\n\t\t\toptions.Pod = pod\n\t\t\toptions.RunningPod = nil\n\t\tdefault:\n\t\t\t// we will continue to use RunningPod.ToAPIPod() as pod here, but\n\t\t\t// options.Pod will be nil and other methods must handle that appropriately.\n\t\t\tpod = options.RunningPod.ToAPIPod()\n\t\t}\n\t}\n\n\t// When we see a create update on an already terminating pod, that implies two pods with the same UID were created in\n\t// close temporal proximity (usually static pod but it's possible for an apiserver to extremely rarely do something\n\t// similar) - flag the sync status to indicate that after the pod terminates it should be reset to \"not running\" to\n\t// allow a subsequent add/update to start the pod worker again. This does not apply to the first time we see a pod,\n\t// such as when the kubelet restarts and we see already terminated pods for the first time.\n\tif !firstTime \u0026\u0026 status.IsTerminationRequested() {\n\t\tif options.UpdateType == kubetypes.SyncPodCreate {\n\t\t\tstatus.restartRequested = true\n\t\t\tklog.V(4).InfoS(\"Pod is terminating but has been requested to restart with same UID, will be reconciled later\", \"pod\", klog.KRef(ns, name), \"podUID\", uid, \"updateType\", options.UpdateType)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// once a pod is terminated by UID, it cannot reenter the pod worker (until the UID is purged by housekeeping)\n\tif status.IsFinished() {\n\t\tklog.V(4).InfoS(\"Pod is finished processing, no further updates\", \"pod\", klog.KRef(ns, name), \"podUID\", uid, \"updateType\", options.UpdateType)\n\t\treturn\n\t}\n\n\t// check for a transition to terminating\n\tvar becameTerminating bool\n\tif !status.IsTerminationRequested() {\n\t\tswitch {\n\t\tcase isRuntimePod:\n\t\t\tklog.V(4).InfoS(\"Pod is orphaned and must be torn down\", \"pod\", klog.KRef(ns, name), \"podUID\", uid, \"updateType\", options.UpdateType)\n\t\t\tstatus.deleted = true\n\t\t\tstatus.terminatingAt = now\n\t\t\tbecameTerminating = true\n\t\tcase pod.DeletionTimestamp != nil:\n\t\t\tklog.V(4).InfoS(\"Pod is marked for graceful deletion, begin teardown\", \"pod\", klog.KRef(ns, name), \"podUID\", uid, \"updateType\", options.UpdateType)\n\t\t\tstatus.deleted = true\n\t\t\tstatus.terminatingAt = now\n\t\t\tbecameTerminating = true\n\t\tcase pod.Status.Phase == v1.PodFailed, pod.Status.Phase == v1.PodSucceeded:\n\t\t\tklog.V(4).InfoS(\"Pod is in a terminal phase (success/failed), begin teardown\", \"pod\", klog.KRef(ns, name), \"podUID\", uid, \"updateType\", options.UpdateType)\n\t\t\tstatus.terminatingAt = now\n\t\t\tbecameTerminating = true\n\t\tcase options.UpdateType == kubetypes.SyncPodKill:\n\t\t\tif options.KillPodOptions != nil \u0026\u0026 options.KillPodOptions.Evict {\n\t\t\t\tklog.V(4).InfoS(\"Pod is being evicted by the kubelet, begin teardown\", \"pod\", klog.KRef(ns, name), \"podUID\", uid, \"updateType\", options.UpdateType)\n\t\t\t\tstatus.evicted = true\n\t\t\t} else {\n\t\t\t\tklog.V(4).InfoS(\"Pod is being removed by the kubelet, begin teardown\", \"pod\", klog.KRef(ns, name), \"podUID\", uid, \"updateType\", options.UpdateType)\n\t\t\t}\n\t\t\tstatus.terminatingAt = now\n\t\t\tbecameTerminating = true\n\t\t}\n\t}\n\n\t// once a pod is terminating, all updates are kills and the grace period can only decrease\n\tvar wasGracePeriodShortened bool\n\tswitch {\n\tcase status.IsTerminated():\n\t\t// A terminated pod may still be waiting for cleanup - if we receive a runtime pod kill request\n\t\t// due to housekeeping seeing an older cached version of the runtime pod simply ignore it until\n\t\t// after the pod worker completes.\n\t\tif isRuntimePod {\n\t\t\tklog.V(3).InfoS(\"Pod is waiting for termination, ignoring runtime-only kill until after pod worker is fully terminated\", \"pod\", klog.KRef(ns, name), \"podUID\", uid, \"updateType\", options.UpdateType)\n\t\t\treturn\n\t\t}\n\n\t\tif options.KillPodOptions != nil {\n\t\t\tif ch := options.KillPodOptions.CompletedCh; ch != nil {\n\t\t\t\tclose(ch)\n\t\t\t}\n\t\t}\n\t\toptions.KillPodOptions = nil\n\n\tcase status.IsTerminationRequested():\n\t\tif options.KillPodOptions == nil {\n\t\t\toptions.KillPodOptions = \u0026KillPodOptions{}\n\t\t}\n\n\t\tif ch := options.KillPodOptions.CompletedCh; ch != nil {\n\t\t\tstatus.notifyPostTerminating = append(status.notifyPostTerminating, ch)\n\t\t}\n\t\tif fn := options.KillPodOptions.PodStatusFunc; fn != nil {\n\t\t\tstatus.statusPostTerminating = append(status.statusPostTerminating, fn)\n\t\t}\n\n\t\tgracePeriod, gracePeriodShortened := calculateEffectiveGracePeriod(status, pod, options.KillPodOptions)\n\n\t\twasGracePeriodShortened = gracePeriodShortened\n\t\tstatus.gracePeriod = gracePeriod\n\t\t// always set the grace period for syncTerminatingPod so we don't have to recalculate,\n\t\t// will never be zero.\n\t\toptions.KillPodOptions.PodTerminationGracePeriodSecondsOverride = \u0026gracePeriod\n\n\tdefault:\n\t\t// KillPodOptions is not valid for sync actions outside of the terminating phase\n\t\tif options.KillPodOptions != nil {\n\t\t\tif ch := options.KillPodOptions.CompletedCh; ch != nil {\n\t\t\t\tclose(ch)\n\t\t\t}\n\t\t\toptions.KillPodOptions = nil\n\t\t}\n\t}\n\n\t// start the pod worker goroutine if it doesn't exist\n\tpodUpdates, exists := p.podUpdates[uid]\n\tif !exists {\n\t\t// buffer the channel to avoid blocking this method\n\t\tpodUpdates = make(chan struct{}, 1)\n\t\tp.podUpdates[uid] = podUpdates\n\n\t\t// ensure that static pods start in the order they are received by UpdatePod\n\t\tif kubetypes.IsStaticPod(pod) {\n\t\t\tp.waitingToStartStaticPodsByFullname[status.fullname] =\n\t\t\t\tappend(p.waitingToStartStaticPodsByFullname[status.fullname], uid)\n\t\t}\n\n\t\t// allow testing of delays in the pod update channel\n\t\tvar outCh \u003c-chan struct{}\n\t\tif p.workerChannelFn != nil {\n\t\t\toutCh = p.workerChannelFn(uid, podUpdates)\n\t\t} else {\n\t\t\toutCh = podUpdates\n\t\t}\n\n\t\t// spawn a pod worker\n\t\tgo func() {\n\t\t\t// TODO: this should be a wait.Until with backoff to handle panics, and\n\t\t\t// accept a context for shutdown\n\t\t\tdefer runtime.HandleCrash()\n\t\t\tdefer klog.V(3).InfoS(\"Pod worker has stopped\", \"podUID\", uid)\n\t\t\tp.podWorkerLoop(uid, outCh)\n\t\t}()\n\t}\n\n\t// measure the maximum latency between a call to UpdatePod and when the pod worker reacts to it\n\t// by preserving the oldest StartTime\n\tif status.pendingUpdate != nil \u0026\u0026 !status.pendingUpdate.StartTime.IsZero() \u0026\u0026 status.pendingUpdate.StartTime.Before(options.StartTime) {\n\t\toptions.StartTime = status.pendingUpdate.StartTime\n\t}\n\n\t// notify the pod worker there is a pending update\n\tstatus.pendingUpdate = \u0026options\n\tstatus.working = true\n\tklog.V(4).InfoS(\"Notifying pod of pending update\", \"pod\", klog.KRef(ns, name), \"podUID\", uid, \"workType\", status.WorkType())\n\tselect {\n\tcase podUpdates \u003c- struct{}{}:\n\tdefault:\n\t}\n\n\tif (becameTerminating || wasGracePeriodShortened) \u0026\u0026 status.cancelFn != nil {\n\t\tklog.V(3).InfoS(\"Cancelling current pod sync\", \"pod\", klog.KRef(ns, name), \"podUID\", uid, \"workType\", status.WorkType())\n\t\tstatus.cancelFn()\n\t\treturn\n\t}\n}","line":{"from":734,"to":976}} {"id":100007396,"name":"calculateEffectiveGracePeriod","signature":"func calculateEffectiveGracePeriod(status *podSyncStatus, pod *v1.Pod, options *KillPodOptions) (int64, bool)","file":"pkg/kubelet/pod_workers.go","code":"// calculateEffectiveGracePeriod sets the initial grace period for a newly terminating pod or allows a\n// shorter grace period to be provided, returning the desired value.\nfunc calculateEffectiveGracePeriod(status *podSyncStatus, pod *v1.Pod, options *KillPodOptions) (int64, bool) {\n\t// enforce the restriction that a grace period can only decrease and track whatever our value is,\n\t// then ensure a calculated value is passed down to lower levels\n\tgracePeriod := status.gracePeriod\n\t// this value is bedrock truth - the apiserver owns telling us this value calculated by apiserver\n\tif override := pod.DeletionGracePeriodSeconds; override != nil {\n\t\tif gracePeriod == 0 || *override \u003c gracePeriod {\n\t\t\tgracePeriod = *override\n\t\t}\n\t}\n\t// we allow other parts of the kubelet (namely eviction) to request this pod be terminated faster\n\tif options != nil {\n\t\tif override := options.PodTerminationGracePeriodSecondsOverride; override != nil {\n\t\t\tif gracePeriod == 0 || *override \u003c gracePeriod {\n\t\t\t\tgracePeriod = *override\n\t\t\t}\n\t\t}\n\t}\n\t// make a best effort to default this value to the pod's desired intent, in the event\n\t// the kubelet provided no requested value (graceful termination?)\n\tif gracePeriod == 0 \u0026\u0026 pod.Spec.TerminationGracePeriodSeconds != nil {\n\t\tgracePeriod = *pod.Spec.TerminationGracePeriodSeconds\n\t}\n\t// no matter what, we always supply a grace period of 1\n\tif gracePeriod \u003c 1 {\n\t\tgracePeriod = 1\n\t}\n\treturn gracePeriod, status.gracePeriod != 0 \u0026\u0026 status.gracePeriod != gracePeriod\n}","line":{"from":978,"to":1008}} {"id":100007397,"name":"allowPodStart","signature":"func (p *podWorkers) allowPodStart(pod *v1.Pod) (canStart bool, canEverStart bool)","file":"pkg/kubelet/pod_workers.go","code":"// allowPodStart tries to start the pod and returns true if allowed, otherwise\n// it requeues the pod and returns false. If the pod will never be able to start\n// because data is missing, or the pod was terminated before start, canEverStart\n// is false. This method can only be called while holding the pod lock.\nfunc (p *podWorkers) allowPodStart(pod *v1.Pod) (canStart bool, canEverStart bool) {\n\tif !kubetypes.IsStaticPod(pod) {\n\t\t// TODO: Do we want to allow non-static pods with the same full name?\n\t\t// Note that it may disable the force deletion of pods.\n\t\treturn true, true\n\t}\n\tstatus, ok := p.podSyncStatuses[pod.UID]\n\tif !ok {\n\t\tklog.ErrorS(nil, \"Pod sync status does not exist, the worker should not be running\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\t\treturn false, false\n\t}\n\tif status.IsTerminationRequested() {\n\t\treturn false, false\n\t}\n\tif !p.allowStaticPodStart(status.fullname, pod.UID) {\n\t\tp.workQueue.Enqueue(pod.UID, wait.Jitter(p.backOffPeriod, workerBackOffPeriodJitterFactor))\n\t\treturn false, true\n\t}\n\treturn true, true\n}","line":{"from":1010,"to":1033}} {"id":100007398,"name":"allowStaticPodStart","signature":"func (p *podWorkers) allowStaticPodStart(fullname string, uid types.UID) bool","file":"pkg/kubelet/pod_workers.go","code":"// allowStaticPodStart tries to start the static pod and returns true if\n// 1. there are no other started static pods with the same fullname\n// 2. the uid matches that of the first valid static pod waiting to start\nfunc (p *podWorkers) allowStaticPodStart(fullname string, uid types.UID) bool {\n\tstartedUID, started := p.startedStaticPodsByFullname[fullname]\n\tif started {\n\t\treturn startedUID == uid\n\t}\n\n\twaitingPods := p.waitingToStartStaticPodsByFullname[fullname]\n\t// TODO: This is O(N) with respect to the number of updates to static pods\n\t// with overlapping full names, and ideally would be O(1).\n\tfor i, waitingUID := range waitingPods {\n\t\t// has pod already terminated or been deleted?\n\t\tstatus, ok := p.podSyncStatuses[waitingUID]\n\t\tif !ok || status.IsTerminationRequested() || status.IsTerminated() {\n\t\t\tcontinue\n\t\t}\n\t\t// another pod is next in line\n\t\tif waitingUID != uid {\n\t\t\tp.waitingToStartStaticPodsByFullname[fullname] = waitingPods[i:]\n\t\t\treturn false\n\t\t}\n\t\t// we are up next, remove ourselves\n\t\twaitingPods = waitingPods[i+1:]\n\t\tbreak\n\t}\n\tif len(waitingPods) != 0 {\n\t\tp.waitingToStartStaticPodsByFullname[fullname] = waitingPods\n\t} else {\n\t\tdelete(p.waitingToStartStaticPodsByFullname, fullname)\n\t}\n\tp.startedStaticPodsByFullname[fullname] = uid\n\treturn true\n}","line":{"from":1035,"to":1069}} {"id":100007399,"name":"cleanupUnstartedPod","signature":"func (p *podWorkers) cleanupUnstartedPod(pod *v1.Pod, status *podSyncStatus)","file":"pkg/kubelet/pod_workers.go","code":"// cleanupUnstartedPod is invoked if a pod that has never been started receives a termination\n// signal before it can be started. This method must be called holding the pod lock.\nfunc (p *podWorkers) cleanupUnstartedPod(pod *v1.Pod, status *podSyncStatus) {\n\tp.cleanupPodUpdates(pod.UID)\n\n\tif status.terminatingAt.IsZero() {\n\t\tklog.V(4).InfoS(\"Pod worker is complete but did not have terminatingAt set, likely programmer error\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\t}\n\tif !status.terminatedAt.IsZero() {\n\t\tklog.V(4).InfoS(\"Pod worker is complete and had terminatedAt set, likely programmer error\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\t}\n\tstatus.finished = true\n\tstatus.working = false\n\tstatus.terminatedAt = p.clock.Now()\n\n\tif p.startedStaticPodsByFullname[status.fullname] == pod.UID {\n\t\tdelete(p.startedStaticPodsByFullname, status.fullname)\n\t}\n}","line":{"from":1071,"to":1089}} {"id":100007400,"name":"startPodSync","signature":"func (p *podWorkers) startPodSync(podUID types.UID) (ctx context.Context, update podWork, canStart, canEverStart, ok bool)","file":"pkg/kubelet/pod_workers.go","code":"// startPodSync is invoked by each pod worker goroutine when a message arrives on the pod update channel.\n// This method consumes a pending update, initializes a context, decides whether the pod is already started\n// or can be started, and updates the cached pod state so that downstream components can observe what the\n// pod worker goroutine is currently attempting to do. If ok is false, there is no available event. If any\n// of the boolean values is false, ensure the appropriate cleanup happens before returning.\n//\n// This method should ensure that either status.pendingUpdate is cleared and merged into status.activeUpdate,\n// or when a pod cannot be started status.pendingUpdate remains the same. Pods that have not been started\n// should never have an activeUpdate because that is exposed to downstream components on started pods.\nfunc (p *podWorkers) startPodSync(podUID types.UID) (ctx context.Context, update podWork, canStart, canEverStart, ok bool) {\n\tp.podLock.Lock()\n\tdefer p.podLock.Unlock()\n\n\t// verify we are known to the pod worker still\n\tstatus, ok := p.podSyncStatuses[podUID]\n\tif !ok {\n\t\t// pod status has disappeared, the worker should exit\n\t\tklog.V(4).InfoS(\"Pod worker no longer has status, worker should exit\", \"podUID\", podUID)\n\t\treturn nil, update, false, false, false\n\t}\n\tif !status.working {\n\t\t// working is used by unit tests to observe whether a worker is currently acting on this pod\n\t\tklog.V(4).InfoS(\"Pod should be marked as working by the pod worker, programmer error\", \"podUID\", podUID)\n\t}\n\tif status.pendingUpdate == nil {\n\t\t// no update available, this means we were queued without work being added or there is a\n\t\t// race condition, both of which are unexpected\n\t\tstatus.working = false\n\t\tklog.V(4).InfoS(\"Pod worker received no pending work, programmer error?\", \"podUID\", podUID)\n\t\treturn nil, update, false, false, false\n\t}\n\n\t// consume the pending update\n\tupdate.WorkType = status.WorkType()\n\tupdate.Options = *status.pendingUpdate\n\tstatus.pendingUpdate = nil\n\tselect {\n\tcase \u003c-p.podUpdates[podUID]:\n\t\t// ensure the pod update channel is empty (it is only ever written to under lock)\n\tdefault:\n\t}\n\n\t// initialize a context for the worker if one does not exist\n\tif status.ctx == nil || status.ctx.Err() == context.Canceled {\n\t\tstatus.ctx, status.cancelFn = context.WithCancel(context.Background())\n\t}\n\tctx = status.ctx\n\n\t// if we are already started, make our state visible to downstream components\n\tif status.IsStarted() {\n\t\tstatus.mergeLastUpdate(update.Options)\n\t\treturn ctx, update, true, true, true\n\t}\n\n\t// if we are already terminating and we only have a running pod, allow the worker\n\t// to \"start\" since we are immediately moving to terminating\n\tif update.Options.RunningPod != nil \u0026\u0026 update.WorkType == TerminatingPod {\n\t\tstatus.mergeLastUpdate(update.Options)\n\t\treturn ctx, update, true, true, true\n\t}\n\n\t// If we receive an update where Pod is nil (running pod is set) but haven't\n\t// started yet, we can only terminate the pod, not start it. We should not be\n\t// asked to start such a pod, but guard here just in case an accident occurs.\n\tif update.Options.Pod == nil {\n\t\tstatus.mergeLastUpdate(update.Options)\n\t\tklog.V(4).InfoS(\"Running pod cannot start ever, programmer error\", \"pod\", klog.KObj(update.Options.Pod), \"podUID\", podUID, \"updateType\", update.WorkType)\n\t\treturn ctx, update, false, false, true\n\t}\n\n\t// verify we can start\n\tcanStart, canEverStart = p.allowPodStart(update.Options.Pod)\n\tswitch {\n\tcase !canEverStart:\n\t\tp.cleanupUnstartedPod(update.Options.Pod, status)\n\t\tstatus.working = false\n\t\tif start := update.Options.StartTime; !start.IsZero() {\n\t\t\tmetrics.PodWorkerDuration.WithLabelValues(\"terminated\").Observe(metrics.SinceInSeconds(start))\n\t\t}\n\t\tklog.V(4).InfoS(\"Pod cannot start ever\", \"pod\", klog.KObj(update.Options.Pod), \"podUID\", podUID, \"updateType\", update.WorkType)\n\t\treturn ctx, update, canStart, canEverStart, true\n\tcase !canStart:\n\t\t// this is the only path we don't start the pod, so we need to put the change back in pendingUpdate\n\t\tstatus.pendingUpdate = \u0026update.Options\n\t\tstatus.working = false\n\t\tklog.V(4).InfoS(\"Pod cannot start yet\", \"pod\", klog.KObj(update.Options.Pod), \"podUID\", podUID)\n\t\treturn ctx, update, canStart, canEverStart, true\n\t}\n\n\t// mark the pod as started\n\tstatus.startedAt = p.clock.Now()\n\tstatus.mergeLastUpdate(update.Options)\n\n\treturn ctx, update, true, true, true\n}","line":{"from":1091,"to":1185}} {"id":100007401,"name":"podUIDAndRefForUpdate","signature":"func podUIDAndRefForUpdate(update UpdatePodOptions) (types.UID, klog.ObjectRef)","file":"pkg/kubelet/pod_workers.go","code":"func podUIDAndRefForUpdate(update UpdatePodOptions) (types.UID, klog.ObjectRef) {\n\tif update.RunningPod != nil {\n\t\treturn update.RunningPod.ID, klog.KObj(update.RunningPod.ToAPIPod())\n\t}\n\treturn update.Pod.UID, klog.KObj(update.Pod)\n}","line":{"from":1187,"to":1192}} {"id":100007402,"name":"podWorkerLoop","signature":"func (p *podWorkers) podWorkerLoop(podUID types.UID, podUpdates \u003c-chan struct{})","file":"pkg/kubelet/pod_workers.go","code":"// podWorkerLoop manages sequential state updates to a pod in a goroutine, exiting once the final\n// state is reached. The loop is responsible for driving the pod through four main phases:\n//\n// 1. Wait to start, guaranteeing no two pods with the same UID or same fullname are running at the same time\n// 2. Sync, orchestrating pod setup by reconciling the desired pod spec with the runtime state of the pod\n// 3. Terminating, ensuring all running containers in the pod are stopped\n// 4. Terminated, cleaning up any resources that must be released before the pod can be deleted\n//\n// The podWorkerLoop is driven by updates delivered to UpdatePod and by SyncKnownPods. If a particular\n// sync method fails, p.workerQueue is updated with backoff but it is the responsibility of the kubelet\n// to trigger new UpdatePod calls. SyncKnownPods will only retry pods that are no longer known to the\n// caller. When a pod transitions working-\u003eterminating or terminating-\u003eterminated, the next update is\n// queued immediately and no kubelet action is required.\nfunc (p *podWorkers) podWorkerLoop(podUID types.UID, podUpdates \u003c-chan struct{}) {\n\tvar lastSyncTime time.Time\n\tfor range podUpdates {\n\t\tctx, update, canStart, canEverStart, ok := p.startPodSync(podUID)\n\t\t// If we had no update waiting, it means someone initialized the channel without filling out pendingUpdate.\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\t// If the pod was terminated prior to the pod being allowed to start, we exit the loop.\n\t\tif !canEverStart {\n\t\t\treturn\n\t\t}\n\t\t// If the pod is not yet ready to start, continue and wait for more updates.\n\t\tif !canStart {\n\t\t\tcontinue\n\t\t}\n\n\t\tpodUID, podRef := podUIDAndRefForUpdate(update.Options)\n\n\t\tklog.V(4).InfoS(\"Processing pod event\", \"pod\", podRef, \"podUID\", podUID, \"updateType\", update.WorkType)\n\t\tvar isTerminal bool\n\t\terr := func() error {\n\t\t\t// The worker is responsible for ensuring the sync method sees the appropriate\n\t\t\t// status updates on resyncs (the result of the last sync), transitions to\n\t\t\t// terminating (no wait), or on terminated (whatever the most recent state is).\n\t\t\t// Only syncing and terminating can generate pod status changes, while terminated\n\t\t\t// pods ensure the most recent status makes it to the api server.\n\t\t\tvar status *kubecontainer.PodStatus\n\t\t\tvar err error\n\t\t\tswitch {\n\t\t\tcase update.Options.RunningPod != nil:\n\t\t\t\t// when we receive a running pod, we don't need status at all because we are\n\t\t\t\t// guaranteed to be terminating and we skip updates to the pod\n\t\t\tdefault:\n\t\t\t\t// wait until we see the next refresh from the PLEG via the cache (max 2s)\n\t\t\t\t// TODO: this adds ~1s of latency on all transitions from sync to terminating\n\t\t\t\t// to terminated, and on all termination retries (including evictions). We should\n\t\t\t\t// improve latency by making the pleg continuous and by allowing pod status\n\t\t\t\t// changes to be refreshed when key events happen (killPod, sync-\u003eterminating).\n\t\t\t\t// Improving this latency also reduces the possibility that a terminated\n\t\t\t\t// container's status is garbage collected before we have a chance to update the\n\t\t\t\t// API server (thus losing the exit code).\n\t\t\t\tstatus, err = p.podCache.GetNewerThan(update.Options.Pod.UID, lastSyncTime)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\t// This is the legacy event thrown by manage pod loop all other events are now dispatched\n\t\t\t\t\t// from syncPodFn\n\t\t\t\t\tp.recorder.Eventf(update.Options.Pod, v1.EventTypeWarning, events.FailedSync, \"error determining status: %v\", err)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Take the appropriate action (illegal phases are prevented by UpdatePod)\n\t\t\tswitch {\n\t\t\tcase update.WorkType == TerminatedPod:\n\t\t\t\terr = p.podSyncer.SyncTerminatedPod(ctx, update.Options.Pod, status)\n\n\t\t\tcase update.WorkType == TerminatingPod:\n\t\t\t\tvar gracePeriod *int64\n\t\t\t\tif opt := update.Options.KillPodOptions; opt != nil {\n\t\t\t\t\tgracePeriod = opt.PodTerminationGracePeriodSecondsOverride\n\t\t\t\t}\n\t\t\t\tpodStatusFn := p.acknowledgeTerminating(podUID)\n\n\t\t\t\t// if we only have a running pod, terminate it directly\n\t\t\t\tif update.Options.RunningPod != nil {\n\t\t\t\t\terr = p.podSyncer.SyncTerminatingRuntimePod(ctx, update.Options.RunningPod)\n\t\t\t\t} else {\n\t\t\t\t\terr = p.podSyncer.SyncTerminatingPod(ctx, update.Options.Pod, status, gracePeriod, podStatusFn)\n\t\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\tisTerminal, err = p.podSyncer.SyncPod(ctx, update.Options.UpdateType, update.Options.Pod, update.Options.MirrorPod, status)\n\t\t\t}\n\n\t\t\tlastSyncTime = p.clock.Now()\n\t\t\treturn err\n\t\t}()\n\n\t\tvar phaseTransition bool\n\t\tswitch {\n\t\tcase err == context.Canceled:\n\t\t\t// when the context is cancelled we expect an update to already be queued\n\t\t\tklog.V(2).InfoS(\"Sync exited with context cancellation error\", \"pod\", podRef, \"podUID\", podUID, \"updateType\", update.WorkType)\n\n\t\tcase err != nil:\n\t\t\t// we will queue a retry\n\t\t\tklog.ErrorS(err, \"Error syncing pod, skipping\", \"pod\", podRef, \"podUID\", podUID)\n\n\t\tcase update.WorkType == TerminatedPod:\n\t\t\t// we can shut down the worker\n\t\t\tp.completeTerminated(podUID)\n\t\t\tif start := update.Options.StartTime; !start.IsZero() {\n\t\t\t\tmetrics.PodWorkerDuration.WithLabelValues(\"terminated\").Observe(metrics.SinceInSeconds(start))\n\t\t\t}\n\t\t\tklog.V(4).InfoS(\"Processing pod event done\", \"pod\", podRef, \"podUID\", podUID, \"updateType\", update.WorkType)\n\t\t\treturn\n\n\t\tcase update.WorkType == TerminatingPod:\n\t\t\t// pods that don't exist in config don't need to be terminated, other loops will clean them up\n\t\t\tif update.Options.RunningPod != nil {\n\t\t\t\tp.completeTerminatingRuntimePod(podUID)\n\t\t\t\tif start := update.Options.StartTime; !start.IsZero() {\n\t\t\t\t\tmetrics.PodWorkerDuration.WithLabelValues(update.Options.UpdateType.String()).Observe(metrics.SinceInSeconds(start))\n\t\t\t\t}\n\t\t\t\tklog.V(4).InfoS(\"Processing pod event done\", \"pod\", podRef, \"podUID\", podUID, \"updateType\", update.WorkType)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// otherwise we move to the terminating phase\n\t\t\tp.completeTerminating(podUID)\n\t\t\tphaseTransition = true\n\n\t\tcase isTerminal:\n\t\t\t// if syncPod indicated we are now terminal, set the appropriate pod status to move to terminating\n\t\t\tklog.V(4).InfoS(\"Pod is terminal\", \"pod\", podRef, \"podUID\", podUID, \"updateType\", update.WorkType)\n\t\t\tp.completeSync(podUID)\n\t\t\tphaseTransition = true\n\t\t}\n\n\t\t// queue a retry if necessary, then put the next event in the channel if any\n\t\tp.completeWork(podUID, phaseTransition, err)\n\t\tif start := update.Options.StartTime; !start.IsZero() {\n\t\t\tmetrics.PodWorkerDuration.WithLabelValues(update.Options.UpdateType.String()).Observe(metrics.SinceInSeconds(start))\n\t\t}\n\t\tklog.V(4).InfoS(\"Processing pod event done\", \"pod\", podRef, \"podUID\", podUID, \"updateType\", update.WorkType)\n\t}\n}","line":{"from":1194,"to":1333}} {"id":100007403,"name":"acknowledgeTerminating","signature":"func (p *podWorkers) acknowledgeTerminating(podUID types.UID) PodStatusFunc","file":"pkg/kubelet/pod_workers.go","code":"// acknowledgeTerminating sets the terminating flag on the pod status once the pod worker sees\n// the termination state so that other components know no new containers will be started in this\n// pod. It then returns the status function, if any, that applies to this pod.\nfunc (p *podWorkers) acknowledgeTerminating(podUID types.UID) PodStatusFunc {\n\tp.podLock.Lock()\n\tdefer p.podLock.Unlock()\n\n\tstatus, ok := p.podSyncStatuses[podUID]\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tif !status.terminatingAt.IsZero() \u0026\u0026 !status.startedTerminating {\n\t\tklog.V(4).InfoS(\"Pod worker has observed request to terminate\", \"podUID\", podUID)\n\t\tstatus.startedTerminating = true\n\t}\n\n\tif l := len(status.statusPostTerminating); l \u003e 0 {\n\t\treturn status.statusPostTerminating[l-1]\n\t}\n\treturn nil\n}","line":{"from":1335,"to":1356}} {"id":100007404,"name":"completeSync","signature":"func (p *podWorkers) completeSync(podUID types.UID)","file":"pkg/kubelet/pod_workers.go","code":"// completeSync is invoked when syncPod completes successfully and indicates the pod is now terminal and should\n// be terminated. This happens when the natural pod lifecycle completes - any pod which is not RestartAlways\n// exits. Unnatural completions, such as evictions, API driven deletion or phase transition, are handled by\n// UpdatePod.\nfunc (p *podWorkers) completeSync(podUID types.UID) {\n\tp.podLock.Lock()\n\tdefer p.podLock.Unlock()\n\n\tklog.V(4).InfoS(\"Pod indicated lifecycle completed naturally and should now terminate\", \"podUID\", podUID)\n\n\tstatus, ok := p.podSyncStatuses[podUID]\n\tif !ok {\n\t\tklog.V(4).InfoS(\"Pod had no status in completeSync, programmer error?\", \"podUID\", podUID)\n\t\treturn\n\t}\n\n\t// update the status of the pod\n\tif status.terminatingAt.IsZero() {\n\t\tstatus.terminatingAt = p.clock.Now()\n\t} else {\n\t\tklog.V(4).InfoS(\"Pod worker attempted to set terminatingAt twice, likely programmer error\", \"podUID\", podUID)\n\t}\n\tstatus.startedTerminating = true\n\n\t// the pod has now transitioned to terminating and we want to run syncTerminatingPod\n\t// as soon as possible, so if no update is already waiting queue a synthetic update\n\tp.requeueLastPodUpdate(podUID, status)\n}","line":{"from":1358,"to":1385}} {"id":100007405,"name":"completeTerminating","signature":"func (p *podWorkers) completeTerminating(podUID types.UID)","file":"pkg/kubelet/pod_workers.go","code":"// completeTerminating is invoked when syncTerminatingPod completes successfully, which means\n// no container is running, no container will be started in the future, and we are ready for\n// cleanup. This updates the termination state which prevents future syncs and will ensure\n// other kubelet loops know this pod is not running any containers.\nfunc (p *podWorkers) completeTerminating(podUID types.UID) {\n\tp.podLock.Lock()\n\tdefer p.podLock.Unlock()\n\n\tklog.V(4).InfoS(\"Pod terminated all containers successfully\", \"podUID\", podUID)\n\n\tstatus, ok := p.podSyncStatuses[podUID]\n\tif !ok {\n\t\treturn\n\t}\n\n\t// update the status of the pod\n\tif status.terminatingAt.IsZero() {\n\t\tklog.V(4).InfoS(\"Pod worker was terminated but did not have terminatingAt set, likely programmer error\", \"podUID\", podUID)\n\t}\n\tstatus.terminatedAt = p.clock.Now()\n\tfor _, ch := range status.notifyPostTerminating {\n\t\tclose(ch)\n\t}\n\tstatus.notifyPostTerminating = nil\n\tstatus.statusPostTerminating = nil\n\n\t// the pod has now transitioned to terminated and we want to run syncTerminatedPod\n\t// as soon as possible, so if no update is already waiting queue a synthetic update\n\tp.requeueLastPodUpdate(podUID, status)\n}","line":{"from":1387,"to":1416}} {"id":100007406,"name":"completeTerminatingRuntimePod","signature":"func (p *podWorkers) completeTerminatingRuntimePod(podUID types.UID)","file":"pkg/kubelet/pod_workers.go","code":"// completeTerminatingRuntimePod is invoked when syncTerminatingPod completes successfully,\n// which means an orphaned pod (no config) is terminated and we can exit. Since orphaned\n// pods have no API representation, we want to exit the loop at this point and ensure no\n// status is present afterwards - the running pod is truly terminated when this is invoked.\nfunc (p *podWorkers) completeTerminatingRuntimePod(podUID types.UID) {\n\tp.podLock.Lock()\n\tdefer p.podLock.Unlock()\n\n\tklog.V(4).InfoS(\"Pod terminated all orphaned containers successfully and worker can now stop\", \"podUID\", podUID)\n\n\tp.cleanupPodUpdates(podUID)\n\n\tstatus, ok := p.podSyncStatuses[podUID]\n\tif !ok {\n\t\treturn\n\t}\n\tif status.terminatingAt.IsZero() {\n\t\tklog.V(4).InfoS(\"Pod worker was terminated but did not have terminatingAt set, likely programmer error\", \"podUID\", podUID)\n\t}\n\tstatus.terminatedAt = p.clock.Now()\n\tstatus.finished = true\n\tstatus.working = false\n\n\tif p.startedStaticPodsByFullname[status.fullname] == podUID {\n\t\tdelete(p.startedStaticPodsByFullname, status.fullname)\n\t}\n\n\t// A runtime pod is transient and not part of the desired state - once it has reached\n\t// terminated we can abandon tracking it.\n\tdelete(p.podSyncStatuses, podUID)\n}","line":{"from":1418,"to":1448}} {"id":100007407,"name":"completeTerminated","signature":"func (p *podWorkers) completeTerminated(podUID types.UID)","file":"pkg/kubelet/pod_workers.go","code":"// completeTerminated is invoked after syncTerminatedPod completes successfully and means we\n// can stop the pod worker. The pod is finalized at this point.\nfunc (p *podWorkers) completeTerminated(podUID types.UID) {\n\tp.podLock.Lock()\n\tdefer p.podLock.Unlock()\n\n\tklog.V(4).InfoS(\"Pod is complete and the worker can now stop\", \"podUID\", podUID)\n\n\tp.cleanupPodUpdates(podUID)\n\n\tstatus, ok := p.podSyncStatuses[podUID]\n\tif !ok {\n\t\treturn\n\t}\n\tif status.terminatingAt.IsZero() {\n\t\tklog.V(4).InfoS(\"Pod worker is complete but did not have terminatingAt set, likely programmer error\", \"podUID\", podUID)\n\t}\n\tif status.terminatedAt.IsZero() {\n\t\tklog.V(4).InfoS(\"Pod worker is complete but did not have terminatedAt set, likely programmer error\", \"podUID\", podUID)\n\t}\n\tstatus.finished = true\n\tstatus.working = false\n\n\tif p.startedStaticPodsByFullname[status.fullname] == podUID {\n\t\tdelete(p.startedStaticPodsByFullname, status.fullname)\n\t}\n}","line":{"from":1450,"to":1476}} {"id":100007408,"name":"completeWork","signature":"func (p *podWorkers) completeWork(podUID types.UID, phaseTransition bool, syncErr error)","file":"pkg/kubelet/pod_workers.go","code":"// completeWork requeues on error or the next sync interval and then immediately executes any pending\n// work.\nfunc (p *podWorkers) completeWork(podUID types.UID, phaseTransition bool, syncErr error) {\n\t// Requeue the last update if the last sync returned error.\n\tswitch {\n\tcase phaseTransition:\n\t\tp.workQueue.Enqueue(podUID, 0)\n\tcase syncErr == nil:\n\t\t// No error; requeue at the regular resync interval.\n\t\tp.workQueue.Enqueue(podUID, wait.Jitter(p.resyncInterval, workerResyncIntervalJitterFactor))\n\tcase strings.Contains(syncErr.Error(), NetworkNotReadyErrorMsg):\n\t\t// Network is not ready; back off for short period of time and retry as network might be ready soon.\n\t\tp.workQueue.Enqueue(podUID, wait.Jitter(backOffOnTransientErrorPeriod, workerBackOffPeriodJitterFactor))\n\tdefault:\n\t\t// Error occurred during the sync; back off and then retry.\n\t\tp.workQueue.Enqueue(podUID, wait.Jitter(p.backOffPeriod, workerBackOffPeriodJitterFactor))\n\t}\n\n\t// if there is a pending update for this worker, requeue immediately, otherwise\n\t// clear working status\n\tp.podLock.Lock()\n\tdefer p.podLock.Unlock()\n\tif status, ok := p.podSyncStatuses[podUID]; ok {\n\t\tif status.pendingUpdate != nil {\n\t\t\tselect {\n\t\t\tcase p.podUpdates[podUID] \u003c- struct{}{}:\n\t\t\t\tklog.V(4).InfoS(\"Requeueing pod due to pending update\", \"podUID\", podUID)\n\t\t\tdefault:\n\t\t\t\tklog.V(4).InfoS(\"Pending update already queued\", \"podUID\", podUID)\n\t\t\t}\n\t\t} else {\n\t\t\tstatus.working = false\n\t\t}\n\t}\n}","line":{"from":1478,"to":1512}} {"id":100007409,"name":"SyncKnownPods","signature":"func (p *podWorkers) SyncKnownPods(desiredPods []*v1.Pod) map[types.UID]PodWorkerSync","file":"pkg/kubelet/pod_workers.go","code":"// SyncKnownPods will purge any fully terminated pods that are not in the desiredPods\n// list, which means SyncKnownPods must be called in a threadsafe manner from calls\n// to UpdatePods for new pods. Because the podworker is dependent on UpdatePod being\n// invoked to drive a pod's state machine, if a pod is missing in the desired list the\n// pod worker must be responsible for delivering that update. The method returns a map\n// of known workers that are not finished with a value of SyncPodTerminated,\n// SyncPodKill, or SyncPodSync depending on whether the pod is terminated, terminating,\n// or syncing.\nfunc (p *podWorkers) SyncKnownPods(desiredPods []*v1.Pod) map[types.UID]PodWorkerSync {\n\tworkers := make(map[types.UID]PodWorkerSync)\n\tknown := make(map[types.UID]struct{})\n\tfor _, pod := range desiredPods {\n\t\tknown[pod.UID] = struct{}{}\n\t}\n\n\tp.podLock.Lock()\n\tdefer p.podLock.Unlock()\n\n\tp.podsSynced = true\n\tfor uid, status := range p.podSyncStatuses {\n\t\t// We retain the worker history of any pod that is still desired according to\n\t\t// its UID. However, there are ]two scenarios during a sync that result in us\n\t\t// needing to purge the history:\n\t\t//\n\t\t// 1. The pod is no longer desired (the local version is orphaned)\n\t\t// 2. The pod received a kill update and then a subsequent create, which means\n\t\t// the UID was reused in the source config (vanishingly rare for API servers,\n\t\t// common for static pods that have specified a fixed UID)\n\t\t//\n\t\t// In the former case we wish to bound the amount of information we store for\n\t\t// deleted pods. In the latter case we wish to minimize the amount of time before\n\t\t// we restart the static pod. If we succeed at removing the worker, then we\n\t\t// omit it from the returned map of known workers, and the caller of SyncKnownPods\n\t\t// is expected to send a new UpdatePod({UpdateType: Create}).\n\t\t_, knownPod := known[uid]\n\t\torphan := !knownPod\n\t\tif status.restartRequested || orphan {\n\t\t\tif p.removeTerminatedWorker(uid, status, orphan) {\n\t\t\t\t// no worker running, we won't return it\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tsync := PodWorkerSync{\n\t\t\tState: status.WorkType(),\n\t\t\tOrphan: orphan,\n\t\t}\n\t\tswitch {\n\t\tcase status.activeUpdate != nil:\n\t\t\tif status.activeUpdate.Pod != nil {\n\t\t\t\tsync.HasConfig = true\n\t\t\t\tsync.Static = kubetypes.IsStaticPod(status.activeUpdate.Pod)\n\t\t\t}\n\t\tcase status.pendingUpdate != nil:\n\t\t\tif status.pendingUpdate.Pod != nil {\n\t\t\t\tsync.HasConfig = true\n\t\t\t\tsync.Static = kubetypes.IsStaticPod(status.pendingUpdate.Pod)\n\t\t\t}\n\t\t}\n\t\tworkers[uid] = sync\n\t}\n\treturn workers\n}","line":{"from":1514,"to":1576}} {"id":100007410,"name":"removeTerminatedWorker","signature":"func (p *podWorkers) removeTerminatedWorker(uid types.UID, status *podSyncStatus, orphaned bool) bool","file":"pkg/kubelet/pod_workers.go","code":"// removeTerminatedWorker cleans up and removes the worker status for a worker\n// that has reached a terminal state of \"finished\" - has successfully exited\n// syncTerminatedPod. This \"forgets\" a pod by UID and allows another pod to be\n// recreated with the same UID. The kubelet preserves state about recently\n// terminated pods to prevent accidentally restarting a terminal pod, which is\n// proportional to the number of pods described in the pod config. The method\n// returns true if the worker was completely removed.\nfunc (p *podWorkers) removeTerminatedWorker(uid types.UID, status *podSyncStatus, orphaned bool) bool {\n\tif !status.finished {\n\t\t// If the pod worker has not reached terminal state and the pod is still known, we wait.\n\t\tif !orphaned {\n\t\t\tklog.V(4).InfoS(\"Pod worker has been requested for removal but is still not fully terminated\", \"podUID\", uid)\n\t\t\treturn false\n\t\t}\n\n\t\t// all orphaned pods are considered deleted\n\t\tstatus.deleted = true\n\n\t\t// When a pod is no longer in the desired set, the pod is considered orphaned and the\n\t\t// the pod worker becomes responsible for driving the pod to completion (there is no\n\t\t// guarantee another component will notify us of updates).\n\t\tswitch {\n\t\tcase !status.IsStarted() \u0026\u0026 !status.observedRuntime:\n\t\t\t// The pod has not been started, which means we can safely clean up the pod - the\n\t\t\t// pod worker will shutdown as a result of this change without executing a sync.\n\t\t\tklog.V(4).InfoS(\"Pod is orphaned and has not been started\", \"podUID\", uid)\n\t\tcase !status.IsTerminationRequested():\n\t\t\t// The pod has been started but termination has not been requested - set the appropriate\n\t\t\t// timestamp and notify the pod worker. Because the pod has been synced at least once,\n\t\t\t// the value of status.activeUpdate will be the fallback for the next sync.\n\t\t\tstatus.terminatingAt = p.clock.Now()\n\t\t\tif status.activeUpdate != nil \u0026\u0026 status.activeUpdate.Pod != nil {\n\t\t\t\tstatus.gracePeriod, _ = calculateEffectiveGracePeriod(status, status.activeUpdate.Pod, nil)\n\t\t\t} else {\n\t\t\t\tstatus.gracePeriod = 1\n\t\t\t}\n\t\t\tp.requeueLastPodUpdate(uid, status)\n\t\t\tklog.V(4).InfoS(\"Pod is orphaned and still running, began terminating\", \"podUID\", uid)\n\t\t\treturn false\n\t\tdefault:\n\t\t\t// The pod is already moving towards termination, notify the pod worker. Because the pod\n\t\t\t// has been synced at least once, the value of status.activeUpdate will be the fallback for\n\t\t\t// the next sync.\n\t\t\tp.requeueLastPodUpdate(uid, status)\n\t\t\tklog.V(4).InfoS(\"Pod is orphaned and still terminating, notified the pod worker\", \"podUID\", uid)\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif status.restartRequested {\n\t\tklog.V(4).InfoS(\"Pod has been terminated but another pod with the same UID was created, remove history to allow restart\", \"podUID\", uid)\n\t} else {\n\t\tklog.V(4).InfoS(\"Pod has been terminated and is no longer known to the kubelet, remove all history\", \"podUID\", uid)\n\t}\n\tdelete(p.podSyncStatuses, uid)\n\tp.cleanupPodUpdates(uid)\n\n\tif p.startedStaticPodsByFullname[status.fullname] == uid {\n\t\tdelete(p.startedStaticPodsByFullname, status.fullname)\n\t}\n\treturn true\n}","line":{"from":1578,"to":1639}} {"id":100007411,"name":"killPodNow","signature":"func killPodNow(podWorkers PodWorkers, recorder record.EventRecorder) eviction.KillPodFunc","file":"pkg/kubelet/pod_workers.go","code":"// killPodNow returns a KillPodFunc that can be used to kill a pod.\n// It is intended to be injected into other modules that need to kill a pod.\nfunc killPodNow(podWorkers PodWorkers, recorder record.EventRecorder) eviction.KillPodFunc {\n\treturn func(pod *v1.Pod, isEvicted bool, gracePeriodOverride *int64, statusFn func(*v1.PodStatus)) error {\n\t\t// determine the grace period to use when killing the pod\n\t\tgracePeriod := int64(0)\n\t\tif gracePeriodOverride != nil {\n\t\t\tgracePeriod = *gracePeriodOverride\n\t\t} else if pod.Spec.TerminationGracePeriodSeconds != nil {\n\t\t\tgracePeriod = *pod.Spec.TerminationGracePeriodSeconds\n\t\t}\n\n\t\t// we timeout and return an error if we don't get a callback within a reasonable time.\n\t\t// the default timeout is relative to the grace period (we settle on 10s to wait for kubelet-\u003eruntime traffic to complete in sigkill)\n\t\ttimeout := int64(gracePeriod + (gracePeriod / 2))\n\t\tminTimeout := int64(10)\n\t\tif timeout \u003c minTimeout {\n\t\t\ttimeout = minTimeout\n\t\t}\n\t\ttimeoutDuration := time.Duration(timeout) * time.Second\n\n\t\t// open a channel we block against until we get a result\n\t\tch := make(chan struct{}, 1)\n\t\tpodWorkers.UpdatePod(UpdatePodOptions{\n\t\t\tPod: pod,\n\t\t\tUpdateType: kubetypes.SyncPodKill,\n\t\t\tKillPodOptions: \u0026KillPodOptions{\n\t\t\t\tCompletedCh: ch,\n\t\t\t\tEvict: isEvicted,\n\t\t\t\tPodStatusFunc: statusFn,\n\t\t\t\tPodTerminationGracePeriodSecondsOverride: gracePeriodOverride,\n\t\t\t},\n\t\t})\n\n\t\t// wait for either a response, or a timeout\n\t\tselect {\n\t\tcase \u003c-ch:\n\t\t\treturn nil\n\t\tcase \u003c-time.After(timeoutDuration):\n\t\t\trecorder.Eventf(pod, v1.EventTypeWarning, events.ExceededGracePeriod, \"Container runtime did not kill the pod within specified grace period.\")\n\t\t\treturn fmt.Errorf(\"timeout waiting to kill pod\")\n\t\t}\n\t}\n}","line":{"from":1641,"to":1684}} {"id":100007412,"name":"cleanupPodUpdates","signature":"func (p *podWorkers) cleanupPodUpdates(uid types.UID)","file":"pkg/kubelet/pod_workers.go","code":"// cleanupPodUpdates closes the podUpdates channel and removes it from\n// podUpdates map so that the corresponding pod worker can stop. It also\n// removes any undelivered work. This method must be called holding the\n// pod lock.\nfunc (p *podWorkers) cleanupPodUpdates(uid types.UID) {\n\tif ch, ok := p.podUpdates[uid]; ok {\n\t\tclose(ch)\n\t}\n\tdelete(p.podUpdates, uid)\n}","line":{"from":1686,"to":1695}} {"id":100007413,"name":"requeueLastPodUpdate","signature":"func (p *podWorkers) requeueLastPodUpdate(podUID types.UID, status *podSyncStatus)","file":"pkg/kubelet/pod_workers.go","code":"// requeueLastPodUpdate creates a new pending pod update from the most recently\n// executed update if no update is already queued, and then notifies the pod\n// worker goroutine of the update. This method must be called while holding\n// the pod lock.\nfunc (p *podWorkers) requeueLastPodUpdate(podUID types.UID, status *podSyncStatus) {\n\t// if there is already an update queued, we can use that instead, or if\n\t// we have no previously executed update, we cannot replay it.\n\tif status.pendingUpdate != nil || status.activeUpdate == nil {\n\t\treturn\n\t}\n\tcopied := *status.activeUpdate\n\tstatus.pendingUpdate = \u0026copied\n\n\t// notify the pod worker\n\tstatus.working = true\n\tselect {\n\tcase p.podUpdates[podUID] \u003c- struct{}{}:\n\tdefault:\n\t}\n}","line":{"from":1697,"to":1716}} {"id":100007414,"name":"NewCriticalPodAdmissionHandler","signature":"func NewCriticalPodAdmissionHandler(getPodsFunc eviction.ActivePodsFunc, killPodFunc eviction.KillPodFunc, recorder record.EventRecorder) *CriticalPodAdmissionHandler","file":"pkg/kubelet/preemption/preemption.go","code":"func NewCriticalPodAdmissionHandler(getPodsFunc eviction.ActivePodsFunc, killPodFunc eviction.KillPodFunc, recorder record.EventRecorder) *CriticalPodAdmissionHandler {\n\treturn \u0026CriticalPodAdmissionHandler{\n\t\tgetPodsFunc: getPodsFunc,\n\t\tkillPodFunc: killPodFunc,\n\t\trecorder: recorder,\n\t}\n}","line":{"from":55,"to":61}} {"id":100007415,"name":"HandleAdmissionFailure","signature":"func (c *CriticalPodAdmissionHandler) HandleAdmissionFailure(admitPod *v1.Pod, failureReasons []lifecycle.PredicateFailureReason) ([]lifecycle.PredicateFailureReason, error)","file":"pkg/kubelet/preemption/preemption.go","code":"// HandleAdmissionFailure gracefully handles admission rejection, and, in some cases,\n// to allow admission of the pod despite its previous failure.\nfunc (c *CriticalPodAdmissionHandler) HandleAdmissionFailure(admitPod *v1.Pod, failureReasons []lifecycle.PredicateFailureReason) ([]lifecycle.PredicateFailureReason, error) {\n\tif !kubetypes.IsCriticalPod(admitPod) {\n\t\treturn failureReasons, nil\n\t}\n\t// InsufficientResourceError is not a reason to reject a critical pod.\n\t// Instead of rejecting, we free up resources to admit it, if no other reasons for rejection exist.\n\tnonResourceReasons := []lifecycle.PredicateFailureReason{}\n\tresourceReasons := []*admissionRequirement{}\n\tfor _, reason := range failureReasons {\n\t\tif r, ok := reason.(*lifecycle.InsufficientResourceError); ok {\n\t\t\tresourceReasons = append(resourceReasons, \u0026admissionRequirement{\n\t\t\t\tresourceName: r.ResourceName,\n\t\t\t\tquantity: r.GetInsufficientAmount(),\n\t\t\t})\n\t\t} else {\n\t\t\tnonResourceReasons = append(nonResourceReasons, reason)\n\t\t}\n\t}\n\tif len(nonResourceReasons) \u003e 0 {\n\t\t// Return only reasons that are not resource related, since critical pods cannot fail admission for resource reasons.\n\t\treturn nonResourceReasons, nil\n\t}\n\terr := c.evictPodsToFreeRequests(admitPod, admissionRequirementList(resourceReasons))\n\t// if no error is returned, preemption succeeded and the pod is safe to admit.\n\treturn nil, err\n}","line":{"from":63,"to":90}} {"id":100007416,"name":"evictPodsToFreeRequests","signature":"func (c *CriticalPodAdmissionHandler) evictPodsToFreeRequests(admitPod *v1.Pod, insufficientResources admissionRequirementList) error","file":"pkg/kubelet/preemption/preemption.go","code":"// evictPodsToFreeRequests takes a list of insufficient resources, and attempts to free them by evicting pods\n// based on requests. For example, if the only insufficient resource is 200Mb of memory, this function could\n// evict a pod with request=250Mb.\nfunc (c *CriticalPodAdmissionHandler) evictPodsToFreeRequests(admitPod *v1.Pod, insufficientResources admissionRequirementList) error {\n\tpodsToPreempt, err := getPodsToPreempt(admitPod, c.getPodsFunc(), insufficientResources)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"preemption: error finding a set of pods to preempt: %v\", err)\n\t}\n\tfor _, pod := range podsToPreempt {\n\t\t// record that we are evicting the pod\n\t\tc.recorder.Eventf(pod, v1.EventTypeWarning, events.PreemptContainer, message)\n\t\t// this is a blocking call and should only return when the pod and its containers are killed.\n\t\tklog.V(3).InfoS(\"Preempting pod to free up resources\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID, \"insufficientResources\", insufficientResources)\n\t\terr := c.killPodFunc(pod, true, nil, func(status *v1.PodStatus) {\n\t\t\tstatus.Phase = v1.PodFailed\n\t\t\tstatus.Reason = events.PreemptContainer\n\t\t\tstatus.Message = message\n\t\t\tif utilfeature.DefaultFeatureGate.Enabled(features.PodDisruptionConditions) {\n\t\t\t\tpodutil.UpdatePodCondition(status, \u0026v1.PodCondition{\n\t\t\t\t\tType: v1.DisruptionTarget,\n\t\t\t\t\tStatus: v1.ConditionTrue,\n\t\t\t\t\tReason: v1.PodReasonTerminationByKubelet,\n\t\t\t\t\tMessage: \"Pod was preempted by Kubelet to accommodate a critical pod.\",\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to evict pod\", \"pod\", klog.KObj(pod))\n\t\t\t// In future syncPod loops, the kubelet will retry the pod deletion steps that it was stuck on.\n\t\t\tcontinue\n\t\t}\n\t\tif len(insufficientResources) \u003e 0 {\n\t\t\tmetrics.Preemptions.WithLabelValues(insufficientResources[0].resourceName.String()).Inc()\n\t\t} else {\n\t\t\tmetrics.Preemptions.WithLabelValues(\"\").Inc()\n\t\t}\n\t\tklog.InfoS(\"Pod evicted successfully\", \"pod\", klog.KObj(pod))\n\t}\n\treturn nil\n}","line":{"from":92,"to":131}} {"id":100007417,"name":"getPodsToPreempt","signature":"func getPodsToPreempt(pod *v1.Pod, pods []*v1.Pod, requirements admissionRequirementList) ([]*v1.Pod, error)","file":"pkg/kubelet/preemption/preemption.go","code":"// getPodsToPreempt returns a list of pods that could be preempted to free requests \u003e= requirements\nfunc getPodsToPreempt(pod *v1.Pod, pods []*v1.Pod, requirements admissionRequirementList) ([]*v1.Pod, error) {\n\tbestEffortPods, burstablePods, guaranteedPods := sortPodsByQOS(pod, pods)\n\n\t// make sure that pods exist to reclaim the requirements\n\tunableToMeetRequirements := requirements.subtract(append(append(bestEffortPods, burstablePods...), guaranteedPods...)...)\n\tif len(unableToMeetRequirements) \u003e 0 {\n\t\treturn nil, fmt.Errorf(\"no set of running pods found to reclaim resources: %v\", unableToMeetRequirements.toString())\n\t}\n\t// find the guaranteed pods we would need to evict if we already evicted ALL burstable and besteffort pods.\n\tguaranteedToEvict, err := getPodsToPreemptByDistance(guaranteedPods, requirements.subtract(append(bestEffortPods, burstablePods...)...))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Find the burstable pods we would need to evict if we already evicted ALL besteffort pods, and the required guaranteed pods.\n\tburstableToEvict, err := getPodsToPreemptByDistance(burstablePods, requirements.subtract(append(bestEffortPods, guaranteedToEvict...)...))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Find the besteffort pods we would need to evict if we already evicted the required guaranteed and burstable pods.\n\tbestEffortToEvict, err := getPodsToPreemptByDistance(bestEffortPods, requirements.subtract(append(burstableToEvict, guaranteedToEvict...)...))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn append(append(bestEffortToEvict, burstableToEvict...), guaranteedToEvict...), nil\n}","line":{"from":133,"to":158}} {"id":100007418,"name":"getPodsToPreemptByDistance","signature":"func getPodsToPreemptByDistance(pods []*v1.Pod, requirements admissionRequirementList) ([]*v1.Pod, error)","file":"pkg/kubelet/preemption/preemption.go","code":"// getPodsToPreemptByDistance finds the pods that have pod requests \u003e= admission requirements.\n// Chooses pods that minimize \"distance\" to the requirements.\n// If more than one pod exists that fulfills the remaining requirements,\n// it chooses the pod that has the \"smaller resource request\"\n// This method, by repeatedly choosing the pod that fulfills as much of the requirements as possible,\n// attempts to minimize the number of pods returned.\nfunc getPodsToPreemptByDistance(pods []*v1.Pod, requirements admissionRequirementList) ([]*v1.Pod, error) {\n\tpodsToEvict := []*v1.Pod{}\n\t// evict pods by shortest distance from remaining requirements, updating requirements every round.\n\tfor len(requirements) \u003e 0 {\n\t\tif len(pods) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"no set of running pods found to reclaim resources: %v\", requirements.toString())\n\t\t}\n\t\t// all distances must be less than len(requirements), because the max distance for a single requirement is 1\n\t\tbestDistance := float64(len(requirements) + 1)\n\t\tbestPodIndex := 0\n\t\t// Find the pod with the smallest distance from requirements\n\t\t// Or, in the case of two equidistant pods, find the pod with \"smaller\" resource requests.\n\t\tfor i, pod := range pods {\n\t\t\tdist := requirements.distance(pod)\n\t\t\tif dist \u003c bestDistance || (bestDistance == dist \u0026\u0026 smallerResourceRequest(pod, pods[bestPodIndex])) {\n\t\t\t\tbestDistance = dist\n\t\t\t\tbestPodIndex = i\n\t\t\t}\n\t\t}\n\t\t// subtract the pod from requirements, and transfer the pod from input-pods to pods-to-evicted\n\t\trequirements = requirements.subtract(pods[bestPodIndex])\n\t\tpodsToEvict = append(podsToEvict, pods[bestPodIndex])\n\t\tpods[bestPodIndex] = pods[len(pods)-1]\n\t\tpods = pods[:len(pods)-1]\n\t}\n\treturn podsToEvict, nil\n}","line":{"from":160,"to":192}} {"id":100007419,"name":"distance","signature":"func (a admissionRequirementList) distance(pod *v1.Pod) float64","file":"pkg/kubelet/preemption/preemption.go","code":"// distance returns distance of the pods requests from the admissionRequirements.\n// The distance is measured by the fraction of the requirement satisfied by the pod,\n// so that each requirement is weighted equally, regardless of absolute magnitude.\nfunc (a admissionRequirementList) distance(pod *v1.Pod) float64 {\n\tdist := float64(0)\n\tfor _, req := range a {\n\t\tremainingRequest := float64(req.quantity - resource.GetResourceRequest(pod, req.resourceName))\n\t\tif remainingRequest \u003e 0 {\n\t\t\tdist += math.Pow(remainingRequest/float64(req.quantity), 2)\n\t\t}\n\t}\n\treturn dist\n}","line":{"from":201,"to":213}} {"id":100007420,"name":"subtract","signature":"func (a admissionRequirementList) subtract(pods ...*v1.Pod) admissionRequirementList","file":"pkg/kubelet/preemption/preemption.go","code":"// subtract returns a new admissionRequirementList containing remaining requirements if the provided pod\n// were to be preempted\nfunc (a admissionRequirementList) subtract(pods ...*v1.Pod) admissionRequirementList {\n\tnewList := []*admissionRequirement{}\n\tfor _, req := range a {\n\t\tnewQuantity := req.quantity\n\t\tfor _, pod := range pods {\n\t\t\tnewQuantity -= resource.GetResourceRequest(pod, req.resourceName)\n\t\t\tif newQuantity \u003c= 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif newQuantity \u003e 0 {\n\t\t\tnewList = append(newList, \u0026admissionRequirement{\n\t\t\t\tresourceName: req.resourceName,\n\t\t\t\tquantity: newQuantity,\n\t\t\t})\n\t\t}\n\t}\n\treturn newList\n}","line":{"from":215,"to":235}} {"id":100007421,"name":"toString","signature":"func (a admissionRequirementList) toString() string","file":"pkg/kubelet/preemption/preemption.go","code":"func (a admissionRequirementList) toString() string {\n\ts := \"[\"\n\tfor _, req := range a {\n\t\ts += fmt.Sprintf(\"(res: %v, q: %d), \", req.resourceName, req.quantity)\n\t}\n\treturn s + \"]\"\n}","line":{"from":237,"to":243}} {"id":100007422,"name":"sortPodsByQOS","signature":"func sortPodsByQOS(preemptor *v1.Pod, pods []*v1.Pod) (bestEffort, burstable, guaranteed []*v1.Pod)","file":"pkg/kubelet/preemption/preemption.go","code":"// sortPodsByQOS returns lists containing besteffort, burstable, and guaranteed pods that\n// can be preempted by preemptor pod.\nfunc sortPodsByQOS(preemptor *v1.Pod, pods []*v1.Pod) (bestEffort, burstable, guaranteed []*v1.Pod) {\n\tfor _, pod := range pods {\n\t\tif kubetypes.Preemptable(preemptor, pod) {\n\t\t\tswitch v1qos.GetPodQOS(pod) {\n\t\t\tcase v1.PodQOSBestEffort:\n\t\t\t\tbestEffort = append(bestEffort, pod)\n\t\t\tcase v1.PodQOSBurstable:\n\t\t\t\tburstable = append(burstable, pod)\n\t\t\tcase v1.PodQOSGuaranteed:\n\t\t\t\tguaranteed = append(guaranteed, pod)\n\t\t\tdefault:\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}","line":{"from":245,"to":263}} {"id":100007423,"name":"smallerResourceRequest","signature":"func smallerResourceRequest(pod1 *v1.Pod, pod2 *v1.Pod) bool","file":"pkg/kubelet/preemption/preemption.go","code":"// smallerResourceRequest returns true if pod1 has a smaller request than pod2\nfunc smallerResourceRequest(pod1 *v1.Pod, pod2 *v1.Pod) bool {\n\tpriorityList := []v1.ResourceName{\n\t\tv1.ResourceMemory,\n\t\tv1.ResourceCPU,\n\t}\n\tfor _, res := range priorityList {\n\t\treq1 := resource.GetResourceRequest(pod1, res)\n\t\treq2 := resource.GetResourceRequest(pod2, res)\n\t\tif req1 \u003c req2 {\n\t\t\treturn true\n\t\t} else if req1 \u003e req2 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":265,"to":281}} {"id":100007424,"name":"newProber","signature":"func newProber(","file":"pkg/kubelet/prober/prober.go","code":"// NewProber creates a Prober, it takes a command runner and\n// several container info managers.\nfunc newProber(\n\trunner kubecontainer.CommandRunner,\n\trecorder record.EventRecorder) *prober {\n\n\tconst followNonLocalRedirects = false\n\treturn \u0026prober{\n\t\texec: execprobe.New(),\n\t\thttp: httpprobe.New(followNonLocalRedirects),\n\t\ttcp: tcpprobe.New(),\n\t\tgrpc: grpcprobe.New(),\n\t\trunner: runner,\n\t\trecorder: recorder,\n\t}\n}","line":{"from":54,"to":69}} {"id":100007425,"name":"recordContainerEvent","signature":"func (pb *prober) recordContainerEvent(pod *v1.Pod, container *v1.Container, eventType, reason, message string, args ...interface{})","file":"pkg/kubelet/prober/prober.go","code":"// recordContainerEvent should be used by the prober for all container related events.\nfunc (pb *prober) recordContainerEvent(pod *v1.Pod, container *v1.Container, eventType, reason, message string, args ...interface{}) {\n\tref, err := kubecontainer.GenerateContainerRef(pod, container)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Can't make a ref to pod and container\", \"pod\", klog.KObj(pod), \"containerName\", container.Name)\n\t\treturn\n\t}\n\tpb.recorder.Eventf(ref, eventType, reason, message, args...)\n}","line":{"from":71,"to":79}} {"id":100007426,"name":"probe","signature":"func (pb *prober) probe(ctx context.Context, probeType probeType, pod *v1.Pod, status v1.PodStatus, container v1.Container, containerID kubecontainer.ContainerID) (results.Result, error)","file":"pkg/kubelet/prober/prober.go","code":"// probe probes the container.\nfunc (pb *prober) probe(ctx context.Context, probeType probeType, pod *v1.Pod, status v1.PodStatus, container v1.Container, containerID kubecontainer.ContainerID) (results.Result, error) {\n\tvar probeSpec *v1.Probe\n\tswitch probeType {\n\tcase readiness:\n\t\tprobeSpec = container.ReadinessProbe\n\tcase liveness:\n\t\tprobeSpec = container.LivenessProbe\n\tcase startup:\n\t\tprobeSpec = container.StartupProbe\n\tdefault:\n\t\treturn results.Failure, fmt.Errorf(\"unknown probe type: %q\", probeType)\n\t}\n\n\tif probeSpec == nil {\n\t\tklog.InfoS(\"Probe is nil\", \"probeType\", probeType, \"pod\", klog.KObj(pod), \"podUID\", pod.UID, \"containerName\", container.Name)\n\t\treturn results.Success, nil\n\t}\n\n\tresult, output, err := pb.runProbeWithRetries(ctx, probeType, probeSpec, pod, status, container, containerID, maxProbeRetries)\n\tif err != nil || (result != probe.Success \u0026\u0026 result != probe.Warning) {\n\t\t// Probe failed in one way or another.\n\t\tif err != nil {\n\t\t\tklog.V(1).ErrorS(err, \"Probe errored\", \"probeType\", probeType, \"pod\", klog.KObj(pod), \"podUID\", pod.UID, \"containerName\", container.Name)\n\t\t\tpb.recordContainerEvent(pod, \u0026container, v1.EventTypeWarning, events.ContainerUnhealthy, \"%s probe errored: %v\", probeType, err)\n\t\t} else { // result != probe.Success\n\t\t\tklog.V(1).InfoS(\"Probe failed\", \"probeType\", probeType, \"pod\", klog.KObj(pod), \"podUID\", pod.UID, \"containerName\", container.Name, \"probeResult\", result, \"output\", output)\n\t\t\tpb.recordContainerEvent(pod, \u0026container, v1.EventTypeWarning, events.ContainerUnhealthy, \"%s probe failed: %s\", probeType, output)\n\t\t}\n\t\treturn results.Failure, err\n\t}\n\tif result == probe.Warning {\n\t\tpb.recordContainerEvent(pod, \u0026container, v1.EventTypeWarning, events.ContainerProbeWarning, \"%s probe warning: %s\", probeType, output)\n\t\tklog.V(3).InfoS(\"Probe succeeded with a warning\", \"probeType\", probeType, \"pod\", klog.KObj(pod), \"podUID\", pod.UID, \"containerName\", container.Name, \"output\", output)\n\t} else {\n\t\tklog.V(3).InfoS(\"Probe succeeded\", \"probeType\", probeType, \"pod\", klog.KObj(pod), \"podUID\", pod.UID, \"containerName\", container.Name)\n\t}\n\treturn results.Success, nil\n}","line":{"from":81,"to":119}} {"id":100007427,"name":"runProbeWithRetries","signature":"func (pb *prober) runProbeWithRetries(ctx context.Context, probeType probeType, p *v1.Probe, pod *v1.Pod, status v1.PodStatus, container v1.Container, containerID kubecontainer.ContainerID, retries int) (probe.Result, string, error)","file":"pkg/kubelet/prober/prober.go","code":"// runProbeWithRetries tries to probe the container in a finite loop, it returns the last result\n// if it never succeeds.\nfunc (pb *prober) runProbeWithRetries(ctx context.Context, probeType probeType, p *v1.Probe, pod *v1.Pod, status v1.PodStatus, container v1.Container, containerID kubecontainer.ContainerID, retries int) (probe.Result, string, error) {\n\tvar err error\n\tvar result probe.Result\n\tvar output string\n\tfor i := 0; i \u003c retries; i++ {\n\t\tresult, output, err = pb.runProbe(ctx, probeType, p, pod, status, container, containerID)\n\t\tif err == nil {\n\t\t\treturn result, output, nil\n\t\t}\n\t}\n\treturn result, output, err\n}","line":{"from":121,"to":134}} {"id":100007428,"name":"runProbe","signature":"func (pb *prober) runProbe(ctx context.Context, probeType probeType, p *v1.Probe, pod *v1.Pod, status v1.PodStatus, container v1.Container, containerID kubecontainer.ContainerID) (probe.Result, string, error)","file":"pkg/kubelet/prober/prober.go","code":"func (pb *prober) runProbe(ctx context.Context, probeType probeType, p *v1.Probe, pod *v1.Pod, status v1.PodStatus, container v1.Container, containerID kubecontainer.ContainerID) (probe.Result, string, error) {\n\ttimeout := time.Duration(p.TimeoutSeconds) * time.Second\n\tif p.Exec != nil {\n\t\tklog.V(4).InfoS(\"Exec-Probe runProbe\", \"pod\", klog.KObj(pod), \"containerName\", container.Name, \"execCommand\", p.Exec.Command)\n\t\tcommand := kubecontainer.ExpandContainerCommandOnlyStatic(p.Exec.Command, container.Env)\n\t\treturn pb.exec.Probe(pb.newExecInContainer(ctx, container, containerID, command, timeout))\n\t}\n\tif p.HTTPGet != nil {\n\t\treq, err := httpprobe.NewRequestForHTTPGetAction(p.HTTPGet, \u0026container, status.PodIP, \"probe\")\n\t\tif err != nil {\n\t\t\treturn probe.Unknown, \"\", err\n\t\t}\n\t\tif klogV4 := klog.V(4); klogV4.Enabled() {\n\t\t\tport := req.URL.Port()\n\t\t\thost := req.URL.Hostname()\n\t\t\tpath := req.URL.Path\n\t\t\tscheme := req.URL.Scheme\n\t\t\theaders := p.HTTPGet.HTTPHeaders\n\t\t\tklogV4.InfoS(\"HTTP-Probe\", \"scheme\", scheme, \"host\", host, \"port\", port, \"path\", path, \"timeout\", timeout, \"headers\", headers)\n\t\t}\n\t\treturn pb.http.Probe(req, timeout)\n\t}\n\tif p.TCPSocket != nil {\n\t\tport, err := probe.ResolveContainerPort(p.TCPSocket.Port, \u0026container)\n\t\tif err != nil {\n\t\t\treturn probe.Unknown, \"\", err\n\t\t}\n\t\thost := p.TCPSocket.Host\n\t\tif host == \"\" {\n\t\t\thost = status.PodIP\n\t\t}\n\t\tklog.V(4).InfoS(\"TCP-Probe\", \"host\", host, \"port\", port, \"timeout\", timeout)\n\t\treturn pb.tcp.Probe(host, port, timeout)\n\t}\n\n\tif p.GRPC != nil {\n\t\thost := status.PodIP\n\t\tservice := \"\"\n\t\tif p.GRPC.Service != nil {\n\t\t\tservice = *p.GRPC.Service\n\t\t}\n\t\tklog.V(4).InfoS(\"GRPC-Probe\", \"host\", host, \"service\", service, \"port\", p.GRPC.Port, \"timeout\", timeout)\n\t\treturn pb.grpc.Probe(host, service, int(p.GRPC.Port), timeout)\n\t}\n\n\tklog.InfoS(\"Failed to find probe builder for container\", \"containerName\", container.Name)\n\treturn probe.Unknown, \"\", fmt.Errorf(\"missing probe handler for %s:%s\", format.Pod(pod), container.Name)\n}","line":{"from":136,"to":183}} {"id":100007429,"name":"newExecInContainer","signature":"func (pb *prober) newExecInContainer(ctx context.Context, container v1.Container, containerID kubecontainer.ContainerID, cmd []string, timeout time.Duration) exec.Cmd","file":"pkg/kubelet/prober/prober.go","code":"func (pb *prober) newExecInContainer(ctx context.Context, container v1.Container, containerID kubecontainer.ContainerID, cmd []string, timeout time.Duration) exec.Cmd {\n\treturn \u0026execInContainer{run: func() ([]byte, error) {\n\t\treturn pb.runner.RunInContainer(ctx, containerID, cmd, timeout)\n\t}}\n}","line":{"from":192,"to":196}} {"id":100007430,"name":"Run","signature":"func (eic *execInContainer) Run() error","file":"pkg/kubelet/prober/prober.go","code":"func (eic *execInContainer) Run() error {\n\treturn nil\n}","line":{"from":198,"to":200}} {"id":100007431,"name":"CombinedOutput","signature":"func (eic *execInContainer) CombinedOutput() ([]byte, error)","file":"pkg/kubelet/prober/prober.go","code":"func (eic *execInContainer) CombinedOutput() ([]byte, error) {\n\treturn eic.run()\n}","line":{"from":202,"to":204}} {"id":100007432,"name":"Output","signature":"func (eic *execInContainer) Output() ([]byte, error)","file":"pkg/kubelet/prober/prober.go","code":"func (eic *execInContainer) Output() ([]byte, error) {\n\treturn nil, fmt.Errorf(\"unimplemented\")\n}","line":{"from":206,"to":208}} {"id":100007433,"name":"SetDir","signature":"func (eic *execInContainer) SetDir(dir string)","file":"pkg/kubelet/prober/prober.go","code":"func (eic *execInContainer) SetDir(dir string) {\n\t// unimplemented\n}","line":{"from":210,"to":212}} {"id":100007434,"name":"SetStdin","signature":"func (eic *execInContainer) SetStdin(in io.Reader)","file":"pkg/kubelet/prober/prober.go","code":"func (eic *execInContainer) SetStdin(in io.Reader) {\n\t// unimplemented\n}","line":{"from":214,"to":216}} {"id":100007435,"name":"SetStdout","signature":"func (eic *execInContainer) SetStdout(out io.Writer)","file":"pkg/kubelet/prober/prober.go","code":"func (eic *execInContainer) SetStdout(out io.Writer) {\n\teic.writer = out\n}","line":{"from":218,"to":220}} {"id":100007436,"name":"SetStderr","signature":"func (eic *execInContainer) SetStderr(out io.Writer)","file":"pkg/kubelet/prober/prober.go","code":"func (eic *execInContainer) SetStderr(out io.Writer) {\n\teic.writer = out\n}","line":{"from":222,"to":224}} {"id":100007437,"name":"SetEnv","signature":"func (eic *execInContainer) SetEnv(env []string)","file":"pkg/kubelet/prober/prober.go","code":"func (eic *execInContainer) SetEnv(env []string) {\n\t// unimplemented\n}","line":{"from":226,"to":228}} {"id":100007438,"name":"Stop","signature":"func (eic *execInContainer) Stop()","file":"pkg/kubelet/prober/prober.go","code":"func (eic *execInContainer) Stop() {\n\t// unimplemented\n}","line":{"from":230,"to":232}} {"id":100007439,"name":"Start","signature":"func (eic *execInContainer) Start() error","file":"pkg/kubelet/prober/prober.go","code":"func (eic *execInContainer) Start() error {\n\tdata, err := eic.run()\n\tif eic.writer != nil {\n\t\t// only record the write error, do not cover the command run error\n\t\tif p, err := eic.writer.Write(data); err != nil {\n\t\t\tklog.ErrorS(err, \"Unable to write all bytes from execInContainer\", \"expectedBytes\", len(data), \"actualBytes\", p)\n\t\t}\n\t}\n\treturn err\n}","line":{"from":234,"to":243}} {"id":100007440,"name":"Wait","signature":"func (eic *execInContainer) Wait() error","file":"pkg/kubelet/prober/prober.go","code":"func (eic *execInContainer) Wait() error {\n\treturn nil\n}","line":{"from":245,"to":247}} {"id":100007441,"name":"StdoutPipe","signature":"func (eic *execInContainer) StdoutPipe() (io.ReadCloser, error)","file":"pkg/kubelet/prober/prober.go","code":"func (eic *execInContainer) StdoutPipe() (io.ReadCloser, error) {\n\treturn nil, fmt.Errorf(\"unimplemented\")\n}","line":{"from":249,"to":251}} {"id":100007442,"name":"StderrPipe","signature":"func (eic *execInContainer) StderrPipe() (io.ReadCloser, error)","file":"pkg/kubelet/prober/prober.go","code":"func (eic *execInContainer) StderrPipe() (io.ReadCloser, error) {\n\treturn nil, fmt.Errorf(\"unimplemented\")\n}","line":{"from":253,"to":255}} {"id":100007443,"name":"NewManager","signature":"func NewManager(","file":"pkg/kubelet/prober/prober_manager.go","code":"// NewManager creates a Manager for pod probing.\nfunc NewManager(\n\tstatusManager status.Manager,\n\tlivenessManager results.Manager,\n\treadinessManager results.Manager,\n\tstartupManager results.Manager,\n\trunner kubecontainer.CommandRunner,\n\trecorder record.EventRecorder) Manager {\n\n\tprober := newProber(runner, recorder)\n\treturn \u0026manager{\n\t\tstatusManager: statusManager,\n\t\tprober: prober,\n\t\treadinessManager: readinessManager,\n\t\tlivenessManager: livenessManager,\n\t\tstartupManager: startupManager,\n\t\tworkers: make(map[probeKey]*worker),\n\t\tstart: clock.RealClock{}.Now(),\n\t}\n}","line":{"from":114,"to":133}} {"id":100007444,"name":"String","signature":"func (t probeType) String() string","file":"pkg/kubelet/prober/prober_manager.go","code":"// For debugging.\nfunc (t probeType) String() string {\n\tswitch t {\n\tcase readiness:\n\t\treturn \"Readiness\"\n\tcase liveness:\n\t\treturn \"Liveness\"\n\tcase startup:\n\t\treturn \"Startup\"\n\tdefault:\n\t\treturn \"UNKNOWN\"\n\t}\n}","line":{"from":155,"to":167}} {"id":100007445,"name":"AddPod","signature":"func (m *manager) AddPod(pod *v1.Pod)","file":"pkg/kubelet/prober/prober_manager.go","code":"func (m *manager) AddPod(pod *v1.Pod) {\n\tm.workerLock.Lock()\n\tdefer m.workerLock.Unlock()\n\n\tkey := probeKey{podUID: pod.UID}\n\tfor _, c := range pod.Spec.Containers {\n\t\tkey.containerName = c.Name\n\n\t\tif c.StartupProbe != nil {\n\t\t\tkey.probeType = startup\n\t\t\tif _, ok := m.workers[key]; ok {\n\t\t\t\tklog.V(8).ErrorS(nil, \"Startup probe already exists for container\",\n\t\t\t\t\t\"pod\", klog.KObj(pod), \"containerName\", c.Name)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw := newWorker(m, startup, pod, c)\n\t\t\tm.workers[key] = w\n\t\t\tgo w.run()\n\t\t}\n\n\t\tif c.ReadinessProbe != nil {\n\t\t\tkey.probeType = readiness\n\t\t\tif _, ok := m.workers[key]; ok {\n\t\t\t\tklog.V(8).ErrorS(nil, \"Readiness probe already exists for container\",\n\t\t\t\t\t\"pod\", klog.KObj(pod), \"containerName\", c.Name)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw := newWorker(m, readiness, pod, c)\n\t\t\tm.workers[key] = w\n\t\t\tgo w.run()\n\t\t}\n\n\t\tif c.LivenessProbe != nil {\n\t\t\tkey.probeType = liveness\n\t\t\tif _, ok := m.workers[key]; ok {\n\t\t\t\tklog.V(8).ErrorS(nil, \"Liveness probe already exists for container\",\n\t\t\t\t\t\"pod\", klog.KObj(pod), \"containerName\", c.Name)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw := newWorker(m, liveness, pod, c)\n\t\t\tm.workers[key] = w\n\t\t\tgo w.run()\n\t\t}\n\t}\n}","line":{"from":169,"to":213}} {"id":100007446,"name":"StopLivenessAndStartup","signature":"func (m *manager) StopLivenessAndStartup(pod *v1.Pod)","file":"pkg/kubelet/prober/prober_manager.go","code":"func (m *manager) StopLivenessAndStartup(pod *v1.Pod) {\n\tm.workerLock.RLock()\n\tdefer m.workerLock.RUnlock()\n\n\tkey := probeKey{podUID: pod.UID}\n\tfor _, c := range pod.Spec.Containers {\n\t\tkey.containerName = c.Name\n\t\tfor _, probeType := range [...]probeType{liveness, startup} {\n\t\t\tkey.probeType = probeType\n\t\t\tif worker, ok := m.workers[key]; ok {\n\t\t\t\tworker.stop()\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":215,"to":229}} {"id":100007447,"name":"RemovePod","signature":"func (m *manager) RemovePod(pod *v1.Pod)","file":"pkg/kubelet/prober/prober_manager.go","code":"func (m *manager) RemovePod(pod *v1.Pod) {\n\tm.workerLock.RLock()\n\tdefer m.workerLock.RUnlock()\n\n\tkey := probeKey{podUID: pod.UID}\n\tfor _, c := range pod.Spec.Containers {\n\t\tkey.containerName = c.Name\n\t\tfor _, probeType := range [...]probeType{readiness, liveness, startup} {\n\t\t\tkey.probeType = probeType\n\t\t\tif worker, ok := m.workers[key]; ok {\n\t\t\t\tworker.stop()\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":231,"to":245}} {"id":100007448,"name":"CleanupPods","signature":"func (m *manager) CleanupPods(desiredPods map[types.UID]sets.Empty)","file":"pkg/kubelet/prober/prober_manager.go","code":"func (m *manager) CleanupPods(desiredPods map[types.UID]sets.Empty) {\n\tm.workerLock.RLock()\n\tdefer m.workerLock.RUnlock()\n\n\tfor key, worker := range m.workers {\n\t\tif _, ok := desiredPods[key.podUID]; !ok {\n\t\t\tworker.stop()\n\t\t}\n\t}\n}","line":{"from":247,"to":256}} {"id":100007449,"name":"UpdatePodStatus","signature":"func (m *manager) UpdatePodStatus(podUID types.UID, podStatus *v1.PodStatus)","file":"pkg/kubelet/prober/prober_manager.go","code":"func (m *manager) UpdatePodStatus(podUID types.UID, podStatus *v1.PodStatus) {\n\tfor i, c := range podStatus.ContainerStatuses {\n\t\tvar started bool\n\t\tif c.State.Running == nil {\n\t\t\tstarted = false\n\t\t} else if result, ok := m.startupManager.Get(kubecontainer.ParseContainerID(c.ContainerID)); ok {\n\t\t\tstarted = result == results.Success\n\t\t} else {\n\t\t\t// The check whether there is a probe which hasn't run yet.\n\t\t\t_, exists := m.getWorker(podUID, c.Name, startup)\n\t\t\tstarted = !exists\n\t\t}\n\t\tpodStatus.ContainerStatuses[i].Started = \u0026started\n\n\t\tif started {\n\t\t\tvar ready bool\n\t\t\tif c.State.Running == nil {\n\t\t\t\tready = false\n\t\t\t} else if result, ok := m.readinessManager.Get(kubecontainer.ParseContainerID(c.ContainerID)); ok \u0026\u0026 result == results.Success {\n\t\t\t\tready = true\n\t\t\t} else {\n\t\t\t\t// The check whether there is a probe which hasn't run yet.\n\t\t\t\tw, exists := m.getWorker(podUID, c.Name, readiness)\n\t\t\t\tready = !exists // no readinessProbe -\u003e always ready\n\t\t\t\tif exists {\n\t\t\t\t\t// Trigger an immediate run of the readinessProbe to update ready state\n\t\t\t\t\tselect {\n\t\t\t\t\tcase w.manualTriggerCh \u003c- struct{}{}:\n\t\t\t\t\tdefault: // Non-blocking.\n\t\t\t\t\t\tklog.InfoS(\"Failed to trigger a manual run\", \"probe\", w.probeType.String())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tpodStatus.ContainerStatuses[i].Ready = ready\n\t\t}\n\t}\n\t// init containers are ready if they have exited with success or if a readiness probe has\n\t// succeeded.\n\tfor i, c := range podStatus.InitContainerStatuses {\n\t\tvar ready bool\n\t\tif c.State.Terminated != nil \u0026\u0026 c.State.Terminated.ExitCode == 0 {\n\t\t\tready = true\n\t\t}\n\t\tpodStatus.InitContainerStatuses[i].Ready = ready\n\t}\n}","line":{"from":258,"to":303}} {"id":100007450,"name":"getWorker","signature":"func (m *manager) getWorker(podUID types.UID, containerName string, probeType probeType) (*worker, bool)","file":"pkg/kubelet/prober/prober_manager.go","code":"func (m *manager) getWorker(podUID types.UID, containerName string, probeType probeType) (*worker, bool) {\n\tm.workerLock.RLock()\n\tdefer m.workerLock.RUnlock()\n\tworker, ok := m.workers[probeKey{podUID, containerName, probeType}]\n\treturn worker, ok\n}","line":{"from":305,"to":310}} {"id":100007451,"name":"removeWorker","signature":"func (m *manager) removeWorker(podUID types.UID, containerName string, probeType probeType)","file":"pkg/kubelet/prober/prober_manager.go","code":"// Called by the worker after exiting.\nfunc (m *manager) removeWorker(podUID types.UID, containerName string, probeType probeType) {\n\tm.workerLock.Lock()\n\tdefer m.workerLock.Unlock()\n\tdelete(m.workers, probeKey{podUID, containerName, probeType})\n}","line":{"from":312,"to":317}} {"id":100007452,"name":"workerCount","signature":"func (m *manager) workerCount() int","file":"pkg/kubelet/prober/prober_manager.go","code":"// workerCount returns the total number of probe workers. For testing.\nfunc (m *manager) workerCount() int {\n\tm.workerLock.RLock()\n\tdefer m.workerLock.RUnlock()\n\treturn len(m.workers)\n}","line":{"from":319,"to":324}} {"id":100007453,"name":"String","signature":"func (r Result) String() string","file":"pkg/kubelet/prober/results/results_manager.go","code":"func (r Result) String() string {\n\tswitch r {\n\tcase Success:\n\t\treturn \"Success\"\n\tcase Failure:\n\t\treturn \"Failure\"\n\tdefault:\n\t\treturn \"UNKNOWN\"\n\t}\n}","line":{"from":56,"to":65}} {"id":100007454,"name":"ToPrometheusType","signature":"func (r Result) ToPrometheusType() float64","file":"pkg/kubelet/prober/results/results_manager.go","code":"// ToPrometheusType translates a Result to a form which is better understood by prometheus.\nfunc (r Result) ToPrometheusType() float64 {\n\tswitch r {\n\tcase Success:\n\t\treturn 0\n\tcase Failure:\n\t\treturn 1\n\tdefault:\n\t\treturn -1\n\t}\n}","line":{"from":67,"to":77}} {"id":100007455,"name":"NewManager","signature":"func NewManager() Manager","file":"pkg/kubelet/prober/results/results_manager.go","code":"// NewManager creates and returns an empty results manager.\nfunc NewManager() Manager {\n\treturn \u0026manager{\n\t\tcache: make(map[kubecontainer.ContainerID]Result),\n\t\tupdates: make(chan Update, 20),\n\t}\n}","line":{"from":98,"to":104}} {"id":100007456,"name":"Get","signature":"func (m *manager) Get(id kubecontainer.ContainerID) (Result, bool)","file":"pkg/kubelet/prober/results/results_manager.go","code":"func (m *manager) Get(id kubecontainer.ContainerID) (Result, bool) {\n\tm.RLock()\n\tdefer m.RUnlock()\n\tresult, found := m.cache[id]\n\treturn result, found\n}","line":{"from":106,"to":111}} {"id":100007457,"name":"Set","signature":"func (m *manager) Set(id kubecontainer.ContainerID, result Result, pod *v1.Pod)","file":"pkg/kubelet/prober/results/results_manager.go","code":"func (m *manager) Set(id kubecontainer.ContainerID, result Result, pod *v1.Pod) {\n\tif m.setInternal(id, result) {\n\t\tm.updates \u003c- Update{id, result, pod.UID}\n\t}\n}","line":{"from":113,"to":117}} {"id":100007458,"name":"setInternal","signature":"func (m *manager) setInternal(id kubecontainer.ContainerID, result Result) bool","file":"pkg/kubelet/prober/results/results_manager.go","code":"// Internal helper for locked portion of set. Returns whether an update should be sent.\nfunc (m *manager) setInternal(id kubecontainer.ContainerID, result Result) bool {\n\tm.Lock()\n\tdefer m.Unlock()\n\tprev, exists := m.cache[id]\n\tif !exists || prev != result {\n\t\tm.cache[id] = result\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":119,"to":129}} {"id":100007459,"name":"Remove","signature":"func (m *manager) Remove(id kubecontainer.ContainerID)","file":"pkg/kubelet/prober/results/results_manager.go","code":"func (m *manager) Remove(id kubecontainer.ContainerID) {\n\tm.Lock()\n\tdefer m.Unlock()\n\tdelete(m.cache, id)\n}","line":{"from":131,"to":135}} {"id":100007460,"name":"Updates","signature":"func (m *manager) Updates() \u003c-chan Update","file":"pkg/kubelet/prober/results/results_manager.go","code":"func (m *manager) Updates() \u003c-chan Update {\n\treturn m.updates\n}","line":{"from":137,"to":139}} {"id":100007461,"name":"newWorker","signature":"func newWorker(","file":"pkg/kubelet/prober/worker.go","code":"// Creates and starts a new probe worker.\nfunc newWorker(\n\tm *manager,\n\tprobeType probeType,\n\tpod *v1.Pod,\n\tcontainer v1.Container) *worker {\n\n\tw := \u0026worker{\n\t\tstopCh: make(chan struct{}, 1), // Buffer so stop() can be non-blocking.\n\t\tmanualTriggerCh: make(chan struct{}, 1), // Buffer so prober_manager can do non-blocking calls to doProbe.\n\t\tpod: pod,\n\t\tcontainer: container,\n\t\tprobeType: probeType,\n\t\tprobeManager: m,\n\t}\n\n\tswitch probeType {\n\tcase readiness:\n\t\tw.spec = container.ReadinessProbe\n\t\tw.resultsManager = m.readinessManager\n\t\tw.initialValue = results.Failure\n\tcase liveness:\n\t\tw.spec = container.LivenessProbe\n\t\tw.resultsManager = m.livenessManager\n\t\tw.initialValue = results.Success\n\tcase startup:\n\t\tw.spec = container.StartupProbe\n\t\tw.resultsManager = m.startupManager\n\t\tw.initialValue = results.Unknown\n\t}\n\n\tpodName := getPodLabelName(w.pod)\n\n\tbasicMetricLabels := metrics.Labels{\n\t\t\"probe_type\": w.probeType.String(),\n\t\t\"container\": w.container.Name,\n\t\t\"pod\": podName,\n\t\t\"namespace\": w.pod.Namespace,\n\t\t\"pod_uid\": string(w.pod.UID),\n\t}\n\n\tproberDurationLabels := metrics.Labels{\n\t\t\"probe_type\": w.probeType.String(),\n\t\t\"container\": w.container.Name,\n\t\t\"pod\": podName,\n\t\t\"namespace\": w.pod.Namespace,\n\t}\n\n\tw.proberResultsSuccessfulMetricLabels = deepCopyPrometheusLabels(basicMetricLabels)\n\tw.proberResultsSuccessfulMetricLabels[\"result\"] = probeResultSuccessful\n\n\tw.proberResultsFailedMetricLabels = deepCopyPrometheusLabels(basicMetricLabels)\n\tw.proberResultsFailedMetricLabels[\"result\"] = probeResultFailed\n\n\tw.proberResultsUnknownMetricLabels = deepCopyPrometheusLabels(basicMetricLabels)\n\tw.proberResultsUnknownMetricLabels[\"result\"] = probeResultUnknown\n\n\tw.proberDurationSuccessfulMetricLabels = deepCopyPrometheusLabels(proberDurationLabels)\n\tw.proberDurationUnknownMetricLabels = deepCopyPrometheusLabels(proberDurationLabels)\n\n\treturn w\n}","line":{"from":87,"to":148}} {"id":100007462,"name":"run","signature":"func (w *worker) run()","file":"pkg/kubelet/prober/worker.go","code":"// run periodically probes the container.\nfunc (w *worker) run() {\n\tctx := context.Background()\n\tprobeTickerPeriod := time.Duration(w.spec.PeriodSeconds) * time.Second\n\n\t// If kubelet restarted the probes could be started in rapid succession.\n\t// Let the worker wait for a random portion of tickerPeriod before probing.\n\t// Do it only if the kubelet has started recently.\n\tif probeTickerPeriod \u003e time.Since(w.probeManager.start) {\n\t\ttime.Sleep(time.Duration(rand.Float64() * float64(probeTickerPeriod)))\n\t}\n\n\tprobeTicker := time.NewTicker(probeTickerPeriod)\n\n\tdefer func() {\n\t\t// Clean up.\n\t\tprobeTicker.Stop()\n\t\tif !w.containerID.IsEmpty() {\n\t\t\tw.resultsManager.Remove(w.containerID)\n\t\t}\n\n\t\tw.probeManager.removeWorker(w.pod.UID, w.container.Name, w.probeType)\n\t\tProberResults.Delete(w.proberResultsSuccessfulMetricLabels)\n\t\tProberResults.Delete(w.proberResultsFailedMetricLabels)\n\t\tProberResults.Delete(w.proberResultsUnknownMetricLabels)\n\t\tProberDuration.Delete(w.proberDurationSuccessfulMetricLabels)\n\t\tProberDuration.Delete(w.proberDurationUnknownMetricLabels)\n\t}()\n\nprobeLoop:\n\tfor w.doProbe(ctx) {\n\t\t// Wait for next probe tick.\n\t\tselect {\n\t\tcase \u003c-w.stopCh:\n\t\t\tbreak probeLoop\n\t\tcase \u003c-probeTicker.C:\n\t\tcase \u003c-w.manualTriggerCh:\n\t\t\t// continue\n\t\t}\n\t}\n}","line":{"from":150,"to":190}} {"id":100007463,"name":"stop","signature":"func (w *worker) stop()","file":"pkg/kubelet/prober/worker.go","code":"// stop stops the probe worker. The worker handles cleanup and removes itself from its manager.\n// It is safe to call stop multiple times.\nfunc (w *worker) stop() {\n\tselect {\n\tcase w.stopCh \u003c- struct{}{}:\n\tdefault: // Non-blocking.\n\t}\n}","line":{"from":192,"to":199}} {"id":100007464,"name":"doProbe","signature":"func (w *worker) doProbe(ctx context.Context) (keepGoing bool)","file":"pkg/kubelet/prober/worker.go","code":"// doProbe probes the container once and records the result.\n// Returns whether the worker should continue.\nfunc (w *worker) doProbe(ctx context.Context) (keepGoing bool) {\n\tdefer func() { recover() }() // Actually eat panics (HandleCrash takes care of logging)\n\tdefer runtime.HandleCrash(func(_ interface{}) { keepGoing = true })\n\n\tstartTime := time.Now()\n\tstatus, ok := w.probeManager.statusManager.GetPodStatus(w.pod.UID)\n\tif !ok {\n\t\t// Either the pod has not been created yet, or it was already deleted.\n\t\tklog.V(3).InfoS(\"No status for pod\", \"pod\", klog.KObj(w.pod))\n\t\treturn true\n\t}\n\n\t// Worker should terminate if pod is terminated.\n\tif status.Phase == v1.PodFailed || status.Phase == v1.PodSucceeded {\n\t\tklog.V(3).InfoS(\"Pod is terminated, exiting probe worker\",\n\t\t\t\"pod\", klog.KObj(w.pod), \"phase\", status.Phase)\n\t\treturn false\n\t}\n\n\tc, ok := podutil.GetContainerStatus(status.ContainerStatuses, w.container.Name)\n\tif !ok || len(c.ContainerID) == 0 {\n\t\t// Either the container has not been created yet, or it was deleted.\n\t\tklog.V(3).InfoS(\"Probe target container not found\",\n\t\t\t\"pod\", klog.KObj(w.pod), \"containerName\", w.container.Name)\n\t\treturn true // Wait for more information.\n\t}\n\n\tif w.containerID.String() != c.ContainerID {\n\t\tif !w.containerID.IsEmpty() {\n\t\t\tw.resultsManager.Remove(w.containerID)\n\t\t}\n\t\tw.containerID = kubecontainer.ParseContainerID(c.ContainerID)\n\t\tw.resultsManager.Set(w.containerID, w.initialValue, w.pod)\n\t\t// We've got a new container; resume probing.\n\t\tw.onHold = false\n\t}\n\n\tif w.onHold {\n\t\t// Worker is on hold until there is a new container.\n\t\treturn true\n\t}\n\n\tif c.State.Running == nil {\n\t\tklog.V(3).InfoS(\"Non-running container probed\",\n\t\t\t\"pod\", klog.KObj(w.pod), \"containerName\", w.container.Name)\n\t\tif !w.containerID.IsEmpty() {\n\t\t\tw.resultsManager.Set(w.containerID, results.Failure, w.pod)\n\t\t}\n\t\t// Abort if the container will not be restarted.\n\t\treturn c.State.Terminated == nil ||\n\t\t\tw.pod.Spec.RestartPolicy != v1.RestartPolicyNever\n\t}\n\n\t// Graceful shutdown of the pod.\n\tif w.pod.ObjectMeta.DeletionTimestamp != nil \u0026\u0026 (w.probeType == liveness || w.probeType == startup) {\n\t\tklog.V(3).InfoS(\"Pod deletion requested, setting probe result to success\",\n\t\t\t\"probeType\", w.probeType, \"pod\", klog.KObj(w.pod), \"containerName\", w.container.Name)\n\t\tif w.probeType == startup {\n\t\t\tklog.InfoS(\"Pod deletion requested before container has fully started\",\n\t\t\t\t\"pod\", klog.KObj(w.pod), \"containerName\", w.container.Name)\n\t\t}\n\t\t// Set a last result to ensure quiet shutdown.\n\t\tw.resultsManager.Set(w.containerID, results.Success, w.pod)\n\t\t// Stop probing at this point.\n\t\treturn false\n\t}\n\n\t// Probe disabled for InitialDelaySeconds.\n\tif int32(time.Since(c.State.Running.StartedAt.Time).Seconds()) \u003c w.spec.InitialDelaySeconds {\n\t\treturn true\n\t}\n\n\tif c.Started != nil \u0026\u0026 *c.Started {\n\t\t// Stop probing for startup once container has started.\n\t\t// we keep it running to make sure it will work for restarted container.\n\t\tif w.probeType == startup {\n\t\t\treturn true\n\t\t}\n\t} else {\n\t\t// Disable other probes until container has started.\n\t\tif w.probeType != startup {\n\t\t\treturn true\n\t\t}\n\t}\n\n\t// Note, exec probe does NOT have access to pod environment variables or downward API\n\tresult, err := w.probeManager.prober.probe(ctx, w.probeType, w.pod, status, w.container, w.containerID)\n\tif err != nil {\n\t\t// Prober error, throw away the result.\n\t\treturn true\n\t}\n\n\tswitch result {\n\tcase results.Success:\n\t\tProberResults.With(w.proberResultsSuccessfulMetricLabels).Inc()\n\t\tProberDuration.With(w.proberDurationSuccessfulMetricLabels).Observe(time.Since(startTime).Seconds())\n\tcase results.Failure:\n\t\tProberResults.With(w.proberResultsFailedMetricLabels).Inc()\n\tdefault:\n\t\tProberResults.With(w.proberResultsUnknownMetricLabels).Inc()\n\t\tProberDuration.With(w.proberDurationUnknownMetricLabels).Observe(time.Since(startTime).Seconds())\n\t}\n\n\tif w.lastResult == result {\n\t\tw.resultRun++\n\t} else {\n\t\tw.lastResult = result\n\t\tw.resultRun = 1\n\t}\n\n\tif (result == results.Failure \u0026\u0026 w.resultRun \u003c int(w.spec.FailureThreshold)) ||\n\t\t(result == results.Success \u0026\u0026 w.resultRun \u003c int(w.spec.SuccessThreshold)) {\n\t\t// Success or failure is below threshold - leave the probe state unchanged.\n\t\treturn true\n\t}\n\n\tw.resultsManager.Set(w.containerID, result, w.pod)\n\n\tif (w.probeType == liveness || w.probeType == startup) \u0026\u0026 result == results.Failure {\n\t\t// The container fails a liveness/startup check, it will need to be restarted.\n\t\t// Stop probing until we see a new container ID. This is to reduce the\n\t\t// chance of hitting #21751, where running `docker exec` when a\n\t\t// container is being stopped may lead to corrupted container state.\n\t\tw.onHold = true\n\t\tw.resultRun = 0\n\t}\n\n\treturn true\n}","line":{"from":201,"to":331}} {"id":100007465,"name":"deepCopyPrometheusLabels","signature":"func deepCopyPrometheusLabels(m metrics.Labels) metrics.Labels","file":"pkg/kubelet/prober/worker.go","code":"func deepCopyPrometheusLabels(m metrics.Labels) metrics.Labels {\n\tret := make(metrics.Labels, len(m))\n\tfor k, v := range m {\n\t\tret[k] = v\n\t}\n\treturn ret\n}","line":{"from":333,"to":339}} {"id":100007466,"name":"getPodLabelName","signature":"func getPodLabelName(pod *v1.Pod) string","file":"pkg/kubelet/prober/worker.go","code":"func getPodLabelName(pod *v1.Pod) string {\n\tpodName := pod.Name\n\tif pod.GenerateName != \"\" {\n\t\tpodNameSlice := strings.Split(pod.Name, \"-\")\n\t\tpodName = strings.Join(podNameSlice[:len(podNameSlice)-1], \"-\")\n\t\tif label, ok := pod.GetLabels()[apps.DefaultDeploymentUniqueLabelKey]; ok {\n\t\t\tpodName = strings.ReplaceAll(podName, fmt.Sprintf(\"-%s\", label), \"\")\n\t\t}\n\t}\n\treturn podName\n}","line":{"from":341,"to":351}} {"id":100007467,"name":"GetContainerOOMScoreAdjust","signature":"func GetContainerOOMScoreAdjust(pod *v1.Pod, container *v1.Container, memoryCapacity int64) int","file":"pkg/kubelet/qos/policy.go","code":"// GetContainerOOMScoreAdjust returns the amount by which the OOM score of all processes in the\n// container should be adjusted.\n// The OOM score of a process is the percentage of memory it consumes\n// multiplied by 10 (barring exceptional cases) + a configurable quantity which is between -1000\n// and 1000. Containers with higher OOM scores are killed if the system runs out of memory.\n// See https://lwn.net/Articles/391222/ for more information.\nfunc GetContainerOOMScoreAdjust(pod *v1.Pod, container *v1.Container, memoryCapacity int64) int {\n\tif types.IsNodeCriticalPod(pod) {\n\t\t// Only node critical pod should be the last to get killed.\n\t\treturn guaranteedOOMScoreAdj\n\t}\n\n\tswitch v1qos.GetPodQOS(pod) {\n\tcase v1.PodQOSGuaranteed:\n\t\t// Guaranteed containers should be the last to get killed.\n\t\treturn guaranteedOOMScoreAdj\n\tcase v1.PodQOSBestEffort:\n\t\treturn besteffortOOMScoreAdj\n\t}\n\n\t// Burstable containers are a middle tier, between Guaranteed and Best-Effort. Ideally,\n\t// we want to protect Burstable containers that consume less memory than requested.\n\t// The formula below is a heuristic. A container requesting for 10% of a system's\n\t// memory will have an OOM score adjust of 900. If a process in container Y\n\t// uses over 10% of memory, its OOM score will be 1000. The idea is that containers\n\t// which use more than their request will have an OOM score of 1000 and will be prime\n\t// targets for OOM kills.\n\t// Note that this is a heuristic, it won't work if a container has many small processes.\n\tmemoryRequest := container.Resources.Requests.Memory().Value()\n\tif utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) {\n\t\tif cs, ok := podutil.GetContainerStatus(pod.Status.ContainerStatuses, container.Name); ok {\n\t\t\tmemoryRequest = cs.AllocatedResources.Memory().Value()\n\t\t}\n\t}\n\toomScoreAdjust := 1000 - (1000*memoryRequest)/memoryCapacity\n\t// A guaranteed pod using 100% of memory can have an OOM score of 10. Ensure\n\t// that burstable pods have a higher OOM score adjustment.\n\tif int(oomScoreAdjust) \u003c (1000 + guaranteedOOMScoreAdj) {\n\t\treturn (1000 + guaranteedOOMScoreAdj)\n\t}\n\t// Give burstable pods a higher chance of survival over besteffort pods.\n\tif int(oomScoreAdjust) == besteffortOOMScoreAdj {\n\t\treturn int(oomScoreAdjust - 1)\n\t}\n\treturn int(oomScoreAdjust)\n}","line":{"from":37,"to":82}} {"id":100007468,"name":"NewReasonCache","signature":"func NewReasonCache() *ReasonCache","file":"pkg/kubelet/reason_cache.go","code":"// NewReasonCache creates an instance of 'ReasonCache'.\nfunc NewReasonCache() *ReasonCache {\n\treturn \u0026ReasonCache{cache: lru.New(maxReasonCacheEntries)}\n}","line":{"from":55,"to":58}} {"id":100007469,"name":"composeKey","signature":"func (c *ReasonCache) composeKey(uid types.UID, name string) string","file":"pkg/kubelet/reason_cache.go","code":"func (c *ReasonCache) composeKey(uid types.UID, name string) string {\n\treturn fmt.Sprintf(\"%s_%s\", uid, name)\n}","line":{"from":60,"to":62}} {"id":100007470,"name":"add","signature":"func (c *ReasonCache) add(uid types.UID, name string, reason error, message string)","file":"pkg/kubelet/reason_cache.go","code":"// add adds error reason into the cache\nfunc (c *ReasonCache) add(uid types.UID, name string, reason error, message string) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tc.cache.Add(c.composeKey(uid, name), ReasonItem{reason, message})\n}","line":{"from":64,"to":69}} {"id":100007471,"name":"Update","signature":"func (c *ReasonCache) Update(uid types.UID, result kubecontainer.PodSyncResult)","file":"pkg/kubelet/reason_cache.go","code":"// Update updates the reason cache with the SyncPodResult. Only SyncResult with\n// StartContainer action will change the cache.\nfunc (c *ReasonCache) Update(uid types.UID, result kubecontainer.PodSyncResult) {\n\tfor _, r := range result.SyncResults {\n\t\tif r.Action != kubecontainer.StartContainer {\n\t\t\tcontinue\n\t\t}\n\t\tname := r.Target.(string)\n\t\tif r.Error != nil {\n\t\t\tc.add(uid, name, r.Error, r.Message)\n\t\t} else {\n\t\t\tc.Remove(uid, name)\n\t\t}\n\t}\n}","line":{"from":71,"to":85}} {"id":100007472,"name":"Remove","signature":"func (c *ReasonCache) Remove(uid types.UID, name string)","file":"pkg/kubelet/reason_cache.go","code":"// Remove removes error reason from the cache\nfunc (c *ReasonCache) Remove(uid types.UID, name string) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tc.cache.Remove(c.composeKey(uid, name))\n}","line":{"from":87,"to":92}} {"id":100007473,"name":"Get","signature":"func (c *ReasonCache) Get(uid types.UID, name string) (*ReasonItem, bool)","file":"pkg/kubelet/reason_cache.go","code":"// Get gets error reason from the cache. The return values are error reason, error message and\n// whether an error reason is found in the cache. If no error reason is found, empty string will\n// be returned for error reason and error message.\nfunc (c *ReasonCache) Get(uid types.UID, name string) (*ReasonItem, bool) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tvalue, ok := c.cache.Get(c.composeKey(uid, name))\n\tif !ok {\n\t\treturn nil, false\n\t}\n\tinfo := value.(ReasonItem)\n\treturn \u0026info, true\n}","line":{"from":94,"to":106}} {"id":100007474,"name":"RunOnce","signature":"func (kl *Kubelet) RunOnce(updates \u003c-chan kubetypes.PodUpdate) ([]RunPodResult, error)","file":"pkg/kubelet/runonce.go","code":"// RunOnce polls from one configuration update and run the associated pods.\nfunc (kl *Kubelet) RunOnce(updates \u003c-chan kubetypes.PodUpdate) ([]RunPodResult, error) {\n\tctx := context.Background()\n\t// Setup filesystem directories.\n\tif err := kl.setupDataDirs(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// If the container logs directory does not exist, create it.\n\tif _, err := os.Stat(ContainerLogsDir); err != nil {\n\t\tif err := kl.os.MkdirAll(ContainerLogsDir, 0755); err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to create directory\", \"path\", ContainerLogsDir)\n\t\t}\n\t}\n\n\tselect {\n\tcase u := \u003c-updates:\n\t\tklog.InfoS(\"Processing manifest with pods\", \"numPods\", len(u.Pods))\n\t\tresult, err := kl.runOnce(ctx, u.Pods, runOnceRetryDelay)\n\t\tklog.InfoS(\"Finished processing pods\", \"numPods\", len(u.Pods))\n\t\treturn result, err\n\tcase \u003c-time.After(runOnceManifestDelay):\n\t\treturn nil, fmt.Errorf(\"no pod manifest update after %v\", runOnceManifestDelay)\n\t}\n}","line":{"from":45,"to":69}} {"id":100007475,"name":"runOnce","signature":"func (kl *Kubelet) runOnce(ctx context.Context, pods []*v1.Pod, retryDelay time.Duration) (results []RunPodResult, err error)","file":"pkg/kubelet/runonce.go","code":"// runOnce runs a given set of pods and returns their status.\nfunc (kl *Kubelet) runOnce(ctx context.Context, pods []*v1.Pod, retryDelay time.Duration) (results []RunPodResult, err error) {\n\tch := make(chan RunPodResult)\n\tadmitted := []*v1.Pod{}\n\tfor _, pod := range pods {\n\t\t// Check if we can admit the pod.\n\t\tif ok, reason, message := kl.canAdmitPod(admitted, pod); !ok {\n\t\t\tkl.rejectPod(pod, reason, message)\n\t\t\tresults = append(results, RunPodResult{pod, nil})\n\t\t\tcontinue\n\t\t}\n\n\t\tadmitted = append(admitted, pod)\n\t\tgo func(pod *v1.Pod) {\n\t\t\terr := kl.runPod(ctx, pod, retryDelay)\n\t\t\tch \u003c- RunPodResult{pod, err}\n\t\t}(pod)\n\t}\n\n\tklog.InfoS(\"Waiting for pods\", \"numPods\", len(admitted))\n\tfailedPods := []string{}\n\tfor i := 0; i \u003c len(admitted); i++ {\n\t\tres := \u003c-ch\n\t\tresults = append(results, res)\n\t\tif res.Err != nil {\n\t\t\tfailedContainerName, err := kl.getFailedContainers(ctx, res.Pod)\n\t\t\tif err != nil {\n\t\t\t\tklog.InfoS(\"Unable to get failed containers' names for pod\", \"pod\", klog.KObj(res.Pod), \"err\", err)\n\t\t\t} else {\n\t\t\t\tklog.InfoS(\"Unable to start pod because container failed\", \"pod\", klog.KObj(res.Pod), \"containerName\", failedContainerName)\n\t\t\t}\n\t\t\tfailedPods = append(failedPods, format.Pod(res.Pod))\n\t\t} else {\n\t\t\tklog.InfoS(\"Started pod\", \"pod\", klog.KObj(res.Pod))\n\t\t}\n\t}\n\tif len(failedPods) \u003e 0 {\n\t\treturn results, fmt.Errorf(\"error running pods: %v\", failedPods)\n\t}\n\tklog.InfoS(\"Pods started\", \"numPods\", len(pods))\n\treturn results, err\n}","line":{"from":71,"to":112}} {"id":100007476,"name":"runPod","signature":"func (kl *Kubelet) runPod(ctx context.Context, pod *v1.Pod, retryDelay time.Duration) error","file":"pkg/kubelet/runonce.go","code":"// runPod runs a single pod and wait until all containers are running.\nfunc (kl *Kubelet) runPod(ctx context.Context, pod *v1.Pod, retryDelay time.Duration) error {\n\tvar isTerminal bool\n\tdelay := retryDelay\n\tretry := 0\n\tfor !isTerminal {\n\t\tstatus, err := kl.containerRuntime.GetPodStatus(ctx, pod.UID, pod.Name, pod.Namespace)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to get status for pod %q: %v\", format.Pod(pod), err)\n\t\t}\n\n\t\tif kl.isPodRunning(pod, status) {\n\t\t\tklog.InfoS(\"Pod's containers running\", \"pod\", klog.KObj(pod))\n\t\t\treturn nil\n\t\t}\n\t\tklog.InfoS(\"Pod's containers not running: syncing\", \"pod\", klog.KObj(pod))\n\n\t\tklog.InfoS(\"Creating a mirror pod for static pod\", \"pod\", klog.KObj(pod))\n\t\tif err := kl.podManager.CreateMirrorPod(pod); err != nil {\n\t\t\tklog.ErrorS(err, \"Failed creating a mirror pod\", \"pod\", klog.KObj(pod))\n\t\t}\n\t\tmirrorPod, _ := kl.podManager.GetMirrorPodByPod(pod)\n\t\tif isTerminal, err = kl.SyncPod(ctx, kubetypes.SyncPodUpdate, pod, mirrorPod, status); err != nil {\n\t\t\treturn fmt.Errorf(\"error syncing pod %q: %v\", format.Pod(pod), err)\n\t\t}\n\t\tif retry \u003e= runOnceMaxRetries {\n\t\t\treturn fmt.Errorf(\"timeout error: pod %q containers not running after %d retries\", format.Pod(pod), runOnceMaxRetries)\n\t\t}\n\t\t// TODO(proppy): health checking would be better than waiting + checking the state at the next iteration.\n\t\tklog.InfoS(\"Pod's containers synced, waiting\", \"pod\", klog.KObj(pod), \"duration\", delay)\n\t\ttime.Sleep(delay)\n\t\tretry++\n\t\tdelay *= runOnceRetryDelayBackoff\n\t}\n\treturn nil\n}","line":{"from":114,"to":149}} {"id":100007477,"name":"isPodRunning","signature":"func (kl *Kubelet) isPodRunning(pod *v1.Pod, status *kubecontainer.PodStatus) bool","file":"pkg/kubelet/runonce.go","code":"// isPodRunning returns true if all containers of a manifest are running.\nfunc (kl *Kubelet) isPodRunning(pod *v1.Pod, status *kubecontainer.PodStatus) bool {\n\tfor _, c := range pod.Spec.Containers {\n\t\tcs := status.FindContainerStatusByName(c.Name)\n\t\tif cs == nil || cs.State != kubecontainer.ContainerStateRunning {\n\t\t\tklog.InfoS(\"Container not running\", \"pod\", klog.KObj(pod), \"containerName\", c.Name)\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":151,"to":161}} {"id":100007478,"name":"getFailedContainers","signature":"func (kl *Kubelet) getFailedContainers(ctx context.Context, pod *v1.Pod) ([]string, error)","file":"pkg/kubelet/runonce.go","code":"// getFailedContainer returns failed container name for pod.\nfunc (kl *Kubelet) getFailedContainers(ctx context.Context, pod *v1.Pod) ([]string, error) {\n\tstatus, err := kl.containerRuntime.GetPodStatus(ctx, pod.UID, pod.Name, pod.Namespace)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to get status for pod %q: %v\", format.Pod(pod), err)\n\t}\n\tvar containerNames []string\n\tfor _, cs := range status.ContainerStatuses {\n\t\tif cs.State != kubecontainer.ContainerStateRunning \u0026\u0026 cs.ExitCode != 0 {\n\t\t\tcontainerNames = append(containerNames, cs.Name)\n\t\t}\n\t}\n\treturn containerNames, nil\n}","line":{"from":163,"to":176}} {"id":100007479,"name":"addHealthCheck","signature":"func (s *runtimeState) addHealthCheck(name string, f healthCheckFnType)","file":"pkg/kubelet/runtime.go","code":"func (s *runtimeState) addHealthCheck(name string, f healthCheckFnType) {\n\ts.Lock()\n\tdefer s.Unlock()\n\ts.healthChecks = append(s.healthChecks, \u0026healthCheck{name: name, fn: f})\n}","line":{"from":48,"to":52}} {"id":100007480,"name":"setRuntimeSync","signature":"func (s *runtimeState) setRuntimeSync(t time.Time)","file":"pkg/kubelet/runtime.go","code":"func (s *runtimeState) setRuntimeSync(t time.Time) {\n\ts.Lock()\n\tdefer s.Unlock()\n\ts.lastBaseRuntimeSync = t\n}","line":{"from":54,"to":58}} {"id":100007481,"name":"setNetworkState","signature":"func (s *runtimeState) setNetworkState(err error)","file":"pkg/kubelet/runtime.go","code":"func (s *runtimeState) setNetworkState(err error) {\n\ts.Lock()\n\tdefer s.Unlock()\n\ts.networkError = err\n}","line":{"from":60,"to":64}} {"id":100007482,"name":"setRuntimeState","signature":"func (s *runtimeState) setRuntimeState(err error)","file":"pkg/kubelet/runtime.go","code":"func (s *runtimeState) setRuntimeState(err error) {\n\ts.Lock()\n\tdefer s.Unlock()\n\ts.runtimeError = err\n}","line":{"from":66,"to":70}} {"id":100007483,"name":"setStorageState","signature":"func (s *runtimeState) setStorageState(err error)","file":"pkg/kubelet/runtime.go","code":"func (s *runtimeState) setStorageState(err error) {\n\ts.Lock()\n\tdefer s.Unlock()\n\ts.storageError = err\n}","line":{"from":72,"to":76}} {"id":100007484,"name":"setPodCIDR","signature":"func (s *runtimeState) setPodCIDR(cidr string)","file":"pkg/kubelet/runtime.go","code":"func (s *runtimeState) setPodCIDR(cidr string) {\n\ts.Lock()\n\tdefer s.Unlock()\n\ts.cidr = cidr\n}","line":{"from":78,"to":82}} {"id":100007485,"name":"podCIDR","signature":"func (s *runtimeState) podCIDR() string","file":"pkg/kubelet/runtime.go","code":"func (s *runtimeState) podCIDR() string {\n\ts.RLock()\n\tdefer s.RUnlock()\n\treturn s.cidr\n}","line":{"from":84,"to":88}} {"id":100007486,"name":"runtimeErrors","signature":"func (s *runtimeState) runtimeErrors() error","file":"pkg/kubelet/runtime.go","code":"func (s *runtimeState) runtimeErrors() error {\n\ts.RLock()\n\tdefer s.RUnlock()\n\terrs := []error{}\n\tif s.lastBaseRuntimeSync.IsZero() {\n\t\terrs = append(errs, errors.New(\"container runtime status check may not have completed yet\"))\n\t} else if !s.lastBaseRuntimeSync.Add(s.baseRuntimeSyncThreshold).After(time.Now()) {\n\t\terrs = append(errs, errors.New(\"container runtime is down\"))\n\t}\n\tfor _, hc := range s.healthChecks {\n\t\tif ok, err := hc.fn(); !ok {\n\t\t\terrs = append(errs, fmt.Errorf(\"%s is not healthy: %v\", hc.name, err))\n\t\t}\n\t}\n\tif s.runtimeError != nil {\n\t\terrs = append(errs, s.runtimeError)\n\t}\n\n\treturn utilerrors.NewAggregate(errs)\n}","line":{"from":90,"to":109}} {"id":100007487,"name":"networkErrors","signature":"func (s *runtimeState) networkErrors() error","file":"pkg/kubelet/runtime.go","code":"func (s *runtimeState) networkErrors() error {\n\ts.RLock()\n\tdefer s.RUnlock()\n\terrs := []error{}\n\tif s.networkError != nil {\n\t\terrs = append(errs, s.networkError)\n\t}\n\treturn utilerrors.NewAggregate(errs)\n}","line":{"from":111,"to":119}} {"id":100007488,"name":"storageErrors","signature":"func (s *runtimeState) storageErrors() error","file":"pkg/kubelet/runtime.go","code":"func (s *runtimeState) storageErrors() error {\n\ts.RLock()\n\tdefer s.RUnlock()\n\terrs := []error{}\n\tif s.storageError != nil {\n\t\terrs = append(errs, s.storageError)\n\t}\n\treturn utilerrors.NewAggregate(errs)\n}","line":{"from":121,"to":129}} {"id":100007489,"name":"newRuntimeState","signature":"func newRuntimeState(runtimeSyncThreshold time.Duration) *runtimeState","file":"pkg/kubelet/runtime.go","code":"func newRuntimeState(runtimeSyncThreshold time.Duration) *runtimeState {\n\treturn \u0026runtimeState{\n\t\tlastBaseRuntimeSync: time.Time{},\n\t\tbaseRuntimeSyncThreshold: runtimeSyncThreshold,\n\t\tnetworkError: ErrNetworkUnknown,\n\t}\n}","line":{"from":131,"to":137}} {"id":100007490,"name":"NewManager","signature":"func NewManager(client clientset.Interface) *Manager","file":"pkg/kubelet/runtimeclass/runtimeclass_manager.go","code":"// NewManager returns a new RuntimeClass Manager. Run must be called before the manager can be used.\nfunc NewManager(client clientset.Interface) *Manager {\n\tconst resyncPeriod = 0\n\n\tfactory := informers.NewSharedInformerFactory(client, resyncPeriod)\n\tlister := factory.Node().V1().RuntimeClasses().Lister()\n\n\treturn \u0026Manager{\n\t\tinformerFactory: factory,\n\t\tlister: lister,\n\t}\n}","line":{"from":34,"to":45}} {"id":100007491,"name":"Start","signature":"func (m *Manager) Start(stopCh \u003c-chan struct{})","file":"pkg/kubelet/runtimeclass/runtimeclass_manager.go","code":"// Start starts syncing the RuntimeClass cache with the apiserver.\nfunc (m *Manager) Start(stopCh \u003c-chan struct{}) {\n\tm.informerFactory.Start(stopCh)\n}","line":{"from":47,"to":50}} {"id":100007492,"name":"WaitForCacheSync","signature":"func (m *Manager) WaitForCacheSync(stopCh \u003c-chan struct{})","file":"pkg/kubelet/runtimeclass/runtimeclass_manager.go","code":"// WaitForCacheSync exposes the WaitForCacheSync method on the informer factory for testing\n// purposes.\nfunc (m *Manager) WaitForCacheSync(stopCh \u003c-chan struct{}) {\n\tm.informerFactory.WaitForCacheSync(stopCh)\n}","line":{"from":52,"to":56}} {"id":100007493,"name":"LookupRuntimeHandler","signature":"func (m *Manager) LookupRuntimeHandler(runtimeClassName *string) (string, error)","file":"pkg/kubelet/runtimeclass/runtimeclass_manager.go","code":"// LookupRuntimeHandler returns the RuntimeHandler string associated with the given RuntimeClass\n// name (or the default of \"\" for nil). If the RuntimeClass is not found, it returns an\n// errors.NotFound error.\nfunc (m *Manager) LookupRuntimeHandler(runtimeClassName *string) (string, error) {\n\tif runtimeClassName == nil || *runtimeClassName == \"\" {\n\t\t// The default RuntimeClass always resolves to the empty runtime handler.\n\t\treturn \"\", nil\n\t}\n\n\tname := *runtimeClassName\n\n\trc, err := m.lister.Get(name)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn \"\", fmt.Errorf(\"failed to lookup RuntimeClass %s: %v\", name, err)\n\t}\n\n\treturn rc.Handler, nil\n}","line":{"from":58,"to":78}} {"id":100007494,"name":"NewSimpleSecretManager","signature":"func NewSimpleSecretManager(kubeClient clientset.Interface) Manager","file":"pkg/kubelet/secret/secret_manager.go","code":"// NewSimpleSecretManager creates a new SecretManager instance.\nfunc NewSimpleSecretManager(kubeClient clientset.Interface) Manager {\n\treturn \u0026simpleSecretManager{kubeClient: kubeClient}\n}","line":{"from":60,"to":63}} {"id":100007495,"name":"GetSecret","signature":"func (s *simpleSecretManager) GetSecret(namespace, name string) (*v1.Secret, error)","file":"pkg/kubelet/secret/secret_manager.go","code":"func (s *simpleSecretManager) GetSecret(namespace, name string) (*v1.Secret, error) {\n\treturn s.kubeClient.CoreV1().Secrets(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n}","line":{"from":65,"to":67}} {"id":100007496,"name":"RegisterPod","signature":"func (s *simpleSecretManager) RegisterPod(pod *v1.Pod)","file":"pkg/kubelet/secret/secret_manager.go","code":"func (s *simpleSecretManager) RegisterPod(pod *v1.Pod) {\n}","line":{"from":69,"to":70}} {"id":100007497,"name":"UnregisterPod","signature":"func (s *simpleSecretManager) UnregisterPod(pod *v1.Pod)","file":"pkg/kubelet/secret/secret_manager.go","code":"func (s *simpleSecretManager) UnregisterPod(pod *v1.Pod) {\n}","line":{"from":72,"to":73}} {"id":100007498,"name":"GetSecret","signature":"func (s *secretManager) GetSecret(namespace, name string) (*v1.Secret, error)","file":"pkg/kubelet/secret/secret_manager.go","code":"func (s *secretManager) GetSecret(namespace, name string) (*v1.Secret, error) {\n\tobject, err := s.manager.GetObject(namespace, name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif secret, ok := object.(*v1.Secret); ok {\n\t\treturn secret, nil\n\t}\n\treturn nil, fmt.Errorf(\"unexpected object type: %v\", object)\n}","line":{"from":83,"to":92}} {"id":100007499,"name":"RegisterPod","signature":"func (s *secretManager) RegisterPod(pod *v1.Pod)","file":"pkg/kubelet/secret/secret_manager.go","code":"func (s *secretManager) RegisterPod(pod *v1.Pod) {\n\ts.manager.RegisterPod(pod)\n}","line":{"from":94,"to":96}} {"id":100007500,"name":"UnregisterPod","signature":"func (s *secretManager) UnregisterPod(pod *v1.Pod)","file":"pkg/kubelet/secret/secret_manager.go","code":"func (s *secretManager) UnregisterPod(pod *v1.Pod) {\n\ts.manager.UnregisterPod(pod)\n}","line":{"from":98,"to":100}} {"id":100007501,"name":"getSecretNames","signature":"func getSecretNames(pod *v1.Pod) sets.String","file":"pkg/kubelet/secret/secret_manager.go","code":"func getSecretNames(pod *v1.Pod) sets.String {\n\tresult := sets.NewString()\n\tpodutil.VisitPodSecretNames(pod, func(name string) bool {\n\t\tresult.Insert(name)\n\t\treturn true\n\t})\n\treturn result\n}","line":{"from":102,"to":109}} {"id":100007502,"name":"NewCachingSecretManager","signature":"func NewCachingSecretManager(kubeClient clientset.Interface, getTTL manager.GetObjectTTLFunc) Manager","file":"pkg/kubelet/secret/secret_manager.go","code":"// NewCachingSecretManager creates a manager that keeps a cache of all secrets\n// necessary for registered pods.\n// It implements the following logic:\n// - whenever a pod is created or updated, the cached versions of all secrets\n// are invalidated\n// - every GetObject() call tries to fetch the value from local cache; if it is\n// not there, invalidated or too old, we fetch it from apiserver and refresh the\n// value in cache; otherwise it is just fetched from cache\nfunc NewCachingSecretManager(kubeClient clientset.Interface, getTTL manager.GetObjectTTLFunc) Manager {\n\tgetSecret := func(namespace, name string, opts metav1.GetOptions) (runtime.Object, error) {\n\t\treturn kubeClient.CoreV1().Secrets(namespace).Get(context.TODO(), name, opts)\n\t}\n\tsecretStore := manager.NewObjectStore(getSecret, clock.RealClock{}, getTTL, defaultTTL)\n\treturn \u0026secretManager{\n\t\tmanager: manager.NewCacheBasedManager(secretStore, getSecretNames),\n\t}\n}","line":{"from":115,"to":131}} {"id":100007503,"name":"NewWatchingSecretManager","signature":"func NewWatchingSecretManager(kubeClient clientset.Interface, resyncInterval time.Duration) Manager","file":"pkg/kubelet/secret/secret_manager.go","code":"// NewWatchingSecretManager creates a manager that keeps a cache of all secrets\n// necessary for registered pods.\n// It implements the following logic:\n// - whenever a pod is created or updated, we start individual watches for all\n// referenced objects that aren't referenced from other registered pods\n// - every GetObject() returns a value from local cache propagated via watches\nfunc NewWatchingSecretManager(kubeClient clientset.Interface, resyncInterval time.Duration) Manager {\n\tlistSecret := func(namespace string, opts metav1.ListOptions) (runtime.Object, error) {\n\t\treturn kubeClient.CoreV1().Secrets(namespace).List(context.TODO(), opts)\n\t}\n\twatchSecret := func(namespace string, opts metav1.ListOptions) (watch.Interface, error) {\n\t\treturn kubeClient.CoreV1().Secrets(namespace).Watch(context.TODO(), opts)\n\t}\n\tnewSecret := func() runtime.Object {\n\t\treturn \u0026v1.Secret{}\n\t}\n\tisImmutable := func(object runtime.Object) bool {\n\t\tif secret, ok := object.(*v1.Secret); ok {\n\t\t\treturn secret.Immutable != nil \u0026\u0026 *secret.Immutable\n\t\t}\n\t\treturn false\n\t}\n\tgr := corev1.Resource(\"secret\")\n\treturn \u0026secretManager{\n\t\tmanager: manager.NewWatchBasedManager(listSecret, watchSecret, newSecret, isImmutable, gr, resyncInterval, getSecretNames),\n\t}\n}","line":{"from":133,"to":159}} {"id":100007504,"name":"NewKubeletAuth","signature":"func NewKubeletAuth(authenticator authenticator.Request, authorizerAttributeGetter authorizer.RequestAttributesGetter, authorizer authorizer.Authorizer) AuthInterface","file":"pkg/kubelet/server/auth.go","code":"// NewKubeletAuth returns a kubelet.AuthInterface composed of the given authenticator, attribute getter, and authorizer\nfunc NewKubeletAuth(authenticator authenticator.Request, authorizerAttributeGetter authorizer.RequestAttributesGetter, authorizer authorizer.Authorizer) AuthInterface {\n\treturn \u0026KubeletAuth{authenticator, authorizerAttributeGetter, authorizer}\n}","line":{"from":40,"to":43}} {"id":100007505,"name":"NewNodeAuthorizerAttributesGetter","signature":"func NewNodeAuthorizerAttributesGetter(nodeName types.NodeName) authorizer.RequestAttributesGetter","file":"pkg/kubelet/server/auth.go","code":"// NewNodeAuthorizerAttributesGetter creates a new authorizer.RequestAttributesGetter for the node.\nfunc NewNodeAuthorizerAttributesGetter(nodeName types.NodeName) authorizer.RequestAttributesGetter {\n\treturn nodeAuthorizerAttributesGetter{nodeName: nodeName}\n}","line":{"from":45,"to":48}} {"id":100007506,"name":"isSubpath","signature":"func isSubpath(subpath, path string) bool","file":"pkg/kubelet/server/auth.go","code":"func isSubpath(subpath, path string) bool {\n\tpath = strings.TrimSuffix(path, \"/\")\n\treturn subpath == path || (strings.HasPrefix(subpath, path) \u0026\u0026 subpath[len(path)] == '/')\n}","line":{"from":54,"to":57}} {"id":100007507,"name":"GetRequestAttributes","signature":"func (n nodeAuthorizerAttributesGetter) GetRequestAttributes(u user.Info, r *http.Request) authorizer.Attributes","file":"pkg/kubelet/server/auth.go","code":"// GetRequestAttributes populates authorizer attributes for the requests to the kubelet API.\n// Default attributes are: {apiVersion=v1,verb=\u003chttp verb from request\u003e,resource=nodes,name=\u003cnode name\u003e,subresource=proxy}\n// More specific verb/resource is set for the following request patterns:\n//\n//\t/stats/* =\u003e verb=\u003capi verb from request\u003e, resource=nodes, name=\u003cnode name\u003e, subresource=stats\n//\t/metrics/* =\u003e verb=\u003capi verb from request\u003e, resource=nodes, name=\u003cnode name\u003e, subresource=metrics\n//\t/logs/* =\u003e verb=\u003capi verb from request\u003e, resource=nodes, name=\u003cnode name\u003e, subresource=log\nfunc (n nodeAuthorizerAttributesGetter) GetRequestAttributes(u user.Info, r *http.Request) authorizer.Attributes {\n\n\tapiVerb := \"\"\n\tswitch r.Method {\n\tcase \"POST\":\n\t\tapiVerb = \"create\"\n\tcase \"GET\":\n\t\tapiVerb = \"get\"\n\tcase \"PUT\":\n\t\tapiVerb = \"update\"\n\tcase \"PATCH\":\n\t\tapiVerb = \"patch\"\n\tcase \"DELETE\":\n\t\tapiVerb = \"delete\"\n\t}\n\n\trequestPath := r.URL.Path\n\n\t// Default attributes mirror the API attributes that would allow this access to the kubelet API\n\tattrs := authorizer.AttributesRecord{\n\t\tUser: u,\n\t\tVerb: apiVerb,\n\t\tNamespace: \"\",\n\t\tAPIGroup: \"\",\n\t\tAPIVersion: \"v1\",\n\t\tResource: \"nodes\",\n\t\tSubresource: \"proxy\",\n\t\tName: string(n.nodeName),\n\t\tResourceRequest: true,\n\t\tPath: requestPath,\n\t}\n\n\t// Override subresource for specific paths\n\t// This allows subdividing access to the kubelet API\n\tswitch {\n\tcase isSubpath(requestPath, statsPath):\n\t\tattrs.Subresource = \"stats\"\n\tcase isSubpath(requestPath, metricsPath):\n\t\tattrs.Subresource = \"metrics\"\n\tcase isSubpath(requestPath, logsPath):\n\t\t// \"log\" to match other log subresources (pods/log, etc)\n\t\tattrs.Subresource = \"log\"\n\t}\n\n\tklog.V(5).InfoS(\"Node request attributes\", \"user\", attrs.GetUser().GetName(), \"verb\", attrs.GetVerb(), \"resource\", attrs.GetResource(), \"subresource\", attrs.GetSubresource())\n\n\treturn attrs\n}","line":{"from":59,"to":113}} {"id":100007508,"name":"Register","signature":"func Register()","file":"pkg/kubelet/server/metrics/metrics.go","code":"// Register all metrics.\nfunc Register() {\n\tregisterMetrics.Do(func() {\n\t\tlegacyregistry.MustRegister(HTTPRequests)\n\t\tlegacyregistry.MustRegister(HTTPRequestsDuration)\n\t\tlegacyregistry.MustRegister(HTTPInflightRequests)\n\t\tlegacyregistry.MustRegister(VolumeStatCalDuration)\n\t})\n}","line":{"from":83,"to":91}} {"id":100007509,"name":"SinceInSeconds","signature":"func SinceInSeconds(start time.Time) float64","file":"pkg/kubelet/server/metrics/metrics.go","code":"// SinceInSeconds gets the time since the specified start in seconds.\nfunc SinceInSeconds(start time.Time) float64 {\n\treturn time.Since(start).Seconds()\n}","line":{"from":93,"to":96}} {"id":100007510,"name":"CollectVolumeStatCalDuration","signature":"func CollectVolumeStatCalDuration(metricSource string, start time.Time)","file":"pkg/kubelet/server/metrics/metrics.go","code":"// CollectVolumeStatCalDuration collects the duration in seconds to calculate volume stats.\nfunc CollectVolumeStatCalDuration(metricSource string, start time.Time) {\n\tVolumeStatCalDuration.WithLabelValues(metricSource).Observe(SinceInSeconds(start))\n}","line":{"from":98,"to":101}} {"id":100007511,"name":"init","signature":"func init()","file":"pkg/kubelet/server/server.go","code":"func init() {\n\tutilruntime.Must(metricsfeatures.AddFeatureGates(utilfeature.DefaultMutableFeatureGate))\n}","line":{"from":90,"to":92}} {"id":100007512,"name":"Handle","signature":"func (a *filteringContainer) Handle(path string, handler http.Handler)","file":"pkg/kubelet/server/server.go","code":"func (a *filteringContainer) Handle(path string, handler http.Handler) {\n\ta.HandleWithFilter(path, handler)\n\ta.registeredHandlePaths = append(a.registeredHandlePaths, path)\n}","line":{"from":143,"to":146}} {"id":100007513,"name":"RegisteredHandlePaths","signature":"func (a *filteringContainer) RegisteredHandlePaths() []string","file":"pkg/kubelet/server/server.go","code":"func (a *filteringContainer) RegisteredHandlePaths() []string {\n\treturn a.registeredHandlePaths\n}","line":{"from":147,"to":149}} {"id":100007514,"name":"ListenAndServeKubeletServer","signature":"func ListenAndServeKubeletServer(","file":"pkg/kubelet/server/server.go","code":"// ListenAndServeKubeletServer initializes a server to respond to HTTP network requests on the Kubelet.\nfunc ListenAndServeKubeletServer(\n\thost HostInterface,\n\tresourceAnalyzer stats.ResourceAnalyzer,\n\tkubeCfg *kubeletconfiginternal.KubeletConfiguration,\n\ttlsOptions *TLSOptions,\n\tauth AuthInterface,\n\ttp oteltrace.TracerProvider) {\n\n\taddress := netutils.ParseIPSloppy(kubeCfg.Address)\n\tport := uint(kubeCfg.Port)\n\tklog.InfoS(\"Starting to listen\", \"address\", address, \"port\", port)\n\thandler := NewServer(host, resourceAnalyzer, auth, tp, kubeCfg)\n\ts := \u0026http.Server{\n\t\tAddr: net.JoinHostPort(address.String(), strconv.FormatUint(uint64(port), 10)),\n\t\tHandler: \u0026handler,\n\t\tIdleTimeout: 90 * time.Second, // matches http.DefaultTransport keep-alive timeout\n\t\tReadTimeout: 4 * 60 * time.Minute,\n\t\tWriteTimeout: 4 * 60 * time.Minute,\n\t\tMaxHeaderBytes: 1 \u003c\u003c 20,\n\t}\n\n\tif tlsOptions != nil {\n\t\ts.TLSConfig = tlsOptions.Config\n\t\t// Passing empty strings as the cert and key files means no\n\t\t// cert/keys are specified and GetCertificate in the TLSConfig\n\t\t// should be called instead.\n\t\tif err := s.ListenAndServeTLS(tlsOptions.CertFile, tlsOptions.KeyFile); err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to listen and serve\")\n\t\t\tos.Exit(1)\n\t\t}\n\t} else if err := s.ListenAndServe(); err != nil {\n\t\tklog.ErrorS(err, \"Failed to listen and serve\")\n\t\tos.Exit(1)\n\t}\n}","line":{"from":151,"to":186}} {"id":100007515,"name":"ListenAndServeKubeletReadOnlyServer","signature":"func ListenAndServeKubeletReadOnlyServer(","file":"pkg/kubelet/server/server.go","code":"// ListenAndServeKubeletReadOnlyServer initializes a server to respond to HTTP network requests on the Kubelet.\nfunc ListenAndServeKubeletReadOnlyServer(\n\thost HostInterface,\n\tresourceAnalyzer stats.ResourceAnalyzer,\n\taddress net.IP,\n\tport uint) {\n\tklog.InfoS(\"Starting to listen read-only\", \"address\", address, \"port\", port)\n\t// TODO: https://github.com/kubernetes/kubernetes/issues/109829 tracer should use WithPublicEndpoint\n\ts := NewServer(host, resourceAnalyzer, nil, oteltrace.NewNoopTracerProvider(), nil)\n\n\tserver := \u0026http.Server{\n\t\tAddr: net.JoinHostPort(address.String(), strconv.FormatUint(uint64(port), 10)),\n\t\tHandler: \u0026s,\n\t\tIdleTimeout: 90 * time.Second, // matches http.DefaultTransport keep-alive timeout\n\t\tReadTimeout: 4 * 60 * time.Minute,\n\t\tWriteTimeout: 4 * 60 * time.Minute,\n\t\tMaxHeaderBytes: 1 \u003c\u003c 20,\n\t}\n\n\tif err := server.ListenAndServe(); err != nil {\n\t\tklog.ErrorS(err, \"Failed to listen and serve\")\n\t\tos.Exit(1)\n\t}\n}","line":{"from":188,"to":211}} {"id":100007516,"name":"ListenAndServePodResources","signature":"func ListenAndServePodResources(socket string, providers podresources.PodResourcesProviders)","file":"pkg/kubelet/server/server.go","code":"// ListenAndServePodResources initializes a gRPC server to serve the PodResources service\nfunc ListenAndServePodResources(socket string, providers podresources.PodResourcesProviders) {\n\tserver := grpc.NewServer(podresourcesgrpc.WithRateLimiter(podresourcesgrpc.DefaultQPS, podresourcesgrpc.DefaultBurstTokens))\n\n\tpodresourcesapiv1alpha1.RegisterPodResourcesListerServer(server, podresources.NewV1alpha1PodResourcesServer(providers))\n\tpodresourcesapi.RegisterPodResourcesListerServer(server, podresources.NewV1PodResourcesServer(providers))\n\n\tl, err := util.CreateListener(socket)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to create listener for podResources endpoint\")\n\t\tos.Exit(1)\n\t}\n\n\tif err := server.Serve(l); err != nil {\n\t\tklog.ErrorS(err, \"Failed to serve\")\n\t\tos.Exit(1)\n\t}\n}","line":{"from":220,"to":237}} {"id":100007517,"name":"NewServer","signature":"func NewServer(","file":"pkg/kubelet/server/server.go","code":"// NewServer initializes and configures a kubelet.Server object to handle HTTP requests.\nfunc NewServer(\n\thost HostInterface,\n\tresourceAnalyzer stats.ResourceAnalyzer,\n\tauth AuthInterface,\n\ttp oteltrace.TracerProvider,\n\tkubeCfg *kubeletconfiginternal.KubeletConfiguration) Server {\n\n\tserver := Server{\n\t\thost: host,\n\t\tresourceAnalyzer: resourceAnalyzer,\n\t\tauth: auth,\n\t\trestfulCont: \u0026filteringContainer{Container: restful.NewContainer()},\n\t\tmetricsBuckets: sets.NewString(),\n\t\tmetricsMethodBuckets: sets.NewString(\"OPTIONS\", \"GET\", \"HEAD\", \"POST\", \"PUT\", \"DELETE\", \"TRACE\", \"CONNECT\"),\n\t}\n\tif auth != nil {\n\t\tserver.InstallAuthFilter()\n\t}\n\tif utilfeature.DefaultFeatureGate.Enabled(features.KubeletTracing) {\n\t\tserver.InstallTracingFilter(tp)\n\t}\n\tserver.InstallDefaultHandlers()\n\tif kubeCfg != nil \u0026\u0026 kubeCfg.EnableDebuggingHandlers {\n\t\tserver.InstallDebuggingHandlers()\n\t\t// To maintain backward compatibility serve logs and pprof only when enableDebuggingHandlers is also enabled\n\t\t// see https://github.com/kubernetes/kubernetes/pull/87273\n\t\tserver.InstallSystemLogHandler(kubeCfg.EnableSystemLogHandler, kubeCfg.EnableSystemLogQuery)\n\t\tserver.InstallProfilingHandler(kubeCfg.EnableProfilingHandler, kubeCfg.EnableContentionProfiling)\n\t\tserver.InstallDebugFlagsHandler(kubeCfg.EnableDebugFlagsHandler)\n\t} else {\n\t\tserver.InstallDebuggingDisabledHandlers()\n\t}\n\treturn server\n}","line":{"from":267,"to":301}} {"id":100007518,"name":"InstallAuthFilter","signature":"func (s *Server) InstallAuthFilter()","file":"pkg/kubelet/server/server.go","code":"// InstallAuthFilter installs authentication filters with the restful Container.\nfunc (s *Server) InstallAuthFilter() {\n\ts.restfulCont.Filter(func(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {\n\t\t// Authenticate\n\t\tinfo, ok, err := s.auth.AuthenticateRequest(req.Request)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Unable to authenticate the request due to an error\")\n\t\t\tresp.WriteErrorString(http.StatusUnauthorized, \"Unauthorized\")\n\t\t\treturn\n\t\t}\n\t\tif !ok {\n\t\t\tresp.WriteErrorString(http.StatusUnauthorized, \"Unauthorized\")\n\t\t\treturn\n\t\t}\n\n\t\t// Get authorization attributes\n\t\tattrs := s.auth.GetRequestAttributes(info.User, req.Request)\n\n\t\t// Authorize\n\t\tdecision, _, err := s.auth.Authorize(req.Request.Context(), attrs)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Authorization error\", \"user\", attrs.GetUser().GetName(), \"verb\", attrs.GetVerb(), \"resource\", attrs.GetResource(), \"subresource\", attrs.GetSubresource())\n\t\t\tmsg := fmt.Sprintf(\"Authorization error (user=%s, verb=%s, resource=%s, subresource=%s)\", attrs.GetUser().GetName(), attrs.GetVerb(), attrs.GetResource(), attrs.GetSubresource())\n\t\t\tresp.WriteErrorString(http.StatusInternalServerError, msg)\n\t\t\treturn\n\t\t}\n\t\tif decision != authorizer.DecisionAllow {\n\t\t\tklog.V(2).InfoS(\"Forbidden\", \"user\", attrs.GetUser().GetName(), \"verb\", attrs.GetVerb(), \"resource\", attrs.GetResource(), \"subresource\", attrs.GetSubresource())\n\t\t\tmsg := fmt.Sprintf(\"Forbidden (user=%s, verb=%s, resource=%s, subresource=%s)\", attrs.GetUser().GetName(), attrs.GetVerb(), attrs.GetResource(), attrs.GetSubresource())\n\t\t\tresp.WriteErrorString(http.StatusForbidden, msg)\n\t\t\treturn\n\t\t}\n\n\t\t// Continue\n\t\tchain.ProcessFilter(req, resp)\n\t})\n}","line":{"from":303,"to":339}} {"id":100007519,"name":"InstallTracingFilter","signature":"func (s *Server) InstallTracingFilter(tp oteltrace.TracerProvider)","file":"pkg/kubelet/server/server.go","code":"// InstallTracingFilter installs OpenTelemetry tracing filter with the restful Container.\nfunc (s *Server) InstallTracingFilter(tp oteltrace.TracerProvider) {\n\ts.restfulCont.Filter(otelrestful.OTelFilter(\"kubelet\", otelrestful.WithTracerProvider(tp)))\n}","line":{"from":341,"to":344}} {"id":100007520,"name":"addMetricsBucketMatcher","signature":"func (s *Server) addMetricsBucketMatcher(bucket string)","file":"pkg/kubelet/server/server.go","code":"// addMetricsBucketMatcher adds a regexp matcher and the relevant bucket to use when\n// it matches. Please be aware this is not thread safe and should not be used dynamically\nfunc (s *Server) addMetricsBucketMatcher(bucket string) {\n\ts.metricsBuckets.Insert(bucket)\n}","line":{"from":346,"to":350}} {"id":100007521,"name":"getMetricBucket","signature":"func (s *Server) getMetricBucket(path string) string","file":"pkg/kubelet/server/server.go","code":"// getMetricBucket find the appropriate metrics reporting bucket for the given path\nfunc (s *Server) getMetricBucket(path string) string {\n\troot := getURLRootPath(path)\n\tif s.metricsBuckets.Has(root) {\n\t\treturn root\n\t}\n\treturn \"other\"\n}","line":{"from":352,"to":359}} {"id":100007522,"name":"getMetricMethodBucket","signature":"func (s *Server) getMetricMethodBucket(method string) string","file":"pkg/kubelet/server/server.go","code":"// getMetricMethodBucket checks for unknown or invalid HTTP verbs\nfunc (s *Server) getMetricMethodBucket(method string) string {\n\tif s.metricsMethodBuckets.Has(method) {\n\t\treturn method\n\t}\n\treturn \"other\"\n}","line":{"from":361,"to":367}} {"id":100007523,"name":"InstallDefaultHandlers","signature":"func (s *Server) InstallDefaultHandlers()","file":"pkg/kubelet/server/server.go","code":"// InstallDefaultHandlers registers the default set of supported HTTP request\n// patterns with the restful Container.\nfunc (s *Server) InstallDefaultHandlers() {\n\ts.addMetricsBucketMatcher(\"healthz\")\n\thealthz.InstallHandler(s.restfulCont,\n\t\thealthz.PingHealthz,\n\t\thealthz.LogHealthz,\n\t\thealthz.NamedCheck(\"syncloop\", s.syncLoopHealthCheck),\n\t)\n\n\tif utilfeature.DefaultFeatureGate.Enabled(metricsfeatures.ComponentSLIs) {\n\t\tslis.SLIMetricsWithReset{}.Install(s.restfulCont)\n\t}\n\ts.addMetricsBucketMatcher(\"pods\")\n\tws := new(restful.WebService)\n\tws.\n\t\tPath(\"/pods\").\n\t\tProduces(restful.MIME_JSON)\n\tws.Route(ws.GET(\"\").\n\t\tTo(s.getPods).\n\t\tOperation(\"getPods\"))\n\ts.restfulCont.Add(ws)\n\n\ts.addMetricsBucketMatcher(\"stats\")\n\ts.restfulCont.Add(stats.CreateHandlers(statsPath, s.host, s.resourceAnalyzer))\n\n\ts.addMetricsBucketMatcher(\"metrics\")\n\ts.addMetricsBucketMatcher(\"metrics/cadvisor\")\n\ts.addMetricsBucketMatcher(\"metrics/probes\")\n\ts.addMetricsBucketMatcher(\"metrics/resource\")\n\ts.restfulCont.Handle(metricsPath, legacyregistry.Handler())\n\n\tincludedMetrics := cadvisormetrics.MetricSet{\n\t\tcadvisormetrics.CpuUsageMetrics: struct{}{},\n\t\tcadvisormetrics.MemoryUsageMetrics: struct{}{},\n\t\tcadvisormetrics.CpuLoadMetrics: struct{}{},\n\t\tcadvisormetrics.DiskIOMetrics: struct{}{},\n\t\tcadvisormetrics.DiskUsageMetrics: struct{}{},\n\t\tcadvisormetrics.NetworkUsageMetrics: struct{}{},\n\t\tcadvisormetrics.AppMetrics: struct{}{},\n\t\tcadvisormetrics.ProcessMetrics: struct{}{},\n\t\tcadvisormetrics.OOMMetrics: struct{}{},\n\t}\n\t// cAdvisor metrics are exposed under the secured handler as well\n\tr := compbasemetrics.NewKubeRegistry()\n\tr.RawMustRegister(metrics.NewPrometheusMachineCollector(prometheusHostAdapter{s.host}, includedMetrics))\n\tif utilfeature.DefaultFeatureGate.Enabled(features.PodAndContainerStatsFromCRI) {\n\t\tr.CustomRegister(collectors.NewCRIMetricsCollector(context.TODO(), s.host.ListPodSandboxMetrics, s.host.ListMetricDescriptors))\n\t} else {\n\t\tcadvisorOpts := cadvisorv2.RequestOptions{\n\t\t\tIdType: cadvisorv2.TypeName,\n\t\t\tCount: 1,\n\t\t\tRecursive: true,\n\t\t}\n\t\tr.RawMustRegister(metrics.NewPrometheusCollector(prometheusHostAdapter{s.host}, containerPrometheusLabelsFunc(s.host), includedMetrics, clock.RealClock{}, cadvisorOpts))\n\t}\n\ts.restfulCont.Handle(cadvisorMetricsPath,\n\t\tcompbasemetrics.HandlerFor(r, compbasemetrics.HandlerOpts{ErrorHandling: compbasemetrics.ContinueOnError}),\n\t)\n\n\ts.addMetricsBucketMatcher(\"metrics/resource\")\n\tresourceRegistry := compbasemetrics.NewKubeRegistry()\n\tresourceRegistry.CustomMustRegister(collectors.NewResourceMetricsCollector(s.resourceAnalyzer))\n\ts.restfulCont.Handle(resourceMetricsPath,\n\t\tcompbasemetrics.HandlerFor(resourceRegistry, compbasemetrics.HandlerOpts{ErrorHandling: compbasemetrics.ContinueOnError}),\n\t)\n\n\t// prober metrics are exposed under a different endpoint\n\n\ts.addMetricsBucketMatcher(\"metrics/probes\")\n\tp := compbasemetrics.NewKubeRegistry()\n\t_ = compbasemetrics.RegisterProcessStartTime(p.Register)\n\tp.MustRegister(prober.ProberResults)\n\tp.MustRegister(prober.ProberDuration)\n\ts.restfulCont.Handle(proberMetricsPath,\n\t\tcompbasemetrics.HandlerFor(p, compbasemetrics.HandlerOpts{ErrorHandling: compbasemetrics.ContinueOnError}),\n\t)\n\n\t// Only enable checkpoint API if the feature is enabled\n\tif utilfeature.DefaultFeatureGate.Enabled(features.ContainerCheckpoint) {\n\t\ts.addMetricsBucketMatcher(\"checkpoint\")\n\t\tws = \u0026restful.WebService{}\n\t\tws.Path(\"/checkpoint\").Produces(restful.MIME_JSON)\n\t\tws.Route(ws.POST(\"/{podNamespace}/{podID}/{containerName}\").\n\t\t\tTo(s.checkpoint).\n\t\t\tOperation(\"checkpoint\"))\n\t\ts.restfulCont.Add(ws)\n\t}\n}","line":{"from":369,"to":457}} {"id":100007524,"name":"InstallDebuggingHandlers","signature":"func (s *Server) InstallDebuggingHandlers()","file":"pkg/kubelet/server/server.go","code":"// InstallDebuggingHandlers registers the HTTP request patterns that serve logs or run commands/containers\nfunc (s *Server) InstallDebuggingHandlers() {\n\tklog.InfoS(\"Adding debug handlers to kubelet server\")\n\n\ts.addMetricsBucketMatcher(\"run\")\n\tws := new(restful.WebService)\n\tws.\n\t\tPath(\"/run\")\n\tws.Route(ws.POST(\"/{podNamespace}/{podID}/{containerName}\").\n\t\tTo(s.getRun).\n\t\tOperation(\"getRun\"))\n\tws.Route(ws.POST(\"/{podNamespace}/{podID}/{uid}/{containerName}\").\n\t\tTo(s.getRun).\n\t\tOperation(\"getRun\"))\n\ts.restfulCont.Add(ws)\n\n\ts.addMetricsBucketMatcher(\"exec\")\n\tws = new(restful.WebService)\n\tws.\n\t\tPath(\"/exec\")\n\tws.Route(ws.GET(\"/{podNamespace}/{podID}/{containerName}\").\n\t\tTo(s.getExec).\n\t\tOperation(\"getExec\"))\n\tws.Route(ws.POST(\"/{podNamespace}/{podID}/{containerName}\").\n\t\tTo(s.getExec).\n\t\tOperation(\"getExec\"))\n\tws.Route(ws.GET(\"/{podNamespace}/{podID}/{uid}/{containerName}\").\n\t\tTo(s.getExec).\n\t\tOperation(\"getExec\"))\n\tws.Route(ws.POST(\"/{podNamespace}/{podID}/{uid}/{containerName}\").\n\t\tTo(s.getExec).\n\t\tOperation(\"getExec\"))\n\ts.restfulCont.Add(ws)\n\n\ts.addMetricsBucketMatcher(\"attach\")\n\tws = new(restful.WebService)\n\tws.\n\t\tPath(\"/attach\")\n\tws.Route(ws.GET(\"/{podNamespace}/{podID}/{containerName}\").\n\t\tTo(s.getAttach).\n\t\tOperation(\"getAttach\"))\n\tws.Route(ws.POST(\"/{podNamespace}/{podID}/{containerName}\").\n\t\tTo(s.getAttach).\n\t\tOperation(\"getAttach\"))\n\tws.Route(ws.GET(\"/{podNamespace}/{podID}/{uid}/{containerName}\").\n\t\tTo(s.getAttach).\n\t\tOperation(\"getAttach\"))\n\tws.Route(ws.POST(\"/{podNamespace}/{podID}/{uid}/{containerName}\").\n\t\tTo(s.getAttach).\n\t\tOperation(\"getAttach\"))\n\ts.restfulCont.Add(ws)\n\n\ts.addMetricsBucketMatcher(\"portForward\")\n\tws = new(restful.WebService)\n\tws.\n\t\tPath(\"/portForward\")\n\tws.Route(ws.GET(\"/{podNamespace}/{podID}\").\n\t\tTo(s.getPortForward).\n\t\tOperation(\"getPortForward\"))\n\tws.Route(ws.POST(\"/{podNamespace}/{podID}\").\n\t\tTo(s.getPortForward).\n\t\tOperation(\"getPortForward\"))\n\tws.Route(ws.GET(\"/{podNamespace}/{podID}/{uid}\").\n\t\tTo(s.getPortForward).\n\t\tOperation(\"getPortForward\"))\n\tws.Route(ws.POST(\"/{podNamespace}/{podID}/{uid}\").\n\t\tTo(s.getPortForward).\n\t\tOperation(\"getPortForward\"))\n\ts.restfulCont.Add(ws)\n\n\ts.addMetricsBucketMatcher(\"containerLogs\")\n\tws = new(restful.WebService)\n\tws.\n\t\tPath(\"/containerLogs\")\n\tws.Route(ws.GET(\"/{podNamespace}/{podID}/{containerName}\").\n\t\tTo(s.getContainerLogs).\n\t\tOperation(\"getContainerLogs\"))\n\ts.restfulCont.Add(ws)\n\n\ts.addMetricsBucketMatcher(\"configz\")\n\tconfigz.InstallHandler(s.restfulCont)\n\n\t// The /runningpods endpoint is used for testing only.\n\ts.addMetricsBucketMatcher(\"runningpods\")\n\tws = new(restful.WebService)\n\tws.\n\t\tPath(\"/runningpods/\").\n\t\tProduces(restful.MIME_JSON)\n\tws.Route(ws.GET(\"\").\n\t\tTo(s.getRunningPods).\n\t\tOperation(\"getRunningPods\"))\n\ts.restfulCont.Add(ws)\n}","line":{"from":459,"to":551}} {"id":100007525,"name":"InstallDebuggingDisabledHandlers","signature":"func (s *Server) InstallDebuggingDisabledHandlers()","file":"pkg/kubelet/server/server.go","code":"// InstallDebuggingDisabledHandlers registers the HTTP request patterns that provide better error message\nfunc (s *Server) InstallDebuggingDisabledHandlers() {\n\th := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.Error(w, \"Debug endpoints are disabled.\", http.StatusMethodNotAllowed)\n\t})\n\n\ts.addMetricsBucketMatcher(\"run\")\n\ts.addMetricsBucketMatcher(\"exec\")\n\ts.addMetricsBucketMatcher(\"attach\")\n\ts.addMetricsBucketMatcher(\"portForward\")\n\ts.addMetricsBucketMatcher(\"containerLogs\")\n\ts.addMetricsBucketMatcher(\"runningpods\")\n\ts.addMetricsBucketMatcher(\"pprof\")\n\ts.addMetricsBucketMatcher(\"logs\")\n\tpaths := []string{\n\t\t\"/run/\", \"/exec/\", \"/attach/\", \"/portForward/\", \"/containerLogs/\",\n\t\t\"/runningpods/\", pprofBasePath, logsPath}\n\tfor _, p := range paths {\n\t\ts.restfulCont.Handle(p, h)\n\t}\n}","line":{"from":553,"to":573}} {"id":100007526,"name":"InstallSystemLogHandler","signature":"func (s *Server) InstallSystemLogHandler(enableSystemLogHandler bool, enableSystemLogQuery bool)","file":"pkg/kubelet/server/server.go","code":"// InstallSystemLogHandler registers the HTTP request patterns for logs endpoint.\nfunc (s *Server) InstallSystemLogHandler(enableSystemLogHandler bool, enableSystemLogQuery bool) {\n\ts.addMetricsBucketMatcher(\"logs\")\n\tif enableSystemLogHandler {\n\t\tws := new(restful.WebService)\n\t\tws.Path(logsPath)\n\t\tws.Route(ws.GET(\"\").\n\t\t\tTo(s.getLogs).\n\t\t\tOperation(\"getLogs\"))\n\t\tif !enableSystemLogQuery {\n\t\t\tws.Route(ws.GET(\"/{logpath:*}\").\n\t\t\t\tTo(s.getLogs).\n\t\t\t\tOperation(\"getLogs\").\n\t\t\t\tParam(ws.PathParameter(\"logpath\", \"path to the log\").DataType(\"string\")))\n\t\t} else {\n\t\t\tws.Route(ws.GET(\"/{logpath:*}\").\n\t\t\t\tTo(s.getLogs).\n\t\t\t\tOperation(\"getLogs\").\n\t\t\t\tParam(ws.PathParameter(\"logpath\", \"path to the log\").DataType(\"string\")).\n\t\t\t\tParam(ws.QueryParameter(\"query\", \"query specifies services(s) or files from which to return logs\").DataType(\"string\")).\n\t\t\t\tParam(ws.QueryParameter(\"sinceTime\", \"sinceTime is an RFC3339 timestamp from which to show logs\").DataType(\"string\")).\n\t\t\t\tParam(ws.QueryParameter(\"untilTime\", \"untilTime is an RFC3339 timestamp until which to show logs\").DataType(\"string\")).\n\t\t\t\tParam(ws.QueryParameter(\"tailLines\", \"tailLines is used to retrieve the specified number of lines from the end of the log\").DataType(\"string\")).\n\t\t\t\tParam(ws.QueryParameter(\"pattern\", \"pattern filters log entries by the provided regex pattern\").DataType(\"string\")).\n\t\t\t\tParam(ws.QueryParameter(\"boot\", \"boot show messages from a specific system boot\").DataType(\"string\")))\n\t\t}\n\t\ts.restfulCont.Add(ws)\n\t} else {\n\t\ts.restfulCont.Handle(logsPath, getHandlerForDisabledEndpoint(\"logs endpoint is disabled.\"))\n\t}\n}","line":{"from":575,"to":605}} {"id":100007527,"name":"getHandlerForDisabledEndpoint","signature":"func getHandlerForDisabledEndpoint(errorMessage string) http.HandlerFunc","file":"pkg/kubelet/server/server.go","code":"func getHandlerForDisabledEndpoint(errorMessage string) http.HandlerFunc {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.Error(w, errorMessage, http.StatusMethodNotAllowed)\n\t})\n}","line":{"from":607,"to":611}} {"id":100007528,"name":"InstallDebugFlagsHandler","signature":"func (s *Server) InstallDebugFlagsHandler(enableDebugFlagsHandler bool)","file":"pkg/kubelet/server/server.go","code":"// InstallDebugFlagsHandler registers the HTTP request patterns for /debug/flags/v endpoint.\nfunc (s *Server) InstallDebugFlagsHandler(enableDebugFlagsHandler bool) {\n\tif enableDebugFlagsHandler {\n\t\t// Setup flags handlers.\n\t\t// so far, only logging related endpoints are considered valid to add for these debug flags.\n\t\ts.restfulCont.Handle(debugFlagPath, routes.StringFlagPutHandler(logs.GlogSetter))\n\t} else {\n\t\ts.restfulCont.Handle(debugFlagPath, getHandlerForDisabledEndpoint(\"flags endpoint is disabled.\"))\n\t\treturn\n\t}\n}","line":{"from":613,"to":623}} {"id":100007529,"name":"InstallProfilingHandler","signature":"func (s *Server) InstallProfilingHandler(enableProfilingLogHandler bool, enableContentionProfiling bool)","file":"pkg/kubelet/server/server.go","code":"// InstallProfilingHandler registers the HTTP request patterns for /debug/pprof endpoint.\nfunc (s *Server) InstallProfilingHandler(enableProfilingLogHandler bool, enableContentionProfiling bool) {\n\ts.addMetricsBucketMatcher(\"debug\")\n\tif !enableProfilingLogHandler {\n\t\ts.restfulCont.Handle(pprofBasePath, getHandlerForDisabledEndpoint(\"profiling endpoint is disabled.\"))\n\t\treturn\n\t}\n\n\thandlePprofEndpoint := func(req *restful.Request, resp *restful.Response) {\n\t\tname := strings.TrimPrefix(req.Request.URL.Path, pprofBasePath)\n\t\tswitch name {\n\t\tcase \"profile\":\n\t\t\tpprof.Profile(resp, req.Request)\n\t\tcase \"symbol\":\n\t\t\tpprof.Symbol(resp, req.Request)\n\t\tcase \"cmdline\":\n\t\t\tpprof.Cmdline(resp, req.Request)\n\t\tcase \"trace\":\n\t\t\tpprof.Trace(resp, req.Request)\n\t\tdefault:\n\t\t\tpprof.Index(resp, req.Request)\n\t\t}\n\t}\n\n\t// Setup pprof handlers.\n\tws := new(restful.WebService).Path(pprofBasePath)\n\tws.Route(ws.GET(\"/{subpath:*}\").To(handlePprofEndpoint)).Doc(\"pprof endpoint\")\n\ts.restfulCont.Add(ws)\n\n\tif enableContentionProfiling {\n\t\tgoruntime.SetBlockProfileRate(1)\n\t}\n}","line":{"from":625,"to":657}} {"id":100007530,"name":"syncLoopHealthCheck","signature":"func (s *Server) syncLoopHealthCheck(req *http.Request) error","file":"pkg/kubelet/server/server.go","code":"// Checks if kubelet's sync loop that updates containers is working.\nfunc (s *Server) syncLoopHealthCheck(req *http.Request) error {\n\tduration := s.host.ResyncInterval() * 2\n\tminDuration := time.Minute * 5\n\tif duration \u003c minDuration {\n\t\tduration = minDuration\n\t}\n\tenterLoopTime := s.host.LatestLoopEntryTime()\n\tif !enterLoopTime.IsZero() \u0026\u0026 time.Now().After(enterLoopTime.Add(duration)) {\n\t\treturn fmt.Errorf(\"sync Loop took longer than expected\")\n\t}\n\treturn nil\n}","line":{"from":659,"to":671}} {"id":100007531,"name":"getContainerLogs","signature":"func (s *Server) getContainerLogs(request *restful.Request, response *restful.Response)","file":"pkg/kubelet/server/server.go","code":"// getContainerLogs handles containerLogs request against the Kubelet\nfunc (s *Server) getContainerLogs(request *restful.Request, response *restful.Response) {\n\tpodNamespace := request.PathParameter(\"podNamespace\")\n\tpodID := request.PathParameter(\"podID\")\n\tcontainerName := request.PathParameter(\"containerName\")\n\tctx := request.Request.Context()\n\n\tif len(podID) == 0 {\n\t\t// TODO: Why return JSON when the rest return plaintext errors?\n\t\t// TODO: Why return plaintext errors?\n\t\tresponse.WriteError(http.StatusBadRequest, fmt.Errorf(`{\"message\": \"Missing podID.\"}`))\n\t\treturn\n\t}\n\tif len(containerName) == 0 {\n\t\t// TODO: Why return JSON when the rest return plaintext errors?\n\t\tresponse.WriteError(http.StatusBadRequest, fmt.Errorf(`{\"message\": \"Missing container name.\"}`))\n\t\treturn\n\t}\n\tif len(podNamespace) == 0 {\n\t\t// TODO: Why return JSON when the rest return plaintext errors?\n\t\tresponse.WriteError(http.StatusBadRequest, fmt.Errorf(`{\"message\": \"Missing podNamespace.\"}`))\n\t\treturn\n\t}\n\n\tquery := request.Request.URL.Query()\n\t// backwards compatibility for the \"tail\" query parameter\n\tif tail := request.QueryParameter(\"tail\"); len(tail) \u003e 0 {\n\t\tquery[\"tailLines\"] = []string{tail}\n\t\t// \"all\" is the same as omitting tail\n\t\tif tail == \"all\" {\n\t\t\tdelete(query, \"tailLines\")\n\t\t}\n\t}\n\t// container logs on the kubelet are locked to the v1 API version of PodLogOptions\n\tlogOptions := \u0026v1.PodLogOptions{}\n\tif err := legacyscheme.ParameterCodec.DecodeParameters(query, v1.SchemeGroupVersion, logOptions); err != nil {\n\t\tresponse.WriteError(http.StatusBadRequest, fmt.Errorf(`{\"message\": \"Unable to decode query.\"}`))\n\t\treturn\n\t}\n\tlogOptions.TypeMeta = metav1.TypeMeta{}\n\tif errs := validation.ValidatePodLogOptions(logOptions); len(errs) \u003e 0 {\n\t\tresponse.WriteError(http.StatusUnprocessableEntity, fmt.Errorf(`{\"message\": \"Invalid request.\"}`))\n\t\treturn\n\t}\n\n\tpod, ok := s.host.GetPodByName(podNamespace, podID)\n\tif !ok {\n\t\tresponse.WriteError(http.StatusNotFound, fmt.Errorf(\"pod %q does not exist\", podID))\n\t\treturn\n\t}\n\t// Check if containerName is valid.\n\tif kubecontainer.GetContainerSpec(pod, containerName) == nil {\n\t\tresponse.WriteError(http.StatusNotFound, fmt.Errorf(\"container %q not found in pod %q\", containerName, podID))\n\t\treturn\n\t}\n\n\tif _, ok := response.ResponseWriter.(http.Flusher); !ok {\n\t\tresponse.WriteError(http.StatusInternalServerError, fmt.Errorf(\"unable to convert %v into http.Flusher, cannot show logs\", reflect.TypeOf(response)))\n\t\treturn\n\t}\n\tfw := flushwriter.Wrap(response.ResponseWriter)\n\tresponse.Header().Set(\"Transfer-Encoding\", \"chunked\")\n\tif err := s.host.GetKubeletContainerLogs(ctx, kubecontainer.GetPodFullName(pod), containerName, logOptions, fw, fw); err != nil {\n\t\tresponse.WriteError(http.StatusBadRequest, err)\n\t\treturn\n\t}\n}","line":{"from":673,"to":739}} {"id":100007532,"name":"encodePods","signature":"func encodePods(pods []*v1.Pod) (data []byte, err error)","file":"pkg/kubelet/server/server.go","code":"// encodePods creates an v1.PodList object from pods and returns the encoded\n// PodList.\nfunc encodePods(pods []*v1.Pod) (data []byte, err error) {\n\tpodList := new(v1.PodList)\n\tfor _, pod := range pods {\n\t\tpodList.Items = append(podList.Items, *pod)\n\t}\n\t// TODO: this needs to be parameterized to the kubelet, not hardcoded. Depends on Kubelet\n\t// as API server refactor.\n\t// TODO: Locked to v1, needs to be made generic\n\tcodec := legacyscheme.Codecs.LegacyCodec(schema.GroupVersion{Group: v1.GroupName, Version: \"v1\"})\n\treturn runtime.Encode(codec, podList)\n}","line":{"from":741,"to":753}} {"id":100007533,"name":"getPods","signature":"func (s *Server) getPods(request *restful.Request, response *restful.Response)","file":"pkg/kubelet/server/server.go","code":"// getPods returns a list of pods bound to the Kubelet and their spec.\nfunc (s *Server) getPods(request *restful.Request, response *restful.Response) {\n\tpods := s.host.GetPods()\n\tdata, err := encodePods(pods)\n\tif err != nil {\n\t\tresponse.WriteError(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\twriteJSONResponse(response, data)\n}","line":{"from":755,"to":764}} {"id":100007534,"name":"getRunningPods","signature":"func (s *Server) getRunningPods(request *restful.Request, response *restful.Response)","file":"pkg/kubelet/server/server.go","code":"// getRunningPods returns a list of pods running on Kubelet. The list is\n// provided by the container runtime, and is different from the list returned\n// by getPods, which is a set of desired pods to run.\nfunc (s *Server) getRunningPods(request *restful.Request, response *restful.Response) {\n\tctx := request.Request.Context()\n\tpods, err := s.host.GetRunningPods(ctx)\n\tif err != nil {\n\t\tresponse.WriteError(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\tdata, err := encodePods(pods)\n\tif err != nil {\n\t\tresponse.WriteError(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\twriteJSONResponse(response, data)\n}","line":{"from":766,"to":782}} {"id":100007535,"name":"getLogs","signature":"func (s *Server) getLogs(request *restful.Request, response *restful.Response)","file":"pkg/kubelet/server/server.go","code":"// getLogs handles logs requests against the Kubelet.\nfunc (s *Server) getLogs(request *restful.Request, response *restful.Response) {\n\ts.host.ServeLogs(response, request.Request)\n}","line":{"from":784,"to":787}} {"id":100007536,"name":"getExecRequestParams","signature":"func getExecRequestParams(req *restful.Request) execRequestParams","file":"pkg/kubelet/server/server.go","code":"func getExecRequestParams(req *restful.Request) execRequestParams {\n\treturn execRequestParams{\n\t\tpodNamespace: req.PathParameter(\"podNamespace\"),\n\t\tpodName: req.PathParameter(\"podID\"),\n\t\tpodUID: types.UID(req.PathParameter(\"uid\")),\n\t\tcontainerName: req.PathParameter(\"containerName\"),\n\t\tcmd: req.Request.URL.Query()[api.ExecCommandParam],\n\t}\n}","line":{"from":797,"to":805}} {"id":100007537,"name":"getPortForwardRequestParams","signature":"func getPortForwardRequestParams(req *restful.Request) portForwardRequestParams","file":"pkg/kubelet/server/server.go","code":"func getPortForwardRequestParams(req *restful.Request) portForwardRequestParams {\n\treturn portForwardRequestParams{\n\t\tpodNamespace: req.PathParameter(\"podNamespace\"),\n\t\tpodName: req.PathParameter(\"podID\"),\n\t\tpodUID: types.UID(req.PathParameter(\"uid\")),\n\t}\n}","line":{"from":813,"to":819}} {"id":100007538,"name":"Error","signature":"func (r *responder) Error(w http.ResponseWriter, req *http.Request, err error)","file":"pkg/kubelet/server/server.go","code":"func (r *responder) Error(w http.ResponseWriter, req *http.Request, err error) {\n\tklog.ErrorS(err, \"Error while proxying request\")\n\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n}","line":{"from":823,"to":826}} {"id":100007539,"name":"proxyStream","signature":"func proxyStream(w http.ResponseWriter, r *http.Request, url *url.URL)","file":"pkg/kubelet/server/server.go","code":"// proxyStream proxies stream to url.\nfunc proxyStream(w http.ResponseWriter, r *http.Request, url *url.URL) {\n\t// TODO(random-liu): Set MaxBytesPerSec to throttle the stream.\n\thandler := proxy.NewUpgradeAwareHandler(url, nil /*transport*/, false /*wrapTransport*/, true /*upgradeRequired*/, \u0026responder{})\n\thandler.ServeHTTP(w, r)\n}","line":{"from":828,"to":833}} {"id":100007540,"name":"getAttach","signature":"func (s *Server) getAttach(request *restful.Request, response *restful.Response)","file":"pkg/kubelet/server/server.go","code":"// getAttach handles requests to attach to a container.\nfunc (s *Server) getAttach(request *restful.Request, response *restful.Response) {\n\tparams := getExecRequestParams(request)\n\tstreamOpts, err := remotecommandserver.NewOptions(request.Request)\n\tif err != nil {\n\t\tutilruntime.HandleError(err)\n\t\tresponse.WriteError(http.StatusBadRequest, err)\n\t\treturn\n\t}\n\tpod, ok := s.host.GetPodByName(params.podNamespace, params.podName)\n\tif !ok {\n\t\tresponse.WriteError(http.StatusNotFound, fmt.Errorf(\"pod does not exist\"))\n\t\treturn\n\t}\n\n\tpodFullName := kubecontainer.GetPodFullName(pod)\n\turl, err := s.host.GetAttach(request.Request.Context(), podFullName, params.podUID, params.containerName, *streamOpts)\n\tif err != nil {\n\t\tstreaming.WriteError(err, response.ResponseWriter)\n\t\treturn\n\t}\n\n\tproxyStream(response.ResponseWriter, request.Request, url)\n}","line":{"from":835,"to":858}} {"id":100007541,"name":"getExec","signature":"func (s *Server) getExec(request *restful.Request, response *restful.Response)","file":"pkg/kubelet/server/server.go","code":"// getExec handles requests to run a command inside a container.\nfunc (s *Server) getExec(request *restful.Request, response *restful.Response) {\n\tparams := getExecRequestParams(request)\n\tstreamOpts, err := remotecommandserver.NewOptions(request.Request)\n\tif err != nil {\n\t\tutilruntime.HandleError(err)\n\t\tresponse.WriteError(http.StatusBadRequest, err)\n\t\treturn\n\t}\n\tpod, ok := s.host.GetPodByName(params.podNamespace, params.podName)\n\tif !ok {\n\t\tresponse.WriteError(http.StatusNotFound, fmt.Errorf(\"pod does not exist\"))\n\t\treturn\n\t}\n\n\tpodFullName := kubecontainer.GetPodFullName(pod)\n\turl, err := s.host.GetExec(request.Request.Context(), podFullName, params.podUID, params.containerName, params.cmd, *streamOpts)\n\tif err != nil {\n\t\tstreaming.WriteError(err, response.ResponseWriter)\n\t\treturn\n\t}\n\tproxyStream(response.ResponseWriter, request.Request, url)\n}","line":{"from":860,"to":882}} {"id":100007542,"name":"getRun","signature":"func (s *Server) getRun(request *restful.Request, response *restful.Response)","file":"pkg/kubelet/server/server.go","code":"// getRun handles requests to run a command inside a container.\nfunc (s *Server) getRun(request *restful.Request, response *restful.Response) {\n\tparams := getExecRequestParams(request)\n\tpod, ok := s.host.GetPodByName(params.podNamespace, params.podName)\n\tif !ok {\n\t\tresponse.WriteError(http.StatusNotFound, fmt.Errorf(\"pod does not exist\"))\n\t\treturn\n\t}\n\n\t// For legacy reasons, run uses different query param than exec.\n\tparams.cmd = strings.Split(request.QueryParameter(\"cmd\"), \" \")\n\tdata, err := s.host.RunInContainer(request.Request.Context(), kubecontainer.GetPodFullName(pod), params.podUID, params.containerName, params.cmd)\n\tif err != nil {\n\t\tresponse.WriteError(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\twriteJSONResponse(response, data)\n}","line":{"from":884,"to":901}} {"id":100007543,"name":"writeJSONResponse","signature":"func writeJSONResponse(response *restful.Response, data []byte)","file":"pkg/kubelet/server/server.go","code":"// Derived from go-restful writeJSON.\nfunc writeJSONResponse(response *restful.Response, data []byte) {\n\tif data == nil {\n\t\tresponse.WriteHeader(http.StatusOK)\n\t\t// do not write a nil representation\n\t\treturn\n\t}\n\tresponse.Header().Set(restful.HEADER_ContentType, restful.MIME_JSON)\n\tresponse.WriteHeader(http.StatusOK)\n\tif _, err := response.Write(data); err != nil {\n\t\tklog.ErrorS(err, \"Error writing response\")\n\t}\n}","line":{"from":903,"to":915}} {"id":100007544,"name":"getPortForward","signature":"func (s *Server) getPortForward(request *restful.Request, response *restful.Response)","file":"pkg/kubelet/server/server.go","code":"// getPortForward handles a new restful port forward request. It determines the\n// pod name and uid and then calls ServePortForward.\nfunc (s *Server) getPortForward(request *restful.Request, response *restful.Response) {\n\tparams := getPortForwardRequestParams(request)\n\n\tportForwardOptions, err := portforward.NewV4Options(request.Request)\n\tif err != nil {\n\t\tutilruntime.HandleError(err)\n\t\tresponse.WriteError(http.StatusBadRequest, err)\n\t\treturn\n\t}\n\tpod, ok := s.host.GetPodByName(params.podNamespace, params.podName)\n\tif !ok {\n\t\tresponse.WriteError(http.StatusNotFound, fmt.Errorf(\"pod does not exist\"))\n\t\treturn\n\t}\n\tif len(params.podUID) \u003e 0 \u0026\u0026 pod.UID != params.podUID {\n\t\tresponse.WriteError(http.StatusNotFound, fmt.Errorf(\"pod not found\"))\n\t\treturn\n\t}\n\n\turl, err := s.host.GetPortForward(request.Request.Context(), pod.Name, pod.Namespace, pod.UID, *portForwardOptions)\n\tif err != nil {\n\t\tstreaming.WriteError(err, response.ResponseWriter)\n\t\treturn\n\t}\n\tproxyStream(response.ResponseWriter, request.Request, url)\n}","line":{"from":917,"to":944}} {"id":100007545,"name":"checkpoint","signature":"func (s *Server) checkpoint(request *restful.Request, response *restful.Response)","file":"pkg/kubelet/server/server.go","code":"// checkpoint handles the checkpoint API request. It checks if the requested\n// podNamespace, pod and container actually exist and only then calls out\n// to the runtime to actually checkpoint the container.\nfunc (s *Server) checkpoint(request *restful.Request, response *restful.Response) {\n\tctx := request.Request.Context()\n\tpod, ok := s.host.GetPodByName(request.PathParameter(\"podNamespace\"), request.PathParameter(\"podID\"))\n\tif !ok {\n\t\tresponse.WriteError(http.StatusNotFound, fmt.Errorf(\"pod does not exist\"))\n\t\treturn\n\t}\n\n\tcontainerName := request.PathParameter(\"containerName\")\n\n\tfound := false\n\tfor _, container := range pod.Spec.Containers {\n\t\tif container.Name == containerName {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\tfor _, container := range pod.Spec.InitContainers {\n\t\t\tif container.Name == containerName {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif !found {\n\t\tfor _, container := range pod.Spec.EphemeralContainers {\n\t\t\tif container.Name == containerName {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif !found {\n\t\tresponse.WriteError(\n\t\t\thttp.StatusNotFound,\n\t\t\tfmt.Errorf(\"container %v does not exist\", containerName),\n\t\t)\n\t\treturn\n\t}\n\n\toptions := \u0026runtimeapi.CheckpointContainerRequest{}\n\t// Query parameter to select an optional timeout. Without the timeout parameter\n\t// the checkpoint command will use the default CRI timeout.\n\ttimeouts := request.Request.URL.Query()[\"timeout\"]\n\tif len(timeouts) \u003e 0 {\n\t\t// If the user specified one or multiple values for timeouts we\n\t\t// are using the last available value.\n\t\ttimeout, err := strconv.ParseInt(timeouts[len(timeouts)-1], 10, 64)\n\t\tif err != nil {\n\t\t\tresponse.WriteError(\n\t\t\t\thttp.StatusNotFound,\n\t\t\t\tfmt.Errorf(\"cannot parse value of timeout parameter\"),\n\t\t\t)\n\t\t\treturn\n\t\t}\n\t\toptions.Timeout = timeout\n\t}\n\n\tif err := s.host.CheckpointContainer(ctx, pod.UID, kubecontainer.GetPodFullName(pod), containerName, options); err != nil {\n\t\tresponse.WriteError(\n\t\t\thttp.StatusInternalServerError,\n\t\t\tfmt.Errorf(\n\t\t\t\t\"checkpointing of %v/%v/%v failed (%v)\",\n\t\t\t\trequest.PathParameter(\"podNamespace\"),\n\t\t\t\trequest.PathParameter(\"podID\"),\n\t\t\t\tcontainerName,\n\t\t\t\terr,\n\t\t\t),\n\t\t)\n\t\treturn\n\t}\n\twriteJSONResponse(\n\t\tresponse,\n\t\t[]byte(fmt.Sprintf(\"{\\\"items\\\":[\\\"%s\\\"]}\", options.Location)),\n\t)\n}","line":{"from":946,"to":1025}} {"id":100007546,"name":"getURLRootPath","signature":"func getURLRootPath(path string) string","file":"pkg/kubelet/server/server.go","code":"// getURLRootPath trims a URL path.\n// For paths in the format of \"/metrics/xxx\", \"metrics/xxx\" is returned;\n// For all other paths, the first part of the path is returned.\nfunc getURLRootPath(path string) string {\n\tparts := strings.SplitN(strings.TrimPrefix(path, \"/\"), \"/\", 3)\n\tif len(parts) == 0 {\n\t\treturn path\n\t}\n\n\tif parts[0] == \"metrics\" \u0026\u0026 len(parts) \u003e 1 {\n\t\treturn fmt.Sprintf(\"%s/%s\", parts[0], parts[1])\n\n\t}\n\treturn parts[0]\n}","line":{"from":1027,"to":1041}} {"id":100007547,"name":"isLongRunningRequest","signature":"func isLongRunningRequest(path string) bool","file":"pkg/kubelet/server/server.go","code":"// isLongRunningRequest determines whether the request is long-running or not.\nfunc isLongRunningRequest(path string) bool {\n\t_, ok := longRunningRequestPathMap[path]\n\treturn ok\n}","line":{"from":1050,"to":1054}} {"id":100007548,"name":"ServeHTTP","signature":"func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request)","file":"pkg/kubelet/server/server.go","code":"// ServeHTTP responds to HTTP requests on the Kubelet.\nfunc (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\thandler := httplog.WithLogging(s.restfulCont, statusesNoTracePred)\n\n\t// monitor http requests\n\tvar serverType string\n\tif s.auth == nil {\n\t\tserverType = \"readonly\"\n\t} else {\n\t\tserverType = \"readwrite\"\n\t}\n\n\tmethod, path := s.getMetricMethodBucket(req.Method), s.getMetricBucket(req.URL.Path)\n\n\tlongRunning := strconv.FormatBool(isLongRunningRequest(path))\n\n\tservermetrics.HTTPRequests.WithLabelValues(method, path, serverType, longRunning).Inc()\n\n\tservermetrics.HTTPInflightRequests.WithLabelValues(method, path, serverType, longRunning).Inc()\n\tdefer servermetrics.HTTPInflightRequests.WithLabelValues(method, path, serverType, longRunning).Dec()\n\n\tstartTime := time.Now()\n\tdefer servermetrics.HTTPRequestsDuration.WithLabelValues(method, path, serverType, longRunning).Observe(servermetrics.SinceInSeconds(startTime))\n\n\thandler.ServeHTTP(w, req)\n}","line":{"from":1066,"to":1091}} {"id":100007549,"name":"GetRequestedContainersInfo","signature":"func (a prometheusHostAdapter) GetRequestedContainersInfo(containerName string, options cadvisorv2.RequestOptions) (map[string]*cadvisorapi.ContainerInfo, error)","file":"pkg/kubelet/server/server.go","code":"func (a prometheusHostAdapter) GetRequestedContainersInfo(containerName string, options cadvisorv2.RequestOptions) (map[string]*cadvisorapi.ContainerInfo, error) {\n\treturn a.host.GetRequestedContainersInfo(containerName, options)\n}","line":{"from":1099,"to":1101}} {"id":100007550,"name":"GetVersionInfo","signature":"func (a prometheusHostAdapter) GetVersionInfo() (*cadvisorapi.VersionInfo, error)","file":"pkg/kubelet/server/server.go","code":"func (a prometheusHostAdapter) GetVersionInfo() (*cadvisorapi.VersionInfo, error) {\n\treturn a.host.GetVersionInfo()\n}","line":{"from":1102,"to":1104}} {"id":100007551,"name":"GetMachineInfo","signature":"func (a prometheusHostAdapter) GetMachineInfo() (*cadvisorapi.MachineInfo, error)","file":"pkg/kubelet/server/server.go","code":"func (a prometheusHostAdapter) GetMachineInfo() (*cadvisorapi.MachineInfo, error) {\n\treturn a.host.GetCachedMachineInfo()\n}","line":{"from":1105,"to":1107}} {"id":100007552,"name":"containerPrometheusLabelsFunc","signature":"func containerPrometheusLabelsFunc(s stats.Provider) metrics.ContainerLabelsFunc","file":"pkg/kubelet/server/server.go","code":"func containerPrometheusLabelsFunc(s stats.Provider) metrics.ContainerLabelsFunc {\n\t// containerPrometheusLabels maps cAdvisor labels to prometheus labels.\n\treturn func(c *cadvisorapi.ContainerInfo) map[string]string {\n\t\t// Prometheus requires that all metrics in the same family have the same labels,\n\t\t// so we arrange to supply blank strings for missing labels\n\t\tvar name, image, podName, namespace, containerName string\n\t\tif len(c.Aliases) \u003e 0 {\n\t\t\tname = c.Aliases[0]\n\t\t}\n\t\timage = c.Spec.Image\n\t\tif v, ok := c.Spec.Labels[kubelettypes.KubernetesPodNameLabel]; ok {\n\t\t\tpodName = v\n\t\t}\n\t\tif v, ok := c.Spec.Labels[kubelettypes.KubernetesPodNamespaceLabel]; ok {\n\t\t\tnamespace = v\n\t\t}\n\t\tif v, ok := c.Spec.Labels[kubelettypes.KubernetesContainerNameLabel]; ok {\n\t\t\tcontainerName = v\n\t\t}\n\t\t// Associate pod cgroup with pod so we have an accurate accounting of sandbox\n\t\tif podName == \"\" \u0026\u0026 namespace == \"\" {\n\t\t\tif pod, found := s.GetPodByCgroupfs(c.Name); found {\n\t\t\t\tpodName = pod.Name\n\t\t\t\tnamespace = pod.Namespace\n\t\t\t}\n\t\t}\n\t\tset := map[string]string{\n\t\t\tmetrics.LabelID: c.Name,\n\t\t\tmetrics.LabelName: name,\n\t\t\tmetrics.LabelImage: image,\n\t\t\t\"pod\": podName,\n\t\t\t\"namespace\": namespace,\n\t\t\t\"container\": containerName,\n\t\t}\n\t\treturn set\n\t}\n}","line":{"from":1109,"to":1145}} {"id":100007553,"name":"newFsResourceAnalyzer","signature":"func newFsResourceAnalyzer(statsProvider Provider, calcVolumePeriod time.Duration, eventRecorder record.EventRecorder) *fsResourceAnalyzer","file":"pkg/kubelet/server/stats/fs_resource_analyzer.go","code":"// newFsResourceAnalyzer returns a new fsResourceAnalyzer implementation\nfunc newFsResourceAnalyzer(statsProvider Provider, calcVolumePeriod time.Duration, eventRecorder record.EventRecorder) *fsResourceAnalyzer {\n\tr := \u0026fsResourceAnalyzer{\n\t\tstatsProvider: statsProvider,\n\t\tcalcPeriod: calcVolumePeriod,\n\t\teventRecorder: eventRecorder,\n\t}\n\tr.cachedVolumeStats.Store(make(statCache))\n\treturn r\n}","line":{"from":49,"to":58}} {"id":100007554,"name":"Start","signature":"func (s *fsResourceAnalyzer) Start()","file":"pkg/kubelet/server/stats/fs_resource_analyzer.go","code":"// Start eager background caching of volume stats.\nfunc (s *fsResourceAnalyzer) Start() {\n\ts.startOnce.Do(func() {\n\t\tif s.calcPeriod \u003c= 0 {\n\t\t\tklog.InfoS(\"Volume stats collection disabled\")\n\t\t\treturn\n\t\t}\n\t\tklog.InfoS(\"Starting FS ResourceAnalyzer\")\n\t\tgo wait.Forever(func() { s.updateCachedPodVolumeStats() }, s.calcPeriod)\n\t})\n}","line":{"from":60,"to":70}} {"id":100007555,"name":"updateCachedPodVolumeStats","signature":"func (s *fsResourceAnalyzer) updateCachedPodVolumeStats()","file":"pkg/kubelet/server/stats/fs_resource_analyzer.go","code":"// updateCachedPodVolumeStats calculates and caches the PodVolumeStats for every Pod known to the kubelet.\nfunc (s *fsResourceAnalyzer) updateCachedPodVolumeStats() {\n\toldCache := s.cachedVolumeStats.Load().(statCache)\n\tnewCache := make(statCache)\n\n\t// Copy existing entries to new map, creating/starting new entries for pods missing from the cache\n\tfor _, pod := range s.statsProvider.GetPods() {\n\t\tif value, found := oldCache[pod.GetUID()]; !found {\n\t\t\tnewCache[pod.GetUID()] = newVolumeStatCalculator(s.statsProvider, s.calcPeriod, pod, s.eventRecorder).StartOnce()\n\t\t} else {\n\t\t\tnewCache[pod.GetUID()] = value\n\t\t}\n\t}\n\n\t// Stop entries for pods that have been deleted\n\tfor uid, entry := range oldCache {\n\t\tif _, found := newCache[uid]; !found {\n\t\t\tentry.StopOnce()\n\t\t}\n\t}\n\n\t// Update the cache reference\n\ts.cachedVolumeStats.Store(newCache)\n}","line":{"from":72,"to":95}} {"id":100007556,"name":"GetPodVolumeStats","signature":"func (s *fsResourceAnalyzer) GetPodVolumeStats(uid types.UID) (PodVolumeStats, bool)","file":"pkg/kubelet/server/stats/fs_resource_analyzer.go","code":"// GetPodVolumeStats returns the PodVolumeStats for a given pod. Results are looked up from a cache that\n// is eagerly populated in the background, and never calculated on the fly.\nfunc (s *fsResourceAnalyzer) GetPodVolumeStats(uid types.UID) (PodVolumeStats, bool) {\n\tcache := s.cachedVolumeStats.Load().(statCache)\n\tstatCalc, found := cache[uid]\n\tif !found {\n\t\t// TODO: Differentiate between stats being empty\n\t\t// See issue #20679\n\t\treturn PodVolumeStats{}, false\n\t}\n\treturn statCalc.GetLatest()\n}","line":{"from":97,"to":108}} {"id":100007557,"name":"CreateHandlers","signature":"func CreateHandlers(rootPath string, provider Provider, summaryProvider SummaryProvider) *restful.WebService","file":"pkg/kubelet/server/stats/handler.go","code":"// CreateHandlers creates the REST handlers for the stats.\nfunc CreateHandlers(rootPath string, provider Provider, summaryProvider SummaryProvider) *restful.WebService {\n\th := \u0026handler{provider, summaryProvider}\n\n\tws := \u0026restful.WebService{}\n\tws.Path(rootPath).\n\t\tProduces(restful.MIME_JSON)\n\n\tendpoints := []struct {\n\t\tpath string\n\t\thandler restful.RouteFunction\n\t}{\n\t\t{\"/summary\", h.handleSummary},\n\t}\n\n\tfor _, e := range endpoints {\n\t\tfor _, method := range []string{\"GET\", \"POST\"} {\n\t\t\tws.Route(ws.\n\t\t\t\tMethod(method).\n\t\t\t\tPath(e.path).\n\t\t\t\tTo(e.handler))\n\t\t}\n\t}\n\n\treturn ws\n}","line":{"from":114,"to":139}} {"id":100007558,"name":"handleSummary","signature":"func (h *handler) handleSummary(request *restful.Request, response *restful.Response)","file":"pkg/kubelet/server/stats/handler.go","code":"// Handles stats summary requests to /stats/summary\n// If \"only_cpu_and_memory\" GET param is true then only cpu and memory is returned in response.\nfunc (h *handler) handleSummary(request *restful.Request, response *restful.Response) {\n\tctx := request.Request.Context()\n\tonlyCPUAndMemory := false\n\terr := request.Request.ParseForm()\n\tif err != nil {\n\t\thandleError(response, \"/stats/summary\", fmt.Errorf(\"parse form failed: %w\", err))\n\t\treturn\n\t}\n\tif onlyCluAndMemoryParam, found := request.Request.Form[\"only_cpu_and_memory\"]; found \u0026\u0026\n\t\tlen(onlyCluAndMemoryParam) == 1 \u0026\u0026 onlyCluAndMemoryParam[0] == \"true\" {\n\t\tonlyCPUAndMemory = true\n\t}\n\tvar summary *statsapi.Summary\n\tif onlyCPUAndMemory {\n\t\tsummary, err = h.summaryProvider.GetCPUAndMemoryStats(ctx)\n\t} else {\n\t\t// external calls to the summary API use cached stats\n\t\tforceStatsUpdate := false\n\t\tsummary, err = h.summaryProvider.Get(ctx, forceStatsUpdate)\n\t}\n\tif err != nil {\n\t\thandleError(response, \"/stats/summary\", err)\n\t} else {\n\t\twriteResponse(response, summary)\n\t}\n}","line":{"from":141,"to":168}} {"id":100007559,"name":"writeResponse","signature":"func writeResponse(response *restful.Response, stats interface{})","file":"pkg/kubelet/server/stats/handler.go","code":"func writeResponse(response *restful.Response, stats interface{}) {\n\tif err := response.WriteAsJson(stats); err != nil {\n\t\tklog.ErrorS(err, \"Error writing response\")\n\t}\n}","line":{"from":170,"to":174}} {"id":100007560,"name":"handleError","signature":"func handleError(response *restful.Response, request string, err error)","file":"pkg/kubelet/server/stats/handler.go","code":"// handleError serializes an error object into an HTTP response.\n// request is provided for logging.\nfunc handleError(response *restful.Response, request string, err error) {\n\tswitch err {\n\tcase kubecontainer.ErrContainerNotFound:\n\t\tresponse.WriteError(http.StatusNotFound, err)\n\tdefault:\n\t\tmsg := fmt.Sprintf(\"Internal Error: %v\", err)\n\t\tklog.ErrorS(err, \"HTTP InternalServerError serving\", \"request\", request)\n\t\tresponse.WriteErrorString(http.StatusInternalServerError, msg)\n\t}\n}","line":{"from":176,"to":187}} {"id":100007561,"name":"NewResourceAnalyzer","signature":"func NewResourceAnalyzer(statsProvider Provider, calVolumeFrequency time.Duration, eventRecorder record.EventRecorder) ResourceAnalyzer","file":"pkg/kubelet/server/stats/resource_analyzer.go","code":"// NewResourceAnalyzer returns a new ResourceAnalyzer\nfunc NewResourceAnalyzer(statsProvider Provider, calVolumeFrequency time.Duration, eventRecorder record.EventRecorder) ResourceAnalyzer {\n\tfsAnalyzer := newFsResourceAnalyzer(statsProvider, calVolumeFrequency, eventRecorder)\n\tsummaryProvider := NewSummaryProvider(statsProvider)\n\treturn \u0026resourceAnalyzer{fsAnalyzer, summaryProvider}\n}","line":{"from":40,"to":45}} {"id":100007562,"name":"Start","signature":"func (ra *resourceAnalyzer) Start()","file":"pkg/kubelet/server/stats/resource_analyzer.go","code":"// Start starts background functions necessary for the ResourceAnalyzer to function\nfunc (ra *resourceAnalyzer) Start() {\n\tra.fsResourceAnalyzer.Start()\n}","line":{"from":47,"to":50}} {"id":100007563,"name":"NewSummaryProvider","signature":"func NewSummaryProvider(statsProvider Provider) SummaryProvider","file":"pkg/kubelet/server/stats/summary.go","code":"// NewSummaryProvider returns a SummaryProvider using the stats provided by the\n// specified statsProvider.\nfunc NewSummaryProvider(statsProvider Provider) SummaryProvider {\n\tkubeletCreationTime := metav1.Now()\n\tbootTime, err := util.GetBootTime()\n\tif err != nil {\n\t\t// bootTime will be zero if we encounter an error getting the boot time.\n\t\tklog.InfoS(\"Error getting system boot time. Node metrics will have an incorrect start time\", \"err\", err)\n\t}\n\n\treturn \u0026summaryProviderImpl{\n\t\tkubeletCreationTime: kubeletCreationTime,\n\t\tsystemBootTime: metav1.NewTime(bootTime),\n\t\tprovider: statsProvider,\n\t}\n}","line":{"from":52,"to":67}} {"id":100007564,"name":"Get","signature":"func (sp *summaryProviderImpl) Get(ctx context.Context, updateStats bool) (*statsapi.Summary, error)","file":"pkg/kubelet/server/stats/summary.go","code":"func (sp *summaryProviderImpl) Get(ctx context.Context, updateStats bool) (*statsapi.Summary, error) {\n\t// TODO(timstclair): Consider returning a best-effort response if any of\n\t// the following errors occur.\n\tnode, err := sp.provider.GetNode()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get node info: %v\", err)\n\t}\n\tnodeConfig := sp.provider.GetNodeConfig()\n\trootStats, networkStats, err := sp.provider.GetCgroupStats(\"/\", updateStats)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get root cgroup stats: %v\", err)\n\t}\n\trootFsStats, err := sp.provider.RootFsStats()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get rootFs stats: %v\", err)\n\t}\n\timageFsStats, err := sp.provider.ImageFsStats(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get imageFs stats: %v\", err)\n\t}\n\tvar podStats []statsapi.PodStats\n\tif updateStats {\n\t\tpodStats, err = sp.provider.ListPodStatsAndUpdateCPUNanoCoreUsage(ctx)\n\t} else {\n\t\tpodStats, err = sp.provider.ListPodStats(ctx)\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to list pod stats: %v\", err)\n\t}\n\n\trlimit, err := sp.provider.RlimitStats()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get rlimit stats: %v\", err)\n\t}\n\n\tnodeStats := statsapi.NodeStats{\n\t\tNodeName: node.Name,\n\t\tCPU: rootStats.CPU,\n\t\tMemory: rootStats.Memory,\n\t\tNetwork: networkStats,\n\t\tStartTime: sp.systemBootTime,\n\t\tFs: rootFsStats,\n\t\tRuntime: \u0026statsapi.RuntimeStats{ImageFs: imageFsStats},\n\t\tRlimit: rlimit,\n\t\tSystemContainers: sp.GetSystemContainersStats(nodeConfig, podStats, updateStats),\n\t}\n\tsummary := statsapi.Summary{\n\t\tNode: nodeStats,\n\t\tPods: podStats,\n\t}\n\treturn \u0026summary, nil\n}","line":{"from":69,"to":120}} {"id":100007565,"name":"GetCPUAndMemoryStats","signature":"func (sp *summaryProviderImpl) GetCPUAndMemoryStats(ctx context.Context) (*statsapi.Summary, error)","file":"pkg/kubelet/server/stats/summary.go","code":"func (sp *summaryProviderImpl) GetCPUAndMemoryStats(ctx context.Context) (*statsapi.Summary, error) {\n\t// TODO(timstclair): Consider returning a best-effort response if any of\n\t// the following errors occur.\n\tnode, err := sp.provider.GetNode()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get node info: %v\", err)\n\t}\n\tnodeConfig := sp.provider.GetNodeConfig()\n\trootStats, err := sp.provider.GetCgroupCPUAndMemoryStats(\"/\", false)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get root cgroup stats: %v\", err)\n\t}\n\n\tpodStats, err := sp.provider.ListPodCPUAndMemoryStats(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to list pod stats: %v\", err)\n\t}\n\n\tnodeStats := statsapi.NodeStats{\n\t\tNodeName: node.Name,\n\t\tCPU: rootStats.CPU,\n\t\tMemory: rootStats.Memory,\n\t\tStartTime: rootStats.StartTime,\n\t\tSystemContainers: sp.GetSystemContainersCPUAndMemoryStats(nodeConfig, podStats, false),\n\t}\n\tsummary := statsapi.Summary{\n\t\tNode: nodeStats,\n\t\tPods: podStats,\n\t}\n\treturn \u0026summary, nil\n}","line":{"from":122,"to":152}} {"id":100007566,"name":"GetSystemContainersStats","signature":"func (sp *summaryProviderImpl) GetSystemContainersStats(nodeConfig cm.NodeConfig, podStats []statsapi.PodStats, updateStats bool) (stats []statsapi.ContainerStats)","file":"pkg/kubelet/server/stats/summary_sys_containers.go","code":"func (sp *summaryProviderImpl) GetSystemContainersStats(nodeConfig cm.NodeConfig, podStats []statsapi.PodStats, updateStats bool) (stats []statsapi.ContainerStats) {\n\tsystemContainers := map[string]struct {\n\t\tname string\n\t\tforceStatsUpdate bool\n\t\tstartTime metav1.Time\n\t}{\n\t\tstatsapi.SystemContainerKubelet: {name: nodeConfig.KubeletCgroupsName, forceStatsUpdate: false, startTime: sp.kubeletCreationTime},\n\t\tstatsapi.SystemContainerRuntime: {name: nodeConfig.RuntimeCgroupsName, forceStatsUpdate: false},\n\t\tstatsapi.SystemContainerMisc: {name: nodeConfig.SystemCgroupsName, forceStatsUpdate: false},\n\t\tstatsapi.SystemContainerPods: {name: sp.provider.GetPodCgroupRoot(), forceStatsUpdate: updateStats},\n\t}\n\tfor sys, cont := range systemContainers {\n\t\t// skip if cgroup name is undefined (not all system containers are required)\n\t\tif cont.name == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\ts, _, err := sp.provider.GetCgroupStats(cont.name, cont.forceStatsUpdate)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to get system container stats\", \"containerName\", cont.name)\n\t\t\tcontinue\n\t\t}\n\t\t// System containers don't have a filesystem associated with them.\n\t\ts.Logs, s.Rootfs = nil, nil\n\t\ts.Name = sys\n\n\t\t// if we know the start time of a system container, use that instead of the start time provided by cAdvisor\n\t\tif !cont.startTime.IsZero() {\n\t\t\ts.StartTime = cont.startTime\n\t\t}\n\t\tstats = append(stats, *s)\n\t}\n\n\treturn stats\n}","line":{"from":30,"to":63}} {"id":100007567,"name":"GetSystemContainersCPUAndMemoryStats","signature":"func (sp *summaryProviderImpl) GetSystemContainersCPUAndMemoryStats(nodeConfig cm.NodeConfig, podStats []statsapi.PodStats, updateStats bool) (stats []statsapi.ContainerStats)","file":"pkg/kubelet/server/stats/summary_sys_containers.go","code":"func (sp *summaryProviderImpl) GetSystemContainersCPUAndMemoryStats(nodeConfig cm.NodeConfig, podStats []statsapi.PodStats, updateStats bool) (stats []statsapi.ContainerStats) {\n\tsystemContainers := map[string]struct {\n\t\tname string\n\t\tforceStatsUpdate bool\n\t\tstartTime metav1.Time\n\t}{\n\t\tstatsapi.SystemContainerKubelet: {name: nodeConfig.KubeletCgroupsName, forceStatsUpdate: false, startTime: sp.kubeletCreationTime},\n\t\tstatsapi.SystemContainerRuntime: {name: nodeConfig.RuntimeCgroupsName, forceStatsUpdate: false},\n\t\tstatsapi.SystemContainerMisc: {name: nodeConfig.SystemCgroupsName, forceStatsUpdate: false},\n\t\tstatsapi.SystemContainerPods: {name: sp.provider.GetPodCgroupRoot(), forceStatsUpdate: updateStats},\n\t}\n\tfor sys, cont := range systemContainers {\n\t\t// skip if cgroup name is undefined (not all system containers are required)\n\t\tif cont.name == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\ts, err := sp.provider.GetCgroupCPUAndMemoryStats(cont.name, cont.forceStatsUpdate)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to get system container stats\", \"containerName\", cont.name)\n\t\t\tcontinue\n\t\t}\n\t\ts.Name = sys\n\n\t\t// if we know the start time of a system container, use that instead of the start time provided by cAdvisor\n\t\tif !cont.startTime.IsZero() {\n\t\t\ts.StartTime = cont.startTime\n\t\t}\n\t\tstats = append(stats, *s)\n\t}\n\n\treturn stats\n}","line":{"from":65,"to":96}} {"id":100007568,"name":"GetSystemContainersStats","signature":"func (sp *summaryProviderImpl) GetSystemContainersStats(nodeConfig cm.NodeConfig, podStats []statsapi.PodStats, updateStats bool) (stats []statsapi.ContainerStats)","file":"pkg/kubelet/server/stats/summary_sys_containers_windows.go","code":"func (sp *summaryProviderImpl) GetSystemContainersStats(nodeConfig cm.NodeConfig, podStats []statsapi.PodStats, updateStats bool) (stats []statsapi.ContainerStats) {\n\tstats = append(stats, sp.getSystemPodsCPUAndMemoryStats(nodeConfig, podStats, updateStats))\n\treturn stats\n}","line":{"from":30,"to":33}} {"id":100007569,"name":"GetSystemContainersCPUAndMemoryStats","signature":"func (sp *summaryProviderImpl) GetSystemContainersCPUAndMemoryStats(nodeConfig cm.NodeConfig, podStats []statsapi.PodStats, updateStats bool) (stats []statsapi.ContainerStats)","file":"pkg/kubelet/server/stats/summary_sys_containers_windows.go","code":"func (sp *summaryProviderImpl) GetSystemContainersCPUAndMemoryStats(nodeConfig cm.NodeConfig, podStats []statsapi.PodStats, updateStats bool) (stats []statsapi.ContainerStats) {\n\tstats = append(stats, sp.getSystemPodsCPUAndMemoryStats(nodeConfig, podStats, updateStats))\n\treturn stats\n}","line":{"from":35,"to":38}} {"id":100007570,"name":"getSystemPodsCPUAndMemoryStats","signature":"func (sp *summaryProviderImpl) getSystemPodsCPUAndMemoryStats(nodeConfig cm.NodeConfig, podStats []statsapi.PodStats, updateStats bool) statsapi.ContainerStats","file":"pkg/kubelet/server/stats/summary_sys_containers_windows.go","code":"func (sp *summaryProviderImpl) getSystemPodsCPUAndMemoryStats(nodeConfig cm.NodeConfig, podStats []statsapi.PodStats, updateStats bool) statsapi.ContainerStats {\n\tnow := metav1.NewTime(time.Now())\n\tpodsSummary := statsapi.ContainerStats{\n\t\tStartTime: now,\n\t\tCPU: \u0026statsapi.CPUStats{},\n\t\tMemory: \u0026statsapi.MemoryStats{},\n\t\tName: statsapi.SystemContainerPods,\n\t}\n\n\t// Sum up all pod's stats.\n\tvar usageCoreNanoSeconds uint64\n\tvar usageNanoCores uint64\n\tvar availableBytes uint64\n\tvar usageBytes uint64\n\tvar workingSetBytes uint64\n\tfor _, pod := range podStats {\n\t\tif pod.CPU != nil {\n\t\t\tpodsSummary.CPU.Time = now\n\t\t\tif pod.CPU.UsageCoreNanoSeconds != nil {\n\t\t\t\tusageCoreNanoSeconds = usageCoreNanoSeconds + *pod.CPU.UsageCoreNanoSeconds\n\t\t\t}\n\t\t\tif pod.CPU.UsageNanoCores != nil {\n\t\t\t\tusageNanoCores = usageNanoCores + *pod.CPU.UsageNanoCores\n\t\t\t}\n\t\t}\n\n\t\tif pod.Memory != nil {\n\t\t\tpodsSummary.Memory.Time = now\n\t\t\tif pod.Memory.AvailableBytes != nil {\n\t\t\t\tavailableBytes = availableBytes + *pod.Memory.AvailableBytes\n\t\t\t}\n\t\t\tif pod.Memory.UsageBytes != nil {\n\t\t\t\tusageBytes = usageBytes + *pod.Memory.UsageBytes\n\t\t\t}\n\t\t\tif pod.Memory.WorkingSetBytes != nil {\n\t\t\t\tworkingSetBytes = workingSetBytes + *pod.Memory.WorkingSetBytes\n\t\t\t}\n\t\t}\n\t}\n\n\t// Set results only if they are not zero.\n\tif usageCoreNanoSeconds != 0 {\n\t\tpodsSummary.CPU.UsageCoreNanoSeconds = \u0026usageCoreNanoSeconds\n\t}\n\tif usageNanoCores != 0 {\n\t\tpodsSummary.CPU.UsageNanoCores = \u0026usageNanoCores\n\t}\n\tif availableBytes != 0 {\n\t\tpodsSummary.Memory.AvailableBytes = \u0026availableBytes\n\t}\n\tif usageBytes != 0 {\n\t\tpodsSummary.Memory.UsageBytes = \u0026usageBytes\n\t}\n\tif workingSetBytes != 0 {\n\t\tpodsSummary.Memory.WorkingSetBytes = \u0026workingSetBytes\n\t}\n\n\treturn podsSummary\n}","line":{"from":40,"to":98}} {"id":100007571,"name":"newVolumeStatCalculator","signature":"func newVolumeStatCalculator(statsProvider Provider, jitterPeriod time.Duration, pod *v1.Pod, eventRecorder record.EventRecorder) *volumeStatCalculator","file":"pkg/kubelet/server/stats/volume_stat_calculator.go","code":"// newVolumeStatCalculator creates a new VolumeStatCalculator\nfunc newVolumeStatCalculator(statsProvider Provider, jitterPeriod time.Duration, pod *v1.Pod, eventRecorder record.EventRecorder) *volumeStatCalculator {\n\treturn \u0026volumeStatCalculator{\n\t\tstatsProvider: statsProvider,\n\t\tjitterPeriod: jitterPeriod,\n\t\tpod: pod,\n\t\tstopChannel: make(chan struct{}),\n\t\teventRecorder: eventRecorder,\n\t}\n}","line":{"from":57,"to":66}} {"id":100007572,"name":"StartOnce","signature":"func (s *volumeStatCalculator) StartOnce() *volumeStatCalculator","file":"pkg/kubelet/server/stats/volume_stat_calculator.go","code":"// StartOnce starts pod volume calc that will occur periodically in the background until s.StopOnce is called\nfunc (s *volumeStatCalculator) StartOnce() *volumeStatCalculator {\n\ts.startO.Do(func() {\n\t\tgo wait.JitterUntil(func() {\n\t\t\ts.calcAndStoreStats()\n\t\t}, s.jitterPeriod, 1.0, true, s.stopChannel)\n\t})\n\treturn s\n}","line":{"from":68,"to":76}} {"id":100007573,"name":"StopOnce","signature":"func (s *volumeStatCalculator) StopOnce() *volumeStatCalculator","file":"pkg/kubelet/server/stats/volume_stat_calculator.go","code":"// StopOnce stops background pod volume calculation. Will not stop a currently executing calculations until\n// they complete their current iteration.\nfunc (s *volumeStatCalculator) StopOnce() *volumeStatCalculator {\n\ts.stopO.Do(func() {\n\t\tclose(s.stopChannel)\n\t})\n\treturn s\n}","line":{"from":78,"to":85}} {"id":100007574,"name":"GetLatest","signature":"func (s *volumeStatCalculator) GetLatest() (PodVolumeStats, bool)","file":"pkg/kubelet/server/stats/volume_stat_calculator.go","code":"// getLatest returns the most recent PodVolumeStats from the cache\nfunc (s *volumeStatCalculator) GetLatest() (PodVolumeStats, bool) {\n\tresult := s.latest.Load()\n\tif result == nil {\n\t\treturn PodVolumeStats{}, false\n\t}\n\treturn result.(PodVolumeStats), true\n}","line":{"from":87,"to":94}} {"id":100007575,"name":"calcAndStoreStats","signature":"func (s *volumeStatCalculator) calcAndStoreStats()","file":"pkg/kubelet/server/stats/volume_stat_calculator.go","code":"// calcAndStoreStats calculates PodVolumeStats for a given pod and writes the result to the s.latest cache.\n// If the pod references PVCs, the prometheus metrics for those are updated with the result.\nfunc (s *volumeStatCalculator) calcAndStoreStats() {\n\t// Find all Volumes for the Pod\n\tvolumes, found := s.statsProvider.ListVolumesForPod(s.pod.UID)\n\tblockVolumes, bvFound := s.statsProvider.ListBlockVolumesForPod(s.pod.UID)\n\tif !found \u0026\u0026 !bvFound {\n\t\treturn\n\t}\n\n\tmetricVolumes := make(map[string]volume.MetricsProvider)\n\n\tif found {\n\t\tfor name, v := range volumes {\n\t\t\tmetricVolumes[name] = v\n\t\t}\n\t}\n\tif bvFound {\n\t\tfor name, v := range blockVolumes {\n\t\t\t// Only add the blockVolume if it implements the MetricsProvider interface\n\t\t\tif _, ok := v.(volume.MetricsProvider); ok {\n\t\t\t\t// Some drivers inherit the MetricsProvider interface from Filesystem\n\t\t\t\t// mode volumes, but do not implement it for Block mode. Checking\n\t\t\t\t// SupportsMetrics() will prevent panics in that case.\n\t\t\t\tif v.SupportsMetrics() {\n\t\t\t\t\tmetricVolumes[name] = v\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Get volume specs for the pod - key'd by volume name\n\tvolumesSpec := make(map[string]v1.Volume)\n\tfor _, v := range s.pod.Spec.Volumes {\n\t\tvolumesSpec[v.Name] = v\n\t}\n\n\t// Call GetMetrics on each Volume and copy the result to a new VolumeStats.FsStats\n\tvar ephemeralStats []stats.VolumeStats\n\tvar persistentStats []stats.VolumeStats\n\tfor name, v := range metricVolumes {\n\t\tmetric, err := func() (*volume.Metrics, error) {\n\t\t\ttrace := utiltrace.New(fmt.Sprintf(\"Calculate volume metrics of %v for pod %v/%v\", name, s.pod.Namespace, s.pod.Name))\n\t\t\tdefer trace.LogIfLong(1 * time.Second)\n\t\t\treturn v.GetMetrics()\n\t\t}()\n\t\tif err != nil {\n\t\t\t// Expected for Volumes that don't support Metrics\n\t\t\tif !volume.IsNotSupported(err) {\n\t\t\t\tklog.V(4).InfoS(\"Failed to calculate volume metrics\", \"pod\", klog.KObj(s.pod), \"podUID\", s.pod.UID, \"volumeName\", name, \"err\", err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\t// Lookup the volume spec and add a 'PVCReference' for volumes that reference a PVC\n\t\tvolSpec := volumesSpec[name]\n\t\tvar pvcRef *stats.PVCReference\n\t\tif pvcSource := volSpec.PersistentVolumeClaim; pvcSource != nil {\n\t\t\tpvcRef = \u0026stats.PVCReference{\n\t\t\t\tName: pvcSource.ClaimName,\n\t\t\t\tNamespace: s.pod.GetNamespace(),\n\t\t\t}\n\t\t} else if volSpec.Ephemeral != nil {\n\t\t\tpvcRef = \u0026stats.PVCReference{\n\t\t\t\tName: ephemeral.VolumeClaimName(s.pod, \u0026volSpec),\n\t\t\t\tNamespace: s.pod.GetNamespace(),\n\t\t\t}\n\t\t}\n\t\tvolumeStats := s.parsePodVolumeStats(name, pvcRef, metric, volSpec)\n\t\tif util.IsLocalEphemeralVolume(volSpec) {\n\t\t\tephemeralStats = append(ephemeralStats, volumeStats)\n\t\t} else {\n\t\t\tpersistentStats = append(persistentStats, volumeStats)\n\t\t}\n\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.CSIVolumeHealth) {\n\t\t\tif metric.Abnormal != nil \u0026\u0026 metric.Message != nil \u0026\u0026 (*metric.Abnormal) {\n\t\t\t\ts.eventRecorder.Event(s.pod, v1.EventTypeWarning, \"VolumeConditionAbnormal\", fmt.Sprintf(\"Volume %s: %s\", name, *metric.Message))\n\t\t\t}\n\t\t}\n\t}\n\n\t// Store the new stats\n\ts.latest.Store(PodVolumeStats{EphemeralVolumes: ephemeralStats,\n\t\tPersistentVolumes: persistentStats})\n}","line":{"from":96,"to":180}} {"id":100007576,"name":"parsePodVolumeStats","signature":"func (s *volumeStatCalculator) parsePodVolumeStats(podName string, pvcRef *stats.PVCReference, metric *volume.Metrics, volSpec v1.Volume) stats.VolumeStats","file":"pkg/kubelet/server/stats/volume_stat_calculator.go","code":"// parsePodVolumeStats converts (internal) volume.Metrics to (external) stats.VolumeStats structures\nfunc (s *volumeStatCalculator) parsePodVolumeStats(podName string, pvcRef *stats.PVCReference, metric *volume.Metrics, volSpec v1.Volume) stats.VolumeStats {\n\n\tvar (\n\t\tavailable, capacity, used, inodes, inodesFree, inodesUsed uint64\n\t)\n\n\tif metric.Available != nil {\n\t\tavailable = uint64(metric.Available.Value())\n\t}\n\tif metric.Capacity != nil {\n\t\tcapacity = uint64(metric.Capacity.Value())\n\t}\n\tif metric.Used != nil {\n\t\tused = uint64(metric.Used.Value())\n\t}\n\tif metric.Inodes != nil {\n\t\tinodes = uint64(metric.Inodes.Value())\n\t}\n\tif metric.InodesFree != nil {\n\t\tinodesFree = uint64(metric.InodesFree.Value())\n\t}\n\tif metric.InodesUsed != nil {\n\t\tinodesUsed = uint64(metric.InodesUsed.Value())\n\t}\n\n\tvolumeStats := stats.VolumeStats{\n\t\tName: podName,\n\t\tPVCRef: pvcRef,\n\t\tFsStats: stats.FsStats{Time: metric.Time, AvailableBytes: \u0026available, CapacityBytes: \u0026capacity,\n\t\t\tUsedBytes: \u0026used, Inodes: \u0026inodes, InodesFree: \u0026inodesFree, InodesUsed: \u0026inodesUsed},\n\t}\n\n\tif metric.Abnormal != nil {\n\t\tvolumeStats.VolumeHealthStats = \u0026stats.VolumeHealthStats{\n\t\t\tAbnormal: *metric.Abnormal,\n\t\t}\n\t}\n\n\treturn volumeStats\n}","line":{"from":182,"to":222}} {"id":100007577,"name":"newCadvisorStatsProvider","signature":"func newCadvisorStatsProvider(","file":"pkg/kubelet/stats/cadvisor_stats_provider.go","code":"// newCadvisorStatsProvider returns a containerStatsProvider that provides\n// container stats from cAdvisor.\nfunc newCadvisorStatsProvider(\n\tcadvisor cadvisor.Interface,\n\tresourceAnalyzer stats.ResourceAnalyzer,\n\timageService kubecontainer.ImageService,\n\tstatusProvider status.PodStatusProvider,\n\thostStatsProvider HostStatsProvider,\n) containerStatsProvider {\n\treturn \u0026cadvisorStatsProvider{\n\t\tcadvisor: cadvisor,\n\t\tresourceAnalyzer: resourceAnalyzer,\n\t\timageService: imageService,\n\t\tstatusProvider: statusProvider,\n\t\thostStatsProvider: hostStatsProvider,\n\t}\n}","line":{"from":60,"to":76}} {"id":100007578,"name":"ListPodStats","signature":"func (p *cadvisorStatsProvider) ListPodStats(_ context.Context) ([]statsapi.PodStats, error)","file":"pkg/kubelet/stats/cadvisor_stats_provider.go","code":"// ListPodStats returns the stats of all the pod-managed containers.\nfunc (p *cadvisorStatsProvider) ListPodStats(_ context.Context) ([]statsapi.PodStats, error) {\n\t// Gets node root filesystem information and image filesystem stats, which\n\t// will be used to populate the available and capacity bytes/inodes in\n\t// container stats.\n\trootFsInfo, err := p.cadvisor.RootFsInfo()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get rootFs info: %v\", err)\n\t}\n\timageFsInfo, err := p.cadvisor.ImagesFsInfo()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get imageFs info: %v\", err)\n\t}\n\tinfos, err := getCadvisorContainerInfo(p.cadvisor)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get container info from cadvisor: %v\", err)\n\t}\n\n\tfilteredInfos, allInfos := filterTerminatedContainerInfoAndAssembleByPodCgroupKey(infos)\n\t// Map each container to a pod and update the PodStats with container data.\n\tpodToStats := map[statsapi.PodReference]*statsapi.PodStats{}\n\tfor key, cinfo := range filteredInfos {\n\t\t// On systemd using devicemapper each mount into the container has an\n\t\t// associated cgroup. We ignore them to ensure we do not get duplicate\n\t\t// entries in our summary. For details on .mount units:\n\t\t// http://man7.org/linux/man-pages/man5/systemd.mount.5.html\n\t\tif strings.HasSuffix(key, \".mount\") {\n\t\t\tcontinue\n\t\t}\n\t\t// Build the Pod key if this container is managed by a Pod\n\t\tif !isPodManagedContainer(\u0026cinfo) {\n\t\t\tcontinue\n\t\t}\n\t\tref := buildPodRef(cinfo.Spec.Labels)\n\n\t\t// Lookup the PodStats for the pod using the PodRef. If none exists,\n\t\t// initialize a new entry.\n\t\tpodStats, found := podToStats[ref]\n\t\tif !found {\n\t\t\tpodStats = \u0026statsapi.PodStats{PodRef: ref}\n\t\t\tpodToStats[ref] = podStats\n\t\t}\n\n\t\t// Update the PodStats entry with the stats from the container by\n\t\t// adding it to podStats.Containers.\n\t\tcontainerName := kubetypes.GetContainerName(cinfo.Spec.Labels)\n\t\tif containerName == leaky.PodInfraContainerName {\n\t\t\t// Special case for infrastructure container which is hidden from\n\t\t\t// the user and has network stats.\n\t\t\tpodStats.Network = cadvisorInfoToNetworkStats(\u0026cinfo)\n\t\t} else {\n\t\t\tcontainerStat := cadvisorInfoToContainerStats(containerName, \u0026cinfo, \u0026rootFsInfo, \u0026imageFsInfo)\n\t\t\t// NOTE: This doesn't support the old pod log path, `/var/log/pods/UID`. For containers\n\t\t\t// using old log path, they will be populated by cadvisorInfoToContainerStats.\n\t\t\tpodUID := types.UID(podStats.PodRef.UID)\n\t\t\tlogs, err := p.hostStatsProvider.getPodContainerLogStats(podStats.PodRef.Namespace, podStats.PodRef.Name, podUID, containerName, \u0026rootFsInfo)\n\t\t\tif err != nil {\n\t\t\t\tklog.ErrorS(err, \"Unable to fetch container log stats\", \"containerName\", containerName)\n\t\t\t} else {\n\t\t\t\tcontainerStat.Logs = logs\n\t\t\t}\n\t\t\tpodStats.Containers = append(podStats.Containers, *containerStat)\n\t\t}\n\t}\n\n\t// Add each PodStats to the result.\n\tresult := make([]statsapi.PodStats, 0, len(podToStats))\n\tfor _, podStats := range podToStats {\n\t\tmakePodStorageStats(podStats, \u0026rootFsInfo, p.resourceAnalyzer, p.hostStatsProvider, false)\n\n\t\tpodUID := types.UID(podStats.PodRef.UID)\n\t\t// Lookup the pod-level cgroup's CPU and memory stats\n\t\tpodInfo := getCadvisorPodInfoFromPodUID(podUID, allInfos)\n\t\tif podInfo != nil {\n\t\t\tcpu, memory := cadvisorInfoToCPUandMemoryStats(podInfo)\n\t\t\tpodStats.CPU = cpu\n\t\t\tpodStats.Memory = memory\n\t\t\tpodStats.ProcessStats = cadvisorInfoToProcessStats(podInfo)\n\t\t}\n\n\t\tstatus, found := p.statusProvider.GetPodStatus(podUID)\n\t\tif found \u0026\u0026 status.StartTime != nil \u0026\u0026 !status.StartTime.IsZero() {\n\t\t\tpodStats.StartTime = *status.StartTime\n\t\t\t// only append stats if we were able to get the start time of the pod\n\t\t\tresult = append(result, *podStats)\n\t\t}\n\t}\n\n\treturn result, nil\n}","line":{"from":78,"to":167}} {"id":100007579,"name":"ListPodStatsAndUpdateCPUNanoCoreUsage","signature":"func (p *cadvisorStatsProvider) ListPodStatsAndUpdateCPUNanoCoreUsage(ctx context.Context) ([]statsapi.PodStats, error)","file":"pkg/kubelet/stats/cadvisor_stats_provider.go","code":"// ListPodStatsAndUpdateCPUNanoCoreUsage updates the cpu nano core usage for\n// the containers and returns the stats for all the pod-managed containers.\n// For cadvisor, cpu nano core usages are pre-computed and cached, so this\n// function simply calls ListPodStats.\nfunc (p *cadvisorStatsProvider) ListPodStatsAndUpdateCPUNanoCoreUsage(ctx context.Context) ([]statsapi.PodStats, error) {\n\treturn p.ListPodStats(ctx)\n}","line":{"from":169,"to":175}} {"id":100007580,"name":"ListPodCPUAndMemoryStats","signature":"func (p *cadvisorStatsProvider) ListPodCPUAndMemoryStats(_ context.Context) ([]statsapi.PodStats, error)","file":"pkg/kubelet/stats/cadvisor_stats_provider.go","code":"// ListPodCPUAndMemoryStats returns the cpu and memory stats of all the pod-managed containers.\nfunc (p *cadvisorStatsProvider) ListPodCPUAndMemoryStats(_ context.Context) ([]statsapi.PodStats, error) {\n\tinfos, err := getCadvisorContainerInfo(p.cadvisor)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get container info from cadvisor: %v\", err)\n\t}\n\tfilteredInfos, allInfos := filterTerminatedContainerInfoAndAssembleByPodCgroupKey(infos)\n\t// Map each container to a pod and update the PodStats with container data.\n\tpodToStats := map[statsapi.PodReference]*statsapi.PodStats{}\n\tfor key, cinfo := range filteredInfos {\n\t\t// On systemd using devicemapper each mount into the container has an\n\t\t// associated cgroup. We ignore them to ensure we do not get duplicate\n\t\t// entries in our summary. For details on .mount units:\n\t\t// http://man7.org/linux/man-pages/man5/systemd.mount.5.html\n\t\tif strings.HasSuffix(key, \".mount\") {\n\t\t\tcontinue\n\t\t}\n\t\t// Build the Pod key if this container is managed by a Pod\n\t\tif !isPodManagedContainer(\u0026cinfo) {\n\t\t\tcontinue\n\t\t}\n\t\tref := buildPodRef(cinfo.Spec.Labels)\n\n\t\t// Lookup the PodStats for the pod using the PodRef. If none exists,\n\t\t// initialize a new entry.\n\t\tpodStats, found := podToStats[ref]\n\t\tif !found {\n\t\t\tpodStats = \u0026statsapi.PodStats{PodRef: ref}\n\t\t\tpodToStats[ref] = podStats\n\t\t}\n\n\t\t// Update the PodStats entry with the stats from the container by\n\t\t// adding it to podStats.Containers.\n\t\tcontainerName := kubetypes.GetContainerName(cinfo.Spec.Labels)\n\t\tif containerName == leaky.PodInfraContainerName {\n\t\t\t// Special case for infrastructure container which is hidden from\n\t\t\t// the user and has network stats.\n\t\t\tpodStats.StartTime = metav1.NewTime(cinfo.Spec.CreationTime)\n\t\t} else {\n\t\t\tpodStats.Containers = append(podStats.Containers, *cadvisorInfoToContainerCPUAndMemoryStats(containerName, \u0026cinfo))\n\t\t}\n\t}\n\n\t// Add each PodStats to the result.\n\tresult := make([]statsapi.PodStats, 0, len(podToStats))\n\tfor _, podStats := range podToStats {\n\t\tpodUID := types.UID(podStats.PodRef.UID)\n\t\t// Lookup the pod-level cgroup's CPU and memory stats\n\t\tpodInfo := getCadvisorPodInfoFromPodUID(podUID, allInfos)\n\t\tif podInfo != nil {\n\t\t\tcpu, memory := cadvisorInfoToCPUandMemoryStats(podInfo)\n\t\t\tpodStats.CPU = cpu\n\t\t\tpodStats.Memory = memory\n\t\t}\n\t\tresult = append(result, *podStats)\n\t}\n\n\treturn result, nil\n}","line":{"from":177,"to":235}} {"id":100007581,"name":"ImageFsStats","signature":"func (p *cadvisorStatsProvider) ImageFsStats(ctx context.Context) (*statsapi.FsStats, error)","file":"pkg/kubelet/stats/cadvisor_stats_provider.go","code":"// ImageFsStats returns the stats of the filesystem for storing images.\nfunc (p *cadvisorStatsProvider) ImageFsStats(ctx context.Context) (*statsapi.FsStats, error) {\n\timageFsInfo, err := p.cadvisor.ImagesFsInfo()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get imageFs info: %v\", err)\n\t}\n\timageStats, err := p.imageService.ImageStats(ctx)\n\tif err != nil || imageStats == nil {\n\t\treturn nil, fmt.Errorf(\"failed to get image stats: %v\", err)\n\t}\n\n\tvar imageFsInodesUsed *uint64\n\tif imageFsInfo.Inodes != nil \u0026\u0026 imageFsInfo.InodesFree != nil {\n\t\timageFsIU := *imageFsInfo.Inodes - *imageFsInfo.InodesFree\n\t\timageFsInodesUsed = \u0026imageFsIU\n\t}\n\n\treturn \u0026statsapi.FsStats{\n\t\tTime: metav1.NewTime(imageFsInfo.Timestamp),\n\t\tAvailableBytes: \u0026imageFsInfo.Available,\n\t\tCapacityBytes: \u0026imageFsInfo.Capacity,\n\t\tUsedBytes: \u0026imageStats.TotalStorageBytes,\n\t\tInodesFree: imageFsInfo.InodesFree,\n\t\tInodes: imageFsInfo.Inodes,\n\t\tInodesUsed: imageFsInodesUsed,\n\t}, nil\n}","line":{"from":237,"to":263}} {"id":100007582,"name":"ImageFsDevice","signature":"func (p *cadvisorStatsProvider) ImageFsDevice(_ context.Context) (string, error)","file":"pkg/kubelet/stats/cadvisor_stats_provider.go","code":"// ImageFsDevice returns name of the device where the image filesystem locates,\n// e.g. /dev/sda1.\nfunc (p *cadvisorStatsProvider) ImageFsDevice(_ context.Context) (string, error) {\n\timageFsInfo, err := p.cadvisor.ImagesFsInfo()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn imageFsInfo.Device, nil\n}","line":{"from":265,"to":273}} {"id":100007583,"name":"buildPodRef","signature":"func buildPodRef(containerLabels map[string]string) statsapi.PodReference","file":"pkg/kubelet/stats/cadvisor_stats_provider.go","code":"// buildPodRef returns a PodReference that identifies the Pod managing cinfo\nfunc buildPodRef(containerLabels map[string]string) statsapi.PodReference {\n\tpodName := kubetypes.GetPodName(containerLabels)\n\tpodNamespace := kubetypes.GetPodNamespace(containerLabels)\n\tpodUID := kubetypes.GetPodUID(containerLabels)\n\treturn statsapi.PodReference{Name: podName, Namespace: podNamespace, UID: podUID}\n}","line":{"from":275,"to":281}} {"id":100007584,"name":"isPodManagedContainer","signature":"func isPodManagedContainer(cinfo *cadvisorapiv2.ContainerInfo) bool","file":"pkg/kubelet/stats/cadvisor_stats_provider.go","code":"// isPodManagedContainer returns true if the cinfo container is managed by a Pod\nfunc isPodManagedContainer(cinfo *cadvisorapiv2.ContainerInfo) bool {\n\tpodName := kubetypes.GetPodName(cinfo.Spec.Labels)\n\tpodNamespace := kubetypes.GetPodNamespace(cinfo.Spec.Labels)\n\tmanaged := podName != \"\" \u0026\u0026 podNamespace != \"\"\n\tif !managed \u0026\u0026 podName != podNamespace {\n\t\tklog.InfoS(\n\t\t\t\"Expect container to have either both podName and podNamespace labels, or neither\",\n\t\t\t\"podNameLabel\", podName, \"podNamespaceLabel\", podNamespace)\n\t}\n\treturn managed\n}","line":{"from":283,"to":294}} {"id":100007585,"name":"getCadvisorPodInfoFromPodUID","signature":"func getCadvisorPodInfoFromPodUID(podUID types.UID, infos map[string]cadvisorapiv2.ContainerInfo) *cadvisorapiv2.ContainerInfo","file":"pkg/kubelet/stats/cadvisor_stats_provider.go","code":"// getCadvisorPodInfoFromPodUID returns a pod cgroup information by matching the podUID with its CgroupName identifier base name\nfunc getCadvisorPodInfoFromPodUID(podUID types.UID, infos map[string]cadvisorapiv2.ContainerInfo) *cadvisorapiv2.ContainerInfo {\n\tif info, found := infos[cm.GetPodCgroupNameSuffix(podUID)]; found {\n\t\treturn \u0026info\n\t}\n\treturn nil\n}","line":{"from":296,"to":302}} {"id":100007586,"name":"filterTerminatedContainerInfoAndAssembleByPodCgroupKey","signature":"func filterTerminatedContainerInfoAndAssembleByPodCgroupKey(containerInfo map[string]cadvisorapiv2.ContainerInfo) (map[string]cadvisorapiv2.ContainerInfo, map[string]cadvisorapiv2.ContainerInfo)","file":"pkg/kubelet/stats/cadvisor_stats_provider.go","code":"// filterTerminatedContainerInfoAndAssembleByPodCgroupKey returns the specified containerInfo but with\n// the stats of the terminated containers removed and all containerInfos assembled by pod cgroup key.\n// the first return map is container cgroup name \u003c-\u003e ContainerInfo and\n// the second return map is pod cgroup key \u003c-\u003e ContainerInfo.\n// A ContainerInfo is considered to be of a terminated container if it has an\n// older CreationTime and zero CPU instantaneous and memory RSS usage.\nfunc filterTerminatedContainerInfoAndAssembleByPodCgroupKey(containerInfo map[string]cadvisorapiv2.ContainerInfo) (map[string]cadvisorapiv2.ContainerInfo, map[string]cadvisorapiv2.ContainerInfo) {\n\tcinfoMap := make(map[containerID][]containerInfoWithCgroup)\n\tcinfosByPodCgroupKey := make(map[string]cadvisorapiv2.ContainerInfo)\n\tfor key, cinfo := range containerInfo {\n\t\tvar podCgroupKey string\n\t\tif cm.IsSystemdStyleName(key) {\n\t\t\t// Convert to internal cgroup name and take the last component only.\n\t\t\tinternalCgroupName := cm.ParseSystemdToCgroupName(key)\n\t\t\tpodCgroupKey = internalCgroupName[len(internalCgroupName)-1]\n\t\t} else {\n\t\t\t// Take last component only.\n\t\t\tpodCgroupKey = filepath.Base(key)\n\t\t}\n\t\tcinfosByPodCgroupKey[podCgroupKey] = cinfo\n\t\tif !isPodManagedContainer(\u0026cinfo) {\n\t\t\tcontinue\n\t\t}\n\t\tcinfoID := containerID{\n\t\t\tpodRef: buildPodRef(cinfo.Spec.Labels),\n\t\t\tcontainerName: kubetypes.GetContainerName(cinfo.Spec.Labels),\n\t\t}\n\t\tcinfoMap[cinfoID] = append(cinfoMap[cinfoID], containerInfoWithCgroup{\n\t\t\tcinfo: cinfo,\n\t\t\tcgroup: key,\n\t\t})\n\t}\n\tresult := make(map[string]cadvisorapiv2.ContainerInfo)\n\tfor _, refs := range cinfoMap {\n\t\tif len(refs) == 1 {\n\t\t\t// ContainerInfo with no CPU/memory/network usage for uncleaned cgroups of\n\t\t\t// already terminated containers, which should not be shown in the results.\n\t\t\tif !isContainerTerminated(\u0026refs[0].cinfo) {\n\t\t\t\tresult[refs[0].cgroup] = refs[0].cinfo\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tsort.Sort(ByCreationTime(refs))\n\t\tfor i := len(refs) - 1; i \u003e= 0; i-- {\n\t\t\tif hasMemoryAndCPUInstUsage(\u0026refs[i].cinfo) {\n\t\t\t\tresult[refs[i].cgroup] = refs[i].cinfo\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn result, cinfosByPodCgroupKey\n}","line":{"from":304,"to":355}} {"id":100007587,"name":"Len","signature":"func (a ByCreationTime) Len() int { return len(a) }","file":"pkg/kubelet/stats/cadvisor_stats_provider.go","code":"func (a ByCreationTime) Len() int { return len(a) }","line":{"from":361,"to":361}} {"id":100007588,"name":"Swap","signature":"func (a ByCreationTime) Swap(i, j int) { a[i], a[j] = a[j], a[i] }","file":"pkg/kubelet/stats/cadvisor_stats_provider.go","code":"func (a ByCreationTime) Swap(i, j int) { a[i], a[j] = a[j], a[i] }","line":{"from":362,"to":362}} {"id":100007589,"name":"Less","signature":"func (a ByCreationTime) Less(i, j int) bool","file":"pkg/kubelet/stats/cadvisor_stats_provider.go","code":"func (a ByCreationTime) Less(i, j int) bool {\n\tif a[i].cinfo.Spec.CreationTime.Equal(a[j].cinfo.Spec.CreationTime) {\n\t\t// There shouldn't be two containers with the same name and/or the same\n\t\t// creation time. However, to make the logic here robust, we break the\n\t\t// tie by moving the one without CPU instantaneous or memory RSS usage\n\t\t// to the beginning.\n\t\treturn hasMemoryAndCPUInstUsage(\u0026a[j].cinfo)\n\t}\n\treturn a[i].cinfo.Spec.CreationTime.Before(a[j].cinfo.Spec.CreationTime)\n}","line":{"from":363,"to":372}} {"id":100007590,"name":"hasMemoryAndCPUInstUsage","signature":"func hasMemoryAndCPUInstUsage(info *cadvisorapiv2.ContainerInfo) bool","file":"pkg/kubelet/stats/cadvisor_stats_provider.go","code":"// hasMemoryAndCPUInstUsage returns true if the specified container info has\n// both non-zero CPU instantaneous usage and non-zero memory RSS usage, and\n// false otherwise.\nfunc hasMemoryAndCPUInstUsage(info *cadvisorapiv2.ContainerInfo) bool {\n\tif !info.Spec.HasCpu || !info.Spec.HasMemory {\n\t\treturn false\n\t}\n\tcstat, found := latestContainerStats(info)\n\tif !found {\n\t\treturn false\n\t}\n\tif cstat.CpuInst == nil {\n\t\treturn false\n\t}\n\treturn cstat.CpuInst.Usage.Total != 0 \u0026\u0026 cstat.Memory.RSS != 0\n}","line":{"from":386,"to":401}} {"id":100007591,"name":"isContainerTerminated","signature":"func isContainerTerminated(info *cadvisorapiv2.ContainerInfo) bool","file":"pkg/kubelet/stats/cadvisor_stats_provider.go","code":"// isContainerTerminated returns true if the specified container meet one of the following conditions\n// 1. info.spec both cpu memory and network are false conditions\n// 2. info.Stats both network and cpu or memory are nil\n// 3. both zero CPU instantaneous usage zero memory RSS usage and zero network usage,\n// and false otherwise.\nfunc isContainerTerminated(info *cadvisorapiv2.ContainerInfo) bool {\n\tif !info.Spec.HasCpu \u0026\u0026 !info.Spec.HasMemory \u0026\u0026 !info.Spec.HasNetwork {\n\t\treturn true\n\t}\n\tcstat, found := latestContainerStats(info)\n\tif !found {\n\t\treturn true\n\t}\n\tif cstat.Network != nil {\n\t\tiStats := cadvisorInfoToNetworkStats(info)\n\t\tif iStats != nil {\n\t\t\tfor _, iStat := range iStats.Interfaces {\n\t\t\t\tif *iStat.RxErrors != 0 || *iStat.TxErrors != 0 || *iStat.RxBytes != 0 || *iStat.TxBytes != 0 {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif cstat.CpuInst == nil || cstat.Memory == nil {\n\t\treturn true\n\t}\n\treturn cstat.CpuInst.Usage.Total == 0 \u0026\u0026 cstat.Memory.RSS == 0\n}","line":{"from":403,"to":430}} {"id":100007592,"name":"getCadvisorContainerInfo","signature":"func getCadvisorContainerInfo(ca cadvisor.Interface) (map[string]cadvisorapiv2.ContainerInfo, error)","file":"pkg/kubelet/stats/cadvisor_stats_provider.go","code":"func getCadvisorContainerInfo(ca cadvisor.Interface) (map[string]cadvisorapiv2.ContainerInfo, error) {\n\tinfos, err := ca.ContainerInfoV2(\"/\", cadvisorapiv2.RequestOptions{\n\t\tIdType: cadvisorapiv2.TypeName,\n\t\tCount: 2, // 2 samples are needed to compute \"instantaneous\" CPU\n\t\tRecursive: true,\n\t})\n\tif err != nil {\n\t\tif _, ok := infos[\"/\"]; ok {\n\t\t\t// If the failure is partial, log it and return a best-effort\n\t\t\t// response.\n\t\t\tklog.ErrorS(err, \"Partial failure issuing cadvisor.ContainerInfoV2\")\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"failed to get root cgroup stats: %v\", err)\n\t\t}\n\t}\n\treturn infos, nil\n}","line":{"from":432,"to":448}} {"id":100007593,"name":"newCRIStatsProvider","signature":"func newCRIStatsProvider(","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"// newCRIStatsProvider returns a containerStatsProvider implementation that\n// provides container stats using CRI.\nfunc newCRIStatsProvider(\n\tcadvisor cadvisor.Interface,\n\tresourceAnalyzer stats.ResourceAnalyzer,\n\truntimeService internalapi.RuntimeService,\n\timageService internalapi.ImageManagerService,\n\thostStatsProvider HostStatsProvider,\n\tpodAndContainerStatsFromCRI bool,\n) containerStatsProvider {\n\treturn \u0026criStatsProvider{\n\t\tcadvisor: cadvisor,\n\t\tresourceAnalyzer: resourceAnalyzer,\n\t\truntimeService: runtimeService,\n\t\timageService: imageService,\n\t\thostStatsProvider: hostStatsProvider,\n\t\tcpuUsageCache: make(map[string]*cpuUsageRecord),\n\t\tpodAndContainerStatsFromCRI: podAndContainerStatsFromCRI,\n\t\tclock: clock.RealClock{},\n\t}\n}","line":{"from":83,"to":103}} {"id":100007594,"name":"ListPodStats","signature":"func (p *criStatsProvider) ListPodStats(ctx context.Context) ([]statsapi.PodStats, error)","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"// ListPodStats returns the stats of all the pod-managed containers.\nfunc (p *criStatsProvider) ListPodStats(ctx context.Context) ([]statsapi.PodStats, error) {\n\t// Don't update CPU nano core usage.\n\treturn p.listPodStats(ctx, false)\n}","line":{"from":105,"to":109}} {"id":100007595,"name":"ListPodStatsAndUpdateCPUNanoCoreUsage","signature":"func (p *criStatsProvider) ListPodStatsAndUpdateCPUNanoCoreUsage(ctx context.Context) ([]statsapi.PodStats, error)","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"// ListPodStatsAndUpdateCPUNanoCoreUsage updates the cpu nano core usage for\n// the containers and returns the stats for all the pod-managed containers.\n// This is a workaround because CRI runtimes do not supply nano core usages,\n// so this function calculate the difference between the current and the last\n// (cached) cpu stats to calculate this metrics. The implementation assumes a\n// single caller to periodically invoke this function to update the metrics. If\n// there exist multiple callers, the period used to compute the cpu usage may\n// vary and the usage could be incoherent (e.g., spiky). If no caller calls\n// this function, the cpu usage will stay nil. Right now, eviction manager is\n// the only caller, and it calls this function every 10s.\nfunc (p *criStatsProvider) ListPodStatsAndUpdateCPUNanoCoreUsage(ctx context.Context) ([]statsapi.PodStats, error) {\n\t// Update CPU nano core usage.\n\treturn p.listPodStats(ctx, true)\n}","line":{"from":111,"to":124}} {"id":100007596,"name":"listPodStats","signature":"func (p *criStatsProvider) listPodStats(ctx context.Context, updateCPUNanoCoreUsage bool) ([]statsapi.PodStats, error)","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"func (p *criStatsProvider) listPodStats(ctx context.Context, updateCPUNanoCoreUsage bool) ([]statsapi.PodStats, error) {\n\t// Gets node root filesystem information, which will be used to populate\n\t// the available and capacity bytes/inodes in container stats.\n\trootFsInfo, err := p.cadvisor.RootFsInfo()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get rootFs info: %v\", err)\n\t}\n\n\tcontainerMap, podSandboxMap, err := p.getPodAndContainerMaps(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get pod or container map: %v\", err)\n\t}\n\n\tif p.podAndContainerStatsFromCRI {\n\t\tresult, err := p.listPodStatsStrictlyFromCRI(ctx, updateCPUNanoCoreUsage, containerMap, podSandboxMap, \u0026rootFsInfo)\n\t\tif err == nil {\n\t\t\t// Call succeeded\n\t\t\treturn result, nil\n\t\t}\n\t\ts, ok := status.FromError(err)\n\t\t// Legitimate failure, rather than the CRI implementation does not support ListPodSandboxStats.\n\t\tif !ok || s.Code() != codes.Unimplemented {\n\t\t\treturn nil, err\n\t\t}\n\t\t// CRI implementation doesn't support ListPodSandboxStats, warn and fallback.\n\t\tklog.V(5).ErrorS(err,\n\t\t\t\"CRI implementation must be updated to support ListPodSandboxStats if PodAndContainerStatsFromCRI feature gate is enabled. Falling back to populating with cAdvisor; this call will fail in the future.\",\n\t\t)\n\t}\n\treturn p.listPodStatsPartiallyFromCRI(ctx, updateCPUNanoCoreUsage, containerMap, podSandboxMap, \u0026rootFsInfo)\n}","line":{"from":126,"to":156}} {"id":100007597,"name":"listPodStatsPartiallyFromCRI","signature":"func (p *criStatsProvider) listPodStatsPartiallyFromCRI(ctx context.Context, updateCPUNanoCoreUsage bool, containerMap map[string]*runtimeapi.Container, podSandboxMap map[string]*runtimeapi.PodSandbox, rootFsInfo *cadvisorapiv2.FsInfo) ([]statsapi.PodStats, error)","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"func (p *criStatsProvider) listPodStatsPartiallyFromCRI(ctx context.Context, updateCPUNanoCoreUsage bool, containerMap map[string]*runtimeapi.Container, podSandboxMap map[string]*runtimeapi.PodSandbox, rootFsInfo *cadvisorapiv2.FsInfo) ([]statsapi.PodStats, error) {\n\t// fsIDtoInfo is a map from filesystem id to its stats. This will be used\n\t// as a cache to avoid querying cAdvisor for the filesystem stats with the\n\t// same filesystem id many times.\n\tfsIDtoInfo := make(map[runtimeapi.FilesystemIdentifier]*cadvisorapiv2.FsInfo)\n\n\t// sandboxIDToPodStats is a temporary map from sandbox ID to its pod stats.\n\tsandboxIDToPodStats := make(map[string]*statsapi.PodStats)\n\n\tresp, err := p.runtimeService.ListContainerStats(ctx, \u0026runtimeapi.ContainerStatsFilter{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to list all container stats: %v\", err)\n\t}\n\tallInfos, err := getCadvisorContainerInfo(p.cadvisor)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to fetch cadvisor stats: %v\", err)\n\t}\n\tcaInfos, allInfos := getCRICadvisorStats(allInfos)\n\n\t// get network stats for containers.\n\t// This is only used on Windows. For other platforms, (nil, nil) should be returned.\n\tcontainerNetworkStats, err := p.listContainerNetworkStats()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to list container network stats: %v\", err)\n\t}\n\n\tfor _, stats := range resp {\n\t\tcontainerID := stats.Attributes.Id\n\t\tcontainer, found := containerMap[containerID]\n\t\tif !found {\n\t\t\tcontinue\n\t\t}\n\n\t\tpodSandboxID := container.PodSandboxId\n\t\tpodSandbox, found := podSandboxMap[podSandboxID]\n\t\tif !found {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Creates the stats of the pod (if not created yet) which the\n\t\t// container belongs to.\n\t\tps, found := sandboxIDToPodStats[podSandboxID]\n\t\tif !found {\n\t\t\tps = buildPodStats(podSandbox)\n\t\t\tsandboxIDToPodStats[podSandboxID] = ps\n\t\t}\n\n\t\t// Fill available stats for full set of required pod stats\n\t\tcs := p.makeContainerStats(stats, container, rootFsInfo, fsIDtoInfo, podSandbox.GetMetadata(), updateCPUNanoCoreUsage)\n\t\tp.addPodNetworkStats(ps, podSandboxID, caInfos, cs, containerNetworkStats[podSandboxID])\n\t\tp.addPodCPUMemoryStats(ps, types.UID(podSandbox.Metadata.Uid), allInfos, cs)\n\t\tp.addProcessStats(ps, types.UID(podSandbox.Metadata.Uid), allInfos, cs)\n\n\t\t// If cadvisor stats is available for the container, use it to populate\n\t\t// container stats\n\t\tcaStats, caFound := caInfos[containerID]\n\t\tif !caFound {\n\t\t\tklog.V(5).InfoS(\"Unable to find cadvisor stats for container\", \"containerID\", containerID)\n\t\t} else {\n\t\t\tp.addCadvisorContainerStats(cs, \u0026caStats)\n\t\t}\n\t\tps.Containers = append(ps.Containers, *cs)\n\t}\n\t// cleanup outdated caches.\n\tp.cleanupOutdatedCaches()\n\n\tresult := make([]statsapi.PodStats, 0, len(sandboxIDToPodStats))\n\tfor _, s := range sandboxIDToPodStats {\n\t\tmakePodStorageStats(s, rootFsInfo, p.resourceAnalyzer, p.hostStatsProvider, true)\n\t\tresult = append(result, *s)\n\t}\n\treturn result, nil\n}","line":{"from":158,"to":230}} {"id":100007598,"name":"listPodStatsStrictlyFromCRI","signature":"func (p *criStatsProvider) listPodStatsStrictlyFromCRI(ctx context.Context, updateCPUNanoCoreUsage bool, containerMap map[string]*runtimeapi.Container, podSandboxMap map[string]*runtimeapi.PodSandbox, rootFsInfo *cadvisorapiv2.FsInfo) ([]statsapi.PodStats, error)","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"func (p *criStatsProvider) listPodStatsStrictlyFromCRI(ctx context.Context, updateCPUNanoCoreUsage bool, containerMap map[string]*runtimeapi.Container, podSandboxMap map[string]*runtimeapi.PodSandbox, rootFsInfo *cadvisorapiv2.FsInfo) ([]statsapi.PodStats, error) {\n\tcriSandboxStats, err := p.runtimeService.ListPodSandboxStats(ctx, \u0026runtimeapi.PodSandboxStatsFilter{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfsIDtoInfo := make(map[runtimeapi.FilesystemIdentifier]*cadvisorapiv2.FsInfo)\n\tsummarySandboxStats := make([]statsapi.PodStats, 0, len(podSandboxMap))\n\tfor _, criSandboxStat := range criSandboxStats {\n\t\tif criSandboxStat == nil || criSandboxStat.Attributes == nil {\n\t\t\tklog.V(5).InfoS(\"Unable to find CRI stats for sandbox\")\n\t\t\tcontinue\n\t\t}\n\t\tpodSandbox, found := podSandboxMap[criSandboxStat.Attributes.Id]\n\t\tif !found {\n\t\t\tcontinue\n\t\t}\n\t\tps := buildPodStats(podSandbox)\n\t\tfor _, criContainerStat := range criSandboxStat.Linux.Containers {\n\t\t\tcontainer, found := containerMap[criContainerStat.Attributes.Id]\n\t\t\tif !found {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Fill available stats for full set of required pod stats\n\t\t\tcs := p.makeContainerStats(criContainerStat, container, rootFsInfo, fsIDtoInfo, podSandbox.GetMetadata(), updateCPUNanoCoreUsage)\n\t\t\tps.Containers = append(ps.Containers, *cs)\n\t\t}\n\t\taddCRIPodNetworkStats(ps, criSandboxStat)\n\t\taddCRIPodCPUStats(ps, criSandboxStat)\n\t\taddCRIPodMemoryStats(ps, criSandboxStat)\n\t\taddCRIPodProcessStats(ps, criSandboxStat)\n\t\tmakePodStorageStats(ps, rootFsInfo, p.resourceAnalyzer, p.hostStatsProvider, true)\n\t\tsummarySandboxStats = append(summarySandboxStats, *ps)\n\t}\n\treturn summarySandboxStats, nil\n}","line":{"from":232,"to":267}} {"id":100007599,"name":"ListPodCPUAndMemoryStats","signature":"func (p *criStatsProvider) ListPodCPUAndMemoryStats(ctx context.Context) ([]statsapi.PodStats, error)","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"// ListPodCPUAndMemoryStats returns the CPU and Memory stats of all the pod-managed containers.\nfunc (p *criStatsProvider) ListPodCPUAndMemoryStats(ctx context.Context) ([]statsapi.PodStats, error) {\n\t// sandboxIDToPodStats is a temporary map from sandbox ID to its pod stats.\n\tsandboxIDToPodStats := make(map[string]*statsapi.PodStats)\n\tcontainerMap, podSandboxMap, err := p.getPodAndContainerMaps(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get pod or container map: %v\", err)\n\t}\n\n\tresult := make([]statsapi.PodStats, 0, len(podSandboxMap))\n\tif p.podAndContainerStatsFromCRI {\n\t\tcriSandboxStats, err := p.runtimeService.ListPodSandboxStats(ctx, \u0026runtimeapi.PodSandboxStatsFilter{})\n\t\t// Call succeeded\n\t\tif err == nil {\n\t\t\tfor _, criSandboxStat := range criSandboxStats {\n\t\t\t\tpodSandbox, found := podSandboxMap[criSandboxStat.Attributes.Id]\n\t\t\t\tif !found {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tps := buildPodStats(podSandbox)\n\t\t\t\taddCRIPodCPUStats(ps, criSandboxStat)\n\t\t\t\taddCRIPodMemoryStats(ps, criSandboxStat)\n\t\t\t\tresult = append(result, *ps)\n\t\t\t}\n\t\t\treturn result, err\n\t\t}\n\t\t// Call failed, why?\n\t\ts, ok := status.FromError(err)\n\t\t// Legitimate failure, rather than the CRI implementation does not support ListPodSandboxStats.\n\t\tif !ok || s.Code() != codes.Unimplemented {\n\t\t\treturn nil, err\n\t\t}\n\t\t// CRI implementation doesn't support ListPodSandboxStats, warn and fallback.\n\t\tklog.ErrorS(err,\n\t\t\t\"CRI implementation must be updated to support ListPodSandboxStats if PodAndContainerStatsFromCRI feature gate is enabled. Falling back to populating with cAdvisor; this call will fail in the future.\",\n\t\t)\n\t}\n\n\tresp, err := p.runtimeService.ListContainerStats(ctx, \u0026runtimeapi.ContainerStatsFilter{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to list all container stats: %v\", err)\n\t}\n\n\tallInfos, err := getCadvisorContainerInfo(p.cadvisor)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to fetch cadvisor stats: %v\", err)\n\t}\n\tcaInfos, allInfos := getCRICadvisorStats(allInfos)\n\n\tfor _, stats := range resp {\n\t\tcontainerID := stats.Attributes.Id\n\t\tcontainer, found := containerMap[containerID]\n\t\tif !found {\n\t\t\tcontinue\n\t\t}\n\n\t\tpodSandboxID := container.PodSandboxId\n\t\tpodSandbox, found := podSandboxMap[podSandboxID]\n\t\tif !found {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Creates the stats of the pod (if not created yet) which the\n\t\t// container belongs to.\n\t\tps, found := sandboxIDToPodStats[podSandboxID]\n\t\tif !found {\n\t\t\tps = buildPodStats(podSandbox)\n\t\t\tsandboxIDToPodStats[podSandboxID] = ps\n\t\t}\n\n\t\t// Fill available CPU and memory stats for full set of required pod stats\n\t\tcs := p.makeContainerCPUAndMemoryStats(stats, container)\n\t\tp.addPodCPUMemoryStats(ps, types.UID(podSandbox.Metadata.Uid), allInfos, cs)\n\n\t\t// If cadvisor stats is available for the container, use it to populate\n\t\t// container stats\n\t\tcaStats, caFound := caInfos[containerID]\n\t\tif !caFound {\n\t\t\tklog.V(4).InfoS(\"Unable to find cadvisor stats for container\", \"containerID\", containerID)\n\t\t} else {\n\t\t\tp.addCadvisorContainerCPUAndMemoryStats(cs, \u0026caStats)\n\t\t}\n\t\tps.Containers = append(ps.Containers, *cs)\n\t}\n\t// cleanup outdated caches.\n\tp.cleanupOutdatedCaches()\n\n\tfor _, s := range sandboxIDToPodStats {\n\t\tresult = append(result, *s)\n\t}\n\treturn result, nil\n}","line":{"from":269,"to":360}} {"id":100007600,"name":"getPodAndContainerMaps","signature":"func (p *criStatsProvider) getPodAndContainerMaps(ctx context.Context) (map[string]*runtimeapi.Container, map[string]*runtimeapi.PodSandbox, error)","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"func (p *criStatsProvider) getPodAndContainerMaps(ctx context.Context) (map[string]*runtimeapi.Container, map[string]*runtimeapi.PodSandbox, error) {\n\tcontainers, err := p.runtimeService.ListContainers(ctx, \u0026runtimeapi.ContainerFilter{})\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to list all containers: %v\", err)\n\t}\n\n\t// Creates pod sandbox map between the pod sandbox ID and the PodSandbox object.\n\tpodSandboxMap := make(map[string]*runtimeapi.PodSandbox)\n\tpodSandboxes, err := p.runtimeService.ListPodSandbox(ctx, \u0026runtimeapi.PodSandboxFilter{})\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to list all pod sandboxes: %v\", err)\n\t}\n\tpodSandboxes = removeTerminatedPods(podSandboxes)\n\tfor _, s := range podSandboxes {\n\t\tpodSandboxMap[s.Id] = s\n\t}\n\n\tcontainers = removeTerminatedContainers(containers)\n\t// Creates container map between the container ID and the Container object.\n\tcontainerMap := make(map[string]*runtimeapi.Container)\n\tfor _, c := range containers {\n\t\tcontainerMap[c.Id] = c\n\t}\n\treturn containerMap, podSandboxMap, nil\n}","line":{"from":362,"to":386}} {"id":100007601,"name":"ImageFsStats","signature":"func (p *criStatsProvider) ImageFsStats(ctx context.Context) (*statsapi.FsStats, error)","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"// ImageFsStats returns the stats of the image filesystem.\nfunc (p *criStatsProvider) ImageFsStats(ctx context.Context) (*statsapi.FsStats, error) {\n\tresp, err := p.imageService.ImageFsInfo(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// CRI may return the stats of multiple image filesystems but we only\n\t// return the first one.\n\t//\n\t// TODO(yguo0905): Support returning stats of multiple image filesystems.\n\tif len(resp) == 0 {\n\t\treturn nil, fmt.Errorf(\"imageFs information is unavailable\")\n\t}\n\tfs := resp[0]\n\ts := \u0026statsapi.FsStats{\n\t\tTime: metav1.NewTime(time.Unix(0, fs.Timestamp)),\n\t\tUsedBytes: \u0026fs.UsedBytes.Value,\n\t}\n\tif fs.InodesUsed != nil {\n\t\ts.InodesUsed = \u0026fs.InodesUsed.Value\n\t}\n\timageFsInfo := p.getFsInfo(fs.GetFsId())\n\tif imageFsInfo != nil {\n\t\t// The image filesystem id is unknown to the local node or there's\n\t\t// an error on retrieving the stats. In these cases, we omit those\n\t\t// stats and return the best-effort partial result. See\n\t\t// https://github.com/kubernetes/heapster/issues/1793.\n\t\ts.AvailableBytes = \u0026imageFsInfo.Available\n\t\ts.CapacityBytes = \u0026imageFsInfo.Capacity\n\t\ts.InodesFree = imageFsInfo.InodesFree\n\t\ts.Inodes = imageFsInfo.Inodes\n\t}\n\treturn s, nil\n}","line":{"from":388,"to":422}} {"id":100007602,"name":"ImageFsDevice","signature":"func (p *criStatsProvider) ImageFsDevice(ctx context.Context) (string, error)","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"// ImageFsDevice returns name of the device where the image filesystem locates,\n// e.g. /dev/sda1.\nfunc (p *criStatsProvider) ImageFsDevice(ctx context.Context) (string, error) {\n\tresp, err := p.imageService.ImageFsInfo(ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfor _, fs := range resp {\n\t\tfsInfo := p.getFsInfo(fs.GetFsId())\n\t\tif fsInfo != nil {\n\t\t\treturn fsInfo.Device, nil\n\t\t}\n\t}\n\treturn \"\", errors.New(\"imagefs device is not found\")\n}","line":{"from":424,"to":438}} {"id":100007603,"name":"getFsInfo","signature":"func (p *criStatsProvider) getFsInfo(fsID *runtimeapi.FilesystemIdentifier) *cadvisorapiv2.FsInfo","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"// getFsInfo returns the information of the filesystem with the specified\n// fsID. If any error occurs, this function logs the error and returns\n// nil.\nfunc (p *criStatsProvider) getFsInfo(fsID *runtimeapi.FilesystemIdentifier) *cadvisorapiv2.FsInfo {\n\tif fsID == nil {\n\t\tklog.V(2).InfoS(\"Failed to get filesystem info: fsID is nil\")\n\t\treturn nil\n\t}\n\tmountpoint := fsID.GetMountpoint()\n\tfsInfo, err := p.cadvisor.GetDirFsInfo(mountpoint)\n\tif err != nil {\n\t\tmsg := \"Failed to get the info of the filesystem with mountpoint\"\n\t\tif err == cadvisorfs.ErrNoSuchDevice {\n\t\t\tklog.V(2).InfoS(msg, \"mountpoint\", mountpoint, \"err\", err)\n\t\t} else {\n\t\t\tklog.ErrorS(err, msg, \"mountpoint\", mountpoint)\n\t\t}\n\t\treturn nil\n\t}\n\treturn \u0026fsInfo\n}","line":{"from":440,"to":460}} {"id":100007604,"name":"buildPodStats","signature":"func buildPodStats(podSandbox *runtimeapi.PodSandbox) *statsapi.PodStats","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"// buildPodStats returns a PodStats that identifies the Pod managing cinfo\nfunc buildPodStats(podSandbox *runtimeapi.PodSandbox) *statsapi.PodStats {\n\treturn \u0026statsapi.PodStats{\n\t\tPodRef: statsapi.PodReference{\n\t\t\tName: podSandbox.Metadata.Name,\n\t\t\tUID: podSandbox.Metadata.Uid,\n\t\t\tNamespace: podSandbox.Metadata.Namespace,\n\t\t},\n\t\t// The StartTime in the summary API is the pod creation time.\n\t\tStartTime: metav1.NewTime(time.Unix(0, podSandbox.CreatedAt)),\n\t}\n}","line":{"from":462,"to":473}} {"id":100007605,"name":"addPodNetworkStats","signature":"func (p *criStatsProvider) addPodNetworkStats(","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"func (p *criStatsProvider) addPodNetworkStats(\n\tps *statsapi.PodStats,\n\tpodSandboxID string,\n\tcaInfos map[string]cadvisorapiv2.ContainerInfo,\n\tcs *statsapi.ContainerStats,\n\tnetStats *statsapi.NetworkStats,\n) {\n\tcaPodSandbox, found := caInfos[podSandboxID]\n\t// try get network stats from cadvisor first.\n\tif found {\n\t\tnetworkStats := cadvisorInfoToNetworkStats(\u0026caPodSandbox)\n\t\tif networkStats != nil {\n\t\t\tps.Network = networkStats\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Not found from cadvisor, get from netStats.\n\tif netStats != nil {\n\t\tps.Network = netStats\n\t\treturn\n\t}\n\n\t// TODO: sum Pod network stats from container stats.\n\tklog.V(4).InfoS(\"Unable to find network stats for sandbox\", \"sandboxID\", podSandboxID)\n}","line":{"from":475,"to":500}} {"id":100007606,"name":"addPodCPUMemoryStats","signature":"func (p *criStatsProvider) addPodCPUMemoryStats(","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"func (p *criStatsProvider) addPodCPUMemoryStats(\n\tps *statsapi.PodStats,\n\tpodUID types.UID,\n\tallInfos map[string]cadvisorapiv2.ContainerInfo,\n\tcs *statsapi.ContainerStats,\n) {\n\t// try get cpu and memory stats from cadvisor first.\n\tpodCgroupInfo := getCadvisorPodInfoFromPodUID(podUID, allInfos)\n\tif podCgroupInfo != nil {\n\t\tcpu, memory := cadvisorInfoToCPUandMemoryStats(podCgroupInfo)\n\t\tps.CPU = cpu\n\t\tps.Memory = memory\n\t\treturn\n\t}\n\n\t// Sum Pod cpu and memory stats from containers stats.\n\tif cs.CPU != nil {\n\t\tif ps.CPU == nil {\n\t\t\tps.CPU = \u0026statsapi.CPUStats{}\n\t\t}\n\n\t\tps.CPU.Time = cs.CPU.Time\n\t\tusageCoreNanoSeconds := getUint64Value(cs.CPU.UsageCoreNanoSeconds) + getUint64Value(ps.CPU.UsageCoreNanoSeconds)\n\t\tusageNanoCores := getUint64Value(cs.CPU.UsageNanoCores) + getUint64Value(ps.CPU.UsageNanoCores)\n\t\tps.CPU.UsageCoreNanoSeconds = \u0026usageCoreNanoSeconds\n\t\tps.CPU.UsageNanoCores = \u0026usageNanoCores\n\t}\n\n\tif cs.Memory != nil {\n\t\tif ps.Memory == nil {\n\t\t\tps.Memory = \u0026statsapi.MemoryStats{}\n\t\t}\n\n\t\tps.Memory.Time = cs.Memory.Time\n\t\tavailableBytes := getUint64Value(cs.Memory.AvailableBytes) + getUint64Value(ps.Memory.AvailableBytes)\n\t\tusageBytes := getUint64Value(cs.Memory.UsageBytes) + getUint64Value(ps.Memory.UsageBytes)\n\t\tworkingSetBytes := getUint64Value(cs.Memory.WorkingSetBytes) + getUint64Value(ps.Memory.WorkingSetBytes)\n\t\trSSBytes := getUint64Value(cs.Memory.RSSBytes) + getUint64Value(ps.Memory.RSSBytes)\n\t\tpageFaults := getUint64Value(cs.Memory.PageFaults) + getUint64Value(ps.Memory.PageFaults)\n\t\tmajorPageFaults := getUint64Value(cs.Memory.MajorPageFaults) + getUint64Value(ps.Memory.MajorPageFaults)\n\t\tps.Memory.AvailableBytes = \u0026availableBytes\n\t\tps.Memory.UsageBytes = \u0026usageBytes\n\t\tps.Memory.WorkingSetBytes = \u0026workingSetBytes\n\t\tps.Memory.RSSBytes = \u0026rSSBytes\n\t\tps.Memory.PageFaults = \u0026pageFaults\n\t\tps.Memory.MajorPageFaults = \u0026majorPageFaults\n\t}\n}","line":{"from":502,"to":549}} {"id":100007607,"name":"addProcessStats","signature":"func (p *criStatsProvider) addProcessStats(","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"func (p *criStatsProvider) addProcessStats(\n\tps *statsapi.PodStats,\n\tpodUID types.UID,\n\tallInfos map[string]cadvisorapiv2.ContainerInfo,\n\tcs *statsapi.ContainerStats,\n) {\n\t// try get process stats from cadvisor only.\n\tinfo := getCadvisorPodInfoFromPodUID(podUID, allInfos)\n\tif info != nil {\n\t\tps.ProcessStats = cadvisorInfoToProcessStats(info)\n\t\treturn\n\t}\n}","line":{"from":551,"to":563}} {"id":100007608,"name":"makeContainerStats","signature":"func (p *criStatsProvider) makeContainerStats(","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"func (p *criStatsProvider) makeContainerStats(\n\tstats *runtimeapi.ContainerStats,\n\tcontainer *runtimeapi.Container,\n\trootFsInfo *cadvisorapiv2.FsInfo,\n\tfsIDtoInfo map[runtimeapi.FilesystemIdentifier]*cadvisorapiv2.FsInfo,\n\tmeta *runtimeapi.PodSandboxMetadata,\n\tupdateCPUNanoCoreUsage bool,\n) *statsapi.ContainerStats {\n\tresult := \u0026statsapi.ContainerStats{\n\t\tName: stats.Attributes.Metadata.Name,\n\t\t// The StartTime in the summary API is the container creation time.\n\t\tStartTime: metav1.NewTime(time.Unix(0, container.CreatedAt)),\n\t\tCPU: \u0026statsapi.CPUStats{},\n\t\tMemory: \u0026statsapi.MemoryStats{},\n\t\tRootfs: \u0026statsapi.FsStats{},\n\t\t// UserDefinedMetrics is not supported by CRI.\n\t}\n\tif stats.Cpu != nil {\n\t\tresult.CPU.Time = metav1.NewTime(time.Unix(0, stats.Cpu.Timestamp))\n\t\tif stats.Cpu.UsageCoreNanoSeconds != nil {\n\t\t\tresult.CPU.UsageCoreNanoSeconds = \u0026stats.Cpu.UsageCoreNanoSeconds.Value\n\t\t}\n\t\tvar usageNanoCores *uint64\n\t\tif updateCPUNanoCoreUsage {\n\t\t\tusageNanoCores = p.getAndUpdateContainerUsageNanoCores(stats)\n\t\t} else {\n\t\t\tusageNanoCores = p.getContainerUsageNanoCores(stats)\n\t\t}\n\t\tif usageNanoCores != nil {\n\t\t\tresult.CPU.UsageNanoCores = usageNanoCores\n\t\t}\n\t} else {\n\t\tresult.CPU.Time = metav1.NewTime(time.Unix(0, time.Now().UnixNano()))\n\t\tresult.CPU.UsageCoreNanoSeconds = uint64Ptr(0)\n\t\tresult.CPU.UsageNanoCores = uint64Ptr(0)\n\t}\n\tif stats.Memory != nil {\n\t\tresult.Memory.Time = metav1.NewTime(time.Unix(0, stats.Memory.Timestamp))\n\t\tif stats.Memory.WorkingSetBytes != nil {\n\t\t\tresult.Memory.WorkingSetBytes = \u0026stats.Memory.WorkingSetBytes.Value\n\t\t}\n\t} else {\n\t\tresult.Memory.Time = metav1.NewTime(time.Unix(0, time.Now().UnixNano()))\n\t\tresult.Memory.WorkingSetBytes = uint64Ptr(0)\n\t}\n\tif stats.WritableLayer != nil {\n\t\tresult.Rootfs.Time = metav1.NewTime(time.Unix(0, stats.WritableLayer.Timestamp))\n\t\tif stats.WritableLayer.UsedBytes != nil {\n\t\t\tresult.Rootfs.UsedBytes = \u0026stats.WritableLayer.UsedBytes.Value\n\t\t}\n\t\tif stats.WritableLayer.InodesUsed != nil {\n\t\t\tresult.Rootfs.InodesUsed = \u0026stats.WritableLayer.InodesUsed.Value\n\t\t}\n\t}\n\tfsID := stats.GetWritableLayer().GetFsId()\n\tif fsID != nil {\n\t\timageFsInfo, found := fsIDtoInfo[*fsID]\n\t\tif !found {\n\t\t\timageFsInfo = p.getFsInfo(fsID)\n\t\t\tfsIDtoInfo[*fsID] = imageFsInfo\n\t\t}\n\t\tif imageFsInfo != nil {\n\t\t\t// The image filesystem id is unknown to the local node or there's\n\t\t\t// an error on retrieving the stats. In these cases, we omit those stats\n\t\t\t// and return the best-effort partial result. See\n\t\t\t// https://github.com/kubernetes/heapster/issues/1793.\n\t\t\tresult.Rootfs.AvailableBytes = \u0026imageFsInfo.Available\n\t\t\tresult.Rootfs.CapacityBytes = \u0026imageFsInfo.Capacity\n\t\t\tresult.Rootfs.InodesFree = imageFsInfo.InodesFree\n\t\t\tresult.Rootfs.Inodes = imageFsInfo.Inodes\n\t\t}\n\t}\n\t// NOTE: This doesn't support the old pod log path, `/var/log/pods/UID`. For containers\n\t// using old log path, empty log stats are returned. This is fine, because we don't\n\t// officially support in-place upgrade anyway.\n\tvar err error\n\tresult.Logs, err = p.hostStatsProvider.getPodContainerLogStats(meta.GetNamespace(), meta.GetName(), types.UID(meta.GetUid()), container.GetMetadata().GetName(), rootFsInfo)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Unable to fetch container log stats\", \"containerName\", container.GetMetadata().GetName())\n\t}\n\treturn result\n}","line":{"from":565,"to":646}} {"id":100007609,"name":"makeContainerCPUAndMemoryStats","signature":"func (p *criStatsProvider) makeContainerCPUAndMemoryStats(","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"func (p *criStatsProvider) makeContainerCPUAndMemoryStats(\n\tstats *runtimeapi.ContainerStats,\n\tcontainer *runtimeapi.Container,\n) *statsapi.ContainerStats {\n\tresult := \u0026statsapi.ContainerStats{\n\t\tName: stats.Attributes.Metadata.Name,\n\t\t// The StartTime in the summary API is the container creation time.\n\t\tStartTime: metav1.NewTime(time.Unix(0, container.CreatedAt)),\n\t\tCPU: \u0026statsapi.CPUStats{},\n\t\tMemory: \u0026statsapi.MemoryStats{},\n\t\t// UserDefinedMetrics is not supported by CRI.\n\t}\n\tif stats.Cpu != nil {\n\t\tresult.CPU.Time = metav1.NewTime(time.Unix(0, stats.Cpu.Timestamp))\n\t\tif stats.Cpu.UsageCoreNanoSeconds != nil {\n\t\t\tresult.CPU.UsageCoreNanoSeconds = \u0026stats.Cpu.UsageCoreNanoSeconds.Value\n\t\t}\n\n\t\tusageNanoCores := p.getContainerUsageNanoCores(stats)\n\t\tif usageNanoCores != nil {\n\t\t\tresult.CPU.UsageNanoCores = usageNanoCores\n\t\t}\n\t} else {\n\t\tresult.CPU.Time = metav1.NewTime(time.Unix(0, time.Now().UnixNano()))\n\t\tresult.CPU.UsageCoreNanoSeconds = uint64Ptr(0)\n\t\tresult.CPU.UsageNanoCores = uint64Ptr(0)\n\t}\n\tif stats.Memory != nil {\n\t\tresult.Memory.Time = metav1.NewTime(time.Unix(0, stats.Memory.Timestamp))\n\t\tif stats.Memory.WorkingSetBytes != nil {\n\t\t\tresult.Memory.WorkingSetBytes = \u0026stats.Memory.WorkingSetBytes.Value\n\t\t}\n\t} else {\n\t\tresult.Memory.Time = metav1.NewTime(time.Unix(0, time.Now().UnixNano()))\n\t\tresult.Memory.WorkingSetBytes = uint64Ptr(0)\n\t}\n\n\treturn result\n}","line":{"from":648,"to":686}} {"id":100007610,"name":"getContainerUsageNanoCores","signature":"func (p *criStatsProvider) getContainerUsageNanoCores(stats *runtimeapi.ContainerStats) *uint64","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"// getContainerUsageNanoCores first attempts to get the usage nano cores from the stats reported\n// by the CRI. If it is unable to, it gets the information from the cache instead.\nfunc (p *criStatsProvider) getContainerUsageNanoCores(stats *runtimeapi.ContainerStats) *uint64 {\n\tif stats == nil || stats.Attributes == nil {\n\t\treturn nil\n\t}\n\n\t// Bypass the cache if the CRI implementation specified the UsageNanoCores.\n\tif stats.Cpu != nil \u0026\u0026 stats.Cpu.UsageNanoCores != nil {\n\t\treturn \u0026stats.Cpu.UsageNanoCores.Value\n\t}\n\n\tp.mutex.RLock()\n\tdefer p.mutex.RUnlock()\n\n\tcached, ok := p.cpuUsageCache[stats.Attributes.Id]\n\tif !ok || cached.usageNanoCores == nil {\n\t\treturn nil\n\t}\n\t// return a copy of the usage\n\tlatestUsage := *cached.usageNanoCores\n\treturn \u0026latestUsage\n}","line":{"from":688,"to":710}} {"id":100007611,"name":"getAndUpdateContainerUsageNanoCores","signature":"func (p *criStatsProvider) getAndUpdateContainerUsageNanoCores(stats *runtimeapi.ContainerStats) *uint64","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"// getAndUpdateContainerUsageNanoCores first attempts to get the usage nano cores from the stats reported\n// by the CRI. If it is unable to, it computes usageNanoCores based on the given and the cached usageCoreNanoSeconds,\n// updates the cache with the computed usageNanoCores, and returns the usageNanoCores.\nfunc (p *criStatsProvider) getAndUpdateContainerUsageNanoCores(stats *runtimeapi.ContainerStats) *uint64 {\n\tif stats == nil || stats.Attributes == nil || stats.Cpu == nil {\n\t\treturn nil\n\t}\n\t// Bypass the cache if the CRI implementation specified the UsageNanoCores.\n\tif stats.Cpu.UsageNanoCores != nil {\n\t\treturn \u0026stats.Cpu.UsageNanoCores.Value\n\t}\n\t// If there is no UsageNanoCores, nor UsageCoreNanoSeconds, there is no information to use\n\tif stats.Cpu.UsageCoreNanoSeconds == nil {\n\t\treturn nil\n\t}\n\tid := stats.Attributes.Id\n\tusage, err := func() (*uint64, error) {\n\t\tp.mutex.Lock()\n\t\tdefer p.mutex.Unlock()\n\n\t\tcached, ok := p.cpuUsageCache[id]\n\t\tif !ok || cached.stats.UsageCoreNanoSeconds == nil || stats.Cpu.UsageCoreNanoSeconds.Value \u003c cached.stats.UsageCoreNanoSeconds.Value {\n\t\t\t// Cannot compute the usage now, but update the cached stats anyway\n\t\t\tp.cpuUsageCache[id] = \u0026cpuUsageRecord{stats: stats.Cpu, usageNanoCores: nil}\n\t\t\treturn nil, nil\n\t\t}\n\n\t\tnewStats := stats.Cpu\n\t\tcachedStats := cached.stats\n\t\tnanoSeconds := newStats.Timestamp - cachedStats.Timestamp\n\t\tif nanoSeconds \u003c= 0 {\n\t\t\treturn nil, fmt.Errorf(\"zero or negative interval (%v - %v)\", newStats.Timestamp, cachedStats.Timestamp)\n\t\t}\n\t\tusageNanoCores := uint64(float64(newStats.UsageCoreNanoSeconds.Value-cachedStats.UsageCoreNanoSeconds.Value) /\n\t\t\tfloat64(nanoSeconds) * float64(time.Second/time.Nanosecond))\n\n\t\t// Update cache with new value.\n\t\tusageToUpdate := usageNanoCores\n\t\tp.cpuUsageCache[id] = \u0026cpuUsageRecord{stats: newStats, usageNanoCores: \u0026usageToUpdate}\n\n\t\treturn \u0026usageNanoCores, nil\n\t}()\n\n\tif err != nil {\n\t\t// This should not happen. Log now to raise visibility\n\t\tklog.ErrorS(err, \"Failed updating cpu usage nano core\")\n\t}\n\treturn usage\n}","line":{"from":712,"to":760}} {"id":100007612,"name":"cleanupOutdatedCaches","signature":"func (p *criStatsProvider) cleanupOutdatedCaches()","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"func (p *criStatsProvider) cleanupOutdatedCaches() {\n\tp.mutex.Lock()\n\tdefer p.mutex.Unlock()\n\n\tfor k, v := range p.cpuUsageCache {\n\t\tif v == nil {\n\t\t\tdelete(p.cpuUsageCache, k)\n\t\t\tcontinue\n\t\t}\n\n\t\tif time.Since(time.Unix(0, v.stats.Timestamp)) \u003e defaultCachePeriod {\n\t\t\tdelete(p.cpuUsageCache, k)\n\t\t}\n\t}\n}","line":{"from":762,"to":776}} {"id":100007613,"name":"removeTerminatedPods","signature":"func removeTerminatedPods(pods []*runtimeapi.PodSandbox) []*runtimeapi.PodSandbox","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"// removeTerminatedPods returns pods with terminated ones removed.\n// It only removes a terminated pod when there is a running instance\n// of the pod with the same name and namespace.\n// This is needed because:\n// 1) PodSandbox may be recreated;\n// 2) Pod may be recreated with the same name and namespace.\nfunc removeTerminatedPods(pods []*runtimeapi.PodSandbox) []*runtimeapi.PodSandbox {\n\tpodMap := make(map[statsapi.PodReference][]*runtimeapi.PodSandbox)\n\t// Sort order by create time\n\tsort.Slice(pods, func(i, j int) bool {\n\t\treturn pods[i].CreatedAt \u003c pods[j].CreatedAt\n\t})\n\tfor _, pod := range pods {\n\t\trefID := statsapi.PodReference{\n\t\t\tName: pod.GetMetadata().GetName(),\n\t\t\tNamespace: pod.GetMetadata().GetNamespace(),\n\t\t\t// UID is intentionally left empty.\n\t\t}\n\t\tpodMap[refID] = append(podMap[refID], pod)\n\t}\n\n\tresult := make([]*runtimeapi.PodSandbox, 0)\n\tfor _, refs := range podMap {\n\t\tif len(refs) == 1 {\n\t\t\tresult = append(result, refs[0])\n\t\t\tcontinue\n\t\t}\n\t\tfound := false\n\t\tfor i := 0; i \u003c len(refs); i++ {\n\t\t\tif refs[i].State == runtimeapi.PodSandboxState_SANDBOX_READY {\n\t\t\t\tfound = true\n\t\t\t\tresult = append(result, refs[i])\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tresult = append(result, refs[len(refs)-1])\n\t\t}\n\t}\n\treturn result\n}","line":{"from":778,"to":817}} {"id":100007614,"name":"removeTerminatedContainers","signature":"func removeTerminatedContainers(containers []*runtimeapi.Container) []*runtimeapi.Container","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"// removeTerminatedContainers removes all terminated containers since they should\n// not be used for usage calculations.\nfunc removeTerminatedContainers(containers []*runtimeapi.Container) []*runtimeapi.Container {\n\tcontainerMap := make(map[containerID][]*runtimeapi.Container)\n\t// Sort order by create time\n\tsort.Slice(containers, func(i, j int) bool {\n\t\treturn containers[i].CreatedAt \u003c containers[j].CreatedAt\n\t})\n\tfor _, container := range containers {\n\t\trefID := containerID{\n\t\t\tpodRef: buildPodRef(container.Labels),\n\t\t\tcontainerName: kubetypes.GetContainerName(container.Labels),\n\t\t}\n\t\tcontainerMap[refID] = append(containerMap[refID], container)\n\t}\n\n\tresult := make([]*runtimeapi.Container, 0)\n\tfor _, refs := range containerMap {\n\t\tfor i := 0; i \u003c len(refs); i++ {\n\t\t\tif refs[i].State == runtimeapi.ContainerState_CONTAINER_RUNNING {\n\t\t\t\tresult = append(result, refs[i])\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}","line":{"from":819,"to":844}} {"id":100007615,"name":"addCadvisorContainerStats","signature":"func (p *criStatsProvider) addCadvisorContainerStats(","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"func (p *criStatsProvider) addCadvisorContainerStats(\n\tcs *statsapi.ContainerStats,\n\tcaPodStats *cadvisorapiv2.ContainerInfo,\n) {\n\tif caPodStats.Spec.HasCustomMetrics {\n\t\tcs.UserDefinedMetrics = cadvisorInfoToUserDefinedMetrics(caPodStats)\n\t}\n\n\tcpu, memory := cadvisorInfoToCPUandMemoryStats(caPodStats)\n\tif cpu != nil {\n\t\tcs.CPU = cpu\n\t}\n\tif memory != nil {\n\t\tcs.Memory = memory\n\t}\n}","line":{"from":846,"to":861}} {"id":100007616,"name":"addCadvisorContainerCPUAndMemoryStats","signature":"func (p *criStatsProvider) addCadvisorContainerCPUAndMemoryStats(","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"func (p *criStatsProvider) addCadvisorContainerCPUAndMemoryStats(\n\tcs *statsapi.ContainerStats,\n\tcaPodStats *cadvisorapiv2.ContainerInfo,\n) {\n\tif caPodStats.Spec.HasCustomMetrics {\n\t\tcs.UserDefinedMetrics = cadvisorInfoToUserDefinedMetrics(caPodStats)\n\t}\n\n\tcpu, memory := cadvisorInfoToCPUandMemoryStats(caPodStats)\n\tif cpu != nil {\n\t\tcs.CPU = cpu\n\t}\n\tif memory != nil {\n\t\tcs.Memory = memory\n\t}\n}","line":{"from":863,"to":878}} {"id":100007617,"name":"getCRICadvisorStats","signature":"func getCRICadvisorStats(infos map[string]cadvisorapiv2.ContainerInfo) (map[string]cadvisorapiv2.ContainerInfo, map[string]cadvisorapiv2.ContainerInfo)","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"func getCRICadvisorStats(infos map[string]cadvisorapiv2.ContainerInfo) (map[string]cadvisorapiv2.ContainerInfo, map[string]cadvisorapiv2.ContainerInfo) {\n\tstats := make(map[string]cadvisorapiv2.ContainerInfo)\n\tfilteredInfos, cinfosByPodCgroupKey := filterTerminatedContainerInfoAndAssembleByPodCgroupKey(infos)\n\tfor key, info := range filteredInfos {\n\t\t// On systemd using devicemapper each mount into the container has an\n\t\t// associated cgroup. We ignore them to ensure we do not get duplicate\n\t\t// entries in our summary. For details on .mount units:\n\t\t// http://man7.org/linux/man-pages/man5/systemd.mount.5.html\n\t\tif strings.HasSuffix(key, \".mount\") {\n\t\t\tcontinue\n\t\t}\n\t\t// Build the Pod key if this container is managed by a Pod\n\t\tif !isPodManagedContainer(\u0026info) {\n\t\t\tcontinue\n\t\t}\n\t\tstats[extractIDFromCgroupPath(key)] = info\n\t}\n\treturn stats, cinfosByPodCgroupKey\n}","line":{"from":880,"to":898}} {"id":100007618,"name":"extractIDFromCgroupPath","signature":"func extractIDFromCgroupPath(cgroupPath string) string","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"func extractIDFromCgroupPath(cgroupPath string) string {\n\t// case0 == cgroupfs: \"/kubepods/burstable/pod2fc932ce-fdcc-454b-97bd-aadfdeb4c340/9be25294016e2dc0340dd605ce1f57b492039b267a6a618a7ad2a7a58a740f32\"\n\tid := filepath.Base(cgroupPath)\n\n\t// case1 == systemd: \"/kubepods.slice/kubepods-burstable.slice/kubepods-burstable-pod2fc932ce_fdcc_454b_97bd_aadfdeb4c340.slice/cri-containerd-aaefb9d8feed2d453b543f6d928cede7a4dbefa6a0ae7c9b990dd234c56e93b9.scope\"\n\t// trim anything before the final '-' and suffix .scope\n\tsystemdSuffix := \".scope\"\n\tif strings.HasSuffix(id, systemdSuffix) {\n\t\tid = strings.TrimSuffix(id, systemdSuffix)\n\t\tcomponents := strings.Split(id, \"-\")\n\t\tif len(components) \u003e 1 {\n\t\t\tid = components[len(components)-1]\n\t\t}\n\t}\n\treturn id\n}","line":{"from":900,"to":915}} {"id":100007619,"name":"addCRIPodNetworkStats","signature":"func addCRIPodNetworkStats(ps *statsapi.PodStats, criPodStat *runtimeapi.PodSandboxStats)","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"func addCRIPodNetworkStats(ps *statsapi.PodStats, criPodStat *runtimeapi.PodSandboxStats) {\n\tif criPodStat == nil || criPodStat.Linux == nil || criPodStat.Linux.Network == nil {\n\t\treturn\n\t}\n\tcriNetwork := criPodStat.Linux.Network\n\tiStats := statsapi.NetworkStats{\n\t\tTime: metav1.NewTime(time.Unix(0, criNetwork.Timestamp)),\n\t\tInterfaceStats: criInterfaceToSummary(criNetwork.DefaultInterface),\n\t\tInterfaces: make([]statsapi.InterfaceStats, 0, len(criNetwork.Interfaces)),\n\t}\n\tfor _, iface := range criNetwork.Interfaces {\n\t\tiStats.Interfaces = append(iStats.Interfaces, criInterfaceToSummary(iface))\n\t}\n\tps.Network = \u0026iStats\n}","line":{"from":917,"to":931}} {"id":100007620,"name":"criInterfaceToSummary","signature":"func criInterfaceToSummary(criIface *runtimeapi.NetworkInterfaceUsage) statsapi.InterfaceStats","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"func criInterfaceToSummary(criIface *runtimeapi.NetworkInterfaceUsage) statsapi.InterfaceStats {\n\treturn statsapi.InterfaceStats{\n\t\tName: criIface.Name,\n\t\tRxBytes: valueOfUInt64Value(criIface.RxBytes),\n\t\tRxErrors: valueOfUInt64Value(criIface.RxErrors),\n\t\tTxBytes: valueOfUInt64Value(criIface.TxBytes),\n\t\tTxErrors: valueOfUInt64Value(criIface.TxErrors),\n\t}\n}","line":{"from":933,"to":941}} {"id":100007621,"name":"addCRIPodCPUStats","signature":"func addCRIPodCPUStats(ps *statsapi.PodStats, criPodStat *runtimeapi.PodSandboxStats)","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"func addCRIPodCPUStats(ps *statsapi.PodStats, criPodStat *runtimeapi.PodSandboxStats) {\n\tif criPodStat == nil || criPodStat.Linux == nil || criPodStat.Linux.Cpu == nil {\n\t\treturn\n\t}\n\tcriCPU := criPodStat.Linux.Cpu\n\tps.CPU = \u0026statsapi.CPUStats{\n\t\tTime: metav1.NewTime(time.Unix(0, criCPU.Timestamp)),\n\t\tUsageNanoCores: valueOfUInt64Value(criCPU.UsageNanoCores),\n\t\tUsageCoreNanoSeconds: valueOfUInt64Value(criCPU.UsageCoreNanoSeconds),\n\t}\n}","line":{"from":943,"to":953}} {"id":100007622,"name":"addCRIPodMemoryStats","signature":"func addCRIPodMemoryStats(ps *statsapi.PodStats, criPodStat *runtimeapi.PodSandboxStats)","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"func addCRIPodMemoryStats(ps *statsapi.PodStats, criPodStat *runtimeapi.PodSandboxStats) {\n\tif criPodStat == nil || criPodStat.Linux == nil || criPodStat.Linux.Memory == nil {\n\t\treturn\n\t}\n\tcriMemory := criPodStat.Linux.Memory\n\tps.Memory = \u0026statsapi.MemoryStats{\n\t\tTime: metav1.NewTime(time.Unix(0, criMemory.Timestamp)),\n\t\tAvailableBytes: valueOfUInt64Value(criMemory.AvailableBytes),\n\t\tUsageBytes: valueOfUInt64Value(criMemory.UsageBytes),\n\t\tWorkingSetBytes: valueOfUInt64Value(criMemory.WorkingSetBytes),\n\t\tRSSBytes: valueOfUInt64Value(criMemory.RssBytes),\n\t\tPageFaults: valueOfUInt64Value(criMemory.PageFaults),\n\t\tMajorPageFaults: valueOfUInt64Value(criMemory.MajorPageFaults),\n\t}\n}","line":{"from":955,"to":969}} {"id":100007623,"name":"addCRIPodProcessStats","signature":"func addCRIPodProcessStats(ps *statsapi.PodStats, criPodStat *runtimeapi.PodSandboxStats)","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"func addCRIPodProcessStats(ps *statsapi.PodStats, criPodStat *runtimeapi.PodSandboxStats) {\n\tif criPodStat == nil || criPodStat.Linux == nil || criPodStat.Linux.Process == nil {\n\t\treturn\n\t}\n\tps.ProcessStats = \u0026statsapi.ProcessStats{\n\t\tProcessCount: valueOfUInt64Value(criPodStat.Linux.Process.ProcessCount),\n\t}\n}","line":{"from":971,"to":978}} {"id":100007624,"name":"valueOfUInt64Value","signature":"func valueOfUInt64Value(value *runtimeapi.UInt64Value) *uint64","file":"pkg/kubelet/stats/cri_stats_provider.go","code":"func valueOfUInt64Value(value *runtimeapi.UInt64Value) *uint64 {\n\tif value == nil {\n\t\treturn nil\n\t}\n\treturn \u0026value.Value\n}","line":{"from":980,"to":985}} {"id":100007625,"name":"listContainerNetworkStats","signature":"func (p *criStatsProvider) listContainerNetworkStats() (map[string]*statsapi.NetworkStats, error)","file":"pkg/kubelet/stats/cri_stats_provider_others.go","code":"// listContainerNetworkStats returns the network stats of all the running containers.\n// It should return (nil, nil) for platforms other than Windows.\nfunc (p *criStatsProvider) listContainerNetworkStats() (map[string]*statsapi.NetworkStats, error) {\n\treturn nil, nil\n}","line":{"from":26,"to":30}} {"id":100007626,"name":"HNSListEndpointRequest","signature":"func (s networkStats) HNSListEndpointRequest() ([]hcsshim.HNSEndpoint, error)","file":"pkg/kubelet/stats/cri_stats_provider_windows.go","code":"func (s networkStats) HNSListEndpointRequest() ([]hcsshim.HNSEndpoint, error) {\n\treturn hcsshim.HNSListEndpointRequest()\n}","line":{"from":41,"to":43}} {"id":100007627,"name":"GetHNSEndpointStats","signature":"func (s networkStats) GetHNSEndpointStats(endpointName string) (*hcsshim.HNSEndpointStats, error)","file":"pkg/kubelet/stats/cri_stats_provider_windows.go","code":"func (s networkStats) GetHNSEndpointStats(endpointName string) (*hcsshim.HNSEndpointStats, error) {\n\treturn hcsshim.GetHNSEndpointStats(endpointName)\n}","line":{"from":45,"to":47}} {"id":100007628,"name":"listContainerNetworkStats","signature":"func (p *criStatsProvider) listContainerNetworkStats() (map[string]*statsapi.NetworkStats, error)","file":"pkg/kubelet/stats/cri_stats_provider_windows.go","code":"// listContainerNetworkStats returns the network stats of all the running containers.\nfunc (p *criStatsProvider) listContainerNetworkStats() (map[string]*statsapi.NetworkStats, error) {\n\tnetworkStatsProvider := newNetworkStatsProvider(p)\n\n\tendpoints, err := networkStatsProvider.HNSListEndpointRequest()\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to fetch current HNS endpoints\")\n\t\treturn nil, err\n\t}\n\n\tnetworkStats := make(map[string]*statsapi.NetworkStats)\n\tfor _, endpoint := range endpoints {\n\t\tendpointStats, err := networkStatsProvider.GetHNSEndpointStats(endpoint.Id)\n\t\tif err != nil {\n\t\t\tklog.V(2).InfoS(\"Failed to fetch statistics for endpoint, continue to get stats for other endpoints\", \"endpointId\", endpoint.Id, \"containers\", endpoint.SharedContainers)\n\t\t\tcontinue\n\t\t}\n\n\t\t// only add the interface for each container if not already in the list\n\t\tfor _, cId := range endpoint.SharedContainers {\n\t\t\tnetworkStat, found := networkStats[cId]\n\t\t\tif found \u0026\u0026 networkStat.Name != endpoint.Name {\n\t\t\t\tiStat := hcsStatToInterfaceStat(endpointStats, endpoint.Name)\n\t\t\t\tnetworkStat.Interfaces = append(networkStat.Interfaces, iStat)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnetworkStats[cId] = hcsStatsToNetworkStats(p.clock.Now(), endpointStats, endpoint.Name)\n\t\t}\n\t}\n\n\treturn networkStats, nil\n}","line":{"from":49,"to":80}} {"id":100007629,"name":"hcsStatsToNetworkStats","signature":"func hcsStatsToNetworkStats(timestamp time.Time, hcsStats *hcsshim.HNSEndpointStats, endpointName string) *statsapi.NetworkStats","file":"pkg/kubelet/stats/cri_stats_provider_windows.go","code":"// hcsStatsToNetworkStats converts hcsshim.Statistics.Network to statsapi.NetworkStats\nfunc hcsStatsToNetworkStats(timestamp time.Time, hcsStats *hcsshim.HNSEndpointStats, endpointName string) *statsapi.NetworkStats {\n\tresult := \u0026statsapi.NetworkStats{\n\t\tTime: metav1.NewTime(timestamp),\n\t\tInterfaces: make([]statsapi.InterfaceStats, 0),\n\t}\n\n\tiStat := hcsStatToInterfaceStat(hcsStats, endpointName)\n\n\t// TODO: add support of multiple interfaces for getting default interface.\n\tresult.Interfaces = append(result.Interfaces, iStat)\n\tresult.InterfaceStats = iStat\n\n\treturn result\n}","line":{"from":82,"to":96}} {"id":100007630,"name":"hcsStatToInterfaceStat","signature":"func hcsStatToInterfaceStat(hcsStats *hcsshim.HNSEndpointStats, endpointName string) statsapi.InterfaceStats","file":"pkg/kubelet/stats/cri_stats_provider_windows.go","code":"func hcsStatToInterfaceStat(hcsStats *hcsshim.HNSEndpointStats, endpointName string) statsapi.InterfaceStats {\n\tiStat := statsapi.InterfaceStats{\n\t\tName: endpointName,\n\t\tRxBytes: \u0026hcsStats.BytesReceived,\n\t\tTxBytes: \u0026hcsStats.BytesSent,\n\t}\n\treturn iStat\n}","line":{"from":98,"to":105}} {"id":100007631,"name":"newNetworkStatsProvider","signature":"func newNetworkStatsProvider(p *criStatsProvider) windowsNetworkStatsProvider","file":"pkg/kubelet/stats/cri_stats_provider_windows.go","code":"// newNetworkStatsProvider uses the real windows hcsshim if not provided otherwise if the interface is provided\n// by the cristatsprovider in testing scenarios it uses that one\nfunc newNetworkStatsProvider(p *criStatsProvider) windowsNetworkStatsProvider {\n\tvar statsProvider windowsNetworkStatsProvider\n\tif p.windowsNetworkStatsProvider == nil {\n\t\tstatsProvider = networkStats{}\n\t} else {\n\t\tstatsProvider = p.windowsNetworkStatsProvider.(windowsNetworkStatsProvider)\n\t}\n\treturn statsProvider\n}","line":{"from":107,"to":117}} {"id":100007632,"name":"cadvisorInfoToCPUandMemoryStats","signature":"func cadvisorInfoToCPUandMemoryStats(info *cadvisorapiv2.ContainerInfo) (*statsapi.CPUStats, *statsapi.MemoryStats)","file":"pkg/kubelet/stats/helper.go","code":"func cadvisorInfoToCPUandMemoryStats(info *cadvisorapiv2.ContainerInfo) (*statsapi.CPUStats, *statsapi.MemoryStats) {\n\tcstat, found := latestContainerStats(info)\n\tif !found {\n\t\treturn nil, nil\n\t}\n\tvar cpuStats *statsapi.CPUStats\n\tvar memoryStats *statsapi.MemoryStats\n\tcpuStats = \u0026statsapi.CPUStats{\n\t\tTime: metav1.NewTime(cstat.Timestamp),\n\t\tUsageNanoCores: uint64Ptr(0),\n\t\tUsageCoreNanoSeconds: uint64Ptr(0),\n\t}\n\tif info.Spec.HasCpu {\n\t\tif cstat.CpuInst != nil {\n\t\t\tcpuStats.UsageNanoCores = \u0026cstat.CpuInst.Usage.Total\n\t\t}\n\t\tif cstat.Cpu != nil {\n\t\t\tcpuStats.UsageCoreNanoSeconds = \u0026cstat.Cpu.Usage.Total\n\t\t}\n\t}\n\tif info.Spec.HasMemory \u0026\u0026 cstat.Memory != nil {\n\t\tpageFaults := cstat.Memory.ContainerData.Pgfault\n\t\tmajorPageFaults := cstat.Memory.ContainerData.Pgmajfault\n\t\tmemoryStats = \u0026statsapi.MemoryStats{\n\t\t\tTime: metav1.NewTime(cstat.Timestamp),\n\t\t\tUsageBytes: \u0026cstat.Memory.Usage,\n\t\t\tWorkingSetBytes: \u0026cstat.Memory.WorkingSet,\n\t\t\tRSSBytes: \u0026cstat.Memory.RSS,\n\t\t\tPageFaults: \u0026pageFaults,\n\t\t\tMajorPageFaults: \u0026majorPageFaults,\n\t\t}\n\t\t// availableBytes = memory limit (if known) - workingset\n\t\tif !isMemoryUnlimited(info.Spec.Memory.Limit) {\n\t\t\tavailableBytes := info.Spec.Memory.Limit - cstat.Memory.WorkingSet\n\t\t\tmemoryStats.AvailableBytes = \u0026availableBytes\n\t\t}\n\t} else {\n\t\tmemoryStats = \u0026statsapi.MemoryStats{\n\t\t\tTime: metav1.NewTime(cstat.Timestamp),\n\t\t\tWorkingSetBytes: uint64Ptr(0),\n\t\t}\n\t}\n\treturn cpuStats, memoryStats\n}","line":{"from":38,"to":81}} {"id":100007633,"name":"cadvisorInfoToContainerStats","signature":"func cadvisorInfoToContainerStats(name string, info *cadvisorapiv2.ContainerInfo, rootFs, imageFs *cadvisorapiv2.FsInfo) *statsapi.ContainerStats","file":"pkg/kubelet/stats/helper.go","code":"// cadvisorInfoToContainerStats returns the statsapi.ContainerStats converted\n// from the container and filesystem info.\nfunc cadvisorInfoToContainerStats(name string, info *cadvisorapiv2.ContainerInfo, rootFs, imageFs *cadvisorapiv2.FsInfo) *statsapi.ContainerStats {\n\tresult := \u0026statsapi.ContainerStats{\n\t\tStartTime: metav1.NewTime(info.Spec.CreationTime),\n\t\tName: name,\n\t}\n\tcstat, found := latestContainerStats(info)\n\tif !found {\n\t\treturn result\n\t}\n\n\tcpu, memory := cadvisorInfoToCPUandMemoryStats(info)\n\tresult.CPU = cpu\n\tresult.Memory = memory\n\n\t// NOTE: if they can be found, log stats will be overwritten\n\t// by the caller, as it knows more information about the pod,\n\t// which is needed to determine log size.\n\tif rootFs != nil {\n\t\t// The container logs live on the node rootfs device\n\t\tresult.Logs = buildLogsStats(cstat, rootFs)\n\t}\n\n\tif imageFs != nil {\n\t\t// The container rootFs lives on the imageFs devices (which may not be the node root fs)\n\t\tresult.Rootfs = buildRootfsStats(cstat, imageFs)\n\t}\n\n\tcfs := cstat.Filesystem\n\tif cfs != nil {\n\t\tif cfs.BaseUsageBytes != nil {\n\t\t\tif result.Rootfs != nil {\n\t\t\t\trootfsUsage := *cfs.BaseUsageBytes\n\t\t\t\tresult.Rootfs.UsedBytes = \u0026rootfsUsage\n\t\t\t}\n\t\t\tif cfs.TotalUsageBytes != nil \u0026\u0026 result.Logs != nil {\n\t\t\t\tlogsUsage := *cfs.TotalUsageBytes - *cfs.BaseUsageBytes\n\t\t\t\tresult.Logs.UsedBytes = \u0026logsUsage\n\t\t\t}\n\t\t}\n\t\tif cfs.InodeUsage != nil \u0026\u0026 result.Rootfs != nil {\n\t\t\trootInodes := *cfs.InodeUsage\n\t\t\tresult.Rootfs.InodesUsed = \u0026rootInodes\n\t\t}\n\t}\n\n\tfor _, acc := range cstat.Accelerators {\n\t\tresult.Accelerators = append(result.Accelerators, statsapi.AcceleratorStats{\n\t\t\tMake: acc.Make,\n\t\t\tModel: acc.Model,\n\t\t\tID: acc.ID,\n\t\t\tMemoryTotal: acc.MemoryTotal,\n\t\t\tMemoryUsed: acc.MemoryUsed,\n\t\t\tDutyCycle: acc.DutyCycle,\n\t\t})\n\t}\n\n\tresult.UserDefinedMetrics = cadvisorInfoToUserDefinedMetrics(info)\n\n\treturn result\n}","line":{"from":83,"to":144}} {"id":100007634,"name":"cadvisorInfoToContainerCPUAndMemoryStats","signature":"func cadvisorInfoToContainerCPUAndMemoryStats(name string, info *cadvisorapiv2.ContainerInfo) *statsapi.ContainerStats","file":"pkg/kubelet/stats/helper.go","code":"// cadvisorInfoToContainerCPUAndMemoryStats returns the statsapi.ContainerStats converted\n// from the container and filesystem info.\nfunc cadvisorInfoToContainerCPUAndMemoryStats(name string, info *cadvisorapiv2.ContainerInfo) *statsapi.ContainerStats {\n\tresult := \u0026statsapi.ContainerStats{\n\t\tStartTime: metav1.NewTime(info.Spec.CreationTime),\n\t\tName: name,\n\t}\n\n\tcpu, memory := cadvisorInfoToCPUandMemoryStats(info)\n\tresult.CPU = cpu\n\tresult.Memory = memory\n\n\treturn result\n}","line":{"from":146,"to":159}} {"id":100007635,"name":"cadvisorInfoToProcessStats","signature":"func cadvisorInfoToProcessStats(info *cadvisorapiv2.ContainerInfo) *statsapi.ProcessStats","file":"pkg/kubelet/stats/helper.go","code":"func cadvisorInfoToProcessStats(info *cadvisorapiv2.ContainerInfo) *statsapi.ProcessStats {\n\tcstat, found := latestContainerStats(info)\n\tif !found || cstat.Processes == nil {\n\t\treturn nil\n\t}\n\tnum := cstat.Processes.ProcessCount\n\treturn \u0026statsapi.ProcessStats{ProcessCount: uint64Ptr(num)}\n}","line":{"from":161,"to":168}} {"id":100007636,"name":"cadvisorInfoToNetworkStats","signature":"func cadvisorInfoToNetworkStats(info *cadvisorapiv2.ContainerInfo) *statsapi.NetworkStats","file":"pkg/kubelet/stats/helper.go","code":"// cadvisorInfoToNetworkStats returns the statsapi.NetworkStats converted from\n// the container info from cadvisor.\nfunc cadvisorInfoToNetworkStats(info *cadvisorapiv2.ContainerInfo) *statsapi.NetworkStats {\n\tif !info.Spec.HasNetwork {\n\t\treturn nil\n\t}\n\tcstat, found := latestContainerStats(info)\n\tif !found {\n\t\treturn nil\n\t}\n\n\tif cstat.Network == nil {\n\t\treturn nil\n\t}\n\n\tiStats := statsapi.NetworkStats{\n\t\tTime: metav1.NewTime(cstat.Timestamp),\n\t}\n\n\tfor i := range cstat.Network.Interfaces {\n\t\tinter := cstat.Network.Interfaces[i]\n\t\tiStat := statsapi.InterfaceStats{\n\t\t\tName: inter.Name,\n\t\t\tRxBytes: \u0026inter.RxBytes,\n\t\t\tRxErrors: \u0026inter.RxErrors,\n\t\t\tTxBytes: \u0026inter.TxBytes,\n\t\t\tTxErrors: \u0026inter.TxErrors,\n\t\t}\n\n\t\tif inter.Name == defaultNetworkInterfaceName {\n\t\t\tiStats.InterfaceStats = iStat\n\t\t}\n\n\t\tiStats.Interfaces = append(iStats.Interfaces, iStat)\n\t}\n\n\treturn \u0026iStats\n}","line":{"from":170,"to":207}} {"id":100007637,"name":"cadvisorInfoToUserDefinedMetrics","signature":"func cadvisorInfoToUserDefinedMetrics(info *cadvisorapiv2.ContainerInfo) []statsapi.UserDefinedMetric","file":"pkg/kubelet/stats/helper.go","code":"// cadvisorInfoToUserDefinedMetrics returns the statsapi.UserDefinedMetric\n// converted from the container info from cadvisor.\nfunc cadvisorInfoToUserDefinedMetrics(info *cadvisorapiv2.ContainerInfo) []statsapi.UserDefinedMetric {\n\ttype specVal struct {\n\t\tref statsapi.UserDefinedMetricDescriptor\n\t\tvalType cadvisorapiv1.DataType\n\t\ttime time.Time\n\t\tvalue float64\n\t}\n\tudmMap := map[string]*specVal{}\n\tfor _, spec := range info.Spec.CustomMetrics {\n\t\tudmMap[spec.Name] = \u0026specVal{\n\t\t\tref: statsapi.UserDefinedMetricDescriptor{\n\t\t\t\tName: spec.Name,\n\t\t\t\tType: statsapi.UserDefinedMetricType(spec.Type),\n\t\t\t\tUnits: spec.Units,\n\t\t\t},\n\t\t\tvalType: spec.Format,\n\t\t}\n\t}\n\tfor _, stat := range info.Stats {\n\t\tfor name, values := range stat.CustomMetrics {\n\t\t\tspecVal, ok := udmMap[name]\n\t\t\tif !ok {\n\t\t\t\tklog.InfoS(\"Spec for custom metric is missing from cAdvisor output\", \"metric\", name, \"spec\", info.Spec, \"metrics\", stat.CustomMetrics)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor _, value := range values {\n\t\t\t\t// Pick the most recent value\n\t\t\t\tif value.Timestamp.Before(specVal.time) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tspecVal.time = value.Timestamp\n\t\t\t\tspecVal.value = value.FloatValue\n\t\t\t\tif specVal.valType == cadvisorapiv1.IntType {\n\t\t\t\t\tspecVal.value = float64(value.IntValue)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tvar udm []statsapi.UserDefinedMetric\n\tfor _, specVal := range udmMap {\n\t\tudm = append(udm, statsapi.UserDefinedMetric{\n\t\t\tUserDefinedMetricDescriptor: specVal.ref,\n\t\t\tTime: metav1.NewTime(specVal.time),\n\t\t\tValue: specVal.value,\n\t\t})\n\t}\n\treturn udm\n}","line":{"from":209,"to":258}} {"id":100007638,"name":"latestContainerStats","signature":"func latestContainerStats(info *cadvisorapiv2.ContainerInfo) (*cadvisorapiv2.ContainerStats, bool)","file":"pkg/kubelet/stats/helper.go","code":"// latestContainerStats returns the latest container stats from cadvisor, or nil if none exist\nfunc latestContainerStats(info *cadvisorapiv2.ContainerInfo) (*cadvisorapiv2.ContainerStats, bool) {\n\tstats := info.Stats\n\tif len(stats) \u003c 1 {\n\t\treturn nil, false\n\t}\n\tlatest := stats[len(stats)-1]\n\tif latest == nil {\n\t\treturn nil, false\n\t}\n\treturn latest, true\n}","line":{"from":260,"to":271}} {"id":100007639,"name":"isMemoryUnlimited","signature":"func isMemoryUnlimited(v uint64) bool","file":"pkg/kubelet/stats/helper.go","code":"func isMemoryUnlimited(v uint64) bool {\n\t// Size after which we consider memory to be \"unlimited\". This is not\n\t// MaxInt64 due to rounding by the kernel.\n\t// TODO: cadvisor should export this https://github.com/google/cadvisor/blob/master/metrics/prometheus.go#L596\n\tconst maxMemorySize = uint64(1 \u003c\u003c 62)\n\n\treturn v \u003e maxMemorySize\n}","line":{"from":273,"to":280}} {"id":100007640,"name":"getCgroupInfo","signature":"func getCgroupInfo(cadvisor cadvisor.Interface, containerName string, updateStats bool) (*cadvisorapiv2.ContainerInfo, error)","file":"pkg/kubelet/stats/helper.go","code":"// getCgroupInfo returns the information of the container with the specified\n// containerName from cadvisor.\nfunc getCgroupInfo(cadvisor cadvisor.Interface, containerName string, updateStats bool) (*cadvisorapiv2.ContainerInfo, error) {\n\tvar maxAge *time.Duration\n\tif updateStats {\n\t\tage := 0 * time.Second\n\t\tmaxAge = \u0026age\n\t}\n\tinfoMap, err := cadvisor.ContainerInfoV2(containerName, cadvisorapiv2.RequestOptions{\n\t\tIdType: cadvisorapiv2.TypeName,\n\t\tCount: 2, // 2 samples are needed to compute \"instantaneous\" CPU\n\t\tRecursive: false,\n\t\tMaxAge: maxAge,\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get container info for %q: %v\", containerName, err)\n\t}\n\tif len(infoMap) != 1 {\n\t\treturn nil, fmt.Errorf(\"unexpected number of containers: %v\", len(infoMap))\n\t}\n\tinfo := infoMap[containerName]\n\treturn \u0026info, nil\n}","line":{"from":282,"to":304}} {"id":100007641,"name":"getCgroupStats","signature":"func getCgroupStats(cadvisor cadvisor.Interface, containerName string, updateStats bool) (*cadvisorapiv2.ContainerStats, error)","file":"pkg/kubelet/stats/helper.go","code":"// getCgroupStats returns the latest stats of the container having the\n// specified containerName from cadvisor.\nfunc getCgroupStats(cadvisor cadvisor.Interface, containerName string, updateStats bool) (*cadvisorapiv2.ContainerStats, error) {\n\tinfo, err := getCgroupInfo(cadvisor, containerName, updateStats)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstats, found := latestContainerStats(info)\n\tif !found {\n\t\treturn nil, fmt.Errorf(\"failed to get latest stats from container info for %q\", containerName)\n\t}\n\treturn stats, nil\n}","line":{"from":306,"to":318}} {"id":100007642,"name":"buildLogsStats","signature":"func buildLogsStats(cstat *cadvisorapiv2.ContainerStats, rootFs *cadvisorapiv2.FsInfo) *statsapi.FsStats","file":"pkg/kubelet/stats/helper.go","code":"func buildLogsStats(cstat *cadvisorapiv2.ContainerStats, rootFs *cadvisorapiv2.FsInfo) *statsapi.FsStats {\n\tfsStats := \u0026statsapi.FsStats{\n\t\tTime: metav1.NewTime(cstat.Timestamp),\n\t\tAvailableBytes: \u0026rootFs.Available,\n\t\tCapacityBytes: \u0026rootFs.Capacity,\n\t\tInodesFree: rootFs.InodesFree,\n\t\tInodes: rootFs.Inodes,\n\t}\n\n\tif rootFs.Inodes != nil \u0026\u0026 rootFs.InodesFree != nil {\n\t\tlogsInodesUsed := *rootFs.Inodes - *rootFs.InodesFree\n\t\tfsStats.InodesUsed = \u0026logsInodesUsed\n\t}\n\treturn fsStats\n}","line":{"from":320,"to":334}} {"id":100007643,"name":"buildRootfsStats","signature":"func buildRootfsStats(cstat *cadvisorapiv2.ContainerStats, imageFs *cadvisorapiv2.FsInfo) *statsapi.FsStats","file":"pkg/kubelet/stats/helper.go","code":"func buildRootfsStats(cstat *cadvisorapiv2.ContainerStats, imageFs *cadvisorapiv2.FsInfo) *statsapi.FsStats {\n\treturn \u0026statsapi.FsStats{\n\t\tTime: metav1.NewTime(cstat.Timestamp),\n\t\tAvailableBytes: \u0026imageFs.Available,\n\t\tCapacityBytes: \u0026imageFs.Capacity,\n\t\tInodesFree: imageFs.InodesFree,\n\t\tInodes: imageFs.Inodes,\n\t}\n}","line":{"from":336,"to":344}} {"id":100007644,"name":"getUint64Value","signature":"func getUint64Value(value *uint64) uint64","file":"pkg/kubelet/stats/helper.go","code":"func getUint64Value(value *uint64) uint64 {\n\tif value == nil {\n\t\treturn 0\n\t}\n\n\treturn *value\n}","line":{"from":346,"to":352}} {"id":100007645,"name":"uint64Ptr","signature":"func uint64Ptr(i uint64) *uint64","file":"pkg/kubelet/stats/helper.go","code":"func uint64Ptr(i uint64) *uint64 {\n\treturn \u0026i\n}","line":{"from":354,"to":356}} {"id":100007646,"name":"calcEphemeralStorage","signature":"func calcEphemeralStorage(containers []statsapi.ContainerStats, volumes []statsapi.VolumeStats, rootFsInfo *cadvisorapiv2.FsInfo,","file":"pkg/kubelet/stats/helper.go","code":"func calcEphemeralStorage(containers []statsapi.ContainerStats, volumes []statsapi.VolumeStats, rootFsInfo *cadvisorapiv2.FsInfo,\n\tpodLogStats *statsapi.FsStats, etcHostsStats *statsapi.FsStats, isCRIStatsProvider bool) *statsapi.FsStats {\n\tresult := \u0026statsapi.FsStats{\n\t\tTime: metav1.NewTime(rootFsInfo.Timestamp),\n\t\tAvailableBytes: \u0026rootFsInfo.Available,\n\t\tCapacityBytes: \u0026rootFsInfo.Capacity,\n\t\tInodesFree: rootFsInfo.InodesFree,\n\t\tInodes: rootFsInfo.Inodes,\n\t}\n\tfor _, container := range containers {\n\t\taddContainerUsage(result, \u0026container, isCRIStatsProvider)\n\t}\n\tfor _, volume := range volumes {\n\t\tresult.UsedBytes = addUsage(result.UsedBytes, volume.FsStats.UsedBytes)\n\t\tresult.InodesUsed = addUsage(result.InodesUsed, volume.InodesUsed)\n\t\tresult.Time = maxUpdateTime(\u0026result.Time, \u0026volume.FsStats.Time)\n\t}\n\tif podLogStats != nil {\n\t\tresult.UsedBytes = addUsage(result.UsedBytes, podLogStats.UsedBytes)\n\t\tresult.InodesUsed = addUsage(result.InodesUsed, podLogStats.InodesUsed)\n\t\tresult.Time = maxUpdateTime(\u0026result.Time, \u0026podLogStats.Time)\n\t}\n\tif etcHostsStats != nil {\n\t\tresult.UsedBytes = addUsage(result.UsedBytes, etcHostsStats.UsedBytes)\n\t\tresult.InodesUsed = addUsage(result.InodesUsed, etcHostsStats.InodesUsed)\n\t\tresult.Time = maxUpdateTime(\u0026result.Time, \u0026etcHostsStats.Time)\n\t}\n\treturn result\n}","line":{"from":358,"to":386}} {"id":100007647,"name":"addContainerUsage","signature":"func addContainerUsage(stat *statsapi.FsStats, container *statsapi.ContainerStats, isCRIStatsProvider bool)","file":"pkg/kubelet/stats/helper.go","code":"func addContainerUsage(stat *statsapi.FsStats, container *statsapi.ContainerStats, isCRIStatsProvider bool) {\n\tif rootFs := container.Rootfs; rootFs != nil {\n\t\tstat.Time = maxUpdateTime(\u0026stat.Time, \u0026rootFs.Time)\n\t\tstat.InodesUsed = addUsage(stat.InodesUsed, rootFs.InodesUsed)\n\t\tstat.UsedBytes = addUsage(stat.UsedBytes, rootFs.UsedBytes)\n\t\tif logs := container.Logs; logs != nil {\n\t\t\tstat.UsedBytes = addUsage(stat.UsedBytes, logs.UsedBytes)\n\t\t\t// We have accurate container log inode usage for CRI stats provider.\n\t\t\tif isCRIStatsProvider {\n\t\t\t\tstat.InodesUsed = addUsage(stat.InodesUsed, logs.InodesUsed)\n\t\t\t}\n\t\t\tstat.Time = maxUpdateTime(\u0026stat.Time, \u0026logs.Time)\n\t\t}\n\t}\n}","line":{"from":388,"to":402}} {"id":100007648,"name":"maxUpdateTime","signature":"func maxUpdateTime(first, second *metav1.Time) metav1.Time","file":"pkg/kubelet/stats/helper.go","code":"func maxUpdateTime(first, second *metav1.Time) metav1.Time {\n\tif first.Before(second) {\n\t\treturn *second\n\t}\n\treturn *first\n}","line":{"from":404,"to":409}} {"id":100007649,"name":"addUsage","signature":"func addUsage(first, second *uint64) *uint64","file":"pkg/kubelet/stats/helper.go","code":"func addUsage(first, second *uint64) *uint64 {\n\tif first == nil {\n\t\treturn second\n\t} else if second == nil {\n\t\treturn first\n\t}\n\ttotal := *first + *second\n\treturn \u0026total\n}","line":{"from":411,"to":419}} {"id":100007650,"name":"makePodStorageStats","signature":"func makePodStorageStats(s *statsapi.PodStats, rootFsInfo *cadvisorapiv2.FsInfo, resourceAnalyzer stats.ResourceAnalyzer, hostStatsProvider HostStatsProvider, isCRIStatsProvider bool)","file":"pkg/kubelet/stats/helper.go","code":"func makePodStorageStats(s *statsapi.PodStats, rootFsInfo *cadvisorapiv2.FsInfo, resourceAnalyzer stats.ResourceAnalyzer, hostStatsProvider HostStatsProvider, isCRIStatsProvider bool) {\n\tpodNs := s.PodRef.Namespace\n\tpodName := s.PodRef.Name\n\tpodUID := types.UID(s.PodRef.UID)\n\tvar ephemeralStats []statsapi.VolumeStats\n\tif vstats, found := resourceAnalyzer.GetPodVolumeStats(podUID); found {\n\t\tephemeralStats = make([]statsapi.VolumeStats, len(vstats.EphemeralVolumes))\n\t\tcopy(ephemeralStats, vstats.EphemeralVolumes)\n\t\ts.VolumeStats = append(append([]statsapi.VolumeStats{}, vstats.EphemeralVolumes...), vstats.PersistentVolumes...)\n\n\t}\n\tlogStats, err := hostStatsProvider.getPodLogStats(podNs, podName, podUID, rootFsInfo)\n\tif err != nil {\n\t\tklog.V(6).ErrorS(err, \"Unable to fetch pod log stats\", \"pod\", klog.KRef(podNs, podName))\n\t\t// If people do in-place upgrade, there might be pods still using\n\t\t// the old log path. For those pods, no pod log stats is returned.\n\t\t// We should continue generating other stats in that case.\n\t\t// calcEphemeralStorage tolerants logStats == nil.\n\t}\n\tetcHostsStats, err := hostStatsProvider.getPodEtcHostsStats(podUID, rootFsInfo)\n\tif err != nil {\n\t\tklog.V(6).ErrorS(err, \"Unable to fetch pod etc hosts stats\", \"pod\", klog.KRef(podNs, podName))\n\t}\n\ts.EphemeralStorage = calcEphemeralStorage(s.Containers, ephemeralStats, rootFsInfo, logStats, etcHostsStats, isCRIStatsProvider)\n}","line":{"from":421,"to":445}} {"id":100007651,"name":"NewHostStatsProvider","signature":"func NewHostStatsProvider(osInterface kubecontainer.OSInterface, podEtcHostsPathFunc PodEtcHostsPathFunc) HostStatsProvider","file":"pkg/kubelet/stats/host_stats_provider.go","code":"// NewHostStatsProvider returns a new HostStatsProvider type struct.\nfunc NewHostStatsProvider(osInterface kubecontainer.OSInterface, podEtcHostsPathFunc PodEtcHostsPathFunc) HostStatsProvider {\n\treturn hostStatsProvider{\n\t\tosInterface: osInterface,\n\t\tpodEtcHostsPathFunc: podEtcHostsPathFunc,\n\t}\n}","line":{"from":56,"to":62}} {"id":100007652,"name":"getPodLogStats","signature":"func (h hostStatsProvider) getPodLogStats(podNamespace, podName string, podUID types.UID, rootFsInfo *cadvisorapiv2.FsInfo) (*statsapi.FsStats, error)","file":"pkg/kubelet/stats/host_stats_provider.go","code":"func (h hostStatsProvider) getPodLogStats(podNamespace, podName string, podUID types.UID, rootFsInfo *cadvisorapiv2.FsInfo) (*statsapi.FsStats, error) {\n\tmetricsByPath, err := h.podLogMetrics(podNamespace, podName, podUID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn metricsByPathToFsStats(metricsByPath, rootFsInfo)\n}","line":{"from":64,"to":70}} {"id":100007653,"name":"getPodContainerLogStats","signature":"func (h hostStatsProvider) getPodContainerLogStats(podNamespace, podName string, podUID types.UID, containerName string, rootFsInfo *cadvisorapiv2.FsInfo) (*statsapi.FsStats, error)","file":"pkg/kubelet/stats/host_stats_provider.go","code":"// getPodContainerLogStats gets stats for container\nfunc (h hostStatsProvider) getPodContainerLogStats(podNamespace, podName string, podUID types.UID, containerName string, rootFsInfo *cadvisorapiv2.FsInfo) (*statsapi.FsStats, error) {\n\tmetricsByPath, err := h.podContainerLogMetrics(podNamespace, podName, podUID, containerName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn metricsByPathToFsStats(metricsByPath, rootFsInfo)\n}","line":{"from":72,"to":79}} {"id":100007654,"name":"getPodEtcHostsStats","signature":"func (h hostStatsProvider) getPodEtcHostsStats(podUID types.UID, rootFsInfo *cadvisorapiv2.FsInfo) (*statsapi.FsStats, error)","file":"pkg/kubelet/stats/host_stats_provider.go","code":"// getPodEtcHostsStats gets status for pod etc hosts usage\nfunc (h hostStatsProvider) getPodEtcHostsStats(podUID types.UID, rootFsInfo *cadvisorapiv2.FsInfo) (*statsapi.FsStats, error) {\n\t// Runtimes may not support etc hosts file (Windows with docker)\n\tpodEtcHostsPath := h.podEtcHostsPathFunc(podUID)\n\t// Some pods have an explicit /etc/hosts mount and the Kubelet will not create an etc-hosts file for them\n\tif _, err := os.Stat(podEtcHostsPath); os.IsNotExist(err) {\n\t\treturn nil, nil\n\t}\n\n\tmetrics := volume.NewMetricsDu(podEtcHostsPath)\n\thostMetrics, err := metrics.GetMetrics()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get stats %v\", err)\n\t}\n\tresult := rootFsInfoToFsStats(rootFsInfo)\n\tusedBytes := uint64(hostMetrics.Used.Value())\n\tinodesUsed := uint64(hostMetrics.InodesUsed.Value())\n\tresult.UsedBytes = addUsage(result.UsedBytes, \u0026usedBytes)\n\tresult.InodesUsed = addUsage(result.InodesUsed, \u0026inodesUsed)\n\tresult.Time = maxUpdateTime(\u0026result.Time, \u0026hostMetrics.Time)\n\treturn result, nil\n}","line":{"from":81,"to":102}} {"id":100007655,"name":"podLogMetrics","signature":"func (h hostStatsProvider) podLogMetrics(podNamespace, podName string, podUID types.UID) (metricsProviderByPath, error)","file":"pkg/kubelet/stats/host_stats_provider.go","code":"func (h hostStatsProvider) podLogMetrics(podNamespace, podName string, podUID types.UID) (metricsProviderByPath, error) {\n\tpodLogsDirectoryPath := kuberuntime.BuildPodLogsDirectory(podNamespace, podName, podUID)\n\treturn h.fileMetricsByDir(podLogsDirectoryPath)\n}","line":{"from":104,"to":107}} {"id":100007656,"name":"podContainerLogMetrics","signature":"func (h hostStatsProvider) podContainerLogMetrics(podNamespace, podName string, podUID types.UID, containerName string) (metricsProviderByPath, error)","file":"pkg/kubelet/stats/host_stats_provider.go","code":"func (h hostStatsProvider) podContainerLogMetrics(podNamespace, podName string, podUID types.UID, containerName string) (metricsProviderByPath, error) {\n\tpodContainerLogsDirectoryPath := kuberuntime.BuildContainerLogsDirectory(podNamespace, podName, podUID, containerName)\n\treturn h.fileMetricsByDir(podContainerLogsDirectoryPath)\n}","line":{"from":109,"to":112}} {"id":100007657,"name":"fileMetricsByDir","signature":"func (h hostStatsProvider) fileMetricsByDir(dirname string) (metricsProviderByPath, error)","file":"pkg/kubelet/stats/host_stats_provider.go","code":"// fileMetricsByDir returns metrics by path for each file under specified directory\nfunc (h hostStatsProvider) fileMetricsByDir(dirname string) (metricsProviderByPath, error) {\n\tfiles, err := h.osInterface.ReadDir(dirname)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresults := metricsProviderByPath{}\n\tfor _, f := range files {\n\t\tif f.IsDir() {\n\t\t\tcontinue\n\t\t}\n\t\t// Only include *files* under pod log directory.\n\t\tfpath := filepath.Join(dirname, f.Name())\n\t\tresults[fpath] = volume.NewMetricsDu(fpath)\n\t}\n\treturn results, nil\n}","line":{"from":114,"to":130}} {"id":100007658,"name":"metricsByPathToFsStats","signature":"func metricsByPathToFsStats(metricsByPath metricsProviderByPath, rootFsInfo *cadvisorapiv2.FsInfo) (*statsapi.FsStats, error)","file":"pkg/kubelet/stats/host_stats_provider.go","code":"// metricsByPathToFsStats converts a metrics provider by path to fs stats\nfunc metricsByPathToFsStats(metricsByPath metricsProviderByPath, rootFsInfo *cadvisorapiv2.FsInfo) (*statsapi.FsStats, error) {\n\tresult := rootFsInfoToFsStats(rootFsInfo)\n\tfor fpath, metrics := range metricsByPath {\n\t\thostMetrics, err := metrics.GetMetrics()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get fsstats for %q: %v\", fpath, err)\n\t\t}\n\t\tusedBytes := uint64(hostMetrics.Used.Value())\n\t\tinodesUsed := uint64(hostMetrics.InodesUsed.Value())\n\t\tresult.UsedBytes = addUsage(result.UsedBytes, \u0026usedBytes)\n\t\tresult.InodesUsed = addUsage(result.InodesUsed, \u0026inodesUsed)\n\t\tresult.Time = maxUpdateTime(\u0026result.Time, \u0026hostMetrics.Time)\n\t}\n\treturn result, nil\n}","line":{"from":132,"to":147}} {"id":100007659,"name":"rootFsInfoToFsStats","signature":"func rootFsInfoToFsStats(rootFsInfo *cadvisorapiv2.FsInfo) *statsapi.FsStats","file":"pkg/kubelet/stats/host_stats_provider.go","code":"// rootFsInfoToFsStats is a utility to convert rootFsInfo into statsapi.FsStats\nfunc rootFsInfoToFsStats(rootFsInfo *cadvisorapiv2.FsInfo) *statsapi.FsStats {\n\treturn \u0026statsapi.FsStats{\n\t\tTime: metav1.NewTime(rootFsInfo.Timestamp),\n\t\tAvailableBytes: \u0026rootFsInfo.Available,\n\t\tCapacityBytes: \u0026rootFsInfo.Capacity,\n\t\tInodesFree: rootFsInfo.InodesFree,\n\t\tInodes: rootFsInfo.Inodes,\n\t}\n}","line":{"from":149,"to":158}} {"id":100007660,"name":"Stats","signature":"func Stats() (*statsapi.RlimitStats, error)","file":"pkg/kubelet/stats/pidlimit/pidlimit_linux.go","code":"// Stats provides basic information about max and current process count\nfunc Stats() (*statsapi.RlimitStats, error) {\n\trlimit := \u0026statsapi.RlimitStats{}\n\n\ttaskMax := int64(-1)\n\t// Calculate the mininum of kernel.pid_max and kernel.threads-max as they both specify the\n\t// system-wide limit on the number of tasks.\n\tfor _, file := range []string{\"/proc/sys/kernel/pid_max\", \"/proc/sys/kernel/threads-max\"} {\n\t\tif content, err := os.ReadFile(file); err == nil {\n\t\t\tif limit, err := strconv.ParseInt(string(content[:len(content)-1]), 10, 64); err == nil {\n\t\t\t\tif taskMax == -1 || taskMax \u003e limit {\n\t\t\t\t\ttaskMax = limit\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// Both reads did not fail.\n\tif taskMax \u003e= 0 {\n\t\trlimit.MaxPID = \u0026taskMax\n\t}\n\n\t// Prefer to read \"/proc/loadavg\" when possible because sysinfo(2)\n\t// returns truncated number when greater than 65538. See\n\t// https://github.com/kubernetes/kubernetes/issues/107107\n\tif procs, err := runningTaskCount(); err == nil {\n\t\trlimit.NumOfRunningProcesses = \u0026procs\n\t} else {\n\t\tvar info syscall.Sysinfo_t\n\t\tsyscall.Sysinfo(\u0026info)\n\t\tprocs := int64(info.Procs)\n\t\trlimit.NumOfRunningProcesses = \u0026procs\n\t}\n\n\trlimit.Time = v1.NewTime(time.Now())\n\n\treturn rlimit, nil\n}","line":{"from":34,"to":70}} {"id":100007661,"name":"runningTaskCount","signature":"func runningTaskCount() (int64, error)","file":"pkg/kubelet/stats/pidlimit/pidlimit_linux.go","code":"func runningTaskCount() (int64, error) {\n\t// Example: 1.36 3.49 4.53 2/3518 3715089\n\tbytes, err := os.ReadFile(\"/proc/loadavg\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tfields := strings.Fields(string(bytes))\n\tif len(fields) \u003c 5 {\n\t\treturn 0, fmt.Errorf(\"not enough fields in /proc/loadavg\")\n\t}\n\tsubfields := strings.Split(fields[3], \"/\")\n\tif len(subfields) != 2 {\n\t\treturn 0, fmt.Errorf(\"error parsing fourth field of /proc/loadavg\")\n\t}\n\treturn strconv.ParseInt(subfields[1], 10, 64)\n}","line":{"from":72,"to":87}} {"id":100007662,"name":"Stats","signature":"func Stats() (*statsapi.RlimitStats, error)","file":"pkg/kubelet/stats/pidlimit/pidlimit_unsupported.go","code":"// Stats provides basic information about max and current process count\nfunc Stats() (*statsapi.RlimitStats, error) {\n\treturn nil, nil\n}","line":{"from":26,"to":29}} {"id":100007663,"name":"NewCRIStatsProvider","signature":"func NewCRIStatsProvider(","file":"pkg/kubelet/stats/provider.go","code":"// NewCRIStatsProvider returns a Provider that provides the node stats\n// from cAdvisor and the container stats from CRI.\nfunc NewCRIStatsProvider(\n\tcadvisor cadvisor.Interface,\n\tresourceAnalyzer stats.ResourceAnalyzer,\n\tpodManager kubepod.Manager,\n\truntimeCache kubecontainer.RuntimeCache,\n\truntimeService internalapi.RuntimeService,\n\timageService internalapi.ImageManagerService,\n\thostStatsProvider HostStatsProvider,\n\tpodAndContainerStatsFromCRI bool,\n) *Provider {\n\treturn newStatsProvider(cadvisor, podManager, runtimeCache, newCRIStatsProvider(cadvisor, resourceAnalyzer,\n\t\truntimeService, imageService, hostStatsProvider, podAndContainerStatsFromCRI))\n}","line":{"from":36,"to":50}} {"id":100007664,"name":"NewCadvisorStatsProvider","signature":"func NewCadvisorStatsProvider(","file":"pkg/kubelet/stats/provider.go","code":"// NewCadvisorStatsProvider returns a containerStatsProvider that provides both\n// the node and the container stats from cAdvisor.\nfunc NewCadvisorStatsProvider(\n\tcadvisor cadvisor.Interface,\n\tresourceAnalyzer stats.ResourceAnalyzer,\n\tpodManager kubepod.Manager,\n\truntimeCache kubecontainer.RuntimeCache,\n\timageService kubecontainer.ImageService,\n\tstatusProvider status.PodStatusProvider,\n\thostStatsProvider HostStatsProvider,\n) *Provider {\n\treturn newStatsProvider(cadvisor, podManager, runtimeCache, newCadvisorStatsProvider(cadvisor, resourceAnalyzer, imageService, statusProvider, hostStatsProvider))\n}","line":{"from":52,"to":64}} {"id":100007665,"name":"newStatsProvider","signature":"func newStatsProvider(","file":"pkg/kubelet/stats/provider.go","code":"// newStatsProvider returns a new Provider that provides node stats from\n// cAdvisor and the container stats using the containerStatsProvider.\nfunc newStatsProvider(\n\tcadvisor cadvisor.Interface,\n\tpodManager kubepod.Manager,\n\truntimeCache kubecontainer.RuntimeCache,\n\tcontainerStatsProvider containerStatsProvider,\n) *Provider {\n\treturn \u0026Provider{\n\t\tcadvisor: cadvisor,\n\t\tpodManager: podManager,\n\t\truntimeCache: runtimeCache,\n\t\tcontainerStatsProvider: containerStatsProvider,\n\t}\n}","line":{"from":66,"to":80}} {"id":100007666,"name":"RlimitStats","signature":"func (p *Provider) RlimitStats() (*statsapi.RlimitStats, error)","file":"pkg/kubelet/stats/provider.go","code":"// RlimitStats returns base information about process count\nfunc (p *Provider) RlimitStats() (*statsapi.RlimitStats, error) {\n\treturn pidlimit.Stats()\n}","line":{"from":100,"to":103}} {"id":100007667,"name":"GetCgroupStats","signature":"func (p *Provider) GetCgroupStats(cgroupName string, updateStats bool) (*statsapi.ContainerStats, *statsapi.NetworkStats, error)","file":"pkg/kubelet/stats/provider.go","code":"// GetCgroupStats returns the stats of the cgroup with the cgroupName. Note that\n// this function doesn't generate filesystem stats.\nfunc (p *Provider) GetCgroupStats(cgroupName string, updateStats bool) (*statsapi.ContainerStats, *statsapi.NetworkStats, error) {\n\tinfo, err := getCgroupInfo(p.cadvisor, cgroupName, updateStats)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to get cgroup stats for %q: %v\", cgroupName, err)\n\t}\n\t// Rootfs and imagefs doesn't make sense for raw cgroup.\n\ts := cadvisorInfoToContainerStats(cgroupName, info, nil, nil)\n\tn := cadvisorInfoToNetworkStats(info)\n\treturn s, n, nil\n}","line":{"from":105,"to":116}} {"id":100007668,"name":"GetCgroupCPUAndMemoryStats","signature":"func (p *Provider) GetCgroupCPUAndMemoryStats(cgroupName string, updateStats bool) (*statsapi.ContainerStats, error)","file":"pkg/kubelet/stats/provider.go","code":"// GetCgroupCPUAndMemoryStats returns the CPU and memory stats of the cgroup with the cgroupName. Note that\n// this function doesn't generate filesystem stats.\nfunc (p *Provider) GetCgroupCPUAndMemoryStats(cgroupName string, updateStats bool) (*statsapi.ContainerStats, error) {\n\tinfo, err := getCgroupInfo(p.cadvisor, cgroupName, updateStats)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get cgroup stats for %q: %v\", cgroupName, err)\n\t}\n\t// Rootfs and imagefs doesn't make sense for raw cgroup.\n\ts := cadvisorInfoToContainerCPUAndMemoryStats(cgroupName, info)\n\treturn s, nil\n}","line":{"from":118,"to":128}} {"id":100007669,"name":"RootFsStats","signature":"func (p *Provider) RootFsStats() (*statsapi.FsStats, error)","file":"pkg/kubelet/stats/provider.go","code":"// RootFsStats returns the stats of the node root filesystem.\nfunc (p *Provider) RootFsStats() (*statsapi.FsStats, error) {\n\trootFsInfo, err := p.cadvisor.RootFsInfo()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get rootFs info: %v\", err)\n\t}\n\n\tvar nodeFsInodesUsed *uint64\n\tif rootFsInfo.Inodes != nil \u0026\u0026 rootFsInfo.InodesFree != nil {\n\t\tnodeFsIU := *rootFsInfo.Inodes - *rootFsInfo.InodesFree\n\t\tnodeFsInodesUsed = \u0026nodeFsIU\n\t}\n\n\t// Get the root container stats's timestamp, which will be used as the\n\t// imageFs stats timestamp. Don't force a stats update, as we only want the timestamp.\n\trootStats, err := getCgroupStats(p.cadvisor, \"/\", false)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get root container stats: %v\", err)\n\t}\n\n\treturn \u0026statsapi.FsStats{\n\t\tTime: metav1.NewTime(rootStats.Timestamp),\n\t\tAvailableBytes: \u0026rootFsInfo.Available,\n\t\tCapacityBytes: \u0026rootFsInfo.Capacity,\n\t\tUsedBytes: \u0026rootFsInfo.Usage,\n\t\tInodesFree: rootFsInfo.InodesFree,\n\t\tInodes: rootFsInfo.Inodes,\n\t\tInodesUsed: nodeFsInodesUsed,\n\t}, nil\n}","line":{"from":130,"to":159}} {"id":100007670,"name":"GetContainerInfo","signature":"func (p *Provider) GetContainerInfo(ctx context.Context, podFullName string, podUID types.UID, containerName string, req *cadvisorapiv1.ContainerInfoRequest) (*cadvisorapiv1.ContainerInfo, error)","file":"pkg/kubelet/stats/provider.go","code":"// GetContainerInfo returns stats (from cAdvisor) for a container.\nfunc (p *Provider) GetContainerInfo(ctx context.Context, podFullName string, podUID types.UID, containerName string, req *cadvisorapiv1.ContainerInfoRequest) (*cadvisorapiv1.ContainerInfo, error) {\n\t// Resolve and type convert back again.\n\t// We need the static pod UID but the kubecontainer API works with types.UID.\n\tpodUID = types.UID(p.podManager.TranslatePodUID(podUID))\n\n\tpods, err := p.runtimeCache.GetPods(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpod := kubecontainer.Pods(pods).FindPod(podFullName, podUID)\n\tcontainer := pod.FindContainerByName(containerName)\n\tif container == nil {\n\t\treturn nil, kubecontainer.ErrContainerNotFound\n\t}\n\n\tci, err := p.cadvisor.DockerContainer(container.ID.ID, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026ci, nil\n}","line":{"from":161,"to":182}} {"id":100007671,"name":"GetRawContainerInfo","signature":"func (p *Provider) GetRawContainerInfo(containerName string, req *cadvisorapiv1.ContainerInfoRequest, subcontainers bool) (map[string]*cadvisorapiv1.ContainerInfo, error)","file":"pkg/kubelet/stats/provider.go","code":"// GetRawContainerInfo returns the stats (from cadvisor) for a non-Kubernetes\n// container.\nfunc (p *Provider) GetRawContainerInfo(containerName string, req *cadvisorapiv1.ContainerInfoRequest, subcontainers bool) (map[string]*cadvisorapiv1.ContainerInfo, error) {\n\tif subcontainers {\n\t\treturn p.cadvisor.SubcontainerInfo(containerName, req)\n\t}\n\tcontainerInfo, err := p.cadvisor.ContainerInfo(containerName, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn map[string]*cadvisorapiv1.ContainerInfo{\n\t\tcontainerInfo.Name: containerInfo,\n\t}, nil\n}","line":{"from":184,"to":197}} {"id":100007672,"name":"HasDedicatedImageFs","signature":"func (p *Provider) HasDedicatedImageFs(ctx context.Context) (bool, error)","file":"pkg/kubelet/stats/provider.go","code":"// HasDedicatedImageFs returns true if a dedicated image filesystem exists for storing images.\nfunc (p *Provider) HasDedicatedImageFs(ctx context.Context) (bool, error) {\n\tdevice, err := p.containerStatsProvider.ImageFsDevice(ctx)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\trootFsInfo, err := p.cadvisor.RootFsInfo()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn device != rootFsInfo.Device, nil\n}","line":{"from":199,"to":210}} {"id":100007673,"name":"GenerateContainersReadyCondition","signature":"func GenerateContainersReadyCondition(spec *v1.PodSpec, containerStatuses []v1.ContainerStatus, podPhase v1.PodPhase) v1.PodCondition","file":"pkg/kubelet/status/generate.go","code":"// GenerateContainersReadyCondition returns the status of \"ContainersReady\" condition.\n// The status of \"ContainersReady\" condition is true when all containers are ready.\nfunc GenerateContainersReadyCondition(spec *v1.PodSpec, containerStatuses []v1.ContainerStatus, podPhase v1.PodPhase) v1.PodCondition {\n\t// Find if all containers are ready or not.\n\tif containerStatuses == nil {\n\t\treturn v1.PodCondition{\n\t\t\tType: v1.ContainersReady,\n\t\t\tStatus: v1.ConditionFalse,\n\t\t\tReason: UnknownContainerStatuses,\n\t\t}\n\t}\n\tunknownContainers := []string{}\n\tunreadyContainers := []string{}\n\tfor _, container := range spec.Containers {\n\t\tif containerStatus, ok := podutil.GetContainerStatus(containerStatuses, container.Name); ok {\n\t\t\tif !containerStatus.Ready {\n\t\t\t\tunreadyContainers = append(unreadyContainers, container.Name)\n\t\t\t}\n\t\t} else {\n\t\t\tunknownContainers = append(unknownContainers, container.Name)\n\t\t}\n\t}\n\n\t// If all containers are known and succeeded, just return PodCompleted.\n\tif podPhase == v1.PodSucceeded \u0026\u0026 len(unknownContainers) == 0 {\n\t\treturn generateContainersReadyConditionForTerminalPhase(podPhase)\n\t}\n\n\t// If the pod phase is failed, explicitly set the ready condition to false for containers since they may be in progress of terminating.\n\tif podPhase == v1.PodFailed {\n\t\treturn generateContainersReadyConditionForTerminalPhase(podPhase)\n\t}\n\n\t// Generate message for containers in unknown condition.\n\tunreadyMessages := []string{}\n\tif len(unknownContainers) \u003e 0 {\n\t\tunreadyMessages = append(unreadyMessages, fmt.Sprintf(\"containers with unknown status: %s\", unknownContainers))\n\t}\n\tif len(unreadyContainers) \u003e 0 {\n\t\tunreadyMessages = append(unreadyMessages, fmt.Sprintf(\"containers with unready status: %s\", unreadyContainers))\n\t}\n\tunreadyMessage := strings.Join(unreadyMessages, \", \")\n\tif unreadyMessage != \"\" {\n\t\treturn v1.PodCondition{\n\t\t\tType: v1.ContainersReady,\n\t\t\tStatus: v1.ConditionFalse,\n\t\t\tReason: ContainersNotReady,\n\t\t\tMessage: unreadyMessage,\n\t\t}\n\t}\n\n\treturn v1.PodCondition{\n\t\tType: v1.ContainersReady,\n\t\tStatus: v1.ConditionTrue,\n\t}\n}","line":{"from":45,"to":100}} {"id":100007674,"name":"GeneratePodReadyCondition","signature":"func GeneratePodReadyCondition(spec *v1.PodSpec, conditions []v1.PodCondition, containerStatuses []v1.ContainerStatus, podPhase v1.PodPhase) v1.PodCondition","file":"pkg/kubelet/status/generate.go","code":"// GeneratePodReadyCondition returns \"Ready\" condition of a pod.\n// The status of \"Ready\" condition is \"True\", if all containers in a pod are ready\n// AND all matching conditions specified in the ReadinessGates have status equal to \"True\".\nfunc GeneratePodReadyCondition(spec *v1.PodSpec, conditions []v1.PodCondition, containerStatuses []v1.ContainerStatus, podPhase v1.PodPhase) v1.PodCondition {\n\tcontainersReady := GenerateContainersReadyCondition(spec, containerStatuses, podPhase)\n\t// If the status of ContainersReady is not True, return the same status, reason and message as ContainersReady.\n\tif containersReady.Status != v1.ConditionTrue {\n\t\treturn v1.PodCondition{\n\t\t\tType: v1.PodReady,\n\t\t\tStatus: containersReady.Status,\n\t\t\tReason: containersReady.Reason,\n\t\t\tMessage: containersReady.Message,\n\t\t}\n\t}\n\n\t// Evaluate corresponding conditions specified in readiness gate\n\t// Generate message if any readiness gate is not satisfied.\n\tunreadyMessages := []string{}\n\tfor _, rg := range spec.ReadinessGates {\n\t\t_, c := podutil.GetPodConditionFromList(conditions, rg.ConditionType)\n\t\tif c == nil {\n\t\t\tunreadyMessages = append(unreadyMessages, fmt.Sprintf(\"corresponding condition of pod readiness gate %q does not exist.\", string(rg.ConditionType)))\n\t\t} else if c.Status != v1.ConditionTrue {\n\t\t\tunreadyMessages = append(unreadyMessages, fmt.Sprintf(\"the status of pod readiness gate %q is not \\\"True\\\", but %v\", string(rg.ConditionType), c.Status))\n\t\t}\n\t}\n\n\t// Set \"Ready\" condition to \"False\" if any readiness gate is not ready.\n\tif len(unreadyMessages) != 0 {\n\t\tunreadyMessage := strings.Join(unreadyMessages, \", \")\n\t\treturn v1.PodCondition{\n\t\t\tType: v1.PodReady,\n\t\t\tStatus: v1.ConditionFalse,\n\t\t\tReason: ReadinessGatesNotReady,\n\t\t\tMessage: unreadyMessage,\n\t\t}\n\t}\n\n\treturn v1.PodCondition{\n\t\tType: v1.PodReady,\n\t\tStatus: v1.ConditionTrue,\n\t}\n}","line":{"from":102,"to":144}} {"id":100007675,"name":"GeneratePodInitializedCondition","signature":"func GeneratePodInitializedCondition(spec *v1.PodSpec, containerStatuses []v1.ContainerStatus, podPhase v1.PodPhase) v1.PodCondition","file":"pkg/kubelet/status/generate.go","code":"// GeneratePodInitializedCondition returns initialized condition if all init containers in a pod are ready, else it\n// returns an uninitialized condition.\nfunc GeneratePodInitializedCondition(spec *v1.PodSpec, containerStatuses []v1.ContainerStatus, podPhase v1.PodPhase) v1.PodCondition {\n\t// Find if all containers are ready or not.\n\tif containerStatuses == nil \u0026\u0026 len(spec.InitContainers) \u003e 0 {\n\t\treturn v1.PodCondition{\n\t\t\tType: v1.PodInitialized,\n\t\t\tStatus: v1.ConditionFalse,\n\t\t\tReason: UnknownContainerStatuses,\n\t\t}\n\t}\n\tunknownContainers := []string{}\n\tunreadyContainers := []string{}\n\tfor _, container := range spec.InitContainers {\n\t\tif containerStatus, ok := podutil.GetContainerStatus(containerStatuses, container.Name); ok {\n\t\t\tif !containerStatus.Ready {\n\t\t\t\tunreadyContainers = append(unreadyContainers, container.Name)\n\t\t\t}\n\t\t} else {\n\t\t\tunknownContainers = append(unknownContainers, container.Name)\n\t\t}\n\t}\n\n\t// If all init containers are known and succeeded, just return PodCompleted.\n\tif podPhase == v1.PodSucceeded \u0026\u0026 len(unknownContainers) == 0 {\n\t\treturn v1.PodCondition{\n\t\t\tType: v1.PodInitialized,\n\t\t\tStatus: v1.ConditionTrue,\n\t\t\tReason: PodCompleted,\n\t\t}\n\t}\n\n\tunreadyMessages := []string{}\n\tif len(unknownContainers) \u003e 0 {\n\t\tunreadyMessages = append(unreadyMessages, fmt.Sprintf(\"containers with unknown status: %s\", unknownContainers))\n\t}\n\tif len(unreadyContainers) \u003e 0 {\n\t\tunreadyMessages = append(unreadyMessages, fmt.Sprintf(\"containers with incomplete status: %s\", unreadyContainers))\n\t}\n\tunreadyMessage := strings.Join(unreadyMessages, \", \")\n\tif unreadyMessage != \"\" {\n\t\treturn v1.PodCondition{\n\t\t\tType: v1.PodInitialized,\n\t\t\tStatus: v1.ConditionFalse,\n\t\t\tReason: ContainersNotInitialized,\n\t\t\tMessage: unreadyMessage,\n\t\t}\n\t}\n\n\treturn v1.PodCondition{\n\t\tType: v1.PodInitialized,\n\t\tStatus: v1.ConditionTrue,\n\t}\n}","line":{"from":146,"to":199}} {"id":100007676,"name":"GeneratePodHasNetworkCondition","signature":"func GeneratePodHasNetworkCondition(pod *v1.Pod, podStatus *kubecontainer.PodStatus) v1.PodCondition","file":"pkg/kubelet/status/generate.go","code":"func GeneratePodHasNetworkCondition(pod *v1.Pod, podStatus *kubecontainer.PodStatus) v1.PodCondition {\n\tnewSandboxNeeded, _, _ := runtimeutil.PodSandboxChanged(pod, podStatus)\n\t// if a new sandbox does not need to be created for a pod, it indicates that\n\t// a sandbox for the pod with networking configured already exists.\n\t// Otherwise, the kubelet needs to invoke the container runtime to create a\n\t// fresh sandbox and configure networking for the sandbox.\n\tif !newSandboxNeeded {\n\t\treturn v1.PodCondition{\n\t\t\tType: kubetypes.PodHasNetwork,\n\t\t\tStatus: v1.ConditionTrue,\n\t\t}\n\t}\n\treturn v1.PodCondition{\n\t\tType: kubetypes.PodHasNetwork,\n\t\tStatus: v1.ConditionFalse,\n\t}\n}","line":{"from":201,"to":217}} {"id":100007677,"name":"generateContainersReadyConditionForTerminalPhase","signature":"func generateContainersReadyConditionForTerminalPhase(podPhase v1.PodPhase) v1.PodCondition","file":"pkg/kubelet/status/generate.go","code":"func generateContainersReadyConditionForTerminalPhase(podPhase v1.PodPhase) v1.PodCondition {\n\tcondition := v1.PodCondition{\n\t\tType: v1.ContainersReady,\n\t\tStatus: v1.ConditionFalse,\n\t}\n\n\tif podPhase == v1.PodFailed {\n\t\tcondition.Reason = PodFailed\n\t} else if podPhase == v1.PodSucceeded {\n\t\tcondition.Reason = PodCompleted\n\t}\n\n\treturn condition\n}","line":{"from":219,"to":232}} {"id":100007678,"name":"generatePodReadyConditionForTerminalPhase","signature":"func generatePodReadyConditionForTerminalPhase(podPhase v1.PodPhase) v1.PodCondition","file":"pkg/kubelet/status/generate.go","code":"func generatePodReadyConditionForTerminalPhase(podPhase v1.PodPhase) v1.PodCondition {\n\tcondition := v1.PodCondition{\n\t\tType: v1.PodReady,\n\t\tStatus: v1.ConditionFalse,\n\t}\n\n\tif podPhase == v1.PodFailed {\n\t\tcondition.Reason = PodFailed\n\t} else if podPhase == v1.PodSucceeded {\n\t\tcondition.Reason = PodCompleted\n\t}\n\n\treturn condition\n}","line":{"from":234,"to":247}} {"id":100007679,"name":"NewPodResourceAllocationCheckpoint","signature":"func NewPodResourceAllocationCheckpoint() *PodResourceAllocationCheckpoint","file":"pkg/kubelet/status/state/checkpoint.go","code":"// NewPodResourceAllocationCheckpoint returns an instance of Checkpoint\nfunc NewPodResourceAllocationCheckpoint() *PodResourceAllocationCheckpoint {\n\t//lint:ignore unexported-type-in-api user-facing error message\n\treturn \u0026PodResourceAllocationCheckpoint{\n\t\tAllocationEntries: make(map[string]map[string]v1.ResourceList),\n\t\tResizeStatusEntries: make(map[string]v1.PodResizeStatus),\n\t}\n}","line":{"from":36,"to":43}} {"id":100007680,"name":"MarshalCheckpoint","signature":"func (prc *PodResourceAllocationCheckpoint) MarshalCheckpoint() ([]byte, error)","file":"pkg/kubelet/status/state/checkpoint.go","code":"// MarshalCheckpoint returns marshalled checkpoint\nfunc (prc *PodResourceAllocationCheckpoint) MarshalCheckpoint() ([]byte, error) {\n\t// make sure checksum wasn't set before so it doesn't affect output checksum\n\tprc.Checksum = 0\n\tprc.Checksum = checksum.New(prc)\n\treturn json.Marshal(*prc)\n}","line":{"from":45,"to":51}} {"id":100007681,"name":"UnmarshalCheckpoint","signature":"func (prc *PodResourceAllocationCheckpoint) UnmarshalCheckpoint(blob []byte) error","file":"pkg/kubelet/status/state/checkpoint.go","code":"// UnmarshalCheckpoint tries to unmarshal passed bytes to checkpoint\nfunc (prc *PodResourceAllocationCheckpoint) UnmarshalCheckpoint(blob []byte) error {\n\treturn json.Unmarshal(blob, prc)\n}","line":{"from":53,"to":56}} {"id":100007682,"name":"VerifyChecksum","signature":"func (prc *PodResourceAllocationCheckpoint) VerifyChecksum() error","file":"pkg/kubelet/status/state/checkpoint.go","code":"// VerifyChecksum verifies that current checksum of checkpoint is valid\nfunc (prc *PodResourceAllocationCheckpoint) VerifyChecksum() error {\n\tck := prc.Checksum\n\tprc.Checksum = 0\n\terr := ck.Verify(prc)\n\tprc.Checksum = ck\n\treturn err\n}","line":{"from":58,"to":65}} {"id":100007683,"name":"Clone","signature":"func (pr PodResourceAllocation) Clone() PodResourceAllocation","file":"pkg/kubelet/status/state/state.go","code":"// Clone returns a copy of PodResourceAllocation\nfunc (pr PodResourceAllocation) Clone() PodResourceAllocation {\n\tprCopy := make(PodResourceAllocation)\n\tfor pod := range pr {\n\t\tprCopy[pod] = make(map[string]v1.ResourceList)\n\t\tfor container, alloc := range pr[pod] {\n\t\t\tprCopy[pod][container] = alloc.DeepCopy()\n\t\t}\n\t}\n\treturn prCopy\n}","line":{"from":29,"to":39}} {"id":100007684,"name":"NewStateCheckpoint","signature":"func NewStateCheckpoint(stateDir, checkpointName string) (State, error)","file":"pkg/kubelet/status/state/state_checkpoint.go","code":"// NewStateCheckpoint creates new State for keeping track of pod resource allocations with checkpoint backend\nfunc NewStateCheckpoint(stateDir, checkpointName string) (State, error) {\n\tcheckpointManager, err := checkpointmanager.NewCheckpointManager(stateDir)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize checkpoint manager for pod allocation tracking: %v\", err)\n\t}\n\tstateCheckpoint := \u0026stateCheckpoint{\n\t\tcache: NewStateMemory(),\n\t\tcheckpointManager: checkpointManager,\n\t\tcheckpointName: checkpointName,\n\t}\n\n\tif err := stateCheckpoint.restoreState(); err != nil {\n\t\t//lint:ignore ST1005 user-facing error message\n\t\treturn nil, fmt.Errorf(\"could not restore state from checkpoint: %v, please drain this node and delete pod allocation checkpoint file %q before restarting Kubelet\", err, path.Join(stateDir, checkpointName))\n\t}\n\treturn stateCheckpoint, nil\n}","line":{"from":39,"to":56}} {"id":100007685,"name":"restoreState","signature":"func (sc *stateCheckpoint) restoreState() error","file":"pkg/kubelet/status/state/state_checkpoint.go","code":"// restores state from a checkpoint and creates it if it doesn't exist\nfunc (sc *stateCheckpoint) restoreState() error {\n\tsc.mux.Lock()\n\tdefer sc.mux.Unlock()\n\tvar err error\n\n\tcheckpoint := NewPodResourceAllocationCheckpoint()\n\n\tif err = sc.checkpointManager.GetCheckpoint(sc.checkpointName, checkpoint); err != nil {\n\t\tif err == errors.ErrCheckpointNotFound {\n\t\t\treturn sc.storeState()\n\t\t}\n\t\treturn err\n\t}\n\n\tsc.cache.SetPodResourceAllocation(checkpoint.AllocationEntries)\n\tsc.cache.SetResizeStatus(checkpoint.ResizeStatusEntries)\n\tklog.V(2).InfoS(\"State checkpoint: restored pod resource allocation state from checkpoint\")\n\treturn nil\n}","line":{"from":58,"to":77}} {"id":100007686,"name":"storeState","signature":"func (sc *stateCheckpoint) storeState() error","file":"pkg/kubelet/status/state/state_checkpoint.go","code":"// saves state to a checkpoint, caller is responsible for locking\nfunc (sc *stateCheckpoint) storeState() error {\n\tcheckpoint := NewPodResourceAllocationCheckpoint()\n\n\tpodAllocation := sc.cache.GetPodResourceAllocation()\n\tfor pod := range podAllocation {\n\t\tcheckpoint.AllocationEntries[pod] = make(map[string]v1.ResourceList)\n\t\tfor container, alloc := range podAllocation[pod] {\n\t\t\tcheckpoint.AllocationEntries[pod][container] = alloc\n\t\t}\n\t}\n\n\tpodResizeStatus := sc.cache.GetResizeStatus()\n\tcheckpoint.ResizeStatusEntries = make(map[string]v1.PodResizeStatus)\n\tfor pUID, rStatus := range podResizeStatus {\n\t\tcheckpoint.ResizeStatusEntries[pUID] = rStatus\n\t}\n\n\terr := sc.checkpointManager.CreateCheckpoint(sc.checkpointName, checkpoint)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to save pod allocation checkpoint\")\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":79,"to":103}} {"id":100007687,"name":"GetContainerResourceAllocation","signature":"func (sc *stateCheckpoint) GetContainerResourceAllocation(podUID string, containerName string) (v1.ResourceList, bool)","file":"pkg/kubelet/status/state/state_checkpoint.go","code":"// GetContainerResourceAllocation returns current resources allocated to a pod's container\nfunc (sc *stateCheckpoint) GetContainerResourceAllocation(podUID string, containerName string) (v1.ResourceList, bool) {\n\tsc.mux.RLock()\n\tdefer sc.mux.RUnlock()\n\treturn sc.cache.GetContainerResourceAllocation(podUID, containerName)\n}","line":{"from":105,"to":110}} {"id":100007688,"name":"GetPodResourceAllocation","signature":"func (sc *stateCheckpoint) GetPodResourceAllocation() PodResourceAllocation","file":"pkg/kubelet/status/state/state_checkpoint.go","code":"// GetPodResourceAllocation returns current pod resource allocation\nfunc (sc *stateCheckpoint) GetPodResourceAllocation() PodResourceAllocation {\n\tsc.mux.RLock()\n\tdefer sc.mux.RUnlock()\n\treturn sc.cache.GetPodResourceAllocation()\n}","line":{"from":112,"to":117}} {"id":100007689,"name":"GetPodResizeStatus","signature":"func (sc *stateCheckpoint) GetPodResizeStatus(podUID string) (v1.PodResizeStatus, bool)","file":"pkg/kubelet/status/state/state_checkpoint.go","code":"// GetPodResizeStatus returns the last resize decision for a pod\nfunc (sc *stateCheckpoint) GetPodResizeStatus(podUID string) (v1.PodResizeStatus, bool) {\n\tsc.mux.RLock()\n\tdefer sc.mux.RUnlock()\n\treturn sc.cache.GetPodResizeStatus(podUID)\n}","line":{"from":119,"to":124}} {"id":100007690,"name":"GetResizeStatus","signature":"func (sc *stateCheckpoint) GetResizeStatus() PodResizeStatus","file":"pkg/kubelet/status/state/state_checkpoint.go","code":"// GetResizeStatus returns the set of resize decisions made\nfunc (sc *stateCheckpoint) GetResizeStatus() PodResizeStatus {\n\tsc.mux.RLock()\n\tdefer sc.mux.RUnlock()\n\treturn sc.cache.GetResizeStatus()\n}","line":{"from":126,"to":131}} {"id":100007691,"name":"SetContainerResourceAllocation","signature":"func (sc *stateCheckpoint) SetContainerResourceAllocation(podUID string, containerName string, alloc v1.ResourceList) error","file":"pkg/kubelet/status/state/state_checkpoint.go","code":"// SetContainerResourceAllocation sets resources allocated to a pod's container\nfunc (sc *stateCheckpoint) SetContainerResourceAllocation(podUID string, containerName string, alloc v1.ResourceList) error {\n\tsc.mux.Lock()\n\tdefer sc.mux.Unlock()\n\tsc.cache.SetContainerResourceAllocation(podUID, containerName, alloc)\n\treturn sc.storeState()\n}","line":{"from":133,"to":139}} {"id":100007692,"name":"SetPodResourceAllocation","signature":"func (sc *stateCheckpoint) SetPodResourceAllocation(a PodResourceAllocation) error","file":"pkg/kubelet/status/state/state_checkpoint.go","code":"// SetPodResourceAllocation sets pod resource allocation\nfunc (sc *stateCheckpoint) SetPodResourceAllocation(a PodResourceAllocation) error {\n\tsc.mux.Lock()\n\tdefer sc.mux.Unlock()\n\tsc.cache.SetPodResourceAllocation(a)\n\treturn sc.storeState()\n}","line":{"from":141,"to":147}} {"id":100007693,"name":"SetPodResizeStatus","signature":"func (sc *stateCheckpoint) SetPodResizeStatus(podUID string, resizeStatus v1.PodResizeStatus) error","file":"pkg/kubelet/status/state/state_checkpoint.go","code":"// SetPodResizeStatus sets the last resize decision for a pod\nfunc (sc *stateCheckpoint) SetPodResizeStatus(podUID string, resizeStatus v1.PodResizeStatus) error {\n\tsc.mux.Lock()\n\tdefer sc.mux.Unlock()\n\tsc.cache.SetPodResizeStatus(podUID, resizeStatus)\n\treturn sc.storeState()\n}","line":{"from":149,"to":155}} {"id":100007694,"name":"SetResizeStatus","signature":"func (sc *stateCheckpoint) SetResizeStatus(rs PodResizeStatus) error","file":"pkg/kubelet/status/state/state_checkpoint.go","code":"// SetResizeStatus sets the resize decisions\nfunc (sc *stateCheckpoint) SetResizeStatus(rs PodResizeStatus) error {\n\tsc.mux.Lock()\n\tdefer sc.mux.Unlock()\n\tsc.cache.SetResizeStatus(rs)\n\treturn sc.storeState()\n}","line":{"from":157,"to":163}} {"id":100007695,"name":"Delete","signature":"func (sc *stateCheckpoint) Delete(podUID string, containerName string) error","file":"pkg/kubelet/status/state/state_checkpoint.go","code":"// Delete deletes allocations for specified pod\nfunc (sc *stateCheckpoint) Delete(podUID string, containerName string) error {\n\tsc.mux.Lock()\n\tdefer sc.mux.Unlock()\n\tsc.cache.Delete(podUID, containerName)\n\treturn sc.storeState()\n}","line":{"from":165,"to":171}} {"id":100007696,"name":"ClearState","signature":"func (sc *stateCheckpoint) ClearState() error","file":"pkg/kubelet/status/state/state_checkpoint.go","code":"// ClearState clears the state and saves it in a checkpoint\nfunc (sc *stateCheckpoint) ClearState() error {\n\tsc.mux.Lock()\n\tdefer sc.mux.Unlock()\n\tsc.cache.ClearState()\n\treturn sc.storeState()\n}","line":{"from":173,"to":179}} {"id":100007697,"name":"NewNoopStateCheckpoint","signature":"func NewNoopStateCheckpoint() State","file":"pkg/kubelet/status/state/state_checkpoint.go","code":"// NewNoopStateCheckpoint creates a dummy state checkpoint manager\nfunc NewNoopStateCheckpoint() State {\n\treturn \u0026noopStateCheckpoint{}\n}","line":{"from":183,"to":186}} {"id":100007698,"name":"GetContainerResourceAllocation","signature":"func (sc *noopStateCheckpoint) GetContainerResourceAllocation(_ string, _ string) (v1.ResourceList, bool)","file":"pkg/kubelet/status/state/state_checkpoint.go","code":"func (sc *noopStateCheckpoint) GetContainerResourceAllocation(_ string, _ string) (v1.ResourceList, bool) {\n\treturn nil, false\n}","line":{"from":188,"to":190}} {"id":100007699,"name":"GetPodResourceAllocation","signature":"func (sc *noopStateCheckpoint) GetPodResourceAllocation() PodResourceAllocation","file":"pkg/kubelet/status/state/state_checkpoint.go","code":"func (sc *noopStateCheckpoint) GetPodResourceAllocation() PodResourceAllocation {\n\treturn nil\n}","line":{"from":192,"to":194}} {"id":100007700,"name":"GetPodResizeStatus","signature":"func (sc *noopStateCheckpoint) GetPodResizeStatus(_ string) (v1.PodResizeStatus, bool)","file":"pkg/kubelet/status/state/state_checkpoint.go","code":"func (sc *noopStateCheckpoint) GetPodResizeStatus(_ string) (v1.PodResizeStatus, bool) {\n\treturn \"\", false\n}","line":{"from":196,"to":198}} {"id":100007701,"name":"GetResizeStatus","signature":"func (sc *noopStateCheckpoint) GetResizeStatus() PodResizeStatus","file":"pkg/kubelet/status/state/state_checkpoint.go","code":"func (sc *noopStateCheckpoint) GetResizeStatus() PodResizeStatus {\n\treturn nil\n}","line":{"from":200,"to":202}} {"id":100007702,"name":"SetContainerResourceAllocation","signature":"func (sc *noopStateCheckpoint) SetContainerResourceAllocation(_ string, _ string, _ v1.ResourceList) error","file":"pkg/kubelet/status/state/state_checkpoint.go","code":"func (sc *noopStateCheckpoint) SetContainerResourceAllocation(_ string, _ string, _ v1.ResourceList) error {\n\treturn nil\n}","line":{"from":204,"to":206}} {"id":100007703,"name":"SetPodResourceAllocation","signature":"func (sc *noopStateCheckpoint) SetPodResourceAllocation(_ PodResourceAllocation) error","file":"pkg/kubelet/status/state/state_checkpoint.go","code":"func (sc *noopStateCheckpoint) SetPodResourceAllocation(_ PodResourceAllocation) error {\n\treturn nil\n}","line":{"from":208,"to":210}} {"id":100007704,"name":"SetPodResizeStatus","signature":"func (sc *noopStateCheckpoint) SetPodResizeStatus(_ string, _ v1.PodResizeStatus) error","file":"pkg/kubelet/status/state/state_checkpoint.go","code":"func (sc *noopStateCheckpoint) SetPodResizeStatus(_ string, _ v1.PodResizeStatus) error {\n\treturn nil\n}","line":{"from":212,"to":214}} {"id":100007705,"name":"SetResizeStatus","signature":"func (sc *noopStateCheckpoint) SetResizeStatus(_ PodResizeStatus) error","file":"pkg/kubelet/status/state/state_checkpoint.go","code":"func (sc *noopStateCheckpoint) SetResizeStatus(_ PodResizeStatus) error {\n\treturn nil\n}","line":{"from":216,"to":218}} {"id":100007706,"name":"Delete","signature":"func (sc *noopStateCheckpoint) Delete(_ string, _ string) error","file":"pkg/kubelet/status/state/state_checkpoint.go","code":"func (sc *noopStateCheckpoint) Delete(_ string, _ string) error {\n\treturn nil\n}","line":{"from":220,"to":222}} {"id":100007707,"name":"ClearState","signature":"func (sc *noopStateCheckpoint) ClearState() error","file":"pkg/kubelet/status/state/state_checkpoint.go","code":"func (sc *noopStateCheckpoint) ClearState() error {\n\treturn nil\n}","line":{"from":224,"to":226}} {"id":100007708,"name":"NewStateMemory","signature":"func NewStateMemory() State","file":"pkg/kubelet/status/state/state_mem.go","code":"// NewStateMemory creates new State to track resources allocated to pods\nfunc NewStateMemory() State {\n\tklog.V(2).InfoS(\"Initialized new in-memory state store for pod resource allocation tracking\")\n\treturn \u0026stateMemory{\n\t\tpodAllocation: PodResourceAllocation{},\n\t\tpodResizeStatus: PodResizeStatus{},\n\t}\n}","line":{"from":34,"to":41}} {"id":100007709,"name":"GetContainerResourceAllocation","signature":"func (s *stateMemory) GetContainerResourceAllocation(podUID string, containerName string) (v1.ResourceList, bool)","file":"pkg/kubelet/status/state/state_mem.go","code":"func (s *stateMemory) GetContainerResourceAllocation(podUID string, containerName string) (v1.ResourceList, bool) {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\talloc, ok := s.podAllocation[podUID][containerName]\n\treturn alloc.DeepCopy(), ok\n}","line":{"from":43,"to":49}} {"id":100007710,"name":"GetPodResourceAllocation","signature":"func (s *stateMemory) GetPodResourceAllocation() PodResourceAllocation","file":"pkg/kubelet/status/state/state_mem.go","code":"func (s *stateMemory) GetPodResourceAllocation() PodResourceAllocation {\n\ts.RLock()\n\tdefer s.RUnlock()\n\treturn s.podAllocation.Clone()\n}","line":{"from":51,"to":55}} {"id":100007711,"name":"GetPodResizeStatus","signature":"func (s *stateMemory) GetPodResizeStatus(podUID string) (v1.PodResizeStatus, bool)","file":"pkg/kubelet/status/state/state_mem.go","code":"func (s *stateMemory) GetPodResizeStatus(podUID string) (v1.PodResizeStatus, bool) {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tresizeStatus, ok := s.podResizeStatus[podUID]\n\treturn resizeStatus, ok\n}","line":{"from":57,"to":63}} {"id":100007712,"name":"GetResizeStatus","signature":"func (s *stateMemory) GetResizeStatus() PodResizeStatus","file":"pkg/kubelet/status/state/state_mem.go","code":"func (s *stateMemory) GetResizeStatus() PodResizeStatus {\n\ts.RLock()\n\tdefer s.RUnlock()\n\tprs := make(map[string]v1.PodResizeStatus)\n\tfor k, v := range s.podResizeStatus {\n\t\tprs[k] = v\n\t}\n\treturn prs\n}","line":{"from":65,"to":73}} {"id":100007713,"name":"SetContainerResourceAllocation","signature":"func (s *stateMemory) SetContainerResourceAllocation(podUID string, containerName string, alloc v1.ResourceList) error","file":"pkg/kubelet/status/state/state_mem.go","code":"func (s *stateMemory) SetContainerResourceAllocation(podUID string, containerName string, alloc v1.ResourceList) error {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tif _, ok := s.podAllocation[podUID]; !ok {\n\t\ts.podAllocation[podUID] = make(map[string]v1.ResourceList)\n\t}\n\n\ts.podAllocation[podUID][containerName] = alloc\n\tklog.V(3).InfoS(\"Updated container resource allocation\", \"podUID\", podUID, \"containerName\", containerName, \"alloc\", alloc)\n\treturn nil\n}","line":{"from":75,"to":86}} {"id":100007714,"name":"SetPodResourceAllocation","signature":"func (s *stateMemory) SetPodResourceAllocation(a PodResourceAllocation) error","file":"pkg/kubelet/status/state/state_mem.go","code":"func (s *stateMemory) SetPodResourceAllocation(a PodResourceAllocation) error {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\ts.podAllocation = a.Clone()\n\tklog.V(3).InfoS(\"Updated pod resource allocation\", \"allocation\", a)\n\treturn nil\n}","line":{"from":88,"to":95}} {"id":100007715,"name":"SetPodResizeStatus","signature":"func (s *stateMemory) SetPodResizeStatus(podUID string, resizeStatus v1.PodResizeStatus) error","file":"pkg/kubelet/status/state/state_mem.go","code":"func (s *stateMemory) SetPodResizeStatus(podUID string, resizeStatus v1.PodResizeStatus) error {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tif resizeStatus != \"\" {\n\t\ts.podResizeStatus[podUID] = resizeStatus\n\t} else {\n\t\tdelete(s.podResizeStatus, podUID)\n\t}\n\tklog.V(3).InfoS(\"Updated pod resize state\", \"podUID\", podUID, \"resizeStatus\", resizeStatus)\n\treturn nil\n}","line":{"from":97,"to":108}} {"id":100007716,"name":"SetResizeStatus","signature":"func (s *stateMemory) SetResizeStatus(rs PodResizeStatus) error","file":"pkg/kubelet/status/state/state_mem.go","code":"func (s *stateMemory) SetResizeStatus(rs PodResizeStatus) error {\n\ts.Lock()\n\tdefer s.Unlock()\n\tprs := make(map[string]v1.PodResizeStatus)\n\tfor k, v := range rs {\n\t\tprs[k] = v\n\t}\n\ts.podResizeStatus = prs\n\tklog.V(3).InfoS(\"Updated pod resize state\", \"resizes\", rs)\n\treturn nil\n}","line":{"from":110,"to":120}} {"id":100007717,"name":"deleteContainer","signature":"func (s *stateMemory) deleteContainer(podUID string, containerName string)","file":"pkg/kubelet/status/state/state_mem.go","code":"func (s *stateMemory) deleteContainer(podUID string, containerName string) {\n\tdelete(s.podAllocation[podUID], containerName)\n\tif len(s.podAllocation[podUID]) == 0 {\n\t\tdelete(s.podAllocation, podUID)\n\t\tdelete(s.podResizeStatus, podUID)\n\t}\n\tklog.V(3).InfoS(\"Deleted pod resource allocation\", \"podUID\", podUID, \"containerName\", containerName)\n}","line":{"from":122,"to":129}} {"id":100007718,"name":"Delete","signature":"func (s *stateMemory) Delete(podUID string, containerName string) error","file":"pkg/kubelet/status/state/state_mem.go","code":"func (s *stateMemory) Delete(podUID string, containerName string) error {\n\ts.Lock()\n\tdefer s.Unlock()\n\tif len(containerName) == 0 {\n\t\tdelete(s.podAllocation, podUID)\n\t\tdelete(s.podResizeStatus, podUID)\n\t\tklog.V(3).InfoS(\"Deleted pod resource allocation and resize state\", \"podUID\", podUID)\n\t\treturn nil\n\t}\n\ts.deleteContainer(podUID, containerName)\n\treturn nil\n}","line":{"from":131,"to":142}} {"id":100007719,"name":"ClearState","signature":"func (s *stateMemory) ClearState() error","file":"pkg/kubelet/status/state/state_mem.go","code":"func (s *stateMemory) ClearState() error {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\ts.podAllocation = make(PodResourceAllocation)\n\ts.podResizeStatus = make(PodResizeStatus)\n\tklog.V(3).InfoS(\"Cleared state\")\n\treturn nil\n}","line":{"from":144,"to":152}} {"id":100007720,"name":"NewManager","signature":"func NewManager(kubeClient clientset.Interface, podManager kubepod.Manager, podDeletionSafety PodDeletionSafetyProvider, podStartupLatencyHelper PodStartupLatencyStateHelper, stateFileDirectory string) Manager","file":"pkg/kubelet/status/status_manager.go","code":"// NewManager returns a functional Manager.\nfunc NewManager(kubeClient clientset.Interface, podManager kubepod.Manager, podDeletionSafety PodDeletionSafetyProvider, podStartupLatencyHelper PodStartupLatencyStateHelper, stateFileDirectory string) Manager {\n\treturn \u0026manager{\n\t\tkubeClient: kubeClient,\n\t\tpodManager: podManager,\n\t\tpodStatuses: make(map[types.UID]versionedPodStatus),\n\t\tpodStatusChannel: make(chan struct{}, 1),\n\t\tapiStatusVersions: make(map[kubetypes.MirrorPodUID]uint64),\n\t\tpodDeletionSafety: podDeletionSafety,\n\t\tpodStartupLatencyHelper: podStartupLatencyHelper,\n\t\tstateFileDirectory: stateFileDirectory,\n\t}\n}","line":{"from":151,"to":163}} {"id":100007721,"name":"isPodStatusByKubeletEqual","signature":"func isPodStatusByKubeletEqual(oldStatus, status *v1.PodStatus) bool","file":"pkg/kubelet/status/status_manager.go","code":"// isPodStatusByKubeletEqual returns true if the given pod statuses are equal when non-kubelet-owned\n// pod conditions are excluded.\n// This method normalizes the status before comparing so as to make sure that meaningless\n// changes will be ignored.\nfunc isPodStatusByKubeletEqual(oldStatus, status *v1.PodStatus) bool {\n\toldCopy := oldStatus.DeepCopy()\n\tfor _, c := range status.Conditions {\n\t\t// both owned and shared conditions are used for kubelet status equality\n\t\tif kubetypes.PodConditionByKubelet(c.Type) || kubetypes.PodConditionSharedByKubelet(c.Type) {\n\t\t\t_, oc := podutil.GetPodCondition(oldCopy, c.Type)\n\t\t\tif oc == nil || oc.Status != c.Status || oc.Message != c.Message || oc.Reason != c.Reason {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\toldCopy.Conditions = status.Conditions\n\treturn apiequality.Semantic.DeepEqual(oldCopy, status)\n}","line":{"from":165,"to":182}} {"id":100007722,"name":"Start","signature":"func (m *manager) Start()","file":"pkg/kubelet/status/status_manager.go","code":"func (m *manager) Start() {\n\t// Initialize m.state to no-op state checkpoint manager\n\tm.state = state.NewNoopStateCheckpoint()\n\n\t// Create pod allocation checkpoint manager even if client is nil so as to allow local get/set of AllocatedResources \u0026 Resize\n\tif utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) {\n\t\tstateImpl, err := state.NewStateCheckpoint(m.stateFileDirectory, podStatusManagerStateFile)\n\t\tif err != nil {\n\t\t\t// This is a crictical, non-recoverable failure.\n\t\t\tklog.ErrorS(err, \"Could not initialize pod allocation checkpoint manager, please drain node and remove policy state file\")\n\t\t\tpanic(err)\n\t\t}\n\t\tm.state = stateImpl\n\t}\n\n\t// Don't start the status manager if we don't have a client. This will happen\n\t// on the master, where the kubelet is responsible for bootstrapping the pods\n\t// of the master components.\n\tif m.kubeClient == nil {\n\t\tklog.InfoS(\"Kubernetes client is nil, not starting status manager\")\n\t\treturn\n\t}\n\n\tklog.InfoS(\"Starting to sync pod status with apiserver\")\n\n\t//nolint:staticcheck // SA1015 Ticker can leak since this is only called once and doesn't handle termination.\n\tsyncTicker := time.NewTicker(syncPeriod).C\n\n\t// syncPod and syncBatch share the same go routine to avoid sync races.\n\tgo wait.Forever(func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase \u003c-m.podStatusChannel:\n\t\t\t\tklog.V(4).InfoS(\"Syncing updated statuses\")\n\t\t\t\tm.syncBatch(false)\n\t\t\tcase \u003c-syncTicker:\n\t\t\t\tklog.V(4).InfoS(\"Syncing all statuses\")\n\t\t\t\tm.syncBatch(true)\n\t\t\t}\n\t\t}\n\t}, 0)\n}","line":{"from":184,"to":225}} {"id":100007723,"name":"GetContainerResourceAllocation","signature":"func (m *manager) GetContainerResourceAllocation(podUID string, containerName string) (v1.ResourceList, bool)","file":"pkg/kubelet/status/status_manager.go","code":"// GetContainerResourceAllocation returns the last checkpointed AllocatedResources values\n// If checkpoint manager has not been initialized, it returns nil, false\nfunc (m *manager) GetContainerResourceAllocation(podUID string, containerName string) (v1.ResourceList, bool) {\n\tm.podStatusesLock.RLock()\n\tdefer m.podStatusesLock.RUnlock()\n\treturn m.state.GetContainerResourceAllocation(podUID, containerName)\n}","line":{"from":227,"to":233}} {"id":100007724,"name":"GetPodResizeStatus","signature":"func (m *manager) GetPodResizeStatus(podUID string) (v1.PodResizeStatus, bool)","file":"pkg/kubelet/status/status_manager.go","code":"// GetPodResizeStatus returns the last checkpointed ResizeStaus value\n// If checkpoint manager has not been initialized, it returns nil, false\nfunc (m *manager) GetPodResizeStatus(podUID string) (v1.PodResizeStatus, bool) {\n\tm.podStatusesLock.RLock()\n\tdefer m.podStatusesLock.RUnlock()\n\treturn m.state.GetPodResizeStatus(podUID)\n}","line":{"from":235,"to":241}} {"id":100007725,"name":"SetPodAllocation","signature":"func (m *manager) SetPodAllocation(pod *v1.Pod) error","file":"pkg/kubelet/status/status_manager.go","code":"// SetPodAllocation checkpoints the resources allocated to a pod's containers\nfunc (m *manager) SetPodAllocation(pod *v1.Pod) error {\n\tm.podStatusesLock.RLock()\n\tdefer m.podStatusesLock.RUnlock()\n\tfor _, container := range pod.Spec.Containers {\n\t\tvar alloc v1.ResourceList\n\t\tif container.Resources.Requests != nil {\n\t\t\talloc = container.Resources.Requests.DeepCopy()\n\t\t}\n\t\tif err := m.state.SetContainerResourceAllocation(string(pod.UID), container.Name, alloc); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":243,"to":257}} {"id":100007726,"name":"SetPodResizeStatus","signature":"func (m *manager) SetPodResizeStatus(podUID types.UID, resizeStatus v1.PodResizeStatus) error","file":"pkg/kubelet/status/status_manager.go","code":"// SetPodResizeStatus checkpoints the last resizing decision for the pod.\nfunc (m *manager) SetPodResizeStatus(podUID types.UID, resizeStatus v1.PodResizeStatus) error {\n\tm.podStatusesLock.RLock()\n\tdefer m.podStatusesLock.RUnlock()\n\treturn m.state.SetPodResizeStatus(string(podUID), resizeStatus)\n}","line":{"from":259,"to":264}} {"id":100007727,"name":"GetPodStatus","signature":"func (m *manager) GetPodStatus(uid types.UID) (v1.PodStatus, bool)","file":"pkg/kubelet/status/status_manager.go","code":"func (m *manager) GetPodStatus(uid types.UID) (v1.PodStatus, bool) {\n\tm.podStatusesLock.RLock()\n\tdefer m.podStatusesLock.RUnlock()\n\tstatus, ok := m.podStatuses[types.UID(m.podManager.TranslatePodUID(uid))]\n\treturn status.status, ok\n}","line":{"from":266,"to":271}} {"id":100007728,"name":"SetPodStatus","signature":"func (m *manager) SetPodStatus(pod *v1.Pod, status v1.PodStatus)","file":"pkg/kubelet/status/status_manager.go","code":"func (m *manager) SetPodStatus(pod *v1.Pod, status v1.PodStatus) {\n\tm.podStatusesLock.Lock()\n\tdefer m.podStatusesLock.Unlock()\n\n\t// Make sure we're caching a deep copy.\n\tstatus = *status.DeepCopy()\n\n\t// Force a status update if deletion timestamp is set. This is necessary\n\t// because if the pod is in the non-running state, the pod worker still\n\t// needs to be able to trigger an update and/or deletion.\n\tm.updateStatusInternal(pod, status, pod.DeletionTimestamp != nil, false)\n}","line":{"from":273,"to":284}} {"id":100007729,"name":"SetContainerReadiness","signature":"func (m *manager) SetContainerReadiness(podUID types.UID, containerID kubecontainer.ContainerID, ready bool)","file":"pkg/kubelet/status/status_manager.go","code":"func (m *manager) SetContainerReadiness(podUID types.UID, containerID kubecontainer.ContainerID, ready bool) {\n\tm.podStatusesLock.Lock()\n\tdefer m.podStatusesLock.Unlock()\n\n\tpod, ok := m.podManager.GetPodByUID(podUID)\n\tif !ok {\n\t\tklog.V(4).InfoS(\"Pod has been deleted, no need to update readiness\", \"podUID\", string(podUID))\n\t\treturn\n\t}\n\n\toldStatus, found := m.podStatuses[pod.UID]\n\tif !found {\n\t\tklog.InfoS(\"Container readiness changed before pod has synced\",\n\t\t\t\"pod\", klog.KObj(pod),\n\t\t\t\"containerID\", containerID.String())\n\t\treturn\n\t}\n\n\t// Find the container to update.\n\tcontainerStatus, _, ok := findContainerStatus(\u0026oldStatus.status, containerID.String())\n\tif !ok {\n\t\tklog.InfoS(\"Container readiness changed for unknown container\",\n\t\t\t\"pod\", klog.KObj(pod),\n\t\t\t\"containerID\", containerID.String())\n\t\treturn\n\t}\n\n\tif containerStatus.Ready == ready {\n\t\tklog.V(4).InfoS(\"Container readiness unchanged\",\n\t\t\t\"ready\", ready,\n\t\t\t\"pod\", klog.KObj(pod),\n\t\t\t\"containerID\", containerID.String())\n\t\treturn\n\t}\n\n\t// Make sure we're not updating the cached version.\n\tstatus := *oldStatus.status.DeepCopy()\n\tcontainerStatus, _, _ = findContainerStatus(\u0026status, containerID.String())\n\tcontainerStatus.Ready = ready\n\n\t// updateConditionFunc updates the corresponding type of condition\n\tupdateConditionFunc := func(conditionType v1.PodConditionType, condition v1.PodCondition) {\n\t\tconditionIndex := -1\n\t\tfor i, condition := range status.Conditions {\n\t\t\tif condition.Type == conditionType {\n\t\t\t\tconditionIndex = i\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif conditionIndex != -1 {\n\t\t\tstatus.Conditions[conditionIndex] = condition\n\t\t} else {\n\t\t\tklog.InfoS(\"PodStatus missing condition type\", \"conditionType\", conditionType, \"status\", status)\n\t\t\tstatus.Conditions = append(status.Conditions, condition)\n\t\t}\n\t}\n\tupdateConditionFunc(v1.PodReady, GeneratePodReadyCondition(\u0026pod.Spec, status.Conditions, status.ContainerStatuses, status.Phase))\n\tupdateConditionFunc(v1.ContainersReady, GenerateContainersReadyCondition(\u0026pod.Spec, status.ContainerStatuses, status.Phase))\n\tm.updateStatusInternal(pod, status, false, false)\n}","line":{"from":286,"to":345}} {"id":100007730,"name":"SetContainerStartup","signature":"func (m *manager) SetContainerStartup(podUID types.UID, containerID kubecontainer.ContainerID, started bool)","file":"pkg/kubelet/status/status_manager.go","code":"func (m *manager) SetContainerStartup(podUID types.UID, containerID kubecontainer.ContainerID, started bool) {\n\tm.podStatusesLock.Lock()\n\tdefer m.podStatusesLock.Unlock()\n\n\tpod, ok := m.podManager.GetPodByUID(podUID)\n\tif !ok {\n\t\tklog.V(4).InfoS(\"Pod has been deleted, no need to update startup\", \"podUID\", string(podUID))\n\t\treturn\n\t}\n\n\toldStatus, found := m.podStatuses[pod.UID]\n\tif !found {\n\t\tklog.InfoS(\"Container startup changed before pod has synced\",\n\t\t\t\"pod\", klog.KObj(pod),\n\t\t\t\"containerID\", containerID.String())\n\t\treturn\n\t}\n\n\t// Find the container to update.\n\tcontainerStatus, _, ok := findContainerStatus(\u0026oldStatus.status, containerID.String())\n\tif !ok {\n\t\tklog.InfoS(\"Container startup changed for unknown container\",\n\t\t\t\"pod\", klog.KObj(pod),\n\t\t\t\"containerID\", containerID.String())\n\t\treturn\n\t}\n\n\tif containerStatus.Started != nil \u0026\u0026 *containerStatus.Started == started {\n\t\tklog.V(4).InfoS(\"Container startup unchanged\",\n\t\t\t\"pod\", klog.KObj(pod),\n\t\t\t\"containerID\", containerID.String())\n\t\treturn\n\t}\n\n\t// Make sure we're not updating the cached version.\n\tstatus := *oldStatus.status.DeepCopy()\n\tcontainerStatus, _, _ = findContainerStatus(\u0026status, containerID.String())\n\tcontainerStatus.Started = \u0026started\n\n\tm.updateStatusInternal(pod, status, false, false)\n}","line":{"from":347,"to":387}} {"id":100007731,"name":"findContainerStatus","signature":"func findContainerStatus(status *v1.PodStatus, containerID string) (containerStatus *v1.ContainerStatus, init bool, ok bool)","file":"pkg/kubelet/status/status_manager.go","code":"func findContainerStatus(status *v1.PodStatus, containerID string) (containerStatus *v1.ContainerStatus, init bool, ok bool) {\n\t// Find the container to update.\n\tfor i, c := range status.ContainerStatuses {\n\t\tif c.ContainerID == containerID {\n\t\t\treturn \u0026status.ContainerStatuses[i], false, true\n\t\t}\n\t}\n\n\tfor i, c := range status.InitContainerStatuses {\n\t\tif c.ContainerID == containerID {\n\t\t\treturn \u0026status.InitContainerStatuses[i], true, true\n\t\t}\n\t}\n\n\treturn nil, false, false\n\n}","line":{"from":389,"to":405}} {"id":100007732,"name":"TerminatePod","signature":"func (m *manager) TerminatePod(pod *v1.Pod)","file":"pkg/kubelet/status/status_manager.go","code":"// TerminatePod ensures that the status of containers is properly defaulted at the end of the pod\n// lifecycle. As the Kubelet must reconcile with the container runtime to observe container status\n// there is always the possibility we are unable to retrieve one or more container statuses due to\n// garbage collection, admin action, or loss of temporary data on a restart. This method ensures\n// that any absent container status is treated as a failure so that we do not incorrectly describe\n// the pod as successful. If we have not yet initialized the pod in the presence of init containers,\n// the init container failure status is sufficient to describe the pod as failing, and we do not need\n// to override waiting containers (unless there is evidence the pod previously started those containers).\n// It also makes sure that pods are transitioned to a terminal phase (Failed or Succeeded) before\n// their deletion.\nfunc (m *manager) TerminatePod(pod *v1.Pod) {\n\tm.podStatusesLock.Lock()\n\tdefer m.podStatusesLock.Unlock()\n\n\t// ensure that all containers have a terminated state - because we do not know whether the container\n\t// was successful, always report an error\n\toldStatus := \u0026pod.Status\n\tcachedStatus, isCached := m.podStatuses[pod.UID]\n\tif isCached {\n\t\toldStatus = \u0026cachedStatus.status\n\t}\n\tstatus := *oldStatus.DeepCopy()\n\n\t// once a pod has initialized, any missing status is treated as a failure\n\tif hasPodInitialized(pod) {\n\t\tfor i := range status.ContainerStatuses {\n\t\t\tif status.ContainerStatuses[i].State.Terminated != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstatus.ContainerStatuses[i].State = v1.ContainerState{\n\t\t\t\tTerminated: \u0026v1.ContainerStateTerminated{\n\t\t\t\t\tReason: \"ContainerStatusUnknown\",\n\t\t\t\t\tMessage: \"The container could not be located when the pod was terminated\",\n\t\t\t\t\tExitCode: 137,\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t}\n\n\t// all but the final suffix of init containers which have no evidence of a container start are\n\t// marked as failed containers\n\tfor i := range initializedContainers(status.InitContainerStatuses) {\n\t\tif status.InitContainerStatuses[i].State.Terminated != nil {\n\t\t\tcontinue\n\t\t}\n\t\tstatus.InitContainerStatuses[i].State = v1.ContainerState{\n\t\t\tTerminated: \u0026v1.ContainerStateTerminated{\n\t\t\t\tReason: \"ContainerStatusUnknown\",\n\t\t\t\tMessage: \"The container could not be located when the pod was terminated\",\n\t\t\t\tExitCode: 137,\n\t\t\t},\n\t\t}\n\t}\n\n\t// Make sure all pods are transitioned to a terminal phase.\n\t// TODO(#116484): Also assign terminal phase to static an pods.\n\tif !kubetypes.IsStaticPod(pod) {\n\t\tswitch status.Phase {\n\t\tcase v1.PodSucceeded, v1.PodFailed:\n\t\t\t// do nothing, already terminal\n\t\tcase v1.PodPending, v1.PodRunning:\n\t\t\tif status.Phase == v1.PodRunning \u0026\u0026 isCached {\n\t\t\t\tklog.InfoS(\"Terminal running pod should have already been marked as failed, programmer error\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\t\t\t}\n\t\t\tklog.V(3).InfoS(\"Marking terminal pod as failed\", \"oldPhase\", status.Phase, \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\t\t\tstatus.Phase = v1.PodFailed\n\t\tdefault:\n\t\t\tklog.ErrorS(fmt.Errorf(\"unknown phase: %v\", status.Phase), \"Unknown phase, programmer error\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\t\t\tstatus.Phase = v1.PodFailed\n\t\t}\n\t}\n\n\tklog.V(5).InfoS(\"TerminatePod calling updateStatusInternal\", \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\tm.updateStatusInternal(pod, status, true, true)\n}","line":{"from":407,"to":481}} {"id":100007733,"name":"hasPodInitialized","signature":"func hasPodInitialized(pod *v1.Pod) bool","file":"pkg/kubelet/status/status_manager.go","code":"// hasPodInitialized returns true if the pod has no evidence of ever starting a regular container, which\n// implies those containers should not be transitioned to terminated status.\nfunc hasPodInitialized(pod *v1.Pod) bool {\n\t// a pod without init containers is always initialized\n\tif len(pod.Spec.InitContainers) == 0 {\n\t\treturn true\n\t}\n\t// if any container has ever moved out of waiting state, the pod has initialized\n\tfor _, status := range pod.Status.ContainerStatuses {\n\t\tif status.LastTerminationState.Terminated != nil || status.State.Waiting == nil {\n\t\t\treturn true\n\t\t}\n\t}\n\t// if the last init container has ever completed with a zero exit code, the pod is initialized\n\tif l := len(pod.Status.InitContainerStatuses); l \u003e 0 {\n\t\tcontainer := pod.Status.InitContainerStatuses[l-1]\n\t\tif state := container.LastTerminationState; state.Terminated != nil \u0026\u0026 state.Terminated.ExitCode == 0 {\n\t\t\treturn true\n\t\t}\n\t\tif state := container.State; state.Terminated != nil \u0026\u0026 state.Terminated.ExitCode == 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\t// otherwise the pod has no record of being initialized\n\treturn false\n}","line":{"from":483,"to":508}} {"id":100007734,"name":"initializedContainers","signature":"func initializedContainers(containers []v1.ContainerStatus) []v1.ContainerStatus","file":"pkg/kubelet/status/status_manager.go","code":"// initializedContainers returns all status except for suffix of containers that are in Waiting\n// state, which is the set of containers that have attempted to start at least once. If all containers\n// are Watiing, the first container is always returned.\nfunc initializedContainers(containers []v1.ContainerStatus) []v1.ContainerStatus {\n\tfor i := len(containers) - 1; i \u003e= 0; i-- {\n\t\tif containers[i].State.Waiting == nil || containers[i].LastTerminationState.Terminated != nil {\n\t\t\treturn containers[0 : i+1]\n\t\t}\n\t}\n\t// always return at least one container\n\tif len(containers) \u003e 0 {\n\t\treturn containers[0:1]\n\t}\n\treturn nil\n}","line":{"from":510,"to":524}} {"id":100007735,"name":"checkContainerStateTransition","signature":"func checkContainerStateTransition(oldStatuses, newStatuses []v1.ContainerStatus, restartPolicy v1.RestartPolicy) error","file":"pkg/kubelet/status/status_manager.go","code":"// checkContainerStateTransition ensures that no container is trying to transition\n// from a terminated to non-terminated state, which is illegal and indicates a\n// logical error in the kubelet.\nfunc checkContainerStateTransition(oldStatuses, newStatuses []v1.ContainerStatus, restartPolicy v1.RestartPolicy) error {\n\t// If we should always restart, containers are allowed to leave the terminated state\n\tif restartPolicy == v1.RestartPolicyAlways {\n\t\treturn nil\n\t}\n\tfor _, oldStatus := range oldStatuses {\n\t\t// Skip any container that wasn't terminated\n\t\tif oldStatus.State.Terminated == nil {\n\t\t\tcontinue\n\t\t}\n\t\t// Skip any container that failed but is allowed to restart\n\t\tif oldStatus.State.Terminated.ExitCode != 0 \u0026\u0026 restartPolicy == v1.RestartPolicyOnFailure {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, newStatus := range newStatuses {\n\t\t\tif oldStatus.Name == newStatus.Name \u0026\u0026 newStatus.State.Terminated == nil {\n\t\t\t\treturn fmt.Errorf(\"terminated container %v attempted illegal transition to non-terminated state\", newStatus.Name)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":526,"to":550}} {"id":100007736,"name":"updateStatusInternal","signature":"func (m *manager) updateStatusInternal(pod *v1.Pod, status v1.PodStatus, forceUpdate, podIsFinished bool)","file":"pkg/kubelet/status/status_manager.go","code":"// updateStatusInternal updates the internal status cache, and queues an update to the api server if\n// necessary.\n// This method IS NOT THREAD SAFE and must be called from a locked function.\nfunc (m *manager) updateStatusInternal(pod *v1.Pod, status v1.PodStatus, forceUpdate, podIsFinished bool) {\n\tvar oldStatus v1.PodStatus\n\tcachedStatus, isCached := m.podStatuses[pod.UID]\n\tif isCached {\n\t\toldStatus = cachedStatus.status\n\t\t// TODO(#116484): Also assign terminal phase to static pods.\n\t\tif !kubetypes.IsStaticPod(pod) {\n\t\t\tif cachedStatus.podIsFinished \u0026\u0026 !podIsFinished {\n\t\t\t\tklog.InfoS(\"Got unexpected podIsFinished=false, while podIsFinished=true in status cache, programmer error.\", \"pod\", klog.KObj(pod))\n\t\t\t\tpodIsFinished = true\n\t\t\t}\n\t\t}\n\t} else if mirrorPod, ok := m.podManager.GetMirrorPodByPod(pod); ok {\n\t\toldStatus = mirrorPod.Status\n\t} else {\n\t\toldStatus = pod.Status\n\t}\n\n\t// Check for illegal state transition in containers\n\tif err := checkContainerStateTransition(oldStatus.ContainerStatuses, status.ContainerStatuses, pod.Spec.RestartPolicy); err != nil {\n\t\tklog.ErrorS(err, \"Status update on pod aborted\", \"pod\", klog.KObj(pod))\n\t\treturn\n\t}\n\tif err := checkContainerStateTransition(oldStatus.InitContainerStatuses, status.InitContainerStatuses, pod.Spec.RestartPolicy); err != nil {\n\t\tklog.ErrorS(err, \"Status update on pod aborted\", \"pod\", klog.KObj(pod))\n\t\treturn\n\t}\n\n\t// Set ContainersReadyCondition.LastTransitionTime.\n\tupdateLastTransitionTime(\u0026status, \u0026oldStatus, v1.ContainersReady)\n\n\t// Set ReadyCondition.LastTransitionTime.\n\tupdateLastTransitionTime(\u0026status, \u0026oldStatus, v1.PodReady)\n\n\t// Set InitializedCondition.LastTransitionTime.\n\tupdateLastTransitionTime(\u0026status, \u0026oldStatus, v1.PodInitialized)\n\n\t// Set PodHasNetwork.LastTransitionTime.\n\tupdateLastTransitionTime(\u0026status, \u0026oldStatus, kubetypes.PodHasNetwork)\n\n\t// Set PodScheduledCondition.LastTransitionTime.\n\tupdateLastTransitionTime(\u0026status, \u0026oldStatus, v1.PodScheduled)\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.PodDisruptionConditions) {\n\t\t// Set DisruptionTarget.LastTransitionTime.\n\t\tupdateLastTransitionTime(\u0026status, \u0026oldStatus, v1.DisruptionTarget)\n\t}\n\n\t// ensure that the start time does not change across updates.\n\tif oldStatus.StartTime != nil \u0026\u0026 !oldStatus.StartTime.IsZero() {\n\t\tstatus.StartTime = oldStatus.StartTime\n\t} else if status.StartTime.IsZero() {\n\t\t// if the status has no start time, we need to set an initial time\n\t\tnow := metav1.Now()\n\t\tstatus.StartTime = \u0026now\n\t}\n\n\tnormalizeStatus(pod, \u0026status)\n\n\t// Perform some more extensive logging of container termination state to assist in\n\t// debugging production races (generally not needed).\n\tif klogV := klog.V(5); klogV.Enabled() {\n\t\tvar containers []string\n\t\tfor _, s := range append(append([]v1.ContainerStatus(nil), status.InitContainerStatuses...), status.ContainerStatuses...) {\n\t\t\tvar current, previous string\n\t\t\tswitch {\n\t\t\tcase s.State.Running != nil:\n\t\t\t\tcurrent = \"running\"\n\t\t\tcase s.State.Waiting != nil:\n\t\t\t\tcurrent = \"waiting\"\n\t\t\tcase s.State.Terminated != nil:\n\t\t\t\tcurrent = fmt.Sprintf(\"terminated=%d\", s.State.Terminated.ExitCode)\n\t\t\tdefault:\n\t\t\t\tcurrent = \"unknown\"\n\t\t\t}\n\t\t\tswitch {\n\t\t\tcase s.LastTerminationState.Running != nil:\n\t\t\t\tprevious = \"running\"\n\t\t\tcase s.LastTerminationState.Waiting != nil:\n\t\t\t\tprevious = \"waiting\"\n\t\t\tcase s.LastTerminationState.Terminated != nil:\n\t\t\t\tprevious = fmt.Sprintf(\"terminated=%d\", s.LastTerminationState.Terminated.ExitCode)\n\t\t\tdefault:\n\t\t\t\tprevious = \"\u003cnone\u003e\"\n\t\t\t}\n\t\t\tcontainers = append(containers, fmt.Sprintf(\"(%s state=%s previous=%s)\", s.Name, current, previous))\n\t\t}\n\t\tsort.Strings(containers)\n\t\tklogV.InfoS(\"updateStatusInternal\", \"version\", cachedStatus.version+1, \"podIsFinished\", podIsFinished, \"pod\", klog.KObj(pod), \"podUID\", pod.UID, \"containers\", strings.Join(containers, \" \"))\n\t}\n\n\t// The intent here is to prevent concurrent updates to a pod's status from\n\t// clobbering each other so the phase of a pod progresses monotonically.\n\tif isCached \u0026\u0026 isPodStatusByKubeletEqual(\u0026cachedStatus.status, \u0026status) \u0026\u0026 !forceUpdate {\n\t\tklog.V(3).InfoS(\"Ignoring same status for pod\", \"pod\", klog.KObj(pod), \"status\", status)\n\t\treturn\n\t}\n\n\tnewStatus := versionedPodStatus{\n\t\tstatus: status,\n\t\tversion: cachedStatus.version + 1,\n\t\tpodName: pod.Name,\n\t\tpodNamespace: pod.Namespace,\n\t\tpodIsFinished: podIsFinished,\n\t}\n\n\t// Multiple status updates can be generated before we update the API server,\n\t// so we track the time from the first status update until we retire it to\n\t// the API.\n\tif cachedStatus.at.IsZero() {\n\t\tnewStatus.at = time.Now()\n\t} else {\n\t\tnewStatus.at = cachedStatus.at\n\t}\n\n\tm.podStatuses[pod.UID] = newStatus\n\n\tselect {\n\tcase m.podStatusChannel \u003c- struct{}{}:\n\tdefault:\n\t\t// there's already a status update pending\n\t}\n}","line":{"from":552,"to":677}} {"id":100007737,"name":"updateLastTransitionTime","signature":"func updateLastTransitionTime(status, oldStatus *v1.PodStatus, conditionType v1.PodConditionType)","file":"pkg/kubelet/status/status_manager.go","code":"// updateLastTransitionTime updates the LastTransitionTime of a pod condition.\nfunc updateLastTransitionTime(status, oldStatus *v1.PodStatus, conditionType v1.PodConditionType) {\n\t_, condition := podutil.GetPodCondition(status, conditionType)\n\tif condition == nil {\n\t\treturn\n\t}\n\t// Need to set LastTransitionTime.\n\tlastTransitionTime := metav1.Now()\n\t_, oldCondition := podutil.GetPodCondition(oldStatus, conditionType)\n\tif oldCondition != nil \u0026\u0026 condition.Status == oldCondition.Status {\n\t\tlastTransitionTime = oldCondition.LastTransitionTime\n\t}\n\tcondition.LastTransitionTime = lastTransitionTime\n}","line":{"from":679,"to":692}} {"id":100007738,"name":"deletePodStatus","signature":"func (m *manager) deletePodStatus(uid types.UID)","file":"pkg/kubelet/status/status_manager.go","code":"// deletePodStatus simply removes the given pod from the status cache.\nfunc (m *manager) deletePodStatus(uid types.UID) {\n\tm.podStatusesLock.Lock()\n\tdefer m.podStatusesLock.Unlock()\n\tdelete(m.podStatuses, uid)\n\tm.podStartupLatencyHelper.DeletePodStartupState(uid)\n\tif utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) {\n\t\tm.state.Delete(string(uid), \"\")\n\t}\n}","line":{"from":694,"to":703}} {"id":100007739,"name":"RemoveOrphanedStatuses","signature":"func (m *manager) RemoveOrphanedStatuses(podUIDs map[types.UID]bool)","file":"pkg/kubelet/status/status_manager.go","code":"// TODO(filipg): It'd be cleaner if we can do this without signal from user.\nfunc (m *manager) RemoveOrphanedStatuses(podUIDs map[types.UID]bool) {\n\tm.podStatusesLock.Lock()\n\tdefer m.podStatusesLock.Unlock()\n\tfor key := range m.podStatuses {\n\t\tif _, ok := podUIDs[key]; !ok {\n\t\t\tklog.V(5).InfoS(\"Removing pod from status map.\", \"podUID\", key)\n\t\t\tdelete(m.podStatuses, key)\n\t\t\tif utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) {\n\t\t\t\tm.state.Delete(string(key), \"\")\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":705,"to":718}} {"id":100007740,"name":"syncBatch","signature":"func (m *manager) syncBatch(all bool) int","file":"pkg/kubelet/status/status_manager.go","code":"// syncBatch syncs pods statuses with the apiserver. Returns the number of syncs\n// attempted for testing.\nfunc (m *manager) syncBatch(all bool) int {\n\ttype podSync struct {\n\t\tpodUID types.UID\n\t\tstatusUID kubetypes.MirrorPodUID\n\t\tstatus versionedPodStatus\n\t}\n\n\tvar updatedStatuses []podSync\n\tpodToMirror, mirrorToPod := m.podManager.GetUIDTranslations()\n\tfunc() { // Critical section\n\t\tm.podStatusesLock.RLock()\n\t\tdefer m.podStatusesLock.RUnlock()\n\n\t\t// Clean up orphaned versions.\n\t\tif all {\n\t\t\tfor uid := range m.apiStatusVersions {\n\t\t\t\t_, hasPod := m.podStatuses[types.UID(uid)]\n\t\t\t\t_, hasMirror := mirrorToPod[uid]\n\t\t\t\tif !hasPod \u0026\u0026 !hasMirror {\n\t\t\t\t\tdelete(m.apiStatusVersions, uid)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Decide which pods need status updates.\n\t\tfor uid, status := range m.podStatuses {\n\t\t\t// translate the pod UID (source) to the status UID (API pod) -\n\t\t\t// static pods are identified in source by pod UID but tracked in the\n\t\t\t// API via the uid of the mirror pod\n\t\t\tuidOfStatus := kubetypes.MirrorPodUID(uid)\n\t\t\tif mirrorUID, ok := podToMirror[kubetypes.ResolvedPodUID(uid)]; ok {\n\t\t\t\tif mirrorUID == \"\" {\n\t\t\t\t\tklog.V(5).InfoS(\"Static pod does not have a corresponding mirror pod; skipping\",\n\t\t\t\t\t\t\"podUID\", uid,\n\t\t\t\t\t\t\"pod\", klog.KRef(status.podNamespace, status.podName))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tuidOfStatus = mirrorUID\n\t\t\t}\n\n\t\t\t// if a new status update has been delivered, trigger an update, otherwise the\n\t\t\t// pod can wait for the next bulk check (which performs reconciliation as well)\n\t\t\tif !all {\n\t\t\t\tif m.apiStatusVersions[uidOfStatus] \u003e= status.version {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tupdatedStatuses = append(updatedStatuses, podSync{uid, uidOfStatus, status})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Ensure that any new status, or mismatched status, or pod that is ready for\n\t\t\t// deletion gets updated. If a status update fails we retry the next time any\n\t\t\t// other pod is updated.\n\t\t\tif m.needsUpdate(types.UID(uidOfStatus), status) {\n\t\t\t\tupdatedStatuses = append(updatedStatuses, podSync{uid, uidOfStatus, status})\n\t\t\t} else if m.needsReconcile(uid, status.status) {\n\t\t\t\t// Delete the apiStatusVersions here to force an update on the pod status\n\t\t\t\t// In most cases the deleted apiStatusVersions here should be filled\n\t\t\t\t// soon after the following syncPod() [If the syncPod() sync an update\n\t\t\t\t// successfully].\n\t\t\t\tdelete(m.apiStatusVersions, uidOfStatus)\n\t\t\t\tupdatedStatuses = append(updatedStatuses, podSync{uid, uidOfStatus, status})\n\t\t\t}\n\t\t}\n\t}()\n\n\tfor _, update := range updatedStatuses {\n\t\tklog.V(5).InfoS(\"Sync pod status\", \"podUID\", update.podUID, \"statusUID\", update.statusUID, \"version\", update.status.version)\n\t\tm.syncPod(update.podUID, update.status)\n\t}\n\n\treturn len(updatedStatuses)\n}","line":{"from":720,"to":794}} {"id":100007741,"name":"syncPod","signature":"func (m *manager) syncPod(uid types.UID, status versionedPodStatus)","file":"pkg/kubelet/status/status_manager.go","code":"// syncPod syncs the given status with the API server. The caller must not hold the status lock.\nfunc (m *manager) syncPod(uid types.UID, status versionedPodStatus) {\n\t// TODO: make me easier to express from client code\n\tpod, err := m.kubeClient.CoreV1().Pods(status.podNamespace).Get(context.TODO(), status.podName, metav1.GetOptions{})\n\tif errors.IsNotFound(err) {\n\t\tklog.V(3).InfoS(\"Pod does not exist on the server\",\n\t\t\t\"podUID\", uid,\n\t\t\t\"pod\", klog.KRef(status.podNamespace, status.podName))\n\t\t// If the Pod is deleted the status will be cleared in\n\t\t// RemoveOrphanedStatuses, so we just ignore the update here.\n\t\treturn\n\t}\n\tif err != nil {\n\t\tklog.InfoS(\"Failed to get status for pod\",\n\t\t\t\"podUID\", uid,\n\t\t\t\"pod\", klog.KRef(status.podNamespace, status.podName),\n\t\t\t\"err\", err)\n\t\treturn\n\t}\n\n\ttranslatedUID := m.podManager.TranslatePodUID(pod.UID)\n\t// Type convert original uid just for the purpose of comparison.\n\tif len(translatedUID) \u003e 0 \u0026\u0026 translatedUID != kubetypes.ResolvedPodUID(uid) {\n\t\tklog.V(2).InfoS(\"Pod was deleted and then recreated, skipping status update\",\n\t\t\t\"pod\", klog.KObj(pod),\n\t\t\t\"oldPodUID\", uid,\n\t\t\t\"podUID\", translatedUID)\n\t\tm.deletePodStatus(uid)\n\t\treturn\n\t}\n\n\tmergedStatus := mergePodStatus(pod.Status, status.status, m.podDeletionSafety.PodCouldHaveRunningContainers(pod))\n\n\tnewPod, patchBytes, unchanged, err := statusutil.PatchPodStatus(context.TODO(), m.kubeClient, pod.Namespace, pod.Name, pod.UID, pod.Status, mergedStatus)\n\tklog.V(3).InfoS(\"Patch status for pod\", \"pod\", klog.KObj(pod), \"podUID\", uid, \"patch\", string(patchBytes))\n\n\tif err != nil {\n\t\tklog.InfoS(\"Failed to update status for pod\", \"pod\", klog.KObj(pod), \"err\", err)\n\t\treturn\n\t}\n\tif unchanged {\n\t\tklog.V(3).InfoS(\"Status for pod is up-to-date\", \"pod\", klog.KObj(pod), \"statusVersion\", status.version)\n\t} else {\n\t\tklog.V(3).InfoS(\"Status for pod updated successfully\", \"pod\", klog.KObj(pod), \"statusVersion\", status.version, \"status\", mergedStatus)\n\t\tpod = newPod\n\t\t// We pass a new object (result of API call which contains updated ResourceVersion)\n\t\tm.podStartupLatencyHelper.RecordStatusUpdated(pod)\n\t}\n\n\t// measure how long the status update took to propagate from generation to update on the server\n\tif status.at.IsZero() {\n\t\tklog.V(3).InfoS(\"Pod had no status time set\", \"pod\", klog.KObj(pod), \"podUID\", uid, \"version\", status.version)\n\t} else {\n\t\tduration := time.Since(status.at).Truncate(time.Millisecond)\n\t\tmetrics.PodStatusSyncDuration.Observe(duration.Seconds())\n\t}\n\n\tm.apiStatusVersions[kubetypes.MirrorPodUID(pod.UID)] = status.version\n\n\t// We don't handle graceful deletion of mirror pods.\n\tif m.canBeDeleted(pod, status.status, status.podIsFinished) {\n\t\tdeleteOptions := metav1.DeleteOptions{\n\t\t\tGracePeriodSeconds: new(int64),\n\t\t\t// Use the pod UID as the precondition for deletion to prevent deleting a\n\t\t\t// newly created pod with the same name and namespace.\n\t\t\tPreconditions: metav1.NewUIDPreconditions(string(pod.UID)),\n\t\t}\n\t\terr = m.kubeClient.CoreV1().Pods(pod.Namespace).Delete(context.TODO(), pod.Name, deleteOptions)\n\t\tif err != nil {\n\t\t\tklog.InfoS(\"Failed to delete status for pod\", \"pod\", klog.KObj(pod), \"err\", err)\n\t\t\treturn\n\t\t}\n\t\tklog.V(3).InfoS(\"Pod fully terminated and removed from etcd\", \"pod\", klog.KObj(pod))\n\t\tm.deletePodStatus(uid)\n\t}\n}","line":{"from":796,"to":871}} {"id":100007742,"name":"needsUpdate","signature":"func (m *manager) needsUpdate(uid types.UID, status versionedPodStatus) bool","file":"pkg/kubelet/status/status_manager.go","code":"// needsUpdate returns whether the status is stale for the given pod UID.\n// This method is not thread safe, and must only be accessed by the sync thread.\nfunc (m *manager) needsUpdate(uid types.UID, status versionedPodStatus) bool {\n\tlatest, ok := m.apiStatusVersions[kubetypes.MirrorPodUID(uid)]\n\tif !ok || latest \u003c status.version {\n\t\treturn true\n\t}\n\tpod, ok := m.podManager.GetPodByUID(uid)\n\tif !ok {\n\t\treturn false\n\t}\n\treturn m.canBeDeleted(pod, status.status, status.podIsFinished)\n}","line":{"from":873,"to":885}} {"id":100007743,"name":"canBeDeleted","signature":"func (m *manager) canBeDeleted(pod *v1.Pod, status v1.PodStatus, podIsFinished bool) bool","file":"pkg/kubelet/status/status_manager.go","code":"func (m *manager) canBeDeleted(pod *v1.Pod, status v1.PodStatus, podIsFinished bool) bool {\n\tif pod.DeletionTimestamp == nil || kubetypes.IsMirrorPod(pod) {\n\t\treturn false\n\t}\n\t// Delay deletion of pods until the phase is terminal, based on pod.Status\n\t// which comes from pod manager.\n\tif !podutil.IsPodPhaseTerminal(pod.Status.Phase) {\n\t\t// For debugging purposes we also log the kubelet's local phase, when the deletion is delayed.\n\t\tklog.V(3).InfoS(\"Delaying pod deletion as the phase is non-terminal\", \"phase\", pod.Status.Phase, \"localPhase\", status.Phase, \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\t\treturn false\n\t}\n\t// If this is an update completing pod termination then we know the pod termination is finished.\n\tif podIsFinished {\n\t\tklog.V(3).InfoS(\"The pod termination is finished as SyncTerminatedPod completes its execution\", \"phase\", pod.Status.Phase, \"localPhase\", status.Phase, \"pod\", klog.KObj(pod), \"podUID\", pod.UID)\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":887,"to":904}} {"id":100007744,"name":"needsReconcile","signature":"func (m *manager) needsReconcile(uid types.UID, status v1.PodStatus) bool","file":"pkg/kubelet/status/status_manager.go","code":"// needsReconcile compares the given status with the status in the pod manager (which\n// in fact comes from apiserver), returns whether the status needs to be reconciled with\n// the apiserver. Now when pod status is inconsistent between apiserver and kubelet,\n// kubelet should forcibly send an update to reconcile the inconsistence, because kubelet\n// should be the source of truth of pod status.\n// NOTE(random-liu): It's simpler to pass in mirror pod uid and get mirror pod by uid, but\n// now the pod manager only supports getting mirror pod by static pod, so we have to pass\n// static pod uid here.\n// TODO(random-liu): Simplify the logic when mirror pod manager is added.\nfunc (m *manager) needsReconcile(uid types.UID, status v1.PodStatus) bool {\n\t// The pod could be a static pod, so we should translate first.\n\tpod, ok := m.podManager.GetPodByUID(uid)\n\tif !ok {\n\t\tklog.V(4).InfoS(\"Pod has been deleted, no need to reconcile\", \"podUID\", string(uid))\n\t\treturn false\n\t}\n\t// If the pod is a static pod, we should check its mirror pod, because only status in mirror pod is meaningful to us.\n\tif kubetypes.IsStaticPod(pod) {\n\t\tmirrorPod, ok := m.podManager.GetMirrorPodByPod(pod)\n\t\tif !ok {\n\t\t\tklog.V(4).InfoS(\"Static pod has no corresponding mirror pod, no need to reconcile\", \"pod\", klog.KObj(pod))\n\t\t\treturn false\n\t\t}\n\t\tpod = mirrorPod\n\t}\n\n\tpodStatus := pod.Status.DeepCopy()\n\tnormalizeStatus(pod, podStatus)\n\n\tif isPodStatusByKubeletEqual(podStatus, \u0026status) {\n\t\t// If the status from the source is the same with the cached status,\n\t\t// reconcile is not needed. Just return.\n\t\treturn false\n\t}\n\tklog.V(3).InfoS(\"Pod status is inconsistent with cached status for pod, a reconciliation should be triggered\",\n\t\t\"pod\", klog.KObj(pod),\n\t\t\"statusDiff\", diff.ObjectDiff(podStatus, \u0026status))\n\n\treturn true\n}","line":{"from":906,"to":945}} {"id":100007745,"name":"normalizeStatus","signature":"func normalizeStatus(pod *v1.Pod, status *v1.PodStatus) *v1.PodStatus","file":"pkg/kubelet/status/status_manager.go","code":"// normalizeStatus normalizes nanosecond precision timestamps in podStatus\n// down to second precision (*RFC339NANO* -\u003e *RFC3339*). This must be done\n// before comparing podStatus to the status returned by apiserver because\n// apiserver does not support RFC339NANO.\n// Related issue #15262/PR #15263 to move apiserver to RFC339NANO is closed.\nfunc normalizeStatus(pod *v1.Pod, status *v1.PodStatus) *v1.PodStatus {\n\tbytesPerStatus := kubecontainer.MaxPodTerminationMessageLogLength\n\tif containers := len(pod.Spec.Containers) + len(pod.Spec.InitContainers); containers \u003e 0 {\n\t\tbytesPerStatus = bytesPerStatus / containers\n\t}\n\tnormalizeTimeStamp := func(t *metav1.Time) {\n\t\t*t = t.Rfc3339Copy()\n\t}\n\tnormalizeContainerState := func(c *v1.ContainerState) {\n\t\tif c.Running != nil {\n\t\t\tnormalizeTimeStamp(\u0026c.Running.StartedAt)\n\t\t}\n\t\tif c.Terminated != nil {\n\t\t\tnormalizeTimeStamp(\u0026c.Terminated.StartedAt)\n\t\t\tnormalizeTimeStamp(\u0026c.Terminated.FinishedAt)\n\t\t\tif len(c.Terminated.Message) \u003e bytesPerStatus {\n\t\t\t\tc.Terminated.Message = c.Terminated.Message[:bytesPerStatus]\n\t\t\t}\n\t\t}\n\t}\n\n\tif status.StartTime != nil {\n\t\tnormalizeTimeStamp(status.StartTime)\n\t}\n\tfor i := range status.Conditions {\n\t\tcondition := \u0026status.Conditions[i]\n\t\tnormalizeTimeStamp(\u0026condition.LastProbeTime)\n\t\tnormalizeTimeStamp(\u0026condition.LastTransitionTime)\n\t}\n\n\t// update container statuses\n\tfor i := range status.ContainerStatuses {\n\t\tcstatus := \u0026status.ContainerStatuses[i]\n\t\tnormalizeContainerState(\u0026cstatus.State)\n\t\tnormalizeContainerState(\u0026cstatus.LastTerminationState)\n\t}\n\t// Sort the container statuses, so that the order won't affect the result of comparison\n\tsort.Sort(kubetypes.SortedContainerStatuses(status.ContainerStatuses))\n\n\t// update init container statuses\n\tfor i := range status.InitContainerStatuses {\n\t\tcstatus := \u0026status.InitContainerStatuses[i]\n\t\tnormalizeContainerState(\u0026cstatus.State)\n\t\tnormalizeContainerState(\u0026cstatus.LastTerminationState)\n\t}\n\t// Sort the container statuses, so that the order won't affect the result of comparison\n\tkubetypes.SortInitContainerStatuses(pod, status.InitContainerStatuses)\n\treturn status\n}","line":{"from":947,"to":1000}} {"id":100007746,"name":"mergePodStatus","signature":"func mergePodStatus(oldPodStatus, newPodStatus v1.PodStatus, couldHaveRunningContainers bool) v1.PodStatus","file":"pkg/kubelet/status/status_manager.go","code":"// mergePodStatus merges oldPodStatus and newPodStatus to preserve where pod conditions\n// not owned by kubelet and to ensure terminal phase transition only happens after all\n// running containers have terminated. This method does not modify the old status.\nfunc mergePodStatus(oldPodStatus, newPodStatus v1.PodStatus, couldHaveRunningContainers bool) v1.PodStatus {\n\tpodConditions := make([]v1.PodCondition, 0, len(oldPodStatus.Conditions)+len(newPodStatus.Conditions))\n\n\tfor _, c := range oldPodStatus.Conditions {\n\t\tif !kubetypes.PodConditionByKubelet(c.Type) {\n\t\t\tpodConditions = append(podConditions, c)\n\t\t}\n\t}\n\n\ttransitioningToTerminalPhase := !podutil.IsPodPhaseTerminal(oldPodStatus.Phase) \u0026\u0026 podutil.IsPodPhaseTerminal(newPodStatus.Phase)\n\n\tfor _, c := range newPodStatus.Conditions {\n\t\tif kubetypes.PodConditionByKubelet(c.Type) {\n\t\t\tpodConditions = append(podConditions, c)\n\t\t} else if kubetypes.PodConditionSharedByKubelet(c.Type) {\n\t\t\t// we replace or append all the \"shared by kubelet\" conditions\n\t\t\tif c.Type == v1.DisruptionTarget {\n\t\t\t\t// guard the update of the DisruptionTarget condition with a check to ensure\n\t\t\t\t// it will only be sent once all containers have terminated and the phase\n\t\t\t\t// is terminal. This avoids sending an unnecessary patch request to add\n\t\t\t\t// the condition if the actual status phase transition is delayed.\n\t\t\t\tif transitioningToTerminalPhase \u0026\u0026 !couldHaveRunningContainers {\n\t\t\t\t\t// update the LastTransitionTime again here because the older transition\n\t\t\t\t\t// time set in updateStatusInternal is likely stale as sending of\n\t\t\t\t\t// the condition was delayed until all pod's containers have terminated.\n\t\t\t\t\tupdateLastTransitionTime(\u0026newPodStatus, \u0026oldPodStatus, c.Type)\n\t\t\t\t\tif _, c := podutil.GetPodConditionFromList(newPodStatus.Conditions, c.Type); c != nil {\n\t\t\t\t\t\t// for shared conditions we update or append in podConditions\n\t\t\t\t\t\tpodConditions = statusutil.ReplaceOrAppendPodCondition(podConditions, c)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tnewPodStatus.Conditions = podConditions\n\n\t// Delay transitioning a pod to a terminal status unless the pod is actually terminal.\n\t// The Kubelet should never transition a pod to terminal status that could have running\n\t// containers and thus actively be leveraging exclusive resources. Note that resources\n\t// like volumes are reconciled by a subsystem in the Kubelet and will converge if a new\n\t// pod reuses an exclusive resource (unmount -\u003e free -\u003e mount), which means we do not\n\t// need wait for those resources to be detached by the Kubelet. In general, resources\n\t// the Kubelet exclusively owns must be released prior to a pod being reported terminal,\n\t// while resources that have participanting components above the API use the pod's\n\t// transition to a terminal phase (or full deletion) to release those resources.\n\tif transitioningToTerminalPhase {\n\t\tif couldHaveRunningContainers {\n\t\t\tnewPodStatus.Phase = oldPodStatus.Phase\n\t\t\tnewPodStatus.Reason = oldPodStatus.Reason\n\t\t\tnewPodStatus.Message = oldPodStatus.Message\n\t\t}\n\t}\n\n\t// If the new phase is terminal, explicitly set the ready condition to false for v1.PodReady and v1.ContainersReady.\n\t// It may take some time for kubelet to reconcile the ready condition, so explicitly set ready conditions to false if the phase is terminal.\n\t// This is done to ensure kubelet does not report a status update with terminal pod phase and ready=true.\n\t// See https://issues.k8s.io/108594 for more details.\n\tif podutil.IsPodPhaseTerminal(newPodStatus.Phase) {\n\t\tif podutil.IsPodReadyConditionTrue(newPodStatus) || podutil.IsContainersReadyConditionTrue(newPodStatus) {\n\t\t\tcontainersReadyCondition := generateContainersReadyConditionForTerminalPhase(newPodStatus.Phase)\n\t\t\tpodutil.UpdatePodCondition(\u0026newPodStatus, \u0026containersReadyCondition)\n\n\t\t\tpodReadyCondition := generatePodReadyConditionForTerminalPhase(newPodStatus.Phase)\n\t\t\tpodutil.UpdatePodCondition(\u0026newPodStatus, \u0026podReadyCondition)\n\t\t}\n\t}\n\n\treturn newPodStatus\n}","line":{"from":1002,"to":1073}} {"id":100007747,"name":"NeedToReconcilePodReadiness","signature":"func NeedToReconcilePodReadiness(pod *v1.Pod) bool","file":"pkg/kubelet/status/status_manager.go","code":"// NeedToReconcilePodReadiness returns if the pod \"Ready\" condition need to be reconcile\nfunc NeedToReconcilePodReadiness(pod *v1.Pod) bool {\n\tif len(pod.Spec.ReadinessGates) == 0 {\n\t\treturn false\n\t}\n\tpodReadyCondition := GeneratePodReadyCondition(\u0026pod.Spec, pod.Status.Conditions, pod.Status.ContainerStatuses, pod.Status.Phase)\n\ti, curCondition := podutil.GetPodConditionFromList(pod.Status.Conditions, v1.PodReady)\n\t// Only reconcile if \"Ready\" condition is present and Status or Message is not expected\n\tif i \u003e= 0 \u0026\u0026 (curCondition.Status != podReadyCondition.Status || curCondition.Message != podReadyCondition.Message) {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":1075,"to":1087}} {"id":100007748,"name":"NewAllowlist","signature":"func NewAllowlist(patterns []string) (*patternAllowlist, error)","file":"pkg/kubelet/sysctl/allowlist.go","code":"// NewAllowlist creates a new Allowlist from a list of sysctls and sysctl pattern (ending in *).\nfunc NewAllowlist(patterns []string) (*patternAllowlist, error) {\n\tw := \u0026patternAllowlist{\n\t\tsysctls: map[string]Namespace{},\n\t\tprefixes: map[string]Namespace{},\n\t}\n\n\tfor _, s := range patterns {\n\t\tif !policyvalidation.IsValidSysctlPattern(s) {\n\t\t\treturn nil, fmt.Errorf(\"sysctl %q must have at most %d characters and match regex %s\",\n\t\t\t\ts,\n\t\t\t\tvalidation.SysctlMaxLength,\n\t\t\t\tpolicyvalidation.SysctlContainSlashPatternFmt,\n\t\t\t)\n\t\t}\n\t\ts = convertSysctlVariableToDotsSeparator(s)\n\t\tif strings.HasSuffix(s, \"*\") {\n\t\t\tprefix := s[:len(s)-1]\n\t\t\tns := NamespacedBy(prefix)\n\t\t\tif ns == unknownNamespace {\n\t\t\t\treturn nil, fmt.Errorf(\"the sysctls %q are not known to be namespaced\", s)\n\t\t\t}\n\t\t\tw.prefixes[prefix] = ns\n\t\t} else {\n\t\t\tns := NamespacedBy(s)\n\t\t\tif ns == unknownNamespace {\n\t\t\t\treturn nil, fmt.Errorf(\"the sysctl %q are not known to be namespaced\", s)\n\t\t\t}\n\t\t\tw.sysctls[s] = ns\n\t\t}\n\t}\n\treturn w, nil\n}","line":{"from":42,"to":74}} {"id":100007749,"name":"validateSysctl","signature":"func (w *patternAllowlist) validateSysctl(sysctl string, hostNet, hostIPC bool) error","file":"pkg/kubelet/sysctl/allowlist.go","code":"// validateSysctl checks that a sysctl is allowlisted because it is known\n// to be namespaced by the Linux kernel. Note that being allowlisted is required, but not\n// sufficient: the container runtime might have a stricter check and refuse to launch a pod.\n//\n// The parameters hostNet and hostIPC are used to forbid sysctls for pod sharing the\n// respective namespaces with the host. This check is only possible for sysctls on\n// the static default allowlist, not those on the custom allowlist provided by the admin.\nfunc (w *patternAllowlist) validateSysctl(sysctl string, hostNet, hostIPC bool) error {\n\tsysctl = convertSysctlVariableToDotsSeparator(sysctl)\n\tnsErrorFmt := \"%q not allowed with host %s enabled\"\n\tif ns, found := w.sysctls[sysctl]; found {\n\t\tif ns == ipcNamespace \u0026\u0026 hostIPC {\n\t\t\treturn fmt.Errorf(nsErrorFmt, sysctl, ns)\n\t\t}\n\t\tif ns == netNamespace \u0026\u0026 hostNet {\n\t\t\treturn fmt.Errorf(nsErrorFmt, sysctl, ns)\n\t\t}\n\t\treturn nil\n\t}\n\tfor p, ns := range w.prefixes {\n\t\tif strings.HasPrefix(sysctl, p) {\n\t\t\tif ns == ipcNamespace \u0026\u0026 hostIPC {\n\t\t\t\treturn fmt.Errorf(nsErrorFmt, sysctl, ns)\n\t\t\t}\n\t\t\tif ns == netNamespace \u0026\u0026 hostNet {\n\t\t\t\treturn fmt.Errorf(nsErrorFmt, sysctl, ns)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"%q not allowlisted\", sysctl)\n}","line":{"from":76,"to":107}} {"id":100007750,"name":"Admit","signature":"func (w *patternAllowlist) Admit(attrs *lifecycle.PodAdmitAttributes) lifecycle.PodAdmitResult","file":"pkg/kubelet/sysctl/allowlist.go","code":"// Admit checks that all sysctls given in pod's security context\n// are valid according to the allowlist.\nfunc (w *patternAllowlist) Admit(attrs *lifecycle.PodAdmitAttributes) lifecycle.PodAdmitResult {\n\tpod := attrs.Pod\n\tif pod.Spec.SecurityContext == nil || len(pod.Spec.SecurityContext.Sysctls) == 0 {\n\t\treturn lifecycle.PodAdmitResult{\n\t\t\tAdmit: true,\n\t\t}\n\t}\n\n\tvar hostNet, hostIPC bool\n\tif pod.Spec.SecurityContext != nil {\n\t\thostNet = pod.Spec.HostNetwork\n\t\thostIPC = pod.Spec.HostIPC\n\t}\n\tfor _, s := range pod.Spec.SecurityContext.Sysctls {\n\t\tif err := w.validateSysctl(s.Name, hostNet, hostIPC); err != nil {\n\t\t\treturn lifecycle.PodAdmitResult{\n\t\t\t\tAdmit: false,\n\t\t\t\tReason: ForbiddenReason,\n\t\t\t\tMessage: fmt.Sprintf(\"forbidden sysctl: %v\", err),\n\t\t\t}\n\t\t}\n\t}\n\n\treturn lifecycle.PodAdmitResult{\n\t\tAdmit: true,\n\t}\n}","line":{"from":109,"to":137}} {"id":100007751,"name":"NamespacedBy","signature":"func NamespacedBy(val string) Namespace","file":"pkg/kubelet/sysctl/namespace.go","code":"// NamespacedBy returns the namespace of the Linux kernel for a sysctl, or\n// unknownNamespace if the sysctl is not known to be namespaced.\nfunc NamespacedBy(val string) Namespace {\n\tif ns, found := namespaces[val]; found {\n\t\treturn ns\n\t}\n\tfor p, ns := range prefixNamespaces {\n\t\tif strings.HasPrefix(val, p) {\n\t\t\treturn ns\n\t\t}\n\t}\n\treturn unknownNamespace\n}","line":{"from":48,"to":60}} {"id":100007752,"name":"SafeSysctlAllowlist","signature":"func SafeSysctlAllowlist() []string","file":"pkg/kubelet/sysctl/safe_sysctls.go","code":"// SafeSysctlAllowlist returns the allowlist of safe sysctls and safe sysctl patterns (ending in *).\n//\n// A sysctl is called safe iff\n// - it is namespaced in the container or the pod\n// - it is isolated, i.e. has no influence on any other pod on the same node.\nfunc SafeSysctlAllowlist() []string {\n\tif goruntime.GOOS == \"linux\" {\n\t\t// make sure we're on a new enough kernel that the ip_local_reserved_ports sysctl is namespaced\n\t\tkernelVersion, err := getKernelVersion()\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to get kernel version, dropping net.ipv4.ip_local_reserved_ports from safe sysctl list\")\n\t\t\treturn safeSysctls\n\t\t}\n\t\tif kernelVersion.LessThan(version.MustParseGeneric(ipLocalReservedPortsMinNamespacedKernelVersion)) {\n\t\t\tklog.ErrorS(nil, \"Kernel version is too old, dropping net.ipv4.ip_local_reserved_ports from safe sysctl list\", \"kernelVersion\", kernelVersion)\n\t\t\treturn safeSysctls\n\t\t}\n\t}\n\treturn safeSysctlsIncludeReservedPorts\n}","line":{"from":48,"to":67}} {"id":100007753,"name":"getKernelVersion","signature":"func getKernelVersion() (*version.Version, error)","file":"pkg/kubelet/sysctl/safe_sysctls.go","code":"func getKernelVersion() (*version.Version, error) {\n\tkernelVersionStr, err := ipvs.NewLinuxKernelHandler().GetKernelVersion()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get kernel version: %w\", err)\n\t}\n\tkernelVersion, err := version.ParseGeneric(kernelVersionStr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse kernel version: %w\", err)\n\t}\n\treturn kernelVersion, nil\n}","line":{"from":69,"to":79}} {"id":100007754,"name":"convertSysctlVariableToDotsSeparator","signature":"func convertSysctlVariableToDotsSeparator(val string) string","file":"pkg/kubelet/sysctl/util.go","code":"// convertSysctlVariableToDotsSeparator can return sysctl variables in dots separator format.\n// The '/' separator is also accepted in place of a '.'.\n// Convert the sysctl variables to dots separator format for validation.\n// More info:\n//\n//\thttps://man7.org/linux/man-pages/man8/sysctl.8.html\n//\thttps://man7.org/linux/man-pages/man5/sysctl.d.5.html\nfunc convertSysctlVariableToDotsSeparator(val string) string {\n\tif val == \"\" {\n\t\treturn val\n\t}\n\tfirstSepIndex := strings.IndexAny(val, \"./\")\n\tif firstSepIndex == -1 || val[firstSepIndex] == '.' {\n\t\treturn val\n\t}\n\n\tf := func(r rune) rune {\n\t\tswitch r {\n\t\tcase '.':\n\t\t\treturn '/'\n\t\tcase '/':\n\t\t\treturn '.'\n\t\t}\n\t\treturn r\n\t}\n\treturn strings.Map(f, val)\n}","line":{"from":25,"to":51}} {"id":100007755,"name":"ConvertPodSysctlsVariableToDotsSeparator","signature":"func ConvertPodSysctlsVariableToDotsSeparator(securityContext *v1.PodSecurityContext)","file":"pkg/kubelet/sysctl/util.go","code":"// ConvertPodSysctlsVariableToDotsSeparator converts sysctls variable in the Pod.Spec.SecurityContext.Sysctls slice into a dot as a separator\n// according to the linux sysctl conversion rules.\n// see https://man7.org/linux/man-pages/man5/sysctl.d.5.html for more details.\nfunc ConvertPodSysctlsVariableToDotsSeparator(securityContext *v1.PodSecurityContext) {\n\tif securityContext == nil {\n\t\treturn\n\t}\n\tfor i, sysctl := range securityContext.Sysctls {\n\t\tsecurityContext.Sysctls[i].Name = convertSysctlVariableToDotsSeparator(sysctl.Name)\n\t}\n\treturn\n}","line":{"from":53,"to":64}} {"id":100007756,"name":"NewManager","signature":"func NewManager(c clientset.Interface) *Manager","file":"pkg/kubelet/token/token_manager.go","code":"// NewManager returns a new token manager.\nfunc NewManager(c clientset.Interface) *Manager {\n\t// check whether the server supports token requests so we can give a more helpful error message\n\tsupported := false\n\tonce := \u0026sync.Once{}\n\ttokenRequestsSupported := func() bool {\n\t\tonce.Do(func() {\n\t\t\tresources, err := c.Discovery().ServerResourcesForGroupVersion(\"v1\")\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor _, resource := range resources.APIResources {\n\t\t\t\tif resource.Name == \"serviceaccounts/token\" {\n\t\t\t\t\tsupported = true\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\treturn supported\n\t}\n\n\tm := \u0026Manager{\n\t\tgetToken: func(name, namespace string, tr *authenticationv1.TokenRequest) (*authenticationv1.TokenRequest, error) {\n\t\t\tif c == nil {\n\t\t\t\treturn nil, errors.New(\"cannot use TokenManager when kubelet is in standalone mode\")\n\t\t\t}\n\t\t\ttokenRequest, err := c.CoreV1().ServiceAccounts(namespace).CreateToken(context.TODO(), name, tr, metav1.CreateOptions{})\n\t\t\tif apierrors.IsNotFound(err) \u0026\u0026 !tokenRequestsSupported() {\n\t\t\t\treturn nil, fmt.Errorf(\"the API server does not have TokenRequest endpoints enabled\")\n\t\t\t}\n\t\t\treturn tokenRequest, err\n\t\t},\n\t\tcache: make(map[string]*authenticationv1.TokenRequest),\n\t\tclock: clock.RealClock{},\n\t}\n\tgo wait.Forever(m.cleanup, gcPeriod)\n\treturn m\n}","line":{"from":45,"to":82}} {"id":100007757,"name":"GetServiceAccountToken","signature":"func (m *Manager) GetServiceAccountToken(namespace, name string, tr *authenticationv1.TokenRequest) (*authenticationv1.TokenRequest, error)","file":"pkg/kubelet/token/token_manager.go","code":"// GetServiceAccountToken gets a service account token for a pod from cache or\n// from the TokenRequest API. This process is as follows:\n// * Check the cache for the current token request.\n// * If the token exists and does not require a refresh, return the current token.\n// * Attempt to refresh the token.\n// * If the token is refreshed successfully, save it in the cache and return the token.\n// * If refresh fails and the old token is still valid, log an error and return the old token.\n// * If refresh fails and the old token is no longer valid, return an error\nfunc (m *Manager) GetServiceAccountToken(namespace, name string, tr *authenticationv1.TokenRequest) (*authenticationv1.TokenRequest, error) {\n\tkey := keyFunc(name, namespace, tr)\n\n\tctr, ok := m.get(key)\n\n\tif ok \u0026\u0026 !m.requiresRefresh(ctr) {\n\t\treturn ctr, nil\n\t}\n\n\ttr, err := m.getToken(name, namespace, tr)\n\tif err != nil {\n\t\tswitch {\n\t\tcase !ok:\n\t\t\treturn nil, fmt.Errorf(\"failed to fetch token: %v\", err)\n\t\tcase m.expired(ctr):\n\t\t\treturn nil, fmt.Errorf(\"token %s expired and refresh failed: %v\", key, err)\n\t\tdefault:\n\t\t\tklog.ErrorS(err, \"Couldn't update token\", \"cacheKey\", key)\n\t\t\treturn ctr, nil\n\t\t}\n\t}\n\n\tm.set(key, tr)\n\treturn tr, nil\n}","line":{"from":96,"to":128}} {"id":100007758,"name":"DeleteServiceAccountToken","signature":"func (m *Manager) DeleteServiceAccountToken(podUID types.UID)","file":"pkg/kubelet/token/token_manager.go","code":"// DeleteServiceAccountToken should be invoked when pod got deleted. It simply\n// clean token manager cache.\nfunc (m *Manager) DeleteServiceAccountToken(podUID types.UID) {\n\tm.cacheMutex.Lock()\n\tdefer m.cacheMutex.Unlock()\n\tfor k, tr := range m.cache {\n\t\tif tr.Spec.BoundObjectRef.UID == podUID {\n\t\t\tdelete(m.cache, k)\n\t\t}\n\t}\n}","line":{"from":130,"to":140}} {"id":100007759,"name":"cleanup","signature":"func (m *Manager) cleanup()","file":"pkg/kubelet/token/token_manager.go","code":"func (m *Manager) cleanup() {\n\tm.cacheMutex.Lock()\n\tdefer m.cacheMutex.Unlock()\n\tfor k, tr := range m.cache {\n\t\tif m.expired(tr) {\n\t\t\tdelete(m.cache, k)\n\t\t}\n\t}\n}","line":{"from":142,"to":150}} {"id":100007760,"name":"get","signature":"func (m *Manager) get(key string) (*authenticationv1.TokenRequest, bool)","file":"pkg/kubelet/token/token_manager.go","code":"func (m *Manager) get(key string) (*authenticationv1.TokenRequest, bool) {\n\tm.cacheMutex.RLock()\n\tdefer m.cacheMutex.RUnlock()\n\tctr, ok := m.cache[key]\n\treturn ctr, ok\n}","line":{"from":152,"to":157}} {"id":100007761,"name":"set","signature":"func (m *Manager) set(key string, tr *authenticationv1.TokenRequest)","file":"pkg/kubelet/token/token_manager.go","code":"func (m *Manager) set(key string, tr *authenticationv1.TokenRequest) {\n\tm.cacheMutex.Lock()\n\tdefer m.cacheMutex.Unlock()\n\tm.cache[key] = tr\n}","line":{"from":159,"to":163}} {"id":100007762,"name":"expired","signature":"func (m *Manager) expired(t *authenticationv1.TokenRequest) bool","file":"pkg/kubelet/token/token_manager.go","code":"func (m *Manager) expired(t *authenticationv1.TokenRequest) bool {\n\treturn m.clock.Now().After(t.Status.ExpirationTimestamp.Time)\n}","line":{"from":165,"to":167}} {"id":100007763,"name":"requiresRefresh","signature":"func (m *Manager) requiresRefresh(tr *authenticationv1.TokenRequest) bool","file":"pkg/kubelet/token/token_manager.go","code":"// requiresRefresh returns true if the token is older than 80% of its total\n// ttl, or if the token is older than 24 hours.\nfunc (m *Manager) requiresRefresh(tr *authenticationv1.TokenRequest) bool {\n\tif tr.Spec.ExpirationSeconds == nil {\n\t\tcpy := tr.DeepCopy()\n\t\tcpy.Status.Token = \"\"\n\t\tklog.ErrorS(nil, \"Expiration seconds was nil for token request\", \"tokenRequest\", cpy)\n\t\treturn false\n\t}\n\tnow := m.clock.Now()\n\texp := tr.Status.ExpirationTimestamp.Time\n\tiat := exp.Add(-1 * time.Duration(*tr.Spec.ExpirationSeconds) * time.Second)\n\n\tjitter := time.Duration(rand.Float64()*maxJitter.Seconds()) * time.Second\n\tif now.After(iat.Add(maxTTL - jitter)) {\n\t\treturn true\n\t}\n\t// Require a refresh if within 20% of the TTL plus a jitter from the expiration time.\n\tif now.After(exp.Add(-1*time.Duration((*tr.Spec.ExpirationSeconds*20)/100)*time.Second - jitter)) {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":169,"to":191}} {"id":100007764,"name":"keyFunc","signature":"func keyFunc(name, namespace string, tr *authenticationv1.TokenRequest) string","file":"pkg/kubelet/token/token_manager.go","code":"// keys should be nonconfidential and safe to log\nfunc keyFunc(name, namespace string, tr *authenticationv1.TokenRequest) string {\n\tvar exp int64\n\tif tr.Spec.ExpirationSeconds != nil {\n\t\texp = *tr.Spec.ExpirationSeconds\n\t}\n\n\tvar ref authenticationv1.BoundObjectReference\n\tif tr.Spec.BoundObjectRef != nil {\n\t\tref = *tr.Spec.BoundObjectRef\n\t}\n\n\treturn fmt.Sprintf(\"%q/%q/%#v/%#v/%#v\", name, namespace, tr.Spec.Audiences, exp, ref)\n}","line":{"from":193,"to":206}} {"id":100007765,"name":"GetContainerName","signature":"func GetContainerName(labels map[string]string) string","file":"pkg/kubelet/types/labels.go","code":"// GetContainerName returns the value of the KubernetesContainerNameLabel.\nfunc GetContainerName(labels map[string]string) string {\n\treturn labels[KubernetesContainerNameLabel]\n}","line":{"from":27,"to":30}} {"id":100007766,"name":"GetPodName","signature":"func GetPodName(labels map[string]string) string","file":"pkg/kubelet/types/labels.go","code":"// GetPodName returns the value of the KubernetesPodNameLabel.\nfunc GetPodName(labels map[string]string) string {\n\treturn labels[KubernetesPodNameLabel]\n}","line":{"from":32,"to":35}} {"id":100007767,"name":"GetPodUID","signature":"func GetPodUID(labels map[string]string) string","file":"pkg/kubelet/types/labels.go","code":"// GetPodUID returns the value of the KubernetesPodUIDLabel.\nfunc GetPodUID(labels map[string]string) string {\n\treturn labels[KubernetesPodUIDLabel]\n}","line":{"from":37,"to":40}} {"id":100007768,"name":"GetPodNamespace","signature":"func GetPodNamespace(labels map[string]string) string","file":"pkg/kubelet/types/labels.go","code":"// GetPodNamespace returns the value of the KubernetesPodNamespaceLabel.\nfunc GetPodNamespace(labels map[string]string) string {\n\treturn labels[KubernetesPodNamespaceLabel]\n}","line":{"from":42,"to":45}} {"id":100007769,"name":"PodConditionByKubelet","signature":"func PodConditionByKubelet(conditionType v1.PodConditionType) bool","file":"pkg/kubelet/types/pod_status.go","code":"// PodConditionByKubelet returns if the pod condition type is owned by kubelet\nfunc PodConditionByKubelet(conditionType v1.PodConditionType) bool {\n\tfor _, c := range PodConditionsByKubelet {\n\t\tif c == conditionType {\n\t\t\treturn true\n\t\t}\n\t}\n\tif utilfeature.DefaultFeatureGate.Enabled(features.PodHasNetworkCondition) {\n\t\tif conditionType == PodHasNetwork {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":33,"to":46}} {"id":100007770,"name":"PodConditionSharedByKubelet","signature":"func PodConditionSharedByKubelet(conditionType v1.PodConditionType) bool","file":"pkg/kubelet/types/pod_status.go","code":"// PodConditionSharedByKubelet returns if the pod condition type is shared by kubelet\nfunc PodConditionSharedByKubelet(conditionType v1.PodConditionType) bool {\n\tif utilfeature.DefaultFeatureGate.Enabled(features.PodDisruptionConditions) {\n\t\tif conditionType == v1.DisruptionTarget {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":48,"to":56}} {"id":100007771,"name":"GetValidatedSources","signature":"func GetValidatedSources(sources []string) ([]string, error)","file":"pkg/kubelet/types/pod_update.go","code":"// GetValidatedSources gets all validated sources from the specified sources.\nfunc GetValidatedSources(sources []string) ([]string, error) {\n\tvalidated := make([]string, 0, len(sources))\n\tfor _, source := range sources {\n\t\tswitch source {\n\t\tcase AllSource:\n\t\t\treturn []string{FileSource, HTTPSource, ApiserverSource}, nil\n\t\tcase FileSource, HTTPSource, ApiserverSource:\n\t\t\tvalidated = append(validated, source)\n\t\tcase \"\":\n\t\t\t// Skip\n\t\tdefault:\n\t\t\treturn []string{}, fmt.Errorf(\"unknown pod source %q\", source)\n\t\t}\n\t}\n\treturn validated, nil\n}","line":{"from":85,"to":101}} {"id":100007772,"name":"GetPodSource","signature":"func GetPodSource(pod *v1.Pod) (string, error)","file":"pkg/kubelet/types/pod_update.go","code":"// GetPodSource returns the source of the pod based on the annotation.\nfunc GetPodSource(pod *v1.Pod) (string, error) {\n\tif pod.Annotations != nil {\n\t\tif source, ok := pod.Annotations[ConfigSourceAnnotationKey]; ok {\n\t\t\treturn source, nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"cannot get source of pod %q\", pod.UID)\n}","line":{"from":103,"to":111}} {"id":100007773,"name":"String","signature":"func (sp SyncPodType) String() string","file":"pkg/kubelet/types/pod_update.go","code":"func (sp SyncPodType) String() string {\n\tswitch sp {\n\tcase SyncPodCreate:\n\t\treturn \"create\"\n\tcase SyncPodUpdate:\n\t\treturn \"update\"\n\tcase SyncPodSync:\n\t\treturn \"sync\"\n\tcase SyncPodKill:\n\t\treturn \"kill\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}","line":{"from":128,"to":141}} {"id":100007774,"name":"IsMirrorPod","signature":"func IsMirrorPod(pod *v1.Pod) bool","file":"pkg/kubelet/types/pod_update.go","code":"// IsMirrorPod returns true if the passed Pod is a Mirror Pod.\nfunc IsMirrorPod(pod *v1.Pod) bool {\n\tif pod.Annotations == nil {\n\t\treturn false\n\t}\n\t_, ok := pod.Annotations[ConfigMirrorAnnotationKey]\n\treturn ok\n}","line":{"from":143,"to":150}} {"id":100007775,"name":"IsStaticPod","signature":"func IsStaticPod(pod *v1.Pod) bool","file":"pkg/kubelet/types/pod_update.go","code":"// IsStaticPod returns true if the pod is a static pod.\nfunc IsStaticPod(pod *v1.Pod) bool {\n\tsource, err := GetPodSource(pod)\n\treturn err == nil \u0026\u0026 source != ApiserverSource\n}","line":{"from":152,"to":156}} {"id":100007776,"name":"IsCriticalPod","signature":"func IsCriticalPod(pod *v1.Pod) bool","file":"pkg/kubelet/types/pod_update.go","code":"// IsCriticalPod returns true if pod's priority is greater than or equal to SystemCriticalPriority.\nfunc IsCriticalPod(pod *v1.Pod) bool {\n\tif IsStaticPod(pod) {\n\t\treturn true\n\t}\n\tif IsMirrorPod(pod) {\n\t\treturn true\n\t}\n\tif pod.Spec.Priority != nil \u0026\u0026 IsCriticalPodBasedOnPriority(*pod.Spec.Priority) {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":158,"to":170}} {"id":100007777,"name":"Preemptable","signature":"func Preemptable(preemptor, preemptee *v1.Pod) bool","file":"pkg/kubelet/types/pod_update.go","code":"// Preemptable returns true if preemptor pod can preempt preemptee pod\n// if preemptee is not critical or if preemptor's priority is greater than preemptee's priority\nfunc Preemptable(preemptor, preemptee *v1.Pod) bool {\n\tif IsCriticalPod(preemptor) \u0026\u0026 !IsCriticalPod(preemptee) {\n\t\treturn true\n\t}\n\tif (preemptor != nil \u0026\u0026 preemptor.Spec.Priority != nil) \u0026\u0026\n\t\t(preemptee != nil \u0026\u0026 preemptee.Spec.Priority != nil) {\n\t\treturn *(preemptor.Spec.Priority) \u003e *(preemptee.Spec.Priority)\n\t}\n\n\treturn false\n}","line":{"from":172,"to":184}} {"id":100007778,"name":"IsCriticalPodBasedOnPriority","signature":"func IsCriticalPodBasedOnPriority(priority int32) bool","file":"pkg/kubelet/types/pod_update.go","code":"// IsCriticalPodBasedOnPriority checks if the given pod is a critical pod based on priority resolved from pod Spec.\nfunc IsCriticalPodBasedOnPriority(priority int32) bool {\n\treturn priority \u003e= scheduling.SystemCriticalPriority\n}","line":{"from":186,"to":189}} {"id":100007779,"name":"IsNodeCriticalPod","signature":"func IsNodeCriticalPod(pod *v1.Pod) bool","file":"pkg/kubelet/types/pod_update.go","code":"// IsNodeCriticalPod checks if the given pod is a system-node-critical\nfunc IsNodeCriticalPod(pod *v1.Pod) bool {\n\treturn IsCriticalPod(pod) \u0026\u0026 (pod.Spec.PriorityClassName == scheduling.SystemNodeCritical)\n}","line":{"from":191,"to":194}} {"id":100007780,"name":"NewTimestamp","signature":"func NewTimestamp() *Timestamp","file":"pkg/kubelet/types/types.go","code":"// NewTimestamp returns a Timestamp object using the current time.\nfunc NewTimestamp() *Timestamp {\n\treturn \u0026Timestamp{time.Now()}\n}","line":{"from":40,"to":43}} {"id":100007781,"name":"ConvertToTimestamp","signature":"func ConvertToTimestamp(timeString string) *Timestamp","file":"pkg/kubelet/types/types.go","code":"// ConvertToTimestamp takes a string, parses it using the RFC3339NanoLenient layout,\n// and converts it to a Timestamp object.\nfunc ConvertToTimestamp(timeString string) *Timestamp {\n\tparsed, _ := time.Parse(RFC3339NanoLenient, timeString)\n\treturn \u0026Timestamp{parsed}\n}","line":{"from":45,"to":50}} {"id":100007782,"name":"Get","signature":"func (t *Timestamp) Get() time.Time","file":"pkg/kubelet/types/types.go","code":"// Get returns the time as time.Time.\nfunc (t *Timestamp) Get() time.Time {\n\treturn t.time\n}","line":{"from":52,"to":55}} {"id":100007783,"name":"GetString","signature":"func (t *Timestamp) GetString() string","file":"pkg/kubelet/types/types.go","code":"// GetString returns the time in the string format using the RFC3339NanoFixed\n// layout.\nfunc (t *Timestamp) GetString() string {\n\treturn t.time.Format(RFC3339NanoFixed)\n}","line":{"from":57,"to":61}} {"id":100007784,"name":"Len","signature":"func (s SortedContainerStatuses) Len() int { return len(s) }","file":"pkg/kubelet/types/types.go","code":"func (s SortedContainerStatuses) Len() int { return len(s) }","line":{"from":66,"to":66}} {"id":100007785,"name":"Swap","signature":"func (s SortedContainerStatuses) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","file":"pkg/kubelet/types/types.go","code":"func (s SortedContainerStatuses) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","line":{"from":67,"to":67}} {"id":100007786,"name":"Less","signature":"func (s SortedContainerStatuses) Less(i, j int) bool","file":"pkg/kubelet/types/types.go","code":"func (s SortedContainerStatuses) Less(i, j int) bool {\n\treturn s[i].Name \u003c s[j].Name\n}","line":{"from":69,"to":71}} {"id":100007787,"name":"SortInitContainerStatuses","signature":"func SortInitContainerStatuses(p *v1.Pod, statuses []v1.ContainerStatus)","file":"pkg/kubelet/types/types.go","code":"// SortInitContainerStatuses ensures that statuses are in the order that their\n// init container appears in the pod spec\nfunc SortInitContainerStatuses(p *v1.Pod, statuses []v1.ContainerStatus) {\n\tcontainers := p.Spec.InitContainers\n\tcurrent := 0\n\tfor _, container := range containers {\n\t\tfor j := current; j \u003c len(statuses); j++ {\n\t\t\tif container.Name == statuses[j].Name {\n\t\t\t\tstatuses[current], statuses[j] = statuses[j], statuses[current]\n\t\t\t\tcurrent++\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":73,"to":87}} {"id":100007788,"name":"SortStatusesOfInitContainers","signature":"func SortStatusesOfInitContainers(p *v1.Pod, statusMap map[string]*v1.ContainerStatus) []v1.ContainerStatus","file":"pkg/kubelet/types/types.go","code":"// SortStatusesOfInitContainers returns the statuses of InitContainers of pod p,\n// in the order that they appear in its spec.\nfunc SortStatusesOfInitContainers(p *v1.Pod, statusMap map[string]*v1.ContainerStatus) []v1.ContainerStatus {\n\tcontainers := p.Spec.InitContainers\n\tstatuses := []v1.ContainerStatus{}\n\tfor _, container := range containers {\n\t\tif status, found := statusMap[container.Name]; found {\n\t\t\tstatuses = append(statuses, *status)\n\t\t}\n\t}\n\treturn statuses\n}","line":{"from":89,"to":100}} {"id":100007789,"name":"writeMappingsToFile","signature":"func (m *UsernsManager) writeMappingsToFile(pod types.UID, userNs userNamespace) error","file":"pkg/kubelet/userns/userns_manager.go","code":"// writeMappingsToFile writes the specified user namespace configuration to the pod\n// directory.\nfunc (m *UsernsManager) writeMappingsToFile(pod types.UID, userNs userNamespace) error {\n\tdir := m.kl.GetPodDir(pod)\n\n\tdata, err := json.Marshal(userNs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfstore, err := utilstore.NewFileStore(dir, \u0026utilfs.DefaultFs{})\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := fstore.Write(mappingsFile, data); err != nil {\n\t\treturn err\n\t}\n\n\t// We need to fsync the parent dir so the file is guaranteed to be there.\n\t// fstore guarantees an atomic write, we need durability too.\n\tparentDir, err := os.Open(dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = parentDir.Sync(); err != nil {\n\t\t// Ignore return here, there is already an error reported.\n\t\tparentDir.Close()\n\t\treturn err\n\t}\n\n\treturn parentDir.Close()\n}","line":{"from":87,"to":119}} {"id":100007790,"name":"readMappingsFromFile","signature":"func (m *UsernsManager) readMappingsFromFile(pod types.UID) ([]byte, error)","file":"pkg/kubelet/userns/userns_manager.go","code":"// readMappingsFromFile reads the user namespace configuration from the pod directory.\nfunc (m *UsernsManager) readMappingsFromFile(pod types.UID) ([]byte, error) {\n\tdir := m.kl.GetPodDir(pod)\n\tfstore, err := utilstore.NewFileStore(dir, \u0026utilfs.DefaultFs{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn fstore.Read(mappingsFile)\n}","line":{"from":121,"to":129}} {"id":100007791,"name":"MakeUserNsManager","signature":"func MakeUserNsManager(kl userNsPodsManager) (*UsernsManager, error)","file":"pkg/kubelet/userns/userns_manager.go","code":"func MakeUserNsManager(kl userNsPodsManager) (*UsernsManager, error) {\n\tm := UsernsManager{\n\t\t// Create a bitArray for all the UID space (2^32).\n\t\t// As a by product of that, no index param to bitArray can be out of bounds (index is uint32).\n\t\tused: allocator.NewAllocationMap((math.MaxUint32+1)/userNsLength, \"user namespaces\"),\n\t\tusedBy: make(map[types.UID]uint32),\n\t\tkl: kl,\n\t}\n\t// First block is reserved for the host.\n\tif _, err := m.used.Allocate(0); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// do not bother reading the list of pods if user namespaces are not enabled.\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.UserNamespacesStatelessPodsSupport) {\n\t\treturn \u0026m, nil\n\t}\n\n\tfound, err := kl.ListPodsFromDisk()\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn \u0026m, nil\n\t\t}\n\t\treturn nil, fmt.Errorf(\"user namespace manager can't read pods from disk: %w\", err)\n\n\t}\n\tfor _, podUID := range found {\n\t\tklog.V(5).InfoS(\"reading pod from disk for user namespace\", \"podUID\", podUID)\n\t\tif err := m.recordPodMappings(podUID); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn \u0026m, nil\n}","line":{"from":131,"to":165}} {"id":100007792,"name":"recordPodMappings","signature":"func (m *UsernsManager) recordPodMappings(pod types.UID) error","file":"pkg/kubelet/userns/userns_manager.go","code":"// recordPodMappings registers the range used for the user namespace if the\n// usernsConfFile exists in the pod directory.\nfunc (m *UsernsManager) recordPodMappings(pod types.UID) error {\n\tcontent, err := m.readMappingsFromFile(pod)\n\tif err != nil \u0026\u0026 err != utilstore.ErrKeyNotFound {\n\t\treturn err\n\t}\n\n\t// If no content, it means the pod doesn't have userns. Nothing else to do\n\tif len(content) == 0 {\n\t\treturn nil\n\t}\n\n\t_, err = m.parseUserNsFileAndRecord(pod, content)\n\treturn err\n}","line":{"from":167,"to":182}} {"id":100007793,"name":"isSet","signature":"func (m *UsernsManager) isSet(v uint32) bool","file":"pkg/kubelet/userns/userns_manager.go","code":"// isSet checks if the specified index is already set.\nfunc (m *UsernsManager) isSet(v uint32) bool {\n\tindex := int(v / userNsLength)\n\treturn m.used.Has(index)\n}","line":{"from":184,"to":188}} {"id":100007794,"name":"allocateOne","signature":"func (m *UsernsManager) allocateOne(pod types.UID) (firstID uint32, length uint32, err error)","file":"pkg/kubelet/userns/userns_manager.go","code":"// allocateOne finds a free user namespace and allocate it to the specified pod.\n// The first return value is the first ID in the user namespace, the second returns\n// the length for the user namespace range.\nfunc (m *UsernsManager) allocateOne(pod types.UID) (firstID uint32, length uint32, err error) {\n\tif m.numAllocated \u003e= maxPods {\n\t\treturn 0, 0, fmt.Errorf(\"limit on count of pods with user namespaces exceeded (limit is %v, current pods with userns: %v)\", maxPods, m.numAllocated)\n\t}\n\tm.numAllocated++\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tm.numAllocated--\n\t\t}\n\t}()\n\n\tfirstZero, found, err := m.used.AllocateNext()\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\tif !found {\n\t\treturn 0, 0, fmt.Errorf(\"could not find an empty slot to allocate a user namespace\")\n\t}\n\n\tklog.V(5).InfoS(\"new pod user namespace allocation\", \"podUID\", pod)\n\n\tfirstID = uint32(firstZero * userNsLength)\n\tm.usedBy[pod] = firstID\n\treturn firstID, userNsLength, nil\n}","line":{"from":190,"to":217}} {"id":100007795,"name":"record","signature":"func (m *UsernsManager) record(pod types.UID, from, length uint32) (err error)","file":"pkg/kubelet/userns/userns_manager.go","code":"// record stores the user namespace [from; from+length] to the specified pod.\nfunc (m *UsernsManager) record(pod types.UID, from, length uint32) (err error) {\n\tif length != userNsLength {\n\t\treturn fmt.Errorf(\"wrong user namespace length %v\", length)\n\t}\n\tif from%userNsLength != 0 {\n\t\treturn fmt.Errorf(\"wrong user namespace offset specified %v\", from)\n\t}\n\tprevFrom, found := m.usedBy[pod]\n\tif found \u0026\u0026 prevFrom != from {\n\t\treturn fmt.Errorf(\"different user namespace range already used by pod %q\", pod)\n\t}\n\tindex := int(from / userNsLength)\n\t// if the pod wasn't found then verify the range is free.\n\tif !found \u0026\u0026 m.used.Has(index) {\n\t\treturn fmt.Errorf(\"range picked for pod %q already taken\", pod)\n\t}\n\t// The pod is already registered, nothing to do.\n\tif found \u0026\u0026 prevFrom == from {\n\t\treturn nil\n\t}\n\tif m.numAllocated \u003e= maxPods {\n\t\treturn fmt.Errorf(\"limit on count of pods with user namespaces exceeded (limit is %v, current pods with userns: %v)\", maxPods, m.numAllocated)\n\t}\n\tm.numAllocated++\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tm.numAllocated--\n\t\t}\n\t}()\n\n\tklog.V(5).InfoS(\"new pod user namespace allocation\", \"podUID\", pod)\n\n\t// \"from\" is a ID (UID/GID), set the corresponding userns of size\n\t// userNsLength in the bit-array.\n\tm.used.Allocate(index)\n\tm.usedBy[pod] = from\n\treturn nil\n}","line":{"from":219,"to":257}} {"id":100007796,"name":"Release","signature":"func (m *UsernsManager) Release(podUID types.UID)","file":"pkg/kubelet/userns/userns_manager.go","code":"// Release releases the user namespace allocated to the specified pod.\nfunc (m *UsernsManager) Release(podUID types.UID) {\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.UserNamespacesStatelessPodsSupport) {\n\t\treturn\n\t}\n\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\n\tm.releaseWithLock(podUID)\n}","line":{"from":259,"to":269}} {"id":100007797,"name":"releaseWithLock","signature":"func (m *UsernsManager) releaseWithLock(pod types.UID)","file":"pkg/kubelet/userns/userns_manager.go","code":"func (m *UsernsManager) releaseWithLock(pod types.UID) {\n\tv, ok := m.usedBy[pod]\n\tif !ok {\n\t\tklog.V(5).InfoS(\"pod user namespace allocation not present\", \"podUID\", pod)\n\t\treturn\n\t}\n\tdelete(m.usedBy, pod)\n\n\tklog.V(5).InfoS(\"releasing pod user namespace allocation\", \"podUID\", pod)\n\tm.numAllocated--\n\tm.removed++\n\n\t_ = os.Remove(filepath.Join(m.kl.GetPodDir(pod), mappingsFile))\n\n\tif m.removed%mapReInitializeThreshold == 0 {\n\t\tn := make(map[types.UID]uint32)\n\t\tfor k, v := range m.usedBy {\n\t\t\tn[k] = v\n\t\t}\n\t\tm.usedBy = n\n\t\tm.removed = 0\n\t}\n\tm.used.Release(int(v / userNsLength))\n}","line":{"from":271,"to":294}} {"id":100007798,"name":"parseUserNsFileAndRecord","signature":"func (m *UsernsManager) parseUserNsFileAndRecord(pod types.UID, content []byte) (userNs userNamespace, err error)","file":"pkg/kubelet/userns/userns_manager.go","code":"func (m *UsernsManager) parseUserNsFileAndRecord(pod types.UID, content []byte) (userNs userNamespace, err error) {\n\tif err = json.Unmarshal([]byte(content), \u0026userNs); err != nil {\n\t\terr = fmt.Errorf(\"can't parse file: %w\", err)\n\t\treturn\n\t}\n\n\tif len(userNs.UIDMappings) != 1 {\n\t\terr = fmt.Errorf(\"invalid user namespace configuration: no more than one mapping allowed.\")\n\t\treturn\n\t}\n\n\tif len(userNs.UIDMappings) != len(userNs.GIDMappings) {\n\t\terr = fmt.Errorf(\"invalid user namespace configuration: GID and UID mappings should be identical.\")\n\t\treturn\n\t}\n\n\tif userNs.UIDMappings[0] != userNs.GIDMappings[0] {\n\t\terr = fmt.Errorf(\"invalid user namespace configuration: GID and UID mapping should be identical\")\n\t\treturn\n\t}\n\n\t// We don't produce configs without root mapped and some runtimes assume it is mapped.\n\t// Validate the file has something we produced and can digest.\n\tif userNs.UIDMappings[0].ContainerId != 0 {\n\t\terr = fmt.Errorf(\"invalid user namespace configuration: UID 0 must be mapped\")\n\t\treturn\n\t}\n\n\tif userNs.GIDMappings[0].ContainerId != 0 {\n\t\terr = fmt.Errorf(\"invalid user namespace configuration: GID 0 must be mapped\")\n\t\treturn\n\t}\n\n\thostId := userNs.UIDMappings[0].HostId\n\tlength := userNs.UIDMappings[0].Length\n\n\terr = m.record(pod, hostId, length)\n\treturn\n}","line":{"from":296,"to":334}} {"id":100007799,"name":"createUserNs","signature":"func (m *UsernsManager) createUserNs(pod *v1.Pod) (userNs userNamespace, err error)","file":"pkg/kubelet/userns/userns_manager.go","code":"func (m *UsernsManager) createUserNs(pod *v1.Pod) (userNs userNamespace, err error) {\n\tfirstID, length, err := m.allocateOne(pod.UID)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tm.releaseWithLock(pod.UID)\n\t\t}\n\t}()\n\n\tuserNs = userNamespace{\n\t\tUIDMappings: []idMapping{\n\t\t\t{\n\t\t\t\tContainerId: 0,\n\t\t\t\tHostId: firstID,\n\t\t\t\tLength: length,\n\t\t\t},\n\t\t},\n\t\tGIDMappings: []idMapping{\n\t\t\t{\n\t\t\t\tContainerId: 0,\n\t\t\t\tHostId: firstID,\n\t\t\t\tLength: length,\n\t\t\t},\n\t\t},\n\t}\n\n\treturn userNs, m.writeMappingsToFile(pod.UID, userNs)\n}","line":{"from":336,"to":366}} {"id":100007800,"name":"GetOrCreateUserNamespaceMappings","signature":"func (m *UsernsManager) GetOrCreateUserNamespaceMappings(pod *v1.Pod) (*runtimeapi.UserNamespace, error)","file":"pkg/kubelet/userns/userns_manager.go","code":"// GetOrCreateUserNamespaceMappings returns the configuration for the sandbox user namespace\nfunc (m *UsernsManager) GetOrCreateUserNamespaceMappings(pod *v1.Pod) (*runtimeapi.UserNamespace, error) {\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.UserNamespacesStatelessPodsSupport) {\n\t\treturn nil, nil\n\t}\n\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\n\tif pod.Spec.HostUsers == nil || *pod.Spec.HostUsers == true {\n\t\treturn \u0026runtimeapi.UserNamespace{\n\t\t\tMode: runtimeapi.NamespaceMode_NODE,\n\t\t}, nil\n\t}\n\n\tcontent, err := m.readMappingsFromFile(pod.UID)\n\tif err != nil \u0026\u0026 err != utilstore.ErrKeyNotFound {\n\t\treturn nil, err\n\t}\n\n\tvar userNs userNamespace\n\tif string(content) != \"\" {\n\t\tuserNs, err = m.parseUserNsFileAndRecord(pod.UID, content)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tuserNs, err = m.createUserNs(pod)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tvar uids []*runtimeapi.IDMapping\n\tvar gids []*runtimeapi.IDMapping\n\n\tfor _, u := range userNs.UIDMappings {\n\t\tuids = append(uids, \u0026runtimeapi.IDMapping{\n\t\t\tHostId: u.HostId,\n\t\t\tContainerId: u.ContainerId,\n\t\t\tLength: u.Length,\n\t\t})\n\t}\n\tfor _, g := range userNs.GIDMappings {\n\t\tgids = append(gids, \u0026runtimeapi.IDMapping{\n\t\t\tHostId: g.HostId,\n\t\t\tContainerId: g.ContainerId,\n\t\t\tLength: g.Length,\n\t\t})\n\t}\n\n\treturn \u0026runtimeapi.UserNamespace{\n\t\tMode: runtimeapi.NamespaceMode_POD,\n\t\tUids: uids,\n\t\tGids: gids,\n\t}, nil\n}","line":{"from":368,"to":424}} {"id":100007801,"name":"CleanupOrphanedPodUsernsAllocations","signature":"func (m *UsernsManager) CleanupOrphanedPodUsernsAllocations(pods []*v1.Pod, runningPods []*kubecontainer.Pod) error","file":"pkg/kubelet/userns/userns_manager.go","code":"// CleanupOrphanedPodUsernsAllocations reconciliates the state of user namespace\n// allocations with the pods actually running. It frees any user namespace\n// allocation for orphaned pods.\nfunc (m *UsernsManager) CleanupOrphanedPodUsernsAllocations(pods []*v1.Pod, runningPods []*kubecontainer.Pod) error {\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.UserNamespacesStatelessPodsSupport) {\n\t\treturn nil\n\t}\n\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\n\tallPods := sets.NewString()\n\tfor _, pod := range pods {\n\t\tallPods.Insert(string(pod.UID))\n\t}\n\tfor _, pod := range runningPods {\n\t\tallPods.Insert(string(pod.ID))\n\t}\n\n\tallFound := sets.NewString()\n\tfound, err := m.kl.ListPodsFromDisk()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, podUID := range found {\n\t\tallFound.Insert(string(podUID))\n\t}\n\n\t// Lets remove all the pods \"found\" that are not known.\n\tfor _, podUID := range found {\n\t\tif allPods.Has(string(podUID)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tklog.V(5).InfoS(\"Clean up orphaned pod user namespace possible allocation\", \"podUID\", podUID)\n\t\tm.releaseWithLock(podUID)\n\t}\n\n\t// Lets remove any existing allocation for a pod that is not \"found\".\n\tfor podUID := range m.usedBy {\n\t\tif allFound.Has(string(podUID)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tklog.V(5).InfoS(\"Clean up orphaned pod user namespace possible allocation\", \"podUID\", podUID)\n\t\tm.releaseWithLock(podUID)\n\t}\n\n\treturn nil\n}","line":{"from":426,"to":476}} {"id":100007802,"name":"GetBootTime","signature":"func GetBootTime() (time.Time, error)","file":"pkg/kubelet/util/boottime_util_darwin.go","code":"// GetBootTime returns the time at which the machine was started, truncated to the nearest second\nfunc GetBootTime() (time.Time, error) {\n\toutput, err := unix.SysctlRaw(\"kern.boottime\")\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\tvar timeval syscall.Timeval\n\tif len(output) != int(unsafe.Sizeof(timeval)) {\n\t\treturn time.Time{}, fmt.Errorf(\"unexpected output when calling syscall kern.bootime. Expected len(output) to be %v, but got %v\",\n\t\t\tint(unsafe.Sizeof(timeval)), len(output))\n\t}\n\ttimeval = *(*syscall.Timeval)(unsafe.Pointer(\u0026output[0]))\n\tsec, nsec := timeval.Unix()\n\treturn time.Unix(sec, nsec).Truncate(time.Second), nil\n}","line":{"from":31,"to":45}} {"id":100007803,"name":"GetBootTime","signature":"func GetBootTime() (time.Time, error)","file":"pkg/kubelet/util/boottime_util_freebsd.go","code":"// GetBootTime returns the time at which the machine was started, truncated to the nearest second\nfunc GetBootTime() (time.Time, error) {\n\tcurrentTime := time.Now()\n\tts := \u0026unix.Timeval{}\n\t_, _, e1 := unix.Syscall(uintptr(unix.SYS_CLOCK_GETTIME), uintptr(unix.CLOCK_UPTIME), uintptr(unsafe.Pointer(ts)), 0)\n\tif e1 != 0 {\n\t\treturn time.Time{}, fmt.Errorf(\"error getting system uptime\")\n\t}\n\n\treturn currentTime.Add(-time.Duration(ts.Sec) * time.Second).Truncate(time.Second), nil\n}","line":{"from":30,"to":40}} {"id":100007804,"name":"GetBootTime","signature":"func GetBootTime() (time.Time, error)","file":"pkg/kubelet/util/boottime_util_linux.go","code":"// GetBootTime returns the time at which the machine was started, truncated to the nearest second\nfunc GetBootTime() (time.Time, error) {\n\tcurrentTime := time.Now()\n\tvar info unix.Sysinfo_t\n\tif err := unix.Sysinfo(\u0026info); err != nil {\n\t\treturn time.Time{}, fmt.Errorf(\"error getting system uptime: %s\", err)\n\t}\n\treturn currentTime.Add(-time.Duration(info.Uptime) * time.Second).Truncate(time.Second), nil\n}","line":{"from":29,"to":37}} {"id":100007805,"name":"NewObjectCache","signature":"func NewObjectCache(f func() (interface{}, error), ttl time.Duration) *ObjectCache","file":"pkg/kubelet/util/cache/object_cache.go","code":"// NewObjectCache creates ObjectCache with an updater.\n// updater returns an object to cache.\nfunc NewObjectCache(f func() (interface{}, error), ttl time.Duration) *ObjectCache {\n\treturn \u0026ObjectCache{\n\t\tupdater: f,\n\t\tcache: expirationcache.NewTTLStore(stringKeyFunc, ttl),\n\t}\n}","line":{"from":40,"to":47}} {"id":100007806,"name":"stringKeyFunc","signature":"func stringKeyFunc(obj interface{}) (string, error)","file":"pkg/kubelet/util/cache/object_cache.go","code":"// stringKeyFunc is a string as cache key function\nfunc stringKeyFunc(obj interface{}) (string, error) {\n\tkey := obj.(objectEntry).key\n\treturn key, nil\n}","line":{"from":49,"to":53}} {"id":100007807,"name":"Get","signature":"func (c *ObjectCache) Get(key string) (interface{}, error)","file":"pkg/kubelet/util/cache/object_cache.go","code":"// Get gets cached objectEntry by using a unique string as the key.\nfunc (c *ObjectCache) Get(key string) (interface{}, error) {\n\tvalue, ok, err := c.cache.Get(objectEntry{key: key})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !ok {\n\t\tobj, err := c.updater()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = c.cache.Add(objectEntry{\n\t\t\tkey: key,\n\t\t\tobj: obj,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn obj, nil\n\t}\n\treturn value.(objectEntry).obj, nil\n}","line":{"from":55,"to":76}} {"id":100007808,"name":"Add","signature":"func (c *ObjectCache) Add(key string, obj interface{}) error","file":"pkg/kubelet/util/cache/object_cache.go","code":"// Add adds objectEntry by using a unique string as the key.\nfunc (c *ObjectCache) Add(key string, obj interface{}) error {\n\treturn c.cache.Add(objectEntry{key: key, obj: obj})\n}","line":{"from":78,"to":81}} {"id":100007809,"name":"Pod","signature":"func Pod(pod *v1.Pod) string","file":"pkg/kubelet/util/format/pod.go","code":"// Pod returns a string representing a pod in a consistent human readable format,\n// with pod UID as part of the string.\nfunc Pod(pod *v1.Pod) string {\n\tif pod == nil {\n\t\treturn \"\u003cnil\u003e\"\n\t}\n\treturn PodDesc(pod.Name, pod.Namespace, pod.UID)\n}","line":{"from":26,"to":33}} {"id":100007810,"name":"PodDesc","signature":"func PodDesc(podName, podNamespace string, podUID types.UID) string","file":"pkg/kubelet/util/format/pod.go","code":"// PodDesc returns a string representing a pod in a consistent human readable format,\n// with pod UID as part of the string.\nfunc PodDesc(podName, podNamespace string, podUID types.UID) string {\n\t// Use underscore as the delimiter because it is not allowed in pod name\n\t// (DNS subdomain format), while allowed in the container name format.\n\treturn fmt.Sprintf(\"%s_%s(%s)\", podName, podNamespace, podUID)\n}","line":{"from":35,"to":41}} {"id":100007811,"name":"LimitWriter","signature":"func LimitWriter(w io.Writer, n int64) io.Writer { return \u0026LimitedWriter{w, n} }","file":"pkg/kubelet/util/ioutils/ioutils.go","code":"// LimitWriter is a copy of the standard library ioutils.LimitReader,\n// applied to the writer interface.\n// LimitWriter returns a Writer that writes to w\n// but stops with EOF after n bytes.\n// The underlying implementation is a *LimitedWriter.\nfunc LimitWriter(w io.Writer, n int64) io.Writer { return \u0026LimitedWriter{w, n} }","line":{"from":21,"to":26}} {"id":100007812,"name":"Write","signature":"func (l *LimitedWriter) Write(p []byte) (n int, err error)","file":"pkg/kubelet/util/ioutils/ioutils.go","code":"func (l *LimitedWriter) Write(p []byte) (n int, err error) {\n\tif l.N \u003c= 0 {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\ttruncated := false\n\tif int64(len(p)) \u003e l.N {\n\t\tp = p[0:l.N]\n\t\ttruncated = true\n\t}\n\tn, err = l.W.Write(p)\n\tl.N -= int64(n)\n\tif err == nil \u0026\u0026 truncated {\n\t\terr = io.ErrShortWrite\n\t}\n\treturn\n}","line":{"from":37,"to":52}} {"id":100007813,"name":"NewObjectStore","signature":"func NewObjectStore(getObject GetObjectFunc, clock clock.Clock, getTTL GetObjectTTLFunc, ttl time.Duration) Store","file":"pkg/kubelet/util/manager/cache_based_manager.go","code":"// NewObjectStore returns a new ttl-based instance of Store interface.\nfunc NewObjectStore(getObject GetObjectFunc, clock clock.Clock, getTTL GetObjectTTLFunc, ttl time.Duration) Store {\n\treturn \u0026objectStore{\n\t\tgetObject: getObject,\n\t\tclock: clock,\n\t\titems: make(map[objectKey]*objectStoreItem),\n\t\tdefaultTTL: ttl,\n\t\tgetTTL: getTTL,\n\t}\n}","line":{"from":75,"to":84}} {"id":100007814,"name":"isObjectOlder","signature":"func isObjectOlder(newObject, oldObject runtime.Object) bool","file":"pkg/kubelet/util/manager/cache_based_manager.go","code":"func isObjectOlder(newObject, oldObject runtime.Object) bool {\n\tif newObject == nil || oldObject == nil {\n\t\treturn false\n\t}\n\tnewVersion, _ := storage.APIObjectVersioner{}.ObjectResourceVersion(newObject)\n\toldVersion, _ := storage.APIObjectVersioner{}.ObjectResourceVersion(oldObject)\n\treturn newVersion \u003c oldVersion\n}","line":{"from":86,"to":93}} {"id":100007815,"name":"AddReference","signature":"func (s *objectStore) AddReference(namespace, name string)","file":"pkg/kubelet/util/manager/cache_based_manager.go","code":"func (s *objectStore) AddReference(namespace, name string) {\n\tkey := objectKey{namespace: namespace, name: name}\n\n\t// AddReference is called from RegisterPod, thus it needs to be efficient.\n\t// Thus Add() is only increasing refCount and generation of a given object.\n\t// Then Get() is responsible for fetching if needed.\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\titem, exists := s.items[key]\n\tif !exists {\n\t\titem = \u0026objectStoreItem{\n\t\t\trefCount: 0,\n\t\t\tdata: \u0026objectData{},\n\t\t}\n\t\ts.items[key] = item\n\t}\n\n\titem.refCount++\n\t// This will trigger fetch on the next Get() operation.\n\titem.data = nil\n}","line":{"from":95,"to":115}} {"id":100007816,"name":"DeleteReference","signature":"func (s *objectStore) DeleteReference(namespace, name string)","file":"pkg/kubelet/util/manager/cache_based_manager.go","code":"func (s *objectStore) DeleteReference(namespace, name string) {\n\tkey := objectKey{namespace: namespace, name: name}\n\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\tif item, ok := s.items[key]; ok {\n\t\titem.refCount--\n\t\tif item.refCount == 0 {\n\t\t\tdelete(s.items, key)\n\t\t}\n\t}\n}","line":{"from":117,"to":128}} {"id":100007817,"name":"GetObjectTTLFromNodeFunc","signature":"func GetObjectTTLFromNodeFunc(getNode func() (*v1.Node, error)) GetObjectTTLFunc","file":"pkg/kubelet/util/manager/cache_based_manager.go","code":"// GetObjectTTLFromNodeFunc returns a function that returns TTL value\n// from a given Node object.\nfunc GetObjectTTLFromNodeFunc(getNode func() (*v1.Node, error)) GetObjectTTLFunc {\n\treturn func() (time.Duration, bool) {\n\t\tnode, err := getNode()\n\t\tif err != nil {\n\t\t\treturn time.Duration(0), false\n\t\t}\n\t\tif node != nil \u0026\u0026 node.Annotations != nil {\n\t\t\tif value, ok := node.Annotations[v1.ObjectTTLAnnotationKey]; ok {\n\t\t\t\tif intValue, err := strconv.Atoi(value); err == nil {\n\t\t\t\t\treturn time.Duration(intValue) * time.Second, true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn time.Duration(0), false\n\t}\n}","line":{"from":130,"to":147}} {"id":100007818,"name":"isObjectFresh","signature":"func (s *objectStore) isObjectFresh(data *objectData) bool","file":"pkg/kubelet/util/manager/cache_based_manager.go","code":"func (s *objectStore) isObjectFresh(data *objectData) bool {\n\tobjectTTL := s.defaultTTL\n\tif ttl, ok := s.getTTL(); ok {\n\t\tobjectTTL = ttl\n\t}\n\treturn s.clock.Now().Before(data.lastUpdateTime.Add(objectTTL))\n}","line":{"from":149,"to":155}} {"id":100007819,"name":"Get","signature":"func (s *objectStore) Get(namespace, name string) (runtime.Object, error)","file":"pkg/kubelet/util/manager/cache_based_manager.go","code":"func (s *objectStore) Get(namespace, name string) (runtime.Object, error) {\n\tkey := objectKey{namespace: namespace, name: name}\n\n\tdata := func() *objectData {\n\t\ts.lock.Lock()\n\t\tdefer s.lock.Unlock()\n\t\titem, exists := s.items[key]\n\t\tif !exists {\n\t\t\treturn nil\n\t\t}\n\t\tif item.data == nil {\n\t\t\titem.data = \u0026objectData{}\n\t\t}\n\t\treturn item.data\n\t}()\n\tif data == nil {\n\t\treturn nil, fmt.Errorf(\"object %q/%q not registered\", namespace, name)\n\t}\n\n\t// After updating data in objectStore, lock the data, fetch object if\n\t// needed and return data.\n\tdata.Lock()\n\tdefer data.Unlock()\n\tif data.err != nil || !s.isObjectFresh(data) {\n\t\topts := metav1.GetOptions{}\n\t\tif data.object != nil \u0026\u0026 data.err == nil {\n\t\t\t// This is just a periodic refresh of an object we successfully fetched previously.\n\t\t\t// In this case, server data from apiserver cache to reduce the load on both\n\t\t\t// etcd and apiserver (the cache is eventually consistent).\n\t\t\tutil.FromApiserverCache(\u0026opts)\n\t\t}\n\n\t\tobject, err := s.getObject(namespace, name, opts)\n\t\tif err != nil \u0026\u0026 !apierrors.IsNotFound(err) \u0026\u0026 data.object == nil \u0026\u0026 data.err == nil {\n\t\t\t// Couldn't fetch the latest object, but there is no cached data to return.\n\t\t\t// Return the fetch result instead.\n\t\t\treturn object, err\n\t\t}\n\t\tif (err == nil \u0026\u0026 !isObjectOlder(object, data.object)) || apierrors.IsNotFound(err) {\n\t\t\t// If the fetch succeeded with a newer version of the object, or if the\n\t\t\t// object could not be found in the apiserver, update the cached data to\n\t\t\t// reflect the current status.\n\t\t\tdata.object = object\n\t\t\tdata.err = err\n\t\t\tdata.lastUpdateTime = s.clock.Now()\n\t\t}\n\t}\n\treturn data.object, data.err\n}","line":{"from":157,"to":205}} {"id":100007820,"name":"GetObject","signature":"func (c *cacheBasedManager) GetObject(namespace, name string) (runtime.Object, error)","file":"pkg/kubelet/util/manager/cache_based_manager.go","code":"func (c *cacheBasedManager) GetObject(namespace, name string) (runtime.Object, error) {\n\treturn c.objectStore.Get(namespace, name)\n}","line":{"from":219,"to":221}} {"id":100007821,"name":"RegisterPod","signature":"func (c *cacheBasedManager) RegisterPod(pod *v1.Pod)","file":"pkg/kubelet/util/manager/cache_based_manager.go","code":"func (c *cacheBasedManager) RegisterPod(pod *v1.Pod) {\n\tnames := c.getReferencedObjects(pod)\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tfor name := range names {\n\t\tc.objectStore.AddReference(pod.Namespace, name)\n\t}\n\tvar prev *v1.Pod\n\tkey := objectKey{namespace: pod.Namespace, name: pod.Name, uid: pod.UID}\n\tprev = c.registeredPods[key]\n\tc.registeredPods[key] = pod\n\tif prev != nil {\n\t\tfor name := range c.getReferencedObjects(prev) {\n\t\t\t// On an update, the .Add() call above will have re-incremented the\n\t\t\t// ref count of any existing object, so any objects that are in both\n\t\t\t// names and prev need to have their ref counts decremented. Any that\n\t\t\t// are only in prev need to be completely removed. This unconditional\n\t\t\t// call takes care of both cases.\n\t\t\tc.objectStore.DeleteReference(prev.Namespace, name)\n\t\t}\n\t}\n}","line":{"from":223,"to":244}} {"id":100007822,"name":"UnregisterPod","signature":"func (c *cacheBasedManager) UnregisterPod(pod *v1.Pod)","file":"pkg/kubelet/util/manager/cache_based_manager.go","code":"func (c *cacheBasedManager) UnregisterPod(pod *v1.Pod) {\n\tvar prev *v1.Pod\n\tkey := objectKey{namespace: pod.Namespace, name: pod.Name, uid: pod.UID}\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tprev = c.registeredPods[key]\n\tdelete(c.registeredPods, key)\n\tif prev != nil {\n\t\tfor name := range c.getReferencedObjects(prev) {\n\t\t\tc.objectStore.DeleteReference(prev.Namespace, name)\n\t\t}\n\t}\n}","line":{"from":246,"to":258}} {"id":100007823,"name":"NewCacheBasedManager","signature":"func NewCacheBasedManager(objectStore Store, getReferencedObjects func(*v1.Pod) sets.String) Manager","file":"pkg/kubelet/util/manager/cache_based_manager.go","code":"// NewCacheBasedManager creates a manager that keeps a cache of all objects\n// necessary for registered pods.\n// It implements the following logic:\n// - whenever a pod is created or updated, the cached versions of all objects\n// is referencing are invalidated\n// - every GetObject() call tries to fetch the value from local cache; if it is\n// not there, invalidated or too old, we fetch it from apiserver and refresh the\n// value in cache; otherwise it is just fetched from cache\nfunc NewCacheBasedManager(objectStore Store, getReferencedObjects func(*v1.Pod) sets.String) Manager {\n\treturn \u0026cacheBasedManager{\n\t\tobjectStore: objectStore,\n\t\tgetReferencedObjects: getReferencedObjects,\n\t\tregisteredPods: make(map[objectKey]*v1.Pod),\n\t}\n}","line":{"from":260,"to":274}} {"id":100007824,"name":"stop","signature":"func (i *objectCacheItem) stop() bool","file":"pkg/kubelet/util/manager/watch_based_manager.go","code":"func (i *objectCacheItem) stop() bool {\n\ti.lock.Lock()\n\tdefer i.lock.Unlock()\n\treturn i.stopThreadUnsafe()\n}","line":{"from":65,"to":69}} {"id":100007825,"name":"stopThreadUnsafe","signature":"func (i *objectCacheItem) stopThreadUnsafe() bool","file":"pkg/kubelet/util/manager/watch_based_manager.go","code":"func (i *objectCacheItem) stopThreadUnsafe() bool {\n\tif i.stopped {\n\t\treturn false\n\t}\n\ti.stopped = true\n\tclose(i.stopCh)\n\tif !i.immutable {\n\t\ti.store.unsetInitialized()\n\t}\n\treturn true\n}","line":{"from":71,"to":81}} {"id":100007826,"name":"setLastAccessTime","signature":"func (i *objectCacheItem) setLastAccessTime(time time.Time)","file":"pkg/kubelet/util/manager/watch_based_manager.go","code":"func (i *objectCacheItem) setLastAccessTime(time time.Time) {\n\ti.lock.Lock()\n\tdefer i.lock.Unlock()\n\ti.lastAccessTime = time\n}","line":{"from":83,"to":87}} {"id":100007827,"name":"setImmutable","signature":"func (i *objectCacheItem) setImmutable()","file":"pkg/kubelet/util/manager/watch_based_manager.go","code":"func (i *objectCacheItem) setImmutable() {\n\ti.lock.Lock()\n\tdefer i.lock.Unlock()\n\ti.immutable = true\n}","line":{"from":89,"to":93}} {"id":100007828,"name":"stopIfIdle","signature":"func (i *objectCacheItem) stopIfIdle(now time.Time, maxIdleTime time.Duration) bool","file":"pkg/kubelet/util/manager/watch_based_manager.go","code":"func (i *objectCacheItem) stopIfIdle(now time.Time, maxIdleTime time.Duration) bool {\n\ti.lock.Lock()\n\tdefer i.lock.Unlock()\n\t// Ensure that we don't try to stop not yet initialized reflector.\n\t// In case of overloaded kube-apiserver, if the list request is\n\t// already being processed, all the work would lost and would have\n\t// to be retried.\n\tif !i.stopped \u0026\u0026 i.store.hasSynced() \u0026\u0026 now.After(i.lastAccessTime.Add(maxIdleTime)) {\n\t\treturn i.stopThreadUnsafe()\n\t}\n\treturn false\n}","line":{"from":95,"to":106}} {"id":100007829,"name":"restartReflectorIfNeeded","signature":"func (i *objectCacheItem) restartReflectorIfNeeded()","file":"pkg/kubelet/util/manager/watch_based_manager.go","code":"func (i *objectCacheItem) restartReflectorIfNeeded() {\n\ti.lock.Lock()\n\tdefer i.lock.Unlock()\n\tif i.immutable || !i.stopped {\n\t\treturn\n\t}\n\ti.stopCh = make(chan struct{})\n\ti.stopped = false\n\tgo i.startReflector()\n}","line":{"from":108,"to":117}} {"id":100007830,"name":"startReflector","signature":"func (i *objectCacheItem) startReflector()","file":"pkg/kubelet/util/manager/watch_based_manager.go","code":"func (i *objectCacheItem) startReflector() {\n\ti.waitGroup.Wait()\n\ti.waitGroup.Add(1)\n\tdefer i.waitGroup.Done()\n\ti.reflector.Run(i.stopCh)\n}","line":{"from":119,"to":124}} {"id":100007831,"name":"Replace","signature":"func (c *cacheStore) Replace(list []interface{}, resourceVersion string) error","file":"pkg/kubelet/util/manager/watch_based_manager.go","code":"func (c *cacheStore) Replace(list []interface{}, resourceVersion string) error {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\terr := c.Store.Replace(list, resourceVersion)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.initialized = true\n\treturn nil\n}","line":{"from":133,"to":142}} {"id":100007832,"name":"hasSynced","signature":"func (c *cacheStore) hasSynced() bool","file":"pkg/kubelet/util/manager/watch_based_manager.go","code":"func (c *cacheStore) hasSynced() bool {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\treturn c.initialized\n}","line":{"from":144,"to":148}} {"id":100007833,"name":"unsetInitialized","signature":"func (c *cacheStore) unsetInitialized()","file":"pkg/kubelet/util/manager/watch_based_manager.go","code":"func (c *cacheStore) unsetInitialized() {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tc.initialized = false\n}","line":{"from":150,"to":154}} {"id":100007834,"name":"NewObjectCache","signature":"func NewObjectCache(","file":"pkg/kubelet/util/manager/watch_based_manager.go","code":"// NewObjectCache returns a new watch-based instance of Store interface.\nfunc NewObjectCache(\n\tlistObject listObjectFunc,\n\twatchObject watchObjectFunc,\n\tnewObject newObjectFunc,\n\tisImmutable isImmutableFunc,\n\tgroupResource schema.GroupResource,\n\tclock clock.Clock,\n\tmaxIdleTime time.Duration,\n\tstopCh \u003c-chan struct{}) Store {\n\n\tif maxIdleTime \u003c minIdleTime {\n\t\tmaxIdleTime = minIdleTime\n\t}\n\n\tstore := \u0026objectCache{\n\t\tlistObject: listObject,\n\t\twatchObject: watchObject,\n\t\tnewObject: newObject,\n\t\tisImmutable: isImmutable,\n\t\tgroupResource: groupResource,\n\t\tclock: clock,\n\t\tmaxIdleTime: maxIdleTime,\n\t\titems: make(map[objectKey]*objectCacheItem),\n\t}\n\n\tgo wait.Until(store.startRecycleIdleWatch, time.Minute, stopCh)\n\tgo store.shutdownWhenStopped(stopCh)\n\treturn store\n}","line":{"from":174,"to":203}} {"id":100007835,"name":"newStore","signature":"func (c *objectCache) newStore() *cacheStore","file":"pkg/kubelet/util/manager/watch_based_manager.go","code":"func (c *objectCache) newStore() *cacheStore {\n\t// TODO: We may consider created a dedicated store keeping just a single\n\t// item, instead of using a generic store implementation for this purpose.\n\t// However, simple benchmarks show that memory overhead in that case is\n\t// decrease from ~600B to ~300B per object. So we are not optimizing it\n\t// until we will see a good reason for that.\n\tstore := cache.NewStore(cache.MetaNamespaceKeyFunc)\n\treturn \u0026cacheStore{store, sync.Mutex{}, false}\n}","line":{"from":205,"to":213}} {"id":100007836,"name":"newReflectorLocked","signature":"func (c *objectCache) newReflectorLocked(namespace, name string) *objectCacheItem","file":"pkg/kubelet/util/manager/watch_based_manager.go","code":"func (c *objectCache) newReflectorLocked(namespace, name string) *objectCacheItem {\n\tfieldSelector := fields.Set{\"metadata.name\": name}.AsSelector().String()\n\tlistFunc := func(options metav1.ListOptions) (runtime.Object, error) {\n\t\toptions.FieldSelector = fieldSelector\n\t\treturn c.listObject(namespace, options)\n\t}\n\twatchFunc := func(options metav1.ListOptions) (watch.Interface, error) {\n\t\toptions.FieldSelector = fieldSelector\n\t\treturn c.watchObject(namespace, options)\n\t}\n\tstore := c.newStore()\n\treflector := cache.NewNamedReflector(\n\t\tfmt.Sprintf(\"object-%q/%q\", namespace, name),\n\t\t\u0026cache.ListWatch{ListFunc: listFunc, WatchFunc: watchFunc},\n\t\tc.newObject(),\n\t\tstore,\n\t\t0,\n\t)\n\titem := \u0026objectCacheItem{\n\t\trefCount: 0,\n\t\tstore: store,\n\t\treflector: reflector,\n\t\thasSynced: func() (bool, error) { return store.hasSynced(), nil },\n\t\tstopCh: make(chan struct{}),\n\t}\n\n\t// Don't start reflector if Kubelet is already shutting down.\n\tif !c.stopped {\n\t\tgo item.startReflector()\n\t}\n\treturn item\n}","line":{"from":215,"to":246}} {"id":100007837,"name":"AddReference","signature":"func (c *objectCache) AddReference(namespace, name string)","file":"pkg/kubelet/util/manager/watch_based_manager.go","code":"func (c *objectCache) AddReference(namespace, name string) {\n\tkey := objectKey{namespace: namespace, name: name}\n\n\t// AddReference is called from RegisterPod thus it needs to be efficient.\n\t// Thus, it is only increasing refCount and in case of first registration\n\t// of a given object it starts corresponding reflector.\n\t// It's responsibility of the first Get operation to wait until the\n\t// reflector propagated the store.\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\titem, exists := c.items[key]\n\tif !exists {\n\t\titem = c.newReflectorLocked(namespace, name)\n\t\tc.items[key] = item\n\t}\n\titem.refCount++\n}","line":{"from":248,"to":264}} {"id":100007838,"name":"DeleteReference","signature":"func (c *objectCache) DeleteReference(namespace, name string)","file":"pkg/kubelet/util/manager/watch_based_manager.go","code":"func (c *objectCache) DeleteReference(namespace, name string) {\n\tkey := objectKey{namespace: namespace, name: name}\n\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tif item, ok := c.items[key]; ok {\n\t\titem.refCount--\n\t\tif item.refCount == 0 {\n\t\t\t// Stop the underlying reflector.\n\t\t\titem.stop()\n\t\t\tdelete(c.items, key)\n\t\t}\n\t}\n}","line":{"from":266,"to":279}} {"id":100007839,"name":"key","signature":"func (c *objectCache) key(namespace, name string) string","file":"pkg/kubelet/util/manager/watch_based_manager.go","code":"// key returns key of an object with a given name and namespace.\n// This has to be in-sync with cache.MetaNamespaceKeyFunc.\nfunc (c *objectCache) key(namespace, name string) string {\n\tif len(namespace) \u003e 0 {\n\t\treturn namespace + \"/\" + name\n\t}\n\treturn name\n}","line":{"from":281,"to":288}} {"id":100007840,"name":"isStopped","signature":"func (c *objectCache) isStopped() bool","file":"pkg/kubelet/util/manager/watch_based_manager.go","code":"func (c *objectCache) isStopped() bool {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\treturn c.stopped\n}","line":{"from":290,"to":294}} {"id":100007841,"name":"Get","signature":"func (c *objectCache) Get(namespace, name string) (runtime.Object, error)","file":"pkg/kubelet/util/manager/watch_based_manager.go","code":"func (c *objectCache) Get(namespace, name string) (runtime.Object, error) {\n\tkey := objectKey{namespace: namespace, name: name}\n\n\tc.lock.RLock()\n\titem, exists := c.items[key]\n\tc.lock.RUnlock()\n\n\tif !exists {\n\t\treturn nil, fmt.Errorf(\"object %q/%q not registered\", namespace, name)\n\t}\n\t// Record last access time independently if it succeeded or not.\n\t// This protects from premature (racy) reflector closure.\n\titem.setLastAccessTime(c.clock.Now())\n\n\t// Don't restart reflector if Kubelet is already shutting down.\n\tif !c.isStopped() {\n\t\titem.restartReflectorIfNeeded()\n\t}\n\tif err := wait.PollImmediate(10*time.Millisecond, time.Second, item.hasSynced); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to sync %s cache: %v\", c.groupResource.String(), err)\n\t}\n\tobj, exists, err := item.store.GetByKey(c.key(namespace, name))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, apierrors.NewNotFound(c.groupResource, name)\n\t}\n\tif object, ok := obj.(runtime.Object); ok {\n\t\t// If the returned object is immutable, stop the reflector.\n\t\t//\n\t\t// NOTE: we may potentially not even start the reflector if the object is\n\t\t// already immutable. However, given that:\n\t\t// - we want to also handle the case when object is marked as immutable later\n\t\t// - Secrets and ConfigMaps are periodically fetched by volumemanager anyway\n\t\t// - doing that wouldn't provide visible scalability/performance gain - we\n\t\t// already have it from here\n\t\t// - doing that would require significant refactoring to reflector\n\t\t// we limit ourselves to just quickly stop the reflector here.\n\t\tif c.isImmutable(object) {\n\t\t\titem.setImmutable()\n\t\t\tif item.stop() {\n\t\t\t\tklog.V(4).InfoS(\"Stopped watching for changes - object is immutable\", \"obj\", klog.KRef(namespace, name))\n\t\t\t}\n\t\t}\n\t\treturn object, nil\n\t}\n\treturn nil, fmt.Errorf(\"unexpected object type: %v\", obj)\n}","line":{"from":296,"to":344}} {"id":100007842,"name":"startRecycleIdleWatch","signature":"func (c *objectCache) startRecycleIdleWatch()","file":"pkg/kubelet/util/manager/watch_based_manager.go","code":"func (c *objectCache) startRecycleIdleWatch() {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tfor key, item := range c.items {\n\t\tif item.stopIfIdle(c.clock.Now(), c.maxIdleTime) {\n\t\t\tklog.V(4).InfoS(\"Not acquired for long time, Stopped watching for changes\", \"objectKey\", key, \"maxIdleTime\", c.maxIdleTime)\n\t\t}\n\t}\n}","line":{"from":346,"to":355}} {"id":100007843,"name":"shutdownWhenStopped","signature":"func (c *objectCache) shutdownWhenStopped(stopCh \u003c-chan struct{})","file":"pkg/kubelet/util/manager/watch_based_manager.go","code":"func (c *objectCache) shutdownWhenStopped(stopCh \u003c-chan struct{}) {\n\t\u003c-stopCh\n\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tc.stopped = true\n\tfor _, item := range c.items {\n\t\titem.stop()\n\t}\n}","line":{"from":357,"to":367}} {"id":100007844,"name":"NewWatchBasedManager","signature":"func NewWatchBasedManager(","file":"pkg/kubelet/util/manager/watch_based_manager.go","code":"// NewWatchBasedManager creates a manager that keeps a cache of all objects\n// necessary for registered pods.\n// It implements the following logic:\n// - whenever a pod is created or updated, we start individual watches for all\n// referenced objects that aren't referenced from other registered pods\n// - every GetObject() returns a value from local cache propagated via watches\nfunc NewWatchBasedManager(\n\tlistObject listObjectFunc,\n\twatchObject watchObjectFunc,\n\tnewObject newObjectFunc,\n\tisImmutable isImmutableFunc,\n\tgroupResource schema.GroupResource,\n\tresyncInterval time.Duration,\n\tgetReferencedObjects func(*v1.Pod) sets.String) Manager {\n\n\t// If a configmap/secret is used as a volume, the volumeManager will visit the objectCacheItem every resyncInterval cycle,\n\t// We just want to stop the objectCacheItem referenced by environment variables,\n\t// So, maxIdleTime is set to an integer multiple of resyncInterval,\n\t// We currently set it to 5 times.\n\tmaxIdleTime := resyncInterval * 5\n\n\t// TODO propagate stopCh from the higher level.\n\tobjectStore := NewObjectCache(listObject, watchObject, newObject, isImmutable, groupResource, clock.RealClock{}, maxIdleTime, wait.NeverStop)\n\treturn NewCacheBasedManager(objectStore, getReferencedObjects)\n}","line":{"from":369,"to":393}} {"id":100007845,"name":"SetNodeOwnerFunc","signature":"func SetNodeOwnerFunc(c clientset.Interface, nodeName string) func(lease *coordinationv1.Lease) error","file":"pkg/kubelet/util/nodelease.go","code":"// SetNodeOwnerFunc helps construct a newLeasePostProcessFunc which sets\n// a node OwnerReference to the given lease object\nfunc SetNodeOwnerFunc(c clientset.Interface, nodeName string) func(lease *coordinationv1.Lease) error {\n\treturn func(lease *coordinationv1.Lease) error {\n\t\t// Setting owner reference needs node's UID. Note that it is different from\n\t\t// kubelet.nodeRef.UID. When lease is initially created, it is possible that\n\t\t// the connection between master and node is not ready yet. So try to set\n\t\t// owner reference every time when renewing the lease, until successful.\n\t\tif len(lease.OwnerReferences) == 0 {\n\t\t\tif node, err := c.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{}); err == nil {\n\t\t\t\tlease.OwnerReferences = []metav1.OwnerReference{\n\t\t\t\t\t{\n\t\t\t\t\t\tAPIVersion: corev1.SchemeGroupVersion.WithKind(\"Node\").Version,\n\t\t\t\t\t\tKind: corev1.SchemeGroupVersion.WithKind(\"Node\").Kind,\n\t\t\t\t\t\tName: nodeName,\n\t\t\t\t\t\tUID: node.UID,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tklog.ErrorS(err, \"Failed to get node when trying to set owner ref to the node lease\", \"node\", klog.KRef(\"\", nodeName))\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n}","line":{"from":30,"to":55}} {"id":100007846,"name":"NewPodStartupLatencyTracker","signature":"func NewPodStartupLatencyTracker() PodStartupLatencyTracker","file":"pkg/kubelet/util/pod_startup_latency_tracker.go","code":"// NewPodStartupLatencyTracker creates an instance of PodStartupLatencyTracker\nfunc NewPodStartupLatencyTracker() PodStartupLatencyTracker {\n\treturn \u0026basicPodStartupLatencyTracker{\n\t\tpods: map[types.UID]*perPodState{},\n\t\tclock: clock.RealClock{},\n\t}\n}","line":{"from":57,"to":63}} {"id":100007847,"name":"ObservedPodOnWatch","signature":"func (p *basicPodStartupLatencyTracker) ObservedPodOnWatch(pod *v1.Pod, when time.Time)","file":"pkg/kubelet/util/pod_startup_latency_tracker.go","code":"func (p *basicPodStartupLatencyTracker) ObservedPodOnWatch(pod *v1.Pod, when time.Time) {\n\tp.lock.Lock()\n\tdefer p.lock.Unlock()\n\n\t// if the pod is terminal, we do not have to track it anymore for startup\n\tif pod.Status.Phase == v1.PodFailed || pod.Status.Phase == v1.PodSucceeded {\n\t\tdelete(p.pods, pod.UID)\n\t\treturn\n\t}\n\n\tstate := p.pods[pod.UID]\n\tif state == nil {\n\t\t// create a new record for pod, only if it was not yet acknowledged by the Kubelet\n\t\t// this is required, as we want to log metric only for those pods, that where scheduled\n\t\t// after Kubelet started\n\t\tif pod.Status.StartTime.IsZero() {\n\t\t\tp.pods[pod.UID] = \u0026perPodState{}\n\t\t}\n\n\t\treturn\n\t}\n\n\tif state.observedRunningTime.IsZero() {\n\t\t// skip, pod didn't start yet\n\t\treturn\n\t}\n\n\tif state.metricRecorded {\n\t\t// skip, pod's latency already recorded\n\t\treturn\n\t}\n\n\tif hasPodStartedSLO(pod) {\n\t\tpodStartingDuration := when.Sub(pod.CreationTimestamp.Time)\n\t\timagePullingDuration := state.lastFinishedPulling.Sub(state.firstStartedPulling)\n\t\tpodStartSLOduration := (podStartingDuration - imagePullingDuration).Seconds()\n\n\t\tklog.InfoS(\"Observed pod startup duration\",\n\t\t\t\"pod\", klog.KObj(pod),\n\t\t\t\"podStartSLOduration\", podStartSLOduration,\n\t\t\t\"podCreationTimestamp\", pod.CreationTimestamp.Time,\n\t\t\t\"firstStartedPulling\", state.firstStartedPulling,\n\t\t\t\"lastFinishedPulling\", state.lastFinishedPulling,\n\t\t\t\"observedRunningTime\", state.observedRunningTime,\n\t\t\t\"watchObservedRunningTime\", when)\n\n\t\tmetrics.PodStartSLIDuration.WithLabelValues().Observe(podStartSLOduration)\n\t\tstate.metricRecorded = true\n\t}\n}","line":{"from":65,"to":114}} {"id":100007848,"name":"RecordImageStartedPulling","signature":"func (p *basicPodStartupLatencyTracker) RecordImageStartedPulling(podUID types.UID)","file":"pkg/kubelet/util/pod_startup_latency_tracker.go","code":"func (p *basicPodStartupLatencyTracker) RecordImageStartedPulling(podUID types.UID) {\n\tp.lock.Lock()\n\tdefer p.lock.Unlock()\n\n\tstate := p.pods[podUID]\n\tif state == nil {\n\t\treturn\n\t}\n\n\tif state.firstStartedPulling.IsZero() {\n\t\tstate.firstStartedPulling = p.clock.Now()\n\t}\n}","line":{"from":116,"to":128}} {"id":100007849,"name":"RecordImageFinishedPulling","signature":"func (p *basicPodStartupLatencyTracker) RecordImageFinishedPulling(podUID types.UID)","file":"pkg/kubelet/util/pod_startup_latency_tracker.go","code":"func (p *basicPodStartupLatencyTracker) RecordImageFinishedPulling(podUID types.UID) {\n\tp.lock.Lock()\n\tdefer p.lock.Unlock()\n\n\tstate := p.pods[podUID]\n\tif state == nil {\n\t\treturn\n\t}\n\n\tstate.lastFinishedPulling = p.clock.Now() // Now is always grater than values from the past.\n}","line":{"from":130,"to":140}} {"id":100007850,"name":"RecordStatusUpdated","signature":"func (p *basicPodStartupLatencyTracker) RecordStatusUpdated(pod *v1.Pod)","file":"pkg/kubelet/util/pod_startup_latency_tracker.go","code":"func (p *basicPodStartupLatencyTracker) RecordStatusUpdated(pod *v1.Pod) {\n\tp.lock.Lock()\n\tdefer p.lock.Unlock()\n\n\tstate := p.pods[pod.UID]\n\tif state == nil {\n\t\treturn\n\t}\n\n\tif state.metricRecorded {\n\t\t// skip, pod latency already recorded\n\t\treturn\n\t}\n\n\tif !state.observedRunningTime.IsZero() {\n\t\t// skip, pod already started\n\t\treturn\n\t}\n\n\tif hasPodStartedSLO(pod) {\n\t\tklog.V(3).InfoS(\"Mark when the pod was running for the first time\", \"pod\", klog.KObj(pod), \"rv\", pod.ResourceVersion)\n\t\tstate.observedRunningTime = p.clock.Now()\n\t}\n}","line":{"from":142,"to":165}} {"id":100007851,"name":"hasPodStartedSLO","signature":"func hasPodStartedSLO(pod *v1.Pod) bool","file":"pkg/kubelet/util/pod_startup_latency_tracker.go","code":"// hasPodStartedSLO, check if for given pod, each container has been started at least once\n//\n// This should reflect \"Pod startup latency SLI\" definition\n// ref: https://github.com/kubernetes/community/blob/master/sig-scalability/slos/pod_startup_latency.md\nfunc hasPodStartedSLO(pod *v1.Pod) bool {\n\tfor _, cs := range pod.Status.ContainerStatuses {\n\t\tif cs.State.Running == nil || cs.State.Running.StartedAt.IsZero() {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}","line":{"from":167,"to":179}} {"id":100007852,"name":"DeletePodStartupState","signature":"func (p *basicPodStartupLatencyTracker) DeletePodStartupState(podUID types.UID)","file":"pkg/kubelet/util/pod_startup_latency_tracker.go","code":"func (p *basicPodStartupLatencyTracker) DeletePodStartupState(podUID types.UID) {\n\tp.lock.Lock()\n\tdefer p.lock.Unlock()\n\n\tdelete(p.pods, podUID)\n}","line":{"from":181,"to":186}} {"id":100007853,"name":"NewBasicWorkQueue","signature":"func NewBasicWorkQueue(clock clock.Clock) WorkQueue","file":"pkg/kubelet/util/queue/work_queue.go","code":"// NewBasicWorkQueue returns a new basic WorkQueue with the provided clock\nfunc NewBasicWorkQueue(clock clock.Clock) WorkQueue {\n\tqueue := make(map[types.UID]time.Time)\n\treturn \u0026basicWorkQueue{queue: queue, clock: clock}\n}","line":{"from":44,"to":48}} {"id":100007854,"name":"GetWork","signature":"func (q *basicWorkQueue) GetWork() []types.UID","file":"pkg/kubelet/util/queue/work_queue.go","code":"func (q *basicWorkQueue) GetWork() []types.UID {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\tnow := q.clock.Now()\n\tvar items []types.UID\n\tfor k, v := range q.queue {\n\t\tif v.Before(now) {\n\t\t\titems = append(items, k)\n\t\t\tdelete(q.queue, k)\n\t\t}\n\t}\n\treturn items\n}","line":{"from":50,"to":62}} {"id":100007855,"name":"Enqueue","signature":"func (q *basicWorkQueue) Enqueue(item types.UID, delay time.Duration)","file":"pkg/kubelet/util/queue/work_queue.go","code":"func (q *basicWorkQueue) Enqueue(item types.UID, delay time.Duration) {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\tq.queue[item] = q.clock.Now().Add(delay)\n}","line":{"from":64,"to":68}} {"id":100007856,"name":"Len","signature":"func (s PodsByCreationTime) Len() int","file":"pkg/kubelet/util/sliceutils/sliceutils.go","code":"func (s PodsByCreationTime) Len() int {\n\treturn len(s)\n}","line":{"from":28,"to":30}} {"id":100007857,"name":"Swap","signature":"func (s PodsByCreationTime) Swap(i, j int)","file":"pkg/kubelet/util/sliceutils/sliceutils.go","code":"func (s PodsByCreationTime) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}","line":{"from":32,"to":34}} {"id":100007858,"name":"Less","signature":"func (s PodsByCreationTime) Less(i, j int) bool","file":"pkg/kubelet/util/sliceutils/sliceutils.go","code":"func (s PodsByCreationTime) Less(i, j int) bool {\n\treturn s[i].CreationTimestamp.Before(\u0026s[j].CreationTimestamp)\n}","line":{"from":36,"to":38}} {"id":100007859,"name":"Less","signature":"func (a ByImageSize) Less(i, j int) bool","file":"pkg/kubelet/util/sliceutils/sliceutils.go","code":"func (a ByImageSize) Less(i, j int) bool {\n\tif a[i].Size == a[j].Size {\n\t\treturn a[i].ID \u003e a[j].ID\n\t}\n\treturn a[i].Size \u003e a[j].Size\n}","line":{"from":44,"to":49}} {"id":100007860,"name":"Len","signature":"func (a ByImageSize) Len() int { return len(a) }","file":"pkg/kubelet/util/sliceutils/sliceutils.go","code":"func (a ByImageSize) Len() int { return len(a) }","line":{"from":50,"to":50}} {"id":100007861,"name":"Swap","signature":"func (a ByImageSize) Swap(i, j int) { a[i], a[j] = a[j], a[i] }","file":"pkg/kubelet/util/sliceutils/sliceutils.go","code":"func (a ByImageSize) Swap(i, j int) { a[i], a[j] = a[j], a[i] }","line":{"from":51,"to":51}} {"id":100007862,"name":"NewFileStore","signature":"func NewFileStore(path string, fs utilfs.Filesystem) (Store, error)","file":"pkg/kubelet/util/store/filestore.go","code":"// NewFileStore returns an instance of FileStore.\nfunc NewFileStore(path string, fs utilfs.Filesystem) (Store, error) {\n\tif err := fs.MkdirAll(path, 0755); err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026FileStore{directoryPath: path, filesystem: fs}, nil\n}","line":{"from":42,"to":48}} {"id":100007863,"name":"Write","signature":"func (f *FileStore) Write(key string, data []byte) error","file":"pkg/kubelet/util/store/filestore.go","code":"// Write writes the given data to a file named key.\nfunc (f *FileStore) Write(key string, data []byte) error {\n\tif err := ValidateKey(key); err != nil {\n\t\treturn err\n\t}\n\tif err := f.filesystem.MkdirAll(f.directoryPath, 0755); err != nil {\n\t\treturn err\n\t}\n\n\treturn writeFile(f.filesystem, f.getPathByKey(key), data)\n}","line":{"from":50,"to":60}} {"id":100007864,"name":"Read","signature":"func (f *FileStore) Read(key string) ([]byte, error)","file":"pkg/kubelet/util/store/filestore.go","code":"// Read reads the data from the file named key.\nfunc (f *FileStore) Read(key string) ([]byte, error) {\n\tif err := ValidateKey(key); err != nil {\n\t\treturn nil, err\n\t}\n\tbytes, err := f.filesystem.ReadFile(f.getPathByKey(key))\n\tif os.IsNotExist(err) {\n\t\treturn bytes, ErrKeyNotFound\n\t}\n\treturn bytes, err\n}","line":{"from":62,"to":72}} {"id":100007865,"name":"Delete","signature":"func (f *FileStore) Delete(key string) error","file":"pkg/kubelet/util/store/filestore.go","code":"// Delete deletes the key file.\nfunc (f *FileStore) Delete(key string) error {\n\tif err := ValidateKey(key); err != nil {\n\t\treturn err\n\t}\n\treturn removePath(f.filesystem, f.getPathByKey(key))\n}","line":{"from":74,"to":80}} {"id":100007866,"name":"List","signature":"func (f *FileStore) List() ([]string, error)","file":"pkg/kubelet/util/store/filestore.go","code":"// List returns all keys in the store.\nfunc (f *FileStore) List() ([]string, error) {\n\tkeys := make([]string, 0)\n\tfiles, err := f.filesystem.ReadDir(f.directoryPath)\n\tif err != nil {\n\t\treturn keys, err\n\t}\n\tfor _, f := range files {\n\t\tif !strings.HasPrefix(f.Name(), tmpPrefix) {\n\t\t\tkeys = append(keys, f.Name())\n\t\t}\n\t}\n\treturn keys, nil\n}","line":{"from":82,"to":95}} {"id":100007867,"name":"getPathByKey","signature":"func (f *FileStore) getPathByKey(key string) string","file":"pkg/kubelet/util/store/filestore.go","code":"// getPathByKey returns the full path of the file for the key.\nfunc (f *FileStore) getPathByKey(key string) string {\n\treturn filepath.Join(f.directoryPath, key)\n}","line":{"from":97,"to":100}} {"id":100007868,"name":"writeFile","signature":"func writeFile(fs utilfs.Filesystem, path string, data []byte) (retErr error)","file":"pkg/kubelet/util/store/filestore.go","code":"// writeFile writes data to path in a single transaction.\nfunc writeFile(fs utilfs.Filesystem, path string, data []byte) (retErr error) {\n\t// Create a temporary file in the base directory of `path` with a prefix.\n\ttmpFile, err := fs.TempFile(filepath.Dir(path), tmpPrefix)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttmpPath := tmpFile.Name()\n\tshouldClose := true\n\n\tdefer func() {\n\t\t// Close the file.\n\t\tif shouldClose {\n\t\t\tif err := tmpFile.Close(); err != nil {\n\t\t\t\tif retErr == nil {\n\t\t\t\t\tretErr = fmt.Errorf(\"close error: %v\", err)\n\t\t\t\t} else {\n\t\t\t\t\tretErr = fmt.Errorf(\"failed to close temp file after error %v; close error: %v\", retErr, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Clean up the temp file on error.\n\t\tif retErr != nil \u0026\u0026 tmpPath != \"\" {\n\t\t\tif err := removePath(fs, tmpPath); err != nil {\n\t\t\t\tretErr = fmt.Errorf(\"failed to remove the temporary file (%q) after error %v; remove error: %v\", tmpPath, retErr, err)\n\t\t\t}\n\t\t}\n\t}()\n\n\t// Write data.\n\tif _, err := tmpFile.Write(data); err != nil {\n\t\treturn err\n\t}\n\n\t// Sync file.\n\tif err := tmpFile.Sync(); err != nil {\n\t\treturn err\n\t}\n\n\t// Closing the file before renaming.\n\terr = tmpFile.Close()\n\tshouldClose = false\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn fs.Rename(tmpPath, path)\n}","line":{"from":102,"to":151}} {"id":100007869,"name":"removePath","signature":"func removePath(fs utilfs.Filesystem, path string) error","file":"pkg/kubelet/util/store/filestore.go","code":"func removePath(fs utilfs.Filesystem, path string) error {\n\tif err := fs.Remove(path); err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":153,"to":158}} {"id":100007870,"name":"ValidateKey","signature":"func ValidateKey(key string) error","file":"pkg/kubelet/util/store/store.go","code":"// ValidateKey returns an error if the given key does not meet the requirement\n// of the key format and length.\nfunc ValidateKey(key string) error {\n\tif len(key) \u003c= keyMaxLength \u0026\u0026 keyRegex.MatchString(key) {\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"invalid key: %q\", key)\n}","line":{"from":57,"to":64}} {"id":100007871,"name":"FromApiserverCache","signature":"func FromApiserverCache(opts *metav1.GetOptions)","file":"pkg/kubelet/util/util.go","code":"// FromApiserverCache modifies \u003copts\u003e so that the GET request will\n// be served from apiserver cache instead of from etcd.\nfunc FromApiserverCache(opts *metav1.GetOptions) {\n\topts.ResourceVersion = \"0\"\n}","line":{"from":25,"to":29}} {"id":100007872,"name":"GetNodenameForKernel","signature":"func GetNodenameForKernel(hostname string, hostDomainName string, setHostnameAsFQDN *bool) (string, error)","file":"pkg/kubelet/util/util.go","code":"// GetNodenameForKernel gets hostname value to set in the hostname field (the nodename field of struct utsname) of the pod.\nfunc GetNodenameForKernel(hostname string, hostDomainName string, setHostnameAsFQDN *bool) (string, error) {\n\tkernelHostname := hostname\n\t// FQDN has to be 64 chars to fit in the Linux nodename kernel field (specification 64 chars and the null terminating char).\n\tconst fqdnMaxLen = 64\n\tif len(hostDomainName) \u003e 0 \u0026\u0026 setHostnameAsFQDN != nil \u0026\u0026 *setHostnameAsFQDN {\n\t\tfqdn := fmt.Sprintf(\"%s.%s\", hostname, hostDomainName)\n\t\t// FQDN has to be shorter than hostnameMaxLen characters.\n\t\tif len(fqdn) \u003e fqdnMaxLen {\n\t\t\treturn \"\", fmt.Errorf(\"failed to construct FQDN from pod hostname and cluster domain, FQDN %s is too long (%d characters is the max, %d characters requested)\", fqdn, fqdnMaxLen, len(fqdn))\n\t\t}\n\t\tkernelHostname = fqdn\n\t}\n\treturn kernelHostname, nil\n}","line":{"from":31,"to":45}} {"id":100007873,"name":"CreateListener","signature":"func CreateListener(endpoint string) (net.Listener, error)","file":"pkg/kubelet/util/util_unix.go","code":"// CreateListener creates a listener on the specified endpoint.\nfunc CreateListener(endpoint string) (net.Listener, error) {\n\tprotocol, addr, err := parseEndpointWithFallbackProtocol(endpoint, unixProtocol)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif protocol != unixProtocol {\n\t\treturn nil, fmt.Errorf(\"only support unix socket endpoint\")\n\t}\n\n\t// Unlink to cleanup the previous socket file.\n\terr = unix.Unlink(addr)\n\tif err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\treturn nil, fmt.Errorf(\"failed to unlink socket file %q: %v\", addr, err)\n\t}\n\n\tif err := os.MkdirAll(filepath.Dir(addr), 0750); err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating socket directory %q: %v\", filepath.Dir(addr), err)\n\t}\n\n\t// Create the socket on a tempfile and move it to the destination socket to handle improper cleanup\n\tfile, err := os.CreateTemp(filepath.Dir(addr), \"\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create temporary file: %v\", err)\n\t}\n\n\tif err := os.Remove(file.Name()); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to remove temporary file: %v\", err)\n\t}\n\n\tl, err := net.Listen(protocol, file.Name())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = os.Rename(file.Name(), addr); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to move temporary file to addr %q: %v\", addr, err)\n\t}\n\n\treturn l, nil\n}","line":{"from":39,"to":79}} {"id":100007874,"name":"GetAddressAndDialer","signature":"func GetAddressAndDialer(endpoint string) (string, func(ctx context.Context, addr string) (net.Conn, error), error)","file":"pkg/kubelet/util/util_unix.go","code":"// GetAddressAndDialer returns the address parsed from the given endpoint and a context dialer.\nfunc GetAddressAndDialer(endpoint string) (string, func(ctx context.Context, addr string) (net.Conn, error), error) {\n\tprotocol, addr, err := parseEndpointWithFallbackProtocol(endpoint, unixProtocol)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\tif protocol != unixProtocol {\n\t\treturn \"\", nil, fmt.Errorf(\"only support unix socket endpoint\")\n\t}\n\n\treturn addr, dial, nil\n}","line":{"from":81,"to":92}} {"id":100007875,"name":"dial","signature":"func dial(ctx context.Context, addr string) (net.Conn, error)","file":"pkg/kubelet/util/util_unix.go","code":"func dial(ctx context.Context, addr string) (net.Conn, error) {\n\treturn (\u0026net.Dialer{}).DialContext(ctx, unixProtocol, addr)\n}","line":{"from":94,"to":96}} {"id":100007876,"name":"parseEndpointWithFallbackProtocol","signature":"func parseEndpointWithFallbackProtocol(endpoint string, fallbackProtocol string) (protocol string, addr string, err error)","file":"pkg/kubelet/util/util_unix.go","code":"func parseEndpointWithFallbackProtocol(endpoint string, fallbackProtocol string) (protocol string, addr string, err error) {\n\tif protocol, addr, err = parseEndpoint(endpoint); err != nil \u0026\u0026 protocol == \"\" {\n\t\tfallbackEndpoint := fallbackProtocol + \"://\" + endpoint\n\t\tprotocol, addr, err = parseEndpoint(fallbackEndpoint)\n\t\tif err == nil {\n\t\t\tklog.InfoS(\"Using this endpoint is deprecated, please consider using full URL format\", \"endpoint\", endpoint, \"URL\", fallbackEndpoint)\n\t\t}\n\t}\n\treturn\n}","line":{"from":98,"to":107}} {"id":100007877,"name":"parseEndpoint","signature":"func parseEndpoint(endpoint string) (string, string, error)","file":"pkg/kubelet/util/util_unix.go","code":"func parseEndpoint(endpoint string) (string, string, error) {\n\tu, err := url.Parse(endpoint)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\tswitch u.Scheme {\n\tcase \"tcp\":\n\t\treturn \"tcp\", u.Host, nil\n\n\tcase \"unix\":\n\t\treturn \"unix\", u.Path, nil\n\n\tcase \"\":\n\t\treturn \"\", \"\", fmt.Errorf(\"using %q as endpoint is deprecated, please consider using full url format\", endpoint)\n\n\tdefault:\n\t\treturn u.Scheme, \"\", fmt.Errorf(\"protocol %q not supported\", u.Scheme)\n\t}\n}","line":{"from":109,"to":128}} {"id":100007878,"name":"LocalEndpoint","signature":"func LocalEndpoint(path, file string) (string, error)","file":"pkg/kubelet/util/util_unix.go","code":"// LocalEndpoint returns the full path to a unix socket at the given endpoint\nfunc LocalEndpoint(path, file string) (string, error) {\n\tu := url.URL{\n\t\tScheme: unixProtocol,\n\t\tPath: path,\n\t}\n\treturn filepath.Join(u.String(), file+\".sock\"), nil\n}","line":{"from":130,"to":137}} {"id":100007879,"name":"IsUnixDomainSocket","signature":"func IsUnixDomainSocket(filePath string) (bool, error)","file":"pkg/kubelet/util/util_unix.go","code":"// IsUnixDomainSocket returns whether a given file is a AF_UNIX socket file\nfunc IsUnixDomainSocket(filePath string) (bool, error) {\n\tfi, err := os.Stat(filePath)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"stat file %s failed: %v\", filePath, err)\n\t}\n\tif fi.Mode()\u0026os.ModeSocket == 0 {\n\t\treturn false, nil\n\t}\n\treturn true, nil\n}","line":{"from":139,"to":149}} {"id":100007880,"name":"NormalizePath","signature":"func NormalizePath(path string) string","file":"pkg/kubelet/util/util_unix.go","code":"// NormalizePath is a no-op for Linux for now\nfunc NormalizePath(path string) string {\n\treturn path\n}","line":{"from":151,"to":154}} {"id":100007881,"name":"CreateListener","signature":"func CreateListener(endpoint string) (net.Listener, error)","file":"pkg/kubelet/util/util_unsupported.go","code":"// CreateListener creates a listener on the specified endpoint.\nfunc CreateListener(endpoint string) (net.Listener, error) {\n\treturn nil, fmt.Errorf(\"CreateListener is unsupported in this build\")\n}","line":{"from":29,"to":32}} {"id":100007882,"name":"GetAddressAndDialer","signature":"func GetAddressAndDialer(endpoint string) (string, func(ctx context.Context, addr string) (net.Conn, error), error)","file":"pkg/kubelet/util/util_unsupported.go","code":"// GetAddressAndDialer returns the address parsed from the given endpoint and a context dialer.\nfunc GetAddressAndDialer(endpoint string) (string, func(ctx context.Context, addr string) (net.Conn, error), error) {\n\treturn \"\", nil, fmt.Errorf(\"GetAddressAndDialer is unsupported in this build\")\n}","line":{"from":34,"to":37}} {"id":100007883,"name":"LockAndCheckSubPath","signature":"func LockAndCheckSubPath(volumePath, subPath string) ([]uintptr, error)","file":"pkg/kubelet/util/util_unsupported.go","code":"// LockAndCheckSubPath empty implementation\nfunc LockAndCheckSubPath(volumePath, subPath string) ([]uintptr, error) {\n\treturn []uintptr{}, nil\n}","line":{"from":39,"to":42}} {"id":100007884,"name":"UnlockPath","signature":"func UnlockPath(fileHandles []uintptr)","file":"pkg/kubelet/util/util_unsupported.go","code":"// UnlockPath empty implementation\nfunc UnlockPath(fileHandles []uintptr) {\n}","line":{"from":44,"to":46}} {"id":100007885,"name":"LocalEndpoint","signature":"func LocalEndpoint(path, file string) (string, error)","file":"pkg/kubelet/util/util_unsupported.go","code":"// LocalEndpoint empty implementation\nfunc LocalEndpoint(path, file string) (string, error) {\n\treturn \"\", fmt.Errorf(\"LocalEndpoints are unsupported in this build\")\n}","line":{"from":48,"to":51}} {"id":100007886,"name":"GetBootTime","signature":"func GetBootTime() (time.Time, error)","file":"pkg/kubelet/util/util_unsupported.go","code":"// GetBootTime empty implementation\nfunc GetBootTime() (time.Time, error) {\n\treturn time.Time{}, fmt.Errorf(\"GetBootTime is unsupported in this build\")\n}","line":{"from":53,"to":56}} {"id":100007887,"name":"CreateListener","signature":"func CreateListener(endpoint string) (net.Listener, error)","file":"pkg/kubelet/util/util_windows.go","code":"// CreateListener creates a listener on the specified endpoint.\nfunc CreateListener(endpoint string) (net.Listener, error) {\n\tprotocol, addr, err := parseEndpoint(endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch protocol {\n\tcase tcpProtocol:\n\t\treturn net.Listen(tcpProtocol, addr)\n\n\tcase npipeProtocol:\n\t\treturn winio.ListenPipe(addr, nil)\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"only support tcp and npipe endpoint\")\n\t}\n}","line":{"from":47,"to":64}} {"id":100007888,"name":"GetAddressAndDialer","signature":"func GetAddressAndDialer(endpoint string) (string, func(ctx context.Context, addr string) (net.Conn, error), error)","file":"pkg/kubelet/util/util_windows.go","code":"// GetAddressAndDialer returns the address parsed from the given endpoint and a context dialer.\nfunc GetAddressAndDialer(endpoint string) (string, func(ctx context.Context, addr string) (net.Conn, error), error) {\n\tprotocol, addr, err := parseEndpoint(endpoint)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\n\tif protocol == tcpProtocol {\n\t\treturn addr, tcpDial, nil\n\t}\n\n\tif protocol == npipeProtocol {\n\t\treturn addr, npipeDial, nil\n\t}\n\n\treturn \"\", nil, fmt.Errorf(\"only support tcp and npipe endpoint\")\n}","line":{"from":66,"to":82}} {"id":100007889,"name":"tcpDial","signature":"func tcpDial(ctx context.Context, addr string) (net.Conn, error)","file":"pkg/kubelet/util/util_windows.go","code":"func tcpDial(ctx context.Context, addr string) (net.Conn, error) {\n\treturn (\u0026net.Dialer{}).DialContext(ctx, tcpProtocol, addr)\n}","line":{"from":84,"to":86}} {"id":100007890,"name":"npipeDial","signature":"func npipeDial(ctx context.Context, addr string) (net.Conn, error)","file":"pkg/kubelet/util/util_windows.go","code":"func npipeDial(ctx context.Context, addr string) (net.Conn, error) {\n\treturn winio.DialPipeContext(ctx, addr)\n}","line":{"from":88,"to":90}} {"id":100007891,"name":"parseEndpoint","signature":"func parseEndpoint(endpoint string) (string, string, error)","file":"pkg/kubelet/util/util_windows.go","code":"func parseEndpoint(endpoint string) (string, string, error) {\n\t// url.Parse doesn't recognize \\, so replace with / first.\n\tendpoint = strings.Replace(endpoint, \"\\\\\", \"/\", -1)\n\tu, err := url.Parse(endpoint)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\tif u.Scheme == \"tcp\" {\n\t\treturn \"tcp\", u.Host, nil\n\t} else if u.Scheme == \"npipe\" {\n\t\tif strings.HasPrefix(u.Path, \"//./pipe\") {\n\t\t\treturn \"npipe\", u.Path, nil\n\t\t}\n\n\t\t// fallback host if not provided.\n\t\thost := u.Host\n\t\tif host == \"\" {\n\t\t\thost = \".\"\n\t\t}\n\t\treturn \"npipe\", fmt.Sprintf(\"//%s%s\", host, u.Path), nil\n\t} else if u.Scheme == \"\" {\n\t\treturn \"\", \"\", fmt.Errorf(\"Using %q as endpoint is deprecated, please consider using full url format\", endpoint)\n\t} else {\n\t\treturn u.Scheme, \"\", fmt.Errorf(\"protocol %q not supported\", u.Scheme)\n\t}\n}","line":{"from":92,"to":118}} {"id":100007892,"name":"LocalEndpoint","signature":"func LocalEndpoint(path, file string) (string, error)","file":"pkg/kubelet/util/util_windows.go","code":"// LocalEndpoint empty implementation\nfunc LocalEndpoint(path, file string) (string, error) {\n\treturn \"\", fmt.Errorf(\"LocalEndpoints are unsupported in this build\")\n}","line":{"from":120,"to":123}} {"id":100007893,"name":"GetBootTime","signature":"func GetBootTime() (time.Time, error)","file":"pkg/kubelet/util/util_windows.go","code":"// GetBootTime returns the time at which the machine was started, truncated to the nearest second\nfunc GetBootTime() (time.Time, error) {\n\tcurrentTime := time.Now()\n\toutput, _, err := tickCount.Call()\n\tif errno, ok := err.(syscall.Errno); !ok || errno != 0 {\n\t\treturn time.Time{}, err\n\t}\n\treturn currentTime.Add(-time.Duration(output) * time.Millisecond).Truncate(time.Second), nil\n}","line":{"from":127,"to":135}} {"id":100007894,"name":"IsUnixDomainSocket","signature":"func IsUnixDomainSocket(filePath string) (bool, error)","file":"pkg/kubelet/util/util_windows.go","code":"// IsUnixDomainSocket returns whether a given file is a AF_UNIX socket file\n// Note that due to the retry logic inside, it could take up to 4 seconds\n// to determine whether or not the file path supplied is a Unix domain socket\nfunc IsUnixDomainSocket(filePath string) (bool, error) {\n\t// Due to the absence of golang support for os.ModeSocket in Windows (https://github.com/golang/go/issues/33357)\n\t// we need to dial the file and check if we receive an error to determine if a file is Unix Domain Socket file.\n\n\t// Note that querrying for the Reparse Points (https://docs.microsoft.com/en-us/windows/win32/fileio/reparse-points)\n\t// for the file (using FSCTL_GET_REPARSE_POINT) and checking for reparse tag: reparseTagSocket\n\t// does NOT work in 1809 if the socket file is created within a bind mounted directory by a container\n\t// and the FSCTL is issued in the host by the kubelet.\n\n\tklog.V(6).InfoS(\"Function IsUnixDomainSocket starts\", \"filePath\", filePath)\n\t// As detailed in https://github.com/kubernetes/kubernetes/issues/104584 we cannot rely\n\t// on the Unix Domain socket working on the very first try, hence the potential need to\n\t// dial multiple times\n\tvar lastSocketErr error\n\terr := wait.PollImmediate(socketDialRetryPeriod, socketDialTimeout,\n\t\tfunc() (bool, error) {\n\t\t\tklog.V(6).InfoS(\"Dialing the socket\", \"filePath\", filePath)\n\t\t\tvar c net.Conn\n\t\t\tc, lastSocketErr = net.Dial(\"unix\", filePath)\n\t\t\tif lastSocketErr == nil {\n\t\t\t\tc.Close()\n\t\t\t\tklog.V(6).InfoS(\"Socket dialed successfully\", \"filePath\", filePath)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\tklog.V(6).InfoS(\"Failed the current attempt to dial the socket, so pausing before retry\",\n\t\t\t\t\"filePath\", filePath, \"err\", lastSocketErr, \"socketDialRetryPeriod\",\n\t\t\t\tsocketDialRetryPeriod)\n\t\t\treturn false, nil\n\t\t})\n\n\t// PollImmediate will return \"timed out waiting for the condition\" if the function it\n\t// invokes never returns true\n\tif err != nil {\n\t\tklog.V(2).InfoS(\"Failed all attempts to dial the socket so marking it as a non-Unix Domain socket. Last socket error along with the error from PollImmediate follow\",\n\t\t\t\"filePath\", filePath, \"lastSocketErr\", lastSocketErr, \"err\", err)\n\t\treturn false, nil\n\t}\n\treturn true, nil\n}","line":{"from":137,"to":178}} {"id":100007895,"name":"NormalizePath","signature":"func NormalizePath(path string) string","file":"pkg/kubelet/util/util_windows.go","code":"// NormalizePath converts FS paths returned by certain go frameworks (like fsnotify)\n// to native Windows paths that can be passed to Windows specific code\nfunc NormalizePath(path string) string {\n\tpath = strings.ReplaceAll(path, \"/\", \"\\\\\")\n\tif strings.HasPrefix(path, \"\\\\\") {\n\t\tpath = \"c:\" + path\n\t}\n\treturn path\n}","line":{"from":180,"to":188}} {"id":100007896,"name":"NewInitializedVolumePluginMgr","signature":"func NewInitializedVolumePluginMgr(","file":"pkg/kubelet/volume_host.go","code":"// NewInitializedVolumePluginMgr returns a new instance of\n// volume.VolumePluginMgr initialized with kubelets implementation of the\n// volume.VolumeHost interface.\n//\n// kubelet - used by VolumeHost methods to expose kubelet specific parameters\n// plugins - used to initialize volumePluginMgr\nfunc NewInitializedVolumePluginMgr(\n\tkubelet *Kubelet,\n\tsecretManager secret.Manager,\n\tconfigMapManager configmap.Manager,\n\ttokenManager *token.Manager,\n\tplugins []volume.VolumePlugin,\n\tprober volume.DynamicPluginProber) (*volume.VolumePluginMgr, error) {\n\n\t// Initialize csiDriverLister before calling InitPlugins\n\tvar informerFactory informers.SharedInformerFactory\n\tvar csiDriverLister storagelisters.CSIDriverLister\n\tvar csiDriversSynced cache.InformerSynced\n\tconst resyncPeriod = 0\n\t// Don't initialize if kubeClient is nil\n\tif kubelet.kubeClient != nil {\n\t\tinformerFactory = informers.NewSharedInformerFactory(kubelet.kubeClient, resyncPeriod)\n\t\tcsiDriverInformer := informerFactory.Storage().V1().CSIDrivers()\n\t\tcsiDriverLister = csiDriverInformer.Lister()\n\t\tcsiDriversSynced = csiDriverInformer.Informer().HasSynced\n\n\t} else {\n\t\tklog.InfoS(\"KubeClient is nil. Skip initialization of CSIDriverLister\")\n\t}\n\n\tkvh := \u0026kubeletVolumeHost{\n\t\tkubelet: kubelet,\n\t\tvolumePluginMgr: volume.VolumePluginMgr{},\n\t\tsecretManager: secretManager,\n\t\tconfigMapManager: configMapManager,\n\t\ttokenManager: tokenManager,\n\t\tinformerFactory: informerFactory,\n\t\tcsiDriverLister: csiDriverLister,\n\t\tcsiDriversSynced: csiDriversSynced,\n\t\texec: utilexec.New(),\n\t}\n\n\tif err := kvh.volumePluginMgr.InitPlugins(plugins, prober, kvh); err != nil {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"could not initialize volume plugins for KubeletVolumePluginMgr: %v\",\n\t\t\terr)\n\t}\n\n\treturn \u0026kvh.volumePluginMgr, nil\n}","line":{"from":48,"to":97}} {"id":100007897,"name":"GetPluginDir","signature":"func (kvh *kubeletVolumeHost) GetPluginDir(pluginName string) string","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) GetPluginDir(pluginName string) string {\n\treturn kvh.kubelet.getPluginDir(pluginName)\n}","line":{"from":103,"to":105}} {"id":100007898,"name":"SetKubeletError","signature":"func (kvh *kubeletVolumeHost) SetKubeletError(err error)","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) SetKubeletError(err error) {\n\tkvh.kubelet.runtimeState.setStorageState(err)\n}","line":{"from":119,"to":121}} {"id":100007899,"name":"GetVolumeDevicePluginDir","signature":"func (kvh *kubeletVolumeHost) GetVolumeDevicePluginDir(pluginName string) string","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) GetVolumeDevicePluginDir(pluginName string) string {\n\treturn kvh.kubelet.getVolumeDevicePluginDir(pluginName)\n}","line":{"from":123,"to":125}} {"id":100007900,"name":"GetPodsDir","signature":"func (kvh *kubeletVolumeHost) GetPodsDir() string","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) GetPodsDir() string {\n\treturn kvh.kubelet.getPodsDir()\n}","line":{"from":127,"to":129}} {"id":100007901,"name":"GetPodVolumeDir","signature":"func (kvh *kubeletVolumeHost) GetPodVolumeDir(podUID types.UID, pluginName string, volumeName string) string","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) GetPodVolumeDir(podUID types.UID, pluginName string, volumeName string) string {\n\tdir := kvh.kubelet.getPodVolumeDir(podUID, pluginName, volumeName)\n\tif runtime.GOOS == \"windows\" {\n\t\tdir = util.GetWindowsPath(dir)\n\t}\n\treturn dir\n}","line":{"from":131,"to":137}} {"id":100007902,"name":"GetPodVolumeDeviceDir","signature":"func (kvh *kubeletVolumeHost) GetPodVolumeDeviceDir(podUID types.UID, pluginName string) string","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) GetPodVolumeDeviceDir(podUID types.UID, pluginName string) string {\n\treturn kvh.kubelet.getPodVolumeDeviceDir(podUID, pluginName)\n}","line":{"from":139,"to":141}} {"id":100007903,"name":"GetPodPluginDir","signature":"func (kvh *kubeletVolumeHost) GetPodPluginDir(podUID types.UID, pluginName string) string","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) GetPodPluginDir(podUID types.UID, pluginName string) string {\n\treturn kvh.kubelet.getPodPluginDir(podUID, pluginName)\n}","line":{"from":143,"to":145}} {"id":100007904,"name":"GetKubeClient","signature":"func (kvh *kubeletVolumeHost) GetKubeClient() clientset.Interface","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) GetKubeClient() clientset.Interface {\n\treturn kvh.kubelet.kubeClient\n}","line":{"from":147,"to":149}} {"id":100007905,"name":"GetSubpather","signature":"func (kvh *kubeletVolumeHost) GetSubpather() subpath.Interface","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) GetSubpather() subpath.Interface {\n\treturn kvh.kubelet.subpather\n}","line":{"from":151,"to":153}} {"id":100007906,"name":"GetFilteredDialOptions","signature":"func (kvh *kubeletVolumeHost) GetFilteredDialOptions() *proxyutil.FilteredDialOptions","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) GetFilteredDialOptions() *proxyutil.FilteredDialOptions {\n\t// FilteredDial is not needed in the kubelet.\n\treturn nil\n}","line":{"from":155,"to":158}} {"id":100007907,"name":"GetHostUtil","signature":"func (kvh *kubeletVolumeHost) GetHostUtil() hostutil.HostUtils","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) GetHostUtil() hostutil.HostUtils {\n\treturn kvh.kubelet.hostutil\n}","line":{"from":160,"to":162}} {"id":100007908,"name":"GetInformerFactory","signature":"func (kvh *kubeletVolumeHost) GetInformerFactory() informers.SharedInformerFactory","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) GetInformerFactory() informers.SharedInformerFactory {\n\treturn kvh.informerFactory\n}","line":{"from":164,"to":166}} {"id":100007909,"name":"CSIDriverLister","signature":"func (kvh *kubeletVolumeHost) CSIDriverLister() storagelisters.CSIDriverLister","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) CSIDriverLister() storagelisters.CSIDriverLister {\n\treturn kvh.csiDriverLister\n}","line":{"from":168,"to":170}} {"id":100007910,"name":"CSIDriversSynced","signature":"func (kvh *kubeletVolumeHost) CSIDriversSynced() cache.InformerSynced","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) CSIDriversSynced() cache.InformerSynced {\n\treturn kvh.csiDriversSynced\n}","line":{"from":172,"to":174}} {"id":100007911,"name":"WaitForCacheSync","signature":"func (kvh *kubeletVolumeHost) WaitForCacheSync() error","file":"pkg/kubelet/volume_host.go","code":"// WaitForCacheSync is a helper function that waits for cache sync for CSIDriverLister\nfunc (kvh *kubeletVolumeHost) WaitForCacheSync() error {\n\tif kvh.csiDriversSynced == nil {\n\t\tklog.ErrorS(nil, \"CsiDriversSynced not found on KubeletVolumeHost\")\n\t\treturn fmt.Errorf(\"csiDriversSynced not found on KubeletVolumeHost\")\n\t}\n\n\tsynced := []cache.InformerSynced{kvh.csiDriversSynced}\n\tif !cache.WaitForCacheSync(wait.NeverStop, synced...) {\n\t\tklog.InfoS(\"Failed to wait for cache sync for CSIDriverLister\")\n\t\treturn fmt.Errorf(\"failed to wait for cache sync for CSIDriverLister\")\n\t}\n\n\treturn nil\n}","line":{"from":176,"to":190}} {"id":100007912,"name":"NewWrapperMounter","signature":"func (kvh *kubeletVolumeHost) NewWrapperMounter(","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) NewWrapperMounter(\n\tvolName string,\n\tspec volume.Spec,\n\tpod *v1.Pod,\n\topts volume.VolumeOptions) (volume.Mounter, error) {\n\t// The name of wrapper volume is set to \"wrapped_{wrapped_volume_name}\"\n\twrapperVolumeName := \"wrapped_\" + volName\n\tif spec.Volume != nil {\n\t\tspec.Volume.Name = wrapperVolumeName\n\t}\n\n\treturn kvh.kubelet.newVolumeMounterFromPlugins(\u0026spec, pod, opts)\n}","line":{"from":192,"to":204}} {"id":100007913,"name":"NewWrapperUnmounter","signature":"func (kvh *kubeletVolumeHost) NewWrapperUnmounter(volName string, spec volume.Spec, podUID types.UID) (volume.Unmounter, error)","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) NewWrapperUnmounter(volName string, spec volume.Spec, podUID types.UID) (volume.Unmounter, error) {\n\t// The name of wrapper volume is set to \"wrapped_{wrapped_volume_name}\"\n\twrapperVolumeName := \"wrapped_\" + volName\n\tif spec.Volume != nil {\n\t\tspec.Volume.Name = wrapperVolumeName\n\t}\n\n\tplugin, err := kvh.kubelet.volumePluginMgr.FindPluginBySpec(\u0026spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn plugin.NewUnmounter(spec.Name(), podUID)\n}","line":{"from":206,"to":219}} {"id":100007914,"name":"GetCloudProvider","signature":"func (kvh *kubeletVolumeHost) GetCloudProvider() cloudprovider.Interface","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) GetCloudProvider() cloudprovider.Interface {\n\treturn kvh.kubelet.cloud\n}","line":{"from":221,"to":223}} {"id":100007915,"name":"GetMounter","signature":"func (kvh *kubeletVolumeHost) GetMounter(pluginName string) mount.Interface","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) GetMounter(pluginName string) mount.Interface {\n\treturn kvh.kubelet.mounter\n}","line":{"from":225,"to":227}} {"id":100007916,"name":"GetHostName","signature":"func (kvh *kubeletVolumeHost) GetHostName() string","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) GetHostName() string {\n\treturn kvh.kubelet.hostname\n}","line":{"from":229,"to":231}} {"id":100007917,"name":"GetHostIP","signature":"func (kvh *kubeletVolumeHost) GetHostIP() (net.IP, error)","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) GetHostIP() (net.IP, error) {\n\thostIPs, err := kvh.kubelet.GetHostIPs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn hostIPs[0], err\n}","line":{"from":233,"to":239}} {"id":100007918,"name":"GetNodeAllocatable","signature":"func (kvh *kubeletVolumeHost) GetNodeAllocatable() (v1.ResourceList, error)","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) GetNodeAllocatable() (v1.ResourceList, error) {\n\tnode, err := kvh.kubelet.getNodeAnyWay()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error retrieving node: %v\", err)\n\t}\n\treturn node.Status.Allocatable, nil\n}","line":{"from":241,"to":247}} {"id":100007919,"name":"GetSecretFunc","signature":"func (kvh *kubeletVolumeHost) GetSecretFunc() func(namespace, name string) (*v1.Secret, error)","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) GetSecretFunc() func(namespace, name string) (*v1.Secret, error) {\n\tif kvh.secretManager != nil {\n\t\treturn kvh.secretManager.GetSecret\n\t}\n\treturn func(namespace, name string) (*v1.Secret, error) {\n\t\treturn nil, fmt.Errorf(\"not supported due to running kubelet in standalone mode\")\n\t}\n}","line":{"from":249,"to":256}} {"id":100007920,"name":"GetConfigMapFunc","signature":"func (kvh *kubeletVolumeHost) GetConfigMapFunc() func(namespace, name string) (*v1.ConfigMap, error)","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) GetConfigMapFunc() func(namespace, name string) (*v1.ConfigMap, error) {\n\tif kvh.configMapManager != nil {\n\t\treturn kvh.configMapManager.GetConfigMap\n\t}\n\treturn func(namespace, name string) (*v1.ConfigMap, error) {\n\t\treturn nil, fmt.Errorf(\"not supported due to running kubelet in standalone mode\")\n\t}\n}","line":{"from":258,"to":265}} {"id":100007921,"name":"GetServiceAccountTokenFunc","signature":"func (kvh *kubeletVolumeHost) GetServiceAccountTokenFunc() func(namespace, name string, tr *authenticationv1.TokenRequest) (*authenticationv1.TokenRequest, error)","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) GetServiceAccountTokenFunc() func(namespace, name string, tr *authenticationv1.TokenRequest) (*authenticationv1.TokenRequest, error) {\n\treturn kvh.tokenManager.GetServiceAccountToken\n}","line":{"from":267,"to":269}} {"id":100007922,"name":"DeleteServiceAccountTokenFunc","signature":"func (kvh *kubeletVolumeHost) DeleteServiceAccountTokenFunc() func(podUID types.UID)","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) DeleteServiceAccountTokenFunc() func(podUID types.UID) {\n\treturn kvh.tokenManager.DeleteServiceAccountToken\n}","line":{"from":271,"to":273}} {"id":100007923,"name":"GetNodeLabels","signature":"func (kvh *kubeletVolumeHost) GetNodeLabels() (map[string]string, error)","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) GetNodeLabels() (map[string]string, error) {\n\tnode, err := kvh.kubelet.GetNode()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error retrieving node: %v\", err)\n\t}\n\treturn node.Labels, nil\n}","line":{"from":275,"to":281}} {"id":100007924,"name":"GetAttachedVolumesFromNodeStatus","signature":"func (kvh *kubeletVolumeHost) GetAttachedVolumesFromNodeStatus() (map[v1.UniqueVolumeName]string, error)","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) GetAttachedVolumesFromNodeStatus() (map[v1.UniqueVolumeName]string, error) {\n\tnode, err := kvh.kubelet.GetNode()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error retrieving node: %v\", err)\n\t}\n\tattachedVolumes := node.Status.VolumesAttached\n\tresult := map[v1.UniqueVolumeName]string{}\n\tfor i := range attachedVolumes {\n\t\tattachedVolume := attachedVolumes[i]\n\t\tresult[attachedVolume.Name] = attachedVolume.DevicePath\n\t}\n\treturn result, nil\n}","line":{"from":283,"to":295}} {"id":100007925,"name":"GetNodeName","signature":"func (kvh *kubeletVolumeHost) GetNodeName() types.NodeName","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) GetNodeName() types.NodeName {\n\treturn kvh.kubelet.nodeName\n}","line":{"from":297,"to":299}} {"id":100007926,"name":"GetEventRecorder","signature":"func (kvh *kubeletVolumeHost) GetEventRecorder() record.EventRecorder","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) GetEventRecorder() record.EventRecorder {\n\treturn kvh.kubelet.recorder\n}","line":{"from":301,"to":303}} {"id":100007927,"name":"GetExec","signature":"func (kvh *kubeletVolumeHost) GetExec(pluginName string) utilexec.Interface","file":"pkg/kubelet/volume_host.go","code":"func (kvh *kubeletVolumeHost) GetExec(pluginName string) utilexec.Interface {\n\treturn kvh.exec\n}","line":{"from":305,"to":307}} {"id":100007928,"name":"DeviceMayBeMounted","signature":"func (av AttachedVolume) DeviceMayBeMounted() bool","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"// DeviceMayBeMounted returns true if device is mounted in global path or is in\n// uncertain state.\nfunc (av AttachedVolume) DeviceMayBeMounted() bool {\n\treturn av.DeviceMountState == operationexecutor.DeviceGloballyMounted ||\n\t\tav.DeviceMountState == operationexecutor.DeviceMountUncertain\n}","line":{"from":200,"to":205}} {"id":100007929,"name":"NewActualStateOfWorld","signature":"func NewActualStateOfWorld(","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"// NewActualStateOfWorld returns a new instance of ActualStateOfWorld.\nfunc NewActualStateOfWorld(\n\tnodeName types.NodeName,\n\tvolumePluginMgr *volume.VolumePluginMgr) ActualStateOfWorld {\n\treturn \u0026actualStateOfWorld{\n\t\tnodeName: nodeName,\n\t\tattachedVolumes: make(map[v1.UniqueVolumeName]attachedVolume),\n\t\tfoundDuringReconstruction: make(map[v1.UniqueVolumeName]map[volumetypes.UniquePodName]types.UID),\n\t\tvolumePluginMgr: volumePluginMgr,\n\t}\n}","line":{"from":207,"to":217}} {"id":100007930,"name":"IsVolumeNotAttachedError","signature":"func IsVolumeNotAttachedError(err error) bool","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"// IsVolumeNotAttachedError returns true if the specified error is a\n// volumeNotAttachedError.\nfunc IsVolumeNotAttachedError(err error) bool {\n\t_, ok := err.(volumeNotAttachedError)\n\treturn ok\n}","line":{"from":219,"to":224}} {"id":100007931,"name":"IsRemountRequiredError","signature":"func IsRemountRequiredError(err error) bool","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"// IsRemountRequiredError returns true if the specified error is a\n// remountRequiredError.\nfunc IsRemountRequiredError(err error) bool {\n\t_, ok := err.(remountRequiredError)\n\treturn ok\n}","line":{"from":226,"to":231}} {"id":100007932,"name":"MarkVolumeAsAttached","signature":"func (asw *actualStateOfWorld) MarkVolumeAsAttached(","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) MarkVolumeAsAttached(\n\tlogger klog.Logger,\n\tvolumeName v1.UniqueVolumeName, volumeSpec *volume.Spec, _ types.NodeName, devicePath string) error {\n\treturn asw.addVolume(volumeName, volumeSpec, devicePath)\n}","line":{"from":361,"to":365}} {"id":100007933,"name":"MarkVolumeAsUncertain","signature":"func (asw *actualStateOfWorld) MarkVolumeAsUncertain(","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) MarkVolumeAsUncertain(\n\tlogger klog.Logger, volumeName v1.UniqueVolumeName, volumeSpec *volume.Spec, _ types.NodeName) error {\n\treturn nil\n}","line":{"from":367,"to":370}} {"id":100007934,"name":"MarkVolumeAsDetached","signature":"func (asw *actualStateOfWorld) MarkVolumeAsDetached(","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) MarkVolumeAsDetached(\n\tvolumeName v1.UniqueVolumeName, nodeName types.NodeName) {\n\tasw.DeleteVolume(volumeName)\n}","line":{"from":372,"to":375}} {"id":100007935,"name":"IsVolumeReconstructed","signature":"func (asw *actualStateOfWorld) IsVolumeReconstructed(volumeName v1.UniqueVolumeName, podName volumetypes.UniquePodName) bool","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) IsVolumeReconstructed(volumeName v1.UniqueVolumeName, podName volumetypes.UniquePodName) bool {\n\tvolumeState := asw.GetVolumeMountState(volumeName, podName)\n\n\t// only uncertain volumes are reconstructed\n\tif volumeState != operationexecutor.VolumeMountUncertain {\n\t\treturn false\n\t}\n\n\tasw.RLock()\n\tdefer asw.RUnlock()\n\tpodMap, ok := asw.foundDuringReconstruction[volumeName]\n\tif !ok {\n\t\treturn false\n\t}\n\t_, foundPod := podMap[podName]\n\treturn foundPod\n}","line":{"from":377,"to":393}} {"id":100007936,"name":"CheckAndMarkVolumeAsUncertainViaReconstruction","signature":"func (asw *actualStateOfWorld) CheckAndMarkVolumeAsUncertainViaReconstruction(opts operationexecutor.MarkVolumeOpts) (bool, error)","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) CheckAndMarkVolumeAsUncertainViaReconstruction(opts operationexecutor.MarkVolumeOpts) (bool, error) {\n\tasw.Lock()\n\tdefer asw.Unlock()\n\n\tvolumeObj, volumeExists := asw.attachedVolumes[opts.VolumeName]\n\tif !volumeExists {\n\t\treturn false, nil\n\t}\n\n\tpodObj, podExists := volumeObj.mountedPods[opts.PodName]\n\tif podExists {\n\t\t// if volume mount was uncertain we should keep trying to unmount the volume\n\t\tif podObj.volumeMountStateForPod == operationexecutor.VolumeMountUncertain {\n\t\t\treturn false, nil\n\t\t}\n\t\tif podObj.volumeMountStateForPod == operationexecutor.VolumeMounted {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\tpodName := opts.PodName\n\tpodUID := opts.PodUID\n\tvolumeName := opts.VolumeName\n\tmounter := opts.Mounter\n\tblockVolumeMapper := opts.BlockVolumeMapper\n\touterVolumeSpecName := opts.OuterVolumeSpecName\n\tvolumeGidValue := opts.VolumeGidVolume\n\tvolumeSpec := opts.VolumeSpec\n\n\tpodObj = mountedPod{\n\t\tpodName: podName,\n\t\tpodUID: podUID,\n\t\tmounter: mounter,\n\t\tblockVolumeMapper: blockVolumeMapper,\n\t\touterVolumeSpecName: outerVolumeSpecName,\n\t\tvolumeGidValue: volumeGidValue,\n\t\tvolumeSpec: volumeSpec,\n\t\tremountRequired: false,\n\t\tvolumeMountStateForPod: operationexecutor.VolumeMountUncertain,\n\t}\n\n\tif mounter != nil {\n\t\t// The mounter stored in the object may have old information,\n\t\t// use the newest one.\n\t\tpodObj.mounter = mounter\n\t}\n\n\tasw.attachedVolumes[volumeName].mountedPods[podName] = podObj\n\n\tpodMap, ok := asw.foundDuringReconstruction[opts.VolumeName]\n\tif !ok {\n\t\tpodMap = map[volumetypes.UniquePodName]types.UID{}\n\t}\n\tpodMap[opts.PodName] = opts.PodUID\n\tasw.foundDuringReconstruction[opts.VolumeName] = podMap\n\treturn true, nil\n}","line":{"from":395,"to":451}} {"id":100007937,"name":"CheckAndMarkDeviceUncertainViaReconstruction","signature":"func (asw *actualStateOfWorld) CheckAndMarkDeviceUncertainViaReconstruction(volumeName v1.UniqueVolumeName, deviceMountPath string) bool","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) CheckAndMarkDeviceUncertainViaReconstruction(volumeName v1.UniqueVolumeName, deviceMountPath string) bool {\n\tasw.Lock()\n\tdefer asw.Unlock()\n\n\tvolumeObj, volumeExists := asw.attachedVolumes[volumeName]\n\t// CheckAndMarkDeviceUncertainViaReconstruction requires volume to be marked as attached, so if\n\t// volume does not exist in ASOW or is in any state other than DeviceNotMounted we should return\n\tif !volumeExists || volumeObj.deviceMountState != operationexecutor.DeviceNotMounted {\n\t\treturn false\n\t}\n\n\tvolumeObj.deviceMountState = operationexecutor.DeviceMountUncertain\n\t// we are only changing deviceMountPath because devicePath at at this stage is\n\t// determined from node object.\n\tvolumeObj.deviceMountPath = deviceMountPath\n\tasw.attachedVolumes[volumeName] = volumeObj\n\treturn true\n\n}","line":{"from":453,"to":471}} {"id":100007938,"name":"MarkVolumeAsMounted","signature":"func (asw *actualStateOfWorld) MarkVolumeAsMounted(markVolumeOpts operationexecutor.MarkVolumeOpts) error","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) MarkVolumeAsMounted(markVolumeOpts operationexecutor.MarkVolumeOpts) error {\n\treturn asw.AddPodToVolume(markVolumeOpts)\n}","line":{"from":473,"to":475}} {"id":100007939,"name":"AddVolumeToReportAsAttached","signature":"func (asw *actualStateOfWorld) AddVolumeToReportAsAttached(logger klog.Logger, volumeName v1.UniqueVolumeName, nodeName types.NodeName)","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) AddVolumeToReportAsAttached(logger klog.Logger, volumeName v1.UniqueVolumeName, nodeName types.NodeName) {\n\t// no operation for kubelet side\n}","line":{"from":477,"to":479}} {"id":100007940,"name":"RemoveVolumeFromReportAsAttached","signature":"func (asw *actualStateOfWorld) RemoveVolumeFromReportAsAttached(volumeName v1.UniqueVolumeName, nodeName types.NodeName) error","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) RemoveVolumeFromReportAsAttached(volumeName v1.UniqueVolumeName, nodeName types.NodeName) error {\n\t// no operation for kubelet side\n\treturn nil\n}","line":{"from":481,"to":484}} {"id":100007941,"name":"MarkVolumeAsUnmounted","signature":"func (asw *actualStateOfWorld) MarkVolumeAsUnmounted(","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) MarkVolumeAsUnmounted(\n\tpodName volumetypes.UniquePodName, volumeName v1.UniqueVolumeName) error {\n\treturn asw.DeletePodFromVolume(podName, volumeName)\n}","line":{"from":486,"to":489}} {"id":100007942,"name":"MarkDeviceAsMounted","signature":"func (asw *actualStateOfWorld) MarkDeviceAsMounted(","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) MarkDeviceAsMounted(\n\tvolumeName v1.UniqueVolumeName, devicePath, deviceMountPath, seLinuxMountContext string) error {\n\treturn asw.SetDeviceMountState(volumeName, operationexecutor.DeviceGloballyMounted, devicePath, deviceMountPath, seLinuxMountContext)\n}","line":{"from":491,"to":494}} {"id":100007943,"name":"MarkDeviceAsUncertain","signature":"func (asw *actualStateOfWorld) MarkDeviceAsUncertain(","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) MarkDeviceAsUncertain(\n\tvolumeName v1.UniqueVolumeName, devicePath, deviceMountPath, seLinuxMountContext string) error {\n\treturn asw.SetDeviceMountState(volumeName, operationexecutor.DeviceMountUncertain, devicePath, deviceMountPath, seLinuxMountContext)\n}","line":{"from":496,"to":499}} {"id":100007944,"name":"MarkVolumeMountAsUncertain","signature":"func (asw *actualStateOfWorld) MarkVolumeMountAsUncertain(markVolumeOpts operationexecutor.MarkVolumeOpts) error","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) MarkVolumeMountAsUncertain(markVolumeOpts operationexecutor.MarkVolumeOpts) error {\n\tmarkVolumeOpts.VolumeMountState = operationexecutor.VolumeMountUncertain\n\treturn asw.AddPodToVolume(markVolumeOpts)\n}","line":{"from":501,"to":504}} {"id":100007945,"name":"MarkDeviceAsUnmounted","signature":"func (asw *actualStateOfWorld) MarkDeviceAsUnmounted(","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) MarkDeviceAsUnmounted(\n\tvolumeName v1.UniqueVolumeName) error {\n\treturn asw.SetDeviceMountState(volumeName, operationexecutor.DeviceNotMounted, \"\", \"\", \"\")\n}","line":{"from":506,"to":509}} {"id":100007946,"name":"UpdateReconstructedDevicePath","signature":"func (asw *actualStateOfWorld) UpdateReconstructedDevicePath(volumeName v1.UniqueVolumeName, devicePath string)","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) UpdateReconstructedDevicePath(volumeName v1.UniqueVolumeName, devicePath string) {\n\tasw.Lock()\n\tdefer asw.Unlock()\n\n\tvolumeObj, volumeExists := asw.attachedVolumes[volumeName]\n\tif !volumeExists {\n\t\treturn\n\t}\n\tif volumeObj.deviceMountState != operationexecutor.DeviceMountUncertain {\n\t\t// Reconciler must have updated volume state, i.e. when a pod uses the volume and\n\t\t// succeeded mounting the volume. Such update has fixed the device path.\n\t\treturn\n\t}\n\n\tvolumeObj.devicePath = devicePath\n\tasw.attachedVolumes[volumeName] = volumeObj\n}","line":{"from":511,"to":527}} {"id":100007947,"name":"GetDeviceMountState","signature":"func (asw *actualStateOfWorld) GetDeviceMountState(volumeName v1.UniqueVolumeName) operationexecutor.DeviceMountState","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) GetDeviceMountState(volumeName v1.UniqueVolumeName) operationexecutor.DeviceMountState {\n\tasw.RLock()\n\tdefer asw.RUnlock()\n\n\tvolumeObj, volumeExists := asw.attachedVolumes[volumeName]\n\tif !volumeExists {\n\t\treturn operationexecutor.DeviceNotMounted\n\t}\n\n\treturn volumeObj.deviceMountState\n}","line":{"from":529,"to":539}} {"id":100007948,"name":"MarkForInUseExpansionError","signature":"func (asw *actualStateOfWorld) MarkForInUseExpansionError(volumeName v1.UniqueVolumeName)","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) MarkForInUseExpansionError(volumeName v1.UniqueVolumeName) {\n\tasw.Lock()\n\tdefer asw.Unlock()\n\n\tvolumeObj, ok := asw.attachedVolumes[volumeName]\n\tif ok {\n\t\tvolumeObj.volumeInUseErrorForExpansion = true\n\t\tasw.attachedVolumes[volumeName] = volumeObj\n\t}\n}","line":{"from":541,"to":550}} {"id":100007949,"name":"GetVolumeMountState","signature":"func (asw *actualStateOfWorld) GetVolumeMountState(volumeName v1.UniqueVolumeName, podName volumetypes.UniquePodName) operationexecutor.VolumeMountState","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) GetVolumeMountState(volumeName v1.UniqueVolumeName, podName volumetypes.UniquePodName) operationexecutor.VolumeMountState {\n\tasw.RLock()\n\tdefer asw.RUnlock()\n\n\tvolumeObj, volumeExists := asw.attachedVolumes[volumeName]\n\tif !volumeExists {\n\t\treturn operationexecutor.VolumeNotMounted\n\t}\n\n\tpodObj, podExists := volumeObj.mountedPods[podName]\n\tif !podExists {\n\t\treturn operationexecutor.VolumeNotMounted\n\t}\n\treturn podObj.volumeMountStateForPod\n}","line":{"from":552,"to":566}} {"id":100007950,"name":"IsVolumeMountedElsewhere","signature":"func (asw *actualStateOfWorld) IsVolumeMountedElsewhere(volumeName v1.UniqueVolumeName, podName volumetypes.UniquePodName) bool","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) IsVolumeMountedElsewhere(volumeName v1.UniqueVolumeName, podName volumetypes.UniquePodName) bool {\n\tasw.RLock()\n\tdefer asw.RUnlock()\n\n\tvolumeObj, volumeExists := asw.attachedVolumes[volumeName]\n\tif !volumeExists {\n\t\treturn false\n\t}\n\n\tfor _, podObj := range volumeObj.mountedPods {\n\t\tif podName != podObj.podName {\n\t\t\t// Treat uncertain mount state as mounted until certain.\n\t\t\tif podObj.volumeMountStateForPod != operationexecutor.VolumeNotMounted {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":568,"to":586}} {"id":100007951,"name":"addVolume","signature":"func (asw *actualStateOfWorld) addVolume(","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"// addVolume adds the given volume to the cache indicating the specified\n// volume is attached to this node. If no volume name is supplied, a unique\n// volume name is generated from the volumeSpec and returned on success. If a\n// volume with the same generated name already exists, this is a noop. If no\n// volume plugin can support the given volumeSpec or more than one plugin can\n// support it, an error is returned.\nfunc (asw *actualStateOfWorld) addVolume(\n\tvolumeName v1.UniqueVolumeName, volumeSpec *volume.Spec, devicePath string) error {\n\tasw.Lock()\n\tdefer asw.Unlock()\n\n\tvolumePlugin, err := asw.volumePluginMgr.FindPluginBySpec(volumeSpec)\n\tif err != nil || volumePlugin == nil {\n\t\treturn fmt.Errorf(\n\t\t\t\"failed to get Plugin from volumeSpec for volume %q err=%v\",\n\t\t\tvolumeSpec.Name(),\n\t\t\terr)\n\t}\n\n\tif len(volumeName) == 0 {\n\t\tvolumeName, err = util.GetUniqueVolumeNameFromSpec(volumePlugin, volumeSpec)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"failed to GetUniqueVolumeNameFromSpec for volumeSpec %q using volume plugin %q err=%v\",\n\t\t\t\tvolumeSpec.Name(),\n\t\t\t\tvolumePlugin.GetPluginName(),\n\t\t\t\terr)\n\t\t}\n\t}\n\n\tpluginIsAttachable := false\n\tif attachablePlugin, err := asw.volumePluginMgr.FindAttachablePluginBySpec(volumeSpec); err == nil \u0026\u0026 attachablePlugin != nil {\n\t\tpluginIsAttachable = true\n\t}\n\n\tvolumeObj, volumeExists := asw.attachedVolumes[volumeName]\n\tif !volumeExists {\n\t\tvolumeObj = attachedVolume{\n\t\t\tvolumeName: volumeName,\n\t\t\tspec: volumeSpec,\n\t\t\tmountedPods: make(map[volumetypes.UniquePodName]mountedPod),\n\t\t\tpluginName: volumePlugin.GetPluginName(),\n\t\t\tpluginIsAttachable: pluginIsAttachable,\n\t\t\tdeviceMountState: operationexecutor.DeviceNotMounted,\n\t\t\tdevicePath: devicePath,\n\t\t}\n\t} else {\n\t\t// If volume object already exists, update the fields such as device path\n\t\tvolumeObj.devicePath = devicePath\n\t\tklog.V(2).InfoS(\"Volume is already added to attachedVolume list, update device path\", \"volumeName\", volumeName, \"path\", devicePath)\n\t}\n\tasw.attachedVolumes[volumeName] = volumeObj\n\n\treturn nil\n}","line":{"from":588,"to":642}} {"id":100007952,"name":"AddPodToVolume","signature":"func (asw *actualStateOfWorld) AddPodToVolume(markVolumeOpts operationexecutor.MarkVolumeOpts) error","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) AddPodToVolume(markVolumeOpts operationexecutor.MarkVolumeOpts) error {\n\tpodName := markVolumeOpts.PodName\n\tpodUID := markVolumeOpts.PodUID\n\tvolumeName := markVolumeOpts.VolumeName\n\tmounter := markVolumeOpts.Mounter\n\tblockVolumeMapper := markVolumeOpts.BlockVolumeMapper\n\touterVolumeSpecName := markVolumeOpts.OuterVolumeSpecName\n\tvolumeGidValue := markVolumeOpts.VolumeGidVolume\n\tvolumeSpec := markVolumeOpts.VolumeSpec\n\tasw.Lock()\n\tdefer asw.Unlock()\n\n\tvolumeObj, volumeExists := asw.attachedVolumes[volumeName]\n\tif !volumeExists {\n\t\treturn fmt.Errorf(\n\t\t\t\"no volume with the name %q exists in the list of attached volumes\",\n\t\t\tvolumeName)\n\t}\n\n\tpodObj, podExists := volumeObj.mountedPods[podName]\n\n\tupdateUncertainVolume := false\n\tif podExists {\n\t\t// Update uncertain volumes - the new markVolumeOpts may have updated information.\n\t\t// Especially reconstructed volumes (marked as uncertain during reconstruction) need\n\t\t// an update.\n\t\tupdateUncertainVolume = utilfeature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) \u0026\u0026 podObj.volumeMountStateForPod == operationexecutor.VolumeMountUncertain\n\t}\n\tif !podExists || updateUncertainVolume {\n\t\t// Add new mountedPod or update existing one.\n\t\tpodObj = mountedPod{\n\t\t\tpodName: podName,\n\t\t\tpodUID: podUID,\n\t\t\tmounter: mounter,\n\t\t\tblockVolumeMapper: blockVolumeMapper,\n\t\t\touterVolumeSpecName: outerVolumeSpecName,\n\t\t\tvolumeGidValue: volumeGidValue,\n\t\t\tvolumeSpec: volumeSpec,\n\t\t\tvolumeMountStateForPod: markVolumeOpts.VolumeMountState,\n\t\t\tseLinuxMountContext: markVolumeOpts.SELinuxMountContext,\n\t\t}\n\t}\n\n\t// If pod exists, reset remountRequired value\n\tpodObj.remountRequired = false\n\tpodObj.volumeMountStateForPod = markVolumeOpts.VolumeMountState\n\n\t// if volume is mounted successfully, then it should be removed from foundDuringReconstruction map\n\tif markVolumeOpts.VolumeMountState == operationexecutor.VolumeMounted {\n\t\tdelete(asw.foundDuringReconstruction[volumeName], podName)\n\t}\n\tif mounter != nil {\n\t\t// The mounter stored in the object may have old information,\n\t\t// use the newest one.\n\t\tpodObj.mounter = mounter\n\t}\n\tasw.attachedVolumes[volumeName].mountedPods[podName] = podObj\n\tif utilfeature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {\n\t\t// Store the mount context also in the AttachedVolume to have a global volume context\n\t\t// for a quick comparison in PodExistsInVolume.\n\t\tif volumeObj.seLinuxMountContext == nil {\n\t\t\tvolumeObj.seLinuxMountContext = \u0026markVolumeOpts.SELinuxMountContext\n\t\t\tasw.attachedVolumes[volumeName] = volumeObj\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":644,"to":711}} {"id":100007953,"name":"MarkVolumeAsResized","signature":"func (asw *actualStateOfWorld) MarkVolumeAsResized(volumeName v1.UniqueVolumeName, claimSize *resource.Quantity) bool","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) MarkVolumeAsResized(volumeName v1.UniqueVolumeName, claimSize *resource.Quantity) bool {\n\tasw.Lock()\n\tdefer asw.Unlock()\n\n\tvolumeObj, ok := asw.attachedVolumes[volumeName]\n\tif ok {\n\t\tvolumeObj.persistentVolumeSize = claimSize\n\t\tasw.attachedVolumes[volumeName] = volumeObj\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":713,"to":724}} {"id":100007954,"name":"MarkRemountRequired","signature":"func (asw *actualStateOfWorld) MarkRemountRequired(","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) MarkRemountRequired(\n\tpodName volumetypes.UniquePodName) {\n\tasw.Lock()\n\tdefer asw.Unlock()\n\tfor volumeName, volumeObj := range asw.attachedVolumes {\n\t\tif podObj, podExists := volumeObj.mountedPods[podName]; podExists {\n\t\t\tvolumePlugin, err :=\n\t\t\t\tasw.volumePluginMgr.FindPluginBySpec(podObj.volumeSpec)\n\t\t\tif err != nil || volumePlugin == nil {\n\t\t\t\t// Log and continue processing\n\t\t\t\tklog.ErrorS(nil, \"MarkRemountRequired failed to FindPluginBySpec for volume\", \"uniquePodName\", podObj.podName, \"podUID\", podObj.podUID, \"volumeName\", volumeName, \"volumeSpecName\", podObj.volumeSpec.Name())\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif volumePlugin.RequiresRemount(podObj.volumeSpec) {\n\t\t\t\tpodObj.remountRequired = true\n\t\t\t\tasw.attachedVolumes[volumeName].mountedPods[podName] = podObj\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":726,"to":746}} {"id":100007955,"name":"SetDeviceMountState","signature":"func (asw *actualStateOfWorld) SetDeviceMountState(","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) SetDeviceMountState(\n\tvolumeName v1.UniqueVolumeName, deviceMountState operationexecutor.DeviceMountState, devicePath, deviceMountPath, seLinuxMountContext string) error {\n\tasw.Lock()\n\tdefer asw.Unlock()\n\n\tvolumeObj, volumeExists := asw.attachedVolumes[volumeName]\n\tif !volumeExists {\n\t\treturn fmt.Errorf(\n\t\t\t\"no volume with the name %q exists in the list of attached volumes\",\n\t\t\tvolumeName)\n\t}\n\n\tvolumeObj.deviceMountState = deviceMountState\n\tvolumeObj.deviceMountPath = deviceMountPath\n\tif devicePath != \"\" {\n\t\tvolumeObj.devicePath = devicePath\n\t}\n\tif utilfeature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {\n\t\tif seLinuxMountContext != \"\" {\n\t\t\tvolumeObj.seLinuxMountContext = \u0026seLinuxMountContext\n\t\t}\n\t}\n\tasw.attachedVolumes[volumeName] = volumeObj\n\treturn nil\n}","line":{"from":748,"to":772}} {"id":100007956,"name":"InitializeClaimSize","signature":"func (asw *actualStateOfWorld) InitializeClaimSize(logger klog.Logger, volumeName v1.UniqueVolumeName, claimSize *resource.Quantity)","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) InitializeClaimSize(logger klog.Logger, volumeName v1.UniqueVolumeName, claimSize *resource.Quantity) {\n\tasw.Lock()\n\tdefer asw.Unlock()\n\n\tvolumeObj, ok := asw.attachedVolumes[volumeName]\n\t// only set volume claim size if claimStatusSize is zero\n\t// this can happen when volume was rebuilt after kubelet startup\n\tif ok \u0026\u0026 volumeObj.persistentVolumeSize == nil {\n\t\tvolumeObj.persistentVolumeSize = claimSize\n\t\tasw.attachedVolumes[volumeName] = volumeObj\n\t}\n}","line":{"from":774,"to":785}} {"id":100007957,"name":"GetClaimSize","signature":"func (asw *actualStateOfWorld) GetClaimSize(volumeName v1.UniqueVolumeName) *resource.Quantity","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) GetClaimSize(volumeName v1.UniqueVolumeName) *resource.Quantity {\n\tasw.RLock()\n\tdefer asw.RUnlock()\n\n\tvolumeObj, ok := asw.attachedVolumes[volumeName]\n\tif ok {\n\t\treturn volumeObj.persistentVolumeSize\n\t}\n\treturn nil\n}","line":{"from":787,"to":796}} {"id":100007958,"name":"DeletePodFromVolume","signature":"func (asw *actualStateOfWorld) DeletePodFromVolume(","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) DeletePodFromVolume(\n\tpodName volumetypes.UniquePodName, volumeName v1.UniqueVolumeName) error {\n\tasw.Lock()\n\tdefer asw.Unlock()\n\n\tvolumeObj, volumeExists := asw.attachedVolumes[volumeName]\n\tif !volumeExists {\n\t\treturn fmt.Errorf(\n\t\t\t\"no volume with the name %q exists in the list of attached volumes\",\n\t\t\tvolumeName)\n\t}\n\n\t_, podExists := volumeObj.mountedPods[podName]\n\tif podExists {\n\t\tdelete(asw.attachedVolumes[volumeName].mountedPods, podName)\n\t}\n\n\t// if there were reconstructed volumes, we should remove them\n\t_, podExists = asw.foundDuringReconstruction[volumeName]\n\tif podExists {\n\t\tdelete(asw.foundDuringReconstruction[volumeName], podName)\n\t}\n\n\treturn nil\n}","line":{"from":798,"to":822}} {"id":100007959,"name":"DeleteVolume","signature":"func (asw *actualStateOfWorld) DeleteVolume(volumeName v1.UniqueVolumeName) error","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) DeleteVolume(volumeName v1.UniqueVolumeName) error {\n\tasw.Lock()\n\tdefer asw.Unlock()\n\n\tvolumeObj, volumeExists := asw.attachedVolumes[volumeName]\n\tif !volumeExists {\n\t\treturn nil\n\t}\n\n\tif len(volumeObj.mountedPods) != 0 {\n\t\treturn fmt.Errorf(\n\t\t\t\"failed to DeleteVolume %q, it still has %v mountedPods\",\n\t\t\tvolumeName,\n\t\t\tlen(volumeObj.mountedPods))\n\t}\n\n\tdelete(asw.attachedVolumes, volumeName)\n\tdelete(asw.foundDuringReconstruction, volumeName)\n\treturn nil\n}","line":{"from":824,"to":843}} {"id":100007960,"name":"PodExistsInVolume","signature":"func (asw *actualStateOfWorld) PodExistsInVolume(podName volumetypes.UniquePodName, volumeName v1.UniqueVolumeName, desiredVolumeSize resource.Quantity, seLinuxLabel string) (bool, string, error)","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) PodExistsInVolume(podName volumetypes.UniquePodName, volumeName v1.UniqueVolumeName, desiredVolumeSize resource.Quantity, seLinuxLabel string) (bool, string, error) {\n\tasw.RLock()\n\tdefer asw.RUnlock()\n\n\tvolumeObj, volumeExists := asw.attachedVolumes[volumeName]\n\tif !volumeExists {\n\t\treturn false, \"\", newVolumeNotAttachedError(volumeName)\n\t}\n\n\t// The volume exists, check its SELinux context mount option\n\tif utilfeature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {\n\t\tif volumeObj.seLinuxMountContext != nil \u0026\u0026 *volumeObj.seLinuxMountContext != seLinuxLabel {\n\t\t\tfullErr := newSELinuxMountMismatchError(volumeName)\n\t\t\treturn false, volumeObj.devicePath, fullErr\n\t\t}\n\t}\n\n\tpodObj, podExists := volumeObj.mountedPods[podName]\n\tif podExists {\n\t\t// if volume mount was uncertain we should keep trying to mount the volume\n\t\tif podObj.volumeMountStateForPod == operationexecutor.VolumeMountUncertain {\n\t\t\treturn false, volumeObj.devicePath, nil\n\t\t}\n\t\tif podObj.remountRequired {\n\t\t\treturn true, volumeObj.devicePath, newRemountRequiredError(volumeObj.volumeName, podObj.podName)\n\t\t}\n\t\tif currentSize, expandVolume := asw.volumeNeedsExpansion(volumeObj, desiredVolumeSize); expandVolume {\n\t\t\treturn true, volumeObj.devicePath, newFsResizeRequiredError(volumeObj.volumeName, podObj.podName, currentSize)\n\t\t}\n\t}\n\n\treturn podExists, volumeObj.devicePath, nil\n}","line":{"from":845,"to":877}} {"id":100007961,"name":"volumeNeedsExpansion","signature":"func (asw *actualStateOfWorld) volumeNeedsExpansion(volumeObj attachedVolume, desiredVolumeSize resource.Quantity) (resource.Quantity, bool)","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) volumeNeedsExpansion(volumeObj attachedVolume, desiredVolumeSize resource.Quantity) (resource.Quantity, bool) {\n\tcurrentSize := resource.Quantity{}\n\tif volumeObj.persistentVolumeSize != nil {\n\t\tcurrentSize = volumeObj.persistentVolumeSize.DeepCopy()\n\t}\n\tif volumeObj.volumeInUseErrorForExpansion {\n\t\treturn currentSize, false\n\t}\n\tif volumeObj.persistentVolumeSize == nil || desiredVolumeSize.IsZero() {\n\t\treturn currentSize, false\n\t}\n\n\tif desiredVolumeSize.Cmp(*volumeObj.persistentVolumeSize) \u003e 0 {\n\t\tvolumePlugin, err := asw.volumePluginMgr.FindNodeExpandablePluginBySpec(volumeObj.spec)\n\t\tif err != nil || volumePlugin == nil {\n\t\t\t// Log and continue processing\n\t\t\tklog.InfoS(\"PodExistsInVolume failed to find expandable plugin\",\n\t\t\t\t\"volume\", volumeObj.volumeName,\n\t\t\t\t\"volumeSpecName\", volumeObj.spec.Name())\n\t\t\treturn currentSize, false\n\t\t}\n\t\tif volumePlugin.RequiresFSResize() {\n\t\t\treturn currentSize, true\n\t\t}\n\t}\n\treturn currentSize, false\n}","line":{"from":879,"to":905}} {"id":100007962,"name":"PodRemovedFromVolume","signature":"func (asw *actualStateOfWorld) PodRemovedFromVolume(","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) PodRemovedFromVolume(\n\tpodName volumetypes.UniquePodName,\n\tvolumeName v1.UniqueVolumeName) bool {\n\tasw.RLock()\n\tdefer asw.RUnlock()\n\n\tvolumeObj, volumeExists := asw.attachedVolumes[volumeName]\n\tif !volumeExists {\n\t\treturn true\n\t}\n\n\tpodObj, podExists := volumeObj.mountedPods[podName]\n\tif podExists {\n\t\t// if volume mount was uncertain we should keep trying to unmount the volume\n\t\tif podObj.volumeMountStateForPod == operationexecutor.VolumeMountUncertain {\n\t\t\treturn false\n\t\t}\n\t\tif podObj.volumeMountStateForPod == operationexecutor.VolumeMounted {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":907,"to":929}} {"id":100007963,"name":"VolumeExistsWithSpecName","signature":"func (asw *actualStateOfWorld) VolumeExistsWithSpecName(podName volumetypes.UniquePodName, volumeSpecName string) bool","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) VolumeExistsWithSpecName(podName volumetypes.UniquePodName, volumeSpecName string) bool {\n\tasw.RLock()\n\tdefer asw.RUnlock()\n\tfor _, volumeObj := range asw.attachedVolumes {\n\t\tif podObj, podExists := volumeObj.mountedPods[podName]; podExists {\n\t\t\tif podObj.volumeSpec.Name() == volumeSpecName {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":931,"to":942}} {"id":100007964,"name":"VolumeExists","signature":"func (asw *actualStateOfWorld) VolumeExists(","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) VolumeExists(\n\tvolumeName v1.UniqueVolumeName) bool {\n\tasw.RLock()\n\tdefer asw.RUnlock()\n\n\t_, volumeExists := asw.attachedVolumes[volumeName]\n\treturn volumeExists\n}","line":{"from":944,"to":951}} {"id":100007965,"name":"GetMountedVolumes","signature":"func (asw *actualStateOfWorld) GetMountedVolumes() []MountedVolume","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) GetMountedVolumes() []MountedVolume {\n\tasw.RLock()\n\tdefer asw.RUnlock()\n\tmountedVolume := make([]MountedVolume, 0 /* len */, len(asw.attachedVolumes) /* cap */)\n\tfor _, volumeObj := range asw.attachedVolumes {\n\t\tfor _, podObj := range volumeObj.mountedPods {\n\t\t\tif podObj.volumeMountStateForPod == operationexecutor.VolumeMounted {\n\t\t\t\tmountedVolume = append(\n\t\t\t\t\tmountedVolume,\n\t\t\t\t\tgetMountedVolume(\u0026podObj, \u0026volumeObj))\n\t\t\t}\n\t\t}\n\t}\n\treturn mountedVolume\n}","line":{"from":953,"to":967}} {"id":100007966,"name":"GetAllMountedVolumes","signature":"func (asw *actualStateOfWorld) GetAllMountedVolumes() []MountedVolume","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"// GetAllMountedVolumes returns all volumes which could be locally mounted for a pod.\nfunc (asw *actualStateOfWorld) GetAllMountedVolumes() []MountedVolume {\n\tasw.RLock()\n\tdefer asw.RUnlock()\n\tmountedVolume := make([]MountedVolume, 0 /* len */, len(asw.attachedVolumes) /* cap */)\n\tfor _, volumeObj := range asw.attachedVolumes {\n\t\tfor _, podObj := range volumeObj.mountedPods {\n\t\t\tif podObj.volumeMountStateForPod == operationexecutor.VolumeMounted ||\n\t\t\t\tpodObj.volumeMountStateForPod == operationexecutor.VolumeMountUncertain {\n\t\t\t\tmountedVolume = append(\n\t\t\t\t\tmountedVolume,\n\t\t\t\t\tgetMountedVolume(\u0026podObj, \u0026volumeObj))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn mountedVolume\n}","line":{"from":969,"to":986}} {"id":100007967,"name":"GetMountedVolumesForPod","signature":"func (asw *actualStateOfWorld) GetMountedVolumesForPod(","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) GetMountedVolumesForPod(\n\tpodName volumetypes.UniquePodName) []MountedVolume {\n\tasw.RLock()\n\tdefer asw.RUnlock()\n\tmountedVolume := make([]MountedVolume, 0 /* len */, len(asw.attachedVolumes) /* cap */)\n\tfor _, volumeObj := range asw.attachedVolumes {\n\t\tfor mountedPodName, podObj := range volumeObj.mountedPods {\n\t\t\tif mountedPodName == podName \u0026\u0026 podObj.volumeMountStateForPod == operationexecutor.VolumeMounted {\n\t\t\t\tmountedVolume = append(\n\t\t\t\t\tmountedVolume,\n\t\t\t\t\tgetMountedVolume(\u0026podObj, \u0026volumeObj))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn mountedVolume\n}","line":{"from":988,"to":1004}} {"id":100007968,"name":"GetPossiblyMountedVolumesForPod","signature":"func (asw *actualStateOfWorld) GetPossiblyMountedVolumesForPod(","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) GetPossiblyMountedVolumesForPod(\n\tpodName volumetypes.UniquePodName) []MountedVolume {\n\tasw.RLock()\n\tdefer asw.RUnlock()\n\tmountedVolume := make([]MountedVolume, 0 /* len */, len(asw.attachedVolumes) /* cap */)\n\tfor _, volumeObj := range asw.attachedVolumes {\n\t\tfor mountedPodName, podObj := range volumeObj.mountedPods {\n\t\t\tif mountedPodName == podName \u0026\u0026\n\t\t\t\t(podObj.volumeMountStateForPod == operationexecutor.VolumeMounted ||\n\t\t\t\t\tpodObj.volumeMountStateForPod == operationexecutor.VolumeMountUncertain) {\n\t\t\t\tmountedVolume = append(\n\t\t\t\t\tmountedVolume,\n\t\t\t\t\tgetMountedVolume(\u0026podObj, \u0026volumeObj))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn mountedVolume\n}","line":{"from":1006,"to":1024}} {"id":100007969,"name":"GetGloballyMountedVolumes","signature":"func (asw *actualStateOfWorld) GetGloballyMountedVolumes() []AttachedVolume","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) GetGloballyMountedVolumes() []AttachedVolume {\n\tasw.RLock()\n\tdefer asw.RUnlock()\n\tgloballyMountedVolumes := make(\n\t\t[]AttachedVolume, 0 /* len */, len(asw.attachedVolumes) /* cap */)\n\tfor _, volumeObj := range asw.attachedVolumes {\n\t\tif volumeObj.deviceMountState == operationexecutor.DeviceGloballyMounted {\n\t\t\tgloballyMountedVolumes = append(\n\t\t\t\tgloballyMountedVolumes,\n\t\t\t\tasw.newAttachedVolume(\u0026volumeObj))\n\t\t}\n\t}\n\n\treturn globallyMountedVolumes\n}","line":{"from":1026,"to":1040}} {"id":100007970,"name":"GetAttachedVolumes","signature":"func (asw *actualStateOfWorld) GetAttachedVolumes() []AttachedVolume","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) GetAttachedVolumes() []AttachedVolume {\n\tasw.RLock()\n\tdefer asw.RUnlock()\n\tallAttachedVolumes := make(\n\t\t[]AttachedVolume, 0 /* len */, len(asw.attachedVolumes) /* cap */)\n\tfor _, volumeObj := range asw.attachedVolumes {\n\t\tallAttachedVolumes = append(\n\t\t\tallAttachedVolumes,\n\t\t\tasw.newAttachedVolume(\u0026volumeObj))\n\t}\n\n\treturn allAttachedVolumes\n}","line":{"from":1042,"to":1054}} {"id":100007971,"name":"GetUnmountedVolumes","signature":"func (asw *actualStateOfWorld) GetUnmountedVolumes() []AttachedVolume","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) GetUnmountedVolumes() []AttachedVolume {\n\tasw.RLock()\n\tdefer asw.RUnlock()\n\tunmountedVolumes := make([]AttachedVolume, 0 /* len */, len(asw.attachedVolumes) /* cap */)\n\tfor _, volumeObj := range asw.attachedVolumes {\n\t\tif len(volumeObj.mountedPods) == 0 {\n\t\t\tunmountedVolumes = append(\n\t\t\t\tunmountedVolumes,\n\t\t\t\tasw.newAttachedVolume(\u0026volumeObj))\n\t\t}\n\t}\n\n\treturn unmountedVolumes\n}","line":{"from":1056,"to":1069}} {"id":100007972,"name":"SyncReconstructedVolume","signature":"func (asw *actualStateOfWorld) SyncReconstructedVolume(volumeName v1.UniqueVolumeName, podName volumetypes.UniquePodName, outerVolumeSpecName string)","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) SyncReconstructedVolume(volumeName v1.UniqueVolumeName, podName volumetypes.UniquePodName, outerVolumeSpecName string) {\n\tasw.Lock()\n\tdefer asw.Unlock()\n\tif volumeObj, volumeExists := asw.attachedVolumes[volumeName]; volumeExists {\n\t\tif podObj, podExists := volumeObj.mountedPods[podName]; podExists {\n\t\t\tif podObj.outerVolumeSpecName != outerVolumeSpecName {\n\t\t\t\tpodObj.outerVolumeSpecName = outerVolumeSpecName\n\t\t\t\tasw.attachedVolumes[volumeName].mountedPods[podName] = podObj\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":1071,"to":1082}} {"id":100007973,"name":"newAttachedVolume","signature":"func (asw *actualStateOfWorld) newAttachedVolume(","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (asw *actualStateOfWorld) newAttachedVolume(\n\tattachedVolume *attachedVolume) AttachedVolume {\n\tseLinuxMountContext := \"\"\n\tif utilfeature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {\n\t\tif attachedVolume.seLinuxMountContext != nil {\n\t\t\tseLinuxMountContext = *attachedVolume.seLinuxMountContext\n\t\t}\n\t}\n\treturn AttachedVolume{\n\t\tAttachedVolume: operationexecutor.AttachedVolume{\n\t\t\tVolumeName: attachedVolume.volumeName,\n\t\t\tVolumeSpec: attachedVolume.spec,\n\t\t\tNodeName: asw.nodeName,\n\t\t\tPluginIsAttachable: attachedVolume.pluginIsAttachable,\n\t\t\tDevicePath: attachedVolume.devicePath,\n\t\t\tDeviceMountPath: attachedVolume.deviceMountPath,\n\t\t\tPluginName: attachedVolume.pluginName,\n\t\t\tSELinuxMountContext: seLinuxMountContext},\n\t\tDeviceMountState: attachedVolume.deviceMountState,\n\t\tSELinuxMountContext: seLinuxMountContext,\n\t}\n}","line":{"from":1084,"to":1105}} {"id":100007974,"name":"Error","signature":"func (err volumeNotAttachedError) Error() string","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (err volumeNotAttachedError) Error() string {\n\treturn fmt.Sprintf(\n\t\t\"volumeName %q does not exist in the list of attached volumes\",\n\t\terr.volumeName)\n}","line":{"from":1116,"to":1120}} {"id":100007975,"name":"newVolumeNotAttachedError","signature":"func newVolumeNotAttachedError(volumeName v1.UniqueVolumeName) error","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func newVolumeNotAttachedError(volumeName v1.UniqueVolumeName) error {\n\treturn volumeNotAttachedError{\n\t\tvolumeName: volumeName,\n\t}\n}","line":{"from":1122,"to":1126}} {"id":100007976,"name":"Error","signature":"func (err remountRequiredError) Error() string","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (err remountRequiredError) Error() string {\n\treturn fmt.Sprintf(\n\t\t\"volumeName %q is mounted to %q but should be remounted\",\n\t\terr.volumeName, err.podName)\n}","line":{"from":1140,"to":1144}} {"id":100007977,"name":"newRemountRequiredError","signature":"func newRemountRequiredError(","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func newRemountRequiredError(\n\tvolumeName v1.UniqueVolumeName, podName volumetypes.UniquePodName) error {\n\treturn remountRequiredError{\n\t\tvolumeName: volumeName,\n\t\tpodName: podName,\n\t}\n}","line":{"from":1146,"to":1152}} {"id":100007978,"name":"Error","signature":"func (err FsResizeRequiredError) Error() string","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (err FsResizeRequiredError) Error() string {\n\treturn fmt.Sprintf(\n\t\t\"volumeName %q mounted to %q needs to resize file system\",\n\t\terr.volumeName, err.podName)\n}","line":{"from":1163,"to":1167}} {"id":100007979,"name":"newFsResizeRequiredError","signature":"func newFsResizeRequiredError(","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func newFsResizeRequiredError(\n\tvolumeName v1.UniqueVolumeName, podName volumetypes.UniquePodName, currentSize resource.Quantity) error {\n\treturn FsResizeRequiredError{\n\t\tCurrentSize: currentSize,\n\t\tvolumeName: volumeName,\n\t\tpodName: podName,\n\t}\n}","line":{"from":1169,"to":1176}} {"id":100007980,"name":"IsFSResizeRequiredError","signature":"func IsFSResizeRequiredError(err error) bool","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"// IsFSResizeRequiredError returns true if the specified error is a\n// fsResizeRequiredError.\nfunc IsFSResizeRequiredError(err error) bool {\n\t_, ok := err.(FsResizeRequiredError)\n\treturn ok\n}","line":{"from":1178,"to":1183}} {"id":100007981,"name":"getMountedVolume","signature":"func getMountedVolume(","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"// getMountedVolume constructs and returns a MountedVolume object from the given\n// mountedPod and attachedVolume objects.\nfunc getMountedVolume(\n\tmountedPod *mountedPod, attachedVolume *attachedVolume) MountedVolume {\n\tseLinuxMountContext := \"\"\n\tif attachedVolume.seLinuxMountContext != nil {\n\t\tseLinuxMountContext = *attachedVolume.seLinuxMountContext\n\t}\n\treturn MountedVolume{\n\t\tMountedVolume: operationexecutor.MountedVolume{\n\t\t\tPodName: mountedPod.podName,\n\t\t\tVolumeName: attachedVolume.volumeName,\n\t\t\tInnerVolumeSpecName: mountedPod.volumeSpec.Name(),\n\t\t\tOuterVolumeSpecName: mountedPod.outerVolumeSpecName,\n\t\t\tPluginName: attachedVolume.pluginName,\n\t\t\tPodUID: mountedPod.podUID,\n\t\t\tMounter: mountedPod.mounter,\n\t\t\tBlockVolumeMapper: mountedPod.blockVolumeMapper,\n\t\t\tVolumeGidValue: mountedPod.volumeGidValue,\n\t\t\tVolumeSpec: mountedPod.volumeSpec,\n\t\t\tDeviceMountPath: attachedVolume.deviceMountPath,\n\t\t\tSELinuxMountContext: seLinuxMountContext}}\n\n}","line":{"from":1185,"to":1208}} {"id":100007982,"name":"Error","signature":"func (err seLinuxMountMismatchError) Error() string","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func (err seLinuxMountMismatchError) Error() string {\n\treturn fmt.Sprintf(\n\t\t\"waiting for unmount of volume %q, because it is already mounted to a different pod with a different SELinux label\",\n\t\terr.volumeName)\n}","line":{"from":1216,"to":1220}} {"id":100007983,"name":"newSELinuxMountMismatchError","signature":"func newSELinuxMountMismatchError(volumeName v1.UniqueVolumeName) error","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"func newSELinuxMountMismatchError(volumeName v1.UniqueVolumeName) error {\n\treturn seLinuxMountMismatchError{\n\t\tvolumeName: volumeName,\n\t}\n}","line":{"from":1222,"to":1226}} {"id":100007984,"name":"IsSELinuxMountMismatchError","signature":"func IsSELinuxMountMismatchError(err error) bool","file":"pkg/kubelet/volumemanager/cache/actual_state_of_world.go","code":"// IsSELinuxMountMismatchError returns true if the specified error is a\n// seLinuxMountMismatchError.\nfunc IsSELinuxMountMismatchError(err error) bool {\n\t_, ok := err.(seLinuxMountMismatchError)\n\treturn ok\n}","line":{"from":1228,"to":1233}} {"id":100007985,"name":"registerSELinuxMetrics","signature":"func registerSELinuxMetrics()","file":"pkg/kubelet/volumemanager/cache/desired_state_of_wold_selinux_metrics.go","code":"func registerSELinuxMetrics() {\n\tregisterMetrics.Do(func() {\n\t\tlegacyregistry.MustRegister(seLinuxContainerContextErrors)\n\t\tlegacyregistry.MustRegister(seLinuxContainerContextWarnings)\n\t\tlegacyregistry.MustRegister(seLinuxPodContextMismatchErrors)\n\t\tlegacyregistry.MustRegister(seLinuxPodContextMismatchWarnings)\n\t\tlegacyregistry.MustRegister(seLinuxVolumeContextMismatchErrors)\n\t\tlegacyregistry.MustRegister(seLinuxVolumeContextMismatchWarnings)\n\t\tlegacyregistry.MustRegister(seLinuxVolumesAdmitted)\n\t})\n}","line":{"from":74,"to":84}} {"id":100007986,"name":"NewDesiredStateOfWorld","signature":"func NewDesiredStateOfWorld(volumePluginMgr *volume.VolumePluginMgr, seLinuxTranslator util.SELinuxLabelTranslator) DesiredStateOfWorld","file":"pkg/kubelet/volumemanager/cache/desired_state_of_world.go","code":"// NewDesiredStateOfWorld returns a new instance of DesiredStateOfWorld.\nfunc NewDesiredStateOfWorld(volumePluginMgr *volume.VolumePluginMgr, seLinuxTranslator util.SELinuxLabelTranslator) DesiredStateOfWorld {\n\tif feature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {\n\t\tregisterSELinuxMetrics()\n\t}\n\treturn \u0026desiredStateOfWorld{\n\t\tvolumesToMount: make(map[v1.UniqueVolumeName]volumeToMount),\n\t\tvolumePluginMgr: volumePluginMgr,\n\t\tpodErrors: make(map[types.UniquePodName]sets.String),\n\t\tseLinuxTranslator: seLinuxTranslator,\n\t}\n}","line":{"from":145,"to":156}} {"id":100007987,"name":"AddPodToVolume","signature":"func (dsw *desiredStateOfWorld) AddPodToVolume(","file":"pkg/kubelet/volumemanager/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) AddPodToVolume(\n\tpodName types.UniquePodName,\n\tpod *v1.Pod,\n\tvolumeSpec *volume.Spec,\n\touterVolumeSpecName string,\n\tvolumeGidValue string,\n\tseLinuxContainerContexts []*v1.SELinuxOptions) (v1.UniqueVolumeName, error) {\n\tdsw.Lock()\n\tdefer dsw.Unlock()\n\n\tvolumePlugin, err := dsw.volumePluginMgr.FindPluginBySpec(volumeSpec)\n\tif err != nil || volumePlugin == nil {\n\t\treturn \"\", fmt.Errorf(\n\t\t\t\"failed to get Plugin from volumeSpec for volume %q err=%v\",\n\t\t\tvolumeSpec.Name(),\n\t\t\terr)\n\t}\n\n\tvar volumeName v1.UniqueVolumeName\n\n\t// The unique volume name used depends on whether the volume is attachable/device-mountable\n\t// or not.\n\tattachable := util.IsAttachableVolume(volumeSpec, dsw.volumePluginMgr)\n\tdeviceMountable := util.IsDeviceMountableVolume(volumeSpec, dsw.volumePluginMgr)\n\tif attachable || deviceMountable {\n\t\t// For attachable/device-mountable volumes, use the unique volume name as reported by\n\t\t// the plugin.\n\t\tvolumeName, err =\n\t\t\tutil.GetUniqueVolumeNameFromSpec(volumePlugin, volumeSpec)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\n\t\t\t\t\"failed to GetUniqueVolumeNameFromSpec for volumeSpec %q using volume plugin %q err=%v\",\n\t\t\t\tvolumeSpec.Name(),\n\t\t\t\tvolumePlugin.GetPluginName(),\n\t\t\t\terr)\n\t\t}\n\t} else {\n\t\t// For non-attachable and non-device-mountable volumes, generate a unique name based on the pod\n\t\t// namespace and name and the name of the volume within the pod.\n\t\tvolumeName = util.GetUniqueVolumeNameFromSpecWithPod(podName, volumePlugin, volumeSpec)\n\t}\n\n\tseLinuxFileLabel, pluginSupportsSELinuxContextMount, err := dsw.getSELinuxLabel(volumeSpec, seLinuxContainerContexts)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tklog.V(4).InfoS(\"expected volume SELinux label context\", \"volume\", volumeSpec.Name(), \"label\", seLinuxFileLabel)\n\n\tif vol, volumeExists := dsw.volumesToMount[volumeName]; !volumeExists {\n\t\tvar sizeLimit *resource.Quantity\n\t\tif volumeSpec.Volume != nil {\n\t\t\tif util.IsLocalEphemeralVolume(*volumeSpec.Volume) {\n\t\t\t\tpodLimits := resourcehelper.PodLimits(pod, resourcehelper.PodResourcesOptions{})\n\t\t\t\tephemeralStorageLimit := podLimits[v1.ResourceEphemeralStorage]\n\t\t\t\tsizeLimit = resource.NewQuantity(ephemeralStorageLimit.Value(), resource.BinarySI)\n\t\t\t\tif volumeSpec.Volume.EmptyDir != nil \u0026\u0026\n\t\t\t\t\tvolumeSpec.Volume.EmptyDir.SizeLimit != nil \u0026\u0026\n\t\t\t\t\tvolumeSpec.Volume.EmptyDir.SizeLimit.Value() \u003e 0 \u0026\u0026\n\t\t\t\t\t(sizeLimit.Value() == 0 || volumeSpec.Volume.EmptyDir.SizeLimit.Value() \u003c sizeLimit.Value()) {\n\t\t\t\t\tsizeLimit = resource.NewQuantity(volumeSpec.Volume.EmptyDir.SizeLimit.Value(), resource.BinarySI)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\teffectiveSELinuxMountLabel := seLinuxFileLabel\n\t\tif !util.VolumeSupportsSELinuxMount(volumeSpec) {\n\t\t\t// Clear SELinux label for the volume with unsupported access modes.\n\t\t\tklog.V(4).InfoS(\"volume does not support SELinux context mount, clearing the expected label\", \"volume\", volumeSpec.Name())\n\t\t\teffectiveSELinuxMountLabel = \"\"\n\t\t}\n\t\tif seLinuxFileLabel != \"\" {\n\t\t\tseLinuxVolumesAdmitted.Add(1.0)\n\t\t}\n\t\tvmt := volumeToMount{\n\t\t\tvolumeName: volumeName,\n\t\t\tpodsToMount: make(map[types.UniquePodName]podToMount),\n\t\t\tpluginIsAttachable: attachable,\n\t\t\tpluginIsDeviceMountable: deviceMountable,\n\t\t\tvolumeGidValue: volumeGidValue,\n\t\t\treportedInUse: false,\n\t\t\tdesiredSizeLimit: sizeLimit,\n\t\t\teffectiveSELinuxMountFileLabel: effectiveSELinuxMountLabel,\n\t\t\toriginalSELinuxLabel: seLinuxFileLabel,\n\t\t}\n\t\t// record desired size of the volume\n\t\tif volumeSpec.PersistentVolume != nil {\n\t\t\tpvCap := volumeSpec.PersistentVolume.Spec.Capacity.Storage()\n\t\t\tif pvCap != nil {\n\t\t\t\tpvCapCopy := pvCap.DeepCopy()\n\t\t\t\tvmt.persistentVolumeSize = \u0026pvCapCopy\n\t\t\t}\n\t\t}\n\t\tdsw.volumesToMount[volumeName] = vmt\n\t} else {\n\t\t// volume exists\n\t\tif pluginSupportsSELinuxContextMount {\n\t\t\tif seLinuxFileLabel != vol.originalSELinuxLabel {\n\t\t\t\t// TODO: update the error message after tests, e.g. add at least the conflicting pod names.\n\t\t\t\tfullErr := fmt.Errorf(\"conflicting SELinux labels of volume %s: %q and %q\", volumeSpec.Name(), vol.originalSELinuxLabel, seLinuxFileLabel)\n\t\t\t\tsupported := util.VolumeSupportsSELinuxMount(volumeSpec)\n\t\t\t\tif err := handleSELinuxMetricError(fullErr, supported, seLinuxVolumeContextMismatchWarnings, seLinuxVolumeContextMismatchErrors); err != nil {\n\t\t\t\t\treturn \"\", err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\toldPodMount, ok := dsw.volumesToMount[volumeName].podsToMount[podName]\n\tmountRequestTime := time.Now()\n\tif ok \u0026\u0026 !volumePlugin.RequiresRemount(volumeSpec) {\n\t\tmountRequestTime = oldPodMount.mountRequestTime\n\t}\n\n\t// Create new podToMount object. If it already exists, it is refreshed with\n\t// updated values (this is required for volumes that require remounting on\n\t// pod update, like Downward API volumes).\n\tdsw.volumesToMount[volumeName].podsToMount[podName] = podToMount{\n\t\tpodName: podName,\n\t\tpod: pod,\n\t\tvolumeSpec: volumeSpec,\n\t\touterVolumeSpecName: outerVolumeSpecName,\n\t\tmountRequestTime: mountRequestTime,\n\t}\n\treturn volumeName, nil\n}","line":{"from":259,"to":382}} {"id":100007988,"name":"getSELinuxLabel","signature":"func (dsw *desiredStateOfWorld) getSELinuxLabel(volumeSpec *volume.Spec, seLinuxContainerContexts []*v1.SELinuxOptions) (string, bool, error)","file":"pkg/kubelet/volumemanager/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) getSELinuxLabel(volumeSpec *volume.Spec, seLinuxContainerContexts []*v1.SELinuxOptions) (string, bool, error) {\n\tvar seLinuxFileLabel string\n\tvar pluginSupportsSELinuxContextMount bool\n\n\tif feature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {\n\t\tvar err error\n\n\t\tif !dsw.seLinuxTranslator.SELinuxEnabled() {\n\t\t\treturn \"\", false, nil\n\t\t}\n\n\t\tpluginSupportsSELinuxContextMount, err = dsw.getSELinuxMountSupport(volumeSpec)\n\t\tif err != nil {\n\t\t\treturn \"\", false, err\n\t\t}\n\t\tseLinuxSupported := util.VolumeSupportsSELinuxMount(volumeSpec)\n\t\tif pluginSupportsSELinuxContextMount {\n\t\t\t// Ensure that a volume that can be mounted with \"-o context=XYZ\" is\n\t\t\t// used only by containers with the same SELinux contexts.\n\t\t\tfor _, containerContext := range seLinuxContainerContexts {\n\t\t\t\tnewLabel, err := dsw.seLinuxTranslator.SELinuxOptionsToFileLabel(containerContext)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfullErr := fmt.Errorf(\"failed to construct SELinux label from context %q: %s\", containerContext, err)\n\t\t\t\t\tif err := handleSELinuxMetricError(fullErr, seLinuxSupported, seLinuxContainerContextWarnings, seLinuxContainerContextErrors); err != nil {\n\t\t\t\t\t\treturn \"\", false, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif seLinuxFileLabel == \"\" {\n\t\t\t\t\tseLinuxFileLabel = newLabel\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif seLinuxFileLabel != newLabel {\n\t\t\t\t\tfullErr := fmt.Errorf(\"volume %s is used with two different SELinux contexts in the same pod: %q, %q\", volumeSpec.Name(), seLinuxFileLabel, newLabel)\n\t\t\t\t\tif err := handleSELinuxMetricError(fullErr, seLinuxSupported, seLinuxPodContextMismatchWarnings, seLinuxPodContextMismatchErrors); err != nil {\n\t\t\t\t\t\treturn \"\", false, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// Volume plugin does not support SELinux context mount.\n\t\t\t// DSW will track this volume with SELinux label \"\", i.e. no mount with\n\t\t\t// -o context.\n\t\t\tseLinuxFileLabel = \"\"\n\t\t}\n\t}\n\treturn seLinuxFileLabel, pluginSupportsSELinuxContextMount, nil\n}","line":{"from":384,"to":430}} {"id":100007989,"name":"MarkVolumesReportedInUse","signature":"func (dsw *desiredStateOfWorld) MarkVolumesReportedInUse(","file":"pkg/kubelet/volumemanager/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) MarkVolumesReportedInUse(\n\treportedVolumes []v1.UniqueVolumeName) {\n\tdsw.Lock()\n\tdefer dsw.Unlock()\n\n\treportedVolumesMap := make(\n\t\tmap[v1.UniqueVolumeName]bool, len(reportedVolumes) /* capacity */)\n\n\tfor _, reportedVolume := range reportedVolumes {\n\t\treportedVolumesMap[reportedVolume] = true\n\t}\n\n\tfor volumeName, volumeObj := range dsw.volumesToMount {\n\t\t_, volumeReported := reportedVolumesMap[volumeName]\n\t\tvolumeObj.reportedInUse = volumeReported\n\t\tdsw.volumesToMount[volumeName] = volumeObj\n\t}\n}","line":{"from":432,"to":449}} {"id":100007990,"name":"DeletePodFromVolume","signature":"func (dsw *desiredStateOfWorld) DeletePodFromVolume(","file":"pkg/kubelet/volumemanager/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) DeletePodFromVolume(\n\tpodName types.UniquePodName, volumeName v1.UniqueVolumeName) {\n\tdsw.Lock()\n\tdefer dsw.Unlock()\n\n\tdelete(dsw.podErrors, podName)\n\n\tvolumeObj, volumeExists := dsw.volumesToMount[volumeName]\n\tif !volumeExists {\n\t\treturn\n\t}\n\n\tif _, podExists := volumeObj.podsToMount[podName]; !podExists {\n\t\treturn\n\t}\n\n\t// Delete pod if it exists\n\tdelete(dsw.volumesToMount[volumeName].podsToMount, podName)\n\n\tif len(dsw.volumesToMount[volumeName].podsToMount) == 0 {\n\t\t// Delete volume if no child pods left\n\t\tdelete(dsw.volumesToMount, volumeName)\n\t}\n}","line":{"from":451,"to":474}} {"id":100007991,"name":"UpdatePersistentVolumeSize","signature":"func (dsw *desiredStateOfWorld) UpdatePersistentVolumeSize(volumeName v1.UniqueVolumeName, size *resource.Quantity)","file":"pkg/kubelet/volumemanager/cache/desired_state_of_world.go","code":"// UpdatePersistentVolumeSize updates last known PV size. This is used for volume expansion and\n// should be only used for persistent volumes.\nfunc (dsw *desiredStateOfWorld) UpdatePersistentVolumeSize(volumeName v1.UniqueVolumeName, size *resource.Quantity) {\n\tdsw.Lock()\n\tdefer dsw.Unlock()\n\n\tvol, volExists := dsw.volumesToMount[volumeName]\n\tif volExists {\n\t\tvol.persistentVolumeSize = size\n\t\tdsw.volumesToMount[volumeName] = vol\n\t}\n}","line":{"from":476,"to":487}} {"id":100007992,"name":"VolumeExists","signature":"func (dsw *desiredStateOfWorld) VolumeExists(","file":"pkg/kubelet/volumemanager/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) VolumeExists(\n\tvolumeName v1.UniqueVolumeName, seLinuxMountContext string) bool {\n\tdsw.RLock()\n\tdefer dsw.RUnlock()\n\n\tvol, volumeExists := dsw.volumesToMount[volumeName]\n\tif !volumeExists {\n\t\treturn false\n\t}\n\tif feature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {\n\t\t// Handling two volumes with the same name and different SELinux context\n\t\t// as two *different* volumes here. Because if a volume is mounted with\n\t\t// an old SELinux context, it must be unmounted first and then mounted again\n\t\t// with the new context.\n\t\t//\n\t\t// This will happen when a pod A with context alpha_t runs and is being\n\t\t// terminated by kubelet and its volumes are being torn down, while a\n\t\t// pod B with context beta_t is already scheduled on the same node,\n\t\t// using the same volumes\n\t\t// The volumes from Pod A must be fully unmounted (incl. UnmountDevice)\n\t\t// and mounted with new SELinux mount options for pod B.\n\t\t// Without SELinux, kubelet can (and often does) reuse device mounted\n\t\t// for A.\n\t\treturn vol.effectiveSELinuxMountFileLabel == seLinuxMountContext\n\t}\n\treturn true\n}","line":{"from":489,"to":515}} {"id":100007993,"name":"PodExistsInVolume","signature":"func (dsw *desiredStateOfWorld) PodExistsInVolume(","file":"pkg/kubelet/volumemanager/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) PodExistsInVolume(\n\tpodName types.UniquePodName, volumeName v1.UniqueVolumeName, seLinuxMountOption string) bool {\n\tdsw.RLock()\n\tdefer dsw.RUnlock()\n\n\tvolumeObj, volumeExists := dsw.volumesToMount[volumeName]\n\tif !volumeExists {\n\t\treturn false\n\t}\n\n\tif feature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {\n\t\tif volumeObj.effectiveSELinuxMountFileLabel != seLinuxMountOption {\n\t\t\t// The volume is in DSW, but with a different SELinux mount option.\n\t\t\t// Report it as unused, so the volume is unmounted and mounted back\n\t\t\t// with the right SELinux option.\n\t\t\treturn false\n\t\t}\n\t}\n\n\t_, podExists := volumeObj.podsToMount[podName]\n\treturn podExists\n}","line":{"from":517,"to":538}} {"id":100007994,"name":"VolumeExistsWithSpecName","signature":"func (dsw *desiredStateOfWorld) VolumeExistsWithSpecName(podName types.UniquePodName, volumeSpecName string) bool","file":"pkg/kubelet/volumemanager/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) VolumeExistsWithSpecName(podName types.UniquePodName, volumeSpecName string) bool {\n\tdsw.RLock()\n\tdefer dsw.RUnlock()\n\tfor _, volumeObj := range dsw.volumesToMount {\n\t\tif podObj, podExists := volumeObj.podsToMount[podName]; podExists {\n\t\t\tif podObj.volumeSpec.Name() == volumeSpecName {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":540,"to":551}} {"id":100007995,"name":"GetPods","signature":"func (dsw *desiredStateOfWorld) GetPods() map[types.UniquePodName]bool","file":"pkg/kubelet/volumemanager/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) GetPods() map[types.UniquePodName]bool {\n\tdsw.RLock()\n\tdefer dsw.RUnlock()\n\n\tpodList := make(map[types.UniquePodName]bool)\n\tfor _, volumeObj := range dsw.volumesToMount {\n\t\tfor podName := range volumeObj.podsToMount {\n\t\t\tpodList[podName] = true\n\t\t}\n\t}\n\treturn podList\n}","line":{"from":553,"to":564}} {"id":100007996,"name":"GetVolumesToMount","signature":"func (dsw *desiredStateOfWorld) GetVolumesToMount() []VolumeToMount","file":"pkg/kubelet/volumemanager/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) GetVolumesToMount() []VolumeToMount {\n\tdsw.RLock()\n\tdefer dsw.RUnlock()\n\n\tvolumesToMount := make([]VolumeToMount, 0 /* len */, len(dsw.volumesToMount) /* cap */)\n\tfor volumeName, volumeObj := range dsw.volumesToMount {\n\t\tfor podName, podObj := range volumeObj.podsToMount {\n\t\t\tvmt := VolumeToMount{\n\t\t\t\tVolumeToMount: operationexecutor.VolumeToMount{\n\t\t\t\t\tVolumeName: volumeName,\n\t\t\t\t\tPodName: podName,\n\t\t\t\t\tPod: podObj.pod,\n\t\t\t\t\tVolumeSpec: podObj.volumeSpec,\n\t\t\t\t\tPluginIsAttachable: volumeObj.pluginIsAttachable,\n\t\t\t\t\tPluginIsDeviceMountable: volumeObj.pluginIsDeviceMountable,\n\t\t\t\t\tOuterVolumeSpecName: podObj.outerVolumeSpecName,\n\t\t\t\t\tVolumeGidValue: volumeObj.volumeGidValue,\n\t\t\t\t\tReportedInUse: volumeObj.reportedInUse,\n\t\t\t\t\tMountRequestTime: podObj.mountRequestTime,\n\t\t\t\t\tDesiredSizeLimit: volumeObj.desiredSizeLimit,\n\t\t\t\t\tSELinuxLabel: volumeObj.effectiveSELinuxMountFileLabel,\n\t\t\t\t},\n\t\t\t}\n\t\t\tif volumeObj.persistentVolumeSize != nil {\n\t\t\t\tvmt.PersistentVolumeSize = volumeObj.persistentVolumeSize.DeepCopy()\n\t\t\t}\n\t\t\tvolumesToMount = append(volumesToMount, vmt)\n\t\t}\n\t}\n\treturn volumesToMount\n}","line":{"from":566,"to":596}} {"id":100007997,"name":"AddErrorToPod","signature":"func (dsw *desiredStateOfWorld) AddErrorToPod(podName types.UniquePodName, err string)","file":"pkg/kubelet/volumemanager/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) AddErrorToPod(podName types.UniquePodName, err string) {\n\tdsw.Lock()\n\tdefer dsw.Unlock()\n\n\tif errs, found := dsw.podErrors[podName]; found {\n\t\tif errs.Len() \u003c= maxPodErrors {\n\t\t\terrs.Insert(err)\n\t\t}\n\t\treturn\n\t}\n\tdsw.podErrors[podName] = sets.NewString(err)\n}","line":{"from":598,"to":609}} {"id":100007998,"name":"PopPodErrors","signature":"func (dsw *desiredStateOfWorld) PopPodErrors(podName types.UniquePodName) []string","file":"pkg/kubelet/volumemanager/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) PopPodErrors(podName types.UniquePodName) []string {\n\tdsw.Lock()\n\tdefer dsw.Unlock()\n\n\tif errs, found := dsw.podErrors[podName]; found {\n\t\tdelete(dsw.podErrors, podName)\n\t\treturn errs.List()\n\t}\n\treturn []string{}\n}","line":{"from":611,"to":620}} {"id":100007999,"name":"GetPodsWithErrors","signature":"func (dsw *desiredStateOfWorld) GetPodsWithErrors() []types.UniquePodName","file":"pkg/kubelet/volumemanager/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) GetPodsWithErrors() []types.UniquePodName {\n\tdsw.RLock()\n\tdefer dsw.RUnlock()\n\n\tpods := make([]types.UniquePodName, 0, len(dsw.podErrors))\n\tfor podName := range dsw.podErrors {\n\t\tpods = append(pods, podName)\n\t}\n\treturn pods\n}","line":{"from":622,"to":631}} {"id":100008000,"name":"MarkVolumeAttachability","signature":"func (dsw *desiredStateOfWorld) MarkVolumeAttachability(volumeName v1.UniqueVolumeName, attachable bool)","file":"pkg/kubelet/volumemanager/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) MarkVolumeAttachability(volumeName v1.UniqueVolumeName, attachable bool) {\n\tdsw.Lock()\n\tdefer dsw.Unlock()\n\tvolumeObj, volumeExists := dsw.volumesToMount[volumeName]\n\tif !volumeExists {\n\t\treturn\n\t}\n\tvolumeObj.pluginIsAttachable = attachable\n\tdsw.volumesToMount[volumeName] = volumeObj\n}","line":{"from":633,"to":642}} {"id":100008001,"name":"getSELinuxMountSupport","signature":"func (dsw *desiredStateOfWorld) getSELinuxMountSupport(volumeSpec *volume.Spec) (bool, error)","file":"pkg/kubelet/volumemanager/cache/desired_state_of_world.go","code":"func (dsw *desiredStateOfWorld) getSELinuxMountSupport(volumeSpec *volume.Spec) (bool, error) {\n\treturn util.SupportsSELinuxContextMount(volumeSpec, dsw.volumePluginMgr)\n}","line":{"from":644,"to":646}} {"id":100008002,"name":"handleSELinuxMetricError","signature":"func handleSELinuxMetricError(err error, seLinuxSupported bool, warningMetric, errorMetric *metrics.Gauge) error","file":"pkg/kubelet/volumemanager/cache/desired_state_of_world.go","code":"// Based on isRWOP, bump the right warning / error metric and either consume the error or return it.\nfunc handleSELinuxMetricError(err error, seLinuxSupported bool, warningMetric, errorMetric *metrics.Gauge) error {\n\tif seLinuxSupported {\n\t\terrorMetric.Add(1.0)\n\t\treturn err\n\t}\n\n\t// This is not an error yet, but it will be when support for other access modes is added.\n\twarningMetric.Add(1.0)\n\tklog.V(4).ErrorS(err, \"Please report this error in https://github.com/kubernetes/enhancements/issues/1710, together with full Pod yaml file\")\n\treturn nil\n}","line":{"from":648,"to":659}} {"id":100008003,"name":"add","signature":"func (v volumeCount) add(state, plugin string)","file":"pkg/kubelet/volumemanager/metrics/metrics.go","code":"func (v volumeCount) add(state, plugin string) {\n\tcount, ok := v[state]\n\tif !ok {\n\t\tcount = map[string]int64{}\n\t}\n\tcount[plugin]++\n\tv[state] = count\n}","line":{"from":85,"to":92}} {"id":100008004,"name":"Register","signature":"func Register(asw cache.ActualStateOfWorld, dsw cache.DesiredStateOfWorld, pluginMgr *volume.VolumePluginMgr)","file":"pkg/kubelet/volumemanager/metrics/metrics.go","code":"// Register registers Volume Manager metrics.\nfunc Register(asw cache.ActualStateOfWorld, dsw cache.DesiredStateOfWorld, pluginMgr *volume.VolumePluginMgr) {\n\tregisterMetrics.Do(func() {\n\t\tlegacyregistry.CustomMustRegister(\u0026totalVolumesCollector{asw: asw, dsw: dsw, pluginMgr: pluginMgr})\n\t\tlegacyregistry.MustRegister(ReconstructVolumeOperationsTotal)\n\t\tlegacyregistry.MustRegister(ReconstructVolumeOperationsErrorsTotal)\n\t\tlegacyregistry.MustRegister(ForceCleanedFailedVolumeOperationsTotal)\n\t\tlegacyregistry.MustRegister(ForceCleanedFailedVolumeOperationsErrorsTotal)\n\t})\n}","line":{"from":94,"to":103}} {"id":100008005,"name":"DescribeWithStability","signature":"func (c *totalVolumesCollector) DescribeWithStability(ch chan\u003c- *metrics.Desc)","file":"pkg/kubelet/volumemanager/metrics/metrics.go","code":"// DescribeWithStability implements the metrics.StableCollector interface.\nfunc (c *totalVolumesCollector) DescribeWithStability(ch chan\u003c- *metrics.Desc) {\n\tch \u003c- totalVolumesDesc\n}","line":{"from":115,"to":118}} {"id":100008006,"name":"CollectWithStability","signature":"func (c *totalVolumesCollector) CollectWithStability(ch chan\u003c- metrics.Metric)","file":"pkg/kubelet/volumemanager/metrics/metrics.go","code":"// CollectWithStability implements the metrics.StableCollector interface.\nfunc (c *totalVolumesCollector) CollectWithStability(ch chan\u003c- metrics.Metric) {\n\tfor stateName, pluginCount := range c.getVolumeCount() {\n\t\tfor pluginName, count := range pluginCount {\n\t\t\tch \u003c- metrics.NewLazyConstMetric(totalVolumesDesc,\n\t\t\t\tmetrics.GaugeValue,\n\t\t\t\tfloat64(count),\n\t\t\t\tpluginName,\n\t\t\t\tstateName)\n\t\t}\n\t}\n}","line":{"from":120,"to":131}} {"id":100008007,"name":"getVolumeCount","signature":"func (c *totalVolumesCollector) getVolumeCount() volumeCount","file":"pkg/kubelet/volumemanager/metrics/metrics.go","code":"func (c *totalVolumesCollector) getVolumeCount() volumeCount {\n\tcounter := make(volumeCount)\n\tfor _, mountedVolume := range c.asw.GetMountedVolumes() {\n\t\tpluginName := volumeutil.GetFullQualifiedPluginNameForVolume(mountedVolume.PluginName, mountedVolume.VolumeSpec)\n\t\tif pluginName == \"\" {\n\t\t\tpluginName = pluginNameNotAvailable\n\t\t}\n\t\tcounter.add(\"actual_state_of_world\", pluginName)\n\t}\n\n\tfor _, volumeToMount := range c.dsw.GetVolumesToMount() {\n\t\tpluginName := pluginNameNotAvailable\n\t\tif plugin, err := c.pluginMgr.FindPluginBySpec(volumeToMount.VolumeSpec); err == nil {\n\t\t\tpluginName = volumeutil.GetFullQualifiedPluginNameForVolume(plugin.GetPluginName(), volumeToMount.VolumeSpec)\n\t\t}\n\t\tcounter.add(\"desired_state_of_world\", pluginName)\n\t}\n\treturn counter\n}","line":{"from":133,"to":151}} {"id":100008008,"name":"NewDesiredStateOfWorldPopulator","signature":"func NewDesiredStateOfWorldPopulator(","file":"pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go","code":"// NewDesiredStateOfWorldPopulator returns a new instance of\n// DesiredStateOfWorldPopulator.\n//\n// kubeClient - used to fetch PV and PVC objects from the API server\n// loopSleepDuration - the amount of time the populator loop sleeps between\n// successive executions\n//\n// podManager - the kubelet podManager that is the source of truth for the pods\n// that exist on this host\n//\n// desiredStateOfWorld - the cache to populate\nfunc NewDesiredStateOfWorldPopulator(\n\tkubeClient clientset.Interface,\n\tloopSleepDuration time.Duration,\n\tpodManager pod.Manager,\n\tpodStateProvider podStateProvider,\n\tdesiredStateOfWorld cache.DesiredStateOfWorld,\n\tactualStateOfWorld cache.ActualStateOfWorld,\n\tkubeContainerRuntime kubecontainer.Runtime,\n\tkeepTerminatedPodVolumes bool,\n\tcsiMigratedPluginManager csimigration.PluginManager,\n\tintreeToCSITranslator csimigration.InTreeToCSITranslator,\n\tvolumePluginMgr *volume.VolumePluginMgr) DesiredStateOfWorldPopulator {\n\treturn \u0026desiredStateOfWorldPopulator{\n\t\tkubeClient: kubeClient,\n\t\tloopSleepDuration: loopSleepDuration,\n\t\tpodManager: podManager,\n\t\tpodStateProvider: podStateProvider,\n\t\tdesiredStateOfWorld: desiredStateOfWorld,\n\t\tactualStateOfWorld: actualStateOfWorld,\n\t\tpods: processedPods{\n\t\t\tprocessedPods: make(map[volumetypes.UniquePodName]bool)},\n\t\tkubeContainerRuntime: kubeContainerRuntime,\n\t\tkeepTerminatedPodVolumes: keepTerminatedPodVolumes,\n\t\thasAddedPods: false,\n\t\thasAddedPodsLock: sync.RWMutex{},\n\t\tcsiMigratedPluginManager: csiMigratedPluginManager,\n\t\tintreeToCSITranslator: intreeToCSITranslator,\n\t\tvolumePluginMgr: volumePluginMgr,\n\t}\n}","line":{"from":79,"to":119}} {"id":100008009,"name":"Run","signature":"func (dswp *desiredStateOfWorldPopulator) Run(sourcesReady config.SourcesReady, stopCh \u003c-chan struct{})","file":"pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go","code":"func (dswp *desiredStateOfWorldPopulator) Run(sourcesReady config.SourcesReady, stopCh \u003c-chan struct{}) {\n\t// Wait for the completion of a loop that started after sources are all ready, then set hasAddedPods accordingly\n\tklog.InfoS(\"Desired state populator starts to run\")\n\twait.PollUntil(dswp.loopSleepDuration, func() (bool, error) {\n\t\tdone := sourcesReady.AllReady()\n\t\tdswp.populatorLoop()\n\t\treturn done, nil\n\t}, stopCh)\n\tdswp.hasAddedPodsLock.Lock()\n\tif !dswp.hasAddedPods {\n\t\tklog.InfoS(\"Finished populating initial desired state of world\")\n\t\tdswp.hasAddedPods = true\n\t}\n\tdswp.hasAddedPodsLock.Unlock()\n\twait.Until(dswp.populatorLoop, dswp.loopSleepDuration, stopCh)\n}","line":{"from":143,"to":158}} {"id":100008010,"name":"ReprocessPod","signature":"func (dswp *desiredStateOfWorldPopulator) ReprocessPod(","file":"pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go","code":"func (dswp *desiredStateOfWorldPopulator) ReprocessPod(\n\tpodName volumetypes.UniquePodName) {\n\tdswp.markPodProcessingFailed(podName)\n}","line":{"from":160,"to":163}} {"id":100008011,"name":"HasAddedPods","signature":"func (dswp *desiredStateOfWorldPopulator) HasAddedPods() bool","file":"pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go","code":"func (dswp *desiredStateOfWorldPopulator) HasAddedPods() bool {\n\tdswp.hasAddedPodsLock.RLock()\n\tdefer dswp.hasAddedPodsLock.RUnlock()\n\treturn dswp.hasAddedPods\n}","line":{"from":165,"to":169}} {"id":100008012,"name":"populatorLoop","signature":"func (dswp *desiredStateOfWorldPopulator) populatorLoop()","file":"pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go","code":"func (dswp *desiredStateOfWorldPopulator) populatorLoop() {\n\tdswp.findAndAddNewPods()\n\tdswp.findAndRemoveDeletedPods()\n}","line":{"from":171,"to":174}} {"id":100008013,"name":"findAndAddNewPods","signature":"func (dswp *desiredStateOfWorldPopulator) findAndAddNewPods()","file":"pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go","code":"// Iterate through all pods and add to desired state of world if they don't\n// exist but should\nfunc (dswp *desiredStateOfWorldPopulator) findAndAddNewPods() {\n\t// Map unique pod name to outer volume name to MountedVolume.\n\tmountedVolumesForPod := make(map[volumetypes.UniquePodName]map[string]cache.MountedVolume)\n\tfor _, mountedVolume := range dswp.actualStateOfWorld.GetMountedVolumes() {\n\t\tmountedVolumes, exist := mountedVolumesForPod[mountedVolume.PodName]\n\t\tif !exist {\n\t\t\tmountedVolumes = make(map[string]cache.MountedVolume)\n\t\t\tmountedVolumesForPod[mountedVolume.PodName] = mountedVolumes\n\t\t}\n\t\tmountedVolumes[mountedVolume.OuterVolumeSpecName] = mountedVolume\n\t}\n\n\tfor _, pod := range dswp.podManager.GetPods() {\n\t\t// Keep consistency of adding pod during reconstruction\n\t\tif dswp.hasAddedPods \u0026\u0026 dswp.podStateProvider.ShouldPodContainersBeTerminating(pod.UID) {\n\t\t\t// Do not (re)add volumes for pods that can't also be starting containers\n\t\t\tcontinue\n\t\t}\n\n\t\tif !dswp.hasAddedPods \u0026\u0026 dswp.podStateProvider.ShouldPodRuntimeBeRemoved(pod.UID) {\n\t\t\t// When kubelet restarts, we need to add pods to dsw if there is a possibility\n\t\t\t// that the container may still be running\n\t\t\tcontinue\n\t\t}\n\n\t\tdswp.processPodVolumes(pod, mountedVolumesForPod)\n\t}\n}","line":{"from":176,"to":205}} {"id":100008014,"name":"findAndRemoveDeletedPods","signature":"func (dswp *desiredStateOfWorldPopulator) findAndRemoveDeletedPods()","file":"pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go","code":"// Iterate through all pods in desired state of world, and remove if they no\n// longer exist\nfunc (dswp *desiredStateOfWorldPopulator) findAndRemoveDeletedPods() {\n\tfor _, volumeToMount := range dswp.desiredStateOfWorld.GetVolumesToMount() {\n\t\tpod, podExists := dswp.podManager.GetPodByUID(volumeToMount.Pod.UID)\n\t\tif podExists {\n\n\t\t\t// check if the attachability has changed for this volume\n\t\t\tif volumeToMount.PluginIsAttachable {\n\t\t\t\tattachableVolumePlugin, err := dswp.volumePluginMgr.FindAttachablePluginBySpec(volumeToMount.VolumeSpec)\n\t\t\t\t// only this means the plugin is truly non-attachable\n\t\t\t\tif err == nil \u0026\u0026 attachableVolumePlugin == nil {\n\t\t\t\t\t// It is not possible right now for a CSI plugin to be both attachable and non-deviceMountable\n\t\t\t\t\t// So the uniqueVolumeName should remain the same after the attachability change\n\t\t\t\t\tdswp.desiredStateOfWorld.MarkVolumeAttachability(volumeToMount.VolumeName, false)\n\t\t\t\t\tklog.InfoS(\"Volume changes from attachable to non-attachable\", \"volumeName\", volumeToMount.VolumeName)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Exclude known pods that we expect to be running\n\t\t\tif !dswp.podStateProvider.ShouldPodRuntimeBeRemoved(pod.UID) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif dswp.keepTerminatedPodVolumes {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\t// Once a pod has been deleted from kubelet pod manager, do not delete\n\t\t// it immediately from volume manager. Instead, check the kubelet\n\t\t// pod state provider to verify that all containers in the pod have been\n\t\t// terminated.\n\t\tif !dswp.podStateProvider.ShouldPodRuntimeBeRemoved(volumeToMount.Pod.UID) {\n\t\t\tklog.V(4).InfoS(\"Pod still has one or more containers in the non-exited state and will not be removed from desired state\", \"pod\", klog.KObj(volumeToMount.Pod))\n\t\t\tcontinue\n\t\t}\n\t\tvar volumeToMountSpecName string\n\t\tif volumeToMount.VolumeSpec != nil {\n\t\t\tvolumeToMountSpecName = volumeToMount.VolumeSpec.Name()\n\t\t}\n\t\tremoved := dswp.actualStateOfWorld.PodRemovedFromVolume(volumeToMount.PodName, volumeToMount.VolumeName)\n\t\tif removed \u0026\u0026 podExists {\n\t\t\tklog.V(4).InfoS(\"Actual state does not yet have volume mount information and pod still exists in pod manager, skip removing volume from desired state\", \"pod\", klog.KObj(volumeToMount.Pod), \"podUID\", volumeToMount.Pod.UID, \"volumeName\", volumeToMountSpecName)\n\t\t\tcontinue\n\t\t}\n\t\tklog.V(4).InfoS(\"Removing volume from desired state\", \"pod\", klog.KObj(volumeToMount.Pod), \"podUID\", volumeToMount.Pod.UID, \"volumeName\", volumeToMountSpecName)\n\t\tdswp.desiredStateOfWorld.DeletePodFromVolume(\n\t\t\tvolumeToMount.PodName, volumeToMount.VolumeName)\n\t\tdswp.deleteProcessedPod(volumeToMount.PodName)\n\t}\n\n\tpodsWithError := dswp.desiredStateOfWorld.GetPodsWithErrors()\n\tfor _, podName := range podsWithError {\n\t\tif _, podExists := dswp.podManager.GetPodByUID(types.UID(podName)); !podExists {\n\t\t\tdswp.desiredStateOfWorld.PopPodErrors(podName)\n\t\t}\n\t}\n}","line":{"from":207,"to":265}} {"id":100008015,"name":"processPodVolumes","signature":"func (dswp *desiredStateOfWorldPopulator) processPodVolumes(","file":"pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go","code":"// processPodVolumes processes the volumes in the given pod and adds them to the\n// desired state of the world.\nfunc (dswp *desiredStateOfWorldPopulator) processPodVolumes(\n\tpod *v1.Pod,\n\tmountedVolumesForPod map[volumetypes.UniquePodName]map[string]cache.MountedVolume) {\n\tif pod == nil {\n\t\treturn\n\t}\n\n\tuniquePodName := util.GetUniquePodName(pod)\n\tif dswp.podPreviouslyProcessed(uniquePodName) {\n\t\treturn\n\t}\n\n\tallVolumesAdded := true\n\tmounts, devices, seLinuxContainerContexts := util.GetPodVolumeNames(pod)\n\n\t// Process volume spec for each volume defined in pod\n\tfor _, podVolume := range pod.Spec.Volumes {\n\t\tif !mounts.Has(podVolume.Name) \u0026\u0026 !devices.Has(podVolume.Name) {\n\t\t\t// Volume is not used in the pod, ignore it.\n\t\t\tklog.V(4).InfoS(\"Skipping unused volume\", \"pod\", klog.KObj(pod), \"volumeName\", podVolume.Name)\n\t\t\tcontinue\n\t\t}\n\n\t\tpvc, volumeSpec, volumeGidValue, err :=\n\t\t\tdswp.createVolumeSpec(podVolume, pod, mounts, devices)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Error processing volume\", \"pod\", klog.KObj(pod), \"volumeName\", podVolume.Name)\n\t\t\tdswp.desiredStateOfWorld.AddErrorToPod(uniquePodName, err.Error())\n\t\t\tallVolumesAdded = false\n\t\t\tcontinue\n\t\t}\n\n\t\t// Add volume to desired state of world\n\t\tuniqueVolumeName, err := dswp.desiredStateOfWorld.AddPodToVolume(\n\t\t\tuniquePodName, pod, volumeSpec, podVolume.Name, volumeGidValue, seLinuxContainerContexts[podVolume.Name])\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to add volume to desiredStateOfWorld\", \"pod\", klog.KObj(pod), \"volumeName\", podVolume.Name, \"volumeSpecName\", volumeSpec.Name())\n\t\t\tdswp.desiredStateOfWorld.AddErrorToPod(uniquePodName, err.Error())\n\t\t\tallVolumesAdded = false\n\t\t} else {\n\t\t\tklog.V(4).InfoS(\"Added volume to desired state\", \"pod\", klog.KObj(pod), \"volumeName\", podVolume.Name, \"volumeSpecName\", volumeSpec.Name())\n\t\t}\n\t\tif !utilfeature.DefaultFeatureGate.Enabled(features.NewVolumeManagerReconstruction) {\n\t\t\t// sync reconstructed volume. This is necessary only when the old-style reconstruction is still used.\n\t\t\t// With reconstruct_new.go, AWS.MarkVolumeAsMounted will update the outer spec name of previously\n\t\t\t// uncertain volumes.\n\t\t\tdswp.actualStateOfWorld.SyncReconstructedVolume(uniqueVolumeName, uniquePodName, podVolume.Name)\n\t\t}\n\n\t\tdswp.checkVolumeFSResize(pod, podVolume, pvc, volumeSpec, uniquePodName, mountedVolumesForPod)\n\t}\n\n\t// some of the volume additions may have failed, should not mark this pod as fully processed\n\tif allVolumesAdded {\n\t\tdswp.markPodProcessed(uniquePodName)\n\t\t// New pod has been synced. Re-mount all volumes that need it\n\t\t// (e.g. DownwardAPI)\n\t\tdswp.actualStateOfWorld.MarkRemountRequired(uniquePodName)\n\t\t// Remove any stored errors for the pod, everything went well in this processPodVolumes\n\t\tdswp.desiredStateOfWorld.PopPodErrors(uniquePodName)\n\t} else if dswp.podHasBeenSeenOnce(uniquePodName) {\n\t\t// For the Pod which has been processed at least once, even though some volumes\n\t\t// may not have been reprocessed successfully this round, we still mark it as processed to avoid\n\t\t// processing it at a very high frequency. The pod will be reprocessed when volume manager calls\n\t\t// ReprocessPod() which is triggered by SyncPod.\n\t\tdswp.markPodProcessed(uniquePodName)\n\t}\n\n}","line":{"from":267,"to":337}} {"id":100008016,"name":"checkVolumeFSResize","signature":"func (dswp *desiredStateOfWorldPopulator) checkVolumeFSResize(","file":"pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go","code":"// checkVolumeFSResize records desired PVC size for a volume mounted by the pod.\n// It is used for comparison with actual size(coming from pvc.Status.Capacity) and calling\n// volume expansion on the node if needed.\nfunc (dswp *desiredStateOfWorldPopulator) checkVolumeFSResize(\n\tpod *v1.Pod,\n\tpodVolume v1.Volume,\n\tpvc *v1.PersistentVolumeClaim,\n\tvolumeSpec *volume.Spec,\n\tuniquePodName volumetypes.UniquePodName,\n\tmountedVolumesForPod map[volumetypes.UniquePodName]map[string]cache.MountedVolume) {\n\n\t// if a volumeSpec does not have PV or has InlineVolumeSpecForCSIMigration set or pvc is nil\n\t// we can't resize the volume and hence resizing should be skipped.\n\tif volumeSpec.PersistentVolume == nil || volumeSpec.InlineVolumeSpecForCSIMigration || pvc == nil {\n\t\t// Only PVC supports resize operation.\n\t\treturn\n\t}\n\n\tuniqueVolumeName, exist := getUniqueVolumeName(uniquePodName, podVolume.Name, mountedVolumesForPod)\n\tif !exist {\n\t\t// Volume not exist in ASW, we assume it hasn't been mounted yet. If it needs resize,\n\t\t// it will be handled as offline resize(if it indeed hasn't been mounted yet),\n\t\t// or online resize in subsequent loop(after we confirm it has been mounted).\n\t\treturn\n\t}\n\t// volumeSpec.ReadOnly is the value that determines if volume could be formatted when being mounted.\n\t// This is the same flag that determines filesystem resizing behaviour for offline resizing and hence\n\t// we should use it here. This value comes from Pod.spec.volumes.persistentVolumeClaim.readOnly.\n\tif volumeSpec.ReadOnly {\n\t\t// This volume is used as read only by this pod, we don't perform resize for read only volumes.\n\t\tklog.V(5).InfoS(\"Skip file system resize check for the volume, as the volume is mounted as readonly\", \"pod\", klog.KObj(pod), \"volumeName\", podVolume.Name)\n\t\treturn\n\t}\n\tpvCap := volumeSpec.PersistentVolume.Spec.Capacity.Storage()\n\tpvcStatusCap := pvc.Status.Capacity.Storage()\n\tdswp.desiredStateOfWorld.UpdatePersistentVolumeSize(uniqueVolumeName, pvCap)\n\n\t// in case the actualStateOfWorld was rebuild after kubelet restart ensure that claimSize is set to accurate value\n\tdswp.actualStateOfWorld.InitializeClaimSize(klog.TODO(), uniqueVolumeName, pvcStatusCap)\n}","line":{"from":339,"to":378}} {"id":100008017,"name":"getUniqueVolumeName","signature":"func getUniqueVolumeName(","file":"pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go","code":"func getUniqueVolumeName(\n\tpodName volumetypes.UniquePodName,\n\touterVolumeSpecName string,\n\tmountedVolumesForPod map[volumetypes.UniquePodName]map[string]cache.MountedVolume) (v1.UniqueVolumeName, bool) {\n\tmountedVolumes, exist := mountedVolumesForPod[podName]\n\tif !exist {\n\t\treturn \"\", false\n\t}\n\tmountedVolume, exist := mountedVolumes[outerVolumeSpecName]\n\tif !exist {\n\t\treturn \"\", false\n\t}\n\treturn mountedVolume.VolumeName, true\n}","line":{"from":380,"to":393}} {"id":100008018,"name":"podPreviouslyProcessed","signature":"func (dswp *desiredStateOfWorldPopulator) podPreviouslyProcessed(","file":"pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go","code":"// podPreviouslyProcessed returns true if the volumes for this pod have already\n// been processed/reprocessed by the populator. Otherwise, the volumes for this pod need to\n// be reprocessed.\nfunc (dswp *desiredStateOfWorldPopulator) podPreviouslyProcessed(\n\tpodName volumetypes.UniquePodName) bool {\n\tdswp.pods.RLock()\n\tdefer dswp.pods.RUnlock()\n\n\treturn dswp.pods.processedPods[podName]\n}","line":{"from":395,"to":404}} {"id":100008019,"name":"markPodProcessingFailed","signature":"func (dswp *desiredStateOfWorldPopulator) markPodProcessingFailed(","file":"pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go","code":"// markPodProcessingFailed marks the specified pod from processedPods as false to indicate that it failed processing\nfunc (dswp *desiredStateOfWorldPopulator) markPodProcessingFailed(\n\tpodName volumetypes.UniquePodName) {\n\tdswp.pods.Lock()\n\tdswp.pods.processedPods[podName] = false\n\tdswp.pods.Unlock()\n}","line":{"from":406,"to":412}} {"id":100008020,"name":"podHasBeenSeenOnce","signature":"func (dswp *desiredStateOfWorldPopulator) podHasBeenSeenOnce(","file":"pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go","code":"// podHasBeenSeenOnce returns true if the pod has been seen by the popoulator\n// at least once.\nfunc (dswp *desiredStateOfWorldPopulator) podHasBeenSeenOnce(\n\tpodName volumetypes.UniquePodName) bool {\n\tdswp.pods.RLock()\n\t_, exist := dswp.pods.processedPods[podName]\n\tdswp.pods.RUnlock()\n\treturn exist\n}","line":{"from":414,"to":422}} {"id":100008021,"name":"markPodProcessed","signature":"func (dswp *desiredStateOfWorldPopulator) markPodProcessed(","file":"pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go","code":"// markPodProcessed records that the volumes for the specified pod have been\n// processed by the populator\nfunc (dswp *desiredStateOfWorldPopulator) markPodProcessed(\n\tpodName volumetypes.UniquePodName) {\n\tdswp.pods.Lock()\n\tdefer dswp.pods.Unlock()\n\n\tdswp.pods.processedPods[podName] = true\n}","line":{"from":424,"to":432}} {"id":100008022,"name":"deleteProcessedPod","signature":"func (dswp *desiredStateOfWorldPopulator) deleteProcessedPod(","file":"pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go","code":"// deleteProcessedPod removes the specified pod from processedPods\nfunc (dswp *desiredStateOfWorldPopulator) deleteProcessedPod(\n\tpodName volumetypes.UniquePodName) {\n\tdswp.pods.Lock()\n\tdefer dswp.pods.Unlock()\n\n\tdelete(dswp.pods.processedPods, podName)\n}","line":{"from":434,"to":441}} {"id":100008023,"name":"createVolumeSpec","signature":"func (dswp *desiredStateOfWorldPopulator) createVolumeSpec(","file":"pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go","code":"// createVolumeSpec creates and returns a mutable volume.Spec object for the\n// specified volume. It dereference any PVC to get PV objects, if needed.\n// Returns an error if unable to obtain the volume at this time.\nfunc (dswp *desiredStateOfWorldPopulator) createVolumeSpec(\n\tpodVolume v1.Volume, pod *v1.Pod, mounts, devices sets.String) (*v1.PersistentVolumeClaim, *volume.Spec, string, error) {\n\tpvcSource := podVolume.VolumeSource.PersistentVolumeClaim\n\tisEphemeral := pvcSource == nil \u0026\u0026 podVolume.VolumeSource.Ephemeral != nil\n\tif isEphemeral {\n\t\t// Generic ephemeral inline volumes are handled the\n\t\t// same way as a PVC reference. The only additional\n\t\t// constraint (checked below) is that the PVC must be\n\t\t// owned by the pod.\n\t\tpvcSource = \u0026v1.PersistentVolumeClaimVolumeSource{\n\t\t\tClaimName: ephemeral.VolumeClaimName(pod, \u0026podVolume),\n\t\t}\n\t}\n\tif pvcSource != nil {\n\t\tklog.V(5).InfoS(\"Found PVC\", \"PVC\", klog.KRef(pod.Namespace, pvcSource.ClaimName))\n\t\t// If podVolume is a PVC, fetch the real PV behind the claim\n\t\tpvc, err := dswp.getPVCExtractPV(\n\t\t\tpod.Namespace, pvcSource.ClaimName)\n\t\tif err != nil {\n\t\t\treturn nil, nil, \"\", fmt.Errorf(\n\t\t\t\t\"error processing PVC %s/%s: %v\",\n\t\t\t\tpod.Namespace,\n\t\t\t\tpvcSource.ClaimName,\n\t\t\t\terr)\n\t\t}\n\t\tif isEphemeral {\n\t\t\tif err := ephemeral.VolumeIsForPod(pod, pvc); err != nil {\n\t\t\t\treturn nil, nil, \"\", err\n\t\t\t}\n\t\t}\n\t\tpvName, pvcUID := pvc.Spec.VolumeName, pvc.UID\n\t\tklog.V(5).InfoS(\"Found bound PV for PVC\", \"PVC\", klog.KRef(pod.Namespace, pvcSource.ClaimName), \"PVCUID\", pvcUID, \"PVName\", pvName)\n\t\t// Fetch actual PV object\n\t\tvolumeSpec, volumeGidValue, err :=\n\t\t\tdswp.getPVSpec(pvName, pvcSource.ReadOnly, pvcUID)\n\t\tif err != nil {\n\t\t\treturn nil, nil, \"\", fmt.Errorf(\n\t\t\t\t\"error processing PVC %s/%s: %v\",\n\t\t\t\tpod.Namespace,\n\t\t\t\tpvcSource.ClaimName,\n\t\t\t\terr)\n\t\t}\n\t\tklog.V(5).InfoS(\"Extracted volumeSpec from bound PV and PVC\", \"PVC\", klog.KRef(pod.Namespace, pvcSource.ClaimName), \"PVCUID\", pvcUID, \"PVName\", pvName, \"volumeSpecName\", volumeSpec.Name())\n\t\tmigratable, err := dswp.csiMigratedPluginManager.IsMigratable(volumeSpec)\n\t\tif err != nil {\n\t\t\treturn nil, nil, \"\", err\n\t\t}\n\t\tif migratable {\n\t\t\tvolumeSpec, err = csimigration.TranslateInTreeSpecToCSI(volumeSpec, pod.Namespace, dswp.intreeToCSITranslator)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, \"\", err\n\t\t\t}\n\t\t}\n\n\t\t// TODO: replace this with util.GetVolumeMode() when features.BlockVolume is removed.\n\t\t// The function will return the right value then.\n\t\tvolumeMode := v1.PersistentVolumeFilesystem\n\t\tif volumeSpec.PersistentVolume != nil \u0026\u0026 volumeSpec.PersistentVolume.Spec.VolumeMode != nil {\n\t\t\tvolumeMode = *volumeSpec.PersistentVolume.Spec.VolumeMode\n\t\t}\n\n\t\t// TODO: remove features.BlockVolume checks / comments after no longer needed\n\t\t// Error if a container has volumeMounts but the volumeMode of PVC isn't Filesystem.\n\t\t// Do not check feature gate here to make sure even when the feature is disabled in kubelet,\n\t\t// because controller-manager / API server can already contain block PVs / PVCs.\n\t\tif mounts.Has(podVolume.Name) \u0026\u0026 volumeMode != v1.PersistentVolumeFilesystem {\n\t\t\treturn nil, nil, \"\", fmt.Errorf(\n\t\t\t\t\"volume %s has volumeMode %s, but is specified in volumeMounts\",\n\t\t\t\tpodVolume.Name,\n\t\t\t\tvolumeMode)\n\t\t}\n\t\t// Error if a container has volumeDevices but the volumeMode of PVC isn't Block\n\t\tif devices.Has(podVolume.Name) \u0026\u0026 volumeMode != v1.PersistentVolumeBlock {\n\t\t\treturn nil, nil, \"\", fmt.Errorf(\n\t\t\t\t\"volume %s has volumeMode %s, but is specified in volumeDevices\",\n\t\t\t\tpodVolume.Name,\n\t\t\t\tvolumeMode)\n\t\t}\n\t\treturn pvc, volumeSpec, volumeGidValue, nil\n\t}\n\n\t// Do not return the original volume object, since the source could mutate it\n\tclonedPodVolume := podVolume.DeepCopy()\n\n\tspec := volume.NewSpecFromVolume(clonedPodVolume)\n\tmigratable, err := dswp.csiMigratedPluginManager.IsMigratable(spec)\n\tif err != nil {\n\t\treturn nil, nil, \"\", err\n\t}\n\tif migratable {\n\t\tspec, err = csimigration.TranslateInTreeSpecToCSI(spec, pod.Namespace, dswp.intreeToCSITranslator)\n\t\tif err != nil {\n\t\t\treturn nil, nil, \"\", err\n\t\t}\n\t}\n\treturn nil, spec, \"\", nil\n}","line":{"from":443,"to":542}} {"id":100008024,"name":"getPVCExtractPV","signature":"func (dswp *desiredStateOfWorldPopulator) getPVCExtractPV(","file":"pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go","code":"// getPVCExtractPV fetches the PVC object with the given namespace and name from\n// the API server, checks whether PVC is being deleted, extracts the name of the PV\n// it is pointing to and returns it.\n// An error is returned if the PVC object's phase is not \"Bound\".\nfunc (dswp *desiredStateOfWorldPopulator) getPVCExtractPV(\n\tnamespace string, claimName string) (*v1.PersistentVolumeClaim, error) {\n\tpvc, err :=\n\t\tdswp.kubeClient.CoreV1().PersistentVolumeClaims(namespace).Get(context.TODO(), claimName, metav1.GetOptions{})\n\tif err != nil || pvc == nil {\n\t\treturn nil, fmt.Errorf(\"failed to fetch PVC from API server: %v\", err)\n\t}\n\n\t// Pods that uses a PVC that is being deleted must not be started.\n\t//\n\t// In case an old kubelet is running without this check or some kubelets\n\t// have this feature disabled, the worst that can happen is that such\n\t// pod is scheduled. This was the default behavior in 1.8 and earlier\n\t// and users should not be that surprised.\n\t// It should happen only in very rare case when scheduler schedules\n\t// a pod and user deletes a PVC that's used by it at the same time.\n\tif pvc.ObjectMeta.DeletionTimestamp != nil {\n\t\treturn nil, errors.New(\"PVC is being deleted\")\n\t}\n\n\tif pvc.Status.Phase != v1.ClaimBound {\n\t\treturn nil, errors.New(\"PVC is not bound\")\n\t}\n\tif pvc.Spec.VolumeName == \"\" {\n\t\treturn nil, errors.New(\"PVC has empty pvc.Spec.VolumeName\")\n\t}\n\n\treturn pvc, nil\n}","line":{"from":544,"to":576}} {"id":100008025,"name":"getPVSpec","signature":"func (dswp *desiredStateOfWorldPopulator) getPVSpec(","file":"pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go","code":"// getPVSpec fetches the PV object with the given name from the API server\n// and returns a volume.Spec representing it.\n// An error is returned if the call to fetch the PV object fails.\nfunc (dswp *desiredStateOfWorldPopulator) getPVSpec(\n\tname string,\n\tpvcReadOnly bool,\n\texpectedClaimUID types.UID) (*volume.Spec, string, error) {\n\tpv, err := dswp.kubeClient.CoreV1().PersistentVolumes().Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil || pv == nil {\n\t\treturn nil, \"\", fmt.Errorf(\n\t\t\t\"failed to fetch PV %s from API server: %v\", name, err)\n\t}\n\n\tif pv.Spec.ClaimRef == nil {\n\t\treturn nil, \"\", fmt.Errorf(\n\t\t\t\"found PV object %s but it has a nil pv.Spec.ClaimRef indicating it is not yet bound to the claim\",\n\t\t\tname)\n\t}\n\n\tif pv.Spec.ClaimRef.UID != expectedClaimUID {\n\t\treturn nil, \"\", fmt.Errorf(\n\t\t\t\"found PV object %s but its pv.Spec.ClaimRef.UID %s does not point to claim.UID %s\",\n\t\t\tname,\n\t\t\tpv.Spec.ClaimRef.UID,\n\t\t\texpectedClaimUID)\n\t}\n\n\tvolumeGidValue := getPVVolumeGidAnnotationValue(pv)\n\treturn volume.NewSpecFromPersistentVolume(pv, pvcReadOnly), volumeGidValue, nil\n}","line":{"from":578,"to":607}} {"id":100008026,"name":"getPVVolumeGidAnnotationValue","signature":"func getPVVolumeGidAnnotationValue(pv *v1.PersistentVolume) string","file":"pkg/kubelet/volumemanager/populator/desired_state_of_world_populator.go","code":"func getPVVolumeGidAnnotationValue(pv *v1.PersistentVolume) string {\n\tif volumeGid, ok := pv.Annotations[util.VolumeGidAnnotationKey]; ok {\n\t\treturn volumeGid\n\t}\n\n\treturn \"\"\n}","line":{"from":609,"to":615}} {"id":100008027,"name":"runOld","signature":"func (rc *reconciler) runOld(stopCh \u003c-chan struct{})","file":"pkg/kubelet/volumemanager/reconciler/reconciler.go","code":"func (rc *reconciler) runOld(stopCh \u003c-chan struct{}) {\n\twait.Until(rc.reconciliationLoopFunc(), rc.loopSleepDuration, stopCh)\n}","line":{"from":29,"to":31}} {"id":100008028,"name":"reconciliationLoopFunc","signature":"func (rc *reconciler) reconciliationLoopFunc() func()","file":"pkg/kubelet/volumemanager/reconciler/reconciler.go","code":"func (rc *reconciler) reconciliationLoopFunc() func() {\n\treturn func() {\n\t\trc.reconcile()\n\n\t\t// Sync the state with the reality once after all existing pods are added to the desired state from all sources.\n\t\t// Otherwise, the reconstruct process may clean up pods' volumes that are still in use because\n\t\t// desired state of world does not contain a complete list of pods.\n\t\tif rc.populatorHasAddedPods() \u0026\u0026 !rc.StatesHasBeenSynced() {\n\t\t\tklog.InfoS(\"Reconciler: start to sync state\")\n\t\t\trc.sync()\n\t\t}\n\t}\n}","line":{"from":33,"to":45}} {"id":100008029,"name":"reconcile","signature":"func (rc *reconciler) reconcile()","file":"pkg/kubelet/volumemanager/reconciler/reconciler.go","code":"func (rc *reconciler) reconcile() {\n\t// Unmounts are triggered before mounts so that a volume that was\n\t// referenced by a pod that was deleted and is now referenced by another\n\t// pod is unmounted from the first pod before being mounted to the new\n\t// pod.\n\trc.unmountVolumes()\n\n\t// Next we mount required volumes. This function could also trigger\n\t// attach if kubelet is responsible for attaching volumes.\n\t// If underlying PVC was resized while in-use then this function also handles volume\n\t// resizing.\n\trc.mountOrAttachVolumes()\n\n\t// Ensure devices that should be detached/unmounted are detached/unmounted.\n\trc.unmountDetachDevices()\n\n\t// After running the above operations if skippedDuringReconstruction is not empty\n\t// then ensure that all volumes which were discovered and skipped during reconstruction\n\t// are added to actualStateOfWorld in uncertain state.\n\tif len(rc.skippedDuringReconstruction) \u003e 0 {\n\t\trc.processReconstructedVolumes()\n\t}\n}","line":{"from":47,"to":69}} {"id":100008030,"name":"processReconstructedVolumes","signature":"func (rc *reconciler) processReconstructedVolumes()","file":"pkg/kubelet/volumemanager/reconciler/reconciler.go","code":"// processReconstructedVolumes checks volumes which were skipped during the reconstruction\n// process because it was assumed that since these volumes were present in DSOW they would get\n// mounted correctly and make it into ASOW.\n// But if mount operation fails for some reason then we still need to mark the volume as uncertain\n// and wait for the next reconciliation loop to deal with it.\nfunc (rc *reconciler) processReconstructedVolumes() {\n\tfor volumeName, glblVolumeInfo := range rc.skippedDuringReconstruction {\n\t\t// check if volume is marked as attached to the node\n\t\t// for now lets only process volumes which are at least known as attached to the node\n\t\t// this should help with most volume types (including secret, configmap etc)\n\t\tif !rc.actualStateOfWorld.VolumeExists(volumeName) {\n\t\t\tklog.V(4).InfoS(\"Volume is not marked as attached to the node. Skipping processing of the volume\", \"volumeName\", volumeName)\n\t\t\tcontinue\n\t\t}\n\t\tuncertainVolumeCount := 0\n\t\t// only delete volumes which were marked as attached here.\n\t\t// This should ensure that - we will wait for volumes which were not marked as attached\n\t\t// before adding them in uncertain state during reconstruction.\n\t\tdelete(rc.skippedDuringReconstruction, volumeName)\n\n\t\tfor podName, volume := range glblVolumeInfo.podVolumes {\n\t\t\tmarkVolumeOpts := operationexecutor.MarkVolumeOpts{\n\t\t\t\tPodName: volume.podName,\n\t\t\t\tPodUID: types.UID(podName),\n\t\t\t\tVolumeName: volume.volumeName,\n\t\t\t\tMounter: volume.mounter,\n\t\t\t\tBlockVolumeMapper: volume.blockVolumeMapper,\n\t\t\t\tOuterVolumeSpecName: volume.outerVolumeSpecName,\n\t\t\t\tVolumeGidVolume: volume.volumeGidValue,\n\t\t\t\tVolumeSpec: volume.volumeSpec,\n\t\t\t\tVolumeMountState: operationexecutor.VolumeMountUncertain,\n\t\t\t}\n\n\t\t\tvolumeAdded, err := rc.actualStateOfWorld.CheckAndMarkVolumeAsUncertainViaReconstruction(markVolumeOpts)\n\n\t\t\t// if volume is not mounted then lets mark volume mounted in uncertain state in ASOW\n\t\t\tif volumeAdded {\n\t\t\t\tuncertainVolumeCount += 1\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"Could not add pod to volume information to actual state of world\", \"pod\", klog.KObj(volume.pod))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tklog.V(4).InfoS(\"Volume is marked as mounted in uncertain state and added to the actual state\", \"pod\", klog.KObj(volume.pod), \"podName\", volume.podName, \"volumeName\", volume.volumeName)\n\t\t\t}\n\t\t}\n\n\t\tif uncertainVolumeCount \u003e 0 {\n\t\t\t// If the volume has device to mount, we mark its device as uncertain\n\t\t\tif glblVolumeInfo.deviceMounter != nil || glblVolumeInfo.blockVolumeMapper != nil {\n\t\t\t\tdeviceMountPath, err := getDeviceMountPath(glblVolumeInfo)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"Could not find device mount path for volume\", \"volumeName\", glblVolumeInfo.volumeName)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tdeviceMounted := rc.actualStateOfWorld.CheckAndMarkDeviceUncertainViaReconstruction(glblVolumeInfo.volumeName, deviceMountPath)\n\t\t\t\tif !deviceMounted {\n\t\t\t\t\tklog.V(3).InfoS(\"Could not mark device as mounted in uncertain state\", \"volumeName\", glblVolumeInfo.volumeName)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":71,"to":132}} {"id":100008031,"name":"NewReconciler","signature":"func NewReconciler(","file":"pkg/kubelet/volumemanager/reconciler/reconciler_common.go","code":"// NewReconciler returns a new instance of Reconciler.\n//\n// controllerAttachDetachEnabled - if true, indicates that the attach/detach\n// controller is responsible for managing the attach/detach operations for\n// this node, and therefore the volume manager should not\n//\n// loopSleepDuration - the amount of time the reconciler loop sleeps between\n// successive executions\n//\n// waitForAttachTimeout - the amount of time the Mount function will wait for\n// the volume to be attached\n//\n// nodeName - the Name for this node, used by Attach and Detach methods\n//\n// desiredStateOfWorld - cache containing the desired state of the world\n//\n// actualStateOfWorld - cache containing the actual state of the world\n//\n// populatorHasAddedPods - checker for whether the populator has finished\n// adding pods to the desiredStateOfWorld cache at least once after sources\n// are all ready (before sources are ready, pods are probably missing)\n//\n// operationExecutor - used to trigger attach/detach/mount/unmount operations\n// safely (prevents more than one operation from being triggered on the same\n// volume)\n//\n// mounter - mounter passed in from kubelet, passed down unmount path\n//\n// hostutil - hostutil passed in from kubelet\n//\n// volumePluginMgr - volume plugin manager passed from kubelet\nfunc NewReconciler(\n\tkubeClient clientset.Interface,\n\tcontrollerAttachDetachEnabled bool,\n\tloopSleepDuration time.Duration,\n\twaitForAttachTimeout time.Duration,\n\tnodeName types.NodeName,\n\tdesiredStateOfWorld cache.DesiredStateOfWorld,\n\tactualStateOfWorld cache.ActualStateOfWorld,\n\tpopulatorHasAddedPods func() bool,\n\toperationExecutor operationexecutor.OperationExecutor,\n\tmounter mount.Interface,\n\thostutil hostutil.HostUtils,\n\tvolumePluginMgr *volumepkg.VolumePluginMgr,\n\tkubeletPodsDir string) Reconciler {\n\treturn \u0026reconciler{\n\t\tkubeClient: kubeClient,\n\t\tcontrollerAttachDetachEnabled: controllerAttachDetachEnabled,\n\t\tloopSleepDuration: loopSleepDuration,\n\t\twaitForAttachTimeout: waitForAttachTimeout,\n\t\tnodeName: nodeName,\n\t\tdesiredStateOfWorld: desiredStateOfWorld,\n\t\tactualStateOfWorld: actualStateOfWorld,\n\t\tpopulatorHasAddedPods: populatorHasAddedPods,\n\t\toperationExecutor: operationExecutor,\n\t\tmounter: mounter,\n\t\thostutil: hostutil,\n\t\tskippedDuringReconstruction: map[v1.UniqueVolumeName]*globalVolumeInfo{},\n\t\tvolumePluginMgr: volumePluginMgr,\n\t\tkubeletPodsDir: kubeletPodsDir,\n\t\ttimeOfLastSync: time.Time{},\n\t\tvolumesFailedReconstruction: make([]podVolume, 0),\n\t\tvolumesNeedDevicePath: make([]v1.UniqueVolumeName, 0),\n\t\tvolumesNeedReportedInUse: make([]v1.UniqueVolumeName, 0),\n\t}\n}","line":{"from":61,"to":126}} {"id":100008032,"name":"Run","signature":"func (rc *reconciler) Run(stopCh \u003c-chan struct{})","file":"pkg/kubelet/volumemanager/reconciler/reconciler_common.go","code":"func (rc *reconciler) Run(stopCh \u003c-chan struct{}) {\n\tif utilfeature.DefaultFeatureGate.Enabled(features.NewVolumeManagerReconstruction) {\n\t\trc.runNew(stopCh)\n\t\treturn\n\t}\n\n\trc.runOld(stopCh)\n}","line":{"from":151,"to":158}} {"id":100008033,"name":"unmountVolumes","signature":"func (rc *reconciler) unmountVolumes()","file":"pkg/kubelet/volumemanager/reconciler/reconciler_common.go","code":"func (rc *reconciler) unmountVolumes() {\n\t// Ensure volumes that should be unmounted are unmounted.\n\tfor _, mountedVolume := range rc.actualStateOfWorld.GetAllMountedVolumes() {\n\t\tif !rc.desiredStateOfWorld.PodExistsInVolume(mountedVolume.PodName, mountedVolume.VolumeName, mountedVolume.SELinuxMountContext) {\n\t\t\t// Volume is mounted, unmount it\n\t\t\tklog.V(5).InfoS(mountedVolume.GenerateMsgDetailed(\"Starting operationExecutor.UnmountVolume\", \"\"))\n\t\t\terr := rc.operationExecutor.UnmountVolume(\n\t\t\t\tmountedVolume.MountedVolume, rc.actualStateOfWorld, rc.kubeletPodsDir)\n\t\t\tif err != nil \u0026\u0026 !isExpectedError(err) {\n\t\t\t\tklog.ErrorS(err, mountedVolume.GenerateErrorDetailed(fmt.Sprintf(\"operationExecutor.UnmountVolume failed (controllerAttachDetachEnabled %v)\", rc.controllerAttachDetachEnabled), err).Error())\n\t\t\t}\n\t\t\tif err == nil {\n\t\t\t\tklog.InfoS(mountedVolume.GenerateMsgDetailed(\"operationExecutor.UnmountVolume started\", \"\"))\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":160,"to":176}} {"id":100008034,"name":"mountOrAttachVolumes","signature":"func (rc *reconciler) mountOrAttachVolumes()","file":"pkg/kubelet/volumemanager/reconciler/reconciler_common.go","code":"func (rc *reconciler) mountOrAttachVolumes() {\n\t// Ensure volumes that should be attached/mounted are attached/mounted.\n\tfor _, volumeToMount := range rc.desiredStateOfWorld.GetVolumesToMount() {\n\t\tvolMounted, devicePath, err := rc.actualStateOfWorld.PodExistsInVolume(volumeToMount.PodName, volumeToMount.VolumeName, volumeToMount.PersistentVolumeSize, volumeToMount.SELinuxLabel)\n\t\tvolumeToMount.DevicePath = devicePath\n\t\tif cache.IsSELinuxMountMismatchError(err) {\n\t\t\t// The volume is mounted, but with an unexpected SELinux context.\n\t\t\t// It will get unmounted in unmountVolumes / unmountDetachDevices and\n\t\t\t// then removed from actualStateOfWorld.\n\t\t\trc.desiredStateOfWorld.AddErrorToPod(volumeToMount.PodName, err.Error())\n\t\t\tcontinue\n\t\t} else if cache.IsVolumeNotAttachedError(err) {\n\t\t\trc.waitForVolumeAttach(volumeToMount)\n\t\t} else if !volMounted || cache.IsRemountRequiredError(err) {\n\t\t\trc.mountAttachedVolumes(volumeToMount, err)\n\t\t} else if cache.IsFSResizeRequiredError(err) {\n\t\t\tfsResizeRequiredErr, _ := err.(cache.FsResizeRequiredError)\n\t\t\trc.expandVolume(volumeToMount, fsResizeRequiredErr.CurrentSize)\n\t\t}\n\t}\n}","line":{"from":178,"to":198}} {"id":100008035,"name":"expandVolume","signature":"func (rc *reconciler) expandVolume(volumeToMount cache.VolumeToMount, currentSize resource.Quantity)","file":"pkg/kubelet/volumemanager/reconciler/reconciler_common.go","code":"func (rc *reconciler) expandVolume(volumeToMount cache.VolumeToMount, currentSize resource.Quantity) {\n\tklog.V(4).InfoS(volumeToMount.GenerateMsgDetailed(\"Starting operationExecutor.ExpandInUseVolume\", \"\"), \"pod\", klog.KObj(volumeToMount.Pod))\n\terr := rc.operationExecutor.ExpandInUseVolume(volumeToMount.VolumeToMount, rc.actualStateOfWorld, currentSize)\n\n\tif err != nil \u0026\u0026 !isExpectedError(err) {\n\t\tklog.ErrorS(err, volumeToMount.GenerateErrorDetailed(\"operationExecutor.ExpandInUseVolume failed\", err).Error(), \"pod\", klog.KObj(volumeToMount.Pod))\n\t}\n\n\tif err == nil {\n\t\tklog.V(4).InfoS(volumeToMount.GenerateMsgDetailed(\"operationExecutor.ExpandInUseVolume started\", \"\"), \"pod\", klog.KObj(volumeToMount.Pod))\n\t}\n}","line":{"from":200,"to":211}} {"id":100008036,"name":"mountAttachedVolumes","signature":"func (rc *reconciler) mountAttachedVolumes(volumeToMount cache.VolumeToMount, podExistError error)","file":"pkg/kubelet/volumemanager/reconciler/reconciler_common.go","code":"func (rc *reconciler) mountAttachedVolumes(volumeToMount cache.VolumeToMount, podExistError error) {\n\t// Volume is not mounted, or is already mounted, but requires remounting\n\tremountingLogStr := \"\"\n\tisRemount := cache.IsRemountRequiredError(podExistError)\n\tif isRemount {\n\t\tremountingLogStr = \"Volume is already mounted to pod, but remount was requested.\"\n\t}\n\tklog.V(4).InfoS(volumeToMount.GenerateMsgDetailed(\"Starting operationExecutor.MountVolume\", remountingLogStr), \"pod\", klog.KObj(volumeToMount.Pod))\n\terr := rc.operationExecutor.MountVolume(\n\t\trc.waitForAttachTimeout,\n\t\tvolumeToMount.VolumeToMount,\n\t\trc.actualStateOfWorld,\n\t\tisRemount)\n\tif err != nil \u0026\u0026 !isExpectedError(err) {\n\t\tklog.ErrorS(err, volumeToMount.GenerateErrorDetailed(fmt.Sprintf(\"operationExecutor.MountVolume failed (controllerAttachDetachEnabled %v)\", rc.controllerAttachDetachEnabled), err).Error(), \"pod\", klog.KObj(volumeToMount.Pod))\n\t}\n\tif err == nil {\n\t\tif remountingLogStr == \"\" {\n\t\t\tklog.V(1).InfoS(volumeToMount.GenerateMsgDetailed(\"operationExecutor.MountVolume started\", remountingLogStr), \"pod\", klog.KObj(volumeToMount.Pod))\n\t\t} else {\n\t\t\tklog.V(5).InfoS(volumeToMount.GenerateMsgDetailed(\"operationExecutor.MountVolume started\", remountingLogStr), \"pod\", klog.KObj(volumeToMount.Pod))\n\t\t}\n\t}\n}","line":{"from":213,"to":236}} {"id":100008037,"name":"waitForVolumeAttach","signature":"func (rc *reconciler) waitForVolumeAttach(volumeToMount cache.VolumeToMount)","file":"pkg/kubelet/volumemanager/reconciler/reconciler_common.go","code":"func (rc *reconciler) waitForVolumeAttach(volumeToMount cache.VolumeToMount) {\n\tlogger := klog.TODO()\n\tif rc.controllerAttachDetachEnabled || !volumeToMount.PluginIsAttachable {\n\t\t//// lets not spin a goroutine and unnecessarily trigger exponential backoff if this happens\n\t\tif volumeToMount.PluginIsAttachable \u0026\u0026 !volumeToMount.ReportedInUse {\n\t\t\tklog.V(5).InfoS(volumeToMount.GenerateMsgDetailed(\"operationExecutor.VerifyControllerAttachedVolume failed\", \" volume not marked in-use\"), \"pod\", klog.KObj(volumeToMount.Pod))\n\t\t\treturn\n\t\t}\n\t\t// Volume is not attached (or doesn't implement attacher), kubelet attach is disabled, wait\n\t\t// for controller to finish attaching volume.\n\t\tklog.V(5).InfoS(volumeToMount.GenerateMsgDetailed(\"Starting operationExecutor.VerifyControllerAttachedVolume\", \"\"), \"pod\", klog.KObj(volumeToMount.Pod))\n\t\terr := rc.operationExecutor.VerifyControllerAttachedVolume(\n\t\t\tlogger,\n\t\t\tvolumeToMount.VolumeToMount,\n\t\t\trc.nodeName,\n\t\t\trc.actualStateOfWorld)\n\t\tif err != nil \u0026\u0026 !isExpectedError(err) {\n\t\t\tklog.ErrorS(err, volumeToMount.GenerateErrorDetailed(fmt.Sprintf(\"operationExecutor.VerifyControllerAttachedVolume failed (controllerAttachDetachEnabled %v)\", rc.controllerAttachDetachEnabled), err).Error(), \"pod\", klog.KObj(volumeToMount.Pod))\n\t\t}\n\t\tif err == nil {\n\t\t\tklog.InfoS(volumeToMount.GenerateMsgDetailed(\"operationExecutor.VerifyControllerAttachedVolume started\", \"\"), \"pod\", klog.KObj(volumeToMount.Pod))\n\t\t}\n\t} else {\n\t\t// Volume is not attached to node, kubelet attach is enabled, volume implements an attacher,\n\t\t// so attach it\n\t\tvolumeToAttach := operationexecutor.VolumeToAttach{\n\t\t\tVolumeName: volumeToMount.VolumeName,\n\t\t\tVolumeSpec: volumeToMount.VolumeSpec,\n\t\t\tNodeName: rc.nodeName,\n\t\t}\n\t\tklog.V(5).InfoS(volumeToAttach.GenerateMsgDetailed(\"Starting operationExecutor.AttachVolume\", \"\"), \"pod\", klog.KObj(volumeToMount.Pod))\n\t\terr := rc.operationExecutor.AttachVolume(logger, volumeToAttach, rc.actualStateOfWorld)\n\t\tif err != nil \u0026\u0026 !isExpectedError(err) {\n\t\t\tklog.ErrorS(err, volumeToMount.GenerateErrorDetailed(fmt.Sprintf(\"operationExecutor.AttachVolume failed (controllerAttachDetachEnabled %v)\", rc.controllerAttachDetachEnabled), err).Error(), \"pod\", klog.KObj(volumeToMount.Pod))\n\t\t}\n\t\tif err == nil {\n\t\t\tklog.InfoS(volumeToMount.GenerateMsgDetailed(\"operationExecutor.AttachVolume started\", \"\"), \"pod\", klog.KObj(volumeToMount.Pod))\n\t\t}\n\t}\n}","line":{"from":238,"to":277}} {"id":100008038,"name":"unmountDetachDevices","signature":"func (rc *reconciler) unmountDetachDevices()","file":"pkg/kubelet/volumemanager/reconciler/reconciler_common.go","code":"func (rc *reconciler) unmountDetachDevices() {\n\tfor _, attachedVolume := range rc.actualStateOfWorld.GetUnmountedVolumes() {\n\t\t// Check IsOperationPending to avoid marking a volume as detached if it's in the process of mounting.\n\t\tif !rc.desiredStateOfWorld.VolumeExists(attachedVolume.VolumeName, attachedVolume.SELinuxMountContext) \u0026\u0026\n\t\t\t!rc.operationExecutor.IsOperationPending(attachedVolume.VolumeName, nestedpendingoperations.EmptyUniquePodName, nestedpendingoperations.EmptyNodeName) {\n\t\t\tif attachedVolume.DeviceMayBeMounted() {\n\t\t\t\t// Volume is globally mounted to device, unmount it\n\t\t\t\tklog.V(5).InfoS(attachedVolume.GenerateMsgDetailed(\"Starting operationExecutor.UnmountDevice\", \"\"))\n\t\t\t\terr := rc.operationExecutor.UnmountDevice(\n\t\t\t\t\tattachedVolume.AttachedVolume, rc.actualStateOfWorld, rc.hostutil)\n\t\t\t\tif err != nil \u0026\u0026 !isExpectedError(err) {\n\t\t\t\t\tklog.ErrorS(err, attachedVolume.GenerateErrorDetailed(fmt.Sprintf(\"operationExecutor.UnmountDevice failed (controllerAttachDetachEnabled %v)\", rc.controllerAttachDetachEnabled), err).Error())\n\t\t\t\t}\n\t\t\t\tif err == nil {\n\t\t\t\t\tklog.InfoS(attachedVolume.GenerateMsgDetailed(\"operationExecutor.UnmountDevice started\", \"\"))\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Volume is attached to node, detach it\n\t\t\t\t// Kubelet not responsible for detaching or this volume has a non-attachable volume plugin.\n\t\t\t\tif rc.controllerAttachDetachEnabled || !attachedVolume.PluginIsAttachable {\n\t\t\t\t\trc.actualStateOfWorld.MarkVolumeAsDetached(attachedVolume.VolumeName, attachedVolume.NodeName)\n\t\t\t\t\tklog.InfoS(attachedVolume.GenerateMsgDetailed(\"Volume detached\", fmt.Sprintf(\"DevicePath %q\", attachedVolume.DevicePath)))\n\t\t\t\t} else {\n\t\t\t\t\t// Only detach if kubelet detach is enabled\n\t\t\t\t\tklog.V(5).InfoS(attachedVolume.GenerateMsgDetailed(\"Starting operationExecutor.DetachVolume\", \"\"))\n\t\t\t\t\terr := rc.operationExecutor.DetachVolume(\n\t\t\t\t\t\tklog.TODO(), attachedVolume.AttachedVolume, false /* verifySafeToDetach */, rc.actualStateOfWorld)\n\t\t\t\t\tif err != nil \u0026\u0026 !isExpectedError(err) {\n\t\t\t\t\t\tklog.ErrorS(err, attachedVolume.GenerateErrorDetailed(fmt.Sprintf(\"operationExecutor.DetachVolume failed (controllerAttachDetachEnabled %v)\", rc.controllerAttachDetachEnabled), err).Error())\n\t\t\t\t\t}\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tklog.InfoS(attachedVolume.GenerateMsgDetailed(\"operationExecutor.DetachVolume started\", \"\"))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":279,"to":316}} {"id":100008039,"name":"isExpectedError","signature":"func isExpectedError(err error) bool","file":"pkg/kubelet/volumemanager/reconciler/reconciler_common.go","code":"// ignore nestedpendingoperations.IsAlreadyExists and exponentialbackoff.IsExponentialBackoff errors, they are expected.\nfunc isExpectedError(err error) bool {\n\treturn nestedpendingoperations.IsAlreadyExists(err) || exponentialbackoff.IsExponentialBackoff(err) || operationexecutor.IsMountFailedPreconditionError(err)\n}","line":{"from":318,"to":321}} {"id":100008040,"name":"runNew","signature":"func (rc *reconciler) runNew(stopCh \u003c-chan struct{})","file":"pkg/kubelet/volumemanager/reconciler/reconciler_new.go","code":"// TODO: Replace Run() when NewVolumeManagerReconstruction is GA\nfunc (rc *reconciler) runNew(stopCh \u003c-chan struct{}) {\n\trc.reconstructVolumes()\n\tklog.InfoS(\"Reconciler: start to sync state\")\n\twait.Until(rc.reconcileNew, rc.loopSleepDuration, stopCh)\n}","line":{"from":26,"to":31}} {"id":100008041,"name":"reconcileNew","signature":"func (rc *reconciler) reconcileNew()","file":"pkg/kubelet/volumemanager/reconciler/reconciler_new.go","code":"func (rc *reconciler) reconcileNew() {\n\treadyToUnmount := rc.readyToUnmount()\n\tif readyToUnmount {\n\t\t// Unmounts are triggered before mounts so that a volume that was\n\t\t// referenced by a pod that was deleted and is now referenced by another\n\t\t// pod is unmounted from the first pod before being mounted to the new\n\t\t// pod.\n\t\trc.unmountVolumes()\n\t}\n\n\t// Next we mount required volumes. This function could also trigger\n\t// attach if kubelet is responsible for attaching volumes.\n\t// If underlying PVC was resized while in-use then this function also handles volume\n\t// resizing.\n\trc.mountOrAttachVolumes()\n\n\t// Unmount volumes only when DSW and ASW are fully populated to prevent unmounting a volume\n\t// that is still needed, but it did not reach DSW yet.\n\tif readyToUnmount {\n\t\t// Ensure devices that should be detached/unmounted are detached/unmounted.\n\t\trc.unmountDetachDevices()\n\n\t\t// Clean up any orphan volumes that failed reconstruction.\n\t\trc.cleanOrphanVolumes()\n\t}\n\n\tif len(rc.volumesNeedDevicePath) != 0 {\n\t\trc.updateReconstructedDevicePaths()\n\t}\n\n\tif len(rc.volumesNeedReportedInUse) != 0 \u0026\u0026 rc.populatorHasAddedPods() {\n\t\t// Once DSW is populated, mark all reconstructed as reported in node.status,\n\t\t// so they can proceed with MountDevice / SetUp.\n\t\trc.desiredStateOfWorld.MarkVolumesReportedInUse(rc.volumesNeedReportedInUse)\n\t\trc.volumesNeedReportedInUse = nil\n\t}\n}","line":{"from":33,"to":69}} {"id":100008042,"name":"sync","signature":"func (rc *reconciler) sync()","file":"pkg/kubelet/volumemanager/reconciler/reconstruct.go","code":"// sync process tries to observe the real world by scanning all pods' volume directories from the disk.\n// If the actual and desired state of worlds are not consistent with the observed world, it means that some\n// mounted volumes are left out probably during kubelet restart. This process will reconstruct\n// the volumes and update the actual and desired states. For the volumes that cannot support reconstruction,\n// it will try to clean up the mount paths with operation executor.\nfunc (rc *reconciler) sync() {\n\tdefer rc.updateLastSyncTime()\n\trc.syncStates(rc.kubeletPodsDir)\n}","line":{"from":30,"to":38}} {"id":100008043,"name":"syncStates","signature":"func (rc *reconciler) syncStates(kubeletPodDir string)","file":"pkg/kubelet/volumemanager/reconciler/reconstruct.go","code":"// syncStates scans the volume directories under the given pod directory.\n// If the volume is not in desired state of world, this function will reconstruct\n// the volume related information and put it in both the actual and desired state of worlds.\n// For some volume plugins that cannot support reconstruction, it will clean up the existing\n// mount points since the volume is no long needed (removed from desired state)\nfunc (rc *reconciler) syncStates(kubeletPodDir string) {\n\t// Get volumes information by reading the pod's directory\n\tpodVolumes, err := getVolumesFromPodDir(kubeletPodDir)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Cannot get volumes from disk, skip sync states for volume reconstruction\")\n\t\treturn\n\t}\n\tvolumesNeedUpdate := make(map[v1.UniqueVolumeName]*globalVolumeInfo)\n\tvolumeNeedReport := []v1.UniqueVolumeName{}\n\tfor _, volume := range podVolumes {\n\t\tif rc.actualStateOfWorld.VolumeExistsWithSpecName(volume.podName, volume.volumeSpecName) {\n\t\t\tklog.V(4).InfoS(\"Volume exists in actual state, skip cleaning up mounts\", \"podName\", volume.podName, \"volumeSpecName\", volume.volumeSpecName)\n\t\t\t// There is nothing to reconstruct\n\t\t\tcontinue\n\t\t}\n\t\tvolumeInDSW := rc.desiredStateOfWorld.VolumeExistsWithSpecName(volume.podName, volume.volumeSpecName)\n\n\t\treconstructedVolume, err := rc.reconstructVolume(volume)\n\t\tif err != nil {\n\t\t\tif volumeInDSW {\n\t\t\t\t// Some pod needs the volume, don't clean it up and hope that\n\t\t\t\t// reconcile() calls SetUp and reconstructs the volume in ASW.\n\t\t\t\tklog.V(4).InfoS(\"Volume exists in desired state, skip cleaning up mounts\", \"podName\", volume.podName, \"volumeSpecName\", volume.volumeSpecName)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// No pod needs the volume.\n\t\t\tklog.InfoS(\"Could not construct volume information, cleaning up mounts\", \"podName\", volume.podName, \"volumeSpecName\", volume.volumeSpecName, \"err\", err)\n\t\t\trc.cleanupMounts(volume)\n\t\t\tcontinue\n\t\t}\n\t\tgvl := \u0026globalVolumeInfo{\n\t\t\tvolumeName: reconstructedVolume.volumeName,\n\t\t\tvolumeSpec: reconstructedVolume.volumeSpec,\n\t\t\tdevicePath: reconstructedVolume.devicePath,\n\t\t\tdeviceMounter: reconstructedVolume.deviceMounter,\n\t\t\tblockVolumeMapper: reconstructedVolume.blockVolumeMapper,\n\t\t\tmounter: reconstructedVolume.mounter,\n\t\t}\n\t\tif cachedInfo, ok := volumesNeedUpdate[reconstructedVolume.volumeName]; ok {\n\t\t\tgvl = cachedInfo\n\t\t}\n\t\tgvl.addPodVolume(reconstructedVolume)\n\t\tif volumeInDSW {\n\t\t\t// Some pod needs the volume. And it exists on disk. Some previous\n\t\t\t// kubelet must have created the directory, therefore it must have\n\t\t\t// reported the volume as in use. Mark the volume as in use also in\n\t\t\t// this new kubelet so reconcile() calls SetUp and re-mounts the\n\t\t\t// volume if it's necessary.\n\t\t\tvolumeNeedReport = append(volumeNeedReport, reconstructedVolume.volumeName)\n\t\t\trc.skippedDuringReconstruction[reconstructedVolume.volumeName] = gvl\n\t\t\tklog.V(4).InfoS(\"Volume exists in desired state, marking as InUse\", \"podName\", volume.podName, \"volumeSpecName\", volume.volumeSpecName)\n\t\t\tcontinue\n\t\t}\n\t\t// There is no pod that uses the volume.\n\t\tif rc.operationExecutor.IsOperationPending(reconstructedVolume.volumeName, nestedpendingoperations.EmptyUniquePodName, nestedpendingoperations.EmptyNodeName) {\n\t\t\tklog.InfoS(\"Volume is in pending operation, skip cleaning up mounts\")\n\t\t}\n\t\tklog.V(2).InfoS(\"Reconciler sync states: could not find pod information in desired state, update it in actual state\", \"reconstructedVolume\", reconstructedVolume)\n\t\tvolumesNeedUpdate[reconstructedVolume.volumeName] = gvl\n\t}\n\n\tif len(volumesNeedUpdate) \u003e 0 {\n\t\tif err = rc.updateStates(volumesNeedUpdate); err != nil {\n\t\t\tklog.ErrorS(err, \"Error occurred during reconstruct volume from disk\")\n\t\t}\n\t}\n\tif len(volumeNeedReport) \u003e 0 {\n\t\trc.desiredStateOfWorld.MarkVolumesReportedInUse(volumeNeedReport)\n\t}\n}","line":{"from":40,"to":114}} {"id":100008044,"name":"updateDevicePath","signature":"func (rc *reconciler) updateDevicePath(volumesNeedUpdate map[v1.UniqueVolumeName]*globalVolumeInfo)","file":"pkg/kubelet/volumemanager/reconciler/reconstruct.go","code":"// updateDevicePath gets the node status to retrieve volume device path information.\nfunc (rc *reconciler) updateDevicePath(volumesNeedUpdate map[v1.UniqueVolumeName]*globalVolumeInfo) {\n\tnode, fetchErr := rc.kubeClient.CoreV1().Nodes().Get(context.TODO(), string(rc.nodeName), metav1.GetOptions{})\n\tif fetchErr != nil {\n\t\tklog.ErrorS(fetchErr, \"UpdateStates in reconciler: could not get node status with error\")\n\t} else {\n\t\tfor _, attachedVolume := range node.Status.VolumesAttached {\n\t\t\tif volume, exists := volumesNeedUpdate[attachedVolume.Name]; exists {\n\t\t\t\tvolume.devicePath = attachedVolume.DevicePath\n\t\t\t\tvolumesNeedUpdate[attachedVolume.Name] = volume\n\t\t\t\tklog.V(4).InfoS(\"Update devicePath from node status for volume\", \"volumeName\", attachedVolume.Name, \"path\", volume.devicePath)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":116,"to":130}} {"id":100008045,"name":"updateStates","signature":"func (rc *reconciler) updateStates(volumesNeedUpdate map[v1.UniqueVolumeName]*globalVolumeInfo) error","file":"pkg/kubelet/volumemanager/reconciler/reconstruct.go","code":"func (rc *reconciler) updateStates(volumesNeedUpdate map[v1.UniqueVolumeName]*globalVolumeInfo) error {\n\t// Get the node status to retrieve volume device path information.\n\t// Skip reporting devicePath in node objects if kubeClient is nil.\n\t// In standalone mode, kubelet is not expected to mount any attachable volume types or secret, configmaps etc.\n\tif rc.kubeClient != nil {\n\t\trc.updateDevicePath(volumesNeedUpdate)\n\t}\n\n\tfor _, gvl := range volumesNeedUpdate {\n\t\terr := rc.actualStateOfWorld.MarkVolumeAsAttached(\n\t\t\t//TODO: the devicePath might not be correct for some volume plugins: see issue #54108\n\t\t\tklog.TODO(), gvl.volumeName, gvl.volumeSpec, rc.nodeName, gvl.devicePath)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Could not add volume information to actual state of world\", \"volumeName\", gvl.volumeName)\n\t\t\tcontinue\n\t\t}\n\t\tfor _, volume := range gvl.podVolumes {\n\t\t\terr = rc.markVolumeState(volume, operationexecutor.VolumeMounted)\n\t\t\tif err != nil {\n\t\t\t\tklog.ErrorS(err, \"Could not add pod to volume information to actual state of world\", \"pod\", klog.KObj(volume.pod))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tklog.V(2).InfoS(\"Volume is marked as mounted and added into the actual state\", \"pod\", klog.KObj(volume.pod), \"podName\", volume.podName, \"volumeName\", volume.volumeName)\n\t\t}\n\t\t// If the volume has device to mount, we mark its device as mounted.\n\t\tif gvl.deviceMounter != nil || gvl.blockVolumeMapper != nil {\n\t\t\tdeviceMountPath, err := getDeviceMountPath(gvl)\n\t\t\tif err != nil {\n\t\t\t\tklog.ErrorS(err, \"Could not find device mount path for volume\", \"volumeName\", gvl.volumeName)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\terr = rc.actualStateOfWorld.MarkDeviceAsMounted(gvl.volumeName, gvl.devicePath, deviceMountPath, \"\")\n\t\t\tif err != nil {\n\t\t\t\tklog.ErrorS(err, \"Could not mark device is mounted to actual state of world\", \"volume\", gvl.volumeName)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tklog.V(2).InfoS(\"Volume is marked device as mounted and added into the actual state\", \"volumeName\", gvl.volumeName)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":132,"to":172}} {"id":100008046,"name":"markVolumeState","signature":"func (rc *reconciler) markVolumeState(volume *reconstructedVolume, volumeState operationexecutor.VolumeMountState) error","file":"pkg/kubelet/volumemanager/reconciler/reconstruct.go","code":"func (rc *reconciler) markVolumeState(volume *reconstructedVolume, volumeState operationexecutor.VolumeMountState) error {\n\tmarkVolumeOpts := operationexecutor.MarkVolumeOpts{\n\t\tPodName: volume.podName,\n\t\tPodUID: types.UID(volume.podName),\n\t\tVolumeName: volume.volumeName,\n\t\tMounter: volume.mounter,\n\t\tBlockVolumeMapper: volume.blockVolumeMapper,\n\t\tOuterVolumeSpecName: volume.outerVolumeSpecName,\n\t\tVolumeGidVolume: volume.volumeGidValue,\n\t\tVolumeSpec: volume.volumeSpec,\n\t\tVolumeMountState: volumeState,\n\t}\n\terr := rc.actualStateOfWorld.MarkVolumeAsMounted(markVolumeOpts)\n\treturn err\n}","line":{"from":174,"to":188}} {"id":100008047,"name":"updateLastSyncTime","signature":"func (rc *reconciler) updateLastSyncTime()","file":"pkg/kubelet/volumemanager/reconciler/reconstruct_common.go","code":"func (rc *reconciler) updateLastSyncTime() {\n\trc.timeOfLastSyncLock.Lock()\n\tdefer rc.timeOfLastSyncLock.Unlock()\n\trc.timeOfLastSync = time.Now()\n}","line":{"from":74,"to":78}} {"id":100008048,"name":"StatesHasBeenSynced","signature":"func (rc *reconciler) StatesHasBeenSynced() bool","file":"pkg/kubelet/volumemanager/reconciler/reconstruct_common.go","code":"func (rc *reconciler) StatesHasBeenSynced() bool {\n\trc.timeOfLastSyncLock.Lock()\n\tdefer rc.timeOfLastSyncLock.Unlock()\n\treturn !rc.timeOfLastSync.IsZero()\n}","line":{"from":80,"to":84}} {"id":100008049,"name":"addPodVolume","signature":"func (gvi *globalVolumeInfo) addPodVolume(rcv *reconstructedVolume)","file":"pkg/kubelet/volumemanager/reconciler/reconstruct_common.go","code":"func (gvi *globalVolumeInfo) addPodVolume(rcv *reconstructedVolume) {\n\tif gvi.podVolumes == nil {\n\t\tgvi.podVolumes = map[volumetypes.UniquePodName]*reconstructedVolume{}\n\t}\n\tgvi.podVolumes[rcv.podName] = rcv\n}","line":{"from":86,"to":91}} {"id":100008050,"name":"cleanupMounts","signature":"func (rc *reconciler) cleanupMounts(volume podVolume)","file":"pkg/kubelet/volumemanager/reconciler/reconstruct_common.go","code":"func (rc *reconciler) cleanupMounts(volume podVolume) {\n\tklog.V(2).InfoS(\"Reconciler sync states: could not find volume information in desired state, clean up the mount points\", \"podName\", volume.podName, \"volumeSpecName\", volume.volumeSpecName)\n\tmountedVolume := operationexecutor.MountedVolume{\n\t\tPodName: volume.podName,\n\t\tVolumeName: v1.UniqueVolumeName(volume.volumeSpecName),\n\t\tInnerVolumeSpecName: volume.volumeSpecName,\n\t\tPluginName: volume.pluginName,\n\t\tPodUID: types.UID(volume.podName),\n\t}\n\tmetrics.ForceCleanedFailedVolumeOperationsTotal.Inc()\n\t// TODO: Currently cleanupMounts only includes UnmountVolume operation. In the next PR, we will add\n\t// to unmount both volume and device in the same routine.\n\terr := rc.operationExecutor.UnmountVolume(mountedVolume, rc.actualStateOfWorld, rc.kubeletPodsDir)\n\tif err != nil {\n\t\tmetrics.ForceCleanedFailedVolumeOperationsErrorsTotal.Inc()\n\t\tklog.ErrorS(err, mountedVolume.GenerateErrorDetailed(\"volumeHandler.UnmountVolumeHandler for UnmountVolume failed\", err).Error())\n\t\treturn\n\t}\n}","line":{"from":93,"to":111}} {"id":100008051,"name":"getDeviceMountPath","signature":"func getDeviceMountPath(gvi *globalVolumeInfo) (string, error)","file":"pkg/kubelet/volumemanager/reconciler/reconstruct_common.go","code":"// getDeviceMountPath returns device mount path for block volume which\n// implements BlockVolumeMapper or filesystem volume which implements\n// DeviceMounter\nfunc getDeviceMountPath(gvi *globalVolumeInfo) (string, error) {\n\tif gvi.blockVolumeMapper != nil {\n\t\t// for block gvi, we return its global map path\n\t\treturn gvi.blockVolumeMapper.GetGlobalMapPath(gvi.volumeSpec)\n\t} else if gvi.deviceMounter != nil {\n\t\t// for filesystem gvi, we return its device mount path if the plugin implements DeviceMounter\n\t\treturn gvi.deviceMounter.GetDeviceMountPath(gvi.volumeSpec)\n\t} else {\n\t\treturn \"\", fmt.Errorf(\"blockVolumeMapper or deviceMounter required\")\n\t}\n}","line":{"from":113,"to":126}} {"id":100008052,"name":"getVolumesFromPodDir","signature":"func getVolumesFromPodDir(podDir string) ([]podVolume, error)","file":"pkg/kubelet/volumemanager/reconciler/reconstruct_common.go","code":"// getVolumesFromPodDir scans through the volumes directories under the given pod directory.\n// It returns a list of pod volume information including pod's uid, volume's plugin name, mount path,\n// and volume spec name.\nfunc getVolumesFromPodDir(podDir string) ([]podVolume, error) {\n\tpodsDirInfo, err := os.ReadDir(podDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvolumes := []podVolume{}\n\tfor i := range podsDirInfo {\n\t\tif !podsDirInfo[i].IsDir() {\n\t\t\tcontinue\n\t\t}\n\t\tpodName := podsDirInfo[i].Name()\n\t\tpodDir := filepath.Join(podDir, podName)\n\n\t\t// Find filesystem volume information\n\t\t// ex. filesystem volume: /pods/{podUid}/volumes/{escapeQualifiedPluginName}/{volumeName}\n\t\tvolumesDirs := map[v1.PersistentVolumeMode]string{\n\t\t\tv1.PersistentVolumeFilesystem: filepath.Join(podDir, config.DefaultKubeletVolumesDirName),\n\t\t}\n\t\t// Find block volume information\n\t\t// ex. block volume: /pods/{podUid}/volumeDevices/{escapeQualifiedPluginName}/{volumeName}\n\t\tvolumesDirs[v1.PersistentVolumeBlock] = filepath.Join(podDir, config.DefaultKubeletVolumeDevicesDirName)\n\n\t\tfor volumeMode, volumesDir := range volumesDirs {\n\t\t\tvar volumesDirInfo []fs.DirEntry\n\t\t\tif volumesDirInfo, err = os.ReadDir(volumesDir); err != nil {\n\t\t\t\t// Just skip the loop because given volumesDir doesn't exist depending on volumeMode\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor _, volumeDir := range volumesDirInfo {\n\t\t\t\tpluginName := volumeDir.Name()\n\t\t\t\tvolumePluginPath := filepath.Join(volumesDir, pluginName)\n\t\t\t\tvolumePluginDirs, err := utilpath.ReadDirNoStat(volumePluginPath)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"Could not read volume plugin directory\", \"volumePluginPath\", volumePluginPath)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tunescapePluginName := utilstrings.UnescapeQualifiedName(pluginName)\n\t\t\t\tfor _, volumeName := range volumePluginDirs {\n\t\t\t\t\tvolumePath := filepath.Join(volumePluginPath, volumeName)\n\t\t\t\t\tklog.V(5).InfoS(\"Volume path from volume plugin directory\", \"podName\", podName, \"volumePath\", volumePath)\n\t\t\t\t\tvolumes = append(volumes, podVolume{\n\t\t\t\t\t\tpodName: volumetypes.UniquePodName(podName),\n\t\t\t\t\t\tvolumeSpecName: volumeName,\n\t\t\t\t\t\tvolumePath: volumePath,\n\t\t\t\t\t\tpluginName: unescapePluginName,\n\t\t\t\t\t\tvolumeMode: volumeMode,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tklog.V(4).InfoS(\"Get volumes from pod directory\", \"path\", podDir, \"volumes\", volumes)\n\treturn volumes, nil\n}","line":{"from":128,"to":184}} {"id":100008053,"name":"reconstructVolume","signature":"func (rc *reconciler) reconstructVolume(volume podVolume) (rvolume *reconstructedVolume, rerr error)","file":"pkg/kubelet/volumemanager/reconciler/reconstruct_common.go","code":"// Reconstruct volume data structure by reading the pod's volume directories\nfunc (rc *reconciler) reconstructVolume(volume podVolume) (rvolume *reconstructedVolume, rerr error) {\n\tmetrics.ReconstructVolumeOperationsTotal.Inc()\n\tdefer func() {\n\t\tif rerr != nil {\n\t\t\tmetrics.ReconstructVolumeOperationsErrorsTotal.Inc()\n\t\t}\n\t}()\n\n\t// plugin initializations\n\tplugin, err := rc.volumePluginMgr.FindPluginByName(volume.pluginName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create pod object\n\tpod := \u0026v1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tUID: types.UID(volume.podName),\n\t\t},\n\t}\n\tmapperPlugin, err := rc.volumePluginMgr.FindMapperPluginByName(volume.pluginName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif volume.volumeMode == v1.PersistentVolumeBlock \u0026\u0026 mapperPlugin == nil {\n\t\treturn nil, fmt.Errorf(\"could not find block volume plugin %q (spec.Name: %q) pod %q (UID: %q)\", volume.pluginName, volume.volumeSpecName, volume.podName, pod.UID)\n\t}\n\n\treconstructed, err := rc.operationExecutor.ReconstructVolumeOperation(\n\t\tvolume.volumeMode,\n\t\tplugin,\n\t\tmapperPlugin,\n\t\tpod.UID,\n\t\tvolume.podName,\n\t\tvolume.volumeSpecName,\n\t\tvolume.volumePath,\n\t\tvolume.pluginName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvolumeSpec := reconstructed.Spec\n\tif volumeSpec == nil {\n\t\treturn nil, fmt.Errorf(\"failed to reconstruct volume for plugin %q (spec.Name: %q) pod %q (UID: %q): got nil\", volume.pluginName, volume.volumeSpecName, volume.podName, pod.UID)\n\t}\n\n\t// We have to find the plugins by volume spec (NOT by plugin name) here\n\t// in order to correctly reconstruct ephemeral volume types.\n\t// Searching by spec checks whether the volume is actually attachable\n\t// (i.e. has a PV) whereas searching by plugin name can only tell whether\n\t// the plugin supports attachable volumes.\n\tattachablePlugin, err := rc.volumePluginMgr.FindAttachablePluginBySpec(volumeSpec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdeviceMountablePlugin, err := rc.volumePluginMgr.FindDeviceMountablePluginBySpec(volumeSpec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar uniqueVolumeName v1.UniqueVolumeName\n\tif attachablePlugin != nil || deviceMountablePlugin != nil {\n\t\tuniqueVolumeName, err = util.GetUniqueVolumeNameFromSpec(plugin, volumeSpec)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tuniqueVolumeName = util.GetUniqueVolumeNameFromSpecWithPod(volume.podName, plugin, volumeSpec)\n\t}\n\n\tvar volumeMapper volumepkg.BlockVolumeMapper\n\tvar volumeMounter volumepkg.Mounter\n\tvar deviceMounter volumepkg.DeviceMounter\n\t// Path to the mount or block device to check\n\tvar checkPath string\n\n\tif volume.volumeMode == v1.PersistentVolumeBlock {\n\t\tvar newMapperErr error\n\t\tvolumeMapper, newMapperErr = mapperPlugin.NewBlockVolumeMapper(\n\t\t\tvolumeSpec,\n\t\t\tpod,\n\t\t\tvolumepkg.VolumeOptions{})\n\t\tif newMapperErr != nil {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"reconstructVolume.NewBlockVolumeMapper failed for volume %q (spec.Name: %q) pod %q (UID: %q) with: %v\",\n\t\t\t\tuniqueVolumeName,\n\t\t\t\tvolumeSpec.Name(),\n\t\t\t\tvolume.podName,\n\t\t\t\tpod.UID,\n\t\t\t\tnewMapperErr)\n\t\t}\n\t\tmapDir, linkName := volumeMapper.GetPodDeviceMapPath()\n\t\tcheckPath = filepath.Join(mapDir, linkName)\n\t} else {\n\t\tvar err error\n\t\tvolumeMounter, err = plugin.NewMounter(\n\t\t\tvolumeSpec,\n\t\t\tpod,\n\t\t\tvolumepkg.VolumeOptions{})\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"reconstructVolume.NewMounter failed for volume %q (spec.Name: %q) pod %q (UID: %q) with: %v\",\n\t\t\t\tuniqueVolumeName,\n\t\t\t\tvolumeSpec.Name(),\n\t\t\t\tvolume.podName,\n\t\t\t\tpod.UID,\n\t\t\t\terr)\n\t\t}\n\t\tcheckPath = volumeMounter.GetPath()\n\t\tif deviceMountablePlugin != nil {\n\t\t\tdeviceMounter, err = deviceMountablePlugin.NewDeviceMounter()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"reconstructVolume.NewDeviceMounter failed for volume %q (spec.Name: %q) pod %q (UID: %q) with: %v\",\n\t\t\t\t\tuniqueVolumeName,\n\t\t\t\t\tvolumeSpec.Name(),\n\t\t\t\t\tvolume.podName,\n\t\t\t\t\tpod.UID,\n\t\t\t\t\terr)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check existence of mount point for filesystem volume or symbolic link for block volume\n\tisExist, checkErr := rc.operationExecutor.CheckVolumeExistenceOperation(volumeSpec, checkPath, volumeSpec.Name(), rc.mounter, uniqueVolumeName, volume.podName, pod.UID, attachablePlugin)\n\tif checkErr != nil {\n\t\treturn nil, checkErr\n\t}\n\t// If mount or symlink doesn't exist, volume reconstruction should be failed\n\tif !isExist {\n\t\treturn nil, fmt.Errorf(\"volume: %q is not mounted\", uniqueVolumeName)\n\t}\n\n\treconstructedVolume := \u0026reconstructedVolume{\n\t\tvolumeName: uniqueVolumeName,\n\t\tpodName: volume.podName,\n\t\tvolumeSpec: volumeSpec,\n\t\t// volume.volumeSpecName is actually InnerVolumeSpecName. It will not be used\n\t\t// for volume cleanup.\n\t\t// in case pod is added back to desired state, outerVolumeSpecName will be updated from dsw information.\n\t\t// See issue #103143 and its fix for details.\n\t\touterVolumeSpecName: volume.volumeSpecName,\n\t\tpod: pod,\n\t\tdeviceMounter: deviceMounter,\n\t\tvolumeGidValue: \"\",\n\t\t// devicePath is updated during updateStates() by checking node status's VolumesAttached data.\n\t\t// TODO: get device path directly from the volume mount path.\n\t\tdevicePath: \"\",\n\t\tmounter: volumeMounter,\n\t\tblockVolumeMapper: volumeMapper,\n\t\tseLinuxMountContext: reconstructed.SELinuxMountContext,\n\t}\n\treturn reconstructedVolume, nil\n}","line":{"from":186,"to":338}} {"id":100008054,"name":"readyToUnmount","signature":"func (rc *reconciler) readyToUnmount() bool","file":"pkg/kubelet/volumemanager/reconciler/reconstruct_new.go","code":"// readyToUnmount returns true when reconciler can start unmounting volumes.\nfunc (rc *reconciler) readyToUnmount() bool {\n\t// During kubelet startup, all volumes present on disk are added as uncertain to ASW.\n\t// Allow unmount only when DSW is fully populated to prevent unmounting volumes that\n\t// did not reach DSW yet.\n\tif !rc.populatorHasAddedPods() {\n\t\treturn false\n\t}\n\n\t// Allow unmount only when ASW device paths were corrected from node.status to prevent\n\t// calling unmount with a wrong devicePath.\n\tif len(rc.volumesNeedDevicePath) != 0 {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":31,"to":46}} {"id":100008055,"name":"reconstructVolumes","signature":"func (rc *reconciler) reconstructVolumes()","file":"pkg/kubelet/volumemanager/reconciler/reconstruct_new.go","code":"// reconstructVolumes tries to reconstruct the actual state of world by scanning all pods' volume\n// directories from the disk. For the volumes that cannot support or fail reconstruction, it will\n// put the volumes to volumesFailedReconstruction to be cleaned up later when DesiredStateOfWorld\n// is populated.\nfunc (rc *reconciler) reconstructVolumes() {\n\tdefer rc.updateLastSyncTime()\n\t// Get volumes information by reading the pod's directory\n\tpodVolumes, err := getVolumesFromPodDir(rc.kubeletPodsDir)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Cannot get volumes from disk, skip sync states for volume reconstruction\")\n\t\treturn\n\t}\n\treconstructedVolumes := make(map[v1.UniqueVolumeName]*globalVolumeInfo)\n\treconstructedVolumeNames := []v1.UniqueVolumeName{}\n\tfor _, volume := range podVolumes {\n\t\tif rc.actualStateOfWorld.VolumeExistsWithSpecName(volume.podName, volume.volumeSpecName) {\n\t\t\tklog.V(4).InfoS(\"Volume exists in actual state, skip cleaning up mounts\", \"podName\", volume.podName, \"volumeSpecName\", volume.volumeSpecName)\n\t\t\t// There is nothing to reconstruct\n\t\t\tcontinue\n\t\t}\n\t\treconstructedVolume, err := rc.reconstructVolume(volume)\n\t\tif err != nil {\n\t\t\tklog.InfoS(\"Could not construct volume information\", \"podName\", volume.podName, \"volumeSpecName\", volume.volumeSpecName, \"err\", err)\n\t\t\t// We can't reconstruct the volume. Remember to check DSW after it's fully populated and force unmount the volume when it's orphaned.\n\t\t\trc.volumesFailedReconstruction = append(rc.volumesFailedReconstruction, volume)\n\t\t\tcontinue\n\t\t}\n\t\tklog.V(4).InfoS(\"Adding reconstructed volume to actual state and node status\", \"podName\", volume.podName, \"volumeSpecName\", volume.volumeSpecName)\n\t\tgvl := \u0026globalVolumeInfo{\n\t\t\tvolumeName: reconstructedVolume.volumeName,\n\t\t\tvolumeSpec: reconstructedVolume.volumeSpec,\n\t\t\tdevicePath: reconstructedVolume.devicePath,\n\t\t\tdeviceMounter: reconstructedVolume.deviceMounter,\n\t\t\tblockVolumeMapper: reconstructedVolume.blockVolumeMapper,\n\t\t\tmounter: reconstructedVolume.mounter,\n\t\t}\n\t\tif cachedInfo, ok := reconstructedVolumes[reconstructedVolume.volumeName]; ok {\n\t\t\tgvl = cachedInfo\n\t\t}\n\t\tgvl.addPodVolume(reconstructedVolume)\n\n\t\treconstructedVolumeNames = append(reconstructedVolumeNames, reconstructedVolume.volumeName)\n\t\treconstructedVolumes[reconstructedVolume.volumeName] = gvl\n\t}\n\n\tif len(reconstructedVolumes) \u003e 0 {\n\t\t// Add the volumes to ASW\n\t\trc.updateStatesNew(reconstructedVolumes)\n\n\t\t// The reconstructed volumes are mounted, hence a previous kubelet must have already put it into node.status.volumesInUse.\n\t\t// Remember to update DSW with this information.\n\t\trc.volumesNeedReportedInUse = reconstructedVolumeNames\n\t\t// Remember to update devicePath from node.status.volumesAttached\n\t\trc.volumesNeedDevicePath = reconstructedVolumeNames\n\t}\n\tklog.V(2).InfoS(\"Volume reconstruction finished\")\n}","line":{"from":48,"to":104}} {"id":100008056,"name":"updateStatesNew","signature":"func (rc *reconciler) updateStatesNew(reconstructedVolumes map[v1.UniqueVolumeName]*globalVolumeInfo)","file":"pkg/kubelet/volumemanager/reconciler/reconstruct_new.go","code":"func (rc *reconciler) updateStatesNew(reconstructedVolumes map[v1.UniqueVolumeName]*globalVolumeInfo) {\n\tfor _, gvl := range reconstructedVolumes {\n\t\terr := rc.actualStateOfWorld.MarkVolumeAsAttached(\n\t\t\t//TODO: the devicePath might not be correct for some volume plugins: see issue #54108\n\t\t\tklog.TODO(), gvl.volumeName, gvl.volumeSpec, rc.nodeName, gvl.devicePath)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Could not add volume information to actual state of world\", \"volumeName\", gvl.volumeName)\n\t\t\tcontinue\n\t\t}\n\t\tvar seLinuxMountContext string\n\t\tfor _, volume := range gvl.podVolumes {\n\t\t\tmarkVolumeOpts := operationexecutor.MarkVolumeOpts{\n\t\t\t\tPodName: volume.podName,\n\t\t\t\tPodUID: types.UID(volume.podName),\n\t\t\t\tVolumeName: volume.volumeName,\n\t\t\t\tMounter: volume.mounter,\n\t\t\t\tBlockVolumeMapper: volume.blockVolumeMapper,\n\t\t\t\tOuterVolumeSpecName: volume.outerVolumeSpecName,\n\t\t\t\tVolumeGidVolume: volume.volumeGidValue,\n\t\t\t\tVolumeSpec: volume.volumeSpec,\n\t\t\t\tVolumeMountState: operationexecutor.VolumeMountUncertain,\n\t\t\t\tSELinuxMountContext: volume.seLinuxMountContext,\n\t\t\t}\n\n\t\t\t_, err = rc.actualStateOfWorld.CheckAndMarkVolumeAsUncertainViaReconstruction(markVolumeOpts)\n\t\t\tif err != nil {\n\t\t\t\tklog.ErrorS(err, \"Could not add pod to volume information to actual state of world\", \"pod\", klog.KObj(volume.pod))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tseLinuxMountContext = volume.seLinuxMountContext\n\t\t\tklog.V(2).InfoS(\"Volume is marked as uncertain and added into the actual state\", \"pod\", klog.KObj(volume.pod), \"podName\", volume.podName, \"volumeName\", volume.volumeName, \"seLinuxMountContext\", volume.seLinuxMountContext)\n\t\t}\n\t\t// If the volume has device to mount, we mark its device as uncertain.\n\t\tif gvl.deviceMounter != nil || gvl.blockVolumeMapper != nil {\n\t\t\tdeviceMountPath, err := getDeviceMountPath(gvl)\n\t\t\tif err != nil {\n\t\t\t\tklog.ErrorS(err, \"Could not find device mount path for volume\", \"volumeName\", gvl.volumeName)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\terr = rc.actualStateOfWorld.MarkDeviceAsUncertain(gvl.volumeName, gvl.devicePath, deviceMountPath, seLinuxMountContext)\n\t\t\tif err != nil {\n\t\t\t\tklog.ErrorS(err, \"Could not mark device is uncertain to actual state of world\", \"volumeName\", gvl.volumeName, \"deviceMountPath\", deviceMountPath)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tklog.V(2).InfoS(\"Volume is marked device as uncertain and added into the actual state\", \"volumeName\", gvl.volumeName, \"deviceMountPath\", deviceMountPath)\n\t\t}\n\t}\n}","line":{"from":106,"to":153}} {"id":100008057,"name":"cleanOrphanVolumes","signature":"func (rc *reconciler) cleanOrphanVolumes()","file":"pkg/kubelet/volumemanager/reconciler/reconstruct_new.go","code":"// cleanOrphanVolumes tries to clean up all volumes that failed reconstruction.\nfunc (rc *reconciler) cleanOrphanVolumes() {\n\tif len(rc.volumesFailedReconstruction) == 0 {\n\t\treturn\n\t}\n\n\tfor _, volume := range rc.volumesFailedReconstruction {\n\t\tif rc.desiredStateOfWorld.VolumeExistsWithSpecName(volume.podName, volume.volumeSpecName) {\n\t\t\t// Some pod needs the volume, don't clean it up and hope that\n\t\t\t// reconcile() calls SetUp and reconstructs the volume in ASW.\n\t\t\tklog.V(4).InfoS(\"Volume exists in desired state, skip cleaning up mounts\", \"podName\", volume.podName, \"volumeSpecName\", volume.volumeSpecName)\n\t\t\tcontinue\n\t\t}\n\t\tklog.InfoS(\"Cleaning up mounts for volume that could not be reconstructed\", \"podName\", volume.podName, \"volumeSpecName\", volume.volumeSpecName)\n\t\trc.cleanupMounts(volume)\n\t}\n\n\tklog.V(2).InfoS(\"Orphan volume cleanup finished\")\n\t// Clean the cache, cleanup is one shot operation.\n\trc.volumesFailedReconstruction = make([]podVolume, 0)\n}","line":{"from":155,"to":175}} {"id":100008058,"name":"updateReconstructedDevicePaths","signature":"func (rc *reconciler) updateReconstructedDevicePaths()","file":"pkg/kubelet/volumemanager/reconciler/reconstruct_new.go","code":"// updateReconstructedDevicePaths tries to file devicePaths of reconstructed volumes from\n// node.Status.VolumesAttached. This can be done only after connection to the API\n// server is established, i.e. it can't be part of reconstructVolumes().\nfunc (rc *reconciler) updateReconstructedDevicePaths() {\n\tklog.V(4).InfoS(\"Updating reconstructed devicePaths\")\n\n\tif rc.kubeClient == nil {\n\t\t// Skip reconstructing devicePath from node objects if kubelet is in standalone mode.\n\t\t// Such kubelet is not expected to mount any attachable volume or Secrets / ConfigMap.\n\t\tklog.V(2).InfoS(\"Skipped reconstruction of DevicePaths from node.status in standalone mode\")\n\t\trc.volumesNeedDevicePath = nil\n\t\treturn\n\t}\n\n\tnode, fetchErr := rc.kubeClient.CoreV1().Nodes().Get(context.TODO(), string(rc.nodeName), metav1.GetOptions{})\n\tif fetchErr != nil {\n\t\t// This may repeat few times per second until kubelet is able to read its own status for the first time.\n\t\tklog.V(2).ErrorS(fetchErr, \"Failed to get Node status to reconstruct device paths\")\n\t\treturn\n\t}\n\n\tfor _, volumeID := range rc.volumesNeedDevicePath {\n\t\tfor _, attachedVolume := range node.Status.VolumesAttached {\n\t\t\tif volumeID != attachedVolume.Name {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\trc.actualStateOfWorld.UpdateReconstructedDevicePath(volumeID, attachedVolume.DevicePath)\n\t\t\tklog.V(4).InfoS(\"Updated devicePath from node status for volume\", \"volumeName\", attachedVolume.Name, \"path\", attachedVolume.DevicePath)\n\t\t}\n\t}\n\tklog.V(2).InfoS(\"DevicePaths of reconstructed volumes updated\")\n\trc.volumesNeedDevicePath = nil\n}","line":{"from":177,"to":209}} {"id":100008059,"name":"NewVolumeManager","signature":"func NewVolumeManager(","file":"pkg/kubelet/volumemanager/volume_manager.go","code":"// NewVolumeManager returns a new concrete instance implementing the\n// VolumeManager interface.\n//\n// kubeClient - kubeClient is the kube API client used by DesiredStateOfWorldPopulator\n// to communicate with the API server to fetch PV and PVC objects\n//\n// volumePluginMgr - the volume plugin manager used to access volume plugins.\n// Must be pre-initialized.\nfunc NewVolumeManager(\n\tcontrollerAttachDetachEnabled bool,\n\tnodeName k8stypes.NodeName,\n\tpodManager pod.Manager,\n\tpodStateProvider podStateProvider,\n\tkubeClient clientset.Interface,\n\tvolumePluginMgr *volume.VolumePluginMgr,\n\tkubeContainerRuntime container.Runtime,\n\tmounter mount.Interface,\n\thostutil hostutil.HostUtils,\n\tkubeletPodsDir string,\n\trecorder record.EventRecorder,\n\tkeepTerminatedPodVolumes bool,\n\tblockVolumePathHandler volumepathhandler.BlockVolumePathHandler) VolumeManager {\n\n\tseLinuxTranslator := util.NewSELinuxLabelTranslator()\n\tvm := \u0026volumeManager{\n\t\tkubeClient: kubeClient,\n\t\tvolumePluginMgr: volumePluginMgr,\n\t\tdesiredStateOfWorld: cache.NewDesiredStateOfWorld(volumePluginMgr, seLinuxTranslator),\n\t\tactualStateOfWorld: cache.NewActualStateOfWorld(nodeName, volumePluginMgr),\n\t\toperationExecutor: operationexecutor.NewOperationExecutor(operationexecutor.NewOperationGenerator(\n\t\t\tkubeClient,\n\t\t\tvolumePluginMgr,\n\t\t\trecorder,\n\t\t\tblockVolumePathHandler)),\n\t}\n\n\tintreeToCSITranslator := csitrans.New()\n\tcsiMigratedPluginManager := csimigration.NewPluginManager(intreeToCSITranslator, utilfeature.DefaultFeatureGate)\n\n\tvm.intreeToCSITranslator = intreeToCSITranslator\n\tvm.csiMigratedPluginManager = csiMigratedPluginManager\n\tvm.desiredStateOfWorldPopulator = populator.NewDesiredStateOfWorldPopulator(\n\t\tkubeClient,\n\t\tdesiredStateOfWorldPopulatorLoopSleepPeriod,\n\t\tpodManager,\n\t\tpodStateProvider,\n\t\tvm.desiredStateOfWorld,\n\t\tvm.actualStateOfWorld,\n\t\tkubeContainerRuntime,\n\t\tkeepTerminatedPodVolumes,\n\t\tcsiMigratedPluginManager,\n\t\tintreeToCSITranslator,\n\t\tvolumePluginMgr)\n\tvm.reconciler = reconciler.NewReconciler(\n\t\tkubeClient,\n\t\tcontrollerAttachDetachEnabled,\n\t\treconcilerLoopSleepPeriod,\n\t\twaitForAttachTimeout,\n\t\tnodeName,\n\t\tvm.desiredStateOfWorld,\n\t\tvm.actualStateOfWorld,\n\t\tvm.desiredStateOfWorldPopulator.HasAddedPods,\n\t\tvm.operationExecutor,\n\t\tmounter,\n\t\thostutil,\n\t\tvolumePluginMgr,\n\t\tkubeletPodsDir)\n\n\treturn vm\n}","line":{"from":158,"to":227}} {"id":100008060,"name":"Run","signature":"func (vm *volumeManager) Run(sourcesReady config.SourcesReady, stopCh \u003c-chan struct{})","file":"pkg/kubelet/volumemanager/volume_manager.go","code":"func (vm *volumeManager) Run(sourcesReady config.SourcesReady, stopCh \u003c-chan struct{}) {\n\tdefer runtime.HandleCrash()\n\n\tif vm.kubeClient != nil {\n\t\t// start informer for CSIDriver\n\t\tgo vm.volumePluginMgr.Run(stopCh)\n\t}\n\n\tgo vm.desiredStateOfWorldPopulator.Run(sourcesReady, stopCh)\n\tklog.V(2).InfoS(\"The desired_state_of_world populator starts\")\n\n\tklog.InfoS(\"Starting Kubelet Volume Manager\")\n\tgo vm.reconciler.Run(stopCh)\n\n\tmetrics.Register(vm.actualStateOfWorld, vm.desiredStateOfWorld, vm.volumePluginMgr)\n\n\t\u003c-stopCh\n\tklog.InfoS(\"Shutting down Kubelet Volume Manager\")\n}","line":{"from":273,"to":291}} {"id":100008061,"name":"GetMountedVolumesForPod","signature":"func (vm *volumeManager) GetMountedVolumesForPod(podName types.UniquePodName) container.VolumeMap","file":"pkg/kubelet/volumemanager/volume_manager.go","code":"func (vm *volumeManager) GetMountedVolumesForPod(podName types.UniquePodName) container.VolumeMap {\n\tpodVolumes := make(container.VolumeMap)\n\tfor _, mountedVolume := range vm.actualStateOfWorld.GetMountedVolumesForPod(podName) {\n\t\tpodVolumes[mountedVolume.OuterVolumeSpecName] = container.VolumeInfo{\n\t\t\tMounter: mountedVolume.Mounter,\n\t\t\tBlockVolumeMapper: mountedVolume.BlockVolumeMapper,\n\t\t\tReadOnly: mountedVolume.VolumeSpec.ReadOnly,\n\t\t\tInnerVolumeSpecName: mountedVolume.InnerVolumeSpecName,\n\t\t}\n\t}\n\treturn podVolumes\n}","line":{"from":293,"to":304}} {"id":100008062,"name":"GetPossiblyMountedVolumesForPod","signature":"func (vm *volumeManager) GetPossiblyMountedVolumesForPod(podName types.UniquePodName) container.VolumeMap","file":"pkg/kubelet/volumemanager/volume_manager.go","code":"func (vm *volumeManager) GetPossiblyMountedVolumesForPod(podName types.UniquePodName) container.VolumeMap {\n\tpodVolumes := make(container.VolumeMap)\n\tfor _, mountedVolume := range vm.actualStateOfWorld.GetPossiblyMountedVolumesForPod(podName) {\n\t\tpodVolumes[mountedVolume.OuterVolumeSpecName] = container.VolumeInfo{\n\t\t\tMounter: mountedVolume.Mounter,\n\t\t\tBlockVolumeMapper: mountedVolume.BlockVolumeMapper,\n\t\t\tReadOnly: mountedVolume.VolumeSpec.ReadOnly,\n\t\t\tInnerVolumeSpecName: mountedVolume.InnerVolumeSpecName,\n\t\t}\n\t}\n\treturn podVolumes\n}","line":{"from":306,"to":317}} {"id":100008063,"name":"GetExtraSupplementalGroupsForPod","signature":"func (vm *volumeManager) GetExtraSupplementalGroupsForPod(pod *v1.Pod) []int64","file":"pkg/kubelet/volumemanager/volume_manager.go","code":"func (vm *volumeManager) GetExtraSupplementalGroupsForPod(pod *v1.Pod) []int64 {\n\tpodName := util.GetUniquePodName(pod)\n\tsupplementalGroups := sets.NewString()\n\n\tfor _, mountedVolume := range vm.actualStateOfWorld.GetMountedVolumesForPod(podName) {\n\t\tif mountedVolume.VolumeGidValue != \"\" {\n\t\t\tsupplementalGroups.Insert(mountedVolume.VolumeGidValue)\n\t\t}\n\t}\n\n\tresult := make([]int64, 0, supplementalGroups.Len())\n\tfor _, group := range supplementalGroups.List() {\n\t\tiGroup, extra := getExtraSupplementalGid(group, pod)\n\t\tif !extra {\n\t\t\tcontinue\n\t\t}\n\n\t\tresult = append(result, int64(iGroup))\n\t}\n\n\treturn result\n}","line":{"from":319,"to":340}} {"id":100008064,"name":"GetVolumesInUse","signature":"func (vm *volumeManager) GetVolumesInUse() []v1.UniqueVolumeName","file":"pkg/kubelet/volumemanager/volume_manager.go","code":"func (vm *volumeManager) GetVolumesInUse() []v1.UniqueVolumeName {\n\t// Report volumes in desired state of world and actual state of world so\n\t// that volumes are marked in use as soon as the decision is made that the\n\t// volume *should* be attached to this node until it is safely unmounted.\n\tdesiredVolumes := vm.desiredStateOfWorld.GetVolumesToMount()\n\tallAttachedVolumes := vm.actualStateOfWorld.GetAttachedVolumes()\n\tvolumesToReportInUse := make([]v1.UniqueVolumeName, 0, len(desiredVolumes)+len(allAttachedVolumes))\n\tdesiredVolumesMap := make(map[v1.UniqueVolumeName]bool, len(desiredVolumes)+len(allAttachedVolumes))\n\n\tfor _, volume := range desiredVolumes {\n\t\tif volume.PluginIsAttachable {\n\t\t\tif _, exists := desiredVolumesMap[volume.VolumeName]; !exists {\n\t\t\t\tdesiredVolumesMap[volume.VolumeName] = true\n\t\t\t\tvolumesToReportInUse = append(volumesToReportInUse, volume.VolumeName)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, volume := range allAttachedVolumes {\n\t\tif volume.PluginIsAttachable {\n\t\t\tif _, exists := desiredVolumesMap[volume.VolumeName]; !exists {\n\t\t\t\tvolumesToReportInUse = append(volumesToReportInUse, volume.VolumeName)\n\t\t\t}\n\t\t}\n\t}\n\n\tsort.Slice(volumesToReportInUse, func(i, j int) bool {\n\t\treturn string(volumesToReportInUse[i]) \u003c string(volumesToReportInUse[j])\n\t})\n\treturn volumesToReportInUse\n}","line":{"from":342,"to":372}} {"id":100008065,"name":"ReconcilerStatesHasBeenSynced","signature":"func (vm *volumeManager) ReconcilerStatesHasBeenSynced() bool","file":"pkg/kubelet/volumemanager/volume_manager.go","code":"func (vm *volumeManager) ReconcilerStatesHasBeenSynced() bool {\n\treturn vm.reconciler.StatesHasBeenSynced()\n}","line":{"from":374,"to":376}} {"id":100008066,"name":"VolumeIsAttached","signature":"func (vm *volumeManager) VolumeIsAttached(","file":"pkg/kubelet/volumemanager/volume_manager.go","code":"func (vm *volumeManager) VolumeIsAttached(\n\tvolumeName v1.UniqueVolumeName) bool {\n\treturn vm.actualStateOfWorld.VolumeExists(volumeName)\n}","line":{"from":378,"to":381}} {"id":100008067,"name":"MarkVolumesAsReportedInUse","signature":"func (vm *volumeManager) MarkVolumesAsReportedInUse(","file":"pkg/kubelet/volumemanager/volume_manager.go","code":"func (vm *volumeManager) MarkVolumesAsReportedInUse(\n\tvolumesReportedAsInUse []v1.UniqueVolumeName) {\n\tvm.desiredStateOfWorld.MarkVolumesReportedInUse(volumesReportedAsInUse)\n}","line":{"from":383,"to":386}} {"id":100008068,"name":"WaitForAttachAndMount","signature":"func (vm *volumeManager) WaitForAttachAndMount(pod *v1.Pod) error","file":"pkg/kubelet/volumemanager/volume_manager.go","code":"func (vm *volumeManager) WaitForAttachAndMount(pod *v1.Pod) error {\n\tif pod == nil {\n\t\treturn nil\n\t}\n\n\texpectedVolumes := getExpectedVolumes(pod)\n\tif len(expectedVolumes) == 0 {\n\t\t// No volumes to verify\n\t\treturn nil\n\t}\n\n\tklog.V(3).InfoS(\"Waiting for volumes to attach and mount for pod\", \"pod\", klog.KObj(pod))\n\tuniquePodName := util.GetUniquePodName(pod)\n\n\t// Some pods expect to have Setup called over and over again to update.\n\t// Remount plugins for which this is true. (Atomically updating volumes,\n\t// like Downward API, depend on this to update the contents of the volume).\n\tvm.desiredStateOfWorldPopulator.ReprocessPod(uniquePodName)\n\n\terr := wait.PollImmediate(\n\t\tpodAttachAndMountRetryInterval,\n\t\tpodAttachAndMountTimeout,\n\t\tvm.verifyVolumesMountedFunc(uniquePodName, expectedVolumes))\n\n\tif err != nil {\n\t\tunmountedVolumes :=\n\t\t\tvm.getUnmountedVolumes(uniquePodName, expectedVolumes)\n\t\t// Also get unattached volumes and volumes not in dsw for error message\n\t\tunattachedVolumes :=\n\t\t\tvm.getUnattachedVolumes(uniquePodName)\n\t\tvolumesNotInDSW :=\n\t\t\tvm.getVolumesNotInDSW(uniquePodName, expectedVolumes)\n\n\t\tif len(unmountedVolumes) == 0 {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn fmt.Errorf(\n\t\t\t\"unmounted volumes=%v, unattached volumes=%v, failed to process volumes=%v: %s\",\n\t\t\tunmountedVolumes,\n\t\t\tunattachedVolumes,\n\t\t\tvolumesNotInDSW,\n\t\t\terr)\n\t}\n\n\tklog.V(3).InfoS(\"All volumes are attached and mounted for pod\", \"pod\", klog.KObj(pod))\n\treturn nil\n}","line":{"from":388,"to":435}} {"id":100008069,"name":"WaitForUnmount","signature":"func (vm *volumeManager) WaitForUnmount(pod *v1.Pod) error","file":"pkg/kubelet/volumemanager/volume_manager.go","code":"func (vm *volumeManager) WaitForUnmount(pod *v1.Pod) error {\n\tif pod == nil {\n\t\treturn nil\n\t}\n\n\tklog.V(3).InfoS(\"Waiting for volumes to unmount for pod\", \"pod\", klog.KObj(pod))\n\tuniquePodName := util.GetUniquePodName(pod)\n\n\tvm.desiredStateOfWorldPopulator.ReprocessPod(uniquePodName)\n\n\terr := wait.PollImmediate(\n\t\tpodAttachAndMountRetryInterval,\n\t\tpodAttachAndMountTimeout,\n\t\tvm.verifyVolumesUnmountedFunc(uniquePodName))\n\n\tif err != nil {\n\t\tvar mountedVolumes []string\n\t\tfor _, v := range vm.actualStateOfWorld.GetMountedVolumesForPod(uniquePodName) {\n\t\t\tmountedVolumes = append(mountedVolumes, v.OuterVolumeSpecName)\n\t\t}\n\t\tsort.Strings(mountedVolumes)\n\n\t\tif len(mountedVolumes) == 0 {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn fmt.Errorf(\n\t\t\t\"mounted volumes=%v: %s\",\n\t\t\tmountedVolumes,\n\t\t\terr)\n\t}\n\n\tklog.V(3).InfoS(\"All volumes are unmounted for pod\", \"pod\", klog.KObj(pod))\n\treturn nil\n}","line":{"from":437,"to":471}} {"id":100008070,"name":"getVolumesNotInDSW","signature":"func (vm *volumeManager) getVolumesNotInDSW(uniquePodName types.UniquePodName, expectedVolumes []string) []string","file":"pkg/kubelet/volumemanager/volume_manager.go","code":"func (vm *volumeManager) getVolumesNotInDSW(uniquePodName types.UniquePodName, expectedVolumes []string) []string {\n\tvolumesNotInDSW := sets.NewString(expectedVolumes...)\n\n\tfor _, volumeToMount := range vm.desiredStateOfWorld.GetVolumesToMount() {\n\t\tif volumeToMount.PodName == uniquePodName {\n\t\t\tvolumesNotInDSW.Delete(volumeToMount.OuterVolumeSpecName)\n\t\t}\n\t}\n\n\treturn volumesNotInDSW.List()\n}","line":{"from":473,"to":483}} {"id":100008071,"name":"getUnattachedVolumes","signature":"func (vm *volumeManager) getUnattachedVolumes(uniquePodName types.UniquePodName) []string","file":"pkg/kubelet/volumemanager/volume_manager.go","code":"// getUnattachedVolumes returns a list of the volumes that are expected to be attached but\n// are not currently attached to the node\nfunc (vm *volumeManager) getUnattachedVolumes(uniquePodName types.UniquePodName) []string {\n\tunattachedVolumes := []string{}\n\tfor _, volumeToMount := range vm.desiredStateOfWorld.GetVolumesToMount() {\n\t\tif volumeToMount.PodName == uniquePodName \u0026\u0026\n\t\t\tvolumeToMount.PluginIsAttachable \u0026\u0026\n\t\t\t!vm.actualStateOfWorld.VolumeExists(volumeToMount.VolumeName) {\n\t\t\tunattachedVolumes = append(unattachedVolumes, volumeToMount.OuterVolumeSpecName)\n\t\t}\n\t}\n\n\treturn unattachedVolumes\n}","line":{"from":485,"to":498}} {"id":100008072,"name":"verifyVolumesMountedFunc","signature":"func (vm *volumeManager) verifyVolumesMountedFunc(podName types.UniquePodName, expectedVolumes []string) wait.ConditionFunc","file":"pkg/kubelet/volumemanager/volume_manager.go","code":"// verifyVolumesMountedFunc returns a method that returns true when all expected\n// volumes are mounted.\nfunc (vm *volumeManager) verifyVolumesMountedFunc(podName types.UniquePodName, expectedVolumes []string) wait.ConditionFunc {\n\treturn func() (done bool, err error) {\n\t\tif errs := vm.desiredStateOfWorld.PopPodErrors(podName); len(errs) \u003e 0 {\n\t\t\treturn true, errors.New(strings.Join(errs, \"; \"))\n\t\t}\n\t\treturn len(vm.getUnmountedVolumes(podName, expectedVolumes)) == 0, nil\n\t}\n}","line":{"from":500,"to":509}} {"id":100008073,"name":"verifyVolumesUnmountedFunc","signature":"func (vm *volumeManager) verifyVolumesUnmountedFunc(podName types.UniquePodName) wait.ConditionFunc","file":"pkg/kubelet/volumemanager/volume_manager.go","code":"// verifyVolumesUnmountedFunc returns a method that is true when there are no mounted volumes for this\n// pod.\nfunc (vm *volumeManager) verifyVolumesUnmountedFunc(podName types.UniquePodName) wait.ConditionFunc {\n\treturn func() (done bool, err error) {\n\t\tif errs := vm.desiredStateOfWorld.PopPodErrors(podName); len(errs) \u003e 0 {\n\t\t\treturn true, errors.New(strings.Join(errs, \"; \"))\n\t\t}\n\t\treturn len(vm.actualStateOfWorld.GetMountedVolumesForPod(podName)) == 0, nil\n\t}\n}","line":{"from":511,"to":520}} {"id":100008074,"name":"getUnmountedVolumes","signature":"func (vm *volumeManager) getUnmountedVolumes(podName types.UniquePodName, expectedVolumes []string) []string","file":"pkg/kubelet/volumemanager/volume_manager.go","code":"// getUnmountedVolumes fetches the current list of mounted volumes from\n// the actual state of the world, and uses it to process the list of\n// expectedVolumes. It returns a list of unmounted volumes.\n// The list also includes volume that may be mounted in uncertain state.\nfunc (vm *volumeManager) getUnmountedVolumes(podName types.UniquePodName, expectedVolumes []string) []string {\n\tmountedVolumes := sets.NewString()\n\tfor _, mountedVolume := range vm.actualStateOfWorld.GetMountedVolumesForPod(podName) {\n\t\tmountedVolumes.Insert(mountedVolume.OuterVolumeSpecName)\n\t}\n\treturn filterUnmountedVolumes(mountedVolumes, expectedVolumes)\n}","line":{"from":522,"to":532}} {"id":100008075,"name":"filterUnmountedVolumes","signature":"func filterUnmountedVolumes(mountedVolumes sets.String, expectedVolumes []string) []string","file":"pkg/kubelet/volumemanager/volume_manager.go","code":"// filterUnmountedVolumes adds each element of expectedVolumes that is not in\n// mountedVolumes to a list of unmountedVolumes and returns it.\nfunc filterUnmountedVolumes(mountedVolumes sets.String, expectedVolumes []string) []string {\n\tunmountedVolumes := []string{}\n\tfor _, expectedVolume := range expectedVolumes {\n\t\tif !mountedVolumes.Has(expectedVolume) {\n\t\t\tunmountedVolumes = append(unmountedVolumes, expectedVolume)\n\t\t}\n\t}\n\treturn unmountedVolumes\n}","line":{"from":534,"to":544}} {"id":100008076,"name":"getExpectedVolumes","signature":"func getExpectedVolumes(pod *v1.Pod) []string","file":"pkg/kubelet/volumemanager/volume_manager.go","code":"// getExpectedVolumes returns a list of volumes that must be mounted in order to\n// consider the volume setup step for this pod satisfied.\nfunc getExpectedVolumes(pod *v1.Pod) []string {\n\tmounts, devices, _ := util.GetPodVolumeNames(pod)\n\treturn mounts.Union(devices).UnsortedList()\n}","line":{"from":546,"to":551}} {"id":100008077,"name":"getExtraSupplementalGid","signature":"func getExtraSupplementalGid(volumeGidValue string, pod *v1.Pod) (int64, bool)","file":"pkg/kubelet/volumemanager/volume_manager.go","code":"// getExtraSupplementalGid returns the value of an extra supplemental GID as\n// defined by an annotation on a volume and a boolean indicating whether the\n// volume defined a GID that the pod doesn't already request.\nfunc getExtraSupplementalGid(volumeGidValue string, pod *v1.Pod) (int64, bool) {\n\tif volumeGidValue == \"\" {\n\t\treturn 0, false\n\t}\n\n\tgid, err := strconv.ParseInt(volumeGidValue, 10, 64)\n\tif err != nil {\n\t\treturn 0, false\n\t}\n\n\tif pod.Spec.SecurityContext != nil {\n\t\tfor _, existingGid := range pod.Spec.SecurityContext.SupplementalGroups {\n\t\t\tif gid == int64(existingGid) {\n\t\t\t\treturn 0, false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn gid, true\n}","line":{"from":553,"to":575}} {"id":100008078,"name":"newNetworkCounters","signature":"func newNetworkCounters() (*networkCounter, error)","file":"pkg/kubelet/winstats/network_stats.go","code":"func newNetworkCounters() (*networkCounter, error) {\n\tpacketsReceivedPerSecondCounter, err := newPerfCounter(packetsReceivedPerSecondQuery)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpacketsSentPerSecondCounter, err := newPerfCounter(packetsSentPerSecondQuery)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbytesReceivedPerSecondCounter, err := newPerfCounter(bytesReceivedPerSecondQuery)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbytesSentPerSecondCounter, err := newPerfCounter(bytesSentPerSecondQuery)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpacketsReceivedDiscardedCounter, err := newPerfCounter(packetsReceivedDiscardedQuery)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpacketsReceivedErrorsCounter, err := newPerfCounter(packetsReceivedErrorsQuery)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpacketsOutboundDiscardedCounter, err := newPerfCounter(packetsOutboundDiscardedQuery)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpacketsOutboundErrorsCounter, err := newPerfCounter(packetsOutboundErrorsQuery)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026networkCounter{\n\t\tpacketsReceivedPerSecondCounter: packetsReceivedPerSecondCounter,\n\t\tpacketsSentPerSecondCounter: packetsSentPerSecondCounter,\n\t\tbytesReceivedPerSecondCounter: bytesReceivedPerSecondCounter,\n\t\tbytesSentPerSecondCounter: bytesSentPerSecondCounter,\n\t\tpacketsReceivedDiscardedCounter: packetsReceivedDiscardedCounter,\n\t\tpacketsReceivedErrorsCounter: packetsReceivedErrorsCounter,\n\t\tpacketsOutboundDiscardedCounter: packetsOutboundDiscardedCounter,\n\t\tpacketsOutboundErrorsCounter: packetsOutboundErrorsCounter,\n\t\tadapterStats: map[string]cadvisorapi.InterfaceStats{},\n\t}, nil\n}","line":{"from":56,"to":108}} {"id":100008079,"name":"getData","signature":"func (n *networkCounter) getData() ([]cadvisorapi.InterfaceStats, error)","file":"pkg/kubelet/winstats/network_stats.go","code":"func (n *networkCounter) getData() ([]cadvisorapi.InterfaceStats, error) {\n\tpacketsReceivedPerSecondData, err := n.packetsReceivedPerSecondCounter.getDataList()\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Unable to get packetsReceivedPerSecond perf counter data\")\n\t\treturn nil, err\n\t}\n\n\tpacketsSentPerSecondData, err := n.packetsSentPerSecondCounter.getDataList()\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Unable to get packetsSentPerSecond perf counter data\")\n\t\treturn nil, err\n\t}\n\n\tbytesReceivedPerSecondData, err := n.bytesReceivedPerSecondCounter.getDataList()\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Unable to get bytesReceivedPerSecond perf counter data\")\n\t\treturn nil, err\n\t}\n\n\tbytesSentPerSecondData, err := n.bytesSentPerSecondCounter.getDataList()\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Unable to get bytesSentPerSecond perf counter data\")\n\t\treturn nil, err\n\t}\n\n\tpacketsReceivedDiscardedData, err := n.packetsReceivedDiscardedCounter.getDataList()\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Unable to get packetsReceivedDiscarded perf counter data\")\n\t\treturn nil, err\n\t}\n\n\tpacketsReceivedErrorsData, err := n.packetsReceivedErrorsCounter.getDataList()\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Unable to get packetsReceivedErrors perf counter data\")\n\t\treturn nil, err\n\t}\n\n\tpacketsOutboundDiscardedData, err := n.packetsOutboundDiscardedCounter.getDataList()\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Unable to get packetsOutboundDiscarded perf counter data\")\n\t\treturn nil, err\n\t}\n\n\tpacketsOutboundErrorsData, err := n.packetsOutboundErrorsCounter.getDataList()\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Unable to get packetsOutboundErrors perf counter data\")\n\t\treturn nil, err\n\t}\n\n\tn.mu.Lock()\n\tdefer n.mu.Unlock()\n\tn.mergeCollectedData(\n\t\tpacketsReceivedPerSecondData,\n\t\tpacketsSentPerSecondData,\n\t\tbytesReceivedPerSecondData,\n\t\tbytesSentPerSecondData,\n\t\tpacketsReceivedDiscardedData,\n\t\tpacketsReceivedErrorsData,\n\t\tpacketsOutboundDiscardedData,\n\t\tpacketsOutboundErrorsData,\n\t)\n\treturn n.listInterfaceStats(), nil\n}","line":{"from":110,"to":172}} {"id":100008080,"name":"mergeCollectedData","signature":"func (n *networkCounter) mergeCollectedData(packetsReceivedPerSecondData,","file":"pkg/kubelet/winstats/network_stats.go","code":"// mergeCollectedData merges the collected data into cache. It should be invoked under lock protected.\nfunc (n *networkCounter) mergeCollectedData(packetsReceivedPerSecondData,\n\tpacketsSentPerSecondData,\n\tbytesReceivedPerSecondData,\n\tbytesSentPerSecondData,\n\tpacketsReceivedDiscardedData,\n\tpacketsReceivedErrorsData,\n\tpacketsOutboundDiscardedData,\n\tpacketsOutboundErrorsData map[string]uint64) {\n\tadapters := sets.NewString()\n\n\t// merge the collected data and list of adapters.\n\tadapters.Insert(n.mergePacketsReceivedPerSecondData(packetsReceivedPerSecondData)...)\n\tadapters.Insert(n.mergePacketsSentPerSecondData(packetsSentPerSecondData)...)\n\tadapters.Insert(n.mergeBytesReceivedPerSecondData(bytesReceivedPerSecondData)...)\n\tadapters.Insert(n.mergeBytesSentPerSecondData(bytesSentPerSecondData)...)\n\tadapters.Insert(n.mergePacketsReceivedDiscardedData(packetsReceivedDiscardedData)...)\n\tadapters.Insert(n.mergePacketsReceivedErrorsData(packetsReceivedErrorsData)...)\n\tadapters.Insert(n.mergePacketsOutboundDiscardedData(packetsOutboundDiscardedData)...)\n\tadapters.Insert(n.mergePacketsOutboundErrorsData(packetsOutboundErrorsData)...)\n\n\t// delete the cache for non-existing adapters.\n\tfor adapter := range n.adapterStats {\n\t\tif !adapters.Has(adapter) {\n\t\t\tdelete(n.adapterStats, adapter)\n\t\t}\n\t}\n}","line":{"from":174,"to":201}} {"id":100008081,"name":"mergePacketsReceivedPerSecondData","signature":"func (n *networkCounter) mergePacketsReceivedPerSecondData(packetsReceivedPerSecondData map[string]uint64) []string","file":"pkg/kubelet/winstats/network_stats.go","code":"func (n *networkCounter) mergePacketsReceivedPerSecondData(packetsReceivedPerSecondData map[string]uint64) []string {\n\tvar adapters []string\n\tfor adapterName, value := range packetsReceivedPerSecondData {\n\t\tadapters = append(adapters, adapterName)\n\t\tnewStat := n.adapterStats[adapterName]\n\t\tnewStat.Name = adapterName\n\t\tnewStat.RxPackets = newStat.RxPackets + value\n\t\tn.adapterStats[adapterName] = newStat\n\t}\n\n\treturn adapters\n}","line":{"from":203,"to":214}} {"id":100008082,"name":"mergePacketsSentPerSecondData","signature":"func (n *networkCounter) mergePacketsSentPerSecondData(packetsSentPerSecondData map[string]uint64) []string","file":"pkg/kubelet/winstats/network_stats.go","code":"func (n *networkCounter) mergePacketsSentPerSecondData(packetsSentPerSecondData map[string]uint64) []string {\n\tvar adapters []string\n\tfor adapterName, value := range packetsSentPerSecondData {\n\t\tadapters = append(adapters, adapterName)\n\t\tnewStat := n.adapterStats[adapterName]\n\t\tnewStat.Name = adapterName\n\t\tnewStat.TxPackets = newStat.TxPackets + value\n\t\tn.adapterStats[adapterName] = newStat\n\t}\n\n\treturn adapters\n}","line":{"from":216,"to":227}} {"id":100008083,"name":"mergeBytesReceivedPerSecondData","signature":"func (n *networkCounter) mergeBytesReceivedPerSecondData(bytesReceivedPerSecondData map[string]uint64) []string","file":"pkg/kubelet/winstats/network_stats.go","code":"func (n *networkCounter) mergeBytesReceivedPerSecondData(bytesReceivedPerSecondData map[string]uint64) []string {\n\tvar adapters []string\n\tfor adapterName, value := range bytesReceivedPerSecondData {\n\t\tadapters = append(adapters, adapterName)\n\t\tnewStat := n.adapterStats[adapterName]\n\t\tnewStat.Name = adapterName\n\t\tnewStat.RxBytes = newStat.RxBytes + value\n\t\tn.adapterStats[adapterName] = newStat\n\t}\n\n\treturn adapters\n}","line":{"from":229,"to":240}} {"id":100008084,"name":"mergeBytesSentPerSecondData","signature":"func (n *networkCounter) mergeBytesSentPerSecondData(bytesSentPerSecondData map[string]uint64) []string","file":"pkg/kubelet/winstats/network_stats.go","code":"func (n *networkCounter) mergeBytesSentPerSecondData(bytesSentPerSecondData map[string]uint64) []string {\n\tvar adapters []string\n\tfor adapterName, value := range bytesSentPerSecondData {\n\t\tadapters = append(adapters, adapterName)\n\t\tnewStat := n.adapterStats[adapterName]\n\t\tnewStat.Name = adapterName\n\t\tnewStat.TxBytes = newStat.TxBytes + value\n\t\tn.adapterStats[adapterName] = newStat\n\t}\n\n\treturn adapters\n}","line":{"from":242,"to":253}} {"id":100008085,"name":"mergePacketsReceivedDiscardedData","signature":"func (n *networkCounter) mergePacketsReceivedDiscardedData(packetsReceivedDiscardedData map[string]uint64) []string","file":"pkg/kubelet/winstats/network_stats.go","code":"func (n *networkCounter) mergePacketsReceivedDiscardedData(packetsReceivedDiscardedData map[string]uint64) []string {\n\tvar adapters []string\n\tfor adapterName, value := range packetsReceivedDiscardedData {\n\t\tadapters = append(adapters, adapterName)\n\t\tnewStat := n.adapterStats[adapterName]\n\t\tnewStat.Name = adapterName\n\t\tnewStat.RxDropped = value\n\t\tn.adapterStats[adapterName] = newStat\n\t}\n\n\treturn adapters\n}","line":{"from":255,"to":266}} {"id":100008086,"name":"mergePacketsReceivedErrorsData","signature":"func (n *networkCounter) mergePacketsReceivedErrorsData(packetsReceivedErrorsData map[string]uint64) []string","file":"pkg/kubelet/winstats/network_stats.go","code":"func (n *networkCounter) mergePacketsReceivedErrorsData(packetsReceivedErrorsData map[string]uint64) []string {\n\tvar adapters []string\n\tfor adapterName, value := range packetsReceivedErrorsData {\n\t\tadapters = append(adapters, adapterName)\n\t\tnewStat := n.adapterStats[adapterName]\n\t\tnewStat.Name = adapterName\n\t\tnewStat.RxErrors = value\n\t\tn.adapterStats[adapterName] = newStat\n\t}\n\n\treturn adapters\n}","line":{"from":268,"to":279}} {"id":100008087,"name":"mergePacketsOutboundDiscardedData","signature":"func (n *networkCounter) mergePacketsOutboundDiscardedData(packetsOutboundDiscardedData map[string]uint64) []string","file":"pkg/kubelet/winstats/network_stats.go","code":"func (n *networkCounter) mergePacketsOutboundDiscardedData(packetsOutboundDiscardedData map[string]uint64) []string {\n\tvar adapters []string\n\tfor adapterName, value := range packetsOutboundDiscardedData {\n\t\tadapters = append(adapters, adapterName)\n\t\tnewStat := n.adapterStats[adapterName]\n\t\tnewStat.Name = adapterName\n\t\tnewStat.TxDropped = value\n\t\tn.adapterStats[adapterName] = newStat\n\t}\n\n\treturn adapters\n}","line":{"from":281,"to":292}} {"id":100008088,"name":"mergePacketsOutboundErrorsData","signature":"func (n *networkCounter) mergePacketsOutboundErrorsData(packetsOutboundErrorsData map[string]uint64) []string","file":"pkg/kubelet/winstats/network_stats.go","code":"func (n *networkCounter) mergePacketsOutboundErrorsData(packetsOutboundErrorsData map[string]uint64) []string {\n\tvar adapters []string\n\tfor adapterName, value := range packetsOutboundErrorsData {\n\t\tadapters = append(adapters, adapterName)\n\t\tnewStat := n.adapterStats[adapterName]\n\t\tnewStat.Name = adapterName\n\t\tnewStat.TxErrors = value\n\t\tn.adapterStats[adapterName] = newStat\n\t}\n\n\treturn adapters\n}","line":{"from":294,"to":305}} {"id":100008089,"name":"listInterfaceStats","signature":"func (n *networkCounter) listInterfaceStats() []cadvisorapi.InterfaceStats","file":"pkg/kubelet/winstats/network_stats.go","code":"func (n *networkCounter) listInterfaceStats() []cadvisorapi.InterfaceStats {\n\tstats := make([]cadvisorapi.InterfaceStats, 0, len(n.adapterStats))\n\tfor _, stat := range n.adapterStats {\n\t\tstats = append(stats, stat)\n\t}\n\treturn stats\n}","line":{"from":307,"to":313}} {"id":100008090,"name":"NewPerfCounterClient","signature":"func NewPerfCounterClient() (Client, error)","file":"pkg/kubelet/winstats/perfcounter_nodestats.go","code":"// NewPerfCounterClient creates a client using perf counters\nfunc NewPerfCounterClient() (Client, error) {\n\t// Initialize the cache\n\tinitCache := cpuUsageCoreNanoSecondsCache{0, 0}\n\treturn newClient(\u0026perfCounterNodeStatsClient{\n\t\tcpuUsageCoreNanoSecondsCache: initCache,\n\t})\n}","line":{"from":69,"to":76}} {"id":100008091,"name":"startMonitoring","signature":"func (p *perfCounterNodeStatsClient) startMonitoring() error","file":"pkg/kubelet/winstats/perfcounter_nodestats.go","code":"func (p *perfCounterNodeStatsClient) startMonitoring() error {\n\tmemory, err := getPhysicallyInstalledSystemMemoryBytes()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tosInfo, err := GetOSInfo()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp.nodeInfo = nodeInfo{\n\t\tkernelVersion: osInfo.GetPatchVersion(),\n\t\tosImageVersion: osInfo.ProductName,\n\t\tmemoryPhysicalCapacityBytes: memory,\n\t\tstartTime: time.Now(),\n\t}\n\n\tcpuCounter, err := newPerfCounter(cpuQuery)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmemWorkingSetCounter, err := newPerfCounter(memoryPrivWorkingSetQuery)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmemCommittedBytesCounter, err := newPerfCounter(memoryCommittedBytesQuery)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnetworkAdapterCounter, err := newNetworkCounters()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo wait.Forever(func() {\n\t\tp.collectMetricsData(cpuCounter, memWorkingSetCounter, memCommittedBytesCounter, networkAdapterCounter)\n\t}, perfCounterUpdatePeriod)\n\n\t// Cache the CPU usage every defaultCachePeriod\n\tgo wait.Forever(func() {\n\t\tnewValue := p.nodeMetrics.cpuUsageCoreNanoSeconds\n\t\tp.mu.Lock()\n\t\tdefer p.mu.Unlock()\n\t\tp.cpuUsageCoreNanoSecondsCache = cpuUsageCoreNanoSecondsCache{\n\t\t\tpreviousValue: p.cpuUsageCoreNanoSecondsCache.latestValue,\n\t\t\tlatestValue: newValue,\n\t\t}\n\t}, defaultCachePeriod)\n\n\treturn nil\n}","line":{"from":87,"to":141}} {"id":100008092,"name":"getMachineInfo","signature":"func (p *perfCounterNodeStatsClient) getMachineInfo() (*cadvisorapi.MachineInfo, error)","file":"pkg/kubelet/winstats/perfcounter_nodestats.go","code":"func (p *perfCounterNodeStatsClient) getMachineInfo() (*cadvisorapi.MachineInfo, error) {\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsystemUUID, err := getSystemUUID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbootId, err := getBootID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026cadvisorapi.MachineInfo{\n\t\tNumCores: ProcessorCount(),\n\t\tMemoryCapacity: p.nodeInfo.memoryPhysicalCapacityBytes,\n\t\tMachineID: hostname,\n\t\tSystemUUID: systemUUID,\n\t\tBootID: bootId,\n\t}, nil\n}","line":{"from":143,"to":166}} {"id":100008093,"name":"ProcessorCount","signature":"func ProcessorCount() int","file":"pkg/kubelet/winstats/perfcounter_nodestats.go","code":"// runtime.NumCPU() will only return the information for a single Processor Group.\n// Since a single group can only hold 64 logical processors, this\n// means when there are more they will be divided into multiple groups.\n// For the above reason, procGetActiveProcessorCount is used to get the\n// cpu count for all processor groups of the windows node.\n// more notes for this issue:\n// same issue in moby: https://github.com/moby/moby/issues/38935#issuecomment-744638345\n// solution in hcsshim: https://github.com/microsoft/hcsshim/blob/master/internal/processorinfo/processor_count.go\nfunc ProcessorCount() int {\n\tif amount := getActiveProcessorCount(allProcessorGroups); amount != 0 {\n\t\treturn int(amount)\n\t}\n\treturn runtime.NumCPU()\n}","line":{"from":168,"to":181}} {"id":100008094,"name":"getActiveProcessorCount","signature":"func getActiveProcessorCount(groupNumber uint16) int","file":"pkg/kubelet/winstats/perfcounter_nodestats.go","code":"func getActiveProcessorCount(groupNumber uint16) int {\n\tr0, _, _ := syscall.Syscall(procGetActiveProcessorCount.Addr(), 1, uintptr(groupNumber), 0, 0)\n\treturn int(r0)\n}","line":{"from":183,"to":186}} {"id":100008095,"name":"getVersionInfo","signature":"func (p *perfCounterNodeStatsClient) getVersionInfo() (*cadvisorapi.VersionInfo, error)","file":"pkg/kubelet/winstats/perfcounter_nodestats.go","code":"func (p *perfCounterNodeStatsClient) getVersionInfo() (*cadvisorapi.VersionInfo, error) {\n\treturn \u0026cadvisorapi.VersionInfo{\n\t\tKernelVersion: p.nodeInfo.kernelVersion,\n\t\tContainerOsVersion: p.nodeInfo.osImageVersion,\n\t}, nil\n}","line":{"from":188,"to":193}} {"id":100008096,"name":"getNodeMetrics","signature":"func (p *perfCounterNodeStatsClient) getNodeMetrics() (nodeMetrics, error)","file":"pkg/kubelet/winstats/perfcounter_nodestats.go","code":"func (p *perfCounterNodeStatsClient) getNodeMetrics() (nodeMetrics, error) {\n\tp.mu.RLock()\n\tdefer p.mu.RUnlock()\n\treturn p.nodeMetrics, nil\n}","line":{"from":195,"to":199}} {"id":100008097,"name":"getNodeInfo","signature":"func (p *perfCounterNodeStatsClient) getNodeInfo() nodeInfo","file":"pkg/kubelet/winstats/perfcounter_nodestats.go","code":"func (p *perfCounterNodeStatsClient) getNodeInfo() nodeInfo {\n\treturn p.nodeInfo\n}","line":{"from":201,"to":203}} {"id":100008098,"name":"collectMetricsData","signature":"func (p *perfCounterNodeStatsClient) collectMetricsData(cpuCounter, memWorkingSetCounter, memCommittedBytesCounter perfCounter, networkAdapterCounter *networkCounter)","file":"pkg/kubelet/winstats/perfcounter_nodestats.go","code":"func (p *perfCounterNodeStatsClient) collectMetricsData(cpuCounter, memWorkingSetCounter, memCommittedBytesCounter perfCounter, networkAdapterCounter *networkCounter) {\n\tcpuValue, err := cpuCounter.getData()\n\tcpuCores := ProcessorCount()\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Unable to get cpu perf counter data\")\n\t\treturn\n\t}\n\n\tmemWorkingSetValue, err := memWorkingSetCounter.getData()\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Unable to get memWorkingSet perf counter data\")\n\t\treturn\n\t}\n\n\tmemCommittedBytesValue, err := memCommittedBytesCounter.getData()\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Unable to get memCommittedBytes perf counter data\")\n\t\treturn\n\t}\n\n\tnetworkAdapterStats, err := networkAdapterCounter.getData()\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Unable to get network adapter perf counter data\")\n\t\treturn\n\t}\n\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tp.nodeMetrics = nodeMetrics{\n\t\tcpuUsageCoreNanoSeconds: p.convertCPUValue(cpuCores, cpuValue),\n\t\tcpuUsageNanoCores: p.getCPUUsageNanoCores(),\n\t\tmemoryPrivWorkingSetBytes: memWorkingSetValue,\n\t\tmemoryCommittedBytes: memCommittedBytesValue,\n\t\tinterfaceStats: networkAdapterStats,\n\t\ttimeStamp: time.Now(),\n\t}\n}","line":{"from":205,"to":241}} {"id":100008099,"name":"convertCPUValue","signature":"func (p *perfCounterNodeStatsClient) convertCPUValue(cpuCores int, cpuValue uint64) uint64","file":"pkg/kubelet/winstats/perfcounter_nodestats.go","code":"func (p *perfCounterNodeStatsClient) convertCPUValue(cpuCores int, cpuValue uint64) uint64 {\n\t// This converts perf counter data which is cpu percentage for all cores into nanoseconds.\n\t// The formula is (cpuPercentage / 100.0) * #cores * 1e+9 (nano seconds). More info here:\n\t// https://github.com/kubernetes/heapster/issues/650\n\tnewValue := p.nodeMetrics.cpuUsageCoreNanoSeconds + uint64((float64(cpuValue)/100.0)*float64(cpuCores)*1e9)\n\treturn newValue\n}","line":{"from":243,"to":249}} {"id":100008100,"name":"getCPUUsageNanoCores","signature":"func (p *perfCounterNodeStatsClient) getCPUUsageNanoCores() uint64","file":"pkg/kubelet/winstats/perfcounter_nodestats.go","code":"func (p *perfCounterNodeStatsClient) getCPUUsageNanoCores() uint64 {\n\tcachePeriodSeconds := uint64(defaultCachePeriod / time.Second)\n\tcpuUsageNanoCores := (p.cpuUsageCoreNanoSecondsCache.latestValue - p.cpuUsageCoreNanoSecondsCache.previousValue) / cachePeriodSeconds\n\treturn cpuUsageNanoCores\n}","line":{"from":251,"to":255}} {"id":100008101,"name":"getSystemUUID","signature":"func getSystemUUID() (string, error)","file":"pkg/kubelet/winstats/perfcounter_nodestats.go","code":"func getSystemUUID() (string, error) {\n\tresult, err := exec.Command(\"wmic\", \"csproduct\", \"get\", \"UUID\").Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfields := strings.Fields(string(result))\n\tif len(fields) != 2 {\n\t\treturn \"\", fmt.Errorf(\"received unexpected value retrieving vm uuid: %q\", string(result))\n\t}\n\treturn fields[1], nil\n}","line":{"from":257,"to":267}} {"id":100008102,"name":"getPhysicallyInstalledSystemMemoryBytes","signature":"func getPhysicallyInstalledSystemMemoryBytes() (uint64, error)","file":"pkg/kubelet/winstats/perfcounter_nodestats.go","code":"func getPhysicallyInstalledSystemMemoryBytes() (uint64, error) {\n\t// We use GlobalMemoryStatusEx instead of GetPhysicallyInstalledSystemMemory\n\t// on Windows node for the following reasons:\n\t// 1. GetPhysicallyInstalledSystemMemory retrieves the amount of physically\n\t// installed RAM from the computer's SMBIOS firmware tables.\n\t// https://msdn.microsoft.com/en-us/library/windows/desktop/cc300158(v=vs.85).aspx\n\t// On some VM, it is unable to read data from SMBIOS and fails with ERROR_INVALID_DATA.\n\t// 2. On Linux node, total physical memory is read from MemTotal in /proc/meminfo.\n\t// GlobalMemoryStatusEx returns the amount of physical memory that is available\n\t// for the operating system to use. The amount returned by GlobalMemoryStatusEx\n\t// is closer in parity with Linux\n\t// https://www.kernel.org/doc/Documentation/filesystems/proc.txt\n\tvar statex MemoryStatusEx\n\tstatex.Length = uint32(unsafe.Sizeof(statex))\n\tret, _, _ := procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(\u0026statex)))\n\n\tif ret == 0 {\n\t\treturn 0, errors.New(\"unable to read physical memory\")\n\t}\n\n\treturn statex.TotalPhys, nil\n}","line":{"from":269,"to":290}} {"id":100008103,"name":"getBootID","signature":"func getBootID() (string, error)","file":"pkg/kubelet/winstats/perfcounter_nodestats.go","code":"func getBootID() (string, error) {\n\tregKey, err := registry.OpenKey(registry.LOCAL_MACHINE, bootIdRegistry, registry.READ)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer regKey.Close()\n\tregValue, _, err := regKey.GetIntegerValue(bootIdKey)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strconv.FormatUint(regValue, 10), nil\n}","line":{"from":292,"to":303}} {"id":100008104,"name":"newPerfCounter","signature":"func newPerfCounter(counter string) (perfCounter, error)","file":"pkg/kubelet/winstats/perfcounters.go","code":"func newPerfCounter(counter string) (perfCounter, error) {\n\tvar queryHandle win_pdh.PDH_HQUERY\n\tvar counterHandle win_pdh.PDH_HCOUNTER\n\n\tret := win_pdh.PdhOpenQuery(0, 0, \u0026queryHandle)\n\tif ret != win_pdh.ERROR_SUCCESS {\n\t\treturn nil, errors.New(\"unable to open query through DLL call\")\n\t}\n\n\tret = win_pdh.PdhAddEnglishCounter(queryHandle, counter, 0, \u0026counterHandle)\n\tif ret != win_pdh.ERROR_SUCCESS {\n\t\treturn nil, fmt.Errorf(\"unable to add process counter: %s. Error code is %x\", counter, ret)\n\t}\n\n\tret = win_pdh.PdhCollectQueryData(queryHandle)\n\tif ret != win_pdh.ERROR_SUCCESS {\n\t\treturn nil, fmt.Errorf(\"unable to collect data from counter. Error code is %x\", ret)\n\t}\n\n\treturn \u0026perfCounterImpl{\n\t\tqueryHandle: queryHandle,\n\t\tcounterHandle: counterHandle,\n\t}, nil\n}","line":{"from":54,"to":77}} {"id":100008105,"name":"getData","signature":"func (p *perfCounterImpl) getData() (uint64, error)","file":"pkg/kubelet/winstats/perfcounters.go","code":"// getData is used for getting data without * in counter name.\nfunc (p *perfCounterImpl) getData() (uint64, error) {\n\tfilledBuf, bufCount, err := p.getQueriedData()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar data uint64 = 0\n\tfor i := 0; i \u003c int(bufCount); i++ {\n\t\tc := filledBuf[i]\n\t\tdata = uint64(c.FmtValue.DoubleValue)\n\t}\n\n\treturn data, nil\n}","line":{"from":79,"to":93}} {"id":100008106,"name":"getDataList","signature":"func (p *perfCounterImpl) getDataList() (map[string]uint64, error)","file":"pkg/kubelet/winstats/perfcounters.go","code":"// getDataList is used for getting data with * in counter name.\nfunc (p *perfCounterImpl) getDataList() (map[string]uint64, error) {\n\tfilledBuf, bufCount, err := p.getQueriedData()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata := map[string]uint64{}\n\tfor i := 0; i \u003c int(bufCount); i++ {\n\t\tc := filledBuf[i]\n\t\tvalue := uint64(c.FmtValue.DoubleValue)\n\t\tname := win_pdh.UTF16PtrToString(c.SzName)\n\t\tdata[name] = value\n\t}\n\n\treturn data, nil\n}","line":{"from":95,"to":111}} {"id":100008107,"name":"getQueriedData","signature":"func (p *perfCounterImpl) getQueriedData() ([]win_pdh.PDH_FMT_COUNTERVALUE_ITEM_DOUBLE, uint32, error)","file":"pkg/kubelet/winstats/perfcounters.go","code":"// getQueriedData is used for getting data using the given query handle.\nfunc (p *perfCounterImpl) getQueriedData() ([]win_pdh.PDH_FMT_COUNTERVALUE_ITEM_DOUBLE, uint32, error) {\n\tret := win_pdh.PdhCollectQueryData(p.queryHandle)\n\tif ret != win_pdh.ERROR_SUCCESS {\n\t\treturn nil, 0, fmt.Errorf(\"unable to collect data from counter. Error code is %x\", ret)\n\t}\n\n\tvar bufSize, bufCount uint32\n\tvar size = uint32(unsafe.Sizeof(win_pdh.PDH_FMT_COUNTERVALUE_ITEM_DOUBLE{}))\n\tvar emptyBuf [1]win_pdh.PDH_FMT_COUNTERVALUE_ITEM_DOUBLE // need at least 1 addressable null ptr.\n\n\tret = win_pdh.PdhGetFormattedCounterArrayDouble(p.counterHandle, \u0026bufSize, \u0026bufCount, \u0026emptyBuf[0])\n\tif ret != win_pdh.PDH_MORE_DATA {\n\t\treturn nil, 0, fmt.Errorf(\"unable to collect data from counter. Error code is %x\", ret)\n\t}\n\n\tfilledBuf := make([]win_pdh.PDH_FMT_COUNTERVALUE_ITEM_DOUBLE, bufCount*size)\n\tret = win_pdh.PdhGetFormattedCounterArrayDouble(p.counterHandle, \u0026bufSize, \u0026bufCount, \u0026filledBuf[0])\n\tif ret != win_pdh.ERROR_SUCCESS {\n\t\treturn nil, 0, fmt.Errorf(\"unable to collect data from counter. Error code is %x\", ret)\n\t}\n\n\treturn filledBuf, bufCount, nil\n}","line":{"from":113,"to":136}} {"id":100008108,"name":"GetOSInfo","signature":"func GetOSInfo() (*OSInfo, error)","file":"pkg/kubelet/winstats/version.go","code":"// GetOSInfo reads Windows version information from the registry\nfunc GetOSInfo() (*OSInfo, error) {\n\t// for log detail\n\tvar keyPrefix string = `regedit:LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion`\n\n\tk, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion`, registry.QUERY_VALUE)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getOSInfo, open Windows %s failed: %w\", keyPrefix, err)\n\t}\n\tdefer k.Close()\n\n\tbuildNumber, _, err := k.GetStringValue(\"CurrentBuildNumber\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getOSInfo, get %s\\\\CurrentBuildNumber failed: %w\", keyPrefix, err)\n\t}\n\n\tmajorVersionNumber, _, err := k.GetIntegerValue(\"CurrentMajorVersionNumber\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getOSInfo, get %s\\\\CurrentMajorVersionNumber failed: %w\", keyPrefix, err)\n\t}\n\n\tminorVersionNumber, _, err := k.GetIntegerValue(\"CurrentMinorVersionNumber\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getOSInfo, get %s\\\\CurrentMinorVersionNumber failed: %w\", keyPrefix, err)\n\t}\n\n\trevision, _, err := k.GetIntegerValue(\"UBR\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getOSInfo, get %s\\\\UBR failed: %w\", keyPrefix, err)\n\t}\n\n\tproductName, _, err := k.GetStringValue(\"ProductName\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getOSInfo, get %s\\\\ProductName failed: %w\", keyPrefix, err)\n\t}\n\n\treturn \u0026OSInfo{\n\t\tBuildNumber: buildNumber,\n\t\tProductName: productName,\n\t\tMajorVersion: majorVersionNumber,\n\t\tMinorVersion: minorVersionNumber,\n\t\tUBR: revision,\n\t}, nil\n}","line":{"from":33,"to":76}} {"id":100008109,"name":"GetPatchVersion","signature":"func (o *OSInfo) GetPatchVersion() string","file":"pkg/kubelet/winstats/version.go","code":"// GetPatchVersion returns full OS version with patch\nfunc (o *OSInfo) GetPatchVersion() string {\n\treturn fmt.Sprintf(\"%d.%d.%s.%d\", o.MajorVersion, o.MinorVersion, o.BuildNumber, o.UBR)\n}","line":{"from":78,"to":81}} {"id":100008110,"name":"GetBuild","signature":"func (o *OSInfo) GetBuild() string","file":"pkg/kubelet/winstats/version.go","code":"// GetBuild returns OS version upto build number\nfunc (o *OSInfo) GetBuild() string {\n\treturn fmt.Sprintf(\"%d.%d.%s\", o.MajorVersion, o.MinorVersion, o.BuildNumber)\n}","line":{"from":83,"to":86}} {"id":100008111,"name":"newClient","signature":"func newClient(statsNodeClient winNodeStatsClient) (Client, error)","file":"pkg/kubelet/winstats/winstats.go","code":"// newClient constructs a Client.\nfunc newClient(statsNodeClient winNodeStatsClient) (Client, error) {\n\tstatsClient := new(StatsClient)\n\tstatsClient.client = statsNodeClient\n\n\terr := statsClient.client.startMonitoring()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn statsClient, nil\n}","line":{"from":79,"to":90}} {"id":100008112,"name":"WinContainerInfos","signature":"func (c *StatsClient) WinContainerInfos() (map[string]cadvisorapiv2.ContainerInfo, error)","file":"pkg/kubelet/winstats/winstats.go","code":"// WinContainerInfos returns a map of container infos. The map contains node and\n// pod level stats. Analogous to cadvisor GetContainerInfoV2 method.\nfunc (c *StatsClient) WinContainerInfos() (map[string]cadvisorapiv2.ContainerInfo, error) {\n\tinfos := make(map[string]cadvisorapiv2.ContainerInfo)\n\trootContainerInfo, err := c.createRootContainerInfo()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinfos[\"/\"] = *rootContainerInfo\n\n\treturn infos, nil\n}","line":{"from":92,"to":104}} {"id":100008113,"name":"WinMachineInfo","signature":"func (c *StatsClient) WinMachineInfo() (*cadvisorapi.MachineInfo, error)","file":"pkg/kubelet/winstats/winstats.go","code":"// WinMachineInfo returns a cadvisorapi.MachineInfo with details about the\n// node machine. Analogous to cadvisor MachineInfo method.\nfunc (c *StatsClient) WinMachineInfo() (*cadvisorapi.MachineInfo, error) {\n\treturn c.client.getMachineInfo()\n}","line":{"from":106,"to":110}} {"id":100008114,"name":"WinVersionInfo","signature":"func (c *StatsClient) WinVersionInfo() (*cadvisorapi.VersionInfo, error)","file":"pkg/kubelet/winstats/winstats.go","code":"// WinVersionInfo returns a cadvisorapi.VersionInfo with version info of\n// the kernel and docker runtime. Analogous to cadvisor VersionInfo method.\nfunc (c *StatsClient) WinVersionInfo() (*cadvisorapi.VersionInfo, error) {\n\treturn c.client.getVersionInfo()\n}","line":{"from":112,"to":116}} {"id":100008115,"name":"createRootContainerInfo","signature":"func (c *StatsClient) createRootContainerInfo() (*cadvisorapiv2.ContainerInfo, error)","file":"pkg/kubelet/winstats/winstats.go","code":"func (c *StatsClient) createRootContainerInfo() (*cadvisorapiv2.ContainerInfo, error) {\n\tnodeMetrics, err := c.client.getNodeMetrics()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar stats []*cadvisorapiv2.ContainerStats\n\tstats = append(stats, \u0026cadvisorapiv2.ContainerStats{\n\t\tTimestamp: nodeMetrics.timeStamp,\n\t\tCpu: \u0026cadvisorapi.CpuStats{\n\t\t\tUsage: cadvisorapi.CpuUsage{\n\t\t\t\tTotal: nodeMetrics.cpuUsageCoreNanoSeconds,\n\t\t\t},\n\t\t},\n\t\tCpuInst: \u0026cadvisorapiv2.CpuInstStats{\n\t\t\tUsage: cadvisorapiv2.CpuInstUsage{\n\t\t\t\tTotal: nodeMetrics.cpuUsageNanoCores,\n\t\t\t},\n\t\t},\n\t\tMemory: \u0026cadvisorapi.MemoryStats{\n\t\t\tWorkingSet: nodeMetrics.memoryPrivWorkingSetBytes,\n\t\t\tUsage: nodeMetrics.memoryCommittedBytes,\n\t\t},\n\t\tNetwork: \u0026cadvisorapiv2.NetworkStats{\n\t\t\tInterfaces: nodeMetrics.interfaceStats,\n\t\t},\n\t})\n\n\tnodeInfo := c.client.getNodeInfo()\n\trootInfo := cadvisorapiv2.ContainerInfo{\n\t\tSpec: cadvisorapiv2.ContainerSpec{\n\t\t\tCreationTime: nodeInfo.startTime,\n\t\t\tHasCpu: true,\n\t\t\tHasMemory: true,\n\t\t\tHasNetwork: true,\n\t\t\tMemory: cadvisorapiv2.MemorySpec{\n\t\t\t\tLimit: nodeInfo.memoryPhysicalCapacityBytes,\n\t\t\t},\n\t\t},\n\t\tStats: stats,\n\t}\n\n\treturn \u0026rootInfo, nil\n}","line":{"from":118,"to":161}} {"id":100008116,"name":"GetDirFsInfo","signature":"func (c *StatsClient) GetDirFsInfo(path string) (cadvisorapiv2.FsInfo, error)","file":"pkg/kubelet/winstats/winstats.go","code":"// GetDirFsInfo returns filesystem capacity and usage information.\nfunc (c *StatsClient) GetDirFsInfo(path string) (cadvisorapiv2.FsInfo, error) {\n\tvar freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes int64\n\tvar err error\n\n\tret, _, err := syscall.Syscall6(\n\t\tprocGetDiskFreeSpaceEx.Addr(),\n\t\t4,\n\t\tuintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(path))),\n\t\tuintptr(unsafe.Pointer(\u0026freeBytesAvailable)),\n\t\tuintptr(unsafe.Pointer(\u0026totalNumberOfBytes)),\n\t\tuintptr(unsafe.Pointer(\u0026totalNumberOfFreeBytes)),\n\t\t0,\n\t\t0,\n\t)\n\tif ret == 0 {\n\t\treturn cadvisorapiv2.FsInfo{}, err\n\t}\n\n\treturn cadvisorapiv2.FsInfo{\n\t\tTimestamp: time.Now(),\n\t\tCapacity: uint64(totalNumberOfBytes),\n\t\tAvailable: uint64(freeBytesAvailable),\n\t\tUsage: uint64(totalNumberOfBytes - freeBytesAvailable),\n\t}, nil\n}","line":{"from":163,"to":188}} {"id":100008117,"name":"NewKubemarkController","signature":"func NewKubemarkController(externalClient kubeclient.Interface, externalInformerFactory informers.SharedInformerFactory,","file":"pkg/kubemark/controller.go","code":"// NewKubemarkController creates KubemarkController using the provided clients to talk to external\n// and kubemark clusters.\nfunc NewKubemarkController(externalClient kubeclient.Interface, externalInformerFactory informers.SharedInformerFactory,\n\tkubemarkClient kubeclient.Interface, kubemarkNodeInformer informersv1.NodeInformer) (*KubemarkController, error) {\n\trcInformer := externalInformerFactory.InformerFor(\u0026apiv1.ReplicationController{}, newReplicationControllerInformer)\n\tpodInformer := externalInformerFactory.InformerFor(\u0026apiv1.Pod{}, newPodInformer)\n\tcontroller := \u0026KubemarkController{\n\t\texternalCluster: externalCluster{\n\t\t\trcLister: listersv1.NewReplicationControllerLister(rcInformer.GetIndexer()),\n\t\t\trcSynced: rcInformer.HasSynced,\n\t\t\tpodLister: listersv1.NewPodLister(podInformer.GetIndexer()),\n\t\t\tpodSynced: podInformer.HasSynced,\n\t\t\tclient: externalClient,\n\t\t},\n\t\tkubemarkCluster: kubemarkCluster{\n\t\t\tnodeLister: kubemarkNodeInformer.Lister(),\n\t\t\tnodeSynced: kubemarkNodeInformer.Informer().HasSynced,\n\t\t\tclient: kubemarkClient,\n\t\t\tnodesToDelete: make(map[string]bool),\n\t\t\tnodesToDeleteLock: sync.Mutex{},\n\t\t},\n\t\trand: rand.New(rand.NewSource(time.Now().UnixNano())),\n\t\tcreateNodeQueue: make(chan string, 1000),\n\t\tnodeGroupQueueSize: make(map[string]int),\n\t\tnodeGroupQueueSizeLock: sync.Mutex{},\n\t}\n\n\tkubemarkNodeInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tUpdateFunc: controller.kubemarkCluster.removeUnneededNodes,\n\t})\n\n\treturn controller, nil\n}","line":{"from":81,"to":113}} {"id":100008118,"name":"WaitForCacheSync","signature":"func (kubemarkController *KubemarkController) WaitForCacheSync(stopCh chan struct{}) bool","file":"pkg/kubemark/controller.go","code":"// WaitForCacheSync waits until all caches in the controller are populated.\nfunc (kubemarkController *KubemarkController) WaitForCacheSync(stopCh chan struct{}) bool {\n\treturn cache.WaitForNamedCacheSync(\"kubemark\", stopCh,\n\t\tkubemarkController.externalCluster.rcSynced,\n\t\tkubemarkController.externalCluster.podSynced,\n\t\tkubemarkController.kubemarkCluster.nodeSynced)\n}","line":{"from":115,"to":121}} {"id":100008119,"name":"Run","signature":"func (kubemarkController *KubemarkController) Run(stopCh chan struct{})","file":"pkg/kubemark/controller.go","code":"// Run populates the node template needed for creation of kubemark nodes and\n// starts the worker routine for creating new nodes.\nfunc (kubemarkController *KubemarkController) Run(stopCh chan struct{}) {\n\tnodeTemplate, err := kubemarkController.getNodeTemplate()\n\tif err != nil {\n\t\tklog.Fatalf(\"failed to get node template: %s\", err)\n\t}\n\tkubemarkController.nodeTemplate = nodeTemplate\n\n\tgo kubemarkController.runNodeCreation(stopCh)\n\t\u003c-stopCh\n}","line":{"from":123,"to":134}} {"id":100008120,"name":"GetNodeNamesForNodeGroup","signature":"func (kubemarkController *KubemarkController) GetNodeNamesForNodeGroup(nodeGroup string) ([]string, error)","file":"pkg/kubemark/controller.go","code":"// GetNodeNamesForNodeGroup returns list of the nodes in the node group.\nfunc (kubemarkController *KubemarkController) GetNodeNamesForNodeGroup(nodeGroup string) ([]string, error) {\n\tselector := labels.SelectorFromSet(labels.Set{nodeGroupLabel: nodeGroup})\n\tpods, err := kubemarkController.externalCluster.podLister.List(selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := make([]string, 0, len(pods))\n\tfor _, pod := range pods {\n\t\tresult = append(result, pod.ObjectMeta.Name)\n\t}\n\treturn result, nil\n}","line":{"from":136,"to":148}} {"id":100008121,"name":"GetNodeGroupSize","signature":"func (kubemarkController *KubemarkController) GetNodeGroupSize(nodeGroup string) (int, error)","file":"pkg/kubemark/controller.go","code":"// GetNodeGroupSize returns the current size for the node group as observed.\nfunc (kubemarkController *KubemarkController) GetNodeGroupSize(nodeGroup string) (int, error) {\n\tselector := labels.SelectorFromSet(labels.Set(map[string]string{nodeGroupLabel: nodeGroup}))\n\tnodes, err := kubemarkController.externalCluster.rcLister.List(selector)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn len(nodes), nil\n}","line":{"from":150,"to":158}} {"id":100008122,"name":"GetNodeGroupTargetSize","signature":"func (kubemarkController *KubemarkController) GetNodeGroupTargetSize(nodeGroup string) (int, error)","file":"pkg/kubemark/controller.go","code":"// GetNodeGroupTargetSize returns the size of the node group as a sum of current\n// observed size and number of upcoming nodes.\nfunc (kubemarkController *KubemarkController) GetNodeGroupTargetSize(nodeGroup string) (int, error) {\n\tkubemarkController.nodeGroupQueueSizeLock.Lock()\n\tdefer kubemarkController.nodeGroupQueueSizeLock.Unlock()\n\trealSize, err := kubemarkController.GetNodeGroupSize(nodeGroup)\n\tif err != nil {\n\t\treturn realSize, err\n\t}\n\treturn realSize + kubemarkController.nodeGroupQueueSize[nodeGroup], nil\n}","line":{"from":160,"to":170}} {"id":100008123,"name":"SetNodeGroupSize","signature":"func (kubemarkController *KubemarkController) SetNodeGroupSize(nodeGroup string, size int) error","file":"pkg/kubemark/controller.go","code":"// SetNodeGroupSize changes the size of node group by adding or removing nodes.\nfunc (kubemarkController *KubemarkController) SetNodeGroupSize(nodeGroup string, size int) error {\n\tcurrSize, err := kubemarkController.GetNodeGroupTargetSize(nodeGroup)\n\tif err != nil {\n\t\treturn err\n\t}\n\tswitch delta := size - currSize; {\n\tcase delta \u003c 0:\n\t\tabsDelta := -delta\n\t\tnodes, err := kubemarkController.GetNodeNamesForNodeGroup(nodeGroup)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(nodes) \u003c absDelta {\n\t\t\treturn fmt.Errorf(\"can't remove %d nodes from %s nodegroup, not enough nodes: %d\", absDelta, nodeGroup, len(nodes))\n\t\t}\n\t\tfor i, node := range nodes {\n\t\t\tif i == absDelta {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif err := kubemarkController.RemoveNodeFromNodeGroup(nodeGroup, node); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\tcase delta \u003e 0:\n\t\tkubemarkController.nodeGroupQueueSizeLock.Lock()\n\t\tkubemarkController.nodeGroupQueueSize[nodeGroup] += delta\n\t\tkubemarkController.nodeGroupQueueSizeLock.Unlock()\n\t\tfor i := 0; i \u003c delta; i++ {\n\t\t\tkubemarkController.createNodeQueue \u003c- nodeGroup\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":172,"to":206}} {"id":100008124,"name":"GetNodeGroupForNode","signature":"func (kubemarkController *KubemarkController) GetNodeGroupForNode(node string) (string, error)","file":"pkg/kubemark/controller.go","code":"// GetNodeGroupForNode returns the name of the node group to which the node\n// belongs.\nfunc (kubemarkController *KubemarkController) GetNodeGroupForNode(node string) (string, error) {\n\tpod := kubemarkController.getPodByName(node)\n\tif pod == nil {\n\t\treturn \"\", fmt.Errorf(\"node %s does not exist\", node)\n\t}\n\tnodeGroup, ok := pod.ObjectMeta.Labels[nodeGroupLabel]\n\tif ok {\n\t\treturn nodeGroup, nil\n\t}\n\treturn \"\", fmt.Errorf(\"can't find nodegroup for node %s due to missing label %s\", node, nodeGroupLabel)\n}","line":{"from":208,"to":220}} {"id":100008125,"name":"addNodeToNodeGroup","signature":"func (kubemarkController *KubemarkController) addNodeToNodeGroup(nodeGroup string) error","file":"pkg/kubemark/controller.go","code":"func (kubemarkController *KubemarkController) addNodeToNodeGroup(nodeGroup string) error {\n\tnode := kubemarkController.nodeTemplate.DeepCopy()\n\tnode.Name = fmt.Sprintf(\"%s-%d\", nodeGroup, kubemarkController.rand.Int63())\n\tnode.Labels = map[string]string{nodeGroupLabel: nodeGroup, \"name\": node.Name}\n\tnode.Spec.Template.Labels = node.Labels\n\n\tvar err error\n\tfor i := 0; i \u003c numRetries; i++ {\n\t\t_, err = kubemarkController.externalCluster.client.CoreV1().ReplicationControllers(node.Namespace).Create(context.TODO(), node, metav1.CreateOptions{})\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn err\n}","line":{"from":222,"to":237}} {"id":100008126,"name":"RemoveNodeFromNodeGroup","signature":"func (kubemarkController *KubemarkController) RemoveNodeFromNodeGroup(nodeGroup string, node string) error","file":"pkg/kubemark/controller.go","code":"func (kubemarkController *KubemarkController) RemoveNodeFromNodeGroup(nodeGroup string, node string) error {\n\tpod := kubemarkController.getPodByName(node)\n\tif pod == nil {\n\t\tklog.Warningf(\"Can't delete node %s from nodegroup %s. Node does not exist.\", node, nodeGroup)\n\t\treturn nil\n\t}\n\tif pod.ObjectMeta.Labels[nodeGroupLabel] != nodeGroup {\n\t\treturn fmt.Errorf(\"can't delete node %s from nodegroup %s. Node is not in nodegroup\", node, nodeGroup)\n\t}\n\tpolicy := metav1.DeletePropagationForeground\n\tvar err error\n\tfor i := 0; i \u003c numRetries; i++ {\n\t\terr = kubemarkController.externalCluster.client.CoreV1().ReplicationControllers(namespaceKubemark).Delete(context.TODO(), pod.ObjectMeta.Labels[\"name\"],\n\t\t\tmetav1.DeleteOptions{PropagationPolicy: \u0026policy})\n\t\tif err == nil {\n\t\t\tklog.Infof(\"marking node %s for deletion\", node)\n\t\t\t// Mark node for deletion from kubemark cluster.\n\t\t\t// Once it becomes unready after replication controller\n\t\t\t// deletion has been noticed, we will delete it explicitly.\n\t\t\t// This is to cover for the fact that kubemark does not\n\t\t\t// take care of this itself.\n\t\t\tkubemarkController.kubemarkCluster.markNodeForDeletion(node)\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"Failed to delete node %s: %v\", node, err)\n}","line":{"from":239,"to":265}} {"id":100008127,"name":"getReplicationControllerByName","signature":"func (kubemarkController *KubemarkController) getReplicationControllerByName(name string) *apiv1.ReplicationController","file":"pkg/kubemark/controller.go","code":"func (kubemarkController *KubemarkController) getReplicationControllerByName(name string) *apiv1.ReplicationController {\n\trcs, err := kubemarkController.externalCluster.rcLister.List(labels.Everything())\n\tif err != nil {\n\t\treturn nil\n\t}\n\tfor _, rc := range rcs {\n\t\tif rc.ObjectMeta.Name == name {\n\t\t\treturn rc\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":267,"to":278}} {"id":100008128,"name":"getPodByName","signature":"func (kubemarkController *KubemarkController) getPodByName(name string) *apiv1.Pod","file":"pkg/kubemark/controller.go","code":"func (kubemarkController *KubemarkController) getPodByName(name string) *apiv1.Pod {\n\tpods, err := kubemarkController.externalCluster.podLister.List(labels.Everything())\n\tif err != nil {\n\t\treturn nil\n\t}\n\tfor _, pod := range pods {\n\t\tif pod.ObjectMeta.Name == name {\n\t\t\treturn pod\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":280,"to":291}} {"id":100008129,"name":"getNodeNameForPod","signature":"func (kubemarkController *KubemarkController) getNodeNameForPod(podName string) (string, error)","file":"pkg/kubemark/controller.go","code":"func (kubemarkController *KubemarkController) getNodeNameForPod(podName string) (string, error) {\n\tpods, err := kubemarkController.externalCluster.podLister.List(labels.Everything())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfor _, pod := range pods {\n\t\tif pod.ObjectMeta.Name == podName {\n\t\t\treturn pod.Labels[\"name\"], nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"pod %s not found\", podName)\n}","line":{"from":293,"to":304}} {"id":100008130,"name":"getNodeTemplate","signature":"func (kubemarkController *KubemarkController) getNodeTemplate() (*apiv1.ReplicationController, error)","file":"pkg/kubemark/controller.go","code":"// getNodeTemplate returns the template for hollow node replication controllers\n// by looking for an existing hollow node specification. This requires at least\n// one kubemark node to be present on startup.\nfunc (kubemarkController *KubemarkController) getNodeTemplate() (*apiv1.ReplicationController, error) {\n\tpodName, err := kubemarkController.kubemarkCluster.getHollowNodeName()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thollowNodeName, err := kubemarkController.getNodeNameForPod(podName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif hollowNode := kubemarkController.getReplicationControllerByName(hollowNodeName); hollowNode != nil {\n\t\tnodeTemplate := \u0026apiv1.ReplicationController{\n\t\t\tSpec: apiv1.ReplicationControllerSpec{\n\t\t\t\tTemplate: hollowNode.Spec.Template,\n\t\t\t},\n\t\t}\n\n\t\tnodeTemplate.Spec.Selector = nil\n\t\tnodeTemplate.Namespace = namespaceKubemark\n\t\tone := int32(1)\n\t\tnodeTemplate.Spec.Replicas = \u0026one\n\n\t\treturn nodeTemplate, nil\n\t}\n\treturn nil, fmt.Errorf(\"can't get hollow node template\")\n}","line":{"from":306,"to":333}} {"id":100008131,"name":"runNodeCreation","signature":"func (kubemarkController *KubemarkController) runNodeCreation(stop \u003c-chan struct{})","file":"pkg/kubemark/controller.go","code":"func (kubemarkController *KubemarkController) runNodeCreation(stop \u003c-chan struct{}) {\n\tfor {\n\t\tselect {\n\t\tcase nodeGroup := \u003c-kubemarkController.createNodeQueue:\n\t\t\tkubemarkController.nodeGroupQueueSizeLock.Lock()\n\t\t\terr := kubemarkController.addNodeToNodeGroup(nodeGroup)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"failed to add node to node group %s: %v\", nodeGroup, err)\n\t\t\t} else {\n\t\t\t\tkubemarkController.nodeGroupQueueSize[nodeGroup]--\n\t\t\t}\n\t\t\tkubemarkController.nodeGroupQueueSizeLock.Unlock()\n\t\tcase \u003c-stop:\n\t\t\treturn\n\t\t}\n\t}\n}","line":{"from":335,"to":351}} {"id":100008132,"name":"getHollowNodeName","signature":"func (kubemarkCluster *kubemarkCluster) getHollowNodeName() (string, error)","file":"pkg/kubemark/controller.go","code":"func (kubemarkCluster *kubemarkCluster) getHollowNodeName() (string, error) {\n\tselector, _ := labels.Parse(nodeGroupLabel)\n\tnodes, err := kubemarkCluster.nodeLister.List(selector)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfor _, node := range nodes {\n\t\treturn node.Name, nil\n\t}\n\treturn \"\", fmt.Errorf(\"did not find any hollow nodes in the cluster\")\n}","line":{"from":353,"to":363}} {"id":100008133,"name":"removeUnneededNodes","signature":"func (kubemarkCluster *kubemarkCluster) removeUnneededNodes(oldObj interface{}, newObj interface{})","file":"pkg/kubemark/controller.go","code":"func (kubemarkCluster *kubemarkCluster) removeUnneededNodes(oldObj interface{}, newObj interface{}) {\n\tnode, ok := newObj.(*apiv1.Node)\n\tif !ok {\n\t\treturn\n\t}\n\tfor _, condition := range node.Status.Conditions {\n\t\t// Delete node if it is in unready state, and it has been\n\t\t// explicitly marked for deletion.\n\t\tif condition.Type == apiv1.NodeReady \u0026\u0026 condition.Status != apiv1.ConditionTrue {\n\t\t\tkubemarkCluster.nodesToDeleteLock.Lock()\n\t\t\tdefer kubemarkCluster.nodesToDeleteLock.Unlock()\n\t\t\tif kubemarkCluster.nodesToDelete[node.Name] {\n\t\t\t\tkubemarkCluster.nodesToDelete[node.Name] = false\n\t\t\t\tif err := kubemarkCluster.client.CoreV1().Nodes().Delete(context.TODO(), node.Name, metav1.DeleteOptions{}); err != nil {\n\t\t\t\t\tklog.Errorf(\"failed to delete node %s from kubemark cluster, err: %v\", node.Name, err)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n}","line":{"from":365,"to":385}} {"id":100008134,"name":"markNodeForDeletion","signature":"func (kubemarkCluster *kubemarkCluster) markNodeForDeletion(name string)","file":"pkg/kubemark/controller.go","code":"func (kubemarkCluster *kubemarkCluster) markNodeForDeletion(name string) {\n\tkubemarkCluster.nodesToDeleteLock.Lock()\n\tdefer kubemarkCluster.nodesToDeleteLock.Unlock()\n\tkubemarkCluster.nodesToDelete[name] = true\n}","line":{"from":387,"to":391}} {"id":100008135,"name":"newReplicationControllerInformer","signature":"func newReplicationControllerInformer(kubeClient kubeclient.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"pkg/kubemark/controller.go","code":"func newReplicationControllerInformer(kubeClient kubeclient.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\trcListWatch := cache.NewListWatchFromClient(kubeClient.CoreV1().RESTClient(), \"replicationcontrollers\", namespaceKubemark, fields.Everything())\n\treturn cache.NewSharedIndexInformer(rcListWatch, \u0026apiv1.ReplicationController{}, resyncPeriod, nil)\n}","line":{"from":393,"to":396}} {"id":100008136,"name":"newPodInformer","signature":"func newPodInformer(kubeClient kubeclient.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"pkg/kubemark/controller.go","code":"func newPodInformer(kubeClient kubeclient.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\tpodListWatch := cache.NewListWatchFromClient(kubeClient.CoreV1().RESTClient(), \"pods\", namespaceKubemark, fields.Everything())\n\treturn cache.NewSharedIndexInformer(podListWatch, \u0026apiv1.Pod{}, resyncPeriod, nil)\n}","line":{"from":398,"to":401}} {"id":100008137,"name":"volumePlugins","signature":"func volumePlugins() []volume.VolumePlugin","file":"pkg/kubemark/hollow_kubelet.go","code":"func volumePlugins() []volume.VolumePlugin {\n\tallPlugins := []volume.VolumePlugin{}\n\tallPlugins = append(allPlugins, emptydir.ProbeVolumePlugins()...)\n\tallPlugins = append(allPlugins, git_repo.ProbeVolumePlugins()...)\n\tallPlugins = append(allPlugins, hostpath.FakeProbeVolumePlugins(volume.VolumeConfig{})...)\n\tallPlugins = append(allPlugins, nfs.ProbeVolumePlugins(volume.VolumeConfig{})...)\n\tallPlugins = append(allPlugins, secret.ProbeVolumePlugins()...)\n\tallPlugins = append(allPlugins, iscsi.ProbeVolumePlugins()...)\n\tallPlugins = append(allPlugins, rbd.ProbeVolumePlugins()...)\n\tallPlugins = append(allPlugins, cephfs.ProbeVolumePlugins()...)\n\tallPlugins = append(allPlugins, downwardapi.ProbeVolumePlugins()...)\n\tallPlugins = append(allPlugins, fc.ProbeVolumePlugins()...)\n\tallPlugins = append(allPlugins, configmap.ProbeVolumePlugins()...)\n\tallPlugins = append(allPlugins, projected.ProbeVolumePlugins()...)\n\tallPlugins = append(allPlugins, portworx.ProbeVolumePlugins()...)\n\tallPlugins = append(allPlugins, local.ProbeVolumePlugins()...)\n\tallPlugins = append(allPlugins, csi.ProbeVolumePlugins()...)\n\treturn allPlugins\n}","line":{"from":70,"to":88}} {"id":100008138,"name":"NewHollowKubelet","signature":"func NewHollowKubelet(","file":"pkg/kubemark/hollow_kubelet.go","code":"func NewHollowKubelet(\n\tflags *options.KubeletFlags,\n\tconfig *kubeletconfig.KubeletConfiguration,\n\tclient *clientset.Clientset,\n\theartbeatClient *clientset.Clientset,\n\tcadvisorInterface cadvisor.Interface,\n\timageService internalapi.ImageManagerService,\n\truntimeService internalapi.RuntimeService,\n\tcontainerManager cm.ContainerManager) *HollowKubelet {\n\td := \u0026kubelet.Dependencies{\n\t\tKubeClient: client,\n\t\tHeartbeatClient: heartbeatClient,\n\t\tProbeManager: probetest.FakeManager{},\n\t\tRemoteRuntimeService: runtimeService,\n\t\tRemoteImageService: imageService,\n\t\tCAdvisorInterface: cadvisorInterface,\n\t\tCloud: nil,\n\t\tOSInterface: \u0026containertest.FakeOS{},\n\t\tContainerManager: containerManager,\n\t\tVolumePlugins: volumePlugins(),\n\t\tTLSOptions: nil,\n\t\tOOMAdjuster: oom.NewFakeOOMAdjuster(),\n\t\tMounter: \u0026mount.FakeMounter{},\n\t\tSubpather: \u0026subpath.FakeSubpath{},\n\t\tHostUtil: hostutil.NewFakeHostUtil(nil),\n\t\tPodStartupLatencyTracker: kubeletutil.NewPodStartupLatencyTracker(),\n\t\tTracerProvider: trace.NewNoopTracerProvider(),\n\t\tRecorder: \u0026record.FakeRecorder{}, // With real recorder we attempt to read /dev/kmsg.\n\t}\n\n\treturn \u0026HollowKubelet{\n\t\tKubeletFlags: flags,\n\t\tKubeletConfiguration: config,\n\t\tKubeletDeps: d,\n\t}\n}","line":{"from":90,"to":125}} {"id":100008139,"name":"Run","signature":"func (hk *HollowKubelet) Run()","file":"pkg/kubemark/hollow_kubelet.go","code":"// Starts this HollowKubelet and blocks.\nfunc (hk *HollowKubelet) Run() {\n\tif err := kubeletapp.RunKubelet(\u0026options.KubeletServer{\n\t\tKubeletFlags: *hk.KubeletFlags,\n\t\tKubeletConfiguration: *hk.KubeletConfiguration,\n\t}, hk.KubeletDeps, false); err != nil {\n\t\tklog.Fatalf(\"Failed to run HollowKubelet: %v. Exiting.\", err)\n\t}\n\tselect {}\n}","line":{"from":127,"to":136}} {"id":100008140,"name":"GetHollowKubeletConfig","signature":"func GetHollowKubeletConfig(opt *HollowKubeletOptions) (*options.KubeletFlags, *kubeletconfig.KubeletConfiguration)","file":"pkg/kubemark/hollow_kubelet.go","code":"// Builds a KubeletConfiguration for the HollowKubelet, ensuring that the\n// usual defaults are applied for fields we do not override.\nfunc GetHollowKubeletConfig(opt *HollowKubeletOptions) (*options.KubeletFlags, *kubeletconfig.KubeletConfiguration) {\n\ttestRootDir := utils.MakeTempDirOrDie(\"hollow-kubelet.\", \"\")\n\tpodFilePath := utils.MakeTempDirOrDie(\"static-pods\", testRootDir)\n\tklog.Infof(\"Using %s as root dir for hollow-kubelet\", testRootDir)\n\n\t// Flags struct\n\tf := options.NewKubeletFlags()\n\tf.RootDirectory = testRootDir\n\tf.HostnameOverride = opt.NodeName\n\tf.MinimumGCAge = metav1.Duration{Duration: 1 * time.Minute}\n\tf.MaxContainerCount = 100\n\tf.MaxPerPodContainerCount = 2\n\tf.NodeLabels = opt.NodeLabels\n\tf.RegisterSchedulable = true\n\n\t// Config struct\n\tc, err := options.NewKubeletConfiguration()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tc.ImageServiceEndpoint = \"unix:///run/containerd/containerd.sock\"\n\tc.StaticPodURL = \"\"\n\tc.EnableServer = true\n\tc.Address = \"0.0.0.0\" /* bind address */\n\tc.Port = int32(opt.KubeletPort)\n\tc.ReadOnlyPort = int32(opt.KubeletReadOnlyPort)\n\tc.StaticPodPath = podFilePath\n\tc.FileCheckFrequency.Duration = 20 * time.Second\n\tc.HTTPCheckFrequency.Duration = 20 * time.Second\n\tc.NodeStatusUpdateFrequency.Duration = 10 * time.Second\n\tc.NodeStatusReportFrequency.Duration = 5 * time.Minute\n\tc.SyncFrequency.Duration = 10 * time.Second\n\tc.EvictionPressureTransitionPeriod.Duration = 5 * time.Minute\n\tc.MaxPods = int32(opt.MaxPods)\n\tc.PodsPerCore = int32(opt.PodsPerCore)\n\tc.ClusterDNS = []string{}\n\tc.ImageGCHighThresholdPercent = 90\n\tc.ImageGCLowThresholdPercent = 80\n\tc.ProviderID = fmt.Sprintf(\"kubemark://%v\", opt.NodeName)\n\tc.VolumeStatsAggPeriod.Duration = time.Minute\n\tc.CgroupRoot = \"\"\n\tc.CPUCFSQuota = true\n\tc.EnableControllerAttachDetach = false\n\tc.EnableDebuggingHandlers = true\n\tc.CgroupsPerQOS = false\n\t// hairpin-veth is used to allow hairpin packets. Note that this deviates from\n\t// what the \"real\" kubelet currently does, because there's no way to\n\t// set promiscuous mode on docker0.\n\tc.HairpinMode = kubeletconfig.HairpinVeth\n\tc.MaxOpenFiles = 1024\n\tc.RegistryBurst = 10\n\tc.RegistryPullQPS = 5.0\n\tc.ResolverConfig = kubetypes.ResolvConfDefault\n\tc.KubeletCgroups = \"/kubelet\"\n\tc.SerializeImagePulls = true\n\tc.SystemCgroups = \"\"\n\tc.ProtectKernelDefaults = false\n\tc.RegisterWithTaints = opt.RegisterWithTaints\n\tc.RegisterNode = true\n\tc.LocalStorageCapacityIsolation = true\n\n\treturn f, c\n}","line":{"from":149,"to":214}} {"id":100008141,"name":"Sync","signature":"func (*FakeProxier) Sync() {}","file":"pkg/kubemark/hollow_proxy.go","code":"func (*FakeProxier) Sync() {}","line":{"from":52,"to":52}} {"id":100008142,"name":"SyncLoop","signature":"func (*FakeProxier) SyncLoop()","file":"pkg/kubemark/hollow_proxy.go","code":"func (*FakeProxier) SyncLoop() {\n\tselect {}\n}","line":{"from":53,"to":55}} {"id":100008143,"name":"OnServiceAdd","signature":"func (*FakeProxier) OnServiceAdd(service *v1.Service) {}","file":"pkg/kubemark/hollow_proxy.go","code":"func (*FakeProxier) OnServiceAdd(service *v1.Service) {}","line":{"from":56,"to":56}} {"id":100008144,"name":"OnServiceUpdate","signature":"func (*FakeProxier) OnServiceUpdate(oldService, service *v1.Service) {}","file":"pkg/kubemark/hollow_proxy.go","code":"func (*FakeProxier) OnServiceUpdate(oldService, service *v1.Service) {}","line":{"from":57,"to":57}} {"id":100008145,"name":"OnServiceDelete","signature":"func (*FakeProxier) OnServiceDelete(service *v1.Service) {}","file":"pkg/kubemark/hollow_proxy.go","code":"func (*FakeProxier) OnServiceDelete(service *v1.Service) {}","line":{"from":58,"to":58}} {"id":100008146,"name":"OnServiceSynced","signature":"func (*FakeProxier) OnServiceSynced() {}","file":"pkg/kubemark/hollow_proxy.go","code":"func (*FakeProxier) OnServiceSynced() {}","line":{"from":59,"to":59}} {"id":100008147,"name":"OnEndpointSliceAdd","signature":"func (*FakeProxier) OnEndpointSliceAdd(slice *discoveryv1.EndpointSlice) {}","file":"pkg/kubemark/hollow_proxy.go","code":"func (*FakeProxier) OnEndpointSliceAdd(slice *discoveryv1.EndpointSlice) {}","line":{"from":60,"to":60}} {"id":100008148,"name":"OnEndpointSliceUpdate","signature":"func (*FakeProxier) OnEndpointSliceUpdate(oldSlice, slice *discoveryv1.EndpointSlice) {}","file":"pkg/kubemark/hollow_proxy.go","code":"func (*FakeProxier) OnEndpointSliceUpdate(oldSlice, slice *discoveryv1.EndpointSlice) {}","line":{"from":61,"to":61}} {"id":100008149,"name":"OnEndpointSliceDelete","signature":"func (*FakeProxier) OnEndpointSliceDelete(slice *discoveryv1.EndpointSlice) {}","file":"pkg/kubemark/hollow_proxy.go","code":"func (*FakeProxier) OnEndpointSliceDelete(slice *discoveryv1.EndpointSlice) {}","line":{"from":62,"to":62}} {"id":100008150,"name":"OnEndpointSlicesSynced","signature":"func (*FakeProxier) OnEndpointSlicesSynced() {}","file":"pkg/kubemark/hollow_proxy.go","code":"func (*FakeProxier) OnEndpointSlicesSynced() {}","line":{"from":63,"to":63}} {"id":100008151,"name":"NewHollowProxyOrDie","signature":"func NewHollowProxyOrDie(","file":"pkg/kubemark/hollow_proxy.go","code":"func NewHollowProxyOrDie(\n\tnodeName string,\n\tclient clientset.Interface,\n\teventClient v1core.EventsGetter,\n\tiptInterface utiliptables.Interface,\n\tsysctl utilsysctl.Interface,\n\texecer utilexec.Interface,\n\tbroadcaster events.EventBroadcaster,\n\trecorder events.EventRecorder,\n\tuseRealProxier bool,\n\tproxierSyncPeriod time.Duration,\n\tproxierMinSyncPeriod time.Duration,\n) (*HollowProxy, error) {\n\t// Create proxier and service/endpoint handlers.\n\tvar proxier proxy.Provider\n\tvar err error\n\n\tif useRealProxier {\n\t\tnodeIP := utilnode.GetNodeIP(client, nodeName)\n\t\tif nodeIP == nil {\n\t\t\tklog.InfoS(\"Can't determine this node's IP, assuming 127.0.0.1\")\n\t\t\tnodeIP = netutils.ParseIPSloppy(\"127.0.0.1\")\n\t\t}\n\t\tfamily := v1.IPv4Protocol\n\t\tif iptInterface.IsIPv6() {\n\t\t\tfamily = v1.IPv6Protocol\n\t\t}\n\t\t// Real proxier with fake iptables, sysctl, etc underneath it.\n\t\t//var err error\n\t\tproxier, err = iptables.NewProxier(\n\t\t\tfamily,\n\t\t\tiptInterface,\n\t\t\tsysctl,\n\t\t\texecer,\n\t\t\tproxierSyncPeriod,\n\t\t\tproxierMinSyncPeriod,\n\t\t\tfalse,\n\t\t\tfalse,\n\t\t\t0,\n\t\t\tproxyutiliptables.NewNoOpLocalDetector(),\n\t\t\tnodeName,\n\t\t\tnodeIP,\n\t\t\trecorder,\n\t\t\tnil,\n\t\t\t[]string{},\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to create proxier: %v\", err)\n\t\t}\n\t} else {\n\t\tproxier = \u0026FakeProxier{}\n\t}\n\n\t// Create a Hollow Proxy instance.\n\tnodeRef := \u0026v1.ObjectReference{\n\t\tKind: \"Node\",\n\t\tName: nodeName,\n\t\tUID: types.UID(nodeName),\n\t\tNamespace: \"\",\n\t}\n\treturn \u0026HollowProxy{\n\t\tProxyServer: \u0026proxyapp.ProxyServer{\n\t\t\tClient: client,\n\t\t\tEventClient: eventClient,\n\t\t\tIptInterface: iptInterface,\n\t\t\tProxier: proxier,\n\t\t\tBroadcaster: broadcaster,\n\t\t\tRecorder: recorder,\n\t\t\tProxyMode: \"fake\",\n\t\t\tNodeRef: nodeRef,\n\t\t\tOOMScoreAdj: utilpointer.Int32Ptr(0),\n\t\t\tConfigSyncPeriod: 30 * time.Second,\n\t\t},\n\t}, nil\n}","line":{"from":65,"to":139}} {"id":100008152,"name":"Run","signature":"func (hp *HollowProxy) Run() error","file":"pkg/kubemark/hollow_proxy.go","code":"func (hp *HollowProxy) Run() error {\n\tif err := hp.ProxyServer.Run(); err != nil {\n\t\treturn fmt.Errorf(\"Error while running proxy: %w\", err)\n\t}\n\treturn nil\n}","line":{"from":141,"to":146}} {"id":100008153,"name":"PrintObj","signature":"func (fn ResourcePrinterFunc) PrintObj(obj runtime.Object, w io.Writer) error","file":"pkg/printers/interface.go","code":"// PrintObj implements ResourcePrinter\nfunc (fn ResourcePrinterFunc) PrintObj(obj runtime.Object, w io.Writer) error {\n\treturn fn(obj, w)\n}","line":{"from":34,"to":37}} {"id":100008154,"name":"AddHandlers","signature":"func AddHandlers(h printers.PrintHandler)","file":"pkg/printers/internalversion/printers.go","code":"// AddHandlers adds print handlers for default Kubernetes types dealing with internal versions.\nfunc AddHandlers(h printers.PrintHandler) {\n\tpodColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Ready\", Type: \"string\", Description: \"The aggregate readiness state of this pod for accepting traffic.\"},\n\t\t{Name: \"Status\", Type: \"string\", Description: \"The aggregate status of the containers in this pod.\"},\n\t\t{Name: \"Restarts\", Type: \"string\", Description: \"The number of times the containers in this pod have been restarted and when the last container in this pod has restarted.\"},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t\t{Name: \"IP\", Type: \"string\", Priority: 1, Description: apiv1.PodStatus{}.SwaggerDoc()[\"podIP\"]},\n\t\t{Name: \"Node\", Type: \"string\", Priority: 1, Description: apiv1.PodSpec{}.SwaggerDoc()[\"nodeName\"]},\n\t\t{Name: \"Nominated Node\", Type: \"string\", Priority: 1, Description: apiv1.PodStatus{}.SwaggerDoc()[\"nominatedNodeName\"]},\n\t\t{Name: \"Readiness Gates\", Type: \"string\", Priority: 1, Description: apiv1.PodSpec{}.SwaggerDoc()[\"readinessGates\"]},\n\t}\n\n\t// Errors are suppressed as TableHandler already logs internally\n\t_ = h.TableHandler(podColumnDefinitions, printPodList)\n\t_ = h.TableHandler(podColumnDefinitions, printPod)\n\n\tpodTemplateColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Containers\", Type: \"string\", Description: \"Names of each container in the template.\"},\n\t\t{Name: \"Images\", Type: \"string\", Description: \"Images referenced by each container in the template.\"},\n\t\t{Name: \"Pod Labels\", Type: \"string\", Description: \"The labels for the pod template.\"},\n\t}\n\t_ = h.TableHandler(podTemplateColumnDefinitions, printPodTemplate)\n\t_ = h.TableHandler(podTemplateColumnDefinitions, printPodTemplateList)\n\n\tpodDisruptionBudgetColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Min Available\", Type: \"string\", Description: \"The minimum number of pods that must be available.\"},\n\t\t{Name: \"Max Unavailable\", Type: \"string\", Description: \"The maximum number of pods that may be unavailable.\"},\n\t\t{Name: \"Allowed Disruptions\", Type: \"integer\", Description: \"Calculated number of pods that may be disrupted at this time.\"},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(podDisruptionBudgetColumnDefinitions, printPodDisruptionBudget)\n\t_ = h.TableHandler(podDisruptionBudgetColumnDefinitions, printPodDisruptionBudgetList)\n\n\treplicationControllerColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Desired\", Type: \"integer\", Description: apiv1.ReplicationControllerSpec{}.SwaggerDoc()[\"replicas\"]},\n\t\t{Name: \"Current\", Type: \"integer\", Description: apiv1.ReplicationControllerStatus{}.SwaggerDoc()[\"replicas\"]},\n\t\t{Name: \"Ready\", Type: \"integer\", Description: apiv1.ReplicationControllerStatus{}.SwaggerDoc()[\"readyReplicas\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t\t{Name: \"Containers\", Type: \"string\", Priority: 1, Description: \"Names of each container in the template.\"},\n\t\t{Name: \"Images\", Type: \"string\", Priority: 1, Description: \"Images referenced by each container in the template.\"},\n\t\t{Name: \"Selector\", Type: \"string\", Priority: 1, Description: apiv1.ReplicationControllerSpec{}.SwaggerDoc()[\"selector\"]},\n\t}\n\t_ = h.TableHandler(replicationControllerColumnDefinitions, printReplicationController)\n\t_ = h.TableHandler(replicationControllerColumnDefinitions, printReplicationControllerList)\n\n\treplicaSetColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Desired\", Type: \"integer\", Description: extensionsv1beta1.ReplicaSetSpec{}.SwaggerDoc()[\"replicas\"]},\n\t\t{Name: \"Current\", Type: \"integer\", Description: extensionsv1beta1.ReplicaSetStatus{}.SwaggerDoc()[\"replicas\"]},\n\t\t{Name: \"Ready\", Type: \"integer\", Description: extensionsv1beta1.ReplicaSetStatus{}.SwaggerDoc()[\"readyReplicas\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t\t{Name: \"Containers\", Type: \"string\", Priority: 1, Description: \"Names of each container in the template.\"},\n\t\t{Name: \"Images\", Type: \"string\", Priority: 1, Description: \"Images referenced by each container in the template.\"},\n\t\t{Name: \"Selector\", Type: \"string\", Priority: 1, Description: extensionsv1beta1.ReplicaSetSpec{}.SwaggerDoc()[\"selector\"]},\n\t}\n\t_ = h.TableHandler(replicaSetColumnDefinitions, printReplicaSet)\n\t_ = h.TableHandler(replicaSetColumnDefinitions, printReplicaSetList)\n\n\tdaemonSetColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Desired\", Type: \"integer\", Description: extensionsv1beta1.DaemonSetStatus{}.SwaggerDoc()[\"desiredNumberScheduled\"]},\n\t\t{Name: \"Current\", Type: \"integer\", Description: extensionsv1beta1.DaemonSetStatus{}.SwaggerDoc()[\"currentNumberScheduled\"]},\n\t\t{Name: \"Ready\", Type: \"integer\", Description: extensionsv1beta1.DaemonSetStatus{}.SwaggerDoc()[\"numberReady\"]},\n\t\t{Name: \"Up-to-date\", Type: \"integer\", Description: extensionsv1beta1.DaemonSetStatus{}.SwaggerDoc()[\"updatedNumberScheduled\"]},\n\t\t{Name: \"Available\", Type: \"integer\", Description: extensionsv1beta1.DaemonSetStatus{}.SwaggerDoc()[\"numberAvailable\"]},\n\t\t{Name: \"Node Selector\", Type: \"string\", Description: apiv1.PodSpec{}.SwaggerDoc()[\"nodeSelector\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t\t{Name: \"Containers\", Type: \"string\", Priority: 1, Description: \"Names of each container in the template.\"},\n\t\t{Name: \"Images\", Type: \"string\", Priority: 1, Description: \"Images referenced by each container in the template.\"},\n\t\t{Name: \"Selector\", Type: \"string\", Priority: 1, Description: extensionsv1beta1.DaemonSetSpec{}.SwaggerDoc()[\"selector\"]},\n\t}\n\t_ = h.TableHandler(daemonSetColumnDefinitions, printDaemonSet)\n\t_ = h.TableHandler(daemonSetColumnDefinitions, printDaemonSetList)\n\n\tjobColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Completions\", Type: \"string\", Description: batchv1.JobStatus{}.SwaggerDoc()[\"succeeded\"]},\n\t\t{Name: \"Duration\", Type: \"string\", Description: \"Time required to complete the job.\"},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t\t{Name: \"Containers\", Type: \"string\", Priority: 1, Description: \"Names of each container in the template.\"},\n\t\t{Name: \"Images\", Type: \"string\", Priority: 1, Description: \"Images referenced by each container in the template.\"},\n\t\t{Name: \"Selector\", Type: \"string\", Priority: 1, Description: batchv1.JobSpec{}.SwaggerDoc()[\"selector\"]},\n\t}\n\t_ = h.TableHandler(jobColumnDefinitions, printJob)\n\t_ = h.TableHandler(jobColumnDefinitions, printJobList)\n\n\tcronJobColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Schedule\", Type: \"string\", Description: batchv1beta1.CronJobSpec{}.SwaggerDoc()[\"schedule\"]},\n\t\t{Name: \"Suspend\", Type: \"boolean\", Description: batchv1beta1.CronJobSpec{}.SwaggerDoc()[\"suspend\"]},\n\t\t{Name: \"Active\", Type: \"integer\", Description: batchv1beta1.CronJobStatus{}.SwaggerDoc()[\"active\"]},\n\t\t{Name: \"Last Schedule\", Type: \"string\", Description: batchv1beta1.CronJobStatus{}.SwaggerDoc()[\"lastScheduleTime\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t\t{Name: \"Containers\", Type: \"string\", Priority: 1, Description: \"Names of each container in the template.\"},\n\t\t{Name: \"Images\", Type: \"string\", Priority: 1, Description: \"Images referenced by each container in the template.\"},\n\t\t{Name: \"Selector\", Type: \"string\", Priority: 1, Description: batchv1.JobSpec{}.SwaggerDoc()[\"selector\"]},\n\t}\n\t_ = h.TableHandler(cronJobColumnDefinitions, printCronJob)\n\t_ = h.TableHandler(cronJobColumnDefinitions, printCronJobList)\n\n\tserviceColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Type\", Type: \"string\", Description: apiv1.ServiceSpec{}.SwaggerDoc()[\"type\"]},\n\t\t{Name: \"Cluster-IP\", Type: \"string\", Description: apiv1.ServiceSpec{}.SwaggerDoc()[\"clusterIP\"]},\n\t\t{Name: \"External-IP\", Type: \"string\", Description: apiv1.ServiceSpec{}.SwaggerDoc()[\"externalIPs\"]},\n\t\t{Name: \"Port(s)\", Type: \"string\", Description: apiv1.ServiceSpec{}.SwaggerDoc()[\"ports\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t\t{Name: \"Selector\", Type: \"string\", Priority: 1, Description: apiv1.ServiceSpec{}.SwaggerDoc()[\"selector\"]},\n\t}\n\n\t_ = h.TableHandler(serviceColumnDefinitions, printService)\n\t_ = h.TableHandler(serviceColumnDefinitions, printServiceList)\n\n\tingressColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Class\", Type: \"string\", Description: \"The name of the IngressClass resource that should be used for additional configuration\"},\n\t\t{Name: \"Hosts\", Type: \"string\", Description: \"Hosts that incoming requests are matched against before the ingress rule\"},\n\t\t{Name: \"Address\", Type: \"string\", Description: \"Address is a list containing ingress points for the load-balancer\"},\n\t\t{Name: \"Ports\", Type: \"string\", Description: \"Ports of TLS configurations that open\"},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(ingressColumnDefinitions, printIngress)\n\t_ = h.TableHandler(ingressColumnDefinitions, printIngressList)\n\n\tingressClassColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Controller\", Type: \"string\", Description: \"Controller that is responsible for handling this class\"},\n\t\t{Name: \"Parameters\", Type: \"string\", Description: \"A reference to a resource with additional parameters\"},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(ingressClassColumnDefinitions, printIngressClass)\n\t_ = h.TableHandler(ingressClassColumnDefinitions, printIngressClassList)\n\n\tstatefulSetColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Ready\", Type: \"string\", Description: \"Number of the pod with ready state\"},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t\t{Name: \"Containers\", Type: \"string\", Priority: 1, Description: \"Names of each container in the template.\"},\n\t\t{Name: \"Images\", Type: \"string\", Priority: 1, Description: \"Images referenced by each container in the template.\"},\n\t}\n\t_ = h.TableHandler(statefulSetColumnDefinitions, printStatefulSet)\n\t_ = h.TableHandler(statefulSetColumnDefinitions, printStatefulSetList)\n\n\tendpointColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Endpoints\", Type: \"string\", Description: apiv1.Endpoints{}.SwaggerDoc()[\"subsets\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(endpointColumnDefinitions, printEndpoints)\n\t_ = h.TableHandler(endpointColumnDefinitions, printEndpointsList)\n\n\tnodeColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Status\", Type: \"string\", Description: \"The status of the node\"},\n\t\t{Name: \"Roles\", Type: \"string\", Description: \"The roles of the node\"},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t\t{Name: \"Version\", Type: \"string\", Description: apiv1.NodeSystemInfo{}.SwaggerDoc()[\"kubeletVersion\"]},\n\t\t{Name: \"Internal-IP\", Type: \"string\", Priority: 1, Description: apiv1.NodeStatus{}.SwaggerDoc()[\"addresses\"]},\n\t\t{Name: \"External-IP\", Type: \"string\", Priority: 1, Description: apiv1.NodeStatus{}.SwaggerDoc()[\"addresses\"]},\n\t\t{Name: \"OS-Image\", Type: \"string\", Priority: 1, Description: apiv1.NodeSystemInfo{}.SwaggerDoc()[\"osImage\"]},\n\t\t{Name: \"Kernel-Version\", Type: \"string\", Priority: 1, Description: apiv1.NodeSystemInfo{}.SwaggerDoc()[\"kernelVersion\"]},\n\t\t{Name: \"Container-Runtime\", Type: \"string\", Priority: 1, Description: apiv1.NodeSystemInfo{}.SwaggerDoc()[\"containerRuntimeVersion\"]},\n\t}\n\n\t_ = h.TableHandler(nodeColumnDefinitions, printNode)\n\t_ = h.TableHandler(nodeColumnDefinitions, printNodeList)\n\n\teventColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Last Seen\", Type: \"string\", Description: apiv1.Event{}.SwaggerDoc()[\"lastTimestamp\"]},\n\t\t{Name: \"Type\", Type: \"string\", Description: apiv1.Event{}.SwaggerDoc()[\"type\"]},\n\t\t{Name: \"Reason\", Type: \"string\", Description: apiv1.Event{}.SwaggerDoc()[\"reason\"]},\n\t\t{Name: \"Object\", Type: \"string\", Description: apiv1.Event{}.SwaggerDoc()[\"involvedObject\"]},\n\t\t{Name: \"Subobject\", Type: \"string\", Priority: 1, Description: apiv1.Event{}.InvolvedObject.SwaggerDoc()[\"fieldPath\"]},\n\t\t{Name: \"Source\", Type: \"string\", Priority: 1, Description: apiv1.Event{}.SwaggerDoc()[\"source\"]},\n\t\t{Name: \"Message\", Type: \"string\", Description: apiv1.Event{}.SwaggerDoc()[\"message\"]},\n\t\t{Name: \"First Seen\", Type: \"string\", Priority: 1, Description: apiv1.Event{}.SwaggerDoc()[\"firstTimestamp\"]},\n\t\t{Name: \"Count\", Type: \"string\", Priority: 1, Description: apiv1.Event{}.SwaggerDoc()[\"count\"]},\n\t\t{Name: \"Name\", Type: \"string\", Priority: 1, Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t}\n\t_ = h.TableHandler(eventColumnDefinitions, printEvent)\n\t_ = h.TableHandler(eventColumnDefinitions, printEventList)\n\n\tnamespaceColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Status\", Type: \"string\", Description: \"The status of the namespace\"},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(namespaceColumnDefinitions, printNamespace)\n\t_ = h.TableHandler(namespaceColumnDefinitions, printNamespaceList)\n\n\tsecretColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Type\", Type: \"string\", Description: apiv1.Secret{}.SwaggerDoc()[\"type\"]},\n\t\t{Name: \"Data\", Type: \"string\", Description: apiv1.Secret{}.SwaggerDoc()[\"data\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(secretColumnDefinitions, printSecret)\n\t_ = h.TableHandler(secretColumnDefinitions, printSecretList)\n\n\tserviceAccountColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Secrets\", Type: \"string\", Description: apiv1.ServiceAccount{}.SwaggerDoc()[\"secrets\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(serviceAccountColumnDefinitions, printServiceAccount)\n\t_ = h.TableHandler(serviceAccountColumnDefinitions, printServiceAccountList)\n\n\tpersistentVolumeColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Capacity\", Type: \"string\", Description: apiv1.PersistentVolumeSpec{}.SwaggerDoc()[\"capacity\"]},\n\t\t{Name: \"Access Modes\", Type: \"string\", Description: apiv1.PersistentVolumeSpec{}.SwaggerDoc()[\"accessModes\"]},\n\t\t{Name: \"Reclaim Policy\", Type: \"string\", Description: apiv1.PersistentVolumeSpec{}.SwaggerDoc()[\"persistentVolumeReclaimPolicy\"]},\n\t\t{Name: \"Status\", Type: \"string\", Description: apiv1.PersistentVolumeStatus{}.SwaggerDoc()[\"phase\"]},\n\t\t{Name: \"Claim\", Type: \"string\", Description: apiv1.PersistentVolumeSpec{}.SwaggerDoc()[\"claimRef\"]},\n\t\t{Name: \"StorageClass\", Type: \"string\", Description: \"StorageClass of the pv\"},\n\t\t{Name: \"Reason\", Type: \"string\", Description: apiv1.PersistentVolumeStatus{}.SwaggerDoc()[\"reason\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t\t{Name: \"VolumeMode\", Type: \"string\", Priority: 1, Description: apiv1.PersistentVolumeSpec{}.SwaggerDoc()[\"volumeMode\"]},\n\t}\n\t_ = h.TableHandler(persistentVolumeColumnDefinitions, printPersistentVolume)\n\t_ = h.TableHandler(persistentVolumeColumnDefinitions, printPersistentVolumeList)\n\n\tpersistentVolumeClaimColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Status\", Type: \"string\", Description: apiv1.PersistentVolumeClaimStatus{}.SwaggerDoc()[\"phase\"]},\n\t\t{Name: \"Volume\", Type: \"string\", Description: apiv1.PersistentVolumeClaimSpec{}.SwaggerDoc()[\"volumeName\"]},\n\t\t{Name: \"Capacity\", Type: \"string\", Description: apiv1.PersistentVolumeClaimStatus{}.SwaggerDoc()[\"capacity\"]},\n\t\t{Name: \"Access Modes\", Type: \"string\", Description: apiv1.PersistentVolumeClaimStatus{}.SwaggerDoc()[\"accessModes\"]},\n\t\t{Name: \"StorageClass\", Type: \"string\", Description: \"StorageClass of the pvc\"},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t\t{Name: \"VolumeMode\", Type: \"string\", Priority: 1, Description: apiv1.PersistentVolumeClaimSpec{}.SwaggerDoc()[\"volumeMode\"]},\n\t}\n\t_ = h.TableHandler(persistentVolumeClaimColumnDefinitions, printPersistentVolumeClaim)\n\t_ = h.TableHandler(persistentVolumeClaimColumnDefinitions, printPersistentVolumeClaimList)\n\n\tcomponentStatusColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Status\", Type: \"string\", Description: \"Status of the component conditions\"},\n\t\t{Name: \"Message\", Type: \"string\", Description: \"Message of the component conditions\"},\n\t\t{Name: \"Error\", Type: \"string\", Description: \"Error of the component conditions\"},\n\t}\n\t_ = h.TableHandler(componentStatusColumnDefinitions, printComponentStatus)\n\t_ = h.TableHandler(componentStatusColumnDefinitions, printComponentStatusList)\n\n\tdeploymentColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Ready\", Type: \"string\", Description: \"Number of the pod with ready state\"},\n\t\t{Name: \"Up-to-date\", Type: \"string\", Description: extensionsv1beta1.DeploymentStatus{}.SwaggerDoc()[\"updatedReplicas\"]},\n\t\t{Name: \"Available\", Type: \"string\", Description: extensionsv1beta1.DeploymentStatus{}.SwaggerDoc()[\"availableReplicas\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t\t{Name: \"Containers\", Type: \"string\", Priority: 1, Description: \"Names of each container in the template.\"},\n\t\t{Name: \"Images\", Type: \"string\", Priority: 1, Description: \"Images referenced by each container in the template.\"},\n\t\t{Name: \"Selector\", Type: \"string\", Priority: 1, Description: extensionsv1beta1.DeploymentSpec{}.SwaggerDoc()[\"selector\"]},\n\t}\n\t_ = h.TableHandler(deploymentColumnDefinitions, printDeployment)\n\t_ = h.TableHandler(deploymentColumnDefinitions, printDeploymentList)\n\n\thorizontalPodAutoscalerColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Reference\", Type: \"string\", Description: autoscalingv2beta1.HorizontalPodAutoscalerSpec{}.SwaggerDoc()[\"scaleTargetRef\"]},\n\t\t{Name: \"Targets\", Type: \"string\", Description: autoscalingv2beta1.HorizontalPodAutoscalerSpec{}.SwaggerDoc()[\"metrics\"]},\n\t\t{Name: \"MinPods\", Type: \"string\", Description: autoscalingv2beta1.HorizontalPodAutoscalerSpec{}.SwaggerDoc()[\"minReplicas\"]},\n\t\t{Name: \"MaxPods\", Type: \"string\", Description: autoscalingv2beta1.HorizontalPodAutoscalerSpec{}.SwaggerDoc()[\"maxReplicas\"]},\n\t\t{Name: \"Replicas\", Type: \"string\", Description: autoscalingv2beta1.HorizontalPodAutoscalerStatus{}.SwaggerDoc()[\"currentReplicas\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(horizontalPodAutoscalerColumnDefinitions, printHorizontalPodAutoscaler)\n\t_ = h.TableHandler(horizontalPodAutoscalerColumnDefinitions, printHorizontalPodAutoscalerList)\n\n\tconfigMapColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Data\", Type: \"string\", Description: apiv1.ConfigMap{}.SwaggerDoc()[\"data\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(configMapColumnDefinitions, printConfigMap)\n\t_ = h.TableHandler(configMapColumnDefinitions, printConfigMapList)\n\n\tnetworkPolicyColumnDefinitioins := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Pod-Selector\", Type: \"string\", Description: extensionsv1beta1.NetworkPolicySpec{}.SwaggerDoc()[\"podSelector\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(networkPolicyColumnDefinitioins, printNetworkPolicy)\n\t_ = h.TableHandler(networkPolicyColumnDefinitioins, printNetworkPolicyList)\n\n\troleBindingsColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Role\", Type: \"string\", Description: rbacv1beta1.RoleBinding{}.SwaggerDoc()[\"roleRef\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t\t{Name: \"Users\", Type: \"string\", Priority: 1, Description: \"Users in the roleBinding\"},\n\t\t{Name: \"Groups\", Type: \"string\", Priority: 1, Description: \"Groups in the roleBinding\"},\n\t\t{Name: \"ServiceAccounts\", Type: \"string\", Priority: 1, Description: \"ServiceAccounts in the roleBinding\"},\n\t}\n\t_ = h.TableHandler(roleBindingsColumnDefinitions, printRoleBinding)\n\t_ = h.TableHandler(roleBindingsColumnDefinitions, printRoleBindingList)\n\n\tclusterRoleBindingsColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Role\", Type: \"string\", Description: rbacv1beta1.ClusterRoleBinding{}.SwaggerDoc()[\"roleRef\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t\t{Name: \"Users\", Type: \"string\", Priority: 1, Description: \"Users in the clusterRoleBinding\"},\n\t\t{Name: \"Groups\", Type: \"string\", Priority: 1, Description: \"Groups in the clusterRoleBinding\"},\n\t\t{Name: \"ServiceAccounts\", Type: \"string\", Priority: 1, Description: \"ServiceAccounts in the clusterRoleBinding\"},\n\t}\n\t_ = h.TableHandler(clusterRoleBindingsColumnDefinitions, printClusterRoleBinding)\n\t_ = h.TableHandler(clusterRoleBindingsColumnDefinitions, printClusterRoleBindingList)\n\n\tcertificateSigningRequestColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t\t{Name: \"SignerName\", Type: \"string\", Description: certificatesv1beta1.CertificateSigningRequestSpec{}.SwaggerDoc()[\"signerName\"]},\n\t\t{Name: \"Requestor\", Type: \"string\", Description: certificatesv1beta1.CertificateSigningRequestSpec{}.SwaggerDoc()[\"request\"]},\n\t\t{Name: \"RequestedDuration\", Type: \"string\", Description: certificatesv1beta1.CertificateSigningRequestSpec{}.SwaggerDoc()[\"expirationSeconds\"]},\n\t\t{Name: \"Condition\", Type: \"string\", Description: certificatesv1beta1.CertificateSigningRequestStatus{}.SwaggerDoc()[\"conditions\"]},\n\t}\n\t_ = h.TableHandler(certificateSigningRequestColumnDefinitions, printCertificateSigningRequest)\n\t_ = h.TableHandler(certificateSigningRequestColumnDefinitions, printCertificateSigningRequestList)\n\n\tclusterTrustBundleColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"SignerName\", Type: \"string\", Description: certificatesv1alpha1.ClusterTrustBundleSpec{}.SwaggerDoc()[\"signerName\"]},\n\t}\n\th.TableHandler(clusterTrustBundleColumnDefinitions, printClusterTrustBundle)\n\th.TableHandler(clusterTrustBundleColumnDefinitions, printClusterTrustBundleList)\n\n\tleaseColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Holder\", Type: \"string\", Description: coordinationv1.LeaseSpec{}.SwaggerDoc()[\"holderIdentity\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(leaseColumnDefinitions, printLease)\n\t_ = h.TableHandler(leaseColumnDefinitions, printLeaseList)\n\n\tstorageClassColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Provisioner\", Type: \"string\", Description: storagev1.StorageClass{}.SwaggerDoc()[\"provisioner\"]},\n\t\t{Name: \"ReclaimPolicy\", Type: \"string\", Description: storagev1.StorageClass{}.SwaggerDoc()[\"reclaimPolicy\"]},\n\t\t{Name: \"VolumeBindingMode\", Type: \"string\", Description: storagev1.StorageClass{}.SwaggerDoc()[\"volumeBindingMode\"]},\n\t\t{Name: \"AllowVolumeExpansion\", Type: \"string\", Description: storagev1.StorageClass{}.SwaggerDoc()[\"allowVolumeExpansion\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\n\t_ = h.TableHandler(storageClassColumnDefinitions, printStorageClass)\n\t_ = h.TableHandler(storageClassColumnDefinitions, printStorageClassList)\n\n\tstatusColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Status\", Type: \"string\", Description: metav1.Status{}.SwaggerDoc()[\"status\"]},\n\t\t{Name: \"Reason\", Type: \"string\", Description: metav1.Status{}.SwaggerDoc()[\"reason\"]},\n\t\t{Name: \"Message\", Type: \"string\", Description: metav1.Status{}.SwaggerDoc()[\"Message\"]},\n\t}\n\n\t_ = h.TableHandler(statusColumnDefinitions, printStatus)\n\n\tcontrollerRevisionColumnDefinition := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Controller\", Type: \"string\", Description: \"Controller of the object\"},\n\t\t{Name: \"Revision\", Type: \"string\", Description: appsv1beta1.ControllerRevision{}.SwaggerDoc()[\"revision\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(controllerRevisionColumnDefinition, printControllerRevision)\n\t_ = h.TableHandler(controllerRevisionColumnDefinition, printControllerRevisionList)\n\n\tresourceQuotaColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t\t{Name: \"Request\", Type: \"string\", Description: \"Request represents a minimum amount of cpu/memory that a container may consume.\"},\n\t\t{Name: \"Limit\", Type: \"string\", Description: \"Limits control the maximum amount of cpu/memory that a container may use independent of contention on the node.\"},\n\t}\n\t_ = h.TableHandler(resourceQuotaColumnDefinitions, printResourceQuota)\n\t_ = h.TableHandler(resourceQuotaColumnDefinitions, printResourceQuotaList)\n\n\tpriorityClassColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Value\", Type: \"integer\", Description: schedulingv1.PriorityClass{}.SwaggerDoc()[\"value\"]},\n\t\t{Name: \"Global-Default\", Type: \"boolean\", Description: schedulingv1.PriorityClass{}.SwaggerDoc()[\"globalDefault\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(priorityClassColumnDefinitions, printPriorityClass)\n\t_ = h.TableHandler(priorityClassColumnDefinitions, printPriorityClassList)\n\n\truntimeClassColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Handler\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"handler\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(runtimeClassColumnDefinitions, printRuntimeClass)\n\t_ = h.TableHandler(runtimeClassColumnDefinitions, printRuntimeClassList)\n\n\tvolumeAttachmentColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Attacher\", Type: \"string\", Format: \"name\", Description: storagev1.VolumeAttachmentSpec{}.SwaggerDoc()[\"attacher\"]},\n\t\t{Name: \"PV\", Type: \"string\", Description: storagev1.VolumeAttachmentSource{}.SwaggerDoc()[\"persistentVolumeName\"]},\n\t\t{Name: \"Node\", Type: \"string\", Description: storagev1.VolumeAttachmentSpec{}.SwaggerDoc()[\"nodeName\"]},\n\t\t{Name: \"Attached\", Type: \"boolean\", Description: storagev1.VolumeAttachmentStatus{}.SwaggerDoc()[\"attached\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(volumeAttachmentColumnDefinitions, printVolumeAttachment)\n\t_ = h.TableHandler(volumeAttachmentColumnDefinitions, printVolumeAttachmentList)\n\n\tendpointSliceColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"AddressType\", Type: \"string\", Description: discoveryv1beta1.EndpointSlice{}.SwaggerDoc()[\"addressType\"]},\n\t\t{Name: \"Ports\", Type: \"string\", Description: discoveryv1beta1.EndpointSlice{}.SwaggerDoc()[\"ports\"]},\n\t\t{Name: \"Endpoints\", Type: \"string\", Description: discoveryv1beta1.EndpointSlice{}.SwaggerDoc()[\"endpoints\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(endpointSliceColumnDefinitions, printEndpointSlice)\n\t_ = h.TableHandler(endpointSliceColumnDefinitions, printEndpointSliceList)\n\n\tcsiNodeColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Drivers\", Type: \"integer\", Description: \"Drivers indicates the number of CSI drivers registered on the node\"},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(csiNodeColumnDefinitions, printCSINode)\n\t_ = h.TableHandler(csiNodeColumnDefinitions, printCSINodeList)\n\n\tcsiDriverColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"AttachRequired\", Type: \"boolean\", Description: storagev1.CSIDriverSpec{}.SwaggerDoc()[\"attachRequired\"]},\n\t\t{Name: \"PodInfoOnMount\", Type: \"boolean\", Description: storagev1.CSIDriverSpec{}.SwaggerDoc()[\"podInfoOnMount\"]},\n\t\t{Name: \"StorageCapacity\", Type: \"boolean\", Description: storagev1.CSIDriverSpec{}.SwaggerDoc()[\"storageCapacity\"]},\n\t}\n\tcsiDriverColumnDefinitions = append(csiDriverColumnDefinitions, []metav1.TableColumnDefinition{\n\t\t{Name: \"TokenRequests\", Type: \"string\", Description: storagev1.CSIDriverSpec{}.SwaggerDoc()[\"tokenRequests\"]},\n\t\t{Name: \"RequiresRepublish\", Type: \"boolean\", Description: storagev1.CSIDriverSpec{}.SwaggerDoc()[\"requiresRepublish\"]},\n\t}...)\n\n\tcsiDriverColumnDefinitions = append(csiDriverColumnDefinitions, []metav1.TableColumnDefinition{\n\t\t{Name: \"Modes\", Type: \"string\", Description: storagev1.CSIDriverSpec{}.SwaggerDoc()[\"volumeLifecycleModes\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}...)\n\t_ = h.TableHandler(csiDriverColumnDefinitions, printCSIDriver)\n\t_ = h.TableHandler(csiDriverColumnDefinitions, printCSIDriverList)\n\n\tcsiStorageCapacityColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"StorageClassName\", Type: \"string\", Description: storagev1.CSIStorageCapacity{}.SwaggerDoc()[\"storageClassName\"]},\n\t\t{Name: \"Capacity\", Type: \"string\", Description: storagev1.CSIStorageCapacity{}.SwaggerDoc()[\"capacity\"]},\n\t}\n\t_ = h.TableHandler(csiStorageCapacityColumnDefinitions, printCSIStorageCapacity)\n\t_ = h.TableHandler(csiStorageCapacityColumnDefinitions, printCSIStorageCapacityList)\n\n\tmutatingWebhookColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Webhooks\", Type: \"integer\", Description: \"Webhooks indicates the number of webhooks registered in this configuration\"},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(mutatingWebhookColumnDefinitions, printMutatingWebhook)\n\t_ = h.TableHandler(mutatingWebhookColumnDefinitions, printMutatingWebhookList)\n\n\tvalidatingWebhookColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Webhooks\", Type: \"integer\", Description: \"Webhooks indicates the number of webhooks registered in this configuration\"},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(validatingWebhookColumnDefinitions, printValidatingWebhook)\n\t_ = h.TableHandler(validatingWebhookColumnDefinitions, printValidatingWebhookList)\n\n\tvalidatingAdmissionPolicy := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Validations\", Type: \"integer\", Description: \"Validations indicates the number of validation rules defined in this configuration\"},\n\t\t{Name: \"ParamKind\", Type: \"string\", Description: \"ParamKind specifies the kind of resources used to parameterize this policy\"},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(validatingAdmissionPolicy, printValidatingAdmissionPolicy)\n\t_ = h.TableHandler(validatingAdmissionPolicy, printValidatingAdmissionPolicyList)\n\n\tvalidatingAdmissionPolicyBinding := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"PolicyName\", Type: \"string\", Description: \"PolicyName indicates the policy definition which the policy binding binded to\"},\n\t\t{Name: \"ParamRef\", Type: \"string\", Description: \"ParamRef indicates the param resource which sets the configration param\"},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(validatingAdmissionPolicyBinding, printValidatingAdmissionPolicyBinding)\n\t_ = h.TableHandler(validatingAdmissionPolicyBinding, printValidatingAdmissionPolicyBindingList)\n\n\tflowSchemaColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"PriorityLevel\", Type: \"string\", Description: flowcontrolv1beta3.PriorityLevelConfigurationReference{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"MatchingPrecedence\", Type: \"string\", Description: flowcontrolv1beta3.FlowSchemaSpec{}.SwaggerDoc()[\"matchingPrecedence\"]},\n\t\t{Name: \"DistinguisherMethod\", Type: \"string\", Description: flowcontrolv1beta3.FlowSchemaSpec{}.SwaggerDoc()[\"distinguisherMethod\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t\t{Name: \"MissingPL\", Type: \"string\", Description: \"references a broken or non-existent PriorityLevelConfiguration\"},\n\t}\n\t_ = h.TableHandler(flowSchemaColumnDefinitions, printFlowSchema)\n\t_ = h.TableHandler(flowSchemaColumnDefinitions, printFlowSchemaList)\n\n\tpriorityLevelColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Type\", Type: \"string\", Description: flowcontrolv1beta3.PriorityLevelConfigurationSpec{}.SwaggerDoc()[\"type\"]},\n\t\t{Name: \"NominalConcurrencyShares\", Type: \"string\", Description: flowcontrolv1beta3.LimitedPriorityLevelConfiguration{}.SwaggerDoc()[\"nominalConcurrencyShares\"]},\n\t\t{Name: \"Queues\", Type: \"string\", Description: flowcontrolv1beta3.QueuingConfiguration{}.SwaggerDoc()[\"queues\"]},\n\t\t{Name: \"HandSize\", Type: \"string\", Description: flowcontrolv1beta3.QueuingConfiguration{}.SwaggerDoc()[\"handSize\"]},\n\t\t{Name: \"QueueLengthLimit\", Type: \"string\", Description: flowcontrolv1beta3.QueuingConfiguration{}.SwaggerDoc()[\"queueLengthLimit\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(priorityLevelColumnDefinitions, printPriorityLevelConfiguration)\n\t_ = h.TableHandler(priorityLevelColumnDefinitions, printPriorityLevelConfigurationList)\n\n\tstorageVersionColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"CommonEncodingVersion\", Type: \"string\", Description: apiserverinternalv1alpha1.StorageVersionStatus{}.SwaggerDoc()[\"commonEncodingVersion\"]},\n\t\t{Name: \"StorageVersions\", Type: \"string\", Description: apiserverinternalv1alpha1.StorageVersionStatus{}.SwaggerDoc()[\"storageVersions\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(storageVersionColumnDefinitions, printStorageVersion)\n\t_ = h.TableHandler(storageVersionColumnDefinitions, printStorageVersionList)\n\n\tscaleColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"Desired\", Type: \"integer\", Description: autoscalingv1.ScaleSpec{}.SwaggerDoc()[\"replicas\"]},\n\t\t{Name: \"Available\", Type: \"integer\", Description: autoscalingv1.ScaleStatus{}.SwaggerDoc()[\"replicas\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(scaleColumnDefinitions, printScale)\n\n\tclusterCIDRColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"PerNodeHostBits\", Type: \"string\", Description: networkingv1alpha1.ClusterCIDRSpec{}.SwaggerDoc()[\"perNodeHostBits\"]},\n\t\t{Name: \"IPv4\", Type: \"string\", Description: networkingv1alpha1.ClusterCIDRSpec{}.SwaggerDoc()[\"ipv4\"]},\n\t\t{Name: \"IPv6\", Type: \"string\", Description: networkingv1alpha1.ClusterCIDRSpec{}.SwaggerDoc()[\"ipv6\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t\t{Name: \"NodeSelector\", Type: \"string\", Priority: 1, Description: networkingv1alpha1.ClusterCIDRSpec{}.SwaggerDoc()[\"nodeSelector\"]},\n\t}\n\n\t_ = h.TableHandler(clusterCIDRColumnDefinitions, printClusterCIDR)\n\t_ = h.TableHandler(clusterCIDRColumnDefinitions, printClusterCIDRList)\n\n\tresourceClassColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"DriverName\", Type: \"string\", Description: resourcev1alpha2.ResourceClass{}.SwaggerDoc()[\"driverName\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(resourceClassColumnDefinitions, printResourceClass)\n\t_ = h.TableHandler(resourceClassColumnDefinitions, printResourceClassList)\n\n\tresourceClaimColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"ResourceClassName\", Type: \"string\", Description: resourcev1alpha2.ResourceClaimSpec{}.SwaggerDoc()[\"resourceClassName\"]},\n\t\t{Name: \"AllocationMode\", Type: \"string\", Description: resourcev1alpha2.ResourceClaimSpec{}.SwaggerDoc()[\"allocationMode\"]},\n\t\t{Name: \"State\", Type: \"string\", Description: \"A summary of the current state (allocated, pending, reserved, etc.).\"},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(resourceClaimColumnDefinitions, printResourceClaim)\n\t_ = h.TableHandler(resourceClaimColumnDefinitions, printResourceClaimList)\n\n\tresourceClaimTemplateColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"ResourceClassName\", Type: \"string\", Description: resourcev1alpha2.ResourceClaimSpec{}.SwaggerDoc()[\"resourceClassName\"]},\n\t\t{Name: \"AllocationMode\", Type: \"string\", Description: resourcev1alpha2.ResourceClaimSpec{}.SwaggerDoc()[\"allocationMode\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(resourceClaimTemplateColumnDefinitions, printResourceClaimTemplate)\n\t_ = h.TableHandler(resourceClaimTemplateColumnDefinitions, printResourceClaimTemplateList)\n\n\tpodSchedulingCtxColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"SelectedNode\", Type: \"string\", Description: resourcev1alpha2.PodSchedulingContextSpec{}.SwaggerDoc()[\"selectedNode\"]},\n\t\t{Name: \"Age\", Type: \"string\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"creationTimestamp\"]},\n\t}\n\t_ = h.TableHandler(podSchedulingCtxColumnDefinitions, printPodSchedulingContext)\n\t_ = h.TableHandler(podSchedulingCtxColumnDefinitions, printPodSchedulingContextList)\n\n\tipAddressColumnDefinitions := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: metav1.ObjectMeta{}.SwaggerDoc()[\"name\"]},\n\t\t{Name: \"ParentRef\", Type: \"string\", Description: networkingv1alpha1.IPAddressSpec{}.SwaggerDoc()[\"parentRef\"]},\n\t}\n\n\th.TableHandler(ipAddressColumnDefinitions, printIPAddress)\n\th.TableHandler(ipAddressColumnDefinitions, printIPAddressList)\n}","line":{"from":88,"to":664}} {"id":100008155,"name":"formatEndpoints","signature":"func formatEndpoints(endpoints *api.Endpoints, ports sets.String) string","file":"pkg/printers/internalversion/printers.go","code":"// Pass ports=nil for all ports.\nfunc formatEndpoints(endpoints *api.Endpoints, ports sets.String) string {\n\tif len(endpoints.Subsets) == 0 {\n\t\treturn \"\u003cnone\u003e\"\n\t}\n\tlist := []string{}\n\tmax := 3\n\tmore := false\n\tcount := 0\n\tfor i := range endpoints.Subsets {\n\t\tss := \u0026endpoints.Subsets[i]\n\t\tif len(ss.Ports) == 0 {\n\t\t\t// It's possible to have headless services with no ports.\n\t\t\tcount += len(ss.Addresses)\n\t\t\tfor i := range ss.Addresses {\n\t\t\t\tif len(list) == max {\n\t\t\t\t\tmore = true\n\t\t\t\t\t// the next loop is redundant\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tlist = append(list, ss.Addresses[i].IP)\n\t\t\t}\n\t\t\t// avoid nesting code too deeply\n\t\t\tcontinue\n\t\t}\n\n\t\t// \"Normal\" services with ports defined.\n\t\tfor i := range ss.Ports {\n\t\t\tport := \u0026ss.Ports[i]\n\t\t\tif ports == nil || ports.Has(port.Name) {\n\t\t\t\tcount += len(ss.Addresses)\n\t\t\t\tfor i := range ss.Addresses {\n\t\t\t\t\tif len(list) == max {\n\t\t\t\t\t\tmore = true\n\t\t\t\t\t\t// the next loop is redundant\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\taddr := \u0026ss.Addresses[i]\n\t\t\t\t\thostPort := net.JoinHostPort(addr.IP, strconv.Itoa(int(port.Port)))\n\t\t\t\t\tlist = append(list, hostPort)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tret := strings.Join(list, \",\")\n\tif more {\n\t\treturn fmt.Sprintf(\"%s + %d more...\", ret, count-max)\n\t}\n\treturn ret\n}","line":{"from":666,"to":716}} {"id":100008156,"name":"formatDiscoveryPorts","signature":"func formatDiscoveryPorts(ports []discovery.EndpointPort) string","file":"pkg/printers/internalversion/printers.go","code":"func formatDiscoveryPorts(ports []discovery.EndpointPort) string {\n\tlist := []string{}\n\tmax := 3\n\tmore := false\n\tcount := 0\n\tfor _, port := range ports {\n\t\tif len(list) \u003c max {\n\t\t\tportNum := \"*\"\n\t\t\tif port.Port != nil {\n\t\t\t\tportNum = strconv.Itoa(int(*port.Port))\n\t\t\t} else if port.Name != nil {\n\t\t\t\tportNum = *port.Name\n\t\t\t}\n\t\t\tlist = append(list, portNum)\n\t\t} else if len(list) == max {\n\t\t\tmore = true\n\t\t}\n\t\tcount++\n\t}\n\treturn listWithMoreString(list, more, count, max)\n}","line":{"from":718,"to":738}} {"id":100008157,"name":"formatDiscoveryEndpoints","signature":"func formatDiscoveryEndpoints(endpoints []discovery.Endpoint) string","file":"pkg/printers/internalversion/printers.go","code":"func formatDiscoveryEndpoints(endpoints []discovery.Endpoint) string {\n\tlist := []string{}\n\tmax := 3\n\tmore := false\n\tcount := 0\n\tfor _, endpoint := range endpoints {\n\t\tfor _, address := range endpoint.Addresses {\n\t\t\tif len(list) \u003c max {\n\t\t\t\tlist = append(list, address)\n\t\t\t} else if len(list) == max {\n\t\t\t\tmore = true\n\t\t\t}\n\t\t\tcount++\n\t\t}\n\t}\n\treturn listWithMoreString(list, more, count, max)\n}","line":{"from":740,"to":756}} {"id":100008158,"name":"listWithMoreString","signature":"func listWithMoreString(list []string, more bool, count, max int) string","file":"pkg/printers/internalversion/printers.go","code":"func listWithMoreString(list []string, more bool, count, max int) string {\n\tret := strings.Join(list, \",\")\n\tif more {\n\t\treturn fmt.Sprintf(\"%s + %d more...\", ret, count-max)\n\t}\n\tif ret == \"\" {\n\t\tret = \"\u003cunset\u003e\"\n\t}\n\treturn ret\n}","line":{"from":758,"to":767}} {"id":100008159,"name":"translateMicroTimestampSince","signature":"func translateMicroTimestampSince(timestamp metav1.MicroTime) string","file":"pkg/printers/internalversion/printers.go","code":"// translateMicroTimestampSince returns the elapsed time since timestamp in\n// human-readable approximation.\nfunc translateMicroTimestampSince(timestamp metav1.MicroTime) string {\n\tif timestamp.IsZero() {\n\t\treturn \"\u003cunknown\u003e\"\n\t}\n\n\treturn duration.HumanDuration(time.Since(timestamp.Time))\n}","line":{"from":769,"to":777}} {"id":100008160,"name":"translateTimestampSince","signature":"func translateTimestampSince(timestamp metav1.Time) string","file":"pkg/printers/internalversion/printers.go","code":"// translateTimestampSince returns the elapsed time since timestamp in\n// human-readable approximation.\nfunc translateTimestampSince(timestamp metav1.Time) string {\n\tif timestamp.IsZero() {\n\t\treturn \"\u003cunknown\u003e\"\n\t}\n\n\treturn duration.HumanDuration(time.Since(timestamp.Time))\n}","line":{"from":779,"to":787}} {"id":100008161,"name":"translateTimestampUntil","signature":"func translateTimestampUntil(timestamp metav1.Time) string","file":"pkg/printers/internalversion/printers.go","code":"// translateTimestampUntil returns the elapsed time until timestamp in\n// human-readable approximation.\nfunc translateTimestampUntil(timestamp metav1.Time) string {\n\tif timestamp.IsZero() {\n\t\treturn \"\u003cunknown\u003e\"\n\t}\n\n\treturn duration.HumanDuration(time.Until(timestamp.Time))\n}","line":{"from":789,"to":797}} {"id":100008162,"name":"printPodList","signature":"func printPodList(podList *api.PodList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printPodList(podList *api.PodList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(podList.Items))\n\tfor i := range podList.Items {\n\t\tr, err := printPod(\u0026podList.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":804,"to":814}} {"id":100008163,"name":"printPod","signature":"func printPod(pod *api.Pod, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printPod(pod *api.Pod, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trestarts := 0\n\ttotalContainers := len(pod.Spec.Containers)\n\treadyContainers := 0\n\tlastRestartDate := metav1.NewTime(time.Time{})\n\n\treason := string(pod.Status.Phase)\n\tif pod.Status.Reason != \"\" {\n\t\treason = pod.Status.Reason\n\t}\n\n\t// If the Pod carries {type:PodScheduled, reason:WaitingForGates}, set reason to 'SchedulingGated'.\n\tfor _, condition := range pod.Status.Conditions {\n\t\tif condition.Type == api.PodScheduled \u0026\u0026 condition.Reason == api.PodReasonSchedulingGated {\n\t\t\treason = api.PodReasonSchedulingGated\n\t\t}\n\t}\n\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: pod},\n\t}\n\n\tswitch pod.Status.Phase {\n\tcase api.PodSucceeded:\n\t\trow.Conditions = podSuccessConditions\n\tcase api.PodFailed:\n\t\trow.Conditions = podFailedConditions\n\t}\n\n\tinitializing := false\n\tfor i := range pod.Status.InitContainerStatuses {\n\t\tcontainer := pod.Status.InitContainerStatuses[i]\n\t\trestarts += int(container.RestartCount)\n\t\tif container.LastTerminationState.Terminated != nil {\n\t\t\tterminatedDate := container.LastTerminationState.Terminated.FinishedAt\n\t\t\tif lastRestartDate.Before(\u0026terminatedDate) {\n\t\t\t\tlastRestartDate = terminatedDate\n\t\t\t}\n\t\t}\n\t\tswitch {\n\t\tcase container.State.Terminated != nil \u0026\u0026 container.State.Terminated.ExitCode == 0:\n\t\t\tcontinue\n\t\tcase container.State.Terminated != nil:\n\t\t\t// initialization is failed\n\t\t\tif len(container.State.Terminated.Reason) == 0 {\n\t\t\t\tif container.State.Terminated.Signal != 0 {\n\t\t\t\t\treason = fmt.Sprintf(\"Init:Signal:%d\", container.State.Terminated.Signal)\n\t\t\t\t} else {\n\t\t\t\t\treason = fmt.Sprintf(\"Init:ExitCode:%d\", container.State.Terminated.ExitCode)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treason = \"Init:\" + container.State.Terminated.Reason\n\t\t\t}\n\t\t\tinitializing = true\n\t\tcase container.State.Waiting != nil \u0026\u0026 len(container.State.Waiting.Reason) \u003e 0 \u0026\u0026 container.State.Waiting.Reason != \"PodInitializing\":\n\t\t\treason = \"Init:\" + container.State.Waiting.Reason\n\t\t\tinitializing = true\n\t\tdefault:\n\t\t\treason = fmt.Sprintf(\"Init:%d/%d\", i, len(pod.Spec.InitContainers))\n\t\t\tinitializing = true\n\t\t}\n\t\tbreak\n\t}\n\tif !initializing {\n\t\trestarts = 0\n\t\thasRunning := false\n\t\tfor i := len(pod.Status.ContainerStatuses) - 1; i \u003e= 0; i-- {\n\t\t\tcontainer := pod.Status.ContainerStatuses[i]\n\n\t\t\trestarts += int(container.RestartCount)\n\t\t\tif container.LastTerminationState.Terminated != nil {\n\t\t\t\tterminatedDate := container.LastTerminationState.Terminated.FinishedAt\n\t\t\t\tif lastRestartDate.Before(\u0026terminatedDate) {\n\t\t\t\t\tlastRestartDate = terminatedDate\n\t\t\t\t}\n\t\t\t}\n\t\t\tif container.State.Waiting != nil \u0026\u0026 container.State.Waiting.Reason != \"\" {\n\t\t\t\treason = container.State.Waiting.Reason\n\t\t\t} else if container.State.Terminated != nil \u0026\u0026 container.State.Terminated.Reason != \"\" {\n\t\t\t\treason = container.State.Terminated.Reason\n\t\t\t} else if container.State.Terminated != nil \u0026\u0026 container.State.Terminated.Reason == \"\" {\n\t\t\t\tif container.State.Terminated.Signal != 0 {\n\t\t\t\t\treason = fmt.Sprintf(\"Signal:%d\", container.State.Terminated.Signal)\n\t\t\t\t} else {\n\t\t\t\t\treason = fmt.Sprintf(\"ExitCode:%d\", container.State.Terminated.ExitCode)\n\t\t\t\t}\n\t\t\t} else if container.Ready \u0026\u0026 container.State.Running != nil {\n\t\t\t\thasRunning = true\n\t\t\t\treadyContainers++\n\t\t\t}\n\t\t}\n\n\t\t// change pod status back to \"Running\" if there is at least one container still reporting as \"Running\" status\n\t\tif reason == \"Completed\" \u0026\u0026 hasRunning {\n\t\t\tif hasPodReadyCondition(pod.Status.Conditions) {\n\t\t\t\treason = \"Running\"\n\t\t\t} else {\n\t\t\t\treason = \"NotReady\"\n\t\t\t}\n\t\t}\n\t}\n\n\tif pod.DeletionTimestamp != nil \u0026\u0026 pod.Status.Reason == node.NodeUnreachablePodReason {\n\t\treason = \"Unknown\"\n\t} else if pod.DeletionTimestamp != nil {\n\t\treason = \"Terminating\"\n\t}\n\n\trestartsStr := strconv.Itoa(restarts)\n\tif !lastRestartDate.IsZero() {\n\t\trestartsStr = fmt.Sprintf(\"%d (%s ago)\", restarts, translateTimestampSince(lastRestartDate))\n\t}\n\n\trow.Cells = append(row.Cells, pod.Name, fmt.Sprintf(\"%d/%d\", readyContainers, totalContainers), reason, restartsStr, translateTimestampSince(pod.CreationTimestamp))\n\tif options.Wide {\n\t\tnodeName := pod.Spec.NodeName\n\t\tnominatedNodeName := pod.Status.NominatedNodeName\n\t\tpodIP := \"\"\n\t\tif len(pod.Status.PodIPs) \u003e 0 {\n\t\t\tpodIP = pod.Status.PodIPs[0].IP\n\t\t}\n\n\t\tif podIP == \"\" {\n\t\t\tpodIP = \"\u003cnone\u003e\"\n\t\t}\n\t\tif nodeName == \"\" {\n\t\t\tnodeName = \"\u003cnone\u003e\"\n\t\t}\n\t\tif nominatedNodeName == \"\" {\n\t\t\tnominatedNodeName = \"\u003cnone\u003e\"\n\t\t}\n\n\t\treadinessGates := \"\u003cnone\u003e\"\n\t\tif len(pod.Spec.ReadinessGates) \u003e 0 {\n\t\t\ttrueConditions := 0\n\t\t\tfor _, readinessGate := range pod.Spec.ReadinessGates {\n\t\t\t\tconditionType := readinessGate.ConditionType\n\t\t\t\tfor _, condition := range pod.Status.Conditions {\n\t\t\t\t\tif condition.Type == conditionType {\n\t\t\t\t\t\tif condition.Status == api.ConditionTrue {\n\t\t\t\t\t\t\ttrueConditions++\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treadinessGates = fmt.Sprintf(\"%d/%d\", trueConditions, len(pod.Spec.ReadinessGates))\n\t\t}\n\t\trow.Cells = append(row.Cells, podIP, nodeName, nominatedNodeName, readinessGates)\n\t}\n\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":816,"to":968}} {"id":100008164,"name":"hasPodReadyCondition","signature":"func hasPodReadyCondition(conditions []api.PodCondition) bool","file":"pkg/printers/internalversion/printers.go","code":"func hasPodReadyCondition(conditions []api.PodCondition) bool {\n\tfor _, condition := range conditions {\n\t\tif condition.Type == api.PodReady \u0026\u0026 condition.Status == api.ConditionTrue {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":970,"to":977}} {"id":100008165,"name":"printPodTemplate","signature":"func printPodTemplate(obj *api.PodTemplate, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printPodTemplate(obj *api.PodTemplate, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\tnames, images := layoutContainerCells(obj.Template.Spec.Containers)\n\trow.Cells = append(row.Cells, obj.Name, names, images, labels.FormatLabels(obj.Template.Labels))\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":979,"to":986}} {"id":100008166,"name":"printPodTemplateList","signature":"func printPodTemplateList(list *api.PodTemplateList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printPodTemplateList(list *api.PodTemplateList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printPodTemplate(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":988,"to":998}} {"id":100008167,"name":"printPodDisruptionBudget","signature":"func printPodDisruptionBudget(obj *policy.PodDisruptionBudget, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printPodDisruptionBudget(obj *policy.PodDisruptionBudget, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\n\tvar minAvailable string\n\tvar maxUnavailable string\n\tif obj.Spec.MinAvailable != nil {\n\t\tminAvailable = obj.Spec.MinAvailable.String()\n\t} else {\n\t\tminAvailable = \"N/A\"\n\t}\n\n\tif obj.Spec.MaxUnavailable != nil {\n\t\tmaxUnavailable = obj.Spec.MaxUnavailable.String()\n\t} else {\n\t\tmaxUnavailable = \"N/A\"\n\t}\n\n\trow.Cells = append(row.Cells, obj.Name, minAvailable, maxUnavailable, int64(obj.Status.DisruptionsAllowed), translateTimestampSince(obj.CreationTimestamp))\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1000,"to":1021}} {"id":100008168,"name":"printPodDisruptionBudgetList","signature":"func printPodDisruptionBudgetList(list *policy.PodDisruptionBudgetList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printPodDisruptionBudgetList(list *policy.PodDisruptionBudgetList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printPodDisruptionBudget(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":1023,"to":1033}} {"id":100008169,"name":"printReplicationController","signature":"func printReplicationController(obj *api.ReplicationController, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"// TODO(AdoHe): try to put wide output in a single method\nfunc printReplicationController(obj *api.ReplicationController, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\n\tdesiredReplicas := obj.Spec.Replicas\n\tcurrentReplicas := obj.Status.Replicas\n\treadyReplicas := obj.Status.ReadyReplicas\n\n\trow.Cells = append(row.Cells, obj.Name, int64(desiredReplicas), int64(currentReplicas), int64(readyReplicas), translateTimestampSince(obj.CreationTimestamp))\n\tif options.Wide {\n\t\tnames, images := layoutContainerCells(obj.Spec.Template.Spec.Containers)\n\t\trow.Cells = append(row.Cells, names, images, labels.FormatLabels(obj.Spec.Selector))\n\t}\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1035,"to":1051}} {"id":100008170,"name":"printReplicationControllerList","signature":"func printReplicationControllerList(list *api.ReplicationControllerList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printReplicationControllerList(list *api.ReplicationControllerList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printReplicationController(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":1053,"to":1063}} {"id":100008171,"name":"printReplicaSet","signature":"func printReplicaSet(obj *apps.ReplicaSet, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printReplicaSet(obj *apps.ReplicaSet, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\n\tdesiredReplicas := obj.Spec.Replicas\n\tcurrentReplicas := obj.Status.Replicas\n\treadyReplicas := obj.Status.ReadyReplicas\n\n\trow.Cells = append(row.Cells, obj.Name, int64(desiredReplicas), int64(currentReplicas), int64(readyReplicas), translateTimestampSince(obj.CreationTimestamp))\n\tif options.Wide {\n\t\tnames, images := layoutContainerCells(obj.Spec.Template.Spec.Containers)\n\t\trow.Cells = append(row.Cells, names, images, metav1.FormatLabelSelector(obj.Spec.Selector))\n\t}\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1065,"to":1080}} {"id":100008172,"name":"printReplicaSetList","signature":"func printReplicaSetList(list *apps.ReplicaSetList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printReplicaSetList(list *apps.ReplicaSetList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printReplicaSet(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":1082,"to":1092}} {"id":100008173,"name":"printJob","signature":"func printJob(obj *batch.Job, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printJob(obj *batch.Job, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\n\tvar completions string\n\tif obj.Spec.Completions != nil {\n\t\tcompletions = fmt.Sprintf(\"%d/%d\", obj.Status.Succeeded, *obj.Spec.Completions)\n\t} else {\n\t\tparallelism := int32(0)\n\t\tif obj.Spec.Parallelism != nil {\n\t\t\tparallelism = *obj.Spec.Parallelism\n\t\t}\n\t\tif parallelism \u003e 1 {\n\t\t\tcompletions = fmt.Sprintf(\"%d/1 of %d\", obj.Status.Succeeded, parallelism)\n\t\t} else {\n\t\t\tcompletions = fmt.Sprintf(\"%d/1\", obj.Status.Succeeded)\n\t\t}\n\t}\n\tvar jobDuration string\n\tswitch {\n\tcase obj.Status.StartTime == nil:\n\tcase obj.Status.CompletionTime == nil:\n\t\tjobDuration = duration.HumanDuration(time.Since(obj.Status.StartTime.Time))\n\tdefault:\n\t\tjobDuration = duration.HumanDuration(obj.Status.CompletionTime.Sub(obj.Status.StartTime.Time))\n\t}\n\n\trow.Cells = append(row.Cells, obj.Name, completions, jobDuration, translateTimestampSince(obj.CreationTimestamp))\n\tif options.Wide {\n\t\tnames, images := layoutContainerCells(obj.Spec.Template.Spec.Containers)\n\t\trow.Cells = append(row.Cells, names, images, metav1.FormatLabelSelector(obj.Spec.Selector))\n\t}\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1094,"to":1128}} {"id":100008174,"name":"printJobList","signature":"func printJobList(list *batch.JobList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printJobList(list *batch.JobList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printJob(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":1130,"to":1140}} {"id":100008175,"name":"printCronJob","signature":"func printCronJob(obj *batch.CronJob, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printCronJob(obj *batch.CronJob, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\n\tlastScheduleTime := \"\u003cnone\u003e\"\n\tif obj.Status.LastScheduleTime != nil {\n\t\tlastScheduleTime = translateTimestampSince(*obj.Status.LastScheduleTime)\n\t}\n\n\trow.Cells = append(row.Cells, obj.Name, obj.Spec.Schedule, printBoolPtr(obj.Spec.Suspend), int64(len(obj.Status.Active)), lastScheduleTime, translateTimestampSince(obj.CreationTimestamp))\n\tif options.Wide {\n\t\tnames, images := layoutContainerCells(obj.Spec.JobTemplate.Spec.Template.Spec.Containers)\n\t\trow.Cells = append(row.Cells, names, images, metav1.FormatLabelSelector(obj.Spec.JobTemplate.Spec.Selector))\n\t}\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1142,"to":1158}} {"id":100008176,"name":"printCronJobList","signature":"func printCronJobList(list *batch.CronJobList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printCronJobList(list *batch.CronJobList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printCronJob(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":1160,"to":1170}} {"id":100008177,"name":"loadBalancerStatusStringer","signature":"func loadBalancerStatusStringer(s api.LoadBalancerStatus, wide bool) string","file":"pkg/printers/internalversion/printers.go","code":"// loadBalancerStatusStringer behaves mostly like a string interface and converts the given status to a string.\n// `wide` indicates whether the returned value is meant for --o=wide output. If not, it's clipped to 16 bytes.\nfunc loadBalancerStatusStringer(s api.LoadBalancerStatus, wide bool) string {\n\tingress := s.Ingress\n\tresult := sets.NewString()\n\tfor i := range ingress {\n\t\tif ingress[i].IP != \"\" {\n\t\t\tresult.Insert(ingress[i].IP)\n\t\t} else if ingress[i].Hostname != \"\" {\n\t\t\tresult.Insert(ingress[i].Hostname)\n\t\t}\n\t}\n\n\tr := strings.Join(result.List(), \",\")\n\tif !wide \u0026\u0026 len(r) \u003e loadBalancerWidth {\n\t\tr = r[0:(loadBalancerWidth-3)] + \"...\"\n\t}\n\treturn r\n}","line":{"from":1172,"to":1190}} {"id":100008178,"name":"getServiceExternalIP","signature":"func getServiceExternalIP(svc *api.Service, wide bool) string","file":"pkg/printers/internalversion/printers.go","code":"func getServiceExternalIP(svc *api.Service, wide bool) string {\n\tswitch svc.Spec.Type {\n\tcase api.ServiceTypeClusterIP:\n\t\tif len(svc.Spec.ExternalIPs) \u003e 0 {\n\t\t\treturn strings.Join(svc.Spec.ExternalIPs, \",\")\n\t\t}\n\t\treturn \"\u003cnone\u003e\"\n\tcase api.ServiceTypeNodePort:\n\t\tif len(svc.Spec.ExternalIPs) \u003e 0 {\n\t\t\treturn strings.Join(svc.Spec.ExternalIPs, \",\")\n\t\t}\n\t\treturn \"\u003cnone\u003e\"\n\tcase api.ServiceTypeLoadBalancer:\n\t\tlbIps := loadBalancerStatusStringer(svc.Status.LoadBalancer, wide)\n\t\tif len(svc.Spec.ExternalIPs) \u003e 0 {\n\t\t\tresults := []string{}\n\t\t\tif len(lbIps) \u003e 0 {\n\t\t\t\tresults = append(results, strings.Split(lbIps, \",\")...)\n\t\t\t}\n\t\t\tresults = append(results, svc.Spec.ExternalIPs...)\n\t\t\treturn strings.Join(results, \",\")\n\t\t}\n\t\tif len(lbIps) \u003e 0 {\n\t\t\treturn lbIps\n\t\t}\n\t\treturn \"\u003cpending\u003e\"\n\tcase api.ServiceTypeExternalName:\n\t\treturn svc.Spec.ExternalName\n\t}\n\treturn \"\u003cunknown\u003e\"\n}","line":{"from":1192,"to":1222}} {"id":100008179,"name":"makePortString","signature":"func makePortString(ports []api.ServicePort) string","file":"pkg/printers/internalversion/printers.go","code":"func makePortString(ports []api.ServicePort) string {\n\tpieces := make([]string, len(ports))\n\tfor ix := range ports {\n\t\tport := \u0026ports[ix]\n\t\tpieces[ix] = fmt.Sprintf(\"%d/%s\", port.Port, port.Protocol)\n\t\tif port.NodePort \u003e 0 {\n\t\t\tpieces[ix] = fmt.Sprintf(\"%d:%d/%s\", port.Port, port.NodePort, port.Protocol)\n\t\t}\n\t}\n\treturn strings.Join(pieces, \",\")\n}","line":{"from":1224,"to":1234}} {"id":100008180,"name":"printService","signature":"func printService(obj *api.Service, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printService(obj *api.Service, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\tsvcType := obj.Spec.Type\n\tinternalIP := \"\u003cnone\u003e\"\n\tif len(obj.Spec.ClusterIPs) \u003e 0 {\n\t\tinternalIP = obj.Spec.ClusterIPs[0]\n\t}\n\n\texternalIP := getServiceExternalIP(obj, options.Wide)\n\tsvcPorts := makePortString(obj.Spec.Ports)\n\tif len(svcPorts) == 0 {\n\t\tsvcPorts = \"\u003cnone\u003e\"\n\t}\n\n\trow.Cells = append(row.Cells, obj.Name, string(svcType), internalIP, externalIP, svcPorts, translateTimestampSince(obj.CreationTimestamp))\n\tif options.Wide {\n\t\trow.Cells = append(row.Cells, labels.FormatLabels(obj.Spec.Selector))\n\t}\n\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1236,"to":1258}} {"id":100008181,"name":"printServiceList","signature":"func printServiceList(list *api.ServiceList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printServiceList(list *api.ServiceList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printService(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":1260,"to":1270}} {"id":100008182,"name":"formatHosts","signature":"func formatHosts(rules []networking.IngressRule) string","file":"pkg/printers/internalversion/printers.go","code":"func formatHosts(rules []networking.IngressRule) string {\n\tlist := []string{}\n\tmax := 3\n\tmore := false\n\tfor _, rule := range rules {\n\t\tif len(list) == max {\n\t\t\tmore = true\n\t\t}\n\t\tif !more \u0026\u0026 len(rule.Host) != 0 {\n\t\t\tlist = append(list, rule.Host)\n\t\t}\n\t}\n\tif len(list) == 0 {\n\t\treturn \"*\"\n\t}\n\tret := strings.Join(list, \",\")\n\tif more {\n\t\treturn fmt.Sprintf(\"%s + %d more...\", ret, len(rules)-max)\n\t}\n\treturn ret\n}","line":{"from":1272,"to":1292}} {"id":100008183,"name":"formatPorts","signature":"func formatPorts(tls []networking.IngressTLS) string","file":"pkg/printers/internalversion/printers.go","code":"func formatPorts(tls []networking.IngressTLS) string {\n\tif len(tls) != 0 {\n\t\treturn \"80, 443\"\n\t}\n\treturn \"80\"\n}","line":{"from":1294,"to":1299}} {"id":100008184,"name":"printIngress","signature":"func printIngress(obj *networking.Ingress, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printIngress(obj *networking.Ingress, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\tclassName := \"\u003cnone\u003e\"\n\tif obj.Spec.IngressClassName != nil {\n\t\tclassName = *obj.Spec.IngressClassName\n\t}\n\thosts := formatHosts(obj.Spec.Rules)\n\taddress := ingressLoadBalancerStatusStringer(obj.Status.LoadBalancer, options.Wide)\n\tports := formatPorts(obj.Spec.TLS)\n\tcreateTime := translateTimestampSince(obj.CreationTimestamp)\n\trow.Cells = append(row.Cells, obj.Name, className, hosts, address, ports, createTime)\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1301,"to":1315}} {"id":100008185,"name":"ingressLoadBalancerStatusStringer","signature":"func ingressLoadBalancerStatusStringer(s networking.IngressLoadBalancerStatus, wide bool) string","file":"pkg/printers/internalversion/printers.go","code":"// ingressLoadBalancerStatusStringer behaves mostly like a string interface and converts the given status to a string.\n// `wide` indicates whether the returned value is meant for --o=wide output. If not, it's clipped to 16 bytes.\nfunc ingressLoadBalancerStatusStringer(s networking.IngressLoadBalancerStatus, wide bool) string {\n\tingress := s.Ingress\n\tresult := sets.NewString()\n\tfor i := range ingress {\n\t\tif ingress[i].IP != \"\" {\n\t\t\tresult.Insert(ingress[i].IP)\n\t\t} else if ingress[i].Hostname != \"\" {\n\t\t\tresult.Insert(ingress[i].Hostname)\n\t\t}\n\t}\n\n\tr := strings.Join(result.List(), \",\")\n\tif !wide \u0026\u0026 len(r) \u003e loadBalancerWidth {\n\t\tr = r[0:(loadBalancerWidth-3)] + \"...\"\n\t}\n\treturn r\n}","line":{"from":1317,"to":1335}} {"id":100008186,"name":"printIngressList","signature":"func printIngressList(list *networking.IngressList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printIngressList(list *networking.IngressList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printIngress(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":1337,"to":1347}} {"id":100008187,"name":"printIngressClass","signature":"func printIngressClass(obj *networking.IngressClass, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printIngressClass(obj *networking.IngressClass, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\tparameters := \"\u003cnone\u003e\"\n\tif obj.Spec.Parameters != nil {\n\t\tparameters = obj.Spec.Parameters.Kind\n\t\tif obj.Spec.Parameters.APIGroup != nil {\n\t\t\tparameters = parameters + \".\" + *obj.Spec.Parameters.APIGroup\n\t\t}\n\t\tparameters = parameters + \"/\" + obj.Spec.Parameters.Name\n\t}\n\tcreateTime := translateTimestampSince(obj.CreationTimestamp)\n\trow.Cells = append(row.Cells, obj.Name, obj.Spec.Controller, parameters, createTime)\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1349,"to":1364}} {"id":100008188,"name":"printIngressClassList","signature":"func printIngressClassList(list *networking.IngressClassList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printIngressClassList(list *networking.IngressClassList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printIngressClass(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":1366,"to":1376}} {"id":100008189,"name":"printStatefulSet","signature":"func printStatefulSet(obj *apps.StatefulSet, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printStatefulSet(obj *apps.StatefulSet, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\tdesiredReplicas := obj.Spec.Replicas\n\treadyReplicas := obj.Status.ReadyReplicas\n\tcreateTime := translateTimestampSince(obj.CreationTimestamp)\n\trow.Cells = append(row.Cells, obj.Name, fmt.Sprintf(\"%d/%d\", int64(readyReplicas), int64(desiredReplicas)), createTime)\n\tif options.Wide {\n\t\tnames, images := layoutContainerCells(obj.Spec.Template.Spec.Containers)\n\t\trow.Cells = append(row.Cells, names, images)\n\t}\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1378,"to":1391}} {"id":100008190,"name":"printStatefulSetList","signature":"func printStatefulSetList(list *apps.StatefulSetList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printStatefulSetList(list *apps.StatefulSetList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printStatefulSet(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":1393,"to":1403}} {"id":100008191,"name":"printDaemonSet","signature":"func printDaemonSet(obj *apps.DaemonSet, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printDaemonSet(obj *apps.DaemonSet, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\n\tdesiredScheduled := obj.Status.DesiredNumberScheduled\n\tcurrentScheduled := obj.Status.CurrentNumberScheduled\n\tnumberReady := obj.Status.NumberReady\n\tnumberUpdated := obj.Status.UpdatedNumberScheduled\n\tnumberAvailable := obj.Status.NumberAvailable\n\n\trow.Cells = append(row.Cells, obj.Name, int64(desiredScheduled), int64(currentScheduled), int64(numberReady), int64(numberUpdated), int64(numberAvailable), labels.FormatLabels(obj.Spec.Template.Spec.NodeSelector), translateTimestampSince(obj.CreationTimestamp))\n\tif options.Wide {\n\t\tnames, images := layoutContainerCells(obj.Spec.Template.Spec.Containers)\n\t\trow.Cells = append(row.Cells, names, images, metav1.FormatLabelSelector(obj.Spec.Selector))\n\t}\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1405,"to":1422}} {"id":100008192,"name":"printDaemonSetList","signature":"func printDaemonSetList(list *apps.DaemonSetList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printDaemonSetList(list *apps.DaemonSetList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printDaemonSet(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":1424,"to":1434}} {"id":100008193,"name":"printEndpoints","signature":"func printEndpoints(obj *api.Endpoints, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printEndpoints(obj *api.Endpoints, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\trow.Cells = append(row.Cells, obj.Name, formatEndpoints(obj, nil), translateTimestampSince(obj.CreationTimestamp))\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1436,"to":1442}} {"id":100008194,"name":"printEndpointsList","signature":"func printEndpointsList(list *api.EndpointsList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printEndpointsList(list *api.EndpointsList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printEndpoints(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":1444,"to":1454}} {"id":100008195,"name":"printEndpointSlice","signature":"func printEndpointSlice(obj *discovery.EndpointSlice, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printEndpointSlice(obj *discovery.EndpointSlice, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\trow.Cells = append(row.Cells, obj.Name, string(obj.AddressType), formatDiscoveryPorts(obj.Ports), formatDiscoveryEndpoints(obj.Endpoints), translateTimestampSince(obj.CreationTimestamp))\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1456,"to":1462}} {"id":100008196,"name":"printEndpointSliceList","signature":"func printEndpointSliceList(list *discovery.EndpointSliceList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printEndpointSliceList(list *discovery.EndpointSliceList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printEndpointSlice(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":1464,"to":1474}} {"id":100008197,"name":"printCSINode","signature":"func printCSINode(obj *storage.CSINode, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printCSINode(obj *storage.CSINode, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\trow.Cells = append(row.Cells, obj.Name, int64(len(obj.Spec.Drivers)), translateTimestampSince(obj.CreationTimestamp))\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1476,"to":1482}} {"id":100008198,"name":"printCSINodeList","signature":"func printCSINodeList(list *storage.CSINodeList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printCSINodeList(list *storage.CSINodeList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printCSINode(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":1484,"to":1494}} {"id":100008199,"name":"printCSIDriver","signature":"func printCSIDriver(obj *storage.CSIDriver, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printCSIDriver(obj *storage.CSIDriver, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\tattachRequired := true\n\tif obj.Spec.AttachRequired != nil {\n\t\tattachRequired = *obj.Spec.AttachRequired\n\t}\n\tpodInfoOnMount := false\n\tif obj.Spec.PodInfoOnMount != nil {\n\t\tpodInfoOnMount = *obj.Spec.PodInfoOnMount\n\t}\n\tallModes := []string{}\n\tfor _, mode := range obj.Spec.VolumeLifecycleModes {\n\t\tallModes = append(allModes, string(mode))\n\t}\n\tmodes := strings.Join(allModes, \",\")\n\tif len(modes) == 0 {\n\t\tmodes = \"\u003cnone\u003e\"\n\t}\n\n\trow.Cells = append(row.Cells, obj.Name, attachRequired, podInfoOnMount)\n\tstorageCapacity := false\n\tif obj.Spec.StorageCapacity != nil {\n\t\tstorageCapacity = *obj.Spec.StorageCapacity\n\t}\n\trow.Cells = append(row.Cells, storageCapacity)\n\n\ttokenRequests := \"\u003cunset\u003e\"\n\tif obj.Spec.TokenRequests != nil {\n\t\taudiences := []string{}\n\t\tfor _, t := range obj.Spec.TokenRequests {\n\t\t\taudiences = append(audiences, t.Audience)\n\t\t}\n\t\ttokenRequests = strings.Join(audiences, \",\")\n\t}\n\trequiresRepublish := false\n\tif obj.Spec.RequiresRepublish != nil {\n\t\trequiresRepublish = *obj.Spec.RequiresRepublish\n\t}\n\trow.Cells = append(row.Cells, tokenRequests, requiresRepublish)\n\n\trow.Cells = append(row.Cells, modes, translateTimestampSince(obj.CreationTimestamp))\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1496,"to":1540}} {"id":100008200,"name":"printCSIDriverList","signature":"func printCSIDriverList(list *storage.CSIDriverList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printCSIDriverList(list *storage.CSIDriverList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printCSIDriver(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":1542,"to":1552}} {"id":100008201,"name":"printCSIStorageCapacity","signature":"func printCSIStorageCapacity(obj *storage.CSIStorageCapacity, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printCSIStorageCapacity(obj *storage.CSIStorageCapacity, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\n\tcapacity := \"\u003cunset\u003e\"\n\tif obj.Capacity != nil {\n\t\tcapacity = obj.Capacity.String()\n\t}\n\n\trow.Cells = append(row.Cells, obj.Name, obj.StorageClassName, capacity)\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1554,"to":1566}} {"id":100008202,"name":"printCSIStorageCapacityList","signature":"func printCSIStorageCapacityList(list *storage.CSIStorageCapacityList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printCSIStorageCapacityList(list *storage.CSIStorageCapacityList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printCSIStorageCapacity(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":1568,"to":1578}} {"id":100008203,"name":"printMutatingWebhook","signature":"func printMutatingWebhook(obj *admissionregistration.MutatingWebhookConfiguration, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printMutatingWebhook(obj *admissionregistration.MutatingWebhookConfiguration, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\trow.Cells = append(row.Cells, obj.Name, int64(len(obj.Webhooks)), translateTimestampSince(obj.CreationTimestamp))\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1580,"to":1586}} {"id":100008204,"name":"printMutatingWebhookList","signature":"func printMutatingWebhookList(list *admissionregistration.MutatingWebhookConfigurationList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printMutatingWebhookList(list *admissionregistration.MutatingWebhookConfigurationList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printMutatingWebhook(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":1588,"to":1598}} {"id":100008205,"name":"printValidatingWebhook","signature":"func printValidatingWebhook(obj *admissionregistration.ValidatingWebhookConfiguration, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printValidatingWebhook(obj *admissionregistration.ValidatingWebhookConfiguration, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\trow.Cells = append(row.Cells, obj.Name, int64(len(obj.Webhooks)), translateTimestampSince(obj.CreationTimestamp))\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1600,"to":1606}} {"id":100008206,"name":"printValidatingWebhookList","signature":"func printValidatingWebhookList(list *admissionregistration.ValidatingWebhookConfigurationList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printValidatingWebhookList(list *admissionregistration.ValidatingWebhookConfigurationList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printValidatingWebhook(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":1608,"to":1618}} {"id":100008207,"name":"printValidatingAdmissionPolicy","signature":"func printValidatingAdmissionPolicy(obj *admissionregistration.ValidatingAdmissionPolicy, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printValidatingAdmissionPolicy(obj *admissionregistration.ValidatingAdmissionPolicy, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\tparamKind := \"\u003cunset\u003e\"\n\tif obj.Spec.ParamKind != nil {\n\t\tparamKind = obj.Spec.ParamKind.APIVersion + \"/\" + obj.Spec.ParamKind.Kind\n\t}\n\trow.Cells = append(row.Cells, obj.Name, int64(len(obj.Spec.Validations)), paramKind, translateTimestampSince(obj.CreationTimestamp))\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1620,"to":1630}} {"id":100008208,"name":"printValidatingAdmissionPolicyList","signature":"func printValidatingAdmissionPolicyList(list *admissionregistration.ValidatingAdmissionPolicyList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printValidatingAdmissionPolicyList(list *admissionregistration.ValidatingAdmissionPolicyList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printValidatingAdmissionPolicy(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":1632,"to":1642}} {"id":100008209,"name":"printValidatingAdmissionPolicyBinding","signature":"func printValidatingAdmissionPolicyBinding(obj *admissionregistration.ValidatingAdmissionPolicyBinding, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printValidatingAdmissionPolicyBinding(obj *admissionregistration.ValidatingAdmissionPolicyBinding, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\tparamName := \"\u003cunset\u003e\"\n\tif obj.Spec.ParamRef != nil {\n\t\tif obj.Spec.ParamRef.Namespace != \"\" {\n\t\t\tparamName = obj.Spec.ParamRef.Namespace + \"/\" + obj.Spec.ParamRef.Name\n\t\t} else {\n\t\t\tparamName = obj.Spec.ParamRef.Name\n\t\t}\n\n\t}\n\trow.Cells = append(row.Cells, obj.Name, obj.Spec.PolicyName, paramName, translateTimestampSince(obj.CreationTimestamp))\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1644,"to":1659}} {"id":100008210,"name":"printValidatingAdmissionPolicyBindingList","signature":"func printValidatingAdmissionPolicyBindingList(list *admissionregistration.ValidatingAdmissionPolicyBindingList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printValidatingAdmissionPolicyBindingList(list *admissionregistration.ValidatingAdmissionPolicyBindingList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printValidatingAdmissionPolicyBinding(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":1661,"to":1671}} {"id":100008211,"name":"printNamespace","signature":"func printNamespace(obj *api.Namespace, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printNamespace(obj *api.Namespace, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\trow.Cells = append(row.Cells, obj.Name, string(obj.Status.Phase), translateTimestampSince(obj.CreationTimestamp))\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1673,"to":1679}} {"id":100008212,"name":"printNamespaceList","signature":"func printNamespaceList(list *api.NamespaceList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printNamespaceList(list *api.NamespaceList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printNamespace(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":1681,"to":1691}} {"id":100008213,"name":"printSecret","signature":"func printSecret(obj *api.Secret, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printSecret(obj *api.Secret, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\trow.Cells = append(row.Cells, obj.Name, string(obj.Type), int64(len(obj.Data)), translateTimestampSince(obj.CreationTimestamp))\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1693,"to":1699}} {"id":100008214,"name":"printSecretList","signature":"func printSecretList(list *api.SecretList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printSecretList(list *api.SecretList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printSecret(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":1701,"to":1711}} {"id":100008215,"name":"printServiceAccount","signature":"func printServiceAccount(obj *api.ServiceAccount, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printServiceAccount(obj *api.ServiceAccount, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\trow.Cells = append(row.Cells, obj.Name, int64(len(obj.Secrets)), translateTimestampSince(obj.CreationTimestamp))\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1713,"to":1719}} {"id":100008216,"name":"printServiceAccountList","signature":"func printServiceAccountList(list *api.ServiceAccountList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printServiceAccountList(list *api.ServiceAccountList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printServiceAccount(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":1721,"to":1731}} {"id":100008217,"name":"printNode","signature":"func printNode(obj *api.Node, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printNode(obj *api.Node, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\n\tconditionMap := make(map[api.NodeConditionType]*api.NodeCondition)\n\tNodeAllConditions := []api.NodeConditionType{api.NodeReady}\n\tfor i := range obj.Status.Conditions {\n\t\tcond := obj.Status.Conditions[i]\n\t\tconditionMap[cond.Type] = \u0026cond\n\t}\n\tvar status []string\n\tfor _, validCondition := range NodeAllConditions {\n\t\tif condition, ok := conditionMap[validCondition]; ok {\n\t\t\tif condition.Status == api.ConditionTrue {\n\t\t\t\tstatus = append(status, string(condition.Type))\n\t\t\t} else {\n\t\t\t\tstatus = append(status, \"Not\"+string(condition.Type))\n\t\t\t}\n\t\t}\n\t}\n\tif len(status) == 0 {\n\t\tstatus = append(status, \"Unknown\")\n\t}\n\tif obj.Spec.Unschedulable {\n\t\tstatus = append(status, \"SchedulingDisabled\")\n\t}\n\n\troles := strings.Join(findNodeRoles(obj), \",\")\n\tif len(roles) == 0 {\n\t\troles = \"\u003cnone\u003e\"\n\t}\n\n\trow.Cells = append(row.Cells, obj.Name, strings.Join(status, \",\"), roles, translateTimestampSince(obj.CreationTimestamp), obj.Status.NodeInfo.KubeletVersion)\n\tif options.Wide {\n\t\tosImage, kernelVersion, crVersion := obj.Status.NodeInfo.OSImage, obj.Status.NodeInfo.KernelVersion, obj.Status.NodeInfo.ContainerRuntimeVersion\n\t\tif osImage == \"\" {\n\t\t\tosImage = \"\u003cunknown\u003e\"\n\t\t}\n\t\tif kernelVersion == \"\" {\n\t\t\tkernelVersion = \"\u003cunknown\u003e\"\n\t\t}\n\t\tif crVersion == \"\" {\n\t\t\tcrVersion = \"\u003cunknown\u003e\"\n\t\t}\n\t\trow.Cells = append(row.Cells, getNodeInternalIP(obj), getNodeExternalIP(obj), osImage, kernelVersion, crVersion)\n\t}\n\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1733,"to":1782}} {"id":100008218,"name":"getNodeExternalIP","signature":"func getNodeExternalIP(node *api.Node) string","file":"pkg/printers/internalversion/printers.go","code":"// Returns first external ip of the node or \"\u003cnone\u003e\" if none is found.\nfunc getNodeExternalIP(node *api.Node) string {\n\tfor _, address := range node.Status.Addresses {\n\t\tif address.Type == api.NodeExternalIP {\n\t\t\treturn address.Address\n\t\t}\n\t}\n\n\treturn \"\u003cnone\u003e\"\n}","line":{"from":1784,"to":1793}} {"id":100008219,"name":"getNodeInternalIP","signature":"func getNodeInternalIP(node *api.Node) string","file":"pkg/printers/internalversion/printers.go","code":"// Returns the internal IP of the node or \"\u003cnone\u003e\" if none is found.\nfunc getNodeInternalIP(node *api.Node) string {\n\tfor _, address := range node.Status.Addresses {\n\t\tif address.Type == api.NodeInternalIP {\n\t\t\treturn address.Address\n\t\t}\n\t}\n\n\treturn \"\u003cnone\u003e\"\n}","line":{"from":1795,"to":1804}} {"id":100008220,"name":"findNodeRoles","signature":"func findNodeRoles(node *api.Node) []string","file":"pkg/printers/internalversion/printers.go","code":"// findNodeRoles returns the roles of a given node.\n// The roles are determined by looking for:\n// * a node-role.kubernetes.io/\u003crole\u003e=\"\" label\n// * a kubernetes.io/role=\"\u003crole\u003e\" label\nfunc findNodeRoles(node *api.Node) []string {\n\troles := sets.NewString()\n\tfor k, v := range node.Labels {\n\t\tswitch {\n\t\tcase strings.HasPrefix(k, labelNodeRolePrefix):\n\t\t\tif role := strings.TrimPrefix(k, labelNodeRolePrefix); len(role) \u003e 0 {\n\t\t\t\troles.Insert(role)\n\t\t\t}\n\n\t\tcase k == nodeLabelRole \u0026\u0026 v != \"\":\n\t\t\troles.Insert(v)\n\t\t}\n\t}\n\treturn roles.List()\n}","line":{"from":1806,"to":1824}} {"id":100008221,"name":"printNodeList","signature":"func printNodeList(list *api.NodeList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printNodeList(list *api.NodeList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printNode(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":1826,"to":1836}} {"id":100008222,"name":"printPersistentVolume","signature":"func printPersistentVolume(obj *api.PersistentVolume, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printPersistentVolume(obj *api.PersistentVolume, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\n\tclaimRefUID := \"\"\n\tif obj.Spec.ClaimRef != nil {\n\t\tclaimRefUID += obj.Spec.ClaimRef.Namespace\n\t\tclaimRefUID += \"/\"\n\t\tclaimRefUID += obj.Spec.ClaimRef.Name\n\t}\n\n\tmodesStr := helper.GetAccessModesAsString(obj.Spec.AccessModes)\n\treclaimPolicyStr := string(obj.Spec.PersistentVolumeReclaimPolicy)\n\n\taQty := obj.Spec.Capacity[api.ResourceStorage]\n\taSize := aQty.String()\n\n\tphase := obj.Status.Phase\n\tif obj.ObjectMeta.DeletionTimestamp != nil {\n\t\tphase = \"Terminating\"\n\t}\n\tvolumeMode := \"\u003cunset\u003e\"\n\tif obj.Spec.VolumeMode != nil {\n\t\tvolumeMode = string(*obj.Spec.VolumeMode)\n\t}\n\n\trow.Cells = append(row.Cells, obj.Name, aSize, modesStr, reclaimPolicyStr,\n\t\tstring(phase), claimRefUID, helper.GetPersistentVolumeClass(obj),\n\t\tobj.Status.Reason, translateTimestampSince(obj.CreationTimestamp), volumeMode)\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1838,"to":1869}} {"id":100008223,"name":"printPersistentVolumeList","signature":"func printPersistentVolumeList(list *api.PersistentVolumeList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printPersistentVolumeList(list *api.PersistentVolumeList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printPersistentVolume(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":1871,"to":1881}} {"id":100008224,"name":"printPersistentVolumeClaim","signature":"func printPersistentVolumeClaim(obj *api.PersistentVolumeClaim, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printPersistentVolumeClaim(obj *api.PersistentVolumeClaim, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\n\tphase := obj.Status.Phase\n\tif obj.ObjectMeta.DeletionTimestamp != nil {\n\t\tphase = \"Terminating\"\n\t}\n\n\tstorage := obj.Spec.Resources.Requests[api.ResourceStorage]\n\tcapacity := \"\"\n\taccessModes := \"\"\n\tvolumeMode := \"\u003cunset\u003e\"\n\tif obj.Spec.VolumeName != \"\" {\n\t\taccessModes = helper.GetAccessModesAsString(obj.Status.AccessModes)\n\t\tstorage = obj.Status.Capacity[api.ResourceStorage]\n\t\tcapacity = storage.String()\n\t}\n\n\tif obj.Spec.VolumeMode != nil {\n\t\tvolumeMode = string(*obj.Spec.VolumeMode)\n\t}\n\n\trow.Cells = append(row.Cells, obj.Name, string(phase), obj.Spec.VolumeName, capacity, accessModes,\n\t\thelper.GetPersistentVolumeClaimClass(obj), translateTimestampSince(obj.CreationTimestamp), volumeMode)\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1883,"to":1910}} {"id":100008225,"name":"printPersistentVolumeClaimList","signature":"func printPersistentVolumeClaimList(list *api.PersistentVolumeClaimList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printPersistentVolumeClaimList(list *api.PersistentVolumeClaimList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printPersistentVolumeClaim(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":1912,"to":1922}} {"id":100008226,"name":"printEvent","signature":"func printEvent(obj *api.Event, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printEvent(obj *api.Event, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\n\tfirstTimestamp := translateTimestampSince(obj.FirstTimestamp)\n\tif obj.FirstTimestamp.IsZero() {\n\t\tfirstTimestamp = translateMicroTimestampSince(obj.EventTime)\n\t}\n\n\tlastTimestamp := translateTimestampSince(obj.LastTimestamp)\n\tif obj.LastTimestamp.IsZero() {\n\t\tlastTimestamp = firstTimestamp\n\t}\n\n\tcount := obj.Count\n\tif obj.Series != nil {\n\t\tlastTimestamp = translateMicroTimestampSince(obj.Series.LastObservedTime)\n\t\tcount = obj.Series.Count\n\t} else if count == 0 {\n\t\t// Singleton events don't have a count set in the new API.\n\t\tcount = 1\n\t}\n\n\tvar target string\n\tif len(obj.InvolvedObject.Name) \u003e 0 {\n\t\ttarget = fmt.Sprintf(\"%s/%s\", strings.ToLower(obj.InvolvedObject.Kind), obj.InvolvedObject.Name)\n\t} else {\n\t\ttarget = strings.ToLower(obj.InvolvedObject.Kind)\n\t}\n\tif options.Wide {\n\t\trow.Cells = append(row.Cells,\n\t\t\tlastTimestamp,\n\t\t\tobj.Type,\n\t\t\tobj.Reason,\n\t\t\ttarget,\n\t\t\tobj.InvolvedObject.FieldPath,\n\t\t\tformatEventSource(obj.Source, obj.ReportingController, obj.ReportingInstance),\n\t\t\tstrings.TrimSpace(obj.Message),\n\t\t\tfirstTimestamp,\n\t\t\tint64(count),\n\t\t\tobj.Name,\n\t\t)\n\t} else {\n\t\trow.Cells = append(row.Cells,\n\t\t\tlastTimestamp,\n\t\t\tobj.Type,\n\t\t\tobj.Reason,\n\t\t\ttarget,\n\t\t\tstrings.TrimSpace(obj.Message),\n\t\t)\n\t}\n\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1924,"to":1978}} {"id":100008227,"name":"printEventList","signature":"func printEventList(list *api.EventList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"// Sorts and prints the EventList in a human-friendly format.\nfunc printEventList(list *api.EventList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printEvent(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":1980,"to":1991}} {"id":100008228,"name":"printRoleBinding","signature":"func printRoleBinding(obj *rbac.RoleBinding, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printRoleBinding(obj *rbac.RoleBinding, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\n\troleRef := fmt.Sprintf(\"%s/%s\", obj.RoleRef.Kind, obj.RoleRef.Name)\n\trow.Cells = append(row.Cells, obj.Name, roleRef, translateTimestampSince(obj.CreationTimestamp))\n\tif options.Wide {\n\t\tusers, groups, sas, _ := rbac.SubjectsStrings(obj.Subjects)\n\t\trow.Cells = append(row.Cells, strings.Join(users, \", \"), strings.Join(groups, \", \"), strings.Join(sas, \", \"))\n\t}\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":1993,"to":2005}} {"id":100008229,"name":"printRoleBindingList","signature":"func printRoleBindingList(list *rbac.RoleBindingList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"// Prints the RoleBinding in a human-friendly format.\nfunc printRoleBindingList(list *rbac.RoleBindingList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printRoleBinding(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":2007,"to":2018}} {"id":100008230,"name":"printClusterRoleBinding","signature":"func printClusterRoleBinding(obj *rbac.ClusterRoleBinding, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printClusterRoleBinding(obj *rbac.ClusterRoleBinding, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\n\troleRef := fmt.Sprintf(\"%s/%s\", obj.RoleRef.Kind, obj.RoleRef.Name)\n\trow.Cells = append(row.Cells, obj.Name, roleRef, translateTimestampSince(obj.CreationTimestamp))\n\tif options.Wide {\n\t\tusers, groups, sas, _ := rbac.SubjectsStrings(obj.Subjects)\n\t\trow.Cells = append(row.Cells, strings.Join(users, \", \"), strings.Join(groups, \", \"), strings.Join(sas, \", \"))\n\t}\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":2020,"to":2032}} {"id":100008231,"name":"printClusterRoleBindingList","signature":"func printClusterRoleBindingList(list *rbac.ClusterRoleBindingList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"// Prints the ClusterRoleBinding in a human-friendly format.\nfunc printClusterRoleBindingList(list *rbac.ClusterRoleBindingList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printClusterRoleBinding(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":2034,"to":2045}} {"id":100008232,"name":"printCertificateSigningRequest","signature":"func printCertificateSigningRequest(obj *certificates.CertificateSigningRequest, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printCertificateSigningRequest(obj *certificates.CertificateSigningRequest, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\tstatus := extractCSRStatus(obj)\n\tsignerName := \"\u003cnone\u003e\"\n\tif obj.Spec.SignerName != \"\" {\n\t\tsignerName = obj.Spec.SignerName\n\t}\n\trequestedDuration := \"\u003cnone\u003e\"\n\tif obj.Spec.ExpirationSeconds != nil {\n\t\trequestedDuration = duration.HumanDuration(csr.ExpirationSecondsToDuration(*obj.Spec.ExpirationSeconds))\n\t}\n\trow.Cells = append(row.Cells, obj.Name, translateTimestampSince(obj.CreationTimestamp), signerName, obj.Spec.Username, requestedDuration, status)\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":2047,"to":2062}} {"id":100008233,"name":"extractCSRStatus","signature":"func extractCSRStatus(csr *certificates.CertificateSigningRequest) string","file":"pkg/printers/internalversion/printers.go","code":"func extractCSRStatus(csr *certificates.CertificateSigningRequest) string {\n\tvar approved, denied, failed bool\n\tfor _, c := range csr.Status.Conditions {\n\t\tswitch c.Type {\n\t\tcase certificates.CertificateApproved:\n\t\t\tapproved = true\n\t\tcase certificates.CertificateDenied:\n\t\t\tdenied = true\n\t\tcase certificates.CertificateFailed:\n\t\t\tfailed = true\n\t\t}\n\t}\n\tvar status string\n\t// must be in order of presidence\n\tif denied {\n\t\tstatus += \"Denied\"\n\t} else if approved {\n\t\tstatus += \"Approved\"\n\t} else {\n\t\tstatus += \"Pending\"\n\t}\n\tif failed {\n\t\tstatus += \",Failed\"\n\t}\n\tif len(csr.Status.Certificate) \u003e 0 {\n\t\tstatus += \",Issued\"\n\t}\n\treturn status\n}","line":{"from":2064,"to":2092}} {"id":100008234,"name":"printCertificateSigningRequestList","signature":"func printCertificateSigningRequestList(list *certificates.CertificateSigningRequestList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printCertificateSigningRequestList(list *certificates.CertificateSigningRequestList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printCertificateSigningRequest(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":2094,"to":2104}} {"id":100008235,"name":"printClusterTrustBundle","signature":"func printClusterTrustBundle(obj *certificates.ClusterTrustBundle, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printClusterTrustBundle(obj *certificates.ClusterTrustBundle, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\tsignerName := \"\u003cnone\u003e\"\n\tif obj.Spec.SignerName != \"\" {\n\t\tsignerName = obj.Spec.SignerName\n\t}\n\trow.Cells = append(row.Cells, obj.Name, signerName)\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":2106,"to":2116}} {"id":100008236,"name":"printClusterTrustBundleList","signature":"func printClusterTrustBundleList(list *certificates.ClusterTrustBundleList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printClusterTrustBundleList(list *certificates.ClusterTrustBundleList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printClusterTrustBundle(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":2118,"to":2128}} {"id":100008237,"name":"printComponentStatus","signature":"func printComponentStatus(obj *api.ComponentStatus, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printComponentStatus(obj *api.ComponentStatus, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\tstatus := \"Unknown\"\n\tmessage := \"\"\n\terror := \"\"\n\tfor _, condition := range obj.Conditions {\n\t\tif condition.Type == api.ComponentHealthy {\n\t\t\tif condition.Status == api.ConditionTrue {\n\t\t\t\tstatus = \"Healthy\"\n\t\t\t} else {\n\t\t\t\tstatus = \"Unhealthy\"\n\t\t\t}\n\t\t\tmessage = condition.Message\n\t\t\terror = condition.Error\n\t\t\tbreak\n\t\t}\n\t}\n\trow.Cells = append(row.Cells, obj.Name, status, message, error)\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":2130,"to":2151}} {"id":100008238,"name":"printComponentStatusList","signature":"func printComponentStatusList(list *api.ComponentStatusList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printComponentStatusList(list *api.ComponentStatusList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printComponentStatus(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":2153,"to":2163}} {"id":100008239,"name":"printDeployment","signature":"func printDeployment(obj *apps.Deployment, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printDeployment(obj *apps.Deployment, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\tdesiredReplicas := obj.Spec.Replicas\n\tupdatedReplicas := obj.Status.UpdatedReplicas\n\treadyReplicas := obj.Status.ReadyReplicas\n\tavailableReplicas := obj.Status.AvailableReplicas\n\tage := translateTimestampSince(obj.CreationTimestamp)\n\tcontainers := obj.Spec.Template.Spec.Containers\n\tselector, err := metav1.LabelSelectorAsSelector(obj.Spec.Selector)\n\tselectorString := \"\"\n\tif err != nil {\n\t\tselectorString = \"\u003cinvalid\u003e\"\n\t} else {\n\t\tselectorString = selector.String()\n\t}\n\trow.Cells = append(row.Cells, obj.Name, fmt.Sprintf(\"%d/%d\", int64(readyReplicas), int64(desiredReplicas)), int64(updatedReplicas), int64(availableReplicas), age)\n\tif options.Wide {\n\t\tcontainers, images := layoutContainerCells(containers)\n\t\trow.Cells = append(row.Cells, containers, images, selectorString)\n\t}\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":2165,"to":2188}} {"id":100008240,"name":"printDeploymentList","signature":"func printDeploymentList(list *apps.DeploymentList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printDeploymentList(list *apps.DeploymentList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printDeployment(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":2190,"to":2200}} {"id":100008241,"name":"formatHPAMetrics","signature":"func formatHPAMetrics(specs []autoscaling.MetricSpec, statuses []autoscaling.MetricStatus) string","file":"pkg/printers/internalversion/printers.go","code":"func formatHPAMetrics(specs []autoscaling.MetricSpec, statuses []autoscaling.MetricStatus) string {\n\tif len(specs) == 0 {\n\t\treturn \"\u003cnone\u003e\"\n\t}\n\tlist := []string{}\n\tmax := 2\n\tmore := false\n\tcount := 0\n\tfor i, spec := range specs {\n\t\tswitch spec.Type {\n\t\tcase autoscaling.ExternalMetricSourceType:\n\t\t\tif spec.External.Target.AverageValue != nil {\n\t\t\t\tcurrent := \"\u003cunknown\u003e\"\n\t\t\t\tif len(statuses) \u003e i \u0026\u0026 statuses[i].External != nil \u0026\u0026 statuses[i].External.Current.AverageValue != nil {\n\t\t\t\t\tcurrent = statuses[i].External.Current.AverageValue.String()\n\t\t\t\t}\n\t\t\t\tlist = append(list, fmt.Sprintf(\"%s/%s (avg)\", current, spec.External.Target.AverageValue.String()))\n\t\t\t} else {\n\t\t\t\tcurrent := \"\u003cunknown\u003e\"\n\t\t\t\tif len(statuses) \u003e i \u0026\u0026 statuses[i].External != nil {\n\t\t\t\t\tcurrent = statuses[i].External.Current.Value.String()\n\t\t\t\t}\n\t\t\t\tlist = append(list, fmt.Sprintf(\"%s/%s\", current, spec.External.Target.Value.String()))\n\t\t\t}\n\t\tcase autoscaling.PodsMetricSourceType:\n\t\t\tcurrent := \"\u003cunknown\u003e\"\n\t\t\tif len(statuses) \u003e i \u0026\u0026 statuses[i].Pods != nil {\n\t\t\t\tcurrent = statuses[i].Pods.Current.AverageValue.String()\n\t\t\t}\n\t\t\tlist = append(list, fmt.Sprintf(\"%s/%s\", current, spec.Pods.Target.AverageValue.String()))\n\t\tcase autoscaling.ObjectMetricSourceType:\n\t\t\tif spec.Object.Target.AverageValue != nil {\n\t\t\t\tcurrent := \"\u003cunknown\u003e\"\n\t\t\t\tif len(statuses) \u003e i \u0026\u0026 statuses[i].Object != nil \u0026\u0026 statuses[i].Object.Current.AverageValue != nil {\n\t\t\t\t\tcurrent = statuses[i].Object.Current.AverageValue.String()\n\t\t\t\t}\n\t\t\t\tlist = append(list, fmt.Sprintf(\"%s/%s (avg)\", current, spec.Object.Target.AverageValue.String()))\n\t\t\t} else {\n\t\t\t\tcurrent := \"\u003cunknown\u003e\"\n\t\t\t\tif len(statuses) \u003e i \u0026\u0026 statuses[i].Object != nil {\n\t\t\t\t\tcurrent = statuses[i].Object.Current.Value.String()\n\t\t\t\t}\n\t\t\t\tlist = append(list, fmt.Sprintf(\"%s/%s\", current, spec.Object.Target.Value.String()))\n\t\t\t}\n\t\tcase autoscaling.ResourceMetricSourceType:\n\t\t\tif spec.Resource.Target.AverageValue != nil {\n\t\t\t\tcurrent := \"\u003cunknown\u003e\"\n\t\t\t\tif len(statuses) \u003e i \u0026\u0026 statuses[i].Resource != nil {\n\t\t\t\t\tcurrent = statuses[i].Resource.Current.AverageValue.String()\n\t\t\t\t}\n\t\t\t\tlist = append(list, fmt.Sprintf(\"%s/%s\", current, spec.Resource.Target.AverageValue.String()))\n\t\t\t} else {\n\t\t\t\tcurrent := \"\u003cunknown\u003e\"\n\t\t\t\tif len(statuses) \u003e i \u0026\u0026 statuses[i].Resource != nil \u0026\u0026 statuses[i].Resource.Current.AverageUtilization != nil {\n\t\t\t\t\tcurrent = fmt.Sprintf(\"%d%%\", *statuses[i].Resource.Current.AverageUtilization)\n\t\t\t\t}\n\n\t\t\t\ttarget := \"\u003cauto\u003e\"\n\t\t\t\tif spec.Resource.Target.AverageUtilization != nil {\n\t\t\t\t\ttarget = fmt.Sprintf(\"%d%%\", *spec.Resource.Target.AverageUtilization)\n\t\t\t\t}\n\t\t\t\tlist = append(list, fmt.Sprintf(\"%s/%s\", current, target))\n\t\t\t}\n\t\tcase autoscaling.ContainerResourceMetricSourceType:\n\t\t\tif spec.ContainerResource.Target.AverageValue != nil {\n\t\t\t\tcurrent := \"\u003cunknown\u003e\"\n\t\t\t\tif len(statuses) \u003e i \u0026\u0026 statuses[i].ContainerResource != nil {\n\t\t\t\t\tcurrent = statuses[i].ContainerResource.Current.AverageValue.String()\n\t\t\t\t}\n\t\t\t\tlist = append(list, fmt.Sprintf(\"%s/%s\", current, spec.ContainerResource.Target.AverageValue.String()))\n\t\t\t} else {\n\t\t\t\tcurrent := \"\u003cunknown\u003e\"\n\t\t\t\tif len(statuses) \u003e i \u0026\u0026 statuses[i].ContainerResource != nil \u0026\u0026 statuses[i].ContainerResource.Current.AverageUtilization != nil {\n\t\t\t\t\tcurrent = fmt.Sprintf(\"%d%%\", *statuses[i].ContainerResource.Current.AverageUtilization)\n\t\t\t\t}\n\n\t\t\t\ttarget := \"\u003cauto\u003e\"\n\t\t\t\tif spec.ContainerResource.Target.AverageUtilization != nil {\n\t\t\t\t\ttarget = fmt.Sprintf(\"%d%%\", *spec.ContainerResource.Target.AverageUtilization)\n\t\t\t\t}\n\t\t\t\tlist = append(list, fmt.Sprintf(\"%s/%s\", current, target))\n\t\t\t}\n\t\tdefault:\n\t\t\tlist = append(list, \"\u003cunknown type\u003e\")\n\t\t}\n\n\t\tcount++\n\t}\n\n\tif count \u003e max {\n\t\tlist = list[:max]\n\t\tmore = true\n\t}\n\n\tret := strings.Join(list, \", \")\n\tif more {\n\t\treturn fmt.Sprintf(\"%s + %d more...\", ret, count-max)\n\t}\n\treturn ret\n}","line":{"from":2202,"to":2301}} {"id":100008242,"name":"printHorizontalPodAutoscaler","signature":"func printHorizontalPodAutoscaler(obj *autoscaling.HorizontalPodAutoscaler, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printHorizontalPodAutoscaler(obj *autoscaling.HorizontalPodAutoscaler, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\n\treference := fmt.Sprintf(\"%s/%s\",\n\t\tobj.Spec.ScaleTargetRef.Kind,\n\t\tobj.Spec.ScaleTargetRef.Name)\n\tminPods := \"\u003cunset\u003e\"\n\tmetrics := formatHPAMetrics(obj.Spec.Metrics, obj.Status.CurrentMetrics)\n\tif obj.Spec.MinReplicas != nil {\n\t\tminPods = fmt.Sprintf(\"%d\", *obj.Spec.MinReplicas)\n\t}\n\tmaxPods := obj.Spec.MaxReplicas\n\tcurrentReplicas := obj.Status.CurrentReplicas\n\trow.Cells = append(row.Cells, obj.Name, reference, metrics, minPods, int64(maxPods), int64(currentReplicas), translateTimestampSince(obj.CreationTimestamp))\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":2303,"to":2320}} {"id":100008243,"name":"printHorizontalPodAutoscalerList","signature":"func printHorizontalPodAutoscalerList(list *autoscaling.HorizontalPodAutoscalerList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printHorizontalPodAutoscalerList(list *autoscaling.HorizontalPodAutoscalerList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printHorizontalPodAutoscaler(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":2322,"to":2332}} {"id":100008244,"name":"printConfigMap","signature":"func printConfigMap(obj *api.ConfigMap, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printConfigMap(obj *api.ConfigMap, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\trow.Cells = append(row.Cells, obj.Name, int64(len(obj.Data)+len(obj.BinaryData)), translateTimestampSince(obj.CreationTimestamp))\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":2334,"to":2340}} {"id":100008245,"name":"printConfigMapList","signature":"func printConfigMapList(list *api.ConfigMapList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printConfigMapList(list *api.ConfigMapList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printConfigMap(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":2342,"to":2352}} {"id":100008246,"name":"printNetworkPolicy","signature":"func printNetworkPolicy(obj *networking.NetworkPolicy, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printNetworkPolicy(obj *networking.NetworkPolicy, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\trow.Cells = append(row.Cells, obj.Name, metav1.FormatLabelSelector(\u0026obj.Spec.PodSelector), translateTimestampSince(obj.CreationTimestamp))\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":2354,"to":2360}} {"id":100008247,"name":"printNetworkPolicyList","signature":"func printNetworkPolicyList(list *networking.NetworkPolicyList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printNetworkPolicyList(list *networking.NetworkPolicyList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printNetworkPolicy(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":2362,"to":2372}} {"id":100008248,"name":"printStorageClass","signature":"func printStorageClass(obj *storage.StorageClass, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printStorageClass(obj *storage.StorageClass, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\n\tname := obj.Name\n\tif storageutil.IsDefaultAnnotation(obj.ObjectMeta) {\n\t\tname += \" (default)\"\n\t}\n\tprovtype := obj.Provisioner\n\treclaimPolicy := string(api.PersistentVolumeReclaimDelete)\n\tif obj.ReclaimPolicy != nil {\n\t\treclaimPolicy = string(*obj.ReclaimPolicy)\n\t}\n\n\tvolumeBindingMode := string(storage.VolumeBindingImmediate)\n\tif obj.VolumeBindingMode != nil {\n\t\tvolumeBindingMode = string(*obj.VolumeBindingMode)\n\t}\n\n\tallowVolumeExpansion := false\n\tif obj.AllowVolumeExpansion != nil {\n\t\tallowVolumeExpansion = *obj.AllowVolumeExpansion\n\t}\n\n\trow.Cells = append(row.Cells, name, provtype, reclaimPolicy, volumeBindingMode, allowVolumeExpansion,\n\t\ttranslateTimestampSince(obj.CreationTimestamp))\n\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":2374,"to":2403}} {"id":100008249,"name":"printStorageClassList","signature":"func printStorageClassList(list *storage.StorageClassList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printStorageClassList(list *storage.StorageClassList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printStorageClass(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":2405,"to":2415}} {"id":100008250,"name":"printLease","signature":"func printLease(obj *coordination.Lease, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printLease(obj *coordination.Lease, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\n\tvar holderIdentity string\n\tif obj.Spec.HolderIdentity != nil {\n\t\tholderIdentity = *obj.Spec.HolderIdentity\n\t}\n\trow.Cells = append(row.Cells, obj.Name, holderIdentity, translateTimestampSince(obj.CreationTimestamp))\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":2417,"to":2428}} {"id":100008251,"name":"printLeaseList","signature":"func printLeaseList(list *coordination.LeaseList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printLeaseList(list *coordination.LeaseList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printLease(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":2430,"to":2440}} {"id":100008252,"name":"printStatus","signature":"func printStatus(obj *metav1.Status, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printStatus(obj *metav1.Status, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\trow.Cells = append(row.Cells, obj.Status, string(obj.Reason), obj.Message)\n\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":2442,"to":2449}} {"id":100008253,"name":"layoutContainerCells","signature":"func layoutContainerCells(containers []api.Container) (names string, images string)","file":"pkg/printers/internalversion/printers.go","code":"// Lay out all the containers on one line if use wide output.\nfunc layoutContainerCells(containers []api.Container) (names string, images string) {\n\tvar namesBuffer bytes.Buffer\n\tvar imagesBuffer bytes.Buffer\n\n\tfor i, container := range containers {\n\t\tnamesBuffer.WriteString(container.Name)\n\t\timagesBuffer.WriteString(container.Image)\n\t\tif i != len(containers)-1 {\n\t\t\tnamesBuffer.WriteString(\",\")\n\t\t\timagesBuffer.WriteString(\",\")\n\t\t}\n\t}\n\treturn namesBuffer.String(), imagesBuffer.String()\n}","line":{"from":2451,"to":2465}} {"id":100008254,"name":"formatEventSource","signature":"func formatEventSource(es api.EventSource, reportingController, reportingInstance string) string","file":"pkg/printers/internalversion/printers.go","code":"// formatEventSource formats EventSource as a comma separated string excluding Host when empty.\n// It uses reportingController when Source.Component is empty and reportingInstance when Source.Host is empty\nfunc formatEventSource(es api.EventSource, reportingController, reportingInstance string) string {\n\treturn formatEventSourceComponentInstance(\n\t\tfirstNonEmpty(es.Component, reportingController),\n\t\tfirstNonEmpty(es.Host, reportingInstance),\n\t)\n}","line":{"from":2467,"to":2474}} {"id":100008255,"name":"firstNonEmpty","signature":"func firstNonEmpty(ss ...string) string","file":"pkg/printers/internalversion/printers.go","code":"func firstNonEmpty(ss ...string) string {\n\tfor _, s := range ss {\n\t\tif len(s) \u003e 0 {\n\t\t\treturn s\n\t\t}\n\t}\n\treturn \"\"\n}","line":{"from":2476,"to":2483}} {"id":100008256,"name":"formatEventSourceComponentInstance","signature":"func formatEventSourceComponentInstance(component, instance string) string","file":"pkg/printers/internalversion/printers.go","code":"func formatEventSourceComponentInstance(component, instance string) string {\n\tif len(instance) == 0 {\n\t\treturn component\n\t}\n\treturn component + \", \" + instance\n}","line":{"from":2485,"to":2490}} {"id":100008257,"name":"printControllerRevision","signature":"func printControllerRevision(obj *apps.ControllerRevision, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printControllerRevision(obj *apps.ControllerRevision, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\n\tcontrollerRef := metav1.GetControllerOf(obj)\n\tcontrollerName := \"\u003cnone\u003e\"\n\tif controllerRef != nil {\n\t\twithKind := true\n\t\tgv, err := schema.ParseGroupVersion(controllerRef.APIVersion)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tgvk := gv.WithKind(controllerRef.Kind)\n\t\tcontrollerName = formatResourceName(gvk.GroupKind(), controllerRef.Name, withKind)\n\t}\n\trevision := obj.Revision\n\tage := translateTimestampSince(obj.CreationTimestamp)\n\trow.Cells = append(row.Cells, obj.Name, controllerName, revision, age)\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":2492,"to":2512}} {"id":100008258,"name":"printControllerRevisionList","signature":"func printControllerRevisionList(list *apps.ControllerRevisionList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printControllerRevisionList(list *apps.ControllerRevisionList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printControllerRevision(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":2514,"to":2524}} {"id":100008259,"name":"formatResourceName","signature":"func formatResourceName(kind schema.GroupKind, name string, withKind bool) string","file":"pkg/printers/internalversion/printers.go","code":"// formatResourceName receives a resource kind, name, and boolean specifying\n// whether or not to update the current name to \"kind/name\"\nfunc formatResourceName(kind schema.GroupKind, name string, withKind bool) string {\n\tif !withKind || kind.Empty() {\n\t\treturn name\n\t}\n\n\treturn strings.ToLower(kind.String()) + \"/\" + name\n}","line":{"from":2526,"to":2534}} {"id":100008260,"name":"printResourceQuota","signature":"func printResourceQuota(resourceQuota *api.ResourceQuota, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printResourceQuota(resourceQuota *api.ResourceQuota, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: resourceQuota},\n\t}\n\n\tresources := make([]api.ResourceName, 0, len(resourceQuota.Status.Hard))\n\tfor resource := range resourceQuota.Status.Hard {\n\t\tresources = append(resources, resource)\n\t}\n\tsort.Sort(SortableResourceNames(resources))\n\n\trequestColumn := bytes.NewBuffer([]byte{})\n\tlimitColumn := bytes.NewBuffer([]byte{})\n\tfor i := range resources {\n\t\tw := requestColumn\n\t\tresource := resources[i]\n\t\tusedQuantity := resourceQuota.Status.Used[resource]\n\t\thardQuantity := resourceQuota.Status.Hard[resource]\n\n\t\t// use limitColumn writer if a resource name prefixed with \"limits\" is found\n\t\tif pieces := strings.Split(resource.String(), \".\"); len(pieces) \u003e 1 \u0026\u0026 pieces[0] == \"limits\" {\n\t\t\tw = limitColumn\n\t\t}\n\n\t\tfmt.Fprintf(w, \"%s: %s/%s, \", resource, usedQuantity.String(), hardQuantity.String())\n\t}\n\n\tage := translateTimestampSince(resourceQuota.CreationTimestamp)\n\trow.Cells = append(row.Cells, resourceQuota.Name, age, strings.TrimSuffix(requestColumn.String(), \", \"), strings.TrimSuffix(limitColumn.String(), \", \"))\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":2536,"to":2566}} {"id":100008261,"name":"printResourceQuotaList","signature":"func printResourceQuotaList(list *api.ResourceQuotaList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printResourceQuotaList(list *api.ResourceQuotaList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printResourceQuota(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":2568,"to":2578}} {"id":100008262,"name":"printPriorityClass","signature":"func printPriorityClass(obj *scheduling.PriorityClass, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printPriorityClass(obj *scheduling.PriorityClass, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\n\tname := obj.Name\n\tvalue := obj.Value\n\tglobalDefault := obj.GlobalDefault\n\trow.Cells = append(row.Cells, name, int64(value), globalDefault, translateTimestampSince(obj.CreationTimestamp))\n\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":2580,"to":2591}} {"id":100008263,"name":"printPriorityClassList","signature":"func printPriorityClassList(list *scheduling.PriorityClassList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printPriorityClassList(list *scheduling.PriorityClassList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printPriorityClass(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":2593,"to":2603}} {"id":100008264,"name":"printRuntimeClass","signature":"func printRuntimeClass(obj *nodeapi.RuntimeClass, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printRuntimeClass(obj *nodeapi.RuntimeClass, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\n\tname := obj.Name\n\thandler := obj.Handler\n\trow.Cells = append(row.Cells, name, handler, translateTimestampSince(obj.CreationTimestamp))\n\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":2605,"to":2615}} {"id":100008265,"name":"printRuntimeClassList","signature":"func printRuntimeClassList(list *nodeapi.RuntimeClassList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printRuntimeClassList(list *nodeapi.RuntimeClassList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printRuntimeClass(\u0026list.Items[i], options)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":2617,"to":2628}} {"id":100008266,"name":"printVolumeAttachment","signature":"func printVolumeAttachment(obj *storage.VolumeAttachment, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printVolumeAttachment(obj *storage.VolumeAttachment, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\n\tname := obj.Name\n\tpvName := \"\"\n\tif obj.Spec.Source.PersistentVolumeName != nil {\n\t\tpvName = *obj.Spec.Source.PersistentVolumeName\n\t}\n\trow.Cells = append(row.Cells, name, obj.Spec.Attacher, pvName, obj.Spec.NodeName, obj.Status.Attached, translateTimestampSince(obj.CreationTimestamp))\n\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":2630,"to":2643}} {"id":100008267,"name":"printVolumeAttachmentList","signature":"func printVolumeAttachmentList(list *storage.VolumeAttachmentList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printVolumeAttachmentList(list *storage.VolumeAttachmentList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printVolumeAttachment(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":2645,"to":2655}} {"id":100008268,"name":"printFlowSchema","signature":"func printFlowSchema(obj *flowcontrol.FlowSchema, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printFlowSchema(obj *flowcontrol.FlowSchema, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\n\tname := obj.Name\n\tplName := obj.Spec.PriorityLevelConfiguration.Name\n\tdistinguisherMethod := \"\u003cnone\u003e\"\n\tif obj.Spec.DistinguisherMethod != nil {\n\t\tdistinguisherMethod = string(obj.Spec.DistinguisherMethod.Type)\n\t}\n\tbadPLRef := \"?\"\n\tfor _, cond := range obj.Status.Conditions {\n\t\tif cond.Type == flowcontrol.FlowSchemaConditionDangling {\n\t\t\tbadPLRef = string(cond.Status)\n\t\t\tbreak\n\t\t}\n\t}\n\trow.Cells = append(row.Cells, name, plName, int64(obj.Spec.MatchingPrecedence), distinguisherMethod, translateTimestampSince(obj.CreationTimestamp), badPLRef)\n\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":2657,"to":2678}} {"id":100008269,"name":"printFlowSchemaList","signature":"func printFlowSchemaList(list *flowcontrol.FlowSchemaList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printFlowSchemaList(list *flowcontrol.FlowSchemaList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfsSeq := make(apihelpers.FlowSchemaSequence, len(list.Items))\n\tfor i := range list.Items {\n\t\tfsSeq[i] = \u0026list.Items[i]\n\t}\n\tsort.Sort(fsSeq)\n\tfor i := range fsSeq {\n\t\tr, err := printFlowSchema(fsSeq[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":2680,"to":2695}} {"id":100008270,"name":"printStorageVersion","signature":"func printStorageVersion(obj *apiserverinternal.StorageVersion, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printStorageVersion(obj *apiserverinternal.StorageVersion, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\tcommonEncodingVersion := \"\u003cunset\u003e\"\n\tif obj.Status.CommonEncodingVersion != nil {\n\t\tcommonEncodingVersion = *obj.Status.CommonEncodingVersion\n\t}\n\trow.Cells = append(row.Cells, obj.Name, commonEncodingVersion, formatStorageVersions(obj.Status.StorageVersions), translateTimestampSince(obj.CreationTimestamp))\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":2697,"to":2707}} {"id":100008271,"name":"formatStorageVersions","signature":"func formatStorageVersions(storageVersions []apiserverinternal.ServerStorageVersion) string","file":"pkg/printers/internalversion/printers.go","code":"func formatStorageVersions(storageVersions []apiserverinternal.ServerStorageVersion) string {\n\tlist := []string{}\n\tmax := 3\n\tmore := false\n\tcount := 0\n\tfor _, sv := range storageVersions {\n\t\tif len(list) \u003c max {\n\t\t\tlist = append(list, fmt.Sprintf(\"%s=%s\", sv.APIServerID, sv.EncodingVersion))\n\t\t} else if len(list) == max {\n\t\t\tmore = true\n\t\t}\n\t\tcount++\n\t}\n\treturn listWithMoreString(list, more, count, max)\n}","line":{"from":2709,"to":2723}} {"id":100008272,"name":"printStorageVersionList","signature":"func printStorageVersionList(list *apiserverinternal.StorageVersionList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printStorageVersionList(list *apiserverinternal.StorageVersionList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printStorageVersion(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":2725,"to":2735}} {"id":100008273,"name":"printPriorityLevelConfiguration","signature":"func printPriorityLevelConfiguration(obj *flowcontrol.PriorityLevelConfiguration, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printPriorityLevelConfiguration(obj *flowcontrol.PriorityLevelConfiguration, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\tname := obj.Name\n\tncs := interface{}(\"\u003cnone\u003e\")\n\tqueues := interface{}(\"\u003cnone\u003e\")\n\thandSize := interface{}(\"\u003cnone\u003e\")\n\tqueueLengthLimit := interface{}(\"\u003cnone\u003e\")\n\tif obj.Spec.Limited != nil {\n\t\tncs = obj.Spec.Limited.NominalConcurrencyShares\n\t\tif qc := obj.Spec.Limited.LimitResponse.Queuing; qc != nil {\n\t\t\tqueues = qc.Queues\n\t\t\thandSize = qc.HandSize\n\t\t\tqueueLengthLimit = qc.QueueLengthLimit\n\t\t}\n\t}\n\trow.Cells = append(row.Cells, name, string(obj.Spec.Type), ncs, queues, handSize, queueLengthLimit, translateTimestampSince(obj.CreationTimestamp))\n\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":2737,"to":2757}} {"id":100008274,"name":"printPriorityLevelConfigurationList","signature":"func printPriorityLevelConfigurationList(list *flowcontrol.PriorityLevelConfigurationList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printPriorityLevelConfigurationList(list *flowcontrol.PriorityLevelConfigurationList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printPriorityLevelConfiguration(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":2759,"to":2769}} {"id":100008275,"name":"printClusterCIDR","signature":"func printClusterCIDR(obj *networking.ClusterCIDR, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printClusterCIDR(obj *networking.ClusterCIDR, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\tipv4 := \"\u003cnone\u003e\"\n\tipv6 := \"\u003cnone\u003e\"\n\n\tif obj.Spec.IPv4 != \"\" {\n\t\tipv4 = obj.Spec.IPv4\n\t}\n\tif obj.Spec.IPv6 != \"\" {\n\t\tipv6 = obj.Spec.IPv6\n\t}\n\n\trow.Cells = append(row.Cells, obj.Name, fmt.Sprint(obj.Spec.PerNodeHostBits), ipv4, ipv6, translateTimestampSince(obj.CreationTimestamp))\n\tif options.Wide {\n\t\tnodeSelector := \"\u003cnone\u003e\"\n\t\tif obj.Spec.NodeSelector != nil {\n\t\t\tallTerms := make([]string, 0)\n\t\t\tfor _, term := range obj.Spec.NodeSelector.NodeSelectorTerms {\n\t\t\t\tif len(term.MatchExpressions) \u003e 0 {\n\t\t\t\t\tmatchExpressions := fmt.Sprintf(\"MatchExpressions: %v\", term.MatchExpressions)\n\t\t\t\t\tallTerms = append(allTerms, matchExpressions)\n\t\t\t\t}\n\n\t\t\t\tif len(term.MatchFields) \u003e 0 {\n\t\t\t\t\tmatchFields := fmt.Sprintf(\"MatchFields: %v\", term.MatchFields)\n\t\t\t\t\tallTerms = append(allTerms, matchFields)\n\t\t\t\t}\n\t\t\t}\n\t\t\tnodeSelector = strings.Join(allTerms, \",\")\n\t\t}\n\n\t\trow.Cells = append(row.Cells, nodeSelector)\n\t}\n\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":2771,"to":2808}} {"id":100008276,"name":"printClusterCIDRList","signature":"func printClusterCIDRList(list *networking.ClusterCIDRList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printClusterCIDRList(list *networking.ClusterCIDRList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printClusterCIDR(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":2810,"to":2820}} {"id":100008277,"name":"printIPAddress","signature":"func printIPAddress(obj *networking.IPAddress, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printIPAddress(obj *networking.IPAddress, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\n\tparentRefName := \"\u003cnone\u003e\"\n\tif obj.Spec.ParentRef != nil {\n\t\tgr := schema.GroupResource{\n\t\t\tGroup: obj.Spec.ParentRef.Group,\n\t\t\tResource: obj.Spec.ParentRef.Resource,\n\t\t}\n\t\tparentRefName = strings.ToLower(gr.String())\n\t\tif obj.Spec.ParentRef.Namespace != \"\" {\n\t\t\tparentRefName += \"/\" + obj.Spec.ParentRef.Namespace\n\t\t}\n\t\tparentRefName += \"/\" + obj.Spec.ParentRef.Name\n\t}\n\tage := translateTimestampSince(obj.CreationTimestamp)\n\trow.Cells = append(row.Cells, obj.Name, parentRefName, age)\n\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":2822,"to":2843}} {"id":100008278,"name":"printIPAddressList","signature":"func printIPAddressList(list *networking.IPAddressList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printIPAddressList(list *networking.IPAddressList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printIPAddress(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":2845,"to":2855}} {"id":100008279,"name":"printScale","signature":"func printScale(obj *autoscaling.Scale, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printScale(obj *autoscaling.Scale, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\trow.Cells = append(row.Cells, obj.Name, int64(obj.Spec.Replicas), int64(obj.Status.Replicas), translateTimestampSince(obj.CreationTimestamp))\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":2857,"to":2863}} {"id":100008280,"name":"printResourceClass","signature":"func printResourceClass(obj *resource.ResourceClass, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printResourceClass(obj *resource.ResourceClass, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\trow.Cells = append(row.Cells, obj.Name, obj.DriverName, translateTimestampSince(obj.CreationTimestamp))\n\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":2865,"to":2872}} {"id":100008281,"name":"printResourceClassList","signature":"func printResourceClassList(list *resource.ResourceClassList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printResourceClassList(list *resource.ResourceClassList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printResourceClass(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":2874,"to":2884}} {"id":100008282,"name":"printResourceClaim","signature":"func printResourceClaim(obj *resource.ResourceClaim, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printResourceClaim(obj *resource.ResourceClaim, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\trow.Cells = append(row.Cells, obj.Name, obj.Spec.ResourceClassName, string(obj.Spec.AllocationMode), resourceClaimState(obj), translateTimestampSince(obj.CreationTimestamp))\n\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":2886,"to":2893}} {"id":100008283,"name":"resourceClaimState","signature":"func resourceClaimState(obj *resource.ResourceClaim) string","file":"pkg/printers/internalversion/printers.go","code":"func resourceClaimState(obj *resource.ResourceClaim) string {\n\tvar states []string\n\tif obj.DeletionTimestamp != nil {\n\t\tstates = append(states, \"deleted\")\n\t}\n\tif obj.Status.Allocation == nil {\n\t\tif obj.DeletionTimestamp == nil {\n\t\t\tstates = append(states, \"pending\")\n\t\t}\n\t} else {\n\t\tstates = append(states, \"allocated\")\n\t\tif len(obj.Status.ReservedFor) \u003e 0 {\n\t\t\tstates = append(states, \"reserved\")\n\t\t} else if obj.DeletionTimestamp != nil || obj.Status.DeallocationRequested {\n\t\t\tstates = append(states, \"deallocating\")\n\t\t}\n\t}\n\treturn strings.Join(states, \",\")\n}","line":{"from":2895,"to":2913}} {"id":100008284,"name":"printResourceClaimList","signature":"func printResourceClaimList(list *resource.ResourceClaimList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printResourceClaimList(list *resource.ResourceClaimList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printResourceClaim(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":2915,"to":2925}} {"id":100008285,"name":"printResourceClaimTemplate","signature":"func printResourceClaimTemplate(obj *resource.ResourceClaimTemplate, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printResourceClaimTemplate(obj *resource.ResourceClaimTemplate, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\trow.Cells = append(row.Cells, obj.Name, obj.Spec.Spec.ResourceClassName, string(obj.Spec.Spec.AllocationMode), translateTimestampSince(obj.CreationTimestamp))\n\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":2927,"to":2934}} {"id":100008286,"name":"printResourceClaimTemplateList","signature":"func printResourceClaimTemplateList(list *resource.ResourceClaimTemplateList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printResourceClaimTemplateList(list *resource.ResourceClaimTemplateList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printResourceClaimTemplate(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":2936,"to":2946}} {"id":100008287,"name":"printPodSchedulingContext","signature":"func printPodSchedulingContext(obj *resource.PodSchedulingContext, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printPodSchedulingContext(obj *resource.PodSchedulingContext, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\trow.Cells = append(row.Cells, obj.Name, obj.Spec.SelectedNode, translateTimestampSince(obj.CreationTimestamp))\n\n\treturn []metav1.TableRow{row}, nil\n}","line":{"from":2948,"to":2955}} {"id":100008288,"name":"printPodSchedulingContextList","signature":"func printPodSchedulingContextList(list *resource.PodSchedulingContextList, options printers.GenerateOptions) ([]metav1.TableRow, error)","file":"pkg/printers/internalversion/printers.go","code":"func printPodSchedulingContextList(list *resource.PodSchedulingContextList, options printers.GenerateOptions) ([]metav1.TableRow, error) {\n\trows := make([]metav1.TableRow, 0, len(list.Items))\n\tfor i := range list.Items {\n\t\tr, err := printPodSchedulingContext(\u0026list.Items[i], options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trows = append(rows, r...)\n\t}\n\treturn rows, nil\n}","line":{"from":2957,"to":2967}} {"id":100008289,"name":"printBoolPtr","signature":"func printBoolPtr(value *bool) string","file":"pkg/printers/internalversion/printers.go","code":"func printBoolPtr(value *bool) string {\n\tif value != nil {\n\t\treturn printBool(*value)\n\t}\n\n\treturn \"\u003cunset\u003e\"\n}","line":{"from":2969,"to":2975}} {"id":100008290,"name":"printBool","signature":"func printBool(value bool) string","file":"pkg/printers/internalversion/printers.go","code":"func printBool(value bool) string {\n\tif value {\n\t\treturn \"True\"\n\t}\n\n\treturn \"False\"\n}","line":{"from":2977,"to":2983}} {"id":100008291,"name":"Len","signature":"func (list SortableResourceNames) Len() int","file":"pkg/printers/internalversion/printers.go","code":"func (list SortableResourceNames) Len() int {\n\treturn len(list)\n}","line":{"from":2988,"to":2990}} {"id":100008292,"name":"Swap","signature":"func (list SortableResourceNames) Swap(i, j int)","file":"pkg/printers/internalversion/printers.go","code":"func (list SortableResourceNames) Swap(i, j int) {\n\tlist[i], list[j] = list[j], list[i]\n}","line":{"from":2992,"to":2994}} {"id":100008293,"name":"Less","signature":"func (list SortableResourceNames) Less(i, j int) bool","file":"pkg/printers/internalversion/printers.go","code":"func (list SortableResourceNames) Less(i, j int) bool {\n\treturn list[i] \u003c list[j]\n}","line":{"from":2996,"to":2998}} {"id":100008294,"name":"ConvertToTable","signature":"func (c TableConvertor) ConvertToTable(ctx context.Context, obj runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/printers/storage/storage.go","code":"// ConvertToTable method - converts objects to metav1.Table objects using TableGenerator\nfunc (c TableConvertor) ConvertToTable(ctx context.Context, obj runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\tnoHeaders := false\n\tif tableOptions != nil {\n\t\tswitch t := tableOptions.(type) {\n\t\tcase *metav1.TableOptions:\n\t\t\tif t != nil {\n\t\t\t\tnoHeaders = t.NoHeaders\n\t\t\t}\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unrecognized type %T for table options, can't display tabular output\", tableOptions)\n\t\t}\n\t}\n\treturn c.TableGenerator.GenerateTable(obj, printers.GenerateOptions{Wide: true, NoHeaders: noHeaders})\n}","line":{"from":33,"to":47}} {"id":100008295,"name":"NewTableGenerator","signature":"func NewTableGenerator() *HumanReadableGenerator","file":"pkg/printers/tablegenerator.go","code":"// NewTableGenerator creates a HumanReadableGenerator suitable for calling GenerateTable().\nfunc NewTableGenerator() *HumanReadableGenerator {\n\treturn \u0026HumanReadableGenerator{\n\t\thandlerMap: make(map[reflect.Type]*handlerEntry),\n\t}\n}","line":{"from":60,"to":65}} {"id":100008296,"name":"With","signature":"func (h *HumanReadableGenerator) With(fns ...func(PrintHandler)) *HumanReadableGenerator","file":"pkg/printers/tablegenerator.go","code":"// With method - accepts a list of builder functions that modify HumanReadableGenerator\nfunc (h *HumanReadableGenerator) With(fns ...func(PrintHandler)) *HumanReadableGenerator {\n\tfor _, fn := range fns {\n\t\tfn(h)\n\t}\n\treturn h\n}","line":{"from":67,"to":73}} {"id":100008297,"name":"GenerateTable","signature":"func (h *HumanReadableGenerator) GenerateTable(obj runtime.Object, options GenerateOptions) (*metav1.Table, error)","file":"pkg/printers/tablegenerator.go","code":"// GenerateTable returns a table for the provided object, using the printer registered for that type. It returns\n// a table that includes all of the information requested by options, but will not remove rows or columns. The\n// caller is responsible for applying rules related to filtering rows or columns.\nfunc (h *HumanReadableGenerator) GenerateTable(obj runtime.Object, options GenerateOptions) (*metav1.Table, error) {\n\tt := reflect.TypeOf(obj)\n\thandler, ok := h.handlerMap[t]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"no table handler registered for this type %v\", t)\n\t}\n\n\targs := []reflect.Value{reflect.ValueOf(obj), reflect.ValueOf(options)}\n\tresults := handler.printFunc.Call(args)\n\tif !results[1].IsNil() {\n\t\treturn nil, results[1].Interface().(error)\n\t}\n\n\tvar columns []metav1.TableColumnDefinition\n\tif !options.NoHeaders {\n\t\tcolumns = handler.columnDefinitions\n\t\tif !options.Wide {\n\t\t\tcolumns = make([]metav1.TableColumnDefinition, 0, len(handler.columnDefinitions))\n\t\t\tfor i := range handler.columnDefinitions {\n\t\t\t\tif handler.columnDefinitions[i].Priority != 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tcolumns = append(columns, handler.columnDefinitions[i])\n\t\t\t}\n\t\t}\n\t}\n\ttable := \u0026metav1.Table{\n\t\tListMeta: metav1.ListMeta{\n\t\t\tResourceVersion: \"\",\n\t\t},\n\t\tColumnDefinitions: columns,\n\t\tRows: results[0].Interface().([]metav1.TableRow),\n\t}\n\tif m, err := meta.ListAccessor(obj); err == nil {\n\t\ttable.ResourceVersion = m.GetResourceVersion()\n\t\ttable.Continue = m.GetContinue()\n\t\ttable.RemainingItemCount = m.GetRemainingItemCount()\n\t} else {\n\t\tif m, err := meta.CommonAccessor(obj); err == nil {\n\t\t\ttable.ResourceVersion = m.GetResourceVersion()\n\t\t}\n\t}\n\treturn table, nil\n}","line":{"from":75,"to":121}} {"id":100008298,"name":"TableHandler","signature":"func (h *HumanReadableGenerator) TableHandler(columnDefinitions []metav1.TableColumnDefinition, printFunc interface{}) error","file":"pkg/printers/tablegenerator.go","code":"// TableHandler adds a print handler with a given set of columns to HumanReadableGenerator instance.\n// See ValidateRowPrintHandlerFunc for required method signature.\nfunc (h *HumanReadableGenerator) TableHandler(columnDefinitions []metav1.TableColumnDefinition, printFunc interface{}) error {\n\tprintFuncValue := reflect.ValueOf(printFunc)\n\tif err := ValidateRowPrintHandlerFunc(printFuncValue); err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unable to register print function: %v\", err))\n\t\treturn err\n\t}\n\tentry := \u0026handlerEntry{\n\t\tcolumnDefinitions: columnDefinitions,\n\t\tprintFunc: printFuncValue,\n\t}\n\n\tobjType := printFuncValue.Type().In(0)\n\tif _, ok := h.handlerMap[objType]; ok {\n\t\terr := fmt.Errorf(\"registered duplicate printer for %v\", objType)\n\t\tutilruntime.HandleError(err)\n\t\treturn err\n\t}\n\th.handlerMap[objType] = entry\n\treturn nil\n}","line":{"from":123,"to":144}} {"id":100008299,"name":"ValidateRowPrintHandlerFunc","signature":"func ValidateRowPrintHandlerFunc(printFunc reflect.Value) error","file":"pkg/printers/tablegenerator.go","code":"// ValidateRowPrintHandlerFunc validates print handler signature.\n// printFunc is the function that will be called to print an object.\n// It must be of the following type:\n//\n//\tfunc printFunc(object ObjectType, options GenerateOptions) ([]metav1.TableRow, error)\n//\n// where ObjectType is the type of the object that will be printed, and the first\n// return value is an array of rows, with each row containing a number of cells that\n// match the number of columns defined for that printer function.\nfunc ValidateRowPrintHandlerFunc(printFunc reflect.Value) error {\n\tif printFunc.Kind() != reflect.Func {\n\t\treturn fmt.Errorf(\"invalid print handler. %#v is not a function\", printFunc)\n\t}\n\tfuncType := printFunc.Type()\n\tif funcType.NumIn() != 2 || funcType.NumOut() != 2 {\n\t\treturn fmt.Errorf(\"invalid print handler.\" +\n\t\t\t\"Must accept 2 parameters and return 2 value\")\n\t}\n\tif funcType.In(1) != reflect.TypeOf((*GenerateOptions)(nil)).Elem() ||\n\t\tfuncType.Out(0) != reflect.TypeOf((*[]metav1.TableRow)(nil)).Elem() ||\n\t\tfuncType.Out(1) != reflect.TypeOf((*error)(nil)).Elem() {\n\t\treturn fmt.Errorf(\"invalid print handler. The expected signature is: \"+\n\t\t\t\"func handler(obj %v, options GenerateOptions) ([]metav1.TableRow, error)\", funcType.In(0))\n\t}\n\treturn nil\n}","line":{"from":146,"to":171}} {"id":100008300,"name":"ProbeDialer","signature":"func ProbeDialer() *net.Dialer","file":"pkg/probe/dialer_others.go","code":"// ProbeDialer returns a dialer optimized for probes to avoid lingering sockets on TIME-WAIT state.\n// The dialer reduces the TIME-WAIT period to 1 seconds instead of the OS default of 60 seconds.\n// Using 1 second instead of 0 because SO_LINGER socket option to 0 causes pending data to be\n// discarded and the connection to be aborted with an RST rather than for the pending data to be\n// transmitted and the connection closed cleanly with a FIN.\n// Ref: https://issues.k8s.io/89898\nfunc ProbeDialer() *net.Dialer {\n\tdialer := \u0026net.Dialer{\n\t\tControl: func(network, address string, c syscall.RawConn) error {\n\t\t\treturn c.Control(func(fd uintptr) {\n\t\t\t\tsyscall.SetsockoptLinger(int(fd), syscall.SOL_SOCKET, syscall.SO_LINGER, \u0026syscall.Linger{Onoff: 1, Linger: 1})\n\t\t\t})\n\t\t},\n\t}\n\treturn dialer\n}","line":{"from":27,"to":42}} {"id":100008301,"name":"ProbeDialer","signature":"func ProbeDialer() *net.Dialer","file":"pkg/probe/dialer_windows.go","code":"// ProbeDialer returns a dialer optimized for probes to avoid lingering sockets on TIME-WAIT state.\n// The dialer reduces the TIME-WAIT period to 1 seconds instead of the OS default of 60 seconds.\n// Using 1 second instead of 0 because SO_LINGER socket option to 0 causes pending data to be\n// discarded and the connection to be aborted with an RST rather than for the pending data to be\n// transmitted and the connection closed cleanly with a FIN.\n// Ref: https://issues.k8s.io/89898\nfunc ProbeDialer() *net.Dialer {\n\tdialer := \u0026net.Dialer{\n\t\tControl: func(network, address string, c syscall.RawConn) error {\n\t\t\treturn c.Control(func(fd uintptr) {\n\t\t\t\tsyscall.SetsockoptLinger(syscall.Handle(fd), syscall.SOL_SOCKET, syscall.SO_LINGER, \u0026syscall.Linger{Onoff: 1, Linger: 1})\n\t\t\t})\n\t\t},\n\t}\n\treturn dialer\n}","line":{"from":27,"to":42}} {"id":100008302,"name":"NewTimeoutError","signature":"func NewTimeoutError(err error, timeout time.Duration) *TimeoutError","file":"pkg/probe/exec/errors.go","code":"// NewTimeoutError returns a new TimeoutError.\nfunc NewTimeoutError(err error, timeout time.Duration) *TimeoutError {\n\treturn \u0026TimeoutError{\n\t\terr: err,\n\t\ttimeout: timeout,\n\t}\n}","line":{"from":23,"to":29}} {"id":100008303,"name":"Error","signature":"func (t *TimeoutError) Error() string","file":"pkg/probe/exec/errors.go","code":"// Error returns the error string.\nfunc (t *TimeoutError) Error() string {\n\treturn t.err.Error()\n}","line":{"from":39,"to":42}} {"id":100008304,"name":"Timeout","signature":"func (t *TimeoutError) Timeout() time.Duration","file":"pkg/probe/exec/errors.go","code":"// Timeout returns the timeout duration of the exec probe.\nfunc (t *TimeoutError) Timeout() time.Duration {\n\treturn t.timeout\n}","line":{"from":44,"to":47}} {"id":100008305,"name":"New","signature":"func New() Prober","file":"pkg/probe/exec/exec.go","code":"// New creates a Prober.\nfunc New() Prober {\n\treturn execProber{}\n}","line":{"from":35,"to":38}} {"id":100008306,"name":"Probe","signature":"func (pr execProber) Probe(e exec.Cmd) (probe.Result, string, error)","file":"pkg/probe/exec/exec.go","code":"// Probe executes a command to check the liveness/readiness of container\n// from executing a command. Returns the Result status, command output, and\n// errors if any.\nfunc (pr execProber) Probe(e exec.Cmd) (probe.Result, string, error) {\n\tvar dataBuffer bytes.Buffer\n\twriter := ioutils.LimitWriter(\u0026dataBuffer, maxReadLength)\n\n\te.SetStderr(writer)\n\te.SetStdout(writer)\n\terr := e.Start()\n\tif err == nil {\n\t\terr = e.Wait()\n\t}\n\tdata := dataBuffer.Bytes()\n\n\tklog.V(4).Infof(\"Exec probe response: %q\", string(data))\n\tif err != nil {\n\t\texit, ok := err.(exec.ExitError)\n\t\tif ok {\n\t\t\tif exit.ExitStatus() == 0 {\n\t\t\t\treturn probe.Success, string(data), nil\n\t\t\t}\n\t\t\treturn probe.Failure, string(data), nil\n\t\t}\n\n\t\ttimeoutErr, ok := err.(*TimeoutError)\n\t\tif ok {\n\t\t\tif utilfeature.DefaultFeatureGate.Enabled(features.ExecProbeTimeout) {\n\t\t\t\t// When exec probe timeout, data is empty, so we should return timeoutErr.Error() as the stdout.\n\t\t\t\treturn probe.Failure, timeoutErr.Error(), nil\n\t\t\t}\n\n\t\t\tklog.Warningf(\"Exec probe timed out after %s but ExecProbeTimeout feature gate was disabled\", timeoutErr.Timeout())\n\t\t}\n\n\t\treturn probe.Unknown, \"\", err\n\t}\n\treturn probe.Success, string(data), nil\n}","line":{"from":47,"to":85}} {"id":100008307,"name":"New","signature":"func New() Prober","file":"pkg/probe/grpc/grpc.go","code":"// New Prober for execute grpc probe\nfunc New() Prober {\n\treturn grpcProber{}\n}","line":{"from":44,"to":47}} {"id":100008308,"name":"Probe","signature":"func (p grpcProber) Probe(host, service string, port int, timeout time.Duration) (probe.Result, string, error)","file":"pkg/probe/grpc/grpc.go","code":"// Probe executes a grpc call to check the liveness/readiness/startup of container.\n// Returns the Result status, command output, and errors if any.\n// Any failure is considered as a probe failure to mimic grpc_health_probe tool behavior.\n// err is always nil\nfunc (p grpcProber) Probe(host, service string, port int, timeout time.Duration) (probe.Result, string, error) {\n\tv := version.Get()\n\n\topts := []grpc.DialOption{\n\t\tgrpc.WithUserAgent(fmt.Sprintf(\"kube-probe/%s.%s\", v.Major, v.Minor)),\n\t\tgrpc.WithBlock(),\n\t\tgrpc.WithTransportCredentials(insecure.NewCredentials()), //credentials are currently not supported\n\t\tgrpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) {\n\t\t\treturn probe.ProbeDialer().DialContext(ctx, \"tcp\", addr)\n\t\t}),\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\n\tdefer cancel()\n\n\taddr := net.JoinHostPort(host, fmt.Sprintf(\"%d\", port))\n\tconn, err := grpc.DialContext(ctx, addr, opts...)\n\n\tif err != nil {\n\t\tif err == context.DeadlineExceeded {\n\t\t\tklog.V(4).ErrorS(err, \"failed to connect grpc service due to timeout\", \"addr\", addr, \"service\", service, \"timeout\", timeout)\n\t\t\treturn probe.Failure, fmt.Sprintf(\"timeout: failed to connect service %q within %v: %+v\", addr, timeout, err), nil\n\t\t} else {\n\t\t\tklog.V(4).ErrorS(err, \"failed to connect grpc service\", \"service\", addr)\n\t\t\treturn probe.Failure, fmt.Sprintf(\"error: failed to connect service at %q: %+v\", addr, err), nil\n\t\t}\n\t}\n\n\tdefer func() {\n\t\t_ = conn.Close()\n\t}()\n\n\tclient := grpchealth.NewHealthClient(conn)\n\n\tresp, err := client.Check(metadata.NewOutgoingContext(ctx, make(metadata.MD)), \u0026grpchealth.HealthCheckRequest{\n\t\tService: service,\n\t})\n\n\tif err != nil {\n\t\tstat, ok := status.FromError(err)\n\t\tif ok {\n\t\t\tswitch stat.Code() {\n\t\t\tcase codes.Unimplemented:\n\t\t\t\tklog.V(4).ErrorS(err, \"server does not implement the grpc health protocol (grpc.health.v1.Health)\", \"addr\", addr, \"service\", service)\n\t\t\t\treturn probe.Failure, fmt.Sprintf(\"error: this server does not implement the grpc health protocol (grpc.health.v1.Health): %s\", stat.Message()), nil\n\t\t\tcase codes.DeadlineExceeded:\n\t\t\t\tklog.V(4).ErrorS(err, \"rpc request not finished within timeout\", \"addr\", addr, \"service\", service, \"timeout\", timeout)\n\t\t\t\treturn probe.Failure, fmt.Sprintf(\"timeout: health rpc did not complete within %v\", timeout), nil\n\t\t\tdefault:\n\t\t\t\tklog.V(4).ErrorS(err, \"rpc probe failed\")\n\t\t\t}\n\t\t} else {\n\t\t\tklog.V(4).ErrorS(err, \"health rpc probe failed\")\n\t\t}\n\n\t\treturn probe.Failure, fmt.Sprintf(\"error: health rpc probe failed: %+v\", err), nil\n\t}\n\n\tif resp.GetStatus() != grpchealth.HealthCheckResponse_SERVING {\n\t\treturn probe.Failure, fmt.Sprintf(\"service unhealthy (responded with %q)\", resp.GetStatus().String()), nil\n\t}\n\n\treturn probe.Success, fmt.Sprintf(\"service healthy\"), nil\n}","line":{"from":49,"to":117}} {"id":100008309,"name":"New","signature":"func New(followNonLocalRedirects bool) Prober","file":"pkg/probe/http/http.go","code":"// New creates Prober that will skip TLS verification while probing.\n// followNonLocalRedirects configures whether the prober should follow redirects to a different hostname.\n// If disabled, redirects to other hosts will trigger a warning result.\nfunc New(followNonLocalRedirects bool) Prober {\n\ttlsConfig := \u0026tls.Config{InsecureSkipVerify: true}\n\treturn NewWithTLSConfig(tlsConfig, followNonLocalRedirects)\n}","line":{"from":37,"to":43}} {"id":100008310,"name":"NewWithTLSConfig","signature":"func NewWithTLSConfig(config *tls.Config, followNonLocalRedirects bool) Prober","file":"pkg/probe/http/http.go","code":"// NewWithTLSConfig takes tls config as parameter.\n// followNonLocalRedirects configures whether the prober should follow redirects to a different hostname.\n// If disabled, redirects to other hosts will trigger a warning result.\nfunc NewWithTLSConfig(config *tls.Config, followNonLocalRedirects bool) Prober {\n\t// We do not want the probe use node's local proxy set.\n\ttransport := utilnet.SetTransportDefaults(\n\t\t\u0026http.Transport{\n\t\t\tTLSClientConfig: config,\n\t\t\tDisableKeepAlives: true,\n\t\t\tProxy: http.ProxyURL(nil),\n\t\t\tDisableCompression: true, // removes Accept-Encoding header\n\t\t\t// DialContext creates unencrypted TCP connections\n\t\t\t// and is also used by the transport for HTTPS connection\n\t\t\tDialContext: probe.ProbeDialer().DialContext,\n\t\t})\n\n\treturn httpProber{transport, followNonLocalRedirects}\n}","line":{"from":45,"to":62}} {"id":100008311,"name":"Probe","signature":"func (pr httpProber) Probe(req *http.Request, timeout time.Duration) (probe.Result, string, error)","file":"pkg/probe/http/http.go","code":"// Probe returns a ProbeRunner capable of running an HTTP check.\nfunc (pr httpProber) Probe(req *http.Request, timeout time.Duration) (probe.Result, string, error) {\n\tclient := \u0026http.Client{\n\t\tTimeout: timeout,\n\t\tTransport: pr.transport,\n\t\tCheckRedirect: RedirectChecker(pr.followNonLocalRedirects),\n\t}\n\treturn DoHTTPProbe(req, client)\n}","line":{"from":74,"to":82}} {"id":100008312,"name":"DoHTTPProbe","signature":"func DoHTTPProbe(req *http.Request, client GetHTTPInterface) (probe.Result, string, error)","file":"pkg/probe/http/http.go","code":"// DoHTTPProbe checks if a GET request to the url succeeds.\n// If the HTTP response code is successful (i.e. 400 \u003e code \u003e= 200), it returns Success.\n// If the HTTP response code is unsuccessful or HTTP communication fails, it returns Failure.\n// This is exported because some other packages may want to do direct HTTP probes.\nfunc DoHTTPProbe(req *http.Request, client GetHTTPInterface) (probe.Result, string, error) {\n\turl := req.URL\n\theaders := req.Header\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\t// Convert errors into failures to catch timeouts.\n\t\treturn probe.Failure, err.Error(), nil\n\t}\n\tdefer res.Body.Close()\n\tb, err := utilio.ReadAtMost(res.Body, maxRespBodyLength)\n\tif err != nil {\n\t\tif err == utilio.ErrLimitReached {\n\t\t\tklog.V(4).Infof(\"Non fatal body truncation for %s, Response: %v\", url.String(), *res)\n\t\t} else {\n\t\t\treturn probe.Failure, \"\", err\n\t\t}\n\t}\n\tbody := string(b)\n\tif res.StatusCode \u003e= http.StatusOK \u0026\u0026 res.StatusCode \u003c http.StatusBadRequest {\n\t\tif res.StatusCode \u003e= http.StatusMultipleChoices { // Redirect\n\t\t\tklog.V(4).Infof(\"Probe terminated redirects for %s, Response: %v\", url.String(), *res)\n\t\t\treturn probe.Warning, fmt.Sprintf(\"Probe terminated redirects, Response body: %v\", body), nil\n\t\t}\n\t\tklog.V(4).Infof(\"Probe succeeded for %s, Response: %v\", url.String(), *res)\n\t\treturn probe.Success, body, nil\n\t}\n\tklog.V(4).Infof(\"Probe failed for %s with request headers %v, response body: %v\", url.String(), headers, body)\n\t// Note: Until https://issue.k8s.io/99425 is addressed, this user-facing failure message must not contain the response body.\n\tfailureMsg := fmt.Sprintf(\"HTTP probe failed with statuscode: %d\", res.StatusCode)\n\treturn probe.Failure, failureMsg, nil\n}","line":{"from":89,"to":123}} {"id":100008313,"name":"RedirectChecker","signature":"func RedirectChecker(followNonLocalRedirects bool) func(*http.Request, []*http.Request) error","file":"pkg/probe/http/http.go","code":"// RedirectChecker returns a function that can be used to check HTTP redirects.\nfunc RedirectChecker(followNonLocalRedirects bool) func(*http.Request, []*http.Request) error {\n\tif followNonLocalRedirects {\n\t\treturn nil // Use the default http client checker.\n\t}\n\n\treturn func(req *http.Request, via []*http.Request) error {\n\t\tif req.URL.Hostname() != via[0].URL.Hostname() {\n\t\t\treturn http.ErrUseLastResponse\n\t\t}\n\t\t// Default behavior: stop after 10 redirects.\n\t\tif len(via) \u003e= 10 {\n\t\t\treturn errors.New(\"stopped after 10 redirects\")\n\t\t}\n\t\treturn nil\n\t}\n}","line":{"from":125,"to":141}} {"id":100008314,"name":"NewProbeRequest","signature":"func NewProbeRequest(url *url.URL, headers http.Header) (*http.Request, error)","file":"pkg/probe/http/request.go","code":"// NewProbeRequest returns an http.Request suitable for use as a request for a\n// probe.\nfunc NewProbeRequest(url *url.URL, headers http.Header) (*http.Request, error) {\n\treturn newProbeRequest(url, headers, \"probe\")\n}","line":{"from":32,"to":36}} {"id":100008315,"name":"NewRequestForHTTPGetAction","signature":"func NewRequestForHTTPGetAction(httpGet *v1.HTTPGetAction, container *v1.Container, podIP string, userAgentFragment string) (*http.Request, error)","file":"pkg/probe/http/request.go","code":"// NewRequestForHTTPGetAction returns an http.Request derived from httpGet.\n// When httpGet.Host is empty, podIP will be used instead.\nfunc NewRequestForHTTPGetAction(httpGet *v1.HTTPGetAction, container *v1.Container, podIP string, userAgentFragment string) (*http.Request, error) {\n\tscheme := strings.ToLower(string(httpGet.Scheme))\n\tif scheme == \"\" {\n\t\tscheme = \"http\"\n\t}\n\n\thost := httpGet.Host\n\tif host == \"\" {\n\t\thost = podIP\n\t}\n\n\tport, err := probe.ResolveContainerPort(httpGet.Port, container)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpath := httpGet.Path\n\turl := formatURL(scheme, host, port, path)\n\theaders := v1HeaderToHTTPHeader(httpGet.HTTPHeaders)\n\n\treturn newProbeRequest(url, headers, userAgentFragment)\n}","line":{"from":38,"to":61}} {"id":100008316,"name":"newProbeRequest","signature":"func newProbeRequest(url *url.URL, headers http.Header, userAgentFragment string) (*http.Request, error)","file":"pkg/probe/http/request.go","code":"func newProbeRequest(url *url.URL, headers http.Header, userAgentFragment string) (*http.Request, error) {\n\treq, err := http.NewRequest(\"GET\", url.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif headers == nil {\n\t\theaders = http.Header{}\n\t}\n\tif _, ok := headers[\"User-Agent\"]; !ok {\n\t\t// User-Agent header was not defined, set it\n\t\theaders.Set(\"User-Agent\", userAgent(userAgentFragment))\n\t}\n\tif _, ok := headers[\"Accept\"]; !ok {\n\t\t// Accept header was not defined. accept all\n\t\theaders.Set(\"Accept\", \"*/*\")\n\t} else if headers.Get(\"Accept\") == \"\" {\n\t\t// Accept header was overridden but is empty. removing\n\t\theaders.Del(\"Accept\")\n\t}\n\treq.Header = headers\n\treq.Host = headers.Get(\"Host\")\n\n\treturn req, nil\n}","line":{"from":63,"to":87}} {"id":100008317,"name":"userAgent","signature":"func userAgent(purpose string) string","file":"pkg/probe/http/request.go","code":"func userAgent(purpose string) string {\n\tv := version.Get()\n\treturn fmt.Sprintf(\"kube-%s/%s.%s\", purpose, v.Major, v.Minor)\n}","line":{"from":89,"to":92}} {"id":100008318,"name":"formatURL","signature":"func formatURL(scheme string, host string, port int, path string) *url.URL","file":"pkg/probe/http/request.go","code":"// formatURL formats a URL from args. For testability.\nfunc formatURL(scheme string, host string, port int, path string) *url.URL {\n\tu, err := url.Parse(path)\n\t// Something is busted with the path, but it's too late to reject it. Pass it along as is.\n\t//\n\t// This construction of a URL may be wrong in some cases, but it preserves\n\t// legacy prober behavior.\n\tif err != nil {\n\t\tu = \u0026url.URL{\n\t\t\tPath: path,\n\t\t}\n\t}\n\tu.Scheme = scheme\n\tu.Host = net.JoinHostPort(host, strconv.Itoa(port))\n\treturn u\n}","line":{"from":94,"to":109}} {"id":100008319,"name":"v1HeaderToHTTPHeader","signature":"func v1HeaderToHTTPHeader(headerList []v1.HTTPHeader) http.Header","file":"pkg/probe/http/request.go","code":"// v1HeaderToHTTPHeader takes a list of HTTPHeader \u003cname, value\u003e string pairs\n// and returns a populated string-\u003e[]string http.Header map.\nfunc v1HeaderToHTTPHeader(headerList []v1.HTTPHeader) http.Header {\n\theaders := make(http.Header)\n\tfor _, header := range headerList {\n\t\theaders.Add(header.Name, header.Value)\n\t}\n\treturn headers\n}","line":{"from":111,"to":119}} {"id":100008320,"name":"New","signature":"func New() Prober","file":"pkg/probe/tcp/tcp.go","code":"// New creates Prober.\nfunc New() Prober {\n\treturn tcpProber{}\n}","line":{"from":29,"to":32}} {"id":100008321,"name":"Probe","signature":"func (pr tcpProber) Probe(host string, port int, timeout time.Duration) (probe.Result, string, error)","file":"pkg/probe/tcp/tcp.go","code":"// Probe checks that a TCP connection to the address can be opened.\nfunc (pr tcpProber) Probe(host string, port int, timeout time.Duration) (probe.Result, string, error) {\n\treturn DoTCPProbe(net.JoinHostPort(host, strconv.Itoa(port)), timeout)\n}","line":{"from":41,"to":44}} {"id":100008322,"name":"DoTCPProbe","signature":"func DoTCPProbe(addr string, timeout time.Duration) (probe.Result, string, error)","file":"pkg/probe/tcp/tcp.go","code":"// DoTCPProbe checks that a TCP socket to the address can be opened.\n// If the socket can be opened, it returns Success\n// If the socket fails to open, it returns Failure.\n// This is exported because some other packages may want to do direct TCP probes.\nfunc DoTCPProbe(addr string, timeout time.Duration) (probe.Result, string, error) {\n\td := probe.ProbeDialer()\n\td.Timeout = timeout\n\tconn, err := d.Dial(\"tcp\", addr)\n\tif err != nil {\n\t\t// Convert errors to failures to handle timeouts.\n\t\treturn probe.Failure, err.Error(), nil\n\t}\n\terr = conn.Close()\n\tif err != nil {\n\t\tklog.Errorf(\"Unexpected error closing TCP probe socket: %v (%#v)\", err, err)\n\t}\n\treturn probe.Success, \"\", nil\n}","line":{"from":46,"to":63}} {"id":100008323,"name":"ResolveContainerPort","signature":"func ResolveContainerPort(param intstr.IntOrString, container *v1.Container) (int, error)","file":"pkg/probe/util.go","code":"func ResolveContainerPort(param intstr.IntOrString, container *v1.Container) (int, error) {\n\tport := -1\n\tvar err error\n\tswitch param.Type {\n\tcase intstr.Int:\n\t\tport = param.IntValue()\n\tcase intstr.String:\n\t\tif port, err = findPortByName(container, param.StrVal); err != nil {\n\t\t\t// Last ditch effort - maybe it was an int stored as string?\n\t\t\tif port, err = strconv.Atoi(param.StrVal); err != nil {\n\t\t\t\treturn port, err\n\t\t\t}\n\t\t}\n\tdefault:\n\t\treturn port, fmt.Errorf(\"intOrString had no kind: %+v\", param)\n\t}\n\tif port \u003e 0 \u0026\u0026 port \u003c 65536 {\n\t\treturn port, nil\n\t}\n\treturn port, fmt.Errorf(\"invalid port number: %v\", port)\n}","line":{"from":27,"to":47}} {"id":100008324,"name":"findPortByName","signature":"func findPortByName(container *v1.Container, portName string) (int, error)","file":"pkg/probe/util.go","code":"// findPortByName is a helper function to look up a port in a container by name.\nfunc findPortByName(container *v1.Container, portName string) (int, error) {\n\tfor _, port := range container.Ports {\n\t\tif port.Name == portName {\n\t\t\treturn int(port.ContainerPort), nil\n\t\t}\n\t}\n\treturn 0, fmt.Errorf(\"port %s not found\", portName)\n}","line":{"from":49,"to":57}} {"id":100008325,"name":"Funcs","signature":"func Funcs(codecs runtimeserializer.CodecFactory) []interface{}","file":"pkg/proxy/apis/config/fuzzer/fuzzer.go","code":"// Funcs returns the fuzzer functions for the kube-proxy apis.\nfunc Funcs(codecs runtimeserializer.CodecFactory) []interface{} {\n\treturn []interface{}{\n\t\tfunc(obj *kubeproxyconfig.KubeProxyConfiguration, c fuzz.Continue) {\n\t\t\tc.FuzzNoCustom(obj)\n\t\t\tobj.BindAddress = fmt.Sprintf(\"%d.%d.%d.%d\", c.Intn(256), c.Intn(256), c.Intn(256), c.Intn(256))\n\t\t\tobj.ClientConnection.ContentType = c.RandString()\n\t\t\tobj.Conntrack.MaxPerCore = pointer.Int32(c.Int31())\n\t\t\tobj.Conntrack.Min = pointer.Int32(c.Int31())\n\t\t\tobj.Conntrack.TCPCloseWaitTimeout = \u0026metav1.Duration{Duration: time.Duration(c.Int63()) * time.Hour}\n\t\t\tobj.Conntrack.TCPEstablishedTimeout = \u0026metav1.Duration{Duration: time.Duration(c.Int63()) * time.Hour}\n\t\t\tobj.FeatureGates = map[string]bool{c.RandString(): true}\n\t\t\tobj.HealthzBindAddress = fmt.Sprintf(\"%d.%d.%d.%d:%d\", c.Intn(256), c.Intn(256), c.Intn(256), c.Intn(256), c.Intn(65536))\n\t\t\tobj.IPTables.MasqueradeBit = pointer.Int32(c.Int31())\n\t\t\tobj.IPTables.LocalhostNodePorts = pointer.Bool(c.RandBool())\n\t\t\tobj.MetricsBindAddress = fmt.Sprintf(\"%d.%d.%d.%d:%d\", c.Intn(256), c.Intn(256), c.Intn(256), c.Intn(256), c.Intn(65536))\n\t\t\tobj.OOMScoreAdj = pointer.Int32(c.Int31())\n\t\t\tobj.ClientConnection.ContentType = \"bar\"\n\t\t\tobj.NodePortAddresses = []string{\"1.2.3.0/24\"}\n\t\t},\n\t}\n}","line":{"from":31,"to":52}} {"id":100008326,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/proxy/apis/config/register.go","code":"// addKnownTypes registers known types to the given scheme\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026KubeProxyConfiguration{},\n\t)\n\treturn nil\n}","line":{"from":37,"to":43}} {"id":100008327,"name":"init","signature":"func init()","file":"pkg/proxy/apis/config/scheme/scheme.go","code":"func init() {\n\tAddToScheme(Scheme)\n}","line":{"from":35,"to":37}} {"id":100008328,"name":"AddToScheme","signature":"func AddToScheme(scheme *runtime.Scheme)","file":"pkg/proxy/apis/config/scheme/scheme.go","code":"// AddToScheme adds the types of this group into the given scheme.\nfunc AddToScheme(scheme *runtime.Scheme) {\n\tutilruntime.Must(v1alpha1.AddToScheme(scheme))\n\tutilruntime.Must(config.AddToScheme(scheme))\n}","line":{"from":39,"to":43}} {"id":100008329,"name":"Set","signature":"func (m *ProxyMode) Set(s string) error","file":"pkg/proxy/apis/config/types.go","code":"func (m *ProxyMode) Set(s string) error {\n\t*m = ProxyMode(s)\n\treturn nil\n}","line":{"from":221,"to":224}} {"id":100008330,"name":"String","signature":"func (m *ProxyMode) String() string","file":"pkg/proxy/apis/config/types.go","code":"func (m *ProxyMode) String() string {\n\tif m != nil {\n\t\treturn string(*m)\n\t}\n\treturn \"\"\n}","line":{"from":226,"to":231}} {"id":100008331,"name":"Type","signature":"func (m *ProxyMode) Type() string","file":"pkg/proxy/apis/config/types.go","code":"func (m *ProxyMode) Type() string {\n\treturn \"ProxyMode\"\n}","line":{"from":233,"to":235}} {"id":100008332,"name":"Set","signature":"func (m *LocalMode) Set(s string) error","file":"pkg/proxy/apis/config/types.go","code":"func (m *LocalMode) Set(s string) error {\n\t*m = LocalMode(s)\n\treturn nil\n}","line":{"from":237,"to":240}} {"id":100008333,"name":"String","signature":"func (m *LocalMode) String() string","file":"pkg/proxy/apis/config/types.go","code":"func (m *LocalMode) String() string {\n\tif m != nil {\n\t\treturn string(*m)\n\t}\n\treturn \"\"\n}","line":{"from":242,"to":247}} {"id":100008334,"name":"Type","signature":"func (m *LocalMode) Type() string","file":"pkg/proxy/apis/config/types.go","code":"func (m *LocalMode) Type() string {\n\treturn \"LocalMode\"\n}","line":{"from":249,"to":251}} {"id":100008335,"name":"String","signature":"func (m *ConfigurationMap) String() string","file":"pkg/proxy/apis/config/types.go","code":"func (m *ConfigurationMap) String() string {\n\tpairs := []string{}\n\tfor k, v := range *m {\n\t\tpairs = append(pairs, fmt.Sprintf(\"%s=%s\", k, v))\n\t}\n\tsort.Strings(pairs)\n\treturn strings.Join(pairs, \",\")\n}","line":{"from":255,"to":262}} {"id":100008336,"name":"Set","signature":"func (m *ConfigurationMap) Set(value string) error","file":"pkg/proxy/apis/config/types.go","code":"func (m *ConfigurationMap) Set(value string) error {\n\tfor _, s := range strings.Split(value, \",\") {\n\t\tif len(s) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tarr := strings.SplitN(s, \"=\", 2)\n\t\tif len(arr) == 2 {\n\t\t\t(*m)[strings.TrimSpace(arr[0])] = strings.TrimSpace(arr[1])\n\t\t} else {\n\t\t\t(*m)[strings.TrimSpace(arr[0])] = \"\"\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":264,"to":277}} {"id":100008337,"name":"Type","signature":"func (*ConfigurationMap) Type() string","file":"pkg/proxy/apis/config/types.go","code":"func (*ConfigurationMap) Type() string {\n\treturn \"mapStringString\"\n}","line":{"from":279,"to":281}} {"id":100008338,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *kruntime.Scheme) error","file":"pkg/proxy/apis/config/v1alpha1/defaults.go","code":"func addDefaultingFuncs(scheme *kruntime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":34,"to":36}} {"id":100008339,"name":"SetDefaults_KubeProxyConfiguration","signature":"func SetDefaults_KubeProxyConfiguration(obj *kubeproxyconfigv1alpha1.KubeProxyConfiguration)","file":"pkg/proxy/apis/config/v1alpha1/defaults.go","code":"func SetDefaults_KubeProxyConfiguration(obj *kubeproxyconfigv1alpha1.KubeProxyConfiguration) {\n\n\tif len(obj.BindAddress) == 0 {\n\t\tobj.BindAddress = \"0.0.0.0\"\n\t}\n\n\tdefaultHealthzAddress, defaultMetricsAddress := getDefaultAddresses(obj.BindAddress)\n\n\tif obj.HealthzBindAddress == \"\" {\n\t\tobj.HealthzBindAddress = fmt.Sprintf(\"%s:%v\", defaultHealthzAddress, ports.ProxyHealthzPort)\n\t} else {\n\t\tobj.HealthzBindAddress = proxyutil.AppendPortIfNeeded(obj.HealthzBindAddress, ports.ProxyHealthzPort)\n\t}\n\tif obj.MetricsBindAddress == \"\" {\n\t\tobj.MetricsBindAddress = fmt.Sprintf(\"%s:%v\", defaultMetricsAddress, ports.ProxyStatusPort)\n\t} else {\n\t\tobj.MetricsBindAddress = proxyutil.AppendPortIfNeeded(obj.MetricsBindAddress, ports.ProxyStatusPort)\n\t}\n\n\tif obj.OOMScoreAdj == nil {\n\t\ttemp := int32(qos.KubeProxyOOMScoreAdj)\n\t\tobj.OOMScoreAdj = \u0026temp\n\t}\n\tif obj.IPTables.SyncPeriod.Duration == 0 {\n\t\tobj.IPTables.SyncPeriod = metav1.Duration{Duration: 30 * time.Second}\n\t}\n\tif obj.IPTables.MinSyncPeriod.Duration == 0 {\n\t\tobj.IPTables.MinSyncPeriod = metav1.Duration{Duration: 1 * time.Second}\n\t}\n\tif obj.IPTables.LocalhostNodePorts == nil {\n\t\tobj.IPTables.LocalhostNodePorts = pointer.Bool(true)\n\t}\n\tif obj.IPVS.SyncPeriod.Duration == 0 {\n\t\tobj.IPVS.SyncPeriod = metav1.Duration{Duration: 30 * time.Second}\n\t}\n\n\tif obj.Conntrack.MaxPerCore == nil {\n\t\tobj.Conntrack.MaxPerCore = pointer.Int32(32 * 1024)\n\t}\n\tif obj.Conntrack.Min == nil {\n\t\tobj.Conntrack.Min = pointer.Int32(128 * 1024)\n\t}\n\n\tif obj.IPTables.MasqueradeBit == nil {\n\t\ttemp := int32(14)\n\t\tobj.IPTables.MasqueradeBit = \u0026temp\n\t}\n\tif obj.Conntrack.TCPEstablishedTimeout == nil {\n\t\tobj.Conntrack.TCPEstablishedTimeout = \u0026metav1.Duration{Duration: 24 * time.Hour} // 1 day (1/5 default)\n\t}\n\tif obj.Conntrack.TCPCloseWaitTimeout == nil {\n\t\t// See https://github.com/kubernetes/kubernetes/issues/32551.\n\t\t//\n\t\t// CLOSE_WAIT conntrack state occurs when the Linux kernel\n\t\t// sees a FIN from the remote server. Note: this is a half-close\n\t\t// condition that persists as long as the local side keeps the\n\t\t// socket open. The condition is rare as it is typical in most\n\t\t// protocols for both sides to issue a close; this typically\n\t\t// occurs when the local socket is lazily garbage collected.\n\t\t//\n\t\t// If the CLOSE_WAIT conntrack entry expires, then FINs from the\n\t\t// local socket will not be properly SNAT'd and will not reach the\n\t\t// remote server (if the connection was subject to SNAT). If the\n\t\t// remote timeouts for FIN_WAIT* states exceed the CLOSE_WAIT\n\t\t// timeout, then there will be an inconsistency in the state of\n\t\t// the connection and a new connection reusing the SNAT (src,\n\t\t// port) pair may be rejected by the remote side with RST. This\n\t\t// can cause new calls to connect(2) to return with ECONNREFUSED.\n\t\t//\n\t\t// We set CLOSE_WAIT to one hour by default to better match\n\t\t// typical server timeouts.\n\t\tobj.Conntrack.TCPCloseWaitTimeout = \u0026metav1.Duration{Duration: 1 * time.Hour}\n\t}\n\tif obj.ConfigSyncPeriod.Duration == 0 {\n\t\tobj.ConfigSyncPeriod.Duration = 15 * time.Minute\n\t}\n\n\tif len(obj.ClientConnection.ContentType) == 0 {\n\t\tobj.ClientConnection.ContentType = \"application/vnd.kubernetes.protobuf\"\n\t}\n\tif obj.ClientConnection.QPS == 0.0 {\n\t\tobj.ClientConnection.QPS = 5.0\n\t}\n\tif obj.ClientConnection.Burst == 0 {\n\t\tobj.ClientConnection.Burst = 10\n\t}\n\tif obj.FeatureGates == nil {\n\t\tobj.FeatureGates = make(map[string]bool)\n\t}\n}","line":{"from":38,"to":127}} {"id":100008340,"name":"getDefaultAddresses","signature":"func getDefaultAddresses(bindAddress string) (defaultHealthzAddress, defaultMetricsAddress string)","file":"pkg/proxy/apis/config/v1alpha1/defaults.go","code":"// getDefaultAddresses returns default address of healthz and metrics server\n// based on the given bind address. IPv6 addresses are enclosed in square\n// brackets for appending port.\nfunc getDefaultAddresses(bindAddress string) (defaultHealthzAddress, defaultMetricsAddress string) {\n\tif netutils.ParseIPSloppy(bindAddress).To4() != nil {\n\t\treturn \"0.0.0.0\", \"127.0.0.1\"\n\t}\n\treturn \"[::]\", \"[::1]\"\n}","line":{"from":129,"to":137}} {"id":100008341,"name":"init","signature":"func init()","file":"pkg/proxy/apis/config/v1alpha1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":38,"to":43}} {"id":100008342,"name":"Validate","signature":"func Validate(config *kubeproxyconfig.KubeProxyConfiguration) field.ErrorList","file":"pkg/proxy/apis/config/validation/validation.go","code":"// Validate validates the configuration of kube-proxy\nfunc Validate(config *kubeproxyconfig.KubeProxyConfiguration) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tnewPath := field.NewPath(\"KubeProxyConfiguration\")\n\n\teffectiveFeatures := utilfeature.DefaultFeatureGate.DeepCopy()\n\tif err := effectiveFeatures.SetFromMap(config.FeatureGates); err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(newPath.Child(\"featureGates\"), config.FeatureGates, err.Error()))\n\t}\n\n\tallErrs = append(allErrs, validateKubeProxyIPTablesConfiguration(config.IPTables, newPath.Child(\"KubeProxyIPTablesConfiguration\"))...)\n\tif config.Mode == kubeproxyconfig.ProxyModeIPVS {\n\t\tallErrs = append(allErrs, validateKubeProxyIPVSConfiguration(config.IPVS, newPath.Child(\"KubeProxyIPVSConfiguration\"))...)\n\t}\n\tallErrs = append(allErrs, validateKubeProxyConntrackConfiguration(config.Conntrack, newPath.Child(\"KubeProxyConntrackConfiguration\"))...)\n\tallErrs = append(allErrs, validateProxyMode(config.Mode, newPath.Child(\"Mode\"))...)\n\tallErrs = append(allErrs, validateClientConnectionConfiguration(config.ClientConnection, newPath.Child(\"ClientConnection\"))...)\n\n\tif config.OOMScoreAdj != nil \u0026\u0026 (*config.OOMScoreAdj \u003c -1000 || *config.OOMScoreAdj \u003e 1000) {\n\t\tallErrs = append(allErrs, field.Invalid(newPath.Child(\"OOMScoreAdj\"), *config.OOMScoreAdj, \"must be within the range [-1000, 1000]\"))\n\t}\n\n\tif config.ConfigSyncPeriod.Duration \u003c= 0 {\n\t\tallErrs = append(allErrs, field.Invalid(newPath.Child(\"ConfigSyncPeriod\"), config.ConfigSyncPeriod, \"must be greater than 0\"))\n\t}\n\n\tif netutils.ParseIPSloppy(config.BindAddress) == nil {\n\t\tallErrs = append(allErrs, field.Invalid(newPath.Child(\"BindAddress\"), config.BindAddress, \"not a valid textual representation of an IP address\"))\n\t}\n\n\tif config.HealthzBindAddress != \"\" {\n\t\tallErrs = append(allErrs, validateHostPort(config.HealthzBindAddress, newPath.Child(\"HealthzBindAddress\"))...)\n\t}\n\tallErrs = append(allErrs, validateHostPort(config.MetricsBindAddress, newPath.Child(\"MetricsBindAddress\"))...)\n\n\tif config.ClusterCIDR != \"\" {\n\t\tcidrs := strings.Split(config.ClusterCIDR, \",\")\n\t\tswitch {\n\t\tcase len(cidrs) \u003e 2:\n\t\t\tallErrs = append(allErrs, field.Invalid(newPath.Child(\"ClusterCIDR\"), config.ClusterCIDR, \"only one CIDR allowed or a valid DualStack CIDR (e.g. 10.100.0.0/16,fde4:8dba:82e1::/48)\"))\n\t\t// if DualStack and two cidrs validate if there is at least one of each IP family\n\t\tcase len(cidrs) == 2:\n\t\t\tisDual, err := netutils.IsDualStackCIDRStrings(cidrs)\n\t\t\tif err != nil || !isDual {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(newPath.Child(\"ClusterCIDR\"), config.ClusterCIDR, \"must be a valid DualStack CIDR (e.g. 10.100.0.0/16,fde4:8dba:82e1::/48)\"))\n\t\t\t}\n\t\t// if we are here means that len(cidrs) == 1, we need to validate it\n\t\tdefault:\n\t\t\tif _, _, err := netutils.ParseCIDRSloppy(config.ClusterCIDR); err != nil {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(newPath.Child(\"ClusterCIDR\"), config.ClusterCIDR, \"must be a valid CIDR block (e.g. 10.100.0.0/16 or fde4:8dba:82e1::/48)\"))\n\t\t\t}\n\t\t}\n\t}\n\n\tif _, err := utilnet.ParsePortRange(config.PortRange); err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(newPath.Child(\"PortRange\"), config.PortRange, \"must be a valid port range (e.g. 300-2000)\"))\n\t}\n\n\tallErrs = append(allErrs, validateKubeProxyNodePortAddress(config.NodePortAddresses, newPath.Child(\"NodePortAddresses\"))...)\n\tallErrs = append(allErrs, validateShowHiddenMetricsVersion(config.ShowHiddenMetricsForVersion, newPath.Child(\"ShowHiddenMetricsForVersion\"))...)\n\tif config.DetectLocalMode == kubeproxyconfig.LocalModeBridgeInterface {\n\t\tallErrs = append(allErrs, validateInterface(config.DetectLocal.BridgeInterface, newPath.Child(\"InterfaceName\"))...)\n\t}\n\tif config.DetectLocalMode == kubeproxyconfig.LocalModeInterfaceNamePrefix {\n\t\tallErrs = append(allErrs, validateInterface(config.DetectLocal.InterfaceNamePrefix, newPath.Child(\"InterfacePrefix\"))...)\n\t}\n\n\treturn allErrs\n}","line":{"from":37,"to":106}} {"id":100008343,"name":"validateKubeProxyIPTablesConfiguration","signature":"func validateKubeProxyIPTablesConfiguration(config kubeproxyconfig.KubeProxyIPTablesConfiguration, fldPath *field.Path) field.ErrorList","file":"pkg/proxy/apis/config/validation/validation.go","code":"func validateKubeProxyIPTablesConfiguration(config kubeproxyconfig.KubeProxyIPTablesConfiguration, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif config.MasqueradeBit != nil \u0026\u0026 (*config.MasqueradeBit \u003c 0 || *config.MasqueradeBit \u003e 31) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"MasqueradeBit\"), config.MasqueradeBit, \"must be within the range [0, 31]\"))\n\t}\n\n\tif config.SyncPeriod.Duration \u003c= 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"SyncPeriod\"), config.SyncPeriod, \"must be greater than 0\"))\n\t}\n\n\tif config.MinSyncPeriod.Duration \u003c 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"MinSyncPeriod\"), config.MinSyncPeriod, \"must be greater than or equal to 0\"))\n\t}\n\n\tif config.MinSyncPeriod.Duration \u003e config.SyncPeriod.Duration {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"SyncPeriod\"), config.MinSyncPeriod, fmt.Sprintf(\"must be greater than or equal to %s\", fldPath.Child(\"MinSyncPeriod\").String())))\n\t}\n\n\treturn allErrs\n}","line":{"from":108,"to":128}} {"id":100008344,"name":"validateKubeProxyIPVSConfiguration","signature":"func validateKubeProxyIPVSConfiguration(config kubeproxyconfig.KubeProxyIPVSConfiguration, fldPath *field.Path) field.ErrorList","file":"pkg/proxy/apis/config/validation/validation.go","code":"func validateKubeProxyIPVSConfiguration(config kubeproxyconfig.KubeProxyIPVSConfiguration, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif config.SyncPeriod.Duration \u003c= 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"SyncPeriod\"), config.SyncPeriod, \"must be greater than 0\"))\n\t}\n\n\tif config.MinSyncPeriod.Duration \u003c 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"MinSyncPeriod\"), config.MinSyncPeriod, \"must be greater than or equal to 0\"))\n\t}\n\n\tif config.MinSyncPeriod.Duration \u003e config.SyncPeriod.Duration {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"SyncPeriod\"), config.MinSyncPeriod, fmt.Sprintf(\"must be greater than or equal to %s\", fldPath.Child(\"MinSyncPeriod\").String())))\n\t}\n\n\tallErrs = append(allErrs, validateIPVSTimeout(config, fldPath)...)\n\tallErrs = append(allErrs, validateIPVSExcludeCIDRs(config.ExcludeCIDRs, fldPath.Child(\"ExcludeCidrs\"))...)\n\n\treturn allErrs\n}","line":{"from":130,"to":149}} {"id":100008345,"name":"validateKubeProxyConntrackConfiguration","signature":"func validateKubeProxyConntrackConfiguration(config kubeproxyconfig.KubeProxyConntrackConfiguration, fldPath *field.Path) field.ErrorList","file":"pkg/proxy/apis/config/validation/validation.go","code":"func validateKubeProxyConntrackConfiguration(config kubeproxyconfig.KubeProxyConntrackConfiguration, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif config.MaxPerCore != nil \u0026\u0026 *config.MaxPerCore \u003c 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"MaxPerCore\"), config.MaxPerCore, \"must be greater than or equal to 0\"))\n\t}\n\n\tif config.Min != nil \u0026\u0026 *config.Min \u003c 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"Min\"), config.Min, \"must be greater than or equal to 0\"))\n\t}\n\n\tif config.TCPEstablishedTimeout.Duration \u003c 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"TCPEstablishedTimeout\"), config.TCPEstablishedTimeout, \"must be greater than or equal to 0\"))\n\t}\n\n\tif config.TCPCloseWaitTimeout.Duration \u003c 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"TCPCloseWaitTimeout\"), config.TCPCloseWaitTimeout, \"must be greater than or equal to 0\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":151,"to":171}} {"id":100008346,"name":"validateProxyMode","signature":"func validateProxyMode(mode kubeproxyconfig.ProxyMode, fldPath *field.Path) field.ErrorList","file":"pkg/proxy/apis/config/validation/validation.go","code":"func validateProxyMode(mode kubeproxyconfig.ProxyMode, fldPath *field.Path) field.ErrorList {\n\tif runtime.GOOS == \"windows\" {\n\t\treturn validateProxyModeWindows(mode, fldPath)\n\t}\n\n\treturn validateProxyModeLinux(mode, fldPath)\n}","line":{"from":173,"to":179}} {"id":100008347,"name":"validateProxyModeLinux","signature":"func validateProxyModeLinux(mode kubeproxyconfig.ProxyMode, fldPath *field.Path) field.ErrorList","file":"pkg/proxy/apis/config/validation/validation.go","code":"func validateProxyModeLinux(mode kubeproxyconfig.ProxyMode, fldPath *field.Path) field.ErrorList {\n\tvalidModes := sets.NewString(\n\t\tstring(kubeproxyconfig.ProxyModeIPTables),\n\t\tstring(kubeproxyconfig.ProxyModeIPVS),\n\t)\n\n\tif mode == \"\" || validModes.Has(string(mode)) {\n\t\treturn nil\n\t}\n\n\terrMsg := fmt.Sprintf(\"must be %s or blank (blank means the best-available proxy [currently iptables])\", strings.Join(validModes.List(), \",\"))\n\treturn field.ErrorList{field.Invalid(fldPath.Child(\"ProxyMode\"), string(mode), errMsg)}\n}","line":{"from":181,"to":193}} {"id":100008348,"name":"validateProxyModeWindows","signature":"func validateProxyModeWindows(mode kubeproxyconfig.ProxyMode, fldPath *field.Path) field.ErrorList","file":"pkg/proxy/apis/config/validation/validation.go","code":"func validateProxyModeWindows(mode kubeproxyconfig.ProxyMode, fldPath *field.Path) field.ErrorList {\n\tvalidModes := sets.NewString(\n\t\tstring(kubeproxyconfig.ProxyModeKernelspace),\n\t)\n\n\tif mode == \"\" || validModes.Has(string(mode)) {\n\t\treturn nil\n\t}\n\n\terrMsg := fmt.Sprintf(\"must be %s or blank (blank means the most-available proxy [currently 'kernelspace'])\", strings.Join(validModes.List(), \",\"))\n\treturn field.ErrorList{field.Invalid(fldPath.Child(\"ProxyMode\"), string(mode), errMsg)}\n}","line":{"from":195,"to":206}} {"id":100008349,"name":"validateClientConnectionConfiguration","signature":"func validateClientConnectionConfiguration(config componentbaseconfig.ClientConnectionConfiguration, fldPath *field.Path) field.ErrorList","file":"pkg/proxy/apis/config/validation/validation.go","code":"func validateClientConnectionConfiguration(config componentbaseconfig.ClientConnectionConfiguration, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(config.Burst), fldPath.Child(\"Burst\"))...)\n\treturn allErrs\n}","line":{"from":208,"to":212}} {"id":100008350,"name":"validateHostPort","signature":"func validateHostPort(input string, fldPath *field.Path) field.ErrorList","file":"pkg/proxy/apis/config/validation/validation.go","code":"func validateHostPort(input string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\thostIP, port, err := net.SplitHostPort(input)\n\tif err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, input, \"must be IP:port\"))\n\t\treturn allErrs\n\t}\n\n\tif ip := netutils.ParseIPSloppy(hostIP); ip == nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, hostIP, \"must be a valid IP\"))\n\t}\n\n\tif p, err := strconv.Atoi(port); err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, port, \"must be a valid port\"))\n\t} else if p \u003c 1 || p \u003e 65535 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, port, \"must be a valid port\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":214,"to":234}} {"id":100008351,"name":"validateKubeProxyNodePortAddress","signature":"func validateKubeProxyNodePortAddress(nodePortAddresses []string, fldPath *field.Path) field.ErrorList","file":"pkg/proxy/apis/config/validation/validation.go","code":"func validateKubeProxyNodePortAddress(nodePortAddresses []string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tfor i := range nodePortAddresses {\n\t\tif _, _, err := netutils.ParseCIDRSloppy(nodePortAddresses[i]); err != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Index(i), nodePortAddresses[i], \"must be a valid CIDR\"))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":236,"to":246}} {"id":100008352,"name":"validateIPVSTimeout","signature":"func validateIPVSTimeout(config kubeproxyconfig.KubeProxyIPVSConfiguration, fldPath *field.Path) field.ErrorList","file":"pkg/proxy/apis/config/validation/validation.go","code":"func validateIPVSTimeout(config kubeproxyconfig.KubeProxyIPVSConfiguration, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif config.TCPTimeout.Duration \u003c 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"TCPTimeout\"), config.TCPTimeout, \"must be greater than or equal to 0\"))\n\t}\n\n\tif config.TCPFinTimeout.Duration \u003c 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"TCPFinTimeout\"), config.TCPFinTimeout, \"must be greater than or equal to 0\"))\n\t}\n\n\tif config.UDPTimeout.Duration \u003c 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"UDPTimeout\"), config.UDPTimeout, \"must be greater than or equal to 0\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":248,"to":264}} {"id":100008353,"name":"validateIPVSExcludeCIDRs","signature":"func validateIPVSExcludeCIDRs(excludeCIDRs []string, fldPath *field.Path) field.ErrorList","file":"pkg/proxy/apis/config/validation/validation.go","code":"func validateIPVSExcludeCIDRs(excludeCIDRs []string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tfor i := range excludeCIDRs {\n\t\tif _, _, err := netutils.ParseCIDRSloppy(excludeCIDRs[i]); err != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Index(i), excludeCIDRs[i], \"must be a valid CIDR\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":266,"to":275}} {"id":100008354,"name":"validateShowHiddenMetricsVersion","signature":"func validateShowHiddenMetricsVersion(version string, fldPath *field.Path) field.ErrorList","file":"pkg/proxy/apis/config/validation/validation.go","code":"func validateShowHiddenMetricsVersion(version string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\terrs := metrics.ValidateShowHiddenMetricsVersion(version)\n\tfor _, e := range errs {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, version, e.Error()))\n\t}\n\n\treturn allErrs\n}","line":{"from":277,"to":285}} {"id":100008355,"name":"validateInterface","signature":"func validateInterface(iface string, fldPath *field.Path) field.ErrorList","file":"pkg/proxy/apis/config/validation/validation.go","code":"func validateInterface(iface string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(iface) == 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, iface, \"must not be empty\"))\n\t}\n\treturn allErrs\n}","line":{"from":287,"to":293}} {"id":100008356,"name":"NewEndpointSliceConfig","signature":"func NewEndpointSliceConfig(endpointSliceInformer discoveryinformers.EndpointSliceInformer, resyncPeriod time.Duration) *EndpointSliceConfig","file":"pkg/proxy/config/config.go","code":"// NewEndpointSliceConfig creates a new EndpointSliceConfig.\nfunc NewEndpointSliceConfig(endpointSliceInformer discoveryinformers.EndpointSliceInformer, resyncPeriod time.Duration) *EndpointSliceConfig {\n\tresult := \u0026EndpointSliceConfig{\n\t\tlisterSynced: endpointSliceInformer.Informer().HasSynced,\n\t}\n\n\tendpointSliceInformer.Informer().AddEventHandlerWithResyncPeriod(\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: result.handleAddEndpointSlice,\n\t\t\tUpdateFunc: result.handleUpdateEndpointSlice,\n\t\t\tDeleteFunc: result.handleDeleteEndpointSlice,\n\t\t},\n\t\tresyncPeriod,\n\t)\n\n\treturn result\n}","line":{"from":72,"to":88}} {"id":100008357,"name":"RegisterEventHandler","signature":"func (c *EndpointSliceConfig) RegisterEventHandler(handler EndpointSliceHandler)","file":"pkg/proxy/config/config.go","code":"// RegisterEventHandler registers a handler which is called on every endpoint slice change.\nfunc (c *EndpointSliceConfig) RegisterEventHandler(handler EndpointSliceHandler) {\n\tc.eventHandlers = append(c.eventHandlers, handler)\n}","line":{"from":90,"to":93}} {"id":100008358,"name":"Run","signature":"func (c *EndpointSliceConfig) Run(stopCh \u003c-chan struct{})","file":"pkg/proxy/config/config.go","code":"// Run waits for cache synced and invokes handlers after syncing.\nfunc (c *EndpointSliceConfig) Run(stopCh \u003c-chan struct{}) {\n\tklog.InfoS(\"Starting endpoint slice config controller\")\n\n\tif !cache.WaitForNamedCacheSync(\"endpoint slice config\", stopCh, c.listerSynced) {\n\t\treturn\n\t}\n\n\tfor _, h := range c.eventHandlers {\n\t\tklog.V(3).InfoS(\"Calling handler.OnEndpointSlicesSynced()\")\n\t\th.OnEndpointSlicesSynced()\n\t}\n}","line":{"from":95,"to":107}} {"id":100008359,"name":"handleAddEndpointSlice","signature":"func (c *EndpointSliceConfig) handleAddEndpointSlice(obj interface{})","file":"pkg/proxy/config/config.go","code":"func (c *EndpointSliceConfig) handleAddEndpointSlice(obj interface{}) {\n\tendpointSlice, ok := obj.(*discovery.EndpointSlice)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unexpected object type: %T\", obj))\n\t\treturn\n\t}\n\tfor _, h := range c.eventHandlers {\n\t\tklog.V(4).InfoS(\"Calling handler.OnEndpointSliceAdd\", \"endpoints\", klog.KObj(endpointSlice))\n\t\th.OnEndpointSliceAdd(endpointSlice)\n\t}\n}","line":{"from":109,"to":119}} {"id":100008360,"name":"handleUpdateEndpointSlice","signature":"func (c *EndpointSliceConfig) handleUpdateEndpointSlice(oldObj, newObj interface{})","file":"pkg/proxy/config/config.go","code":"func (c *EndpointSliceConfig) handleUpdateEndpointSlice(oldObj, newObj interface{}) {\n\toldEndpointSlice, ok := oldObj.(*discovery.EndpointSlice)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unexpected object type: %T\", newObj))\n\t\treturn\n\t}\n\tnewEndpointSlice, ok := newObj.(*discovery.EndpointSlice)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unexpected object type: %T\", newObj))\n\t\treturn\n\t}\n\tfor _, h := range c.eventHandlers {\n\t\tklog.V(4).InfoS(\"Calling handler.OnEndpointSliceUpdate\")\n\t\th.OnEndpointSliceUpdate(oldEndpointSlice, newEndpointSlice)\n\t}\n}","line":{"from":121,"to":136}} {"id":100008361,"name":"handleDeleteEndpointSlice","signature":"func (c *EndpointSliceConfig) handleDeleteEndpointSlice(obj interface{})","file":"pkg/proxy/config/config.go","code":"func (c *EndpointSliceConfig) handleDeleteEndpointSlice(obj interface{}) {\n\tendpointSlice, ok := obj.(*discovery.EndpointSlice)\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"unexpected object type: %T\", obj))\n\t\t\treturn\n\t\t}\n\t\tif endpointSlice, ok = tombstone.Obj.(*discovery.EndpointSlice); !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"unexpected object type: %T\", obj))\n\t\t\treturn\n\t\t}\n\t}\n\tfor _, h := range c.eventHandlers {\n\t\tklog.V(4).InfoS(\"Calling handler.OnEndpointsDelete\")\n\t\th.OnEndpointSliceDelete(endpointSlice)\n\t}\n}","line":{"from":138,"to":155}} {"id":100008362,"name":"NewServiceConfig","signature":"func NewServiceConfig(serviceInformer coreinformers.ServiceInformer, resyncPeriod time.Duration) *ServiceConfig","file":"pkg/proxy/config/config.go","code":"// NewServiceConfig creates a new ServiceConfig.\nfunc NewServiceConfig(serviceInformer coreinformers.ServiceInformer, resyncPeriod time.Duration) *ServiceConfig {\n\tresult := \u0026ServiceConfig{\n\t\tlisterSynced: serviceInformer.Informer().HasSynced,\n\t}\n\n\tserviceInformer.Informer().AddEventHandlerWithResyncPeriod(\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: result.handleAddService,\n\t\t\tUpdateFunc: result.handleUpdateService,\n\t\t\tDeleteFunc: result.handleDeleteService,\n\t\t},\n\t\tresyncPeriod,\n\t)\n\n\treturn result\n}","line":{"from":163,"to":179}} {"id":100008363,"name":"RegisterEventHandler","signature":"func (c *ServiceConfig) RegisterEventHandler(handler ServiceHandler)","file":"pkg/proxy/config/config.go","code":"// RegisterEventHandler registers a handler which is called on every service change.\nfunc (c *ServiceConfig) RegisterEventHandler(handler ServiceHandler) {\n\tc.eventHandlers = append(c.eventHandlers, handler)\n}","line":{"from":181,"to":184}} {"id":100008364,"name":"Run","signature":"func (c *ServiceConfig) Run(stopCh \u003c-chan struct{})","file":"pkg/proxy/config/config.go","code":"// Run waits for cache synced and invokes handlers after syncing.\nfunc (c *ServiceConfig) Run(stopCh \u003c-chan struct{}) {\n\tklog.InfoS(\"Starting service config controller\")\n\n\tif !cache.WaitForNamedCacheSync(\"service config\", stopCh, c.listerSynced) {\n\t\treturn\n\t}\n\n\tfor i := range c.eventHandlers {\n\t\tklog.V(3).InfoS(\"Calling handler.OnServiceSynced()\")\n\t\tc.eventHandlers[i].OnServiceSynced()\n\t}\n}","line":{"from":186,"to":198}} {"id":100008365,"name":"handleAddService","signature":"func (c *ServiceConfig) handleAddService(obj interface{})","file":"pkg/proxy/config/config.go","code":"func (c *ServiceConfig) handleAddService(obj interface{}) {\n\tservice, ok := obj.(*v1.Service)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unexpected object type: %v\", obj))\n\t\treturn\n\t}\n\tfor i := range c.eventHandlers {\n\t\tklog.V(4).InfoS(\"Calling handler.OnServiceAdd\")\n\t\tc.eventHandlers[i].OnServiceAdd(service)\n\t}\n}","line":{"from":200,"to":210}} {"id":100008366,"name":"handleUpdateService","signature":"func (c *ServiceConfig) handleUpdateService(oldObj, newObj interface{})","file":"pkg/proxy/config/config.go","code":"func (c *ServiceConfig) handleUpdateService(oldObj, newObj interface{}) {\n\toldService, ok := oldObj.(*v1.Service)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unexpected object type: %v\", oldObj))\n\t\treturn\n\t}\n\tservice, ok := newObj.(*v1.Service)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unexpected object type: %v\", newObj))\n\t\treturn\n\t}\n\tfor i := range c.eventHandlers {\n\t\tklog.V(4).InfoS(\"Calling handler.OnServiceUpdate\")\n\t\tc.eventHandlers[i].OnServiceUpdate(oldService, service)\n\t}\n}","line":{"from":212,"to":227}} {"id":100008367,"name":"handleDeleteService","signature":"func (c *ServiceConfig) handleDeleteService(obj interface{})","file":"pkg/proxy/config/config.go","code":"func (c *ServiceConfig) handleDeleteService(obj interface{}) {\n\tservice, ok := obj.(*v1.Service)\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"unexpected object type: %v\", obj))\n\t\t\treturn\n\t\t}\n\t\tif service, ok = tombstone.Obj.(*v1.Service); !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"unexpected object type: %v\", obj))\n\t\t\treturn\n\t\t}\n\t}\n\tfor i := range c.eventHandlers {\n\t\tklog.V(4).InfoS(\"Calling handler.OnServiceDelete\")\n\t\tc.eventHandlers[i].OnServiceDelete(service)\n\t}\n}","line":{"from":229,"to":246}} {"id":100008368,"name":"OnNodeAdd","signature":"func (*NoopNodeHandler) OnNodeAdd(node *v1.Node) {}","file":"pkg/proxy/config/config.go","code":"// OnNodeAdd is a noop handler for Node creates.\nfunc (*NoopNodeHandler) OnNodeAdd(node *v1.Node) {}","line":{"from":269,"to":270}} {"id":100008369,"name":"OnNodeUpdate","signature":"func (*NoopNodeHandler) OnNodeUpdate(oldNode, node *v1.Node) {}","file":"pkg/proxy/config/config.go","code":"// OnNodeUpdate is a noop handler for Node updates.\nfunc (*NoopNodeHandler) OnNodeUpdate(oldNode, node *v1.Node) {}","line":{"from":272,"to":273}} {"id":100008370,"name":"OnNodeDelete","signature":"func (*NoopNodeHandler) OnNodeDelete(node *v1.Node) {}","file":"pkg/proxy/config/config.go","code":"// OnNodeDelete is a noop handler for Node deletes.\nfunc (*NoopNodeHandler) OnNodeDelete(node *v1.Node) {}","line":{"from":275,"to":276}} {"id":100008371,"name":"OnNodeSynced","signature":"func (*NoopNodeHandler) OnNodeSynced() {}","file":"pkg/proxy/config/config.go","code":"// OnNodeSynced is a noop handler for Node syncs.\nfunc (*NoopNodeHandler) OnNodeSynced() {}","line":{"from":278,"to":279}} {"id":100008372,"name":"NewNodeConfig","signature":"func NewNodeConfig(nodeInformer coreinformers.NodeInformer, resyncPeriod time.Duration) *NodeConfig","file":"pkg/proxy/config/config.go","code":"// NewNodeConfig creates a new NodeConfig.\nfunc NewNodeConfig(nodeInformer coreinformers.NodeInformer, resyncPeriod time.Duration) *NodeConfig {\n\tresult := \u0026NodeConfig{\n\t\tlisterSynced: nodeInformer.Informer().HasSynced,\n\t}\n\n\tnodeInformer.Informer().AddEventHandlerWithResyncPeriod(\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: result.handleAddNode,\n\t\t\tUpdateFunc: result.handleUpdateNode,\n\t\t\tDeleteFunc: result.handleDeleteNode,\n\t\t},\n\t\tresyncPeriod,\n\t)\n\n\treturn result\n}","line":{"from":290,"to":306}} {"id":100008373,"name":"RegisterEventHandler","signature":"func (c *NodeConfig) RegisterEventHandler(handler NodeHandler)","file":"pkg/proxy/config/config.go","code":"// RegisterEventHandler registers a handler which is called on every node change.\nfunc (c *NodeConfig) RegisterEventHandler(handler NodeHandler) {\n\tc.eventHandlers = append(c.eventHandlers, handler)\n}","line":{"from":308,"to":311}} {"id":100008374,"name":"Run","signature":"func (c *NodeConfig) Run(stopCh \u003c-chan struct{})","file":"pkg/proxy/config/config.go","code":"// Run starts the goroutine responsible for calling registered handlers.\nfunc (c *NodeConfig) Run(stopCh \u003c-chan struct{}) {\n\tklog.InfoS(\"Starting node config controller\")\n\n\tif !cache.WaitForNamedCacheSync(\"node config\", stopCh, c.listerSynced) {\n\t\treturn\n\t}\n\n\tfor i := range c.eventHandlers {\n\t\tklog.V(3).InfoS(\"Calling handler.OnNodeSynced()\")\n\t\tc.eventHandlers[i].OnNodeSynced()\n\t}\n}","line":{"from":313,"to":325}} {"id":100008375,"name":"handleAddNode","signature":"func (c *NodeConfig) handleAddNode(obj interface{})","file":"pkg/proxy/config/config.go","code":"func (c *NodeConfig) handleAddNode(obj interface{}) {\n\tnode, ok := obj.(*v1.Node)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unexpected object type: %v\", obj))\n\t\treturn\n\t}\n\tfor i := range c.eventHandlers {\n\t\tklog.V(4).InfoS(\"Calling handler.OnNodeAdd\")\n\t\tc.eventHandlers[i].OnNodeAdd(node)\n\t}\n}","line":{"from":327,"to":337}} {"id":100008376,"name":"handleUpdateNode","signature":"func (c *NodeConfig) handleUpdateNode(oldObj, newObj interface{})","file":"pkg/proxy/config/config.go","code":"func (c *NodeConfig) handleUpdateNode(oldObj, newObj interface{}) {\n\toldNode, ok := oldObj.(*v1.Node)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unexpected object type: %v\", oldObj))\n\t\treturn\n\t}\n\tnode, ok := newObj.(*v1.Node)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unexpected object type: %v\", newObj))\n\t\treturn\n\t}\n\tfor i := range c.eventHandlers {\n\t\tklog.V(5).InfoS(\"Calling handler.OnNodeUpdate\")\n\t\tc.eventHandlers[i].OnNodeUpdate(oldNode, node)\n\t}\n}","line":{"from":339,"to":354}} {"id":100008377,"name":"handleDeleteNode","signature":"func (c *NodeConfig) handleDeleteNode(obj interface{})","file":"pkg/proxy/config/config.go","code":"func (c *NodeConfig) handleDeleteNode(obj interface{}) {\n\tnode, ok := obj.(*v1.Node)\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"unexpected object type: %v\", obj))\n\t\t\treturn\n\t\t}\n\t\tif node, ok = tombstone.Obj.(*v1.Node); !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"unexpected object type: %v\", obj))\n\t\t\treturn\n\t\t}\n\t}\n\tfor i := range c.eventHandlers {\n\t\tklog.V(4).InfoS(\"Calling handler.OnNodeDelete\")\n\t\tc.eventHandlers[i].OnNodeDelete(node)\n\t}\n}","line":{"from":356,"to":373}} {"id":100008378,"name":"String","signature":"func (info *BaseEndpointInfo) String() string","file":"pkg/proxy/endpoints.go","code":"// String is part of proxy.Endpoint interface.\nfunc (info *BaseEndpointInfo) String() string {\n\treturn info.Endpoint\n}","line":{"from":78,"to":81}} {"id":100008379,"name":"GetIsLocal","signature":"func (info *BaseEndpointInfo) GetIsLocal() bool","file":"pkg/proxy/endpoints.go","code":"// GetIsLocal is part of proxy.Endpoint interface.\nfunc (info *BaseEndpointInfo) GetIsLocal() bool {\n\treturn info.IsLocal\n}","line":{"from":83,"to":86}} {"id":100008380,"name":"IsReady","signature":"func (info *BaseEndpointInfo) IsReady() bool","file":"pkg/proxy/endpoints.go","code":"// IsReady returns true if an endpoint is ready and not terminating.\nfunc (info *BaseEndpointInfo) IsReady() bool {\n\treturn info.Ready\n}","line":{"from":88,"to":91}} {"id":100008381,"name":"IsServing","signature":"func (info *BaseEndpointInfo) IsServing() bool","file":"pkg/proxy/endpoints.go","code":"// IsServing returns true if an endpoint is ready, regardless of if the\n// endpoint is terminating.\nfunc (info *BaseEndpointInfo) IsServing() bool {\n\treturn info.Serving\n}","line":{"from":93,"to":97}} {"id":100008382,"name":"IsTerminating","signature":"func (info *BaseEndpointInfo) IsTerminating() bool","file":"pkg/proxy/endpoints.go","code":"// IsTerminating retruns true if an endpoint is terminating. For pods,\n// that is any pod with a deletion timestamp.\nfunc (info *BaseEndpointInfo) IsTerminating() bool {\n\treturn info.Terminating\n}","line":{"from":99,"to":103}} {"id":100008383,"name":"GetZoneHints","signature":"func (info *BaseEndpointInfo) GetZoneHints() sets.String","file":"pkg/proxy/endpoints.go","code":"// GetZoneHints returns the zone hint for the endpoint.\nfunc (info *BaseEndpointInfo) GetZoneHints() sets.String {\n\treturn info.ZoneHints\n}","line":{"from":105,"to":108}} {"id":100008384,"name":"IP","signature":"func (info *BaseEndpointInfo) IP() string","file":"pkg/proxy/endpoints.go","code":"// IP returns just the IP part of the endpoint, it's a part of proxy.Endpoint interface.\nfunc (info *BaseEndpointInfo) IP() string {\n\treturn utilproxy.IPPart(info.Endpoint)\n}","line":{"from":110,"to":113}} {"id":100008385,"name":"Port","signature":"func (info *BaseEndpointInfo) Port() (int, error)","file":"pkg/proxy/endpoints.go","code":"// Port returns just the Port part of the endpoint.\nfunc (info *BaseEndpointInfo) Port() (int, error) {\n\treturn utilproxy.PortPart(info.Endpoint)\n}","line":{"from":115,"to":118}} {"id":100008386,"name":"Equal","signature":"func (info *BaseEndpointInfo) Equal(other Endpoint) bool","file":"pkg/proxy/endpoints.go","code":"// Equal is part of proxy.Endpoint interface.\nfunc (info *BaseEndpointInfo) Equal(other Endpoint) bool {\n\treturn info.String() == other.String() \u0026\u0026\n\t\tinfo.GetIsLocal() == other.GetIsLocal() \u0026\u0026\n\t\tinfo.IsReady() == other.IsReady()\n}","line":{"from":120,"to":125}} {"id":100008387,"name":"GetNodeName","signature":"func (info *BaseEndpointInfo) GetNodeName() string","file":"pkg/proxy/endpoints.go","code":"// GetNodeName returns the NodeName for this endpoint.\nfunc (info *BaseEndpointInfo) GetNodeName() string {\n\treturn info.NodeName\n}","line":{"from":127,"to":130}} {"id":100008388,"name":"GetZone","signature":"func (info *BaseEndpointInfo) GetZone() string","file":"pkg/proxy/endpoints.go","code":"// GetZone returns the Zone for this endpoint.\nfunc (info *BaseEndpointInfo) GetZone() string {\n\treturn info.Zone\n}","line":{"from":132,"to":135}} {"id":100008389,"name":"newBaseEndpointInfo","signature":"func newBaseEndpointInfo(IP, nodeName, zone string, port int, isLocal bool,","file":"pkg/proxy/endpoints.go","code":"func newBaseEndpointInfo(IP, nodeName, zone string, port int, isLocal bool,\n\tready, serving, terminating bool, zoneHints sets.String) *BaseEndpointInfo {\n\treturn \u0026BaseEndpointInfo{\n\t\tEndpoint: net.JoinHostPort(IP, strconv.Itoa(port)),\n\t\tIsLocal: isLocal,\n\t\tReady: ready,\n\t\tServing: serving,\n\t\tTerminating: terminating,\n\t\tZoneHints: zoneHints,\n\t\tNodeName: nodeName,\n\t\tZone: zone,\n\t}\n}","line":{"from":137,"to":149}} {"id":100008390,"name":"NewEndpointChangeTracker","signature":"func NewEndpointChangeTracker(hostname string, makeEndpointInfo makeEndpointFunc, ipFamily v1.IPFamily, recorder events.EventRecorder, processEndpointsMapChange processEndpointsMapChangeFunc) *EndpointChangeTracker","file":"pkg/proxy/endpoints.go","code":"// NewEndpointChangeTracker initializes an EndpointsChangeMap\nfunc NewEndpointChangeTracker(hostname string, makeEndpointInfo makeEndpointFunc, ipFamily v1.IPFamily, recorder events.EventRecorder, processEndpointsMapChange processEndpointsMapChangeFunc) *EndpointChangeTracker {\n\treturn \u0026EndpointChangeTracker{\n\t\tlastChangeTriggerTimes: make(map[types.NamespacedName][]time.Time),\n\t\ttrackerStartTime: time.Now(),\n\t\tprocessEndpointsMapChange: processEndpointsMapChange,\n\t\tendpointSliceCache: NewEndpointSliceCache(hostname, ipFamily, recorder, makeEndpointInfo),\n\t}\n}","line":{"from":176,"to":184}} {"id":100008391,"name":"EndpointSliceUpdate","signature":"func (ect *EndpointChangeTracker) EndpointSliceUpdate(endpointSlice *discovery.EndpointSlice, removeSlice bool) bool","file":"pkg/proxy/endpoints.go","code":"// EndpointSliceUpdate updates given service's endpoints change map based on the \u003cprevious, current\u003e endpoints pair.\n// It returns true if items changed, otherwise return false. Will add/update/delete items of EndpointsChangeMap.\n// If removeSlice is true, slice will be removed, otherwise it will be added or updated.\nfunc (ect *EndpointChangeTracker) EndpointSliceUpdate(endpointSlice *discovery.EndpointSlice, removeSlice bool) bool {\n\tif !supportedEndpointSliceAddressTypes.Has(string(endpointSlice.AddressType)) {\n\t\tklog.V(4).InfoS(\"EndpointSlice address type not supported by kube-proxy\", \"addressType\", endpointSlice.AddressType)\n\t\treturn false\n\t}\n\n\t// This should never happen\n\tif endpointSlice == nil {\n\t\tklog.ErrorS(nil, \"Nil endpointSlice passed to EndpointSliceUpdate\")\n\t\treturn false\n\t}\n\n\tnamespacedName, _, err := endpointSliceCacheKeys(endpointSlice)\n\tif err != nil {\n\t\tklog.InfoS(\"Error getting endpoint slice cache keys\", \"err\", err)\n\t\treturn false\n\t}\n\n\tmetrics.EndpointChangesTotal.Inc()\n\n\tect.lock.Lock()\n\tdefer ect.lock.Unlock()\n\n\tchangeNeeded := ect.endpointSliceCache.updatePending(endpointSlice, removeSlice)\n\n\tif changeNeeded {\n\t\tmetrics.EndpointChangesPending.Inc()\n\t\t// In case of Endpoints deletion, the LastChangeTriggerTime annotation is\n\t\t// by-definition coming from the time of last update, which is not what\n\t\t// we want to measure. So we simply ignore it in this cases.\n\t\t// TODO(wojtek-t, robscott): Address the problem for EndpointSlice deletion\n\t\t// when other EndpointSlice for that service still exist.\n\t\tif removeSlice {\n\t\t\tdelete(ect.lastChangeTriggerTimes, namespacedName)\n\t\t} else if t := getLastChangeTriggerTime(endpointSlice.Annotations); !t.IsZero() \u0026\u0026 t.After(ect.trackerStartTime) {\n\t\t\tect.lastChangeTriggerTimes[namespacedName] =\n\t\t\t\tappend(ect.lastChangeTriggerTimes[namespacedName], t)\n\t\t}\n\t}\n\n\treturn changeNeeded\n}","line":{"from":186,"to":230}} {"id":100008392,"name":"PendingChanges","signature":"func (ect *EndpointChangeTracker) PendingChanges() sets.String","file":"pkg/proxy/endpoints.go","code":"// PendingChanges returns a set whose keys are the names of the services whose endpoints\n// have changed since the last time ect was used to update an EndpointsMap. (You must call\n// this _before_ calling em.Update(ect).)\nfunc (ect *EndpointChangeTracker) PendingChanges() sets.String {\n\treturn ect.endpointSliceCache.pendingChanges()\n}","line":{"from":232,"to":237}} {"id":100008393,"name":"checkoutChanges","signature":"func (ect *EndpointChangeTracker) checkoutChanges() []*endpointsChange","file":"pkg/proxy/endpoints.go","code":"// checkoutChanges returns a list of pending endpointsChanges and marks them as\n// applied.\nfunc (ect *EndpointChangeTracker) checkoutChanges() []*endpointsChange {\n\tmetrics.EndpointChangesPending.Set(0)\n\n\treturn ect.endpointSliceCache.checkoutChanges()\n}","line":{"from":239,"to":245}} {"id":100008394,"name":"checkoutTriggerTimes","signature":"func (ect *EndpointChangeTracker) checkoutTriggerTimes(lastChangeTriggerTimes *map[types.NamespacedName][]time.Time)","file":"pkg/proxy/endpoints.go","code":"// checkoutTriggerTimes applies the locally cached trigger times to a map of\n// trigger times that have been passed in and empties the local cache.\nfunc (ect *EndpointChangeTracker) checkoutTriggerTimes(lastChangeTriggerTimes *map[types.NamespacedName][]time.Time) {\n\tect.lock.Lock()\n\tdefer ect.lock.Unlock()\n\n\tfor k, v := range ect.lastChangeTriggerTimes {\n\t\tprev, ok := (*lastChangeTriggerTimes)[k]\n\t\tif !ok {\n\t\t\t(*lastChangeTriggerTimes)[k] = v\n\t\t} else {\n\t\t\t(*lastChangeTriggerTimes)[k] = append(prev, v...)\n\t\t}\n\t}\n\tect.lastChangeTriggerTimes = make(map[types.NamespacedName][]time.Time)\n}","line":{"from":247,"to":262}} {"id":100008395,"name":"getLastChangeTriggerTime","signature":"func getLastChangeTriggerTime(annotations map[string]string) time.Time","file":"pkg/proxy/endpoints.go","code":"// getLastChangeTriggerTime returns the time.Time value of the\n// EndpointsLastChangeTriggerTime annotation stored in the given endpoints\n// object or the \"zero\" time if the annotation wasn't set or was set\n// incorrectly.\nfunc getLastChangeTriggerTime(annotations map[string]string) time.Time {\n\t// TODO(#81360): ignore case when Endpoint is deleted.\n\tif _, ok := annotations[v1.EndpointsLastChangeTriggerTime]; !ok {\n\t\t// It's possible that the Endpoints object won't have the\n\t\t// EndpointsLastChangeTriggerTime annotation set. In that case return\n\t\t// the 'zero value', which is ignored in the upstream code.\n\t\treturn time.Time{}\n\t}\n\tval, err := time.Parse(time.RFC3339Nano, annotations[v1.EndpointsLastChangeTriggerTime])\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Error while parsing EndpointsLastChangeTriggerTimeAnnotation\",\n\t\t\t\"value\", annotations[v1.EndpointsLastChangeTriggerTime])\n\t\t// In case of error val = time.Zero, which is ignored in the upstream code.\n\t}\n\treturn val\n}","line":{"from":264,"to":283}} {"id":100008396,"name":"Update","signature":"func (em EndpointsMap) Update(changes *EndpointChangeTracker) (result UpdateEndpointMapResult)","file":"pkg/proxy/endpoints.go","code":"// Update updates endpointsMap base on the given changes.\nfunc (em EndpointsMap) Update(changes *EndpointChangeTracker) (result UpdateEndpointMapResult) {\n\tresult.DeletedUDPEndpoints = make([]ServiceEndpoint, 0)\n\tresult.NewlyActiveUDPServices = make([]ServicePortName, 0)\n\tresult.LastChangeTriggerTimes = make(map[types.NamespacedName][]time.Time)\n\n\tem.apply(changes, \u0026result.DeletedUDPEndpoints, \u0026result.NewlyActiveUDPServices, \u0026result.LastChangeTriggerTimes)\n\n\treturn result\n}","line":{"from":313,"to":322}} {"id":100008397,"name":"apply","signature":"func (em EndpointsMap) apply(ect *EndpointChangeTracker, deletedUDPEndpoints *[]ServiceEndpoint,","file":"pkg/proxy/endpoints.go","code":"// apply the changes to EndpointsMap, update the passed-in stale-conntrack-entry arrays,\n// and clear the changes map. In addition it returns (via argument) and resets the\n// lastChangeTriggerTimes for all endpoints that were changed and will result in syncing\n// the proxy rules. apply triggers processEndpointsMapChange on every change.\nfunc (em EndpointsMap) apply(ect *EndpointChangeTracker, deletedUDPEndpoints *[]ServiceEndpoint,\n\tnewlyActiveUDPServices *[]ServicePortName, lastChangeTriggerTimes *map[types.NamespacedName][]time.Time) {\n\tif ect == nil {\n\t\treturn\n\t}\n\n\tchanges := ect.checkoutChanges()\n\tfor _, change := range changes {\n\t\tif ect.processEndpointsMapChange != nil {\n\t\t\tect.processEndpointsMapChange(change.previous, change.current)\n\t\t}\n\t\tem.unmerge(change.previous)\n\t\tem.merge(change.current)\n\t\tdetectStaleConntrackEntries(change.previous, change.current, deletedUDPEndpoints, newlyActiveUDPServices)\n\t}\n\tect.checkoutTriggerTimes(lastChangeTriggerTimes)\n}","line":{"from":327,"to":347}} {"id":100008398,"name":"merge","signature":"func (em EndpointsMap) merge(other EndpointsMap)","file":"pkg/proxy/endpoints.go","code":"// Merge ensures that the current EndpointsMap contains all \u003cservice, endpoints\u003e pairs from the EndpointsMap passed in.\nfunc (em EndpointsMap) merge(other EndpointsMap) {\n\tfor svcPortName := range other {\n\t\tem[svcPortName] = other[svcPortName]\n\t}\n}","line":{"from":349,"to":354}} {"id":100008399,"name":"unmerge","signature":"func (em EndpointsMap) unmerge(other EndpointsMap)","file":"pkg/proxy/endpoints.go","code":"// Unmerge removes the \u003cservice, endpoints\u003e pairs from the current EndpointsMap which are contained in the EndpointsMap passed in.\nfunc (em EndpointsMap) unmerge(other EndpointsMap) {\n\tfor svcPortName := range other {\n\t\tdelete(em, svcPortName)\n\t}\n}","line":{"from":356,"to":361}} {"id":100008400,"name":"getLocalReadyEndpointIPs","signature":"func (em EndpointsMap) getLocalReadyEndpointIPs() map[types.NamespacedName]sets.String","file":"pkg/proxy/endpoints.go","code":"// getLocalEndpointIPs returns endpoints IPs if given endpoint is local - local means the endpoint is running in same host as kube-proxy.\nfunc (em EndpointsMap) getLocalReadyEndpointIPs() map[types.NamespacedName]sets.String {\n\tlocalIPs := make(map[types.NamespacedName]sets.String)\n\tfor svcPortName, epList := range em {\n\t\tfor _, ep := range epList {\n\t\t\t// Only add ready endpoints for health checking. Terminating endpoints may still serve traffic\n\t\t\t// but the health check signal should fail if there are only terminating endpoints on a node.\n\t\t\tif !ep.IsReady() {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif ep.GetIsLocal() {\n\t\t\t\tnsn := svcPortName.NamespacedName\n\t\t\t\tif localIPs[nsn] == nil {\n\t\t\t\t\tlocalIPs[nsn] = sets.NewString()\n\t\t\t\t}\n\t\t\t\tlocalIPs[nsn].Insert(ep.IP())\n\t\t\t}\n\t\t}\n\t}\n\treturn localIPs\n}","line":{"from":363,"to":384}} {"id":100008401,"name":"LocalReadyEndpoints","signature":"func (em EndpointsMap) LocalReadyEndpoints() map[types.NamespacedName]int","file":"pkg/proxy/endpoints.go","code":"// LocalReadyEndpoints returns a map of Service names to the number of local ready\n// endpoints for that service.\nfunc (em EndpointsMap) LocalReadyEndpoints() map[types.NamespacedName]int {\n\t// TODO: If this will appear to be computationally expensive, consider\n\t// computing this incrementally similarly to endpointsMap.\n\n\t// (Note that we need to call getLocalEndpointIPs first to squash the data by IP,\n\t// because the EndpointsMap is sorted by IP+port, not just IP, and we want to\n\t// consider a Service pointing to 10.0.0.1:80 and 10.0.0.1:443 to have 1 endpoint,\n\t// not 2.)\n\n\teps := make(map[types.NamespacedName]int)\n\tlocalIPs := em.getLocalReadyEndpointIPs()\n\tfor nsn, ips := range localIPs {\n\t\teps[nsn] = len(ips)\n\t}\n\treturn eps\n}","line":{"from":386,"to":403}} {"id":100008402,"name":"detectStaleConntrackEntries","signature":"func detectStaleConntrackEntries(oldEndpointsMap, newEndpointsMap EndpointsMap, deletedUDPEndpoints *[]ServiceEndpoint, newlyActiveUDPServices *[]ServicePortName)","file":"pkg/proxy/endpoints.go","code":"// detectStaleConntrackEntries detects services that may be associated with stale conntrack entries.\n// (See UpdateEndpointMapResult.DeletedUDPEndpoints and .NewlyActiveUDPServices.)\nfunc detectStaleConntrackEntries(oldEndpointsMap, newEndpointsMap EndpointsMap, deletedUDPEndpoints *[]ServiceEndpoint, newlyActiveUDPServices *[]ServicePortName) {\n\t// Find the UDP endpoints that we were sending traffic to in oldEndpointsMap, but\n\t// are no longer sending to newEndpointsMap. The proxier should make sure that\n\t// conntrack does not accidentally route any new connections to them.\n\tfor svcPortName, epList := range oldEndpointsMap {\n\t\tif svcPortName.Protocol != v1.ProtocolUDP {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, ep := range epList {\n\t\t\t// If the old endpoint wasn't Ready then there can't be stale\n\t\t\t// conntrack entries since there was no traffic sent to it.\n\t\t\tif !ep.IsReady() {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tdeleted := true\n\t\t\t// Check if the endpoint has changed, including if it went from\n\t\t\t// ready to not ready. If it did change stale entries for the old\n\t\t\t// endpoint have to be cleared.\n\t\t\tfor i := range newEndpointsMap[svcPortName] {\n\t\t\t\tif newEndpointsMap[svcPortName][i].Equal(ep) {\n\t\t\t\t\tdeleted = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif deleted {\n\t\t\t\tklog.V(4).InfoS(\"Deleted endpoint may have stale conntrack entries\", \"portName\", svcPortName, \"endpoint\", ep)\n\t\t\t\t*deletedUDPEndpoints = append(*deletedUDPEndpoints, ServiceEndpoint{Endpoint: ep.String(), ServicePortName: svcPortName})\n\t\t\t}\n\t\t}\n\t}\n\n\t// Detect services that have gone from 0 to non-0 ready endpoints. If there were\n\t// previously 0 endpoints, but someone tried to connect to it, then a conntrack\n\t// entry may have been created blackholing traffic to that IP, which should be\n\t// deleted now.\n\tfor svcPortName, epList := range newEndpointsMap {\n\t\tif svcPortName.Protocol != v1.ProtocolUDP {\n\t\t\tcontinue\n\t\t}\n\n\t\tepReady := 0\n\t\tfor _, ep := range epList {\n\t\t\tif ep.IsReady() {\n\t\t\t\tepReady++\n\t\t\t}\n\t\t}\n\n\t\toldEpReady := 0\n\t\tfor _, ep := range oldEndpointsMap[svcPortName] {\n\t\t\tif ep.IsReady() {\n\t\t\t\toldEpReady++\n\t\t\t}\n\t\t}\n\n\t\tif epReady \u003e 0 \u0026\u0026 oldEpReady == 0 {\n\t\t\t*newlyActiveUDPServices = append(*newlyActiveUDPServices, svcPortName)\n\t\t}\n\t}\n}","line":{"from":405,"to":467}} {"id":100008403,"name":"NewEndpointSliceCache","signature":"func NewEndpointSliceCache(hostname string, ipFamily v1.IPFamily, recorder events.EventRecorder, makeEndpointInfo makeEndpointFunc) *EndpointSliceCache","file":"pkg/proxy/endpointslicecache.go","code":"// NewEndpointSliceCache initializes an EndpointSliceCache.\nfunc NewEndpointSliceCache(hostname string, ipFamily v1.IPFamily, recorder events.EventRecorder, makeEndpointInfo makeEndpointFunc) *EndpointSliceCache {\n\tif makeEndpointInfo == nil {\n\t\tmakeEndpointInfo = standardEndpointInfo\n\t}\n\treturn \u0026EndpointSliceCache{\n\t\ttrackerByServiceMap: map[types.NamespacedName]*endpointSliceTracker{},\n\t\thostname: hostname,\n\t\tipFamily: ipFamily,\n\t\tmakeEndpointInfo: makeEndpointInfo,\n\t\trecorder: recorder,\n\t}\n}","line":{"from":95,"to":107}} {"id":100008404,"name":"newEndpointSliceTracker","signature":"func newEndpointSliceTracker() *endpointSliceTracker","file":"pkg/proxy/endpointslicecache.go","code":"// newEndpointSliceTracker initializes an endpointSliceTracker.\nfunc newEndpointSliceTracker() *endpointSliceTracker {\n\treturn \u0026endpointSliceTracker{\n\t\tapplied: endpointSliceInfoByName{},\n\t\tpending: endpointSliceInfoByName{},\n\t}\n}","line":{"from":109,"to":115}} {"id":100008405,"name":"newEndpointSliceInfo","signature":"func newEndpointSliceInfo(endpointSlice *discovery.EndpointSlice, remove bool) *endpointSliceInfo","file":"pkg/proxy/endpointslicecache.go","code":"// newEndpointSliceInfo generates endpointSliceInfo from an EndpointSlice.\nfunc newEndpointSliceInfo(endpointSlice *discovery.EndpointSlice, remove bool) *endpointSliceInfo {\n\tesInfo := \u0026endpointSliceInfo{\n\t\tPorts: make([]discovery.EndpointPort, len(endpointSlice.Ports)),\n\t\tEndpoints: []*endpointInfo{},\n\t\tRemove: remove,\n\t}\n\n\t// copy here to avoid mutating shared EndpointSlice object.\n\tcopy(esInfo.Ports, endpointSlice.Ports)\n\tsort.Sort(byPort(esInfo.Ports))\n\n\tif !remove {\n\t\tfor _, endpoint := range endpointSlice.Endpoints {\n\t\t\tepInfo := \u0026endpointInfo{\n\t\t\t\tAddresses: endpoint.Addresses,\n\t\t\t\tZone: endpoint.Zone,\n\t\t\t\tNodeName: endpoint.NodeName,\n\n\t\t\t\t// conditions\n\t\t\t\tReady: endpoint.Conditions.Ready == nil || *endpoint.Conditions.Ready,\n\t\t\t\tServing: endpoint.Conditions.Serving == nil || *endpoint.Conditions.Serving,\n\t\t\t\tTerminating: endpoint.Conditions.Terminating != nil \u0026\u0026 *endpoint.Conditions.Terminating,\n\t\t\t}\n\n\t\t\tif utilfeature.DefaultFeatureGate.Enabled(features.TopologyAwareHints) {\n\t\t\t\tif endpoint.Hints != nil \u0026\u0026 len(endpoint.Hints.ForZones) \u003e 0 {\n\t\t\t\t\tepInfo.ZoneHints = sets.String{}\n\t\t\t\t\tfor _, zone := range endpoint.Hints.ForZones {\n\t\t\t\t\t\tepInfo.ZoneHints.Insert(zone.Name)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tesInfo.Endpoints = append(esInfo.Endpoints, epInfo)\n\t\t}\n\n\t\tsort.Sort(byAddress(esInfo.Endpoints))\n\t}\n\n\treturn esInfo\n}","line":{"from":117,"to":158}} {"id":100008406,"name":"standardEndpointInfo","signature":"func standardEndpointInfo(ep *BaseEndpointInfo, _ *ServicePortName) Endpoint","file":"pkg/proxy/endpointslicecache.go","code":"// standardEndpointInfo is the default makeEndpointFunc.\nfunc standardEndpointInfo(ep *BaseEndpointInfo, _ *ServicePortName) Endpoint {\n\treturn ep\n}","line":{"from":160,"to":163}} {"id":100008407,"name":"updatePending","signature":"func (cache *EndpointSliceCache) updatePending(endpointSlice *discovery.EndpointSlice, remove bool) bool","file":"pkg/proxy/endpointslicecache.go","code":"// updatePending updates a pending slice in the cache.\nfunc (cache *EndpointSliceCache) updatePending(endpointSlice *discovery.EndpointSlice, remove bool) bool {\n\tserviceKey, sliceKey, err := endpointSliceCacheKeys(endpointSlice)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Error getting endpoint slice cache keys\")\n\t\treturn false\n\t}\n\n\tesInfo := newEndpointSliceInfo(endpointSlice, remove)\n\n\tcache.lock.Lock()\n\tdefer cache.lock.Unlock()\n\n\tif _, ok := cache.trackerByServiceMap[serviceKey]; !ok {\n\t\tcache.trackerByServiceMap[serviceKey] = newEndpointSliceTracker()\n\t}\n\n\tchanged := cache.esInfoChanged(serviceKey, sliceKey, esInfo)\n\n\tif changed {\n\t\tcache.trackerByServiceMap[serviceKey].pending[sliceKey] = esInfo\n\t}\n\n\treturn changed\n}","line":{"from":165,"to":189}} {"id":100008408,"name":"pendingChanges","signature":"func (cache *EndpointSliceCache) pendingChanges() sets.String","file":"pkg/proxy/endpointslicecache.go","code":"// pendingChanges returns a set whose keys are the names of the services whose endpoints\n// have changed since the last time checkoutChanges was called\nfunc (cache *EndpointSliceCache) pendingChanges() sets.String {\n\tcache.lock.Lock()\n\tdefer cache.lock.Unlock()\n\n\tchanges := sets.NewString()\n\tfor serviceNN, esTracker := range cache.trackerByServiceMap {\n\t\tif len(esTracker.pending) \u003e 0 {\n\t\t\tchanges.Insert(serviceNN.String())\n\t\t}\n\t}\n\treturn changes\n}","line":{"from":191,"to":204}} {"id":100008409,"name":"checkoutChanges","signature":"func (cache *EndpointSliceCache) checkoutChanges() []*endpointsChange","file":"pkg/proxy/endpointslicecache.go","code":"// checkoutChanges returns a list of all endpointsChanges that are\n// pending and then marks them as applied.\nfunc (cache *EndpointSliceCache) checkoutChanges() []*endpointsChange {\n\tchanges := []*endpointsChange{}\n\n\tcache.lock.Lock()\n\tdefer cache.lock.Unlock()\n\n\tfor serviceNN, esTracker := range cache.trackerByServiceMap {\n\t\tif len(esTracker.pending) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tchange := \u0026endpointsChange{}\n\n\t\tchange.previous = cache.getEndpointsMap(serviceNN, esTracker.applied)\n\n\t\tfor name, sliceInfo := range esTracker.pending {\n\t\t\tif sliceInfo.Remove {\n\t\t\t\tdelete(esTracker.applied, name)\n\t\t\t} else {\n\t\t\t\tesTracker.applied[name] = sliceInfo\n\t\t\t}\n\n\t\t\tdelete(esTracker.pending, name)\n\t\t}\n\n\t\tchange.current = cache.getEndpointsMap(serviceNN, esTracker.applied)\n\t\tchanges = append(changes, change)\n\t}\n\n\treturn changes\n}","line":{"from":206,"to":238}} {"id":100008410,"name":"getEndpointsMap","signature":"func (cache *EndpointSliceCache) getEndpointsMap(serviceNN types.NamespacedName, sliceInfoByName endpointSliceInfoByName) EndpointsMap","file":"pkg/proxy/endpointslicecache.go","code":"// getEndpointsMap computes an EndpointsMap for a given set of EndpointSlices.\nfunc (cache *EndpointSliceCache) getEndpointsMap(serviceNN types.NamespacedName, sliceInfoByName endpointSliceInfoByName) EndpointsMap {\n\tendpointInfoBySP := cache.endpointInfoByServicePort(serviceNN, sliceInfoByName)\n\treturn endpointsMapFromEndpointInfo(endpointInfoBySP)\n}","line":{"from":240,"to":244}} {"id":100008411,"name":"endpointInfoByServicePort","signature":"func (cache *EndpointSliceCache) endpointInfoByServicePort(serviceNN types.NamespacedName, sliceInfoByName endpointSliceInfoByName) spToEndpointMap","file":"pkg/proxy/endpointslicecache.go","code":"// endpointInfoByServicePort groups endpoint info by service port name and address.\nfunc (cache *EndpointSliceCache) endpointInfoByServicePort(serviceNN types.NamespacedName, sliceInfoByName endpointSliceInfoByName) spToEndpointMap {\n\tendpointInfoBySP := spToEndpointMap{}\n\n\tfor _, sliceInfo := range sliceInfoByName {\n\t\tfor _, port := range sliceInfo.Ports {\n\t\t\tif port.Name == nil {\n\t\t\t\tklog.ErrorS(nil, \"Ignoring port with nil name\", \"portName\", port.Name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// TODO: handle nil ports to mean \"all\"\n\t\t\tif port.Port == nil || *port.Port == int32(0) {\n\t\t\t\tklog.ErrorS(nil, \"Ignoring invalid endpoint port\", \"portName\", *port.Name)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tsvcPortName := ServicePortName{\n\t\t\t\tNamespacedName: serviceNN,\n\t\t\t\tPort: *port.Name,\n\t\t\t\tProtocol: *port.Protocol,\n\t\t\t}\n\n\t\t\tendpointInfoBySP[svcPortName] = cache.addEndpoints(\u0026svcPortName, int(*port.Port), endpointInfoBySP[svcPortName], sliceInfo.Endpoints)\n\t\t}\n\t}\n\n\treturn endpointInfoBySP\n}","line":{"from":246,"to":273}} {"id":100008412,"name":"addEndpoints","signature":"func (cache *EndpointSliceCache) addEndpoints(svcPortName *ServicePortName, portNum int, endpointSet map[string]Endpoint, endpoints []*endpointInfo) map[string]Endpoint","file":"pkg/proxy/endpointslicecache.go","code":"// addEndpoints adds endpointInfo for each unique endpoint.\nfunc (cache *EndpointSliceCache) addEndpoints(svcPortName *ServicePortName, portNum int, endpointSet map[string]Endpoint, endpoints []*endpointInfo) map[string]Endpoint {\n\tif endpointSet == nil {\n\t\tendpointSet = map[string]Endpoint{}\n\t}\n\n\t// iterate through endpoints to add them to endpointSet.\n\tfor _, endpoint := range endpoints {\n\t\tif len(endpoint.Addresses) == 0 {\n\t\t\tklog.ErrorS(nil, \"Ignoring invalid endpoint port with empty address\", \"endpoint\", endpoint)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Filter out the incorrect IP version case. Any endpoint port that\n\t\t// contains incorrect IP version will be ignored.\n\t\tif (cache.ipFamily == v1.IPv6Protocol) != utilnet.IsIPv6String(endpoint.Addresses[0]) {\n\t\t\t// Emit event on the corresponding service which had a different IP\n\t\t\t// version than the endpoint.\n\t\t\tutilproxy.LogAndEmitIncorrectIPVersionEvent(cache.recorder, \"endpointslice\", endpoint.Addresses[0], svcPortName.NamespacedName.Namespace, svcPortName.NamespacedName.Name, \"\")\n\t\t\tcontinue\n\t\t}\n\n\t\tisLocal := false\n\t\tnodeName := \"\"\n\t\tif endpoint.NodeName != nil {\n\t\t\tisLocal = cache.isLocal(*endpoint.NodeName)\n\t\t\tnodeName = *endpoint.NodeName\n\t\t}\n\n\t\tzone := \"\"\n\t\tif endpoint.Zone != nil {\n\t\t\tzone = *endpoint.Zone\n\t\t}\n\n\t\tendpointInfo := newBaseEndpointInfo(endpoint.Addresses[0], nodeName, zone, portNum, isLocal,\n\t\t\tendpoint.Ready, endpoint.Serving, endpoint.Terminating, endpoint.ZoneHints)\n\n\t\t// This logic ensures we're deduplicating potential overlapping endpoints\n\t\t// isLocal should not vary between matching endpoints, but if it does, we\n\t\t// favor a true value here if it exists.\n\t\tif _, exists := endpointSet[endpointInfo.String()]; !exists || isLocal {\n\t\t\tendpointSet[endpointInfo.String()] = cache.makeEndpointInfo(endpointInfo, svcPortName)\n\t\t}\n\t}\n\n\treturn endpointSet\n}","line":{"from":275,"to":321}} {"id":100008413,"name":"isLocal","signature":"func (cache *EndpointSliceCache) isLocal(hostname string) bool","file":"pkg/proxy/endpointslicecache.go","code":"func (cache *EndpointSliceCache) isLocal(hostname string) bool {\n\treturn len(cache.hostname) \u003e 0 \u0026\u0026 hostname == cache.hostname\n}","line":{"from":323,"to":325}} {"id":100008414,"name":"esInfoChanged","signature":"func (cache *EndpointSliceCache) esInfoChanged(serviceKey types.NamespacedName, sliceKey string, esInfo *endpointSliceInfo) bool","file":"pkg/proxy/endpointslicecache.go","code":"// esInfoChanged returns true if the esInfo parameter should be set as a new\n// pending value in the cache.\nfunc (cache *EndpointSliceCache) esInfoChanged(serviceKey types.NamespacedName, sliceKey string, esInfo *endpointSliceInfo) bool {\n\tif _, ok := cache.trackerByServiceMap[serviceKey]; ok {\n\t\tappliedInfo, appliedOk := cache.trackerByServiceMap[serviceKey].applied[sliceKey]\n\t\tpendingInfo, pendingOk := cache.trackerByServiceMap[serviceKey].pending[sliceKey]\n\n\t\t// If there's already a pending value, return whether or not this would\n\t\t// change that.\n\t\tif pendingOk {\n\t\t\treturn !reflect.DeepEqual(esInfo, pendingInfo)\n\t\t}\n\n\t\t// If there's already an applied value, return whether or not this would\n\t\t// change that.\n\t\tif appliedOk {\n\t\t\treturn !reflect.DeepEqual(esInfo, appliedInfo)\n\t\t}\n\t}\n\n\t// If this is marked for removal and does not exist in the cache, no changes\n\t// are necessary.\n\tif esInfo.Remove {\n\t\treturn false\n\t}\n\n\t// If not in the cache, and not marked for removal, it should be added.\n\treturn true\n}","line":{"from":327,"to":355}} {"id":100008415,"name":"endpointsMapFromEndpointInfo","signature":"func endpointsMapFromEndpointInfo(endpointInfoBySP map[ServicePortName]map[string]Endpoint) EndpointsMap","file":"pkg/proxy/endpointslicecache.go","code":"// endpointsMapFromEndpointInfo computes an endpointsMap from endpointInfo that\n// has been grouped by service port and IP.\nfunc endpointsMapFromEndpointInfo(endpointInfoBySP map[ServicePortName]map[string]Endpoint) EndpointsMap {\n\tendpointsMap := EndpointsMap{}\n\n\t// transform endpointInfoByServicePort into an endpointsMap with sorted IPs.\n\tfor svcPortName, endpointSet := range endpointInfoBySP {\n\t\tif len(endpointSet) \u003e 0 {\n\t\t\tendpointsMap[svcPortName] = []Endpoint{}\n\t\t\tfor _, endpointInfo := range endpointSet {\n\t\t\t\tendpointsMap[svcPortName] = append(endpointsMap[svcPortName], endpointInfo)\n\n\t\t\t}\n\t\t\t// Ensure endpoints are always returned in the same order to simplify diffing.\n\t\t\tsort.Sort(byEndpoint(endpointsMap[svcPortName]))\n\n\t\t\tklog.V(3).InfoS(\"Setting endpoints for service port name\", \"portName\", svcPortName, \"endpoints\", formatEndpointsList(endpointsMap[svcPortName]))\n\t\t}\n\t}\n\n\treturn endpointsMap\n}","line":{"from":357,"to":378}} {"id":100008416,"name":"formatEndpointsList","signature":"func formatEndpointsList(endpoints []Endpoint) []string","file":"pkg/proxy/endpointslicecache.go","code":"// formatEndpointsList returns a string list converted from an endpoints list.\nfunc formatEndpointsList(endpoints []Endpoint) []string {\n\tvar formattedList []string\n\tfor _, ep := range endpoints {\n\t\tformattedList = append(formattedList, ep.String())\n\t}\n\treturn formattedList\n}","line":{"from":380,"to":387}} {"id":100008417,"name":"endpointSliceCacheKeys","signature":"func endpointSliceCacheKeys(endpointSlice *discovery.EndpointSlice) (types.NamespacedName, string, error)","file":"pkg/proxy/endpointslicecache.go","code":"// endpointSliceCacheKeys returns cache keys used for a given EndpointSlice.\nfunc endpointSliceCacheKeys(endpointSlice *discovery.EndpointSlice) (types.NamespacedName, string, error) {\n\tvar err error\n\tserviceName, ok := endpointSlice.Labels[discovery.LabelServiceName]\n\tif !ok || serviceName == \"\" {\n\t\terr = fmt.Errorf(\"no %s label set on endpoint slice: %s\", discovery.LabelServiceName, endpointSlice.Name)\n\t} else if endpointSlice.Namespace == \"\" || endpointSlice.Name == \"\" {\n\t\terr = fmt.Errorf(\"expected EndpointSlice name and namespace to be set: %v\", endpointSlice)\n\t}\n\treturn types.NamespacedName{Namespace: endpointSlice.Namespace, Name: serviceName}, endpointSlice.Name, err\n}","line":{"from":389,"to":399}} {"id":100008418,"name":"Len","signature":"func (e byAddress) Len() int","file":"pkg/proxy/endpointslicecache.go","code":"func (e byAddress) Len() int {\n\treturn len(e)\n}","line":{"from":404,"to":406}} {"id":100008419,"name":"Swap","signature":"func (e byAddress) Swap(i, j int)","file":"pkg/proxy/endpointslicecache.go","code":"func (e byAddress) Swap(i, j int) {\n\te[i], e[j] = e[j], e[i]\n}","line":{"from":407,"to":409}} {"id":100008420,"name":"Less","signature":"func (e byAddress) Less(i, j int) bool","file":"pkg/proxy/endpointslicecache.go","code":"func (e byAddress) Less(i, j int) bool {\n\treturn strings.Join(e[i].Addresses, \",\") \u003c strings.Join(e[j].Addresses, \",\")\n}","line":{"from":410,"to":412}} {"id":100008421,"name":"Len","signature":"func (e byEndpoint) Len() int","file":"pkg/proxy/endpointslicecache.go","code":"func (e byEndpoint) Len() int {\n\treturn len(e)\n}","line":{"from":417,"to":419}} {"id":100008422,"name":"Swap","signature":"func (e byEndpoint) Swap(i, j int)","file":"pkg/proxy/endpointslicecache.go","code":"func (e byEndpoint) Swap(i, j int) {\n\te[i], e[j] = e[j], e[i]\n}","line":{"from":420,"to":422}} {"id":100008423,"name":"Less","signature":"func (e byEndpoint) Less(i, j int) bool","file":"pkg/proxy/endpointslicecache.go","code":"func (e byEndpoint) Less(i, j int) bool {\n\treturn e[i].String() \u003c e[j].String()\n}","line":{"from":423,"to":425}} {"id":100008424,"name":"Len","signature":"func (p byPort) Len() int","file":"pkg/proxy/endpointslicecache.go","code":"func (p byPort) Len() int {\n\treturn len(p)\n}","line":{"from":430,"to":432}} {"id":100008425,"name":"Swap","signature":"func (p byPort) Swap(i, j int)","file":"pkg/proxy/endpointslicecache.go","code":"func (p byPort) Swap(i, j int) {\n\tp[i], p[j] = p[j], p[i]\n}","line":{"from":433,"to":435}} {"id":100008426,"name":"Less","signature":"func (p byPort) Less(i, j int) bool","file":"pkg/proxy/endpointslicecache.go","code":"func (p byPort) Less(i, j int) bool {\n\treturn *p[i].Port \u003c *p[j].Port\n}","line":{"from":436,"to":438}} {"id":100008427,"name":"Listen","signature":"func (stdNetListener) Listen(addr string) (net.Listener, error)","file":"pkg/proxy/healthcheck/common.go","code":"func (stdNetListener) Listen(addr string) (net.Listener, error) {\n\treturn net.Listen(\"tcp\", addr)\n}","line":{"from":48,"to":50}} {"id":100008428,"name":"New","signature":"func (stdHTTPServerFactory) New(addr string, handler http.Handler) httpServer","file":"pkg/proxy/healthcheck/common.go","code":"func (stdHTTPServerFactory) New(addr string, handler http.Handler) httpServer {\n\treturn \u0026http.Server{\n\t\tAddr: addr,\n\t\tHandler: handler,\n\t}\n}","line":{"from":57,"to":62}} {"id":100008429,"name":"NewProxierHealthServer","signature":"func NewProxierHealthServer(addr string, healthTimeout time.Duration, recorder events.EventRecorder, nodeRef *v1.ObjectReference) ProxierHealthUpdater","file":"pkg/proxy/healthcheck/proxier_health.go","code":"// NewProxierHealthServer returns a proxier health http server.\nfunc NewProxierHealthServer(addr string, healthTimeout time.Duration, recorder events.EventRecorder, nodeRef *v1.ObjectReference) ProxierHealthUpdater {\n\treturn newProxierHealthServer(stdNetListener{}, stdHTTPServerFactory{}, clock.RealClock{}, addr, healthTimeout, recorder, nodeRef)\n}","line":{"from":67,"to":70}} {"id":100008430,"name":"newProxierHealthServer","signature":"func newProxierHealthServer(listener listener, httpServerFactory httpServerFactory, c clock.Clock, addr string, healthTimeout time.Duration, recorder events.EventRecorder, nodeRef *v1.ObjectReference) *proxierHealthServer","file":"pkg/proxy/healthcheck/proxier_health.go","code":"func newProxierHealthServer(listener listener, httpServerFactory httpServerFactory, c clock.Clock, addr string, healthTimeout time.Duration, recorder events.EventRecorder, nodeRef *v1.ObjectReference) *proxierHealthServer {\n\treturn \u0026proxierHealthServer{\n\t\tlistener: listener,\n\t\thttpFactory: httpServerFactory,\n\t\tclock: c,\n\t\taddr: addr,\n\t\thealthTimeout: healthTimeout,\n\t\trecorder: recorder,\n\t\tnodeRef: nodeRef,\n\t}\n}","line":{"from":72,"to":82}} {"id":100008431,"name":"Updated","signature":"func (hs *proxierHealthServer) Updated()","file":"pkg/proxy/healthcheck/proxier_health.go","code":"// Updated indicates that kube-proxy has successfully updated its backend, so it should\n// be considered healthy now.\nfunc (hs *proxierHealthServer) Updated() {\n\ths.oldestPendingQueued.Store(zeroTime)\n\ths.lastUpdated.Store(hs.clock.Now())\n}","line":{"from":84,"to":89}} {"id":100008432,"name":"QueuedUpdate","signature":"func (hs *proxierHealthServer) QueuedUpdate()","file":"pkg/proxy/healthcheck/proxier_health.go","code":"// QueuedUpdate indicates that the proxy has received changes from the apiserver but\n// has not yet pushed them to its backend. If the proxy does not call Updated within the\n// healthTimeout time then it will be considered unhealthy.\nfunc (hs *proxierHealthServer) QueuedUpdate() {\n\t// Set oldestPendingQueued only if it's currently zero\n\ths.oldestPendingQueued.CompareAndSwap(zeroTime, hs.clock.Now())\n}","line":{"from":91,"to":97}} {"id":100008433,"name":"IsHealthy","signature":"func (hs *proxierHealthServer) IsHealthy() bool","file":"pkg/proxy/healthcheck/proxier_health.go","code":"// IsHealthy returns the proxier's health state, following the same definition\n// the HTTP server defines.\nfunc (hs *proxierHealthServer) IsHealthy() bool {\n\tisHealthy, _, _ := hs.isHealthy()\n\treturn isHealthy\n}","line":{"from":99,"to":104}} {"id":100008434,"name":"isHealthy","signature":"func (hs *proxierHealthServer) isHealthy() (bool, time.Time, time.Time)","file":"pkg/proxy/healthcheck/proxier_health.go","code":"func (hs *proxierHealthServer) isHealthy() (bool, time.Time, time.Time) {\n\tvar oldestPendingQueued, lastUpdated time.Time\n\tif val := hs.oldestPendingQueued.Load(); val != nil {\n\t\toldestPendingQueued = val.(time.Time)\n\t}\n\tif val := hs.lastUpdated.Load(); val != nil {\n\t\tlastUpdated = val.(time.Time)\n\t}\n\tcurrentTime := hs.clock.Now()\n\n\thealthy := false\n\tswitch {\n\tcase oldestPendingQueued.IsZero():\n\t\t// The proxy is healthy while it's starting up\n\t\t// or the proxy is fully synced.\n\t\thealthy = true\n\tcase currentTime.Sub(oldestPendingQueued) \u003c hs.healthTimeout:\n\t\t// There's an unprocessed update queued, but it's not late yet\n\t\thealthy = true\n\t}\n\n\treturn healthy, lastUpdated, currentTime\n}","line":{"from":106,"to":128}} {"id":100008435,"name":"Run","signature":"func (hs *proxierHealthServer) Run() error","file":"pkg/proxy/healthcheck/proxier_health.go","code":"// Run starts the healthz HTTP server and blocks until it exits.\nfunc (hs *proxierHealthServer) Run() error {\n\tserveMux := http.NewServeMux()\n\tserveMux.Handle(\"/healthz\", healthzHandler{hs: hs})\n\tserver := hs.httpFactory.New(hs.addr, serveMux)\n\n\tlistener, err := hs.listener.Listen(hs.addr)\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"failed to start proxier healthz on %s: %v\", hs.addr, err)\n\t\t// TODO(thockin): move eventing back to caller\n\t\tif hs.recorder != nil {\n\t\t\ths.recorder.Eventf(hs.nodeRef, nil, api.EventTypeWarning, \"FailedToStartProxierHealthcheck\", \"StartKubeProxy\", msg)\n\t\t}\n\t\treturn fmt.Errorf(\"%v\", msg)\n\t}\n\n\tklog.V(3).InfoS(\"Starting healthz HTTP server\", \"address\", hs.addr)\n\n\tif err := server.Serve(listener); err != nil {\n\t\treturn fmt.Errorf(\"proxier healthz closed with error: %v\", err)\n\t}\n\treturn nil\n}","line":{"from":130,"to":152}} {"id":100008436,"name":"ServeHTTP","signature":"func (h healthzHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request)","file":"pkg/proxy/healthcheck/proxier_health.go","code":"func (h healthzHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {\n\thealthy, lastUpdated, currentTime := h.hs.isHealthy()\n\tresp.Header().Set(\"Content-Type\", \"application/json\")\n\tresp.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\tif !healthy {\n\t\tresp.WriteHeader(http.StatusServiceUnavailable)\n\t} else {\n\t\tresp.WriteHeader(http.StatusOK)\n\t\t// In older releases, the returned \"lastUpdated\" time indicated the last\n\t\t// time the proxier sync loop ran, even if nothing had changed. To\n\t\t// preserve compatibility, we use the same semantics: the returned\n\t\t// lastUpdated value is \"recent\" if the server is healthy. The kube-proxy\n\t\t// metrics provide more detailed information.\n\t\tlastUpdated = currentTime\n\t}\n\tfmt.Fprintf(resp, `{\"lastUpdated\": %q,\"currentTime\": %q}`, lastUpdated, currentTime)\n}","line":{"from":158,"to":174}} {"id":100008437,"name":"newServiceHealthServer","signature":"func newServiceHealthServer(hostname string, recorder events.EventRecorder, listener listener, factory httpServerFactory, nodePortAddresses *utilproxy.NodePortAddresses, healthzServer proxierHealthChecker) ServiceHealthServer","file":"pkg/proxy/healthcheck/service_health.go","code":"func newServiceHealthServer(hostname string, recorder events.EventRecorder, listener listener, factory httpServerFactory, nodePortAddresses *utilproxy.NodePortAddresses, healthzServer proxierHealthChecker) ServiceHealthServer {\n\n\tnodeAddresses, err := nodePortAddresses.GetNodeAddresses(utilproxy.RealNetwork{})\n\tif err != nil || nodeAddresses.Len() == 0 {\n\t\tklog.ErrorS(err, \"Failed to get node ip address matching node port addresses, health check port will listen to all node addresses\", \"nodePortAddresses\", nodePortAddresses)\n\t\tnodeAddresses = sets.NewString()\n\t\tnodeAddresses.Insert(utilproxy.IPv4ZeroCIDR)\n\t}\n\n\t// if any of the addresses is zero cidr then we listen\n\t// to old style :\u003cport\u003e\n\tfor _, addr := range nodeAddresses.List() {\n\t\tif utilproxy.IsZeroCIDR(addr) {\n\t\t\tnodeAddresses = sets.NewString(\"\")\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn \u0026server{\n\t\thostname: hostname,\n\t\trecorder: recorder,\n\t\tlistener: listener,\n\t\thttpFactory: factory,\n\t\thealthzServer: healthzServer,\n\t\tservices: map[types.NamespacedName]*hcInstance{},\n\t\tnodeAddresses: nodeAddresses,\n\t}\n}","line":{"from":61,"to":88}} {"id":100008438,"name":"NewServiceHealthServer","signature":"func NewServiceHealthServer(hostname string, recorder events.EventRecorder, nodePortAddresses *utilproxy.NodePortAddresses, healthzServer proxierHealthChecker) ServiceHealthServer","file":"pkg/proxy/healthcheck/service_health.go","code":"// NewServiceHealthServer allocates a new service healthcheck server manager\nfunc NewServiceHealthServer(hostname string, recorder events.EventRecorder, nodePortAddresses *utilproxy.NodePortAddresses, healthzServer proxierHealthChecker) ServiceHealthServer {\n\treturn newServiceHealthServer(hostname, recorder, stdNetListener{}, stdHTTPServerFactory{}, nodePortAddresses, healthzServer)\n}","line":{"from":90,"to":93}} {"id":100008439,"name":"SyncServices","signature":"func (hcs *server) SyncServices(newServices map[types.NamespacedName]uint16) error","file":"pkg/proxy/healthcheck/service_health.go","code":"func (hcs *server) SyncServices(newServices map[types.NamespacedName]uint16) error {\n\thcs.lock.Lock()\n\tdefer hcs.lock.Unlock()\n\n\t// Remove any that are not needed any more.\n\tfor nsn, svc := range hcs.services {\n\t\tif port, found := newServices[nsn]; !found || port != svc.port {\n\t\t\tklog.V(2).InfoS(\"Closing healthcheck\", \"service\", nsn, \"port\", svc.port)\n\n\t\t\t// errors are loged in closeAll()\n\t\t\t_ = svc.closeAll()\n\n\t\t\tdelete(hcs.services, nsn)\n\n\t\t}\n\t}\n\n\t// Add any that are needed.\n\tfor nsn, port := range newServices {\n\t\tif hcs.services[nsn] != nil {\n\t\t\tklog.V(3).InfoS(\"Existing healthcheck\", \"service\", nsn, \"port\", port)\n\t\t\tcontinue\n\t\t}\n\n\t\tklog.V(2).InfoS(\"Opening healthcheck\", \"service\", nsn, \"port\", port)\n\n\t\tsvc := \u0026hcInstance{nsn: nsn, port: port}\n\t\terr := svc.listenAndServeAll(hcs)\n\n\t\tif err != nil {\n\t\t\tmsg := fmt.Sprintf(\"node %s failed to start healthcheck %q on port %d: %v\", hcs.hostname, nsn.String(), port, err)\n\n\t\t\tif hcs.recorder != nil {\n\t\t\t\thcs.recorder.Eventf(\n\t\t\t\t\t\u0026v1.ObjectReference{\n\t\t\t\t\t\tKind: \"Service\",\n\t\t\t\t\t\tNamespace: nsn.Namespace,\n\t\t\t\t\t\tName: nsn.Name,\n\t\t\t\t\t\tUID: types.UID(nsn.String()),\n\t\t\t\t\t}, nil, api.EventTypeWarning, \"FailedToStartServiceHealthcheck\", \"Listen\", msg)\n\t\t\t}\n\t\t\tklog.ErrorS(err, \"Failed to start healthcheck\", \"node\", hcs.hostname, \"service\", nsn, \"port\", port)\n\t\t\tcontinue\n\t\t}\n\t\thcs.services[nsn] = svc\n\t}\n\treturn nil\n}","line":{"from":109,"to":156}} {"id":100008440,"name":"listenAndServeAll","signature":"func (hcI *hcInstance) listenAndServeAll(hcs *server) error","file":"pkg/proxy/healthcheck/service_health.go","code":"// listenAll opens health check port on all the addresses provided\nfunc (hcI *hcInstance) listenAndServeAll(hcs *server) error {\n\tvar err error\n\tvar listener net.Listener\n\n\taddresses := hcs.nodeAddresses.List()\n\thcI.httpServers = make([]httpServer, 0, len(addresses))\n\n\t// for each of the node addresses start listening and serving\n\tfor _, address := range addresses {\n\t\taddr := net.JoinHostPort(address, fmt.Sprint(hcI.port))\n\t\t// create http server\n\t\thttpSrv := hcs.httpFactory.New(addr, hcHandler{name: hcI.nsn, hcs: hcs})\n\t\t// start listener\n\t\tlistener, err = hcs.listener.Listen(addr)\n\t\tif err != nil {\n\t\t\t// must close whatever have been previously opened\n\t\t\t// to allow a retry/or port ownership change as needed\n\t\t\t_ = hcI.closeAll()\n\t\t\treturn err\n\t\t}\n\n\t\t// start serving\n\t\tgo func(hcI *hcInstance, listener net.Listener, httpSrv httpServer) {\n\t\t\t// Serve() will exit and return ErrServerClosed when the http server is closed.\n\t\t\tklog.V(3).InfoS(\"Starting goroutine for healthcheck\", \"service\", hcI.nsn, \"address\", listener.Addr())\n\t\t\tif err := httpSrv.Serve(listener); err != nil \u0026\u0026 err != http.ErrServerClosed {\n\t\t\t\tklog.ErrorS(err, \"Healthcheck closed\", \"service\", hcI.nsn)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tklog.V(3).InfoS(\"Healthcheck closed\", \"service\", hcI.nsn, \"address\", listener.Addr())\n\t\t}(hcI, listener, httpSrv)\n\n\t\thcI.httpServers = append(hcI.httpServers, httpSrv)\n\t}\n\n\treturn nil\n}","line":{"from":167,"to":204}} {"id":100008441,"name":"closeAll","signature":"func (hcI *hcInstance) closeAll() error","file":"pkg/proxy/healthcheck/service_health.go","code":"func (hcI *hcInstance) closeAll() error {\n\terrors := []error{}\n\tfor _, server := range hcI.httpServers {\n\t\tif err := server.Close(); err != nil {\n\t\t\tklog.ErrorS(err, \"Error closing server for health check service\", \"service\", hcI.nsn)\n\t\t\terrors = append(errors, err)\n\t\t}\n\t}\n\n\tif len(errors) \u003e 0 {\n\t\treturn utilerrors.NewAggregate(errors)\n\t}\n\n\treturn nil\n}","line":{"from":206,"to":220}} {"id":100008442,"name":"ServeHTTP","signature":"func (h hcHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request)","file":"pkg/proxy/healthcheck/service_health.go","code":"func (h hcHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {\n\th.hcs.lock.RLock()\n\tsvc, ok := h.hcs.services[h.name]\n\tif !ok || svc == nil {\n\t\th.hcs.lock.RUnlock()\n\t\tklog.ErrorS(nil, \"Received request for closed healthcheck\", \"service\", h.name)\n\t\treturn\n\t}\n\tcount := svc.endpoints\n\tkubeProxyHealthy := h.hcs.healthzServer.IsHealthy()\n\th.hcs.lock.RUnlock()\n\n\tresp.Header().Set(\"Content-Type\", \"application/json\")\n\tresp.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\tif count != 0 \u0026\u0026 kubeProxyHealthy {\n\t\tresp.WriteHeader(http.StatusOK)\n\t} else {\n\t\tresp.WriteHeader(http.StatusServiceUnavailable)\n\t}\n\tfmt.Fprint(resp, strings.Trim(dedent.Dedent(fmt.Sprintf(`\n\t\t{\n\t\t\t\"service\": {\n\t\t\t\t\"namespace\": %q,\n\t\t\t\t\"name\": %q\n\t\t\t},\n\t\t\t\"localEndpoints\": %d,\n\t\t\t\"serviceProxyHealthy\": %v\n\t\t}\n\t\t`, h.name.Namespace, h.name.Name, count, kubeProxyHealthy)), \"\\n\"))\n}","line":{"from":229,"to":258}} {"id":100008443,"name":"SyncEndpoints","signature":"func (hcs *server) SyncEndpoints(newEndpoints map[types.NamespacedName]int) error","file":"pkg/proxy/healthcheck/service_health.go","code":"func (hcs *server) SyncEndpoints(newEndpoints map[types.NamespacedName]int) error {\n\thcs.lock.Lock()\n\tdefer hcs.lock.Unlock()\n\n\tfor nsn, count := range newEndpoints {\n\t\tif hcs.services[nsn] == nil {\n\t\t\tcontinue\n\t\t}\n\t\tklog.V(3).InfoS(\"Reporting endpoints for healthcheck\", \"endpointCount\", count, \"service\", nsn)\n\t\thcs.services[nsn].endpoints = count\n\t}\n\tfor nsn, hci := range hcs.services {\n\t\tif _, found := newEndpoints[nsn]; !found {\n\t\t\thci.endpoints = 0\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":260,"to":277}} {"id":100008444,"name":"NewFakeServiceHealthServer","signature":"func NewFakeServiceHealthServer() ServiceHealthServer","file":"pkg/proxy/healthcheck/service_health.go","code":"// NewFakeServiceHealthServer allocates a new fake service healthcheck server manager\nfunc NewFakeServiceHealthServer() ServiceHealthServer {\n\treturn FakeServiceHealthServer{}\n}","line":{"from":282,"to":285}} {"id":100008445,"name":"SyncServices","signature":"func (fake FakeServiceHealthServer) SyncServices(_ map[types.NamespacedName]uint16) error","file":"pkg/proxy/healthcheck/service_health.go","code":"// SyncServices is part of ServiceHealthServer\nfunc (fake FakeServiceHealthServer) SyncServices(_ map[types.NamespacedName]uint16) error {\n\treturn nil\n}","line":{"from":287,"to":290}} {"id":100008446,"name":"SyncEndpoints","signature":"func (fake FakeServiceHealthServer) SyncEndpoints(_ map[types.NamespacedName]int) error","file":"pkg/proxy/healthcheck/service_health.go","code":"// SyncEndpoints is part of ServiceHealthServer\nfunc (fake FakeServiceHealthServer) SyncEndpoints(_ map[types.NamespacedName]int) error {\n\treturn nil\n}","line":{"from":292,"to":295}} {"id":100008447,"name":"newServiceInfo","signature":"func newServiceInfo(port *v1.ServicePort, service *v1.Service, bsvcPortInfo *proxy.BaseServicePortInfo) proxy.ServicePort","file":"pkg/proxy/iptables/proxier.go","code":"// returns a new proxy.ServicePort which abstracts a serviceInfo\nfunc newServiceInfo(port *v1.ServicePort, service *v1.Service, bsvcPortInfo *proxy.BaseServicePortInfo) proxy.ServicePort {\n\tsvcPort := \u0026servicePortInfo{BaseServicePortInfo: bsvcPortInfo}\n\n\t// Store the following for performance reasons.\n\tsvcName := types.NamespacedName{Namespace: service.Namespace, Name: service.Name}\n\tsvcPortName := proxy.ServicePortName{NamespacedName: svcName, Port: port.Name}\n\tprotocol := strings.ToLower(string(svcPort.Protocol()))\n\tsvcPort.nameString = svcPortName.String()\n\tsvcPort.clusterPolicyChainName = servicePortPolicyClusterChain(svcPort.nameString, protocol)\n\tsvcPort.localPolicyChainName = servicePortPolicyLocalChainName(svcPort.nameString, protocol)\n\tsvcPort.firewallChainName = serviceFirewallChainName(svcPort.nameString, protocol)\n\tsvcPort.externalChainName = serviceExternalChainName(svcPort.nameString, protocol)\n\n\treturn svcPort\n}","line":{"from":109,"to":124}} {"id":100008448,"name":"newEndpointInfo","signature":"func newEndpointInfo(baseInfo *proxy.BaseEndpointInfo, svcPortName *proxy.ServicePortName) proxy.Endpoint","file":"pkg/proxy/iptables/proxier.go","code":"// returns a new proxy.Endpoint which abstracts a endpointsInfo\nfunc newEndpointInfo(baseInfo *proxy.BaseEndpointInfo, svcPortName *proxy.ServicePortName) proxy.Endpoint {\n\treturn \u0026endpointsInfo{\n\t\tBaseEndpointInfo: baseInfo,\n\t\tChainName: servicePortEndpointChainName(svcPortName.String(), strings.ToLower(string(svcPortName.Protocol)), baseInfo.Endpoint),\n\t}\n}","line":{"from":133,"to":139}} {"id":100008449,"name":"Equal","signature":"func (e *endpointsInfo) Equal(other proxy.Endpoint) bool","file":"pkg/proxy/iptables/proxier.go","code":"// Equal overrides the Equal() function implemented by proxy.BaseEndpointInfo.\nfunc (e *endpointsInfo) Equal(other proxy.Endpoint) bool {\n\to, ok := other.(*endpointsInfo)\n\tif !ok {\n\t\tklog.ErrorS(nil, \"Failed to cast endpointsInfo\")\n\t\treturn false\n\t}\n\treturn e.Endpoint == o.Endpoint \u0026\u0026\n\t\te.IsLocal == o.IsLocal \u0026\u0026\n\t\te.ChainName == o.ChainName \u0026\u0026\n\t\te.Ready == o.Ready\n}","line":{"from":141,"to":152}} {"id":100008450,"name":"NewProxier","signature":"func NewProxier(ipFamily v1.IPFamily,","file":"pkg/proxy/iptables/proxier.go","code":"// NewProxier returns a new Proxier given an iptables Interface instance.\n// Because of the iptables logic, it is assumed that there is only a single Proxier active on a machine.\n// An error will be returned if iptables fails to update or acquire the initial lock.\n// Once a proxier is created, it will keep iptables up to date in the background and\n// will not terminate if a particular iptables call fails.\nfunc NewProxier(ipFamily v1.IPFamily,\n\tipt utiliptables.Interface,\n\tsysctl utilsysctl.Interface,\n\texec utilexec.Interface,\n\tsyncPeriod time.Duration,\n\tminSyncPeriod time.Duration,\n\tmasqueradeAll bool,\n\tlocalhostNodePorts bool,\n\tmasqueradeBit int,\n\tlocalDetector proxyutiliptables.LocalTrafficDetector,\n\thostname string,\n\tnodeIP net.IP,\n\trecorder events.EventRecorder,\n\thealthzServer healthcheck.ProxierHealthUpdater,\n\tnodePortAddressStrings []string,\n) (*Proxier, error) {\n\tnodePortAddresses := utilproxy.NewNodePortAddresses(nodePortAddressStrings)\n\n\tif !nodePortAddresses.ContainsIPv4Loopback() {\n\t\tlocalhostNodePorts = false\n\t}\n\tif localhostNodePorts {\n\t\t// Set the route_localnet sysctl we need for exposing NodePorts on loopback addresses\n\t\t// Refer to https://issues.k8s.io/90259\n\t\tklog.InfoS(\"Setting route_localnet=1 to allow node-ports on localhost; to change this either disable iptables.localhostNodePorts (--iptables-localhost-nodeports) or set nodePortAddresses (--nodeport-addresses) to filter loopback addresses\")\n\t\tif err := utilproxy.EnsureSysctl(sysctl, sysctlRouteLocalnet, 1); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Proxy needs br_netfilter and bridge-nf-call-iptables=1 when containers\n\t// are connected to a Linux bridge (but not SDN bridges). Until most\n\t// plugins handle this, log when config is missing\n\tif val, err := sysctl.GetSysctl(sysctlBridgeCallIPTables); err == nil \u0026\u0026 val != 1 {\n\t\tklog.InfoS(\"Missing br-netfilter module or unset sysctl br-nf-call-iptables, proxy may not work as intended\")\n\t}\n\n\t// Generate the masquerade mark to use for SNAT rules.\n\tmasqueradeValue := 1 \u003c\u003c uint(masqueradeBit)\n\tmasqueradeMark := fmt.Sprintf(\"%#08x\", masqueradeValue)\n\tklog.V(2).InfoS(\"Using iptables mark for masquerade\", \"ipFamily\", ipt.Protocol(), \"mark\", masqueradeMark)\n\n\tserviceHealthServer := healthcheck.NewServiceHealthServer(hostname, recorder, nodePortAddresses, healthzServer)\n\n\tproxier := \u0026Proxier{\n\t\tsvcPortMap: make(proxy.ServicePortMap),\n\t\tserviceChanges: proxy.NewServiceChangeTracker(newServiceInfo, ipFamily, recorder, nil),\n\t\tendpointsMap: make(proxy.EndpointsMap),\n\t\tendpointsChanges: proxy.NewEndpointChangeTracker(hostname, newEndpointInfo, ipFamily, recorder, nil),\n\t\tneedFullSync: true,\n\t\tsyncPeriod: syncPeriod,\n\t\tiptables: ipt,\n\t\tmasqueradeAll: masqueradeAll,\n\t\tmasqueradeMark: masqueradeMark,\n\t\texec: exec,\n\t\tlocalDetector: localDetector,\n\t\thostname: hostname,\n\t\tnodeIP: nodeIP,\n\t\trecorder: recorder,\n\t\tserviceHealthServer: serviceHealthServer,\n\t\thealthzServer: healthzServer,\n\t\tprecomputedProbabilities: make([]string, 0, 1001),\n\t\tiptablesData: bytes.NewBuffer(nil),\n\t\texistingFilterChainsData: bytes.NewBuffer(nil),\n\t\tfilterChains: utilproxy.LineBuffer{},\n\t\tfilterRules: utilproxy.LineBuffer{},\n\t\tnatChains: utilproxy.LineBuffer{},\n\t\tnatRules: utilproxy.LineBuffer{},\n\t\tlocalhostNodePorts: localhostNodePorts,\n\t\tnodePortAddresses: nodePortAddresses,\n\t\tnetworkInterfacer: utilproxy.RealNetwork{},\n\t}\n\n\tburstSyncs := 2\n\tklog.V(2).InfoS(\"Iptables sync params\", \"ipFamily\", ipt.Protocol(), \"minSyncPeriod\", minSyncPeriod, \"syncPeriod\", syncPeriod, \"burstSyncs\", burstSyncs)\n\t// We pass syncPeriod to ipt.Monitor, which will call us only if it needs to.\n\t// We need to pass *some* maxInterval to NewBoundedFrequencyRunner anyway though.\n\t// time.Hour is arbitrary.\n\tproxier.syncRunner = async.NewBoundedFrequencyRunner(\"sync-runner\", proxier.syncProxyRules, minSyncPeriod, time.Hour, burstSyncs)\n\n\tgo ipt.Monitor(kubeProxyCanaryChain, []utiliptables.Table{utiliptables.TableMangle, utiliptables.TableNAT, utiliptables.TableFilter},\n\t\tproxier.forceSyncProxyRules, syncPeriod, wait.NeverStop)\n\n\tif ipt.HasRandomFully() {\n\t\tklog.V(2).InfoS(\"Iptables supports --random-fully\", \"ipFamily\", ipt.Protocol())\n\t} else {\n\t\tklog.V(2).InfoS(\"Iptables does not support --random-fully\", \"ipFamily\", ipt.Protocol())\n\t}\n\n\treturn proxier, nil\n}","line":{"from":224,"to":319}} {"id":100008451,"name":"NewDualStackProxier","signature":"func NewDualStackProxier(","file":"pkg/proxy/iptables/proxier.go","code":"// NewDualStackProxier creates a MetaProxier instance, with IPv4 and IPv6 proxies.\nfunc NewDualStackProxier(\n\tipt [2]utiliptables.Interface,\n\tsysctl utilsysctl.Interface,\n\texec utilexec.Interface,\n\tsyncPeriod time.Duration,\n\tminSyncPeriod time.Duration,\n\tmasqueradeAll bool,\n\tlocalhostNodePorts bool,\n\tmasqueradeBit int,\n\tlocalDetectors [2]proxyutiliptables.LocalTrafficDetector,\n\thostname string,\n\tnodeIP [2]net.IP,\n\trecorder events.EventRecorder,\n\thealthzServer healthcheck.ProxierHealthUpdater,\n\tnodePortAddresses []string,\n) (proxy.Provider, error) {\n\t// Create an ipv4 instance of the single-stack proxier\n\tipFamilyMap := utilproxy.MapCIDRsByIPFamily(nodePortAddresses)\n\tipv4Proxier, err := NewProxier(v1.IPv4Protocol, ipt[0], sysctl,\n\t\texec, syncPeriod, minSyncPeriod, masqueradeAll, localhostNodePorts, masqueradeBit, localDetectors[0], hostname,\n\t\tnodeIP[0], recorder, healthzServer, ipFamilyMap[v1.IPv4Protocol])\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create ipv4 proxier: %v\", err)\n\t}\n\n\tipv6Proxier, err := NewProxier(v1.IPv6Protocol, ipt[1], sysctl,\n\t\texec, syncPeriod, minSyncPeriod, masqueradeAll, false, masqueradeBit, localDetectors[1], hostname,\n\t\tnodeIP[1], recorder, healthzServer, ipFamilyMap[v1.IPv6Protocol])\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create ipv6 proxier: %v\", err)\n\t}\n\treturn metaproxier.NewMetaProxier(ipv4Proxier, ipv6Proxier), nil\n}","line":{"from":321,"to":354}} {"id":100008452,"name":"CleanupLeftovers","signature":"func CleanupLeftovers(ipt utiliptables.Interface) (encounteredError bool)","file":"pkg/proxy/iptables/proxier.go","code":"// CleanupLeftovers removes all iptables rules and chains created by the Proxier\n// It returns true if an error was encountered. Errors are logged.\nfunc CleanupLeftovers(ipt utiliptables.Interface) (encounteredError bool) {\n\t// Unlink our chains\n\tfor _, jump := range append(iptablesJumpChains, iptablesCleanupOnlyChains...) {\n\t\targs := append(jump.extraArgs,\n\t\t\t\"-m\", \"comment\", \"--comment\", jump.comment,\n\t\t\t\"-j\", string(jump.dstChain),\n\t\t)\n\t\tif err := ipt.DeleteRule(jump.table, jump.srcChain, args...); err != nil {\n\t\t\tif !utiliptables.IsNotFoundError(err) {\n\t\t\t\tklog.ErrorS(err, \"Error removing pure-iptables proxy rule\")\n\t\t\t\tencounteredError = true\n\t\t\t}\n\t\t}\n\t}\n\n\t// Flush and remove all of our \"-t nat\" chains.\n\tiptablesData := bytes.NewBuffer(nil)\n\tif err := ipt.SaveInto(utiliptables.TableNAT, iptablesData); err != nil {\n\t\tklog.ErrorS(err, \"Failed to execute iptables-save\", \"table\", utiliptables.TableNAT)\n\t\tencounteredError = true\n\t} else {\n\t\texistingNATChains := utiliptables.GetChainsFromTable(iptablesData.Bytes())\n\t\tnatChains := \u0026utilproxy.LineBuffer{}\n\t\tnatRules := \u0026utilproxy.LineBuffer{}\n\t\tnatChains.Write(\"*nat\")\n\t\t// Start with chains we know we need to remove.\n\t\tfor _, chain := range []utiliptables.Chain{kubeServicesChain, kubeNodePortsChain, kubePostroutingChain} {\n\t\t\tif _, found := existingNATChains[chain]; found {\n\t\t\t\tchainString := string(chain)\n\t\t\t\tnatChains.Write(utiliptables.MakeChainLine(chain)) // flush\n\t\t\t\tnatRules.Write(\"-X\", chainString) // delete\n\t\t\t}\n\t\t}\n\t\t// Hunt for service and endpoint chains.\n\t\tfor chain := range existingNATChains {\n\t\t\tchainString := string(chain)\n\t\t\tif isServiceChainName(chainString) {\n\t\t\t\tnatChains.Write(utiliptables.MakeChainLine(chain)) // flush\n\t\t\t\tnatRules.Write(\"-X\", chainString) // delete\n\t\t\t}\n\t\t}\n\t\tnatRules.Write(\"COMMIT\")\n\t\tnatLines := append(natChains.Bytes(), natRules.Bytes()...)\n\t\t// Write it.\n\t\terr = ipt.Restore(utiliptables.TableNAT, natLines, utiliptables.NoFlushTables, utiliptables.RestoreCounters)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to execute iptables-restore\", \"table\", utiliptables.TableNAT)\n\t\t\tmetrics.IptablesRestoreFailuresTotal.Inc()\n\t\t\tencounteredError = true\n\t\t}\n\t}\n\n\t// Flush and remove all of our \"-t filter\" chains.\n\tiptablesData.Reset()\n\tif err := ipt.SaveInto(utiliptables.TableFilter, iptablesData); err != nil {\n\t\tklog.ErrorS(err, \"Failed to execute iptables-save\", \"table\", utiliptables.TableFilter)\n\t\tencounteredError = true\n\t} else {\n\t\texistingFilterChains := utiliptables.GetChainsFromTable(iptablesData.Bytes())\n\t\tfilterChains := \u0026utilproxy.LineBuffer{}\n\t\tfilterRules := \u0026utilproxy.LineBuffer{}\n\t\tfilterChains.Write(\"*filter\")\n\t\tfor _, chain := range []utiliptables.Chain{kubeServicesChain, kubeExternalServicesChain, kubeForwardChain, kubeNodePortsChain} {\n\t\t\tif _, found := existingFilterChains[chain]; found {\n\t\t\t\tchainString := string(chain)\n\t\t\t\tfilterChains.Write(utiliptables.MakeChainLine(chain))\n\t\t\t\tfilterRules.Write(\"-X\", chainString)\n\t\t\t}\n\t\t}\n\t\tfilterRules.Write(\"COMMIT\")\n\t\tfilterLines := append(filterChains.Bytes(), filterRules.Bytes()...)\n\t\t// Write it.\n\t\tif err := ipt.Restore(utiliptables.TableFilter, filterLines, utiliptables.NoFlushTables, utiliptables.RestoreCounters); err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to execute iptables-restore\", \"table\", utiliptables.TableFilter)\n\t\t\tmetrics.IptablesRestoreFailuresTotal.Inc()\n\t\t\tencounteredError = true\n\t\t}\n\t}\n\treturn encounteredError\n}","line":{"from":394,"to":475}} {"id":100008453,"name":"computeProbability","signature":"func computeProbability(n int) string","file":"pkg/proxy/iptables/proxier.go","code":"func computeProbability(n int) string {\n\treturn fmt.Sprintf(\"%0.10f\", 1.0/float64(n))\n}","line":{"from":477,"to":479}} {"id":100008454,"name":"precomputeProbabilities","signature":"func (proxier *Proxier) precomputeProbabilities(numberOfPrecomputed int)","file":"pkg/proxy/iptables/proxier.go","code":"// This assumes proxier.mu is held\nfunc (proxier *Proxier) precomputeProbabilities(numberOfPrecomputed int) {\n\tif len(proxier.precomputedProbabilities) == 0 {\n\t\tproxier.precomputedProbabilities = append(proxier.precomputedProbabilities, \"\u003cbad value\u003e\")\n\t}\n\tfor i := len(proxier.precomputedProbabilities); i \u003c= numberOfPrecomputed; i++ {\n\t\tproxier.precomputedProbabilities = append(proxier.precomputedProbabilities, computeProbability(i))\n\t}\n}","line":{"from":481,"to":489}} {"id":100008455,"name":"probability","signature":"func (proxier *Proxier) probability(n int) string","file":"pkg/proxy/iptables/proxier.go","code":"// This assumes proxier.mu is held\nfunc (proxier *Proxier) probability(n int) string {\n\tif n \u003e= len(proxier.precomputedProbabilities) {\n\t\tproxier.precomputeProbabilities(n)\n\t}\n\treturn proxier.precomputedProbabilities[n]\n}","line":{"from":491,"to":497}} {"id":100008456,"name":"Sync","signature":"func (proxier *Proxier) Sync()","file":"pkg/proxy/iptables/proxier.go","code":"// Sync is called to synchronize the proxier state to iptables as soon as possible.\nfunc (proxier *Proxier) Sync() {\n\tif proxier.healthzServer != nil {\n\t\tproxier.healthzServer.QueuedUpdate()\n\t}\n\tmetrics.SyncProxyRulesLastQueuedTimestamp.SetToCurrentTime()\n\tproxier.syncRunner.Run()\n}","line":{"from":499,"to":506}} {"id":100008457,"name":"SyncLoop","signature":"func (proxier *Proxier) SyncLoop()","file":"pkg/proxy/iptables/proxier.go","code":"// SyncLoop runs periodic work. This is expected to run as a goroutine or as the main loop of the app. It does not return.\nfunc (proxier *Proxier) SyncLoop() {\n\t// Update healthz timestamp at beginning in case Sync() never succeeds.\n\tif proxier.healthzServer != nil {\n\t\tproxier.healthzServer.Updated()\n\t}\n\n\t// synthesize \"last change queued\" time as the informers are syncing.\n\tmetrics.SyncProxyRulesLastQueuedTimestamp.SetToCurrentTime()\n\tproxier.syncRunner.Loop(wait.NeverStop)\n}","line":{"from":508,"to":518}} {"id":100008458,"name":"setInitialized","signature":"func (proxier *Proxier) setInitialized(value bool)","file":"pkg/proxy/iptables/proxier.go","code":"func (proxier *Proxier) setInitialized(value bool) {\n\tvar initialized int32\n\tif value {\n\t\tinitialized = 1\n\t}\n\tatomic.StoreInt32(\u0026proxier.initialized, initialized)\n}","line":{"from":520,"to":526}} {"id":100008459,"name":"isInitialized","signature":"func (proxier *Proxier) isInitialized() bool","file":"pkg/proxy/iptables/proxier.go","code":"func (proxier *Proxier) isInitialized() bool {\n\treturn atomic.LoadInt32(\u0026proxier.initialized) \u003e 0\n}","line":{"from":528,"to":530}} {"id":100008460,"name":"OnServiceAdd","signature":"func (proxier *Proxier) OnServiceAdd(service *v1.Service)","file":"pkg/proxy/iptables/proxier.go","code":"// OnServiceAdd is called whenever creation of new service object\n// is observed.\nfunc (proxier *Proxier) OnServiceAdd(service *v1.Service) {\n\tproxier.OnServiceUpdate(nil, service)\n}","line":{"from":532,"to":536}} {"id":100008461,"name":"OnServiceUpdate","signature":"func (proxier *Proxier) OnServiceUpdate(oldService, service *v1.Service)","file":"pkg/proxy/iptables/proxier.go","code":"// OnServiceUpdate is called whenever modification of an existing\n// service object is observed.\nfunc (proxier *Proxier) OnServiceUpdate(oldService, service *v1.Service) {\n\tif proxier.serviceChanges.Update(oldService, service) \u0026\u0026 proxier.isInitialized() {\n\t\tproxier.Sync()\n\t}\n}","line":{"from":538,"to":544}} {"id":100008462,"name":"OnServiceDelete","signature":"func (proxier *Proxier) OnServiceDelete(service *v1.Service)","file":"pkg/proxy/iptables/proxier.go","code":"// OnServiceDelete is called whenever deletion of an existing service\n// object is observed.\nfunc (proxier *Proxier) OnServiceDelete(service *v1.Service) {\n\tproxier.OnServiceUpdate(service, nil)\n\n}","line":{"from":546,"to":551}} {"id":100008463,"name":"OnServiceSynced","signature":"func (proxier *Proxier) OnServiceSynced()","file":"pkg/proxy/iptables/proxier.go","code":"// OnServiceSynced is called once all the initial event handlers were\n// called and the state is fully propagated to local cache.\nfunc (proxier *Proxier) OnServiceSynced() {\n\tproxier.mu.Lock()\n\tproxier.servicesSynced = true\n\tproxier.setInitialized(proxier.endpointSlicesSynced)\n\tproxier.mu.Unlock()\n\n\t// Sync unconditionally - this is called once per lifetime.\n\tproxier.syncProxyRules()\n}","line":{"from":553,"to":563}} {"id":100008464,"name":"OnEndpointSliceAdd","signature":"func (proxier *Proxier) OnEndpointSliceAdd(endpointSlice *discovery.EndpointSlice)","file":"pkg/proxy/iptables/proxier.go","code":"// OnEndpointSliceAdd is called whenever creation of a new endpoint slice object\n// is observed.\nfunc (proxier *Proxier) OnEndpointSliceAdd(endpointSlice *discovery.EndpointSlice) {\n\tif proxier.endpointsChanges.EndpointSliceUpdate(endpointSlice, false) \u0026\u0026 proxier.isInitialized() {\n\t\tproxier.Sync()\n\t}\n}","line":{"from":565,"to":571}} {"id":100008465,"name":"OnEndpointSliceUpdate","signature":"func (proxier *Proxier) OnEndpointSliceUpdate(_, endpointSlice *discovery.EndpointSlice)","file":"pkg/proxy/iptables/proxier.go","code":"// OnEndpointSliceUpdate is called whenever modification of an existing endpoint\n// slice object is observed.\nfunc (proxier *Proxier) OnEndpointSliceUpdate(_, endpointSlice *discovery.EndpointSlice) {\n\tif proxier.endpointsChanges.EndpointSliceUpdate(endpointSlice, false) \u0026\u0026 proxier.isInitialized() {\n\t\tproxier.Sync()\n\t}\n}","line":{"from":573,"to":579}} {"id":100008466,"name":"OnEndpointSliceDelete","signature":"func (proxier *Proxier) OnEndpointSliceDelete(endpointSlice *discovery.EndpointSlice)","file":"pkg/proxy/iptables/proxier.go","code":"// OnEndpointSliceDelete is called whenever deletion of an existing endpoint slice\n// object is observed.\nfunc (proxier *Proxier) OnEndpointSliceDelete(endpointSlice *discovery.EndpointSlice) {\n\tif proxier.endpointsChanges.EndpointSliceUpdate(endpointSlice, true) \u0026\u0026 proxier.isInitialized() {\n\t\tproxier.Sync()\n\t}\n}","line":{"from":581,"to":587}} {"id":100008467,"name":"OnEndpointSlicesSynced","signature":"func (proxier *Proxier) OnEndpointSlicesSynced()","file":"pkg/proxy/iptables/proxier.go","code":"// OnEndpointSlicesSynced is called once all the initial event handlers were\n// called and the state is fully propagated to local cache.\nfunc (proxier *Proxier) OnEndpointSlicesSynced() {\n\tproxier.mu.Lock()\n\tproxier.endpointSlicesSynced = true\n\tproxier.setInitialized(proxier.servicesSynced)\n\tproxier.mu.Unlock()\n\n\t// Sync unconditionally - this is called once per lifetime.\n\tproxier.syncProxyRules()\n}","line":{"from":589,"to":599}} {"id":100008468,"name":"OnNodeAdd","signature":"func (proxier *Proxier) OnNodeAdd(node *v1.Node)","file":"pkg/proxy/iptables/proxier.go","code":"// OnNodeAdd is called whenever creation of new node object\n// is observed.\nfunc (proxier *Proxier) OnNodeAdd(node *v1.Node) {\n\tif node.Name != proxier.hostname {\n\t\tklog.ErrorS(nil, \"Received a watch event for a node that doesn't match the current node\",\n\t\t\t\"eventNode\", node.Name, \"currentNode\", proxier.hostname)\n\t\treturn\n\t}\n\n\tif reflect.DeepEqual(proxier.nodeLabels, node.Labels) {\n\t\treturn\n\t}\n\n\tproxier.mu.Lock()\n\tproxier.nodeLabels = map[string]string{}\n\tfor k, v := range node.Labels {\n\t\tproxier.nodeLabels[k] = v\n\t}\n\tproxier.needFullSync = true\n\tproxier.mu.Unlock()\n\tklog.V(4).InfoS(\"Updated proxier node labels\", \"labels\", node.Labels)\n\n\tproxier.Sync()\n}","line":{"from":601,"to":624}} {"id":100008469,"name":"OnNodeUpdate","signature":"func (proxier *Proxier) OnNodeUpdate(oldNode, node *v1.Node)","file":"pkg/proxy/iptables/proxier.go","code":"// OnNodeUpdate is called whenever modification of an existing\n// node object is observed.\nfunc (proxier *Proxier) OnNodeUpdate(oldNode, node *v1.Node) {\n\tif node.Name != proxier.hostname {\n\t\tklog.ErrorS(nil, \"Received a watch event for a node that doesn't match the current node\",\n\t\t\t\"eventNode\", node.Name, \"currentNode\", proxier.hostname)\n\t\treturn\n\t}\n\n\tif reflect.DeepEqual(proxier.nodeLabels, node.Labels) {\n\t\treturn\n\t}\n\n\tproxier.mu.Lock()\n\tproxier.nodeLabels = map[string]string{}\n\tfor k, v := range node.Labels {\n\t\tproxier.nodeLabels[k] = v\n\t}\n\tproxier.needFullSync = true\n\tproxier.mu.Unlock()\n\tklog.V(4).InfoS(\"Updated proxier node labels\", \"labels\", node.Labels)\n\n\tproxier.Sync()\n}","line":{"from":626,"to":649}} {"id":100008470,"name":"OnNodeDelete","signature":"func (proxier *Proxier) OnNodeDelete(node *v1.Node)","file":"pkg/proxy/iptables/proxier.go","code":"// OnNodeDelete is called whenever deletion of an existing node\n// object is observed.\nfunc (proxier *Proxier) OnNodeDelete(node *v1.Node) {\n\tif node.Name != proxier.hostname {\n\t\tklog.ErrorS(nil, \"Received a watch event for a node that doesn't match the current node\",\n\t\t\t\"eventNode\", node.Name, \"currentNode\", proxier.hostname)\n\t\treturn\n\t}\n\tproxier.mu.Lock()\n\tproxier.nodeLabels = nil\n\tproxier.needFullSync = true\n\tproxier.mu.Unlock()\n\n\tproxier.Sync()\n}","line":{"from":651,"to":665}} {"id":100008471,"name":"OnNodeSynced","signature":"func (proxier *Proxier) OnNodeSynced()","file":"pkg/proxy/iptables/proxier.go","code":"// OnNodeSynced is called once all the initial event handlers were\n// called and the state is fully propagated to local cache.\nfunc (proxier *Proxier) OnNodeSynced() {\n}","line":{"from":667,"to":670}} {"id":100008472,"name":"portProtoHash","signature":"func portProtoHash(servicePortName string, protocol string) string","file":"pkg/proxy/iptables/proxier.go","code":"// portProtoHash takes the ServicePortName and protocol for a service\n// returns the associated 16 character hash. This is computed by hashing (sha256)\n// then encoding to base32 and truncating to 16 chars. We do this because IPTables\n// Chain Names must be \u003c= 28 chars long, and the longer they are the harder they are to read.\nfunc portProtoHash(servicePortName string, protocol string) string {\n\thash := sha256.Sum256([]byte(servicePortName + protocol))\n\tencoded := base32.StdEncoding.EncodeToString(hash[:])\n\treturn encoded[:16]\n}","line":{"from":672,"to":680}} {"id":100008473,"name":"servicePortPolicyClusterChain","signature":"func servicePortPolicyClusterChain(servicePortName string, protocol string) utiliptables.Chain","file":"pkg/proxy/iptables/proxier.go","code":"// servicePortPolicyClusterChain returns the name of the KUBE-SVC-XXXX chain for a service, which is the\n// main iptables chain for that service, used for dispatching to endpoints when using `Cluster`\n// traffic policy.\nfunc servicePortPolicyClusterChain(servicePortName string, protocol string) utiliptables.Chain {\n\treturn utiliptables.Chain(servicePortPolicyClusterChainNamePrefix + portProtoHash(servicePortName, protocol))\n}","line":{"from":693,"to":698}} {"id":100008474,"name":"servicePortPolicyLocalChainName","signature":"func servicePortPolicyLocalChainName(servicePortName string, protocol string) utiliptables.Chain","file":"pkg/proxy/iptables/proxier.go","code":"// servicePortPolicyLocalChainName returns the name of the KUBE-SVL-XXXX chain for a service, which\n// handles dispatching to local endpoints when using `Local` traffic policy. This chain only\n// exists if the service has `Local` internal or external traffic policy.\nfunc servicePortPolicyLocalChainName(servicePortName string, protocol string) utiliptables.Chain {\n\treturn utiliptables.Chain(servicePortPolicyLocalChainNamePrefix + portProtoHash(servicePortName, protocol))\n}","line":{"from":700,"to":705}} {"id":100008475,"name":"serviceFirewallChainName","signature":"func serviceFirewallChainName(servicePortName string, protocol string) utiliptables.Chain","file":"pkg/proxy/iptables/proxier.go","code":"// serviceFirewallChainName returns the name of the KUBE-FW-XXXX chain for a service, which\n// is used to implement the filtering for the LoadBalancerSourceRanges feature.\nfunc serviceFirewallChainName(servicePortName string, protocol string) utiliptables.Chain {\n\treturn utiliptables.Chain(serviceFirewallChainNamePrefix + portProtoHash(servicePortName, protocol))\n}","line":{"from":707,"to":711}} {"id":100008476,"name":"serviceExternalChainName","signature":"func serviceExternalChainName(servicePortName string, protocol string) utiliptables.Chain","file":"pkg/proxy/iptables/proxier.go","code":"// serviceExternalChainName returns the name of the KUBE-EXT-XXXX chain for a service, which\n// implements \"short-circuiting\" for internally-originated external-destination traffic when using\n// `Local` external traffic policy. It forwards traffic from local sources to the KUBE-SVC-XXXX\n// chain and traffic from external sources to the KUBE-SVL-XXXX chain.\nfunc serviceExternalChainName(servicePortName string, protocol string) utiliptables.Chain {\n\treturn utiliptables.Chain(serviceExternalChainNamePrefix + portProtoHash(servicePortName, protocol))\n}","line":{"from":713,"to":719}} {"id":100008477,"name":"servicePortEndpointChainName","signature":"func servicePortEndpointChainName(servicePortName string, protocol string, endpoint string) utiliptables.Chain","file":"pkg/proxy/iptables/proxier.go","code":"// servicePortEndpointChainName returns the name of the KUBE-SEP-XXXX chain for a particular\n// service endpoint.\nfunc servicePortEndpointChainName(servicePortName string, protocol string, endpoint string) utiliptables.Chain {\n\thash := sha256.Sum256([]byte(servicePortName + protocol + endpoint))\n\tencoded := base32.StdEncoding.EncodeToString(hash[:])\n\treturn utiliptables.Chain(servicePortEndpointChainNamePrefix + encoded[:16])\n}","line":{"from":721,"to":727}} {"id":100008478,"name":"isServiceChainName","signature":"func isServiceChainName(chainString string) bool","file":"pkg/proxy/iptables/proxier.go","code":"func isServiceChainName(chainString string) bool {\n\tprefixes := []string{\n\t\tservicePortPolicyClusterChainNamePrefix,\n\t\tservicePortPolicyLocalChainNamePrefix,\n\t\tservicePortEndpointChainNamePrefix,\n\t\tserviceFirewallChainNamePrefix,\n\t\tserviceExternalChainNamePrefix,\n\t\tdeprecatedServiceLBChainNamePrefix,\n\t}\n\n\tfor _, p := range prefixes {\n\t\tif strings.HasPrefix(chainString, p) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":729,"to":745}} {"id":100008479,"name":"deleteUDPEndpointConnections","signature":"func (proxier *Proxier) deleteUDPEndpointConnections(deletedUDPEndpoints []proxy.ServiceEndpoint)","file":"pkg/proxy/iptables/proxier.go","code":"// After a UDP endpoint has been removed, we must flush any pending conntrack entries to it, or else we\n// risk sending more traffic to it, all of which will be lost (because UDP).\n// This assumes the proxier mutex is held\n// TODO: move it to util\nfunc (proxier *Proxier) deleteUDPEndpointConnections(deletedUDPEndpoints []proxy.ServiceEndpoint) {\n\tfor _, epSvcPair := range deletedUDPEndpoints {\n\t\tif svcInfo, ok := proxier.svcPortMap[epSvcPair.ServicePortName]; ok {\n\t\t\tendpointIP := utilproxy.IPPart(epSvcPair.Endpoint)\n\t\t\tnodePort := svcInfo.NodePort()\n\t\t\tvar err error\n\t\t\tif nodePort != 0 {\n\t\t\t\terr = conntrack.ClearEntriesForPortNAT(proxier.exec, endpointIP, nodePort, v1.ProtocolUDP)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"Failed to delete nodeport-related endpoint connections\", \"servicePortName\", epSvcPair.ServicePortName)\n\t\t\t\t}\n\t\t\t}\n\t\t\terr = conntrack.ClearEntriesForNAT(proxier.exec, svcInfo.ClusterIP().String(), endpointIP, v1.ProtocolUDP)\n\t\t\tif err != nil {\n\t\t\t\tklog.ErrorS(err, \"Failed to delete endpoint connections\", \"servicePortName\", epSvcPair.ServicePortName)\n\t\t\t}\n\t\t\tfor _, extIP := range svcInfo.ExternalIPStrings() {\n\t\t\t\terr := conntrack.ClearEntriesForNAT(proxier.exec, extIP, endpointIP, v1.ProtocolUDP)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"Failed to delete endpoint connections for externalIP\", \"servicePortName\", epSvcPair.ServicePortName, \"externalIP\", extIP)\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, lbIP := range svcInfo.LoadBalancerIPStrings() {\n\t\t\t\terr := conntrack.ClearEntriesForNAT(proxier.exec, lbIP, endpointIP, v1.ProtocolUDP)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"Failed to delete endpoint connections for LoadBalancerIP\", \"servicePortName\", epSvcPair.ServicePortName, \"loadBalancerIP\", lbIP)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":747,"to":781}} {"id":100008480,"name":"appendServiceCommentLocked","signature":"func (proxier *Proxier) appendServiceCommentLocked(args []string, svcName string) []string","file":"pkg/proxy/iptables/proxier.go","code":"// Assumes proxier.mu is held.\nfunc (proxier *Proxier) appendServiceCommentLocked(args []string, svcName string) []string {\n\t// Not printing these comments, can reduce size of iptables (in case of large\n\t// number of endpoints) even by 40%+. So if total number of endpoint chains\n\t// is large enough, we simply drop those comments.\n\tif proxier.largeClusterMode {\n\t\treturn args\n\t}\n\treturn append(args, \"-m\", \"comment\", \"--comment\", svcName)\n}","line":{"from":783,"to":792}} {"id":100008481,"name":"forceSyncProxyRules","signature":"func (proxier *Proxier) forceSyncProxyRules()","file":"pkg/proxy/iptables/proxier.go","code":"// Called by the iptables.Monitor, and in response to topology changes; this calls\n// syncProxyRules() and tells it to resync all services, regardless of whether the\n// Service or Endpoints/EndpointSlice objects themselves have changed\nfunc (proxier *Proxier) forceSyncProxyRules() {\n\tproxier.mu.Lock()\n\tproxier.needFullSync = true\n\tproxier.mu.Unlock()\n\n\tproxier.syncProxyRules()\n}","line":{"from":794,"to":803}} {"id":100008482,"name":"syncProxyRules","signature":"func (proxier *Proxier) syncProxyRules()","file":"pkg/proxy/iptables/proxier.go","code":"// This is where all of the iptables-save/restore calls happen.\n// The only other iptables rules are those that are setup in iptablesInit()\n// This assumes proxier.mu is NOT held\nfunc (proxier *Proxier) syncProxyRules() {\n\tproxier.mu.Lock()\n\tdefer proxier.mu.Unlock()\n\n\t// don't sync rules till we've received services and endpoints\n\tif !proxier.isInitialized() {\n\t\tklog.V(2).InfoS(\"Not syncing iptables until Services and Endpoints have been received from master\")\n\t\treturn\n\t}\n\n\t// Keep track of how long syncs take.\n\tstart := time.Now()\n\tdefer func() {\n\t\tmetrics.SyncProxyRulesLatency.Observe(metrics.SinceInSeconds(start))\n\t\tklog.V(2).InfoS(\"SyncProxyRules complete\", \"elapsed\", time.Since(start))\n\t}()\n\n\ttryPartialSync := !proxier.needFullSync \u0026\u0026 utilfeature.DefaultFeatureGate.Enabled(features.MinimizeIPTablesRestore)\n\tvar serviceChanged, endpointsChanged sets.String\n\tif tryPartialSync {\n\t\tserviceChanged = proxier.serviceChanges.PendingChanges()\n\t\tendpointsChanged = proxier.endpointsChanges.PendingChanges()\n\t}\n\tserviceUpdateResult := proxier.svcPortMap.Update(proxier.serviceChanges)\n\tendpointUpdateResult := proxier.endpointsMap.Update(proxier.endpointsChanges)\n\n\t// We need to detect stale connections to UDP Services so we\n\t// can clean dangling conntrack entries that can blackhole traffic.\n\tconntrackCleanupServiceIPs := serviceUpdateResult.DeletedUDPClusterIPs\n\tconntrackCleanupServiceNodePorts := sets.NewInt()\n\t// merge stale services gathered from updateEndpointsMap\n\t// an UDP service that changes from 0 to non-0 endpoints is considered stale.\n\tfor _, svcPortName := range endpointUpdateResult.NewlyActiveUDPServices {\n\t\tif svcInfo, ok := proxier.svcPortMap[svcPortName]; ok {\n\t\t\tklog.V(4).InfoS(\"Newly-active UDP service may have stale conntrack entries\", \"servicePortName\", svcPortName)\n\t\t\tconntrackCleanupServiceIPs.Insert(svcInfo.ClusterIP().String())\n\t\t\tfor _, extIP := range svcInfo.ExternalIPStrings() {\n\t\t\t\tconntrackCleanupServiceIPs.Insert(extIP)\n\t\t\t}\n\t\t\tfor _, lbIP := range svcInfo.LoadBalancerIPStrings() {\n\t\t\t\tconntrackCleanupServiceIPs.Insert(lbIP)\n\t\t\t}\n\t\t\tnodePort := svcInfo.NodePort()\n\t\t\tif svcInfo.Protocol() == v1.ProtocolUDP \u0026\u0026 nodePort != 0 {\n\t\t\t\tconntrackCleanupServiceNodePorts.Insert(nodePort)\n\t\t\t}\n\t\t}\n\t}\n\n\tklog.V(2).InfoS(\"Syncing iptables rules\")\n\n\tsuccess := false\n\tdefer func() {\n\t\tif !success {\n\t\t\tklog.InfoS(\"Sync failed\", \"retryingTime\", proxier.syncPeriod)\n\t\t\tproxier.syncRunner.RetryAfter(proxier.syncPeriod)\n\t\t\tif tryPartialSync {\n\t\t\t\tmetrics.IptablesPartialRestoreFailuresTotal.Inc()\n\t\t\t}\n\t\t\t// proxier.serviceChanges and proxier.endpointChanges have already\n\t\t\t// been flushed, so we've lost the state needed to be able to do\n\t\t\t// a partial sync.\n\t\t\tproxier.needFullSync = true\n\t\t}\n\t}()\n\n\tif !tryPartialSync {\n\t\t// Ensure that our jump rules (eg from PREROUTING to KUBE-SERVICES) exist.\n\t\t// We can't do this as part of the iptables-restore because we don't want\n\t\t// to specify/replace *all* of the rules in PREROUTING, etc.\n\t\t//\n\t\t// We need to create these rules when kube-proxy first starts, and we need\n\t\t// to recreate them if the utiliptables Monitor detects that iptables has\n\t\t// been flushed. In both of those cases, the code will force a full sync.\n\t\t// In all other cases, it ought to be safe to assume that the rules\n\t\t// already exist, so we'll skip this step when doing a partial sync, to\n\t\t// save us from having to invoke /sbin/iptables 20 times on each sync\n\t\t// (which will be very slow on hosts with lots of iptables rules).\n\t\tfor _, jump := range append(iptablesJumpChains, iptablesKubeletJumpChains...) {\n\t\t\tif _, err := proxier.iptables.EnsureChain(jump.table, jump.dstChain); err != nil {\n\t\t\t\tklog.ErrorS(err, \"Failed to ensure chain exists\", \"table\", jump.table, \"chain\", jump.dstChain)\n\t\t\t\treturn\n\t\t\t}\n\t\t\targs := jump.extraArgs\n\t\t\tif jump.comment != \"\" {\n\t\t\t\targs = append(args, \"-m\", \"comment\", \"--comment\", jump.comment)\n\t\t\t}\n\t\t\targs = append(args, \"-j\", string(jump.dstChain))\n\t\t\tif _, err := proxier.iptables.EnsureRule(utiliptables.Prepend, jump.table, jump.srcChain, args...); err != nil {\n\t\t\t\tklog.ErrorS(err, \"Failed to ensure chain jumps\", \"table\", jump.table, \"srcChain\", jump.srcChain, \"dstChain\", jump.dstChain)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\t//\n\t// Below this point we will not return until we try to write the iptables rules.\n\t//\n\n\t// Reset all buffers used later.\n\t// This is to avoid memory reallocations and thus improve performance.\n\tproxier.filterChains.Reset()\n\tproxier.filterRules.Reset()\n\tproxier.natChains.Reset()\n\tproxier.natRules.Reset()\n\n\t// Write chain lines for all the \"top-level\" chains we'll be filling in\n\tfor _, chainName := range []utiliptables.Chain{kubeServicesChain, kubeExternalServicesChain, kubeForwardChain, kubeNodePortsChain, kubeProxyFirewallChain} {\n\t\tproxier.filterChains.Write(utiliptables.MakeChainLine(chainName))\n\t}\n\tfor _, chainName := range []utiliptables.Chain{kubeServicesChain, kubeNodePortsChain, kubePostroutingChain, kubeMarkMasqChain} {\n\t\tproxier.natChains.Write(utiliptables.MakeChainLine(chainName))\n\t}\n\n\t// Install the kubernetes-specific postrouting rules. We use a whole chain for\n\t// this so that it is easier to flush and change, for example if the mark\n\t// value should ever change.\n\t// NB: THIS MUST MATCH the corresponding code in the kubelet\n\tproxier.natRules.Write(\n\t\t\"-A\", string(kubePostroutingChain),\n\t\t\"-m\", \"mark\", \"!\", \"--mark\", fmt.Sprintf(\"%s/%s\", proxier.masqueradeMark, proxier.masqueradeMark),\n\t\t\"-j\", \"RETURN\",\n\t)\n\t// Clear the mark to avoid re-masquerading if the packet re-traverses the network stack.\n\tproxier.natRules.Write(\n\t\t\"-A\", string(kubePostroutingChain),\n\t\t\"-j\", \"MARK\", \"--xor-mark\", proxier.masqueradeMark,\n\t)\n\tmasqRule := []string{\n\t\t\"-A\", string(kubePostroutingChain),\n\t\t\"-m\", \"comment\", \"--comment\", `\"kubernetes service traffic requiring SNAT\"`,\n\t\t\"-j\", \"MASQUERADE\",\n\t}\n\tif proxier.iptables.HasRandomFully() {\n\t\tmasqRule = append(masqRule, \"--random-fully\")\n\t}\n\tproxier.natRules.Write(masqRule)\n\n\t// Install the kubernetes-specific masquerade mark rule. We use a whole chain for\n\t// this so that it is easier to flush and change, for example if the mark\n\t// value should ever change.\n\tproxier.natRules.Write(\n\t\t\"-A\", string(kubeMarkMasqChain),\n\t\t\"-j\", \"MARK\", \"--or-mark\", proxier.masqueradeMark,\n\t)\n\n\tisIPv6 := proxier.iptables.IsIPv6()\n\tif !isIPv6 \u0026\u0026 proxier.localhostNodePorts {\n\t\t// Kube-proxy's use of `route_localnet` to enable NodePorts on localhost\n\t\t// creates a security hole (https://issue.k8s.io/90259) which this\n\t\t// iptables rule mitigates.\n\t\t// NB: THIS MUST MATCH the corresponding code in the kubelet. (Actually,\n\t\t// kubelet uses \"--dst\"/\"--src\" rather than \"-d\"/\"-s\" but that's just a\n\t\t// command-line thing and results in the same rule being created.)\n\t\tproxier.filterChains.Write(utiliptables.MakeChainLine(kubeletFirewallChain))\n\t\tproxier.filterRules.Write(\n\t\t\t\"-A\", string(kubeletFirewallChain),\n\t\t\t\"-m\", \"comment\", \"--comment\", `\"block incoming localnet connections\"`,\n\t\t\t\"-d\", \"127.0.0.0/8\",\n\t\t\t\"!\", \"-s\", \"127.0.0.0/8\",\n\t\t\t\"-m\", \"conntrack\",\n\t\t\t\"!\", \"--ctstate\", \"RELATED,ESTABLISHED,DNAT\",\n\t\t\t\"-j\", \"DROP\",\n\t\t)\n\t}\n\n\t// Accumulate NAT chains to keep.\n\tactiveNATChains := map[utiliptables.Chain]bool{} // use a map as a set\n\n\t// To avoid growing this slice, we arbitrarily set its size to 64,\n\t// there is never more than that many arguments for a single line.\n\t// Note that even if we go over 64, it will still be correct - it\n\t// is just for efficiency, not correctness.\n\targs := make([]string, 64)\n\n\t// Compute total number of endpoint chains across all services\n\t// to get a sense of how big the cluster is.\n\ttotalEndpoints := 0\n\tfor svcName := range proxier.svcPortMap {\n\t\ttotalEndpoints += len(proxier.endpointsMap[svcName])\n\t}\n\tproxier.largeClusterMode = (totalEndpoints \u003e largeClusterEndpointsThreshold)\n\n\t// These two variables are used to publish the sync_proxy_rules_no_endpoints_total\n\t// metric.\n\tserviceNoLocalEndpointsTotalInternal := 0\n\tserviceNoLocalEndpointsTotalExternal := 0\n\n\t// Build rules for each service-port.\n\tfor svcName, svc := range proxier.svcPortMap {\n\t\tsvcInfo, ok := svc.(*servicePortInfo)\n\t\tif !ok {\n\t\t\tklog.ErrorS(nil, \"Failed to cast serviceInfo\", \"serviceName\", svcName)\n\t\t\tcontinue\n\t\t}\n\t\tprotocol := strings.ToLower(string(svcInfo.Protocol()))\n\t\tsvcPortNameString := svcInfo.nameString\n\n\t\t// Figure out the endpoints for Cluster and Local traffic policy.\n\t\t// allLocallyReachableEndpoints is the set of all endpoints that can be routed to\n\t\t// from this node, given the service's traffic policies. hasEndpoints is true\n\t\t// if the service has any usable endpoints on any node, not just this one.\n\t\tallEndpoints := proxier.endpointsMap[svcName]\n\t\tclusterEndpoints, localEndpoints, allLocallyReachableEndpoints, hasEndpoints := proxy.CategorizeEndpoints(allEndpoints, svcInfo, proxier.nodeLabels)\n\n\t\t// Note the endpoint chains that will be used\n\t\tfor _, ep := range allLocallyReachableEndpoints {\n\t\t\tif epInfo, ok := ep.(*endpointsInfo); ok {\n\t\t\t\tactiveNATChains[epInfo.ChainName] = true\n\t\t\t}\n\t\t}\n\n\t\t// clusterPolicyChain contains the endpoints used with \"Cluster\" traffic policy\n\t\tclusterPolicyChain := svcInfo.clusterPolicyChainName\n\t\tusesClusterPolicyChain := len(clusterEndpoints) \u003e 0 \u0026\u0026 svcInfo.UsesClusterEndpoints()\n\t\tif usesClusterPolicyChain {\n\t\t\tactiveNATChains[clusterPolicyChain] = true\n\t\t}\n\n\t\t// localPolicyChain contains the endpoints used with \"Local\" traffic policy\n\t\tlocalPolicyChain := svcInfo.localPolicyChainName\n\t\tusesLocalPolicyChain := len(localEndpoints) \u003e 0 \u0026\u0026 svcInfo.UsesLocalEndpoints()\n\t\tif usesLocalPolicyChain {\n\t\t\tactiveNATChains[localPolicyChain] = true\n\t\t}\n\n\t\t// internalPolicyChain is the chain containing the endpoints for\n\t\t// \"internal\" (ClusterIP) traffic. internalTrafficChain is the chain that\n\t\t// internal traffic is routed to (which is always the same as\n\t\t// internalPolicyChain). hasInternalEndpoints is true if we should\n\t\t// generate rules pointing to internalTrafficChain, or false if there are\n\t\t// no available internal endpoints.\n\t\tinternalPolicyChain := clusterPolicyChain\n\t\thasInternalEndpoints := hasEndpoints\n\t\tif svcInfo.InternalPolicyLocal() {\n\t\t\tinternalPolicyChain = localPolicyChain\n\t\t\tif len(localEndpoints) == 0 {\n\t\t\t\thasInternalEndpoints = false\n\t\t\t}\n\t\t}\n\t\tinternalTrafficChain := internalPolicyChain\n\n\t\t// Similarly, externalPolicyChain is the chain containing the endpoints\n\t\t// for \"external\" (NodePort, LoadBalancer, and ExternalIP) traffic.\n\t\t// externalTrafficChain is the chain that external traffic is routed to\n\t\t// (which is always the service's \"EXT\" chain). hasExternalEndpoints is\n\t\t// true if there are endpoints that will be reached by external traffic.\n\t\t// (But we may still have to generate externalTrafficChain even if there\n\t\t// are no external endpoints, to ensure that the short-circuit rules for\n\t\t// local traffic are set up.)\n\t\texternalPolicyChain := clusterPolicyChain\n\t\thasExternalEndpoints := hasEndpoints\n\t\tif svcInfo.ExternalPolicyLocal() {\n\t\t\texternalPolicyChain = localPolicyChain\n\t\t\tif len(localEndpoints) == 0 {\n\t\t\t\thasExternalEndpoints = false\n\t\t\t}\n\t\t}\n\t\texternalTrafficChain := svcInfo.externalChainName // eventually jumps to externalPolicyChain\n\n\t\t// usesExternalTrafficChain is based on hasEndpoints, not hasExternalEndpoints,\n\t\t// because we need the local-traffic-short-circuiting rules even when there\n\t\t// are no externally-usable endpoints.\n\t\tusesExternalTrafficChain := hasEndpoints \u0026\u0026 svcInfo.ExternallyAccessible()\n\t\tif usesExternalTrafficChain {\n\t\t\tactiveNATChains[externalTrafficChain] = true\n\t\t}\n\n\t\t// Traffic to LoadBalancer IPs can go directly to externalTrafficChain\n\t\t// unless LoadBalancerSourceRanges is in use in which case we will\n\t\t// create a firewall chain.\n\t\tloadBalancerTrafficChain := externalTrafficChain\n\t\tfwChain := svcInfo.firewallChainName\n\t\tusesFWChain := hasEndpoints \u0026\u0026 len(svcInfo.LoadBalancerIPStrings()) \u003e 0 \u0026\u0026 len(svcInfo.LoadBalancerSourceRanges()) \u003e 0\n\t\tif usesFWChain {\n\t\t\tactiveNATChains[fwChain] = true\n\t\t\tloadBalancerTrafficChain = fwChain\n\t\t}\n\n\t\tvar internalTrafficFilterTarget, internalTrafficFilterComment string\n\t\tvar externalTrafficFilterTarget, externalTrafficFilterComment string\n\t\tif !hasEndpoints {\n\t\t\t// The service has no endpoints at all; hasInternalEndpoints and\n\t\t\t// hasExternalEndpoints will also be false, and we will not\n\t\t\t// generate any chains in the \"nat\" table for the service; only\n\t\t\t// rules in the \"filter\" table rejecting incoming packets for\n\t\t\t// the service's IPs.\n\t\t\tinternalTrafficFilterTarget = \"REJECT\"\n\t\t\tinternalTrafficFilterComment = fmt.Sprintf(`\"%s has no endpoints\"`, svcPortNameString)\n\t\t\texternalTrafficFilterTarget = \"REJECT\"\n\t\t\texternalTrafficFilterComment = internalTrafficFilterComment\n\t\t} else {\n\t\t\tif !hasInternalEndpoints {\n\t\t\t\t// The internalTrafficPolicy is \"Local\" but there are no local\n\t\t\t\t// endpoints. Traffic to the clusterIP will be dropped, but\n\t\t\t\t// external traffic may still be accepted.\n\t\t\t\tinternalTrafficFilterTarget = \"DROP\"\n\t\t\t\tinternalTrafficFilterComment = fmt.Sprintf(`\"%s has no local endpoints\"`, svcPortNameString)\n\t\t\t\tserviceNoLocalEndpointsTotalInternal++\n\t\t\t}\n\t\t\tif !hasExternalEndpoints {\n\t\t\t\t// The externalTrafficPolicy is \"Local\" but there are no\n\t\t\t\t// local endpoints. Traffic to \"external\" IPs from outside\n\t\t\t\t// the cluster will be dropped, but traffic from inside\n\t\t\t\t// the cluster may still be accepted.\n\t\t\t\texternalTrafficFilterTarget = \"DROP\"\n\t\t\t\texternalTrafficFilterComment = fmt.Sprintf(`\"%s has no local endpoints\"`, svcPortNameString)\n\t\t\t\tserviceNoLocalEndpointsTotalExternal++\n\t\t\t}\n\t\t}\n\n\t\t// Capture the clusterIP.\n\t\tif hasInternalEndpoints {\n\t\t\tproxier.natRules.Write(\n\t\t\t\t\"-A\", string(kubeServicesChain),\n\t\t\t\t\"-m\", \"comment\", \"--comment\", fmt.Sprintf(`\"%s cluster IP\"`, svcPortNameString),\n\t\t\t\t\"-m\", protocol, \"-p\", protocol,\n\t\t\t\t\"-d\", svcInfo.ClusterIP().String(),\n\t\t\t\t\"--dport\", strconv.Itoa(svcInfo.Port()),\n\t\t\t\t\"-j\", string(internalTrafficChain))\n\t\t} else {\n\t\t\t// No endpoints.\n\t\t\tproxier.filterRules.Write(\n\t\t\t\t\"-A\", string(kubeServicesChain),\n\t\t\t\t\"-m\", \"comment\", \"--comment\", internalTrafficFilterComment,\n\t\t\t\t\"-m\", protocol, \"-p\", protocol,\n\t\t\t\t\"-d\", svcInfo.ClusterIP().String(),\n\t\t\t\t\"--dport\", strconv.Itoa(svcInfo.Port()),\n\t\t\t\t\"-j\", internalTrafficFilterTarget,\n\t\t\t)\n\t\t}\n\n\t\t// Capture externalIPs.\n\t\tfor _, externalIP := range svcInfo.ExternalIPStrings() {\n\t\t\tif hasEndpoints {\n\t\t\t\t// Send traffic bound for external IPs to the \"external\n\t\t\t\t// destinations\" chain.\n\t\t\t\tproxier.natRules.Write(\n\t\t\t\t\t\"-A\", string(kubeServicesChain),\n\t\t\t\t\t\"-m\", \"comment\", \"--comment\", fmt.Sprintf(`\"%s external IP\"`, svcPortNameString),\n\t\t\t\t\t\"-m\", protocol, \"-p\", protocol,\n\t\t\t\t\t\"-d\", externalIP,\n\t\t\t\t\t\"--dport\", strconv.Itoa(svcInfo.Port()),\n\t\t\t\t\t\"-j\", string(externalTrafficChain))\n\t\t\t}\n\t\t\tif !hasExternalEndpoints {\n\t\t\t\t// Either no endpoints at all (REJECT) or no endpoints for\n\t\t\t\t// external traffic (DROP anything that didn't get\n\t\t\t\t// short-circuited by the EXT chain.)\n\t\t\t\tproxier.filterRules.Write(\n\t\t\t\t\t\"-A\", string(kubeExternalServicesChain),\n\t\t\t\t\t\"-m\", \"comment\", \"--comment\", externalTrafficFilterComment,\n\t\t\t\t\t\"-m\", protocol, \"-p\", protocol,\n\t\t\t\t\t\"-d\", externalIP,\n\t\t\t\t\t\"--dport\", strconv.Itoa(svcInfo.Port()),\n\t\t\t\t\t\"-j\", externalTrafficFilterTarget,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\t// Capture load-balancer ingress.\n\t\tfor _, lbip := range svcInfo.LoadBalancerIPStrings() {\n\t\t\tif hasEndpoints {\n\t\t\t\tproxier.natRules.Write(\n\t\t\t\t\t\"-A\", string(kubeServicesChain),\n\t\t\t\t\t\"-m\", \"comment\", \"--comment\", fmt.Sprintf(`\"%s loadbalancer IP\"`, svcPortNameString),\n\t\t\t\t\t\"-m\", protocol, \"-p\", protocol,\n\t\t\t\t\t\"-d\", lbip,\n\t\t\t\t\t\"--dport\", strconv.Itoa(svcInfo.Port()),\n\t\t\t\t\t\"-j\", string(loadBalancerTrafficChain))\n\n\t\t\t}\n\t\t\tif usesFWChain {\n\t\t\t\tproxier.filterRules.Write(\n\t\t\t\t\t\"-A\", string(kubeProxyFirewallChain),\n\t\t\t\t\t\"-m\", \"comment\", \"--comment\", fmt.Sprintf(`\"%s traffic not accepted by %s\"`, svcPortNameString, svcInfo.firewallChainName),\n\t\t\t\t\t\"-m\", protocol, \"-p\", protocol,\n\t\t\t\t\t\"-d\", lbip,\n\t\t\t\t\t\"--dport\", strconv.Itoa(svcInfo.Port()),\n\t\t\t\t\t\"-j\", \"DROP\")\n\t\t\t}\n\t\t}\n\t\tif !hasExternalEndpoints {\n\t\t\t// Either no endpoints at all (REJECT) or no endpoints for\n\t\t\t// external traffic (DROP anything that didn't get short-circuited\n\t\t\t// by the EXT chain.)\n\t\t\tfor _, lbip := range svcInfo.LoadBalancerIPStrings() {\n\t\t\t\tproxier.filterRules.Write(\n\t\t\t\t\t\"-A\", string(kubeExternalServicesChain),\n\t\t\t\t\t\"-m\", \"comment\", \"--comment\", externalTrafficFilterComment,\n\t\t\t\t\t\"-m\", protocol, \"-p\", protocol,\n\t\t\t\t\t\"-d\", lbip,\n\t\t\t\t\t\"--dport\", strconv.Itoa(svcInfo.Port()),\n\t\t\t\t\t\"-j\", externalTrafficFilterTarget,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\t// Capture nodeports.\n\t\tif svcInfo.NodePort() != 0 {\n\t\t\tif hasEndpoints {\n\t\t\t\t// Jump to the external destination chain. For better or for\n\t\t\t\t// worse, nodeports are not subect to loadBalancerSourceRanges,\n\t\t\t\t// and we can't change that.\n\t\t\t\tproxier.natRules.Write(\n\t\t\t\t\t\"-A\", string(kubeNodePortsChain),\n\t\t\t\t\t\"-m\", \"comment\", \"--comment\", svcPortNameString,\n\t\t\t\t\t\"-m\", protocol, \"-p\", protocol,\n\t\t\t\t\t\"--dport\", strconv.Itoa(svcInfo.NodePort()),\n\t\t\t\t\t\"-j\", string(externalTrafficChain))\n\t\t\t}\n\t\t\tif !hasExternalEndpoints {\n\t\t\t\t// Either no endpoints at all (REJECT) or no endpoints for\n\t\t\t\t// external traffic (DROP anything that didn't get\n\t\t\t\t// short-circuited by the EXT chain.)\n\t\t\t\tproxier.filterRules.Write(\n\t\t\t\t\t\"-A\", string(kubeExternalServicesChain),\n\t\t\t\t\t\"-m\", \"comment\", \"--comment\", externalTrafficFilterComment,\n\t\t\t\t\t\"-m\", \"addrtype\", \"--dst-type\", \"LOCAL\",\n\t\t\t\t\t\"-m\", protocol, \"-p\", protocol,\n\t\t\t\t\t\"--dport\", strconv.Itoa(svcInfo.NodePort()),\n\t\t\t\t\t\"-j\", externalTrafficFilterTarget,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\t// Capture healthCheckNodePorts.\n\t\tif svcInfo.HealthCheckNodePort() != 0 {\n\t\t\t// no matter if node has local endpoints, healthCheckNodePorts\n\t\t\t// need to add a rule to accept the incoming connection\n\t\t\tproxier.filterRules.Write(\n\t\t\t\t\"-A\", string(kubeNodePortsChain),\n\t\t\t\t\"-m\", \"comment\", \"--comment\", fmt.Sprintf(`\"%s health check node port\"`, svcPortNameString),\n\t\t\t\t\"-m\", \"tcp\", \"-p\", \"tcp\",\n\t\t\t\t\"--dport\", strconv.Itoa(svcInfo.HealthCheckNodePort()),\n\t\t\t\t\"-j\", \"ACCEPT\",\n\t\t\t)\n\t\t}\n\n\t\t// If the SVC/SVL/EXT/FW/SEP chains have not changed since the last sync\n\t\t// then we can omit them from the restore input. (We have already marked\n\t\t// them in activeNATChains, so they won't get deleted.)\n\t\tif tryPartialSync \u0026\u0026 !serviceChanged.Has(svcName.NamespacedName.String()) \u0026\u0026 !endpointsChanged.Has(svcName.NamespacedName.String()) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Set up internal traffic handling.\n\t\tif hasInternalEndpoints {\n\t\t\targs = append(args[:0],\n\t\t\t\t\"-m\", \"comment\", \"--comment\", fmt.Sprintf(`\"%s cluster IP\"`, svcPortNameString),\n\t\t\t\t\"-m\", protocol, \"-p\", protocol,\n\t\t\t\t\"-d\", svcInfo.ClusterIP().String(),\n\t\t\t\t\"--dport\", strconv.Itoa(svcInfo.Port()),\n\t\t\t)\n\t\t\tif proxier.masqueradeAll {\n\t\t\t\tproxier.natRules.Write(\n\t\t\t\t\t\"-A\", string(internalTrafficChain),\n\t\t\t\t\targs,\n\t\t\t\t\t\"-j\", string(kubeMarkMasqChain))\n\t\t\t} else if proxier.localDetector.IsImplemented() {\n\t\t\t\t// This masquerades off-cluster traffic to a service VIP. The\n\t\t\t\t// idea is that you can establish a static route for your\n\t\t\t\t// Service range, routing to any node, and that node will\n\t\t\t\t// bridge into the Service for you. Since that might bounce\n\t\t\t\t// off-node, we masquerade here.\n\t\t\t\tproxier.natRules.Write(\n\t\t\t\t\t\"-A\", string(internalTrafficChain),\n\t\t\t\t\targs,\n\t\t\t\t\tproxier.localDetector.IfNotLocal(),\n\t\t\t\t\t\"-j\", string(kubeMarkMasqChain))\n\t\t\t}\n\t\t}\n\n\t\t// Set up external traffic handling (if any \"external\" destinations are\n\t\t// enabled). All captured traffic for all external destinations should\n\t\t// jump to externalTrafficChain, which will handle some special cases and\n\t\t// then jump to externalPolicyChain.\n\t\tif usesExternalTrafficChain {\n\t\t\tproxier.natChains.Write(utiliptables.MakeChainLine(externalTrafficChain))\n\n\t\t\tif !svcInfo.ExternalPolicyLocal() {\n\t\t\t\t// If we are using non-local endpoints we need to masquerade,\n\t\t\t\t// in case we cross nodes.\n\t\t\t\tproxier.natRules.Write(\n\t\t\t\t\t\"-A\", string(externalTrafficChain),\n\t\t\t\t\t\"-m\", \"comment\", \"--comment\", fmt.Sprintf(`\"masquerade traffic for %s external destinations\"`, svcPortNameString),\n\t\t\t\t\t\"-j\", string(kubeMarkMasqChain))\n\t\t\t} else {\n\t\t\t\t// If we are only using same-node endpoints, we can retain the\n\t\t\t\t// source IP in most cases.\n\n\t\t\t\tif proxier.localDetector.IsImplemented() {\n\t\t\t\t\t// Treat all locally-originated pod -\u003e external destination\n\t\t\t\t\t// traffic as a special-case. It is subject to neither\n\t\t\t\t\t// form of traffic policy, which simulates going up-and-out\n\t\t\t\t\t// to an external load-balancer and coming back in.\n\t\t\t\t\tproxier.natRules.Write(\n\t\t\t\t\t\t\"-A\", string(externalTrafficChain),\n\t\t\t\t\t\t\"-m\", \"comment\", \"--comment\", fmt.Sprintf(`\"pod traffic for %s external destinations\"`, svcPortNameString),\n\t\t\t\t\t\tproxier.localDetector.IfLocal(),\n\t\t\t\t\t\t\"-j\", string(clusterPolicyChain))\n\t\t\t\t}\n\n\t\t\t\t// Locally originated traffic (not a pod, but the host node)\n\t\t\t\t// still needs masquerade because the LBIP itself is a local\n\t\t\t\t// address, so that will be the chosen source IP.\n\t\t\t\tproxier.natRules.Write(\n\t\t\t\t\t\"-A\", string(externalTrafficChain),\n\t\t\t\t\t\"-m\", \"comment\", \"--comment\", fmt.Sprintf(`\"masquerade LOCAL traffic for %s external destinations\"`, svcPortNameString),\n\t\t\t\t\t\"-m\", \"addrtype\", \"--src-type\", \"LOCAL\",\n\t\t\t\t\t\"-j\", string(kubeMarkMasqChain))\n\n\t\t\t\t// Redirect all src-type=LOCAL -\u003e external destination to the\n\t\t\t\t// policy=cluster chain. This allows traffic originating\n\t\t\t\t// from the host to be redirected to the service correctly.\n\t\t\t\tproxier.natRules.Write(\n\t\t\t\t\t\"-A\", string(externalTrafficChain),\n\t\t\t\t\t\"-m\", \"comment\", \"--comment\", fmt.Sprintf(`\"route LOCAL traffic for %s external destinations\"`, svcPortNameString),\n\t\t\t\t\t\"-m\", \"addrtype\", \"--src-type\", \"LOCAL\",\n\t\t\t\t\t\"-j\", string(clusterPolicyChain))\n\t\t\t}\n\n\t\t\t// Anything else falls thru to the appropriate policy chain.\n\t\t\tif hasExternalEndpoints {\n\t\t\t\tproxier.natRules.Write(\n\t\t\t\t\t\"-A\", string(externalTrafficChain),\n\t\t\t\t\t\"-j\", string(externalPolicyChain))\n\t\t\t}\n\t\t}\n\n\t\t// Set up firewall chain, if needed\n\t\tif usesFWChain {\n\t\t\tproxier.natChains.Write(utiliptables.MakeChainLine(fwChain))\n\n\t\t\t// The service firewall rules are created based on the\n\t\t\t// loadBalancerSourceRanges field. This only works for VIP-like\n\t\t\t// loadbalancers that preserve source IPs. For loadbalancers which\n\t\t\t// direct traffic to service NodePort, the firewall rules will not\n\t\t\t// apply.\n\t\t\targs = append(args[:0],\n\t\t\t\t\"-A\", string(fwChain),\n\t\t\t\t\"-m\", \"comment\", \"--comment\", fmt.Sprintf(`\"%s loadbalancer IP\"`, svcPortNameString),\n\t\t\t)\n\n\t\t\t// firewall filter based on each source range\n\t\t\tallowFromNode := false\n\t\t\tfor _, src := range svcInfo.LoadBalancerSourceRanges() {\n\t\t\t\tproxier.natRules.Write(args, \"-s\", src, \"-j\", string(externalTrafficChain))\n\t\t\t\t_, cidr, err := netutils.ParseCIDRSloppy(src)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"Error parsing CIDR in LoadBalancerSourceRanges, dropping it\", \"cidr\", cidr)\n\t\t\t\t} else if cidr.Contains(proxier.nodeIP) {\n\t\t\t\t\tallowFromNode = true\n\t\t\t\t}\n\t\t\t}\n\t\t\t// For VIP-like LBs, the VIP is often added as a local\n\t\t\t// address (via an IP route rule). In that case, a request\n\t\t\t// from a node to the VIP will not hit the loadbalancer but\n\t\t\t// will loop back with the source IP set to the VIP. We\n\t\t\t// need the following rules to allow requests from this node.\n\t\t\tif allowFromNode {\n\t\t\t\tfor _, lbip := range svcInfo.LoadBalancerIPStrings() {\n\t\t\t\t\tproxier.natRules.Write(\n\t\t\t\t\t\targs,\n\t\t\t\t\t\t\"-s\", lbip,\n\t\t\t\t\t\t\"-j\", string(externalTrafficChain))\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If the packet was able to reach the end of firewall chain,\n\t\t\t// then it did not get DNATed, so it will match the\n\t\t\t// corresponding KUBE-PROXY-FIREWALL rule.\n\t\t\tproxier.natRules.Write(\n\t\t\t\t\"-A\", string(fwChain),\n\t\t\t\t\"-m\", \"comment\", \"--comment\", fmt.Sprintf(`\"other traffic to %s will be dropped by KUBE-PROXY-FIREWALL\"`, svcPortNameString),\n\t\t\t)\n\t\t}\n\n\t\t// If Cluster policy is in use, create the chain and create rules jumping\n\t\t// from clusterPolicyChain to the clusterEndpoints\n\t\tif usesClusterPolicyChain {\n\t\t\tproxier.natChains.Write(utiliptables.MakeChainLine(clusterPolicyChain))\n\t\t\tproxier.writeServiceToEndpointRules(svcPortNameString, svcInfo, clusterPolicyChain, clusterEndpoints, args)\n\t\t}\n\n\t\t// If Local policy is in use, create the chain and create rules jumping\n\t\t// from localPolicyChain to the localEndpoints\n\t\tif usesLocalPolicyChain {\n\t\t\tproxier.natChains.Write(utiliptables.MakeChainLine(localPolicyChain))\n\t\t\tproxier.writeServiceToEndpointRules(svcPortNameString, svcInfo, localPolicyChain, localEndpoints, args)\n\t\t}\n\n\t\t// Generate the per-endpoint chains.\n\t\tfor _, ep := range allLocallyReachableEndpoints {\n\t\t\tepInfo, ok := ep.(*endpointsInfo)\n\t\t\tif !ok {\n\t\t\t\tklog.ErrorS(nil, \"Failed to cast endpointsInfo\", \"endpointsInfo\", ep)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tendpointChain := epInfo.ChainName\n\n\t\t\t// Create the endpoint chain\n\t\t\tproxier.natChains.Write(utiliptables.MakeChainLine(endpointChain))\n\t\t\tactiveNATChains[endpointChain] = true\n\n\t\t\targs = append(args[:0], \"-A\", string(endpointChain))\n\t\t\targs = proxier.appendServiceCommentLocked(args, svcPortNameString)\n\t\t\t// Handle traffic that loops back to the originator with SNAT.\n\t\t\tproxier.natRules.Write(\n\t\t\t\targs,\n\t\t\t\t\"-s\", epInfo.IP(),\n\t\t\t\t\"-j\", string(kubeMarkMasqChain))\n\t\t\t// Update client-affinity lists.\n\t\t\tif svcInfo.SessionAffinityType() == v1.ServiceAffinityClientIP {\n\t\t\t\targs = append(args, \"-m\", \"recent\", \"--name\", string(endpointChain), \"--set\")\n\t\t\t}\n\t\t\t// DNAT to final destination.\n\t\t\targs = append(args, \"-m\", protocol, \"-p\", protocol, \"-j\", \"DNAT\", \"--to-destination\", epInfo.Endpoint)\n\t\t\tproxier.natRules.Write(args)\n\t\t}\n\t}\n\n\t// Delete chains no longer in use. Since \"iptables-save\" can take several seconds\n\t// to run on hosts with lots of iptables rules, we don't bother to do this on\n\t// every sync in large clusters. (Stale chains will not be referenced by any\n\t// active rules, so they're harmless other than taking up memory.)\n\tif !proxier.largeClusterMode || time.Since(proxier.lastIPTablesCleanup) \u003e proxier.syncPeriod {\n\t\tvar existingNATChains map[utiliptables.Chain]struct{}\n\n\t\tproxier.iptablesData.Reset()\n\t\tif err := proxier.iptables.SaveInto(utiliptables.TableNAT, proxier.iptablesData); err == nil {\n\t\t\texistingNATChains = utiliptables.GetChainsFromTable(proxier.iptablesData.Bytes())\n\n\t\t\tfor chain := range existingNATChains {\n\t\t\t\tif !activeNATChains[chain] {\n\t\t\t\t\tchainString := string(chain)\n\t\t\t\t\tif !isServiceChainName(chainString) {\n\t\t\t\t\t\t// Ignore chains that aren't ours.\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\t// We must (as per iptables) write a chain-line\n\t\t\t\t\t// for it, which has the nice effect of flushing\n\t\t\t\t\t// the chain. Then we can remove the chain.\n\t\t\t\t\tproxier.natChains.Write(utiliptables.MakeChainLine(chain))\n\t\t\t\t\tproxier.natRules.Write(\"-X\", chainString)\n\t\t\t\t}\n\t\t\t}\n\t\t\tproxier.lastIPTablesCleanup = time.Now()\n\t\t} else {\n\t\t\tklog.ErrorS(err, \"Failed to execute iptables-save: stale chains will not be deleted\")\n\t\t}\n\t}\n\n\t// Finally, tail-call to the nodePorts chain. This needs to be after all\n\t// other service portal rules.\n\tnodeAddresses, err := proxier.nodePortAddresses.GetNodeAddresses(proxier.networkInterfacer)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to get node ip address matching nodeport cidrs, services with nodeport may not work as intended\", \"CIDRs\", proxier.nodePortAddresses)\n\t}\n\t// nodeAddresses may contain dual-stack zero-CIDRs if proxier.nodePortAddresses is empty.\n\t// Ensure nodeAddresses only contains the addresses for this proxier's IP family.\n\tfor addr := range nodeAddresses {\n\t\tif utilproxy.IsZeroCIDR(addr) \u0026\u0026 isIPv6 == netutils.IsIPv6CIDRString(addr) {\n\t\t\t// if any of the addresses is zero cidr of this IP family, non-zero IPs can be excluded.\n\t\t\tnodeAddresses = sets.NewString(addr)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfor address := range nodeAddresses {\n\t\tif utilproxy.IsZeroCIDR(address) {\n\t\t\tdestinations := []string{\"-m\", \"addrtype\", \"--dst-type\", \"LOCAL\"}\n\t\t\tif isIPv6 {\n\t\t\t\t// For IPv6, Regardless of the value of localhostNodePorts is true\n\t\t\t\t// or false, we should disable access to the nodePort via localhost. Since it never works and always\n\t\t\t\t// cause kernel warnings.\n\t\t\t\tdestinations = append(destinations, \"!\", \"-d\", \"::1/128\")\n\t\t\t}\n\n\t\t\tif !proxier.localhostNodePorts \u0026\u0026 !isIPv6 {\n\t\t\t\t// If set localhostNodePorts to \"false\"(route_localnet=0), We should generate iptables rules that\n\t\t\t\t// disable NodePort services to be accessed via localhost. Since it doesn't work and causes\n\t\t\t\t// the kernel to log warnings if anyone tries.\n\t\t\t\tdestinations = append(destinations, \"!\", \"-d\", \"127.0.0.0/8\")\n\t\t\t}\n\n\t\t\tproxier.natRules.Write(\n\t\t\t\t\"-A\", string(kubeServicesChain),\n\t\t\t\t\"-m\", \"comment\", \"--comment\", `\"kubernetes service nodeports; NOTE: this must be the last rule in this chain\"`,\n\t\t\t\tdestinations,\n\t\t\t\t\"-j\", string(kubeNodePortsChain))\n\t\t\tbreak\n\t\t}\n\n\t\t// Ignore IP addresses with incorrect version\n\t\tif isIPv6 \u0026\u0026 !netutils.IsIPv6String(address) || !isIPv6 \u0026\u0026 netutils.IsIPv6String(address) {\n\t\t\tklog.ErrorS(nil, \"IP has incorrect IP version\", \"IP\", address)\n\t\t\tcontinue\n\t\t}\n\n\t\t// For ipv6, Regardless of the value of localhostNodePorts is true or false, we should disallow access\n\t\t// to the nodePort via lookBack address.\n\t\tif isIPv6 \u0026\u0026 utilproxy.IsLoopBack(address) {\n\t\t\tklog.ErrorS(nil, \"disallow nodePort services to be accessed via ipv6 localhost address\", \"IP\", address)\n\t\t\tcontinue\n\t\t}\n\n\t\t// For ipv4, When localhostNodePorts is set to false, Ignore ipv4 lookBack address\n\t\tif !isIPv6 \u0026\u0026 utilproxy.IsLoopBack(address) \u0026\u0026 !proxier.localhostNodePorts {\n\t\t\tklog.ErrorS(nil, \"disallow nodePort services to be accessed via ipv4 localhost address\", \"IP\", address)\n\t\t\tcontinue\n\t\t}\n\n\t\t// create nodeport rules for each IP one by one\n\t\tproxier.natRules.Write(\n\t\t\t\"-A\", string(kubeServicesChain),\n\t\t\t\"-m\", \"comment\", \"--comment\", `\"kubernetes service nodeports; NOTE: this must be the last rule in this chain\"`,\n\t\t\t\"-d\", address,\n\t\t\t\"-j\", string(kubeNodePortsChain))\n\t}\n\n\t// Drop the packets in INVALID state, which would potentially cause\n\t// unexpected connection reset.\n\t// https://github.com/kubernetes/kubernetes/issues/74839\n\tproxier.filterRules.Write(\n\t\t\"-A\", string(kubeForwardChain),\n\t\t\"-m\", \"conntrack\",\n\t\t\"--ctstate\", \"INVALID\",\n\t\t\"-j\", \"DROP\",\n\t)\n\n\t// If the masqueradeMark has been added then we want to forward that same\n\t// traffic, this allows NodePort traffic to be forwarded even if the default\n\t// FORWARD policy is not accept.\n\tproxier.filterRules.Write(\n\t\t\"-A\", string(kubeForwardChain),\n\t\t\"-m\", \"comment\", \"--comment\", `\"kubernetes forwarding rules\"`,\n\t\t\"-m\", \"mark\", \"--mark\", fmt.Sprintf(\"%s/%s\", proxier.masqueradeMark, proxier.masqueradeMark),\n\t\t\"-j\", \"ACCEPT\",\n\t)\n\n\t// The following rule ensures the traffic after the initial packet accepted\n\t// by the \"kubernetes forwarding rules\" rule above will be accepted.\n\tproxier.filterRules.Write(\n\t\t\"-A\", string(kubeForwardChain),\n\t\t\"-m\", \"comment\", \"--comment\", `\"kubernetes forwarding conntrack rule\"`,\n\t\t\"-m\", \"conntrack\",\n\t\t\"--ctstate\", \"RELATED,ESTABLISHED\",\n\t\t\"-j\", \"ACCEPT\",\n\t)\n\n\tmetrics.IptablesRulesTotal.WithLabelValues(string(utiliptables.TableFilter)).Set(float64(proxier.filterRules.Lines()))\n\tmetrics.IptablesRulesTotal.WithLabelValues(string(utiliptables.TableNAT)).Set(float64(proxier.natRules.Lines()))\n\n\t// Sync rules.\n\tproxier.iptablesData.Reset()\n\tproxier.iptablesData.WriteString(\"*filter\\n\")\n\tproxier.iptablesData.Write(proxier.filterChains.Bytes())\n\tproxier.iptablesData.Write(proxier.filterRules.Bytes())\n\tproxier.iptablesData.WriteString(\"COMMIT\\n\")\n\tproxier.iptablesData.WriteString(\"*nat\\n\")\n\tproxier.iptablesData.Write(proxier.natChains.Bytes())\n\tproxier.iptablesData.Write(proxier.natRules.Bytes())\n\tproxier.iptablesData.WriteString(\"COMMIT\\n\")\n\n\tklog.V(2).InfoS(\"Reloading service iptables data\",\n\t\t\"numServices\", len(proxier.svcPortMap),\n\t\t\"numEndpoints\", totalEndpoints,\n\t\t\"numFilterChains\", proxier.filterChains.Lines(),\n\t\t\"numFilterRules\", proxier.filterRules.Lines(),\n\t\t\"numNATChains\", proxier.natChains.Lines(),\n\t\t\"numNATRules\", proxier.natRules.Lines(),\n\t)\n\tklog.V(9).InfoS(\"Restoring iptables\", \"rules\", proxier.iptablesData.Bytes())\n\n\t// NOTE: NoFlushTables is used so we don't flush non-kubernetes chains in the table\n\terr = proxier.iptables.RestoreAll(proxier.iptablesData.Bytes(), utiliptables.NoFlushTables, utiliptables.RestoreCounters)\n\tif err != nil {\n\t\tif pErr, ok := err.(utiliptables.ParseError); ok {\n\t\t\tlines := utiliptables.ExtractLines(proxier.iptablesData.Bytes(), pErr.Line(), 3)\n\t\t\tklog.ErrorS(pErr, \"Failed to execute iptables-restore\", \"rules\", lines)\n\t\t} else {\n\t\t\tklog.ErrorS(err, \"Failed to execute iptables-restore\")\n\t\t}\n\t\tmetrics.IptablesRestoreFailuresTotal.Inc()\n\t\treturn\n\t}\n\tsuccess = true\n\tproxier.needFullSync = false\n\n\tfor name, lastChangeTriggerTimes := range endpointUpdateResult.LastChangeTriggerTimes {\n\t\tfor _, lastChangeTriggerTime := range lastChangeTriggerTimes {\n\t\t\tlatency := metrics.SinceInSeconds(lastChangeTriggerTime)\n\t\t\tmetrics.NetworkProgrammingLatency.Observe(latency)\n\t\t\tklog.V(4).InfoS(\"Network programming\", \"endpoint\", klog.KRef(name.Namespace, name.Name), \"elapsed\", latency)\n\t\t}\n\t}\n\n\tmetrics.SyncProxyRulesNoLocalEndpointsTotal.WithLabelValues(\"internal\").Set(float64(serviceNoLocalEndpointsTotalInternal))\n\tmetrics.SyncProxyRulesNoLocalEndpointsTotal.WithLabelValues(\"external\").Set(float64(serviceNoLocalEndpointsTotalExternal))\n\tif proxier.healthzServer != nil {\n\t\tproxier.healthzServer.Updated()\n\t}\n\tmetrics.SyncProxyRulesLastTimestamp.SetToCurrentTime()\n\n\t// Update service healthchecks. The endpoints list might include services that are\n\t// not \"OnlyLocal\", but the services list will not, and the serviceHealthServer\n\t// will just drop those endpoints.\n\tif err := proxier.serviceHealthServer.SyncServices(proxier.svcPortMap.HealthCheckNodePorts()); err != nil {\n\t\tklog.ErrorS(err, \"Error syncing healthcheck services\")\n\t}\n\tif err := proxier.serviceHealthServer.SyncEndpoints(proxier.endpointsMap.LocalReadyEndpoints()); err != nil {\n\t\tklog.ErrorS(err, \"Error syncing healthcheck endpoints\")\n\t}\n\n\t// Finish housekeeping.\n\t// Clear stale conntrack entries for UDP Services, this has to be done AFTER the iptables rules are programmed.\n\t// TODO: these could be made more consistent.\n\tklog.V(4).InfoS(\"Deleting conntrack stale entries for services\", \"IPs\", conntrackCleanupServiceIPs.UnsortedList())\n\tfor _, svcIP := range conntrackCleanupServiceIPs.UnsortedList() {\n\t\tif err := conntrack.ClearEntriesForIP(proxier.exec, svcIP, v1.ProtocolUDP); err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to delete stale service connections\", \"IP\", svcIP)\n\t\t}\n\t}\n\tklog.V(4).InfoS(\"Deleting conntrack stale entries for services\", \"nodePorts\", conntrackCleanupServiceNodePorts.UnsortedList())\n\tfor _, nodePort := range conntrackCleanupServiceNodePorts.UnsortedList() {\n\t\terr := conntrack.ClearEntriesForPort(proxier.exec, nodePort, isIPv6, v1.ProtocolUDP)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to clear udp conntrack\", \"nodePort\", nodePort)\n\t\t}\n\t}\n\tklog.V(4).InfoS(\"Deleting stale endpoint connections\", \"endpoints\", endpointUpdateResult.DeletedUDPEndpoints)\n\tproxier.deleteUDPEndpointConnections(endpointUpdateResult.DeletedUDPEndpoints)\n}","line":{"from":805,"to":1641}} {"id":100008483,"name":"writeServiceToEndpointRules","signature":"func (proxier *Proxier) writeServiceToEndpointRules(svcPortNameString string, svcInfo proxy.ServicePort, svcChain utiliptables.Chain, endpoints []proxy.Endpoint, args []string)","file":"pkg/proxy/iptables/proxier.go","code":"func (proxier *Proxier) writeServiceToEndpointRules(svcPortNameString string, svcInfo proxy.ServicePort, svcChain utiliptables.Chain, endpoints []proxy.Endpoint, args []string) {\n\t// First write session affinity rules, if applicable.\n\tif svcInfo.SessionAffinityType() == v1.ServiceAffinityClientIP {\n\t\tfor _, ep := range endpoints {\n\t\t\tepInfo, ok := ep.(*endpointsInfo)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcomment := fmt.Sprintf(`\"%s -\u003e %s\"`, svcPortNameString, epInfo.Endpoint)\n\n\t\t\targs = append(args[:0],\n\t\t\t\t\"-A\", string(svcChain),\n\t\t\t)\n\t\t\targs = proxier.appendServiceCommentLocked(args, comment)\n\t\t\targs = append(args,\n\t\t\t\t\"-m\", \"recent\", \"--name\", string(epInfo.ChainName),\n\t\t\t\t\"--rcheck\", \"--seconds\", strconv.Itoa(svcInfo.StickyMaxAgeSeconds()), \"--reap\",\n\t\t\t\t\"-j\", string(epInfo.ChainName),\n\t\t\t)\n\t\t\tproxier.natRules.Write(args)\n\t\t}\n\t}\n\n\t// Now write loadbalancing rules.\n\tnumEndpoints := len(endpoints)\n\tfor i, ep := range endpoints {\n\t\tepInfo, ok := ep.(*endpointsInfo)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tcomment := fmt.Sprintf(`\"%s -\u003e %s\"`, svcPortNameString, epInfo.Endpoint)\n\n\t\targs = append(args[:0], \"-A\", string(svcChain))\n\t\targs = proxier.appendServiceCommentLocked(args, comment)\n\t\tif i \u003c (numEndpoints - 1) {\n\t\t\t// Each rule is a probabilistic match.\n\t\t\targs = append(args,\n\t\t\t\t\"-m\", \"statistic\",\n\t\t\t\t\"--mode\", \"random\",\n\t\t\t\t\"--probability\", proxier.probability(numEndpoints-i))\n\t\t}\n\t\t// The final (or only if n == 1) rule is a guaranteed match.\n\t\tproxier.natRules.Write(args, \"-j\", string(epInfo.ChainName))\n\t}\n}","line":{"from":1643,"to":1687}} {"id":100008484,"name":"String","signature":"func (g *listItem) String() string","file":"pkg/proxy/ipvs/graceful_termination.go","code":"// String return the unique real server name(with virtual server information)\nfunc (g *listItem) String() string {\n\treturn GetUniqueRSName(g.VirtualServer, g.RealServer)\n}","line":{"from":40,"to":43}} {"id":100008485,"name":"GetUniqueRSName","signature":"func GetUniqueRSName(vs *utilipvs.VirtualServer, rs *utilipvs.RealServer) string","file":"pkg/proxy/ipvs/graceful_termination.go","code":"// GetUniqueRSName return a string type unique rs name with vs information\nfunc GetUniqueRSName(vs *utilipvs.VirtualServer, rs *utilipvs.RealServer) string {\n\treturn vs.String() + \"/\" + rs.String()\n}","line":{"from":45,"to":48}} {"id":100008486,"name":"add","signature":"func (q *graceTerminateRSList) add(rs *listItem) bool","file":"pkg/proxy/ipvs/graceful_termination.go","code":"// add push an new element to the rsList\nfunc (q *graceTerminateRSList) add(rs *listItem) bool {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\tuniqueRS := rs.String()\n\tif _, ok := q.list[uniqueRS]; ok {\n\t\treturn false\n\t}\n\n\tklog.V(5).InfoS(\"Adding real server to graceful delete real server list\", \"realServer\", rs)\n\tq.list[uniqueRS] = rs\n\treturn true\n}","line":{"from":55,"to":68}} {"id":100008487,"name":"remove","signature":"func (q *graceTerminateRSList) remove(rs *listItem) bool","file":"pkg/proxy/ipvs/graceful_termination.go","code":"// remove remove an element from the rsList\nfunc (q *graceTerminateRSList) remove(rs *listItem) bool {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\tuniqueRS := rs.String()\n\tif _, ok := q.list[uniqueRS]; ok {\n\t\tdelete(q.list, uniqueRS)\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":70,"to":81}} {"id":100008488,"name":"len","signature":"func (q *graceTerminateRSList) len() int","file":"pkg/proxy/ipvs/graceful_termination.go","code":"// return the size of the list\nfunc (q *graceTerminateRSList) len() int {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\treturn len(q.list)\n}","line":{"from":83,"to":89}} {"id":100008489,"name":"flushList","signature":"func (q *graceTerminateRSList) flushList(handler func(rsToDelete *listItem) (bool, error)) bool","file":"pkg/proxy/ipvs/graceful_termination.go","code":"func (q *graceTerminateRSList) flushList(handler func(rsToDelete *listItem) (bool, error)) bool {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\tsuccess := true\n\tfor name, rs := range q.list {\n\t\tdeleted, err := handler(rs)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Error in deleting real server\", \"realServer\", name)\n\t\t\tsuccess = false\n\t\t}\n\t\tif deleted {\n\t\t\tklog.InfoS(\"Removed real server from graceful delete real server list\", \"realServer\", name)\n\t\t\tdelete(q.list, rs.String())\n\t\t}\n\t}\n\treturn success\n}","line":{"from":91,"to":107}} {"id":100008490,"name":"exist","signature":"func (q *graceTerminateRSList) exist(uniqueRS string) (*listItem, bool)","file":"pkg/proxy/ipvs/graceful_termination.go","code":"// exist check whether the specified unique RS is in the rsList\nfunc (q *graceTerminateRSList) exist(uniqueRS string) (*listItem, bool) {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\tif rs, ok := q.list[uniqueRS]; ok {\n\t\treturn rs, true\n\t}\n\treturn nil, false\n}","line":{"from":109,"to":118}} {"id":100008491,"name":"NewGracefulTerminationManager","signature":"func NewGracefulTerminationManager(ipvs utilipvs.Interface) *GracefulTerminationManager","file":"pkg/proxy/ipvs/graceful_termination.go","code":"// NewGracefulTerminationManager create a gracefulTerminationManager to manage ipvs rs graceful termination work\nfunc NewGracefulTerminationManager(ipvs utilipvs.Interface) *GracefulTerminationManager {\n\tl := make(map[string]*listItem)\n\treturn \u0026GracefulTerminationManager{\n\t\trsList: graceTerminateRSList{\n\t\t\tlist: l,\n\t\t},\n\t\tipvs: ipvs,\n\t}\n}","line":{"from":127,"to":136}} {"id":100008492,"name":"InTerminationList","signature":"func (m *GracefulTerminationManager) InTerminationList(uniqueRS string) bool","file":"pkg/proxy/ipvs/graceful_termination.go","code":"// InTerminationList to check whether specified unique rs name is in graceful termination list\nfunc (m *GracefulTerminationManager) InTerminationList(uniqueRS string) bool {\n\t_, exist := m.rsList.exist(uniqueRS)\n\treturn exist\n}","line":{"from":138,"to":142}} {"id":100008493,"name":"GracefulDeleteRS","signature":"func (m *GracefulTerminationManager) GracefulDeleteRS(vs *utilipvs.VirtualServer, rs *utilipvs.RealServer) error","file":"pkg/proxy/ipvs/graceful_termination.go","code":"// GracefulDeleteRS to update rs weight to 0, and add rs to graceful terminate list\nfunc (m *GracefulTerminationManager) GracefulDeleteRS(vs *utilipvs.VirtualServer, rs *utilipvs.RealServer) error {\n\t// Try to delete rs before add it to graceful delete list\n\tele := \u0026listItem{\n\t\tVirtualServer: vs,\n\t\tRealServer: rs,\n\t}\n\tdeleted, err := m.deleteRsFunc(ele)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Error in deleting real server\", \"realServer\", ele)\n\t}\n\tif deleted {\n\t\treturn nil\n\t}\n\trs.Weight = 0\n\terr = m.ipvs.UpdateRealServer(vs, rs)\n\tif err != nil {\n\t\treturn err\n\t}\n\tklog.V(5).InfoS(\"Adding real server to graceful delete real server list\", \"realServer\", ele)\n\tm.rsList.add(ele)\n\treturn nil\n}","line":{"from":144,"to":166}} {"id":100008494,"name":"deleteRsFunc","signature":"func (m *GracefulTerminationManager) deleteRsFunc(rsToDelete *listItem) (bool, error)","file":"pkg/proxy/ipvs/graceful_termination.go","code":"func (m *GracefulTerminationManager) deleteRsFunc(rsToDelete *listItem) (bool, error) {\n\tklog.V(5).InfoS(\"Trying to delete real server\", \"realServer\", rsToDelete)\n\trss, err := m.ipvs.GetRealServers(rsToDelete.VirtualServer)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tfor _, rs := range rss {\n\t\tif rsToDelete.RealServer.Equal(rs) {\n\t\t\t// For UDP and SCTP traffic, no graceful termination, we immediately delete the RS\n\t\t\t// (existing connections will be deleted on the next packet because sysctlExpireNoDestConn=1)\n\t\t\t// For other protocols, don't delete until all connections have expired)\n\t\t\tif utilipvs.IsRsGracefulTerminationNeeded(rsToDelete.VirtualServer.Protocol) \u0026\u0026 rs.ActiveConn+rs.InactiveConn != 0 {\n\t\t\t\tklog.V(5).InfoS(\"Skip deleting real server till all connection have expired\", \"realServer\", rsToDelete, \"activeConnection\", rs.ActiveConn, \"inactiveConnection\", rs.InactiveConn)\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\tklog.V(5).InfoS(\"Deleting real server\", \"realServer\", rsToDelete)\n\t\t\terr := m.ipvs.DeleteRealServer(rsToDelete.VirtualServer, rs)\n\t\t\tif err != nil {\n\t\t\t\treturn false, fmt.Errorf(\"delete destination %q err: %w\", rs.String(), err)\n\t\t\t}\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn true, fmt.Errorf(\"failed to delete rs %q, can't find the real server\", rsToDelete.String())\n}","line":{"from":168,"to":192}} {"id":100008495,"name":"tryDeleteRs","signature":"func (m *GracefulTerminationManager) tryDeleteRs()","file":"pkg/proxy/ipvs/graceful_termination.go","code":"func (m *GracefulTerminationManager) tryDeleteRs() {\n\tif !m.rsList.flushList(m.deleteRsFunc) {\n\t\tklog.ErrorS(nil, \"Try flush graceful termination list error\")\n\t}\n}","line":{"from":194,"to":198}} {"id":100008496,"name":"MoveRSOutofGracefulDeleteList","signature":"func (m *GracefulTerminationManager) MoveRSOutofGracefulDeleteList(uniqueRS string) error","file":"pkg/proxy/ipvs/graceful_termination.go","code":"// MoveRSOutofGracefulDeleteList to delete an rs and remove it from the rsList immediately\nfunc (m *GracefulTerminationManager) MoveRSOutofGracefulDeleteList(uniqueRS string) error {\n\trsToDelete, find := m.rsList.exist(uniqueRS)\n\tif !find || rsToDelete == nil {\n\t\treturn fmt.Errorf(\"failed to find rs: %q\", uniqueRS)\n\t}\n\terr := m.ipvs.DeleteRealServer(rsToDelete.VirtualServer, rsToDelete.RealServer)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.rsList.remove(rsToDelete)\n\treturn nil\n}","line":{"from":200,"to":212}} {"id":100008497,"name":"Run","signature":"func (m *GracefulTerminationManager) Run()","file":"pkg/proxy/ipvs/graceful_termination.go","code":"// Run start a goroutine to try to delete rs in the graceful delete rsList with an interval 1 minute\nfunc (m *GracefulTerminationManager) Run() {\n\tgo wait.Until(m.tryDeleteRs, rsCheckDeleteInterval, wait.NeverStop)\n}","line":{"from":214,"to":217}} {"id":100008498,"name":"NewIPSet","signature":"func NewIPSet(handle utilipset.Interface, name string, setType utilipset.Type, isIPv6 bool, comment string) *IPSet","file":"pkg/proxy/ipvs/ipset.go","code":"// NewIPSet initialize a new IPSet struct\nfunc NewIPSet(handle utilipset.Interface, name string, setType utilipset.Type, isIPv6 bool, comment string) *IPSet {\n\thashFamily := utilipset.ProtocolFamilyIPV4\n\tif isIPv6 {\n\t\thashFamily = utilipset.ProtocolFamilyIPV6\n\t\t// In dual-stack both ipv4 and ipv6 ipset's can co-exist. To\n\t\t// ensure unique names the prefix for ipv6 is changed from\n\t\t// \"KUBE-\" to \"KUBE-6-\". The \"KUBE-\" prefix is kept for\n\t\t// backward compatibility. The maximum name length of an ipset\n\t\t// is 31 characters which must be taken into account. The\n\t\t// ipv4 names are not altered to minimize the risk for\n\t\t// problems on upgrades.\n\t\tif strings.HasPrefix(name, \"KUBE-\") {\n\t\t\tname = strings.Replace(name, \"KUBE-\", \"KUBE-6-\", 1)\n\t\t\tif len(name) \u003e 31 {\n\t\t\t\tklog.InfoS(\"Ipset name truncated\", \"ipSetName\", name, \"truncatedName\", name[:31])\n\t\t\t\tname = name[:31]\n\t\t\t}\n\t\t}\n\t}\n\tset := \u0026IPSet{\n\t\tIPSet: utilipset.IPSet{\n\t\t\tName: name,\n\t\t\tSetType: setType,\n\t\t\tHashFamily: hashFamily,\n\t\t\tComment: comment,\n\t\t},\n\t\tactiveEntries: sets.New[string](),\n\t\thandle: handle,\n\t}\n\treturn set\n}","line":{"from":101,"to":132}} {"id":100008499,"name":"validateEntry","signature":"func (set *IPSet) validateEntry(entry *utilipset.Entry) bool","file":"pkg/proxy/ipvs/ipset.go","code":"func (set *IPSet) validateEntry(entry *utilipset.Entry) bool {\n\treturn entry.Validate(\u0026set.IPSet)\n}","line":{"from":134,"to":136}} {"id":100008500,"name":"isEmpty","signature":"func (set *IPSet) isEmpty() bool","file":"pkg/proxy/ipvs/ipset.go","code":"func (set *IPSet) isEmpty() bool {\n\treturn set.activeEntries.Len() == 0\n}","line":{"from":138,"to":140}} {"id":100008501,"name":"getComment","signature":"func (set *IPSet) getComment() string","file":"pkg/proxy/ipvs/ipset.go","code":"func (set *IPSet) getComment() string {\n\treturn fmt.Sprintf(\"\\\"%s\\\"\", set.Comment)\n}","line":{"from":142,"to":144}} {"id":100008502,"name":"resetEntries","signature":"func (set *IPSet) resetEntries()","file":"pkg/proxy/ipvs/ipset.go","code":"func (set *IPSet) resetEntries() {\n\tset.activeEntries = sets.New[string]()\n}","line":{"from":146,"to":148}} {"id":100008503,"name":"syncIPSetEntries","signature":"func (set *IPSet) syncIPSetEntries()","file":"pkg/proxy/ipvs/ipset.go","code":"func (set *IPSet) syncIPSetEntries() {\n\tappliedEntries, err := set.handle.ListEntries(set.Name)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to list ip set entries\")\n\t\treturn\n\t}\n\n\t// currentIPSetEntries represents Endpoints watched from API Server.\n\tcurrentIPSetEntries := sets.New[string]()\n\tfor _, appliedEntry := range appliedEntries {\n\t\tcurrentIPSetEntries.Insert(appliedEntry)\n\t}\n\n\tif !set.activeEntries.Equal(currentIPSetEntries) {\n\t\t// Clean legacy entries\n\t\tfor _, entry := range currentIPSetEntries.Difference(set.activeEntries).UnsortedList() {\n\t\t\tif err := set.handle.DelEntry(entry, set.Name); err != nil {\n\t\t\t\tif !utilipset.IsNotFoundError(err) {\n\t\t\t\t\tklog.ErrorS(err, \"Failed to delete ip set entry from ip set\", \"ipSetEntry\", entry, \"ipSet\", set.Name)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tklog.V(3).InfoS(\"Successfully deleted legacy ip set entry from ip set\", \"ipSetEntry\", entry, \"ipSet\", set.Name)\n\t\t\t}\n\t\t}\n\t\t// Create active entries\n\t\tfor _, entry := range set.activeEntries.Difference(currentIPSetEntries).UnsortedList() {\n\t\t\tif err := set.handle.AddEntry(entry, \u0026set.IPSet, true); err != nil {\n\t\t\t\tklog.ErrorS(err, \"Failed to add ip set entry to ip set\", \"ipSetEntry\", entry, \"ipSet\", set.Name)\n\t\t\t} else {\n\t\t\t\tklog.V(3).InfoS(\"Successfully added ip set entry to ip set\", \"ipSetEntry\", entry, \"ipSet\", set.Name)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":150,"to":183}} {"id":100008504,"name":"ensureIPSet","signature":"func ensureIPSet(set *IPSet) error","file":"pkg/proxy/ipvs/ipset.go","code":"func ensureIPSet(set *IPSet) error {\n\tif err := set.handle.CreateSet(\u0026set.IPSet, true); err != nil {\n\t\tklog.ErrorS(err, \"Failed to make sure existence of ip set\", \"ipSet\", set)\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":185,"to":191}} {"id":100008505,"name":"checkMinVersion","signature":"func checkMinVersion(vstring string) bool","file":"pkg/proxy/ipvs/ipset.go","code":"// checkMinVersion checks if ipset current version satisfies required min version\nfunc checkMinVersion(vstring string) bool {\n\tversion, err := utilversion.ParseGeneric(vstring)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Got invalid version string\", \"versionString\", vstring)\n\t\treturn false\n\t}\n\n\tminVersion, err := utilversion.ParseGeneric(MinIPSetCheckVersion)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Got invalid version string\", \"versionString\", MinIPSetCheckVersion)\n\t\treturn false\n\t}\n\treturn !version.LessThan(minVersion)\n}","line":{"from":193,"to":207}} {"id":100008506,"name":"NewNetLinkHandle","signature":"func NewNetLinkHandle(isIPv6 bool) NetLinkHandle","file":"pkg/proxy/ipvs/netlink_linux.go","code":"// NewNetLinkHandle will create a new NetLinkHandle\nfunc NewNetLinkHandle(isIPv6 bool) NetLinkHandle {\n\treturn \u0026netlinkHandle{netlink.Handle{}, isIPv6}\n}","line":{"from":40,"to":43}} {"id":100008507,"name":"EnsureAddressBind","signature":"func (h *netlinkHandle) EnsureAddressBind(address, devName string) (exist bool, err error)","file":"pkg/proxy/ipvs/netlink_linux.go","code":"// EnsureAddressBind checks if address is bound to the interface and, if not, binds it. If the address is already bound, return true.\nfunc (h *netlinkHandle) EnsureAddressBind(address, devName string) (exist bool, err error) {\n\tdev, err := h.LinkByName(devName)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"error get interface: %s, err: %v\", devName, err)\n\t}\n\taddr := netutils.ParseIPSloppy(address)\n\tif addr == nil {\n\t\treturn false, fmt.Errorf(\"error parse ip address: %s\", address)\n\t}\n\tif err := h.AddrAdd(dev, \u0026netlink.Addr{IPNet: netlink.NewIPNet(addr)}); err != nil {\n\t\t// \"EEXIST\" will be returned if the address is already bound to device\n\t\tif err == unix.EEXIST {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, fmt.Errorf(\"error bind address: %s to interface: %s, err: %v\", address, devName, err)\n\t}\n\treturn false, nil\n}","line":{"from":45,"to":63}} {"id":100008508,"name":"UnbindAddress","signature":"func (h *netlinkHandle) UnbindAddress(address, devName string) error","file":"pkg/proxy/ipvs/netlink_linux.go","code":"// UnbindAddress makes sure IP address is unbound from the network interface.\nfunc (h *netlinkHandle) UnbindAddress(address, devName string) error {\n\tdev, err := h.LinkByName(devName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error get interface: %s, err: %v\", devName, err)\n\t}\n\taddr := netutils.ParseIPSloppy(address)\n\tif addr == nil {\n\t\treturn fmt.Errorf(\"error parse ip address: %s\", address)\n\t}\n\tif err := h.AddrDel(dev, \u0026netlink.Addr{IPNet: netlink.NewIPNet(addr)}); err != nil {\n\t\tif err != unix.ENXIO {\n\t\t\treturn fmt.Errorf(\"error unbind address: %s from interface: %s, err: %v\", address, devName, err)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":65,"to":81}} {"id":100008509,"name":"EnsureDummyDevice","signature":"func (h *netlinkHandle) EnsureDummyDevice(devName string) (bool, error)","file":"pkg/proxy/ipvs/netlink_linux.go","code":"// EnsureDummyDevice is part of interface\nfunc (h *netlinkHandle) EnsureDummyDevice(devName string) (bool, error) {\n\t_, err := h.LinkByName(devName)\n\tif err == nil {\n\t\t// found dummy device\n\t\treturn true, nil\n\t}\n\tdummy := \u0026netlink.Dummy{\n\t\tLinkAttrs: netlink.LinkAttrs{Name: devName},\n\t}\n\treturn false, h.LinkAdd(dummy)\n}","line":{"from":83,"to":94}} {"id":100008510,"name":"DeleteDummyDevice","signature":"func (h *netlinkHandle) DeleteDummyDevice(devName string) error","file":"pkg/proxy/ipvs/netlink_linux.go","code":"// DeleteDummyDevice is part of interface.\nfunc (h *netlinkHandle) DeleteDummyDevice(devName string) error {\n\tlink, err := h.LinkByName(devName)\n\tif err != nil {\n\t\t_, ok := err.(netlink.LinkNotFoundError)\n\t\tif ok {\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"error deleting a non-exist dummy device: %s, %v\", devName, err)\n\t}\n\tdummy, ok := link.(*netlink.Dummy)\n\tif !ok {\n\t\treturn fmt.Errorf(\"expect dummy device, got device type: %s\", link.Type())\n\t}\n\treturn h.LinkDel(dummy)\n}","line":{"from":96,"to":111}} {"id":100008511,"name":"ListBindAddress","signature":"func (h *netlinkHandle) ListBindAddress(devName string) ([]string, error)","file":"pkg/proxy/ipvs/netlink_linux.go","code":"// ListBindAddress will list all IP addresses which are bound in a given interface\nfunc (h *netlinkHandle) ListBindAddress(devName string) ([]string, error) {\n\tdev, err := h.LinkByName(devName)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error get interface: %s, err: %v\", devName, err)\n\t}\n\taddrs, err := h.AddrList(dev, 0)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error list bound address of interface: %s, err: %v\", devName, err)\n\t}\n\tvar ips []string\n\tfor _, addr := range addrs {\n\t\tips = append(ips, addr.IP.String())\n\t}\n\treturn ips, nil\n}","line":{"from":113,"to":128}} {"id":100008512,"name":"GetAllLocalAddresses","signature":"func (h *netlinkHandle) GetAllLocalAddresses() (sets.Set[string], error)","file":"pkg/proxy/ipvs/netlink_linux.go","code":"// GetAllLocalAddresses return all local addresses on the node.\n// Only the addresses of the current family are returned.\n// IPv6 link-local and loopback addresses are excluded.\nfunc (h *netlinkHandle) GetAllLocalAddresses() (sets.Set[string], error) {\n\taddr, err := net.InterfaceAddrs()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not get addresses: %v\", err)\n\t}\n\treturn utilproxy.AddressSet(h.isValidForSet, addr), nil\n}","line":{"from":130,"to":139}} {"id":100008513,"name":"GetLocalAddresses","signature":"func (h *netlinkHandle) GetLocalAddresses(dev string) (sets.Set[string], error)","file":"pkg/proxy/ipvs/netlink_linux.go","code":"// GetLocalAddresses return all local addresses for an interface.\n// Only the addresses of the current family are returned.\n// IPv6 link-local and loopback addresses are excluded.\nfunc (h *netlinkHandle) GetLocalAddresses(dev string) (sets.Set[string], error) {\n\tifi, err := net.InterfaceByName(dev)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not get interface %s: %v\", dev, err)\n\t}\n\taddr, err := ifi.Addrs()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Can't get addresses from %s: %v\", ifi.Name, err)\n\t}\n\treturn utilproxy.AddressSet(h.isValidForSet, addr), nil\n}","line":{"from":141,"to":154}} {"id":100008514,"name":"isValidForSet","signature":"func (h *netlinkHandle) isValidForSet(ip net.IP) bool","file":"pkg/proxy/ipvs/netlink_linux.go","code":"func (h *netlinkHandle) isValidForSet(ip net.IP) bool {\n\tif h.isIPv6 != netutils.IsIPv6(ip) {\n\t\treturn false\n\t}\n\tif h.isIPv6 \u0026\u0026 ip.IsLinkLocalUnicast() {\n\t\treturn false\n\t}\n\tif ip.IsLoopback() {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":156,"to":167}} {"id":100008515,"name":"GetAllLocalAddressesExcept","signature":"func (h *netlinkHandle) GetAllLocalAddressesExcept(dev string) (sets.Set[string], error)","file":"pkg/proxy/ipvs/netlink_linux.go","code":"// GetAllLocalAddressesExcept return all local addresses on the node,\n// except from the passed dev. This is not the same as to take the\n// diff between GetAllLocalAddresses and GetLocalAddresses since an\n// address can be assigned to many interfaces. This problem raised\n// https://github.com/kubernetes/kubernetes/issues/114815\nfunc (h *netlinkHandle) GetAllLocalAddressesExcept(dev string) (sets.Set[string], error) {\n\tifaces, err := net.Interfaces()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar addr []net.Addr\n\tfor _, iface := range ifaces {\n\t\tif iface.Name == dev {\n\t\t\tcontinue\n\t\t}\n\t\tifadr, err := iface.Addrs()\n\t\tif err != nil {\n\t\t\t// This may happen if the interface was deleted. Ignore\n\t\t\t// but log the error.\n\t\t\tklog.ErrorS(err, \"Reading addresses\", \"interface\", iface.Name)\n\t\t\tcontinue\n\t\t}\n\t\taddr = append(addr, ifadr...)\n\t}\n\treturn utilproxy.AddressSet(h.isValidForSet, addr), nil\n}","line":{"from":169,"to":194}} {"id":100008516,"name":"NewNetLinkHandle","signature":"func NewNetLinkHandle(ipv6 bool) NetLinkHandle","file":"pkg/proxy/ipvs/netlink_unsupported.go","code":"// NewNetLinkHandle will create an EmptyHandle\nfunc NewNetLinkHandle(ipv6 bool) NetLinkHandle {\n\treturn \u0026netlinkHandle{}\n}","line":{"from":34,"to":37}} {"id":100008517,"name":"EnsureAddressBind","signature":"func (h *netlinkHandle) EnsureAddressBind(address, devName string) (exist bool, err error)","file":"pkg/proxy/ipvs/netlink_unsupported.go","code":"// EnsureAddressBind checks if address is bound to the interface and, if not, binds it. If the address is already bound, return true.\nfunc (h *netlinkHandle) EnsureAddressBind(address, devName string) (exist bool, err error) {\n\treturn false, fmt.Errorf(\"netlink not supported for this platform\")\n}","line":{"from":39,"to":42}} {"id":100008518,"name":"UnbindAddress","signature":"func (h *netlinkHandle) UnbindAddress(address, devName string) error","file":"pkg/proxy/ipvs/netlink_unsupported.go","code":"// UnbindAddress unbind address from the interface\nfunc (h *netlinkHandle) UnbindAddress(address, devName string) error {\n\treturn fmt.Errorf(\"netlink not supported for this platform\")\n}","line":{"from":44,"to":47}} {"id":100008519,"name":"EnsureDummyDevice","signature":"func (h *netlinkHandle) EnsureDummyDevice(devName string) (bool, error)","file":"pkg/proxy/ipvs/netlink_unsupported.go","code":"// EnsureDummyDevice is part of interface\nfunc (h *netlinkHandle) EnsureDummyDevice(devName string) (bool, error) {\n\treturn false, fmt.Errorf(\"netlink is not supported in this platform\")\n}","line":{"from":49,"to":52}} {"id":100008520,"name":"DeleteDummyDevice","signature":"func (h *netlinkHandle) DeleteDummyDevice(devName string) error","file":"pkg/proxy/ipvs/netlink_unsupported.go","code":"// DeleteDummyDevice is part of interface.\nfunc (h *netlinkHandle) DeleteDummyDevice(devName string) error {\n\treturn fmt.Errorf(\"netlink is not supported in this platform\")\n}","line":{"from":54,"to":57}} {"id":100008521,"name":"ListBindAddress","signature":"func (h *netlinkHandle) ListBindAddress(devName string) ([]string, error)","file":"pkg/proxy/ipvs/netlink_unsupported.go","code":"// ListBindAddress is part of interface.\nfunc (h *netlinkHandle) ListBindAddress(devName string) ([]string, error) {\n\treturn nil, fmt.Errorf(\"netlink is not supported in this platform\")\n}","line":{"from":59,"to":62}} {"id":100008522,"name":"GetAllLocalAddresses","signature":"func (h *netlinkHandle) GetAllLocalAddresses() (sets.Set[string], error)","file":"pkg/proxy/ipvs/netlink_unsupported.go","code":"// GetAllLocalAddresses is part of interface.\nfunc (h *netlinkHandle) GetAllLocalAddresses() (sets.Set[string], error) {\n\treturn nil, fmt.Errorf(\"netlink is not supported in this platform\")\n}","line":{"from":64,"to":67}} {"id":100008523,"name":"GetLocalAddresses","signature":"func (h *netlinkHandle) GetLocalAddresses(dev string) (sets.Set[string], error)","file":"pkg/proxy/ipvs/netlink_unsupported.go","code":"// GetLocalAddresses is part of interface.\nfunc (h *netlinkHandle) GetLocalAddresses(dev string) (sets.Set[string], error) {\n\treturn nil, fmt.Errorf(\"netlink is not supported in this platform\")\n}","line":{"from":69,"to":72}} {"id":100008524,"name":"GetAllLocalAddressesExcept","signature":"func (h *netlinkHandle) GetAllLocalAddressesExcept(dev string) (sets.Set[string], error)","file":"pkg/proxy/ipvs/netlink_unsupported.go","code":"// GetAllLocalAddressesExcept is part of interface.\nfunc (h *netlinkHandle) GetAllLocalAddressesExcept(dev string) (sets.Set[string], error) {\n\treturn nil, fmt.Errorf(\"netlink is not supported in this platform\")\n}","line":{"from":74,"to":77}} {"id":100008525,"name":"isValidForSet","signature":"func (h *netlinkHandle) isValidForSet(ip net.IP) bool","file":"pkg/proxy/ipvs/netlink_unsupported.go","code":"// Must match the one in proxier_test.go\nfunc (h *netlinkHandle) isValidForSet(ip net.IP) bool {\n\treturn false\n}","line":{"from":79,"to":82}} {"id":100008526,"name":"NewProxier","signature":"func NewProxier(ipFamily v1.IPFamily,","file":"pkg/proxy/ipvs/proxier.go","code":"// NewProxier returns a new Proxier given an iptables and ipvs Interface instance.\n// Because of the iptables and ipvs logic, it is assumed that there is only a single Proxier active on a machine.\n// An error will be returned if it fails to update or acquire the initial lock.\n// Once a proxier is created, it will keep iptables and ipvs rules up to date in the background and\n// will not terminate if a particular iptables or ipvs call fails.\nfunc NewProxier(ipFamily v1.IPFamily,\n\tipt utiliptables.Interface,\n\tipvs utilipvs.Interface,\n\tipset utilipset.Interface,\n\tsysctl utilsysctl.Interface,\n\texec utilexec.Interface,\n\tsyncPeriod time.Duration,\n\tminSyncPeriod time.Duration,\n\texcludeCIDRs []string,\n\tstrictARP bool,\n\ttcpTimeout time.Duration,\n\ttcpFinTimeout time.Duration,\n\tudpTimeout time.Duration,\n\tmasqueradeAll bool,\n\tmasqueradeBit int,\n\tlocalDetector proxyutiliptables.LocalTrafficDetector,\n\thostname string,\n\tnodeIP net.IP,\n\trecorder events.EventRecorder,\n\thealthzServer healthcheck.ProxierHealthUpdater,\n\tscheduler string,\n\tnodePortAddressStrings []string,\n\tkernelHandler KernelHandler,\n) (*Proxier, error) {\n\t// Proxy needs br_netfilter and bridge-nf-call-iptables=1 when containers\n\t// are connected to a Linux bridge (but not SDN bridges). Until most\n\t// plugins handle this, log when config is missing\n\tif val, err := sysctl.GetSysctl(sysctlBridgeCallIPTables); err == nil \u0026\u0026 val != 1 {\n\t\tklog.InfoS(\"Missing br-netfilter module or unset sysctl br-nf-call-iptables, proxy may not work as intended\")\n\t}\n\n\t// Set the conntrack sysctl we need for\n\tif err := utilproxy.EnsureSysctl(sysctl, sysctlVSConnTrack, 1); err != nil {\n\t\treturn nil, err\n\t}\n\n\tkernelVersionStr, err := kernelHandler.GetKernelVersion()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error determining kernel version to find required kernel modules for ipvs support: %v\", err)\n\t}\n\tkernelVersion, err := version.ParseGeneric(kernelVersionStr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing kernel version %q: %v\", kernelVersionStr, err)\n\t}\n\tif kernelVersion.LessThan(version.MustParseGeneric(connReuseMinSupportedKernelVersion)) {\n\t\tklog.ErrorS(nil, \"Can't set sysctl, kernel version doesn't satisfy minimum version requirements\", \"sysctl\", sysctlConnReuse, \"minimumKernelVersion\", connReuseMinSupportedKernelVersion)\n\t} else if kernelVersion.AtLeast(version.MustParseGeneric(connReuseFixedKernelVersion)) {\n\t\t// https://github.com/kubernetes/kubernetes/issues/93297\n\t\tklog.V(2).InfoS(\"Left as-is\", \"sysctl\", sysctlConnReuse)\n\t} else {\n\t\t// Set the connection reuse mode\n\t\tif err := utilproxy.EnsureSysctl(sysctl, sysctlConnReuse, 0); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Set the expire_nodest_conn sysctl we need for\n\tif err := utilproxy.EnsureSysctl(sysctl, sysctlExpireNoDestConn, 1); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Set the expire_quiescent_template sysctl we need for\n\tif err := utilproxy.EnsureSysctl(sysctl, sysctlExpireQuiescentTemplate, 1); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Set the ip_forward sysctl we need for\n\tif err := utilproxy.EnsureSysctl(sysctl, sysctlForward, 1); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif strictARP {\n\t\t// Set the arp_ignore sysctl we need for\n\t\tif err := utilproxy.EnsureSysctl(sysctl, sysctlArpIgnore, 1); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Set the arp_announce sysctl we need for\n\t\tif err := utilproxy.EnsureSysctl(sysctl, sysctlArpAnnounce, 2); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Configure IPVS timeouts if any one of the timeout parameters have been set.\n\t// This is the equivalent to running ipvsadm --set, a value of 0 indicates the\n\t// current system timeout should be preserved\n\tif tcpTimeout \u003e 0 || tcpFinTimeout \u003e 0 || udpTimeout \u003e 0 {\n\t\tif err := ipvs.ConfigureTimeouts(tcpTimeout, tcpFinTimeout, udpTimeout); err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to configure IPVS timeouts\")\n\t\t}\n\t}\n\n\t// Generate the masquerade mark to use for SNAT rules.\n\tmasqueradeValue := 1 \u003c\u003c uint(masqueradeBit)\n\tmasqueradeMark := fmt.Sprintf(\"%#08x\", masqueradeValue)\n\n\tklog.V(2).InfoS(\"Record nodeIP and family\", \"nodeIP\", nodeIP, \"family\", ipFamily)\n\n\tif len(scheduler) == 0 {\n\t\tklog.InfoS(\"IPVS scheduler not specified, use rr by default\")\n\t\tscheduler = defaultScheduler\n\t}\n\n\tnodePortAddresses := utilproxy.NewNodePortAddresses(nodePortAddressStrings)\n\n\tserviceHealthServer := healthcheck.NewServiceHealthServer(hostname, recorder, nodePortAddresses, healthzServer)\n\n\t// excludeCIDRs has been validated before, here we just parse it to IPNet list\n\tparsedExcludeCIDRs, _ := netutils.ParseCIDRs(excludeCIDRs)\n\n\tproxier := \u0026Proxier{\n\t\tipFamily: ipFamily,\n\t\tsvcPortMap: make(proxy.ServicePortMap),\n\t\tserviceChanges: proxy.NewServiceChangeTracker(newServiceInfo, ipFamily, recorder, nil),\n\t\tendpointsMap: make(proxy.EndpointsMap),\n\t\tendpointsChanges: proxy.NewEndpointChangeTracker(hostname, nil, ipFamily, recorder, nil),\n\t\tinitialSync: true,\n\t\tsyncPeriod: syncPeriod,\n\t\tminSyncPeriod: minSyncPeriod,\n\t\texcludeCIDRs: parsedExcludeCIDRs,\n\t\tiptables: ipt,\n\t\tmasqueradeAll: masqueradeAll,\n\t\tmasqueradeMark: masqueradeMark,\n\t\texec: exec,\n\t\tlocalDetector: localDetector,\n\t\thostname: hostname,\n\t\tnodeIP: nodeIP,\n\t\trecorder: recorder,\n\t\tserviceHealthServer: serviceHealthServer,\n\t\thealthzServer: healthzServer,\n\t\tipvs: ipvs,\n\t\tipvsScheduler: scheduler,\n\t\tiptablesData: bytes.NewBuffer(nil),\n\t\tfilterChainsData: bytes.NewBuffer(nil),\n\t\tnatChains: utilproxy.LineBuffer{},\n\t\tnatRules: utilproxy.LineBuffer{},\n\t\tfilterChains: utilproxy.LineBuffer{},\n\t\tfilterRules: utilproxy.LineBuffer{},\n\t\tnetlinkHandle: NewNetLinkHandle(ipFamily == v1.IPv6Protocol),\n\t\tipset: ipset,\n\t\tnodePortAddresses: nodePortAddresses,\n\t\tnetworkInterfacer: utilproxy.RealNetwork{},\n\t\tgracefuldeleteManager: NewGracefulTerminationManager(ipvs),\n\t}\n\t// initialize ipsetList with all sets we needed\n\tproxier.ipsetList = make(map[string]*IPSet)\n\tfor _, is := range ipsetInfo {\n\t\tproxier.ipsetList[is.name] = NewIPSet(ipset, is.name, is.setType, (ipFamily == v1.IPv6Protocol), is.comment)\n\t}\n\tburstSyncs := 2\n\tklog.V(2).InfoS(\"ipvs sync params\", \"ipFamily\", ipt.Protocol(), \"minSyncPeriod\", minSyncPeriod, \"syncPeriod\", syncPeriod, \"burstSyncs\", burstSyncs)\n\tproxier.syncRunner = async.NewBoundedFrequencyRunner(\"sync-runner\", proxier.syncProxyRules, minSyncPeriod, syncPeriod, burstSyncs)\n\tproxier.gracefuldeleteManager.Run()\n\treturn proxier, nil\n}","line":{"from":304,"to":463}} {"id":100008527,"name":"NewDualStackProxier","signature":"func NewDualStackProxier(","file":"pkg/proxy/ipvs/proxier.go","code":"// NewDualStackProxier returns a new Proxier for dual-stack operation\nfunc NewDualStackProxier(\n\tipt [2]utiliptables.Interface,\n\tipvs utilipvs.Interface,\n\tipset utilipset.Interface,\n\tsysctl utilsysctl.Interface,\n\texec utilexec.Interface,\n\tsyncPeriod time.Duration,\n\tminSyncPeriod time.Duration,\n\texcludeCIDRs []string,\n\tstrictARP bool,\n\ttcpTimeout time.Duration,\n\ttcpFinTimeout time.Duration,\n\tudpTimeout time.Duration,\n\tmasqueradeAll bool,\n\tmasqueradeBit int,\n\tlocalDetectors [2]proxyutiliptables.LocalTrafficDetector,\n\thostname string,\n\tnodeIP [2]net.IP,\n\trecorder events.EventRecorder,\n\thealthzServer healthcheck.ProxierHealthUpdater,\n\tscheduler string,\n\tnodePortAddresses []string,\n\tkernelHandler KernelHandler,\n) (proxy.Provider, error) {\n\n\tsafeIpset := newSafeIpset(ipset)\n\n\tipFamilyMap := utilproxy.MapCIDRsByIPFamily(nodePortAddresses)\n\n\t// Create an ipv4 instance of the single-stack proxier\n\tipv4Proxier, err := NewProxier(v1.IPv4Protocol, ipt[0], ipvs, safeIpset, sysctl,\n\t\texec, syncPeriod, minSyncPeriod, filterCIDRs(false, excludeCIDRs), strictARP,\n\t\ttcpTimeout, tcpFinTimeout, udpTimeout, masqueradeAll, masqueradeBit,\n\t\tlocalDetectors[0], hostname, nodeIP[0],\n\t\trecorder, healthzServer, scheduler, ipFamilyMap[v1.IPv4Protocol], kernelHandler)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create ipv4 proxier: %v\", err)\n\t}\n\n\tipv6Proxier, err := NewProxier(v1.IPv6Protocol, ipt[1], ipvs, safeIpset, sysctl,\n\t\texec, syncPeriod, minSyncPeriod, filterCIDRs(true, excludeCIDRs), strictARP,\n\t\ttcpTimeout, tcpFinTimeout, udpTimeout, masqueradeAll, masqueradeBit,\n\t\tlocalDetectors[1], hostname, nodeIP[1],\n\t\tnil, nil, scheduler, ipFamilyMap[v1.IPv6Protocol], kernelHandler)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create ipv6 proxier: %v\", err)\n\t}\n\n\t// Return a meta-proxier that dispatch calls between the two\n\t// single-stack proxier instances\n\treturn metaproxier.NewMetaProxier(ipv4Proxier, ipv6Proxier), nil\n}","line":{"from":465,"to":517}} {"id":100008528,"name":"filterCIDRs","signature":"func filterCIDRs(wantIPv6 bool, cidrs []string) []string","file":"pkg/proxy/ipvs/proxier.go","code":"func filterCIDRs(wantIPv6 bool, cidrs []string) []string {\n\tvar filteredCIDRs []string\n\tfor _, cidr := range cidrs {\n\t\tif netutils.IsIPv6CIDRString(cidr) == wantIPv6 {\n\t\t\tfilteredCIDRs = append(filteredCIDRs, cidr)\n\t\t}\n\t}\n\treturn filteredCIDRs\n}","line":{"from":519,"to":527}} {"id":100008529,"name":"newServiceInfo","signature":"func newServiceInfo(port *v1.ServicePort, service *v1.Service, bsvcPortInfo *proxy.BaseServicePortInfo) proxy.ServicePort","file":"pkg/proxy/ipvs/proxier.go","code":"// returns a new proxy.ServicePort which abstracts a serviceInfo\nfunc newServiceInfo(port *v1.ServicePort, service *v1.Service, bsvcPortInfo *proxy.BaseServicePortInfo) proxy.ServicePort {\n\tsvcPort := \u0026servicePortInfo{BaseServicePortInfo: bsvcPortInfo}\n\n\t// Store the following for performance reasons.\n\tsvcName := types.NamespacedName{Namespace: service.Namespace, Name: service.Name}\n\tsvcPortName := proxy.ServicePortName{NamespacedName: svcName, Port: port.Name}\n\tsvcPort.nameString = svcPortName.String()\n\n\treturn svcPort\n}","line":{"from":536,"to":546}} {"id":100008530,"name":"NewLinuxKernelHandler","signature":"func NewLinuxKernelHandler() *LinuxKernelHandler","file":"pkg/proxy/ipvs/proxier.go","code":"// NewLinuxKernelHandler initializes LinuxKernelHandler with exec.\nfunc NewLinuxKernelHandler() *LinuxKernelHandler {\n\treturn \u0026LinuxKernelHandler{\n\t\texecutor: utilexec.New(),\n\t}\n}","line":{"from":558,"to":563}} {"id":100008531,"name":"getFirstColumn","signature":"func getFirstColumn(r io.Reader) ([]string, error)","file":"pkg/proxy/ipvs/proxier.go","code":"// getFirstColumn reads all the content from r into memory and return a\n// slice which consists of the first word from each line.\nfunc getFirstColumn(r io.Reader) ([]string, error) {\n\tb, err := io.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlines := strings.Split(string(b), \"\\n\")\n\twords := make([]string, 0, len(lines))\n\tfor i := range lines {\n\t\tfields := strings.Fields(lines[i])\n\t\tif len(fields) \u003e 0 {\n\t\t\twords = append(words, fields[0])\n\t\t}\n\t}\n\treturn words, nil\n}","line":{"from":565,"to":582}} {"id":100008532,"name":"GetKernelVersion","signature":"func (handle *LinuxKernelHandler) GetKernelVersion() (string, error)","file":"pkg/proxy/ipvs/proxier.go","code":"// GetKernelVersion returns currently running kernel version.\nfunc (handle *LinuxKernelHandler) GetKernelVersion() (string, error) {\n\tkernelVersionFile := \"/proc/sys/kernel/osrelease\"\n\tfileContent, err := os.ReadFile(kernelVersionFile)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error reading osrelease file %q: %v\", kernelVersionFile, err)\n\t}\n\n\treturn strings.TrimSpace(string(fileContent)), nil\n}","line":{"from":584,"to":593}} {"id":100008533,"name":"CanUseIPVSProxier","signature":"func CanUseIPVSProxier(ipvs utilipvs.Interface, ipsetver IPSetVersioner, scheduler string) error","file":"pkg/proxy/ipvs/proxier.go","code":"// CanUseIPVSProxier checks if we can use the ipvs Proxier.\n// The ipset version and the scheduler are checked. If any virtual servers (VS)\n// already exist with the configured scheduler, we just return. Otherwise\n// we check if a dummy VS can be configured with the configured scheduler.\n// Kernel modules will be loaded automatically if necessary.\nfunc CanUseIPVSProxier(ipvs utilipvs.Interface, ipsetver IPSetVersioner, scheduler string) error {\n\t// BUG: https://github.com/moby/ipvs/issues/27\n\t// If ipvs is not compiled into the kernel no error is returned and handle==nil.\n\t// This in turn causes ipvs.GetVirtualServers and ipvs.AddVirtualServer\n\t// to return ok (err==nil). If/when this bug is fixed parameter \"ipvs\" will be nil\n\t// if ipvs is not supported by the kernel. Until then a re-read work-around is used.\n\tif ipvs == nil {\n\t\treturn fmt.Errorf(\"Ipvs not supported by the kernel\")\n\t}\n\n\t// Check ipset version\n\tversionString, err := ipsetver.GetVersion()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting ipset version, error: %v\", err)\n\t}\n\tif !checkMinVersion(versionString) {\n\t\treturn fmt.Errorf(\"ipset version: %s is less than min required version: %s\", versionString, MinIPSetCheckVersion)\n\t}\n\n\tif scheduler == \"\" {\n\t\tscheduler = defaultScheduler\n\t}\n\n\t// If any virtual server (VS) using the scheduler exist we skip the checks.\n\tvservers, err := ipvs.GetVirtualServers()\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Can't read the ipvs\")\n\t\treturn err\n\t}\n\tklog.V(5).InfoS(\"Virtual Servers\", \"count\", len(vservers))\n\tif len(vservers) \u003e 0 {\n\t\t// This is most likely a kube-proxy re-start. We know that ipvs works\n\t\t// and if any VS uses the configured scheduler, we are done.\n\t\tfor _, vs := range vservers {\n\t\t\tif vs.Scheduler == scheduler {\n\t\t\t\tklog.V(5).InfoS(\"VS exist, Skipping checks\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\tklog.V(5).InfoS(\"No existing VS uses the configured scheduler\", \"scheduler\", scheduler)\n\t}\n\n\t// Try to insert a dummy VS with the passed scheduler.\n\t// We should use a VIP address that is not used on the node.\n\t// An address \"198.51.100.0\" from the TEST-NET-2 rage in https://datatracker.ietf.org/doc/html/rfc5737\n\t// is used. These addresses are reserved for documentation. If the user is using\n\t// this address for a VS anyway we *will* mess up, but that would be an invalid configuration.\n\t// If the user have configured the address to an interface on the node (but not a VS)\n\t// then traffic will temporary be routed to ipvs during the probe and dropped.\n\t// The later case is also and invalid configuration, but the traffic impact will be minor.\n\t// This should not be a problem if users honors reserved addresses, but cut/paste\n\t// from documentation is not unheard of, so the restriction to not use the TEST-NET-2 range\n\t// must be documented.\n\tvs := utilipvs.VirtualServer{\n\t\tAddress: netutils.ParseIPSloppy(\"198.51.100.0\"),\n\t\tProtocol: \"TCP\",\n\t\tPort: 20000,\n\t\tScheduler: scheduler,\n\t}\n\tif err := ipvs.AddVirtualServer(\u0026vs); err != nil {\n\t\tklog.ErrorS(err, \"Could not create dummy VS\", \"scheduler\", scheduler)\n\t\treturn err\n\t}\n\n\t// To overcome the BUG described above we check that the VS is *really* added.\n\tvservers, err = ipvs.GetVirtualServers()\n\tif err != nil {\n\t\tklog.ErrorS(err, \"ipvs.GetVirtualServers\")\n\t\treturn err\n\t}\n\tklog.V(5).InfoS(\"Virtual Servers after adding dummy\", \"count\", len(vservers))\n\tif len(vservers) == 0 {\n\t\tklog.InfoS(\"Dummy VS not created\", \"scheduler\", scheduler)\n\t\treturn fmt.Errorf(\"Ipvs not supported\") // This is a BUG work-around\n\t}\n\tklog.V(5).InfoS(\"Dummy VS created\", \"vs\", vs)\n\n\tif err := ipvs.DeleteVirtualServer(\u0026vs); err != nil {\n\t\tklog.ErrorS(err, \"Could not delete dummy VS\")\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":595,"to":683}} {"id":100008534,"name":"cleanupIptablesLeftovers","signature":"func cleanupIptablesLeftovers(ipt utiliptables.Interface) (encounteredError bool)","file":"pkg/proxy/ipvs/proxier.go","code":"// CleanupIptablesLeftovers removes all iptables rules and chains created by the Proxier\n// It returns true if an error was encountered. Errors are logged.\nfunc cleanupIptablesLeftovers(ipt utiliptables.Interface) (encounteredError bool) {\n\t// Unlink the iptables chains created by ipvs Proxier\n\tfor _, jc := range iptablesJumpChain {\n\t\targs := []string{\n\t\t\t\"-m\", \"comment\", \"--comment\", jc.comment,\n\t\t\t\"-j\", string(jc.to),\n\t\t}\n\t\tif err := ipt.DeleteRule(jc.table, jc.from, args...); err != nil {\n\t\t\tif !utiliptables.IsNotFoundError(err) {\n\t\t\t\tklog.ErrorS(err, \"Error removing iptables rules in ipvs proxier\")\n\t\t\t\tencounteredError = true\n\t\t\t}\n\t\t}\n\t}\n\n\t// Flush and remove all of our chains. Flushing all chains before removing them also removes all links between chains first.\n\tfor _, ch := range iptablesCleanupChains {\n\t\tif err := ipt.FlushChain(ch.table, ch.chain); err != nil {\n\t\t\tif !utiliptables.IsNotFoundError(err) {\n\t\t\t\tklog.ErrorS(err, \"Error removing iptables rules in ipvs proxier\")\n\t\t\t\tencounteredError = true\n\t\t\t}\n\t\t}\n\t}\n\n\t// Remove all of our chains.\n\tfor _, ch := range iptablesCleanupChains {\n\t\tif err := ipt.DeleteChain(ch.table, ch.chain); err != nil {\n\t\t\tif !utiliptables.IsNotFoundError(err) {\n\t\t\t\tklog.ErrorS(err, \"Error removing iptables rules in ipvs proxier\")\n\t\t\t\tencounteredError = true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn encounteredError\n}","line":{"from":685,"to":723}} {"id":100008535,"name":"CleanupLeftovers","signature":"func CleanupLeftovers(ipvs utilipvs.Interface, ipt utiliptables.Interface, ipset utilipset.Interface) (encounteredError bool)","file":"pkg/proxy/ipvs/proxier.go","code":"// CleanupLeftovers clean up all ipvs and iptables rules created by ipvs Proxier.\nfunc CleanupLeftovers(ipvs utilipvs.Interface, ipt utiliptables.Interface, ipset utilipset.Interface) (encounteredError bool) {\n\t// Clear all ipvs rules\n\tif ipvs != nil {\n\t\terr := ipvs.Flush()\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Error flushing ipvs rules\")\n\t\t\tencounteredError = true\n\t\t}\n\t}\n\t// Delete dummy interface created by ipvs Proxier.\n\tnl := NewNetLinkHandle(false)\n\terr := nl.DeleteDummyDevice(defaultDummyDevice)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Error deleting dummy device created by ipvs proxier\", \"device\", defaultDummyDevice)\n\t\tencounteredError = true\n\t}\n\t// Clear iptables created by ipvs Proxier.\n\tencounteredError = cleanupIptablesLeftovers(ipt) || encounteredError\n\t// Destroy ip sets created by ipvs Proxier. We should call it after cleaning up\n\t// iptables since we can NOT delete ip set which is still referenced by iptables.\n\tfor _, set := range ipsetInfo {\n\t\terr = ipset.DestroySet(set.name)\n\t\tif err != nil {\n\t\t\tif !utilipset.IsNotFoundError(err) {\n\t\t\t\tklog.ErrorS(err, \"Error removing ipset\", \"ipset\", set.name)\n\t\t\t\tencounteredError = true\n\t\t\t}\n\t\t}\n\t}\n\treturn encounteredError\n}","line":{"from":725,"to":756}} {"id":100008536,"name":"Sync","signature":"func (proxier *Proxier) Sync()","file":"pkg/proxy/ipvs/proxier.go","code":"// Sync is called to synchronize the proxier state to iptables and ipvs as soon as possible.\nfunc (proxier *Proxier) Sync() {\n\tif proxier.healthzServer != nil {\n\t\tproxier.healthzServer.QueuedUpdate()\n\t}\n\tmetrics.SyncProxyRulesLastQueuedTimestamp.SetToCurrentTime()\n\tproxier.syncRunner.Run()\n}","line":{"from":758,"to":765}} {"id":100008537,"name":"SyncLoop","signature":"func (proxier *Proxier) SyncLoop()","file":"pkg/proxy/ipvs/proxier.go","code":"// SyncLoop runs periodic work. This is expected to run as a goroutine or as the main loop of the app. It does not return.\nfunc (proxier *Proxier) SyncLoop() {\n\t// Update healthz timestamp at beginning in case Sync() never succeeds.\n\tif proxier.healthzServer != nil {\n\t\tproxier.healthzServer.Updated()\n\t}\n\t// synthesize \"last change queued\" time as the informers are syncing.\n\tmetrics.SyncProxyRulesLastQueuedTimestamp.SetToCurrentTime()\n\tproxier.syncRunner.Loop(wait.NeverStop)\n}","line":{"from":767,"to":776}} {"id":100008538,"name":"setInitialized","signature":"func (proxier *Proxier) setInitialized(value bool)","file":"pkg/proxy/ipvs/proxier.go","code":"func (proxier *Proxier) setInitialized(value bool) {\n\tvar initialized int32\n\tif value {\n\t\tinitialized = 1\n\t}\n\tatomic.StoreInt32(\u0026proxier.initialized, initialized)\n}","line":{"from":778,"to":784}} {"id":100008539,"name":"isInitialized","signature":"func (proxier *Proxier) isInitialized() bool","file":"pkg/proxy/ipvs/proxier.go","code":"func (proxier *Proxier) isInitialized() bool {\n\treturn atomic.LoadInt32(\u0026proxier.initialized) \u003e 0\n}","line":{"from":786,"to":788}} {"id":100008540,"name":"OnServiceAdd","signature":"func (proxier *Proxier) OnServiceAdd(service *v1.Service)","file":"pkg/proxy/ipvs/proxier.go","code":"// OnServiceAdd is called whenever creation of new service object is observed.\nfunc (proxier *Proxier) OnServiceAdd(service *v1.Service) {\n\tproxier.OnServiceUpdate(nil, service)\n}","line":{"from":790,"to":793}} {"id":100008541,"name":"OnServiceUpdate","signature":"func (proxier *Proxier) OnServiceUpdate(oldService, service *v1.Service)","file":"pkg/proxy/ipvs/proxier.go","code":"// OnServiceUpdate is called whenever modification of an existing service object is observed.\nfunc (proxier *Proxier) OnServiceUpdate(oldService, service *v1.Service) {\n\tif proxier.serviceChanges.Update(oldService, service) \u0026\u0026 proxier.isInitialized() {\n\t\tproxier.Sync()\n\t}\n}","line":{"from":795,"to":800}} {"id":100008542,"name":"OnServiceDelete","signature":"func (proxier *Proxier) OnServiceDelete(service *v1.Service)","file":"pkg/proxy/ipvs/proxier.go","code":"// OnServiceDelete is called whenever deletion of an existing service object is observed.\nfunc (proxier *Proxier) OnServiceDelete(service *v1.Service) {\n\tproxier.OnServiceUpdate(service, nil)\n}","line":{"from":802,"to":805}} {"id":100008543,"name":"OnServiceSynced","signature":"func (proxier *Proxier) OnServiceSynced()","file":"pkg/proxy/ipvs/proxier.go","code":"// OnServiceSynced is called once all the initial event handlers were called and the state is fully propagated to local cache.\nfunc (proxier *Proxier) OnServiceSynced() {\n\tproxier.mu.Lock()\n\tproxier.servicesSynced = true\n\tproxier.setInitialized(proxier.endpointSlicesSynced)\n\tproxier.mu.Unlock()\n\n\t// Sync unconditionally - this is called once per lifetime.\n\tproxier.syncProxyRules()\n}","line":{"from":807,"to":816}} {"id":100008544,"name":"OnEndpointSliceAdd","signature":"func (proxier *Proxier) OnEndpointSliceAdd(endpointSlice *discovery.EndpointSlice)","file":"pkg/proxy/ipvs/proxier.go","code":"// OnEndpointSliceAdd is called whenever creation of a new endpoint slice object\n// is observed.\nfunc (proxier *Proxier) OnEndpointSliceAdd(endpointSlice *discovery.EndpointSlice) {\n\tif proxier.endpointsChanges.EndpointSliceUpdate(endpointSlice, false) \u0026\u0026 proxier.isInitialized() {\n\t\tproxier.Sync()\n\t}\n}","line":{"from":818,"to":824}} {"id":100008545,"name":"OnEndpointSliceUpdate","signature":"func (proxier *Proxier) OnEndpointSliceUpdate(_, endpointSlice *discovery.EndpointSlice)","file":"pkg/proxy/ipvs/proxier.go","code":"// OnEndpointSliceUpdate is called whenever modification of an existing endpoint\n// slice object is observed.\nfunc (proxier *Proxier) OnEndpointSliceUpdate(_, endpointSlice *discovery.EndpointSlice) {\n\tif proxier.endpointsChanges.EndpointSliceUpdate(endpointSlice, false) \u0026\u0026 proxier.isInitialized() {\n\t\tproxier.Sync()\n\t}\n}","line":{"from":826,"to":832}} {"id":100008546,"name":"OnEndpointSliceDelete","signature":"func (proxier *Proxier) OnEndpointSliceDelete(endpointSlice *discovery.EndpointSlice)","file":"pkg/proxy/ipvs/proxier.go","code":"// OnEndpointSliceDelete is called whenever deletion of an existing endpoint slice\n// object is observed.\nfunc (proxier *Proxier) OnEndpointSliceDelete(endpointSlice *discovery.EndpointSlice) {\n\tif proxier.endpointsChanges.EndpointSliceUpdate(endpointSlice, true) \u0026\u0026 proxier.isInitialized() {\n\t\tproxier.Sync()\n\t}\n}","line":{"from":834,"to":840}} {"id":100008547,"name":"OnEndpointSlicesSynced","signature":"func (proxier *Proxier) OnEndpointSlicesSynced()","file":"pkg/proxy/ipvs/proxier.go","code":"// OnEndpointSlicesSynced is called once all the initial event handlers were\n// called and the state is fully propagated to local cache.\nfunc (proxier *Proxier) OnEndpointSlicesSynced() {\n\tproxier.mu.Lock()\n\tproxier.endpointSlicesSynced = true\n\tproxier.setInitialized(proxier.servicesSynced)\n\tproxier.mu.Unlock()\n\n\t// Sync unconditionally - this is called once per lifetime.\n\tproxier.syncProxyRules()\n}","line":{"from":842,"to":852}} {"id":100008548,"name":"OnNodeAdd","signature":"func (proxier *Proxier) OnNodeAdd(node *v1.Node)","file":"pkg/proxy/ipvs/proxier.go","code":"// OnNodeAdd is called whenever creation of new node object\n// is observed.\nfunc (proxier *Proxier) OnNodeAdd(node *v1.Node) {\n\tif node.Name != proxier.hostname {\n\t\tklog.ErrorS(nil, \"Received a watch event for a node that doesn't match the current node\", \"eventNode\", node.Name, \"currentNode\", proxier.hostname)\n\t\treturn\n\t}\n\n\tif reflect.DeepEqual(proxier.nodeLabels, node.Labels) {\n\t\treturn\n\t}\n\n\tproxier.mu.Lock()\n\tproxier.nodeLabels = map[string]string{}\n\tfor k, v := range node.Labels {\n\t\tproxier.nodeLabels[k] = v\n\t}\n\tproxier.mu.Unlock()\n\tklog.V(4).InfoS(\"Updated proxier node labels\", \"labels\", node.Labels)\n\n\tproxier.Sync()\n}","line":{"from":854,"to":875}} {"id":100008549,"name":"OnNodeUpdate","signature":"func (proxier *Proxier) OnNodeUpdate(oldNode, node *v1.Node)","file":"pkg/proxy/ipvs/proxier.go","code":"// OnNodeUpdate is called whenever modification of an existing\n// node object is observed.\nfunc (proxier *Proxier) OnNodeUpdate(oldNode, node *v1.Node) {\n\tif node.Name != proxier.hostname {\n\t\tklog.ErrorS(nil, \"Received a watch event for a node that doesn't match the current node\", \"eventNode\", node.Name, \"currentNode\", proxier.hostname)\n\t\treturn\n\t}\n\n\tif reflect.DeepEqual(proxier.nodeLabels, node.Labels) {\n\t\treturn\n\t}\n\n\tproxier.mu.Lock()\n\tproxier.nodeLabels = map[string]string{}\n\tfor k, v := range node.Labels {\n\t\tproxier.nodeLabels[k] = v\n\t}\n\tproxier.mu.Unlock()\n\tklog.V(4).InfoS(\"Updated proxier node labels\", \"labels\", node.Labels)\n\n\tproxier.Sync()\n}","line":{"from":877,"to":898}} {"id":100008550,"name":"OnNodeDelete","signature":"func (proxier *Proxier) OnNodeDelete(node *v1.Node)","file":"pkg/proxy/ipvs/proxier.go","code":"// OnNodeDelete is called whenever deletion of an existing node\n// object is observed.\nfunc (proxier *Proxier) OnNodeDelete(node *v1.Node) {\n\tif node.Name != proxier.hostname {\n\t\tklog.ErrorS(nil, \"Received a watch event for a node that doesn't match the current node\", \"eventNode\", node.Name, \"currentNode\", proxier.hostname)\n\t\treturn\n\t}\n\tproxier.mu.Lock()\n\tproxier.nodeLabels = nil\n\tproxier.mu.Unlock()\n\n\tproxier.Sync()\n}","line":{"from":900,"to":912}} {"id":100008551,"name":"OnNodeSynced","signature":"func (proxier *Proxier) OnNodeSynced()","file":"pkg/proxy/ipvs/proxier.go","code":"// OnNodeSynced is called once all the initial event handlers were\n// called and the state is fully propagated to local cache.\nfunc (proxier *Proxier) OnNodeSynced() {\n}","line":{"from":914,"to":917}} {"id":100008552,"name":"syncProxyRules","signature":"func (proxier *Proxier) syncProxyRules()","file":"pkg/proxy/ipvs/proxier.go","code":"// This is where all of the ipvs calls happen.\nfunc (proxier *Proxier) syncProxyRules() {\n\tproxier.mu.Lock()\n\tdefer proxier.mu.Unlock()\n\n\t// don't sync rules till we've received services and endpoints\n\tif !proxier.isInitialized() {\n\t\tklog.V(2).InfoS(\"Not syncing ipvs rules until Services and Endpoints have been received from master\")\n\t\treturn\n\t}\n\n\t// its safe to set initialSync to false as it acts as a flag for startup actions\n\t// and the mutex is held.\n\tdefer func() {\n\t\tproxier.initialSync = false\n\t}()\n\n\t// Keep track of how long syncs take.\n\tstart := time.Now()\n\tdefer func() {\n\t\tmetrics.SyncProxyRulesLatency.Observe(metrics.SinceInSeconds(start))\n\t\tklog.V(4).InfoS(\"syncProxyRules complete\", \"elapsed\", time.Since(start))\n\t}()\n\n\t// We assume that if this was called, we really want to sync them,\n\t// even if nothing changed in the meantime. In other words, callers are\n\t// responsible for detecting no-op changes and not calling this function.\n\tserviceUpdateResult := proxier.svcPortMap.Update(proxier.serviceChanges)\n\tendpointUpdateResult := proxier.endpointsMap.Update(proxier.endpointsChanges)\n\n\t// We need to detect stale connections to UDP Services so we\n\t// can clean dangling conntrack entries that can blackhole traffic.\n\tconntrackCleanupServiceIPs := serviceUpdateResult.DeletedUDPClusterIPs\n\tconntrackCleanupServiceNodePorts := sets.NewInt()\n\t// merge stale services gathered from updateEndpointsMap\n\t// an UDP service that changes from 0 to non-0 endpoints is considered stale.\n\tfor _, svcPortName := range endpointUpdateResult.NewlyActiveUDPServices {\n\t\tif svcInfo, ok := proxier.svcPortMap[svcPortName]; ok {\n\t\t\tklog.V(4).InfoS(\"Newly-active UDP service may have stale conntrack entries\", \"servicePortName\", svcPortName)\n\t\t\tconntrackCleanupServiceIPs.Insert(svcInfo.ClusterIP().String())\n\t\t\tfor _, extIP := range svcInfo.ExternalIPStrings() {\n\t\t\t\tconntrackCleanupServiceIPs.Insert(extIP)\n\t\t\t}\n\t\t\tfor _, lbIP := range svcInfo.LoadBalancerIPStrings() {\n\t\t\t\tconntrackCleanupServiceIPs.Insert(lbIP)\n\t\t\t}\n\t\t\tnodePort := svcInfo.NodePort()\n\t\t\tif svcInfo.Protocol() == v1.ProtocolUDP \u0026\u0026 nodePort != 0 {\n\t\t\t\tconntrackCleanupServiceNodePorts.Insert(nodePort)\n\t\t\t}\n\t\t}\n\t}\n\n\tklog.V(3).InfoS(\"Syncing ipvs proxier rules\")\n\n\tproxier.serviceNoLocalEndpointsInternal = sets.New[string]()\n\tproxier.serviceNoLocalEndpointsExternal = sets.New[string]()\n\t// Begin install iptables\n\n\t// Reset all buffers used later.\n\t// This is to avoid memory reallocations and thus improve performance.\n\tproxier.natChains.Reset()\n\tproxier.natRules.Reset()\n\tproxier.filterChains.Reset()\n\tproxier.filterRules.Reset()\n\n\t// Write table headers.\n\tproxier.filterChains.Write(\"*filter\")\n\tproxier.natChains.Write(\"*nat\")\n\n\tproxier.createAndLinkKubeChain()\n\n\t// make sure dummy interface exists in the system where ipvs Proxier will bind service address on it\n\t_, err := proxier.netlinkHandle.EnsureDummyDevice(defaultDummyDevice)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to create dummy interface\", \"interface\", defaultDummyDevice)\n\t\treturn\n\t}\n\n\t// make sure ip sets exists in the system.\n\tfor _, set := range proxier.ipsetList {\n\t\tif err := ensureIPSet(set); err != nil {\n\t\t\treturn\n\t\t}\n\t\tset.resetEntries()\n\t}\n\n\t// activeIPVSServices represents IPVS service successfully created in this round of sync\n\tactiveIPVSServices := sets.New[string]()\n\t// activeBindAddrs Represents addresses we want on the defaultDummyDevice after this round of sync\n\tactiveBindAddrs := sets.New[string]()\n\t// alreadyBoundAddrs Represents addresses currently assigned to the dummy interface\n\talreadyBoundAddrs, err := proxier.netlinkHandle.GetLocalAddresses(defaultDummyDevice)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Error listing addresses binded to dummy interface\")\n\t}\n\t// nodeAddressSet All addresses *except* those on the dummy interface\n\tnodeAddressSet, err := proxier.netlinkHandle.GetAllLocalAddressesExcept(defaultDummyDevice)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Error listing node addresses\")\n\t}\n\n\thasNodePort := false\n\tfor _, svc := range proxier.svcPortMap {\n\t\tsvcInfo, ok := svc.(*servicePortInfo)\n\t\tif ok \u0026\u0026 svcInfo.NodePort() != 0 {\n\t\t\thasNodePort = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Both nodeAddresses and nodeIPs can be reused for all nodePort services\n\t// and only need to be computed if we have at least one nodePort service.\n\tvar (\n\t\t// List of node addresses to listen on if a nodePort is set.\n\t\tnodeAddresses []string\n\t\t// List of node IP addresses to be used as IPVS services if nodePort is set.\n\t\tnodeIPs []net.IP\n\t)\n\n\tif hasNodePort {\n\t\tnodeAddrSet, err := proxier.nodePortAddresses.GetNodeAddresses(proxier.networkInterfacer)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to get node IP address matching nodeport cidr\")\n\t\t} else {\n\t\t\tnodeAddresses = nodeAddrSet.List()\n\t\t\tfor _, address := range nodeAddresses {\n\t\t\t\ta := netutils.ParseIPSloppy(address)\n\t\t\t\tif a.IsLoopback() {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif utilproxy.IsZeroCIDR(address) {\n\t\t\t\t\tnodeIPs = nil\n\t\t\t\t\tfor _, ipStr := range nodeAddressSet.UnsortedList() {\n\t\t\t\t\t\tnodeIPs = append(nodeIPs, netutils.ParseIPSloppy(ipStr))\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif getIPFamily(a) == proxier.ipFamily {\n\t\t\t\t\tnodeIPs = append(nodeIPs, a)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Build IPVS rules for each service.\n\tfor svcPortName, svcPort := range proxier.svcPortMap {\n\t\tsvcInfo, ok := svcPort.(*servicePortInfo)\n\t\tif !ok {\n\t\t\tklog.ErrorS(nil, \"Failed to cast serviceInfo\", \"servicePortName\", svcPortName)\n\t\t\tcontinue\n\t\t}\n\n\t\tprotocol := strings.ToLower(string(svcInfo.Protocol()))\n\t\t// Precompute svcNameString; with many services the many calls\n\t\t// to ServicePortName.String() show up in CPU profiles.\n\t\tsvcPortNameString := svcPortName.String()\n\n\t\t// Handle traffic that loops back to the originator with SNAT.\n\t\tfor _, e := range proxier.endpointsMap[svcPortName] {\n\t\t\tep, ok := e.(*proxy.BaseEndpointInfo)\n\t\t\tif !ok {\n\t\t\t\tklog.ErrorS(nil, \"Failed to cast BaseEndpointInfo\", \"endpoint\", e)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !ep.IsLocal {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tepIP := ep.IP()\n\t\t\tepPort, err := ep.Port()\n\t\t\t// Error parsing this endpoint has been logged. Skip to next endpoint.\n\t\t\tif epIP == \"\" || err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tentry := \u0026utilipset.Entry{\n\t\t\t\tIP: epIP,\n\t\t\t\tPort: epPort,\n\t\t\t\tProtocol: protocol,\n\t\t\t\tIP2: epIP,\n\t\t\t\tSetType: utilipset.HashIPPortIP,\n\t\t\t}\n\t\t\tif valid := proxier.ipsetList[kubeLoopBackIPSet].validateEntry(entry); !valid {\n\t\t\t\tklog.ErrorS(nil, \"Error adding entry to ipset\", \"entry\", entry, \"ipset\", proxier.ipsetList[kubeLoopBackIPSet].Name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tproxier.ipsetList[kubeLoopBackIPSet].activeEntries.Insert(entry.String())\n\t\t}\n\n\t\t// Capture the clusterIP.\n\t\t// ipset call\n\t\tentry := \u0026utilipset.Entry{\n\t\t\tIP: svcInfo.ClusterIP().String(),\n\t\t\tPort: svcInfo.Port(),\n\t\t\tProtocol: protocol,\n\t\t\tSetType: utilipset.HashIPPort,\n\t\t}\n\t\t// add service Cluster IP:Port to kubeServiceAccess ip set for the purpose of solving hairpin.\n\t\t// proxier.kubeServiceAccessSet.activeEntries.Insert(entry.String())\n\t\tif valid := proxier.ipsetList[kubeClusterIPSet].validateEntry(entry); !valid {\n\t\t\tklog.ErrorS(nil, \"Error adding entry to ipset\", \"entry\", entry, \"ipset\", proxier.ipsetList[kubeClusterIPSet].Name)\n\t\t\tcontinue\n\t\t}\n\t\tproxier.ipsetList[kubeClusterIPSet].activeEntries.Insert(entry.String())\n\t\t// ipvs call\n\t\tserv := \u0026utilipvs.VirtualServer{\n\t\t\tAddress: svcInfo.ClusterIP(),\n\t\t\tPort: uint16(svcInfo.Port()),\n\t\t\tProtocol: string(svcInfo.Protocol()),\n\t\t\tScheduler: proxier.ipvsScheduler,\n\t\t}\n\t\t// Set session affinity flag and timeout for IPVS service\n\t\tif svcInfo.SessionAffinityType() == v1.ServiceAffinityClientIP {\n\t\t\tserv.Flags |= utilipvs.FlagPersistent\n\t\t\tserv.Timeout = uint32(svcInfo.StickyMaxAgeSeconds())\n\t\t}\n\t\t// Set the source hash flag needed for the distribution method \"mh\"\n\t\tif proxier.ipvsScheduler == \"mh\" {\n\t\t\tserv.Flags |= utilipvs.FlagSourceHash\n\t\t}\n\t\t// We need to bind ClusterIP to dummy interface, so set `bindAddr` parameter to `true` in syncService()\n\t\tif err := proxier.syncService(svcPortNameString, serv, true, alreadyBoundAddrs); err == nil {\n\t\t\tactiveIPVSServices.Insert(serv.String())\n\t\t\tactiveBindAddrs.Insert(serv.Address.String())\n\t\t\t// ExternalTrafficPolicy only works for NodePort and external LB traffic, does not affect ClusterIP\n\t\t\t// So we still need clusterIP rules in onlyNodeLocalEndpoints mode.\n\t\t\tinternalNodeLocal := false\n\t\t\tif svcInfo.InternalPolicyLocal() {\n\t\t\t\tinternalNodeLocal = true\n\t\t\t}\n\t\t\tif err := proxier.syncEndpoint(svcPortName, internalNodeLocal, serv); err != nil {\n\t\t\t\tklog.ErrorS(err, \"Failed to sync endpoint for service\", \"servicePortName\", svcPortName, \"virtualServer\", serv)\n\t\t\t}\n\t\t} else {\n\t\t\tklog.ErrorS(err, \"Failed to sync service\", \"servicePortName\", svcPortName, \"virtualServer\", serv)\n\t\t}\n\n\t\t// Capture externalIPs.\n\t\tfor _, externalIP := range svcInfo.ExternalIPStrings() {\n\t\t\t// ipset call\n\t\t\tentry := \u0026utilipset.Entry{\n\t\t\t\tIP: externalIP,\n\t\t\t\tPort: svcInfo.Port(),\n\t\t\t\tProtocol: protocol,\n\t\t\t\tSetType: utilipset.HashIPPort,\n\t\t\t}\n\n\t\t\tif svcInfo.ExternalPolicyLocal() {\n\t\t\t\tif valid := proxier.ipsetList[kubeExternalIPLocalSet].validateEntry(entry); !valid {\n\t\t\t\t\tklog.ErrorS(nil, \"Error adding entry to ipset\", \"entry\", entry, \"ipset\", proxier.ipsetList[kubeExternalIPLocalSet].Name)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tproxier.ipsetList[kubeExternalIPLocalSet].activeEntries.Insert(entry.String())\n\t\t\t} else {\n\t\t\t\t// We have to SNAT packets to external IPs.\n\t\t\t\tif valid := proxier.ipsetList[kubeExternalIPSet].validateEntry(entry); !valid {\n\t\t\t\t\tklog.ErrorS(nil, \"Error adding entry to ipset\", \"entry\", entry, \"ipset\", proxier.ipsetList[kubeExternalIPSet].Name)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tproxier.ipsetList[kubeExternalIPSet].activeEntries.Insert(entry.String())\n\t\t\t}\n\n\t\t\t// ipvs call\n\t\t\tserv := \u0026utilipvs.VirtualServer{\n\t\t\t\tAddress: netutils.ParseIPSloppy(externalIP),\n\t\t\t\tPort: uint16(svcInfo.Port()),\n\t\t\t\tProtocol: string(svcInfo.Protocol()),\n\t\t\t\tScheduler: proxier.ipvsScheduler,\n\t\t\t}\n\t\t\tif svcInfo.SessionAffinityType() == v1.ServiceAffinityClientIP {\n\t\t\t\tserv.Flags |= utilipvs.FlagPersistent\n\t\t\t\tserv.Timeout = uint32(svcInfo.StickyMaxAgeSeconds())\n\t\t\t}\n\t\t\t// Set the source hash flag needed for the distribution method \"mh\"\n\t\t\tif proxier.ipvsScheduler == \"mh\" {\n\t\t\t\tserv.Flags |= utilipvs.FlagSourceHash\n\t\t\t}\n\t\t\t// We must not add the address to the dummy device if it exist on another interface\n\t\t\tshouldBind := !nodeAddressSet.Has(serv.Address.String())\n\t\t\tif err := proxier.syncService(svcPortNameString, serv, shouldBind, alreadyBoundAddrs); err == nil {\n\t\t\t\tactiveIPVSServices.Insert(serv.String())\n\t\t\t\tif shouldBind {\n\t\t\t\t\tactiveBindAddrs.Insert(serv.Address.String())\n\t\t\t\t}\n\t\t\t\tif err := proxier.syncEndpoint(svcPortName, svcInfo.ExternalPolicyLocal(), serv); err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"Failed to sync endpoint for service\", \"servicePortName\", svcPortName, \"virtualServer\", serv)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tklog.ErrorS(err, \"Failed to sync service\", \"servicePortName\", svcPortName, \"virtualServer\", serv)\n\t\t\t}\n\t\t}\n\n\t\t// Capture load-balancer ingress.\n\t\tfor _, ingress := range svcInfo.LoadBalancerIPStrings() {\n\t\t\t// ipset call\n\t\t\tentry = \u0026utilipset.Entry{\n\t\t\t\tIP: ingress,\n\t\t\t\tPort: svcInfo.Port(),\n\t\t\t\tProtocol: protocol,\n\t\t\t\tSetType: utilipset.HashIPPort,\n\t\t\t}\n\t\t\t// add service load balancer ingressIP:Port to kubeServiceAccess ip set for the purpose of solving hairpin.\n\t\t\t// proxier.kubeServiceAccessSet.activeEntries.Insert(entry.String())\n\t\t\t// If we are proxying globally, we need to masquerade in case we cross nodes.\n\t\t\t// If we are proxying only locally, we can retain the source IP.\n\t\t\tif valid := proxier.ipsetList[kubeLoadBalancerSet].validateEntry(entry); !valid {\n\t\t\t\tklog.ErrorS(nil, \"Error adding entry to ipset\", \"entry\", entry, \"ipset\", proxier.ipsetList[kubeLoadBalancerSet].Name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tproxier.ipsetList[kubeLoadBalancerSet].activeEntries.Insert(entry.String())\n\t\t\t// insert loadbalancer entry to lbIngressLocalSet if service externaltrafficpolicy=local\n\t\t\tif svcInfo.ExternalPolicyLocal() {\n\t\t\t\tif valid := proxier.ipsetList[kubeLoadBalancerLocalSet].validateEntry(entry); !valid {\n\t\t\t\t\tklog.ErrorS(nil, \"Error adding entry to ipset\", \"entry\", entry, \"ipset\", proxier.ipsetList[kubeLoadBalancerLocalSet].Name)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tproxier.ipsetList[kubeLoadBalancerLocalSet].activeEntries.Insert(entry.String())\n\t\t\t}\n\t\t\tif len(svcInfo.LoadBalancerSourceRanges()) != 0 {\n\t\t\t\t// The service firewall rules are created based on ServiceSpec.loadBalancerSourceRanges field.\n\t\t\t\t// This currently works for loadbalancers that preserves source ips.\n\t\t\t\t// For loadbalancers which direct traffic to service NodePort, the firewall rules will not apply.\n\t\t\t\tif valid := proxier.ipsetList[kubeLoadBalancerFWSet].validateEntry(entry); !valid {\n\t\t\t\t\tklog.ErrorS(nil, \"Error adding entry to ipset\", \"entry\", entry, \"ipset\", proxier.ipsetList[kubeLoadBalancerFWSet].Name)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tproxier.ipsetList[kubeLoadBalancerFWSet].activeEntries.Insert(entry.String())\n\t\t\t\tallowFromNode := false\n\t\t\t\tfor _, src := range svcInfo.LoadBalancerSourceRanges() {\n\t\t\t\t\t// ipset call\n\t\t\t\t\tentry = \u0026utilipset.Entry{\n\t\t\t\t\t\tIP: ingress,\n\t\t\t\t\t\tPort: svcInfo.Port(),\n\t\t\t\t\t\tProtocol: protocol,\n\t\t\t\t\t\tNet: src,\n\t\t\t\t\t\tSetType: utilipset.HashIPPortNet,\n\t\t\t\t\t}\n\t\t\t\t\t// enumerate all white list source cidr\n\t\t\t\t\tif valid := proxier.ipsetList[kubeLoadBalancerSourceCIDRSet].validateEntry(entry); !valid {\n\t\t\t\t\t\tklog.ErrorS(nil, \"Error adding entry to ipset\", \"entry\", entry, \"ipset\", proxier.ipsetList[kubeLoadBalancerSourceCIDRSet].Name)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tproxier.ipsetList[kubeLoadBalancerSourceCIDRSet].activeEntries.Insert(entry.String())\n\n\t\t\t\t\t// ignore error because it has been validated\n\t\t\t\t\t_, cidr, _ := netutils.ParseCIDRSloppy(src)\n\t\t\t\t\tif cidr.Contains(proxier.nodeIP) {\n\t\t\t\t\t\tallowFromNode = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// generally, ip route rule was added to intercept request to loadbalancer vip from the\n\t\t\t\t// loadbalancer's backend hosts. In this case, request will not hit the loadbalancer but loop back directly.\n\t\t\t\t// Need to add the following rule to allow request on host.\n\t\t\t\tif allowFromNode {\n\t\t\t\t\tentry = \u0026utilipset.Entry{\n\t\t\t\t\t\tIP: ingress,\n\t\t\t\t\t\tPort: svcInfo.Port(),\n\t\t\t\t\t\tProtocol: protocol,\n\t\t\t\t\t\tIP2: ingress,\n\t\t\t\t\t\tSetType: utilipset.HashIPPortIP,\n\t\t\t\t\t}\n\t\t\t\t\t// enumerate all white list source ip\n\t\t\t\t\tif valid := proxier.ipsetList[kubeLoadBalancerSourceIPSet].validateEntry(entry); !valid {\n\t\t\t\t\t\tklog.ErrorS(nil, \"Error adding entry to ipset\", \"entry\", entry, \"ipset\", proxier.ipsetList[kubeLoadBalancerSourceIPSet].Name)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tproxier.ipsetList[kubeLoadBalancerSourceIPSet].activeEntries.Insert(entry.String())\n\t\t\t\t}\n\t\t\t}\n\t\t\t// ipvs call\n\t\t\tserv := \u0026utilipvs.VirtualServer{\n\t\t\t\tAddress: netutils.ParseIPSloppy(ingress),\n\t\t\t\tPort: uint16(svcInfo.Port()),\n\t\t\t\tProtocol: string(svcInfo.Protocol()),\n\t\t\t\tScheduler: proxier.ipvsScheduler,\n\t\t\t}\n\t\t\tif svcInfo.SessionAffinityType() == v1.ServiceAffinityClientIP {\n\t\t\t\tserv.Flags |= utilipvs.FlagPersistent\n\t\t\t\tserv.Timeout = uint32(svcInfo.StickyMaxAgeSeconds())\n\t\t\t}\n\t\t\t// Set the source hash flag needed for the distribution method \"mh\"\n\t\t\tif proxier.ipvsScheduler == \"mh\" {\n\t\t\t\tserv.Flags |= utilipvs.FlagSourceHash\n\t\t\t}\n\t\t\t// We must not add the address to the dummy device if it exist on another interface\n\t\t\tshouldBind := !nodeAddressSet.Has(serv.Address.String())\n\t\t\tif err := proxier.syncService(svcPortNameString, serv, shouldBind, alreadyBoundAddrs); err == nil {\n\t\t\t\tactiveIPVSServices.Insert(serv.String())\n\t\t\t\tif shouldBind {\n\t\t\t\t\tactiveBindAddrs.Insert(serv.Address.String())\n\t\t\t\t}\n\t\t\t\tif err := proxier.syncEndpoint(svcPortName, svcInfo.ExternalPolicyLocal(), serv); err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"Failed to sync endpoint for service\", \"servicePortName\", svcPortName, \"virtualServer\", serv)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tklog.ErrorS(err, \"Failed to sync service\", \"servicePortName\", svcPortName, \"virtualServer\", serv)\n\t\t\t}\n\t\t}\n\n\t\tif svcInfo.NodePort() != 0 {\n\t\t\tif len(nodeAddresses) == 0 || len(nodeIPs) == 0 {\n\t\t\t\t// Skip nodePort configuration since an error occurred when\n\t\t\t\t// computing nodeAddresses or nodeIPs.\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Nodeports need SNAT, unless they're local.\n\t\t\t// ipset call\n\n\t\t\tvar (\n\t\t\t\tnodePortSet *IPSet\n\t\t\t\tentries []*utilipset.Entry\n\t\t\t)\n\n\t\t\tswitch protocol {\n\t\t\tcase utilipset.ProtocolTCP:\n\t\t\t\tnodePortSet = proxier.ipsetList[kubeNodePortSetTCP]\n\t\t\t\tentries = []*utilipset.Entry{{\n\t\t\t\t\t// No need to provide ip info\n\t\t\t\t\tPort: svcInfo.NodePort(),\n\t\t\t\t\tProtocol: protocol,\n\t\t\t\t\tSetType: utilipset.BitmapPort,\n\t\t\t\t}}\n\t\t\tcase utilipset.ProtocolUDP:\n\t\t\t\tnodePortSet = proxier.ipsetList[kubeNodePortSetUDP]\n\t\t\t\tentries = []*utilipset.Entry{{\n\t\t\t\t\t// No need to provide ip info\n\t\t\t\t\tPort: svcInfo.NodePort(),\n\t\t\t\t\tProtocol: protocol,\n\t\t\t\t\tSetType: utilipset.BitmapPort,\n\t\t\t\t}}\n\t\t\tcase utilipset.ProtocolSCTP:\n\t\t\t\tnodePortSet = proxier.ipsetList[kubeNodePortSetSCTP]\n\t\t\t\t// Since hash ip:port is used for SCTP, all the nodeIPs to be used in the SCTP ipset entries.\n\t\t\t\tentries = []*utilipset.Entry{}\n\t\t\t\tfor _, nodeIP := range nodeIPs {\n\t\t\t\t\tentries = append(entries, \u0026utilipset.Entry{\n\t\t\t\t\t\tIP: nodeIP.String(),\n\t\t\t\t\t\tPort: svcInfo.NodePort(),\n\t\t\t\t\t\tProtocol: protocol,\n\t\t\t\t\t\tSetType: utilipset.HashIPPort,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\t// It should never hit\n\t\t\t\tklog.ErrorS(nil, \"Unsupported protocol type\", \"protocol\", protocol)\n\t\t\t}\n\t\t\tif nodePortSet != nil {\n\t\t\t\tentryInvalidErr := false\n\t\t\t\tfor _, entry := range entries {\n\t\t\t\t\tif valid := nodePortSet.validateEntry(entry); !valid {\n\t\t\t\t\t\tklog.ErrorS(nil, \"Error adding entry to ipset\", \"entry\", entry, \"ipset\", nodePortSet.Name)\n\t\t\t\t\t\tentryInvalidErr = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tnodePortSet.activeEntries.Insert(entry.String())\n\t\t\t\t}\n\t\t\t\tif entryInvalidErr {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Add externaltrafficpolicy=local type nodeport entry\n\t\t\tif svcInfo.ExternalPolicyLocal() {\n\t\t\t\tvar nodePortLocalSet *IPSet\n\t\t\t\tswitch protocol {\n\t\t\t\tcase utilipset.ProtocolTCP:\n\t\t\t\t\tnodePortLocalSet = proxier.ipsetList[kubeNodePortLocalSetTCP]\n\t\t\t\tcase utilipset.ProtocolUDP:\n\t\t\t\t\tnodePortLocalSet = proxier.ipsetList[kubeNodePortLocalSetUDP]\n\t\t\t\tcase utilipset.ProtocolSCTP:\n\t\t\t\t\tnodePortLocalSet = proxier.ipsetList[kubeNodePortLocalSetSCTP]\n\t\t\t\tdefault:\n\t\t\t\t\t// It should never hit\n\t\t\t\t\tklog.ErrorS(nil, \"Unsupported protocol type\", \"protocol\", protocol)\n\t\t\t\t}\n\t\t\t\tif nodePortLocalSet != nil {\n\t\t\t\t\tentryInvalidErr := false\n\t\t\t\t\tfor _, entry := range entries {\n\t\t\t\t\t\tif valid := nodePortLocalSet.validateEntry(entry); !valid {\n\t\t\t\t\t\t\tklog.ErrorS(nil, \"Error adding entry to ipset\", \"entry\", entry, \"ipset\", nodePortLocalSet.Name)\n\t\t\t\t\t\t\tentryInvalidErr = true\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnodePortLocalSet.activeEntries.Insert(entry.String())\n\t\t\t\t\t}\n\t\t\t\t\tif entryInvalidErr {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Build ipvs kernel routes for each node ip address\n\t\t\tfor _, nodeIP := range nodeIPs {\n\t\t\t\t// ipvs call\n\t\t\t\tserv := \u0026utilipvs.VirtualServer{\n\t\t\t\t\tAddress: nodeIP,\n\t\t\t\t\tPort: uint16(svcInfo.NodePort()),\n\t\t\t\t\tProtocol: string(svcInfo.Protocol()),\n\t\t\t\t\tScheduler: proxier.ipvsScheduler,\n\t\t\t\t}\n\t\t\t\tif svcInfo.SessionAffinityType() == v1.ServiceAffinityClientIP {\n\t\t\t\t\tserv.Flags |= utilipvs.FlagPersistent\n\t\t\t\t\tserv.Timeout = uint32(svcInfo.StickyMaxAgeSeconds())\n\t\t\t\t}\n\t\t\t\t// Set the source hash flag needed for the distribution method \"mh\"\n\t\t\t\tif proxier.ipvsScheduler == \"mh\" {\n\t\t\t\t\tserv.Flags |= utilipvs.FlagSourceHash\n\t\t\t\t}\n\t\t\t\t// There is no need to bind Node IP to dummy interface, so set parameter `bindAddr` to `false`.\n\t\t\t\tif err := proxier.syncService(svcPortNameString, serv, false, alreadyBoundAddrs); err == nil {\n\t\t\t\t\tactiveIPVSServices.Insert(serv.String())\n\t\t\t\t\tif err := proxier.syncEndpoint(svcPortName, svcInfo.ExternalPolicyLocal(), serv); err != nil {\n\t\t\t\t\t\tklog.ErrorS(err, \"Failed to sync endpoint for service\", \"servicePortName\", svcPortName, \"virtualServer\", serv)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tklog.ErrorS(err, \"Failed to sync service\", \"servicePortName\", svcPortName, \"virtualServer\", serv)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif svcInfo.HealthCheckNodePort() != 0 {\n\t\t\tnodePortSet := proxier.ipsetList[kubeHealthCheckNodePortSet]\n\t\t\tentry := \u0026utilipset.Entry{\n\t\t\t\t// No need to provide ip info\n\t\t\t\tPort: svcInfo.HealthCheckNodePort(),\n\t\t\t\tProtocol: \"tcp\",\n\t\t\t\tSetType: utilipset.BitmapPort,\n\t\t\t}\n\n\t\t\tif valid := nodePortSet.validateEntry(entry); !valid {\n\t\t\t\tklog.ErrorS(nil, \"Error adding entry to ipset\", \"entry\", entry, \"ipset\", nodePortSet.Name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnodePortSet.activeEntries.Insert(entry.String())\n\t\t}\n\t}\n\n\t// Set the KUBE-IPVS-IPS set to the \"activeBindAddrs\"\n\tproxier.ipsetList[kubeIPVSSet].activeEntries = activeBindAddrs\n\n\t// sync ipset entries\n\tfor _, set := range proxier.ipsetList {\n\t\tset.syncIPSetEntries()\n\t}\n\n\t// Tail call iptables rules for ipset, make sure only call iptables once\n\t// in a single loop per ip set.\n\tproxier.writeIptablesRules()\n\n\t// Sync iptables rules.\n\t// NOTE: NoFlushTables is used so we don't flush non-kubernetes chains in the table.\n\tproxier.iptablesData.Reset()\n\tproxier.iptablesData.Write(proxier.natChains.Bytes())\n\tproxier.iptablesData.Write(proxier.natRules.Bytes())\n\tproxier.iptablesData.Write(proxier.filterChains.Bytes())\n\tproxier.iptablesData.Write(proxier.filterRules.Bytes())\n\n\tklog.V(5).InfoS(\"Restoring iptables\", \"rules\", proxier.iptablesData.Bytes())\n\terr = proxier.iptables.RestoreAll(proxier.iptablesData.Bytes(), utiliptables.NoFlushTables, utiliptables.RestoreCounters)\n\tif err != nil {\n\t\tif pErr, ok := err.(utiliptables.ParseError); ok {\n\t\t\tlines := utiliptables.ExtractLines(proxier.iptablesData.Bytes(), pErr.Line(), 3)\n\t\t\tklog.ErrorS(pErr, \"Failed to execute iptables-restore\", \"rules\", lines)\n\t\t} else {\n\t\t\tklog.ErrorS(err, \"Failed to execute iptables-restore\", \"rules\", proxier.iptablesData.Bytes())\n\t\t}\n\t\tmetrics.IptablesRestoreFailuresTotal.Inc()\n\t\treturn\n\t}\n\tfor name, lastChangeTriggerTimes := range endpointUpdateResult.LastChangeTriggerTimes {\n\t\tfor _, lastChangeTriggerTime := range lastChangeTriggerTimes {\n\t\t\tlatency := metrics.SinceInSeconds(lastChangeTriggerTime)\n\t\t\tmetrics.NetworkProgrammingLatency.Observe(latency)\n\t\t\tklog.V(4).InfoS(\"Network programming\", \"endpoint\", klog.KRef(name.Namespace, name.Name), \"elapsed\", latency)\n\t\t}\n\t}\n\n\t// Remove superfluous addresses from the dummy device\n\tsuperfluousAddresses := alreadyBoundAddrs.Difference(activeBindAddrs)\n\tif superfluousAddresses.Len() \u003e 0 {\n\t\tklog.V(2).InfoS(\"Removing addresses\", \"interface\", defaultDummyDevice, \"addresses\", superfluousAddresses)\n\t\tfor adr := range superfluousAddresses {\n\t\t\tif err := proxier.netlinkHandle.UnbindAddress(adr, defaultDummyDevice); err != nil {\n\t\t\t\tklog.ErrorS(err, \"UnbindAddress\", \"interface\", defaultDummyDevice, \"address\", adr)\n\t\t\t}\n\t\t}\n\t}\n\n\t// currentIPVSServices represent IPVS services listed from the system\n\t// (including any we have created in this sync)\n\tcurrentIPVSServices := make(map[string]*utilipvs.VirtualServer)\n\tappliedSvcs, err := proxier.ipvs.GetVirtualServers()\n\tif err == nil {\n\t\tfor _, appliedSvc := range appliedSvcs {\n\t\t\tcurrentIPVSServices[appliedSvc.String()] = appliedSvc\n\t\t}\n\t} else {\n\t\tklog.ErrorS(err, \"Failed to get ipvs service\")\n\t}\n\tproxier.cleanLegacyService(activeIPVSServices, currentIPVSServices)\n\n\tif proxier.healthzServer != nil {\n\t\tproxier.healthzServer.Updated()\n\t}\n\tmetrics.SyncProxyRulesLastTimestamp.SetToCurrentTime()\n\n\t// Update service healthchecks. The endpoints list might include services that are\n\t// not \"OnlyLocal\", but the services list will not, and the serviceHealthServer\n\t// will just drop those endpoints.\n\tif err := proxier.serviceHealthServer.SyncServices(proxier.svcPortMap.HealthCheckNodePorts()); err != nil {\n\t\tklog.ErrorS(err, \"Error syncing healthcheck services\")\n\t}\n\tif err := proxier.serviceHealthServer.SyncEndpoints(proxier.endpointsMap.LocalReadyEndpoints()); err != nil {\n\t\tklog.ErrorS(err, \"Error syncing healthcheck endpoints\")\n\t}\n\n\tmetrics.SyncProxyRulesNoLocalEndpointsTotal.WithLabelValues(\"internal\").Set(float64(proxier.serviceNoLocalEndpointsInternal.Len()))\n\tmetrics.SyncProxyRulesNoLocalEndpointsTotal.WithLabelValues(\"external\").Set(float64(proxier.serviceNoLocalEndpointsExternal.Len()))\n\n\t// Finish housekeeping.\n\t// Clear stale conntrack entries for UDP Services, this has to be done AFTER the ipvs rules are programmed.\n\t// TODO: these could be made more consistent.\n\tklog.V(4).InfoS(\"Deleting conntrack stale entries for services\", \"IPs\", conntrackCleanupServiceIPs.UnsortedList())\n\tfor _, svcIP := range conntrackCleanupServiceIPs.UnsortedList() {\n\t\tif err := conntrack.ClearEntriesForIP(proxier.exec, svcIP, v1.ProtocolUDP); err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to delete stale service connections\", \"IP\", svcIP)\n\t\t}\n\t}\n\tklog.V(4).InfoS(\"Deleting conntrack stale entries for services\", \"nodePorts\", conntrackCleanupServiceNodePorts.UnsortedList())\n\tfor _, nodePort := range conntrackCleanupServiceNodePorts.UnsortedList() {\n\t\terr := conntrack.ClearEntriesForPort(proxier.exec, nodePort, proxier.ipFamily == v1.IPv6Protocol, v1.ProtocolUDP)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to clear udp conntrack\", \"nodePort\", nodePort)\n\t\t}\n\t}\n\tklog.V(4).InfoS(\"Deleting stale endpoint connections\", \"endpoints\", endpointUpdateResult.DeletedUDPEndpoints)\n\tproxier.deleteUDPEndpointConnections(endpointUpdateResult.DeletedUDPEndpoints)\n}","line":{"from":919,"to":1556}} {"id":100008553,"name":"writeIptablesRules","signature":"func (proxier *Proxier) writeIptablesRules()","file":"pkg/proxy/ipvs/proxier.go","code":"// writeIptablesRules write all iptables rules to proxier.natRules or proxier.FilterRules that ipvs proxier needed\n// according to proxier.ipsetList information and the ipset match relationship that `ipsetWithIptablesChain` specified.\n// some ipset(kubeClusterIPSet for example) have particular match rules and iptables jump relation should be sync separately.\nfunc (proxier *Proxier) writeIptablesRules() {\n\n\t// Dismiss connects to localhost early in the service chain\n\tloAddr := \"127.0.0.0/8\"\n\tif proxier.ipFamily == v1.IPv6Protocol {\n\t\tloAddr = \"::1/128\"\n\t}\n\tproxier.natRules.Write(\"-A\", string(kubeServicesChain), \"-s\", loAddr, \"-j\", \"RETURN\")\n\n\t// We are creating those slices ones here to avoid memory reallocations\n\t// in every loop. Note that reuse the memory, instead of doing:\n\t// slice = \u003csome new slice\u003e\n\t// you should always do one of the below:\n\t// slice = slice[:0] // and then append to it\n\t// slice = append(slice[:0], ...)\n\t// To avoid growing this slice, we arbitrarily set its size to 64,\n\t// there is never more than that many arguments for a single line.\n\t// Note that even if we go over 64, it will still be correct - it\n\t// is just for efficiency, not correctness.\n\targs := make([]string, 64)\n\n\tfor _, set := range ipsetWithIptablesChain {\n\t\tif _, find := proxier.ipsetList[set.name]; find \u0026\u0026 !proxier.ipsetList[set.name].isEmpty() {\n\t\t\targs = append(args[:0], \"-A\", set.from)\n\t\t\tif set.protocolMatch != \"\" {\n\t\t\t\targs = append(args, \"-p\", set.protocolMatch)\n\t\t\t}\n\t\t\targs = append(args,\n\t\t\t\t\"-m\", \"comment\", \"--comment\", proxier.ipsetList[set.name].getComment(),\n\t\t\t\t\"-m\", \"set\", \"--match-set\", proxier.ipsetList[set.name].Name,\n\t\t\t\tset.matchType,\n\t\t\t)\n\t\t\tif set.table == utiliptables.TableFilter {\n\t\t\t\tproxier.filterRules.Write(args, \"-j\", set.to)\n\t\t\t} else {\n\t\t\t\tproxier.natRules.Write(args, \"-j\", set.to)\n\t\t\t}\n\t\t}\n\t}\n\n\tif !proxier.ipsetList[kubeClusterIPSet].isEmpty() {\n\t\targs = append(args[:0],\n\t\t\t\"-A\", string(kubeServicesChain),\n\t\t\t\"-m\", \"comment\", \"--comment\", proxier.ipsetList[kubeClusterIPSet].getComment(),\n\t\t\t\"-m\", \"set\", \"--match-set\", proxier.ipsetList[kubeClusterIPSet].Name,\n\t\t)\n\t\tif proxier.masqueradeAll {\n\t\t\tproxier.natRules.Write(\n\t\t\t\targs, \"dst,dst\",\n\t\t\t\t\"-j\", string(kubeMarkMasqChain))\n\t\t} else if proxier.localDetector.IsImplemented() {\n\t\t\t// This masquerades off-cluster traffic to a service VIP. The idea\n\t\t\t// is that you can establish a static route for your Service range,\n\t\t\t// routing to any node, and that node will bridge into the Service\n\t\t\t// for you. Since that might bounce off-node, we masquerade here.\n\t\t\t// If/when we support \"Local\" policy for VIPs, we should update this.\n\t\t\tproxier.natRules.Write(\n\t\t\t\targs, \"dst,dst\",\n\t\t\t\tproxier.localDetector.IfNotLocal(),\n\t\t\t\t\"-j\", string(kubeMarkMasqChain))\n\t\t} else {\n\t\t\t// Masquerade all OUTPUT traffic coming from a service ip.\n\t\t\t// The kube dummy interface has all service VIPs assigned which\n\t\t\t// results in the service VIP being picked as the source IP to reach\n\t\t\t// a VIP. This leads to a connection from VIP:\u003crandom port\u003e to\n\t\t\t// VIP:\u003cservice port\u003e.\n\t\t\t// Always masquerading OUTPUT (node-originating) traffic with a VIP\n\t\t\t// source ip and service port destination fixes the outgoing connections.\n\t\t\tproxier.natRules.Write(\n\t\t\t\targs, \"src,dst\",\n\t\t\t\t\"-j\", string(kubeMarkMasqChain))\n\t\t}\n\t}\n\n\t// externalIPRules adds iptables rules applies to Service ExternalIPs\n\texternalIPRules := func(args []string) {\n\t\t// Allow traffic for external IPs that does not come from a bridge (i.e. not from a container)\n\t\t// nor from a local process to be forwarded to the service.\n\t\t// This rule roughly translates to \"all traffic from off-machine\".\n\t\t// This is imperfect in the face of network plugins that might not use a bridge, but we can revisit that later.\n\t\texternalTrafficOnlyArgs := append(args,\n\t\t\t\"-m\", \"physdev\", \"!\", \"--physdev-is-in\",\n\t\t\t\"-m\", \"addrtype\", \"!\", \"--src-type\", \"LOCAL\")\n\t\tproxier.natRules.Write(externalTrafficOnlyArgs, \"-j\", \"ACCEPT\")\n\t\tdstLocalOnlyArgs := append(args, \"-m\", \"addrtype\", \"--dst-type\", \"LOCAL\")\n\t\t// Allow traffic bound for external IPs that happen to be recognized as local IPs to stay local.\n\t\t// This covers cases like GCE load-balancers which get added to the local routing table.\n\t\tproxier.natRules.Write(dstLocalOnlyArgs, \"-j\", \"ACCEPT\")\n\t}\n\n\tif !proxier.ipsetList[kubeExternalIPSet].isEmpty() {\n\t\t// Build masquerade rules for packets to external IPs.\n\t\targs = append(args[:0],\n\t\t\t\"-A\", string(kubeServicesChain),\n\t\t\t\"-m\", \"comment\", \"--comment\", proxier.ipsetList[kubeExternalIPSet].getComment(),\n\t\t\t\"-m\", \"set\", \"--match-set\", proxier.ipsetList[kubeExternalIPSet].Name,\n\t\t\t\"dst,dst\",\n\t\t)\n\t\tproxier.natRules.Write(args, \"-j\", string(kubeMarkMasqChain))\n\t\texternalIPRules(args)\n\t}\n\n\tif !proxier.ipsetList[kubeExternalIPLocalSet].isEmpty() {\n\t\targs = append(args[:0],\n\t\t\t\"-A\", string(kubeServicesChain),\n\t\t\t\"-m\", \"comment\", \"--comment\", proxier.ipsetList[kubeExternalIPLocalSet].getComment(),\n\t\t\t\"-m\", \"set\", \"--match-set\", proxier.ipsetList[kubeExternalIPLocalSet].Name,\n\t\t\t\"dst,dst\",\n\t\t)\n\t\texternalIPRules(args)\n\t}\n\n\t// -A KUBE-SERVICES -m addrtype --dst-type LOCAL -j KUBE-NODE-PORT\n\targs = append(args[:0],\n\t\t\"-A\", string(kubeServicesChain),\n\t\t\"-m\", \"addrtype\", \"--dst-type\", \"LOCAL\",\n\t)\n\tproxier.natRules.Write(args, \"-j\", string(kubeNodePortChain))\n\n\t// mark for masquerading for KUBE-LOAD-BALANCER\n\tproxier.natRules.Write(\n\t\t\"-A\", string(kubeLoadBalancerChain),\n\t\t\"-j\", string(kubeMarkMasqChain),\n\t)\n\n\t// drop packets filtered by KUBE-SOURCE-RANGES-FIREWALL\n\tproxier.filterRules.Write(\n\t\t\"-A\", string(kubeSourceRangesFirewallChain),\n\t\t\"-j\", \"DROP\",\n\t)\n\n\t// Accept all traffic with destination of ipvs virtual service, in case other iptables rules\n\t// block the traffic, that may result in ipvs rules invalid.\n\t// Those rules must be in the end of KUBE-SERVICE chain\n\tproxier.acceptIPVSTraffic()\n\n\t// If the masqueradeMark has been added then we want to forward that same\n\t// traffic, this allows NodePort traffic to be forwarded even if the default\n\t// FORWARD policy is not accept.\n\tproxier.filterRules.Write(\n\t\t\"-A\", string(kubeForwardChain),\n\t\t\"-m\", \"comment\", \"--comment\", `\"kubernetes forwarding rules\"`,\n\t\t\"-m\", \"mark\", \"--mark\", fmt.Sprintf(\"%s/%s\", proxier.masqueradeMark, proxier.masqueradeMark),\n\t\t\"-j\", \"ACCEPT\",\n\t)\n\n\t// The following rule ensures the traffic after the initial packet accepted\n\t// by the \"kubernetes forwarding rules\" rule above will be accepted.\n\tproxier.filterRules.Write(\n\t\t\"-A\", string(kubeForwardChain),\n\t\t\"-m\", \"comment\", \"--comment\", `\"kubernetes forwarding conntrack rule\"`,\n\t\t\"-m\", \"conntrack\",\n\t\t\"--ctstate\", \"RELATED,ESTABLISHED\",\n\t\t\"-j\", \"ACCEPT\",\n\t)\n\n\t// Add rule to accept traffic towards health check node port\n\tproxier.filterRules.Write(\n\t\t\"-A\", string(kubeNodePortChain),\n\t\t\"-m\", \"comment\", \"--comment\", proxier.ipsetList[kubeHealthCheckNodePortSet].getComment(),\n\t\t\"-m\", \"set\", \"--match-set\", proxier.ipsetList[kubeHealthCheckNodePortSet].Name, \"dst\",\n\t\t\"-j\", \"ACCEPT\",\n\t)\n\n\t// Add rules to the filter/KUBE-IPVS-FILTER chain to prevent access to ports on the host through VIP addresses.\n\t// https://github.com/kubernetes/kubernetes/issues/72236\n\tproxier.filterRules.Write(\n\t\t\"-A\", string(kubeIPVSFilterChain),\n\t\t\"-m\", \"set\", \"--match-set\", proxier.ipsetList[kubeLoadBalancerSet].Name, \"dst,dst\", \"-j\", \"RETURN\")\n\tproxier.filterRules.Write(\n\t\t\"-A\", string(kubeIPVSFilterChain),\n\t\t\"-m\", \"set\", \"--match-set\", proxier.ipsetList[kubeClusterIPSet].Name, \"dst,dst\", \"-j\", \"RETURN\")\n\tproxier.filterRules.Write(\n\t\t\"-A\", string(kubeIPVSFilterChain),\n\t\t\"-m\", \"set\", \"--match-set\", proxier.ipsetList[kubeExternalIPSet].Name, \"dst,dst\", \"-j\", \"RETURN\")\n\tproxier.filterRules.Write(\n\t\t\"-A\", string(kubeIPVSFilterChain),\n\t\t\"-m\", \"set\", \"--match-set\", proxier.ipsetList[kubeHealthCheckNodePortSet].Name, \"dst\", \"-j\", \"RETURN\")\n\tproxier.filterRules.Write(\n\t\t\"-A\", string(kubeIPVSFilterChain),\n\t\t\"-m\", \"conntrack\", \"--ctstate\", \"NEW\",\n\t\t\"-m\", \"set\", \"--match-set\", proxier.ipsetList[kubeIPVSSet].Name, \"dst\", \"-j\", \"REJECT\")\n\n\t// Install the kubernetes-specific postrouting rules. We use a whole chain for\n\t// this so that it is easier to flush and change, for example if the mark\n\t// value should ever change.\n\t// NB: THIS MUST MATCH the corresponding code in the kubelet\n\tproxier.natRules.Write(\n\t\t\"-A\", string(kubePostroutingChain),\n\t\t\"-m\", \"mark\", \"!\", \"--mark\", fmt.Sprintf(\"%s/%s\", proxier.masqueradeMark, proxier.masqueradeMark),\n\t\t\"-j\", \"RETURN\",\n\t)\n\t// Clear the mark to avoid re-masquerading if the packet re-traverses the network stack.\n\tproxier.natRules.Write(\n\t\t\"-A\", string(kubePostroutingChain),\n\t\t// XOR proxier.masqueradeMark to unset it\n\t\t\"-j\", \"MARK\", \"--xor-mark\", proxier.masqueradeMark,\n\t)\n\tmasqRule := []string{\n\t\t\"-A\", string(kubePostroutingChain),\n\t\t\"-m\", \"comment\", \"--comment\", `\"kubernetes service traffic requiring SNAT\"`,\n\t\t\"-j\", \"MASQUERADE\",\n\t}\n\tif proxier.iptables.HasRandomFully() {\n\t\tmasqRule = append(masqRule, \"--random-fully\")\n\t}\n\tproxier.natRules.Write(masqRule)\n\n\t// Install the kubernetes-specific masquerade mark rule. We use a whole chain for\n\t// this so that it is easier to flush and change, for example if the mark\n\t// value should ever change.\n\tproxier.natRules.Write(\n\t\t\"-A\", string(kubeMarkMasqChain),\n\t\t\"-j\", \"MARK\", \"--or-mark\", proxier.masqueradeMark,\n\t)\n\n\t// Write the end-of-table markers.\n\tproxier.filterRules.Write(\"COMMIT\")\n\tproxier.natRules.Write(\"COMMIT\")\n}","line":{"from":1558,"to":1780}} {"id":100008554,"name":"acceptIPVSTraffic","signature":"func (proxier *Proxier) acceptIPVSTraffic()","file":"pkg/proxy/ipvs/proxier.go","code":"func (proxier *Proxier) acceptIPVSTraffic() {\n\tsets := []string{kubeClusterIPSet, kubeLoadBalancerSet}\n\tfor _, set := range sets {\n\t\tvar matchType string\n\t\tif !proxier.ipsetList[set].isEmpty() {\n\t\t\tswitch proxier.ipsetList[set].SetType {\n\t\t\tcase utilipset.BitmapPort:\n\t\t\t\tmatchType = \"dst\"\n\t\t\tdefault:\n\t\t\t\tmatchType = \"dst,dst\"\n\t\t\t}\n\t\t\tproxier.natRules.Write(\n\t\t\t\t\"-A\", string(kubeServicesChain),\n\t\t\t\t\"-m\", \"set\", \"--match-set\", proxier.ipsetList[set].Name, matchType,\n\t\t\t\t\"-j\", \"ACCEPT\",\n\t\t\t)\n\t\t}\n\t}\n}","line":{"from":1782,"to":1800}} {"id":100008555,"name":"createAndLinkKubeChain","signature":"func (proxier *Proxier) createAndLinkKubeChain()","file":"pkg/proxy/ipvs/proxier.go","code":"// createAndLinkKubeChain create all kube chains that ipvs proxier need and write basic link.\nfunc (proxier *Proxier) createAndLinkKubeChain() {\n\tfor _, ch := range iptablesChains {\n\t\tif _, err := proxier.iptables.EnsureChain(ch.table, ch.chain); err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to ensure chain exists\", \"table\", ch.table, \"chain\", ch.chain)\n\t\t\treturn\n\t\t}\n\t\tif ch.table == utiliptables.TableNAT {\n\t\t\tproxier.natChains.Write(utiliptables.MakeChainLine(ch.chain))\n\t\t} else {\n\t\t\tproxier.filterChains.Write(utiliptables.MakeChainLine(ch.chain))\n\t\t}\n\t}\n\n\tfor _, jc := range iptablesJumpChain {\n\t\targs := []string{\"-m\", \"comment\", \"--comment\", jc.comment, \"-j\", string(jc.to)}\n\t\tif _, err := proxier.iptables.EnsureRule(utiliptables.Prepend, jc.table, jc.from, args...); err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to ensure chain jumps\", \"table\", jc.table, \"srcChain\", jc.from, \"dstChain\", jc.to)\n\t\t}\n\t}\n\n}","line":{"from":1802,"to":1823}} {"id":100008556,"name":"deleteUDPEndpointConnections","signature":"func (proxier *Proxier) deleteUDPEndpointConnections(deletedUDPEndpoints []proxy.ServiceEndpoint)","file":"pkg/proxy/ipvs/proxier.go","code":"// After a UDP endpoint has been removed, we must flush any pending conntrack entries to it, or else we\n// risk sending more traffic to it, all of which will be lost (because UDP).\n// This assumes the proxier mutex is held\n// TODO: move it to util\nfunc (proxier *Proxier) deleteUDPEndpointConnections(deletedUDPEndpoints []proxy.ServiceEndpoint) {\n\tfor _, epSvcPair := range deletedUDPEndpoints {\n\t\tif svcInfo, ok := proxier.svcPortMap[epSvcPair.ServicePortName]; ok {\n\t\t\tendpointIP := utilproxy.IPPart(epSvcPair.Endpoint)\n\t\t\tnodePort := svcInfo.NodePort()\n\t\t\tvar err error\n\t\t\tif nodePort != 0 {\n\t\t\t\terr = conntrack.ClearEntriesForPortNAT(proxier.exec, endpointIP, nodePort, v1.ProtocolUDP)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"Failed to delete nodeport-related endpoint connections\", \"servicePortName\", epSvcPair.ServicePortName)\n\t\t\t\t}\n\t\t\t}\n\t\t\terr = conntrack.ClearEntriesForNAT(proxier.exec, svcInfo.ClusterIP().String(), endpointIP, v1.ProtocolUDP)\n\t\t\tif err != nil {\n\t\t\t\tklog.ErrorS(err, \"Failed to delete endpoint connections\", \"servicePortName\", epSvcPair.ServicePortName)\n\t\t\t}\n\t\t\tfor _, extIP := range svcInfo.ExternalIPStrings() {\n\t\t\t\terr := conntrack.ClearEntriesForNAT(proxier.exec, extIP, endpointIP, v1.ProtocolUDP)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"Failed to delete endpoint connections for externalIP\", \"servicePortName\", epSvcPair.ServicePortName, \"externalIP\", extIP)\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, lbIP := range svcInfo.LoadBalancerIPStrings() {\n\t\t\t\terr := conntrack.ClearEntriesForNAT(proxier.exec, lbIP, endpointIP, v1.ProtocolUDP)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"Failed to delete endpoint connections for LoadBalancerIP\", \"servicePortName\", epSvcPair.ServicePortName, \"loadBalancerIP\", lbIP)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":1825,"to":1859}} {"id":100008557,"name":"syncService","signature":"func (proxier *Proxier) syncService(svcName string, vs *utilipvs.VirtualServer, bindAddr bool, alreadyBoundAddrs sets.Set[string]) error","file":"pkg/proxy/ipvs/proxier.go","code":"func (proxier *Proxier) syncService(svcName string, vs *utilipvs.VirtualServer, bindAddr bool, alreadyBoundAddrs sets.Set[string]) error {\n\tappliedVirtualServer, _ := proxier.ipvs.GetVirtualServer(vs)\n\tif appliedVirtualServer == nil || !appliedVirtualServer.Equal(vs) {\n\t\tif appliedVirtualServer == nil {\n\t\t\t// IPVS service is not found, create a new service\n\t\t\tklog.V(3).InfoS(\"Adding new service\", \"serviceName\", svcName, \"virtualServer\", vs)\n\t\t\tif err := proxier.ipvs.AddVirtualServer(vs); err != nil {\n\t\t\t\tklog.ErrorS(err, \"Failed to add IPVS service\", \"serviceName\", svcName)\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\t// IPVS service was changed, update the existing one\n\t\t\t// During updates, service VIP will not go down\n\t\t\tklog.V(3).InfoS(\"IPVS service was changed\", \"serviceName\", svcName)\n\t\t\tif err := proxier.ipvs.UpdateVirtualServer(vs); err != nil {\n\t\t\t\tklog.ErrorS(err, \"Failed to update IPVS service\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// bind service address to dummy interface\n\tif bindAddr {\n\t\t// always attempt to bind if alreadyBoundAddrs is nil,\n\t\t// otherwise check if it's already binded and return early\n\t\tif alreadyBoundAddrs != nil \u0026\u0026 alreadyBoundAddrs.Has(vs.Address.String()) {\n\t\t\treturn nil\n\t\t}\n\n\t\tklog.V(4).InfoS(\"Bind address\", \"address\", vs.Address)\n\t\t_, err := proxier.netlinkHandle.EnsureAddressBind(vs.Address.String(), defaultDummyDevice)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to bind service address to dummy device\", \"serviceName\", svcName)\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":1861,"to":1899}} {"id":100008558,"name":"syncEndpoint","signature":"func (proxier *Proxier) syncEndpoint(svcPortName proxy.ServicePortName, onlyNodeLocalEndpoints bool, vs *utilipvs.VirtualServer) error","file":"pkg/proxy/ipvs/proxier.go","code":"func (proxier *Proxier) syncEndpoint(svcPortName proxy.ServicePortName, onlyNodeLocalEndpoints bool, vs *utilipvs.VirtualServer) error {\n\tappliedVirtualServer, err := proxier.ipvs.GetVirtualServer(vs)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to get IPVS service\")\n\t\treturn err\n\t}\n\tif appliedVirtualServer == nil {\n\t\treturn errors.New(\"IPVS virtual service does not exist\")\n\t}\n\n\t// curEndpoints represents IPVS destinations listed from current system.\n\tcurEndpoints := sets.NewString()\n\tcurDests, err := proxier.ipvs.GetRealServers(appliedVirtualServer)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to list IPVS destinations\")\n\t\treturn err\n\t}\n\tfor _, des := range curDests {\n\t\tcurEndpoints.Insert(des.String())\n\t}\n\n\tendpoints := proxier.endpointsMap[svcPortName]\n\n\t// Filtering for topology aware endpoints. This function will only\n\t// filter endpoints if appropriate feature gates are enabled and the\n\t// Service does not have conflicting configuration such as\n\t// externalTrafficPolicy=Local.\n\tsvcInfo, ok := proxier.svcPortMap[svcPortName]\n\tif !ok {\n\t\tklog.InfoS(\"Unable to filter endpoints due to missing service info\", \"servicePortName\", svcPortName)\n\t} else {\n\t\tclusterEndpoints, localEndpoints, _, hasAnyEndpoints := proxy.CategorizeEndpoints(endpoints, svcInfo, proxier.nodeLabels)\n\t\tif onlyNodeLocalEndpoints {\n\t\t\tif len(localEndpoints) \u003e 0 {\n\t\t\t\tendpoints = localEndpoints\n\t\t\t} else {\n\t\t\t\t// https://github.com/kubernetes/kubernetes/pull/97081\n\t\t\t\t// Allow access from local PODs even if no local endpoints exist.\n\t\t\t\t// Traffic from an external source will be routed but the reply\n\t\t\t\t// will have the POD address and will be discarded.\n\t\t\t\tendpoints = clusterEndpoints\n\n\t\t\t\tif hasAnyEndpoints \u0026\u0026 svcInfo.InternalPolicyLocal() {\n\t\t\t\t\tproxier.serviceNoLocalEndpointsInternal.Insert(svcPortName.NamespacedName.String())\n\t\t\t\t}\n\n\t\t\t\tif hasAnyEndpoints \u0026\u0026 svcInfo.ExternalPolicyLocal() {\n\t\t\t\t\tproxier.serviceNoLocalEndpointsExternal.Insert(svcPortName.NamespacedName.String())\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tendpoints = clusterEndpoints\n\t\t}\n\t}\n\n\tnewEndpoints := sets.NewString()\n\tfor _, epInfo := range endpoints {\n\t\tnewEndpoints.Insert(epInfo.String())\n\t}\n\n\t// Create new endpoints\n\tfor _, ep := range newEndpoints.List() {\n\t\tip, port, err := net.SplitHostPort(ep)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to parse endpoint\", \"endpoint\", ep)\n\t\t\tcontinue\n\t\t}\n\t\tportNum, err := strconv.Atoi(port)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to parse endpoint port\", \"port\", port)\n\t\t\tcontinue\n\t\t}\n\n\t\tnewDest := \u0026utilipvs.RealServer{\n\t\t\tAddress: netutils.ParseIPSloppy(ip),\n\t\t\tPort: uint16(portNum),\n\t\t\tWeight: 1,\n\t\t}\n\n\t\tif curEndpoints.Has(ep) {\n\t\t\t// if we are syncing for the first time, loop through all current destinations and\n\t\t\t// reset their weight.\n\t\t\tif proxier.initialSync {\n\t\t\t\tfor _, dest := range curDests {\n\t\t\t\t\tif dest.Weight != newDest.Weight {\n\t\t\t\t\t\terr = proxier.ipvs.UpdateRealServer(appliedVirtualServer, newDest)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tklog.ErrorS(err, \"Failed to update destination\", \"newDest\", newDest)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// check if newEndpoint is in gracefulDelete list, if true, delete this ep immediately\n\t\t\tuniqueRS := GetUniqueRSName(vs, newDest)\n\t\t\tif !proxier.gracefuldeleteManager.InTerminationList(uniqueRS) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tklog.V(5).InfoS(\"new ep is in graceful delete list\", \"uniqueRealServer\", uniqueRS)\n\t\t\terr := proxier.gracefuldeleteManager.MoveRSOutofGracefulDeleteList(uniqueRS)\n\t\t\tif err != nil {\n\t\t\t\tklog.ErrorS(err, \"Failed to delete endpoint in gracefulDeleteQueue\", \"endpoint\", ep)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\terr = proxier.ipvs.AddRealServer(appliedVirtualServer, newDest)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to add destination\", \"newDest\", newDest)\n\t\t\tcontinue\n\t\t}\n\t}\n\n\t// Delete old endpoints\n\tfor _, ep := range curEndpoints.Difference(newEndpoints).UnsortedList() {\n\t\t// if curEndpoint is in gracefulDelete, skip\n\t\tuniqueRS := vs.String() + \"/\" + ep\n\t\tif proxier.gracefuldeleteManager.InTerminationList(uniqueRS) {\n\t\t\tcontinue\n\t\t}\n\t\tip, port, err := net.SplitHostPort(ep)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to parse endpoint\", \"endpoint\", ep)\n\t\t\tcontinue\n\t\t}\n\t\tportNum, err := strconv.Atoi(port)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to parse endpoint port\", \"port\", port)\n\t\t\tcontinue\n\t\t}\n\n\t\tdelDest := \u0026utilipvs.RealServer{\n\t\t\tAddress: netutils.ParseIPSloppy(ip),\n\t\t\tPort: uint16(portNum),\n\t\t}\n\n\t\tklog.V(5).InfoS(\"Using graceful delete\", \"uniqueRealServer\", uniqueRS)\n\t\terr = proxier.gracefuldeleteManager.GracefulDeleteRS(appliedVirtualServer, delDest)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to delete destination\", \"uniqueRealServer\", uniqueRS)\n\t\t\tcontinue\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":1901,"to":2044}} {"id":100008559,"name":"cleanLegacyService","signature":"func (proxier *Proxier) cleanLegacyService(activeServices sets.Set[string], currentServices map[string]*utilipvs.VirtualServer)","file":"pkg/proxy/ipvs/proxier.go","code":"func (proxier *Proxier) cleanLegacyService(activeServices sets.Set[string], currentServices map[string]*utilipvs.VirtualServer) {\n\tfor cs, svc := range currentServices {\n\t\tif proxier.isIPInExcludeCIDRs(svc.Address) {\n\t\t\tcontinue\n\t\t}\n\t\tif getIPFamily(svc.Address) != proxier.ipFamily {\n\t\t\t// Not our family\n\t\t\tcontinue\n\t\t}\n\t\tif !activeServices.Has(cs) {\n\t\t\tklog.V(4).InfoS(\"Delete service\", \"virtualServer\", svc)\n\t\t\tif err := proxier.ipvs.DeleteVirtualServer(svc); err != nil {\n\t\t\t\tklog.ErrorS(err, \"Failed to delete service\", \"virtualServer\", svc)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":2046,"to":2062}} {"id":100008560,"name":"isIPInExcludeCIDRs","signature":"func (proxier *Proxier) isIPInExcludeCIDRs(ip net.IP) bool","file":"pkg/proxy/ipvs/proxier.go","code":"func (proxier *Proxier) isIPInExcludeCIDRs(ip net.IP) bool {\n\t// make sure it does not fall within an excluded CIDR range.\n\tfor _, excludedCIDR := range proxier.excludeCIDRs {\n\t\tif excludedCIDR.Contains(ip) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":2064,"to":2072}} {"id":100008561,"name":"getIPFamily","signature":"func getIPFamily(ip net.IP) v1.IPFamily","file":"pkg/proxy/ipvs/proxier.go","code":"func getIPFamily(ip net.IP) v1.IPFamily {\n\tif netutils.IsIPv4(ip) {\n\t\treturn v1.IPv4Protocol\n\t}\n\treturn v1.IPv6Protocol\n}","line":{"from":2074,"to":2079}} {"id":100008562,"name":"newSafeIpset","signature":"func newSafeIpset(ipset ipset.Interface) ipset.Interface","file":"pkg/proxy/ipvs/safe_ipset.go","code":"func newSafeIpset(ipset ipset.Interface) ipset.Interface {\n\treturn \u0026safeIpset{\n\t\tipset: ipset,\n\t}\n}","line":{"from":30,"to":34}} {"id":100008563,"name":"FlushSet","signature":"func (s *safeIpset) FlushSet(set string) error","file":"pkg/proxy/ipvs/safe_ipset.go","code":"// FlushSet deletes all entries from a named set.\nfunc (s *safeIpset) FlushSet(set string) error {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\treturn s.ipset.FlushSet(set)\n}","line":{"from":36,"to":41}} {"id":100008564,"name":"DestroySet","signature":"func (s *safeIpset) DestroySet(set string) error","file":"pkg/proxy/ipvs/safe_ipset.go","code":"// DestroySet deletes a named set.\nfunc (s *safeIpset) DestroySet(set string) error {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\treturn s.ipset.DestroySet(set)\n}","line":{"from":43,"to":48}} {"id":100008565,"name":"DestroyAllSets","signature":"func (s *safeIpset) DestroyAllSets() error","file":"pkg/proxy/ipvs/safe_ipset.go","code":"// DestroyAllSets deletes all sets.\nfunc (s *safeIpset) DestroyAllSets() error {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\treturn s.ipset.DestroyAllSets()\n}","line":{"from":50,"to":55}} {"id":100008566,"name":"CreateSet","signature":"func (s *safeIpset) CreateSet(set *ipset.IPSet, ignoreExistErr bool) error","file":"pkg/proxy/ipvs/safe_ipset.go","code":"// CreateSet creates a new set. It will ignore error when the set already exists if ignoreExistErr=true.\nfunc (s *safeIpset) CreateSet(set *ipset.IPSet, ignoreExistErr bool) error {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\treturn s.ipset.CreateSet(set, ignoreExistErr)\n}","line":{"from":57,"to":62}} {"id":100008567,"name":"AddEntry","signature":"func (s *safeIpset) AddEntry(entry string, set *ipset.IPSet, ignoreExistErr bool) error","file":"pkg/proxy/ipvs/safe_ipset.go","code":"// AddEntry adds a new entry to the named set. It will ignore error when the entry already exists if ignoreExistErr=true.\nfunc (s *safeIpset) AddEntry(entry string, set *ipset.IPSet, ignoreExistErr bool) error {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\treturn s.ipset.AddEntry(entry, set, ignoreExistErr)\n}","line":{"from":64,"to":69}} {"id":100008568,"name":"DelEntry","signature":"func (s *safeIpset) DelEntry(entry string, set string) error","file":"pkg/proxy/ipvs/safe_ipset.go","code":"// DelEntry deletes one entry from the named set\nfunc (s *safeIpset) DelEntry(entry string, set string) error {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\treturn s.ipset.DelEntry(entry, set)\n}","line":{"from":71,"to":76}} {"id":100008569,"name":"TestEntry","signature":"func (s *safeIpset) TestEntry(entry string, set string) (bool, error)","file":"pkg/proxy/ipvs/safe_ipset.go","code":"// Test test if an entry exists in the named set\nfunc (s *safeIpset) TestEntry(entry string, set string) (bool, error) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\treturn s.ipset.TestEntry(entry, set)\n}","line":{"from":78,"to":83}} {"id":100008570,"name":"ListEntries","signature":"func (s *safeIpset) ListEntries(set string) ([]string, error)","file":"pkg/proxy/ipvs/safe_ipset.go","code":"// ListEntries lists all the entries from a named set\nfunc (s *safeIpset) ListEntries(set string) ([]string, error) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\treturn s.ipset.ListEntries(set)\n}","line":{"from":85,"to":90}} {"id":100008571,"name":"ListSets","signature":"func (s *safeIpset) ListSets() ([]string, error)","file":"pkg/proxy/ipvs/safe_ipset.go","code":"// ListSets list all set names from kernel\nfunc (s *safeIpset) ListSets() ([]string, error) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\treturn s.ipset.ListSets()\n}","line":{"from":92,"to":97}} {"id":100008572,"name":"GetVersion","signature":"func (s *safeIpset) GetVersion() (string, error)","file":"pkg/proxy/ipvs/safe_ipset.go","code":"// GetVersion returns the \"X.Y\" version string for ipset.\nfunc (s *safeIpset) GetVersion() (string, error) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\treturn s.ipset.GetVersion()\n}","line":{"from":99,"to":104}} {"id":100008573,"name":"NewMetaProxier","signature":"func NewMetaProxier(ipv4Proxier, ipv6Proxier proxy.Provider) proxy.Provider","file":"pkg/proxy/metaproxier/meta_proxier.go","code":"// NewMetaProxier returns a dual-stack \"meta-proxier\". Proxier API\n// calls will be dispatched to the ProxyProvider instances depending\n// on address family.\nfunc NewMetaProxier(ipv4Proxier, ipv6Proxier proxy.Provider) proxy.Provider {\n\treturn proxy.Provider(\u0026metaProxier{\n\t\tipv4Proxier: ipv4Proxier,\n\t\tipv6Proxier: ipv6Proxier,\n\t})\n}","line":{"from":36,"to":44}} {"id":100008574,"name":"Sync","signature":"func (proxier *metaProxier) Sync()","file":"pkg/proxy/metaproxier/meta_proxier.go","code":"// Sync immediately synchronizes the ProxyProvider's current state to\n// proxy rules.\nfunc (proxier *metaProxier) Sync() {\n\tproxier.ipv4Proxier.Sync()\n\tproxier.ipv6Proxier.Sync()\n}","line":{"from":46,"to":51}} {"id":100008575,"name":"SyncLoop","signature":"func (proxier *metaProxier) SyncLoop()","file":"pkg/proxy/metaproxier/meta_proxier.go","code":"// SyncLoop runs periodic work. This is expected to run as a\n// goroutine or as the main loop of the app. It does not return.\nfunc (proxier *metaProxier) SyncLoop() {\n\tgo proxier.ipv6Proxier.SyncLoop() // Use go-routine here!\n\tproxier.ipv4Proxier.SyncLoop() // never returns\n}","line":{"from":53,"to":58}} {"id":100008576,"name":"OnServiceAdd","signature":"func (proxier *metaProxier) OnServiceAdd(service *v1.Service)","file":"pkg/proxy/metaproxier/meta_proxier.go","code":"// OnServiceAdd is called whenever creation of new service object is observed.\nfunc (proxier *metaProxier) OnServiceAdd(service *v1.Service) {\n\tproxier.ipv4Proxier.OnServiceAdd(service)\n\tproxier.ipv6Proxier.OnServiceAdd(service)\n}","line":{"from":60,"to":64}} {"id":100008577,"name":"OnServiceUpdate","signature":"func (proxier *metaProxier) OnServiceUpdate(oldService, service *v1.Service)","file":"pkg/proxy/metaproxier/meta_proxier.go","code":"// OnServiceUpdate is called whenever modification of an existing\n// service object is observed.\nfunc (proxier *metaProxier) OnServiceUpdate(oldService, service *v1.Service) {\n\tproxier.ipv4Proxier.OnServiceUpdate(oldService, service)\n\tproxier.ipv6Proxier.OnServiceUpdate(oldService, service)\n}","line":{"from":66,"to":71}} {"id":100008578,"name":"OnServiceDelete","signature":"func (proxier *metaProxier) OnServiceDelete(service *v1.Service)","file":"pkg/proxy/metaproxier/meta_proxier.go","code":"// OnServiceDelete is called whenever deletion of an existing service\n// object is observed.\nfunc (proxier *metaProxier) OnServiceDelete(service *v1.Service) {\n\tproxier.ipv4Proxier.OnServiceDelete(service)\n\tproxier.ipv6Proxier.OnServiceDelete(service)\n\n}","line":{"from":73,"to":79}} {"id":100008579,"name":"OnServiceSynced","signature":"func (proxier *metaProxier) OnServiceSynced()","file":"pkg/proxy/metaproxier/meta_proxier.go","code":"// OnServiceSynced is called once all the initial event handlers were\n// called and the state is fully propagated to local cache.\nfunc (proxier *metaProxier) OnServiceSynced() {\n\tproxier.ipv4Proxier.OnServiceSynced()\n\tproxier.ipv6Proxier.OnServiceSynced()\n}","line":{"from":81,"to":86}} {"id":100008580,"name":"OnEndpointSliceAdd","signature":"func (proxier *metaProxier) OnEndpointSliceAdd(endpointSlice *discovery.EndpointSlice)","file":"pkg/proxy/metaproxier/meta_proxier.go","code":"// OnEndpointSliceAdd is called whenever creation of a new endpoint slice object\n// is observed.\nfunc (proxier *metaProxier) OnEndpointSliceAdd(endpointSlice *discovery.EndpointSlice) {\n\tswitch endpointSlice.AddressType {\n\tcase discovery.AddressTypeIPv4:\n\t\tproxier.ipv4Proxier.OnEndpointSliceAdd(endpointSlice)\n\tcase discovery.AddressTypeIPv6:\n\t\tproxier.ipv6Proxier.OnEndpointSliceAdd(endpointSlice)\n\tdefault:\n\t\tklog.ErrorS(nil, \"EndpointSlice address type not supported\", \"addressType\", endpointSlice.AddressType)\n\t}\n}","line":{"from":88,"to":99}} {"id":100008581,"name":"OnEndpointSliceUpdate","signature":"func (proxier *metaProxier) OnEndpointSliceUpdate(oldEndpointSlice, newEndpointSlice *discovery.EndpointSlice)","file":"pkg/proxy/metaproxier/meta_proxier.go","code":"// OnEndpointSliceUpdate is called whenever modification of an existing endpoint\n// slice object is observed.\nfunc (proxier *metaProxier) OnEndpointSliceUpdate(oldEndpointSlice, newEndpointSlice *discovery.EndpointSlice) {\n\tswitch newEndpointSlice.AddressType {\n\tcase discovery.AddressTypeIPv4:\n\t\tproxier.ipv4Proxier.OnEndpointSliceUpdate(oldEndpointSlice, newEndpointSlice)\n\tcase discovery.AddressTypeIPv6:\n\t\tproxier.ipv6Proxier.OnEndpointSliceUpdate(oldEndpointSlice, newEndpointSlice)\n\tdefault:\n\t\tklog.ErrorS(nil, \"EndpointSlice address type not supported\", \"addressType\", newEndpointSlice.AddressType)\n\t}\n}","line":{"from":101,"to":112}} {"id":100008582,"name":"OnEndpointSliceDelete","signature":"func (proxier *metaProxier) OnEndpointSliceDelete(endpointSlice *discovery.EndpointSlice)","file":"pkg/proxy/metaproxier/meta_proxier.go","code":"// OnEndpointSliceDelete is called whenever deletion of an existing endpoint slice\n// object is observed.\nfunc (proxier *metaProxier) OnEndpointSliceDelete(endpointSlice *discovery.EndpointSlice) {\n\tswitch endpointSlice.AddressType {\n\tcase discovery.AddressTypeIPv4:\n\t\tproxier.ipv4Proxier.OnEndpointSliceDelete(endpointSlice)\n\tcase discovery.AddressTypeIPv6:\n\t\tproxier.ipv6Proxier.OnEndpointSliceDelete(endpointSlice)\n\tdefault:\n\t\tklog.ErrorS(nil, \"EndpointSlice address type not supported\", \"addressType\", endpointSlice.AddressType)\n\t}\n}","line":{"from":114,"to":125}} {"id":100008583,"name":"OnEndpointSlicesSynced","signature":"func (proxier *metaProxier) OnEndpointSlicesSynced()","file":"pkg/proxy/metaproxier/meta_proxier.go","code":"// OnEndpointSlicesSynced is called once all the initial event handlers were\n// called and the state is fully propagated to local cache.\nfunc (proxier *metaProxier) OnEndpointSlicesSynced() {\n\tproxier.ipv4Proxier.OnEndpointSlicesSynced()\n\tproxier.ipv6Proxier.OnEndpointSlicesSynced()\n}","line":{"from":127,"to":132}} {"id":100008584,"name":"OnNodeAdd","signature":"func (proxier *metaProxier) OnNodeAdd(node *v1.Node)","file":"pkg/proxy/metaproxier/meta_proxier.go","code":"// OnNodeAdd is called whenever creation of new node object is observed.\nfunc (proxier *metaProxier) OnNodeAdd(node *v1.Node) {\n\tproxier.ipv4Proxier.OnNodeAdd(node)\n\tproxier.ipv6Proxier.OnNodeAdd(node)\n}","line":{"from":134,"to":138}} {"id":100008585,"name":"OnNodeUpdate","signature":"func (proxier *metaProxier) OnNodeUpdate(oldNode, node *v1.Node)","file":"pkg/proxy/metaproxier/meta_proxier.go","code":"// OnNodeUpdate is called whenever modification of an existing\n// node object is observed.\nfunc (proxier *metaProxier) OnNodeUpdate(oldNode, node *v1.Node) {\n\tproxier.ipv4Proxier.OnNodeUpdate(oldNode, node)\n\tproxier.ipv6Proxier.OnNodeUpdate(oldNode, node)\n}","line":{"from":140,"to":145}} {"id":100008586,"name":"OnNodeDelete","signature":"func (proxier *metaProxier) OnNodeDelete(node *v1.Node)","file":"pkg/proxy/metaproxier/meta_proxier.go","code":"// OnNodeDelete is called whenever deletion of an existing node\n// object is observed.\nfunc (proxier *metaProxier) OnNodeDelete(node *v1.Node) {\n\tproxier.ipv4Proxier.OnNodeDelete(node)\n\tproxier.ipv6Proxier.OnNodeDelete(node)\n\n}","line":{"from":147,"to":153}} {"id":100008587,"name":"OnNodeSynced","signature":"func (proxier *metaProxier) OnNodeSynced()","file":"pkg/proxy/metaproxier/meta_proxier.go","code":"// OnNodeSynced is called once all the initial event handlers were\n// called and the state is fully propagated to local cache.\nfunc (proxier *metaProxier) OnNodeSynced() {\n\tproxier.ipv4Proxier.OnNodeSynced()\n\tproxier.ipv6Proxier.OnNodeSynced()\n}","line":{"from":155,"to":160}} {"id":100008588,"name":"RegisterMetrics","signature":"func RegisterMetrics()","file":"pkg/proxy/metrics/metrics.go","code":"// RegisterMetrics registers kube-proxy metrics.\nfunc RegisterMetrics() {\n\tregisterMetricsOnce.Do(func() {\n\t\tlegacyregistry.MustRegister(SyncProxyRulesLatency)\n\t\tlegacyregistry.MustRegister(SyncProxyRulesLastTimestamp)\n\t\tlegacyregistry.MustRegister(NetworkProgrammingLatency)\n\t\tlegacyregistry.MustRegister(EndpointChangesPending)\n\t\tlegacyregistry.MustRegister(EndpointChangesTotal)\n\t\tlegacyregistry.MustRegister(ServiceChangesPending)\n\t\tlegacyregistry.MustRegister(ServiceChangesTotal)\n\t\tlegacyregistry.MustRegister(IptablesRulesTotal)\n\t\tlegacyregistry.MustRegister(IptablesRestoreFailuresTotal)\n\t\tlegacyregistry.MustRegister(IptablesPartialRestoreFailuresTotal)\n\t\tlegacyregistry.MustRegister(SyncProxyRulesLastQueuedTimestamp)\n\t\tlegacyregistry.MustRegister(SyncProxyRulesNoLocalEndpointsTotal)\n\t})\n}","line":{"from":179,"to":195}} {"id":100008589,"name":"SinceInSeconds","signature":"func SinceInSeconds(start time.Time) float64","file":"pkg/proxy/metrics/metrics.go","code":"// SinceInSeconds gets the time since the specified start in seconds.\nfunc SinceInSeconds(start time.Time) float64 {\n\treturn time.Since(start).Seconds()\n}","line":{"from":197,"to":200}} {"id":100008590,"name":"NewNodePodCIDRHandler","signature":"func NewNodePodCIDRHandler(podCIDRs []string) *NodePodCIDRHandler","file":"pkg/proxy/node.go","code":"func NewNodePodCIDRHandler(podCIDRs []string) *NodePodCIDRHandler {\n\treturn \u0026NodePodCIDRHandler{\n\t\tpodCIDRs: podCIDRs,\n\t}\n}","line":{"from":36,"to":40}} {"id":100008591,"name":"OnNodeAdd","signature":"func (n *NodePodCIDRHandler) OnNodeAdd(node *v1.Node)","file":"pkg/proxy/node.go","code":"// OnNodeAdd is a handler for Node creates.\nfunc (n *NodePodCIDRHandler) OnNodeAdd(node *v1.Node) {\n\tn.mu.Lock()\n\tdefer n.mu.Unlock()\n\n\tpodCIDRs := node.Spec.PodCIDRs\n\t// initialize podCIDRs\n\tif len(n.podCIDRs) == 0 \u0026\u0026 len(podCIDRs) \u003e 0 {\n\t\tklog.InfoS(\"Setting current PodCIDRs\", \"podCIDRs\", podCIDRs)\n\t\tn.podCIDRs = podCIDRs\n\t\treturn\n\t}\n\tif !reflect.DeepEqual(n.podCIDRs, podCIDRs) {\n\t\tklog.ErrorS(nil, \"Using NodeCIDR LocalDetector mode, current PodCIDRs are different than previous PodCIDRs, restarting\",\n\t\t\t\"node\", klog.KObj(node), \"newPodCIDRs\", podCIDRs, \"oldPodCIDRs\", n.podCIDRs)\n\t\tpanic(\"Current Node PodCIDRs are different than previous PodCIDRs, restarting\")\n\t}\n}","line":{"from":44,"to":61}} {"id":100008592,"name":"OnNodeUpdate","signature":"func (n *NodePodCIDRHandler) OnNodeUpdate(_, node *v1.Node)","file":"pkg/proxy/node.go","code":"// OnNodeUpdate is a handler for Node updates.\nfunc (n *NodePodCIDRHandler) OnNodeUpdate(_, node *v1.Node) {\n\tn.mu.Lock()\n\tdefer n.mu.Unlock()\n\tpodCIDRs := node.Spec.PodCIDRs\n\t// initialize podCIDRs\n\tif len(n.podCIDRs) == 0 \u0026\u0026 len(podCIDRs) \u003e 0 {\n\t\tklog.InfoS(\"Setting current PodCIDRs\", \"podCIDRs\", podCIDRs)\n\t\tn.podCIDRs = podCIDRs\n\t\treturn\n\t}\n\tif !reflect.DeepEqual(n.podCIDRs, podCIDRs) {\n\t\tklog.ErrorS(nil, \"Using NodeCIDR LocalDetector mode, current PodCIDRs are different than previous PodCIDRs, restarting\",\n\t\t\t\"node\", klog.KObj(node), \"newPodCIDRs\", podCIDRs, \"oldPODCIDRs\", n.podCIDRs)\n\t\tpanic(\"Current Node PodCIDRs are different than previous PodCIDRs, restarting\")\n\t}\n}","line":{"from":63,"to":79}} {"id":100008593,"name":"OnNodeDelete","signature":"func (n *NodePodCIDRHandler) OnNodeDelete(node *v1.Node)","file":"pkg/proxy/node.go","code":"// OnNodeDelete is a handler for Node deletes.\nfunc (n *NodePodCIDRHandler) OnNodeDelete(node *v1.Node) {\n\tklog.ErrorS(nil, \"Current Node is being deleted\", \"node\", klog.KObj(node))\n}","line":{"from":81,"to":84}} {"id":100008594,"name":"OnNodeSynced","signature":"func (n *NodePodCIDRHandler) OnNodeSynced() {}","file":"pkg/proxy/node.go","code":"// OnNodeSynced is a handler for Node syncs.\nfunc (n *NodePodCIDRHandler) OnNodeSynced() {}","line":{"from":86,"to":87}} {"id":100008595,"name":"String","signature":"func (bsvcPortInfo *BaseServicePortInfo) String() string","file":"pkg/proxy/service.go","code":"// String is part of ServicePort interface.\nfunc (bsvcPortInfo *BaseServicePortInfo) String() string {\n\treturn fmt.Sprintf(\"%s:%d/%s\", bsvcPortInfo.clusterIP, bsvcPortInfo.port, bsvcPortInfo.protocol)\n}","line":{"from":61,"to":64}} {"id":100008596,"name":"ClusterIP","signature":"func (bsvcPortInfo *BaseServicePortInfo) ClusterIP() net.IP","file":"pkg/proxy/service.go","code":"// ClusterIP is part of ServicePort interface.\nfunc (bsvcPortInfo *BaseServicePortInfo) ClusterIP() net.IP {\n\treturn bsvcPortInfo.clusterIP\n}","line":{"from":66,"to":69}} {"id":100008597,"name":"Port","signature":"func (bsvcPortInfo *BaseServicePortInfo) Port() int","file":"pkg/proxy/service.go","code":"// Port is part of ServicePort interface.\nfunc (bsvcPortInfo *BaseServicePortInfo) Port() int {\n\treturn bsvcPortInfo.port\n}","line":{"from":71,"to":74}} {"id":100008598,"name":"SessionAffinityType","signature":"func (bsvcPortInfo *BaseServicePortInfo) SessionAffinityType() v1.ServiceAffinity","file":"pkg/proxy/service.go","code":"// SessionAffinityType is part of the ServicePort interface.\nfunc (bsvcPortInfo *BaseServicePortInfo) SessionAffinityType() v1.ServiceAffinity {\n\treturn bsvcPortInfo.sessionAffinityType\n}","line":{"from":76,"to":79}} {"id":100008599,"name":"StickyMaxAgeSeconds","signature":"func (bsvcPortInfo *BaseServicePortInfo) StickyMaxAgeSeconds() int","file":"pkg/proxy/service.go","code":"// StickyMaxAgeSeconds is part of the ServicePort interface\nfunc (bsvcPortInfo *BaseServicePortInfo) StickyMaxAgeSeconds() int {\n\treturn bsvcPortInfo.stickyMaxAgeSeconds\n}","line":{"from":81,"to":84}} {"id":100008600,"name":"Protocol","signature":"func (bsvcPortInfo *BaseServicePortInfo) Protocol() v1.Protocol","file":"pkg/proxy/service.go","code":"// Protocol is part of ServicePort interface.\nfunc (bsvcPortInfo *BaseServicePortInfo) Protocol() v1.Protocol {\n\treturn bsvcPortInfo.protocol\n}","line":{"from":86,"to":89}} {"id":100008601,"name":"LoadBalancerSourceRanges","signature":"func (bsvcPortInfo *BaseServicePortInfo) LoadBalancerSourceRanges() []string","file":"pkg/proxy/service.go","code":"// LoadBalancerSourceRanges is part of ServicePort interface\nfunc (bsvcPortInfo *BaseServicePortInfo) LoadBalancerSourceRanges() []string {\n\treturn bsvcPortInfo.loadBalancerSourceRanges\n}","line":{"from":91,"to":94}} {"id":100008602,"name":"HealthCheckNodePort","signature":"func (bsvcPortInfo *BaseServicePortInfo) HealthCheckNodePort() int","file":"pkg/proxy/service.go","code":"// HealthCheckNodePort is part of ServicePort interface.\nfunc (bsvcPortInfo *BaseServicePortInfo) HealthCheckNodePort() int {\n\treturn bsvcPortInfo.healthCheckNodePort\n}","line":{"from":96,"to":99}} {"id":100008603,"name":"NodePort","signature":"func (bsvcPortInfo *BaseServicePortInfo) NodePort() int","file":"pkg/proxy/service.go","code":"// NodePort is part of the ServicePort interface.\nfunc (bsvcPortInfo *BaseServicePortInfo) NodePort() int {\n\treturn bsvcPortInfo.nodePort\n}","line":{"from":101,"to":104}} {"id":100008604,"name":"ExternalIPStrings","signature":"func (bsvcPortInfo *BaseServicePortInfo) ExternalIPStrings() []string","file":"pkg/proxy/service.go","code":"// ExternalIPStrings is part of ServicePort interface.\nfunc (bsvcPortInfo *BaseServicePortInfo) ExternalIPStrings() []string {\n\treturn bsvcPortInfo.externalIPs\n}","line":{"from":106,"to":109}} {"id":100008605,"name":"LoadBalancerIPStrings","signature":"func (bsvcPortInfo *BaseServicePortInfo) LoadBalancerIPStrings() []string","file":"pkg/proxy/service.go","code":"// LoadBalancerIPStrings is part of ServicePort interface.\nfunc (bsvcPortInfo *BaseServicePortInfo) LoadBalancerIPStrings() []string {\n\tvar ips []string\n\tfor _, ing := range bsvcPortInfo.loadBalancerStatus.Ingress {\n\t\tips = append(ips, ing.IP)\n\t}\n\treturn ips\n}","line":{"from":111,"to":118}} {"id":100008606,"name":"ExternalPolicyLocal","signature":"func (bsvcPortInfo *BaseServicePortInfo) ExternalPolicyLocal() bool","file":"pkg/proxy/service.go","code":"// ExternalPolicyLocal is part of ServicePort interface.\nfunc (bsvcPortInfo *BaseServicePortInfo) ExternalPolicyLocal() bool {\n\treturn bsvcPortInfo.externalPolicyLocal\n}","line":{"from":120,"to":123}} {"id":100008607,"name":"InternalPolicyLocal","signature":"func (bsvcPortInfo *BaseServicePortInfo) InternalPolicyLocal() bool","file":"pkg/proxy/service.go","code":"// InternalPolicyLocal is part of ServicePort interface\nfunc (bsvcPortInfo *BaseServicePortInfo) InternalPolicyLocal() bool {\n\treturn bsvcPortInfo.internalPolicyLocal\n}","line":{"from":125,"to":128}} {"id":100008608,"name":"InternalTrafficPolicy","signature":"func (bsvcPortInfo *BaseServicePortInfo) InternalTrafficPolicy() *v1.ServiceInternalTrafficPolicy","file":"pkg/proxy/service.go","code":"// InternalTrafficPolicy is part of ServicePort interface\nfunc (bsvcPortInfo *BaseServicePortInfo) InternalTrafficPolicy() *v1.ServiceInternalTrafficPolicy {\n\treturn bsvcPortInfo.internalTrafficPolicy\n}","line":{"from":130,"to":133}} {"id":100008609,"name":"HintsAnnotation","signature":"func (bsvcPortInfo *BaseServicePortInfo) HintsAnnotation() string","file":"pkg/proxy/service.go","code":"// HintsAnnotation is part of ServicePort interface.\nfunc (bsvcPortInfo *BaseServicePortInfo) HintsAnnotation() string {\n\treturn bsvcPortInfo.hintsAnnotation\n}","line":{"from":135,"to":138}} {"id":100008610,"name":"ExternallyAccessible","signature":"func (bsvcPortInfo *BaseServicePortInfo) ExternallyAccessible() bool","file":"pkg/proxy/service.go","code":"// ExternallyAccessible is part of ServicePort interface.\nfunc (bsvcPortInfo *BaseServicePortInfo) ExternallyAccessible() bool {\n\treturn bsvcPortInfo.nodePort != 0 || len(bsvcPortInfo.loadBalancerStatus.Ingress) != 0 || len(bsvcPortInfo.externalIPs) != 0\n}","line":{"from":140,"to":143}} {"id":100008611,"name":"UsesClusterEndpoints","signature":"func (bsvcPortInfo *BaseServicePortInfo) UsesClusterEndpoints() bool","file":"pkg/proxy/service.go","code":"// UsesClusterEndpoints is part of ServicePort interface.\nfunc (bsvcPortInfo *BaseServicePortInfo) UsesClusterEndpoints() bool {\n\t// The service port uses Cluster endpoints if the internal traffic policy is \"Cluster\",\n\t// or if it accepts external traffic at all. (Even if the external traffic policy is\n\t// \"Local\", we need Cluster endpoints to implement short circuiting.)\n\treturn !bsvcPortInfo.internalPolicyLocal || bsvcPortInfo.ExternallyAccessible()\n}","line":{"from":145,"to":151}} {"id":100008612,"name":"UsesLocalEndpoints","signature":"func (bsvcPortInfo *BaseServicePortInfo) UsesLocalEndpoints() bool","file":"pkg/proxy/service.go","code":"// UsesLocalEndpoints is part of ServicePort interface.\nfunc (bsvcPortInfo *BaseServicePortInfo) UsesLocalEndpoints() bool {\n\treturn bsvcPortInfo.internalPolicyLocal || (bsvcPortInfo.externalPolicyLocal \u0026\u0026 bsvcPortInfo.ExternallyAccessible())\n}","line":{"from":153,"to":156}} {"id":100008613,"name":"newBaseServiceInfo","signature":"func (sct *ServiceChangeTracker) newBaseServiceInfo(port *v1.ServicePort, service *v1.Service) *BaseServicePortInfo","file":"pkg/proxy/service.go","code":"func (sct *ServiceChangeTracker) newBaseServiceInfo(port *v1.ServicePort, service *v1.Service) *BaseServicePortInfo {\n\texternalPolicyLocal := apiservice.ExternalPolicyLocal(service)\n\tinternalPolicyLocal := apiservice.InternalPolicyLocal(service)\n\n\tvar stickyMaxAgeSeconds int\n\tif service.Spec.SessionAffinity == v1.ServiceAffinityClientIP {\n\t\t// Kube-apiserver side guarantees SessionAffinityConfig won't be nil when session affinity type is ClientIP\n\t\tstickyMaxAgeSeconds = int(*service.Spec.SessionAffinityConfig.ClientIP.TimeoutSeconds)\n\t}\n\n\tclusterIP := utilproxy.GetClusterIPByFamily(sct.ipFamily, service)\n\tinfo := \u0026BaseServicePortInfo{\n\t\tclusterIP: netutils.ParseIPSloppy(clusterIP),\n\t\tport: int(port.Port),\n\t\tprotocol: port.Protocol,\n\t\tnodePort: int(port.NodePort),\n\t\tsessionAffinityType: service.Spec.SessionAffinity,\n\t\tstickyMaxAgeSeconds: stickyMaxAgeSeconds,\n\t\texternalPolicyLocal: externalPolicyLocal,\n\t\tinternalPolicyLocal: internalPolicyLocal,\n\t\tinternalTrafficPolicy: service.Spec.InternalTrafficPolicy,\n\t}\n\n\t// v1.DeprecatedAnnotationTopologyAwareHints has precedence over v1.AnnotationTopologyMode.\n\tvar ok bool\n\tinfo.hintsAnnotation, ok = service.Annotations[v1.DeprecatedAnnotationTopologyAwareHints]\n\tif !ok {\n\t\tinfo.hintsAnnotation, _ = service.Annotations[v1.AnnotationTopologyMode]\n\t}\n\n\tloadBalancerSourceRanges := make([]string, len(service.Spec.LoadBalancerSourceRanges))\n\tfor i, sourceRange := range service.Spec.LoadBalancerSourceRanges {\n\t\tloadBalancerSourceRanges[i] = strings.TrimSpace(sourceRange)\n\t}\n\t// filter external ips, source ranges and ingress ips\n\t// prior to dual stack services, this was considered an error, but with dual stack\n\t// services, this is actually expected. Hence we downgraded from reporting by events\n\t// to just log lines with high verbosity\n\n\tipFamilyMap := utilproxy.MapIPsByIPFamily(service.Spec.ExternalIPs)\n\tinfo.externalIPs = ipFamilyMap[sct.ipFamily]\n\n\t// Log the IPs not matching the ipFamily\n\tif ips, ok := ipFamilyMap[utilproxy.OtherIPFamily(sct.ipFamily)]; ok \u0026\u0026 len(ips) \u003e 0 {\n\t\tklog.V(4).InfoS(\"Service change tracker ignored the following external IPs for given service as they don't match IP Family\",\n\t\t\t\"ipFamily\", sct.ipFamily, \"externalIPs\", strings.Join(ips, \",\"), \"service\", klog.KObj(service))\n\t}\n\n\tipFamilyMap = utilproxy.MapCIDRsByIPFamily(loadBalancerSourceRanges)\n\tinfo.loadBalancerSourceRanges = ipFamilyMap[sct.ipFamily]\n\t// Log the CIDRs not matching the ipFamily\n\tif cidrs, ok := ipFamilyMap[utilproxy.OtherIPFamily(sct.ipFamily)]; ok \u0026\u0026 len(cidrs) \u003e 0 {\n\t\tklog.V(4).InfoS(\"Service change tracker ignored the following load balancer source ranges for given Service as they don't match IP Family\",\n\t\t\t\"ipFamily\", sct.ipFamily, \"loadBalancerSourceRanges\", strings.Join(cidrs, \",\"), \"service\", klog.KObj(service))\n\t}\n\n\t// Obtain Load Balancer Ingress IPs\n\tvar ips []string\n\tfor _, ing := range service.Status.LoadBalancer.Ingress {\n\t\tif ing.IP != \"\" {\n\t\t\tips = append(ips, ing.IP)\n\t\t}\n\t}\n\n\tif len(ips) \u003e 0 {\n\t\tipFamilyMap = utilproxy.MapIPsByIPFamily(ips)\n\n\t\tif ipList, ok := ipFamilyMap[utilproxy.OtherIPFamily(sct.ipFamily)]; ok \u0026\u0026 len(ipList) \u003e 0 {\n\t\t\tklog.V(4).InfoS(\"Service change tracker ignored the following load balancer ingress IPs for given Service as they don't match the IP Family\",\n\t\t\t\t\"ipFamily\", sct.ipFamily, \"loadBalancerIngressIps\", strings.Join(ipList, \",\"), \"service\", klog.KObj(service))\n\t\t}\n\t\t// Create the LoadBalancerStatus with the filtered IPs\n\t\tfor _, ip := range ipFamilyMap[sct.ipFamily] {\n\t\t\tinfo.loadBalancerStatus.Ingress = append(info.loadBalancerStatus.Ingress, v1.LoadBalancerIngress{IP: ip})\n\t\t}\n\t}\n\n\tif apiservice.NeedsHealthCheck(service) {\n\t\tp := service.Spec.HealthCheckNodePort\n\t\tif p == 0 {\n\t\t\tklog.ErrorS(nil, \"Service has no healthcheck nodeport\", \"service\", klog.KObj(service))\n\t\t} else {\n\t\t\tinfo.healthCheckNodePort = int(p)\n\t\t}\n\t}\n\n\treturn info\n}","line":{"from":158,"to":245}} {"id":100008614,"name":"NewServiceChangeTracker","signature":"func NewServiceChangeTracker(makeServiceInfo makeServicePortFunc, ipFamily v1.IPFamily, recorder events.EventRecorder, processServiceMapChange processServiceMapChangeFunc) *ServiceChangeTracker","file":"pkg/proxy/service.go","code":"// NewServiceChangeTracker initializes a ServiceChangeTracker\nfunc NewServiceChangeTracker(makeServiceInfo makeServicePortFunc, ipFamily v1.IPFamily, recorder events.EventRecorder, processServiceMapChange processServiceMapChangeFunc) *ServiceChangeTracker {\n\treturn \u0026ServiceChangeTracker{\n\t\titems: make(map[types.NamespacedName]*serviceChange),\n\t\tmakeServiceInfo: makeServiceInfo,\n\t\trecorder: recorder,\n\t\tipFamily: ipFamily,\n\t\tprocessServiceMapChange: processServiceMapChange,\n\t}\n}","line":{"from":276,"to":285}} {"id":100008615,"name":"Update","signature":"func (sct *ServiceChangeTracker) Update(previous, current *v1.Service) bool","file":"pkg/proxy/service.go","code":"// Update updates given service's change map based on the \u003cprevious, current\u003e service pair. It returns true if items changed,\n// otherwise return false. Update can be used to add/update/delete items of ServiceChangeMap. For example,\n// Add item\n// - pass \u003cnil, service\u003e as the \u003cprevious, current\u003e pair.\n//\n// Update item\n// - pass \u003coldService, service\u003e as the \u003cprevious, current\u003e pair.\n//\n// Delete item\n// - pass \u003cservice, nil\u003e as the \u003cprevious, current\u003e pair.\nfunc (sct *ServiceChangeTracker) Update(previous, current *v1.Service) bool {\n\t// This is unexpected, we should return false directly.\n\tif previous == nil \u0026\u0026 current == nil {\n\t\treturn false\n\t}\n\n\tsvc := current\n\tif svc == nil {\n\t\tsvc = previous\n\t}\n\tmetrics.ServiceChangesTotal.Inc()\n\tnamespacedName := types.NamespacedName{Namespace: svc.Namespace, Name: svc.Name}\n\n\tsct.lock.Lock()\n\tdefer sct.lock.Unlock()\n\n\tchange, exists := sct.items[namespacedName]\n\tif !exists {\n\t\tchange = \u0026serviceChange{}\n\t\tchange.previous = sct.serviceToServiceMap(previous)\n\t\tsct.items[namespacedName] = change\n\t}\n\tchange.current = sct.serviceToServiceMap(current)\n\t// if change.previous equal to change.current, it means no change\n\tif reflect.DeepEqual(change.previous, change.current) {\n\t\tdelete(sct.items, namespacedName)\n\t} else {\n\t\tklog.V(4).InfoS(\"Service updated ports\", \"service\", klog.KObj(svc), \"portCount\", len(change.current))\n\t}\n\tmetrics.ServiceChangesPending.Set(float64(len(sct.items)))\n\treturn len(sct.items) \u003e 0\n}","line":{"from":287,"to":328}} {"id":100008616,"name":"PendingChanges","signature":"func (sct *ServiceChangeTracker) PendingChanges() sets.String","file":"pkg/proxy/service.go","code":"// PendingChanges returns a set whose keys are the names of the services that have changed\n// since the last time sct was used to update a ServiceMap. (You must call this _before_\n// calling sm.Update(sct).)\nfunc (sct *ServiceChangeTracker) PendingChanges() sets.String {\n\tsct.lock.Lock()\n\tdefer sct.lock.Unlock()\n\n\tchanges := sets.NewString()\n\tfor name := range sct.items {\n\t\tchanges.Insert(name.String())\n\t}\n\treturn changes\n}","line":{"from":330,"to":342}} {"id":100008617,"name":"Update","signature":"func (sm ServicePortMap) Update(changes *ServiceChangeTracker) (result UpdateServiceMapResult)","file":"pkg/proxy/service.go","code":"// Update updates ServicePortMap base on the given changes.\nfunc (sm ServicePortMap) Update(changes *ServiceChangeTracker) (result UpdateServiceMapResult) {\n\tresult.DeletedUDPClusterIPs = sets.NewString()\n\tsm.apply(changes, result.DeletedUDPClusterIPs)\n\treturn result\n}","line":{"from":352,"to":357}} {"id":100008618,"name":"HealthCheckNodePorts","signature":"func (sm ServicePortMap) HealthCheckNodePorts() map[types.NamespacedName]uint16","file":"pkg/proxy/service.go","code":"// HealthCheckNodePorts returns a map of Service names to HealthCheckNodePort values\n// for all Services in sm with non-zero HealthCheckNodePort.\nfunc (sm ServicePortMap) HealthCheckNodePorts() map[types.NamespacedName]uint16 {\n\t// TODO: If this will appear to be computationally expensive, consider\n\t// computing this incrementally similarly to svcPortMap.\n\tports := make(map[types.NamespacedName]uint16)\n\tfor svcPortName, info := range sm {\n\t\tif info.HealthCheckNodePort() != 0 {\n\t\t\tports[svcPortName.NamespacedName] = uint16(info.HealthCheckNodePort())\n\t\t}\n\t}\n\treturn ports\n}","line":{"from":359,"to":371}} {"id":100008619,"name":"serviceToServiceMap","signature":"func (sct *ServiceChangeTracker) serviceToServiceMap(service *v1.Service) ServicePortMap","file":"pkg/proxy/service.go","code":"// serviceToServiceMap translates a single Service object to a ServicePortMap.\n//\n// NOTE: service object should NOT be modified.\nfunc (sct *ServiceChangeTracker) serviceToServiceMap(service *v1.Service) ServicePortMap {\n\tif service == nil {\n\t\treturn nil\n\t}\n\n\tif utilproxy.ShouldSkipService(service) {\n\t\treturn nil\n\t}\n\n\tclusterIP := utilproxy.GetClusterIPByFamily(sct.ipFamily, service)\n\tif clusterIP == \"\" {\n\t\treturn nil\n\t}\n\n\tsvcPortMap := make(ServicePortMap)\n\tsvcName := types.NamespacedName{Namespace: service.Namespace, Name: service.Name}\n\tfor i := range service.Spec.Ports {\n\t\tservicePort := \u0026service.Spec.Ports[i]\n\t\tsvcPortName := ServicePortName{NamespacedName: svcName, Port: servicePort.Name, Protocol: servicePort.Protocol}\n\t\tbaseSvcInfo := sct.newBaseServiceInfo(servicePort, service)\n\t\tif sct.makeServiceInfo != nil {\n\t\t\tsvcPortMap[svcPortName] = sct.makeServiceInfo(servicePort, service, baseSvcInfo)\n\t\t} else {\n\t\t\tsvcPortMap[svcPortName] = baseSvcInfo\n\t\t}\n\t}\n\treturn svcPortMap\n}","line":{"from":376,"to":406}} {"id":100008620,"name":"apply","signature":"func (sm *ServicePortMap) apply(changes *ServiceChangeTracker, deletedUDPClusterIPs sets.String)","file":"pkg/proxy/service.go","code":"// apply the changes to ServicePortMap and update the deleted UDP cluster IP set.\n// apply triggers processServiceMapChange on every change.\nfunc (sm *ServicePortMap) apply(changes *ServiceChangeTracker, deletedUDPClusterIPs sets.String) {\n\tchanges.lock.Lock()\n\tdefer changes.lock.Unlock()\n\tfor _, change := range changes.items {\n\t\tif changes.processServiceMapChange != nil {\n\t\t\tchanges.processServiceMapChange(change.previous, change.current)\n\t\t}\n\t\tsm.merge(change.current)\n\t\t// filter out the Update event of current changes from previous changes before calling unmerge() so that can\n\t\t// skip deleting the Update events.\n\t\tchange.previous.filter(change.current)\n\t\tsm.unmerge(change.previous, deletedUDPClusterIPs)\n\t}\n\t// clear changes after applying them to ServicePortMap.\n\tchanges.items = make(map[types.NamespacedName]*serviceChange)\n\tmetrics.ServiceChangesPending.Set(0)\n}","line":{"from":408,"to":426}} {"id":100008621,"name":"merge","signature":"func (sm *ServicePortMap) merge(other ServicePortMap) sets.String","file":"pkg/proxy/service.go","code":"// merge adds other ServicePortMap's elements to current ServicePortMap.\n// If collision, other ALWAYS win. Otherwise add the other to current.\n// In other words, if some elements in current collisions with other, update the current by other.\n// It returns a string type set which stores all the newly merged services' identifier, ServicePortName.String(), to help users\n// tell if a service is deleted or updated.\n// The returned value is one of the arguments of ServicePortMap.unmerge().\n// ServicePortMap A Merge ServicePortMap B will do following 2 things:\n// - update ServicePortMap A.\n// - produce a string set which stores all other ServicePortMap's ServicePortName.String().\n//\n// For example,\n//\n//\tA{}\n//\tB{{\"ns\", \"cluster-ip\", \"http\"}: {\"172.16.55.10\", 1234, \"TCP\"}}\n//\t A updated to be {{\"ns\", \"cluster-ip\", \"http\"}: {\"172.16.55.10\", 1234, \"TCP\"}}\n//\t produce string set {\"ns/cluster-ip:http\"}\n//\n//\tA{{\"ns\", \"cluster-ip\", \"http\"}: {\"172.16.55.10\", 345, \"UDP\"}}\n//\tB{{\"ns\", \"cluster-ip\", \"http\"}: {\"172.16.55.10\", 1234, \"TCP\"}}\n//\t A updated to be {{\"ns\", \"cluster-ip\", \"http\"}: {\"172.16.55.10\", 1234, \"TCP\"}}\n//\t produce string set {\"ns/cluster-ip:http\"}\nfunc (sm *ServicePortMap) merge(other ServicePortMap) sets.String {\n\t// existingPorts is going to store all identifiers of all services in `other` ServicePortMap.\n\texistingPorts := sets.NewString()\n\tfor svcPortName, info := range other {\n\t\t// Take ServicePortName.String() as the newly merged service's identifier and put it into existingPorts.\n\t\texistingPorts.Insert(svcPortName.String())\n\t\t_, exists := (*sm)[svcPortName]\n\t\tif !exists {\n\t\t\tklog.V(4).InfoS(\"Adding new service port\", \"portName\", svcPortName, \"servicePort\", info)\n\t\t} else {\n\t\t\tklog.V(4).InfoS(\"Updating existing service port\", \"portName\", svcPortName, \"servicePort\", info)\n\t\t}\n\t\t(*sm)[svcPortName] = info\n\t}\n\treturn existingPorts\n}","line":{"from":428,"to":464}} {"id":100008622,"name":"filter","signature":"func (sm *ServicePortMap) filter(other ServicePortMap)","file":"pkg/proxy/service.go","code":"// filter filters out elements from ServicePortMap base on given ports string sets.\nfunc (sm *ServicePortMap) filter(other ServicePortMap) {\n\tfor svcPortName := range *sm {\n\t\t// skip the delete for Update event.\n\t\tif _, ok := other[svcPortName]; ok {\n\t\t\tdelete(*sm, svcPortName)\n\t\t}\n\t}\n}","line":{"from":466,"to":474}} {"id":100008623,"name":"unmerge","signature":"func (sm *ServicePortMap) unmerge(other ServicePortMap, deletedUDPClusterIPs sets.String)","file":"pkg/proxy/service.go","code":"// unmerge deletes all other ServicePortMap's elements from current ServicePortMap and\n// updates deletedUDPClusterIPs with all of the newly-deleted UDP cluster IPs.\nfunc (sm *ServicePortMap) unmerge(other ServicePortMap, deletedUDPClusterIPs sets.String) {\n\tfor svcPortName := range other {\n\t\tinfo, exists := (*sm)[svcPortName]\n\t\tif exists {\n\t\t\tklog.V(4).InfoS(\"Removing service port\", \"portName\", svcPortName)\n\t\t\tif info.Protocol() == v1.ProtocolUDP {\n\t\t\t\tdeletedUDPClusterIPs.Insert(info.ClusterIP().String())\n\t\t\t}\n\t\t\tdelete(*sm, svcPortName)\n\t\t} else {\n\t\t\tklog.ErrorS(nil, \"Service port does not exists\", \"portName\", svcPortName)\n\t\t}\n\t}\n}","line":{"from":476,"to":491}} {"id":100008624,"name":"CategorizeEndpoints","signature":"func CategorizeEndpoints(endpoints []Endpoint, svcInfo ServicePort, nodeLabels map[string]string) (clusterEndpoints, localEndpoints, allReachableEndpoints []Endpoint, hasAnyEndpoints bool)","file":"pkg/proxy/topology.go","code":"// CategorizeEndpoints returns:\n//\n// - The service's usable Cluster-traffic-policy endpoints (taking topology into account, if\n// relevant). This will be nil if the service does not ever use Cluster traffic policy.\n//\n// - The service's usable Local-traffic-policy endpoints (including terminating endpoints, if\n// relevant). This will be nil if the service does not ever use Local traffic policy.\n//\n// - The combined list of all endpoints reachable from this node (which is the union of the\n// previous two lists, but in the case where it is identical to one or the other, we avoid\n// allocating a separate list).\n//\n// - An indication of whether the service has any endpoints reachable from anywhere in the\n// cluster. (This may be true even if allReachableEndpoints is empty.)\nfunc CategorizeEndpoints(endpoints []Endpoint, svcInfo ServicePort, nodeLabels map[string]string) (clusterEndpoints, localEndpoints, allReachableEndpoints []Endpoint, hasAnyEndpoints bool) {\n\tvar useTopology, useServingTerminatingEndpoints bool\n\n\tif svcInfo.UsesClusterEndpoints() {\n\t\tuseTopology = canUseTopology(endpoints, svcInfo, nodeLabels)\n\t\tclusterEndpoints = filterEndpoints(endpoints, func(ep Endpoint) bool {\n\t\t\tif !ep.IsReady() {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif useTopology \u0026\u0026 !availableForTopology(ep, nodeLabels) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\n\t\t// if there are 0 cluster-wide endpoints, we can try to fallback to any terminating endpoints that are ready.\n\t\t// When falling back to terminating endpoints, we do NOT consider topology aware routing since this is a best\n\t\t// effort attempt to avoid dropping connections.\n\t\tif len(clusterEndpoints) == 0 \u0026\u0026 utilfeature.DefaultFeatureGate.Enabled(features.ProxyTerminatingEndpoints) {\n\t\t\tclusterEndpoints = filterEndpoints(endpoints, func(ep Endpoint) bool {\n\t\t\t\tif ep.IsServing() \u0026\u0026 ep.IsTerminating() {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\t\treturn false\n\t\t\t})\n\t\t}\n\n\t\t// If there are any Ready endpoints anywhere in the cluster, we are\n\t\t// guaranteed to get one in clusterEndpoints.\n\t\tif len(clusterEndpoints) \u003e 0 {\n\t\t\thasAnyEndpoints = true\n\t\t}\n\t}\n\n\tif !svcInfo.UsesLocalEndpoints() {\n\t\tallReachableEndpoints = clusterEndpoints\n\t\treturn\n\t}\n\n\t// Pre-scan the endpoints, to figure out which type of endpoint Local\n\t// traffic policy will use, and also to see if there are any usable\n\t// endpoints anywhere in the cluster.\n\tvar hasLocalReadyEndpoints, hasLocalServingTerminatingEndpoints bool\n\tfor _, ep := range endpoints {\n\t\tif ep.IsReady() {\n\t\t\thasAnyEndpoints = true\n\t\t\tif ep.GetIsLocal() {\n\t\t\t\thasLocalReadyEndpoints = true\n\t\t\t}\n\t\t} else if ep.IsServing() \u0026\u0026 ep.IsTerminating() \u0026\u0026 utilfeature.DefaultFeatureGate.Enabled(features.ProxyTerminatingEndpoints) {\n\t\t\thasAnyEndpoints = true\n\t\t\tif ep.GetIsLocal() {\n\t\t\t\thasLocalServingTerminatingEndpoints = true\n\t\t\t}\n\t\t}\n\t}\n\n\tif hasLocalReadyEndpoints {\n\t\tlocalEndpoints = filterEndpoints(endpoints, func(ep Endpoint) bool {\n\t\t\treturn ep.GetIsLocal() \u0026\u0026 ep.IsReady()\n\t\t})\n\t} else if hasLocalServingTerminatingEndpoints {\n\t\tuseServingTerminatingEndpoints = true\n\t\tlocalEndpoints = filterEndpoints(endpoints, func(ep Endpoint) bool {\n\t\t\treturn ep.GetIsLocal() \u0026\u0026 ep.IsServing() \u0026\u0026 ep.IsTerminating()\n\t\t})\n\t}\n\n\tif !svcInfo.UsesClusterEndpoints() {\n\t\tallReachableEndpoints = localEndpoints\n\t\treturn\n\t}\n\n\tif !useTopology \u0026\u0026 !useServingTerminatingEndpoints {\n\t\t// !useServingTerminatingEndpoints means that localEndpoints contains only\n\t\t// Ready endpoints. !useTopology means that clusterEndpoints contains *every*\n\t\t// Ready endpoint. So clusterEndpoints must be a superset of localEndpoints.\n\t\tallReachableEndpoints = clusterEndpoints\n\t\treturn\n\t}\n\n\t// clusterEndpoints may contain remote endpoints that aren't in localEndpoints, while\n\t// localEndpoints may contain terminating or topologically-unavailable local endpoints\n\t// that aren't in clusterEndpoints. So we have to merge the two lists.\n\tendpointsMap := make(map[string]Endpoint, len(clusterEndpoints)+len(localEndpoints))\n\tfor _, ep := range clusterEndpoints {\n\t\tendpointsMap[ep.String()] = ep\n\t}\n\tfor _, ep := range localEndpoints {\n\t\tendpointsMap[ep.String()] = ep\n\t}\n\tallReachableEndpoints = make([]Endpoint, 0, len(endpointsMap))\n\tfor _, ep := range endpointsMap {\n\t\tallReachableEndpoints = append(allReachableEndpoints, ep)\n\t}\n\n\treturn\n}","line":{"from":26,"to":138}} {"id":100008625,"name":"canUseTopology","signature":"func canUseTopology(endpoints []Endpoint, svcInfo ServicePort, nodeLabels map[string]string) bool","file":"pkg/proxy/topology.go","code":"// canUseTopology returns true if topology aware routing is enabled and properly configured\n// in this cluster. That is, it checks that:\n// * The TopologyAwareHints feature is enabled\n// * The \"service.kubernetes.io/topology-aware-hints\" annotation on this Service is set to \"Auto\"\n// * The node's labels include \"topology.kubernetes.io/zone\"\n// * All of the endpoints for this Service have a topology hint\n// * At least one endpoint for this Service is hinted for this node's zone.\nfunc canUseTopology(endpoints []Endpoint, svcInfo ServicePort, nodeLabels map[string]string) bool {\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.TopologyAwareHints) {\n\t\treturn false\n\t}\n\t// Any non-empty and non-disabled values for the hints annotation are acceptable.\n\thintsAnnotation := svcInfo.HintsAnnotation()\n\tif hintsAnnotation == \"\" || hintsAnnotation == \"disabled\" || hintsAnnotation == \"Disabled\" {\n\t\treturn false\n\t}\n\n\tzone, ok := nodeLabels[v1.LabelTopologyZone]\n\tif !ok || zone == \"\" {\n\t\tklog.InfoS(\"Skipping topology aware endpoint filtering since node is missing label\", \"label\", v1.LabelTopologyZone)\n\t\treturn false\n\t}\n\n\thasEndpointForZone := false\n\tfor _, endpoint := range endpoints {\n\t\tif !endpoint.IsReady() {\n\t\t\tcontinue\n\t\t}\n\t\tif endpoint.GetZoneHints().Len() == 0 {\n\t\t\tklog.InfoS(\"Skipping topology aware endpoint filtering since one or more endpoints is missing a zone hint\")\n\t\t\treturn false\n\t\t}\n\n\t\tif endpoint.GetZoneHints().Has(zone) {\n\t\t\thasEndpointForZone = true\n\t\t}\n\t}\n\n\tif !hasEndpointForZone {\n\t\tklog.InfoS(\"Skipping topology aware endpoint filtering since no hints were provided for zone\", \"zone\", zone)\n\t\treturn false\n\t}\n\n\treturn true\n}","line":{"from":140,"to":184}} {"id":100008626,"name":"availableForTopology","signature":"func availableForTopology(endpoint Endpoint, nodeLabels map[string]string) bool","file":"pkg/proxy/topology.go","code":"// availableForTopology checks if this endpoint is available for use on this node, given\n// topology constraints. (It assumes that canUseTopology() returned true.)\nfunc availableForTopology(endpoint Endpoint, nodeLabels map[string]string) bool {\n\tzone := nodeLabels[v1.LabelTopologyZone]\n\treturn endpoint.GetZoneHints().Has(zone)\n}","line":{"from":186,"to":191}} {"id":100008627,"name":"filterEndpoints","signature":"func filterEndpoints(endpoints []Endpoint, predicate func(Endpoint) bool) []Endpoint","file":"pkg/proxy/topology.go","code":"// filterEndpoints filters endpoints according to predicate\nfunc filterEndpoints(endpoints []Endpoint, predicate func(Endpoint) bool) []Endpoint {\n\tfilteredEndpoints := make([]Endpoint, 0, len(endpoints))\n\n\tfor _, ep := range endpoints {\n\t\tif predicate(ep) {\n\t\t\tfilteredEndpoints = append(filteredEndpoints, ep)\n\t\t}\n\t}\n\n\treturn filteredEndpoints\n}","line":{"from":193,"to":204}} {"id":100008628,"name":"String","signature":"func (spn ServicePortName) String() string","file":"pkg/proxy/types.go","code":"func (spn ServicePortName) String() string {\n\treturn fmt.Sprintf(\"%s%s\", spn.NamespacedName.String(), fmtPortName(spn.Port))\n}","line":{"from":51,"to":53}} {"id":100008629,"name":"fmtPortName","signature":"func fmtPortName(in string) string","file":"pkg/proxy/types.go","code":"func fmtPortName(in string) string {\n\tif in == \"\" {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(\":%s\", in)\n}","line":{"from":55,"to":60}} {"id":100008630,"name":"IPPart","signature":"func IPPart(s string) string","file":"pkg/proxy/util/endpoints.go","code":"// IPPart returns just the IP part of an IP or IP:port or endpoint string. If the IP\n// part is an IPv6 address enclosed in brackets (e.g. \"[fd00:1::5]:9999\"),\n// then the brackets are stripped as well.\nfunc IPPart(s string) string {\n\tif ip := netutils.ParseIPSloppy(s); ip != nil {\n\t\t// IP address without port\n\t\treturn s\n\t}\n\t// Must be IP:port\n\thost, _, err := net.SplitHostPort(s)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to parse host-port\", \"input\", s)\n\t\treturn \"\"\n\t}\n\t// Check if host string is a valid IP address\n\tip := netutils.ParseIPSloppy(host)\n\tif ip == nil {\n\t\tklog.ErrorS(nil, \"Failed to parse IP\", \"input\", host)\n\t\treturn \"\"\n\t}\n\treturn ip.String()\n}","line":{"from":27,"to":48}} {"id":100008631,"name":"PortPart","signature":"func PortPart(s string) (int, error)","file":"pkg/proxy/util/endpoints.go","code":"// PortPart returns just the port part of an endpoint string.\nfunc PortPart(s string) (int, error) {\n\t// Must be IP:port\n\t_, port, err := net.SplitHostPort(s)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to parse host-port\", \"input\", s)\n\t\treturn -1, err\n\t}\n\tportNumber, err := strconv.Atoi(port)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to parse port\", \"input\", port)\n\t\treturn -1, err\n\t}\n\treturn portNumber, nil\n}","line":{"from":50,"to":64}} {"id":100008632,"name":"NewNoOpLocalDetector","signature":"func NewNoOpLocalDetector() LocalTrafficDetector","file":"pkg/proxy/util/iptables/traffic.go","code":"// NewNoOpLocalDetector is a no-op implementation of LocalTrafficDetector\nfunc NewNoOpLocalDetector() LocalTrafficDetector {\n\treturn \u0026noOpLocalDetector{}\n}","line":{"from":41,"to":44}} {"id":100008633,"name":"IsImplemented","signature":"func (n *noOpLocalDetector) IsImplemented() bool","file":"pkg/proxy/util/iptables/traffic.go","code":"func (n *noOpLocalDetector) IsImplemented() bool {\n\treturn false\n}","line":{"from":46,"to":48}} {"id":100008634,"name":"IfLocal","signature":"func (n *noOpLocalDetector) IfLocal() []string","file":"pkg/proxy/util/iptables/traffic.go","code":"func (n *noOpLocalDetector) IfLocal() []string {\n\treturn nil // no-op; matches all traffic\n}","line":{"from":50,"to":52}} {"id":100008635,"name":"IfNotLocal","signature":"func (n *noOpLocalDetector) IfNotLocal() []string","file":"pkg/proxy/util/iptables/traffic.go","code":"func (n *noOpLocalDetector) IfNotLocal() []string {\n\treturn nil // no-op; matches all traffic\n}","line":{"from":54,"to":56}} {"id":100008636,"name":"NewDetectLocalByCIDR","signature":"func NewDetectLocalByCIDR(cidr string, ipt utiliptables.Interface) (LocalTrafficDetector, error)","file":"pkg/proxy/util/iptables/traffic.go","code":"// NewDetectLocalByCIDR implements the LocalTrafficDetector interface using a CIDR. This can be used when a single CIDR\n// range can be used to capture the notion of local traffic.\nfunc NewDetectLocalByCIDR(cidr string, ipt utiliptables.Interface) (LocalTrafficDetector, error) {\n\tif netutils.IsIPv6CIDRString(cidr) != ipt.IsIPv6() {\n\t\treturn nil, fmt.Errorf(\"CIDR %s has incorrect IP version: expect isIPv6=%t\", cidr, ipt.IsIPv6())\n\t}\n\t_, _, err := netutils.ParseCIDRSloppy(cidr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026detectLocalByCIDR{\n\t\tifLocal: []string{\"-s\", cidr},\n\t\tifNotLocal: []string{\"!\", \"-s\", cidr},\n\t}, nil\n}","line":{"from":63,"to":77}} {"id":100008637,"name":"IsImplemented","signature":"func (d *detectLocalByCIDR) IsImplemented() bool","file":"pkg/proxy/util/iptables/traffic.go","code":"func (d *detectLocalByCIDR) IsImplemented() bool {\n\treturn true\n}","line":{"from":79,"to":81}} {"id":100008638,"name":"IfLocal","signature":"func (d *detectLocalByCIDR) IfLocal() []string","file":"pkg/proxy/util/iptables/traffic.go","code":"func (d *detectLocalByCIDR) IfLocal() []string {\n\treturn d.ifLocal\n}","line":{"from":83,"to":85}} {"id":100008639,"name":"IfNotLocal","signature":"func (d *detectLocalByCIDR) IfNotLocal() []string","file":"pkg/proxy/util/iptables/traffic.go","code":"func (d *detectLocalByCIDR) IfNotLocal() []string {\n\treturn d.ifNotLocal\n}","line":{"from":87,"to":89}} {"id":100008640,"name":"NewDetectLocalByBridgeInterface","signature":"func NewDetectLocalByBridgeInterface(interfaceName string) (LocalTrafficDetector, error)","file":"pkg/proxy/util/iptables/traffic.go","code":"// NewDetectLocalByBridgeInterface implements the LocalTrafficDetector interface using a bridge interface name.\n// This can be used when a bridge can be used to capture the notion of local traffic from pods.\nfunc NewDetectLocalByBridgeInterface(interfaceName string) (LocalTrafficDetector, error) {\n\tif len(interfaceName) == 0 {\n\t\treturn nil, fmt.Errorf(\"no bridge interface name set\")\n\t}\n\treturn \u0026detectLocalByBridgeInterface{\n\t\tifLocal: []string{\"-i\", interfaceName},\n\t\tifNotLocal: []string{\"!\", \"-i\", interfaceName},\n\t}, nil\n}","line":{"from":96,"to":106}} {"id":100008641,"name":"IsImplemented","signature":"func (d *detectLocalByBridgeInterface) IsImplemented() bool","file":"pkg/proxy/util/iptables/traffic.go","code":"func (d *detectLocalByBridgeInterface) IsImplemented() bool {\n\treturn true\n}","line":{"from":108,"to":110}} {"id":100008642,"name":"IfLocal","signature":"func (d *detectLocalByBridgeInterface) IfLocal() []string","file":"pkg/proxy/util/iptables/traffic.go","code":"func (d *detectLocalByBridgeInterface) IfLocal() []string {\n\treturn d.ifLocal\n}","line":{"from":112,"to":114}} {"id":100008643,"name":"IfNotLocal","signature":"func (d *detectLocalByBridgeInterface) IfNotLocal() []string","file":"pkg/proxy/util/iptables/traffic.go","code":"func (d *detectLocalByBridgeInterface) IfNotLocal() []string {\n\treturn d.ifNotLocal\n}","line":{"from":116,"to":118}} {"id":100008644,"name":"NewDetectLocalByInterfaceNamePrefix","signature":"func NewDetectLocalByInterfaceNamePrefix(interfacePrefix string) (LocalTrafficDetector, error)","file":"pkg/proxy/util/iptables/traffic.go","code":"// NewDetectLocalByInterfaceNamePrefix implements the LocalTrafficDetector interface using an interface name prefix.\n// This can be used when a pod interface name prefix can be used to capture the notion of local traffic. Note\n// that this will match on all interfaces that start with the given prefix.\nfunc NewDetectLocalByInterfaceNamePrefix(interfacePrefix string) (LocalTrafficDetector, error) {\n\tif len(interfacePrefix) == 0 {\n\t\treturn nil, fmt.Errorf(\"no interface prefix set\")\n\t}\n\treturn \u0026detectLocalByInterfaceNamePrefix{\n\t\tifLocal: []string{\"-i\", interfacePrefix + \"+\"},\n\t\tifNotLocal: []string{\"!\", \"-i\", interfacePrefix + \"+\"},\n\t}, nil\n}","line":{"from":125,"to":136}} {"id":100008645,"name":"IsImplemented","signature":"func (d *detectLocalByInterfaceNamePrefix) IsImplemented() bool","file":"pkg/proxy/util/iptables/traffic.go","code":"func (d *detectLocalByInterfaceNamePrefix) IsImplemented() bool {\n\treturn true\n}","line":{"from":138,"to":140}} {"id":100008646,"name":"IfLocal","signature":"func (d *detectLocalByInterfaceNamePrefix) IfLocal() []string","file":"pkg/proxy/util/iptables/traffic.go","code":"func (d *detectLocalByInterfaceNamePrefix) IfLocal() []string {\n\treturn d.ifLocal\n}","line":{"from":142,"to":144}} {"id":100008647,"name":"IfNotLocal","signature":"func (d *detectLocalByInterfaceNamePrefix) IfNotLocal() []string","file":"pkg/proxy/util/iptables/traffic.go","code":"func (d *detectLocalByInterfaceNamePrefix) IfNotLocal() []string {\n\treturn d.ifNotLocal\n}","line":{"from":146,"to":148}} {"id":100008648,"name":"InterfaceAddrs","signature":"func (RealNetwork) InterfaceAddrs() ([]net.Addr, error)","file":"pkg/proxy/util/network.go","code":"// InterfaceAddrs wraps net.InterfaceAddrs(), it's a part of NetworkInterfacer interface.\nfunc (RealNetwork) InterfaceAddrs() ([]net.Addr, error) {\n\treturn net.InterfaceAddrs()\n}","line":{"from":34,"to":37}} {"id":100008649,"name":"NewNodePortAddresses","signature":"func NewNodePortAddresses(cidrStrings []string) *NodePortAddresses","file":"pkg/proxy/util/nodeport_addresses.go","code":"// NewNodePortAddresses takes the `--nodeport-addresses` value (which is assumed to\n// contain only valid CIDRs) and returns a NodePortAddresses object. If cidrStrings is\n// empty, this is treated as `[\"0.0.0.0/0\", \"::/0\"]`.\nfunc NewNodePortAddresses(cidrStrings []string) *NodePortAddresses {\n\tif len(cidrStrings) == 0 {\n\t\tcidrStrings = []string{IPv4ZeroCIDR, IPv6ZeroCIDR}\n\t}\n\n\tnpa := \u0026NodePortAddresses{\n\t\tcidrStrings: cidrStrings,\n\t}\n\n\tfor _, str := range npa.cidrStrings {\n\t\t_, cidr, _ := netutils.ParseCIDRSloppy(str)\n\t\tnpa.cidrs = append(npa.cidrs, cidr)\n\n\t\tif netutils.IsIPv4CIDR(cidr) {\n\t\t\tif cidr.IP.IsLoopback() || cidr.Contains(ipv4LoopbackStart) {\n\t\t\t\tnpa.containsIPv4Loopback = true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn npa\n}","line":{"from":38,"to":62}} {"id":100008650,"name":"String","signature":"func (npa *NodePortAddresses) String() string","file":"pkg/proxy/util/nodeport_addresses.go","code":"func (npa *NodePortAddresses) String() string {\n\treturn fmt.Sprintf(\"%v\", npa.cidrStrings)\n}","line":{"from":64,"to":66}} {"id":100008651,"name":"GetNodeAddresses","signature":"func (npa *NodePortAddresses) GetNodeAddresses(nw NetworkInterfacer) (sets.String, error)","file":"pkg/proxy/util/nodeport_addresses.go","code":"// GetNodeAddresses return all matched node IP addresses for npa's CIDRs.\n// If npa's CIDRs include \"0.0.0.0/0\" and/or \"::/0\", then those values will be returned\n// verbatim in the response and no actual IPs of that family will be returned.\n// If no matching IPs are found, GetNodeAddresses will return an error.\n// NetworkInterfacer is injected for test purpose.\nfunc (npa *NodePortAddresses) GetNodeAddresses(nw NetworkInterfacer) (sets.String, error) {\n\tuniqueAddressList := sets.NewString()\n\n\t// First round of iteration to pick out `0.0.0.0/0` or `::/0` for the sake of excluding non-zero IPs.\n\tfor _, cidr := range npa.cidrStrings {\n\t\tif IsZeroCIDR(cidr) {\n\t\t\tuniqueAddressList.Insert(cidr)\n\t\t}\n\t}\n\n\taddrs, err := nw.InterfaceAddrs()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error listing all interfaceAddrs from host, error: %v\", err)\n\t}\n\n\t// Second round of iteration to parse IPs based on cidr.\n\tfor _, cidr := range npa.cidrs {\n\t\tif IsZeroCIDR(cidr.String()) {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, addr := range addrs {\n\t\t\tvar ip net.IP\n\t\t\t// nw.InterfaceAddrs may return net.IPAddr or net.IPNet on windows, and it will return net.IPNet on linux.\n\t\t\tswitch v := addr.(type) {\n\t\t\tcase *net.IPAddr:\n\t\t\t\tip = v.IP\n\t\t\tcase *net.IPNet:\n\t\t\t\tip = v.IP\n\t\t\tdefault:\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif cidr.Contains(ip) {\n\t\t\t\tif netutils.IsIPv6(ip) \u0026\u0026 !uniqueAddressList.Has(IPv6ZeroCIDR) {\n\t\t\t\t\tuniqueAddressList.Insert(ip.String())\n\t\t\t\t}\n\t\t\t\tif !netutils.IsIPv6(ip) \u0026\u0026 !uniqueAddressList.Has(IPv4ZeroCIDR) {\n\t\t\t\t\tuniqueAddressList.Insert(ip.String())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif uniqueAddressList.Len() == 0 {\n\t\treturn nil, fmt.Errorf(\"no addresses found for cidrs %v\", npa.cidrStrings)\n\t}\n\n\treturn uniqueAddressList, nil\n}","line":{"from":68,"to":122}} {"id":100008652,"name":"ContainsIPv4Loopback","signature":"func (npa *NodePortAddresses) ContainsIPv4Loopback() bool","file":"pkg/proxy/util/nodeport_addresses.go","code":"// ContainsIPv4Loopback returns true if npa's CIDRs contain an IPv4 loopback address.\nfunc (npa *NodePortAddresses) ContainsIPv4Loopback() bool {\n\treturn npa.containsIPv4Loopback\n}","line":{"from":124,"to":127}} {"id":100008653,"name":"isValidEndpoint","signature":"func isValidEndpoint(host string, port int) bool","file":"pkg/proxy/util/utils.go","code":"// isValidEndpoint checks that the given host / port pair are valid endpoint\nfunc isValidEndpoint(host string, port int) bool {\n\treturn host != \"\" \u0026\u0026 port \u003e 0\n}","line":{"from":57,"to":60}} {"id":100008654,"name":"BuildPortsToEndpointsMap","signature":"func BuildPortsToEndpointsMap(endpoints *v1.Endpoints) map[string][]string","file":"pkg/proxy/util/utils.go","code":"// BuildPortsToEndpointsMap builds a map of portname -\u003e all ip:ports for that\n// portname. Explode Endpoints.Subsets[*] into this structure.\nfunc BuildPortsToEndpointsMap(endpoints *v1.Endpoints) map[string][]string {\n\tportsToEndpoints := map[string][]string{}\n\tfor i := range endpoints.Subsets {\n\t\tss := \u0026endpoints.Subsets[i]\n\t\tfor i := range ss.Ports {\n\t\t\tport := \u0026ss.Ports[i]\n\t\t\tfor i := range ss.Addresses {\n\t\t\t\taddr := \u0026ss.Addresses[i]\n\t\t\t\tif isValidEndpoint(addr.IP, int(port.Port)) {\n\t\t\t\t\tportsToEndpoints[port.Name] = append(portsToEndpoints[port.Name], net.JoinHostPort(addr.IP, strconv.Itoa(int(port.Port))))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn portsToEndpoints\n}","line":{"from":62,"to":79}} {"id":100008655,"name":"IsZeroCIDR","signature":"func IsZeroCIDR(cidr string) bool","file":"pkg/proxy/util/utils.go","code":"// IsZeroCIDR checks whether the input CIDR string is either\n// the IPv4 or IPv6 zero CIDR\nfunc IsZeroCIDR(cidr string) bool {\n\tif cidr == IPv4ZeroCIDR || cidr == IPv6ZeroCIDR {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":81,"to":88}} {"id":100008656,"name":"IsLoopBack","signature":"func IsLoopBack(ip string) bool","file":"pkg/proxy/util/utils.go","code":"// IsLoopBack checks if a given IP address is a loopback address.\nfunc IsLoopBack(ip string) bool {\n\tnetIP := netutils.ParseIPSloppy(ip)\n\tif netIP != nil {\n\t\treturn netIP.IsLoopback()\n\t}\n\treturn false\n}","line":{"from":90,"to":97}} {"id":100008657,"name":"IsProxyableIP","signature":"func IsProxyableIP(ip string) error","file":"pkg/proxy/util/utils.go","code":"// IsProxyableIP checks if a given IP address is permitted to be proxied\nfunc IsProxyableIP(ip string) error {\n\tnetIP := netutils.ParseIPSloppy(ip)\n\tif netIP == nil {\n\t\treturn ErrAddressNotAllowed\n\t}\n\treturn isProxyableIP(netIP)\n}","line":{"from":99,"to":106}} {"id":100008658,"name":"isProxyableIP","signature":"func isProxyableIP(ip net.IP) error","file":"pkg/proxy/util/utils.go","code":"func isProxyableIP(ip net.IP) error {\n\tif !ip.IsGlobalUnicast() {\n\t\treturn ErrAddressNotAllowed\n\t}\n\treturn nil\n}","line":{"from":108,"to":113}} {"id":100008659,"name":"IsProxyableHostname","signature":"func IsProxyableHostname(ctx context.Context, resolv Resolver, hostname string) error","file":"pkg/proxy/util/utils.go","code":"// IsProxyableHostname checks if the IP addresses for a given hostname are permitted to be proxied\nfunc IsProxyableHostname(ctx context.Context, resolv Resolver, hostname string) error {\n\tresp, err := resolv.LookupIPAddr(ctx, hostname)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(resp) == 0 {\n\t\treturn ErrNoAddresses\n\t}\n\n\tfor _, host := range resp {\n\t\tif err := isProxyableIP(host.IP); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":120,"to":137}} {"id":100008660,"name":"IsAllowedHost","signature":"func IsAllowedHost(host net.IP, denied []*net.IPNet) error","file":"pkg/proxy/util/utils.go","code":"// IsAllowedHost checks if the given IP host address is in a network in the denied list.\nfunc IsAllowedHost(host net.IP, denied []*net.IPNet) error {\n\tfor _, ipNet := range denied {\n\t\tif ipNet.Contains(host) {\n\t\t\treturn ErrAddressNotAllowed\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":139,"to":147}} {"id":100008661,"name":"GetLocalAddrs","signature":"func GetLocalAddrs() ([]net.IP, error)","file":"pkg/proxy/util/utils.go","code":"// GetLocalAddrs returns a list of all network addresses on the local system\nfunc GetLocalAddrs() ([]net.IP, error) {\n\tvar localAddrs []net.IP\n\n\taddrs, err := net.InterfaceAddrs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, addr := range addrs {\n\t\tip, _, err := netutils.ParseCIDRSloppy(addr.String())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tlocalAddrs = append(localAddrs, ip)\n\t}\n\n\treturn localAddrs, nil\n}","line":{"from":149,"to":168}} {"id":100008662,"name":"GetLocalAddrSet","signature":"func GetLocalAddrSet() netutils.IPSet","file":"pkg/proxy/util/utils.go","code":"// GetLocalAddrSet return a local IPSet.\n// If failed to get local addr, will assume no local ips.\nfunc GetLocalAddrSet() netutils.IPSet {\n\tlocalAddrs, err := GetLocalAddrs()\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to get local addresses assuming no local IPs\")\n\t} else if len(localAddrs) == 0 {\n\t\tklog.InfoS(\"No local addresses were found\")\n\t}\n\n\tlocalAddrSet := netutils.IPSet{}\n\tlocalAddrSet.Insert(localAddrs...)\n\treturn localAddrSet\n}","line":{"from":170,"to":183}} {"id":100008663,"name":"ShouldSkipService","signature":"func ShouldSkipService(service *v1.Service) bool","file":"pkg/proxy/util/utils.go","code":"// ShouldSkipService checks if a given service should skip proxying\nfunc ShouldSkipService(service *v1.Service) bool {\n\t// if ClusterIP is \"None\" or empty, skip proxying\n\tif !helper.IsServiceIPSet(service) {\n\t\tklog.V(3).InfoS(\"Skipping service due to cluster IP\", \"service\", klog.KObj(service), \"clusterIP\", service.Spec.ClusterIP)\n\t\treturn true\n\t}\n\t// Even if ClusterIP is set, ServiceTypeExternalName services don't get proxied\n\tif service.Spec.Type == v1.ServiceTypeExternalName {\n\t\tklog.V(3).InfoS(\"Skipping service due to Type=ExternalName\", \"service\", klog.KObj(service))\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":185,"to":198}} {"id":100008664,"name":"AddressSet","signature":"func AddressSet(isValid func(ip net.IP) bool, addrs []net.Addr) sets.Set[string]","file":"pkg/proxy/util/utils.go","code":"// AddressSet validates the addresses in the slice using the \"isValid\" function.\n// Addresses that pass the validation are returned as a string Set.\nfunc AddressSet(isValid func(ip net.IP) bool, addrs []net.Addr) sets.Set[string] {\n\tips := sets.New[string]()\n\tfor _, a := range addrs {\n\t\tvar ip net.IP\n\t\tswitch v := a.(type) {\n\t\tcase *net.IPAddr:\n\t\t\tip = v.IP\n\t\tcase *net.IPNet:\n\t\t\tip = v.IP\n\t\tdefault:\n\t\t\tcontinue\n\t\t}\n\t\tif isValid(ip) {\n\t\t\tips.Insert(ip.String())\n\t\t}\n\t}\n\treturn ips\n}","line":{"from":200,"to":219}} {"id":100008665,"name":"LogAndEmitIncorrectIPVersionEvent","signature":"func LogAndEmitIncorrectIPVersionEvent(recorder events.EventRecorder, fieldName, fieldValue, svcNamespace, svcName string, svcUID types.UID)","file":"pkg/proxy/util/utils.go","code":"// LogAndEmitIncorrectIPVersionEvent logs and emits incorrect IP version event.\nfunc LogAndEmitIncorrectIPVersionEvent(recorder events.EventRecorder, fieldName, fieldValue, svcNamespace, svcName string, svcUID types.UID) {\n\terrMsg := fmt.Sprintf(\"%s in %s has incorrect IP version\", fieldValue, fieldName)\n\tklog.ErrorS(nil, \"Incorrect IP version\", \"service\", klog.KRef(svcNamespace, svcName), \"field\", fieldName, \"value\", fieldValue)\n\tif recorder != nil {\n\t\trecorder.Eventf(\n\t\t\t\u0026v1.ObjectReference{\n\t\t\t\tKind: \"Service\",\n\t\t\t\tName: svcName,\n\t\t\t\tNamespace: svcNamespace,\n\t\t\t\tUID: svcUID,\n\t\t\t}, nil, v1.EventTypeWarning, \"KubeProxyIncorrectIPVersion\", \"GatherEndpoints\", errMsg)\n\t}\n}","line":{"from":221,"to":234}} {"id":100008666,"name":"MapIPsByIPFamily","signature":"func MapIPsByIPFamily(ipStrings []string) map[v1.IPFamily][]string","file":"pkg/proxy/util/utils.go","code":"// MapIPsByIPFamily maps a slice of IPs to their respective IP families (v4 or v6)\nfunc MapIPsByIPFamily(ipStrings []string) map[v1.IPFamily][]string {\n\tipFamilyMap := map[v1.IPFamily][]string{}\n\tfor _, ip := range ipStrings {\n\t\t// Handle only the valid IPs\n\t\tif ipFamily, err := getIPFamilyFromIP(ip); err == nil {\n\t\t\tipFamilyMap[ipFamily] = append(ipFamilyMap[ipFamily], ip)\n\t\t} else {\n\t\t\t// this function is called in multiple places. All of which\n\t\t\t// have sanitized data. Except the case of ExternalIPs which is\n\t\t\t// not validated by api-server. Specifically empty strings\n\t\t\t// validation. Which yields into a lot of bad error logs.\n\t\t\t// check for empty string\n\t\t\tif len(strings.TrimSpace(ip)) != 0 {\n\t\t\t\tklog.ErrorS(nil, \"Skipping invalid IP\", \"ip\", ip)\n\n\t\t\t}\n\t\t}\n\t}\n\treturn ipFamilyMap\n}","line":{"from":236,"to":256}} {"id":100008667,"name":"MapCIDRsByIPFamily","signature":"func MapCIDRsByIPFamily(cidrStrings []string) map[v1.IPFamily][]string","file":"pkg/proxy/util/utils.go","code":"// MapCIDRsByIPFamily maps a slice of IPs to their respective IP families (v4 or v6)\nfunc MapCIDRsByIPFamily(cidrStrings []string) map[v1.IPFamily][]string {\n\tipFamilyMap := map[v1.IPFamily][]string{}\n\tfor _, cidr := range cidrStrings {\n\t\t// Handle only the valid CIDRs\n\t\tif ipFamily, err := getIPFamilyFromCIDR(cidr); err == nil {\n\t\t\tipFamilyMap[ipFamily] = append(ipFamilyMap[ipFamily], cidr)\n\t\t} else {\n\t\t\tklog.ErrorS(nil, \"Skipping invalid CIDR\", \"cidr\", cidr)\n\t\t}\n\t}\n\treturn ipFamilyMap\n}","line":{"from":258,"to":270}} {"id":100008668,"name":"getIPFamilyFromIP","signature":"func getIPFamilyFromIP(ipStr string) (v1.IPFamily, error)","file":"pkg/proxy/util/utils.go","code":"func getIPFamilyFromIP(ipStr string) (v1.IPFamily, error) {\n\tnetIP := netutils.ParseIPSloppy(ipStr)\n\tif netIP == nil {\n\t\treturn \"\", ErrAddressNotAllowed\n\t}\n\n\tif netutils.IsIPv6(netIP) {\n\t\treturn v1.IPv6Protocol, nil\n\t}\n\treturn v1.IPv4Protocol, nil\n}","line":{"from":272,"to":282}} {"id":100008669,"name":"getIPFamilyFromCIDR","signature":"func getIPFamilyFromCIDR(cidrStr string) (v1.IPFamily, error)","file":"pkg/proxy/util/utils.go","code":"func getIPFamilyFromCIDR(cidrStr string) (v1.IPFamily, error) {\n\t_, netCIDR, err := netutils.ParseCIDRSloppy(cidrStr)\n\tif err != nil {\n\t\treturn \"\", ErrAddressNotAllowed\n\t}\n\tif netutils.IsIPv6CIDR(netCIDR) {\n\t\treturn v1.IPv6Protocol, nil\n\t}\n\treturn v1.IPv4Protocol, nil\n}","line":{"from":284,"to":293}} {"id":100008670,"name":"OtherIPFamily","signature":"func OtherIPFamily(ipFamily v1.IPFamily) v1.IPFamily","file":"pkg/proxy/util/utils.go","code":"// OtherIPFamily returns the other ip family\nfunc OtherIPFamily(ipFamily v1.IPFamily) v1.IPFamily {\n\tif ipFamily == v1.IPv6Protocol {\n\t\treturn v1.IPv4Protocol\n\t}\n\n\treturn v1.IPv6Protocol\n}","line":{"from":295,"to":302}} {"id":100008671,"name":"AppendPortIfNeeded","signature":"func AppendPortIfNeeded(addr string, port int32) string","file":"pkg/proxy/util/utils.go","code":"// AppendPortIfNeeded appends the given port to IP address unless it is already in\n// \"ipv4:port\" or \"[ipv6]:port\" format.\nfunc AppendPortIfNeeded(addr string, port int32) string {\n\t// Return if address is already in \"ipv4:port\" or \"[ipv6]:port\" format.\n\tif _, _, err := net.SplitHostPort(addr); err == nil {\n\t\treturn addr\n\t}\n\n\t// Simply return for invalid case. This should be caught by validation instead.\n\tip := netutils.ParseIPSloppy(addr)\n\tif ip == nil {\n\t\treturn addr\n\t}\n\n\t// Append port to address.\n\tif ip.To4() != nil {\n\t\treturn fmt.Sprintf(\"%s:%d\", addr, port)\n\t}\n\treturn fmt.Sprintf(\"[%s]:%d\", addr, port)\n}","line":{"from":304,"to":323}} {"id":100008672,"name":"ShuffleStrings","signature":"func ShuffleStrings(s []string) []string","file":"pkg/proxy/util/utils.go","code":"// ShuffleStrings copies strings from the specified slice into a copy in random\n// order. It returns a new slice.\nfunc ShuffleStrings(s []string) []string {\n\tif s == nil {\n\t\treturn nil\n\t}\n\tshuffled := make([]string, len(s))\n\tperm := utilrand.Perm(len(s))\n\tfor i, j := range perm {\n\t\tshuffled[j] = s[i]\n\t}\n\treturn shuffled\n}","line":{"from":325,"to":337}} {"id":100008673,"name":"EnsureSysctl","signature":"func EnsureSysctl(sysctl utilsysctl.Interface, name string, newVal int) error","file":"pkg/proxy/util/utils.go","code":"// EnsureSysctl sets a kernel sysctl to a given numeric value.\nfunc EnsureSysctl(sysctl utilsysctl.Interface, name string, newVal int) error {\n\tif oldVal, _ := sysctl.GetSysctl(name); oldVal != newVal {\n\t\tif err := sysctl.SetSysctl(name, newVal); err != nil {\n\t\t\treturn fmt.Errorf(\"can't set sysctl %s to %d: %v\", name, newVal, err)\n\t\t}\n\t\tklog.V(1).InfoS(\"Changed sysctl\", \"name\", name, \"before\", oldVal, \"after\", newVal)\n\t}\n\treturn nil\n}","line":{"from":339,"to":348}} {"id":100008674,"name":"NewFilteredDialContext","signature":"func NewFilteredDialContext(wrapped DialContext, resolv Resolver, opts *FilteredDialOptions) DialContext","file":"pkg/proxy/util/utils.go","code":"// NewFilteredDialContext returns a DialContext function that filters connections based on a FilteredDialOptions.\nfunc NewFilteredDialContext(wrapped DialContext, resolv Resolver, opts *FilteredDialOptions) DialContext {\n\tif wrapped == nil {\n\t\twrapped = http.DefaultTransport.(*http.Transport).DialContext\n\t}\n\tif opts == nil {\n\t\t// Do no filtering\n\t\treturn wrapped\n\t}\n\tif resolv == nil {\n\t\tresolv = net.DefaultResolver\n\t}\n\tif len(opts.DialHostCIDRDenylist) == 0 \u0026\u0026 opts.AllowLocalLoopback {\n\t\t// Do no filtering.\n\t\treturn wrapped\n\t}\n\treturn func(ctx context.Context, network, address string) (net.Conn, error) {\n\t\t// DialContext is given host:port. LookupIPAddress expects host.\n\t\taddressToResolve, _, err := net.SplitHostPort(address)\n\t\tif err != nil {\n\t\t\taddressToResolve = address\n\t\t}\n\n\t\tresp, err := resolv.LookupIPAddr(ctx, addressToResolve)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif len(resp) == 0 {\n\t\t\treturn nil, ErrNoAddresses\n\t\t}\n\n\t\tfor _, host := range resp {\n\t\t\tif !opts.AllowLocalLoopback {\n\t\t\t\tif err := isProxyableIP(host.IP); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif opts.DialHostCIDRDenylist != nil {\n\t\t\t\tif err := IsAllowedHost(host.IP, opts.DialHostCIDRDenylist); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn wrapped(ctx, network, address)\n\t}\n}","line":{"from":362,"to":408}} {"id":100008675,"name":"GetClusterIPByFamily","signature":"func GetClusterIPByFamily(ipFamily v1.IPFamily, service *v1.Service) string","file":"pkg/proxy/util/utils.go","code":"// GetClusterIPByFamily returns a service clusterip by family\nfunc GetClusterIPByFamily(ipFamily v1.IPFamily, service *v1.Service) string {\n\t// allowing skew\n\tif len(service.Spec.IPFamilies) == 0 {\n\t\tif len(service.Spec.ClusterIP) == 0 || service.Spec.ClusterIP == v1.ClusterIPNone {\n\t\t\treturn \"\"\n\t\t}\n\n\t\tIsIPv6Family := (ipFamily == v1.IPv6Protocol)\n\t\tif IsIPv6Family == netutils.IsIPv6String(service.Spec.ClusterIP) {\n\t\t\treturn service.Spec.ClusterIP\n\t\t}\n\n\t\treturn \"\"\n\t}\n\n\tfor idx, family := range service.Spec.IPFamilies {\n\t\tif family == ipFamily {\n\t\t\tif idx \u003c len(service.Spec.ClusterIPs) {\n\t\t\t\treturn service.Spec.ClusterIPs[idx]\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\"\n}","line":{"from":410,"to":435}} {"id":100008676,"name":"Write","signature":"func (buf *LineBuffer) Write(args ...interface{})","file":"pkg/proxy/util/utils.go","code":"// Write takes a list of arguments, each a string or []string, joins all the\n// individual strings with spaces, terminates with newline, and writes to buf.\n// Any other argument type will panic.\nfunc (buf *LineBuffer) Write(args ...interface{}) {\n\tfor i, arg := range args {\n\t\tif i \u003e 0 {\n\t\t\tbuf.b.WriteByte(' ')\n\t\t}\n\t\tswitch x := arg.(type) {\n\t\tcase string:\n\t\t\tbuf.b.WriteString(x)\n\t\tcase []string:\n\t\t\tfor j, s := range x {\n\t\t\t\tif j \u003e 0 {\n\t\t\t\t\tbuf.b.WriteByte(' ')\n\t\t\t\t}\n\t\t\t\tbuf.b.WriteString(s)\n\t\t\t}\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"unknown argument type: %T\", x))\n\t\t}\n\t}\n\tbuf.b.WriteByte('\\n')\n\tbuf.lines++\n}","line":{"from":442,"to":466}} {"id":100008677,"name":"WriteBytes","signature":"func (buf *LineBuffer) WriteBytes(bytes []byte)","file":"pkg/proxy/util/utils.go","code":"// WriteBytes writes bytes to buffer, and terminates with newline.\nfunc (buf *LineBuffer) WriteBytes(bytes []byte) {\n\tbuf.b.Write(bytes)\n\tbuf.b.WriteByte('\\n')\n\tbuf.lines++\n}","line":{"from":468,"to":473}} {"id":100008678,"name":"Reset","signature":"func (buf *LineBuffer) Reset()","file":"pkg/proxy/util/utils.go","code":"// Reset clears buf\nfunc (buf *LineBuffer) Reset() {\n\tbuf.b.Reset()\n\tbuf.lines = 0\n}","line":{"from":475,"to":479}} {"id":100008679,"name":"Bytes","signature":"func (buf *LineBuffer) Bytes() []byte","file":"pkg/proxy/util/utils.go","code":"// Bytes returns the contents of buf as a []byte\nfunc (buf *LineBuffer) Bytes() []byte {\n\treturn buf.b.Bytes()\n}","line":{"from":481,"to":484}} {"id":100008680,"name":"Lines","signature":"func (buf *LineBuffer) Lines() int","file":"pkg/proxy/util/utils.go","code":"// Lines returns the number of lines in buf. Note that more precisely, this returns the\n// number of times Write() or WriteBytes() was called; it assumes that you never wrote\n// any newlines to the buffer yourself.\nfunc (buf *LineBuffer) Lines() int {\n\treturn buf.lines\n}","line":{"from":486,"to":491}} {"id":100008681,"name":"RevertPorts","signature":"func RevertPorts(replacementPortsMap, originalPortsMap map[netutils.LocalPort]netutils.Closeable)","file":"pkg/proxy/util/utils.go","code":"// RevertPorts is closing ports in replacementPortsMap but not in originalPortsMap. In other words, it only\n// closes the ports opened in this sync.\nfunc RevertPorts(replacementPortsMap, originalPortsMap map[netutils.LocalPort]netutils.Closeable) {\n\tfor k, v := range replacementPortsMap {\n\t\t// Only close newly opened local ports - leave ones that were open before this update\n\t\tif originalPortsMap[k] == nil {\n\t\t\tklog.V(2).InfoS(\"Closing local port\", \"port\", k.String())\n\t\t\tv.Close()\n\t\t}\n\t}\n}","line":{"from":493,"to":503}} {"id":100008682,"name":"getNetworkByName","signature":"func (hns hns) getNetworkByName(name string) (*hnsNetworkInfo, error)","file":"pkg/proxy/winkernel/hns.go","code":"func (hns hns) getNetworkByName(name string) (*hnsNetworkInfo, error) {\n\thnsnetwork, err := hcn.GetNetworkByName(name)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Error getting network by name\")\n\t\treturn nil, err\n\t}\n\n\tvar remoteSubnets []*remoteSubnetInfo\n\tfor _, policy := range hnsnetwork.Policies {\n\t\tif policy.Type == hcn.RemoteSubnetRoute {\n\t\t\tpolicySettings := hcn.RemoteSubnetRoutePolicySetting{}\n\t\t\terr = json.Unmarshal(policy.Settings, \u0026policySettings)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to unmarshal Remote Subnet policy settings\")\n\t\t\t}\n\t\t\trs := \u0026remoteSubnetInfo{\n\t\t\t\tdestinationPrefix: policySettings.DestinationPrefix,\n\t\t\t\tisolationID: policySettings.IsolationId,\n\t\t\t\tproviderAddress: policySettings.ProviderAddress,\n\t\t\t\tdrMacAddress: policySettings.DistributedRouterMacAddress,\n\t\t\t}\n\t\t\tremoteSubnets = append(remoteSubnets, rs)\n\t\t}\n\t}\n\n\treturn \u0026hnsNetworkInfo{\n\t\tid: hnsnetwork.Id,\n\t\tname: hnsnetwork.Name,\n\t\tnetworkType: string(hnsnetwork.Type),\n\t\tremoteSubnets: remoteSubnets,\n\t}, nil\n}","line":{"from":55,"to":86}} {"id":100008683,"name":"getAllEndpointsByNetwork","signature":"func (hns hns) getAllEndpointsByNetwork(networkName string) (map[string]*(endpointsInfo), error)","file":"pkg/proxy/winkernel/hns.go","code":"func (hns hns) getAllEndpointsByNetwork(networkName string) (map[string]*(endpointsInfo), error) {\n\thcnnetwork, err := hcn.GetNetworkByName(networkName)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"failed to get HNS network by name\", \"name\", networkName)\n\t\treturn nil, err\n\t}\n\tendpoints, err := hcn.ListEndpointsOfNetwork(hcnnetwork.Id)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to list endpoints: %w\", err)\n\t}\n\tendpointInfos := make(map[string]*(endpointsInfo))\n\tfor _, ep := range endpoints {\n\n\t\tif len(ep.IpConfigurations) == 0 {\n\t\t\tklog.V(3).InfoS(\"No IpConfigurations found in endpoint info of queried endpoints\", \"endpoint\", ep)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Add to map with key endpoint ID or IP address\n\t\t// Storing this is expensive in terms of memory, however there is a bug in Windows Server 2019 that can cause two endpoints to be created with the same IP address.\n\t\t// TODO: Store by IP only and remove any lookups by endpoint ID.\n\t\tendpointInfos[ep.Id] = \u0026endpointsInfo{\n\t\t\tip: ep.IpConfigurations[0].IpAddress,\n\t\t\tisLocal: uint32(ep.Flags\u0026hcn.EndpointFlagsRemoteEndpoint) == 0,\n\t\t\tmacAddress: ep.MacAddress,\n\t\t\thnsID: ep.Id,\n\t\t\thns: hns,\n\t\t\t// only ready and not terminating endpoints were added to HNS\n\t\t\tready: true,\n\t\t\tserving: true,\n\t\t\tterminating: false,\n\t\t}\n\t\tendpointInfos[ep.IpConfigurations[0].IpAddress] = endpointInfos[ep.Id]\n\n\t\tif len(ep.IpConfigurations) == 1 {\n\t\t\tcontinue\n\t\t}\n\n\t\t// If ipFamilyPolicy is RequireDualStack or PreferDualStack, then there will be 2 IPS (iPV4 and IPV6)\n\t\t// in the endpoint list\n\t\tendpointDualstack := \u0026endpointsInfo{\n\t\t\tip: ep.IpConfigurations[1].IpAddress,\n\t\t\tisLocal: uint32(ep.Flags\u0026hcn.EndpointFlagsRemoteEndpoint) == 0,\n\t\t\tmacAddress: ep.MacAddress,\n\t\t\thnsID: ep.Id,\n\t\t\thns: hns,\n\t\t\t// only ready and not terminating endpoints were added to HNS\n\t\t\tready: true,\n\t\t\tserving: true,\n\t\t\tterminating: false,\n\t\t}\n\t\tendpointInfos[ep.IpConfigurations[1].IpAddress] = endpointDualstack\n\t}\n\tklog.V(3).InfoS(\"Queried endpoints from network\", \"network\", networkName)\n\tklog.V(5).InfoS(\"Queried endpoints details\", \"network\", networkName, \"endpointInfos\", endpointInfos)\n\treturn endpointInfos, nil\n}","line":{"from":88,"to":144}} {"id":100008684,"name":"getEndpointByID","signature":"func (hns hns) getEndpointByID(id string) (*endpointsInfo, error)","file":"pkg/proxy/winkernel/hns.go","code":"func (hns hns) getEndpointByID(id string) (*endpointsInfo, error) {\n\thnsendpoint, err := hcn.GetEndpointByID(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026endpointsInfo{ //TODO: fill out PA\n\t\tip: hnsendpoint.IpConfigurations[0].IpAddress,\n\t\tisLocal: uint32(hnsendpoint.Flags\u0026hcn.EndpointFlagsRemoteEndpoint) == 0, //TODO: Change isLocal to isRemote\n\t\tmacAddress: hnsendpoint.MacAddress,\n\t\thnsID: hnsendpoint.Id,\n\t\thns: hns,\n\t}, nil\n}","line":{"from":146,"to":158}} {"id":100008685,"name":"getEndpointByIpAddress","signature":"func (hns hns) getEndpointByIpAddress(ip string, networkName string) (*endpointsInfo, error)","file":"pkg/proxy/winkernel/hns.go","code":"func (hns hns) getEndpointByIpAddress(ip string, networkName string) (*endpointsInfo, error) {\n\thnsnetwork, err := hcn.GetNetworkByName(networkName)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Error getting network by name\")\n\t\treturn nil, err\n\t}\n\n\tendpoints, err := hcn.ListEndpoints()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to list endpoints: %w\", err)\n\t}\n\tfor _, endpoint := range endpoints {\n\t\tequal := false\n\t\tif endpoint.IpConfigurations != nil \u0026\u0026 len(endpoint.IpConfigurations) \u003e 0 {\n\t\t\tequal = endpoint.IpConfigurations[0].IpAddress == ip\n\n\t\t\tif !equal \u0026\u0026 len(endpoint.IpConfigurations) \u003e 1 {\n\t\t\t\tequal = endpoint.IpConfigurations[1].IpAddress == ip\n\t\t\t}\n\t\t}\n\t\tif equal \u0026\u0026 strings.EqualFold(endpoint.HostComputeNetwork, hnsnetwork.Id) {\n\t\t\treturn \u0026endpointsInfo{\n\t\t\t\tip: ip,\n\t\t\t\tisLocal: uint32(endpoint.Flags\u0026hcn.EndpointFlagsRemoteEndpoint) == 0, //TODO: Change isLocal to isRemote\n\t\t\t\tmacAddress: endpoint.MacAddress,\n\t\t\t\thnsID: endpoint.Id,\n\t\t\t\thns: hns,\n\t\t\t}, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"Endpoint %v not found on network %s\", ip, networkName)\n}","line":{"from":159,"to":190}} {"id":100008686,"name":"getEndpointByName","signature":"func (hns hns) getEndpointByName(name string) (*endpointsInfo, error)","file":"pkg/proxy/winkernel/hns.go","code":"func (hns hns) getEndpointByName(name string) (*endpointsInfo, error) {\n\thnsendpoint, err := hcn.GetEndpointByName(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026endpointsInfo{ //TODO: fill out PA\n\t\tip: hnsendpoint.IpConfigurations[0].IpAddress,\n\t\tisLocal: uint32(hnsendpoint.Flags\u0026hcn.EndpointFlagsRemoteEndpoint) == 0, //TODO: Change isLocal to isRemote\n\t\tmacAddress: hnsendpoint.MacAddress,\n\t\thnsID: hnsendpoint.Id,\n\t\thns: hns,\n\t}, nil\n}","line":{"from":191,"to":203}} {"id":100008687,"name":"createEndpoint","signature":"func (hns hns) createEndpoint(ep *endpointsInfo, networkName string) (*endpointsInfo, error)","file":"pkg/proxy/winkernel/hns.go","code":"func (hns hns) createEndpoint(ep *endpointsInfo, networkName string) (*endpointsInfo, error) {\n\thnsNetwork, err := hcn.GetNetworkByName(networkName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar flags hcn.EndpointFlags\n\tif !ep.isLocal {\n\t\tflags |= hcn.EndpointFlagsRemoteEndpoint\n\t}\n\tipConfig := \u0026hcn.IpConfig{\n\t\tIpAddress: ep.ip,\n\t}\n\thnsEndpoint := \u0026hcn.HostComputeEndpoint{\n\t\tIpConfigurations: []hcn.IpConfig{*ipConfig},\n\t\tMacAddress: ep.macAddress,\n\t\tFlags: flags,\n\t\tSchemaVersion: hcn.SchemaVersion{\n\t\t\tMajor: 2,\n\t\t\tMinor: 0,\n\t\t},\n\t}\n\n\tvar createdEndpoint *hcn.HostComputeEndpoint\n\tif !ep.isLocal {\n\t\tif len(ep.providerAddress) != 0 {\n\t\t\tpolicySettings := hcn.ProviderAddressEndpointPolicySetting{\n\t\t\t\tProviderAddress: ep.providerAddress,\n\t\t\t}\n\t\t\tpolicySettingsJson, err := json.Marshal(policySettings)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"PA Policy creation failed: %v\", err)\n\t\t\t}\n\t\t\tpaPolicy := hcn.EndpointPolicy{\n\t\t\t\tType: hcn.NetworkProviderAddress,\n\t\t\t\tSettings: policySettingsJson,\n\t\t\t}\n\t\t\thnsEndpoint.Policies = append(hnsEndpoint.Policies, paPolicy)\n\t\t}\n\t\tcreatedEndpoint, err = hnsNetwork.CreateRemoteEndpoint(hnsEndpoint)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tcreatedEndpoint, err = hnsNetwork.CreateEndpoint(hnsEndpoint)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn \u0026endpointsInfo{\n\t\tip: createdEndpoint.IpConfigurations[0].IpAddress,\n\t\tisLocal: uint32(createdEndpoint.Flags\u0026hcn.EndpointFlagsRemoteEndpoint) == 0,\n\t\tmacAddress: createdEndpoint.MacAddress,\n\t\thnsID: createdEndpoint.Id,\n\t\tproviderAddress: ep.providerAddress, //TODO get from createdEndpoint\n\t\thns: hns,\n\t}, nil\n}","line":{"from":204,"to":260}} {"id":100008688,"name":"deleteEndpoint","signature":"func (hns hns) deleteEndpoint(hnsID string) error","file":"pkg/proxy/winkernel/hns.go","code":"func (hns hns) deleteEndpoint(hnsID string) error {\n\thnsendpoint, err := hcn.GetEndpointByID(hnsID)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = hnsendpoint.Delete()\n\tif err == nil {\n\t\tklog.V(3).InfoS(\"Remote endpoint resource deleted\", \"hnsID\", hnsID)\n\t}\n\treturn err\n}","line":{"from":261,"to":271}} {"id":100008689,"name":"findLoadBalancerID","signature":"func findLoadBalancerID(endpoints []endpointsInfo, vip string, protocol, internalPort, externalPort uint16) (loadBalancerIdentifier, error)","file":"pkg/proxy/winkernel/hns.go","code":"// findLoadBalancerID will construct a id from the provided loadbalancer fields\nfunc findLoadBalancerID(endpoints []endpointsInfo, vip string, protocol, internalPort, externalPort uint16) (loadBalancerIdentifier, error) {\n\t// Compute hash from backends (endpoint IDs)\n\thash, err := hashEndpoints(endpoints)\n\tif err != nil {\n\t\tklog.V(2).ErrorS(err, \"Error hashing endpoints\", \"endpoints\", endpoints)\n\t\treturn loadBalancerIdentifier{}, err\n\t}\n\tif len(vip) \u003e 0 {\n\t\treturn loadBalancerIdentifier{protocol: protocol, internalPort: internalPort, externalPort: externalPort, vip: vip, endpointsHash: hash}, nil\n\t}\n\treturn loadBalancerIdentifier{protocol: protocol, internalPort: internalPort, externalPort: externalPort, endpointsHash: hash}, nil\n}","line":{"from":273,"to":285}} {"id":100008690,"name":"getAllLoadBalancers","signature":"func (hns hns) getAllLoadBalancers() (map[loadBalancerIdentifier]*loadBalancerInfo, error)","file":"pkg/proxy/winkernel/hns.go","code":"func (hns hns) getAllLoadBalancers() (map[loadBalancerIdentifier]*loadBalancerInfo, error) {\n\tlbs, err := hcn.ListLoadBalancers()\n\tvar id loadBalancerIdentifier\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tloadBalancers := make(map[loadBalancerIdentifier]*(loadBalancerInfo))\n\tfor _, lb := range lbs {\n\t\tportMap := lb.PortMappings[0]\n\t\t// Compute hash from backends (endpoint IDs)\n\t\thash, err := hashEndpoints(lb.HostComputeEndpoints)\n\t\tif err != nil {\n\t\t\tklog.V(2).ErrorS(err, \"Error hashing endpoints\", \"policy\", lb)\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(lb.FrontendVIPs) == 0 {\n\t\t\t// Leave VIP uninitialized\n\t\t\tid = loadBalancerIdentifier{protocol: uint16(portMap.Protocol), internalPort: portMap.InternalPort, externalPort: portMap.ExternalPort, endpointsHash: hash}\n\t\t} else {\n\t\t\tid = loadBalancerIdentifier{protocol: uint16(portMap.Protocol), internalPort: portMap.InternalPort, externalPort: portMap.ExternalPort, vip: lb.FrontendVIPs[0], endpointsHash: hash}\n\t\t}\n\t\tloadBalancers[id] = \u0026loadBalancerInfo{\n\t\t\thnsID: lb.Id,\n\t\t}\n\t}\n\tklog.V(3).InfoS(\"Queried load balancers\", \"count\", len(lbs))\n\treturn loadBalancers, nil\n}","line":{"from":287,"to":314}} {"id":100008691,"name":"getLoadBalancer","signature":"func (hns hns) getLoadBalancer(endpoints []endpointsInfo, flags loadBalancerFlags, sourceVip string, vip string, protocol uint16, internalPort uint16, externalPort uint16, previousLoadBalancers map[loadBalancerIdentifier]*loadBalancerInfo) (*loadBalancerInfo, error)","file":"pkg/proxy/winkernel/hns.go","code":"func (hns hns) getLoadBalancer(endpoints []endpointsInfo, flags loadBalancerFlags, sourceVip string, vip string, protocol uint16, internalPort uint16, externalPort uint16, previousLoadBalancers map[loadBalancerIdentifier]*loadBalancerInfo) (*loadBalancerInfo, error) {\n\tvar id loadBalancerIdentifier\n\tvips := []string{}\n\t// Compute hash from backends (endpoint IDs)\n\thash, err := hashEndpoints(endpoints)\n\tif err != nil {\n\t\tklog.V(2).ErrorS(err, \"Error hashing endpoints\", \"endpoints\", endpoints)\n\t\treturn nil, err\n\t}\n\tif len(vip) \u003e 0 {\n\t\tid = loadBalancerIdentifier{protocol: protocol, internalPort: internalPort, externalPort: externalPort, vip: vip, endpointsHash: hash}\n\t\tvips = append(vips, vip)\n\t} else {\n\t\tid = loadBalancerIdentifier{protocol: protocol, internalPort: internalPort, externalPort: externalPort, endpointsHash: hash}\n\t}\n\n\tif lb, found := previousLoadBalancers[id]; found {\n\t\tklog.V(1).InfoS(\"Found cached Hns loadbalancer policy resource\", \"policies\", lb)\n\t\treturn lb, nil\n\t}\n\n\tlbPortMappingFlags := hcn.LoadBalancerPortMappingFlagsNone\n\tif flags.isILB {\n\t\tlbPortMappingFlags |= hcn.LoadBalancerPortMappingFlagsILB\n\t}\n\tif flags.useMUX {\n\t\tlbPortMappingFlags |= hcn.LoadBalancerPortMappingFlagsUseMux\n\t}\n\tif flags.preserveDIP {\n\t\tlbPortMappingFlags |= hcn.LoadBalancerPortMappingFlagsPreserveDIP\n\t}\n\tif flags.localRoutedVIP {\n\t\tlbPortMappingFlags |= hcn.LoadBalancerPortMappingFlagsLocalRoutedVIP\n\t}\n\tif flags.isVipExternalIP {\n\t\tlbPortMappingFlags |= LoadBalancerPortMappingFlagsVipExternalIP\n\t}\n\n\tlbFlags := hcn.LoadBalancerFlagsNone\n\tif flags.isDSR {\n\t\tlbFlags |= hcn.LoadBalancerFlagsDSR\n\t}\n\n\tif flags.isIPv6 {\n\t\tlbFlags |= LoadBalancerFlagsIPv6\n\t}\n\n\tlbDistributionType := hcn.LoadBalancerDistributionNone\n\n\tif flags.sessionAffinity {\n\t\tlbDistributionType = hcn.LoadBalancerDistributionSourceIP\n\t}\n\n\tloadBalancer := \u0026hcn.HostComputeLoadBalancer{\n\t\tSourceVIP: sourceVip,\n\t\tPortMappings: []hcn.LoadBalancerPortMapping{\n\t\t\t{\n\t\t\t\tProtocol: uint32(protocol),\n\t\t\t\tInternalPort: internalPort,\n\t\t\t\tExternalPort: externalPort,\n\t\t\t\tDistributionType: lbDistributionType,\n\t\t\t\tFlags: lbPortMappingFlags,\n\t\t\t},\n\t\t},\n\t\tFrontendVIPs: vips,\n\t\tSchemaVersion: hcn.SchemaVersion{\n\t\t\tMajor: 2,\n\t\t\tMinor: 0,\n\t\t},\n\t\tFlags: lbFlags,\n\t}\n\n\tfor _, ep := range endpoints {\n\t\tloadBalancer.HostComputeEndpoints = append(loadBalancer.HostComputeEndpoints, ep.hnsID)\n\t}\n\n\tlb, err := loadBalancer.Create()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tklog.V(1).InfoS(\"Created Hns loadbalancer policy resource\", \"loadBalancer\", lb)\n\tlbInfo := \u0026loadBalancerInfo{\n\t\thnsID: lb.Id,\n\t}\n\t// Add to map of load balancers\n\tpreviousLoadBalancers[id] = lbInfo\n\treturn lbInfo, err\n}","line":{"from":316,"to":405}} {"id":100008692,"name":"deleteLoadBalancer","signature":"func (hns hns) deleteLoadBalancer(hnsID string) error","file":"pkg/proxy/winkernel/hns.go","code":"func (hns hns) deleteLoadBalancer(hnsID string) error {\n\tlb, err := hcn.GetLoadBalancerByID(hnsID)\n\tif err != nil {\n\t\t// Return silently\n\t\treturn nil\n\t}\n\n\terr = lb.Delete()\n\tif err != nil {\n\t\t// There is a bug in Windows Server 2019, that can cause the delete call to fail sometimes. We retry one more time.\n\t\t// TODO: The logic in syncProxyRules should be rewritten in the future to better stage and handle a call like this failing using the policyApplied fields.\n\t\tklog.V(1).ErrorS(err, \"Error deleting Hns loadbalancer policy resource. Attempting one more time...\", \"loadBalancer\", lb)\n\t\treturn lb.Delete()\n\t}\n\treturn err\n}","line":{"from":407,"to":422}} {"id":100008693,"name":"hashEndpoints","signature":"func hashEndpoints[T string | endpointsInfo](endpoints []T) (hash [20]byte, err error)","file":"pkg/proxy/winkernel/hns.go","code":"// Calculates a hash from the given endpoint IDs.\nfunc hashEndpoints[T string | endpointsInfo](endpoints []T) (hash [20]byte, err error) {\n\tvar id string\n\t// Recover in case something goes wrong. Return error and null byte array.\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = r.(error)\n\t\t\thash = [20]byte{}\n\t\t}\n\t}()\n\n\t// Iterate over endpoints, compute hash\n\tfor _, ep := range endpoints {\n\t\tswitch x := any(ep).(type) {\n\t\tcase endpointsInfo:\n\t\t\tid = strings.ToUpper(x.hnsID)\n\t\tcase string:\n\t\t\tid = x\n\t\t}\n\t\tif len(id) \u003e 0 {\n\t\t\t// We XOR the hashes of endpoints, since they are an unordered set.\n\t\t\t// This can cause collisions, but is sufficient since we are using other keys to identify the load balancer.\n\t\t\thash = xor(hash, sha1.Sum(([]byte(id))))\n\t\t}\n\t}\n\treturn\n}","line":{"from":424,"to":450}} {"id":100008694,"name":"xor","signature":"func xor(b1 [20]byte, b2 [20]byte) (xorbytes [20]byte)","file":"pkg/proxy/winkernel/hns.go","code":"func xor(b1 [20]byte, b2 [20]byte) (xorbytes [20]byte) {\n\tfor i := 0; i \u003c 20; i++ {\n\t\txorbytes[i] = b1[i] ^ b2[i]\n\t}\n\treturn xorbytes\n}","line":{"from":452,"to":457}} {"id":100008695,"name":"RegisterMetrics","signature":"func RegisterMetrics()","file":"pkg/proxy/winkernel/metrics.go","code":"// RegisterMetrics registers kube-proxy metrics for Windows modes.\nfunc RegisterMetrics() {\n\tregisterMetricsOnce.Do(func() {\n\t\tlegacyregistry.MustRegister(metrics.SyncProxyRulesLatency)\n\t\tlegacyregistry.MustRegister(metrics.SyncProxyRulesLastTimestamp)\n\t\tlegacyregistry.MustRegister(metrics.EndpointChangesPending)\n\t\tlegacyregistry.MustRegister(metrics.EndpointChangesTotal)\n\t\tlegacyregistry.MustRegister(metrics.ServiceChangesPending)\n\t\tlegacyregistry.MustRegister(metrics.ServiceChangesTotal)\n\t\tlegacyregistry.MustRegister(metrics.SyncProxyRulesLastQueuedTimestamp)\n\t})\n}","line":{"from":28,"to":39}} {"id":100008696,"name":"CanUseWinKernelProxier","signature":"func CanUseWinKernelProxier(kcompat KernelCompatTester) (bool, error)","file":"pkg/proxy/winkernel/proxier.go","code":"// CanUseWinKernelProxier returns true if we should use the Kernel Proxier\n// instead of the \"classic\" userspace Proxier. This is determined by checking\n// the windows kernel version and for the existence of kernel features.\nfunc CanUseWinKernelProxier(kcompat KernelCompatTester) (bool, error) {\n\t// Check that the kernel supports what we need.\n\tif err := kcompat.IsCompatible(); err != nil {\n\t\treturn false, err\n\t}\n\treturn true, nil\n}","line":{"from":63,"to":72}} {"id":100008697,"name":"IsCompatible","signature":"func (lkct WindowsKernelCompatTester) IsCompatible() error","file":"pkg/proxy/winkernel/proxier.go","code":"// IsCompatible returns true if winkernel can support this mode of proxy\nfunc (lkct WindowsKernelCompatTester) IsCompatible() error {\n\t_, err := hcsshim.HNSListPolicyListRequest()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Windows kernel is not compatible for Kernel mode\")\n\t}\n\treturn nil\n}","line":{"from":76,"to":83}} {"id":100008698,"name":"newHostNetworkService","signature":"func newHostNetworkService() (HostNetworkService, hcn.SupportedFeatures)","file":"pkg/proxy/winkernel/proxier.go","code":"func newHostNetworkService() (HostNetworkService, hcn.SupportedFeatures) {\n\tvar h HostNetworkService\n\tsupportedFeatures := hcn.GetSupportedFeatures()\n\tif supportedFeatures.Api.V2 {\n\t\th = hns{}\n\t} else {\n\t\tpanic(\"Windows HNS Api V2 required. This version of windows does not support API V2\")\n\t}\n\treturn h, supportedFeatures\n}","line":{"from":157,"to":166}} {"id":100008699,"name":"logFormattedEndpoints","signature":"func logFormattedEndpoints(logMsg string, logLevel klog.Level, svcPortName proxy.ServicePortName, eps []proxy.Endpoint)","file":"pkg/proxy/winkernel/proxier.go","code":"// logFormattedEndpoints will log all endpoints and its states which are taking part in endpointmap change.\n// This mostly for debugging purpose and verbosity is set to 5.\nfunc logFormattedEndpoints(logMsg string, logLevel klog.Level, svcPortName proxy.ServicePortName, eps []proxy.Endpoint) {\n\tif klog.V(logLevel).Enabled() {\n\t\tvar epInfo string\n\t\tfor _, v := range eps {\n\t\t\tepInfo = epInfo + fmt.Sprintf(\"\\n %s={Ready:%v,Serving:%v,Terminating:%v,IsRemote:%v}\", v.String(), v.IsReady(), v.IsServing(), v.IsTerminating(), !v.GetIsLocal())\n\t\t}\n\t\tklog.V(logLevel).InfoS(logMsg, \"svcPortName\", svcPortName, \"endpoints\", epInfo)\n\t}\n}","line":{"from":168,"to":178}} {"id":100008700,"name":"cleanupStaleLoadbalancers","signature":"func (proxier *Proxier) cleanupStaleLoadbalancers()","file":"pkg/proxy/winkernel/proxier.go","code":"// This will cleanup stale load balancers which are pending delete\n// in last iteration. This function will act like a self healing of stale\n// loadbalancer entries.\nfunc (proxier *Proxier) cleanupStaleLoadbalancers() {\n\ti := 0\n\tcountStaleLB := len(proxier.mapStaleLoadbalancers)\n\tif countStaleLB == 0 {\n\t\treturn\n\t}\n\tklog.V(3).InfoS(\"Cleanup of stale loadbalancers triggered\", \"LB Count\", countStaleLB)\n\tfor lbID := range proxier.mapStaleLoadbalancers {\n\t\ti++\n\t\tif err := proxier.hns.deleteLoadBalancer(lbID); err == nil {\n\t\t\tdelete(proxier.mapStaleLoadbalancers, lbID)\n\t\t}\n\t\tif i == MAX_COUNT_STALE_LOADBALANCERS {\n\t\t\t// The remaining stale loadbalancers will be cleaned up in next iteration\n\t\t\tbreak\n\t\t}\n\t}\n\tcountStaleLB = len(proxier.mapStaleLoadbalancers)\n\tif countStaleLB \u003e 0 {\n\t\tklog.V(3).InfoS(\"Stale loadbalancers still remaining\", \"LB Count\", countStaleLB, \"stale_lb_ids\", proxier.mapStaleLoadbalancers)\n\t}\n}","line":{"from":180,"to":204}} {"id":100008701,"name":"getNetworkName","signature":"func getNetworkName(hnsNetworkName string) (string, error)","file":"pkg/proxy/winkernel/proxier.go","code":"func getNetworkName(hnsNetworkName string) (string, error) {\n\tif len(hnsNetworkName) == 0 {\n\t\tklog.V(3).InfoS(\"Flag --network-name not set, checking environment variable\")\n\t\thnsNetworkName = os.Getenv(\"KUBE_NETWORK\")\n\t\tif len(hnsNetworkName) == 0 {\n\t\t\treturn \"\", fmt.Errorf(\"Environment variable KUBE_NETWORK and network-flag not initialized\")\n\t\t}\n\t}\n\treturn hnsNetworkName, nil\n}","line":{"from":206,"to":215}} {"id":100008702,"name":"getNetworkInfo","signature":"func getNetworkInfo(hns HostNetworkService, hnsNetworkName string) (*hnsNetworkInfo, error)","file":"pkg/proxy/winkernel/proxier.go","code":"func getNetworkInfo(hns HostNetworkService, hnsNetworkName string) (*hnsNetworkInfo, error) {\n\thnsNetworkInfo, err := hns.getNetworkByName(hnsNetworkName)\n\tfor err != nil {\n\t\tklog.ErrorS(err, \"Unable to find HNS Network specified, please check network name and CNI deployment\", \"hnsNetworkName\", hnsNetworkName)\n\t\ttime.Sleep(1 * time.Second)\n\t\thnsNetworkInfo, err = hns.getNetworkByName(hnsNetworkName)\n\t}\n\treturn hnsNetworkInfo, err\n}","line":{"from":217,"to":225}} {"id":100008703,"name":"isOverlay","signature":"func isOverlay(hnsNetworkInfo *hnsNetworkInfo) bool","file":"pkg/proxy/winkernel/proxier.go","code":"func isOverlay(hnsNetworkInfo *hnsNetworkInfo) bool {\n\treturn strings.EqualFold(hnsNetworkInfo.networkType, NETWORK_TYPE_OVERLAY)\n}","line":{"from":227,"to":229}} {"id":100008704,"name":"DualStackCompatible","signature":"func (t DualStackCompatTester) DualStackCompatible(networkName string) bool","file":"pkg/proxy/winkernel/proxier.go","code":"func (t DualStackCompatTester) DualStackCompatible(networkName string) bool {\n\t// First tag of hcsshim that has a proper check for dual stack support is v0.8.22 due to a bug.\n\tif err := hcn.IPv6DualStackSupported(); err != nil {\n\t\t// Hcn *can* fail the query to grab the version of hcn itself (which this call will do internally before parsing\n\t\t// to see if dual stack is supported), but the only time this can happen, at least that can be discerned, is if the host\n\t\t// is pre-1803 and hcn didn't exist. hcsshim should truthfully return a known error if this happened that we can\n\t\t// check against, and the case where 'err != this known error' would be the 'this feature isn't supported' case, as is being\n\t\t// used here. For now, seeming as how nothing before ws2019 (1809) is listed as supported for k8s we can pretty much assume\n\t\t// any error here isn't because the query failed, it's just that dualstack simply isn't supported on the host. With all\n\t\t// that in mind, just log as info and not error to let the user know we're falling back.\n\t\tklog.InfoS(\"This version of Windows does not support dual-stack, falling back to single-stack\", \"err\", err.Error())\n\t\treturn false\n\t}\n\n\t// check if network is using overlay\n\thns, _ := newHostNetworkService()\n\tnetworkName, err := getNetworkName(networkName)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Unable to determine dual-stack status, falling back to single-stack\")\n\t\treturn false\n\t}\n\tnetworkInfo, err := getNetworkInfo(hns, networkName)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Unable to determine dual-stack status, falling back to single-stack\")\n\t\treturn false\n\t}\n\n\tif utilfeature.DefaultFeatureGate.Enabled(kubefeatures.WinOverlay) \u0026\u0026 isOverlay(networkInfo) {\n\t\t// Overlay (VXLAN) networks on Windows do not support dual-stack networking today\n\t\tklog.InfoS(\"Winoverlay does not support dual-stack, falling back to single-stack\")\n\t\treturn false\n\t}\n\n\treturn true\n}","line":{"from":238,"to":272}} {"id":100008705,"name":"String","signature":"func (info *endpointsInfo) String() string","file":"pkg/proxy/winkernel/proxier.go","code":"// String is part of proxy.Endpoint interface.\nfunc (info *endpointsInfo) String() string {\n\treturn net.JoinHostPort(info.ip, strconv.Itoa(int(info.port)))\n}","line":{"from":291,"to":294}} {"id":100008706,"name":"GetIsLocal","signature":"func (info *endpointsInfo) GetIsLocal() bool","file":"pkg/proxy/winkernel/proxier.go","code":"// GetIsLocal is part of proxy.Endpoint interface.\nfunc (info *endpointsInfo) GetIsLocal() bool {\n\treturn info.isLocal\n}","line":{"from":296,"to":299}} {"id":100008707,"name":"IsReady","signature":"func (info *endpointsInfo) IsReady() bool","file":"pkg/proxy/winkernel/proxier.go","code":"// IsReady returns true if an endpoint is ready and not terminating.\nfunc (info *endpointsInfo) IsReady() bool {\n\treturn info.ready\n}","line":{"from":301,"to":304}} {"id":100008708,"name":"IsServing","signature":"func (info *endpointsInfo) IsServing() bool","file":"pkg/proxy/winkernel/proxier.go","code":"// IsServing returns true if an endpoint is ready, regardless of it's terminating state.\nfunc (info *endpointsInfo) IsServing() bool {\n\treturn info.serving\n}","line":{"from":306,"to":309}} {"id":100008709,"name":"IsTerminating","signature":"func (info *endpointsInfo) IsTerminating() bool","file":"pkg/proxy/winkernel/proxier.go","code":"// IsTerminating returns true if an endpoint is terminating.\nfunc (info *endpointsInfo) IsTerminating() bool {\n\treturn info.terminating\n}","line":{"from":311,"to":314}} {"id":100008710,"name":"GetZoneHints","signature":"func (info *endpointsInfo) GetZoneHints() sets.String","file":"pkg/proxy/winkernel/proxier.go","code":"// GetZoneHint returns the zone hint for the endpoint.\nfunc (info *endpointsInfo) GetZoneHints() sets.String {\n\treturn sets.String{}\n}","line":{"from":316,"to":319}} {"id":100008711,"name":"IP","signature":"func (info *endpointsInfo) IP() string","file":"pkg/proxy/winkernel/proxier.go","code":"// IP returns just the IP part of the endpoint, it's a part of proxy.Endpoint interface.\nfunc (info *endpointsInfo) IP() string {\n\treturn info.ip\n}","line":{"from":321,"to":324}} {"id":100008712,"name":"Port","signature":"func (info *endpointsInfo) Port() (int, error)","file":"pkg/proxy/winkernel/proxier.go","code":"// Port returns just the Port part of the endpoint.\nfunc (info *endpointsInfo) Port() (int, error) {\n\treturn int(info.port), nil\n}","line":{"from":326,"to":329}} {"id":100008713,"name":"Equal","signature":"func (info *endpointsInfo) Equal(other proxy.Endpoint) bool","file":"pkg/proxy/winkernel/proxier.go","code":"// Equal is part of proxy.Endpoint interface.\nfunc (info *endpointsInfo) Equal(other proxy.Endpoint) bool {\n\treturn info.String() == other.String() \u0026\u0026 info.GetIsLocal() == other.GetIsLocal()\n}","line":{"from":331,"to":334}} {"id":100008714,"name":"GetNodeName","signature":"func (info *endpointsInfo) GetNodeName() string","file":"pkg/proxy/winkernel/proxier.go","code":"// GetNodeName returns the NodeName for this endpoint.\nfunc (info *endpointsInfo) GetNodeName() string {\n\treturn \"\"\n}","line":{"from":336,"to":339}} {"id":100008715,"name":"GetZone","signature":"func (info *endpointsInfo) GetZone() string","file":"pkg/proxy/winkernel/proxier.go","code":"// GetZone returns the Zone for this endpoint.\nfunc (info *endpointsInfo) GetZone() string {\n\treturn \"\"\n}","line":{"from":341,"to":344}} {"id":100008716,"name":"conjureMac","signature":"func conjureMac(macPrefix string, ip net.IP) string","file":"pkg/proxy/winkernel/proxier.go","code":"// Uses mac prefix and IPv4 address to return a mac address\n// This ensures mac addresses are unique for proper load balancing\n// There is a possibility of MAC collisions but this Mac address is used for remote endpoints only\n// and not sent on the wire.\nfunc conjureMac(macPrefix string, ip net.IP) string {\n\tif ip4 := ip.To4(); ip4 != nil {\n\t\ta, b, c, d := ip4[0], ip4[1], ip4[2], ip4[3]\n\t\treturn fmt.Sprintf(\"%v-%02x-%02x-%02x-%02x\", macPrefix, a, b, c, d)\n\t} else if ip6 := ip.To16(); ip6 != nil {\n\t\ta, b, c, d := ip6[15], ip6[14], ip6[13], ip6[12]\n\t\treturn fmt.Sprintf(\"%v-%02x-%02x-%02x-%02x\", macPrefix, a, b, c, d)\n\t}\n\treturn \"02-11-22-33-44-55\"\n}","line":{"from":346,"to":359}} {"id":100008717,"name":"endpointsMapChange","signature":"func (proxier *Proxier) endpointsMapChange(oldEndpointsMap, newEndpointsMap proxy.EndpointsMap)","file":"pkg/proxy/winkernel/proxier.go","code":"func (proxier *Proxier) endpointsMapChange(oldEndpointsMap, newEndpointsMap proxy.EndpointsMap) {\n\t// This will optimize remote endpoint and loadbalancer deletion based on the annotation\n\tvar svcPortMap = make(map[proxy.ServicePortName]bool)\n\tvar logLevel klog.Level = 5\n\tfor svcPortName, eps := range oldEndpointsMap {\n\t\tlogFormattedEndpoints(\"endpointsMapChange oldEndpointsMap\", logLevel, svcPortName, eps)\n\t\tsvcPortMap[svcPortName] = true\n\t\tproxier.onEndpointsMapChange(\u0026svcPortName, false)\n\t}\n\n\tfor svcPortName, eps := range newEndpointsMap {\n\t\tlogFormattedEndpoints(\"endpointsMapChange newEndpointsMap\", logLevel, svcPortName, eps)\n\t\t// redundantCleanup true means cleanup is called second time on the same svcPort\n\t\tredundantCleanup := svcPortMap[svcPortName]\n\t\tproxier.onEndpointsMapChange(\u0026svcPortName, redundantCleanup)\n\t}\n}","line":{"from":361,"to":377}} {"id":100008718,"name":"onEndpointsMapChange","signature":"func (proxier *Proxier) onEndpointsMapChange(svcPortName *proxy.ServicePortName, redundantCleanup bool)","file":"pkg/proxy/winkernel/proxier.go","code":"func (proxier *Proxier) onEndpointsMapChange(svcPortName *proxy.ServicePortName, redundantCleanup bool) {\n\n\tsvc, exists := proxier.svcPortMap[*svcPortName]\n\n\tif exists {\n\t\tsvcInfo, ok := svc.(*serviceInfo)\n\n\t\tif !ok {\n\t\t\tklog.ErrorS(nil, \"Failed to cast serviceInfo\", \"servicePortName\", svcPortName)\n\t\t\treturn\n\t\t}\n\n\t\tif svcInfo.winProxyOptimization \u0026\u0026 redundantCleanup {\n\t\t\t// This is a second cleanup call.\n\t\t\t// Second cleanup on the same svcPort will be ignored if the\n\t\t\t// winProxyOptimization is Enabled\n\t\t\treturn\n\t\t}\n\n\t\tklog.V(3).InfoS(\"Endpoints are modified. Service is stale\", \"servicePortName\", svcPortName)\n\t\tsvcInfo.cleanupAllPolicies(proxier.endpointsMap[*svcPortName], proxier.mapStaleLoadbalancers, true)\n\t} else {\n\t\t// If no service exists, just cleanup the remote endpoints\n\t\tklog.V(3).InfoS(\"Endpoints are orphaned, cleaning up\")\n\t\t// Cleanup Endpoints references\n\t\tepInfos, exists := proxier.endpointsMap[*svcPortName]\n\n\t\tif exists {\n\t\t\t// Cleanup Endpoints references\n\t\t\tfor _, ep := range epInfos {\n\t\t\t\tepInfo, ok := ep.(*endpointsInfo)\n\n\t\t\t\tif ok {\n\t\t\t\t\tepInfo.Cleanup()\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":379,"to":418}} {"id":100008719,"name":"serviceMapChange","signature":"func (proxier *Proxier) serviceMapChange(previous, current proxy.ServicePortMap)","file":"pkg/proxy/winkernel/proxier.go","code":"func (proxier *Proxier) serviceMapChange(previous, current proxy.ServicePortMap) {\n\tfor svcPortName := range current {\n\t\tproxier.onServiceMapChange(\u0026svcPortName)\n\t}\n\n\tfor svcPortName := range previous {\n\t\tif _, ok := current[svcPortName]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tproxier.onServiceMapChange(\u0026svcPortName)\n\t}\n}","line":{"from":420,"to":431}} {"id":100008720,"name":"onServiceMapChange","signature":"func (proxier *Proxier) onServiceMapChange(svcPortName *proxy.ServicePortName)","file":"pkg/proxy/winkernel/proxier.go","code":"func (proxier *Proxier) onServiceMapChange(svcPortName *proxy.ServicePortName) {\n\n\tsvc, exists := proxier.svcPortMap[*svcPortName]\n\n\tif exists {\n\t\tsvcInfo, ok := svc.(*serviceInfo)\n\n\t\tif !ok {\n\t\t\tklog.ErrorS(nil, \"Failed to cast serviceInfo\", \"servicePortName\", svcPortName)\n\t\t\treturn\n\t\t}\n\n\t\tklog.V(3).InfoS(\"Updating existing service port\", \"servicePortName\", svcPortName, \"clusterIP\", svcInfo.ClusterIP(), \"port\", svcInfo.Port(), \"protocol\", svcInfo.Protocol())\n\t\tsvcInfo.cleanupAllPolicies(proxier.endpointsMap[*svcPortName], proxier.mapStaleLoadbalancers, false)\n\t}\n}","line":{"from":433,"to":448}} {"id":100008721,"name":"newEndpointInfo","signature":"func (proxier *Proxier) newEndpointInfo(baseInfo *proxy.BaseEndpointInfo, _ *proxy.ServicePortName) proxy.Endpoint","file":"pkg/proxy/winkernel/proxier.go","code":"// returns a new proxy.Endpoint which abstracts a endpointsInfo\nfunc (proxier *Proxier) newEndpointInfo(baseInfo *proxy.BaseEndpointInfo, _ *proxy.ServicePortName) proxy.Endpoint {\n\n\tportNumber, err := baseInfo.Port()\n\n\tif err != nil {\n\t\tportNumber = 0\n\t}\n\n\tinfo := \u0026endpointsInfo{\n\t\tip: baseInfo.IP(),\n\t\tport: uint16(portNumber),\n\t\tisLocal: baseInfo.GetIsLocal(),\n\t\tmacAddress: conjureMac(\"02-11\", netutils.ParseIPSloppy(baseInfo.IP())),\n\t\trefCount: new(uint16),\n\t\thnsID: \"\",\n\t\thns: proxier.hns,\n\n\t\tready: baseInfo.Ready,\n\t\tserving: baseInfo.Serving,\n\t\tterminating: baseInfo.Terminating,\n\t}\n\n\treturn info\n}","line":{"from":450,"to":474}} {"id":100008722,"name":"newSourceVIP","signature":"func newSourceVIP(hns HostNetworkService, network string, ip string, mac string, providerAddress string) (*endpointsInfo, error)","file":"pkg/proxy/winkernel/proxier.go","code":"func newSourceVIP(hns HostNetworkService, network string, ip string, mac string, providerAddress string) (*endpointsInfo, error) {\n\thnsEndpoint := \u0026endpointsInfo{\n\t\tip: ip,\n\t\tisLocal: true,\n\t\tmacAddress: mac,\n\t\tproviderAddress: providerAddress,\n\n\t\tready: true,\n\t\tserving: true,\n\t\tterminating: false,\n\t}\n\tep, err := hns.createEndpoint(hnsEndpoint, network)\n\treturn ep, err\n}","line":{"from":476,"to":489}} {"id":100008723,"name":"DecrementRefCount","signature":"func (ep *endpointsInfo) DecrementRefCount()","file":"pkg/proxy/winkernel/proxier.go","code":"func (ep *endpointsInfo) DecrementRefCount() {\n\tklog.V(3).InfoS(\"Decrementing Endpoint RefCount\", \"endpointsInfo\", ep)\n\tif !ep.GetIsLocal() \u0026\u0026 ep.refCount != nil \u0026\u0026 *ep.refCount \u003e 0 {\n\t\t*ep.refCount--\n\t}\n}","line":{"from":491,"to":496}} {"id":100008724,"name":"Cleanup","signature":"func (ep *endpointsInfo) Cleanup()","file":"pkg/proxy/winkernel/proxier.go","code":"func (ep *endpointsInfo) Cleanup() {\n\tklog.V(3).InfoS(\"Endpoint cleanup\", \"endpointsInfo\", ep)\n\tif !ep.GetIsLocal() \u0026\u0026 ep.refCount != nil {\n\t\t*ep.refCount--\n\n\t\t// Remove the remote hns endpoint, if no service is referring it\n\t\t// Never delete a Local Endpoint. Local Endpoints are already created by other entities.\n\t\t// Remove only remote endpoints created by this service\n\t\tif *ep.refCount \u003c= 0 \u0026\u0026 !ep.GetIsLocal() {\n\t\t\tklog.V(4).InfoS(\"Removing endpoints, since no one is referencing it\", \"endpoint\", ep)\n\t\t\terr := ep.hns.deleteEndpoint(ep.hnsID)\n\t\t\tif err == nil {\n\t\t\t\tep.hnsID = \"\"\n\t\t\t} else {\n\t\t\t\tklog.ErrorS(err, \"Endpoint deletion failed\", \"ip\", ep.IP())\n\t\t\t}\n\t\t}\n\n\t\tep.refCount = nil\n\t}\n}","line":{"from":498,"to":518}} {"id":100008725,"name":"getRefCount","signature":"func (refCountMap endPointsReferenceCountMap) getRefCount(hnsID string) *uint16","file":"pkg/proxy/winkernel/proxier.go","code":"func (refCountMap endPointsReferenceCountMap) getRefCount(hnsID string) *uint16 {\n\trefCount, exists := refCountMap[hnsID]\n\tif !exists {\n\t\trefCountMap[hnsID] = new(uint16)\n\t\trefCount = refCountMap[hnsID]\n\t}\n\treturn refCount\n}","line":{"from":520,"to":527}} {"id":100008726,"name":"newServiceInfo","signature":"func (proxier *Proxier) newServiceInfo(port *v1.ServicePort, service *v1.Service, bsvcPortInfo *proxy.BaseServicePortInfo) proxy.ServicePort","file":"pkg/proxy/winkernel/proxier.go","code":"// returns a new proxy.ServicePort which abstracts a serviceInfo\nfunc (proxier *Proxier) newServiceInfo(port *v1.ServicePort, service *v1.Service, bsvcPortInfo *proxy.BaseServicePortInfo) proxy.ServicePort {\n\tinfo := \u0026serviceInfo{BaseServicePortInfo: bsvcPortInfo}\n\tpreserveDIP := service.Annotations[\"preserve-destination\"] == \"true\"\n\t// Annotation introduced to enable optimized loadbalancing\n\twinProxyOptimization := !(strings.ToUpper(service.Annotations[\"winProxyOptimization\"]) == \"DISABLED\")\n\tlocalTrafficDSR := service.Spec.ExternalTrafficPolicy == v1.ServiceExternalTrafficPolicyLocal\n\tvar internalTrafficLocal bool\n\tif service.Spec.InternalTrafficPolicy != nil {\n\t\tinternalTrafficLocal = *service.Spec.InternalTrafficPolicy == v1.ServiceInternalTrafficPolicyLocal\n\t}\n\terr := hcn.DSRSupported()\n\tif err != nil {\n\t\tpreserveDIP = false\n\t\tlocalTrafficDSR = false\n\t}\n\t// targetPort is zero if it is specified as a name in port.TargetPort.\n\t// Its real value would be got later from endpoints.\n\ttargetPort := 0\n\tif port.TargetPort.Type == intstr.Int {\n\t\ttargetPort = port.TargetPort.IntValue()\n\t}\n\n\tinfo.preserveDIP = preserveDIP\n\tinfo.targetPort = targetPort\n\tinfo.hns = proxier.hns\n\tinfo.localTrafficDSR = localTrafficDSR\n\tinfo.internalTrafficLocal = internalTrafficLocal\n\tinfo.winProxyOptimization = winProxyOptimization\n\tklog.V(3).InfoS(\"Flags enabled for service\", \"service\", service.Name, \"localTrafficDSR\", localTrafficDSR, \"internalTrafficLocal\", internalTrafficLocal, \"preserveDIP\", preserveDIP, \"winProxyOptimization\", winProxyOptimization)\n\n\tfor _, eip := range service.Spec.ExternalIPs {\n\t\tinfo.externalIPs = append(info.externalIPs, \u0026externalIPInfo{ip: eip})\n\t}\n\n\tfor _, ingress := range service.Status.LoadBalancer.Ingress {\n\t\tif netutils.ParseIPSloppy(ingress.IP) != nil {\n\t\t\tinfo.loadBalancerIngressIPs = append(info.loadBalancerIngressIPs, \u0026loadBalancerIngressInfo{ip: ingress.IP})\n\t\t}\n\t}\n\treturn info\n}","line":{"from":529,"to":570}} {"id":100008727,"name":"findRemoteSubnetProviderAddress","signature":"func (network hnsNetworkInfo) findRemoteSubnetProviderAddress(ip string) string","file":"pkg/proxy/winkernel/proxier.go","code":"func (network hnsNetworkInfo) findRemoteSubnetProviderAddress(ip string) string {\n\tvar providerAddress string\n\tfor _, rs := range network.remoteSubnets {\n\t\t_, ipNet, err := netutils.ParseCIDRSloppy(rs.destinationPrefix)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to parse CIDR\")\n\t\t}\n\t\tif ipNet.Contains(netutils.ParseIPSloppy(ip)) {\n\t\t\tproviderAddress = rs.providerAddress\n\t\t}\n\t\tif ip == rs.providerAddress {\n\t\t\tproviderAddress = rs.providerAddress\n\t\t}\n\t}\n\n\treturn providerAddress\n}","line":{"from":572,"to":588}} {"id":100008728,"name":"String","signature":"func (lp *localPort) String() string","file":"pkg/proxy/winkernel/proxier.go","code":"func (lp *localPort) String() string {\n\treturn fmt.Sprintf(\"%q (%s:%d/%s)\", lp.desc, lp.ip, lp.port, lp.protocol)\n}","line":{"from":652,"to":654}} {"id":100008729,"name":"Enum","signature":"func Enum(p v1.Protocol) uint16","file":"pkg/proxy/winkernel/proxier.go","code":"func Enum(p v1.Protocol) uint16 {\n\tif p == v1.ProtocolTCP {\n\t\treturn 6\n\t}\n\tif p == v1.ProtocolUDP {\n\t\treturn 17\n\t}\n\tif p == v1.ProtocolSCTP {\n\t\treturn 132\n\t}\n\treturn 0\n}","line":{"from":656,"to":667}} {"id":100008730,"name":"NewProxier","signature":"func NewProxier(","file":"pkg/proxy/winkernel/proxier.go","code":"// NewProxier returns a new Proxier\nfunc NewProxier(\n\tsyncPeriod time.Duration,\n\tminSyncPeriod time.Duration,\n\tmasqueradeAll bool,\n\tmasqueradeBit int,\n\tclusterCIDR string,\n\thostname string,\n\tnodeIP net.IP,\n\trecorder events.EventRecorder,\n\thealthzServer healthcheck.ProxierHealthUpdater,\n\tconfig config.KubeProxyWinkernelConfiguration,\n\thealthzPort int,\n) (*Proxier, error) {\n\tmasqueradeValue := 1 \u003c\u003c uint(masqueradeBit)\n\tmasqueradeMark := fmt.Sprintf(\"%#08x/%#08x\", masqueradeValue, masqueradeValue)\n\n\tif nodeIP == nil {\n\t\tklog.InfoS(\"Invalid nodeIP, initializing kube-proxy with 127.0.0.1 as nodeIP\")\n\t\tnodeIP = netutils.ParseIPSloppy(\"127.0.0.1\")\n\t}\n\n\tif len(clusterCIDR) == 0 {\n\t\tklog.InfoS(\"ClusterCIDR not specified, unable to distinguish between internal and external traffic\")\n\t}\n\n\t// windows listens to all node addresses\n\tnodePortAddresses := utilproxy.NewNodePortAddresses(nil)\n\tserviceHealthServer := healthcheck.NewServiceHealthServer(hostname, recorder, nodePortAddresses, healthzServer)\n\n\thns, supportedFeatures := newHostNetworkService()\n\thnsNetworkName, err := getNetworkName(config.NetworkName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tklog.V(3).InfoS(\"Cleaning up old HNS policy lists\")\n\tdeleteAllHnsLoadBalancerPolicy()\n\n\t// Get HNS network information\n\thnsNetworkInfo, err := getNetworkInfo(hns, hnsNetworkName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Network could have been detected before Remote Subnet Routes are applied or ManagementIP is updated\n\t// Sleep and update the network to include new information\n\tif isOverlay(hnsNetworkInfo) {\n\t\ttime.Sleep(10 * time.Second)\n\t\thnsNetworkInfo, err = hns.getNetworkByName(hnsNetworkName)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"could not find HNS network %s\", hnsNetworkName)\n\t\t}\n\t}\n\n\tklog.V(1).InfoS(\"Hns Network loaded\", \"hnsNetworkInfo\", hnsNetworkInfo)\n\tisDSR := config.EnableDSR\n\tif isDSR \u0026\u0026 !utilfeature.DefaultFeatureGate.Enabled(kubefeatures.WinDSR) {\n\t\treturn nil, fmt.Errorf(\"WinDSR feature gate not enabled\")\n\t}\n\terr = hcn.DSRSupported()\n\tif isDSR \u0026\u0026 err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar sourceVip string\n\tvar hostMac string\n\tif isOverlay(hnsNetworkInfo) {\n\t\tif !utilfeature.DefaultFeatureGate.Enabled(kubefeatures.WinOverlay) {\n\t\t\treturn nil, fmt.Errorf(\"WinOverlay feature gate not enabled\")\n\t\t}\n\t\terr = hcn.RemoteSubnetSupported()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsourceVip = config.SourceVip\n\t\tif len(sourceVip) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"source-vip flag not set\")\n\t\t}\n\n\t\tif nodeIP.IsUnspecified() {\n\t\t\t// attempt to get the correct ip address\n\t\t\tklog.V(2).InfoS(\"Node ip was unspecified, attempting to find node ip\")\n\t\t\tnodeIP, err = apiutil.ResolveBindAddress(nodeIP)\n\t\t\tif err != nil {\n\t\t\t\tklog.InfoS(\"Failed to find an ip. You may need set the --bind-address flag\", \"err\", err)\n\t\t\t}\n\t\t}\n\n\t\tinterfaces, _ := net.Interfaces() //TODO create interfaces\n\t\tfor _, inter := range interfaces {\n\t\t\taddresses, _ := inter.Addrs()\n\t\t\tfor _, addr := range addresses {\n\t\t\t\taddrIP, _, _ := netutils.ParseCIDRSloppy(addr.String())\n\t\t\t\tif addrIP.String() == nodeIP.String() {\n\t\t\t\t\tklog.V(2).InfoS(\"Record Host MAC address\", \"addr\", inter.HardwareAddr)\n\t\t\t\t\thostMac = inter.HardwareAddr.String()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif len(hostMac) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"could not find host mac address for %s\", nodeIP)\n\t\t}\n\t}\n\n\tisIPv6 := netutils.IsIPv6(nodeIP)\n\tproxier := \u0026Proxier{\n\t\tendPointsRefCount: make(endPointsReferenceCountMap),\n\t\tsvcPortMap: make(proxy.ServicePortMap),\n\t\tendpointsMap: make(proxy.EndpointsMap),\n\t\tmasqueradeAll: masqueradeAll,\n\t\tmasqueradeMark: masqueradeMark,\n\t\tclusterCIDR: clusterCIDR,\n\t\thostname: hostname,\n\t\tnodeIP: nodeIP,\n\t\trecorder: recorder,\n\t\tserviceHealthServer: serviceHealthServer,\n\t\thealthzServer: healthzServer,\n\t\thns: hns,\n\t\tnetwork: *hnsNetworkInfo,\n\t\tsourceVip: sourceVip,\n\t\thostMac: hostMac,\n\t\tisDSR: isDSR,\n\t\tsupportedFeatures: supportedFeatures,\n\t\tisIPv6Mode: isIPv6,\n\t\thealthzPort: healthzPort,\n\t\trootHnsEndpointName: config.RootHnsEndpointName,\n\t\tforwardHealthCheckVip: config.ForwardHealthCheckVip,\n\t\tmapStaleLoadbalancers: make(map[string]bool),\n\t}\n\n\tipFamily := v1.IPv4Protocol\n\tif isIPv6 {\n\t\tipFamily = v1.IPv6Protocol\n\t}\n\tserviceChanges := proxy.NewServiceChangeTracker(proxier.newServiceInfo, ipFamily, recorder, proxier.serviceMapChange)\n\tendPointChangeTracker := proxy.NewEndpointChangeTracker(hostname, proxier.newEndpointInfo, ipFamily, recorder, proxier.endpointsMapChange)\n\tproxier.endpointsChanges = endPointChangeTracker\n\tproxier.serviceChanges = serviceChanges\n\n\tburstSyncs := 2\n\tklog.V(3).InfoS(\"Record sync param\", \"minSyncPeriod\", minSyncPeriod, \"syncPeriod\", syncPeriod, \"burstSyncs\", burstSyncs)\n\tproxier.syncRunner = async.NewBoundedFrequencyRunner(\"sync-runner\", proxier.syncProxyRules, minSyncPeriod, syncPeriod, burstSyncs)\n\treturn proxier, nil\n}","line":{"from":676,"to":820}} {"id":100008731,"name":"NewDualStackProxier","signature":"func NewDualStackProxier(","file":"pkg/proxy/winkernel/proxier.go","code":"func NewDualStackProxier(\n\tsyncPeriod time.Duration,\n\tminSyncPeriod time.Duration,\n\tmasqueradeAll bool,\n\tmasqueradeBit int,\n\tclusterCIDR string,\n\thostname string,\n\tnodeIP [2]net.IP,\n\trecorder events.EventRecorder,\n\thealthzServer healthcheck.ProxierHealthUpdater,\n\tconfig config.KubeProxyWinkernelConfiguration,\n\thealthzPort int,\n) (proxy.Provider, error) {\n\n\t// Create an ipv4 instance of the single-stack proxier\n\tipv4Proxier, err := NewProxier(syncPeriod, minSyncPeriod, masqueradeAll, masqueradeBit,\n\t\tclusterCIDR, hostname, nodeIP[0], recorder, healthzServer, config, healthzPort)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create ipv4 proxier: %v, hostname: %s, clusterCIDR : %s, nodeIP:%v\", err, hostname, clusterCIDR, nodeIP[0])\n\t}\n\n\tipv6Proxier, err := NewProxier(syncPeriod, minSyncPeriod, masqueradeAll, masqueradeBit,\n\t\tclusterCIDR, hostname, nodeIP[1], recorder, healthzServer, config, healthzPort)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create ipv6 proxier: %v, hostname: %s, clusterCIDR : %s, nodeIP:%v\", err, hostname, clusterCIDR, nodeIP[1])\n\t}\n\n\t// Return a meta-proxier that dispatch calls between the two\n\t// single-stack proxier instances\n\treturn metaproxier.NewMetaProxier(ipv4Proxier, ipv6Proxier), nil\n}","line":{"from":822,"to":853}} {"id":100008732,"name":"CleanupLeftovers","signature":"func CleanupLeftovers() (encounteredError bool)","file":"pkg/proxy/winkernel/proxier.go","code":"// CleanupLeftovers removes all hns rules created by the Proxier\n// It returns true if an error was encountered. Errors are logged.\nfunc CleanupLeftovers() (encounteredError bool) {\n\t// Delete all Hns Load Balancer Policies\n\tdeleteAllHnsLoadBalancerPolicy()\n\t// TODO\n\t// Delete all Hns Remote endpoints\n\n\treturn encounteredError\n}","line":{"from":855,"to":864}} {"id":100008733,"name":"cleanupAllPolicies","signature":"func (svcInfo *serviceInfo) cleanupAllPolicies(endpoints []proxy.Endpoint, mapStaleLoadbalancers map[string]bool, isEndpointChange bool)","file":"pkg/proxy/winkernel/proxier.go","code":"func (svcInfo *serviceInfo) cleanupAllPolicies(endpoints []proxy.Endpoint, mapStaleLoadbalancers map[string]bool, isEndpointChange bool) {\n\tklog.V(3).InfoS(\"Service cleanup\", \"serviceInfo\", svcInfo)\n\t// if it's an endpoint change and winProxyOptimization annotation enable, skip lb deletion and remoteEndpoint deletion\n\twinProxyOptimization := isEndpointChange \u0026\u0026 svcInfo.winProxyOptimization\n\tif winProxyOptimization {\n\t\tklog.V(3).InfoS(\"Skipped loadbalancer deletion.\", \"hnsID\", svcInfo.hnsID, \"nodePorthnsID\", svcInfo.nodePorthnsID, \"winProxyOptimization\", svcInfo.winProxyOptimization, \"isEndpointChange\", isEndpointChange)\n\t} else {\n\t\t// Skip the svcInfo.policyApplied check to remove all the policies\n\t\tsvcInfo.deleteLoadBalancerPolicy(mapStaleLoadbalancers)\n\t}\n\t// Cleanup Endpoints references\n\tfor _, ep := range endpoints {\n\t\tepInfo, ok := ep.(*endpointsInfo)\n\t\tif ok {\n\t\t\tif winProxyOptimization {\n\t\t\t\tepInfo.DecrementRefCount()\n\t\t\t} else {\n\t\t\t\tepInfo.Cleanup()\n\t\t\t}\n\t\t}\n\t}\n\tif svcInfo.remoteEndpoint != nil {\n\t\tsvcInfo.remoteEndpoint.Cleanup()\n\t}\n\n\tsvcInfo.policyApplied = false\n}","line":{"from":866,"to":892}} {"id":100008734,"name":"deleteLoadBalancerPolicy","signature":"func (svcInfo *serviceInfo) deleteLoadBalancerPolicy(mapStaleLoadbalancer map[string]bool)","file":"pkg/proxy/winkernel/proxier.go","code":"func (svcInfo *serviceInfo) deleteLoadBalancerPolicy(mapStaleLoadbalancer map[string]bool) {\n\t// Remove the Hns Policy corresponding to this service\n\thns := svcInfo.hns\n\tif err := hns.deleteLoadBalancer(svcInfo.hnsID); err != nil {\n\t\tmapStaleLoadbalancer[svcInfo.hnsID] = true\n\t\tklog.V(1).ErrorS(err, \"Error deleting Hns loadbalancer policy resource.\", \"hnsID\", svcInfo.hnsID, \"ClusterIP\", svcInfo.ClusterIP())\n\t} else {\n\t\t// On successful delete, remove hnsId\n\t\tsvcInfo.hnsID = \"\"\n\t}\n\n\tif err := hns.deleteLoadBalancer(svcInfo.nodePorthnsID); err != nil {\n\t\tmapStaleLoadbalancer[svcInfo.nodePorthnsID] = true\n\t\tklog.V(1).ErrorS(err, \"Error deleting Hns NodePort policy resource.\", \"hnsID\", svcInfo.nodePorthnsID, \"NodePort\", svcInfo.NodePort())\n\t} else {\n\t\t// On successful delete, remove hnsId\n\t\tsvcInfo.nodePorthnsID = \"\"\n\t}\n\n\tfor _, externalIP := range svcInfo.externalIPs {\n\t\tmapStaleLoadbalancer[externalIP.hnsID] = true\n\t\tif err := hns.deleteLoadBalancer(externalIP.hnsID); err != nil {\n\t\t\tklog.V(1).ErrorS(err, \"Error deleting Hns ExternalIP policy resource.\", \"hnsID\", externalIP.hnsID, \"IP\", externalIP.ip)\n\t\t} else {\n\t\t\t// On successful delete, remove hnsId\n\t\t\texternalIP.hnsID = \"\"\n\t\t}\n\t}\n\tfor _, lbIngressIP := range svcInfo.loadBalancerIngressIPs {\n\t\tklog.V(3).InfoS(\"Loadbalancer Hns LoadBalancer delete triggered for loadBalancer Ingress resources in cleanup\", \"lbIngressIP\", lbIngressIP)\n\t\tif err := hns.deleteLoadBalancer(lbIngressIP.hnsID); err != nil {\n\t\t\tmapStaleLoadbalancer[lbIngressIP.hnsID] = true\n\t\t\tklog.V(1).ErrorS(err, \"Error deleting Hns IngressIP policy resource.\", \"hnsID\", lbIngressIP.hnsID, \"IP\", lbIngressIP.ip)\n\t\t} else {\n\t\t\t// On successful delete, remove hnsId\n\t\t\tlbIngressIP.hnsID = \"\"\n\t\t}\n\n\t\tif lbIngressIP.healthCheckHnsID != \"\" {\n\t\t\tif err := hns.deleteLoadBalancer(lbIngressIP.healthCheckHnsID); err != nil {\n\t\t\t\tmapStaleLoadbalancer[lbIngressIP.healthCheckHnsID] = true\n\t\t\t\tklog.V(1).ErrorS(err, \"Error deleting Hns IngressIP HealthCheck policy resource.\", \"hnsID\", lbIngressIP.healthCheckHnsID, \"IP\", lbIngressIP.ip)\n\t\t\t} else {\n\t\t\t\t// On successful delete, remove hnsId\n\t\t\t\tlbIngressIP.healthCheckHnsID = \"\"\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":894,"to":942}} {"id":100008735,"name":"deleteAllHnsLoadBalancerPolicy","signature":"func deleteAllHnsLoadBalancerPolicy()","file":"pkg/proxy/winkernel/proxier.go","code":"func deleteAllHnsLoadBalancerPolicy() {\n\tplists, err := hcsshim.HNSListPolicyListRequest()\n\tif err != nil {\n\t\treturn\n\t}\n\tfor _, plist := range plists {\n\t\tklog.V(3).InfoS(\"Remove policy\", \"policies\", plist)\n\t\t_, err = plist.Delete()\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to delete policy list\")\n\t\t}\n\t}\n\n}","line":{"from":944,"to":957}} {"id":100008736,"name":"getHnsNetworkInfo","signature":"func getHnsNetworkInfo(hnsNetworkName string) (*hnsNetworkInfo, error)","file":"pkg/proxy/winkernel/proxier.go","code":"func getHnsNetworkInfo(hnsNetworkName string) (*hnsNetworkInfo, error) {\n\thnsnetwork, err := hcsshim.GetHNSNetworkByName(hnsNetworkName)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to get HNS Network by name\")\n\t\treturn nil, err\n\t}\n\n\treturn \u0026hnsNetworkInfo{\n\t\tid: hnsnetwork.Id,\n\t\tname: hnsnetwork.Name,\n\t\tnetworkType: hnsnetwork.Type,\n\t}, nil\n}","line":{"from":959,"to":971}} {"id":100008737,"name":"Sync","signature":"func (proxier *Proxier) Sync()","file":"pkg/proxy/winkernel/proxier.go","code":"// Sync is called to synchronize the proxier state to hns as soon as possible.\nfunc (proxier *Proxier) Sync() {\n\tif proxier.healthzServer != nil {\n\t\tproxier.healthzServer.QueuedUpdate()\n\t}\n\tmetrics.SyncProxyRulesLastQueuedTimestamp.SetToCurrentTime()\n\tproxier.syncRunner.Run()\n}","line":{"from":973,"to":980}} {"id":100008738,"name":"SyncLoop","signature":"func (proxier *Proxier) SyncLoop()","file":"pkg/proxy/winkernel/proxier.go","code":"// SyncLoop runs periodic work. This is expected to run as a goroutine or as the main loop of the app. It does not return.\nfunc (proxier *Proxier) SyncLoop() {\n\t// Update healthz timestamp at beginning in case Sync() never succeeds.\n\tif proxier.healthzServer != nil {\n\t\tproxier.healthzServer.Updated()\n\t}\n\t// synthesize \"last change queued\" time as the informers are syncing.\n\tmetrics.SyncProxyRulesLastQueuedTimestamp.SetToCurrentTime()\n\tproxier.syncRunner.Loop(wait.NeverStop)\n}","line":{"from":982,"to":991}} {"id":100008739,"name":"setInitialized","signature":"func (proxier *Proxier) setInitialized(value bool)","file":"pkg/proxy/winkernel/proxier.go","code":"func (proxier *Proxier) setInitialized(value bool) {\n\tvar initialized int32\n\tif value {\n\t\tinitialized = 1\n\t}\n\tatomic.StoreInt32(\u0026proxier.initialized, initialized)\n}","line":{"from":993,"to":999}} {"id":100008740,"name":"isInitialized","signature":"func (proxier *Proxier) isInitialized() bool","file":"pkg/proxy/winkernel/proxier.go","code":"func (proxier *Proxier) isInitialized() bool {\n\treturn atomic.LoadInt32(\u0026proxier.initialized) \u003e 0\n}","line":{"from":1001,"to":1003}} {"id":100008741,"name":"OnServiceAdd","signature":"func (proxier *Proxier) OnServiceAdd(service *v1.Service)","file":"pkg/proxy/winkernel/proxier.go","code":"// OnServiceAdd is called whenever creation of new service object\n// is observed.\nfunc (proxier *Proxier) OnServiceAdd(service *v1.Service) {\n\tproxier.OnServiceUpdate(nil, service)\n}","line":{"from":1005,"to":1009}} {"id":100008742,"name":"OnServiceUpdate","signature":"func (proxier *Proxier) OnServiceUpdate(oldService, service *v1.Service)","file":"pkg/proxy/winkernel/proxier.go","code":"// OnServiceUpdate is called whenever modification of an existing\n// service object is observed.\nfunc (proxier *Proxier) OnServiceUpdate(oldService, service *v1.Service) {\n\tif proxier.serviceChanges.Update(oldService, service) \u0026\u0026 proxier.isInitialized() {\n\t\tproxier.Sync()\n\t}\n}","line":{"from":1011,"to":1017}} {"id":100008743,"name":"OnServiceDelete","signature":"func (proxier *Proxier) OnServiceDelete(service *v1.Service)","file":"pkg/proxy/winkernel/proxier.go","code":"// OnServiceDelete is called whenever deletion of an existing service\n// object is observed.\nfunc (proxier *Proxier) OnServiceDelete(service *v1.Service) {\n\tproxier.OnServiceUpdate(service, nil)\n}","line":{"from":1019,"to":1023}} {"id":100008744,"name":"OnServiceSynced","signature":"func (proxier *Proxier) OnServiceSynced()","file":"pkg/proxy/winkernel/proxier.go","code":"// OnServiceSynced is called once all the initial event handlers were\n// called and the state is fully propagated to local cache.\nfunc (proxier *Proxier) OnServiceSynced() {\n\tproxier.mu.Lock()\n\tproxier.servicesSynced = true\n\tproxier.setInitialized(proxier.endpointSlicesSynced)\n\tproxier.mu.Unlock()\n\n\t// Sync unconditionally - this is called once per lifetime.\n\tproxier.syncProxyRules()\n}","line":{"from":1025,"to":1035}} {"id":100008745,"name":"shouldSkipService","signature":"func shouldSkipService(svcName types.NamespacedName, service *v1.Service) bool","file":"pkg/proxy/winkernel/proxier.go","code":"func shouldSkipService(svcName types.NamespacedName, service *v1.Service) bool {\n\t// if ClusterIP is \"None\" or empty, skip proxying\n\tif !helper.IsServiceIPSet(service) {\n\t\tklog.V(3).InfoS(\"Skipping service due to clusterIP\", \"serviceName\", svcName, \"clusterIP\", service.Spec.ClusterIP)\n\t\treturn true\n\t}\n\t// Even if ClusterIP is set, ServiceTypeExternalName services don't get proxied\n\tif service.Spec.Type == v1.ServiceTypeExternalName {\n\t\tklog.V(3).InfoS(\"Skipping service due to Type=ExternalName\", \"serviceName\", svcName)\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":1037,"to":1049}} {"id":100008746,"name":"OnEndpointSliceAdd","signature":"func (proxier *Proxier) OnEndpointSliceAdd(endpointSlice *discovery.EndpointSlice)","file":"pkg/proxy/winkernel/proxier.go","code":"// OnEndpointSliceAdd is called whenever creation of a new endpoint slice object\n// is observed.\nfunc (proxier *Proxier) OnEndpointSliceAdd(endpointSlice *discovery.EndpointSlice) {\n\tif proxier.endpointsChanges.EndpointSliceUpdate(endpointSlice, false) \u0026\u0026 proxier.isInitialized() {\n\t\tproxier.Sync()\n\t}\n}","line":{"from":1051,"to":1057}} {"id":100008747,"name":"OnEndpointSliceUpdate","signature":"func (proxier *Proxier) OnEndpointSliceUpdate(_, endpointSlice *discovery.EndpointSlice)","file":"pkg/proxy/winkernel/proxier.go","code":"// OnEndpointSliceUpdate is called whenever modification of an existing endpoint\n// slice object is observed.\nfunc (proxier *Proxier) OnEndpointSliceUpdate(_, endpointSlice *discovery.EndpointSlice) {\n\tif proxier.endpointsChanges.EndpointSliceUpdate(endpointSlice, false) \u0026\u0026 proxier.isInitialized() {\n\t\tproxier.Sync()\n\t}\n}","line":{"from":1059,"to":1065}} {"id":100008748,"name":"OnEndpointSliceDelete","signature":"func (proxier *Proxier) OnEndpointSliceDelete(endpointSlice *discovery.EndpointSlice)","file":"pkg/proxy/winkernel/proxier.go","code":"// OnEndpointSliceDelete is called whenever deletion of an existing endpoint slice\n// object is observed.\nfunc (proxier *Proxier) OnEndpointSliceDelete(endpointSlice *discovery.EndpointSlice) {\n\tif proxier.endpointsChanges.EndpointSliceUpdate(endpointSlice, true) \u0026\u0026 proxier.isInitialized() {\n\t\tproxier.Sync()\n\t}\n}","line":{"from":1067,"to":1073}} {"id":100008749,"name":"OnEndpointSlicesSynced","signature":"func (proxier *Proxier) OnEndpointSlicesSynced()","file":"pkg/proxy/winkernel/proxier.go","code":"// OnEndpointSlicesSynced is called once all the initial event handlers were\n// called and the state is fully propagated to local cache.\nfunc (proxier *Proxier) OnEndpointSlicesSynced() {\n\tproxier.mu.Lock()\n\tproxier.endpointSlicesSynced = true\n\tproxier.setInitialized(proxier.servicesSynced)\n\tproxier.mu.Unlock()\n\n\t// Sync unconditionally - this is called once per lifetime.\n\tproxier.syncProxyRules()\n}","line":{"from":1075,"to":1085}} {"id":100008750,"name":"cleanupAllPolicies","signature":"func (proxier *Proxier) cleanupAllPolicies()","file":"pkg/proxy/winkernel/proxier.go","code":"func (proxier *Proxier) cleanupAllPolicies() {\n\tfor svcName, svc := range proxier.svcPortMap {\n\t\tsvcInfo, ok := svc.(*serviceInfo)\n\t\tif !ok {\n\t\t\tklog.ErrorS(nil, \"Failed to cast serviceInfo\", \"serviceName\", svcName)\n\t\t\tcontinue\n\t\t}\n\t\tsvcInfo.cleanupAllPolicies(proxier.endpointsMap[svcName], proxier.mapStaleLoadbalancers, false)\n\t}\n}","line":{"from":1087,"to":1096}} {"id":100008751,"name":"isNetworkNotFoundError","signature":"func isNetworkNotFoundError(err error) bool","file":"pkg/proxy/winkernel/proxier.go","code":"func isNetworkNotFoundError(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\tif _, ok := err.(hcn.NetworkNotFoundError); ok {\n\t\treturn true\n\t}\n\tif _, ok := err.(hcsshim.NetworkNotFoundError); ok {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":1098,"to":1109}} {"id":100008752,"name":"isAllEndpointsTerminating","signature":"func (proxier *Proxier) isAllEndpointsTerminating(svcName proxy.ServicePortName, isLocalTrafficDSR bool) bool","file":"pkg/proxy/winkernel/proxier.go","code":"// isAllEndpointsTerminating function will return true if all the endpoints are terminating.\n// If atleast one is not terminating, then return false\nfunc (proxier *Proxier) isAllEndpointsTerminating(svcName proxy.ServicePortName, isLocalTrafficDSR bool) bool {\n\tfor _, epInfo := range proxier.endpointsMap[svcName] {\n\t\tep, ok := epInfo.(*endpointsInfo)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tif isLocalTrafficDSR \u0026\u0026 !ep.GetIsLocal() {\n\t\t\t// KEP-1669: Ignore remote endpoints when the ExternalTrafficPolicy is Local (DSR Mode)\n\t\t\tcontinue\n\t\t}\n\t\t// If Readiness Probe fails and pod is not under delete, then\n\t\t// the state of the endpoint will be - Ready:False, Serving:False, Terminating:False\n\t\tif !ep.IsReady() \u0026\u0026 !ep.IsTerminating() {\n\t\t\t// Ready:false, Terminating:False, ignore\n\t\t\tcontinue\n\t\t}\n\t\tif !ep.IsTerminating() {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":1111,"to":1134}} {"id":100008753,"name":"isAllEndpointsNonServing","signature":"func (proxier *Proxier) isAllEndpointsNonServing(svcName proxy.ServicePortName, isLocalTrafficDSR bool) bool","file":"pkg/proxy/winkernel/proxier.go","code":"// isAllEndpointsNonServing function will return true if all the endpoints are non serving.\n// If atleast one is serving, then return false\nfunc (proxier *Proxier) isAllEndpointsNonServing(svcName proxy.ServicePortName, isLocalTrafficDSR bool) bool {\n\tfor _, epInfo := range proxier.endpointsMap[svcName] {\n\t\tep, ok := epInfo.(*endpointsInfo)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tif isLocalTrafficDSR \u0026\u0026 !ep.GetIsLocal() {\n\t\t\tcontinue\n\t\t}\n\t\tif ep.IsServing() {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":1136,"to":1152}} {"id":100008754,"name":"updateQueriedEndpoints","signature":"func updateQueriedEndpoints(newHnsEndpoint *endpointsInfo, queriedEndpoints map[string]*endpointsInfo)","file":"pkg/proxy/winkernel/proxier.go","code":"// updateQueriedEndpoints updates the queriedEndpoints map with newly created endpoint details\nfunc updateQueriedEndpoints(newHnsEndpoint *endpointsInfo, queriedEndpoints map[string]*endpointsInfo) {\n\t// store newly created endpoints in queriedEndpoints\n\tqueriedEndpoints[newHnsEndpoint.hnsID] = newHnsEndpoint\n\tqueriedEndpoints[newHnsEndpoint.ip] = newHnsEndpoint\n}","line":{"from":1154,"to":1159}} {"id":100008755,"name":"syncProxyRules","signature":"func (proxier *Proxier) syncProxyRules()","file":"pkg/proxy/winkernel/proxier.go","code":"// This is where all of the hns save/restore calls happen.\n// assumes proxier.mu is held\nfunc (proxier *Proxier) syncProxyRules() {\n\tproxier.mu.Lock()\n\tdefer proxier.mu.Unlock()\n\n\t// don't sync rules till we've received services and endpoints\n\tif !proxier.isInitialized() {\n\t\tklog.V(2).InfoS(\"Not syncing hns until Services and Endpoints have been received from master\")\n\t\treturn\n\t}\n\n\t// Keep track of how long syncs take.\n\tstart := time.Now()\n\tdefer func() {\n\t\tmetrics.SyncProxyRulesLatency.Observe(metrics.SinceInSeconds(start))\n\t\tklog.V(4).InfoS(\"Syncing proxy rules complete\", \"elapsed\", time.Since(start))\n\t}()\n\n\thnsNetworkName := proxier.network.name\n\thns := proxier.hns\n\n\tvar gatewayHnsendpoint *endpointsInfo\n\tif proxier.forwardHealthCheckVip {\n\t\tgatewayHnsendpoint, _ = hns.getEndpointByName(proxier.rootHnsEndpointName)\n\t}\n\n\tprevNetworkID := proxier.network.id\n\tupdatedNetwork, err := hns.getNetworkByName(hnsNetworkName)\n\tif updatedNetwork == nil || updatedNetwork.id != prevNetworkID || isNetworkNotFoundError(err) {\n\t\tklog.InfoS(\"The HNS network is not present or has changed since the last sync, please check the CNI deployment\", \"hnsNetworkName\", hnsNetworkName)\n\t\tproxier.cleanupAllPolicies()\n\t\tif updatedNetwork != nil {\n\t\t\tproxier.network = *updatedNetwork\n\t\t}\n\t\treturn\n\t}\n\n\t// We assume that if this was called, we really want to sync them,\n\t// even if nothing changed in the meantime. In other words, callers are\n\t// responsible for detecting no-op changes and not calling this function.\n\tserviceUpdateResult := proxier.svcPortMap.Update(proxier.serviceChanges)\n\tendpointUpdateResult := proxier.endpointsMap.Update(proxier.endpointsChanges)\n\n\tdeletedUDPClusterIPs := serviceUpdateResult.DeletedUDPClusterIPs\n\t// merge stale services gathered from updateEndpointsMap\n\tfor _, svcPortName := range endpointUpdateResult.NewlyActiveUDPServices {\n\t\tif svcInfo, ok := proxier.svcPortMap[svcPortName]; ok \u0026\u0026 svcInfo != nil \u0026\u0026 svcInfo.Protocol() == v1.ProtocolUDP {\n\t\t\tklog.V(2).InfoS(\"Newly-active UDP service may have stale conntrack entries\", \"servicePortName\", svcPortName)\n\t\t\tdeletedUDPClusterIPs.Insert(svcInfo.ClusterIP().String())\n\t\t}\n\t}\n\t// Query HNS for endpoints and load balancers\n\tqueriedEndpoints, err := hns.getAllEndpointsByNetwork(hnsNetworkName)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Querying HNS for endpoints failed\")\n\t\treturn\n\t}\n\tif queriedEndpoints == nil {\n\t\tklog.V(4).InfoS(\"No existing endpoints found in HNS\")\n\t\tqueriedEndpoints = make(map[string]*(endpointsInfo))\n\t}\n\tqueriedLoadBalancers, err := hns.getAllLoadBalancers()\n\tif queriedLoadBalancers == nil {\n\t\tklog.V(4).InfoS(\"No existing load balancers found in HNS\")\n\t\tqueriedLoadBalancers = make(map[loadBalancerIdentifier]*(loadBalancerInfo))\n\t}\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Querying HNS for load balancers failed\")\n\t\treturn\n\t}\n\tif strings.EqualFold(proxier.network.networkType, NETWORK_TYPE_OVERLAY) {\n\t\tif _, ok := queriedEndpoints[proxier.sourceVip]; !ok {\n\t\t\t_, err = newSourceVIP(hns, hnsNetworkName, proxier.sourceVip, proxier.hostMac, proxier.nodeIP.String())\n\t\t\tif err != nil {\n\t\t\t\tklog.ErrorS(err, \"Source Vip endpoint creation failed\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tklog.V(3).InfoS(\"Syncing Policies\")\n\n\t// Program HNS by adding corresponding policies for each service.\n\tfor svcName, svc := range proxier.svcPortMap {\n\t\tsvcInfo, ok := svc.(*serviceInfo)\n\t\tif !ok {\n\t\t\tklog.ErrorS(nil, \"Failed to cast serviceInfo\", \"serviceName\", svcName)\n\t\t\tcontinue\n\t\t}\n\n\t\tif svcInfo.policyApplied {\n\t\t\tklog.V(4).InfoS(\"Policy already applied\", \"serviceInfo\", svcInfo)\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.EqualFold(proxier.network.networkType, NETWORK_TYPE_OVERLAY) {\n\t\t\tserviceVipEndpoint := queriedEndpoints[svcInfo.ClusterIP().String()]\n\t\t\tif serviceVipEndpoint == nil {\n\t\t\t\tklog.V(4).InfoS(\"No existing remote endpoint\", \"IP\", svcInfo.ClusterIP())\n\t\t\t\thnsEndpoint := \u0026endpointsInfo{\n\t\t\t\t\tip: svcInfo.ClusterIP().String(),\n\t\t\t\t\tisLocal: false,\n\t\t\t\t\tmacAddress: proxier.hostMac,\n\t\t\t\t\tproviderAddress: proxier.nodeIP.String(),\n\t\t\t\t}\n\n\t\t\t\tnewHnsEndpoint, err := hns.createEndpoint(hnsEndpoint, hnsNetworkName)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"Remote endpoint creation failed for service VIP\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tnewHnsEndpoint.refCount = proxier.endPointsRefCount.getRefCount(newHnsEndpoint.hnsID)\n\t\t\t\t*newHnsEndpoint.refCount++\n\t\t\t\tsvcInfo.remoteEndpoint = newHnsEndpoint\n\t\t\t\tupdateQueriedEndpoints(newHnsEndpoint, queriedEndpoints)\n\t\t\t}\n\t\t}\n\n\t\tvar hnsEndpoints []endpointsInfo\n\t\tvar hnsLocalEndpoints []endpointsInfo\n\t\tklog.V(4).InfoS(\"Applying Policy\", \"serviceInfo\", svcName)\n\t\t// Create Remote endpoints for every endpoint, corresponding to the service\n\t\tcontainsPublicIP := false\n\t\tcontainsNodeIP := false\n\t\tvar allEndpointsTerminating, allEndpointsNonServing bool\n\t\tsomeEndpointsServing := true\n\n\t\tif utilfeature.DefaultFeatureGate.Enabled(kubefeatures.ProxyTerminatingEndpoints) \u0026\u0026 len(svcInfo.loadBalancerIngressIPs) \u003e 0 {\n\t\t\t// Check should be done only if comes under the feature gate or enabled\n\t\t\t// The check should be done only if Spec.Type == Loadbalancer.\n\t\t\tallEndpointsTerminating = proxier.isAllEndpointsTerminating(svcName, svcInfo.localTrafficDSR)\n\t\t\tallEndpointsNonServing = proxier.isAllEndpointsNonServing(svcName, svcInfo.localTrafficDSR)\n\t\t\tsomeEndpointsServing = !allEndpointsNonServing\n\t\t\tklog.V(4).InfoS(\"Terminating status checked for all endpoints\", \"svcClusterIP\", svcInfo.ClusterIP(), \"allEndpointsTerminating\", allEndpointsTerminating, \"allEndpointsNonServing\", allEndpointsNonServing, \"localTrafficDSR\", svcInfo.localTrafficDSR)\n\t\t} else {\n\t\t\tklog.V(4).InfoS(\"Skipped terminating status check for all endpoints\", \"svcClusterIP\", svcInfo.ClusterIP(), \"proxyEndpointsFeatureGateEnabled\", utilfeature.DefaultFeatureGate.Enabled(kubefeatures.ProxyTerminatingEndpoints), \"ingressLBCount\", len(svcInfo.loadBalancerIngressIPs))\n\t\t}\n\n\t\tfor _, epInfo := range proxier.endpointsMap[svcName] {\n\t\t\tep, ok := epInfo.(*endpointsInfo)\n\t\t\tif !ok {\n\t\t\t\tklog.ErrorS(nil, \"Failed to cast endpointsInfo\", \"serviceName\", svcName)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif svcInfo.internalTrafficLocal \u0026\u0026 svcInfo.localTrafficDSR \u0026\u0026 !ep.GetIsLocal() {\n\t\t\t\t// No need to use or create remote endpoint when internal and external traffic policy is remote\n\t\t\t\tklog.V(3).InfoS(\"Skipping the endpoint. Both internalTraffic and external traffic policies are local\", \"EpIP\", ep.ip, \" EpPort\", ep.port)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif someEndpointsServing {\n\n\t\t\t\tif !allEndpointsTerminating \u0026\u0026 !ep.IsReady() {\n\t\t\t\t\tklog.V(3).InfoS(\"Skipping the endpoint for LB creation. Endpoint is either not ready or all not all endpoints are terminating\", \"EpIP\", ep.ip, \" EpPort\", ep.port, \"allEndpointsTerminating\", allEndpointsTerminating, \"IsEpReady\", ep.IsReady())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif !ep.IsServing() {\n\t\t\t\t\tklog.V(3).InfoS(\"Skipping the endpoint for LB creation. Endpoint is not serving\", \"EpIP\", ep.ip, \" EpPort\", ep.port, \"IsEpServing\", ep.IsServing())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tvar newHnsEndpoint *endpointsInfo\n\t\t\thnsNetworkName := proxier.network.name\n\t\t\tvar err error\n\n\t\t\t// targetPort is zero if it is specified as a name in port.TargetPort, so the real port should be got from endpoints.\n\t\t\t// Note that hcsshim.AddLoadBalancer() doesn't support endpoints with different ports, so only port from first endpoint is used.\n\t\t\t// TODO(feiskyer): add support of different endpoint ports after hcsshim.AddLoadBalancer() add that.\n\t\t\tif svcInfo.targetPort == 0 {\n\t\t\t\tsvcInfo.targetPort = int(ep.port)\n\t\t\t}\n\t\t\t// There is a bug in Windows Server 2019 that can cause two endpoints to be created with the same IP address, so we need to check using endpoint ID first.\n\t\t\t// TODO: Remove lookup by endpoint ID, and use the IP address only, so we don't need to maintain multiple keys for lookup.\n\t\t\tif len(ep.hnsID) \u003e 0 {\n\t\t\t\tnewHnsEndpoint = queriedEndpoints[ep.hnsID]\n\t\t\t}\n\n\t\t\tif newHnsEndpoint == nil {\n\t\t\t\t// First check if an endpoint resource exists for this IP, on the current host\n\t\t\t\t// A Local endpoint could exist here already\n\t\t\t\t// A remote endpoint was already created and proxy was restarted\n\t\t\t\tnewHnsEndpoint = queriedEndpoints[ep.IP()]\n\t\t\t}\n\n\t\t\tif newHnsEndpoint == nil {\n\t\t\t\tif ep.GetIsLocal() {\n\t\t\t\t\tklog.ErrorS(err, \"Local endpoint not found: on network\", \"ip\", ep.IP(), \"hnsNetworkName\", hnsNetworkName)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif strings.EqualFold(proxier.network.networkType, NETWORK_TYPE_OVERLAY) {\n\t\t\t\t\tklog.InfoS(\"Updating network to check for new remote subnet policies\", \"networkName\", proxier.network.name)\n\t\t\t\t\tnetworkName := proxier.network.name\n\t\t\t\t\tupdatedNetwork, err := hns.getNetworkByName(networkName)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tklog.ErrorS(err, \"Unable to find HNS Network specified, please check network name and CNI deployment\", \"hnsNetworkName\", hnsNetworkName)\n\t\t\t\t\t\tproxier.cleanupAllPolicies()\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tproxier.network = *updatedNetwork\n\t\t\t\t\tproviderAddress := proxier.network.findRemoteSubnetProviderAddress(ep.IP())\n\t\t\t\t\tif len(providerAddress) == 0 {\n\t\t\t\t\t\tklog.InfoS(\"Could not find provider address, assuming it is a public IP\", \"IP\", ep.IP())\n\t\t\t\t\t\tproviderAddress = proxier.nodeIP.String()\n\t\t\t\t\t}\n\n\t\t\t\t\thnsEndpoint := \u0026endpointsInfo{\n\t\t\t\t\t\tip: ep.ip,\n\t\t\t\t\t\tisLocal: false,\n\t\t\t\t\t\tmacAddress: conjureMac(\"02-11\", netutils.ParseIPSloppy(ep.ip)),\n\t\t\t\t\t\tproviderAddress: providerAddress,\n\t\t\t\t\t}\n\n\t\t\t\t\tnewHnsEndpoint, err = hns.createEndpoint(hnsEndpoint, hnsNetworkName)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tklog.ErrorS(err, \"Remote endpoint creation failed\", \"endpointsInfo\", hnsEndpoint)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tupdateQueriedEndpoints(newHnsEndpoint, queriedEndpoints)\n\t\t\t\t} else {\n\n\t\t\t\t\thnsEndpoint := \u0026endpointsInfo{\n\t\t\t\t\t\tip: ep.ip,\n\t\t\t\t\t\tisLocal: false,\n\t\t\t\t\t\tmacAddress: ep.macAddress,\n\t\t\t\t\t}\n\n\t\t\t\t\tnewHnsEndpoint, err = hns.createEndpoint(hnsEndpoint, hnsNetworkName)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tklog.ErrorS(err, \"Remote endpoint creation failed\")\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tupdateQueriedEndpoints(newHnsEndpoint, queriedEndpoints)\n\t\t\t\t}\n\t\t\t}\n\t\t\t// For Overlay networks 'SourceVIP' on an Load balancer Policy can either be chosen as\n\t\t\t// a) Source VIP configured on kube-proxy (or)\n\t\t\t// b) Node IP of the current node\n\t\t\t//\n\t\t\t// For L2Bridge network the Source VIP is always the NodeIP of the current node and the same\n\t\t\t// would be configured on kube-proxy as SourceVIP\n\t\t\t//\n\t\t\t// The logic for choosing the SourceVIP in Overlay networks is based on the backend endpoints:\n\t\t\t// a) Endpoints are any IP's outside the cluster ==\u003e Choose NodeIP as the SourceVIP\n\t\t\t// b) Endpoints are IP addresses of a remote node =\u003e Choose NodeIP as the SourceVIP\n\t\t\t// c) Everything else (Local POD's, Remote POD's, Node IP of current node) ==\u003e Choose the configured SourceVIP\n\t\t\tif strings.EqualFold(proxier.network.networkType, NETWORK_TYPE_OVERLAY) \u0026\u0026 !ep.GetIsLocal() {\n\t\t\t\tproviderAddress := proxier.network.findRemoteSubnetProviderAddress(ep.IP())\n\n\t\t\t\tisNodeIP := (ep.IP() == providerAddress)\n\t\t\t\tisPublicIP := (len(providerAddress) == 0)\n\t\t\t\tklog.InfoS(\"Endpoint on overlay network\", \"ip\", ep.IP(), \"hnsNetworkName\", hnsNetworkName, \"isNodeIP\", isNodeIP, \"isPublicIP\", isPublicIP)\n\n\t\t\t\tcontainsNodeIP = containsNodeIP || isNodeIP\n\t\t\t\tcontainsPublicIP = containsPublicIP || isPublicIP\n\t\t\t}\n\n\t\t\t// Save the hnsId for reference\n\t\t\tklog.V(1).InfoS(\"Hns endpoint resource\", \"endpointsInfo\", newHnsEndpoint)\n\n\t\t\thnsEndpoints = append(hnsEndpoints, *newHnsEndpoint)\n\t\t\tif newHnsEndpoint.GetIsLocal() {\n\t\t\t\thnsLocalEndpoints = append(hnsLocalEndpoints, *newHnsEndpoint)\n\t\t\t} else {\n\t\t\t\t// We only share the refCounts for remote endpoints\n\t\t\t\tep.refCount = proxier.endPointsRefCount.getRefCount(newHnsEndpoint.hnsID)\n\t\t\t\t*ep.refCount++\n\t\t\t}\n\n\t\t\tep.hnsID = newHnsEndpoint.hnsID\n\n\t\t\tklog.V(3).InfoS(\"Endpoint resource found\", \"endpointsInfo\", ep)\n\t\t}\n\n\t\tklog.V(3).InfoS(\"Associated endpoints for service\", \"endpointsInfo\", hnsEndpoints, \"serviceName\", svcName)\n\n\t\tif len(svcInfo.hnsID) \u003e 0 {\n\t\t\t// This should not happen\n\t\t\tklog.InfoS(\"Load Balancer already exists -- Debug \", \"hnsID\", svcInfo.hnsID)\n\t\t}\n\n\t\t// In ETP:Cluster, if all endpoints are under termination,\n\t\t// it will have serving and terminating, else only ready and serving\n\t\tif len(hnsEndpoints) == 0 {\n\t\t\tif svcInfo.winProxyOptimization {\n\t\t\t\t// Deleting loadbalancers when there are no endpoints to serve.\n\t\t\t\tklog.V(3).InfoS(\"Cleanup existing \", \"endpointsInfo\", hnsEndpoints, \"serviceName\", svcName)\n\t\t\t\tsvcInfo.deleteLoadBalancerPolicy(proxier.mapStaleLoadbalancers)\n\t\t\t}\n\t\t\tklog.ErrorS(nil, \"Endpoint information not available for service, not applying any policy\", \"serviceName\", svcName)\n\t\t\tcontinue\n\t\t}\n\n\t\tklog.V(4).InfoS(\"Trying to apply Policies for service\", \"serviceInfo\", svcInfo)\n\t\tvar hnsLoadBalancer *loadBalancerInfo\n\t\tvar sourceVip = proxier.sourceVip\n\t\tif containsPublicIP || containsNodeIP {\n\t\t\tsourceVip = proxier.nodeIP.String()\n\t\t}\n\n\t\tsessionAffinityClientIP := svcInfo.SessionAffinityType() == v1.ServiceAffinityClientIP\n\t\tif sessionAffinityClientIP \u0026\u0026 !proxier.supportedFeatures.SessionAffinity {\n\t\t\tklog.InfoS(\"Session Affinity is not supported on this version of Windows\")\n\t\t}\n\n\t\tendpointsAvailableForLB := !allEndpointsTerminating \u0026\u0026 !allEndpointsNonServing\n\t\tproxier.deleteExistingLoadBalancer(hns, svcInfo.winProxyOptimization, \u0026svcInfo.hnsID, sourceVip, Enum(svcInfo.Protocol()), uint16(svcInfo.targetPort), uint16(svcInfo.Port()), hnsEndpoints, queriedLoadBalancers)\n\n\t\t// clusterIPEndpoints is the endpoint list used for creating ClusterIP loadbalancer.\n\t\tclusterIPEndpoints := hnsEndpoints\n\t\tif svcInfo.internalTrafficLocal {\n\t\t\t// Take local endpoints for clusterip loadbalancer when internal traffic policy is local.\n\t\t\tclusterIPEndpoints = hnsLocalEndpoints\n\t\t}\n\n\t\tif len(clusterIPEndpoints) \u003e 0 {\n\n\t\t\t// If all endpoints are terminating, then no need to create Cluster IP LoadBalancer\n\t\t\t// Cluster IP LoadBalancer creation\n\t\t\thnsLoadBalancer, err := hns.getLoadBalancer(\n\t\t\t\tclusterIPEndpoints,\n\t\t\t\tloadBalancerFlags{isDSR: proxier.isDSR, isIPv6: proxier.isIPv6Mode, sessionAffinity: sessionAffinityClientIP},\n\t\t\t\tsourceVip,\n\t\t\t\tsvcInfo.ClusterIP().String(),\n\t\t\t\tEnum(svcInfo.Protocol()),\n\t\t\t\tuint16(svcInfo.targetPort),\n\t\t\t\tuint16(svcInfo.Port()),\n\t\t\t\tqueriedLoadBalancers,\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tklog.ErrorS(err, \"Policy creation failed\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tsvcInfo.hnsID = hnsLoadBalancer.hnsID\n\t\t\tklog.V(3).InfoS(\"Hns LoadBalancer resource created for cluster ip resources\", \"clusterIP\", svcInfo.ClusterIP(), \"hnsID\", hnsLoadBalancer.hnsID)\n\n\t\t} else {\n\t\t\tklog.V(3).InfoS(\"Skipped creating Hns LoadBalancer for cluster ip resources. Reason : all endpoints are terminating\", \"clusterIP\", svcInfo.ClusterIP(), \"nodeport\", svcInfo.NodePort(), \"allEndpointsTerminating\", allEndpointsTerminating)\n\t\t}\n\n\t\t// If nodePort is specified, user should be able to use nodeIP:nodePort to reach the backend endpoints\n\t\tif svcInfo.NodePort() \u003e 0 {\n\t\t\t// If the preserve-destination service annotation is present, we will disable routing mesh for NodePort.\n\t\t\t// This means that health services can use Node Port without falsely getting results from a different node.\n\t\t\tnodePortEndpoints := hnsEndpoints\n\t\t\tif svcInfo.preserveDIP || svcInfo.localTrafficDSR {\n\t\t\t\tnodePortEndpoints = hnsLocalEndpoints\n\t\t\t}\n\n\t\t\tproxier.deleteExistingLoadBalancer(hns, svcInfo.winProxyOptimization, \u0026svcInfo.nodePorthnsID, sourceVip, Enum(svcInfo.Protocol()), uint16(svcInfo.targetPort), uint16(svcInfo.Port()), nodePortEndpoints, queriedLoadBalancers)\n\n\t\t\tif len(nodePortEndpoints) \u003e 0 \u0026\u0026 endpointsAvailableForLB {\n\t\t\t\t// If all endpoints are in terminating stage, then no need to create Node Port LoadBalancer\n\t\t\t\thnsLoadBalancer, err := hns.getLoadBalancer(\n\t\t\t\t\tnodePortEndpoints,\n\t\t\t\t\tloadBalancerFlags{isVipExternalIP: true, isDSR: svcInfo.localTrafficDSR, localRoutedVIP: true, sessionAffinity: sessionAffinityClientIP, isIPv6: proxier.isIPv6Mode},\n\t\t\t\t\tsourceVip,\n\t\t\t\t\t\"\",\n\t\t\t\t\tEnum(svcInfo.Protocol()),\n\t\t\t\t\tuint16(svcInfo.targetPort),\n\t\t\t\t\tuint16(svcInfo.NodePort()),\n\t\t\t\t\tqueriedLoadBalancers,\n\t\t\t\t)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"Policy creation failed\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tsvcInfo.nodePorthnsID = hnsLoadBalancer.hnsID\n\t\t\t\tklog.V(3).InfoS(\"Hns LoadBalancer resource created for nodePort resources\", \"clusterIP\", svcInfo.ClusterIP(), \"nodeport\", svcInfo.NodePort(), \"hnsID\", hnsLoadBalancer.hnsID)\n\t\t\t} else {\n\t\t\t\tklog.V(3).InfoS(\"Skipped creating Hns LoadBalancer for nodePort resources\", \"clusterIP\", svcInfo.ClusterIP(), \"nodeport\", svcInfo.NodePort(), \"allEndpointsTerminating\", allEndpointsTerminating)\n\t\t\t}\n\t\t}\n\n\t\t// Create a Load Balancer Policy for each external IP\n\t\tfor _, externalIP := range svcInfo.externalIPs {\n\t\t\t// Disable routing mesh if ExternalTrafficPolicy is set to local\n\t\t\texternalIPEndpoints := hnsEndpoints\n\t\t\tif svcInfo.localTrafficDSR {\n\t\t\t\texternalIPEndpoints = hnsLocalEndpoints\n\t\t\t}\n\n\t\t\tproxier.deleteExistingLoadBalancer(hns, svcInfo.winProxyOptimization, \u0026externalIP.hnsID, sourceVip, Enum(svcInfo.Protocol()), uint16(svcInfo.targetPort), uint16(svcInfo.Port()), externalIPEndpoints, queriedLoadBalancers)\n\n\t\t\tif len(externalIPEndpoints) \u003e 0 \u0026\u0026 endpointsAvailableForLB {\n\t\t\t\t// If all endpoints are in terminating stage, then no need to External IP LoadBalancer\n\t\t\t\t// Try loading existing policies, if already available\n\t\t\t\thnsLoadBalancer, err = hns.getLoadBalancer(\n\t\t\t\t\texternalIPEndpoints,\n\t\t\t\t\tloadBalancerFlags{isVipExternalIP: true, isDSR: svcInfo.localTrafficDSR, sessionAffinity: sessionAffinityClientIP, isIPv6: proxier.isIPv6Mode},\n\t\t\t\t\tsourceVip,\n\t\t\t\t\texternalIP.ip,\n\t\t\t\t\tEnum(svcInfo.Protocol()),\n\t\t\t\t\tuint16(svcInfo.targetPort),\n\t\t\t\t\tuint16(svcInfo.Port()),\n\t\t\t\t\tqueriedLoadBalancers,\n\t\t\t\t)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"Policy creation failed\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\texternalIP.hnsID = hnsLoadBalancer.hnsID\n\t\t\t\tklog.V(3).InfoS(\"Hns LoadBalancer resource created for externalIP resources\", \"externalIP\", externalIP, \"hnsID\", hnsLoadBalancer.hnsID)\n\t\t\t} else {\n\t\t\t\tklog.V(3).InfoS(\"Skipped creating Hns LoadBalancer for externalIP resources\", \"externalIP\", externalIP, \"allEndpointsTerminating\", allEndpointsTerminating)\n\t\t\t}\n\t\t}\n\t\t// Create a Load Balancer Policy for each loadbalancer ingress\n\t\tfor _, lbIngressIP := range svcInfo.loadBalancerIngressIPs {\n\t\t\t// Try loading existing policies, if already available\n\t\t\tlbIngressEndpoints := hnsEndpoints\n\t\t\tif svcInfo.preserveDIP || svcInfo.localTrafficDSR {\n\t\t\t\tlbIngressEndpoints = hnsLocalEndpoints\n\t\t\t}\n\n\t\t\tproxier.deleteExistingLoadBalancer(hns, svcInfo.winProxyOptimization, \u0026lbIngressIP.hnsID, sourceVip, Enum(svcInfo.Protocol()), uint16(svcInfo.targetPort), uint16(svcInfo.Port()), lbIngressEndpoints, queriedLoadBalancers)\n\n\t\t\tif len(lbIngressEndpoints) \u003e 0 {\n\t\t\t\thnsLoadBalancer, err := hns.getLoadBalancer(\n\t\t\t\t\tlbIngressEndpoints,\n\t\t\t\t\tloadBalancerFlags{isVipExternalIP: true, isDSR: svcInfo.preserveDIP || svcInfo.localTrafficDSR, useMUX: svcInfo.preserveDIP, preserveDIP: svcInfo.preserveDIP, sessionAffinity: sessionAffinityClientIP, isIPv6: proxier.isIPv6Mode},\n\t\t\t\t\tsourceVip,\n\t\t\t\t\tlbIngressIP.ip,\n\t\t\t\t\tEnum(svcInfo.Protocol()),\n\t\t\t\t\tuint16(svcInfo.targetPort),\n\t\t\t\t\tuint16(svcInfo.Port()),\n\t\t\t\t\tqueriedLoadBalancers,\n\t\t\t\t)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"Policy creation failed\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tlbIngressIP.hnsID = hnsLoadBalancer.hnsID\n\t\t\t\tklog.V(3).InfoS(\"Hns LoadBalancer resource created for loadBalancer Ingress resources\", \"lbIngressIP\", lbIngressIP)\n\t\t\t} else {\n\t\t\t\tklog.V(3).InfoS(\"Skipped creating Hns LoadBalancer for loadBalancer Ingress resources\", \"lbIngressIP\", lbIngressIP)\n\t\t\t}\n\n\t\t\tif proxier.forwardHealthCheckVip \u0026\u0026 gatewayHnsendpoint != nil \u0026\u0026 endpointsAvailableForLB {\n\t\t\t\t// Avoid creating health check loadbalancer if all the endpoints are terminating\n\t\t\t\tnodeport := proxier.healthzPort\n\t\t\t\tif svcInfo.HealthCheckNodePort() != 0 {\n\t\t\t\t\tnodeport = svcInfo.HealthCheckNodePort()\n\t\t\t\t}\n\n\t\t\t\tproxier.deleteExistingLoadBalancer(hns, svcInfo.winProxyOptimization, \u0026lbIngressIP.healthCheckHnsID, sourceVip, Enum(svcInfo.Protocol()), uint16(svcInfo.targetPort), uint16(svcInfo.Port()), []endpointsInfo{*gatewayHnsendpoint}, queriedLoadBalancers)\n\n\t\t\t\thnsHealthCheckLoadBalancer, err := hns.getLoadBalancer(\n\t\t\t\t\t[]endpointsInfo{*gatewayHnsendpoint},\n\t\t\t\t\tloadBalancerFlags{isDSR: false, useMUX: svcInfo.preserveDIP, preserveDIP: svcInfo.preserveDIP},\n\t\t\t\t\tsourceVip,\n\t\t\t\t\tlbIngressIP.ip,\n\t\t\t\t\tEnum(svcInfo.Protocol()),\n\t\t\t\t\tuint16(nodeport),\n\t\t\t\t\tuint16(nodeport),\n\t\t\t\t\tqueriedLoadBalancers,\n\t\t\t\t)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"Policy creation failed\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tlbIngressIP.healthCheckHnsID = hnsHealthCheckLoadBalancer.hnsID\n\t\t\t\tklog.V(3).InfoS(\"Hns Health Check LoadBalancer resource created for loadBalancer Ingress resources\", \"ip\", lbIngressIP)\n\t\t\t} else {\n\t\t\t\tklog.V(3).InfoS(\"Skipped creating Hns Health Check LoadBalancer for loadBalancer Ingress resources\", \"ip\", lbIngressIP, \"allEndpointsTerminating\", allEndpointsTerminating)\n\t\t\t}\n\t\t}\n\t\tsvcInfo.policyApplied = true\n\t\tklog.V(2).InfoS(\"Policy successfully applied for service\", \"serviceInfo\", svcInfo)\n\t}\n\n\tif proxier.healthzServer != nil {\n\t\tproxier.healthzServer.Updated()\n\t}\n\tmetrics.SyncProxyRulesLastTimestamp.SetToCurrentTime()\n\n\t// Update service healthchecks. The endpoints list might include services that are\n\t// not \"OnlyLocal\", but the services list will not, and the serviceHealthServer\n\t// will just drop those endpoints.\n\tif err := proxier.serviceHealthServer.SyncServices(proxier.svcPortMap.HealthCheckNodePorts()); err != nil {\n\t\tklog.ErrorS(err, \"Error syncing healthcheck services\")\n\t}\n\tif err := proxier.serviceHealthServer.SyncEndpoints(proxier.endpointsMap.LocalReadyEndpoints()); err != nil {\n\t\tklog.ErrorS(err, \"Error syncing healthcheck endpoints\")\n\t}\n\n\t// Finish housekeeping.\n\t// TODO: these could be made more consistent.\n\tfor _, svcIP := range deletedUDPClusterIPs.UnsortedList() {\n\t\t// TODO : Check if this is required to cleanup stale services here\n\t\tklog.V(5).InfoS(\"Pending delete stale service IP connections\", \"IP\", svcIP)\n\t}\n\n\t// remove stale endpoint refcount entries\n\tfor hnsID, referenceCount := range proxier.endPointsRefCount {\n\t\tif *referenceCount \u003c= 0 {\n\t\t\tklog.V(3).InfoS(\"Deleting unreferenced remote endpoint\", \"hnsID\", hnsID)\n\t\t\tproxier.hns.deleteEndpoint(hnsID)\n\t\t\tdelete(proxier.endPointsRefCount, hnsID)\n\t\t}\n\t}\n\t// This will cleanup stale load balancers which are pending delete\n\t// in last iteration\n\tproxier.cleanupStaleLoadbalancers()\n}","line":{"from":1161,"to":1672}} {"id":100008756,"name":"deleteExistingLoadBalancer","signature":"func (proxier *Proxier) deleteExistingLoadBalancer(hns HostNetworkService, winProxyOptimization bool, lbHnsID *string, sourceVip string, protocol, intPort, extPort uint16, endpoints []endpointsInfo, queriedLoadBalancers map[loadBalancerIdentifier]*loadBalancerInfo) bool","file":"pkg/proxy/winkernel/proxier.go","code":"// deleteExistingLoadBalancer checks whether loadbalancer delete is needed or not.\n// If it is needed, the function will delete the existing loadbalancer and return true, else false.\nfunc (proxier *Proxier) deleteExistingLoadBalancer(hns HostNetworkService, winProxyOptimization bool, lbHnsID *string, sourceVip string, protocol, intPort, extPort uint16, endpoints []endpointsInfo, queriedLoadBalancers map[loadBalancerIdentifier]*loadBalancerInfo) bool {\n\n\tif !winProxyOptimization || *lbHnsID == \"\" {\n\t\t// Loadbalancer delete not needed\n\t\treturn false\n\t}\n\n\tlbID, lbIdErr := findLoadBalancerID(\n\t\tendpoints,\n\t\tsourceVip,\n\t\tprotocol,\n\t\tintPort,\n\t\textPort,\n\t)\n\n\tif lbIdErr != nil {\n\t\treturn proxier.deleteLoadBalancer(hns, lbHnsID)\n\t}\n\n\tif _, ok := queriedLoadBalancers[lbID]; ok {\n\t\t// The existing loadbalancer in the system is same as what we try to delete and recreate. So we skip deleting.\n\t\treturn false\n\t}\n\n\treturn proxier.deleteLoadBalancer(hns, lbHnsID)\n}","line":{"from":1674,"to":1701}} {"id":100008757,"name":"deleteLoadBalancer","signature":"func (proxier *Proxier) deleteLoadBalancer(hns HostNetworkService, lbHnsID *string) bool","file":"pkg/proxy/winkernel/proxier.go","code":"func (proxier *Proxier) deleteLoadBalancer(hns HostNetworkService, lbHnsID *string) bool {\n\tklog.V(3).InfoS(\"Hns LoadBalancer delete triggered for loadBalancer resources\", \"lbHnsID\", *lbHnsID)\n\tif err := hns.deleteLoadBalancer(*lbHnsID); err != nil {\n\t\t// This will be cleanup by cleanupStaleLoadbalancer fnction.\n\t\tproxier.mapStaleLoadbalancers[*lbHnsID] = true\n\t}\n\t*lbHnsID = \"\"\n\treturn true\n}","line":{"from":1703,"to":1711}} {"id":100008758,"name":"V1ResourceByStorageClass","signature":"func V1ResourceByStorageClass(storageClass string, resourceName corev1.ResourceName) corev1.ResourceName","file":"pkg/quota/v1/evaluator/core/persistent_volume_claims.go","code":"// V1ResourceByStorageClass returns a quota resource name by storage class.\nfunc V1ResourceByStorageClass(storageClass string, resourceName corev1.ResourceName) corev1.ResourceName {\n\treturn corev1.ResourceName(string(storageClass + storageClassSuffix + string(resourceName)))\n}","line":{"from":62,"to":65}} {"id":100008759,"name":"NewPersistentVolumeClaimEvaluator","signature":"func NewPersistentVolumeClaimEvaluator(f quota.ListerForResourceFunc) quota.Evaluator","file":"pkg/quota/v1/evaluator/core/persistent_volume_claims.go","code":"// NewPersistentVolumeClaimEvaluator returns an evaluator that can evaluate persistent volume claims\nfunc NewPersistentVolumeClaimEvaluator(f quota.ListerForResourceFunc) quota.Evaluator {\n\tlistFuncByNamespace := generic.ListResourceUsingListerFunc(f, corev1.SchemeGroupVersion.WithResource(\"persistentvolumeclaims\"))\n\tpvcEvaluator := \u0026pvcEvaluator{listFuncByNamespace: listFuncByNamespace}\n\treturn pvcEvaluator\n}","line":{"from":67,"to":72}} {"id":100008760,"name":"Constraints","signature":"func (p *pvcEvaluator) Constraints(required []corev1.ResourceName, item runtime.Object) error","file":"pkg/quota/v1/evaluator/core/persistent_volume_claims.go","code":"// Constraints verifies that all required resources are present on the item.\nfunc (p *pvcEvaluator) Constraints(required []corev1.ResourceName, item runtime.Object) error {\n\t// no-op for persistent volume claims\n\treturn nil\n}","line":{"from":80,"to":84}} {"id":100008761,"name":"GroupResource","signature":"func (p *pvcEvaluator) GroupResource() schema.GroupResource","file":"pkg/quota/v1/evaluator/core/persistent_volume_claims.go","code":"// GroupResource that this evaluator tracks\nfunc (p *pvcEvaluator) GroupResource() schema.GroupResource {\n\treturn corev1.SchemeGroupVersion.WithResource(\"persistentvolumeclaims\").GroupResource()\n}","line":{"from":86,"to":89}} {"id":100008762,"name":"Handles","signature":"func (p *pvcEvaluator) Handles(a admission.Attributes) bool","file":"pkg/quota/v1/evaluator/core/persistent_volume_claims.go","code":"// Handles returns true if the evaluator should handle the specified operation.\nfunc (p *pvcEvaluator) Handles(a admission.Attributes) bool {\n\top := a.GetOperation()\n\tif op == admission.Create {\n\t\treturn true\n\t}\n\tif op == admission.Update {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":91,"to":101}} {"id":100008763,"name":"Matches","signature":"func (p *pvcEvaluator) Matches(resourceQuota *corev1.ResourceQuota, item runtime.Object) (bool, error)","file":"pkg/quota/v1/evaluator/core/persistent_volume_claims.go","code":"// Matches returns true if the evaluator matches the specified quota with the provided input item\nfunc (p *pvcEvaluator) Matches(resourceQuota *corev1.ResourceQuota, item runtime.Object) (bool, error) {\n\treturn generic.Matches(resourceQuota, item, p.MatchingResources, generic.MatchesNoScopeFunc)\n}","line":{"from":103,"to":106}} {"id":100008764,"name":"MatchingScopes","signature":"func (p *pvcEvaluator) MatchingScopes(item runtime.Object, scopes []corev1.ScopedResourceSelectorRequirement) ([]corev1.ScopedResourceSelectorRequirement, error)","file":"pkg/quota/v1/evaluator/core/persistent_volume_claims.go","code":"// MatchingScopes takes the input specified list of scopes and input object. Returns the set of scopes resource matches.\nfunc (p *pvcEvaluator) MatchingScopes(item runtime.Object, scopes []corev1.ScopedResourceSelectorRequirement) ([]corev1.ScopedResourceSelectorRequirement, error) {\n\treturn []corev1.ScopedResourceSelectorRequirement{}, nil\n}","line":{"from":108,"to":111}} {"id":100008765,"name":"UncoveredQuotaScopes","signature":"func (p *pvcEvaluator) UncoveredQuotaScopes(limitedScopes []corev1.ScopedResourceSelectorRequirement, matchedQuotaScopes []corev1.ScopedResourceSelectorRequirement) ([]corev1.ScopedResourceSelectorRequirement, error)","file":"pkg/quota/v1/evaluator/core/persistent_volume_claims.go","code":"// UncoveredQuotaScopes takes the input matched scopes which are limited by configuration and the matched quota scopes.\n// It returns the scopes which are in limited scopes but don't have a corresponding covering quota scope\nfunc (p *pvcEvaluator) UncoveredQuotaScopes(limitedScopes []corev1.ScopedResourceSelectorRequirement, matchedQuotaScopes []corev1.ScopedResourceSelectorRequirement) ([]corev1.ScopedResourceSelectorRequirement, error) {\n\treturn []corev1.ScopedResourceSelectorRequirement{}, nil\n}","line":{"from":113,"to":117}} {"id":100008766,"name":"MatchingResources","signature":"func (p *pvcEvaluator) MatchingResources(items []corev1.ResourceName) []corev1.ResourceName","file":"pkg/quota/v1/evaluator/core/persistent_volume_claims.go","code":"// MatchingResources takes the input specified list of resources and returns the set of resources it matches.\nfunc (p *pvcEvaluator) MatchingResources(items []corev1.ResourceName) []corev1.ResourceName {\n\tresult := []corev1.ResourceName{}\n\tfor _, item := range items {\n\t\t// match object count quota fields\n\t\tif quota.Contains([]corev1.ResourceName{pvcObjectCountName}, item) {\n\t\t\tresult = append(result, item)\n\t\t\tcontinue\n\t\t}\n\t\t// match pvc resources\n\t\tif quota.Contains(pvcResources, item) {\n\t\t\tresult = append(result, item)\n\t\t\tcontinue\n\t\t}\n\t\t// match pvc resources scoped by storage class (\u003cstorage-class-name\u003e.storageclass.storage.k8s.io/\u003cresource\u003e)\n\t\tfor _, resource := range pvcResources {\n\t\t\tbyStorageClass := storageClassSuffix + string(resource)\n\t\t\tif strings.HasSuffix(string(item), byStorageClass) {\n\t\t\t\tresult = append(result, item)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}","line":{"from":119,"to":143}} {"id":100008767,"name":"Usage","signature":"func (p *pvcEvaluator) Usage(item runtime.Object) (corev1.ResourceList, error)","file":"pkg/quota/v1/evaluator/core/persistent_volume_claims.go","code":"// Usage knows how to measure usage associated with item.\nfunc (p *pvcEvaluator) Usage(item runtime.Object) (corev1.ResourceList, error) {\n\tresult := corev1.ResourceList{}\n\tpvc, err := toExternalPersistentVolumeClaimOrError(item)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\n\t// charge for claim\n\tresult[corev1.ResourcePersistentVolumeClaims] = *(resource.NewQuantity(1, resource.DecimalSI))\n\tresult[pvcObjectCountName] = *(resource.NewQuantity(1, resource.DecimalSI))\n\tstorageClassRef := storagehelpers.GetPersistentVolumeClaimClass(pvc)\n\tif len(storageClassRef) \u003e 0 {\n\t\tstorageClassClaim := corev1.ResourceName(storageClassRef + storageClassSuffix + string(corev1.ResourcePersistentVolumeClaims))\n\t\tresult[storageClassClaim] = *(resource.NewQuantity(1, resource.DecimalSI))\n\t}\n\n\trequestedStorage := p.getStorageUsage(pvc)\n\tif requestedStorage != nil {\n\t\tresult[corev1.ResourceRequestsStorage] = *requestedStorage\n\t\t// charge usage to the storage class (if present)\n\t\tif len(storageClassRef) \u003e 0 {\n\t\t\tstorageClassStorage := corev1.ResourceName(storageClassRef + storageClassSuffix + string(corev1.ResourceRequestsStorage))\n\t\t\tresult[storageClassStorage] = *requestedStorage\n\t\t}\n\t}\n\n\treturn result, nil\n}","line":{"from":145,"to":173}} {"id":100008768,"name":"getStorageUsage","signature":"func (p *pvcEvaluator) getStorageUsage(pvc *corev1.PersistentVolumeClaim) *resource.Quantity","file":"pkg/quota/v1/evaluator/core/persistent_volume_claims.go","code":"func (p *pvcEvaluator) getStorageUsage(pvc *corev1.PersistentVolumeClaim) *resource.Quantity {\n\tvar result *resource.Quantity\n\troundUpFunc := func(i *resource.Quantity) *resource.Quantity {\n\t\troundedRequest := i.DeepCopy()\n\t\tif !roundedRequest.RoundUp(0) {\n\t\t\t// Ensure storage requests are counted as whole byte values, to pass resourcequota validation.\n\t\t\t// See https://issue.k8s.io/94313\n\t\t\treturn \u0026roundedRequest\n\t\t}\n\t\treturn i\n\t}\n\n\tif userRequest, ok := pvc.Spec.Resources.Requests[corev1.ResourceStorage]; ok {\n\t\tresult = roundUpFunc(\u0026userRequest)\n\t}\n\n\tif utilfeature.DefaultFeatureGate.Enabled(k8sfeatures.RecoverVolumeExpansionFailure) \u0026\u0026 result != nil {\n\t\tif len(pvc.Status.AllocatedResources) == 0 {\n\t\t\treturn result\n\t\t}\n\n\t\t// if AllocatedResources is set and is greater than user request, we should use it.\n\t\tif allocatedRequest, ok := pvc.Status.AllocatedResources[corev1.ResourceStorage]; ok {\n\t\t\tif allocatedRequest.Cmp(*result) \u003e 0 {\n\t\t\t\tresult = roundUpFunc(\u0026allocatedRequest)\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}","line":{"from":175,"to":204}} {"id":100008769,"name":"UsageStats","signature":"func (p *pvcEvaluator) UsageStats(options quota.UsageStatsOptions) (quota.UsageStats, error)","file":"pkg/quota/v1/evaluator/core/persistent_volume_claims.go","code":"// UsageStats calculates aggregate usage for the object.\nfunc (p *pvcEvaluator) UsageStats(options quota.UsageStatsOptions) (quota.UsageStats, error) {\n\treturn generic.CalculateUsageStats(options, p.listFuncByNamespace, generic.MatchesNoScopeFunc, p.Usage)\n}","line":{"from":206,"to":209}} {"id":100008770,"name":"toExternalPersistentVolumeClaimOrError","signature":"func toExternalPersistentVolumeClaimOrError(obj runtime.Object) (*corev1.PersistentVolumeClaim, error)","file":"pkg/quota/v1/evaluator/core/persistent_volume_claims.go","code":"func toExternalPersistentVolumeClaimOrError(obj runtime.Object) (*corev1.PersistentVolumeClaim, error) {\n\tpvc := \u0026corev1.PersistentVolumeClaim{}\n\tswitch t := obj.(type) {\n\tcase *corev1.PersistentVolumeClaim:\n\t\tpvc = t\n\tcase *api.PersistentVolumeClaim:\n\t\tif err := k8s_api_v1.Convert_core_PersistentVolumeClaim_To_v1_PersistentVolumeClaim(t, pvc, nil); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"expect *api.PersistentVolumeClaim or *v1.PersistentVolumeClaim, got %v\", t)\n\t}\n\treturn pvc, nil\n}","line":{"from":214,"to":227}} {"id":100008771,"name":"RequiresQuotaReplenish","signature":"func RequiresQuotaReplenish(pvc, oldPVC *corev1.PersistentVolumeClaim) bool","file":"pkg/quota/v1/evaluator/core/persistent_volume_claims.go","code":"// RequiresQuotaReplenish enables quota monitoring for PVCs.\nfunc RequiresQuotaReplenish(pvc, oldPVC *corev1.PersistentVolumeClaim) bool {\n\tif utilfeature.DefaultFeatureGate.Enabled(k8sfeatures.RecoverVolumeExpansionFailure) {\n\t\tif oldPVC.Status.AllocatedResources.Storage() != pvc.Status.AllocatedResources.Storage() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":229,"to":237}} {"id":100008772,"name":"maskResourceWithPrefix","signature":"func maskResourceWithPrefix(resource corev1.ResourceName, prefix string) corev1.ResourceName","file":"pkg/quota/v1/evaluator/core/pods.go","code":"// maskResourceWithPrefix mask resource with certain prefix\n// e.g. hugepages-XXX -\u003e requests.hugepages-XXX\nfunc maskResourceWithPrefix(resource corev1.ResourceName, prefix string) corev1.ResourceName {\n\treturn corev1.ResourceName(fmt.Sprintf(\"%s%s\", prefix, string(resource)))\n}","line":{"from":75,"to":79}} {"id":100008773,"name":"isExtendedResourceNameForQuota","signature":"func isExtendedResourceNameForQuota(name corev1.ResourceName) bool","file":"pkg/quota/v1/evaluator/core/pods.go","code":"// isExtendedResourceNameForQuota returns true if the extended resource name\n// has the quota related resource prefix.\nfunc isExtendedResourceNameForQuota(name corev1.ResourceName) bool {\n\t// As overcommit is not supported by extended resources for now,\n\t// only quota objects in format of \"requests.resourceName\" is allowed.\n\treturn !helper.IsNativeResource(name) \u0026\u0026 strings.HasPrefix(string(name), corev1.DefaultResourceRequestsPrefix)\n}","line":{"from":81,"to":87}} {"id":100008774,"name":"NewPodEvaluator","signature":"func NewPodEvaluator(f quota.ListerForResourceFunc, clock clock.Clock) quota.Evaluator","file":"pkg/quota/v1/evaluator/core/pods.go","code":"// NewPodEvaluator returns an evaluator that can evaluate pods\nfunc NewPodEvaluator(f quota.ListerForResourceFunc, clock clock.Clock) quota.Evaluator {\n\tlistFuncByNamespace := generic.ListResourceUsingListerFunc(f, corev1.SchemeGroupVersion.WithResource(\"pods\"))\n\tpodEvaluator := \u0026podEvaluator{listFuncByNamespace: listFuncByNamespace, clock: clock}\n\treturn podEvaluator\n}","line":{"from":102,"to":107}} {"id":100008775,"name":"Constraints","signature":"func (p *podEvaluator) Constraints(required []corev1.ResourceName, item runtime.Object) error","file":"pkg/quota/v1/evaluator/core/pods.go","code":"// Constraints verifies that all required resources are present on the pod\n// In addition, it validates that the resources are valid (i.e. requests \u003c limits)\nfunc (p *podEvaluator) Constraints(required []corev1.ResourceName, item runtime.Object) error {\n\tpod, err := toExternalPodOrError(item)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// BACKWARD COMPATIBILITY REQUIREMENT: if we quota cpu or memory, then each container\n\t// must make an explicit request for the resource. this was a mistake. it coupled\n\t// validation with resource counting, but we did this before QoS was even defined.\n\t// let's not make that mistake again with other resources now that QoS is defined.\n\trequiredSet := quota.ToSet(required).Intersection(validationSet)\n\tmissingSetResourceToContainerNames := make(map[string]sets.String)\n\tfor i := range pod.Spec.Containers {\n\t\tenforcePodContainerConstraints(\u0026pod.Spec.Containers[i], requiredSet, missingSetResourceToContainerNames)\n\t}\n\tfor i := range pod.Spec.InitContainers {\n\t\tenforcePodContainerConstraints(\u0026pod.Spec.InitContainers[i], requiredSet, missingSetResourceToContainerNames)\n\t}\n\tif len(missingSetResourceToContainerNames) == 0 {\n\t\treturn nil\n\t}\n\tvar resources = sets.NewString()\n\tfor resource := range missingSetResourceToContainerNames {\n\t\tresources.Insert(resource)\n\t}\n\tvar errorMessages = make([]string, 0, len(missingSetResourceToContainerNames))\n\tfor _, resource := range resources.List() {\n\t\terrorMessages = append(errorMessages, fmt.Sprintf(\"%s for: %s\", resource, strings.Join(missingSetResourceToContainerNames[resource].List(), \",\")))\n\t}\n\treturn fmt.Errorf(\"must specify %s\", strings.Join(errorMessages, \"; \"))\n}","line":{"from":117,"to":149}} {"id":100008776,"name":"GroupResource","signature":"func (p *podEvaluator) GroupResource() schema.GroupResource","file":"pkg/quota/v1/evaluator/core/pods.go","code":"// GroupResource that this evaluator tracks\nfunc (p *podEvaluator) GroupResource() schema.GroupResource {\n\treturn corev1.SchemeGroupVersion.WithResource(\"pods\").GroupResource()\n}","line":{"from":151,"to":154}} {"id":100008777,"name":"Handles","signature":"func (p *podEvaluator) Handles(a admission.Attributes) bool","file":"pkg/quota/v1/evaluator/core/pods.go","code":"// Handles returns true if the evaluator should handle the specified attributes.\nfunc (p *podEvaluator) Handles(a admission.Attributes) bool {\n\top := a.GetOperation()\n\tif op == admission.Create {\n\t\treturn true\n\t}\n\tif feature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) \u0026\u0026 op == admission.Update {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":156,"to":166}} {"id":100008778,"name":"Matches","signature":"func (p *podEvaluator) Matches(resourceQuota *corev1.ResourceQuota, item runtime.Object) (bool, error)","file":"pkg/quota/v1/evaluator/core/pods.go","code":"// Matches returns true if the evaluator matches the specified quota with the provided input item\nfunc (p *podEvaluator) Matches(resourceQuota *corev1.ResourceQuota, item runtime.Object) (bool, error) {\n\treturn generic.Matches(resourceQuota, item, p.MatchingResources, podMatchesScopeFunc)\n}","line":{"from":168,"to":171}} {"id":100008779,"name":"MatchingResources","signature":"func (p *podEvaluator) MatchingResources(input []corev1.ResourceName) []corev1.ResourceName","file":"pkg/quota/v1/evaluator/core/pods.go","code":"// MatchingResources takes the input specified list of resources and returns the set of resources it matches.\nfunc (p *podEvaluator) MatchingResources(input []corev1.ResourceName) []corev1.ResourceName {\n\tresult := quota.Intersection(input, podResources)\n\tfor _, resource := range input {\n\t\t// for resources with certain prefix, e.g. hugepages\n\t\tif quota.ContainsPrefix(podResourcePrefixes, resource) {\n\t\t\tresult = append(result, resource)\n\t\t}\n\t\t// for extended resources\n\t\tif isExtendedResourceNameForQuota(resource) {\n\t\t\tresult = append(result, resource)\n\t\t}\n\t}\n\n\treturn result\n}","line":{"from":173,"to":188}} {"id":100008780,"name":"MatchingScopes","signature":"func (p *podEvaluator) MatchingScopes(item runtime.Object, scopeSelectors []corev1.ScopedResourceSelectorRequirement) ([]corev1.ScopedResourceSelectorRequirement, error)","file":"pkg/quota/v1/evaluator/core/pods.go","code":"// MatchingScopes takes the input specified list of scopes and pod object. Returns the set of scope selectors pod matches.\nfunc (p *podEvaluator) MatchingScopes(item runtime.Object, scopeSelectors []corev1.ScopedResourceSelectorRequirement) ([]corev1.ScopedResourceSelectorRequirement, error) {\n\tmatchedScopes := []corev1.ScopedResourceSelectorRequirement{}\n\tfor _, selector := range scopeSelectors {\n\t\tmatch, err := podMatchesScopeFunc(selector, item)\n\t\tif err != nil {\n\t\t\treturn []corev1.ScopedResourceSelectorRequirement{}, fmt.Errorf(\"error on matching scope %v: %v\", selector, err)\n\t\t}\n\t\tif match {\n\t\t\tmatchedScopes = append(matchedScopes, selector)\n\t\t}\n\t}\n\treturn matchedScopes, nil\n}","line":{"from":190,"to":203}} {"id":100008781,"name":"UncoveredQuotaScopes","signature":"func (p *podEvaluator) UncoveredQuotaScopes(limitedScopes []corev1.ScopedResourceSelectorRequirement, matchedQuotaScopes []corev1.ScopedResourceSelectorRequirement) ([]corev1.ScopedResourceSelectorRequirement, error)","file":"pkg/quota/v1/evaluator/core/pods.go","code":"// UncoveredQuotaScopes takes the input matched scopes which are limited by configuration and the matched quota scopes.\n// It returns the scopes which are in limited scopes but don't have a corresponding covering quota scope\nfunc (p *podEvaluator) UncoveredQuotaScopes(limitedScopes []corev1.ScopedResourceSelectorRequirement, matchedQuotaScopes []corev1.ScopedResourceSelectorRequirement) ([]corev1.ScopedResourceSelectorRequirement, error) {\n\tuncoveredScopes := []corev1.ScopedResourceSelectorRequirement{}\n\tfor _, selector := range limitedScopes {\n\t\tisCovered := false\n\t\tfor _, matchedScopeSelector := range matchedQuotaScopes {\n\t\t\tif matchedScopeSelector.ScopeName == selector.ScopeName {\n\t\t\t\tisCovered = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !isCovered {\n\t\t\tuncoveredScopes = append(uncoveredScopes, selector)\n\t\t}\n\t}\n\treturn uncoveredScopes, nil\n}","line":{"from":205,"to":223}} {"id":100008782,"name":"Usage","signature":"func (p *podEvaluator) Usage(item runtime.Object) (corev1.ResourceList, error)","file":"pkg/quota/v1/evaluator/core/pods.go","code":"// Usage knows how to measure usage associated with pods\nfunc (p *podEvaluator) Usage(item runtime.Object) (corev1.ResourceList, error) {\n\t// delegate to normal usage\n\treturn PodUsageFunc(item, p.clock)\n}","line":{"from":225,"to":229}} {"id":100008783,"name":"UsageStats","signature":"func (p *podEvaluator) UsageStats(options quota.UsageStatsOptions) (quota.UsageStats, error)","file":"pkg/quota/v1/evaluator/core/pods.go","code":"// UsageStats calculates aggregate usage for the object.\nfunc (p *podEvaluator) UsageStats(options quota.UsageStatsOptions) (quota.UsageStats, error) {\n\treturn generic.CalculateUsageStats(options, p.listFuncByNamespace, podMatchesScopeFunc, p.Usage)\n}","line":{"from":231,"to":234}} {"id":100008784,"name":"enforcePodContainerConstraints","signature":"func enforcePodContainerConstraints(container *corev1.Container, requiredSet sets.String, missingSetResourceToContainerNames map[string]sets.String)","file":"pkg/quota/v1/evaluator/core/pods.go","code":"// enforcePodContainerConstraints checks for required resources that are not set on this container and\n// adds them to missingSet.\nfunc enforcePodContainerConstraints(container *corev1.Container, requiredSet sets.String, missingSetResourceToContainerNames map[string]sets.String) {\n\trequests := container.Resources.Requests\n\tlimits := container.Resources.Limits\n\tcontainerUsage := podComputeUsageHelper(requests, limits)\n\tcontainerSet := quota.ToSet(quota.ResourceNames(containerUsage))\n\tif !containerSet.Equal(requiredSet) {\n\t\tif difference := requiredSet.Difference(containerSet); difference.Len() != 0 {\n\t\t\tfor _, diff := range difference.List() {\n\t\t\t\tif _, ok := missingSetResourceToContainerNames[diff]; !ok {\n\t\t\t\t\tmissingSetResourceToContainerNames[diff] = sets.NewString(container.Name)\n\t\t\t\t} else {\n\t\t\t\t\tmissingSetResourceToContainerNames[diff].Insert(container.Name)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":239,"to":257}} {"id":100008785,"name":"podComputeUsageHelper","signature":"func podComputeUsageHelper(requests corev1.ResourceList, limits corev1.ResourceList) corev1.ResourceList","file":"pkg/quota/v1/evaluator/core/pods.go","code":"// podComputeUsageHelper can summarize the pod compute quota usage based on requests and limits\nfunc podComputeUsageHelper(requests corev1.ResourceList, limits corev1.ResourceList) corev1.ResourceList {\n\tresult := corev1.ResourceList{}\n\tresult[corev1.ResourcePods] = resource.MustParse(\"1\")\n\tif request, found := requests[corev1.ResourceCPU]; found {\n\t\tresult[corev1.ResourceCPU] = request\n\t\tresult[corev1.ResourceRequestsCPU] = request\n\t}\n\tif limit, found := limits[corev1.ResourceCPU]; found {\n\t\tresult[corev1.ResourceLimitsCPU] = limit\n\t}\n\tif request, found := requests[corev1.ResourceMemory]; found {\n\t\tresult[corev1.ResourceMemory] = request\n\t\tresult[corev1.ResourceRequestsMemory] = request\n\t}\n\tif limit, found := limits[corev1.ResourceMemory]; found {\n\t\tresult[corev1.ResourceLimitsMemory] = limit\n\t}\n\tif request, found := requests[corev1.ResourceEphemeralStorage]; found {\n\t\tresult[corev1.ResourceEphemeralStorage] = request\n\t\tresult[corev1.ResourceRequestsEphemeralStorage] = request\n\t}\n\tif limit, found := limits[corev1.ResourceEphemeralStorage]; found {\n\t\tresult[corev1.ResourceLimitsEphemeralStorage] = limit\n\t}\n\tfor resource, request := range requests {\n\t\t// for resources with certain prefix, e.g. hugepages\n\t\tif quota.ContainsPrefix(requestedResourcePrefixes, resource) {\n\t\t\tresult[resource] = request\n\t\t\tresult[maskResourceWithPrefix(resource, corev1.DefaultResourceRequestsPrefix)] = request\n\t\t}\n\t\t// for extended resources\n\t\tif helper.IsExtendedResourceName(resource) {\n\t\t\t// only quota objects in format of \"requests.resourceName\" is allowed for extended resource.\n\t\t\tresult[maskResourceWithPrefix(resource, corev1.DefaultResourceRequestsPrefix)] = request\n\t\t}\n\t}\n\n\treturn result\n}","line":{"from":259,"to":298}} {"id":100008786,"name":"toExternalPodOrError","signature":"func toExternalPodOrError(obj runtime.Object) (*corev1.Pod, error)","file":"pkg/quota/v1/evaluator/core/pods.go","code":"func toExternalPodOrError(obj runtime.Object) (*corev1.Pod, error) {\n\tpod := \u0026corev1.Pod{}\n\tswitch t := obj.(type) {\n\tcase *corev1.Pod:\n\t\tpod = t\n\tcase *api.Pod:\n\t\tif err := k8s_api_v1.Convert_core_Pod_To_v1_Pod(t, pod, nil); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"expect *api.Pod or *v1.Pod, got %v\", t)\n\t}\n\treturn pod, nil\n}","line":{"from":300,"to":313}} {"id":100008787,"name":"podMatchesScopeFunc","signature":"func podMatchesScopeFunc(selector corev1.ScopedResourceSelectorRequirement, object runtime.Object) (bool, error)","file":"pkg/quota/v1/evaluator/core/pods.go","code":"// podMatchesScopeFunc is a function that knows how to evaluate if a pod matches a scope\nfunc podMatchesScopeFunc(selector corev1.ScopedResourceSelectorRequirement, object runtime.Object) (bool, error) {\n\tpod, err := toExternalPodOrError(object)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tswitch selector.ScopeName {\n\tcase corev1.ResourceQuotaScopeTerminating:\n\t\treturn isTerminating(pod), nil\n\tcase corev1.ResourceQuotaScopeNotTerminating:\n\t\treturn !isTerminating(pod), nil\n\tcase corev1.ResourceQuotaScopeBestEffort:\n\t\treturn isBestEffort(pod), nil\n\tcase corev1.ResourceQuotaScopeNotBestEffort:\n\t\treturn !isBestEffort(pod), nil\n\tcase corev1.ResourceQuotaScopePriorityClass:\n\t\tif selector.Operator == corev1.ScopeSelectorOpExists {\n\t\t\t// This is just checking for existence of a priorityClass on the pod,\n\t\t\t// no need to take the overhead of selector parsing/evaluation.\n\t\t\treturn len(pod.Spec.PriorityClassName) != 0, nil\n\t\t}\n\t\treturn podMatchesSelector(pod, selector)\n\tcase corev1.ResourceQuotaScopeCrossNamespacePodAffinity:\n\t\treturn usesCrossNamespacePodAffinity(pod), nil\n\t}\n\treturn false, nil\n}","line":{"from":315,"to":341}} {"id":100008788,"name":"PodUsageFunc","signature":"func PodUsageFunc(obj runtime.Object, clock clock.Clock) (corev1.ResourceList, error)","file":"pkg/quota/v1/evaluator/core/pods.go","code":"// PodUsageFunc returns the quota usage for a pod.\n// A pod is charged for quota if the following are not true.\n// - pod has a terminal phase (failed or succeeded)\n// - pod has been marked for deletion and grace period has expired\nfunc PodUsageFunc(obj runtime.Object, clock clock.Clock) (corev1.ResourceList, error) {\n\tpod, err := toExternalPodOrError(obj)\n\tif err != nil {\n\t\treturn corev1.ResourceList{}, err\n\t}\n\n\t// always quota the object count (even if the pod is end of life)\n\t// object count quotas track all objects that are in storage.\n\t// where \"pods\" tracks all pods that have not reached a terminal state,\n\t// count/pods tracks all pods independent of state.\n\tresult := corev1.ResourceList{\n\t\tpodObjectCountName: *(resource.NewQuantity(1, resource.DecimalSI)),\n\t}\n\n\t// by convention, we do not quota compute resources that have reached end-of life\n\t// note: the \"pods\" resource is considered a compute resource since it is tied to life-cycle.\n\tif !QuotaV1Pod(pod, clock) {\n\t\treturn result, nil\n\t}\n\n\topts := resourcehelper.PodResourcesOptions{\n\t\tInPlacePodVerticalScalingEnabled: feature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling),\n\t}\n\trequests := resourcehelper.PodRequests(pod, opts)\n\tlimits := resourcehelper.PodLimits(pod, opts)\n\n\tresult = quota.Add(result, podComputeUsageHelper(requests, limits))\n\treturn result, nil\n}","line":{"from":343,"to":375}} {"id":100008789,"name":"isBestEffort","signature":"func isBestEffort(pod *corev1.Pod) bool","file":"pkg/quota/v1/evaluator/core/pods.go","code":"func isBestEffort(pod *corev1.Pod) bool {\n\treturn qos.GetPodQOS(pod) == corev1.PodQOSBestEffort\n}","line":{"from":377,"to":379}} {"id":100008790,"name":"isTerminating","signature":"func isTerminating(pod *corev1.Pod) bool","file":"pkg/quota/v1/evaluator/core/pods.go","code":"func isTerminating(pod *corev1.Pod) bool {\n\tif pod.Spec.ActiveDeadlineSeconds != nil \u0026\u0026 *pod.Spec.ActiveDeadlineSeconds \u003e= int64(0) {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":381,"to":386}} {"id":100008791,"name":"podMatchesSelector","signature":"func podMatchesSelector(pod *corev1.Pod, selector corev1.ScopedResourceSelectorRequirement) (bool, error)","file":"pkg/quota/v1/evaluator/core/pods.go","code":"func podMatchesSelector(pod *corev1.Pod, selector corev1.ScopedResourceSelectorRequirement) (bool, error) {\n\tlabelSelector, err := helper.ScopedResourceSelectorRequirementsAsSelector(selector)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"failed to parse and convert selector: %v\", err)\n\t}\n\tvar m map[string]string\n\tif len(pod.Spec.PriorityClassName) != 0 {\n\t\tm = map[string]string{string(corev1.ResourceQuotaScopePriorityClass): pod.Spec.PriorityClassName}\n\t}\n\tif labelSelector.Matches(labels.Set(m)) {\n\t\treturn true, nil\n\t}\n\treturn false, nil\n}","line":{"from":388,"to":401}} {"id":100008792,"name":"crossNamespacePodAffinityTerm","signature":"func crossNamespacePodAffinityTerm(term *corev1.PodAffinityTerm) bool","file":"pkg/quota/v1/evaluator/core/pods.go","code":"func crossNamespacePodAffinityTerm(term *corev1.PodAffinityTerm) bool {\n\treturn len(term.Namespaces) != 0 || term.NamespaceSelector != nil\n}","line":{"from":403,"to":405}} {"id":100008793,"name":"crossNamespacePodAffinityTerms","signature":"func crossNamespacePodAffinityTerms(terms []corev1.PodAffinityTerm) bool","file":"pkg/quota/v1/evaluator/core/pods.go","code":"func crossNamespacePodAffinityTerms(terms []corev1.PodAffinityTerm) bool {\n\tfor _, t := range terms {\n\t\tif crossNamespacePodAffinityTerm(\u0026t) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":407,"to":414}} {"id":100008794,"name":"crossNamespaceWeightedPodAffinityTerms","signature":"func crossNamespaceWeightedPodAffinityTerms(terms []corev1.WeightedPodAffinityTerm) bool","file":"pkg/quota/v1/evaluator/core/pods.go","code":"func crossNamespaceWeightedPodAffinityTerms(terms []corev1.WeightedPodAffinityTerm) bool {\n\tfor _, t := range terms {\n\t\tif crossNamespacePodAffinityTerm(\u0026t.PodAffinityTerm) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":416,"to":423}} {"id":100008795,"name":"usesCrossNamespacePodAffinity","signature":"func usesCrossNamespacePodAffinity(pod *corev1.Pod) bool","file":"pkg/quota/v1/evaluator/core/pods.go","code":"func usesCrossNamespacePodAffinity(pod *corev1.Pod) bool {\n\tif pod == nil || pod.Spec.Affinity == nil {\n\t\treturn false\n\t}\n\n\taffinity := pod.Spec.Affinity.PodAffinity\n\tif affinity != nil {\n\t\tif crossNamespacePodAffinityTerms(affinity.RequiredDuringSchedulingIgnoredDuringExecution) {\n\t\t\treturn true\n\t\t}\n\t\tif crossNamespaceWeightedPodAffinityTerms(affinity.PreferredDuringSchedulingIgnoredDuringExecution) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tantiAffinity := pod.Spec.Affinity.PodAntiAffinity\n\tif antiAffinity != nil {\n\t\tif crossNamespacePodAffinityTerms(antiAffinity.RequiredDuringSchedulingIgnoredDuringExecution) {\n\t\t\treturn true\n\t\t}\n\t\tif crossNamespaceWeightedPodAffinityTerms(antiAffinity.PreferredDuringSchedulingIgnoredDuringExecution) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":425,"to":451}} {"id":100008796,"name":"QuotaV1Pod","signature":"func QuotaV1Pod(pod *corev1.Pod, clock clock.Clock) bool","file":"pkg/quota/v1/evaluator/core/pods.go","code":"// QuotaV1Pod returns true if the pod is eligible to track against a quota\n// if it's not in a terminal state according to its phase.\nfunc QuotaV1Pod(pod *corev1.Pod, clock clock.Clock) bool {\n\t// if pod is terminal, ignore it for quota\n\tif corev1.PodFailed == pod.Status.Phase || corev1.PodSucceeded == pod.Status.Phase {\n\t\treturn false\n\t}\n\t// if pods are stuck terminating (for example, a node is lost), we do not want\n\t// to charge the user for that pod in quota because it could prevent them from\n\t// scaling up new pods to service their application.\n\tif pod.DeletionTimestamp != nil \u0026\u0026 pod.DeletionGracePeriodSeconds != nil {\n\t\tnow := clock.Now()\n\t\tdeletionTime := pod.DeletionTimestamp.Time\n\t\tgracePeriod := time.Duration(*pod.DeletionGracePeriodSeconds) * time.Second\n\t\tif now.After(deletionTime.Add(gracePeriod)) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":453,"to":472}} {"id":100008797,"name":"NewEvaluators","signature":"func NewEvaluators(f quota.ListerForResourceFunc) []quota.Evaluator","file":"pkg/quota/v1/evaluator/core/registry.go","code":"// NewEvaluators returns the list of static evaluators that manage more than counts\nfunc NewEvaluators(f quota.ListerForResourceFunc) []quota.Evaluator {\n\t// these evaluators have special logic\n\tresult := []quota.Evaluator{\n\t\tNewPodEvaluator(f, clock.RealClock{}),\n\t\tNewServiceEvaluator(f),\n\t\tNewPersistentVolumeClaimEvaluator(f),\n\t}\n\t// these evaluators require an alias for backwards compatibility\n\tfor gvr, alias := range legacyObjectCountAliases {\n\t\tresult = append(result,\n\t\t\tgeneric.NewObjectCountEvaluator(gvr.GroupResource(), generic.ListResourceUsingListerFunc(f, gvr), alias))\n\t}\n\treturn result\n}","line":{"from":35,"to":49}} {"id":100008798,"name":"NewServiceEvaluator","signature":"func NewServiceEvaluator(f quota.ListerForResourceFunc) quota.Evaluator","file":"pkg/quota/v1/evaluator/core/services.go","code":"// NewServiceEvaluator returns an evaluator that can evaluate services.\nfunc NewServiceEvaluator(f quota.ListerForResourceFunc) quota.Evaluator {\n\tlistFuncByNamespace := generic.ListResourceUsingListerFunc(f, corev1.SchemeGroupVersion.WithResource(\"services\"))\n\tserviceEvaluator := \u0026serviceEvaluator{listFuncByNamespace: listFuncByNamespace}\n\treturn serviceEvaluator\n}","line":{"from":44,"to":49}} {"id":100008799,"name":"Constraints","signature":"func (p *serviceEvaluator) Constraints(required []corev1.ResourceName, item runtime.Object) error","file":"pkg/quota/v1/evaluator/core/services.go","code":"// Constraints verifies that all required resources are present on the item\nfunc (p *serviceEvaluator) Constraints(required []corev1.ResourceName, item runtime.Object) error {\n\t// this is a no-op for services\n\treturn nil\n}","line":{"from":57,"to":61}} {"id":100008800,"name":"GroupResource","signature":"func (p *serviceEvaluator) GroupResource() schema.GroupResource","file":"pkg/quota/v1/evaluator/core/services.go","code":"// GroupResource that this evaluator tracks\nfunc (p *serviceEvaluator) GroupResource() schema.GroupResource {\n\treturn corev1.SchemeGroupVersion.WithResource(\"services\").GroupResource()\n}","line":{"from":63,"to":66}} {"id":100008801,"name":"Handles","signature":"func (p *serviceEvaluator) Handles(a admission.Attributes) bool","file":"pkg/quota/v1/evaluator/core/services.go","code":"// Handles returns true of the evaluator should handle the specified operation.\nfunc (p *serviceEvaluator) Handles(a admission.Attributes) bool {\n\toperation := a.GetOperation()\n\t// We handle create and update because a service type can change.\n\treturn admission.Create == operation || admission.Update == operation\n}","line":{"from":68,"to":73}} {"id":100008802,"name":"Matches","signature":"func (p *serviceEvaluator) Matches(resourceQuota *corev1.ResourceQuota, item runtime.Object) (bool, error)","file":"pkg/quota/v1/evaluator/core/services.go","code":"// Matches returns true if the evaluator matches the specified quota with the provided input item\nfunc (p *serviceEvaluator) Matches(resourceQuota *corev1.ResourceQuota, item runtime.Object) (bool, error) {\n\treturn generic.Matches(resourceQuota, item, p.MatchingResources, generic.MatchesNoScopeFunc)\n}","line":{"from":75,"to":78}} {"id":100008803,"name":"MatchingResources","signature":"func (p *serviceEvaluator) MatchingResources(input []corev1.ResourceName) []corev1.ResourceName","file":"pkg/quota/v1/evaluator/core/services.go","code":"// MatchingResources takes the input specified list of resources and returns the set of resources it matches.\nfunc (p *serviceEvaluator) MatchingResources(input []corev1.ResourceName) []corev1.ResourceName {\n\treturn quota.Intersection(input, serviceResources)\n}","line":{"from":80,"to":83}} {"id":100008804,"name":"MatchingScopes","signature":"func (p *serviceEvaluator) MatchingScopes(item runtime.Object, scopes []corev1.ScopedResourceSelectorRequirement) ([]corev1.ScopedResourceSelectorRequirement, error)","file":"pkg/quota/v1/evaluator/core/services.go","code":"// MatchingScopes takes the input specified list of scopes and input object. Returns the set of scopes resource matches.\nfunc (p *serviceEvaluator) MatchingScopes(item runtime.Object, scopes []corev1.ScopedResourceSelectorRequirement) ([]corev1.ScopedResourceSelectorRequirement, error) {\n\treturn []corev1.ScopedResourceSelectorRequirement{}, nil\n}","line":{"from":85,"to":88}} {"id":100008805,"name":"UncoveredQuotaScopes","signature":"func (p *serviceEvaluator) UncoveredQuotaScopes(limitedScopes []corev1.ScopedResourceSelectorRequirement, matchedQuotaScopes []corev1.ScopedResourceSelectorRequirement) ([]corev1.ScopedResourceSelectorRequirement, error)","file":"pkg/quota/v1/evaluator/core/services.go","code":"// UncoveredQuotaScopes takes the input matched scopes which are limited by configuration and the matched quota scopes.\n// It returns the scopes which are in limited scopes but don't have a corresponding covering quota scope\nfunc (p *serviceEvaluator) UncoveredQuotaScopes(limitedScopes []corev1.ScopedResourceSelectorRequirement, matchedQuotaScopes []corev1.ScopedResourceSelectorRequirement) ([]corev1.ScopedResourceSelectorRequirement, error) {\n\treturn []corev1.ScopedResourceSelectorRequirement{}, nil\n}","line":{"from":90,"to":94}} {"id":100008806,"name":"toExternalServiceOrError","signature":"func toExternalServiceOrError(obj runtime.Object) (*corev1.Service, error)","file":"pkg/quota/v1/evaluator/core/services.go","code":"// convert the input object to an internal service object or error.\nfunc toExternalServiceOrError(obj runtime.Object) (*corev1.Service, error) {\n\tsvc := \u0026corev1.Service{}\n\tswitch t := obj.(type) {\n\tcase *corev1.Service:\n\t\tsvc = t\n\tcase *api.Service:\n\t\tif err := k8s_api_v1.Convert_core_Service_To_v1_Service(t, svc, nil); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"expect *api.Service or *v1.Service, got %v\", t)\n\t}\n\treturn svc, nil\n}","line":{"from":96,"to":110}} {"id":100008807,"name":"Usage","signature":"func (p *serviceEvaluator) Usage(item runtime.Object) (corev1.ResourceList, error)","file":"pkg/quota/v1/evaluator/core/services.go","code":"// Usage knows how to measure usage associated with services\nfunc (p *serviceEvaluator) Usage(item runtime.Object) (corev1.ResourceList, error) {\n\tresult := corev1.ResourceList{}\n\tsvc, err := toExternalServiceOrError(item)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tports := len(svc.Spec.Ports)\n\t// default service usage\n\tresult[serviceObjectCountName] = *(resource.NewQuantity(1, resource.DecimalSI))\n\tresult[corev1.ResourceServices] = *(resource.NewQuantity(1, resource.DecimalSI))\n\tresult[corev1.ResourceServicesLoadBalancers] = resource.Quantity{Format: resource.DecimalSI}\n\tresult[corev1.ResourceServicesNodePorts] = resource.Quantity{Format: resource.DecimalSI}\n\tswitch svc.Spec.Type {\n\tcase corev1.ServiceTypeNodePort:\n\t\t// node port services need to count node ports\n\t\tvalue := resource.NewQuantity(int64(ports), resource.DecimalSI)\n\t\tresult[corev1.ResourceServicesNodePorts] = *value\n\tcase corev1.ServiceTypeLoadBalancer:\n\t\t// load balancer services need to count node ports. If creation of node ports\n\t\t// is suppressed only ports with explicit NodePort values are counted.\n\t\t// nodeports won't be allocated yet, so we can't simply count the actual values.\n\t\t// We need to look at the intent.\n\t\tif svc.Spec.AllocateLoadBalancerNodePorts != nil \u0026\u0026\n\t\t\t*svc.Spec.AllocateLoadBalancerNodePorts == false {\n\t\t\tresult[corev1.ResourceServicesNodePorts] = *portsWithNodePorts(svc)\n\t\t} else {\n\t\t\tvalue := resource.NewQuantity(int64(ports), resource.DecimalSI)\n\t\t\tresult[corev1.ResourceServicesNodePorts] = *value\n\t\t}\n\t\tresult[corev1.ResourceServicesLoadBalancers] = *(resource.NewQuantity(1, resource.DecimalSI))\n\t}\n\treturn result, nil\n}","line":{"from":112,"to":145}} {"id":100008808,"name":"portsWithNodePorts","signature":"func portsWithNodePorts(svc *corev1.Service) *resource.Quantity","file":"pkg/quota/v1/evaluator/core/services.go","code":"func portsWithNodePorts(svc *corev1.Service) *resource.Quantity {\n\tcount := 0\n\tfor _, p := range svc.Spec.Ports {\n\t\tif p.NodePort != 0 {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn resource.NewQuantity(int64(count), resource.DecimalSI)\n}","line":{"from":147,"to":155}} {"id":100008809,"name":"UsageStats","signature":"func (p *serviceEvaluator) UsageStats(options quota.UsageStatsOptions) (quota.UsageStats, error)","file":"pkg/quota/v1/evaluator/core/services.go","code":"// UsageStats calculates aggregate usage for the object.\nfunc (p *serviceEvaluator) UsageStats(options quota.UsageStatsOptions) (quota.UsageStats, error) {\n\treturn generic.CalculateUsageStats(options, p.listFuncByNamespace, generic.MatchesNoScopeFunc, p.Usage)\n}","line":{"from":157,"to":160}} {"id":100008810,"name":"GetQuotaServiceType","signature":"func GetQuotaServiceType(service *corev1.Service) corev1.ServiceType","file":"pkg/quota/v1/evaluator/core/services.go","code":"// GetQuotaServiceType returns ServiceType if the service type is eligible to track against a quota, nor return \"\"\nfunc GetQuotaServiceType(service *corev1.Service) corev1.ServiceType {\n\tswitch service.Spec.Type {\n\tcase corev1.ServiceTypeNodePort:\n\t\treturn corev1.ServiceTypeNodePort\n\tcase corev1.ServiceTypeLoadBalancer:\n\t\treturn corev1.ServiceTypeLoadBalancer\n\t}\n\treturn corev1.ServiceType(\"\")\n}","line":{"from":164,"to":173}} {"id":100008811,"name":"NewQuotaConfigurationForAdmission","signature":"func NewQuotaConfigurationForAdmission() quota.Configuration","file":"pkg/quota/v1/install/registry.go","code":"// NewQuotaConfigurationForAdmission returns a quota configuration for admission control.\nfunc NewQuotaConfigurationForAdmission() quota.Configuration {\n\tevaluators := core.NewEvaluators(nil)\n\treturn generic.NewConfiguration(evaluators, DefaultIgnoredResources())\n}","line":{"from":29,"to":33}} {"id":100008812,"name":"NewQuotaConfigurationForControllers","signature":"func NewQuotaConfigurationForControllers(f quota.ListerForResourceFunc) quota.Configuration","file":"pkg/quota/v1/install/registry.go","code":"// NewQuotaConfigurationForControllers returns a quota configuration for controllers.\nfunc NewQuotaConfigurationForControllers(f quota.ListerForResourceFunc) quota.Configuration {\n\tevaluators := core.NewEvaluators(f)\n\treturn generic.NewConfiguration(evaluators, DefaultIgnoredResources())\n}","line":{"from":35,"to":39}} {"id":100008813,"name":"DefaultIgnoredResources","signature":"func DefaultIgnoredResources() map[schema.GroupResource]struct{}","file":"pkg/quota/v1/install/registry.go","code":"// DefaultIgnoredResources returns the default set of resources that quota system\n// should ignore. This is exposed so downstream integrators can have access to them.\nfunc DefaultIgnoredResources() map[schema.GroupResource]struct{} {\n\treturn ignoredResources\n}","line":{"from":58,"to":62}} {"id":100008814,"name":"DefaultUpdateFilter","signature":"func DefaultUpdateFilter() func(resource schema.GroupVersionResource, oldObj, newObj interface{}) bool","file":"pkg/quota/v1/install/update_filter.go","code":"// DefaultUpdateFilter returns the default update filter for resource update events for consideration for quota.\nfunc DefaultUpdateFilter() func(resource schema.GroupVersionResource, oldObj, newObj interface{}) bool {\n\treturn func(resource schema.GroupVersionResource, oldObj, newObj interface{}) bool {\n\t\tswitch resource.GroupResource() {\n\t\tcase schema.GroupResource{Resource: \"pods\"}:\n\t\t\toldPod := oldObj.(*v1.Pod)\n\t\t\tnewPod := newObj.(*v1.Pod)\n\t\t\treturn core.QuotaV1Pod(oldPod, clock.RealClock{}) \u0026\u0026 !core.QuotaV1Pod(newPod, clock.RealClock{})\n\t\tcase schema.GroupResource{Resource: \"services\"}:\n\t\t\toldService := oldObj.(*v1.Service)\n\t\t\tnewService := newObj.(*v1.Service)\n\t\t\treturn core.GetQuotaServiceType(oldService) != core.GetQuotaServiceType(newService)\n\t\tcase schema.GroupResource{Resource: \"persistentvolumeclaims\"}:\n\t\t\toldPVC := oldObj.(*v1.PersistentVolumeClaim)\n\t\t\tnewPVC := newObj.(*v1.PersistentVolumeClaim)\n\t\t\treturn core.RequiresQuotaReplenish(newPVC, oldPVC)\n\t\t}\n\n\t\treturn false\n\t}\n}","line":{"from":26,"to":46}} {"id":100008815,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error)","file":"pkg/registry/admissionregistration/mutatingwebhookconfiguration/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against mutatingWebhookConfiguration.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026admissionregistration.MutatingWebhookConfiguration{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026admissionregistration.MutatingWebhookConfigurationList{} },\n\t\tObjectNameFunc: func(obj runtime.Object) (string, error) {\n\t\t\treturn obj.(*admissionregistration.MutatingWebhookConfiguration).Name, nil\n\t\t},\n\t\tDefaultQualifiedResource: admissionregistration.Resource(\"mutatingwebhookconfigurations\"),\n\t\tSingularQualifiedResource: admissionregistration.Resource(\"mutatingwebhookconfiguration\"),\n\n\t\tCreateStrategy: mutatingwebhookconfiguration.Strategy,\n\t\tUpdateStrategy: mutatingwebhookconfiguration.Strategy,\n\t\tDeleteStrategy: mutatingwebhookconfiguration.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026REST{store}, nil\n}","line":{"from":36,"to":58}} {"id":100008816,"name":"Categories","signature":"func (r *REST) Categories() []string","file":"pkg/registry/admissionregistration/mutatingwebhookconfiguration/storage/storage.go","code":"// Categories implements the CategoriesProvider interface. Returns a list of categories a resource is part of.\nfunc (r *REST) Categories() []string {\n\treturn []string{\"api-extensions\"}\n}","line":{"from":63,"to":66}} {"id":100008817,"name":"NamespaceScoped","signature":"func (mutatingWebhookConfigurationStrategy) NamespaceScoped() bool","file":"pkg/registry/admissionregistration/mutatingwebhookconfiguration/strategy.go","code":"// NamespaceScoped returns false because MutatingWebhookConfiguration is cluster-scoped resource.\nfunc (mutatingWebhookConfigurationStrategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":40,"to":43}} {"id":100008818,"name":"PrepareForCreate","signature":"func (mutatingWebhookConfigurationStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/admissionregistration/mutatingwebhookconfiguration/strategy.go","code":"// PrepareForCreate clears the status of an mutatingWebhookConfiguration before creation.\nfunc (mutatingWebhookConfigurationStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tic := obj.(*admissionregistration.MutatingWebhookConfiguration)\n\tic.Generation = 1\n\n\tadmissionregistration.DropDisabledMutatingWebhookConfigurationFields(ic, nil)\n}","line":{"from":45,"to":51}} {"id":100008819,"name":"WarningsOnCreate","signature":"func (mutatingWebhookConfigurationStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/admissionregistration/mutatingwebhookconfiguration/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (mutatingWebhookConfigurationStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":53,"to":56}} {"id":100008820,"name":"PrepareForUpdate","signature":"func (mutatingWebhookConfigurationStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/admissionregistration/mutatingwebhookconfiguration/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (mutatingWebhookConfigurationStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewIC := obj.(*admissionregistration.MutatingWebhookConfiguration)\n\toldIC := old.(*admissionregistration.MutatingWebhookConfiguration)\n\n\tadmissionregistration.DropDisabledMutatingWebhookConfigurationFields(newIC, oldIC)\n\t// Any changes to the spec increment the generation number, any changes to the\n\t// status should reflect the generation number of the corresponding object.\n\t// See metav1.ObjectMeta description for more information on Generation.\n\tif !reflect.DeepEqual(oldIC.Webhooks, newIC.Webhooks) {\n\t\tnewIC.Generation = oldIC.Generation + 1\n\t}\n}","line":{"from":58,"to":70}} {"id":100008821,"name":"Validate","signature":"func (mutatingWebhookConfigurationStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/admissionregistration/mutatingwebhookconfiguration/strategy.go","code":"// Validate validates a new mutatingWebhookConfiguration.\nfunc (mutatingWebhookConfigurationStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tic := obj.(*admissionregistration.MutatingWebhookConfiguration)\n\treturn validation.ValidateMutatingWebhookConfiguration(ic)\n}","line":{"from":72,"to":76}} {"id":100008822,"name":"Canonicalize","signature":"func (mutatingWebhookConfigurationStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/admissionregistration/mutatingwebhookconfiguration/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (mutatingWebhookConfigurationStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":78,"to":80}} {"id":100008823,"name":"AllowCreateOnUpdate","signature":"func (mutatingWebhookConfigurationStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/admissionregistration/mutatingwebhookconfiguration/strategy.go","code":"// AllowCreateOnUpdate is true for mutatingWebhookConfiguration; this means you may create one with a PUT request.\nfunc (mutatingWebhookConfigurationStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":82,"to":85}} {"id":100008824,"name":"ValidateUpdate","signature":"func (mutatingWebhookConfigurationStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/admissionregistration/mutatingwebhookconfiguration/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (mutatingWebhookConfigurationStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateMutatingWebhookConfigurationUpdate(obj.(*admissionregistration.MutatingWebhookConfiguration), old.(*admissionregistration.MutatingWebhookConfiguration))\n}","line":{"from":87,"to":90}} {"id":100008825,"name":"WarningsOnUpdate","signature":"func (mutatingWebhookConfigurationStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/admissionregistration/mutatingwebhookconfiguration/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (mutatingWebhookConfigurationStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":92,"to":95}} {"id":100008826,"name":"AllowUnconditionalUpdate","signature":"func (mutatingWebhookConfigurationStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/admissionregistration/mutatingwebhookconfiguration/strategy.go","code":"// AllowUnconditionalUpdate is the default update policy for mutatingWebhookConfiguration objects. Status update should\n// only be allowed if version match.\nfunc (mutatingWebhookConfigurationStrategy) AllowUnconditionalUpdate() bool {\n\treturn false\n}","line":{"from":97,"to":101}} {"id":100008827,"name":"Resolve","signature":"func (d *discoveryResourceResolver) Resolve(gvk schema.GroupVersionKind) (schema.GroupVersionResource, error)","file":"pkg/registry/admissionregistration/resolver/resolver.go","code":"func (d *discoveryResourceResolver) Resolve(gvk schema.GroupVersionKind) (schema.GroupVersionResource, error) {\n\tgv := gvk.GroupVersion()\n\t// TODO: refactor this into an efficient gvk --\u003e gvr resolver that remembers hits and re-resolves group/version info on misses\n\tresources, err := d.client.ServerResourcesForGroupVersion(gv.String())\n\tif err != nil {\n\t\treturn schema.GroupVersionResource{}, err\n\t}\n\tfor _, resource := range resources.APIResources {\n\t\tif resource.Kind != gvk.Kind {\n\t\t\t// ignore unrelated kinds\n\t\t\tcontinue\n\t\t}\n\t\tif strings.Contains(resource.Name, \"/\") {\n\t\t\t// ignore subresources\n\t\t\tcontinue\n\t\t}\n\t\tif resource.Group != \"\" \u0026\u0026 resource.Group != gvk.Group {\n\t\t\t// group didn't match\n\t\t\tcontinue\n\t\t}\n\t\tif resource.Version != \"\" \u0026\u0026 resource.Version != gvk.Version {\n\t\t\t// version didn't match\n\t\t\tcontinue\n\t\t}\n\t\treturn gv.WithResource(resource.Name), nil\n\t}\n\treturn schema.GroupVersionResource{}, \u0026meta.NoKindMatchError{GroupKind: gvk.GroupKind(), SearchedVersions: []string{gvk.Version}}\n}","line":{"from":35,"to":62}} {"id":100008828,"name":"NewDiscoveryResourceResolver","signature":"func NewDiscoveryResourceResolver(client discovery.DiscoveryInterface) (ResourceResolver, error)","file":"pkg/registry/admissionregistration/resolver/resolver.go","code":"func NewDiscoveryResourceResolver(client discovery.DiscoveryInterface) (ResourceResolver, error) {\n\treturn \u0026discoveryResourceResolver{client: client}, nil\n}","line":{"from":64,"to":66}} {"id":100008829,"name":"Resolve","signature":"func (f ResourceResolverFunc) Resolve(gvk schema.GroupVersionKind) (schema.GroupVersionResource, error)","file":"pkg/registry/admissionregistration/resolver/resolver.go","code":"func (f ResourceResolverFunc) Resolve(gvk schema.GroupVersionKind) (schema.GroupVersionResource, error) {\n\treturn f(gvk)\n}","line":{"from":70,"to":72}} {"id":100008830,"name":"NewRESTStorage","signature":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error)","file":"pkg/registry/admissionregistration/rest/storage_apiserver.go","code":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error) {\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(admissionregistration.GroupName, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs)\n\t// If you add a version here, be sure to add an entry in `k8s.io/kubernetes/cmd/kube-apiserver/app/aggregator.go with specific priorities.\n\t// TODO refactor the plumbing to provide the information in the APIGroupInfo\n\n\tif storageMap, err := p.v1Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[admissionregistrationv1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\tif storageMap, err := p.v1alpha1Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[admissionregistrationv1alpha1.SchemeGroupVersion.Version] = storageMap\n\t}\n\treturn apiGroupInfo, nil\n}","line":{"from":42,"to":59}} {"id":100008831,"name":"v1Storage","signature":"func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/admissionregistration/rest/storage_apiserver.go","code":"func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\t// validatingwebhookconfigurations\n\tif resource := \"validatingwebhookconfigurations\"; apiResourceConfigSource.ResourceEnabled(admissionregistrationv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tvalidatingStorage, err := validatingwebhookconfigurationstorage.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = validatingStorage\n\t}\n\n\t// mutatingwebhookconfigurations\n\tif resource := \"mutatingwebhookconfigurations\"; apiResourceConfigSource.ResourceEnabled(admissionregistrationv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tmutatingStorage, err := mutatingwebhookconfigurationstorage.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = mutatingStorage\n\t}\n\n\treturn storage, nil\n}","line":{"from":61,"to":83}} {"id":100008832,"name":"v1alpha1Storage","signature":"func (p RESTStorageProvider) v1alpha1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/admissionregistration/rest/storage_apiserver.go","code":"func (p RESTStorageProvider) v1alpha1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\t// use a simple wrapper so that initialization order won't cause a nil getter\n\tvar policyGetter rest.Getter\n\n\tr, err := resolver.NewDiscoveryResourceResolver(p.DiscoveryClient)\n\tif err != nil {\n\t\treturn storage, err\n\t}\n\n\t// validatingadmissionpolicies\n\tif resource := \"validatingadmissionpolicies\"; apiResourceConfigSource.ResourceEnabled(admissionregistrationv1alpha1.SchemeGroupVersion.WithResource(resource)) {\n\t\tpolicyStorage, policyStatusStorage, err := validatingadmissionpolicystorage.NewREST(restOptionsGetter, p.Authorizer, r)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tpolicyGetter = policyStorage\n\t\tstorage[resource] = policyStorage\n\t\tstorage[resource+\"/status\"] = policyStatusStorage\n\t}\n\n\t// validatingadmissionpolicybindings\n\tif resource := \"validatingadmissionpolicybindings\"; apiResourceConfigSource.ResourceEnabled(admissionregistrationv1alpha1.SchemeGroupVersion.WithResource(resource)) {\n\t\tpolicyBindingStorage, err := policybindingstorage.NewREST(restOptionsGetter, p.Authorizer, \u0026policybindingstorage.DefaultPolicyGetter{Getter: policyGetter}, r)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = policyBindingStorage\n\t}\n\n\treturn storage, nil\n}","line":{"from":85,"to":117}} {"id":100008833,"name":"GroupName","signature":"func (p RESTStorageProvider) GroupName() string","file":"pkg/registry/admissionregistration/rest/storage_apiserver.go","code":"func (p RESTStorageProvider) GroupName() string {\n\treturn admissionregistration.GroupName\n}","line":{"from":119,"to":121}} {"id":100008834,"name":"authorizeCreate","signature":"func (v *validatingAdmissionPolicyStrategy) authorizeCreate(ctx context.Context, obj runtime.Object) error","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/authz.go","code":"func (v *validatingAdmissionPolicyStrategy) authorizeCreate(ctx context.Context, obj runtime.Object) error {\n\tpolicy := obj.(*admissionregistration.ValidatingAdmissionPolicy)\n\tif policy.Spec.ParamKind == nil {\n\t\t// no paramRef in new object\n\t\treturn nil\n\t}\n\n\treturn v.authorize(ctx, policy)\n}","line":{"from":31,"to":39}} {"id":100008835,"name":"authorizeUpdate","signature":"func (v *validatingAdmissionPolicyStrategy) authorizeUpdate(ctx context.Context, obj, old runtime.Object) error","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/authz.go","code":"func (v *validatingAdmissionPolicyStrategy) authorizeUpdate(ctx context.Context, obj, old runtime.Object) error {\n\tpolicy := obj.(*admissionregistration.ValidatingAdmissionPolicy)\n\tif policy.Spec.ParamKind == nil {\n\t\t// no paramRef in new object\n\t\treturn nil\n\t}\n\n\toldPolicy := old.(*admissionregistration.ValidatingAdmissionPolicy)\n\tif oldPolicy.Spec.ParamKind != nil \u0026\u0026 *oldPolicy.Spec.ParamKind == *policy.Spec.ParamKind {\n\t\t// identical paramKind to old object\n\t\treturn nil\n\t}\n\n\treturn v.authorize(ctx, policy)\n}","line":{"from":41,"to":55}} {"id":100008836,"name":"authorize","signature":"func (v *validatingAdmissionPolicyStrategy) authorize(ctx context.Context, policy *admissionregistration.ValidatingAdmissionPolicy) error","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/authz.go","code":"func (v *validatingAdmissionPolicyStrategy) authorize(ctx context.Context, policy *admissionregistration.ValidatingAdmissionPolicy) error {\n\tif v.authorizer == nil || policy.Spec.ParamKind == nil {\n\t\treturn nil\n\t}\n\n\t// for superuser, skip all checks\n\tif rbacregistry.EscalationAllowed(ctx) {\n\t\treturn nil\n\t}\n\n\tuser, ok := genericapirequest.UserFrom(ctx)\n\tif !ok {\n\t\treturn fmt.Errorf(\"cannot identify user to authorize read access to paramKind resources\")\n\t}\n\n\tparamKind := policy.Spec.ParamKind\n\t// default to requiring permissions on all group/version/resources\n\tresource, apiGroup, apiVersion := \"*\", \"*\", \"*\"\n\tif gv, err := schema.ParseGroupVersion(paramKind.APIVersion); err == nil {\n\t\t// we only need to authorize the parsed group/version\n\t\tapiGroup = gv.Group\n\t\tapiVersion = gv.Version\n\t\tif gvr, err := v.resourceResolver.Resolve(gv.WithKind(paramKind.Kind)); err == nil {\n\t\t\t// we only need to authorize the resolved resource\n\t\t\tresource = gvr.Resource\n\t\t}\n\t}\n\n\t// require that the user can read (verb \"get\") the referred kind.\n\tattrs := authorizer.AttributesRecord{\n\t\tUser: user,\n\t\tVerb: \"get\",\n\t\tResourceRequest: true,\n\t\tName: \"*\",\n\t\tNamespace: \"*\",\n\t\tAPIGroup: apiGroup,\n\t\tAPIVersion: apiVersion,\n\t\tResource: resource,\n\t}\n\n\td, _, err := v.authorizer.Authorize(ctx, attrs)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif d != authorizer.DecisionAllow {\n\t\treturn fmt.Errorf(`user %v must have \"get\" permission on all objects of the referenced paramKind (kind=%s, apiVersion=%s)`, user, paramKind.Kind, paramKind.APIVersion)\n\t}\n\treturn nil\n}","line":{"from":57,"to":105}} {"id":100008837,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter, authorizer authorizer.Authorizer, resourceResolver resolver.ResourceResolver) (*REST, *StatusREST, error)","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/storage/storage.go","code":"// NewREST returns two RESTStorage objects that will work against validatingAdmissionPolicy and its status.\nfunc NewREST(optsGetter generic.RESTOptionsGetter, authorizer authorizer.Authorizer, resourceResolver resolver.ResourceResolver) (*REST, *StatusREST, error) {\n\tr := \u0026REST{}\n\tstrategy := validatingadmissionpolicy.NewStrategy(authorizer, resourceResolver)\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026admissionregistration.ValidatingAdmissionPolicy{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026admissionregistration.ValidatingAdmissionPolicyList{} },\n\t\tObjectNameFunc: func(obj runtime.Object) (string, error) {\n\t\t\treturn obj.(*admissionregistration.ValidatingAdmissionPolicy).Name, nil\n\t\t},\n\t\tDefaultQualifiedResource: groupResource,\n\t\tSingularQualifiedResource: admissionregistration.Resource(\"validatingadmissionpolicy\"),\n\n\t\tCreateStrategy: strategy,\n\t\tUpdateStrategy: strategy,\n\t\tDeleteStrategy: strategy,\n\t\tResetFieldsStrategy: strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tr.Store = store\n\tstatusStrategy := validatingadmissionpolicy.NewStatusStrategy(strategy)\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = statusStrategy\n\tstatusStore.ResetFieldsStrategy = statusStrategy\n\tsr := \u0026StatusREST{store: \u0026statusStore}\n\treturn r, sr, nil\n}","line":{"from":50,"to":81}} {"id":100008838,"name":"Categories","signature":"func (r *REST) Categories() []string","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/storage/storage.go","code":"// Categories implements the CategoriesProvider interface. Returns a list of categories a resource is part of.\nfunc (r *REST) Categories() []string {\n\treturn []string{\"api-extensions\"}\n}","line":{"from":86,"to":89}} {"id":100008839,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/storage/storage.go","code":"// New generates a new ValidatingAdmissionPolicy object\nfunc (r *StatusREST) New() runtime.Object {\n\treturn \u0026admissionregistration.ValidatingAdmissionPolicy{}\n}","line":{"from":91,"to":94}} {"id":100008840,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/storage/storage.go","code":"// Destroy disposes the store object. For the StatusREST, this is a no-op.\nfunc (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":96,"to":100}} {"id":100008841,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":102,"to":105}} {"id":100008842,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/storage/storage.go","code":"// GetResetFields returns the fields that got reset by the REST endpoint\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":107,"to":110}} {"id":100008843,"name":"ConvertToTable","signature":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/storage/storage.go","code":"// ConvertToTable delegates to the store, implements TableConverter\nfunc (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":112,"to":115}} {"id":100008844,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/storage/storage.go","code":"// Update alters the status subset of an object. Delegates to the store\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, forceAllowCreate, options)\n}","line":{"from":117,"to":120}} {"id":100008845,"name":"NewStrategy","signature":"func NewStrategy(authorizer authorizer.Authorizer, resourceResolver resolver.ResourceResolver) *validatingAdmissionPolicyStrategy","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/strategy.go","code":"// NewStrategy is the default logic that applies when creating and updating validatingAdmissionPolicy objects.\nfunc NewStrategy(authorizer authorizer.Authorizer, resourceResolver resolver.ResourceResolver) *validatingAdmissionPolicyStrategy {\n\treturn \u0026validatingAdmissionPolicyStrategy{\n\t\tObjectTyper: legacyscheme.Scheme,\n\t\tNameGenerator: names.SimpleNameGenerator,\n\t\tauthorizer: authorizer,\n\t\tresourceResolver: resourceResolver,\n\t}\n}","line":{"from":44,"to":52}} {"id":100008846,"name":"NamespaceScoped","signature":"func (v *validatingAdmissionPolicyStrategy) NamespaceScoped() bool","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/strategy.go","code":"// NamespaceScoped returns false because ValidatingAdmissionPolicy is cluster-scoped resource.\nfunc (v *validatingAdmissionPolicyStrategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":54,"to":57}} {"id":100008847,"name":"PrepareForCreate","signature":"func (v *validatingAdmissionPolicyStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/strategy.go","code":"// PrepareForCreate clears the status of an validatingAdmissionPolicy before creation.\nfunc (v *validatingAdmissionPolicyStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tic := obj.(*admissionregistration.ValidatingAdmissionPolicy)\n\tic.Status = admissionregistration.ValidatingAdmissionPolicyStatus{}\n\tic.Generation = 1\n}","line":{"from":59,"to":64}} {"id":100008848,"name":"PrepareForUpdate","signature":"func (v *validatingAdmissionPolicyStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (v *validatingAdmissionPolicyStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewIC := obj.(*admissionregistration.ValidatingAdmissionPolicy)\n\toldIC := old.(*admissionregistration.ValidatingAdmissionPolicy)\n\n\t// Prevent any update on the Status object\n\tnewIC.Status = oldIC.Status\n\n\t// Any changes to the spec increment the generation number, any changes to the\n\t// status should reflect the generation number of the corresponding object.\n\t// See metav1.ObjectMeta description for more information on Generation.\n\tif !apiequality.Semantic.DeepEqual(oldIC.Spec, newIC.Spec) {\n\t\tnewIC.Generation = oldIC.Generation + 1\n\t}\n}","line":{"from":66,"to":80}} {"id":100008849,"name":"Validate","signature":"func (v *validatingAdmissionPolicyStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/strategy.go","code":"// Validate validates a new validatingAdmissionPolicy.\nfunc (v *validatingAdmissionPolicyStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\terrs := validation.ValidateValidatingAdmissionPolicy(obj.(*admissionregistration.ValidatingAdmissionPolicy))\n\tif len(errs) == 0 {\n\t\t// if the object is well-formed, also authorize the paramKind\n\t\tif err := v.authorizeCreate(ctx, obj); err != nil {\n\t\t\terrs = append(errs, field.Forbidden(field.NewPath(\"spec\", \"paramKind\"), err.Error()))\n\t\t}\n\t}\n\treturn errs\n}","line":{"from":82,"to":92}} {"id":100008850,"name":"WarningsOnCreate","signature":"func (v *validatingAdmissionPolicyStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (v *validatingAdmissionPolicyStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":94,"to":97}} {"id":100008851,"name":"Canonicalize","signature":"func (v *validatingAdmissionPolicyStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (v *validatingAdmissionPolicyStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":99,"to":101}} {"id":100008852,"name":"AllowCreateOnUpdate","signature":"func (v *validatingAdmissionPolicyStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/strategy.go","code":"// AllowCreateOnUpdate is true for validatingAdmissionPolicy; this means you may create one with a PUT request.\nfunc (v *validatingAdmissionPolicyStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":103,"to":106}} {"id":100008853,"name":"ValidateUpdate","signature":"func (v *validatingAdmissionPolicyStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (v *validatingAdmissionPolicyStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\terrs := validation.ValidateValidatingAdmissionPolicyUpdate(obj.(*admissionregistration.ValidatingAdmissionPolicy), old.(*admissionregistration.ValidatingAdmissionPolicy))\n\tif len(errs) == 0 {\n\t\t// if the object is well-formed, also authorize the paramKind\n\t\tif err := v.authorizeUpdate(ctx, obj, old); err != nil {\n\t\t\terrs = append(errs, field.Forbidden(field.NewPath(\"spec\", \"paramKind\"), err.Error()))\n\t\t}\n\t}\n\treturn errs\n}","line":{"from":108,"to":118}} {"id":100008854,"name":"WarningsOnUpdate","signature":"func (v *validatingAdmissionPolicyStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (v *validatingAdmissionPolicyStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":120,"to":123}} {"id":100008855,"name":"AllowUnconditionalUpdate","signature":"func (v *validatingAdmissionPolicyStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/strategy.go","code":"// AllowUnconditionalUpdate is the default update policy for validatingAdmissionPolicy objects. Status update should\n// only be allowed if version match.\nfunc (v *validatingAdmissionPolicyStrategy) AllowUnconditionalUpdate() bool {\n\treturn false\n}","line":{"from":125,"to":129}} {"id":100008856,"name":"GetResetFields","signature":"func (v *validatingAdmissionPolicyStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (v *validatingAdmissionPolicyStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"admissionregistration.k8s.io/v1alpha1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":131,"to":141}} {"id":100008857,"name":"ValidateUpdate","signature":"func (s *validatingAdmissionPolicyStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/strategy.go","code":"// ValidateUpdate is the default update validation of an update to the status object.\nfunc (s *validatingAdmissionPolicyStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateValidatingAdmissionPolicyStatusUpdate(obj.(*admissionregistration.ValidatingAdmissionPolicy), old.(*admissionregistration.ValidatingAdmissionPolicy))\n}","line":{"from":147,"to":150}} {"id":100008858,"name":"PrepareForUpdate","signature":"func (s *validatingAdmissionPolicyStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/strategy.go","code":"// PrepareForUpdate differs from the main strategy where setting the spec is not\n// allowed, but setting status is OK.\nfunc (s *validatingAdmissionPolicyStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewIC := obj.(*admissionregistration.ValidatingAdmissionPolicy)\n\toldIC := old.(*admissionregistration.ValidatingAdmissionPolicy)\n\n\t// Prevent any update on the Spec object from Status Strategy\n\tnewIC.Spec = oldIC.Spec\n\n\tmetav1.ResetObjectMetaForStatus(\u0026newIC.ObjectMeta, \u0026oldIC.ObjectMeta)\n\t// No change in the generation.\n}","line":{"from":152,"to":163}} {"id":100008859,"name":"GetResetFields","signature":"func (s *validatingAdmissionPolicyStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (s *validatingAdmissionPolicyStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"admissionregistration.k8s.io/v1alpha1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t\tfieldpath.MakePathOrDie(\"metadata\"),\n\t\t),\n\t}\n}","line":{"from":165,"to":174}} {"id":100008860,"name":"NewStatusStrategy","signature":"func NewStatusStrategy(policyStrategy *validatingAdmissionPolicyStrategy) *validatingAdmissionPolicyStatusStrategy","file":"pkg/registry/admissionregistration/validatingadmissionpolicy/strategy.go","code":"// NewStatusStrategy creates a strategy for operating the status object.\nfunc NewStatusStrategy(policyStrategy *validatingAdmissionPolicyStrategy) *validatingAdmissionPolicyStatusStrategy {\n\treturn \u0026validatingAdmissionPolicyStatusStrategy{validatingAdmissionPolicyStrategy: policyStrategy}\n}","line":{"from":176,"to":179}} {"id":100008861,"name":"authorizeCreate","signature":"func (v *validatingAdmissionPolicyBindingStrategy) authorizeCreate(ctx context.Context, obj runtime.Object) error","file":"pkg/registry/admissionregistration/validatingadmissionpolicybinding/authz.go","code":"func (v *validatingAdmissionPolicyBindingStrategy) authorizeCreate(ctx context.Context, obj runtime.Object) error {\n\tbinding := obj.(*admissionregistration.ValidatingAdmissionPolicyBinding)\n\tif binding.Spec.ParamRef == nil {\n\t\t// no paramRef in new object\n\t\treturn nil\n\t}\n\n\treturn v.authorize(ctx, binding)\n}","line":{"from":31,"to":39}} {"id":100008862,"name":"authorizeUpdate","signature":"func (v *validatingAdmissionPolicyBindingStrategy) authorizeUpdate(ctx context.Context, obj, old runtime.Object) error","file":"pkg/registry/admissionregistration/validatingadmissionpolicybinding/authz.go","code":"func (v *validatingAdmissionPolicyBindingStrategy) authorizeUpdate(ctx context.Context, obj, old runtime.Object) error {\n\tbinding := obj.(*admissionregistration.ValidatingAdmissionPolicyBinding)\n\tif binding.Spec.ParamRef == nil {\n\t\t// no paramRef in new object\n\t\treturn nil\n\t}\n\n\toldBinding := old.(*admissionregistration.ValidatingAdmissionPolicyBinding)\n\tif oldBinding.Spec.ParamRef != nil \u0026\u0026 *oldBinding.Spec.ParamRef == *binding.Spec.ParamRef \u0026\u0026 oldBinding.Spec.PolicyName == binding.Spec.PolicyName {\n\t\t// identical paramRef and policy to old object\n\t\treturn nil\n\t}\n\n\treturn v.authorize(ctx, binding)\n}","line":{"from":41,"to":55}} {"id":100008863,"name":"authorize","signature":"func (v *validatingAdmissionPolicyBindingStrategy) authorize(ctx context.Context, binding *admissionregistration.ValidatingAdmissionPolicyBinding) error","file":"pkg/registry/admissionregistration/validatingadmissionpolicybinding/authz.go","code":"func (v *validatingAdmissionPolicyBindingStrategy) authorize(ctx context.Context, binding *admissionregistration.ValidatingAdmissionPolicyBinding) error {\n\tif v.authorizer == nil || v.resourceResolver == nil || binding.Spec.ParamRef == nil {\n\t\treturn nil\n\t}\n\n\t// for superuser, skip all checks\n\tif rbacregistry.EscalationAllowed(ctx) {\n\t\treturn nil\n\t}\n\n\tuser, ok := genericapirequest.UserFrom(ctx)\n\tif !ok {\n\t\treturn fmt.Errorf(\"cannot identify user to authorize read access to paramRef object\")\n\t}\n\n\t// default to requiring permissions on all group/version/resources\n\tresource, apiGroup, apiVersion := \"*\", \"*\", \"*\"\n\n\tif policy, err := v.policyGetter.GetValidatingAdmissionPolicy(ctx, binding.Spec.PolicyName); err == nil \u0026\u0026 policy.Spec.ParamKind != nil {\n\t\tparamKind := policy.Spec.ParamKind\n\t\tif gv, err := schema.ParseGroupVersion(paramKind.APIVersion); err == nil {\n\t\t\t// we only need to authorize the parsed group/version\n\t\t\tapiGroup = gv.Group\n\t\t\tapiVersion = gv.Version\n\t\t\tif gvr, err := v.resourceResolver.Resolve(gv.WithKind(paramKind.Kind)); err == nil {\n\t\t\t\t// we only need to authorize the resolved resource\n\t\t\t\tresource = gvr.Resource\n\t\t\t}\n\t\t}\n\t}\n\n\tparamRef := binding.Spec.ParamRef\n\n\t// require that the user can read (verb \"get\") the referred resource.\n\tattrs := authorizer.AttributesRecord{\n\t\tUser: user,\n\t\tVerb: \"get\",\n\t\tResourceRequest: true,\n\t\tName: paramRef.Name,\n\t\tNamespace: paramRef.Namespace,\n\t\tAPIGroup: apiGroup,\n\t\tAPIVersion: apiVersion,\n\t\tResource: resource,\n\t}\n\n\td, _, err := v.authorizer.Authorize(ctx, attrs)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif d != authorizer.DecisionAllow {\n\t\treturn fmt.Errorf(`user %v does not have \"get\" permission on the object referenced by paramRef`, user)\n\t}\n\treturn nil\n}","line":{"from":57,"to":110}} {"id":100008864,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter, authorizer authorizer.Authorizer, policyGetter PolicyGetter, resourceResolver resolver.ResourceResolver) (*REST, error)","file":"pkg/registry/admissionregistration/validatingadmissionpolicybinding/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against policyBinding.\nfunc NewREST(optsGetter generic.RESTOptionsGetter, authorizer authorizer.Authorizer, policyGetter PolicyGetter, resourceResolver resolver.ResourceResolver) (*REST, error) {\n\tr := \u0026REST{}\n\tstrategy := validatingadmissionpolicybinding.NewStrategy(authorizer, policyGetter, resourceResolver)\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026admissionregistration.ValidatingAdmissionPolicyBinding{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026admissionregistration.ValidatingAdmissionPolicyBindingList{} },\n\t\tObjectNameFunc: func(obj runtime.Object) (string, error) {\n\t\t\treturn obj.(*admissionregistration.ValidatingAdmissionPolicyBinding).Name, nil\n\t\t},\n\t\tDefaultQualifiedResource: groupResource,\n\t\tSingularQualifiedResource: admissionregistration.Resource(\"validatingadmissionpolicybinding\"),\n\n\t\tCreateStrategy: strategy,\n\t\tUpdateStrategy: strategy,\n\t\tDeleteStrategy: strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\tr.Store = store\n\treturn r, nil\n}","line":{"from":43,"to":68}} {"id":100008865,"name":"Categories","signature":"func (r *REST) Categories() []string","file":"pkg/registry/admissionregistration/validatingadmissionpolicybinding/storage/storage.go","code":"// Categories implements the CategoriesProvider interface. Returns a list of categories a resource is part of.\nfunc (r *REST) Categories() []string {\n\treturn []string{\"api-extensions\"}\n}","line":{"from":73,"to":76}} {"id":100008866,"name":"GetValidatingAdmissionPolicy","signature":"func (g *DefaultPolicyGetter) GetValidatingAdmissionPolicy(ctx context.Context, name string) (*admissionregistration.ValidatingAdmissionPolicy, error)","file":"pkg/registry/admissionregistration/validatingadmissionpolicybinding/storage/storage.go","code":"func (g *DefaultPolicyGetter) GetValidatingAdmissionPolicy(ctx context.Context, name string) (*admissionregistration.ValidatingAdmissionPolicy, error) {\n\tp, err := g.Getter.Get(ctx, name, \u0026metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn p.(*admissionregistration.ValidatingAdmissionPolicy), err\n}","line":{"from":88,"to":94}} {"id":100008867,"name":"NewStrategy","signature":"func NewStrategy(authorizer authorizer.Authorizer, policyGetter PolicyGetter, resourceResolver resolver.ResourceResolver) *validatingAdmissionPolicyBindingStrategy","file":"pkg/registry/admissionregistration/validatingadmissionpolicybinding/strategy.go","code":"// NewStrategy is the default logic that applies when creating and updating ValidatingAdmissionPolicyBinding objects.\nfunc NewStrategy(authorizer authorizer.Authorizer, policyGetter PolicyGetter, resourceResolver resolver.ResourceResolver) *validatingAdmissionPolicyBindingStrategy {\n\treturn \u0026validatingAdmissionPolicyBindingStrategy{\n\t\tObjectTyper: legacyscheme.Scheme,\n\t\tNameGenerator: names.SimpleNameGenerator,\n\t\tauthorizer: authorizer,\n\t\tpolicyGetter: policyGetter,\n\t\tresourceResolver: resourceResolver,\n\t}\n}","line":{"from":48,"to":57}} {"id":100008868,"name":"NamespaceScoped","signature":"func (v *validatingAdmissionPolicyBindingStrategy) NamespaceScoped() bool","file":"pkg/registry/admissionregistration/validatingadmissionpolicybinding/strategy.go","code":"// NamespaceScoped returns false because ValidatingAdmissionPolicyBinding is cluster-scoped resource.\nfunc (v *validatingAdmissionPolicyBindingStrategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":59,"to":62}} {"id":100008869,"name":"PrepareForCreate","signature":"func (v *validatingAdmissionPolicyBindingStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/admissionregistration/validatingadmissionpolicybinding/strategy.go","code":"// PrepareForCreate clears the status of an ValidatingAdmissionPolicyBinding before creation.\nfunc (v *validatingAdmissionPolicyBindingStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tic := obj.(*admissionregistration.ValidatingAdmissionPolicyBinding)\n\tic.Generation = 1\n}","line":{"from":64,"to":68}} {"id":100008870,"name":"PrepareForUpdate","signature":"func (v *validatingAdmissionPolicyBindingStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/admissionregistration/validatingadmissionpolicybinding/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (v *validatingAdmissionPolicyBindingStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewIC := obj.(*admissionregistration.ValidatingAdmissionPolicyBinding)\n\toldIC := old.(*admissionregistration.ValidatingAdmissionPolicyBinding)\n\n\t// Any changes to the spec increment the generation number, any changes to the\n\t// status should reflect the generation number of the corresponding object.\n\t// See metav1.ObjectMeta description for more information on Generation.\n\tif !apiequality.Semantic.DeepEqual(oldIC.Spec, newIC.Spec) {\n\t\tnewIC.Generation = oldIC.Generation + 1\n\t}\n}","line":{"from":70,"to":81}} {"id":100008871,"name":"Validate","signature":"func (v *validatingAdmissionPolicyBindingStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/admissionregistration/validatingadmissionpolicybinding/strategy.go","code":"// Validate validates a new ValidatingAdmissionPolicyBinding.\nfunc (v *validatingAdmissionPolicyBindingStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\terrs := validation.ValidateValidatingAdmissionPolicyBinding(obj.(*admissionregistration.ValidatingAdmissionPolicyBinding))\n\tif len(errs) == 0 {\n\t\t// if the object is well-formed, also authorize the paramRef\n\t\tif err := v.authorizeCreate(ctx, obj); err != nil {\n\t\t\terrs = append(errs, field.Forbidden(field.NewPath(\"spec\", \"paramRef\"), err.Error()))\n\t\t}\n\t}\n\treturn errs\n}","line":{"from":83,"to":93}} {"id":100008872,"name":"WarningsOnCreate","signature":"func (v *validatingAdmissionPolicyBindingStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/admissionregistration/validatingadmissionpolicybinding/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (v *validatingAdmissionPolicyBindingStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":95,"to":98}} {"id":100008873,"name":"Canonicalize","signature":"func (v *validatingAdmissionPolicyBindingStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/admissionregistration/validatingadmissionpolicybinding/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (v *validatingAdmissionPolicyBindingStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":100,"to":102}} {"id":100008874,"name":"AllowCreateOnUpdate","signature":"func (v *validatingAdmissionPolicyBindingStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/admissionregistration/validatingadmissionpolicybinding/strategy.go","code":"// AllowCreateOnUpdate is true for ValidatingAdmissionPolicyBinding; this means you may create one with a PUT request.\nfunc (v *validatingAdmissionPolicyBindingStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":104,"to":107}} {"id":100008875,"name":"ValidateUpdate","signature":"func (v *validatingAdmissionPolicyBindingStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/admissionregistration/validatingadmissionpolicybinding/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (v *validatingAdmissionPolicyBindingStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\terrs := validation.ValidateValidatingAdmissionPolicyBindingUpdate(obj.(*admissionregistration.ValidatingAdmissionPolicyBinding), old.(*admissionregistration.ValidatingAdmissionPolicyBinding))\n\tif len(errs) == 0 {\n\t\t// if the object is well-formed, also authorize the paramRef\n\t\tif err := v.authorizeUpdate(ctx, obj, old); err != nil {\n\t\t\terrs = append(errs, field.Forbidden(field.NewPath(\"spec\", \"paramRef\"), err.Error()))\n\t\t}\n\t}\n\treturn errs\n}","line":{"from":109,"to":119}} {"id":100008876,"name":"WarningsOnUpdate","signature":"func (v *validatingAdmissionPolicyBindingStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/admissionregistration/validatingadmissionpolicybinding/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (v *validatingAdmissionPolicyBindingStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":121,"to":124}} {"id":100008877,"name":"AllowUnconditionalUpdate","signature":"func (v *validatingAdmissionPolicyBindingStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/admissionregistration/validatingadmissionpolicybinding/strategy.go","code":"// AllowUnconditionalUpdate is the default update policy for ValidatingAdmissionPolicyBinding objects. Status update should\n// only be allowed if version match.\nfunc (v *validatingAdmissionPolicyBindingStrategy) AllowUnconditionalUpdate() bool {\n\treturn false\n}","line":{"from":126,"to":130}} {"id":100008878,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error)","file":"pkg/registry/admissionregistration/validatingwebhookconfiguration/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against validatingWebhookConfiguration.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026admissionregistration.ValidatingWebhookConfiguration{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026admissionregistration.ValidatingWebhookConfigurationList{} },\n\t\tObjectNameFunc: func(obj runtime.Object) (string, error) {\n\t\t\treturn obj.(*admissionregistration.ValidatingWebhookConfiguration).Name, nil\n\t\t},\n\t\tDefaultQualifiedResource: admissionregistration.Resource(\"validatingwebhookconfigurations\"),\n\t\tSingularQualifiedResource: admissionregistration.Resource(\"validatingwebhookconfiguration\"),\n\n\t\tCreateStrategy: validatingwebhookconfiguration.Strategy,\n\t\tUpdateStrategy: validatingwebhookconfiguration.Strategy,\n\t\tDeleteStrategy: validatingwebhookconfiguration.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026REST{store}, nil\n}","line":{"from":36,"to":58}} {"id":100008879,"name":"Categories","signature":"func (r *REST) Categories() []string","file":"pkg/registry/admissionregistration/validatingwebhookconfiguration/storage/storage.go","code":"// Categories implements the CategoriesProvider interface. Returns a list of categories a resource is part of.\nfunc (r *REST) Categories() []string {\n\treturn []string{\"api-extensions\"}\n}","line":{"from":63,"to":66}} {"id":100008880,"name":"NamespaceScoped","signature":"func (validatingWebhookConfigurationStrategy) NamespaceScoped() bool","file":"pkg/registry/admissionregistration/validatingwebhookconfiguration/strategy.go","code":"// NamespaceScoped returns false because ValidatingWebhookConfiguration is cluster-scoped resource.\nfunc (validatingWebhookConfigurationStrategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":40,"to":43}} {"id":100008881,"name":"PrepareForCreate","signature":"func (validatingWebhookConfigurationStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/admissionregistration/validatingwebhookconfiguration/strategy.go","code":"// PrepareForCreate clears the status of an validatingWebhookConfiguration before creation.\nfunc (validatingWebhookConfigurationStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tic := obj.(*admissionregistration.ValidatingWebhookConfiguration)\n\tic.Generation = 1\n\n\tadmissionregistration.DropDisabledValidatingWebhookConfigurationFields(ic, nil)\n}","line":{"from":45,"to":51}} {"id":100008882,"name":"PrepareForUpdate","signature":"func (validatingWebhookConfigurationStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/admissionregistration/validatingwebhookconfiguration/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (validatingWebhookConfigurationStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewIC := obj.(*admissionregistration.ValidatingWebhookConfiguration)\n\toldIC := old.(*admissionregistration.ValidatingWebhookConfiguration)\n\n\tadmissionregistration.DropDisabledValidatingWebhookConfigurationFields(newIC, oldIC)\n\t// Any changes to the spec increment the generation number, any changes to the\n\t// status should reflect the generation number of the corresponding object.\n\t// See metav1.ObjectMeta description for more information on Generation.\n\tif !reflect.DeepEqual(oldIC.Webhooks, newIC.Webhooks) {\n\t\tnewIC.Generation = oldIC.Generation + 1\n\t}\n}","line":{"from":53,"to":65}} {"id":100008883,"name":"Validate","signature":"func (validatingWebhookConfigurationStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/admissionregistration/validatingwebhookconfiguration/strategy.go","code":"// Validate validates a new validatingWebhookConfiguration.\nfunc (validatingWebhookConfigurationStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\treturn validation.ValidateValidatingWebhookConfiguration(obj.(*admissionregistration.ValidatingWebhookConfiguration))\n}","line":{"from":67,"to":70}} {"id":100008884,"name":"WarningsOnCreate","signature":"func (validatingWebhookConfigurationStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/admissionregistration/validatingwebhookconfiguration/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (validatingWebhookConfigurationStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":72,"to":75}} {"id":100008885,"name":"Canonicalize","signature":"func (validatingWebhookConfigurationStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/admissionregistration/validatingwebhookconfiguration/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (validatingWebhookConfigurationStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":77,"to":79}} {"id":100008886,"name":"AllowCreateOnUpdate","signature":"func (validatingWebhookConfigurationStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/admissionregistration/validatingwebhookconfiguration/strategy.go","code":"// AllowCreateOnUpdate is true for validatingWebhookConfiguration; this means you may create one with a PUT request.\nfunc (validatingWebhookConfigurationStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":81,"to":84}} {"id":100008887,"name":"ValidateUpdate","signature":"func (validatingWebhookConfigurationStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/admissionregistration/validatingwebhookconfiguration/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (validatingWebhookConfigurationStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateValidatingWebhookConfigurationUpdate(obj.(*admissionregistration.ValidatingWebhookConfiguration), old.(*admissionregistration.ValidatingWebhookConfiguration))\n}","line":{"from":86,"to":89}} {"id":100008888,"name":"WarningsOnUpdate","signature":"func (validatingWebhookConfigurationStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/admissionregistration/validatingwebhookconfiguration/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (validatingWebhookConfigurationStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":91,"to":94}} {"id":100008889,"name":"AllowUnconditionalUpdate","signature":"func (validatingWebhookConfigurationStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/admissionregistration/validatingwebhookconfiguration/strategy.go","code":"// AllowUnconditionalUpdate is the default update policy for validatingWebhookConfiguration objects. Status update should\n// only be allowed if version match.\nfunc (validatingWebhookConfigurationStrategy) AllowUnconditionalUpdate() bool {\n\treturn false\n}","line":{"from":96,"to":100}} {"id":100008890,"name":"NewRESTStorage","signature":"func (p StorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error)","file":"pkg/registry/apiserverinternal/rest/storage.go","code":"// NewRESTStorage returns a StorageProvider\nfunc (p StorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error) {\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(apiserverinternal.GroupName, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs)\n\n\tif storageMap, err := p.v1alpha1Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[apiserverv1alpha1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\treturn apiGroupInfo, nil\n}","line":{"from":33,"to":44}} {"id":100008891,"name":"v1alpha1Storage","signature":"func (p StorageProvider) v1alpha1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/apiserverinternal/rest/storage.go","code":"func (p StorageProvider) v1alpha1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\tif resource := \"storageversions\"; apiResourceConfigSource.ResourceEnabled(apiserverv1alpha1.SchemeGroupVersion.WithResource(resource)) {\n\t\ts, status, err := storageversionstorage.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstorage[resource] = s\n\t\tstorage[resource+\"/status\"] = status\n\t}\n\n\treturn storage, nil\n}","line":{"from":46,"to":59}} {"id":100008892,"name":"GroupName","signature":"func (p StorageProvider) GroupName() string","file":"pkg/registry/apiserverinternal/rest/storage.go","code":"// GroupName is the group name for the storage provider\nfunc (p StorageProvider) GroupName() string {\n\treturn apiserverinternal.GroupName\n}","line":{"from":61,"to":64}} {"id":100008893,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error)","file":"pkg/registry/apiserverinternal/storageversion/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against storageVersions\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026apiserverinternal.StorageVersion{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026apiserverinternal.StorageVersionList{} },\n\t\tObjectNameFunc: func(obj runtime.Object) (string, error) {\n\t\t\treturn obj.(*apiserverinternal.StorageVersion).Name, nil\n\t\t},\n\t\tDefaultQualifiedResource: apiserverinternal.Resource(\"storageversions\"),\n\t\tSingularQualifiedResource: apiserverinternal.Resource(\"storageversion\"),\n\n\t\tCreateStrategy: strategy.Strategy,\n\t\tUpdateStrategy: strategy.Strategy,\n\t\tDeleteStrategy: strategy.Strategy,\n\t\tResetFieldsStrategy: strategy.Strategy,\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = strategy.StatusStrategy\n\tstatusStore.ResetFieldsStrategy = strategy.StatusStrategy\n\treturn \u0026REST{store}, \u0026StatusREST{store: \u0026statusStore}, nil\n}","line":{"from":40,"to":65}} {"id":100008894,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"pkg/registry/apiserverinternal/storageversion/storage/storage.go","code":"// New creates a new StorageVersion object.\nfunc (r *StatusREST) New() runtime.Object {\n\treturn \u0026apiserverinternal.StorageVersion{}\n}","line":{"from":72,"to":75}} {"id":100008895,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"pkg/registry/apiserverinternal/storageversion/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":77,"to":81}} {"id":100008896,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/apiserverinternal/storageversion/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":83,"to":86}} {"id":100008897,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/apiserverinternal/storageversion/storage/storage.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":88,"to":93}} {"id":100008898,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/apiserverinternal/storageversion/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":95,"to":98}} {"id":100008899,"name":"ConvertToTable","signature":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/apiserverinternal/storageversion/storage/storage.go","code":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":100,"to":102}} {"id":100008900,"name":"NamespaceScoped","signature":"func (storageVersionStrategy) NamespaceScoped() bool","file":"pkg/registry/apiserverinternal/storageversion/strategy.go","code":"// NamespaceScoped returns false because all StorageVersion's need to be cluster scoped\nfunc (storageVersionStrategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":41,"to":44}} {"id":100008901,"name":"GetResetFields","signature":"func (storageVersionStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/apiserverinternal/storageversion/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (storageVersionStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"internal.apiserver.k8s.io/v1alpha1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":46,"to":56}} {"id":100008902,"name":"PrepareForCreate","signature":"func (storageVersionStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/apiserverinternal/storageversion/strategy.go","code":"// PrepareForCreate clears the status of an StorageVersion before creation.\nfunc (storageVersionStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tsv := obj.(*apiserverinternal.StorageVersion)\n\tsv.Status = apiserverinternal.StorageVersionStatus{}\n}","line":{"from":58,"to":62}} {"id":100008903,"name":"PrepareForUpdate","signature":"func (storageVersionStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/apiserverinternal/storageversion/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (storageVersionStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tsv := obj.(*apiserverinternal.StorageVersion)\n\tsv.Status = old.(*apiserverinternal.StorageVersion).Status\n}","line":{"from":64,"to":68}} {"id":100008904,"name":"Validate","signature":"func (storageVersionStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/apiserverinternal/storageversion/strategy.go","code":"// Validate validates a new storageVersion.\nfunc (storageVersionStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tsv := obj.(*apiserverinternal.StorageVersion)\n\treturn validation.ValidateStorageVersion(sv)\n}","line":{"from":70,"to":74}} {"id":100008905,"name":"WarningsOnCreate","signature":"func (storageVersionStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/apiserverinternal/storageversion/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (storageVersionStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":76,"to":79}} {"id":100008906,"name":"Canonicalize","signature":"func (storageVersionStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/apiserverinternal/storageversion/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (storageVersionStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":81,"to":83}} {"id":100008907,"name":"AllowCreateOnUpdate","signature":"func (storageVersionStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/apiserverinternal/storageversion/strategy.go","code":"// Does not allow creating a StorageVersion object with a PUT request.\nfunc (storageVersionStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":85,"to":88}} {"id":100008908,"name":"ValidateUpdate","signature":"func (storageVersionStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/apiserverinternal/storageversion/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (storageVersionStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewStorageVersion := obj.(*apiserverinternal.StorageVersion)\n\toldStorageVersion := old.(*apiserverinternal.StorageVersion)\n\tvalidationErrorList := validation.ValidateStorageVersionUpdate(newStorageVersion, oldStorageVersion)\n\treturn validationErrorList\n}","line":{"from":90,"to":96}} {"id":100008909,"name":"WarningsOnUpdate","signature":"func (storageVersionStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/apiserverinternal/storageversion/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (storageVersionStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":98,"to":101}} {"id":100008910,"name":"AllowUnconditionalUpdate","signature":"func (storageVersionStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/apiserverinternal/storageversion/strategy.go","code":"// AllowUnconditionalUpdate is the default update policy for storageVersion objects. Status update should\n// only be allowed if version match.\nfunc (storageVersionStrategy) AllowUnconditionalUpdate() bool {\n\treturn false\n}","line":{"from":103,"to":107}} {"id":100008911,"name":"GetResetFields","signature":"func (storageVersionStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/apiserverinternal/storageversion/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (storageVersionStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"internal.apiserver.k8s.io/v1alpha1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"metadata\"),\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":116,"to":127}} {"id":100008912,"name":"PrepareForUpdate","signature":"func (storageVersionStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/apiserverinternal/storageversion/strategy.go","code":"func (storageVersionStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewSV := obj.(*apiserverinternal.StorageVersion)\n\toldSV := old.(*apiserverinternal.StorageVersion)\n\n\tnewSV.Spec = oldSV.Spec\n\tmetav1.ResetObjectMetaForStatus(\u0026newSV.ObjectMeta, \u0026oldSV.ObjectMeta)\n}","line":{"from":129,"to":135}} {"id":100008913,"name":"ValidateUpdate","signature":"func (storageVersionStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/apiserverinternal/storageversion/strategy.go","code":"func (storageVersionStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateStorageVersionStatusUpdate(obj.(*apiserverinternal.StorageVersion), old.(*apiserverinternal.StorageVersion))\n}","line":{"from":137,"to":139}} {"id":100008914,"name":"WarningsOnUpdate","signature":"func (storageVersionStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/apiserverinternal/storageversion/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (storageVersionStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":141,"to":144}} {"id":100008915,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error)","file":"pkg/registry/apps/controllerrevision/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work with ControllerRevision objects.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026apps.ControllerRevision{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026apps.ControllerRevisionList{} },\n\t\tDefaultQualifiedResource: apps.Resource(\"controllerrevisions\"),\n\t\tSingularQualifiedResource: apps.Resource(\"controllerrevision\"),\n\n\t\tCreateStrategy: controllerrevision.Strategy,\n\t\tUpdateStrategy: controllerrevision.Strategy,\n\t\tDeleteStrategy: controllerrevision.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026REST{store}, nil\n}","line":{"from":35,"to":54}} {"id":100008916,"name":"NamespaceScoped","signature":"func (strategy) NamespaceScoped() bool","file":"pkg/registry/apps/controllerrevision/strategy.go","code":"func (strategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":47,"to":49}} {"id":100008917,"name":"Canonicalize","signature":"func (strategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/apps/controllerrevision/strategy.go","code":"func (strategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":51,"to":52}} {"id":100008918,"name":"AllowCreateOnUpdate","signature":"func (strategy) AllowCreateOnUpdate() bool","file":"pkg/registry/apps/controllerrevision/strategy.go","code":"func (strategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":54,"to":56}} {"id":100008919,"name":"PrepareForCreate","signature":"func (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/apps/controllerrevision/strategy.go","code":"func (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\t_ = obj.(*apps.ControllerRevision)\n}","line":{"from":58,"to":60}} {"id":100008920,"name":"Validate","signature":"func (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/apps/controllerrevision/strategy.go","code":"func (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\trevision := obj.(*apps.ControllerRevision)\n\n\treturn validation.ValidateControllerRevision(revision)\n}","line":{"from":62,"to":66}} {"id":100008921,"name":"WarningsOnCreate","signature":"func (strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return nil }","file":"pkg/registry/apps/controllerrevision/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return nil }","line":{"from":68,"to":69}} {"id":100008922,"name":"PrepareForUpdate","signature":"func (strategy) PrepareForUpdate(ctx context.Context, newObj, oldObj runtime.Object)","file":"pkg/registry/apps/controllerrevision/strategy.go","code":"func (strategy) PrepareForUpdate(ctx context.Context, newObj, oldObj runtime.Object) {\n\t_ = oldObj.(*apps.ControllerRevision)\n\t_ = newObj.(*apps.ControllerRevision)\n}","line":{"from":71,"to":74}} {"id":100008923,"name":"AllowUnconditionalUpdate","signature":"func (strategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/apps/controllerrevision/strategy.go","code":"func (strategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":76,"to":78}} {"id":100008924,"name":"ValidateUpdate","signature":"func (strategy) ValidateUpdate(ctx context.Context, newObj, oldObj runtime.Object) field.ErrorList","file":"pkg/registry/apps/controllerrevision/strategy.go","code":"func (strategy) ValidateUpdate(ctx context.Context, newObj, oldObj runtime.Object) field.ErrorList {\n\toldRevision, newRevision := oldObj.(*apps.ControllerRevision), newObj.(*apps.ControllerRevision)\n\treturn validation.ValidateControllerRevisionUpdate(newRevision, oldRevision)\n}","line":{"from":80,"to":83}} {"id":100008925,"name":"WarningsOnUpdate","signature":"func (strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string { return nil }","file":"pkg/registry/apps/controllerrevision/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string { return nil }","line":{"from":85,"to":86}} {"id":100008926,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error)","file":"pkg/registry/apps/daemonset/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against DaemonSets.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026apps.DaemonSet{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026apps.DaemonSetList{} },\n\t\tDefaultQualifiedResource: apps.Resource(\"daemonsets\"),\n\t\tSingularQualifiedResource: apps.Resource(\"daemonset\"),\n\n\t\tCreateStrategy: daemonset.Strategy,\n\t\tUpdateStrategy: daemonset.Strategy,\n\t\tDeleteStrategy: daemonset.Strategy,\n\t\tResetFieldsStrategy: daemonset.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = daemonset.StatusStrategy\n\tstatusStore.ResetFieldsStrategy = daemonset.StatusStrategy\n\n\treturn \u0026REST{store}, \u0026StatusREST{store: \u0026statusStore}, nil\n}","line":{"from":40,"to":65}} {"id":100008927,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/apps/daemonset/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"ds\"}\n}","line":{"from":70,"to":73}} {"id":100008928,"name":"Categories","signature":"func (r *REST) Categories() []string","file":"pkg/registry/apps/daemonset/storage/storage.go","code":"// Categories implements the CategoriesProvider interface. Returns a list of categories a resource is part of.\nfunc (r *REST) Categories() []string {\n\treturn []string{\"all\"}\n}","line":{"from":77,"to":80}} {"id":100008929,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"pkg/registry/apps/daemonset/storage/storage.go","code":"// New creates a new DaemonSet object.\nfunc (r *StatusREST) New() runtime.Object {\n\treturn \u0026apps.DaemonSet{}\n}","line":{"from":87,"to":90}} {"id":100008930,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"pkg/registry/apps/daemonset/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":92,"to":96}} {"id":100008931,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/apps/daemonset/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":98,"to":101}} {"id":100008932,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/apps/daemonset/storage/storage.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":103,"to":108}} {"id":100008933,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/apps/daemonset/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":110,"to":113}} {"id":100008934,"name":"ConvertToTable","signature":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/apps/daemonset/storage/storage.go","code":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":115,"to":117}} {"id":100008935,"name":"DefaultGarbageCollectionPolicy","signature":"func (daemonSetStrategy) DefaultGarbageCollectionPolicy(ctx context.Context) rest.GarbageCollectionPolicy","file":"pkg/registry/apps/daemonset/strategy.go","code":"// DefaultGarbageCollectionPolicy returns DeleteDependents for all currently served versions.\nfunc (daemonSetStrategy) DefaultGarbageCollectionPolicy(ctx context.Context) rest.GarbageCollectionPolicy {\n\treturn rest.DeleteDependents\n}","line":{"from":51,"to":54}} {"id":100008936,"name":"NamespaceScoped","signature":"func (daemonSetStrategy) NamespaceScoped() bool","file":"pkg/registry/apps/daemonset/strategy.go","code":"// NamespaceScoped returns true because all DaemonSets need to be within a namespace.\nfunc (daemonSetStrategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":56,"to":59}} {"id":100008937,"name":"GetResetFields","signature":"func (daemonSetStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/apps/daemonset/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (daemonSetStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"apps/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":61,"to":71}} {"id":100008938,"name":"PrepareForCreate","signature":"func (daemonSetStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/apps/daemonset/strategy.go","code":"// PrepareForCreate clears the status of a daemon set before creation.\nfunc (daemonSetStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tdaemonSet := obj.(*apps.DaemonSet)\n\tdaemonSet.Status = apps.DaemonSetStatus{}\n\n\tdaemonSet.Generation = 1\n\tif daemonSet.Spec.TemplateGeneration \u003c 1 {\n\t\tdaemonSet.Spec.TemplateGeneration = 1\n\t}\n\n\tpod.DropDisabledTemplateFields(\u0026daemonSet.Spec.Template, nil)\n}","line":{"from":73,"to":84}} {"id":100008939,"name":"PrepareForUpdate","signature":"func (daemonSetStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/apps/daemonset/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (daemonSetStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewDaemonSet := obj.(*apps.DaemonSet)\n\toldDaemonSet := old.(*apps.DaemonSet)\n\n\tpod.DropDisabledTemplateFields(\u0026newDaemonSet.Spec.Template, \u0026oldDaemonSet.Spec.Template)\n\n\t// update is not allowed to set status\n\tnewDaemonSet.Status = oldDaemonSet.Status\n\n\t// update is not allowed to set TemplateGeneration\n\tnewDaemonSet.Spec.TemplateGeneration = oldDaemonSet.Spec.TemplateGeneration\n\n\t// Any changes to the spec increment the generation number, any changes to the\n\t// status should reflect the generation number of the corresponding object. We push\n\t// the burden of managing the status onto the clients because we can't (in general)\n\t// know here what version of spec the writer of the status has seen. It may seem like\n\t// we can at first -- since obj contains spec -- but in the future we will probably make\n\t// status its own object, and even if we don't, writes may be the result of a\n\t// read-update-write loop, so the contents of spec may not actually be the spec that\n\t// the manager has *seen*.\n\t//\n\t// TODO: Any changes to a part of the object that represents desired state (labels,\n\t// annotations etc) should also increment the generation.\n\tif !apiequality.Semantic.DeepEqual(oldDaemonSet.Spec.Template, newDaemonSet.Spec.Template) {\n\t\tnewDaemonSet.Spec.TemplateGeneration = oldDaemonSet.Spec.TemplateGeneration + 1\n\t\tnewDaemonSet.Generation = oldDaemonSet.Generation + 1\n\t\treturn\n\t}\n\tif !apiequality.Semantic.DeepEqual(oldDaemonSet.Spec, newDaemonSet.Spec) {\n\t\tnewDaemonSet.Generation = oldDaemonSet.Generation + 1\n\t}\n}","line":{"from":86,"to":118}} {"id":100008940,"name":"Validate","signature":"func (daemonSetStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/apps/daemonset/strategy.go","code":"// Validate validates a new daemon set.\nfunc (daemonSetStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tdaemonSet := obj.(*apps.DaemonSet)\n\topts := pod.GetValidationOptionsFromPodTemplate(\u0026daemonSet.Spec.Template, nil)\n\treturn validation.ValidateDaemonSet(daemonSet, opts)\n}","line":{"from":120,"to":125}} {"id":100008941,"name":"WarningsOnCreate","signature":"func (daemonSetStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/apps/daemonset/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (daemonSetStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\tnewDaemonSet := obj.(*apps.DaemonSet)\n\treturn pod.GetWarningsForPodTemplate(ctx, field.NewPath(\"spec\", \"template\"), \u0026newDaemonSet.Spec.Template, nil)\n}","line":{"from":127,"to":131}} {"id":100008942,"name":"Canonicalize","signature":"func (daemonSetStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/apps/daemonset/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (daemonSetStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":133,"to":135}} {"id":100008943,"name":"AllowCreateOnUpdate","signature":"func (daemonSetStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/apps/daemonset/strategy.go","code":"// AllowCreateOnUpdate is false for daemon set; this means a POST is\n// needed to create one\nfunc (daemonSetStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":137,"to":141}} {"id":100008944,"name":"ValidateUpdate","signature":"func (daemonSetStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/apps/daemonset/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (daemonSetStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewDaemonSet := obj.(*apps.DaemonSet)\n\toldDaemonSet := old.(*apps.DaemonSet)\n\n\topts := pod.GetValidationOptionsFromPodTemplate(\u0026newDaemonSet.Spec.Template, \u0026oldDaemonSet.Spec.Template)\n\topts.AllowInvalidLabelValueInSelector = opts.AllowInvalidLabelValueInSelector || metav1validation.LabelSelectorHasInvalidLabelValue(oldDaemonSet.Spec.Selector)\n\n\tallErrs := validation.ValidateDaemonSet(obj.(*apps.DaemonSet), opts)\n\tallErrs = append(allErrs, validation.ValidateDaemonSetUpdate(newDaemonSet, oldDaemonSet, opts)...)\n\n\t// Update is not allowed to set Spec.Selector for apps/v1 and apps/v1beta2 (allowed for extensions/v1beta1).\n\t// If RequestInfo is nil, it is better to revert to old behavior (i.e. allow update to set Spec.Selector)\n\t// to prevent unintentionally breaking users who may rely on the old behavior.\n\t// TODO(#50791): after extensions/v1beta1 is removed, move selector immutability check inside ValidateDaemonSetUpdate().\n\tif requestInfo, found := genericapirequest.RequestInfoFrom(ctx); found {\n\t\tgroupVersion := schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}\n\t\tswitch groupVersion {\n\t\tcase extensionsv1beta1.SchemeGroupVersion:\n\t\t\t// no-op for compatibility\n\t\tdefault:\n\t\t\t// disallow mutation of selector\n\t\t\tallErrs = append(allErrs, apivalidation.ValidateImmutableField(newDaemonSet.Spec.Selector, oldDaemonSet.Spec.Selector, field.NewPath(\"spec\").Child(\"selector\"))...)\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":143,"to":170}} {"id":100008945,"name":"WarningsOnUpdate","signature":"func (daemonSetStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/apps/daemonset/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (daemonSetStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\tvar warnings []string\n\tnewDaemonSet := obj.(*apps.DaemonSet)\n\toldDaemonSet := old.(*apps.DaemonSet)\n\tif newDaemonSet.Spec.TemplateGeneration != oldDaemonSet.Spec.TemplateGeneration {\n\t\twarnings = pod.GetWarningsForPodTemplate(ctx, field.NewPath(\"spec\", \"template\"), \u0026newDaemonSet.Spec.Template, \u0026oldDaemonSet.Spec.Template)\n\t}\n\treturn warnings\n}","line":{"from":172,"to":181}} {"id":100008946,"name":"AllowUnconditionalUpdate","signature":"func (daemonSetStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/apps/daemonset/strategy.go","code":"// AllowUnconditionalUpdate is the default update policy for daemon set objects.\nfunc (daemonSetStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":183,"to":186}} {"id":100008947,"name":"GetResetFields","signature":"func (daemonSetStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/apps/daemonset/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (daemonSetStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"apps/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t}\n}","line":{"from":195,"to":203}} {"id":100008948,"name":"PrepareForUpdate","signature":"func (daemonSetStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/apps/daemonset/strategy.go","code":"func (daemonSetStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewDaemonSet := obj.(*apps.DaemonSet)\n\toldDaemonSet := old.(*apps.DaemonSet)\n\tnewDaemonSet.Spec = oldDaemonSet.Spec\n}","line":{"from":205,"to":209}} {"id":100008949,"name":"ValidateUpdate","signature":"func (daemonSetStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/apps/daemonset/strategy.go","code":"func (daemonSetStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateDaemonSetStatusUpdate(obj.(*apps.DaemonSet), old.(*apps.DaemonSet))\n}","line":{"from":211,"to":213}} {"id":100008950,"name":"WarningsOnUpdate","signature":"func (daemonSetStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/apps/daemonset/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (daemonSetStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":215,"to":218}} {"id":100008951,"name":"ReplicasPathMappings","signature":"func ReplicasPathMappings() managedfields.ResourcePathMappings","file":"pkg/registry/apps/deployment/storage/storage.go","code":"// ReplicasPathMappings returns the mappings between each group version and a replicas path\nfunc ReplicasPathMappings() managedfields.ResourcePathMappings {\n\treturn replicasPathInDeployment\n}","line":{"from":60,"to":63}} {"id":100008952,"name":"NewStorage","signature":"func NewStorage(optsGetter generic.RESTOptionsGetter) (DeploymentStorage, error)","file":"pkg/registry/apps/deployment/storage/storage.go","code":"// NewStorage returns new instance of DeploymentStorage.\nfunc NewStorage(optsGetter generic.RESTOptionsGetter) (DeploymentStorage, error) {\n\tdeploymentRest, deploymentStatusRest, deploymentRollbackRest, err := NewREST(optsGetter)\n\tif err != nil {\n\t\treturn DeploymentStorage{}, err\n\t}\n\n\treturn DeploymentStorage{\n\t\tDeployment: deploymentRest,\n\t\tStatus: deploymentStatusRest,\n\t\tScale: \u0026ScaleREST{store: deploymentRest.Store},\n\t\tRollback: deploymentRollbackRest,\n\t}, nil\n}","line":{"from":72,"to":85}} {"id":100008953,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, *RollbackREST, error)","file":"pkg/registry/apps/deployment/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against deployments.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, *RollbackREST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026apps.Deployment{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026apps.DeploymentList{} },\n\t\tDefaultQualifiedResource: apps.Resource(\"deployments\"),\n\t\tSingularQualifiedResource: apps.Resource(\"deployment\"),\n\n\t\tCreateStrategy: deployment.Strategy,\n\t\tUpdateStrategy: deployment.Strategy,\n\t\tDeleteStrategy: deployment.Strategy,\n\t\tResetFieldsStrategy: deployment.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = deployment.StatusStrategy\n\tstatusStore.ResetFieldsStrategy = deployment.StatusStrategy\n\treturn \u0026REST{store}, \u0026StatusREST{store: \u0026statusStore}, \u0026RollbackREST{store: store}, nil\n}","line":{"from":92,"to":116}} {"id":100008954,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/apps/deployment/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"deploy\"}\n}","line":{"from":121,"to":124}} {"id":100008955,"name":"Categories","signature":"func (r *REST) Categories() []string","file":"pkg/registry/apps/deployment/storage/storage.go","code":"// Categories implements the CategoriesProvider interface. Returns a list of categories a resource is part of.\nfunc (r *REST) Categories() []string {\n\treturn []string{\"all\"}\n}","line":{"from":129,"to":132}} {"id":100008956,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"pkg/registry/apps/deployment/storage/storage.go","code":"// New returns empty Deployment object.\nfunc (r *StatusREST) New() runtime.Object {\n\treturn \u0026apps.Deployment{}\n}","line":{"from":139,"to":142}} {"id":100008957,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"pkg/registry/apps/deployment/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":144,"to":148}} {"id":100008958,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/apps/deployment/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":150,"to":153}} {"id":100008959,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/apps/deployment/storage/storage.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":155,"to":160}} {"id":100008960,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/apps/deployment/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":162,"to":165}} {"id":100008961,"name":"ConvertToTable","signature":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/apps/deployment/storage/storage.go","code":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":167,"to":169}} {"id":100008962,"name":"ProducesMIMETypes","signature":"func (r *RollbackREST) ProducesMIMETypes(verb string) []string","file":"pkg/registry/apps/deployment/storage/storage.go","code":"// ProducesMIMETypes returns a list of the MIME types the specified HTTP verb (GET, POST, DELETE,\n// PATCH) can respond with.\nfunc (r *RollbackREST) ProducesMIMETypes(verb string) []string {\n\treturn nil\n}","line":{"from":176,"to":180}} {"id":100008963,"name":"ProducesObject","signature":"func (r *RollbackREST) ProducesObject(verb string) interface{}","file":"pkg/registry/apps/deployment/storage/storage.go","code":"// ProducesObject returns an object the specified HTTP verb respond with. It will overwrite storage object if\n// it is not nil. Only the type of the return object matters, the value will be ignored.\nfunc (r *RollbackREST) ProducesObject(verb string) interface{} {\n\treturn metav1.Status{}\n}","line":{"from":182,"to":186}} {"id":100008964,"name":"New","signature":"func (r *RollbackREST) New() runtime.Object","file":"pkg/registry/apps/deployment/storage/storage.go","code":"// New creates a rollback\nfunc (r *RollbackREST) New() runtime.Object {\n\treturn \u0026apps.DeploymentRollback{}\n}","line":{"from":190,"to":193}} {"id":100008965,"name":"Destroy","signature":"func (r *RollbackREST) Destroy()","file":"pkg/registry/apps/deployment/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *RollbackREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":195,"to":199}} {"id":100008966,"name":"Create","signature":"func (r *RollbackREST) Create(ctx context.Context, name string, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error)","file":"pkg/registry/apps/deployment/storage/storage.go","code":"// Create runs rollback for deployment\nfunc (r *RollbackREST) Create(ctx context.Context, name string, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {\n\trollback, ok := obj.(*apps.DeploymentRollback)\n\tif !ok {\n\t\treturn nil, errors.NewBadRequest(fmt.Sprintf(\"not a DeploymentRollback: %#v\", obj))\n\t}\n\n\tif errs := appsvalidation.ValidateDeploymentRollback(rollback); len(errs) != 0 {\n\t\treturn nil, errors.NewInvalid(apps.Kind(\"DeploymentRollback\"), rollback.Name, errs)\n\t}\n\tif name != rollback.Name {\n\t\treturn nil, errors.NewBadRequest(\"name in URL does not match name in DeploymentRollback object\")\n\t}\n\n\tif createValidation != nil {\n\t\tif err := createValidation(ctx, obj.DeepCopyObject()); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Update the Deployment with information in DeploymentRollback to trigger rollback\n\terr := r.rollbackDeployment(ctx, rollback.Name, \u0026rollback.RollbackTo, rollback.UpdatedAnnotations, dryrun.IsDryRun(options.DryRun))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026metav1.Status{\n\t\tStatus: metav1.StatusSuccess,\n\t\tMessage: fmt.Sprintf(\"rollback request for deployment %q succeeded\", rollback.Name),\n\t\tCode: http.StatusOK,\n\t}, nil\n}","line":{"from":203,"to":233}} {"id":100008967,"name":"rollbackDeployment","signature":"func (r *RollbackREST) rollbackDeployment(ctx context.Context, deploymentID string, config *apps.RollbackConfig, annotations map[string]string, dryRun bool) error","file":"pkg/registry/apps/deployment/storage/storage.go","code":"func (r *RollbackREST) rollbackDeployment(ctx context.Context, deploymentID string, config *apps.RollbackConfig, annotations map[string]string, dryRun bool) error {\n\tif _, err := r.setDeploymentRollback(ctx, deploymentID, config, annotations, dryRun); err != nil {\n\t\terr = storeerr.InterpretGetError(err, apps.Resource(\"deployments\"), deploymentID)\n\t\terr = storeerr.InterpretUpdateError(err, apps.Resource(\"deployments\"), deploymentID)\n\t\tif _, ok := err.(*errors.StatusError); !ok {\n\t\t\terr = errors.NewInternalError(err)\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":235,"to":245}} {"id":100008968,"name":"setDeploymentRollback","signature":"func (r *RollbackREST) setDeploymentRollback(ctx context.Context, deploymentID string, config *apps.RollbackConfig, annotations map[string]string, dryRun bool) (*apps.Deployment, error)","file":"pkg/registry/apps/deployment/storage/storage.go","code":"func (r *RollbackREST) setDeploymentRollback(ctx context.Context, deploymentID string, config *apps.RollbackConfig, annotations map[string]string, dryRun bool) (*apps.Deployment, error) {\n\tdKey, err := r.store.KeyFunc(ctx, deploymentID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar finalDeployment *apps.Deployment\n\terr = r.store.Storage.GuaranteedUpdate(ctx, dKey, \u0026apps.Deployment{}, false, nil, storage.SimpleUpdate(func(obj runtime.Object) (runtime.Object, error) {\n\t\td, ok := obj.(*apps.Deployment)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"unexpected object: %#v\", obj)\n\t\t}\n\t\tif d.Annotations == nil {\n\t\t\td.Annotations = make(map[string]string)\n\t\t}\n\t\tfor k, v := range annotations {\n\t\t\td.Annotations[k] = v\n\t\t}\n\t\td.Spec.RollbackTo = config\n\t\tfinalDeployment = d\n\t\treturn d, nil\n\t}), dryRun, nil)\n\treturn finalDeployment, err\n}","line":{"from":247,"to":269}} {"id":100008969,"name":"GroupVersionKind","signature":"func (r *ScaleREST) GroupVersionKind(containingGV schema.GroupVersion) schema.GroupVersionKind","file":"pkg/registry/apps/deployment/storage/storage.go","code":"// GroupVersionKind returns GroupVersionKind for Deployment Scale object\nfunc (r *ScaleREST) GroupVersionKind(containingGV schema.GroupVersion) schema.GroupVersionKind {\n\tswitch containingGV {\n\tcase extensionsv1beta1.SchemeGroupVersion:\n\t\treturn extensionsv1beta1.SchemeGroupVersion.WithKind(\"Scale\")\n\tcase appsv1beta1.SchemeGroupVersion:\n\t\treturn appsv1beta1.SchemeGroupVersion.WithKind(\"Scale\")\n\tcase appsv1beta2.SchemeGroupVersion:\n\t\treturn appsv1beta2.SchemeGroupVersion.WithKind(\"Scale\")\n\tdefault:\n\t\treturn autoscalingv1.SchemeGroupVersion.WithKind(\"Scale\")\n\t}\n}","line":{"from":280,"to":292}} {"id":100008970,"name":"New","signature":"func (r *ScaleREST) New() runtime.Object","file":"pkg/registry/apps/deployment/storage/storage.go","code":"// New creates a new Scale object\nfunc (r *ScaleREST) New() runtime.Object {\n\treturn \u0026autoscaling.Scale{}\n}","line":{"from":294,"to":297}} {"id":100008971,"name":"Destroy","signature":"func (r *ScaleREST) Destroy()","file":"pkg/registry/apps/deployment/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *ScaleREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":299,"to":303}} {"id":100008972,"name":"Get","signature":"func (r *ScaleREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/apps/deployment/storage/storage.go","code":"// Get retrieves object from Scale storage.\nfunc (r *ScaleREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\tobj, err := r.store.Get(ctx, name, options)\n\tif err != nil {\n\t\treturn nil, errors.NewNotFound(apps.Resource(\"deployments/scale\"), name)\n\t}\n\tdeployment := obj.(*apps.Deployment)\n\tscale, err := scaleFromDeployment(deployment)\n\tif err != nil {\n\t\treturn nil, errors.NewBadRequest(fmt.Sprintf(\"%v\", err))\n\t}\n\treturn scale, nil\n}","line":{"from":305,"to":317}} {"id":100008973,"name":"Update","signature":"func (r *ScaleREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/apps/deployment/storage/storage.go","code":"// Update alters scale subset of Deployment object.\nfunc (r *ScaleREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\tobj, _, err := r.store.Update(\n\t\tctx,\n\t\tname,\n\t\t\u0026scaleUpdatedObjectInfo{name, objInfo},\n\t\ttoScaleCreateValidation(createValidation),\n\t\ttoScaleUpdateValidation(updateValidation),\n\t\tfalse,\n\t\toptions,\n\t)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\tdeployment := obj.(*apps.Deployment)\n\tnewScale, err := scaleFromDeployment(deployment)\n\tif err != nil {\n\t\treturn nil, false, errors.NewBadRequest(fmt.Sprintf(\"%v\", err))\n\t}\n\treturn newScale, false, nil\n}","line":{"from":319,"to":339}} {"id":100008974,"name":"ConvertToTable","signature":"func (r *ScaleREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/apps/deployment/storage/storage.go","code":"func (r *ScaleREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":341,"to":343}} {"id":100008975,"name":"toScaleCreateValidation","signature":"func toScaleCreateValidation(f rest.ValidateObjectFunc) rest.ValidateObjectFunc","file":"pkg/registry/apps/deployment/storage/storage.go","code":"func toScaleCreateValidation(f rest.ValidateObjectFunc) rest.ValidateObjectFunc {\n\treturn func(ctx context.Context, obj runtime.Object) error {\n\t\tscale, err := scaleFromDeployment(obj.(*apps.Deployment))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn f(ctx, scale)\n\t}\n}","line":{"from":345,"to":353}} {"id":100008976,"name":"toScaleUpdateValidation","signature":"func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjectUpdateFunc","file":"pkg/registry/apps/deployment/storage/storage.go","code":"func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjectUpdateFunc {\n\treturn func(ctx context.Context, obj, old runtime.Object) error {\n\t\tnewScale, err := scaleFromDeployment(obj.(*apps.Deployment))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\toldScale, err := scaleFromDeployment(old.(*apps.Deployment))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn f(ctx, newScale, oldScale)\n\t}\n}","line":{"from":355,"to":367}} {"id":100008977,"name":"scaleFromDeployment","signature":"func scaleFromDeployment(deployment *apps.Deployment) (*autoscaling.Scale, error)","file":"pkg/registry/apps/deployment/storage/storage.go","code":"// scaleFromDeployment returns a scale subresource for a deployment.\nfunc scaleFromDeployment(deployment *apps.Deployment) (*autoscaling.Scale, error) {\n\tselector, err := metav1.LabelSelectorAsSelector(deployment.Spec.Selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026autoscaling.Scale{\n\t\t// TODO: Create a variant of ObjectMeta type that only contains the fields below.\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: deployment.Name,\n\t\t\tNamespace: deployment.Namespace,\n\t\t\tUID: deployment.UID,\n\t\t\tResourceVersion: deployment.ResourceVersion,\n\t\t\tCreationTimestamp: deployment.CreationTimestamp,\n\t\t},\n\t\tSpec: autoscaling.ScaleSpec{\n\t\t\tReplicas: deployment.Spec.Replicas,\n\t\t},\n\t\tStatus: autoscaling.ScaleStatus{\n\t\t\tReplicas: deployment.Status.Replicas,\n\t\t\tSelector: selector.String(),\n\t\t},\n\t}, nil\n}","line":{"from":369,"to":393}} {"id":100008978,"name":"Preconditions","signature":"func (i *scaleUpdatedObjectInfo) Preconditions() *metav1.Preconditions","file":"pkg/registry/apps/deployment/storage/storage.go","code":"func (i *scaleUpdatedObjectInfo) Preconditions() *metav1.Preconditions {\n\treturn i.reqObjInfo.Preconditions()\n}","line":{"from":401,"to":403}} {"id":100008979,"name":"UpdatedObject","signature":"func (i *scaleUpdatedObjectInfo) UpdatedObject(ctx context.Context, oldObj runtime.Object) (runtime.Object, error)","file":"pkg/registry/apps/deployment/storage/storage.go","code":"func (i *scaleUpdatedObjectInfo) UpdatedObject(ctx context.Context, oldObj runtime.Object) (runtime.Object, error) {\n\tdeployment, ok := oldObj.DeepCopyObject().(*apps.Deployment)\n\tif !ok {\n\t\treturn nil, errors.NewBadRequest(fmt.Sprintf(\"expected existing object type to be Deployment, got %T\", deployment))\n\t}\n\t// if zero-value, the existing object does not exist\n\tif len(deployment.ResourceVersion) == 0 {\n\t\treturn nil, errors.NewNotFound(apps.Resource(\"deployments/scale\"), i.name)\n\t}\n\n\tgroupVersion := schema.GroupVersion{Group: \"apps\", Version: \"v1\"}\n\tif requestInfo, found := genericapirequest.RequestInfoFrom(ctx); found {\n\t\trequestGroupVersion := schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}\n\t\tif _, ok := replicasPathInDeployment[requestGroupVersion.String()]; ok {\n\t\t\tgroupVersion = requestGroupVersion\n\t\t} else {\n\t\t\tklog.Fatalf(\"Unrecognized group/version in request info %q\", requestGroupVersion.String())\n\t\t}\n\t}\n\n\tmanagedFieldsHandler := managedfields.NewScaleHandler(\n\t\tdeployment.ManagedFields,\n\t\tgroupVersion,\n\t\treplicasPathInDeployment,\n\t)\n\n\t// deployment -\u003e old scale\n\toldScale, err := scaleFromDeployment(deployment)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tscaleManagedFields, err := managedFieldsHandler.ToSubresource()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\toldScale.ManagedFields = scaleManagedFields\n\n\t// old scale -\u003e new scale\n\tnewScaleObj, err := i.reqObjInfo.UpdatedObject(ctx, oldScale)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif newScaleObj == nil {\n\t\treturn nil, errors.NewBadRequest(\"nil update passed to Scale\")\n\t}\n\tscale, ok := newScaleObj.(*autoscaling.Scale)\n\tif !ok {\n\t\treturn nil, errors.NewBadRequest(fmt.Sprintf(\"expected input object type to be Scale, but %T\", newScaleObj))\n\t}\n\n\t// validate\n\tif errs := autoscalingvalidation.ValidateScale(scale); len(errs) \u003e 0 {\n\t\treturn nil, errors.NewInvalid(autoscaling.Kind(\"Scale\"), deployment.Name, errs)\n\t}\n\n\t// validate precondition if specified (resourceVersion matching is handled by storage)\n\tif len(scale.UID) \u003e 0 \u0026\u0026 scale.UID != deployment.UID {\n\t\treturn nil, errors.NewConflict(\n\t\t\tapps.Resource(\"deployments/scale\"),\n\t\t\tdeployment.Name,\n\t\t\tfmt.Errorf(\"Precondition failed: UID in precondition: %v, UID in object meta: %v\", scale.UID, deployment.UID),\n\t\t)\n\t}\n\n\t// move replicas/resourceVersion fields to object and return\n\tdeployment.Spec.Replicas = scale.Spec.Replicas\n\tdeployment.ResourceVersion = scale.ResourceVersion\n\n\tupdatedEntries, err := managedFieldsHandler.ToParent(scale.ManagedFields)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdeployment.ManagedFields = updatedEntries\n\n\treturn deployment, nil\n}","line":{"from":405,"to":480}} {"id":100008980,"name":"DefaultGarbageCollectionPolicy","signature":"func (deploymentStrategy) DefaultGarbageCollectionPolicy(ctx context.Context) rest.GarbageCollectionPolicy","file":"pkg/registry/apps/deployment/strategy.go","code":"// DefaultGarbageCollectionPolicy returns DeleteDependents for all currently served versions.\nfunc (deploymentStrategy) DefaultGarbageCollectionPolicy(ctx context.Context) rest.GarbageCollectionPolicy {\n\treturn rest.DeleteDependents\n}","line":{"from":54,"to":57}} {"id":100008981,"name":"NamespaceScoped","signature":"func (deploymentStrategy) NamespaceScoped() bool","file":"pkg/registry/apps/deployment/strategy.go","code":"// NamespaceScoped is true for deployment.\nfunc (deploymentStrategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":59,"to":62}} {"id":100008982,"name":"GetResetFields","signature":"func (deploymentStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/apps/deployment/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (deploymentStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"apps/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":64,"to":74}} {"id":100008983,"name":"PrepareForCreate","signature":"func (deploymentStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/apps/deployment/strategy.go","code":"// PrepareForCreate clears fields that are not allowed to be set by end users on creation.\nfunc (deploymentStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tdeployment := obj.(*apps.Deployment)\n\tdeployment.Status = apps.DeploymentStatus{}\n\tdeployment.Generation = 1\n\n\tpod.DropDisabledTemplateFields(\u0026deployment.Spec.Template, nil)\n}","line":{"from":76,"to":83}} {"id":100008984,"name":"Validate","signature":"func (deploymentStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/apps/deployment/strategy.go","code":"// Validate validates a new deployment.\nfunc (deploymentStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tdeployment := obj.(*apps.Deployment)\n\topts := pod.GetValidationOptionsFromPodTemplate(\u0026deployment.Spec.Template, nil)\n\treturn appsvalidation.ValidateDeployment(deployment, opts)\n}","line":{"from":85,"to":90}} {"id":100008985,"name":"WarningsOnCreate","signature":"func (deploymentStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/apps/deployment/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (deploymentStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\tnewDeployment := obj.(*apps.Deployment)\n\tvar warnings []string\n\tif msgs := utilvalidation.IsDNS1123Label(newDeployment.Name); len(msgs) != 0 {\n\t\twarnings = append(warnings, fmt.Sprintf(\"metadata.name: this is used in Pod names and hostnames, which can result in surprising behavior; a DNS label is recommended: %v\", msgs))\n\t}\n\twarnings = append(warnings, pod.GetWarningsForPodTemplate(ctx, field.NewPath(\"spec\", \"template\"), \u0026newDeployment.Spec.Template, nil)...)\n\treturn warnings\n}","line":{"from":92,"to":101}} {"id":100008986,"name":"Canonicalize","signature":"func (deploymentStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/apps/deployment/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (deploymentStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":103,"to":105}} {"id":100008987,"name":"AllowCreateOnUpdate","signature":"func (deploymentStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/apps/deployment/strategy.go","code":"// AllowCreateOnUpdate is false for deployments.\nfunc (deploymentStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":107,"to":110}} {"id":100008988,"name":"PrepareForUpdate","signature":"func (deploymentStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/apps/deployment/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (deploymentStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewDeployment := obj.(*apps.Deployment)\n\toldDeployment := old.(*apps.Deployment)\n\tnewDeployment.Status = oldDeployment.Status\n\n\tpod.DropDisabledTemplateFields(\u0026newDeployment.Spec.Template, \u0026oldDeployment.Spec.Template)\n\n\t// Spec updates bump the generation so that we can distinguish between\n\t// scaling events and template changes, annotation updates bump the generation\n\t// because annotations are copied from deployments to their replica sets.\n\tif !apiequality.Semantic.DeepEqual(newDeployment.Spec, oldDeployment.Spec) ||\n\t\t!apiequality.Semantic.DeepEqual(newDeployment.Annotations, oldDeployment.Annotations) {\n\t\tnewDeployment.Generation = oldDeployment.Generation + 1\n\t}\n}","line":{"from":112,"to":127}} {"id":100008989,"name":"ValidateUpdate","signature":"func (deploymentStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/apps/deployment/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (deploymentStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewDeployment := obj.(*apps.Deployment)\n\toldDeployment := old.(*apps.Deployment)\n\n\topts := pod.GetValidationOptionsFromPodTemplate(\u0026newDeployment.Spec.Template, \u0026oldDeployment.Spec.Template)\n\tallErrs := appsvalidation.ValidateDeploymentUpdate(newDeployment, oldDeployment, opts)\n\n\t// Update is not allowed to set Spec.Selector for all groups/versions except extensions/v1beta1.\n\t// If RequestInfo is nil, it is better to revert to old behavior (i.e. allow update to set Spec.Selector)\n\t// to prevent unintentionally breaking users who may rely on the old behavior.\n\t// TODO(#50791): after apps/v1beta1 and extensions/v1beta1 are removed,\n\t// move selector immutability check inside ValidateDeploymentUpdate().\n\tif requestInfo, found := genericapirequest.RequestInfoFrom(ctx); found {\n\t\tgroupVersion := schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}\n\t\tswitch groupVersion {\n\t\tcase appsv1beta1.SchemeGroupVersion, extensionsv1beta1.SchemeGroupVersion:\n\t\t\t// no-op for compatibility\n\t\tdefault:\n\t\t\t// disallow mutation of selector\n\t\t\tallErrs = append(allErrs, apivalidation.ValidateImmutableField(newDeployment.Spec.Selector, oldDeployment.Spec.Selector, field.NewPath(\"spec\").Child(\"selector\"))...)\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":129,"to":154}} {"id":100008990,"name":"WarningsOnUpdate","signature":"func (deploymentStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/apps/deployment/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (deploymentStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\tvar warnings []string\n\tnewDeployment := obj.(*apps.Deployment)\n\toldDeployment := old.(*apps.Deployment)\n\tif newDeployment.Generation != oldDeployment.Generation {\n\t\twarnings = pod.GetWarningsForPodTemplate(ctx, field.NewPath(\"spec\", \"template\"), \u0026newDeployment.Spec.Template, \u0026oldDeployment.Spec.Template)\n\t}\n\treturn warnings\n}","line":{"from":156,"to":165}} {"id":100008991,"name":"AllowUnconditionalUpdate","signature":"func (deploymentStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/apps/deployment/strategy.go","code":"func (deploymentStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":167,"to":169}} {"id":100008992,"name":"GetResetFields","signature":"func (deploymentStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/apps/deployment/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (deploymentStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"apps/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t\tfieldpath.MakePathOrDie(\"metadata\", \"labels\"),\n\t\t),\n\t}\n}","line":{"from":178,"to":187}} {"id":100008993,"name":"PrepareForUpdate","signature":"func (deploymentStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/apps/deployment/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update of status\nfunc (deploymentStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewDeployment := obj.(*apps.Deployment)\n\toldDeployment := old.(*apps.Deployment)\n\tnewDeployment.Spec = oldDeployment.Spec\n\tnewDeployment.Labels = oldDeployment.Labels\n}","line":{"from":189,"to":195}} {"id":100008994,"name":"ValidateUpdate","signature":"func (deploymentStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/apps/deployment/strategy.go","code":"// ValidateUpdate is the default update validation for an end user updating status\nfunc (deploymentStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn appsvalidation.ValidateDeploymentStatusUpdate(obj.(*apps.Deployment), old.(*apps.Deployment))\n}","line":{"from":197,"to":200}} {"id":100008995,"name":"WarningsOnUpdate","signature":"func (deploymentStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/apps/deployment/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (deploymentStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":202,"to":205}} {"id":100008996,"name":"ReplicasPathMappings","signature":"func ReplicasPathMappings() managedfields.ResourcePathMappings","file":"pkg/registry/apps/replicaset/storage/storage.go","code":"// ReplicasPathMappings returns the mappings between each group version and a replicas path\nfunc ReplicasPathMappings() managedfields.ResourcePathMappings {\n\treturn replicasPathInReplicaSet\n}","line":{"from":56,"to":59}} {"id":100008997,"name":"NewStorage","signature":"func NewStorage(optsGetter generic.RESTOptionsGetter) (ReplicaSetStorage, error)","file":"pkg/registry/apps/replicaset/storage/storage.go","code":"// NewStorage returns new instance of ReplicaSetStorage.\nfunc NewStorage(optsGetter generic.RESTOptionsGetter) (ReplicaSetStorage, error) {\n\treplicaSetRest, replicaSetStatusRest, err := NewREST(optsGetter)\n\tif err != nil {\n\t\treturn ReplicaSetStorage{}, err\n\t}\n\n\treturn ReplicaSetStorage{\n\t\tReplicaSet: replicaSetRest,\n\t\tStatus: replicaSetStatusRest,\n\t\tScale: \u0026ScaleREST{store: replicaSetRest.Store},\n\t}, nil\n}","line":{"from":67,"to":79}} {"id":100008998,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error)","file":"pkg/registry/apps/replicaset/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against ReplicaSet.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026apps.ReplicaSet{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026apps.ReplicaSetList{} },\n\t\tPredicateFunc: replicaset.MatchReplicaSet,\n\t\tDefaultQualifiedResource: apps.Resource(\"replicasets\"),\n\t\tSingularQualifiedResource: apps.Resource(\"replicaset\"),\n\n\t\tCreateStrategy: replicaset.Strategy,\n\t\tUpdateStrategy: replicaset.Strategy,\n\t\tDeleteStrategy: replicaset.Strategy,\n\t\tResetFieldsStrategy: replicaset.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: replicaset.GetAttrs}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = replicaset.StatusStrategy\n\tstatusStore.ResetFieldsStrategy = replicaset.StatusStrategy\n\n\treturn \u0026REST{store}, \u0026StatusREST{store: \u0026statusStore}, nil\n}","line":{"from":86,"to":112}} {"id":100008999,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/apps/replicaset/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"rs\"}\n}","line":{"from":117,"to":120}} {"id":100009000,"name":"Categories","signature":"func (r *REST) Categories() []string","file":"pkg/registry/apps/replicaset/storage/storage.go","code":"// Categories implements the CategoriesProvider interface. Returns a list of categories a resource is part of.\nfunc (r *REST) Categories() []string {\n\treturn []string{\"all\"}\n}","line":{"from":125,"to":128}} {"id":100009001,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"pkg/registry/apps/replicaset/storage/storage.go","code":"// New returns empty ReplicaSet object.\nfunc (r *StatusREST) New() runtime.Object {\n\treturn \u0026apps.ReplicaSet{}\n}","line":{"from":135,"to":138}} {"id":100009002,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"pkg/registry/apps/replicaset/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":140,"to":144}} {"id":100009003,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/apps/replicaset/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":146,"to":149}} {"id":100009004,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/apps/replicaset/storage/storage.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":151,"to":156}} {"id":100009005,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/apps/replicaset/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":158,"to":161}} {"id":100009006,"name":"ConvertToTable","signature":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/apps/replicaset/storage/storage.go","code":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":163,"to":165}} {"id":100009007,"name":"GroupVersionKind","signature":"func (r *ScaleREST) GroupVersionKind(containingGV schema.GroupVersion) schema.GroupVersionKind","file":"pkg/registry/apps/replicaset/storage/storage.go","code":"// GroupVersionKind returns GroupVersionKind for ReplicaSet Scale object\nfunc (r *ScaleREST) GroupVersionKind(containingGV schema.GroupVersion) schema.GroupVersionKind {\n\tswitch containingGV {\n\tcase extensionsv1beta1.SchemeGroupVersion:\n\t\treturn extensionsv1beta1.SchemeGroupVersion.WithKind(\"Scale\")\n\tcase appsv1beta1.SchemeGroupVersion:\n\t\treturn appsv1beta1.SchemeGroupVersion.WithKind(\"Scale\")\n\tcase appsv1beta2.SchemeGroupVersion:\n\t\treturn appsv1beta2.SchemeGroupVersion.WithKind(\"Scale\")\n\tdefault:\n\t\treturn autoscalingv1.SchemeGroupVersion.WithKind(\"Scale\")\n\t}\n}","line":{"from":176,"to":188}} {"id":100009008,"name":"New","signature":"func (r *ScaleREST) New() runtime.Object","file":"pkg/registry/apps/replicaset/storage/storage.go","code":"// New creates a new Scale object\nfunc (r *ScaleREST) New() runtime.Object {\n\treturn \u0026autoscaling.Scale{}\n}","line":{"from":190,"to":193}} {"id":100009009,"name":"Destroy","signature":"func (r *ScaleREST) Destroy()","file":"pkg/registry/apps/replicaset/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *ScaleREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":195,"to":199}} {"id":100009010,"name":"Get","signature":"func (r *ScaleREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/apps/replicaset/storage/storage.go","code":"// Get retrieves object from Scale storage.\nfunc (r *ScaleREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\tobj, err := r.store.Get(ctx, name, options)\n\tif err != nil {\n\t\treturn nil, errors.NewNotFound(apps.Resource(\"replicasets/scale\"), name)\n\t}\n\trs := obj.(*apps.ReplicaSet)\n\tscale, err := scaleFromReplicaSet(rs)\n\tif err != nil {\n\t\treturn nil, errors.NewBadRequest(fmt.Sprintf(\"%v\", err))\n\t}\n\treturn scale, err\n}","line":{"from":201,"to":213}} {"id":100009011,"name":"Update","signature":"func (r *ScaleREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/apps/replicaset/storage/storage.go","code":"// Update alters scale subset of ReplicaSet object.\nfunc (r *ScaleREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\tobj, _, err := r.store.Update(\n\t\tctx,\n\t\tname,\n\t\t\u0026scaleUpdatedObjectInfo{name, objInfo},\n\t\ttoScaleCreateValidation(createValidation),\n\t\ttoScaleUpdateValidation(updateValidation),\n\t\tfalse,\n\t\toptions,\n\t)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\trs := obj.(*apps.ReplicaSet)\n\tnewScale, err := scaleFromReplicaSet(rs)\n\tif err != nil {\n\t\treturn nil, false, errors.NewBadRequest(fmt.Sprintf(\"%v\", err))\n\t}\n\treturn newScale, false, err\n}","line":{"from":215,"to":235}} {"id":100009012,"name":"ConvertToTable","signature":"func (r *ScaleREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/apps/replicaset/storage/storage.go","code":"func (r *ScaleREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":237,"to":239}} {"id":100009013,"name":"toScaleCreateValidation","signature":"func toScaleCreateValidation(f rest.ValidateObjectFunc) rest.ValidateObjectFunc","file":"pkg/registry/apps/replicaset/storage/storage.go","code":"func toScaleCreateValidation(f rest.ValidateObjectFunc) rest.ValidateObjectFunc {\n\treturn func(ctx context.Context, obj runtime.Object) error {\n\t\tscale, err := scaleFromReplicaSet(obj.(*apps.ReplicaSet))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn f(ctx, scale)\n\t}\n}","line":{"from":241,"to":249}} {"id":100009014,"name":"toScaleUpdateValidation","signature":"func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjectUpdateFunc","file":"pkg/registry/apps/replicaset/storage/storage.go","code":"func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjectUpdateFunc {\n\treturn func(ctx context.Context, obj, old runtime.Object) error {\n\t\tnewScale, err := scaleFromReplicaSet(obj.(*apps.ReplicaSet))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\toldScale, err := scaleFromReplicaSet(old.(*apps.ReplicaSet))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn f(ctx, newScale, oldScale)\n\t}\n}","line":{"from":251,"to":263}} {"id":100009015,"name":"scaleFromReplicaSet","signature":"func scaleFromReplicaSet(rs *apps.ReplicaSet) (*autoscaling.Scale, error)","file":"pkg/registry/apps/replicaset/storage/storage.go","code":"// scaleFromReplicaSet returns a scale subresource for a replica set.\nfunc scaleFromReplicaSet(rs *apps.ReplicaSet) (*autoscaling.Scale, error) {\n\tselector, err := metav1.LabelSelectorAsSelector(rs.Spec.Selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026autoscaling.Scale{\n\t\t// TODO: Create a variant of ObjectMeta type that only contains the fields below.\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: rs.Name,\n\t\t\tNamespace: rs.Namespace,\n\t\t\tUID: rs.UID,\n\t\t\tResourceVersion: rs.ResourceVersion,\n\t\t\tCreationTimestamp: rs.CreationTimestamp,\n\t\t},\n\t\tSpec: autoscaling.ScaleSpec{\n\t\t\tReplicas: rs.Spec.Replicas,\n\t\t},\n\t\tStatus: autoscaling.ScaleStatus{\n\t\t\tReplicas: rs.Status.Replicas,\n\t\t\tSelector: selector.String(),\n\t\t},\n\t}, nil\n}","line":{"from":265,"to":288}} {"id":100009016,"name":"Preconditions","signature":"func (i *scaleUpdatedObjectInfo) Preconditions() *metav1.Preconditions","file":"pkg/registry/apps/replicaset/storage/storage.go","code":"func (i *scaleUpdatedObjectInfo) Preconditions() *metav1.Preconditions {\n\treturn i.reqObjInfo.Preconditions()\n}","line":{"from":296,"to":298}} {"id":100009017,"name":"UpdatedObject","signature":"func (i *scaleUpdatedObjectInfo) UpdatedObject(ctx context.Context, oldObj runtime.Object) (runtime.Object, error)","file":"pkg/registry/apps/replicaset/storage/storage.go","code":"func (i *scaleUpdatedObjectInfo) UpdatedObject(ctx context.Context, oldObj runtime.Object) (runtime.Object, error) {\n\treplicaset, ok := oldObj.DeepCopyObject().(*apps.ReplicaSet)\n\tif !ok {\n\t\treturn nil, errors.NewBadRequest(fmt.Sprintf(\"expected existing object type to be ReplicaSet, got %T\", replicaset))\n\t}\n\t// if zero-value, the existing object does not exist\n\tif len(replicaset.ResourceVersion) == 0 {\n\t\treturn nil, errors.NewNotFound(apps.Resource(\"replicasets/scale\"), i.name)\n\t}\n\n\tgroupVersion := schema.GroupVersion{Group: \"apps\", Version: \"v1\"}\n\tif requestInfo, found := genericapirequest.RequestInfoFrom(ctx); found {\n\t\trequestGroupVersion := schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}\n\t\tif _, ok := replicasPathInReplicaSet[requestGroupVersion.String()]; ok {\n\t\t\tgroupVersion = requestGroupVersion\n\t\t} else {\n\t\t\tklog.Fatalf(\"Unrecognized group/version in request info %q\", requestGroupVersion.String())\n\t\t}\n\t}\n\n\tmanagedFieldsHandler := managedfields.NewScaleHandler(\n\t\treplicaset.ManagedFields,\n\t\tgroupVersion,\n\t\treplicasPathInReplicaSet,\n\t)\n\n\t// replicaset -\u003e old scale\n\toldScale, err := scaleFromReplicaSet(replicaset)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tscaleManagedFields, err := managedFieldsHandler.ToSubresource()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\toldScale.ManagedFields = scaleManagedFields\n\n\t// old scale -\u003e new scale\n\tnewScaleObj, err := i.reqObjInfo.UpdatedObject(ctx, oldScale)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif newScaleObj == nil {\n\t\treturn nil, errors.NewBadRequest(\"nil update passed to Scale\")\n\t}\n\tscale, ok := newScaleObj.(*autoscaling.Scale)\n\tif !ok {\n\t\treturn nil, errors.NewBadRequest(fmt.Sprintf(\"expected input object type to be Scale, but %T\", newScaleObj))\n\t}\n\n\t// validate\n\tif errs := autoscalingvalidation.ValidateScale(scale); len(errs) \u003e 0 {\n\t\treturn nil, errors.NewInvalid(autoscaling.Kind(\"Scale\"), replicaset.Name, errs)\n\t}\n\n\t// validate precondition if specified (resourceVersion matching is handled by storage)\n\tif len(scale.UID) \u003e 0 \u0026\u0026 scale.UID != replicaset.UID {\n\t\treturn nil, errors.NewConflict(\n\t\t\tapps.Resource(\"replicasets/scale\"),\n\t\t\treplicaset.Name,\n\t\t\tfmt.Errorf(\"Precondition failed: UID in precondition: %v, UID in object meta: %v\", scale.UID, replicaset.UID),\n\t\t)\n\t}\n\n\t// move replicas/resourceVersion fields to object and return\n\treplicaset.Spec.Replicas = scale.Spec.Replicas\n\treplicaset.ResourceVersion = scale.ResourceVersion\n\n\tupdatedEntries, err := managedFieldsHandler.ToParent(scale.ManagedFields)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treplicaset.ManagedFields = updatedEntries\n\n\treturn replicaset, nil\n}","line":{"from":300,"to":376}} {"id":100009018,"name":"DefaultGarbageCollectionPolicy","signature":"func (rsStrategy) DefaultGarbageCollectionPolicy(ctx context.Context) rest.GarbageCollectionPolicy","file":"pkg/registry/apps/replicaset/strategy.go","code":"// DefaultGarbageCollectionPolicy returns DeleteDependents for all currently served versions.\nfunc (rsStrategy) DefaultGarbageCollectionPolicy(ctx context.Context) rest.GarbageCollectionPolicy {\n\treturn rest.DeleteDependents\n}","line":{"from":59,"to":62}} {"id":100009019,"name":"NamespaceScoped","signature":"func (rsStrategy) NamespaceScoped() bool","file":"pkg/registry/apps/replicaset/strategy.go","code":"// NamespaceScoped returns true because all ReplicaSets need to be within a namespace.\nfunc (rsStrategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":64,"to":67}} {"id":100009020,"name":"GetResetFields","signature":"func (rsStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/apps/replicaset/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (rsStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"apps/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":69,"to":79}} {"id":100009021,"name":"PrepareForCreate","signature":"func (rsStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/apps/replicaset/strategy.go","code":"// PrepareForCreate clears the status of a ReplicaSet before creation.\nfunc (rsStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\trs := obj.(*apps.ReplicaSet)\n\trs.Status = apps.ReplicaSetStatus{}\n\n\trs.Generation = 1\n\n\tpod.DropDisabledTemplateFields(\u0026rs.Spec.Template, nil)\n}","line":{"from":81,"to":89}} {"id":100009022,"name":"PrepareForUpdate","signature":"func (rsStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/apps/replicaset/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (rsStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewRS := obj.(*apps.ReplicaSet)\n\toldRS := old.(*apps.ReplicaSet)\n\t// update is not allowed to set status\n\tnewRS.Status = oldRS.Status\n\n\tpod.DropDisabledTemplateFields(\u0026newRS.Spec.Template, \u0026oldRS.Spec.Template)\n\n\t// Any changes to the spec increment the generation number, any changes to the\n\t// status should reflect the generation number of the corresponding object. We push\n\t// the burden of managing the status onto the clients because we can't (in general)\n\t// know here what version of spec the writer of the status has seen. It may seem like\n\t// we can at first -- since obj contains spec -- but in the future we will probably make\n\t// status its own object, and even if we don't, writes may be the result of a\n\t// read-update-write loop, so the contents of spec may not actually be the spec that\n\t// the ReplicaSet has *seen*.\n\tif !apiequality.Semantic.DeepEqual(oldRS.Spec, newRS.Spec) {\n\t\tnewRS.Generation = oldRS.Generation + 1\n\t}\n}","line":{"from":91,"to":111}} {"id":100009023,"name":"Validate","signature":"func (rsStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/apps/replicaset/strategy.go","code":"// Validate validates a new ReplicaSet.\nfunc (rsStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\trs := obj.(*apps.ReplicaSet)\n\topts := pod.GetValidationOptionsFromPodTemplate(\u0026rs.Spec.Template, nil)\n\treturn appsvalidation.ValidateReplicaSet(rs, opts)\n}","line":{"from":113,"to":118}} {"id":100009024,"name":"WarningsOnCreate","signature":"func (rsStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/apps/replicaset/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (rsStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\tnewRS := obj.(*apps.ReplicaSet)\n\tvar warnings []string\n\tif msgs := utilvalidation.IsDNS1123Label(newRS.Name); len(msgs) != 0 {\n\t\twarnings = append(warnings, fmt.Sprintf(\"metadata.name: this is used in Pod names and hostnames, which can result in surprising behavior; a DNS label is recommended: %v\", msgs))\n\t}\n\twarnings = append(warnings, pod.GetWarningsForPodTemplate(ctx, field.NewPath(\"spec\", \"template\"), \u0026newRS.Spec.Template, nil)...)\n\treturn warnings\n}","line":{"from":120,"to":129}} {"id":100009025,"name":"Canonicalize","signature":"func (rsStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/apps/replicaset/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (rsStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":131,"to":133}} {"id":100009026,"name":"AllowCreateOnUpdate","signature":"func (rsStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/apps/replicaset/strategy.go","code":"// AllowCreateOnUpdate is false for ReplicaSets; this means a POST is\n// needed to create one.\nfunc (rsStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":135,"to":139}} {"id":100009027,"name":"ValidateUpdate","signature":"func (rsStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/apps/replicaset/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (rsStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewReplicaSet := obj.(*apps.ReplicaSet)\n\toldReplicaSet := old.(*apps.ReplicaSet)\n\n\topts := pod.GetValidationOptionsFromPodTemplate(\u0026newReplicaSet.Spec.Template, \u0026oldReplicaSet.Spec.Template)\n\tallErrs := appsvalidation.ValidateReplicaSet(obj.(*apps.ReplicaSet), opts)\n\tallErrs = append(allErrs, appsvalidation.ValidateReplicaSetUpdate(newReplicaSet, oldReplicaSet, opts)...)\n\n\t// Update is not allowed to set Spec.Selector for all groups/versions except extensions/v1beta1.\n\t// If RequestInfo is nil, it is better to revert to old behavior (i.e. allow update to set Spec.Selector)\n\t// to prevent unintentionally breaking users who may rely on the old behavior.\n\t// TODO(#50791): after extensions/v1beta1 is removed, move selector immutability check inside ValidateReplicaSetUpdate().\n\tif requestInfo, found := genericapirequest.RequestInfoFrom(ctx); found {\n\t\tgroupVersion := schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}\n\t\tswitch groupVersion {\n\t\tcase extensionsv1beta1.SchemeGroupVersion:\n\t\t\t// no-op for compatibility\n\t\tdefault:\n\t\t\t// disallow mutation of selector\n\t\t\tallErrs = append(allErrs, apivalidation.ValidateImmutableField(newReplicaSet.Spec.Selector, oldReplicaSet.Spec.Selector, field.NewPath(\"spec\").Child(\"selector\"))...)\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":141,"to":166}} {"id":100009028,"name":"WarningsOnUpdate","signature":"func (rsStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/apps/replicaset/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (rsStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\tvar warnings []string\n\tnewReplicaSet := obj.(*apps.ReplicaSet)\n\toldReplicaSet := old.(*apps.ReplicaSet)\n\tif newReplicaSet.Generation != oldReplicaSet.Generation {\n\t\twarnings = pod.GetWarningsForPodTemplate(ctx, field.NewPath(\"spec\", \"template\"), \u0026newReplicaSet.Spec.Template, \u0026oldReplicaSet.Spec.Template)\n\t}\n\treturn warnings\n}","line":{"from":168,"to":177}} {"id":100009029,"name":"AllowUnconditionalUpdate","signature":"func (rsStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/apps/replicaset/strategy.go","code":"func (rsStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":179,"to":181}} {"id":100009030,"name":"ToSelectableFields","signature":"func ToSelectableFields(rs *apps.ReplicaSet) fields.Set","file":"pkg/registry/apps/replicaset/strategy.go","code":"// ToSelectableFields returns a field set that represents the object.\nfunc ToSelectableFields(rs *apps.ReplicaSet) fields.Set {\n\tobjectMetaFieldsSet := generic.ObjectMetaFieldsSet(\u0026rs.ObjectMeta, true)\n\trsSpecificFieldsSet := fields.Set{\n\t\t\"status.replicas\": strconv.Itoa(int(rs.Status.Replicas)),\n\t}\n\treturn generic.MergeFieldsSets(objectMetaFieldsSet, rsSpecificFieldsSet)\n}","line":{"from":183,"to":190}} {"id":100009031,"name":"GetAttrs","signature":"func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error)","file":"pkg/registry/apps/replicaset/strategy.go","code":"// GetAttrs returns labels and fields of a given object for filtering purposes.\nfunc GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {\n\trs, ok := obj.(*apps.ReplicaSet)\n\tif !ok {\n\t\treturn nil, nil, fmt.Errorf(\"given object is not a ReplicaSet\")\n\t}\n\treturn labels.Set(rs.ObjectMeta.Labels), ToSelectableFields(rs), nil\n}","line":{"from":192,"to":199}} {"id":100009032,"name":"MatchReplicaSet","signature":"func MatchReplicaSet(label labels.Selector, field fields.Selector) apistorage.SelectionPredicate","file":"pkg/registry/apps/replicaset/strategy.go","code":"// MatchReplicaSet is the filter used by the generic etcd backend to route\n// watch events from etcd to clients of the apiserver only interested in specific\n// labels/fields.\nfunc MatchReplicaSet(label labels.Selector, field fields.Selector) apistorage.SelectionPredicate {\n\treturn apistorage.SelectionPredicate{\n\t\tLabel: label,\n\t\tField: field,\n\t\tGetAttrs: GetAttrs,\n\t}\n}","line":{"from":201,"to":210}} {"id":100009033,"name":"GetResetFields","signature":"func (rsStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/apps/replicaset/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (rsStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"apps/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t}\n}","line":{"from":219,"to":227}} {"id":100009034,"name":"PrepareForUpdate","signature":"func (rsStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/apps/replicaset/strategy.go","code":"func (rsStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewRS := obj.(*apps.ReplicaSet)\n\toldRS := old.(*apps.ReplicaSet)\n\t// update is not allowed to set spec\n\tnewRS.Spec = oldRS.Spec\n}","line":{"from":229,"to":234}} {"id":100009035,"name":"ValidateUpdate","signature":"func (rsStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/apps/replicaset/strategy.go","code":"func (rsStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn appsvalidation.ValidateReplicaSetStatusUpdate(obj.(*apps.ReplicaSet), old.(*apps.ReplicaSet))\n}","line":{"from":236,"to":238}} {"id":100009036,"name":"WarningsOnUpdate","signature":"func (rsStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/apps/replicaset/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (rsStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":240,"to":243}} {"id":100009037,"name":"NewRESTStorage","signature":"func (p StorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error)","file":"pkg/registry/apps/rest/storage_apps.go","code":"// NewRESTStorage returns APIGroupInfo object.\nfunc (p StorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error) {\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(apps.GroupName, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs)\n\t// If you add a version here, be sure to add an entry in `k8s.io/kubernetes/cmd/kube-apiserver/app/aggregator.go with specific priorities.\n\t// TODO refactor the plumbing to provide the information in the APIGroupInfo\n\n\tif storageMap, err := p.v1Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[appsapiv1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\treturn apiGroupInfo, nil\n}","line":{"from":37,"to":50}} {"id":100009038,"name":"v1Storage","signature":"func (p StorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/apps/rest/storage_apps.go","code":"func (p StorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\t// deployments\n\tif resource := \"deployments\"; apiResourceConfigSource.ResourceEnabled(appsapiv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tdeploymentStorage, err := deploymentstore.NewStorage(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = deploymentStorage.Deployment\n\t\tstorage[resource+\"/status\"] = deploymentStorage.Status\n\t\tstorage[resource+\"/scale\"] = deploymentStorage.Scale\n\t}\n\n\t// statefulsets\n\tif resource := \"statefulsets\"; apiResourceConfigSource.ResourceEnabled(appsapiv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstatefulSetStorage, err := statefulsetstore.NewStorage(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = statefulSetStorage.StatefulSet\n\t\tstorage[resource+\"/status\"] = statefulSetStorage.Status\n\t\tstorage[resource+\"/scale\"] = statefulSetStorage.Scale\n\t}\n\n\t// daemonsets\n\tif resource := \"daemonsets\"; apiResourceConfigSource.ResourceEnabled(appsapiv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tdaemonSetStorage, daemonSetStatusStorage, err := daemonsetstore.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = daemonSetStorage\n\t\tstorage[resource+\"/status\"] = daemonSetStatusStorage\n\t}\n\n\t// replicasets\n\tif resource := \"replicasets\"; apiResourceConfigSource.ResourceEnabled(appsapiv1.SchemeGroupVersion.WithResource(resource)) {\n\t\treplicaSetStorage, err := replicasetstore.NewStorage(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = replicaSetStorage.ReplicaSet\n\t\tstorage[resource+\"/status\"] = replicaSetStorage.Status\n\t\tstorage[resource+\"/scale\"] = replicaSetStorage.Scale\n\t}\n\n\t// controllerrevisions\n\tif resource := \"controllerrevisions\"; apiResourceConfigSource.ResourceEnabled(appsapiv1.SchemeGroupVersion.WithResource(resource)) {\n\t\thistoryStorage, err := controllerrevisionsstore.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = historyStorage\n\t}\n\n\treturn storage, nil\n}","line":{"from":52,"to":108}} {"id":100009039,"name":"GroupName","signature":"func (p StorageProvider) GroupName() string","file":"pkg/registry/apps/rest/storage_apps.go","code":"// GroupName returns name of the group\nfunc (p StorageProvider) GroupName() string {\n\treturn apps.GroupName\n}","line":{"from":110,"to":113}} {"id":100009040,"name":"ReplicasPathMappings","signature":"func ReplicasPathMappings() managedfields.ResourcePathMappings","file":"pkg/registry/apps/statefulset/storage/storage.go","code":"// ReplicasPathMappings returns the mappings between each group version and a replicas path\nfunc ReplicasPathMappings() managedfields.ResourcePathMappings {\n\treturn replicasPathInStatefulSet\n}","line":{"from":53,"to":56}} {"id":100009041,"name":"NewStorage","signature":"func NewStorage(optsGetter generic.RESTOptionsGetter) (StatefulSetStorage, error)","file":"pkg/registry/apps/statefulset/storage/storage.go","code":"// NewStorage returns new instance of StatefulSetStorage.\nfunc NewStorage(optsGetter generic.RESTOptionsGetter) (StatefulSetStorage, error) {\n\tstatefulSetRest, statefulSetStatusRest, err := NewREST(optsGetter)\n\tif err != nil {\n\t\treturn StatefulSetStorage{}, err\n\t}\n\n\treturn StatefulSetStorage{\n\t\tStatefulSet: statefulSetRest,\n\t\tStatus: statefulSetStatusRest,\n\t\tScale: \u0026ScaleREST{store: statefulSetRest.Store},\n\t}, nil\n}","line":{"from":65,"to":77}} {"id":100009042,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error)","file":"pkg/registry/apps/statefulset/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against statefulsets.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026apps.StatefulSet{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026apps.StatefulSetList{} },\n\t\tDefaultQualifiedResource: apps.Resource(\"statefulsets\"),\n\t\tSingularQualifiedResource: apps.Resource(\"statefulset\"),\n\n\t\tCreateStrategy: statefulset.Strategy,\n\t\tUpdateStrategy: statefulset.Strategy,\n\t\tDeleteStrategy: statefulset.Strategy,\n\t\tResetFieldsStrategy: statefulset.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = statefulset.StatusStrategy\n\tstatusStore.ResetFieldsStrategy = statefulset.StatusStrategy\n\treturn \u0026REST{store}, \u0026StatusREST{store: \u0026statusStore}, nil\n}","line":{"from":84,"to":108}} {"id":100009043,"name":"Categories","signature":"func (r *REST) Categories() []string","file":"pkg/registry/apps/statefulset/storage/storage.go","code":"// Categories implements the CategoriesProvider interface. Returns a list of categories a resource is part of.\nfunc (r *REST) Categories() []string {\n\treturn []string{\"all\"}\n}","line":{"from":113,"to":116}} {"id":100009044,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"pkg/registry/apps/statefulset/storage/storage.go","code":"// New returns empty StatefulSet object.\nfunc (r *StatusREST) New() runtime.Object {\n\treturn \u0026apps.StatefulSet{}\n}","line":{"from":123,"to":126}} {"id":100009045,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"pkg/registry/apps/statefulset/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":128,"to":132}} {"id":100009046,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/apps/statefulset/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":134,"to":137}} {"id":100009047,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/apps/statefulset/storage/storage.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":139,"to":144}} {"id":100009048,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/apps/statefulset/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":146,"to":149}} {"id":100009049,"name":"ConvertToTable","signature":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/apps/statefulset/storage/storage.go","code":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":151,"to":153}} {"id":100009050,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/apps/statefulset/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"sts\"}\n}","line":{"from":158,"to":161}} {"id":100009051,"name":"GroupVersionKind","signature":"func (r *ScaleREST) GroupVersionKind(containingGV schema.GroupVersion) schema.GroupVersionKind","file":"pkg/registry/apps/statefulset/storage/storage.go","code":"// GroupVersionKind returns GroupVersionKind for StatefulSet Scale object\nfunc (r *ScaleREST) GroupVersionKind(containingGV schema.GroupVersion) schema.GroupVersionKind {\n\tswitch containingGV {\n\tcase appsv1beta1.SchemeGroupVersion:\n\t\treturn appsv1beta1.SchemeGroupVersion.WithKind(\"Scale\")\n\tcase appsv1beta2.SchemeGroupVersion:\n\t\treturn appsv1beta2.SchemeGroupVersion.WithKind(\"Scale\")\n\tdefault:\n\t\treturn autoscalingv1.SchemeGroupVersion.WithKind(\"Scale\")\n\t}\n}","line":{"from":172,"to":182}} {"id":100009052,"name":"New","signature":"func (r *ScaleREST) New() runtime.Object","file":"pkg/registry/apps/statefulset/storage/storage.go","code":"// New creates a new Scale object\nfunc (r *ScaleREST) New() runtime.Object {\n\treturn \u0026autoscaling.Scale{}\n}","line":{"from":184,"to":187}} {"id":100009053,"name":"Destroy","signature":"func (r *ScaleREST) Destroy()","file":"pkg/registry/apps/statefulset/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *ScaleREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":189,"to":193}} {"id":100009054,"name":"Get","signature":"func (r *ScaleREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/apps/statefulset/storage/storage.go","code":"// Get retrieves object from Scale storage.\nfunc (r *ScaleREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\tobj, err := r.store.Get(ctx, name, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tss := obj.(*apps.StatefulSet)\n\tscale, err := scaleFromStatefulSet(ss)\n\tif err != nil {\n\t\treturn nil, errors.NewBadRequest(fmt.Sprintf(\"%v\", err))\n\t}\n\treturn scale, err\n}","line":{"from":195,"to":207}} {"id":100009055,"name":"Update","signature":"func (r *ScaleREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/apps/statefulset/storage/storage.go","code":"// Update alters scale subset of StatefulSet object.\nfunc (r *ScaleREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\tobj, _, err := r.store.Update(\n\t\tctx,\n\t\tname,\n\t\t\u0026scaleUpdatedObjectInfo{name, objInfo},\n\t\ttoScaleCreateValidation(createValidation),\n\t\ttoScaleUpdateValidation(updateValidation),\n\t\tfalse,\n\t\toptions,\n\t)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\tss := obj.(*apps.StatefulSet)\n\tnewScale, err := scaleFromStatefulSet(ss)\n\tif err != nil {\n\t\treturn nil, false, errors.NewBadRequest(fmt.Sprintf(\"%v\", err))\n\t}\n\treturn newScale, false, err\n}","line":{"from":209,"to":229}} {"id":100009056,"name":"ConvertToTable","signature":"func (r *ScaleREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/apps/statefulset/storage/storage.go","code":"func (r *ScaleREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":231,"to":233}} {"id":100009057,"name":"toScaleCreateValidation","signature":"func toScaleCreateValidation(f rest.ValidateObjectFunc) rest.ValidateObjectFunc","file":"pkg/registry/apps/statefulset/storage/storage.go","code":"func toScaleCreateValidation(f rest.ValidateObjectFunc) rest.ValidateObjectFunc {\n\treturn func(ctx context.Context, obj runtime.Object) error {\n\t\tscale, err := scaleFromStatefulSet(obj.(*apps.StatefulSet))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn f(ctx, scale)\n\t}\n}","line":{"from":235,"to":243}} {"id":100009058,"name":"toScaleUpdateValidation","signature":"func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjectUpdateFunc","file":"pkg/registry/apps/statefulset/storage/storage.go","code":"func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjectUpdateFunc {\n\treturn func(ctx context.Context, obj, old runtime.Object) error {\n\t\tnewScale, err := scaleFromStatefulSet(obj.(*apps.StatefulSet))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\toldScale, err := scaleFromStatefulSet(old.(*apps.StatefulSet))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn f(ctx, newScale, oldScale)\n\t}\n}","line":{"from":245,"to":257}} {"id":100009059,"name":"scaleFromStatefulSet","signature":"func scaleFromStatefulSet(ss *apps.StatefulSet) (*autoscaling.Scale, error)","file":"pkg/registry/apps/statefulset/storage/storage.go","code":"// scaleFromStatefulSet returns a scale subresource for a statefulset.\nfunc scaleFromStatefulSet(ss *apps.StatefulSet) (*autoscaling.Scale, error) {\n\tselector, err := metav1.LabelSelectorAsSelector(ss.Spec.Selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026autoscaling.Scale{\n\t\t// TODO: Create a variant of ObjectMeta type that only contains the fields below.\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: ss.Name,\n\t\t\tNamespace: ss.Namespace,\n\t\t\tUID: ss.UID,\n\t\t\tResourceVersion: ss.ResourceVersion,\n\t\t\tCreationTimestamp: ss.CreationTimestamp,\n\t\t},\n\t\tSpec: autoscaling.ScaleSpec{\n\t\t\tReplicas: ss.Spec.Replicas,\n\t\t},\n\t\tStatus: autoscaling.ScaleStatus{\n\t\t\tReplicas: ss.Status.Replicas,\n\t\t\tSelector: selector.String(),\n\t\t},\n\t}, nil\n}","line":{"from":259,"to":282}} {"id":100009060,"name":"Preconditions","signature":"func (i *scaleUpdatedObjectInfo) Preconditions() *metav1.Preconditions","file":"pkg/registry/apps/statefulset/storage/storage.go","code":"func (i *scaleUpdatedObjectInfo) Preconditions() *metav1.Preconditions {\n\treturn i.reqObjInfo.Preconditions()\n}","line":{"from":290,"to":292}} {"id":100009061,"name":"UpdatedObject","signature":"func (i *scaleUpdatedObjectInfo) UpdatedObject(ctx context.Context, oldObj runtime.Object) (runtime.Object, error)","file":"pkg/registry/apps/statefulset/storage/storage.go","code":"func (i *scaleUpdatedObjectInfo) UpdatedObject(ctx context.Context, oldObj runtime.Object) (runtime.Object, error) {\n\tstatefulset, ok := oldObj.DeepCopyObject().(*apps.StatefulSet)\n\tif !ok {\n\t\treturn nil, errors.NewBadRequest(fmt.Sprintf(\"expected existing object type to be StatefulSet, got %T\", statefulset))\n\t}\n\t// if zero-value, the existing object does not exist\n\tif len(statefulset.ResourceVersion) == 0 {\n\t\treturn nil, errors.NewNotFound(apps.Resource(\"statefulsets/scale\"), i.name)\n\t}\n\n\tgroupVersion := schema.GroupVersion{Group: \"apps\", Version: \"v1\"}\n\tif requestInfo, found := genericapirequest.RequestInfoFrom(ctx); found {\n\t\trequestGroupVersion := schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}\n\t\tif _, ok := replicasPathInStatefulSet[requestGroupVersion.String()]; ok {\n\t\t\tgroupVersion = requestGroupVersion\n\t\t} else {\n\t\t\tklog.Fatalf(\"Unrecognized group/version in request info %q\", requestGroupVersion.String())\n\t\t}\n\t}\n\n\tmanagedFieldsHandler := managedfields.NewScaleHandler(\n\t\tstatefulset.ManagedFields,\n\t\tgroupVersion,\n\t\treplicasPathInStatefulSet,\n\t)\n\n\t// statefulset -\u003e old scale\n\toldScale, err := scaleFromStatefulSet(statefulset)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tscaleManagedFields, err := managedFieldsHandler.ToSubresource()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\toldScale.ManagedFields = scaleManagedFields\n\n\t// old scale -\u003e new scale\n\tnewScaleObj, err := i.reqObjInfo.UpdatedObject(ctx, oldScale)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif newScaleObj == nil {\n\t\treturn nil, errors.NewBadRequest(\"nil update passed to Scale\")\n\t}\n\tscale, ok := newScaleObj.(*autoscaling.Scale)\n\tif !ok {\n\t\treturn nil, errors.NewBadRequest(fmt.Sprintf(\"expected input object type to be Scale, but %T\", newScaleObj))\n\t}\n\n\t// validate\n\tif errs := autoscalingvalidation.ValidateScale(scale); len(errs) \u003e 0 {\n\t\treturn nil, errors.NewInvalid(autoscaling.Kind(\"Scale\"), statefulset.Name, errs)\n\t}\n\n\t// validate precondition if specified (resourceVersion matching is handled by storage)\n\tif len(scale.UID) \u003e 0 \u0026\u0026 scale.UID != statefulset.UID {\n\t\treturn nil, errors.NewConflict(\n\t\t\tapps.Resource(\"statefulsets/scale\"),\n\t\t\tstatefulset.Name,\n\t\t\tfmt.Errorf(\"Precondition failed: UID in precondition: %v, UID in object meta: %v\", scale.UID, statefulset.UID),\n\t\t)\n\t}\n\n\t// move replicas/resourceVersion fields to object and return\n\tstatefulset.Spec.Replicas = scale.Spec.Replicas\n\tstatefulset.ResourceVersion = scale.ResourceVersion\n\n\tupdatedEntries, err := managedFieldsHandler.ToParent(scale.ManagedFields)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstatefulset.ManagedFields = updatedEntries\n\n\treturn statefulset, nil\n}","line":{"from":294,"to":369}} {"id":100009062,"name":"DefaultGarbageCollectionPolicy","signature":"func (statefulSetStrategy) DefaultGarbageCollectionPolicy(ctx context.Context) rest.GarbageCollectionPolicy","file":"pkg/registry/apps/statefulset/strategy.go","code":"// DefaultGarbageCollectionPolicy returns DeleteDependents for all currently served versions.\nfunc (statefulSetStrategy) DefaultGarbageCollectionPolicy(ctx context.Context) rest.GarbageCollectionPolicy {\n\treturn rest.DeleteDependents\n}","line":{"from":49,"to":52}} {"id":100009063,"name":"NamespaceScoped","signature":"func (statefulSetStrategy) NamespaceScoped() bool","file":"pkg/registry/apps/statefulset/strategy.go","code":"// NamespaceScoped returns true because all StatefulSet' need to be within a namespace.\nfunc (statefulSetStrategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":54,"to":57}} {"id":100009064,"name":"GetResetFields","signature":"func (statefulSetStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/apps/statefulset/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (statefulSetStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"apps/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":59,"to":69}} {"id":100009065,"name":"PrepareForCreate","signature":"func (statefulSetStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/apps/statefulset/strategy.go","code":"// PrepareForCreate clears the status of an StatefulSet before creation.\nfunc (statefulSetStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tstatefulSet := obj.(*apps.StatefulSet)\n\t// create cannot set status\n\tstatefulSet.Status = apps.StatefulSetStatus{}\n\n\tstatefulSet.Generation = 1\n\n\tdropStatefulSetDisabledFields(statefulSet, nil)\n\tpod.DropDisabledTemplateFields(\u0026statefulSet.Spec.Template, nil)\n}","line":{"from":71,"to":81}} {"id":100009066,"name":"maxUnavailableInUse","signature":"func maxUnavailableInUse(statefulset *apps.StatefulSet) bool","file":"pkg/registry/apps/statefulset/strategy.go","code":"// maxUnavailableInUse returns true if StatefulSet's maxUnavailable set(used)\nfunc maxUnavailableInUse(statefulset *apps.StatefulSet) bool {\n\tif statefulset == nil {\n\t\treturn false\n\t}\n\tif statefulset.Spec.UpdateStrategy.RollingUpdate == nil {\n\t\treturn false\n\t}\n\n\treturn statefulset.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable != nil\n}","line":{"from":83,"to":93}} {"id":100009067,"name":"PrepareForUpdate","signature":"func (statefulSetStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/apps/statefulset/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (statefulSetStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewStatefulSet := obj.(*apps.StatefulSet)\n\toldStatefulSet := old.(*apps.StatefulSet)\n\t// Update is not allowed to set status\n\tnewStatefulSet.Status = oldStatefulSet.Status\n\n\tdropStatefulSetDisabledFields(newStatefulSet, oldStatefulSet)\n\tpod.DropDisabledTemplateFields(\u0026newStatefulSet.Spec.Template, \u0026oldStatefulSet.Spec.Template)\n\n\t// Any changes to the spec increment the generation number, any changes to the\n\t// status should reflect the generation number of the corresponding object.\n\t// See metav1.ObjectMeta description for more information on Generation.\n\tif !apiequality.Semantic.DeepEqual(oldStatefulSet.Spec, newStatefulSet.Spec) {\n\t\tnewStatefulSet.Generation = oldStatefulSet.Generation + 1\n\t}\n}","line":{"from":95,"to":111}} {"id":100009068,"name":"dropStatefulSetDisabledFields","signature":"func dropStatefulSetDisabledFields(newSS *apps.StatefulSet, oldSS *apps.StatefulSet)","file":"pkg/registry/apps/statefulset/strategy.go","code":"// dropStatefulSetDisabledFields drops fields that are not used if their associated feature gates\n// are not enabled.\n// The typical pattern is:\n//\n//\tif !utilfeature.DefaultFeatureGate.Enabled(features.MyFeature) \u0026\u0026 !myFeatureInUse(oldSvc) {\n//\t newSvc.Spec.MyFeature = nil\n//\t}\nfunc dropStatefulSetDisabledFields(newSS *apps.StatefulSet, oldSS *apps.StatefulSet) {\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.StatefulSetAutoDeletePVC) {\n\t\tif oldSS == nil || oldSS.Spec.PersistentVolumeClaimRetentionPolicy == nil {\n\t\t\tnewSS.Spec.PersistentVolumeClaimRetentionPolicy = nil\n\t\t}\n\t}\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.MaxUnavailableStatefulSet) \u0026\u0026 !maxUnavailableInUse(oldSS) {\n\t\tif newSS.Spec.UpdateStrategy.RollingUpdate != nil {\n\t\t\tnewSS.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable = nil\n\t\t}\n\t}\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.StatefulSetStartOrdinal) {\n\t\tif oldSS == nil || oldSS.Spec.Ordinals == nil {\n\t\t\t// Reset Spec.Ordinals to the default value (nil).\n\t\t\tnewSS.Spec.Ordinals = nil\n\t\t}\n\t}\n}","line":{"from":113,"to":137}} {"id":100009069,"name":"Validate","signature":"func (statefulSetStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/apps/statefulset/strategy.go","code":"// Validate validates a new StatefulSet.\nfunc (statefulSetStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tstatefulSet := obj.(*apps.StatefulSet)\n\topts := pod.GetValidationOptionsFromPodTemplate(\u0026statefulSet.Spec.Template, nil)\n\treturn validation.ValidateStatefulSet(statefulSet, opts)\n}","line":{"from":139,"to":144}} {"id":100009070,"name":"WarningsOnCreate","signature":"func (statefulSetStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/apps/statefulset/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (statefulSetStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\tnewStatefulSet := obj.(*apps.StatefulSet)\n\twarnings := pod.GetWarningsForPodTemplate(ctx, field.NewPath(\"spec\", \"template\"), \u0026newStatefulSet.Spec.Template, nil)\n\tfor i, pvc := range newStatefulSet.Spec.VolumeClaimTemplates {\n\t\twarnings = append(warnings, pvcutil.GetWarningsForPersistentVolumeClaimSpec(field.NewPath(\"spec\", \"volumeClaimTemplates\").Index(i), pvc.Spec)...)\n\t}\n\treturn warnings\n}","line":{"from":146,"to":154}} {"id":100009071,"name":"Canonicalize","signature":"func (statefulSetStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/apps/statefulset/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (statefulSetStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":156,"to":158}} {"id":100009072,"name":"AllowCreateOnUpdate","signature":"func (statefulSetStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/apps/statefulset/strategy.go","code":"// AllowCreateOnUpdate is false for StatefulSet; this means POST is needed to create one.\nfunc (statefulSetStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":160,"to":163}} {"id":100009073,"name":"ValidateUpdate","signature":"func (statefulSetStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/apps/statefulset/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (statefulSetStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewStatefulSet := obj.(*apps.StatefulSet)\n\toldStatefulSet := old.(*apps.StatefulSet)\n\n\topts := pod.GetValidationOptionsFromPodTemplate(\u0026newStatefulSet.Spec.Template, \u0026oldStatefulSet.Spec.Template)\n\treturn validation.ValidateStatefulSetUpdate(newStatefulSet, oldStatefulSet, opts)\n}","line":{"from":165,"to":172}} {"id":100009074,"name":"WarningsOnUpdate","signature":"func (statefulSetStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/apps/statefulset/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (statefulSetStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\tvar warnings []string\n\tnewStatefulSet := obj.(*apps.StatefulSet)\n\toldStatefulSet := old.(*apps.StatefulSet)\n\tif newStatefulSet.Generation != oldStatefulSet.Generation {\n\t\twarnings = pod.GetWarningsForPodTemplate(ctx, field.NewPath(\"spec\", \"template\"), \u0026newStatefulSet.Spec.Template, \u0026oldStatefulSet.Spec.Template)\n\t}\n\tfor i, pvc := range newStatefulSet.Spec.VolumeClaimTemplates {\n\t\twarnings = append(warnings, pvcutil.GetWarningsForPersistentVolumeClaimSpec(field.NewPath(\"spec\", \"volumeClaimTemplates\").Index(i).Child(\"Spec\"), pvc.Spec)...)\n\t}\n\n\treturn warnings\n}","line":{"from":174,"to":187}} {"id":100009075,"name":"AllowUnconditionalUpdate","signature":"func (statefulSetStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/apps/statefulset/strategy.go","code":"// AllowUnconditionalUpdate is the default update policy for StatefulSet objects.\nfunc (statefulSetStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":189,"to":192}} {"id":100009076,"name":"GetResetFields","signature":"func (statefulSetStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/apps/statefulset/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (statefulSetStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"apps/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t}\n}","line":{"from":201,"to":209}} {"id":100009077,"name":"PrepareForUpdate","signature":"func (statefulSetStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/apps/statefulset/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update of status\nfunc (statefulSetStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewStatefulSet := obj.(*apps.StatefulSet)\n\toldStatefulSet := old.(*apps.StatefulSet)\n\t// status changes are not allowed to update spec\n\tnewStatefulSet.Spec = oldStatefulSet.Spec\n}","line":{"from":211,"to":217}} {"id":100009078,"name":"ValidateUpdate","signature":"func (statefulSetStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/apps/statefulset/strategy.go","code":"// ValidateUpdate is the default update validation for an end user updating status\nfunc (statefulSetStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\t// TODO: Validate status updates.\n\treturn validation.ValidateStatefulSetStatusUpdate(obj.(*apps.StatefulSet), old.(*apps.StatefulSet))\n}","line":{"from":219,"to":223}} {"id":100009079,"name":"WarningsOnUpdate","signature":"func (statefulSetStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/apps/statefulset/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (statefulSetStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":225,"to":228}} {"id":100009080,"name":"NewRESTStorage","signature":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error)","file":"pkg/registry/authentication/rest/storage_authentication.go","code":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error) {\n\t// TODO figure out how to make the swagger generation stable, while allowing this endpoint to be disabled.\n\t// if p.Authenticator == nil {\n\t// \treturn genericapiserver.APIGroupInfo{}, false\n\t// }\n\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(authentication.GroupName, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs)\n\t// If you add a version here, be sure to add an entry in `k8s.io/kubernetes/cmd/kube-apiserver/app/aggregator.go with specific priorities.\n\t// TODO refactor the plumbing to provide the information in the APIGroupInfo\n\n\tif storageMap := p.v1alpha1Storage(apiResourceConfigSource, restOptionsGetter); len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[authenticationv1alpha1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\tif storageMap := p.v1beta1Storage(apiResourceConfigSource, restOptionsGetter); len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[authenticationv1beta1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\tif storageMap := p.v1Storage(apiResourceConfigSource, restOptionsGetter); len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[authenticationv1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\treturn apiGroupInfo, nil\n}","line":{"from":42,"to":65}} {"id":100009081,"name":"v1Storage","signature":"func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) map[string]rest.Storage","file":"pkg/registry/authentication/rest/storage_authentication.go","code":"func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) map[string]rest.Storage {\n\tstorage := map[string]rest.Storage{}\n\n\t// tokenreviews\n\tif resource := \"tokenreviews\"; apiResourceConfigSource.ResourceEnabled(authenticationv1.SchemeGroupVersion.WithResource(resource)) {\n\t\ttokenReviewStorage := tokenreview.NewREST(p.Authenticator, p.APIAudiences)\n\t\tstorage[resource] = tokenReviewStorage\n\t}\n\n\treturn storage\n}","line":{"from":67,"to":77}} {"id":100009082,"name":"v1alpha1Storage","signature":"func (p RESTStorageProvider) v1alpha1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) map[string]rest.Storage","file":"pkg/registry/authentication/rest/storage_authentication.go","code":"func (p RESTStorageProvider) v1alpha1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) map[string]rest.Storage {\n\tstorage := map[string]rest.Storage{}\n\n\t// selfsubjectreviews\n\tif resource := \"selfsubjectreviews\"; apiResourceConfigSource.ResourceEnabled(authenticationv1alpha1.SchemeGroupVersion.WithResource(resource)) {\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.APISelfSubjectReview) {\n\t\t\tselfSRStorage := selfsubjectreview.NewREST()\n\t\t\tstorage[resource] = selfSRStorage\n\t\t} else {\n\t\t\tklog.Warningln(\"SelfSubjectReview API is disabled because corresponding feature gate APISelfSubjectReview is not enabled.\")\n\t\t}\n\t}\n\treturn storage\n}","line":{"from":79,"to":92}} {"id":100009083,"name":"v1beta1Storage","signature":"func (p RESTStorageProvider) v1beta1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) map[string]rest.Storage","file":"pkg/registry/authentication/rest/storage_authentication.go","code":"func (p RESTStorageProvider) v1beta1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) map[string]rest.Storage {\n\tstorage := map[string]rest.Storage{}\n\n\t// selfsubjectreviews\n\tif resource := \"selfsubjectreviews\"; apiResourceConfigSource.ResourceEnabled(authenticationv1beta1.SchemeGroupVersion.WithResource(resource)) {\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.APISelfSubjectReview) {\n\t\t\tselfSRStorage := selfsubjectreview.NewREST()\n\t\t\tstorage[resource] = selfSRStorage\n\t\t} else {\n\t\t\tklog.Warningln(\"SelfSubjectReview API is disabled because corresponding feature gate APISelfSubjectReview is not enabled.\")\n\t\t}\n\t}\n\treturn storage\n}","line":{"from":94,"to":107}} {"id":100009084,"name":"GroupName","signature":"func (p RESTStorageProvider) GroupName() string","file":"pkg/registry/authentication/rest/storage_authentication.go","code":"func (p RESTStorageProvider) GroupName() string {\n\treturn authentication.GroupName\n}","line":{"from":109,"to":111}} {"id":100009085,"name":"NewREST","signature":"func NewREST() *REST","file":"pkg/registry/authentication/selfsubjectreview/rest.go","code":"// NewREST returns a RESTStorage object that will work against selfsubjectreviews.\nfunc NewREST() *REST {\n\treturn \u0026REST{}\n}","line":{"from":43,"to":46}} {"id":100009086,"name":"NamespaceScoped","signature":"func (r *REST) NamespaceScoped() bool","file":"pkg/registry/authentication/selfsubjectreview/rest.go","code":"// NamespaceScoped fulfill rest.Scoper\nfunc (r *REST) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":48,"to":51}} {"id":100009087,"name":"New","signature":"func (r *REST) New() runtime.Object","file":"pkg/registry/authentication/selfsubjectreview/rest.go","code":"// New creates a new selfsubjectreview object.\nfunc (r *REST) New() runtime.Object {\n\treturn \u0026authenticationapi.SelfSubjectReview{}\n}","line":{"from":53,"to":56}} {"id":100009088,"name":"Destroy","signature":"func (r *REST) Destroy()","file":"pkg/registry/authentication/selfsubjectreview/rest.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *REST) Destroy() {\n\t// Given no underlying store, we don't destroy anything\n\t// here explicitly.\n}","line":{"from":58,"to":62}} {"id":100009089,"name":"Create","signature":"func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error)","file":"pkg/registry/authentication/selfsubjectreview/rest.go","code":"// Create returns attributes of the subject making the request.\nfunc (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {\n\tif createValidation != nil {\n\t\tif err := createValidation(ctx, obj.DeepCopyObject()); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t_, ok := obj.(*authenticationapi.SelfSubjectReview)\n\tif !ok {\n\t\treturn nil, apierrors.NewBadRequest(fmt.Sprintf(\"not a SelfSubjectReview: %#v\", obj))\n\t}\n\n\tuser, ok := genericapirequest.UserFrom(ctx)\n\tif !ok {\n\t\treturn nil, apierrors.NewBadRequest(\"no user present on request\")\n\t}\n\n\textra := user.GetExtra()\n\n\tselfSR := \u0026authenticationapi.SelfSubjectReview{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tCreationTimestamp: metav1.NewTime(time.Now()),\n\t\t},\n\t\tStatus: authenticationapi.SelfSubjectReviewStatus{\n\t\t\tUserInfo: authenticationapi.UserInfo{\n\t\t\t\tUsername: user.GetName(),\n\t\t\t\tUID: user.GetUID(),\n\t\t\t\tGroups: user.GetGroups(),\n\t\t\t\tExtra: make(map[string]authenticationapi.ExtraValue, len(extra)),\n\t\t\t},\n\t\t},\n\t}\n\tfor key, attr := range extra {\n\t\tselfSR.Status.UserInfo.Extra[key] = attr\n\t}\n\n\treturn selfSR, nil\n}","line":{"from":64,"to":102}} {"id":100009090,"name":"GetSingularName","signature":"func (r *REST) GetSingularName() string","file":"pkg/registry/authentication/selfsubjectreview/rest.go","code":"func (r *REST) GetSingularName() string {\n\treturn \"selfsubjectreview\"\n}","line":{"from":106,"to":108}} {"id":100009091,"name":"NewREST","signature":"func NewREST(tokenAuthenticator authenticator.Request, apiAudiences []string) *REST","file":"pkg/registry/authentication/tokenreview/storage.go","code":"func NewREST(tokenAuthenticator authenticator.Request, apiAudiences []string) *REST {\n\treturn \u0026REST{\n\t\ttokenAuthenticator: tokenAuthenticator,\n\t\tapiAudiences: apiAudiences,\n\t}\n}","line":{"from":42,"to":47}} {"id":100009092,"name":"NamespaceScoped","signature":"func (r *REST) NamespaceScoped() bool","file":"pkg/registry/authentication/tokenreview/storage.go","code":"func (r *REST) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":49,"to":51}} {"id":100009093,"name":"New","signature":"func (r *REST) New() runtime.Object","file":"pkg/registry/authentication/tokenreview/storage.go","code":"func (r *REST) New() runtime.Object {\n\treturn \u0026authentication.TokenReview{}\n}","line":{"from":53,"to":55}} {"id":100009094,"name":"Destroy","signature":"func (r *REST) Destroy()","file":"pkg/registry/authentication/tokenreview/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *REST) Destroy() {\n\t// Given no underlying store, we don't destroy anything\n\t// here explicitly.\n}","line":{"from":57,"to":61}} {"id":100009095,"name":"GetSingularName","signature":"func (r *REST) GetSingularName() string","file":"pkg/registry/authentication/tokenreview/storage.go","code":"func (r *REST) GetSingularName() string {\n\treturn \"tokenreview\"\n}","line":{"from":65,"to":67}} {"id":100009096,"name":"Create","signature":"func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error)","file":"pkg/registry/authentication/tokenreview/storage.go","code":"func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {\n\ttokenReview, ok := obj.(*authentication.TokenReview)\n\tif !ok {\n\t\treturn nil, apierrors.NewBadRequest(fmt.Sprintf(\"not a TokenReview: %#v\", obj))\n\t}\n\tnamespace := genericapirequest.NamespaceValue(ctx)\n\tif len(namespace) != 0 {\n\t\treturn nil, apierrors.NewBadRequest(fmt.Sprintf(\"namespace is not allowed on this type: %v\", namespace))\n\t}\n\n\tif len(tokenReview.Spec.Token) == 0 {\n\t\treturn nil, apierrors.NewBadRequest(fmt.Sprintf(\"token is required for TokenReview in authentication\"))\n\t}\n\n\tif createValidation != nil {\n\t\tif err := createValidation(ctx, obj.DeepCopyObject()); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif r.tokenAuthenticator == nil {\n\t\treturn tokenReview, nil\n\t}\n\n\t// create a header that contains nothing but the token\n\tfakeReq := \u0026http.Request{Header: http.Header{}}\n\tfakeReq.Header.Add(\"Authorization\", \"Bearer \"+tokenReview.Spec.Token)\n\n\tauds := tokenReview.Spec.Audiences\n\tif len(auds) == 0 {\n\t\tauds = r.apiAudiences\n\t}\n\tif len(auds) \u003e 0 {\n\t\tfakeReq = fakeReq.WithContext(authenticator.WithAudiences(fakeReq.Context(), auds))\n\t}\n\n\tresp, ok, err := r.tokenAuthenticator.AuthenticateRequest(fakeReq)\n\ttokenReview.Status.Authenticated = ok\n\tif err != nil {\n\t\ttokenReview.Status.Error = err.Error()\n\t}\n\n\tif len(auds) \u003e 0 \u0026\u0026 resp != nil \u0026\u0026 len(authenticator.Audiences(auds).Intersect(resp.Audiences)) == 0 {\n\t\tklog.Errorf(\"error validating audience. want=%q got=%q\", auds, resp.Audiences)\n\t\treturn nil, badAuthenticatorAuds\n\t}\n\n\tif resp != nil \u0026\u0026 resp.User != nil {\n\t\ttokenReview.Status.User = authentication.UserInfo{\n\t\t\tUsername: resp.User.GetName(),\n\t\t\tUID: resp.User.GetUID(),\n\t\t\tGroups: resp.User.GetGroups(),\n\t\t\tExtra: map[string]authentication.ExtraValue{},\n\t\t}\n\t\tfor k, v := range resp.User.GetExtra() {\n\t\t\ttokenReview.Status.User.Extra[k] = authentication.ExtraValue(v)\n\t\t}\n\t\ttokenReview.Status.Audiences = resp.Audiences\n\t}\n\n\treturn tokenReview, nil\n}","line":{"from":69,"to":130}} {"id":100009097,"name":"NewREST","signature":"func NewREST(authorizer authorizer.Authorizer) *REST","file":"pkg/registry/authorization/localsubjectaccessreview/rest.go","code":"func NewREST(authorizer authorizer.Authorizer) *REST {\n\treturn \u0026REST{authorizer}\n}","line":{"from":38,"to":40}} {"id":100009098,"name":"NamespaceScoped","signature":"func (r *REST) NamespaceScoped() bool","file":"pkg/registry/authorization/localsubjectaccessreview/rest.go","code":"func (r *REST) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":42,"to":44}} {"id":100009099,"name":"New","signature":"func (r *REST) New() runtime.Object","file":"pkg/registry/authorization/localsubjectaccessreview/rest.go","code":"func (r *REST) New() runtime.Object {\n\treturn \u0026authorizationapi.LocalSubjectAccessReview{}\n}","line":{"from":46,"to":48}} {"id":100009100,"name":"Destroy","signature":"func (r *REST) Destroy()","file":"pkg/registry/authorization/localsubjectaccessreview/rest.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *REST) Destroy() {\n\t// Given no underlying store, we don't destroy anything\n\t// here explicitly.\n}","line":{"from":50,"to":54}} {"id":100009101,"name":"GetSingularName","signature":"func (r *REST) GetSingularName() string","file":"pkg/registry/authorization/localsubjectaccessreview/rest.go","code":"func (r *REST) GetSingularName() string {\n\treturn \"localsubjectaccessreview\"\n}","line":{"from":58,"to":60}} {"id":100009102,"name":"Create","signature":"func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error)","file":"pkg/registry/authorization/localsubjectaccessreview/rest.go","code":"func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {\n\tlocalSubjectAccessReview, ok := obj.(*authorizationapi.LocalSubjectAccessReview)\n\tif !ok {\n\t\treturn nil, apierrors.NewBadRequest(fmt.Sprintf(\"not a LocaLocalSubjectAccessReview: %#v\", obj))\n\t}\n\tif errs := authorizationvalidation.ValidateLocalSubjectAccessReview(localSubjectAccessReview); len(errs) \u003e 0 {\n\t\treturn nil, apierrors.NewInvalid(authorizationapi.Kind(localSubjectAccessReview.Kind), \"\", errs)\n\t}\n\tnamespace := genericapirequest.NamespaceValue(ctx)\n\tif len(namespace) == 0 {\n\t\treturn nil, apierrors.NewBadRequest(fmt.Sprintf(\"namespace is required on this type: %v\", namespace))\n\t}\n\tif namespace != localSubjectAccessReview.Namespace {\n\t\treturn nil, apierrors.NewBadRequest(fmt.Sprintf(\"spec.resourceAttributes.namespace must match namespace: %v\", namespace))\n\t}\n\n\tif createValidation != nil {\n\t\tif err := createValidation(ctx, obj.DeepCopyObject()); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tauthorizationAttributes := authorizationutil.AuthorizationAttributesFrom(localSubjectAccessReview.Spec)\n\tdecision, reason, evaluationErr := r.authorizer.Authorize(ctx, authorizationAttributes)\n\n\tlocalSubjectAccessReview.Status = authorizationapi.SubjectAccessReviewStatus{\n\t\tAllowed: (decision == authorizer.DecisionAllow),\n\t\tDenied: (decision == authorizer.DecisionDeny),\n\t\tReason: reason,\n\t}\n\tif evaluationErr != nil {\n\t\tlocalSubjectAccessReview.Status.EvaluationError = evaluationErr.Error()\n\t}\n\n\treturn localSubjectAccessReview, nil\n}","line":{"from":62,"to":97}} {"id":100009103,"name":"NewRESTStorage","signature":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error)","file":"pkg/registry/authorization/rest/storage_authorization.go","code":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error) {\n\tif p.Authorizer == nil {\n\t\treturn genericapiserver.APIGroupInfo{}, nil\n\t}\n\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(authorization.GroupName, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs)\n\t// If you add a version here, be sure to add an entry in `k8s.io/kubernetes/cmd/kube-apiserver/app/aggregator.go with specific priorities.\n\t// TODO refactor the plumbing to provide the information in the APIGroupInfo\n\n\tif storageMap := p.v1Storage(apiResourceConfigSource, restOptionsGetter); len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[authorizationv1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\treturn apiGroupInfo, nil\n}","line":{"from":39,"to":53}} {"id":100009104,"name":"v1Storage","signature":"func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) map[string]rest.Storage","file":"pkg/registry/authorization/rest/storage_authorization.go","code":"func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) map[string]rest.Storage {\n\tstorage := map[string]rest.Storage{}\n\n\t// subjectaccessreviews\n\tif resource := \"subjectaccessreviews\"; apiResourceConfigSource.ResourceEnabled(authorizationv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = subjectaccessreview.NewREST(p.Authorizer)\n\t}\n\n\t// selfsubjectaccessreviews\n\tif resource := \"selfsubjectaccessreviews\"; apiResourceConfigSource.ResourceEnabled(authorizationv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = selfsubjectaccessreview.NewREST(p.Authorizer)\n\t}\n\n\t// localsubjectaccessreviews\n\tif resource := \"localsubjectaccessreviews\"; apiResourceConfigSource.ResourceEnabled(authorizationv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = localsubjectaccessreview.NewREST(p.Authorizer)\n\t}\n\n\t// selfsubjectrulesreviews\n\tif resource := \"selfsubjectrulesreviews\"; apiResourceConfigSource.ResourceEnabled(authorizationv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = selfsubjectrulesreview.NewREST(p.RuleResolver)\n\t}\n\n\treturn storage\n}","line":{"from":55,"to":79}} {"id":100009105,"name":"GroupName","signature":"func (p RESTStorageProvider) GroupName() string","file":"pkg/registry/authorization/rest/storage_authorization.go","code":"func (p RESTStorageProvider) GroupName() string {\n\treturn authorization.GroupName\n}","line":{"from":81,"to":83}} {"id":100009106,"name":"NewREST","signature":"func NewREST(authorizer authorizer.Authorizer) *REST","file":"pkg/registry/authorization/selfsubjectaccessreview/rest.go","code":"func NewREST(authorizer authorizer.Authorizer) *REST {\n\treturn \u0026REST{authorizer}\n}","line":{"from":38,"to":40}} {"id":100009107,"name":"NamespaceScoped","signature":"func (r *REST) NamespaceScoped() bool","file":"pkg/registry/authorization/selfsubjectaccessreview/rest.go","code":"func (r *REST) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":42,"to":44}} {"id":100009108,"name":"New","signature":"func (r *REST) New() runtime.Object","file":"pkg/registry/authorization/selfsubjectaccessreview/rest.go","code":"func (r *REST) New() runtime.Object {\n\treturn \u0026authorizationapi.SelfSubjectAccessReview{}\n}","line":{"from":46,"to":48}} {"id":100009109,"name":"Destroy","signature":"func (r *REST) Destroy()","file":"pkg/registry/authorization/selfsubjectaccessreview/rest.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *REST) Destroy() {\n\t// Given no underlying store, we don't destroy anything\n\t// here explicitly.\n}","line":{"from":50,"to":54}} {"id":100009110,"name":"GetSingularName","signature":"func (r *REST) GetSingularName() string","file":"pkg/registry/authorization/selfsubjectaccessreview/rest.go","code":"func (r *REST) GetSingularName() string {\n\treturn \"selfsubjectaccessreview\"\n}","line":{"from":58,"to":60}} {"id":100009111,"name":"Create","signature":"func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error)","file":"pkg/registry/authorization/selfsubjectaccessreview/rest.go","code":"func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {\n\tselfSAR, ok := obj.(*authorizationapi.SelfSubjectAccessReview)\n\tif !ok {\n\t\treturn nil, apierrors.NewBadRequest(fmt.Sprintf(\"not a SelfSubjectAccessReview: %#v\", obj))\n\t}\n\tif errs := authorizationvalidation.ValidateSelfSubjectAccessReview(selfSAR); len(errs) \u003e 0 {\n\t\treturn nil, apierrors.NewInvalid(authorizationapi.Kind(selfSAR.Kind), \"\", errs)\n\t}\n\tuserToCheck, exists := genericapirequest.UserFrom(ctx)\n\tif !exists {\n\t\treturn nil, apierrors.NewBadRequest(\"no user present on request\")\n\t}\n\n\tif createValidation != nil {\n\t\tif err := createValidation(ctx, obj.DeepCopyObject()); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tvar authorizationAttributes authorizer.AttributesRecord\n\tif selfSAR.Spec.ResourceAttributes != nil {\n\t\tauthorizationAttributes = authorizationutil.ResourceAttributesFrom(userToCheck, *selfSAR.Spec.ResourceAttributes)\n\t} else {\n\t\tauthorizationAttributes = authorizationutil.NonResourceAttributesFrom(userToCheck, *selfSAR.Spec.NonResourceAttributes)\n\t}\n\n\tdecision, reason, evaluationErr := r.authorizer.Authorize(ctx, authorizationAttributes)\n\n\tselfSAR.Status = authorizationapi.SubjectAccessReviewStatus{\n\t\tAllowed: (decision == authorizer.DecisionAllow),\n\t\tDenied: (decision == authorizer.DecisionDeny),\n\t\tReason: reason,\n\t}\n\tif evaluationErr != nil {\n\t\tselfSAR.Status.EvaluationError = evaluationErr.Error()\n\t}\n\n\treturn selfSAR, nil\n}","line":{"from":62,"to":100}} {"id":100009112,"name":"NewREST","signature":"func NewREST(ruleResolver authorizer.RuleResolver) *REST","file":"pkg/registry/authorization/selfsubjectrulesreview/rest.go","code":"// NewREST returns a RESTStorage object that will work against selfsubjectrulesreview.\nfunc NewREST(ruleResolver authorizer.RuleResolver) *REST {\n\treturn \u0026REST{ruleResolver}\n}","line":{"from":37,"to":40}} {"id":100009113,"name":"NamespaceScoped","signature":"func (r *REST) NamespaceScoped() bool","file":"pkg/registry/authorization/selfsubjectrulesreview/rest.go","code":"// NamespaceScoped fulfill rest.Scoper\nfunc (r *REST) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":42,"to":45}} {"id":100009114,"name":"New","signature":"func (r *REST) New() runtime.Object","file":"pkg/registry/authorization/selfsubjectrulesreview/rest.go","code":"// New creates a new selfsubjectrulesreview object.\nfunc (r *REST) New() runtime.Object {\n\treturn \u0026authorizationapi.SelfSubjectRulesReview{}\n}","line":{"from":47,"to":50}} {"id":100009115,"name":"Destroy","signature":"func (r *REST) Destroy()","file":"pkg/registry/authorization/selfsubjectrulesreview/rest.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *REST) Destroy() {\n\t// Given no underlying store, we don't destroy anything\n\t// here explicitly.\n}","line":{"from":52,"to":56}} {"id":100009116,"name":"Create","signature":"func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error)","file":"pkg/registry/authorization/selfsubjectrulesreview/rest.go","code":"// Create attempts to get self subject rules in specific namespace.\nfunc (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {\n\tselfSRR, ok := obj.(*authorizationapi.SelfSubjectRulesReview)\n\tif !ok {\n\t\treturn nil, apierrors.NewBadRequest(fmt.Sprintf(\"not a SelfSubjectRulesReview: %#v\", obj))\n\t}\n\n\tuser, ok := genericapirequest.UserFrom(ctx)\n\tif !ok {\n\t\treturn nil, apierrors.NewBadRequest(\"no user present on request\")\n\t}\n\n\tnamespace := selfSRR.Spec.Namespace\n\tif namespace == \"\" {\n\t\treturn nil, apierrors.NewBadRequest(\"no namespace on request\")\n\t}\n\n\tif createValidation != nil {\n\t\tif err := createValidation(ctx, obj.DeepCopyObject()); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tresourceInfo, nonResourceInfo, incomplete, err := r.ruleResolver.RulesFor(user, namespace)\n\n\tret := \u0026authorizationapi.SelfSubjectRulesReview{\n\t\tStatus: authorizationapi.SubjectRulesReviewStatus{\n\t\t\tResourceRules: getResourceRules(resourceInfo),\n\t\t\tNonResourceRules: getNonResourceRules(nonResourceInfo),\n\t\t\tIncomplete: incomplete,\n\t\t},\n\t}\n\n\tif err != nil {\n\t\tret.Status.EvaluationError = err.Error()\n\t}\n\n\treturn ret, nil\n}","line":{"from":58,"to":96}} {"id":100009117,"name":"GetSingularName","signature":"func (r *REST) GetSingularName() string","file":"pkg/registry/authorization/selfsubjectrulesreview/rest.go","code":"func (r *REST) GetSingularName() string {\n\treturn \"selfsubjectrulesreview\"\n}","line":{"from":100,"to":102}} {"id":100009118,"name":"getResourceRules","signature":"func getResourceRules(infos []authorizer.ResourceRuleInfo) []authorizationapi.ResourceRule","file":"pkg/registry/authorization/selfsubjectrulesreview/rest.go","code":"func getResourceRules(infos []authorizer.ResourceRuleInfo) []authorizationapi.ResourceRule {\n\trules := make([]authorizationapi.ResourceRule, len(infos))\n\tfor i, info := range infos {\n\t\trules[i] = authorizationapi.ResourceRule{\n\t\t\tVerbs: info.GetVerbs(),\n\t\t\tAPIGroups: info.GetAPIGroups(),\n\t\t\tResources: info.GetResources(),\n\t\t\tResourceNames: info.GetResourceNames(),\n\t\t}\n\t}\n\treturn rules\n}","line":{"from":104,"to":115}} {"id":100009119,"name":"getNonResourceRules","signature":"func getNonResourceRules(infos []authorizer.NonResourceRuleInfo) []authorizationapi.NonResourceRule","file":"pkg/registry/authorization/selfsubjectrulesreview/rest.go","code":"func getNonResourceRules(infos []authorizer.NonResourceRuleInfo) []authorizationapi.NonResourceRule {\n\trules := make([]authorizationapi.NonResourceRule, len(infos))\n\tfor i, info := range infos {\n\t\trules[i] = authorizationapi.NonResourceRule{\n\t\t\tVerbs: info.GetVerbs(),\n\t\t\tNonResourceURLs: info.GetNonResourceURLs(),\n\t\t}\n\t}\n\treturn rules\n}","line":{"from":117,"to":126}} {"id":100009120,"name":"NewREST","signature":"func NewREST(authorizer authorizer.Authorizer) *REST","file":"pkg/registry/authorization/subjectaccessreview/rest.go","code":"func NewREST(authorizer authorizer.Authorizer) *REST {\n\treturn \u0026REST{authorizer}\n}","line":{"from":37,"to":39}} {"id":100009121,"name":"NamespaceScoped","signature":"func (r *REST) NamespaceScoped() bool","file":"pkg/registry/authorization/subjectaccessreview/rest.go","code":"func (r *REST) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":41,"to":43}} {"id":100009122,"name":"New","signature":"func (r *REST) New() runtime.Object","file":"pkg/registry/authorization/subjectaccessreview/rest.go","code":"func (r *REST) New() runtime.Object {\n\treturn \u0026authorizationapi.SubjectAccessReview{}\n}","line":{"from":45,"to":47}} {"id":100009123,"name":"Destroy","signature":"func (r *REST) Destroy()","file":"pkg/registry/authorization/subjectaccessreview/rest.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *REST) Destroy() {\n\t// Given no underlying store, we don't destroy anything\n\t// here explicitly.\n}","line":{"from":49,"to":53}} {"id":100009124,"name":"GetSingularName","signature":"func (r *REST) GetSingularName() string","file":"pkg/registry/authorization/subjectaccessreview/rest.go","code":"func (r *REST) GetSingularName() string {\n\treturn \"subjectaccessreview\"\n}","line":{"from":57,"to":59}} {"id":100009125,"name":"Create","signature":"func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error)","file":"pkg/registry/authorization/subjectaccessreview/rest.go","code":"func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {\n\tsubjectAccessReview, ok := obj.(*authorizationapi.SubjectAccessReview)\n\tif !ok {\n\t\treturn nil, apierrors.NewBadRequest(fmt.Sprintf(\"not a SubjectAccessReview: %#v\", obj))\n\t}\n\tif errs := authorizationvalidation.ValidateSubjectAccessReview(subjectAccessReview); len(errs) \u003e 0 {\n\t\treturn nil, apierrors.NewInvalid(authorizationapi.Kind(subjectAccessReview.Kind), \"\", errs)\n\t}\n\n\tif createValidation != nil {\n\t\tif err := createValidation(ctx, obj.DeepCopyObject()); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tauthorizationAttributes := authorizationutil.AuthorizationAttributesFrom(subjectAccessReview.Spec)\n\tdecision, reason, evaluationErr := r.authorizer.Authorize(ctx, authorizationAttributes)\n\n\tsubjectAccessReview.Status = authorizationapi.SubjectAccessReviewStatus{\n\t\tAllowed: (decision == authorizer.DecisionAllow),\n\t\tDenied: (decision == authorizer.DecisionDeny),\n\t\tReason: reason,\n\t}\n\tif evaluationErr != nil {\n\t\tsubjectAccessReview.Status.EvaluationError = evaluationErr.Error()\n\t}\n\n\treturn subjectAccessReview, nil\n}","line":{"from":61,"to":89}} {"id":100009126,"name":"ResourceAttributesFrom","signature":"func ResourceAttributesFrom(user user.Info, in authorizationapi.ResourceAttributes) authorizer.AttributesRecord","file":"pkg/registry/authorization/util/helpers.go","code":"// ResourceAttributesFrom combines the API object information and the user.Info from the context to build a full authorizer.AttributesRecord for resource access\nfunc ResourceAttributesFrom(user user.Info, in authorizationapi.ResourceAttributes) authorizer.AttributesRecord {\n\treturn authorizer.AttributesRecord{\n\t\tUser: user,\n\t\tVerb: in.Verb,\n\t\tNamespace: in.Namespace,\n\t\tAPIGroup: in.Group,\n\t\tAPIVersion: in.Version,\n\t\tResource: in.Resource,\n\t\tSubresource: in.Subresource,\n\t\tName: in.Name,\n\t\tResourceRequest: true,\n\t}\n}","line":{"from":25,"to":38}} {"id":100009127,"name":"NonResourceAttributesFrom","signature":"func NonResourceAttributesFrom(user user.Info, in authorizationapi.NonResourceAttributes) authorizer.AttributesRecord","file":"pkg/registry/authorization/util/helpers.go","code":"// NonResourceAttributesFrom combines the API object information and the user.Info from the context to build a full authorizer.AttributesRecord for non resource access\nfunc NonResourceAttributesFrom(user user.Info, in authorizationapi.NonResourceAttributes) authorizer.AttributesRecord {\n\treturn authorizer.AttributesRecord{\n\t\tUser: user,\n\t\tResourceRequest: false,\n\t\tPath: in.Path,\n\t\tVerb: in.Verb,\n\t}\n}","line":{"from":40,"to":48}} {"id":100009128,"name":"convertToUserInfoExtra","signature":"func convertToUserInfoExtra(extra map[string]authorizationapi.ExtraValue) map[string][]string","file":"pkg/registry/authorization/util/helpers.go","code":"func convertToUserInfoExtra(extra map[string]authorizationapi.ExtraValue) map[string][]string {\n\tif extra == nil {\n\t\treturn nil\n\t}\n\tret := map[string][]string{}\n\tfor k, v := range extra {\n\t\tret[k] = []string(v)\n\t}\n\n\treturn ret\n}","line":{"from":50,"to":60}} {"id":100009129,"name":"AuthorizationAttributesFrom","signature":"func AuthorizationAttributesFrom(spec authorizationapi.SubjectAccessReviewSpec) authorizer.AttributesRecord","file":"pkg/registry/authorization/util/helpers.go","code":"// AuthorizationAttributesFrom takes a spec and returns the proper authz attributes to check it.\nfunc AuthorizationAttributesFrom(spec authorizationapi.SubjectAccessReviewSpec) authorizer.AttributesRecord {\n\tuserToCheck := \u0026user.DefaultInfo{\n\t\tName: spec.User,\n\t\tGroups: spec.Groups,\n\t\tUID: spec.UID,\n\t\tExtra: convertToUserInfoExtra(spec.Extra),\n\t}\n\n\tvar authorizationAttributes authorizer.AttributesRecord\n\tif spec.ResourceAttributes != nil {\n\t\tauthorizationAttributes = ResourceAttributesFrom(userToCheck, *spec.ResourceAttributes)\n\t} else {\n\t\tauthorizationAttributes = NonResourceAttributesFrom(userToCheck, *spec.NonResourceAttributes)\n\t}\n\n\treturn authorizationAttributes\n}","line":{"from":62,"to":79}} {"id":100009130,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error)","file":"pkg/registry/autoscaling/horizontalpodautoscaler/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against horizontal pod autoscalers.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026autoscaling.HorizontalPodAutoscaler{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026autoscaling.HorizontalPodAutoscalerList{} },\n\t\tDefaultQualifiedResource: autoscaling.Resource(\"horizontalpodautoscalers\"),\n\t\tSingularQualifiedResource: autoscaling.Resource(\"horizontalpodautoscaler\"),\n\n\t\tCreateStrategy: horizontalpodautoscaler.Strategy,\n\t\tUpdateStrategy: horizontalpodautoscaler.Strategy,\n\t\tDeleteStrategy: horizontalpodautoscaler.Strategy,\n\t\tResetFieldsStrategy: horizontalpodautoscaler.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = horizontalpodautoscaler.StatusStrategy\n\tstatusStore.ResetFieldsStrategy = horizontalpodautoscaler.StatusStrategy\n\treturn \u0026REST{store}, \u0026StatusREST{store: \u0026statusStore}, nil\n}","line":{"from":40,"to":64}} {"id":100009131,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/autoscaling/horizontalpodautoscaler/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"hpa\"}\n}","line":{"from":69,"to":72}} {"id":100009132,"name":"Categories","signature":"func (r *REST) Categories() []string","file":"pkg/registry/autoscaling/horizontalpodautoscaler/storage/storage.go","code":"// Categories implements the CategoriesProvider interface. Returns a list of categories a resource is part of.\nfunc (r *REST) Categories() []string {\n\treturn []string{\"all\"}\n}","line":{"from":77,"to":80}} {"id":100009133,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"pkg/registry/autoscaling/horizontalpodautoscaler/storage/storage.go","code":"// New creates a new HorizontalPodAutoscaler object.\nfunc (r *StatusREST) New() runtime.Object {\n\treturn \u0026autoscaling.HorizontalPodAutoscaler{}\n}","line":{"from":87,"to":90}} {"id":100009134,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"pkg/registry/autoscaling/horizontalpodautoscaler/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":92,"to":96}} {"id":100009135,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/autoscaling/horizontalpodautoscaler/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":98,"to":101}} {"id":100009136,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/autoscaling/horizontalpodautoscaler/storage/storage.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":103,"to":108}} {"id":100009137,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/autoscaling/horizontalpodautoscaler/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":110,"to":113}} {"id":100009138,"name":"ConvertToTable","signature":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/autoscaling/horizontalpodautoscaler/storage/storage.go","code":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":115,"to":117}} {"id":100009139,"name":"NamespaceScoped","signature":"func (autoscalerStrategy) NamespaceScoped() bool","file":"pkg/registry/autoscaling/horizontalpodautoscaler/strategy.go","code":"// NamespaceScoped is true for autoscaler.\nfunc (autoscalerStrategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":43,"to":46}} {"id":100009140,"name":"GetResetFields","signature":"func (autoscalerStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/autoscaling/horizontalpodautoscaler/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (autoscalerStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"autoscaling/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t\t\"autoscaling/v2\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t\t\"autoscaling/v2beta1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t\t\"autoscaling/v2beta2\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":48,"to":67}} {"id":100009141,"name":"PrepareForCreate","signature":"func (autoscalerStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/autoscaling/horizontalpodautoscaler/strategy.go","code":"// PrepareForCreate clears fields that are not allowed to be set by end users on creation.\nfunc (autoscalerStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tnewHPA := obj.(*autoscaling.HorizontalPodAutoscaler)\n\n\t// create cannot set status\n\tnewHPA.Status = autoscaling.HorizontalPodAutoscalerStatus{}\n\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.HPAContainerMetrics) {\n\t\tdropContainerMetricSources(newHPA.Spec.Metrics)\n\t}\n}","line":{"from":69,"to":79}} {"id":100009142,"name":"Validate","signature":"func (autoscalerStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/autoscaling/horizontalpodautoscaler/strategy.go","code":"// Validate validates a new autoscaler.\nfunc (autoscalerStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tautoscaler := obj.(*autoscaling.HorizontalPodAutoscaler)\n\treturn validation.ValidateHorizontalPodAutoscaler(autoscaler)\n}","line":{"from":81,"to":85}} {"id":100009143,"name":"WarningsOnCreate","signature":"func (autoscalerStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/autoscaling/horizontalpodautoscaler/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (autoscalerStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":87,"to":90}} {"id":100009144,"name":"Canonicalize","signature":"func (autoscalerStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/autoscaling/horizontalpodautoscaler/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (autoscalerStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":92,"to":94}} {"id":100009145,"name":"AllowCreateOnUpdate","signature":"func (autoscalerStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/autoscaling/horizontalpodautoscaler/strategy.go","code":"// AllowCreateOnUpdate is false for autoscalers.\nfunc (autoscalerStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":96,"to":99}} {"id":100009146,"name":"PrepareForUpdate","signature":"func (autoscalerStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/autoscaling/horizontalpodautoscaler/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (autoscalerStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewHPA := obj.(*autoscaling.HorizontalPodAutoscaler)\n\toldHPA := old.(*autoscaling.HorizontalPodAutoscaler)\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.HPAContainerMetrics) \u0026\u0026 !hasContainerMetricSources(oldHPA) {\n\t\tdropContainerMetricSources(newHPA.Spec.Metrics)\n\t}\n\t// Update is not allowed to set status\n\tnewHPA.Status = oldHPA.Status\n}","line":{"from":101,"to":110}} {"id":100009147,"name":"dropContainerMetricSources","signature":"func dropContainerMetricSources(metrics []autoscaling.MetricSpec)","file":"pkg/registry/autoscaling/horizontalpodautoscaler/strategy.go","code":"// dropContainerMetricSources ensures all container resource metric sources are nil\nfunc dropContainerMetricSources(metrics []autoscaling.MetricSpec) {\n\tfor i := range metrics {\n\t\tmetrics[i].ContainerResource = nil\n\t}\n}","line":{"from":112,"to":117}} {"id":100009148,"name":"hasContainerMetricSources","signature":"func hasContainerMetricSources(hpa *autoscaling.HorizontalPodAutoscaler) bool","file":"pkg/registry/autoscaling/horizontalpodautoscaler/strategy.go","code":"// hasContainerMetricSources returns true if the hpa has any container resource metric sources\nfunc hasContainerMetricSources(hpa *autoscaling.HorizontalPodAutoscaler) bool {\n\tfor i := range hpa.Spec.Metrics {\n\t\tif hpa.Spec.Metrics[i].ContainerResource != nil {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":119,"to":127}} {"id":100009149,"name":"ValidateUpdate","signature":"func (autoscalerStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/autoscaling/horizontalpodautoscaler/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (autoscalerStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateHorizontalPodAutoscalerUpdate(obj.(*autoscaling.HorizontalPodAutoscaler), old.(*autoscaling.HorizontalPodAutoscaler))\n}","line":{"from":129,"to":132}} {"id":100009150,"name":"WarningsOnUpdate","signature":"func (autoscalerStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/autoscaling/horizontalpodautoscaler/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (autoscalerStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":134,"to":137}} {"id":100009151,"name":"AllowUnconditionalUpdate","signature":"func (autoscalerStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/autoscaling/horizontalpodautoscaler/strategy.go","code":"func (autoscalerStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":139,"to":141}} {"id":100009152,"name":"GetResetFields","signature":"func (autoscalerStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/autoscaling/horizontalpodautoscaler/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (autoscalerStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"autoscaling/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t\t\"autoscaling/v2\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t\t\"autoscaling/v2beta1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t\t\"autoscaling/v2beta2\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":150,"to":169}} {"id":100009153,"name":"PrepareForUpdate","signature":"func (autoscalerStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/autoscaling/horizontalpodautoscaler/strategy.go","code":"func (autoscalerStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewAutoscaler := obj.(*autoscaling.HorizontalPodAutoscaler)\n\toldAutoscaler := old.(*autoscaling.HorizontalPodAutoscaler)\n\t// status changes are not allowed to update spec\n\tnewAutoscaler.Spec = oldAutoscaler.Spec\n}","line":{"from":171,"to":176}} {"id":100009154,"name":"ValidateUpdate","signature":"func (autoscalerStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/autoscaling/horizontalpodautoscaler/strategy.go","code":"func (autoscalerStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateHorizontalPodAutoscalerStatusUpdate(obj.(*autoscaling.HorizontalPodAutoscaler), old.(*autoscaling.HorizontalPodAutoscaler))\n}","line":{"from":178,"to":180}} {"id":100009155,"name":"WarningsOnUpdate","signature":"func (autoscalerStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/autoscaling/horizontalpodautoscaler/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (autoscalerStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":182,"to":185}} {"id":100009156,"name":"NewRESTStorage","signature":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error)","file":"pkg/registry/autoscaling/rest/storage_autoscaling.go","code":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error) {\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(autoscaling.GroupName, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs)\n\t// If you add a version here, be sure to add an entry in `k8s.io/kubernetes/cmd/kube-apiserver/app/aggregator.go with specific priorities.\n\t// TODO refactor the plumbing to provide the information in the APIGroupInfo\n\n\tif storageMap, err := p.v2beta2Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[autoscalingapiv2beta2.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\tif storageMap, err := p.v2Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[autoscalingapiv2.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\tif storageMap, err := p.v2beta1Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[autoscalingapiv2beta1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\tif storageMap, err := p.v1Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[autoscalingapiv1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\treturn apiGroupInfo, nil\n}","line":{"from":35,"to":65}} {"id":100009157,"name":"v1Storage","signature":"func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/autoscaling/rest/storage_autoscaling.go","code":"func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\t// horizontalpodautoscalers\n\tif resource := \"horizontalpodautoscalers\"; apiResourceConfigSource.ResourceEnabled(autoscalingapiv1.SchemeGroupVersion.WithResource(resource)) {\n\t\thpaStorage, hpaStatusStorage, err := horizontalpodautoscalerstore.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = hpaStorage\n\t\tstorage[resource+\"/status\"] = hpaStatusStorage\n\t}\n\n\treturn storage, nil\n}","line":{"from":67,"to":81}} {"id":100009158,"name":"v2beta1Storage","signature":"func (p RESTStorageProvider) v2beta1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/autoscaling/rest/storage_autoscaling.go","code":"func (p RESTStorageProvider) v2beta1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\t// horizontalpodautoscalers\n\tif resource := \"horizontalpodautoscalers\"; apiResourceConfigSource.ResourceEnabled(autoscalingapiv2beta1.SchemeGroupVersion.WithResource(resource)) {\n\t\thpaStorage, hpaStatusStorage, err := horizontalpodautoscalerstore.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = hpaStorage\n\t\tstorage[resource+\"/status\"] = hpaStatusStorage\n\t}\n\n\treturn storage, nil\n}","line":{"from":83,"to":97}} {"id":100009159,"name":"v2beta2Storage","signature":"func (p RESTStorageProvider) v2beta2Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/autoscaling/rest/storage_autoscaling.go","code":"func (p RESTStorageProvider) v2beta2Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\t// horizontalpodautoscalers\n\tif resource := \"horizontalpodautoscalers\"; apiResourceConfigSource.ResourceEnabled(autoscalingapiv2beta2.SchemeGroupVersion.WithResource(resource)) {\n\t\thpaStorage, hpaStatusStorage, err := horizontalpodautoscalerstore.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = hpaStorage\n\t\tstorage[resource+\"/status\"] = hpaStatusStorage\n\t}\n\treturn storage, nil\n}","line":{"from":99,"to":112}} {"id":100009160,"name":"v2Storage","signature":"func (p RESTStorageProvider) v2Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/autoscaling/rest/storage_autoscaling.go","code":"func (p RESTStorageProvider) v2Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\t// horizontalpodautoscalers\n\tif resource := \"horizontalpodautoscalers\"; apiResourceConfigSource.ResourceEnabled(autoscalingapiv2.SchemeGroupVersion.WithResource(resource)) {\n\t\thpaStorage, hpaStatusStorage, err := horizontalpodautoscalerstore.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = hpaStorage\n\t\tstorage[resource+\"/status\"] = hpaStatusStorage\n\t}\n\n\treturn storage, nil\n}","line":{"from":114,"to":128}} {"id":100009161,"name":"GroupName","signature":"func (p RESTStorageProvider) GroupName() string","file":"pkg/registry/autoscaling/rest/storage_autoscaling.go","code":"func (p RESTStorageProvider) GroupName() string {\n\treturn autoscaling.GroupName\n}","line":{"from":130,"to":132}} {"id":100009162,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error)","file":"pkg/registry/batch/cronjob/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against CronJobs.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026batch.CronJob{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026batch.CronJobList{} },\n\t\tDefaultQualifiedResource: batch.Resource(\"cronjobs\"),\n\t\tSingularQualifiedResource: batch.Resource(\"cronjob\"),\n\n\t\tCreateStrategy: cronjob.Strategy,\n\t\tUpdateStrategy: cronjob.Strategy,\n\t\tDeleteStrategy: cronjob.Strategy,\n\t\tResetFieldsStrategy: cronjob.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = cronjob.StatusStrategy\n\tstatusStore.ResetFieldsStrategy = cronjob.StatusStrategy\n\n\treturn \u0026REST{store}, \u0026StatusREST{store: \u0026statusStore}, nil\n}","line":{"from":40,"to":65}} {"id":100009163,"name":"Categories","signature":"func (r *REST) Categories() []string","file":"pkg/registry/batch/cronjob/storage/storage.go","code":"// Categories implements the CategoriesProvider interface. Returns a list of categories a resource is part of.\nfunc (r *REST) Categories() []string {\n\treturn []string{\"all\"}\n}","line":{"from":70,"to":73}} {"id":100009164,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/batch/cronjob/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"cj\"}\n}","line":{"from":75,"to":78}} {"id":100009165,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"pkg/registry/batch/cronjob/storage/storage.go","code":"// New creates a new CronJob object.\nfunc (r *StatusREST) New() runtime.Object {\n\treturn \u0026batch.CronJob{}\n}","line":{"from":85,"to":88}} {"id":100009166,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"pkg/registry/batch/cronjob/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":90,"to":94}} {"id":100009167,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/batch/cronjob/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":96,"to":99}} {"id":100009168,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/batch/cronjob/storage/storage.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":101,"to":106}} {"id":100009169,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/batch/cronjob/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":108,"to":111}} {"id":100009170,"name":"ConvertToTable","signature":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/batch/cronjob/storage/storage.go","code":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":113,"to":115}} {"id":100009171,"name":"DefaultGarbageCollectionPolicy","signature":"func (cronJobStrategy) DefaultGarbageCollectionPolicy(ctx context.Context) rest.GarbageCollectionPolicy","file":"pkg/registry/batch/cronjob/strategy.go","code":"// DefaultGarbageCollectionPolicy returns OrphanDependents for batch/v1beta1 for backwards compatibility,\n// and DeleteDependents for all other versions.\nfunc (cronJobStrategy) DefaultGarbageCollectionPolicy(ctx context.Context) rest.GarbageCollectionPolicy {\n\tvar groupVersion schema.GroupVersion\n\tif requestInfo, found := genericapirequest.RequestInfoFrom(ctx); found {\n\t\tgroupVersion = schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}\n\t}\n\tswitch groupVersion {\n\tcase batchv1beta1.SchemeGroupVersion:\n\t\t// for back compatibility\n\t\treturn rest.OrphanDependents\n\tdefault:\n\t\treturn rest.DeleteDependents\n\t}\n}","line":{"from":49,"to":63}} {"id":100009172,"name":"NamespaceScoped","signature":"func (cronJobStrategy) NamespaceScoped() bool","file":"pkg/registry/batch/cronjob/strategy.go","code":"// NamespaceScoped returns true because all scheduled jobs need to be within a namespace.\nfunc (cronJobStrategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":65,"to":68}} {"id":100009173,"name":"GetResetFields","signature":"func (cronJobStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/batch/cronjob/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (cronJobStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"batch/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t\t\"batch/v1beta1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":70,"to":83}} {"id":100009174,"name":"PrepareForCreate","signature":"func (cronJobStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/batch/cronjob/strategy.go","code":"// PrepareForCreate clears the status of a scheduled job before creation.\nfunc (cronJobStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tcronJob := obj.(*batch.CronJob)\n\tcronJob.Status = batch.CronJobStatus{}\n\n\tcronJob.Generation = 1\n\n\tpod.DropDisabledTemplateFields(\u0026cronJob.Spec.JobTemplate.Spec.Template, nil)\n}","line":{"from":85,"to":93}} {"id":100009175,"name":"PrepareForUpdate","signature":"func (cronJobStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/batch/cronjob/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (cronJobStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewCronJob := obj.(*batch.CronJob)\n\toldCronJob := old.(*batch.CronJob)\n\tnewCronJob.Status = oldCronJob.Status\n\n\tpod.DropDisabledTemplateFields(\u0026newCronJob.Spec.JobTemplate.Spec.Template, \u0026oldCronJob.Spec.JobTemplate.Spec.Template)\n\n\t// Any changes to the spec increment the generation number.\n\t// See metav1.ObjectMeta description for more information on Generation.\n\tif !apiequality.Semantic.DeepEqual(newCronJob.Spec, oldCronJob.Spec) {\n\t\tnewCronJob.Generation = oldCronJob.Generation + 1\n\t}\n}","line":{"from":95,"to":108}} {"id":100009176,"name":"Validate","signature":"func (cronJobStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/batch/cronjob/strategy.go","code":"// Validate validates a new scheduled job.\nfunc (cronJobStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tcronJob := obj.(*batch.CronJob)\n\topts := pod.GetValidationOptionsFromPodTemplate(\u0026cronJob.Spec.JobTemplate.Spec.Template, nil)\n\treturn batchvalidation.ValidateCronJobCreate(cronJob, opts)\n}","line":{"from":110,"to":115}} {"id":100009177,"name":"WarningsOnCreate","signature":"func (cronJobStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/batch/cronjob/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (cronJobStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\tnewCronJob := obj.(*batch.CronJob)\n\tvar warnings []string\n\tif msgs := utilvalidation.IsDNS1123Label(newCronJob.Name); len(msgs) != 0 {\n\t\twarnings = append(warnings, fmt.Sprintf(\"metadata.name: this is used in Pod names and hostnames, which can result in surprising behavior; a DNS label is recommended: %v\", msgs))\n\t}\n\twarnings = append(warnings, pod.GetWarningsForPodTemplate(ctx, field.NewPath(\"spec\", \"jobTemplate\", \"spec\", \"template\"), \u0026newCronJob.Spec.JobTemplate.Spec.Template, nil)...)\n\tif strings.Contains(newCronJob.Spec.Schedule, \"TZ\") {\n\t\twarnings = append(warnings, fmt.Sprintf(\"CRON_TZ or TZ used in %s is not officially supported, see https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/ for more details\", field.NewPath(\"spec\", \"spec\", \"schedule\")))\n\t}\n\treturn warnings\n}","line":{"from":117,"to":129}} {"id":100009178,"name":"Canonicalize","signature":"func (cronJobStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/batch/cronjob/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (cronJobStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":131,"to":133}} {"id":100009179,"name":"AllowUnconditionalUpdate","signature":"func (cronJobStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/batch/cronjob/strategy.go","code":"func (cronJobStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":135,"to":137}} {"id":100009180,"name":"AllowCreateOnUpdate","signature":"func (cronJobStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/batch/cronjob/strategy.go","code":"// AllowCreateOnUpdate is false for scheduled jobs; this means a POST is needed to create one.\nfunc (cronJobStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":139,"to":142}} {"id":100009181,"name":"ValidateUpdate","signature":"func (cronJobStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/batch/cronjob/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (cronJobStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewCronJob := obj.(*batch.CronJob)\n\toldCronJob := old.(*batch.CronJob)\n\n\topts := pod.GetValidationOptionsFromPodTemplate(\u0026newCronJob.Spec.JobTemplate.Spec.Template, \u0026oldCronJob.Spec.JobTemplate.Spec.Template)\n\treturn batchvalidation.ValidateCronJobUpdate(newCronJob, oldCronJob, opts)\n}","line":{"from":144,"to":151}} {"id":100009182,"name":"WarningsOnUpdate","signature":"func (cronJobStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/batch/cronjob/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (cronJobStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\tvar warnings []string\n\tnewCronJob := obj.(*batch.CronJob)\n\toldCronJob := old.(*batch.CronJob)\n\tif newCronJob.Generation != oldCronJob.Generation {\n\t\twarnings = pod.GetWarningsForPodTemplate(ctx, field.NewPath(\"spec\", \"jobTemplate\", \"spec\", \"template\"), \u0026newCronJob.Spec.JobTemplate.Spec.Template, \u0026oldCronJob.Spec.JobTemplate.Spec.Template)\n\t}\n\tif strings.Contains(newCronJob.Spec.Schedule, \"TZ\") {\n\t\twarnings = append(warnings, fmt.Sprintf(\"CRON_TZ or TZ used in %s is not officially supported, see https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/ for more details\", field.NewPath(\"spec\", \"spec\", \"schedule\")))\n\t}\n\treturn warnings\n}","line":{"from":153,"to":165}} {"id":100009183,"name":"GetResetFields","signature":"func (cronJobStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/batch/cronjob/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (cronJobStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"batch/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t\t\"batch/v1beta1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t}\n}","line":{"from":174,"to":185}} {"id":100009184,"name":"PrepareForUpdate","signature":"func (cronJobStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/batch/cronjob/strategy.go","code":"func (cronJobStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewJob := obj.(*batch.CronJob)\n\toldJob := old.(*batch.CronJob)\n\tnewJob.Spec = oldJob.Spec\n}","line":{"from":187,"to":191}} {"id":100009185,"name":"ValidateUpdate","signature":"func (cronJobStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/batch/cronjob/strategy.go","code":"func (cronJobStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn field.ErrorList{}\n}","line":{"from":193,"to":195}} {"id":100009186,"name":"WarningsOnUpdate","signature":"func (cronJobStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/batch/cronjob/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (cronJobStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":197,"to":200}} {"id":100009187,"name":"NewStorage","signature":"func NewStorage(optsGetter generic.RESTOptionsGetter) (JobStorage, error)","file":"pkg/registry/batch/job/storage/storage.go","code":"// NewStorage creates a new JobStorage against etcd.\nfunc NewStorage(optsGetter generic.RESTOptionsGetter) (JobStorage, error) {\n\tjobRest, jobStatusRest, err := NewREST(optsGetter)\n\tif err != nil {\n\t\treturn JobStorage{}, err\n\t}\n\n\treturn JobStorage{\n\t\tJob: jobRest,\n\t\tStatus: jobStatusRest,\n\t}, nil\n}","line":{"from":43,"to":54}} {"id":100009188,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error)","file":"pkg/registry/batch/job/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against Jobs.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026batch.Job{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026batch.JobList{} },\n\t\tPredicateFunc: job.MatchJob,\n\t\tDefaultQualifiedResource: batch.Resource(\"jobs\"),\n\t\tSingularQualifiedResource: batch.Resource(\"job\"),\n\n\t\tCreateStrategy: job.Strategy,\n\t\tUpdateStrategy: job.Strategy,\n\t\tDeleteStrategy: job.Strategy,\n\t\tResetFieldsStrategy: job.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: job.GetAttrs}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = job.StatusStrategy\n\tstatusStore.ResetFieldsStrategy = job.StatusStrategy\n\n\treturn \u0026REST{store}, \u0026StatusREST{store: \u0026statusStore}, nil\n}","line":{"from":64,"to":90}} {"id":100009189,"name":"Categories","signature":"func (r *REST) Categories() []string","file":"pkg/registry/batch/job/storage/storage.go","code":"// Categories implements the CategoriesProvider interface. Returns a list of categories a resource is part of.\nfunc (r *REST) Categories() []string {\n\treturn []string{\"all\"}\n}","line":{"from":95,"to":98}} {"id":100009190,"name":"Delete","signature":"func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions) (runtime.Object, bool, error)","file":"pkg/registry/batch/job/storage/storage.go","code":"func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions) (runtime.Object, bool, error) {\n\t//nolint:staticcheck // SA1019 backwards compatibility\n\t//nolint: staticcheck\n\tif options != nil \u0026\u0026 options.PropagationPolicy == nil \u0026\u0026 options.OrphanDependents == nil \u0026\u0026\n\t\tjob.Strategy.DefaultGarbageCollectionPolicy(ctx) == rest.OrphanDependents {\n\t\t// Throw a warning if delete options are not explicitly set as Job deletion strategy by default is orphaning\n\t\t// pods in v1.\n\t\twarning.AddWarning(ctx, \"\", deleteOptionWarnings)\n\t}\n\treturn r.Store.Delete(ctx, name, deleteValidation, options)\n}","line":{"from":100,"to":110}} {"id":100009191,"name":"DeleteCollection","signature":"func (r *REST) DeleteCollection(ctx context.Context, deleteValidation rest.ValidateObjectFunc, deleteOptions *metav1.DeleteOptions, listOptions *internalversion.ListOptions) (runtime.Object, error)","file":"pkg/registry/batch/job/storage/storage.go","code":"func (r *REST) DeleteCollection(ctx context.Context, deleteValidation rest.ValidateObjectFunc, deleteOptions *metav1.DeleteOptions, listOptions *internalversion.ListOptions) (runtime.Object, error) {\n\t//nolint:staticcheck // SA1019 backwards compatibility\n\tif deleteOptions.PropagationPolicy == nil \u0026\u0026 deleteOptions.OrphanDependents == nil \u0026\u0026\n\t\tjob.Strategy.DefaultGarbageCollectionPolicy(ctx) == rest.OrphanDependents {\n\t\t// Throw a warning if delete options are not explicitly set as Job deletion strategy by default is orphaning\n\t\t// pods in v1.\n\t\twarning.AddWarning(ctx, \"\", deleteOptionWarnings)\n\t}\n\treturn r.Store.DeleteCollection(ctx, deleteValidation, deleteOptions, listOptions)\n}","line":{"from":112,"to":121}} {"id":100009192,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"pkg/registry/batch/job/storage/storage.go","code":"// New creates a new Job object.\nfunc (r *StatusREST) New() runtime.Object {\n\treturn \u0026batch.Job{}\n}","line":{"from":128,"to":131}} {"id":100009193,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"pkg/registry/batch/job/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":133,"to":137}} {"id":100009194,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/batch/job/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":139,"to":142}} {"id":100009195,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/batch/job/storage/storage.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":144,"to":149}} {"id":100009196,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/batch/job/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":151,"to":154}} {"id":100009197,"name":"ConvertToTable","signature":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/batch/job/storage/storage.go","code":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":156,"to":158}} {"id":100009198,"name":"DefaultGarbageCollectionPolicy","signature":"func (jobStrategy) DefaultGarbageCollectionPolicy(ctx context.Context) rest.GarbageCollectionPolicy","file":"pkg/registry/batch/job/strategy.go","code":"// DefaultGarbageCollectionPolicy returns OrphanDependents for batch/v1 for backwards compatibility,\n// and DeleteDependents for all other versions.\nfunc (jobStrategy) DefaultGarbageCollectionPolicy(ctx context.Context) rest.GarbageCollectionPolicy {\n\tvar groupVersion schema.GroupVersion\n\tif requestInfo, found := genericapirequest.RequestInfoFrom(ctx); found {\n\t\tgroupVersion = schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}\n\t}\n\tswitch groupVersion {\n\tcase batchv1.SchemeGroupVersion:\n\t\t// for back compatibility\n\t\treturn rest.OrphanDependents\n\tdefault:\n\t\treturn rest.DeleteDependents\n\t}\n}","line":{"from":58,"to":72}} {"id":100009199,"name":"NamespaceScoped","signature":"func (jobStrategy) NamespaceScoped() bool","file":"pkg/registry/batch/job/strategy.go","code":"// NamespaceScoped returns true because all jobs need to be within a namespace.\nfunc (jobStrategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":74,"to":77}} {"id":100009200,"name":"GetResetFields","signature":"func (jobStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/batch/job/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (jobStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"batch/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":79,"to":89}} {"id":100009201,"name":"PrepareForCreate","signature":"func (jobStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/batch/job/strategy.go","code":"// PrepareForCreate clears the status of a job before creation.\nfunc (jobStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tjob := obj.(*batch.Job)\n\tjob.Status = batch.JobStatus{}\n\n\tjob.Generation = 1\n\n\t// While legacy tracking is supported, we use an annotation to mark whether\n\t// jobs are tracked with finalizers.\n\taddJobTrackingAnnotation(job)\n\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.JobPodFailurePolicy) {\n\t\tjob.Spec.PodFailurePolicy = nil\n\t}\n\n\tpod.DropDisabledTemplateFields(\u0026job.Spec.Template, nil)\n}","line":{"from":91,"to":107}} {"id":100009202,"name":"addJobTrackingAnnotation","signature":"func addJobTrackingAnnotation(job *batch.Job)","file":"pkg/registry/batch/job/strategy.go","code":"func addJobTrackingAnnotation(job *batch.Job) {\n\tif job.Annotations == nil {\n\t\tjob.Annotations = map[string]string{}\n\t}\n\tjob.Annotations[batchv1.JobTrackingFinalizer] = \"\"\n}","line":{"from":109,"to":114}} {"id":100009203,"name":"hasJobTrackingAnnotation","signature":"func hasJobTrackingAnnotation(job *batch.Job) bool","file":"pkg/registry/batch/job/strategy.go","code":"func hasJobTrackingAnnotation(job *batch.Job) bool {\n\tif job.Annotations == nil {\n\t\treturn false\n\t}\n\t_, ok := job.Annotations[batchv1.JobTrackingFinalizer]\n\treturn ok\n}","line":{"from":116,"to":122}} {"id":100009204,"name":"PrepareForUpdate","signature":"func (jobStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/batch/job/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (jobStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewJob := obj.(*batch.Job)\n\toldJob := old.(*batch.Job)\n\tnewJob.Status = oldJob.Status\n\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.JobPodFailurePolicy) \u0026\u0026 oldJob.Spec.PodFailurePolicy == nil {\n\t\tnewJob.Spec.PodFailurePolicy = nil\n\t}\n\n\tpod.DropDisabledTemplateFields(\u0026newJob.Spec.Template, \u0026oldJob.Spec.Template)\n\n\t// Any changes to the spec increment the generation number.\n\t// See metav1.ObjectMeta description for more information on Generation.\n\tif !apiequality.Semantic.DeepEqual(newJob.Spec, oldJob.Spec) {\n\t\tnewJob.Generation = oldJob.Generation + 1\n\t}\n\n\t// While legacy tracking is supported, we use an annotation to mark whether\n\t// jobs are tracked with finalizers. This annotation cannot be removed by\n\t// users.\n\tif hasJobTrackingAnnotation(oldJob) {\n\t\taddJobTrackingAnnotation(newJob)\n\t}\n}","line":{"from":124,"to":148}} {"id":100009205,"name":"Validate","signature":"func (jobStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/batch/job/strategy.go","code":"// Validate validates a new job.\nfunc (jobStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tjob := obj.(*batch.Job)\n\t// TODO: move UID generation earlier and do this in defaulting logic?\n\tif job.Spec.ManualSelector == nil || *job.Spec.ManualSelector == false {\n\t\tgenerateSelector(job)\n\t}\n\topts := validationOptionsForJob(job, nil)\n\treturn batchvalidation.ValidateJob(job, opts)\n}","line":{"from":150,"to":159}} {"id":100009206,"name":"validationOptionsForJob","signature":"func validationOptionsForJob(newJob, oldJob *batch.Job) batchvalidation.JobValidationOptions","file":"pkg/registry/batch/job/strategy.go","code":"func validationOptionsForJob(newJob, oldJob *batch.Job) batchvalidation.JobValidationOptions {\n\tvar newPodTemplate, oldPodTemplate *core.PodTemplateSpec\n\tif newJob != nil {\n\t\tnewPodTemplate = \u0026newJob.Spec.Template\n\t}\n\tif oldJob != nil {\n\t\toldPodTemplate = \u0026oldJob.Spec.Template\n\t}\n\topts := batchvalidation.JobValidationOptions{\n\t\tPodValidationOptions: pod.GetValidationOptionsFromPodTemplate(newPodTemplate, oldPodTemplate),\n\t\tAllowTrackingAnnotation: true,\n\t\tAllowElasticIndexedJobs: utilfeature.DefaultFeatureGate.Enabled(features.ElasticIndexedJob),\n\t\tRequirePrefixedLabels: true,\n\t}\n\tif oldJob != nil {\n\t\topts.AllowInvalidLabelValueInSelector = opts.AllowInvalidLabelValueInSelector || metav1validation.LabelSelectorHasInvalidLabelValue(oldJob.Spec.Selector)\n\n\t\t// Because we don't support the tracking with finalizers for already\n\t\t// existing jobs, we allow the annotation only if the Job already had it,\n\t\t// regardless of the feature gate.\n\t\topts.AllowTrackingAnnotation = hasJobTrackingAnnotation(oldJob)\n\n\t\t// Updating node affinity, node selector and tolerations is allowed\n\t\t// only for suspended jobs that never started before.\n\t\tsuspended := oldJob.Spec.Suspend != nil \u0026\u0026 *oldJob.Spec.Suspend\n\t\tnotStarted := oldJob.Status.StartTime == nil\n\t\topts.AllowMutableSchedulingDirectives = suspended \u0026\u0026 notStarted\n\n\t\t// Validation should not fail jobs if they don't have the new labels.\n\t\t// This can be removed once we have high confidence that both labels exist (1.30 at least)\n\t\t_, hadJobName := oldJob.Spec.Template.Labels[batch.JobNameLabel]\n\t\t_, hadControllerUid := oldJob.Spec.Template.Labels[batch.ControllerUidLabel]\n\t\topts.RequirePrefixedLabels = hadJobName \u0026\u0026 hadControllerUid\n\t}\n\treturn opts\n}","line":{"from":161,"to":196}} {"id":100009207,"name":"WarningsOnCreate","signature":"func (jobStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/batch/job/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (jobStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\tnewJob := obj.(*batch.Job)\n\tvar warnings []string\n\tif msgs := utilvalidation.IsDNS1123Label(newJob.Name); len(msgs) != 0 {\n\t\twarnings = append(warnings, fmt.Sprintf(\"metadata.name: this is used in Pod names and hostnames, which can result in surprising behavior; a DNS label is recommended: %v\", msgs))\n\t}\n\twarnings = append(warnings, pod.GetWarningsForPodTemplate(ctx, field.NewPath(\"spec\", \"template\"), \u0026newJob.Spec.Template, nil)...)\n\treturn warnings\n}","line":{"from":198,"to":207}} {"id":100009208,"name":"generateSelector","signature":"func generateSelector(obj *batch.Job)","file":"pkg/registry/batch/job/strategy.go","code":"// generateSelector adds a selector to a job and labels to its template\n// which can be used to uniquely identify the pods created by that job,\n// if the user has requested this behavior.\nfunc generateSelector(obj *batch.Job) {\n\tif obj.Spec.Template.Labels == nil {\n\t\tobj.Spec.Template.Labels = make(map[string]string)\n\t}\n\t// The job-name label is unique except in cases that are expected to be\n\t// quite uncommon, and is more user friendly than uid. So, we add it as\n\t// a label.\n\tjobNameLabels := []string{batch.LegacyJobNameLabel, batch.JobNameLabel}\n\tfor _, value := range jobNameLabels {\n\t\t_, found := obj.Spec.Template.Labels[value]\n\t\tif found {\n\t\t\t// User asked us to automatically generate a selector, but set manual labels.\n\t\t\t// If there is a conflict, we will reject in validation.\n\t\t} else {\n\t\t\tobj.Spec.Template.Labels[value] = string(obj.ObjectMeta.Name)\n\t\t}\n\t}\n\n\t// The controller-uid label makes the pods that belong to this job\n\t// only match this job.\n\tcontrollerUidLabels := []string{batch.LegacyControllerUidLabel, batch.ControllerUidLabel}\n\tfor _, value := range controllerUidLabels {\n\t\t_, found := obj.Spec.Template.Labels[value]\n\t\tif found {\n\t\t\t// User asked us to automatically generate a selector, but set manual labels.\n\t\t\t// If there is a conflict, we will reject in validation.\n\t\t} else {\n\t\t\tobj.Spec.Template.Labels[value] = string(obj.ObjectMeta.UID)\n\t\t}\n\t}\n\t// Select the controller-uid label. This is sufficient for uniqueness.\n\tif obj.Spec.Selector == nil {\n\t\tobj.Spec.Selector = \u0026metav1.LabelSelector{}\n\t}\n\tif obj.Spec.Selector.MatchLabels == nil {\n\t\tobj.Spec.Selector.MatchLabels = make(map[string]string)\n\t}\n\n\tif _, found := obj.Spec.Selector.MatchLabels[batch.ControllerUidLabel]; !found {\n\t\tobj.Spec.Selector.MatchLabels[batch.ControllerUidLabel] = string(obj.ObjectMeta.UID)\n\t}\n\t// If the user specified matchLabel controller-uid=$WRONGUID, then it should fail\n\t// in validation, either because the selector does not match the pod template\n\t// (controller-uid=$WRONGUID does not match controller-uid=$UID, which we applied\n\t// above, or we will reject in validation because the template has the wrong\n\t// labels.\n}","line":{"from":209,"to":258}} {"id":100009209,"name":"Canonicalize","signature":"func (jobStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/batch/job/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (jobStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":265,"to":267}} {"id":100009210,"name":"AllowUnconditionalUpdate","signature":"func (jobStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/batch/job/strategy.go","code":"func (jobStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":269,"to":271}} {"id":100009211,"name":"AllowCreateOnUpdate","signature":"func (jobStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/batch/job/strategy.go","code":"// AllowCreateOnUpdate is false for jobs; this means a POST is needed to create one.\nfunc (jobStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":273,"to":276}} {"id":100009212,"name":"ValidateUpdate","signature":"func (jobStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/batch/job/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (jobStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tjob := obj.(*batch.Job)\n\toldJob := old.(*batch.Job)\n\n\topts := validationOptionsForJob(job, oldJob)\n\tvalidationErrorList := batchvalidation.ValidateJob(job, opts)\n\tupdateErrorList := batchvalidation.ValidateJobUpdate(job, oldJob, opts)\n\treturn append(validationErrorList, updateErrorList...)\n}","line":{"from":278,"to":287}} {"id":100009213,"name":"WarningsOnUpdate","signature":"func (jobStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/batch/job/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (jobStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\tvar warnings []string\n\tnewJob := obj.(*batch.Job)\n\toldJob := old.(*batch.Job)\n\tif newJob.Generation != oldJob.Generation {\n\t\twarnings = pod.GetWarningsForPodTemplate(ctx, field.NewPath(\"spec\", \"template\"), \u0026newJob.Spec.Template, \u0026oldJob.Spec.Template)\n\t}\n\treturn warnings\n}","line":{"from":289,"to":298}} {"id":100009214,"name":"GetResetFields","signature":"func (jobStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/batch/job/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (jobStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"batch/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t}\n}","line":{"from":306,"to":314}} {"id":100009215,"name":"PrepareForUpdate","signature":"func (jobStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/batch/job/strategy.go","code":"func (jobStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewJob := obj.(*batch.Job)\n\toldJob := old.(*batch.Job)\n\tnewJob.Spec = oldJob.Spec\n}","line":{"from":316,"to":320}} {"id":100009216,"name":"ValidateUpdate","signature":"func (jobStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/batch/job/strategy.go","code":"func (jobStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn batchvalidation.ValidateJobUpdateStatus(obj.(*batch.Job), old.(*batch.Job))\n}","line":{"from":322,"to":324}} {"id":100009217,"name":"WarningsOnUpdate","signature":"func (jobStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/batch/job/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (jobStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":326,"to":329}} {"id":100009218,"name":"JobToSelectableFields","signature":"func JobToSelectableFields(job *batch.Job) fields.Set","file":"pkg/registry/batch/job/strategy.go","code":"// JobSelectableFields returns a field set that represents the object for matching purposes.\nfunc JobToSelectableFields(job *batch.Job) fields.Set {\n\tobjectMetaFieldsSet := generic.ObjectMetaFieldsSet(\u0026job.ObjectMeta, true)\n\tspecificFieldsSet := fields.Set{\n\t\t\"status.successful\": strconv.Itoa(int(job.Status.Succeeded)),\n\t}\n\treturn generic.MergeFieldsSets(objectMetaFieldsSet, specificFieldsSet)\n}","line":{"from":331,"to":338}} {"id":100009219,"name":"GetAttrs","signature":"func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error)","file":"pkg/registry/batch/job/strategy.go","code":"// GetAttrs returns labels and fields of a given object for filtering purposes.\nfunc GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {\n\tjob, ok := obj.(*batch.Job)\n\tif !ok {\n\t\treturn nil, nil, fmt.Errorf(\"given object is not a job.\")\n\t}\n\treturn labels.Set(job.ObjectMeta.Labels), JobToSelectableFields(job), nil\n}","line":{"from":340,"to":347}} {"id":100009220,"name":"MatchJob","signature":"func MatchJob(label labels.Selector, field fields.Selector) storage.SelectionPredicate","file":"pkg/registry/batch/job/strategy.go","code":"// MatchJob is the filter used by the generic etcd backend to route\n// watch events from etcd to clients of the apiserver only interested in specific\n// labels/fields.\nfunc MatchJob(label labels.Selector, field fields.Selector) storage.SelectionPredicate {\n\treturn storage.SelectionPredicate{\n\t\tLabel: label,\n\t\tField: field,\n\t\tGetAttrs: GetAttrs,\n\t}\n}","line":{"from":349,"to":358}} {"id":100009221,"name":"NewRESTStorage","signature":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error)","file":"pkg/registry/batch/rest/storage_batch.go","code":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error) {\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(batch.GroupName, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs)\n\t// If you add a version here, be sure to add an entry in `k8s.io/kubernetes/cmd/kube-apiserver/app/aggregator.go with specific priorities.\n\t// TODO refactor the plumbing to provide the information in the APIGroupInfo\n\n\tif storageMap, err := p.v1Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[batchapiv1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\tif storageMap, err := p.v1beta1Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[batchapiv1beta1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\treturn apiGroupInfo, nil\n}","line":{"from":34,"to":52}} {"id":100009222,"name":"v1Storage","signature":"func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/batch/rest/storage_batch.go","code":"func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\t// jobs\n\tif resource := \"jobs\"; apiResourceConfigSource.ResourceEnabled(batchapiv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tjobsStorage, jobsStatusStorage, err := jobstore.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = jobsStorage\n\t\tstorage[resource+\"/status\"] = jobsStatusStorage\n\t}\n\n\t// cronjobs\n\tif resource := \"cronjobs\"; apiResourceConfigSource.ResourceEnabled(batchapiv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tcronJobsStorage, cronJobsStatusStorage, err := cronjobstore.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = cronJobsStorage\n\t\tstorage[resource+\"/status\"] = cronJobsStatusStorage\n\t}\n\treturn storage, nil\n}","line":{"from":54,"to":77}} {"id":100009223,"name":"v1beta1Storage","signature":"func (p RESTStorageProvider) v1beta1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/batch/rest/storage_batch.go","code":"func (p RESTStorageProvider) v1beta1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\t// cronjobs\n\tif resource := \"cronjobs\"; apiResourceConfigSource.ResourceEnabled(batchapiv1beta1.SchemeGroupVersion.WithResource(resource)) {\n\t\tcronJobsStorage, cronJobsStatusStorage, err := cronjobstore.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = cronJobsStorage\n\t\tstorage[resource+\"/status\"] = cronJobsStatusStorage\n\t}\n\n\treturn storage, nil\n}","line":{"from":79,"to":93}} {"id":100009224,"name":"GroupName","signature":"func (p RESTStorageProvider) GroupName() string","file":"pkg/registry/batch/rest/storage_batch.go","code":"func (p RESTStorageProvider) GroupName() string {\n\treturn batch.GroupName\n}","line":{"from":95,"to":97}} {"id":100009225,"name":"init","signature":"func init()","file":"pkg/registry/certificates/certificates/storage/metrics.go","code":"func init() {\n\tregisterMetricsOnce.Do(func() {\n\t\tlegacyregistry.MustRegister(csrDurationRequested)\n\t\tlegacyregistry.MustRegister(csrDurationHonored)\n\t})\n}","line":{"from":69,"to":74}} {"id":100009226,"name":"countCSRDurationMetric","signature":"func countCSRDurationMetric(requested, honored counterVecMetric) genericregistry.BeginUpdateFunc","file":"pkg/registry/certificates/certificates/storage/metrics.go","code":"func countCSRDurationMetric(requested, honored counterVecMetric) genericregistry.BeginUpdateFunc {\n\treturn func(ctx context.Context, obj, old runtime.Object, options *metav1.UpdateOptions) (genericregistry.FinishFunc, error) {\n\t\treturn func(ctx context.Context, success bool) {\n\t\t\tif !success {\n\t\t\t\treturn // ignore failures\n\t\t\t}\n\n\t\t\tif dryrun.IsDryRun(options.DryRun) {\n\t\t\t\treturn // ignore things that would not get persisted\n\t\t\t}\n\n\t\t\toldCSR, ok := old.(*certificates.CertificateSigningRequest)\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// if the old CSR already has a certificate, do not double count it\n\t\t\tif len(oldCSR.Status.Certificate) \u003e 0 {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif oldCSR.Spec.ExpirationSeconds == nil {\n\t\t\t\treturn // ignore CSRs that are not using the CSR duration feature\n\t\t\t}\n\n\t\t\tnewCSR, ok := obj.(*certificates.CertificateSigningRequest)\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tissuedCert := newCSR.Status.Certificate\n\n\t\t\t// new CSR has no issued certificate yet so do not count it.\n\t\t\t// note that this means that we will ignore CSRs that set a duration\n\t\t\t// but never get approved/signed. this is fine because the point\n\t\t\t// of these metrics is to understand if the duration is honored\n\t\t\t// by the signer. we are not checking the behavior of the approver.\n\t\t\tif len(issuedCert) == 0 {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tsigner := compressSignerName(oldCSR.Spec.SignerName)\n\n\t\t\t// at this point we know that this CSR is going to be persisted and\n\t\t\t// the cert was just issued and the client requested a duration\n\t\t\trequested.WithLabelValues(signer).Inc()\n\n\t\t\tcerts, err := cert.ParseCertsPEM(issuedCert)\n\t\t\tif err != nil {\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"metrics recording failed to parse certificate for CSR %s: %w\", oldCSR.Name, err))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// now we check to see if the signer honored the requested duration\n\t\t\tcertificate := certs[0]\n\t\t\twantDuration := csr.ExpirationSecondsToDuration(*oldCSR.Spec.ExpirationSeconds)\n\t\t\tactualDuration := certificate.NotAfter.Sub(certificate.NotBefore)\n\t\t\tif isDurationHonored(wantDuration, actualDuration) {\n\t\t\t\thonored.WithLabelValues(signer).Inc()\n\t\t\t}\n\t\t}, nil\n\t}\n}","line":{"from":82,"to":143}} {"id":100009227,"name":"isDurationHonored","signature":"func isDurationHonored(want, got time.Duration) bool","file":"pkg/registry/certificates/certificates/storage/metrics.go","code":"func isDurationHonored(want, got time.Duration) bool {\n\tdelta := want - got\n\tif delta \u003c 0 {\n\t\tdelta = -delta\n\t}\n\n\t// short-lived cert backdating + 5% of want\n\tmaxDelta := 5*time.Minute + (want / 20)\n\n\treturn delta \u003c maxDelta\n}","line":{"from":145,"to":155}} {"id":100009228,"name":"compressSignerName","signature":"func compressSignerName(name string) string","file":"pkg/registry/certificates/certificates/storage/metrics.go","code":"func compressSignerName(name string) string {\n\tif strings.HasPrefix(name, \"kubernetes.io/\") {\n\t\treturn name\n\t}\n\n\treturn \"other\"\n}","line":{"from":157,"to":163}} {"id":100009229,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, *ApprovalREST, error)","file":"pkg/registry/certificates/certificates/storage/storage.go","code":"// NewREST returns a registry which will store CertificateSigningRequest in the given helper.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, *ApprovalREST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026certificates.CertificateSigningRequest{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026certificates.CertificateSigningRequestList{} },\n\t\tDefaultQualifiedResource: certificates.Resource(\"certificatesigningrequests\"),\n\t\tSingularQualifiedResource: certificates.Resource(\"certificatesigningrequest\"),\n\n\t\tCreateStrategy: csrregistry.Strategy,\n\t\tUpdateStrategy: csrregistry.Strategy,\n\t\tDeleteStrategy: csrregistry.Strategy,\n\t\tResetFieldsStrategy: csrregistry.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: csrregistry.GetAttrs}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// Subresources use the same store and creation strategy, which only\n\t// allows empty subs. Updates to an existing subresource are handled by\n\t// dedicated strategies.\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = csrregistry.StatusStrategy\n\tstatusStore.ResetFieldsStrategy = csrregistry.StatusStrategy\n\tstatusStore.BeginUpdate = countCSRDurationMetric(csrDurationRequested, csrDurationHonored)\n\n\tapprovalStore := *store\n\tapprovalStore.UpdateStrategy = csrregistry.ApprovalStrategy\n\tapprovalStore.ResetFieldsStrategy = csrregistry.ApprovalStrategy\n\n\treturn \u0026REST{store}, \u0026StatusREST{store: \u0026statusStore}, \u0026ApprovalREST{store: \u0026approvalStore}, nil\n}","line":{"from":40,"to":73}} {"id":100009230,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/certificates/certificates/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"csr\"}\n}","line":{"from":78,"to":81}} {"id":100009231,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"pkg/registry/certificates/certificates/storage/storage.go","code":"// New creates a new CertificateSigningRequest object.\nfunc (r *StatusREST) New() runtime.Object {\n\treturn \u0026certificates.CertificateSigningRequest{}\n}","line":{"from":88,"to":91}} {"id":100009232,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"pkg/registry/certificates/certificates/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":93,"to":97}} {"id":100009233,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/certificates/certificates/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":99,"to":102}} {"id":100009234,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/certificates/certificates/storage/storage.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":104,"to":109}} {"id":100009235,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/certificates/certificates/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":111,"to":114}} {"id":100009236,"name":"ConvertToTable","signature":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/certificates/certificates/storage/storage.go","code":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":116,"to":118}} {"id":100009237,"name":"New","signature":"func (r *ApprovalREST) New() runtime.Object","file":"pkg/registry/certificates/certificates/storage/storage.go","code":"// New creates a new CertificateSigningRequest object.\nfunc (r *ApprovalREST) New() runtime.Object {\n\treturn \u0026certificates.CertificateSigningRequest{}\n}","line":{"from":127,"to":130}} {"id":100009238,"name":"Destroy","signature":"func (r *ApprovalREST) Destroy()","file":"pkg/registry/certificates/certificates/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *ApprovalREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":132,"to":136}} {"id":100009239,"name":"Get","signature":"func (r *ApprovalREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/certificates/certificates/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *ApprovalREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":138,"to":141}} {"id":100009240,"name":"Update","signature":"func (r *ApprovalREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/certificates/certificates/storage/storage.go","code":"// Update alters the approval subset of an object.\nfunc (r *ApprovalREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":143,"to":148}} {"id":100009241,"name":"GetResetFields","signature":"func (r *ApprovalREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/certificates/certificates/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *ApprovalREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":150,"to":153}} {"id":100009242,"name":"NamespaceScoped","signature":"func (csrStrategy) NamespaceScoped() bool","file":"pkg/registry/certificates/certificates/strategy.go","code":"// NamespaceScoped is false for CSRs.\nfunc (csrStrategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":47,"to":50}} {"id":100009243,"name":"GetResetFields","signature":"func (csrStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/certificates/certificates/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (csrStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"certificates.k8s.io/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t\t\"certificates.k8s.io/v1beta1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":52,"to":67}} {"id":100009244,"name":"AllowCreateOnUpdate","signature":"func (csrStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/certificates/certificates/strategy.go","code":"// AllowCreateOnUpdate is false for CSRs.\nfunc (csrStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":69,"to":72}} {"id":100009245,"name":"PrepareForCreate","signature":"func (csrStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/certificates/certificates/strategy.go","code":"// PrepareForCreate clears fields that are not allowed to be set by end users\n// on creation.\nfunc (csrStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tcsr := obj.(*certificates.CertificateSigningRequest)\n\n\t// Clear any user-specified info\n\tcsr.Spec.Username = \"\"\n\tcsr.Spec.UID = \"\"\n\tcsr.Spec.Groups = nil\n\tcsr.Spec.Extra = nil\n\t// Inject user.Info from request context\n\tif user, ok := genericapirequest.UserFrom(ctx); ok {\n\t\tcsr.Spec.Username = user.GetName()\n\t\tcsr.Spec.UID = user.GetUID()\n\t\tcsr.Spec.Groups = user.GetGroups()\n\t\tif extra := user.GetExtra(); len(extra) \u003e 0 {\n\t\t\tcsr.Spec.Extra = map[string]certificates.ExtraValue{}\n\t\t\tfor k, v := range extra {\n\t\t\t\tcsr.Spec.Extra[k] = v\n\t\t\t}\n\t\t}\n\t}\n\n\t// Be explicit that users cannot create pre-approved certificate requests.\n\tcsr.Status = certificates.CertificateSigningRequestStatus{}\n\tcsr.Status.Conditions = []certificates.CertificateSigningRequestCondition{}\n}","line":{"from":74,"to":100}} {"id":100009246,"name":"PrepareForUpdate","signature":"func (csrStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/certificates/certificates/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users\n// on update. Certificate requests are immutable after creation except via subresources.\nfunc (csrStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewCSR := obj.(*certificates.CertificateSigningRequest)\n\toldCSR := old.(*certificates.CertificateSigningRequest)\n\n\tnewCSR.Spec = oldCSR.Spec\n\tnewCSR.Status = oldCSR.Status\n}","line":{"from":102,"to":110}} {"id":100009247,"name":"Validate","signature":"func (csrStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/certificates/certificates/strategy.go","code":"// Validate validates a new CSR. Validation must check for a correct signature.\nfunc (csrStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tcsr := obj.(*certificates.CertificateSigningRequest)\n\treturn validation.ValidateCertificateSigningRequestCreate(csr)\n}","line":{"from":112,"to":116}} {"id":100009248,"name":"WarningsOnCreate","signature":"func (csrStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return nil }","file":"pkg/registry/certificates/certificates/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (csrStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return nil }","line":{"from":118,"to":119}} {"id":100009249,"name":"Canonicalize","signature":"func (csrStrategy) Canonicalize(obj runtime.Object) {}","file":"pkg/registry/certificates/certificates/strategy.go","code":"// Canonicalize normalizes the object after validation (which includes a signature check).\nfunc (csrStrategy) Canonicalize(obj runtime.Object) {}","line":{"from":121,"to":122}} {"id":100009250,"name":"ValidateUpdate","signature":"func (csrStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/certificates/certificates/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (csrStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\toldCSR := old.(*certificates.CertificateSigningRequest)\n\tnewCSR := obj.(*certificates.CertificateSigningRequest)\n\treturn validation.ValidateCertificateSigningRequestUpdate(newCSR, oldCSR)\n}","line":{"from":124,"to":129}} {"id":100009251,"name":"WarningsOnUpdate","signature":"func (csrStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/certificates/certificates/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (csrStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":131,"to":134}} {"id":100009252,"name":"AllowUnconditionalUpdate","signature":"func (csrStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/certificates/certificates/strategy.go","code":"// If AllowUnconditionalUpdate() is true and the object specified by\n// the user does not have a resource version, then generic Update()\n// populates it with the latest version. Else, it checks that the\n// version specified by the user matches the version of latest etcd\n// object.\nfunc (csrStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":136,"to":143}} {"id":100009253,"name":"GetResetFields","signature":"func (csrStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/certificates/certificates/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (csrStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"certificates.k8s.io/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t\tfieldpath.MakePathOrDie(\"status\", \"conditions\"),\n\t\t),\n\t\t\"certificates.k8s.io/v1beta1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t\tfieldpath.MakePathOrDie(\"status\", \"conditions\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":152,"to":167}} {"id":100009254,"name":"PrepareForUpdate","signature":"func (csrStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/certificates/certificates/strategy.go","code":"func (csrStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewCSR := obj.(*certificates.CertificateSigningRequest)\n\toldCSR := old.(*certificates.CertificateSigningRequest)\n\n\t// Updating /status should not modify spec\n\tnewCSR.Spec = oldCSR.Spec\n\n\t// Specifically preserve existing Approved/Denied conditions.\n\t// Adding/removing Approved/Denied conditions will cause these to fail,\n\t// and the change in Approved/Denied conditions will produce a validation error\n\tpreserveConditionInstances(newCSR, oldCSR, certificates.CertificateApproved)\n\tpreserveConditionInstances(newCSR, oldCSR, certificates.CertificateDenied)\n\n\tpopulateConditionTimestamps(newCSR, oldCSR)\n}","line":{"from":169,"to":183}} {"id":100009255,"name":"preserveConditionInstances","signature":"func preserveConditionInstances(newCSR, oldCSR *certificates.CertificateSigningRequest, conditionType certificates.RequestConditionType) bool","file":"pkg/registry/certificates/certificates/strategy.go","code":"// preserveConditionInstances copies instances of the specified condition type from oldCSR to newCSR.\n// or returns false if the newCSR added or removed instances\nfunc preserveConditionInstances(newCSR, oldCSR *certificates.CertificateSigningRequest, conditionType certificates.RequestConditionType) bool {\n\toldIndices := findConditionIndices(oldCSR, conditionType)\n\tnewIndices := findConditionIndices(newCSR, conditionType)\n\tif len(oldIndices) != len(newIndices) {\n\t\t// instances were added or removed, we cannot preserve the existing values\n\t\treturn false\n\t}\n\t// preserve the old condition values\n\tfor i, oldIndex := range oldIndices {\n\t\tnewCSR.Status.Conditions[newIndices[i]] = oldCSR.Status.Conditions[oldIndex]\n\t}\n\treturn true\n}","line":{"from":185,"to":199}} {"id":100009256,"name":"findConditionIndices","signature":"func findConditionIndices(csr *certificates.CertificateSigningRequest, conditionType certificates.RequestConditionType) []int","file":"pkg/registry/certificates/certificates/strategy.go","code":"// findConditionIndices returns the indices of instances of the specified condition type\nfunc findConditionIndices(csr *certificates.CertificateSigningRequest, conditionType certificates.RequestConditionType) []int {\n\tvar retval []int\n\tfor i, c := range csr.Status.Conditions {\n\t\tif c.Type == conditionType {\n\t\t\tretval = append(retval, i)\n\t\t}\n\t}\n\treturn retval\n}","line":{"from":201,"to":210}} {"id":100009257,"name":"populateConditionTimestamps","signature":"func populateConditionTimestamps(newCSR, oldCSR *certificates.CertificateSigningRequest)","file":"pkg/registry/certificates/certificates/strategy.go","code":"// populateConditionTimestamps sets LastUpdateTime and LastTransitionTime in newCSR if missing\nfunc populateConditionTimestamps(newCSR, oldCSR *certificates.CertificateSigningRequest) {\n\tnow := nowFunc()\n\tfor i := range newCSR.Status.Conditions {\n\t\tif newCSR.Status.Conditions[i].LastUpdateTime.IsZero() {\n\t\t\tnewCSR.Status.Conditions[i].LastUpdateTime = now\n\t\t}\n\n\t\t// preserve existing lastTransitionTime if the condition with this type/status already exists,\n\t\t// otherwise set to now.\n\t\tif newCSR.Status.Conditions[i].LastTransitionTime.IsZero() {\n\t\t\tlastTransition := now\n\t\t\tfor _, oldCondition := range oldCSR.Status.Conditions {\n\t\t\t\tif oldCondition.Type == newCSR.Status.Conditions[i].Type \u0026\u0026\n\t\t\t\t\toldCondition.Status == newCSR.Status.Conditions[i].Status \u0026\u0026\n\t\t\t\t\t!oldCondition.LastTransitionTime.IsZero() {\n\t\t\t\t\tlastTransition = oldCondition.LastTransitionTime\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tnewCSR.Status.Conditions[i].LastTransitionTime = lastTransition\n\t\t}\n\t}\n}","line":{"from":215,"to":238}} {"id":100009258,"name":"ValidateUpdate","signature":"func (csrStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/certificates/certificates/strategy.go","code":"func (csrStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateCertificateSigningRequestStatusUpdate(obj.(*certificates.CertificateSigningRequest), old.(*certificates.CertificateSigningRequest))\n}","line":{"from":240,"to":242}} {"id":100009259,"name":"WarningsOnUpdate","signature":"func (csrStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/certificates/certificates/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (csrStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":244,"to":247}} {"id":100009260,"name":"Canonicalize","signature":"func (csrStatusStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/certificates/certificates/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (csrStatusStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":249,"to":251}} {"id":100009261,"name":"GetResetFields","signature":"func (csrApprovalStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/certificates/certificates/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (csrApprovalStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"certificates.k8s.io/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t\tfieldpath.MakePathOrDie(\"status\", \"certificate\"),\n\t\t),\n\t\t\"certificates.k8s.io/v1beta1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t\tfieldpath.MakePathOrDie(\"status\", \"certificate\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":260,"to":275}} {"id":100009262,"name":"PrepareForUpdate","signature":"func (csrApprovalStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/certificates/certificates/strategy.go","code":"// PrepareForUpdate prepares the new certificate signing request by limiting\n// the data that is updated to only the conditions and populating condition timestamps\nfunc (csrApprovalStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewCSR := obj.(*certificates.CertificateSigningRequest)\n\toldCSR := old.(*certificates.CertificateSigningRequest)\n\n\tpopulateConditionTimestamps(newCSR, oldCSR)\n\tnewConditions := newCSR.Status.Conditions\n\n\t// Updating the approval should only update the conditions.\n\tnewCSR.Spec = oldCSR.Spec\n\tnewCSR.Status = oldCSR.Status\n\tnewCSR.Status.Conditions = newConditions\n}","line":{"from":277,"to":290}} {"id":100009263,"name":"ValidateUpdate","signature":"func (csrApprovalStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/certificates/certificates/strategy.go","code":"func (csrApprovalStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateCertificateSigningRequestApprovalUpdate(obj.(*certificates.CertificateSigningRequest), old.(*certificates.CertificateSigningRequest))\n}","line":{"from":292,"to":294}} {"id":100009264,"name":"WarningsOnUpdate","signature":"func (csrApprovalStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/certificates/certificates/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (csrApprovalStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":296,"to":299}} {"id":100009265,"name":"GetAttrs","signature":"func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error)","file":"pkg/registry/certificates/certificates/strategy.go","code":"// GetAttrs returns labels and fields of a given object for filtering purposes.\nfunc GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {\n\tcsr, ok := obj.(*certificates.CertificateSigningRequest)\n\tif !ok {\n\t\treturn nil, nil, fmt.Errorf(\"not a certificatesigningrequest\")\n\t}\n\treturn labels.Set(csr.Labels), SelectableFields(csr), nil\n}","line":{"from":301,"to":308}} {"id":100009266,"name":"SelectableFields","signature":"func SelectableFields(obj *certificates.CertificateSigningRequest) fields.Set","file":"pkg/registry/certificates/certificates/strategy.go","code":"// SelectableFields returns a field set that can be used for filter selection\nfunc SelectableFields(obj *certificates.CertificateSigningRequest) fields.Set {\n\tobjectMetaFieldsSet := generic.ObjectMetaFieldsSet(\u0026obj.ObjectMeta, false)\n\tcsrSpecificFieldsSet := fields.Set{\n\t\t\"spec.signerName\": obj.Spec.SignerName,\n\t}\n\treturn generic.MergeFieldsSets(objectMetaFieldsSet, csrSpecificFieldsSet)\n}","line":{"from":310,"to":317}} {"id":100009267,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error)","file":"pkg/registry/certificates/clustertrustbundle/storage/storage.go","code":"// NewREST returns a RESTStorage object for ClusterTrustBundle objects.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026api.ClusterTrustBundle{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026api.ClusterTrustBundleList{} },\n\t\tDefaultQualifiedResource: api.Resource(\"clustertrustbundles\"),\n\t\tSingularQualifiedResource: api.Resource(\"clustertrustbundle\"),\n\n\t\tCreateStrategy: clustertrustbundle.Strategy,\n\t\tUpdateStrategy: clustertrustbundle.Strategy,\n\t\tDeleteStrategy: clustertrustbundle.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{\n\t\tRESTOptions: optsGetter,\n\t\tAttrFunc: getAttrs,\n\t}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026REST{store}, nil\n}","line":{"from":44,"to":66}} {"id":100009268,"name":"getAttrs","signature":"func getAttrs(obj runtime.Object) (labels.Set, fields.Set, error)","file":"pkg/registry/certificates/clustertrustbundle/storage/storage.go","code":"func getAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {\n\tbundle, ok := obj.(*api.ClusterTrustBundle)\n\tif !ok {\n\t\treturn nil, nil, fmt.Errorf(\"not a clustertrustbundle\")\n\t}\n\n\tselectableFields := generic.MergeFieldsSets(generic.ObjectMetaFieldsSet(\u0026bundle.ObjectMeta, false), fields.Set{\n\t\t\"spec.signerName\": bundle.Spec.SignerName,\n\t})\n\n\treturn labels.Set(bundle.Labels), selectableFields, nil\n}","line":{"from":68,"to":79}} {"id":100009269,"name":"NamespaceScoped","signature":"func (strategy) NamespaceScoped() bool","file":"pkg/registry/certificates/clustertrustbundle/strategy.go","code":"func (strategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":46,"to":48}} {"id":100009270,"name":"PrepareForCreate","signature":"func (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {}","file":"pkg/registry/certificates/clustertrustbundle/strategy.go","code":"func (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {}","line":{"from":50,"to":50}} {"id":100009271,"name":"Validate","signature":"func (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/certificates/clustertrustbundle/strategy.go","code":"func (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tbundle := obj.(*certificates.ClusterTrustBundle)\n\treturn certvalidation.ValidateClusterTrustBundle(bundle, certvalidation.ValidateClusterTrustBundleOptions{})\n}","line":{"from":52,"to":55}} {"id":100009272,"name":"WarningsOnCreate","signature":"func (strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/certificates/clustertrustbundle/strategy.go","code":"func (strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":57,"to":59}} {"id":100009273,"name":"Canonicalize","signature":"func (strategy) Canonicalize(obj runtime.Object) {}","file":"pkg/registry/certificates/clustertrustbundle/strategy.go","code":"func (strategy) Canonicalize(obj runtime.Object) {}","line":{"from":61,"to":61}} {"id":100009274,"name":"AllowCreateOnUpdate","signature":"func (strategy) AllowCreateOnUpdate() bool","file":"pkg/registry/certificates/clustertrustbundle/strategy.go","code":"func (strategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":63,"to":65}} {"id":100009275,"name":"PrepareForUpdate","signature":"func (s strategy) PrepareForUpdate(ctx context.Context, new, old runtime.Object) {}","file":"pkg/registry/certificates/clustertrustbundle/strategy.go","code":"func (s strategy) PrepareForUpdate(ctx context.Context, new, old runtime.Object) {}","line":{"from":67,"to":67}} {"id":100009276,"name":"ValidateUpdate","signature":"func (s strategy) ValidateUpdate(ctx context.Context, new, old runtime.Object) field.ErrorList","file":"pkg/registry/certificates/clustertrustbundle/strategy.go","code":"func (s strategy) ValidateUpdate(ctx context.Context, new, old runtime.Object) field.ErrorList {\n\tnewBundle := new.(*certificates.ClusterTrustBundle)\n\toldBundle := old.(*certificates.ClusterTrustBundle)\n\treturn certvalidation.ValidateClusterTrustBundleUpdate(newBundle, oldBundle)\n}","line":{"from":69,"to":73}} {"id":100009277,"name":"WarningsOnUpdate","signature":"func (strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/certificates/clustertrustbundle/strategy.go","code":"func (strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":75,"to":77}} {"id":100009278,"name":"AllowUnconditionalUpdate","signature":"func (strategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/certificates/clustertrustbundle/strategy.go","code":"func (strategy) AllowUnconditionalUpdate() bool {\n\treturn false\n}","line":{"from":79,"to":81}} {"id":100009279,"name":"NewRESTStorage","signature":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error)","file":"pkg/registry/certificates/rest/storage_certificates.go","code":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error) {\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(certificates.GroupName, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs)\n\t// If you add a version here, be sure to add an entry in `k8s.io/kubernetes/cmd/kube-apiserver/app/aggregator.go with specific priorities.\n\t// TODO refactor the plumbing to provide the information in the APIGroupInfo\n\n\tif storageMap, err := p.v1Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[certificatesapiv1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\tif storageMap, err := p.v1alpha1Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[certificatesapiv1alpha1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\treturn apiGroupInfo, nil\n}","line":{"from":37,"to":55}} {"id":100009280,"name":"v1Storage","signature":"func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/certificates/rest/storage_certificates.go","code":"func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\tif resource := \"certificatesigningrequests\"; apiResourceConfigSource.ResourceEnabled(certificatesapiv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tcsrStorage, csrStatusStorage, csrApprovalStorage, err := certificatestore.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstorage[resource] = csrStorage\n\t\tstorage[resource+\"/status\"] = csrStatusStorage\n\t\tstorage[resource+\"/approval\"] = csrApprovalStorage\n\t}\n\n\treturn storage, nil\n}","line":{"from":57,"to":71}} {"id":100009281,"name":"v1alpha1Storage","signature":"func (p RESTStorageProvider) v1alpha1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/certificates/rest/storage_certificates.go","code":"func (p RESTStorageProvider) v1alpha1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\tif resource := \"clustertrustbundles\"; apiResourceConfigSource.ResourceEnabled(certificatesapiv1alpha1.SchemeGroupVersion.WithResource(resource)) {\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.ClusterTrustBundle) {\n\t\t\tbundleStorage, err := clustertrustbundlestore.NewREST(restOptionsGetter)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tstorage[resource] = bundleStorage\n\t\t} else {\n\t\t\tklog.Warning(\"ClusterTrustBundle storage is disabled because the ClusterTrustBundle feature gate is disabled\")\n\t\t}\n\t}\n\n\treturn storage, nil\n}","line":{"from":73,"to":89}} {"id":100009282,"name":"GroupName","signature":"func (p RESTStorageProvider) GroupName() string","file":"pkg/registry/certificates/rest/storage_certificates.go","code":"func (p RESTStorageProvider) GroupName() string {\n\treturn certificates.GroupName\n}","line":{"from":91,"to":93}} {"id":100009283,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error)","file":"pkg/registry/coordination/lease/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against leases.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026coordinationapi.Lease{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026coordinationapi.LeaseList{} },\n\t\tDefaultQualifiedResource: coordinationapi.Resource(\"leases\"),\n\t\tSingularQualifiedResource: coordinationapi.Resource(\"lease\"),\n\n\t\tCreateStrategy: lease.Strategy,\n\t\tUpdateStrategy: lease.Strategy,\n\t\tDeleteStrategy: lease.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026REST{store}, nil\n}","line":{"from":35,"to":55}} {"id":100009284,"name":"NamespaceScoped","signature":"func (leaseStrategy) NamespaceScoped() bool","file":"pkg/registry/coordination/lease/strategy.go","code":"// NamespaceScoped returns true because all Lease' need to be within a namespace.\nfunc (leaseStrategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":39,"to":42}} {"id":100009285,"name":"PrepareForCreate","signature":"func (leaseStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/coordination/lease/strategy.go","code":"// PrepareForCreate prepares Lease for creation.\nfunc (leaseStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n}","line":{"from":44,"to":46}} {"id":100009286,"name":"PrepareForUpdate","signature":"func (leaseStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/coordination/lease/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (leaseStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n}","line":{"from":48,"to":50}} {"id":100009287,"name":"Validate","signature":"func (leaseStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/coordination/lease/strategy.go","code":"// Validate validates a new Lease.\nfunc (leaseStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tlease := obj.(*coordination.Lease)\n\treturn validation.ValidateLease(lease)\n}","line":{"from":52,"to":56}} {"id":100009288,"name":"WarningsOnCreate","signature":"func (leaseStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return nil }","file":"pkg/registry/coordination/lease/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (leaseStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return nil }","line":{"from":58,"to":59}} {"id":100009289,"name":"Canonicalize","signature":"func (leaseStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/coordination/lease/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (leaseStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":61,"to":63}} {"id":100009290,"name":"AllowCreateOnUpdate","signature":"func (leaseStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/coordination/lease/strategy.go","code":"// AllowCreateOnUpdate is true for Lease; this means you may create one with a PUT request.\nfunc (leaseStrategy) AllowCreateOnUpdate() bool {\n\treturn true\n}","line":{"from":65,"to":68}} {"id":100009291,"name":"ValidateUpdate","signature":"func (leaseStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/coordination/lease/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (leaseStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateLeaseUpdate(obj.(*coordination.Lease), old.(*coordination.Lease))\n}","line":{"from":70,"to":73}} {"id":100009292,"name":"WarningsOnUpdate","signature":"func (leaseStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/coordination/lease/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (leaseStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":75,"to":78}} {"id":100009293,"name":"AllowUnconditionalUpdate","signature":"func (leaseStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/coordination/lease/strategy.go","code":"// AllowUnconditionalUpdate is the default update policy for Lease objects.\nfunc (leaseStrategy) AllowUnconditionalUpdate() bool {\n\treturn false\n}","line":{"from":80,"to":83}} {"id":100009294,"name":"NewRESTStorage","signature":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error)","file":"pkg/registry/coordination/rest/storage_coordination.go","code":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error) {\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(coordination.GroupName, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs)\n\t// If you add a version here, be sure to add an entry in `k8s.io/kubernetes/cmd/kube-apiserver/app/aggregator.go with specific priorities.\n\t// TODO refactor the plumbing to provide the information in the APIGroupInfo\n\n\tif storageMap, err := p.v1Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[coordinationv1.SchemeGroupVersion.Version] = storageMap\n\t}\n\treturn apiGroupInfo, nil\n}","line":{"from":32,"to":43}} {"id":100009295,"name":"v1Storage","signature":"func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/coordination/rest/storage_coordination.go","code":"func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\t// leases\n\tif resource := \"leases\"; apiResourceConfigSource.ResourceEnabled(coordinationv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tleaseStorage, err := leasestorage.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = leaseStorage\n\t}\n\treturn storage, nil\n}","line":{"from":45,"to":57}} {"id":100009296,"name":"GroupName","signature":"func (p RESTStorageProvider) GroupName() string","file":"pkg/registry/coordination/rest/storage_coordination.go","code":"func (p RESTStorageProvider) GroupName() string {\n\treturn coordination.GroupName\n}","line":{"from":59,"to":61}} {"id":100009297,"name":"NewStorage","signature":"func NewStorage(serverRetriever func() map[string]Server) *REST","file":"pkg/registry/core/componentstatus/rest.go","code":"// NewStorage returns a new REST.\nfunc NewStorage(serverRetriever func() map[string]Server) *REST {\n\treturn \u0026REST{\n\t\tGetServersToValidate: serverRetriever,\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n}","line":{"from":45,"to":51}} {"id":100009298,"name":"NamespaceScoped","signature":"func (*REST) NamespaceScoped() bool","file":"pkg/registry/core/componentstatus/rest.go","code":"func (*REST) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":53,"to":55}} {"id":100009299,"name":"New","signature":"func (rs *REST) New() runtime.Object","file":"pkg/registry/core/componentstatus/rest.go","code":"func (rs *REST) New() runtime.Object {\n\treturn \u0026api.ComponentStatus{}\n}","line":{"from":57,"to":59}} {"id":100009300,"name":"GetSingularName","signature":"func (rs *REST) GetSingularName() string","file":"pkg/registry/core/componentstatus/rest.go","code":"func (rs *REST) GetSingularName() string {\n\treturn \"componentstatus\"\n}","line":{"from":63,"to":65}} {"id":100009301,"name":"Destroy","signature":"func (r *REST) Destroy()","file":"pkg/registry/core/componentstatus/rest.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *REST) Destroy() {\n\t// Given no underlying store, we don't destroy anything\n\t// here explicitly.\n}","line":{"from":67,"to":71}} {"id":100009302,"name":"NewList","signature":"func (rs *REST) NewList() runtime.Object","file":"pkg/registry/core/componentstatus/rest.go","code":"func (rs *REST) NewList() runtime.Object {\n\treturn \u0026api.ComponentStatusList{}\n}","line":{"from":73,"to":75}} {"id":100009303,"name":"List","signature":"func (rs *REST) List(ctx context.Context, options *metainternalversion.ListOptions) (runtime.Object, error)","file":"pkg/registry/core/componentstatus/rest.go","code":"// Returns the list of component status. Note that the label and field are both ignored.\n// Note that this call doesn't support labels or selectors.\nfunc (rs *REST) List(ctx context.Context, options *metainternalversion.ListOptions) (runtime.Object, error) {\n\tservers := rs.GetServersToValidate()\n\n\twait := sync.WaitGroup{}\n\twait.Add(len(servers))\n\tstatuses := make(chan api.ComponentStatus, len(servers))\n\tfor k, v := range servers {\n\t\tgo func(name string, server Server) {\n\t\t\tdefer wait.Done()\n\t\t\tstatus := rs.getComponentStatus(name, server)\n\t\t\tstatuses \u003c- *status\n\t\t}(k, v)\n\t}\n\twait.Wait()\n\tclose(statuses)\n\n\tpred := componentStatusPredicate(options)\n\n\treply := []api.ComponentStatus{}\n\tfor status := range statuses {\n\t\t// ComponentStatus resources currently (v1.14) do not support labeling, however the filtering is executed\n\t\t// nonetheless in case the request contains Label or Field selectors (which will effectively filter out\n\t\t// all of the results and return an empty response).\n\t\tif matched := matchesPredicate(status, \u0026pred); matched {\n\t\t\treply = append(reply, status)\n\t\t}\n\t}\n\treturn \u0026api.ComponentStatusList{Items: reply}, nil\n}","line":{"from":77,"to":107}} {"id":100009304,"name":"componentStatusPredicate","signature":"func componentStatusPredicate(options *metainternalversion.ListOptions) storage.SelectionPredicate","file":"pkg/registry/core/componentstatus/rest.go","code":"func componentStatusPredicate(options *metainternalversion.ListOptions) storage.SelectionPredicate {\n\tpred := storage.SelectionPredicate{\n\t\tLabel: labels.Everything(),\n\t\tField: fields.Everything(),\n\t\tGetAttrs: nil,\n\t}\n\tif options != nil {\n\t\tif options.LabelSelector != nil {\n\t\t\tpred.Label = options.LabelSelector\n\t\t}\n\t\tif options.FieldSelector != nil {\n\t\t\tpred.Field = options.FieldSelector\n\t\t}\n\t}\n\treturn pred\n}","line":{"from":109,"to":124}} {"id":100009305,"name":"matchesPredicate","signature":"func matchesPredicate(status api.ComponentStatus, pred *storage.SelectionPredicate) bool","file":"pkg/registry/core/componentstatus/rest.go","code":"func matchesPredicate(status api.ComponentStatus, pred *storage.SelectionPredicate) bool {\n\t// currently no fields except the generic meta fields are supported for predicate matching\n\tfieldsSet := generic.AddObjectMetaFieldsSet(make(fields.Set, 2), \u0026status.ObjectMeta, true)\n\treturn pred.MatchesObjectAttributes(\n\t\tstatus.ObjectMeta.Labels,\n\t\tfieldsSet,\n\t)\n}","line":{"from":126,"to":133}} {"id":100009306,"name":"Get","signature":"func (rs *REST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/core/componentstatus/rest.go","code":"func (rs *REST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\tservers := rs.GetServersToValidate()\n\n\tif server, ok := servers[name]; !ok {\n\t\treturn nil, fmt.Errorf(\"Component not found: %s\", name)\n\t} else {\n\t\treturn rs.getComponentStatus(name, server), nil\n\t}\n}","line":{"from":135,"to":143}} {"id":100009307,"name":"ToConditionStatus","signature":"func ToConditionStatus(s probe.Result) api.ConditionStatus","file":"pkg/registry/core/componentstatus/rest.go","code":"func ToConditionStatus(s probe.Result) api.ConditionStatus {\n\tswitch s {\n\tcase probe.Success:\n\t\treturn api.ConditionTrue\n\tcase probe.Failure:\n\t\treturn api.ConditionFalse\n\tdefault:\n\t\treturn api.ConditionUnknown\n\t}\n}","line":{"from":145,"to":154}} {"id":100009308,"name":"getComponentStatus","signature":"func (rs *REST) getComponentStatus(name string, server Server) *api.ComponentStatus","file":"pkg/registry/core/componentstatus/rest.go","code":"func (rs *REST) getComponentStatus(name string, server Server) *api.ComponentStatus {\n\tstatus, msg, err := server.DoServerCheck()\n\terrorMsg := \"\"\n\tif err != nil {\n\t\terrorMsg = err.Error()\n\t}\n\n\tc := \u0026api.ComponentCondition{\n\t\tType: api.ComponentHealthy,\n\t\tStatus: ToConditionStatus(status),\n\t\tMessage: msg,\n\t\tError: errorMsg,\n\t}\n\n\tretVal := \u0026api.ComponentStatus{\n\t\tConditions: []api.ComponentCondition{*c},\n\t}\n\tretVal.Name = name\n\n\treturn retVal\n}","line":{"from":156,"to":176}} {"id":100009309,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/core/componentstatus/rest.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"cs\"}\n}","line":{"from":181,"to":184}} {"id":100009310,"name":"DoServerCheck","signature":"func (server *HttpServer) DoServerCheck() (probe.Result, string, error)","file":"pkg/registry/core/componentstatus/validator.go","code":"func (server *HttpServer) DoServerCheck() (probe.Result, string, error) {\n\t// setup the prober\n\tserver.Once.Do(func() {\n\t\tif server.Prober != nil {\n\t\t\treturn\n\t\t}\n\t\tconst followNonLocalRedirects = true\n\t\tserver.Prober = httpprober.NewWithTLSConfig(server.TLSConfig, followNonLocalRedirects)\n\t})\n\n\tscheme := \"http\"\n\tif server.EnableHTTPS {\n\t\tscheme = \"https\"\n\t}\n\turl := utilnet.FormatURL(scheme, server.Addr, server.Port, server.Path)\n\n\treq, err := httpprober.NewProbeRequest(url, nil)\n\tif err != nil {\n\t\treturn probe.Unknown, \"\", fmt.Errorf(\"failed to construct probe request: %w\", err)\n\t}\n\tresult, data, err := server.Prober.Probe(req, probeTimeOut)\n\n\tif err != nil {\n\t\treturn probe.Unknown, \"\", err\n\t}\n\tif result == probe.Failure {\n\t\treturn probe.Failure, data, err\n\t}\n\tif server.Validate != nil {\n\t\tif err := server.Validate([]byte(data)); err != nil {\n\t\t\treturn probe.Failure, data, err\n\t\t}\n\t}\n\treturn result, data, nil\n}","line":{"from":67,"to":101}} {"id":100009311,"name":"DoServerCheck","signature":"func (server *EtcdServer) DoServerCheck() (probe.Result, string, error)","file":"pkg/registry/core/componentstatus/validator.go","code":"func (server *EtcdServer) DoServerCheck() (probe.Result, string, error) {\n\tprober, err := factory.CreateProber(server.Config)\n\tif err != nil {\n\t\treturn probe.Failure, \"\", err\n\t}\n\tdefer prober.Close()\n\n\tctx, cancel := context.WithTimeout(context.Background(), probeTimeOut)\n\tdefer cancel()\n\terr = prober.Probe(ctx)\n\tif err != nil {\n\t\treturn probe.Failure, \"\", err\n\t}\n\treturn probe.Success, \"\", err\n}","line":{"from":107,"to":121}} {"id":100009312,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error)","file":"pkg/registry/core/configmap/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work with ConfigMap objects.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026api.ConfigMap{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026api.ConfigMapList{} },\n\t\tPredicateFunc: configmap.Matcher,\n\t\tDefaultQualifiedResource: api.Resource(\"configmaps\"),\n\t\tSingularQualifiedResource: api.Resource(\"configmap\"),\n\n\t\tCreateStrategy: configmap.Strategy,\n\t\tUpdateStrategy: configmap.Strategy,\n\t\tDeleteStrategy: configmap.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{\n\t\tRESTOptions: optsGetter,\n\t\tAttrFunc: configmap.GetAttrs,\n\t}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026REST{store}, nil\n}","line":{"from":36,"to":59}} {"id":100009313,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/core/configmap/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"cm\"}\n}","line":{"from":64,"to":67}} {"id":100009314,"name":"NamespaceScoped","signature":"func (strategy) NamespaceScoped() bool","file":"pkg/registry/core/configmap/strategy.go","code":"func (strategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":52,"to":54}} {"id":100009315,"name":"PrepareForCreate","signature":"func (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/core/configmap/strategy.go","code":"func (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tconfigMap := obj.(*api.ConfigMap)\n\tdropDisabledFields(configMap, nil)\n}","line":{"from":56,"to":59}} {"id":100009316,"name":"Validate","signature":"func (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/core/configmap/strategy.go","code":"func (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tcfg := obj.(*api.ConfigMap)\n\n\treturn validation.ValidateConfigMap(cfg)\n}","line":{"from":61,"to":65}} {"id":100009317,"name":"WarningsOnCreate","signature":"func (strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return nil }","file":"pkg/registry/core/configmap/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return nil }","line":{"from":67,"to":68}} {"id":100009318,"name":"Canonicalize","signature":"func (strategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/core/configmap/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (strategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":70,"to":72}} {"id":100009319,"name":"AllowCreateOnUpdate","signature":"func (strategy) AllowCreateOnUpdate() bool","file":"pkg/registry/core/configmap/strategy.go","code":"func (strategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":74,"to":76}} {"id":100009320,"name":"PrepareForUpdate","signature":"func (strategy) PrepareForUpdate(ctx context.Context, newObj, oldObj runtime.Object)","file":"pkg/registry/core/configmap/strategy.go","code":"func (strategy) PrepareForUpdate(ctx context.Context, newObj, oldObj runtime.Object) {\n\toldConfigMap := oldObj.(*api.ConfigMap)\n\tnewConfigMap := newObj.(*api.ConfigMap)\n\tdropDisabledFields(newConfigMap, oldConfigMap)\n}","line":{"from":78,"to":82}} {"id":100009321,"name":"ValidateUpdate","signature":"func (strategy) ValidateUpdate(ctx context.Context, newObj, oldObj runtime.Object) field.ErrorList","file":"pkg/registry/core/configmap/strategy.go","code":"func (strategy) ValidateUpdate(ctx context.Context, newObj, oldObj runtime.Object) field.ErrorList {\n\toldCfg, newCfg := oldObj.(*api.ConfigMap), newObj.(*api.ConfigMap)\n\n\treturn validation.ValidateConfigMapUpdate(newCfg, oldCfg)\n}","line":{"from":84,"to":88}} {"id":100009322,"name":"WarningsOnUpdate","signature":"func (strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string { return nil }","file":"pkg/registry/core/configmap/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string { return nil }","line":{"from":90,"to":91}} {"id":100009323,"name":"dropDisabledFields","signature":"func dropDisabledFields(configMap *api.ConfigMap, oldConfigMap *api.ConfigMap)","file":"pkg/registry/core/configmap/strategy.go","code":"func dropDisabledFields(configMap *api.ConfigMap, oldConfigMap *api.ConfigMap) {\n}","line":{"from":93,"to":94}} {"id":100009324,"name":"AllowUnconditionalUpdate","signature":"func (strategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/core/configmap/strategy.go","code":"func (strategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":96,"to":98}} {"id":100009325,"name":"GetAttrs","signature":"func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error)","file":"pkg/registry/core/configmap/strategy.go","code":"// GetAttrs returns labels and fields of a given object for filtering purposes.\nfunc GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {\n\tconfigMap, ok := obj.(*api.ConfigMap)\n\tif !ok {\n\t\treturn nil, nil, fmt.Errorf(\"not a configmap\")\n\t}\n\treturn labels.Set(configMap.Labels), SelectableFields(configMap), nil\n}","line":{"from":100,"to":107}} {"id":100009326,"name":"Matcher","signature":"func Matcher(label labels.Selector, field fields.Selector) pkgstorage.SelectionPredicate","file":"pkg/registry/core/configmap/strategy.go","code":"// Matcher returns a selection predicate for a given label and field selector.\nfunc Matcher(label labels.Selector, field fields.Selector) pkgstorage.SelectionPredicate {\n\treturn pkgstorage.SelectionPredicate{\n\t\tLabel: label,\n\t\tField: field,\n\t\tGetAttrs: GetAttrs,\n\t}\n}","line":{"from":109,"to":116}} {"id":100009327,"name":"SelectableFields","signature":"func SelectableFields(obj *api.ConfigMap) fields.Set","file":"pkg/registry/core/configmap/strategy.go","code":"// SelectableFields returns a field set that can be used for filter selection\nfunc SelectableFields(obj *api.ConfigMap) fields.Set {\n\treturn generic.ObjectMetaFieldsSet(\u0026obj.ObjectMeta, true)\n}","line":{"from":118,"to":121}} {"id":100009328,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error)","file":"pkg/registry/core/endpoint/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against endpoints.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026api.Endpoints{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026api.EndpointsList{} },\n\t\tDefaultQualifiedResource: api.Resource(\"endpoints\"),\n\t\tSingularQualifiedResource: api.Resource(\"endpoints\"),\n\n\t\tCreateStrategy: endpoint.Strategy,\n\t\tUpdateStrategy: endpoint.Strategy,\n\t\tDeleteStrategy: endpoint.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026REST{store}, nil\n}","line":{"from":36,"to":55}} {"id":100009329,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/core/endpoint/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"ep\"}\n}","line":{"from":60,"to":63}} {"id":100009330,"name":"NamespaceScoped","signature":"func (endpointsStrategy) NamespaceScoped() bool","file":"pkg/registry/core/endpoint/strategy.go","code":"// NamespaceScoped is true for endpoints.\nfunc (endpointsStrategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":40,"to":43}} {"id":100009331,"name":"PrepareForCreate","signature":"func (endpointsStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/core/endpoint/strategy.go","code":"// PrepareForCreate clears fields that are not allowed to be set by end users on creation.\nfunc (endpointsStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n}","line":{"from":45,"to":47}} {"id":100009332,"name":"PrepareForUpdate","signature":"func (endpointsStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/core/endpoint/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (endpointsStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n}","line":{"from":49,"to":51}} {"id":100009333,"name":"Validate","signature":"func (endpointsStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/core/endpoint/strategy.go","code":"// Validate validates a new endpoints.\nfunc (endpointsStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\treturn validation.ValidateEndpointsCreate(obj.(*api.Endpoints))\n}","line":{"from":53,"to":56}} {"id":100009334,"name":"WarningsOnCreate","signature":"func (endpointsStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/core/endpoint/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (endpointsStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":58,"to":61}} {"id":100009335,"name":"Canonicalize","signature":"func (endpointsStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/core/endpoint/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (endpointsStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":63,"to":65}} {"id":100009336,"name":"AllowCreateOnUpdate","signature":"func (endpointsStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/core/endpoint/strategy.go","code":"// AllowCreateOnUpdate is true for endpoints.\nfunc (endpointsStrategy) AllowCreateOnUpdate() bool {\n\treturn true\n}","line":{"from":67,"to":70}} {"id":100009337,"name":"ValidateUpdate","signature":"func (endpointsStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/core/endpoint/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (endpointsStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateEndpointsUpdate(obj.(*api.Endpoints), old.(*api.Endpoints))\n}","line":{"from":72,"to":75}} {"id":100009338,"name":"WarningsOnUpdate","signature":"func (endpointsStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/core/endpoint/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (endpointsStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":77,"to":80}} {"id":100009339,"name":"AllowUnconditionalUpdate","signature":"func (endpointsStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/core/endpoint/strategy.go","code":"func (endpointsStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":82,"to":84}} {"id":100009340,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter, ttl uint64) (*REST, error)","file":"pkg/registry/core/event/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against events.\nfunc NewREST(optsGetter generic.RESTOptionsGetter, ttl uint64) (*REST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026api.Event{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026api.EventList{} },\n\t\tPredicateFunc: event.Matcher,\n\t\tTTLFunc: func(runtime.Object, uint64, bool) (uint64, error) {\n\t\t\treturn ttl, nil\n\t\t},\n\t\tDefaultQualifiedResource: api.Resource(\"events\"),\n\t\tSingularQualifiedResource: api.Resource(\"event\"),\n\n\t\tCreateStrategy: event.Strategy,\n\t\tUpdateStrategy: event.Strategy,\n\t\tDeleteStrategy: event.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: event.GetAttrs}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026REST{store}, nil\n}","line":{"from":36,"to":59}} {"id":100009341,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/core/event/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"ev\"}\n}","line":{"from":64,"to":67}} {"id":100009342,"name":"DefaultGarbageCollectionPolicy","signature":"func (eventStrategy) DefaultGarbageCollectionPolicy(ctx context.Context) rest.GarbageCollectionPolicy","file":"pkg/registry/core/event/strategy.go","code":"func (eventStrategy) DefaultGarbageCollectionPolicy(ctx context.Context) rest.GarbageCollectionPolicy {\n\treturn rest.Unsupported\n}","line":{"from":47,"to":49}} {"id":100009343,"name":"NamespaceScoped","signature":"func (eventStrategy) NamespaceScoped() bool","file":"pkg/registry/core/event/strategy.go","code":"func (eventStrategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":51,"to":53}} {"id":100009344,"name":"PrepareForCreate","signature":"func (eventStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/core/event/strategy.go","code":"func (eventStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n}","line":{"from":55,"to":56}} {"id":100009345,"name":"PrepareForUpdate","signature":"func (eventStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/core/event/strategy.go","code":"func (eventStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n}","line":{"from":58,"to":59}} {"id":100009346,"name":"Validate","signature":"func (eventStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/core/event/strategy.go","code":"func (eventStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tgroupVersion := requestGroupVersion(ctx)\n\tevent := obj.(*api.Event)\n\treturn validation.ValidateEventCreate(event, groupVersion)\n}","line":{"from":61,"to":65}} {"id":100009347,"name":"WarningsOnCreate","signature":"func (eventStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return nil }","file":"pkg/registry/core/event/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (eventStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return nil }","line":{"from":67,"to":68}} {"id":100009348,"name":"Canonicalize","signature":"func (eventStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/core/event/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (eventStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":70,"to":72}} {"id":100009349,"name":"AllowCreateOnUpdate","signature":"func (eventStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/core/event/strategy.go","code":"func (eventStrategy) AllowCreateOnUpdate() bool {\n\treturn true\n}","line":{"from":74,"to":76}} {"id":100009350,"name":"ValidateUpdate","signature":"func (eventStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/core/event/strategy.go","code":"func (eventStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tgroupVersion := requestGroupVersion(ctx)\n\tevent := obj.(*api.Event)\n\toldEvent := old.(*api.Event)\n\treturn validation.ValidateEventUpdate(event, oldEvent, groupVersion)\n}","line":{"from":78,"to":83}} {"id":100009351,"name":"WarningsOnUpdate","signature":"func (eventStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/core/event/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (eventStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":85,"to":88}} {"id":100009352,"name":"AllowUnconditionalUpdate","signature":"func (eventStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/core/event/strategy.go","code":"func (eventStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":90,"to":92}} {"id":100009353,"name":"GetAttrs","signature":"func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error)","file":"pkg/registry/core/event/strategy.go","code":"// GetAttrs returns labels and fields of a given object for filtering purposes.\nfunc GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {\n\tevent, ok := obj.(*api.Event)\n\tif !ok {\n\t\treturn nil, nil, fmt.Errorf(\"not an event\")\n\t}\n\treturn labels.Set(event.Labels), ToSelectableFields(event), nil\n}","line":{"from":94,"to":101}} {"id":100009354,"name":"Matcher","signature":"func Matcher(label labels.Selector, field fields.Selector) storage.SelectionPredicate","file":"pkg/registry/core/event/strategy.go","code":"// Matcher returns a selection predicate for a given label and field selector.\nfunc Matcher(label labels.Selector, field fields.Selector) storage.SelectionPredicate {\n\treturn storage.SelectionPredicate{\n\t\tLabel: label,\n\t\tField: field,\n\t\tGetAttrs: GetAttrs,\n\t}\n}","line":{"from":103,"to":110}} {"id":100009355,"name":"ToSelectableFields","signature":"func ToSelectableFields(event *api.Event) fields.Set","file":"pkg/registry/core/event/strategy.go","code":"// ToSelectableFields returns a field set that represents the object.\nfunc ToSelectableFields(event *api.Event) fields.Set {\n\tobjectMetaFieldsSet := generic.ObjectMetaFieldsSet(\u0026event.ObjectMeta, true)\n\tsource := event.Source.Component\n\tif source == \"\" {\n\t\tsource = event.ReportingController\n\t}\n\tspecificFieldsSet := fields.Set{\n\t\t\"involvedObject.kind\": event.InvolvedObject.Kind,\n\t\t\"involvedObject.namespace\": event.InvolvedObject.Namespace,\n\t\t\"involvedObject.name\": event.InvolvedObject.Name,\n\t\t\"involvedObject.uid\": string(event.InvolvedObject.UID),\n\t\t\"involvedObject.apiVersion\": event.InvolvedObject.APIVersion,\n\t\t\"involvedObject.resourceVersion\": event.InvolvedObject.ResourceVersion,\n\t\t\"involvedObject.fieldPath\": event.InvolvedObject.FieldPath,\n\t\t\"reason\": event.Reason,\n\t\t\"reportingComponent\": event.ReportingController, // use the core/v1 field name\n\t\t\"source\": source,\n\t\t\"type\": event.Type,\n\t}\n\treturn generic.MergeFieldsSets(specificFieldsSet, objectMetaFieldsSet)\n}","line":{"from":112,"to":133}} {"id":100009356,"name":"requestGroupVersion","signature":"func requestGroupVersion(ctx context.Context) schema.GroupVersion","file":"pkg/registry/core/event/strategy.go","code":"// requestGroupVersion returns the group/version associated with the given context, or a zero-value group/version.\nfunc requestGroupVersion(ctx context.Context) schema.GroupVersion {\n\tif requestInfo, found := genericapirequest.RequestInfoFrom(ctx); found {\n\t\treturn schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}\n\t}\n\treturn schema.GroupVersion{}\n}","line":{"from":135,"to":141}} {"id":100009357,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error)","file":"pkg/registry/core/limitrange/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against limit ranges.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026api.LimitRange{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026api.LimitRangeList{} },\n\t\tDefaultQualifiedResource: api.Resource(\"limitranges\"),\n\t\tSingularQualifiedResource: api.Resource(\"limitrange\"),\n\n\t\tCreateStrategy: limitrange.Strategy,\n\t\tUpdateStrategy: limitrange.Strategy,\n\t\tDeleteStrategy: limitrange.Strategy,\n\n\t\t// TODO: define table converter that exposes more than name/creation timestamp\n\t\tTableConvertor: rest.NewDefaultTableConvertor(api.Resource(\"limitranges\")),\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026REST{store}, nil\n}","line":{"from":33,"to":53}} {"id":100009358,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/core/limitrange/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"limits\"}\n}","line":{"from":58,"to":61}} {"id":100009359,"name":"NamespaceScoped","signature":"func (limitrangeStrategy) NamespaceScoped() bool","file":"pkg/registry/core/limitrange/strategy.go","code":"func (limitrangeStrategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":40,"to":42}} {"id":100009360,"name":"PrepareForCreate","signature":"func (limitrangeStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/core/limitrange/strategy.go","code":"func (limitrangeStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tlimitRange := obj.(*api.LimitRange)\n\tif len(limitRange.Name) == 0 {\n\t\tlimitRange.Name = string(uuid.NewUUID())\n\t}\n}","line":{"from":44,"to":49}} {"id":100009361,"name":"PrepareForUpdate","signature":"func (limitrangeStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/core/limitrange/strategy.go","code":"func (limitrangeStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n}","line":{"from":51,"to":52}} {"id":100009362,"name":"Validate","signature":"func (limitrangeStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/core/limitrange/strategy.go","code":"func (limitrangeStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tlimitRange := obj.(*api.LimitRange)\n\treturn validation.ValidateLimitRange(limitRange)\n}","line":{"from":54,"to":57}} {"id":100009363,"name":"WarningsOnCreate","signature":"func (limitrangeStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/core/limitrange/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (limitrangeStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":59,"to":62}} {"id":100009364,"name":"Canonicalize","signature":"func (limitrangeStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/core/limitrange/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (limitrangeStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":64,"to":66}} {"id":100009365,"name":"AllowCreateOnUpdate","signature":"func (limitrangeStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/core/limitrange/strategy.go","code":"func (limitrangeStrategy) AllowCreateOnUpdate() bool {\n\treturn true\n}","line":{"from":68,"to":70}} {"id":100009366,"name":"ValidateUpdate","signature":"func (limitrangeStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/core/limitrange/strategy.go","code":"func (limitrangeStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tlimitRange := obj.(*api.LimitRange)\n\treturn validation.ValidateLimitRange(limitRange)\n}","line":{"from":72,"to":75}} {"id":100009367,"name":"WarningsOnUpdate","signature":"func (limitrangeStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/core/limitrange/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (limitrangeStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":77,"to":80}} {"id":100009368,"name":"AllowUnconditionalUpdate","signature":"func (limitrangeStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/core/limitrange/strategy.go","code":"func (limitrangeStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":82,"to":84}} {"id":100009369,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, *FinalizeREST, error)","file":"pkg/registry/core/namespace/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against namespaces.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, *FinalizeREST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026api.Namespace{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026api.NamespaceList{} },\n\t\tPredicateFunc: namespace.MatchNamespace,\n\t\tDefaultQualifiedResource: api.Resource(\"namespaces\"),\n\t\tSingularQualifiedResource: api.Resource(\"namespace\"),\n\n\t\tCreateStrategy: namespace.Strategy,\n\t\tUpdateStrategy: namespace.Strategy,\n\t\tDeleteStrategy: namespace.Strategy,\n\t\tResetFieldsStrategy: namespace.Strategy,\n\t\tReturnDeletedObject: true,\n\n\t\tShouldDeleteDuringUpdate: ShouldDeleteNamespaceDuringUpdate,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: namespace.GetAttrs}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = namespace.StatusStrategy\n\tstatusStore.ResetFieldsStrategy = namespace.StatusStrategy\n\n\tfinalizeStore := *store\n\tfinalizeStore.UpdateStrategy = namespace.FinalizeStrategy\n\tfinalizeStore.ResetFieldsStrategy = namespace.FinalizeStrategy\n\n\treturn \u0026REST{store: store, status: \u0026statusStore}, \u0026StatusREST{store: \u0026statusStore}, \u0026FinalizeREST{store: \u0026finalizeStore}, nil\n}","line":{"from":59,"to":92}} {"id":100009370,"name":"NamespaceScoped","signature":"func (r *REST) NamespaceScoped() bool","file":"pkg/registry/core/namespace/storage/storage.go","code":"func (r *REST) NamespaceScoped() bool {\n\treturn r.store.NamespaceScoped()\n}","line":{"from":94,"to":96}} {"id":100009371,"name":"GetSingularName","signature":"func (r *REST) GetSingularName() string","file":"pkg/registry/core/namespace/storage/storage.go","code":"func (r *REST) GetSingularName() string {\n\treturn r.store.GetSingularName()\n}","line":{"from":100,"to":102}} {"id":100009372,"name":"New","signature":"func (r *REST) New() runtime.Object","file":"pkg/registry/core/namespace/storage/storage.go","code":"func (r *REST) New() runtime.Object {\n\treturn r.store.New()\n}","line":{"from":104,"to":106}} {"id":100009373,"name":"Destroy","signature":"func (r *REST) Destroy()","file":"pkg/registry/core/namespace/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *REST) Destroy() {\n\tr.store.Destroy()\n}","line":{"from":108,"to":111}} {"id":100009374,"name":"NewList","signature":"func (r *REST) NewList() runtime.Object","file":"pkg/registry/core/namespace/storage/storage.go","code":"func (r *REST) NewList() runtime.Object {\n\treturn r.store.NewList()\n}","line":{"from":113,"to":115}} {"id":100009375,"name":"List","signature":"func (r *REST) List(ctx context.Context, options *metainternalversion.ListOptions) (runtime.Object, error)","file":"pkg/registry/core/namespace/storage/storage.go","code":"func (r *REST) List(ctx context.Context, options *metainternalversion.ListOptions) (runtime.Object, error) {\n\treturn r.store.List(ctx, options)\n}","line":{"from":117,"to":119}} {"id":100009376,"name":"Create","signature":"func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error)","file":"pkg/registry/core/namespace/storage/storage.go","code":"func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {\n\treturn r.store.Create(ctx, obj, createValidation, options)\n}","line":{"from":121,"to":123}} {"id":100009377,"name":"Update","signature":"func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/core/namespace/storage/storage.go","code":"func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, forceAllowCreate, options)\n}","line":{"from":125,"to":127}} {"id":100009378,"name":"Get","signature":"func (r *REST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/core/namespace/storage/storage.go","code":"func (r *REST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":129,"to":131}} {"id":100009379,"name":"Watch","signature":"func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptions) (watch.Interface, error)","file":"pkg/registry/core/namespace/storage/storage.go","code":"func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptions) (watch.Interface, error) {\n\treturn r.store.Watch(ctx, options)\n}","line":{"from":133,"to":135}} {"id":100009380,"name":"Delete","signature":"func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions) (runtime.Object, bool, error)","file":"pkg/registry/core/namespace/storage/storage.go","code":"// Delete enforces life-cycle rules for namespace termination\nfunc (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions) (runtime.Object, bool, error) {\n\tnsObj, err := r.Get(ctx, name, \u0026metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\tnamespace := nsObj.(*api.Namespace)\n\n\t// Ensure we have a UID precondition\n\tif options == nil {\n\t\toptions = metav1.NewDeleteOptions(0)\n\t}\n\tif options.Preconditions == nil {\n\t\toptions.Preconditions = \u0026metav1.Preconditions{}\n\t}\n\tif options.Preconditions.UID == nil {\n\t\toptions.Preconditions.UID = \u0026namespace.UID\n\t} else if *options.Preconditions.UID != namespace.UID {\n\t\terr = apierrors.NewConflict(\n\t\t\tapi.Resource(\"namespaces\"),\n\t\t\tname,\n\t\t\tfmt.Errorf(\"Precondition failed: UID in precondition: %v, UID in object meta: %v\", *options.Preconditions.UID, namespace.UID),\n\t\t)\n\t\treturn nil, false, err\n\t}\n\tif options.Preconditions.ResourceVersion != nil \u0026\u0026 *options.Preconditions.ResourceVersion != namespace.ResourceVersion {\n\t\terr = apierrors.NewConflict(\n\t\t\tapi.Resource(\"namespaces\"),\n\t\t\tname,\n\t\t\tfmt.Errorf(\"Precondition failed: ResourceVersion in precondition: %v, ResourceVersion in object meta: %v\", *options.Preconditions.ResourceVersion, namespace.ResourceVersion),\n\t\t)\n\t\treturn nil, false, err\n\t}\n\n\t// upon first request to delete, we switch the phase to start namespace termination\n\t// TODO: enhance graceful deletion's calls to DeleteStrategy to allow phase change and finalizer patterns\n\tif namespace.DeletionTimestamp.IsZero() {\n\t\tkey, err := r.store.KeyFunc(ctx, name)\n\t\tif err != nil {\n\t\t\treturn nil, false, err\n\t\t}\n\n\t\tpreconditions := storage.Preconditions{UID: options.Preconditions.UID, ResourceVersion: options.Preconditions.ResourceVersion}\n\n\t\tout := r.store.NewFunc()\n\t\terr = r.store.Storage.GuaranteedUpdate(\n\t\t\tctx, key, out, false, \u0026preconditions,\n\t\t\tstorage.SimpleUpdate(func(existing runtime.Object) (runtime.Object, error) {\n\t\t\t\texistingNamespace, ok := existing.(*api.Namespace)\n\t\t\t\tif !ok {\n\t\t\t\t\t// wrong type\n\t\t\t\t\treturn nil, fmt.Errorf(\"expected *api.Namespace, got %v\", existing)\n\t\t\t\t}\n\t\t\t\tif err := deleteValidation(ctx, existingNamespace); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\t// Set the deletion timestamp if needed\n\t\t\t\tif existingNamespace.DeletionTimestamp.IsZero() {\n\t\t\t\t\tnow := metav1.Now()\n\t\t\t\t\texistingNamespace.DeletionTimestamp = \u0026now\n\t\t\t\t}\n\t\t\t\t// Set the namespace phase to terminating, if needed\n\t\t\t\tif existingNamespace.Status.Phase != api.NamespaceTerminating {\n\t\t\t\t\texistingNamespace.Status.Phase = api.NamespaceTerminating\n\t\t\t\t}\n\n\t\t\t\t// the current finalizers which are on namespace\n\t\t\t\tcurrentFinalizers := map[string]bool{}\n\t\t\t\tfor _, f := range existingNamespace.Finalizers {\n\t\t\t\t\tcurrentFinalizers[f] = true\n\t\t\t\t}\n\t\t\t\t// the finalizers we should ensure on namespace\n\t\t\t\tshouldHaveFinalizers := map[string]bool{\n\t\t\t\t\tmetav1.FinalizerOrphanDependents: shouldHaveOrphanFinalizer(options, currentFinalizers[metav1.FinalizerOrphanDependents]),\n\t\t\t\t\tmetav1.FinalizerDeleteDependents: shouldHaveDeleteDependentsFinalizer(options, currentFinalizers[metav1.FinalizerDeleteDependents]),\n\t\t\t\t}\n\t\t\t\t// determine whether there are changes\n\t\t\t\tchangeNeeded := false\n\t\t\t\tfor finalizer, shouldHave := range shouldHaveFinalizers {\n\t\t\t\t\tchangeNeeded = currentFinalizers[finalizer] != shouldHave || changeNeeded\n\t\t\t\t\tif shouldHave {\n\t\t\t\t\t\tcurrentFinalizers[finalizer] = true\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdelete(currentFinalizers, finalizer)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// make the changes if needed\n\t\t\t\tif changeNeeded {\n\t\t\t\t\tnewFinalizers := []string{}\n\t\t\t\t\tfor f := range currentFinalizers {\n\t\t\t\t\t\tnewFinalizers = append(newFinalizers, f)\n\t\t\t\t\t}\n\t\t\t\t\texistingNamespace.Finalizers = newFinalizers\n\t\t\t\t}\n\t\t\t\treturn existingNamespace, nil\n\t\t\t}),\n\t\t\tdryrun.IsDryRun(options.DryRun),\n\t\t\tnil,\n\t\t)\n\n\t\tif err != nil {\n\t\t\terr = storageerr.InterpretGetError(err, api.Resource(\"namespaces\"), name)\n\t\t\terr = storageerr.InterpretUpdateError(err, api.Resource(\"namespaces\"), name)\n\t\t\tif _, ok := err.(*apierrors.StatusError); !ok {\n\t\t\t\terr = apierrors.NewInternalError(err)\n\t\t\t}\n\t\t\treturn nil, false, err\n\t\t}\n\n\t\treturn out, false, nil\n\t}\n\n\t// prior to final deletion, we must ensure that finalizers is empty\n\tif len(namespace.Spec.Finalizers) != 0 {\n\t\treturn namespace, false, nil\n\t}\n\treturn r.store.Delete(ctx, name, deleteValidation, options)\n}","line":{"from":137,"to":255}} {"id":100009381,"name":"ShouldDeleteNamespaceDuringUpdate","signature":"func ShouldDeleteNamespaceDuringUpdate(ctx context.Context, key string, obj, existing runtime.Object) bool","file":"pkg/registry/core/namespace/storage/storage.go","code":"// ShouldDeleteNamespaceDuringUpdate adds namespace-specific spec.finalizer checks on top of the default generic ShouldDeleteDuringUpdate behavior\nfunc ShouldDeleteNamespaceDuringUpdate(ctx context.Context, key string, obj, existing runtime.Object) bool {\n\tns, ok := obj.(*api.Namespace)\n\tif !ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unexpected type %T\", obj))\n\t\treturn false\n\t}\n\treturn len(ns.Spec.Finalizers) == 0 \u0026\u0026 genericregistry.ShouldDeleteDuringUpdate(ctx, key, obj, existing)\n}","line":{"from":257,"to":265}} {"id":100009382,"name":"shouldHaveOrphanFinalizer","signature":"func shouldHaveOrphanFinalizer(options *metav1.DeleteOptions, haveOrphanFinalizer bool) bool","file":"pkg/registry/core/namespace/storage/storage.go","code":"func shouldHaveOrphanFinalizer(options *metav1.DeleteOptions, haveOrphanFinalizer bool) bool {\n\t//nolint:staticcheck // SA1019 backwards compatibility\n\tif options.OrphanDependents != nil {\n\t\treturn *options.OrphanDependents\n\t}\n\tif options.PropagationPolicy != nil {\n\t\treturn *options.PropagationPolicy == metav1.DeletePropagationOrphan\n\t}\n\treturn haveOrphanFinalizer\n}","line":{"from":267,"to":276}} {"id":100009383,"name":"shouldHaveDeleteDependentsFinalizer","signature":"func shouldHaveDeleteDependentsFinalizer(options *metav1.DeleteOptions, haveDeleteDependentsFinalizer bool) bool","file":"pkg/registry/core/namespace/storage/storage.go","code":"func shouldHaveDeleteDependentsFinalizer(options *metav1.DeleteOptions, haveDeleteDependentsFinalizer bool) bool {\n\t//nolint:staticcheck // SA1019 backwards compatibility\n\tif options.OrphanDependents != nil {\n\t\treturn *options.OrphanDependents == false\n\t}\n\tif options.PropagationPolicy != nil {\n\t\treturn *options.PropagationPolicy == metav1.DeletePropagationForeground\n\t}\n\treturn haveDeleteDependentsFinalizer\n}","line":{"from":278,"to":287}} {"id":100009384,"name":"ConvertToTable","signature":"func (e *REST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/core/namespace/storage/storage.go","code":"func (e *REST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn e.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":289,"to":291}} {"id":100009385,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/core/namespace/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"ns\"}\n}","line":{"from":296,"to":299}} {"id":100009386,"name":"StorageVersion","signature":"func (r *REST) StorageVersion() runtime.GroupVersioner","file":"pkg/registry/core/namespace/storage/storage.go","code":"func (r *REST) StorageVersion() runtime.GroupVersioner {\n\treturn r.store.StorageVersion()\n}","line":{"from":303,"to":305}} {"id":100009387,"name":"GetResetFields","signature":"func (r *REST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/namespace/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *REST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":307,"to":310}} {"id":100009388,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"pkg/registry/core/namespace/storage/storage.go","code":"func (r *StatusREST) New() runtime.Object {\n\treturn r.store.New()\n}","line":{"from":311,"to":313}} {"id":100009389,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"pkg/registry/core/namespace/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":315,"to":319}} {"id":100009390,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/core/namespace/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":321,"to":324}} {"id":100009391,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/core/namespace/storage/storage.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":326,"to":331}} {"id":100009392,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/namespace/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":333,"to":336}} {"id":100009393,"name":"ConvertToTable","signature":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/core/namespace/storage/storage.go","code":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":338,"to":340}} {"id":100009394,"name":"New","signature":"func (r *FinalizeREST) New() runtime.Object","file":"pkg/registry/core/namespace/storage/storage.go","code":"func (r *FinalizeREST) New() runtime.Object {\n\treturn r.store.New()\n}","line":{"from":342,"to":344}} {"id":100009395,"name":"Destroy","signature":"func (r *FinalizeREST) Destroy()","file":"pkg/registry/core/namespace/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *FinalizeREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":346,"to":350}} {"id":100009396,"name":"Update","signature":"func (r *FinalizeREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/core/namespace/storage/storage.go","code":"// Update alters the status finalizers subset of an object.\nfunc (r *FinalizeREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":352,"to":357}} {"id":100009397,"name":"GetResetFields","signature":"func (r *FinalizeREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/namespace/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *FinalizeREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":359,"to":362}} {"id":100009398,"name":"NamespaceScoped","signature":"func (namespaceStrategy) NamespaceScoped() bool","file":"pkg/registry/core/namespace/strategy.go","code":"// NamespaceScoped is false for namespaces.\nfunc (namespaceStrategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":47,"to":50}} {"id":100009399,"name":"GetResetFields","signature":"func (namespaceStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/namespace/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (namespaceStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n}","line":{"from":52,"to":60}} {"id":100009400,"name":"PrepareForCreate","signature":"func (namespaceStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/core/namespace/strategy.go","code":"// PrepareForCreate clears fields that are not allowed to be set by end users on creation.\nfunc (namespaceStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\t// on create, status is active\n\tnamespace := obj.(*api.Namespace)\n\tnamespace.Status = api.NamespaceStatus{\n\t\tPhase: api.NamespaceActive,\n\t}\n\t// on create, we require the kubernetes value\n\t// we cannot use this in defaults conversion because we let it get removed over life of object\n\thasKubeFinalizer := false\n\tfor i := range namespace.Spec.Finalizers {\n\t\tif namespace.Spec.Finalizers[i] == api.FinalizerKubernetes {\n\t\t\thasKubeFinalizer = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !hasKubeFinalizer {\n\t\tif len(namespace.Spec.Finalizers) == 0 {\n\t\t\tnamespace.Spec.Finalizers = []api.FinalizerName{api.FinalizerKubernetes}\n\t\t} else {\n\t\t\tnamespace.Spec.Finalizers = append(namespace.Spec.Finalizers, api.FinalizerKubernetes)\n\t\t}\n\t}\n}","line":{"from":62,"to":85}} {"id":100009401,"name":"PrepareForUpdate","signature":"func (namespaceStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/core/namespace/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (namespaceStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewNamespace := obj.(*api.Namespace)\n\toldNamespace := old.(*api.Namespace)\n\tnewNamespace.Spec.Finalizers = oldNamespace.Spec.Finalizers\n\tnewNamespace.Status = oldNamespace.Status\n}","line":{"from":87,"to":93}} {"id":100009402,"name":"Validate","signature":"func (namespaceStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/core/namespace/strategy.go","code":"// Validate validates a new namespace.\nfunc (namespaceStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tnamespace := obj.(*api.Namespace)\n\treturn validation.ValidateNamespace(namespace)\n}","line":{"from":95,"to":99}} {"id":100009403,"name":"WarningsOnCreate","signature":"func (namespaceStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/core/namespace/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (namespaceStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":101,"to":104}} {"id":100009404,"name":"Canonicalize","signature":"func (namespaceStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/core/namespace/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (namespaceStrategy) Canonicalize(obj runtime.Object) {\n\t// Ensure the label matches the name for namespaces just created using GenerateName,\n\t// where the final name wasn't available for defaulting to make this change.\n\t// This code needs to be kept in sync with the implementation that exists\n\t// in Namespace defaulting (pkg/apis/core/v1)\n\t// Why this hook *and* defaults.go?\n\t//\n\t// CREATE:\n\t// Defaulting and PrepareForCreate happen before generateName is completed\n\t// (i.e. the name is not yet known). Validation happens after generateName\n\t// but should not modify objects. Canonicalize happens later, which makes\n\t// it the best hook for setting the label.\n\t//\n\t// UPDATE:\n\t// Defaulting and Canonicalize will both trigger with the full name.\n\t//\n\t// GET:\n\t// Only defaulting will be applied.\n\tns := obj.(*api.Namespace)\n\tif ns.Labels == nil {\n\t\tns.Labels = map[string]string{}\n\t}\n\tns.Labels[v1.LabelMetadataName] = ns.Name\n}","line":{"from":106,"to":130}} {"id":100009405,"name":"AllowCreateOnUpdate","signature":"func (namespaceStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/core/namespace/strategy.go","code":"// AllowCreateOnUpdate is false for namespaces.\nfunc (namespaceStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":132,"to":135}} {"id":100009406,"name":"ValidateUpdate","signature":"func (namespaceStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/core/namespace/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (namespaceStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\terrorList := validation.ValidateNamespace(obj.(*api.Namespace))\n\treturn append(errorList, validation.ValidateNamespaceUpdate(obj.(*api.Namespace), old.(*api.Namespace))...)\n}","line":{"from":137,"to":141}} {"id":100009407,"name":"WarningsOnUpdate","signature":"func (namespaceStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/core/namespace/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (namespaceStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":143,"to":146}} {"id":100009408,"name":"AllowUnconditionalUpdate","signature":"func (namespaceStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/core/namespace/strategy.go","code":"func (namespaceStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":148,"to":150}} {"id":100009409,"name":"GetResetFields","signature":"func (namespaceStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/namespace/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (namespaceStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t}\n}","line":{"from":158,"to":166}} {"id":100009410,"name":"PrepareForUpdate","signature":"func (namespaceStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/core/namespace/strategy.go","code":"func (namespaceStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewNamespace := obj.(*api.Namespace)\n\toldNamespace := old.(*api.Namespace)\n\tnewNamespace.Spec = oldNamespace.Spec\n}","line":{"from":168,"to":172}} {"id":100009411,"name":"ValidateUpdate","signature":"func (namespaceStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/core/namespace/strategy.go","code":"func (namespaceStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateNamespaceStatusUpdate(obj.(*api.Namespace), old.(*api.Namespace))\n}","line":{"from":174,"to":176}} {"id":100009412,"name":"WarningsOnUpdate","signature":"func (namespaceStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/core/namespace/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (namespaceStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":178,"to":181}} {"id":100009413,"name":"ValidateUpdate","signature":"func (namespaceFinalizeStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/core/namespace/strategy.go","code":"func (namespaceFinalizeStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateNamespaceFinalizeUpdate(obj.(*api.Namespace), old.(*api.Namespace))\n}","line":{"from":189,"to":191}} {"id":100009414,"name":"WarningsOnUpdate","signature":"func (namespaceFinalizeStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/core/namespace/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (namespaceFinalizeStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":193,"to":196}} {"id":100009415,"name":"GetResetFields","signature":"func (namespaceFinalizeStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/namespace/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (namespaceFinalizeStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n}","line":{"from":198,"to":206}} {"id":100009416,"name":"PrepareForUpdate","signature":"func (namespaceFinalizeStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/core/namespace/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (namespaceFinalizeStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewNamespace := obj.(*api.Namespace)\n\toldNamespace := old.(*api.Namespace)\n\tnewNamespace.Status = oldNamespace.Status\n}","line":{"from":208,"to":213}} {"id":100009417,"name":"GetAttrs","signature":"func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error)","file":"pkg/registry/core/namespace/strategy.go","code":"// GetAttrs returns labels and fields of a given object for filtering purposes.\nfunc GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {\n\tnamespaceObj, ok := obj.(*api.Namespace)\n\tif !ok {\n\t\treturn nil, nil, fmt.Errorf(\"not a namespace\")\n\t}\n\treturn labels.Set(namespaceObj.Labels), NamespaceToSelectableFields(namespaceObj), nil\n}","line":{"from":215,"to":222}} {"id":100009418,"name":"MatchNamespace","signature":"func MatchNamespace(label labels.Selector, field fields.Selector) apistorage.SelectionPredicate","file":"pkg/registry/core/namespace/strategy.go","code":"// MatchNamespace returns a generic matcher for a given label and field selector.\nfunc MatchNamespace(label labels.Selector, field fields.Selector) apistorage.SelectionPredicate {\n\treturn apistorage.SelectionPredicate{\n\t\tLabel: label,\n\t\tField: field,\n\t\tGetAttrs: GetAttrs,\n\t}\n}","line":{"from":224,"to":231}} {"id":100009419,"name":"NamespaceToSelectableFields","signature":"func NamespaceToSelectableFields(namespace *api.Namespace) fields.Set","file":"pkg/registry/core/namespace/strategy.go","code":"// NamespaceToSelectableFields returns a field set that represents the object\nfunc NamespaceToSelectableFields(namespace *api.Namespace) fields.Set {\n\tobjectMetaFieldsSet := generic.ObjectMetaFieldsSet(\u0026namespace.ObjectMeta, false)\n\tspecificFieldsSet := fields.Set{\n\t\t\"status.phase\": string(namespace.Status.Phase),\n\t\t// This is a bug, but we need to support it for backward compatibility.\n\t\t\"name\": namespace.Name,\n\t}\n\treturn generic.MergeFieldsSets(objectMetaFieldsSet, specificFieldsSet)\n}","line":{"from":233,"to":242}} {"id":100009420,"name":"New","signature":"func (r *ProxyREST) New() runtime.Object","file":"pkg/registry/core/node/rest/proxy.go","code":"// New returns an empty nodeProxyOptions object.\nfunc (r *ProxyREST) New() runtime.Object {\n\treturn \u0026api.NodeProxyOptions{}\n}","line":{"from":48,"to":51}} {"id":100009421,"name":"Destroy","signature":"func (r *ProxyREST) Destroy()","file":"pkg/registry/core/node/rest/proxy.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *ProxyREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":53,"to":57}} {"id":100009422,"name":"ConnectMethods","signature":"func (r *ProxyREST) ConnectMethods() []string","file":"pkg/registry/core/node/rest/proxy.go","code":"// ConnectMethods returns the list of HTTP methods that can be proxied\nfunc (r *ProxyREST) ConnectMethods() []string {\n\treturn proxyMethods\n}","line":{"from":59,"to":62}} {"id":100009423,"name":"NewConnectOptions","signature":"func (r *ProxyREST) NewConnectOptions() (runtime.Object, bool, string)","file":"pkg/registry/core/node/rest/proxy.go","code":"// NewConnectOptions returns versioned resource that represents proxy parameters\nfunc (r *ProxyREST) NewConnectOptions() (runtime.Object, bool, string) {\n\treturn \u0026api.NodeProxyOptions{}, true, \"path\"\n}","line":{"from":64,"to":67}} {"id":100009424,"name":"Connect","signature":"func (r *ProxyREST) Connect(ctx context.Context, id string, opts runtime.Object, responder rest.Responder) (http.Handler, error)","file":"pkg/registry/core/node/rest/proxy.go","code":"// Connect returns a handler for the node proxy\nfunc (r *ProxyREST) Connect(ctx context.Context, id string, opts runtime.Object, responder rest.Responder) (http.Handler, error) {\n\tproxyOpts, ok := opts.(*api.NodeProxyOptions)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Invalid options object: %#v\", opts)\n\t}\n\tlocation, transport, err := node.ResourceLocation(r.Store, r.Connection, r.ProxyTransport, ctx, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlocation.Path = net.JoinPreservingTrailingSlash(location.Path, proxyOpts.Path)\n\t// Return a proxy handler that uses the desired transport, wrapped with additional proxy handling (to get URL rewriting, X-Forwarded-* headers, etc)\n\treturn newThrottledUpgradeAwareProxyHandler(location, transport, true, false, responder), nil\n}","line":{"from":69,"to":82}} {"id":100009425,"name":"newThrottledUpgradeAwareProxyHandler","signature":"func newThrottledUpgradeAwareProxyHandler(location *url.URL, transport http.RoundTripper, wrapTransport, upgradeRequired bool, responder rest.Responder) *proxy.UpgradeAwareHandler","file":"pkg/registry/core/node/rest/proxy.go","code":"func newThrottledUpgradeAwareProxyHandler(location *url.URL, transport http.RoundTripper, wrapTransport, upgradeRequired bool, responder rest.Responder) *proxy.UpgradeAwareHandler {\n\thandler := proxy.NewUpgradeAwareHandler(location, transport, wrapTransport, upgradeRequired, proxy.NewErrorResponder(responder))\n\thandler.MaxBytesPerSec = capabilities.Get().PerConnectionBandwidthLimitBytesPerSec\n\treturn handler\n}","line":{"from":84,"to":88}} {"id":100009426,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"pkg/registry/core/node/storage/storage.go","code":"// New creates a new Node object.\nfunc (r *StatusREST) New() runtime.Object {\n\treturn \u0026api.Node{}\n}","line":{"from":63,"to":66}} {"id":100009427,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"pkg/registry/core/node/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":68,"to":72}} {"id":100009428,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/core/node/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":74,"to":77}} {"id":100009429,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/core/node/storage/storage.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":79,"to":84}} {"id":100009430,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/node/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":86,"to":89}} {"id":100009431,"name":"ConvertToTable","signature":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/core/node/storage/storage.go","code":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":91,"to":93}} {"id":100009432,"name":"NewStorage","signature":"func NewStorage(optsGetter generic.RESTOptionsGetter, kubeletClientConfig client.KubeletClientConfig, proxyTransport http.RoundTripper) (*NodeStorage, error)","file":"pkg/registry/core/node/storage/storage.go","code":"// NewStorage returns a NodeStorage object that will work against nodes.\nfunc NewStorage(optsGetter generic.RESTOptionsGetter, kubeletClientConfig client.KubeletClientConfig, proxyTransport http.RoundTripper) (*NodeStorage, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026api.Node{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026api.NodeList{} },\n\t\tPredicateFunc: node.MatchNode,\n\t\tDefaultQualifiedResource: api.Resource(\"nodes\"),\n\t\tSingularQualifiedResource: api.Resource(\"node\"),\n\n\t\tCreateStrategy: node.Strategy,\n\t\tUpdateStrategy: node.Strategy,\n\t\tDeleteStrategy: node.Strategy,\n\t\tResetFieldsStrategy: node.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{\n\t\tRESTOptions: optsGetter,\n\t\tAttrFunc: node.GetAttrs,\n\t}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = node.StatusStrategy\n\tstatusStore.ResetFieldsStrategy = node.StatusStrategy\n\n\t// Set up REST handlers\n\tnodeREST := \u0026REST{Store: store, proxyTransport: proxyTransport}\n\tstatusREST := \u0026StatusREST{store: \u0026statusStore}\n\tproxyREST := \u0026noderest.ProxyREST{Store: store, ProxyTransport: proxyTransport}\n\n\t// Build a NodeGetter that looks up nodes using the REST handler\n\tnodeGetter := client.NodeGetterFunc(func(ctx context.Context, nodeName string, options metav1.GetOptions) (*v1.Node, error) {\n\t\tobj, err := nodeREST.Get(ctx, nodeName, \u0026options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tnode, ok := obj.(*api.Node)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"unexpected type %T\", obj)\n\t\t}\n\t\t// TODO: Remove the conversion. Consider only return the NodeAddresses\n\t\texternalNode := \u0026v1.Node{}\n\t\terr = k8s_api_v1.Convert_core_Node_To_v1_Node(node, externalNode, nil)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to convert to v1.Node: %v\", err)\n\t\t}\n\t\treturn externalNode, nil\n\t})\n\tconnectionInfoGetter, err := client.NewNodeConnectionInfoGetter(nodeGetter, kubeletClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnodeREST.connection = connectionInfoGetter\n\tproxyREST.Connection = connectionInfoGetter\n\n\treturn \u0026NodeStorage{\n\t\tNode: nodeREST,\n\t\tStatus: statusREST,\n\t\tProxy: proxyREST,\n\t\tKubeletConnectionInfo: connectionInfoGetter,\n\t}, nil\n}","line":{"from":95,"to":159}} {"id":100009433,"name":"ResourceLocation","signature":"func (r *REST) ResourceLocation(ctx context.Context, id string) (*url.URL, http.RoundTripper, error)","file":"pkg/registry/core/node/storage/storage.go","code":"// ResourceLocation returns a URL to which one can send traffic for the specified node.\nfunc (r *REST) ResourceLocation(ctx context.Context, id string) (*url.URL, http.RoundTripper, error) {\n\treturn node.ResourceLocation(r, r.connection, r.proxyTransport, ctx, id)\n}","line":{"from":164,"to":167}} {"id":100009434,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/core/node/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"no\"}\n}","line":{"from":169,"to":172}} {"id":100009435,"name":"NamespaceScoped","signature":"func (nodeStrategy) NamespaceScoped() bool","file":"pkg/registry/core/node/strategy.go","code":"// NamespaceScoped is false for nodes.\nfunc (nodeStrategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":55,"to":58}} {"id":100009436,"name":"GetResetFields","signature":"func (nodeStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/node/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (nodeStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":60,"to":70}} {"id":100009437,"name":"AllowCreateOnUpdate","signature":"func (nodeStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/core/node/strategy.go","code":"// AllowCreateOnUpdate is false for nodes.\nfunc (nodeStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":72,"to":75}} {"id":100009438,"name":"PrepareForCreate","signature":"func (nodeStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/core/node/strategy.go","code":"// PrepareForCreate clears fields that are not allowed to be set by end users on creation.\nfunc (nodeStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tnode := obj.(*api.Node)\n\tdropDisabledFields(node, nil)\n}","line":{"from":77,"to":81}} {"id":100009439,"name":"PrepareForUpdate","signature":"func (nodeStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/core/node/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (nodeStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewNode := obj.(*api.Node)\n\toldNode := old.(*api.Node)\n\tnewNode.Status = oldNode.Status\n\n\tdropDisabledFields(newNode, oldNode)\n}","line":{"from":83,"to":90}} {"id":100009440,"name":"dropDisabledFields","signature":"func dropDisabledFields(node *api.Node, oldNode *api.Node)","file":"pkg/registry/core/node/strategy.go","code":"func dropDisabledFields(node *api.Node, oldNode *api.Node) {\n\t// Nodes allow *all* fields, including status, to be set on create.\n\t// for create\n\tif oldNode == nil {\n\t\tnode.Spec.ConfigSource = nil\n\t\tnode.Status.Config = nil\n\t}\n\n\t// for update\n\tif !nodeConfigSourceInUse(oldNode) \u0026\u0026 oldNode != nil {\n\t\tnode.Spec.ConfigSource = nil\n\t}\n\n}","line":{"from":92,"to":105}} {"id":100009441,"name":"nodeConfigSourceInUse","signature":"func nodeConfigSourceInUse(node *api.Node) bool","file":"pkg/registry/core/node/strategy.go","code":"// nodeConfigSourceInUse returns true if node's Spec ConfigSource is set(used)\nfunc nodeConfigSourceInUse(node *api.Node) bool {\n\tif node == nil {\n\t\treturn false\n\t}\n\tif node.Spec.ConfigSource != nil {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":107,"to":116}} {"id":100009442,"name":"Validate","signature":"func (nodeStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/core/node/strategy.go","code":"// Validate validates a new node.\nfunc (nodeStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tnode := obj.(*api.Node)\n\treturn validation.ValidateNode(node)\n}","line":{"from":118,"to":122}} {"id":100009443,"name":"WarningsOnCreate","signature":"func (nodeStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/core/node/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (nodeStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn fieldIsDeprecatedWarnings(obj)\n}","line":{"from":124,"to":127}} {"id":100009444,"name":"Canonicalize","signature":"func (nodeStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/core/node/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (nodeStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":129,"to":131}} {"id":100009445,"name":"ValidateUpdate","signature":"func (nodeStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/core/node/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (nodeStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\terrorList := validation.ValidateNode(obj.(*api.Node))\n\treturn append(errorList, validation.ValidateNodeUpdate(obj.(*api.Node), old.(*api.Node))...)\n}","line":{"from":133,"to":137}} {"id":100009446,"name":"WarningsOnUpdate","signature":"func (nodeStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/core/node/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (nodeStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn fieldIsDeprecatedWarnings(obj)\n}","line":{"from":139,"to":142}} {"id":100009447,"name":"AllowUnconditionalUpdate","signature":"func (nodeStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/core/node/strategy.go","code":"func (nodeStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":144,"to":146}} {"id":100009448,"name":"GetResetFields","signature":"func (nodeStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/node/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (nodeStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":154,"to":164}} {"id":100009449,"name":"PrepareForUpdate","signature":"func (nodeStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/core/node/strategy.go","code":"func (nodeStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewNode := obj.(*api.Node)\n\toldNode := old.(*api.Node)\n\tnewNode.Spec = oldNode.Spec\n\n\tif !nodeStatusConfigInUse(oldNode) {\n\t\tnewNode.Status.Config = nil\n\t}\n}","line":{"from":166,"to":174}} {"id":100009450,"name":"nodeStatusConfigInUse","signature":"func nodeStatusConfigInUse(node *api.Node) bool","file":"pkg/registry/core/node/strategy.go","code":"// nodeStatusConfigInUse returns true if node's Status Config is set(used)\nfunc nodeStatusConfigInUse(node *api.Node) bool {\n\tif node == nil {\n\t\treturn false\n\t}\n\tif node.Status.Config != nil {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":176,"to":185}} {"id":100009451,"name":"ValidateUpdate","signature":"func (nodeStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/core/node/strategy.go","code":"func (nodeStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateNodeUpdate(obj.(*api.Node), old.(*api.Node))\n}","line":{"from":187,"to":189}} {"id":100009452,"name":"WarningsOnUpdate","signature":"func (nodeStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/core/node/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (nodeStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":191,"to":194}} {"id":100009453,"name":"Canonicalize","signature":"func (nodeStatusStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/core/node/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (nodeStatusStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":196,"to":198}} {"id":100009454,"name":"NodeToSelectableFields","signature":"func NodeToSelectableFields(node *api.Node) fields.Set","file":"pkg/registry/core/node/strategy.go","code":"// NodeToSelectableFields returns a field set that represents the object.\nfunc NodeToSelectableFields(node *api.Node) fields.Set {\n\tobjectMetaFieldsSet := generic.ObjectMetaFieldsSet(\u0026node.ObjectMeta, false)\n\tspecificFieldsSet := fields.Set{\n\t\t\"spec.unschedulable\": fmt.Sprint(node.Spec.Unschedulable),\n\t}\n\treturn generic.MergeFieldsSets(objectMetaFieldsSet, specificFieldsSet)\n}","line":{"from":205,"to":212}} {"id":100009455,"name":"GetAttrs","signature":"func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error)","file":"pkg/registry/core/node/strategy.go","code":"// GetAttrs returns labels and fields of a given object for filtering purposes.\nfunc GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {\n\tnodeObj, ok := obj.(*api.Node)\n\tif !ok {\n\t\treturn nil, nil, fmt.Errorf(\"not a node\")\n\t}\n\treturn labels.Set(nodeObj.ObjectMeta.Labels), NodeToSelectableFields(nodeObj), nil\n}","line":{"from":214,"to":221}} {"id":100009456,"name":"MatchNode","signature":"func MatchNode(label labels.Selector, field fields.Selector) pkgstorage.SelectionPredicate","file":"pkg/registry/core/node/strategy.go","code":"// MatchNode returns a generic matcher for a given label and field selector.\nfunc MatchNode(label labels.Selector, field fields.Selector) pkgstorage.SelectionPredicate {\n\treturn pkgstorage.SelectionPredicate{\n\t\tLabel: label,\n\t\tField: field,\n\t\tGetAttrs: GetAttrs,\n\t}\n}","line":{"from":223,"to":230}} {"id":100009457,"name":"ResourceLocation","signature":"func ResourceLocation(getter ResourceGetter, connection client.ConnectionInfoGetter, proxyTransport http.RoundTripper, ctx context.Context, id string) (*url.URL, http.RoundTripper, error)","file":"pkg/registry/core/node/strategy.go","code":"// ResourceLocation returns a URL and transport which one can use to send traffic for the specified node.\nfunc ResourceLocation(getter ResourceGetter, connection client.ConnectionInfoGetter, proxyTransport http.RoundTripper, ctx context.Context, id string) (*url.URL, http.RoundTripper, error) {\n\tschemeReq, name, portReq, valid := utilnet.SplitSchemeNamePort(id)\n\tif !valid {\n\t\treturn nil, nil, errors.NewBadRequest(fmt.Sprintf(\"invalid node request %q\", id))\n\t}\n\n\tinfo, err := connection.GetConnectionInfo(ctx, types.NodeName(name))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif err := proxyutil.IsProxyableHostname(ctx, \u0026net.Resolver{}, info.Hostname); err != nil {\n\t\treturn nil, nil, errors.NewBadRequest(err.Error())\n\t}\n\n\t// We check if we want to get a default Kubelet's transport. It happens if either:\n\t// - no port is specified in request (Kubelet's port is default)\n\t// - the requested port matches the kubelet port for this node\n\tif portReq == \"\" || portReq == info.Port {\n\t\treturn \u0026url.URL{\n\t\t\t\tScheme: info.Scheme,\n\t\t\t\tHost: net.JoinHostPort(info.Hostname, info.Port),\n\t\t\t},\n\t\t\tinfo.Transport,\n\t\t\tnil\n\t}\n\n\t// Otherwise, return the requested scheme and port, and the proxy transport\n\treturn \u0026url.URL{Scheme: schemeReq, Host: net.JoinHostPort(info.Hostname, portReq)}, proxyTransport, nil\n}","line":{"from":232,"to":262}} {"id":100009458,"name":"fieldIsDeprecatedWarnings","signature":"func fieldIsDeprecatedWarnings(obj runtime.Object) []string","file":"pkg/registry/core/node/strategy.go","code":"func fieldIsDeprecatedWarnings(obj runtime.Object) []string {\n\tnewNode := obj.(*api.Node)\n\tvar warnings []string\n\tif newNode.Spec.ConfigSource != nil {\n\t\t// KEP https://github.com/kubernetes/enhancements/issues/281\n\t\twarnings = append(warnings, \"spec.configSource: the feature is removed\")\n\t}\n\tif len(newNode.Spec.DoNotUseExternalID) \u003e 0 {\n\t\twarnings = append(warnings, \"spec.externalID: this field is deprecated, and is unused by Kubernetes\")\n\t}\n\treturn warnings\n}","line":{"from":264,"to":275}} {"id":100009459,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error)","file":"pkg/registry/core/persistentvolume/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against persistent volumes.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026api.PersistentVolume{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026api.PersistentVolumeList{} },\n\t\tPredicateFunc: persistentvolume.MatchPersistentVolumes,\n\t\tDefaultQualifiedResource: api.Resource(\"persistentvolumes\"),\n\t\tSingularQualifiedResource: api.Resource(\"persistentvolume\"),\n\n\t\tCreateStrategy: persistentvolume.Strategy,\n\t\tUpdateStrategy: persistentvolume.Strategy,\n\t\tDeleteStrategy: persistentvolume.Strategy,\n\t\tReturnDeletedObject: true,\n\t\tResetFieldsStrategy: persistentvolume.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: persistentvolume.GetAttrs}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = persistentvolume.StatusStrategy\n\tstatusStore.ResetFieldsStrategy = persistentvolume.StatusStrategy\n\n\treturn \u0026REST{store}, \u0026StatusREST{store: \u0026statusStore}, nil\n}","line":{"from":40,"to":67}} {"id":100009460,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/core/persistentvolume/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"pv\"}\n}","line":{"from":72,"to":75}} {"id":100009461,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"pkg/registry/core/persistentvolume/storage/storage.go","code":"// New creates a new PersistentVolume object.\nfunc (r *StatusREST) New() runtime.Object {\n\treturn \u0026api.PersistentVolume{}\n}","line":{"from":82,"to":85}} {"id":100009462,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"pkg/registry/core/persistentvolume/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":87,"to":91}} {"id":100009463,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/core/persistentvolume/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":93,"to":96}} {"id":100009464,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/core/persistentvolume/storage/storage.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":98,"to":103}} {"id":100009465,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/persistentvolume/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":105,"to":108}} {"id":100009466,"name":"ConvertToTable","signature":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/core/persistentvolume/storage/storage.go","code":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":110,"to":112}} {"id":100009467,"name":"NamespaceScoped","signature":"func (persistentvolumeStrategy) NamespaceScoped() bool","file":"pkg/registry/core/persistentvolume/strategy.go","code":"func (persistentvolumeStrategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":48,"to":50}} {"id":100009468,"name":"GetResetFields","signature":"func (persistentvolumeStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/persistentvolume/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (persistentvolumeStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":52,"to":62}} {"id":100009469,"name":"PrepareForCreate","signature":"func (persistentvolumeStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/core/persistentvolume/strategy.go","code":"// ResetBeforeCreate clears the Status field which is not allowed to be set by end users on creation.\nfunc (persistentvolumeStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tpv := obj.(*api.PersistentVolume)\n\tpv.Status = api.PersistentVolumeStatus{}\n\n\tpvutil.DropDisabledFields(\u0026pv.Spec, nil)\n}","line":{"from":64,"to":70}} {"id":100009470,"name":"Validate","signature":"func (persistentvolumeStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/core/persistentvolume/strategy.go","code":"func (persistentvolumeStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tpersistentvolume := obj.(*api.PersistentVolume)\n\topts := validation.ValidationOptionsForPersistentVolume(persistentvolume, nil)\n\terrorList := validation.ValidatePersistentVolume(persistentvolume, opts)\n\treturn append(errorList, volumevalidation.ValidatePersistentVolume(persistentvolume)...)\n}","line":{"from":72,"to":77}} {"id":100009471,"name":"WarningsOnCreate","signature":"func (persistentvolumeStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/core/persistentvolume/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (persistentvolumeStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn pvutil.GetWarningsForPersistentVolume(obj.(*api.PersistentVolume))\n}","line":{"from":79,"to":82}} {"id":100009472,"name":"Canonicalize","signature":"func (persistentvolumeStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/core/persistentvolume/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (persistentvolumeStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":84,"to":86}} {"id":100009473,"name":"AllowCreateOnUpdate","signature":"func (persistentvolumeStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/core/persistentvolume/strategy.go","code":"func (persistentvolumeStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":88,"to":90}} {"id":100009474,"name":"PrepareForUpdate","signature":"func (persistentvolumeStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/core/persistentvolume/strategy.go","code":"// PrepareForUpdate sets the Status fields which is not allowed to be set by an end user updating a PV\nfunc (persistentvolumeStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewPv := obj.(*api.PersistentVolume)\n\toldPv := old.(*api.PersistentVolume)\n\tnewPv.Status = oldPv.Status\n\n\tpvutil.DropDisabledFields(\u0026newPv.Spec, \u0026oldPv.Spec)\n}","line":{"from":92,"to":99}} {"id":100009475,"name":"ValidateUpdate","signature":"func (persistentvolumeStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/core/persistentvolume/strategy.go","code":"func (persistentvolumeStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewPv := obj.(*api.PersistentVolume)\n\toldPv := old.(*api.PersistentVolume)\n\topts := validation.ValidationOptionsForPersistentVolume(newPv, oldPv)\n\terrorList := validation.ValidatePersistentVolume(newPv, opts)\n\terrorList = append(errorList, volumevalidation.ValidatePersistentVolume(newPv)...)\n\treturn append(errorList, validation.ValidatePersistentVolumeUpdate(newPv, oldPv, opts)...)\n}","line":{"from":101,"to":108}} {"id":100009476,"name":"WarningsOnUpdate","signature":"func (persistentvolumeStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/core/persistentvolume/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (persistentvolumeStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn pvutil.GetWarningsForPersistentVolume(obj.(*api.PersistentVolume))\n}","line":{"from":110,"to":113}} {"id":100009477,"name":"AllowUnconditionalUpdate","signature":"func (persistentvolumeStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/core/persistentvolume/strategy.go","code":"func (persistentvolumeStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":115,"to":117}} {"id":100009478,"name":"GetResetFields","signature":"func (persistentvolumeStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/persistentvolume/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (persistentvolumeStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":125,"to":135}} {"id":100009479,"name":"PrepareForUpdate","signature":"func (persistentvolumeStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/core/persistentvolume/strategy.go","code":"// PrepareForUpdate sets the Spec field which is not allowed to be changed when updating a PV's Status\nfunc (persistentvolumeStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewPv := obj.(*api.PersistentVolume)\n\toldPv := old.(*api.PersistentVolume)\n\tnewPv.Spec = oldPv.Spec\n}","line":{"from":137,"to":142}} {"id":100009480,"name":"ValidateUpdate","signature":"func (persistentvolumeStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/core/persistentvolume/strategy.go","code":"func (persistentvolumeStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidatePersistentVolumeStatusUpdate(obj.(*api.PersistentVolume), old.(*api.PersistentVolume))\n}","line":{"from":144,"to":146}} {"id":100009481,"name":"WarningsOnUpdate","signature":"func (persistentvolumeStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/core/persistentvolume/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (persistentvolumeStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":148,"to":151}} {"id":100009482,"name":"GetAttrs","signature":"func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error)","file":"pkg/registry/core/persistentvolume/strategy.go","code":"// GetAttrs returns labels and fields of a given object for filtering purposes.\nfunc GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {\n\tpersistentvolumeObj, ok := obj.(*api.PersistentVolume)\n\tif !ok {\n\t\treturn nil, nil, fmt.Errorf(\"not a persistentvolume\")\n\t}\n\treturn labels.Set(persistentvolumeObj.Labels), PersistentVolumeToSelectableFields(persistentvolumeObj), nil\n}","line":{"from":153,"to":160}} {"id":100009483,"name":"MatchPersistentVolumes","signature":"func MatchPersistentVolumes(label labels.Selector, field fields.Selector) storage.SelectionPredicate","file":"pkg/registry/core/persistentvolume/strategy.go","code":"// MatchPersistentVolume returns a generic matcher for a given label and field selector.\nfunc MatchPersistentVolumes(label labels.Selector, field fields.Selector) storage.SelectionPredicate {\n\treturn storage.SelectionPredicate{\n\t\tLabel: label,\n\t\tField: field,\n\t\tGetAttrs: GetAttrs,\n\t}\n}","line":{"from":162,"to":169}} {"id":100009484,"name":"PersistentVolumeToSelectableFields","signature":"func PersistentVolumeToSelectableFields(persistentvolume *api.PersistentVolume) fields.Set","file":"pkg/registry/core/persistentvolume/strategy.go","code":"// PersistentVolumeToSelectableFields returns a field set that represents the object\nfunc PersistentVolumeToSelectableFields(persistentvolume *api.PersistentVolume) fields.Set {\n\tobjectMetaFieldsSet := generic.ObjectMetaFieldsSet(\u0026persistentvolume.ObjectMeta, false)\n\tspecificFieldsSet := fields.Set{\n\t\t// This is a bug, but we need to support it for backward compatibility.\n\t\t\"name\": persistentvolume.Name,\n\t}\n\treturn generic.MergeFieldsSets(objectMetaFieldsSet, specificFieldsSet)\n}","line":{"from":171,"to":179}} {"id":100009485,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error)","file":"pkg/registry/core/persistentvolumeclaim/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against persistent volume claims.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026api.PersistentVolumeClaim{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026api.PersistentVolumeClaimList{} },\n\t\tPredicateFunc: persistentvolumeclaim.MatchPersistentVolumeClaim,\n\t\tDefaultQualifiedResource: api.Resource(\"persistentvolumeclaims\"),\n\t\tSingularQualifiedResource: api.Resource(\"persistentvolumeclaim\"),\n\n\t\tCreateStrategy: persistentvolumeclaim.Strategy,\n\t\tUpdateStrategy: persistentvolumeclaim.Strategy,\n\t\tDeleteStrategy: persistentvolumeclaim.Strategy,\n\t\tReturnDeletedObject: true,\n\t\tResetFieldsStrategy: persistentvolumeclaim.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: persistentvolumeclaim.GetAttrs}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = persistentvolumeclaim.StatusStrategy\n\tstatusStore.ResetFieldsStrategy = persistentvolumeclaim.StatusStrategy\n\n\trest := \u0026REST{store}\n\tstore.Decorator = rest.defaultOnRead\n\n\treturn rest, \u0026StatusREST{store: \u0026statusStore}, nil\n}","line":{"from":41,"to":71}} {"id":100009486,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/core/persistentvolumeclaim/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"pvc\"}\n}","line":{"from":76,"to":79}} {"id":100009487,"name":"defaultOnRead","signature":"func (r *REST) defaultOnRead(obj runtime.Object)","file":"pkg/registry/core/persistentvolumeclaim/storage/storage.go","code":"// defaultOnRead sets interlinked fields that were not previously set on read.\n// We can't do this in the normal defaulting path because that same logic\n// applies on Get, Create, and Update, but we need to distinguish between them.\n//\n// This will be called on both PersistentVolumeClaim and PersistentVolumeClaimList types.\nfunc (r *REST) defaultOnRead(obj runtime.Object) {\n\tswitch s := obj.(type) {\n\tcase *api.PersistentVolumeClaim:\n\t\tr.defaultOnReadPvc(s)\n\tcase *api.PersistentVolumeClaimList:\n\t\tr.defaultOnReadPvcList(s)\n\tdefault:\n\t\t// This was not an object we can default. This is not an error, as the\n\t\t// caching layer can pass through here, too.\n\t}\n}","line":{"from":81,"to":96}} {"id":100009488,"name":"defaultOnReadPvcList","signature":"func (r *REST) defaultOnReadPvcList(pvcList *api.PersistentVolumeClaimList)","file":"pkg/registry/core/persistentvolumeclaim/storage/storage.go","code":"// defaultOnReadPvcList defaults a PersistentVolumeClaimList.\nfunc (r *REST) defaultOnReadPvcList(pvcList *api.PersistentVolumeClaimList) {\n\tif pvcList == nil {\n\t\treturn\n\t}\n\n\tfor i := range pvcList.Items {\n\t\tr.defaultOnReadPvc(\u0026pvcList.Items[i])\n\t}\n}","line":{"from":98,"to":107}} {"id":100009489,"name":"defaultOnReadPvc","signature":"func (r *REST) defaultOnReadPvc(pvc *api.PersistentVolumeClaim)","file":"pkg/registry/core/persistentvolumeclaim/storage/storage.go","code":"// defaultOnReadPvc defaults a single PersistentVolumeClaim.\nfunc (r *REST) defaultOnReadPvc(pvc *api.PersistentVolumeClaim) {\n\tif pvc == nil {\n\t\treturn\n\t}\n\n\t// We set dataSourceRef to the same value as dataSource at creation time now,\n\t// but for pre-existing PVCs with data sources, the dataSourceRef field will\n\t// be blank, so we fill it in here at read time.\n\tpvcutil.NormalizeDataSources(\u0026pvc.Spec)\n}","line":{"from":109,"to":119}} {"id":100009490,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"pkg/registry/core/persistentvolumeclaim/storage/storage.go","code":"// New creates a new PersistentVolumeClaim object.\nfunc (r *StatusREST) New() runtime.Object {\n\treturn \u0026api.PersistentVolumeClaim{}\n}","line":{"from":126,"to":129}} {"id":100009491,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"pkg/registry/core/persistentvolumeclaim/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":131,"to":135}} {"id":100009492,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/core/persistentvolumeclaim/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":137,"to":140}} {"id":100009493,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/core/persistentvolumeclaim/storage/storage.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":142,"to":147}} {"id":100009494,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/persistentvolumeclaim/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":149,"to":152}} {"id":100009495,"name":"ConvertToTable","signature":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/core/persistentvolumeclaim/storage/storage.go","code":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":154,"to":156}} {"id":100009496,"name":"NamespaceScoped","signature":"func (persistentvolumeclaimStrategy) NamespaceScoped() bool","file":"pkg/registry/core/persistentvolumeclaim/strategy.go","code":"func (persistentvolumeclaimStrategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":48,"to":50}} {"id":100009497,"name":"GetResetFields","signature":"func (persistentvolumeclaimStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/persistentvolumeclaim/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (persistentvolumeclaimStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":52,"to":62}} {"id":100009498,"name":"PrepareForCreate","signature":"func (persistentvolumeclaimStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/core/persistentvolumeclaim/strategy.go","code":"// PrepareForCreate clears the Status field which is not allowed to be set by end users on creation.\nfunc (persistentvolumeclaimStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tpvc := obj.(*api.PersistentVolumeClaim)\n\tpvc.Status = api.PersistentVolumeClaimStatus{}\n\tpvcutil.DropDisabledFields(\u0026pvc.Spec, nil)\n\n\t// For data sources, we need to do 2 things to implement KEP 1495\n\n\t// First drop invalid values from spec.dataSource (anything other than PVC or\n\t// VolumeSnapshot) if certain conditions are met.\n\tpvcutil.EnforceDataSourceBackwardsCompatibility(\u0026pvc.Spec, nil)\n\n\t// Second copy dataSource -\u003e dataSourceRef or dataSourceRef -\u003e dataSource if one of them\n\t// is nil and the other is non-nil\n\tpvcutil.NormalizeDataSources(\u0026pvc.Spec)\n}","line":{"from":64,"to":79}} {"id":100009499,"name":"Validate","signature":"func (persistentvolumeclaimStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/core/persistentvolumeclaim/strategy.go","code":"func (persistentvolumeclaimStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tpvc := obj.(*api.PersistentVolumeClaim)\n\topts := validation.ValidationOptionsForPersistentVolumeClaim(pvc, nil)\n\treturn validation.ValidatePersistentVolumeClaim(pvc, opts)\n}","line":{"from":81,"to":85}} {"id":100009500,"name":"WarningsOnCreate","signature":"func (persistentvolumeclaimStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/core/persistentvolumeclaim/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (persistentvolumeclaimStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn pvcutil.GetWarningsForPersistentVolumeClaim(obj.(*api.PersistentVolumeClaim))\n}","line":{"from":87,"to":90}} {"id":100009501,"name":"Canonicalize","signature":"func (persistentvolumeclaimStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/core/persistentvolumeclaim/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (persistentvolumeclaimStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":92,"to":94}} {"id":100009502,"name":"AllowCreateOnUpdate","signature":"func (persistentvolumeclaimStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/core/persistentvolumeclaim/strategy.go","code":"func (persistentvolumeclaimStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":96,"to":98}} {"id":100009503,"name":"PrepareForUpdate","signature":"func (persistentvolumeclaimStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/core/persistentvolumeclaim/strategy.go","code":"// PrepareForUpdate sets the Status field which is not allowed to be set by end users on update\nfunc (persistentvolumeclaimStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewPvc := obj.(*api.PersistentVolumeClaim)\n\toldPvc := old.(*api.PersistentVolumeClaim)\n\tnewPvc.Status = oldPvc.Status\n\n\tpvcutil.DropDisabledFields(\u0026newPvc.Spec, \u0026oldPvc.Spec)\n\n\t// We need to use similar logic to PrepareForCreate here both to preserve backwards\n\t// compatibility with the old behavior (ignoring of garbage dataSources at both create\n\t// and update time) and also for compatibility with older clients, that might omit\n\t// the dataSourceRef field which we filled in automatically, so we have to fill it\n\t// in again here.\n\tpvcutil.EnforceDataSourceBackwardsCompatibility(\u0026newPvc.Spec, \u0026oldPvc.Spec)\n\tpvcutil.NormalizeDataSources(\u0026newPvc.Spec)\n\n\t// We also normalize the data source fields of the old PVC, so that objects saved\n\t// from an earlier version will pass validation.\n\tpvcutil.NormalizeDataSources(\u0026oldPvc.Spec)\n}","line":{"from":100,"to":119}} {"id":100009504,"name":"ValidateUpdate","signature":"func (persistentvolumeclaimStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/core/persistentvolumeclaim/strategy.go","code":"func (persistentvolumeclaimStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewPvc := obj.(*api.PersistentVolumeClaim)\n\toldPvc := old.(*api.PersistentVolumeClaim)\n\topts := validation.ValidationOptionsForPersistentVolumeClaim(newPvc, oldPvc)\n\terrorList := validation.ValidatePersistentVolumeClaim(newPvc, opts)\n\treturn append(errorList, validation.ValidatePersistentVolumeClaimUpdate(newPvc, oldPvc, opts)...)\n}","line":{"from":121,"to":127}} {"id":100009505,"name":"WarningsOnUpdate","signature":"func (persistentvolumeclaimStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/core/persistentvolumeclaim/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (persistentvolumeclaimStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn pvcutil.GetWarningsForPersistentVolumeClaim(obj.(*api.PersistentVolumeClaim))\n}","line":{"from":129,"to":132}} {"id":100009506,"name":"AllowUnconditionalUpdate","signature":"func (persistentvolumeclaimStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/core/persistentvolumeclaim/strategy.go","code":"func (persistentvolumeclaimStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":134,"to":136}} {"id":100009507,"name":"GetResetFields","signature":"func (persistentvolumeclaimStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/persistentvolumeclaim/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (persistentvolumeclaimStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":144,"to":154}} {"id":100009508,"name":"PrepareForUpdate","signature":"func (persistentvolumeclaimStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/core/persistentvolumeclaim/strategy.go","code":"// PrepareForUpdate sets the Spec field which is not allowed to be changed when updating a PV's Status\nfunc (persistentvolumeclaimStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewPVC := obj.(*api.PersistentVolumeClaim)\n\toldPVC := old.(*api.PersistentVolumeClaim)\n\tnewPVC.Spec = oldPVC.Spec\n\tpvcutil.DropDisabledFieldsFromStatus(newPVC, oldPVC)\n}","line":{"from":156,"to":162}} {"id":100009509,"name":"ValidateUpdate","signature":"func (persistentvolumeclaimStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/core/persistentvolumeclaim/strategy.go","code":"func (persistentvolumeclaimStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewPvc := obj.(*api.PersistentVolumeClaim)\n\toldPvc := old.(*api.PersistentVolumeClaim)\n\topts := validation.ValidationOptionsForPersistentVolumeClaim(newPvc, oldPvc)\n\treturn validation.ValidatePersistentVolumeClaimStatusUpdate(newPvc, oldPvc, opts)\n}","line":{"from":164,"to":169}} {"id":100009510,"name":"WarningsOnUpdate","signature":"func (persistentvolumeclaimStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/core/persistentvolumeclaim/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (persistentvolumeclaimStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":171,"to":174}} {"id":100009511,"name":"GetAttrs","signature":"func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error)","file":"pkg/registry/core/persistentvolumeclaim/strategy.go","code":"// GetAttrs returns labels and fields of a given object for filtering purposes.\nfunc GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {\n\tpersistentvolumeclaimObj, ok := obj.(*api.PersistentVolumeClaim)\n\tif !ok {\n\t\treturn nil, nil, fmt.Errorf(\"not a persistentvolumeclaim\")\n\t}\n\treturn labels.Set(persistentvolumeclaimObj.Labels), PersistentVolumeClaimToSelectableFields(persistentvolumeclaimObj), nil\n}","line":{"from":176,"to":183}} {"id":100009512,"name":"MatchPersistentVolumeClaim","signature":"func MatchPersistentVolumeClaim(label labels.Selector, field fields.Selector) storage.SelectionPredicate","file":"pkg/registry/core/persistentvolumeclaim/strategy.go","code":"// MatchPersistentVolumeClaim returns a generic matcher for a given label and field selector.\nfunc MatchPersistentVolumeClaim(label labels.Selector, field fields.Selector) storage.SelectionPredicate {\n\treturn storage.SelectionPredicate{\n\t\tLabel: label,\n\t\tField: field,\n\t\tGetAttrs: GetAttrs,\n\t}\n}","line":{"from":185,"to":192}} {"id":100009513,"name":"PersistentVolumeClaimToSelectableFields","signature":"func PersistentVolumeClaimToSelectableFields(persistentvolumeclaim *api.PersistentVolumeClaim) fields.Set","file":"pkg/registry/core/persistentvolumeclaim/strategy.go","code":"// PersistentVolumeClaimToSelectableFields returns a field set that represents the object\nfunc PersistentVolumeClaimToSelectableFields(persistentvolumeclaim *api.PersistentVolumeClaim) fields.Set {\n\tobjectMetaFieldsSet := generic.ObjectMetaFieldsSet(\u0026persistentvolumeclaim.ObjectMeta, true)\n\tspecificFieldsSet := fields.Set{\n\t\t// This is a bug, but we need to support it for backward compatibility.\n\t\t\"name\": persistentvolumeclaim.Name,\n\t}\n\treturn generic.MergeFieldsSets(objectMetaFieldsSet, specificFieldsSet)\n}","line":{"from":194,"to":202}} {"id":100009514,"name":"New","signature":"func (r *LogREST) New() runtime.Object","file":"pkg/registry/core/pod/rest/log.go","code":"// New creates a new Pod log options object\nfunc (r *LogREST) New() runtime.Object {\n\t// TODO - return a resource that represents a log\n\treturn \u0026api.Pod{}\n}","line":{"from":48,"to":52}} {"id":100009515,"name":"Destroy","signature":"func (r *LogREST) Destroy()","file":"pkg/registry/core/pod/rest/log.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *LogREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":54,"to":58}} {"id":100009516,"name":"ProducesMIMETypes","signature":"func (r *LogREST) ProducesMIMETypes(verb string) []string","file":"pkg/registry/core/pod/rest/log.go","code":"// ProducesMIMETypes returns a list of the MIME types the specified HTTP verb (GET, POST, DELETE,\n// PATCH) can respond with.\nfunc (r *LogREST) ProducesMIMETypes(verb string) []string {\n\t// Since the default list does not include \"plain/text\", we need to\n\t// explicitly override ProducesMIMETypes, so that it gets added to\n\t// the \"produces\" section for pods/{name}/log\n\treturn []string{\n\t\t\"text/plain\",\n\t}\n}","line":{"from":60,"to":69}} {"id":100009517,"name":"ProducesObject","signature":"func (r *LogREST) ProducesObject(verb string) interface{}","file":"pkg/registry/core/pod/rest/log.go","code":"// ProducesObject returns an object the specified HTTP verb respond with. It will overwrite storage object if\n// it is not nil. Only the type of the return object matters, the value will be ignored.\nfunc (r *LogREST) ProducesObject(verb string) interface{} {\n\treturn \"\"\n}","line":{"from":71,"to":75}} {"id":100009518,"name":"Get","signature":"func (r *LogREST) Get(ctx context.Context, name string, opts runtime.Object) (runtime.Object, error)","file":"pkg/registry/core/pod/rest/log.go","code":"// Get retrieves a runtime.Object that will stream the contents of the pod log\nfunc (r *LogREST) Get(ctx context.Context, name string, opts runtime.Object) (runtime.Object, error) {\n\t// register the metrics if the context is used. This assumes sync.Once is fast. If it's not, it could be an init block.\n\tregisterMetrics()\n\n\tlogOpts, ok := opts.(*api.PodLogOptions)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid options object: %#v\", opts)\n\t}\n\n\tcountSkipTLSMetric(logOpts.InsecureSkipTLSVerifyBackend)\n\n\tif errs := validation.ValidatePodLogOptions(logOpts); len(errs) \u003e 0 {\n\t\treturn nil, errors.NewInvalid(api.Kind(\"PodLogOptions\"), name, errs)\n\t}\n\tlocation, transport, err := pod.LogLocation(ctx, r.Store, r.KubeletConn, name, logOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026genericrest.LocationStreamer{\n\t\tLocation: location,\n\t\tTransport: transport,\n\t\tContentType: \"text/plain\",\n\t\tFlush: logOpts.Follow,\n\t\tResponseChecker: genericrest.NewGenericHttpResponseChecker(api.Resource(\"pods/log\"), name),\n\t\tRedirectChecker: genericrest.PreventRedirects,\n\t\tTLSVerificationErrorCounter: podLogsTLSFailure,\n\t\tDeprecatedTLSVerificationErrorCounter: deprecatedPodLogsTLSFailure,\n\t}, nil\n}","line":{"from":77,"to":106}} {"id":100009519,"name":"countSkipTLSMetric","signature":"func countSkipTLSMetric(insecureSkipTLSVerifyBackend bool)","file":"pkg/registry/core/pod/rest/log.go","code":"func countSkipTLSMetric(insecureSkipTLSVerifyBackend bool) {\n\tusageType := usageEnforce\n\tif insecureSkipTLSVerifyBackend {\n\t\tusageType = usageSkipAllowed\n\t}\n\n\tcounter, err := podLogsUsage.GetMetricWithLabelValues(usageType)\n\tif err != nil {\n\t\tutilruntime.HandleError(err)\n\t\treturn\n\t}\n\tcounter.Inc()\n\n\tdeprecatedPodLogsUsage.WithLabelValues(usageType).Inc()\n}","line":{"from":108,"to":122}} {"id":100009520,"name":"NewGetOptions","signature":"func (r *LogREST) NewGetOptions() (runtime.Object, bool, string)","file":"pkg/registry/core/pod/rest/log.go","code":"// NewGetOptions creates a new options object\nfunc (r *LogREST) NewGetOptions() (runtime.Object, bool, string) {\n\treturn \u0026api.PodLogOptions{}, false, \"\"\n}","line":{"from":124,"to":127}} {"id":100009521,"name":"OverrideMetricsVerb","signature":"func (r *LogREST) OverrideMetricsVerb(oldVerb string) (newVerb string)","file":"pkg/registry/core/pod/rest/log.go","code":"// OverrideMetricsVerb override the GET verb to CONNECT for pod log resource\nfunc (r *LogREST) OverrideMetricsVerb(oldVerb string) (newVerb string) {\n\tnewVerb = oldVerb\n\n\tif oldVerb == \"GET\" {\n\t\tnewVerb = \"CONNECT\"\n\t}\n\n\treturn\n}","line":{"from":129,"to":138}} {"id":100009522,"name":"registerMetrics","signature":"func registerMetrics()","file":"pkg/registry/core/pod/rest/metrics.go","code":"func registerMetrics() {\n\tregisterMetricsOnce.Do(func() {\n\t\tlegacyregistry.MustRegister(podLogsUsage)\n\t\tlegacyregistry.MustRegister(podLogsTLSFailure)\n\t\tlegacyregistry.MustRegister(deprecatedPodLogsUsage)\n\t\tlegacyregistry.MustRegister(deprecatedPodLogsTLSFailure)\n\t})\n}","line":{"from":86,"to":93}} {"id":100009523,"name":"New","signature":"func (r *ProxyREST) New() runtime.Object","file":"pkg/registry/core/pod/rest/subresources.go","code":"// New returns an empty podProxyOptions object.\nfunc (r *ProxyREST) New() runtime.Object {\n\treturn \u0026api.PodProxyOptions{}\n}","line":{"from":47,"to":50}} {"id":100009524,"name":"Destroy","signature":"func (r *ProxyREST) Destroy()","file":"pkg/registry/core/pod/rest/subresources.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *ProxyREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":52,"to":56}} {"id":100009525,"name":"ConnectMethods","signature":"func (r *ProxyREST) ConnectMethods() []string","file":"pkg/registry/core/pod/rest/subresources.go","code":"// ConnectMethods returns the list of HTTP methods that can be proxied\nfunc (r *ProxyREST) ConnectMethods() []string {\n\treturn proxyMethods\n}","line":{"from":58,"to":61}} {"id":100009526,"name":"NewConnectOptions","signature":"func (r *ProxyREST) NewConnectOptions() (runtime.Object, bool, string)","file":"pkg/registry/core/pod/rest/subresources.go","code":"// NewConnectOptions returns versioned resource that represents proxy parameters\nfunc (r *ProxyREST) NewConnectOptions() (runtime.Object, bool, string) {\n\treturn \u0026api.PodProxyOptions{}, true, \"path\"\n}","line":{"from":63,"to":66}} {"id":100009527,"name":"Connect","signature":"func (r *ProxyREST) Connect(ctx context.Context, id string, opts runtime.Object, responder rest.Responder) (http.Handler, error)","file":"pkg/registry/core/pod/rest/subresources.go","code":"// Connect returns a handler for the pod proxy\nfunc (r *ProxyREST) Connect(ctx context.Context, id string, opts runtime.Object, responder rest.Responder) (http.Handler, error) {\n\tproxyOpts, ok := opts.(*api.PodProxyOptions)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Invalid options object: %#v\", opts)\n\t}\n\tlocation, transport, err := pod.ResourceLocation(ctx, r.Store, r.ProxyTransport, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlocation.Path = net.JoinPreservingTrailingSlash(location.Path, proxyOpts.Path)\n\t// Return a proxy handler that uses the desired transport, wrapped with additional proxy handling (to get URL rewriting, X-Forwarded-* headers, etc)\n\treturn newThrottledUpgradeAwareProxyHandler(location, transport, true, false, responder), nil\n}","line":{"from":68,"to":81}} {"id":100009528,"name":"New","signature":"func (r *AttachREST) New() runtime.Object","file":"pkg/registry/core/pod/rest/subresources.go","code":"// New creates a new podAttachOptions object.\nfunc (r *AttachREST) New() runtime.Object {\n\treturn \u0026api.PodAttachOptions{}\n}","line":{"from":95,"to":98}} {"id":100009529,"name":"Destroy","signature":"func (r *AttachREST) Destroy()","file":"pkg/registry/core/pod/rest/subresources.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *AttachREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":100,"to":104}} {"id":100009530,"name":"Connect","signature":"func (r *AttachREST) Connect(ctx context.Context, name string, opts runtime.Object, responder rest.Responder) (http.Handler, error)","file":"pkg/registry/core/pod/rest/subresources.go","code":"// Connect returns a handler for the pod exec proxy\nfunc (r *AttachREST) Connect(ctx context.Context, name string, opts runtime.Object, responder rest.Responder) (http.Handler, error) {\n\tattachOpts, ok := opts.(*api.PodAttachOptions)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Invalid options object: %#v\", opts)\n\t}\n\tlocation, transport, err := pod.AttachLocation(ctx, r.Store, r.KubeletConn, name, attachOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newThrottledUpgradeAwareProxyHandler(location, transport, false, true, responder), nil\n}","line":{"from":106,"to":117}} {"id":100009531,"name":"NewConnectOptions","signature":"func (r *AttachREST) NewConnectOptions() (runtime.Object, bool, string)","file":"pkg/registry/core/pod/rest/subresources.go","code":"// NewConnectOptions returns the versioned object that represents exec parameters\nfunc (r *AttachREST) NewConnectOptions() (runtime.Object, bool, string) {\n\treturn \u0026api.PodAttachOptions{}, false, \"\"\n}","line":{"from":119,"to":122}} {"id":100009532,"name":"ConnectMethods","signature":"func (r *AttachREST) ConnectMethods() []string","file":"pkg/registry/core/pod/rest/subresources.go","code":"// ConnectMethods returns the methods supported by exec\nfunc (r *AttachREST) ConnectMethods() []string {\n\treturn upgradeableMethods\n}","line":{"from":124,"to":127}} {"id":100009533,"name":"New","signature":"func (r *ExecREST) New() runtime.Object","file":"pkg/registry/core/pod/rest/subresources.go","code":"// New creates a new podExecOptions object.\nfunc (r *ExecREST) New() runtime.Object {\n\treturn \u0026api.PodExecOptions{}\n}","line":{"from":138,"to":141}} {"id":100009534,"name":"Destroy","signature":"func (r *ExecREST) Destroy()","file":"pkg/registry/core/pod/rest/subresources.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *ExecREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":143,"to":147}} {"id":100009535,"name":"Connect","signature":"func (r *ExecREST) Connect(ctx context.Context, name string, opts runtime.Object, responder rest.Responder) (http.Handler, error)","file":"pkg/registry/core/pod/rest/subresources.go","code":"// Connect returns a handler for the pod exec proxy\nfunc (r *ExecREST) Connect(ctx context.Context, name string, opts runtime.Object, responder rest.Responder) (http.Handler, error) {\n\texecOpts, ok := opts.(*api.PodExecOptions)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid options object: %#v\", opts)\n\t}\n\tlocation, transport, err := pod.ExecLocation(ctx, r.Store, r.KubeletConn, name, execOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newThrottledUpgradeAwareProxyHandler(location, transport, false, true, responder), nil\n}","line":{"from":149,"to":160}} {"id":100009536,"name":"NewConnectOptions","signature":"func (r *ExecREST) NewConnectOptions() (runtime.Object, bool, string)","file":"pkg/registry/core/pod/rest/subresources.go","code":"// NewConnectOptions returns the versioned object that represents exec parameters\nfunc (r *ExecREST) NewConnectOptions() (runtime.Object, bool, string) {\n\treturn \u0026api.PodExecOptions{}, false, \"\"\n}","line":{"from":162,"to":165}} {"id":100009537,"name":"ConnectMethods","signature":"func (r *ExecREST) ConnectMethods() []string","file":"pkg/registry/core/pod/rest/subresources.go","code":"// ConnectMethods returns the methods supported by exec\nfunc (r *ExecREST) ConnectMethods() []string {\n\treturn upgradeableMethods\n}","line":{"from":167,"to":170}} {"id":100009538,"name":"New","signature":"func (r *PortForwardREST) New() runtime.Object","file":"pkg/registry/core/pod/rest/subresources.go","code":"// New returns an empty podPortForwardOptions object\nfunc (r *PortForwardREST) New() runtime.Object {\n\treturn \u0026api.PodPortForwardOptions{}\n}","line":{"from":181,"to":184}} {"id":100009539,"name":"Destroy","signature":"func (r *PortForwardREST) Destroy()","file":"pkg/registry/core/pod/rest/subresources.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *PortForwardREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":186,"to":190}} {"id":100009540,"name":"NewConnectOptions","signature":"func (r *PortForwardREST) NewConnectOptions() (runtime.Object, bool, string)","file":"pkg/registry/core/pod/rest/subresources.go","code":"// NewConnectOptions returns the versioned object that represents the\n// portforward parameters\nfunc (r *PortForwardREST) NewConnectOptions() (runtime.Object, bool, string) {\n\treturn \u0026api.PodPortForwardOptions{}, false, \"\"\n}","line":{"from":192,"to":196}} {"id":100009541,"name":"ConnectMethods","signature":"func (r *PortForwardREST) ConnectMethods() []string","file":"pkg/registry/core/pod/rest/subresources.go","code":"// ConnectMethods returns the methods supported by portforward\nfunc (r *PortForwardREST) ConnectMethods() []string {\n\treturn upgradeableMethods\n}","line":{"from":198,"to":201}} {"id":100009542,"name":"Connect","signature":"func (r *PortForwardREST) Connect(ctx context.Context, name string, opts runtime.Object, responder rest.Responder) (http.Handler, error)","file":"pkg/registry/core/pod/rest/subresources.go","code":"// Connect returns a handler for the pod portforward proxy\nfunc (r *PortForwardREST) Connect(ctx context.Context, name string, opts runtime.Object, responder rest.Responder) (http.Handler, error) {\n\tportForwardOpts, ok := opts.(*api.PodPortForwardOptions)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid options object: %#v\", opts)\n\t}\n\tlocation, transport, err := pod.PortForwardLocation(ctx, r.Store, r.KubeletConn, name, portForwardOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newThrottledUpgradeAwareProxyHandler(location, transport, false, true, responder), nil\n}","line":{"from":203,"to":214}} {"id":100009543,"name":"newThrottledUpgradeAwareProxyHandler","signature":"func newThrottledUpgradeAwareProxyHandler(location *url.URL, transport http.RoundTripper, wrapTransport, upgradeRequired bool, responder rest.Responder) *proxy.UpgradeAwareHandler","file":"pkg/registry/core/pod/rest/subresources.go","code":"func newThrottledUpgradeAwareProxyHandler(location *url.URL, transport http.RoundTripper, wrapTransport, upgradeRequired bool, responder rest.Responder) *proxy.UpgradeAwareHandler {\n\thandler := proxy.NewUpgradeAwareHandler(location, transport, wrapTransport, upgradeRequired, proxy.NewErrorResponder(responder))\n\thandler.MaxBytesPerSec = capabilities.Get().PerConnectionBandwidthLimitBytesPerSec\n\treturn handler\n}","line":{"from":216,"to":220}} {"id":100009544,"name":"newEvictionStorage","signature":"func newEvictionStorage(store rest.StandardStorage, podDisruptionBudgetClient policyclient.PodDisruptionBudgetsGetter) *EvictionREST","file":"pkg/registry/core/pod/storage/eviction.go","code":"func newEvictionStorage(store rest.StandardStorage, podDisruptionBudgetClient policyclient.PodDisruptionBudgetsGetter) *EvictionREST {\n\treturn \u0026EvictionREST{store: store, podDisruptionBudgetClient: podDisruptionBudgetClient}\n}","line":{"from":65,"to":67}} {"id":100009545,"name":"GroupVersionKind","signature":"func (r *EvictionREST) GroupVersionKind(containingGV schema.GroupVersion) schema.GroupVersionKind","file":"pkg/registry/core/pod/storage/eviction.go","code":"// GroupVersionKind specifies a particular GroupVersionKind to discovery\nfunc (r *EvictionREST) GroupVersionKind(containingGV schema.GroupVersion) schema.GroupVersionKind {\n\treturn v1Eviction\n}","line":{"from":81,"to":84}} {"id":100009546,"name":"AcceptsGroupVersion","signature":"func (r *EvictionREST) AcceptsGroupVersion(gv schema.GroupVersion) bool","file":"pkg/registry/core/pod/storage/eviction.go","code":"// AcceptsGroupVersion indicates both v1 and v1beta1 Eviction objects are acceptable\nfunc (r *EvictionREST) AcceptsGroupVersion(gv schema.GroupVersion) bool {\n\tswitch gv {\n\tcase policyv1.SchemeGroupVersion, policyv1beta1.SchemeGroupVersion:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":86,"to":94}} {"id":100009547,"name":"New","signature":"func (r *EvictionREST) New() runtime.Object","file":"pkg/registry/core/pod/storage/eviction.go","code":"// New creates a new eviction resource\nfunc (r *EvictionREST) New() runtime.Object {\n\treturn \u0026policy.Eviction{}\n}","line":{"from":96,"to":99}} {"id":100009548,"name":"Destroy","signature":"func (r *EvictionREST) Destroy()","file":"pkg/registry/core/pod/storage/eviction.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *EvictionREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":101,"to":105}} {"id":100009549,"name":"propagateDryRun","signature":"func propagateDryRun(eviction *policy.Eviction, options *metav1.CreateOptions) (*metav1.DeleteOptions, error)","file":"pkg/registry/core/pod/storage/eviction.go","code":"// Propagate dry-run takes the dry-run option from the request and pushes it into the eviction object.\n// It returns an error if they have non-matching dry-run options.\nfunc propagateDryRun(eviction *policy.Eviction, options *metav1.CreateOptions) (*metav1.DeleteOptions, error) {\n\tif eviction.DeleteOptions == nil {\n\t\treturn \u0026metav1.DeleteOptions{DryRun: options.DryRun}, nil\n\t}\n\tif len(eviction.DeleteOptions.DryRun) == 0 {\n\t\teviction.DeleteOptions.DryRun = options.DryRun\n\t\treturn eviction.DeleteOptions, nil\n\t}\n\tif len(options.DryRun) == 0 {\n\t\treturn eviction.DeleteOptions, nil\n\t}\n\n\tif !reflect.DeepEqual(options.DryRun, eviction.DeleteOptions.DryRun) {\n\t\treturn nil, fmt.Errorf(\"Non-matching dry-run options in request and content: %v and %v\", options.DryRun, eviction.DeleteOptions.DryRun)\n\t}\n\treturn eviction.DeleteOptions, nil\n}","line":{"from":107,"to":125}} {"id":100009550,"name":"Create","signature":"func (r *EvictionREST) Create(ctx context.Context, name string, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error)","file":"pkg/registry/core/pod/storage/eviction.go","code":"// Create attempts to create a new eviction. That is, it tries to evict a pod.\nfunc (r *EvictionREST) Create(ctx context.Context, name string, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {\n\teviction, ok := obj.(*policy.Eviction)\n\tif !ok {\n\t\treturn nil, errors.NewBadRequest(fmt.Sprintf(\"not a Eviction object: %T\", obj))\n\t}\n\n\tif name != eviction.Name {\n\t\treturn nil, errors.NewBadRequest(\"name in URL does not match name in Eviction object\")\n\t}\n\n\toriginalDeleteOptions, err := propagateDryRun(eviction, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif createValidation != nil {\n\t\tif err := createValidation(ctx, eviction.DeepCopyObject()); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tvar pod *api.Pod\n\tdeletedPod := false\n\t// by default, retry conflict errors\n\tshouldRetry := errors.IsConflict\n\tif !resourceVersionIsUnset(originalDeleteOptions) {\n\t\t// if the original options included a resourceVersion precondition, don't retry\n\t\tshouldRetry = func(err error) bool { return false }\n\t}\n\n\terr = retry.OnError(EvictionsRetry, shouldRetry, func() error {\n\t\tpod, err = getPod(r, ctx, eviction.Name)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Evicting a terminal pod should result in direct deletion of pod as it already caused disruption by the time we are evicting.\n\t\t// There is no need to check for pdb.\n\t\tif !canIgnorePDB(pod) {\n\t\t\t// Pod is not in a state where we can skip checking PDBs, exit the loop, and continue to PDB checks.\n\t\t\treturn nil\n\t\t}\n\n\t\t// the PDB can be ignored, so delete the pod\n\t\tdeleteOptions := originalDeleteOptions\n\n\t\t// We should check if resourceVersion is already set by the requestor\n\t\t// as it might be older than the pod we just fetched and should be\n\t\t// honored.\n\t\tif shouldEnforceResourceVersion(pod) \u0026\u0026 resourceVersionIsUnset(originalDeleteOptions) {\n\t\t\t// Set deleteOptions.Preconditions.ResourceVersion to ensure we're not\n\t\t\t// racing with another PDB-impacting process elsewhere.\n\t\t\tdeleteOptions = deleteOptions.DeepCopy()\n\t\t\tsetPreconditionsResourceVersion(deleteOptions, \u0026pod.ResourceVersion)\n\t\t}\n\t\terr = addConditionAndDeletePod(r, ctx, eviction.Name, rest.ValidateAllObjectFunc, deleteOptions)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdeletedPod = true\n\t\treturn nil\n\t})\n\tswitch {\n\tcase err != nil:\n\t\t// this can happen in cases where the PDB can be ignored, but there was a problem issuing the pod delete:\n\t\t// maybe we conflicted too many times or we didn't have permission or something else weird.\n\t\treturn nil, err\n\n\tcase deletedPod:\n\t\t// this happens when we successfully deleted the pod. In this case, we're done executing because we've evicted/deleted the pod\n\t\treturn \u0026metav1.Status{Status: metav1.StatusSuccess}, nil\n\n\tdefault:\n\t\t// this happens when we didn't have an error and we didn't delete the pod. The only branch that happens on is when\n\t\t// we cannot ignored the PDB for this pod, so this is the fall through case.\n\t}\n\n\tvar rtStatus *metav1.Status\n\tvar pdbName string\n\tupdateDeletionOptions := false\n\n\terr = func() error {\n\t\tpdbs, err := r.getPodDisruptionBudgets(ctx, pod)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif len(pdbs) \u003e 1 {\n\t\t\trtStatus = \u0026metav1.Status{\n\t\t\t\tStatus: metav1.StatusFailure,\n\t\t\t\tMessage: \"This pod has more than one PodDisruptionBudget, which the eviction subresource does not support.\",\n\t\t\t\tCode: 500,\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\tif len(pdbs) == 0 {\n\t\t\treturn nil\n\t\t}\n\n\t\tpdb := \u0026pdbs[0]\n\t\tpdbName = pdb.Name\n\n\t\t// IsPodReady is the current implementation of IsHealthy\n\t\t// If the pod is healthy, it should be guarded by the PDB.\n\t\tif !podutil.IsPodReady(pod) {\n\t\t\tif feature.DefaultFeatureGate.Enabled(features.PDBUnhealthyPodEvictionPolicy) {\n\t\t\t\tif pdb.Spec.UnhealthyPodEvictionPolicy != nil \u0026\u0026 *pdb.Spec.UnhealthyPodEvictionPolicy == policyv1.AlwaysAllow {\n\t\t\t\t\t// Delete the unhealthy pod, it doesn't count towards currentHealthy and desiredHealthy and we should not decrement disruptionsAllowed.\n\t\t\t\t\tupdateDeletionOptions = true\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t\t// default nil and IfHealthyBudget policy\n\t\t\tif pdb.Status.CurrentHealthy \u003e= pdb.Status.DesiredHealthy \u0026\u0026 pdb.Status.DesiredHealthy \u003e 0 {\n\t\t\t\t// Delete the unhealthy pod, it doesn't count towards currentHealthy and desiredHealthy and we should not decrement disruptionsAllowed.\n\t\t\t\t// Application guarded by the PDB is not disrupted at the moment and deleting unhealthy (unready) pod will not disrupt it.\n\t\t\t\tupdateDeletionOptions = true\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t// confirm no disruptions allowed in checkAndDecrement\n\t\t}\n\n\t\trefresh := false\n\t\terr = retry.RetryOnConflict(EvictionsRetry, func() error {\n\t\t\tif refresh {\n\t\t\t\tpdb, err = r.podDisruptionBudgetClient.PodDisruptionBudgets(pod.Namespace).Get(context.TODO(), pdbName, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Try to verify-and-decrement\n\n\t\t\t// If it was false already, or if it becomes false during the course of our retries,\n\t\t\t// raise an error marked as a 429.\n\t\t\tif err = r.checkAndDecrement(pod.Namespace, pod.Name, *pdb, dryrun.IsDryRun(originalDeleteOptions.DryRun)); err != nil {\n\t\t\t\trefresh = true\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\treturn err\n\t}()\n\tif err == wait.ErrWaitTimeout {\n\t\terr = errors.NewTimeoutError(fmt.Sprintf(\"couldn't update PodDisruptionBudget %q due to conflicts\", pdbName), 10)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif rtStatus != nil {\n\t\treturn rtStatus, nil\n\t}\n\n\t// At this point there was either no PDB or we succeeded in decrementing or\n\t// the pod was unhealthy (unready) and we have enough healthy replicas\n\n\tdeleteOptions := originalDeleteOptions\n\n\t// Set deleteOptions.Preconditions.ResourceVersion to ensure\n\t// the pod hasn't been considered healthy (ready) since we calculated\n\tif updateDeletionOptions {\n\t\t// Take a copy so we can compare to client-provied Options later.\n\t\tdeleteOptions = deleteOptions.DeepCopy()\n\t\tsetPreconditionsResourceVersion(deleteOptions, \u0026pod.ResourceVersion)\n\t}\n\n\t// Try the delete\n\terr = addConditionAndDeletePod(r, ctx, eviction.Name, rest.ValidateAllObjectFunc, deleteOptions)\n\tif err != nil {\n\t\tif errors.IsConflict(err) \u0026\u0026 updateDeletionOptions \u0026\u0026\n\t\t\t(originalDeleteOptions.Preconditions == nil || originalDeleteOptions.Preconditions.ResourceVersion == nil) {\n\t\t\t// If we encounter a resource conflict error, we updated the deletion options to include them,\n\t\t\t// and the original deletion options did not specify ResourceVersion, we send back\n\t\t\t// TooManyRequests so clients will retry.\n\t\t\treturn nil, createTooManyRequestsError(pdbName)\n\t\t}\n\t\treturn nil, err\n\t}\n\n\t// Success!\n\treturn \u0026metav1.Status{Status: metav1.StatusSuccess}, nil\n}","line":{"from":127,"to":309}} {"id":100009551,"name":"addConditionAndDeletePod","signature":"func addConditionAndDeletePod(r *EvictionREST, ctx context.Context, name string, validation rest.ValidateObjectFunc, options *metav1.DeleteOptions) error","file":"pkg/registry/core/pod/storage/eviction.go","code":"func addConditionAndDeletePod(r *EvictionREST, ctx context.Context, name string, validation rest.ValidateObjectFunc, options *metav1.DeleteOptions) error {\n\tif !dryrun.IsDryRun(options.DryRun) \u0026\u0026 feature.DefaultFeatureGate.Enabled(features.PodDisruptionConditions) {\n\t\tgetLatestPod := func(_ context.Context, _, oldObj runtime.Object) (runtime.Object, error) {\n\t\t\t// Throwaway the newObj. We care only about the latest pod obtained from etcd (oldObj).\n\t\t\t// So we can add DisruptionTarget condition in conditionAppender without conflicts.\n\t\t\tlatestPod := oldObj.(*api.Pod).DeepCopy()\n\t\t\tif options.Preconditions != nil {\n\t\t\t\tif uid := options.Preconditions.UID; uid != nil \u0026\u0026 len(*uid) \u003e 0 \u0026\u0026 *uid != latestPod.UID {\n\t\t\t\t\treturn nil, errors.NewConflict(\n\t\t\t\t\t\tschema.GroupResource{Group: \"\", Resource: \"Pod\"},\n\t\t\t\t\t\tlatestPod.Name,\n\t\t\t\t\t\tfmt.Errorf(\"the UID in the precondition (%s) does not match the UID in record (%s). The object might have been deleted and then recreated\", *uid, latestPod.UID),\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tif rv := options.Preconditions.ResourceVersion; rv != nil \u0026\u0026 len(*rv) \u003e 0 \u0026\u0026 *rv != latestPod.ResourceVersion {\n\t\t\t\t\treturn nil, errors.NewConflict(\n\t\t\t\t\t\tschema.GroupResource{Group: \"\", Resource: \"Pod\"},\n\t\t\t\t\t\tlatestPod.Name,\n\t\t\t\t\t\tfmt.Errorf(\"the ResourceVersion in the precondition (%s) does not match the ResourceVersion in record (%s). The object might have been modified\", *rv, latestPod.ResourceVersion),\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn latestPod, nil\n\t\t}\n\n\t\tconditionAppender := func(_ context.Context, newObj, _ runtime.Object) (runtime.Object, error) {\n\t\t\tpodObj := newObj.(*api.Pod)\n\t\t\tpodutil.UpdatePodCondition(\u0026podObj.Status, \u0026api.PodCondition{\n\t\t\t\tType: api.DisruptionTarget,\n\t\t\t\tStatus: api.ConditionTrue,\n\t\t\t\tReason: \"EvictionByEvictionAPI\",\n\t\t\t\tMessage: \"Eviction API: evicting\",\n\t\t\t})\n\t\t\treturn podObj, nil\n\t\t}\n\n\t\tpodUpdatedObjectInfo := rest.DefaultUpdatedObjectInfo(nil, getLatestPod, conditionAppender) // order important\n\n\t\tupdatedPodObject, _, err := r.store.Update(ctx, name, podUpdatedObjectInfo, rest.ValidateAllObjectFunc, rest.ValidateAllObjectUpdateFunc, false, \u0026metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif !resourceVersionIsUnset(options) {\n\t\t\tnewResourceVersion, err := meta.NewAccessor().ResourceVersion(updatedPodObject)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// bump the resource version, since we are the one who modified it via the update\n\t\t\toptions = options.DeepCopy()\n\t\t\toptions.Preconditions.ResourceVersion = \u0026newResourceVersion\n\t\t}\n\t}\n\t_, _, err := r.store.Delete(ctx, name, rest.ValidateAllObjectFunc, options)\n\treturn err\n}","line":{"from":311,"to":366}} {"id":100009552,"name":"getPod","signature":"func getPod(r *EvictionREST, ctx context.Context, name string) (*api.Pod, error)","file":"pkg/registry/core/pod/storage/eviction.go","code":"func getPod(r *EvictionREST, ctx context.Context, name string) (*api.Pod, error) {\n\tobj, err := r.store.Get(ctx, name, \u0026metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn obj.(*api.Pod), nil\n}","line":{"from":368,"to":374}} {"id":100009553,"name":"setPreconditionsResourceVersion","signature":"func setPreconditionsResourceVersion(deleteOptions *metav1.DeleteOptions, resourceVersion *string)","file":"pkg/registry/core/pod/storage/eviction.go","code":"func setPreconditionsResourceVersion(deleteOptions *metav1.DeleteOptions, resourceVersion *string) {\n\tif deleteOptions.Preconditions == nil {\n\t\tdeleteOptions.Preconditions = \u0026metav1.Preconditions{}\n\t}\n\tdeleteOptions.Preconditions.ResourceVersion = resourceVersion\n}","line":{"from":376,"to":381}} {"id":100009554,"name":"canIgnorePDB","signature":"func canIgnorePDB(pod *api.Pod) bool","file":"pkg/registry/core/pod/storage/eviction.go","code":"// canIgnorePDB returns true for pod conditions that allow the pod to be deleted\n// without checking PDBs.\nfunc canIgnorePDB(pod *api.Pod) bool {\n\tif pod.Status.Phase == api.PodSucceeded || pod.Status.Phase == api.PodFailed ||\n\t\tpod.Status.Phase == api.PodPending || !pod.ObjectMeta.DeletionTimestamp.IsZero() {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":383,"to":391}} {"id":100009555,"name":"shouldEnforceResourceVersion","signature":"func shouldEnforceResourceVersion(pod *api.Pod) bool","file":"pkg/registry/core/pod/storage/eviction.go","code":"func shouldEnforceResourceVersion(pod *api.Pod) bool {\n\t// We don't need to enforce ResourceVersion for terminal pods\n\tif pod.Status.Phase == api.PodSucceeded || pod.Status.Phase == api.PodFailed || !pod.ObjectMeta.DeletionTimestamp.IsZero() {\n\t\treturn false\n\t}\n\t// Return true for all other pods to ensure we don't race against a pod becoming\n\t// healthy (ready) and violating PDBs.\n\treturn true\n}","line":{"from":393,"to":401}} {"id":100009556,"name":"resourceVersionIsUnset","signature":"func resourceVersionIsUnset(options *metav1.DeleteOptions) bool","file":"pkg/registry/core/pod/storage/eviction.go","code":"func resourceVersionIsUnset(options *metav1.DeleteOptions) bool {\n\treturn options.Preconditions == nil || options.Preconditions.ResourceVersion == nil\n}","line":{"from":403,"to":405}} {"id":100009557,"name":"createTooManyRequestsError","signature":"func createTooManyRequestsError(name string) error","file":"pkg/registry/core/pod/storage/eviction.go","code":"func createTooManyRequestsError(name string) error {\n\t// TODO: Once there are time-based\n\t// budgets, we can sometimes compute a sensible suggested value. But\n\t// even without that, we can give a suggestion (even if small) that\n\t// prevents well-behaved clients from hammering us.\n\terr := errors.NewTooManyRequests(\"Cannot evict pod as it would violate the pod's disruption budget.\", 10)\n\terr.ErrStatus.Details.Causes = append(err.ErrStatus.Details.Causes, metav1.StatusCause{Type: policyv1.DisruptionBudgetCause, Message: fmt.Sprintf(\"The disruption budget %s is still being processed by the server.\", name)})\n\treturn err\n}","line":{"from":407,"to":415}} {"id":100009558,"name":"checkAndDecrement","signature":"func (r *EvictionREST) checkAndDecrement(namespace string, podName string, pdb policyv1.PodDisruptionBudget, dryRun bool) error","file":"pkg/registry/core/pod/storage/eviction.go","code":"// checkAndDecrement checks if the provided PodDisruptionBudget allows any disruption.\nfunc (r *EvictionREST) checkAndDecrement(namespace string, podName string, pdb policyv1.PodDisruptionBudget, dryRun bool) error {\n\tif pdb.Status.ObservedGeneration \u003c pdb.Generation {\n\n\t\treturn createTooManyRequestsError(pdb.Name)\n\t}\n\tif pdb.Status.DisruptionsAllowed \u003c 0 {\n\t\treturn errors.NewForbidden(policy.Resource(\"poddisruptionbudget\"), pdb.Name, fmt.Errorf(\"pdb disruptions allowed is negative\"))\n\t}\n\tif len(pdb.Status.DisruptedPods) \u003e MaxDisruptedPodSize {\n\t\treturn errors.NewForbidden(policy.Resource(\"poddisruptionbudget\"), pdb.Name, fmt.Errorf(\"DisruptedPods map too big - too many evictions not confirmed by PDB controller\"))\n\t}\n\tif pdb.Status.DisruptionsAllowed == 0 {\n\t\terr := errors.NewTooManyRequests(\"Cannot evict pod as it would violate the pod's disruption budget.\", 0)\n\t\terr.ErrStatus.Details.Causes = append(err.ErrStatus.Details.Causes, metav1.StatusCause{Type: policyv1.DisruptionBudgetCause, Message: fmt.Sprintf(\"The disruption budget %s needs %d healthy pods and has %d currently\", pdb.Name, pdb.Status.DesiredHealthy, pdb.Status.CurrentHealthy)})\n\t\treturn err\n\t}\n\n\tpdb.Status.DisruptionsAllowed--\n\tif pdb.Status.DisruptionsAllowed == 0 {\n\t\tpdbhelper.UpdateDisruptionAllowedCondition(\u0026pdb)\n\t}\n\n\t// If this is a dry-run, we don't need to go any further than that.\n\tif dryRun {\n\t\treturn nil\n\t}\n\n\tif pdb.Status.DisruptedPods == nil {\n\t\tpdb.Status.DisruptedPods = make(map[string]metav1.Time)\n\t}\n\n\t// Eviction handler needs to inform the PDB controller that it is about to delete a pod\n\t// so it should not consider it as available in calculations when updating PodDisruptions allowed.\n\t// If the pod is not deleted within a reasonable time limit PDB controller will assume that it won't\n\t// be deleted at all and remove it from DisruptedPod map.\n\tpdb.Status.DisruptedPods[podName] = metav1.Time{Time: time.Now()}\n\tif _, err := r.podDisruptionBudgetClient.PodDisruptionBudgets(namespace).UpdateStatus(context.TODO(), \u0026pdb, metav1.UpdateOptions{}); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":417,"to":459}} {"id":100009559,"name":"getPodDisruptionBudgets","signature":"func (r *EvictionREST) getPodDisruptionBudgets(ctx context.Context, pod *api.Pod) ([]policyv1.PodDisruptionBudget, error)","file":"pkg/registry/core/pod/storage/eviction.go","code":"// getPodDisruptionBudgets returns any PDBs that match the pod or err if there's an error.\nfunc (r *EvictionREST) getPodDisruptionBudgets(ctx context.Context, pod *api.Pod) ([]policyv1.PodDisruptionBudget, error) {\n\tpdbList, err := r.podDisruptionBudgetClient.PodDisruptionBudgets(pod.Namespace).List(context.TODO(), metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar pdbs []policyv1.PodDisruptionBudget\n\tfor _, pdb := range pdbList.Items {\n\t\tif pdb.Namespace != pod.Namespace {\n\t\t\tcontinue\n\t\t}\n\t\tselector, err := metav1.LabelSelectorAsSelector(pdb.Spec.Selector)\n\t\tif err != nil {\n\t\t\t// This object has an invalid selector, it does not match the pod\n\t\t\tcontinue\n\t\t}\n\t\t// If a PDB with a nil or empty selector creeps in, it should match nothing, not everything.\n\t\tif selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tpdbs = append(pdbs, pdb)\n\t}\n\n\treturn pdbs, nil\n}","line":{"from":461,"to":487}} {"id":100009560,"name":"NewStorage","signature":"func NewStorage(optsGetter generic.RESTOptionsGetter, k client.ConnectionInfoGetter, proxyTransport http.RoundTripper, podDisruptionBudgetClient policyclient.PodDisruptionBudgetsGetter) (PodStorage, error)","file":"pkg/registry/core/pod/storage/storage.go","code":"// NewStorage returns a RESTStorage object that will work against pods.\nfunc NewStorage(optsGetter generic.RESTOptionsGetter, k client.ConnectionInfoGetter, proxyTransport http.RoundTripper, podDisruptionBudgetClient policyclient.PodDisruptionBudgetsGetter) (PodStorage, error) {\n\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026api.Pod{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026api.PodList{} },\n\t\tPredicateFunc: registrypod.MatchPod,\n\t\tDefaultQualifiedResource: api.Resource(\"pods\"),\n\t\tSingularQualifiedResource: api.Resource(\"pod\"),\n\n\t\tCreateStrategy: registrypod.Strategy,\n\t\tUpdateStrategy: registrypod.Strategy,\n\t\tDeleteStrategy: registrypod.Strategy,\n\t\tResetFieldsStrategy: registrypod.Strategy,\n\t\tReturnDeletedObject: true,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{\n\t\tRESTOptions: optsGetter,\n\t\tAttrFunc: registrypod.GetAttrs,\n\t\tTriggerFunc: map[string]storage.IndexerFunc{\"spec.nodeName\": registrypod.NodeNameTriggerFunc},\n\t\tIndexers: registrypod.Indexers(),\n\t}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn PodStorage{}, err\n\t}\n\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = registrypod.StatusStrategy\n\tstatusStore.ResetFieldsStrategy = registrypod.StatusStrategy\n\tephemeralContainersStore := *store\n\tephemeralContainersStore.UpdateStrategy = registrypod.EphemeralContainersStrategy\n\n\tbindingREST := \u0026BindingREST{store: store}\n\treturn PodStorage{\n\t\tPod: \u0026REST{store, proxyTransport},\n\t\tBinding: \u0026BindingREST{store: store},\n\t\tLegacyBinding: \u0026LegacyBindingREST{bindingREST},\n\t\tEviction: newEvictionStorage(\u0026statusStore, podDisruptionBudgetClient),\n\t\tStatus: \u0026StatusREST{store: \u0026statusStore},\n\t\tEphemeralContainers: \u0026EphemeralContainersREST{store: \u0026ephemeralContainersStore},\n\t\tLog: \u0026podrest.LogREST{Store: store, KubeletConn: k},\n\t\tProxy: \u0026podrest.ProxyREST{Store: store, ProxyTransport: proxyTransport},\n\t\tExec: \u0026podrest.ExecREST{Store: store, KubeletConn: k},\n\t\tAttach: \u0026podrest.AttachREST{Store: store, KubeletConn: k},\n\t\tPortForward: \u0026podrest.PortForwardREST{Store: store, KubeletConn: k},\n\t}, nil\n}","line":{"from":70,"to":118}} {"id":100009561,"name":"ResourceLocation","signature":"func (r *REST) ResourceLocation(ctx context.Context, name string) (*url.URL, http.RoundTripper, error)","file":"pkg/registry/core/pod/storage/storage.go","code":"// ResourceLocation returns a pods location from its HostIP\nfunc (r *REST) ResourceLocation(ctx context.Context, name string) (*url.URL, http.RoundTripper, error) {\n\treturn registrypod.ResourceLocation(ctx, r, r.proxyTransport, name)\n}","line":{"from":123,"to":126}} {"id":100009562,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/core/pod/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"po\"}\n}","line":{"from":131,"to":134}} {"id":100009563,"name":"Categories","signature":"func (r *REST) Categories() []string","file":"pkg/registry/core/pod/storage/storage.go","code":"// Categories implements the CategoriesProvider interface. Returns a list of categories a resource is part of.\nfunc (r *REST) Categories() []string {\n\treturn []string{\"all\"}\n}","line":{"from":139,"to":142}} {"id":100009564,"name":"NamespaceScoped","signature":"func (r *BindingREST) NamespaceScoped() bool","file":"pkg/registry/core/pod/storage/storage.go","code":"// NamespaceScoped fulfill rest.Scoper\nfunc (r *BindingREST) NamespaceScoped() bool {\n\treturn r.store.NamespaceScoped()\n}","line":{"from":149,"to":152}} {"id":100009565,"name":"New","signature":"func (r *BindingREST) New() runtime.Object","file":"pkg/registry/core/pod/storage/storage.go","code":"// New creates a new binding resource\nfunc (r *BindingREST) New() runtime.Object {\n\treturn \u0026api.Binding{}\n}","line":{"from":154,"to":157}} {"id":100009566,"name":"Destroy","signature":"func (r *BindingREST) Destroy()","file":"pkg/registry/core/pod/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *BindingREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":159,"to":163}} {"id":100009567,"name":"Create","signature":"func (r *BindingREST) Create(ctx context.Context, name string, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (out runtime.Object, err error)","file":"pkg/registry/core/pod/storage/storage.go","code":"// Create ensures a pod is bound to a specific host.\nfunc (r *BindingREST) Create(ctx context.Context, name string, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (out runtime.Object, err error) {\n\tbinding, ok := obj.(*api.Binding)\n\tif !ok {\n\t\treturn nil, errors.NewBadRequest(fmt.Sprintf(\"not a Binding object: %#v\", obj))\n\t}\n\n\tif name != binding.Name {\n\t\treturn nil, errors.NewBadRequest(\"name in URL does not match name in Binding object\")\n\t}\n\n\t// TODO: move me to a binding strategy\n\tif errs := validation.ValidatePodBinding(binding); len(errs) != 0 {\n\t\treturn nil, errs.ToAggregate()\n\t}\n\n\tif createValidation != nil {\n\t\tif err := createValidation(ctx, binding.DeepCopyObject()); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\terr = r.assignPod(ctx, binding.UID, binding.ResourceVersion, binding.Name, binding.Target.Name, binding.Annotations, dryrun.IsDryRun(options.DryRun))\n\tout = \u0026metav1.Status{Status: metav1.StatusSuccess}\n\treturn\n}","line":{"from":168,"to":193}} {"id":100009568,"name":"PreserveRequestObjectMetaSystemFieldsOnSubresourceCreate","signature":"func (r *BindingREST) PreserveRequestObjectMetaSystemFieldsOnSubresourceCreate() bool","file":"pkg/registry/core/pod/storage/storage.go","code":"// PreserveRequestObjectMetaSystemFieldsOnSubresourceCreate indicates to a\n// handler that this endpoint requires the UID and ResourceVersion to use as\n// preconditions. Other fields, such as timestamp, are ignored.\nfunc (r *BindingREST) PreserveRequestObjectMetaSystemFieldsOnSubresourceCreate() bool {\n\treturn true\n}","line":{"from":195,"to":200}} {"id":100009569,"name":"setPodHostAndAnnotations","signature":"func (r *BindingREST) setPodHostAndAnnotations(ctx context.Context, podUID types.UID, podResourceVersion, podID, machine string, annotations map[string]string, dryRun bool) (finalPod *api.Pod, err error)","file":"pkg/registry/core/pod/storage/storage.go","code":"// setPodHostAndAnnotations sets the given pod's host to 'machine' if and only if\n// the pod is unassigned and merges the provided annotations with those of the pod.\n// Returns the current state of the pod, or an error.\nfunc (r *BindingREST) setPodHostAndAnnotations(ctx context.Context, podUID types.UID, podResourceVersion, podID, machine string, annotations map[string]string, dryRun bool) (finalPod *api.Pod, err error) {\n\tpodKey, err := r.store.KeyFunc(ctx, podID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar preconditions *storage.Preconditions\n\tif podUID != \"\" || podResourceVersion != \"\" {\n\t\tpreconditions = \u0026storage.Preconditions{}\n\t\tif podUID != \"\" {\n\t\t\tpreconditions.UID = \u0026podUID\n\t\t}\n\t\tif podResourceVersion != \"\" {\n\t\t\tpreconditions.ResourceVersion = \u0026podResourceVersion\n\t\t}\n\t}\n\n\terr = r.store.Storage.GuaranteedUpdate(ctx, podKey, \u0026api.Pod{}, false, preconditions, storage.SimpleUpdate(func(obj runtime.Object) (runtime.Object, error) {\n\t\tpod, ok := obj.(*api.Pod)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"unexpected object: %#v\", obj)\n\t\t}\n\t\tif pod.DeletionTimestamp != nil {\n\t\t\treturn nil, fmt.Errorf(\"pod %s is being deleted, cannot be assigned to a host\", pod.Name)\n\t\t}\n\t\tif pod.Spec.NodeName != \"\" {\n\t\t\treturn nil, fmt.Errorf(\"pod %v is already assigned to node %q\", pod.Name, pod.Spec.NodeName)\n\t\t}\n\t\t// Reject binding to a scheduling un-ready Pod.\n\t\tif len(pod.Spec.SchedulingGates) != 0 {\n\t\t\treturn nil, fmt.Errorf(\"pod %v has non-empty .spec.schedulingGates\", pod.Name)\n\t\t}\n\t\tpod.Spec.NodeName = machine\n\t\tif pod.Annotations == nil {\n\t\t\tpod.Annotations = make(map[string]string)\n\t\t}\n\t\tfor k, v := range annotations {\n\t\t\tpod.Annotations[k] = v\n\t\t}\n\t\tpodutil.UpdatePodCondition(\u0026pod.Status, \u0026api.PodCondition{\n\t\t\tType: api.PodScheduled,\n\t\t\tStatus: api.ConditionTrue,\n\t\t})\n\t\tfinalPod = pod\n\t\treturn pod, nil\n\t}), dryRun, nil)\n\treturn finalPod, err\n}","line":{"from":202,"to":252}} {"id":100009570,"name":"assignPod","signature":"func (r *BindingREST) assignPod(ctx context.Context, podUID types.UID, podResourceVersion, podID string, machine string, annotations map[string]string, dryRun bool) (err error)","file":"pkg/registry/core/pod/storage/storage.go","code":"// assignPod assigns the given pod to the given machine.\nfunc (r *BindingREST) assignPod(ctx context.Context, podUID types.UID, podResourceVersion, podID string, machine string, annotations map[string]string, dryRun bool) (err error) {\n\tif _, err = r.setPodHostAndAnnotations(ctx, podUID, podResourceVersion, podID, machine, annotations, dryRun); err != nil {\n\t\terr = storeerr.InterpretGetError(err, api.Resource(\"pods\"), podID)\n\t\terr = storeerr.InterpretUpdateError(err, api.Resource(\"pods\"), podID)\n\t\tif _, ok := err.(*errors.StatusError); !ok {\n\t\t\terr = errors.NewConflict(api.Resource(\"pods/binding\"), podID, err)\n\t\t}\n\t}\n\treturn\n}","line":{"from":254,"to":264}} {"id":100009571,"name":"NamespaceScoped","signature":"func (r *LegacyBindingREST) NamespaceScoped() bool","file":"pkg/registry/core/pod/storage/storage.go","code":"// NamespaceScoped fulfill rest.Scoper\nfunc (r *LegacyBindingREST) NamespaceScoped() bool {\n\treturn r.bindingRest.NamespaceScoped()\n}","line":{"from":273,"to":276}} {"id":100009572,"name":"New","signature":"func (r *LegacyBindingREST) New() runtime.Object","file":"pkg/registry/core/pod/storage/storage.go","code":"// New creates a new binding resource\nfunc (r *LegacyBindingREST) New() runtime.Object {\n\treturn r.bindingRest.New()\n}","line":{"from":278,"to":281}} {"id":100009573,"name":"Destroy","signature":"func (r *LegacyBindingREST) Destroy()","file":"pkg/registry/core/pod/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *LegacyBindingREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":283,"to":287}} {"id":100009574,"name":"Create","signature":"func (r *LegacyBindingREST) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (out runtime.Object, err error)","file":"pkg/registry/core/pod/storage/storage.go","code":"// Create ensures a pod is bound to a specific host.\nfunc (r *LegacyBindingREST) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (out runtime.Object, err error) {\n\tmetadata, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn nil, errors.NewBadRequest(fmt.Sprintf(\"not a Binding object: %T\", obj))\n\t}\n\treturn r.bindingRest.Create(ctx, metadata.GetName(), obj, createValidation, options)\n}","line":{"from":289,"to":296}} {"id":100009575,"name":"GetSingularName","signature":"func (r *LegacyBindingREST) GetSingularName() string","file":"pkg/registry/core/pod/storage/storage.go","code":"func (r *LegacyBindingREST) GetSingularName() string {\n\treturn \"binding\"\n}","line":{"from":298,"to":300}} {"id":100009576,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"pkg/registry/core/pod/storage/storage.go","code":"// New creates a new pod resource\nfunc (r *StatusREST) New() runtime.Object {\n\treturn \u0026api.Pod{}\n}","line":{"from":307,"to":310}} {"id":100009577,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"pkg/registry/core/pod/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":312,"to":316}} {"id":100009578,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/core/pod/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":318,"to":321}} {"id":100009579,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/core/pod/storage/storage.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":323,"to":328}} {"id":100009580,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/pod/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":330,"to":333}} {"id":100009581,"name":"ConvertToTable","signature":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/core/pod/storage/storage.go","code":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":335,"to":337}} {"id":100009582,"name":"Get","signature":"func (r *EphemeralContainersREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/core/pod/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *EphemeralContainersREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":346,"to":349}} {"id":100009583,"name":"New","signature":"func (r *EphemeralContainersREST) New() runtime.Object","file":"pkg/registry/core/pod/storage/storage.go","code":"// New creates a new pod resource\nfunc (r *EphemeralContainersREST) New() runtime.Object {\n\treturn \u0026api.Pod{}\n}","line":{"from":351,"to":354}} {"id":100009584,"name":"Destroy","signature":"func (r *EphemeralContainersREST) Destroy()","file":"pkg/registry/core/pod/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *EphemeralContainersREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":356,"to":360}} {"id":100009585,"name":"Update","signature":"func (r *EphemeralContainersREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/core/pod/storage/storage.go","code":"// Update alters the EphemeralContainers field in PodSpec\nfunc (r *EphemeralContainersREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":362,"to":367}} {"id":100009586,"name":"NamespaceScoped","signature":"func (podStrategy) NamespaceScoped() bool","file":"pkg/registry/core/pod/strategy.go","code":"// NamespaceScoped is true for pods.\nfunc (podStrategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":64,"to":67}} {"id":100009587,"name":"GetResetFields","signature":"func (podStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/pod/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (podStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":69,"to":79}} {"id":100009588,"name":"PrepareForCreate","signature":"func (podStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/core/pod/strategy.go","code":"// PrepareForCreate clears fields that are not allowed to be set by end users on creation.\nfunc (podStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tpod := obj.(*api.Pod)\n\tpod.Status = api.PodStatus{\n\t\tPhase: api.PodPending,\n\t\tQOSClass: qos.GetPodQOS(pod),\n\t}\n\n\tpodutil.DropDisabledPodFields(pod, nil)\n\n\tapplyWaitingForSchedulingGatesCondition(pod)\n}","line":{"from":81,"to":92}} {"id":100009589,"name":"PrepareForUpdate","signature":"func (podStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/core/pod/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (podStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewPod := obj.(*api.Pod)\n\toldPod := old.(*api.Pod)\n\tnewPod.Status = oldPod.Status\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) {\n\t\t// With support for in-place pod resizing, container resources are now mutable.\n\t\t// If container resources are updated with new resource requests values, a pod resize is\n\t\t// desired. The status of this request is reflected by setting Resize field to \"Proposed\"\n\t\t// as a signal to the caller that the request is being considered.\n\t\tpodutil.MarkPodProposedForResize(oldPod, newPod)\n\t}\n\n\tpodutil.DropDisabledPodFields(newPod, oldPod)\n}","line":{"from":94,"to":109}} {"id":100009590,"name":"Validate","signature":"func (podStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/core/pod/strategy.go","code":"// Validate validates a new pod.\nfunc (podStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tpod := obj.(*api.Pod)\n\topts := podutil.GetValidationOptionsFromPodSpecAndMeta(\u0026pod.Spec, nil, \u0026pod.ObjectMeta, nil)\n\treturn corevalidation.ValidatePodCreate(pod, opts)\n}","line":{"from":111,"to":116}} {"id":100009591,"name":"WarningsOnCreate","signature":"func (podStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/core/pod/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (podStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\tnewPod := obj.(*api.Pod)\n\tvar warnings []string\n\tif msgs := utilvalidation.IsDNS1123Label(newPod.Name); len(msgs) != 0 {\n\t\twarnings = append(warnings, fmt.Sprintf(\"metadata.name: this is used in the Pod's hostname, which can result in surprising behavior; a DNS label is recommended: %v\", msgs))\n\t}\n\twarnings = append(warnings, podutil.GetWarningsForPod(ctx, newPod, nil)...)\n\treturn warnings\n}","line":{"from":118,"to":127}} {"id":100009592,"name":"Canonicalize","signature":"func (podStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/core/pod/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (podStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":129,"to":131}} {"id":100009593,"name":"AllowCreateOnUpdate","signature":"func (podStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/core/pod/strategy.go","code":"// AllowCreateOnUpdate is false for pods.\nfunc (podStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":133,"to":136}} {"id":100009594,"name":"ValidateUpdate","signature":"func (podStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/core/pod/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (podStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\t// Allow downward api usage of hugepages on pod update if feature is enabled or if the old pod already had used them.\n\tpod := obj.(*api.Pod)\n\toldPod := old.(*api.Pod)\n\topts := podutil.GetValidationOptionsFromPodSpecAndMeta(\u0026pod.Spec, \u0026oldPod.Spec, \u0026pod.ObjectMeta, \u0026oldPod.ObjectMeta)\n\treturn corevalidation.ValidatePodUpdate(obj.(*api.Pod), old.(*api.Pod), opts)\n}","line":{"from":138,"to":145}} {"id":100009595,"name":"WarningsOnUpdate","signature":"func (podStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/core/pod/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (podStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\t// skip warnings on pod update, since humans don't typically interact directly with pods,\n\t// and we don't want to pay the evaluation cost on what might be a high-frequency update path\n\treturn nil\n}","line":{"from":147,"to":152}} {"id":100009596,"name":"AllowUnconditionalUpdate","signature":"func (podStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/core/pod/strategy.go","code":"// AllowUnconditionalUpdate allows pods to be overwritten\nfunc (podStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":154,"to":157}} {"id":100009597,"name":"CheckGracefulDelete","signature":"func (podStrategy) CheckGracefulDelete(ctx context.Context, obj runtime.Object, options *metav1.DeleteOptions) bool","file":"pkg/registry/core/pod/strategy.go","code":"// CheckGracefulDelete allows a pod to be gracefully deleted. It updates the DeleteOptions to\n// reflect the desired grace value.\nfunc (podStrategy) CheckGracefulDelete(ctx context.Context, obj runtime.Object, options *metav1.DeleteOptions) bool {\n\tif options == nil {\n\t\treturn false\n\t}\n\tpod := obj.(*api.Pod)\n\tperiod := int64(0)\n\t// user has specified a value\n\tif options.GracePeriodSeconds != nil {\n\t\tperiod = *options.GracePeriodSeconds\n\t} else {\n\t\t// use the default value if set, or deletes the pod immediately (0)\n\t\tif pod.Spec.TerminationGracePeriodSeconds != nil {\n\t\t\tperiod = *pod.Spec.TerminationGracePeriodSeconds\n\t\t}\n\t}\n\t// if the pod is not scheduled, delete immediately\n\tif len(pod.Spec.NodeName) == 0 {\n\t\tperiod = 0\n\t}\n\t// if the pod is already terminated, delete immediately\n\tif pod.Status.Phase == api.PodFailed || pod.Status.Phase == api.PodSucceeded {\n\t\tperiod = 0\n\t}\n\n\tif period \u003c 0 {\n\t\tperiod = 1\n\t}\n\n\t// ensure the options and the pod are in sync\n\toptions.GracePeriodSeconds = \u0026period\n\treturn true\n}","line":{"from":159,"to":192}} {"id":100009598,"name":"GetResetFields","signature":"func (podStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/pod/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (podStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t\tfieldpath.MakePathOrDie(\"metadata\", \"deletionTimestamp\"),\n\t\t\tfieldpath.MakePathOrDie(\"metadata\", \"ownerReferences\"),\n\t\t),\n\t}\n}","line":{"from":201,"to":211}} {"id":100009599,"name":"PrepareForUpdate","signature":"func (podStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/core/pod/strategy.go","code":"func (podStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewPod := obj.(*api.Pod)\n\toldPod := old.(*api.Pod)\n\tnewPod.Spec = oldPod.Spec\n\tnewPod.DeletionTimestamp = nil\n\n\t// don't allow the pods/status endpoint to touch owner references since old kubelets corrupt them in a way\n\t// that breaks garbage collection\n\tnewPod.OwnerReferences = oldPod.OwnerReferences\n}","line":{"from":213,"to":222}} {"id":100009600,"name":"ValidateUpdate","signature":"func (podStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/core/pod/strategy.go","code":"func (podStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tpod := obj.(*api.Pod)\n\toldPod := old.(*api.Pod)\n\topts := podutil.GetValidationOptionsFromPodSpecAndMeta(\u0026pod.Spec, \u0026oldPod.Spec, \u0026pod.ObjectMeta, \u0026oldPod.ObjectMeta)\n\n\treturn corevalidation.ValidatePodStatusUpdate(obj.(*api.Pod), old.(*api.Pod), opts)\n}","line":{"from":224,"to":230}} {"id":100009601,"name":"WarningsOnUpdate","signature":"func (podStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/core/pod/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (podStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":232,"to":235}} {"id":100009602,"name":"dropNonEphemeralContainerUpdates","signature":"func dropNonEphemeralContainerUpdates(newPod, oldPod *api.Pod) *api.Pod","file":"pkg/registry/core/pod/strategy.go","code":"// dropNonEphemeralContainerUpdates discards all changes except for pod.Spec.EphemeralContainers and certain metadata\nfunc dropNonEphemeralContainerUpdates(newPod, oldPod *api.Pod) *api.Pod {\n\tpod := oldPod.DeepCopy()\n\tpod.Name = newPod.Name\n\tpod.Namespace = newPod.Namespace\n\tpod.ResourceVersion = newPod.ResourceVersion\n\tpod.UID = newPod.UID\n\tpod.Spec.EphemeralContainers = newPod.Spec.EphemeralContainers\n\treturn pod\n}","line":{"from":244,"to":253}} {"id":100009603,"name":"PrepareForUpdate","signature":"func (podEphemeralContainersStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/core/pod/strategy.go","code":"func (podEphemeralContainersStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewPod := obj.(*api.Pod)\n\toldPod := old.(*api.Pod)\n\n\t*newPod = *dropNonEphemeralContainerUpdates(newPod, oldPod)\n\tpodutil.DropDisabledPodFields(newPod, oldPod)\n}","line":{"from":255,"to":261}} {"id":100009604,"name":"ValidateUpdate","signature":"func (podEphemeralContainersStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/core/pod/strategy.go","code":"func (podEphemeralContainersStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewPod := obj.(*api.Pod)\n\toldPod := old.(*api.Pod)\n\topts := podutil.GetValidationOptionsFromPodSpecAndMeta(\u0026newPod.Spec, \u0026oldPod.Spec, \u0026newPod.ObjectMeta, \u0026oldPod.ObjectMeta)\n\treturn corevalidation.ValidatePodEphemeralContainersUpdate(newPod, oldPod, opts)\n}","line":{"from":263,"to":268}} {"id":100009605,"name":"WarningsOnUpdate","signature":"func (podEphemeralContainersStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/core/pod/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (podEphemeralContainersStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":270,"to":273}} {"id":100009606,"name":"GetAttrs","signature":"func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error)","file":"pkg/registry/core/pod/strategy.go","code":"// GetAttrs returns labels and fields of a given object for filtering purposes.\nfunc GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {\n\tpod, ok := obj.(*api.Pod)\n\tif !ok {\n\t\treturn nil, nil, fmt.Errorf(\"not a pod\")\n\t}\n\treturn labels.Set(pod.ObjectMeta.Labels), ToSelectableFields(pod), nil\n}","line":{"from":275,"to":282}} {"id":100009607,"name":"MatchPod","signature":"func MatchPod(label labels.Selector, field fields.Selector) storage.SelectionPredicate","file":"pkg/registry/core/pod/strategy.go","code":"// MatchPod returns a generic matcher for a given label and field selector.\nfunc MatchPod(label labels.Selector, field fields.Selector) storage.SelectionPredicate {\n\treturn storage.SelectionPredicate{\n\t\tLabel: label,\n\t\tField: field,\n\t\tGetAttrs: GetAttrs,\n\t\tIndexFields: []string{\"spec.nodeName\"},\n\t}\n}","line":{"from":284,"to":292}} {"id":100009608,"name":"NodeNameTriggerFunc","signature":"func NodeNameTriggerFunc(obj runtime.Object) string","file":"pkg/registry/core/pod/strategy.go","code":"// NodeNameTriggerFunc returns value spec.nodename of given object.\nfunc NodeNameTriggerFunc(obj runtime.Object) string {\n\treturn obj.(*api.Pod).Spec.NodeName\n}","line":{"from":294,"to":297}} {"id":100009609,"name":"NodeNameIndexFunc","signature":"func NodeNameIndexFunc(obj interface{}) ([]string, error)","file":"pkg/registry/core/pod/strategy.go","code":"// NodeNameIndexFunc return value spec.nodename of given object.\nfunc NodeNameIndexFunc(obj interface{}) ([]string, error) {\n\tpod, ok := obj.(*api.Pod)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"not a pod\")\n\t}\n\treturn []string{pod.Spec.NodeName}, nil\n}","line":{"from":299,"to":306}} {"id":100009610,"name":"Indexers","signature":"func Indexers() *cache.Indexers","file":"pkg/registry/core/pod/strategy.go","code":"// Indexers returns the indexers for pod storage.\nfunc Indexers() *cache.Indexers {\n\treturn \u0026cache.Indexers{\n\t\tstorage.FieldIndex(\"spec.nodeName\"): NodeNameIndexFunc,\n\t}\n}","line":{"from":308,"to":313}} {"id":100009611,"name":"ToSelectableFields","signature":"func ToSelectableFields(pod *api.Pod) fields.Set","file":"pkg/registry/core/pod/strategy.go","code":"// ToSelectableFields returns a field set that represents the object\n// TODO: fields are not labels, and the validation rules for them do not apply.\nfunc ToSelectableFields(pod *api.Pod) fields.Set {\n\t// The purpose of allocation with a given number of elements is to reduce\n\t// amount of allocations needed to create the fields.Set. If you add any\n\t// field here or the number of object-meta related fields changes, this should\n\t// be adjusted.\n\tpodSpecificFieldsSet := make(fields.Set, 9)\n\tpodSpecificFieldsSet[\"spec.nodeName\"] = pod.Spec.NodeName\n\tpodSpecificFieldsSet[\"spec.restartPolicy\"] = string(pod.Spec.RestartPolicy)\n\tpodSpecificFieldsSet[\"spec.schedulerName\"] = string(pod.Spec.SchedulerName)\n\tpodSpecificFieldsSet[\"spec.serviceAccountName\"] = string(pod.Spec.ServiceAccountName)\n\tpodSpecificFieldsSet[\"status.phase\"] = string(pod.Status.Phase)\n\t// TODO: add podIPs as a downward API value(s) with proper format\n\tpodIP := \"\"\n\tif len(pod.Status.PodIPs) \u003e 0 {\n\t\tpodIP = string(pod.Status.PodIPs[0].IP)\n\t}\n\tpodSpecificFieldsSet[\"status.podIP\"] = podIP\n\tpodSpecificFieldsSet[\"status.nominatedNodeName\"] = string(pod.Status.NominatedNodeName)\n\treturn generic.AddObjectMetaFieldsSet(podSpecificFieldsSet, \u0026pod.ObjectMeta, true)\n}","line":{"from":315,"to":336}} {"id":100009612,"name":"getPod","signature":"func getPod(ctx context.Context, getter ResourceGetter, name string) (*api.Pod, error)","file":"pkg/registry/core/pod/strategy.go","code":"func getPod(ctx context.Context, getter ResourceGetter, name string) (*api.Pod, error) {\n\tobj, err := getter.Get(ctx, name, \u0026metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpod := obj.(*api.Pod)\n\tif pod == nil {\n\t\treturn nil, fmt.Errorf(\"Unexpected object type: %#v\", pod)\n\t}\n\treturn pod, nil\n}","line":{"from":343,"to":353}} {"id":100009613,"name":"getPodIP","signature":"func getPodIP(pod *api.Pod) string","file":"pkg/registry/core/pod/strategy.go","code":"// getPodIP returns primary IP for a Pod\nfunc getPodIP(pod *api.Pod) string {\n\tif pod == nil {\n\t\treturn \"\"\n\t}\n\tif len(pod.Status.PodIPs) \u003e 0 {\n\t\treturn pod.Status.PodIPs[0].IP\n\t}\n\n\treturn \"\"\n}","line":{"from":355,"to":365}} {"id":100009614,"name":"ResourceLocation","signature":"func ResourceLocation(ctx context.Context, getter ResourceGetter, rt http.RoundTripper, id string) (*url.URL, http.RoundTripper, error)","file":"pkg/registry/core/pod/strategy.go","code":"// ResourceLocation returns a URL to which one can send traffic for the specified pod.\nfunc ResourceLocation(ctx context.Context, getter ResourceGetter, rt http.RoundTripper, id string) (*url.URL, http.RoundTripper, error) {\n\t// Allow ID as \"podname\" or \"podname:port\" or \"scheme:podname:port\".\n\t// If port is not specified, try to use the first defined port on the pod.\n\tscheme, name, port, valid := utilnet.SplitSchemeNamePort(id)\n\tif !valid {\n\t\treturn nil, nil, errors.NewBadRequest(fmt.Sprintf(\"invalid pod request %q\", id))\n\t}\n\n\tpod, err := getPod(ctx, getter, name)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Try to figure out a port.\n\tif port == \"\" {\n\t\tfor i := range pod.Spec.Containers {\n\t\t\tif len(pod.Spec.Containers[i].Ports) \u003e 0 {\n\t\t\t\tport = fmt.Sprintf(\"%d\", pod.Spec.Containers[i].Ports[0].ContainerPort)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tpodIP := getPodIP(pod)\n\tif err := proxyutil.IsProxyableIP(podIP); err != nil {\n\t\treturn nil, nil, errors.NewBadRequest(err.Error())\n\t}\n\n\tloc := \u0026url.URL{\n\t\tScheme: scheme,\n\t}\n\tif port == \"\" {\n\t\t// when using an ipv6 IP as a hostname in a URL, it must be wrapped in [...]\n\t\t// net.JoinHostPort does this for you.\n\t\tif strings.Contains(podIP, \":\") {\n\t\t\tloc.Host = \"[\" + podIP + \"]\"\n\t\t} else {\n\t\t\tloc.Host = podIP\n\t\t}\n\t} else {\n\t\tloc.Host = net.JoinHostPort(podIP, port)\n\t}\n\treturn loc, rt, nil\n}","line":{"from":367,"to":410}} {"id":100009615,"name":"LogLocation","signature":"func LogLocation(","file":"pkg/registry/core/pod/strategy.go","code":"// LogLocation returns the log URL for a pod container. If opts.Container is blank\n// and only one container is present in the pod, that container is used.\nfunc LogLocation(\n\tctx context.Context, getter ResourceGetter,\n\tconnInfo client.ConnectionInfoGetter,\n\tname string,\n\topts *api.PodLogOptions,\n) (*url.URL, http.RoundTripper, error) {\n\tpod, err := getPod(ctx, getter, name)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Try to figure out a container\n\t// If a container was provided, it must be valid\n\tcontainer := opts.Container\n\tcontainer, err = validateContainer(container, pod)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tnodeName := types.NodeName(pod.Spec.NodeName)\n\tif len(nodeName) == 0 {\n\t\t// If pod has not been assigned a host, return an empty location\n\t\treturn nil, nil, nil\n\t}\n\tnodeInfo, err := connInfo.GetConnectionInfo(ctx, nodeName)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tparams := url.Values{}\n\tif opts.Follow {\n\t\tparams.Add(\"follow\", \"true\")\n\t}\n\tif opts.Previous {\n\t\tparams.Add(\"previous\", \"true\")\n\t}\n\tif opts.Timestamps {\n\t\tparams.Add(\"timestamps\", \"true\")\n\t}\n\tif opts.SinceSeconds != nil {\n\t\tparams.Add(\"sinceSeconds\", strconv.FormatInt(*opts.SinceSeconds, 10))\n\t}\n\tif opts.SinceTime != nil {\n\t\tparams.Add(\"sinceTime\", opts.SinceTime.Format(time.RFC3339))\n\t}\n\tif opts.TailLines != nil {\n\t\tparams.Add(\"tailLines\", strconv.FormatInt(*opts.TailLines, 10))\n\t}\n\tif opts.LimitBytes != nil {\n\t\tparams.Add(\"limitBytes\", strconv.FormatInt(*opts.LimitBytes, 10))\n\t}\n\tloc := \u0026url.URL{\n\t\tScheme: nodeInfo.Scheme,\n\t\tHost: net.JoinHostPort(nodeInfo.Hostname, nodeInfo.Port),\n\t\tPath: fmt.Sprintf(\"/containerLogs/%s/%s/%s\", pod.Namespace, pod.Name, container),\n\t\tRawQuery: params.Encode(),\n\t}\n\n\tif opts.InsecureSkipTLSVerifyBackend {\n\t\treturn loc, nodeInfo.InsecureSkipTLSVerifyTransport, nil\n\t}\n\treturn loc, nodeInfo.Transport, nil\n}","line":{"from":412,"to":474}} {"id":100009616,"name":"podHasContainerWithName","signature":"func podHasContainerWithName(pod *api.Pod, containerName string) bool","file":"pkg/registry/core/pod/strategy.go","code":"func podHasContainerWithName(pod *api.Pod, containerName string) bool {\n\tvar hasContainer bool\n\tpodutil.VisitContainers(\u0026pod.Spec, podutil.AllFeatureEnabledContainers(), func(c *api.Container, containerType podutil.ContainerType) bool {\n\t\tif c.Name == containerName {\n\t\t\thasContainer = true\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t})\n\treturn hasContainer\n}","line":{"from":476,"to":486}} {"id":100009617,"name":"streamParams","signature":"func streamParams(params url.Values, opts runtime.Object) error","file":"pkg/registry/core/pod/strategy.go","code":"func streamParams(params url.Values, opts runtime.Object) error {\n\tswitch opts := opts.(type) {\n\tcase *api.PodExecOptions:\n\t\tif opts.Stdin {\n\t\t\tparams.Add(api.ExecStdinParam, \"1\")\n\t\t}\n\t\tif opts.Stdout {\n\t\t\tparams.Add(api.ExecStdoutParam, \"1\")\n\t\t}\n\t\tif opts.Stderr {\n\t\t\tparams.Add(api.ExecStderrParam, \"1\")\n\t\t}\n\t\tif opts.TTY {\n\t\t\tparams.Add(api.ExecTTYParam, \"1\")\n\t\t}\n\t\tfor _, c := range opts.Command {\n\t\t\tparams.Add(\"command\", c)\n\t\t}\n\tcase *api.PodAttachOptions:\n\t\tif opts.Stdin {\n\t\t\tparams.Add(api.ExecStdinParam, \"1\")\n\t\t}\n\t\tif opts.Stdout {\n\t\t\tparams.Add(api.ExecStdoutParam, \"1\")\n\t\t}\n\t\tif opts.Stderr {\n\t\t\tparams.Add(api.ExecStderrParam, \"1\")\n\t\t}\n\t\tif opts.TTY {\n\t\t\tparams.Add(api.ExecTTYParam, \"1\")\n\t\t}\n\tcase *api.PodPortForwardOptions:\n\t\tif len(opts.Ports) \u003e 0 {\n\t\t\tports := make([]string, len(opts.Ports))\n\t\t\tfor i, p := range opts.Ports {\n\t\t\t\tports[i] = strconv.FormatInt(int64(p), 10)\n\t\t\t}\n\t\t\tparams.Add(api.PortHeader, strings.Join(ports, \",\"))\n\t\t}\n\tdefault:\n\t\treturn fmt.Errorf(\"Unknown object for streaming: %v\", opts)\n\t}\n\treturn nil\n}","line":{"from":488,"to":531}} {"id":100009618,"name":"AttachLocation","signature":"func AttachLocation(","file":"pkg/registry/core/pod/strategy.go","code":"// AttachLocation returns the attach URL for a pod container. If opts.Container is blank\n// and only one container is present in the pod, that container is used.\nfunc AttachLocation(\n\tctx context.Context,\n\tgetter ResourceGetter,\n\tconnInfo client.ConnectionInfoGetter,\n\tname string,\n\topts *api.PodAttachOptions,\n) (*url.URL, http.RoundTripper, error) {\n\treturn streamLocation(ctx, getter, connInfo, name, opts, opts.Container, \"attach\")\n}","line":{"from":533,"to":543}} {"id":100009619,"name":"ExecLocation","signature":"func ExecLocation(","file":"pkg/registry/core/pod/strategy.go","code":"// ExecLocation returns the exec URL for a pod container. If opts.Container is blank\n// and only one container is present in the pod, that container is used.\nfunc ExecLocation(\n\tctx context.Context,\n\tgetter ResourceGetter,\n\tconnInfo client.ConnectionInfoGetter,\n\tname string,\n\topts *api.PodExecOptions,\n) (*url.URL, http.RoundTripper, error) {\n\treturn streamLocation(ctx, getter, connInfo, name, opts, opts.Container, \"exec\")\n}","line":{"from":545,"to":555}} {"id":100009620,"name":"streamLocation","signature":"func streamLocation(","file":"pkg/registry/core/pod/strategy.go","code":"func streamLocation(\n\tctx context.Context,\n\tgetter ResourceGetter,\n\tconnInfo client.ConnectionInfoGetter,\n\tname string,\n\topts runtime.Object,\n\tcontainer,\n\tpath string,\n) (*url.URL, http.RoundTripper, error) {\n\tpod, err := getPod(ctx, getter, name)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Try to figure out a container\n\t// If a container was provided, it must be valid\n\tcontainer, err = validateContainer(container, pod)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tnodeName := types.NodeName(pod.Spec.NodeName)\n\tif len(nodeName) == 0 {\n\t\t// If pod has not been assigned a host, return an empty location\n\t\treturn nil, nil, errors.NewBadRequest(fmt.Sprintf(\"pod %s does not have a host assigned\", name))\n\t}\n\tnodeInfo, err := connInfo.GetConnectionInfo(ctx, nodeName)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tparams := url.Values{}\n\tif err := streamParams(params, opts); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tloc := \u0026url.URL{\n\t\tScheme: nodeInfo.Scheme,\n\t\tHost: net.JoinHostPort(nodeInfo.Hostname, nodeInfo.Port),\n\t\tPath: fmt.Sprintf(\"/%s/%s/%s/%s\", path, pod.Namespace, pod.Name, container),\n\t\tRawQuery: params.Encode(),\n\t}\n\treturn loc, nodeInfo.Transport, nil\n}","line":{"from":557,"to":598}} {"id":100009621,"name":"PortForwardLocation","signature":"func PortForwardLocation(","file":"pkg/registry/core/pod/strategy.go","code":"// PortForwardLocation returns the port-forward URL for a pod.\nfunc PortForwardLocation(\n\tctx context.Context,\n\tgetter ResourceGetter,\n\tconnInfo client.ConnectionInfoGetter,\n\tname string,\n\topts *api.PodPortForwardOptions,\n) (*url.URL, http.RoundTripper, error) {\n\tpod, err := getPod(ctx, getter, name)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tnodeName := types.NodeName(pod.Spec.NodeName)\n\tif len(nodeName) == 0 {\n\t\t// If pod has not been assigned a host, return an empty location\n\t\treturn nil, nil, errors.NewBadRequest(fmt.Sprintf(\"pod %s does not have a host assigned\", name))\n\t}\n\tnodeInfo, err := connInfo.GetConnectionInfo(ctx, nodeName)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tparams := url.Values{}\n\tif err := streamParams(params, opts); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tloc := \u0026url.URL{\n\t\tScheme: nodeInfo.Scheme,\n\t\tHost: net.JoinHostPort(nodeInfo.Hostname, nodeInfo.Port),\n\t\tPath: fmt.Sprintf(\"/portForward/%s/%s\", pod.Namespace, pod.Name),\n\t\tRawQuery: params.Encode(),\n\t}\n\treturn loc, nodeInfo.Transport, nil\n}","line":{"from":600,"to":633}} {"id":100009622,"name":"validateContainer","signature":"func validateContainer(container string, pod *api.Pod) (string, error)","file":"pkg/registry/core/pod/strategy.go","code":"// validateContainer validate container is valid for pod, return valid container\nfunc validateContainer(container string, pod *api.Pod) (string, error) {\n\tif len(container) == 0 {\n\t\tswitch len(pod.Spec.Containers) {\n\t\tcase 1:\n\t\t\tcontainer = pod.Spec.Containers[0].Name\n\t\tcase 0:\n\t\t\treturn \"\", errors.NewBadRequest(fmt.Sprintf(\"a container name must be specified for pod %s\", pod.Name))\n\t\tdefault:\n\t\t\tvar containerNames []string\n\t\t\tpodutil.VisitContainers(\u0026pod.Spec, podutil.AllFeatureEnabledContainers(), func(c *api.Container, containerType podutil.ContainerType) bool {\n\t\t\t\tcontainerNames = append(containerNames, c.Name)\n\t\t\t\treturn true\n\t\t\t})\n\t\t\terrStr := fmt.Sprintf(\"a container name must be specified for pod %s, choose one of: %s\", pod.Name, containerNames)\n\t\t\treturn \"\", errors.NewBadRequest(errStr)\n\t\t}\n\t} else {\n\t\tif !podHasContainerWithName(pod, container) {\n\t\t\treturn \"\", errors.NewBadRequest(fmt.Sprintf(\"container %s is not valid for pod %s\", container, pod.Name))\n\t\t}\n\t}\n\n\treturn container, nil\n}","line":{"from":635,"to":659}} {"id":100009623,"name":"applyWaitingForSchedulingGatesCondition","signature":"func applyWaitingForSchedulingGatesCondition(pod *api.Pod)","file":"pkg/registry/core/pod/strategy.go","code":"// applyWaitingForSchedulingGatesCondition adds a {type:PodScheduled, reason:WaitingForGates} condition\n// to a new-created Pod if necessary.\nfunc applyWaitingForSchedulingGatesCondition(pod *api.Pod) {\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.PodSchedulingReadiness) ||\n\t\tlen(pod.Spec.SchedulingGates) == 0 {\n\t\treturn\n\t}\n\n\t// If found a condition with type PodScheduled, return.\n\tfor _, condition := range pod.Status.Conditions {\n\t\tif condition.Type == api.PodScheduled {\n\t\t\treturn\n\t\t}\n\t}\n\n\tpod.Status.Conditions = append(pod.Status.Conditions, api.PodCondition{\n\t\tType: api.PodScheduled,\n\t\tStatus: api.ConditionFalse,\n\t\tReason: api.PodReasonSchedulingGated,\n\t\tMessage: \"Scheduling is blocked due to non-empty scheduling gates\",\n\t})\n}","line":{"from":661,"to":682}} {"id":100009624,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error)","file":"pkg/registry/core/podtemplate/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against pod templates.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026api.PodTemplate{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026api.PodTemplateList{} },\n\t\tDefaultQualifiedResource: api.Resource(\"podtemplates\"),\n\t\tSingularQualifiedResource: api.Resource(\"podtemplate\"),\n\n\t\tCreateStrategy: podtemplate.Strategy,\n\t\tUpdateStrategy: podtemplate.Strategy,\n\t\tDeleteStrategy: podtemplate.Strategy,\n\n\t\tReturnDeletedObject: true,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026REST{store}, nil\n}","line":{"from":35,"to":56}} {"id":100009625,"name":"NamespaceScoped","signature":"func (podTemplateStrategy) NamespaceScoped() bool","file":"pkg/registry/core/podtemplate/strategy.go","code":"// NamespaceScoped is true for pod templates.\nfunc (podTemplateStrategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":42,"to":45}} {"id":100009626,"name":"PrepareForCreate","signature":"func (podTemplateStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/core/podtemplate/strategy.go","code":"// PrepareForCreate clears fields that are not allowed to be set by end users on creation.\nfunc (podTemplateStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\ttemplate := obj.(*api.PodTemplate)\n\ttemplate.Generation = 1\n\tpod.DropDisabledTemplateFields(\u0026template.Template, nil)\n}","line":{"from":47,"to":52}} {"id":100009627,"name":"Validate","signature":"func (podTemplateStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/core/podtemplate/strategy.go","code":"// Validate validates a new pod template.\nfunc (podTemplateStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\ttemplate := obj.(*api.PodTemplate)\n\topts := pod.GetValidationOptionsFromPodTemplate(\u0026template.Template, nil)\n\treturn corevalidation.ValidatePodTemplate(template, opts)\n}","line":{"from":54,"to":59}} {"id":100009628,"name":"WarningsOnCreate","signature":"func (podTemplateStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/core/podtemplate/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (podTemplateStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\tnewPodTemplate := obj.(*api.PodTemplate)\n\treturn pod.GetWarningsForPodTemplate(ctx, field.NewPath(\"template\"), \u0026newPodTemplate.Template, nil)\n}","line":{"from":61,"to":65}} {"id":100009629,"name":"Canonicalize","signature":"func (podTemplateStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/core/podtemplate/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (podTemplateStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":67,"to":69}} {"id":100009630,"name":"AllowCreateOnUpdate","signature":"func (podTemplateStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/core/podtemplate/strategy.go","code":"// AllowCreateOnUpdate is false for pod templates.\nfunc (podTemplateStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":71,"to":74}} {"id":100009631,"name":"PrepareForUpdate","signature":"func (podTemplateStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/core/podtemplate/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (podTemplateStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewTemplate := obj.(*api.PodTemplate)\n\toldTemplate := old.(*api.PodTemplate)\n\n\tpod.DropDisabledTemplateFields(\u0026newTemplate.Template, \u0026oldTemplate.Template)\n\n\t// Any changes to the template increment the generation number.\n\t// See metav1.ObjectMeta description for more information on Generation.\n\tif !apiequality.Semantic.DeepEqual(newTemplate.Template, oldTemplate.Template) {\n\t\tnewTemplate.Generation = oldTemplate.Generation + 1\n\t}\n\n}","line":{"from":76,"to":89}} {"id":100009632,"name":"ValidateUpdate","signature":"func (podTemplateStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/core/podtemplate/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (podTemplateStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\ttemplate := obj.(*api.PodTemplate)\n\toldTemplate := old.(*api.PodTemplate)\n\n\t// Allow downward api usage of hugepages on pod update if feature is enabled or if the old pod already had used them.\n\topts := pod.GetValidationOptionsFromPodTemplate(\u0026template.Template, \u0026oldTemplate.Template)\n\treturn corevalidation.ValidatePodTemplateUpdate(template, oldTemplate, opts)\n}","line":{"from":91,"to":99}} {"id":100009633,"name":"WarningsOnUpdate","signature":"func (podTemplateStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/core/podtemplate/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (podTemplateStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\tvar warnings []string\n\tnewTemplate := obj.(*api.PodTemplate)\n\toldTemplate := old.(*api.PodTemplate)\n\tif newTemplate.Generation != oldTemplate.Generation {\n\t\twarnings = pod.GetWarningsForPodTemplate(ctx, field.NewPath(\"template\"), \u0026newTemplate.Template, \u0026oldTemplate.Template)\n\t}\n\treturn warnings\n}","line":{"from":101,"to":110}} {"id":100009634,"name":"AllowUnconditionalUpdate","signature":"func (podTemplateStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/core/podtemplate/strategy.go","code":"func (podTemplateStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":112,"to":114}} {"id":100009635,"name":"ReplicasPathMappings","signature":"func ReplicasPathMappings() managedfields.ResourcePathMappings","file":"pkg/registry/core/replicationcontroller/storage/storage.go","code":"// ReplicasPathMappings returns the mappings between each group version and a replicas path\nfunc ReplicasPathMappings() managedfields.ResourcePathMappings {\n\treturn replicasPathInReplicationController\n}","line":{"from":55,"to":58}} {"id":100009636,"name":"NewStorage","signature":"func NewStorage(optsGetter generic.RESTOptionsGetter) (ControllerStorage, error)","file":"pkg/registry/core/replicationcontroller/storage/storage.go","code":"func NewStorage(optsGetter generic.RESTOptionsGetter) (ControllerStorage, error) {\n\tcontrollerREST, statusREST, err := NewREST(optsGetter)\n\tif err != nil {\n\t\treturn ControllerStorage{}, err\n\t}\n\n\treturn ControllerStorage{\n\t\tController: controllerREST,\n\t\tStatus: statusREST,\n\t\tScale: \u0026ScaleREST{store: controllerREST.Store},\n\t}, nil\n}","line":{"from":65,"to":76}} {"id":100009637,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error)","file":"pkg/registry/core/replicationcontroller/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against replication controllers.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026api.ReplicationController{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026api.ReplicationControllerList{} },\n\t\tPredicateFunc: replicationcontroller.MatchController,\n\t\tDefaultQualifiedResource: api.Resource(\"replicationcontrollers\"),\n\t\tSingularQualifiedResource: api.Resource(\"replicationcontroller\"),\n\n\t\tCreateStrategy: replicationcontroller.Strategy,\n\t\tUpdateStrategy: replicationcontroller.Strategy,\n\t\tDeleteStrategy: replicationcontroller.Strategy,\n\t\tResetFieldsStrategy: replicationcontroller.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: replicationcontroller.GetAttrs}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = replicationcontroller.StatusStrategy\n\tstatusStore.ResetFieldsStrategy = replicationcontroller.StatusStrategy\n\n\treturn \u0026REST{store}, \u0026StatusREST{store: \u0026statusStore}, nil\n}","line":{"from":82,"to":108}} {"id":100009638,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/core/replicationcontroller/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"rc\"}\n}","line":{"from":113,"to":116}} {"id":100009639,"name":"Categories","signature":"func (r *REST) Categories() []string","file":"pkg/registry/core/replicationcontroller/storage/storage.go","code":"// Categories implements the CategoriesProvider interface. Returns a list of categories a resource is part of.\nfunc (r *REST) Categories() []string {\n\treturn []string{\"all\"}\n}","line":{"from":121,"to":124}} {"id":100009640,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"pkg/registry/core/replicationcontroller/storage/storage.go","code":"func (r *StatusREST) New() runtime.Object {\n\treturn \u0026api.ReplicationController{}\n}","line":{"from":131,"to":133}} {"id":100009641,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"pkg/registry/core/replicationcontroller/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":135,"to":139}} {"id":100009642,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/core/replicationcontroller/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":141,"to":144}} {"id":100009643,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/core/replicationcontroller/storage/storage.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":146,"to":151}} {"id":100009644,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/replicationcontroller/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":153,"to":156}} {"id":100009645,"name":"ConvertToTable","signature":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/core/replicationcontroller/storage/storage.go","code":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":158,"to":160}} {"id":100009646,"name":"GroupVersionKind","signature":"func (r *ScaleREST) GroupVersionKind(containingGV schema.GroupVersion) schema.GroupVersionKind","file":"pkg/registry/core/replicationcontroller/storage/storage.go","code":"func (r *ScaleREST) GroupVersionKind(containingGV schema.GroupVersion) schema.GroupVersionKind {\n\tswitch containingGV {\n\tcase extensionsv1beta1.SchemeGroupVersion:\n\t\treturn extensionsv1beta1.SchemeGroupVersion.WithKind(\"Scale\")\n\tdefault:\n\t\treturn autoscalingv1.SchemeGroupVersion.WithKind(\"Scale\")\n\t}\n}","line":{"from":170,"to":177}} {"id":100009647,"name":"New","signature":"func (r *ScaleREST) New() runtime.Object","file":"pkg/registry/core/replicationcontroller/storage/storage.go","code":"// New creates a new Scale object\nfunc (r *ScaleREST) New() runtime.Object {\n\treturn \u0026autoscaling.Scale{}\n}","line":{"from":179,"to":182}} {"id":100009648,"name":"Destroy","signature":"func (r *ScaleREST) Destroy()","file":"pkg/registry/core/replicationcontroller/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *ScaleREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":184,"to":188}} {"id":100009649,"name":"Get","signature":"func (r *ScaleREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/core/replicationcontroller/storage/storage.go","code":"func (r *ScaleREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\tobj, err := r.store.Get(ctx, name, options)\n\tif err != nil {\n\t\treturn nil, errors.NewNotFound(autoscaling.Resource(\"replicationcontrollers/scale\"), name)\n\t}\n\trc := obj.(*api.ReplicationController)\n\treturn scaleFromRC(rc), nil\n}","line":{"from":190,"to":197}} {"id":100009650,"name":"Update","signature":"func (r *ScaleREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/core/replicationcontroller/storage/storage.go","code":"func (r *ScaleREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\tobj, _, err := r.store.Update(\n\t\tctx,\n\t\tname,\n\t\t\u0026scaleUpdatedObjectInfo{name, objInfo},\n\t\ttoScaleCreateValidation(createValidation),\n\t\ttoScaleUpdateValidation(updateValidation),\n\t\tfalse,\n\t\toptions,\n\t)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\trc := obj.(*api.ReplicationController)\n\treturn scaleFromRC(rc), false, nil\n}","line":{"from":199,"to":214}} {"id":100009651,"name":"ConvertToTable","signature":"func (r *ScaleREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/core/replicationcontroller/storage/storage.go","code":"func (r *ScaleREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":216,"to":218}} {"id":100009652,"name":"toScaleCreateValidation","signature":"func toScaleCreateValidation(f rest.ValidateObjectFunc) rest.ValidateObjectFunc","file":"pkg/registry/core/replicationcontroller/storage/storage.go","code":"func toScaleCreateValidation(f rest.ValidateObjectFunc) rest.ValidateObjectFunc {\n\treturn func(ctx context.Context, obj runtime.Object) error {\n\t\treturn f(ctx, scaleFromRC(obj.(*api.ReplicationController)))\n\t}\n}","line":{"from":220,"to":224}} {"id":100009653,"name":"toScaleUpdateValidation","signature":"func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjectUpdateFunc","file":"pkg/registry/core/replicationcontroller/storage/storage.go","code":"func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjectUpdateFunc {\n\treturn func(ctx context.Context, obj, old runtime.Object) error {\n\t\treturn f(\n\t\t\tctx,\n\t\t\tscaleFromRC(obj.(*api.ReplicationController)),\n\t\t\tscaleFromRC(old.(*api.ReplicationController)),\n\t\t)\n\t}\n}","line":{"from":226,"to":234}} {"id":100009654,"name":"scaleFromRC","signature":"func scaleFromRC(rc *api.ReplicationController) *autoscaling.Scale","file":"pkg/registry/core/replicationcontroller/storage/storage.go","code":"// scaleFromRC returns a scale subresource for a replication controller.\nfunc scaleFromRC(rc *api.ReplicationController) *autoscaling.Scale {\n\treturn \u0026autoscaling.Scale{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: rc.Name,\n\t\t\tNamespace: rc.Namespace,\n\t\t\tUID: rc.UID,\n\t\t\tResourceVersion: rc.ResourceVersion,\n\t\t\tCreationTimestamp: rc.CreationTimestamp,\n\t\t},\n\t\tSpec: autoscaling.ScaleSpec{\n\t\t\tReplicas: rc.Spec.Replicas,\n\t\t},\n\t\tStatus: autoscaling.ScaleStatus{\n\t\t\tReplicas: rc.Status.Replicas,\n\t\t\tSelector: labels.SelectorFromSet(rc.Spec.Selector).String(),\n\t\t},\n\t}\n}","line":{"from":236,"to":254}} {"id":100009655,"name":"Preconditions","signature":"func (i *scaleUpdatedObjectInfo) Preconditions() *metav1.Preconditions","file":"pkg/registry/core/replicationcontroller/storage/storage.go","code":"func (i *scaleUpdatedObjectInfo) Preconditions() *metav1.Preconditions {\n\treturn i.reqObjInfo.Preconditions()\n}","line":{"from":262,"to":264}} {"id":100009656,"name":"UpdatedObject","signature":"func (i *scaleUpdatedObjectInfo) UpdatedObject(ctx context.Context, oldObj runtime.Object) (runtime.Object, error)","file":"pkg/registry/core/replicationcontroller/storage/storage.go","code":"func (i *scaleUpdatedObjectInfo) UpdatedObject(ctx context.Context, oldObj runtime.Object) (runtime.Object, error) {\n\treplicationcontroller, ok := oldObj.DeepCopyObject().(*api.ReplicationController)\n\tif !ok {\n\t\treturn nil, errors.NewBadRequest(fmt.Sprintf(\"expected existing object type to be ReplicationController, got %T\", replicationcontroller))\n\t}\n\t// if zero-value, the existing object does not exist\n\tif len(replicationcontroller.ResourceVersion) == 0 {\n\t\treturn nil, errors.NewNotFound(api.Resource(\"replicationcontrollers/scale\"), i.name)\n\t}\n\n\tgroupVersion := schema.GroupVersion{Group: \"\", Version: \"v1\"}\n\tif requestInfo, found := genericapirequest.RequestInfoFrom(ctx); found {\n\t\trequestGroupVersion := schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}\n\t\tif _, ok := replicasPathInReplicationController[requestGroupVersion.String()]; ok {\n\t\t\tgroupVersion = requestGroupVersion\n\t\t} else {\n\t\t\tklog.Fatalf(\"Unrecognized group/version in request info %q\", requestGroupVersion.String())\n\t\t}\n\t}\n\n\tmanagedFieldsHandler := managedfields.NewScaleHandler(\n\t\treplicationcontroller.ManagedFields,\n\t\tgroupVersion,\n\t\treplicasPathInReplicationController,\n\t)\n\n\t// replicationcontroller -\u003e old scale\n\toldScale := scaleFromRC(replicationcontroller)\n\tscaleManagedFields, err := managedFieldsHandler.ToSubresource()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\toldScale.ManagedFields = scaleManagedFields\n\n\t// old scale -\u003e new scale\n\tnewScaleObj, err := i.reqObjInfo.UpdatedObject(ctx, oldScale)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif newScaleObj == nil {\n\t\treturn nil, errors.NewBadRequest(\"nil update passed to Scale\")\n\t}\n\tscale, ok := newScaleObj.(*autoscaling.Scale)\n\tif !ok {\n\t\treturn nil, errors.NewBadRequest(fmt.Sprintf(\"expected input object type to be Scale, but %T\", newScaleObj))\n\t}\n\n\t// validate\n\tif errs := validation.ValidateScale(scale); len(errs) \u003e 0 {\n\t\treturn nil, errors.NewInvalid(autoscaling.Kind(\"Scale\"), replicationcontroller.Name, errs)\n\t}\n\n\t// validate precondition if specified (resourceVersion matching is handled by storage)\n\tif len(scale.UID) \u003e 0 \u0026\u0026 scale.UID != replicationcontroller.UID {\n\t\treturn nil, errors.NewConflict(\n\t\t\tapi.Resource(\"replicationcontrollers/scale\"),\n\t\t\treplicationcontroller.Name,\n\t\t\tfmt.Errorf(\"Precondition failed: UID in precondition: %v, UID in object meta: %v\", scale.UID, replicationcontroller.UID),\n\t\t)\n\t}\n\n\t// move replicas/resourceVersion fields to object and return\n\treplicationcontroller.Spec.Replicas = scale.Spec.Replicas\n\treplicationcontroller.ResourceVersion = scale.ResourceVersion\n\n\tupdatedEntries, err := managedFieldsHandler.ToParent(scale.ManagedFields)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treplicationcontroller.ManagedFields = updatedEntries\n\n\treturn replicationcontroller, nil\n}","line":{"from":266,"to":338}} {"id":100009657,"name":"DefaultGarbageCollectionPolicy","signature":"func (rcStrategy) DefaultGarbageCollectionPolicy(ctx context.Context) rest.GarbageCollectionPolicy","file":"pkg/registry/core/replicationcontroller/strategy.go","code":"// DefaultGarbageCollectionPolicy returns OrphanDependents for v1 for backwards compatibility,\n// and DeleteDependents for all other versions.\nfunc (rcStrategy) DefaultGarbageCollectionPolicy(ctx context.Context) rest.GarbageCollectionPolicy {\n\tvar groupVersion schema.GroupVersion\n\tif requestInfo, found := genericapirequest.RequestInfoFrom(ctx); found {\n\t\tgroupVersion = schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}\n\t}\n\tswitch groupVersion {\n\tcase corev1.SchemeGroupVersion:\n\t\t// for back compatibility\n\t\treturn rest.OrphanDependents\n\tdefault:\n\t\treturn rest.DeleteDependents\n\t}\n}","line":{"from":57,"to":71}} {"id":100009658,"name":"NamespaceScoped","signature":"func (rcStrategy) NamespaceScoped() bool","file":"pkg/registry/core/replicationcontroller/strategy.go","code":"// NamespaceScoped returns true because all Replication Controllers need to be within a namespace.\nfunc (rcStrategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":73,"to":76}} {"id":100009659,"name":"GetResetFields","signature":"func (rcStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/replicationcontroller/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (rcStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":78,"to":88}} {"id":100009660,"name":"PrepareForCreate","signature":"func (rcStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/core/replicationcontroller/strategy.go","code":"// PrepareForCreate clears the status of a replication controller before creation.\nfunc (rcStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tcontroller := obj.(*api.ReplicationController)\n\tcontroller.Status = api.ReplicationControllerStatus{}\n\n\tcontroller.Generation = 1\n\n\tpod.DropDisabledTemplateFields(controller.Spec.Template, nil)\n}","line":{"from":90,"to":98}} {"id":100009661,"name":"PrepareForUpdate","signature":"func (rcStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/core/replicationcontroller/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (rcStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewController := obj.(*api.ReplicationController)\n\toldController := old.(*api.ReplicationController)\n\t// update is not allowed to set status\n\tnewController.Status = oldController.Status\n\n\tpod.DropDisabledTemplateFields(newController.Spec.Template, oldController.Spec.Template)\n\n\t// Any changes to the spec increment the generation number, any changes to the\n\t// status should reflect the generation number of the corresponding object. We push\n\t// the burden of managing the status onto the clients because we can't (in general)\n\t// know here what version of spec the writer of the status has seen. It may seem like\n\t// we can at first -- since obj contains spec -- but in the future we will probably make\n\t// status its own object, and even if we don't, writes may be the result of a\n\t// read-update-write loop, so the contents of spec may not actually be the spec that\n\t// the controller has *seen*.\n\tif !apiequality.Semantic.DeepEqual(oldController.Spec, newController.Spec) {\n\t\tnewController.Generation = oldController.Generation + 1\n\t}\n}","line":{"from":100,"to":120}} {"id":100009662,"name":"Validate","signature":"func (rcStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/core/replicationcontroller/strategy.go","code":"// Validate validates a new replication controller.\nfunc (rcStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tcontroller := obj.(*api.ReplicationController)\n\topts := pod.GetValidationOptionsFromPodTemplate(controller.Spec.Template, nil)\n\treturn corevalidation.ValidateReplicationController(controller, opts)\n}","line":{"from":122,"to":127}} {"id":100009663,"name":"WarningsOnCreate","signature":"func (rcStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/core/replicationcontroller/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (rcStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\tnewRC := obj.(*api.ReplicationController)\n\tvar warnings []string\n\tif msgs := utilvalidation.IsDNS1123Label(newRC.Name); len(msgs) != 0 {\n\t\twarnings = append(warnings, fmt.Sprintf(\"metadata.name: this is used in Pod names and hostnames, which can result in surprising behavior; a DNS label is recommended: %v\", msgs))\n\t}\n\twarnings = append(warnings, pod.GetWarningsForPodTemplate(ctx, field.NewPath(\"spec\", \"template\"), newRC.Spec.Template, nil)...)\n\treturn warnings\n}","line":{"from":129,"to":138}} {"id":100009664,"name":"Canonicalize","signature":"func (rcStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/core/replicationcontroller/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (rcStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":140,"to":142}} {"id":100009665,"name":"AllowCreateOnUpdate","signature":"func (rcStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/core/replicationcontroller/strategy.go","code":"// AllowCreateOnUpdate is false for replication controllers; this means a POST is\n// needed to create one.\nfunc (rcStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":144,"to":148}} {"id":100009666,"name":"ValidateUpdate","signature":"func (rcStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/core/replicationcontroller/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (rcStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\toldRc := old.(*api.ReplicationController)\n\tnewRc := obj.(*api.ReplicationController)\n\n\topts := pod.GetValidationOptionsFromPodTemplate(newRc.Spec.Template, oldRc.Spec.Template)\n\tvalidationErrorList := corevalidation.ValidateReplicationController(newRc, opts)\n\tupdateErrorList := corevalidation.ValidateReplicationControllerUpdate(newRc, oldRc, opts)\n\terrs := append(validationErrorList, updateErrorList...)\n\n\tfor key, value := range helper.NonConvertibleFields(oldRc.Annotations) {\n\t\tparts := strings.Split(key, \"/\")\n\t\tif len(parts) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\tbrokenField := parts[1]\n\n\t\tswitch {\n\t\tcase strings.Contains(brokenField, \"selector\"):\n\t\t\tif !apiequality.Semantic.DeepEqual(oldRc.Spec.Selector, newRc.Spec.Selector) {\n\t\t\t\terrs = append(errs, field.Invalid(field.NewPath(\"spec\").Child(\"selector\"), newRc.Spec.Selector, \"cannot update non-convertible selector\"))\n\t\t\t}\n\t\tdefault:\n\t\t\terrs = append(errs, \u0026field.Error{Type: field.ErrorTypeNotFound, BadValue: value, Field: brokenField, Detail: \"unknown non-convertible field\"})\n\t\t}\n\t}\n\n\treturn errs\n}","line":{"from":150,"to":178}} {"id":100009667,"name":"WarningsOnUpdate","signature":"func (rcStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/core/replicationcontroller/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (rcStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\tvar warnings []string\n\toldRc := old.(*api.ReplicationController)\n\tnewRc := obj.(*api.ReplicationController)\n\tif oldRc.Generation != newRc.Generation {\n\t\twarnings = pod.GetWarningsForPodTemplate(ctx, field.NewPath(\"spec\", \"template\"), oldRc.Spec.Template, newRc.Spec.Template)\n\t}\n\treturn warnings\n}","line":{"from":180,"to":189}} {"id":100009668,"name":"AllowUnconditionalUpdate","signature":"func (rcStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/core/replicationcontroller/strategy.go","code":"func (rcStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":191,"to":193}} {"id":100009669,"name":"ControllerToSelectableFields","signature":"func ControllerToSelectableFields(controller *api.ReplicationController) fields.Set","file":"pkg/registry/core/replicationcontroller/strategy.go","code":"// ControllerToSelectableFields returns a field set that represents the object.\nfunc ControllerToSelectableFields(controller *api.ReplicationController) fields.Set {\n\tobjectMetaFieldsSet := generic.ObjectMetaFieldsSet(\u0026controller.ObjectMeta, true)\n\tcontrollerSpecificFieldsSet := fields.Set{\n\t\t\"status.replicas\": strconv.Itoa(int(controller.Status.Replicas)),\n\t}\n\treturn generic.MergeFieldsSets(objectMetaFieldsSet, controllerSpecificFieldsSet)\n}","line":{"from":195,"to":202}} {"id":100009670,"name":"GetAttrs","signature":"func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error)","file":"pkg/registry/core/replicationcontroller/strategy.go","code":"// GetAttrs returns labels and fields of a given object for filtering purposes.\nfunc GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {\n\trc, ok := obj.(*api.ReplicationController)\n\tif !ok {\n\t\treturn nil, nil, fmt.Errorf(\"given object is not a replication controller\")\n\t}\n\treturn labels.Set(rc.ObjectMeta.Labels), ControllerToSelectableFields(rc), nil\n}","line":{"from":204,"to":211}} {"id":100009671,"name":"MatchController","signature":"func MatchController(label labels.Selector, field fields.Selector) apistorage.SelectionPredicate","file":"pkg/registry/core/replicationcontroller/strategy.go","code":"// MatchController is the filter used by the generic etcd backend to route\n// watch events from etcd to clients of the apiserver only interested in specific\n// labels/fields.\nfunc MatchController(label labels.Selector, field fields.Selector) apistorage.SelectionPredicate {\n\treturn apistorage.SelectionPredicate{\n\t\tLabel: label,\n\t\tField: field,\n\t\tGetAttrs: GetAttrs,\n\t}\n}","line":{"from":213,"to":222}} {"id":100009672,"name":"GetResetFields","signature":"func (rcStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/replicationcontroller/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (rcStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t}\n}","line":{"from":231,"to":239}} {"id":100009673,"name":"PrepareForUpdate","signature":"func (rcStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/core/replicationcontroller/strategy.go","code":"func (rcStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewRc := obj.(*api.ReplicationController)\n\toldRc := old.(*api.ReplicationController)\n\t// update is not allowed to set spec\n\tnewRc.Spec = oldRc.Spec\n}","line":{"from":241,"to":246}} {"id":100009674,"name":"ValidateUpdate","signature":"func (rcStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/core/replicationcontroller/strategy.go","code":"func (rcStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn corevalidation.ValidateReplicationControllerStatusUpdate(obj.(*api.ReplicationController), old.(*api.ReplicationController))\n}","line":{"from":248,"to":250}} {"id":100009675,"name":"WarningsOnUpdate","signature":"func (rcStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/core/replicationcontroller/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (rcStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":252,"to":255}} {"id":100009676,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error)","file":"pkg/registry/core/resourcequota/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against resource quotas.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026api.ResourceQuota{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026api.ResourceQuotaList{} },\n\t\tDefaultQualifiedResource: api.Resource(\"resourcequotas\"),\n\t\tSingularQualifiedResource: api.Resource(\"resourcequota\"),\n\n\t\tCreateStrategy: resourcequota.Strategy,\n\t\tUpdateStrategy: resourcequota.Strategy,\n\t\tDeleteStrategy: resourcequota.Strategy,\n\t\tResetFieldsStrategy: resourcequota.Strategy,\n\t\tReturnDeletedObject: true,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = resourcequota.StatusStrategy\n\tstatusStore.ResetFieldsStrategy = resourcequota.StatusStrategy\n\n\treturn \u0026REST{store}, \u0026StatusREST{store: \u0026statusStore}, nil\n}","line":{"from":40,"to":66}} {"id":100009677,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/core/resourcequota/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"quota\"}\n}","line":{"from":71,"to":74}} {"id":100009678,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"pkg/registry/core/resourcequota/storage/storage.go","code":"// New creates a new ResourceQuota object.\nfunc (r *StatusREST) New() runtime.Object {\n\treturn \u0026api.ResourceQuota{}\n}","line":{"from":81,"to":84}} {"id":100009679,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"pkg/registry/core/resourcequota/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":86,"to":90}} {"id":100009680,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/core/resourcequota/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":92,"to":95}} {"id":100009681,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/core/resourcequota/storage/storage.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":97,"to":102}} {"id":100009682,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/resourcequota/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":104,"to":107}} {"id":100009683,"name":"ConvertToTable","signature":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/core/resourcequota/storage/storage.go","code":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":109,"to":111}} {"id":100009684,"name":"NamespaceScoped","signature":"func (resourcequotaStrategy) NamespaceScoped() bool","file":"pkg/registry/core/resourcequota/strategy.go","code":"// NamespaceScoped is true for resourcequotas.\nfunc (resourcequotaStrategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":41,"to":44}} {"id":100009685,"name":"GetResetFields","signature":"func (resourcequotaStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/resourcequota/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (resourcequotaStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":46,"to":56}} {"id":100009686,"name":"PrepareForCreate","signature":"func (resourcequotaStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/core/resourcequota/strategy.go","code":"// PrepareForCreate clears fields that are not allowed to be set by end users on creation.\nfunc (resourcequotaStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tresourcequota := obj.(*api.ResourceQuota)\n\tresourcequota.Status = api.ResourceQuotaStatus{}\n}","line":{"from":58,"to":62}} {"id":100009687,"name":"PrepareForUpdate","signature":"func (resourcequotaStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/core/resourcequota/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (resourcequotaStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewResourcequota := obj.(*api.ResourceQuota)\n\toldResourcequota := old.(*api.ResourceQuota)\n\tnewResourcequota.Status = oldResourcequota.Status\n}","line":{"from":64,"to":69}} {"id":100009688,"name":"Validate","signature":"func (resourcequotaStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/core/resourcequota/strategy.go","code":"// Validate validates a new resourcequota.\nfunc (resourcequotaStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tresourcequota := obj.(*api.ResourceQuota)\n\treturn validation.ValidateResourceQuota(resourcequota)\n}","line":{"from":71,"to":75}} {"id":100009689,"name":"WarningsOnCreate","signature":"func (resourcequotaStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/core/resourcequota/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (resourcequotaStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":77,"to":80}} {"id":100009690,"name":"Canonicalize","signature":"func (resourcequotaStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/core/resourcequota/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (resourcequotaStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":82,"to":84}} {"id":100009691,"name":"AllowCreateOnUpdate","signature":"func (resourcequotaStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/core/resourcequota/strategy.go","code":"// AllowCreateOnUpdate is false for resourcequotas.\nfunc (resourcequotaStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":86,"to":89}} {"id":100009692,"name":"ValidateUpdate","signature":"func (resourcequotaStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/core/resourcequota/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (resourcequotaStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewObj, oldObj := obj.(*api.ResourceQuota), old.(*api.ResourceQuota)\n\treturn validation.ValidateResourceQuotaUpdate(newObj, oldObj)\n}","line":{"from":91,"to":95}} {"id":100009693,"name":"WarningsOnUpdate","signature":"func (resourcequotaStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/core/resourcequota/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (resourcequotaStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":97,"to":100}} {"id":100009694,"name":"AllowUnconditionalUpdate","signature":"func (resourcequotaStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/core/resourcequota/strategy.go","code":"func (resourcequotaStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":102,"to":104}} {"id":100009695,"name":"GetResetFields","signature":"func (resourcequotaStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/resourcequota/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (resourcequotaStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":113,"to":123}} {"id":100009696,"name":"PrepareForUpdate","signature":"func (resourcequotaStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/core/resourcequota/strategy.go","code":"func (resourcequotaStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewResourcequota := obj.(*api.ResourceQuota)\n\toldResourcequota := old.(*api.ResourceQuota)\n\tnewResourcequota.Spec = oldResourcequota.Spec\n}","line":{"from":125,"to":129}} {"id":100009697,"name":"ValidateUpdate","signature":"func (resourcequotaStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/core/resourcequota/strategy.go","code":"func (resourcequotaStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateResourceQuotaStatusUpdate(obj.(*api.ResourceQuota), old.(*api.ResourceQuota))\n}","line":{"from":131,"to":133}} {"id":100009698,"name":"WarningsOnUpdate","signature":"func (resourcequotaStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/core/resourcequota/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (resourcequotaStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":135,"to":138}} {"id":100009699,"name":"NewLegacyRESTStorage","signature":"func (c LegacyRESTStorageProvider) NewLegacyRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (LegacyRESTStorage, genericapiserver.APIGroupInfo, error)","file":"pkg/registry/core/rest/storage_core.go","code":"func (c LegacyRESTStorageProvider) NewLegacyRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (LegacyRESTStorage, genericapiserver.APIGroupInfo, error) {\n\tapiGroupInfo := genericapiserver.APIGroupInfo{\n\t\tPrioritizedVersions: legacyscheme.Scheme.PrioritizedVersionsForGroup(\"\"),\n\t\tVersionedResourcesStorageMap: map[string]map[string]rest.Storage{},\n\t\tScheme: legacyscheme.Scheme,\n\t\tParameterCodec: legacyscheme.ParameterCodec,\n\t\tNegotiatedSerializer: legacyscheme.Codecs,\n\t}\n\n\tpodDisruptionClient, err := policyclient.NewForConfig(c.LoopbackClientConfig)\n\tif err != nil {\n\t\treturn LegacyRESTStorage{}, genericapiserver.APIGroupInfo{}, err\n\t}\n\trestStorage := LegacyRESTStorage{}\n\n\tpodTemplateStorage, err := podtemplatestore.NewREST(restOptionsGetter)\n\tif err != nil {\n\t\treturn LegacyRESTStorage{}, genericapiserver.APIGroupInfo{}, err\n\t}\n\n\teventStorage, err := eventstore.NewREST(restOptionsGetter, uint64(c.EventTTL.Seconds()))\n\tif err != nil {\n\t\treturn LegacyRESTStorage{}, genericapiserver.APIGroupInfo{}, err\n\t}\n\tlimitRangeStorage, err := limitrangestore.NewREST(restOptionsGetter)\n\tif err != nil {\n\t\treturn LegacyRESTStorage{}, genericapiserver.APIGroupInfo{}, err\n\t}\n\n\tresourceQuotaStorage, resourceQuotaStatusStorage, err := resourcequotastore.NewREST(restOptionsGetter)\n\tif err != nil {\n\t\treturn LegacyRESTStorage{}, genericapiserver.APIGroupInfo{}, err\n\t}\n\tsecretStorage, err := secretstore.NewREST(restOptionsGetter)\n\tif err != nil {\n\t\treturn LegacyRESTStorage{}, genericapiserver.APIGroupInfo{}, err\n\t}\n\tpersistentVolumeStorage, persistentVolumeStatusStorage, err := pvstore.NewREST(restOptionsGetter)\n\tif err != nil {\n\t\treturn LegacyRESTStorage{}, genericapiserver.APIGroupInfo{}, err\n\t}\n\tpersistentVolumeClaimStorage, persistentVolumeClaimStatusStorage, err := pvcstore.NewREST(restOptionsGetter)\n\tif err != nil {\n\t\treturn LegacyRESTStorage{}, genericapiserver.APIGroupInfo{}, err\n\t}\n\tconfigMapStorage, err := configmapstore.NewREST(restOptionsGetter)\n\tif err != nil {\n\t\treturn LegacyRESTStorage{}, genericapiserver.APIGroupInfo{}, err\n\t}\n\n\tnamespaceStorage, namespaceStatusStorage, namespaceFinalizeStorage, err := namespacestore.NewREST(restOptionsGetter)\n\tif err != nil {\n\t\treturn LegacyRESTStorage{}, genericapiserver.APIGroupInfo{}, err\n\t}\n\n\tendpointsStorage, err := endpointsstore.NewREST(restOptionsGetter)\n\tif err != nil {\n\t\treturn LegacyRESTStorage{}, genericapiserver.APIGroupInfo{}, err\n\t}\n\n\tnodeStorage, err := nodestore.NewStorage(restOptionsGetter, c.KubeletClientConfig, c.ProxyTransport)\n\tif err != nil {\n\t\treturn LegacyRESTStorage{}, genericapiserver.APIGroupInfo{}, err\n\t}\n\n\tpodStorage, err := podstore.NewStorage(\n\t\trestOptionsGetter,\n\t\tnodeStorage.KubeletConnectionInfo,\n\t\tc.ProxyTransport,\n\t\tpodDisruptionClient,\n\t)\n\tif err != nil {\n\t\treturn LegacyRESTStorage{}, genericapiserver.APIGroupInfo{}, err\n\t}\n\n\tvar serviceAccountStorage *serviceaccountstore.REST\n\tif c.ServiceAccountIssuer != nil {\n\t\tserviceAccountStorage, err = serviceaccountstore.NewREST(restOptionsGetter, c.ServiceAccountIssuer, c.APIAudiences, c.ServiceAccountMaxExpiration, podStorage.Pod.Store, secretStorage.Store, c.ExtendExpiration)\n\t} else {\n\t\tserviceAccountStorage, err = serviceaccountstore.NewREST(restOptionsGetter, nil, nil, 0, nil, nil, false)\n\t}\n\tif err != nil {\n\t\treturn LegacyRESTStorage{}, genericapiserver.APIGroupInfo{}, err\n\t}\n\n\tvar serviceClusterIPRegistry rangeallocation.RangeRegistry\n\tserviceClusterIPRange := c.ServiceIPRange\n\tif serviceClusterIPRange.IP == nil {\n\t\treturn LegacyRESTStorage{}, genericapiserver.APIGroupInfo{}, fmt.Errorf(\"service clusterIPRange is missing\")\n\t}\n\n\tserviceStorageConfig, err := c.StorageFactory.NewConfig(api.Resource(\"services\"))\n\tif err != nil {\n\t\treturn LegacyRESTStorage{}, genericapiserver.APIGroupInfo{}, err\n\t}\n\tvar serviceClusterIPAllocator, secondaryServiceClusterIPAllocator ipallocator.Interface\n\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.MultiCIDRServiceAllocator) {\n\t\tserviceClusterIPAllocator, err = ipallocator.New(\u0026serviceClusterIPRange, func(max int, rangeSpec string, offset int) (allocator.Interface, error) {\n\t\t\tvar mem allocator.Snapshottable\n\t\t\tmem = allocator.NewAllocationMapWithOffset(max, rangeSpec, offset)\n\t\t\t// TODO etcdallocator package to return a storage interface via the storageFactory\n\t\t\tetcd, err := serviceallocator.NewEtcd(mem, \"/ranges/serviceips\", serviceStorageConfig.ForResource(api.Resource(\"serviceipallocations\")))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tserviceClusterIPRegistry = etcd\n\t\t\treturn etcd, nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn LegacyRESTStorage{}, genericapiserver.APIGroupInfo{}, fmt.Errorf(\"cannot create cluster IP allocator: %v\", err)\n\t\t}\n\t} else {\n\t\tnetworkingv1alphaClient, err := networkingv1alpha1client.NewForConfig(c.LoopbackClientConfig)\n\t\tif err != nil {\n\t\t\treturn LegacyRESTStorage{}, genericapiserver.APIGroupInfo{}, err\n\t\t}\n\t\tserviceClusterIPAllocator, err = ipallocator.NewIPAllocator(\u0026serviceClusterIPRange, networkingv1alphaClient, c.Informers.Networking().V1alpha1().IPAddresses())\n\t\tif err != nil {\n\t\t\treturn LegacyRESTStorage{}, genericapiserver.APIGroupInfo{}, fmt.Errorf(\"cannot create cluster IP allocator: %v\", err)\n\t\t}\n\t}\n\n\tserviceClusterIPAllocator.EnableMetrics()\n\trestStorage.ServiceClusterIPAllocator = serviceClusterIPRegistry\n\n\t// allocator for secondary service ip range\n\tif c.SecondaryServiceIPRange.IP != nil {\n\t\tvar secondaryServiceClusterIPRegistry rangeallocation.RangeRegistry\n\t\tif !utilfeature.DefaultFeatureGate.Enabled(features.MultiCIDRServiceAllocator) {\n\t\t\tsecondaryServiceClusterIPAllocator, err = ipallocator.New(\u0026c.SecondaryServiceIPRange, func(max int, rangeSpec string, offset int) (allocator.Interface, error) {\n\t\t\t\tvar mem allocator.Snapshottable\n\t\t\t\tmem = allocator.NewAllocationMapWithOffset(max, rangeSpec, offset)\n\t\t\t\t// TODO etcdallocator package to return a storage interface via the storageFactory\n\t\t\t\tetcd, err := serviceallocator.NewEtcd(mem, \"/ranges/secondaryserviceips\", serviceStorageConfig.ForResource(api.Resource(\"serviceipallocations\")))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tsecondaryServiceClusterIPRegistry = etcd\n\t\t\t\treturn etcd, nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn LegacyRESTStorage{}, genericapiserver.APIGroupInfo{}, fmt.Errorf(\"cannot create cluster secondary IP allocator: %v\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tnetworkingv1alphaClient, err := networkingv1alpha1client.NewForConfig(c.LoopbackClientConfig)\n\t\t\tif err != nil {\n\t\t\t\treturn LegacyRESTStorage{}, genericapiserver.APIGroupInfo{}, err\n\t\t\t}\n\t\t\tsecondaryServiceClusterIPAllocator, err = ipallocator.NewIPAllocator(\u0026c.SecondaryServiceIPRange, networkingv1alphaClient, c.Informers.Networking().V1alpha1().IPAddresses())\n\t\t\tif err != nil {\n\t\t\t\treturn LegacyRESTStorage{}, genericapiserver.APIGroupInfo{}, fmt.Errorf(\"cannot create cluster secondary IP allocator: %v\", err)\n\t\t\t}\n\t\t}\n\t\tsecondaryServiceClusterIPAllocator.EnableMetrics()\n\t\trestStorage.SecondaryServiceClusterIPAllocator = secondaryServiceClusterIPRegistry\n\t}\n\n\tvar serviceNodePortRegistry rangeallocation.RangeRegistry\n\tserviceNodePortAllocator, err := portallocator.New(c.ServiceNodePortRange, func(max int, rangeSpec string, offset int) (allocator.Interface, error) {\n\t\tmem := allocator.NewAllocationMapWithOffset(max, rangeSpec, offset)\n\t\t// TODO etcdallocator package to return a storage interface via the storageFactory\n\t\tetcd, err := serviceallocator.NewEtcd(mem, \"/ranges/servicenodeports\", serviceStorageConfig.ForResource(api.Resource(\"servicenodeportallocations\")))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tserviceNodePortRegistry = etcd\n\t\treturn etcd, nil\n\t})\n\tif err != nil {\n\t\treturn LegacyRESTStorage{}, genericapiserver.APIGroupInfo{}, fmt.Errorf(\"cannot create cluster port allocator: %v\", err)\n\t}\n\tserviceNodePortAllocator.EnableMetrics()\n\trestStorage.ServiceNodePortAllocator = serviceNodePortRegistry\n\n\tcontrollerStorage, err := controllerstore.NewStorage(restOptionsGetter)\n\tif err != nil {\n\t\treturn LegacyRESTStorage{}, genericapiserver.APIGroupInfo{}, err\n\t}\n\n\tserviceIPAllocators := map[api.IPFamily]ipallocator.Interface{\n\t\tserviceClusterIPAllocator.IPFamily(): serviceClusterIPAllocator,\n\t}\n\tif secondaryServiceClusterIPAllocator != nil {\n\t\tserviceIPAllocators[secondaryServiceClusterIPAllocator.IPFamily()] = secondaryServiceClusterIPAllocator\n\t}\n\n\tserviceRESTStorage, serviceStatusStorage, serviceRESTProxy, err := servicestore.NewREST(\n\t\trestOptionsGetter,\n\t\tserviceClusterIPAllocator.IPFamily(),\n\t\tserviceIPAllocators,\n\t\tserviceNodePortAllocator,\n\t\tendpointsStorage,\n\t\tpodStorage.Pod,\n\t\tc.ProxyTransport)\n\tif err != nil {\n\t\treturn LegacyRESTStorage{}, genericapiserver.APIGroupInfo{}, err\n\t}\n\n\tstorage := map[string]rest.Storage{}\n\tif resource := \"pods\"; apiResourceConfigSource.ResourceEnabled(corev1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = podStorage.Pod\n\t\tstorage[resource+\"/attach\"] = podStorage.Attach\n\t\tstorage[resource+\"/status\"] = podStorage.Status\n\t\tstorage[resource+\"/log\"] = podStorage.Log\n\t\tstorage[resource+\"/exec\"] = podStorage.Exec\n\t\tstorage[resource+\"/portforward\"] = podStorage.PortForward\n\t\tstorage[resource+\"/proxy\"] = podStorage.Proxy\n\t\tstorage[resource+\"/binding\"] = podStorage.Binding\n\t\tif podStorage.Eviction != nil {\n\t\t\tstorage[resource+\"/eviction\"] = podStorage.Eviction\n\t\t}\n\t\tstorage[resource+\"/ephemeralcontainers\"] = podStorage.EphemeralContainers\n\n\t}\n\tif resource := \"bindings\"; apiResourceConfigSource.ResourceEnabled(corev1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = podStorage.LegacyBinding\n\t}\n\n\tif resource := \"podtemplates\"; apiResourceConfigSource.ResourceEnabled(corev1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = podTemplateStorage\n\t}\n\n\tif resource := \"replicationcontrollers\"; apiResourceConfigSource.ResourceEnabled(corev1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = controllerStorage.Controller\n\t\tstorage[resource+\"/status\"] = controllerStorage.Status\n\t\tif legacyscheme.Scheme.IsVersionRegistered(schema.GroupVersion{Group: \"autoscaling\", Version: \"v1\"}) {\n\t\t\tstorage[resource+\"/scale\"] = controllerStorage.Scale\n\t\t}\n\t}\n\n\tif resource := \"services\"; apiResourceConfigSource.ResourceEnabled(corev1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = serviceRESTStorage\n\t\tstorage[resource+\"/proxy\"] = serviceRESTProxy\n\t\tstorage[resource+\"/status\"] = serviceStatusStorage\n\t}\n\n\tif resource := \"endpoints\"; apiResourceConfigSource.ResourceEnabled(corev1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = endpointsStorage\n\t}\n\n\tif resource := \"nodes\"; apiResourceConfigSource.ResourceEnabled(corev1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = nodeStorage.Node\n\t\tstorage[resource+\"/proxy\"] = nodeStorage.Proxy\n\t\tstorage[resource+\"/status\"] = nodeStorage.Status\n\t}\n\n\tif resource := \"events\"; apiResourceConfigSource.ResourceEnabled(corev1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = eventStorage\n\t}\n\n\tif resource := \"limitranges\"; apiResourceConfigSource.ResourceEnabled(corev1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = limitRangeStorage\n\t}\n\n\tif resource := \"resourcequotas\"; apiResourceConfigSource.ResourceEnabled(corev1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = resourceQuotaStorage\n\t\tstorage[resource+\"/status\"] = resourceQuotaStatusStorage\n\t}\n\n\tif resource := \"namespaces\"; apiResourceConfigSource.ResourceEnabled(corev1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = namespaceStorage\n\t\tstorage[resource+\"/status\"] = namespaceStatusStorage\n\t\tstorage[resource+\"/finalize\"] = namespaceFinalizeStorage\n\t}\n\n\tif resource := \"secrets\"; apiResourceConfigSource.ResourceEnabled(corev1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = secretStorage\n\t}\n\n\tif resource := \"serviceaccounts\"; apiResourceConfigSource.ResourceEnabled(corev1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = serviceAccountStorage\n\t\tif serviceAccountStorage.Token != nil {\n\t\t\tstorage[resource+\"/token\"] = serviceAccountStorage.Token\n\t\t}\n\t}\n\n\tif resource := \"persistentvolumes\"; apiResourceConfigSource.ResourceEnabled(corev1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = persistentVolumeStorage\n\t\tstorage[resource+\"/status\"] = persistentVolumeStatusStorage\n\t}\n\n\tif resource := \"persistentvolumeclaims\"; apiResourceConfigSource.ResourceEnabled(corev1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = persistentVolumeClaimStorage\n\t\tstorage[resource+\"/status\"] = persistentVolumeClaimStatusStorage\n\t}\n\n\tif resource := \"configmaps\"; apiResourceConfigSource.ResourceEnabled(corev1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = configMapStorage\n\t}\n\n\tif resource := \"componentstatuses\"; apiResourceConfigSource.ResourceEnabled(corev1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = componentstatus.NewStorage(componentStatusStorage{c.StorageFactory}.serversToValidate)\n\t}\n\n\tif len(storage) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[\"v1\"] = storage\n\t}\n\n\treturn restStorage, apiGroupInfo, nil\n}","line":{"from":103,"to":403}} {"id":100009700,"name":"GroupName","signature":"func (p LegacyRESTStorageProvider) GroupName() string","file":"pkg/registry/core/rest/storage_core.go","code":"func (p LegacyRESTStorageProvider) GroupName() string {\n\treturn api.GroupName\n}","line":{"from":405,"to":407}} {"id":100009701,"name":"serversToValidate","signature":"func (s componentStatusStorage) serversToValidate() map[string]componentstatus.Server","file":"pkg/registry/core/rest/storage_core.go","code":"func (s componentStatusStorage) serversToValidate() map[string]componentstatus.Server {\n\t// this is fragile, which assumes that the default port is being used\n\t// TODO: switch to secure port until these components remove the ability to serve insecurely.\n\tserversToValidate := map[string]componentstatus.Server{\n\t\t\"controller-manager\": \u0026componentstatus.HttpServer{EnableHTTPS: true, TLSConfig: \u0026tls.Config{InsecureSkipVerify: true}, Addr: \"127.0.0.1\", Port: ports.KubeControllerManagerPort, Path: \"/healthz\"},\n\t\t\"scheduler\": \u0026componentstatus.HttpServer{EnableHTTPS: true, TLSConfig: \u0026tls.Config{InsecureSkipVerify: true}, Addr: \"127.0.0.1\", Port: kubeschedulerconfig.DefaultKubeSchedulerPort, Path: \"/healthz\"},\n\t}\n\n\tfor ix, cfg := range s.storageFactory.Configs() {\n\t\tserversToValidate[fmt.Sprintf(\"etcd-%d\", ix)] = \u0026componentstatus.EtcdServer{Config: cfg}\n\t}\n\treturn serversToValidate\n}","line":{"from":413,"to":425}} {"id":100009702,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error)","file":"pkg/registry/core/secret/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against secrets.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026api.Secret{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026api.SecretList{} },\n\t\tPredicateFunc: secret.Matcher,\n\t\tDefaultQualifiedResource: api.Resource(\"secrets\"),\n\t\tSingularQualifiedResource: api.Resource(\"secret\"),\n\n\t\tCreateStrategy: secret.Strategy,\n\t\tUpdateStrategy: secret.Strategy,\n\t\tDeleteStrategy: secret.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{\n\t\tRESTOptions: optsGetter,\n\t\tAttrFunc: secret.GetAttrs,\n\t}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026REST{store}, nil\n}","line":{"from":35,"to":58}} {"id":100009703,"name":"NamespaceScoped","signature":"func (strategy) NamespaceScoped() bool","file":"pkg/registry/core/secret/strategy.go","code":"func (strategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":51,"to":53}} {"id":100009704,"name":"PrepareForCreate","signature":"func (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/core/secret/strategy.go","code":"func (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tsecret := obj.(*api.Secret)\n\tdropDisabledFields(secret, nil)\n}","line":{"from":55,"to":58}} {"id":100009705,"name":"Validate","signature":"func (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/core/secret/strategy.go","code":"func (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\treturn validation.ValidateSecret(obj.(*api.Secret))\n}","line":{"from":60,"to":62}} {"id":100009706,"name":"WarningsOnCreate","signature":"func (strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/core/secret/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn warningsForSecret(obj.(*api.Secret))\n}","line":{"from":64,"to":67}} {"id":100009707,"name":"Canonicalize","signature":"func (strategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/core/secret/strategy.go","code":"func (strategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":69,"to":70}} {"id":100009708,"name":"AllowCreateOnUpdate","signature":"func (strategy) AllowCreateOnUpdate() bool","file":"pkg/registry/core/secret/strategy.go","code":"func (strategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":72,"to":74}} {"id":100009709,"name":"PrepareForUpdate","signature":"func (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/core/secret/strategy.go","code":"func (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewSecret := obj.(*api.Secret)\n\toldSecret := old.(*api.Secret)\n\n\t// this is weird, but consistent with what the validatedUpdate function used to do.\n\tif len(newSecret.Type) == 0 {\n\t\tnewSecret.Type = oldSecret.Type\n\t}\n\n\tdropDisabledFields(newSecret, oldSecret)\n}","line":{"from":76,"to":86}} {"id":100009710,"name":"ValidateUpdate","signature":"func (strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/core/secret/strategy.go","code":"func (strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateSecretUpdate(obj.(*api.Secret), old.(*api.Secret))\n}","line":{"from":88,"to":90}} {"id":100009711,"name":"WarningsOnUpdate","signature":"func (strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/core/secret/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn warningsForSecret(obj.(*api.Secret))\n}","line":{"from":92,"to":95}} {"id":100009712,"name":"dropDisabledFields","signature":"func dropDisabledFields(secret *api.Secret, oldSecret *api.Secret)","file":"pkg/registry/core/secret/strategy.go","code":"func dropDisabledFields(secret *api.Secret, oldSecret *api.Secret) {\n}","line":{"from":97,"to":98}} {"id":100009713,"name":"AllowUnconditionalUpdate","signature":"func (strategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/core/secret/strategy.go","code":"func (strategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":100,"to":102}} {"id":100009714,"name":"GetAttrs","signature":"func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error)","file":"pkg/registry/core/secret/strategy.go","code":"// GetAttrs returns labels and fields of a given object for filtering purposes.\nfunc GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {\n\tsecret, ok := obj.(*api.Secret)\n\tif !ok {\n\t\treturn nil, nil, fmt.Errorf(\"not a secret\")\n\t}\n\treturn labels.Set(secret.Labels), SelectableFields(secret), nil\n}","line":{"from":104,"to":111}} {"id":100009715,"name":"Matcher","signature":"func Matcher(label labels.Selector, field fields.Selector) pkgstorage.SelectionPredicate","file":"pkg/registry/core/secret/strategy.go","code":"// Matcher returns a selection predicate for a given label and field selector.\nfunc Matcher(label labels.Selector, field fields.Selector) pkgstorage.SelectionPredicate {\n\treturn pkgstorage.SelectionPredicate{\n\t\tLabel: label,\n\t\tField: field,\n\t\tGetAttrs: GetAttrs,\n\t}\n}","line":{"from":113,"to":120}} {"id":100009716,"name":"SelectableFields","signature":"func SelectableFields(obj *api.Secret) fields.Set","file":"pkg/registry/core/secret/strategy.go","code":"// SelectableFields returns a field set that can be used for filter selection\nfunc SelectableFields(obj *api.Secret) fields.Set {\n\tobjectMetaFieldsSet := generic.ObjectMetaFieldsSet(\u0026obj.ObjectMeta, true)\n\tsecretSpecificFieldsSet := fields.Set{\n\t\t\"type\": string(obj.Type),\n\t}\n\treturn generic.MergeFieldsSets(objectMetaFieldsSet, secretSpecificFieldsSet)\n}","line":{"from":122,"to":129}} {"id":100009717,"name":"warningsForSecret","signature":"func warningsForSecret(secret *api.Secret) []string","file":"pkg/registry/core/secret/strategy.go","code":"func warningsForSecret(secret *api.Secret) []string {\n\tvar warnings []string\n\tif secret.Type == api.SecretTypeTLS {\n\t\t// Verify that the key matches the cert.\n\t\t_, err := tls.X509KeyPair(secret.Data[api.TLSCertKey], secret.Data[api.TLSPrivateKeyKey])\n\t\tif err != nil {\n\t\t\twarnings = append(warnings, err.Error())\n\t\t}\n\t}\n\treturn warnings\n}","line":{"from":131,"to":141}} {"id":100009718,"name":"NewAllocationMap","signature":"func NewAllocationMap(max int, rangeSpec string) *AllocationBitmap","file":"pkg/registry/core/service/allocator/bitmap.go","code":"// NewAllocationMap creates an allocation bitmap using the random scan strategy.\nfunc NewAllocationMap(max int, rangeSpec string) *AllocationBitmap {\n\treturn NewAllocationMapWithOffset(max, rangeSpec, 0)\n}","line":{"from":62,"to":65}} {"id":100009719,"name":"NewAllocationMapWithOffset","signature":"func NewAllocationMapWithOffset(max int, rangeSpec string, offset int) *AllocationBitmap","file":"pkg/registry/core/service/allocator/bitmap.go","code":"// NewAllocationMapWithOffset creates an allocation bitmap using a random scan strategy that\n// allows to pass an offset that divides the allocation bitmap in two blocks.\n// The first block of values will not be used for random value assigned by the AllocateNext()\n// method until the second block of values has been exhausted.\n// The offset value must be always smaller than the bitmap size.\nfunc NewAllocationMapWithOffset(max int, rangeSpec string, offset int) *AllocationBitmap {\n\ta := AllocationBitmap{\n\t\tstrategy: randomScanStrategyWithOffset{\n\t\t\trand: rand.New(rand.NewSource(time.Now().UnixNano())),\n\t\t\toffset: offset,\n\t\t},\n\t\tallocated: big.NewInt(0),\n\t\tcount: 0,\n\t\tmax: max,\n\t\trangeSpec: rangeSpec,\n\t}\n\n\treturn \u0026a\n}","line":{"from":67,"to":85}} {"id":100009720,"name":"Allocate","signature":"func (r *AllocationBitmap) Allocate(offset int) (bool, error)","file":"pkg/registry/core/service/allocator/bitmap.go","code":"// Allocate attempts to reserve the provided item.\n// Returns true if it was allocated, false if it was already in use\nfunc (r *AllocationBitmap) Allocate(offset int) (bool, error) {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\n\t// max is the maximum size of the usable items in the range\n\tif offset \u003c 0 || offset \u003e= r.max {\n\t\treturn false, fmt.Errorf(\"offset %d out of range [0,%d]\", offset, r.max)\n\t}\n\tif r.allocated.Bit(offset) == 1 {\n\t\treturn false, nil\n\t}\n\tr.allocated = r.allocated.SetBit(r.allocated, offset, 1)\n\tr.count++\n\treturn true, nil\n}","line":{"from":87,"to":103}} {"id":100009721,"name":"AllocateNext","signature":"func (r *AllocationBitmap) AllocateNext() (int, bool, error)","file":"pkg/registry/core/service/allocator/bitmap.go","code":"// AllocateNext reserves one of the items from the pool.\n// (0, false, nil) may be returned if there are no items left.\nfunc (r *AllocationBitmap) AllocateNext() (int, bool, error) {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\n\tnext, ok := r.strategy.AllocateBit(r.allocated, r.max, r.count)\n\tif !ok {\n\t\treturn 0, false, nil\n\t}\n\tr.count++\n\tr.allocated = r.allocated.SetBit(r.allocated, next, 1)\n\treturn next, true, nil\n}","line":{"from":105,"to":118}} {"id":100009722,"name":"Release","signature":"func (r *AllocationBitmap) Release(offset int) error","file":"pkg/registry/core/service/allocator/bitmap.go","code":"// Release releases the item back to the pool. Releasing an\n// unallocated item or an item out of the range is a no-op and\n// returns no error.\nfunc (r *AllocationBitmap) Release(offset int) error {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\n\tif r.allocated.Bit(offset) == 0 {\n\t\treturn nil\n\t}\n\n\tr.allocated = r.allocated.SetBit(r.allocated, offset, 0)\n\tr.count--\n\treturn nil\n}","line":{"from":120,"to":134}} {"id":100009723,"name":"ForEach","signature":"func (r *AllocationBitmap) ForEach(fn func(int))","file":"pkg/registry/core/service/allocator/bitmap.go","code":"// ForEach calls the provided function for each allocated bit. The\n// AllocationBitmap may not be modified while this loop is running.\nfunc (r *AllocationBitmap) ForEach(fn func(int)) {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\n\twords := r.allocated.Bits()\n\tfor wordIdx, word := range words {\n\t\tbit := 0\n\t\tfor word \u003e 0 {\n\t\t\tif (word \u0026 1) != 0 {\n\t\t\t\tfn((wordIdx * wordSize * 8) + bit)\n\t\t\t\tword = word \u0026^ 1\n\t\t\t}\n\t\t\tbit++\n\t\t\tword = word \u003e\u003e 1\n\t\t}\n\t}\n}","line":{"from":143,"to":161}} {"id":100009724,"name":"Has","signature":"func (r *AllocationBitmap) Has(offset int) bool","file":"pkg/registry/core/service/allocator/bitmap.go","code":"// Has returns true if the provided item is already allocated and a call\n// to Allocate(offset) would fail.\nfunc (r *AllocationBitmap) Has(offset int) bool {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\n\treturn r.allocated.Bit(offset) == 1\n}","line":{"from":163,"to":170}} {"id":100009725,"name":"Free","signature":"func (r *AllocationBitmap) Free() int","file":"pkg/registry/core/service/allocator/bitmap.go","code":"// Free returns the count of items left in the range.\nfunc (r *AllocationBitmap) Free() int {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\treturn r.max - r.count\n}","line":{"from":172,"to":177}} {"id":100009726,"name":"Snapshot","signature":"func (r *AllocationBitmap) Snapshot() (string, []byte)","file":"pkg/registry/core/service/allocator/bitmap.go","code":"// Snapshot saves the current state of the pool.\nfunc (r *AllocationBitmap) Snapshot() (string, []byte) {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\n\treturn r.rangeSpec, r.allocated.Bytes()\n}","line":{"from":179,"to":185}} {"id":100009727,"name":"Restore","signature":"func (r *AllocationBitmap) Restore(rangeSpec string, data []byte) error","file":"pkg/registry/core/service/allocator/bitmap.go","code":"// Restore restores the pool to the previously captured state.\nfunc (r *AllocationBitmap) Restore(rangeSpec string, data []byte) error {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\n\tif r.rangeSpec != rangeSpec {\n\t\treturn errors.New(\"the provided range does not match the current range\")\n\t}\n\n\tr.allocated = big.NewInt(0).SetBytes(data)\n\tr.count = countBits(r.allocated)\n\n\treturn nil\n}","line":{"from":187,"to":200}} {"id":100009728,"name":"Destroy","signature":"func (r *AllocationBitmap) Destroy()","file":"pkg/registry/core/service/allocator/bitmap.go","code":"// Destroy cleans up everything on shutdown.\nfunc (r *AllocationBitmap) Destroy() {\n}","line":{"from":202,"to":204}} {"id":100009729,"name":"AllocateBit","signature":"func (rss randomScanStrategy) AllocateBit(allocated *big.Int, max, count int) (int, bool)","file":"pkg/registry/core/service/allocator/bitmap.go","code":"func (rss randomScanStrategy) AllocateBit(allocated *big.Int, max, count int) (int, bool) {\n\tif count \u003e= max {\n\t\treturn 0, false\n\t}\n\toffset := rss.rand.Intn(max)\n\tfor i := 0; i \u003c max; i++ {\n\t\tat := (offset + i) % max\n\t\tif allocated.Bit(at) == 0 {\n\t\t\treturn at, true\n\t\t}\n\t}\n\treturn 0, false\n}","line":{"from":213,"to":225}} {"id":100009730,"name":"AllocateBit","signature":"func (rss randomScanStrategyWithOffset) AllocateBit(allocated *big.Int, max, count int) (int, bool)","file":"pkg/registry/core/service/allocator/bitmap.go","code":"func (rss randomScanStrategyWithOffset) AllocateBit(allocated *big.Int, max, count int) (int, bool) {\n\tif count \u003e= max {\n\t\treturn 0, false\n\t}\n\t// size of the upper subrange, prioritized for random allocation\n\tsubrangeMax := max - rss.offset\n\t// try to get a value from the upper range [rss.reserved, max]\n\tstart := rss.rand.Intn(subrangeMax)\n\tfor i := 0; i \u003c subrangeMax; i++ {\n\t\tat := rss.offset + ((start + i) % subrangeMax)\n\t\tif allocated.Bit(at) == 0 {\n\t\t\treturn at, true\n\t\t}\n\t}\n\n\tstart = rss.rand.Intn(rss.offset)\n\t// subrange full, try to get the value from the first block before giving up.\n\tfor i := 0; i \u003c rss.offset; i++ {\n\t\tat := (start + i) % rss.offset\n\t\tif allocated.Bit(at) == 0 {\n\t\t\treturn at, true\n\t\t}\n\t}\n\treturn 0, false\n}","line":{"from":238,"to":262}} {"id":100009731,"name":"NewEtcd","signature":"func NewEtcd(alloc allocator.Snapshottable, baseKey string, config *storagebackend.ConfigForResource) (*Etcd, error)","file":"pkg/registry/core/service/allocator/storage/storage.go","code":"// NewEtcd returns an allocator that is backed by Etcd and can manage\n// persisting the snapshot state of allocation after each allocation is made.\nfunc NewEtcd(alloc allocator.Snapshottable, baseKey string, config *storagebackend.ConfigForResource) (*Etcd, error) {\n\tstorage, d, err := generic.NewRawStorage(config, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar once sync.Once\n\treturn \u0026Etcd{\n\t\talloc: alloc,\n\t\tstorage: storage,\n\t\tbaseKey: baseKey,\n\t\tresource: config.GroupResource,\n\t\tdestroyFn: func() { once.Do(d) },\n\t}, nil\n}","line":{"from":63,"to":79}} {"id":100009732,"name":"Allocate","signature":"func (e *Etcd) Allocate(offset int) (bool, error)","file":"pkg/registry/core/service/allocator/storage/storage.go","code":"// Allocate attempts to allocate the item.\nfunc (e *Etcd) Allocate(offset int) (bool, error) {\n\te.lock.Lock()\n\tdefer e.lock.Unlock()\n\n\terr := e.tryUpdate(func() error {\n\t\tok, err := e.alloc.Allocate(offset)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !ok {\n\t\t\treturn errorUnableToAllocate\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tif err == errorUnableToAllocate {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn false, err\n\t}\n\treturn true, nil\n}","line":{"from":81,"to":103}} {"id":100009733,"name":"AllocateNext","signature":"func (e *Etcd) AllocateNext() (int, bool, error)","file":"pkg/registry/core/service/allocator/storage/storage.go","code":"// AllocateNext attempts to allocate the next item.\nfunc (e *Etcd) AllocateNext() (int, bool, error) {\n\te.lock.Lock()\n\tdefer e.lock.Unlock()\n\tvar offset int\n\tvar ok bool\n\tvar err error\n\n\terr = e.tryUpdate(func() error {\n\t\t// update the offset here\n\t\toffset, ok, err = e.alloc.AllocateNext()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !ok {\n\t\t\treturn errorUnableToAllocate\n\t\t}\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tif err == errorUnableToAllocate {\n\t\t\treturn offset, false, nil\n\t\t}\n\t\treturn offset, false, err\n\t}\n\treturn offset, true, nil\n}","line":{"from":105,"to":132}} {"id":100009734,"name":"Release","signature":"func (e *Etcd) Release(item int) error","file":"pkg/registry/core/service/allocator/storage/storage.go","code":"// Release attempts to release the provided item.\nfunc (e *Etcd) Release(item int) error {\n\te.lock.Lock()\n\tdefer e.lock.Unlock()\n\n\treturn e.tryUpdate(func() error {\n\t\treturn e.alloc.Release(item)\n\t})\n\n}","line":{"from":134,"to":143}} {"id":100009735,"name":"ForEach","signature":"func (e *Etcd) ForEach(fn func(int))","file":"pkg/registry/core/service/allocator/storage/storage.go","code":"func (e *Etcd) ForEach(fn func(int)) {\n\te.lock.Lock()\n\tdefer e.lock.Unlock()\n\te.alloc.ForEach(fn)\n}","line":{"from":145,"to":149}} {"id":100009736,"name":"tryUpdate","signature":"func (e *Etcd) tryUpdate(fn func() error) error","file":"pkg/registry/core/service/allocator/storage/storage.go","code":"// tryUpdate performs a read-update to persist the latest snapshot state of allocation.\nfunc (e *Etcd) tryUpdate(fn func() error) error {\n\terr := e.storage.GuaranteedUpdate(context.TODO(), e.baseKey, \u0026api.RangeAllocation{}, true, nil,\n\t\tstorage.SimpleUpdate(func(input runtime.Object) (output runtime.Object, err error) {\n\t\t\texisting := input.(*api.RangeAllocation)\n\t\t\tif len(existing.ResourceVersion) == 0 {\n\t\t\t\treturn nil, fmt.Errorf(\"cannot allocate resources of type %s at this time\", e.resource.String())\n\t\t\t}\n\t\t\tif existing.ResourceVersion != e.last {\n\t\t\t\tif err := e.alloc.Restore(existing.Range, existing.Data); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err := fn(); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\te.last = existing.ResourceVersion\n\t\t\trangeSpec, data := e.alloc.Snapshot()\n\t\t\texisting.Range = rangeSpec\n\t\t\texisting.Data = data\n\t\t\treturn existing, nil\n\t\t}),\n\t\tnil,\n\t)\n\treturn storeerr.InterpretUpdateError(err, e.resource, \"\")\n}","line":{"from":151,"to":176}} {"id":100009737,"name":"Get","signature":"func (e *Etcd) Get() (*api.RangeAllocation, error)","file":"pkg/registry/core/service/allocator/storage/storage.go","code":"// Get returns an api.RangeAllocation that represents the current state in\n// etcd. If the key does not exist, the object will have an empty ResourceVersion.\nfunc (e *Etcd) Get() (*api.RangeAllocation, error) {\n\texisting := \u0026api.RangeAllocation{}\n\tif err := e.storage.Get(context.TODO(), e.baseKey, storage.GetOptions{IgnoreNotFound: true}, existing); err != nil {\n\t\treturn nil, storeerr.InterpretGetError(err, e.resource, \"\")\n\t}\n\treturn existing, nil\n}","line":{"from":178,"to":186}} {"id":100009738,"name":"CreateOrUpdate","signature":"func (e *Etcd) CreateOrUpdate(snapshot *api.RangeAllocation) error","file":"pkg/registry/core/service/allocator/storage/storage.go","code":"// CreateOrUpdate attempts to update the current etcd state with the provided\n// allocation.\nfunc (e *Etcd) CreateOrUpdate(snapshot *api.RangeAllocation) error {\n\te.lock.Lock()\n\tdefer e.lock.Unlock()\n\n\tlast := \"\"\n\terr := e.storage.GuaranteedUpdate(context.TODO(), e.baseKey, \u0026api.RangeAllocation{}, true, nil,\n\t\tstorage.SimpleUpdate(func(input runtime.Object) (output runtime.Object, err error) {\n\t\t\texisting := input.(*api.RangeAllocation)\n\t\t\tswitch {\n\t\t\tcase len(snapshot.ResourceVersion) != 0 \u0026\u0026 len(existing.ResourceVersion) != 0:\n\t\t\t\tif snapshot.ResourceVersion != existing.ResourceVersion {\n\t\t\t\t\treturn nil, apierrors.NewConflict(e.resource, \"\", fmt.Errorf(\"the provided resource version does not match\"))\n\t\t\t\t}\n\t\t\tcase len(existing.ResourceVersion) != 0:\n\t\t\t\treturn nil, apierrors.NewConflict(e.resource, \"\", fmt.Errorf(\"another caller has already initialized the resource\"))\n\t\t\t}\n\t\t\tlast = snapshot.ResourceVersion\n\t\t\treturn snapshot, nil\n\t\t}),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn storeerr.InterpretUpdateError(err, e.resource, \"\")\n\t}\n\terr = e.alloc.Restore(snapshot.Range, snapshot.Data)\n\tif err == nil {\n\t\te.last = last\n\t}\n\treturn err\n}","line":{"from":188,"to":219}} {"id":100009739,"name":"Has","signature":"func (e *Etcd) Has(item int) bool","file":"pkg/registry/core/service/allocator/storage/storage.go","code":"// Has implements allocator.Interface::Has\nfunc (e *Etcd) Has(item int) bool {\n\te.lock.Lock()\n\tdefer e.lock.Unlock()\n\n\treturn e.alloc.Has(item)\n}","line":{"from":221,"to":227}} {"id":100009740,"name":"Free","signature":"func (e *Etcd) Free() int","file":"pkg/registry/core/service/allocator/storage/storage.go","code":"// Free implements allocator.Interface::Free\nfunc (e *Etcd) Free() int {\n\te.lock.Lock()\n\tdefer e.lock.Unlock()\n\n\treturn e.alloc.Free()\n}","line":{"from":229,"to":235}} {"id":100009741,"name":"Destroy","signature":"func (e *Etcd) Destroy()","file":"pkg/registry/core/service/allocator/storage/storage.go","code":"// Destroy implement allocator.Interface::Destroy\nfunc (e *Etcd) Destroy() {\n\te.destroyFn()\n}","line":{"from":237,"to":240}} {"id":100009742,"name":"countBits","signature":"func countBits(n *big.Int) int","file":"pkg/registry/core/service/allocator/utils.go","code":"// countBits returns the number of set bits in n\nfunc countBits(n *big.Int) int {\n\tvar count int = 0\n\tfor _, w := range n.Bits() {\n\t\tcount += bits.OnesCount64(uint64(w))\n\t}\n\treturn count\n}","line":{"from":24,"to":31}} {"id":100009743,"name":"New","signature":"func New(cidr *net.IPNet, allocatorFactory allocator.AllocatorWithOffsetFactory) (*Range, error)","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"// New creates a Range over a net.IPNet, calling allocatorFactory to construct the backing store.\nfunc New(cidr *net.IPNet, allocatorFactory allocator.AllocatorWithOffsetFactory) (*Range, error) {\n\tmax := netutils.RangeSize(cidr)\n\tbase := netutils.BigForIP(cidr.IP)\n\trangeSpec := cidr.String()\n\tvar family api.IPFamily\n\n\tif netutils.IsIPv6CIDR(cidr) {\n\t\tfamily = api.IPv6Protocol\n\t\t// Limit the max size, since the allocator keeps a bitmap of that size.\n\t\tif max \u003e 65536 {\n\t\t\tmax = 65536\n\t\t}\n\t} else {\n\t\tfamily = api.IPv4Protocol\n\t\t// Don't use the IPv4 network's broadcast address, but don't just\n\t\t// Allocate() it - we don't ever want to be able to release it.\n\t\tmax--\n\t}\n\n\t// Don't use the network's \".0\" address, but don't just Allocate() it - we\n\t// don't ever want to be able to release it.\n\tbase.Add(base, big.NewInt(1))\n\tmax--\n\n\t// cidr with whole mask can be negative\n\tif max \u003c 0 {\n\t\tmax = 0\n\t}\n\n\tr := Range{\n\t\tnet: cidr,\n\t\tbase: base,\n\t\tmax: maximum(0, int(max)),\n\t\tfamily: family,\n\t\tmetrics: \u0026emptyMetricsRecorder{}, // disabled by default\n\t}\n\n\toffset := calculateRangeOffset(cidr)\n\n\tvar err error\n\tr.alloc, err = allocatorFactory(r.max, rangeSpec, offset)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026r, nil\n}","line":{"from":61,"to":107}} {"id":100009744,"name":"NewInMemory","signature":"func NewInMemory(cidr *net.IPNet) (*Range, error)","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"// NewInMemory creates an in-memory allocator.\nfunc NewInMemory(cidr *net.IPNet) (*Range, error) {\n\treturn New(cidr, func(max int, rangeSpec string, offset int) (allocator.Interface, error) {\n\t\treturn allocator.NewAllocationMapWithOffset(max, rangeSpec, offset), nil\n\t})\n}","line":{"from":109,"to":114}} {"id":100009745,"name":"NewFromSnapshot","signature":"func NewFromSnapshot(snap *api.RangeAllocation) (*Range, error)","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"// NewFromSnapshot allocates a Range and initializes it from a snapshot.\nfunc NewFromSnapshot(snap *api.RangeAllocation) (*Range, error) {\n\t_, ipnet, err := netutils.ParseCIDRSloppy(snap.Range)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr, err := NewInMemory(ipnet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := r.Restore(ipnet, snap.Data); err != nil {\n\t\treturn nil, err\n\t}\n\treturn r, nil\n}","line":{"from":116,"to":130}} {"id":100009746,"name":"maximum","signature":"func maximum(a, b int) int","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"func maximum(a, b int) int {\n\tif a \u003e b {\n\t\treturn a\n\t}\n\treturn b\n}","line":{"from":132,"to":137}} {"id":100009747,"name":"Free","signature":"func (r *Range) Free() int","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"// Free returns the count of IP addresses left in the range.\nfunc (r *Range) Free() int {\n\treturn r.alloc.Free()\n}","line":{"from":139,"to":142}} {"id":100009748,"name":"Used","signature":"func (r *Range) Used() int","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"// Used returns the count of IP addresses used in the range.\nfunc (r *Range) Used() int {\n\treturn r.max - r.alloc.Free()\n}","line":{"from":144,"to":147}} {"id":100009749,"name":"CIDR","signature":"func (r *Range) CIDR() net.IPNet","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"// CIDR returns the CIDR covered by the range.\nfunc (r *Range) CIDR() net.IPNet {\n\treturn *r.net\n}","line":{"from":149,"to":152}} {"id":100009750,"name":"DryRun","signature":"func (r *Range) DryRun() Interface","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"// DryRun returns a non-persisting form of this Range.\nfunc (r *Range) DryRun() Interface {\n\treturn dryRunRange{r}\n}","line":{"from":154,"to":157}} {"id":100009751,"name":"Allocate","signature":"func (r *Range) Allocate(ip net.IP) error","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"// Allocate attempts to reserve the provided IP. ErrNotInRange or\n// ErrAllocated will be returned if the IP is not valid for this range\n// or has already been reserved. ErrFull will be returned if there\n// are no addresses left.\nfunc (r *Range) Allocate(ip net.IP) error {\n\treturn r.allocate(ip, dryRunFalse)\n}","line":{"from":163,"to":169}} {"id":100009752,"name":"allocate","signature":"func (r *Range) allocate(ip net.IP, dryRun bool) error","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"func (r *Range) allocate(ip net.IP, dryRun bool) error {\n\tlabel := r.CIDR()\n\tok, offset := r.contains(ip)\n\tif !ok {\n\t\tif !dryRun {\n\t\t\t// update metrics\n\t\t\tr.metrics.incrementAllocationErrors(label.String(), \"static\")\n\t\t}\n\t\treturn \u0026ErrNotInRange{ip, r.net.String()}\n\t}\n\tif dryRun {\n\t\t// Don't bother to check whether the IP is actually free. It's racy and\n\t\t// not worth the effort to plumb any further.\n\t\treturn nil\n\t}\n\n\tallocated, err := r.alloc.Allocate(offset)\n\tif err != nil {\n\t\t// update metrics\n\t\tr.metrics.incrementAllocationErrors(label.String(), \"static\")\n\n\t\treturn err\n\t}\n\tif !allocated {\n\t\t// update metrics\n\t\tr.metrics.incrementAllocationErrors(label.String(), \"static\")\n\n\t\treturn ErrAllocated\n\t}\n\t// update metrics\n\tr.metrics.incrementAllocations(label.String(), \"static\")\n\tr.metrics.setAllocated(label.String(), r.Used())\n\tr.metrics.setAvailable(label.String(), r.Free())\n\n\treturn nil\n}","line":{"from":171,"to":206}} {"id":100009753,"name":"AllocateNext","signature":"func (r *Range) AllocateNext() (net.IP, error)","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"// AllocateNext reserves one of the IPs from the pool. ErrFull may\n// be returned if there are no addresses left.\nfunc (r *Range) AllocateNext() (net.IP, error) {\n\treturn r.allocateNext(dryRunFalse)\n}","line":{"from":208,"to":212}} {"id":100009754,"name":"allocateNext","signature":"func (r *Range) allocateNext(dryRun bool) (net.IP, error)","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"func (r *Range) allocateNext(dryRun bool) (net.IP, error) {\n\tlabel := r.CIDR()\n\tif dryRun {\n\t\t// Don't bother finding a free value. It's racy and not worth the\n\t\t// effort to plumb any further.\n\t\treturn r.CIDR().IP, nil\n\t}\n\n\toffset, ok, err := r.alloc.AllocateNext()\n\tif err != nil {\n\t\t// update metrics\n\t\tr.metrics.incrementAllocationErrors(label.String(), \"dynamic\")\n\n\t\treturn nil, err\n\t}\n\tif !ok {\n\t\t// update metrics\n\t\tr.metrics.incrementAllocationErrors(label.String(), \"dynamic\")\n\n\t\treturn nil, ErrFull\n\t}\n\t// update metrics\n\tr.metrics.incrementAllocations(label.String(), \"dynamic\")\n\tr.metrics.setAllocated(label.String(), r.Used())\n\tr.metrics.setAvailable(label.String(), r.Free())\n\n\treturn netutils.AddIPOffset(r.base, offset), nil\n}","line":{"from":214,"to":241}} {"id":100009755,"name":"Release","signature":"func (r *Range) Release(ip net.IP) error","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"// Release releases the IP back to the pool. Releasing an\n// unallocated IP or an IP out of the range is a no-op and\n// returns no error.\nfunc (r *Range) Release(ip net.IP) error {\n\treturn r.release(ip, dryRunFalse)\n}","line":{"from":243,"to":248}} {"id":100009756,"name":"release","signature":"func (r *Range) release(ip net.IP, dryRun bool) error","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"func (r *Range) release(ip net.IP, dryRun bool) error {\n\tok, offset := r.contains(ip)\n\tif !ok {\n\t\treturn nil\n\t}\n\tif dryRun {\n\t\treturn nil\n\t}\n\n\terr := r.alloc.Release(offset)\n\tif err == nil {\n\t\t// update metrics\n\t\tlabel := r.CIDR()\n\t\tr.metrics.setAllocated(label.String(), r.Used())\n\t\tr.metrics.setAvailable(label.String(), r.Free())\n\t}\n\treturn err\n}","line":{"from":250,"to":267}} {"id":100009757,"name":"ForEach","signature":"func (r *Range) ForEach(fn func(net.IP))","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"// ForEach calls the provided function for each allocated IP.\nfunc (r *Range) ForEach(fn func(net.IP)) {\n\tr.alloc.ForEach(func(offset int) {\n\t\tip, _ := netutils.GetIndexedIP(r.net, offset+1) // +1 because Range doesn't store IP 0\n\t\tfn(ip)\n\t})\n}","line":{"from":269,"to":275}} {"id":100009758,"name":"Has","signature":"func (r *Range) Has(ip net.IP) bool","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"// Has returns true if the provided IP is already allocated and a call\n// to Allocate(ip) would fail with ErrAllocated.\nfunc (r *Range) Has(ip net.IP) bool {\n\tok, offset := r.contains(ip)\n\tif !ok {\n\t\treturn false\n\t}\n\n\treturn r.alloc.Has(offset)\n}","line":{"from":277,"to":286}} {"id":100009759,"name":"IPFamily","signature":"func (r *Range) IPFamily() api.IPFamily","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"// IPFamily returns the IP family of this range.\nfunc (r *Range) IPFamily() api.IPFamily {\n\treturn r.family\n}","line":{"from":288,"to":291}} {"id":100009760,"name":"Snapshot","signature":"func (r *Range) Snapshot(dst *api.RangeAllocation) error","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"// Snapshot saves the current state of the pool.\nfunc (r *Range) Snapshot(dst *api.RangeAllocation) error {\n\tsnapshottable, ok := r.alloc.(allocator.Snapshottable)\n\tif !ok {\n\t\treturn fmt.Errorf(\"not a snapshottable allocator\")\n\t}\n\trangeString, data := snapshottable.Snapshot()\n\tdst.Range = rangeString\n\tdst.Data = data\n\treturn nil\n}","line":{"from":293,"to":303}} {"id":100009761,"name":"Restore","signature":"func (r *Range) Restore(net *net.IPNet, data []byte) error","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"// Restore restores the pool to the previously captured state. ErrMismatchedNetwork\n// is returned if the provided IPNet range doesn't exactly match the previous range.\nfunc (r *Range) Restore(net *net.IPNet, data []byte) error {\n\tif !net.IP.Equal(r.net.IP) || net.Mask.String() != r.net.Mask.String() {\n\t\treturn ErrMismatchedNetwork\n\t}\n\tsnapshottable, ok := r.alloc.(allocator.Snapshottable)\n\tif !ok {\n\t\treturn fmt.Errorf(\"not a snapshottable allocator\")\n\t}\n\tif err := snapshottable.Restore(net.String(), data); err != nil {\n\t\treturn fmt.Errorf(\"restoring snapshot encountered %v\", err)\n\t}\n\treturn nil\n}","line":{"from":305,"to":319}} {"id":100009762,"name":"contains","signature":"func (r *Range) contains(ip net.IP) (bool, int)","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"// contains returns true and the offset if the ip is in the range, and false\n// and nil otherwise. The first and last addresses of the CIDR are omitted.\nfunc (r *Range) contains(ip net.IP) (bool, int) {\n\tif !r.net.Contains(ip) {\n\t\treturn false, 0\n\t}\n\n\toffset := calculateIPOffset(r.base, ip)\n\tif offset \u003c 0 || offset \u003e= r.max {\n\t\treturn false, 0\n\t}\n\treturn true, offset\n}","line":{"from":321,"to":333}} {"id":100009763,"name":"Destroy","signature":"func (r *Range) Destroy()","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"// Destroy shuts down internal allocator.\nfunc (r *Range) Destroy() {\n\tr.alloc.Destroy()\n}","line":{"from":335,"to":338}} {"id":100009764,"name":"EnableMetrics","signature":"func (r *Range) EnableMetrics()","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"// EnableMetrics enables metrics recording.\nfunc (r *Range) EnableMetrics() {\n\tregisterMetrics()\n\tr.metrics = \u0026metricsRecorder{}\n}","line":{"from":340,"to":344}} {"id":100009765,"name":"calculateIPOffset","signature":"func calculateIPOffset(base *big.Int, ip net.IP) int","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"// calculateIPOffset calculates the integer offset of ip from base such that\n// base + offset = ip. It requires ip \u003e= base.\nfunc calculateIPOffset(base *big.Int, ip net.IP) int {\n\treturn int(big.NewInt(0).Sub(netutils.BigForIP(ip), base).Int64())\n}","line":{"from":346,"to":350}} {"id":100009766,"name":"calculateRangeOffset","signature":"func calculateRangeOffset(cidr *net.IPNet) int","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"// calculateRangeOffset estimates the offset used on the range for statically allocation based on\n// the following formula `min(max($min, cidrSize/$step), $max)`, described as ~never less than\n// $min or more than $max, with a graduated step function between them~. The function returns 0\n// if any of the parameters is invalid.\nfunc calculateRangeOffset(cidr *net.IPNet) int {\n\t// default values for min(max($min, cidrSize/$step), $max)\n\tconst (\n\t\tmin = 16\n\t\tmax = 256\n\t\tstep = 16\n\t)\n\n\tcidrSize := netutils.RangeSize(cidr)\n\t// available addresses are always less than the cidr size\n\t// A /28 CIDR returns 16 addresses, but 2 of them, the network\n\t// and broadcast addresses are not available.\n\tif cidrSize \u003c= min {\n\t\treturn 0\n\t}\n\n\toffset := cidrSize / step\n\tif offset \u003c min {\n\t\treturn min\n\t}\n\tif offset \u003e max {\n\t\treturn max\n\t}\n\treturn int(offset)\n}","line":{"from":352,"to":380}} {"id":100009767,"name":"Allocate","signature":"func (dry dryRunRange) Allocate(ip net.IP) error","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"func (dry dryRunRange) Allocate(ip net.IP) error {\n\treturn dry.real.allocate(ip, dryRunTrue)\n}","line":{"from":387,"to":389}} {"id":100009768,"name":"AllocateNext","signature":"func (dry dryRunRange) AllocateNext() (net.IP, error)","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"func (dry dryRunRange) AllocateNext() (net.IP, error) {\n\treturn dry.real.allocateNext(dryRunTrue)\n}","line":{"from":391,"to":393}} {"id":100009769,"name":"Release","signature":"func (dry dryRunRange) Release(ip net.IP) error","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"func (dry dryRunRange) Release(ip net.IP) error {\n\treturn dry.real.release(ip, dryRunTrue)\n}","line":{"from":395,"to":397}} {"id":100009770,"name":"ForEach","signature":"func (dry dryRunRange) ForEach(cb func(net.IP))","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"func (dry dryRunRange) ForEach(cb func(net.IP)) {\n\tdry.real.ForEach(cb)\n}","line":{"from":399,"to":401}} {"id":100009771,"name":"CIDR","signature":"func (dry dryRunRange) CIDR() net.IPNet","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"func (dry dryRunRange) CIDR() net.IPNet {\n\treturn dry.real.CIDR()\n}","line":{"from":403,"to":405}} {"id":100009772,"name":"IPFamily","signature":"func (dry dryRunRange) IPFamily() api.IPFamily","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"func (dry dryRunRange) IPFamily() api.IPFamily {\n\treturn dry.real.IPFamily()\n}","line":{"from":407,"to":409}} {"id":100009773,"name":"DryRun","signature":"func (dry dryRunRange) DryRun() Interface","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"func (dry dryRunRange) DryRun() Interface {\n\treturn dry\n}","line":{"from":411,"to":413}} {"id":100009774,"name":"Has","signature":"func (dry dryRunRange) Has(ip net.IP) bool","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"func (dry dryRunRange) Has(ip net.IP) bool {\n\treturn dry.real.Has(ip)\n}","line":{"from":415,"to":417}} {"id":100009775,"name":"Destroy","signature":"func (dry dryRunRange) Destroy()","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"func (dry dryRunRange) Destroy() {\n}","line":{"from":419,"to":420}} {"id":100009776,"name":"EnableMetrics","signature":"func (dry dryRunRange) EnableMetrics()","file":"pkg/registry/core/service/ipallocator/bitmap.go","code":"func (dry dryRunRange) EnableMetrics() {\n}","line":{"from":422,"to":423}} {"id":100009777,"name":"NewRepair","signature":"func NewRepair(interval time.Duration, serviceClient corev1client.ServicesGetter, eventClient eventsv1client.EventsV1Interface, network *net.IPNet, alloc rangeallocation.RangeRegistry, secondaryNetwork *net.IPNet, secondaryAlloc rangeallocation.RangeRegistry) *Repair","file":"pkg/registry/core/service/ipallocator/controller/repair.go","code":"// NewRepair creates a controller that periodically ensures that all clusterIPs are uniquely allocated across the cluster\n// and generates informational warnings for a cluster that is not in sync.\nfunc NewRepair(interval time.Duration, serviceClient corev1client.ServicesGetter, eventClient eventsv1client.EventsV1Interface, network *net.IPNet, alloc rangeallocation.RangeRegistry, secondaryNetwork *net.IPNet, secondaryAlloc rangeallocation.RangeRegistry) *Repair {\n\teventBroadcaster := events.NewBroadcaster(\u0026events.EventSinkImpl{Interface: eventClient})\n\trecorder := eventBroadcaster.NewRecorder(legacyscheme.Scheme, \"ipallocator-repair-controller\")\n\n\t// build *ByFamily struct members\n\tnetworkByFamily := make(map[v1.IPFamily]*net.IPNet)\n\tallocatorByFamily := make(map[v1.IPFamily]rangeallocation.RangeRegistry)\n\tleaksByFamily := make(map[v1.IPFamily]map[string]int)\n\n\tprimary := v1.IPv4Protocol\n\tsecondary := v1.IPv6Protocol\n\tif netutils.IsIPv6(network.IP) {\n\t\tprimary = v1.IPv6Protocol\n\t}\n\n\tnetworkByFamily[primary] = network\n\tallocatorByFamily[primary] = alloc\n\tleaksByFamily[primary] = make(map[string]int)\n\n\tif secondaryNetwork != nil \u0026\u0026 secondaryNetwork.IP != nil {\n\t\tif primary == v1.IPv6Protocol {\n\t\t\tsecondary = v1.IPv4Protocol\n\t\t}\n\t\tnetworkByFamily[secondary] = secondaryNetwork\n\t\tallocatorByFamily[secondary] = secondaryAlloc\n\t\tleaksByFamily[secondary] = make(map[string]int)\n\t}\n\n\treturn \u0026Repair{\n\t\tinterval: interval,\n\t\tserviceClient: serviceClient,\n\n\t\tnetworkByFamily: networkByFamily,\n\t\tallocatorByFamily: allocatorByFamily,\n\n\t\tleaksByFamily: leaksByFamily,\n\t\tbroadcaster: eventBroadcaster,\n\t\trecorder: recorder,\n\t}\n}","line":{"from":74,"to":115}} {"id":100009778,"name":"RunUntil","signature":"func (c *Repair) RunUntil(onFirstSuccess func(), stopCh chan struct{})","file":"pkg/registry/core/service/ipallocator/controller/repair.go","code":"// RunUntil starts the controller until the provided ch is closed.\nfunc (c *Repair) RunUntil(onFirstSuccess func(), stopCh chan struct{}) {\n\tc.broadcaster.StartRecordingToSink(stopCh)\n\tdefer c.broadcaster.Shutdown()\n\n\tvar once sync.Once\n\twait.Until(func() {\n\t\tif err := c.runOnce(); err != nil {\n\t\t\truntime.HandleError(err)\n\t\t\treturn\n\t\t}\n\t\tonce.Do(onFirstSuccess)\n\t}, c.interval, stopCh)\n}","line":{"from":117,"to":130}} {"id":100009779,"name":"runOnce","signature":"func (c *Repair) runOnce() error","file":"pkg/registry/core/service/ipallocator/controller/repair.go","code":"// runOnce verifies the state of the cluster IP allocations and returns an error if an unrecoverable problem occurs.\nfunc (c *Repair) runOnce() error {\n\treturn retry.RetryOnConflict(retry.DefaultBackoff, c.doRunOnce)\n}","line":{"from":132,"to":135}} {"id":100009780,"name":"doRunOnce","signature":"func (c *Repair) doRunOnce() error","file":"pkg/registry/core/service/ipallocator/controller/repair.go","code":"// doRunOnce verifies the state of the cluster IP allocations and returns an error if an unrecoverable problem occurs.\nfunc (c *Repair) doRunOnce() error {\n\t// TODO: (per smarterclayton) if Get() or ListServices() is a weak consistency read,\n\t// or if they are executed against different leaders,\n\t// the ordering guarantee required to ensure no IP is allocated twice is violated.\n\t// ListServices must return a ResourceVersion higher than the etcd index Get triggers,\n\t// and the release code must not release services that have had IPs allocated but not yet been created\n\t// See #8295\n\n\t// If etcd server is not running we should wait for some time and fail only then. This is particularly\n\t// important when we start apiserver and etcd at the same time.\n\tsnapshotByFamily := make(map[v1.IPFamily]*api.RangeAllocation)\n\tstoredByFamily := make(map[v1.IPFamily]ipallocator.Interface)\n\n\terr := wait.PollImmediate(time.Second, 10*time.Second, func() (bool, error) {\n\t\tfor family, allocator := range c.allocatorByFamily {\n\t\t\t// get snapshot if it is not there\n\t\t\tif _, ok := snapshotByFamily[family]; !ok {\n\t\t\t\tsnapshot, err := allocator.Get()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\n\t\t\t\tsnapshotByFamily[family] = snapshot\n\t\t\t}\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to refresh the service IP block: %v\", err)\n\t}\n\n\t// ensure that ranges are assigned\n\tfor family, snapshot := range snapshotByFamily {\n\t\tif snapshot.Range == \"\" {\n\t\t\tsnapshot.Range = c.networkByFamily[family].String()\n\t\t}\n\t}\n\n\t// Create an allocator because it is easy to use.\n\tfor family, snapshot := range snapshotByFamily {\n\t\tstored, err := ipallocator.NewFromSnapshot(snapshot)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to rebuild allocator from snapshots for family:%v with error:%v\", family, err)\n\t\t}\n\n\t\tstoredByFamily[family] = stored\n\t}\n\n\trebuiltByFamily := make(map[v1.IPFamily]*ipallocator.Range)\n\n\tfor family, network := range c.networkByFamily {\n\t\trebuilt, err := ipallocator.NewInMemory(network)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to create CIDR range for family %v: %v\", family, err)\n\t\t}\n\n\t\trebuiltByFamily[family] = rebuilt\n\t}\n\t// We explicitly send no resource version, since the resource version\n\t// of 'snapshot' is from a different collection, it's not comparable to\n\t// the service collection. The caching layer keeps per-collection RVs,\n\t// and this is proper, since in theory the collections could be hosted\n\t// in separate etcd (or even non-etcd) instances.\n\tlist, err := c.serviceClient.Services(metav1.NamespaceAll).List(context.TODO(), metav1.ListOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to refresh the service IP block: %v\", err)\n\t}\n\n\tgetFamilyByIP := func(ip net.IP) v1.IPFamily {\n\t\tif netutils.IsIPv6(ip) {\n\t\t\treturn v1.IPv6Protocol\n\t\t}\n\t\treturn v1.IPv4Protocol\n\t}\n\n\t// Check every Service's ClusterIP, and rebuild the state as we think it should be.\n\tfor _, svc := range list.Items {\n\t\tif !helper.IsServiceIPSet(\u0026svc) {\n\t\t\t// didn't need a cluster IP\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, ip := range svc.Spec.ClusterIPs {\n\t\t\tip := netutils.ParseIPSloppy(ip)\n\t\t\tif ip == nil {\n\t\t\t\t// cluster IP is corrupt\n\t\t\t\tc.recorder.Eventf(\u0026svc, nil, v1.EventTypeWarning, \"ClusterIPNotValid\", \"ClusterIPValidation\", \"Cluster IP %s is not a valid IP; please recreate service\", ip)\n\t\t\t\truntime.HandleError(fmt.Errorf(\"the cluster IP %s for service %s/%s is not a valid IP; please recreate\", ip, svc.Name, svc.Namespace))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfamily := getFamilyByIP(ip)\n\t\t\tif _, ok := rebuiltByFamily[family]; !ok {\n\t\t\t\t// this service is using an IPFamily no longer configured on cluster\n\t\t\t\tc.recorder.Eventf(\u0026svc, nil, v1.EventTypeWarning, \"ClusterIPNotValid\", \"ClusterIPValidation\", \"Cluster IP %s(%s) is of ip family that is no longer configured on cluster; please recreate service\", ip, family)\n\t\t\t\truntime.HandleError(fmt.Errorf(\"the cluster IP %s(%s) for service %s/%s is of ip family that is no longer configured on cluster; please recreate\", ip, family, svc.Name, svc.Namespace))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// mark it as in-use\n\t\t\tactualAlloc := rebuiltByFamily[family]\n\t\t\tswitch err := actualAlloc.Allocate(ip); err {\n\t\t\tcase nil:\n\t\t\t\tactualStored := storedByFamily[family]\n\t\t\t\tif actualStored.Has(ip) {\n\t\t\t\t\t// remove it from the old set, so we can find leaks\n\t\t\t\t\tactualStored.Release(ip)\n\t\t\t\t} else {\n\t\t\t\t\t// cluster IP doesn't seem to be allocated\n\t\t\t\t\tc.recorder.Eventf(\u0026svc, nil, v1.EventTypeWarning, \"ClusterIPNotAllocated\", \"ClusterIPAllocation\", \"Cluster IP [%v]:%s is not allocated; repairing\", family, ip)\n\t\t\t\t\truntime.HandleError(fmt.Errorf(\"the cluster IP [%v]:%s for service %s/%s is not allocated; repairing\", family, ip, svc.Name, svc.Namespace))\n\t\t\t\t}\n\t\t\t\tdelete(c.leaksByFamily[family], ip.String()) // it is used, so it can't be leaked\n\t\t\tcase ipallocator.ErrAllocated:\n\t\t\t\t// cluster IP is duplicate\n\t\t\t\tc.recorder.Eventf(\u0026svc, nil, v1.EventTypeWarning, \"ClusterIPAlreadyAllocated\", \"ClusterIPAllocation\", \"Cluster IP [%v]:%s was assigned to multiple services; please recreate service\", family, ip)\n\t\t\t\truntime.HandleError(fmt.Errorf(\"the cluster IP [%v]:%s for service %s/%s was assigned to multiple services; please recreate\", family, ip, svc.Name, svc.Namespace))\n\t\t\tcase err.(*ipallocator.ErrNotInRange):\n\t\t\t\t// cluster IP is out of range\n\t\t\t\tc.recorder.Eventf(\u0026svc, nil, v1.EventTypeWarning, \"ClusterIPOutOfRange\", \"ClusterIPAllocation\", \"Cluster IP [%v]:%s is not within the service CIDR %s; please recreate service\", family, ip, c.networkByFamily[family])\n\t\t\t\truntime.HandleError(fmt.Errorf(\"the cluster IP [%v]:%s for service %s/%s is not within the service CIDR %s; please recreate\", family, ip, svc.Name, svc.Namespace, c.networkByFamily[family]))\n\t\t\tcase ipallocator.ErrFull:\n\t\t\t\t// somehow we are out of IPs\n\t\t\t\tcidr := actualAlloc.CIDR()\n\t\t\t\tc.recorder.Eventf(\u0026svc, nil, v1.EventTypeWarning, \"ServiceCIDRFull\", \"ClusterIPAllocation\", \"Service CIDR %v is full; you must widen the CIDR in order to create new services for Cluster IP [%v]:%s\", cidr, family, ip)\n\t\t\t\treturn fmt.Errorf(\"the service CIDR %v is full; you must widen the CIDR in order to create new services for Cluster IP [%v]:%s\", cidr, family, ip)\n\t\t\tdefault:\n\t\t\t\tc.recorder.Eventf(\u0026svc, nil, v1.EventTypeWarning, \"UnknownError\", \"ClusterIPAllocation\", \"Unable to allocate cluster IP [%v]:%s due to an unknown error\", family, ip)\n\t\t\t\treturn fmt.Errorf(\"unable to allocate cluster IP [%v]:%s for service %s/%s due to an unknown error, exiting: %v\", family, ip, svc.Name, svc.Namespace, err)\n\t\t\t}\n\t\t}\n\t}\n\n\t// leak check\n\tfor family, leaks := range c.leaksByFamily {\n\t\tc.checkLeaked(leaks, storedByFamily[family], rebuiltByFamily[family])\n\t}\n\n\t// save logic\n\t// Blast the rebuilt state into storage.\n\tfor family, rebuilt := range rebuiltByFamily {\n\t\terr = c.saveSnapShot(rebuilt, c.allocatorByFamily[family], snapshotByFamily[family])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":137,"to":287}} {"id":100009781,"name":"saveSnapShot","signature":"func (c *Repair) saveSnapShot(rebuilt *ipallocator.Range, alloc rangeallocation.RangeRegistry, snapshot *api.RangeAllocation) error","file":"pkg/registry/core/service/ipallocator/controller/repair.go","code":"func (c *Repair) saveSnapShot(rebuilt *ipallocator.Range, alloc rangeallocation.RangeRegistry, snapshot *api.RangeAllocation) error {\n\tif err := rebuilt.Snapshot(snapshot); err != nil {\n\t\treturn fmt.Errorf(\"unable to snapshot the updated service IP allocations: %v\", err)\n\t}\n\tif err := alloc.CreateOrUpdate(snapshot); err != nil {\n\t\tif errors.IsConflict(err) {\n\t\t\treturn err\n\t\t}\n\t\treturn fmt.Errorf(\"unable to persist the updated service IP allocations: %v\", err)\n\t}\n\n\treturn nil\n}","line":{"from":289,"to":301}} {"id":100009782,"name":"checkLeaked","signature":"func (c *Repair) checkLeaked(leaks map[string]int, stored ipallocator.Interface, rebuilt *ipallocator.Range)","file":"pkg/registry/core/service/ipallocator/controller/repair.go","code":"func (c *Repair) checkLeaked(leaks map[string]int, stored ipallocator.Interface, rebuilt *ipallocator.Range) {\n\t// Check for IPs that are left in the old set. They appear to have been leaked.\n\tstored.ForEach(func(ip net.IP) {\n\t\tcount, found := leaks[ip.String()]\n\t\tswitch {\n\t\tcase !found:\n\t\t\t// flag it to be cleaned up after any races (hopefully) are gone\n\t\t\truntime.HandleError(fmt.Errorf(\"the cluster IP %s may have leaked: flagging for later clean up\", ip))\n\t\t\tcount = numRepairsBeforeLeakCleanup - 1\n\t\t\tfallthrough\n\t\tcase count \u003e 0:\n\t\t\t// pretend it is still in use until count expires\n\t\t\tleaks[ip.String()] = count - 1\n\t\t\tif err := rebuilt.Allocate(ip); err != nil {\n\t\t\t\truntime.HandleError(fmt.Errorf(\"the cluster IP %s may have leaked, but can not be allocated: %v\", ip, err))\n\t\t\t}\n\t\tdefault:\n\t\t\t// do not add it to the rebuilt set, which means it will be available for reuse\n\t\t\truntime.HandleError(fmt.Errorf(\"the cluster IP %s appears to have leaked: cleaning up\", ip))\n\t\t}\n\t})\n}","line":{"from":303,"to":324}} {"id":100009783,"name":"NewRepairIPAddress","signature":"func NewRepairIPAddress(interval time.Duration,","file":"pkg/registry/core/service/ipallocator/controller/repairip.go","code":"// NewRepair creates a controller that periodically ensures that all clusterIPs are uniquely allocated across the cluster\n// and generates informational warnings for a cluster that is not in sync.\nfunc NewRepairIPAddress(interval time.Duration,\n\tclient kubernetes.Interface,\n\tnetwork *net.IPNet,\n\tsecondaryNetwork *net.IPNet,\n\tserviceInformer coreinformers.ServiceInformer,\n\tipAddressInformer networkinginformers.IPAddressInformer) *RepairIPAddress {\n\teventBroadcaster := events.NewBroadcaster(\u0026events.EventSinkImpl{Interface: client.EventsV1()})\n\trecorder := eventBroadcaster.NewRecorder(legacyscheme.Scheme, \"ipallocator-repair-controller\")\n\n\tnetworkByFamily := make(map[netutils.IPFamily]*net.IPNet)\n\tprimary := netutils.IPFamilyOfCIDR(network)\n\tnetworkByFamily[primary] = network\n\tif secondaryNetwork != nil {\n\t\tsecondary := netutils.IPFamilyOfCIDR(secondaryNetwork)\n\t\tnetworkByFamily[secondary] = secondaryNetwork\n\t}\n\n\tr := \u0026RepairIPAddress{\n\t\tinterval: interval,\n\t\tclient: client,\n\t\tnetworkByFamily: networkByFamily,\n\t\tserviceLister: serviceInformer.Lister(),\n\t\tservicesSynced: serviceInformer.Informer().HasSynced,\n\t\tipAddressLister: ipAddressInformer.Lister(),\n\t\tipAddressSynced: ipAddressInformer.Informer().HasSynced,\n\t\tsvcQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"services\"),\n\t\tipQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"ipaddresses\"),\n\t\tworkerLoopPeriod: time.Second,\n\t\tbroadcaster: eventBroadcaster,\n\t\trecorder: recorder,\n\t\tclock: clock.RealClock{},\n\t}\n\n\tserviceInformer.Informer().AddEventHandlerWithResyncPeriod(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tkey, err := cache.MetaNamespaceKeyFunc(obj)\n\t\t\tif err == nil {\n\t\t\t\tr.svcQueue.Add(key)\n\t\t\t}\n\t\t},\n\t\tUpdateFunc: func(old interface{}, new interface{}) {\n\t\t\tkey, err := cache.MetaNamespaceKeyFunc(new)\n\t\t\tif err == nil {\n\t\t\t\tr.svcQueue.Add(key)\n\t\t\t}\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\t// IndexerInformer uses a delta queue, therefore for deletes we have to use this\n\t\t\t// key function.\n\t\t\tkey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)\n\t\t\tif err == nil {\n\t\t\t\tr.svcQueue.Add(key)\n\t\t\t}\n\t\t},\n\t}, interval)\n\n\tipAddressInformer.Informer().AddEventHandlerWithResyncPeriod(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tkey, err := cache.MetaNamespaceKeyFunc(obj)\n\t\t\tif err == nil {\n\t\t\t\tr.ipQueue.Add(key)\n\t\t\t}\n\t\t},\n\t\tUpdateFunc: func(old interface{}, new interface{}) {\n\t\t\tkey, err := cache.MetaNamespaceKeyFunc(new)\n\t\t\tif err == nil {\n\t\t\t\tr.ipQueue.Add(key)\n\t\t\t}\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\t// IndexerInformer uses a delta queue, therefore for deletes we have to use this\n\t\t\t// key function.\n\t\t\tkey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)\n\t\t\tif err == nil {\n\t\t\t\tr.ipQueue.Add(key)\n\t\t\t}\n\t\t},\n\t}, interval)\n\n\treturn r\n}","line":{"from":108,"to":190}} {"id":100009784,"name":"RunUntil","signature":"func (r *RepairIPAddress) RunUntil(onFirstSuccess func(), stopCh chan struct{})","file":"pkg/registry/core/service/ipallocator/controller/repairip.go","code":"// RunUntil starts the controller until the provided ch is closed.\nfunc (r *RepairIPAddress) RunUntil(onFirstSuccess func(), stopCh chan struct{}) {\n\tdefer r.ipQueue.ShutDown()\n\tdefer r.svcQueue.ShutDown()\n\tr.broadcaster.StartRecordingToSink(stopCh)\n\tdefer r.broadcaster.Shutdown()\n\n\tklog.Info(\"Starting ipallocator-repair-controller\")\n\tdefer klog.Info(\"Shutting down ipallocator-repair-controller\")\n\n\tif !cache.WaitForNamedCacheSync(\"ipallocator-repair-controller\", stopCh, r.ipAddressSynced, r.servicesSynced) {\n\t\treturn\n\t}\n\n\t// First sync goes through all the Services and IPAddresses in the cache,\n\t// once synced, it signals the main loop and works using the handlers, since\n\t// it's less expensive and more optimal.\n\tif err := r.runOnce(); err != nil {\n\t\truntime.HandleError(err)\n\t\treturn\n\t}\n\tonFirstSuccess()\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.Until(r.ipWorker, r.workerLoopPeriod, stopCh)\n\t\tgo wait.Until(r.svcWorker, r.workerLoopPeriod, stopCh)\n\t}\n\n\t\u003c-stopCh\n}","line":{"from":192,"to":221}} {"id":100009785,"name":"runOnce","signature":"func (r *RepairIPAddress) runOnce() error","file":"pkg/registry/core/service/ipallocator/controller/repairip.go","code":"// runOnce verifies the state of the ClusterIP allocations and returns an error if an unrecoverable problem occurs.\nfunc (r *RepairIPAddress) runOnce() error {\n\treturn retry.RetryOnConflict(retry.DefaultBackoff, r.doRunOnce)\n}","line":{"from":223,"to":226}} {"id":100009786,"name":"doRunOnce","signature":"func (r *RepairIPAddress) doRunOnce() error","file":"pkg/registry/core/service/ipallocator/controller/repairip.go","code":"// doRunOnce verifies the state of the ClusterIP allocations and returns an error if an unrecoverable problem occurs.\nfunc (r *RepairIPAddress) doRunOnce() error {\n\tservices, err := r.serviceLister.List(labels.Everything())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to refresh the service IP block: %v\", err)\n\t}\n\n\t// Check every Service's ClusterIP, and rebuild the state as we think it should be.\n\tfor _, svc := range services {\n\t\tkey, err := cache.MetaNamespaceKeyFunc(svc)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = r.syncService(key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// We have checked that every Service has its corresponding IP.\n\t// Check that there is no IP created by the allocator without\n\t// a Service associated.\n\tipLabelSelector := labels.Set(map[string]string{\n\t\tnetworkingv1alpha1.LabelManagedBy: ipallocator.ControllerName,\n\t}).AsSelectorPreValidated()\n\tipAddresses, err := r.ipAddressLister.List(ipLabelSelector)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to refresh the IPAddress block: %v\", err)\n\t}\n\t// Check every IPAddress matches the corresponding Service, and rebuild the state as we think it should be.\n\tfor _, ipAddress := range ipAddresses {\n\t\tkey, err := cache.MetaNamespaceKeyFunc(ipAddress)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = r.syncIPAddress(key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":228,"to":270}} {"id":100009787,"name":"svcWorker","signature":"func (r *RepairIPAddress) svcWorker()","file":"pkg/registry/core/service/ipallocator/controller/repairip.go","code":"func (r *RepairIPAddress) svcWorker() {\n\tfor r.processNextWorkSvc() {\n\t}\n}","line":{"from":272,"to":275}} {"id":100009788,"name":"processNextWorkSvc","signature":"func (r *RepairIPAddress) processNextWorkSvc() bool","file":"pkg/registry/core/service/ipallocator/controller/repairip.go","code":"func (r *RepairIPAddress) processNextWorkSvc() bool {\n\teKey, quit := r.svcQueue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer r.svcQueue.Done(eKey)\n\n\terr := r.syncService(eKey.(string))\n\tr.handleSvcErr(err, eKey)\n\n\treturn true\n}","line":{"from":277,"to":288}} {"id":100009789,"name":"handleSvcErr","signature":"func (r *RepairIPAddress) handleSvcErr(err error, key interface{})","file":"pkg/registry/core/service/ipallocator/controller/repairip.go","code":"func (r *RepairIPAddress) handleSvcErr(err error, key interface{}) {\n\tif err == nil {\n\t\tr.svcQueue.Forget(key)\n\t\treturn\n\t}\n\n\tif r.svcQueue.NumRequeues(key) \u003c maxRetries {\n\t\tklog.V(2).InfoS(\"Error syncing Service, retrying\", \"service\", key, \"err\", err)\n\t\tr.svcQueue.AddRateLimited(key)\n\t\treturn\n\t}\n\n\tklog.Warningf(\"Dropping Service %q out of the queue: %v\", key, err)\n\tr.svcQueue.Forget(key)\n\truntime.HandleError(err)\n}","line":{"from":290,"to":305}} {"id":100009790,"name":"syncService","signature":"func (r *RepairIPAddress) syncService(key string) error","file":"pkg/registry/core/service/ipallocator/controller/repairip.go","code":"// syncServices reconcile the Service ClusterIPs to verify that each one has the corresponding IPAddress object associated\nfunc (r *RepairIPAddress) syncService(key string) error {\n\tvar syncError error\n\tnamespace, name, err := cache.SplitMetaNamespaceKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsvc, err := r.serviceLister.Services(namespace).Get(name)\n\tif err != nil {\n\t\t// nothing to do\n\t\treturn nil\n\t}\n\tif !helper.IsServiceIPSet(svc) {\n\t\t// didn't need a ClusterIP\n\t\treturn nil\n\t}\n\n\tfor _, clusterIP := range svc.Spec.ClusterIPs {\n\t\tip := netutils.ParseIPSloppy(clusterIP)\n\t\tif ip == nil {\n\t\t\t// ClusterIP is corrupt, ClusterIPs are already validated, but double checking here\n\t\t\t// in case there are some inconsistencies with the parsers\n\t\t\tr.recorder.Eventf(svc, nil, v1.EventTypeWarning, \"ClusterIPNotValid\", \"ClusterIPValidation\", \"Cluster IP %s is not a valid IP; please recreate Service\", ip)\n\t\t\truntime.HandleError(fmt.Errorf(\"the ClusterIP %s for Service %s/%s is not a valid IP; please recreate Service\", ip, svc.Namespace, svc.Name))\n\t\t\tcontinue\n\t\t}\n\n\t\tfamily := netutils.IPFamilyOf(ip)\n\t\tv1Family := getFamilyByIP(ip)\n\t\tnetwork, ok := r.networkByFamily[family]\n\t\tif !ok {\n\t\t\t// this service is using an IPFamily no longer configured on cluster\n\t\t\tr.recorder.Eventf(svc, nil, v1.EventTypeWarning, \"ClusterIPNotValid\", \"ClusterIPValidation\", \"Cluster IP %s(%s) is of ip family that is no longer configured on cluster; please recreate Service\", ip, v1Family)\n\t\t\truntime.HandleError(fmt.Errorf(\"the ClusterIP [%v]: %s for Service %s/%s is of ip family that is no longer configured on cluster; please recreate Service\", v1Family, ip, svc.Namespace, svc.Name))\n\t\t\tcontinue\n\t\t}\n\t\tif !network.Contains(ip) {\n\t\t\t// ClusterIP is out of range\n\t\t\tr.recorder.Eventf(svc, nil, v1.EventTypeWarning, \"ClusterIPOutOfRange\", \"ClusterIPAllocation\", \"Cluster IP [%v]: %s is not within the configured Service CIDR %s; please recreate service\", v1Family, ip, network.String())\n\t\t\truntime.HandleError(fmt.Errorf(\"the ClusterIP [%v]: %s for Service %s/%s is not within the service CIDR %s; please recreate\", v1Family, ip, svc.Namespace, svc.Name, network.String()))\n\t\t\tcontinue\n\t\t}\n\n\t\t// Get the IPAddress object associated to the ClusterIP\n\t\tipAddress, err := r.ipAddressLister.Get(ip.String())\n\t\tif apierrors.IsNotFound(err) {\n\t\t\t// ClusterIP doesn't seem to be allocated, create it.\n\t\t\tr.recorder.Eventf(svc, nil, v1.EventTypeWarning, \"ClusterIPNotAllocated\", \"ClusterIPAllocation\", \"Cluster IP [%v]: %s is not allocated; repairing\", v1Family, ip)\n\t\t\truntime.HandleError(fmt.Errorf(\"the ClusterIP [%v]: %s for Service %s/%s is not allocated; repairing\", v1Family, ip, svc.Namespace, svc.Name))\n\t\t\t_, err := r.client.NetworkingV1alpha1().IPAddresses().Create(context.Background(), newIPAddress(ip.String(), svc), metav1.CreateOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\tr.recorder.Eventf(svc, nil, v1.EventTypeWarning, \"UnknownError\", \"ClusterIPAllocation\", \"Unable to allocate ClusterIP [%v]: %s due to an unknown error\", v1Family, ip)\n\t\t\treturn fmt.Errorf(\"unable to allocate ClusterIP [%v]: %s for Service %s/%s due to an unknown error, will retry later: %v\", v1Family, ip, svc.Namespace, svc.Name, err)\n\t\t}\n\n\t\t// IPAddress that belongs to a Service must reference a Service\n\t\tif ipAddress.Spec.ParentRef.Group != \"\" ||\n\t\t\tipAddress.Spec.ParentRef.Resource != \"services\" {\n\t\t\tr.recorder.Eventf(svc, nil, v1.EventTypeWarning, \"ClusterIPNotAllocated\", \"ClusterIPAllocation\", \"the ClusterIP [%v]: %s for Service %s/%s has a wrong reference; repairing\", v1Family, ip, svc.Namespace, svc.Name)\n\t\t\tif err := r.recreateIPAddress(ipAddress.Name, svc); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// IPAddress that belongs to a Service must reference the current Service\n\t\tif ipAddress.Spec.ParentRef.Namespace != svc.Namespace ||\n\t\t\tipAddress.Spec.ParentRef.Name != svc.Name {\n\t\t\t// verify that there are no two Services with the same IP, otherwise\n\t\t\t// it will keep deleting and recreating the same IPAddress changing the reference\n\t\t\trefService, err := r.serviceLister.Services(ipAddress.Spec.ParentRef.Namespace).Get(ipAddress.Spec.ParentRef.Name)\n\t\t\tif err != nil {\n\t\t\t\tr.recorder.Eventf(svc, nil, v1.EventTypeWarning, \"ClusterIPNotAllocated\", \"ClusterIPAllocation\", \"the ClusterIP [%v]: %s for Service %s/%s has a wrong reference; repairing\", v1Family, ip, svc.Namespace, svc.Name)\n\t\t\t\tif err := r.recreateIPAddress(ipAddress.Name, svc); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// the IPAddress is duplicate but current Service is not the referenced, it has to be recreated\n\t\t\tfor _, clusterIP := range refService.Spec.ClusterIPs {\n\t\t\t\tif ipAddress.Name == clusterIP {\n\t\t\t\t\tr.recorder.Eventf(svc, nil, v1.EventTypeWarning, \"ClusterIPAlreadyAllocated\", \"ClusterIPAllocation\", \"Cluster IP [%v]:%s was assigned to multiple services; please recreate service\", family, ip)\n\t\t\t\t\truntime.HandleError(fmt.Errorf(\"the cluster IP [%v]:%s for service %s/%s was assigned to other services %s/%s; please recreate\", family, ip, svc.Namespace, svc.Name, refService.Namespace, refService.Name))\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// IPAddress must have the corresponding labels assigned by the allocator\n\t\tif !verifyIPAddressLabels(ipAddress) {\n\t\t\tif err := r.recreateIPAddress(ipAddress.Name, svc); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t}\n\treturn syncError\n}","line":{"from":307,"to":410}} {"id":100009791,"name":"recreateIPAddress","signature":"func (r *RepairIPAddress) recreateIPAddress(name string, svc *v1.Service) error","file":"pkg/registry/core/service/ipallocator/controller/repairip.go","code":"func (r *RepairIPAddress) recreateIPAddress(name string, svc *v1.Service) error {\n\terr := r.client.NetworkingV1alpha1().IPAddresses().Delete(context.Background(), name, metav1.DeleteOptions{})\n\tif err != nil \u0026\u0026 !apierrors.IsNotFound(err) {\n\t\treturn err\n\t}\n\t_, err = r.client.NetworkingV1alpha1().IPAddresses().Create(context.Background(), newIPAddress(name, svc), metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":412,"to":422}} {"id":100009792,"name":"ipWorker","signature":"func (r *RepairIPAddress) ipWorker()","file":"pkg/registry/core/service/ipallocator/controller/repairip.go","code":"func (r *RepairIPAddress) ipWorker() {\n\tfor r.processNextWorkIp() {\n\t}\n}","line":{"from":424,"to":427}} {"id":100009793,"name":"processNextWorkIp","signature":"func (r *RepairIPAddress) processNextWorkIp() bool","file":"pkg/registry/core/service/ipallocator/controller/repairip.go","code":"func (r *RepairIPAddress) processNextWorkIp() bool {\n\teKey, quit := r.ipQueue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer r.ipQueue.Done(eKey)\n\n\terr := r.syncIPAddress(eKey.(string))\n\tr.handleIpErr(err, eKey)\n\n\treturn true\n}","line":{"from":429,"to":440}} {"id":100009794,"name":"handleIpErr","signature":"func (r *RepairIPAddress) handleIpErr(err error, key interface{})","file":"pkg/registry/core/service/ipallocator/controller/repairip.go","code":"func (r *RepairIPAddress) handleIpErr(err error, key interface{}) {\n\tif err == nil {\n\t\tr.ipQueue.Forget(key)\n\t\treturn\n\t}\n\n\tif r.ipQueue.NumRequeues(key) \u003c maxRetries {\n\t\tklog.V(2).InfoS(\"Error syncing Service, retrying\", \"service\", key, \"err\", err)\n\t\tr.ipQueue.AddRateLimited(key)\n\t\treturn\n\t}\n\n\tklog.Warningf(\"Dropping Service %q out of the queue: %v\", key, err)\n\tr.ipQueue.Forget(key)\n\truntime.HandleError(err)\n}","line":{"from":442,"to":457}} {"id":100009795,"name":"syncIPAddress","signature":"func (r *RepairIPAddress) syncIPAddress(key string) error","file":"pkg/registry/core/service/ipallocator/controller/repairip.go","code":"// syncIPAddress verify that the IPAddress that are owned by the ipallocator controller reference an existing Service\n// to avoid leaking IPAddresses. IPAddresses that are owned by other controllers are not processed to avoid hotloops.\n// IPAddress that reference Services and are part of the ClusterIP are validated in the syncService loop.\nfunc (r *RepairIPAddress) syncIPAddress(key string) error {\n\tipAddress, err := r.ipAddressLister.Get(key)\n\tif err != nil {\n\t\t// nothing to do\n\t\treturn nil\n\t}\n\n\t// not mananged by this controller\n\tif !managedByController(ipAddress) {\n\t\treturn nil\n\t}\n\n\t// does not reference a Service but created by the service allocator, something else have changed it, delete it\n\tif ipAddress.Spec.ParentRef.Group != \"\" ||\n\t\tipAddress.Spec.ParentRef.Resource != \"services\" {\n\t\truntime.HandleError(fmt.Errorf(\"IPAddress %s appears to have been modified, not referencing a Service %v: cleaning up\", ipAddress.Name, ipAddress.Spec.ParentRef))\n\t\tr.recorder.Eventf(ipAddress, nil, v1.EventTypeWarning, \"IPAddressNotAllocated\", \"IPAddressAllocation\", \"IPAddress %s appears to have been modified, not referencing a Service %v: cleaning up\", ipAddress.Name, ipAddress.Spec.ParentRef)\n\t\terr := r.client.NetworkingV1alpha1().IPAddresses().Delete(context.Background(), ipAddress.Name, metav1.DeleteOptions{})\n\t\tif err != nil \u0026\u0026 !apierrors.IsNotFound(err) {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\tsvc, err := r.serviceLister.Services(ipAddress.Spec.ParentRef.Namespace).Get(ipAddress.Spec.ParentRef.Name)\n\tif apierrors.IsNotFound(err) {\n\t\t// cleaning all IPAddress without an owner reference IF the time since it was created is greater than 60 seconds (default timeout value on the kube-apiserver)\n\t\t// This is required because during the Service creation there is a time that the IPAddress object exists but the Service is still being created\n\t\t// Assume that CreationTimestamp exists.\n\t\tipLifetime := r.clock.Now().Sub(ipAddress.CreationTimestamp.Time)\n\t\tgracePeriod := 60 * time.Second\n\t\tif ipLifetime \u003e gracePeriod {\n\t\t\truntime.HandleError(fmt.Errorf(\"IPAddress %s appears to have leaked: cleaning up\", ipAddress.Name))\n\t\t\tr.recorder.Eventf(ipAddress, nil, v1.EventTypeWarning, \"IPAddressNotAllocated\", \"IPAddressAllocation\", \"IPAddress: %s for Service %s/%s appears to have leaked: cleaning up\", ipAddress.Name, ipAddress.Spec.ParentRef.Namespace, ipAddress.Spec.ParentRef.Name)\n\t\t\terr := r.client.NetworkingV1alpha1().IPAddresses().Delete(context.Background(), ipAddress.Name, metav1.DeleteOptions{})\n\t\t\tif err != nil \u0026\u0026 !apierrors.IsNotFound(err) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\t// requeue after the grace period\n\t\tr.ipQueue.AddAfter(key, gracePeriod-ipLifetime)\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\truntime.HandleError(fmt.Errorf(\"unable to get parent Service for IPAddress %s due to an unknown error: %v\", ipAddress, err))\n\t\tr.recorder.Eventf(ipAddress, nil, v1.EventTypeWarning, \"UnknownError\", \"IPAddressAllocation\", \"Unable to get parent Service for IPAddress %s due to an unknown error\", ipAddress)\n\t\treturn err\n\t}\n\t// The service exists, we have checked in previous loop that all Service to IPAddress are correct\n\t// but we also have to check the reverse, that the IPAddress to Service relation is correct\n\tfor _, clusterIP := range svc.Spec.ClusterIPs {\n\t\tif ipAddress.Name == clusterIP {\n\t\t\treturn nil\n\t\t}\n\t}\n\truntime.HandleError(fmt.Errorf(\"the IPAddress: %s for Service %s/%s has a wrong reference %#v; cleaning up\", ipAddress.Name, svc.Name, svc.Namespace, ipAddress.Spec.ParentRef))\n\tr.recorder.Eventf(ipAddress, nil, v1.EventTypeWarning, \"IPAddressWrongReference\", \"IPAddressAllocation\", \"IPAddress: %s for Service %s/%s has a wrong reference; cleaning up\", ipAddress.Name, svc.Namespace, svc.Name)\n\terr = r.client.NetworkingV1alpha1().IPAddresses().Delete(context.Background(), ipAddress.Name, metav1.DeleteOptions{})\n\tif err != nil \u0026\u0026 !apierrors.IsNotFound(err) {\n\t\treturn err\n\t}\n\treturn nil\n\n}","line":{"from":459,"to":525}} {"id":100009796,"name":"newIPAddress","signature":"func newIPAddress(name string, svc *v1.Service) *networkingv1alpha1.IPAddress","file":"pkg/registry/core/service/ipallocator/controller/repairip.go","code":"func newIPAddress(name string, svc *v1.Service) *networkingv1alpha1.IPAddress {\n\tfamily := string(v1.IPv4Protocol)\n\tif netutils.IsIPv6String(name) {\n\t\tfamily = string(v1.IPv6Protocol)\n\t}\n\treturn \u0026networkingv1alpha1.IPAddress{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tLabels: map[string]string{\n\t\t\t\tnetworkingv1alpha1.LabelIPAddressFamily: family,\n\t\t\t\tnetworkingv1alpha1.LabelManagedBy: ipallocator.ControllerName,\n\t\t\t},\n\t\t},\n\t\tSpec: networkingv1alpha1.IPAddressSpec{\n\t\t\tParentRef: serviceToRef(svc),\n\t\t},\n\t}\n}","line":{"from":526,"to":543}} {"id":100009797,"name":"serviceToRef","signature":"func serviceToRef(svc *v1.Service) *networkingv1alpha1.ParentReference","file":"pkg/registry/core/service/ipallocator/controller/repairip.go","code":"func serviceToRef(svc *v1.Service) *networkingv1alpha1.ParentReference {\n\tif svc == nil {\n\t\treturn nil\n\t}\n\n\treturn \u0026networkingv1alpha1.ParentReference{\n\t\tGroup: \"\",\n\t\tResource: \"services\",\n\t\tNamespace: svc.Namespace,\n\t\tName: svc.Name,\n\t\tUID: svc.UID,\n\t}\n}","line":{"from":545,"to":557}} {"id":100009798,"name":"getFamilyByIP","signature":"func getFamilyByIP(ip net.IP) v1.IPFamily","file":"pkg/registry/core/service/ipallocator/controller/repairip.go","code":"func getFamilyByIP(ip net.IP) v1.IPFamily {\n\tif netutils.IsIPv6(ip) {\n\t\treturn v1.IPv6Protocol\n\t}\n\treturn v1.IPv4Protocol\n}","line":{"from":559,"to":564}} {"id":100009799,"name":"managedByController","signature":"func managedByController(ip *networkingv1alpha1.IPAddress) bool","file":"pkg/registry/core/service/ipallocator/controller/repairip.go","code":"// managedByController returns true if the controller of the provided\n// EndpointSlices is the EndpointSlice controller.\nfunc managedByController(ip *networkingv1alpha1.IPAddress) bool {\n\tmanagedBy, ok := ip.Labels[networkingv1alpha1.LabelManagedBy]\n\tif !ok {\n\t\treturn false\n\t}\n\treturn managedBy == ipallocator.ControllerName\n}","line":{"from":566,"to":574}} {"id":100009800,"name":"verifyIPAddressLabels","signature":"func verifyIPAddressLabels(ip *networkingv1alpha1.IPAddress) bool","file":"pkg/registry/core/service/ipallocator/controller/repairip.go","code":"func verifyIPAddressLabels(ip *networkingv1alpha1.IPAddress) bool {\n\tlabelFamily, ok := ip.Labels[networkingv1alpha1.LabelIPAddressFamily]\n\tif !ok {\n\t\treturn false\n\t}\n\n\tfamily := string(v1.IPv4Protocol)\n\tif netutils.IsIPv6String(ip.Name) {\n\t\tfamily = string(v1.IPv6Protocol)\n\t}\n\tif family != labelFamily {\n\t\treturn false\n\t}\n\treturn managedByController(ip)\n}","line":{"from":576,"to":590}} {"id":100009801,"name":"Error","signature":"func (e *ErrNotInRange) Error() string","file":"pkg/registry/core/service/ipallocator/interfaces.go","code":"func (e *ErrNotInRange) Error() string {\n\treturn fmt.Sprintf(\"the provided IP (%v) is not in the valid range. The range of valid IPs is %s\", e.IP, e.ValidRange)\n}","line":{"from":55,"to":57}} {"id":100009802,"name":"NewIPAllocator","signature":"func NewIPAllocator(","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"// NewIPAllocator returns an IP allocator associated to a network range\n// that use the IPAddress objectto track the assigned IP addresses,\n// using an informer cache as storage.\nfunc NewIPAllocator(\n\tcidr *net.IPNet,\n\tclient networkingv1alpha1client.NetworkingV1alpha1Interface,\n\tipAddressInformer networkingv1alpha1informers.IPAddressInformer,\n) (*Allocator, error) {\n\tprefix, err := netip.ParsePrefix(cidr.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif prefix.Addr().Is6() \u0026\u0026 prefix.Bits() \u003c 64 {\n\t\treturn nil, fmt.Errorf(\"shortest allowed prefix length for service CIDR is 64, got %d\", prefix.Bits())\n\t}\n\n\t// TODO: use the utils/net function once is available\n\tsize := hostsPerNetwork(cidr)\n\tvar family api.IPFamily\n\tif netutils.IsIPv6CIDR(cidr) {\n\t\tfamily = api.IPv6Protocol\n\t} else {\n\t\tfamily = api.IPv4Protocol\n\t}\n\t// Caching the first, offset and last addresses allows to optimize\n\t// the search loops by using the netip.Addr iterator instead\n\t// of having to do conversions with IP addresses.\n\t// Don't allocate the network's \".0\" address.\n\tipFirst := prefix.Masked().Addr().Next()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Use the broadcast address as last address for IPv6\n\tipLast, err := broadcastAddress(prefix)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// For IPv4 don't use the network's broadcast address\n\tif family == api.IPv4Protocol {\n\t\tipLast = ipLast.Prev()\n\t}\n\t// KEP-3070: Reserve Service IP Ranges For Dynamic and Static IP Allocation\n\t// calculate the subrange offset\n\trangeOffset := calculateRangeOffset(cidr)\n\toffsetAddress, err := addOffsetAddress(ipFirst, uint64(rangeOffset))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ta := \u0026Allocator{\n\t\tcidr: cidr,\n\t\tprefix: prefix,\n\t\tfirstAddress: ipFirst,\n\t\tlastAddress: ipLast,\n\t\trangeOffset: rangeOffset,\n\t\toffsetAddress: offsetAddress,\n\t\tsize: size,\n\t\tfamily: family,\n\t\tclient: client,\n\t\tipAddressLister: ipAddressInformer.Lister(),\n\t\tipAddressSynced: ipAddressInformer.Informer().HasSynced,\n\t\tmetrics: \u0026emptyMetricsRecorder{}, // disabled by default\n\t\tmetricLabel: cidr.String(),\n\t\trand: rand.New(rand.NewSource(time.Now().UnixNano())),\n\t}\n\n\treturn a, nil\n}","line":{"from":71,"to":138}} {"id":100009803,"name":"createIPAddress","signature":"func (a *Allocator) createIPAddress(name string, svc *api.Service, scope string) error","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"func (a *Allocator) createIPAddress(name string, svc *api.Service, scope string) error {\n\tipAddress := networkingv1alpha1.IPAddress{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tLabels: map[string]string{\n\t\t\t\tnetworkingv1alpha1.LabelIPAddressFamily: string(a.IPFamily()),\n\t\t\t\tnetworkingv1alpha1.LabelManagedBy: ControllerName,\n\t\t\t},\n\t\t},\n\t\tSpec: networkingv1alpha1.IPAddressSpec{\n\t\t\tParentRef: serviceToRef(svc),\n\t\t},\n\t}\n\t_, err := a.client.IPAddresses().Create(context.Background(), \u0026ipAddress, metav1.CreateOptions{})\n\tif err != nil {\n\t\t// update metrics\n\t\ta.metrics.incrementAllocationErrors(a.metricLabel, scope)\n\t\tif apierrors.IsAlreadyExists(err) {\n\t\t\treturn ErrAllocated\n\t\t}\n\t\treturn err\n\t}\n\t// update metrics\n\ta.metrics.incrementAllocations(a.metricLabel, scope)\n\ta.metrics.setAllocated(a.metricLabel, a.Used())\n\ta.metrics.setAvailable(a.metricLabel, a.Free())\n\treturn nil\n}","line":{"from":140,"to":167}} {"id":100009804,"name":"Allocate","signature":"func (a *Allocator) Allocate(ip net.IP) error","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"// Allocate attempts to reserve the provided IP. ErrNotInRange or\n// ErrAllocated will be returned if the IP is not valid for this range\n// or has already been reserved. ErrFull will be returned if there\n// are no addresses left.\n// Only for testing, it will fail to create the IPAddress object because\n// the Service reference is required.\nfunc (a *Allocator) Allocate(ip net.IP) error {\n\treturn a.AllocateService(nil, ip)\n}","line":{"from":169,"to":177}} {"id":100009805,"name":"AllocateService","signature":"func (a *Allocator) AllocateService(svc *api.Service, ip net.IP) error","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"// AllocateService attempts to reserve the provided IP. ErrNotInRange or\n// ErrAllocated will be returned if the IP is not valid for this range\n// or has already been reserved. ErrFull will be returned if there\n// are no addresses left.\nfunc (a *Allocator) AllocateService(svc *api.Service, ip net.IP) error {\n\treturn a.allocateService(svc, ip, dryRunFalse)\n}","line":{"from":179,"to":185}} {"id":100009806,"name":"allocateService","signature":"func (a *Allocator) allocateService(svc *api.Service, ip net.IP, dryRun bool) error","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"func (a *Allocator) allocateService(svc *api.Service, ip net.IP, dryRun bool) error {\n\tif !a.ipAddressSynced() {\n\t\treturn fmt.Errorf(\"allocator not ready\")\n\t}\n\taddr, err := netip.ParseAddr(ip.String())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// check address is within the range of available addresses\n\tif addr.Less(a.firstAddress) || // requested address is lower than the first address in the subnet\n\t\ta.lastAddress.Less(addr) { // the last address in the subnet is lower than the requested address\n\t\tif !dryRun {\n\t\t\t// update metrics\n\t\t\ta.metrics.incrementAllocationErrors(a.metricLabel, \"static\")\n\t\t}\n\t\treturn \u0026ErrNotInRange{ip, a.prefix.String()}\n\t}\n\tif dryRun {\n\t\treturn nil\n\t}\n\treturn a.createIPAddress(ip.String(), svc, \"static\")\n}","line":{"from":187,"to":209}} {"id":100009807,"name":"AllocateNext","signature":"func (a *Allocator) AllocateNext() (net.IP, error)","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"// AllocateNext return an IP address that wasn't allocated yet.\n// Only for testing, it will fail to create the IPAddress object because\n// the Service reference is required.\nfunc (a *Allocator) AllocateNext() (net.IP, error) {\n\treturn a.AllocateNextService(nil)\n}","line":{"from":211,"to":216}} {"id":100009808,"name":"AllocateNextService","signature":"func (a *Allocator) AllocateNextService(svc *api.Service) (net.IP, error)","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"// AllocateNext return an IP address that wasn't allocated yet.\nfunc (a *Allocator) AllocateNextService(svc *api.Service) (net.IP, error) {\n\treturn a.allocateNextService(svc, dryRunFalse)\n}","line":{"from":218,"to":221}} {"id":100009809,"name":"allocateNextService","signature":"func (a *Allocator) allocateNextService(svc *api.Service, dryRun bool) (net.IP, error)","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"// allocateNextService tries to allocate a free IP address within the subnet.\n// If the subnet is big enough, it partitions the subnet into two subranges,\n// delimited by a.rangeOffset.\n// It tries to allocate a free IP address from the upper subnet first and\n// falls back to the lower subnet.\n// It starts allocating from a random IP within each range.\nfunc (a *Allocator) allocateNextService(svc *api.Service, dryRun bool) (net.IP, error) {\n\tif !a.ipAddressSynced() {\n\t\treturn nil, fmt.Errorf(\"allocator not ready\")\n\t}\n\tif dryRun {\n\t\t// Don't bother finding a free value. It's racy and not worth the\n\t\t// effort to plumb any further.\n\t\treturn a.CIDR().IP, nil\n\t}\n\n\ttrace := utiltrace.New(\"allocate dynamic ClusterIP address\")\n\tdefer trace.LogIfLong(500 * time.Millisecond)\n\n\t// rand.Int63n panics for n \u003c= 0 so we need to avoid problems when\n\t// converting from uint64 to int64\n\trangeSize := a.size - uint64(a.rangeOffset)\n\tvar offset uint64\n\tswitch {\n\tcase rangeSize \u003e= math.MaxInt64:\n\t\toffset = rand.Uint64()\n\tcase rangeSize == 0:\n\t\treturn net.IP{}, ErrFull\n\tdefault:\n\t\toffset = uint64(a.rand.Int63n(int64(rangeSize)))\n\t}\n\titerator := ipIterator(a.offsetAddress, a.lastAddress, offset)\n\tip, err := a.allocateFromRange(iterator, svc)\n\tif err == nil {\n\t\treturn ip, nil\n\t}\n\t// check the lower range\n\tif a.rangeOffset != 0 {\n\t\toffset = uint64(a.rand.Intn(a.rangeOffset))\n\t\titerator = ipIterator(a.firstAddress, a.offsetAddress.Prev(), offset)\n\t\tip, err = a.allocateFromRange(iterator, svc)\n\t\tif err == nil {\n\t\t\treturn ip, nil\n\t\t}\n\t}\n\t// update metrics\n\ta.metrics.incrementAllocationErrors(a.metricLabel, \"dynamic\")\n\treturn net.IP{}, ErrFull\n}","line":{"from":223,"to":271}} {"id":100009810,"name":"ipIterator","signature":"func ipIterator(first netip.Addr, last netip.Addr, offset uint64) func() netip.Addr","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"// IP iterator allows to iterate over all the IP addresses\n// in a range defined by the start and last address.\n// It starts iterating at the address position defined by the offset.\n// It returns an invalid address to indicate it hasfinished.\nfunc ipIterator(first netip.Addr, last netip.Addr, offset uint64) func() netip.Addr {\n\t// There are no modulo operations for IP addresses\n\tmodulo := func(addr netip.Addr) netip.Addr {\n\t\tif addr.Compare(last) == 1 {\n\t\t\treturn first\n\t\t}\n\t\treturn addr\n\t}\n\tnext := func(addr netip.Addr) netip.Addr {\n\t\treturn modulo(addr.Next())\n\t}\n\tstart, err := addOffsetAddress(first, offset)\n\tif err != nil {\n\t\treturn func() netip.Addr { return netip.Addr{} }\n\t}\n\tstart = modulo(start)\n\tip := start\n\tseen := false\n\treturn func() netip.Addr {\n\t\tvalue := ip\n\t\t// is the last or the first iteration\n\t\tif value == start {\n\t\t\tif seen {\n\t\t\t\treturn netip.Addr{}\n\t\t\t}\n\t\t\tseen = true\n\t\t}\n\t\tip = next(ip)\n\t\treturn value\n\t}\n\n}","line":{"from":273,"to":308}} {"id":100009811,"name":"allocateFromRange","signature":"func (a *Allocator) allocateFromRange(iterator func() netip.Addr, svc *api.Service) (net.IP, error)","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"// allocateFromRange allocates an empty IP address from the range of\n// IPs between the first and last address (both included), starting\n// from the start address.\n// TODO: this is a linear search, it can be optimized.\nfunc (a *Allocator) allocateFromRange(iterator func() netip.Addr, svc *api.Service) (net.IP, error) {\n\tfor {\n\t\tip := iterator()\n\t\tif !ip.IsValid() {\n\t\t\tbreak\n\t\t}\n\t\tname := ip.String()\n\t\t_, err := a.ipAddressLister.Get(name)\n\t\t// continue if ip already exist\n\t\tif err == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif !apierrors.IsNotFound(err) {\n\t\t\tklog.Infof(\"unexpected error: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\t// address is not present on the cache, try to allocate it\n\t\terr = a.createIPAddress(name, svc, \"dynamic\")\n\t\t// an error can happen if there is a race and our informer was not updated\n\t\t// swallow the error and try with the next IP address\n\t\tif err != nil {\n\t\t\tklog.Infof(\"can not create IPAddress %s: %v\", name, err)\n\t\t\tcontinue\n\t\t}\n\t\treturn ip.AsSlice(), nil\n\t}\n\treturn net.IP{}, ErrFull\n}","line":{"from":310,"to":341}} {"id":100009812,"name":"Release","signature":"func (a *Allocator) Release(ip net.IP) error","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"// Release releases the IP back to the pool. Releasing an\n// unallocated IP or an IP out of the range is a no-op and\n// returns no error.\nfunc (a *Allocator) Release(ip net.IP) error {\n\treturn a.release(ip, dryRunFalse)\n}","line":{"from":343,"to":348}} {"id":100009813,"name":"release","signature":"func (a *Allocator) release(ip net.IP, dryRun bool) error","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"func (a *Allocator) release(ip net.IP, dryRun bool) error {\n\tif !a.ipAddressSynced() {\n\t\treturn fmt.Errorf(\"allocator not ready\")\n\t}\n\tif dryRun {\n\t\treturn nil\n\t}\n\tname := ip.String()\n\t// Try to Delete the IPAddress independently of the cache state.\n\t// The error is ignored for compatibility reasons.\n\terr := a.client.IPAddresses().Delete(context.Background(), name, metav1.DeleteOptions{})\n\tif err == nil {\n\t\t// update metrics\n\t\ta.metrics.setAllocated(a.metricLabel, a.Used())\n\t\ta.metrics.setAvailable(a.metricLabel, a.Free())\n\t\treturn nil\n\t}\n\tklog.Infof(\"error releasing ip %s : %v\", name, err)\n\treturn nil\n}","line":{"from":350,"to":369}} {"id":100009814,"name":"ForEach","signature":"func (a *Allocator) ForEach(f func(net.IP))","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"// ForEach executes the function on each allocated IP\n// This is required to satisfy the Allocator Interface only\nfunc (a *Allocator) ForEach(f func(net.IP)) {\n\tipLabelSelector := labels.Set(map[string]string{\n\t\tnetworkingv1alpha1.LabelIPAddressFamily: string(a.IPFamily()),\n\t\tnetworkingv1alpha1.LabelManagedBy: ControllerName,\n\t}).AsSelectorPreValidated()\n\tips, err := a.ipAddressLister.List(ipLabelSelector)\n\tif err != nil {\n\t\treturn\n\t}\n\tfor _, ip := range ips {\n\t\tf(netutils.ParseIPSloppy(ip.Name))\n\t}\n}","line":{"from":371,"to":385}} {"id":100009815,"name":"CIDR","signature":"func (a *Allocator) CIDR() net.IPNet","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"func (a *Allocator) CIDR() net.IPNet {\n\treturn *a.cidr\n}","line":{"from":387,"to":389}} {"id":100009816,"name":"Has","signature":"func (a *Allocator) Has(ip net.IP) bool","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"// for testing\nfunc (a *Allocator) Has(ip net.IP) bool {\n\t// convert IP to name\n\tname := ip.String()\n\tipAddress, err := a.client.IPAddresses().Get(context.Background(), name, metav1.GetOptions{})\n\tif err != nil || len(ipAddress.Name) == 0 {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":391,"to":400}} {"id":100009817,"name":"IPFamily","signature":"func (a *Allocator) IPFamily() api.IPFamily","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"func (a *Allocator) IPFamily() api.IPFamily {\n\treturn a.family\n}","line":{"from":402,"to":404}} {"id":100009818,"name":"Used","signature":"func (a *Allocator) Used() int","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"// for testing\nfunc (a *Allocator) Used() int {\n\tipLabelSelector := labels.Set(map[string]string{\n\t\tnetworkingv1alpha1.LabelIPAddressFamily: string(a.IPFamily()),\n\t\tnetworkingv1alpha1.LabelManagedBy: ControllerName,\n\t}).AsSelectorPreValidated()\n\tips, err := a.ipAddressLister.List(ipLabelSelector)\n\tif err != nil {\n\t\treturn 0\n\t}\n\treturn len(ips)\n}","line":{"from":406,"to":417}} {"id":100009819,"name":"Free","signature":"func (a *Allocator) Free() int","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"// for testing\nfunc (a *Allocator) Free() int {\n\treturn int(a.size) - a.Used()\n}","line":{"from":419,"to":422}} {"id":100009820,"name":"Destroy","signature":"func (a *Allocator) Destroy()","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"// Destroy\nfunc (a *Allocator) Destroy() {\n}","line":{"from":424,"to":426}} {"id":100009821,"name":"DryRun","signature":"func (a *Allocator) DryRun() Interface","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"// DryRun\nfunc (a *Allocator) DryRun() Interface {\n\treturn dryRunAllocator{a}\n}","line":{"from":428,"to":431}} {"id":100009822,"name":"EnableMetrics","signature":"func (a *Allocator) EnableMetrics()","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"// EnableMetrics\nfunc (a *Allocator) EnableMetrics() {\n\tregisterMetrics()\n\ta.metrics = \u0026metricsRecorder{}\n}","line":{"from":433,"to":437}} {"id":100009823,"name":"Allocate","signature":"func (dry dryRunAllocator) Allocate(ip net.IP) error","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"func (dry dryRunAllocator) Allocate(ip net.IP) error {\n\treturn dry.real.allocateService(nil, ip, dryRunTrue)\n\n}","line":{"from":444,"to":447}} {"id":100009824,"name":"AllocateNext","signature":"func (dry dryRunAllocator) AllocateNext() (net.IP, error)","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"func (dry dryRunAllocator) AllocateNext() (net.IP, error) {\n\treturn dry.real.allocateNextService(nil, dryRunTrue)\n}","line":{"from":449,"to":451}} {"id":100009825,"name":"Release","signature":"func (dry dryRunAllocator) Release(ip net.IP) error","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"func (dry dryRunAllocator) Release(ip net.IP) error {\n\treturn dry.real.release(ip, dryRunTrue)\n}","line":{"from":453,"to":455}} {"id":100009826,"name":"ForEach","signature":"func (dry dryRunAllocator) ForEach(cb func(net.IP))","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"func (dry dryRunAllocator) ForEach(cb func(net.IP)) {\n\tdry.real.ForEach(cb)\n}","line":{"from":457,"to":459}} {"id":100009827,"name":"CIDR","signature":"func (dry dryRunAllocator) CIDR() net.IPNet","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"func (dry dryRunAllocator) CIDR() net.IPNet {\n\treturn dry.real.CIDR()\n}","line":{"from":461,"to":463}} {"id":100009828,"name":"IPFamily","signature":"func (dry dryRunAllocator) IPFamily() api.IPFamily","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"func (dry dryRunAllocator) IPFamily() api.IPFamily {\n\treturn dry.real.IPFamily()\n}","line":{"from":465,"to":467}} {"id":100009829,"name":"DryRun","signature":"func (dry dryRunAllocator) DryRun() Interface","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"func (dry dryRunAllocator) DryRun() Interface {\n\treturn dry\n}","line":{"from":469,"to":471}} {"id":100009830,"name":"Has","signature":"func (dry dryRunAllocator) Has(ip net.IP) bool","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"func (dry dryRunAllocator) Has(ip net.IP) bool {\n\treturn dry.real.Has(ip)\n}","line":{"from":473,"to":475}} {"id":100009831,"name":"Destroy","signature":"func (dry dryRunAllocator) Destroy()","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"func (dry dryRunAllocator) Destroy() {\n}","line":{"from":477,"to":478}} {"id":100009832,"name":"EnableMetrics","signature":"func (dry dryRunAllocator) EnableMetrics()","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"func (dry dryRunAllocator) EnableMetrics() {\n}","line":{"from":480,"to":481}} {"id":100009833,"name":"addOffsetAddress","signature":"func addOffsetAddress(address netip.Addr, offset uint64) (netip.Addr, error)","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"// addOffsetAddress returns the address at the provided offset within the subnet\n// TODO: move it to k8s.io/utils/net, this is the same as current AddIPOffset()\n// but using netip.Addr instead of net.IP\nfunc addOffsetAddress(address netip.Addr, offset uint64) (netip.Addr, error) {\n\taddressBig := big.NewInt(0).SetBytes(address.AsSlice())\n\tr := big.NewInt(0).Add(addressBig, big.NewInt(int64(offset)))\n\taddr, ok := netip.AddrFromSlice(r.Bytes())\n\tif !ok {\n\t\treturn netip.Addr{}, fmt.Errorf(\"invalid address %v\", r.Bytes())\n\t}\n\treturn addr, nil\n}","line":{"from":483,"to":494}} {"id":100009834,"name":"hostsPerNetwork","signature":"func hostsPerNetwork(subnet *net.IPNet) uint64","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"// hostsPerNetwork returns the number of available hosts in a subnet.\n// The max number is limited by the size of an uint64.\n// Number of hosts is calculated with the formula:\n// IPv4: 2^x – 2, not consider network and broadcast address\n// IPv6: 2^x - 1, not consider network address\n// where x is the number of host bits in the subnet.\nfunc hostsPerNetwork(subnet *net.IPNet) uint64 {\n\tones, bits := subnet.Mask.Size()\n\t// this checks that we are not overflowing an int64\n\tif bits-ones \u003e= 64 {\n\t\treturn math.MaxUint64\n\t}\n\tmax := uint64(1) \u003c\u003c uint(bits-ones)\n\t// Don't use the network's \".0\" address,\n\tif max == 0 {\n\t\treturn 0\n\t}\n\tmax--\n\tif netutils.IsIPv4CIDR(subnet) {\n\t\t// Don't use the IPv4 network's broadcast address\n\t\tif max == 0 {\n\t\t\treturn 0\n\t\t}\n\t\tmax--\n\t}\n\treturn max\n}","line":{"from":496,"to":522}} {"id":100009835,"name":"broadcastAddress","signature":"func broadcastAddress(subnet netip.Prefix) (netip.Addr, error)","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"// broadcastAddress returns the broadcast address of the subnet\n// The broadcast address is obtained by setting all the host bits\n// in a subnet to 1.\n// network 192.168.0.0/24 : subnet bits 24 host bits 32 - 24 = 8\n// broadcast address 192.168.0.255\nfunc broadcastAddress(subnet netip.Prefix) (netip.Addr, error) {\n\tbase := subnet.Masked().Addr()\n\tbytes := base.AsSlice()\n\t// get all the host bits from the subnet\n\tn := 8*len(bytes) - subnet.Bits()\n\t// set all the host bits to 1\n\tfor i := len(bytes) - 1; i \u003e= 0 \u0026\u0026 n \u003e 0; i-- {\n\t\tif n \u003e= 8 {\n\t\t\tbytes[i] = 0xff\n\t\t\tn -= 8\n\t\t} else {\n\t\t\tmask := ^uint8(0) \u003e\u003e (8 - n)\n\t\t\tbytes[i] |= mask\n\t\t\tbreak\n\t\t}\n\t}\n\n\taddr, ok := netip.AddrFromSlice(bytes)\n\tif !ok {\n\t\treturn netip.Addr{}, fmt.Errorf(\"invalid address %v\", bytes)\n\t}\n\treturn addr, nil\n}","line":{"from":524,"to":551}} {"id":100009836,"name":"serviceToRef","signature":"func serviceToRef(svc *api.Service) *networkingv1alpha1.ParentReference","file":"pkg/registry/core/service/ipallocator/ipallocator.go","code":"// serviceToRef obtain the Service Parent Reference\nfunc serviceToRef(svc *api.Service) *networkingv1alpha1.ParentReference {\n\tif svc == nil {\n\t\treturn nil\n\t}\n\n\treturn \u0026networkingv1alpha1.ParentReference{\n\t\tGroup: \"\",\n\t\tResource: \"services\",\n\t\tNamespace: svc.Namespace,\n\t\tName: svc.Name,\n\t\tUID: svc.UID,\n\t}\n}","line":{"from":553,"to":566}} {"id":100009837,"name":"registerMetrics","signature":"func registerMetrics()","file":"pkg/registry/core/service/ipallocator/metrics.go","code":"func registerMetrics() {\n\tregisterMetricsOnce.Do(func() {\n\t\tlegacyregistry.MustRegister(clusterIPAllocated)\n\t\tlegacyregistry.MustRegister(clusterIPAvailable)\n\t\tlegacyregistry.MustRegister(clusterIPAllocations)\n\t\tlegacyregistry.MustRegister(clusterIPAllocationErrors)\n\t})\n}","line":{"from":80,"to":87}} {"id":100009838,"name":"setAllocated","signature":"func (m *metricsRecorder) setAllocated(cidr string, allocated int)","file":"pkg/registry/core/service/ipallocator/metrics.go","code":"func (m *metricsRecorder) setAllocated(cidr string, allocated int) {\n\tclusterIPAllocated.WithLabelValues(cidr).Set(float64(allocated))\n}","line":{"from":100,"to":102}} {"id":100009839,"name":"setAvailable","signature":"func (m *metricsRecorder) setAvailable(cidr string, available int)","file":"pkg/registry/core/service/ipallocator/metrics.go","code":"func (m *metricsRecorder) setAvailable(cidr string, available int) {\n\tclusterIPAvailable.WithLabelValues(cidr).Set(float64(available))\n}","line":{"from":104,"to":106}} {"id":100009840,"name":"incrementAllocations","signature":"func (m *metricsRecorder) incrementAllocations(cidr, scope string)","file":"pkg/registry/core/service/ipallocator/metrics.go","code":"func (m *metricsRecorder) incrementAllocations(cidr, scope string) {\n\tclusterIPAllocations.WithLabelValues(cidr, scope).Inc()\n}","line":{"from":108,"to":110}} {"id":100009841,"name":"incrementAllocationErrors","signature":"func (m *metricsRecorder) incrementAllocationErrors(cidr, scope string)","file":"pkg/registry/core/service/ipallocator/metrics.go","code":"func (m *metricsRecorder) incrementAllocationErrors(cidr, scope string) {\n\tclusterIPAllocationErrors.WithLabelValues(cidr, scope).Inc()\n}","line":{"from":112,"to":114}} {"id":100009842,"name":"setAllocated","signature":"func (*emptyMetricsRecorder) setAllocated(cidr string, allocated int) {}","file":"pkg/registry/core/service/ipallocator/metrics.go","code":"func (*emptyMetricsRecorder) setAllocated(cidr string, allocated int) {}","line":{"from":119,"to":119}} {"id":100009843,"name":"setAvailable","signature":"func (*emptyMetricsRecorder) setAvailable(cidr string, available int) {}","file":"pkg/registry/core/service/ipallocator/metrics.go","code":"func (*emptyMetricsRecorder) setAvailable(cidr string, available int) {}","line":{"from":120,"to":120}} {"id":100009844,"name":"incrementAllocations","signature":"func (*emptyMetricsRecorder) incrementAllocations(cidr, scope string) {}","file":"pkg/registry/core/service/ipallocator/metrics.go","code":"func (*emptyMetricsRecorder) incrementAllocations(cidr, scope string) {}","line":{"from":121,"to":121}} {"id":100009845,"name":"incrementAllocationErrors","signature":"func (*emptyMetricsRecorder) incrementAllocationErrors(cidr, scope string) {}","file":"pkg/registry/core/service/ipallocator/metrics.go","code":"func (*emptyMetricsRecorder) incrementAllocationErrors(cidr, scope string) {}","line":{"from":122,"to":122}} {"id":100009846,"name":"Error","signature":"func (e *ErrNotInRange) Error() string","file":"pkg/registry/core/service/portallocator/allocator.go","code":"func (e *ErrNotInRange) Error() string {\n\treturn fmt.Sprintf(\"provided port is not in the valid range. The range of valid ports is %s\", e.ValidPorts)\n}","line":{"from":53,"to":55}} {"id":100009847,"name":"New","signature":"func New(pr net.PortRange, allocatorFactory allocator.AllocatorWithOffsetFactory) (*PortAllocator, error)","file":"pkg/registry/core/service/portallocator/allocator.go","code":"// New creates a PortAllocator over a net.PortRange, calling allocatorFactory to construct the backing store.\nfunc New(pr net.PortRange, allocatorFactory allocator.AllocatorWithOffsetFactory) (*PortAllocator, error) {\n\tmax := pr.Size\n\trangeSpec := pr.String()\n\n\ta := \u0026PortAllocator{\n\t\tportRange: pr,\n\t\tmetrics: \u0026emptyMetricsRecorder{},\n\t}\n\n\tvar offset = 0\n\tif utilfeature.DefaultFeatureGate.Enabled(features.ServiceNodePortStaticSubrange) {\n\t\toffset = calculateRangeOffset(pr)\n\t}\n\n\tvar err error\n\ta.alloc, err = allocatorFactory(max, rangeSpec, offset)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn a, err\n}","line":{"from":69,"to":91}} {"id":100009848,"name":"NewInMemory","signature":"func NewInMemory(pr net.PortRange) (*PortAllocator, error)","file":"pkg/registry/core/service/portallocator/allocator.go","code":"// NewInMemory creates an in-memory allocator.\nfunc NewInMemory(pr net.PortRange) (*PortAllocator, error) {\n\treturn New(pr, func(max int, rangeSpec string, offset int) (allocator.Interface, error) {\n\t\treturn allocator.NewAllocationMapWithOffset(max, rangeSpec, offset), nil\n\t})\n}","line":{"from":93,"to":98}} {"id":100009849,"name":"NewFromSnapshot","signature":"func NewFromSnapshot(snap *api.RangeAllocation) (*PortAllocator, error)","file":"pkg/registry/core/service/portallocator/allocator.go","code":"// NewFromSnapshot allocates a PortAllocator and initializes it from a snapshot.\nfunc NewFromSnapshot(snap *api.RangeAllocation) (*PortAllocator, error) {\n\tpr, err := net.ParsePortRange(snap.Range)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr, err := NewInMemory(*pr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := r.Restore(*pr, snap.Data); err != nil {\n\t\treturn nil, err\n\t}\n\treturn r, nil\n}","line":{"from":100,"to":114}} {"id":100009850,"name":"Free","signature":"func (r *PortAllocator) Free() int","file":"pkg/registry/core/service/portallocator/allocator.go","code":"// Free returns the count of port left in the range.\nfunc (r *PortAllocator) Free() int {\n\treturn r.alloc.Free()\n}","line":{"from":116,"to":119}} {"id":100009851,"name":"Used","signature":"func (r *PortAllocator) Used() int","file":"pkg/registry/core/service/portallocator/allocator.go","code":"// Used returns the count of ports used in the range.\nfunc (r *PortAllocator) Used() int {\n\treturn r.portRange.Size - r.alloc.Free()\n}","line":{"from":121,"to":124}} {"id":100009852,"name":"Allocate","signature":"func (r *PortAllocator) Allocate(port int) error","file":"pkg/registry/core/service/portallocator/allocator.go","code":"// Allocate attempts to reserve the provided port. ErrNotInRange or\n// ErrAllocated will be returned if the port is not valid for this range\n// or has already been reserved. ErrFull will be returned if there\n// are no ports left.\nfunc (r *PortAllocator) Allocate(port int) error {\n\tok, offset := r.contains(port)\n\tif !ok {\n\t\t// update metrics\n\t\tr.metrics.incrementAllocationErrors(\"static\")\n\n\t\t// include valid port range in error\n\t\tvalidPorts := r.portRange.String()\n\t\treturn \u0026ErrNotInRange{validPorts}\n\t}\n\n\tallocated, err := r.alloc.Allocate(offset)\n\tif err != nil {\n\t\t// update metrics\n\t\tr.metrics.incrementAllocationErrors(\"static\")\n\t\treturn err\n\t}\n\tif !allocated {\n\t\t// update metrics\n\t\tr.metrics.incrementAllocationErrors(\"static\")\n\t\treturn ErrAllocated\n\t}\n\n\t// update metrics\n\tr.metrics.incrementAllocations(\"static\")\n\tr.metrics.setAllocated(r.Used())\n\tr.metrics.setAvailable(r.Free())\n\n\treturn nil\n}","line":{"from":126,"to":159}} {"id":100009853,"name":"AllocateNext","signature":"func (r *PortAllocator) AllocateNext() (int, error)","file":"pkg/registry/core/service/portallocator/allocator.go","code":"// AllocateNext reserves one of the ports from the pool. ErrFull may\n// be returned if there are no ports left.\nfunc (r *PortAllocator) AllocateNext() (int, error) {\n\toffset, ok, err := r.alloc.AllocateNext()\n\tif err != nil {\n\t\tr.metrics.incrementAllocationErrors(\"dynamic\")\n\t\treturn 0, err\n\t}\n\tif !ok {\n\t\tr.metrics.incrementAllocationErrors(\"dynamic\")\n\t\treturn 0, ErrFull\n\t}\n\n\t// update metrics\n\tr.metrics.incrementAllocations(\"dynamic\")\n\tr.metrics.setAllocated(r.Used())\n\tr.metrics.setAvailable(r.Free())\n\n\treturn r.portRange.Base + offset, nil\n}","line":{"from":161,"to":180}} {"id":100009854,"name":"ForEach","signature":"func (r *PortAllocator) ForEach(fn func(int))","file":"pkg/registry/core/service/portallocator/allocator.go","code":"// ForEach calls the provided function for each allocated port.\nfunc (r *PortAllocator) ForEach(fn func(int)) {\n\tr.alloc.ForEach(func(offset int) {\n\t\tfn(r.portRange.Base + offset)\n\t})\n}","line":{"from":182,"to":187}} {"id":100009855,"name":"Release","signature":"func (r *PortAllocator) Release(port int) error","file":"pkg/registry/core/service/portallocator/allocator.go","code":"// Release releases the port back to the pool. Releasing an\n// unallocated port or a port out of the range is a no-op and\n// returns no error.\nfunc (r *PortAllocator) Release(port int) error {\n\tok, offset := r.contains(port)\n\tif !ok {\n\t\tklog.Warningf(\"port is not in the range when release it. port: %v\", port)\n\t\treturn nil\n\t}\n\n\terr := r.alloc.Release(offset)\n\tif err == nil {\n\t\t// update metrics\n\t\tr.metrics.setAllocated(r.Used())\n\t\tr.metrics.setAvailable(r.Free())\n\t}\n\treturn err\n}","line":{"from":189,"to":206}} {"id":100009856,"name":"Has","signature":"func (r *PortAllocator) Has(port int) bool","file":"pkg/registry/core/service/portallocator/allocator.go","code":"// Has returns true if the provided port is already allocated and a call\n// to Allocate(port) would fail with ErrAllocated.\nfunc (r *PortAllocator) Has(port int) bool {\n\tok, offset := r.contains(port)\n\tif !ok {\n\t\treturn false\n\t}\n\n\treturn r.alloc.Has(offset)\n}","line":{"from":208,"to":217}} {"id":100009857,"name":"Snapshot","signature":"func (r *PortAllocator) Snapshot(dst *api.RangeAllocation) error","file":"pkg/registry/core/service/portallocator/allocator.go","code":"// Snapshot saves the current state of the pool.\nfunc (r *PortAllocator) Snapshot(dst *api.RangeAllocation) error {\n\tsnapshottable, ok := r.alloc.(allocator.Snapshottable)\n\tif !ok {\n\t\treturn fmt.Errorf(\"not a snapshottable allocator\")\n\t}\n\trangeString, data := snapshottable.Snapshot()\n\tdst.Range = rangeString\n\tdst.Data = data\n\treturn nil\n}","line":{"from":219,"to":229}} {"id":100009858,"name":"Restore","signature":"func (r *PortAllocator) Restore(pr net.PortRange, data []byte) error","file":"pkg/registry/core/service/portallocator/allocator.go","code":"// Restore restores the pool to the previously captured state. ErrMismatchedNetwork\n// is returned if the provided port range doesn't exactly match the previous range.\nfunc (r *PortAllocator) Restore(pr net.PortRange, data []byte) error {\n\tif pr.String() != r.portRange.String() {\n\t\treturn ErrMismatchedNetwork\n\t}\n\tsnapshottable, ok := r.alloc.(allocator.Snapshottable)\n\tif !ok {\n\t\treturn fmt.Errorf(\"not a snapshottable allocator\")\n\t}\n\treturn snapshottable.Restore(pr.String(), data)\n}","line":{"from":231,"to":242}} {"id":100009859,"name":"contains","signature":"func (r *PortAllocator) contains(port int) (bool, int)","file":"pkg/registry/core/service/portallocator/allocator.go","code":"// contains returns true and the offset if the port is in the range, and false\n// and nil otherwise.\nfunc (r *PortAllocator) contains(port int) (bool, int) {\n\tif !r.portRange.Contains(port) {\n\t\treturn false, 0\n\t}\n\n\toffset := port - r.portRange.Base\n\treturn true, offset\n}","line":{"from":244,"to":253}} {"id":100009860,"name":"Destroy","signature":"func (r *PortAllocator) Destroy()","file":"pkg/registry/core/service/portallocator/allocator.go","code":"// Destroy shuts down internal allocator.\nfunc (r *PortAllocator) Destroy() {\n\tr.alloc.Destroy()\n}","line":{"from":255,"to":258}} {"id":100009861,"name":"EnableMetrics","signature":"func (r *PortAllocator) EnableMetrics()","file":"pkg/registry/core/service/portallocator/allocator.go","code":"// EnableMetrics enables metrics recording.\nfunc (r *PortAllocator) EnableMetrics() {\n\tregisterMetrics()\n\tr.metrics = \u0026metricsRecorder{}\n}","line":{"from":260,"to":264}} {"id":100009862,"name":"calculateRangeOffset","signature":"func calculateRangeOffset(pr net.PortRange) int","file":"pkg/registry/core/service/portallocator/allocator.go","code":"// calculateRangeOffset estimates the offset used on the range for statically allocation based on\n// the following formula `min(max($min, rangeSize/$step), $max)`, described as ~never less than\n// $min or more than $max, with a graduated step function between them~. The function returns 0\n// if any of the parameters is invalid.\nfunc calculateRangeOffset(pr net.PortRange) int {\n\t// default values for min(max($min, rangeSize/$step), $max)\n\tconst (\n\t\tmin = 16\n\t\tmax = 128\n\t\tstep = 32\n\t)\n\n\trangeSize := pr.Size\n\t// offset should always be smaller than the range size\n\tif rangeSize \u003c= min {\n\t\treturn 0\n\t}\n\n\toffset := rangeSize / step\n\tif offset \u003c min {\n\t\treturn min\n\t}\n\tif offset \u003e max {\n\t\treturn max\n\t}\n\treturn int(offset)\n}","line":{"from":266,"to":292}} {"id":100009863,"name":"NewRepair","signature":"func NewRepair(interval time.Duration, serviceClient corev1client.ServicesGetter, eventClient eventsv1client.EventsV1Interface, portRange net.PortRange, alloc rangeallocation.RangeRegistry) *Repair","file":"pkg/registry/core/service/portallocator/controller/repair.go","code":"// NewRepair creates a controller that periodically ensures that all ports are uniquely allocated across the cluster\n// and generates informational warnings for a cluster that is not in sync.\nfunc NewRepair(interval time.Duration, serviceClient corev1client.ServicesGetter, eventClient eventsv1client.EventsV1Interface, portRange net.PortRange, alloc rangeallocation.RangeRegistry) *Repair {\n\teventBroadcaster := events.NewBroadcaster(\u0026events.EventSinkImpl{Interface: eventClient})\n\trecorder := eventBroadcaster.NewRecorder(legacyscheme.Scheme, \"portallocator-repair-controller\")\n\n\treturn \u0026Repair{\n\t\tinterval: interval,\n\t\tserviceClient: serviceClient,\n\t\tportRange: portRange,\n\t\talloc: alloc,\n\t\tleaks: map[int]int{},\n\t\tbroadcaster: eventBroadcaster,\n\t\trecorder: recorder,\n\t}\n}","line":{"from":58,"to":73}} {"id":100009864,"name":"RunUntil","signature":"func (c *Repair) RunUntil(onFirstSuccess func(), stopCh chan struct{})","file":"pkg/registry/core/service/portallocator/controller/repair.go","code":"// RunUntil starts the controller until the provided ch is closed.\nfunc (c *Repair) RunUntil(onFirstSuccess func(), stopCh chan struct{}) {\n\tc.broadcaster.StartRecordingToSink(stopCh)\n\tdefer c.broadcaster.Shutdown()\n\n\tvar once sync.Once\n\twait.Until(func() {\n\t\tif err := c.runOnce(); err != nil {\n\t\t\truntime.HandleError(err)\n\t\t\treturn\n\t\t}\n\t\tonce.Do(onFirstSuccess)\n\t}, c.interval, stopCh)\n}","line":{"from":75,"to":88}} {"id":100009865,"name":"runOnce","signature":"func (c *Repair) runOnce() error","file":"pkg/registry/core/service/portallocator/controller/repair.go","code":"// runOnce verifies the state of the port allocations and returns an error if an unrecoverable problem occurs.\nfunc (c *Repair) runOnce() error {\n\treturn retry.RetryOnConflict(retry.DefaultBackoff, c.doRunOnce)\n}","line":{"from":90,"to":93}} {"id":100009866,"name":"doRunOnce","signature":"func (c *Repair) doRunOnce() error","file":"pkg/registry/core/service/portallocator/controller/repair.go","code":"// doRunOnce verifies the state of the port allocations and returns an error if an unrecoverable problem occurs.\nfunc (c *Repair) doRunOnce() error {\n\t// TODO: (per smarterclayton) if Get() or ListServices() is a weak consistency read,\n\t// or if they are executed against different leaders,\n\t// the ordering guarantee required to ensure no port is allocated twice is violated.\n\t// ListServices must return a ResourceVersion higher than the etcd index Get triggers,\n\t// and the release code must not release services that have had ports allocated but not yet been created\n\t// See #8295\n\n\t// If etcd server is not running we should wait for some time and fail only then. This is particularly\n\t// important when we start apiserver and etcd at the same time.\n\tvar snapshot *api.RangeAllocation\n\n\terr := wait.PollImmediate(time.Second, 10*time.Second, func() (bool, error) {\n\t\tvar err error\n\t\tsnapshot, err = c.alloc.Get()\n\t\treturn err == nil, err\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to refresh the port allocations: %v\", err)\n\t}\n\t// If not yet initialized.\n\tif snapshot.Range == \"\" {\n\t\tsnapshot.Range = c.portRange.String()\n\t}\n\t// Create an allocator because it is easy to use.\n\tstored, err := portallocator.NewFromSnapshot(snapshot)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to rebuild allocator from snapshot: %v\", err)\n\t}\n\n\t// We explicitly send no resource version, since the resource version\n\t// of 'snapshot' is from a different collection, it's not comparable to\n\t// the service collection. The caching layer keeps per-collection RVs,\n\t// and this is proper, since in theory the collections could be hosted\n\t// in separate etcd (or even non-etcd) instances.\n\tlist, err := c.serviceClient.Services(metav1.NamespaceAll).List(context.TODO(), metav1.ListOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to refresh the port block: %v\", err)\n\t}\n\n\trebuilt, err := portallocator.NewInMemory(c.portRange)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to create port allocator: %v\", err)\n\t}\n\t// Check every Service's ports, and rebuild the state as we think it should be.\n\tfor i := range list.Items {\n\t\tsvc := \u0026list.Items[i]\n\t\tports := collectServiceNodePorts(svc)\n\t\tif len(ports) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, port := range ports {\n\t\t\tswitch err := rebuilt.Allocate(port); err {\n\t\t\tcase nil:\n\t\t\t\tif stored.Has(port) {\n\t\t\t\t\t// remove it from the old set, so we can find leaks\n\t\t\t\t\tstored.Release(port)\n\t\t\t\t} else {\n\t\t\t\t\t// doesn't seem to be allocated\n\t\t\t\t\tc.recorder.Eventf(svc, nil, corev1.EventTypeWarning, \"PortNotAllocated\", \"PortAllocation\", \"Port %d is not allocated; repairing\", port)\n\t\t\t\t\truntime.HandleError(fmt.Errorf(\"the node port %d for service %s/%s is not allocated; repairing\", port, svc.Name, svc.Namespace))\n\t\t\t\t}\n\t\t\t\tdelete(c.leaks, port) // it is used, so it can't be leaked\n\t\t\tcase portallocator.ErrAllocated:\n\t\t\t\t// port is duplicate, reallocate\n\t\t\t\tc.recorder.Eventf(svc, nil, corev1.EventTypeWarning, \"PortAlreadyAllocated\", \"PortAllocation\", \"Port %d was assigned to multiple services; please recreate service\", port)\n\t\t\t\truntime.HandleError(fmt.Errorf(\"the node port %d for service %s/%s was assigned to multiple services; please recreate\", port, svc.Name, svc.Namespace))\n\t\t\tcase err.(*portallocator.ErrNotInRange):\n\t\t\t\t// port is out of range, reallocate\n\t\t\t\tc.recorder.Eventf(svc, nil, corev1.EventTypeWarning, \"PortOutOfRange\", \"PortAllocation\", \"Port %d is not within the port range %s; please recreate service\", port, c.portRange)\n\t\t\t\truntime.HandleError(fmt.Errorf(\"the port %d for service %s/%s is not within the port range %s; please recreate\", port, svc.Name, svc.Namespace, c.portRange))\n\t\t\tcase portallocator.ErrFull:\n\t\t\t\t// somehow we are out of ports\n\t\t\t\tc.recorder.Eventf(svc, nil, corev1.EventTypeWarning, \"PortRangeFull\", \"PortAllocation\", \"Port range %s is full; you must widen the port range in order to create new services\", c.portRange)\n\t\t\t\treturn fmt.Errorf(\"the port range %s is full; you must widen the port range in order to create new services\", c.portRange)\n\t\t\tdefault:\n\t\t\t\tc.recorder.Eventf(svc, nil, corev1.EventTypeWarning, \"UnknownError\", \"PortAllocation\", \"Unable to allocate port %d due to an unknown error\", port)\n\t\t\t\treturn fmt.Errorf(\"unable to allocate port %d for service %s/%s due to an unknown error, exiting: %v\", port, svc.Name, svc.Namespace, err)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check for ports that are left in the old set. They appear to have been leaked.\n\tstored.ForEach(func(port int) {\n\t\tcount, found := c.leaks[port]\n\t\tswitch {\n\t\tcase !found:\n\t\t\t// flag it to be cleaned up after any races (hopefully) are gone\n\t\t\truntime.HandleError(fmt.Errorf(\"the node port %d may have leaked: flagging for later clean up\", port))\n\t\t\tcount = numRepairsBeforeLeakCleanup - 1\n\t\t\tfallthrough\n\t\tcase count \u003e 0:\n\t\t\t// pretend it is still in use until count expires\n\t\t\tc.leaks[port] = count - 1\n\t\t\tif err := rebuilt.Allocate(port); err != nil {\n\t\t\t\truntime.HandleError(fmt.Errorf(\"the node port %d may have leaked, but can not be allocated: %v\", port, err))\n\t\t\t}\n\t\tdefault:\n\t\t\t// do not add it to the rebuilt set, which means it will be available for reuse\n\t\t\truntime.HandleError(fmt.Errorf(\"the node port %d appears to have leaked: cleaning up\", port))\n\t\t}\n\t})\n\n\t// Blast the rebuilt state into storage.\n\tif err := rebuilt.Snapshot(snapshot); err != nil {\n\t\treturn fmt.Errorf(\"unable to snapshot the updated port allocations: %v\", err)\n\t}\n\n\tif err := c.alloc.CreateOrUpdate(snapshot); err != nil {\n\t\tif errors.IsConflict(err) {\n\t\t\treturn err\n\t\t}\n\t\treturn fmt.Errorf(\"unable to persist the updated port allocations: %v\", err)\n\t}\n\treturn nil\n}","line":{"from":95,"to":212}} {"id":100009867,"name":"collectServiceNodePorts","signature":"func collectServiceNodePorts(service *corev1.Service) []int","file":"pkg/registry/core/service/portallocator/controller/repair.go","code":"// collectServiceNodePorts returns nodePorts specified in the Service.\n// Please note that:\n// 1. same nodePort with *same* protocol will be duplicated as it is\n// 2. same nodePort with *different* protocol will be deduplicated\nfunc collectServiceNodePorts(service *corev1.Service) []int {\n\tvar servicePorts []int\n\t// map from nodePort to set of protocols\n\tseen := make(map[int]sets.String)\n\tfor _, port := range service.Spec.Ports {\n\t\tnodePort := int(port.NodePort)\n\t\tif nodePort == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tproto := string(port.Protocol)\n\t\ts := seen[nodePort]\n\t\tif s == nil { // have not seen this nodePort before\n\t\t\ts = sets.NewString(proto)\n\t\t\tservicePorts = append(servicePorts, nodePort)\n\t\t} else if s.Has(proto) { // same nodePort with same protocol\n\t\t\tservicePorts = append(servicePorts, nodePort)\n\t\t} else { // same nodePort with different protocol\n\t\t\ts.Insert(proto)\n\t\t}\n\t\tseen[nodePort] = s\n\t}\n\n\thealthPort := int(service.Spec.HealthCheckNodePort)\n\tif healthPort != 0 {\n\t\ts := seen[healthPort]\n\t\t// TODO: is it safe to assume the protocol is always TCP?\n\t\tif s == nil || s.Has(string(corev1.ProtocolTCP)) {\n\t\t\tservicePorts = append(servicePorts, healthPort)\n\t\t}\n\t}\n\n\treturn servicePorts\n}","line":{"from":214,"to":250}} {"id":100009868,"name":"registerMetrics","signature":"func registerMetrics()","file":"pkg/registry/core/service/portallocator/metrics.go","code":"func registerMetrics() {\n\tregisterMetricsOnce.Do(func() {\n\t\tlegacyregistry.MustRegister(nodePortAllocated)\n\t\tlegacyregistry.MustRegister(nodePortAvailable)\n\t\tlegacyregistry.MustRegister(nodePortAllocations)\n\t\tlegacyregistry.MustRegister(nodePortAllocationErrors)\n\t})\n}","line":{"from":78,"to":85}} {"id":100009869,"name":"setAllocated","signature":"func (m *metricsRecorder) setAllocated(allocated int)","file":"pkg/registry/core/service/portallocator/metrics.go","code":"func (m *metricsRecorder) setAllocated(allocated int) {\n\tnodePortAllocated.Set(float64(allocated))\n}","line":{"from":98,"to":100}} {"id":100009870,"name":"setAvailable","signature":"func (m *metricsRecorder) setAvailable(available int)","file":"pkg/registry/core/service/portallocator/metrics.go","code":"func (m *metricsRecorder) setAvailable(available int) {\n\tnodePortAvailable.Set(float64(available))\n}","line":{"from":102,"to":104}} {"id":100009871,"name":"incrementAllocations","signature":"func (m *metricsRecorder) incrementAllocations(scope string)","file":"pkg/registry/core/service/portallocator/metrics.go","code":"func (m *metricsRecorder) incrementAllocations(scope string) {\n\tnodePortAllocations.WithLabelValues(scope).Inc()\n}","line":{"from":106,"to":108}} {"id":100009872,"name":"incrementAllocationErrors","signature":"func (m *metricsRecorder) incrementAllocationErrors(scope string)","file":"pkg/registry/core/service/portallocator/metrics.go","code":"func (m *metricsRecorder) incrementAllocationErrors(scope string) {\n\tnodePortAllocationErrors.WithLabelValues(scope).Inc()\n}","line":{"from":110,"to":112}} {"id":100009873,"name":"setAllocated","signature":"func (*emptyMetricsRecorder) setAllocated(allocated int) {}","file":"pkg/registry/core/service/portallocator/metrics.go","code":"func (*emptyMetricsRecorder) setAllocated(allocated int) {}","line":{"from":117,"to":117}} {"id":100009874,"name":"setAvailable","signature":"func (*emptyMetricsRecorder) setAvailable(available int) {}","file":"pkg/registry/core/service/portallocator/metrics.go","code":"func (*emptyMetricsRecorder) setAvailable(available int) {}","line":{"from":118,"to":118}} {"id":100009875,"name":"incrementAllocations","signature":"func (*emptyMetricsRecorder) incrementAllocations(scope string) {}","file":"pkg/registry/core/service/portallocator/metrics.go","code":"func (*emptyMetricsRecorder) incrementAllocations(scope string) {}","line":{"from":119,"to":119}} {"id":100009876,"name":"incrementAllocationErrors","signature":"func (*emptyMetricsRecorder) incrementAllocationErrors(scope string) {}","file":"pkg/registry/core/service/portallocator/metrics.go","code":"func (*emptyMetricsRecorder) incrementAllocationErrors(scope string) {}","line":{"from":120,"to":120}} {"id":100009877,"name":"StartOperation","signature":"func StartOperation(pa Interface, dryRun bool) *PortAllocationOperation","file":"pkg/registry/core/service/portallocator/operation.go","code":"// Creates a portAllocationOperation, tracking a set of allocations \u0026 releases\n// If dryRun is specified, never actually allocate or release anything\nfunc StartOperation(pa Interface, dryRun bool) *PortAllocationOperation {\n\top := \u0026PortAllocationOperation{}\n\top.pa = pa\n\top.allocated = []int{}\n\top.releaseDeferred = []int{}\n\top.shouldRollback = true\n\top.dryRun = dryRun\n\treturn op\n}","line":{"from":41,"to":51}} {"id":100009878,"name":"Finish","signature":"func (op *PortAllocationOperation) Finish()","file":"pkg/registry/core/service/portallocator/operation.go","code":"// Will rollback unless marked as shouldRollback = false by a Commit(). Call from a defer block\nfunc (op *PortAllocationOperation) Finish() {\n\tif op.shouldRollback {\n\t\top.Rollback()\n\t}\n}","line":{"from":53,"to":58}} {"id":100009879,"name":"Rollback","signature":"func (op *PortAllocationOperation) Rollback() []error","file":"pkg/registry/core/service/portallocator/operation.go","code":"// (Try to) undo any operations we did\nfunc (op *PortAllocationOperation) Rollback() []error {\n\tif op.dryRun {\n\t\treturn nil\n\t}\n\n\terrors := []error{}\n\n\tfor _, allocated := range op.allocated {\n\t\terr := op.pa.Release(allocated)\n\t\tif err != nil {\n\t\t\terrors = append(errors, err)\n\t\t}\n\t}\n\n\tif len(errors) == 0 {\n\t\treturn nil\n\t}\n\treturn errors\n}","line":{"from":60,"to":79}} {"id":100009880,"name":"Commit","signature":"func (op *PortAllocationOperation) Commit() []error","file":"pkg/registry/core/service/portallocator/operation.go","code":"// (Try to) perform any deferred operations.\n// Note that even if this fails, we don't rollback; we always want to err on the side of over-allocation,\n// and Commit should be called _after_ the owner is written\nfunc (op *PortAllocationOperation) Commit() []error {\n\tif op.dryRun {\n\t\treturn nil\n\t}\n\n\terrors := []error{}\n\n\tfor _, release := range op.releaseDeferred {\n\t\terr := op.pa.Release(release)\n\t\tif err != nil {\n\t\t\terrors = append(errors, err)\n\t\t}\n\t}\n\n\t// Even on error, we don't rollback\n\t// Problems should be fixed by an eventual reconciliation / restart\n\top.shouldRollback = false\n\n\tif len(errors) == 0 {\n\t\treturn nil\n\t}\n\n\treturn errors\n}","line":{"from":81,"to":107}} {"id":100009881,"name":"Allocate","signature":"func (op *PortAllocationOperation) Allocate(port int) error","file":"pkg/registry/core/service/portallocator/operation.go","code":"// Allocates a port, and record it for future rollback\nfunc (op *PortAllocationOperation) Allocate(port int) error {\n\tif op.dryRun {\n\t\tif op.pa.Has(port) {\n\t\t\treturn ErrAllocated\n\t\t}\n\t\tfor _, a := range op.allocated {\n\t\t\tif port == a {\n\t\t\t\treturn ErrAllocated\n\t\t\t}\n\t\t}\n\t\top.allocated = append(op.allocated, port)\n\t\treturn nil\n\t}\n\n\terr := op.pa.Allocate(port)\n\tif err == nil {\n\t\top.allocated = append(op.allocated, port)\n\t}\n\treturn err\n}","line":{"from":109,"to":129}} {"id":100009882,"name":"AllocateNext","signature":"func (op *PortAllocationOperation) AllocateNext() (int, error)","file":"pkg/registry/core/service/portallocator/operation.go","code":"// Allocates a port, and record it for future rollback\nfunc (op *PortAllocationOperation) AllocateNext() (int, error) {\n\tif op.dryRun {\n\t\t// Find the max element of the allocated ports array.\n\t\t// If no ports are already being allocated by this operation,\n\t\t// then choose a sensible guess for a dummy port number\n\t\tvar lastPort int\n\t\tfor _, allocatedPort := range op.allocated {\n\t\t\tif allocatedPort \u003e lastPort {\n\t\t\t\tlastPort = allocatedPort\n\t\t\t}\n\t\t}\n\t\tif len(op.allocated) == 0 {\n\t\t\tlastPort = 32768\n\t\t}\n\n\t\t// Try to find the next non allocated port.\n\t\t// If too many ports are full, just reuse one,\n\t\t// since this is just a dummy value.\n\t\tfor port := lastPort + 1; port \u003c 100; port++ {\n\t\t\terr := op.Allocate(port)\n\t\t\tif err == nil {\n\t\t\t\treturn port, nil\n\t\t\t}\n\t\t}\n\t\top.allocated = append(op.allocated, lastPort+1)\n\t\treturn lastPort + 1, nil\n\t}\n\n\tport, err := op.pa.AllocateNext()\n\tif err == nil {\n\t\top.allocated = append(op.allocated, port)\n\t}\n\treturn port, err\n}","line":{"from":131,"to":165}} {"id":100009883,"name":"ReleaseDeferred","signature":"func (op *PortAllocationOperation) ReleaseDeferred(port int)","file":"pkg/registry/core/service/portallocator/operation.go","code":"// Marks a port so that it will be released if this operation Commits\nfunc (op *PortAllocationOperation) ReleaseDeferred(port int) {\n\top.releaseDeferred = append(op.releaseDeferred, port)\n}","line":{"from":167,"to":170}} {"id":100009884,"name":"New","signature":"func (r *ProxyREST) New() runtime.Object","file":"pkg/registry/core/service/proxy.go","code":"// New returns an empty service resource\nfunc (r *ProxyREST) New() runtime.Object {\n\treturn \u0026api.ServiceProxyOptions{}\n}","line":{"from":44,"to":47}} {"id":100009885,"name":"Destroy","signature":"func (r *ProxyREST) Destroy()","file":"pkg/registry/core/service/proxy.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *ProxyREST) Destroy() {\n\t// Given no underlying store, we don't destroy anything\n\t// here explicitly.\n}","line":{"from":49,"to":53}} {"id":100009886,"name":"ConnectMethods","signature":"func (r *ProxyREST) ConnectMethods() []string","file":"pkg/registry/core/service/proxy.go","code":"// ConnectMethods returns the list of HTTP methods that can be proxied\nfunc (r *ProxyREST) ConnectMethods() []string {\n\treturn proxyMethods\n}","line":{"from":55,"to":58}} {"id":100009887,"name":"NewConnectOptions","signature":"func (r *ProxyREST) NewConnectOptions() (runtime.Object, bool, string)","file":"pkg/registry/core/service/proxy.go","code":"// NewConnectOptions returns versioned resource that represents proxy parameters\nfunc (r *ProxyREST) NewConnectOptions() (runtime.Object, bool, string) {\n\treturn \u0026api.ServiceProxyOptions{}, true, \"path\"\n}","line":{"from":60,"to":63}} {"id":100009888,"name":"Connect","signature":"func (r *ProxyREST) Connect(ctx context.Context, id string, opts runtime.Object, responder rest.Responder) (http.Handler, error)","file":"pkg/registry/core/service/proxy.go","code":"// Connect returns a handler for the service proxy\nfunc (r *ProxyREST) Connect(ctx context.Context, id string, opts runtime.Object, responder rest.Responder) (http.Handler, error) {\n\tproxyOpts, ok := opts.(*api.ServiceProxyOptions)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Invalid options object: %#v\", opts)\n\t}\n\tlocation, transport, err := r.Redirector.ResourceLocation(ctx, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlocation.Path = net.JoinPreservingTrailingSlash(location.Path, proxyOpts.Path)\n\t// Return a proxy handler that uses the desired transport, wrapped with additional proxy handling (to get URL rewriting, X-Forwarded-* headers, etc)\n\treturn newThrottledUpgradeAwareProxyHandler(location, transport, true, false, responder), nil\n}","line":{"from":65,"to":78}} {"id":100009889,"name":"newThrottledUpgradeAwareProxyHandler","signature":"func newThrottledUpgradeAwareProxyHandler(location *url.URL, transport http.RoundTripper, wrapTransport, upgradeRequired bool, responder rest.Responder) *proxy.UpgradeAwareHandler","file":"pkg/registry/core/service/proxy.go","code":"func newThrottledUpgradeAwareProxyHandler(location *url.URL, transport http.RoundTripper, wrapTransport, upgradeRequired bool, responder rest.Responder) *proxy.UpgradeAwareHandler {\n\thandler := proxy.NewUpgradeAwareHandler(location, transport, wrapTransport, upgradeRequired, proxy.NewErrorResponder(responder))\n\thandler.MaxBytesPerSec = capabilities.Get().PerConnectionBandwidthLimitBytesPerSec\n\treturn handler\n}","line":{"from":80,"to":84}} {"id":100009890,"name":"makeAlloc","signature":"func makeAlloc(defaultFamily api.IPFamily, ipAllocs map[api.IPFamily]ipallocator.Interface, portAlloc portallocator.Interface) Allocators","file":"pkg/registry/core/service/storage/alloc.go","code":"// This is a trasitionary function to facilitate service REST flattening.\nfunc makeAlloc(defaultFamily api.IPFamily, ipAllocs map[api.IPFamily]ipallocator.Interface, portAlloc portallocator.Interface) Allocators {\n\treturn Allocators{\n\t\tdefaultServiceIPFamily: defaultFamily,\n\t\tserviceIPAllocatorsByFamily: ipAllocs,\n\t\tserviceNodePorts: portAlloc,\n\t}\n}","line":{"from":55,"to":62}} {"id":100009891,"name":"allocateCreate","signature":"func (al *Allocators) allocateCreate(service *api.Service, dryRun bool) (transaction, error)","file":"pkg/registry/core/service/storage/alloc.go","code":"func (al *Allocators) allocateCreate(service *api.Service, dryRun bool) (transaction, error) {\n\tresult := metaTransaction{}\n\tsuccess := false\n\n\tdefer func() {\n\t\tif !success {\n\t\t\tresult.Revert()\n\t\t}\n\t}()\n\n\t// Ensure IP family fields are correctly initialized. We do it here, since\n\t// we want this to be visible even when dryRun == true.\n\tif err := al.initIPFamilyFields(After{service}, Before{nil}); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Allocate ClusterIPs\n\t//TODO(thockin): validation should not pass with empty clusterIP, but it\n\t//does (and is tested!). Fixing that all is a big PR and will have to\n\t//happen later.\n\tif txn, err := al.txnAllocClusterIPs(service, dryRun); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tresult = append(result, txn)\n\t}\n\n\t// Allocate ports\n\tif txn, err := al.txnAllocNodePorts(service, dryRun); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tresult = append(result, txn)\n\t}\n\n\tsuccess = true\n\treturn result, nil\n}","line":{"from":64,"to":99}} {"id":100009892,"name":"initIPFamilyFields","signature":"func (al *Allocators) initIPFamilyFields(after After, before Before) error","file":"pkg/registry/core/service/storage/alloc.go","code":"// attempts to default service ip families according to cluster configuration\n// while ensuring that provided families are configured on cluster.\nfunc (al *Allocators) initIPFamilyFields(after After, before Before) error {\n\toldService, service := before.Service, after.Service\n\n\t// can not do anything here\n\tif service.Spec.Type == api.ServiceTypeExternalName {\n\t\treturn nil\n\t}\n\n\t// We don't want to auto-upgrade (add an IP) or downgrade (remove an IP)\n\t// PreferDualStack services following a cluster change to/from\n\t// dual-stackness.\n\t//\n\t// That means a PreferDualStack service will only be upgraded/downgraded\n\t// when:\n\t// - changing ipFamilyPolicy to \"RequireDualStack\" or \"SingleStack\" AND\n\t// - adding or removing a secondary clusterIP or ipFamily\n\tif isMatchingPreferDualStackClusterIPFields(after, before) {\n\t\treturn nil // nothing more to do.\n\t}\n\n\t// If the user didn't specify ipFamilyPolicy, we can infer a default. We\n\t// don't want a static default because we want to make sure that we never\n\t// change between single- and dual-stack modes with explicit direction, as\n\t// provided by ipFamilyPolicy. Consider these cases:\n\t// * Create (POST): If they didn't specify a policy we can assume it's\n\t// always SingleStack.\n\t// * Update (PUT): If they didn't specify a policy we need to adopt the\n\t// policy from before. This is better than always assuming SingleStack\n\t// because a PUT that changes clusterIPs from 2 to 1 value but doesn't\n\t// specify ipFamily would work.\n\t// * Update (PATCH): If they didn't specify a policy it will adopt the\n\t// policy from before.\n\tif service.Spec.IPFamilyPolicy == nil {\n\t\tif oldService != nil \u0026\u0026 oldService.Spec.IPFamilyPolicy != nil {\n\t\t\t// Update from an object with policy, use the old policy\n\t\t\tservice.Spec.IPFamilyPolicy = oldService.Spec.IPFamilyPolicy\n\t\t} else if service.Spec.ClusterIP == api.ClusterIPNone \u0026\u0026 len(service.Spec.Selector) == 0 {\n\t\t\t// Special-case: headless + selectorless defaults to dual.\n\t\t\trequireDualStack := api.IPFamilyPolicyRequireDualStack\n\t\t\tservice.Spec.IPFamilyPolicy = \u0026requireDualStack\n\t\t} else {\n\t\t\t// create or update from an object without policy (e.g.\n\t\t\t// ExternalName) to one that needs policy\n\t\t\tsingleStack := api.IPFamilyPolicySingleStack\n\t\t\tservice.Spec.IPFamilyPolicy = \u0026singleStack\n\t\t}\n\t}\n\t// Henceforth we can assume ipFamilyPolicy is set.\n\n\t// Do some loose pre-validation of the input. This makes it easier in the\n\t// rest of allocation code to not have to consider corner cases.\n\t// TODO(thockin): when we tighten validation (e.g. to require IPs) we will\n\t// need a \"strict\" and a \"loose\" form of this.\n\tif el := validation.ValidateServiceClusterIPsRelatedFields(service); len(el) != 0 {\n\t\treturn errors.NewInvalid(api.Kind(\"Service\"), service.Name, el)\n\t}\n\n\t//TODO(thockin): Move this logic to validation?\n\tel := make(field.ErrorList, 0)\n\n\t// Update-only prep work.\n\tif oldService != nil {\n\t\tif getIPFamilyPolicy(service) == api.IPFamilyPolicySingleStack {\n\t\t\t// As long as ClusterIPs and IPFamilies have not changed, setting\n\t\t\t// the policy to single-stack is clear intent.\n\t\t\t// ClusterIPs[0] is immutable, so it is safe to keep.\n\t\t\tif sameClusterIPs(oldService, service) \u0026\u0026 len(service.Spec.ClusterIPs) \u003e 1 {\n\t\t\t\tservice.Spec.ClusterIPs = service.Spec.ClusterIPs[0:1]\n\t\t\t}\n\t\t\tif sameIPFamilies(oldService, service) \u0026\u0026 len(service.Spec.IPFamilies) \u003e 1 {\n\t\t\t\tservice.Spec.IPFamilies = service.Spec.IPFamilies[0:1]\n\t\t\t}\n\t\t} else {\n\t\t\t// If the policy is anything but single-stack AND they reduced these\n\t\t\t// fields, it's an error. They need to specify policy.\n\t\t\tif reducedClusterIPs(After{service}, Before{oldService}) {\n\t\t\t\tel = append(el, field.Invalid(field.NewPath(\"spec\", \"ipFamilyPolicy\"), service.Spec.IPFamilyPolicy,\n\t\t\t\t\t\"must be 'SingleStack' to release the secondary cluster IP\"))\n\t\t\t}\n\t\t\tif reducedIPFamilies(After{service}, Before{oldService}) {\n\t\t\t\tel = append(el, field.Invalid(field.NewPath(\"spec\", \"ipFamilyPolicy\"), service.Spec.IPFamilyPolicy,\n\t\t\t\t\t\"must be 'SingleStack' to release the secondary IP family\"))\n\t\t\t}\n\t\t}\n\t}\n\n\t// Make sure ipFamilyPolicy makes sense for the provided ipFamilies and\n\t// clusterIPs. Further checks happen below - after the special cases.\n\tif getIPFamilyPolicy(service) == api.IPFamilyPolicySingleStack {\n\t\tif len(service.Spec.ClusterIPs) == 2 {\n\t\t\tel = append(el, field.Invalid(field.NewPath(\"spec\", \"ipFamilyPolicy\"), service.Spec.IPFamilyPolicy,\n\t\t\t\t\"must be 'RequireDualStack' or 'PreferDualStack' when multiple cluster IPs are specified\"))\n\t\t}\n\t\tif len(service.Spec.IPFamilies) == 2 {\n\t\t\tel = append(el, field.Invalid(field.NewPath(\"spec\", \"ipFamilyPolicy\"), service.Spec.IPFamilyPolicy,\n\t\t\t\t\"must be 'RequireDualStack' or 'PreferDualStack' when multiple IP families are specified\"))\n\t\t}\n\t}\n\n\t// Infer IPFamilies[] from ClusterIPs[]. Further checks happen below,\n\t// after the special cases.\n\tfor i, ip := range service.Spec.ClusterIPs {\n\t\tif ip == api.ClusterIPNone {\n\t\t\tbreak\n\t\t}\n\n\t\t// We previously validated that IPs are well-formed and that if an\n\t\t// ipFamilies[] entry exists it matches the IP.\n\t\tfam := familyOf(ip)\n\n\t\t// If the corresponding family is not specified, add it.\n\t\tif i \u003e= len(service.Spec.IPFamilies) {\n\t\t\t// Families are checked more later, but this is a better error in\n\t\t\t// this specific case (indicating the user-provided IP, rather\n\t\t\t// than than the auto-assigned family).\n\t\t\tif _, found := al.serviceIPAllocatorsByFamily[fam]; !found {\n\t\t\t\tel = append(el, field.Invalid(field.NewPath(\"spec\", \"clusterIPs\").Index(i), service.Spec.ClusterIPs,\n\t\t\t\t\tfmt.Sprintf(\"%s is not configured on this cluster\", fam)))\n\t\t\t} else {\n\t\t\t\t// OK to infer.\n\t\t\t\tservice.Spec.IPFamilies = append(service.Spec.IPFamilies, fam)\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we have validation errors, bail out now so we don't make them worse.\n\tif len(el) \u003e 0 {\n\t\treturn errors.NewInvalid(api.Kind(\"Service\"), service.Name, el)\n\t}\n\n\t// Special-case: headless + selectorless. This has to happen before other\n\t// checks because it explicitly allows combinations of inputs that would\n\t// otherwise be errors.\n\tif service.Spec.ClusterIP == api.ClusterIPNone \u0026\u0026 len(service.Spec.Selector) == 0 {\n\t\t// If IPFamilies was not set by the user, start with the default\n\t\t// family.\n\t\tif len(service.Spec.IPFamilies) == 0 {\n\t\t\tservice.Spec.IPFamilies = []api.IPFamily{al.defaultServiceIPFamily}\n\t\t}\n\n\t\t// this follows headful services. With one exception on a single stack\n\t\t// cluster the user is allowed to create headless services that has multi families\n\t\t// the validation allows it\n\t\tif len(service.Spec.IPFamilies) \u003c 2 {\n\t\t\tif *(service.Spec.IPFamilyPolicy) != api.IPFamilyPolicySingleStack {\n\t\t\t\t// add the alt ipfamily\n\t\t\t\tif service.Spec.IPFamilies[0] == api.IPv4Protocol {\n\t\t\t\t\tservice.Spec.IPFamilies = append(service.Spec.IPFamilies, api.IPv6Protocol)\n\t\t\t\t} else {\n\t\t\t\t\tservice.Spec.IPFamilies = append(service.Spec.IPFamilies, api.IPv4Protocol)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// nothing more needed here\n\t\treturn nil\n\t}\n\n\t//\n\t// Everything below this MUST happen *after* the above special cases.\n\t//\n\n\t// Demanding dual-stack on a non dual-stack cluster.\n\tif getIPFamilyPolicy(service) == api.IPFamilyPolicyRequireDualStack {\n\t\tif len(al.serviceIPAllocatorsByFamily) \u003c 2 {\n\t\t\tel = append(el, field.Invalid(field.NewPath(\"spec\", \"ipFamilyPolicy\"), service.Spec.IPFamilyPolicy,\n\t\t\t\t\"this cluster is not configured for dual-stack services\"))\n\t\t}\n\t}\n\n\t// If there is a family requested then it has to be configured on cluster.\n\tfor i, ipFamily := range service.Spec.IPFamilies {\n\t\tif _, found := al.serviceIPAllocatorsByFamily[ipFamily]; !found {\n\t\t\tel = append(el, field.Invalid(field.NewPath(\"spec\", \"ipFamilies\").Index(i), ipFamily, \"not configured on this cluster\"))\n\t\t}\n\t}\n\n\t// If we have validation errors, don't bother with the rest.\n\tif len(el) \u003e 0 {\n\t\treturn errors.NewInvalid(api.Kind(\"Service\"), service.Name, el)\n\t}\n\n\t// nil families, gets cluster default\n\tif len(service.Spec.IPFamilies) == 0 {\n\t\tservice.Spec.IPFamilies = []api.IPFamily{al.defaultServiceIPFamily}\n\t}\n\n\t// If this service is looking for dual-stack and this cluster does have two\n\t// families, append the missing family.\n\tif *(service.Spec.IPFamilyPolicy) != api.IPFamilyPolicySingleStack \u0026\u0026\n\t\tlen(service.Spec.IPFamilies) == 1 \u0026\u0026\n\t\tlen(al.serviceIPAllocatorsByFamily) == 2 {\n\n\t\tif service.Spec.IPFamilies[0] == api.IPv4Protocol {\n\t\t\tservice.Spec.IPFamilies = append(service.Spec.IPFamilies, api.IPv6Protocol)\n\t\t} else if service.Spec.IPFamilies[0] == api.IPv6Protocol {\n\t\t\tservice.Spec.IPFamilies = append(service.Spec.IPFamilies, api.IPv4Protocol)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":101,"to":304}} {"id":100009893,"name":"txnAllocClusterIPs","signature":"func (al *Allocators) txnAllocClusterIPs(service *api.Service, dryRun bool) (transaction, error)","file":"pkg/registry/core/service/storage/alloc.go","code":"func (al *Allocators) txnAllocClusterIPs(service *api.Service, dryRun bool) (transaction, error) {\n\t// clusterIPs that were allocated may need to be released in case of\n\t// failure at a higher level.\n\tallocated, err := al.allocClusterIPs(service, dryRun)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttxn := callbackTransaction{\n\t\trevert: func() {\n\t\t\tif dryRun {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tactuallyReleased, err := al.releaseIPs(allocated)\n\t\t\tif err != nil {\n\t\t\t\tklog.ErrorS(err, \"failed to clean up after failed service create\",\n\t\t\t\t\t\"service\", klog.KObj(service),\n\t\t\t\t\t\"shouldRelease\", allocated,\n\t\t\t\t\t\"released\", actuallyReleased)\n\t\t\t}\n\t\t},\n\t\tcommit: func() {\n\t\t\tif !dryRun {\n\t\t\t\tif len(allocated) \u003e 0 {\n\t\t\t\t\tklog.InfoS(\"allocated clusterIPs\",\n\t\t\t\t\t\t\"service\", klog.KObj(service),\n\t\t\t\t\t\t\"clusterIPs\", allocated)\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t}\n\treturn txn, nil\n}","line":{"from":306,"to":338}} {"id":100009894,"name":"allocClusterIPs","signature":"func (al *Allocators) allocClusterIPs(service *api.Service, dryRun bool) (map[api.IPFamily]string, error)","file":"pkg/registry/core/service/storage/alloc.go","code":"// allocates ClusterIPs for a service\nfunc (al *Allocators) allocClusterIPs(service *api.Service, dryRun bool) (map[api.IPFamily]string, error) {\n\t// external name don't get ClusterIPs\n\tif service.Spec.Type == api.ServiceTypeExternalName {\n\t\treturn nil, nil\n\t}\n\n\t// headless don't get ClusterIPs\n\tif len(service.Spec.ClusterIPs) \u003e 0 \u0026\u0026 service.Spec.ClusterIPs[0] == api.ClusterIPNone {\n\t\treturn nil, nil\n\t}\n\n\ttoAlloc := make(map[api.IPFamily]string)\n\t// at this stage, the only fact we know is that service has correct ip families\n\t// assigned to it. It may have partial assigned ClusterIPs (Upgrade to dual stack)\n\t// may have no ips at all. The below loop is meant to fix this\n\t// (we also know that this cluster has these families)\n\n\t// if there is no slice to work with\n\tif service.Spec.ClusterIPs == nil {\n\t\tservice.Spec.ClusterIPs = make([]string, 0, len(service.Spec.IPFamilies))\n\t}\n\n\tfor i, ipFamily := range service.Spec.IPFamilies {\n\t\tif i \u003e (len(service.Spec.ClusterIPs) - 1) {\n\t\t\tservice.Spec.ClusterIPs = append(service.Spec.ClusterIPs, \"\" /* just a marker */)\n\t\t}\n\n\t\ttoAlloc[ipFamily] = service.Spec.ClusterIPs[i]\n\t}\n\n\t// allocate\n\tallocated, err := al.allocIPs(service, toAlloc, dryRun)\n\n\t// set if successful\n\tif err == nil {\n\t\tfor family, ip := range allocated {\n\t\t\tfor i, check := range service.Spec.IPFamilies {\n\t\t\t\tif family == check {\n\t\t\t\t\tservice.Spec.ClusterIPs[i] = ip\n\t\t\t\t\t// while we technically don't need to do that testing rest does not\n\t\t\t\t\t// go through conversion logic but goes through validation *sigh*.\n\t\t\t\t\t// so we set ClusterIP here as well\n\t\t\t\t\t// because the testing code expects valid (as they are output-ed from conversion)\n\t\t\t\t\t// as it patches fields\n\t\t\t\t\tif i == 0 {\n\t\t\t\t\t\tservice.Spec.ClusterIP = ip\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allocated, err\n}","line":{"from":340,"to":394}} {"id":100009895,"name":"allocIPs","signature":"func (al *Allocators) allocIPs(service *api.Service, toAlloc map[api.IPFamily]string, dryRun bool) (map[api.IPFamily]string, error)","file":"pkg/registry/core/service/storage/alloc.go","code":"func (al *Allocators) allocIPs(service *api.Service, toAlloc map[api.IPFamily]string, dryRun bool) (map[api.IPFamily]string, error) {\n\tallocated := make(map[api.IPFamily]string)\n\n\tfor family, ip := range toAlloc {\n\t\tallocator := al.serviceIPAllocatorsByFamily[family] // should always be there, as we pre validate\n\t\tif dryRun {\n\t\t\tallocator = allocator.DryRun()\n\t\t}\n\t\tif ip == \"\" {\n\t\t\tvar allocatedIP net.IP\n\t\t\tvar err error\n\t\t\tif utilfeature.DefaultFeatureGate.Enabled(features.MultiCIDRServiceAllocator) {\n\t\t\t\tsvcAllocator, ok := allocator.(*ipallocator.Allocator)\n\t\t\t\tif ok {\n\t\t\t\t\tallocatedIP, err = svcAllocator.AllocateNextService(service)\n\t\t\t\t} else {\n\t\t\t\t\tallocatedIP, err = allocator.AllocateNext()\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tallocatedIP, err = allocator.AllocateNext()\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn allocated, errors.NewInternalError(fmt.Errorf(\"failed to allocate a serviceIP: %v\", err))\n\t\t\t}\n\t\t\tallocated[family] = allocatedIP.String()\n\t\t} else {\n\t\t\tparsedIP := netutils.ParseIPSloppy(ip)\n\t\t\tif parsedIP == nil {\n\t\t\t\treturn allocated, errors.NewInternalError(fmt.Errorf(\"failed to parse service IP %q\", ip))\n\t\t\t}\n\t\t\tvar err error\n\t\t\tif utilfeature.DefaultFeatureGate.Enabled(features.MultiCIDRServiceAllocator) {\n\t\t\t\tsvcAllocator, ok := allocator.(*ipallocator.Allocator)\n\t\t\t\tif ok {\n\t\t\t\t\terr = svcAllocator.AllocateService(service, parsedIP)\n\t\t\t\t} else {\n\t\t\t\t\terr = allocator.Allocate(parsedIP)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terr = allocator.Allocate(parsedIP)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tel := field.ErrorList{field.Invalid(field.NewPath(\"spec\", \"clusterIPs\"), service.Spec.ClusterIPs, fmt.Sprintf(\"failed to allocate IP %v: %v\", ip, err))}\n\t\t\t\treturn allocated, errors.NewInvalid(api.Kind(\"Service\"), service.Name, el)\n\t\t\t}\n\t\t\tallocated[family] = ip\n\t\t}\n\t}\n\treturn allocated, nil\n}","line":{"from":396,"to":445}} {"id":100009896,"name":"releaseIPs","signature":"func (al *Allocators) releaseIPs(toRelease map[api.IPFamily]string) (map[api.IPFamily]string, error)","file":"pkg/registry/core/service/storage/alloc.go","code":"// releases clusterIPs per family\nfunc (al *Allocators) releaseIPs(toRelease map[api.IPFamily]string) (map[api.IPFamily]string, error) {\n\tif toRelease == nil {\n\t\treturn nil, nil\n\t}\n\n\treleased := make(map[api.IPFamily]string)\n\tfor family, ip := range toRelease {\n\t\tallocator, ok := al.serviceIPAllocatorsByFamily[family]\n\t\tif !ok {\n\t\t\t// Maybe the cluster was previously configured for dual-stack,\n\t\t\t// then switched to single-stack?\n\t\t\tklog.InfoS(\"Not releasing ClusterIP because related family is not enabled\", \"clusterIP\", ip, \"family\", family)\n\t\t\tcontinue\n\t\t}\n\n\t\tparsedIP := netutils.ParseIPSloppy(ip)\n\t\tif parsedIP == nil {\n\t\t\treturn released, errors.NewInternalError(fmt.Errorf(\"failed to parse service IP %q\", ip))\n\t\t}\n\t\tif err := allocator.Release(parsedIP); err != nil {\n\t\t\treturn released, err\n\t\t}\n\t\treleased[family] = ip\n\t}\n\n\treturn released, nil\n}","line":{"from":447,"to":474}} {"id":100009897,"name":"txnAllocNodePorts","signature":"func (al *Allocators) txnAllocNodePorts(service *api.Service, dryRun bool) (transaction, error)","file":"pkg/registry/core/service/storage/alloc.go","code":"func (al *Allocators) txnAllocNodePorts(service *api.Service, dryRun bool) (transaction, error) {\n\t// The allocator tracks dry-run-ness internally.\n\tnodePortOp := portallocator.StartOperation(al.serviceNodePorts, dryRun)\n\n\ttxn := callbackTransaction{\n\t\tcommit: func() {\n\t\t\tnodePortOp.Commit()\n\t\t\t// We don't NEED to call Finish() here, but for that package says\n\t\t\t// to, so for future-safety, we will.\n\t\t\tnodePortOp.Finish()\n\t\t},\n\t\trevert: func() {\n\t\t\t// Weirdly named but this will revert if commit wasn't called\n\t\t\tnodePortOp.Finish()\n\t\t},\n\t}\n\n\t// Allocate NodePorts, if needed.\n\tif service.Spec.Type == api.ServiceTypeNodePort || service.Spec.Type == api.ServiceTypeLoadBalancer {\n\t\tif err := initNodePorts(service, nodePortOp); err != nil {\n\t\t\ttxn.Revert()\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Handle ExternalTraffic related fields during service creation.\n\tif apiservice.NeedsHealthCheck(service) {\n\t\tif err := al.allocHealthCheckNodePort(service, nodePortOp); err != nil {\n\t\t\ttxn.Revert()\n\t\t\treturn nil, errors.NewInternalError(err)\n\t\t}\n\t}\n\n\treturn txn, nil\n}","line":{"from":476,"to":510}} {"id":100009898,"name":"initNodePorts","signature":"func initNodePorts(service *api.Service, nodePortOp *portallocator.PortAllocationOperation) error","file":"pkg/registry/core/service/storage/alloc.go","code":"func initNodePorts(service *api.Service, nodePortOp *portallocator.PortAllocationOperation) error {\n\tsvcPortToNodePort := map[int]int{}\n\tfor i := range service.Spec.Ports {\n\t\tservicePort := \u0026service.Spec.Ports[i]\n\t\tif servicePort.NodePort == 0 \u0026\u0026 !shouldAllocateNodePorts(service) {\n\t\t\t// Don't allocate new ports, but do respect specific requests.\n\t\t\tcontinue\n\t\t}\n\t\tallocatedNodePort := svcPortToNodePort[int(servicePort.Port)]\n\t\tif allocatedNodePort == 0 {\n\t\t\t// This will only scan forward in the service.Spec.Ports list because any matches\n\t\t\t// before the current port would have been found in svcPortToNodePort. This is really\n\t\t\t// looking for any user provided values.\n\t\t\tnp := findRequestedNodePort(int(servicePort.Port), service.Spec.Ports)\n\t\t\tif np != 0 {\n\t\t\t\terr := nodePortOp.Allocate(np)\n\t\t\t\tif err != nil {\n\t\t\t\t\t// TODO: when validation becomes versioned, this gets more complicated.\n\t\t\t\t\tel := field.ErrorList{field.Invalid(field.NewPath(\"spec\", \"ports\").Index(i).Child(\"nodePort\"), np, err.Error())}\n\t\t\t\t\treturn errors.NewInvalid(api.Kind(\"Service\"), service.Name, el)\n\t\t\t\t}\n\t\t\t\tservicePort.NodePort = int32(np)\n\t\t\t\tsvcPortToNodePort[int(servicePort.Port)] = np\n\t\t\t} else {\n\t\t\t\tnodePort, err := nodePortOp.AllocateNext()\n\t\t\t\tif err != nil {\n\t\t\t\t\t// TODO: what error should be returned here? It's not a\n\t\t\t\t\t// field-level validation failure (the field is valid), and it's\n\t\t\t\t\t// not really an internal error.\n\t\t\t\t\treturn errors.NewInternalError(fmt.Errorf(\"failed to allocate a nodePort: %v\", err))\n\t\t\t\t}\n\t\t\t\tservicePort.NodePort = int32(nodePort)\n\t\t\t\tsvcPortToNodePort[int(servicePort.Port)] = nodePort\n\t\t\t}\n\t\t} else if int(servicePort.NodePort) != allocatedNodePort {\n\t\t\t// TODO(xiangpengzhao): do we need to allocate a new NodePort in this case?\n\t\t\t// Note: the current implementation is better, because it saves a NodePort.\n\t\t\tif servicePort.NodePort == 0 {\n\t\t\t\tservicePort.NodePort = int32(allocatedNodePort)\n\t\t\t} else {\n\t\t\t\terr := nodePortOp.Allocate(int(servicePort.NodePort))\n\t\t\t\tif err != nil {\n\t\t\t\t\t// TODO: when validation becomes versioned, this gets more complicated.\n\t\t\t\t\tel := field.ErrorList{field.Invalid(field.NewPath(\"spec\", \"ports\").Index(i).Child(\"nodePort\"), servicePort.NodePort, err.Error())}\n\t\t\t\t\treturn errors.NewInvalid(api.Kind(\"Service\"), service.Name, el)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":512,"to":563}} {"id":100009899,"name":"allocHealthCheckNodePort","signature":"func (al *Allocators) allocHealthCheckNodePort(service *api.Service, nodePortOp *portallocator.PortAllocationOperation) error","file":"pkg/registry/core/service/storage/alloc.go","code":"// allocHealthCheckNodePort allocates health check node port to service.\nfunc (al *Allocators) allocHealthCheckNodePort(service *api.Service, nodePortOp *portallocator.PortAllocationOperation) error {\n\thealthCheckNodePort := service.Spec.HealthCheckNodePort\n\tif healthCheckNodePort != 0 {\n\t\t// If the request has a health check nodePort in mind, attempt to reserve it.\n\t\terr := nodePortOp.Allocate(int(healthCheckNodePort))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to allocate requested HealthCheck NodePort %v: %v\",\n\t\t\t\thealthCheckNodePort, err)\n\t\t}\n\t} else {\n\t\t// If the request has no health check nodePort specified, allocate any.\n\t\thealthCheckNodePort, err := nodePortOp.AllocateNext()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to allocate a HealthCheck NodePort %v: %v\", healthCheckNodePort, err)\n\t\t}\n\t\tservice.Spec.HealthCheckNodePort = int32(healthCheckNodePort)\n\t}\n\treturn nil\n}","line":{"from":565,"to":584}} {"id":100009900,"name":"allocateUpdate","signature":"func (al *Allocators) allocateUpdate(after After, before Before, dryRun bool) (transaction, error)","file":"pkg/registry/core/service/storage/alloc.go","code":"func (al *Allocators) allocateUpdate(after After, before Before, dryRun bool) (transaction, error) {\n\tresult := metaTransaction{}\n\tsuccess := false\n\n\tdefer func() {\n\t\tif !success {\n\t\t\tresult.Revert()\n\t\t}\n\t}()\n\n\t// Ensure IP family fields are correctly initialized. We do it here, since\n\t// we want this to be visible even when dryRun == true.\n\tif err := al.initIPFamilyFields(after, before); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Allocate ClusterIPs\n\t//TODO(thockin): validation should not pass with empty clusterIP, but it\n\t//does (and is tested!). Fixing that all is a big PR and will have to\n\t//happen later.\n\tif txn, err := al.txnUpdateClusterIPs(after, before, dryRun); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tresult = append(result, txn)\n\t}\n\n\t// Allocate ports\n\tif txn, err := al.txnUpdateNodePorts(after, before, dryRun); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tresult = append(result, txn)\n\t}\n\n\tsuccess = true\n\treturn result, nil\n}","line":{"from":586,"to":621}} {"id":100009901,"name":"txnUpdateClusterIPs","signature":"func (al *Allocators) txnUpdateClusterIPs(after After, before Before, dryRun bool) (transaction, error)","file":"pkg/registry/core/service/storage/alloc.go","code":"func (al *Allocators) txnUpdateClusterIPs(after After, before Before, dryRun bool) (transaction, error) {\n\tservice := after.Service\n\n\tallocated, released, err := al.updateClusterIPs(after, before, dryRun)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// on failure: Any newly allocated IP must be released back\n\t// on failure: Any previously allocated IP that would have been released,\n\t// must *not* be released\n\t// on success: Any previously allocated IP that should be released, will be\n\t// released\n\ttxn := callbackTransaction{\n\t\tcommit: func() {\n\t\t\tif dryRun {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif len(allocated) \u003e 0 {\n\t\t\t\tklog.InfoS(\"allocated clusterIPs\",\n\t\t\t\t\t\"service\", klog.KObj(service),\n\t\t\t\t\t\"clusterIPs\", allocated)\n\t\t\t}\n\t\t\tif actuallyReleased, err := al.releaseIPs(released); err != nil {\n\t\t\t\tklog.ErrorS(err, \"failed to clean up after successful service update\",\n\t\t\t\t\t\"service\", klog.KObj(service),\n\t\t\t\t\t\"shouldRelease\", released,\n\t\t\t\t\t\"released\", actuallyReleased)\n\t\t\t}\n\t\t},\n\t\trevert: func() {\n\t\t\tif dryRun {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif actuallyReleased, err := al.releaseIPs(allocated); err != nil {\n\t\t\t\tklog.ErrorS(err, \"failed to clean up after failed service update\",\n\t\t\t\t\t\"service\", klog.KObj(service),\n\t\t\t\t\t\"shouldRelease\", allocated,\n\t\t\t\t\t\"released\", actuallyReleased)\n\t\t\t}\n\t\t},\n\t}\n\treturn txn, nil\n}","line":{"from":623,"to":666}} {"id":100009902,"name":"updateClusterIPs","signature":"func (al *Allocators) updateClusterIPs(after After, before Before, dryRun bool) (allocated map[api.IPFamily]string, toRelease map[api.IPFamily]string, err error)","file":"pkg/registry/core/service/storage/alloc.go","code":"// handles type change/upgrade/downgrade change type for an update service\n// this func does not perform actual release of clusterIPs. it returns\n// a map[family]ip for the caller to release when everything else has\n// executed successfully\nfunc (al *Allocators) updateClusterIPs(after After, before Before, dryRun bool) (allocated map[api.IPFamily]string, toRelease map[api.IPFamily]string, err error) {\n\toldService, service := before.Service, after.Service\n\n\t// We don't want to auto-upgrade (add an IP) or downgrade (remove an IP)\n\t// PreferDualStack services following a cluster change to/from\n\t// dual-stackness.\n\t//\n\t// That means a PreferDualStack service will only be upgraded/downgraded\n\t// when:\n\t// - changing ipFamilyPolicy to \"RequireDualStack\" or \"SingleStack\" AND\n\t// - adding or removing a secondary clusterIP or ipFamily\n\tif isMatchingPreferDualStackClusterIPFields(after, before) {\n\t\treturn allocated, toRelease, nil // nothing more to do.\n\t}\n\n\t// use cases:\n\t// A: service changing types from ExternalName TO ClusterIP types ==\u003e allocate all new\n\t// B: service changing types from ClusterIP types TO ExternalName ==\u003e release all allocated\n\t// C: Service upgrading to dual stack ==\u003e partial allocation\n\t// D: service downgrading from dual stack ==\u003e partial release\n\n\t// CASE A:\n\t// Update service from ExternalName to non-ExternalName, should initialize ClusterIP.\n\tif oldService.Spec.Type == api.ServiceTypeExternalName \u0026\u0026 service.Spec.Type != api.ServiceTypeExternalName {\n\t\tallocated, err := al.allocClusterIPs(service, dryRun)\n\t\treturn allocated, nil, err\n\t}\n\n\t// if headless service then we bail out early (no clusterIPs management needed)\n\tif len(oldService.Spec.ClusterIPs) \u003e 0 \u0026\u0026 oldService.Spec.ClusterIPs[0] == api.ClusterIPNone {\n\t\treturn nil, nil, nil\n\t}\n\n\t// CASE B:\n\t// Update service from non-ExternalName to ExternalName, should release ClusterIP if exists.\n\tif oldService.Spec.Type != api.ServiceTypeExternalName \u0026\u0026 service.Spec.Type == api.ServiceTypeExternalName {\n\t\ttoRelease = make(map[api.IPFamily]string)\n\t\tfor i, family := range oldService.Spec.IPFamilies {\n\t\t\ttoRelease[family] = oldService.Spec.ClusterIPs[i]\n\t\t}\n\t\treturn nil, toRelease, nil\n\t}\n\n\tupgraded := len(oldService.Spec.IPFamilies) == 1 \u0026\u0026 len(service.Spec.IPFamilies) == 2\n\tdowngraded := len(oldService.Spec.IPFamilies) == 2 \u0026\u0026 len(service.Spec.IPFamilies) == 1\n\n\t// CASE C:\n\tif upgraded {\n\t\ttoAllocate := make(map[api.IPFamily]string)\n\t\t// if secondary ip was named, just get it. if not add a marker\n\t\tif len(service.Spec.ClusterIPs) \u003c 2 {\n\t\t\tservice.Spec.ClusterIPs = append(service.Spec.ClusterIPs, \"\" /* marker */)\n\t\t}\n\n\t\ttoAllocate[service.Spec.IPFamilies[1]] = service.Spec.ClusterIPs[1]\n\n\t\t// allocate\n\t\tallocated, err := al.allocIPs(service, toAllocate, dryRun)\n\t\t// set if successful\n\t\tif err == nil {\n\t\t\tservice.Spec.ClusterIPs[1] = allocated[service.Spec.IPFamilies[1]]\n\t\t}\n\n\t\treturn allocated, nil, err\n\t}\n\n\t// CASE D:\n\tif downgraded {\n\t\ttoRelease = make(map[api.IPFamily]string)\n\t\ttoRelease[oldService.Spec.IPFamilies[1]] = oldService.Spec.ClusterIPs[1]\n\t\t// note: we don't release clusterIP, this is left to clean up in the action itself\n\t\treturn nil, toRelease, err\n\t}\n\t// it was not an upgrade nor downgrade\n\treturn nil, nil, nil\n}","line":{"from":668,"to":747}} {"id":100009903,"name":"txnUpdateNodePorts","signature":"func (al *Allocators) txnUpdateNodePorts(after After, before Before, dryRun bool) (transaction, error)","file":"pkg/registry/core/service/storage/alloc.go","code":"func (al *Allocators) txnUpdateNodePorts(after After, before Before, dryRun bool) (transaction, error) {\n\toldService, service := before.Service, after.Service\n\n\t// The allocator tracks dry-run-ness internally.\n\tnodePortOp := portallocator.StartOperation(al.serviceNodePorts, dryRun)\n\n\ttxn := callbackTransaction{\n\t\tcommit: func() {\n\t\t\tnodePortOp.Commit()\n\t\t\t// We don't NEED to call Finish() here, but for that package says\n\t\t\t// to, so for future-safety, we will.\n\t\t\tnodePortOp.Finish()\n\t\t},\n\t\trevert: func() {\n\t\t\t// Weirdly named but this will revert if commit wasn't called\n\t\t\tnodePortOp.Finish()\n\t\t},\n\t}\n\n\t// Update service from NodePort or LoadBalancer to ExternalName or ClusterIP, should release NodePort if exists.\n\tif (oldService.Spec.Type == api.ServiceTypeNodePort || oldService.Spec.Type == api.ServiceTypeLoadBalancer) \u0026\u0026\n\t\t(service.Spec.Type == api.ServiceTypeExternalName || service.Spec.Type == api.ServiceTypeClusterIP) {\n\t\tal.releaseNodePorts(oldService, nodePortOp)\n\t}\n\n\t// Update service from any type to NodePort or LoadBalancer, should update NodePort.\n\tif service.Spec.Type == api.ServiceTypeNodePort || service.Spec.Type == api.ServiceTypeLoadBalancer {\n\t\tif err := al.updateNodePorts(After{service}, Before{oldService}, nodePortOp); err != nil {\n\t\t\ttxn.Revert()\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Handle ExternalTraffic related updates.\n\tsuccess, err := al.updateHealthCheckNodePort(After{service}, Before{oldService}, nodePortOp)\n\tif !success || err != nil {\n\t\ttxn.Revert()\n\t\treturn nil, err\n\t}\n\n\treturn txn, nil\n}","line":{"from":749,"to":790}} {"id":100009904,"name":"releaseNodePorts","signature":"func (al *Allocators) releaseNodePorts(service *api.Service, nodePortOp *portallocator.PortAllocationOperation)","file":"pkg/registry/core/service/storage/alloc.go","code":"func (al *Allocators) releaseNodePorts(service *api.Service, nodePortOp *portallocator.PortAllocationOperation) {\n\tnodePorts := collectServiceNodePorts(service)\n\n\tfor _, nodePort := range nodePorts {\n\t\tnodePortOp.ReleaseDeferred(nodePort)\n\t}\n}","line":{"from":792,"to":798}} {"id":100009905,"name":"updateNodePorts","signature":"func (al *Allocators) updateNodePorts(after After, before Before, nodePortOp *portallocator.PortAllocationOperation) error","file":"pkg/registry/core/service/storage/alloc.go","code":"func (al *Allocators) updateNodePorts(after After, before Before, nodePortOp *portallocator.PortAllocationOperation) error {\n\toldService, newService := before.Service, after.Service\n\n\toldNodePortsNumbers := collectServiceNodePorts(oldService)\n\tnewNodePorts := []ServiceNodePort{}\n\tportAllocated := map[int]bool{}\n\n\tfor i := range newService.Spec.Ports {\n\t\tservicePort := \u0026newService.Spec.Ports[i]\n\t\tif servicePort.NodePort == 0 \u0026\u0026 !shouldAllocateNodePorts(newService) {\n\t\t\t// Don't allocate new ports, but do respect specific requests.\n\t\t\tcontinue\n\t\t}\n\t\tnodePort := ServiceNodePort{Protocol: servicePort.Protocol, NodePort: servicePort.NodePort}\n\t\tif nodePort.NodePort != 0 {\n\t\t\tif !containsNumber(oldNodePortsNumbers, int(nodePort.NodePort)) \u0026\u0026 !portAllocated[int(nodePort.NodePort)] {\n\t\t\t\terr := nodePortOp.Allocate(int(nodePort.NodePort))\n\t\t\t\tif err != nil {\n\t\t\t\t\tel := field.ErrorList{field.Invalid(field.NewPath(\"spec\", \"ports\").Index(i).Child(\"nodePort\"), nodePort.NodePort, err.Error())}\n\t\t\t\t\treturn errors.NewInvalid(api.Kind(\"Service\"), newService.Name, el)\n\t\t\t\t}\n\t\t\t\tportAllocated[int(nodePort.NodePort)] = true\n\t\t\t}\n\t\t} else {\n\t\t\tnodePortNumber, err := nodePortOp.AllocateNext()\n\t\t\tif err != nil {\n\t\t\t\t// TODO: what error should be returned here? It's not a\n\t\t\t\t// field-level validation failure (the field is valid), and it's\n\t\t\t\t// not really an internal error.\n\t\t\t\treturn errors.NewInternalError(fmt.Errorf(\"failed to allocate a nodePort: %v\", err))\n\t\t\t}\n\t\t\tservicePort.NodePort = int32(nodePortNumber)\n\t\t\tnodePort.NodePort = servicePort.NodePort\n\t\t}\n\t\tif containsNodePort(newNodePorts, nodePort) {\n\t\t\treturn fmt.Errorf(\"duplicate nodePort: %v\", nodePort)\n\t\t}\n\t\tnewNodePorts = append(newNodePorts, nodePort)\n\t}\n\n\tnewNodePortsNumbers := collectServiceNodePorts(newService)\n\n\t// The comparison loops are O(N^2), but we don't expect N to be huge\n\t// (there's a hard-limit at 2^16, because they're ports; and even 4 ports would be a lot)\n\tfor _, oldNodePortNumber := range oldNodePortsNumbers {\n\t\tif containsNumber(newNodePortsNumbers, oldNodePortNumber) {\n\t\t\tcontinue\n\t\t}\n\t\tnodePortOp.ReleaseDeferred(int(oldNodePortNumber))\n\t}\n\n\treturn nil\n}","line":{"from":800,"to":852}} {"id":100009906,"name":"updateHealthCheckNodePort","signature":"func (al *Allocators) updateHealthCheckNodePort(after After, before Before, nodePortOp *portallocator.PortAllocationOperation) (bool, error)","file":"pkg/registry/core/service/storage/alloc.go","code":"// updateHealthCheckNodePort handles HealthCheckNodePort allocation/release\n// and adjusts HealthCheckNodePort during service update if needed.\nfunc (al *Allocators) updateHealthCheckNodePort(after After, before Before, nodePortOp *portallocator.PortAllocationOperation) (bool, error) {\n\toldService, service := before.Service, after.Service\n\n\tneededHealthCheckNodePort := apiservice.NeedsHealthCheck(oldService)\n\toldHealthCheckNodePort := oldService.Spec.HealthCheckNodePort\n\n\tneedsHealthCheckNodePort := apiservice.NeedsHealthCheck(service)\n\n\tswitch {\n\t// Case 1: Transition from don't need HealthCheckNodePort to needs HealthCheckNodePort.\n\t// Allocate a health check node port or attempt to reserve the user-specified one if provided.\n\t// Insert health check node port into the service's HealthCheckNodePort field if needed.\n\tcase !neededHealthCheckNodePort \u0026\u0026 needsHealthCheckNodePort:\n\t\tif err := al.allocHealthCheckNodePort(service, nodePortOp); err != nil {\n\t\t\treturn false, errors.NewInternalError(err)\n\t\t}\n\n\t// Case 2: Transition from needs HealthCheckNodePort to don't need HealthCheckNodePort.\n\t// Free the existing healthCheckNodePort and clear the HealthCheckNodePort field.\n\tcase neededHealthCheckNodePort \u0026\u0026 !needsHealthCheckNodePort:\n\t\tnodePortOp.ReleaseDeferred(int(oldHealthCheckNodePort))\n\t}\n\treturn true, nil\n}","line":{"from":854,"to":879}} {"id":100009907,"name":"releaseAllocatedResources","signature":"func (al *Allocators) releaseAllocatedResources(svc *api.Service)","file":"pkg/registry/core/service/storage/alloc.go","code":"func (al *Allocators) releaseAllocatedResources(svc *api.Service) {\n\tal.releaseClusterIPs(svc)\n\n\tfor _, nodePort := range collectServiceNodePorts(svc) {\n\t\terr := al.serviceNodePorts.Release(nodePort)\n\t\tif err != nil {\n\t\t\t// these should be caught by an eventual reconciliation / restart\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"Error releasing service %s node port %d: %v\", svc.Name, nodePort, err))\n\t\t}\n\t}\n\n\tif apiservice.NeedsHealthCheck(svc) {\n\t\tnodePort := svc.Spec.HealthCheckNodePort\n\t\tif nodePort \u003e 0 {\n\t\t\terr := al.serviceNodePorts.Release(int(nodePort))\n\t\t\tif err != nil {\n\t\t\t\t// these should be caught by an eventual reconciliation / restart\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"Error releasing service %s health check node port %d: %v\", svc.Name, nodePort, err))\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":881,"to":902}} {"id":100009908,"name":"releaseClusterIPs","signature":"func (al *Allocators) releaseClusterIPs(service *api.Service) (released map[api.IPFamily]string, err error)","file":"pkg/registry/core/service/storage/alloc.go","code":"// releases allocated ClusterIPs for service that is about to be deleted\nfunc (al *Allocators) releaseClusterIPs(service *api.Service) (released map[api.IPFamily]string, err error) {\n\t// external name don't get ClusterIPs\n\tif service.Spec.Type == api.ServiceTypeExternalName {\n\t\treturn nil, nil\n\t}\n\n\t// headless don't get ClusterIPs\n\tif len(service.Spec.ClusterIPs) \u003e 0 \u0026\u0026 service.Spec.ClusterIPs[0] == api.ClusterIPNone {\n\t\treturn nil, nil\n\t}\n\n\ttoRelease := make(map[api.IPFamily]string)\n\tfor _, ip := range service.Spec.ClusterIPs {\n\t\tif netutils.IsIPv6String(ip) {\n\t\t\ttoRelease[api.IPv6Protocol] = ip\n\t\t} else {\n\t\t\ttoRelease[api.IPv4Protocol] = ip\n\t\t}\n\t}\n\treturn al.releaseIPs(toRelease)\n}","line":{"from":904,"to":925}} {"id":100009909,"name":"Destroy","signature":"func (al *Allocators) Destroy()","file":"pkg/registry/core/service/storage/alloc.go","code":"func (al *Allocators) Destroy() {\n\tal.serviceNodePorts.Destroy()\n\tfor _, a := range al.serviceIPAllocatorsByFamily {\n\t\ta.Destroy()\n\t}\n}","line":{"from":927,"to":932}} {"id":100009910,"name":"containsNumber","signature":"func containsNumber(haystack []int, needle int) bool","file":"pkg/registry/core/service/storage/alloc.go","code":"// This is O(N), but we expect haystack to be small;\n// so small that we expect a linear search to be faster\nfunc containsNumber(haystack []int, needle int) bool {\n\tfor _, v := range haystack {\n\t\tif v == needle {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":934,"to":943}} {"id":100009911,"name":"containsNodePort","signature":"func containsNodePort(serviceNodePorts []ServiceNodePort, serviceNodePort ServiceNodePort) bool","file":"pkg/registry/core/service/storage/alloc.go","code":"// This is O(N), but we expect serviceNodePorts to be small;\n// so small that we expect a linear search to be faster\nfunc containsNodePort(serviceNodePorts []ServiceNodePort, serviceNodePort ServiceNodePort) bool {\n\tfor _, snp := range serviceNodePorts {\n\t\tif snp == serviceNodePort {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":945,"to":954}} {"id":100009912,"name":"findRequestedNodePort","signature":"func findRequestedNodePort(port int, servicePorts []api.ServicePort) int","file":"pkg/registry/core/service/storage/alloc.go","code":"// Loop through the service ports list, find one with the same port number and\n// NodePort specified, return this NodePort otherwise return 0.\nfunc findRequestedNodePort(port int, servicePorts []api.ServicePort) int {\n\tfor i := range servicePorts {\n\t\tservicePort := servicePorts[i]\n\t\tif port == int(servicePort.Port) \u0026\u0026 servicePort.NodePort != 0 {\n\t\t\treturn int(servicePort.NodePort)\n\t\t}\n\t}\n\treturn 0\n}","line":{"from":956,"to":966}} {"id":100009913,"name":"shouldAllocateNodePorts","signature":"func shouldAllocateNodePorts(service *api.Service) bool","file":"pkg/registry/core/service/storage/alloc.go","code":"func shouldAllocateNodePorts(service *api.Service) bool {\n\tif service.Spec.Type == api.ServiceTypeNodePort {\n\t\treturn true\n\t}\n\tif service.Spec.Type == api.ServiceTypeLoadBalancer {\n\t\treturn *service.Spec.AllocateLoadBalancerNodePorts\n\t}\n\treturn false\n}","line":{"from":968,"to":976}} {"id":100009914,"name":"collectServiceNodePorts","signature":"func collectServiceNodePorts(service *api.Service) []int","file":"pkg/registry/core/service/storage/alloc.go","code":"func collectServiceNodePorts(service *api.Service) []int {\n\tservicePorts := []int{}\n\tfor i := range service.Spec.Ports {\n\t\tservicePort := \u0026service.Spec.Ports[i]\n\t\tif servicePort.NodePort != 0 {\n\t\t\tservicePorts = append(servicePorts, int(servicePort.NodePort))\n\t\t}\n\t}\n\treturn servicePorts\n}","line":{"from":978,"to":987}} {"id":100009915,"name":"isMatchingPreferDualStackClusterIPFields","signature":"func isMatchingPreferDualStackClusterIPFields(after After, before Before) bool","file":"pkg/registry/core/service/storage/alloc.go","code":"// tests if two preferred dual-stack service have matching ClusterIPFields\n// assumption: old service is a valid, default service (e.g., loaded from store)\nfunc isMatchingPreferDualStackClusterIPFields(after After, before Before) bool {\n\toldService, service := before.Service, after.Service\n\n\tif oldService == nil {\n\t\treturn false\n\t}\n\n\tif service.Spec.IPFamilyPolicy == nil {\n\t\treturn false\n\t}\n\n\t// if type mutated then it is an update\n\t// that needs to run through the entire process.\n\tif oldService.Spec.Type != service.Spec.Type {\n\t\treturn false\n\t}\n\t// both must be type that gets an IP assigned\n\tif service.Spec.Type != api.ServiceTypeClusterIP \u0026\u0026\n\t\tservice.Spec.Type != api.ServiceTypeNodePort \u0026\u0026\n\t\tservice.Spec.Type != api.ServiceTypeLoadBalancer {\n\t\treturn false\n\t}\n\n\t// both must be of IPFamilyPolicy==PreferDualStack\n\tif service.Spec.IPFamilyPolicy != nil \u0026\u0026 *(service.Spec.IPFamilyPolicy) != api.IPFamilyPolicyPreferDualStack {\n\t\treturn false\n\t}\n\n\tif oldService.Spec.IPFamilyPolicy != nil \u0026\u0026 *(oldService.Spec.IPFamilyPolicy) != api.IPFamilyPolicyPreferDualStack {\n\t\treturn false\n\t}\n\n\tif !sameClusterIPs(oldService, service) {\n\t\treturn false\n\t}\n\n\tif !sameIPFamilies(oldService, service) {\n\t\treturn false\n\t}\n\n\t// they match on\n\t// Policy: preferDualStack\n\t// ClusterIPs\n\t// IPFamilies\n\treturn true\n}","line":{"from":989,"to":1036}} {"id":100009916,"name":"getIPFamilyPolicy","signature":"func getIPFamilyPolicy(svc *api.Service) api.IPFamilyPolicy","file":"pkg/registry/core/service/storage/alloc.go","code":"// Helper to avoid nil-checks all over. Callers of this need to be checking\n// for an exact value.\nfunc getIPFamilyPolicy(svc *api.Service) api.IPFamilyPolicy {\n\tif svc.Spec.IPFamilyPolicy == nil {\n\t\treturn \"\" // callers need to handle this\n\t}\n\treturn *svc.Spec.IPFamilyPolicy\n}","line":{"from":1038,"to":1045}} {"id":100009917,"name":"sameClusterIPs","signature":"func sameClusterIPs(lhs, rhs *api.Service) bool","file":"pkg/registry/core/service/storage/alloc.go","code":"func sameClusterIPs(lhs, rhs *api.Service) bool {\n\tif len(rhs.Spec.ClusterIPs) != len(lhs.Spec.ClusterIPs) {\n\t\treturn false\n\t}\n\n\tfor i, ip := range rhs.Spec.ClusterIPs {\n\t\tif lhs.Spec.ClusterIPs[i] != ip {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}","line":{"from":1047,"to":1059}} {"id":100009918,"name":"reducedClusterIPs","signature":"func reducedClusterIPs(after After, before Before) bool","file":"pkg/registry/core/service/storage/alloc.go","code":"func reducedClusterIPs(after After, before Before) bool {\n\toldSvc, newSvc := before.Service, after.Service\n\n\tif len(newSvc.Spec.ClusterIPs) == 0 { // Not specified\n\t\treturn false\n\t}\n\treturn len(newSvc.Spec.ClusterIPs) \u003c len(oldSvc.Spec.ClusterIPs)\n}","line":{"from":1061,"to":1068}} {"id":100009919,"name":"sameIPFamilies","signature":"func sameIPFamilies(lhs, rhs *api.Service) bool","file":"pkg/registry/core/service/storage/alloc.go","code":"func sameIPFamilies(lhs, rhs *api.Service) bool {\n\tif len(rhs.Spec.IPFamilies) != len(lhs.Spec.IPFamilies) {\n\t\treturn false\n\t}\n\n\tfor i, family := range rhs.Spec.IPFamilies {\n\t\tif lhs.Spec.IPFamilies[i] != family {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}","line":{"from":1070,"to":1082}} {"id":100009920,"name":"reducedIPFamilies","signature":"func reducedIPFamilies(after After, before Before) bool","file":"pkg/registry/core/service/storage/alloc.go","code":"func reducedIPFamilies(after After, before Before) bool {\n\toldSvc, newSvc := before.Service, after.Service\n\n\tif len(newSvc.Spec.IPFamilies) == 0 { // Not specified\n\t\treturn false\n\t}\n\treturn len(newSvc.Spec.IPFamilies) \u003c len(oldSvc.Spec.IPFamilies)\n}","line":{"from":1084,"to":1091}} {"id":100009921,"name":"familyOf","signature":"func familyOf(ip string) api.IPFamily","file":"pkg/registry/core/service/storage/alloc.go","code":"// Helper to get the IP family of a given IP.\nfunc familyOf(ip string) api.IPFamily {\n\tif netutils.IsIPv4String(ip) {\n\t\treturn api.IPv4Protocol\n\t}\n\tif netutils.IsIPv6String(ip) {\n\t\treturn api.IPv6Protocol\n\t}\n\treturn api.IPFamily(\"unknown\")\n}","line":{"from":1093,"to":1102}} {"id":100009922,"name":"NewREST","signature":"func NewREST(","file":"pkg/registry/core/service/storage/storage.go","code":"// NewREST returns a REST object that will work against services.\nfunc NewREST(\n\toptsGetter generic.RESTOptionsGetter,\n\tserviceIPFamily api.IPFamily,\n\tipAllocs map[api.IPFamily]ipallocator.Interface,\n\tportAlloc portallocator.Interface,\n\tendpoints EndpointsStorage,\n\tpods PodStorage,\n\tproxyTransport http.RoundTripper) (*REST, *StatusREST, *svcreg.ProxyREST, error) {\n\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026api.Service{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026api.ServiceList{} },\n\t\tDefaultQualifiedResource: api.Resource(\"services\"),\n\t\tSingularQualifiedResource: api.Resource(\"service\"),\n\t\tReturnDeletedObject: true,\n\n\t\tCreateStrategy: svcreg.Strategy,\n\t\tUpdateStrategy: svcreg.Strategy,\n\t\tDeleteStrategy: svcreg.Strategy,\n\t\tResetFieldsStrategy: svcreg.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = svcreg.StatusStrategy\n\tstatusStore.ResetFieldsStrategy = svcreg.StatusStrategy\n\n\tvar primaryIPFamily api.IPFamily = serviceIPFamily\n\tvar secondaryIPFamily api.IPFamily = \"\" // sentinel value\n\tif len(ipAllocs) \u003e 1 {\n\t\tsecondaryIPFamily = otherFamily(serviceIPFamily)\n\t}\n\tgenericStore := \u0026REST{\n\t\tStore: store,\n\t\tprimaryIPFamily: primaryIPFamily,\n\t\tsecondaryIPFamily: secondaryIPFamily,\n\t\talloc: makeAlloc(serviceIPFamily, ipAllocs, portAlloc),\n\t\tendpoints: endpoints,\n\t\tpods: pods,\n\t\tproxyTransport: proxyTransport,\n\t}\n\tstore.Decorator = genericStore.defaultOnRead\n\tstore.AfterDelete = genericStore.afterDelete\n\tstore.BeginCreate = genericStore.beginCreate\n\tstore.BeginUpdate = genericStore.beginUpdate\n\n\treturn genericStore, \u0026StatusREST{store: \u0026statusStore}, \u0026svcreg.ProxyREST{Redirector: genericStore, ProxyTransport: proxyTransport}, nil\n}","line":{"from":78,"to":131}} {"id":100009923,"name":"otherFamily","signature":"func otherFamily(fam api.IPFamily) api.IPFamily","file":"pkg/registry/core/service/storage/storage.go","code":"// otherFamily returns the non-selected IPFamily. This assumes the input is\n// valid.\nfunc otherFamily(fam api.IPFamily) api.IPFamily {\n\tif fam == api.IPv4Protocol {\n\t\treturn api.IPv6Protocol\n\t}\n\treturn api.IPv4Protocol\n}","line":{"from":133,"to":140}} {"id":100009924,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/core/service/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"svc\"}\n}","line":{"from":147,"to":150}} {"id":100009925,"name":"Categories","signature":"func (r *REST) Categories() []string","file":"pkg/registry/core/service/storage/storage.go","code":"// Categories implements the CategoriesProvider interface. Returns a list of categories a resource is part of.\nfunc (r *REST) Categories() []string {\n\treturn []string{\"all\"}\n}","line":{"from":152,"to":155}} {"id":100009926,"name":"Destroy","signature":"func (r *REST) Destroy()","file":"pkg/registry/core/service/storage/storage.go","code":"// Destroy cleans up everything on shutdown.\nfunc (r *REST) Destroy() {\n\tr.Store.Destroy()\n\tr.alloc.Destroy()\n}","line":{"from":157,"to":161}} {"id":100009927,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"pkg/registry/core/service/storage/storage.go","code":"func (r *StatusREST) New() runtime.Object {\n\treturn \u0026api.Service{}\n}","line":{"from":168,"to":170}} {"id":100009928,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"pkg/registry/core/service/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":172,"to":176}} {"id":100009929,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/core/service/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":178,"to":181}} {"id":100009930,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/core/service/storage/storage.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":183,"to":188}} {"id":100009931,"name":"ConvertToTable","signature":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/core/service/storage/storage.go","code":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":190,"to":192}} {"id":100009932,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/service/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":194,"to":197}} {"id":100009933,"name":"defaultOnRead","signature":"func (r *REST) defaultOnRead(obj runtime.Object)","file":"pkg/registry/core/service/storage/storage.go","code":"// defaultOnRead sets interlinked fields that were not previously set on read.\n// We can't do this in the normal defaulting path because that same logic\n// applies on Get, Create, and Update, but we need to distinguish between them.\n//\n// This will be called on both Service and ServiceList types.\nfunc (r *REST) defaultOnRead(obj runtime.Object) {\n\tswitch s := obj.(type) {\n\tcase *api.Service:\n\t\tr.defaultOnReadService(s)\n\tcase *api.ServiceList:\n\t\tr.defaultOnReadServiceList(s)\n\tdefault:\n\t\t// This was not an object we can default. This is not an error, as the\n\t\t// caching layer can pass through here, too.\n\t}\n}","line":{"from":218,"to":233}} {"id":100009934,"name":"defaultOnReadServiceList","signature":"func (r *REST) defaultOnReadServiceList(serviceList *api.ServiceList)","file":"pkg/registry/core/service/storage/storage.go","code":"// defaultOnReadServiceList defaults a ServiceList.\nfunc (r *REST) defaultOnReadServiceList(serviceList *api.ServiceList) {\n\tif serviceList == nil {\n\t\treturn\n\t}\n\n\tfor i := range serviceList.Items {\n\t\tr.defaultOnReadService(\u0026serviceList.Items[i])\n\t}\n}","line":{"from":235,"to":244}} {"id":100009935,"name":"defaultOnReadService","signature":"func (r *REST) defaultOnReadService(service *api.Service)","file":"pkg/registry/core/service/storage/storage.go","code":"// defaultOnReadService defaults a single Service.\nfunc (r *REST) defaultOnReadService(service *api.Service) {\n\tif service == nil {\n\t\treturn\n\t}\n\n\t// We might find Services that were written before ClusterIP became plural.\n\t// We still want to present a consistent view of them.\n\tnormalizeClusterIPs(After{service}, Before{nil})\n\n\t// Set ipFamilies and ipFamilyPolicy if needed.\n\tr.defaultOnReadIPFamilies(service)\n\n\t// We unintentionally defaulted internalTrafficPolicy when it's not needed\n\t// for the ExternalName type. It's too late to change the field in storage,\n\t// but we can drop the field when read.\n\tdefaultOnReadInternalTrafficPolicy(service)\n}","line":{"from":246,"to":263}} {"id":100009936,"name":"defaultOnReadInternalTrafficPolicy","signature":"func defaultOnReadInternalTrafficPolicy(service *api.Service)","file":"pkg/registry/core/service/storage/storage.go","code":"func defaultOnReadInternalTrafficPolicy(service *api.Service) {\n\tif service.Spec.Type == api.ServiceTypeExternalName {\n\t\tservice.Spec.InternalTrafficPolicy = nil\n\t}\n}","line":{"from":265,"to":269}} {"id":100009937,"name":"defaultOnReadIPFamilies","signature":"func (r *REST) defaultOnReadIPFamilies(service *api.Service)","file":"pkg/registry/core/service/storage/storage.go","code":"func (r *REST) defaultOnReadIPFamilies(service *api.Service) {\n\t// ExternalName does not need this.\n\tif !needsClusterIP(service) {\n\t\treturn\n\t}\n\n\t// If IPFamilies is set, we assume IPFamilyPolicy is also set (it should\n\t// not be possible to have one and not the other), and therefore we don't\n\t// need further defaulting. Likewise, if IPFamilies is *not* set, we\n\t// assume IPFamilyPolicy can't be set either.\n\tif len(service.Spec.IPFamilies) \u003e 0 {\n\t\treturn\n\t}\n\n\tsingleStack := api.IPFamilyPolicySingleStack\n\trequireDualStack := api.IPFamilyPolicyRequireDualStack\n\n\tif service.Spec.ClusterIP == api.ClusterIPNone {\n\t\t// Headless.\n\t\tif len(service.Spec.Selector) == 0 {\n\t\t\t// Headless + selectorless is a special-case.\n\t\t\t//\n\t\t\t// At this stage we don't know what kind of endpoints (specifically\n\t\t\t// their IPFamilies) the user has assigned to this selectorless\n\t\t\t// service. We assume it has dual-stack and we default it to\n\t\t\t// RequireDualStack on any cluster (single- or dual-stack\n\t\t\t// configured).\n\t\t\tservice.Spec.IPFamilyPolicy = \u0026requireDualStack\n\t\t\tservice.Spec.IPFamilies = []api.IPFamily{r.primaryIPFamily, otherFamily(r.primaryIPFamily)}\n\t\t} else {\n\t\t\t// Headless + selector - default to single.\n\t\t\tservice.Spec.IPFamilyPolicy = \u0026singleStack\n\t\t\tservice.Spec.IPFamilies = []api.IPFamily{r.primaryIPFamily}\n\t\t}\n\t} else {\n\t\t// Headful: init ipFamilies from clusterIPs.\n\t\tservice.Spec.IPFamilies = make([]api.IPFamily, len(service.Spec.ClusterIPs))\n\t\tfor idx, ip := range service.Spec.ClusterIPs {\n\t\t\tif netutil.IsIPv6String(ip) {\n\t\t\t\tservice.Spec.IPFamilies[idx] = api.IPv6Protocol\n\t\t\t} else {\n\t\t\t\tservice.Spec.IPFamilies[idx] = api.IPv4Protocol\n\t\t\t}\n\t\t}\n\t\tif len(service.Spec.IPFamilies) == 1 {\n\t\t\tservice.Spec.IPFamilyPolicy = \u0026singleStack\n\t\t} else if len(service.Spec.IPFamilies) == 2 {\n\t\t\t// It shouldn't be possible to get here, but just in case.\n\t\t\tservice.Spec.IPFamilyPolicy = \u0026requireDualStack\n\t\t}\n\t}\n}","line":{"from":271,"to":322}} {"id":100009938,"name":"afterDelete","signature":"func (r *REST) afterDelete(obj runtime.Object, options *metav1.DeleteOptions)","file":"pkg/registry/core/service/storage/storage.go","code":"func (r *REST) afterDelete(obj runtime.Object, options *metav1.DeleteOptions) {\n\tsvc := obj.(*api.Service)\n\n\t// Normally this defaulting is done automatically, but the hook (Decorator)\n\t// is called at the end of this process, and we want the fully-formed\n\t// object.\n\tr.defaultOnReadService(svc)\n\n\t// Only perform the cleanup if this is a non-dryrun deletion\n\tif !dryrun.IsDryRun(options.DryRun) {\n\t\t// It would be better if we had the caller context, but that changes\n\t\t// this hook signature.\n\t\tctx := genericapirequest.WithNamespace(genericapirequest.NewContext(), svc.Namespace)\n\t\t// TODO: This is clumsy. It was added for fear that the endpoints\n\t\t// controller might lag, and we could end up rusing the service name\n\t\t// with old endpoints. We should solve that better and remove this, or\n\t\t// else we should do this for EndpointSlice, too.\n\t\t_, _, err := r.endpoints.Delete(ctx, svc.Name, rest.ValidateAllObjectFunc, \u0026metav1.DeleteOptions{})\n\t\tif err != nil \u0026\u0026 !errors.IsNotFound(err) {\n\t\t\tklog.Errorf(\"delete service endpoints %s/%s failed: %v\", svc.Name, svc.Namespace, err)\n\t\t}\n\n\t\tr.alloc.releaseAllocatedResources(svc)\n\t}\n}","line":{"from":324,"to":348}} {"id":100009939,"name":"beginCreate","signature":"func (r *REST) beginCreate(ctx context.Context, obj runtime.Object, options *metav1.CreateOptions) (genericregistry.FinishFunc, error)","file":"pkg/registry/core/service/storage/storage.go","code":"func (r *REST) beginCreate(ctx context.Context, obj runtime.Object, options *metav1.CreateOptions) (genericregistry.FinishFunc, error) {\n\tsvc := obj.(*api.Service)\n\n\t// Make sure ClusterIP and ClusterIPs are in sync. This has to happen\n\t// early, before anyone looks at them.\n\tnormalizeClusterIPs(After{svc}, Before{nil})\n\n\t// Allocate IPs and ports. If we had a transactional store, this would just\n\t// be part of the larger transaction. We don't have that, so we have to do\n\t// it manually. This has to happen here and not in any earlier hooks (e.g.\n\t// defaulting) because it needs to be aware of flags and be able to access\n\t// API storage.\n\ttxn, err := r.alloc.allocateCreate(svc, dryrun.IsDryRun(options.DryRun))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Our cleanup callback\n\tfinish := func(_ context.Context, success bool) {\n\t\tif success {\n\t\t\ttxn.Commit()\n\t\t} else {\n\t\t\ttxn.Revert()\n\t\t}\n\t}\n\n\treturn finish, nil\n}","line":{"from":350,"to":377}} {"id":100009940,"name":"beginUpdate","signature":"func (r *REST) beginUpdate(ctx context.Context, obj, oldObj runtime.Object, options *metav1.UpdateOptions) (genericregistry.FinishFunc, error)","file":"pkg/registry/core/service/storage/storage.go","code":"func (r *REST) beginUpdate(ctx context.Context, obj, oldObj runtime.Object, options *metav1.UpdateOptions) (genericregistry.FinishFunc, error) {\n\tnewSvc := obj.(*api.Service)\n\toldSvc := oldObj.(*api.Service)\n\n\t// Make sure the existing object has all fields we expect to be defaulted.\n\t// This might not be true if the saved object predates these fields (the\n\t// Decorator hook is not called on 'old' in the update path.\n\tr.defaultOnReadService(oldSvc)\n\n\t// Fix up allocated values that the client may have not specified (for\n\t// idempotence).\n\tpatchAllocatedValues(After{newSvc}, Before{oldSvc})\n\n\t// Make sure ClusterIP and ClusterIPs are in sync. This has to happen\n\t// early, before anyone looks at them.\n\tnormalizeClusterIPs(After{newSvc}, Before{oldSvc})\n\n\t// Allocate and initialize fields.\n\ttxn, err := r.alloc.allocateUpdate(After{newSvc}, Before{oldSvc}, dryrun.IsDryRun(options.DryRun))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Our cleanup callback\n\tfinish := func(_ context.Context, success bool) {\n\t\tif success {\n\t\t\ttxn.Commit()\n\t\t} else {\n\t\t\ttxn.Revert()\n\t\t}\n\t}\n\n\treturn finish, nil\n}","line":{"from":379,"to":412}} {"id":100009941,"name":"ResourceLocation","signature":"func (r *REST) ResourceLocation(ctx context.Context, id string) (*url.URL, http.RoundTripper, error)","file":"pkg/registry/core/service/storage/storage.go","code":"// ResourceLocation returns a URL to which one can send traffic for the specified service.\nfunc (r *REST) ResourceLocation(ctx context.Context, id string) (*url.URL, http.RoundTripper, error) {\n\t// Allow ID as \"svcname\", \"svcname:port\", or \"scheme:svcname:port\".\n\tsvcScheme, svcName, portStr, valid := utilnet.SplitSchemeNamePort(id)\n\tif !valid {\n\t\treturn nil, nil, errors.NewBadRequest(fmt.Sprintf(\"invalid service request %q\", id))\n\t}\n\n\t// If a port *number* was specified, find the corresponding service port name\n\tif portNum, err := strconv.ParseInt(portStr, 10, 64); err == nil {\n\t\tobj, err := r.Get(ctx, svcName, \u0026metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tsvc := obj.(*api.Service)\n\t\tfound := false\n\t\tfor _, svcPort := range svc.Spec.Ports {\n\t\t\tif int64(svcPort.Port) == portNum {\n\t\t\t\t// use the declared port's name\n\t\t\t\tportStr = svcPort.Name\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\treturn nil, nil, errors.NewServiceUnavailable(fmt.Sprintf(\"no service port %d found for service %q\", portNum, svcName))\n\t\t}\n\t}\n\n\tobj, err := r.endpoints.Get(ctx, svcName, \u0026metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\teps := obj.(*api.Endpoints)\n\tif len(eps.Subsets) == 0 {\n\t\treturn nil, nil, errors.NewServiceUnavailable(fmt.Sprintf(\"no endpoints available for service %q\", svcName))\n\t}\n\t// Pick a random Subset to start searching from.\n\tssSeed := rand.Intn(len(eps.Subsets))\n\t// Find a Subset that has the port.\n\tfor ssi := 0; ssi \u003c len(eps.Subsets); ssi++ {\n\t\tss := \u0026eps.Subsets[(ssSeed+ssi)%len(eps.Subsets)]\n\t\tif len(ss.Addresses) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tfor i := range ss.Ports {\n\t\t\tif ss.Ports[i].Name == portStr {\n\t\t\t\taddrSeed := rand.Intn(len(ss.Addresses))\n\t\t\t\t// This is a little wonky, but it's expensive to test for the presence of a Pod\n\t\t\t\t// So we repeatedly try at random and validate it, this means that for an invalid\n\t\t\t\t// service with a lot of endpoints we're going to potentially make a lot of calls,\n\t\t\t\t// but in the expected case we'll only make one.\n\t\t\t\tfor try := 0; try \u003c len(ss.Addresses); try++ {\n\t\t\t\t\taddr := ss.Addresses[(addrSeed+try)%len(ss.Addresses)]\n\t\t\t\t\t// We only proxy to addresses that are actually pods.\n\t\t\t\t\tif err := isValidAddress(ctx, \u0026addr, r.pods); err != nil {\n\t\t\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"Address %v isn't valid (%v)\", addr, err))\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tip := addr.IP\n\t\t\t\t\tport := int(ss.Ports[i].Port)\n\t\t\t\t\treturn \u0026url.URL{\n\t\t\t\t\t\tScheme: svcScheme,\n\t\t\t\t\t\tHost: net.JoinHostPort(ip, strconv.Itoa(port)),\n\t\t\t\t\t}, r.proxyTransport, nil\n\t\t\t\t}\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"Failed to find a valid address, skipping subset: %v\", ss))\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, nil, errors.NewServiceUnavailable(fmt.Sprintf(\"no endpoints available for service %q\", id))\n}","line":{"from":414,"to":485}} {"id":100009942,"name":"isValidAddress","signature":"func isValidAddress(ctx context.Context, addr *api.EndpointAddress, pods rest.Getter) error","file":"pkg/registry/core/service/storage/storage.go","code":"func isValidAddress(ctx context.Context, addr *api.EndpointAddress, pods rest.Getter) error {\n\tif addr.TargetRef == nil {\n\t\treturn fmt.Errorf(\"Address has no target ref, skipping: %v\", addr)\n\t}\n\tif genericapirequest.NamespaceValue(ctx) != addr.TargetRef.Namespace {\n\t\treturn fmt.Errorf(\"Address namespace doesn't match context namespace\")\n\t}\n\tobj, err := pods.Get(ctx, addr.TargetRef.Name, \u0026metav1.GetOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\tpod, ok := obj.(*api.Pod)\n\tif !ok {\n\t\treturn fmt.Errorf(\"failed to cast to pod: %v\", obj)\n\t}\n\tif pod == nil {\n\t\treturn fmt.Errorf(\"pod is missing, skipping (%s/%s)\", addr.TargetRef.Namespace, addr.TargetRef.Name)\n\t}\n\tfor _, podIP := range pod.Status.PodIPs {\n\t\tif podIP.IP == addr.IP {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"pod ip(s) doesn't match endpoint ip, skipping: %v vs %s (%s/%s)\", pod.Status.PodIPs, addr.IP, addr.TargetRef.Namespace, addr.TargetRef.Name)\n}","line":{"from":487,"to":511}} {"id":100009943,"name":"normalizeClusterIPs","signature":"func normalizeClusterIPs(after After, before Before)","file":"pkg/registry/core/service/storage/storage.go","code":"// normalizeClusterIPs adjust clusterIPs based on ClusterIP. This must not\n// consider any other fields.\nfunc normalizeClusterIPs(after After, before Before) {\n\toldSvc, newSvc := before.Service, after.Service\n\n\t// In all cases here, we don't need to over-think the inputs. Validation\n\t// will be called on the new object soon enough. All this needs to do is\n\t// try to divine what user meant with these linked fields. The below\n\t// is verbosely written for clarity.\n\n\t// **** IMPORTANT *****\n\t// as a governing rule. User must (either)\n\t// -- Use singular only (old client)\n\t// -- singular and plural fields (new clients)\n\n\tif oldSvc == nil {\n\t\t// This was a create operation.\n\t\t// User specified singular and not plural (e.g. an old client), so init\n\t\t// plural for them.\n\t\tif len(newSvc.Spec.ClusterIP) \u003e 0 \u0026\u0026 len(newSvc.Spec.ClusterIPs) == 0 {\n\t\t\tnewSvc.Spec.ClusterIPs = []string{newSvc.Spec.ClusterIP}\n\t\t\treturn\n\t\t}\n\n\t\t// we don't init singular based on plural because\n\t\t// new client must use both fields\n\n\t\t// Either both were not specified (will be allocated) or both were\n\t\t// specified (will be validated).\n\t\treturn\n\t}\n\n\t// This was an update operation\n\n\t// ClusterIPs were cleared by an old client which was trying to patch\n\t// some field and didn't provide ClusterIPs\n\tif len(oldSvc.Spec.ClusterIPs) \u003e 0 \u0026\u0026 len(newSvc.Spec.ClusterIPs) == 0 {\n\t\t// if ClusterIP is the same, then it is an old client trying to\n\t\t// patch service and didn't provide ClusterIPs\n\t\tif oldSvc.Spec.ClusterIP == newSvc.Spec.ClusterIP {\n\t\t\tnewSvc.Spec.ClusterIPs = oldSvc.Spec.ClusterIPs\n\t\t}\n\t}\n\n\t// clusterIP is not the same\n\tif oldSvc.Spec.ClusterIP != newSvc.Spec.ClusterIP {\n\t\t// this is a client trying to clear it\n\t\tif len(oldSvc.Spec.ClusterIP) \u003e 0 \u0026\u0026 len(newSvc.Spec.ClusterIP) == 0 {\n\t\t\t// if clusterIPs are the same, then clear on their behalf\n\t\t\tif sameClusterIPs(oldSvc, newSvc) {\n\t\t\t\tnewSvc.Spec.ClusterIPs = nil\n\t\t\t}\n\n\t\t\t// if they provided nil, then we are fine (handled by patching case above)\n\t\t\t// if they changed it then validation will catch it\n\t\t} else {\n\t\t\t// ClusterIP has changed but not cleared *and* ClusterIPs are the same\n\t\t\t// then we set ClusterIPs based on ClusterIP\n\t\t\tif sameClusterIPs(oldSvc, newSvc) {\n\t\t\t\tnewSvc.Spec.ClusterIPs = []string{newSvc.Spec.ClusterIP}\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":513,"to":576}} {"id":100009944,"name":"patchAllocatedValues","signature":"func patchAllocatedValues(after After, before Before)","file":"pkg/registry/core/service/storage/storage.go","code":"// patchAllocatedValues allows clients to avoid a read-modify-write cycle while\n// preserving values that we allocated on their behalf. For example, they\n// might create a Service without specifying the ClusterIP, in which case we\n// allocate one. If they resubmit that same YAML, we want it to succeed.\nfunc patchAllocatedValues(after After, before Before) {\n\toldSvc, newSvc := before.Service, after.Service\n\n\tif needsClusterIP(oldSvc) \u0026\u0026 needsClusterIP(newSvc) {\n\t\tif newSvc.Spec.ClusterIP == \"\" {\n\t\t\tnewSvc.Spec.ClusterIP = oldSvc.Spec.ClusterIP\n\t\t}\n\t\tif len(newSvc.Spec.ClusterIPs) == 0 \u0026\u0026 len(oldSvc.Spec.ClusterIPs) \u003e 0 {\n\t\t\tnewSvc.Spec.ClusterIPs = oldSvc.Spec.ClusterIPs\n\t\t}\n\t}\n\n\tif needsNodePort(oldSvc) \u0026\u0026 needsNodePort(newSvc) {\n\t\tnodePortsUsed := func(svc *api.Service) sets.Int32 {\n\t\t\tused := sets.NewInt32()\n\t\t\tfor _, p := range svc.Spec.Ports {\n\t\t\t\tif p.NodePort != 0 {\n\t\t\t\t\tused.Insert(p.NodePort)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn used\n\t\t}\n\n\t\t// Build a set of all the ports in oldSvc that are also in newSvc. We know\n\t\t// we can't patch these values.\n\t\tused := nodePortsUsed(oldSvc).Intersection(nodePortsUsed(newSvc))\n\n\t\t// Map NodePorts by name. The user may have changed other properties\n\t\t// of the port, but we won't see that here.\n\t\tnp := map[string]int32{}\n\t\tfor i := range oldSvc.Spec.Ports {\n\t\t\tp := \u0026oldSvc.Spec.Ports[i]\n\t\t\tnp[p.Name] = p.NodePort\n\t\t}\n\n\t\t// If newSvc is missing values, try to patch them in when we know them and\n\t\t// they haven't been used for another port.\n\n\t\tfor i := range newSvc.Spec.Ports {\n\t\t\tp := \u0026newSvc.Spec.Ports[i]\n\t\t\tif p.NodePort == 0 {\n\t\t\t\toldVal := np[p.Name]\n\t\t\t\tif !used.Has(oldVal) {\n\t\t\t\t\tp.NodePort = oldVal\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif needsHCNodePort(oldSvc) \u0026\u0026 needsHCNodePort(newSvc) {\n\t\tif newSvc.Spec.HealthCheckNodePort == 0 {\n\t\t\tnewSvc.Spec.HealthCheckNodePort = oldSvc.Spec.HealthCheckNodePort\n\t\t}\n\t}\n}","line":{"from":578,"to":636}} {"id":100009945,"name":"needsClusterIP","signature":"func needsClusterIP(svc *api.Service) bool","file":"pkg/registry/core/service/storage/storage.go","code":"func needsClusterIP(svc *api.Service) bool {\n\tif svc.Spec.Type == api.ServiceTypeExternalName {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":638,"to":643}} {"id":100009946,"name":"needsNodePort","signature":"func needsNodePort(svc *api.Service) bool","file":"pkg/registry/core/service/storage/storage.go","code":"func needsNodePort(svc *api.Service) bool {\n\tif svc.Spec.Type == api.ServiceTypeNodePort || svc.Spec.Type == api.ServiceTypeLoadBalancer {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":645,"to":650}} {"id":100009947,"name":"needsHCNodePort","signature":"func needsHCNodePort(svc *api.Service) bool","file":"pkg/registry/core/service/storage/storage.go","code":"func needsHCNodePort(svc *api.Service) bool {\n\tif svc.Spec.Type != api.ServiceTypeLoadBalancer {\n\t\treturn false\n\t}\n\tif svc.Spec.ExternalTrafficPolicy != api.ServiceExternalTrafficPolicyLocal {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":652,"to":660}} {"id":100009948,"name":"Commit","signature":"func (mt metaTransaction) Commit()","file":"pkg/registry/core/service/storage/transaction.go","code":"func (mt metaTransaction) Commit() {\n\tfor _, t := range mt {\n\t\tt.Commit()\n\t}\n}","line":{"from":34,"to":38}} {"id":100009949,"name":"Revert","signature":"func (mt metaTransaction) Revert()","file":"pkg/registry/core/service/storage/transaction.go","code":"func (mt metaTransaction) Revert() {\n\tfor _, t := range mt {\n\t\tt.Revert()\n\t}\n}","line":{"from":40,"to":44}} {"id":100009950,"name":"Commit","signature":"func (cb callbackTransaction) Commit()","file":"pkg/registry/core/service/storage/transaction.go","code":"func (cb callbackTransaction) Commit() {\n\tif cb.commit != nil {\n\t\tcb.commit()\n\t}\n}","line":{"from":52,"to":56}} {"id":100009951,"name":"Revert","signature":"func (cb callbackTransaction) Revert()","file":"pkg/registry/core/service/storage/transaction.go","code":"func (cb callbackTransaction) Revert() {\n\tif cb.revert != nil {\n\t\tcb.revert()\n\t}\n}","line":{"from":58,"to":62}} {"id":100009952,"name":"NamespaceScoped","signature":"func (svcStrategy) NamespaceScoped() bool","file":"pkg/registry/core/service/strategy.go","code":"// NamespaceScoped is true for services.\nfunc (svcStrategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":45,"to":48}} {"id":100009953,"name":"GetResetFields","signature":"func (svcStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/service/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (svcStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":50,"to":60}} {"id":100009954,"name":"PrepareForCreate","signature":"func (svcStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/core/service/strategy.go","code":"// PrepareForCreate sets contextual defaults and clears fields that are not allowed to be set by end users on creation.\nfunc (svcStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tservice := obj.(*api.Service)\n\tservice.Status = api.ServiceStatus{}\n\n\tdropServiceDisabledFields(service, nil)\n}","line":{"from":62,"to":68}} {"id":100009955,"name":"PrepareForUpdate","signature":"func (svcStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/core/service/strategy.go","code":"// PrepareForUpdate sets contextual defaults and clears fields that are not allowed to be set by end users on update.\nfunc (svcStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewService := obj.(*api.Service)\n\toldService := old.(*api.Service)\n\tnewService.Status = oldService.Status\n\n\tdropServiceDisabledFields(newService, oldService)\n\tdropTypeDependentFields(newService, oldService)\n}","line":{"from":70,"to":78}} {"id":100009956,"name":"Validate","signature":"func (svcStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/core/service/strategy.go","code":"// Validate validates a new service.\nfunc (svcStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tservice := obj.(*api.Service)\n\tallErrs := validation.ValidateServiceCreate(service)\n\treturn allErrs\n}","line":{"from":80,"to":85}} {"id":100009957,"name":"WarningsOnCreate","signature":"func (svcStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/core/service/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (svcStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn serviceapi.GetWarningsForService(obj.(*api.Service), nil)\n}","line":{"from":87,"to":90}} {"id":100009958,"name":"Canonicalize","signature":"func (svcStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/core/service/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (svcStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":92,"to":94}} {"id":100009959,"name":"AllowCreateOnUpdate","signature":"func (svcStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/core/service/strategy.go","code":"func (svcStrategy) AllowCreateOnUpdate() bool {\n\treturn true\n}","line":{"from":96,"to":98}} {"id":100009960,"name":"ValidateUpdate","signature":"func (strategy svcStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/core/service/strategy.go","code":"func (strategy svcStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tallErrs := validation.ValidateServiceUpdate(obj.(*api.Service), old.(*api.Service))\n\treturn allErrs\n}","line":{"from":100,"to":103}} {"id":100009961,"name":"WarningsOnUpdate","signature":"func (svcStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/core/service/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (svcStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn serviceapi.GetWarningsForService(obj.(*api.Service), old.(*api.Service))\n}","line":{"from":105,"to":108}} {"id":100009962,"name":"AllowUnconditionalUpdate","signature":"func (svcStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/core/service/strategy.go","code":"func (svcStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":110,"to":112}} {"id":100009963,"name":"dropServiceDisabledFields","signature":"func dropServiceDisabledFields(newSvc *api.Service, oldSvc *api.Service)","file":"pkg/registry/core/service/strategy.go","code":"// dropServiceDisabledFields drops fields that are not used if their associated feature gates\n// are not enabled. The typical pattern is:\n//\n//\tif !utilfeature.DefaultFeatureGate.Enabled(features.MyFeature) \u0026\u0026 !myFeatureInUse(oldSvc) {\n//\t newSvc.Spec.MyFeature = nil\n//\t}\nfunc dropServiceDisabledFields(newSvc *api.Service, oldSvc *api.Service) {\n\n}","line":{"from":114,"to":122}} {"id":100009964,"name":"GetResetFields","signature":"func (serviceStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/core/service/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (serviceStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":131,"to":141}} {"id":100009965,"name":"PrepareForUpdate","signature":"func (serviceStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/core/service/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update of status\nfunc (serviceStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewService := obj.(*api.Service)\n\toldService := old.(*api.Service)\n\t// status changes are not allowed to update spec\n\tnewService.Spec = oldService.Spec\n}","line":{"from":143,"to":149}} {"id":100009966,"name":"ValidateUpdate","signature":"func (serviceStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/core/service/strategy.go","code":"// ValidateUpdate is the default update validation for an end user updating status\nfunc (serviceStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateServiceStatusUpdate(obj.(*api.Service), old.(*api.Service))\n}","line":{"from":151,"to":154}} {"id":100009967,"name":"WarningsOnUpdate","signature":"func (serviceStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/core/service/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (serviceStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":156,"to":159}} {"id":100009968,"name":"sameStringSlice","signature":"func sameStringSlice(a []string, b []string) bool","file":"pkg/registry/core/service/strategy.go","code":"func sameStringSlice(a []string, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":161,"to":171}} {"id":100009969,"name":"dropTypeDependentFields","signature":"func dropTypeDependentFields(newSvc *api.Service, oldSvc *api.Service)","file":"pkg/registry/core/service/strategy.go","code":"// This is an unusual case. Service has a number of inter-related fields and\n// in order to avoid breaking clients we try really hard to infer what users\n// mean when they change them.\n//\n// Services are effectively a discriminated union, where `type` is the\n// discriminator. Some fields just don't make sense with some types, so we\n// clear them.\n//\n// As a rule, we almost never change user input. This can get tricky when APIs\n// evolve and new dependent fields are added. This specific case includes\n// fields that are allocated from a pool and need to be released. Anyone who\n// is contemplating copying this pattern should think REALLY hard about almost\n// any other option.\nfunc dropTypeDependentFields(newSvc *api.Service, oldSvc *api.Service) {\n\t// For now we are only wiping on updates. This minimizes potential\n\t// confusion since many of the cases we are handling here are pretty niche.\n\tif oldSvc == nil {\n\t\treturn\n\t}\n\n\t// In all of these cases we only want to wipe a field if we a) know it no\n\t// longer applies; b) might have initialized it automatically; c) know the\n\t// user did not ALSO try to change it (in which case it should fail in\n\t// validation).\n\n\t// If the user is switching to a type that does not need a value in\n\t// clusterIP/clusterIPs (even \"None\" counts as a value), we might be able\n\t// to wipe some fields.\n\tif needsClusterIP(oldSvc) \u0026\u0026 !needsClusterIP(newSvc) {\n\t\tif sameClusterIPs(oldSvc, newSvc) {\n\t\t\t// These will be deallocated later.\n\t\t\tnewSvc.Spec.ClusterIP = \"\"\n\t\t\tnewSvc.Spec.ClusterIPs = nil\n\t\t}\n\t\tif sameIPFamilies(oldSvc, newSvc) {\n\t\t\tnewSvc.Spec.IPFamilies = nil\n\t\t}\n\t\tif sameIPFamilyPolicy(oldSvc, newSvc) {\n\t\t\tnewSvc.Spec.IPFamilyPolicy = nil\n\t\t}\n\t}\n\n\t// If the user is switching to a type that doesn't use NodePorts AND they\n\t// did not change any NodePort values, we can wipe them. They will be\n\t// deallocated later.\n\tif needsNodePort(oldSvc) \u0026\u0026 !needsNodePort(newSvc) \u0026\u0026 sameNodePorts(oldSvc, newSvc) {\n\t\tfor i := range newSvc.Spec.Ports {\n\t\t\tnewSvc.Spec.Ports[i].NodePort = 0\n\t\t}\n\t}\n\n\t// If the user is switching to a case that doesn't use HealthCheckNodePort AND they\n\t// did not change the HealthCheckNodePort value, we can wipe it. It will\n\t// be deallocated later.\n\tif needsHCNodePort(oldSvc) \u0026\u0026 !needsHCNodePort(newSvc) \u0026\u0026 sameHCNodePort(oldSvc, newSvc) {\n\t\tnewSvc.Spec.HealthCheckNodePort = 0\n\t}\n\n\t// If a user is switching to a type that doesn't need allocatedLoadBalancerNodePorts AND they did not change\n\t// this field, it is safe to drop it.\n\tif oldSvc.Spec.Type == api.ServiceTypeLoadBalancer \u0026\u0026 newSvc.Spec.Type != api.ServiceTypeLoadBalancer {\n\t\tif newSvc.Spec.AllocateLoadBalancerNodePorts != nil \u0026\u0026 oldSvc.Spec.AllocateLoadBalancerNodePorts != nil {\n\t\t\tif *oldSvc.Spec.AllocateLoadBalancerNodePorts == *newSvc.Spec.AllocateLoadBalancerNodePorts {\n\t\t\t\tnewSvc.Spec.AllocateLoadBalancerNodePorts = nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// If a user is switching to a type that doesn't need LoadBalancerClass AND they did not change\n\t// this field, it is safe to drop it.\n\tif canSetLoadBalancerClass(oldSvc) \u0026\u0026 !canSetLoadBalancerClass(newSvc) \u0026\u0026 sameLoadBalancerClass(oldSvc, newSvc) {\n\t\tnewSvc.Spec.LoadBalancerClass = nil\n\t}\n\n\t// If a user is switching to a type that doesn't need ExternalTrafficPolicy\n\t// AND they did not change this field, it is safe to drop it.\n\tif needsExternalTrafficPolicy(oldSvc) \u0026\u0026 !needsExternalTrafficPolicy(newSvc) \u0026\u0026 sameExternalTrafficPolicy(oldSvc, newSvc) {\n\t\tnewSvc.Spec.ExternalTrafficPolicy = api.ServiceExternalTrafficPolicy(\"\")\n\t}\n\n\t// NOTE: there are other fields like `selector` which we could wipe.\n\t// Historically we did not wipe them and they are not allocated from\n\t// finite pools, so we are (currently) choosing to leave them alone.\n\n\t// Clear the load-balancer status if it is no longer appropriate. Although\n\t// LB de-provisioning is actually asynchronous, we don't need to expose the\n\t// user to that complexity.\n\tif newSvc.Spec.Type != api.ServiceTypeLoadBalancer {\n\t\tnewSvc.Status.LoadBalancer = api.LoadBalancerStatus{}\n\t}\n}","line":{"from":173,"to":263}} {"id":100009970,"name":"needsClusterIP","signature":"func needsClusterIP(svc *api.Service) bool","file":"pkg/registry/core/service/strategy.go","code":"func needsClusterIP(svc *api.Service) bool {\n\tif svc.Spec.Type == api.ServiceTypeExternalName {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":265,"to":270}} {"id":100009971,"name":"sameClusterIPs","signature":"func sameClusterIPs(oldSvc, newSvc *api.Service) bool","file":"pkg/registry/core/service/strategy.go","code":"func sameClusterIPs(oldSvc, newSvc *api.Service) bool {\n\tsameSingular := oldSvc.Spec.ClusterIP == newSvc.Spec.ClusterIP\n\tsamePlural := sameStringSlice(oldSvc.Spec.ClusterIPs, newSvc.Spec.ClusterIPs)\n\treturn sameSingular \u0026\u0026 samePlural\n}","line":{"from":272,"to":276}} {"id":100009972,"name":"sameIPFamilies","signature":"func sameIPFamilies(oldSvc, newSvc *api.Service) bool","file":"pkg/registry/core/service/strategy.go","code":"func sameIPFamilies(oldSvc, newSvc *api.Service) bool {\n\treturn reflect.DeepEqual(oldSvc.Spec.IPFamilies, newSvc.Spec.IPFamilies)\n}","line":{"from":278,"to":280}} {"id":100009973,"name":"getIPFamilyPolicy","signature":"func getIPFamilyPolicy(svc *api.Service) string","file":"pkg/registry/core/service/strategy.go","code":"func getIPFamilyPolicy(svc *api.Service) string {\n\tif svc.Spec.IPFamilyPolicy == nil {\n\t\treturn \"\"\n\t}\n\treturn string(*svc.Spec.IPFamilyPolicy)\n}","line":{"from":282,"to":287}} {"id":100009974,"name":"sameIPFamilyPolicy","signature":"func sameIPFamilyPolicy(oldSvc, newSvc *api.Service) bool","file":"pkg/registry/core/service/strategy.go","code":"func sameIPFamilyPolicy(oldSvc, newSvc *api.Service) bool {\n\treturn getIPFamilyPolicy(oldSvc) == getIPFamilyPolicy(newSvc)\n}","line":{"from":289,"to":291}} {"id":100009975,"name":"needsNodePort","signature":"func needsNodePort(svc *api.Service) bool","file":"pkg/registry/core/service/strategy.go","code":"func needsNodePort(svc *api.Service) bool {\n\tif svc.Spec.Type == api.ServiceTypeNodePort || svc.Spec.Type == api.ServiceTypeLoadBalancer {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":293,"to":298}} {"id":100009976,"name":"sameNodePorts","signature":"func sameNodePorts(oldSvc, newSvc *api.Service) bool","file":"pkg/registry/core/service/strategy.go","code":"func sameNodePorts(oldSvc, newSvc *api.Service) bool {\n\t// Helper to make a set of NodePort values.\n\tallNodePorts := func(svc *api.Service) sets.Int {\n\t\tout := sets.NewInt()\n\t\tfor i := range svc.Spec.Ports {\n\t\t\tif svc.Spec.Ports[i].NodePort != 0 {\n\t\t\t\tout.Insert(int(svc.Spec.Ports[i].NodePort))\n\t\t\t}\n\t\t}\n\t\treturn out\n\t}\n\n\toldPorts := allNodePorts(oldSvc)\n\tnewPorts := allNodePorts(newSvc)\n\n\t// Users can add, remove, or modify ports, as long as they don't add any\n\t// net-new NodePorts.\n\treturn oldPorts.IsSuperset(newPorts)\n}","line":{"from":300,"to":318}} {"id":100009977,"name":"needsHCNodePort","signature":"func needsHCNodePort(svc *api.Service) bool","file":"pkg/registry/core/service/strategy.go","code":"func needsHCNodePort(svc *api.Service) bool {\n\tif svc.Spec.Type != api.ServiceTypeLoadBalancer {\n\t\treturn false\n\t}\n\tif svc.Spec.ExternalTrafficPolicy != api.ServiceExternalTrafficPolicyLocal {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":320,"to":328}} {"id":100009978,"name":"sameHCNodePort","signature":"func sameHCNodePort(oldSvc, newSvc *api.Service) bool","file":"pkg/registry/core/service/strategy.go","code":"func sameHCNodePort(oldSvc, newSvc *api.Service) bool {\n\treturn oldSvc.Spec.HealthCheckNodePort == newSvc.Spec.HealthCheckNodePort\n}","line":{"from":330,"to":332}} {"id":100009979,"name":"canSetLoadBalancerClass","signature":"func canSetLoadBalancerClass(svc *api.Service) bool","file":"pkg/registry/core/service/strategy.go","code":"func canSetLoadBalancerClass(svc *api.Service) bool {\n\treturn svc.Spec.Type == api.ServiceTypeLoadBalancer\n}","line":{"from":334,"to":336}} {"id":100009980,"name":"sameLoadBalancerClass","signature":"func sameLoadBalancerClass(oldSvc, newSvc *api.Service) bool","file":"pkg/registry/core/service/strategy.go","code":"func sameLoadBalancerClass(oldSvc, newSvc *api.Service) bool {\n\tif (oldSvc.Spec.LoadBalancerClass == nil) != (newSvc.Spec.LoadBalancerClass == nil) {\n\t\treturn false\n\t}\n\tif oldSvc.Spec.LoadBalancerClass == nil {\n\t\treturn true // both are nil\n\t}\n\treturn *oldSvc.Spec.LoadBalancerClass == *newSvc.Spec.LoadBalancerClass\n}","line":{"from":338,"to":346}} {"id":100009981,"name":"needsExternalTrafficPolicy","signature":"func needsExternalTrafficPolicy(svc *api.Service) bool","file":"pkg/registry/core/service/strategy.go","code":"func needsExternalTrafficPolicy(svc *api.Service) bool {\n\treturn svc.Spec.Type == api.ServiceTypeNodePort || svc.Spec.Type == api.ServiceTypeLoadBalancer\n}","line":{"from":348,"to":350}} {"id":100009982,"name":"sameExternalTrafficPolicy","signature":"func sameExternalTrafficPolicy(oldSvc, newSvc *api.Service) bool","file":"pkg/registry/core/service/strategy.go","code":"func sameExternalTrafficPolicy(oldSvc, newSvc *api.Service) bool {\n\treturn oldSvc.Spec.ExternalTrafficPolicy == newSvc.Spec.ExternalTrafficPolicy\n}","line":{"from":352,"to":354}} {"id":100009983,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter, issuer token.TokenGenerator, auds authenticator.Audiences, max time.Duration, podStorage, secretStorage *genericregistry.Store, extendExpiration bool) (*REST, error)","file":"pkg/registry/core/serviceaccount/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against service accounts.\nfunc NewREST(optsGetter generic.RESTOptionsGetter, issuer token.TokenGenerator, auds authenticator.Audiences, max time.Duration, podStorage, secretStorage *genericregistry.Store, extendExpiration bool) (*REST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026api.ServiceAccount{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026api.ServiceAccountList{} },\n\t\tDefaultQualifiedResource: api.Resource(\"serviceaccounts\"),\n\t\tSingularQualifiedResource: api.Resource(\"serviceaccount\"),\n\n\t\tCreateStrategy: serviceaccount.Strategy,\n\t\tUpdateStrategy: serviceaccount.Strategy,\n\t\tDeleteStrategy: serviceaccount.Strategy,\n\t\tReturnDeletedObject: true,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar trest *TokenREST\n\tif issuer != nil \u0026\u0026 podStorage != nil \u0026\u0026 secretStorage != nil {\n\t\ttrest = \u0026TokenREST{\n\t\t\tsvcaccts: store,\n\t\t\tpods: podStorage,\n\t\t\tsecrets: secretStorage,\n\t\t\tissuer: issuer,\n\t\t\tauds: auds,\n\t\t\taudsSet: sets.NewString(auds...),\n\t\t\tmaxExpirationSeconds: int64(max.Seconds()),\n\t\t\textendExpiration: extendExpiration,\n\t\t}\n\t}\n\n\treturn \u0026REST{\n\t\tStore: store,\n\t\tToken: trest,\n\t}, nil\n}","line":{"from":41,"to":79}} {"id":100009984,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/core/serviceaccount/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"sa\"}\n}","line":{"from":84,"to":87}} {"id":100009985,"name":"New","signature":"func (r *TokenREST) New() runtime.Object","file":"pkg/registry/core/serviceaccount/storage/token.go","code":"func (r *TokenREST) New() runtime.Object {\n\treturn \u0026authenticationapi.TokenRequest{}\n}","line":{"from":42,"to":44}} {"id":100009986,"name":"Destroy","signature":"func (r *TokenREST) Destroy()","file":"pkg/registry/core/serviceaccount/storage/token.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *TokenREST) Destroy() {\n\t// Given no underlying store, we don't destroy anything\n\t// here explicitly.\n}","line":{"from":46,"to":50}} {"id":100009987,"name":"Create","signature":"func (r *TokenREST) Create(ctx context.Context, name string, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error)","file":"pkg/registry/core/serviceaccount/storage/token.go","code":"func (r *TokenREST) Create(ctx context.Context, name string, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {\n\treq := obj.(*authenticationapi.TokenRequest)\n\n\t// Get the namespace from the context (populated from the URL).\n\tnamespace, ok := genericapirequest.NamespaceFrom(ctx)\n\tif !ok {\n\t\treturn nil, errors.NewBadRequest(\"namespace is required\")\n\t}\n\n\t// require name/namespace in the body to match URL if specified\n\tif len(req.Name) \u003e 0 \u0026\u0026 req.Name != name {\n\t\terrs := field.ErrorList{field.Invalid(field.NewPath(\"metadata\").Child(\"name\"), req.Name, \"must match the service account name if specified\")}\n\t\treturn nil, errors.NewInvalid(gvk.GroupKind(), name, errs)\n\t}\n\tif len(req.Namespace) \u003e 0 \u0026\u0026 req.Namespace != namespace {\n\t\terrs := field.ErrorList{field.Invalid(field.NewPath(\"metadata\").Child(\"namespace\"), req.Namespace, \"must match the service account namespace if specified\")}\n\t\treturn nil, errors.NewInvalid(gvk.GroupKind(), name, errs)\n\t}\n\n\t// Lookup service account\n\tsvcacctObj, err := r.svcaccts.Get(ctx, name, \u0026metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsvcacct := svcacctObj.(*api.ServiceAccount)\n\n\t// Default unset spec audiences to API server audiences based on server config\n\tif len(req.Spec.Audiences) == 0 {\n\t\treq.Spec.Audiences = r.auds\n\t}\n\t// Populate metadata fields if not set\n\tif len(req.Name) == 0 {\n\t\treq.Name = svcacct.Name\n\t}\n\tif len(req.Namespace) == 0 {\n\t\treq.Namespace = svcacct.Namespace\n\t}\n\n\t// Save current time before building the token, to make sure the expiration\n\t// returned in TokenRequestStatus would be \u003c= the exp field in token.\n\tnowTime := time.Now()\n\treq.CreationTimestamp = metav1.NewTime(nowTime)\n\n\t// Clear status\n\treq.Status = authenticationapi.TokenRequestStatus{}\n\n\t// call static validation, then validating admission\n\tif errs := authenticationvalidation.ValidateTokenRequest(req); len(errs) != 0 {\n\t\treturn nil, errors.NewInvalid(gvk.GroupKind(), \"\", errs)\n\t}\n\tif createValidation != nil {\n\t\tif err := createValidation(ctx, obj.DeepCopyObject()); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tvar (\n\t\tpod *api.Pod\n\t\tsecret *api.Secret\n\t)\n\n\tif ref := req.Spec.BoundObjectRef; ref != nil {\n\t\tvar uid types.UID\n\n\t\tgvk := schema.FromAPIVersionAndKind(ref.APIVersion, ref.Kind)\n\t\tswitch {\n\t\tcase gvk.Group == \"\" \u0026\u0026 gvk.Kind == \"Pod\":\n\t\t\tnewCtx := newContext(ctx, \"pods\", ref.Name, gvk)\n\t\t\tpodObj, err := r.pods.Get(newCtx, ref.Name, \u0026metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tpod = podObj.(*api.Pod)\n\t\t\tif name != pod.Spec.ServiceAccountName {\n\t\t\t\treturn nil, errors.NewBadRequest(fmt.Sprintf(\"cannot bind token for serviceaccount %q to pod running with different serviceaccount name.\", name))\n\t\t\t}\n\t\t\tuid = pod.UID\n\t\tcase gvk.Group == \"\" \u0026\u0026 gvk.Kind == \"Secret\":\n\t\t\tnewCtx := newContext(ctx, \"secrets\", ref.Name, gvk)\n\t\t\tsecretObj, err := r.secrets.Get(newCtx, ref.Name, \u0026metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tsecret = secretObj.(*api.Secret)\n\t\t\tuid = secret.UID\n\t\tdefault:\n\t\t\treturn nil, errors.NewBadRequest(fmt.Sprintf(\"cannot bind token to object of type %s\", gvk.String()))\n\t\t}\n\t\tif ref.UID != \"\" \u0026\u0026 uid != ref.UID {\n\t\t\treturn nil, errors.NewConflict(schema.GroupResource{Group: gvk.Group, Resource: gvk.Kind}, ref.Name, fmt.Errorf(\"the UID in the bound object reference (%s) does not match the UID in record. The object might have been deleted and then recreated\", ref.UID))\n\t\t}\n\t}\n\n\tif r.maxExpirationSeconds \u003e 0 \u0026\u0026 req.Spec.ExpirationSeconds \u003e r.maxExpirationSeconds {\n\t\t//only positive value is valid\n\t\twarning.AddWarning(ctx, \"\", fmt.Sprintf(\"requested expiration of %d seconds shortened to %d seconds\", req.Spec.ExpirationSeconds, r.maxExpirationSeconds))\n\t\treq.Spec.ExpirationSeconds = r.maxExpirationSeconds\n\t}\n\n\t// Tweak expiration for safe transition of projected service account token.\n\t// Warn (instead of fail) after requested expiration time.\n\t// Fail after hard-coded extended expiration time.\n\t// Only perform the extension when token is pod-bound.\n\tvar warnAfter int64\n\texp := req.Spec.ExpirationSeconds\n\tif r.extendExpiration \u0026\u0026 pod != nil \u0026\u0026 req.Spec.ExpirationSeconds == token.WarnOnlyBoundTokenExpirationSeconds \u0026\u0026 r.isKubeAudiences(req.Spec.Audiences) {\n\t\twarnAfter = exp\n\t\texp = token.ExpirationExtensionSeconds\n\t}\n\n\tsc, pc := token.Claims(*svcacct, pod, secret, exp, warnAfter, req.Spec.Audiences)\n\ttokdata, err := r.issuer.GenerateToken(sc, pc)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to generate token: %v\", err)\n\t}\n\n\t// populate status\n\tout := req.DeepCopy()\n\tout.Status = authenticationapi.TokenRequestStatus{\n\t\tToken: tokdata,\n\t\tExpirationTimestamp: metav1.Time{Time: nowTime.Add(time.Duration(out.Spec.ExpirationSeconds) * time.Second)},\n\t}\n\treturn out, nil\n}","line":{"from":72,"to":195}} {"id":100009988,"name":"GroupVersionKind","signature":"func (r *TokenREST) GroupVersionKind(schema.GroupVersion) schema.GroupVersionKind","file":"pkg/registry/core/serviceaccount/storage/token.go","code":"func (r *TokenREST) GroupVersionKind(schema.GroupVersion) schema.GroupVersionKind {\n\treturn gvk\n}","line":{"from":197,"to":199}} {"id":100009989,"name":"newContext","signature":"func newContext(ctx context.Context, resource, name string, gvk schema.GroupVersionKind) context.Context","file":"pkg/registry/core/serviceaccount/storage/token.go","code":"// newContext return a copy of ctx in which new RequestInfo is set\nfunc newContext(ctx context.Context, resource, name string, gvk schema.GroupVersionKind) context.Context {\n\toldInfo, found := genericapirequest.RequestInfoFrom(ctx)\n\tif !found {\n\t\treturn ctx\n\t}\n\tnewInfo := genericapirequest.RequestInfo{\n\t\tIsResourceRequest: true,\n\t\tVerb: \"get\",\n\t\tNamespace: oldInfo.Namespace,\n\t\tResource: resource,\n\t\tName: name,\n\t\tParts: []string{resource, name},\n\t\tAPIGroup: gvk.Group,\n\t\tAPIVersion: gvk.Version,\n\t}\n\treturn genericapirequest.WithRequestInfo(ctx, \u0026newInfo)\n}","line":{"from":205,"to":222}} {"id":100009990,"name":"isKubeAudiences","signature":"func (r *TokenREST) isKubeAudiences(tokenAudience []string) bool","file":"pkg/registry/core/serviceaccount/storage/token.go","code":"// isKubeAudiences returns true if the tokenaudiences is a strict subset of apiserver audiences.\nfunc (r *TokenREST) isKubeAudiences(tokenAudience []string) bool {\n\t// tokenAudiences must be a strict subset of apiserver audiences\n\treturn r.audsSet.HasAll(tokenAudience...)\n}","line":{"from":224,"to":228}} {"id":100009991,"name":"NamespaceScoped","signature":"func (strategy) NamespaceScoped() bool","file":"pkg/registry/core/serviceaccount/strategy.go","code":"func (strategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":40,"to":42}} {"id":100009992,"name":"PrepareForCreate","signature":"func (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/core/serviceaccount/strategy.go","code":"func (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tcleanSecretReferences(obj.(*api.ServiceAccount))\n}","line":{"from":44,"to":46}} {"id":100009993,"name":"Validate","signature":"func (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/core/serviceaccount/strategy.go","code":"func (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\treturn validation.ValidateServiceAccount(obj.(*api.ServiceAccount))\n}","line":{"from":48,"to":50}} {"id":100009994,"name":"WarningsOnCreate","signature":"func (strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return nil }","file":"pkg/registry/core/serviceaccount/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return nil }","line":{"from":52,"to":53}} {"id":100009995,"name":"Canonicalize","signature":"func (strategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/core/serviceaccount/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (strategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":55,"to":57}} {"id":100009996,"name":"AllowCreateOnUpdate","signature":"func (strategy) AllowCreateOnUpdate() bool","file":"pkg/registry/core/serviceaccount/strategy.go","code":"func (strategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":59,"to":61}} {"id":100009997,"name":"PrepareForUpdate","signature":"func (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/core/serviceaccount/strategy.go","code":"func (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tcleanSecretReferences(obj.(*api.ServiceAccount))\n}","line":{"from":63,"to":65}} {"id":100009998,"name":"cleanSecretReferences","signature":"func cleanSecretReferences(serviceAccount *api.ServiceAccount)","file":"pkg/registry/core/serviceaccount/strategy.go","code":"func cleanSecretReferences(serviceAccount *api.ServiceAccount) {\n\tfor i, secret := range serviceAccount.Secrets {\n\t\tserviceAccount.Secrets[i] = api.ObjectReference{Name: secret.Name}\n\t}\n}","line":{"from":67,"to":71}} {"id":100009999,"name":"ValidateUpdate","signature":"func (strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/core/serviceaccount/strategy.go","code":"func (strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateServiceAccountUpdate(obj.(*api.ServiceAccount), old.(*api.ServiceAccount))\n}","line":{"from":73,"to":75}} {"id":100010000,"name":"WarningsOnUpdate","signature":"func (strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/core/serviceaccount/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":77,"to":80}} {"id":100010001,"name":"AllowUnconditionalUpdate","signature":"func (strategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/core/serviceaccount/strategy.go","code":"func (strategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":82,"to":84}} {"id":100010002,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error)","file":"pkg/registry/discovery/endpointslice/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against endpoint slices.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026discovery.EndpointSlice{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026discovery.EndpointSliceList{} },\n\t\tDefaultQualifiedResource: discovery.Resource(\"endpointslices\"),\n\t\tSingularQualifiedResource: discovery.Resource(\"endpointslice\"),\n\n\t\tCreateStrategy: endpointslice.Strategy,\n\t\tUpdateStrategy: endpointslice.Strategy,\n\t\tDeleteStrategy: endpointslice.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026REST{store}, nil\n}","line":{"from":35,"to":54}} {"id":100010003,"name":"NamespaceScoped","signature":"func (endpointSliceStrategy) NamespaceScoped() bool","file":"pkg/registry/discovery/endpointslice/strategy.go","code":"// NamespaceScoped returns true because all EndpointSlices need to be within a namespace.\nfunc (endpointSliceStrategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":50,"to":53}} {"id":100010004,"name":"PrepareForCreate","signature":"func (endpointSliceStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/discovery/endpointslice/strategy.go","code":"// PrepareForCreate clears the status of an EndpointSlice before creation.\nfunc (endpointSliceStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tendpointSlice := obj.(*discovery.EndpointSlice)\n\tendpointSlice.Generation = 1\n\n\tdropDisabledFieldsOnCreate(endpointSlice)\n\tdropTopologyOnV1(ctx, nil, endpointSlice)\n}","line":{"from":55,"to":62}} {"id":100010005,"name":"PrepareForUpdate","signature":"func (endpointSliceStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/discovery/endpointslice/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (endpointSliceStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewEPS := obj.(*discovery.EndpointSlice)\n\toldEPS := old.(*discovery.EndpointSlice)\n\n\t// Increment generation if anything other than meta changed\n\t// This needs to be changed if a status attribute is added to EndpointSlice\n\togNewMeta := newEPS.ObjectMeta\n\togOldMeta := oldEPS.ObjectMeta\n\tnewEPS.ObjectMeta = metav1.ObjectMeta{}\n\toldEPS.ObjectMeta = metav1.ObjectMeta{}\n\n\tif !apiequality.Semantic.DeepEqual(newEPS, oldEPS) || !apiequality.Semantic.DeepEqual(ogNewMeta.Labels, ogOldMeta.Labels) {\n\t\togNewMeta.Generation = ogOldMeta.Generation + 1\n\t}\n\n\tnewEPS.ObjectMeta = ogNewMeta\n\toldEPS.ObjectMeta = ogOldMeta\n\n\tdropDisabledFieldsOnUpdate(oldEPS, newEPS)\n\tdropTopologyOnV1(ctx, oldEPS, newEPS)\n}","line":{"from":64,"to":85}} {"id":100010006,"name":"Validate","signature":"func (endpointSliceStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/discovery/endpointslice/strategy.go","code":"// Validate validates a new EndpointSlice.\nfunc (endpointSliceStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tendpointSlice := obj.(*discovery.EndpointSlice)\n\terr := validation.ValidateEndpointSliceCreate(endpointSlice)\n\treturn err\n}","line":{"from":87,"to":92}} {"id":100010007,"name":"WarningsOnCreate","signature":"func (endpointSliceStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/discovery/endpointslice/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (endpointSliceStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\teps := obj.(*discovery.EndpointSlice)\n\tif eps == nil {\n\t\treturn nil\n\t}\n\tvar warnings []string\n\twarnings = append(warnings, warnOnDeprecatedAddressType(eps.AddressType)...)\n\treturn warnings\n}","line":{"from":94,"to":103}} {"id":100010008,"name":"Canonicalize","signature":"func (endpointSliceStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/discovery/endpointslice/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (endpointSliceStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":105,"to":107}} {"id":100010009,"name":"AllowCreateOnUpdate","signature":"func (endpointSliceStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/discovery/endpointslice/strategy.go","code":"// AllowCreateOnUpdate is false for EndpointSlice; this means POST is needed to create one.\nfunc (endpointSliceStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":109,"to":112}} {"id":100010010,"name":"ValidateUpdate","signature":"func (endpointSliceStrategy) ValidateUpdate(ctx context.Context, new, old runtime.Object) field.ErrorList","file":"pkg/registry/discovery/endpointslice/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (endpointSliceStrategy) ValidateUpdate(ctx context.Context, new, old runtime.Object) field.ErrorList {\n\tnewEPS := new.(*discovery.EndpointSlice)\n\toldEPS := old.(*discovery.EndpointSlice)\n\treturn validation.ValidateEndpointSliceUpdate(newEPS, oldEPS)\n}","line":{"from":114,"to":119}} {"id":100010011,"name":"WarningsOnUpdate","signature":"func (endpointSliceStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/discovery/endpointslice/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (endpointSliceStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":121,"to":124}} {"id":100010012,"name":"AllowUnconditionalUpdate","signature":"func (endpointSliceStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/discovery/endpointslice/strategy.go","code":"// AllowUnconditionalUpdate is the default update policy for EndpointSlice objects.\nfunc (endpointSliceStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":126,"to":129}} {"id":100010013,"name":"dropDisabledFieldsOnCreate","signature":"func dropDisabledFieldsOnCreate(endpointSlice *discovery.EndpointSlice)","file":"pkg/registry/discovery/endpointslice/strategy.go","code":"// dropDisabledConditionsOnCreate will drop any fields that are disabled.\nfunc dropDisabledFieldsOnCreate(endpointSlice *discovery.EndpointSlice) {\n\tdropHints := !utilfeature.DefaultFeatureGate.Enabled(features.TopologyAwareHints)\n\n\tif dropHints {\n\t\tfor i := range endpointSlice.Endpoints {\n\t\t\tif dropHints {\n\t\t\t\tendpointSlice.Endpoints[i].Hints = nil\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":131,"to":142}} {"id":100010014,"name":"dropDisabledFieldsOnUpdate","signature":"func dropDisabledFieldsOnUpdate(oldEPS, newEPS *discovery.EndpointSlice)","file":"pkg/registry/discovery/endpointslice/strategy.go","code":"// dropDisabledFieldsOnUpdate will drop any disable fields that have not already\n// been set on the EndpointSlice.\nfunc dropDisabledFieldsOnUpdate(oldEPS, newEPS *discovery.EndpointSlice) {\n\tdropHints := !utilfeature.DefaultFeatureGate.Enabled(features.TopologyAwareHints)\n\tif dropHints {\n\t\tfor _, ep := range oldEPS.Endpoints {\n\t\t\tif ep.Hints != nil {\n\t\t\t\tdropHints = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif dropHints {\n\t\tfor i := range newEPS.Endpoints {\n\t\t\tif dropHints {\n\t\t\t\tnewEPS.Endpoints[i].Hints = nil\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":144,"to":164}} {"id":100010015,"name":"dropTopologyOnV1","signature":"func dropTopologyOnV1(ctx context.Context, oldEPS, newEPS *discovery.EndpointSlice)","file":"pkg/registry/discovery/endpointslice/strategy.go","code":"// dropTopologyOnV1 on V1 request wipes the DeprecatedTopology field and copies\n// the NodeName value into DeprecatedTopology\nfunc dropTopologyOnV1(ctx context.Context, oldEPS, newEPS *discovery.EndpointSlice) {\n\tif info, ok := genericapirequest.RequestInfoFrom(ctx); ok {\n\t\trequestGV := schema.GroupVersion{Group: info.APIGroup, Version: info.APIVersion}\n\t\tif requestGV == discoveryv1beta1.SchemeGroupVersion {\n\t\t\treturn\n\t\t}\n\n\t\t// do not drop topology if endpoints have not been changed\n\t\tif oldEPS != nil \u0026\u0026 apiequality.Semantic.DeepEqual(oldEPS.Endpoints, newEPS.Endpoints) {\n\t\t\treturn\n\t\t}\n\n\t\t// Only node names that exist in previous version of the EndpointSlice\n\t\t// deprecatedTopology fields may be retained in new version of the\n\t\t// EndpointSlice.\n\t\tprevNodeNames := getDeprecatedTopologyNodeNames(oldEPS)\n\n\t\tfor i := range newEPS.Endpoints {\n\t\t\tep := \u0026newEPS.Endpoints[i]\n\n\t\t\tnewTopologyNodeName, ok := ep.DeprecatedTopology[corev1.LabelHostname]\n\t\t\tif ep.NodeName == nil \u0026\u0026 ok \u0026\u0026 prevNodeNames.Has(newTopologyNodeName) \u0026\u0026 len(apivalidation.ValidateNodeName(newTopologyNodeName, false)) == 0 {\n\t\t\t\t// Copy the label previously used to store the node name into the nodeName field,\n\t\t\t\t// in order to make partial updates preserve previous node info\n\t\t\t\tep.NodeName = \u0026newTopologyNodeName\n\t\t\t}\n\t\t\t// Drop writes to this field via the v1 API as documented\n\t\t\tep.DeprecatedTopology = nil\n\t\t}\n\t}\n}","line":{"from":166,"to":198}} {"id":100010016,"name":"getDeprecatedTopologyNodeNames","signature":"func getDeprecatedTopologyNodeNames(eps *discovery.EndpointSlice) sets.String","file":"pkg/registry/discovery/endpointslice/strategy.go","code":"// getDeprecatedTopologyNodeNames returns a set of node names present in\n// deprecatedTopology fields within the provided EndpointSlice.\nfunc getDeprecatedTopologyNodeNames(eps *discovery.EndpointSlice) sets.String {\n\tif eps == nil {\n\t\treturn nil\n\t}\n\tvar names sets.String\n\tfor _, ep := range eps.Endpoints {\n\t\tif nodeName, ok := ep.DeprecatedTopology[corev1.LabelHostname]; ok \u0026\u0026 len(nodeName) \u003e 0 {\n\t\t\tif names == nil {\n\t\t\t\tnames = sets.NewString()\n\t\t\t}\n\t\t\tnames.Insert(nodeName)\n\t\t}\n\t}\n\treturn names\n}","line":{"from":200,"to":216}} {"id":100010017,"name":"warnOnDeprecatedAddressType","signature":"func warnOnDeprecatedAddressType(addressType discovery.AddressType) []string","file":"pkg/registry/discovery/endpointslice/strategy.go","code":"// warnOnDeprecatedAddressType returns a warning for endpointslices with FQDN AddressType\nfunc warnOnDeprecatedAddressType(addressType discovery.AddressType) []string {\n\tif addressType == discovery.AddressTypeFQDN {\n\t\treturn []string{fmt.Sprintf(\"%s: FQDN endpoints are deprecated\", field.NewPath(\"spec\").Child(\"addressType\"))}\n\t}\n\treturn nil\n}","line":{"from":218,"to":224}} {"id":100010018,"name":"NewRESTStorage","signature":"func (p StorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error)","file":"pkg/registry/discovery/rest/storage_discovery.go","code":"// NewRESTStorage returns a new storage provider.\nfunc (p StorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error) {\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(discovery.GroupName, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs)\n\t// If you add a version here, be sure to add an entry in `k8s.io/kubernetes/cmd/kube-apiserver/app/aggregator.go with specific priorities.\n\t// TODO refactor the plumbing to provide the information in the APIGroupInfo\n\n\tif storageMap, err := p.v1beta1Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[discoveryv1beta1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\tif storageMap, err := p.v1Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[discoveryv1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\treturn apiGroupInfo, nil\n}","line":{"from":34,"to":53}} {"id":100010019,"name":"v1beta1Storage","signature":"func (p StorageProvider) v1beta1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/discovery/rest/storage_discovery.go","code":"func (p StorageProvider) v1beta1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\tif resource := \"endpointslices\"; apiResourceConfigSource.ResourceEnabled(discoveryv1beta1.SchemeGroupVersion.WithResource(resource)) {\n\t\tendpointSliceStorage, err := endpointslicestorage.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = endpointSliceStorage\n\t}\n\n\treturn storage, nil\n}","line":{"from":55,"to":67}} {"id":100010020,"name":"v1Storage","signature":"func (p StorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/discovery/rest/storage_discovery.go","code":"func (p StorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\tif resource := \"endpointslices\"; apiResourceConfigSource.ResourceEnabled(discoveryv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tendpointSliceStorage, err := endpointslicestorage.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = endpointSliceStorage\n\t}\n\n\treturn storage, nil\n}","line":{"from":69,"to":81}} {"id":100010021,"name":"GroupName","signature":"func (p StorageProvider) GroupName() string","file":"pkg/registry/discovery/rest/storage_discovery.go","code":"// GroupName is the group name for the storage provider.\nfunc (p StorageProvider) GroupName() string {\n\treturn discovery.GroupName\n}","line":{"from":83,"to":86}} {"id":100010022,"name":"NewRESTStorage","signature":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error)","file":"pkg/registry/events/rest/storage_events.go","code":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error) {\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(events.GroupName, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs)\n\t// If you add a version here, be sure to add an entry in `k8s.io/kubernetes/cmd/kube-apiserver/app/aggregator.go with specific priorities.\n\t// TODO refactor the plumbing to provide the information in the APIGroupInfo\n\n\tif storageMap, err := p.v1beta1Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[eventsapiv1beta1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\tif storageMap, err := p.v1Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[eventsapiv1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\treturn apiGroupInfo, nil\n}","line":{"from":37,"to":55}} {"id":100010023,"name":"v1beta1Storage","signature":"func (p RESTStorageProvider) v1beta1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/events/rest/storage_events.go","code":"func (p RESTStorageProvider) v1beta1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\t// events\n\tif resource := \"events\"; apiResourceConfigSource.ResourceEnabled(eventsapiv1beta1.SchemeGroupVersion.WithResource(resource)) {\n\t\teventsStorage, err := eventstore.NewREST(restOptionsGetter, uint64(p.TTL.Seconds()))\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = eventsStorage\n\t}\n\n\treturn storage, nil\n}","line":{"from":57,"to":70}} {"id":100010024,"name":"v1Storage","signature":"func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/events/rest/storage_events.go","code":"func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\t// events\n\tif resource := \"events\"; apiResourceConfigSource.ResourceEnabled(eventsapiv1.SchemeGroupVersion.WithResource(resource)) {\n\t\teventsStorage, err := eventstore.NewREST(restOptionsGetter, uint64(p.TTL.Seconds()))\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = eventsStorage\n\t}\n\n\treturn storage, nil\n}","line":{"from":72,"to":85}} {"id":100010025,"name":"GroupName","signature":"func (p RESTStorageProvider) GroupName() string","file":"pkg/registry/events/rest/storage_events.go","code":"func (p RESTStorageProvider) GroupName() string {\n\treturn events.GroupName\n}","line":{"from":87,"to":89}} {"id":100010026,"name":"NewSuggestedFlowSchemaEnsurer","signature":"func NewSuggestedFlowSchemaEnsurer(client flowcontrolclient.FlowSchemaInterface, lister flowcontrollisters.FlowSchemaLister) FlowSchemaEnsurer","file":"pkg/registry/flowcontrol/ensurer/flowschema.go","code":"// NewSuggestedFlowSchemaEnsurer returns a FlowSchemaEnsurer instance that\n// can be used to ensure a set of suggested FlowSchema configuration objects.\nfunc NewSuggestedFlowSchemaEnsurer(client flowcontrolclient.FlowSchemaInterface, lister flowcontrollisters.FlowSchemaLister) FlowSchemaEnsurer {\n\twrapper := \u0026flowSchemaWrapper{\n\t\tclient: client,\n\t\tlister: lister,\n\t}\n\treturn \u0026fsEnsurer{\n\t\tstrategy: newSuggestedEnsureStrategy(wrapper),\n\t\twrapper: wrapper,\n\t}\n}","line":{"from":54,"to":65}} {"id":100010027,"name":"NewMandatoryFlowSchemaEnsurer","signature":"func NewMandatoryFlowSchemaEnsurer(client flowcontrolclient.FlowSchemaInterface, lister flowcontrollisters.FlowSchemaLister) FlowSchemaEnsurer","file":"pkg/registry/flowcontrol/ensurer/flowschema.go","code":"// NewMandatoryFlowSchemaEnsurer returns a FlowSchemaEnsurer instance that\n// can be used to ensure a set of mandatory FlowSchema configuration objects.\nfunc NewMandatoryFlowSchemaEnsurer(client flowcontrolclient.FlowSchemaInterface, lister flowcontrollisters.FlowSchemaLister) FlowSchemaEnsurer {\n\twrapper := \u0026flowSchemaWrapper{\n\t\tclient: client,\n\t\tlister: lister,\n\t}\n\treturn \u0026fsEnsurer{\n\t\tstrategy: newMandatoryEnsureStrategy(wrapper),\n\t\twrapper: wrapper,\n\t}\n}","line":{"from":67,"to":78}} {"id":100010028,"name":"NewFlowSchemaRemover","signature":"func NewFlowSchemaRemover(client flowcontrolclient.FlowSchemaInterface, lister flowcontrollisters.FlowSchemaLister) FlowSchemaRemover","file":"pkg/registry/flowcontrol/ensurer/flowschema.go","code":"// NewFlowSchemaRemover returns a FlowSchemaRemover instance that\n// can be used to remove a set of FlowSchema configuration objects.\nfunc NewFlowSchemaRemover(client flowcontrolclient.FlowSchemaInterface, lister flowcontrollisters.FlowSchemaLister) FlowSchemaRemover {\n\treturn \u0026fsEnsurer{\n\t\twrapper: \u0026flowSchemaWrapper{\n\t\t\tclient: client,\n\t\t\tlister: lister,\n\t\t},\n\t}\n}","line":{"from":80,"to":89}} {"id":100010029,"name":"GetFlowSchemaRemoveCandidates","signature":"func GetFlowSchemaRemoveCandidates(lister flowcontrollisters.FlowSchemaLister, bootstrap []*flowcontrolv1beta3.FlowSchema) ([]string, error)","file":"pkg/registry/flowcontrol/ensurer/flowschema.go","code":"// GetFlowSchemaRemoveCandidates returns a list of FlowSchema object\n// names that are candidates for deletion from the cluster.\n// bootstrap: a set of hard coded FlowSchema configuration objects\n// kube-apiserver maintains in-memory.\nfunc GetFlowSchemaRemoveCandidates(lister flowcontrollisters.FlowSchemaLister, bootstrap []*flowcontrolv1beta3.FlowSchema) ([]string, error) {\n\tfsList, err := lister.List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to list FlowSchema - %w\", err)\n\t}\n\n\tbootstrapNames := sets.String{}\n\tfor i := range bootstrap {\n\t\tbootstrapNames.Insert(bootstrap[i].GetName())\n\t}\n\n\tcurrentObjects := make([]metav1.Object, len(fsList))\n\tfor i := range fsList {\n\t\tcurrentObjects[i] = fsList[i]\n\t}\n\n\treturn getDanglingBootstrapObjectNames(bootstrapNames, currentObjects), nil\n}","line":{"from":91,"to":112}} {"id":100010030,"name":"Ensure","signature":"func (e *fsEnsurer) Ensure(flowSchemas []*flowcontrolv1beta3.FlowSchema) error","file":"pkg/registry/flowcontrol/ensurer/flowschema.go","code":"func (e *fsEnsurer) Ensure(flowSchemas []*flowcontrolv1beta3.FlowSchema) error {\n\tfor _, flowSchema := range flowSchemas {\n\t\tif err := ensureConfiguration(e.wrapper, e.strategy, flowSchema); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":119,"to":127}} {"id":100010031,"name":"RemoveAutoUpdateEnabledObjects","signature":"func (e *fsEnsurer) RemoveAutoUpdateEnabledObjects(flowSchemas []string) error","file":"pkg/registry/flowcontrol/ensurer/flowschema.go","code":"func (e *fsEnsurer) RemoveAutoUpdateEnabledObjects(flowSchemas []string) error {\n\tfor _, flowSchema := range flowSchemas {\n\t\tif err := removeAutoUpdateEnabledConfiguration(e.wrapper, flowSchema); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":129,"to":137}} {"id":100010032,"name":"TypeName","signature":"func (fs *flowSchemaWrapper) TypeName() string","file":"pkg/registry/flowcontrol/ensurer/flowschema.go","code":"func (fs *flowSchemaWrapper) TypeName() string {\n\treturn \"FlowSchema\"\n}","line":{"from":146,"to":148}} {"id":100010033,"name":"Create","signature":"func (fs *flowSchemaWrapper) Create(object runtime.Object) (runtime.Object, error)","file":"pkg/registry/flowcontrol/ensurer/flowschema.go","code":"func (fs *flowSchemaWrapper) Create(object runtime.Object) (runtime.Object, error) {\n\tfsObject, ok := object.(*flowcontrolv1beta3.FlowSchema)\n\tif !ok {\n\t\treturn nil, errObjectNotFlowSchema\n\t}\n\n\treturn fs.client.Create(context.TODO(), fsObject, metav1.CreateOptions{FieldManager: fieldManager})\n}","line":{"from":150,"to":157}} {"id":100010034,"name":"Update","signature":"func (fs *flowSchemaWrapper) Update(object runtime.Object) (runtime.Object, error)","file":"pkg/registry/flowcontrol/ensurer/flowschema.go","code":"func (fs *flowSchemaWrapper) Update(object runtime.Object) (runtime.Object, error) {\n\tfsObject, ok := object.(*flowcontrolv1beta3.FlowSchema)\n\tif !ok {\n\t\treturn nil, errObjectNotFlowSchema\n\t}\n\n\treturn fs.client.Update(context.TODO(), fsObject, metav1.UpdateOptions{FieldManager: fieldManager})\n}","line":{"from":159,"to":166}} {"id":100010035,"name":"Get","signature":"func (fs *flowSchemaWrapper) Get(name string) (configurationObject, error)","file":"pkg/registry/flowcontrol/ensurer/flowschema.go","code":"func (fs *flowSchemaWrapper) Get(name string) (configurationObject, error) {\n\treturn fs.lister.Get(name)\n}","line":{"from":168,"to":170}} {"id":100010036,"name":"Delete","signature":"func (fs *flowSchemaWrapper) Delete(name string) error","file":"pkg/registry/flowcontrol/ensurer/flowschema.go","code":"func (fs *flowSchemaWrapper) Delete(name string) error {\n\treturn fs.client.Delete(context.TODO(), name, metav1.DeleteOptions{})\n}","line":{"from":172,"to":174}} {"id":100010037,"name":"CopySpec","signature":"func (fs *flowSchemaWrapper) CopySpec(bootstrap, current runtime.Object) error","file":"pkg/registry/flowcontrol/ensurer/flowschema.go","code":"func (fs *flowSchemaWrapper) CopySpec(bootstrap, current runtime.Object) error {\n\tbootstrapFS, ok := bootstrap.(*flowcontrolv1beta3.FlowSchema)\n\tif !ok {\n\t\treturn errObjectNotFlowSchema\n\t}\n\tcurrentFS, ok := current.(*flowcontrolv1beta3.FlowSchema)\n\tif !ok {\n\t\treturn errObjectNotFlowSchema\n\t}\n\n\tspecCopy := bootstrapFS.Spec.DeepCopy()\n\tcurrentFS.Spec = *specCopy\n\treturn nil\n}","line":{"from":176,"to":189}} {"id":100010038,"name":"HasSpecChanged","signature":"func (fs *flowSchemaWrapper) HasSpecChanged(bootstrap, current runtime.Object) (bool, error)","file":"pkg/registry/flowcontrol/ensurer/flowschema.go","code":"func (fs *flowSchemaWrapper) HasSpecChanged(bootstrap, current runtime.Object) (bool, error) {\n\tbootstrapFS, ok := bootstrap.(*flowcontrolv1beta3.FlowSchema)\n\tif !ok {\n\t\treturn false, errObjectNotFlowSchema\n\t}\n\tcurrentFS, ok := current.(*flowcontrolv1beta3.FlowSchema)\n\tif !ok {\n\t\treturn false, errObjectNotFlowSchema\n\t}\n\n\treturn flowSchemaSpecChanged(bootstrapFS, currentFS), nil\n}","line":{"from":191,"to":202}} {"id":100010039,"name":"flowSchemaSpecChanged","signature":"func flowSchemaSpecChanged(expected, actual *flowcontrolv1beta3.FlowSchema) bool","file":"pkg/registry/flowcontrol/ensurer/flowschema.go","code":"func flowSchemaSpecChanged(expected, actual *flowcontrolv1beta3.FlowSchema) bool {\n\tcopiedExpectedFlowSchema := expected.DeepCopy()\n\tflowcontrolapisv1beta3.SetObjectDefaults_FlowSchema(copiedExpectedFlowSchema)\n\treturn !equality.Semantic.DeepEqual(copiedExpectedFlowSchema.Spec, actual.Spec)\n}","line":{"from":204,"to":208}} {"id":100010040,"name":"NewSuggestedPriorityLevelEnsurerEnsurer","signature":"func NewSuggestedPriorityLevelEnsurerEnsurer(client flowcontrolclient.PriorityLevelConfigurationInterface, lister flowcontrollisters.PriorityLevelConfigurationLister) PriorityLevelEnsurer","file":"pkg/registry/flowcontrol/ensurer/prioritylevelconfiguration.go","code":"// NewSuggestedPriorityLevelEnsurerEnsurer returns a PriorityLevelEnsurer instance that\n// can be used to ensure a set of suggested PriorityLevelConfiguration configuration objects.\nfunc NewSuggestedPriorityLevelEnsurerEnsurer(client flowcontrolclient.PriorityLevelConfigurationInterface, lister flowcontrollisters.PriorityLevelConfigurationLister) PriorityLevelEnsurer {\n\twrapper := \u0026priorityLevelConfigurationWrapper{\n\t\tclient: client,\n\t\tlister: lister,\n\t}\n\treturn \u0026plEnsurer{\n\t\tstrategy: newSuggestedEnsureStrategy(wrapper),\n\t\twrapper: wrapper,\n\t}\n}","line":{"from":55,"to":66}} {"id":100010041,"name":"NewMandatoryPriorityLevelEnsurer","signature":"func NewMandatoryPriorityLevelEnsurer(client flowcontrolclient.PriorityLevelConfigurationInterface, lister flowcontrollisters.PriorityLevelConfigurationLister) PriorityLevelEnsurer","file":"pkg/registry/flowcontrol/ensurer/prioritylevelconfiguration.go","code":"// NewMandatoryPriorityLevelEnsurer returns a PriorityLevelEnsurer instance that\n// can be used to ensure a set of mandatory PriorityLevelConfiguration configuration objects.\nfunc NewMandatoryPriorityLevelEnsurer(client flowcontrolclient.PriorityLevelConfigurationInterface, lister flowcontrollisters.PriorityLevelConfigurationLister) PriorityLevelEnsurer {\n\twrapper := \u0026priorityLevelConfigurationWrapper{\n\t\tclient: client,\n\t\tlister: lister,\n\t}\n\treturn \u0026plEnsurer{\n\t\tstrategy: newMandatoryEnsureStrategy(wrapper),\n\t\twrapper: wrapper,\n\t}\n}","line":{"from":68,"to":79}} {"id":100010042,"name":"NewPriorityLevelRemover","signature":"func NewPriorityLevelRemover(client flowcontrolclient.PriorityLevelConfigurationInterface, lister flowcontrollisters.PriorityLevelConfigurationLister) PriorityLevelRemover","file":"pkg/registry/flowcontrol/ensurer/prioritylevelconfiguration.go","code":"// NewPriorityLevelRemover returns a PriorityLevelRemover instance that\n// can be used to remove a set of PriorityLevelConfiguration configuration objects.\nfunc NewPriorityLevelRemover(client flowcontrolclient.PriorityLevelConfigurationInterface, lister flowcontrollisters.PriorityLevelConfigurationLister) PriorityLevelRemover {\n\treturn \u0026plEnsurer{\n\t\twrapper: \u0026priorityLevelConfigurationWrapper{\n\t\t\tclient: client,\n\t\t\tlister: lister,\n\t\t},\n\t}\n}","line":{"from":81,"to":90}} {"id":100010043,"name":"GetPriorityLevelRemoveCandidates","signature":"func GetPriorityLevelRemoveCandidates(lister flowcontrollisters.PriorityLevelConfigurationLister, bootstrap []*flowcontrolv1beta3.PriorityLevelConfiguration) ([]string, error)","file":"pkg/registry/flowcontrol/ensurer/prioritylevelconfiguration.go","code":"// GetPriorityLevelRemoveCandidates returns a list of PriorityLevelConfiguration\n// names that are candidates for removal from the cluster.\n// bootstrap: a set of hard coded PriorityLevelConfiguration configuration\n// objects kube-apiserver maintains in-memory.\nfunc GetPriorityLevelRemoveCandidates(lister flowcontrollisters.PriorityLevelConfigurationLister, bootstrap []*flowcontrolv1beta3.PriorityLevelConfiguration) ([]string, error) {\n\tplList, err := lister.List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to list PriorityLevelConfiguration - %w\", err)\n\t}\n\n\tbootstrapNames := sets.String{}\n\tfor i := range bootstrap {\n\t\tbootstrapNames.Insert(bootstrap[i].GetName())\n\t}\n\n\tcurrentObjects := make([]metav1.Object, len(plList))\n\tfor i := range plList {\n\t\tcurrentObjects[i] = plList[i]\n\t}\n\n\treturn getDanglingBootstrapObjectNames(bootstrapNames, currentObjects), nil\n}","line":{"from":92,"to":113}} {"id":100010044,"name":"Ensure","signature":"func (e *plEnsurer) Ensure(priorityLevels []*flowcontrolv1beta3.PriorityLevelConfiguration) error","file":"pkg/registry/flowcontrol/ensurer/prioritylevelconfiguration.go","code":"func (e *plEnsurer) Ensure(priorityLevels []*flowcontrolv1beta3.PriorityLevelConfiguration) error {\n\tfor _, priorityLevel := range priorityLevels {\n\t\tif err := ensureConfiguration(e.wrapper, e.strategy, priorityLevel); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":120,"to":128}} {"id":100010045,"name":"RemoveAutoUpdateEnabledObjects","signature":"func (e *plEnsurer) RemoveAutoUpdateEnabledObjects(priorityLevels []string) error","file":"pkg/registry/flowcontrol/ensurer/prioritylevelconfiguration.go","code":"func (e *plEnsurer) RemoveAutoUpdateEnabledObjects(priorityLevels []string) error {\n\tfor _, priorityLevel := range priorityLevels {\n\t\tif err := removeAutoUpdateEnabledConfiguration(e.wrapper, priorityLevel); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":130,"to":138}} {"id":100010046,"name":"TypeName","signature":"func (fs *priorityLevelConfigurationWrapper) TypeName() string","file":"pkg/registry/flowcontrol/ensurer/prioritylevelconfiguration.go","code":"func (fs *priorityLevelConfigurationWrapper) TypeName() string {\n\treturn \"PriorityLevelConfiguration\"\n}","line":{"from":147,"to":149}} {"id":100010047,"name":"Create","signature":"func (fs *priorityLevelConfigurationWrapper) Create(object runtime.Object) (runtime.Object, error)","file":"pkg/registry/flowcontrol/ensurer/prioritylevelconfiguration.go","code":"func (fs *priorityLevelConfigurationWrapper) Create(object runtime.Object) (runtime.Object, error) {\n\tplObject, ok := object.(*flowcontrolv1beta3.PriorityLevelConfiguration)\n\tif !ok {\n\t\treturn nil, errObjectNotPriorityLevel\n\t}\n\n\treturn fs.client.Create(context.TODO(), plObject, metav1.CreateOptions{FieldManager: fieldManager})\n}","line":{"from":151,"to":158}} {"id":100010048,"name":"Update","signature":"func (fs *priorityLevelConfigurationWrapper) Update(object runtime.Object) (runtime.Object, error)","file":"pkg/registry/flowcontrol/ensurer/prioritylevelconfiguration.go","code":"func (fs *priorityLevelConfigurationWrapper) Update(object runtime.Object) (runtime.Object, error) {\n\tfsObject, ok := object.(*flowcontrolv1beta3.PriorityLevelConfiguration)\n\tif !ok {\n\t\treturn nil, errObjectNotPriorityLevel\n\t}\n\n\treturn fs.client.Update(context.TODO(), fsObject, metav1.UpdateOptions{FieldManager: fieldManager})\n}","line":{"from":160,"to":167}} {"id":100010049,"name":"Get","signature":"func (fs *priorityLevelConfigurationWrapper) Get(name string) (configurationObject, error)","file":"pkg/registry/flowcontrol/ensurer/prioritylevelconfiguration.go","code":"func (fs *priorityLevelConfigurationWrapper) Get(name string) (configurationObject, error) {\n\treturn fs.lister.Get(name)\n}","line":{"from":169,"to":171}} {"id":100010050,"name":"Delete","signature":"func (fs *priorityLevelConfigurationWrapper) Delete(name string) error","file":"pkg/registry/flowcontrol/ensurer/prioritylevelconfiguration.go","code":"func (fs *priorityLevelConfigurationWrapper) Delete(name string) error {\n\treturn fs.client.Delete(context.TODO(), name, metav1.DeleteOptions{})\n}","line":{"from":173,"to":175}} {"id":100010051,"name":"CopySpec","signature":"func (fs *priorityLevelConfigurationWrapper) CopySpec(bootstrap, current runtime.Object) error","file":"pkg/registry/flowcontrol/ensurer/prioritylevelconfiguration.go","code":"func (fs *priorityLevelConfigurationWrapper) CopySpec(bootstrap, current runtime.Object) error {\n\tbootstrapFS, ok := bootstrap.(*flowcontrolv1beta3.PriorityLevelConfiguration)\n\tif !ok {\n\t\treturn errObjectNotPriorityLevel\n\t}\n\tcurrentFS, ok := current.(*flowcontrolv1beta3.PriorityLevelConfiguration)\n\tif !ok {\n\t\treturn errObjectNotPriorityLevel\n\t}\n\n\tspecCopy := bootstrapFS.Spec.DeepCopy()\n\tcurrentFS.Spec = *specCopy\n\treturn nil\n}","line":{"from":177,"to":190}} {"id":100010052,"name":"HasSpecChanged","signature":"func (fs *priorityLevelConfigurationWrapper) HasSpecChanged(bootstrap, current runtime.Object) (bool, error)","file":"pkg/registry/flowcontrol/ensurer/prioritylevelconfiguration.go","code":"func (fs *priorityLevelConfigurationWrapper) HasSpecChanged(bootstrap, current runtime.Object) (bool, error) {\n\tbootstrapFS, ok := bootstrap.(*flowcontrolv1beta3.PriorityLevelConfiguration)\n\tif !ok {\n\t\treturn false, errObjectNotPriorityLevel\n\t}\n\tcurrentFS, ok := current.(*flowcontrolv1beta3.PriorityLevelConfiguration)\n\tif !ok {\n\t\treturn false, errObjectNotPriorityLevel\n\t}\n\n\treturn priorityLevelSpecChanged(bootstrapFS, currentFS), nil\n}","line":{"from":192,"to":203}} {"id":100010053,"name":"priorityLevelSpecChanged","signature":"func priorityLevelSpecChanged(expected, actual *flowcontrolv1beta3.PriorityLevelConfiguration) bool","file":"pkg/registry/flowcontrol/ensurer/prioritylevelconfiguration.go","code":"func priorityLevelSpecChanged(expected, actual *flowcontrolv1beta3.PriorityLevelConfiguration) bool {\n\tcopiedExpectedPriorityLevel := expected.DeepCopy()\n\tflowcontrolapisv1beta3.SetObjectDefaults_PriorityLevelConfiguration(copiedExpectedPriorityLevel)\n\treturn !equality.Semantic.DeepEqual(copiedExpectedPriorityLevel.Spec, actual.Spec)\n}","line":{"from":205,"to":209}} {"id":100010054,"name":"newSuggestedEnsureStrategy","signature":"func newSuggestedEnsureStrategy(copier specCopier) ensureStrategy","file":"pkg/registry/flowcontrol/ensurer/strategy.go","code":"func newSuggestedEnsureStrategy(copier specCopier) ensureStrategy {\n\treturn \u0026strategy{\n\t\tcopier: copier,\n\t\talwaysAutoUpdateSpec: false,\n\t\tname: \"suggested\",\n\t}\n}","line":{"from":108,"to":114}} {"id":100010055,"name":"newMandatoryEnsureStrategy","signature":"func newMandatoryEnsureStrategy(copier specCopier) ensureStrategy","file":"pkg/registry/flowcontrol/ensurer/strategy.go","code":"func newMandatoryEnsureStrategy(copier specCopier) ensureStrategy {\n\treturn \u0026strategy{\n\t\tcopier: copier,\n\t\talwaysAutoUpdateSpec: true,\n\t\tname: \"mandatory\",\n\t}\n}","line":{"from":116,"to":122}} {"id":100010056,"name":"Name","signature":"func (s *strategy) Name() string","file":"pkg/registry/flowcontrol/ensurer/strategy.go","code":"func (s *strategy) Name() string {\n\treturn s.name\n}","line":{"from":131,"to":133}} {"id":100010057,"name":"ShouldUpdate","signature":"func (s *strategy) ShouldUpdate(current, bootstrap configurationObject) (runtime.Object, bool, error)","file":"pkg/registry/flowcontrol/ensurer/strategy.go","code":"func (s *strategy) ShouldUpdate(current, bootstrap configurationObject) (runtime.Object, bool, error) {\n\tif current == nil || bootstrap == nil {\n\t\treturn nil, false, nil\n\t}\n\n\tautoUpdateSpec := s.alwaysAutoUpdateSpec\n\tif !autoUpdateSpec {\n\t\tautoUpdateSpec = shouldUpdateSpec(current)\n\t}\n\tupdateAnnotation := shouldUpdateAnnotation(current, autoUpdateSpec)\n\n\tvar specChanged bool\n\tif autoUpdateSpec {\n\t\tchanged, err := s.copier.HasSpecChanged(bootstrap, current)\n\t\tif err != nil {\n\t\t\treturn nil, false, fmt.Errorf(\"failed to compare spec - %w\", err)\n\t\t}\n\t\tspecChanged = changed\n\t}\n\n\tif !(updateAnnotation || specChanged) {\n\t\t// the annotation key is up to date and the spec has not changed, no update is necessary\n\t\treturn nil, false, nil\n\t}\n\n\t// if we are here, either we need to update the annotation key or the spec.\n\tcopy, ok := current.DeepCopyObject().(configurationObject)\n\tif !ok {\n\t\t// we should never be here\n\t\treturn nil, false, errors.New(\"incompatible object type\")\n\t}\n\n\tif updateAnnotation {\n\t\tsetAutoUpdateAnnotation(copy, autoUpdateSpec)\n\t}\n\tif specChanged {\n\t\ts.copier.CopySpec(bootstrap, copy)\n\t}\n\n\treturn copy, true, nil\n}","line":{"from":135,"to":175}} {"id":100010058,"name":"shouldUpdateSpec","signature":"func shouldUpdateSpec(accessor metav1.Object) bool","file":"pkg/registry/flowcontrol/ensurer/strategy.go","code":"// shouldUpdateSpec inspects the auto-update annotation key and generation field to determine\n// whether the configurationWrapper object should be auto-updated.\nfunc shouldUpdateSpec(accessor metav1.Object) bool {\n\tvalue, _ := accessor.GetAnnotations()[flowcontrolv1beta3.AutoUpdateAnnotationKey]\n\tif autoUpdate, err := strconv.ParseBool(value); err == nil {\n\t\treturn autoUpdate\n\t}\n\n\t// We are here because of either a or b:\n\t// a. the annotation key is missing.\n\t// b. the annotation key is present but the value does not represent a boolean.\n\t// In either case, if the operator hasn't changed the spec, we can safely auto update.\n\t// Please note that we can't protect the changes made by the operator in the following scenario:\n\t// - The operator deletes and recreates the same object with a variant spec (generation resets to 1).\n\tif accessor.GetGeneration() == 1 {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":177,"to":195}} {"id":100010059,"name":"shouldUpdateAnnotation","signature":"func shouldUpdateAnnotation(accessor metav1.Object, desired bool) bool","file":"pkg/registry/flowcontrol/ensurer/strategy.go","code":"// shouldUpdateAnnotation determines whether the current value of the auto-update annotation\n// key matches the desired value.\nfunc shouldUpdateAnnotation(accessor metav1.Object, desired bool) bool {\n\tif value, ok := accessor.GetAnnotations()[flowcontrolv1beta3.AutoUpdateAnnotationKey]; ok {\n\t\tif current, err := strconv.ParseBool(value); err == nil \u0026\u0026 current == desired {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}","line":{"from":197,"to":207}} {"id":100010060,"name":"setAutoUpdateAnnotation","signature":"func setAutoUpdateAnnotation(accessor metav1.Object, autoUpdate bool)","file":"pkg/registry/flowcontrol/ensurer/strategy.go","code":"// setAutoUpdateAnnotation sets the auto-update annotation key to the specified value.\nfunc setAutoUpdateAnnotation(accessor metav1.Object, autoUpdate bool) {\n\tif accessor.GetAnnotations() == nil {\n\t\taccessor.SetAnnotations(map[string]string{})\n\t}\n\n\taccessor.GetAnnotations()[flowcontrolv1beta3.AutoUpdateAnnotationKey] = strconv.FormatBool(autoUpdate)\n}","line":{"from":209,"to":216}} {"id":100010061,"name":"ensureConfiguration","signature":"func ensureConfiguration(wrapper configurationWrapper, strategy ensureStrategy, bootstrap configurationObject) error","file":"pkg/registry/flowcontrol/ensurer/strategy.go","code":"// ensureConfiguration ensures the boostrap configurationWrapper on the cluster based on the specified strategy.\nfunc ensureConfiguration(wrapper configurationWrapper, strategy ensureStrategy, bootstrap configurationObject) error {\n\tname := bootstrap.GetName()\n\tconfigurationType := strategy.Name()\n\n\tvar current configurationObject\n\tvar err error\n\tfor {\n\t\tcurrent, err = wrapper.Get(bootstrap.GetName())\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t\tif !apierrors.IsNotFound(err) {\n\t\t\treturn fmt.Errorf(\"failed to retrieve %s type=%s name=%q error=%w\", wrapper.TypeName(), configurationType, name, err)\n\t\t}\n\n\t\t// we always re-create a missing configuration object\n\t\tif _, err = wrapper.Create(bootstrap); err == nil {\n\t\t\tklog.V(2).InfoS(fmt.Sprintf(\"Successfully created %s\", wrapper.TypeName()), \"type\", configurationType, \"name\", name)\n\t\t\treturn nil\n\t\t}\n\n\t\tif !apierrors.IsAlreadyExists(err) {\n\t\t\treturn fmt.Errorf(\"cannot create %s type=%s name=%q error=%w\", wrapper.TypeName(), configurationType, name, err)\n\t\t}\n\t\tklog.V(5).InfoS(fmt.Sprintf(\"Something created the %s concurrently\", wrapper.TypeName()), \"type\", configurationType, \"name\", name)\n\t}\n\n\tklog.V(5).InfoS(fmt.Sprintf(\"The %s already exists, checking whether it is up to date\", wrapper.TypeName()), \"type\", configurationType, \"name\", name)\n\tnewObject, update, err := strategy.ShouldUpdate(current, bootstrap)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to determine whether auto-update is required for %s type=%s name=%q error=%w\", wrapper.TypeName(), configurationType, name, err)\n\t}\n\tif !update {\n\t\tif klogV := klog.V(5); klogV.Enabled() {\n\t\t\tklogV.InfoS(\"No update required\", \"wrapper\", wrapper.TypeName(), \"type\", configurationType, \"name\", name,\n\t\t\t\t\"diff\", cmp.Diff(current, bootstrap))\n\t\t}\n\t\treturn nil\n\t}\n\n\tif _, err = wrapper.Update(newObject); err == nil {\n\t\tklog.V(2).Infof(\"Updated the %s type=%s name=%q diff: %s\", wrapper.TypeName(), configurationType, name, cmp.Diff(current, newObject))\n\t\treturn nil\n\t}\n\n\tif apierrors.IsConflict(err) {\n\t\tklog.V(2).InfoS(fmt.Sprintf(\"Something updated the %s concurrently, I will check its spec later\", wrapper.TypeName()), \"type\", configurationType, \"name\", name)\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"failed to update the %s, will retry later type=%s name=%q error=%w\", wrapper.TypeName(), configurationType, name, err)\n}","line":{"from":218,"to":270}} {"id":100010062,"name":"removeAutoUpdateEnabledConfiguration","signature":"func removeAutoUpdateEnabledConfiguration(wrapper configurationWrapper, name string) error","file":"pkg/registry/flowcontrol/ensurer/strategy.go","code":"// removeAutoUpdateEnabledConfiguration makes an attempt to remove the given\n// configuration object if automatic update of the spec is enabled for this object.\nfunc removeAutoUpdateEnabledConfiguration(wrapper configurationWrapper, name string) error {\n\tcurrent, err := wrapper.Get(name)\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn fmt.Errorf(\"failed to retrieve the %s, will retry later name=%q error=%w\", wrapper.TypeName(), name, err)\n\t}\n\n\tvalue := current.GetAnnotations()[flowcontrolv1beta3.AutoUpdateAnnotationKey]\n\tautoUpdate, err := strconv.ParseBool(value)\n\tif err != nil {\n\t\tklog.ErrorS(err, fmt.Sprintf(\"Skipping deletion of the %s\", wrapper.TypeName()), \"name\", name)\n\n\t\t// This may need manual intervention, in case the annotation value is malformed,\n\t\t// so don't return an error, that might trigger futile retry loop.\n\t\treturn nil\n\t}\n\tif !autoUpdate {\n\t\tklog.V(5).InfoS(fmt.Sprintf(\"Skipping deletion of the %s\", wrapper.TypeName()), \"name\", name)\n\t\treturn nil\n\t}\n\n\tif err := wrapper.Delete(name); err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\tklog.V(5).InfoS(fmt.Sprintf(\"Something concurrently deleted the %s\", wrapper.TypeName()), \"name\", name)\n\t\t\treturn nil\n\t\t}\n\n\t\treturn fmt.Errorf(\"failed to delete the %s, will retry later name=%q error=%w\", wrapper.TypeName(), name, err)\n\t}\n\n\tklog.V(2).InfoS(fmt.Sprintf(\"Successfully deleted the %s\", wrapper.TypeName()), \"name\", name)\n\treturn nil\n}","line":{"from":272,"to":309}} {"id":100010063,"name":"getDanglingBootstrapObjectNames","signature":"func getDanglingBootstrapObjectNames(bootstrap sets.String, current []metav1.Object) []string","file":"pkg/registry/flowcontrol/ensurer/strategy.go","code":"// getDanglingBootstrapObjectNames returns a list of names of bootstrap\n// configuration objects that are potentially candidates for deletion from\n// the cluster, given a set of bootstrap and current configuration.\n// - bootstrap: a set of hard coded configuration kube-apiserver maintains in-memory.\n// - current: a set of configuration objects that exist on the cluster\n//\n// Any object present in current is added to the list if both a and b are true:\n//\n//\ta. the object in current is missing from the bootstrap configuration\n//\tb. the object has the designated auto-update annotation key\n//\n// This function shares the common logic for both FlowSchema and\n// PriorityLevelConfiguration type and hence it accepts metav1.Object only.\nfunc getDanglingBootstrapObjectNames(bootstrap sets.String, current []metav1.Object) []string {\n\tif len(current) == 0 {\n\t\treturn nil\n\t}\n\n\tcandidates := make([]string, 0)\n\tfor i := range current {\n\t\tobject := current[i]\n\t\tif _, ok := object.GetAnnotations()[flowcontrolv1beta3.AutoUpdateAnnotationKey]; !ok {\n\t\t\t// the configuration object does not have the annotation key,\n\t\t\t// it's probably a user defined configuration object,\n\t\t\t// so we can skip it.\n\t\t\tcontinue\n\t\t}\n\n\t\tif _, ok := bootstrap[object.GetName()]; !ok {\n\t\t\tcandidates = append(candidates, object.GetName())\n\t\t}\n\t}\n\treturn candidates\n}","line":{"from":311,"to":344}} {"id":100010064,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error)","file":"pkg/registry/flowcontrol/flowschema/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against flow schemas.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026flowcontrol.FlowSchema{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026flowcontrol.FlowSchemaList{} },\n\t\tDefaultQualifiedResource: flowcontrol.Resource(\"flowschemas\"),\n\t\tSingularQualifiedResource: flowcontrol.Resource(\"flowschema\"),\n\n\t\tCreateStrategy: flowschema.Strategy,\n\t\tUpdateStrategy: flowschema.Strategy,\n\t\tDeleteStrategy: flowschema.Strategy,\n\t\tResetFieldsStrategy: flowschema.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tstatusStore := *store\n\tstatusStore.CreateStrategy = nil\n\tstatusStore.UpdateStrategy = flowschema.StatusStrategy\n\tstatusStore.DeleteStrategy = nil\n\tstatusStore.ResetFieldsStrategy = flowschema.StatusStrategy\n\n\treturn \u0026REST{store}, \u0026StatusREST{store: \u0026statusStore}, nil\n}","line":{"from":46,"to":73}} {"id":100010065,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"pkg/registry/flowcontrol/flowschema/storage/storage.go","code":"// New creates a new flow schema object.\nfunc (r *StatusREST) New() runtime.Object {\n\treturn \u0026flowcontrol.FlowSchema{}\n}","line":{"from":80,"to":83}} {"id":100010066,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"pkg/registry/flowcontrol/flowschema/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":85,"to":89}} {"id":100010067,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/flowcontrol/flowschema/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":91,"to":94}} {"id":100010068,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/flowcontrol/flowschema/storage/storage.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":96,"to":101}} {"id":100010069,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/flowcontrol/flowschema/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":103,"to":106}} {"id":100010070,"name":"ConvertToTable","signature":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/flowcontrol/flowschema/storage/storage.go","code":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":108,"to":110}} {"id":100010071,"name":"NamespaceScoped","signature":"func (flowSchemaStrategy) NamespaceScoped() bool","file":"pkg/registry/flowcontrol/flowschema/strategy.go","code":"// NamespaceScoped returns false because all PriorityClasses are global.\nfunc (flowSchemaStrategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":41,"to":44}} {"id":100010072,"name":"GetResetFields","signature":"func (flowSchemaStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/flowcontrol/flowschema/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (flowSchemaStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"flowcontrol.apiserver.k8s.io/v1alpha1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t\t\"flowcontrol.apiserver.k8s.io/v1beta1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t\t\"flowcontrol.apiserver.k8s.io/v1beta2\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t\t\"flowcontrol.apiserver.k8s.io/v1beta3\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":46,"to":65}} {"id":100010073,"name":"PrepareForCreate","signature":"func (flowSchemaStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/flowcontrol/flowschema/strategy.go","code":"// PrepareForCreate clears the status of a flow-schema before creation.\nfunc (flowSchemaStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tfl := obj.(*flowcontrol.FlowSchema)\n\tfl.Status = flowcontrol.FlowSchemaStatus{}\n\tfl.Generation = 1\n}","line":{"from":67,"to":72}} {"id":100010074,"name":"PrepareForUpdate","signature":"func (flowSchemaStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/flowcontrol/flowschema/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (flowSchemaStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewFlowSchema := obj.(*flowcontrol.FlowSchema)\n\toldFlowSchema := old.(*flowcontrol.FlowSchema)\n\n\t// Spec updates bump the generation so that we can distinguish between status updates.\n\tif !apiequality.Semantic.DeepEqual(newFlowSchema.Spec, oldFlowSchema.Spec) {\n\t\tnewFlowSchema.Generation = oldFlowSchema.Generation + 1\n\t}\n\tnewFlowSchema.Status = oldFlowSchema.Status\n}","line":{"from":74,"to":84}} {"id":100010075,"name":"Validate","signature":"func (flowSchemaStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/flowcontrol/flowschema/strategy.go","code":"// Validate validates a new flow-schema.\nfunc (flowSchemaStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\treturn validation.ValidateFlowSchema(obj.(*flowcontrol.FlowSchema))\n}","line":{"from":86,"to":89}} {"id":100010076,"name":"WarningsOnCreate","signature":"func (flowSchemaStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/flowcontrol/flowschema/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (flowSchemaStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":91,"to":94}} {"id":100010077,"name":"Canonicalize","signature":"func (flowSchemaStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/flowcontrol/flowschema/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (flowSchemaStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":96,"to":98}} {"id":100010078,"name":"AllowUnconditionalUpdate","signature":"func (flowSchemaStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/flowcontrol/flowschema/strategy.go","code":"func (flowSchemaStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":100,"to":102}} {"id":100010079,"name":"AllowCreateOnUpdate","signature":"func (flowSchemaStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/flowcontrol/flowschema/strategy.go","code":"// AllowCreateOnUpdate is false for flow-schemas; this means a POST is needed to create one.\nfunc (flowSchemaStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":104,"to":107}} {"id":100010080,"name":"ValidateUpdate","signature":"func (flowSchemaStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/flowcontrol/flowschema/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (flowSchemaStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateFlowSchemaUpdate(old.(*flowcontrol.FlowSchema), obj.(*flowcontrol.FlowSchema))\n}","line":{"from":109,"to":112}} {"id":100010081,"name":"WarningsOnUpdate","signature":"func (flowSchemaStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/flowcontrol/flowschema/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (flowSchemaStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":114,"to":117}} {"id":100010082,"name":"GetResetFields","signature":"func (flowSchemaStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/flowcontrol/flowschema/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (flowSchemaStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"flowcontrol.apiserver.k8s.io/v1alpha1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"metadata\"),\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t\t\"flowcontrol.apiserver.k8s.io/v1beta1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"metadata\"),\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t\t\"flowcontrol.apiserver.k8s.io/v1beta2\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"metadata\"),\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t\t\"flowcontrol.apiserver.k8s.io/v1beta3\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"metadata\"),\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":126,"to":149}} {"id":100010083,"name":"PrepareForUpdate","signature":"func (flowSchemaStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/flowcontrol/flowschema/strategy.go","code":"func (flowSchemaStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewFlowSchema := obj.(*flowcontrol.FlowSchema)\n\toldFlowSchema := old.(*flowcontrol.FlowSchema)\n\n\t// managedFields must be preserved since it's been modified to\n\t// track changed fields in the status update.\n\tmanagedFields := newFlowSchema.ManagedFields\n\tnewFlowSchema.ObjectMeta = oldFlowSchema.ObjectMeta\n\tnewFlowSchema.ManagedFields = managedFields\n\tnewFlowSchema.Spec = oldFlowSchema.Spec\n}","line":{"from":151,"to":161}} {"id":100010084,"name":"ValidateUpdate","signature":"func (flowSchemaStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/flowcontrol/flowschema/strategy.go","code":"func (flowSchemaStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateFlowSchemaStatusUpdate(old.(*flowcontrol.FlowSchema), obj.(*flowcontrol.FlowSchema))\n}","line":{"from":163,"to":165}} {"id":100010085,"name":"WarningsOnUpdate","signature":"func (flowSchemaStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/flowcontrol/flowschema/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (flowSchemaStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":167,"to":170}} {"id":100010086,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error)","file":"pkg/registry/flowcontrol/prioritylevelconfiguration/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against priority level configuration.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026flowcontrol.PriorityLevelConfiguration{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026flowcontrol.PriorityLevelConfigurationList{} },\n\t\tDefaultQualifiedResource: flowcontrol.Resource(\"prioritylevelconfigurations\"),\n\t\tSingularQualifiedResource: flowcontrol.Resource(\"prioritylevelconfiguration\"),\n\n\t\tCreateStrategy: prioritylevelconfiguration.Strategy,\n\t\tUpdateStrategy: prioritylevelconfiguration.Strategy,\n\t\tDeleteStrategy: prioritylevelconfiguration.Strategy,\n\t\tResetFieldsStrategy: prioritylevelconfiguration.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tstatusStore := *store\n\tstatusStore.CreateStrategy = nil\n\tstatusStore.UpdateStrategy = prioritylevelconfiguration.StatusStrategy\n\tstatusStore.DeleteStrategy = nil\n\tstatusStore.ResetFieldsStrategy = prioritylevelconfiguration.StatusStrategy\n\n\treturn \u0026REST{store}, \u0026StatusREST{store: \u0026statusStore}, nil\n}","line":{"from":46,"to":73}} {"id":100010087,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"pkg/registry/flowcontrol/prioritylevelconfiguration/storage/storage.go","code":"// New creates a new priority level configuration object.\nfunc (r *StatusREST) New() runtime.Object {\n\treturn \u0026flowcontrol.PriorityLevelConfiguration{}\n}","line":{"from":80,"to":83}} {"id":100010088,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"pkg/registry/flowcontrol/prioritylevelconfiguration/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":85,"to":89}} {"id":100010089,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/flowcontrol/prioritylevelconfiguration/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":91,"to":94}} {"id":100010090,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/flowcontrol/prioritylevelconfiguration/storage/storage.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":96,"to":101}} {"id":100010091,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/flowcontrol/prioritylevelconfiguration/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":103,"to":106}} {"id":100010092,"name":"ConvertToTable","signature":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/flowcontrol/prioritylevelconfiguration/storage/storage.go","code":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":108,"to":110}} {"id":100010093,"name":"NamespaceScoped","signature":"func (priorityLevelConfigurationStrategy) NamespaceScoped() bool","file":"pkg/registry/flowcontrol/prioritylevelconfiguration/strategy.go","code":"// NamespaceScoped returns false because all PriorityClasses are global.\nfunc (priorityLevelConfigurationStrategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":43,"to":46}} {"id":100010094,"name":"GetResetFields","signature":"func (priorityLevelConfigurationStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/flowcontrol/prioritylevelconfiguration/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (priorityLevelConfigurationStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"flowcontrol.apiserver.k8s.io/v1alpha1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t\t\"flowcontrol.apiserver.k8s.io/v1beta1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t\t\"flowcontrol.apiserver.k8s.io/v1beta2\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t\t\"flowcontrol.apiserver.k8s.io/v1beta3\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":48,"to":67}} {"id":100010095,"name":"PrepareForCreate","signature":"func (priorityLevelConfigurationStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/flowcontrol/prioritylevelconfiguration/strategy.go","code":"// PrepareForCreate clears the status of a priority-level-configuration before creation.\nfunc (priorityLevelConfigurationStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tpl := obj.(*flowcontrol.PriorityLevelConfiguration)\n\tpl.Status = flowcontrol.PriorityLevelConfigurationStatus{}\n\tpl.Generation = 1\n}","line":{"from":69,"to":74}} {"id":100010096,"name":"PrepareForUpdate","signature":"func (priorityLevelConfigurationStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/flowcontrol/prioritylevelconfiguration/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (priorityLevelConfigurationStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewPriorityLevelConfiguration := obj.(*flowcontrol.PriorityLevelConfiguration)\n\toldPriorityLevelConfiguration := old.(*flowcontrol.PriorityLevelConfiguration)\n\n\t// Spec updates bump the generation so that we can distinguish between status updates.\n\tif !apiequality.Semantic.DeepEqual(newPriorityLevelConfiguration.Spec, oldPriorityLevelConfiguration.Spec) {\n\t\tnewPriorityLevelConfiguration.Generation = oldPriorityLevelConfiguration.Generation + 1\n\t}\n\tnewPriorityLevelConfiguration.Status = oldPriorityLevelConfiguration.Status\n}","line":{"from":76,"to":86}} {"id":100010097,"name":"Validate","signature":"func (priorityLevelConfigurationStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/flowcontrol/prioritylevelconfiguration/strategy.go","code":"// Validate validates a new priority-level.\nfunc (priorityLevelConfigurationStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\treturn validation.ValidatePriorityLevelConfiguration(obj.(*flowcontrol.PriorityLevelConfiguration), getRequestGroupVersion(ctx))\n}","line":{"from":88,"to":91}} {"id":100010098,"name":"WarningsOnCreate","signature":"func (priorityLevelConfigurationStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/flowcontrol/prioritylevelconfiguration/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (priorityLevelConfigurationStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":93,"to":96}} {"id":100010099,"name":"Canonicalize","signature":"func (priorityLevelConfigurationStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/flowcontrol/prioritylevelconfiguration/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (priorityLevelConfigurationStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":98,"to":100}} {"id":100010100,"name":"AllowUnconditionalUpdate","signature":"func (priorityLevelConfigurationStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/flowcontrol/prioritylevelconfiguration/strategy.go","code":"func (priorityLevelConfigurationStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":102,"to":104}} {"id":100010101,"name":"AllowCreateOnUpdate","signature":"func (priorityLevelConfigurationStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/flowcontrol/prioritylevelconfiguration/strategy.go","code":"// AllowCreateOnUpdate is false for priority-level-configurations; this means a POST is needed to create one.\nfunc (priorityLevelConfigurationStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":106,"to":109}} {"id":100010102,"name":"ValidateUpdate","signature":"func (priorityLevelConfigurationStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/flowcontrol/prioritylevelconfiguration/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (priorityLevelConfigurationStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidatePriorityLevelConfiguration(obj.(*flowcontrol.PriorityLevelConfiguration), getRequestGroupVersion(ctx))\n}","line":{"from":111,"to":114}} {"id":100010103,"name":"WarningsOnUpdate","signature":"func (priorityLevelConfigurationStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/flowcontrol/prioritylevelconfiguration/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (priorityLevelConfigurationStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":116,"to":119}} {"id":100010104,"name":"GetResetFields","signature":"func (priorityLevelConfigurationStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/flowcontrol/prioritylevelconfiguration/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (priorityLevelConfigurationStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"flowcontrol.apiserver.k8s.io/v1alpha1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t\tfieldpath.MakePathOrDie(\"metadata\"),\n\t\t),\n\t\t\"flowcontrol.apiserver.k8s.io/v1beta1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t\tfieldpath.MakePathOrDie(\"metadata\"),\n\t\t),\n\t\t\"flowcontrol.apiserver.k8s.io/v1beta2\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t\tfieldpath.MakePathOrDie(\"metadata\"),\n\t\t),\n\t\t\"flowcontrol.apiserver.k8s.io/v1beta3\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t\tfieldpath.MakePathOrDie(\"metadata\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":128,"to":151}} {"id":100010105,"name":"PrepareForUpdate","signature":"func (priorityLevelConfigurationStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/flowcontrol/prioritylevelconfiguration/strategy.go","code":"func (priorityLevelConfigurationStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewPriorityLevelConfiguration := obj.(*flowcontrol.PriorityLevelConfiguration)\n\toldPriorityLevelConfiguration := old.(*flowcontrol.PriorityLevelConfiguration)\n\n\t// managedFields must be preserved since it's been modified to\n\t// track changed fields in the status update.\n\tmanagedFields := newPriorityLevelConfiguration.ManagedFields\n\tnewPriorityLevelConfiguration.ObjectMeta = oldPriorityLevelConfiguration.ObjectMeta\n\tnewPriorityLevelConfiguration.ManagedFields = managedFields\n\tnewPriorityLevelConfiguration.Spec = oldPriorityLevelConfiguration.Spec\n}","line":{"from":153,"to":163}} {"id":100010106,"name":"ValidateUpdate","signature":"func (priorityLevelConfigurationStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/flowcontrol/prioritylevelconfiguration/strategy.go","code":"func (priorityLevelConfigurationStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidatePriorityLevelConfigurationStatusUpdate(old.(*flowcontrol.PriorityLevelConfiguration), obj.(*flowcontrol.PriorityLevelConfiguration))\n}","line":{"from":165,"to":167}} {"id":100010107,"name":"WarningsOnUpdate","signature":"func (priorityLevelConfigurationStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/flowcontrol/prioritylevelconfiguration/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (priorityLevelConfigurationStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":169,"to":172}} {"id":100010108,"name":"getRequestGroupVersion","signature":"func getRequestGroupVersion(ctx context.Context) schema.GroupVersion","file":"pkg/registry/flowcontrol/prioritylevelconfiguration/strategy.go","code":"func getRequestGroupVersion(ctx context.Context) schema.GroupVersion {\n\tif requestInfo, exists := genericapirequest.RequestInfoFrom(ctx); exists {\n\t\treturn schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}\n\t}\n\treturn schema.GroupVersion{}\n}","line":{"from":174,"to":179}} {"id":100010109,"name":"NewRESTStorage","signature":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error)","file":"pkg/registry/flowcontrol/rest/storage_flowcontrol.go","code":"// NewRESTStorage creates a new rest storage for flow-control api models.\nfunc (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error) {\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(flowcontrol.GroupName, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs)\n\n\tif storageMap, err := p.storage(apiResourceConfigSource, restOptionsGetter, flowcontrolapisv1alpha1.SchemeGroupVersion); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[flowcontrolapisv1alpha1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\tif storageMap, err := p.storage(apiResourceConfigSource, restOptionsGetter, flowcontrolapisv1beta1.SchemeGroupVersion); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[flowcontrolapisv1beta1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\tif storageMap, err := p.storage(apiResourceConfigSource, restOptionsGetter, flowcontrolapisv1beta2.SchemeGroupVersion); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[flowcontrolapisv1beta2.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\tif storageMap, err := p.storage(apiResourceConfigSource, restOptionsGetter, flowcontrolapisv1beta3.SchemeGroupVersion); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[flowcontrolapisv1beta3.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\treturn apiGroupInfo, nil\n}","line":{"from":57,"to":86}} {"id":100010110,"name":"storage","signature":"func (p RESTStorageProvider) storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter, groupVersion schema.GroupVersion) (map[string]rest.Storage, error)","file":"pkg/registry/flowcontrol/rest/storage_flowcontrol.go","code":"func (p RESTStorageProvider) storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter, groupVersion schema.GroupVersion) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\t// flow-schema\n\tif resource := \"flowschemas\"; apiResourceConfigSource.ResourceEnabled(groupVersion.WithResource(resource)) {\n\t\tflowSchemaStorage, flowSchemaStatusStorage, err := flowschemastore.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstorage[resource] = flowSchemaStorage\n\t\tstorage[resource+\"/status\"] = flowSchemaStatusStorage\n\t}\n\n\t// priority-level-configuration\n\tif resource := \"prioritylevelconfigurations\"; apiResourceConfigSource.ResourceEnabled(groupVersion.WithResource(resource)) {\n\t\tpriorityLevelConfigurationStorage, priorityLevelConfigurationStatusStorage, err := prioritylevelconfigurationstore.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstorage[resource] = priorityLevelConfigurationStorage\n\t\tstorage[resource+\"/status\"] = priorityLevelConfigurationStatusStorage\n\t}\n\n\treturn storage, nil\n}","line":{"from":88,"to":112}} {"id":100010111,"name":"GroupName","signature":"func (p RESTStorageProvider) GroupName() string","file":"pkg/registry/flowcontrol/rest/storage_flowcontrol.go","code":"// GroupName returns group name of the storage\nfunc (p RESTStorageProvider) GroupName() string {\n\treturn flowcontrol.GroupName\n}","line":{"from":114,"to":117}} {"id":100010112,"name":"PostStartHook","signature":"func (p RESTStorageProvider) PostStartHook() (string, genericapiserver.PostStartHookFunc, error)","file":"pkg/registry/flowcontrol/rest/storage_flowcontrol.go","code":"// PostStartHook returns the hook func that launches the config provider\nfunc (p RESTStorageProvider) PostStartHook() (string, genericapiserver.PostStartHookFunc, error) {\n\tbce := \u0026bootstrapConfigurationEnsurer{\n\t\tinformersSynced: []cache.InformerSynced{\n\t\t\tp.InformerFactory.Flowcontrol().V1beta3().PriorityLevelConfigurations().Informer().HasSynced,\n\t\t\tp.InformerFactory.Flowcontrol().V1beta3().FlowSchemas().Informer().HasSynced,\n\t\t},\n\t\tfsLister: p.InformerFactory.Flowcontrol().V1beta3().FlowSchemas().Lister(),\n\t\tplcLister: p.InformerFactory.Flowcontrol().V1beta3().PriorityLevelConfigurations().Lister(),\n\t}\n\treturn PostStartHookName, bce.ensureAPFBootstrapConfiguration, nil\n}","line":{"from":119,"to":130}} {"id":100010113,"name":"ensureAPFBootstrapConfiguration","signature":"func (bce *bootstrapConfigurationEnsurer) ensureAPFBootstrapConfiguration(hookContext genericapiserver.PostStartHookContext) error","file":"pkg/registry/flowcontrol/rest/storage_flowcontrol.go","code":"func (bce *bootstrapConfigurationEnsurer) ensureAPFBootstrapConfiguration(hookContext genericapiserver.PostStartHookContext) error {\n\tclientset, err := flowcontrolclient.NewForConfig(hookContext.LoopbackClientConfig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to initialize clientset for APF - %w\", err)\n\t}\n\n\t// get a derived context that gets cancelled after 5m or\n\t// when the StopCh gets closed, whichever happens first.\n\tctx, cancel := contextFromChannelAndMaxWaitDuration(hookContext.StopCh, 5*time.Minute)\n\tdefer cancel()\n\n\tif !cache.WaitForCacheSync(ctx.Done(), bce.informersSynced...) {\n\t\treturn fmt.Errorf(\"APF bootstrap ensurer timed out waiting for cache sync\")\n\t}\n\n\terr = wait.PollImmediateUntilWithContext(\n\t\tctx,\n\t\ttime.Second,\n\t\tfunc(context.Context) (bool, error) {\n\t\t\tif err := ensure(clientset, bce.fsLister, bce.plcLister); err != nil {\n\t\t\t\tklog.ErrorS(err, \"APF bootstrap ensurer ran into error, will retry later\")\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn true, nil\n\t\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to initialize APF bootstrap configuration\")\n\t}\n\n\t// we have successfully initialized the bootstrap configuration, now we\n\t// spin up a goroutine which reconciles the bootstrap configuration periodically.\n\tgo func() {\n\t\twait.PollImmediateUntil(\n\t\t\ttime.Minute,\n\t\t\tfunc() (bool, error) {\n\t\t\t\tif err := ensure(clientset, bce.fsLister, bce.plcLister); err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"APF bootstrap ensurer ran into error, will retry later\")\n\t\t\t\t}\n\t\t\t\t// always auto update both suggested and mandatory configuration\n\t\t\t\treturn false, nil\n\t\t\t}, hookContext.StopCh)\n\t\tklog.Info(\"APF bootstrap ensurer is exiting\")\n\t}()\n\n\treturn nil\n}","line":{"from":138,"to":183}} {"id":100010114,"name":"ensure","signature":"func ensure(clientset flowcontrolclient.FlowcontrolV1beta3Interface, fsLister flowcontrollisters.FlowSchemaLister, plcLister flowcontrollisters.PriorityLevelConfigurationLister) error","file":"pkg/registry/flowcontrol/rest/storage_flowcontrol.go","code":"func ensure(clientset flowcontrolclient.FlowcontrolV1beta3Interface, fsLister flowcontrollisters.FlowSchemaLister, plcLister flowcontrollisters.PriorityLevelConfigurationLister) error {\n\tif err := ensureSuggestedConfiguration(clientset, fsLister, plcLister); err != nil {\n\t\t// We should not attempt creation of mandatory objects if ensuring the suggested\n\t\t// configuration resulted in an error.\n\t\t// This only happens when the stop channel is closed.\n\t\treturn fmt.Errorf(\"failed ensuring suggested settings - %w\", err)\n\t}\n\n\tif err := ensureMandatoryConfiguration(clientset, fsLister, plcLister); err != nil {\n\t\treturn fmt.Errorf(\"failed ensuring mandatory settings - %w\", err)\n\t}\n\n\tif err := removeDanglingBootstrapConfiguration(clientset, fsLister, plcLister); err != nil {\n\t\treturn fmt.Errorf(\"failed to delete removed settings - %w\", err)\n\t}\n\n\treturn nil\n}","line":{"from":185,"to":202}} {"id":100010115,"name":"ensureSuggestedConfiguration","signature":"func ensureSuggestedConfiguration(clientset flowcontrolclient.FlowcontrolV1beta3Interface, fsLister flowcontrollisters.FlowSchemaLister, plcLister flowcontrollisters.PriorityLevelConfigurationLister) error","file":"pkg/registry/flowcontrol/rest/storage_flowcontrol.go","code":"func ensureSuggestedConfiguration(clientset flowcontrolclient.FlowcontrolV1beta3Interface, fsLister flowcontrollisters.FlowSchemaLister, plcLister flowcontrollisters.PriorityLevelConfigurationLister) error {\n\tplEnsurer := ensurer.NewSuggestedPriorityLevelEnsurerEnsurer(clientset.PriorityLevelConfigurations(), plcLister)\n\tif err := plEnsurer.Ensure(flowcontrolbootstrap.SuggestedPriorityLevelConfigurations); err != nil {\n\t\treturn err\n\t}\n\n\tfsEnsurer := ensurer.NewSuggestedFlowSchemaEnsurer(clientset.FlowSchemas(), fsLister)\n\treturn fsEnsurer.Ensure(flowcontrolbootstrap.SuggestedFlowSchemas)\n}","line":{"from":204,"to":212}} {"id":100010116,"name":"ensureMandatoryConfiguration","signature":"func ensureMandatoryConfiguration(clientset flowcontrolclient.FlowcontrolV1beta3Interface, fsLister flowcontrollisters.FlowSchemaLister, plcLister flowcontrollisters.PriorityLevelConfigurationLister) error","file":"pkg/registry/flowcontrol/rest/storage_flowcontrol.go","code":"func ensureMandatoryConfiguration(clientset flowcontrolclient.FlowcontrolV1beta3Interface, fsLister flowcontrollisters.FlowSchemaLister, plcLister flowcontrollisters.PriorityLevelConfigurationLister) error {\n\tfsEnsurer := ensurer.NewMandatoryFlowSchemaEnsurer(clientset.FlowSchemas(), fsLister)\n\tif err := fsEnsurer.Ensure(flowcontrolbootstrap.MandatoryFlowSchemas); err != nil {\n\t\treturn err\n\t}\n\n\tplEnsurer := ensurer.NewMandatoryPriorityLevelEnsurer(clientset.PriorityLevelConfigurations(), plcLister)\n\treturn plEnsurer.Ensure(flowcontrolbootstrap.MandatoryPriorityLevelConfigurations)\n}","line":{"from":214,"to":222}} {"id":100010117,"name":"removeDanglingBootstrapConfiguration","signature":"func removeDanglingBootstrapConfiguration(clientset flowcontrolclient.FlowcontrolV1beta3Interface, fsLister flowcontrollisters.FlowSchemaLister, plcLister flowcontrollisters.PriorityLevelConfigurationLister) error","file":"pkg/registry/flowcontrol/rest/storage_flowcontrol.go","code":"func removeDanglingBootstrapConfiguration(clientset flowcontrolclient.FlowcontrolV1beta3Interface, fsLister flowcontrollisters.FlowSchemaLister, plcLister flowcontrollisters.PriorityLevelConfigurationLister) error {\n\tif err := removeDanglingBootstrapFlowSchema(clientset.FlowSchemas(), fsLister); err != nil {\n\t\treturn err\n\t}\n\n\treturn removeDanglingBootstrapPriorityLevel(clientset.PriorityLevelConfigurations(), plcLister)\n}","line":{"from":224,"to":230}} {"id":100010118,"name":"removeDanglingBootstrapFlowSchema","signature":"func removeDanglingBootstrapFlowSchema(client flowcontrolclient.FlowSchemaInterface, lister flowcontrollisters.FlowSchemaLister) error","file":"pkg/registry/flowcontrol/rest/storage_flowcontrol.go","code":"func removeDanglingBootstrapFlowSchema(client flowcontrolclient.FlowSchemaInterface, lister flowcontrollisters.FlowSchemaLister) error {\n\tbootstrap := append(flowcontrolbootstrap.MandatoryFlowSchemas, flowcontrolbootstrap.SuggestedFlowSchemas...)\n\tcandidates, err := ensurer.GetFlowSchemaRemoveCandidates(lister, bootstrap)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(candidates) == 0 {\n\t\treturn nil\n\t}\n\n\tfsRemover := ensurer.NewFlowSchemaRemover(client, lister)\n\treturn fsRemover.RemoveAutoUpdateEnabledObjects(candidates)\n}","line":{"from":232,"to":244}} {"id":100010119,"name":"removeDanglingBootstrapPriorityLevel","signature":"func removeDanglingBootstrapPriorityLevel(client flowcontrolclient.PriorityLevelConfigurationInterface, lister flowcontrollisters.PriorityLevelConfigurationLister) error","file":"pkg/registry/flowcontrol/rest/storage_flowcontrol.go","code":"func removeDanglingBootstrapPriorityLevel(client flowcontrolclient.PriorityLevelConfigurationInterface, lister flowcontrollisters.PriorityLevelConfigurationLister) error {\n\tbootstrap := append(flowcontrolbootstrap.MandatoryPriorityLevelConfigurations, flowcontrolbootstrap.SuggestedPriorityLevelConfigurations...)\n\tcandidates, err := ensurer.GetPriorityLevelRemoveCandidates(lister, bootstrap)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(candidates) == 0 {\n\t\treturn nil\n\t}\n\n\tplRemover := ensurer.NewPriorityLevelRemover(client, lister)\n\treturn plRemover.RemoveAutoUpdateEnabledObjects(candidates)\n}","line":{"from":246,"to":258}} {"id":100010120,"name":"contextFromChannelAndMaxWaitDuration","signature":"func contextFromChannelAndMaxWaitDuration(stopCh \u003c-chan struct{}, maxWait time.Duration) (context.Context, context.CancelFunc)","file":"pkg/registry/flowcontrol/rest/storage_flowcontrol.go","code":"// contextFromChannelAndMaxWaitDuration returns a Context that is bound to the\n// specified channel and the wait duration. The derived context will be\n// cancelled when the specified channel stopCh is closed or the maximum wait\n// duration specified in maxWait elapses, whichever happens first.\n//\n// Note the caller must *always* call the CancelFunc, otherwise resources may be leaked.\nfunc contextFromChannelAndMaxWaitDuration(stopCh \u003c-chan struct{}, maxWait time.Duration) (context.Context, context.CancelFunc) {\n\tctx, cancel := context.WithCancel(context.Background())\n\n\tgo func() {\n\t\tdefer cancel()\n\n\t\tselect {\n\t\tcase \u003c-stopCh:\n\t\tcase \u003c-time.After(maxWait):\n\n\t\t// the caller can explicitly cancel the context which is an\n\t\t// indication to us to exit the goroutine immediately.\n\t\t// Note that we are calling cancel more than once when we are here,\n\t\t// CancelFunc is idempotent and we expect no ripple effects here.\n\t\tcase \u003c-ctx.Done():\n\t\t}\n\t}()\n\treturn ctx, cancel\n}","line":{"from":260,"to":284}} {"id":100010121,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error)","file":"pkg/registry/networking/clustercidr/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against ClusterCIDRs.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026networkingapi.ClusterCIDR{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026networkingapi.ClusterCIDRList{} },\n\t\tDefaultQualifiedResource: networkingapi.Resource(\"clustercidrs\"),\n\t\tSingularQualifiedResource: networkingapi.Resource(\"clustercidr\"),\n\n\t\tCreateStrategy: clustercidr.Strategy,\n\t\tUpdateStrategy: clustercidr.Strategy,\n\t\tDeleteStrategy: clustercidr.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026REST{store}, nil\n}","line":{"from":36,"to":56}} {"id":100010122,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/networking/clustercidr/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"cc\"}\n}","line":{"from":61,"to":64}} {"id":100010123,"name":"NamespaceScoped","signature":"func (clusterCIDRStrategy) NamespaceScoped() bool","file":"pkg/registry/networking/clustercidr/strategy.go","code":"// NamespaceScoped returns false because all clusterCIDRs do not need to be within a namespace.\nfunc (clusterCIDRStrategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":39,"to":42}} {"id":100010124,"name":"PrepareForCreate","signature":"func (clusterCIDRStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {}","file":"pkg/registry/networking/clustercidr/strategy.go","code":"func (clusterCIDRStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {}","line":{"from":44,"to":44}} {"id":100010125,"name":"PrepareForUpdate","signature":"func (clusterCIDRStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {}","file":"pkg/registry/networking/clustercidr/strategy.go","code":"func (clusterCIDRStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {}","line":{"from":46,"to":46}} {"id":100010126,"name":"Validate","signature":"func (clusterCIDRStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/networking/clustercidr/strategy.go","code":"// Validate validates a new ClusterCIDR.\nfunc (clusterCIDRStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tclusterCIDR := obj.(*networking.ClusterCIDR)\n\treturn validation.ValidateClusterCIDR(clusterCIDR)\n}","line":{"from":48,"to":52}} {"id":100010127,"name":"WarningsOnCreate","signature":"func (clusterCIDRStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/networking/clustercidr/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (clusterCIDRStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":54,"to":57}} {"id":100010128,"name":"Canonicalize","signature":"func (clusterCIDRStrategy) Canonicalize(obj runtime.Object) {}","file":"pkg/registry/networking/clustercidr/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (clusterCIDRStrategy) Canonicalize(obj runtime.Object) {}","line":{"from":59,"to":60}} {"id":100010129,"name":"AllowCreateOnUpdate","signature":"func (clusterCIDRStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/networking/clustercidr/strategy.go","code":"// AllowCreateOnUpdate is false for ClusterCIDR; this means POST is needed to create one.\nfunc (clusterCIDRStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":62,"to":65}} {"id":100010130,"name":"ValidateUpdate","signature":"func (clusterCIDRStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/networking/clustercidr/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (clusterCIDRStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tvalidationErrorList := validation.ValidateClusterCIDR(obj.(*networking.ClusterCIDR))\n\tupdateErrorList := validation.ValidateClusterCIDRUpdate(obj.(*networking.ClusterCIDR), old.(*networking.ClusterCIDR))\n\treturn append(validationErrorList, updateErrorList...)\n}","line":{"from":67,"to":72}} {"id":100010131,"name":"WarningsOnUpdate","signature":"func (clusterCIDRStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/networking/clustercidr/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (clusterCIDRStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":74,"to":77}} {"id":100010132,"name":"AllowUnconditionalUpdate","signature":"func (clusterCIDRStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/networking/clustercidr/strategy.go","code":"// AllowUnconditionalUpdate is the default update policy for ClusterCIDR objects.\nfunc (clusterCIDRStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":79,"to":82}} {"id":100010133,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error)","file":"pkg/registry/networking/ingress/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against replication controllers.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026networking.Ingress{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026networking.IngressList{} },\n\t\tDefaultQualifiedResource: networking.Resource(\"ingresses\"),\n\t\tSingularQualifiedResource: networking.Resource(\"ingress\"),\n\n\t\tCreateStrategy: ingress.Strategy,\n\t\tUpdateStrategy: ingress.Strategy,\n\t\tDeleteStrategy: ingress.Strategy,\n\t\tResetFieldsStrategy: ingress.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = ingress.StatusStrategy\n\tstatusStore.ResetFieldsStrategy = ingress.StatusStrategy\n\treturn \u0026REST{store}, \u0026StatusREST{store: \u0026statusStore}, nil\n}","line":{"from":40,"to":64}} {"id":100010134,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/networking/ingress/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"ing\"}\n}","line":{"from":69,"to":72}} {"id":100010135,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"pkg/registry/networking/ingress/storage/storage.go","code":"// New creates an instance of the StatusREST object\nfunc (r *StatusREST) New() runtime.Object {\n\treturn \u0026networking.Ingress{}\n}","line":{"from":79,"to":82}} {"id":100010136,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"pkg/registry/networking/ingress/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":84,"to":88}} {"id":100010137,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/networking/ingress/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":90,"to":93}} {"id":100010138,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/networking/ingress/storage/storage.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":95,"to":100}} {"id":100010139,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/networking/ingress/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":102,"to":105}} {"id":100010140,"name":"ConvertToTable","signature":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/networking/ingress/storage/storage.go","code":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":107,"to":109}} {"id":100010141,"name":"NamespaceScoped","signature":"func (ingressStrategy) NamespaceScoped() bool","file":"pkg/registry/networking/ingress/strategy.go","code":"// NamespaceScoped returns true because all Ingress' need to be within a namespace.\nfunc (ingressStrategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":46,"to":49}} {"id":100010142,"name":"GetResetFields","signature":"func (ingressStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/networking/ingress/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (ingressStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"extensions/v1beta1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t\t\"networking.k8s.io/v1beta1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t\t\"networking.k8s.io/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":51,"to":67}} {"id":100010143,"name":"PrepareForCreate","signature":"func (ingressStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/networking/ingress/strategy.go","code":"// PrepareForCreate clears the status of an Ingress before creation.\nfunc (ingressStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tingress := obj.(*networking.Ingress)\n\t// create cannot set status\n\tingress.Status = networking.IngressStatus{}\n\n\tingress.Generation = 1\n}","line":{"from":69,"to":76}} {"id":100010144,"name":"PrepareForUpdate","signature":"func (ingressStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/networking/ingress/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (ingressStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewIngress := obj.(*networking.Ingress)\n\toldIngress := old.(*networking.Ingress)\n\t// Update is not allowed to set status\n\tnewIngress.Status = oldIngress.Status\n\n\t// Any changes to the spec increment the generation number, any changes to the\n\t// status should reflect the generation number of the corresponding object.\n\t// See metav1.ObjectMeta description for more information on Generation.\n\tif !apiequality.Semantic.DeepEqual(oldIngress.Spec, newIngress.Spec) {\n\t\tnewIngress.Generation = oldIngress.Generation + 1\n\t}\n\n}","line":{"from":78,"to":92}} {"id":100010145,"name":"Validate","signature":"func (ingressStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/networking/ingress/strategy.go","code":"// Validate validates ingresses on create.\nfunc (ingressStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tingress := obj.(*networking.Ingress)\n\treturn validation.ValidateIngressCreate(ingress)\n}","line":{"from":94,"to":98}} {"id":100010146,"name":"WarningsOnCreate","signature":"func (ingressStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/networking/ingress/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (ingressStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\tvar warnings []string\n\tingress := obj.(*networking.Ingress)\n\t_, annotationIsSet := ingress.Annotations[annotationIngressClass]\n\tif annotationIsSet \u0026\u0026 ingress.Spec.IngressClassName == nil {\n\t\twarnings = append(warnings, fmt.Sprintf(\"annotation %q is deprecated, please use 'spec.ingressClassName' instead\", annotationIngressClass))\n\t}\n\treturn warnings\n}","line":{"from":100,"to":109}} {"id":100010147,"name":"Canonicalize","signature":"func (ingressStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/networking/ingress/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (ingressStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":111,"to":113}} {"id":100010148,"name":"AllowCreateOnUpdate","signature":"func (ingressStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/networking/ingress/strategy.go","code":"// AllowCreateOnUpdate is false for Ingress; this means POST is needed to create one.\nfunc (ingressStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":115,"to":118}} {"id":100010149,"name":"ValidateUpdate","signature":"func (ingressStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/networking/ingress/strategy.go","code":"// ValidateUpdate validates ingresses on update.\nfunc (ingressStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateIngressUpdate(obj.(*networking.Ingress), old.(*networking.Ingress))\n}","line":{"from":120,"to":123}} {"id":100010150,"name":"WarningsOnUpdate","signature":"func (ingressStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/networking/ingress/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (ingressStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":125,"to":128}} {"id":100010151,"name":"AllowUnconditionalUpdate","signature":"func (ingressStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/networking/ingress/strategy.go","code":"// AllowUnconditionalUpdate is the default update policy for Ingress objects.\nfunc (ingressStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":130,"to":133}} {"id":100010152,"name":"GetResetFields","signature":"func (ingressStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/networking/ingress/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (ingressStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"extensions/v1beta1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t\t\"networking.k8s.io/v1beta1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t\t\"networking.k8s.io/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":142,"to":158}} {"id":100010153,"name":"PrepareForUpdate","signature":"func (ingressStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/networking/ingress/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update of status\nfunc (ingressStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewIngress := obj.(*networking.Ingress)\n\toldIngress := old.(*networking.Ingress)\n\t// status changes are not allowed to update spec\n\tnewIngress.Spec = oldIngress.Spec\n}","line":{"from":160,"to":166}} {"id":100010154,"name":"ValidateUpdate","signature":"func (ingressStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/networking/ingress/strategy.go","code":"// ValidateUpdate is the default update validation for an end user updating status\nfunc (ingressStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateIngressStatusUpdate(obj.(*networking.Ingress), old.(*networking.Ingress))\n}","line":{"from":168,"to":171}} {"id":100010155,"name":"WarningsOnUpdate","signature":"func (ingressStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/networking/ingress/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (ingressStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":173,"to":176}} {"id":100010156,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error)","file":"pkg/registry/networking/ingressclass/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against replication controllers.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026networking.IngressClass{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026networking.IngressClassList{} },\n\t\tDefaultQualifiedResource: networking.Resource(\"ingressclasses\"),\n\t\tSingularQualifiedResource: networking.Resource(\"ingressclass\"),\n\n\t\tCreateStrategy: ingressclass.Strategy,\n\t\tUpdateStrategy: ingressclass.Strategy,\n\t\tDeleteStrategy: ingressclass.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026REST{store}, nil\n}","line":{"from":35,"to":55}} {"id":100010157,"name":"NamespaceScoped","signature":"func (ingressClassStrategy) NamespaceScoped() bool","file":"pkg/registry/networking/ingressclass/strategy.go","code":"// NamespaceScoped returns false because IngressClass is a non-namespaced\n// resource.\nfunc (ingressClassStrategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":42,"to":46}} {"id":100010158,"name":"PrepareForCreate","signature":"func (ingressClassStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/networking/ingressclass/strategy.go","code":"// PrepareForCreate prepares an IngressClass for creation.\nfunc (ingressClassStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tingressClass := obj.(*networking.IngressClass)\n\tingressClass.Generation = 1\n}","line":{"from":48,"to":52}} {"id":100010159,"name":"PrepareForUpdate","signature":"func (ingressClassStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/networking/ingressclass/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on\n// update.\nfunc (ingressClassStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewIngressClass := obj.(*networking.IngressClass)\n\toldIngressClass := old.(*networking.IngressClass)\n\n\t// Any changes to the spec increment the generation number.\n\t// See metav1.ObjectMeta description for more information on Generation.\n\tif !apiequality.Semantic.DeepEqual(oldIngressClass.Spec, newIngressClass.Spec) {\n\t\tnewIngressClass.Generation = oldIngressClass.Generation + 1\n\t}\n}","line":{"from":54,"to":65}} {"id":100010160,"name":"Validate","signature":"func (ingressClassStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/networking/ingressclass/strategy.go","code":"// Validate validates a new IngressClass.\nfunc (ingressClassStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tingressClass := obj.(*networking.IngressClass)\n\treturn validation.ValidateIngressClass(ingressClass)\n}","line":{"from":67,"to":71}} {"id":100010161,"name":"WarningsOnCreate","signature":"func (ingressClassStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/networking/ingressclass/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (ingressClassStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":73,"to":76}} {"id":100010162,"name":"Canonicalize","signature":"func (ingressClassStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/networking/ingressclass/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (ingressClassStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":78,"to":80}} {"id":100010163,"name":"AllowCreateOnUpdate","signature":"func (ingressClassStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/networking/ingressclass/strategy.go","code":"// AllowCreateOnUpdate is false for IngressClass; this means POST is needed to\n// create one.\nfunc (ingressClassStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":82,"to":86}} {"id":100010164,"name":"ValidateUpdate","signature":"func (ingressClassStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/networking/ingressclass/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (ingressClassStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewIngressClass := obj.(*networking.IngressClass)\n\toldIngressClass := old.(*networking.IngressClass)\n\n\treturn validation.ValidateIngressClassUpdate(newIngressClass, oldIngressClass)\n}","line":{"from":88,"to":94}} {"id":100010165,"name":"WarningsOnUpdate","signature":"func (ingressClassStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/networking/ingressclass/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (ingressClassStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":96,"to":99}} {"id":100010166,"name":"AllowUnconditionalUpdate","signature":"func (ingressClassStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/networking/ingressclass/strategy.go","code":"// AllowUnconditionalUpdate is the default update policy for IngressClass\n// objects.\nfunc (ingressClassStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":101,"to":105}} {"id":100010167,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error)","file":"pkg/registry/networking/ipaddress/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against endpoint slices.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026networking.IPAddress{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026networking.IPAddressList{} },\n\t\tDefaultQualifiedResource: networking.Resource(\"ipaddresses\"),\n\t\tSingularQualifiedResource: networking.Resource(\"ipaddress\"),\n\n\t\tCreateStrategy: ipaddress.Strategy,\n\t\tUpdateStrategy: ipaddress.Strategy,\n\t\tDeleteStrategy: ipaddress.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026REST{store}, nil\n}","line":{"from":36,"to":55}} {"id":100010168,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/networking/ipaddress/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"ip\"}\n}","line":{"from":60,"to":63}} {"id":100010169,"name":"GenerateName","signature":"func (noopNameGenerator) GenerateName(base string) string","file":"pkg/registry/networking/ipaddress/strategy.go","code":"func (noopNameGenerator) GenerateName(base string) string {\n\treturn base\n}","line":{"from":40,"to":42}} {"id":100010170,"name":"NamespaceScoped","signature":"func (ipAddressStrategy) NamespaceScoped() bool","file":"pkg/registry/networking/ipaddress/strategy.go","code":"// NamespaceScoped returns false because all IPAddresses is cluster scoped.\nfunc (ipAddressStrategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":53,"to":56}} {"id":100010171,"name":"PrepareForCreate","signature":"func (ipAddressStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/networking/ipaddress/strategy.go","code":"// PrepareForCreate clears the status of an IPAddress before creation.\nfunc (ipAddressStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\t_ = obj.(*networking.IPAddress)\n\n}","line":{"from":58,"to":62}} {"id":100010172,"name":"PrepareForUpdate","signature":"func (ipAddressStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/networking/ipaddress/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (ipAddressStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewIPAddress := obj.(*networking.IPAddress)\n\toldIPAddress := old.(*networking.IPAddress)\n\n\t_, _ = newIPAddress, oldIPAddress\n}","line":{"from":64,"to":70}} {"id":100010173,"name":"Validate","signature":"func (ipAddressStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/networking/ipaddress/strategy.go","code":"// Validate validates a new IPAddress.\nfunc (ipAddressStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tipAddress := obj.(*networking.IPAddress)\n\terr := validation.ValidateIPAddress(ipAddress)\n\treturn err\n}","line":{"from":72,"to":77}} {"id":100010174,"name":"Canonicalize","signature":"func (ipAddressStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/networking/ipaddress/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (ipAddressStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":79,"to":81}} {"id":100010175,"name":"AllowCreateOnUpdate","signature":"func (ipAddressStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/networking/ipaddress/strategy.go","code":"// AllowCreateOnUpdate is false for IPAddress; this means POST is needed to create one.\nfunc (ipAddressStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":83,"to":86}} {"id":100010176,"name":"ValidateUpdate","signature":"func (ipAddressStrategy) ValidateUpdate(ctx context.Context, new, old runtime.Object) field.ErrorList","file":"pkg/registry/networking/ipaddress/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (ipAddressStrategy) ValidateUpdate(ctx context.Context, new, old runtime.Object) field.ErrorList {\n\tnewIPAddress := new.(*networking.IPAddress)\n\toldIPAddress := old.(*networking.IPAddress)\n\terrList := validation.ValidateIPAddress(newIPAddress)\n\terrList = append(errList, validation.ValidateIPAddressUpdate(newIPAddress, oldIPAddress)...)\n\treturn errList\n}","line":{"from":88,"to":95}} {"id":100010177,"name":"AllowUnconditionalUpdate","signature":"func (ipAddressStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/networking/ipaddress/strategy.go","code":"// AllowUnconditionalUpdate is the default update policy for IPAddress objects.\nfunc (ipAddressStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":97,"to":100}} {"id":100010178,"name":"WarningsOnCreate","signature":"func (ipAddressStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/networking/ipaddress/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (ipAddressStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":102,"to":105}} {"id":100010179,"name":"WarningsOnUpdate","signature":"func (ipAddressStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/networking/ipaddress/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (ipAddressStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":107,"to":110}} {"id":100010180,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error)","file":"pkg/registry/networking/networkpolicy/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against NetworkPolicies.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026networkingapi.NetworkPolicy{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026networkingapi.NetworkPolicyList{} },\n\t\tDefaultQualifiedResource: networkingapi.Resource(\"networkpolicies\"),\n\t\tSingularQualifiedResource: networkingapi.Resource(\"networkpolicy\"),\n\n\t\tCreateStrategy: networkpolicy.Strategy,\n\t\tUpdateStrategy: networkpolicy.Strategy,\n\t\tDeleteStrategy: networkpolicy.Strategy,\n\t\tResetFieldsStrategy: networkpolicy.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = networkpolicy.StatusStrategy\n\tstatusStore.ResetFieldsStrategy = networkpolicy.StatusStrategy\n\treturn \u0026REST{store}, \u0026StatusREST{store: \u0026statusStore}, nil\n\n}","line":{"from":41,"to":66}} {"id":100010181,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/networking/networkpolicy/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"netpol\"}\n}","line":{"from":71,"to":74}} {"id":100010182,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"pkg/registry/networking/networkpolicy/storage/storage.go","code":"// New creates an instance of the StatusREST object\nfunc (r *StatusREST) New() runtime.Object {\n\treturn \u0026networkingapi.NetworkPolicy{}\n}","line":{"from":81,"to":84}} {"id":100010183,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"pkg/registry/networking/networkpolicy/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":86,"to":90}} {"id":100010184,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/networking/networkpolicy/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":92,"to":95}} {"id":100010185,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/networking/networkpolicy/storage/storage.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":97,"to":102}} {"id":100010186,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/networking/networkpolicy/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":104,"to":107}} {"id":100010187,"name":"NamespaceScoped","signature":"func (networkPolicyStrategy) NamespaceScoped() bool","file":"pkg/registry/networking/networkpolicy/strategy.go","code":"// NamespaceScoped returns true because all NetworkPolicies need to be within a namespace.\nfunc (networkPolicyStrategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":44,"to":47}} {"id":100010188,"name":"GetResetFields","signature":"func (networkPolicyStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/networking/networkpolicy/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (networkPolicyStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"extensions/v1beta1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t\t\"networking.k8s.io/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\treturn fields\n}","line":{"from":49,"to":61}} {"id":100010189,"name":"PrepareForCreate","signature":"func (networkPolicyStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/networking/networkpolicy/strategy.go","code":"// PrepareForCreate clears the status of a NetworkPolicy before creation.\nfunc (networkPolicyStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tnetworkPolicy := obj.(*networking.NetworkPolicy)\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.NetworkPolicyStatus) {\n\t\t// Create does not set a status when operation is not directed to status subresource\n\t\tnetworkPolicy.Status = networking.NetworkPolicyStatus{}\n\t}\n\n\tnetworkPolicy.Generation = 1\n\n}","line":{"from":63,"to":74}} {"id":100010190,"name":"PrepareForUpdate","signature":"func (networkPolicyStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/networking/networkpolicy/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (networkPolicyStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewNetworkPolicy := obj.(*networking.NetworkPolicy)\n\toldNetworkPolicy := old.(*networking.NetworkPolicy)\n\n\t// We copy the status if the FG is enabled, or if previously there was already data on the conditions field\n\t// As soon as the FeatureGate is removed, the whole if statement should be removed as well\n\tif utilfeature.DefaultFeatureGate.Enabled(features.NetworkPolicyStatus) || len(oldNetworkPolicy.Status.Conditions) \u003e 0 {\n\t\t// Update is not allowed to set status when the operation is not directed to status subresource\n\t\tnewNetworkPolicy.Status = oldNetworkPolicy.Status\n\t}\n\n\t// Any changes to the spec increment the generation number, any changes to the\n\t// status should reflect the generation number of the corresponding object.\n\t// See metav1.ObjectMeta description for more information on Generation.\n\tif !reflect.DeepEqual(oldNetworkPolicy.Spec, newNetworkPolicy.Spec) {\n\t\tnewNetworkPolicy.Generation = oldNetworkPolicy.Generation + 1\n\t}\n}","line":{"from":76,"to":94}} {"id":100010191,"name":"Validate","signature":"func (networkPolicyStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/networking/networkpolicy/strategy.go","code":"// Validate validates a new NetworkPolicy.\nfunc (networkPolicyStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tnetworkPolicy := obj.(*networking.NetworkPolicy)\n\tops := validation.ValidationOptionsForNetworking(networkPolicy, nil)\n\treturn validation.ValidateNetworkPolicy(networkPolicy, ops)\n}","line":{"from":96,"to":101}} {"id":100010192,"name":"WarningsOnCreate","signature":"func (networkPolicyStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/networking/networkpolicy/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (networkPolicyStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":103,"to":106}} {"id":100010193,"name":"Canonicalize","signature":"func (networkPolicyStrategy) Canonicalize(obj runtime.Object) {}","file":"pkg/registry/networking/networkpolicy/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (networkPolicyStrategy) Canonicalize(obj runtime.Object) {}","line":{"from":108,"to":109}} {"id":100010194,"name":"AllowCreateOnUpdate","signature":"func (networkPolicyStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/networking/networkpolicy/strategy.go","code":"// AllowCreateOnUpdate is false for NetworkPolicy; this means POST is needed to create one.\nfunc (networkPolicyStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":111,"to":114}} {"id":100010195,"name":"ValidateUpdate","signature":"func (networkPolicyStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/networking/networkpolicy/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (networkPolicyStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\topts := validation.ValidationOptionsForNetworking(obj.(*networking.NetworkPolicy), old.(*networking.NetworkPolicy))\n\tvalidationErrorList := validation.ValidateNetworkPolicy(obj.(*networking.NetworkPolicy), opts)\n\tupdateErrorList := validation.ValidateNetworkPolicyUpdate(obj.(*networking.NetworkPolicy), old.(*networking.NetworkPolicy), opts)\n\treturn append(validationErrorList, updateErrorList...)\n}","line":{"from":116,"to":122}} {"id":100010196,"name":"WarningsOnUpdate","signature":"func (networkPolicyStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/networking/networkpolicy/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (networkPolicyStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":124,"to":127}} {"id":100010197,"name":"AllowUnconditionalUpdate","signature":"func (networkPolicyStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/networking/networkpolicy/strategy.go","code":"// AllowUnconditionalUpdate is the default update policy for NetworkPolicy objects.\nfunc (networkPolicyStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":129,"to":132}} {"id":100010198,"name":"GetResetFields","signature":"func (networkPolicyStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/networking/networkpolicy/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (networkPolicyStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"extensions/v1beta1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t\t\"networking.k8s.io/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t}\n\treturn fields\n}","line":{"from":141,"to":153}} {"id":100010199,"name":"PrepareForUpdate","signature":"func (networkPolicyStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/networking/networkpolicy/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update of status\nfunc (networkPolicyStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewNetworkPolicy := obj.(*networking.NetworkPolicy)\n\toldNetworkPolicy := old.(*networking.NetworkPolicy)\n\t// status changes are not allowed to update spec\n\tnewNetworkPolicy.Spec = oldNetworkPolicy.Spec\n\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.NetworkPolicyStatus) {\n\t\t// As network policy status is composed only of an array of conditions, we can say that the status\n\t\t// is in use if the condition array is bigger than 0.\n\t\t// quoting @thockin: \"we generally keep data in this case, but no updates except to clear it\"\n\t\tif len(newNetworkPolicy.Status.Conditions) == 0 {\n\t\t\tnewNetworkPolicy.Status = networking.NetworkPolicyStatus{}\n\t\t} else {\n\t\t\t// keep the old status in case of the update is not to clear it\n\t\t\tnewNetworkPolicy.Status = oldNetworkPolicy.Status\n\t\t}\n\t}\n}","line":{"from":155,"to":173}} {"id":100010200,"name":"ValidateUpdate","signature":"func (networkPolicyStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/networking/networkpolicy/strategy.go","code":"// ValidateUpdate is the default update validation for an end user updating status\nfunc (networkPolicyStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateNetworkPolicyStatusUpdate(obj.(*networking.NetworkPolicy).Status,\n\t\told.(*networking.NetworkPolicy).Status, field.NewPath(\"status\"))\n}","line":{"from":175,"to":179}} {"id":100010201,"name":"WarningsOnUpdate","signature":"func (networkPolicyStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/networking/networkpolicy/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (networkPolicyStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":181,"to":184}} {"id":100010202,"name":"NewRESTStorage","signature":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error)","file":"pkg/registry/networking/rest/storage_settings.go","code":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error) {\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(networking.GroupName, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs)\n\t// If you add a version here, be sure to add an entry in `k8s.io/kubernetes/cmd/kube-apiserver/app/aggregator.go with specific priorities.\n\t// TODO refactor the plumbing to provide the information in the APIGroupInfo\n\n\tif storageMap, err := p.v1alpha1Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[networkingapiv1alpha1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\tif storageMap, err := p.v1Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[networkingapiv1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\treturn apiGroupInfo, nil\n}","line":{"from":37,"to":55}} {"id":100010203,"name":"v1Storage","signature":"func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/networking/rest/storage_settings.go","code":"func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\t// networkpolicies\n\tif resource := \"networkpolicies\"; apiResourceConfigSource.ResourceEnabled(networkingapiv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tnetworkPolicyStorage, networkPolicyStatusStorage, err := networkpolicystore.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = networkPolicyStorage\n\t\tstorage[resource+\"/status\"] = networkPolicyStatusStorage\n\t}\n\n\t// ingresses\n\tif resource := \"ingresses\"; apiResourceConfigSource.ResourceEnabled(networkingapiv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tingressStorage, ingressStatusStorage, err := ingressstore.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = ingressStorage\n\t\tstorage[resource+\"/status\"] = ingressStatusStorage\n\t}\n\n\t// ingressclasses\n\tif resource := \"ingressclasses\"; apiResourceConfigSource.ResourceEnabled(networkingapiv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tingressClassStorage, err := ingressclassstore.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = ingressClassStorage\n\t}\n\n\treturn storage, nil\n}","line":{"from":57,"to":90}} {"id":100010204,"name":"v1alpha1Storage","signature":"func (p RESTStorageProvider) v1alpha1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/networking/rest/storage_settings.go","code":"func (p RESTStorageProvider) v1alpha1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\t// clustercidrs\n\tif resource := \"clustercidrs\"; apiResourceConfigSource.ResourceEnabled(networkingapiv1alpha1.SchemeGroupVersion.WithResource(resource)) {\n\t\tclusterCIDRCStorage, err := clustercidrstore.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = clusterCIDRCStorage\n\t}\n\n\t// ipaddress\n\tif resource := \"ipaddresses\"; apiResourceConfigSource.ResourceEnabled(networkingapiv1alpha1.SchemeGroupVersion.WithResource(resource)) {\n\t\tipAddressStorage, err := ipaddressstore.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = ipAddressStorage\n\t}\n\treturn storage, nil\n}","line":{"from":92,"to":112}} {"id":100010205,"name":"GroupName","signature":"func (p RESTStorageProvider) GroupName() string","file":"pkg/registry/networking/rest/storage_settings.go","code":"func (p RESTStorageProvider) GroupName() string {\n\treturn networking.GroupName\n}","line":{"from":114,"to":116}} {"id":100010206,"name":"NewRESTStorage","signature":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error)","file":"pkg/registry/node/rest/runtime_class.go","code":"// NewRESTStorage returns a RESTStorageProvider\nfunc (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error) {\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(nodeinternal.GroupName, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs)\n\n\tif storageMap, err := p.v1beta1Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\t// remove in 1.26\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[nodev1beta1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\tif storageMap, err := p.v1Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[nodev1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\treturn apiGroupInfo, nil\n}","line":{"from":34,"to":52}} {"id":100010207,"name":"v1beta1Storage","signature":"func (p RESTStorageProvider) v1beta1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/node/rest/runtime_class.go","code":"func (p RESTStorageProvider) v1beta1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\tif resource := \"runtimeclasses\"; apiResourceConfigSource.ResourceEnabled(nodev1beta1.SchemeGroupVersion.WithResource(resource)) {\n\t\ts, err := runtimeclassstorage.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = s\n\t}\n\n\treturn storage, nil\n}","line":{"from":54,"to":66}} {"id":100010208,"name":"v1Storage","signature":"func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/node/rest/runtime_class.go","code":"func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\tif resource := \"runtimeclasses\"; apiResourceConfigSource.ResourceEnabled(nodev1.SchemeGroupVersion.WithResource(resource)) {\n\t\ts, err := runtimeclassstorage.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = s\n\t}\n\n\treturn storage, nil\n}","line":{"from":68,"to":80}} {"id":100010209,"name":"GroupName","signature":"func (p RESTStorageProvider) GroupName() string","file":"pkg/registry/node/rest/runtime_class.go","code":"// GroupName is the group name for the storage provider\nfunc (p RESTStorageProvider) GroupName() string {\n\treturn nodeinternal.GroupName\n}","line":{"from":82,"to":85}} {"id":100010210,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error)","file":"pkg/registry/node/runtimeclass/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against runtime classes.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026node.RuntimeClass{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026node.RuntimeClassList{} },\n\t\tObjectNameFunc: func(obj runtime.Object) (string, error) {\n\t\t\treturn obj.(*node.RuntimeClass).Name, nil\n\t\t},\n\t\tDefaultQualifiedResource: node.Resource(\"runtimeclasses\"),\n\t\tSingularQualifiedResource: node.Resource(\"runtimeclass\"),\n\n\t\tCreateStrategy: runtimeclass.Strategy,\n\t\tUpdateStrategy: runtimeclass.Strategy,\n\t\tDeleteStrategy: runtimeclass.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026REST{store}, nil\n}","line":{"from":35,"to":57}} {"id":100010211,"name":"NamespaceScoped","signature":"func (strategy) NamespaceScoped() bool","file":"pkg/registry/node/runtimeclass/strategy.go","code":"// NamespaceScoped is false for RuntimeClasses\nfunc (strategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":47,"to":50}} {"id":100010212,"name":"AllowCreateOnUpdate","signature":"func (strategy) AllowCreateOnUpdate() bool","file":"pkg/registry/node/runtimeclass/strategy.go","code":"// AllowCreateOnUpdate is true for RuntimeClasses.\nfunc (strategy) AllowCreateOnUpdate() bool {\n\treturn true\n}","line":{"from":52,"to":55}} {"id":100010213,"name":"PrepareForCreate","signature":"func (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/node/runtimeclass/strategy.go","code":"// PrepareForCreate clears fields that are not allowed to be set by end users\n// on creation.\nfunc (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n}","line":{"from":57,"to":60}} {"id":100010214,"name":"PrepareForUpdate","signature":"func (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/node/runtimeclass/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewRuntimeClass := obj.(*node.RuntimeClass)\n\toldRuntimeClass := old.(*node.RuntimeClass)\n\n\t_, _ = newRuntimeClass, oldRuntimeClass\n}","line":{"from":62,"to":68}} {"id":100010215,"name":"Validate","signature":"func (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/node/runtimeclass/strategy.go","code":"// Validate validates a new RuntimeClass. Validation must check for a correct signature.\nfunc (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\truntimeClass := obj.(*node.RuntimeClass)\n\treturn validation.ValidateRuntimeClass(runtimeClass)\n}","line":{"from":70,"to":74}} {"id":100010216,"name":"WarningsOnCreate","signature":"func (strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/node/runtimeclass/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nodeapi.GetWarningsForRuntimeClass(obj.(*node.RuntimeClass))\n}","line":{"from":76,"to":79}} {"id":100010217,"name":"Canonicalize","signature":"func (strategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/node/runtimeclass/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (strategy) Canonicalize(obj runtime.Object) {\n\t_ = obj.(*node.RuntimeClass)\n}","line":{"from":81,"to":84}} {"id":100010218,"name":"ValidateUpdate","signature":"func (strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/node/runtimeclass/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewObj := obj.(*node.RuntimeClass)\n\terrorList := validation.ValidateRuntimeClass(newObj)\n\treturn append(errorList, validation.ValidateRuntimeClassUpdate(newObj, old.(*node.RuntimeClass))...)\n}","line":{"from":86,"to":91}} {"id":100010219,"name":"WarningsOnUpdate","signature":"func (strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/node/runtimeclass/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nodeapi.GetWarningsForRuntimeClass(obj.(*node.RuntimeClass))\n}","line":{"from":93,"to":96}} {"id":100010220,"name":"AllowUnconditionalUpdate","signature":"func (strategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/node/runtimeclass/strategy.go","code":"// If AllowUnconditionalUpdate() is true and the object specified by\n// the user does not have a resource version, then generic Update()\n// populates it with the latest version. Else, it checks that the\n// version specified by the user matches the version of latest etcd\n// object.\nfunc (strategy) AllowUnconditionalUpdate() bool {\n\treturn false\n}","line":{"from":98,"to":105}} {"id":100010221,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error)","file":"pkg/registry/policy/poddisruptionbudget/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against pod disruption budgets.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026policyapi.PodDisruptionBudget{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026policyapi.PodDisruptionBudgetList{} },\n\t\tDefaultQualifiedResource: policyapi.Resource(\"poddisruptionbudgets\"),\n\t\tSingularQualifiedResource: policyapi.Resource(\"poddisruptionbudget\"),\n\n\t\tCreateStrategy: poddisruptionbudget.Strategy,\n\t\tUpdateStrategy: poddisruptionbudget.Strategy,\n\t\tDeleteStrategy: poddisruptionbudget.Strategy,\n\t\tResetFieldsStrategy: poddisruptionbudget.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = poddisruptionbudget.StatusStrategy\n\tstatusStore.ResetFieldsStrategy = poddisruptionbudget.StatusStrategy\n\treturn \u0026REST{store}, \u0026StatusREST{store: \u0026statusStore}, nil\n}","line":{"from":40,"to":64}} {"id":100010222,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/policy/poddisruptionbudget/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"pdb\"}\n}","line":{"from":66,"to":69}} {"id":100010223,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"pkg/registry/policy/poddisruptionbudget/storage/storage.go","code":"// New creates a new PodDisruptionBudget object.\nfunc (r *StatusREST) New() runtime.Object {\n\treturn \u0026policyapi.PodDisruptionBudget{}\n}","line":{"from":76,"to":79}} {"id":100010224,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"pkg/registry/policy/poddisruptionbudget/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":81,"to":85}} {"id":100010225,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/policy/poddisruptionbudget/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":87,"to":90}} {"id":100010226,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/policy/poddisruptionbudget/storage/storage.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":92,"to":97}} {"id":100010227,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/policy/poddisruptionbudget/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":99,"to":102}} {"id":100010228,"name":"ConvertToTable","signature":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/policy/poddisruptionbudget/storage/storage.go","code":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":104,"to":106}} {"id":100010229,"name":"NamespaceScoped","signature":"func (podDisruptionBudgetStrategy) NamespaceScoped() bool","file":"pkg/registry/policy/poddisruptionbudget/strategy.go","code":"// NamespaceScoped returns true because all PodDisruptionBudget' need to be within a namespace.\nfunc (podDisruptionBudgetStrategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":46,"to":49}} {"id":100010230,"name":"GetResetFields","signature":"func (podDisruptionBudgetStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/policy/poddisruptionbudget/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (podDisruptionBudgetStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"policy/v1beta1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t\t\"policy/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":51,"to":64}} {"id":100010231,"name":"PrepareForCreate","signature":"func (podDisruptionBudgetStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/policy/poddisruptionbudget/strategy.go","code":"// PrepareForCreate clears the status of an PodDisruptionBudget before creation.\nfunc (podDisruptionBudgetStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tpodDisruptionBudget := obj.(*policy.PodDisruptionBudget)\n\t// create cannot set status\n\tpodDisruptionBudget.Status = policy.PodDisruptionBudgetStatus{}\n\n\tpodDisruptionBudget.Generation = 1\n\n\tdropDisabledFields(\u0026podDisruptionBudget.Spec, nil)\n}","line":{"from":66,"to":75}} {"id":100010232,"name":"PrepareForUpdate","signature":"func (podDisruptionBudgetStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/policy/poddisruptionbudget/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (podDisruptionBudgetStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewPodDisruptionBudget := obj.(*policy.PodDisruptionBudget)\n\toldPodDisruptionBudget := old.(*policy.PodDisruptionBudget)\n\t// Update is not allowed to set status\n\tnewPodDisruptionBudget.Status = oldPodDisruptionBudget.Status\n\n\t// Any changes to the spec increment the generation number, any changes to the\n\t// status should reflect the generation number of the corresponding object.\n\t// See metav1.ObjectMeta description for more information on Generation.\n\tif !apiequality.Semantic.DeepEqual(oldPodDisruptionBudget.Spec, newPodDisruptionBudget.Spec) {\n\t\tnewPodDisruptionBudget.Generation = oldPodDisruptionBudget.Generation + 1\n\t}\n\n\tdropDisabledFields(\u0026newPodDisruptionBudget.Spec, \u0026oldPodDisruptionBudget.Spec)\n}","line":{"from":77,"to":92}} {"id":100010233,"name":"Validate","signature":"func (podDisruptionBudgetStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/policy/poddisruptionbudget/strategy.go","code":"// Validate validates a new PodDisruptionBudget.\nfunc (podDisruptionBudgetStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tpodDisruptionBudget := obj.(*policy.PodDisruptionBudget)\n\topts := validation.PodDisruptionBudgetValidationOptions{\n\t\tAllowInvalidLabelValueInSelector: false,\n\t}\n\treturn validation.ValidatePodDisruptionBudget(podDisruptionBudget, opts)\n}","line":{"from":94,"to":101}} {"id":100010234,"name":"WarningsOnCreate","signature":"func (podDisruptionBudgetStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/policy/poddisruptionbudget/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (podDisruptionBudgetStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":103,"to":106}} {"id":100010235,"name":"Canonicalize","signature":"func (podDisruptionBudgetStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/policy/poddisruptionbudget/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (podDisruptionBudgetStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":108,"to":110}} {"id":100010236,"name":"AllowCreateOnUpdate","signature":"func (podDisruptionBudgetStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/policy/poddisruptionbudget/strategy.go","code":"// AllowCreateOnUpdate is true for PodDisruptionBudget; this means you may create one with a PUT request.\nfunc (podDisruptionBudgetStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":112,"to":115}} {"id":100010237,"name":"ValidateUpdate","signature":"func (podDisruptionBudgetStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/policy/poddisruptionbudget/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (podDisruptionBudgetStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\topts := validation.PodDisruptionBudgetValidationOptions{\n\t\tAllowInvalidLabelValueInSelector: hasInvalidLabelValueInLabelSelector(old.(*policy.PodDisruptionBudget)),\n\t}\n\treturn validation.ValidatePodDisruptionBudget(obj.(*policy.PodDisruptionBudget), opts)\n}","line":{"from":117,"to":123}} {"id":100010238,"name":"WarningsOnUpdate","signature":"func (podDisruptionBudgetStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/policy/poddisruptionbudget/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (podDisruptionBudgetStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":125,"to":128}} {"id":100010239,"name":"AllowUnconditionalUpdate","signature":"func (podDisruptionBudgetStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/policy/poddisruptionbudget/strategy.go","code":"// AllowUnconditionalUpdate is the default update policy for PodDisruptionBudget objects. Status update should\n// only be allowed if version match.\nfunc (podDisruptionBudgetStrategy) AllowUnconditionalUpdate() bool {\n\treturn false\n}","line":{"from":130,"to":134}} {"id":100010240,"name":"GetResetFields","signature":"func (podDisruptionBudgetStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/policy/poddisruptionbudget/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (podDisruptionBudgetStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"policy/v1beta1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t\t\"policy/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":143,"to":156}} {"id":100010241,"name":"PrepareForUpdate","signature":"func (podDisruptionBudgetStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/policy/poddisruptionbudget/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update of status\nfunc (podDisruptionBudgetStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewPodDisruptionBudget := obj.(*policy.PodDisruptionBudget)\n\toldPodDisruptionBudget := old.(*policy.PodDisruptionBudget)\n\t// status changes are not allowed to update spec\n\tnewPodDisruptionBudget.Spec = oldPodDisruptionBudget.Spec\n}","line":{"from":158,"to":164}} {"id":100010242,"name":"ValidateUpdate","signature":"func (podDisruptionBudgetStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/policy/poddisruptionbudget/strategy.go","code":"// ValidateUpdate is the default update validation for an end user updating status\nfunc (podDisruptionBudgetStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tvar apiVersion schema.GroupVersion\n\tif requestInfo, found := genericapirequest.RequestInfoFrom(ctx); found {\n\t\tapiVersion = schema.GroupVersion{\n\t\t\tGroup: requestInfo.APIGroup,\n\t\t\tVersion: requestInfo.APIVersion,\n\t\t}\n\t}\n\treturn validation.ValidatePodDisruptionBudgetStatusUpdate(obj.(*policy.PodDisruptionBudget).Status,\n\t\told.(*policy.PodDisruptionBudget).Status, field.NewPath(\"status\"), apiVersion)\n}","line":{"from":166,"to":177}} {"id":100010243,"name":"WarningsOnUpdate","signature":"func (podDisruptionBudgetStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/policy/poddisruptionbudget/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (podDisruptionBudgetStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":179,"to":182}} {"id":100010244,"name":"hasInvalidLabelValueInLabelSelector","signature":"func hasInvalidLabelValueInLabelSelector(pdb *policy.PodDisruptionBudget) bool","file":"pkg/registry/policy/poddisruptionbudget/strategy.go","code":"func hasInvalidLabelValueInLabelSelector(pdb *policy.PodDisruptionBudget) bool {\n\tif pdb.Spec.Selector != nil {\n\t\tlabelSelectorValidationOptions := metav1validation.LabelSelectorValidationOptions{AllowInvalidLabelValueInSelector: false}\n\t\treturn len(metav1validation.ValidateLabelSelector(pdb.Spec.Selector, labelSelectorValidationOptions, nil)) \u003e 0\n\t}\n\treturn false\n}","line":{"from":184,"to":190}} {"id":100010245,"name":"dropDisabledFields","signature":"func dropDisabledFields(pdbSpec, oldPDBSpec *policy.PodDisruptionBudgetSpec)","file":"pkg/registry/policy/poddisruptionbudget/strategy.go","code":"// dropDisabledFields removes disabled fields from the pod disruption budget spec.\n// This should be called from PrepareForCreate/PrepareForUpdate for all resources containing a pod disruption budget spec.\nfunc dropDisabledFields(pdbSpec, oldPDBSpec *policy.PodDisruptionBudgetSpec) {\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.PDBUnhealthyPodEvictionPolicy) {\n\t\tif !unhealthyPodEvictionPolicyInUse(oldPDBSpec) {\n\t\t\tpdbSpec.UnhealthyPodEvictionPolicy = nil\n\t\t}\n\t}\n}","line":{"from":192,"to":200}} {"id":100010246,"name":"unhealthyPodEvictionPolicyInUse","signature":"func unhealthyPodEvictionPolicyInUse(oldPDBSpec *policy.PodDisruptionBudgetSpec) bool","file":"pkg/registry/policy/poddisruptionbudget/strategy.go","code":"func unhealthyPodEvictionPolicyInUse(oldPDBSpec *policy.PodDisruptionBudgetSpec) bool {\n\tif oldPDBSpec == nil {\n\t\treturn false\n\t}\n\tif oldPDBSpec.UnhealthyPodEvictionPolicy != nil {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":202,"to":210}} {"id":100010247,"name":"NewRESTStorage","signature":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error)","file":"pkg/registry/policy/rest/storage_policy.go","code":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error) {\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(policy.GroupName, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs)\n\t// If you add a version here, be sure to add an entry in `k8s.io/kubernetes/cmd/kube-apiserver/app/aggregator.go with specific priorities.\n\t// TODO refactor the plumbing to provide the information in the APIGroupInfo\n\n\tif storageMap, err := p.v1beta1Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[policyapiv1beta1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\tif storageMap, err := p.v1Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[policyapiv1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\treturn apiGroupInfo, nil\n}","line":{"from":33,"to":51}} {"id":100010248,"name":"v1beta1Storage","signature":"func (p RESTStorageProvider) v1beta1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/policy/rest/storage_policy.go","code":"func (p RESTStorageProvider) v1beta1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\t// poddisruptionbudgets\n\tif resource := \"poddisruptionbudgets\"; apiResourceConfigSource.ResourceEnabled(policyapiv1beta1.SchemeGroupVersion.WithResource(resource)) {\n\t\tpoddisruptionbudgetStorage, poddisruptionbudgetStatusStorage, err := poddisruptionbudgetstore.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = poddisruptionbudgetStorage\n\t\tstorage[resource+\"/status\"] = poddisruptionbudgetStatusStorage\n\t}\n\n\treturn storage, nil\n}","line":{"from":53,"to":67}} {"id":100010249,"name":"v1Storage","signature":"func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/policy/rest/storage_policy.go","code":"func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\tif resource := \"poddisruptionbudgets\"; apiResourceConfigSource.ResourceEnabled(policyapiv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tpoddisruptionbudgetStorage, poddisruptionbudgetStatusStorage, err := poddisruptionbudgetstore.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = poddisruptionbudgetStorage\n\t\tstorage[resource+\"/status\"] = poddisruptionbudgetStatusStorage\n\t}\n\n\treturn storage, nil\n}","line":{"from":69,"to":82}} {"id":100010250,"name":"GroupName","signature":"func (p RESTStorageProvider) GroupName() string","file":"pkg/registry/policy/rest/storage_policy.go","code":"func (p RESTStorageProvider) GroupName() string {\n\treturn policy.GroupName\n}","line":{"from":84,"to":86}} {"id":100010251,"name":"NewStorage","signature":"func NewStorage(s rest.StandardStorage, authorizer authorizer.Authorizer, ruleResolver rbacregistryvalidation.AuthorizationRuleResolver) *Storage","file":"pkg/registry/rbac/clusterrole/policybased/storage.go","code":"func NewStorage(s rest.StandardStorage, authorizer authorizer.Authorizer, ruleResolver rbacregistryvalidation.AuthorizationRuleResolver) *Storage {\n\treturn \u0026Storage{s, authorizer, ruleResolver}\n}","line":{"from":45,"to":47}} {"id":100010252,"name":"Destroy","signature":"func (r *Storage) Destroy()","file":"pkg/registry/rbac/clusterrole/policybased/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *Storage) Destroy() {\n\tr.StandardStorage.Destroy()\n}","line":{"from":49,"to":52}} {"id":100010253,"name":"NamespaceScoped","signature":"func (r *Storage) NamespaceScoped() bool","file":"pkg/registry/rbac/clusterrole/policybased/storage.go","code":"func (r *Storage) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":54,"to":56}} {"id":100010254,"name":"StorageVersion","signature":"func (r *Storage) StorageVersion() runtime.GroupVersioner","file":"pkg/registry/rbac/clusterrole/policybased/storage.go","code":"func (r *Storage) StorageVersion() runtime.GroupVersioner {\n\tsvp, ok := r.StandardStorage.(rest.StorageVersionProvider)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn svp.StorageVersion()\n}","line":{"from":58,"to":64}} {"id":100010255,"name":"Create","signature":"func (s *Storage) Create(ctx context.Context, obj runtime.Object, createValidatingAdmission rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error)","file":"pkg/registry/rbac/clusterrole/policybased/storage.go","code":"func (s *Storage) Create(ctx context.Context, obj runtime.Object, createValidatingAdmission rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {\n\tif rbacregistry.EscalationAllowed(ctx) || rbacregistry.RoleEscalationAuthorized(ctx, s.authorizer) {\n\t\treturn s.StandardStorage.Create(ctx, obj, createValidatingAdmission, options)\n\t}\n\n\tclusterRole := obj.(*rbac.ClusterRole)\n\trules := clusterRole.Rules\n\tif err := rbacregistryvalidation.ConfirmNoEscalationInternal(ctx, s.ruleResolver, rules); err != nil {\n\t\treturn nil, apierrors.NewForbidden(groupResource, clusterRole.Name, err)\n\t}\n\t// to set the aggregation rule, since it can gather anything, requires * on *.*\n\tif hasAggregationRule(clusterRole) {\n\t\tif err := rbacregistryvalidation.ConfirmNoEscalationInternal(ctx, s.ruleResolver, fullAuthority); err != nil {\n\t\t\treturn nil, apierrors.NewForbidden(groupResource, clusterRole.Name, errors.New(\"must have cluster-admin privileges to use the aggregationRule\"))\n\t\t}\n\t}\n\n\treturn s.StandardStorage.Create(ctx, obj, createValidatingAdmission, options)\n}","line":{"from":73,"to":91}} {"id":100010256,"name":"Update","signature":"func (s *Storage) Update(ctx context.Context, name string, obj rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/rbac/clusterrole/policybased/storage.go","code":"func (s *Storage) Update(ctx context.Context, name string, obj rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\tif rbacregistry.EscalationAllowed(ctx) || rbacregistry.RoleEscalationAuthorized(ctx, s.authorizer) {\n\t\treturn s.StandardStorage.Update(ctx, name, obj, createValidation, updateValidation, forceAllowCreate, options)\n\t}\n\n\tnonEscalatingInfo := rest.WrapUpdatedObjectInfo(obj, func(ctx context.Context, obj runtime.Object, oldObj runtime.Object) (runtime.Object, error) {\n\t\tclusterRole := obj.(*rbac.ClusterRole)\n\t\toldClusterRole := oldObj.(*rbac.ClusterRole)\n\n\t\t// if we're only mutating fields needed for the GC to eventually delete this obj, return\n\t\tif rbacregistry.IsOnlyMutatingGCFields(obj, oldObj, kapihelper.Semantic) {\n\t\t\treturn obj, nil\n\t\t}\n\n\t\trules := clusterRole.Rules\n\t\tif err := rbacregistryvalidation.ConfirmNoEscalationInternal(ctx, s.ruleResolver, rules); err != nil {\n\t\t\treturn nil, apierrors.NewForbidden(groupResource, clusterRole.Name, err)\n\t\t}\n\t\t// to change the aggregation rule, since it can gather anything and prevent tightening, requires * on *.*\n\t\tif hasAggregationRule(clusterRole) || hasAggregationRule(oldClusterRole) {\n\t\t\tif err := rbacregistryvalidation.ConfirmNoEscalationInternal(ctx, s.ruleResolver, fullAuthority); err != nil {\n\t\t\t\treturn nil, apierrors.NewForbidden(groupResource, clusterRole.Name, errors.New(\"must have cluster-admin privileges to use the aggregationRule\"))\n\t\t\t}\n\t\t}\n\n\t\treturn obj, nil\n\t})\n\n\treturn s.StandardStorage.Update(ctx, name, nonEscalatingInfo, createValidation, updateValidation, forceAllowCreate, options)\n}","line":{"from":93,"to":122}} {"id":100010257,"name":"hasAggregationRule","signature":"func hasAggregationRule(clusterRole *rbac.ClusterRole) bool","file":"pkg/registry/rbac/clusterrole/policybased/storage.go","code":"func hasAggregationRule(clusterRole *rbac.ClusterRole) bool {\n\treturn clusterRole.AggregationRule != nil \u0026\u0026 len(clusterRole.AggregationRule.ClusterRoleSelectors) \u003e 0\n}","line":{"from":124,"to":126}} {"id":100010258,"name":"GetSingularName","signature":"func (s *Storage) GetSingularName() string","file":"pkg/registry/rbac/clusterrole/policybased/storage.go","code":"func (s *Storage) GetSingularName() string {\n\tsnp, ok := s.StandardStorage.(rest.SingularNameProvider)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn snp.GetSingularName()\n}","line":{"from":130,"to":136}} {"id":100010259,"name":"NewRegistry","signature":"func NewRegistry(s rest.StandardStorage) Registry","file":"pkg/registry/rbac/clusterrole/registry.go","code":"// NewRegistry returns a new Registry interface for the given Storage. Any mismatched\n// types will panic.\nfunc NewRegistry(s rest.StandardStorage) Registry {\n\treturn \u0026storage{s}\n}","line":{"from":40,"to":44}} {"id":100010260,"name":"GetClusterRole","signature":"func (s *storage) GetClusterRole(ctx context.Context, name string, options *metav1.GetOptions) (*rbacv1.ClusterRole, error)","file":"pkg/registry/rbac/clusterrole/registry.go","code":"func (s *storage) GetClusterRole(ctx context.Context, name string, options *metav1.GetOptions) (*rbacv1.ClusterRole, error) {\n\tobj, err := s.Get(ctx, name, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret := \u0026rbacv1.ClusterRole{}\n\tif err := rbacv1helpers.Convert_rbac_ClusterRole_To_v1_ClusterRole(obj.(*rbac.ClusterRole), ret, nil); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ret, nil\n}","line":{"from":46,"to":57}} {"id":100010261,"name":"GetClusterRole","signature":"func (a AuthorizerAdapter) GetClusterRole(name string) (*rbacv1.ClusterRole, error)","file":"pkg/registry/rbac/clusterrole/registry.go","code":"// GetClusterRole returns the corresponding ClusterRole by name\nfunc (a AuthorizerAdapter) GetClusterRole(name string) (*rbacv1.ClusterRole, error) {\n\treturn a.Registry.GetClusterRole(genericapirequest.NewContext(), name, \u0026metav1.GetOptions{})\n}","line":{"from":64,"to":67}} {"id":100010262,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error)","file":"pkg/registry/rbac/clusterrole/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against ClusterRole objects.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026rbac.ClusterRole{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026rbac.ClusterRoleList{} },\n\t\tDefaultQualifiedResource: rbac.Resource(\"clusterroles\"),\n\t\tSingularQualifiedResource: rbac.Resource(\"clusterrole\"),\n\n\t\tCreateStrategy: clusterrole.Strategy,\n\t\tUpdateStrategy: clusterrole.Strategy,\n\t\tDeleteStrategy: clusterrole.Strategy,\n\n\t\t// TODO: define table converter that exposes more than name/creation timestamp?\n\t\tTableConvertor: rest.NewDefaultTableConvertor(rbac.Resource(\"clusterroles\")),\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026REST{store}, nil\n}","line":{"from":33,"to":54}} {"id":100010263,"name":"NamespaceScoped","signature":"func (strategy) NamespaceScoped() bool","file":"pkg/registry/rbac/clusterrole/strategy.go","code":"// NamespaceScoped is false for ClusterRoles.\nfunc (strategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":48,"to":51}} {"id":100010264,"name":"AllowCreateOnUpdate","signature":"func (strategy) AllowCreateOnUpdate() bool","file":"pkg/registry/rbac/clusterrole/strategy.go","code":"// AllowCreateOnUpdate is true for ClusterRoles.\nfunc (strategy) AllowCreateOnUpdate() bool {\n\treturn true\n}","line":{"from":53,"to":56}} {"id":100010265,"name":"PrepareForCreate","signature":"func (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/rbac/clusterrole/strategy.go","code":"// PrepareForCreate clears fields that are not allowed to be set by end users\n// on creation.\nfunc (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\t_ = obj.(*rbac.ClusterRole)\n}","line":{"from":58,"to":62}} {"id":100010266,"name":"PrepareForUpdate","signature":"func (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/rbac/clusterrole/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewClusterRole := obj.(*rbac.ClusterRole)\n\toldClusterRole := old.(*rbac.ClusterRole)\n\n\t_, _ = newClusterRole, oldClusterRole\n}","line":{"from":64,"to":70}} {"id":100010267,"name":"Validate","signature":"func (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/rbac/clusterrole/strategy.go","code":"// Validate validates a new ClusterRole. Validation must check for a correct signature.\nfunc (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tclusterRole := obj.(*rbac.ClusterRole)\n\topts := validation.ClusterRoleValidationOptions{\n\t\tAllowInvalidLabelValueInSelector: false,\n\t}\n\treturn validation.ValidateClusterRole(clusterRole, opts)\n}","line":{"from":72,"to":79}} {"id":100010268,"name":"WarningsOnCreate","signature":"func (strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return nil }","file":"pkg/registry/rbac/clusterrole/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return nil }","line":{"from":81,"to":82}} {"id":100010269,"name":"Canonicalize","signature":"func (strategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/rbac/clusterrole/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (strategy) Canonicalize(obj runtime.Object) {\n\t_ = obj.(*rbac.ClusterRole)\n}","line":{"from":84,"to":87}} {"id":100010270,"name":"ValidateUpdate","signature":"func (strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/rbac/clusterrole/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewObj := obj.(*rbac.ClusterRole)\n\toldObj := old.(*rbac.ClusterRole)\n\topts := validation.ClusterRoleValidationOptions{\n\t\tAllowInvalidLabelValueInSelector: hasInvalidLabelValueInLabelSelector(oldObj),\n\t}\n\terrorList := validation.ValidateClusterRole(newObj, opts)\n\treturn append(errorList, validation.ValidateClusterRoleUpdate(newObj, old.(*rbac.ClusterRole), opts)...)\n}","line":{"from":89,"to":98}} {"id":100010271,"name":"WarningsOnUpdate","signature":"func (strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/rbac/clusterrole/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":100,"to":103}} {"id":100010272,"name":"AllowUnconditionalUpdate","signature":"func (strategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/rbac/clusterrole/strategy.go","code":"// If AllowUnconditionalUpdate() is true and the object specified by\n// the user does not have a resource version, then generic Update()\n// populates it with the latest version. Else, it checks that the\n// version specified by the user matches the version of latest etcd\n// object.\nfunc (strategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":105,"to":112}} {"id":100010273,"name":"hasInvalidLabelValueInLabelSelector","signature":"func hasInvalidLabelValueInLabelSelector(role *rbac.ClusterRole) bool","file":"pkg/registry/rbac/clusterrole/strategy.go","code":"func hasInvalidLabelValueInLabelSelector(role *rbac.ClusterRole) bool {\n\tif role.AggregationRule != nil {\n\t\tlabelSelectorValidationOptions := metav1validation.LabelSelectorValidationOptions{AllowInvalidLabelValueInSelector: false}\n\t\tfor _, selector := range role.AggregationRule.ClusterRoleSelectors {\n\t\t\tif len(metav1validation.ValidateLabelSelector(\u0026selector, labelSelectorValidationOptions, nil)) \u003e 0 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":114,"to":124}} {"id":100010274,"name":"NewStorage","signature":"func NewStorage(s rest.StandardStorage, authorizer authorizer.Authorizer, ruleResolver rbacregistryvalidation.AuthorizationRuleResolver) *Storage","file":"pkg/registry/rbac/clusterrolebinding/policybased/storage.go","code":"func NewStorage(s rest.StandardStorage, authorizer authorizer.Authorizer, ruleResolver rbacregistryvalidation.AuthorizationRuleResolver) *Storage {\n\treturn \u0026Storage{s, authorizer, ruleResolver}\n}","line":{"from":46,"to":48}} {"id":100010275,"name":"Destroy","signature":"func (r *Storage) Destroy()","file":"pkg/registry/rbac/clusterrolebinding/policybased/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *Storage) Destroy() {\n\tr.StandardStorage.Destroy()\n}","line":{"from":50,"to":53}} {"id":100010276,"name":"NamespaceScoped","signature":"func (r *Storage) NamespaceScoped() bool","file":"pkg/registry/rbac/clusterrolebinding/policybased/storage.go","code":"func (r *Storage) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":55,"to":57}} {"id":100010277,"name":"StorageVersion","signature":"func (r *Storage) StorageVersion() runtime.GroupVersioner","file":"pkg/registry/rbac/clusterrolebinding/policybased/storage.go","code":"func (r *Storage) StorageVersion() runtime.GroupVersioner {\n\tsvp, ok := r.StandardStorage.(rest.StorageVersionProvider)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn svp.StorageVersion()\n}","line":{"from":59,"to":65}} {"id":100010278,"name":"Create","signature":"func (s *Storage) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error)","file":"pkg/registry/rbac/clusterrolebinding/policybased/storage.go","code":"func (s *Storage) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {\n\tif rbacregistry.EscalationAllowed(ctx) {\n\t\treturn s.StandardStorage.Create(ctx, obj, createValidation, options)\n\t}\n\n\tclusterRoleBinding := obj.(*rbac.ClusterRoleBinding)\n\tif rbacregistry.BindingAuthorized(ctx, clusterRoleBinding.RoleRef, metav1.NamespaceNone, s.authorizer) {\n\t\treturn s.StandardStorage.Create(ctx, obj, createValidation, options)\n\t}\n\n\tv1RoleRef := rbacv1.RoleRef{}\n\terr := rbacv1helpers.Convert_rbac_RoleRef_To_v1_RoleRef(\u0026clusterRoleBinding.RoleRef, \u0026v1RoleRef, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trules, err := s.ruleResolver.GetRoleReferenceRules(v1RoleRef, metav1.NamespaceNone)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rbacregistryvalidation.ConfirmNoEscalation(ctx, s.ruleResolver, rules); err != nil {\n\t\treturn nil, errors.NewForbidden(groupResource, clusterRoleBinding.Name, err)\n\t}\n\treturn s.StandardStorage.Create(ctx, obj, createValidation, options)\n}","line":{"from":69,"to":92}} {"id":100010279,"name":"Update","signature":"func (s *Storage) Update(ctx context.Context, name string, obj rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/rbac/clusterrolebinding/policybased/storage.go","code":"func (s *Storage) Update(ctx context.Context, name string, obj rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\tif rbacregistry.EscalationAllowed(ctx) {\n\t\treturn s.StandardStorage.Update(ctx, name, obj, createValidation, updateValidation, forceAllowCreate, options)\n\t}\n\n\tnonEscalatingInfo := rest.WrapUpdatedObjectInfo(obj, func(ctx context.Context, obj runtime.Object, oldObj runtime.Object) (runtime.Object, error) {\n\t\tclusterRoleBinding := obj.(*rbac.ClusterRoleBinding)\n\n\t\t// if we're only mutating fields needed for the GC to eventually delete this obj, return\n\t\tif rbacregistry.IsOnlyMutatingGCFields(obj, oldObj, kapihelper.Semantic) {\n\t\t\treturn obj, nil\n\t\t}\n\n\t\t// if we're explicitly authorized to bind this clusterrole, return\n\t\tif rbacregistry.BindingAuthorized(ctx, clusterRoleBinding.RoleRef, metav1.NamespaceNone, s.authorizer) {\n\t\t\treturn obj, nil\n\t\t}\n\n\t\t// Otherwise, see if we already have all the permissions contained in the referenced clusterrole\n\t\tv1RoleRef := rbacv1.RoleRef{}\n\t\terr := rbacv1helpers.Convert_rbac_RoleRef_To_v1_RoleRef(\u0026clusterRoleBinding.RoleRef, \u0026v1RoleRef, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trules, err := s.ruleResolver.GetRoleReferenceRules(v1RoleRef, metav1.NamespaceNone)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := rbacregistryvalidation.ConfirmNoEscalation(ctx, s.ruleResolver, rules); err != nil {\n\t\t\treturn nil, errors.NewForbidden(groupResource, clusterRoleBinding.Name, err)\n\t\t}\n\t\treturn obj, nil\n\t})\n\n\treturn s.StandardStorage.Update(ctx, name, nonEscalatingInfo, createValidation, updateValidation, forceAllowCreate, options)\n}","line":{"from":94,"to":129}} {"id":100010280,"name":"GetSingularName","signature":"func (s *Storage) GetSingularName() string","file":"pkg/registry/rbac/clusterrolebinding/policybased/storage.go","code":"func (s *Storage) GetSingularName() string {\n\tsnp, ok := s.StandardStorage.(rest.SingularNameProvider)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn snp.GetSingularName()\n}","line":{"from":133,"to":139}} {"id":100010281,"name":"NewRegistry","signature":"func NewRegistry(s rest.StandardStorage) Registry","file":"pkg/registry/rbac/clusterrolebinding/registry.go","code":"// NewRegistry returns a new Registry interface for the given Storage. Any mismatched\n// types will panic.\nfunc NewRegistry(s rest.StandardStorage) Registry {\n\treturn \u0026storage{s}\n}","line":{"from":40,"to":44}} {"id":100010282,"name":"ListClusterRoleBindings","signature":"func (s *storage) ListClusterRoleBindings(ctx context.Context, options *metainternalversion.ListOptions) (*rbacv1.ClusterRoleBindingList, error)","file":"pkg/registry/rbac/clusterrolebinding/registry.go","code":"func (s *storage) ListClusterRoleBindings(ctx context.Context, options *metainternalversion.ListOptions) (*rbacv1.ClusterRoleBindingList, error) {\n\tobj, err := s.List(ctx, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret := \u0026rbacv1.ClusterRoleBindingList{}\n\tif err := rbacv1helpers.Convert_rbac_ClusterRoleBindingList_To_v1_ClusterRoleBindingList(obj.(*rbac.ClusterRoleBindingList), ret, nil); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ret, nil\n}","line":{"from":46,"to":57}} {"id":100010283,"name":"ListClusterRoleBindings","signature":"func (a AuthorizerAdapter) ListClusterRoleBindings() ([]*rbacv1.ClusterRoleBinding, error)","file":"pkg/registry/rbac/clusterrolebinding/registry.go","code":"func (a AuthorizerAdapter) ListClusterRoleBindings() ([]*rbacv1.ClusterRoleBinding, error) {\n\tlist, err := a.Registry.ListClusterRoleBindings(genericapirequest.NewContext(), \u0026metainternalversion.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret := []*rbacv1.ClusterRoleBinding{}\n\tfor i := range list.Items {\n\t\tret = append(ret, \u0026list.Items[i])\n\t}\n\treturn ret, nil\n}","line":{"from":64,"to":75}} {"id":100010284,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error)","file":"pkg/registry/rbac/clusterrolebinding/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against ClusterRoleBinding objects.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026rbac.ClusterRoleBinding{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026rbac.ClusterRoleBindingList{} },\n\t\tDefaultQualifiedResource: rbac.Resource(\"clusterrolebindings\"),\n\t\tSingularQualifiedResource: rbac.Resource(\"clusterrolebinding\"),\n\n\t\tCreateStrategy: clusterrolebinding.Strategy,\n\t\tUpdateStrategy: clusterrolebinding.Strategy,\n\t\tDeleteStrategy: clusterrolebinding.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026REST{store}, nil\n}","line":{"from":35,"to":55}} {"id":100010285,"name":"NamespaceScoped","signature":"func (strategy) NamespaceScoped() bool","file":"pkg/registry/rbac/clusterrolebinding/strategy.go","code":"// NamespaceScoped is false for ClusterRoleBindings.\nfunc (strategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":47,"to":50}} {"id":100010286,"name":"AllowCreateOnUpdate","signature":"func (strategy) AllowCreateOnUpdate() bool","file":"pkg/registry/rbac/clusterrolebinding/strategy.go","code":"// AllowCreateOnUpdate is true for ClusterRoleBindings.\nfunc (strategy) AllowCreateOnUpdate() bool {\n\treturn true\n}","line":{"from":52,"to":55}} {"id":100010287,"name":"PrepareForCreate","signature":"func (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/rbac/clusterrolebinding/strategy.go","code":"// PrepareForCreate clears fields that are not allowed to be set by end users\n// on creation.\nfunc (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\t_ = obj.(*rbac.ClusterRoleBinding)\n}","line":{"from":57,"to":61}} {"id":100010288,"name":"PrepareForUpdate","signature":"func (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/rbac/clusterrolebinding/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewClusterRoleBinding := obj.(*rbac.ClusterRoleBinding)\n\toldClusterRoleBinding := old.(*rbac.ClusterRoleBinding)\n\n\t_, _ = newClusterRoleBinding, oldClusterRoleBinding\n}","line":{"from":63,"to":69}} {"id":100010289,"name":"Validate","signature":"func (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/rbac/clusterrolebinding/strategy.go","code":"// Validate validates a new ClusterRoleBinding. Validation must check for a correct signature.\nfunc (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tclusterRoleBinding := obj.(*rbac.ClusterRoleBinding)\n\treturn validation.ValidateClusterRoleBinding(clusterRoleBinding)\n}","line":{"from":71,"to":75}} {"id":100010290,"name":"WarningsOnCreate","signature":"func (strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return nil }","file":"pkg/registry/rbac/clusterrolebinding/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return nil }","line":{"from":77,"to":78}} {"id":100010291,"name":"Canonicalize","signature":"func (strategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/rbac/clusterrolebinding/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (strategy) Canonicalize(obj runtime.Object) {\n\t_ = obj.(*rbac.ClusterRoleBinding)\n}","line":{"from":80,"to":83}} {"id":100010292,"name":"ValidateUpdate","signature":"func (strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/rbac/clusterrolebinding/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewObj := obj.(*rbac.ClusterRoleBinding)\n\terrorList := validation.ValidateClusterRoleBinding(newObj)\n\treturn append(errorList, validation.ValidateClusterRoleBindingUpdate(newObj, old.(*rbac.ClusterRoleBinding))...)\n}","line":{"from":85,"to":90}} {"id":100010293,"name":"WarningsOnUpdate","signature":"func (strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/rbac/clusterrolebinding/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":92,"to":95}} {"id":100010294,"name":"AllowUnconditionalUpdate","signature":"func (strategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/rbac/clusterrolebinding/strategy.go","code":"// If AllowUnconditionalUpdate() is true and the object specified by\n// the user does not have a resource version, then generic Update()\n// populates it with the latest version. Else, it checks that the\n// version specified by the user matches the version of latest etcd\n// object.\nfunc (strategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":97,"to":104}} {"id":100010295,"name":"EscalationAllowed","signature":"func EscalationAllowed(ctx context.Context) bool","file":"pkg/registry/rbac/escalation_check.go","code":"// EscalationAllowed checks if the user associated with the context is a superuser\nfunc EscalationAllowed(ctx context.Context) bool {\n\tu, ok := genericapirequest.UserFrom(ctx)\n\tif !ok {\n\t\treturn false\n\t}\n\n\t// system:masters is special because the API server uses it for privileged loopback connections\n\t// therefore we know that a member of system:masters can always do anything\n\tfor _, group := range u.GetGroups() {\n\t\tif group == user.SystemPrivilegedGroup {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":31,"to":47}} {"id":100010296,"name":"RoleEscalationAuthorized","signature":"func RoleEscalationAuthorized(ctx context.Context, a authorizer.Authorizer) bool","file":"pkg/registry/rbac/escalation_check.go","code":"// RoleEscalationAuthorized checks if the user associated with the context is explicitly authorized to escalate the role resource associated with the context\nfunc RoleEscalationAuthorized(ctx context.Context, a authorizer.Authorizer) bool {\n\tif a == nil {\n\t\treturn false\n\t}\n\n\tuser, ok := genericapirequest.UserFrom(ctx)\n\tif !ok {\n\t\treturn false\n\t}\n\n\trequestInfo, ok := genericapirequest.RequestInfoFrom(ctx)\n\tif !ok {\n\t\treturn false\n\t}\n\n\tif !requestInfo.IsResourceRequest {\n\t\treturn false\n\t}\n\n\trequestResource := schema.GroupResource{Group: requestInfo.APIGroup, Resource: requestInfo.Resource}\n\tif !roleResources[requestResource] {\n\t\treturn false\n\t}\n\n\tattrs := authorizer.AttributesRecord{\n\t\tUser: user,\n\t\tVerb: \"escalate\",\n\t\tAPIGroup: requestInfo.APIGroup,\n\t\tAPIVersion: \"*\",\n\t\tResource: requestInfo.Resource,\n\t\tName: requestInfo.Name,\n\t\tNamespace: requestInfo.Namespace,\n\t\tResourceRequest: true,\n\t}\n\n\tdecision, _, err := a.Authorize(ctx, attrs)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\n\t\t\t\"error authorizing user %#v to escalate %#v named %q in namespace %q: %v\",\n\t\t\tuser, requestResource, requestInfo.Name, requestInfo.Namespace, err,\n\t\t))\n\t}\n\treturn decision == authorizer.DecisionAllow\n}","line":{"from":54,"to":98}} {"id":100010297,"name":"BindingAuthorized","signature":"func BindingAuthorized(ctx context.Context, roleRef rbac.RoleRef, bindingNamespace string, a authorizer.Authorizer) bool","file":"pkg/registry/rbac/escalation_check.go","code":"// BindingAuthorized returns true if the user associated with the context is explicitly authorized to bind the specified roleRef\nfunc BindingAuthorized(ctx context.Context, roleRef rbac.RoleRef, bindingNamespace string, a authorizer.Authorizer) bool {\n\tif a == nil {\n\t\treturn false\n\t}\n\n\tuser, ok := genericapirequest.UserFrom(ctx)\n\tif !ok {\n\t\treturn false\n\t}\n\n\tattrs := authorizer.AttributesRecord{\n\t\tUser: user,\n\t\tVerb: \"bind\",\n\t\t// check against the namespace where the binding is being created (or the empty namespace for clusterrolebindings).\n\t\t// this allows delegation to bind particular clusterroles in rolebindings within particular namespaces,\n\t\t// and to authorize binding a clusterrole across all namespaces in a clusterrolebinding.\n\t\tNamespace: bindingNamespace,\n\t\tResourceRequest: true,\n\t}\n\n\t// This occurs after defaulting and conversion, so values pulled from the roleRef won't change\n\t// Invalid APIGroup or Name values will fail validation\n\tswitch roleRef.Kind {\n\tcase \"ClusterRole\":\n\t\tattrs.APIGroup = roleRef.APIGroup\n\t\tattrs.APIVersion = \"*\"\n\t\tattrs.Resource = \"clusterroles\"\n\t\tattrs.Name = roleRef.Name\n\tcase \"Role\":\n\t\tattrs.APIGroup = roleRef.APIGroup\n\t\tattrs.APIVersion = \"*\"\n\t\tattrs.Resource = \"roles\"\n\t\tattrs.Name = roleRef.Name\n\tdefault:\n\t\treturn false\n\t}\n\n\tdecision, _, err := a.Authorize(ctx, attrs)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\n\t\t\t\"error authorizing user %#v to bind %#v in namespace %s: %v\",\n\t\t\tuser, roleRef, bindingNamespace, err,\n\t\t))\n\t}\n\treturn decision == authorizer.DecisionAllow\n}","line":{"from":100,"to":146}} {"id":100010298,"name":"IsOnlyMutatingGCFields","signature":"func IsOnlyMutatingGCFields(obj, old runtime.Object, equalities conversion.Equalities) bool","file":"pkg/registry/rbac/helpers.go","code":"// IsOnlyMutatingGCFields checks finalizers and ownerrefs which GC manipulates\n// and indicates that only those fields are changing\nfunc IsOnlyMutatingGCFields(obj, old runtime.Object, equalities conversion.Equalities) bool {\n\tif old == nil || reflect.ValueOf(old).IsNil() {\n\t\treturn false\n\t}\n\n\t// make a copy of the newObj so that we can stomp for comparison\n\tcopied := obj.DeepCopyObject()\n\tcopiedMeta, err := meta.Accessor(copied)\n\tif err != nil {\n\t\treturn false\n\t}\n\toldMeta, err := meta.Accessor(old)\n\tif err != nil {\n\t\treturn false\n\t}\n\tcopiedMeta.SetOwnerReferences(oldMeta.GetOwnerReferences())\n\tcopiedMeta.SetFinalizers(oldMeta.GetFinalizers())\n\tcopiedMeta.SetSelfLink(oldMeta.GetSelfLink())\n\tcopiedMeta.SetManagedFields(oldMeta.GetManagedFields())\n\n\treturn equalities.DeepEqual(copied, old)\n}","line":{"from":27,"to":50}} {"id":100010299,"name":"NewRESTStorage","signature":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error)","file":"pkg/registry/rbac/rest/storage_rbac.go","code":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error) {\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(rbac.GroupName, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs)\n\t// If you add a version here, be sure to add an entry in `k8s.io/kubernetes/cmd/kube-apiserver/app/aggregator.go with specific priorities.\n\t// TODO refactor the plumbing to provide the information in the APIGroupInfo\n\n\tif storageMap, err := p.storage(rbacapiv1.SchemeGroupVersion, apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[rbacapiv1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\treturn apiGroupInfo, nil\n}","line":{"from":67,"to":79}} {"id":100010300,"name":"storage","signature":"func (p RESTStorageProvider) storage(version schema.GroupVersion, apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/rbac/rest/storage_rbac.go","code":"func (p RESTStorageProvider) storage(version schema.GroupVersion, apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\trolesStorage, err := rolestore.NewREST(restOptionsGetter)\n\tif err != nil {\n\t\treturn storage, err\n\t}\n\troleBindingsStorage, err := rolebindingstore.NewREST(restOptionsGetter)\n\tif err != nil {\n\t\treturn storage, err\n\t}\n\tclusterRolesStorage, err := clusterrolestore.NewREST(restOptionsGetter)\n\tif err != nil {\n\t\treturn storage, err\n\t}\n\tclusterRoleBindingsStorage, err := clusterrolebindingstore.NewREST(restOptionsGetter)\n\tif err != nil {\n\t\treturn storage, err\n\t}\n\n\tauthorizationRuleResolver := rbacregistryvalidation.NewDefaultRuleResolver(\n\t\trole.AuthorizerAdapter{Registry: role.NewRegistry(rolesStorage)},\n\t\trolebinding.AuthorizerAdapter{Registry: rolebinding.NewRegistry(roleBindingsStorage)},\n\t\tclusterrole.AuthorizerAdapter{Registry: clusterrole.NewRegistry(clusterRolesStorage)},\n\t\tclusterrolebinding.AuthorizerAdapter{Registry: clusterrolebinding.NewRegistry(clusterRoleBindingsStorage)},\n\t)\n\n\t// roles\n\tif resource := \"roles\"; apiResourceConfigSource.ResourceEnabled(rbacapiv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = rolepolicybased.NewStorage(rolesStorage, p.Authorizer, authorizationRuleResolver)\n\t}\n\n\t// rolebindings\n\tif resource := \"rolebindings\"; apiResourceConfigSource.ResourceEnabled(rbacapiv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = rolebindingpolicybased.NewStorage(roleBindingsStorage, p.Authorizer, authorizationRuleResolver)\n\t}\n\n\t// clusterroles\n\tif resource := \"clusterroles\"; apiResourceConfigSource.ResourceEnabled(rbacapiv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = clusterrolepolicybased.NewStorage(clusterRolesStorage, p.Authorizer, authorizationRuleResolver)\n\t}\n\n\t// clusterrolebindings\n\tif resource := \"clusterrolebindings\"; apiResourceConfigSource.ResourceEnabled(rbacapiv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = clusterrolebindingpolicybased.NewStorage(clusterRoleBindingsStorage, p.Authorizer, authorizationRuleResolver)\n\t}\n\n\treturn storage, nil\n}","line":{"from":81,"to":129}} {"id":100010301,"name":"PostStartHook","signature":"func (p RESTStorageProvider) PostStartHook() (string, genericapiserver.PostStartHookFunc, error)","file":"pkg/registry/rbac/rest/storage_rbac.go","code":"func (p RESTStorageProvider) PostStartHook() (string, genericapiserver.PostStartHookFunc, error) {\n\tpolicy := \u0026PolicyData{\n\t\tClusterRoles: append(bootstrappolicy.ClusterRoles(), bootstrappolicy.ControllerRoles()...),\n\t\tClusterRoleBindings: append(bootstrappolicy.ClusterRoleBindings(), bootstrappolicy.ControllerRoleBindings()...),\n\t\tRoles: bootstrappolicy.NamespaceRoles(),\n\t\tRoleBindings: bootstrappolicy.NamespaceRoleBindings(),\n\t\tClusterRolesToAggregate: bootstrappolicy.ClusterRolesToAggregate(),\n\t\tClusterRoleBindingsToSplit: bootstrappolicy.ClusterRoleBindingsToSplit(),\n\t}\n\treturn PostStartHookName, policy.EnsureRBACPolicy(), nil\n}","line":{"from":131,"to":141}} {"id":100010302,"name":"isConflictOrServiceUnavailable","signature":"func isConflictOrServiceUnavailable(err error) bool","file":"pkg/registry/rbac/rest/storage_rbac.go","code":"func isConflictOrServiceUnavailable(err error) bool {\n\treturn apierrors.IsConflict(err) || apierrors.IsServiceUnavailable(err)\n}","line":{"from":154,"to":156}} {"id":100010303,"name":"retryOnConflictOrServiceUnavailable","signature":"func retryOnConflictOrServiceUnavailable(backoff wait.Backoff, fn func() error) error","file":"pkg/registry/rbac/rest/storage_rbac.go","code":"func retryOnConflictOrServiceUnavailable(backoff wait.Backoff, fn func() error) error {\n\treturn retry.OnError(backoff, isConflictOrServiceUnavailable, fn)\n}","line":{"from":158,"to":160}} {"id":100010304,"name":"EnsureRBACPolicy","signature":"func (p *PolicyData) EnsureRBACPolicy() genericapiserver.PostStartHookFunc","file":"pkg/registry/rbac/rest/storage_rbac.go","code":"func (p *PolicyData) EnsureRBACPolicy() genericapiserver.PostStartHookFunc {\n\treturn func(hookContext genericapiserver.PostStartHookContext) error {\n\t\t// initializing roles is really important. On some e2e runs, we've seen cases where etcd is down when the server\n\t\t// starts, the roles don't initialize, and nothing works.\n\t\terr := wait.Poll(1*time.Second, 30*time.Second, func() (done bool, err error) {\n\t\t\tclient, err := clientset.NewForConfig(hookContext.LoopbackClientConfig)\n\t\t\tif err != nil {\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"unable to initialize client set: %v\", err))\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn ensureRBACPolicy(p, client)\n\t\t})\n\t\t// if we're never able to make it through initialization, kill the API server\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to initialize roles: %v\", err)\n\t\t}\n\n\t\treturn nil\n\t}\n}","line":{"from":162,"to":181}} {"id":100010305,"name":"ensureRBACPolicy","signature":"func ensureRBACPolicy(p *PolicyData, client clientset.Interface) (done bool, err error)","file":"pkg/registry/rbac/rest/storage_rbac.go","code":"func ensureRBACPolicy(p *PolicyData, client clientset.Interface) (done bool, err error) {\n\tfailedReconciliation := false\n\t// Make sure etcd is responding before we start reconciling\n\tif _, err := client.RbacV1().ClusterRoles().List(context.TODO(), metav1.ListOptions{}); err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unable to initialize clusterroles: %v\", err))\n\t\treturn false, nil\n\t}\n\tif _, err := client.RbacV1().ClusterRoleBindings().List(context.TODO(), metav1.ListOptions{}); err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unable to initialize clusterrolebindings: %v\", err))\n\t\treturn false, nil\n\t}\n\n\t// if the new cluster roles to aggregate do not yet exist, then we need to copy the old roles if they don't exist\n\t// in new locations\n\tif err := primeAggregatedClusterRoles(p.ClusterRolesToAggregate, client.RbacV1()); err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unable to prime aggregated clusterroles: %v\", err))\n\t\treturn false, nil\n\t}\n\n\tif err := primeSplitClusterRoleBindings(p.ClusterRoleBindingsToSplit, client.RbacV1()); err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unable to prime split ClusterRoleBindings: %v\", err))\n\t\treturn false, nil\n\t}\n\n\t// ensure bootstrap roles are created or reconciled\n\tfor _, clusterRole := range p.ClusterRoles {\n\t\topts := reconciliation.ReconcileRoleOptions{\n\t\t\tRole: reconciliation.ClusterRoleRuleOwner{ClusterRole: \u0026clusterRole},\n\t\t\tClient: reconciliation.ClusterRoleModifier{Client: client.RbacV1().ClusterRoles()},\n\t\t\tConfirm: true,\n\t\t}\n\t\t// ServiceUnavailble error is returned when the API server is blocked by storage version updates\n\t\terr := retryOnConflictOrServiceUnavailable(retry.DefaultBackoff, func() error {\n\t\t\tresult, err := opts.Run()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tswitch {\n\t\t\tcase result.Protected \u0026\u0026 result.Operation != reconciliation.ReconcileNone:\n\t\t\t\tklog.Warningf(\"skipped reconcile-protected clusterrole.%s/%s with missing permissions: %v\", rbac.GroupName, clusterRole.Name, result.MissingRules)\n\t\t\tcase result.Operation == reconciliation.ReconcileUpdate:\n\t\t\t\tklog.V(2).Infof(\"updated clusterrole.%s/%s with additional permissions: %v\", rbac.GroupName, clusterRole.Name, result.MissingRules)\n\t\t\tcase result.Operation == reconciliation.ReconcileCreate:\n\t\t\t\tklog.V(2).Infof(\"created clusterrole.%s/%s\", rbac.GroupName, clusterRole.Name)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\t// don't fail on failures, try to create as many as you can\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"unable to reconcile clusterrole.%s/%s: %v\", rbac.GroupName, clusterRole.Name, err))\n\t\t\tfailedReconciliation = true\n\t\t}\n\t}\n\n\t// ensure bootstrap rolebindings are created or reconciled\n\tfor _, clusterRoleBinding := range p.ClusterRoleBindings {\n\t\topts := reconciliation.ReconcileRoleBindingOptions{\n\t\t\tRoleBinding: reconciliation.ClusterRoleBindingAdapter{ClusterRoleBinding: \u0026clusterRoleBinding},\n\t\t\tClient: reconciliation.ClusterRoleBindingClientAdapter{Client: client.RbacV1().ClusterRoleBindings()},\n\t\t\tConfirm: true,\n\t\t}\n\t\t// ServiceUnavailble error is returned when the API server is blocked by storage version updates\n\t\terr := retryOnConflictOrServiceUnavailable(retry.DefaultBackoff, func() error {\n\t\t\tresult, err := opts.Run()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tswitch {\n\t\t\tcase result.Protected \u0026\u0026 result.Operation != reconciliation.ReconcileNone:\n\t\t\t\tklog.Warningf(\"skipped reconcile-protected clusterrolebinding.%s/%s with missing subjects: %v\", rbac.GroupName, clusterRoleBinding.Name, result.MissingSubjects)\n\t\t\tcase result.Operation == reconciliation.ReconcileUpdate:\n\t\t\t\tklog.V(2).Infof(\"updated clusterrolebinding.%s/%s with additional subjects: %v\", rbac.GroupName, clusterRoleBinding.Name, result.MissingSubjects)\n\t\t\tcase result.Operation == reconciliation.ReconcileCreate:\n\t\t\t\tklog.V(2).Infof(\"created clusterrolebinding.%s/%s\", rbac.GroupName, clusterRoleBinding.Name)\n\t\t\tcase result.Operation == reconciliation.ReconcileRecreate:\n\t\t\t\tklog.V(2).Infof(\"recreated clusterrolebinding.%s/%s\", rbac.GroupName, clusterRoleBinding.Name)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\t// don't fail on failures, try to create as many as you can\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"unable to reconcile clusterrolebinding.%s/%s: %v\", rbac.GroupName, clusterRoleBinding.Name, err))\n\t\t\tfailedReconciliation = true\n\t\t}\n\t}\n\n\t// ensure bootstrap namespaced roles are created or reconciled\n\tfor namespace, roles := range p.Roles {\n\t\tfor _, role := range roles {\n\t\t\topts := reconciliation.ReconcileRoleOptions{\n\t\t\t\tRole: reconciliation.RoleRuleOwner{Role: \u0026role},\n\t\t\t\tClient: reconciliation.RoleModifier{Client: client.RbacV1(), NamespaceClient: client.CoreV1().Namespaces()},\n\t\t\t\tConfirm: true,\n\t\t\t}\n\t\t\t// ServiceUnavailble error is returned when the API server is blocked by storage version updates\n\t\t\terr := retryOnConflictOrServiceUnavailable(retry.DefaultBackoff, func() error {\n\t\t\t\tresult, err := opts.Run()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tswitch {\n\t\t\t\tcase result.Protected \u0026\u0026 result.Operation != reconciliation.ReconcileNone:\n\t\t\t\t\tklog.Warningf(\"skipped reconcile-protected role.%s/%s in %v with missing permissions: %v\", rbac.GroupName, role.Name, namespace, result.MissingRules)\n\t\t\t\tcase result.Operation == reconciliation.ReconcileUpdate:\n\t\t\t\t\tklog.V(2).Infof(\"updated role.%s/%s in %v with additional permissions: %v\", rbac.GroupName, role.Name, namespace, result.MissingRules)\n\t\t\t\tcase result.Operation == reconciliation.ReconcileCreate:\n\t\t\t\t\tklog.V(2).Infof(\"created role.%s/%s in %v\", rbac.GroupName, role.Name, namespace)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\t// don't fail on failures, try to create as many as you can\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"unable to reconcile role.%s/%s in %v: %v\", rbac.GroupName, role.Name, namespace, err))\n\t\t\t\tfailedReconciliation = true\n\t\t\t}\n\t\t}\n\t}\n\n\t// ensure bootstrap namespaced rolebindings are created or reconciled\n\tfor namespace, roleBindings := range p.RoleBindings {\n\t\tfor _, roleBinding := range roleBindings {\n\t\t\topts := reconciliation.ReconcileRoleBindingOptions{\n\t\t\t\tRoleBinding: reconciliation.RoleBindingAdapter{RoleBinding: \u0026roleBinding},\n\t\t\t\tClient: reconciliation.RoleBindingClientAdapter{Client: client.RbacV1(), NamespaceClient: client.CoreV1().Namespaces()},\n\t\t\t\tConfirm: true,\n\t\t\t}\n\t\t\t// ServiceUnavailble error is returned when the API server is blocked by storage version updates\n\t\t\terr := retryOnConflictOrServiceUnavailable(retry.DefaultBackoff, func() error {\n\t\t\t\tresult, err := opts.Run()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tswitch {\n\t\t\t\tcase result.Protected \u0026\u0026 result.Operation != reconciliation.ReconcileNone:\n\t\t\t\t\tklog.Warningf(\"skipped reconcile-protected rolebinding.%s/%s in %v with missing subjects: %v\", rbac.GroupName, roleBinding.Name, namespace, result.MissingSubjects)\n\t\t\t\tcase result.Operation == reconciliation.ReconcileUpdate:\n\t\t\t\t\tklog.V(2).Infof(\"updated rolebinding.%s/%s in %v with additional subjects: %v\", rbac.GroupName, roleBinding.Name, namespace, result.MissingSubjects)\n\t\t\t\tcase result.Operation == reconciliation.ReconcileCreate:\n\t\t\t\t\tklog.V(2).Infof(\"created rolebinding.%s/%s in %v\", rbac.GroupName, roleBinding.Name, namespace)\n\t\t\t\tcase result.Operation == reconciliation.ReconcileRecreate:\n\t\t\t\t\tklog.V(2).Infof(\"recreated rolebinding.%s/%s in %v\", rbac.GroupName, roleBinding.Name, namespace)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\t// don't fail on failures, try to create as many as you can\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"unable to reconcile rolebinding.%s/%s in %v: %v\", rbac.GroupName, roleBinding.Name, namespace, err))\n\t\t\t\tfailedReconciliation = true\n\t\t\t}\n\t\t}\n\t}\n\t// failed to reconcile some objects, retry\n\tif failedReconciliation {\n\t\treturn false, nil\n\t}\n\n\treturn true, nil\n}","line":{"from":183,"to":340}} {"id":100010306,"name":"GroupName","signature":"func (p RESTStorageProvider) GroupName() string","file":"pkg/registry/rbac/rest/storage_rbac.go","code":"func (p RESTStorageProvider) GroupName() string {\n\treturn rbac.GroupName\n}","line":{"from":342,"to":344}} {"id":100010307,"name":"primeAggregatedClusterRoles","signature":"func primeAggregatedClusterRoles(clusterRolesToAggregate map[string]string, clusterRoleClient rbacv1client.ClusterRolesGetter) error","file":"pkg/registry/rbac/rest/storage_rbac.go","code":"// primeAggregatedClusterRoles copies roles that have transitioned to aggregated roles and may need to pick up changes\n// that were done to the legacy roles.\nfunc primeAggregatedClusterRoles(clusterRolesToAggregate map[string]string, clusterRoleClient rbacv1client.ClusterRolesGetter) error {\n\tfor oldName, newName := range clusterRolesToAggregate {\n\t\t_, err := clusterRoleClient.ClusterRoles().Get(context.TODO(), newName, metav1.GetOptions{})\n\t\tif err == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif !apierrors.IsNotFound(err) {\n\t\t\treturn err\n\t\t}\n\n\t\texistingRole, err := clusterRoleClient.ClusterRoles().Get(context.TODO(), oldName, metav1.GetOptions{})\n\t\tif apierrors.IsNotFound(err) {\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif existingRole.AggregationRule != nil {\n\t\t\t// the old role already moved to an aggregated role, so there are no custom rules to migrate at this point\n\t\t\treturn nil\n\t\t}\n\t\tklog.V(1).Infof(\"migrating %v to %v\", existingRole.Name, newName)\n\t\texistingRole.Name = newName\n\t\texistingRole.ResourceVersion = \"\" // clear this so the object can be created.\n\t\tif _, err := clusterRoleClient.ClusterRoles().Create(context.TODO(), existingRole, metav1.CreateOptions{}); err != nil \u0026\u0026 !apierrors.IsAlreadyExists(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":346,"to":378}} {"id":100010308,"name":"primeSplitClusterRoleBindings","signature":"func primeSplitClusterRoleBindings(clusterRoleBindingToSplit map[string]rbacapiv1.ClusterRoleBinding, clusterRoleBindingClient rbacv1client.ClusterRoleBindingsGetter) error","file":"pkg/registry/rbac/rest/storage_rbac.go","code":"// primeSplitClusterRoleBindings ensures the existence of target ClusterRoleBindings\n// by copying Subjects, Annotations, and Labels from the specified source\n// ClusterRoleBinding, if present.\nfunc primeSplitClusterRoleBindings(clusterRoleBindingToSplit map[string]rbacapiv1.ClusterRoleBinding, clusterRoleBindingClient rbacv1client.ClusterRoleBindingsGetter) error {\n\tfor existingBindingName, clusterRoleBindingToCreate := range clusterRoleBindingToSplit {\n\t\t// If source ClusterRoleBinding does not exist, do nothing.\n\t\texistingRoleBinding, err := clusterRoleBindingClient.ClusterRoleBindings().Get(context.TODO(), existingBindingName, metav1.GetOptions{})\n\t\tif apierrors.IsNotFound(err) {\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// If the target ClusterRoleBinding already exists, do nothing.\n\t\t_, err = clusterRoleBindingClient.ClusterRoleBindings().Get(context.TODO(), clusterRoleBindingToCreate.Name, metav1.GetOptions{})\n\t\tif err == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif !apierrors.IsNotFound(err) {\n\t\t\treturn err\n\t\t}\n\n\t\t// If the source exists, but the target does not,\n\t\t// copy the subjects, labels, and annotations from the former to create the latter.\n\t\tklog.V(1).Infof(\"copying subjects, labels, and annotations from ClusterRoleBinding %q to template %q\", existingBindingName, clusterRoleBindingToCreate.Name)\n\t\tnewCRB := clusterRoleBindingToCreate.DeepCopy()\n\t\tnewCRB.Subjects = existingRoleBinding.Subjects\n\t\tnewCRB.Labels = existingRoleBinding.Labels\n\t\tnewCRB.Annotations = existingRoleBinding.Annotations\n\t\tif _, err := clusterRoleBindingClient.ClusterRoleBindings().Create(context.TODO(), newCRB, metav1.CreateOptions{}); err != nil \u0026\u0026 !apierrors.IsAlreadyExists(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":380,"to":415}} {"id":100010309,"name":"NewStorage","signature":"func NewStorage(s rest.StandardStorage, authorizer authorizer.Authorizer, ruleResolver rbacregistryvalidation.AuthorizationRuleResolver) *Storage","file":"pkg/registry/rbac/role/policybased/storage.go","code":"func NewStorage(s rest.StandardStorage, authorizer authorizer.Authorizer, ruleResolver rbacregistryvalidation.AuthorizationRuleResolver) *Storage {\n\treturn \u0026Storage{s, authorizer, ruleResolver}\n}","line":{"from":44,"to":46}} {"id":100010310,"name":"Destroy","signature":"func (r *Storage) Destroy()","file":"pkg/registry/rbac/role/policybased/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *Storage) Destroy() {\n\tr.StandardStorage.Destroy()\n}","line":{"from":48,"to":51}} {"id":100010311,"name":"NamespaceScoped","signature":"func (r *Storage) NamespaceScoped() bool","file":"pkg/registry/rbac/role/policybased/storage.go","code":"func (r *Storage) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":53,"to":55}} {"id":100010312,"name":"StorageVersion","signature":"func (r *Storage) StorageVersion() runtime.GroupVersioner","file":"pkg/registry/rbac/role/policybased/storage.go","code":"func (r *Storage) StorageVersion() runtime.GroupVersioner {\n\tsvp, ok := r.StandardStorage.(rest.StorageVersionProvider)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn svp.StorageVersion()\n}","line":{"from":57,"to":63}} {"id":100010313,"name":"Create","signature":"func (s *Storage) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error)","file":"pkg/registry/rbac/role/policybased/storage.go","code":"func (s *Storage) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {\n\tif rbacregistry.EscalationAllowed(ctx) || rbacregistry.RoleEscalationAuthorized(ctx, s.authorizer) {\n\t\treturn s.StandardStorage.Create(ctx, obj, createValidation, options)\n\t}\n\n\trole := obj.(*rbac.Role)\n\trules := role.Rules\n\tif err := rbacregistryvalidation.ConfirmNoEscalationInternal(ctx, s.ruleResolver, rules); err != nil {\n\t\treturn nil, errors.NewForbidden(groupResource, role.Name, err)\n\t}\n\treturn s.StandardStorage.Create(ctx, obj, createValidation, options)\n}","line":{"from":67,"to":78}} {"id":100010314,"name":"Update","signature":"func (s *Storage) Update(ctx context.Context, name string, obj rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/rbac/role/policybased/storage.go","code":"func (s *Storage) Update(ctx context.Context, name string, obj rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\tif rbacregistry.EscalationAllowed(ctx) || rbacregistry.RoleEscalationAuthorized(ctx, s.authorizer) {\n\t\treturn s.StandardStorage.Update(ctx, name, obj, createValidation, updateValidation, forceAllowCreate, options)\n\t}\n\n\tnonEscalatingInfo := rest.WrapUpdatedObjectInfo(obj, func(ctx context.Context, obj runtime.Object, oldObj runtime.Object) (runtime.Object, error) {\n\t\trole := obj.(*rbac.Role)\n\n\t\t// if we're only mutating fields needed for the GC to eventually delete this obj, return\n\t\tif rbacregistry.IsOnlyMutatingGCFields(obj, oldObj, kapihelper.Semantic) {\n\t\t\treturn obj, nil\n\t\t}\n\n\t\trules := role.Rules\n\t\tif err := rbacregistryvalidation.ConfirmNoEscalationInternal(ctx, s.ruleResolver, rules); err != nil {\n\t\t\treturn nil, errors.NewForbidden(groupResource, role.Name, err)\n\t\t}\n\t\treturn obj, nil\n\t})\n\n\treturn s.StandardStorage.Update(ctx, name, nonEscalatingInfo, createValidation, updateValidation, forceAllowCreate, options)\n}","line":{"from":80,"to":101}} {"id":100010315,"name":"GetSingularName","signature":"func (s *Storage) GetSingularName() string","file":"pkg/registry/rbac/role/policybased/storage.go","code":"func (s *Storage) GetSingularName() string {\n\tsnp, ok := s.StandardStorage.(rest.SingularNameProvider)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn snp.GetSingularName()\n}","line":{"from":105,"to":111}} {"id":100010316,"name":"NewRegistry","signature":"func NewRegistry(s rest.StandardStorage) Registry","file":"pkg/registry/rbac/role/registry.go","code":"// NewRegistry returns a new Registry interface for the given Storage. Any mismatched\n// types will panic.\nfunc NewRegistry(s rest.StandardStorage) Registry {\n\treturn \u0026storage{s}\n}","line":{"from":40,"to":44}} {"id":100010317,"name":"GetRole","signature":"func (s *storage) GetRole(ctx context.Context, name string, options *metav1.GetOptions) (*rbacv1.Role, error)","file":"pkg/registry/rbac/role/registry.go","code":"func (s *storage) GetRole(ctx context.Context, name string, options *metav1.GetOptions) (*rbacv1.Role, error) {\n\tobj, err := s.Get(ctx, name, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret := \u0026rbacv1.Role{}\n\tif err := rbacv1helpers.Convert_rbac_Role_To_v1_Role(obj.(*rbac.Role), ret, nil); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ret, nil\n}","line":{"from":46,"to":57}} {"id":100010318,"name":"GetRole","signature":"func (a AuthorizerAdapter) GetRole(namespace, name string) (*rbacv1.Role, error)","file":"pkg/registry/rbac/role/registry.go","code":"// GetRole returns the corresponding Role by name in specified namespace\nfunc (a AuthorizerAdapter) GetRole(namespace, name string) (*rbacv1.Role, error) {\n\treturn a.Registry.GetRole(genericapirequest.WithNamespace(genericapirequest.NewContext(), namespace), name, \u0026metav1.GetOptions{})\n}","line":{"from":64,"to":67}} {"id":100010319,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error)","file":"pkg/registry/rbac/role/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against Role objects.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026rbac.Role{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026rbac.RoleList{} },\n\t\tDefaultQualifiedResource: rbac.Resource(\"roles\"),\n\t\tSingularQualifiedResource: rbac.Resource(\"role\"),\n\n\t\tCreateStrategy: role.Strategy,\n\t\tUpdateStrategy: role.Strategy,\n\t\tDeleteStrategy: role.Strategy,\n\n\t\t// TODO: define table converter that exposes more than name/creation timestamp?\n\t\tTableConvertor: rest.NewDefaultTableConvertor(rbac.Resource(\"roles\")),\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026REST{store}, nil\n}","line":{"from":33,"to":54}} {"id":100010320,"name":"NamespaceScoped","signature":"func (strategy) NamespaceScoped() bool","file":"pkg/registry/rbac/role/strategy.go","code":"// NamespaceScoped is true for Roles.\nfunc (strategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":47,"to":50}} {"id":100010321,"name":"AllowCreateOnUpdate","signature":"func (strategy) AllowCreateOnUpdate() bool","file":"pkg/registry/rbac/role/strategy.go","code":"// AllowCreateOnUpdate is true for Roles.\nfunc (strategy) AllowCreateOnUpdate() bool {\n\treturn true\n}","line":{"from":52,"to":55}} {"id":100010322,"name":"PrepareForCreate","signature":"func (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/rbac/role/strategy.go","code":"// PrepareForCreate clears fields that are not allowed to be set by end users\n// on creation.\nfunc (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\t_ = obj.(*rbac.Role)\n}","line":{"from":57,"to":61}} {"id":100010323,"name":"PrepareForUpdate","signature":"func (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/rbac/role/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewRole := obj.(*rbac.Role)\n\toldRole := old.(*rbac.Role)\n\n\t_, _ = newRole, oldRole\n}","line":{"from":63,"to":69}} {"id":100010324,"name":"Validate","signature":"func (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/rbac/role/strategy.go","code":"// Validate validates a new Role. Validation must check for a correct signature.\nfunc (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\trole := obj.(*rbac.Role)\n\treturn validation.ValidateRole(role)\n}","line":{"from":71,"to":75}} {"id":100010325,"name":"WarningsOnCreate","signature":"func (strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return nil }","file":"pkg/registry/rbac/role/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return nil }","line":{"from":77,"to":78}} {"id":100010326,"name":"Canonicalize","signature":"func (strategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/rbac/role/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (strategy) Canonicalize(obj runtime.Object) {\n\t_ = obj.(*rbac.Role)\n}","line":{"from":80,"to":83}} {"id":100010327,"name":"ValidateUpdate","signature":"func (strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/rbac/role/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewObj := obj.(*rbac.Role)\n\terrorList := validation.ValidateRole(newObj)\n\treturn append(errorList, validation.ValidateRoleUpdate(newObj, old.(*rbac.Role))...)\n}","line":{"from":85,"to":90}} {"id":100010328,"name":"WarningsOnUpdate","signature":"func (strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/rbac/role/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":92,"to":95}} {"id":100010329,"name":"AllowUnconditionalUpdate","signature":"func (strategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/rbac/role/strategy.go","code":"// If AllowUnconditionalUpdate() is true and the object specified by\n// the user does not have a resource version, then generic Update()\n// populates it with the latest version. Else, it checks that the\n// version specified by the user matches the version of latest etcd\n// object.\nfunc (strategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":97,"to":104}} {"id":100010330,"name":"NewStorage","signature":"func NewStorage(s rest.StandardStorage, authorizer authorizer.Authorizer, ruleResolver rbacregistryvalidation.AuthorizationRuleResolver) *Storage","file":"pkg/registry/rbac/rolebinding/policybased/storage.go","code":"func NewStorage(s rest.StandardStorage, authorizer authorizer.Authorizer, ruleResolver rbacregistryvalidation.AuthorizationRuleResolver) *Storage {\n\treturn \u0026Storage{s, authorizer, ruleResolver}\n}","line":{"from":47,"to":49}} {"id":100010331,"name":"Destroy","signature":"func (r *Storage) Destroy()","file":"pkg/registry/rbac/rolebinding/policybased/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *Storage) Destroy() {\n\tr.StandardStorage.Destroy()\n}","line":{"from":51,"to":54}} {"id":100010332,"name":"NamespaceScoped","signature":"func (r *Storage) NamespaceScoped() bool","file":"pkg/registry/rbac/rolebinding/policybased/storage.go","code":"func (r *Storage) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":56,"to":58}} {"id":100010333,"name":"StorageVersion","signature":"func (r *Storage) StorageVersion() runtime.GroupVersioner","file":"pkg/registry/rbac/rolebinding/policybased/storage.go","code":"func (r *Storage) StorageVersion() runtime.GroupVersioner {\n\tsvp, ok := r.StandardStorage.(rest.StorageVersionProvider)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn svp.StorageVersion()\n}","line":{"from":60,"to":66}} {"id":100010334,"name":"Create","signature":"func (s *Storage) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error)","file":"pkg/registry/rbac/rolebinding/policybased/storage.go","code":"func (s *Storage) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {\n\tif rbacregistry.EscalationAllowed(ctx) {\n\t\treturn s.StandardStorage.Create(ctx, obj, createValidation, options)\n\t}\n\n\t// Get the namespace from the context (populated from the URL).\n\t// The namespace in the object can be empty until StandardStorage.Create()-\u003eBeforeCreate() populates it from the context.\n\tnamespace, ok := genericapirequest.NamespaceFrom(ctx)\n\tif !ok {\n\t\treturn nil, errors.NewBadRequest(\"namespace is required\")\n\t}\n\n\troleBinding := obj.(*rbac.RoleBinding)\n\tif rbacregistry.BindingAuthorized(ctx, roleBinding.RoleRef, namespace, s.authorizer) {\n\t\treturn s.StandardStorage.Create(ctx, obj, createValidation, options)\n\t}\n\n\tv1RoleRef := rbacv1.RoleRef{}\n\terr := rbacv1helpers.Convert_rbac_RoleRef_To_v1_RoleRef(\u0026roleBinding.RoleRef, \u0026v1RoleRef, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trules, err := s.ruleResolver.GetRoleReferenceRules(v1RoleRef, namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := rbacregistryvalidation.ConfirmNoEscalation(ctx, s.ruleResolver, rules); err != nil {\n\t\treturn nil, errors.NewForbidden(groupResource, roleBinding.Name, err)\n\t}\n\treturn s.StandardStorage.Create(ctx, obj, createValidation, options)\n}","line":{"from":70,"to":100}} {"id":100010335,"name":"Update","signature":"func (s *Storage) Update(ctx context.Context, name string, obj rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/rbac/rolebinding/policybased/storage.go","code":"func (s *Storage) Update(ctx context.Context, name string, obj rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\tif rbacregistry.EscalationAllowed(ctx) {\n\t\treturn s.StandardStorage.Update(ctx, name, obj, createValidation, updateValidation, forceAllowCreate, options)\n\t}\n\n\tnonEscalatingInfo := rest.WrapUpdatedObjectInfo(obj, func(ctx context.Context, obj runtime.Object, oldObj runtime.Object) (runtime.Object, error) {\n\t\t// Get the namespace from the context (populated from the URL).\n\t\t// The namespace in the object can be empty until StandardStorage.Update()-\u003eBeforeUpdate() populates it from the context.\n\t\tnamespace, ok := genericapirequest.NamespaceFrom(ctx)\n\t\tif !ok {\n\t\t\treturn nil, errors.NewBadRequest(\"namespace is required\")\n\t\t}\n\n\t\troleBinding := obj.(*rbac.RoleBinding)\n\n\t\t// if we're only mutating fields needed for the GC to eventually delete this obj, return\n\t\tif rbacregistry.IsOnlyMutatingGCFields(obj, oldObj, kapihelper.Semantic) {\n\t\t\treturn obj, nil\n\t\t}\n\n\t\t// if we're explicitly authorized to bind this role, return\n\t\tif rbacregistry.BindingAuthorized(ctx, roleBinding.RoleRef, namespace, s.authorizer) {\n\t\t\treturn obj, nil\n\t\t}\n\n\t\t// Otherwise, see if we already have all the permissions contained in the referenced role\n\t\tv1RoleRef := rbacv1.RoleRef{}\n\t\terr := rbacv1helpers.Convert_rbac_RoleRef_To_v1_RoleRef(\u0026roleBinding.RoleRef, \u0026v1RoleRef, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trules, err := s.ruleResolver.GetRoleReferenceRules(v1RoleRef, namespace)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := rbacregistryvalidation.ConfirmNoEscalation(ctx, s.ruleResolver, rules); err != nil {\n\t\t\treturn nil, errors.NewForbidden(groupResource, roleBinding.Name, err)\n\t\t}\n\t\treturn obj, nil\n\t})\n\n\treturn s.StandardStorage.Update(ctx, name, nonEscalatingInfo, createValidation, updateValidation, forceAllowCreate, options)\n}","line":{"from":102,"to":144}} {"id":100010336,"name":"GetSingularName","signature":"func (s *Storage) GetSingularName() string","file":"pkg/registry/rbac/rolebinding/policybased/storage.go","code":"func (s *Storage) GetSingularName() string {\n\tsnp, ok := s.StandardStorage.(rest.SingularNameProvider)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn snp.GetSingularName()\n}","line":{"from":148,"to":154}} {"id":100010337,"name":"NewRegistry","signature":"func NewRegistry(s rest.StandardStorage) Registry","file":"pkg/registry/rbac/rolebinding/registry.go","code":"// NewRegistry returns a new Registry interface for the given Storage. Any mismatched\n// types will panic.\nfunc NewRegistry(s rest.StandardStorage) Registry {\n\treturn \u0026storage{s}\n}","line":{"from":40,"to":44}} {"id":100010338,"name":"ListRoleBindings","signature":"func (s *storage) ListRoleBindings(ctx context.Context, options *metainternalversion.ListOptions) (*rbacv1.RoleBindingList, error)","file":"pkg/registry/rbac/rolebinding/registry.go","code":"func (s *storage) ListRoleBindings(ctx context.Context, options *metainternalversion.ListOptions) (*rbacv1.RoleBindingList, error) {\n\tobj, err := s.List(ctx, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret := \u0026rbacv1.RoleBindingList{}\n\tif err := rbacv1helpers.Convert_rbac_RoleBindingList_To_v1_RoleBindingList(obj.(*rbac.RoleBindingList), ret, nil); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ret, nil\n}","line":{"from":46,"to":57}} {"id":100010339,"name":"ListRoleBindings","signature":"func (a AuthorizerAdapter) ListRoleBindings(namespace string) ([]*rbacv1.RoleBinding, error)","file":"pkg/registry/rbac/rolebinding/registry.go","code":"func (a AuthorizerAdapter) ListRoleBindings(namespace string) ([]*rbacv1.RoleBinding, error) {\n\tlist, err := a.Registry.ListRoleBindings(genericapirequest.WithNamespace(genericapirequest.NewContext(), namespace), \u0026metainternalversion.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret := []*rbacv1.RoleBinding{}\n\tfor i := range list.Items {\n\t\tret = append(ret, \u0026list.Items[i])\n\t}\n\treturn ret, nil\n}","line":{"from":64,"to":75}} {"id":100010340,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error)","file":"pkg/registry/rbac/rolebinding/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against RoleBinding objects.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026rbac.RoleBinding{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026rbac.RoleBindingList{} },\n\t\tDefaultQualifiedResource: rbac.Resource(\"rolebindings\"),\n\t\tSingularQualifiedResource: rbac.Resource(\"rolebinding\"),\n\n\t\tCreateStrategy: rolebinding.Strategy,\n\t\tUpdateStrategy: rolebinding.Strategy,\n\t\tDeleteStrategy: rolebinding.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026REST{store}, nil\n}","line":{"from":35,"to":55}} {"id":100010341,"name":"NamespaceScoped","signature":"func (strategy) NamespaceScoped() bool","file":"pkg/registry/rbac/rolebinding/strategy.go","code":"// NamespaceScoped is true for RoleBindings.\nfunc (strategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":47,"to":50}} {"id":100010342,"name":"AllowCreateOnUpdate","signature":"func (strategy) AllowCreateOnUpdate() bool","file":"pkg/registry/rbac/rolebinding/strategy.go","code":"// AllowCreateOnUpdate is true for RoleBindings.\nfunc (strategy) AllowCreateOnUpdate() bool {\n\treturn true\n}","line":{"from":52,"to":55}} {"id":100010343,"name":"PrepareForCreate","signature":"func (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/rbac/rolebinding/strategy.go","code":"// PrepareForCreate clears fields that are not allowed to be set by end users\n// on creation.\nfunc (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\t_ = obj.(*rbac.RoleBinding)\n}","line":{"from":57,"to":61}} {"id":100010344,"name":"PrepareForUpdate","signature":"func (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/rbac/rolebinding/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewRoleBinding := obj.(*rbac.RoleBinding)\n\toldRoleBinding := old.(*rbac.RoleBinding)\n\n\t_, _ = newRoleBinding, oldRoleBinding\n}","line":{"from":63,"to":69}} {"id":100010345,"name":"Validate","signature":"func (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/rbac/rolebinding/strategy.go","code":"// Validate validates a new RoleBinding. Validation must check for a correct signature.\nfunc (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\troleBinding := obj.(*rbac.RoleBinding)\n\treturn validation.ValidateRoleBinding(roleBinding)\n}","line":{"from":71,"to":75}} {"id":100010346,"name":"WarningsOnCreate","signature":"func (strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return nil }","file":"pkg/registry/rbac/rolebinding/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return nil }","line":{"from":77,"to":78}} {"id":100010347,"name":"Canonicalize","signature":"func (strategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/rbac/rolebinding/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (strategy) Canonicalize(obj runtime.Object) {\n\t_ = obj.(*rbac.RoleBinding)\n}","line":{"from":80,"to":83}} {"id":100010348,"name":"ValidateUpdate","signature":"func (strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/rbac/rolebinding/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewObj := obj.(*rbac.RoleBinding)\n\terrorList := validation.ValidateRoleBinding(newObj)\n\treturn append(errorList, validation.ValidateRoleBindingUpdate(newObj, old.(*rbac.RoleBinding))...)\n}","line":{"from":85,"to":90}} {"id":100010349,"name":"WarningsOnUpdate","signature":"func (strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/rbac/rolebinding/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":92,"to":95}} {"id":100010350,"name":"AllowUnconditionalUpdate","signature":"func (strategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/rbac/rolebinding/strategy.go","code":"// If AllowUnconditionalUpdate() is true and the object specified by\n// the user does not have a resource version, then generic Update()\n// populates it with the latest version. Else, it checks that the\n// version specified by the user matches the version of latest etcd\n// object.\nfunc (strategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":97,"to":104}} {"id":100010351,"name":"ConfirmNoEscalationInternal","signature":"func ConfirmNoEscalationInternal(ctx context.Context, ruleResolver AuthorizationRuleResolver, inRules []rbac.PolicyRule) error","file":"pkg/registry/rbac/validation/internal_version_adapter.go","code":"func ConfirmNoEscalationInternal(ctx context.Context, ruleResolver AuthorizationRuleResolver, inRules []rbac.PolicyRule) error {\n\trules := []rbacv1.PolicyRule{}\n\tfor i := range inRules {\n\t\tv1Rule := rbacv1.PolicyRule{}\n\t\terr := rbacv1helpers.Convert_rbac_PolicyRule_To_v1_PolicyRule(\u0026inRules[i], \u0026v1Rule, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\trules = append(rules, v1Rule)\n\t}\n\n\treturn ConfirmNoEscalation(ctx, ruleResolver, rules)\n}","line":{"from":27,"to":39}} {"id":100010352,"name":"CompactRules","signature":"func CompactRules(rules []rbacv1.PolicyRule) ([]rbacv1.PolicyRule, error)","file":"pkg/registry/rbac/validation/policy_compact.go","code":"// CompactRules combines rules that contain a single APIGroup/Resource, differ only by verb, and contain no other attributes.\n// this is a fast check, and works well with the decomposed \"missing rules\" list from a Covers check.\nfunc CompactRules(rules []rbacv1.PolicyRule) ([]rbacv1.PolicyRule, error) {\n\tcompacted := make([]rbacv1.PolicyRule, 0, len(rules))\n\n\tsimpleRules := map[simpleResource]*rbacv1.PolicyRule{}\n\tfor _, rule := range rules {\n\t\tif resource, isSimple := isSimpleResourceRule(\u0026rule); isSimple {\n\t\t\tif existingRule, ok := simpleRules[resource]; ok {\n\t\t\t\t// Add the new verbs to the existing simple resource rule\n\t\t\t\tif existingRule.Verbs == nil {\n\t\t\t\t\texistingRule.Verbs = []string{}\n\t\t\t\t}\n\t\t\t\texistingRule.Verbs = append(existingRule.Verbs, rule.Verbs...)\n\t\t\t} else {\n\t\t\t\t// Copy the rule to accumulate matching simple resource rules into\n\t\t\t\tsimpleRules[resource] = rule.DeepCopy()\n\t\t\t}\n\t\t} else {\n\t\t\tcompacted = append(compacted, rule)\n\t\t}\n\t}\n\n\t// Once we've consolidated the simple resource rules, add them to the compacted list\n\tfor _, simpleRule := range simpleRules {\n\t\tcompacted = append(compacted, *simpleRule)\n\t}\n\n\treturn compacted, nil\n}","line":{"from":32,"to":61}} {"id":100010353,"name":"isSimpleResourceRule","signature":"func isSimpleResourceRule(rule *rbacv1.PolicyRule) (simpleResource, bool)","file":"pkg/registry/rbac/validation/policy_compact.go","code":"// isSimpleResourceRule returns true if the given rule contains verbs, a single resource, a single API group, at most one Resource Name, and no other values\nfunc isSimpleResourceRule(rule *rbacv1.PolicyRule) (simpleResource, bool) {\n\tresource := simpleResource{}\n\n\t// If we have \"complex\" rule attributes, return early without allocations or expensive comparisons\n\tif len(rule.ResourceNames) \u003e 1 || len(rule.NonResourceURLs) \u003e 0 {\n\t\treturn resource, false\n\t}\n\t// If we have multiple api groups or resources, return early\n\tif len(rule.APIGroups) != 1 || len(rule.Resources) != 1 {\n\t\treturn resource, false\n\t}\n\n\t// Test if this rule only contains APIGroups/Resources/Verbs/ResourceNames\n\tsimpleRule := \u0026rbacv1.PolicyRule{APIGroups: rule.APIGroups, Resources: rule.Resources, Verbs: rule.Verbs, ResourceNames: rule.ResourceNames}\n\tif !reflect.DeepEqual(simpleRule, rule) {\n\t\treturn resource, false\n\t}\n\n\tif len(rule.ResourceNames) == 0 {\n\t\tresource = simpleResource{Group: rule.APIGroups[0], Resource: rule.Resources[0], ResourceNameExist: false}\n\t} else {\n\t\tresource = simpleResource{Group: rule.APIGroups[0], Resource: rule.Resources[0], ResourceNameExist: true, ResourceName: rule.ResourceNames[0]}\n\t}\n\n\treturn resource, true\n}","line":{"from":63,"to":89}} {"id":100010354,"name":"ConfirmNoEscalation","signature":"func ConfirmNoEscalation(ctx context.Context, ruleResolver AuthorizationRuleResolver, rules []rbacv1.PolicyRule) error","file":"pkg/registry/rbac/validation/rule.go","code":"// ConfirmNoEscalation determines if the roles for a given user in a given namespace encompass the provided role.\nfunc ConfirmNoEscalation(ctx context.Context, ruleResolver AuthorizationRuleResolver, rules []rbacv1.PolicyRule) error {\n\truleResolutionErrors := []error{}\n\n\tuser, ok := genericapirequest.UserFrom(ctx)\n\tif !ok {\n\t\treturn fmt.Errorf(\"no user on context\")\n\t}\n\tnamespace, _ := genericapirequest.NamespaceFrom(ctx)\n\n\townerRules, err := ruleResolver.RulesFor(user, namespace)\n\tif err != nil {\n\t\t// As per AuthorizationRuleResolver contract, this may return a non fatal error with an incomplete list of policies. Log the error and continue.\n\t\tklog.V(1).Infof(\"non-fatal error getting local rules for %v: %v\", user, err)\n\t\truleResolutionErrors = append(ruleResolutionErrors, err)\n\t}\n\n\townerRightsCover, missingRights := validation.Covers(ownerRules, rules)\n\tif !ownerRightsCover {\n\t\tcompactMissingRights := missingRights\n\t\tif compact, err := CompactRules(missingRights); err == nil {\n\t\t\tcompactMissingRights = compact\n\t\t}\n\n\t\tmissingDescriptions := sets.NewString()\n\t\tfor _, missing := range compactMissingRights {\n\t\t\tmissingDescriptions.Insert(rbacv1helpers.CompactString(missing))\n\t\t}\n\n\t\tmsg := fmt.Sprintf(\"user %q (groups=%q) is attempting to grant RBAC permissions not currently held:\\n%s\", user.GetName(), user.GetGroups(), strings.Join(missingDescriptions.List(), \"\\n\"))\n\t\tif len(ruleResolutionErrors) \u003e 0 {\n\t\t\tmsg = msg + fmt.Sprintf(\"; resolution errors: %v\", ruleResolutionErrors)\n\t\t}\n\n\t\treturn errors.New(msg)\n\t}\n\treturn nil\n}","line":{"from":52,"to":89}} {"id":100010355,"name":"NewDefaultRuleResolver","signature":"func NewDefaultRuleResolver(roleGetter RoleGetter, roleBindingLister RoleBindingLister, clusterRoleGetter ClusterRoleGetter, clusterRoleBindingLister ClusterRoleBindingLister) *DefaultRuleResolver","file":"pkg/registry/rbac/validation/rule.go","code":"func NewDefaultRuleResolver(roleGetter RoleGetter, roleBindingLister RoleBindingLister, clusterRoleGetter ClusterRoleGetter, clusterRoleBindingLister ClusterRoleBindingLister) *DefaultRuleResolver {\n\treturn \u0026DefaultRuleResolver{roleGetter, roleBindingLister, clusterRoleGetter, clusterRoleBindingLister}\n}","line":{"from":98,"to":100}} {"id":100010356,"name":"RulesFor","signature":"func (r *DefaultRuleResolver) RulesFor(user user.Info, namespace string) ([]rbacv1.PolicyRule, error)","file":"pkg/registry/rbac/validation/rule.go","code":"func (r *DefaultRuleResolver) RulesFor(user user.Info, namespace string) ([]rbacv1.PolicyRule, error) {\n\tvisitor := \u0026ruleAccumulator{}\n\tr.VisitRulesFor(user, namespace, visitor.visit)\n\treturn visitor.rules, utilerrors.NewAggregate(visitor.errors)\n}","line":{"from":118,"to":122}} {"id":100010357,"name":"visit","signature":"func (r *ruleAccumulator) visit(source fmt.Stringer, rule *rbacv1.PolicyRule, err error) bool","file":"pkg/registry/rbac/validation/rule.go","code":"func (r *ruleAccumulator) visit(source fmt.Stringer, rule *rbacv1.PolicyRule, err error) bool {\n\tif rule != nil {\n\t\tr.rules = append(r.rules, *rule)\n\t}\n\tif err != nil {\n\t\tr.errors = append(r.errors, err)\n\t}\n\treturn true\n}","line":{"from":129,"to":137}} {"id":100010358,"name":"describeSubject","signature":"func describeSubject(s *rbacv1.Subject, bindingNamespace string) string","file":"pkg/registry/rbac/validation/rule.go","code":"func describeSubject(s *rbacv1.Subject, bindingNamespace string) string {\n\tswitch s.Kind {\n\tcase rbacv1.ServiceAccountKind:\n\t\tif len(s.Namespace) \u003e 0 {\n\t\t\treturn fmt.Sprintf(\"%s %q\", s.Kind, s.Name+\"/\"+s.Namespace)\n\t\t}\n\t\treturn fmt.Sprintf(\"%s %q\", s.Kind, s.Name+\"/\"+bindingNamespace)\n\tdefault:\n\t\treturn fmt.Sprintf(\"%s %q\", s.Kind, s.Name)\n\t}\n}","line":{"from":139,"to":149}} {"id":100010359,"name":"String","signature":"func (d *clusterRoleBindingDescriber) String() string","file":"pkg/registry/rbac/validation/rule.go","code":"func (d *clusterRoleBindingDescriber) String() string {\n\treturn fmt.Sprintf(\"ClusterRoleBinding %q of %s %q to %s\",\n\t\td.binding.Name,\n\t\td.binding.RoleRef.Kind,\n\t\td.binding.RoleRef.Name,\n\t\tdescribeSubject(d.subject, \"\"),\n\t)\n}","line":{"from":156,"to":163}} {"id":100010360,"name":"String","signature":"func (d *roleBindingDescriber) String() string","file":"pkg/registry/rbac/validation/rule.go","code":"func (d *roleBindingDescriber) String() string {\n\treturn fmt.Sprintf(\"RoleBinding %q of %s %q to %s\",\n\t\td.binding.Name+\"/\"+d.binding.Namespace,\n\t\td.binding.RoleRef.Kind,\n\t\td.binding.RoleRef.Name,\n\t\tdescribeSubject(d.subject, d.binding.Namespace),\n\t)\n}","line":{"from":170,"to":177}} {"id":100010361,"name":"VisitRulesFor","signature":"func (r *DefaultRuleResolver) VisitRulesFor(user user.Info, namespace string, visitor func(source fmt.Stringer, rule *rbacv1.PolicyRule, err error) bool)","file":"pkg/registry/rbac/validation/rule.go","code":"func (r *DefaultRuleResolver) VisitRulesFor(user user.Info, namespace string, visitor func(source fmt.Stringer, rule *rbacv1.PolicyRule, err error) bool) {\n\tif clusterRoleBindings, err := r.clusterRoleBindingLister.ListClusterRoleBindings(); err != nil {\n\t\tif !visitor(nil, nil, err) {\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tsourceDescriber := \u0026clusterRoleBindingDescriber{}\n\t\tfor _, clusterRoleBinding := range clusterRoleBindings {\n\t\t\tsubjectIndex, applies := appliesTo(user, clusterRoleBinding.Subjects, \"\")\n\t\t\tif !applies {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\trules, err := r.GetRoleReferenceRules(clusterRoleBinding.RoleRef, \"\")\n\t\t\tif err != nil {\n\t\t\t\tif !visitor(nil, nil, err) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsourceDescriber.binding = clusterRoleBinding\n\t\t\tsourceDescriber.subject = \u0026clusterRoleBinding.Subjects[subjectIndex]\n\t\t\tfor i := range rules {\n\t\t\t\tif !visitor(sourceDescriber, \u0026rules[i], nil) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(namespace) \u003e 0 {\n\t\tif roleBindings, err := r.roleBindingLister.ListRoleBindings(namespace); err != nil {\n\t\t\tif !visitor(nil, nil, err) {\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tsourceDescriber := \u0026roleBindingDescriber{}\n\t\t\tfor _, roleBinding := range roleBindings {\n\t\t\t\tsubjectIndex, applies := appliesTo(user, roleBinding.Subjects, namespace)\n\t\t\t\tif !applies {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\trules, err := r.GetRoleReferenceRules(roleBinding.RoleRef, namespace)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif !visitor(nil, nil, err) {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tsourceDescriber.binding = roleBinding\n\t\t\t\tsourceDescriber.subject = \u0026roleBinding.Subjects[subjectIndex]\n\t\t\t\tfor i := range rules {\n\t\t\t\t\tif !visitor(sourceDescriber, \u0026rules[i], nil) {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":179,"to":237}} {"id":100010362,"name":"GetRoleReferenceRules","signature":"func (r *DefaultRuleResolver) GetRoleReferenceRules(roleRef rbacv1.RoleRef, bindingNamespace string) ([]rbacv1.PolicyRule, error)","file":"pkg/registry/rbac/validation/rule.go","code":"// GetRoleReferenceRules attempts to resolve the RoleBinding or ClusterRoleBinding.\nfunc (r *DefaultRuleResolver) GetRoleReferenceRules(roleRef rbacv1.RoleRef, bindingNamespace string) ([]rbacv1.PolicyRule, error) {\n\tswitch roleRef.Kind {\n\tcase \"Role\":\n\t\trole, err := r.roleGetter.GetRole(bindingNamespace, roleRef.Name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn role.Rules, nil\n\n\tcase \"ClusterRole\":\n\t\tclusterRole, err := r.clusterRoleGetter.GetClusterRole(roleRef.Name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn clusterRole.Rules, nil\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported role reference kind: %q\", roleRef.Kind)\n\t}\n}","line":{"from":239,"to":259}} {"id":100010363,"name":"appliesTo","signature":"func appliesTo(user user.Info, bindingSubjects []rbacv1.Subject, namespace string) (int, bool)","file":"pkg/registry/rbac/validation/rule.go","code":"// appliesTo returns whether any of the bindingSubjects applies to the specified subject,\n// and if true, the index of the first subject that applies\nfunc appliesTo(user user.Info, bindingSubjects []rbacv1.Subject, namespace string) (int, bool) {\n\tfor i, bindingSubject := range bindingSubjects {\n\t\tif appliesToUser(user, bindingSubject, namespace) {\n\t\t\treturn i, true\n\t\t}\n\t}\n\treturn 0, false\n}","line":{"from":261,"to":270}} {"id":100010364,"name":"has","signature":"func has(set []string, ele string) bool","file":"pkg/registry/rbac/validation/rule.go","code":"func has(set []string, ele string) bool {\n\tfor _, s := range set {\n\t\tif s == ele {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":272,"to":279}} {"id":100010365,"name":"appliesToUser","signature":"func appliesToUser(user user.Info, subject rbacv1.Subject, namespace string) bool","file":"pkg/registry/rbac/validation/rule.go","code":"func appliesToUser(user user.Info, subject rbacv1.Subject, namespace string) bool {\n\tswitch subject.Kind {\n\tcase rbacv1.UserKind:\n\t\treturn user.GetName() == subject.Name\n\n\tcase rbacv1.GroupKind:\n\t\treturn has(user.GetGroups(), subject.Name)\n\n\tcase rbacv1.ServiceAccountKind:\n\t\t// default the namespace to namespace we're working in if its available. This allows rolebindings that reference\n\t\t// SAs in th local namespace to avoid having to qualify them.\n\t\tsaNamespace := namespace\n\t\tif len(subject.Namespace) \u003e 0 {\n\t\t\tsaNamespace = subject.Namespace\n\t\t}\n\t\tif len(saNamespace) == 0 {\n\t\t\treturn false\n\t\t}\n\t\t// use a more efficient comparison for RBAC checking\n\t\treturn serviceaccount.MatchesUsername(saNamespace, subject.Name, user.GetName())\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":281,"to":304}} {"id":100010366,"name":"NewTestRuleResolver","signature":"func NewTestRuleResolver(roles []*rbacv1.Role, roleBindings []*rbacv1.RoleBinding, clusterRoles []*rbacv1.ClusterRole, clusterRoleBindings []*rbacv1.ClusterRoleBinding) (AuthorizationRuleResolver, *StaticRoles)","file":"pkg/registry/rbac/validation/rule.go","code":"// NewTestRuleResolver returns a rule resolver from lists of role objects.\nfunc NewTestRuleResolver(roles []*rbacv1.Role, roleBindings []*rbacv1.RoleBinding, clusterRoles []*rbacv1.ClusterRole, clusterRoleBindings []*rbacv1.ClusterRoleBinding) (AuthorizationRuleResolver, *StaticRoles) {\n\tr := StaticRoles{\n\t\troles: roles,\n\t\troleBindings: roleBindings,\n\t\tclusterRoles: clusterRoles,\n\t\tclusterRoleBindings: clusterRoleBindings,\n\t}\n\treturn newMockRuleResolver(\u0026r), \u0026r\n}","line":{"from":306,"to":315}} {"id":100010367,"name":"newMockRuleResolver","signature":"func newMockRuleResolver(r *StaticRoles) AuthorizationRuleResolver","file":"pkg/registry/rbac/validation/rule.go","code":"func newMockRuleResolver(r *StaticRoles) AuthorizationRuleResolver {\n\treturn NewDefaultRuleResolver(r, r, r, r)\n}","line":{"from":317,"to":319}} {"id":100010368,"name":"GetRole","signature":"func (r *StaticRoles) GetRole(namespace, name string) (*rbacv1.Role, error)","file":"pkg/registry/rbac/validation/rule.go","code":"func (r *StaticRoles) GetRole(namespace, name string) (*rbacv1.Role, error) {\n\tif len(namespace) == 0 {\n\t\treturn nil, errors.New(\"must provide namespace when getting role\")\n\t}\n\tfor _, role := range r.roles {\n\t\tif role.Namespace == namespace \u0026\u0026 role.Name == name {\n\t\t\treturn role, nil\n\t\t}\n\t}\n\treturn nil, errors.New(\"role not found\")\n}","line":{"from":329,"to":339}} {"id":100010369,"name":"GetClusterRole","signature":"func (r *StaticRoles) GetClusterRole(name string) (*rbacv1.ClusterRole, error)","file":"pkg/registry/rbac/validation/rule.go","code":"func (r *StaticRoles) GetClusterRole(name string) (*rbacv1.ClusterRole, error) {\n\tfor _, clusterRole := range r.clusterRoles {\n\t\tif clusterRole.Name == name {\n\t\t\treturn clusterRole, nil\n\t\t}\n\t}\n\treturn nil, errors.New(\"clusterrole not found\")\n}","line":{"from":341,"to":348}} {"id":100010370,"name":"ListRoleBindings","signature":"func (r *StaticRoles) ListRoleBindings(namespace string) ([]*rbacv1.RoleBinding, error)","file":"pkg/registry/rbac/validation/rule.go","code":"func (r *StaticRoles) ListRoleBindings(namespace string) ([]*rbacv1.RoleBinding, error) {\n\tif len(namespace) == 0 {\n\t\treturn nil, errors.New(\"must provide namespace when listing role bindings\")\n\t}\n\n\troleBindingList := []*rbacv1.RoleBinding{}\n\tfor _, roleBinding := range r.roleBindings {\n\t\tif roleBinding.Namespace != namespace {\n\t\t\tcontinue\n\t\t}\n\t\t// TODO(ericchiang): need to implement label selectors?\n\t\troleBindingList = append(roleBindingList, roleBinding)\n\t}\n\treturn roleBindingList, nil\n}","line":{"from":350,"to":364}} {"id":100010371,"name":"ListClusterRoleBindings","signature":"func (r *StaticRoles) ListClusterRoleBindings() ([]*rbacv1.ClusterRoleBinding, error)","file":"pkg/registry/rbac/validation/rule.go","code":"func (r *StaticRoles) ListClusterRoleBindings() ([]*rbacv1.ClusterRoleBinding, error) {\n\treturn r.clusterRoleBindings, nil\n}","line":{"from":366,"to":368}} {"id":100010372,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error)","file":"pkg/registry/resource/podschedulingcontext/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against PodSchedulingContext.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026resource.PodSchedulingContext{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026resource.PodSchedulingContextList{} },\n\t\tPredicateFunc: podschedulingcontext.Match,\n\t\tDefaultQualifiedResource: resource.Resource(\"podschedulingcontexts\"),\n\t\tSingularQualifiedResource: resource.Resource(\"podschedulingcontext\"),\n\n\t\tCreateStrategy: podschedulingcontext.Strategy,\n\t\tUpdateStrategy: podschedulingcontext.Strategy,\n\t\tDeleteStrategy: podschedulingcontext.Strategy,\n\t\tReturnDeletedObject: true,\n\t\tResetFieldsStrategy: podschedulingcontext.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: podschedulingcontext.GetAttrs}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = podschedulingcontext.StatusStrategy\n\tstatusStore.ResetFieldsStrategy = podschedulingcontext.StatusStrategy\n\n\trest := \u0026REST{store}\n\n\treturn rest, \u0026StatusREST{store: \u0026statusStore}, nil\n}","line":{"from":40,"to":69}} {"id":100010373,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"pkg/registry/resource/podschedulingcontext/storage/storage.go","code":"// New creates a new PodSchedulingContext object.\nfunc (r *StatusREST) New() runtime.Object {\n\treturn \u0026resource.PodSchedulingContext{}\n}","line":{"from":76,"to":79}} {"id":100010374,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"pkg/registry/resource/podschedulingcontext/storage/storage.go","code":"func (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":81,"to":84}} {"id":100010375,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/resource/podschedulingcontext/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":86,"to":89}} {"id":100010376,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/resource/podschedulingcontext/storage/storage.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":91,"to":96}} {"id":100010377,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/resource/podschedulingcontext/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":98,"to":101}} {"id":100010378,"name":"NamespaceScoped","signature":"func (podSchedulingStrategy) NamespaceScoped() bool","file":"pkg/registry/resource/podschedulingcontext/strategy.go","code":"func (podSchedulingStrategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":46,"to":48}} {"id":100010379,"name":"GetResetFields","signature":"func (podSchedulingStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/resource/podschedulingcontext/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy and\n// should not be modified by the user. For a new PodSchedulingContext that is the\n// status.\nfunc (podSchedulingStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"resource.k8s.io/v1alpha2\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":50,"to":61}} {"id":100010380,"name":"PrepareForCreate","signature":"func (podSchedulingStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/resource/podschedulingcontext/strategy.go","code":"func (podSchedulingStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tscheduling := obj.(*resource.PodSchedulingContext)\n\t// Status must not be set by user on create.\n\tscheduling.Status = resource.PodSchedulingContextStatus{}\n}","line":{"from":63,"to":67}} {"id":100010381,"name":"Validate","signature":"func (podSchedulingStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/resource/podschedulingcontext/strategy.go","code":"func (podSchedulingStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tscheduling := obj.(*resource.PodSchedulingContext)\n\treturn validation.ValidatePodSchedulingContexts(scheduling)\n}","line":{"from":69,"to":72}} {"id":100010382,"name":"WarningsOnCreate","signature":"func (podSchedulingStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/resource/podschedulingcontext/strategy.go","code":"func (podSchedulingStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":74,"to":76}} {"id":100010383,"name":"Canonicalize","signature":"func (podSchedulingStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/resource/podschedulingcontext/strategy.go","code":"func (podSchedulingStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":78,"to":79}} {"id":100010384,"name":"AllowCreateOnUpdate","signature":"func (podSchedulingStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/resource/podschedulingcontext/strategy.go","code":"func (podSchedulingStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":81,"to":83}} {"id":100010385,"name":"PrepareForUpdate","signature":"func (podSchedulingStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/resource/podschedulingcontext/strategy.go","code":"func (podSchedulingStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewScheduling := obj.(*resource.PodSchedulingContext)\n\toldScheduling := old.(*resource.PodSchedulingContext)\n\tnewScheduling.Status = oldScheduling.Status\n}","line":{"from":85,"to":89}} {"id":100010386,"name":"ValidateUpdate","signature":"func (podSchedulingStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/resource/podschedulingcontext/strategy.go","code":"func (podSchedulingStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewScheduling := obj.(*resource.PodSchedulingContext)\n\toldScheduling := old.(*resource.PodSchedulingContext)\n\terrorList := validation.ValidatePodSchedulingContexts(newScheduling)\n\treturn append(errorList, validation.ValidatePodSchedulingContextUpdate(newScheduling, oldScheduling)...)\n}","line":{"from":91,"to":96}} {"id":100010387,"name":"WarningsOnUpdate","signature":"func (podSchedulingStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/resource/podschedulingcontext/strategy.go","code":"func (podSchedulingStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":98,"to":100}} {"id":100010388,"name":"AllowUnconditionalUpdate","signature":"func (podSchedulingStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/resource/podschedulingcontext/strategy.go","code":"func (podSchedulingStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":102,"to":104}} {"id":100010389,"name":"GetResetFields","signature":"func (podSchedulingStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/resource/podschedulingcontext/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy and\n// should not be modified by the user. For a status update that is the spec.\nfunc (podSchedulingStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"resource.k8s.io/v1alpha2\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":112,"to":122}} {"id":100010390,"name":"PrepareForUpdate","signature":"func (podSchedulingStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/resource/podschedulingcontext/strategy.go","code":"func (podSchedulingStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewScheduling := obj.(*resource.PodSchedulingContext)\n\toldScheduling := old.(*resource.PodSchedulingContext)\n\tnewScheduling.Spec = oldScheduling.Spec\n}","line":{"from":124,"to":128}} {"id":100010391,"name":"ValidateUpdate","signature":"func (podSchedulingStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/resource/podschedulingcontext/strategy.go","code":"func (podSchedulingStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewScheduling := obj.(*resource.PodSchedulingContext)\n\toldScheduling := old.(*resource.PodSchedulingContext)\n\treturn validation.ValidatePodSchedulingContextStatusUpdate(newScheduling, oldScheduling)\n}","line":{"from":130,"to":134}} {"id":100010392,"name":"WarningsOnUpdate","signature":"func (podSchedulingStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/resource/podschedulingcontext/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (podSchedulingStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":136,"to":139}} {"id":100010393,"name":"Match","signature":"func Match(label labels.Selector, field fields.Selector) storage.SelectionPredicate","file":"pkg/registry/resource/podschedulingcontext/strategy.go","code":"// Match returns a generic matcher for a given label and field selector.\nfunc Match(label labels.Selector, field fields.Selector) storage.SelectionPredicate {\n\treturn storage.SelectionPredicate{\n\t\tLabel: label,\n\t\tField: field,\n\t\tGetAttrs: GetAttrs,\n\t}\n}","line":{"from":141,"to":148}} {"id":100010394,"name":"GetAttrs","signature":"func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error)","file":"pkg/registry/resource/podschedulingcontext/strategy.go","code":"// GetAttrs returns labels and fields of a given object for filtering purposes.\nfunc GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {\n\tscheduling, ok := obj.(*resource.PodSchedulingContext)\n\tif !ok {\n\t\treturn nil, nil, errors.New(\"not a PodSchedulingContext\")\n\t}\n\treturn labels.Set(scheduling.Labels), toSelectableFields(scheduling), nil\n}","line":{"from":150,"to":157}} {"id":100010395,"name":"toSelectableFields","signature":"func toSelectableFields(scheduling *resource.PodSchedulingContext) fields.Set","file":"pkg/registry/resource/podschedulingcontext/strategy.go","code":"// toSelectableFields returns a field set that represents the object\nfunc toSelectableFields(scheduling *resource.PodSchedulingContext) fields.Set {\n\tfields := generic.ObjectMetaFieldsSet(\u0026scheduling.ObjectMeta, true)\n\treturn fields\n}","line":{"from":159,"to":163}} {"id":100010396,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error)","file":"pkg/registry/resource/resourceclaim/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against ResourceClaims.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, *StatusREST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026resource.ResourceClaim{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026resource.ResourceClaimList{} },\n\t\tPredicateFunc: resourceclaim.Match,\n\t\tDefaultQualifiedResource: resource.Resource(\"resourceclaims\"),\n\t\tSingularQualifiedResource: resource.Resource(\"resourceclaim\"),\n\n\t\tCreateStrategy: resourceclaim.Strategy,\n\t\tUpdateStrategy: resourceclaim.Strategy,\n\t\tDeleteStrategy: resourceclaim.Strategy,\n\t\tReturnDeletedObject: true,\n\t\tResetFieldsStrategy: resourceclaim.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: resourceclaim.GetAttrs}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = resourceclaim.StatusStrategy\n\tstatusStore.ResetFieldsStrategy = resourceclaim.StatusStrategy\n\n\trest := \u0026REST{store}\n\n\treturn rest, \u0026StatusREST{store: \u0026statusStore}, nil\n}","line":{"from":40,"to":69}} {"id":100010397,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"pkg/registry/resource/resourceclaim/storage/storage.go","code":"// New creates a new ResourceClaim object.\nfunc (r *StatusREST) New() runtime.Object {\n\treturn \u0026resource.ResourceClaim{}\n}","line":{"from":76,"to":79}} {"id":100010398,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"pkg/registry/resource/resourceclaim/storage/storage.go","code":"func (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":81,"to":84}} {"id":100010399,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/resource/resourceclaim/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":86,"to":89}} {"id":100010400,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/resource/resourceclaim/storage/storage.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":91,"to":96}} {"id":100010401,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/resource/resourceclaim/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":98,"to":101}} {"id":100010402,"name":"NamespaceScoped","signature":"func (resourceclaimStrategy) NamespaceScoped() bool","file":"pkg/registry/resource/resourceclaim/strategy.go","code":"func (resourceclaimStrategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":46,"to":48}} {"id":100010403,"name":"GetResetFields","signature":"func (resourceclaimStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/resource/resourceclaim/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy and\n// should not be modified by the user. For a new ResourceClaim that is the\n// status.\nfunc (resourceclaimStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"resource.k8s.io/v1alpha2\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":50,"to":61}} {"id":100010404,"name":"PrepareForCreate","signature":"func (resourceclaimStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/resource/resourceclaim/strategy.go","code":"func (resourceclaimStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tclaim := obj.(*resource.ResourceClaim)\n\t// Status must not be set by user on create.\n\tclaim.Status = resource.ResourceClaimStatus{}\n}","line":{"from":63,"to":67}} {"id":100010405,"name":"Validate","signature":"func (resourceclaimStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/resource/resourceclaim/strategy.go","code":"func (resourceclaimStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tclaim := obj.(*resource.ResourceClaim)\n\treturn validation.ValidateClaim(claim)\n}","line":{"from":69,"to":72}} {"id":100010406,"name":"WarningsOnCreate","signature":"func (resourceclaimStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/resource/resourceclaim/strategy.go","code":"func (resourceclaimStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":74,"to":76}} {"id":100010407,"name":"Canonicalize","signature":"func (resourceclaimStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/resource/resourceclaim/strategy.go","code":"func (resourceclaimStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":78,"to":79}} {"id":100010408,"name":"AllowCreateOnUpdate","signature":"func (resourceclaimStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/resource/resourceclaim/strategy.go","code":"func (resourceclaimStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":81,"to":83}} {"id":100010409,"name":"PrepareForUpdate","signature":"func (resourceclaimStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/resource/resourceclaim/strategy.go","code":"func (resourceclaimStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewClaim := obj.(*resource.ResourceClaim)\n\toldClaim := old.(*resource.ResourceClaim)\n\tnewClaim.Status = oldClaim.Status\n}","line":{"from":85,"to":89}} {"id":100010410,"name":"ValidateUpdate","signature":"func (resourceclaimStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/resource/resourceclaim/strategy.go","code":"func (resourceclaimStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewClaim := obj.(*resource.ResourceClaim)\n\toldClaim := old.(*resource.ResourceClaim)\n\terrorList := validation.ValidateClaim(newClaim)\n\treturn append(errorList, validation.ValidateClaimUpdate(newClaim, oldClaim)...)\n}","line":{"from":91,"to":96}} {"id":100010411,"name":"WarningsOnUpdate","signature":"func (resourceclaimStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/resource/resourceclaim/strategy.go","code":"func (resourceclaimStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":98,"to":100}} {"id":100010412,"name":"AllowUnconditionalUpdate","signature":"func (resourceclaimStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/resource/resourceclaim/strategy.go","code":"func (resourceclaimStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":102,"to":104}} {"id":100010413,"name":"GetResetFields","signature":"func (resourceclaimStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/resource/resourceclaim/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy and\n// should not be modified by the user. For a status update that is the spec.\nfunc (resourceclaimStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"resource.k8s.io/v1alpha2\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":112,"to":122}} {"id":100010414,"name":"PrepareForUpdate","signature":"func (resourceclaimStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/resource/resourceclaim/strategy.go","code":"func (resourceclaimStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewClaim := obj.(*resource.ResourceClaim)\n\toldClaim := old.(*resource.ResourceClaim)\n\tnewClaim.Spec = oldClaim.Spec\n}","line":{"from":124,"to":128}} {"id":100010415,"name":"ValidateUpdate","signature":"func (resourceclaimStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/resource/resourceclaim/strategy.go","code":"func (resourceclaimStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewClaim := obj.(*resource.ResourceClaim)\n\toldClaim := old.(*resource.ResourceClaim)\n\treturn validation.ValidateClaimStatusUpdate(newClaim, oldClaim)\n}","line":{"from":130,"to":134}} {"id":100010416,"name":"WarningsOnUpdate","signature":"func (resourceclaimStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/resource/resourceclaim/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (resourceclaimStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":136,"to":139}} {"id":100010417,"name":"Match","signature":"func Match(label labels.Selector, field fields.Selector) storage.SelectionPredicate","file":"pkg/registry/resource/resourceclaim/strategy.go","code":"// Match returns a generic matcher for a given label and field selector.\nfunc Match(label labels.Selector, field fields.Selector) storage.SelectionPredicate {\n\treturn storage.SelectionPredicate{\n\t\tLabel: label,\n\t\tField: field,\n\t\tGetAttrs: GetAttrs,\n\t}\n}","line":{"from":141,"to":148}} {"id":100010418,"name":"GetAttrs","signature":"func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error)","file":"pkg/registry/resource/resourceclaim/strategy.go","code":"// GetAttrs returns labels and fields of a given object for filtering purposes.\nfunc GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {\n\tclaim, ok := obj.(*resource.ResourceClaim)\n\tif !ok {\n\t\treturn nil, nil, errors.New(\"not a resourceclaim\")\n\t}\n\treturn labels.Set(claim.Labels), toSelectableFields(claim), nil\n}","line":{"from":150,"to":157}} {"id":100010419,"name":"toSelectableFields","signature":"func toSelectableFields(claim *resource.ResourceClaim) fields.Set","file":"pkg/registry/resource/resourceclaim/strategy.go","code":"// toSelectableFields returns a field set that represents the object\nfunc toSelectableFields(claim *resource.ResourceClaim) fields.Set {\n\tfields := generic.ObjectMetaFieldsSet(\u0026claim.ObjectMeta, true)\n\treturn fields\n}","line":{"from":159,"to":163}} {"id":100010420,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error)","file":"pkg/registry/resource/resourceclaimtemplate/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against ResourceClass.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026resource.ResourceClaimTemplate{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026resource.ResourceClaimTemplateList{} },\n\t\tDefaultQualifiedResource: resource.Resource(\"resourceclaimtemplates\"),\n\t\tSingularQualifiedResource: resource.Resource(\"resourceclaimtemplate\"),\n\n\t\tCreateStrategy: resourceclaimtemplate.Strategy,\n\t\tUpdateStrategy: resourceclaimtemplate.Strategy,\n\t\tDeleteStrategy: resourceclaimtemplate.Strategy,\n\t\tReturnDeletedObject: true,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: resourceclaimtemplate.GetAttrs}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026REST{store}, nil\n}","line":{"from":35,"to":56}} {"id":100010421,"name":"NamespaceScoped","signature":"func (resourceClaimTemplateStrategy) NamespaceScoped() bool","file":"pkg/registry/resource/resourceclaimtemplate/strategy.go","code":"func (resourceClaimTemplateStrategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":42,"to":44}} {"id":100010422,"name":"PrepareForCreate","signature":"func (resourceClaimTemplateStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/resource/resourceclaimtemplate/strategy.go","code":"func (resourceClaimTemplateStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n}","line":{"from":46,"to":47}} {"id":100010423,"name":"Validate","signature":"func (resourceClaimTemplateStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/resource/resourceclaimtemplate/strategy.go","code":"func (resourceClaimTemplateStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tresourceClaimTemplate := obj.(*resource.ResourceClaimTemplate)\n\treturn validation.ValidateClaimTemplate(resourceClaimTemplate)\n}","line":{"from":49,"to":52}} {"id":100010424,"name":"WarningsOnCreate","signature":"func (resourceClaimTemplateStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/resource/resourceclaimtemplate/strategy.go","code":"func (resourceClaimTemplateStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":54,"to":56}} {"id":100010425,"name":"Canonicalize","signature":"func (resourceClaimTemplateStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/resource/resourceclaimtemplate/strategy.go","code":"func (resourceClaimTemplateStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":58,"to":59}} {"id":100010426,"name":"AllowCreateOnUpdate","signature":"func (resourceClaimTemplateStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/resource/resourceclaimtemplate/strategy.go","code":"func (resourceClaimTemplateStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":61,"to":63}} {"id":100010427,"name":"PrepareForUpdate","signature":"func (resourceClaimTemplateStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/resource/resourceclaimtemplate/strategy.go","code":"func (resourceClaimTemplateStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n}","line":{"from":65,"to":66}} {"id":100010428,"name":"ValidateUpdate","signature":"func (resourceClaimTemplateStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/resource/resourceclaimtemplate/strategy.go","code":"func (resourceClaimTemplateStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\terrorList := validation.ValidateClaimTemplate(obj.(*resource.ResourceClaimTemplate))\n\treturn append(errorList, validation.ValidateClaimTemplateUpdate(obj.(*resource.ResourceClaimTemplate), old.(*resource.ResourceClaimTemplate))...)\n}","line":{"from":68,"to":71}} {"id":100010429,"name":"WarningsOnUpdate","signature":"func (resourceClaimTemplateStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/resource/resourceclaimtemplate/strategy.go","code":"func (resourceClaimTemplateStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":73,"to":75}} {"id":100010430,"name":"AllowUnconditionalUpdate","signature":"func (resourceClaimTemplateStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/resource/resourceclaimtemplate/strategy.go","code":"func (resourceClaimTemplateStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":77,"to":79}} {"id":100010431,"name":"GetAttrs","signature":"func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error)","file":"pkg/registry/resource/resourceclaimtemplate/strategy.go","code":"// GetAttrs returns labels and fields of a given object for filtering purposes.\nfunc GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {\n\ttemplate, ok := obj.(*resource.ResourceClaimTemplate)\n\tif !ok {\n\t\treturn nil, nil, errors.New(\"not a resourceclaimtemplate\")\n\t}\n\treturn labels.Set(template.Labels), toSelectableFields(template), nil\n}","line":{"from":81,"to":88}} {"id":100010432,"name":"toSelectableFields","signature":"func toSelectableFields(template *resource.ResourceClaimTemplate) fields.Set","file":"pkg/registry/resource/resourceclaimtemplate/strategy.go","code":"// toSelectableFields returns a field set that represents the object\nfunc toSelectableFields(template *resource.ResourceClaimTemplate) fields.Set {\n\tfields := generic.ObjectMetaFieldsSet(\u0026template.ObjectMeta, true)\n\treturn fields\n}","line":{"from":90,"to":94}} {"id":100010433,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error)","file":"pkg/registry/resource/resourceclass/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against ResourceClass.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026resource.ResourceClass{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026resource.ResourceClassList{} },\n\t\tDefaultQualifiedResource: resource.Resource(\"resourceclasses\"),\n\t\tSingularQualifiedResource: resource.Resource(\"resourceclass\"),\n\n\t\tCreateStrategy: resourceclass.Strategy,\n\t\tUpdateStrategy: resourceclass.Strategy,\n\t\tDeleteStrategy: resourceclass.Strategy,\n\t\tReturnDeletedObject: true,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026REST{store}, nil\n}","line":{"from":35,"to":56}} {"id":100010434,"name":"NamespaceScoped","signature":"func (resourceClassStrategy) NamespaceScoped() bool","file":"pkg/registry/resource/resourceclass/strategy.go","code":"func (resourceClassStrategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":38,"to":40}} {"id":100010435,"name":"PrepareForCreate","signature":"func (resourceClassStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/resource/resourceclass/strategy.go","code":"func (resourceClassStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n}","line":{"from":42,"to":43}} {"id":100010436,"name":"Validate","signature":"func (resourceClassStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/resource/resourceclass/strategy.go","code":"func (resourceClassStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tresourceClass := obj.(*resource.ResourceClass)\n\treturn validation.ValidateClass(resourceClass)\n}","line":{"from":45,"to":48}} {"id":100010437,"name":"WarningsOnCreate","signature":"func (resourceClassStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/resource/resourceclass/strategy.go","code":"func (resourceClassStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":50,"to":52}} {"id":100010438,"name":"Canonicalize","signature":"func (resourceClassStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/resource/resourceclass/strategy.go","code":"func (resourceClassStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":54,"to":55}} {"id":100010439,"name":"AllowCreateOnUpdate","signature":"func (resourceClassStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/resource/resourceclass/strategy.go","code":"func (resourceClassStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":57,"to":59}} {"id":100010440,"name":"PrepareForUpdate","signature":"func (resourceClassStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/resource/resourceclass/strategy.go","code":"func (resourceClassStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n}","line":{"from":61,"to":62}} {"id":100010441,"name":"ValidateUpdate","signature":"func (resourceClassStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/resource/resourceclass/strategy.go","code":"func (resourceClassStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\terrorList := validation.ValidateClass(obj.(*resource.ResourceClass))\n\treturn append(errorList, validation.ValidateClassUpdate(obj.(*resource.ResourceClass), old.(*resource.ResourceClass))...)\n}","line":{"from":64,"to":67}} {"id":100010442,"name":"WarningsOnUpdate","signature":"func (resourceClassStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/resource/resourceclass/strategy.go","code":"func (resourceClassStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":69,"to":71}} {"id":100010443,"name":"AllowUnconditionalUpdate","signature":"func (resourceClassStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/resource/resourceclass/strategy.go","code":"func (resourceClassStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":73,"to":75}} {"id":100010444,"name":"NewRESTStorage","signature":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error)","file":"pkg/registry/resource/rest/storage_resource.go","code":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error) {\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(resource.GroupName, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs)\n\t// If you add a version here, be sure to add an entry in `k8s.io/kubernetes/cmd/kube-apiserver/app/aggregator.go with specific priorities.\n\t// TODO refactor the plumbing to provide the information in the APIGroupInfo\n\n\tif storageMap, err := p.v1alpha2Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[resourcev1alpha2.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\treturn apiGroupInfo, nil\n}","line":{"from":35,"to":47}} {"id":100010445,"name":"v1alpha2Storage","signature":"func (p RESTStorageProvider) v1alpha2Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/resource/rest/storage_resource.go","code":"func (p RESTStorageProvider) v1alpha2Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\tif resource := \"resourceclasses\"; apiResourceConfigSource.ResourceEnabled(resourcev1alpha2.SchemeGroupVersion.WithResource(resource)) {\n\t\tresourceClassStorage, err := resourceclassstore.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstorage[resource] = resourceClassStorage\n\t}\n\n\tif resource := \"resourceclaims\"; apiResourceConfigSource.ResourceEnabled(resourcev1alpha2.SchemeGroupVersion.WithResource(resource)) {\n\t\tresourceClaimStorage, resourceClaimStatusStorage, err := resourceclaimstore.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstorage[resource] = resourceClaimStorage\n\t\tstorage[resource+\"/status\"] = resourceClaimStatusStorage\n\t}\n\n\tif resource := \"resourceclaimtemplates\"; apiResourceConfigSource.ResourceEnabled(resourcev1alpha2.SchemeGroupVersion.WithResource(resource)) {\n\t\tresourceClaimTemplateStorage, err := resourceclaimtemplatestore.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstorage[resource] = resourceClaimTemplateStorage\n\t}\n\n\tif resource := \"podschedulingcontexts\"; apiResourceConfigSource.ResourceEnabled(resourcev1alpha2.SchemeGroupVersion.WithResource(resource)) {\n\t\tpodSchedulingStorage, podSchedulingStatusStorage, err := podschedulingcontextsstore.NewREST(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstorage[resource] = podSchedulingStorage\n\t\tstorage[resource+\"/status\"] = podSchedulingStatusStorage\n\t}\n\n\treturn storage, nil\n}","line":{"from":49,"to":87}} {"id":100010446,"name":"GroupName","signature":"func (p RESTStorageProvider) GroupName() string","file":"pkg/registry/resource/rest/storage_resource.go","code":"func (p RESTStorageProvider) GroupName() string {\n\treturn resource.GroupName\n}","line":{"from":89,"to":91}} {"id":100010447,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error)","file":"pkg/registry/scheduling/priorityclass/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against priority classes.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026scheduling.PriorityClass{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026scheduling.PriorityClassList{} },\n\t\tDefaultQualifiedResource: scheduling.Resource(\"priorityclasses\"),\n\t\tSingularQualifiedResource: scheduling.Resource(\"priorityclass\"),\n\n\t\tCreateStrategy: priorityclass.Strategy,\n\t\tUpdateStrategy: priorityclass.Strategy,\n\t\tDeleteStrategy: priorityclass.Strategy,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026REST{store}, nil\n}","line":{"from":41,"to":61}} {"id":100010448,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/scheduling/priorityclass/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"pc\"}\n}","line":{"from":66,"to":69}} {"id":100010449,"name":"Delete","signature":"func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions) (runtime.Object, bool, error)","file":"pkg/registry/scheduling/priorityclass/storage/storage.go","code":"// Delete ensures that system priority classes are not deleted.\nfunc (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions) (runtime.Object, bool, error) {\n\tfor _, spc := range schedulingapiv1.SystemPriorityClasses() {\n\t\tif name == spc.Name {\n\t\t\treturn nil, false, apierrors.NewForbidden(scheduling.Resource(\"priorityclasses\"), spc.Name, errors.New(\"this is a system priority class and cannot be deleted\"))\n\t\t}\n\t}\n\n\treturn r.Store.Delete(ctx, name, deleteValidation, options)\n}","line":{"from":71,"to":80}} {"id":100010450,"name":"NamespaceScoped","signature":"func (priorityClassStrategy) NamespaceScoped() bool","file":"pkg/registry/scheduling/priorityclass/strategy.go","code":"// NamespaceScoped returns false because all PriorityClasses are global.\nfunc (priorityClassStrategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":39,"to":42}} {"id":100010451,"name":"PrepareForCreate","signature":"func (priorityClassStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/scheduling/priorityclass/strategy.go","code":"// PrepareForCreate clears the status of a PriorityClass before creation.\nfunc (priorityClassStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tpc := obj.(*scheduling.PriorityClass)\n\tpc.Generation = 1\n}","line":{"from":44,"to":48}} {"id":100010452,"name":"PrepareForUpdate","signature":"func (priorityClassStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {}","file":"pkg/registry/scheduling/priorityclass/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (priorityClassStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {}","line":{"from":50,"to":51}} {"id":100010453,"name":"Validate","signature":"func (priorityClassStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/scheduling/priorityclass/strategy.go","code":"// Validate validates a new PriorityClass.\nfunc (priorityClassStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tpc := obj.(*scheduling.PriorityClass)\n\treturn validation.ValidatePriorityClass(pc)\n}","line":{"from":53,"to":57}} {"id":100010454,"name":"WarningsOnCreate","signature":"func (priorityClassStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/scheduling/priorityclass/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (priorityClassStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":59,"to":62}} {"id":100010455,"name":"Canonicalize","signature":"func (priorityClassStrategy) Canonicalize(obj runtime.Object) {}","file":"pkg/registry/scheduling/priorityclass/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (priorityClassStrategy) Canonicalize(obj runtime.Object) {}","line":{"from":64,"to":65}} {"id":100010456,"name":"AllowCreateOnUpdate","signature":"func (priorityClassStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/scheduling/priorityclass/strategy.go","code":"// AllowCreateOnUpdate is false for PriorityClass; this means POST is needed to create one.\nfunc (priorityClassStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":67,"to":70}} {"id":100010457,"name":"ValidateUpdate","signature":"func (priorityClassStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/scheduling/priorityclass/strategy.go","code":"// ValidateUpdate is the default update validation for an end user.\nfunc (priorityClassStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidatePriorityClassUpdate(obj.(*scheduling.PriorityClass), old.(*scheduling.PriorityClass))\n}","line":{"from":72,"to":75}} {"id":100010458,"name":"WarningsOnUpdate","signature":"func (priorityClassStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/scheduling/priorityclass/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (priorityClassStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":77,"to":80}} {"id":100010459,"name":"AllowUnconditionalUpdate","signature":"func (priorityClassStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/scheduling/priorityclass/strategy.go","code":"// AllowUnconditionalUpdate is the default update policy for PriorityClass objects.\nfunc (priorityClassStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":82,"to":85}} {"id":100010460,"name":"NewRESTStorage","signature":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error)","file":"pkg/registry/scheduling/rest/storage_scheduling.go","code":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error) {\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(scheduling.GroupName, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs)\n\n\tif storageMap, err := p.v1Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[schedulingapiv1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\treturn apiGroupInfo, nil\n}","line":{"from":47,"to":57}} {"id":100010461,"name":"v1Storage","signature":"func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/scheduling/rest/storage_scheduling.go","code":"func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\t// priorityclasses\n\tif resource := \"priorityclasses\"; apiResourceConfigSource.ResourceEnabled(schedulingapiv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tif priorityClassStorage, err := priorityclassstore.NewREST(restOptionsGetter); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tstorage[resource] = priorityClassStorage\n\t\t}\n\t}\n\n\treturn storage, nil\n}","line":{"from":59,"to":72}} {"id":100010462,"name":"PostStartHook","signature":"func (p RESTStorageProvider) PostStartHook() (string, genericapiserver.PostStartHookFunc, error)","file":"pkg/registry/scheduling/rest/storage_scheduling.go","code":"func (p RESTStorageProvider) PostStartHook() (string, genericapiserver.PostStartHookFunc, error) {\n\treturn PostStartHookName, AddSystemPriorityClasses(), nil\n}","line":{"from":74,"to":76}} {"id":100010463,"name":"AddSystemPriorityClasses","signature":"func AddSystemPriorityClasses() genericapiserver.PostStartHookFunc","file":"pkg/registry/scheduling/rest/storage_scheduling.go","code":"func AddSystemPriorityClasses() genericapiserver.PostStartHookFunc {\n\treturn func(hookContext genericapiserver.PostStartHookContext) error {\n\t\t// Adding system priority classes is important. If they fail to add, many critical system\n\t\t// components may fail and cluster may break.\n\t\terr := wait.Poll(1*time.Second, 30*time.Second, func() (done bool, err error) {\n\t\t\tschedClientSet, err := schedulingclient.NewForConfig(hookContext.LoopbackClientConfig)\n\t\t\tif err != nil {\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"unable to initialize client: %v\", err))\n\t\t\t\treturn false, nil\n\t\t\t}\n\n\t\t\tfor _, pc := range schedulingapiv1.SystemPriorityClasses() {\n\t\t\t\t_, err := schedClientSet.PriorityClasses().Get(context.TODO(), pc.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\t\t\t_, err := schedClientSet.PriorityClasses().Create(context.TODO(), pc, metav1.CreateOptions{})\n\t\t\t\t\t\tif err == nil || apierrors.IsAlreadyExists(err) {\n\t\t\t\t\t\t\tklog.Infof(\"created PriorityClass %s with value %v\", pc.Name, pc.Value)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// ServiceUnavailble error is returned when the API server is blocked by storage version updates\n\t\t\t\t\t\tif apierrors.IsServiceUnavailable(err) {\n\t\t\t\t\t\t\tklog.Infof(\"going to retry, unable to create PriorityClass %s: %v\", pc.Name, err)\n\t\t\t\t\t\t\treturn false, nil\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn false, err\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Unable to get the priority class for reasons other than \"not found\".\n\t\t\t\t\t\tklog.Warningf(\"unable to get PriorityClass %v: %v. Retrying...\", pc.Name, err)\n\t\t\t\t\t\treturn false, nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tklog.Infof(\"all system priority classes are created successfully or already exist.\")\n\t\t\treturn true, nil\n\t\t})\n\t\t// if we're never able to make it through initialization, kill the API server.\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to add default system priority classes: %v\", err)\n\t\t}\n\t\treturn nil\n\t}\n}","line":{"from":78,"to":120}} {"id":100010464,"name":"GroupName","signature":"func (p RESTStorageProvider) GroupName() string","file":"pkg/registry/scheduling/rest/storage_scheduling.go","code":"func (p RESTStorageProvider) GroupName() string {\n\treturn scheduling.GroupName\n}","line":{"from":122,"to":124}} {"id":100010465,"name":"NewStorage","signature":"func NewStorage(optsGetter generic.RESTOptionsGetter) (*CSIDriverStorage, error)","file":"pkg/registry/storage/csidriver/storage/storage.go","code":"// NewStorage returns a RESTStorage object that will work against CSIDrivers\nfunc NewStorage(optsGetter generic.RESTOptionsGetter) (*CSIDriverStorage, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026storageapi.CSIDriver{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026storageapi.CSIDriverList{} },\n\t\tDefaultQualifiedResource: storageapi.Resource(\"csidrivers\"),\n\t\tSingularQualifiedResource: storageapi.Resource(\"csidriver\"),\n\n\t\tCreateStrategy: csidriver.Strategy,\n\t\tUpdateStrategy: csidriver.Strategy,\n\t\tDeleteStrategy: csidriver.Strategy,\n\t\tReturnDeletedObject: true,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026CSIDriverStorage{\n\t\tCSIDriver: \u0026REST{store},\n\t}, nil\n}","line":{"from":40,"to":63}} {"id":100010466,"name":"NamespaceScoped","signature":"func (csiDriverStrategy) NamespaceScoped() bool","file":"pkg/registry/storage/csidriver/strategy.go","code":"func (csiDriverStrategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":43,"to":45}} {"id":100010467,"name":"PrepareForCreate","signature":"func (csiDriverStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/storage/csidriver/strategy.go","code":"// PrepareForCreate clears the fields for which the corresponding feature is disabled.\nfunc (csiDriverStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tcsiDriver := obj.(*storage.CSIDriver)\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {\n\t\tcsiDriver.Spec.SELinuxMount = nil\n\t}\n}","line":{"from":47,"to":53}} {"id":100010468,"name":"Validate","signature":"func (csiDriverStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/storage/csidriver/strategy.go","code":"func (csiDriverStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tcsiDriver := obj.(*storage.CSIDriver)\n\n\treturn validation.ValidateCSIDriver(csiDriver)\n}","line":{"from":55,"to":59}} {"id":100010469,"name":"WarningsOnCreate","signature":"func (csiDriverStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/storage/csidriver/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (csiDriverStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":61,"to":64}} {"id":100010470,"name":"Canonicalize","signature":"func (csiDriverStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/storage/csidriver/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (csiDriverStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":66,"to":68}} {"id":100010471,"name":"AllowCreateOnUpdate","signature":"func (csiDriverStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/storage/csidriver/strategy.go","code":"func (csiDriverStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":70,"to":72}} {"id":100010472,"name":"PrepareForUpdate","signature":"func (csiDriverStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/storage/csidriver/strategy.go","code":"// PrepareForUpdate clears the fields for which the corresponding feature is disabled and\n// existing object does not already have that field set. This allows the field to remain when\n// downgrading to a version that has the feature disabled.\nfunc (csiDriverStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewCSIDriver := obj.(*storage.CSIDriver)\n\toldCSIDriver := old.(*storage.CSIDriver)\n\n\tif oldCSIDriver.Spec.SELinuxMount == nil \u0026\u0026\n\t\t!utilfeature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {\n\t\tnewCSIDriver.Spec.SELinuxMount = nil\n\t}\n\n\t// Any changes to the mutable fields increment the generation number.\n\tif !apiequality.Semantic.DeepEqual(oldCSIDriver.Spec.TokenRequests, newCSIDriver.Spec.TokenRequests) ||\n\t\t!apiequality.Semantic.DeepEqual(oldCSIDriver.Spec.RequiresRepublish, newCSIDriver.Spec.RequiresRepublish) ||\n\t\t!apiequality.Semantic.DeepEqual(oldCSIDriver.Spec.SELinuxMount, newCSIDriver.Spec.SELinuxMount) {\n\t\tnewCSIDriver.Generation = oldCSIDriver.Generation + 1\n\t}\n}","line":{"from":74,"to":92}} {"id":100010473,"name":"ValidateUpdate","signature":"func (csiDriverStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/storage/csidriver/strategy.go","code":"func (csiDriverStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewCSIDriverObj := obj.(*storage.CSIDriver)\n\toldCSIDriverObj := old.(*storage.CSIDriver)\n\treturn validation.ValidateCSIDriverUpdate(newCSIDriverObj, oldCSIDriverObj)\n}","line":{"from":94,"to":98}} {"id":100010474,"name":"WarningsOnUpdate","signature":"func (csiDriverStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/storage/csidriver/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (csiDriverStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":100,"to":103}} {"id":100010475,"name":"AllowUnconditionalUpdate","signature":"func (csiDriverStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/storage/csidriver/strategy.go","code":"func (csiDriverStrategy) AllowUnconditionalUpdate() bool {\n\treturn false\n}","line":{"from":105,"to":107}} {"id":100010476,"name":"NewStorage","signature":"func NewStorage(optsGetter generic.RESTOptionsGetter) (*CSINodeStorage, error)","file":"pkg/registry/storage/csinode/storage/storage.go","code":"// NewStorage returns a RESTStorage object that will work against CSINodes\nfunc NewStorage(optsGetter generic.RESTOptionsGetter) (*CSINodeStorage, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026storageapi.CSINode{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026storageapi.CSINodeList{} },\n\t\tDefaultQualifiedResource: storageapi.Resource(\"csinodes\"),\n\t\tSingularQualifiedResource: storageapi.Resource(\"csinode\"),\n\n\t\tCreateStrategy: csinode.Strategy,\n\t\tUpdateStrategy: csinode.Strategy,\n\t\tDeleteStrategy: csinode.Strategy,\n\t\tReturnDeletedObject: true,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026CSINodeStorage{\n\t\tCSINode: \u0026REST{store},\n\t}, nil\n}","line":{"from":40,"to":63}} {"id":100010477,"name":"NamespaceScoped","signature":"func (csiNodeStrategy) NamespaceScoped() bool","file":"pkg/registry/storage/csinode/strategy.go","code":"func (csiNodeStrategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":40,"to":42}} {"id":100010478,"name":"PrepareForCreate","signature":"func (csiNodeStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/storage/csinode/strategy.go","code":"// PrepareForCreate clears fields that are not allowed to be set on creation.\nfunc (csiNodeStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n}","line":{"from":44,"to":46}} {"id":100010479,"name":"Validate","signature":"func (csiNodeStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/storage/csinode/strategy.go","code":"func (csiNodeStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tcsiNode := obj.(*storage.CSINode)\n\tvalidateOptions := validation.CSINodeValidationOptions{\n\t\tAllowLongNodeID: true,\n\t}\n\n\terrs := validation.ValidateCSINode(csiNode, validateOptions)\n\n\treturn errs\n}","line":{"from":48,"to":57}} {"id":100010480,"name":"WarningsOnCreate","signature":"func (csiNodeStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return nil }","file":"pkg/registry/storage/csinode/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (csiNodeStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return nil }","line":{"from":59,"to":60}} {"id":100010481,"name":"Canonicalize","signature":"func (csiNodeStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/storage/csinode/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (csiNodeStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":62,"to":64}} {"id":100010482,"name":"AllowCreateOnUpdate","signature":"func (csiNodeStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/storage/csinode/strategy.go","code":"func (csiNodeStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":66,"to":68}} {"id":100010483,"name":"PrepareForUpdate","signature":"func (csiNodeStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/storage/csinode/strategy.go","code":"// PrepareForUpdate sets the driver's Allocatable fields that are not allowed to be set by an end user updating a CSINode.\nfunc (csiNodeStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n}","line":{"from":70,"to":72}} {"id":100010484,"name":"ValidateUpdate","signature":"func (csiNodeStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/storage/csinode/strategy.go","code":"func (csiNodeStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewCSINodeObj := obj.(*storage.CSINode)\n\toldCSINodeObj := old.(*storage.CSINode)\n\tvalidateOptions := validation.CSINodeValidationOptions{\n\t\tAllowLongNodeID: true,\n\t}\n\n\terrorList := validation.ValidateCSINode(newCSINodeObj, validateOptions)\n\treturn append(errorList, validation.ValidateCSINodeUpdate(newCSINodeObj, oldCSINodeObj, validateOptions)...)\n}","line":{"from":74,"to":83}} {"id":100010485,"name":"WarningsOnUpdate","signature":"func (csiNodeStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/storage/csinode/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (csiNodeStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":85,"to":88}} {"id":100010486,"name":"AllowUnconditionalUpdate","signature":"func (csiNodeStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/storage/csinode/strategy.go","code":"func (csiNodeStrategy) AllowUnconditionalUpdate() bool {\n\treturn false\n}","line":{"from":90,"to":92}} {"id":100010487,"name":"NewStorage","signature":"func NewStorage(optsGetter generic.RESTOptionsGetter) (*CSIStorageCapacityStorage, error)","file":"pkg/registry/storage/csistoragecapacity/storage/storage.go","code":"// NewStorage returns a RESTStorage object that will work against CSIStorageCapacity\nfunc NewStorage(optsGetter generic.RESTOptionsGetter) (*CSIStorageCapacityStorage, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026storageapi.CSIStorageCapacity{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026storageapi.CSIStorageCapacityList{} },\n\t\tDefaultQualifiedResource: storageapi.Resource(\"csistoragecapacities\"),\n\t\tSingularQualifiedResource: storageapi.Resource(\"csistoragecapacity\"),\n\n\t\tTableConvertor: rest.NewDefaultTableConvertor(storageapi.Resource(\"csistoragecapacities\")),\n\n\t\tCreateStrategy: csistoragecapacity.Strategy,\n\t\tUpdateStrategy: csistoragecapacity.Strategy,\n\t\tDeleteStrategy: csistoragecapacity.Strategy,\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026CSIStorageCapacityStorage{\n\t\tCSIStorageCapacity: \u0026REST{store},\n\t}, nil\n}","line":{"from":38,"to":60}} {"id":100010488,"name":"NamespaceScoped","signature":"func (csiStorageCapacityStrategy) NamespaceScoped() bool","file":"pkg/registry/storage/csistoragecapacity/strategy.go","code":"func (csiStorageCapacityStrategy) NamespaceScoped() bool {\n\treturn true\n}","line":{"from":42,"to":44}} {"id":100010489,"name":"PrepareForCreate","signature":"func (csiStorageCapacityStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/storage/csistoragecapacity/strategy.go","code":"// PrepareForCreate is currently a NOP.\nfunc (csiStorageCapacityStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n}","line":{"from":46,"to":48}} {"id":100010490,"name":"Validate","signature":"func (csiStorageCapacityStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/storage/csistoragecapacity/strategy.go","code":"func (csiStorageCapacityStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tcsiStorageCapacity := obj.(*storage.CSIStorageCapacity)\n\topts := validation.CSIStorageCapacityValidateOptions{\n\t\tAllowInvalidLabelValueInSelector: false,\n\t}\n\terrs := validation.ValidateCSIStorageCapacity(csiStorageCapacity, opts)\n\terrs = append(errs, validation.ValidateCSIStorageCapacity(csiStorageCapacity, opts)...)\n\n\treturn errs\n}","line":{"from":50,"to":59}} {"id":100010491,"name":"WarningsOnCreate","signature":"func (csiStorageCapacityStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/storage/csistoragecapacity/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (csiStorageCapacityStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn storageutil.GetWarningsForCSIStorageCapacity(obj.(*storage.CSIStorageCapacity))\n}","line":{"from":61,"to":64}} {"id":100010492,"name":"Canonicalize","signature":"func (csiStorageCapacityStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/storage/csistoragecapacity/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (csiStorageCapacityStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":66,"to":68}} {"id":100010493,"name":"AllowCreateOnUpdate","signature":"func (csiStorageCapacityStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/storage/csistoragecapacity/strategy.go","code":"func (csiStorageCapacityStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":70,"to":72}} {"id":100010494,"name":"PrepareForUpdate","signature":"func (csiStorageCapacityStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/storage/csistoragecapacity/strategy.go","code":"// PrepareForUpdate is currently a NOP.\nfunc (csiStorageCapacityStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n}","line":{"from":74,"to":76}} {"id":100010495,"name":"ValidateUpdate","signature":"func (csiStorageCapacityStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/storage/csistoragecapacity/strategy.go","code":"func (csiStorageCapacityStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewCSIStorageCapacityObj := obj.(*storage.CSIStorageCapacity)\n\toldCSIStorageCapacityObj := old.(*storage.CSIStorageCapacity)\n\topts := validation.CSIStorageCapacityValidateOptions{\n\t\tAllowInvalidLabelValueInSelector: hasInvalidLabelValueInLabelSelector(oldCSIStorageCapacityObj),\n\t}\n\terrorList := validation.ValidateCSIStorageCapacity(newCSIStorageCapacityObj, opts)\n\treturn append(errorList, validation.ValidateCSIStorageCapacityUpdate(newCSIStorageCapacityObj, oldCSIStorageCapacityObj)...)\n}","line":{"from":78,"to":86}} {"id":100010496,"name":"WarningsOnUpdate","signature":"func (csiStorageCapacityStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/storage/csistoragecapacity/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (csiStorageCapacityStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn storageutil.GetWarningsForCSIStorageCapacity(obj.(*storage.CSIStorageCapacity))\n}","line":{"from":88,"to":91}} {"id":100010497,"name":"AllowUnconditionalUpdate","signature":"func (csiStorageCapacityStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/storage/csistoragecapacity/strategy.go","code":"func (csiStorageCapacityStrategy) AllowUnconditionalUpdate() bool {\n\treturn false\n}","line":{"from":93,"to":95}} {"id":100010498,"name":"hasInvalidLabelValueInLabelSelector","signature":"func hasInvalidLabelValueInLabelSelector(capacity *storage.CSIStorageCapacity) bool","file":"pkg/registry/storage/csistoragecapacity/strategy.go","code":"func hasInvalidLabelValueInLabelSelector(capacity *storage.CSIStorageCapacity) bool {\n\tlabelSelectorValidationOptions := metav1validation.LabelSelectorValidationOptions{AllowInvalidLabelValueInSelector: false}\n\treturn len(metav1validation.ValidateLabelSelector(capacity.NodeTopology, labelSelectorValidationOptions, nil)) \u003e 0\n}","line":{"from":97,"to":100}} {"id":100010499,"name":"NewRESTStorage","signature":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error)","file":"pkg/registry/storage/rest/storage_storage.go","code":"func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (genericapiserver.APIGroupInfo, error) {\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(storageapi.GroupName, legacyscheme.Scheme, legacyscheme.ParameterCodec, legacyscheme.Codecs)\n\t// If you add a version here, be sure to add an entry in `k8s.io/kubernetes/cmd/kube-apiserver/app/aggregator.go with specific priorities.\n\t// TODO refactor the plumbing to provide the information in the APIGroupInfo\n\n\tif storageMap, err := p.v1alpha1Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[storageapiv1alpha1.SchemeGroupVersion.Version] = storageMap\n\t}\n\tif storageMap, err := p.v1beta1Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[storageapiv1beta1.SchemeGroupVersion.Version] = storageMap\n\t}\n\tif storageMap, err := p.v1Storage(apiResourceConfigSource, restOptionsGetter); err != nil {\n\t\treturn genericapiserver.APIGroupInfo{}, err\n\t} else if len(storageMap) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[storageapiv1.SchemeGroupVersion.Version] = storageMap\n\t}\n\n\treturn apiGroupInfo, nil\n}","line":{"from":39,"to":61}} {"id":100010500,"name":"v1alpha1Storage","signature":"func (p RESTStorageProvider) v1alpha1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/storage/rest/storage_storage.go","code":"func (p RESTStorageProvider) v1alpha1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\t// register csistoragecapacities\n\tif resource := \"csistoragecapacities\"; apiResourceConfigSource.ResourceEnabled(storageapiv1alpha1.SchemeGroupVersion.WithResource(resource)) {\n\t\tcsiStorageStorage, err := csistoragecapacitystore.NewStorage(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = csiStorageStorage.CSIStorageCapacity\n\t}\n\n\treturn storage, nil\n}","line":{"from":63,"to":76}} {"id":100010501,"name":"v1beta1Storage","signature":"func (p RESTStorageProvider) v1beta1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/storage/rest/storage_storage.go","code":"func (p RESTStorageProvider) v1beta1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorage := map[string]rest.Storage{}\n\n\t// register csistoragecapacities\n\tif resource := \"csistoragecapacities\"; apiResourceConfigSource.ResourceEnabled(storageapiv1beta1.SchemeGroupVersion.WithResource(resource)) {\n\t\tcsiStorageStorage, err := csistoragecapacitystore.NewStorage(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = csiStorageStorage.CSIStorageCapacity\n\t}\n\n\treturn storage, nil\n}","line":{"from":78,"to":91}} {"id":100010502,"name":"v1Storage","signature":"func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error)","file":"pkg/registry/storage/rest/storage_storage.go","code":"func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {\n\tstorageClassStorage, err := storageclassstore.NewREST(restOptionsGetter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvolumeAttachmentStorage, err := volumeattachmentstore.NewStorage(restOptionsGetter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstorage := map[string]rest.Storage{}\n\n\t// storageclasses\n\tif resource := \"storageclasses\"; apiResourceConfigSource.ResourceEnabled(storageapiv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = storageClassStorage\n\t}\n\n\t// volumeattachments\n\tif resource := \"volumeattachments\"; apiResourceConfigSource.ResourceEnabled(storageapiv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tstorage[resource] = volumeAttachmentStorage.VolumeAttachment\n\t\tstorage[resource+\"/status\"] = volumeAttachmentStorage.Status\n\t}\n\n\t// register csinodes\n\tif resource := \"csinodes\"; apiResourceConfigSource.ResourceEnabled(storageapiv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tcsiNodeStorage, err := csinodestore.NewStorage(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstorage[resource] = csiNodeStorage.CSINode\n\t}\n\n\t// register csidrivers\n\tif resource := \"csidrivers\"; apiResourceConfigSource.ResourceEnabled(storageapiv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tcsiDriverStorage, err := csidriverstore.NewStorage(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = csiDriverStorage.CSIDriver\n\t}\n\n\t// register csistoragecapacities\n\tif resource := \"csistoragecapacities\"; apiResourceConfigSource.ResourceEnabled(storageapiv1.SchemeGroupVersion.WithResource(resource)) {\n\t\tcsiStorageStorage, err := csistoragecapacitystore.NewStorage(restOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn storage, err\n\t\t}\n\t\tstorage[resource] = csiStorageStorage.CSIStorageCapacity\n\t}\n\n\treturn storage, nil\n}","line":{"from":93,"to":144}} {"id":100010503,"name":"GroupName","signature":"func (p RESTStorageProvider) GroupName() string","file":"pkg/registry/storage/rest/storage_storage.go","code":"func (p RESTStorageProvider) GroupName() string {\n\treturn storageapi.GroupName\n}","line":{"from":146,"to":148}} {"id":100010504,"name":"NewREST","signature":"func NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error)","file":"pkg/registry/storage/storageclass/storage/storage.go","code":"// NewREST returns a RESTStorage object that will work against storage classes.\nfunc NewREST(optsGetter generic.RESTOptionsGetter) (*REST, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026storageapi.StorageClass{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026storageapi.StorageClassList{} },\n\t\tDefaultQualifiedResource: storageapi.Resource(\"storageclasses\"),\n\t\tSingularQualifiedResource: storageapi.Resource(\"storageclass\"),\n\n\t\tCreateStrategy: storageclass.Strategy,\n\t\tUpdateStrategy: storageclass.Strategy,\n\t\tDeleteStrategy: storageclass.Strategy,\n\t\tReturnDeletedObject: true,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026REST{store}, nil\n}","line":{"from":36,"to":57}} {"id":100010505,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"pkg/registry/storage/storageclass/storage/storage.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"sc\"}\n}","line":{"from":62,"to":65}} {"id":100010506,"name":"NamespaceScoped","signature":"func (storageClassStrategy) NamespaceScoped() bool","file":"pkg/registry/storage/storageclass/strategy.go","code":"func (storageClassStrategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":41,"to":43}} {"id":100010507,"name":"PrepareForCreate","signature":"func (storageClassStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/storage/storageclass/strategy.go","code":"// ResetBeforeCreate clears the Status field which is not allowed to be set by end users on creation.\nfunc (storageClassStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n}","line":{"from":45,"to":47}} {"id":100010508,"name":"Validate","signature":"func (storageClassStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/storage/storageclass/strategy.go","code":"func (storageClassStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tstorageClass := obj.(*storage.StorageClass)\n\treturn validation.ValidateStorageClass(storageClass)\n}","line":{"from":49,"to":52}} {"id":100010509,"name":"WarningsOnCreate","signature":"func (storageClassStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/storage/storageclass/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (storageClassStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn storageutil.GetWarningsForStorageClass(obj.(*storage.StorageClass))\n}","line":{"from":54,"to":57}} {"id":100010510,"name":"Canonicalize","signature":"func (storageClassStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/storage/storageclass/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (storageClassStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":59,"to":61}} {"id":100010511,"name":"AllowCreateOnUpdate","signature":"func (storageClassStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/storage/storageclass/strategy.go","code":"func (storageClassStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":63,"to":65}} {"id":100010512,"name":"PrepareForUpdate","signature":"func (storageClassStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/storage/storageclass/strategy.go","code":"// PrepareForUpdate sets the Status fields which is not allowed to be set by an end user updating a PV\nfunc (storageClassStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n}","line":{"from":67,"to":69}} {"id":100010513,"name":"ValidateUpdate","signature":"func (storageClassStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/storage/storageclass/strategy.go","code":"func (storageClassStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\terrorList := validation.ValidateStorageClass(obj.(*storage.StorageClass))\n\treturn append(errorList, validation.ValidateStorageClassUpdate(obj.(*storage.StorageClass), old.(*storage.StorageClass))...)\n}","line":{"from":71,"to":74}} {"id":100010514,"name":"WarningsOnUpdate","signature":"func (storageClassStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/storage/storageclass/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (storageClassStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn storageutil.GetWarningsForStorageClass(obj.(*storage.StorageClass))\n}","line":{"from":76,"to":79}} {"id":100010515,"name":"AllowUnconditionalUpdate","signature":"func (storageClassStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/storage/storageclass/strategy.go","code":"func (storageClassStrategy) AllowUnconditionalUpdate() bool {\n\treturn true\n}","line":{"from":81,"to":83}} {"id":100010516,"name":"NewStorage","signature":"func NewStorage(optsGetter generic.RESTOptionsGetter) (*VolumeAttachmentStorage, error)","file":"pkg/registry/storage/volumeattachment/storage/storage.go","code":"// NewStorage returns a RESTStorage object that will work against VolumeAttachments\nfunc NewStorage(optsGetter generic.RESTOptionsGetter) (*VolumeAttachmentStorage, error) {\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026storageapi.VolumeAttachment{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026storageapi.VolumeAttachmentList{} },\n\t\tDefaultQualifiedResource: storageapi.Resource(\"volumeattachments\"),\n\t\tSingularQualifiedResource: storageapi.Resource(\"volumeattachment\"),\n\n\t\tCreateStrategy: volumeattachment.Strategy,\n\t\tUpdateStrategy: volumeattachment.Strategy,\n\t\tDeleteStrategy: volumeattachment.Strategy,\n\t\tResetFieldsStrategy: volumeattachment.Strategy,\n\t\tReturnDeletedObject: true,\n\n\t\tTableConvertor: printerstorage.TableConvertor{TableGenerator: printers.NewTableGenerator().With(printersinternal.AddHandlers)},\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\n\tstatusStore := *store\n\tstatusStore.UpdateStrategy = volumeattachment.StatusStrategy\n\tstatusStore.ResetFieldsStrategy = volumeattachment.StatusStrategy\n\n\treturn \u0026VolumeAttachmentStorage{\n\t\tVolumeAttachment: \u0026REST{store},\n\t\tStatus: \u0026StatusREST{store: \u0026statusStore},\n\t}, nil\n}","line":{"from":46,"to":75}} {"id":100010517,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"pkg/registry/storage/volumeattachment/storage/storage.go","code":"// New creates a new VolumeAttachment resource\nfunc (r *StatusREST) New() runtime.Object {\n\treturn \u0026storageapi.VolumeAttachment{}\n}","line":{"from":84,"to":87}} {"id":100010518,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"pkg/registry/storage/volumeattachment/storage/storage.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":89,"to":93}} {"id":100010519,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"pkg/registry/storage/volumeattachment/storage/storage.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":95,"to":98}} {"id":100010520,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"pkg/registry/storage/volumeattachment/storage/storage.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":100,"to":105}} {"id":100010521,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/storage/volumeattachment/storage/storage.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":107,"to":110}} {"id":100010522,"name":"ConvertToTable","signature":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"pkg/registry/storage/volumeattachment/storage/storage.go","code":"func (r *StatusREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\treturn r.store.ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":112,"to":114}} {"id":100010523,"name":"NamespaceScoped","signature":"func (volumeAttachmentStrategy) NamespaceScoped() bool","file":"pkg/registry/storage/volumeattachment/strategy.go","code":"func (volumeAttachmentStrategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":42,"to":44}} {"id":100010524,"name":"GetResetFields","signature":"func (volumeAttachmentStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/storage/volumeattachment/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (volumeAttachmentStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"storage.k8s.io/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":46,"to":56}} {"id":100010525,"name":"PrepareForCreate","signature":"func (volumeAttachmentStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"pkg/registry/storage/volumeattachment/strategy.go","code":"// ResetBeforeCreate clears the Status field which is not allowed to be set by end users on creation.\nfunc (volumeAttachmentStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tvolumeAttachment := obj.(*storage.VolumeAttachment)\n\tvolumeAttachment.Status = storage.VolumeAttachmentStatus{}\n}","line":{"from":58,"to":62}} {"id":100010526,"name":"Validate","signature":"func (volumeAttachmentStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"pkg/registry/storage/volumeattachment/strategy.go","code":"func (volumeAttachmentStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tvolumeAttachment := obj.(*storage.VolumeAttachment)\n\n\terrs := validation.ValidateVolumeAttachment(volumeAttachment)\n\n\t// tighten up validation of newly created v1 attachments\n\terrs = append(errs, validation.ValidateVolumeAttachmentV1(volumeAttachment)...)\n\treturn errs\n}","line":{"from":64,"to":72}} {"id":100010527,"name":"WarningsOnCreate","signature":"func (volumeAttachmentStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"pkg/registry/storage/volumeattachment/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (volumeAttachmentStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":74,"to":77}} {"id":100010528,"name":"Canonicalize","signature":"func (volumeAttachmentStrategy) Canonicalize(obj runtime.Object)","file":"pkg/registry/storage/volumeattachment/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (volumeAttachmentStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":79,"to":81}} {"id":100010529,"name":"AllowCreateOnUpdate","signature":"func (volumeAttachmentStrategy) AllowCreateOnUpdate() bool","file":"pkg/registry/storage/volumeattachment/strategy.go","code":"func (volumeAttachmentStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":83,"to":85}} {"id":100010530,"name":"PrepareForUpdate","signature":"func (volumeAttachmentStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/storage/volumeattachment/strategy.go","code":"// PrepareForUpdate sets the Status fields which is not allowed to be set by an end user updating a VolumeAttachment\nfunc (volumeAttachmentStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewVolumeAttachment := obj.(*storage.VolumeAttachment)\n\toldVolumeAttachment := old.(*storage.VolumeAttachment)\n\n\tnewVolumeAttachment.Status = oldVolumeAttachment.Status\n\t// No need to increment Generation because we don't allow updates to spec\n\n}","line":{"from":87,"to":95}} {"id":100010531,"name":"ValidateUpdate","signature":"func (volumeAttachmentStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"pkg/registry/storage/volumeattachment/strategy.go","code":"func (volumeAttachmentStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewVolumeAttachmentObj := obj.(*storage.VolumeAttachment)\n\toldVolumeAttachmentObj := old.(*storage.VolumeAttachment)\n\terrorList := validation.ValidateVolumeAttachment(newVolumeAttachmentObj)\n\treturn append(errorList, validation.ValidateVolumeAttachmentUpdate(newVolumeAttachmentObj, oldVolumeAttachmentObj)...)\n}","line":{"from":97,"to":102}} {"id":100010532,"name":"WarningsOnUpdate","signature":"func (volumeAttachmentStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"pkg/registry/storage/volumeattachment/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (volumeAttachmentStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":104,"to":107}} {"id":100010533,"name":"AllowUnconditionalUpdate","signature":"func (volumeAttachmentStrategy) AllowUnconditionalUpdate() bool","file":"pkg/registry/storage/volumeattachment/strategy.go","code":"func (volumeAttachmentStrategy) AllowUnconditionalUpdate() bool {\n\treturn false\n}","line":{"from":109,"to":111}} {"id":100010534,"name":"GetResetFields","signature":"func (volumeAttachmentStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"pkg/registry/storage/volumeattachment/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (volumeAttachmentStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"storage.k8s.io/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"metadata\"),\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":122,"to":133}} {"id":100010535,"name":"PrepareForUpdate","signature":"func (volumeAttachmentStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"pkg/registry/storage/volumeattachment/strategy.go","code":"// PrepareForUpdate sets the Status fields which is not allowed to be set by an end user updating a VolumeAttachment\nfunc (volumeAttachmentStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewVolumeAttachment := obj.(*storage.VolumeAttachment)\n\toldVolumeAttachment := old.(*storage.VolumeAttachment)\n\n\tnewVolumeAttachment.Spec = oldVolumeAttachment.Spec\n\tmetav1.ResetObjectMetaForStatus(\u0026newVolumeAttachment.ObjectMeta, \u0026oldVolumeAttachment.ObjectMeta)\n}","line":{"from":135,"to":142}} {"id":100010536,"name":"Install","signature":"func (l Logs) Install(c *restful.Container)","file":"pkg/routes/logs.go","code":"// Install func registers the logs handler.\nfunc (l Logs) Install(c *restful.Container) {\n\t// use restful: ws.Route(ws.GET(\"/logs/{logpath:*}\").To(fileHandler))\n\t// See github.com/emicklei/go-restful/blob/master/examples/static/restful-serve-static.go\n\tws := new(restful.WebService)\n\tws.Path(\"/logs\")\n\tws.Doc(\"get log files\")\n\tws.Route(ws.GET(\"/{logpath:*}\").To(logFileHandler).Param(ws.PathParameter(\"logpath\", \"path to the log\").DataType(\"string\")))\n\tws.Route(ws.GET(\"/\").To(logFileListHandler))\n\n\tc.Add(ws)\n}","line":{"from":30,"to":41}} {"id":100010537,"name":"logFileHandler","signature":"func logFileHandler(req *restful.Request, resp *restful.Response)","file":"pkg/routes/logs.go","code":"func logFileHandler(req *restful.Request, resp *restful.Response) {\n\tlogdir := \"/var/log\"\n\tactual := path.Join(logdir, req.PathParameter(\"logpath\"))\n\n\t// check filename length first, return 404 if it's oversize.\n\tif logFileNameIsTooLong(actual) {\n\t\thttp.Error(resp, \"file not found\", http.StatusNotFound)\n\t\treturn\n\t}\n\thttp.ServeFile(resp.ResponseWriter, req.Request, actual)\n}","line":{"from":43,"to":53}} {"id":100010538,"name":"logFileListHandler","signature":"func logFileListHandler(req *restful.Request, resp *restful.Response)","file":"pkg/routes/logs.go","code":"func logFileListHandler(req *restful.Request, resp *restful.Response) {\n\tlogdir := \"/var/log\"\n\thttp.ServeFile(resp.ResponseWriter, req.Request, logdir)\n}","line":{"from":55,"to":58}} {"id":100010539,"name":"logFileNameIsTooLong","signature":"func logFileNameIsTooLong(filePath string) bool","file":"pkg/routes/logs.go","code":"// logFileNameIsTooLong checks filename length, returns true if it's longer than 255.\n// cause http.ServeFile returns default error code 500 except for NotExist and Forbidden, but we need to separate the real 500 from oversize filename here.\nfunc logFileNameIsTooLong(filePath string) bool {\n\t_, err := os.Stat(filePath)\n\tif err != nil {\n\t\tif e, ok := err.(*os.PathError); ok \u0026\u0026 e.Err == fileNameTooLong {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":60,"to":70}} {"id":100010540,"name":"NewOpenIDMetadataServer","signature":"func NewOpenIDMetadataServer(configJSON, keysetJSON []byte) *OpenIDMetadataServer","file":"pkg/routes/openidmetadata.go","code":"// NewOpenIDMetadataServer creates a new OpenIDMetadataServer.\n// The issuer is the OIDC issuer; keys are the keys that may be used to sign\n// KSA tokens.\nfunc NewOpenIDMetadataServer(configJSON, keysetJSON []byte) *OpenIDMetadataServer {\n\treturn \u0026OpenIDMetadataServer{\n\t\tconfigJSON: configJSON,\n\t\tkeysetJSON: keysetJSON,\n\t}\n}","line":{"from":49,"to":57}} {"id":100010541,"name":"Install","signature":"func (s *OpenIDMetadataServer) Install(c *restful.Container)","file":"pkg/routes/openidmetadata.go","code":"// Install adds this server to the request router c.\nfunc (s *OpenIDMetadataServer) Install(c *restful.Container) {\n\t// Configuration WebService\n\t// Container.Add \"will detect duplicate root paths and exit in that case\",\n\t// so we need a root for /.well-known/openid-configuration to avoid conflicts.\n\tcfg := new(restful.WebService).\n\t\tProduces(restful.MIME_JSON)\n\n\tcfg.Path(serviceaccount.OpenIDConfigPath).Route(\n\t\tcfg.GET(\"\").\n\t\t\tTo(fromStandard(s.serveConfiguration)).\n\t\t\tDoc(\"get service account issuer OpenID configuration, also known as the 'OIDC discovery doc'\").\n\t\t\tOperation(\"getServiceAccountIssuerOpenIDConfiguration\").\n\t\t\t// Just include the OK, doesn't look like we include Internal Error in our openapi-spec.\n\t\t\tReturns(http.StatusOK, \"OK\", \"\"))\n\tc.Add(cfg)\n\n\t// JWKS WebService\n\tjwks := new(restful.WebService).\n\t\tProduces(mimeJWKS)\n\n\tjwks.Path(serviceaccount.JWKSPath).Route(\n\t\tjwks.GET(\"\").\n\t\t\tTo(fromStandard(s.serveKeys)).\n\t\t\tDoc(\"get service account issuer OpenID JSON Web Key Set (contains public token verification keys)\").\n\t\t\tOperation(\"getServiceAccountIssuerOpenIDKeyset\").\n\t\t\t// Just include the OK, doesn't look like we include Internal Error in our openapi-spec.\n\t\t\tReturns(http.StatusOK, \"OK\", \"\"))\n\tc.Add(jwks)\n}","line":{"from":59,"to":88}} {"id":100010542,"name":"fromStandard","signature":"func fromStandard(h http.HandlerFunc) restful.RouteFunction","file":"pkg/routes/openidmetadata.go","code":"// fromStandard provides compatibility between the standard (net/http) handler signature and the restful signature.\nfunc fromStandard(h http.HandlerFunc) restful.RouteFunction {\n\treturn func(req *restful.Request, resp *restful.Response) {\n\t\th(resp, req.Request)\n\t}\n}","line":{"from":90,"to":95}} {"id":100010543,"name":"serveConfiguration","signature":"func (s *OpenIDMetadataServer) serveConfiguration(w http.ResponseWriter, req *http.Request)","file":"pkg/routes/openidmetadata.go","code":"func (s *OpenIDMetadataServer) serveConfiguration(w http.ResponseWriter, req *http.Request) {\n\tw.Header().Set(restful.HEADER_ContentType, restful.MIME_JSON)\n\tw.Header().Set(headerCacheControl, cacheControl)\n\tif _, err := w.Write(s.configJSON); err != nil {\n\t\tklog.Errorf(\"failed to write service account issuer metadata response: %v\", err)\n\t\treturn\n\t}\n}","line":{"from":97,"to":104}} {"id":100010544,"name":"serveKeys","signature":"func (s *OpenIDMetadataServer) serveKeys(w http.ResponseWriter, req *http.Request)","file":"pkg/routes/openidmetadata.go","code":"func (s *OpenIDMetadataServer) serveKeys(w http.ResponseWriter, req *http.Request) {\n\t// Per RFC7517 : https://tools.ietf.org/html/rfc7517#section-8.5.1\n\tw.Header().Set(restful.HEADER_ContentType, mimeJWKS)\n\tw.Header().Set(headerCacheControl, cacheControl)\n\tif _, err := w.Write(s.keysetJSON); err != nil {\n\t\tklog.Errorf(\"failed to write service account issuer JWKS response: %v\", err)\n\t\treturn\n\t}\n}","line":{"from":106,"to":114}} {"id":100010545,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"pkg/scheduler/apis/config/register.go","code":"// addKnownTypes registers known types to the given scheme\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026KubeSchedulerConfiguration{},\n\t\t\u0026DefaultPreemptionArgs{},\n\t\t\u0026InterPodAffinityArgs{},\n\t\t\u0026NodeResourcesFitArgs{},\n\t\t\u0026PodTopologySpreadArgs{},\n\t\t\u0026VolumeBindingArgs{},\n\t\t\u0026NodeResourcesBalancedAllocationArgs{},\n\t\t\u0026NodeAffinityArgs{},\n\t)\n\treturn nil\n}","line":{"from":37,"to":50}} {"id":100010546,"name":"init","signature":"func init()","file":"pkg/scheduler/apis/config/scheme/scheme.go","code":"func init() {\n\tAddToScheme(Scheme)\n}","line":{"from":37,"to":39}} {"id":100010547,"name":"AddToScheme","signature":"func AddToScheme(scheme *runtime.Scheme)","file":"pkg/scheduler/apis/config/scheme/scheme.go","code":"// AddToScheme builds the kubescheduler scheme using all known versions of the kubescheduler api.\nfunc AddToScheme(scheme *runtime.Scheme) {\n\tutilruntime.Must(config.AddToScheme(scheme))\n\tutilruntime.Must(configv1beta2.AddToScheme(scheme))\n\tutilruntime.Must(configv1beta3.AddToScheme(scheme))\n\tutilruntime.Must(configv1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(\n\t\tconfigv1.SchemeGroupVersion,\n\t\tconfigv1beta3.SchemeGroupVersion,\n\t\tconfigv1beta2.SchemeGroupVersion,\n\t))\n}","line":{"from":41,"to":52}} {"id":100010548,"name":"Names","signature":"func (p *Plugins) Names() []string","file":"pkg/scheduler/apis/config/types.go","code":"// Names returns the list of enabled plugin names.\nfunc (p *Plugins) Names() []string {\n\tif p == nil {\n\t\treturn nil\n\t}\n\textensions := []PluginSet{\n\t\tp.PreEnqueue,\n\t\tp.PreFilter,\n\t\tp.Filter,\n\t\tp.PostFilter,\n\t\tp.Reserve,\n\t\tp.PreScore,\n\t\tp.Score,\n\t\tp.PreBind,\n\t\tp.Bind,\n\t\tp.PostBind,\n\t\tp.Permit,\n\t\tp.QueueSort,\n\t}\n\tn := sets.NewString()\n\tfor _, e := range extensions {\n\t\tfor _, pg := range e.Enabled {\n\t\t\tn.Insert(pg.Name)\n\t\t}\n\t}\n\treturn n.List()\n}","line":{"from":231,"to":257}} {"id":100010549,"name":"GetPluginArgConversionScheme","signature":"func GetPluginArgConversionScheme() *runtime.Scheme","file":"pkg/scheduler/apis/config/v1/conversion.go","code":"func GetPluginArgConversionScheme() *runtime.Scheme {\n\tinitPluginArgConversionScheme.Do(func() {\n\t\t// set up the scheme used for plugin arg conversion\n\t\tpluginArgConversionScheme = runtime.NewScheme()\n\t\tutilruntime.Must(AddToScheme(pluginArgConversionScheme))\n\t\tutilruntime.Must(config.AddToScheme(pluginArgConversionScheme))\n\t})\n\treturn pluginArgConversionScheme\n}","line":{"from":38,"to":46}} {"id":100010550,"name":"Convert_v1_KubeSchedulerConfiguration_To_config_KubeSchedulerConfiguration","signature":"func Convert_v1_KubeSchedulerConfiguration_To_config_KubeSchedulerConfiguration(in *v1.KubeSchedulerConfiguration, out *config.KubeSchedulerConfiguration, s conversion.Scope) error","file":"pkg/scheduler/apis/config/v1/conversion.go","code":"func Convert_v1_KubeSchedulerConfiguration_To_config_KubeSchedulerConfiguration(in *v1.KubeSchedulerConfiguration, out *config.KubeSchedulerConfiguration, s conversion.Scope) error {\n\tif err := autoConvert_v1_KubeSchedulerConfiguration_To_config_KubeSchedulerConfiguration(in, out, s); err != nil {\n\t\treturn err\n\t}\n\treturn convertToInternalPluginConfigArgs(out)\n}","line":{"from":48,"to":53}} {"id":100010551,"name":"convertToInternalPluginConfigArgs","signature":"func convertToInternalPluginConfigArgs(out *config.KubeSchedulerConfiguration) error","file":"pkg/scheduler/apis/config/v1/conversion.go","code":"// convertToInternalPluginConfigArgs converts PluginConfig#Args into internal\n// types using a scheme, after applying defaults.\nfunc convertToInternalPluginConfigArgs(out *config.KubeSchedulerConfiguration) error {\n\tscheme := GetPluginArgConversionScheme()\n\tfor i := range out.Profiles {\n\t\tprof := \u0026out.Profiles[i]\n\t\tfor j := range prof.PluginConfig {\n\t\t\targs := prof.PluginConfig[j].Args\n\t\t\tif args == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif _, isUnknown := args.(*runtime.Unknown); isUnknown {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tinternalArgs, err := scheme.ConvertToVersion(args, config.SchemeGroupVersion)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"converting .Profiles[%d].PluginConfig[%d].Args into internal type: %w\", i, j, err)\n\t\t\t}\n\t\t\tprof.PluginConfig[j].Args = internalArgs\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":55,"to":77}} {"id":100010552,"name":"Convert_config_KubeSchedulerConfiguration_To_v1_KubeSchedulerConfiguration","signature":"func Convert_config_KubeSchedulerConfiguration_To_v1_KubeSchedulerConfiguration(in *config.KubeSchedulerConfiguration, out *v1.KubeSchedulerConfiguration, s conversion.Scope) error","file":"pkg/scheduler/apis/config/v1/conversion.go","code":"func Convert_config_KubeSchedulerConfiguration_To_v1_KubeSchedulerConfiguration(in *config.KubeSchedulerConfiguration, out *v1.KubeSchedulerConfiguration, s conversion.Scope) error {\n\tif err := autoConvert_config_KubeSchedulerConfiguration_To_v1_KubeSchedulerConfiguration(in, out, s); err != nil {\n\t\treturn err\n\t}\n\treturn convertToExternalPluginConfigArgs(out)\n}","line":{"from":79,"to":84}} {"id":100010553,"name":"convertToExternalPluginConfigArgs","signature":"func convertToExternalPluginConfigArgs(out *v1.KubeSchedulerConfiguration) error","file":"pkg/scheduler/apis/config/v1/conversion.go","code":"// convertToExternalPluginConfigArgs converts PluginConfig#Args into\n// external (versioned) types using a scheme.\nfunc convertToExternalPluginConfigArgs(out *v1.KubeSchedulerConfiguration) error {\n\tscheme := GetPluginArgConversionScheme()\n\tfor i := range out.Profiles {\n\t\tfor j := range out.Profiles[i].PluginConfig {\n\t\t\targs := out.Profiles[i].PluginConfig[j].Args\n\t\t\tif args.Object == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif _, isUnknown := args.Object.(*runtime.Unknown); isUnknown {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\texternalArgs, err := scheme.ConvertToVersion(args.Object, SchemeGroupVersion)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tout.Profiles[i].PluginConfig[j].Args.Object = externalArgs\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":86,"to":107}} {"id":100010554,"name":"getDefaultPlugins","signature":"func getDefaultPlugins() *v1.Plugins","file":"pkg/scheduler/apis/config/v1/default_plugins.go","code":"// getDefaultPlugins returns the default set of plugins.\nfunc getDefaultPlugins() *v1.Plugins {\n\tplugins := \u0026v1.Plugins{\n\t\tMultiPoint: v1.PluginSet{\n\t\t\tEnabled: []v1.Plugin{\n\t\t\t\t{Name: names.PrioritySort},\n\t\t\t\t{Name: names.NodeUnschedulable},\n\t\t\t\t{Name: names.NodeName},\n\t\t\t\t{Name: names.TaintToleration, Weight: pointer.Int32(3)},\n\t\t\t\t{Name: names.NodeAffinity, Weight: pointer.Int32(2)},\n\t\t\t\t{Name: names.NodePorts},\n\t\t\t\t{Name: names.NodeResourcesFit, Weight: pointer.Int32(1)},\n\t\t\t\t{Name: names.VolumeRestrictions},\n\t\t\t\t{Name: names.EBSLimits},\n\t\t\t\t{Name: names.GCEPDLimits},\n\t\t\t\t{Name: names.NodeVolumeLimits},\n\t\t\t\t{Name: names.AzureDiskLimits},\n\t\t\t\t{Name: names.VolumeBinding},\n\t\t\t\t{Name: names.VolumeZone},\n\t\t\t\t{Name: names.PodTopologySpread, Weight: pointer.Int32(2)},\n\t\t\t\t{Name: names.InterPodAffinity, Weight: pointer.Int32(2)},\n\t\t\t\t{Name: names.DefaultPreemption},\n\t\t\t\t{Name: names.NodeResourcesBalancedAllocation, Weight: pointer.Int32(1)},\n\t\t\t\t{Name: names.ImageLocality, Weight: pointer.Int32(1)},\n\t\t\t\t{Name: names.DefaultBinder},\n\t\t\t},\n\t\t},\n\t}\n\tapplyFeatureGates(plugins)\n\n\treturn plugins\n}","line":{"from":29,"to":60}} {"id":100010555,"name":"applyFeatureGates","signature":"func applyFeatureGates(config *v1.Plugins)","file":"pkg/scheduler/apis/config/v1/default_plugins.go","code":"func applyFeatureGates(config *v1.Plugins) {\n\tif utilfeature.DefaultFeatureGate.Enabled(features.PodSchedulingReadiness) {\n\t\tconfig.MultiPoint.Enabled = append(config.MultiPoint.Enabled, v1.Plugin{Name: names.SchedulingGates})\n\t}\n\tif utilfeature.DefaultFeatureGate.Enabled(features.DynamicResourceAllocation) {\n\t\t// This plugin should come before DefaultPreemption because if\n\t\t// there is a problem with a Pod and PostFilter gets called to\n\t\t// resolve the problem, it is better to first deallocate an\n\t\t// idle ResourceClaim than it is to evict some Pod that might\n\t\t// be doing useful work.\n\t\tfor i := range config.MultiPoint.Enabled {\n\t\t\tif config.MultiPoint.Enabled[i].Name == names.DefaultPreemption {\n\t\t\t\textended := make([]v1.Plugin, 0, len(config.MultiPoint.Enabled)+1)\n\t\t\t\textended = append(extended, config.MultiPoint.Enabled[:i]...)\n\t\t\t\textended = append(extended, v1.Plugin{Name: names.DynamicResources})\n\t\t\t\textended = append(extended, config.MultiPoint.Enabled[i:]...)\n\t\t\t\tconfig.MultiPoint.Enabled = extended\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":62,"to":83}} {"id":100010556,"name":"mergePlugins","signature":"func mergePlugins(logger klog.Logger, defaultPlugins, customPlugins *v1.Plugins) *v1.Plugins","file":"pkg/scheduler/apis/config/v1/default_plugins.go","code":"// mergePlugins merges the custom set into the given default one, handling disabled sets.\nfunc mergePlugins(logger klog.Logger, defaultPlugins, customPlugins *v1.Plugins) *v1.Plugins {\n\tif customPlugins == nil {\n\t\treturn defaultPlugins\n\t}\n\n\tdefaultPlugins.MultiPoint = mergePluginSet(logger, defaultPlugins.MultiPoint, customPlugins.MultiPoint)\n\tdefaultPlugins.PreEnqueue = mergePluginSet(logger, defaultPlugins.PreEnqueue, customPlugins.PreEnqueue)\n\tdefaultPlugins.QueueSort = mergePluginSet(logger, defaultPlugins.QueueSort, customPlugins.QueueSort)\n\tdefaultPlugins.PreFilter = mergePluginSet(logger, defaultPlugins.PreFilter, customPlugins.PreFilter)\n\tdefaultPlugins.Filter = mergePluginSet(logger, defaultPlugins.Filter, customPlugins.Filter)\n\tdefaultPlugins.PostFilter = mergePluginSet(logger, defaultPlugins.PostFilter, customPlugins.PostFilter)\n\tdefaultPlugins.PreScore = mergePluginSet(logger, defaultPlugins.PreScore, customPlugins.PreScore)\n\tdefaultPlugins.Score = mergePluginSet(logger, defaultPlugins.Score, customPlugins.Score)\n\tdefaultPlugins.Reserve = mergePluginSet(logger, defaultPlugins.Reserve, customPlugins.Reserve)\n\tdefaultPlugins.Permit = mergePluginSet(logger, defaultPlugins.Permit, customPlugins.Permit)\n\tdefaultPlugins.PreBind = mergePluginSet(logger, defaultPlugins.PreBind, customPlugins.PreBind)\n\tdefaultPlugins.Bind = mergePluginSet(logger, defaultPlugins.Bind, customPlugins.Bind)\n\tdefaultPlugins.PostBind = mergePluginSet(logger, defaultPlugins.PostBind, customPlugins.PostBind)\n\treturn defaultPlugins\n}","line":{"from":85,"to":105}} {"id":100010557,"name":"mergePluginSet","signature":"func mergePluginSet(logger klog.Logger, defaultPluginSet, customPluginSet v1.PluginSet) v1.PluginSet","file":"pkg/scheduler/apis/config/v1/default_plugins.go","code":"func mergePluginSet(logger klog.Logger, defaultPluginSet, customPluginSet v1.PluginSet) v1.PluginSet {\n\tdisabledPlugins := sets.NewString()\n\tenabledCustomPlugins := make(map[string]pluginIndex)\n\t// replacedPluginIndex is a set of index of plugins, which have replaced the default plugins.\n\treplacedPluginIndex := sets.NewInt()\n\tvar disabled []v1.Plugin\n\tfor _, disabledPlugin := range customPluginSet.Disabled {\n\t\t// if the user is manually disabling any (or all, with \"*\") default plugins for an extension point,\n\t\t// we need to track that so that the MultiPoint extension logic in the framework can know to skip\n\t\t// inserting unspecified default plugins to this point.\n\t\tdisabled = append(disabled, v1.Plugin{Name: disabledPlugin.Name})\n\t\tdisabledPlugins.Insert(disabledPlugin.Name)\n\t}\n\n\t// With MultiPoint, we may now have some disabledPlugins in the default registry\n\t// For example, we enable PluginX with Filter+Score through MultiPoint but disable its Score plugin by default.\n\tfor _, disabledPlugin := range defaultPluginSet.Disabled {\n\t\tdisabled = append(disabled, v1.Plugin{Name: disabledPlugin.Name})\n\t\tdisabledPlugins.Insert(disabledPlugin.Name)\n\t}\n\n\tfor index, enabledPlugin := range customPluginSet.Enabled {\n\t\tenabledCustomPlugins[enabledPlugin.Name] = pluginIndex{index, enabledPlugin}\n\t}\n\tvar enabledPlugins []v1.Plugin\n\tif !disabledPlugins.Has(\"*\") {\n\t\tfor _, defaultEnabledPlugin := range defaultPluginSet.Enabled {\n\t\t\tif disabledPlugins.Has(defaultEnabledPlugin.Name) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// The default plugin is explicitly re-configured, update the default plugin accordingly.\n\t\t\tif customPlugin, ok := enabledCustomPlugins[defaultEnabledPlugin.Name]; ok {\n\t\t\t\tlogger.Info(\"Default plugin is explicitly re-configured; overriding\", \"plugin\", defaultEnabledPlugin.Name)\n\t\t\t\t// Update the default plugin in place to preserve order.\n\t\t\t\tdefaultEnabledPlugin = customPlugin.plugin\n\t\t\t\treplacedPluginIndex.Insert(customPlugin.index)\n\t\t\t}\n\t\t\tenabledPlugins = append(enabledPlugins, defaultEnabledPlugin)\n\t\t}\n\t}\n\n\t// Append all the custom plugins which haven't replaced any default plugins.\n\t// Note: duplicated custom plugins will still be appended here.\n\t// If so, the instantiation of scheduler framework will detect it and abort.\n\tfor index, plugin := range customPluginSet.Enabled {\n\t\tif !replacedPluginIndex.Has(index) {\n\t\t\tenabledPlugins = append(enabledPlugins, plugin)\n\t\t}\n\t}\n\treturn v1.PluginSet{Enabled: enabledPlugins, Disabled: disabled}\n}","line":{"from":112,"to":162}} {"id":100010558,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/scheduler/apis/config/v1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":37,"to":39}} {"id":100010559,"name":"pluginsNames","signature":"func pluginsNames(p *configv1.Plugins) []string","file":"pkg/scheduler/apis/config/v1/defaults.go","code":"func pluginsNames(p *configv1.Plugins) []string {\n\tif p == nil {\n\t\treturn nil\n\t}\n\textensions := []configv1.PluginSet{\n\t\tp.MultiPoint,\n\t\tp.PreFilter,\n\t\tp.Filter,\n\t\tp.PostFilter,\n\t\tp.Reserve,\n\t\tp.PreScore,\n\t\tp.Score,\n\t\tp.PreBind,\n\t\tp.Bind,\n\t\tp.PostBind,\n\t\tp.Permit,\n\t\tp.PreEnqueue,\n\t\tp.QueueSort,\n\t}\n\tn := sets.NewString()\n\tfor _, e := range extensions {\n\t\tfor _, pg := range e.Enabled {\n\t\t\tn.Insert(pg.Name)\n\t\t}\n\t}\n\treturn n.List()\n}","line":{"from":41,"to":67}} {"id":100010560,"name":"setDefaults_KubeSchedulerProfile","signature":"func setDefaults_KubeSchedulerProfile(logger klog.Logger, prof *configv1.KubeSchedulerProfile)","file":"pkg/scheduler/apis/config/v1/defaults.go","code":"func setDefaults_KubeSchedulerProfile(logger klog.Logger, prof *configv1.KubeSchedulerProfile) {\n\t// Set default plugins.\n\tprof.Plugins = mergePlugins(logger, getDefaultPlugins(), prof.Plugins)\n\t// Set default plugin configs.\n\tscheme := GetPluginArgConversionScheme()\n\texistingConfigs := sets.NewString()\n\tfor j := range prof.PluginConfig {\n\t\texistingConfigs.Insert(prof.PluginConfig[j].Name)\n\t\targs := prof.PluginConfig[j].Args.Object\n\t\tif _, isUnknown := args.(*runtime.Unknown); isUnknown {\n\t\t\tcontinue\n\t\t}\n\t\tscheme.Default(args)\n\t}\n\n\t// Append default configs for plugins that didn't have one explicitly set.\n\tfor _, name := range pluginsNames(prof.Plugins) {\n\t\tif existingConfigs.Has(name) {\n\t\t\tcontinue\n\t\t}\n\t\tgvk := configv1.SchemeGroupVersion.WithKind(name + \"Args\")\n\t\targs, err := scheme.New(gvk)\n\t\tif err != nil {\n\t\t\t// This plugin is out-of-tree or doesn't require configuration.\n\t\t\tcontinue\n\t\t}\n\t\tscheme.Default(args)\n\t\targs.GetObjectKind().SetGroupVersionKind(gvk)\n\t\tprof.PluginConfig = append(prof.PluginConfig, configv1.PluginConfig{\n\t\t\tName: name,\n\t\t\tArgs: runtime.RawExtension{Object: args},\n\t\t})\n\t}\n}","line":{"from":69,"to":102}} {"id":100010561,"name":"SetDefaults_KubeSchedulerConfiguration","signature":"func SetDefaults_KubeSchedulerConfiguration(obj *configv1.KubeSchedulerConfiguration)","file":"pkg/scheduler/apis/config/v1/defaults.go","code":"// SetDefaults_KubeSchedulerConfiguration sets additional defaults\nfunc SetDefaults_KubeSchedulerConfiguration(obj *configv1.KubeSchedulerConfiguration) {\n\tlogger := klog.TODO() // called by generated code that doesn't pass a logger. See #115724\n\tif obj.Parallelism == nil {\n\t\tobj.Parallelism = pointer.Int32(16)\n\t}\n\n\tif len(obj.Profiles) == 0 {\n\t\tobj.Profiles = append(obj.Profiles, configv1.KubeSchedulerProfile{})\n\t}\n\t// Only apply a default scheduler name when there is a single profile.\n\t// Validation will ensure that every profile has a non-empty unique name.\n\tif len(obj.Profiles) == 1 \u0026\u0026 obj.Profiles[0].SchedulerName == nil {\n\t\tobj.Profiles[0].SchedulerName = pointer.String(v1.DefaultSchedulerName)\n\t}\n\n\t// Add the default set of plugins and apply the configuration.\n\tfor i := range obj.Profiles {\n\t\tprof := \u0026obj.Profiles[i]\n\t\tsetDefaults_KubeSchedulerProfile(logger, prof)\n\t}\n\n\tif obj.PercentageOfNodesToScore == nil {\n\t\tobj.PercentageOfNodesToScore = pointer.Int32(config.DefaultPercentageOfNodesToScore)\n\t}\n\n\tif len(obj.LeaderElection.ResourceLock) == 0 {\n\t\t// Use lease-based leader election to reduce cost.\n\t\t// We migrated for EndpointsLease lock in 1.17 and starting in 1.20 we\n\t\t// migrated to Lease lock.\n\t\tobj.LeaderElection.ResourceLock = \"leases\"\n\t}\n\tif len(obj.LeaderElection.ResourceNamespace) == 0 {\n\t\tobj.LeaderElection.ResourceNamespace = configv1.SchedulerDefaultLockObjectNamespace\n\t}\n\tif len(obj.LeaderElection.ResourceName) == 0 {\n\t\tobj.LeaderElection.ResourceName = configv1.SchedulerDefaultLockObjectName\n\t}\n\n\tif len(obj.ClientConnection.ContentType) == 0 {\n\t\tobj.ClientConnection.ContentType = \"application/vnd.kubernetes.protobuf\"\n\t}\n\t// Scheduler has an opinion about QPS/Burst, setting specific defaults for itself, instead of generic settings.\n\tif obj.ClientConnection.QPS == 0.0 {\n\t\tobj.ClientConnection.QPS = 50.0\n\t}\n\tif obj.ClientConnection.Burst == 0 {\n\t\tobj.ClientConnection.Burst = 100\n\t}\n\n\t// Use the default LeaderElectionConfiguration options\n\tcomponentbaseconfigv1alpha1.RecommendedDefaultLeaderElectionConfiguration(\u0026obj.LeaderElection)\n\n\tif obj.PodInitialBackoffSeconds == nil {\n\t\tobj.PodInitialBackoffSeconds = pointer.Int64(1)\n\t}\n\n\tif obj.PodMaxBackoffSeconds == nil {\n\t\tobj.PodMaxBackoffSeconds = pointer.Int64(10)\n\t}\n\n\t// Enable profiling by default in the scheduler\n\tif obj.EnableProfiling == nil {\n\t\tobj.EnableProfiling = pointer.Bool(true)\n\t}\n\n\t// Enable contention profiling by default if profiling is enabled\n\tif *obj.EnableProfiling \u0026\u0026 obj.EnableContentionProfiling == nil {\n\t\tobj.EnableContentionProfiling = pointer.Bool(true)\n\t}\n}","line":{"from":104,"to":174}} {"id":100010562,"name":"SetDefaults_DefaultPreemptionArgs","signature":"func SetDefaults_DefaultPreemptionArgs(obj *configv1.DefaultPreemptionArgs)","file":"pkg/scheduler/apis/config/v1/defaults.go","code":"func SetDefaults_DefaultPreemptionArgs(obj *configv1.DefaultPreemptionArgs) {\n\tif obj.MinCandidateNodesPercentage == nil {\n\t\tobj.MinCandidateNodesPercentage = pointer.Int32(10)\n\t}\n\tif obj.MinCandidateNodesAbsolute == nil {\n\t\tobj.MinCandidateNodesAbsolute = pointer.Int32(100)\n\t}\n}","line":{"from":176,"to":183}} {"id":100010563,"name":"SetDefaults_InterPodAffinityArgs","signature":"func SetDefaults_InterPodAffinityArgs(obj *configv1.InterPodAffinityArgs)","file":"pkg/scheduler/apis/config/v1/defaults.go","code":"func SetDefaults_InterPodAffinityArgs(obj *configv1.InterPodAffinityArgs) {\n\tif obj.HardPodAffinityWeight == nil {\n\t\tobj.HardPodAffinityWeight = pointer.Int32(1)\n\t}\n}","line":{"from":185,"to":189}} {"id":100010564,"name":"SetDefaults_VolumeBindingArgs","signature":"func SetDefaults_VolumeBindingArgs(obj *configv1.VolumeBindingArgs)","file":"pkg/scheduler/apis/config/v1/defaults.go","code":"func SetDefaults_VolumeBindingArgs(obj *configv1.VolumeBindingArgs) {\n\tif obj.BindTimeoutSeconds == nil {\n\t\tobj.BindTimeoutSeconds = pointer.Int64(600)\n\t}\n\tif len(obj.Shape) == 0 \u0026\u0026 feature.DefaultFeatureGate.Enabled(features.VolumeCapacityPriority) {\n\t\tobj.Shape = []configv1.UtilizationShapePoint{\n\t\t\t{\n\t\t\t\tUtilization: 0,\n\t\t\t\tScore: 0,\n\t\t\t},\n\t\t\t{\n\t\t\t\tUtilization: 100,\n\t\t\t\tScore: int32(config.MaxCustomPriorityScore),\n\t\t\t},\n\t\t}\n\t}\n}","line":{"from":191,"to":207}} {"id":100010565,"name":"SetDefaults_NodeResourcesBalancedAllocationArgs","signature":"func SetDefaults_NodeResourcesBalancedAllocationArgs(obj *configv1.NodeResourcesBalancedAllocationArgs)","file":"pkg/scheduler/apis/config/v1/defaults.go","code":"func SetDefaults_NodeResourcesBalancedAllocationArgs(obj *configv1.NodeResourcesBalancedAllocationArgs) {\n\tif len(obj.Resources) == 0 {\n\t\tobj.Resources = defaultResourceSpec\n\t\treturn\n\t}\n\t// If the weight is not set or it is explicitly set to 0, then apply the default weight(1) instead.\n\tfor i := range obj.Resources {\n\t\tif obj.Resources[i].Weight == 0 {\n\t\t\tobj.Resources[i].Weight = 1\n\t\t}\n\t}\n}","line":{"from":209,"to":220}} {"id":100010566,"name":"SetDefaults_PodTopologySpreadArgs","signature":"func SetDefaults_PodTopologySpreadArgs(obj *configv1.PodTopologySpreadArgs)","file":"pkg/scheduler/apis/config/v1/defaults.go","code":"func SetDefaults_PodTopologySpreadArgs(obj *configv1.PodTopologySpreadArgs) {\n\tif obj.DefaultingType == \"\" {\n\t\tobj.DefaultingType = configv1.SystemDefaulting\n\t}\n}","line":{"from":222,"to":226}} {"id":100010567,"name":"SetDefaults_NodeResourcesFitArgs","signature":"func SetDefaults_NodeResourcesFitArgs(obj *configv1.NodeResourcesFitArgs)","file":"pkg/scheduler/apis/config/v1/defaults.go","code":"func SetDefaults_NodeResourcesFitArgs(obj *configv1.NodeResourcesFitArgs) {\n\tif obj.ScoringStrategy == nil {\n\t\tobj.ScoringStrategy = \u0026configv1.ScoringStrategy{\n\t\t\tType: configv1.ScoringStrategyType(config.LeastAllocated),\n\t\t\tResources: defaultResourceSpec,\n\t\t}\n\t}\n\tif len(obj.ScoringStrategy.Resources) == 0 {\n\t\t// If no resources specified, use the default set.\n\t\tobj.ScoringStrategy.Resources = append(obj.ScoringStrategy.Resources, defaultResourceSpec...)\n\t}\n\tfor i := range obj.ScoringStrategy.Resources {\n\t\tif obj.ScoringStrategy.Resources[i].Weight == 0 {\n\t\t\tobj.ScoringStrategy.Resources[i].Weight = 1\n\t\t}\n\t}\n}","line":{"from":228,"to":244}} {"id":100010568,"name":"init","signature":"func init()","file":"pkg/scheduler/apis/config/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":37,"to":42}} {"id":100010569,"name":"GetPluginArgConversionScheme","signature":"func GetPluginArgConversionScheme() *runtime.Scheme","file":"pkg/scheduler/apis/config/v1beta2/conversion.go","code":"func GetPluginArgConversionScheme() *runtime.Scheme {\n\tinitPluginArgConversionScheme.Do(func() {\n\t\t// set up the scheme used for plugin arg conversion\n\t\tpluginArgConversionScheme = runtime.NewScheme()\n\t\tutilruntime.Must(AddToScheme(pluginArgConversionScheme))\n\t\tutilruntime.Must(config.AddToScheme(pluginArgConversionScheme))\n\t})\n\treturn pluginArgConversionScheme\n}","line":{"from":38,"to":46}} {"id":100010570,"name":"Convert_v1beta2_KubeSchedulerConfiguration_To_config_KubeSchedulerConfiguration","signature":"func Convert_v1beta2_KubeSchedulerConfiguration_To_config_KubeSchedulerConfiguration(in *v1beta2.KubeSchedulerConfiguration, out *config.KubeSchedulerConfiguration, s conversion.Scope) error","file":"pkg/scheduler/apis/config/v1beta2/conversion.go","code":"func Convert_v1beta2_KubeSchedulerConfiguration_To_config_KubeSchedulerConfiguration(in *v1beta2.KubeSchedulerConfiguration, out *config.KubeSchedulerConfiguration, s conversion.Scope) error {\n\tif err := autoConvert_v1beta2_KubeSchedulerConfiguration_To_config_KubeSchedulerConfiguration(in, out, s); err != nil {\n\t\treturn err\n\t}\n\treturn convertToInternalPluginConfigArgs(out)\n}","line":{"from":48,"to":53}} {"id":100010571,"name":"convertToInternalPluginConfigArgs","signature":"func convertToInternalPluginConfigArgs(out *config.KubeSchedulerConfiguration) error","file":"pkg/scheduler/apis/config/v1beta2/conversion.go","code":"// convertToInternalPluginConfigArgs converts PluginConfig#Args into internal\n// types using a scheme, after applying defaults.\nfunc convertToInternalPluginConfigArgs(out *config.KubeSchedulerConfiguration) error {\n\tscheme := GetPluginArgConversionScheme()\n\tfor i := range out.Profiles {\n\t\tprof := \u0026out.Profiles[i]\n\t\tfor j := range prof.PluginConfig {\n\t\t\targs := prof.PluginConfig[j].Args\n\t\t\tif args == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif _, isUnknown := args.(*runtime.Unknown); isUnknown {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tinternalArgs, err := scheme.ConvertToVersion(args, config.SchemeGroupVersion)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"converting .Profiles[%d].PluginConfig[%d].Args into internal type: %w\", i, j, err)\n\t\t\t}\n\t\t\tprof.PluginConfig[j].Args = internalArgs\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":55,"to":77}} {"id":100010572,"name":"Convert_config_KubeSchedulerConfiguration_To_v1beta2_KubeSchedulerConfiguration","signature":"func Convert_config_KubeSchedulerConfiguration_To_v1beta2_KubeSchedulerConfiguration(in *config.KubeSchedulerConfiguration, out *v1beta2.KubeSchedulerConfiguration, s conversion.Scope) error","file":"pkg/scheduler/apis/config/v1beta2/conversion.go","code":"func Convert_config_KubeSchedulerConfiguration_To_v1beta2_KubeSchedulerConfiguration(in *config.KubeSchedulerConfiguration, out *v1beta2.KubeSchedulerConfiguration, s conversion.Scope) error {\n\tif err := autoConvert_config_KubeSchedulerConfiguration_To_v1beta2_KubeSchedulerConfiguration(in, out, s); err != nil {\n\t\treturn err\n\t}\n\treturn convertToExternalPluginConfigArgs(out)\n}","line":{"from":79,"to":84}} {"id":100010573,"name":"convertToExternalPluginConfigArgs","signature":"func convertToExternalPluginConfigArgs(out *v1beta2.KubeSchedulerConfiguration) error","file":"pkg/scheduler/apis/config/v1beta2/conversion.go","code":"// convertToExternalPluginConfigArgs converts PluginConfig#Args into\n// external (versioned) types using a scheme.\nfunc convertToExternalPluginConfigArgs(out *v1beta2.KubeSchedulerConfiguration) error {\n\tscheme := GetPluginArgConversionScheme()\n\tfor i := range out.Profiles {\n\t\tfor j := range out.Profiles[i].PluginConfig {\n\t\t\targs := out.Profiles[i].PluginConfig[j].Args\n\t\t\tif args.Object == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif _, isUnknown := args.Object.(*runtime.Unknown); isUnknown {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\texternalArgs, err := scheme.ConvertToVersion(args.Object, SchemeGroupVersion)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tout.Profiles[i].PluginConfig[j].Args.Object = externalArgs\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":86,"to":107}} {"id":100010574,"name":"Convert_config_KubeSchedulerProfile_To_v1beta2_KubeSchedulerProfile","signature":"func Convert_config_KubeSchedulerProfile_To_v1beta2_KubeSchedulerProfile(in *config.KubeSchedulerProfile, out *v1beta2.KubeSchedulerProfile, s conversion.Scope) error","file":"pkg/scheduler/apis/config/v1beta2/conversion.go","code":"// Convert_config_KubeSchedulerProfile_To_v1beta2_KubeSchedulerProfile uses auto coversion by\n// ignoring per profile PercentageOfNodesToScore.\nfunc Convert_config_KubeSchedulerProfile_To_v1beta2_KubeSchedulerProfile(in *config.KubeSchedulerProfile, out *v1beta2.KubeSchedulerProfile, s conversion.Scope) error {\n\treturn autoConvert_config_KubeSchedulerProfile_To_v1beta2_KubeSchedulerProfile(in, out, s)\n}","line":{"from":109,"to":113}} {"id":100010575,"name":"Convert_config_Plugins_To_v1beta2_Plugins","signature":"func Convert_config_Plugins_To_v1beta2_Plugins(in *config.Plugins, out *v1beta2.Plugins, s conversion.Scope) error","file":"pkg/scheduler/apis/config/v1beta2/conversion.go","code":"func Convert_config_Plugins_To_v1beta2_Plugins(in *config.Plugins, out *v1beta2.Plugins, s conversion.Scope) error {\n\treturn autoConvert_config_Plugins_To_v1beta2_Plugins(in, out, s)\n}","line":{"from":115,"to":117}} {"id":100010576,"name":"getDefaultPlugins","signature":"func getDefaultPlugins() *v1beta2.Plugins","file":"pkg/scheduler/apis/config/v1beta2/default_plugins.go","code":"// getDefaultPlugins returns the default set of plugins.\nfunc getDefaultPlugins() *v1beta2.Plugins {\n\tplugins := \u0026v1beta2.Plugins{\n\t\tQueueSort: v1beta2.PluginSet{\n\t\t\tEnabled: []v1beta2.Plugin{\n\t\t\t\t{Name: names.PrioritySort},\n\t\t\t},\n\t\t},\n\t\tPreFilter: v1beta2.PluginSet{\n\t\t\tEnabled: []v1beta2.Plugin{\n\t\t\t\t{Name: names.NodeResourcesFit},\n\t\t\t\t{Name: names.NodePorts},\n\t\t\t\t{Name: names.VolumeRestrictions},\n\t\t\t\t{Name: names.PodTopologySpread},\n\t\t\t\t{Name: names.InterPodAffinity},\n\t\t\t\t{Name: names.VolumeBinding},\n\t\t\t\t{Name: names.VolumeZone},\n\t\t\t\t{Name: names.NodeAffinity},\n\t\t\t},\n\t\t},\n\t\tFilter: v1beta2.PluginSet{\n\t\t\tEnabled: []v1beta2.Plugin{\n\t\t\t\t{Name: names.NodeUnschedulable},\n\t\t\t\t{Name: names.NodeName},\n\t\t\t\t{Name: names.TaintToleration},\n\t\t\t\t{Name: names.NodeAffinity},\n\t\t\t\t{Name: names.NodePorts},\n\t\t\t\t{Name: names.NodeResourcesFit},\n\t\t\t\t{Name: names.VolumeRestrictions},\n\t\t\t\t{Name: names.EBSLimits},\n\t\t\t\t{Name: names.GCEPDLimits},\n\t\t\t\t{Name: names.NodeVolumeLimits},\n\t\t\t\t{Name: names.AzureDiskLimits},\n\t\t\t\t{Name: names.VolumeBinding},\n\t\t\t\t{Name: names.VolumeZone},\n\t\t\t\t{Name: names.PodTopologySpread},\n\t\t\t\t{Name: names.InterPodAffinity},\n\t\t\t},\n\t\t},\n\t\tPostFilter: v1beta2.PluginSet{\n\t\t\tEnabled: []v1beta2.Plugin{\n\t\t\t\t{Name: names.DefaultPreemption},\n\t\t\t},\n\t\t},\n\t\tPreScore: v1beta2.PluginSet{\n\t\t\tEnabled: []v1beta2.Plugin{\n\t\t\t\t{Name: names.InterPodAffinity},\n\t\t\t\t{Name: names.PodTopologySpread},\n\t\t\t\t{Name: names.TaintToleration},\n\t\t\t\t{Name: names.NodeAffinity},\n\t\t\t\t{Name: names.NodeResourcesFit},\n\t\t\t\t{Name: names.NodeResourcesBalancedAllocation},\n\t\t\t},\n\t\t},\n\t\tScore: v1beta2.PluginSet{\n\t\t\tEnabled: []v1beta2.Plugin{\n\t\t\t\t{Name: names.NodeResourcesBalancedAllocation, Weight: pointer.Int32(1)},\n\t\t\t\t{Name: names.ImageLocality, Weight: pointer.Int32(1)},\n\t\t\t\t{Name: names.InterPodAffinity, Weight: pointer.Int32(1)},\n\t\t\t\t{Name: names.NodeResourcesFit, Weight: pointer.Int32(1)},\n\t\t\t\t{Name: names.NodeAffinity, Weight: pointer.Int32(1)},\n\t\t\t\t// Weight is doubled because:\n\t\t\t\t// - This is a score coming from user preference.\n\t\t\t\t// - It makes its signal comparable to NodeResourcesFit.LeastAllocated.\n\t\t\t\t{Name: names.PodTopologySpread, Weight: pointer.Int32(2)},\n\t\t\t\t{Name: names.TaintToleration, Weight: pointer.Int32(1)},\n\t\t\t},\n\t\t},\n\t\tReserve: v1beta2.PluginSet{\n\t\t\tEnabled: []v1beta2.Plugin{\n\t\t\t\t{Name: names.VolumeBinding},\n\t\t\t},\n\t\t},\n\t\tPreBind: v1beta2.PluginSet{\n\t\t\tEnabled: []v1beta2.Plugin{\n\t\t\t\t{Name: names.VolumeBinding},\n\t\t\t},\n\t\t},\n\t\tBind: v1beta2.PluginSet{\n\t\t\tEnabled: []v1beta2.Plugin{\n\t\t\t\t{Name: names.DefaultBinder},\n\t\t\t},\n\t\t},\n\t}\n\tapplyFeatureGates(plugins)\n\n\treturn plugins\n}","line":{"from":29,"to":116}} {"id":100010577,"name":"applyFeatureGates","signature":"func applyFeatureGates(config *v1beta2.Plugins)","file":"pkg/scheduler/apis/config/v1beta2/default_plugins.go","code":"func applyFeatureGates(config *v1beta2.Plugins) {\n\tif utilfeature.DefaultFeatureGate.Enabled(features.VolumeCapacityPriority) {\n\t\tconfig.Score.Enabled = append(config.Score.Enabled, v1beta2.Plugin{Name: names.VolumeBinding, Weight: pointer.Int32(1)})\n\t}\n\tif utilfeature.DefaultFeatureGate.Enabled(features.PodSchedulingReadiness) {\n\t\tconfig.PreEnqueue.Enabled = append(config.PreEnqueue.Enabled, v1beta2.Plugin{Name: names.SchedulingGates})\n\t}\n}","line":{"from":118,"to":125}} {"id":100010578,"name":"mergePlugins","signature":"func mergePlugins(defaultPlugins, customPlugins *v1beta2.Plugins) *v1beta2.Plugins","file":"pkg/scheduler/apis/config/v1beta2/default_plugins.go","code":"// mergePlugins merges the custom set into the given default one, handling disabled sets.\nfunc mergePlugins(defaultPlugins, customPlugins *v1beta2.Plugins) *v1beta2.Plugins {\n\tif customPlugins == nil {\n\t\treturn defaultPlugins\n\t}\n\n\tdefaultPlugins.QueueSort = mergePluginSet(defaultPlugins.QueueSort, customPlugins.QueueSort)\n\tdefaultPlugins.PreFilter = mergePluginSet(defaultPlugins.PreFilter, customPlugins.PreFilter)\n\tdefaultPlugins.Filter = mergePluginSet(defaultPlugins.Filter, customPlugins.Filter)\n\tdefaultPlugins.PostFilter = mergePluginSet(defaultPlugins.PostFilter, customPlugins.PostFilter)\n\tdefaultPlugins.PreScore = mergePluginSet(defaultPlugins.PreScore, customPlugins.PreScore)\n\tdefaultPlugins.Score = mergePluginSet(defaultPlugins.Score, customPlugins.Score)\n\tdefaultPlugins.Reserve = mergePluginSet(defaultPlugins.Reserve, customPlugins.Reserve)\n\tdefaultPlugins.Permit = mergePluginSet(defaultPlugins.Permit, customPlugins.Permit)\n\tdefaultPlugins.PreBind = mergePluginSet(defaultPlugins.PreBind, customPlugins.PreBind)\n\tdefaultPlugins.Bind = mergePluginSet(defaultPlugins.Bind, customPlugins.Bind)\n\tdefaultPlugins.PostBind = mergePluginSet(defaultPlugins.PostBind, customPlugins.PostBind)\n\treturn defaultPlugins\n}","line":{"from":127,"to":145}} {"id":100010579,"name":"mergePluginSet","signature":"func mergePluginSet(defaultPluginSet, customPluginSet v1beta2.PluginSet) v1beta2.PluginSet","file":"pkg/scheduler/apis/config/v1beta2/default_plugins.go","code":"func mergePluginSet(defaultPluginSet, customPluginSet v1beta2.PluginSet) v1beta2.PluginSet {\n\tdisabledPlugins := sets.NewString()\n\tenabledCustomPlugins := make(map[string]pluginIndex)\n\t// replacedPluginIndex is a set of index of plugins, which have replaced the default plugins.\n\treplacedPluginIndex := sets.NewInt()\n\tfor _, disabledPlugin := range customPluginSet.Disabled {\n\t\tdisabledPlugins.Insert(disabledPlugin.Name)\n\t}\n\tfor index, enabledPlugin := range customPluginSet.Enabled {\n\t\tenabledCustomPlugins[enabledPlugin.Name] = pluginIndex{index, enabledPlugin}\n\t}\n\tvar enabledPlugins []v1beta2.Plugin\n\tif !disabledPlugins.Has(\"*\") {\n\t\tfor _, defaultEnabledPlugin := range defaultPluginSet.Enabled {\n\t\t\tif disabledPlugins.Has(defaultEnabledPlugin.Name) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// The default plugin is explicitly re-configured, update the default plugin accordingly.\n\t\t\tif customPlugin, ok := enabledCustomPlugins[defaultEnabledPlugin.Name]; ok {\n\t\t\t\tklog.InfoS(\"Default plugin is explicitly re-configured; overriding\", \"plugin\", defaultEnabledPlugin.Name)\n\t\t\t\t// Update the default plugin in place to preserve order.\n\t\t\t\tdefaultEnabledPlugin = customPlugin.plugin\n\t\t\t\treplacedPluginIndex.Insert(customPlugin.index)\n\t\t\t}\n\t\t\tenabledPlugins = append(enabledPlugins, defaultEnabledPlugin)\n\t\t}\n\t}\n\n\t// Append all the custom plugins which haven't replaced any default plugins.\n\t// Note: duplicated custom plugins will still be appended here.\n\t// If so, the instantiation of scheduler framework will detect it and abort.\n\tfor index, plugin := range customPluginSet.Enabled {\n\t\tif !replacedPluginIndex.Has(index) {\n\t\t\tenabledPlugins = append(enabledPlugins, plugin)\n\t\t}\n\t}\n\treturn v1beta2.PluginSet{Enabled: enabledPlugins}\n}","line":{"from":152,"to":189}} {"id":100010580,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/scheduler/apis/config/v1beta2/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":36,"to":38}} {"id":100010581,"name":"pluginsNames","signature":"func pluginsNames(p *v1beta2.Plugins) []string","file":"pkg/scheduler/apis/config/v1beta2/defaults.go","code":"func pluginsNames(p *v1beta2.Plugins) []string {\n\tif p == nil {\n\t\treturn nil\n\t}\n\textensions := []v1beta2.PluginSet{\n\t\tp.PreFilter,\n\t\tp.Filter,\n\t\tp.PostFilter,\n\t\tp.Reserve,\n\t\tp.PreScore,\n\t\tp.Score,\n\t\tp.PreBind,\n\t\tp.Bind,\n\t\tp.PostBind,\n\t\tp.Permit,\n\t\tp.QueueSort,\n\t}\n\tn := sets.NewString()\n\tfor _, e := range extensions {\n\t\tfor _, pg := range e.Enabled {\n\t\t\tn.Insert(pg.Name)\n\t\t}\n\t}\n\treturn n.List()\n}","line":{"from":40,"to":64}} {"id":100010582,"name":"setDefaults_KubeSchedulerProfile","signature":"func setDefaults_KubeSchedulerProfile(prof *v1beta2.KubeSchedulerProfile)","file":"pkg/scheduler/apis/config/v1beta2/defaults.go","code":"func setDefaults_KubeSchedulerProfile(prof *v1beta2.KubeSchedulerProfile) {\n\t// Set default plugins.\n\tprof.Plugins = mergePlugins(getDefaultPlugins(), prof.Plugins)\n\n\t// Set default plugin configs.\n\tscheme := GetPluginArgConversionScheme()\n\texistingConfigs := sets.NewString()\n\tfor j := range prof.PluginConfig {\n\t\texistingConfigs.Insert(prof.PluginConfig[j].Name)\n\t\targs := prof.PluginConfig[j].Args.Object\n\t\tif _, isUnknown := args.(*runtime.Unknown); isUnknown {\n\t\t\tcontinue\n\t\t}\n\t\tscheme.Default(args)\n\t}\n\n\t// Append default configs for plugins that didn't have one explicitly set.\n\tfor _, name := range pluginsNames(prof.Plugins) {\n\t\tif existingConfigs.Has(name) {\n\t\t\tcontinue\n\t\t}\n\t\tgvk := v1beta2.SchemeGroupVersion.WithKind(name + \"Args\")\n\t\targs, err := scheme.New(gvk)\n\t\tif err != nil {\n\t\t\t// This plugin is out-of-tree or doesn't require configuration.\n\t\t\tcontinue\n\t\t}\n\t\tscheme.Default(args)\n\t\targs.GetObjectKind().SetGroupVersionKind(gvk)\n\t\tprof.PluginConfig = append(prof.PluginConfig, v1beta2.PluginConfig{\n\t\t\tName: name,\n\t\t\tArgs: runtime.RawExtension{Object: args},\n\t\t})\n\t}\n}","line":{"from":66,"to":100}} {"id":100010583,"name":"SetDefaults_KubeSchedulerConfiguration","signature":"func SetDefaults_KubeSchedulerConfiguration(obj *v1beta2.KubeSchedulerConfiguration)","file":"pkg/scheduler/apis/config/v1beta2/defaults.go","code":"// SetDefaults_KubeSchedulerConfiguration sets additional defaults\nfunc SetDefaults_KubeSchedulerConfiguration(obj *v1beta2.KubeSchedulerConfiguration) {\n\tif obj.Parallelism == nil {\n\t\tobj.Parallelism = pointer.Int32(16)\n\t}\n\n\tif len(obj.Profiles) == 0 {\n\t\tobj.Profiles = append(obj.Profiles, v1beta2.KubeSchedulerProfile{})\n\t}\n\t// Only apply a default scheduler name when there is a single profile.\n\t// Validation will ensure that every profile has a non-empty unique name.\n\tif len(obj.Profiles) == 1 \u0026\u0026 obj.Profiles[0].SchedulerName == nil {\n\t\tobj.Profiles[0].SchedulerName = pointer.String(v1.DefaultSchedulerName)\n\t}\n\n\t// Add the default set of plugins and apply the configuration.\n\tfor i := range obj.Profiles {\n\t\tprof := \u0026obj.Profiles[i]\n\t\tsetDefaults_KubeSchedulerProfile(prof)\n\t}\n\n\tif obj.PercentageOfNodesToScore == nil {\n\t\tobj.PercentageOfNodesToScore = pointer.Int32(config.DefaultPercentageOfNodesToScore)\n\t}\n\n\tif len(obj.LeaderElection.ResourceLock) == 0 {\n\t\t// Use lease-based leader election to reduce cost.\n\t\t// We migrated for EndpointsLease lock in 1.17 and starting in 1.20 we\n\t\t// migrated to Lease lock.\n\t\tobj.LeaderElection.ResourceLock = \"leases\"\n\t}\n\tif len(obj.LeaderElection.ResourceNamespace) == 0 {\n\t\tobj.LeaderElection.ResourceNamespace = v1beta2.SchedulerDefaultLockObjectNamespace\n\t}\n\tif len(obj.LeaderElection.ResourceName) == 0 {\n\t\tobj.LeaderElection.ResourceName = v1beta2.SchedulerDefaultLockObjectName\n\t}\n\n\tif len(obj.ClientConnection.ContentType) == 0 {\n\t\tobj.ClientConnection.ContentType = \"application/vnd.kubernetes.protobuf\"\n\t}\n\t// Scheduler has an opinion about QPS/Burst, setting specific defaults for itself, instead of generic settings.\n\tif obj.ClientConnection.QPS == 0.0 {\n\t\tobj.ClientConnection.QPS = 50.0\n\t}\n\tif obj.ClientConnection.Burst == 0 {\n\t\tobj.ClientConnection.Burst = 100\n\t}\n\n\t// Use the default LeaderElectionConfiguration options\n\tcomponentbaseconfigv1alpha1.RecommendedDefaultLeaderElectionConfiguration(\u0026obj.LeaderElection)\n\n\tif obj.PodInitialBackoffSeconds == nil {\n\t\tobj.PodInitialBackoffSeconds = pointer.Int64(1)\n\t}\n\n\tif obj.PodMaxBackoffSeconds == nil {\n\t\tobj.PodMaxBackoffSeconds = pointer.Int64(10)\n\t}\n\n\t// Enable profiling by default in the scheduler\n\tif obj.EnableProfiling == nil {\n\t\tobj.EnableProfiling = pointer.Bool(true)\n\t}\n\n\t// Enable contention profiling by default if profiling is enabled\n\tif *obj.EnableProfiling \u0026\u0026 obj.EnableContentionProfiling == nil {\n\t\tobj.EnableContentionProfiling = pointer.Bool(true)\n\t}\n}","line":{"from":102,"to":171}} {"id":100010584,"name":"SetDefaults_DefaultPreemptionArgs","signature":"func SetDefaults_DefaultPreemptionArgs(obj *v1beta2.DefaultPreemptionArgs)","file":"pkg/scheduler/apis/config/v1beta2/defaults.go","code":"func SetDefaults_DefaultPreemptionArgs(obj *v1beta2.DefaultPreemptionArgs) {\n\tif obj.MinCandidateNodesPercentage == nil {\n\t\tobj.MinCandidateNodesPercentage = pointer.Int32(10)\n\t}\n\tif obj.MinCandidateNodesAbsolute == nil {\n\t\tobj.MinCandidateNodesAbsolute = pointer.Int32(100)\n\t}\n}","line":{"from":173,"to":180}} {"id":100010585,"name":"SetDefaults_InterPodAffinityArgs","signature":"func SetDefaults_InterPodAffinityArgs(obj *v1beta2.InterPodAffinityArgs)","file":"pkg/scheduler/apis/config/v1beta2/defaults.go","code":"func SetDefaults_InterPodAffinityArgs(obj *v1beta2.InterPodAffinityArgs) {\n\tif obj.HardPodAffinityWeight == nil {\n\t\tobj.HardPodAffinityWeight = pointer.Int32(1)\n\t}\n}","line":{"from":182,"to":186}} {"id":100010586,"name":"SetDefaults_VolumeBindingArgs","signature":"func SetDefaults_VolumeBindingArgs(obj *v1beta2.VolumeBindingArgs)","file":"pkg/scheduler/apis/config/v1beta2/defaults.go","code":"func SetDefaults_VolumeBindingArgs(obj *v1beta2.VolumeBindingArgs) {\n\tif obj.BindTimeoutSeconds == nil {\n\t\tobj.BindTimeoutSeconds = pointer.Int64(600)\n\t}\n\tif len(obj.Shape) == 0 \u0026\u0026 feature.DefaultFeatureGate.Enabled(features.VolumeCapacityPriority) {\n\t\tobj.Shape = []v1beta2.UtilizationShapePoint{\n\t\t\t{\n\t\t\t\tUtilization: 0,\n\t\t\t\tScore: 0,\n\t\t\t},\n\t\t\t{\n\t\t\t\tUtilization: 100,\n\t\t\t\tScore: int32(config.MaxCustomPriorityScore),\n\t\t\t},\n\t\t}\n\t}\n}","line":{"from":188,"to":204}} {"id":100010587,"name":"SetDefaults_NodeResourcesBalancedAllocationArgs","signature":"func SetDefaults_NodeResourcesBalancedAllocationArgs(obj *v1beta2.NodeResourcesBalancedAllocationArgs)","file":"pkg/scheduler/apis/config/v1beta2/defaults.go","code":"func SetDefaults_NodeResourcesBalancedAllocationArgs(obj *v1beta2.NodeResourcesBalancedAllocationArgs) {\n\tif len(obj.Resources) == 0 {\n\t\tobj.Resources = defaultResourceSpec\n\t\treturn\n\t}\n\t// If the weight is not set or it is explicitly set to 0, then apply the default weight(1) instead.\n\tfor i := range obj.Resources {\n\t\tif obj.Resources[i].Weight == 0 {\n\t\t\tobj.Resources[i].Weight = 1\n\t\t}\n\t}\n}","line":{"from":206,"to":217}} {"id":100010588,"name":"SetDefaults_PodTopologySpreadArgs","signature":"func SetDefaults_PodTopologySpreadArgs(obj *v1beta2.PodTopologySpreadArgs)","file":"pkg/scheduler/apis/config/v1beta2/defaults.go","code":"func SetDefaults_PodTopologySpreadArgs(obj *v1beta2.PodTopologySpreadArgs) {\n\tif obj.DefaultingType == \"\" {\n\t\tobj.DefaultingType = v1beta2.SystemDefaulting\n\t}\n}","line":{"from":219,"to":223}} {"id":100010589,"name":"SetDefaults_NodeResourcesFitArgs","signature":"func SetDefaults_NodeResourcesFitArgs(obj *v1beta2.NodeResourcesFitArgs)","file":"pkg/scheduler/apis/config/v1beta2/defaults.go","code":"func SetDefaults_NodeResourcesFitArgs(obj *v1beta2.NodeResourcesFitArgs) {\n\tif obj.ScoringStrategy == nil {\n\t\tobj.ScoringStrategy = \u0026v1beta2.ScoringStrategy{\n\t\t\tType: v1beta2.ScoringStrategyType(config.LeastAllocated),\n\t\t\tResources: defaultResourceSpec,\n\t\t}\n\t}\n\tif len(obj.ScoringStrategy.Resources) == 0 {\n\t\t// If no resources specified, use the default set.\n\t\tobj.ScoringStrategy.Resources = append(obj.ScoringStrategy.Resources, defaultResourceSpec...)\n\t}\n\tfor i := range obj.ScoringStrategy.Resources {\n\t\tif obj.ScoringStrategy.Resources[i].Weight == 0 {\n\t\t\tobj.ScoringStrategy.Resources[i].Weight = 1\n\t\t}\n\t}\n}","line":{"from":225,"to":241}} {"id":100010590,"name":"init","signature":"func init()","file":"pkg/scheduler/apis/config/v1beta2/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":37,"to":42}} {"id":100010591,"name":"GetPluginArgConversionScheme","signature":"func GetPluginArgConversionScheme() *runtime.Scheme","file":"pkg/scheduler/apis/config/v1beta3/conversion.go","code":"func GetPluginArgConversionScheme() *runtime.Scheme {\n\tinitPluginArgConversionScheme.Do(func() {\n\t\t// set up the scheme used for plugin arg conversion\n\t\tpluginArgConversionScheme = runtime.NewScheme()\n\t\tutilruntime.Must(AddToScheme(pluginArgConversionScheme))\n\t\tutilruntime.Must(config.AddToScheme(pluginArgConversionScheme))\n\t})\n\treturn pluginArgConversionScheme\n}","line":{"from":38,"to":46}} {"id":100010592,"name":"Convert_v1beta3_KubeSchedulerConfiguration_To_config_KubeSchedulerConfiguration","signature":"func Convert_v1beta3_KubeSchedulerConfiguration_To_config_KubeSchedulerConfiguration(in *v1beta3.KubeSchedulerConfiguration, out *config.KubeSchedulerConfiguration, s conversion.Scope) error","file":"pkg/scheduler/apis/config/v1beta3/conversion.go","code":"func Convert_v1beta3_KubeSchedulerConfiguration_To_config_KubeSchedulerConfiguration(in *v1beta3.KubeSchedulerConfiguration, out *config.KubeSchedulerConfiguration, s conversion.Scope) error {\n\tif err := autoConvert_v1beta3_KubeSchedulerConfiguration_To_config_KubeSchedulerConfiguration(in, out, s); err != nil {\n\t\treturn err\n\t}\n\treturn convertToInternalPluginConfigArgs(out)\n}","line":{"from":48,"to":53}} {"id":100010593,"name":"convertToInternalPluginConfigArgs","signature":"func convertToInternalPluginConfigArgs(out *config.KubeSchedulerConfiguration) error","file":"pkg/scheduler/apis/config/v1beta3/conversion.go","code":"// convertToInternalPluginConfigArgs converts PluginConfig#Args into internal\n// types using a scheme, after applying defaults.\nfunc convertToInternalPluginConfigArgs(out *config.KubeSchedulerConfiguration) error {\n\tscheme := GetPluginArgConversionScheme()\n\tfor i := range out.Profiles {\n\t\tprof := \u0026out.Profiles[i]\n\t\tfor j := range prof.PluginConfig {\n\t\t\targs := prof.PluginConfig[j].Args\n\t\t\tif args == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif _, isUnknown := args.(*runtime.Unknown); isUnknown {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tinternalArgs, err := scheme.ConvertToVersion(args, config.SchemeGroupVersion)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"converting .Profiles[%d].PluginConfig[%d].Args into internal type: %w\", i, j, err)\n\t\t\t}\n\t\t\tprof.PluginConfig[j].Args = internalArgs\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":55,"to":77}} {"id":100010594,"name":"Convert_config_KubeSchedulerConfiguration_To_v1beta3_KubeSchedulerConfiguration","signature":"func Convert_config_KubeSchedulerConfiguration_To_v1beta3_KubeSchedulerConfiguration(in *config.KubeSchedulerConfiguration, out *v1beta3.KubeSchedulerConfiguration, s conversion.Scope) error","file":"pkg/scheduler/apis/config/v1beta3/conversion.go","code":"func Convert_config_KubeSchedulerConfiguration_To_v1beta3_KubeSchedulerConfiguration(in *config.KubeSchedulerConfiguration, out *v1beta3.KubeSchedulerConfiguration, s conversion.Scope) error {\n\tif err := autoConvert_config_KubeSchedulerConfiguration_To_v1beta3_KubeSchedulerConfiguration(in, out, s); err != nil {\n\t\treturn err\n\t}\n\treturn convertToExternalPluginConfigArgs(out)\n}","line":{"from":79,"to":84}} {"id":100010595,"name":"convertToExternalPluginConfigArgs","signature":"func convertToExternalPluginConfigArgs(out *v1beta3.KubeSchedulerConfiguration) error","file":"pkg/scheduler/apis/config/v1beta3/conversion.go","code":"// convertToExternalPluginConfigArgs converts PluginConfig#Args into\n// external (versioned) types using a scheme.\nfunc convertToExternalPluginConfigArgs(out *v1beta3.KubeSchedulerConfiguration) error {\n\tscheme := GetPluginArgConversionScheme()\n\tfor i := range out.Profiles {\n\t\tfor j := range out.Profiles[i].PluginConfig {\n\t\t\targs := out.Profiles[i].PluginConfig[j].Args\n\t\t\tif args.Object == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif _, isUnknown := args.Object.(*runtime.Unknown); isUnknown {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\texternalArgs, err := scheme.ConvertToVersion(args.Object, SchemeGroupVersion)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tout.Profiles[i].PluginConfig[j].Args.Object = externalArgs\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":86,"to":107}} {"id":100010596,"name":"Convert_config_KubeSchedulerProfile_To_v1beta3_KubeSchedulerProfile","signature":"func Convert_config_KubeSchedulerProfile_To_v1beta3_KubeSchedulerProfile(in *config.KubeSchedulerProfile, out *v1beta3.KubeSchedulerProfile, s conversion.Scope) error","file":"pkg/scheduler/apis/config/v1beta3/conversion.go","code":"// Convert_config_KubeSchedulerProfile_To_v1beta3_KubeSchedulerProfile called auto coversion by\n// ignoring per profile PercentageOfNodesToScore.\nfunc Convert_config_KubeSchedulerProfile_To_v1beta3_KubeSchedulerProfile(in *config.KubeSchedulerProfile, out *v1beta3.KubeSchedulerProfile, s conversion.Scope) error {\n\treturn autoConvert_config_KubeSchedulerProfile_To_v1beta3_KubeSchedulerProfile(in, out, s)\n}","line":{"from":109,"to":113}} {"id":100010597,"name":"Convert_config_Plugins_To_v1beta3_Plugins","signature":"func Convert_config_Plugins_To_v1beta3_Plugins(in *config.Plugins, out *v1beta3.Plugins, s conversion.Scope) error","file":"pkg/scheduler/apis/config/v1beta3/conversion.go","code":"// Convert_config_Plugins_To_v1beta3_Plugins is an autogenerated conversion function.\nfunc Convert_config_Plugins_To_v1beta3_Plugins(in *config.Plugins, out *v1beta3.Plugins, s conversion.Scope) error {\n\treturn autoConvert_config_Plugins_To_v1beta3_Plugins(in, out, s)\n}","line":{"from":115,"to":118}} {"id":100010598,"name":"getDefaultPlugins","signature":"func getDefaultPlugins() *v1beta3.Plugins","file":"pkg/scheduler/apis/config/v1beta3/default_plugins.go","code":"// getDefaultPlugins returns the default set of plugins.\nfunc getDefaultPlugins() *v1beta3.Plugins {\n\tplugins := \u0026v1beta3.Plugins{\n\t\tMultiPoint: v1beta3.PluginSet{\n\t\t\tEnabled: []v1beta3.Plugin{\n\t\t\t\t{Name: names.PrioritySort},\n\t\t\t\t{Name: names.NodeUnschedulable},\n\t\t\t\t{Name: names.NodeName},\n\t\t\t\t{Name: names.TaintToleration, Weight: pointer.Int32(3)},\n\t\t\t\t{Name: names.NodeAffinity, Weight: pointer.Int32(2)},\n\t\t\t\t{Name: names.NodePorts},\n\t\t\t\t{Name: names.NodeResourcesFit, Weight: pointer.Int32(1)},\n\t\t\t\t{Name: names.VolumeRestrictions},\n\t\t\t\t{Name: names.EBSLimits},\n\t\t\t\t{Name: names.GCEPDLimits},\n\t\t\t\t{Name: names.NodeVolumeLimits},\n\t\t\t\t{Name: names.AzureDiskLimits},\n\t\t\t\t{Name: names.VolumeBinding},\n\t\t\t\t{Name: names.VolumeZone},\n\t\t\t\t{Name: names.PodTopologySpread, Weight: pointer.Int32(2)},\n\t\t\t\t{Name: names.InterPodAffinity, Weight: pointer.Int32(2)},\n\t\t\t\t{Name: names.DefaultPreemption},\n\t\t\t\t{Name: names.NodeResourcesBalancedAllocation, Weight: pointer.Int32(1)},\n\t\t\t\t{Name: names.ImageLocality, Weight: pointer.Int32(1)},\n\t\t\t\t{Name: names.DefaultBinder},\n\t\t\t},\n\t\t},\n\t}\n\tapplyFeatureGates(plugins)\n\n\treturn plugins\n}","line":{"from":29,"to":60}} {"id":100010599,"name":"applyFeatureGates","signature":"func applyFeatureGates(config *v1beta3.Plugins)","file":"pkg/scheduler/apis/config/v1beta3/default_plugins.go","code":"func applyFeatureGates(config *v1beta3.Plugins) {\n\tif utilfeature.DefaultFeatureGate.Enabled(features.PodSchedulingReadiness) {\n\t\tconfig.MultiPoint.Enabled = append(config.MultiPoint.Enabled, v1beta3.Plugin{Name: names.SchedulingGates})\n\t}\n}","line":{"from":62,"to":66}} {"id":100010600,"name":"mergePlugins","signature":"func mergePlugins(defaultPlugins, customPlugins *v1beta3.Plugins) *v1beta3.Plugins","file":"pkg/scheduler/apis/config/v1beta3/default_plugins.go","code":"// mergePlugins merges the custom set into the given default one, handling disabled sets.\nfunc mergePlugins(defaultPlugins, customPlugins *v1beta3.Plugins) *v1beta3.Plugins {\n\tif customPlugins == nil {\n\t\treturn defaultPlugins\n\t}\n\n\tdefaultPlugins.MultiPoint = mergePluginSet(defaultPlugins.MultiPoint, customPlugins.MultiPoint)\n\tdefaultPlugins.QueueSort = mergePluginSet(defaultPlugins.QueueSort, customPlugins.QueueSort)\n\tdefaultPlugins.PreFilter = mergePluginSet(defaultPlugins.PreFilter, customPlugins.PreFilter)\n\tdefaultPlugins.Filter = mergePluginSet(defaultPlugins.Filter, customPlugins.Filter)\n\tdefaultPlugins.PostFilter = mergePluginSet(defaultPlugins.PostFilter, customPlugins.PostFilter)\n\tdefaultPlugins.PreScore = mergePluginSet(defaultPlugins.PreScore, customPlugins.PreScore)\n\tdefaultPlugins.Score = mergePluginSet(defaultPlugins.Score, customPlugins.Score)\n\tdefaultPlugins.Reserve = mergePluginSet(defaultPlugins.Reserve, customPlugins.Reserve)\n\tdefaultPlugins.Permit = mergePluginSet(defaultPlugins.Permit, customPlugins.Permit)\n\tdefaultPlugins.PreBind = mergePluginSet(defaultPlugins.PreBind, customPlugins.PreBind)\n\tdefaultPlugins.Bind = mergePluginSet(defaultPlugins.Bind, customPlugins.Bind)\n\tdefaultPlugins.PostBind = mergePluginSet(defaultPlugins.PostBind, customPlugins.PostBind)\n\treturn defaultPlugins\n}","line":{"from":68,"to":87}} {"id":100010601,"name":"mergePluginSet","signature":"func mergePluginSet(defaultPluginSet, customPluginSet v1beta3.PluginSet) v1beta3.PluginSet","file":"pkg/scheduler/apis/config/v1beta3/default_plugins.go","code":"func mergePluginSet(defaultPluginSet, customPluginSet v1beta3.PluginSet) v1beta3.PluginSet {\n\tdisabledPlugins := sets.NewString()\n\tenabledCustomPlugins := make(map[string]pluginIndex)\n\t// replacedPluginIndex is a set of index of plugins, which have replaced the default plugins.\n\treplacedPluginIndex := sets.NewInt()\n\tvar disabled []v1beta3.Plugin\n\tfor _, disabledPlugin := range customPluginSet.Disabled {\n\t\t// if the user is manually disabling any (or all, with \"*\") default plugins for an extension point,\n\t\t// we need to track that so that the MultiPoint extension logic in the framework can know to skip\n\t\t// inserting unspecified default plugins to this point.\n\t\tdisabled = append(disabled, v1beta3.Plugin{Name: disabledPlugin.Name})\n\t\tdisabledPlugins.Insert(disabledPlugin.Name)\n\t}\n\n\t// With MultiPoint, we may now have some disabledPlugins in the default registry\n\t// For example, we enable PluginX with Filter+Score through MultiPoint but disable its Score plugin by default.\n\tfor _, disabledPlugin := range defaultPluginSet.Disabled {\n\t\tdisabled = append(disabled, v1beta3.Plugin{Name: disabledPlugin.Name})\n\t\tdisabledPlugins.Insert(disabledPlugin.Name)\n\t}\n\n\tfor index, enabledPlugin := range customPluginSet.Enabled {\n\t\tenabledCustomPlugins[enabledPlugin.Name] = pluginIndex{index, enabledPlugin}\n\t}\n\tvar enabledPlugins []v1beta3.Plugin\n\tif !disabledPlugins.Has(\"*\") {\n\t\tfor _, defaultEnabledPlugin := range defaultPluginSet.Enabled {\n\t\t\tif disabledPlugins.Has(defaultEnabledPlugin.Name) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// The default plugin is explicitly re-configured, update the default plugin accordingly.\n\t\t\tif customPlugin, ok := enabledCustomPlugins[defaultEnabledPlugin.Name]; ok {\n\t\t\t\tklog.InfoS(\"Default plugin is explicitly re-configured; overriding\", \"plugin\", defaultEnabledPlugin.Name)\n\t\t\t\t// Update the default plugin in place to preserve order.\n\t\t\t\tdefaultEnabledPlugin = customPlugin.plugin\n\t\t\t\treplacedPluginIndex.Insert(customPlugin.index)\n\t\t\t}\n\t\t\tenabledPlugins = append(enabledPlugins, defaultEnabledPlugin)\n\t\t}\n\t}\n\n\t// Append all the custom plugins which haven't replaced any default plugins.\n\t// Note: duplicated custom plugins will still be appended here.\n\t// If so, the instantiation of scheduler framework will detect it and abort.\n\tfor index, plugin := range customPluginSet.Enabled {\n\t\tif !replacedPluginIndex.Has(index) {\n\t\t\tenabledPlugins = append(enabledPlugins, plugin)\n\t\t}\n\t}\n\treturn v1beta3.PluginSet{Enabled: enabledPlugins, Disabled: disabled}\n}","line":{"from":94,"to":144}} {"id":100010602,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"pkg/scheduler/apis/config/v1beta3/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":36,"to":38}} {"id":100010603,"name":"pluginsNames","signature":"func pluginsNames(p *v1beta3.Plugins) []string","file":"pkg/scheduler/apis/config/v1beta3/defaults.go","code":"func pluginsNames(p *v1beta3.Plugins) []string {\n\tif p == nil {\n\t\treturn nil\n\t}\n\textensions := []v1beta3.PluginSet{\n\t\tp.MultiPoint,\n\t\tp.PreFilter,\n\t\tp.Filter,\n\t\tp.PostFilter,\n\t\tp.Reserve,\n\t\tp.PreScore,\n\t\tp.Score,\n\t\tp.PreBind,\n\t\tp.Bind,\n\t\tp.PostBind,\n\t\tp.Permit,\n\t\tp.QueueSort,\n\t}\n\tn := sets.NewString()\n\tfor _, e := range extensions {\n\t\tfor _, pg := range e.Enabled {\n\t\t\tn.Insert(pg.Name)\n\t\t}\n\t}\n\treturn n.List()\n}","line":{"from":40,"to":65}} {"id":100010604,"name":"setDefaults_KubeSchedulerProfile","signature":"func setDefaults_KubeSchedulerProfile(prof *v1beta3.KubeSchedulerProfile)","file":"pkg/scheduler/apis/config/v1beta3/defaults.go","code":"func setDefaults_KubeSchedulerProfile(prof *v1beta3.KubeSchedulerProfile) {\n\t// Set default plugins.\n\tprof.Plugins = mergePlugins(getDefaultPlugins(), prof.Plugins)\n\t// Set default plugin configs.\n\tscheme := GetPluginArgConversionScheme()\n\texistingConfigs := sets.NewString()\n\tfor j := range prof.PluginConfig {\n\t\texistingConfigs.Insert(prof.PluginConfig[j].Name)\n\t\targs := prof.PluginConfig[j].Args.Object\n\t\tif _, isUnknown := args.(*runtime.Unknown); isUnknown {\n\t\t\tcontinue\n\t\t}\n\t\tscheme.Default(args)\n\t}\n\n\t// Append default configs for plugins that didn't have one explicitly set.\n\tfor _, name := range pluginsNames(prof.Plugins) {\n\t\tif existingConfigs.Has(name) {\n\t\t\tcontinue\n\t\t}\n\t\tgvk := v1beta3.SchemeGroupVersion.WithKind(name + \"Args\")\n\t\targs, err := scheme.New(gvk)\n\t\tif err != nil {\n\t\t\t// This plugin is out-of-tree or doesn't require configuration.\n\t\t\tcontinue\n\t\t}\n\t\tscheme.Default(args)\n\t\targs.GetObjectKind().SetGroupVersionKind(gvk)\n\t\tprof.PluginConfig = append(prof.PluginConfig, v1beta3.PluginConfig{\n\t\t\tName: name,\n\t\t\tArgs: runtime.RawExtension{Object: args},\n\t\t})\n\t}\n}","line":{"from":67,"to":100}} {"id":100010605,"name":"SetDefaults_KubeSchedulerConfiguration","signature":"func SetDefaults_KubeSchedulerConfiguration(obj *v1beta3.KubeSchedulerConfiguration)","file":"pkg/scheduler/apis/config/v1beta3/defaults.go","code":"// SetDefaults_KubeSchedulerConfiguration sets additional defaults\nfunc SetDefaults_KubeSchedulerConfiguration(obj *v1beta3.KubeSchedulerConfiguration) {\n\tif obj.Parallelism == nil {\n\t\tobj.Parallelism = pointer.Int32(16)\n\t}\n\n\tif len(obj.Profiles) == 0 {\n\t\tobj.Profiles = append(obj.Profiles, v1beta3.KubeSchedulerProfile{})\n\t}\n\t// Only apply a default scheduler name when there is a single profile.\n\t// Validation will ensure that every profile has a non-empty unique name.\n\tif len(obj.Profiles) == 1 \u0026\u0026 obj.Profiles[0].SchedulerName == nil {\n\t\tobj.Profiles[0].SchedulerName = pointer.String(v1.DefaultSchedulerName)\n\t}\n\n\t// Add the default set of plugins and apply the configuration.\n\tfor i := range obj.Profiles {\n\t\tprof := \u0026obj.Profiles[i]\n\t\tsetDefaults_KubeSchedulerProfile(prof)\n\t}\n\n\tif obj.PercentageOfNodesToScore == nil {\n\t\tpercentageOfNodesToScore := int32(config.DefaultPercentageOfNodesToScore)\n\t\tobj.PercentageOfNodesToScore = \u0026percentageOfNodesToScore\n\t}\n\n\tif len(obj.LeaderElection.ResourceLock) == 0 {\n\t\t// Use lease-based leader election to reduce cost.\n\t\t// We migrated for EndpointsLease lock in 1.17 and starting in 1.20 we\n\t\t// migrated to Lease lock.\n\t\tobj.LeaderElection.ResourceLock = \"leases\"\n\t}\n\tif len(obj.LeaderElection.ResourceNamespace) == 0 {\n\t\tobj.LeaderElection.ResourceNamespace = v1beta3.SchedulerDefaultLockObjectNamespace\n\t}\n\tif len(obj.LeaderElection.ResourceName) == 0 {\n\t\tobj.LeaderElection.ResourceName = v1beta3.SchedulerDefaultLockObjectName\n\t}\n\n\tif len(obj.ClientConnection.ContentType) == 0 {\n\t\tobj.ClientConnection.ContentType = \"application/vnd.kubernetes.protobuf\"\n\t}\n\t// Scheduler has an opinion about QPS/Burst, setting specific defaults for itself, instead of generic settings.\n\tif obj.ClientConnection.QPS == 0.0 {\n\t\tobj.ClientConnection.QPS = 50.0\n\t}\n\tif obj.ClientConnection.Burst == 0 {\n\t\tobj.ClientConnection.Burst = 100\n\t}\n\n\t// Use the default LeaderElectionConfiguration options\n\tcomponentbaseconfigv1alpha1.RecommendedDefaultLeaderElectionConfiguration(\u0026obj.LeaderElection)\n\n\tif obj.PodInitialBackoffSeconds == nil {\n\t\tobj.PodInitialBackoffSeconds = pointer.Int64(1)\n\t}\n\n\tif obj.PodMaxBackoffSeconds == nil {\n\t\tobj.PodMaxBackoffSeconds = pointer.Int64(10)\n\t}\n\n\t// Enable profiling by default in the scheduler\n\tif obj.EnableProfiling == nil {\n\t\tobj.EnableProfiling = pointer.Bool(true)\n\t}\n\n\t// Enable contention profiling by default if profiling is enabled\n\tif *obj.EnableProfiling \u0026\u0026 obj.EnableContentionProfiling == nil {\n\t\tobj.EnableContentionProfiling = pointer.Bool(true)\n\t}\n}","line":{"from":102,"to":172}} {"id":100010606,"name":"SetDefaults_DefaultPreemptionArgs","signature":"func SetDefaults_DefaultPreemptionArgs(obj *v1beta3.DefaultPreemptionArgs)","file":"pkg/scheduler/apis/config/v1beta3/defaults.go","code":"func SetDefaults_DefaultPreemptionArgs(obj *v1beta3.DefaultPreemptionArgs) {\n\tif obj.MinCandidateNodesPercentage == nil {\n\t\tobj.MinCandidateNodesPercentage = pointer.Int32(10)\n\t}\n\tif obj.MinCandidateNodesAbsolute == nil {\n\t\tobj.MinCandidateNodesAbsolute = pointer.Int32(100)\n\t}\n}","line":{"from":174,"to":181}} {"id":100010607,"name":"SetDefaults_InterPodAffinityArgs","signature":"func SetDefaults_InterPodAffinityArgs(obj *v1beta3.InterPodAffinityArgs)","file":"pkg/scheduler/apis/config/v1beta3/defaults.go","code":"func SetDefaults_InterPodAffinityArgs(obj *v1beta3.InterPodAffinityArgs) {\n\tif obj.HardPodAffinityWeight == nil {\n\t\tobj.HardPodAffinityWeight = pointer.Int32(1)\n\t}\n}","line":{"from":183,"to":187}} {"id":100010608,"name":"SetDefaults_VolumeBindingArgs","signature":"func SetDefaults_VolumeBindingArgs(obj *v1beta3.VolumeBindingArgs)","file":"pkg/scheduler/apis/config/v1beta3/defaults.go","code":"func SetDefaults_VolumeBindingArgs(obj *v1beta3.VolumeBindingArgs) {\n\tif obj.BindTimeoutSeconds == nil {\n\t\tobj.BindTimeoutSeconds = pointer.Int64(600)\n\t}\n\tif len(obj.Shape) == 0 \u0026\u0026 feature.DefaultFeatureGate.Enabled(features.VolumeCapacityPriority) {\n\t\tobj.Shape = []v1beta3.UtilizationShapePoint{\n\t\t\t{\n\t\t\t\tUtilization: 0,\n\t\t\t\tScore: 0,\n\t\t\t},\n\t\t\t{\n\t\t\t\tUtilization: 100,\n\t\t\t\tScore: int32(config.MaxCustomPriorityScore),\n\t\t\t},\n\t\t}\n\t}\n}","line":{"from":189,"to":205}} {"id":100010609,"name":"SetDefaults_NodeResourcesBalancedAllocationArgs","signature":"func SetDefaults_NodeResourcesBalancedAllocationArgs(obj *v1beta3.NodeResourcesBalancedAllocationArgs)","file":"pkg/scheduler/apis/config/v1beta3/defaults.go","code":"func SetDefaults_NodeResourcesBalancedAllocationArgs(obj *v1beta3.NodeResourcesBalancedAllocationArgs) {\n\tif len(obj.Resources) == 0 {\n\t\tobj.Resources = defaultResourceSpec\n\t\treturn\n\t}\n\t// If the weight is not set or it is explicitly set to 0, then apply the default weight(1) instead.\n\tfor i := range obj.Resources {\n\t\tif obj.Resources[i].Weight == 0 {\n\t\t\tobj.Resources[i].Weight = 1\n\t\t}\n\t}\n}","line":{"from":207,"to":218}} {"id":100010610,"name":"SetDefaults_PodTopologySpreadArgs","signature":"func SetDefaults_PodTopologySpreadArgs(obj *v1beta3.PodTopologySpreadArgs)","file":"pkg/scheduler/apis/config/v1beta3/defaults.go","code":"func SetDefaults_PodTopologySpreadArgs(obj *v1beta3.PodTopologySpreadArgs) {\n\tif obj.DefaultingType == \"\" {\n\t\tobj.DefaultingType = v1beta3.SystemDefaulting\n\t}\n}","line":{"from":220,"to":224}} {"id":100010611,"name":"SetDefaults_NodeResourcesFitArgs","signature":"func SetDefaults_NodeResourcesFitArgs(obj *v1beta3.NodeResourcesFitArgs)","file":"pkg/scheduler/apis/config/v1beta3/defaults.go","code":"func SetDefaults_NodeResourcesFitArgs(obj *v1beta3.NodeResourcesFitArgs) {\n\tif obj.ScoringStrategy == nil {\n\t\tobj.ScoringStrategy = \u0026v1beta3.ScoringStrategy{\n\t\t\tType: v1beta3.ScoringStrategyType(config.LeastAllocated),\n\t\t\tResources: defaultResourceSpec,\n\t\t}\n\t}\n\tif len(obj.ScoringStrategy.Resources) == 0 {\n\t\t// If no resources specified, use the default set.\n\t\tobj.ScoringStrategy.Resources = append(obj.ScoringStrategy.Resources, defaultResourceSpec...)\n\t}\n\tfor i := range obj.ScoringStrategy.Resources {\n\t\tif obj.ScoringStrategy.Resources[i].Weight == 0 {\n\t\t\tobj.ScoringStrategy.Resources[i].Weight = 1\n\t\t}\n\t}\n}","line":{"from":226,"to":242}} {"id":100010612,"name":"init","signature":"func init()","file":"pkg/scheduler/apis/config/v1beta3/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":37,"to":42}} {"id":100010613,"name":"ValidateKubeSchedulerConfiguration","signature":"func ValidateKubeSchedulerConfiguration(cc *config.KubeSchedulerConfiguration) utilerrors.Aggregate","file":"pkg/scheduler/apis/config/validation/validation.go","code":"// ValidateKubeSchedulerConfiguration ensures validation of the KubeSchedulerConfiguration struct\nfunc ValidateKubeSchedulerConfiguration(cc *config.KubeSchedulerConfiguration) utilerrors.Aggregate {\n\tvar errs []error\n\terrs = append(errs, componentbasevalidation.ValidateClientConnectionConfiguration(\u0026cc.ClientConnection, field.NewPath(\"clientConnection\")).ToAggregate())\n\terrs = append(errs, componentbasevalidation.ValidateLeaderElectionConfiguration(\u0026cc.LeaderElection, field.NewPath(\"leaderElection\")).ToAggregate())\n\n\t// TODO: This can be removed when ResourceLock is not available\n\t// Only ResourceLock values with leases are allowed\n\tif cc.LeaderElection.LeaderElect \u0026\u0026 cc.LeaderElection.ResourceLock != \"leases\" {\n\t\tleaderElectionPath := field.NewPath(\"leaderElection\")\n\t\terrs = append(errs, field.Invalid(leaderElectionPath.Child(\"resourceLock\"), cc.LeaderElection.ResourceLock, `resourceLock value must be \"leases\"`))\n\t}\n\n\tprofilesPath := field.NewPath(\"profiles\")\n\tif cc.Parallelism \u003c= 0 {\n\t\terrs = append(errs, field.Invalid(field.NewPath(\"parallelism\"), cc.Parallelism, \"should be an integer value greater than zero\"))\n\t}\n\n\tif len(cc.Profiles) == 0 {\n\t\terrs = append(errs, field.Required(profilesPath, \"\"))\n\t} else {\n\t\texistingProfiles := make(map[string]int, len(cc.Profiles))\n\t\tfor i := range cc.Profiles {\n\t\t\tprofile := \u0026cc.Profiles[i]\n\t\t\tpath := profilesPath.Index(i)\n\t\t\terrs = append(errs, validateKubeSchedulerProfile(path, cc.APIVersion, profile)...)\n\t\t\tif idx, ok := existingProfiles[profile.SchedulerName]; ok {\n\t\t\t\terrs = append(errs, field.Duplicate(path.Child(\"schedulerName\"), profilesPath.Index(idx).Child(\"schedulerName\")))\n\t\t\t}\n\t\t\texistingProfiles[profile.SchedulerName] = i\n\t\t}\n\t\terrs = append(errs, validateCommonQueueSort(profilesPath, cc.Profiles)...)\n\t}\n\tif len(cc.HealthzBindAddress) \u003e 0 {\n\t\thost, port, err := splitHostIntPort(cc.HealthzBindAddress)\n\t\tif err != nil {\n\t\t\terrs = append(errs, field.Invalid(field.NewPath(\"healthzBindAddress\"), cc.HealthzBindAddress, err.Error()))\n\t\t} else {\n\t\t\tif errMsgs := validation.IsValidIP(host); errMsgs != nil {\n\t\t\t\terrs = append(errs, field.Invalid(field.NewPath(\"healthzBindAddress\"), cc.HealthzBindAddress, strings.Join(errMsgs, \",\")))\n\t\t\t}\n\t\t\tif port != 0 {\n\t\t\t\terrs = append(errs, field.Invalid(field.NewPath(\"healthzBindAddress\"), cc.HealthzBindAddress, \"must be empty or with an explicit 0 port\"))\n\t\t\t}\n\t\t}\n\t}\n\tif len(cc.MetricsBindAddress) \u003e 0 {\n\t\thost, port, err := splitHostIntPort(cc.MetricsBindAddress)\n\t\tif err != nil {\n\t\t\terrs = append(errs, field.Invalid(field.NewPath(\"metricsBindAddress\"), cc.MetricsBindAddress, err.Error()))\n\t\t} else {\n\t\t\tif errMsgs := validation.IsValidIP(host); errMsgs != nil {\n\t\t\t\terrs = append(errs, field.Invalid(field.NewPath(\"metricsBindAddress\"), cc.MetricsBindAddress, strings.Join(errMsgs, \",\")))\n\t\t\t}\n\t\t\tif port != 0 {\n\t\t\t\terrs = append(errs, field.Invalid(field.NewPath(\"metricsBindAddress\"), cc.MetricsBindAddress, \"must be empty or with an explicit 0 port\"))\n\t\t\t}\n\t\t}\n\t}\n\n\terrs = append(errs, validatePercentageOfNodesToScore(field.NewPath(\"percentageOfNodesToScore\"), cc.PercentageOfNodesToScore))\n\n\tif cc.PodInitialBackoffSeconds \u003c= 0 {\n\t\terrs = append(errs, field.Invalid(field.NewPath(\"podInitialBackoffSeconds\"),\n\t\t\tcc.PodInitialBackoffSeconds, \"must be greater than 0\"))\n\t}\n\tif cc.PodMaxBackoffSeconds \u003c cc.PodInitialBackoffSeconds {\n\t\terrs = append(errs, field.Invalid(field.NewPath(\"podMaxBackoffSeconds\"),\n\t\t\tcc.PodMaxBackoffSeconds, \"must be greater than or equal to PodInitialBackoffSeconds\"))\n\t}\n\n\terrs = append(errs, validateExtenders(field.NewPath(\"extenders\"), cc.Extenders)...)\n\treturn utilerrors.Flatten(utilerrors.NewAggregate(errs))\n}","line":{"from":40,"to":113}} {"id":100010614,"name":"splitHostIntPort","signature":"func splitHostIntPort(s string) (string, int, error)","file":"pkg/scheduler/apis/config/validation/validation.go","code":"func splitHostIntPort(s string) (string, int, error) {\n\thost, port, err := net.SplitHostPort(s)\n\tif err != nil {\n\t\treturn \"\", 0, err\n\t}\n\tportInt, err := strconv.Atoi(port)\n\tif err != nil {\n\t\treturn \"\", 0, err\n\t}\n\treturn host, portInt, err\n}","line":{"from":115,"to":125}} {"id":100010615,"name":"validatePercentageOfNodesToScore","signature":"func validatePercentageOfNodesToScore(path *field.Path, percentageOfNodesToScore *int32) error","file":"pkg/scheduler/apis/config/validation/validation.go","code":"func validatePercentageOfNodesToScore(path *field.Path, percentageOfNodesToScore *int32) error {\n\tif percentageOfNodesToScore != nil {\n\t\tif *percentageOfNodesToScore \u003c 0 || *percentageOfNodesToScore \u003e 100 {\n\t\t\treturn field.Invalid(path, *percentageOfNodesToScore, \"not in valid range [0-100]\")\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":127,"to":134}} {"id":100010616,"name":"isPluginInvalid","signature":"func isPluginInvalid(apiVersion string, name string) (bool, string)","file":"pkg/scheduler/apis/config/validation/validation.go","code":"// isPluginInvalid checks if a given plugin was removed/deprecated in the given component\n// config version or earlier.\nfunc isPluginInvalid(apiVersion string, name string) (bool, string) {\n\tfor _, dp := range invalidPluginsByVersion {\n\t\tfor _, plugin := range dp.plugins {\n\t\t\tif name == plugin {\n\t\t\t\treturn true, dp.schemeGroupVersion\n\t\t\t}\n\t\t}\n\t\tif apiVersion == dp.schemeGroupVersion {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn false, \"\"\n}","line":{"from":159,"to":173}} {"id":100010617,"name":"validatePluginSetForInvalidPlugins","signature":"func validatePluginSetForInvalidPlugins(path *field.Path, apiVersion string, ps config.PluginSet) []error","file":"pkg/scheduler/apis/config/validation/validation.go","code":"func validatePluginSetForInvalidPlugins(path *field.Path, apiVersion string, ps config.PluginSet) []error {\n\tvar errs []error\n\tfor i, plugin := range ps.Enabled {\n\t\tif invalid, invalidVersion := isPluginInvalid(apiVersion, plugin.Name); invalid {\n\t\t\terrs = append(errs, field.Invalid(path.Child(\"enabled\").Index(i), plugin.Name, fmt.Sprintf(\"was invalid in version %q (KubeSchedulerConfiguration is version %q)\", invalidVersion, apiVersion)))\n\t\t}\n\t}\n\treturn errs\n}","line":{"from":175,"to":183}} {"id":100010618,"name":"validateKubeSchedulerProfile","signature":"func validateKubeSchedulerProfile(path *field.Path, apiVersion string, profile *config.KubeSchedulerProfile) []error","file":"pkg/scheduler/apis/config/validation/validation.go","code":"func validateKubeSchedulerProfile(path *field.Path, apiVersion string, profile *config.KubeSchedulerProfile) []error {\n\tvar errs []error\n\tif len(profile.SchedulerName) == 0 {\n\t\terrs = append(errs, field.Required(path.Child(\"schedulerName\"), \"\"))\n\t}\n\terrs = append(errs, validatePercentageOfNodesToScore(path.Child(\"percentageOfNodesToScore\"), profile.PercentageOfNodesToScore))\n\terrs = append(errs, validatePluginConfig(path, apiVersion, profile)...)\n\treturn errs\n}","line":{"from":185,"to":193}} {"id":100010619,"name":"validatePluginConfig","signature":"func validatePluginConfig(path *field.Path, apiVersion string, profile *config.KubeSchedulerProfile) []error","file":"pkg/scheduler/apis/config/validation/validation.go","code":"func validatePluginConfig(path *field.Path, apiVersion string, profile *config.KubeSchedulerProfile) []error {\n\tvar errs []error\n\tm := map[string]interface{}{\n\t\t\"DefaultPreemption\": ValidateDefaultPreemptionArgs,\n\t\t\"InterPodAffinity\": ValidateInterPodAffinityArgs,\n\t\t\"NodeAffinity\": ValidateNodeAffinityArgs,\n\t\t\"NodeResourcesBalancedAllocation\": ValidateNodeResourcesBalancedAllocationArgs,\n\t\t\"NodeResourcesFitArgs\": ValidateNodeResourcesFitArgs,\n\t\t\"PodTopologySpread\": ValidatePodTopologySpreadArgs,\n\t\t\"VolumeBinding\": ValidateVolumeBindingArgs,\n\t}\n\n\tif profile.Plugins != nil {\n\t\tstagesToPluginSet := map[string]config.PluginSet{\n\t\t\t\"preEnqueue\": profile.Plugins.PreEnqueue,\n\t\t\t\"queueSort\": profile.Plugins.QueueSort,\n\t\t\t\"preFilter\": profile.Plugins.PreFilter,\n\t\t\t\"filter\": profile.Plugins.Filter,\n\t\t\t\"postFilter\": profile.Plugins.PostFilter,\n\t\t\t\"preScore\": profile.Plugins.PreScore,\n\t\t\t\"score\": profile.Plugins.Score,\n\t\t\t\"reserve\": profile.Plugins.Reserve,\n\t\t\t\"permit\": profile.Plugins.Permit,\n\t\t\t\"preBind\": profile.Plugins.PreBind,\n\t\t\t\"bind\": profile.Plugins.Bind,\n\t\t\t\"postBind\": profile.Plugins.PostBind,\n\t\t}\n\n\t\tpluginsPath := path.Child(\"plugins\")\n\t\tfor s, p := range stagesToPluginSet {\n\t\t\terrs = append(errs, validatePluginSetForInvalidPlugins(\n\t\t\t\tpluginsPath.Child(s), apiVersion, p)...)\n\t\t}\n\t}\n\n\tseenPluginConfig := make(sets.String)\n\n\tfor i := range profile.PluginConfig {\n\t\tpluginConfigPath := path.Child(\"pluginConfig\").Index(i)\n\t\tname := profile.PluginConfig[i].Name\n\t\targs := profile.PluginConfig[i].Args\n\t\tif seenPluginConfig.Has(name) {\n\t\t\terrs = append(errs, field.Duplicate(pluginConfigPath, name))\n\t\t} else {\n\t\t\tseenPluginConfig.Insert(name)\n\t\t}\n\t\tif invalid, invalidVersion := isPluginInvalid(apiVersion, name); invalid {\n\t\t\terrs = append(errs, field.Invalid(pluginConfigPath, name, fmt.Sprintf(\"was invalid in version %q (KubeSchedulerConfiguration is version %q)\", invalidVersion, apiVersion)))\n\t\t} else if validateFunc, ok := m[name]; ok {\n\t\t\t// type mismatch, no need to validate the `args`.\n\t\t\tif reflect.TypeOf(args) != reflect.ValueOf(validateFunc).Type().In(1) {\n\t\t\t\terrs = append(errs, field.Invalid(pluginConfigPath.Child(\"args\"), args, \"has to match plugin args\"))\n\t\t\t} else {\n\t\t\t\tin := []reflect.Value{reflect.ValueOf(pluginConfigPath.Child(\"args\")), reflect.ValueOf(args)}\n\t\t\t\tres := reflect.ValueOf(validateFunc).Call(in)\n\t\t\t\t// It's possible that validation function return a Aggregate, just append here and it will be flattened at the end of CC validation.\n\t\t\t\tif res[0].Interface() != nil {\n\t\t\t\t\terrs = append(errs, res[0].Interface().(error))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn errs\n}","line":{"from":195,"to":258}} {"id":100010620,"name":"validateCommonQueueSort","signature":"func validateCommonQueueSort(path *field.Path, profiles []config.KubeSchedulerProfile) []error","file":"pkg/scheduler/apis/config/validation/validation.go","code":"func validateCommonQueueSort(path *field.Path, profiles []config.KubeSchedulerProfile) []error {\n\tvar errs []error\n\tvar canon config.PluginSet\n\tvar queueSortName string\n\tvar queueSortArgs runtime.Object\n\tif profiles[0].Plugins != nil {\n\t\tcanon = profiles[0].Plugins.QueueSort\n\t\tif len(profiles[0].Plugins.QueueSort.Enabled) != 0 {\n\t\t\tqueueSortName = profiles[0].Plugins.QueueSort.Enabled[0].Name\n\t\t}\n\t\tlength := len(profiles[0].Plugins.QueueSort.Enabled)\n\t\tif length \u003e 1 {\n\t\t\terrs = append(errs, field.Invalid(path.Index(0).Child(\"plugins\", \"queueSort\", \"Enabled\"), length, \"only one queue sort plugin can be enabled\"))\n\t\t}\n\t}\n\tfor _, cfg := range profiles[0].PluginConfig {\n\t\tif len(queueSortName) \u003e 0 \u0026\u0026 cfg.Name == queueSortName {\n\t\t\tqueueSortArgs = cfg.Args\n\t\t}\n\t}\n\tfor i := 1; i \u003c len(profiles); i++ {\n\t\tvar curr config.PluginSet\n\t\tif profiles[i].Plugins != nil {\n\t\t\tcurr = profiles[i].Plugins.QueueSort\n\t\t}\n\t\tif !cmp.Equal(canon, curr) {\n\t\t\terrs = append(errs, field.Invalid(path.Index(i).Child(\"plugins\", \"queueSort\"), curr, \"has to match for all profiles\"))\n\t\t}\n\t\tfor _, cfg := range profiles[i].PluginConfig {\n\t\t\tif cfg.Name == queueSortName \u0026\u0026 !cmp.Equal(queueSortArgs, cfg.Args) {\n\t\t\t\terrs = append(errs, field.Invalid(path.Index(i).Child(\"pluginConfig\", \"args\"), cfg.Args, \"has to match for all profiles\"))\n\t\t\t}\n\t\t}\n\t}\n\treturn errs\n}","line":{"from":260,"to":295}} {"id":100010621,"name":"validateExtenders","signature":"func validateExtenders(fldPath *field.Path, extenders []config.Extender) []error","file":"pkg/scheduler/apis/config/validation/validation.go","code":"// validateExtenders validates the configured extenders for the Scheduler\nfunc validateExtenders(fldPath *field.Path, extenders []config.Extender) []error {\n\tvar errs []error\n\tbinders := 0\n\textenderManagedResources := sets.NewString()\n\tfor i, extender := range extenders {\n\t\tpath := fldPath.Index(i)\n\t\tif len(extender.PrioritizeVerb) \u003e 0 \u0026\u0026 extender.Weight \u003c= 0 {\n\t\t\terrs = append(errs, field.Invalid(path.Child(\"weight\"),\n\t\t\t\textender.Weight, \"must have a positive weight applied to it\"))\n\t\t}\n\t\tif extender.BindVerb != \"\" {\n\t\t\tbinders++\n\t\t}\n\t\tfor j, resource := range extender.ManagedResources {\n\t\t\tmanagedResourcesPath := path.Child(\"managedResources\").Index(j)\n\t\t\tvalidationErrors := validateExtendedResourceName(managedResourcesPath.Child(\"name\"), v1.ResourceName(resource.Name))\n\t\t\terrs = append(errs, validationErrors...)\n\t\t\tif extenderManagedResources.Has(resource.Name) {\n\t\t\t\terrs = append(errs, field.Invalid(managedResourcesPath.Child(\"name\"),\n\t\t\t\t\tresource.Name, \"duplicate extender managed resource name\"))\n\t\t\t}\n\t\t\textenderManagedResources.Insert(resource.Name)\n\t\t}\n\t}\n\tif binders \u003e 1 {\n\t\terrs = append(errs, field.Invalid(fldPath, fmt.Sprintf(\"found %d extenders implementing bind\", binders), \"only one extender can implement bind\"))\n\t}\n\treturn errs\n}","line":{"from":297,"to":326}} {"id":100010622,"name":"validateExtendedResourceName","signature":"func validateExtendedResourceName(path *field.Path, name v1.ResourceName) []error","file":"pkg/scheduler/apis/config/validation/validation.go","code":"// validateExtendedResourceName checks whether the specified name is a valid\n// extended resource name.\nfunc validateExtendedResourceName(path *field.Path, name v1.ResourceName) []error {\n\tvar validationErrors []error\n\tfor _, msg := range validation.IsQualifiedName(string(name)) {\n\t\tvalidationErrors = append(validationErrors, field.Invalid(path, name, msg))\n\t}\n\tif len(validationErrors) != 0 {\n\t\treturn validationErrors\n\t}\n\tif !v1helper.IsExtendedResourceName(name) {\n\t\tvalidationErrors = append(validationErrors, field.Invalid(path, string(name), \"is an invalid extended resource name\"))\n\t}\n\treturn validationErrors\n}","line":{"from":328,"to":342}} {"id":100010623,"name":"ValidateDefaultPreemptionArgs","signature":"func ValidateDefaultPreemptionArgs(path *field.Path, args *config.DefaultPreemptionArgs) error","file":"pkg/scheduler/apis/config/validation/validation_pluginargs.go","code":"// ValidateDefaultPreemptionArgs validates that DefaultPreemptionArgs are correct.\nfunc ValidateDefaultPreemptionArgs(path *field.Path, args *config.DefaultPreemptionArgs) error {\n\tvar allErrs field.ErrorList\n\tpercentagePath := path.Child(\"minCandidateNodesPercentage\")\n\tabsolutePath := path.Child(\"minCandidateNodesAbsolute\")\n\tif err := validateMinCandidateNodesPercentage(args.MinCandidateNodesPercentage, percentagePath); err != nil {\n\t\tallErrs = append(allErrs, err)\n\t}\n\tif err := validateMinCandidateNodesAbsolute(args.MinCandidateNodesAbsolute, absolutePath); err != nil {\n\t\tallErrs = append(allErrs, err)\n\t}\n\tif args.MinCandidateNodesPercentage == 0 \u0026\u0026 args.MinCandidateNodesAbsolute == 0 {\n\t\tallErrs = append(allErrs,\n\t\t\tfield.Invalid(percentagePath, args.MinCandidateNodesPercentage, \"cannot be zero at the same time as minCandidateNodesAbsolute\"),\n\t\t\tfield.Invalid(absolutePath, args.MinCandidateNodesAbsolute, \"cannot be zero at the same time as minCandidateNodesPercentage\"))\n\t}\n\treturn allErrs.ToAggregate()\n}","line":{"from":40,"to":57}} {"id":100010624,"name":"validateMinCandidateNodesPercentage","signature":"func validateMinCandidateNodesPercentage(minCandidateNodesPercentage int32, p *field.Path) *field.Error","file":"pkg/scheduler/apis/config/validation/validation_pluginargs.go","code":"// validateMinCandidateNodesPercentage validates that\n// minCandidateNodesPercentage is within the allowed range.\nfunc validateMinCandidateNodesPercentage(minCandidateNodesPercentage int32, p *field.Path) *field.Error {\n\tif minCandidateNodesPercentage \u003c 0 || minCandidateNodesPercentage \u003e 100 {\n\t\treturn field.Invalid(p, minCandidateNodesPercentage, \"not in valid range [0, 100]\")\n\t}\n\treturn nil\n}","line":{"from":59,"to":66}} {"id":100010625,"name":"validateMinCandidateNodesAbsolute","signature":"func validateMinCandidateNodesAbsolute(minCandidateNodesAbsolute int32, p *field.Path) *field.Error","file":"pkg/scheduler/apis/config/validation/validation_pluginargs.go","code":"// validateMinCandidateNodesAbsolute validates that minCandidateNodesAbsolute\n// is within the allowed range.\nfunc validateMinCandidateNodesAbsolute(minCandidateNodesAbsolute int32, p *field.Path) *field.Error {\n\tif minCandidateNodesAbsolute \u003c 0 {\n\t\treturn field.Invalid(p, minCandidateNodesAbsolute, \"not in valid range [0, inf)\")\n\t}\n\treturn nil\n}","line":{"from":68,"to":75}} {"id":100010626,"name":"ValidateInterPodAffinityArgs","signature":"func ValidateInterPodAffinityArgs(path *field.Path, args *config.InterPodAffinityArgs) error","file":"pkg/scheduler/apis/config/validation/validation_pluginargs.go","code":"// ValidateInterPodAffinityArgs validates that InterPodAffinityArgs are correct.\nfunc ValidateInterPodAffinityArgs(path *field.Path, args *config.InterPodAffinityArgs) error {\n\treturn validateHardPodAffinityWeight(path.Child(\"hardPodAffinityWeight\"), args.HardPodAffinityWeight)\n}","line":{"from":77,"to":80}} {"id":100010627,"name":"validateHardPodAffinityWeight","signature":"func validateHardPodAffinityWeight(path *field.Path, w int32) error","file":"pkg/scheduler/apis/config/validation/validation_pluginargs.go","code":"// validateHardPodAffinityWeight validates that weight is within allowed range.\nfunc validateHardPodAffinityWeight(path *field.Path, w int32) error {\n\tconst (\n\t\tminHardPodAffinityWeight = 0\n\t\tmaxHardPodAffinityWeight = 100\n\t)\n\n\tif w \u003c minHardPodAffinityWeight || w \u003e maxHardPodAffinityWeight {\n\t\tmsg := fmt.Sprintf(\"not in valid range [%d, %d]\", minHardPodAffinityWeight, maxHardPodAffinityWeight)\n\t\treturn field.Invalid(path, w, msg)\n\t}\n\treturn nil\n}","line":{"from":82,"to":94}} {"id":100010628,"name":"ValidatePodTopologySpreadArgs","signature":"func ValidatePodTopologySpreadArgs(path *field.Path, args *config.PodTopologySpreadArgs) error","file":"pkg/scheduler/apis/config/validation/validation_pluginargs.go","code":"// ValidatePodTopologySpreadArgs validates that PodTopologySpreadArgs are correct.\n// It replicates the validation from pkg/apis/core/validation.validateTopologySpreadConstraints\n// with an additional check for .labelSelector to be nil.\nfunc ValidatePodTopologySpreadArgs(path *field.Path, args *config.PodTopologySpreadArgs) error {\n\tvar allErrs field.ErrorList\n\tif err := validateDefaultingType(path.Child(\"defaultingType\"), args.DefaultingType, args.DefaultConstraints); err != nil {\n\t\tallErrs = append(allErrs, err)\n\t}\n\n\tdefaultConstraintsPath := path.Child(\"defaultConstraints\")\n\tfor i, c := range args.DefaultConstraints {\n\t\tp := defaultConstraintsPath.Index(i)\n\t\tif c.MaxSkew \u003c= 0 {\n\t\t\tf := p.Child(\"maxSkew\")\n\t\t\tallErrs = append(allErrs, field.Invalid(f, c.MaxSkew, \"not in valid range (0, inf)\"))\n\t\t}\n\t\tallErrs = append(allErrs, validateTopologyKey(p.Child(\"topologyKey\"), c.TopologyKey)...)\n\t\tif err := validateWhenUnsatisfiable(p.Child(\"whenUnsatisfiable\"), c.WhenUnsatisfiable); err != nil {\n\t\t\tallErrs = append(allErrs, err)\n\t\t}\n\t\tif c.LabelSelector != nil {\n\t\t\tf := field.Forbidden(p.Child(\"labelSelector\"), \"constraint must not define a selector, as they deduced for each pod\")\n\t\t\tallErrs = append(allErrs, f)\n\t\t}\n\t\tif err := validateConstraintNotRepeat(defaultConstraintsPath, args.DefaultConstraints, i); err != nil {\n\t\t\tallErrs = append(allErrs, err)\n\t\t}\n\t}\n\tif len(allErrs) == 0 {\n\t\treturn nil\n\t}\n\treturn allErrs.ToAggregate()\n}","line":{"from":96,"to":128}} {"id":100010629,"name":"validateDefaultingType","signature":"func validateDefaultingType(p *field.Path, v config.PodTopologySpreadConstraintsDefaulting, constraints []v1.TopologySpreadConstraint) *field.Error","file":"pkg/scheduler/apis/config/validation/validation_pluginargs.go","code":"func validateDefaultingType(p *field.Path, v config.PodTopologySpreadConstraintsDefaulting, constraints []v1.TopologySpreadConstraint) *field.Error {\n\tif v != config.SystemDefaulting \u0026\u0026 v != config.ListDefaulting {\n\t\treturn field.NotSupported(p, v, []string{string(config.SystemDefaulting), string(config.ListDefaulting)})\n\t}\n\tif v == config.SystemDefaulting \u0026\u0026 len(constraints) \u003e 0 {\n\t\treturn field.Invalid(p, v, \"when .defaultConstraints are not empty\")\n\t}\n\treturn nil\n}","line":{"from":130,"to":138}} {"id":100010630,"name":"validateTopologyKey","signature":"func validateTopologyKey(p *field.Path, v string) field.ErrorList","file":"pkg/scheduler/apis/config/validation/validation_pluginargs.go","code":"func validateTopologyKey(p *field.Path, v string) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tif len(v) == 0 {\n\t\tallErrs = append(allErrs, field.Required(p, \"can not be empty\"))\n\t} else {\n\t\tallErrs = append(allErrs, metav1validation.ValidateLabelName(v, p)...)\n\t}\n\treturn allErrs\n}","line":{"from":140,"to":148}} {"id":100010631,"name":"validateWhenUnsatisfiable","signature":"func validateWhenUnsatisfiable(p *field.Path, v v1.UnsatisfiableConstraintAction) *field.Error","file":"pkg/scheduler/apis/config/validation/validation_pluginargs.go","code":"func validateWhenUnsatisfiable(p *field.Path, v v1.UnsatisfiableConstraintAction) *field.Error {\n\tsupportedScheduleActions := sets.NewString(string(v1.DoNotSchedule), string(v1.ScheduleAnyway))\n\n\tif len(v) == 0 {\n\t\treturn field.Required(p, \"can not be empty\")\n\t}\n\tif !supportedScheduleActions.Has(string(v)) {\n\t\treturn field.NotSupported(p, v, supportedScheduleActions.List())\n\t}\n\treturn nil\n}","line":{"from":150,"to":160}} {"id":100010632,"name":"validateConstraintNotRepeat","signature":"func validateConstraintNotRepeat(path *field.Path, constraints []v1.TopologySpreadConstraint, idx int) *field.Error","file":"pkg/scheduler/apis/config/validation/validation_pluginargs.go","code":"func validateConstraintNotRepeat(path *field.Path, constraints []v1.TopologySpreadConstraint, idx int) *field.Error {\n\tc := \u0026constraints[idx]\n\tfor i := range constraints[:idx] {\n\t\tother := \u0026constraints[i]\n\t\tif c.TopologyKey == other.TopologyKey \u0026\u0026 c.WhenUnsatisfiable == other.WhenUnsatisfiable {\n\t\t\treturn field.Duplicate(path.Index(idx), fmt.Sprintf(\"{%v, %v}\", c.TopologyKey, c.WhenUnsatisfiable))\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":162,"to":171}} {"id":100010633,"name":"validateFunctionShape","signature":"func validateFunctionShape(shape []config.UtilizationShapePoint, path *field.Path) field.ErrorList","file":"pkg/scheduler/apis/config/validation/validation_pluginargs.go","code":"func validateFunctionShape(shape []config.UtilizationShapePoint, path *field.Path) field.ErrorList {\n\tconst (\n\t\tminUtilization = 0\n\t\tmaxUtilization = 100\n\t\tminScore = 0\n\t\tmaxScore = int32(config.MaxCustomPriorityScore)\n\t)\n\n\tvar allErrs field.ErrorList\n\n\tif len(shape) == 0 {\n\t\tallErrs = append(allErrs, field.Required(path, \"at least one point must be specified\"))\n\t\treturn allErrs\n\t}\n\n\tfor i := 1; i \u003c len(shape); i++ {\n\t\tif shape[i-1].Utilization \u003e= shape[i].Utilization {\n\t\t\tallErrs = append(allErrs, field.Invalid(path.Index(i).Child(\"utilization\"), shape[i].Utilization, \"utilization values must be sorted in increasing order\"))\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfor i, point := range shape {\n\t\tif point.Utilization \u003c minUtilization || point.Utilization \u003e maxUtilization {\n\t\t\tmsg := fmt.Sprintf(\"not in valid range [%d, %d]\", minUtilization, maxUtilization)\n\t\t\tallErrs = append(allErrs, field.Invalid(path.Index(i).Child(\"utilization\"), point.Utilization, msg))\n\t\t}\n\n\t\tif point.Score \u003c minScore || point.Score \u003e maxScore {\n\t\t\tmsg := fmt.Sprintf(\"not in valid range [%d, %d]\", minScore, maxScore)\n\t\t\tallErrs = append(allErrs, field.Invalid(path.Index(i).Child(\"score\"), point.Score, msg))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":173,"to":208}} {"id":100010634,"name":"validateResources","signature":"func validateResources(resources []config.ResourceSpec, p *field.Path) field.ErrorList","file":"pkg/scheduler/apis/config/validation/validation_pluginargs.go","code":"func validateResources(resources []config.ResourceSpec, p *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tfor i, resource := range resources {\n\t\tif resource.Weight \u003c= 0 || resource.Weight \u003e 100 {\n\t\t\tmsg := fmt.Sprintf(\"resource weight of %v not in valid range (0, 100]\", resource.Name)\n\t\t\tallErrs = append(allErrs, field.Invalid(p.Index(i).Child(\"weight\"), resource.Weight, msg))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":210,"to":219}} {"id":100010635,"name":"ValidateNodeResourcesBalancedAllocationArgs","signature":"func ValidateNodeResourcesBalancedAllocationArgs(path *field.Path, args *config.NodeResourcesBalancedAllocationArgs) error","file":"pkg/scheduler/apis/config/validation/validation_pluginargs.go","code":"// ValidateNodeResourcesBalancedAllocationArgs validates that NodeResourcesBalancedAllocationArgs are set correctly.\nfunc ValidateNodeResourcesBalancedAllocationArgs(path *field.Path, args *config.NodeResourcesBalancedAllocationArgs) error {\n\tvar allErrs field.ErrorList\n\tseenResources := sets.NewString()\n\tfor i, resource := range args.Resources {\n\t\tif seenResources.Has(resource.Name) {\n\t\t\tallErrs = append(allErrs, field.Duplicate(path.Child(\"resources\").Index(i).Child(\"name\"), resource.Name))\n\t\t} else {\n\t\t\tseenResources.Insert(resource.Name)\n\t\t}\n\t\tif resource.Weight != 1 {\n\t\t\tallErrs = append(allErrs, field.Invalid(path.Child(\"resources\").Index(i).Child(\"weight\"), resource.Weight, \"must be 1\"))\n\t\t}\n\t}\n\treturn allErrs.ToAggregate()\n}","line":{"from":221,"to":236}} {"id":100010636,"name":"ValidateNodeAffinityArgs","signature":"func ValidateNodeAffinityArgs(path *field.Path, args *config.NodeAffinityArgs) error","file":"pkg/scheduler/apis/config/validation/validation_pluginargs.go","code":"// ValidateNodeAffinityArgs validates that NodeAffinityArgs are correct.\nfunc ValidateNodeAffinityArgs(path *field.Path, args *config.NodeAffinityArgs) error {\n\tif args.AddedAffinity == nil {\n\t\treturn nil\n\t}\n\taffinity := args.AddedAffinity\n\tvar errs []error\n\tif ns := affinity.RequiredDuringSchedulingIgnoredDuringExecution; ns != nil {\n\t\t_, err := nodeaffinity.NewNodeSelector(ns, field.WithPath(path.Child(\"addedAffinity\", \"requiredDuringSchedulingIgnoredDuringExecution\")))\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\t// TODO: Add validation for requiredDuringSchedulingRequiredDuringExecution when it gets added to the API.\n\tif terms := affinity.PreferredDuringSchedulingIgnoredDuringExecution; len(terms) != 0 {\n\t\t_, err := nodeaffinity.NewPreferredSchedulingTerms(terms, field.WithPath(path.Child(\"addedAffinity\", \"preferredDuringSchedulingIgnoredDuringExecution\")))\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\treturn errors.Flatten(errors.NewAggregate(errs))\n}","line":{"from":238,"to":259}} {"id":100010637,"name":"ValidateVolumeBindingArgs","signature":"func ValidateVolumeBindingArgs(path *field.Path, args *config.VolumeBindingArgs) error","file":"pkg/scheduler/apis/config/validation/validation_pluginargs.go","code":"// ValidateVolumeBindingArgs validates that VolumeBindingArgs are set correctly.\nfunc ValidateVolumeBindingArgs(path *field.Path, args *config.VolumeBindingArgs) error {\n\treturn ValidateVolumeBindingArgsWithOptions(path, args, VolumeBindingArgsValidationOptions{\n\t\tAllowVolumeCapacityPriority: utilfeature.DefaultFeatureGate.Enabled(features.VolumeCapacityPriority),\n\t})\n}","line":{"from":266,"to":271}} {"id":100010638,"name":"ValidateVolumeBindingArgsWithOptions","signature":"func ValidateVolumeBindingArgsWithOptions(path *field.Path, args *config.VolumeBindingArgs, opts VolumeBindingArgsValidationOptions) error","file":"pkg/scheduler/apis/config/validation/validation_pluginargs.go","code":"// ValidateVolumeBindingArgs validates that VolumeBindingArgs with scheduler features.\nfunc ValidateVolumeBindingArgsWithOptions(path *field.Path, args *config.VolumeBindingArgs, opts VolumeBindingArgsValidationOptions) error {\n\tvar allErrs field.ErrorList\n\n\tif args.BindTimeoutSeconds \u003c 0 {\n\t\tallErrs = append(allErrs, field.Invalid(path.Child(\"bindTimeoutSeconds\"), args.BindTimeoutSeconds, \"invalid BindTimeoutSeconds, should not be a negative value\"))\n\t}\n\n\tif opts.AllowVolumeCapacityPriority {\n\t\tallErrs = append(allErrs, validateFunctionShape(args.Shape, path.Child(\"shape\"))...)\n\t} else if args.Shape != nil {\n\t\t// When the feature is off, return an error if the config is not nil.\n\t\t// This prevents unexpected configuration from taking effect when the\n\t\t// feature turns on in the future.\n\t\tallErrs = append(allErrs, field.Invalid(path.Child(\"shape\"), args.Shape, \"unexpected field `shape`, remove it or turn on the feature gate VolumeCapacityPriority\"))\n\t}\n\treturn allErrs.ToAggregate()\n}","line":{"from":273,"to":290}} {"id":100010639,"name":"ValidateNodeResourcesFitArgs","signature":"func ValidateNodeResourcesFitArgs(path *field.Path, args *config.NodeResourcesFitArgs) error","file":"pkg/scheduler/apis/config/validation/validation_pluginargs.go","code":"func ValidateNodeResourcesFitArgs(path *field.Path, args *config.NodeResourcesFitArgs) error {\n\tvar allErrs field.ErrorList\n\tresPath := path.Child(\"ignoredResources\")\n\tfor i, res := range args.IgnoredResources {\n\t\tpath := resPath.Index(i)\n\t\tif errs := metav1validation.ValidateLabelName(res, path); len(errs) != 0 {\n\t\t\tallErrs = append(allErrs, errs...)\n\t\t}\n\t}\n\n\tgroupPath := path.Child(\"ignoredResourceGroups\")\n\tfor i, group := range args.IgnoredResourceGroups {\n\t\tpath := groupPath.Index(i)\n\t\tif strings.Contains(group, \"/\") {\n\t\t\tallErrs = append(allErrs, field.Invalid(path, group, \"resource group name can't contain '/'\"))\n\t\t}\n\t\tif errs := metav1validation.ValidateLabelName(group, path); len(errs) != 0 {\n\t\t\tallErrs = append(allErrs, errs...)\n\t\t}\n\t}\n\n\tstrategyPath := path.Child(\"scoringStrategy\")\n\tif args.ScoringStrategy != nil {\n\t\tif !supportedScoringStrategyTypes.Has(string(args.ScoringStrategy.Type)) {\n\t\t\tallErrs = append(allErrs, field.NotSupported(strategyPath.Child(\"type\"), args.ScoringStrategy.Type, supportedScoringStrategyTypes.List()))\n\t\t}\n\t\tallErrs = append(allErrs, validateResources(args.ScoringStrategy.Resources, strategyPath.Child(\"resources\"))...)\n\t\tif args.ScoringStrategy.RequestedToCapacityRatio != nil {\n\t\t\tallErrs = append(allErrs, validateFunctionShape(args.ScoringStrategy.RequestedToCapacityRatio.Shape, strategyPath.Child(\"shape\"))...)\n\t\t}\n\t}\n\n\tif len(allErrs) == 0 {\n\t\treturn nil\n\t}\n\treturn allErrs.ToAggregate()\n}","line":{"from":292,"to":328}} {"id":100010640,"name":"onStorageClassAdd","signature":"func (sched *Scheduler) onStorageClassAdd(obj interface{})","file":"pkg/scheduler/eventhandlers.go","code":"func (sched *Scheduler) onStorageClassAdd(obj interface{}) {\n\tsc, ok := obj.(*storagev1.StorageClass)\n\tif !ok {\n\t\tklog.ErrorS(nil, \"Cannot convert to *storagev1.StorageClass\", \"obj\", obj)\n\t\treturn\n\t}\n\n\t// CheckVolumeBindingPred fails if pod has unbound immediate PVCs. If these\n\t// PVCs have specified StorageClass name, creating StorageClass objects\n\t// with late binding will cause predicates to pass, so we need to move pods\n\t// to active queue.\n\t// We don't need to invalidate cached results because results will not be\n\t// cached for pod that has unbound immediate PVCs.\n\tif sc.VolumeBindingMode != nil \u0026\u0026 *sc.VolumeBindingMode == storagev1.VolumeBindingWaitForFirstConsumer {\n\t\tsched.SchedulingQueue.MoveAllToActiveOrBackoffQueue(queue.StorageClassAdd, nil)\n\t}\n}","line":{"from":45,"to":61}} {"id":100010641,"name":"addNodeToCache","signature":"func (sched *Scheduler) addNodeToCache(obj interface{})","file":"pkg/scheduler/eventhandlers.go","code":"func (sched *Scheduler) addNodeToCache(obj interface{}) {\n\tnode, ok := obj.(*v1.Node)\n\tif !ok {\n\t\tklog.ErrorS(nil, \"Cannot convert to *v1.Node\", \"obj\", obj)\n\t\treturn\n\t}\n\n\tnodeInfo := sched.Cache.AddNode(node)\n\tklog.V(3).InfoS(\"Add event for node\", \"node\", klog.KObj(node))\n\tsched.SchedulingQueue.MoveAllToActiveOrBackoffQueue(queue.NodeAdd, preCheckForNode(nodeInfo))\n}","line":{"from":63,"to":73}} {"id":100010642,"name":"updateNodeInCache","signature":"func (sched *Scheduler) updateNodeInCache(oldObj, newObj interface{})","file":"pkg/scheduler/eventhandlers.go","code":"func (sched *Scheduler) updateNodeInCache(oldObj, newObj interface{}) {\n\toldNode, ok := oldObj.(*v1.Node)\n\tif !ok {\n\t\tklog.ErrorS(nil, \"Cannot convert oldObj to *v1.Node\", \"oldObj\", oldObj)\n\t\treturn\n\t}\n\tnewNode, ok := newObj.(*v1.Node)\n\tif !ok {\n\t\tklog.ErrorS(nil, \"Cannot convert newObj to *v1.Node\", \"newObj\", newObj)\n\t\treturn\n\t}\n\n\tnodeInfo := sched.Cache.UpdateNode(oldNode, newNode)\n\t// Only requeue unschedulable pods if the node became more schedulable.\n\tif event := nodeSchedulingPropertiesChange(newNode, oldNode); event != nil {\n\t\tsched.SchedulingQueue.MoveAllToActiveOrBackoffQueue(*event, preCheckForNode(nodeInfo))\n\t}\n}","line":{"from":75,"to":92}} {"id":100010643,"name":"deleteNodeFromCache","signature":"func (sched *Scheduler) deleteNodeFromCache(obj interface{})","file":"pkg/scheduler/eventhandlers.go","code":"func (sched *Scheduler) deleteNodeFromCache(obj interface{}) {\n\tvar node *v1.Node\n\tswitch t := obj.(type) {\n\tcase *v1.Node:\n\t\tnode = t\n\tcase cache.DeletedFinalStateUnknown:\n\t\tvar ok bool\n\t\tnode, ok = t.Obj.(*v1.Node)\n\t\tif !ok {\n\t\t\tklog.ErrorS(nil, \"Cannot convert to *v1.Node\", \"obj\", t.Obj)\n\t\t\treturn\n\t\t}\n\tdefault:\n\t\tklog.ErrorS(nil, \"Cannot convert to *v1.Node\", \"obj\", t)\n\t\treturn\n\t}\n\tklog.V(3).InfoS(\"Delete event for node\", \"node\", klog.KObj(node))\n\tif err := sched.Cache.RemoveNode(node); err != nil {\n\t\tklog.ErrorS(err, \"Scheduler cache RemoveNode failed\")\n\t}\n}","line":{"from":94,"to":114}} {"id":100010644,"name":"addPodToSchedulingQueue","signature":"func (sched *Scheduler) addPodToSchedulingQueue(obj interface{})","file":"pkg/scheduler/eventhandlers.go","code":"func (sched *Scheduler) addPodToSchedulingQueue(obj interface{}) {\n\tpod := obj.(*v1.Pod)\n\tklog.V(3).InfoS(\"Add event for unscheduled pod\", \"pod\", klog.KObj(pod))\n\tif err := sched.SchedulingQueue.Add(pod); err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unable to queue %T: %v\", obj, err))\n\t}\n}","line":{"from":116,"to":122}} {"id":100010645,"name":"updatePodInSchedulingQueue","signature":"func (sched *Scheduler) updatePodInSchedulingQueue(oldObj, newObj interface{})","file":"pkg/scheduler/eventhandlers.go","code":"func (sched *Scheduler) updatePodInSchedulingQueue(oldObj, newObj interface{}) {\n\toldPod, newPod := oldObj.(*v1.Pod), newObj.(*v1.Pod)\n\t// Bypass update event that carries identical objects; otherwise, a duplicated\n\t// Pod may go through scheduling and cause unexpected behavior (see #96071).\n\tif oldPod.ResourceVersion == newPod.ResourceVersion {\n\t\treturn\n\t}\n\n\tisAssumed, err := sched.Cache.IsAssumedPod(newPod)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"failed to check whether pod %s/%s is assumed: %v\", newPod.Namespace, newPod.Name, err))\n\t}\n\tif isAssumed {\n\t\treturn\n\t}\n\n\tif err := sched.SchedulingQueue.Update(oldPod, newPod); err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unable to update %T: %v\", newObj, err))\n\t}\n}","line":{"from":124,"to":143}} {"id":100010646,"name":"deletePodFromSchedulingQueue","signature":"func (sched *Scheduler) deletePodFromSchedulingQueue(obj interface{})","file":"pkg/scheduler/eventhandlers.go","code":"func (sched *Scheduler) deletePodFromSchedulingQueue(obj interface{}) {\n\tvar pod *v1.Pod\n\tswitch t := obj.(type) {\n\tcase *v1.Pod:\n\t\tpod = obj.(*v1.Pod)\n\tcase cache.DeletedFinalStateUnknown:\n\t\tvar ok bool\n\t\tpod, ok = t.Obj.(*v1.Pod)\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"unable to convert object %T to *v1.Pod in %T\", obj, sched))\n\t\t\treturn\n\t\t}\n\tdefault:\n\t\tutilruntime.HandleError(fmt.Errorf(\"unable to handle object in %T: %T\", sched, obj))\n\t\treturn\n\t}\n\tklog.V(3).InfoS(\"Delete event for unscheduled pod\", \"pod\", klog.KObj(pod))\n\tif err := sched.SchedulingQueue.Delete(pod); err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unable to dequeue %T: %v\", obj, err))\n\t}\n\tfwk, err := sched.frameworkForPod(pod)\n\tif err != nil {\n\t\t// This shouldn't happen, because we only accept for scheduling the pods\n\t\t// which specify a scheduler name that matches one of the profiles.\n\t\tklog.ErrorS(err, \"Unable to get profile\", \"pod\", klog.KObj(pod))\n\t\treturn\n\t}\n\t// If a waiting pod is rejected, it indicates it's previously assumed and we're\n\t// removing it from the scheduler cache. In this case, signal a AssignedPodDelete\n\t// event to immediately retry some unscheduled Pods.\n\tif fwk.RejectWaitingPod(pod.UID) {\n\t\tsched.SchedulingQueue.MoveAllToActiveOrBackoffQueue(queue.AssignedPodDelete, nil)\n\t}\n}","line":{"from":145,"to":178}} {"id":100010647,"name":"addPodToCache","signature":"func (sched *Scheduler) addPodToCache(obj interface{})","file":"pkg/scheduler/eventhandlers.go","code":"func (sched *Scheduler) addPodToCache(obj interface{}) {\n\tpod, ok := obj.(*v1.Pod)\n\tif !ok {\n\t\tklog.ErrorS(nil, \"Cannot convert to *v1.Pod\", \"obj\", obj)\n\t\treturn\n\t}\n\tklog.V(3).InfoS(\"Add event for scheduled pod\", \"pod\", klog.KObj(pod))\n\n\tif err := sched.Cache.AddPod(pod); err != nil {\n\t\tklog.ErrorS(err, \"Scheduler cache AddPod failed\", \"pod\", klog.KObj(pod))\n\t}\n\n\tsched.SchedulingQueue.AssignedPodAdded(pod)\n}","line":{"from":180,"to":193}} {"id":100010648,"name":"updatePodInCache","signature":"func (sched *Scheduler) updatePodInCache(oldObj, newObj interface{})","file":"pkg/scheduler/eventhandlers.go","code":"func (sched *Scheduler) updatePodInCache(oldObj, newObj interface{}) {\n\toldPod, ok := oldObj.(*v1.Pod)\n\tif !ok {\n\t\tklog.ErrorS(nil, \"Cannot convert oldObj to *v1.Pod\", \"oldObj\", oldObj)\n\t\treturn\n\t}\n\tnewPod, ok := newObj.(*v1.Pod)\n\tif !ok {\n\t\tklog.ErrorS(nil, \"Cannot convert newObj to *v1.Pod\", \"newObj\", newObj)\n\t\treturn\n\t}\n\tklog.V(4).InfoS(\"Update event for scheduled pod\", \"pod\", klog.KObj(oldPod))\n\n\tif err := sched.Cache.UpdatePod(oldPod, newPod); err != nil {\n\t\tklog.ErrorS(err, \"Scheduler cache UpdatePod failed\", \"pod\", klog.KObj(oldPod))\n\t}\n\n\tsched.SchedulingQueue.AssignedPodUpdated(newPod)\n}","line":{"from":195,"to":213}} {"id":100010649,"name":"deletePodFromCache","signature":"func (sched *Scheduler) deletePodFromCache(obj interface{})","file":"pkg/scheduler/eventhandlers.go","code":"func (sched *Scheduler) deletePodFromCache(obj interface{}) {\n\tvar pod *v1.Pod\n\tswitch t := obj.(type) {\n\tcase *v1.Pod:\n\t\tpod = t\n\tcase cache.DeletedFinalStateUnknown:\n\t\tvar ok bool\n\t\tpod, ok = t.Obj.(*v1.Pod)\n\t\tif !ok {\n\t\t\tklog.ErrorS(nil, \"Cannot convert to *v1.Pod\", \"obj\", t.Obj)\n\t\t\treturn\n\t\t}\n\tdefault:\n\t\tklog.ErrorS(nil, \"Cannot convert to *v1.Pod\", \"obj\", t)\n\t\treturn\n\t}\n\tklog.V(3).InfoS(\"Delete event for scheduled pod\", \"pod\", klog.KObj(pod))\n\tif err := sched.Cache.RemovePod(pod); err != nil {\n\t\tklog.ErrorS(err, \"Scheduler cache RemovePod failed\", \"pod\", klog.KObj(pod))\n\t}\n\n\tsched.SchedulingQueue.MoveAllToActiveOrBackoffQueue(queue.AssignedPodDelete, nil)\n}","line":{"from":215,"to":237}} {"id":100010650,"name":"assignedPod","signature":"func assignedPod(pod *v1.Pod) bool","file":"pkg/scheduler/eventhandlers.go","code":"// assignedPod selects pods that are assigned (scheduled and running).\nfunc assignedPod(pod *v1.Pod) bool {\n\treturn len(pod.Spec.NodeName) != 0\n}","line":{"from":239,"to":242}} {"id":100010651,"name":"responsibleForPod","signature":"func responsibleForPod(pod *v1.Pod, profiles profile.Map) bool","file":"pkg/scheduler/eventhandlers.go","code":"// responsibleForPod returns true if the pod has asked to be scheduled by the given scheduler.\nfunc responsibleForPod(pod *v1.Pod, profiles profile.Map) bool {\n\treturn profiles.HandlesSchedulerName(pod.Spec.SchedulerName)\n}","line":{"from":244,"to":247}} {"id":100010652,"name":"addAllEventHandlers","signature":"func addAllEventHandlers(","file":"pkg/scheduler/eventhandlers.go","code":"// addAllEventHandlers is a helper function used in tests and in Scheduler\n// to add event handlers for various informers.\nfunc addAllEventHandlers(\n\tsched *Scheduler,\n\tinformerFactory informers.SharedInformerFactory,\n\tdynInformerFactory dynamicinformer.DynamicSharedInformerFactory,\n\tgvkMap map[framework.GVK]framework.ActionType,\n) {\n\t// scheduled pod cache\n\tinformerFactory.Core().V1().Pods().Informer().AddEventHandler(\n\t\tcache.FilteringResourceEventHandler{\n\t\t\tFilterFunc: func(obj interface{}) bool {\n\t\t\t\tswitch t := obj.(type) {\n\t\t\t\tcase *v1.Pod:\n\t\t\t\t\treturn assignedPod(t)\n\t\t\t\tcase cache.DeletedFinalStateUnknown:\n\t\t\t\t\tif _, ok := t.Obj.(*v1.Pod); ok {\n\t\t\t\t\t\t// The carried object may be stale, so we don't use it to check if\n\t\t\t\t\t\t// it's assigned or not. Attempting to cleanup anyways.\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"unable to convert object %T to *v1.Pod in %T\", obj, sched))\n\t\t\t\t\treturn false\n\t\t\t\tdefault:\n\t\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"unable to handle object in %T: %T\", sched, obj))\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t},\n\t\t\tHandler: cache.ResourceEventHandlerFuncs{\n\t\t\t\tAddFunc: sched.addPodToCache,\n\t\t\t\tUpdateFunc: sched.updatePodInCache,\n\t\t\t\tDeleteFunc: sched.deletePodFromCache,\n\t\t\t},\n\t\t},\n\t)\n\t// unscheduled pod queue\n\tinformerFactory.Core().V1().Pods().Informer().AddEventHandler(\n\t\tcache.FilteringResourceEventHandler{\n\t\t\tFilterFunc: func(obj interface{}) bool {\n\t\t\t\tswitch t := obj.(type) {\n\t\t\t\tcase *v1.Pod:\n\t\t\t\t\treturn !assignedPod(t) \u0026\u0026 responsibleForPod(t, sched.Profiles)\n\t\t\t\tcase cache.DeletedFinalStateUnknown:\n\t\t\t\t\tif pod, ok := t.Obj.(*v1.Pod); ok {\n\t\t\t\t\t\t// The carried object may be stale, so we don't use it to check if\n\t\t\t\t\t\t// it's assigned or not.\n\t\t\t\t\t\treturn responsibleForPod(pod, sched.Profiles)\n\t\t\t\t\t}\n\t\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"unable to convert object %T to *v1.Pod in %T\", obj, sched))\n\t\t\t\t\treturn false\n\t\t\t\tdefault:\n\t\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"unable to handle object in %T: %T\", sched, obj))\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t},\n\t\t\tHandler: cache.ResourceEventHandlerFuncs{\n\t\t\t\tAddFunc: sched.addPodToSchedulingQueue,\n\t\t\t\tUpdateFunc: sched.updatePodInSchedulingQueue,\n\t\t\t\tDeleteFunc: sched.deletePodFromSchedulingQueue,\n\t\t\t},\n\t\t},\n\t)\n\n\tinformerFactory.Core().V1().Nodes().Informer().AddEventHandler(\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: sched.addNodeToCache,\n\t\t\tUpdateFunc: sched.updateNodeInCache,\n\t\t\tDeleteFunc: sched.deleteNodeFromCache,\n\t\t},\n\t)\n\n\tbuildEvtResHandler := func(at framework.ActionType, gvk framework.GVK, shortGVK string) cache.ResourceEventHandlerFuncs {\n\t\tfuncs := cache.ResourceEventHandlerFuncs{}\n\t\tif at\u0026framework.Add != 0 {\n\t\t\tevt := framework.ClusterEvent{Resource: gvk, ActionType: framework.Add, Label: fmt.Sprintf(\"%vAdd\", shortGVK)}\n\t\t\tfuncs.AddFunc = func(_ interface{}) {\n\t\t\t\tsched.SchedulingQueue.MoveAllToActiveOrBackoffQueue(evt, nil)\n\t\t\t}\n\t\t}\n\t\tif at\u0026framework.Update != 0 {\n\t\t\tevt := framework.ClusterEvent{Resource: gvk, ActionType: framework.Update, Label: fmt.Sprintf(\"%vUpdate\", shortGVK)}\n\t\t\tfuncs.UpdateFunc = func(_, _ interface{}) {\n\t\t\t\tsched.SchedulingQueue.MoveAllToActiveOrBackoffQueue(evt, nil)\n\t\t\t}\n\t\t}\n\t\tif at\u0026framework.Delete != 0 {\n\t\t\tevt := framework.ClusterEvent{Resource: gvk, ActionType: framework.Delete, Label: fmt.Sprintf(\"%vDelete\", shortGVK)}\n\t\t\tfuncs.DeleteFunc = func(_ interface{}) {\n\t\t\t\tsched.SchedulingQueue.MoveAllToActiveOrBackoffQueue(evt, nil)\n\t\t\t}\n\t\t}\n\t\treturn funcs\n\t}\n\n\tfor gvk, at := range gvkMap {\n\t\tswitch gvk {\n\t\tcase framework.Node, framework.Pod:\n\t\t\t// Do nothing.\n\t\tcase framework.CSINode:\n\t\t\tinformerFactory.Storage().V1().CSINodes().Informer().AddEventHandler(\n\t\t\t\tbuildEvtResHandler(at, framework.CSINode, \"CSINode\"),\n\t\t\t)\n\t\tcase framework.CSIDriver:\n\t\t\tinformerFactory.Storage().V1().CSIDrivers().Informer().AddEventHandler(\n\t\t\t\tbuildEvtResHandler(at, framework.CSIDriver, \"CSIDriver\"),\n\t\t\t)\n\t\tcase framework.CSIStorageCapacity:\n\t\t\tinformerFactory.Storage().V1().CSIStorageCapacities().Informer().AddEventHandler(\n\t\t\t\tbuildEvtResHandler(at, framework.CSIStorageCapacity, \"CSIStorageCapacity\"),\n\t\t\t)\n\t\tcase framework.PersistentVolume:\n\t\t\t// MaxPDVolumeCountPredicate: since it relies on the counts of PV.\n\t\t\t//\n\t\t\t// PvAdd: Pods created when there are no PVs available will be stuck in\n\t\t\t// unschedulable queue. But unbound PVs created for static provisioning and\n\t\t\t// delay binding storage class are skipped in PV controller dynamic\n\t\t\t// provisioning and binding process, will not trigger events to schedule pod\n\t\t\t// again. So we need to move pods to active queue on PV add for this\n\t\t\t// scenario.\n\t\t\t//\n\t\t\t// PvUpdate: Scheduler.bindVolumesWorker may fail to update assumed pod volume\n\t\t\t// bindings due to conflicts if PVs are updated by PV controller or other\n\t\t\t// parties, then scheduler will add pod back to unschedulable queue. We\n\t\t\t// need to move pods to active queue on PV update for this scenario.\n\t\t\tinformerFactory.Core().V1().PersistentVolumes().Informer().AddEventHandler(\n\t\t\t\tbuildEvtResHandler(at, framework.PersistentVolume, \"Pv\"),\n\t\t\t)\n\t\tcase framework.PersistentVolumeClaim:\n\t\t\t// MaxPDVolumeCountPredicate: add/update PVC will affect counts of PV when it is bound.\n\t\t\tinformerFactory.Core().V1().PersistentVolumeClaims().Informer().AddEventHandler(\n\t\t\t\tbuildEvtResHandler(at, framework.PersistentVolumeClaim, \"Pvc\"),\n\t\t\t)\n\t\tcase framework.PodSchedulingContext:\n\t\t\tif utilfeature.DefaultFeatureGate.Enabled(features.DynamicResourceAllocation) {\n\t\t\t\t_, _ = informerFactory.Resource().V1alpha2().PodSchedulingContexts().Informer().AddEventHandler(\n\t\t\t\t\tbuildEvtResHandler(at, framework.PodSchedulingContext, \"PodSchedulingContext\"),\n\t\t\t\t)\n\t\t\t}\n\t\tcase framework.ResourceClaim:\n\t\t\tif utilfeature.DefaultFeatureGate.Enabled(features.DynamicResourceAllocation) {\n\t\t\t\t_, _ = informerFactory.Resource().V1alpha2().ResourceClaims().Informer().AddEventHandler(\n\t\t\t\t\tbuildEvtResHandler(at, framework.ResourceClaim, \"ResourceClaim\"),\n\t\t\t\t)\n\t\t\t}\n\t\tcase framework.StorageClass:\n\t\t\tif at\u0026framework.Add != 0 {\n\t\t\t\tinformerFactory.Storage().V1().StorageClasses().Informer().AddEventHandler(\n\t\t\t\t\tcache.ResourceEventHandlerFuncs{\n\t\t\t\t\t\tAddFunc: sched.onStorageClassAdd,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tif at\u0026framework.Update != 0 {\n\t\t\t\tinformerFactory.Storage().V1().StorageClasses().Informer().AddEventHandler(\n\t\t\t\t\tcache.ResourceEventHandlerFuncs{\n\t\t\t\t\t\tUpdateFunc: func(_, _ interface{}) {\n\t\t\t\t\t\t\tsched.SchedulingQueue.MoveAllToActiveOrBackoffQueue(queue.StorageClassUpdate, nil)\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\tdefault:\n\t\t\t// Tests may not instantiate dynInformerFactory.\n\t\t\tif dynInformerFactory == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// GVK is expected to be at least 3-folded, separated by dots.\n\t\t\t// \u003ckind in plural\u003e.\u003cversion\u003e.\u003cgroup\u003e\n\t\t\t// Valid examples:\n\t\t\t// - foos.v1.example.com\n\t\t\t// - bars.v1beta1.a.b.c\n\t\t\t// Invalid examples:\n\t\t\t// - foos.v1 (2 sections)\n\t\t\t// - foo.v1.example.com (the first section should be plural)\n\t\t\tif strings.Count(string(gvk), \".\") \u003c 2 {\n\t\t\t\tklog.ErrorS(nil, \"incorrect event registration\", \"gvk\", gvk)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Fall back to try dynamic informers.\n\t\t\tgvr, _ := schema.ParseResourceArg(string(gvk))\n\t\t\tdynInformer := dynInformerFactory.ForResource(*gvr).Informer()\n\t\t\tdynInformer.AddEventHandler(\n\t\t\t\tbuildEvtResHandler(at, gvk, strings.Title(gvr.Resource)),\n\t\t\t)\n\t\t}\n\t}\n}","line":{"from":249,"to":435}} {"id":100010653,"name":"nodeSchedulingPropertiesChange","signature":"func nodeSchedulingPropertiesChange(newNode *v1.Node, oldNode *v1.Node) *framework.ClusterEvent","file":"pkg/scheduler/eventhandlers.go","code":"func nodeSchedulingPropertiesChange(newNode *v1.Node, oldNode *v1.Node) *framework.ClusterEvent {\n\tif nodeSpecUnschedulableChanged(newNode, oldNode) {\n\t\treturn \u0026queue.NodeSpecUnschedulableChange\n\t}\n\tif nodeAllocatableChanged(newNode, oldNode) {\n\t\treturn \u0026queue.NodeAllocatableChange\n\t}\n\tif nodeLabelsChanged(newNode, oldNode) {\n\t\treturn \u0026queue.NodeLabelChange\n\t}\n\tif nodeTaintsChanged(newNode, oldNode) {\n\t\treturn \u0026queue.NodeTaintChange\n\t}\n\tif nodeConditionsChanged(newNode, oldNode) {\n\t\treturn \u0026queue.NodeConditionChange\n\t}\n\n\treturn nil\n}","line":{"from":437,"to":455}} {"id":100010654,"name":"nodeAllocatableChanged","signature":"func nodeAllocatableChanged(newNode *v1.Node, oldNode *v1.Node) bool","file":"pkg/scheduler/eventhandlers.go","code":"func nodeAllocatableChanged(newNode *v1.Node, oldNode *v1.Node) bool {\n\treturn !reflect.DeepEqual(oldNode.Status.Allocatable, newNode.Status.Allocatable)\n}","line":{"from":457,"to":459}} {"id":100010655,"name":"nodeLabelsChanged","signature":"func nodeLabelsChanged(newNode *v1.Node, oldNode *v1.Node) bool","file":"pkg/scheduler/eventhandlers.go","code":"func nodeLabelsChanged(newNode *v1.Node, oldNode *v1.Node) bool {\n\treturn !reflect.DeepEqual(oldNode.GetLabels(), newNode.GetLabels())\n}","line":{"from":461,"to":463}} {"id":100010656,"name":"nodeTaintsChanged","signature":"func nodeTaintsChanged(newNode *v1.Node, oldNode *v1.Node) bool","file":"pkg/scheduler/eventhandlers.go","code":"func nodeTaintsChanged(newNode *v1.Node, oldNode *v1.Node) bool {\n\treturn !reflect.DeepEqual(newNode.Spec.Taints, oldNode.Spec.Taints)\n}","line":{"from":465,"to":467}} {"id":100010657,"name":"nodeConditionsChanged","signature":"func nodeConditionsChanged(newNode *v1.Node, oldNode *v1.Node) bool","file":"pkg/scheduler/eventhandlers.go","code":"func nodeConditionsChanged(newNode *v1.Node, oldNode *v1.Node) bool {\n\tstrip := func(conditions []v1.NodeCondition) map[v1.NodeConditionType]v1.ConditionStatus {\n\t\tconditionStatuses := make(map[v1.NodeConditionType]v1.ConditionStatus, len(conditions))\n\t\tfor i := range conditions {\n\t\t\tconditionStatuses[conditions[i].Type] = conditions[i].Status\n\t\t}\n\t\treturn conditionStatuses\n\t}\n\treturn !reflect.DeepEqual(strip(oldNode.Status.Conditions), strip(newNode.Status.Conditions))\n}","line":{"from":469,"to":478}} {"id":100010658,"name":"nodeSpecUnschedulableChanged","signature":"func nodeSpecUnschedulableChanged(newNode *v1.Node, oldNode *v1.Node) bool","file":"pkg/scheduler/eventhandlers.go","code":"func nodeSpecUnschedulableChanged(newNode *v1.Node, oldNode *v1.Node) bool {\n\treturn newNode.Spec.Unschedulable != oldNode.Spec.Unschedulable \u0026\u0026 !newNode.Spec.Unschedulable\n}","line":{"from":480,"to":482}} {"id":100010659,"name":"preCheckForNode","signature":"func preCheckForNode(nodeInfo *framework.NodeInfo) queue.PreEnqueueCheck","file":"pkg/scheduler/eventhandlers.go","code":"func preCheckForNode(nodeInfo *framework.NodeInfo) queue.PreEnqueueCheck {\n\t// Note: the following checks doesn't take preemption into considerations, in very rare\n\t// cases (e.g., node resizing), \"pod\" may still fail a check but preemption helps. We deliberately\n\t// chose to ignore those cases as unschedulable pods will be re-queued eventually.\n\treturn func(pod *v1.Pod) bool {\n\t\tadmissionResults := AdmissionCheck(pod, nodeInfo, false)\n\t\tif len(admissionResults) != 0 {\n\t\t\treturn false\n\t\t}\n\t\t_, isUntolerated := corev1helpers.FindMatchingUntoleratedTaint(nodeInfo.Node().Spec.Taints, pod.Spec.Tolerations, func(t *v1.Taint) bool {\n\t\t\treturn t.Effect == v1.TaintEffectNoSchedule\n\t\t})\n\t\treturn !isUntolerated\n\t}\n}","line":{"from":484,"to":498}} {"id":100010660,"name":"AdmissionCheck","signature":"func AdmissionCheck(pod *v1.Pod, nodeInfo *framework.NodeInfo, includeAllFailures bool) []AdmissionResult","file":"pkg/scheduler/eventhandlers.go","code":"// AdmissionCheck calls the filtering logic of noderesources/nodeport/nodeAffinity/nodename\n// and returns the failure reasons. It's used in kubelet(pkg/kubelet/lifecycle/predicate.go) and scheduler.\n// It returns the first failure if `includeAllFailures` is set to false; otherwise\n// returns all failures.\nfunc AdmissionCheck(pod *v1.Pod, nodeInfo *framework.NodeInfo, includeAllFailures bool) []AdmissionResult {\n\tvar admissionResults []AdmissionResult\n\tinsufficientResources := noderesources.Fits(pod, nodeInfo)\n\tif len(insufficientResources) != 0 {\n\t\tfor i := range insufficientResources {\n\t\t\tadmissionResults = append(admissionResults, AdmissionResult{InsufficientResource: \u0026insufficientResources[i]})\n\t\t}\n\t\tif !includeAllFailures {\n\t\t\treturn admissionResults\n\t\t}\n\t}\n\n\tif matches, _ := corev1nodeaffinity.GetRequiredNodeAffinity(pod).Match(nodeInfo.Node()); !matches {\n\t\tadmissionResults = append(admissionResults, AdmissionResult{Name: nodeaffinity.Name, Reason: nodeaffinity.ErrReasonPod})\n\t\tif !includeAllFailures {\n\t\t\treturn admissionResults\n\t\t}\n\t}\n\tif !nodename.Fits(pod, nodeInfo) {\n\t\tadmissionResults = append(admissionResults, AdmissionResult{Name: nodename.Name, Reason: nodename.ErrReason})\n\t\tif !includeAllFailures {\n\t\t\treturn admissionResults\n\t\t}\n\t}\n\tif !nodeports.Fits(pod, nodeInfo) {\n\t\tadmissionResults = append(admissionResults, AdmissionResult{Name: nodeports.Name, Reason: nodeports.ErrReason})\n\t\tif !includeAllFailures {\n\t\t\treturn admissionResults\n\t\t}\n\t}\n\treturn admissionResults\n}","line":{"from":500,"to":535}} {"id":100010661,"name":"makeTransport","signature":"func makeTransport(config *schedulerapi.Extender) (http.RoundTripper, error)","file":"pkg/scheduler/extender.go","code":"func makeTransport(config *schedulerapi.Extender) (http.RoundTripper, error) {\n\tvar cfg restclient.Config\n\tif config.TLSConfig != nil {\n\t\tcfg.TLSClientConfig.Insecure = config.TLSConfig.Insecure\n\t\tcfg.TLSClientConfig.ServerName = config.TLSConfig.ServerName\n\t\tcfg.TLSClientConfig.CertFile = config.TLSConfig.CertFile\n\t\tcfg.TLSClientConfig.KeyFile = config.TLSConfig.KeyFile\n\t\tcfg.TLSClientConfig.CAFile = config.TLSConfig.CAFile\n\t\tcfg.TLSClientConfig.CertData = config.TLSConfig.CertData\n\t\tcfg.TLSClientConfig.KeyData = config.TLSConfig.KeyData\n\t\tcfg.TLSClientConfig.CAData = config.TLSConfig.CAData\n\t}\n\tif config.EnableHTTPS {\n\t\thasCA := len(cfg.CAFile) \u003e 0 || len(cfg.CAData) \u003e 0\n\t\tif !hasCA {\n\t\t\tcfg.Insecure = true\n\t\t}\n\t}\n\ttlsConfig, err := restclient.TLSConfigFor(\u0026cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif tlsConfig != nil {\n\t\treturn utilnet.SetTransportDefaults(\u0026http.Transport{\n\t\t\tTLSClientConfig: tlsConfig,\n\t\t}), nil\n\t}\n\treturn utilnet.SetTransportDefaults(\u0026http.Transport{}), nil\n}","line":{"from":55,"to":83}} {"id":100010662,"name":"NewHTTPExtender","signature":"func NewHTTPExtender(config *schedulerapi.Extender) (framework.Extender, error)","file":"pkg/scheduler/extender.go","code":"// NewHTTPExtender creates an HTTPExtender object.\nfunc NewHTTPExtender(config *schedulerapi.Extender) (framework.Extender, error) {\n\tif config.HTTPTimeout.Duration.Nanoseconds() == 0 {\n\t\tconfig.HTTPTimeout.Duration = time.Duration(DefaultExtenderTimeout)\n\t}\n\n\ttransport, err := makeTransport(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := \u0026http.Client{\n\t\tTransport: transport,\n\t\tTimeout: config.HTTPTimeout.Duration,\n\t}\n\tmanagedResources := sets.NewString()\n\tfor _, r := range config.ManagedResources {\n\t\tmanagedResources.Insert(string(r.Name))\n\t}\n\treturn \u0026HTTPExtender{\n\t\textenderURL: config.URLPrefix,\n\t\tpreemptVerb: config.PreemptVerb,\n\t\tfilterVerb: config.FilterVerb,\n\t\tprioritizeVerb: config.PrioritizeVerb,\n\t\tbindVerb: config.BindVerb,\n\t\tweight: config.Weight,\n\t\tclient: client,\n\t\tnodeCacheCapable: config.NodeCacheCapable,\n\t\tmanagedResources: managedResources,\n\t\tignorable: config.Ignorable,\n\t}, nil\n}","line":{"from":85,"to":115}} {"id":100010663,"name":"Name","signature":"func (h *HTTPExtender) Name() string","file":"pkg/scheduler/extender.go","code":"// Name returns extenderURL to identify the extender.\nfunc (h *HTTPExtender) Name() string {\n\treturn h.extenderURL\n}","line":{"from":117,"to":120}} {"id":100010664,"name":"IsIgnorable","signature":"func (h *HTTPExtender) IsIgnorable() bool","file":"pkg/scheduler/extender.go","code":"// IsIgnorable returns true indicates scheduling should not fail when this extender\n// is unavailable\nfunc (h *HTTPExtender) IsIgnorable() bool {\n\treturn h.ignorable\n}","line":{"from":122,"to":126}} {"id":100010665,"name":"SupportsPreemption","signature":"func (h *HTTPExtender) SupportsPreemption() bool","file":"pkg/scheduler/extender.go","code":"// SupportsPreemption returns true if an extender supports preemption.\n// An extender should have preempt verb defined and enabled its own node cache.\nfunc (h *HTTPExtender) SupportsPreemption() bool {\n\treturn len(h.preemptVerb) \u003e 0\n}","line":{"from":128,"to":132}} {"id":100010666,"name":"ProcessPreemption","signature":"func (h *HTTPExtender) ProcessPreemption(","file":"pkg/scheduler/extender.go","code":"// ProcessPreemption returns filtered candidate nodes and victims after running preemption logic in extender.\nfunc (h *HTTPExtender) ProcessPreemption(\n\tpod *v1.Pod,\n\tnodeNameToVictims map[string]*extenderv1.Victims,\n\tnodeInfos framework.NodeInfoLister,\n) (map[string]*extenderv1.Victims, error) {\n\tvar (\n\t\tresult extenderv1.ExtenderPreemptionResult\n\t\targs *extenderv1.ExtenderPreemptionArgs\n\t)\n\n\tif !h.SupportsPreemption() {\n\t\treturn nil, fmt.Errorf(\"preempt verb is not defined for extender %v but run into ProcessPreemption\", h.extenderURL)\n\t}\n\n\tif h.nodeCacheCapable {\n\t\t// If extender has cached node info, pass NodeNameToMetaVictims in args.\n\t\tnodeNameToMetaVictims := convertToMetaVictims(nodeNameToVictims)\n\t\targs = \u0026extenderv1.ExtenderPreemptionArgs{\n\t\t\tPod: pod,\n\t\t\tNodeNameToMetaVictims: nodeNameToMetaVictims,\n\t\t}\n\t} else {\n\t\targs = \u0026extenderv1.ExtenderPreemptionArgs{\n\t\t\tPod: pod,\n\t\t\tNodeNameToVictims: nodeNameToVictims,\n\t\t}\n\t}\n\n\tif err := h.send(h.preemptVerb, args, \u0026result); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Extender will always return NodeNameToMetaVictims.\n\t// So let's convert it to NodeNameToVictims by using \u003cnodeInfos\u003e.\n\tnewNodeNameToVictims, err := h.convertToVictims(result.NodeNameToMetaVictims, nodeInfos)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Do not override \u003cnodeNameToVictims\u003e.\n\treturn newNodeNameToVictims, nil\n}","line":{"from":134,"to":175}} {"id":100010667,"name":"convertToVictims","signature":"func (h *HTTPExtender) convertToVictims(","file":"pkg/scheduler/extender.go","code":"// convertToVictims converts \"nodeNameToMetaVictims\" from object identifiers,\n// such as UIDs and names, to object pointers.\nfunc (h *HTTPExtender) convertToVictims(\n\tnodeNameToMetaVictims map[string]*extenderv1.MetaVictims,\n\tnodeInfos framework.NodeInfoLister,\n) (map[string]*extenderv1.Victims, error) {\n\tnodeNameToVictims := map[string]*extenderv1.Victims{}\n\tfor nodeName, metaVictims := range nodeNameToMetaVictims {\n\t\tnodeInfo, err := nodeInfos.Get(nodeName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvictims := \u0026extenderv1.Victims{\n\t\t\tPods: []*v1.Pod{},\n\t\t\tNumPDBViolations: metaVictims.NumPDBViolations,\n\t\t}\n\t\tfor _, metaPod := range metaVictims.Pods {\n\t\t\tpod, err := h.convertPodUIDToPod(metaPod, nodeInfo)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tvictims.Pods = append(victims.Pods, pod)\n\t\t}\n\t\tnodeNameToVictims[nodeName] = victims\n\t}\n\treturn nodeNameToVictims, nil\n}","line":{"from":177,"to":203}} {"id":100010668,"name":"convertPodUIDToPod","signature":"func (h *HTTPExtender) convertPodUIDToPod(","file":"pkg/scheduler/extender.go","code":"// convertPodUIDToPod returns v1.Pod object for given MetaPod and node info.\n// The v1.Pod object is restored by nodeInfo.Pods().\n// It returns an error if there's cache inconsistency between default scheduler\n// and extender, i.e. when the pod is not found in nodeInfo.Pods.\nfunc (h *HTTPExtender) convertPodUIDToPod(\n\tmetaPod *extenderv1.MetaPod,\n\tnodeInfo *framework.NodeInfo) (*v1.Pod, error) {\n\tfor _, p := range nodeInfo.Pods {\n\t\tif string(p.Pod.UID) == metaPod.UID {\n\t\t\treturn p.Pod, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"extender: %v claims to preempt pod (UID: %v) on node: %v, but the pod is not found on that node\",\n\t\th.extenderURL, metaPod, nodeInfo.Node().Name)\n}","line":{"from":205,"to":219}} {"id":100010669,"name":"convertToMetaVictims","signature":"func convertToMetaVictims(","file":"pkg/scheduler/extender.go","code":"// convertToMetaVictims converts from struct type to meta types.\nfunc convertToMetaVictims(\n\tnodeNameToVictims map[string]*extenderv1.Victims,\n) map[string]*extenderv1.MetaVictims {\n\tnodeNameToMetaVictims := map[string]*extenderv1.MetaVictims{}\n\tfor node, victims := range nodeNameToVictims {\n\t\tmetaVictims := \u0026extenderv1.MetaVictims{\n\t\t\tPods: []*extenderv1.MetaPod{},\n\t\t\tNumPDBViolations: victims.NumPDBViolations,\n\t\t}\n\t\tfor _, pod := range victims.Pods {\n\t\t\tmetaPod := \u0026extenderv1.MetaPod{\n\t\t\t\tUID: string(pod.UID),\n\t\t\t}\n\t\t\tmetaVictims.Pods = append(metaVictims.Pods, metaPod)\n\t\t}\n\t\tnodeNameToMetaVictims[node] = metaVictims\n\t}\n\treturn nodeNameToMetaVictims\n}","line":{"from":221,"to":240}} {"id":100010670,"name":"Filter","signature":"func (h *HTTPExtender) Filter(","file":"pkg/scheduler/extender.go","code":"// Filter based on extender implemented predicate functions. The filtered list is\n// expected to be a subset of the supplied list; otherwise the function returns an error.\n// The failedNodes and failedAndUnresolvableNodes optionally contains the list\n// of failed nodes and failure reasons, except nodes in the latter are\n// unresolvable.\nfunc (h *HTTPExtender) Filter(\n\tpod *v1.Pod,\n\tnodes []*v1.Node,\n) (filteredList []*v1.Node, failedNodes, failedAndUnresolvableNodes extenderv1.FailedNodesMap, err error) {\n\tvar (\n\t\tresult extenderv1.ExtenderFilterResult\n\t\tnodeList *v1.NodeList\n\t\tnodeNames *[]string\n\t\tnodeResult []*v1.Node\n\t\targs *extenderv1.ExtenderArgs\n\t)\n\tfromNodeName := make(map[string]*v1.Node)\n\tfor _, n := range nodes {\n\t\tfromNodeName[n.Name] = n\n\t}\n\n\tif h.filterVerb == \"\" {\n\t\treturn nodes, extenderv1.FailedNodesMap{}, extenderv1.FailedNodesMap{}, nil\n\t}\n\n\tif h.nodeCacheCapable {\n\t\tnodeNameSlice := make([]string, 0, len(nodes))\n\t\tfor _, node := range nodes {\n\t\t\tnodeNameSlice = append(nodeNameSlice, node.Name)\n\t\t}\n\t\tnodeNames = \u0026nodeNameSlice\n\t} else {\n\t\tnodeList = \u0026v1.NodeList{}\n\t\tfor _, node := range nodes {\n\t\t\tnodeList.Items = append(nodeList.Items, *node)\n\t\t}\n\t}\n\n\targs = \u0026extenderv1.ExtenderArgs{\n\t\tPod: pod,\n\t\tNodes: nodeList,\n\t\tNodeNames: nodeNames,\n\t}\n\n\tif err := h.send(h.filterVerb, args, \u0026result); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tif result.Error != \"\" {\n\t\treturn nil, nil, nil, fmt.Errorf(result.Error)\n\t}\n\n\tif h.nodeCacheCapable \u0026\u0026 result.NodeNames != nil {\n\t\tnodeResult = make([]*v1.Node, len(*result.NodeNames))\n\t\tfor i, nodeName := range *result.NodeNames {\n\t\t\tif n, ok := fromNodeName[nodeName]; ok {\n\t\t\t\tnodeResult[i] = n\n\t\t\t} else {\n\t\t\t\treturn nil, nil, nil, fmt.Errorf(\n\t\t\t\t\t\"extender %q claims a filtered node %q which is not found in the input node list\",\n\t\t\t\t\th.extenderURL, nodeName)\n\t\t\t}\n\t\t}\n\t} else if result.Nodes != nil {\n\t\tnodeResult = make([]*v1.Node, len(result.Nodes.Items))\n\t\tfor i := range result.Nodes.Items {\n\t\t\tnodeResult[i] = \u0026result.Nodes.Items[i]\n\t\t}\n\t}\n\n\treturn nodeResult, result.FailedNodes, result.FailedAndUnresolvableNodes, nil\n}","line":{"from":242,"to":312}} {"id":100010671,"name":"Prioritize","signature":"func (h *HTTPExtender) Prioritize(pod *v1.Pod, nodes []*v1.Node) (*extenderv1.HostPriorityList, int64, error)","file":"pkg/scheduler/extender.go","code":"// Prioritize based on extender implemented priority functions. Weight*priority is added\n// up for each such priority function. The returned score is added to the score computed\n// by Kubernetes scheduler. The total score is used to do the host selection.\nfunc (h *HTTPExtender) Prioritize(pod *v1.Pod, nodes []*v1.Node) (*extenderv1.HostPriorityList, int64, error) {\n\tvar (\n\t\tresult extenderv1.HostPriorityList\n\t\tnodeList *v1.NodeList\n\t\tnodeNames *[]string\n\t\targs *extenderv1.ExtenderArgs\n\t)\n\n\tif h.prioritizeVerb == \"\" {\n\t\tresult := extenderv1.HostPriorityList{}\n\t\tfor _, node := range nodes {\n\t\t\tresult = append(result, extenderv1.HostPriority{Host: node.Name, Score: 0})\n\t\t}\n\t\treturn \u0026result, 0, nil\n\t}\n\n\tif h.nodeCacheCapable {\n\t\tnodeNameSlice := make([]string, 0, len(nodes))\n\t\tfor _, node := range nodes {\n\t\t\tnodeNameSlice = append(nodeNameSlice, node.Name)\n\t\t}\n\t\tnodeNames = \u0026nodeNameSlice\n\t} else {\n\t\tnodeList = \u0026v1.NodeList{}\n\t\tfor _, node := range nodes {\n\t\t\tnodeList.Items = append(nodeList.Items, *node)\n\t\t}\n\t}\n\n\targs = \u0026extenderv1.ExtenderArgs{\n\t\tPod: pod,\n\t\tNodes: nodeList,\n\t\tNodeNames: nodeNames,\n\t}\n\n\tif err := h.send(h.prioritizeVerb, args, \u0026result); err != nil {\n\t\treturn nil, 0, err\n\t}\n\treturn \u0026result, h.weight, nil\n}","line":{"from":314,"to":356}} {"id":100010672,"name":"Bind","signature":"func (h *HTTPExtender) Bind(binding *v1.Binding) error","file":"pkg/scheduler/extender.go","code":"// Bind delegates the action of binding a pod to a node to the extender.\nfunc (h *HTTPExtender) Bind(binding *v1.Binding) error {\n\tvar result extenderv1.ExtenderBindingResult\n\tif !h.IsBinder() {\n\t\t// This shouldn't happen as this extender wouldn't have become a Binder.\n\t\treturn fmt.Errorf(\"unexpected empty bindVerb in extender\")\n\t}\n\treq := \u0026extenderv1.ExtenderBindingArgs{\n\t\tPodName: binding.Name,\n\t\tPodNamespace: binding.Namespace,\n\t\tPodUID: binding.UID,\n\t\tNode: binding.Target.Name,\n\t}\n\tif err := h.send(h.bindVerb, req, \u0026result); err != nil {\n\t\treturn err\n\t}\n\tif result.Error != \"\" {\n\t\treturn fmt.Errorf(result.Error)\n\t}\n\treturn nil\n}","line":{"from":358,"to":378}} {"id":100010673,"name":"IsBinder","signature":"func (h *HTTPExtender) IsBinder() bool","file":"pkg/scheduler/extender.go","code":"// IsBinder returns whether this extender is configured for the Bind method.\nfunc (h *HTTPExtender) IsBinder() bool {\n\treturn h.bindVerb != \"\"\n}","line":{"from":380,"to":383}} {"id":100010674,"name":"send","signature":"func (h *HTTPExtender) send(action string, args interface{}, result interface{}) error","file":"pkg/scheduler/extender.go","code":"// Helper function to send messages to the extender\nfunc (h *HTTPExtender) send(action string, args interface{}, result interface{}) error {\n\tout, err := json.Marshal(args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\turl := strings.TrimRight(h.extenderURL, \"/\") + \"/\" + action\n\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewReader(out))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tresp, err := h.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"failed %v with extender at URL %v, code %v\", action, url, resp.StatusCode)\n\t}\n\n\treturn json.NewDecoder(resp.Body).Decode(result)\n}","line":{"from":385,"to":412}} {"id":100010675,"name":"IsInterested","signature":"func (h *HTTPExtender) IsInterested(pod *v1.Pod) bool","file":"pkg/scheduler/extender.go","code":"// IsInterested returns true if at least one extended resource requested by\n// this pod is managed by this extender.\nfunc (h *HTTPExtender) IsInterested(pod *v1.Pod) bool {\n\tif h.managedResources.Len() == 0 {\n\t\treturn true\n\t}\n\tif h.hasManagedResources(pod.Spec.Containers) {\n\t\treturn true\n\t}\n\tif h.hasManagedResources(pod.Spec.InitContainers) {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":414,"to":427}} {"id":100010676,"name":"hasManagedResources","signature":"func (h *HTTPExtender) hasManagedResources(containers []v1.Container) bool","file":"pkg/scheduler/extender.go","code":"func (h *HTTPExtender) hasManagedResources(containers []v1.Container) bool {\n\tfor i := range containers {\n\t\tcontainer := \u0026containers[i]\n\t\tfor resourceName := range container.Resources.Requests {\n\t\t\tif h.managedResources.Has(string(resourceName)) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\tfor resourceName := range container.Resources.Limits {\n\t\t\tif h.managedResources.Has(string(resourceName)) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":429,"to":444}} {"id":100010677,"name":"NewCycleState","signature":"func NewCycleState() *CycleState","file":"pkg/scheduler/framework/cycle_state.go","code":"// NewCycleState initializes a new CycleState and returns its pointer.\nfunc NewCycleState() *CycleState {\n\treturn \u0026CycleState{}\n}","line":{"from":59,"to":62}} {"id":100010678,"name":"ShouldRecordPluginMetrics","signature":"func (c *CycleState) ShouldRecordPluginMetrics() bool","file":"pkg/scheduler/framework/cycle_state.go","code":"// ShouldRecordPluginMetrics returns whether PluginExecutionDuration metrics should be recorded.\nfunc (c *CycleState) ShouldRecordPluginMetrics() bool {\n\tif c == nil {\n\t\treturn false\n\t}\n\treturn c.recordPluginMetrics\n}","line":{"from":64,"to":70}} {"id":100010679,"name":"SetRecordPluginMetrics","signature":"func (c *CycleState) SetRecordPluginMetrics(flag bool)","file":"pkg/scheduler/framework/cycle_state.go","code":"// SetRecordPluginMetrics sets recordPluginMetrics to the given value.\nfunc (c *CycleState) SetRecordPluginMetrics(flag bool) {\n\tif c == nil {\n\t\treturn\n\t}\n\tc.recordPluginMetrics = flag\n}","line":{"from":72,"to":78}} {"id":100010680,"name":"Clone","signature":"func (c *CycleState) Clone() *CycleState","file":"pkg/scheduler/framework/cycle_state.go","code":"// Clone creates a copy of CycleState and returns its pointer. Clone returns\n// nil if the context being cloned is nil.\nfunc (c *CycleState) Clone() *CycleState {\n\tif c == nil {\n\t\treturn nil\n\t}\n\tcopy := NewCycleState()\n\tc.storage.Range(func(k, v interface{}) bool {\n\t\tcopy.storage.Store(k, v.(StateData).Clone())\n\t\treturn true\n\t})\n\tcopy.recordPluginMetrics = c.recordPluginMetrics\n\tcopy.SkipFilterPlugins = c.SkipFilterPlugins\n\tcopy.SkipScorePlugins = c.SkipScorePlugins\n\n\treturn copy\n}","line":{"from":80,"to":96}} {"id":100010681,"name":"Read","signature":"func (c *CycleState) Read(key StateKey) (StateData, error)","file":"pkg/scheduler/framework/cycle_state.go","code":"// Read retrieves data with the given \"key\" from CycleState. If the key is not\n// present an error is returned.\n// This function is thread safe by using sync.Map.\nfunc (c *CycleState) Read(key StateKey) (StateData, error) {\n\tif v, ok := c.storage.Load(key); ok {\n\t\treturn v.(StateData), nil\n\t}\n\treturn nil, ErrNotFound\n}","line":{"from":98,"to":106}} {"id":100010682,"name":"Write","signature":"func (c *CycleState) Write(key StateKey, val StateData)","file":"pkg/scheduler/framework/cycle_state.go","code":"// Write stores the given \"val\" in CycleState with the given \"key\".\n// This function is thread safe by using sync.Map.\nfunc (c *CycleState) Write(key StateKey, val StateData) {\n\tc.storage.Store(key, val)\n}","line":{"from":108,"to":112}} {"id":100010683,"name":"Delete","signature":"func (c *CycleState) Delete(key StateKey)","file":"pkg/scheduler/framework/cycle_state.go","code":"// Delete deletes data with the given key from CycleState.\n// This function is thread safe by using sync.Map.\nfunc (c *CycleState) Delete(key StateKey) {\n\tc.storage.Delete(key)\n}","line":{"from":114,"to":118}} {"id":100010684,"name":"String","signature":"func (c Code) String() string","file":"pkg/scheduler/framework/interface.go","code":"func (c Code) String() string {\n\treturn codes[c]\n}","line":{"from":104,"to":106}} {"id":100010685,"name":"Clone","signature":"func (s *PodsToActivate) Clone() StateData","file":"pkg/scheduler/framework/interface.go","code":"// Clone just returns the same state.\nfunc (s *PodsToActivate) Clone() StateData {\n\treturn s\n}","line":{"from":133,"to":136}} {"id":100010686,"name":"NewPodsToActivate","signature":"func NewPodsToActivate() *PodsToActivate","file":"pkg/scheduler/framework/interface.go","code":"// NewPodsToActivate instantiates a PodsToActivate object.\nfunc NewPodsToActivate() *PodsToActivate {\n\treturn \u0026PodsToActivate{Map: make(map[string]*v1.Pod)}\n}","line":{"from":138,"to":141}} {"id":100010687,"name":"WithError","signature":"func (s *Status) WithError(err error) *Status","file":"pkg/scheduler/framework/interface.go","code":"func (s *Status) WithError(err error) *Status {\n\ts.err = err\n\treturn s\n}","line":{"from":157,"to":160}} {"id":100010688,"name":"Code","signature":"func (s *Status) Code() Code","file":"pkg/scheduler/framework/interface.go","code":"// Code returns code of the Status.\nfunc (s *Status) Code() Code {\n\tif s == nil {\n\t\treturn Success\n\t}\n\treturn s.code\n}","line":{"from":162,"to":168}} {"id":100010689,"name":"Message","signature":"func (s *Status) Message() string","file":"pkg/scheduler/framework/interface.go","code":"// Message returns a concatenated message on reasons of the Status.\nfunc (s *Status) Message() string {\n\tif s == nil {\n\t\treturn \"\"\n\t}\n\treturn strings.Join(s.Reasons(), \", \")\n}","line":{"from":170,"to":176}} {"id":100010690,"name":"SetFailedPlugin","signature":"func (s *Status) SetFailedPlugin(plugin string)","file":"pkg/scheduler/framework/interface.go","code":"// SetFailedPlugin sets the given plugin name to s.failedPlugin.\nfunc (s *Status) SetFailedPlugin(plugin string) {\n\ts.failedPlugin = plugin\n}","line":{"from":178,"to":181}} {"id":100010691,"name":"WithFailedPlugin","signature":"func (s *Status) WithFailedPlugin(plugin string) *Status","file":"pkg/scheduler/framework/interface.go","code":"// WithFailedPlugin sets the given plugin name to s.failedPlugin,\n// and returns the given status object.\nfunc (s *Status) WithFailedPlugin(plugin string) *Status {\n\ts.SetFailedPlugin(plugin)\n\treturn s\n}","line":{"from":183,"to":188}} {"id":100010692,"name":"FailedPlugin","signature":"func (s *Status) FailedPlugin() string","file":"pkg/scheduler/framework/interface.go","code":"// FailedPlugin returns the failed plugin name.\nfunc (s *Status) FailedPlugin() string {\n\treturn s.failedPlugin\n}","line":{"from":190,"to":193}} {"id":100010693,"name":"Reasons","signature":"func (s *Status) Reasons() []string","file":"pkg/scheduler/framework/interface.go","code":"// Reasons returns reasons of the Status.\nfunc (s *Status) Reasons() []string {\n\tif s.err != nil {\n\t\treturn append([]string{s.err.Error()}, s.reasons...)\n\t}\n\treturn s.reasons\n}","line":{"from":195,"to":201}} {"id":100010694,"name":"AppendReason","signature":"func (s *Status) AppendReason(reason string)","file":"pkg/scheduler/framework/interface.go","code":"// AppendReason appends given reason to the Status.\nfunc (s *Status) AppendReason(reason string) {\n\ts.reasons = append(s.reasons, reason)\n}","line":{"from":203,"to":206}} {"id":100010695,"name":"IsSuccess","signature":"func (s *Status) IsSuccess() bool","file":"pkg/scheduler/framework/interface.go","code":"// IsSuccess returns true if and only if \"Status\" is nil or Code is \"Success\".\nfunc (s *Status) IsSuccess() bool {\n\treturn s.Code() == Success\n}","line":{"from":208,"to":211}} {"id":100010696,"name":"IsWait","signature":"func (s *Status) IsWait() bool","file":"pkg/scheduler/framework/interface.go","code":"// IsWait returns true if and only if \"Status\" is non-nil and its Code is \"Wait\".\nfunc (s *Status) IsWait() bool {\n\treturn s.Code() == Wait\n}","line":{"from":213,"to":216}} {"id":100010697,"name":"IsSkip","signature":"func (s *Status) IsSkip() bool","file":"pkg/scheduler/framework/interface.go","code":"// IsSkip returns true if and only if \"Status\" is non-nil and its Code is \"Skip\".\nfunc (s *Status) IsSkip() bool {\n\treturn s.Code() == Skip\n}","line":{"from":218,"to":221}} {"id":100010698,"name":"IsUnschedulable","signature":"func (s *Status) IsUnschedulable() bool","file":"pkg/scheduler/framework/interface.go","code":"// IsUnschedulable returns true if \"Status\" is Unschedulable (Unschedulable or UnschedulableAndUnresolvable).\nfunc (s *Status) IsUnschedulable() bool {\n\tcode := s.Code()\n\treturn code == Unschedulable || code == UnschedulableAndUnresolvable\n}","line":{"from":223,"to":227}} {"id":100010699,"name":"AsError","signature":"func (s *Status) AsError() error","file":"pkg/scheduler/framework/interface.go","code":"// AsError returns nil if the status is a success, a wait or a skip; otherwise returns an \"error\" object\n// with a concatenated message on reasons of the Status.\nfunc (s *Status) AsError() error {\n\tif s.IsSuccess() || s.IsWait() || s.IsSkip() {\n\t\treturn nil\n\t}\n\tif s.err != nil {\n\t\treturn s.err\n\t}\n\treturn errors.New(s.Message())\n}","line":{"from":229,"to":239}} {"id":100010700,"name":"Equal","signature":"func (s *Status) Equal(x *Status) bool","file":"pkg/scheduler/framework/interface.go","code":"// Equal checks equality of two statuses. This is useful for testing with\n// cmp.Equal.\nfunc (s *Status) Equal(x *Status) bool {\n\tif s == nil || x == nil {\n\t\treturn s.IsSuccess() \u0026\u0026 x.IsSuccess()\n\t}\n\tif s.code != x.code {\n\t\treturn false\n\t}\n\tif !cmp.Equal(s.err, x.err, cmpopts.EquateErrors()) {\n\t\treturn false\n\t}\n\tif !cmp.Equal(s.reasons, x.reasons) {\n\t\treturn false\n\t}\n\treturn cmp.Equal(s.failedPlugin, x.failedPlugin)\n}","line":{"from":241,"to":257}} {"id":100010701,"name":"NewStatus","signature":"func NewStatus(code Code, reasons ...string) *Status","file":"pkg/scheduler/framework/interface.go","code":"// NewStatus makes a Status out of the given arguments and returns its pointer.\nfunc NewStatus(code Code, reasons ...string) *Status {\n\ts := \u0026Status{\n\t\tcode: code,\n\t\treasons: reasons,\n\t}\n\treturn s\n}","line":{"from":259,"to":266}} {"id":100010702,"name":"AsStatus","signature":"func AsStatus(err error) *Status","file":"pkg/scheduler/framework/interface.go","code":"// AsStatus wraps an error in a Status.\nfunc AsStatus(err error) *Status {\n\tif err == nil {\n\t\treturn nil\n\t}\n\treturn \u0026Status{\n\t\tcode: Error,\n\t\terr: err,\n\t}\n}","line":{"from":268,"to":277}} {"id":100010703,"name":"AllNodes","signature":"func (p *PreFilterResult) AllNodes() bool","file":"pkg/scheduler/framework/interface.go","code":"func (p *PreFilterResult) AllNodes() bool {\n\treturn p == nil || p.NodeNames == nil\n}","line":{"from":647,"to":649}} {"id":100010704,"name":"Merge","signature":"func (p *PreFilterResult) Merge(in *PreFilterResult) *PreFilterResult","file":"pkg/scheduler/framework/interface.go","code":"func (p *PreFilterResult) Merge(in *PreFilterResult) *PreFilterResult {\n\tif p.AllNodes() \u0026\u0026 in.AllNodes() {\n\t\treturn nil\n\t}\n\n\tr := PreFilterResult{}\n\tif p.AllNodes() {\n\t\tr.NodeNames = in.NodeNames.Clone()\n\t\treturn \u0026r\n\t}\n\tif in.AllNodes() {\n\t\tr.NodeNames = p.NodeNames.Clone()\n\t\treturn \u0026r\n\t}\n\n\tr.NodeNames = p.NodeNames.Intersection(in.NodeNames)\n\treturn \u0026r\n}","line":{"from":651,"to":668}} {"id":100010705,"name":"NewPostFilterResultWithNominatedNode","signature":"func NewPostFilterResultWithNominatedNode(name string) *PostFilterResult","file":"pkg/scheduler/framework/interface.go","code":"func NewPostFilterResultWithNominatedNode(name string) *PostFilterResult {\n\treturn \u0026PostFilterResult{\n\t\tNominatingInfo: \u0026NominatingInfo{\n\t\t\tNominatedNodeName: name,\n\t\t\tNominatingMode: ModeOverride,\n\t\t},\n\t}\n}","line":{"from":687,"to":694}} {"id":100010706,"name":"Mode","signature":"func (ni *NominatingInfo) Mode() NominatingMode","file":"pkg/scheduler/framework/interface.go","code":"func (ni *NominatingInfo) Mode() NominatingMode {\n\tif ni == nil {\n\t\treturn ModeNoop\n\t}\n\treturn ni.NominatingMode\n}","line":{"from":696,"to":701}} {"id":100010707,"name":"SendError","signature":"func (e *ErrorChannel) SendError(err error)","file":"pkg/scheduler/framework/parallelize/error_channel.go","code":"// SendError sends an error without blocking the sender.\nfunc (e *ErrorChannel) SendError(err error) {\n\tselect {\n\tcase e.errCh \u003c- err:\n\tdefault:\n\t}\n}","line":{"from":29,"to":35}} {"id":100010708,"name":"SendErrorWithCancel","signature":"func (e *ErrorChannel) SendErrorWithCancel(err error, cancel context.CancelFunc)","file":"pkg/scheduler/framework/parallelize/error_channel.go","code":"// SendErrorWithCancel sends an error without blocking the sender and calls\n// cancel function.\nfunc (e *ErrorChannel) SendErrorWithCancel(err error, cancel context.CancelFunc) {\n\te.SendError(err)\n\tcancel()\n}","line":{"from":37,"to":42}} {"id":100010709,"name":"ReceiveError","signature":"func (e *ErrorChannel) ReceiveError() error","file":"pkg/scheduler/framework/parallelize/error_channel.go","code":"// ReceiveError receives an error from channel without blocking on the receiver.\nfunc (e *ErrorChannel) ReceiveError() error {\n\tselect {\n\tcase err := \u003c-e.errCh:\n\t\treturn err\n\tdefault:\n\t\treturn nil\n\t}\n}","line":{"from":44,"to":52}} {"id":100010710,"name":"NewErrorChannel","signature":"func NewErrorChannel() *ErrorChannel","file":"pkg/scheduler/framework/parallelize/error_channel.go","code":"// NewErrorChannel returns a new ErrorChannel.\nfunc NewErrorChannel() *ErrorChannel {\n\treturn \u0026ErrorChannel{\n\t\terrCh: make(chan error, 1),\n\t}\n}","line":{"from":54,"to":59}} {"id":100010711,"name":"NewParallelizer","signature":"func NewParallelizer(p int) Parallelizer","file":"pkg/scheduler/framework/parallelize/parallelism.go","code":"// NewParallelizer returns an object holding the parallelism.\nfunc NewParallelizer(p int) Parallelizer {\n\treturn Parallelizer{parallelism: p}\n}","line":{"from":35,"to":38}} {"id":100010712,"name":"chunkSizeFor","signature":"func chunkSizeFor(n, parallelism int) int","file":"pkg/scheduler/framework/parallelize/parallelism.go","code":"// chunkSizeFor returns a chunk size for the given number of items to use for\n// parallel work. The size aims to produce good CPU utilization.\n// returns max(1, min(sqrt(n), n/Parallelism))\nfunc chunkSizeFor(n, parallelism int) int {\n\ts := int(math.Sqrt(float64(n)))\n\n\tif r := n/parallelism + 1; s \u003e r {\n\t\ts = r\n\t} else if s \u003c 1 {\n\t\ts = 1\n\t}\n\treturn s\n}","line":{"from":40,"to":52}} {"id":100010713,"name":"Until","signature":"func (p Parallelizer) Until(ctx context.Context, pieces int, doWorkPiece workqueue.DoWorkPieceFunc, operation string)","file":"pkg/scheduler/framework/parallelize/parallelism.go","code":"// Until is a wrapper around workqueue.ParallelizeUntil to use in scheduling algorithms.\n// A given operation will be a label that is recorded in the goroutine metric.\nfunc (p Parallelizer) Until(ctx context.Context, pieces int, doWorkPiece workqueue.DoWorkPieceFunc, operation string) {\n\tgoroutinesMetric := metrics.Goroutines.WithLabelValues(operation)\n\twithMetrics := func(piece int) {\n\t\tgoroutinesMetric.Inc()\n\t\tdoWorkPiece(piece)\n\t\tgoroutinesMetric.Dec()\n\t}\n\n\tworkqueue.ParallelizeUntil(ctx, p.parallelism, pieces, withMetrics, workqueue.WithChunkSize(chunkSizeFor(pieces, p.parallelism)))\n}","line":{"from":54,"to":65}} {"id":100010714,"name":"New","signature":"func New(_ runtime.Object, handle framework.Handle) (framework.Plugin, error)","file":"pkg/scheduler/framework/plugins/defaultbinder/default_binder.go","code":"// New creates a DefaultBinder.\nfunc New(_ runtime.Object, handle framework.Handle) (framework.Plugin, error) {\n\treturn \u0026DefaultBinder{handle: handle}, nil\n}","line":{"from":40,"to":43}} {"id":100010715,"name":"Name","signature":"func (b DefaultBinder) Name() string","file":"pkg/scheduler/framework/plugins/defaultbinder/default_binder.go","code":"// Name returns the name of the plugin.\nfunc (b DefaultBinder) Name() string {\n\treturn Name\n}","line":{"from":45,"to":48}} {"id":100010716,"name":"Bind","signature":"func (b DefaultBinder) Bind(ctx context.Context, state *framework.CycleState, p *v1.Pod, nodeName string) *framework.Status","file":"pkg/scheduler/framework/plugins/defaultbinder/default_binder.go","code":"// Bind binds pods to nodes using the k8s client.\nfunc (b DefaultBinder) Bind(ctx context.Context, state *framework.CycleState, p *v1.Pod, nodeName string) *framework.Status {\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(3).Info(\"Attempting to bind pod to node\", \"pod\", klog.KObj(p), \"node\", klog.KRef(\"\", nodeName))\n\tbinding := \u0026v1.Binding{\n\t\tObjectMeta: metav1.ObjectMeta{Namespace: p.Namespace, Name: p.Name, UID: p.UID},\n\t\tTarget: v1.ObjectReference{Kind: \"Node\", Name: nodeName},\n\t}\n\terr := b.handle.ClientSet().CoreV1().Pods(binding.Namespace).Bind(ctx, binding, metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn framework.AsStatus(err)\n\t}\n\treturn nil\n}","line":{"from":50,"to":63}} {"id":100010717,"name":"Name","signature":"func (pl *DefaultPreemption) Name() string","file":"pkg/scheduler/framework/plugins/defaultpreemption/default_preemption.go","code":"// Name returns name of the plugin. It is used in logs, etc.\nfunc (pl *DefaultPreemption) Name() string {\n\treturn Name\n}","line":{"from":60,"to":63}} {"id":100010718,"name":"New","signature":"func New(dpArgs runtime.Object, fh framework.Handle, fts feature.Features) (framework.Plugin, error)","file":"pkg/scheduler/framework/plugins/defaultpreemption/default_preemption.go","code":"// New initializes a new plugin and returns it.\nfunc New(dpArgs runtime.Object, fh framework.Handle, fts feature.Features) (framework.Plugin, error) {\n\targs, ok := dpArgs.(*config.DefaultPreemptionArgs)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"got args of type %T, want *DefaultPreemptionArgs\", dpArgs)\n\t}\n\tif err := validation.ValidateDefaultPreemptionArgs(nil, args); err != nil {\n\t\treturn nil, err\n\t}\n\tpl := DefaultPreemption{\n\t\tfh: fh,\n\t\tfts: fts,\n\t\targs: *args,\n\t\tpodLister: fh.SharedInformerFactory().Core().V1().Pods().Lister(),\n\t\tpdbLister: getPDBLister(fh.SharedInformerFactory()),\n\t}\n\treturn \u0026pl, nil\n}","line":{"from":65,"to":82}} {"id":100010719,"name":"PostFilter","signature":"func (pl *DefaultPreemption) PostFilter(ctx context.Context, state *framework.CycleState, pod *v1.Pod, m framework.NodeToStatusMap) (*framework.PostFilterResult, *framework.Status)","file":"pkg/scheduler/framework/plugins/defaultpreemption/default_preemption.go","code":"// PostFilter invoked at the postFilter extension point.\nfunc (pl *DefaultPreemption) PostFilter(ctx context.Context, state *framework.CycleState, pod *v1.Pod, m framework.NodeToStatusMap) (*framework.PostFilterResult, *framework.Status) {\n\tdefer func() {\n\t\tmetrics.PreemptionAttempts.Inc()\n\t}()\n\n\tpe := preemption.Evaluator{\n\t\tPluginName: names.DefaultPreemption,\n\t\tHandler: pl.fh,\n\t\tPodLister: pl.podLister,\n\t\tPdbLister: pl.pdbLister,\n\t\tState: state,\n\t\tInterface: pl,\n\t}\n\n\tresult, status := pe.Preempt(ctx, pod, m)\n\tif status.Message() != \"\" {\n\t\treturn result, framework.NewStatus(status.Code(), \"preemption: \"+status.Message())\n\t}\n\treturn result, status\n}","line":{"from":84,"to":104}} {"id":100010720,"name":"calculateNumCandidates","signature":"func (pl *DefaultPreemption) calculateNumCandidates(numNodes int32) int32","file":"pkg/scheduler/framework/plugins/defaultpreemption/default_preemption.go","code":"// calculateNumCandidates returns the number of candidates the FindCandidates\n// method must produce from dry running based on the constraints given by\n// \u003cminCandidateNodesPercentage\u003e and \u003cminCandidateNodesAbsolute\u003e. The number of\n// candidates returned will never be greater than \u003cnumNodes\u003e.\nfunc (pl *DefaultPreemption) calculateNumCandidates(numNodes int32) int32 {\n\tn := (numNodes * pl.args.MinCandidateNodesPercentage) / 100\n\tif n \u003c pl.args.MinCandidateNodesAbsolute {\n\t\tn = pl.args.MinCandidateNodesAbsolute\n\t}\n\tif n \u003e numNodes {\n\t\tn = numNodes\n\t}\n\treturn n\n}","line":{"from":106,"to":119}} {"id":100010721,"name":"GetOffsetAndNumCandidates","signature":"func (pl *DefaultPreemption) GetOffsetAndNumCandidates(numNodes int32) (int32, int32)","file":"pkg/scheduler/framework/plugins/defaultpreemption/default_preemption.go","code":"// GetOffsetAndNumCandidates chooses a random offset and calculates the number\n// of candidates that should be shortlisted for dry running preemption.\nfunc (pl *DefaultPreemption) GetOffsetAndNumCandidates(numNodes int32) (int32, int32) {\n\treturn rand.Int31n(numNodes), pl.calculateNumCandidates(numNodes)\n}","line":{"from":121,"to":125}} {"id":100010722,"name":"CandidatesToVictimsMap","signature":"func (pl *DefaultPreemption) CandidatesToVictimsMap(candidates []preemption.Candidate) map[string]*extenderv1.Victims","file":"pkg/scheduler/framework/plugins/defaultpreemption/default_preemption.go","code":"// This function is not applicable for out-of-tree preemption plugins that exercise\n// different preemption candidates on the same nominated node.\nfunc (pl *DefaultPreemption) CandidatesToVictimsMap(candidates []preemption.Candidate) map[string]*extenderv1.Victims {\n\tm := make(map[string]*extenderv1.Victims, len(candidates))\n\tfor _, c := range candidates {\n\t\tm[c.Name()] = c.Victims()\n\t}\n\treturn m\n}","line":{"from":127,"to":135}} {"id":100010723,"name":"SelectVictimsOnNode","signature":"func (pl *DefaultPreemption) SelectVictimsOnNode(","file":"pkg/scheduler/framework/plugins/defaultpreemption/default_preemption.go","code":"// SelectVictimsOnNode finds minimum set of pods on the given node that should be preempted in order to make enough room\n// for \"pod\" to be scheduled.\nfunc (pl *DefaultPreemption) SelectVictimsOnNode(\n\tctx context.Context,\n\tstate *framework.CycleState,\n\tpod *v1.Pod,\n\tnodeInfo *framework.NodeInfo,\n\tpdbs []*policy.PodDisruptionBudget) ([]*v1.Pod, int, *framework.Status) {\n\tvar potentialVictims []*framework.PodInfo\n\tremovePod := func(rpi *framework.PodInfo) error {\n\t\tif err := nodeInfo.RemovePod(rpi.Pod); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tstatus := pl.fh.RunPreFilterExtensionRemovePod(ctx, state, pod, rpi, nodeInfo)\n\t\tif !status.IsSuccess() {\n\t\t\treturn status.AsError()\n\t\t}\n\t\treturn nil\n\t}\n\taddPod := func(api *framework.PodInfo) error {\n\t\tnodeInfo.AddPodInfo(api)\n\t\tstatus := pl.fh.RunPreFilterExtensionAddPod(ctx, state, pod, api, nodeInfo)\n\t\tif !status.IsSuccess() {\n\t\t\treturn status.AsError()\n\t\t}\n\t\treturn nil\n\t}\n\t// As the first step, remove all the lower priority pods from the node and\n\t// check if the given pod can be scheduled.\n\tpodPriority := corev1helpers.PodPriority(pod)\n\tfor _, pi := range nodeInfo.Pods {\n\t\tif corev1helpers.PodPriority(pi.Pod) \u003c podPriority {\n\t\t\tpotentialVictims = append(potentialVictims, pi)\n\t\t\tif err := removePod(pi); err != nil {\n\t\t\t\treturn nil, 0, framework.AsStatus(err)\n\t\t\t}\n\t\t}\n\t}\n\n\t// No potential victims are found, and so we don't need to evaluate the node again since its state didn't change.\n\tif len(potentialVictims) == 0 {\n\t\tmessage := fmt.Sprintf(\"No preemption victims found for incoming pod\")\n\t\treturn nil, 0, framework.NewStatus(framework.UnschedulableAndUnresolvable, message)\n\t}\n\n\t// If the new pod does not fit after removing all the lower priority pods,\n\t// we are almost done and this node is not suitable for preemption. The only\n\t// condition that we could check is if the \"pod\" is failing to schedule due to\n\t// inter-pod affinity to one or more victims, but we have decided not to\n\t// support this case for performance reasons. Having affinity to lower\n\t// priority pods is not a recommended configuration anyway.\n\tif status := pl.fh.RunFilterPluginsWithNominatedPods(ctx, state, pod, nodeInfo); !status.IsSuccess() {\n\t\treturn nil, 0, status\n\t}\n\tvar victims []*v1.Pod\n\tnumViolatingVictim := 0\n\tsort.Slice(potentialVictims, func(i, j int) bool { return util.MoreImportantPod(potentialVictims[i].Pod, potentialVictims[j].Pod) })\n\t// Try to reprieve as many pods as possible. We first try to reprieve the PDB\n\t// violating victims and then other non-violating ones. In both cases, we start\n\t// from the highest priority victims.\n\tviolatingVictims, nonViolatingVictims := filterPodsWithPDBViolation(potentialVictims, pdbs)\n\treprievePod := func(pi *framework.PodInfo) (bool, error) {\n\t\tif err := addPod(pi); err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tstatus := pl.fh.RunFilterPluginsWithNominatedPods(ctx, state, pod, nodeInfo)\n\t\tfits := status.IsSuccess()\n\t\tif !fits {\n\t\t\tif err := removePod(pi); err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\trpi := pi.Pod\n\t\t\tvictims = append(victims, rpi)\n\t\t\tklog.V(5).InfoS(\"Pod is a potential preemption victim on node\", \"pod\", klog.KObj(rpi), \"node\", klog.KObj(nodeInfo.Node()))\n\t\t}\n\t\treturn fits, nil\n\t}\n\tfor _, p := range violatingVictims {\n\t\tif fits, err := reprievePod(p); err != nil {\n\t\t\treturn nil, 0, framework.AsStatus(err)\n\t\t} else if !fits {\n\t\t\tnumViolatingVictim++\n\t\t}\n\t}\n\t// Now we try to reprieve non-violating victims.\n\tfor _, p := range nonViolatingVictims {\n\t\tif _, err := reprievePod(p); err != nil {\n\t\t\treturn nil, 0, framework.AsStatus(err)\n\t\t}\n\t}\n\treturn victims, numViolatingVictim, framework.NewStatus(framework.Success)\n}","line":{"from":137,"to":228}} {"id":100010724,"name":"PodEligibleToPreemptOthers","signature":"func (pl *DefaultPreemption) PodEligibleToPreemptOthers(pod *v1.Pod, nominatedNodeStatus *framework.Status) (bool, string)","file":"pkg/scheduler/framework/plugins/defaultpreemption/default_preemption.go","code":"// PodEligibleToPreemptOthers returns one bool and one string. The bool\n// indicates whether this pod should be considered for preempting other pods or\n// not. The string includes the reason if this pod isn't eligible.\n// There're several reasons:\n// 1. The pod has a preemptionPolicy of Never.\n// 2. The pod has already preempted other pods and the victims are in their graceful termination period.\n// Currently we check the node that is nominated for this pod, and as long as there are\n// terminating pods on this node, we don't attempt to preempt more pods.\nfunc (pl *DefaultPreemption) PodEligibleToPreemptOthers(pod *v1.Pod, nominatedNodeStatus *framework.Status) (bool, string) {\n\tif pod.Spec.PreemptionPolicy != nil \u0026\u0026 *pod.Spec.PreemptionPolicy == v1.PreemptNever {\n\t\treturn false, \"not eligible due to preemptionPolicy=Never.\"\n\t}\n\n\tnodeInfos := pl.fh.SnapshotSharedLister().NodeInfos()\n\tnomNodeName := pod.Status.NominatedNodeName\n\tif len(nomNodeName) \u003e 0 {\n\t\t// If the pod's nominated node is considered as UnschedulableAndUnresolvable by the filters,\n\t\t// then the pod should be considered for preempting again.\n\t\tif nominatedNodeStatus.Code() == framework.UnschedulableAndUnresolvable {\n\t\t\treturn true, \"\"\n\t\t}\n\n\t\tif nodeInfo, _ := nodeInfos.Get(nomNodeName); nodeInfo != nil {\n\t\t\tpodPriority := corev1helpers.PodPriority(pod)\n\t\t\tfor _, p := range nodeInfo.Pods {\n\t\t\t\tif corev1helpers.PodPriority(p.Pod) \u003c podPriority \u0026\u0026 podTerminatingByPreemption(p.Pod, pl.fts.EnablePodDisruptionConditions) {\n\t\t\t\t\t// There is a terminating pod on the nominated node.\n\t\t\t\t\treturn false, \"not eligible due to a terminating pod on the nominated node.\"\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn true, \"\"\n}","line":{"from":230,"to":263}} {"id":100010725,"name":"podTerminatingByPreemption","signature":"func podTerminatingByPreemption(p *v1.Pod, enablePodDisruptionConditions bool) bool","file":"pkg/scheduler/framework/plugins/defaultpreemption/default_preemption.go","code":"// podTerminatingByPreemption returns the pod's terminating state if feature PodDisruptionConditions is not enabled.\n// Otherwise, it additionally checks if the termination state is caused by scheduler preemption.\nfunc podTerminatingByPreemption(p *v1.Pod, enablePodDisruptionConditions bool) bool {\n\tif p.DeletionTimestamp == nil {\n\t\treturn false\n\t}\n\n\tif !enablePodDisruptionConditions {\n\t\treturn true\n\t}\n\n\tfor _, condition := range p.Status.Conditions {\n\t\tif condition.Type == v1.DisruptionTarget {\n\t\t\treturn condition.Status == v1.ConditionTrue \u0026\u0026 condition.Reason == v1.PodReasonPreemptionByScheduler\n\t\t}\n\t}\n\treturn false\n}","line":{"from":265,"to":282}} {"id":100010726,"name":"filterPodsWithPDBViolation","signature":"func filterPodsWithPDBViolation(podInfos []*framework.PodInfo, pdbs []*policy.PodDisruptionBudget) (violatingPodInfos, nonViolatingPodInfos []*framework.PodInfo)","file":"pkg/scheduler/framework/plugins/defaultpreemption/default_preemption.go","code":"// filterPodsWithPDBViolation groups the given \"pods\" into two groups of \"violatingPods\"\n// and \"nonViolatingPods\" based on whether their PDBs will be violated if they are\n// preempted.\n// This function is stable and does not change the order of received pods. So, if it\n// receives a sorted list, grouping will preserve the order of the input list.\nfunc filterPodsWithPDBViolation(podInfos []*framework.PodInfo, pdbs []*policy.PodDisruptionBudget) (violatingPodInfos, nonViolatingPodInfos []*framework.PodInfo) {\n\tpdbsAllowed := make([]int32, len(pdbs))\n\tfor i, pdb := range pdbs {\n\t\tpdbsAllowed[i] = pdb.Status.DisruptionsAllowed\n\t}\n\n\tfor _, podInfo := range podInfos {\n\t\tpod := podInfo.Pod\n\t\tpdbForPodIsViolated := false\n\t\t// A pod with no labels will not match any PDB. So, no need to check.\n\t\tif len(pod.Labels) != 0 {\n\t\t\tfor i, pdb := range pdbs {\n\t\t\t\tif pdb.Namespace != pod.Namespace {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tselector, err := metav1.LabelSelectorAsSelector(pdb.Spec.Selector)\n\t\t\t\tif err != nil {\n\t\t\t\t\t// This object has an invalid selector, it does not match the pod\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// A PDB with a nil or empty selector matches nothing.\n\t\t\t\tif selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Existing in DisruptedPods means it has been processed in API server,\n\t\t\t\t// we don't treat it as a violating case.\n\t\t\t\tif _, exist := pdb.Status.DisruptedPods[pod.Name]; exist {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// Only decrement the matched pdb when it's not in its \u003cDisruptedPods\u003e;\n\t\t\t\t// otherwise we may over-decrement the budget number.\n\t\t\t\tpdbsAllowed[i]--\n\t\t\t\t// We have found a matching PDB.\n\t\t\t\tif pdbsAllowed[i] \u003c 0 {\n\t\t\t\t\tpdbForPodIsViolated = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif pdbForPodIsViolated {\n\t\t\tviolatingPodInfos = append(violatingPodInfos, podInfo)\n\t\t} else {\n\t\t\tnonViolatingPodInfos = append(nonViolatingPodInfos, podInfo)\n\t\t}\n\t}\n\treturn violatingPodInfos, nonViolatingPodInfos\n}","line":{"from":284,"to":335}} {"id":100010727,"name":"getPDBLister","signature":"func getPDBLister(informerFactory informers.SharedInformerFactory) policylisters.PodDisruptionBudgetLister","file":"pkg/scheduler/framework/plugins/defaultpreemption/default_preemption.go","code":"func getPDBLister(informerFactory informers.SharedInformerFactory) policylisters.PodDisruptionBudgetLister {\n\treturn informerFactory.Policy().V1().PodDisruptionBudgets().Lister()\n}","line":{"from":337,"to":339}} {"id":100010728,"name":"Clone","signature":"func (d *stateData) Clone() framework.StateData","file":"pkg/scheduler/framework/plugins/dynamicresources/dynamicresources.go","code":"func (d *stateData) Clone() framework.StateData {\n\treturn d\n}","line":{"from":92,"to":94}} {"id":100010729,"name":"updateClaimStatus","signature":"func (d *stateData) updateClaimStatus(ctx context.Context, clientset kubernetes.Interface, index int, claim *resourcev1alpha2.ResourceClaim) error","file":"pkg/scheduler/framework/plugins/dynamicresources/dynamicresources.go","code":"func (d *stateData) updateClaimStatus(ctx context.Context, clientset kubernetes.Interface, index int, claim *resourcev1alpha2.ResourceClaim) error {\n\t// TODO (#113700): replace with patch operation. Beware that patching must only succeed if the\n\t// object has not been modified in parallel by someone else.\n\tclaim, err := clientset.ResourceV1alpha2().ResourceClaims(claim.Namespace).UpdateStatus(ctx, claim, metav1.UpdateOptions{})\n\t// TODO: metric for update results, with the operation (\"set selected\n\t// node\", \"set PotentialNodes\", etc.) as one dimension.\n\tif err != nil {\n\t\treturn fmt.Errorf(\"update resource claim: %w\", err)\n\t}\n\n\t// Remember the new instance. This is relevant when the plugin must\n\t// update the same claim multiple times (for example, first reserve\n\t// the claim, then later remove the reservation), because otherwise the second\n\t// update would fail with a \"was modified\" error.\n\td.claims[index] = claim\n\n\treturn nil\n}","line":{"from":96,"to":113}} {"id":100010730,"name":"initializePodSchedulingContexts","signature":"func (d *stateData) initializePodSchedulingContexts(ctx context.Context, pod *v1.Pod, podSchedulingContextLister resourcev1alpha2listers.PodSchedulingContextLister) (*resourcev1alpha2.PodSchedulingContext, error)","file":"pkg/scheduler/framework/plugins/dynamicresources/dynamicresources.go","code":"// initializePodSchedulingContext can be called concurrently. It returns an existing PodSchedulingContext\n// object if there is one already, retrieves one if not, or as a last resort creates\n// one from scratch.\nfunc (d *stateData) initializePodSchedulingContexts(ctx context.Context, pod *v1.Pod, podSchedulingContextLister resourcev1alpha2listers.PodSchedulingContextLister) (*resourcev1alpha2.PodSchedulingContext, error) {\n\t// TODO (#113701): check if this mutex locking can be avoided by calling initializePodSchedulingContext during PreFilter.\n\td.mutex.Lock()\n\tdefer d.mutex.Unlock()\n\n\tif d.schedulingCtx != nil {\n\t\treturn d.schedulingCtx, nil\n\t}\n\n\tschedulingCtx, err := podSchedulingContextLister.PodSchedulingContexts(pod.Namespace).Get(pod.Name)\n\tswitch {\n\tcase apierrors.IsNotFound(err):\n\t\tcontroller := true\n\t\tschedulingCtx = \u0026resourcev1alpha2.PodSchedulingContext{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: pod.Name,\n\t\t\t\tNamespace: pod.Namespace,\n\t\t\t\tOwnerReferences: []metav1.OwnerReference{\n\t\t\t\t\t{\n\t\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t\t\tKind: \"Pod\",\n\t\t\t\t\t\tName: pod.Name,\n\t\t\t\t\t\tUID: pod.UID,\n\t\t\t\t\t\tController: \u0026controller,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\terr = nil\n\tcase err != nil:\n\t\treturn nil, err\n\tdefault:\n\t\t// We have an object, but it might be obsolete.\n\t\tif !metav1.IsControlledBy(schedulingCtx, pod) {\n\t\t\treturn nil, fmt.Errorf(\"PodSchedulingContext object with UID %s is not owned by Pod %s/%s\", schedulingCtx.UID, pod.Namespace, pod.Name)\n\t\t}\n\t}\n\td.schedulingCtx = schedulingCtx\n\treturn schedulingCtx, err\n}","line":{"from":115,"to":157}} {"id":100010731,"name":"publishPodSchedulingContexts","signature":"func (d *stateData) publishPodSchedulingContexts(ctx context.Context, clientset kubernetes.Interface, schedulingCtx *resourcev1alpha2.PodSchedulingContext) error","file":"pkg/scheduler/framework/plugins/dynamicresources/dynamicresources.go","code":"// publishPodSchedulingContext creates or updates the PodSchedulingContext object.\nfunc (d *stateData) publishPodSchedulingContexts(ctx context.Context, clientset kubernetes.Interface, schedulingCtx *resourcev1alpha2.PodSchedulingContext) error {\n\td.mutex.Lock()\n\tdefer d.mutex.Unlock()\n\n\tvar err error\n\tlogger := klog.FromContext(ctx)\n\tmsg := \"Updating PodSchedulingContext\"\n\tif schedulingCtx.UID == \"\" {\n\t\tmsg = \"Creating PodSchedulingContext\"\n\t}\n\tif loggerV := logger.V(6); loggerV.Enabled() {\n\t\t// At a high enough log level, dump the entire object.\n\t\tloggerV.Info(msg, \"podSchedulingCtxDump\", schedulingCtx)\n\t} else {\n\t\tlogger.V(5).Info(msg, \"podSchedulingCtx\", klog.KObj(schedulingCtx))\n\t}\n\tif schedulingCtx.UID == \"\" {\n\t\tschedulingCtx, err = clientset.ResourceV1alpha2().PodSchedulingContexts(schedulingCtx.Namespace).Create(ctx, schedulingCtx, metav1.CreateOptions{})\n\t} else {\n\t\t// TODO (#113700): patch here to avoid racing with drivers which update the status.\n\t\tschedulingCtx, err = clientset.ResourceV1alpha2().PodSchedulingContexts(schedulingCtx.Namespace).Update(ctx, schedulingCtx, metav1.UpdateOptions{})\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\td.schedulingCtx = schedulingCtx\n\td.podSchedulingDirty = false\n\treturn nil\n}","line":{"from":159,"to":188}} {"id":100010732,"name":"storePodSchedulingContexts","signature":"func (d *stateData) storePodSchedulingContexts(schedulingCtx *resourcev1alpha2.PodSchedulingContext)","file":"pkg/scheduler/framework/plugins/dynamicresources/dynamicresources.go","code":"// storePodSchedulingContext replaces the pod schedulingCtx object in the state.\nfunc (d *stateData) storePodSchedulingContexts(schedulingCtx *resourcev1alpha2.PodSchedulingContext) {\n\td.mutex.Lock()\n\tdefer d.mutex.Unlock()\n\n\td.schedulingCtx = schedulingCtx\n\td.podSchedulingDirty = true\n}","line":{"from":190,"to":197}} {"id":100010733,"name":"statusForClaim","signature":"func statusForClaim(schedulingCtx *resourcev1alpha2.PodSchedulingContext, podClaimName string) *resourcev1alpha2.ResourceClaimSchedulingStatus","file":"pkg/scheduler/framework/plugins/dynamicresources/dynamicresources.go","code":"func statusForClaim(schedulingCtx *resourcev1alpha2.PodSchedulingContext, podClaimName string) *resourcev1alpha2.ResourceClaimSchedulingStatus {\n\tfor _, status := range schedulingCtx.Status.ResourceClaims {\n\t\tif status.Name == podClaimName {\n\t\t\treturn \u0026status\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":199,"to":206}} {"id":100010734,"name":"New","signature":"func New(plArgs runtime.Object, fh framework.Handle, fts feature.Features) (framework.Plugin, error)","file":"pkg/scheduler/framework/plugins/dynamicresources/dynamicresources.go","code":"// New initializes a new plugin and returns it.\nfunc New(plArgs runtime.Object, fh framework.Handle, fts feature.Features) (framework.Plugin, error) {\n\tif !fts.EnableDynamicResourceAllocation {\n\t\t// Disabled, won't do anything.\n\t\treturn \u0026dynamicResources{}, nil\n\t}\n\n\treturn \u0026dynamicResources{\n\t\tenabled: true,\n\t\tclientset: fh.ClientSet(),\n\t\tclaimLister: fh.SharedInformerFactory().Resource().V1alpha2().ResourceClaims().Lister(),\n\t\tclassLister: fh.SharedInformerFactory().Resource().V1alpha2().ResourceClasses().Lister(),\n\t\tpodSchedulingContextLister: fh.SharedInformerFactory().Resource().V1alpha2().PodSchedulingContexts().Lister(),\n\t}, nil\n}","line":{"from":217,"to":231}} {"id":100010735,"name":"Name","signature":"func (pl *dynamicResources) Name() string","file":"pkg/scheduler/framework/plugins/dynamicresources/dynamicresources.go","code":"// Name returns name of the plugin. It is used in logs, etc.\nfunc (pl *dynamicResources) Name() string {\n\treturn Name\n}","line":{"from":241,"to":244}} {"id":100010736,"name":"EventsToRegister","signature":"func (pl *dynamicResources) EventsToRegister() []framework.ClusterEvent","file":"pkg/scheduler/framework/plugins/dynamicresources/dynamicresources.go","code":"// EventsToRegister returns the possible events that may make a Pod\n// failed by this plugin schedulable.\nfunc (pl *dynamicResources) EventsToRegister() []framework.ClusterEvent {\n\tif !pl.enabled {\n\t\treturn nil\n\t}\n\n\tevents := []framework.ClusterEvent{\n\t\t// Allocation is tracked in ResourceClaims, so any changes may make the pods schedulable.\n\t\t{Resource: framework.ResourceClaim, ActionType: framework.Add | framework.Update},\n\t\t// When a driver has provided additional information, a pod waiting for that information\n\t\t// may be schedulable.\n\t\t// TODO (#113702): can we change this so that such an event does not trigger *all* pods?\n\t\t// Yes: https://github.com/kubernetes/kubernetes/blob/abcbaed0784baf5ed2382aae9705a8918f2daa18/pkg/scheduler/eventhandlers.go#L70\n\t\t{Resource: framework.PodSchedulingContext, ActionType: framework.Add | framework.Update},\n\t\t// A resource might depend on node labels for topology filtering.\n\t\t// A new or updated node may make pods schedulable.\n\t\t{Resource: framework.Node, ActionType: framework.Add | framework.UpdateNodeLabel},\n\t}\n\treturn events\n}","line":{"from":246,"to":266}} {"id":100010737,"name":"podResourceClaims","signature":"func (pl *dynamicResources) podResourceClaims(pod *v1.Pod) ([]*resourcev1alpha2.ResourceClaim, error)","file":"pkg/scheduler/framework/plugins/dynamicresources/dynamicresources.go","code":"// podResourceClaims returns the ResourceClaims for all pod.Spec.PodResourceClaims.\nfunc (pl *dynamicResources) podResourceClaims(pod *v1.Pod) ([]*resourcev1alpha2.ResourceClaim, error) {\n\tclaims := make([]*resourcev1alpha2.ResourceClaim, 0, len(pod.Spec.ResourceClaims))\n\tfor _, resource := range pod.Spec.ResourceClaims {\n\t\tclaimName := resourceclaim.Name(pod, \u0026resource)\n\t\tisEphemeral := resource.Source.ResourceClaimTemplateName != nil\n\t\tclaim, err := pl.claimLister.ResourceClaims(pod.Namespace).Get(claimName)\n\t\tif err != nil {\n\t\t\t// The error usually has already enough context (\"resourcevolumeclaim \"myclaim\" not found\"),\n\t\t\t// but we can do better for generic ephemeral inline volumes where that situation\n\t\t\t// is normal directly after creating a pod.\n\t\t\tif isEphemeral \u0026\u0026 apierrors.IsNotFound(err) {\n\t\t\t\terr = fmt.Errorf(\"waiting for dynamic resource controller to create the resourceclaim %q\", claimName)\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif claim.DeletionTimestamp != nil {\n\t\t\treturn nil, fmt.Errorf(\"resourceclaim %q is being deleted\", claim.Name)\n\t\t}\n\n\t\tif isEphemeral {\n\t\t\tif err := resourceclaim.IsForPod(pod, claim); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\t// We store the pointer as returned by the lister. The\n\t\t// assumption is that if a claim gets modified while our code\n\t\t// runs, the cache will store a new pointer, not mutate the\n\t\t// existing object that we point to here.\n\t\tclaims = append(claims, claim)\n\t}\n\treturn claims, nil\n}","line":{"from":268,"to":301}} {"id":100010738,"name":"PreFilter","signature":"func (pl *dynamicResources) PreFilter(ctx context.Context, state *framework.CycleState, pod *v1.Pod) (*framework.PreFilterResult, *framework.Status)","file":"pkg/scheduler/framework/plugins/dynamicresources/dynamicresources.go","code":"// PreFilter invoked at the prefilter extension point to check if pod has all\n// immediate claims bound. UnschedulableAndUnresolvable is returned if\n// the pod cannot be scheduled at the moment on any node.\nfunc (pl *dynamicResources) PreFilter(ctx context.Context, state *framework.CycleState, pod *v1.Pod) (*framework.PreFilterResult, *framework.Status) {\n\tif !pl.enabled {\n\t\treturn nil, nil\n\t}\n\tlogger := klog.FromContext(ctx)\n\n\t// If the pod does not reference any claim, we don't need to do\n\t// anything for it. We just initialize an empty state to record that\n\t// observation for the other functions. This gets updated below\n\t// if we get that far.\n\ts := \u0026stateData{}\n\tstate.Write(stateKey, s)\n\n\tclaims, err := pl.podResourceClaims(pod)\n\tif err != nil {\n\t\treturn nil, statusUnschedulable(logger, err.Error())\n\t}\n\tlogger.V(5).Info(\"pod resource claims\", \"pod\", klog.KObj(pod), \"resourceclaims\", klog.KObjSlice(claims))\n\t// If the pod does not reference any claim, we don't need to do\n\t// anything for it.\n\tif len(claims) == 0 {\n\t\treturn nil, nil\n\t}\n\n\ts.availableOnNodes = make([]*nodeaffinity.NodeSelector, len(claims))\n\tfor index, claim := range claims {\n\t\tif claim.Spec.AllocationMode == resourcev1alpha2.AllocationModeImmediate \u0026\u0026\n\t\t\tclaim.Status.Allocation == nil {\n\t\t\t// This will get resolved by the resource driver.\n\t\t\treturn nil, statusUnschedulable(logger, \"unallocated immediate resourceclaim\", \"pod\", klog.KObj(pod), \"resourceclaim\", klog.KObj(claim))\n\t\t}\n\t\tif claim.Status.DeallocationRequested {\n\t\t\t// This will get resolved by the resource driver.\n\t\t\treturn nil, statusUnschedulable(logger, \"resourceclaim must be reallocated\", \"pod\", klog.KObj(pod), \"resourceclaim\", klog.KObj(claim))\n\t\t}\n\t\tif claim.Status.Allocation != nil \u0026\u0026\n\t\t\t!resourceclaim.CanBeReserved(claim) \u0026\u0026\n\t\t\t!resourceclaim.IsReservedForPod(pod, claim) {\n\t\t\t// Resource is in use. The pod has to wait.\n\t\t\treturn nil, statusUnschedulable(logger, \"resourceclaim in use\", \"pod\", klog.KObj(pod), \"resourceclaim\", klog.KObj(claim))\n\t\t}\n\t\tif claim.Status.Allocation != nil \u0026\u0026\n\t\t\tclaim.Status.Allocation.AvailableOnNodes != nil {\n\t\t\tnodeSelector, err := nodeaffinity.NewNodeSelector(claim.Status.Allocation.AvailableOnNodes)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, statusError(logger, err)\n\t\t\t}\n\t\t\ts.availableOnNodes[index] = nodeSelector\n\t\t}\n\t}\n\n\ts.claims = claims\n\tstate.Write(stateKey, s)\n\treturn nil, nil\n}","line":{"from":303,"to":360}} {"id":100010739,"name":"PreFilterExtensions","signature":"func (pl *dynamicResources) PreFilterExtensions() framework.PreFilterExtensions","file":"pkg/scheduler/framework/plugins/dynamicresources/dynamicresources.go","code":"// PreFilterExtensions returns prefilter extensions, pod add and remove.\nfunc (pl *dynamicResources) PreFilterExtensions() framework.PreFilterExtensions {\n\treturn nil\n}","line":{"from":362,"to":365}} {"id":100010740,"name":"getStateData","signature":"func getStateData(cs *framework.CycleState) (*stateData, error)","file":"pkg/scheduler/framework/plugins/dynamicresources/dynamicresources.go","code":"func getStateData(cs *framework.CycleState) (*stateData, error) {\n\tstate, err := cs.Read(stateKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts, ok := state.(*stateData)\n\tif !ok {\n\t\treturn nil, errors.New(\"unable to convert state into stateData\")\n\t}\n\treturn s, nil\n}","line":{"from":367,"to":377}} {"id":100010741,"name":"Filter","signature":"func (pl *dynamicResources) Filter(ctx context.Context, cs *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status","file":"pkg/scheduler/framework/plugins/dynamicresources/dynamicresources.go","code":"// Filter invoked at the filter extension point.\n// It evaluates if a pod can fit due to the resources it requests,\n// for both allocated and unallocated claims.\n//\n// For claims that are bound, then it checks that the node affinity is\n// satisfied by the given node.\n//\n// For claims that are unbound, it checks whether the claim might get allocated\n// for the node.\nfunc (pl *dynamicResources) Filter(ctx context.Context, cs *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status {\n\tif !pl.enabled {\n\t\treturn nil\n\t}\n\tstate, err := getStateData(cs)\n\tif err != nil {\n\t\treturn statusError(klog.FromContext(ctx), err)\n\t}\n\tif len(state.claims) == 0 {\n\t\treturn nil\n\t}\n\n\tlogger := klog.FromContext(ctx)\n\tnode := nodeInfo.Node()\n\n\tvar unavailableClaims []int\n\tfor index, claim := range state.claims {\n\t\tlogger.V(10).Info(\"filtering based on resource claims of the pod\", \"pod\", klog.KObj(pod), \"node\", klog.KObj(node), \"resourceclaim\", klog.KObj(claim))\n\t\tswitch {\n\t\tcase claim.Status.Allocation != nil:\n\t\t\tif nodeSelector := state.availableOnNodes[index]; nodeSelector != nil {\n\t\t\t\tif !nodeSelector.Match(node) {\n\t\t\t\t\tlogger.V(5).Info(\"AvailableOnNodes does not match\", \"pod\", klog.KObj(pod), \"node\", klog.KObj(node), \"resourceclaim\", klog.KObj(claim))\n\t\t\t\t\tunavailableClaims = append(unavailableClaims, index)\n\t\t\t\t}\n\t\t\t}\n\t\tcase claim.Status.DeallocationRequested:\n\t\t\t// We shouldn't get here. PreFilter already checked this.\n\t\t\treturn statusUnschedulable(logger, \"resourceclaim must be reallocated\", \"pod\", klog.KObj(pod), \"node\", klog.KObj(node), \"resourceclaim\", klog.KObj(claim))\n\t\tcase claim.Spec.AllocationMode == resourcev1alpha2.AllocationModeWaitForFirstConsumer:\n\t\t\t// The ResourceClass might have a node filter. This is\n\t\t\t// useful for trimming the initial set of potential\n\t\t\t// nodes before we ask the driver(s) for information\n\t\t\t// about the specific pod.\n\t\t\tclass, err := pl.classLister.Get(claim.Spec.ResourceClassName)\n\t\t\tif err != nil {\n\t\t\t\t// If the class does not exist, then allocation cannot proceed.\n\t\t\t\treturn statusError(logger, fmt.Errorf(\"look up resource class: %v\", err))\n\t\t\t}\n\t\t\tif class.SuitableNodes != nil {\n\t\t\t\t// TODO (#113700): parse class.SuitableNodes once in PreFilter, reuse result.\n\t\t\t\tmatches, err := corev1helpers.MatchNodeSelectorTerms(node, class.SuitableNodes)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn statusError(logger, fmt.Errorf(\"potential node filter: %v\", err))\n\t\t\t\t}\n\t\t\t\tif !matches {\n\t\t\t\t\treturn statusUnschedulable(logger, \"excluded by resource class node filter\", \"pod\", klog.KObj(pod), \"node\", klog.KObj(node), \"resourceclass\", klog.KObj(class))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Now we need information from drivers.\n\t\t\tschedulingCtx, err := state.initializePodSchedulingContexts(ctx, pod, pl.podSchedulingContextLister)\n\t\t\tif err != nil {\n\t\t\t\treturn statusError(logger, err)\n\t\t\t}\n\t\t\tstatus := statusForClaim(schedulingCtx, pod.Spec.ResourceClaims[index].Name)\n\t\t\tif status != nil {\n\t\t\t\tfor _, unsuitableNode := range status.UnsuitableNodes {\n\t\t\t\t\tif node.Name == unsuitableNode {\n\t\t\t\t\t\treturn statusUnschedulable(logger, \"resourceclaim cannot be allocated for the node (unsuitable)\", \"pod\", klog.KObj(pod), \"node\", klog.KObj(node), \"resourceclaim\", klog.KObj(claim), \"unsuitablenodes\", status.UnsuitableNodes)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\t// This should have been delayed allocation. Immediate\n\t\t\t// allocation was already checked for in PreFilter.\n\t\t\treturn statusError(logger, fmt.Errorf(\"internal error, unexpected allocation mode %v\", claim.Spec.AllocationMode))\n\t\t}\n\t}\n\n\tif len(unavailableClaims) \u003e 0 {\n\t\tstate.mutex.Lock()\n\t\tdefer state.mutex.Unlock()\n\t\tif state.unavailableClaims == nil {\n\t\t\tstate.unavailableClaims = sets.NewInt()\n\t\t}\n\n\t\tfor index := range unavailableClaims {\n\t\t\tclaim := state.claims[index]\n\t\t\t// Deallocation makes more sense for claims with\n\t\t\t// delayed allocation. Claims with immediate allocation\n\t\t\t// would just get allocated again for a random node,\n\t\t\t// which is unlikely to help the pod.\n\t\t\tif claim.Spec.AllocationMode == resourcev1alpha2.AllocationModeWaitForFirstConsumer {\n\t\t\t\tstate.unavailableClaims.Insert(unavailableClaims...)\n\t\t\t}\n\t\t}\n\t\treturn statusUnschedulable(logger, \"resourceclaim not available on the node\", \"pod\", klog.KObj(pod))\n\t}\n\n\treturn nil\n}","line":{"from":379,"to":479}} {"id":100010742,"name":"PostFilter","signature":"func (pl *dynamicResources) PostFilter(ctx context.Context, cs *framework.CycleState, pod *v1.Pod, filteredNodeStatusMap framework.NodeToStatusMap) (*framework.PostFilterResult, *framework.Status)","file":"pkg/scheduler/framework/plugins/dynamicresources/dynamicresources.go","code":"// PostFilter checks whether there are allocated claims that could get\n// deallocated to help get the Pod schedulable. If yes, it picks one and\n// requests its deallocation. This only gets called when filtering found no\n// suitable node.\nfunc (pl *dynamicResources) PostFilter(ctx context.Context, cs *framework.CycleState, pod *v1.Pod, filteredNodeStatusMap framework.NodeToStatusMap) (*framework.PostFilterResult, *framework.Status) {\n\tif !pl.enabled {\n\t\treturn nil, framework.NewStatus(framework.Unschedulable, \"plugin disabled\")\n\t}\n\tlogger := klog.FromContext(ctx)\n\tstate, err := getStateData(cs)\n\tif err != nil {\n\t\treturn nil, statusError(logger, err)\n\t}\n\tif len(state.claims) == 0 {\n\t\treturn nil, framework.NewStatus(framework.Unschedulable, \"no new claims to deallocate\")\n\t}\n\n\t// Iterating over a map is random. This is intentional here, we want to\n\t// pick one claim randomly because there is no better heuristic.\n\tfor index := range state.unavailableClaims {\n\t\tclaim := state.claims[index]\n\t\tif len(claim.Status.ReservedFor) == 0 ||\n\t\t\tlen(claim.Status.ReservedFor) == 1 \u0026\u0026 claim.Status.ReservedFor[0].UID == pod.UID {\n\t\t\tclaim := state.claims[index].DeepCopy()\n\t\t\tclaim.Status.DeallocationRequested = true\n\t\t\tclaim.Status.ReservedFor = nil\n\t\t\tlogger.V(5).Info(\"Requesting deallocation of ResourceClaim\", \"pod\", klog.KObj(pod), \"resourceclaim\", klog.KObj(claim))\n\t\t\tif err := state.updateClaimStatus(ctx, pl.clientset, index, claim); err != nil {\n\t\t\t\treturn nil, statusError(logger, err)\n\t\t\t}\n\t\t\treturn nil, nil\n\t\t}\n\t}\n\treturn nil, framework.NewStatus(framework.Unschedulable, \"still not schedulable\")\n}","line":{"from":481,"to":515}} {"id":100010743,"name":"PreScore","signature":"func (pl *dynamicResources) PreScore(ctx context.Context, cs *framework.CycleState, pod *v1.Pod, nodes []*v1.Node) *framework.Status","file":"pkg/scheduler/framework/plugins/dynamicresources/dynamicresources.go","code":"// PreScore is passed a list of all nodes that would fit the pod. Not all\n// claims are necessarily allocated yet, so here we can set the SuitableNodes\n// field for those which are pending.\nfunc (pl *dynamicResources) PreScore(ctx context.Context, cs *framework.CycleState, pod *v1.Pod, nodes []*v1.Node) *framework.Status {\n\tif !pl.enabled {\n\t\treturn nil\n\t}\n\tstate, err := getStateData(cs)\n\tif err != nil {\n\t\treturn statusError(klog.FromContext(ctx), err)\n\t}\n\tif len(state.claims) == 0 {\n\t\treturn nil\n\t}\n\n\tlogger := klog.FromContext(ctx)\n\tschedulingCtx, err := state.initializePodSchedulingContexts(ctx, pod, pl.podSchedulingContextLister)\n\tif err != nil {\n\t\treturn statusError(logger, err)\n\t}\n\tpending := false\n\tfor _, claim := range state.claims {\n\t\tif claim.Status.Allocation == nil {\n\t\t\tpending = true\n\t\t}\n\t}\n\tif pending \u0026\u0026 !haveAllNodes(schedulingCtx.Spec.PotentialNodes, nodes) {\n\t\t// Remember the potential nodes. The object will get created or\n\t\t// updated in Reserve. This is both an optimization and\n\t\t// covers the case that PreScore doesn't get called when there\n\t\t// is only a single node.\n\t\tlogger.V(5).Info(\"remembering potential nodes\", \"pod\", klog.KObj(pod), \"potentialnodes\", klog.KObjSlice(nodes))\n\t\tschedulingCtx = schedulingCtx.DeepCopy()\n\t\tnumNodes := len(nodes)\n\t\tif numNodes \u003e resourcev1alpha2.PodSchedulingNodeListMaxSize {\n\t\t\tnumNodes = resourcev1alpha2.PodSchedulingNodeListMaxSize\n\t\t}\n\t\tschedulingCtx.Spec.PotentialNodes = make([]string, 0, numNodes)\n\t\tif numNodes == len(nodes) {\n\t\t\t// Copy all node names.\n\t\t\tfor _, node := range nodes {\n\t\t\t\tschedulingCtx.Spec.PotentialNodes = append(schedulingCtx.Spec.PotentialNodes, node.Name)\n\t\t\t}\n\t\t} else {\n\t\t\t// Select a random subset of the nodes to comply with\n\t\t\t// the PotentialNodes length limit. Randomization is\n\t\t\t// done for us by Go which iterates over map entries\n\t\t\t// randomly.\n\t\t\tnodeNames := map[string]struct{}{}\n\t\t\tfor _, node := range nodes {\n\t\t\t\tnodeNames[node.Name] = struct{}{}\n\t\t\t}\n\t\t\tfor nodeName := range nodeNames {\n\t\t\t\tif len(schedulingCtx.Spec.PotentialNodes) \u003e= resourcev1alpha2.PodSchedulingNodeListMaxSize {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tschedulingCtx.Spec.PotentialNodes = append(schedulingCtx.Spec.PotentialNodes, nodeName)\n\t\t\t}\n\t\t}\n\t\tsort.Strings(schedulingCtx.Spec.PotentialNodes)\n\t\tstate.storePodSchedulingContexts(schedulingCtx)\n\t}\n\tlogger.V(5).Info(\"all potential nodes already set\", \"pod\", klog.KObj(pod), \"potentialnodes\", nodes)\n\treturn nil\n}","line":{"from":517,"to":581}} {"id":100010744,"name":"haveAllNodes","signature":"func haveAllNodes(nodeNames []string, nodes []*v1.Node) bool","file":"pkg/scheduler/framework/plugins/dynamicresources/dynamicresources.go","code":"func haveAllNodes(nodeNames []string, nodes []*v1.Node) bool {\n\tfor _, node := range nodes {\n\t\tif !haveNode(nodeNames, node.Name) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":583,"to":590}} {"id":100010745,"name":"haveNode","signature":"func haveNode(nodeNames []string, nodeName string) bool","file":"pkg/scheduler/framework/plugins/dynamicresources/dynamicresources.go","code":"func haveNode(nodeNames []string, nodeName string) bool {\n\tfor _, n := range nodeNames {\n\t\tif n == nodeName {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":592,"to":599}} {"id":100010746,"name":"Reserve","signature":"func (pl *dynamicResources) Reserve(ctx context.Context, cs *framework.CycleState, pod *v1.Pod, nodeName string) *framework.Status","file":"pkg/scheduler/framework/plugins/dynamicresources/dynamicresources.go","code":"// Reserve reserves claims for the pod.\nfunc (pl *dynamicResources) Reserve(ctx context.Context, cs *framework.CycleState, pod *v1.Pod, nodeName string) *framework.Status {\n\tif !pl.enabled {\n\t\treturn nil\n\t}\n\tstate, err := getStateData(cs)\n\tif err != nil {\n\t\treturn statusError(klog.FromContext(ctx), err)\n\t}\n\tif len(state.claims) == 0 {\n\t\treturn nil\n\t}\n\n\tnumDelayedAllocationPending := 0\n\tnumClaimsWithStatusInfo := 0\n\tlogger := klog.FromContext(ctx)\n\tschedulingCtx, err := state.initializePodSchedulingContexts(ctx, pod, pl.podSchedulingContextLister)\n\tif err != nil {\n\t\treturn statusError(logger, err)\n\t}\n\tfor index, claim := range state.claims {\n\t\tif claim.Status.Allocation != nil {\n\t\t\t// Allocated, but perhaps not reserved yet.\n\t\t\tif resourceclaim.IsReservedForPod(pod, claim) {\n\t\t\t\tlogger.V(5).Info(\"is reserved\", \"pod\", klog.KObj(pod), \"node\", klog.ObjectRef{Name: nodeName}, \"resourceclaim\", klog.KObj(claim))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tclaim := claim.DeepCopy()\n\t\t\tclaim.Status.ReservedFor = append(claim.Status.ReservedFor,\n\t\t\t\tresourcev1alpha2.ResourceClaimConsumerReference{\n\t\t\t\t\tResource: \"pods\",\n\t\t\t\t\tName: pod.Name,\n\t\t\t\t\tUID: pod.UID,\n\t\t\t\t})\n\t\t\tlogger.V(5).Info(\"reserve\", \"pod\", klog.KObj(pod), \"node\", klog.ObjectRef{Name: nodeName}, \"resourceclaim\", klog.KObj(claim))\n\t\t\t_, err := pl.clientset.ResourceV1alpha2().ResourceClaims(claim.Namespace).UpdateStatus(ctx, claim, metav1.UpdateOptions{})\n\t\t\t// TODO: metric for update errors.\n\t\t\tif err != nil {\n\t\t\t\treturn statusError(logger, err)\n\t\t\t}\n\t\t\t// If we get here, we know that reserving the claim for\n\t\t\t// the pod worked and we can proceed with schedulingCtx\n\t\t\t// it.\n\t\t} else {\n\t\t\t// Must be delayed allocation.\n\t\t\tnumDelayedAllocationPending++\n\n\t\t\t// Did the driver provide information that steered node\n\t\t\t// selection towards a node that it can support?\n\t\t\tif statusForClaim(schedulingCtx, pod.Spec.ResourceClaims[index].Name) != nil {\n\t\t\t\tnumClaimsWithStatusInfo++\n\t\t\t}\n\t\t}\n\t}\n\n\tif numDelayedAllocationPending == 0 {\n\t\t// Nothing left to do.\n\t\treturn nil\n\t}\n\n\tpodSchedulingDirty := state.podSchedulingDirty\n\tif len(schedulingCtx.Spec.PotentialNodes) == 0 {\n\t\t// PreScore was not called, probably because there was\n\t\t// only one candidate. We need to ask whether that\n\t\t// node is suitable, otherwise the scheduler will pick\n\t\t// it forever even when it cannot satisfy the claim.\n\t\tschedulingCtx = schedulingCtx.DeepCopy()\n\t\tschedulingCtx.Spec.PotentialNodes = []string{nodeName}\n\t\tlogger.V(5).Info(\"asking for information about single potential node\", \"pod\", klog.KObj(pod), \"node\", klog.ObjectRef{Name: nodeName})\n\t\tpodSchedulingDirty = true\n\t}\n\n\t// When there is only one pending resource, we can go ahead with\n\t// requesting allocation even when we don't have the information from\n\t// the driver yet. Otherwise we wait for information before blindly\n\t// making a decision that might have to be reversed later.\n\tif numDelayedAllocationPending == 1 || numClaimsWithStatusInfo == numDelayedAllocationPending {\n\t\tschedulingCtx = schedulingCtx.DeepCopy()\n\t\t// TODO: can we increase the chance that the scheduler picks\n\t\t// the same node as before when allocation is on-going,\n\t\t// assuming that that node still fits the pod? Picking a\n\t\t// different node may lead to some claims being allocated for\n\t\t// one node and others for another, which then would have to be\n\t\t// resolved with deallocation.\n\t\tschedulingCtx.Spec.SelectedNode = nodeName\n\t\tlogger.V(5).Info(\"start allocation\", \"pod\", klog.KObj(pod), \"node\", klog.ObjectRef{Name: nodeName})\n\t\tif err := state.publishPodSchedulingContexts(ctx, pl.clientset, schedulingCtx); err != nil {\n\t\t\treturn statusError(logger, err)\n\t\t}\n\t\treturn statusUnschedulable(logger, \"waiting for resource driver to allocate resource\", \"pod\", klog.KObj(pod), \"node\", klog.ObjectRef{Name: nodeName})\n\t}\n\n\t// May have been modified earlier in PreScore or above.\n\tif podSchedulingDirty {\n\t\tif err := state.publishPodSchedulingContexts(ctx, pl.clientset, schedulingCtx); err != nil {\n\t\t\treturn statusError(logger, err)\n\t\t}\n\t}\n\n\t// More than one pending claim and not enough information about all of them.\n\t//\n\t// TODO: can or should we ensure that schedulingCtx gets aborted while\n\t// waiting for resources *before* triggering delayed volume\n\t// provisioning? On the one hand, volume provisioning is currently\n\t// irreversible, so it better should come last. On the other hand,\n\t// triggering both in parallel might be faster.\n\treturn statusUnschedulable(logger, \"waiting for resource driver to provide information\", \"pod\", klog.KObj(pod))\n}","line":{"from":601,"to":708}} {"id":100010747,"name":"Unreserve","signature":"func (pl *dynamicResources) Unreserve(ctx context.Context, cs *framework.CycleState, pod *v1.Pod, nodeName string)","file":"pkg/scheduler/framework/plugins/dynamicresources/dynamicresources.go","code":"// Unreserve clears the ReservedFor field for all claims.\n// It's idempotent, and does nothing if no state found for the given pod.\nfunc (pl *dynamicResources) Unreserve(ctx context.Context, cs *framework.CycleState, pod *v1.Pod, nodeName string) {\n\tif !pl.enabled {\n\t\treturn\n\t}\n\tstate, err := getStateData(cs)\n\tif err != nil {\n\t\treturn\n\t}\n\tif len(state.claims) == 0 {\n\t\treturn\n\t}\n\n\tlogger := klog.FromContext(ctx)\n\tfor index, claim := range state.claims {\n\t\tif claim.Status.Allocation != nil \u0026\u0026\n\t\t\tresourceclaim.IsReservedForPod(pod, claim) {\n\t\t\t// Remove pod from ReservedFor.\n\t\t\tclaim := claim.DeepCopy()\n\t\t\treservedFor := make([]resourcev1alpha2.ResourceClaimConsumerReference, 0, len(claim.Status.ReservedFor)-1)\n\t\t\tfor _, reserved := range claim.Status.ReservedFor {\n\t\t\t\t// TODO: can UID be assumed to be unique all resources or do we also need to compare Group/Version/Resource?\n\t\t\t\tif reserved.UID != pod.UID {\n\t\t\t\t\treservedFor = append(reservedFor, reserved)\n\t\t\t\t}\n\t\t\t}\n\t\t\tclaim.Status.ReservedFor = reservedFor\n\t\t\tlogger.V(5).Info(\"unreserve\", \"resourceclaim\", klog.KObj(claim))\n\t\t\tif err := state.updateClaimStatus(ctx, pl.clientset, index, claim); err != nil {\n\t\t\t\t// We will get here again when pod schedulingCtx\n\t\t\t\t// is retried.\n\t\t\t\tlogger.Error(err, \"unreserve\", \"resourceclaim\", klog.KObj(claim))\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":710,"to":746}} {"id":100010748,"name":"PostBind","signature":"func (pl *dynamicResources) PostBind(ctx context.Context, cs *framework.CycleState, pod *v1.Pod, nodeName string)","file":"pkg/scheduler/framework/plugins/dynamicresources/dynamicresources.go","code":"// PostBind is called after a pod is successfully bound to a node. Now we are\n// sure that a PodSchedulingContext object, if it exists, is definitely not going to\n// be needed anymore and can delete it. This is a one-shot thing, there won't\n// be any retries. This is okay because it should usually work and in those\n// cases where it doesn't, the garbage collector will eventually clean up.\nfunc (pl *dynamicResources) PostBind(ctx context.Context, cs *framework.CycleState, pod *v1.Pod, nodeName string) {\n\tif !pl.enabled {\n\t\treturn\n\t}\n\tstate, err := getStateData(cs)\n\tif err != nil {\n\t\treturn\n\t}\n\tif len(state.claims) == 0 {\n\t\treturn\n\t}\n\n\t// We cannot know for sure whether the PodSchedulingContext object exists. We\n\t// might have created it in the previous pod schedulingCtx cycle and not\n\t// have it in our informer cache yet. Let's try to delete, just to be\n\t// on the safe side.\n\tlogger := klog.FromContext(ctx)\n\terr = pl.clientset.ResourceV1alpha2().PodSchedulingContexts(pod.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{})\n\tswitch {\n\tcase apierrors.IsNotFound(err):\n\t\tlogger.V(5).Info(\"no PodSchedulingContext object to delete\")\n\tcase err != nil:\n\t\tlogger.Error(err, \"delete PodSchedulingContext\")\n\tdefault:\n\t\tlogger.V(5).Info(\"PodSchedulingContext object deleted\")\n\t}\n}","line":{"from":748,"to":779}} {"id":100010749,"name":"statusUnschedulable","signature":"func statusUnschedulable(logger klog.Logger, reason string, kv ...interface{}) *framework.Status","file":"pkg/scheduler/framework/plugins/dynamicresources/dynamicresources.go","code":"// statusUnschedulable ensures that there is a log message associated with the\n// line where the status originated.\nfunc statusUnschedulable(logger klog.Logger, reason string, kv ...interface{}) *framework.Status {\n\tif loggerV := logger.V(5); loggerV.Enabled() {\n\t\thelper, loggerV := loggerV.WithCallStackHelper()\n\t\thelper()\n\t\tkv = append(kv, \"reason\", reason)\n\t\t// nolint: logcheck // warns because it cannot check key/values\n\t\tloggerV.Info(\"pod unschedulable\", kv...)\n\t}\n\treturn framework.NewStatus(framework.UnschedulableAndUnresolvable, reason)\n}","line":{"from":781,"to":792}} {"id":100010750,"name":"statusError","signature":"func statusError(logger klog.Logger, err error, kv ...interface{}) *framework.Status","file":"pkg/scheduler/framework/plugins/dynamicresources/dynamicresources.go","code":"// statusError ensures that there is a log message associated with the\n// line where the error originated.\nfunc statusError(logger klog.Logger, err error, kv ...interface{}) *framework.Status {\n\tif loggerV := logger.V(5); loggerV.Enabled() {\n\t\thelper, loggerV := loggerV.WithCallStackHelper()\n\t\thelper()\n\t\t// nolint: logcheck // warns because it cannot check key/values\n\t\tloggerV.Error(err, \"dynamic resource plugin failed\", kv...)\n\t}\n\treturn framework.AsStatus(err)\n}","line":{"from":794,"to":804}} {"id":100010751,"name":"DefaultNormalizeScore","signature":"func DefaultNormalizeScore(maxPriority int64, reverse bool, scores framework.NodeScoreList) *framework.Status","file":"pkg/scheduler/framework/plugins/helper/normalize_score.go","code":"// DefaultNormalizeScore generates a Normalize Score function that can normalize the\n// scores from [0, max(scores)] to [0, maxPriority]. If reverse is set to true, it\n// reverses the scores by subtracting it from maxPriority.\n// Note: The input scores are always assumed to be non-negative integers.\nfunc DefaultNormalizeScore(maxPriority int64, reverse bool, scores framework.NodeScoreList) *framework.Status {\n\tvar maxCount int64\n\tfor i := range scores {\n\t\tif scores[i].Score \u003e maxCount {\n\t\t\tmaxCount = scores[i].Score\n\t\t}\n\t}\n\n\tif maxCount == 0 {\n\t\tif reverse {\n\t\t\tfor i := range scores {\n\t\t\t\tscores[i].Score = maxPriority\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\tfor i := range scores {\n\t\tscore := scores[i].Score\n\n\t\tscore = maxPriority * score / maxCount\n\t\tif reverse {\n\t\t\tscore = maxPriority - score\n\t\t}\n\n\t\tscores[i].Score = score\n\t}\n\treturn nil\n}","line":{"from":23,"to":55}} {"id":100010752,"name":"BuildBrokenLinearFunction","signature":"func BuildBrokenLinearFunction(shape FunctionShape) func(int64) int64","file":"pkg/scheduler/framework/plugins/helper/shape_score.go","code":"// BuildBrokenLinearFunction creates a function which is built using linear segments. Segments are defined via shape array.\n// Shape[i].Utilization slice represents points on \"Utilization\" axis where different segments meet.\n// Shape[i].Score represents function values at meeting points.\n//\n// function f(p) is defined as:\n//\n//\tshape[0].Score for p \u003c shape[0].Utilization\n//\tshape[n-1].Score for p \u003e shape[n-1].Utilization\n//\n// and linear between points (p \u003c shape[i].Utilization)\nfunc BuildBrokenLinearFunction(shape FunctionShape) func(int64) int64 {\n\treturn func(p int64) int64 {\n\t\tfor i := 0; i \u003c len(shape); i++ {\n\t\t\tif p \u003c= int64(shape[i].Utilization) {\n\t\t\t\tif i == 0 {\n\t\t\t\t\treturn shape[0].Score\n\t\t\t\t}\n\t\t\t\treturn shape[i-1].Score + (shape[i].Score-shape[i-1].Score)*(p-shape[i-1].Utilization)/(shape[i].Utilization-shape[i-1].Utilization)\n\t\t\t}\n\t\t}\n\t\treturn shape[len(shape)-1].Score\n\t}\n}","line":{"from":30,"to":52}} {"id":100010753,"name":"DefaultSelector","signature":"func DefaultSelector(","file":"pkg/scheduler/framework/plugins/helper/spread.go","code":"// DefaultSelector returns a selector deduced from the Services, Replication\n// Controllers, Replica Sets, and Stateful Sets matching the given pod.\nfunc DefaultSelector(\n\tpod *v1.Pod,\n\tsl corelisters.ServiceLister,\n\tcl corelisters.ReplicationControllerLister,\n\trsl appslisters.ReplicaSetLister,\n\tssl appslisters.StatefulSetLister,\n) labels.Selector {\n\tlabelSet := make(labels.Set)\n\t// Since services, RCs, RSs and SSs match the pod, they won't have conflicting\n\t// labels. Merging is safe.\n\n\tif services, err := GetPodServices(sl, pod); err == nil {\n\t\tfor _, service := range services {\n\t\t\tlabelSet = labels.Merge(labelSet, service.Spec.Selector)\n\t\t}\n\t}\n\tselector := labelSet.AsSelector()\n\n\towner := metav1.GetControllerOfNoCopy(pod)\n\tif owner == nil {\n\t\treturn selector\n\t}\n\n\tgv, err := schema.ParseGroupVersion(owner.APIVersion)\n\tif err != nil {\n\t\treturn selector\n\t}\n\n\tgvk := gv.WithKind(owner.Kind)\n\tswitch gvk {\n\tcase rcKind:\n\t\tif rc, err := cl.ReplicationControllers(pod.Namespace).Get(owner.Name); err == nil {\n\t\t\tlabelSet = labels.Merge(labelSet, rc.Spec.Selector)\n\t\t\tselector = labelSet.AsSelector()\n\t\t}\n\tcase rsKind:\n\t\tif rs, err := rsl.ReplicaSets(pod.Namespace).Get(owner.Name); err == nil {\n\t\t\tif other, err := metav1.LabelSelectorAsSelector(rs.Spec.Selector); err == nil {\n\t\t\t\tif r, ok := other.Requirements(); ok {\n\t\t\t\t\tselector = selector.Add(r...)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase ssKind:\n\t\tif ss, err := ssl.StatefulSets(pod.Namespace).Get(owner.Name); err == nil {\n\t\t\tif other, err := metav1.LabelSelectorAsSelector(ss.Spec.Selector); err == nil {\n\t\t\t\tif r, ok := other.Requirements(); ok {\n\t\t\t\t\tselector = selector.Add(r...)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tdefault:\n\t\t// Not owned by a supported controller.\n\t}\n\n\treturn selector\n}","line":{"from":35,"to":93}} {"id":100010754,"name":"GetPodServices","signature":"func GetPodServices(sl corelisters.ServiceLister, pod *v1.Pod) ([]*v1.Service, error)","file":"pkg/scheduler/framework/plugins/helper/spread.go","code":"// GetPodServices gets the services that have the selector that match the labels on the given pod.\nfunc GetPodServices(sl corelisters.ServiceLister, pod *v1.Pod) ([]*v1.Service, error) {\n\tallServices, err := sl.Services(pod.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar services []*v1.Service\n\tfor i := range allServices {\n\t\tservice := allServices[i]\n\t\tif service.Spec.Selector == nil {\n\t\t\t// services with nil selectors match nothing, not everything.\n\t\t\tcontinue\n\t\t}\n\t\tselector := labels.Set(service.Spec.Selector).AsSelectorPreValidated()\n\t\tif selector.Matches(labels.Set(pod.Labels)) {\n\t\t\tservices = append(services, service)\n\t\t}\n\t}\n\n\treturn services, nil\n}","line":{"from":95,"to":116}} {"id":100010755,"name":"DoNotScheduleTaintsFilterFunc","signature":"func DoNotScheduleTaintsFilterFunc() func(t *v1.Taint) bool","file":"pkg/scheduler/framework/plugins/helper/taint.go","code":"// DoNotScheduleTaintsFilterFunc returns the filter function that can\n// filter out the node taints that reject scheduling Pod on a Node.\nfunc DoNotScheduleTaintsFilterFunc() func(t *v1.Taint) bool {\n\treturn func(t *v1.Taint) bool {\n\t\t// PodToleratesNodeTaints is only interested in NoSchedule and NoExecute taints.\n\t\treturn t.Effect == v1.TaintEffectNoSchedule || t.Effect == v1.TaintEffectNoExecute\n\t}\n}","line":{"from":21,"to":28}} {"id":100010756,"name":"Name","signature":"func (pl *ImageLocality) Name() string","file":"pkg/scheduler/framework/plugins/imagelocality/image_locality.go","code":"// Name returns name of the plugin. It is used in logs, etc.\nfunc (pl *ImageLocality) Name() string {\n\treturn Name\n}","line":{"from":48,"to":51}} {"id":100010757,"name":"Score","signature":"func (pl *ImageLocality) Score(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status)","file":"pkg/scheduler/framework/plugins/imagelocality/image_locality.go","code":"// Score invoked at the score extension point.\nfunc (pl *ImageLocality) Score(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status) {\n\tnodeInfo, err := pl.handle.SnapshotSharedLister().NodeInfos().Get(nodeName)\n\tif err != nil {\n\t\treturn 0, framework.AsStatus(fmt.Errorf(\"getting node %q from Snapshot: %w\", nodeName, err))\n\t}\n\n\tnodeInfos, err := pl.handle.SnapshotSharedLister().NodeInfos().List()\n\tif err != nil {\n\t\treturn 0, framework.AsStatus(err)\n\t}\n\ttotalNumNodes := len(nodeInfos)\n\n\tscore := calculatePriority(sumImageScores(nodeInfo, pod.Spec.Containers, totalNumNodes), len(pod.Spec.Containers))\n\n\treturn score, nil\n}","line":{"from":53,"to":69}} {"id":100010758,"name":"ScoreExtensions","signature":"func (pl *ImageLocality) ScoreExtensions() framework.ScoreExtensions","file":"pkg/scheduler/framework/plugins/imagelocality/image_locality.go","code":"// ScoreExtensions of the Score plugin.\nfunc (pl *ImageLocality) ScoreExtensions() framework.ScoreExtensions {\n\treturn nil\n}","line":{"from":71,"to":74}} {"id":100010759,"name":"New","signature":"func New(_ runtime.Object, h framework.Handle) (framework.Plugin, error)","file":"pkg/scheduler/framework/plugins/imagelocality/image_locality.go","code":"// New initializes a new plugin and returns it.\nfunc New(_ runtime.Object, h framework.Handle) (framework.Plugin, error) {\n\treturn \u0026ImageLocality{handle: h}, nil\n}","line":{"from":76,"to":79}} {"id":100010760,"name":"calculatePriority","signature":"func calculatePriority(sumScores int64, numContainers int) int64","file":"pkg/scheduler/framework/plugins/imagelocality/image_locality.go","code":"// calculatePriority returns the priority of a node. Given the sumScores of requested images on the node, the node's\n// priority is obtained by scaling the maximum priority value with a ratio proportional to the sumScores.\nfunc calculatePriority(sumScores int64, numContainers int) int64 {\n\tmaxThreshold := maxContainerThreshold * int64(numContainers)\n\tif sumScores \u003c minThreshold {\n\t\tsumScores = minThreshold\n\t} else if sumScores \u003e maxThreshold {\n\t\tsumScores = maxThreshold\n\t}\n\n\treturn int64(framework.MaxNodeScore) * (sumScores - minThreshold) / (maxThreshold - minThreshold)\n}","line":{"from":81,"to":92}} {"id":100010761,"name":"sumImageScores","signature":"func sumImageScores(nodeInfo *framework.NodeInfo, containers []v1.Container, totalNumNodes int) int64","file":"pkg/scheduler/framework/plugins/imagelocality/image_locality.go","code":"// sumImageScores returns the sum of image scores of all the containers that are already on the node.\n// Each image receives a raw score of its size, scaled by scaledImageScore. The raw scores are later used to calculate\n// the final score. Note that the init containers are not considered for it's rare for users to deploy huge init containers.\nfunc sumImageScores(nodeInfo *framework.NodeInfo, containers []v1.Container, totalNumNodes int) int64 {\n\tvar sum int64\n\tfor _, container := range containers {\n\t\tif state, ok := nodeInfo.ImageStates[normalizedImageName(container.Image)]; ok {\n\t\t\tsum += scaledImageScore(state, totalNumNodes)\n\t\t}\n\t}\n\treturn sum\n}","line":{"from":94,"to":105}} {"id":100010762,"name":"scaledImageScore","signature":"func scaledImageScore(imageState *framework.ImageStateSummary, totalNumNodes int) int64","file":"pkg/scheduler/framework/plugins/imagelocality/image_locality.go","code":"// scaledImageScore returns an adaptively scaled score for the given state of an image.\n// The size of the image is used as the base score, scaled by a factor which considers how much nodes the image has \"spread\" to.\n// This heuristic aims to mitigate the undesirable \"node heating problem\", i.e., pods get assigned to the same or\n// a few nodes due to image locality.\nfunc scaledImageScore(imageState *framework.ImageStateSummary, totalNumNodes int) int64 {\n\tspread := float64(imageState.NumNodes) / float64(totalNumNodes)\n\treturn int64(float64(imageState.Size) * spread)\n}","line":{"from":107,"to":114}} {"id":100010763,"name":"normalizedImageName","signature":"func normalizedImageName(name string) string","file":"pkg/scheduler/framework/plugins/imagelocality/image_locality.go","code":"// normalizedImageName returns the CRI compliant name for a given image.\n// TODO: cover the corner cases of missed matches, e.g,\n// 1. Using Docker as runtime and docker.io/library/test:tag in pod spec, but only test:tag will present in node status\n// 2. Using the implicit registry, i.e., test:tag or library/test:tag in pod spec but only docker.io/library/test:tag\n// in node status; note that if users consistently use one registry format, this should not happen.\nfunc normalizedImageName(name string) string {\n\tif strings.LastIndex(name, \":\") \u003c= strings.LastIndex(name, \"/\") {\n\t\tname = name + \":latest\"\n\t}\n\treturn name\n}","line":{"from":116,"to":126}} {"id":100010764,"name":"Clone","signature":"func (s *preFilterState) Clone() framework.StateData","file":"pkg/scheduler/framework/plugins/interpodaffinity/filtering.go","code":"// Clone the prefilter state.\nfunc (s *preFilterState) Clone() framework.StateData {\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\tcopy := preFilterState{}\n\tcopy.affinityCounts = s.affinityCounts.clone()\n\tcopy.antiAffinityCounts = s.antiAffinityCounts.clone()\n\tcopy.existingAntiAffinityCounts = s.existingAntiAffinityCounts.clone()\n\t// No need to deep copy the podInfo because it shouldn't change.\n\tcopy.podInfo = s.podInfo\n\tcopy.namespaceLabels = s.namespaceLabels\n\treturn \u0026copy\n}","line":{"from":57,"to":71}} {"id":100010765,"name":"updateWithPod","signature":"func (s *preFilterState) updateWithPod(pInfo *framework.PodInfo, node *v1.Node, multiplier int64)","file":"pkg/scheduler/framework/plugins/interpodaffinity/filtering.go","code":"// updateWithPod updates the preFilterState counters with the (anti)affinity matches for the given podInfo.\nfunc (s *preFilterState) updateWithPod(pInfo *framework.PodInfo, node *v1.Node, multiplier int64) {\n\tif s == nil {\n\t\treturn\n\t}\n\n\ts.existingAntiAffinityCounts.updateWithAntiAffinityTerms(pInfo.RequiredAntiAffinityTerms, s.podInfo.Pod, s.namespaceLabels, node, multiplier)\n\ts.affinityCounts.updateWithAffinityTerms(s.podInfo.RequiredAffinityTerms, pInfo.Pod, node, multiplier)\n\t// The incoming pod's terms have the namespaceSelector merged into the namespaces, and so\n\t// here we don't lookup the updated pod's namespace labels, hence passing nil for nsLabels.\n\ts.antiAffinityCounts.updateWithAntiAffinityTerms(s.podInfo.RequiredAntiAffinityTerms, pInfo.Pod, nil, node, multiplier)\n}","line":{"from":73,"to":84}} {"id":100010766,"name":"append","signature":"func (m topologyToMatchedTermCount) append(toAppend topologyToMatchedTermCount)","file":"pkg/scheduler/framework/plugins/interpodaffinity/filtering.go","code":"func (m topologyToMatchedTermCount) append(toAppend topologyToMatchedTermCount) {\n\tfor pair := range toAppend {\n\t\tm[pair] += toAppend[pair]\n\t}\n}","line":{"from":92,"to":96}} {"id":100010767,"name":"clone","signature":"func (m topologyToMatchedTermCount) clone() topologyToMatchedTermCount","file":"pkg/scheduler/framework/plugins/interpodaffinity/filtering.go","code":"func (m topologyToMatchedTermCount) clone() topologyToMatchedTermCount {\n\tcopy := make(topologyToMatchedTermCount, len(m))\n\tcopy.append(m)\n\treturn copy\n}","line":{"from":98,"to":102}} {"id":100010768,"name":"update","signature":"func (m topologyToMatchedTermCount) update(node *v1.Node, tk string, value int64)","file":"pkg/scheduler/framework/plugins/interpodaffinity/filtering.go","code":"func (m topologyToMatchedTermCount) update(node *v1.Node, tk string, value int64) {\n\tif tv, ok := node.Labels[tk]; ok {\n\t\tpair := topologyPair{key: tk, value: tv}\n\t\tm[pair] += value\n\t\t// value could be negative, hence we delete the entry if it is down to zero.\n\t\tif m[pair] == 0 {\n\t\t\tdelete(m, pair)\n\t\t}\n\t}\n}","line":{"from":104,"to":113}} {"id":100010769,"name":"updateWithAffinityTerms","signature":"func (m topologyToMatchedTermCount) updateWithAffinityTerms(","file":"pkg/scheduler/framework/plugins/interpodaffinity/filtering.go","code":"// updates the topologyToMatchedTermCount map with the specified value\n// for each affinity term if \"targetPod\" matches ALL terms.\nfunc (m topologyToMatchedTermCount) updateWithAffinityTerms(\n\tterms []framework.AffinityTerm, pod *v1.Pod, node *v1.Node, value int64) {\n\tif podMatchesAllAffinityTerms(terms, pod) {\n\t\tfor _, t := range terms {\n\t\t\tm.update(node, t.TopologyKey, value)\n\t\t}\n\t}\n}","line":{"from":115,"to":124}} {"id":100010770,"name":"updateWithAntiAffinityTerms","signature":"func (m topologyToMatchedTermCount) updateWithAntiAffinityTerms(terms []framework.AffinityTerm, pod *v1.Pod, nsLabels labels.Set, node *v1.Node, value int64)","file":"pkg/scheduler/framework/plugins/interpodaffinity/filtering.go","code":"// updates the topologyToMatchedTermCount map with the specified value\n// for each anti-affinity term matched the target pod.\nfunc (m topologyToMatchedTermCount) updateWithAntiAffinityTerms(terms []framework.AffinityTerm, pod *v1.Pod, nsLabels labels.Set, node *v1.Node, value int64) {\n\t// Check anti-affinity terms.\n\tfor _, t := range terms {\n\t\tif t.Matches(pod, nsLabels) {\n\t\t\tm.update(node, t.TopologyKey, value)\n\t\t}\n\t}\n}","line":{"from":126,"to":135}} {"id":100010771,"name":"podMatchesAllAffinityTerms","signature":"func podMatchesAllAffinityTerms(terms []framework.AffinityTerm, pod *v1.Pod) bool","file":"pkg/scheduler/framework/plugins/interpodaffinity/filtering.go","code":"// returns true IFF the given pod matches all the given terms.\nfunc podMatchesAllAffinityTerms(terms []framework.AffinityTerm, pod *v1.Pod) bool {\n\tif len(terms) == 0 {\n\t\treturn false\n\t}\n\tfor _, t := range terms {\n\t\t// The incoming pod NamespaceSelector was merged into the Namespaces set, and so\n\t\t// we are not explicitly passing in namespace labels.\n\t\tif !t.Matches(pod, nil) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":137,"to":150}} {"id":100010772,"name":"getExistingAntiAffinityCounts","signature":"func (pl *InterPodAffinity) getExistingAntiAffinityCounts(ctx context.Context, pod *v1.Pod, nsLabels labels.Set, nodes []*framework.NodeInfo) topologyToMatchedTermCount","file":"pkg/scheduler/framework/plugins/interpodaffinity/filtering.go","code":"// calculates the following for each existing pod on each node:\n// 1. Whether it has PodAntiAffinity\n// 2. Whether any AntiAffinityTerm matches the incoming pod\nfunc (pl *InterPodAffinity) getExistingAntiAffinityCounts(ctx context.Context, pod *v1.Pod, nsLabels labels.Set, nodes []*framework.NodeInfo) topologyToMatchedTermCount {\n\ttopoMaps := make([]topologyToMatchedTermCount, len(nodes))\n\tindex := int32(-1)\n\tprocessNode := func(i int) {\n\t\tnodeInfo := nodes[i]\n\t\tnode := nodeInfo.Node()\n\t\tif node == nil {\n\t\t\tklog.ErrorS(nil, \"Node not found\")\n\t\t\treturn\n\t\t}\n\t\ttopoMap := make(topologyToMatchedTermCount)\n\t\tfor _, existingPod := range nodeInfo.PodsWithRequiredAntiAffinity {\n\t\t\ttopoMap.updateWithAntiAffinityTerms(existingPod.RequiredAntiAffinityTerms, pod, nsLabels, node, 1)\n\t\t}\n\t\tif len(topoMap) != 0 {\n\t\t\ttopoMaps[atomic.AddInt32(\u0026index, 1)] = topoMap\n\t\t}\n\t}\n\tpl.parallelizer.Until(ctx, len(nodes), processNode, pl.Name())\n\n\tresult := make(topologyToMatchedTermCount)\n\tfor i := 0; i \u003c= int(index); i++ {\n\t\tresult.append(topoMaps[i])\n\t}\n\n\treturn result\n}","line":{"from":152,"to":181}} {"id":100010773,"name":"getIncomingAffinityAntiAffinityCounts","signature":"func (pl *InterPodAffinity) getIncomingAffinityAntiAffinityCounts(ctx context.Context, podInfo *framework.PodInfo, allNodes []*framework.NodeInfo) (topologyToMatchedTermCount, topologyToMatchedTermCount)","file":"pkg/scheduler/framework/plugins/interpodaffinity/filtering.go","code":"// finds existing Pods that match affinity terms of the incoming pod's (anti)affinity terms.\n// It returns a topologyToMatchedTermCount that are checked later by the affinity\n// predicate. With this topologyToMatchedTermCount available, the affinity predicate does not\n// need to check all the pods in the cluster.\nfunc (pl *InterPodAffinity) getIncomingAffinityAntiAffinityCounts(ctx context.Context, podInfo *framework.PodInfo, allNodes []*framework.NodeInfo) (topologyToMatchedTermCount, topologyToMatchedTermCount) {\n\taffinityCounts := make(topologyToMatchedTermCount)\n\tantiAffinityCounts := make(topologyToMatchedTermCount)\n\tif len(podInfo.RequiredAffinityTerms) == 0 \u0026\u0026 len(podInfo.RequiredAntiAffinityTerms) == 0 {\n\t\treturn affinityCounts, antiAffinityCounts\n\t}\n\n\taffinityCountsList := make([]topologyToMatchedTermCount, len(allNodes))\n\tantiAffinityCountsList := make([]topologyToMatchedTermCount, len(allNodes))\n\tindex := int32(-1)\n\tprocessNode := func(i int) {\n\t\tnodeInfo := allNodes[i]\n\t\tnode := nodeInfo.Node()\n\t\tif node == nil {\n\t\t\tklog.ErrorS(nil, \"Node not found\")\n\t\t\treturn\n\t\t}\n\t\taffinity := make(topologyToMatchedTermCount)\n\t\tantiAffinity := make(topologyToMatchedTermCount)\n\t\tfor _, existingPod := range nodeInfo.Pods {\n\t\t\taffinity.updateWithAffinityTerms(podInfo.RequiredAffinityTerms, existingPod.Pod, node, 1)\n\t\t\t// The incoming pod's terms have the namespaceSelector merged into the namespaces, and so\n\t\t\t// here we don't lookup the existing pod's namespace labels, hence passing nil for nsLabels.\n\t\t\tantiAffinity.updateWithAntiAffinityTerms(podInfo.RequiredAntiAffinityTerms, existingPod.Pod, nil, node, 1)\n\t\t}\n\n\t\tif len(affinity) \u003e 0 || len(antiAffinity) \u003e 0 {\n\t\t\tk := atomic.AddInt32(\u0026index, 1)\n\t\t\taffinityCountsList[k] = affinity\n\t\t\tantiAffinityCountsList[k] = antiAffinity\n\t\t}\n\t}\n\tpl.parallelizer.Until(ctx, len(allNodes), processNode, pl.Name())\n\n\tfor i := 0; i \u003c= int(index); i++ {\n\t\taffinityCounts.append(affinityCountsList[i])\n\t\tantiAffinityCounts.append(antiAffinityCountsList[i])\n\t}\n\n\treturn affinityCounts, antiAffinityCounts\n}","line":{"from":183,"to":227}} {"id":100010774,"name":"PreFilter","signature":"func (pl *InterPodAffinity) PreFilter(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod) (*framework.PreFilterResult, *framework.Status)","file":"pkg/scheduler/framework/plugins/interpodaffinity/filtering.go","code":"// PreFilter invoked at the prefilter extension point.\nfunc (pl *InterPodAffinity) PreFilter(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod) (*framework.PreFilterResult, *framework.Status) {\n\tvar allNodes []*framework.NodeInfo\n\tvar nodesWithRequiredAntiAffinityPods []*framework.NodeInfo\n\tvar err error\n\tif allNodes, err = pl.sharedLister.NodeInfos().List(); err != nil {\n\t\treturn nil, framework.AsStatus(fmt.Errorf(\"failed to list NodeInfos: %w\", err))\n\t}\n\tif nodesWithRequiredAntiAffinityPods, err = pl.sharedLister.NodeInfos().HavePodsWithRequiredAntiAffinityList(); err != nil {\n\t\treturn nil, framework.AsStatus(fmt.Errorf(\"failed to list NodeInfos with pods with affinity: %w\", err))\n\t}\n\n\ts := \u0026preFilterState{}\n\n\tif s.podInfo, err = framework.NewPodInfo(pod); err != nil {\n\t\treturn nil, framework.NewStatus(framework.UnschedulableAndUnresolvable, fmt.Sprintf(\"parsing pod: %+v\", err))\n\t}\n\n\tfor i := range s.podInfo.RequiredAffinityTerms {\n\t\tif err := pl.mergeAffinityTermNamespacesIfNotEmpty(\u0026s.podInfo.RequiredAffinityTerms[i]); err != nil {\n\t\t\treturn nil, framework.AsStatus(err)\n\t\t}\n\t}\n\tfor i := range s.podInfo.RequiredAntiAffinityTerms {\n\t\tif err := pl.mergeAffinityTermNamespacesIfNotEmpty(\u0026s.podInfo.RequiredAntiAffinityTerms[i]); err != nil {\n\t\t\treturn nil, framework.AsStatus(err)\n\t\t}\n\t}\n\ts.namespaceLabels = GetNamespaceLabelsSnapshot(pod.Namespace, pl.nsLister)\n\n\ts.existingAntiAffinityCounts = pl.getExistingAntiAffinityCounts(ctx, pod, s.namespaceLabels, nodesWithRequiredAntiAffinityPods)\n\ts.affinityCounts, s.antiAffinityCounts = pl.getIncomingAffinityAntiAffinityCounts(ctx, s.podInfo, allNodes)\n\n\tif len(s.existingAntiAffinityCounts) == 0 \u0026\u0026 len(s.podInfo.RequiredAffinityTerms) == 0 \u0026\u0026 len(s.podInfo.RequiredAntiAffinityTerms) == 0 {\n\t\treturn nil, framework.NewStatus(framework.Skip)\n\t}\n\n\tcycleState.Write(preFilterStateKey, s)\n\treturn nil, nil\n}","line":{"from":229,"to":268}} {"id":100010775,"name":"PreFilterExtensions","signature":"func (pl *InterPodAffinity) PreFilterExtensions() framework.PreFilterExtensions","file":"pkg/scheduler/framework/plugins/interpodaffinity/filtering.go","code":"// PreFilterExtensions returns prefilter extensions, pod add and remove.\nfunc (pl *InterPodAffinity) PreFilterExtensions() framework.PreFilterExtensions {\n\treturn pl\n}","line":{"from":270,"to":273}} {"id":100010776,"name":"AddPod","signature":"func (pl *InterPodAffinity) AddPod(ctx context.Context, cycleState *framework.CycleState, podToSchedule *v1.Pod, podInfoToAdd *framework.PodInfo, nodeInfo *framework.NodeInfo) *framework.Status","file":"pkg/scheduler/framework/plugins/interpodaffinity/filtering.go","code":"// AddPod from pre-computed data in cycleState.\nfunc (pl *InterPodAffinity) AddPod(ctx context.Context, cycleState *framework.CycleState, podToSchedule *v1.Pod, podInfoToAdd *framework.PodInfo, nodeInfo *framework.NodeInfo) *framework.Status {\n\tstate, err := getPreFilterState(cycleState)\n\tif err != nil {\n\t\treturn framework.AsStatus(err)\n\t}\n\tstate.updateWithPod(podInfoToAdd, nodeInfo.Node(), 1)\n\treturn nil\n}","line":{"from":275,"to":283}} {"id":100010777,"name":"RemovePod","signature":"func (pl *InterPodAffinity) RemovePod(ctx context.Context, cycleState *framework.CycleState, podToSchedule *v1.Pod, podInfoToRemove *framework.PodInfo, nodeInfo *framework.NodeInfo) *framework.Status","file":"pkg/scheduler/framework/plugins/interpodaffinity/filtering.go","code":"// RemovePod from pre-computed data in cycleState.\nfunc (pl *InterPodAffinity) RemovePod(ctx context.Context, cycleState *framework.CycleState, podToSchedule *v1.Pod, podInfoToRemove *framework.PodInfo, nodeInfo *framework.NodeInfo) *framework.Status {\n\tstate, err := getPreFilterState(cycleState)\n\tif err != nil {\n\t\treturn framework.AsStatus(err)\n\t}\n\tstate.updateWithPod(podInfoToRemove, nodeInfo.Node(), -1)\n\treturn nil\n}","line":{"from":285,"to":293}} {"id":100010778,"name":"getPreFilterState","signature":"func getPreFilterState(cycleState *framework.CycleState) (*preFilterState, error)","file":"pkg/scheduler/framework/plugins/interpodaffinity/filtering.go","code":"func getPreFilterState(cycleState *framework.CycleState) (*preFilterState, error) {\n\tc, err := cycleState.Read(preFilterStateKey)\n\tif err != nil {\n\t\t// preFilterState doesn't exist, likely PreFilter wasn't invoked.\n\t\treturn nil, fmt.Errorf(\"error reading %q from cycleState: %w\", preFilterStateKey, err)\n\t}\n\n\ts, ok := c.(*preFilterState)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"%+v convert to interpodaffinity.state error\", c)\n\t}\n\treturn s, nil\n}","line":{"from":295,"to":307}} {"id":100010779,"name":"satisfyExistingPodsAntiAffinity","signature":"func satisfyExistingPodsAntiAffinity(state *preFilterState, nodeInfo *framework.NodeInfo) bool","file":"pkg/scheduler/framework/plugins/interpodaffinity/filtering.go","code":"// Checks if scheduling the pod onto this node would break any anti-affinity\n// terms indicated by the existing pods.\nfunc satisfyExistingPodsAntiAffinity(state *preFilterState, nodeInfo *framework.NodeInfo) bool {\n\tif len(state.existingAntiAffinityCounts) \u003e 0 {\n\t\t// Iterate over topology pairs to get any of the pods being affected by\n\t\t// the scheduled pod anti-affinity terms\n\t\tfor topologyKey, topologyValue := range nodeInfo.Node().Labels {\n\t\t\ttp := topologyPair{key: topologyKey, value: topologyValue}\n\t\t\tif state.existingAntiAffinityCounts[tp] \u003e 0 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}","line":{"from":309,"to":323}} {"id":100010780,"name":"satisfyPodAntiAffinity","signature":"func satisfyPodAntiAffinity(state *preFilterState, nodeInfo *framework.NodeInfo) bool","file":"pkg/scheduler/framework/plugins/interpodaffinity/filtering.go","code":"// Checks if the node satisfies the incoming pod's anti-affinity rules.\nfunc satisfyPodAntiAffinity(state *preFilterState, nodeInfo *framework.NodeInfo) bool {\n\tif len(state.antiAffinityCounts) \u003e 0 {\n\t\tfor _, term := range state.podInfo.RequiredAntiAffinityTerms {\n\t\t\tif topologyValue, ok := nodeInfo.Node().Labels[term.TopologyKey]; ok {\n\t\t\t\ttp := topologyPair{key: term.TopologyKey, value: topologyValue}\n\t\t\t\tif state.antiAffinityCounts[tp] \u003e 0 {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}","line":{"from":325,"to":338}} {"id":100010781,"name":"satisfyPodAffinity","signature":"func satisfyPodAffinity(state *preFilterState, nodeInfo *framework.NodeInfo) bool","file":"pkg/scheduler/framework/plugins/interpodaffinity/filtering.go","code":"// Checks if the node satisfies the incoming pod's affinity rules.\nfunc satisfyPodAffinity(state *preFilterState, nodeInfo *framework.NodeInfo) bool {\n\tpodsExist := true\n\tfor _, term := range state.podInfo.RequiredAffinityTerms {\n\t\tif topologyValue, ok := nodeInfo.Node().Labels[term.TopologyKey]; ok {\n\t\t\ttp := topologyPair{key: term.TopologyKey, value: topologyValue}\n\t\t\tif state.affinityCounts[tp] \u003c= 0 {\n\t\t\t\tpodsExist = false\n\t\t\t}\n\t\t} else {\n\t\t\t// All topology labels must exist on the node.\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif !podsExist {\n\t\t// This pod may be the first pod in a series that have affinity to themselves. In order\n\t\t// to not leave such pods in pending state forever, we check that if no other pod\n\t\t// in the cluster matches the namespace and selector of this pod, the pod matches\n\t\t// its own terms, and the node has all the requested topologies, then we allow the pod\n\t\t// to pass the affinity check.\n\t\tif len(state.affinityCounts) == 0 \u0026\u0026 podMatchesAllAffinityTerms(state.podInfo.RequiredAffinityTerms, state.podInfo.Pod) {\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":340,"to":367}} {"id":100010782,"name":"Filter","signature":"func (pl *InterPodAffinity) Filter(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status","file":"pkg/scheduler/framework/plugins/interpodaffinity/filtering.go","code":"// Filter invoked at the filter extension point.\n// It checks if a pod can be scheduled on the specified node with pod affinity/anti-affinity configuration.\nfunc (pl *InterPodAffinity) Filter(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status {\n\tif nodeInfo.Node() == nil {\n\t\treturn framework.NewStatus(framework.Error, \"node not found\")\n\t}\n\n\tstate, err := getPreFilterState(cycleState)\n\tif err != nil {\n\t\treturn framework.AsStatus(err)\n\t}\n\n\tif !satisfyPodAffinity(state, nodeInfo) {\n\t\treturn framework.NewStatus(framework.UnschedulableAndUnresolvable, ErrReasonAffinityRulesNotMatch)\n\t}\n\n\tif !satisfyPodAntiAffinity(state, nodeInfo) {\n\t\treturn framework.NewStatus(framework.Unschedulable, ErrReasonAntiAffinityRulesNotMatch)\n\t}\n\n\tif !satisfyExistingPodsAntiAffinity(state, nodeInfo) {\n\t\treturn framework.NewStatus(framework.Unschedulable, ErrReasonExistingAntiAffinityRulesNotMatch)\n\t}\n\n\treturn nil\n}","line":{"from":369,"to":394}} {"id":100010783,"name":"Name","signature":"func (pl *InterPodAffinity) Name() string","file":"pkg/scheduler/framework/plugins/interpodaffinity/plugin.go","code":"// Name returns name of the plugin. It is used in logs, etc.\nfunc (pl *InterPodAffinity) Name() string {\n\treturn Name\n}","line":{"from":50,"to":53}} {"id":100010784,"name":"EventsToRegister","signature":"func (pl *InterPodAffinity) EventsToRegister() []framework.ClusterEvent","file":"pkg/scheduler/framework/plugins/interpodaffinity/plugin.go","code":"// EventsToRegister returns the possible events that may make a failed Pod\n// schedulable\nfunc (pl *InterPodAffinity) EventsToRegister() []framework.ClusterEvent {\n\treturn []framework.ClusterEvent{\n\t\t// All ActionType includes the following events:\n\t\t// - Delete. An unschedulable Pod may fail due to violating an existing Pod's anti-affinity constraints,\n\t\t// deleting an existing Pod may make it schedulable.\n\t\t// - Update. Updating on an existing Pod's labels (e.g., removal) may make\n\t\t// an unschedulable Pod schedulable.\n\t\t// - Add. An unschedulable Pod may fail due to violating pod-affinity constraints,\n\t\t// adding an assigned Pod may make it schedulable.\n\t\t{Resource: framework.Pod, ActionType: framework.All},\n\t\t{Resource: framework.Node, ActionType: framework.Add | framework.UpdateNodeLabel},\n\t}\n}","line":{"from":55,"to":69}} {"id":100010785,"name":"New","signature":"func New(plArgs runtime.Object, h framework.Handle) (framework.Plugin, error)","file":"pkg/scheduler/framework/plugins/interpodaffinity/plugin.go","code":"// New initializes a new plugin and returns it.\nfunc New(plArgs runtime.Object, h framework.Handle) (framework.Plugin, error) {\n\tif h.SnapshotSharedLister() == nil {\n\t\treturn nil, fmt.Errorf(\"SnapshotSharedlister is nil\")\n\t}\n\targs, err := getArgs(plArgs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := validation.ValidateInterPodAffinityArgs(nil, \u0026args); err != nil {\n\t\treturn nil, err\n\t}\n\tpl := \u0026InterPodAffinity{\n\t\tparallelizer: h.Parallelizer(),\n\t\targs: args,\n\t\tsharedLister: h.SnapshotSharedLister(),\n\t\tnsLister: h.SharedInformerFactory().Core().V1().Namespaces().Lister(),\n\t}\n\n\treturn pl, nil\n}","line":{"from":71,"to":91}} {"id":100010786,"name":"getArgs","signature":"func getArgs(obj runtime.Object) (config.InterPodAffinityArgs, error)","file":"pkg/scheduler/framework/plugins/interpodaffinity/plugin.go","code":"func getArgs(obj runtime.Object) (config.InterPodAffinityArgs, error) {\n\tptr, ok := obj.(*config.InterPodAffinityArgs)\n\tif !ok {\n\t\treturn config.InterPodAffinityArgs{}, fmt.Errorf(\"want args to be of type InterPodAffinityArgs, got %T\", obj)\n\t}\n\treturn *ptr, nil\n}","line":{"from":93,"to":99}} {"id":100010787,"name":"mergeAffinityTermNamespacesIfNotEmpty","signature":"func (pl *InterPodAffinity) mergeAffinityTermNamespacesIfNotEmpty(at *framework.AffinityTerm) error","file":"pkg/scheduler/framework/plugins/interpodaffinity/plugin.go","code":"// Updates Namespaces with the set of namespaces identified by NamespaceSelector.\n// If successful, NamespaceSelector is set to nil.\n// The assumption is that the term is for an incoming pod, in which case\n// namespaceSelector is either unrolled into Namespaces (and so the selector\n// is set to Nothing()) or is Empty(), which means match everything. Therefore,\n// there when matching against this term, there is no need to lookup the existing\n// pod's namespace labels to match them against term's namespaceSelector explicitly.\nfunc (pl *InterPodAffinity) mergeAffinityTermNamespacesIfNotEmpty(at *framework.AffinityTerm) error {\n\tif at.NamespaceSelector.Empty() {\n\t\treturn nil\n\t}\n\tns, err := pl.nsLister.List(at.NamespaceSelector)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, n := range ns {\n\t\tat.Namespaces.Insert(n.Name)\n\t}\n\tat.NamespaceSelector = labels.Nothing()\n\treturn nil\n}","line":{"from":101,"to":121}} {"id":100010788,"name":"GetNamespaceLabelsSnapshot","signature":"func GetNamespaceLabelsSnapshot(ns string, nsLister listersv1.NamespaceLister) (nsLabels labels.Set)","file":"pkg/scheduler/framework/plugins/interpodaffinity/plugin.go","code":"// GetNamespaceLabelsSnapshot returns a snapshot of the labels associated with\n// the namespace.\nfunc GetNamespaceLabelsSnapshot(ns string, nsLister listersv1.NamespaceLister) (nsLabels labels.Set) {\n\tpodNS, err := nsLister.Get(ns)\n\tif err == nil {\n\t\t// Create and return snapshot of the labels.\n\t\treturn labels.Merge(podNS.Labels, nil)\n\t}\n\tklog.V(3).InfoS(\"getting namespace, assuming empty set of namespace labels\", \"namespace\", ns, \"err\", err)\n\treturn\n}","line":{"from":123,"to":133}} {"id":100010789,"name":"Clone","signature":"func (s *preScoreState) Clone() framework.StateData","file":"pkg/scheduler/framework/plugins/interpodaffinity/scoring.go","code":"// Clone implements the mandatory Clone interface. We don't really copy the data since\n// there is no need for that.\nfunc (s *preScoreState) Clone() framework.StateData {\n\treturn s\n}","line":{"from":43,"to":47}} {"id":100010790,"name":"processTerm","signature":"func (m scoreMap) processTerm(term *framework.AffinityTerm, weight int32, pod *v1.Pod, nsLabels labels.Set, node *v1.Node, multiplier int32)","file":"pkg/scheduler/framework/plugins/interpodaffinity/scoring.go","code":"func (m scoreMap) processTerm(term *framework.AffinityTerm, weight int32, pod *v1.Pod, nsLabels labels.Set, node *v1.Node, multiplier int32) {\n\tif term.Matches(pod, nsLabels) {\n\t\tif tpValue, tpValueExist := node.Labels[term.TopologyKey]; tpValueExist {\n\t\t\tif m[term.TopologyKey] == nil {\n\t\t\t\tm[term.TopologyKey] = make(map[string]int64)\n\t\t\t}\n\t\t\tm[term.TopologyKey][tpValue] += int64(weight * multiplier)\n\t\t}\n\t}\n}","line":{"from":49,"to":58}} {"id":100010791,"name":"processTerms","signature":"func (m scoreMap) processTerms(terms []framework.WeightedAffinityTerm, pod *v1.Pod, nsLabels labels.Set, node *v1.Node, multiplier int32)","file":"pkg/scheduler/framework/plugins/interpodaffinity/scoring.go","code":"func (m scoreMap) processTerms(terms []framework.WeightedAffinityTerm, pod *v1.Pod, nsLabels labels.Set, node *v1.Node, multiplier int32) {\n\tfor _, term := range terms {\n\t\tm.processTerm(\u0026term.AffinityTerm, term.Weight, pod, nsLabels, node, multiplier)\n\t}\n}","line":{"from":60,"to":64}} {"id":100010792,"name":"append","signature":"func (m scoreMap) append(other scoreMap)","file":"pkg/scheduler/framework/plugins/interpodaffinity/scoring.go","code":"func (m scoreMap) append(other scoreMap) {\n\tfor topology, oScores := range other {\n\t\tscores := m[topology]\n\t\tif scores == nil {\n\t\t\tm[topology] = oScores\n\t\t\tcontinue\n\t\t}\n\t\tfor k, v := range oScores {\n\t\t\tscores[k] += v\n\t\t}\n\t}\n}","line":{"from":66,"to":77}} {"id":100010793,"name":"processExistingPod","signature":"func (pl *InterPodAffinity) processExistingPod(","file":"pkg/scheduler/framework/plugins/interpodaffinity/scoring.go","code":"func (pl *InterPodAffinity) processExistingPod(\n\tstate *preScoreState,\n\texistingPod *framework.PodInfo,\n\texistingPodNodeInfo *framework.NodeInfo,\n\tincomingPod *v1.Pod,\n\ttopoScore scoreMap,\n) {\n\texistingPodNode := existingPodNodeInfo.Node()\n\tif len(existingPodNode.Labels) == 0 {\n\t\treturn\n\t}\n\n\t// For every soft pod affinity term of \u003cpod\u003e, if \u003cexistingPod\u003e matches the term,\n\t// increment \u003cp.counts\u003e for every node in the cluster with the same \u003cterm.TopologyKey\u003e\n\t// value as that of \u003cexistingPods\u003e`s node by the term`s weight.\n\t// Note that the incoming pod's terms have the namespaceSelector merged into the namespaces, and so\n\t// here we don't lookup the existing pod's namespace labels, hence passing nil for nsLabels.\n\ttopoScore.processTerms(state.podInfo.PreferredAffinityTerms, existingPod.Pod, nil, existingPodNode, 1)\n\n\t// For every soft pod anti-affinity term of \u003cpod\u003e, if \u003cexistingPod\u003e matches the term,\n\t// decrement \u003cp.counts\u003e for every node in the cluster with the same \u003cterm.TopologyKey\u003e\n\t// value as that of \u003cexistingPod\u003e`s node by the term`s weight.\n\t// Note that the incoming pod's terms have the namespaceSelector merged into the namespaces, and so\n\t// here we don't lookup the existing pod's namespace labels, hence passing nil for nsLabels.\n\ttopoScore.processTerms(state.podInfo.PreferredAntiAffinityTerms, existingPod.Pod, nil, existingPodNode, -1)\n\n\t// For every hard pod affinity term of \u003cexistingPod\u003e, if \u003cpod\u003e matches the term,\n\t// increment \u003cp.counts\u003e for every node in the cluster with the same \u003cterm.TopologyKey\u003e\n\t// value as that of \u003cexistingPod\u003e's node by the constant \u003cargs.hardPodAffinityWeight\u003e\n\tif pl.args.HardPodAffinityWeight \u003e 0 \u0026\u0026 len(existingPodNode.Labels) != 0 {\n\t\tfor _, t := range existingPod.RequiredAffinityTerms {\n\t\t\ttopoScore.processTerm(\u0026t, pl.args.HardPodAffinityWeight, incomingPod, state.namespaceLabels, existingPodNode, 1)\n\t\t}\n\t}\n\n\t// For every soft pod affinity term of \u003cexistingPod\u003e, if \u003cpod\u003e matches the term,\n\t// increment \u003cp.counts\u003e for every node in the cluster with the same \u003cterm.TopologyKey\u003e\n\t// value as that of \u003cexistingPod\u003e's node by the term's weight.\n\ttopoScore.processTerms(existingPod.PreferredAffinityTerms, incomingPod, state.namespaceLabels, existingPodNode, 1)\n\n\t// For every soft pod anti-affinity term of \u003cexistingPod\u003e, if \u003cpod\u003e matches the term,\n\t// decrement \u003cpm.counts\u003e for every node in the cluster with the same \u003cterm.TopologyKey\u003e\n\t// value as that of \u003cexistingPod\u003e's node by the term's weight.\n\ttopoScore.processTerms(existingPod.PreferredAntiAffinityTerms, incomingPod, state.namespaceLabels, existingPodNode, -1)\n}","line":{"from":79,"to":123}} {"id":100010794,"name":"PreScore","signature":"func (pl *InterPodAffinity) PreScore(","file":"pkg/scheduler/framework/plugins/interpodaffinity/scoring.go","code":"// PreScore builds and writes cycle state used by Score and NormalizeScore.\nfunc (pl *InterPodAffinity) PreScore(\n\tpCtx context.Context,\n\tcycleState *framework.CycleState,\n\tpod *v1.Pod,\n\tnodes []*v1.Node,\n) *framework.Status {\n\tif len(nodes) == 0 {\n\t\t// No nodes to score.\n\t\treturn nil\n\t}\n\n\tif pl.sharedLister == nil {\n\t\treturn framework.NewStatus(framework.Error, \"empty shared lister in InterPodAffinity PreScore\")\n\t}\n\n\taffinity := pod.Spec.Affinity\n\thasPreferredAffinityConstraints := affinity != nil \u0026\u0026 affinity.PodAffinity != nil \u0026\u0026 len(affinity.PodAffinity.PreferredDuringSchedulingIgnoredDuringExecution) \u003e 0\n\thasPreferredAntiAffinityConstraints := affinity != nil \u0026\u0026 affinity.PodAntiAffinity != nil \u0026\u0026 len(affinity.PodAntiAffinity.PreferredDuringSchedulingIgnoredDuringExecution) \u003e 0\n\n\t// Optionally ignore calculating preferences of existing pods' affinity rules\n\t// if the incoming pod has no inter-pod affinities.\n\tif pl.args.IgnorePreferredTermsOfExistingPods \u0026\u0026 !hasPreferredAffinityConstraints \u0026\u0026 !hasPreferredAntiAffinityConstraints {\n\t\tcycleState.Write(preScoreStateKey, \u0026preScoreState{\n\t\t\ttopologyScore: make(map[string]map[string]int64),\n\t\t})\n\t\treturn nil\n\t}\n\n\t// Unless the pod being scheduled has preferred affinity terms, we only\n\t// need to process nodes hosting pods with affinity.\n\tvar allNodes []*framework.NodeInfo\n\tvar err error\n\tif hasPreferredAffinityConstraints || hasPreferredAntiAffinityConstraints {\n\t\tallNodes, err = pl.sharedLister.NodeInfos().List()\n\t\tif err != nil {\n\t\t\treturn framework.AsStatus(fmt.Errorf(\"failed to get all nodes from shared lister: %w\", err))\n\t\t}\n\t} else {\n\t\tallNodes, err = pl.sharedLister.NodeInfos().HavePodsWithAffinityList()\n\t\tif err != nil {\n\t\t\treturn framework.AsStatus(fmt.Errorf(\"failed to get pods with affinity list: %w\", err))\n\t\t}\n\t}\n\n\tstate := \u0026preScoreState{\n\t\ttopologyScore: make(map[string]map[string]int64),\n\t}\n\n\tif state.podInfo, err = framework.NewPodInfo(pod); err != nil {\n\t\t// Ideally we never reach here, because errors will be caught by PreFilter\n\t\treturn framework.AsStatus(fmt.Errorf(\"failed to parse pod: %w\", err))\n\t}\n\n\tfor i := range state.podInfo.PreferredAffinityTerms {\n\t\tif err := pl.mergeAffinityTermNamespacesIfNotEmpty(\u0026state.podInfo.PreferredAffinityTerms[i].AffinityTerm); err != nil {\n\t\t\treturn framework.AsStatus(fmt.Errorf(\"updating PreferredAffinityTerms: %w\", err))\n\t\t}\n\t}\n\tfor i := range state.podInfo.PreferredAntiAffinityTerms {\n\t\tif err := pl.mergeAffinityTermNamespacesIfNotEmpty(\u0026state.podInfo.PreferredAntiAffinityTerms[i].AffinityTerm); err != nil {\n\t\t\treturn framework.AsStatus(fmt.Errorf(\"updating PreferredAntiAffinityTerms: %w\", err))\n\t\t}\n\t}\n\tstate.namespaceLabels = GetNamespaceLabelsSnapshot(pod.Namespace, pl.nsLister)\n\n\ttopoScores := make([]scoreMap, len(allNodes))\n\tindex := int32(-1)\n\tprocessNode := func(i int) {\n\t\tnodeInfo := allNodes[i]\n\t\tif nodeInfo.Node() == nil {\n\t\t\treturn\n\t\t}\n\t\t// Unless the pod being scheduled has preferred affinity terms, we only\n\t\t// need to process pods with affinity in the node.\n\t\tpodsToProcess := nodeInfo.PodsWithAffinity\n\t\tif hasPreferredAffinityConstraints || hasPreferredAntiAffinityConstraints {\n\t\t\t// We need to process all the pods.\n\t\t\tpodsToProcess = nodeInfo.Pods\n\t\t}\n\n\t\ttopoScore := make(scoreMap)\n\t\tfor _, existingPod := range podsToProcess {\n\t\t\tpl.processExistingPod(state, existingPod, nodeInfo, pod, topoScore)\n\t\t}\n\t\tif len(topoScore) \u003e 0 {\n\t\t\ttopoScores[atomic.AddInt32(\u0026index, 1)] = topoScore\n\t\t}\n\t}\n\tpl.parallelizer.Until(pCtx, len(allNodes), processNode, pl.Name())\n\n\tfor i := 0; i \u003c= int(index); i++ {\n\t\tstate.topologyScore.append(topoScores[i])\n\t}\n\n\tcycleState.Write(preScoreStateKey, state)\n\treturn nil\n}","line":{"from":125,"to":222}} {"id":100010795,"name":"getPreScoreState","signature":"func getPreScoreState(cycleState *framework.CycleState) (*preScoreState, error)","file":"pkg/scheduler/framework/plugins/interpodaffinity/scoring.go","code":"func getPreScoreState(cycleState *framework.CycleState) (*preScoreState, error) {\n\tc, err := cycleState.Read(preScoreStateKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read %q from cycleState: %w\", preScoreStateKey, err)\n\t}\n\n\ts, ok := c.(*preScoreState)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"%+v convert to interpodaffinity.preScoreState error\", c)\n\t}\n\treturn s, nil\n}","line":{"from":224,"to":235}} {"id":100010796,"name":"Score","signature":"func (pl *InterPodAffinity) Score(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status)","file":"pkg/scheduler/framework/plugins/interpodaffinity/scoring.go","code":"// Score invoked at the Score extension point.\n// The \"score\" returned in this function is the sum of weights got from cycleState which have its topologyKey matching with the node's labels.\n// it is normalized later.\n// Note: the returned \"score\" is positive for pod-affinity, and negative for pod-antiaffinity.\nfunc (pl *InterPodAffinity) Score(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status) {\n\tnodeInfo, err := pl.sharedLister.NodeInfos().Get(nodeName)\n\tif err != nil {\n\t\treturn 0, framework.AsStatus(fmt.Errorf(\"failed to get node %q from Snapshot: %w\", nodeName, err))\n\t}\n\tnode := nodeInfo.Node()\n\n\ts, err := getPreScoreState(cycleState)\n\tif err != nil {\n\t\treturn 0, framework.AsStatus(err)\n\t}\n\tvar score int64\n\tfor tpKey, tpValues := range s.topologyScore {\n\t\tif v, exist := node.Labels[tpKey]; exist {\n\t\t\tscore += tpValues[v]\n\t\t}\n\t}\n\n\treturn score, nil\n}","line":{"from":237,"to":260}} {"id":100010797,"name":"NormalizeScore","signature":"func (pl *InterPodAffinity) NormalizeScore(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, scores framework.NodeScoreList) *framework.Status","file":"pkg/scheduler/framework/plugins/interpodaffinity/scoring.go","code":"// NormalizeScore normalizes the score for each filteredNode.\nfunc (pl *InterPodAffinity) NormalizeScore(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, scores framework.NodeScoreList) *framework.Status {\n\ts, err := getPreScoreState(cycleState)\n\tif err != nil {\n\t\treturn framework.AsStatus(err)\n\t}\n\tif len(s.topologyScore) == 0 {\n\t\treturn nil\n\t}\n\n\tvar minCount int64 = math.MaxInt64\n\tvar maxCount int64 = math.MinInt64\n\tfor i := range scores {\n\t\tscore := scores[i].Score\n\t\tif score \u003e maxCount {\n\t\t\tmaxCount = score\n\t\t}\n\t\tif score \u003c minCount {\n\t\t\tminCount = score\n\t\t}\n\t}\n\n\tmaxMinDiff := maxCount - minCount\n\tfor i := range scores {\n\t\tfScore := float64(0)\n\t\tif maxMinDiff \u003e 0 {\n\t\t\tfScore = float64(framework.MaxNodeScore) * (float64(scores[i].Score-minCount) / float64(maxMinDiff))\n\t\t}\n\n\t\tscores[i].Score = int64(fScore)\n\t}\n\n\treturn nil\n}","line":{"from":262,"to":295}} {"id":100010798,"name":"ScoreExtensions","signature":"func (pl *InterPodAffinity) ScoreExtensions() framework.ScoreExtensions","file":"pkg/scheduler/framework/plugins/interpodaffinity/scoring.go","code":"// ScoreExtensions of the Score plugin.\nfunc (pl *InterPodAffinity) ScoreExtensions() framework.ScoreExtensions {\n\treturn pl\n}","line":{"from":297,"to":300}} {"id":100010799,"name":"Name","signature":"func (pl *NodeAffinity) Name() string","file":"pkg/scheduler/framework/plugins/nodeaffinity/node_affinity.go","code":"// Name returns name of the plugin. It is used in logs, etc.\nfunc (pl *NodeAffinity) Name() string {\n\treturn Name\n}","line":{"from":68,"to":71}} {"id":100010800,"name":"Clone","signature":"func (s *preFilterState) Clone() framework.StateData","file":"pkg/scheduler/framework/plugins/nodeaffinity/node_affinity.go","code":"// Clone just returns the same state because it is not affected by pod additions or deletions.\nfunc (s *preFilterState) Clone() framework.StateData {\n\treturn s\n}","line":{"from":77,"to":80}} {"id":100010801,"name":"EventsToRegister","signature":"func (pl *NodeAffinity) EventsToRegister() []framework.ClusterEvent","file":"pkg/scheduler/framework/plugins/nodeaffinity/node_affinity.go","code":"// EventsToRegister returns the possible events that may make a Pod\n// failed by this plugin schedulable.\nfunc (pl *NodeAffinity) EventsToRegister() []framework.ClusterEvent {\n\treturn []framework.ClusterEvent{\n\t\t{Resource: framework.Node, ActionType: framework.Add | framework.Update},\n\t}\n}","line":{"from":82,"to":88}} {"id":100010802,"name":"PreFilter","signature":"func (pl *NodeAffinity) PreFilter(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod) (*framework.PreFilterResult, *framework.Status)","file":"pkg/scheduler/framework/plugins/nodeaffinity/node_affinity.go","code":"// PreFilter builds and writes cycle state used by Filter.\nfunc (pl *NodeAffinity) PreFilter(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod) (*framework.PreFilterResult, *framework.Status) {\n\taffinity := pod.Spec.Affinity\n\tnoNodeAffinity := (affinity == nil ||\n\t\taffinity.NodeAffinity == nil ||\n\t\taffinity.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution == nil)\n\tif noNodeAffinity \u0026\u0026 pl.addedNodeSelector == nil \u0026\u0026 pod.Spec.NodeSelector == nil {\n\t\t// NodeAffinity Filter has nothing to do with the Pod.\n\t\treturn nil, framework.NewStatus(framework.Skip)\n\t}\n\n\tstate := \u0026preFilterState{requiredNodeSelectorAndAffinity: nodeaffinity.GetRequiredNodeAffinity(pod)}\n\tcycleState.Write(preFilterStateKey, state)\n\n\tif noNodeAffinity || len(affinity.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution.NodeSelectorTerms) == 0 {\n\t\treturn nil, nil\n\t}\n\n\t// Check if there is affinity to a specific node and return it.\n\tterms := affinity.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution.NodeSelectorTerms\n\tvar nodeNames sets.String\n\tfor _, t := range terms {\n\t\tvar termNodeNames sets.String\n\t\tfor _, r := range t.MatchFields {\n\t\t\tif r.Key == metav1.ObjectNameField \u0026\u0026 r.Operator == v1.NodeSelectorOpIn {\n\t\t\t\t// The requirements represent ANDed constraints, and so we need to\n\t\t\t\t// find the intersection of nodes.\n\t\t\t\ts := sets.NewString(r.Values...)\n\t\t\t\tif termNodeNames == nil {\n\t\t\t\t\ttermNodeNames = s\n\t\t\t\t} else {\n\t\t\t\t\ttermNodeNames = termNodeNames.Intersection(s)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif termNodeNames == nil {\n\t\t\t// If this term has no node.Name field affinity,\n\t\t\t// then all nodes are eligible because the terms are ORed.\n\t\t\treturn nil, nil\n\t\t}\n\t\tnodeNames = nodeNames.Union(termNodeNames)\n\t}\n\t// If nodeNames is not nil, but length is 0, it means each term have conflicting affinity to node.Name;\n\t// therefore, pod will not match any node.\n\tif nodeNames != nil \u0026\u0026 len(nodeNames) == 0 {\n\t\treturn nil, framework.NewStatus(framework.UnschedulableAndUnresolvable, errReasonConflict)\n\t} else if len(nodeNames) \u003e 0 {\n\t\treturn \u0026framework.PreFilterResult{NodeNames: nodeNames}, nil\n\t}\n\treturn nil, nil\n\n}","line":{"from":90,"to":141}} {"id":100010803,"name":"PreFilterExtensions","signature":"func (pl *NodeAffinity) PreFilterExtensions() framework.PreFilterExtensions","file":"pkg/scheduler/framework/plugins/nodeaffinity/node_affinity.go","code":"// PreFilterExtensions not necessary for this plugin as state doesn't depend on pod additions or deletions.\nfunc (pl *NodeAffinity) PreFilterExtensions() framework.PreFilterExtensions {\n\treturn nil\n}","line":{"from":143,"to":146}} {"id":100010804,"name":"Filter","signature":"func (pl *NodeAffinity) Filter(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status","file":"pkg/scheduler/framework/plugins/nodeaffinity/node_affinity.go","code":"// Filter checks if the Node matches the Pod .spec.affinity.nodeAffinity and\n// the plugin's added affinity.\nfunc (pl *NodeAffinity) Filter(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status {\n\tnode := nodeInfo.Node()\n\tif node == nil {\n\t\treturn framework.NewStatus(framework.Error, \"node not found\")\n\t}\n\tif pl.addedNodeSelector != nil \u0026\u0026 !pl.addedNodeSelector.Match(node) {\n\t\treturn framework.NewStatus(framework.UnschedulableAndUnresolvable, errReasonEnforced)\n\t}\n\n\ts, err := getPreFilterState(state)\n\tif err != nil {\n\t\t// Fallback to calculate requiredNodeSelector and requiredNodeAffinity\n\t\t// here when PreFilter is disabled.\n\t\ts = \u0026preFilterState{requiredNodeSelectorAndAffinity: nodeaffinity.GetRequiredNodeAffinity(pod)}\n\t}\n\n\t// Ignore parsing errors for backwards compatibility.\n\tmatch, _ := s.requiredNodeSelectorAndAffinity.Match(node)\n\tif !match {\n\t\treturn framework.NewStatus(framework.UnschedulableAndUnresolvable, ErrReasonPod)\n\t}\n\n\treturn nil\n}","line":{"from":148,"to":173}} {"id":100010805,"name":"Clone","signature":"func (s *preScoreState) Clone() framework.StateData","file":"pkg/scheduler/framework/plugins/nodeaffinity/node_affinity.go","code":"// Clone implements the mandatory Clone interface. We don't really copy the data since\n// there is no need for that.\nfunc (s *preScoreState) Clone() framework.StateData {\n\treturn s\n}","line":{"from":180,"to":184}} {"id":100010806,"name":"PreScore","signature":"func (pl *NodeAffinity) PreScore(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodes []*v1.Node) *framework.Status","file":"pkg/scheduler/framework/plugins/nodeaffinity/node_affinity.go","code":"// PreScore builds and writes cycle state used by Score and NormalizeScore.\nfunc (pl *NodeAffinity) PreScore(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodes []*v1.Node) *framework.Status {\n\tif len(nodes) == 0 {\n\t\treturn nil\n\t}\n\tpreferredNodeAffinity, err := getPodPreferredNodeAffinity(pod)\n\tif err != nil {\n\t\treturn framework.AsStatus(err)\n\t}\n\tstate := \u0026preScoreState{\n\t\tpreferredNodeAffinity: preferredNodeAffinity,\n\t}\n\tcycleState.Write(preScoreStateKey, state)\n\treturn nil\n}","line":{"from":186,"to":200}} {"id":100010807,"name":"Score","signature":"func (pl *NodeAffinity) Score(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status)","file":"pkg/scheduler/framework/plugins/nodeaffinity/node_affinity.go","code":"// Score returns the sum of the weights of the terms that match the Node.\n// Terms came from the Pod .spec.affinity.nodeAffinity and from the plugin's\n// default affinity.\nfunc (pl *NodeAffinity) Score(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status) {\n\tnodeInfo, err := pl.handle.SnapshotSharedLister().NodeInfos().Get(nodeName)\n\tif err != nil {\n\t\treturn 0, framework.AsStatus(fmt.Errorf(\"getting node %q from Snapshot: %w\", nodeName, err))\n\t}\n\n\tnode := nodeInfo.Node()\n\n\tvar count int64\n\tif pl.addedPrefSchedTerms != nil {\n\t\tcount += pl.addedPrefSchedTerms.Score(node)\n\t}\n\n\ts, err := getPreScoreState(state)\n\tif err != nil {\n\t\t// Fallback to calculate preferredNodeAffinity here when PreScore is disabled.\n\t\tpreferredNodeAffinity, err := getPodPreferredNodeAffinity(pod)\n\t\tif err != nil {\n\t\t\treturn 0, framework.AsStatus(err)\n\t\t}\n\t\ts = \u0026preScoreState{\n\t\t\tpreferredNodeAffinity: preferredNodeAffinity,\n\t\t}\n\t}\n\n\tif s.preferredNodeAffinity != nil {\n\t\tcount += s.preferredNodeAffinity.Score(node)\n\t}\n\n\treturn count, nil\n}","line":{"from":202,"to":235}} {"id":100010808,"name":"NormalizeScore","signature":"func (pl *NodeAffinity) NormalizeScore(ctx context.Context, state *framework.CycleState, pod *v1.Pod, scores framework.NodeScoreList) *framework.Status","file":"pkg/scheduler/framework/plugins/nodeaffinity/node_affinity.go","code":"// NormalizeScore invoked after scoring all nodes.\nfunc (pl *NodeAffinity) NormalizeScore(ctx context.Context, state *framework.CycleState, pod *v1.Pod, scores framework.NodeScoreList) *framework.Status {\n\treturn helper.DefaultNormalizeScore(framework.MaxNodeScore, false, scores)\n}","line":{"from":237,"to":240}} {"id":100010809,"name":"ScoreExtensions","signature":"func (pl *NodeAffinity) ScoreExtensions() framework.ScoreExtensions","file":"pkg/scheduler/framework/plugins/nodeaffinity/node_affinity.go","code":"// ScoreExtensions of the Score plugin.\nfunc (pl *NodeAffinity) ScoreExtensions() framework.ScoreExtensions {\n\treturn pl\n}","line":{"from":242,"to":245}} {"id":100010810,"name":"New","signature":"func New(plArgs runtime.Object, h framework.Handle) (framework.Plugin, error)","file":"pkg/scheduler/framework/plugins/nodeaffinity/node_affinity.go","code":"// New initializes a new plugin and returns it.\nfunc New(plArgs runtime.Object, h framework.Handle) (framework.Plugin, error) {\n\targs, err := getArgs(plArgs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpl := \u0026NodeAffinity{\n\t\thandle: h,\n\t}\n\tif args.AddedAffinity != nil {\n\t\tif ns := args.AddedAffinity.RequiredDuringSchedulingIgnoredDuringExecution; ns != nil {\n\t\t\tpl.addedNodeSelector, err = nodeaffinity.NewNodeSelector(ns)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"parsing addedAffinity.requiredDuringSchedulingIgnoredDuringExecution: %w\", err)\n\t\t\t}\n\t\t}\n\t\t// TODO: parse requiredDuringSchedulingRequiredDuringExecution when it gets added to the API.\n\t\tif terms := args.AddedAffinity.PreferredDuringSchedulingIgnoredDuringExecution; len(terms) != 0 {\n\t\t\tpl.addedPrefSchedTerms, err = nodeaffinity.NewPreferredSchedulingTerms(terms)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"parsing addedAffinity.preferredDuringSchedulingIgnoredDuringExecution: %w\", err)\n\t\t\t}\n\t\t}\n\t}\n\treturn pl, nil\n}","line":{"from":247,"to":272}} {"id":100010811,"name":"getArgs","signature":"func getArgs(obj runtime.Object) (config.NodeAffinityArgs, error)","file":"pkg/scheduler/framework/plugins/nodeaffinity/node_affinity.go","code":"func getArgs(obj runtime.Object) (config.NodeAffinityArgs, error) {\n\tptr, ok := obj.(*config.NodeAffinityArgs)\n\tif !ok {\n\t\treturn config.NodeAffinityArgs{}, fmt.Errorf(\"args are not of type NodeAffinityArgs, got %T\", obj)\n\t}\n\treturn *ptr, validation.ValidateNodeAffinityArgs(nil, ptr)\n}","line":{"from":274,"to":280}} {"id":100010812,"name":"getPodPreferredNodeAffinity","signature":"func getPodPreferredNodeAffinity(pod *v1.Pod) (*nodeaffinity.PreferredSchedulingTerms, error)","file":"pkg/scheduler/framework/plugins/nodeaffinity/node_affinity.go","code":"func getPodPreferredNodeAffinity(pod *v1.Pod) (*nodeaffinity.PreferredSchedulingTerms, error) {\n\taffinity := pod.Spec.Affinity\n\tif affinity != nil \u0026\u0026 affinity.NodeAffinity != nil \u0026\u0026 affinity.NodeAffinity.PreferredDuringSchedulingIgnoredDuringExecution != nil {\n\t\treturn nodeaffinity.NewPreferredSchedulingTerms(affinity.NodeAffinity.PreferredDuringSchedulingIgnoredDuringExecution)\n\t}\n\treturn nil, nil\n}","line":{"from":282,"to":288}} {"id":100010813,"name":"getPreScoreState","signature":"func getPreScoreState(cycleState *framework.CycleState) (*preScoreState, error)","file":"pkg/scheduler/framework/plugins/nodeaffinity/node_affinity.go","code":"func getPreScoreState(cycleState *framework.CycleState) (*preScoreState, error) {\n\tc, err := cycleState.Read(preScoreStateKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"reading %q from cycleState: %w\", preScoreStateKey, err)\n\t}\n\n\ts, ok := c.(*preScoreState)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid PreScore state, got type %T\", c)\n\t}\n\treturn s, nil\n}","line":{"from":290,"to":301}} {"id":100010814,"name":"getPreFilterState","signature":"func getPreFilterState(cycleState *framework.CycleState) (*preFilterState, error)","file":"pkg/scheduler/framework/plugins/nodeaffinity/node_affinity.go","code":"func getPreFilterState(cycleState *framework.CycleState) (*preFilterState, error) {\n\tc, err := cycleState.Read(preFilterStateKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"reading %q from cycleState: %v\", preFilterStateKey, err)\n\t}\n\n\ts, ok := c.(*preFilterState)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid PreFilter state, got type %T\", c)\n\t}\n\treturn s, nil\n}","line":{"from":303,"to":314}} {"id":100010815,"name":"EventsToRegister","signature":"func (pl *NodeName) EventsToRegister() []framework.ClusterEvent","file":"pkg/scheduler/framework/plugins/nodename/node_name.go","code":"// EventsToRegister returns the possible events that may make a Pod\n// failed by this plugin schedulable.\nfunc (pl *NodeName) EventsToRegister() []framework.ClusterEvent {\n\treturn []framework.ClusterEvent{\n\t\t{Resource: framework.Node, ActionType: framework.Add | framework.Update},\n\t}\n}","line":{"from":42,"to":48}} {"id":100010816,"name":"Name","signature":"func (pl *NodeName) Name() string","file":"pkg/scheduler/framework/plugins/nodename/node_name.go","code":"// Name returns name of the plugin. It is used in logs, etc.\nfunc (pl *NodeName) Name() string {\n\treturn Name\n}","line":{"from":50,"to":53}} {"id":100010817,"name":"Filter","signature":"func (pl *NodeName) Filter(ctx context.Context, _ *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status","file":"pkg/scheduler/framework/plugins/nodename/node_name.go","code":"// Filter invoked at the filter extension point.\nfunc (pl *NodeName) Filter(ctx context.Context, _ *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status {\n\tif nodeInfo.Node() == nil {\n\t\treturn framework.NewStatus(framework.Error, \"node not found\")\n\t}\n\tif !Fits(pod, nodeInfo) {\n\t\treturn framework.NewStatus(framework.UnschedulableAndUnresolvable, ErrReason)\n\t}\n\treturn nil\n}","line":{"from":55,"to":64}} {"id":100010818,"name":"Fits","signature":"func Fits(pod *v1.Pod, nodeInfo *framework.NodeInfo) bool","file":"pkg/scheduler/framework/plugins/nodename/node_name.go","code":"// Fits actually checks if the pod fits the node.\nfunc Fits(pod *v1.Pod, nodeInfo *framework.NodeInfo) bool {\n\treturn len(pod.Spec.NodeName) == 0 || pod.Spec.NodeName == nodeInfo.Node().Name\n}","line":{"from":66,"to":69}} {"id":100010819,"name":"New","signature":"func New(_ runtime.Object, _ framework.Handle) (framework.Plugin, error)","file":"pkg/scheduler/framework/plugins/nodename/node_name.go","code":"// New initializes a new plugin and returns it.\nfunc New(_ runtime.Object, _ framework.Handle) (framework.Plugin, error) {\n\treturn \u0026NodeName{}, nil\n}","line":{"from":71,"to":74}} {"id":100010820,"name":"Clone","signature":"func (s preFilterState) Clone() framework.StateData","file":"pkg/scheduler/framework/plugins/nodeports/node_ports.go","code":"// Clone the prefilter state.\nfunc (s preFilterState) Clone() framework.StateData {\n\t// The state is not impacted by adding/removing existing pods, hence we don't need to make a deep copy.\n\treturn s\n}","line":{"from":50,"to":54}} {"id":100010821,"name":"Name","signature":"func (pl *NodePorts) Name() string","file":"pkg/scheduler/framework/plugins/nodeports/node_ports.go","code":"// Name returns name of the plugin. It is used in logs, etc.\nfunc (pl *NodePorts) Name() string {\n\treturn Name\n}","line":{"from":56,"to":59}} {"id":100010822,"name":"getContainerPorts","signature":"func getContainerPorts(pods ...*v1.Pod) []*v1.ContainerPort","file":"pkg/scheduler/framework/plugins/nodeports/node_ports.go","code":"// getContainerPorts returns the used host ports of Pods: if 'port' was used, a 'port:true' pair\n// will be in the result; but it does not resolve port conflict.\nfunc getContainerPorts(pods ...*v1.Pod) []*v1.ContainerPort {\n\tports := []*v1.ContainerPort{}\n\tfor _, pod := range pods {\n\t\tfor j := range pod.Spec.Containers {\n\t\t\tcontainer := \u0026pod.Spec.Containers[j]\n\t\t\tfor k := range container.Ports {\n\t\t\t\tports = append(ports, \u0026container.Ports[k])\n\t\t\t}\n\t\t}\n\t}\n\treturn ports\n}","line":{"from":61,"to":74}} {"id":100010823,"name":"PreFilter","signature":"func (pl *NodePorts) PreFilter(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod) (*framework.PreFilterResult, *framework.Status)","file":"pkg/scheduler/framework/plugins/nodeports/node_ports.go","code":"// PreFilter invoked at the prefilter extension point.\nfunc (pl *NodePorts) PreFilter(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod) (*framework.PreFilterResult, *framework.Status) {\n\ts := getContainerPorts(pod)\n\tcycleState.Write(preFilterStateKey, preFilterState(s))\n\treturn nil, nil\n}","line":{"from":76,"to":81}} {"id":100010824,"name":"PreFilterExtensions","signature":"func (pl *NodePorts) PreFilterExtensions() framework.PreFilterExtensions","file":"pkg/scheduler/framework/plugins/nodeports/node_ports.go","code":"// PreFilterExtensions do not exist for this plugin.\nfunc (pl *NodePorts) PreFilterExtensions() framework.PreFilterExtensions {\n\treturn nil\n}","line":{"from":83,"to":86}} {"id":100010825,"name":"getPreFilterState","signature":"func getPreFilterState(cycleState *framework.CycleState) (preFilterState, error)","file":"pkg/scheduler/framework/plugins/nodeports/node_ports.go","code":"func getPreFilterState(cycleState *framework.CycleState) (preFilterState, error) {\n\tc, err := cycleState.Read(preFilterStateKey)\n\tif err != nil {\n\t\t// preFilterState doesn't exist, likely PreFilter wasn't invoked.\n\t\treturn nil, fmt.Errorf(\"reading %q from cycleState: %w\", preFilterStateKey, err)\n\t}\n\n\ts, ok := c.(preFilterState)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"%+v convert to nodeports.preFilterState error\", c)\n\t}\n\treturn s, nil\n}","line":{"from":88,"to":100}} {"id":100010826,"name":"EventsToRegister","signature":"func (pl *NodePorts) EventsToRegister() []framework.ClusterEvent","file":"pkg/scheduler/framework/plugins/nodeports/node_ports.go","code":"// EventsToRegister returns the possible events that may make a Pod\n// failed by this plugin schedulable.\nfunc (pl *NodePorts) EventsToRegister() []framework.ClusterEvent {\n\treturn []framework.ClusterEvent{\n\t\t// Due to immutable fields `spec.containers[*].ports`, pod update events are ignored.\n\t\t{Resource: framework.Pod, ActionType: framework.Delete},\n\t\t{Resource: framework.Node, ActionType: framework.Add | framework.Update},\n\t}\n}","line":{"from":102,"to":110}} {"id":100010827,"name":"Filter","signature":"func (pl *NodePorts) Filter(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status","file":"pkg/scheduler/framework/plugins/nodeports/node_ports.go","code":"// Filter invoked at the filter extension point.\nfunc (pl *NodePorts) Filter(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status {\n\twantPorts, err := getPreFilterState(cycleState)\n\tif err != nil {\n\t\treturn framework.AsStatus(err)\n\t}\n\n\tfits := fitsPorts(wantPorts, nodeInfo)\n\tif !fits {\n\t\treturn framework.NewStatus(framework.Unschedulable, ErrReason)\n\t}\n\n\treturn nil\n}","line":{"from":112,"to":125}} {"id":100010828,"name":"Fits","signature":"func Fits(pod *v1.Pod, nodeInfo *framework.NodeInfo) bool","file":"pkg/scheduler/framework/plugins/nodeports/node_ports.go","code":"// Fits checks if the pod fits the node.\nfunc Fits(pod *v1.Pod, nodeInfo *framework.NodeInfo) bool {\n\treturn fitsPorts(getContainerPorts(pod), nodeInfo)\n}","line":{"from":127,"to":130}} {"id":100010829,"name":"fitsPorts","signature":"func fitsPorts(wantPorts []*v1.ContainerPort, nodeInfo *framework.NodeInfo) bool","file":"pkg/scheduler/framework/plugins/nodeports/node_ports.go","code":"func fitsPorts(wantPorts []*v1.ContainerPort, nodeInfo *framework.NodeInfo) bool {\n\t// try to see whether existingPorts and wantPorts will conflict or not\n\texistingPorts := nodeInfo.UsedPorts\n\tfor _, cp := range wantPorts {\n\t\tif existingPorts.CheckConflict(cp.HostIP, string(cp.Protocol), cp.HostPort) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":132,"to":141}} {"id":100010830,"name":"New","signature":"func New(_ runtime.Object, _ framework.Handle) (framework.Plugin, error)","file":"pkg/scheduler/framework/plugins/nodeports/node_ports.go","code":"// New initializes a new plugin and returns it.\nfunc New(_ runtime.Object, _ framework.Handle) (framework.Plugin, error) {\n\treturn \u0026NodePorts{}, nil\n}","line":{"from":143,"to":146}} {"id":100010831,"name":"Clone","signature":"func (s *balancedAllocationPreScoreState) Clone() framework.StateData","file":"pkg/scheduler/framework/plugins/noderesources/balanced_allocation.go","code":"// Clone implements the mandatory Clone interface. We don't really copy the data since\n// there is no need for that.\nfunc (s *balancedAllocationPreScoreState) Clone() framework.StateData {\n\treturn s\n}","line":{"from":58,"to":62}} {"id":100010832,"name":"PreScore","signature":"func (ba *BalancedAllocation) PreScore(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodes []*v1.Node) *framework.Status","file":"pkg/scheduler/framework/plugins/noderesources/balanced_allocation.go","code":"// PreScore calculates incoming pod's resource requests and writes them to the cycle state used.\nfunc (ba *BalancedAllocation) PreScore(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodes []*v1.Node) *framework.Status {\n\tstate := \u0026balancedAllocationPreScoreState{\n\t\tpodRequests: ba.calculatePodResourceRequestList(pod, ba.resources),\n\t}\n\tcycleState.Write(balancedAllocationPreScoreStateKey, state)\n\treturn nil\n}","line":{"from":64,"to":71}} {"id":100010833,"name":"getBalancedAllocationPreScoreState","signature":"func getBalancedAllocationPreScoreState(cycleState *framework.CycleState) (*balancedAllocationPreScoreState, error)","file":"pkg/scheduler/framework/plugins/noderesources/balanced_allocation.go","code":"func getBalancedAllocationPreScoreState(cycleState *framework.CycleState) (*balancedAllocationPreScoreState, error) {\n\tc, err := cycleState.Read(balancedAllocationPreScoreStateKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"reading %q from cycleState: %w\", balancedAllocationPreScoreStateKey, err)\n\t}\n\n\ts, ok := c.(*balancedAllocationPreScoreState)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid PreScore state, got type %T\", c)\n\t}\n\treturn s, nil\n}","line":{"from":73,"to":84}} {"id":100010834,"name":"Name","signature":"func (ba *BalancedAllocation) Name() string","file":"pkg/scheduler/framework/plugins/noderesources/balanced_allocation.go","code":"// Name returns name of the plugin. It is used in logs, etc.\nfunc (ba *BalancedAllocation) Name() string {\n\treturn BalancedAllocationName\n}","line":{"from":86,"to":89}} {"id":100010835,"name":"Score","signature":"func (ba *BalancedAllocation) Score(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status)","file":"pkg/scheduler/framework/plugins/noderesources/balanced_allocation.go","code":"// Score invoked at the score extension point.\nfunc (ba *BalancedAllocation) Score(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status) {\n\tnodeInfo, err := ba.handle.SnapshotSharedLister().NodeInfos().Get(nodeName)\n\tif err != nil {\n\t\treturn 0, framework.AsStatus(fmt.Errorf(\"getting node %q from Snapshot: %w\", nodeName, err))\n\t}\n\n\ts, err := getBalancedAllocationPreScoreState(state)\n\tif err != nil {\n\t\ts = \u0026balancedAllocationPreScoreState{podRequests: ba.calculatePodResourceRequestList(pod, ba.resources)}\n\t}\n\n\t// ba.score favors nodes with balanced resource usage rate.\n\t// It calculates the standard deviation for those resources and prioritizes the node based on how close the usage of those resources is to each other.\n\t// Detail: score = (1 - std) * MaxNodeScore, where std is calculated by the root square of Σ((fraction(i)-mean)^2)/len(resources)\n\t// The algorithm is partly inspired by:\n\t// \"Wei Huang et al. An Energy Efficient Virtual Machine Placement Algorithm with Balanced Resource Utilization\"\n\treturn ba.score(pod, nodeInfo, s.podRequests)\n}","line":{"from":91,"to":109}} {"id":100010836,"name":"ScoreExtensions","signature":"func (ba *BalancedAllocation) ScoreExtensions() framework.ScoreExtensions","file":"pkg/scheduler/framework/plugins/noderesources/balanced_allocation.go","code":"// ScoreExtensions of the Score plugin.\nfunc (ba *BalancedAllocation) ScoreExtensions() framework.ScoreExtensions {\n\treturn nil\n}","line":{"from":111,"to":114}} {"id":100010837,"name":"NewBalancedAllocation","signature":"func NewBalancedAllocation(baArgs runtime.Object, h framework.Handle, fts feature.Features) (framework.Plugin, error)","file":"pkg/scheduler/framework/plugins/noderesources/balanced_allocation.go","code":"// NewBalancedAllocation initializes a new plugin and returns it.\nfunc NewBalancedAllocation(baArgs runtime.Object, h framework.Handle, fts feature.Features) (framework.Plugin, error) {\n\targs, ok := baArgs.(*config.NodeResourcesBalancedAllocationArgs)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"want args to be of type NodeResourcesBalancedAllocationArgs, got %T\", baArgs)\n\t}\n\n\tif err := validation.ValidateNodeResourcesBalancedAllocationArgs(nil, args); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026BalancedAllocation{\n\t\thandle: h,\n\t\tresourceAllocationScorer: resourceAllocationScorer{\n\t\t\tName: BalancedAllocationName,\n\t\t\tscorer: balancedResourceScorer,\n\t\t\tuseRequested: true,\n\t\t\tresources: args.Resources,\n\t\t},\n\t}, nil\n}","line":{"from":116,"to":136}} {"id":100010838,"name":"balancedResourceScorer","signature":"func balancedResourceScorer(requested, allocable []int64) int64","file":"pkg/scheduler/framework/plugins/noderesources/balanced_allocation.go","code":"func balancedResourceScorer(requested, allocable []int64) int64 {\n\tvar resourceToFractions []float64\n\tvar totalFraction float64\n\tfor i := range requested {\n\t\tif allocable[i] == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tfraction := float64(requested[i]) / float64(allocable[i])\n\t\tif fraction \u003e 1 {\n\t\t\tfraction = 1\n\t\t}\n\t\ttotalFraction += fraction\n\t\tresourceToFractions = append(resourceToFractions, fraction)\n\t}\n\n\tstd := 0.0\n\n\t// For most cases, resources are limited to cpu and memory, the std could be simplified to std := (fraction1-fraction2)/2\n\t// len(fractions) \u003e 2: calculate std based on the well-known formula - root square of Σ((fraction(i)-mean)^2)/len(fractions)\n\t// Otherwise, set the std to zero is enough.\n\tif len(resourceToFractions) == 2 {\n\t\tstd = math.Abs((resourceToFractions[0] - resourceToFractions[1]) / 2)\n\n\t} else if len(resourceToFractions) \u003e 2 {\n\t\tmean := totalFraction / float64(len(resourceToFractions))\n\t\tvar sum float64\n\t\tfor _, fraction := range resourceToFractions {\n\t\t\tsum = sum + (fraction-mean)*(fraction-mean)\n\t\t}\n\t\tstd = math.Sqrt(sum / float64(len(resourceToFractions)))\n\t}\n\n\t// STD (standard deviation) is always a positive value. 1-deviation lets the score to be higher for node which has least deviation and\n\t// multiplying it with `MaxNodeScore` provides the scaling factor needed.\n\treturn int64((1 - std) * float64(framework.MaxNodeScore))\n}","line":{"from":138,"to":173}} {"id":100010839,"name":"ScoreExtensions","signature":"func (f *Fit) ScoreExtensions() framework.ScoreExtensions","file":"pkg/scheduler/framework/plugins/noderesources/fit.go","code":"// ScoreExtensions of the Score plugin.\nfunc (f *Fit) ScoreExtensions() framework.ScoreExtensions {\n\treturn nil\n}","line":{"from":92,"to":95}} {"id":100010840,"name":"Clone","signature":"func (s *preFilterState) Clone() framework.StateData","file":"pkg/scheduler/framework/plugins/noderesources/fit.go","code":"// Clone the prefilter state.\nfunc (s *preFilterState) Clone() framework.StateData {\n\treturn s\n}","line":{"from":102,"to":105}} {"id":100010841,"name":"Clone","signature":"func (s *preScoreState) Clone() framework.StateData","file":"pkg/scheduler/framework/plugins/noderesources/fit.go","code":"// Clone implements the mandatory Clone interface. We don't really copy the data since\n// there is no need for that.\nfunc (s *preScoreState) Clone() framework.StateData {\n\treturn s\n}","line":{"from":114,"to":118}} {"id":100010842,"name":"PreScore","signature":"func (f *Fit) PreScore(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodes []*v1.Node) *framework.Status","file":"pkg/scheduler/framework/plugins/noderesources/fit.go","code":"// PreScore calculates incoming pod's resource requests and writes them to the cycle state used.\nfunc (f *Fit) PreScore(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodes []*v1.Node) *framework.Status {\n\tstate := \u0026preScoreState{\n\t\tpodRequests: f.calculatePodResourceRequestList(pod, f.resources),\n\t}\n\tcycleState.Write(preScoreStateKey, state)\n\treturn nil\n}","line":{"from":120,"to":127}} {"id":100010843,"name":"getPreScoreState","signature":"func getPreScoreState(cycleState *framework.CycleState) (*preScoreState, error)","file":"pkg/scheduler/framework/plugins/noderesources/fit.go","code":"func getPreScoreState(cycleState *framework.CycleState) (*preScoreState, error) {\n\tc, err := cycleState.Read(preScoreStateKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"reading %q from cycleState: %w\", preScoreStateKey, err)\n\t}\n\n\ts, ok := c.(*preScoreState)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid PreScore state, got type %T\", c)\n\t}\n\treturn s, nil\n}","line":{"from":129,"to":140}} {"id":100010844,"name":"Name","signature":"func (f *Fit) Name() string","file":"pkg/scheduler/framework/plugins/noderesources/fit.go","code":"// Name returns name of the plugin. It is used in logs, etc.\nfunc (f *Fit) Name() string {\n\treturn Name\n}","line":{"from":142,"to":145}} {"id":100010845,"name":"NewFit","signature":"func NewFit(plArgs runtime.Object, h framework.Handle, fts feature.Features) (framework.Plugin, error)","file":"pkg/scheduler/framework/plugins/noderesources/fit.go","code":"// NewFit initializes a new plugin and returns it.\nfunc NewFit(plArgs runtime.Object, h framework.Handle, fts feature.Features) (framework.Plugin, error) {\n\targs, ok := plArgs.(*config.NodeResourcesFitArgs)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"want args to be of type NodeResourcesFitArgs, got %T\", plArgs)\n\t}\n\tif err := validation.ValidateNodeResourcesFitArgs(nil, args); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif args.ScoringStrategy == nil {\n\t\treturn nil, fmt.Errorf(\"scoring strategy not specified\")\n\t}\n\n\tstrategy := args.ScoringStrategy.Type\n\tscorePlugin, exists := nodeResourceStrategyTypeMap[strategy]\n\tif !exists {\n\t\treturn nil, fmt.Errorf(\"scoring strategy %s is not supported\", strategy)\n\t}\n\n\treturn \u0026Fit{\n\t\tignoredResources: sets.NewString(args.IgnoredResources...),\n\t\tignoredResourceGroups: sets.NewString(args.IgnoredResourceGroups...),\n\t\tenableInPlacePodVerticalScaling: fts.EnableInPlacePodVerticalScaling,\n\t\thandle: h,\n\t\tresourceAllocationScorer: *scorePlugin(args),\n\t}, nil\n}","line":{"from":147,"to":174}} {"id":100010846,"name":"computePodResourceRequest","signature":"func computePodResourceRequest(pod *v1.Pod) *preFilterState","file":"pkg/scheduler/framework/plugins/noderesources/fit.go","code":"// computePodResourceRequest returns a framework.Resource that covers the largest\n// width in each resource dimension. Because init-containers run sequentially, we collect\n// the max in each dimension iteratively. In contrast, we sum the resource vectors for\n// regular containers since they run simultaneously.\n//\n// # The resources defined for Overhead should be added to the calculated Resource request sum\n//\n// Example:\n//\n// Pod:\n//\n//\tInitContainers\n//\t IC1:\n//\t CPU: 2\n//\t Memory: 1G\n//\t IC2:\n//\t CPU: 2\n//\t Memory: 3G\n//\tContainers\n//\t C1:\n//\t CPU: 2\n//\t Memory: 1G\n//\t C2:\n//\t CPU: 1\n//\t Memory: 1G\n//\n// Result: CPU: 3, Memory: 3G\nfunc computePodResourceRequest(pod *v1.Pod) *preFilterState {\n\t// pod hasn't scheduled yet so we don't need to worry about InPlacePodVerticalScalingEnabled\n\treqs := resource.PodRequests(pod, resource.PodResourcesOptions{})\n\tresult := \u0026preFilterState{}\n\tresult.SetMaxResource(reqs)\n\treturn result\n}","line":{"from":176,"to":209}} {"id":100010847,"name":"PreFilter","signature":"func (f *Fit) PreFilter(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod) (*framework.PreFilterResult, *framework.Status)","file":"pkg/scheduler/framework/plugins/noderesources/fit.go","code":"// PreFilter invoked at the prefilter extension point.\nfunc (f *Fit) PreFilter(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod) (*framework.PreFilterResult, *framework.Status) {\n\tcycleState.Write(preFilterStateKey, computePodResourceRequest(pod))\n\treturn nil, nil\n}","line":{"from":211,"to":215}} {"id":100010848,"name":"PreFilterExtensions","signature":"func (f *Fit) PreFilterExtensions() framework.PreFilterExtensions","file":"pkg/scheduler/framework/plugins/noderesources/fit.go","code":"// PreFilterExtensions returns prefilter extensions, pod add and remove.\nfunc (f *Fit) PreFilterExtensions() framework.PreFilterExtensions {\n\treturn nil\n}","line":{"from":217,"to":220}} {"id":100010849,"name":"getPreFilterState","signature":"func getPreFilterState(cycleState *framework.CycleState) (*preFilterState, error)","file":"pkg/scheduler/framework/plugins/noderesources/fit.go","code":"func getPreFilterState(cycleState *framework.CycleState) (*preFilterState, error) {\n\tc, err := cycleState.Read(preFilterStateKey)\n\tif err != nil {\n\t\t// preFilterState doesn't exist, likely PreFilter wasn't invoked.\n\t\treturn nil, fmt.Errorf(\"error reading %q from cycleState: %w\", preFilterStateKey, err)\n\t}\n\n\ts, ok := c.(*preFilterState)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"%+v convert to NodeResourcesFit.preFilterState error\", c)\n\t}\n\treturn s, nil\n}","line":{"from":222,"to":234}} {"id":100010850,"name":"EventsToRegister","signature":"func (f *Fit) EventsToRegister() []framework.ClusterEvent","file":"pkg/scheduler/framework/plugins/noderesources/fit.go","code":"// EventsToRegister returns the possible events that may make a Pod\n// failed by this plugin schedulable.\nfunc (f *Fit) EventsToRegister() []framework.ClusterEvent {\n\tpodActionType := framework.Delete\n\tif f.enableInPlacePodVerticalScaling {\n\t\t// If InPlacePodVerticalScaling (KEP 1287) is enabled, then PodUpdate event should be registered\n\t\t// for this plugin since a Pod update may free up resources that make other Pods schedulable.\n\t\tpodActionType |= framework.Update\n\t}\n\treturn []framework.ClusterEvent{\n\t\t{Resource: framework.Pod, ActionType: podActionType},\n\t\t{Resource: framework.Node, ActionType: framework.Add | framework.Update},\n\t}\n}","line":{"from":236,"to":249}} {"id":100010851,"name":"Filter","signature":"func (f *Fit) Filter(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status","file":"pkg/scheduler/framework/plugins/noderesources/fit.go","code":"// Filter invoked at the filter extension point.\n// Checks if a node has sufficient resources, such as cpu, memory, gpu, opaque int resources etc to run a pod.\n// It returns a list of insufficient resources, if empty, then the node has all the resources requested by the pod.\nfunc (f *Fit) Filter(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status {\n\ts, err := getPreFilterState(cycleState)\n\tif err != nil {\n\t\treturn framework.AsStatus(err)\n\t}\n\n\tinsufficientResources := fitsRequest(s, nodeInfo, f.ignoredResources, f.ignoredResourceGroups)\n\n\tif len(insufficientResources) != 0 {\n\t\t// We will keep all failure reasons.\n\t\tfailureReasons := make([]string, 0, len(insufficientResources))\n\t\tfor i := range insufficientResources {\n\t\t\tfailureReasons = append(failureReasons, insufficientResources[i].Reason)\n\t\t}\n\t\treturn framework.NewStatus(framework.Unschedulable, failureReasons...)\n\t}\n\treturn nil\n}","line":{"from":251,"to":271}} {"id":100010852,"name":"Fits","signature":"func Fits(pod *v1.Pod, nodeInfo *framework.NodeInfo) []InsufficientResource","file":"pkg/scheduler/framework/plugins/noderesources/fit.go","code":"// Fits checks if node have enough resources to host the pod.\nfunc Fits(pod *v1.Pod, nodeInfo *framework.NodeInfo) []InsufficientResource {\n\treturn fitsRequest(computePodResourceRequest(pod), nodeInfo, nil, nil)\n}","line":{"from":284,"to":287}} {"id":100010853,"name":"fitsRequest","signature":"func fitsRequest(podRequest *preFilterState, nodeInfo *framework.NodeInfo, ignoredExtendedResources, ignoredResourceGroups sets.String) []InsufficientResource","file":"pkg/scheduler/framework/plugins/noderesources/fit.go","code":"func fitsRequest(podRequest *preFilterState, nodeInfo *framework.NodeInfo, ignoredExtendedResources, ignoredResourceGroups sets.String) []InsufficientResource {\n\tinsufficientResources := make([]InsufficientResource, 0, 4)\n\n\tallowedPodNumber := nodeInfo.Allocatable.AllowedPodNumber\n\tif len(nodeInfo.Pods)+1 \u003e allowedPodNumber {\n\t\tinsufficientResources = append(insufficientResources, InsufficientResource{\n\t\t\tResourceName: v1.ResourcePods,\n\t\t\tReason: \"Too many pods\",\n\t\t\tRequested: 1,\n\t\t\tUsed: int64(len(nodeInfo.Pods)),\n\t\t\tCapacity: int64(allowedPodNumber),\n\t\t})\n\t}\n\n\tif podRequest.MilliCPU == 0 \u0026\u0026\n\t\tpodRequest.Memory == 0 \u0026\u0026\n\t\tpodRequest.EphemeralStorage == 0 \u0026\u0026\n\t\tlen(podRequest.ScalarResources) == 0 {\n\t\treturn insufficientResources\n\t}\n\n\tif podRequest.MilliCPU \u003e (nodeInfo.Allocatable.MilliCPU - nodeInfo.Requested.MilliCPU) {\n\t\tinsufficientResources = append(insufficientResources, InsufficientResource{\n\t\t\tResourceName: v1.ResourceCPU,\n\t\t\tReason: \"Insufficient cpu\",\n\t\t\tRequested: podRequest.MilliCPU,\n\t\t\tUsed: nodeInfo.Requested.MilliCPU,\n\t\t\tCapacity: nodeInfo.Allocatable.MilliCPU,\n\t\t})\n\t}\n\tif podRequest.Memory \u003e (nodeInfo.Allocatable.Memory - nodeInfo.Requested.Memory) {\n\t\tinsufficientResources = append(insufficientResources, InsufficientResource{\n\t\t\tResourceName: v1.ResourceMemory,\n\t\t\tReason: \"Insufficient memory\",\n\t\t\tRequested: podRequest.Memory,\n\t\t\tUsed: nodeInfo.Requested.Memory,\n\t\t\tCapacity: nodeInfo.Allocatable.Memory,\n\t\t})\n\t}\n\tif podRequest.EphemeralStorage \u003e (nodeInfo.Allocatable.EphemeralStorage - nodeInfo.Requested.EphemeralStorage) {\n\t\tinsufficientResources = append(insufficientResources, InsufficientResource{\n\t\t\tResourceName: v1.ResourceEphemeralStorage,\n\t\t\tReason: \"Insufficient ephemeral-storage\",\n\t\t\tRequested: podRequest.EphemeralStorage,\n\t\t\tUsed: nodeInfo.Requested.EphemeralStorage,\n\t\t\tCapacity: nodeInfo.Allocatable.EphemeralStorage,\n\t\t})\n\t}\n\n\tfor rName, rQuant := range podRequest.ScalarResources {\n\t\t// Skip in case request quantity is zero\n\t\tif rQuant == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif v1helper.IsExtendedResourceName(rName) {\n\t\t\t// If this resource is one of the extended resources that should be ignored, we will skip checking it.\n\t\t\t// rName is guaranteed to have a slash due to API validation.\n\t\t\tvar rNamePrefix string\n\t\t\tif ignoredResourceGroups.Len() \u003e 0 {\n\t\t\t\trNamePrefix = strings.Split(string(rName), \"/\")[0]\n\t\t\t}\n\t\t\tif ignoredExtendedResources.Has(string(rName)) || ignoredResourceGroups.Has(rNamePrefix) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tif rQuant \u003e (nodeInfo.Allocatable.ScalarResources[rName] - nodeInfo.Requested.ScalarResources[rName]) {\n\t\t\tinsufficientResources = append(insufficientResources, InsufficientResource{\n\t\t\t\tResourceName: rName,\n\t\t\t\tReason: fmt.Sprintf(\"Insufficient %v\", rName),\n\t\t\t\tRequested: podRequest.ScalarResources[rName],\n\t\t\t\tUsed: nodeInfo.Requested.ScalarResources[rName],\n\t\t\t\tCapacity: nodeInfo.Allocatable.ScalarResources[rName],\n\t\t\t})\n\t\t}\n\t}\n\n\treturn insufficientResources\n}","line":{"from":289,"to":368}} {"id":100010854,"name":"Score","signature":"func (f *Fit) Score(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status)","file":"pkg/scheduler/framework/plugins/noderesources/fit.go","code":"// Score invoked at the Score extension point.\nfunc (f *Fit) Score(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status) {\n\tnodeInfo, err := f.handle.SnapshotSharedLister().NodeInfos().Get(nodeName)\n\tif err != nil {\n\t\treturn 0, framework.AsStatus(fmt.Errorf(\"getting node %q from Snapshot: %w\", nodeName, err))\n\t}\n\n\ts, err := getPreScoreState(state)\n\tif err != nil {\n\t\ts = \u0026preScoreState{\n\t\t\tpodRequests: f.calculatePodResourceRequestList(pod, f.resources),\n\t\t}\n\t}\n\n\treturn f.score(pod, nodeInfo, s.podRequests)\n}","line":{"from":370,"to":385}} {"id":100010855,"name":"leastResourceScorer","signature":"func leastResourceScorer(resources []config.ResourceSpec) func([]int64, []int64) int64","file":"pkg/scheduler/framework/plugins/noderesources/least_allocated.go","code":"// leastResourceScorer favors nodes with fewer requested resources.\n// It calculates the percentage of memory, CPU and other resources requested by pods scheduled on the node, and\n// prioritizes based on the minimum of the average of the fraction of requested to capacity.\n//\n// Details:\n// (cpu((capacity-requested)*MaxNodeScore*cpuWeight/capacity) + memory((capacity-requested)*MaxNodeScore*memoryWeight/capacity) + ...)/weightSum\nfunc leastResourceScorer(resources []config.ResourceSpec) func([]int64, []int64) int64 {\n\treturn func(requested, allocable []int64) int64 {\n\t\tvar nodeScore, weightSum int64\n\t\tfor i := range requested {\n\t\t\tif allocable[i] == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tweight := resources[i].Weight\n\t\t\tresourceScore := leastRequestedScore(requested[i], allocable[i])\n\t\t\tnodeScore += resourceScore * weight\n\t\t\tweightSum += weight\n\t\t}\n\t\tif weightSum == 0 {\n\t\t\treturn 0\n\t\t}\n\t\treturn nodeScore / weightSum\n\t}\n}","line":{"from":24,"to":47}} {"id":100010856,"name":"leastRequestedScore","signature":"func leastRequestedScore(requested, capacity int64) int64","file":"pkg/scheduler/framework/plugins/noderesources/least_allocated.go","code":"// The unused capacity is calculated on a scale of 0-MaxNodeScore\n// 0 being the lowest priority and `MaxNodeScore` being the highest.\n// The more unused resources the higher the score is.\nfunc leastRequestedScore(requested, capacity int64) int64 {\n\tif capacity == 0 {\n\t\treturn 0\n\t}\n\tif requested \u003e capacity {\n\t\treturn 0\n\t}\n\n\treturn ((capacity - requested) * framework.MaxNodeScore) / capacity\n}","line":{"from":49,"to":61}} {"id":100010857,"name":"mostResourceScorer","signature":"func mostResourceScorer(resources []config.ResourceSpec) func(requested, allocable []int64) int64","file":"pkg/scheduler/framework/plugins/noderesources/most_allocated.go","code":"// mostResourceScorer favors nodes with most requested resources.\n// It calculates the percentage of memory and CPU requested by pods scheduled on the node, and prioritizes\n// based on the maximum of the average of the fraction of requested to capacity.\n//\n// Details:\n// (cpu(MaxNodeScore * requested * cpuWeight / capacity) + memory(MaxNodeScore * requested * memoryWeight / capacity) + ...) / weightSum\nfunc mostResourceScorer(resources []config.ResourceSpec) func(requested, allocable []int64) int64 {\n\treturn func(requested, allocable []int64) int64 {\n\t\tvar nodeScore, weightSum int64\n\t\tfor i := range requested {\n\t\t\tif allocable[i] == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tweight := resources[i].Weight\n\t\t\tresourceScore := mostRequestedScore(requested[i], allocable[i])\n\t\t\tnodeScore += resourceScore * weight\n\t\t\tweightSum += weight\n\t\t}\n\t\tif weightSum == 0 {\n\t\t\treturn 0\n\t\t}\n\t\treturn nodeScore / weightSum\n\t}\n}","line":{"from":24,"to":47}} {"id":100010858,"name":"mostRequestedScore","signature":"func mostRequestedScore(requested, capacity int64) int64","file":"pkg/scheduler/framework/plugins/noderesources/most_allocated.go","code":"// The used capacity is calculated on a scale of 0-MaxNodeScore (MaxNodeScore is\n// constant with value set to 100).\n// 0 being the lowest priority and 100 being the highest.\n// The more resources are used the higher the score is. This function\n// is almost a reversed version of noderesources.leastRequestedScore.\nfunc mostRequestedScore(requested, capacity int64) int64 {\n\tif capacity == 0 {\n\t\treturn 0\n\t}\n\tif requested \u003e capacity {\n\t\t// `requested` might be greater than `capacity` because pods with no\n\t\t// requests get minimum values.\n\t\trequested = capacity\n\t}\n\n\treturn (requested * framework.MaxNodeScore) / capacity\n}","line":{"from":49,"to":65}} {"id":100010859,"name":"buildRequestedToCapacityRatioScorerFunction","signature":"func buildRequestedToCapacityRatioScorerFunction(scoringFunctionShape helper.FunctionShape, resources []config.ResourceSpec) func([]int64, []int64) int64","file":"pkg/scheduler/framework/plugins/noderesources/requested_to_capacity_ratio.go","code":"// buildRequestedToCapacityRatioScorerFunction allows users to apply bin packing\n// on core resources like CPU, Memory as well as extended resources like accelerators.\nfunc buildRequestedToCapacityRatioScorerFunction(scoringFunctionShape helper.FunctionShape, resources []config.ResourceSpec) func([]int64, []int64) int64 {\n\trawScoringFunction := helper.BuildBrokenLinearFunction(scoringFunctionShape)\n\tresourceScoringFunction := func(requested, capacity int64) int64 {\n\t\tif capacity == 0 || requested \u003e capacity {\n\t\t\treturn rawScoringFunction(maxUtilization)\n\t\t}\n\n\t\treturn rawScoringFunction(requested * maxUtilization / capacity)\n\t}\n\treturn func(requested, allocable []int64) int64 {\n\t\tvar nodeScore, weightSum int64\n\t\tfor i := range requested {\n\t\t\tif allocable[i] == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tweight := resources[i].Weight\n\t\t\tresourceScore := resourceScoringFunction(requested[i], allocable[i])\n\t\t\tif resourceScore \u003e 0 {\n\t\t\t\tnodeScore += resourceScore * weight\n\t\t\t\tweightSum += weight\n\t\t\t}\n\t\t}\n\t\tif weightSum == 0 {\n\t\t\treturn 0\n\t\t}\n\t\treturn int64(math.Round(float64(nodeScore) / float64(weightSum)))\n\t}\n}","line":{"from":29,"to":58}} {"id":100010860,"name":"requestedToCapacityRatioScorer","signature":"func requestedToCapacityRatioScorer(resources []config.ResourceSpec, shape []config.UtilizationShapePoint) func([]int64, []int64) int64","file":"pkg/scheduler/framework/plugins/noderesources/requested_to_capacity_ratio.go","code":"func requestedToCapacityRatioScorer(resources []config.ResourceSpec, shape []config.UtilizationShapePoint) func([]int64, []int64) int64 {\n\tshapes := make([]helper.FunctionShapePoint, 0, len(shape))\n\tfor _, point := range shape {\n\t\tshapes = append(shapes, helper.FunctionShapePoint{\n\t\t\tUtilization: int64(point.Utilization),\n\t\t\t// MaxCustomPriorityScore may diverge from the max score used in the scheduler and defined by MaxNodeScore,\n\t\t\t// therefore we need to scale the score returned by requested to capacity ratio to the score range\n\t\t\t// used by the scheduler.\n\t\t\tScore: int64(point.Score) * (framework.MaxNodeScore / config.MaxCustomPriorityScore),\n\t\t})\n\t}\n\n\treturn buildRequestedToCapacityRatioScorerFunction(shapes, resources)\n}","line":{"from":60,"to":73}} {"id":100010861,"name":"score","signature":"func (r *resourceAllocationScorer) score(","file":"pkg/scheduler/framework/plugins/noderesources/resource_allocation.go","code":"// score will use `scorer` function to calculate the score.\nfunc (r *resourceAllocationScorer) score(\n\tpod *v1.Pod,\n\tnodeInfo *framework.NodeInfo,\n\tpodRequests []int64) (int64, *framework.Status) {\n\tnode := nodeInfo.Node()\n\tif node == nil {\n\t\treturn 0, framework.NewStatus(framework.Error, \"node not found\")\n\t}\n\t// resources not set, nothing scheduled,\n\tif len(r.resources) == 0 {\n\t\treturn 0, framework.NewStatus(framework.Error, \"resources not found\")\n\t}\n\n\trequested := make([]int64, len(r.resources))\n\tallocatable := make([]int64, len(r.resources))\n\tfor i := range r.resources {\n\t\talloc, req := r.calculateResourceAllocatableRequest(nodeInfo, v1.ResourceName(r.resources[i].Name), podRequests[i])\n\t\t// Only fill the extended resource entry when it's non-zero.\n\t\tif alloc == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tallocatable[i] = alloc\n\t\trequested[i] = req\n\t}\n\n\tscore := r.scorer(requested, allocatable)\n\n\tif klogV := klog.V(10); klogV.Enabled() { // Serializing these maps is costly.\n\t\tklogV.InfoS(\"Listing internal info for allocatable resources, requested resources and score\", \"pod\",\n\t\t\tklog.KObj(pod), \"node\", klog.KObj(node), \"resourceAllocationScorer\", r.Name,\n\t\t\t\"allocatableResource\", allocatable, \"requestedResource\", requested, \"resourceScore\", score,\n\t\t)\n\t}\n\n\treturn score, nil\n}","line":{"from":45,"to":81}} {"id":100010862,"name":"calculateResourceAllocatableRequest","signature":"func (r *resourceAllocationScorer) calculateResourceAllocatableRequest(nodeInfo *framework.NodeInfo, resource v1.ResourceName, podRequest int64) (int64, int64)","file":"pkg/scheduler/framework/plugins/noderesources/resource_allocation.go","code":"// calculateResourceAllocatableRequest returns 2 parameters:\n// - 1st param: quantity of allocatable resource on the node.\n// - 2nd param: aggregated quantity of requested resource on the node.\n// Note: if it's an extended resource, and the pod doesn't request it, (0, 0) is returned.\nfunc (r *resourceAllocationScorer) calculateResourceAllocatableRequest(nodeInfo *framework.NodeInfo, resource v1.ResourceName, podRequest int64) (int64, int64) {\n\trequested := nodeInfo.NonZeroRequested\n\tif r.useRequested {\n\t\trequested = nodeInfo.Requested\n\t}\n\n\t// If it's an extended resource, and the pod doesn't request it. We return (0, 0)\n\t// as an implication to bypass scoring on this resource.\n\tif podRequest == 0 \u0026\u0026 schedutil.IsScalarResourceName(resource) {\n\t\treturn 0, 0\n\t}\n\tswitch resource {\n\tcase v1.ResourceCPU:\n\t\treturn nodeInfo.Allocatable.MilliCPU, (requested.MilliCPU + podRequest)\n\tcase v1.ResourceMemory:\n\t\treturn nodeInfo.Allocatable.Memory, (requested.Memory + podRequest)\n\tcase v1.ResourceEphemeralStorage:\n\t\treturn nodeInfo.Allocatable.EphemeralStorage, (nodeInfo.Requested.EphemeralStorage + podRequest)\n\tdefault:\n\t\tif _, exists := nodeInfo.Allocatable.ScalarResources[resource]; exists {\n\t\t\treturn nodeInfo.Allocatable.ScalarResources[resource], (nodeInfo.Requested.ScalarResources[resource] + podRequest)\n\t\t}\n\t}\n\tklog.V(10).InfoS(\"Requested resource is omitted for node score calculation\", \"resourceName\", resource)\n\treturn 0, 0\n}","line":{"from":83,"to":112}} {"id":100010863,"name":"calculatePodResourceRequest","signature":"func (r *resourceAllocationScorer) calculatePodResourceRequest(pod *v1.Pod, resourceName v1.ResourceName) int64","file":"pkg/scheduler/framework/plugins/noderesources/resource_allocation.go","code":"// calculatePodResourceRequest returns the total non-zero requests. If Overhead is defined for the pod\n// the Overhead is added to the result.\nfunc (r *resourceAllocationScorer) calculatePodResourceRequest(pod *v1.Pod, resourceName v1.ResourceName) int64 {\n\n\topts := resourcehelper.PodResourcesOptions{\n\t\tInPlacePodVerticalScalingEnabled: utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling),\n\t}\n\tif !r.useRequested {\n\t\topts.NonMissingContainerRequests = v1.ResourceList{\n\t\t\tv1.ResourceCPU: *resource.NewMilliQuantity(schedutil.DefaultMilliCPURequest, resource.DecimalSI),\n\t\t\tv1.ResourceMemory: *resource.NewQuantity(schedutil.DefaultMemoryRequest, resource.DecimalSI),\n\t\t}\n\t}\n\n\trequests := resourcehelper.PodRequests(pod, opts)\n\n\tquantity := requests[resourceName]\n\tif resourceName == v1.ResourceCPU {\n\t\treturn quantity.MilliValue()\n\t}\n\treturn quantity.Value()\n}","line":{"from":114,"to":135}} {"id":100010864,"name":"calculatePodResourceRequestList","signature":"func (r *resourceAllocationScorer) calculatePodResourceRequestList(pod *v1.Pod, resources []config.ResourceSpec) []int64","file":"pkg/scheduler/framework/plugins/noderesources/resource_allocation.go","code":"func (r *resourceAllocationScorer) calculatePodResourceRequestList(pod *v1.Pod, resources []config.ResourceSpec) []int64 {\n\tpodRequests := make([]int64, len(resources))\n\tfor i := range resources {\n\t\tpodRequests[i] = r.calculatePodResourceRequest(pod, v1.ResourceName(resources[i].Name))\n\t}\n\treturn podRequests\n}","line":{"from":137,"to":143}} {"id":100010865,"name":"EventsToRegister","signature":"func (pl *NodeUnschedulable) EventsToRegister() []framework.ClusterEvent","file":"pkg/scheduler/framework/plugins/nodeunschedulable/node_unschedulable.go","code":"// EventsToRegister returns the possible events that may make a Pod\n// failed by this plugin schedulable.\nfunc (pl *NodeUnschedulable) EventsToRegister() []framework.ClusterEvent {\n\treturn []framework.ClusterEvent{\n\t\t{Resource: framework.Node, ActionType: framework.Add | framework.UpdateNodeTaint},\n\t}\n}","line":{"from":47,"to":53}} {"id":100010866,"name":"Name","signature":"func (pl *NodeUnschedulable) Name() string","file":"pkg/scheduler/framework/plugins/nodeunschedulable/node_unschedulable.go","code":"// Name returns name of the plugin. It is used in logs, etc.\nfunc (pl *NodeUnschedulable) Name() string {\n\treturn Name\n}","line":{"from":55,"to":58}} {"id":100010867,"name":"Filter","signature":"func (pl *NodeUnschedulable) Filter(ctx context.Context, _ *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status","file":"pkg/scheduler/framework/plugins/nodeunschedulable/node_unschedulable.go","code":"// Filter invoked at the filter extension point.\nfunc (pl *NodeUnschedulable) Filter(ctx context.Context, _ *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status {\n\tnode := nodeInfo.Node()\n\tif node == nil {\n\t\treturn framework.NewStatus(framework.UnschedulableAndUnresolvable, ErrReasonUnknownCondition)\n\t}\n\t// If pod tolerate unschedulable taint, it's also tolerate `node.Spec.Unschedulable`.\n\tpodToleratesUnschedulable := v1helper.TolerationsTolerateTaint(pod.Spec.Tolerations, \u0026v1.Taint{\n\t\tKey: v1.TaintNodeUnschedulable,\n\t\tEffect: v1.TaintEffectNoSchedule,\n\t})\n\tif node.Spec.Unschedulable \u0026\u0026 !podToleratesUnschedulable {\n\t\treturn framework.NewStatus(framework.UnschedulableAndUnresolvable, ErrReasonUnschedulable)\n\t}\n\treturn nil\n}","line":{"from":60,"to":75}} {"id":100010868,"name":"New","signature":"func New(_ runtime.Object, _ framework.Handle) (framework.Plugin, error)","file":"pkg/scheduler/framework/plugins/nodeunschedulable/node_unschedulable.go","code":"// New initializes a new plugin and returns it.\nfunc New(_ runtime.Object, _ framework.Handle) (framework.Plugin, error) {\n\treturn \u0026NodeUnschedulable{}, nil\n}","line":{"from":77,"to":80}} {"id":100010869,"name":"Name","signature":"func (pl *CSILimits) Name() string","file":"pkg/scheduler/framework/plugins/nodevolumelimits/csi.go","code":"// Name returns name of the plugin. It is used in logs, etc.\nfunc (pl *CSILimits) Name() string {\n\treturn CSIName\n}","line":{"from":69,"to":72}} {"id":100010870,"name":"EventsToRegister","signature":"func (pl *CSILimits) EventsToRegister() []framework.ClusterEvent","file":"pkg/scheduler/framework/plugins/nodevolumelimits/csi.go","code":"// EventsToRegister returns the possible events that may make a Pod\n// failed by this plugin schedulable.\nfunc (pl *CSILimits) EventsToRegister() []framework.ClusterEvent {\n\treturn []framework.ClusterEvent{\n\t\t{Resource: framework.CSINode, ActionType: framework.Add},\n\t\t{Resource: framework.Pod, ActionType: framework.Delete},\n\t}\n}","line":{"from":74,"to":81}} {"id":100010871,"name":"Filter","signature":"func (pl *CSILimits) Filter(ctx context.Context, _ *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status","file":"pkg/scheduler/framework/plugins/nodevolumelimits/csi.go","code":"// Filter invoked at the filter extension point.\nfunc (pl *CSILimits) Filter(ctx context.Context, _ *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status {\n\t// If the new pod doesn't have any volume attached to it, the predicate will always be true\n\tif len(pod.Spec.Volumes) == 0 {\n\t\treturn nil\n\t}\n\n\tnode := nodeInfo.Node()\n\tif node == nil {\n\t\treturn framework.NewStatus(framework.Error, \"node not found\")\n\t}\n\n\t// If CSINode doesn't exist, the predicate may read the limits from Node object\n\tcsiNode, err := pl.csiNodeLister.Get(node.Name)\n\tif err != nil {\n\t\t// TODO: return the error once CSINode is created by default (2 releases)\n\t\tklog.V(5).InfoS(\"Could not get a CSINode object for the node\", \"node\", klog.KObj(node), \"err\", err)\n\t}\n\n\tnewVolumes := make(map[string]string)\n\tif err := pl.filterAttachableVolumes(pod, csiNode, true /* new pod */, newVolumes); err != nil {\n\t\treturn framework.AsStatus(err)\n\t}\n\n\t// If the pod doesn't have any new CSI volumes, the predicate will always be true\n\tif len(newVolumes) == 0 {\n\t\treturn nil\n\t}\n\n\t// If the node doesn't have volume limits, the predicate will always be true\n\tnodeVolumeLimits := getVolumeLimits(nodeInfo, csiNode)\n\tif len(nodeVolumeLimits) == 0 {\n\t\treturn nil\n\t}\n\n\tattachedVolumes := make(map[string]string)\n\tfor _, existingPod := range nodeInfo.Pods {\n\t\tif err := pl.filterAttachableVolumes(existingPod.Pod, csiNode, false /* existing pod */, attachedVolumes); err != nil {\n\t\t\treturn framework.AsStatus(err)\n\t\t}\n\t}\n\n\tattachedVolumeCount := map[string]int{}\n\tfor volumeUniqueName, volumeLimitKey := range attachedVolumes {\n\t\t// Don't count single volume used in multiple pods more than once\n\t\tdelete(newVolumes, volumeUniqueName)\n\t\tattachedVolumeCount[volumeLimitKey]++\n\t}\n\n\tnewVolumeCount := map[string]int{}\n\tfor _, volumeLimitKey := range newVolumes {\n\t\tnewVolumeCount[volumeLimitKey]++\n\t}\n\n\tfor volumeLimitKey, count := range newVolumeCount {\n\t\tmaxVolumeLimit, ok := nodeVolumeLimits[v1.ResourceName(volumeLimitKey)]\n\t\tif ok {\n\t\t\tcurrentVolumeCount := attachedVolumeCount[volumeLimitKey]\n\t\t\tklog.V(5).InfoS(\"Found plugin volume limits\", \"node\", node.Name, \"volumeLimitKey\", volumeLimitKey,\n\t\t\t\t\"maxLimits\", maxVolumeLimit, \"currentVolumeCount\", currentVolumeCount, \"newVolumeCount\", count,\n\t\t\t\t\"pod\", klog.KObj(pod))\n\t\t\tif currentVolumeCount+count \u003e int(maxVolumeLimit) {\n\t\t\t\treturn framework.NewStatus(framework.Unschedulable, ErrReasonMaxVolumeCountExceeded)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":83,"to":151}} {"id":100010872,"name":"filterAttachableVolumes","signature":"func (pl *CSILimits) filterAttachableVolumes(","file":"pkg/scheduler/framework/plugins/nodevolumelimits/csi.go","code":"func (pl *CSILimits) filterAttachableVolumes(\n\tpod *v1.Pod, csiNode *storagev1.CSINode, newPod bool, result map[string]string) error {\n\tfor _, vol := range pod.Spec.Volumes {\n\t\tpvcName := \"\"\n\t\tisEphemeral := false\n\t\tswitch {\n\t\tcase vol.PersistentVolumeClaim != nil:\n\t\t\t// Normal CSI volume can only be used through PVC\n\t\t\tpvcName = vol.PersistentVolumeClaim.ClaimName\n\t\tcase vol.Ephemeral != nil:\n\t\t\t// Generic ephemeral inline volumes also use a PVC,\n\t\t\t// just with a computed name and certain ownership.\n\t\t\t// That is checked below once the pvc object is\n\t\t\t// retrieved.\n\t\t\tpvcName = ephemeral.VolumeClaimName(pod, \u0026vol)\n\t\t\tisEphemeral = true\n\t\tdefault:\n\t\t\t// Inline Volume does not have PVC.\n\t\t\t// Need to check if CSI migration is enabled for this inline volume.\n\t\t\t// - If the volume is migratable and CSI migration is enabled, need to count it\n\t\t\t// as well.\n\t\t\t// - If the volume is not migratable, it will be count in non_csi filter.\n\t\t\tif err := pl.checkAttachableInlineVolume(vol, csiNode, pod, result); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif pvcName == \"\" {\n\t\t\treturn fmt.Errorf(\"PersistentVolumeClaim had no name\")\n\t\t}\n\n\t\tpvc, err := pl.pvcLister.PersistentVolumeClaims(pod.Namespace).Get(pvcName)\n\n\t\tif err != nil {\n\t\t\tif newPod {\n\t\t\t\t// The PVC is required to proceed with\n\t\t\t\t// scheduling of a new pod because it cannot\n\t\t\t\t// run without it. Bail out immediately.\n\t\t\t\treturn fmt.Errorf(\"looking up PVC %s/%s: %v\", pod.Namespace, pvcName, err)\n\t\t\t}\n\t\t\t// If the PVC is invalid, we don't count the volume because\n\t\t\t// there's no guarantee that it belongs to the running predicate.\n\t\t\tklog.V(5).InfoS(\"Unable to look up PVC info\", \"pod\", klog.KObj(pod), \"PVC\", klog.KRef(pod.Namespace, pvcName))\n\t\t\tcontinue\n\t\t}\n\n\t\t// The PVC for an ephemeral volume must be owned by the pod.\n\t\tif isEphemeral {\n\t\t\tif err := ephemeral.VolumeIsForPod(pod, pvc); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tdriverName, volumeHandle := pl.getCSIDriverInfo(csiNode, pvc)\n\t\tif driverName == \"\" || volumeHandle == \"\" {\n\t\t\tklog.V(5).InfoS(\"Could not find a CSI driver name or volume handle, not counting volume\")\n\t\t\tcontinue\n\t\t}\n\n\t\tvolumeUniqueName := fmt.Sprintf(\"%s/%s\", driverName, volumeHandle)\n\t\tvolumeLimitKey := volumeutil.GetCSIAttachLimitKey(driverName)\n\t\tresult[volumeUniqueName] = volumeLimitKey\n\t}\n\treturn nil\n}","line":{"from":153,"to":219}} {"id":100010873,"name":"checkAttachableInlineVolume","signature":"func (pl *CSILimits) checkAttachableInlineVolume(vol v1.Volume, csiNode *storagev1.CSINode,","file":"pkg/scheduler/framework/plugins/nodevolumelimits/csi.go","code":"// checkAttachableInlineVolume takes an inline volume and add to the result map if the\n// volume is migratable and CSI migration for this plugin has been enabled.\nfunc (pl *CSILimits) checkAttachableInlineVolume(vol v1.Volume, csiNode *storagev1.CSINode,\n\tpod *v1.Pod, result map[string]string) error {\n\tif !pl.translator.IsInlineMigratable(\u0026vol) {\n\t\treturn nil\n\t}\n\t// Check if the intree provisioner CSI migration has been enabled.\n\tinTreeProvisionerName, err := pl.translator.GetInTreePluginNameFromSpec(nil, \u0026vol)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"looking up provisioner name for volume %v: %w\", vol, err)\n\t}\n\tif !isCSIMigrationOn(csiNode, inTreeProvisionerName) {\n\t\tcsiNodeName := \"\"\n\t\tif csiNode != nil {\n\t\t\tcsiNodeName = csiNode.Name\n\t\t}\n\t\tklog.V(5).InfoS(\"CSI Migration is not enabled for provisioner\", \"provisioner\", inTreeProvisionerName,\n\t\t\t\"pod\", klog.KObj(pod), \"csiNode\", csiNodeName)\n\t\treturn nil\n\t}\n\t// Do translation for the in-tree volume.\n\ttranslatedPV, err := pl.translator.TranslateInTreeInlineVolumeToCSI(\u0026vol, pod.Namespace)\n\tif err != nil || translatedPV == nil {\n\t\treturn fmt.Errorf(\"converting volume(%v) from inline to csi: %w\", vol, err)\n\t}\n\tdriverName, err := pl.translator.GetCSINameFromInTreeName(inTreeProvisionerName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"looking up CSI driver name for provisioner %s: %w\", inTreeProvisionerName, err)\n\t}\n\t// TranslateInTreeInlineVolumeToCSI should translate inline volume to CSI. If it is not set,\n\t// the volume does not support inline. Skip the count.\n\tif translatedPV.Spec.PersistentVolumeSource.CSI == nil {\n\t\treturn nil\n\t}\n\tvolumeUniqueName := fmt.Sprintf(\"%s/%s\", driverName, translatedPV.Spec.PersistentVolumeSource.CSI.VolumeHandle)\n\tvolumeLimitKey := volumeutil.GetCSIAttachLimitKey(driverName)\n\tresult[volumeUniqueName] = volumeLimitKey\n\treturn nil\n}","line":{"from":221,"to":260}} {"id":100010874,"name":"getCSIDriverInfo","signature":"func (pl *CSILimits) getCSIDriverInfo(csiNode *storagev1.CSINode, pvc *v1.PersistentVolumeClaim) (string, string)","file":"pkg/scheduler/framework/plugins/nodevolumelimits/csi.go","code":"// getCSIDriverInfo returns the CSI driver name and volume ID of a given PVC.\n// If the PVC is from a migrated in-tree plugin, this function will return\n// the information of the CSI driver that the plugin has been migrated to.\nfunc (pl *CSILimits) getCSIDriverInfo(csiNode *storagev1.CSINode, pvc *v1.PersistentVolumeClaim) (string, string) {\n\tpvName := pvc.Spec.VolumeName\n\n\tif pvName == \"\" {\n\t\tklog.V(5).InfoS(\"Persistent volume had no name for claim\", \"PVC\", klog.KObj(pvc))\n\t\treturn pl.getCSIDriverInfoFromSC(csiNode, pvc)\n\t}\n\n\tpv, err := pl.pvLister.Get(pvName)\n\tif err != nil {\n\t\tklog.V(5).InfoS(\"Unable to look up PV info for PVC and PV\", \"PVC\", klog.KObj(pvc), \"PV\", klog.KRef(\"\", pvName))\n\t\t// If we can't fetch PV associated with PVC, may be it got deleted\n\t\t// or PVC was prebound to a PVC that hasn't been created yet.\n\t\t// fallback to using StorageClass for volume counting\n\t\treturn pl.getCSIDriverInfoFromSC(csiNode, pvc)\n\t}\n\n\tcsiSource := pv.Spec.PersistentVolumeSource.CSI\n\tif csiSource == nil {\n\t\t// We make a fast path for non-CSI volumes that aren't migratable\n\t\tif !pl.translator.IsPVMigratable(pv) {\n\t\t\treturn \"\", \"\"\n\t\t}\n\n\t\tpluginName, err := pl.translator.GetInTreePluginNameFromSpec(pv, nil)\n\t\tif err != nil {\n\t\t\tklog.V(5).InfoS(\"Unable to look up plugin name from PV spec\", \"err\", err)\n\t\t\treturn \"\", \"\"\n\t\t}\n\n\t\tif !isCSIMigrationOn(csiNode, pluginName) {\n\t\t\tklog.V(5).InfoS(\"CSI Migration of plugin is not enabled\", \"plugin\", pluginName)\n\t\t\treturn \"\", \"\"\n\t\t}\n\n\t\tcsiPV, err := pl.translator.TranslateInTreePVToCSI(pv)\n\t\tif err != nil {\n\t\t\tklog.V(5).InfoS(\"Unable to translate in-tree volume to CSI\", \"err\", err)\n\t\t\treturn \"\", \"\"\n\t\t}\n\n\t\tif csiPV.Spec.PersistentVolumeSource.CSI == nil {\n\t\t\tklog.V(5).InfoS(\"Unable to get a valid volume source for translated PV\", \"PV\", pvName)\n\t\t\treturn \"\", \"\"\n\t\t}\n\n\t\tcsiSource = csiPV.Spec.PersistentVolumeSource.CSI\n\t}\n\n\treturn csiSource.Driver, csiSource.VolumeHandle\n}","line":{"from":262,"to":315}} {"id":100010875,"name":"getCSIDriverInfoFromSC","signature":"func (pl *CSILimits) getCSIDriverInfoFromSC(csiNode *storagev1.CSINode, pvc *v1.PersistentVolumeClaim) (string, string)","file":"pkg/scheduler/framework/plugins/nodevolumelimits/csi.go","code":"// getCSIDriverInfoFromSC returns the CSI driver name and a random volume ID of a given PVC's StorageClass.\nfunc (pl *CSILimits) getCSIDriverInfoFromSC(csiNode *storagev1.CSINode, pvc *v1.PersistentVolumeClaim) (string, string) {\n\tnamespace := pvc.Namespace\n\tpvcName := pvc.Name\n\tscName := storagehelpers.GetPersistentVolumeClaimClass(pvc)\n\n\t// If StorageClass is not set or not found, then PVC must be using immediate binding mode\n\t// and hence it must be bound before scheduling. So it is safe to not count it.\n\tif scName == \"\" {\n\t\tklog.V(5).InfoS(\"PVC has no StorageClass\", \"PVC\", klog.KObj(pvc))\n\t\treturn \"\", \"\"\n\t}\n\n\tstorageClass, err := pl.scLister.Get(scName)\n\tif err != nil {\n\t\tklog.V(5).InfoS(\"Could not get StorageClass for PVC\", \"PVC\", klog.KObj(pvc), \"err\", err)\n\t\treturn \"\", \"\"\n\t}\n\n\t// We use random prefix to avoid conflict with volume IDs. If PVC is bound during the execution of the\n\t// predicate and there is another pod on the same node that uses same volume, then we will overcount\n\t// the volume and consider both volumes as different.\n\tvolumeHandle := fmt.Sprintf(\"%s-%s/%s\", pl.randomVolumeIDPrefix, namespace, pvcName)\n\n\tprovisioner := storageClass.Provisioner\n\tif pl.translator.IsMigratableIntreePluginByName(provisioner) {\n\t\tif !isCSIMigrationOn(csiNode, provisioner) {\n\t\t\tklog.V(5).InfoS(\"CSI Migration of provisioner is not enabled\", \"provisioner\", provisioner)\n\t\t\treturn \"\", \"\"\n\t\t}\n\n\t\tdriverName, err := pl.translator.GetCSINameFromInTreeName(provisioner)\n\t\tif err != nil {\n\t\t\tklog.V(5).InfoS(\"Unable to look up driver name from provisioner name\", \"provisioner\", provisioner, \"err\", err)\n\t\t\treturn \"\", \"\"\n\t\t}\n\t\treturn driverName, volumeHandle\n\t}\n\n\treturn provisioner, volumeHandle\n}","line":{"from":317,"to":357}} {"id":100010876,"name":"NewCSI","signature":"func NewCSI(_ runtime.Object, handle framework.Handle, fts feature.Features) (framework.Plugin, error)","file":"pkg/scheduler/framework/plugins/nodevolumelimits/csi.go","code":"// NewCSI initializes a new plugin and returns it.\nfunc NewCSI(_ runtime.Object, handle framework.Handle, fts feature.Features) (framework.Plugin, error) {\n\tinformerFactory := handle.SharedInformerFactory()\n\tpvLister := informerFactory.Core().V1().PersistentVolumes().Lister()\n\tpvcLister := informerFactory.Core().V1().PersistentVolumeClaims().Lister()\n\tcsiNodesLister := informerFactory.Storage().V1().CSINodes().Lister()\n\tscLister := informerFactory.Storage().V1().StorageClasses().Lister()\n\tcsiTranslator := csitrans.New()\n\n\treturn \u0026CSILimits{\n\t\tcsiNodeLister: csiNodesLister,\n\t\tpvLister: pvLister,\n\t\tpvcLister: pvcLister,\n\t\tscLister: scLister,\n\t\trandomVolumeIDPrefix: rand.String(32),\n\t\ttranslator: csiTranslator,\n\t}, nil\n}","line":{"from":359,"to":376}} {"id":100010877,"name":"getVolumeLimits","signature":"func getVolumeLimits(nodeInfo *framework.NodeInfo, csiNode *storagev1.CSINode) map[v1.ResourceName]int64","file":"pkg/scheduler/framework/plugins/nodevolumelimits/csi.go","code":"func getVolumeLimits(nodeInfo *framework.NodeInfo, csiNode *storagev1.CSINode) map[v1.ResourceName]int64 {\n\t// TODO: stop getting values from Node object in v1.18\n\tnodeVolumeLimits := volumeLimits(nodeInfo)\n\tif csiNode != nil {\n\t\tfor i := range csiNode.Spec.Drivers {\n\t\t\td := csiNode.Spec.Drivers[i]\n\t\t\tif d.Allocatable != nil \u0026\u0026 d.Allocatable.Count != nil {\n\t\t\t\t// TODO: drop GetCSIAttachLimitKey once we don't get values from Node object (v1.18)\n\t\t\t\tk := v1.ResourceName(volumeutil.GetCSIAttachLimitKey(d.Name))\n\t\t\t\tnodeVolumeLimits[k] = int64(*d.Allocatable.Count)\n\t\t\t}\n\t\t}\n\t}\n\treturn nodeVolumeLimits\n}","line":{"from":378,"to":392}} {"id":100010878,"name":"NewAzureDisk","signature":"func NewAzureDisk(_ runtime.Object, handle framework.Handle, fts feature.Features) (framework.Plugin, error)","file":"pkg/scheduler/framework/plugins/nodevolumelimits/non_csi.go","code":"// NewAzureDisk returns function that initializes a new plugin and returns it.\nfunc NewAzureDisk(_ runtime.Object, handle framework.Handle, fts feature.Features) (framework.Plugin, error) {\n\tinformerFactory := handle.SharedInformerFactory()\n\treturn newNonCSILimitsWithInformerFactory(azureDiskVolumeFilterType, informerFactory, fts), nil\n}","line":{"from":72,"to":76}} {"id":100010879,"name":"NewCinder","signature":"func NewCinder(_ runtime.Object, handle framework.Handle, fts feature.Features) (framework.Plugin, error)","file":"pkg/scheduler/framework/plugins/nodevolumelimits/non_csi.go","code":"// NewCinder returns function that initializes a new plugin and returns it.\nfunc NewCinder(_ runtime.Object, handle framework.Handle, fts feature.Features) (framework.Plugin, error) {\n\tinformerFactory := handle.SharedInformerFactory()\n\treturn newNonCSILimitsWithInformerFactory(cinderVolumeFilterType, informerFactory, fts), nil\n}","line":{"from":81,"to":85}} {"id":100010880,"name":"NewEBS","signature":"func NewEBS(_ runtime.Object, handle framework.Handle, fts feature.Features) (framework.Plugin, error)","file":"pkg/scheduler/framework/plugins/nodevolumelimits/non_csi.go","code":"// NewEBS returns function that initializes a new plugin and returns it.\nfunc NewEBS(_ runtime.Object, handle framework.Handle, fts feature.Features) (framework.Plugin, error) {\n\tinformerFactory := handle.SharedInformerFactory()\n\treturn newNonCSILimitsWithInformerFactory(ebsVolumeFilterType, informerFactory, fts), nil\n}","line":{"from":90,"to":94}} {"id":100010881,"name":"NewGCEPD","signature":"func NewGCEPD(_ runtime.Object, handle framework.Handle, fts feature.Features) (framework.Plugin, error)","file":"pkg/scheduler/framework/plugins/nodevolumelimits/non_csi.go","code":"// NewGCEPD returns function that initializes a new plugin and returns it.\nfunc NewGCEPD(_ runtime.Object, handle framework.Handle, fts feature.Features) (framework.Plugin, error) {\n\tinformerFactory := handle.SharedInformerFactory()\n\treturn newNonCSILimitsWithInformerFactory(gcePDVolumeFilterType, informerFactory, fts), nil\n}","line":{"from":99,"to":103}} {"id":100010882,"name":"newNonCSILimitsWithInformerFactory","signature":"func newNonCSILimitsWithInformerFactory(","file":"pkg/scheduler/framework/plugins/nodevolumelimits/non_csi.go","code":"// newNonCSILimitsWithInformerFactory returns a plugin with filter name and informer factory.\nfunc newNonCSILimitsWithInformerFactory(\n\tfilterName string,\n\tinformerFactory informers.SharedInformerFactory,\n\tfts feature.Features,\n) framework.Plugin {\n\tpvLister := informerFactory.Core().V1().PersistentVolumes().Lister()\n\tpvcLister := informerFactory.Core().V1().PersistentVolumeClaims().Lister()\n\tcsiNodesLister := informerFactory.Storage().V1().CSINodes().Lister()\n\tscLister := informerFactory.Storage().V1().StorageClasses().Lister()\n\n\treturn newNonCSILimits(filterName, csiNodesLister, scLister, pvLister, pvcLister, fts)\n}","line":{"from":125,"to":137}} {"id":100010883,"name":"newNonCSILimits","signature":"func newNonCSILimits(","file":"pkg/scheduler/framework/plugins/nodevolumelimits/non_csi.go","code":"// newNonCSILimits creates a plugin which evaluates whether a pod can fit based on the\n// number of volumes which match a filter that it requests, and those that are already present.\n//\n// DEPRECATED\n// All cloudprovider specific predicates defined here are deprecated in favour of CSI volume limit\n// predicate - MaxCSIVolumeCountPred.\n//\n// The predicate looks for both volumes used directly, as well as PVC volumes that are backed by relevant volume\n// types, counts the number of unique volumes, and rejects the new pod if it would place the total count over\n// the maximum.\nfunc newNonCSILimits(\n\tfilterName string,\n\tcsiNodeLister storagelisters.CSINodeLister,\n\tscLister storagelisters.StorageClassLister,\n\tpvLister corelisters.PersistentVolumeLister,\n\tpvcLister corelisters.PersistentVolumeClaimLister,\n\tfts feature.Features,\n) framework.Plugin {\n\tvar filter VolumeFilter\n\tvar volumeLimitKey v1.ResourceName\n\tvar name string\n\n\tswitch filterName {\n\tcase ebsVolumeFilterType:\n\t\tname = EBSName\n\t\tfilter = ebsVolumeFilter\n\t\tvolumeLimitKey = v1.ResourceName(volumeutil.EBSVolumeLimitKey)\n\tcase gcePDVolumeFilterType:\n\t\tname = GCEPDName\n\t\tfilter = gcePDVolumeFilter\n\t\tvolumeLimitKey = v1.ResourceName(volumeutil.GCEVolumeLimitKey)\n\tcase azureDiskVolumeFilterType:\n\t\tname = AzureDiskName\n\t\tfilter = azureDiskVolumeFilter\n\t\tvolumeLimitKey = v1.ResourceName(volumeutil.AzureVolumeLimitKey)\n\tcase cinderVolumeFilterType:\n\t\tname = CinderName\n\t\tfilter = cinderVolumeFilter\n\t\tvolumeLimitKey = v1.ResourceName(volumeutil.CinderVolumeLimitKey)\n\tdefault:\n\t\tklog.ErrorS(errors.New(\"wrong filterName\"), \"Cannot create nonCSILimits plugin\")\n\t\treturn nil\n\t}\n\tpl := \u0026nonCSILimits{\n\t\tname: name,\n\t\tfilter: filter,\n\t\tvolumeLimitKey: volumeLimitKey,\n\t\tmaxVolumeFunc: getMaxVolumeFunc(filterName),\n\t\tcsiNodeLister: csiNodeLister,\n\t\tpvLister: pvLister,\n\t\tpvcLister: pvcLister,\n\t\tscLister: scLister,\n\t\trandomVolumeIDPrefix: rand.String(32),\n\t}\n\n\treturn pl\n}","line":{"from":139,"to":195}} {"id":100010884,"name":"Name","signature":"func (pl *nonCSILimits) Name() string","file":"pkg/scheduler/framework/plugins/nodevolumelimits/non_csi.go","code":"// Name returns name of the plugin. It is used in logs, etc.\nfunc (pl *nonCSILimits) Name() string {\n\treturn pl.name\n}","line":{"from":197,"to":200}} {"id":100010885,"name":"EventsToRegister","signature":"func (pl *nonCSILimits) EventsToRegister() []framework.ClusterEvent","file":"pkg/scheduler/framework/plugins/nodevolumelimits/non_csi.go","code":"// EventsToRegister returns the possible events that may make a Pod\n// failed by this plugin schedulable.\nfunc (pl *nonCSILimits) EventsToRegister() []framework.ClusterEvent {\n\treturn []framework.ClusterEvent{\n\t\t{Resource: framework.Node, ActionType: framework.Add},\n\t\t{Resource: framework.Pod, ActionType: framework.Delete},\n\t}\n}","line":{"from":202,"to":209}} {"id":100010886,"name":"Filter","signature":"func (pl *nonCSILimits) Filter(ctx context.Context, _ *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status","file":"pkg/scheduler/framework/plugins/nodevolumelimits/non_csi.go","code":"// Filter invoked at the filter extension point.\nfunc (pl *nonCSILimits) Filter(ctx context.Context, _ *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status {\n\t// If a pod doesn't have any volume attached to it, the predicate will always be true.\n\t// Thus we make a fast path for it, to avoid unnecessary computations in this case.\n\tif len(pod.Spec.Volumes) == 0 {\n\t\treturn nil\n\t}\n\n\tnewVolumes := make(sets.String)\n\tif err := pl.filterVolumes(pod, true /* new pod */, newVolumes); err != nil {\n\t\treturn framework.AsStatus(err)\n\t}\n\n\t// quick return\n\tif len(newVolumes) == 0 {\n\t\treturn nil\n\t}\n\n\tnode := nodeInfo.Node()\n\tif node == nil {\n\t\treturn framework.NewStatus(framework.Error, \"node not found\")\n\t}\n\n\tvar csiNode *storage.CSINode\n\tvar err error\n\tif pl.csiNodeLister != nil {\n\t\tcsiNode, err = pl.csiNodeLister.Get(node.Name)\n\t\tif err != nil {\n\t\t\t// we don't fail here because the CSINode object is only necessary\n\t\t\t// for determining whether the migration is enabled or not\n\t\t\tklog.V(5).InfoS(\"Could not get a CSINode object for the node\", \"node\", klog.KObj(node), \"err\", err)\n\t\t}\n\t}\n\n\t// if a plugin has been migrated to a CSI driver, defer to the CSI predicate\n\tif pl.filter.IsMigrated(csiNode) {\n\t\treturn nil\n\t}\n\n\t// count unique volumes\n\texistingVolumes := make(sets.String)\n\tfor _, existingPod := range nodeInfo.Pods {\n\t\tif err := pl.filterVolumes(existingPod.Pod, false /* existing pod */, existingVolumes); err != nil {\n\t\t\treturn framework.AsStatus(err)\n\t\t}\n\t}\n\tnumExistingVolumes := len(existingVolumes)\n\n\t// filter out already-mounted volumes\n\tfor k := range existingVolumes {\n\t\tdelete(newVolumes, k)\n\t}\n\n\tnumNewVolumes := len(newVolumes)\n\tmaxAttachLimit := pl.maxVolumeFunc(node)\n\tvolumeLimits := volumeLimits(nodeInfo)\n\tif maxAttachLimitFromAllocatable, ok := volumeLimits[pl.volumeLimitKey]; ok {\n\t\tmaxAttachLimit = int(maxAttachLimitFromAllocatable)\n\t}\n\n\tif numExistingVolumes+numNewVolumes \u003e maxAttachLimit {\n\t\treturn framework.NewStatus(framework.Unschedulable, ErrReasonMaxVolumeCountExceeded)\n\t}\n\treturn nil\n}","line":{"from":211,"to":275}} {"id":100010887,"name":"filterVolumes","signature":"func (pl *nonCSILimits) filterVolumes(pod *v1.Pod, newPod bool, filteredVolumes sets.String) error","file":"pkg/scheduler/framework/plugins/nodevolumelimits/non_csi.go","code":"func (pl *nonCSILimits) filterVolumes(pod *v1.Pod, newPod bool, filteredVolumes sets.String) error {\n\tvolumes := pod.Spec.Volumes\n\tfor i := range volumes {\n\t\tvol := \u0026volumes[i]\n\t\tif id, ok := pl.filter.FilterVolume(vol); ok {\n\t\t\tfilteredVolumes.Insert(id)\n\t\t\tcontinue\n\t\t}\n\n\t\tpvcName := \"\"\n\t\tisEphemeral := false\n\t\tswitch {\n\t\tcase vol.PersistentVolumeClaim != nil:\n\t\t\tpvcName = vol.PersistentVolumeClaim.ClaimName\n\t\tcase vol.Ephemeral != nil:\n\t\t\t// Generic ephemeral inline volumes also use a PVC,\n\t\t\t// just with a computed name and certain ownership.\n\t\t\t// That is checked below once the pvc object is\n\t\t\t// retrieved.\n\t\t\tpvcName = ephemeral.VolumeClaimName(pod, vol)\n\t\t\tisEphemeral = true\n\t\tdefault:\n\t\t\tcontinue\n\t\t}\n\t\tif pvcName == \"\" {\n\t\t\treturn fmt.Errorf(\"PersistentVolumeClaim had no name\")\n\t\t}\n\n\t\t// Until we know real ID of the volume use namespace/pvcName as substitute\n\t\t// with a random prefix (calculated and stored inside 'c' during initialization)\n\t\t// to avoid conflicts with existing volume IDs.\n\t\tpvID := fmt.Sprintf(\"%s-%s/%s\", pl.randomVolumeIDPrefix, pod.Namespace, pvcName)\n\n\t\tpvc, err := pl.pvcLister.PersistentVolumeClaims(pod.Namespace).Get(pvcName)\n\t\tif err != nil {\n\t\t\tif newPod {\n\t\t\t\t// The PVC is required to proceed with\n\t\t\t\t// scheduling of a new pod because it cannot\n\t\t\t\t// run without it. Bail out immediately.\n\t\t\t\treturn fmt.Errorf(\"looking up PVC %s/%s: %v\", pod.Namespace, pvcName, err)\n\t\t\t}\n\t\t\t// If the PVC is invalid, we don't count the volume because\n\t\t\t// there's no guarantee that it belongs to the running predicate.\n\t\t\tklog.V(4).InfoS(\"Unable to look up PVC info, assuming PVC doesn't match predicate when counting limits\", \"pod\", klog.KObj(pod), \"PVC\", klog.KRef(pod.Namespace, pvcName), \"err\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\t// The PVC for an ephemeral volume must be owned by the pod.\n\t\tif isEphemeral {\n\t\t\tif err := ephemeral.VolumeIsForPod(pod, pvc); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tpvName := pvc.Spec.VolumeName\n\t\tif pvName == \"\" {\n\t\t\t// PVC is not bound. It was either deleted and created again or\n\t\t\t// it was forcefully unbound by admin. The pod can still use the\n\t\t\t// original PV where it was bound to, so we count the volume if\n\t\t\t// it belongs to the running predicate.\n\t\t\tif pl.matchProvisioner(pvc) {\n\t\t\t\tklog.V(4).InfoS(\"PVC is not bound, assuming PVC matches predicate when counting limits\", \"pod\", klog.KObj(pod), \"PVC\", klog.KRef(pod.Namespace, pvcName))\n\t\t\t\tfilteredVolumes.Insert(pvID)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tpv, err := pl.pvLister.Get(pvName)\n\t\tif err != nil {\n\t\t\t// If the PV is invalid and PVC belongs to the running predicate,\n\t\t\t// log the error and count the PV towards the PV limit.\n\t\t\tif pl.matchProvisioner(pvc) {\n\t\t\t\tklog.V(4).InfoS(\"Unable to look up PV, assuming PV matches predicate when counting limits\", \"pod\", klog.KObj(pod), \"PVC\", klog.KRef(pod.Namespace, pvcName), \"PV\", klog.KRef(\"\", pvName), \"err\", err)\n\t\t\t\tfilteredVolumes.Insert(pvID)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif id, ok := pl.filter.FilterPersistentVolume(pv); ok {\n\t\t\tfilteredVolumes.Insert(id)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":277,"to":361}} {"id":100010888,"name":"matchProvisioner","signature":"func (pl *nonCSILimits) matchProvisioner(pvc *v1.PersistentVolumeClaim) bool","file":"pkg/scheduler/framework/plugins/nodevolumelimits/non_csi.go","code":"// matchProvisioner helps identify if the given PVC belongs to the running predicate.\nfunc (pl *nonCSILimits) matchProvisioner(pvc *v1.PersistentVolumeClaim) bool {\n\tif pvc.Spec.StorageClassName == nil {\n\t\treturn false\n\t}\n\n\tstorageClass, err := pl.scLister.Get(*pvc.Spec.StorageClassName)\n\tif err != nil || storageClass == nil {\n\t\treturn false\n\t}\n\n\treturn pl.filter.MatchProvisioner(storageClass)\n}","line":{"from":363,"to":375}} {"id":100010889,"name":"getMaxVolLimitFromEnv","signature":"func getMaxVolLimitFromEnv() int","file":"pkg/scheduler/framework/plugins/nodevolumelimits/non_csi.go","code":"// getMaxVolLimitFromEnv checks the max PD volumes environment variable, otherwise returning a default value.\nfunc getMaxVolLimitFromEnv() int {\n\tif rawMaxVols := os.Getenv(KubeMaxPDVols); rawMaxVols != \"\" {\n\t\tif parsedMaxVols, err := strconv.Atoi(rawMaxVols); err != nil {\n\t\t\tklog.ErrorS(err, \"Unable to parse maximum PD volumes value, using default\")\n\t\t} else if parsedMaxVols \u003c= 0 {\n\t\t\tklog.ErrorS(errors.New(\"maximum PD volumes is negative\"), \"Unable to parse maximum PD volumes value, using default\")\n\t\t} else {\n\t\t\treturn parsedMaxVols\n\t\t}\n\t}\n\n\treturn -1\n}","line":{"from":377,"to":390}} {"id":100010890,"name":"getMaxVolumeFunc","signature":"func getMaxVolumeFunc(filterName string) func(node *v1.Node) int","file":"pkg/scheduler/framework/plugins/nodevolumelimits/non_csi.go","code":"func getMaxVolumeFunc(filterName string) func(node *v1.Node) int {\n\treturn func(node *v1.Node) int {\n\t\tmaxVolumesFromEnv := getMaxVolLimitFromEnv()\n\t\tif maxVolumesFromEnv \u003e 0 {\n\t\t\treturn maxVolumesFromEnv\n\t\t}\n\n\t\tvar nodeInstanceType string\n\t\tfor k, v := range node.ObjectMeta.Labels {\n\t\t\tif k == v1.LabelInstanceType || k == v1.LabelInstanceTypeStable {\n\t\t\t\tnodeInstanceType = v\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tswitch filterName {\n\t\tcase ebsVolumeFilterType:\n\t\t\treturn getMaxEBSVolume(nodeInstanceType)\n\t\tcase gcePDVolumeFilterType:\n\t\t\treturn defaultMaxGCEPDVolumes\n\t\tcase azureDiskVolumeFilterType:\n\t\t\treturn defaultMaxAzureDiskVolumes\n\t\tcase cinderVolumeFilterType:\n\t\t\treturn volumeutil.DefaultMaxCinderVolumes\n\t\tdefault:\n\t\t\treturn -1\n\t\t}\n\t}\n}","line":{"from":504,"to":531}} {"id":100010891,"name":"getMaxEBSVolume","signature":"func getMaxEBSVolume(nodeInstanceType string) int","file":"pkg/scheduler/framework/plugins/nodevolumelimits/non_csi.go","code":"func getMaxEBSVolume(nodeInstanceType string) int {\n\tif ok, _ := regexp.MatchString(volumeutil.EBSNitroLimitRegex, nodeInstanceType); ok {\n\t\treturn volumeutil.DefaultMaxEBSNitroVolumeLimit\n\t}\n\treturn volumeutil.DefaultMaxEBSVolumes\n}","line":{"from":533,"to":538}} {"id":100010892,"name":"isCSIMigrationOn","signature":"func isCSIMigrationOn(csiNode *storagev1.CSINode, pluginName string) bool","file":"pkg/scheduler/framework/plugins/nodevolumelimits/utils.go","code":"// isCSIMigrationOn returns a boolean value indicating whether\n// the CSI migration has been enabled for a particular storage plugin.\nfunc isCSIMigrationOn(csiNode *storagev1.CSINode, pluginName string) bool {\n\tif csiNode == nil || len(pluginName) == 0 {\n\t\treturn false\n\t}\n\n\t// In-tree storage to CSI driver migration feature should be enabled,\n\t// along with the plugin-specific one\n\tswitch pluginName {\n\tcase csilibplugins.AWSEBSInTreePluginName:\n\t\treturn true\n\tcase csilibplugins.PortworxVolumePluginName:\n\t\tif !utilfeature.DefaultFeatureGate.Enabled(features.CSIMigrationPortworx) {\n\t\t\treturn false\n\t\t}\n\tcase csilibplugins.GCEPDInTreePluginName:\n\t\tif !utilfeature.DefaultFeatureGate.Enabled(features.CSIMigrationGCE) {\n\t\t\treturn false\n\t\t}\n\tcase csilibplugins.AzureDiskInTreePluginName:\n\t\treturn true\n\tcase csilibplugins.CinderInTreePluginName:\n\t\treturn true\n\tcase csilibplugins.RBDVolumePluginName:\n\t\tif !utilfeature.DefaultFeatureGate.Enabled(features.CSIMigrationRBD) {\n\t\t\treturn false\n\t\t}\n\tdefault:\n\t\treturn false\n\t}\n\n\t// The plugin name should be listed in the CSINode object annotation.\n\t// This indicates that the plugin has been migrated to a CSI driver in the node.\n\tcsiNodeAnn := csiNode.GetAnnotations()\n\tif csiNodeAnn == nil {\n\t\treturn false\n\t}\n\n\tvar mpaSet sets.String\n\tmpa := csiNodeAnn[v1.MigratedPluginsAnnotationKey]\n\tif len(mpa) == 0 {\n\t\tmpaSet = sets.NewString()\n\t} else {\n\t\ttok := strings.Split(mpa, \",\")\n\t\tmpaSet = sets.NewString(tok...)\n\t}\n\n\treturn mpaSet.Has(pluginName)\n}","line":{"from":32,"to":81}} {"id":100010893,"name":"volumeLimits","signature":"func volumeLimits(n *framework.NodeInfo) map[v1.ResourceName]int64","file":"pkg/scheduler/framework/plugins/nodevolumelimits/utils.go","code":"// volumeLimits returns volume limits associated with the node.\nfunc volumeLimits(n *framework.NodeInfo) map[v1.ResourceName]int64 {\n\tvolumeLimits := map[v1.ResourceName]int64{}\n\tfor k, v := range n.Allocatable.ScalarResources {\n\t\tif v1helper.IsAttachableVolumeResourceName(k) {\n\t\t\tvolumeLimits[k] = v\n\t\t}\n\t}\n\treturn volumeLimits\n}","line":{"from":83,"to":92}} {"id":100010894,"name":"matchNodeInclusionPolicies","signature":"func (tsc *topologySpreadConstraint) matchNodeInclusionPolicies(pod *v1.Pod, node *v1.Node, require nodeaffinity.RequiredNodeAffinity) bool","file":"pkg/scheduler/framework/plugins/podtopologyspread/common.go","code":"func (tsc *topologySpreadConstraint) matchNodeInclusionPolicies(pod *v1.Pod, node *v1.Node, require nodeaffinity.RequiredNodeAffinity) bool {\n\tif tsc.NodeAffinityPolicy == v1.NodeInclusionPolicyHonor {\n\t\t// We ignore parsing errors here for backwards compatibility.\n\t\tif match, _ := require.Match(node); !match {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif tsc.NodeTaintsPolicy == v1.NodeInclusionPolicyHonor {\n\t\tif _, untolerated := v1helper.FindMatchingUntoleratedTaint(node.Spec.Taints, pod.Spec.Tolerations, helper.DoNotScheduleTaintsFilterFunc()); untolerated {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":46,"to":60}} {"id":100010895,"name":"buildDefaultConstraints","signature":"func (pl *PodTopologySpread) buildDefaultConstraints(p *v1.Pod, action v1.UnsatisfiableConstraintAction) ([]topologySpreadConstraint, error)","file":"pkg/scheduler/framework/plugins/podtopologyspread/common.go","code":"// buildDefaultConstraints builds the constraints for a pod using\n// .DefaultConstraints and the selectors from the services, replication\n// controllers, replica sets and stateful sets that match the pod.\nfunc (pl *PodTopologySpread) buildDefaultConstraints(p *v1.Pod, action v1.UnsatisfiableConstraintAction) ([]topologySpreadConstraint, error) {\n\tconstraints, err := pl.filterTopologySpreadConstraints(pl.defaultConstraints, p.Labels, action)\n\tif err != nil || len(constraints) == 0 {\n\t\treturn nil, err\n\t}\n\tselector := helper.DefaultSelector(p, pl.services, pl.replicationCtrls, pl.replicaSets, pl.statefulSets)\n\tif selector.Empty() {\n\t\treturn nil, nil\n\t}\n\tfor i := range constraints {\n\t\tconstraints[i].Selector = selector\n\t}\n\treturn constraints, nil\n}","line":{"from":62,"to":78}} {"id":100010896,"name":"nodeLabelsMatchSpreadConstraints","signature":"func nodeLabelsMatchSpreadConstraints(nodeLabels map[string]string, constraints []topologySpreadConstraint) bool","file":"pkg/scheduler/framework/plugins/podtopologyspread/common.go","code":"// nodeLabelsMatchSpreadConstraints checks if ALL topology keys in spread Constraints are present in node labels.\nfunc nodeLabelsMatchSpreadConstraints(nodeLabels map[string]string, constraints []topologySpreadConstraint) bool {\n\tfor _, c := range constraints {\n\t\tif _, ok := nodeLabels[c.TopologyKey]; !ok {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":80,"to":88}} {"id":100010897,"name":"filterTopologySpreadConstraints","signature":"func (pl *PodTopologySpread) filterTopologySpreadConstraints(constraints []v1.TopologySpreadConstraint, podLabels map[string]string, action v1.UnsatisfiableConstraintAction) ([]topologySpreadConstraint, error)","file":"pkg/scheduler/framework/plugins/podtopologyspread/common.go","code":"func (pl *PodTopologySpread) filterTopologySpreadConstraints(constraints []v1.TopologySpreadConstraint, podLabels map[string]string, action v1.UnsatisfiableConstraintAction) ([]topologySpreadConstraint, error) {\n\tvar result []topologySpreadConstraint\n\tfor _, c := range constraints {\n\t\tif c.WhenUnsatisfiable == action {\n\t\t\tselector, err := metav1.LabelSelectorAsSelector(c.LabelSelector)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif pl.enableMatchLabelKeysInPodTopologySpread \u0026\u0026 len(c.MatchLabelKeys) \u003e 0 {\n\t\t\t\tmatchLabels := make(labels.Set)\n\t\t\t\tfor _, labelKey := range c.MatchLabelKeys {\n\t\t\t\t\tif value, ok := podLabels[labelKey]; ok {\n\t\t\t\t\t\tmatchLabels[labelKey] = value\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif len(matchLabels) \u003e 0 {\n\t\t\t\t\tselector = mergeLabelSetWithSelector(matchLabels, selector)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttsc := topologySpreadConstraint{\n\t\t\t\tMaxSkew: c.MaxSkew,\n\t\t\t\tTopologyKey: c.TopologyKey,\n\t\t\t\tSelector: selector,\n\t\t\t\tMinDomains: 1, // If MinDomains is nil, we treat MinDomains as 1.\n\t\t\t\tNodeAffinityPolicy: v1.NodeInclusionPolicyHonor, // If NodeAffinityPolicy is nil, we treat NodeAffinityPolicy as \"Honor\".\n\t\t\t\tNodeTaintsPolicy: v1.NodeInclusionPolicyIgnore, // If NodeTaintsPolicy is nil, we treat NodeTaintsPolicy as \"Ignore\".\n\t\t\t}\n\t\t\tif pl.enableMinDomainsInPodTopologySpread \u0026\u0026 c.MinDomains != nil {\n\t\t\t\ttsc.MinDomains = *c.MinDomains\n\t\t\t}\n\t\t\tif pl.enableNodeInclusionPolicyInPodTopologySpread {\n\t\t\t\tif c.NodeAffinityPolicy != nil {\n\t\t\t\t\ttsc.NodeAffinityPolicy = *c.NodeAffinityPolicy\n\t\t\t\t}\n\t\t\t\tif c.NodeTaintsPolicy != nil {\n\t\t\t\t\ttsc.NodeTaintsPolicy = *c.NodeTaintsPolicy\n\t\t\t\t}\n\t\t\t}\n\t\t\tresult = append(result, tsc)\n\t\t}\n\t}\n\treturn result, nil\n}","line":{"from":90,"to":134}} {"id":100010898,"name":"mergeLabelSetWithSelector","signature":"func mergeLabelSetWithSelector(matchLabels labels.Set, s labels.Selector) labels.Selector","file":"pkg/scheduler/framework/plugins/podtopologyspread/common.go","code":"func mergeLabelSetWithSelector(matchLabels labels.Set, s labels.Selector) labels.Selector {\n\tmergedSelector := labels.SelectorFromSet(matchLabels)\n\n\trequirements, ok := s.Requirements()\n\tif !ok {\n\t\treturn s\n\t}\n\n\tfor _, r := range requirements {\n\t\tmergedSelector = mergedSelector.Add(r)\n\t}\n\n\treturn mergedSelector\n}","line":{"from":136,"to":149}} {"id":100010899,"name":"countPodsMatchSelector","signature":"func countPodsMatchSelector(podInfos []*framework.PodInfo, selector labels.Selector, ns string) int","file":"pkg/scheduler/framework/plugins/podtopologyspread/common.go","code":"func countPodsMatchSelector(podInfos []*framework.PodInfo, selector labels.Selector, ns string) int {\n\tif selector.Empty() {\n\t\treturn 0\n\t}\n\tcount := 0\n\tfor _, p := range podInfos {\n\t\t// Bypass terminating Pod (see #87621).\n\t\tif p.Pod.DeletionTimestamp != nil || p.Pod.Namespace != ns {\n\t\t\tcontinue\n\t\t}\n\t\tif selector.Matches(labels.Set(p.Pod.Labels)) {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count\n}","line":{"from":151,"to":166}} {"id":100010900,"name":"minMatchNum","signature":"func (s *preFilterState) minMatchNum(tpKey string, minDomains int32, enableMinDomainsInPodTopologySpread bool) (int, error)","file":"pkg/scheduler/framework/plugins/podtopologyspread/filtering.go","code":"// minMatchNum returns the global minimum for the calculation of skew while taking MinDomains into account.\nfunc (s *preFilterState) minMatchNum(tpKey string, minDomains int32, enableMinDomainsInPodTopologySpread bool) (int, error) {\n\tpaths, ok := s.TpKeyToCriticalPaths[tpKey]\n\tif !ok {\n\t\treturn 0, fmt.Errorf(\"failed to retrieve path by topology key\")\n\t}\n\n\tminMatchNum := paths[0].MatchNum\n\tif !enableMinDomainsInPodTopologySpread {\n\t\treturn minMatchNum, nil\n\t}\n\n\tdomainsNum, ok := s.TpKeyToDomainsNum[tpKey]\n\tif !ok {\n\t\treturn 0, fmt.Errorf(\"failed to retrieve the number of domains by topology key\")\n\t}\n\n\tif domainsNum \u003c int(minDomains) {\n\t\t// When the number of eligible domains with matching topology keys is less than `minDomains`,\n\t\t// it treats \"global minimum\" as 0.\n\t\tminMatchNum = 0\n\t}\n\n\treturn minMatchNum, nil\n}","line":{"from":53,"to":77}} {"id":100010901,"name":"Clone","signature":"func (s *preFilterState) Clone() framework.StateData","file":"pkg/scheduler/framework/plugins/podtopologyspread/filtering.go","code":"// Clone makes a copy of the given state.\nfunc (s *preFilterState) Clone() framework.StateData {\n\tif s == nil {\n\t\treturn nil\n\t}\n\tcopy := preFilterState{\n\t\t// Constraints are shared because they don't change.\n\t\tConstraints: s.Constraints,\n\t\tTpKeyToCriticalPaths: make(map[string]*criticalPaths, len(s.TpKeyToCriticalPaths)),\n\t\t// The number of domains does not change as a result of AddPod/RemovePod methods on PreFilter Extensions\n\t\tTpKeyToDomainsNum: s.TpKeyToDomainsNum,\n\t\tTpPairToMatchNum: make(map[topologyPair]int, len(s.TpPairToMatchNum)),\n\t}\n\tfor tpKey, paths := range s.TpKeyToCriticalPaths {\n\t\tcopy.TpKeyToCriticalPaths[tpKey] = \u0026criticalPaths{paths[0], paths[1]}\n\t}\n\tfor tpPair, matchNum := range s.TpPairToMatchNum {\n\t\tcopyPair := topologyPair{key: tpPair.key, value: tpPair.value}\n\t\tcopy.TpPairToMatchNum[copyPair] = matchNum\n\t}\n\treturn \u0026copy\n}","line":{"from":79,"to":100}} {"id":100010902,"name":"newCriticalPaths","signature":"func newCriticalPaths() *criticalPaths","file":"pkg/scheduler/framework/plugins/podtopologyspread/filtering.go","code":"func newCriticalPaths() *criticalPaths {\n\treturn \u0026criticalPaths{{MatchNum: math.MaxInt32}, {MatchNum: math.MaxInt32}}\n}","line":{"from":116,"to":118}} {"id":100010903,"name":"update","signature":"func (p *criticalPaths) update(tpVal string, num int)","file":"pkg/scheduler/framework/plugins/podtopologyspread/filtering.go","code":"func (p *criticalPaths) update(tpVal string, num int) {\n\t// first verify if `tpVal` exists or not\n\ti := -1\n\tif tpVal == p[0].TopologyValue {\n\t\ti = 0\n\t} else if tpVal == p[1].TopologyValue {\n\t\ti = 1\n\t}\n\n\tif i \u003e= 0 {\n\t\t// `tpVal` exists\n\t\tp[i].MatchNum = num\n\t\tif p[0].MatchNum \u003e p[1].MatchNum {\n\t\t\t// swap paths[0] and paths[1]\n\t\t\tp[0], p[1] = p[1], p[0]\n\t\t}\n\t} else {\n\t\t// `tpVal` doesn't exist\n\t\tif num \u003c p[0].MatchNum {\n\t\t\t// update paths[1] with paths[0]\n\t\t\tp[1] = p[0]\n\t\t\t// update paths[0]\n\t\t\tp[0].TopologyValue, p[0].MatchNum = tpVal, num\n\t\t} else if num \u003c p[1].MatchNum {\n\t\t\t// update paths[1]\n\t\t\tp[1].TopologyValue, p[1].MatchNum = tpVal, num\n\t\t}\n\t}\n}","line":{"from":120,"to":148}} {"id":100010904,"name":"PreFilter","signature":"func (pl *PodTopologySpread) PreFilter(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod) (*framework.PreFilterResult, *framework.Status)","file":"pkg/scheduler/framework/plugins/podtopologyspread/filtering.go","code":"// PreFilter invoked at the prefilter extension point.\nfunc (pl *PodTopologySpread) PreFilter(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod) (*framework.PreFilterResult, *framework.Status) {\n\ts, err := pl.calPreFilterState(ctx, pod)\n\tif err != nil {\n\t\treturn nil, framework.AsStatus(err)\n\t}\n\tcycleState.Write(preFilterStateKey, s)\n\treturn nil, nil\n}","line":{"from":150,"to":158}} {"id":100010905,"name":"PreFilterExtensions","signature":"func (pl *PodTopologySpread) PreFilterExtensions() framework.PreFilterExtensions","file":"pkg/scheduler/framework/plugins/podtopologyspread/filtering.go","code":"// PreFilterExtensions returns prefilter extensions, pod add and remove.\nfunc (pl *PodTopologySpread) PreFilterExtensions() framework.PreFilterExtensions {\n\treturn pl\n}","line":{"from":160,"to":163}} {"id":100010906,"name":"AddPod","signature":"func (pl *PodTopologySpread) AddPod(ctx context.Context, cycleState *framework.CycleState, podToSchedule *v1.Pod, podInfoToAdd *framework.PodInfo, nodeInfo *framework.NodeInfo) *framework.Status","file":"pkg/scheduler/framework/plugins/podtopologyspread/filtering.go","code":"// AddPod from pre-computed data in cycleState.\nfunc (pl *PodTopologySpread) AddPod(ctx context.Context, cycleState *framework.CycleState, podToSchedule *v1.Pod, podInfoToAdd *framework.PodInfo, nodeInfo *framework.NodeInfo) *framework.Status {\n\ts, err := getPreFilterState(cycleState)\n\tif err != nil {\n\t\treturn framework.AsStatus(err)\n\t}\n\n\tpl.updateWithPod(s, podInfoToAdd.Pod, podToSchedule, nodeInfo.Node(), 1)\n\treturn nil\n}","line":{"from":165,"to":174}} {"id":100010907,"name":"RemovePod","signature":"func (pl *PodTopologySpread) RemovePod(ctx context.Context, cycleState *framework.CycleState, podToSchedule *v1.Pod, podInfoToRemove *framework.PodInfo, nodeInfo *framework.NodeInfo) *framework.Status","file":"pkg/scheduler/framework/plugins/podtopologyspread/filtering.go","code":"// RemovePod from pre-computed data in cycleState.\nfunc (pl *PodTopologySpread) RemovePod(ctx context.Context, cycleState *framework.CycleState, podToSchedule *v1.Pod, podInfoToRemove *framework.PodInfo, nodeInfo *framework.NodeInfo) *framework.Status {\n\ts, err := getPreFilterState(cycleState)\n\tif err != nil {\n\t\treturn framework.AsStatus(err)\n\t}\n\n\tpl.updateWithPod(s, podInfoToRemove.Pod, podToSchedule, nodeInfo.Node(), -1)\n\treturn nil\n}","line":{"from":176,"to":185}} {"id":100010908,"name":"updateWithPod","signature":"func (pl *PodTopologySpread) updateWithPod(s *preFilterState, updatedPod, preemptorPod *v1.Pod, node *v1.Node, delta int)","file":"pkg/scheduler/framework/plugins/podtopologyspread/filtering.go","code":"func (pl *PodTopologySpread) updateWithPod(s *preFilterState, updatedPod, preemptorPod *v1.Pod, node *v1.Node, delta int) {\n\tif s == nil || updatedPod.Namespace != preemptorPod.Namespace || node == nil {\n\t\treturn\n\t}\n\tif !nodeLabelsMatchSpreadConstraints(node.Labels, s.Constraints) {\n\t\treturn\n\t}\n\n\trequiredSchedulingTerm := nodeaffinity.GetRequiredNodeAffinity(preemptorPod)\n\tif !pl.enableNodeInclusionPolicyInPodTopologySpread {\n\t\t// spreading is applied to nodes that pass those filters.\n\t\t// Ignore parsing errors for backwards compatibility.\n\t\tif match, _ := requiredSchedulingTerm.Match(node); !match {\n\t\t\treturn\n\t\t}\n\t}\n\n\tpodLabelSet := labels.Set(updatedPod.Labels)\n\tfor _, constraint := range s.Constraints {\n\t\tif !constraint.Selector.Matches(podLabelSet) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif pl.enableNodeInclusionPolicyInPodTopologySpread \u0026\u0026\n\t\t\t!constraint.matchNodeInclusionPolicies(preemptorPod, node, requiredSchedulingTerm) {\n\t\t\tcontinue\n\t\t}\n\n\t\tk, v := constraint.TopologyKey, node.Labels[constraint.TopologyKey]\n\t\tpair := topologyPair{key: k, value: v}\n\t\ts.TpPairToMatchNum[pair] += delta\n\t\ts.TpKeyToCriticalPaths[k].update(v, s.TpPairToMatchNum[pair])\n\t}\n}","line":{"from":187,"to":220}} {"id":100010909,"name":"getPreFilterState","signature":"func getPreFilterState(cycleState *framework.CycleState) (*preFilterState, error)","file":"pkg/scheduler/framework/plugins/podtopologyspread/filtering.go","code":"// getPreFilterState fetches a pre-computed preFilterState.\nfunc getPreFilterState(cycleState *framework.CycleState) (*preFilterState, error) {\n\tc, err := cycleState.Read(preFilterStateKey)\n\tif err != nil {\n\t\t// preFilterState doesn't exist, likely PreFilter wasn't invoked.\n\t\treturn nil, fmt.Errorf(\"reading %q from cycleState: %w\", preFilterStateKey, err)\n\t}\n\n\ts, ok := c.(*preFilterState)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"%+v convert to podtopologyspread.preFilterState error\", c)\n\t}\n\treturn s, nil\n}","line":{"from":222,"to":235}} {"id":100010910,"name":"calPreFilterState","signature":"func (pl *PodTopologySpread) calPreFilterState(ctx context.Context, pod *v1.Pod) (*preFilterState, error)","file":"pkg/scheduler/framework/plugins/podtopologyspread/filtering.go","code":"// calPreFilterState computes preFilterState describing how pods are spread on topologies.\nfunc (pl *PodTopologySpread) calPreFilterState(ctx context.Context, pod *v1.Pod) (*preFilterState, error) {\n\tallNodes, err := pl.sharedLister.NodeInfos().List()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"listing NodeInfos: %w\", err)\n\t}\n\tvar constraints []topologySpreadConstraint\n\tif len(pod.Spec.TopologySpreadConstraints) \u003e 0 {\n\t\t// We have feature gating in APIServer to strip the spec\n\t\t// so don't need to re-check feature gate, just check length of Constraints.\n\t\tconstraints, err = pl.filterTopologySpreadConstraints(\n\t\t\tpod.Spec.TopologySpreadConstraints,\n\t\t\tpod.Labels,\n\t\t\tv1.DoNotSchedule,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"obtaining pod's hard topology spread constraints: %w\", err)\n\t\t}\n\t} else {\n\t\tconstraints, err = pl.buildDefaultConstraints(pod, v1.DoNotSchedule)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"setting default hard topology spread constraints: %w\", err)\n\t\t}\n\t}\n\tif len(constraints) == 0 {\n\t\treturn \u0026preFilterState{}, nil\n\t}\n\n\ts := preFilterState{\n\t\tConstraints: constraints,\n\t\tTpKeyToCriticalPaths: make(map[string]*criticalPaths, len(constraints)),\n\t\tTpPairToMatchNum: make(map[topologyPair]int, sizeHeuristic(len(allNodes), constraints)),\n\t}\n\n\ttpCountsByNode := make([]map[topologyPair]int, len(allNodes))\n\trequiredNodeAffinity := nodeaffinity.GetRequiredNodeAffinity(pod)\n\tprocessNode := func(i int) {\n\t\tnodeInfo := allNodes[i]\n\t\tnode := nodeInfo.Node()\n\t\tif node == nil {\n\t\t\tklog.ErrorS(nil, \"Node not found\")\n\t\t\treturn\n\t\t}\n\n\t\tif !pl.enableNodeInclusionPolicyInPodTopologySpread {\n\t\t\t// spreading is applied to nodes that pass those filters.\n\t\t\t// Ignore parsing errors for backwards compatibility.\n\t\t\tif match, _ := requiredNodeAffinity.Match(node); !match {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t// Ensure current node's labels contains all topologyKeys in 'Constraints'.\n\t\tif !nodeLabelsMatchSpreadConstraints(node.Labels, constraints) {\n\t\t\treturn\n\t\t}\n\n\t\ttpCounts := make(map[topologyPair]int, len(constraints))\n\t\tfor _, c := range constraints {\n\t\t\tif pl.enableNodeInclusionPolicyInPodTopologySpread \u0026\u0026\n\t\t\t\t!c.matchNodeInclusionPolicies(pod, node, requiredNodeAffinity) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tpair := topologyPair{key: c.TopologyKey, value: node.Labels[c.TopologyKey]}\n\t\t\tcount := countPodsMatchSelector(nodeInfo.Pods, c.Selector, pod.Namespace)\n\t\t\ttpCounts[pair] = count\n\t\t}\n\t\ttpCountsByNode[i] = tpCounts\n\t}\n\tpl.parallelizer.Until(ctx, len(allNodes), processNode, pl.Name())\n\n\tfor _, tpCounts := range tpCountsByNode {\n\t\tfor tp, count := range tpCounts {\n\t\t\ts.TpPairToMatchNum[tp] += count\n\t\t}\n\t}\n\tif pl.enableMinDomainsInPodTopologySpread {\n\t\ts.TpKeyToDomainsNum = make(map[string]int, len(constraints))\n\t\tfor tp := range s.TpPairToMatchNum {\n\t\t\ts.TpKeyToDomainsNum[tp.key]++\n\t\t}\n\t}\n\n\t// calculate min match for each topology pair\n\tfor i := 0; i \u003c len(constraints); i++ {\n\t\tkey := constraints[i].TopologyKey\n\t\ts.TpKeyToCriticalPaths[key] = newCriticalPaths()\n\t}\n\tfor pair, num := range s.TpPairToMatchNum {\n\t\ts.TpKeyToCriticalPaths[pair.key].update(pair.value, num)\n\t}\n\n\treturn \u0026s, nil\n}","line":{"from":237,"to":331}} {"id":100010911,"name":"Filter","signature":"func (pl *PodTopologySpread) Filter(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status","file":"pkg/scheduler/framework/plugins/podtopologyspread/filtering.go","code":"// Filter invoked at the filter extension point.\nfunc (pl *PodTopologySpread) Filter(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status {\n\tnode := nodeInfo.Node()\n\tif node == nil {\n\t\treturn framework.AsStatus(fmt.Errorf(\"node not found\"))\n\t}\n\n\ts, err := getPreFilterState(cycleState)\n\tif err != nil {\n\t\treturn framework.AsStatus(err)\n\t}\n\n\t// However, \"empty\" preFilterState is legit which tolerates every toSchedule Pod.\n\tif len(s.Constraints) == 0 {\n\t\treturn nil\n\t}\n\n\tpodLabelSet := labels.Set(pod.Labels)\n\tfor _, c := range s.Constraints {\n\t\ttpKey := c.TopologyKey\n\t\ttpVal, ok := node.Labels[c.TopologyKey]\n\t\tif !ok {\n\t\t\tklog.V(5).InfoS(\"Node doesn't have required label\", \"node\", klog.KObj(node), \"label\", tpKey)\n\t\t\treturn framework.NewStatus(framework.UnschedulableAndUnresolvable, ErrReasonNodeLabelNotMatch)\n\t\t}\n\n\t\t// judging criteria:\n\t\t// 'existing matching num' + 'if self-match (1 or 0)' - 'global minimum' \u003c= 'maxSkew'\n\t\tminMatchNum, err := s.minMatchNum(tpKey, c.MinDomains, pl.enableMinDomainsInPodTopologySpread)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Internal error occurred while retrieving value precalculated in PreFilter\", \"topologyKey\", tpKey, \"paths\", s.TpKeyToCriticalPaths)\n\t\t\tcontinue\n\t\t}\n\n\t\tselfMatchNum := 0\n\t\tif c.Selector.Matches(podLabelSet) {\n\t\t\tselfMatchNum = 1\n\t\t}\n\n\t\tpair := topologyPair{key: tpKey, value: tpVal}\n\t\tmatchNum := 0\n\t\tif tpCount, ok := s.TpPairToMatchNum[pair]; ok {\n\t\t\tmatchNum = tpCount\n\t\t}\n\t\tskew := matchNum + selfMatchNum - minMatchNum\n\t\tif skew \u003e int(c.MaxSkew) {\n\t\t\tklog.V(5).InfoS(\"Node failed spreadConstraint: matchNum + selfMatchNum - minMatchNum \u003e maxSkew\", \"node\", klog.KObj(node), \"topologyKey\", tpKey, \"matchNum\", matchNum, \"selfMatchNum\", selfMatchNum, \"minMatchNum\", minMatchNum, \"maxSkew\", c.MaxSkew)\n\t\t\treturn framework.NewStatus(framework.Unschedulable, ErrReasonConstraintsNotMatch)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":333,"to":385}} {"id":100010912,"name":"sizeHeuristic","signature":"func sizeHeuristic(nodes int, constraints []topologySpreadConstraint) int","file":"pkg/scheduler/framework/plugins/podtopologyspread/filtering.go","code":"func sizeHeuristic(nodes int, constraints []topologySpreadConstraint) int {\n\tfor _, c := range constraints {\n\t\tif c.TopologyKey == v1.LabelHostname {\n\t\t\treturn nodes\n\t\t}\n\t}\n\treturn 0\n}","line":{"from":387,"to":394}} {"id":100010913,"name":"Name","signature":"func (pl *PodTopologySpread) Name() string","file":"pkg/scheduler/framework/plugins/podtopologyspread/plugin.go","code":"// Name returns name of the plugin. It is used in logs, etc.\nfunc (pl *PodTopologySpread) Name() string {\n\treturn Name\n}","line":{"from":79,"to":82}} {"id":100010914,"name":"New","signature":"func New(plArgs runtime.Object, h framework.Handle, fts feature.Features) (framework.Plugin, error)","file":"pkg/scheduler/framework/plugins/podtopologyspread/plugin.go","code":"// New initializes a new plugin and returns it.\nfunc New(plArgs runtime.Object, h framework.Handle, fts feature.Features) (framework.Plugin, error) {\n\tif h.SnapshotSharedLister() == nil {\n\t\treturn nil, fmt.Errorf(\"SnapshotSharedlister is nil\")\n\t}\n\targs, err := getArgs(plArgs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := validation.ValidatePodTopologySpreadArgs(nil, \u0026args); err != nil {\n\t\treturn nil, err\n\t}\n\tpl := \u0026PodTopologySpread{\n\t\tparallelizer: h.Parallelizer(),\n\t\tsharedLister: h.SnapshotSharedLister(),\n\t\tdefaultConstraints: args.DefaultConstraints,\n\t\tenableMinDomainsInPodTopologySpread: fts.EnableMinDomainsInPodTopologySpread,\n\t\tenableNodeInclusionPolicyInPodTopologySpread: fts.EnableNodeInclusionPolicyInPodTopologySpread,\n\t\tenableMatchLabelKeysInPodTopologySpread: fts.EnableMatchLabelKeysInPodTopologySpread,\n\t}\n\tif args.DefaultingType == config.SystemDefaulting {\n\t\tpl.defaultConstraints = systemDefaultConstraints\n\t\tpl.systemDefaulted = true\n\t}\n\tif len(pl.defaultConstraints) != 0 {\n\t\tif h.SharedInformerFactory() == nil {\n\t\t\treturn nil, fmt.Errorf(\"SharedInformerFactory is nil\")\n\t\t}\n\t\tpl.setListers(h.SharedInformerFactory())\n\t}\n\treturn pl, nil\n}","line":{"from":84,"to":115}} {"id":100010915,"name":"getArgs","signature":"func getArgs(obj runtime.Object) (config.PodTopologySpreadArgs, error)","file":"pkg/scheduler/framework/plugins/podtopologyspread/plugin.go","code":"func getArgs(obj runtime.Object) (config.PodTopologySpreadArgs, error) {\n\tptr, ok := obj.(*config.PodTopologySpreadArgs)\n\tif !ok {\n\t\treturn config.PodTopologySpreadArgs{}, fmt.Errorf(\"want args to be of type PodTopologySpreadArgs, got %T\", obj)\n\t}\n\treturn *ptr, nil\n}","line":{"from":117,"to":123}} {"id":100010916,"name":"setListers","signature":"func (pl *PodTopologySpread) setListers(factory informers.SharedInformerFactory)","file":"pkg/scheduler/framework/plugins/podtopologyspread/plugin.go","code":"func (pl *PodTopologySpread) setListers(factory informers.SharedInformerFactory) {\n\tpl.services = factory.Core().V1().Services().Lister()\n\tpl.replicationCtrls = factory.Core().V1().ReplicationControllers().Lister()\n\tpl.replicaSets = factory.Apps().V1().ReplicaSets().Lister()\n\tpl.statefulSets = factory.Apps().V1().StatefulSets().Lister()\n}","line":{"from":125,"to":130}} {"id":100010917,"name":"EventsToRegister","signature":"func (pl *PodTopologySpread) EventsToRegister() []framework.ClusterEvent","file":"pkg/scheduler/framework/plugins/podtopologyspread/plugin.go","code":"// EventsToRegister returns the possible events that may make a Pod\n// failed by this plugin schedulable.\nfunc (pl *PodTopologySpread) EventsToRegister() []framework.ClusterEvent {\n\treturn []framework.ClusterEvent{\n\t\t// All ActionType includes the following events:\n\t\t// - Add. An unschedulable Pod may fail due to violating topology spread constraints,\n\t\t// adding an assigned Pod may make it schedulable.\n\t\t// - Update. Updating on an existing Pod's labels (e.g., removal) may make\n\t\t// an unschedulable Pod schedulable.\n\t\t// - Delete. An unschedulable Pod may fail due to violating an existing Pod's topology spread constraints,\n\t\t// deleting an existing Pod may make it schedulable.\n\t\t{Resource: framework.Pod, ActionType: framework.All},\n\t\t// Node add|delete|updateLabel maybe lead an topology key changed,\n\t\t// and make these pod in scheduling schedulable or unschedulable.\n\t\t{Resource: framework.Node, ActionType: framework.Add | framework.Delete | framework.UpdateNodeLabel},\n\t}\n}","line":{"from":132,"to":148}} {"id":100010918,"name":"Clone","signature":"func (s *preScoreState) Clone() framework.StateData","file":"pkg/scheduler/framework/plugins/podtopologyspread/scoring.go","code":"// Clone implements the mandatory Clone interface. We don't really copy the data since\n// there is no need for that.\nfunc (s *preScoreState) Clone() framework.StateData {\n\treturn s\n}","line":{"from":48,"to":52}} {"id":100010919,"name":"initPreScoreState","signature":"func (pl *PodTopologySpread) initPreScoreState(s *preScoreState, pod *v1.Pod, filteredNodes []*v1.Node, requireAllTopologies bool) error","file":"pkg/scheduler/framework/plugins/podtopologyspread/scoring.go","code":"// initPreScoreState iterates \"filteredNodes\" to filter out the nodes which\n// don't have required topologyKey(s), and initialize:\n// 1) s.TopologyPairToPodCounts: keyed with both eligible topology pair and node names.\n// 2) s.IgnoredNodes: the set of nodes that shouldn't be scored.\n// 3) s.TopologyNormalizingWeight: The weight to be given to each constraint based on the number of values in a topology.\nfunc (pl *PodTopologySpread) initPreScoreState(s *preScoreState, pod *v1.Pod, filteredNodes []*v1.Node, requireAllTopologies bool) error {\n\tvar err error\n\tif len(pod.Spec.TopologySpreadConstraints) \u003e 0 {\n\t\ts.Constraints, err = pl.filterTopologySpreadConstraints(\n\t\t\tpod.Spec.TopologySpreadConstraints,\n\t\t\tpod.Labels,\n\t\t\tv1.ScheduleAnyway,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"obtaining pod's soft topology spread constraints: %w\", err)\n\t\t}\n\t} else {\n\t\ts.Constraints, err = pl.buildDefaultConstraints(pod, v1.ScheduleAnyway)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"setting default soft topology spread constraints: %w\", err)\n\t\t}\n\t}\n\tif len(s.Constraints) == 0 {\n\t\treturn nil\n\t}\n\ttopoSize := make([]int, len(s.Constraints))\n\tfor _, node := range filteredNodes {\n\t\tif requireAllTopologies \u0026\u0026 !nodeLabelsMatchSpreadConstraints(node.Labels, s.Constraints) {\n\t\t\t// Nodes which don't have all required topologyKeys present are ignored\n\t\t\t// when scoring later.\n\t\t\ts.IgnoredNodes.Insert(node.Name)\n\t\t\tcontinue\n\t\t}\n\t\tfor i, constraint := range s.Constraints {\n\t\t\t// per-node counts are calculated during Score.\n\t\t\tif constraint.TopologyKey == v1.LabelHostname {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpair := topologyPair{key: constraint.TopologyKey, value: node.Labels[constraint.TopologyKey]}\n\t\t\tif s.TopologyPairToPodCounts[pair] == nil {\n\t\t\t\ts.TopologyPairToPodCounts[pair] = new(int64)\n\t\t\t\ttopoSize[i]++\n\t\t\t}\n\t\t}\n\t}\n\n\ts.TopologyNormalizingWeight = make([]float64, len(s.Constraints))\n\tfor i, c := range s.Constraints {\n\t\tsz := topoSize[i]\n\t\tif c.TopologyKey == v1.LabelHostname {\n\t\t\tsz = len(filteredNodes) - len(s.IgnoredNodes)\n\t\t}\n\t\ts.TopologyNormalizingWeight[i] = topologyNormalizingWeight(sz)\n\t}\n\treturn nil\n}","line":{"from":54,"to":109}} {"id":100010920,"name":"PreScore","signature":"func (pl *PodTopologySpread) PreScore(","file":"pkg/scheduler/framework/plugins/podtopologyspread/scoring.go","code":"// PreScore builds and writes cycle state used by Score and NormalizeScore.\nfunc (pl *PodTopologySpread) PreScore(\n\tctx context.Context,\n\tcycleState *framework.CycleState,\n\tpod *v1.Pod,\n\tfilteredNodes []*v1.Node,\n) *framework.Status {\n\tallNodes, err := pl.sharedLister.NodeInfos().List()\n\tif err != nil {\n\t\treturn framework.AsStatus(fmt.Errorf(\"getting all nodes: %w\", err))\n\t}\n\n\tif len(filteredNodes) == 0 || len(allNodes) == 0 {\n\t\t// No nodes to score.\n\t\treturn nil\n\t}\n\n\tstate := \u0026preScoreState{\n\t\tIgnoredNodes: sets.NewString(),\n\t\tTopologyPairToPodCounts: make(map[topologyPair]*int64),\n\t}\n\t// Only require that nodes have all the topology labels if using\n\t// non-system-default spreading rules. This allows nodes that don't have a\n\t// zone label to still have hostname spreading.\n\trequireAllTopologies := len(pod.Spec.TopologySpreadConstraints) \u003e 0 || !pl.systemDefaulted\n\terr = pl.initPreScoreState(state, pod, filteredNodes, requireAllTopologies)\n\tif err != nil {\n\t\treturn framework.AsStatus(fmt.Errorf(\"calculating preScoreState: %w\", err))\n\t}\n\n\t// return if incoming pod doesn't have soft topology spread Constraints.\n\tif len(state.Constraints) == 0 {\n\t\tcycleState.Write(preScoreStateKey, state)\n\t\treturn nil\n\t}\n\n\t// Ignore parsing errors for backwards compatibility.\n\trequiredNodeAffinity := nodeaffinity.GetRequiredNodeAffinity(pod)\n\tprocessAllNode := func(i int) {\n\t\tnodeInfo := allNodes[i]\n\t\tnode := nodeInfo.Node()\n\t\tif node == nil {\n\t\t\treturn\n\t\t}\n\n\t\tif !pl.enableNodeInclusionPolicyInPodTopologySpread {\n\t\t\t// `node` should satisfy incoming pod's NodeSelector/NodeAffinity\n\t\t\tif match, _ := requiredNodeAffinity.Match(node); !match {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t// All topologyKeys need to be present in `node`\n\t\tif requireAllTopologies \u0026\u0026 !nodeLabelsMatchSpreadConstraints(node.Labels, state.Constraints) {\n\t\t\treturn\n\t\t}\n\n\t\tfor _, c := range state.Constraints {\n\t\t\tif pl.enableNodeInclusionPolicyInPodTopologySpread \u0026\u0026\n\t\t\t\t!c.matchNodeInclusionPolicies(pod, node, requiredNodeAffinity) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tpair := topologyPair{key: c.TopologyKey, value: node.Labels[c.TopologyKey]}\n\t\t\t// If current topology pair is not associated with any candidate node,\n\t\t\t// continue to avoid unnecessary calculation.\n\t\t\t// Per-node counts are also skipped, as they are done during Score.\n\t\t\ttpCount := state.TopologyPairToPodCounts[pair]\n\t\t\tif tpCount == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcount := countPodsMatchSelector(nodeInfo.Pods, c.Selector, pod.Namespace)\n\t\t\tatomic.AddInt64(tpCount, int64(count))\n\t\t}\n\t}\n\tpl.parallelizer.Until(ctx, len(allNodes), processAllNode, pl.Name())\n\n\tcycleState.Write(preScoreStateKey, state)\n\treturn nil\n}","line":{"from":111,"to":190}} {"id":100010921,"name":"Score","signature":"func (pl *PodTopologySpread) Score(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status)","file":"pkg/scheduler/framework/plugins/podtopologyspread/scoring.go","code":"// Score invoked at the Score extension point.\n// The \"score\" returned in this function is the matching number of pods on the `nodeName`,\n// it is normalized later.\nfunc (pl *PodTopologySpread) Score(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status) {\n\tnodeInfo, err := pl.sharedLister.NodeInfos().Get(nodeName)\n\tif err != nil {\n\t\treturn 0, framework.AsStatus(fmt.Errorf(\"getting node %q from Snapshot: %w\", nodeName, err))\n\t}\n\n\tnode := nodeInfo.Node()\n\ts, err := getPreScoreState(cycleState)\n\tif err != nil {\n\t\treturn 0, framework.AsStatus(err)\n\t}\n\n\t// Return if the node is not qualified.\n\tif s.IgnoredNodes.Has(node.Name) {\n\t\treturn 0, nil\n\t}\n\n\t// For each present \u003cpair\u003e, current node gets a credit of \u003cmatchSum\u003e.\n\t// And we sum up \u003cmatchSum\u003e and return it as this node's score.\n\tvar score float64\n\tfor i, c := range s.Constraints {\n\t\tif tpVal, ok := node.Labels[c.TopologyKey]; ok {\n\t\t\tvar cnt int64\n\t\t\tif c.TopologyKey == v1.LabelHostname {\n\t\t\t\tcnt = int64(countPodsMatchSelector(nodeInfo.Pods, c.Selector, pod.Namespace))\n\t\t\t} else {\n\t\t\t\tpair := topologyPair{key: c.TopologyKey, value: tpVal}\n\t\t\t\tcnt = *s.TopologyPairToPodCounts[pair]\n\t\t\t}\n\t\t\tscore += scoreForCount(cnt, c.MaxSkew, s.TopologyNormalizingWeight[i])\n\t\t}\n\t}\n\treturn int64(math.Round(score)), nil\n}","line":{"from":192,"to":228}} {"id":100010922,"name":"NormalizeScore","signature":"func (pl *PodTopologySpread) NormalizeScore(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, scores framework.NodeScoreList) *framework.Status","file":"pkg/scheduler/framework/plugins/podtopologyspread/scoring.go","code":"// NormalizeScore invoked after scoring all nodes.\nfunc (pl *PodTopologySpread) NormalizeScore(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, scores framework.NodeScoreList) *framework.Status {\n\ts, err := getPreScoreState(cycleState)\n\tif err != nil {\n\t\treturn framework.AsStatus(err)\n\t}\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\t// Calculate \u003cminScore\u003e and \u003cmaxScore\u003e\n\tvar minScore int64 = math.MaxInt64\n\tvar maxScore int64\n\tfor i, score := range scores {\n\t\t// it's mandatory to check if \u003cscore.Name\u003e is present in m.IgnoredNodes\n\t\tif s.IgnoredNodes.Has(score.Name) {\n\t\t\tscores[i].Score = invalidScore\n\t\t\tcontinue\n\t\t}\n\t\tif score.Score \u003c minScore {\n\t\t\tminScore = score.Score\n\t\t}\n\t\tif score.Score \u003e maxScore {\n\t\t\tmaxScore = score.Score\n\t\t}\n\t}\n\n\tfor i := range scores {\n\t\tif scores[i].Score == invalidScore {\n\t\t\tscores[i].Score = 0\n\t\t\tcontinue\n\t\t}\n\t\tif maxScore == 0 {\n\t\t\tscores[i].Score = framework.MaxNodeScore\n\t\t\tcontinue\n\t\t}\n\t\ts := scores[i].Score\n\t\tscores[i].Score = framework.MaxNodeScore * (maxScore + minScore - s) / maxScore\n\t}\n\treturn nil\n}","line":{"from":230,"to":270}} {"id":100010923,"name":"ScoreExtensions","signature":"func (pl *PodTopologySpread) ScoreExtensions() framework.ScoreExtensions","file":"pkg/scheduler/framework/plugins/podtopologyspread/scoring.go","code":"// ScoreExtensions of the Score plugin.\nfunc (pl *PodTopologySpread) ScoreExtensions() framework.ScoreExtensions {\n\treturn pl\n}","line":{"from":272,"to":275}} {"id":100010924,"name":"getPreScoreState","signature":"func getPreScoreState(cycleState *framework.CycleState) (*preScoreState, error)","file":"pkg/scheduler/framework/plugins/podtopologyspread/scoring.go","code":"func getPreScoreState(cycleState *framework.CycleState) (*preScoreState, error) {\n\tc, err := cycleState.Read(preScoreStateKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading %q from cycleState: %w\", preScoreStateKey, err)\n\t}\n\n\ts, ok := c.(*preScoreState)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"%+v convert to podtopologyspread.preScoreState error\", c)\n\t}\n\treturn s, nil\n}","line":{"from":277,"to":288}} {"id":100010925,"name":"topologyNormalizingWeight","signature":"func topologyNormalizingWeight(size int) float64","file":"pkg/scheduler/framework/plugins/podtopologyspread/scoring.go","code":"// topologyNormalizingWeight calculates the weight for the topology, based on\n// the number of values that exist for a topology.\n// Since \u003csize\u003e is at least 1 (all nodes that passed the Filters are in the\n// same topology), and k8s supports 5k nodes, the result is in the interval\n// \u003c1.09, 8.52\u003e.\n//\n// Note: \u003csize\u003e could also be zero when no nodes have the required topologies,\n// however we don't care about topology weight in this case as we return a 0\n// score for all nodes.\nfunc topologyNormalizingWeight(size int) float64 {\n\treturn math.Log(float64(size + 2))\n}","line":{"from":290,"to":301}} {"id":100010926,"name":"scoreForCount","signature":"func scoreForCount(cnt int64, maxSkew int32, tpWeight float64) float64","file":"pkg/scheduler/framework/plugins/podtopologyspread/scoring.go","code":"// scoreForCount calculates the score based on number of matching pods in a\n// topology domain, the constraint's maxSkew and the topology weight.\n// `maxSkew-1` is added to the score so that differences between topology\n// domains get watered down, controlling the tolerance of the score to skews.\nfunc scoreForCount(cnt int64, maxSkew int32, tpWeight float64) float64 {\n\treturn float64(cnt)*tpWeight + float64(maxSkew-1)\n}","line":{"from":303,"to":309}} {"id":100010927,"name":"Name","signature":"func (pl *PrioritySort) Name() string","file":"pkg/scheduler/framework/plugins/queuesort/priority_sort.go","code":"// Name returns name of the plugin.\nfunc (pl *PrioritySort) Name() string {\n\treturn Name\n}","line":{"from":34,"to":37}} {"id":100010928,"name":"Less","signature":"func (pl *PrioritySort) Less(pInfo1, pInfo2 *framework.QueuedPodInfo) bool","file":"pkg/scheduler/framework/plugins/queuesort/priority_sort.go","code":"// Less is the function used by the activeQ heap algorithm to sort pods.\n// It sorts pods based on their priority. When priorities are equal, it uses\n// PodQueueInfo.timestamp.\nfunc (pl *PrioritySort) Less(pInfo1, pInfo2 *framework.QueuedPodInfo) bool {\n\tp1 := corev1helpers.PodPriority(pInfo1.Pod)\n\tp2 := corev1helpers.PodPriority(pInfo2.Pod)\n\treturn (p1 \u003e p2) || (p1 == p2 \u0026\u0026 pInfo1.Timestamp.Before(pInfo2.Timestamp))\n}","line":{"from":39,"to":46}} {"id":100010929,"name":"New","signature":"func New(_ runtime.Object, handle framework.Handle) (framework.Plugin, error)","file":"pkg/scheduler/framework/plugins/queuesort/priority_sort.go","code":"// New initializes a new plugin and returns it.\nfunc New(_ runtime.Object, handle framework.Handle) (framework.Plugin, error) {\n\treturn \u0026PrioritySort{}, nil\n}","line":{"from":48,"to":51}} {"id":100010930,"name":"NewInTreeRegistry","signature":"func NewInTreeRegistry() runtime.Registry","file":"pkg/scheduler/framework/plugins/registry.go","code":"// NewInTreeRegistry builds the registry with all the in-tree plugins.\n// A scheduler that runs out of tree plugins can register additional plugins\n// through the WithFrameworkOutOfTreeRegistry option.\nfunc NewInTreeRegistry() runtime.Registry {\n\tfts := plfeature.Features{\n\t\tEnableDynamicResourceAllocation: feature.DefaultFeatureGate.Enabled(features.DynamicResourceAllocation),\n\t\tEnableReadWriteOncePod: feature.DefaultFeatureGate.Enabled(features.ReadWriteOncePod),\n\t\tEnableVolumeCapacityPriority: feature.DefaultFeatureGate.Enabled(features.VolumeCapacityPriority),\n\t\tEnableMinDomainsInPodTopologySpread: feature.DefaultFeatureGate.Enabled(features.MinDomainsInPodTopologySpread),\n\t\tEnableNodeInclusionPolicyInPodTopologySpread: feature.DefaultFeatureGate.Enabled(features.NodeInclusionPolicyInPodTopologySpread),\n\t\tEnableMatchLabelKeysInPodTopologySpread: feature.DefaultFeatureGate.Enabled(features.MatchLabelKeysInPodTopologySpread),\n\t\tEnablePodSchedulingReadiness: feature.DefaultFeatureGate.Enabled(features.PodSchedulingReadiness),\n\t\tEnablePodDisruptionConditions: feature.DefaultFeatureGate.Enabled(features.PodDisruptionConditions),\n\t\tEnableInPlacePodVerticalScaling: feature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling),\n\t}\n\n\tregistry := runtime.Registry{\n\t\tdynamicresources.Name: runtime.FactoryAdapter(fts, dynamicresources.New),\n\t\tselectorspread.Name: selectorspread.New,\n\t\timagelocality.Name: imagelocality.New,\n\t\ttainttoleration.Name: tainttoleration.New,\n\t\tnodename.Name: nodename.New,\n\t\tnodeports.Name: nodeports.New,\n\t\tnodeaffinity.Name: nodeaffinity.New,\n\t\tpodtopologyspread.Name: runtime.FactoryAdapter(fts, podtopologyspread.New),\n\t\tnodeunschedulable.Name: nodeunschedulable.New,\n\t\tnoderesources.Name: runtime.FactoryAdapter(fts, noderesources.NewFit),\n\t\tnoderesources.BalancedAllocationName: runtime.FactoryAdapter(fts, noderesources.NewBalancedAllocation),\n\t\tvolumebinding.Name: runtime.FactoryAdapter(fts, volumebinding.New),\n\t\tvolumerestrictions.Name: runtime.FactoryAdapter(fts, volumerestrictions.New),\n\t\tvolumezone.Name: volumezone.New,\n\t\tnodevolumelimits.CSIName: runtime.FactoryAdapter(fts, nodevolumelimits.NewCSI),\n\t\tnodevolumelimits.EBSName: runtime.FactoryAdapter(fts, nodevolumelimits.NewEBS),\n\t\tnodevolumelimits.GCEPDName: runtime.FactoryAdapter(fts, nodevolumelimits.NewGCEPD),\n\t\tnodevolumelimits.AzureDiskName: runtime.FactoryAdapter(fts, nodevolumelimits.NewAzureDisk),\n\t\tnodevolumelimits.CinderName: runtime.FactoryAdapter(fts, nodevolumelimits.NewCinder),\n\t\tinterpodaffinity.Name: interpodaffinity.New,\n\t\tqueuesort.Name: queuesort.New,\n\t\tdefaultbinder.Name: defaultbinder.New,\n\t\tdefaultpreemption.Name: runtime.FactoryAdapter(fts, defaultpreemption.New),\n\t\tschedulinggates.Name: runtime.FactoryAdapter(fts, schedulinggates.New),\n\t}\n\n\treturn registry\n}","line":{"from":45,"to":89}} {"id":100010931,"name":"Name","signature":"func (pl *SchedulingGates) Name() string","file":"pkg/scheduler/framework/plugins/schedulinggates/scheduling_gates.go","code":"func (pl *SchedulingGates) Name() string {\n\treturn Name\n}","line":{"from":41,"to":43}} {"id":100010932,"name":"PreEnqueue","signature":"func (pl *SchedulingGates) PreEnqueue(ctx context.Context, p *v1.Pod) *framework.Status","file":"pkg/scheduler/framework/plugins/schedulinggates/scheduling_gates.go","code":"func (pl *SchedulingGates) PreEnqueue(ctx context.Context, p *v1.Pod) *framework.Status {\n\tif !pl.enablePodSchedulingReadiness || len(p.Spec.SchedulingGates) == 0 {\n\t\treturn nil\n\t}\n\tvar gates []string\n\tfor _, gate := range p.Spec.SchedulingGates {\n\t\tgates = append(gates, gate.Name)\n\t}\n\treturn framework.NewStatus(framework.UnschedulableAndUnresolvable, fmt.Sprintf(\"waiting for scheduling gates: %v\", gates))\n}","line":{"from":45,"to":54}} {"id":100010933,"name":"EventsToRegister","signature":"func (pl *SchedulingGates) EventsToRegister() []framework.ClusterEvent","file":"pkg/scheduler/framework/plugins/schedulinggates/scheduling_gates.go","code":"// EventsToRegister returns the possible events that may make a Pod\n// failed by this plugin schedulable.\nfunc (pl *SchedulingGates) EventsToRegister() []framework.ClusterEvent {\n\treturn []framework.ClusterEvent{\n\t\t{Resource: framework.Pod, ActionType: framework.Update},\n\t}\n}","line":{"from":56,"to":62}} {"id":100010934,"name":"New","signature":"func New(_ runtime.Object, _ framework.Handle, fts feature.Features) (framework.Plugin, error)","file":"pkg/scheduler/framework/plugins/schedulinggates/scheduling_gates.go","code":"// New initializes a new plugin and returns it.\nfunc New(_ runtime.Object, _ framework.Handle, fts feature.Features) (framework.Plugin, error) {\n\treturn \u0026SchedulingGates{enablePodSchedulingReadiness: fts.EnablePodSchedulingReadiness}, nil\n}","line":{"from":64,"to":67}} {"id":100010935,"name":"Name","signature":"func (pl *SelectorSpread) Name() string","file":"pkg/scheduler/framework/plugins/selectorspread/selector_spread.go","code":"// Name returns name of the plugin. It is used in logs, etc.\nfunc (pl *SelectorSpread) Name() string {\n\treturn Name\n}","line":{"from":57,"to":60}} {"id":100010936,"name":"Clone","signature":"func (s *preScoreState) Clone() framework.StateData","file":"pkg/scheduler/framework/plugins/selectorspread/selector_spread.go","code":"// Clone implements the mandatory Clone interface. We don't really copy the data since\n// there is no need for that.\nfunc (s *preScoreState) Clone() framework.StateData {\n\treturn s\n}","line":{"from":67,"to":71}} {"id":100010937,"name":"skipSelectorSpread","signature":"func skipSelectorSpread(pod *v1.Pod) bool","file":"pkg/scheduler/framework/plugins/selectorspread/selector_spread.go","code":"// skipSelectorSpread returns true if the pod's TopologySpreadConstraints are specified.\n// Note that this doesn't take into account default constraints defined for\n// the PodTopologySpread plugin.\nfunc skipSelectorSpread(pod *v1.Pod) bool {\n\treturn len(pod.Spec.TopologySpreadConstraints) != 0\n}","line":{"from":73,"to":78}} {"id":100010938,"name":"Score","signature":"func (pl *SelectorSpread) Score(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status)","file":"pkg/scheduler/framework/plugins/selectorspread/selector_spread.go","code":"// Score invoked at the Score extension point.\n// The \"score\" returned in this function is the matching number of pods on the `nodeName`,\n// it is normalized later.\nfunc (pl *SelectorSpread) Score(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status) {\n\tif skipSelectorSpread(pod) {\n\t\treturn 0, nil\n\t}\n\n\tc, err := state.Read(preScoreStateKey)\n\tif err != nil {\n\t\treturn 0, framework.AsStatus(fmt.Errorf(\"reading %q from cycleState: %w\", preScoreStateKey, err))\n\t}\n\n\ts, ok := c.(*preScoreState)\n\tif !ok {\n\t\treturn 0, framework.AsStatus(fmt.Errorf(\"cannot convert saved state to selectorspread.preScoreState\"))\n\t}\n\n\tnodeInfo, err := pl.sharedLister.NodeInfos().Get(nodeName)\n\tif err != nil {\n\t\treturn 0, framework.AsStatus(fmt.Errorf(\"getting node %q from Snapshot: %w\", nodeName, err))\n\t}\n\n\tcount := countMatchingPods(pod.Namespace, s.selector, nodeInfo)\n\treturn int64(count), nil\n}","line":{"from":80,"to":105}} {"id":100010939,"name":"NormalizeScore","signature":"func (pl *SelectorSpread) NormalizeScore(ctx context.Context, state *framework.CycleState, pod *v1.Pod, scores framework.NodeScoreList) *framework.Status","file":"pkg/scheduler/framework/plugins/selectorspread/selector_spread.go","code":"// NormalizeScore invoked after scoring all nodes.\n// For this plugin, it calculates the score of each node\n// based on the number of existing matching pods on the node\n// where zone information is included on the nodes, it favors nodes\n// in zones with fewer existing matching pods.\nfunc (pl *SelectorSpread) NormalizeScore(ctx context.Context, state *framework.CycleState, pod *v1.Pod, scores framework.NodeScoreList) *framework.Status {\n\tif skipSelectorSpread(pod) {\n\t\treturn nil\n\t}\n\n\tcountsByZone := make(map[string]int64, 10)\n\tmaxCountByZone := int64(0)\n\tmaxCountByNodeName := int64(0)\n\n\tfor i := range scores {\n\t\tif scores[i].Score \u003e maxCountByNodeName {\n\t\t\tmaxCountByNodeName = scores[i].Score\n\t\t}\n\t\tnodeInfo, err := pl.sharedLister.NodeInfos().Get(scores[i].Name)\n\t\tif err != nil {\n\t\t\treturn framework.AsStatus(fmt.Errorf(\"getting node %q from Snapshot: %w\", scores[i].Name, err))\n\t\t}\n\t\tzoneID := utilnode.GetZoneKey(nodeInfo.Node())\n\t\tif zoneID == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tcountsByZone[zoneID] += scores[i].Score\n\t}\n\n\tfor zoneID := range countsByZone {\n\t\tif countsByZone[zoneID] \u003e maxCountByZone {\n\t\t\tmaxCountByZone = countsByZone[zoneID]\n\t\t}\n\t}\n\n\thaveZones := len(countsByZone) != 0\n\n\tmaxCountByNodeNameFloat64 := float64(maxCountByNodeName)\n\tmaxCountByZoneFloat64 := float64(maxCountByZone)\n\tMaxNodeScoreFloat64 := float64(framework.MaxNodeScore)\n\n\tfor i := range scores {\n\t\t// initializing to the default/max node score of maxPriority\n\t\tfScore := MaxNodeScoreFloat64\n\t\tif maxCountByNodeName \u003e 0 {\n\t\t\tfScore = MaxNodeScoreFloat64 * (float64(maxCountByNodeName-scores[i].Score) / maxCountByNodeNameFloat64)\n\t\t}\n\t\t// If there is zone information present, incorporate it\n\t\tif haveZones {\n\t\t\tnodeInfo, err := pl.sharedLister.NodeInfos().Get(scores[i].Name)\n\t\t\tif err != nil {\n\t\t\t\treturn framework.AsStatus(fmt.Errorf(\"getting node %q from Snapshot: %w\", scores[i].Name, err))\n\t\t\t}\n\n\t\t\tzoneID := utilnode.GetZoneKey(nodeInfo.Node())\n\t\t\tif zoneID != \"\" {\n\t\t\t\tzoneScore := MaxNodeScoreFloat64\n\t\t\t\tif maxCountByZone \u003e 0 {\n\t\t\t\t\tzoneScore = MaxNodeScoreFloat64 * (float64(maxCountByZone-countsByZone[zoneID]) / maxCountByZoneFloat64)\n\t\t\t\t}\n\t\t\t\tfScore = (fScore * (1.0 - zoneWeighting)) + (zoneWeighting * zoneScore)\n\t\t\t}\n\t\t}\n\t\tscores[i].Score = int64(fScore)\n\t}\n\treturn nil\n}","line":{"from":107,"to":173}} {"id":100010940,"name":"ScoreExtensions","signature":"func (pl *SelectorSpread) ScoreExtensions() framework.ScoreExtensions","file":"pkg/scheduler/framework/plugins/selectorspread/selector_spread.go","code":"// ScoreExtensions of the Score plugin.\nfunc (pl *SelectorSpread) ScoreExtensions() framework.ScoreExtensions {\n\treturn pl\n}","line":{"from":175,"to":178}} {"id":100010941,"name":"PreScore","signature":"func (pl *SelectorSpread) PreScore(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodes []*v1.Node) *framework.Status","file":"pkg/scheduler/framework/plugins/selectorspread/selector_spread.go","code":"// PreScore builds and writes cycle state used by Score and NormalizeScore.\nfunc (pl *SelectorSpread) PreScore(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodes []*v1.Node) *framework.Status {\n\tif skipSelectorSpread(pod) {\n\t\treturn nil\n\t}\n\tselector := helper.DefaultSelector(\n\t\tpod,\n\t\tpl.services,\n\t\tpl.replicationControllers,\n\t\tpl.replicaSets,\n\t\tpl.statefulSets,\n\t)\n\tstate := \u0026preScoreState{\n\t\tselector: selector,\n\t}\n\tcycleState.Write(preScoreStateKey, state)\n\treturn nil\n}","line":{"from":180,"to":197}} {"id":100010942,"name":"New","signature":"func New(_ runtime.Object, handle framework.Handle) (framework.Plugin, error)","file":"pkg/scheduler/framework/plugins/selectorspread/selector_spread.go","code":"// New initializes a new plugin and returns it.\nfunc New(_ runtime.Object, handle framework.Handle) (framework.Plugin, error) {\n\tsharedLister := handle.SnapshotSharedLister()\n\tif sharedLister == nil {\n\t\treturn nil, fmt.Errorf(\"SnapshotSharedLister is nil\")\n\t}\n\tsharedInformerFactory := handle.SharedInformerFactory()\n\tif sharedInformerFactory == nil {\n\t\treturn nil, fmt.Errorf(\"SharedInformerFactory is nil\")\n\t}\n\treturn \u0026SelectorSpread{\n\t\tsharedLister: sharedLister,\n\t\tservices: sharedInformerFactory.Core().V1().Services().Lister(),\n\t\treplicationControllers: sharedInformerFactory.Core().V1().ReplicationControllers().Lister(),\n\t\treplicaSets: sharedInformerFactory.Apps().V1().ReplicaSets().Lister(),\n\t\tstatefulSets: sharedInformerFactory.Apps().V1().StatefulSets().Lister(),\n\t}, nil\n}","line":{"from":199,"to":216}} {"id":100010943,"name":"countMatchingPods","signature":"func countMatchingPods(namespace string, selector labels.Selector, nodeInfo *framework.NodeInfo) int","file":"pkg/scheduler/framework/plugins/selectorspread/selector_spread.go","code":"// countMatchingPods counts pods based on namespace and matching all selectors\nfunc countMatchingPods(namespace string, selector labels.Selector, nodeInfo *framework.NodeInfo) int {\n\tif len(nodeInfo.Pods) == 0 || selector.Empty() {\n\t\treturn 0\n\t}\n\tcount := 0\n\tfor _, p := range nodeInfo.Pods {\n\t\t// Ignore pods being deleted for spreading purposes\n\t\t// Similar to how it is done for SelectorSpreadPriority\n\t\tif namespace == p.Pod.Namespace \u0026\u0026 p.Pod.DeletionTimestamp == nil {\n\t\t\tif selector.Matches(labels.Set(p.Pod.Labels)) {\n\t\t\t\tcount++\n\t\t\t}\n\t\t}\n\t}\n\treturn count\n}","line":{"from":218,"to":234}} {"id":100010944,"name":"Name","signature":"func (pl *TaintToleration) Name() string","file":"pkg/scheduler/framework/plugins/tainttoleration/taint_toleration.go","code":"// Name returns name of the plugin. It is used in logs, etc.\nfunc (pl *TaintToleration) Name() string {\n\treturn Name\n}","line":{"from":50,"to":53}} {"id":100010945,"name":"EventsToRegister","signature":"func (pl *TaintToleration) EventsToRegister() []framework.ClusterEvent","file":"pkg/scheduler/framework/plugins/tainttoleration/taint_toleration.go","code":"// EventsToRegister returns the possible events that may make a Pod\n// failed by this plugin schedulable.\nfunc (pl *TaintToleration) EventsToRegister() []framework.ClusterEvent {\n\treturn []framework.ClusterEvent{\n\t\t{Resource: framework.Node, ActionType: framework.Add | framework.Update},\n\t}\n}","line":{"from":55,"to":61}} {"id":100010946,"name":"Filter","signature":"func (pl *TaintToleration) Filter(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status","file":"pkg/scheduler/framework/plugins/tainttoleration/taint_toleration.go","code":"// Filter invoked at the filter extension point.\nfunc (pl *TaintToleration) Filter(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status {\n\tnode := nodeInfo.Node()\n\tif node == nil {\n\t\treturn framework.AsStatus(fmt.Errorf(\"invalid nodeInfo\"))\n\t}\n\n\ttaint, isUntolerated := v1helper.FindMatchingUntoleratedTaint(node.Spec.Taints, pod.Spec.Tolerations, helper.DoNotScheduleTaintsFilterFunc())\n\tif !isUntolerated {\n\t\treturn nil\n\t}\n\n\terrReason := fmt.Sprintf(\"node(s) had untolerated taint {%s: %s}\", taint.Key, taint.Value)\n\treturn framework.NewStatus(framework.UnschedulableAndUnresolvable, errReason)\n}","line":{"from":63,"to":77}} {"id":100010947,"name":"Clone","signature":"func (s *preScoreState) Clone() framework.StateData","file":"pkg/scheduler/framework/plugins/tainttoleration/taint_toleration.go","code":"// Clone implements the mandatory Clone interface. We don't really copy the data since\n// there is no need for that.\nfunc (s *preScoreState) Clone() framework.StateData {\n\treturn s\n}","line":{"from":84,"to":88}} {"id":100010948,"name":"getAllTolerationPreferNoSchedule","signature":"func getAllTolerationPreferNoSchedule(tolerations []v1.Toleration) (tolerationList []v1.Toleration)","file":"pkg/scheduler/framework/plugins/tainttoleration/taint_toleration.go","code":"// getAllTolerationEffectPreferNoSchedule gets the list of all Tolerations with Effect PreferNoSchedule or with no effect.\nfunc getAllTolerationPreferNoSchedule(tolerations []v1.Toleration) (tolerationList []v1.Toleration) {\n\tfor _, toleration := range tolerations {\n\t\t// Empty effect means all effects which includes PreferNoSchedule, so we need to collect it as well.\n\t\tif len(toleration.Effect) == 0 || toleration.Effect == v1.TaintEffectPreferNoSchedule {\n\t\t\ttolerationList = append(tolerationList, toleration)\n\t\t}\n\t}\n\treturn\n}","line":{"from":90,"to":99}} {"id":100010949,"name":"PreScore","signature":"func (pl *TaintToleration) PreScore(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodes []*v1.Node) *framework.Status","file":"pkg/scheduler/framework/plugins/tainttoleration/taint_toleration.go","code":"// PreScore builds and writes cycle state used by Score and NormalizeScore.\nfunc (pl *TaintToleration) PreScore(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodes []*v1.Node) *framework.Status {\n\tif len(nodes) == 0 {\n\t\treturn nil\n\t}\n\ttolerationsPreferNoSchedule := getAllTolerationPreferNoSchedule(pod.Spec.Tolerations)\n\tstate := \u0026preScoreState{\n\t\ttolerationsPreferNoSchedule: tolerationsPreferNoSchedule,\n\t}\n\tcycleState.Write(preScoreStateKey, state)\n\treturn nil\n}","line":{"from":101,"to":112}} {"id":100010950,"name":"getPreScoreState","signature":"func getPreScoreState(cycleState *framework.CycleState) (*preScoreState, error)","file":"pkg/scheduler/framework/plugins/tainttoleration/taint_toleration.go","code":"func getPreScoreState(cycleState *framework.CycleState) (*preScoreState, error) {\n\tc, err := cycleState.Read(preScoreStateKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read %q from cycleState: %w\", preScoreStateKey, err)\n\t}\n\n\ts, ok := c.(*preScoreState)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"%+v convert to tainttoleration.preScoreState error\", c)\n\t}\n\treturn s, nil\n}","line":{"from":114,"to":125}} {"id":100010951,"name":"countIntolerableTaintsPreferNoSchedule","signature":"func countIntolerableTaintsPreferNoSchedule(taints []v1.Taint, tolerations []v1.Toleration) (intolerableTaints int)","file":"pkg/scheduler/framework/plugins/tainttoleration/taint_toleration.go","code":"// CountIntolerableTaintsPreferNoSchedule gives the count of intolerable taints of a pod with effect PreferNoSchedule\nfunc countIntolerableTaintsPreferNoSchedule(taints []v1.Taint, tolerations []v1.Toleration) (intolerableTaints int) {\n\tfor _, taint := range taints {\n\t\t// check only on taints that have effect PreferNoSchedule\n\t\tif taint.Effect != v1.TaintEffectPreferNoSchedule {\n\t\t\tcontinue\n\t\t}\n\n\t\tif !v1helper.TolerationsTolerateTaint(tolerations, \u0026taint) {\n\t\t\tintolerableTaints++\n\t\t}\n\t}\n\treturn\n}","line":{"from":127,"to":140}} {"id":100010952,"name":"Score","signature":"func (pl *TaintToleration) Score(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status)","file":"pkg/scheduler/framework/plugins/tainttoleration/taint_toleration.go","code":"// Score invoked at the Score extension point.\nfunc (pl *TaintToleration) Score(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status) {\n\tnodeInfo, err := pl.handle.SnapshotSharedLister().NodeInfos().Get(nodeName)\n\tif err != nil {\n\t\treturn 0, framework.AsStatus(fmt.Errorf(\"getting node %q from Snapshot: %w\", nodeName, err))\n\t}\n\tnode := nodeInfo.Node()\n\n\ts, err := getPreScoreState(state)\n\tif err != nil {\n\t\treturn 0, framework.AsStatus(err)\n\t}\n\n\tscore := int64(countIntolerableTaintsPreferNoSchedule(node.Spec.Taints, s.tolerationsPreferNoSchedule))\n\treturn score, nil\n}","line":{"from":142,"to":157}} {"id":100010953,"name":"NormalizeScore","signature":"func (pl *TaintToleration) NormalizeScore(ctx context.Context, _ *framework.CycleState, pod *v1.Pod, scores framework.NodeScoreList) *framework.Status","file":"pkg/scheduler/framework/plugins/tainttoleration/taint_toleration.go","code":"// NormalizeScore invoked after scoring all nodes.\nfunc (pl *TaintToleration) NormalizeScore(ctx context.Context, _ *framework.CycleState, pod *v1.Pod, scores framework.NodeScoreList) *framework.Status {\n\treturn helper.DefaultNormalizeScore(framework.MaxNodeScore, true, scores)\n}","line":{"from":159,"to":162}} {"id":100010954,"name":"ScoreExtensions","signature":"func (pl *TaintToleration) ScoreExtensions() framework.ScoreExtensions","file":"pkg/scheduler/framework/plugins/tainttoleration/taint_toleration.go","code":"// ScoreExtensions of the Score plugin.\nfunc (pl *TaintToleration) ScoreExtensions() framework.ScoreExtensions {\n\treturn pl\n}","line":{"from":164,"to":167}} {"id":100010955,"name":"New","signature":"func New(_ runtime.Object, h framework.Handle) (framework.Plugin, error)","file":"pkg/scheduler/framework/plugins/tainttoleration/taint_toleration.go","code":"// New initializes a new plugin and returns it.\nfunc New(_ runtime.Object, h framework.Handle) (framework.Plugin, error) {\n\treturn \u0026TaintToleration{handle: h}, nil\n}","line":{"from":169,"to":172}} {"id":100010956,"name":"Error","signature":"func (e *errWrongType) Error() string","file":"pkg/scheduler/framework/plugins/volumebinding/assume_cache.go","code":"func (e *errWrongType) Error() string {\n\treturn fmt.Sprintf(\"could not convert object to type %v: %+v\", e.typeName, e.object)\n}","line":{"from":58,"to":60}} {"id":100010957,"name":"Error","signature":"func (e *errNotFound) Error() string","file":"pkg/scheduler/framework/plugins/volumebinding/assume_cache.go","code":"func (e *errNotFound) Error() string {\n\treturn fmt.Sprintf(\"could not find %v %q\", e.typeName, e.objectName)\n}","line":{"from":67,"to":69}} {"id":100010958,"name":"Error","signature":"func (e *errObjectName) Error() string","file":"pkg/scheduler/framework/plugins/volumebinding/assume_cache.go","code":"func (e *errObjectName) Error() string {\n\treturn fmt.Sprintf(\"failed to get object name: %v\", e.detailedErr)\n}","line":{"from":75,"to":77}} {"id":100010959,"name":"objInfoKeyFunc","signature":"func objInfoKeyFunc(obj interface{}) (string, error)","file":"pkg/scheduler/framework/plugins/volumebinding/assume_cache.go","code":"func objInfoKeyFunc(obj interface{}) (string, error) {\n\tobjInfo, ok := obj.(*objInfo)\n\tif !ok {\n\t\treturn \"\", \u0026errWrongType{\"objInfo\", obj}\n\t}\n\treturn objInfo.name, nil\n}","line":{"from":115,"to":121}} {"id":100010960,"name":"objInfoIndexFunc","signature":"func (c *assumeCache) objInfoIndexFunc(obj interface{}) ([]string, error)","file":"pkg/scheduler/framework/plugins/volumebinding/assume_cache.go","code":"func (c *assumeCache) objInfoIndexFunc(obj interface{}) ([]string, error) {\n\tobjInfo, ok := obj.(*objInfo)\n\tif !ok {\n\t\treturn []string{\"\"}, \u0026errWrongType{\"objInfo\", obj}\n\t}\n\treturn c.indexFunc(objInfo.latestObj)\n}","line":{"from":123,"to":129}} {"id":100010961,"name":"NewAssumeCache","signature":"func NewAssumeCache(informer cache.SharedIndexInformer, description, indexName string, indexFunc cache.IndexFunc) AssumeCache","file":"pkg/scheduler/framework/plugins/volumebinding/assume_cache.go","code":"// NewAssumeCache creates an assume cache for general objects.\nfunc NewAssumeCache(informer cache.SharedIndexInformer, description, indexName string, indexFunc cache.IndexFunc) AssumeCache {\n\tc := \u0026assumeCache{\n\t\tdescription: description,\n\t\tindexFunc: indexFunc,\n\t\tindexName: indexName,\n\t}\n\tindexers := cache.Indexers{}\n\tif indexName != \"\" \u0026\u0026 indexFunc != nil {\n\t\tindexers[indexName] = c.objInfoIndexFunc\n\t}\n\tc.store = cache.NewIndexer(objInfoKeyFunc, indexers)\n\n\t// Unit tests don't use informers\n\tif informer != nil {\n\t\tinformer.AddEventHandler(\n\t\t\tcache.ResourceEventHandlerFuncs{\n\t\t\t\tAddFunc: c.add,\n\t\t\t\tUpdateFunc: c.update,\n\t\t\t\tDeleteFunc: c.delete,\n\t\t\t},\n\t\t)\n\t}\n\treturn c\n}","line":{"from":131,"to":155}} {"id":100010962,"name":"add","signature":"func (c *assumeCache) add(obj interface{})","file":"pkg/scheduler/framework/plugins/volumebinding/assume_cache.go","code":"func (c *assumeCache) add(obj interface{}) {\n\tif obj == nil {\n\t\treturn\n\t}\n\n\tname, err := cache.MetaNamespaceKeyFunc(obj)\n\tif err != nil {\n\t\tklog.ErrorS(\u0026errObjectName{err}, \"Add failed\")\n\t\treturn\n\t}\n\n\tc.rwMutex.Lock()\n\tdefer c.rwMutex.Unlock()\n\n\tif objInfo, _ := c.getObjInfo(name); objInfo != nil {\n\t\tnewVersion, err := c.getObjVersion(name, obj)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Add failed: couldn't get object version\")\n\t\t\treturn\n\t\t}\n\n\t\tstoredVersion, err := c.getObjVersion(name, objInfo.latestObj)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Add failed: couldn't get stored object version\")\n\t\t\treturn\n\t\t}\n\n\t\t// Only update object if version is newer.\n\t\t// This is so we don't override assumed objects due to informer resync.\n\t\tif newVersion \u003c= storedVersion {\n\t\t\tklog.V(10).InfoS(\"Skip adding object to assume cache because version is not newer than storedVersion\", \"description\", c.description, \"cacheKey\", name, \"newVersion\", newVersion, \"storedVersion\", storedVersion)\n\t\t\treturn\n\t\t}\n\t}\n\n\tobjInfo := \u0026objInfo{name: name, latestObj: obj, apiObj: obj}\n\tif err = c.store.Update(objInfo); err != nil {\n\t\tklog.InfoS(\"Error occurred while updating stored object\", \"err\", err)\n\t} else {\n\t\tklog.V(10).InfoS(\"Adding object to assume cache\", \"description\", c.description, \"cacheKey\", name, \"assumeCache\", obj)\n\t}\n}","line":{"from":157,"to":198}} {"id":100010963,"name":"update","signature":"func (c *assumeCache) update(oldObj interface{}, newObj interface{})","file":"pkg/scheduler/framework/plugins/volumebinding/assume_cache.go","code":"func (c *assumeCache) update(oldObj interface{}, newObj interface{}) {\n\tc.add(newObj)\n}","line":{"from":200,"to":202}} {"id":100010964,"name":"delete","signature":"func (c *assumeCache) delete(obj interface{})","file":"pkg/scheduler/framework/plugins/volumebinding/assume_cache.go","code":"func (c *assumeCache) delete(obj interface{}) {\n\tif obj == nil {\n\t\treturn\n\t}\n\n\tname, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)\n\tif err != nil {\n\t\tklog.ErrorS(\u0026errObjectName{err}, \"Failed to delete\")\n\t\treturn\n\t}\n\n\tc.rwMutex.Lock()\n\tdefer c.rwMutex.Unlock()\n\n\tobjInfo := \u0026objInfo{name: name}\n\terr = c.store.Delete(objInfo)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to delete\", \"description\", c.description, \"cacheKey\", name)\n\t}\n}","line":{"from":204,"to":223}} {"id":100010965,"name":"getObjVersion","signature":"func (c *assumeCache) getObjVersion(name string, obj interface{}) (int64, error)","file":"pkg/scheduler/framework/plugins/volumebinding/assume_cache.go","code":"func (c *assumeCache) getObjVersion(name string, obj interface{}) (int64, error) {\n\tobjAccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\tobjResourceVersion, err := strconv.ParseInt(objAccessor.GetResourceVersion(), 10, 64)\n\tif err != nil {\n\t\treturn -1, fmt.Errorf(\"error parsing ResourceVersion %q for %v %q: %s\", objAccessor.GetResourceVersion(), c.description, name, err)\n\t}\n\treturn objResourceVersion, nil\n}","line":{"from":225,"to":236}} {"id":100010966,"name":"getObjInfo","signature":"func (c *assumeCache) getObjInfo(name string) (*objInfo, error)","file":"pkg/scheduler/framework/plugins/volumebinding/assume_cache.go","code":"func (c *assumeCache) getObjInfo(name string) (*objInfo, error) {\n\tobj, ok, err := c.store.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !ok {\n\t\treturn nil, \u0026errNotFound{c.description, name}\n\t}\n\n\tobjInfo, ok := obj.(*objInfo)\n\tif !ok {\n\t\treturn nil, \u0026errWrongType{\"objInfo\", obj}\n\t}\n\treturn objInfo, nil\n}","line":{"from":238,"to":252}} {"id":100010967,"name":"Get","signature":"func (c *assumeCache) Get(objName string) (interface{}, error)","file":"pkg/scheduler/framework/plugins/volumebinding/assume_cache.go","code":"func (c *assumeCache) Get(objName string) (interface{}, error) {\n\tc.rwMutex.RLock()\n\tdefer c.rwMutex.RUnlock()\n\n\tobjInfo, err := c.getObjInfo(objName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn objInfo.latestObj, nil\n}","line":{"from":254,"to":263}} {"id":100010968,"name":"GetAPIObj","signature":"func (c *assumeCache) GetAPIObj(objName string) (interface{}, error)","file":"pkg/scheduler/framework/plugins/volumebinding/assume_cache.go","code":"func (c *assumeCache) GetAPIObj(objName string) (interface{}, error) {\n\tc.rwMutex.RLock()\n\tdefer c.rwMutex.RUnlock()\n\n\tobjInfo, err := c.getObjInfo(objName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn objInfo.apiObj, nil\n}","line":{"from":265,"to":274}} {"id":100010969,"name":"List","signature":"func (c *assumeCache) List(indexObj interface{}) []interface{}","file":"pkg/scheduler/framework/plugins/volumebinding/assume_cache.go","code":"func (c *assumeCache) List(indexObj interface{}) []interface{} {\n\tc.rwMutex.RLock()\n\tdefer c.rwMutex.RUnlock()\n\n\tallObjs := []interface{}{}\n\tobjs, err := c.store.Index(c.indexName, \u0026objInfo{latestObj: indexObj})\n\tif err != nil {\n\t\tklog.ErrorS(err, \"List index error\")\n\t\treturn nil\n\t}\n\n\tfor _, obj := range objs {\n\t\tobjInfo, ok := obj.(*objInfo)\n\t\tif !ok {\n\t\t\tklog.ErrorS(\u0026errWrongType{\"objInfo\", obj}, \"List error\")\n\t\t\tcontinue\n\t\t}\n\t\tallObjs = append(allObjs, objInfo.latestObj)\n\t}\n\treturn allObjs\n}","line":{"from":276,"to":296}} {"id":100010970,"name":"Assume","signature":"func (c *assumeCache) Assume(obj interface{}) error","file":"pkg/scheduler/framework/plugins/volumebinding/assume_cache.go","code":"func (c *assumeCache) Assume(obj interface{}) error {\n\tname, err := cache.MetaNamespaceKeyFunc(obj)\n\tif err != nil {\n\t\treturn \u0026errObjectName{err}\n\t}\n\n\tc.rwMutex.Lock()\n\tdefer c.rwMutex.Unlock()\n\n\tobjInfo, err := c.getObjInfo(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnewVersion, err := c.getObjVersion(name, obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstoredVersion, err := c.getObjVersion(name, objInfo.latestObj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif newVersion \u003c storedVersion {\n\t\treturn fmt.Errorf(\"%v %q is out of sync (stored: %d, assume: %d)\", c.description, name, storedVersion, newVersion)\n\t}\n\n\t// Only update the cached object\n\tobjInfo.latestObj = obj\n\tklog.V(4).InfoS(\"Assumed object\", \"description\", c.description, \"cacheKey\", name, \"version\", newVersion)\n\treturn nil\n}","line":{"from":298,"to":330}} {"id":100010971,"name":"Restore","signature":"func (c *assumeCache) Restore(objName string)","file":"pkg/scheduler/framework/plugins/volumebinding/assume_cache.go","code":"func (c *assumeCache) Restore(objName string) {\n\tc.rwMutex.Lock()\n\tdefer c.rwMutex.Unlock()\n\n\tobjInfo, err := c.getObjInfo(objName)\n\tif err != nil {\n\t\t// This could be expected if object got deleted\n\t\tklog.V(5).InfoS(\"Restore object\", \"description\", c.description, \"cacheKey\", objName, \"err\", err)\n\t} else {\n\t\tobjInfo.latestObj = objInfo.apiObj\n\t\tklog.V(4).InfoS(\"Restored object\", \"description\", c.description, \"cacheKey\", objName)\n\t}\n}","line":{"from":332,"to":344}} {"id":100010972,"name":"pvStorageClassIndexFunc","signature":"func pvStorageClassIndexFunc(obj interface{}) ([]string, error)","file":"pkg/scheduler/framework/plugins/volumebinding/assume_cache.go","code":"func pvStorageClassIndexFunc(obj interface{}) ([]string, error) {\n\tif pv, ok := obj.(*v1.PersistentVolume); ok {\n\t\treturn []string{storagehelpers.GetPersistentVolumeClass(pv)}, nil\n\t}\n\treturn []string{\"\"}, fmt.Errorf(\"object is not a v1.PersistentVolume: %v\", obj)\n}","line":{"from":359,"to":364}} {"id":100010973,"name":"NewPVAssumeCache","signature":"func NewPVAssumeCache(informer cache.SharedIndexInformer) PVAssumeCache","file":"pkg/scheduler/framework/plugins/volumebinding/assume_cache.go","code":"// NewPVAssumeCache creates a PV assume cache.\nfunc NewPVAssumeCache(informer cache.SharedIndexInformer) PVAssumeCache {\n\treturn \u0026pvAssumeCache{NewAssumeCache(informer, \"v1.PersistentVolume\", \"storageclass\", pvStorageClassIndexFunc)}\n}","line":{"from":366,"to":369}} {"id":100010974,"name":"GetPV","signature":"func (c *pvAssumeCache) GetPV(pvName string) (*v1.PersistentVolume, error)","file":"pkg/scheduler/framework/plugins/volumebinding/assume_cache.go","code":"func (c *pvAssumeCache) GetPV(pvName string) (*v1.PersistentVolume, error) {\n\tobj, err := c.Get(pvName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpv, ok := obj.(*v1.PersistentVolume)\n\tif !ok {\n\t\treturn nil, \u0026errWrongType{\"v1.PersistentVolume\", obj}\n\t}\n\treturn pv, nil\n}","line":{"from":371,"to":382}} {"id":100010975,"name":"GetAPIPV","signature":"func (c *pvAssumeCache) GetAPIPV(pvName string) (*v1.PersistentVolume, error)","file":"pkg/scheduler/framework/plugins/volumebinding/assume_cache.go","code":"func (c *pvAssumeCache) GetAPIPV(pvName string) (*v1.PersistentVolume, error) {\n\tobj, err := c.GetAPIObj(pvName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpv, ok := obj.(*v1.PersistentVolume)\n\tif !ok {\n\t\treturn nil, \u0026errWrongType{\"v1.PersistentVolume\", obj}\n\t}\n\treturn pv, nil\n}","line":{"from":384,"to":394}} {"id":100010976,"name":"ListPVs","signature":"func (c *pvAssumeCache) ListPVs(storageClassName string) []*v1.PersistentVolume","file":"pkg/scheduler/framework/plugins/volumebinding/assume_cache.go","code":"func (c *pvAssumeCache) ListPVs(storageClassName string) []*v1.PersistentVolume {\n\tobjs := c.List(\u0026v1.PersistentVolume{\n\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\tStorageClassName: storageClassName,\n\t\t},\n\t})\n\tpvs := []*v1.PersistentVolume{}\n\tfor _, obj := range objs {\n\t\tpv, ok := obj.(*v1.PersistentVolume)\n\t\tif !ok {\n\t\t\tklog.ErrorS(\u0026errWrongType{\"v1.PersistentVolume\", obj}, \"ListPVs\")\n\t\t\tcontinue\n\t\t}\n\t\tpvs = append(pvs, pv)\n\t}\n\treturn pvs\n}","line":{"from":396,"to":412}} {"id":100010977,"name":"NewPVCAssumeCache","signature":"func NewPVCAssumeCache(informer cache.SharedIndexInformer) PVCAssumeCache","file":"pkg/scheduler/framework/plugins/volumebinding/assume_cache.go","code":"// NewPVCAssumeCache creates a PVC assume cache.\nfunc NewPVCAssumeCache(informer cache.SharedIndexInformer) PVCAssumeCache {\n\treturn \u0026pvcAssumeCache{NewAssumeCache(informer, \"v1.PersistentVolumeClaim\", \"\", nil)}\n}","line":{"from":428,"to":431}} {"id":100010978,"name":"GetPVC","signature":"func (c *pvcAssumeCache) GetPVC(pvcKey string) (*v1.PersistentVolumeClaim, error)","file":"pkg/scheduler/framework/plugins/volumebinding/assume_cache.go","code":"func (c *pvcAssumeCache) GetPVC(pvcKey string) (*v1.PersistentVolumeClaim, error) {\n\tobj, err := c.Get(pvcKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpvc, ok := obj.(*v1.PersistentVolumeClaim)\n\tif !ok {\n\t\treturn nil, \u0026errWrongType{\"v1.PersistentVolumeClaim\", obj}\n\t}\n\treturn pvc, nil\n}","line":{"from":433,"to":444}} {"id":100010979,"name":"GetAPIPVC","signature":"func (c *pvcAssumeCache) GetAPIPVC(pvcKey string) (*v1.PersistentVolumeClaim, error)","file":"pkg/scheduler/framework/plugins/volumebinding/assume_cache.go","code":"func (c *pvcAssumeCache) GetAPIPVC(pvcKey string) (*v1.PersistentVolumeClaim, error) {\n\tobj, err := c.GetAPIObj(pvcKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpvc, ok := obj.(*v1.PersistentVolumeClaim)\n\tif !ok {\n\t\treturn nil, \u0026errWrongType{\"v1.PersistentVolumeClaim\", obj}\n\t}\n\treturn pvc, nil\n}","line":{"from":446,"to":456}} {"id":100010980,"name":"Len","signature":"func (reasons ConflictReasons) Len() int { return len(reasons) }","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"func (reasons ConflictReasons) Len() int { return len(reasons) }","line":{"from":58,"to":58}} {"id":100010981,"name":"Less","signature":"func (reasons ConflictReasons) Less(i, j int) bool { return reasons[i] \u003c reasons[j] }","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"func (reasons ConflictReasons) Less(i, j int) bool { return reasons[i] \u003c reasons[j] }","line":{"from":59,"to":59}} {"id":100010982,"name":"Swap","signature":"func (reasons ConflictReasons) Swap(i, j int) { reasons[i], reasons[j] = reasons[j], reasons[i] }","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"func (reasons ConflictReasons) Swap(i, j int) { reasons[i], reasons[j] = reasons[j], reasons[i] }","line":{"from":60,"to":60}} {"id":100010983,"name":"StorageClassName","signature":"func (b *BindingInfo) StorageClassName() string","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"// StorageClassName returns the name of the storage class.\nfunc (b *BindingInfo) StorageClassName() string {\n\treturn b.pv.Spec.StorageClassName\n}","line":{"from":82,"to":85}} {"id":100010984,"name":"StorageResource","signature":"func (b *BindingInfo) StorageResource() *StorageResource","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"// StorageResource returns storage resource.\nfunc (b *BindingInfo) StorageResource() *StorageResource {\n\t// both fields are mandatory\n\trequestedQty := b.pvc.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]\n\tcapacityQty := b.pv.Spec.Capacity[v1.ResourceName(v1.ResourceStorage)]\n\treturn \u0026StorageResource{\n\t\tRequested: requestedQty.Value(),\n\t\tCapacity: capacityQty.Value(),\n\t}\n}","line":{"from":93,"to":102}} {"id":100010985,"name":"NewVolumeBinder","signature":"func NewVolumeBinder(","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"// NewVolumeBinder sets up all the caches needed for the scheduler to make volume binding decisions.\n//\n// capacityCheck determines how storage capacity is checked (CSIStorageCapacity feature).\nfunc NewVolumeBinder(\n\tkubeClient clientset.Interface,\n\tpodInformer coreinformers.PodInformer,\n\tnodeInformer coreinformers.NodeInformer,\n\tcsiNodeInformer storageinformers.CSINodeInformer,\n\tpvcInformer coreinformers.PersistentVolumeClaimInformer,\n\tpvInformer coreinformers.PersistentVolumeInformer,\n\tstorageClassInformer storageinformers.StorageClassInformer,\n\tcapacityCheck CapacityCheck,\n\tbindTimeout time.Duration) SchedulerVolumeBinder {\n\tb := \u0026volumeBinder{\n\t\tkubeClient: kubeClient,\n\t\tpodLister: podInformer.Lister(),\n\t\tclassLister: storageClassInformer.Lister(),\n\t\tnodeLister: nodeInformer.Lister(),\n\t\tcsiNodeLister: csiNodeInformer.Lister(),\n\t\tpvcCache: NewPVCAssumeCache(pvcInformer.Informer()),\n\t\tpvCache: NewPVAssumeCache(pvInformer.Informer()),\n\t\tbindTimeout: bindTimeout,\n\t\ttranslator: csitrans.New(),\n\t}\n\n\tb.csiDriverLister = capacityCheck.CSIDriverInformer.Lister()\n\tb.csiStorageCapacityLister = capacityCheck.CSIStorageCapacityInformer.Lister()\n\n\treturn b\n}","line":{"from":243,"to":272}} {"id":100010986,"name":"FindPodVolumes","signature":"func (b *volumeBinder) FindPodVolumes(pod *v1.Pod, podVolumeClaims *PodVolumeClaims, node *v1.Node) (podVolumes *PodVolumes, reasons ConflictReasons, err error)","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"// FindPodVolumes finds the matching PVs for PVCs and nodes to provision PVs\n// for the given pod and node. If the node does not fit, conflict reasons are\n// returned.\nfunc (b *volumeBinder) FindPodVolumes(pod *v1.Pod, podVolumeClaims *PodVolumeClaims, node *v1.Node) (podVolumes *PodVolumes, reasons ConflictReasons, err error) {\n\tpodVolumes = \u0026PodVolumes{}\n\n\t// Warning: Below log needs high verbosity as it can be printed several times (#60933).\n\tklog.V(5).InfoS(\"FindPodVolumes\", \"pod\", klog.KObj(pod), \"node\", klog.KObj(node))\n\n\t// Initialize to true for pods that don't have volumes. These\n\t// booleans get translated into reason strings when the function\n\t// returns without an error.\n\tunboundVolumesSatisfied := true\n\tboundVolumesSatisfied := true\n\tsufficientStorage := true\n\tboundPVsFound := true\n\tdefer func() {\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif !boundVolumesSatisfied {\n\t\t\treasons = append(reasons, ErrReasonNodeConflict)\n\t\t}\n\t\tif !unboundVolumesSatisfied {\n\t\t\treasons = append(reasons, ErrReasonBindConflict)\n\t\t}\n\t\tif !sufficientStorage {\n\t\t\treasons = append(reasons, ErrReasonNotEnoughSpace)\n\t\t}\n\t\tif !boundPVsFound {\n\t\t\treasons = append(reasons, ErrReasonPVNotExist)\n\t\t}\n\t}()\n\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tmetrics.VolumeSchedulingStageFailed.WithLabelValues(\"predicate\").Inc()\n\t\t}\n\t}()\n\n\tvar (\n\t\tstaticBindings []*BindingInfo\n\t\tdynamicProvisions []*v1.PersistentVolumeClaim\n\t)\n\tdefer func() {\n\t\t// Although we do not distinguish nil from empty in this function, for\n\t\t// easier testing, we normalize empty to nil.\n\t\tif len(staticBindings) == 0 {\n\t\t\tstaticBindings = nil\n\t\t}\n\t\tif len(dynamicProvisions) == 0 {\n\t\t\tdynamicProvisions = nil\n\t\t}\n\t\tpodVolumes.StaticBindings = staticBindings\n\t\tpodVolumes.DynamicProvisions = dynamicProvisions\n\t}()\n\n\t// Check PV node affinity on bound volumes\n\tif len(podVolumeClaims.boundClaims) \u003e 0 {\n\t\tboundVolumesSatisfied, boundPVsFound, err = b.checkBoundClaims(podVolumeClaims.boundClaims, node, pod)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Find matching volumes and node for unbound claims\n\tif len(podVolumeClaims.unboundClaimsDelayBinding) \u003e 0 {\n\t\tvar (\n\t\t\tclaimsToFindMatching []*v1.PersistentVolumeClaim\n\t\t\tclaimsToProvision []*v1.PersistentVolumeClaim\n\t\t)\n\n\t\t// Filter out claims to provision\n\t\tfor _, claim := range podVolumeClaims.unboundClaimsDelayBinding {\n\t\t\tif selectedNode, ok := claim.Annotations[volume.AnnSelectedNode]; ok {\n\t\t\t\tif selectedNode != node.Name {\n\t\t\t\t\t// Fast path, skip unmatched node.\n\t\t\t\t\tunboundVolumesSatisfied = false\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tclaimsToProvision = append(claimsToProvision, claim)\n\t\t\t} else {\n\t\t\t\tclaimsToFindMatching = append(claimsToFindMatching, claim)\n\t\t\t}\n\t\t}\n\n\t\t// Find matching volumes\n\t\tif len(claimsToFindMatching) \u003e 0 {\n\t\t\tvar unboundClaims []*v1.PersistentVolumeClaim\n\t\t\tunboundVolumesSatisfied, staticBindings, unboundClaims, err = b.findMatchingVolumes(pod, claimsToFindMatching, podVolumeClaims.unboundVolumesDelayBinding, node)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tclaimsToProvision = append(claimsToProvision, unboundClaims...)\n\t\t}\n\n\t\t// Check for claims to provision. This is the first time where we potentially\n\t\t// find out that storage is not sufficient for the node.\n\t\tif len(claimsToProvision) \u003e 0 {\n\t\t\tunboundVolumesSatisfied, sufficientStorage, dynamicProvisions, err = b.checkVolumeProvisions(pod, claimsToProvision, node)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}","line":{"from":274,"to":381}} {"id":100010987,"name":"GetEligibleNodes","signature":"func (b *volumeBinder) GetEligibleNodes(boundClaims []*v1.PersistentVolumeClaim) (eligibleNodes sets.String)","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"// GetEligibleNodes checks the existing bound claims of the pod to determine if the list of nodes can be\n// potentially reduced down to a subset of eligible nodes based on the bound claims which then can be used\n// in subsequent scheduling stages.\n//\n// Returning 'nil' for eligibleNodes indicates that such eligible node reduction cannot be made and all nodes\n// should be considered.\nfunc (b *volumeBinder) GetEligibleNodes(boundClaims []*v1.PersistentVolumeClaim) (eligibleNodes sets.String) {\n\tif len(boundClaims) == 0 {\n\t\treturn\n\t}\n\n\tvar errs []error\n\tfor _, pvc := range boundClaims {\n\t\tpvName := pvc.Spec.VolumeName\n\t\tpv, err := b.pvCache.GetPV(pvName)\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t\tcontinue\n\t\t}\n\n\t\t// if the PersistentVolume is local and has node affinity matching specific node(s),\n\t\t// add them to the eligible nodes\n\t\tnodeNames := util.GetLocalPersistentVolumeNodeNames(pv)\n\t\tif len(nodeNames) != 0 {\n\t\t\t// on the first found list of eligible nodes for the local PersistentVolume,\n\t\t\t// insert to the eligible node set.\n\t\t\tif eligibleNodes == nil {\n\t\t\t\teligibleNodes = sets.NewString(nodeNames...)\n\t\t\t} else {\n\t\t\t\t// for subsequent finding of eligible nodes for the local PersistentVolume,\n\t\t\t\t// take the intersection of the nodes with the existing eligible nodes\n\t\t\t\t// for cases if PV1 has node affinity to node1 and PV2 has node affinity to node2,\n\t\t\t\t// then the eligible node list should be empty.\n\t\t\t\teligibleNodes = eligibleNodes.Intersection(sets.NewString(nodeNames...))\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(errs) \u003e 0 {\n\t\tklog.V(4).InfoS(\"GetEligibleNodes: one or more error occurred finding eligible nodes\", \"error\", errs)\n\t\treturn nil\n\t}\n\n\tif eligibleNodes != nil {\n\t\tklog.V(4).InfoS(\"GetEligibleNodes: reduced down eligible nodes\", \"nodes\", eligibleNodes)\n\t}\n\treturn\n}","line":{"from":383,"to":430}} {"id":100010988,"name":"AssumePodVolumes","signature":"func (b *volumeBinder) AssumePodVolumes(assumedPod *v1.Pod, nodeName string, podVolumes *PodVolumes) (allFullyBound bool, err error)","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"// AssumePodVolumes will take the matching PVs and PVCs to provision in pod's\n// volume information for the chosen node, and:\n// 1. Update the pvCache with the new prebound PV.\n// 2. Update the pvcCache with the new PVCs with annotations set\n// 3. Update PodVolumes again with cached API updates for PVs and PVCs.\nfunc (b *volumeBinder) AssumePodVolumes(assumedPod *v1.Pod, nodeName string, podVolumes *PodVolumes) (allFullyBound bool, err error) {\n\tklog.V(4).InfoS(\"AssumePodVolumes\", \"pod\", klog.KObj(assumedPod), \"node\", klog.KRef(\"\", nodeName))\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tmetrics.VolumeSchedulingStageFailed.WithLabelValues(\"assume\").Inc()\n\t\t}\n\t}()\n\n\tif allBound := b.arePodVolumesBound(assumedPod); allBound {\n\t\tklog.V(4).InfoS(\"AssumePodVolumes: all PVCs bound and nothing to do\", \"pod\", klog.KObj(assumedPod), \"node\", klog.KRef(\"\", nodeName))\n\t\treturn true, nil\n\t}\n\n\t// Assume PV\n\tnewBindings := []*BindingInfo{}\n\tfor _, binding := range podVolumes.StaticBindings {\n\t\tnewPV, dirty, err := volume.GetBindVolumeToClaim(binding.pv, binding.pvc)\n\t\tklog.V(5).InfoS(\"AssumePodVolumes: GetBindVolumeToClaim\",\n\t\t\t\"pod\", klog.KObj(assumedPod),\n\t\t\t\"PV\", klog.KObj(binding.pv),\n\t\t\t\"PVC\", klog.KObj(binding.pvc),\n\t\t\t\"newPV\", klog.KObj(newPV),\n\t\t\t\"dirty\", dirty,\n\t\t)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"AssumePodVolumes: fail to GetBindVolumeToClaim\")\n\t\t\tb.revertAssumedPVs(newBindings)\n\t\t\treturn false, err\n\t\t}\n\t\t// TODO: can we assume every time?\n\t\tif dirty {\n\t\t\terr = b.pvCache.Assume(newPV)\n\t\t\tif err != nil {\n\t\t\t\tb.revertAssumedPVs(newBindings)\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}\n\t\tnewBindings = append(newBindings, \u0026BindingInfo{pv: newPV, pvc: binding.pvc})\n\t}\n\n\t// Assume PVCs\n\tnewProvisionedPVCs := []*v1.PersistentVolumeClaim{}\n\tfor _, claim := range podVolumes.DynamicProvisions {\n\t\t// The claims from method args can be pointing to watcher cache. We must not\n\t\t// modify these, therefore create a copy.\n\t\tclaimClone := claim.DeepCopy()\n\t\tmetav1.SetMetaDataAnnotation(\u0026claimClone.ObjectMeta, volume.AnnSelectedNode, nodeName)\n\t\terr = b.pvcCache.Assume(claimClone)\n\t\tif err != nil {\n\t\t\tb.revertAssumedPVs(newBindings)\n\t\t\tb.revertAssumedPVCs(newProvisionedPVCs)\n\t\t\treturn\n\t\t}\n\n\t\tnewProvisionedPVCs = append(newProvisionedPVCs, claimClone)\n\t}\n\n\tpodVolumes.StaticBindings = newBindings\n\tpodVolumes.DynamicProvisions = newProvisionedPVCs\n\treturn\n}","line":{"from":432,"to":497}} {"id":100010989,"name":"RevertAssumedPodVolumes","signature":"func (b *volumeBinder) RevertAssumedPodVolumes(podVolumes *PodVolumes)","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"// RevertAssumedPodVolumes will revert assumed PV and PVC cache.\nfunc (b *volumeBinder) RevertAssumedPodVolumes(podVolumes *PodVolumes) {\n\tb.revertAssumedPVs(podVolumes.StaticBindings)\n\tb.revertAssumedPVCs(podVolumes.DynamicProvisions)\n}","line":{"from":499,"to":503}} {"id":100010990,"name":"BindPodVolumes","signature":"func (b *volumeBinder) BindPodVolumes(ctx context.Context, assumedPod *v1.Pod, podVolumes *PodVolumes) (err error)","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"// BindPodVolumes gets the cached bindings and PVCs to provision in pod's volumes information,\n// makes the API update for those PVs/PVCs, and waits for the PVCs to be completely bound\n// by the PV controller.\nfunc (b *volumeBinder) BindPodVolumes(ctx context.Context, assumedPod *v1.Pod, podVolumes *PodVolumes) (err error) {\n\tklog.V(4).InfoS(\"BindPodVolumes\", \"pod\", klog.KObj(assumedPod), \"node\", klog.KRef(\"\", assumedPod.Spec.NodeName))\n\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tmetrics.VolumeSchedulingStageFailed.WithLabelValues(\"bind\").Inc()\n\t\t}\n\t}()\n\n\tbindings := podVolumes.StaticBindings\n\tclaimsToProvision := podVolumes.DynamicProvisions\n\n\t// Start API operations\n\terr = b.bindAPIUpdate(ctx, assumedPod, bindings, claimsToProvision)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = wait.Poll(time.Second, b.bindTimeout, func() (bool, error) {\n\t\tb, err := b.checkBindings(assumedPod, bindings, claimsToProvision)\n\t\treturn b, err\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"binding volumes: %w\", err)\n\t}\n\treturn nil\n}","line":{"from":505,"to":534}} {"id":100010991,"name":"getPodName","signature":"func getPodName(pod *v1.Pod) string","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"func getPodName(pod *v1.Pod) string {\n\treturn pod.Namespace + \"/\" + pod.Name\n}","line":{"from":536,"to":538}} {"id":100010992,"name":"getPVCName","signature":"func getPVCName(pvc *v1.PersistentVolumeClaim) string","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"func getPVCName(pvc *v1.PersistentVolumeClaim) string {\n\treturn pvc.Namespace + \"/\" + pvc.Name\n}","line":{"from":540,"to":542}} {"id":100010993,"name":"bindAPIUpdate","signature":"func (b *volumeBinder) bindAPIUpdate(ctx context.Context, pod *v1.Pod, bindings []*BindingInfo, claimsToProvision []*v1.PersistentVolumeClaim) error","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"// bindAPIUpdate makes the API update for those PVs/PVCs.\nfunc (b *volumeBinder) bindAPIUpdate(ctx context.Context, pod *v1.Pod, bindings []*BindingInfo, claimsToProvision []*v1.PersistentVolumeClaim) error {\n\tpodName := getPodName(pod)\n\tif bindings == nil {\n\t\treturn fmt.Errorf(\"failed to get cached bindings for pod %q\", podName)\n\t}\n\tif claimsToProvision == nil {\n\t\treturn fmt.Errorf(\"failed to get cached claims to provision for pod %q\", podName)\n\t}\n\n\tlastProcessedBinding := 0\n\tlastProcessedProvisioning := 0\n\tdefer func() {\n\t\t// only revert assumed cached updates for volumes we haven't successfully bound\n\t\tif lastProcessedBinding \u003c len(bindings) {\n\t\t\tb.revertAssumedPVs(bindings[lastProcessedBinding:])\n\t\t}\n\t\t// only revert assumed cached updates for claims we haven't updated,\n\t\tif lastProcessedProvisioning \u003c len(claimsToProvision) {\n\t\t\tb.revertAssumedPVCs(claimsToProvision[lastProcessedProvisioning:])\n\t\t}\n\t}()\n\n\tvar (\n\t\tbinding *BindingInfo\n\t\ti int\n\t\tclaim *v1.PersistentVolumeClaim\n\t)\n\n\t// Do the actual prebinding. Let the PV controller take care of the rest\n\t// There is no API rollback if the actual binding fails\n\tfor _, binding = range bindings {\n\t\t// TODO: does it hurt if we make an api call and nothing needs to be updated?\n\t\tklog.V(5).InfoS(\"Updating PersistentVolume: binding to claim\", \"pod\", klog.KObj(pod), \"PV\", klog.KObj(binding.pv), \"PVC\", klog.KObj(binding.pvc))\n\t\tnewPV, err := b.kubeClient.CoreV1().PersistentVolumes().Update(ctx, binding.pv, metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\tklog.V(4).InfoS(\"Updating PersistentVolume: binding to claim failed\", \"pod\", klog.KObj(pod), \"PV\", klog.KObj(binding.pv), \"PVC\", klog.KObj(binding.pvc), \"err\", err)\n\t\t\treturn err\n\t\t}\n\n\t\tklog.V(2).InfoS(\"Updated PersistentVolume with claim. Waiting for binding to complete\", \"pod\", klog.KObj(pod), \"PV\", klog.KObj(binding.pv), \"PVC\", klog.KObj(binding.pvc))\n\t\t// Save updated object from apiserver for later checking.\n\t\tbinding.pv = newPV\n\t\tlastProcessedBinding++\n\t}\n\n\t// Update claims objects to trigger volume provisioning. Let the PV controller take care of the rest\n\t// PV controller is expected to signal back by removing related annotations if actual provisioning fails\n\tfor i, claim = range claimsToProvision {\n\t\tklog.V(5).InfoS(\"Updating claims objects to trigger volume provisioning\", \"pod\", klog.KObj(pod), \"PVC\", klog.KObj(claim))\n\t\tnewClaim, err := b.kubeClient.CoreV1().PersistentVolumeClaims(claim.Namespace).Update(ctx, claim, metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\tklog.V(4).InfoS(\"Updating PersistentVolumeClaim: binding to volume failed\", \"PVC\", klog.KObj(claim), \"err\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t// Save updated object from apiserver for later checking.\n\t\tclaimsToProvision[i] = newClaim\n\t\tlastProcessedProvisioning++\n\t}\n\n\treturn nil\n}","line":{"from":544,"to":606}} {"id":100010994,"name":"checkBindings","signature":"func (b *volumeBinder) checkBindings(pod *v1.Pod, bindings []*BindingInfo, claimsToProvision []*v1.PersistentVolumeClaim) (bool, error)","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"// checkBindings runs through all the PVCs in the Pod and checks:\n// * if the PVC is fully bound\n// * if there are any conditions that require binding to fail and be retried\n//\n// It returns true when all of the Pod's PVCs are fully bound, and error if\n// binding (and scheduling) needs to be retried\n// Note that it checks on API objects not PV/PVC cache, this is because\n// PV/PVC cache can be assumed again in main scheduler loop, we must check\n// latest state in API server which are shared with PV controller and\n// provisioners\nfunc (b *volumeBinder) checkBindings(pod *v1.Pod, bindings []*BindingInfo, claimsToProvision []*v1.PersistentVolumeClaim) (bool, error) {\n\tpodName := getPodName(pod)\n\tif bindings == nil {\n\t\treturn false, fmt.Errorf(\"failed to get cached bindings for pod %q\", podName)\n\t}\n\tif claimsToProvision == nil {\n\t\treturn false, fmt.Errorf(\"failed to get cached claims to provision for pod %q\", podName)\n\t}\n\n\tnode, err := b.nodeLister.Get(pod.Spec.NodeName)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"failed to get node %q: %w\", pod.Spec.NodeName, err)\n\t}\n\n\tcsiNode, err := b.csiNodeLister.Get(node.Name)\n\tif err != nil {\n\t\t// TODO: return the error once CSINode is created by default\n\t\tklog.V(4).InfoS(\"Could not get a CSINode object for the node\", \"node\", klog.KObj(node), \"err\", err)\n\t}\n\n\t// Check for any conditions that might require scheduling retry\n\n\t// When pod is deleted, binding operation should be cancelled. There is no\n\t// need to check PV/PVC bindings any more.\n\t_, err = b.podLister.Pods(pod.Namespace).Get(pod.Name)\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\treturn false, fmt.Errorf(\"pod does not exist any more: %w\", err)\n\t\t}\n\t\tklog.ErrorS(err, \"Failed to get pod from the lister\", \"pod\", klog.KObj(pod))\n\t}\n\n\tfor _, binding := range bindings {\n\t\tpv, err := b.pvCache.GetAPIPV(binding.pv.Name)\n\t\tif err != nil {\n\t\t\treturn false, fmt.Errorf(\"failed to check binding: %w\", err)\n\t\t}\n\n\t\tpvc, err := b.pvcCache.GetAPIPVC(getPVCName(binding.pvc))\n\t\tif err != nil {\n\t\t\treturn false, fmt.Errorf(\"failed to check binding: %w\", err)\n\t\t}\n\n\t\t// Because we updated PV in apiserver, skip if API object is older\n\t\t// and wait for new API object propagated from apiserver.\n\t\tif versioner.CompareResourceVersion(binding.pv, pv) \u003e 0 {\n\t\t\treturn false, nil\n\t\t}\n\n\t\tpv, err = b.tryTranslatePVToCSI(pv, csiNode)\n\t\tif err != nil {\n\t\t\treturn false, fmt.Errorf(\"failed to translate pv to csi: %w\", err)\n\t\t}\n\n\t\t// Check PV's node affinity (the node might not have the proper label)\n\t\tif err := volume.CheckNodeAffinity(pv, node.Labels); err != nil {\n\t\t\treturn false, fmt.Errorf(\"pv %q node affinity doesn't match node %q: %w\", pv.Name, node.Name, err)\n\t\t}\n\n\t\t// Check if pv.ClaimRef got dropped by unbindVolume()\n\t\tif pv.Spec.ClaimRef == nil || pv.Spec.ClaimRef.UID == \"\" {\n\t\t\treturn false, fmt.Errorf(\"ClaimRef got reset for pv %q\", pv.Name)\n\t\t}\n\n\t\t// Check if pvc is fully bound\n\t\tif !b.isPVCFullyBound(pvc) {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\tfor _, claim := range claimsToProvision {\n\t\tpvc, err := b.pvcCache.GetAPIPVC(getPVCName(claim))\n\t\tif err != nil {\n\t\t\treturn false, fmt.Errorf(\"failed to check provisioning pvc: %w\", err)\n\t\t}\n\n\t\t// Because we updated PVC in apiserver, skip if API object is older\n\t\t// and wait for new API object propagated from apiserver.\n\t\tif versioner.CompareResourceVersion(claim, pvc) \u003e 0 {\n\t\t\treturn false, nil\n\t\t}\n\n\t\t// Check if selectedNode annotation is still set\n\t\tif pvc.Annotations == nil {\n\t\t\treturn false, fmt.Errorf(\"selectedNode annotation reset for PVC %q\", pvc.Name)\n\t\t}\n\t\tselectedNode := pvc.Annotations[volume.AnnSelectedNode]\n\t\tif selectedNode != pod.Spec.NodeName {\n\t\t\t// If provisioner fails to provision a volume, selectedNode\n\t\t\t// annotation will be removed to signal back to the scheduler to\n\t\t\t// retry.\n\t\t\treturn false, fmt.Errorf(\"provisioning failed for PVC %q\", pvc.Name)\n\t\t}\n\n\t\t// If the PVC is bound to a PV, check its node affinity\n\t\tif pvc.Spec.VolumeName != \"\" {\n\t\t\tpv, err := b.pvCache.GetAPIPV(pvc.Spec.VolumeName)\n\t\t\tif err != nil {\n\t\t\t\tif _, ok := err.(*errNotFound); ok {\n\t\t\t\t\t// We tolerate NotFound error here, because PV is possibly\n\t\t\t\t\t// not found because of API delay, we can check next time.\n\t\t\t\t\t// And if PV does not exist because it's deleted, PVC will\n\t\t\t\t\t// be unbound eventually.\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t\treturn false, fmt.Errorf(\"failed to get pv %q from cache: %w\", pvc.Spec.VolumeName, err)\n\t\t\t}\n\n\t\t\tpv, err = b.tryTranslatePVToCSI(pv, csiNode)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\tif err := volume.CheckNodeAffinity(pv, node.Labels); err != nil {\n\t\t\t\treturn false, fmt.Errorf(\"pv %q node affinity doesn't match node %q: %w\", pv.Name, node.Name, err)\n\t\t\t}\n\t\t}\n\n\t\t// Check if pvc is fully bound\n\t\tif !b.isPVCFullyBound(pvc) {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\t// All pvs and pvcs that we operated on are bound\n\tklog.V(2).InfoS(\"All PVCs for pod are bound\", \"pod\", klog.KObj(pod))\n\treturn true, nil\n}","line":{"from":612,"to":749}} {"id":100010995,"name":"isVolumeBound","signature":"func (b *volumeBinder) isVolumeBound(pod *v1.Pod, vol *v1.Volume) (bound bool, pvc *v1.PersistentVolumeClaim, err error)","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"func (b *volumeBinder) isVolumeBound(pod *v1.Pod, vol *v1.Volume) (bound bool, pvc *v1.PersistentVolumeClaim, err error) {\n\tpvcName := \"\"\n\tisEphemeral := false\n\tswitch {\n\tcase vol.PersistentVolumeClaim != nil:\n\t\tpvcName = vol.PersistentVolumeClaim.ClaimName\n\tcase vol.Ephemeral != nil:\n\t\t// Generic ephemeral inline volumes also use a PVC,\n\t\t// just with a computed name, and...\n\t\tpvcName = ephemeral.VolumeClaimName(pod, vol)\n\t\tisEphemeral = true\n\tdefault:\n\t\treturn true, nil, nil\n\t}\n\n\tbound, pvc, err = b.isPVCBound(pod.Namespace, pvcName)\n\t// ... the PVC must be owned by the pod.\n\tif isEphemeral \u0026\u0026 err == nil \u0026\u0026 pvc != nil {\n\t\tif err := ephemeral.VolumeIsForPod(pod, pvc); err != nil {\n\t\t\treturn false, nil, err\n\t\t}\n\t}\n\treturn\n}","line":{"from":751,"to":774}} {"id":100010996,"name":"isPVCBound","signature":"func (b *volumeBinder) isPVCBound(namespace, pvcName string) (bool, *v1.PersistentVolumeClaim, error)","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"func (b *volumeBinder) isPVCBound(namespace, pvcName string) (bool, *v1.PersistentVolumeClaim, error) {\n\tclaim := \u0026v1.PersistentVolumeClaim{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: pvcName,\n\t\t\tNamespace: namespace,\n\t\t},\n\t}\n\tpvcKey := getPVCName(claim)\n\tpvc, err := b.pvcCache.GetPVC(pvcKey)\n\tif err != nil || pvc == nil {\n\t\treturn false, nil, fmt.Errorf(\"error getting PVC %q: %v\", pvcKey, err)\n\t}\n\n\tfullyBound := b.isPVCFullyBound(pvc)\n\tif fullyBound {\n\t\tklog.V(5).InfoS(\"PVC is fully bound to PV\", \"PVC\", klog.KObj(pvc), \"PV\", klog.KRef(\"\", pvc.Spec.VolumeName))\n\t} else {\n\t\tif pvc.Spec.VolumeName != \"\" {\n\t\t\tklog.V(5).InfoS(\"PVC is not fully bound to PV\", \"PVC\", klog.KObj(pvc), \"PV\", klog.KRef(\"\", pvc.Spec.VolumeName))\n\t\t} else {\n\t\t\tklog.V(5).InfoS(\"PVC is not bound\", \"PVC\", klog.KObj(pvc))\n\t\t}\n\t}\n\treturn fullyBound, pvc, nil\n}","line":{"from":776,"to":800}} {"id":100010997,"name":"isPVCFullyBound","signature":"func (b *volumeBinder) isPVCFullyBound(pvc *v1.PersistentVolumeClaim) bool","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"func (b *volumeBinder) isPVCFullyBound(pvc *v1.PersistentVolumeClaim) bool {\n\treturn pvc.Spec.VolumeName != \"\" \u0026\u0026 metav1.HasAnnotation(pvc.ObjectMeta, volume.AnnBindCompleted)\n}","line":{"from":802,"to":804}} {"id":100010998,"name":"arePodVolumesBound","signature":"func (b *volumeBinder) arePodVolumesBound(pod *v1.Pod) bool","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"// arePodVolumesBound returns true if all volumes are fully bound\nfunc (b *volumeBinder) arePodVolumesBound(pod *v1.Pod) bool {\n\tfor _, vol := range pod.Spec.Volumes {\n\t\tif isBound, _, _ := b.isVolumeBound(pod, \u0026vol); !isBound {\n\t\t\t// Pod has at least one PVC that needs binding\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":806,"to":815}} {"id":100010999,"name":"GetPodVolumeClaims","signature":"func (b *volumeBinder) GetPodVolumeClaims(pod *v1.Pod) (podVolumeClaims *PodVolumeClaims, err error)","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"// GetPodVolumeClaims returns a pod's PVCs separated into bound, unbound with delayed binding (including provisioning),\n// unbound with immediate binding (including prebound) and PVs that belong to storage classes of unbound PVCs with delayed binding.\nfunc (b *volumeBinder) GetPodVolumeClaims(pod *v1.Pod) (podVolumeClaims *PodVolumeClaims, err error) {\n\tpodVolumeClaims = \u0026PodVolumeClaims{\n\t\tboundClaims: []*v1.PersistentVolumeClaim{},\n\t\tunboundClaimsImmediate: []*v1.PersistentVolumeClaim{},\n\t\tunboundClaimsDelayBinding: []*v1.PersistentVolumeClaim{},\n\t}\n\n\tfor _, vol := range pod.Spec.Volumes {\n\t\tvolumeBound, pvc, err := b.isVolumeBound(pod, \u0026vol)\n\t\tif err != nil {\n\t\t\treturn podVolumeClaims, err\n\t\t}\n\t\tif pvc == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif volumeBound {\n\t\t\tpodVolumeClaims.boundClaims = append(podVolumeClaims.boundClaims, pvc)\n\t\t} else {\n\t\t\tdelayBindingMode, err := volume.IsDelayBindingMode(pvc, b.classLister)\n\t\t\tif err != nil {\n\t\t\t\treturn podVolumeClaims, err\n\t\t\t}\n\t\t\t// Prebound PVCs are treated as unbound immediate binding\n\t\t\tif delayBindingMode \u0026\u0026 pvc.Spec.VolumeName == \"\" {\n\t\t\t\t// Scheduler path\n\t\t\t\tpodVolumeClaims.unboundClaimsDelayBinding = append(podVolumeClaims.unboundClaimsDelayBinding, pvc)\n\t\t\t} else {\n\t\t\t\t// !delayBindingMode || pvc.Spec.VolumeName != \"\"\n\t\t\t\t// Immediate binding should have already been bound\n\t\t\t\tpodVolumeClaims.unboundClaimsImmediate = append(podVolumeClaims.unboundClaimsImmediate, pvc)\n\t\t\t}\n\t\t}\n\t}\n\n\tpodVolumeClaims.unboundVolumesDelayBinding = map[string][]*v1.PersistentVolume{}\n\tfor _, pvc := range podVolumeClaims.unboundClaimsDelayBinding {\n\t\t// Get storage class name from each PVC\n\t\tstorageClassName := volume.GetPersistentVolumeClaimClass(pvc)\n\t\tpodVolumeClaims.unboundVolumesDelayBinding[storageClassName] = b.pvCache.ListPVs(storageClassName)\n\t}\n\treturn podVolumeClaims, nil\n}","line":{"from":817,"to":860}} {"id":100011000,"name":"checkBoundClaims","signature":"func (b *volumeBinder) checkBoundClaims(claims []*v1.PersistentVolumeClaim, node *v1.Node, pod *v1.Pod) (bool, bool, error)","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"func (b *volumeBinder) checkBoundClaims(claims []*v1.PersistentVolumeClaim, node *v1.Node, pod *v1.Pod) (bool, bool, error) {\n\tcsiNode, err := b.csiNodeLister.Get(node.Name)\n\tif err != nil {\n\t\t// TODO: return the error once CSINode is created by default\n\t\tklog.V(4).InfoS(\"Could not get a CSINode object for the node\", \"node\", klog.KObj(node), \"err\", err)\n\t}\n\n\tfor _, pvc := range claims {\n\t\tpvName := pvc.Spec.VolumeName\n\t\tpv, err := b.pvCache.GetPV(pvName)\n\t\tif err != nil {\n\t\t\tif _, ok := err.(*errNotFound); ok {\n\t\t\t\terr = nil\n\t\t\t}\n\t\t\treturn true, false, err\n\t\t}\n\n\t\tpv, err = b.tryTranslatePVToCSI(pv, csiNode)\n\t\tif err != nil {\n\t\t\treturn false, true, err\n\t\t}\n\n\t\terr = volume.CheckNodeAffinity(pv, node.Labels)\n\t\tif err != nil {\n\t\t\tklog.V(4).InfoS(\"PersistentVolume and node mismatch for pod\", \"PV\", klog.KRef(\"\", pvName), \"node\", klog.KObj(node), \"pod\", klog.KObj(pod), \"err\", err)\n\t\t\treturn false, true, nil\n\t\t}\n\t\tklog.V(5).InfoS(\"PersistentVolume and node matches for pod\", \"PV\", klog.KRef(\"\", pvName), \"node\", klog.KObj(node), \"pod\", klog.KObj(pod))\n\t}\n\n\tklog.V(4).InfoS(\"All bound volumes for pod match with node\", \"pod\", klog.KObj(pod), \"node\", klog.KObj(node))\n\treturn true, true, nil\n}","line":{"from":862,"to":894}} {"id":100011001,"name":"findMatchingVolumes","signature":"func (b *volumeBinder) findMatchingVolumes(pod *v1.Pod, claimsToBind []*v1.PersistentVolumeClaim, unboundVolumesDelayBinding map[string][]*v1.PersistentVolume, node *v1.Node) (foundMatches bool, bindings []*BindingInfo, unboundClaims []*v1.PersistentVolumeClaim, err error)","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"// findMatchingVolumes tries to find matching volumes for given claims,\n// and return unbound claims for further provision.\nfunc (b *volumeBinder) findMatchingVolumes(pod *v1.Pod, claimsToBind []*v1.PersistentVolumeClaim, unboundVolumesDelayBinding map[string][]*v1.PersistentVolume, node *v1.Node) (foundMatches bool, bindings []*BindingInfo, unboundClaims []*v1.PersistentVolumeClaim, err error) {\n\t// Sort all the claims by increasing size request to get the smallest fits\n\tsort.Sort(byPVCSize(claimsToBind))\n\n\tchosenPVs := map[string]*v1.PersistentVolume{}\n\n\tfoundMatches = true\n\n\tfor _, pvc := range claimsToBind {\n\t\t// Get storage class name from each PVC\n\t\tstorageClassName := volume.GetPersistentVolumeClaimClass(pvc)\n\t\tpvs := unboundVolumesDelayBinding[storageClassName]\n\n\t\t// Find a matching PV\n\t\tpv, err := volume.FindMatchingVolume(pvc, pvs, node, chosenPVs, true)\n\t\tif err != nil {\n\t\t\treturn false, nil, nil, err\n\t\t}\n\t\tif pv == nil {\n\t\t\tklog.V(4).InfoS(\"No matching volumes for pod\", \"pod\", klog.KObj(pod), \"PVC\", klog.KObj(pvc), \"node\", klog.KObj(node))\n\t\t\tunboundClaims = append(unboundClaims, pvc)\n\t\t\tfoundMatches = false\n\t\t\tcontinue\n\t\t}\n\n\t\t// matching PV needs to be excluded so we don't select it again\n\t\tchosenPVs[pv.Name] = pv\n\t\tbindings = append(bindings, \u0026BindingInfo{pv: pv, pvc: pvc})\n\t\tklog.V(5).InfoS(\"Found matching PV for PVC for pod\", \"PV\", klog.KObj(pv), \"PVC\", klog.KObj(pvc), \"node\", klog.KObj(node), \"pod\", klog.KObj(pod))\n\t}\n\n\tif foundMatches {\n\t\tklog.V(4).InfoS(\"Found matching volumes for pod\", \"pod\", klog.KObj(pod), \"node\", klog.KObj(node))\n\t}\n\n\treturn\n}","line":{"from":896,"to":934}} {"id":100011002,"name":"checkVolumeProvisions","signature":"func (b *volumeBinder) checkVolumeProvisions(pod *v1.Pod, claimsToProvision []*v1.PersistentVolumeClaim, node *v1.Node) (provisionSatisfied, sufficientStorage bool, dynamicProvisions []*v1.PersistentVolumeClaim, err error)","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"// checkVolumeProvisions checks given unbound claims (the claims have gone through func\n// findMatchingVolumes, and do not have matching volumes for binding), and return true\n// if all of the claims are eligible for dynamic provision.\nfunc (b *volumeBinder) checkVolumeProvisions(pod *v1.Pod, claimsToProvision []*v1.PersistentVolumeClaim, node *v1.Node) (provisionSatisfied, sufficientStorage bool, dynamicProvisions []*v1.PersistentVolumeClaim, err error) {\n\tdynamicProvisions = []*v1.PersistentVolumeClaim{}\n\n\t// We return early with provisionedClaims == nil if a check\n\t// fails or we encounter an error.\n\tfor _, claim := range claimsToProvision {\n\t\tpvcName := getPVCName(claim)\n\t\tclassName := volume.GetPersistentVolumeClaimClass(claim)\n\t\tif className == \"\" {\n\t\t\treturn false, false, nil, fmt.Errorf(\"no class for claim %q\", pvcName)\n\t\t}\n\n\t\tclass, err := b.classLister.Get(className)\n\t\tif err != nil {\n\t\t\treturn false, false, nil, fmt.Errorf(\"failed to find storage class %q\", className)\n\t\t}\n\t\tprovisioner := class.Provisioner\n\t\tif provisioner == \"\" || provisioner == volume.NotSupportedProvisioner {\n\t\t\tklog.V(4).InfoS(\"Storage class of claim does not support dynamic provisioning\", \"storageClassName\", className, \"PVC\", klog.KObj(claim))\n\t\t\treturn false, true, nil, nil\n\t\t}\n\n\t\t// Check if the node can satisfy the topology requirement in the class\n\t\tif !v1helper.MatchTopologySelectorTerms(class.AllowedTopologies, labels.Set(node.Labels)) {\n\t\t\tklog.V(4).InfoS(\"Node cannot satisfy provisioning topology requirements of claim\", \"node\", klog.KObj(node), \"PVC\", klog.KObj(claim))\n\t\t\treturn false, true, nil, nil\n\t\t}\n\n\t\t// Check storage capacity.\n\t\tsufficient, err := b.hasEnoughCapacity(provisioner, claim, class, node)\n\t\tif err != nil {\n\t\t\treturn false, false, nil, err\n\t\t}\n\t\tif !sufficient {\n\t\t\t// hasEnoughCapacity logs an explanation.\n\t\t\treturn true, false, nil, nil\n\t\t}\n\n\t\tdynamicProvisions = append(dynamicProvisions, claim)\n\n\t}\n\tklog.V(4).InfoS(\"Provisioning for claims of pod that has no matching volumes...\", \"claimCount\", len(claimsToProvision), \"pod\", klog.KObj(pod), \"node\", klog.KObj(node))\n\n\treturn true, true, dynamicProvisions, nil\n}","line":{"from":936,"to":983}} {"id":100011003,"name":"revertAssumedPVs","signature":"func (b *volumeBinder) revertAssumedPVs(bindings []*BindingInfo)","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"func (b *volumeBinder) revertAssumedPVs(bindings []*BindingInfo) {\n\tfor _, BindingInfo := range bindings {\n\t\tb.pvCache.Restore(BindingInfo.pv.Name)\n\t}\n}","line":{"from":985,"to":989}} {"id":100011004,"name":"revertAssumedPVCs","signature":"func (b *volumeBinder) revertAssumedPVCs(claims []*v1.PersistentVolumeClaim)","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"func (b *volumeBinder) revertAssumedPVCs(claims []*v1.PersistentVolumeClaim) {\n\tfor _, claim := range claims {\n\t\tb.pvcCache.Restore(getPVCName(claim))\n\t}\n}","line":{"from":991,"to":995}} {"id":100011005,"name":"hasEnoughCapacity","signature":"func (b *volumeBinder) hasEnoughCapacity(provisioner string, claim *v1.PersistentVolumeClaim, storageClass *storagev1.StorageClass, node *v1.Node) (bool, error)","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"// hasEnoughCapacity checks whether the provisioner has enough capacity left for a new volume of the given size\n// that is available from the node.\nfunc (b *volumeBinder) hasEnoughCapacity(provisioner string, claim *v1.PersistentVolumeClaim, storageClass *storagev1.StorageClass, node *v1.Node) (bool, error) {\n\tquantity, ok := claim.Spec.Resources.Requests[v1.ResourceStorage]\n\tif !ok {\n\t\t// No capacity to check for.\n\t\treturn true, nil\n\t}\n\n\t// Only enabled for CSI drivers which opt into it.\n\tdriver, err := b.csiDriverLister.Get(provisioner)\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\t// Either the provisioner is not a CSI driver or the driver does not\n\t\t\t// opt into storage capacity scheduling. Either way, skip\n\t\t\t// capacity checking.\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, err\n\t}\n\tif driver.Spec.StorageCapacity == nil || !*driver.Spec.StorageCapacity {\n\t\treturn true, nil\n\t}\n\n\t// Look for a matching CSIStorageCapacity object(s).\n\t// TODO (for beta): benchmark this and potentially introduce some kind of lookup structure (https://github.com/kubernetes/enhancements/issues/1698#issuecomment-654356718).\n\tcapacities, err := b.csiStorageCapacityLister.List(labels.Everything())\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tsizeInBytes := quantity.Value()\n\tfor _, capacity := range capacities {\n\t\tif capacity.StorageClassName == storageClass.Name \u0026\u0026\n\t\t\tcapacitySufficient(capacity, sizeInBytes) \u0026\u0026\n\t\t\tb.nodeHasAccess(node, capacity) {\n\t\t\t// Enough capacity found.\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\t// TODO (?): this doesn't give any information about which pools where considered and why\n\t// they had to be rejected. Log that above? But that might be a lot of log output...\n\tklog.V(4).InfoS(\"Node has no accessible CSIStorageCapacity with enough capacity for PVC\",\n\t\t\"node\", klog.KObj(node), \"PVC\", klog.KObj(claim), \"size\", sizeInBytes, \"storageClass\", klog.KObj(storageClass))\n\treturn false, nil\n}","line":{"from":997,"to":1043}} {"id":100011006,"name":"capacitySufficient","signature":"func capacitySufficient(capacity *storagev1.CSIStorageCapacity, sizeInBytes int64) bool","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"func capacitySufficient(capacity *storagev1.CSIStorageCapacity, sizeInBytes int64) bool {\n\tlimit := capacity.Capacity\n\tif capacity.MaximumVolumeSize != nil {\n\t\t// Prefer MaximumVolumeSize if available, it is more precise.\n\t\tlimit = capacity.MaximumVolumeSize\n\t}\n\treturn limit != nil \u0026\u0026 limit.Value() \u003e= sizeInBytes\n}","line":{"from":1045,"to":1052}} {"id":100011007,"name":"nodeHasAccess","signature":"func (b *volumeBinder) nodeHasAccess(node *v1.Node, capacity *storagev1.CSIStorageCapacity) bool","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"func (b *volumeBinder) nodeHasAccess(node *v1.Node, capacity *storagev1.CSIStorageCapacity) bool {\n\tif capacity.NodeTopology == nil {\n\t\t// Unavailable\n\t\treturn false\n\t}\n\t// Only matching by label is supported.\n\tselector, err := metav1.LabelSelectorAsSelector(capacity.NodeTopology)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Unexpected error converting to a label selector\", \"nodeTopology\", capacity.NodeTopology)\n\t\treturn false\n\t}\n\treturn selector.Matches(labels.Set(node.Labels))\n}","line":{"from":1054,"to":1066}} {"id":100011008,"name":"Len","signature":"func (a byPVCSize) Len() int","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"func (a byPVCSize) Len() int {\n\treturn len(a)\n}","line":{"from":1070,"to":1072}} {"id":100011009,"name":"Swap","signature":"func (a byPVCSize) Swap(i, j int)","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"func (a byPVCSize) Swap(i, j int) {\n\ta[i], a[j] = a[j], a[i]\n}","line":{"from":1074,"to":1076}} {"id":100011010,"name":"Less","signature":"func (a byPVCSize) Less(i, j int) bool","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"func (a byPVCSize) Less(i, j int) bool {\n\tiSize := a[i].Spec.Resources.Requests[v1.ResourceStorage]\n\tjSize := a[j].Spec.Resources.Requests[v1.ResourceStorage]\n\t// return true if iSize is less than jSize\n\treturn iSize.Cmp(jSize) == -1\n}","line":{"from":1078,"to":1083}} {"id":100011011,"name":"isCSIMigrationOnForPlugin","signature":"func isCSIMigrationOnForPlugin(pluginName string) bool","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"// isCSIMigrationOnForPlugin checks if CSI migration is enabled for a given plugin.\nfunc isCSIMigrationOnForPlugin(pluginName string) bool {\n\tswitch pluginName {\n\tcase csiplugins.AWSEBSInTreePluginName:\n\t\treturn true\n\tcase csiplugins.GCEPDInTreePluginName:\n\t\treturn utilfeature.DefaultFeatureGate.Enabled(features.CSIMigrationGCE)\n\tcase csiplugins.AzureDiskInTreePluginName:\n\t\treturn true\n\tcase csiplugins.CinderInTreePluginName:\n\t\treturn true\n\tcase csiplugins.PortworxVolumePluginName:\n\t\treturn utilfeature.DefaultFeatureGate.Enabled(features.CSIMigrationPortworx)\n\tcase csiplugins.RBDVolumePluginName:\n\t\treturn utilfeature.DefaultFeatureGate.Enabled(features.CSIMigrationRBD)\n\t}\n\treturn false\n}","line":{"from":1085,"to":1102}} {"id":100011012,"name":"isPluginMigratedToCSIOnNode","signature":"func isPluginMigratedToCSIOnNode(pluginName string, csiNode *storagev1.CSINode) bool","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"// isPluginMigratedToCSIOnNode checks if an in-tree plugin has been migrated to a CSI driver on the node.\nfunc isPluginMigratedToCSIOnNode(pluginName string, csiNode *storagev1.CSINode) bool {\n\tif csiNode == nil {\n\t\treturn false\n\t}\n\n\tcsiNodeAnn := csiNode.GetAnnotations()\n\tif csiNodeAnn == nil {\n\t\treturn false\n\t}\n\n\tvar mpaSet sets.String\n\tmpa := csiNodeAnn[v1.MigratedPluginsAnnotationKey]\n\tif len(mpa) == 0 {\n\t\tmpaSet = sets.NewString()\n\t} else {\n\t\ttok := strings.Split(mpa, \",\")\n\t\tmpaSet = sets.NewString(tok...)\n\t}\n\n\treturn mpaSet.Has(pluginName)\n}","line":{"from":1104,"to":1125}} {"id":100011013,"name":"tryTranslatePVToCSI","signature":"func (b *volumeBinder) tryTranslatePVToCSI(pv *v1.PersistentVolume, csiNode *storagev1.CSINode) (*v1.PersistentVolume, error)","file":"pkg/scheduler/framework/plugins/volumebinding/binder.go","code":"// tryTranslatePVToCSI will translate the in-tree PV to CSI if it meets the criteria. If not, it returns the unmodified in-tree PV.\nfunc (b *volumeBinder) tryTranslatePVToCSI(pv *v1.PersistentVolume, csiNode *storagev1.CSINode) (*v1.PersistentVolume, error) {\n\tif !b.translator.IsPVMigratable(pv) {\n\t\treturn pv, nil\n\t}\n\n\tpluginName, err := b.translator.GetInTreePluginNameFromSpec(pv, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not get plugin name from pv: %v\", err)\n\t}\n\n\tif !isCSIMigrationOnForPlugin(pluginName) {\n\t\treturn pv, nil\n\t}\n\n\tif !isPluginMigratedToCSIOnNode(pluginName, csiNode) {\n\t\treturn pv, nil\n\t}\n\n\ttransPV, err := b.translator.TranslateInTreePVToCSI(pv)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not translate pv: %v\", err)\n\t}\n\n\treturn transPV, nil\n}","line":{"from":1127,"to":1152}} {"id":100011014,"name":"RegisterVolumeSchedulingMetrics","signature":"func RegisterVolumeSchedulingMetrics()","file":"pkg/scheduler/framework/plugins/volumebinding/metrics/metrics.go","code":"// RegisterVolumeSchedulingMetrics is used for scheduler, because the volume binding cache is a library\n// used by scheduler process.\nfunc RegisterVolumeSchedulingMetrics() {\n\tlegacyregistry.MustRegister(VolumeBindingRequestSchedulerBinderCache)\n\tlegacyregistry.MustRegister(VolumeSchedulingStageFailed)\n}","line":{"from":50,"to":55}} {"id":100011015,"name":"buildScorerFunction","signature":"func buildScorerFunction(scoringFunctionShape helper.FunctionShape) volumeCapacityScorer","file":"pkg/scheduler/framework/plugins/volumebinding/scorer.go","code":"// buildScorerFunction builds volumeCapacityScorer from the scoring function shape.\nfunc buildScorerFunction(scoringFunctionShape helper.FunctionShape) volumeCapacityScorer {\n\trawScoringFunction := helper.BuildBrokenLinearFunction(scoringFunctionShape)\n\tf := func(requested, capacity int64) int64 {\n\t\tif capacity == 0 || requested \u003e capacity {\n\t\t\treturn rawScoringFunction(maxUtilization)\n\t\t}\n\n\t\treturn rawScoringFunction(requested * maxUtilization / capacity)\n\t}\n\treturn func(classResources classResourceMap) int64 {\n\t\tvar nodeScore int64\n\t\t// in alpha stage, all classes have the same weight\n\t\tweightSum := len(classResources)\n\t\tif weightSum == 0 {\n\t\t\treturn 0\n\t\t}\n\t\tfor _, resource := range classResources {\n\t\t\tclassScore := f(resource.Requested, resource.Capacity)\n\t\t\tnodeScore += classScore\n\t\t}\n\t\treturn int64(math.Round(float64(nodeScore) / float64(weightSum)))\n\t}\n}","line":{"from":31,"to":54}} {"id":100011016,"name":"Clone","signature":"func (d *stateData) Clone() framework.StateData","file":"pkg/scheduler/framework/plugins/volumebinding/volume_binding.go","code":"func (d *stateData) Clone() framework.StateData {\n\treturn d\n}","line":{"from":59,"to":61}} {"id":100011017,"name":"Name","signature":"func (pl *VolumeBinding) Name() string","file":"pkg/scheduler/framework/plugins/volumebinding/volume_binding.go","code":"// Name returns name of the plugin. It is used in logs, etc.\nfunc (pl *VolumeBinding) Name() string {\n\treturn Name\n}","line":{"from":83,"to":86}} {"id":100011018,"name":"EventsToRegister","signature":"func (pl *VolumeBinding) EventsToRegister() []framework.ClusterEvent","file":"pkg/scheduler/framework/plugins/volumebinding/volume_binding.go","code":"// EventsToRegister returns the possible events that may make a Pod\n// failed by this plugin schedulable.\nfunc (pl *VolumeBinding) EventsToRegister() []framework.ClusterEvent {\n\tevents := []framework.ClusterEvent{\n\t\t// Pods may fail because of missing or mis-configured storage class\n\t\t// (e.g., allowedTopologies, volumeBindingMode), and hence may become\n\t\t// schedulable upon StorageClass Add or Update events.\n\t\t{Resource: framework.StorageClass, ActionType: framework.Add | framework.Update},\n\t\t// We bind PVCs with PVs, so any changes may make the pods schedulable.\n\t\t{Resource: framework.PersistentVolumeClaim, ActionType: framework.Add | framework.Update},\n\t\t{Resource: framework.PersistentVolume, ActionType: framework.Add | framework.Update},\n\t\t// Pods may fail to find available PVs because the node labels do not\n\t\t// match the storage class's allowed topologies or PV's node affinity.\n\t\t// A new or updated node may make pods schedulable.\n\t\t{Resource: framework.Node, ActionType: framework.Add | framework.UpdateNodeLabel},\n\t\t// We rely on CSI node to translate in-tree PV to CSI.\n\t\t{Resource: framework.CSINode, ActionType: framework.Add | framework.Update},\n\t\t// When CSIStorageCapacity is enabled, pods may become schedulable\n\t\t// on CSI driver \u0026 storage capacity changes.\n\t\t{Resource: framework.CSIDriver, ActionType: framework.Add | framework.Update},\n\t\t{Resource: framework.CSIStorageCapacity, ActionType: framework.Add | framework.Update},\n\t}\n\treturn events\n}","line":{"from":88,"to":111}} {"id":100011019,"name":"podHasPVCs","signature":"func (pl *VolumeBinding) podHasPVCs(pod *v1.Pod) (bool, error)","file":"pkg/scheduler/framework/plugins/volumebinding/volume_binding.go","code":"// podHasPVCs returns 2 values:\n// - the first one to denote if the given \"pod\" has any PVC defined.\n// - the second one to return any error if the requested PVC is illegal.\nfunc (pl *VolumeBinding) podHasPVCs(pod *v1.Pod) (bool, error) {\n\thasPVC := false\n\tfor _, vol := range pod.Spec.Volumes {\n\t\tvar pvcName string\n\t\tisEphemeral := false\n\t\tswitch {\n\t\tcase vol.PersistentVolumeClaim != nil:\n\t\t\tpvcName = vol.PersistentVolumeClaim.ClaimName\n\t\tcase vol.Ephemeral != nil:\n\t\t\tpvcName = ephemeral.VolumeClaimName(pod, \u0026vol)\n\t\t\tisEphemeral = true\n\t\tdefault:\n\t\t\t// Volume is not using a PVC, ignore\n\t\t\tcontinue\n\t\t}\n\t\thasPVC = true\n\t\tpvc, err := pl.PVCLister.PersistentVolumeClaims(pod.Namespace).Get(pvcName)\n\t\tif err != nil {\n\t\t\t// The error usually has already enough context (\"persistentvolumeclaim \"myclaim\" not found\"),\n\t\t\t// but we can do better for generic ephemeral inline volumes where that situation\n\t\t\t// is normal directly after creating a pod.\n\t\t\tif isEphemeral \u0026\u0026 apierrors.IsNotFound(err) {\n\t\t\t\terr = fmt.Errorf(\"waiting for ephemeral volume controller to create the persistentvolumeclaim %q\", pvcName)\n\t\t\t}\n\t\t\treturn hasPVC, err\n\t\t}\n\n\t\tif pvc.Status.Phase == v1.ClaimLost {\n\t\t\treturn hasPVC, fmt.Errorf(\"persistentvolumeclaim %q bound to non-existent persistentvolume %q\", pvc.Name, pvc.Spec.VolumeName)\n\t\t}\n\n\t\tif pvc.DeletionTimestamp != nil {\n\t\t\treturn hasPVC, fmt.Errorf(\"persistentvolumeclaim %q is being deleted\", pvc.Name)\n\t\t}\n\n\t\tif isEphemeral {\n\t\t\tif err := ephemeral.VolumeIsForPod(pod, pvc); err != nil {\n\t\t\t\treturn hasPVC, err\n\t\t\t}\n\t\t}\n\t}\n\treturn hasPVC, nil\n}","line":{"from":113,"to":158}} {"id":100011020,"name":"PreFilter","signature":"func (pl *VolumeBinding) PreFilter(ctx context.Context, state *framework.CycleState, pod *v1.Pod) (*framework.PreFilterResult, *framework.Status)","file":"pkg/scheduler/framework/plugins/volumebinding/volume_binding.go","code":"// PreFilter invoked at the prefilter extension point to check if pod has all\n// immediate PVCs bound. If not all immediate PVCs are bound, an\n// UnschedulableAndUnresolvable is returned.\nfunc (pl *VolumeBinding) PreFilter(ctx context.Context, state *framework.CycleState, pod *v1.Pod) (*framework.PreFilterResult, *framework.Status) {\n\t// If pod does not reference any PVC, we don't need to do anything.\n\tif hasPVC, err := pl.podHasPVCs(pod); err != nil {\n\t\treturn nil, framework.NewStatus(framework.UnschedulableAndUnresolvable, err.Error())\n\t} else if !hasPVC {\n\t\tstate.Write(stateKey, \u0026stateData{})\n\t\treturn nil, framework.NewStatus(framework.Skip)\n\t}\n\tpodVolumeClaims, err := pl.Binder.GetPodVolumeClaims(pod)\n\tif err != nil {\n\t\treturn nil, framework.AsStatus(err)\n\t}\n\tif len(podVolumeClaims.unboundClaimsImmediate) \u003e 0 {\n\t\t// Return UnschedulableAndUnresolvable error if immediate claims are\n\t\t// not bound. Pod will be moved to active/backoff queues once these\n\t\t// claims are bound by PV controller.\n\t\tstatus := framework.NewStatus(framework.UnschedulableAndUnresolvable)\n\t\tstatus.AppendReason(\"pod has unbound immediate PersistentVolumeClaims\")\n\t\treturn nil, status\n\t}\n\t// Attempt to reduce down the number of nodes to consider in subsequent scheduling stages if pod has bound claims.\n\tvar result *framework.PreFilterResult\n\tif eligibleNodes := pl.Binder.GetEligibleNodes(podVolumeClaims.boundClaims); eligibleNodes != nil {\n\t\tresult = \u0026framework.PreFilterResult{\n\t\t\tNodeNames: eligibleNodes,\n\t\t}\n\t}\n\n\tstate.Write(stateKey, \u0026stateData{\n\t\tpodVolumesByNode: make(map[string]*PodVolumes),\n\t\tpodVolumeClaims: \u0026PodVolumeClaims{\n\t\t\tboundClaims: podVolumeClaims.boundClaims,\n\t\t\tunboundClaimsDelayBinding: podVolumeClaims.unboundClaimsDelayBinding,\n\t\t\tunboundVolumesDelayBinding: podVolumeClaims.unboundVolumesDelayBinding,\n\t\t},\n\t})\n\treturn result, nil\n}","line":{"from":160,"to":200}} {"id":100011021,"name":"PreFilterExtensions","signature":"func (pl *VolumeBinding) PreFilterExtensions() framework.PreFilterExtensions","file":"pkg/scheduler/framework/plugins/volumebinding/volume_binding.go","code":"// PreFilterExtensions returns prefilter extensions, pod add and remove.\nfunc (pl *VolumeBinding) PreFilterExtensions() framework.PreFilterExtensions {\n\treturn nil\n}","line":{"from":202,"to":205}} {"id":100011022,"name":"getStateData","signature":"func getStateData(cs *framework.CycleState) (*stateData, error)","file":"pkg/scheduler/framework/plugins/volumebinding/volume_binding.go","code":"func getStateData(cs *framework.CycleState) (*stateData, error) {\n\tstate, err := cs.Read(stateKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts, ok := state.(*stateData)\n\tif !ok {\n\t\treturn nil, errors.New(\"unable to convert state into stateData\")\n\t}\n\treturn s, nil\n}","line":{"from":207,"to":217}} {"id":100011023,"name":"Filter","signature":"func (pl *VolumeBinding) Filter(ctx context.Context, cs *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status","file":"pkg/scheduler/framework/plugins/volumebinding/volume_binding.go","code":"// Filter invoked at the filter extension point.\n// It evaluates if a pod can fit due to the volumes it requests,\n// for both bound and unbound PVCs.\n//\n// For PVCs that are bound, then it checks that the corresponding PV's node affinity is\n// satisfied by the given node.\n//\n// For PVCs that are unbound, it tries to find available PVs that can satisfy the PVC requirements\n// and that the PV node affinity is satisfied by the given node.\n//\n// If storage capacity tracking is enabled, then enough space has to be available\n// for the node and volumes that still need to be created.\n//\n// The predicate returns true if all bound PVCs have compatible PVs with the node, and if all unbound\n// PVCs can be matched with an available and node-compatible PV.\nfunc (pl *VolumeBinding) Filter(ctx context.Context, cs *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status {\n\tnode := nodeInfo.Node()\n\tif node == nil {\n\t\treturn framework.NewStatus(framework.Error, \"node not found\")\n\t}\n\n\tstate, err := getStateData(cs)\n\tif err != nil {\n\t\treturn framework.AsStatus(err)\n\t}\n\n\tpodVolumes, reasons, err := pl.Binder.FindPodVolumes(pod, state.podVolumeClaims, node)\n\n\tif err != nil {\n\t\treturn framework.AsStatus(err)\n\t}\n\n\tif len(reasons) \u003e 0 {\n\t\tstatus := framework.NewStatus(framework.UnschedulableAndUnresolvable)\n\t\tfor _, reason := range reasons {\n\t\t\tstatus.AppendReason(string(reason))\n\t\t}\n\t\treturn status\n\t}\n\n\t// multiple goroutines call `Filter` on different nodes simultaneously and the `CycleState` may be duplicated, so we must use a local lock here\n\tstate.Lock()\n\tstate.podVolumesByNode[node.Name] = podVolumes\n\tstate.Unlock()\n\treturn nil\n}","line":{"from":219,"to":264}} {"id":100011024,"name":"Score","signature":"func (pl *VolumeBinding) Score(ctx context.Context, cs *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status)","file":"pkg/scheduler/framework/plugins/volumebinding/volume_binding.go","code":"// Score invoked at the score extension point.\nfunc (pl *VolumeBinding) Score(ctx context.Context, cs *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status) {\n\tif pl.scorer == nil {\n\t\treturn 0, nil\n\t}\n\tstate, err := getStateData(cs)\n\tif err != nil {\n\t\treturn 0, framework.AsStatus(err)\n\t}\n\tpodVolumes, ok := state.podVolumesByNode[nodeName]\n\tif !ok {\n\t\treturn 0, nil\n\t}\n\t// group by storage class\n\tclassResources := make(classResourceMap)\n\tfor _, staticBinding := range podVolumes.StaticBindings {\n\t\tclass := staticBinding.StorageClassName()\n\t\tstorageResource := staticBinding.StorageResource()\n\t\tif _, ok := classResources[class]; !ok {\n\t\t\tclassResources[class] = \u0026StorageResource{\n\t\t\t\tRequested: 0,\n\t\t\t\tCapacity: 0,\n\t\t\t}\n\t\t}\n\t\tclassResources[class].Requested += storageResource.Requested\n\t\tclassResources[class].Capacity += storageResource.Capacity\n\t}\n\treturn pl.scorer(classResources), nil\n}","line":{"from":266,"to":294}} {"id":100011025,"name":"ScoreExtensions","signature":"func (pl *VolumeBinding) ScoreExtensions() framework.ScoreExtensions","file":"pkg/scheduler/framework/plugins/volumebinding/volume_binding.go","code":"// ScoreExtensions of the Score plugin.\nfunc (pl *VolumeBinding) ScoreExtensions() framework.ScoreExtensions {\n\treturn nil\n}","line":{"from":296,"to":299}} {"id":100011026,"name":"Reserve","signature":"func (pl *VolumeBinding) Reserve(ctx context.Context, cs *framework.CycleState, pod *v1.Pod, nodeName string) *framework.Status","file":"pkg/scheduler/framework/plugins/volumebinding/volume_binding.go","code":"// Reserve reserves volumes of pod and saves binding status in cycle state.\nfunc (pl *VolumeBinding) Reserve(ctx context.Context, cs *framework.CycleState, pod *v1.Pod, nodeName string) *framework.Status {\n\tstate, err := getStateData(cs)\n\tif err != nil {\n\t\treturn framework.AsStatus(err)\n\t}\n\t// we don't need to hold the lock as only one node will be reserved for the given pod\n\tpodVolumes, ok := state.podVolumesByNode[nodeName]\n\tif ok {\n\t\tallBound, err := pl.Binder.AssumePodVolumes(pod, nodeName, podVolumes)\n\t\tif err != nil {\n\t\t\treturn framework.AsStatus(err)\n\t\t}\n\t\tstate.allBound = allBound\n\t} else {\n\t\t// may not exist if the pod does not reference any PVC\n\t\tstate.allBound = true\n\t}\n\treturn nil\n}","line":{"from":301,"to":320}} {"id":100011027,"name":"PreBind","signature":"func (pl *VolumeBinding) PreBind(ctx context.Context, cs *framework.CycleState, pod *v1.Pod, nodeName string) *framework.Status","file":"pkg/scheduler/framework/plugins/volumebinding/volume_binding.go","code":"// PreBind will make the API update with the assumed bindings and wait until\n// the PV controller has completely finished the binding operation.\n//\n// If binding errors, times out or gets undone, then an error will be returned to\n// retry scheduling.\nfunc (pl *VolumeBinding) PreBind(ctx context.Context, cs *framework.CycleState, pod *v1.Pod, nodeName string) *framework.Status {\n\ts, err := getStateData(cs)\n\tif err != nil {\n\t\treturn framework.AsStatus(err)\n\t}\n\tif s.allBound {\n\t\t// no need to bind volumes\n\t\treturn nil\n\t}\n\t// we don't need to hold the lock as only one node will be pre-bound for the given pod\n\tpodVolumes, ok := s.podVolumesByNode[nodeName]\n\tif !ok {\n\t\treturn framework.AsStatus(fmt.Errorf(\"no pod volumes found for node %q\", nodeName))\n\t}\n\tklog.V(5).InfoS(\"Trying to bind volumes for pod\", \"pod\", klog.KObj(pod))\n\terr = pl.Binder.BindPodVolumes(ctx, pod, podVolumes)\n\tif err != nil {\n\t\tklog.V(1).InfoS(\"Failed to bind volumes for pod\", \"pod\", klog.KObj(pod), \"err\", err)\n\t\treturn framework.AsStatus(err)\n\t}\n\tklog.V(5).InfoS(\"Success binding volumes for pod\", \"pod\", klog.KObj(pod))\n\treturn nil\n}","line":{"from":322,"to":349}} {"id":100011028,"name":"Unreserve","signature":"func (pl *VolumeBinding) Unreserve(ctx context.Context, cs *framework.CycleState, pod *v1.Pod, nodeName string)","file":"pkg/scheduler/framework/plugins/volumebinding/volume_binding.go","code":"// Unreserve clears assumed PV and PVC cache.\n// It's idempotent, and does nothing if no cache found for the given pod.\nfunc (pl *VolumeBinding) Unreserve(ctx context.Context, cs *framework.CycleState, pod *v1.Pod, nodeName string) {\n\ts, err := getStateData(cs)\n\tif err != nil {\n\t\treturn\n\t}\n\t// we don't need to hold the lock as only one node may be unreserved\n\tpodVolumes, ok := s.podVolumesByNode[nodeName]\n\tif !ok {\n\t\treturn\n\t}\n\tpl.Binder.RevertAssumedPodVolumes(podVolumes)\n}","line":{"from":351,"to":364}} {"id":100011029,"name":"New","signature":"func New(plArgs runtime.Object, fh framework.Handle, fts feature.Features) (framework.Plugin, error)","file":"pkg/scheduler/framework/plugins/volumebinding/volume_binding.go","code":"// New initializes a new plugin and returns it.\nfunc New(plArgs runtime.Object, fh framework.Handle, fts feature.Features) (framework.Plugin, error) {\n\targs, ok := plArgs.(*config.VolumeBindingArgs)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"want args to be of type VolumeBindingArgs, got %T\", plArgs)\n\t}\n\tif err := validation.ValidateVolumeBindingArgsWithOptions(nil, args, validation.VolumeBindingArgsValidationOptions{\n\t\tAllowVolumeCapacityPriority: fts.EnableVolumeCapacityPriority,\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\tpodInformer := fh.SharedInformerFactory().Core().V1().Pods()\n\tnodeInformer := fh.SharedInformerFactory().Core().V1().Nodes()\n\tpvcInformer := fh.SharedInformerFactory().Core().V1().PersistentVolumeClaims()\n\tpvInformer := fh.SharedInformerFactory().Core().V1().PersistentVolumes()\n\tstorageClassInformer := fh.SharedInformerFactory().Storage().V1().StorageClasses()\n\tcsiNodeInformer := fh.SharedInformerFactory().Storage().V1().CSINodes()\n\tcapacityCheck := CapacityCheck{\n\t\tCSIDriverInformer: fh.SharedInformerFactory().Storage().V1().CSIDrivers(),\n\t\tCSIStorageCapacityInformer: fh.SharedInformerFactory().Storage().V1().CSIStorageCapacities(),\n\t}\n\tbinder := NewVolumeBinder(fh.ClientSet(), podInformer, nodeInformer, csiNodeInformer, pvcInformer, pvInformer, storageClassInformer, capacityCheck, time.Duration(args.BindTimeoutSeconds)*time.Second)\n\n\t// build score function\n\tvar scorer volumeCapacityScorer\n\tif fts.EnableVolumeCapacityPriority {\n\t\tshape := make(helper.FunctionShape, 0, len(args.Shape))\n\t\tfor _, point := range args.Shape {\n\t\t\tshape = append(shape, helper.FunctionShapePoint{\n\t\t\t\tUtilization: int64(point.Utilization),\n\t\t\t\tScore: int64(point.Score) * (framework.MaxNodeScore / config.MaxCustomPriorityScore),\n\t\t\t})\n\t\t}\n\t\tscorer = buildScorerFunction(shape)\n\t}\n\treturn \u0026VolumeBinding{\n\t\tBinder: binder,\n\t\tPVCLister: pvcInformer.Lister(),\n\t\tscorer: scorer,\n\t\tfts: fts,\n\t}, nil\n}","line":{"from":366,"to":407}} {"id":100011030,"name":"updateWithPod","signature":"func (s *preFilterState) updateWithPod(podInfo *framework.PodInfo, multiplier int)","file":"pkg/scheduler/framework/plugins/volumerestrictions/volume_restrictions.go","code":"func (s *preFilterState) updateWithPod(podInfo *framework.PodInfo, multiplier int) {\n\ts.conflictingPVCRefCount += multiplier * s.conflictingPVCRefCountForPod(podInfo)\n}","line":{"from":67,"to":69}} {"id":100011031,"name":"conflictingPVCRefCountForPod","signature":"func (s *preFilterState) conflictingPVCRefCountForPod(podInfo *framework.PodInfo) int","file":"pkg/scheduler/framework/plugins/volumerestrictions/volume_restrictions.go","code":"func (s *preFilterState) conflictingPVCRefCountForPod(podInfo *framework.PodInfo) int {\n\tconflicts := 0\n\tfor _, volume := range podInfo.Pod.Spec.Volumes {\n\t\tif volume.PersistentVolumeClaim == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif s.readWriteOncePodPVCs.Has(volume.PersistentVolumeClaim.ClaimName) {\n\t\t\tconflicts += 1\n\t\t}\n\t}\n\treturn conflicts\n}","line":{"from":71,"to":82}} {"id":100011032,"name":"Clone","signature":"func (s *preFilterState) Clone() framework.StateData","file":"pkg/scheduler/framework/plugins/volumerestrictions/volume_restrictions.go","code":"// Clone the prefilter state.\nfunc (s *preFilterState) Clone() framework.StateData {\n\tif s == nil {\n\t\treturn nil\n\t}\n\treturn \u0026preFilterState{\n\t\treadWriteOncePodPVCs: s.readWriteOncePodPVCs,\n\t\tconflictingPVCRefCount: s.conflictingPVCRefCount,\n\t}\n}","line":{"from":84,"to":93}} {"id":100011033,"name":"Name","signature":"func (pl *VolumeRestrictions) Name() string","file":"pkg/scheduler/framework/plugins/volumerestrictions/volume_restrictions.go","code":"// Name returns name of the plugin. It is used in logs, etc.\nfunc (pl *VolumeRestrictions) Name() string {\n\treturn Name\n}","line":{"from":95,"to":98}} {"id":100011034,"name":"isVolumeConflict","signature":"func isVolumeConflict(volume *v1.Volume, pod *v1.Pod) bool","file":"pkg/scheduler/framework/plugins/volumerestrictions/volume_restrictions.go","code":"func isVolumeConflict(volume *v1.Volume, pod *v1.Pod) bool {\n\tfor _, existingVolume := range pod.Spec.Volumes {\n\t\t// Same GCE disk mounted by multiple pods conflicts unless all pods mount it read-only.\n\t\tif volume.GCEPersistentDisk != nil \u0026\u0026 existingVolume.GCEPersistentDisk != nil {\n\t\t\tdisk, existingDisk := volume.GCEPersistentDisk, existingVolume.GCEPersistentDisk\n\t\t\tif disk.PDName == existingDisk.PDName \u0026\u0026 !(disk.ReadOnly \u0026\u0026 existingDisk.ReadOnly) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\tif volume.AWSElasticBlockStore != nil \u0026\u0026 existingVolume.AWSElasticBlockStore != nil {\n\t\t\tif volume.AWSElasticBlockStore.VolumeID == existingVolume.AWSElasticBlockStore.VolumeID {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\tif volume.ISCSI != nil \u0026\u0026 existingVolume.ISCSI != nil {\n\t\t\tiqn := volume.ISCSI.IQN\n\t\t\teiqn := existingVolume.ISCSI.IQN\n\t\t\t// two ISCSI volumes are same, if they share the same iqn. As iscsi volumes are of type\n\t\t\t// RWO or ROX, we could permit only one RW mount. Same iscsi volume mounted by multiple Pods\n\t\t\t// conflict unless all other pods mount as read only.\n\t\t\tif iqn == eiqn \u0026\u0026 !(volume.ISCSI.ReadOnly \u0026\u0026 existingVolume.ISCSI.ReadOnly) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\tif volume.RBD != nil \u0026\u0026 existingVolume.RBD != nil {\n\t\t\tmon, pool, image := volume.RBD.CephMonitors, volume.RBD.RBDPool, volume.RBD.RBDImage\n\t\t\temon, epool, eimage := existingVolume.RBD.CephMonitors, existingVolume.RBD.RBDPool, existingVolume.RBD.RBDImage\n\t\t\t// two RBDs images are the same if they share the same Ceph monitor, are in the same RADOS Pool, and have the same image name\n\t\t\t// only one read-write mount is permitted for the same RBD image.\n\t\t\t// same RBD image mounted by multiple Pods conflicts unless all Pods mount the image read-only\n\t\t\tif haveOverlap(mon, emon) \u0026\u0026 pool == epool \u0026\u0026 image == eimage \u0026\u0026 !(volume.RBD.ReadOnly \u0026\u0026 existingVolume.RBD.ReadOnly) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":100,"to":140}} {"id":100011035,"name":"haveOverlap","signature":"func haveOverlap(a1, a2 []string) bool","file":"pkg/scheduler/framework/plugins/volumerestrictions/volume_restrictions.go","code":"// haveOverlap searches two arrays and returns true if they have at least one common element; returns false otherwise.\nfunc haveOverlap(a1, a2 []string) bool {\n\tif len(a1) \u003e len(a2) {\n\t\ta1, a2 = a2, a1\n\t}\n\tm := sets.New(a1...)\n\tfor _, val := range a2 {\n\t\tif _, ok := m[val]; ok {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":142,"to":155}} {"id":100011036,"name":"PreFilter","signature":"func (pl *VolumeRestrictions) PreFilter(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod) (*framework.PreFilterResult, *framework.Status)","file":"pkg/scheduler/framework/plugins/volumerestrictions/volume_restrictions.go","code":"// PreFilter computes and stores cycleState containing details for enforcing ReadWriteOncePod.\nfunc (pl *VolumeRestrictions) PreFilter(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod) (*framework.PreFilterResult, *framework.Status) {\n\tif !pl.enableReadWriteOncePod {\n\t\treturn nil, nil\n\t}\n\n\tpvcs, err := pl.readWriteOncePodPVCsForPod(ctx, pod)\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\treturn nil, framework.NewStatus(framework.UnschedulableAndUnresolvable, err.Error())\n\t\t}\n\t\treturn nil, framework.AsStatus(err)\n\t}\n\n\ts, err := pl.calPreFilterState(ctx, pod, pvcs)\n\tif err != nil {\n\t\treturn nil, framework.AsStatus(err)\n\t}\n\tcycleState.Write(preFilterStateKey, s)\n\treturn nil, nil\n}","line":{"from":157,"to":177}} {"id":100011037,"name":"AddPod","signature":"func (pl *VolumeRestrictions) AddPod(ctx context.Context, cycleState *framework.CycleState, podToSchedule *v1.Pod, podInfoToAdd *framework.PodInfo, nodeInfo *framework.NodeInfo) *framework.Status","file":"pkg/scheduler/framework/plugins/volumerestrictions/volume_restrictions.go","code":"// AddPod from pre-computed data in cycleState.\nfunc (pl *VolumeRestrictions) AddPod(ctx context.Context, cycleState *framework.CycleState, podToSchedule *v1.Pod, podInfoToAdd *framework.PodInfo, nodeInfo *framework.NodeInfo) *framework.Status {\n\tif !pl.enableReadWriteOncePod {\n\t\treturn nil\n\t}\n\tstate, err := getPreFilterState(cycleState)\n\tif err != nil {\n\t\treturn framework.AsStatus(err)\n\t}\n\tstate.updateWithPod(podInfoToAdd, 1)\n\treturn nil\n}","line":{"from":179,"to":190}} {"id":100011038,"name":"RemovePod","signature":"func (pl *VolumeRestrictions) RemovePod(ctx context.Context, cycleState *framework.CycleState, podToSchedule *v1.Pod, podInfoToRemove *framework.PodInfo, nodeInfo *framework.NodeInfo) *framework.Status","file":"pkg/scheduler/framework/plugins/volumerestrictions/volume_restrictions.go","code":"// RemovePod from pre-computed data in cycleState.\nfunc (pl *VolumeRestrictions) RemovePod(ctx context.Context, cycleState *framework.CycleState, podToSchedule *v1.Pod, podInfoToRemove *framework.PodInfo, nodeInfo *framework.NodeInfo) *framework.Status {\n\tif !pl.enableReadWriteOncePod {\n\t\treturn nil\n\t}\n\tstate, err := getPreFilterState(cycleState)\n\tif err != nil {\n\t\treturn framework.AsStatus(err)\n\t}\n\tstate.updateWithPod(podInfoToRemove, -1)\n\treturn nil\n}","line":{"from":192,"to":203}} {"id":100011039,"name":"getPreFilterState","signature":"func getPreFilterState(cycleState *framework.CycleState) (*preFilterState, error)","file":"pkg/scheduler/framework/plugins/volumerestrictions/volume_restrictions.go","code":"func getPreFilterState(cycleState *framework.CycleState) (*preFilterState, error) {\n\tc, err := cycleState.Read(preFilterStateKey)\n\tif err != nil {\n\t\t// preFilterState doesn't exist, likely PreFilter wasn't invoked.\n\t\treturn nil, fmt.Errorf(\"cannot read %q from cycleState\", preFilterStateKey)\n\t}\n\n\ts, ok := c.(*preFilterState)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"%+v convert to volumerestrictions.state error\", c)\n\t}\n\treturn s, nil\n}","line":{"from":205,"to":217}} {"id":100011040,"name":"calPreFilterState","signature":"func (pl *VolumeRestrictions) calPreFilterState(ctx context.Context, pod *v1.Pod, pvcs sets.Set[string]) (*preFilterState, error)","file":"pkg/scheduler/framework/plugins/volumerestrictions/volume_restrictions.go","code":"// calPreFilterState computes preFilterState describing which PVCs use ReadWriteOncePod\n// and which pods in the cluster are in conflict.\nfunc (pl *VolumeRestrictions) calPreFilterState(ctx context.Context, pod *v1.Pod, pvcs sets.Set[string]) (*preFilterState, error) {\n\tconflictingPVCRefCount := 0\n\tfor pvc := range pvcs {\n\t\tkey := framework.GetNamespacedName(pod.Namespace, pvc)\n\t\tif pl.sharedLister.StorageInfos().IsPVCUsedByPods(key) {\n\t\t\t// There can only be at most one pod using the ReadWriteOncePod PVC.\n\t\t\tconflictingPVCRefCount += 1\n\t\t}\n\t}\n\treturn \u0026preFilterState{\n\t\treadWriteOncePodPVCs: pvcs,\n\t\tconflictingPVCRefCount: conflictingPVCRefCount,\n\t}, nil\n}","line":{"from":219,"to":234}} {"id":100011041,"name":"readWriteOncePodPVCsForPod","signature":"func (pl *VolumeRestrictions) readWriteOncePodPVCsForPod(ctx context.Context, pod *v1.Pod) (sets.Set[string], error)","file":"pkg/scheduler/framework/plugins/volumerestrictions/volume_restrictions.go","code":"func (pl *VolumeRestrictions) readWriteOncePodPVCsForPod(ctx context.Context, pod *v1.Pod) (sets.Set[string], error) {\n\tpvcs := sets.New[string]()\n\tfor _, volume := range pod.Spec.Volumes {\n\t\tif volume.PersistentVolumeClaim == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tpvc, err := pl.pvcLister.PersistentVolumeClaims(pod.Namespace).Get(volume.PersistentVolumeClaim.ClaimName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif !v1helper.ContainsAccessMode(pvc.Spec.AccessModes, v1.ReadWriteOncePod) {\n\t\t\tcontinue\n\t\t}\n\t\tpvcs.Insert(pvc.Name)\n\t}\n\treturn pvcs, nil\n}","line":{"from":236,"to":254}} {"id":100011042,"name":"satisfyVolumeConflicts","signature":"func satisfyVolumeConflicts(pod *v1.Pod, nodeInfo *framework.NodeInfo) bool","file":"pkg/scheduler/framework/plugins/volumerestrictions/volume_restrictions.go","code":"// Checks if scheduling the pod onto this node would cause any conflicts with\n// existing volumes.\nfunc satisfyVolumeConflicts(pod *v1.Pod, nodeInfo *framework.NodeInfo) bool {\n\tfor i := range pod.Spec.Volumes {\n\t\tv := \u0026pod.Spec.Volumes[i]\n\t\t// fast path if there is no conflict checking targets.\n\t\tif v.GCEPersistentDisk == nil \u0026\u0026 v.AWSElasticBlockStore == nil \u0026\u0026 v.RBD == nil \u0026\u0026 v.ISCSI == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, ev := range nodeInfo.Pods {\n\t\t\tif isVolumeConflict(v, ev.Pod) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}","line":{"from":256,"to":273}} {"id":100011043,"name":"satisfyReadWriteOncePod","signature":"func satisfyReadWriteOncePod(ctx context.Context, state *preFilterState) *framework.Status","file":"pkg/scheduler/framework/plugins/volumerestrictions/volume_restrictions.go","code":"// Checks if scheduling the pod would cause any ReadWriteOncePod PVC access mode conflicts.\nfunc satisfyReadWriteOncePod(ctx context.Context, state *preFilterState) *framework.Status {\n\tif state == nil {\n\t\treturn nil\n\t}\n\tif state.conflictingPVCRefCount \u003e 0 {\n\t\treturn framework.NewStatus(framework.Unschedulable, ErrReasonReadWriteOncePodConflict)\n\t}\n\treturn nil\n}","line":{"from":275,"to":284}} {"id":100011044,"name":"PreFilterExtensions","signature":"func (pl *VolumeRestrictions) PreFilterExtensions() framework.PreFilterExtensions","file":"pkg/scheduler/framework/plugins/volumerestrictions/volume_restrictions.go","code":"// PreFilterExtensions returns prefilter extensions, pod add and remove.\nfunc (pl *VolumeRestrictions) PreFilterExtensions() framework.PreFilterExtensions {\n\treturn pl\n}","line":{"from":286,"to":289}} {"id":100011045,"name":"Filter","signature":"func (pl *VolumeRestrictions) Filter(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status","file":"pkg/scheduler/framework/plugins/volumerestrictions/volume_restrictions.go","code":"// Filter invoked at the filter extension point.\n// It evaluates if a pod can fit due to the volumes it requests, and those that\n// are already mounted. If there is already a volume mounted on that node, another pod that uses the same volume\n// can't be scheduled there.\n// This is GCE, Amazon EBS, ISCSI and Ceph RBD specific for now:\n// - GCE PD allows multiple mounts as long as they're all read-only\n// - AWS EBS forbids any two pods mounting the same volume ID\n// - Ceph RBD forbids if any two pods share at least same monitor, and match pool and image, and the image is read-only\n// - ISCSI forbids if any two pods share at least same IQN and ISCSI volume is read-only\n// If the pod uses PVCs with the ReadWriteOncePod access mode, it evaluates if\n// these PVCs are already in-use and if preemption will help.\nfunc (pl *VolumeRestrictions) Filter(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status {\n\tif !satisfyVolumeConflicts(pod, nodeInfo) {\n\t\treturn framework.NewStatus(framework.Unschedulable, ErrReasonDiskConflict)\n\t}\n\tif !pl.enableReadWriteOncePod {\n\t\treturn nil\n\t}\n\tstate, err := getPreFilterState(cycleState)\n\tif err != nil {\n\t\treturn framework.AsStatus(err)\n\t}\n\treturn satisfyReadWriteOncePod(ctx, state)\n}","line":{"from":291,"to":314}} {"id":100011046,"name":"EventsToRegister","signature":"func (pl *VolumeRestrictions) EventsToRegister() []framework.ClusterEvent","file":"pkg/scheduler/framework/plugins/volumerestrictions/volume_restrictions.go","code":"// EventsToRegister returns the possible events that may make a Pod\n// failed by this plugin schedulable.\nfunc (pl *VolumeRestrictions) EventsToRegister() []framework.ClusterEvent {\n\treturn []framework.ClusterEvent{\n\t\t// Pods may fail to schedule because of volumes conflicting with other pods on same node.\n\t\t// Once running pods are deleted and volumes have been released, the unschedulable pod will be schedulable.\n\t\t// Due to immutable fields `spec.volumes`, pod update events are ignored.\n\t\t{Resource: framework.Pod, ActionType: framework.Delete},\n\t\t// A new Node may make a pod schedulable.\n\t\t{Resource: framework.Node, ActionType: framework.Add},\n\t\t// Pods may fail to schedule because the PVC it uses has not yet been created.\n\t\t// This PVC is required to exist to check its access modes.\n\t\t{Resource: framework.PersistentVolumeClaim, ActionType: framework.Add | framework.Update},\n\t}\n}","line":{"from":316,"to":330}} {"id":100011047,"name":"New","signature":"func New(_ runtime.Object, handle framework.Handle, fts feature.Features) (framework.Plugin, error)","file":"pkg/scheduler/framework/plugins/volumerestrictions/volume_restrictions.go","code":"// New initializes a new plugin and returns it.\nfunc New(_ runtime.Object, handle framework.Handle, fts feature.Features) (framework.Plugin, error) {\n\tinformerFactory := handle.SharedInformerFactory()\n\tpvcLister := informerFactory.Core().V1().PersistentVolumeClaims().Lister()\n\tsharedLister := handle.SnapshotSharedLister()\n\n\treturn \u0026VolumeRestrictions{\n\t\tpvcLister: pvcLister,\n\t\tsharedLister: sharedLister,\n\t\tenableReadWriteOncePod: fts.EnableReadWriteOncePod,\n\t}, nil\n}","line":{"from":332,"to":343}} {"id":100011048,"name":"Clone","signature":"func (d *stateData) Clone() framework.StateData","file":"pkg/scheduler/framework/plugins/volumezone/volume_zone.go","code":"func (d *stateData) Clone() framework.StateData {\n\treturn d\n}","line":{"from":75,"to":77}} {"id":100011049,"name":"Name","signature":"func (pl *VolumeZone) Name() string","file":"pkg/scheduler/framework/plugins/volumezone/volume_zone.go","code":"// Name returns name of the plugin. It is used in logs, etc.\nfunc (pl *VolumeZone) Name() string {\n\treturn Name\n}","line":{"from":86,"to":89}} {"id":100011050,"name":"PreFilter","signature":"func (pl *VolumeZone) PreFilter(ctx context.Context, cs *framework.CycleState, pod *v1.Pod) (*framework.PreFilterResult, *framework.Status)","file":"pkg/scheduler/framework/plugins/volumezone/volume_zone.go","code":"// PreFilter invoked at the prefilter extension point\n//\n// # It finds the topology of the PersistentVolumes corresponding to the volumes a pod requests\n//\n// Currently, this is only supported with PersistentVolumeClaims,\n// and only looks for the bound PersistentVolume.\nfunc (pl *VolumeZone) PreFilter(ctx context.Context, cs *framework.CycleState, pod *v1.Pod) (*framework.PreFilterResult, *framework.Status) {\n\tpodPVTopologies, status := pl.getPVbyPod(ctx, pod)\n\tif !status.IsSuccess() {\n\t\treturn nil, status\n\t}\n\tif len(podPVTopologies) == 0 {\n\t\treturn nil, framework.NewStatus(framework.Skip)\n\t}\n\tcs.Write(preFilterStateKey, \u0026stateData{podPVTopologies: podPVTopologies})\n\treturn nil, nil\n}","line":{"from":91,"to":107}} {"id":100011051,"name":"getPVbyPod","signature":"func (pl *VolumeZone) getPVbyPod(ctx context.Context, pod *v1.Pod) ([]pvTopology, *framework.Status)","file":"pkg/scheduler/framework/plugins/volumezone/volume_zone.go","code":"func (pl *VolumeZone) getPVbyPod(ctx context.Context, pod *v1.Pod) ([]pvTopology, *framework.Status) {\n\tpodPVTopologies := make([]pvTopology, 0)\n\n\tfor i := range pod.Spec.Volumes {\n\t\tvolume := pod.Spec.Volumes[i]\n\t\tif volume.PersistentVolumeClaim == nil {\n\t\t\tcontinue\n\t\t}\n\t\tpvcName := volume.PersistentVolumeClaim.ClaimName\n\t\tif pvcName == \"\" {\n\t\t\treturn nil, framework.NewStatus(framework.UnschedulableAndUnresolvable, \"PersistentVolumeClaim had no name\")\n\t\t}\n\t\tpvc, err := pl.pvcLister.PersistentVolumeClaims(pod.Namespace).Get(pvcName)\n\t\tif s := getErrorAsStatus(err); !s.IsSuccess() {\n\t\t\treturn nil, s\n\t\t}\n\n\t\tpvName := pvc.Spec.VolumeName\n\t\tif pvName == \"\" {\n\t\t\tscName := storagehelpers.GetPersistentVolumeClaimClass(pvc)\n\t\t\tif len(scName) == 0 {\n\t\t\t\treturn nil, framework.NewStatus(framework.UnschedulableAndUnresolvable, \"PersistentVolumeClaim had no pv name and storageClass name\")\n\t\t\t}\n\n\t\t\tclass, err := pl.scLister.Get(scName)\n\t\t\tif s := getErrorAsStatus(err); !s.IsSuccess() {\n\t\t\t\treturn nil, s\n\t\t\t}\n\t\t\tif class.VolumeBindingMode == nil {\n\t\t\t\treturn nil, framework.NewStatus(framework.UnschedulableAndUnresolvable, fmt.Sprintf(\"VolumeBindingMode not set for StorageClass %q\", scName))\n\t\t\t}\n\t\t\tif *class.VolumeBindingMode == storage.VolumeBindingWaitForFirstConsumer {\n\t\t\t\t// Skip unbound volumes\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\treturn nil, framework.NewStatus(framework.UnschedulableAndUnresolvable, \"PersistentVolume had no name\")\n\t\t}\n\n\t\tpv, err := pl.pvLister.Get(pvName)\n\t\tif s := getErrorAsStatus(err); !s.IsSuccess() {\n\t\t\treturn nil, s\n\t\t}\n\n\t\tfor _, key := range topologyLabels {\n\t\t\tif value, ok := pv.ObjectMeta.Labels[key]; ok {\n\t\t\t\tvolumeVSet, err := volumehelpers.LabelZonesToSet(value)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.InfoS(\"Failed to parse label, ignoring the label\", \"label\", fmt.Sprintf(\"%s:%s\", key, value), \"err\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tpodPVTopologies = append(podPVTopologies, pvTopology{\n\t\t\t\t\tpvName: pv.Name,\n\t\t\t\t\tkey: key,\n\t\t\t\t\tvalues: volumeVSet,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\treturn podPVTopologies, nil\n}","line":{"from":109,"to":169}} {"id":100011052,"name":"PreFilterExtensions","signature":"func (pl *VolumeZone) PreFilterExtensions() framework.PreFilterExtensions","file":"pkg/scheduler/framework/plugins/volumezone/volume_zone.go","code":"// PreFilterExtensions returns prefilter extensions, pod add and remove.\nfunc (pl *VolumeZone) PreFilterExtensions() framework.PreFilterExtensions {\n\treturn nil\n}","line":{"from":171,"to":174}} {"id":100011053,"name":"Filter","signature":"func (pl *VolumeZone) Filter(ctx context.Context, cs *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status","file":"pkg/scheduler/framework/plugins/volumezone/volume_zone.go","code":"// Filter invoked at the filter extension point.\n//\n// It evaluates if a pod can fit due to the volumes it requests, given\n// that some volumes may have zone scheduling constraints. The requirement is that any\n// volume zone-labels must match the equivalent zone-labels on the node. It is OK for\n// the node to have more zone-label constraints (for example, a hypothetical replicated\n// volume might allow region-wide access)\n//\n// Currently this is only supported with PersistentVolumeClaims, and looks to the labels\n// only on the bound PersistentVolume.\n//\n// Working with volumes declared inline in the pod specification (i.e. not\n// using a PersistentVolume) is likely to be harder, as it would require\n// determining the zone of a volume during scheduling, and that is likely to\n// require calling out to the cloud provider. It seems that we are moving away\n// from inline volume declarations anyway.\nfunc (pl *VolumeZone) Filter(ctx context.Context, cs *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status {\n\t// If a pod doesn't have any volume attached to it, the predicate will always be true.\n\t// Thus we make a fast path for it, to avoid unnecessary computations in this case.\n\tif len(pod.Spec.Volumes) == 0 {\n\t\treturn nil\n\t}\n\tvar podPVTopologies []pvTopology\n\tstate, err := getStateData(cs)\n\tif err != nil {\n\t\t// Fallback to calculate pv list here\n\t\tvar status *framework.Status\n\t\tpodPVTopologies, status = pl.getPVbyPod(ctx, pod)\n\t\tif !status.IsSuccess() {\n\t\t\treturn status\n\t\t}\n\t} else {\n\t\tpodPVTopologies = state.podPVTopologies\n\t}\n\n\tnode := nodeInfo.Node()\n\thasAnyNodeConstraint := false\n\tfor _, topologyLabel := range topologyLabels {\n\t\tif _, ok := node.Labels[topologyLabel]; ok {\n\t\t\thasAnyNodeConstraint = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !hasAnyNodeConstraint {\n\t\t// The node has no zone constraints, so we're OK to schedule.\n\t\t// This is to handle a single-zone cluster scenario where the node may not have any topology labels.\n\t\treturn nil\n\t}\n\n\tfor _, pvTopology := range podPVTopologies {\n\t\tv, ok := node.Labels[pvTopology.key]\n\t\tif !ok || !pvTopology.values.Has(v) {\n\t\t\tklog.V(10).InfoS(\"Won't schedule pod onto node due to volume (mismatch on label key)\", \"pod\", klog.KObj(pod), \"node\", klog.KObj(node), \"PV\", klog.KRef(\"\", pvTopology.pvName), \"PVLabelKey\", pvTopology.key)\n\t\t\treturn framework.NewStatus(framework.UnschedulableAndUnresolvable, ErrReasonConflict)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":176,"to":235}} {"id":100011054,"name":"getStateData","signature":"func getStateData(cs *framework.CycleState) (*stateData, error)","file":"pkg/scheduler/framework/plugins/volumezone/volume_zone.go","code":"func getStateData(cs *framework.CycleState) (*stateData, error) {\n\tstate, err := cs.Read(preFilterStateKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts, ok := state.(*stateData)\n\tif !ok {\n\t\treturn nil, errors.New(\"unable to convert state into stateData\")\n\t}\n\treturn s, nil\n}","line":{"from":237,"to":247}} {"id":100011055,"name":"getErrorAsStatus","signature":"func getErrorAsStatus(err error) *framework.Status","file":"pkg/scheduler/framework/plugins/volumezone/volume_zone.go","code":"func getErrorAsStatus(err error) *framework.Status {\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\treturn framework.NewStatus(framework.UnschedulableAndUnresolvable, err.Error())\n\t\t}\n\t\treturn framework.AsStatus(err)\n\t}\n\treturn nil\n}","line":{"from":249,"to":257}} {"id":100011056,"name":"EventsToRegister","signature":"func (pl *VolumeZone) EventsToRegister() []framework.ClusterEvent","file":"pkg/scheduler/framework/plugins/volumezone/volume_zone.go","code":"// EventsToRegister returns the possible events that may make a Pod\n// failed by this plugin schedulable.\nfunc (pl *VolumeZone) EventsToRegister() []framework.ClusterEvent {\n\treturn []framework.ClusterEvent{\n\t\t// New storageClass with bind mode `VolumeBindingWaitForFirstConsumer` will make a pod schedulable.\n\t\t// Due to immutable field `storageClass.volumeBindingMode`, storageClass update events are ignored.\n\t\t{Resource: framework.StorageClass, ActionType: framework.Add},\n\t\t// A new node or updating a node's volume zone labels may make a pod schedulable.\n\t\t{Resource: framework.Node, ActionType: framework.Add | framework.UpdateNodeLabel},\n\t\t// A new pvc may make a pod schedulable.\n\t\t// Due to fields are immutable except `spec.resources`, pvc update events are ignored.\n\t\t{Resource: framework.PersistentVolumeClaim, ActionType: framework.Add},\n\t\t// A new pv or updating a pv's volume zone labels may make a pod schedulable.\n\t\t{Resource: framework.PersistentVolume, ActionType: framework.Add | framework.Update},\n\t}\n}","line":{"from":259,"to":274}} {"id":100011057,"name":"New","signature":"func New(_ runtime.Object, handle framework.Handle) (framework.Plugin, error)","file":"pkg/scheduler/framework/plugins/volumezone/volume_zone.go","code":"// New initializes a new plugin and returns it.\nfunc New(_ runtime.Object, handle framework.Handle) (framework.Plugin, error) {\n\tinformerFactory := handle.SharedInformerFactory()\n\tpvLister := informerFactory.Core().V1().PersistentVolumes().Lister()\n\tpvcLister := informerFactory.Core().V1().PersistentVolumeClaims().Lister()\n\tscLister := informerFactory.Storage().V1().StorageClasses().Lister()\n\treturn \u0026VolumeZone{\n\t\tpvLister,\n\t\tpvcLister,\n\t\tscLister,\n\t}, nil\n}","line":{"from":276,"to":287}} {"id":100011058,"name":"Victims","signature":"func (s *candidate) Victims() *extenderv1.Victims","file":"pkg/scheduler/framework/preemption/preemption.go","code":"// Victims returns s.victims.\nfunc (s *candidate) Victims() *extenderv1.Victims {\n\treturn s.victims\n}","line":{"from":65,"to":68}} {"id":100011059,"name":"Name","signature":"func (s *candidate) Name() string","file":"pkg/scheduler/framework/preemption/preemption.go","code":"// Name returns s.name.\nfunc (s *candidate) Name() string {\n\treturn s.name\n}","line":{"from":70,"to":73}} {"id":100011060,"name":"newCandidateList","signature":"func newCandidateList(size int32) *candidateList","file":"pkg/scheduler/framework/preemption/preemption.go","code":"func newCandidateList(size int32) *candidateList {\n\treturn \u0026candidateList{idx: -1, items: make([]Candidate, size)}\n}","line":{"from":80,"to":82}} {"id":100011061,"name":"add","signature":"func (cl *candidateList) add(c *candidate)","file":"pkg/scheduler/framework/preemption/preemption.go","code":"// add adds a new candidate to the internal array atomically.\nfunc (cl *candidateList) add(c *candidate) {\n\tif idx := atomic.AddInt32(\u0026cl.idx, 1); idx \u003c int32(len(cl.items)) {\n\t\tcl.items[idx] = c\n\t}\n}","line":{"from":84,"to":89}} {"id":100011062,"name":"size","signature":"func (cl *candidateList) size() int32","file":"pkg/scheduler/framework/preemption/preemption.go","code":"// size returns the number of candidate stored. Note that some add() operations\n// might still be executing when this is called, so care must be taken to\n// ensure that all add() operations complete before accessing the elements of\n// the list.\nfunc (cl *candidateList) size() int32 {\n\tn := atomic.LoadInt32(\u0026cl.idx) + 1\n\tif n \u003e= int32(len(cl.items)) {\n\t\tn = int32(len(cl.items))\n\t}\n\treturn n\n}","line":{"from":91,"to":101}} {"id":100011063,"name":"get","signature":"func (cl *candidateList) get() []Candidate","file":"pkg/scheduler/framework/preemption/preemption.go","code":"// get returns the internal candidate array. This function is NOT atomic and\n// assumes that all add() operations have been completed.\nfunc (cl *candidateList) get() []Candidate {\n\treturn cl.items[:cl.size()]\n}","line":{"from":103,"to":107}} {"id":100011064,"name":"Preempt","signature":"func (ev *Evaluator) Preempt(ctx context.Context, pod *v1.Pod, m framework.NodeToStatusMap) (*framework.PostFilterResult, *framework.Status)","file":"pkg/scheduler/framework/preemption/preemption.go","code":"// Preempt returns a PostFilterResult carrying suggested nominatedNodeName, along with a Status.\n// The semantics of returned \u003cPostFilterResult, Status\u003e varies on different scenarios:\n//\n// - \u003cnil, Error\u003e. This denotes it's a transient/rare error that may be self-healed in future cycles.\n//\n// - \u003cnil, Unschedulable\u003e. This status is mostly as expected like the preemptor is waiting for the\n// victims to be fully terminated.\n//\n// - In both cases above, a nil PostFilterResult is returned to keep the pod's nominatedNodeName unchanged.\n//\n// - \u003cnon-nil PostFilterResult, Unschedulable\u003e. It indicates the pod cannot be scheduled even with preemption.\n// In this case, a non-nil PostFilterResult is returned and result.NominatingMode instructs how to deal with\n// the nominatedNodeName.\n//\n// - \u003cnon-nil PostFilterResult, Success\u003e. It's the regular happy path\n// and the non-empty nominatedNodeName will be applied to the preemptor pod.\nfunc (ev *Evaluator) Preempt(ctx context.Context, pod *v1.Pod, m framework.NodeToStatusMap) (*framework.PostFilterResult, *framework.Status) {\n\t// 0) Fetch the latest version of \u003cpod\u003e.\n\t// It's safe to directly fetch pod here. Because the informer cache has already been\n\t// initialized when creating the Scheduler obj.\n\t// However, tests may need to manually initialize the shared pod informer.\n\tpodNamespace, podName := pod.Namespace, pod.Name\n\tpod, err := ev.PodLister.Pods(pod.Namespace).Get(pod.Name)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Getting the updated preemptor pod object\", \"pod\", klog.KRef(podNamespace, podName))\n\t\treturn nil, framework.AsStatus(err)\n\t}\n\n\t// 1) Ensure the preemptor is eligible to preempt other pods.\n\tif ok, msg := ev.PodEligibleToPreemptOthers(pod, m[pod.Status.NominatedNodeName]); !ok {\n\t\tklog.V(5).InfoS(\"Pod is not eligible for preemption\", \"pod\", klog.KObj(pod), \"reason\", msg)\n\t\treturn nil, framework.NewStatus(framework.Unschedulable, msg)\n\t}\n\n\t// 2) Find all preemption candidates.\n\tcandidates, nodeToStatusMap, err := ev.findCandidates(ctx, pod, m)\n\tif err != nil \u0026\u0026 len(candidates) == 0 {\n\t\treturn nil, framework.AsStatus(err)\n\t}\n\n\t// Return a FitError only when there are no candidates that fit the pod.\n\tif len(candidates) == 0 {\n\t\tfitError := \u0026framework.FitError{\n\t\t\tPod: pod,\n\t\t\tNumAllNodes: len(nodeToStatusMap),\n\t\t\tDiagnosis: framework.Diagnosis{\n\t\t\t\tNodeToStatusMap: nodeToStatusMap,\n\t\t\t\t// Leave FailedPlugins as nil as it won't be used on moving Pods.\n\t\t\t},\n\t\t}\n\t\t// Specify nominatedNodeName to clear the pod's nominatedNodeName status, if applicable.\n\t\treturn framework.NewPostFilterResultWithNominatedNode(\"\"), framework.NewStatus(framework.Unschedulable, fitError.Error())\n\t}\n\n\t// 3) Interact with registered Extenders to filter out some candidates if needed.\n\tcandidates, status := ev.callExtenders(pod, candidates)\n\tif !status.IsSuccess() {\n\t\treturn nil, status\n\t}\n\n\t// 4) Find the best candidate.\n\tbestCandidate := ev.SelectCandidate(candidates)\n\tif bestCandidate == nil || len(bestCandidate.Name()) == 0 {\n\t\treturn nil, framework.NewStatus(framework.Unschedulable, \"no candidate node for preemption\")\n\t}\n\n\t// 5) Perform preparation work before nominating the selected candidate.\n\tif status := ev.prepareCandidate(ctx, bestCandidate, pod, ev.PluginName); !status.IsSuccess() {\n\t\treturn nil, status\n\t}\n\n\treturn framework.NewPostFilterResultWithNominatedNode(bestCandidate.Name()), framework.NewStatus(framework.Success)\n}","line":{"from":136,"to":208}} {"id":100011065,"name":"findCandidates","signature":"func (ev *Evaluator) findCandidates(ctx context.Context, pod *v1.Pod, m framework.NodeToStatusMap) ([]Candidate, framework.NodeToStatusMap, error)","file":"pkg/scheduler/framework/preemption/preemption.go","code":"// FindCandidates calculates a slice of preemption candidates.\n// Each candidate is executable to make the given \u003cpod\u003e schedulable.\nfunc (ev *Evaluator) findCandidates(ctx context.Context, pod *v1.Pod, m framework.NodeToStatusMap) ([]Candidate, framework.NodeToStatusMap, error) {\n\tallNodes, err := ev.Handler.SnapshotSharedLister().NodeInfos().List()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif len(allNodes) == 0 {\n\t\treturn nil, nil, errors.New(\"no nodes available\")\n\t}\n\tpotentialNodes, unschedulableNodeStatus := nodesWherePreemptionMightHelp(allNodes, m)\n\tif len(potentialNodes) == 0 {\n\t\tklog.V(3).InfoS(\"Preemption will not help schedule pod on any node\", \"pod\", klog.KObj(pod))\n\t\t// In this case, we should clean-up any existing nominated node name of the pod.\n\t\tif err := util.ClearNominatedNodeName(ctx, ev.Handler.ClientSet(), pod); err != nil {\n\t\t\tklog.ErrorS(err, \"Cannot clear 'NominatedNodeName' field of pod\", \"pod\", klog.KObj(pod))\n\t\t\t// We do not return as this error is not critical.\n\t\t}\n\t\treturn nil, unschedulableNodeStatus, nil\n\t}\n\n\tpdbs, err := getPodDisruptionBudgets(ev.PdbLister)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\toffset, numCandidates := ev.GetOffsetAndNumCandidates(int32(len(potentialNodes)))\n\tif klogV := klog.V(5); klogV.Enabled() {\n\t\tvar sample []string\n\t\tfor i := offset; i \u003c offset+10 \u0026\u0026 i \u003c int32(len(potentialNodes)); i++ {\n\t\t\tsample = append(sample, potentialNodes[i].Node().Name)\n\t\t}\n\t\tklogV.InfoS(\"Selecting candidates from a pool of nodes\", \"potentialNodesCount\", len(potentialNodes), \"offset\", offset, \"sampleLength\", len(sample), \"sample\", sample, \"candidates\", numCandidates)\n\t}\n\tcandidates, nodeStatuses, err := ev.DryRunPreemption(ctx, pod, potentialNodes, pdbs, offset, numCandidates)\n\tfor node, nodeStatus := range unschedulableNodeStatus {\n\t\tnodeStatuses[node] = nodeStatus\n\t}\n\treturn candidates, nodeStatuses, err\n}","line":{"from":210,"to":249}} {"id":100011066,"name":"callExtenders","signature":"func (ev *Evaluator) callExtenders(pod *v1.Pod, candidates []Candidate) ([]Candidate, *framework.Status)","file":"pkg/scheduler/framework/preemption/preemption.go","code":"// callExtenders calls given \u003cextenders\u003e to select the list of feasible candidates.\n// We will only check \u003ccandidates\u003e with extenders that support preemption.\n// Extenders which do not support preemption may later prevent preemptor from being scheduled on the nominated\n// node. In that case, scheduler will find a different host for the preemptor in subsequent scheduling cycles.\nfunc (ev *Evaluator) callExtenders(pod *v1.Pod, candidates []Candidate) ([]Candidate, *framework.Status) {\n\textenders := ev.Handler.Extenders()\n\tnodeLister := ev.Handler.SnapshotSharedLister().NodeInfos()\n\tif len(extenders) == 0 {\n\t\treturn candidates, nil\n\t}\n\n\t// Migrate candidate slice to victimsMap to adapt to the Extender interface.\n\t// It's only applicable for candidate slice that have unique nominated node name.\n\tvictimsMap := ev.CandidatesToVictimsMap(candidates)\n\tif len(victimsMap) == 0 {\n\t\treturn candidates, nil\n\t}\n\tfor _, extender := range extenders {\n\t\tif !extender.SupportsPreemption() || !extender.IsInterested(pod) {\n\t\t\tcontinue\n\t\t}\n\t\tnodeNameToVictims, err := extender.ProcessPreemption(pod, victimsMap, nodeLister)\n\t\tif err != nil {\n\t\t\tif extender.IsIgnorable() {\n\t\t\t\tklog.InfoS(\"Skipping extender as it returned error and has ignorable flag set\",\n\t\t\t\t\t\"extender\", extender, \"err\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn nil, framework.AsStatus(err)\n\t\t}\n\t\t// Check if the returned victims are valid.\n\t\tfor nodeName, victims := range nodeNameToVictims {\n\t\t\tif victims == nil || len(victims.Pods) == 0 {\n\t\t\t\tif extender.IsIgnorable() {\n\t\t\t\t\tdelete(nodeNameToVictims, nodeName)\n\t\t\t\t\tklog.InfoS(\"Ignoring node without victims\", \"node\", klog.KRef(\"\", nodeName))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\treturn nil, framework.AsStatus(fmt.Errorf(\"expected at least one victim pod on node %q\", nodeName))\n\t\t\t}\n\t\t}\n\n\t\t// Replace victimsMap with new result after preemption. So the\n\t\t// rest of extenders can continue use it as parameter.\n\t\tvictimsMap = nodeNameToVictims\n\n\t\t// If node list becomes empty, no preemption can happen regardless of other extenders.\n\t\tif len(victimsMap) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tvar newCandidates []Candidate\n\tfor nodeName := range victimsMap {\n\t\tnewCandidates = append(newCandidates, \u0026candidate{\n\t\t\tvictims: victimsMap[nodeName],\n\t\t\tname: nodeName,\n\t\t})\n\t}\n\treturn newCandidates, nil\n}","line":{"from":251,"to":311}} {"id":100011067,"name":"SelectCandidate","signature":"func (ev *Evaluator) SelectCandidate(candidates []Candidate) Candidate","file":"pkg/scheduler/framework/preemption/preemption.go","code":"// SelectCandidate chooses the best-fit candidate from given \u003ccandidates\u003e and return it.\n// NOTE: This method is exported for easier testing in default preemption.\nfunc (ev *Evaluator) SelectCandidate(candidates []Candidate) Candidate {\n\tif len(candidates) == 0 {\n\t\treturn nil\n\t}\n\tif len(candidates) == 1 {\n\t\treturn candidates[0]\n\t}\n\n\tvictimsMap := ev.CandidatesToVictimsMap(candidates)\n\tcandidateNode := pickOneNodeForPreemption(victimsMap)\n\n\t// Same as candidatesToVictimsMap, this logic is not applicable for out-of-tree\n\t// preemption plugins that exercise different candidates on the same nominated node.\n\tif victims := victimsMap[candidateNode]; victims != nil {\n\t\treturn \u0026candidate{\n\t\t\tvictims: victims,\n\t\t\tname: candidateNode,\n\t\t}\n\t}\n\n\t// We shouldn't reach here.\n\tklog.ErrorS(errors.New(\"no candidate selected\"), \"Should not reach here\", \"candidates\", candidates)\n\t// To not break the whole flow, return the first candidate.\n\treturn candidates[0]\n}","line":{"from":313,"to":339}} {"id":100011068,"name":"prepareCandidate","signature":"func (ev *Evaluator) prepareCandidate(ctx context.Context, c Candidate, pod *v1.Pod, pluginName string) *framework.Status","file":"pkg/scheduler/framework/preemption/preemption.go","code":"// prepareCandidate does some preparation work before nominating the selected candidate:\n// - Evict the victim pods\n// - Reject the victim pods if they are in waitingPod map\n// - Clear the low-priority pods' nominatedNodeName status if needed\nfunc (ev *Evaluator) prepareCandidate(ctx context.Context, c Candidate, pod *v1.Pod, pluginName string) *framework.Status {\n\tfh := ev.Handler\n\tcs := ev.Handler.ClientSet()\n\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\terrCh := parallelize.NewErrorChannel()\n\tpreemptPod := func(index int) {\n\t\tvictim := c.Victims().Pods[index]\n\t\t// If the victim is a WaitingPod, send a reject message to the PermitPlugin.\n\t\t// Otherwise we should delete the victim.\n\t\tif waitingPod := fh.GetWaitingPod(victim.UID); waitingPod != nil {\n\t\t\twaitingPod.Reject(pluginName, \"preempted\")\n\t\t\tklog.V(2).InfoS(\"Preemptor pod rejected a waiting pod\", \"preemptor\", klog.KObj(pod), \"waitingPod\", klog.KObj(victim), \"node\", c.Name())\n\t\t} else {\n\t\t\tif feature.DefaultFeatureGate.Enabled(features.PodDisruptionConditions) {\n\t\t\t\tvictimPodApply := corev1apply.Pod(victim.Name, victim.Namespace).WithStatus(corev1apply.PodStatus())\n\t\t\t\tvictimPodApply.Status.WithConditions(corev1apply.PodCondition().\n\t\t\t\t\tWithType(v1.DisruptionTarget).\n\t\t\t\t\tWithStatus(v1.ConditionTrue).\n\t\t\t\t\tWithReason(v1.PodReasonPreemptionByScheduler).\n\t\t\t\t\tWithMessage(fmt.Sprintf(\"%s: preempting to accommodate a higher priority pod\", pod.Spec.SchedulerName)).\n\t\t\t\t\tWithLastTransitionTime(metav1.Now()),\n\t\t\t\t)\n\n\t\t\t\tif _, err := cs.CoreV1().Pods(victim.Namespace).ApplyStatus(ctx, victimPodApply, metav1.ApplyOptions{FieldManager: fieldManager, Force: true}); err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"Preparing pod preemption\", \"pod\", klog.KObj(victim), \"preemptor\", klog.KObj(pod))\n\t\t\t\t\terrCh.SendErrorWithCancel(err, cancel)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err := util.DeletePod(ctx, cs, victim); err != nil {\n\t\t\t\tklog.ErrorS(err, \"Preempting pod\", \"pod\", klog.KObj(victim), \"preemptor\", klog.KObj(pod))\n\t\t\t\terrCh.SendErrorWithCancel(err, cancel)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tklog.V(2).InfoS(\"Preemptor Pod preempted victim Pod\", \"preemptor\", klog.KObj(pod), \"victim\", klog.KObj(victim), \"node\", c.Name())\n\t\t}\n\n\t\tfh.EventRecorder().Eventf(victim, pod, v1.EventTypeNormal, \"Preempted\", \"Preempting\", \"Preempted by a pod on node %v\", c.Name())\n\t}\n\n\tfh.Parallelizer().Until(ctx, len(c.Victims().Pods), preemptPod, ev.PluginName)\n\tif err := errCh.ReceiveError(); err != nil {\n\t\treturn framework.AsStatus(err)\n\t}\n\n\tmetrics.PreemptionVictims.Observe(float64(len(c.Victims().Pods)))\n\n\t// Lower priority pods nominated to run on this node, may no longer fit on\n\t// this node. So, we should remove their nomination. Removing their\n\t// nomination updates these pods and moves them to the active queue. It\n\t// lets scheduler find another place for them.\n\tnominatedPods := getLowerPriorityNominatedPods(fh, pod, c.Name())\n\tif err := util.ClearNominatedNodeName(ctx, cs, nominatedPods...); err != nil {\n\t\tklog.ErrorS(err, \"Cannot clear 'NominatedNodeName' field\")\n\t\t// We do not return as this error is not critical.\n\t}\n\n\treturn nil\n}","line":{"from":341,"to":405}} {"id":100011069,"name":"nodesWherePreemptionMightHelp","signature":"func nodesWherePreemptionMightHelp(nodes []*framework.NodeInfo, m framework.NodeToStatusMap) ([]*framework.NodeInfo, framework.NodeToStatusMap)","file":"pkg/scheduler/framework/preemption/preemption.go","code":"// nodesWherePreemptionMightHelp returns a list of nodes with failed predicates\n// that may be satisfied by removing pods from the node.\nfunc nodesWherePreemptionMightHelp(nodes []*framework.NodeInfo, m framework.NodeToStatusMap) ([]*framework.NodeInfo, framework.NodeToStatusMap) {\n\tvar potentialNodes []*framework.NodeInfo\n\tnodeStatuses := make(framework.NodeToStatusMap)\n\tfor _, node := range nodes {\n\t\tname := node.Node().Name\n\t\t// We rely on the status by each plugin - 'Unschedulable' or 'UnschedulableAndUnresolvable'\n\t\t// to determine whether preemption may help or not on the node.\n\t\tif m[name].Code() == framework.UnschedulableAndUnresolvable {\n\t\t\tnodeStatuses[node.Node().Name] = framework.NewStatus(framework.UnschedulableAndUnresolvable, \"Preemption is not helpful for scheduling\")\n\t\t\tcontinue\n\t\t}\n\t\tpotentialNodes = append(potentialNodes, node)\n\t}\n\treturn potentialNodes, nodeStatuses\n}","line":{"from":407,"to":423}} {"id":100011070,"name":"getPodDisruptionBudgets","signature":"func getPodDisruptionBudgets(pdbLister policylisters.PodDisruptionBudgetLister) ([]*policy.PodDisruptionBudget, error)","file":"pkg/scheduler/framework/preemption/preemption.go","code":"func getPodDisruptionBudgets(pdbLister policylisters.PodDisruptionBudgetLister) ([]*policy.PodDisruptionBudget, error) {\n\tif pdbLister != nil {\n\t\treturn pdbLister.List(labels.Everything())\n\t}\n\treturn nil, nil\n}","line":{"from":425,"to":430}} {"id":100011071,"name":"pickOneNodeForPreemption","signature":"func pickOneNodeForPreemption(nodesToVictims map[string]*extenderv1.Victims) string","file":"pkg/scheduler/framework/preemption/preemption.go","code":"// pickOneNodeForPreemption chooses one node among the given nodes. It assumes\n// pods in each map entry are ordered by decreasing priority.\n// It picks a node based on the following criteria:\n// 1. A node with minimum number of PDB violations.\n// 2. A node with minimum highest priority victim is picked.\n// 3. Ties are broken by sum of priorities of all victims.\n// 4. If there are still ties, node with the minimum number of victims is picked.\n// 5. If there are still ties, node with the latest start time of all highest priority victims is picked.\n// 6. If there are still ties, the first such node is picked (sort of randomly).\n// The 'minNodes1' and 'minNodes2' are being reused here to save the memory\n// allocation and garbage collection time.\nfunc pickOneNodeForPreemption(nodesToVictims map[string]*extenderv1.Victims) string {\n\tif len(nodesToVictims) == 0 {\n\t\treturn \"\"\n\t}\n\n\tallCandidates := make([]string, 0, len(nodesToVictims))\n\tfor node := range nodesToVictims {\n\t\tallCandidates = append(allCandidates, node)\n\t}\n\n\tminNumPDBViolatingScoreFunc := func(node string) int64 {\n\t\t// The smaller the NumPDBViolations, the higher the score.\n\t\treturn -nodesToVictims[node].NumPDBViolations\n\t}\n\tminHighestPriorityScoreFunc := func(node string) int64 {\n\t\t// highestPodPriority is the highest priority among the victims on this node.\n\t\thighestPodPriority := corev1helpers.PodPriority(nodesToVictims[node].Pods[0])\n\t\t// The smaller the highestPodPriority, the higher the score.\n\t\treturn -int64(highestPodPriority)\n\t}\n\tminSumPrioritiesScoreFunc := func(node string) int64 {\n\t\tvar sumPriorities int64\n\t\tfor _, pod := range nodesToVictims[node].Pods {\n\t\t\t// We add MaxInt32+1 to all priorities to make all of them \u003e= 0. This is\n\t\t\t// needed so that a node with a few pods with negative priority is not\n\t\t\t// picked over a node with a smaller number of pods with the same negative\n\t\t\t// priority (and similar scenarios).\n\t\t\tsumPriorities += int64(corev1helpers.PodPriority(pod)) + int64(math.MaxInt32+1)\n\t\t}\n\t\t// The smaller the sumPriorities, the higher the score.\n\t\treturn -sumPriorities\n\t}\n\tminNumPodsScoreFunc := func(node string) int64 {\n\t\t// The smaller the length of pods, the higher the score.\n\t\treturn -int64(len(nodesToVictims[node].Pods))\n\t}\n\tlatestStartTimeScoreFunc := func(node string) int64 {\n\t\t// Get earliest start time of all pods on the current node.\n\t\tearliestStartTimeOnNode := util.GetEarliestPodStartTime(nodesToVictims[node])\n\t\tif earliestStartTimeOnNode == nil {\n\t\t\tklog.ErrorS(errors.New(\"earliestStartTime is nil for node\"), \"Should not reach here\", \"node\", node)\n\t\t\treturn int64(math.MinInt64)\n\t\t}\n\t\t// The bigger the earliestStartTimeOnNode, the higher the score.\n\t\treturn earliestStartTimeOnNode.UnixNano()\n\t}\n\n\t// Each scoreFunc scores the nodes according to specific rules and keeps the name of the node\n\t// with the highest score. If and only if the scoreFunc has more than one node with the highest\n\t// score, we will execute the other scoreFunc in order of precedence.\n\tscoreFuncs := []func(string) int64{\n\t\t// A node with a minimum number of PDB is preferable.\n\t\tminNumPDBViolatingScoreFunc,\n\t\t// A node with a minimum highest priority victim is preferable.\n\t\tminHighestPriorityScoreFunc,\n\t\t// A node with the smallest sum of priorities is preferable.\n\t\tminSumPrioritiesScoreFunc,\n\t\t// A node with the minimum number of pods is preferable.\n\t\tminNumPodsScoreFunc,\n\t\t// A node with the latest start time of all highest priority victims is preferable.\n\t\tlatestStartTimeScoreFunc,\n\t\t// If there are still ties, then the first Node in the list is selected.\n\t}\n\n\tfor _, f := range scoreFuncs {\n\t\tselectedNodes := []string{}\n\t\tmaxScore := int64(math.MinInt64)\n\t\tfor _, node := range allCandidates {\n\t\t\tscore := f(node)\n\t\t\tif score \u003e maxScore {\n\t\t\t\tmaxScore = score\n\t\t\t\tselectedNodes = []string{}\n\t\t\t}\n\t\t\tif score == maxScore {\n\t\t\t\tselectedNodes = append(selectedNodes, node)\n\t\t\t}\n\t\t}\n\t\tif len(selectedNodes) == 1 {\n\t\t\treturn selectedNodes[0]\n\t\t}\n\t\tallCandidates = selectedNodes\n\t}\n\n\treturn allCandidates[0]\n}","line":{"from":432,"to":527}} {"id":100011072,"name":"getLowerPriorityNominatedPods","signature":"func getLowerPriorityNominatedPods(pn framework.PodNominator, pod *v1.Pod, nodeName string) []*v1.Pod","file":"pkg/scheduler/framework/preemption/preemption.go","code":"// getLowerPriorityNominatedPods returns pods whose priority is smaller than the\n// priority of the given \"pod\" and are nominated to run on the given node.\n// Note: We could possibly check if the nominated lower priority pods still fit\n// and return those that no longer fit, but that would require lots of\n// manipulation of NodeInfo and PreFilter state per nominated pod. It may not be\n// worth the complexity, especially because we generally expect to have a very\n// small number of nominated pods per node.\nfunc getLowerPriorityNominatedPods(pn framework.PodNominator, pod *v1.Pod, nodeName string) []*v1.Pod {\n\tpodInfos := pn.NominatedPodsForNode(nodeName)\n\n\tif len(podInfos) == 0 {\n\t\treturn nil\n\t}\n\n\tvar lowerPriorityPods []*v1.Pod\n\tpodPriority := corev1helpers.PodPriority(pod)\n\tfor _, pi := range podInfos {\n\t\tif corev1helpers.PodPriority(pi.Pod) \u003c podPriority {\n\t\t\tlowerPriorityPods = append(lowerPriorityPods, pi.Pod)\n\t\t}\n\t}\n\treturn lowerPriorityPods\n}","line":{"from":529,"to":551}} {"id":100011073,"name":"DryRunPreemption","signature":"func (ev *Evaluator) DryRunPreemption(ctx context.Context, pod *v1.Pod, potentialNodes []*framework.NodeInfo,","file":"pkg/scheduler/framework/preemption/preemption.go","code":"// DryRunPreemption simulates Preemption logic on \u003cpotentialNodes\u003e in parallel,\n// returns preemption candidates and a map indicating filtered nodes statuses.\n// The number of candidates depends on the constraints defined in the plugin's args. In the returned list of\n// candidates, ones that do not violate PDB are preferred over ones that do.\n// NOTE: This method is exported for easier testing in default preemption.\nfunc (ev *Evaluator) DryRunPreemption(ctx context.Context, pod *v1.Pod, potentialNodes []*framework.NodeInfo,\n\tpdbs []*policy.PodDisruptionBudget, offset int32, numCandidates int32) ([]Candidate, framework.NodeToStatusMap, error) {\n\tfh := ev.Handler\n\tnonViolatingCandidates := newCandidateList(numCandidates)\n\tviolatingCandidates := newCandidateList(numCandidates)\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\tnodeStatuses := make(framework.NodeToStatusMap)\n\tvar statusesLock sync.Mutex\n\tvar errs []error\n\tcheckNode := func(i int) {\n\t\tnodeInfoCopy := potentialNodes[(int(offset)+i)%len(potentialNodes)].Clone()\n\t\tstateCopy := ev.State.Clone()\n\t\tpods, numPDBViolations, status := ev.SelectVictimsOnNode(ctx, stateCopy, pod, nodeInfoCopy, pdbs)\n\t\tif status.IsSuccess() \u0026\u0026 len(pods) != 0 {\n\t\t\tvictims := extenderv1.Victims{\n\t\t\t\tPods: pods,\n\t\t\t\tNumPDBViolations: int64(numPDBViolations),\n\t\t\t}\n\t\t\tc := \u0026candidate{\n\t\t\t\tvictims: \u0026victims,\n\t\t\t\tname: nodeInfoCopy.Node().Name,\n\t\t\t}\n\t\t\tif numPDBViolations == 0 {\n\t\t\t\tnonViolatingCandidates.add(c)\n\t\t\t} else {\n\t\t\t\tviolatingCandidates.add(c)\n\t\t\t}\n\t\t\tnvcSize, vcSize := nonViolatingCandidates.size(), violatingCandidates.size()\n\t\t\tif nvcSize \u003e 0 \u0026\u0026 nvcSize+vcSize \u003e= numCandidates {\n\t\t\t\tcancel()\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tif status.IsSuccess() \u0026\u0026 len(pods) == 0 {\n\t\t\tstatus = framework.AsStatus(fmt.Errorf(\"expected at least one victim pod on node %q\", nodeInfoCopy.Node().Name))\n\t\t}\n\t\tstatusesLock.Lock()\n\t\tif status.Code() == framework.Error {\n\t\t\terrs = append(errs, status.AsError())\n\t\t}\n\t\tnodeStatuses[nodeInfoCopy.Node().Name] = status\n\t\tstatusesLock.Unlock()\n\t}\n\tfh.Parallelizer().Until(ctx, len(potentialNodes), checkNode, ev.PluginName)\n\treturn append(nonViolatingCandidates.get(), violatingCandidates.get()...), nodeStatuses, utilerrors.NewAggregate(errs)\n}","line":{"from":553,"to":604}} {"id":100011074,"name":"getExtensionPoints","signature":"func (f *frameworkImpl) getExtensionPoints(plugins *config.Plugins) []extensionPoint","file":"pkg/scheduler/framework/runtime/framework.go","code":"func (f *frameworkImpl) getExtensionPoints(plugins *config.Plugins) []extensionPoint {\n\treturn []extensionPoint{\n\t\t{\u0026plugins.PreFilter, \u0026f.preFilterPlugins},\n\t\t{\u0026plugins.Filter, \u0026f.filterPlugins},\n\t\t{\u0026plugins.PostFilter, \u0026f.postFilterPlugins},\n\t\t{\u0026plugins.Reserve, \u0026f.reservePlugins},\n\t\t{\u0026plugins.PreScore, \u0026f.preScorePlugins},\n\t\t{\u0026plugins.Score, \u0026f.scorePlugins},\n\t\t{\u0026plugins.PreBind, \u0026f.preBindPlugins},\n\t\t{\u0026plugins.Bind, \u0026f.bindPlugins},\n\t\t{\u0026plugins.PostBind, \u0026f.postBindPlugins},\n\t\t{\u0026plugins.Permit, \u0026f.permitPlugins},\n\t\t{\u0026plugins.PreEnqueue, \u0026f.preEnqueuePlugins},\n\t\t{\u0026plugins.QueueSort, \u0026f.queueSortPlugins},\n\t}\n}","line":{"from":102,"to":117}} {"id":100011075,"name":"Extenders","signature":"func (f *frameworkImpl) Extenders() []framework.Extender","file":"pkg/scheduler/framework/runtime/framework.go","code":"// Extenders returns the registered extenders.\nfunc (f *frameworkImpl) Extenders() []framework.Extender {\n\treturn f.extenders\n}","line":{"from":119,"to":122}} {"id":100011076,"name":"WithComponentConfigVersion","signature":"func WithComponentConfigVersion(componentConfigVersion string) Option","file":"pkg/scheduler/framework/runtime/framework.go","code":"// WithComponentConfigVersion sets the component config version to the\n// KubeSchedulerConfiguration version used. The string should be the full\n// scheme group/version of the external type we converted from (for example\n// \"kubescheduler.config.k8s.io/v1beta2\")\nfunc WithComponentConfigVersion(componentConfigVersion string) Option {\n\treturn func(o *frameworkOptions) {\n\t\to.componentConfigVersion = componentConfigVersion\n\t}\n}","line":{"from":142,"to":150}} {"id":100011077,"name":"WithClientSet","signature":"func WithClientSet(clientSet clientset.Interface) Option","file":"pkg/scheduler/framework/runtime/framework.go","code":"// WithClientSet sets clientSet for the scheduling frameworkImpl.\nfunc WithClientSet(clientSet clientset.Interface) Option {\n\treturn func(o *frameworkOptions) {\n\t\to.clientSet = clientSet\n\t}\n}","line":{"from":152,"to":157}} {"id":100011078,"name":"WithKubeConfig","signature":"func WithKubeConfig(kubeConfig *restclient.Config) Option","file":"pkg/scheduler/framework/runtime/framework.go","code":"// WithKubeConfig sets kubeConfig for the scheduling frameworkImpl.\nfunc WithKubeConfig(kubeConfig *restclient.Config) Option {\n\treturn func(o *frameworkOptions) {\n\t\to.kubeConfig = kubeConfig\n\t}\n}","line":{"from":159,"to":164}} {"id":100011079,"name":"WithEventRecorder","signature":"func WithEventRecorder(recorder events.EventRecorder) Option","file":"pkg/scheduler/framework/runtime/framework.go","code":"// WithEventRecorder sets clientSet for the scheduling frameworkImpl.\nfunc WithEventRecorder(recorder events.EventRecorder) Option {\n\treturn func(o *frameworkOptions) {\n\t\to.eventRecorder = recorder\n\t}\n}","line":{"from":166,"to":171}} {"id":100011080,"name":"WithInformerFactory","signature":"func WithInformerFactory(informerFactory informers.SharedInformerFactory) Option","file":"pkg/scheduler/framework/runtime/framework.go","code":"// WithInformerFactory sets informer factory for the scheduling frameworkImpl.\nfunc WithInformerFactory(informerFactory informers.SharedInformerFactory) Option {\n\treturn func(o *frameworkOptions) {\n\t\to.informerFactory = informerFactory\n\t}\n}","line":{"from":173,"to":178}} {"id":100011081,"name":"WithSnapshotSharedLister","signature":"func WithSnapshotSharedLister(snapshotSharedLister framework.SharedLister) Option","file":"pkg/scheduler/framework/runtime/framework.go","code":"// WithSnapshotSharedLister sets the SharedLister of the snapshot.\nfunc WithSnapshotSharedLister(snapshotSharedLister framework.SharedLister) Option {\n\treturn func(o *frameworkOptions) {\n\t\to.snapshotSharedLister = snapshotSharedLister\n\t}\n}","line":{"from":180,"to":185}} {"id":100011082,"name":"WithPodNominator","signature":"func WithPodNominator(nominator framework.PodNominator) Option","file":"pkg/scheduler/framework/runtime/framework.go","code":"// WithPodNominator sets podNominator for the scheduling frameworkImpl.\nfunc WithPodNominator(nominator framework.PodNominator) Option {\n\treturn func(o *frameworkOptions) {\n\t\to.podNominator = nominator\n\t}\n}","line":{"from":187,"to":192}} {"id":100011083,"name":"WithExtenders","signature":"func WithExtenders(extenders []framework.Extender) Option","file":"pkg/scheduler/framework/runtime/framework.go","code":"// WithExtenders sets extenders for the scheduling frameworkImpl.\nfunc WithExtenders(extenders []framework.Extender) Option {\n\treturn func(o *frameworkOptions) {\n\t\to.extenders = extenders\n\t}\n}","line":{"from":194,"to":199}} {"id":100011084,"name":"WithParallelism","signature":"func WithParallelism(parallelism int) Option","file":"pkg/scheduler/framework/runtime/framework.go","code":"// WithParallelism sets parallelism for the scheduling frameworkImpl.\nfunc WithParallelism(parallelism int) Option {\n\treturn func(o *frameworkOptions) {\n\t\to.parallelizer = parallelize.NewParallelizer(parallelism)\n\t}\n}","line":{"from":201,"to":206}} {"id":100011085,"name":"WithCaptureProfile","signature":"func WithCaptureProfile(c CaptureProfile) Option","file":"pkg/scheduler/framework/runtime/framework.go","code":"// WithCaptureProfile sets a callback to capture the finalized profile.\nfunc WithCaptureProfile(c CaptureProfile) Option {\n\treturn func(o *frameworkOptions) {\n\t\to.captureProfile = c\n\t}\n}","line":{"from":211,"to":216}} {"id":100011086,"name":"WithClusterEventMap","signature":"func WithClusterEventMap(m map[framework.ClusterEvent]sets.String) Option","file":"pkg/scheduler/framework/runtime/framework.go","code":"// WithClusterEventMap sets clusterEventMap for the scheduling frameworkImpl.\nfunc WithClusterEventMap(m map[framework.ClusterEvent]sets.String) Option {\n\treturn func(o *frameworkOptions) {\n\t\to.clusterEventMap = m\n\t}\n}","line":{"from":218,"to":223}} {"id":100011087,"name":"WithMetricsRecorder","signature":"func WithMetricsRecorder(r *metrics.MetricAsyncRecorder) Option","file":"pkg/scheduler/framework/runtime/framework.go","code":"// WithMetricsRecorder sets metrics recorder for the scheduling frameworkImpl.\nfunc WithMetricsRecorder(r *metrics.MetricAsyncRecorder) Option {\n\treturn func(o *frameworkOptions) {\n\t\to.metricsRecorder = r\n\t}\n}","line":{"from":225,"to":230}} {"id":100011088,"name":"defaultFrameworkOptions","signature":"func defaultFrameworkOptions(stopCh \u003c-chan struct{}) frameworkOptions","file":"pkg/scheduler/framework/runtime/framework.go","code":"// defaultFrameworkOptions are applied when no option corresponding to those fields exist.\nfunc defaultFrameworkOptions(stopCh \u003c-chan struct{}) frameworkOptions {\n\treturn frameworkOptions{\n\t\tmetricsRecorder: metrics.NewMetricsAsyncRecorder(1000, time.Second, stopCh),\n\t\tclusterEventMap: make(map[framework.ClusterEvent]sets.String),\n\t\tparallelizer: parallelize.NewParallelizer(parallelize.DefaultParallelism),\n\t}\n}","line":{"from":232,"to":239}} {"id":100011089,"name":"NewFramework","signature":"func NewFramework(r Registry, profile *config.KubeSchedulerProfile, stopCh \u003c-chan struct{}, opts ...Option) (framework.Framework, error)","file":"pkg/scheduler/framework/runtime/framework.go","code":"// NewFramework initializes plugins given the configuration and the registry.\nfunc NewFramework(r Registry, profile *config.KubeSchedulerProfile, stopCh \u003c-chan struct{}, opts ...Option) (framework.Framework, error) {\n\toptions := defaultFrameworkOptions(stopCh)\n\tfor _, opt := range opts {\n\t\topt(\u0026options)\n\t}\n\n\tf := \u0026frameworkImpl{\n\t\tregistry: r,\n\t\tsnapshotSharedLister: options.snapshotSharedLister,\n\t\tscorePluginWeight: make(map[string]int),\n\t\twaitingPods: newWaitingPodsMap(),\n\t\tclientSet: options.clientSet,\n\t\tkubeConfig: options.kubeConfig,\n\t\teventRecorder: options.eventRecorder,\n\t\tinformerFactory: options.informerFactory,\n\t\tmetricsRecorder: options.metricsRecorder,\n\t\textenders: options.extenders,\n\t\tPodNominator: options.podNominator,\n\t\tparallelizer: options.parallelizer,\n\t}\n\n\tif profile == nil {\n\t\treturn f, nil\n\t}\n\n\tf.profileName = profile.SchedulerName\n\tf.percentageOfNodesToScore = profile.PercentageOfNodesToScore\n\tif profile.Plugins == nil {\n\t\treturn f, nil\n\t}\n\n\t// get needed plugins from config\n\tpg := f.pluginsNeeded(profile.Plugins)\n\n\tpluginConfig := make(map[string]runtime.Object, len(profile.PluginConfig))\n\tfor i := range profile.PluginConfig {\n\t\tname := profile.PluginConfig[i].Name\n\t\tif _, ok := pluginConfig[name]; ok {\n\t\t\treturn nil, fmt.Errorf(\"repeated config for plugin %s\", name)\n\t\t}\n\t\tpluginConfig[name] = profile.PluginConfig[i].Args\n\t}\n\toutputProfile := config.KubeSchedulerProfile{\n\t\tSchedulerName: f.profileName,\n\t\tPercentageOfNodesToScore: f.percentageOfNodesToScore,\n\t\tPlugins: profile.Plugins,\n\t\tPluginConfig: make([]config.PluginConfig, 0, len(pg)),\n\t}\n\n\tpluginsMap := make(map[string]framework.Plugin)\n\tfor name, factory := range r {\n\t\t// initialize only needed plugins.\n\t\tif !pg.Has(name) {\n\t\t\tcontinue\n\t\t}\n\n\t\targs := pluginConfig[name]\n\t\tif args != nil {\n\t\t\toutputProfile.PluginConfig = append(outputProfile.PluginConfig, config.PluginConfig{\n\t\t\t\tName: name,\n\t\t\t\tArgs: args,\n\t\t\t})\n\t\t}\n\t\tp, err := factory(args, f)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"initializing plugin %q: %w\", name, err)\n\t\t}\n\t\tpluginsMap[name] = p\n\n\t\t// Update ClusterEventMap in place.\n\t\tfillEventToPluginMap(p, options.clusterEventMap)\n\t}\n\n\t// initialize plugins per individual extension points\n\tfor _, e := range f.getExtensionPoints(profile.Plugins) {\n\t\tif err := updatePluginList(e.slicePtr, *e.plugins, pluginsMap); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// initialize multiPoint plugins to their expanded extension points\n\tif len(profile.Plugins.MultiPoint.Enabled) \u003e 0 {\n\t\tif err := f.expandMultiPointPlugins(profile, pluginsMap); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif len(f.queueSortPlugins) != 1 {\n\t\treturn nil, fmt.Errorf(\"only one queue sort plugin required for profile with scheduler name %q, but got %d\", profile.SchedulerName, len(f.queueSortPlugins))\n\t}\n\tif len(f.bindPlugins) == 0 {\n\t\treturn nil, fmt.Errorf(\"at least one bind plugin is needed for profile with scheduler name %q\", profile.SchedulerName)\n\t}\n\n\tif err := getScoreWeights(f, pluginsMap, append(profile.Plugins.Score.Enabled, profile.Plugins.MultiPoint.Enabled...)); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Verifying the score weights again since Plugin.Name() could return a different\n\t// value from the one used in the configuration.\n\tfor _, scorePlugin := range f.scorePlugins {\n\t\tif f.scorePluginWeight[scorePlugin.Name()] == 0 {\n\t\t\treturn nil, fmt.Errorf(\"score plugin %q is not configured with weight\", scorePlugin.Name())\n\t\t}\n\t}\n\n\tif options.captureProfile != nil {\n\t\tif len(outputProfile.PluginConfig) != 0 {\n\t\t\tsort.Slice(outputProfile.PluginConfig, func(i, j int) bool {\n\t\t\t\treturn outputProfile.PluginConfig[i].Name \u003c outputProfile.PluginConfig[j].Name\n\t\t\t})\n\t\t} else {\n\t\t\toutputProfile.PluginConfig = nil\n\t\t}\n\t\toptions.captureProfile(outputProfile)\n\t}\n\n\t// Cache metric streams for prefilter and filter plugins.\n\tfor i, pl := range f.preFilterPlugins {\n\t\tf.preFilterPlugins[i] = \u0026instrumentedPreFilterPlugin{\n\t\t\tPreFilterPlugin: f.preFilterPlugins[i],\n\t\t\tmetric: metrics.PluginEvaluationTotal.WithLabelValues(pl.Name(), metrics.PreFilter, f.profileName),\n\t\t}\n\t}\n\tfor i, pl := range f.filterPlugins {\n\t\tf.filterPlugins[i] = \u0026instrumentedFilterPlugin{\n\t\t\tFilterPlugin: f.filterPlugins[i],\n\t\t\tmetric: metrics.PluginEvaluationTotal.WithLabelValues(pl.Name(), metrics.Filter, f.profileName),\n\t\t}\n\t}\n\n\treturn f, nil\n}","line":{"from":243,"to":376}} {"id":100011090,"name":"SetPodNominator","signature":"func (f *frameworkImpl) SetPodNominator(n framework.PodNominator)","file":"pkg/scheduler/framework/runtime/framework.go","code":"func (f *frameworkImpl) SetPodNominator(n framework.PodNominator) {\n\tf.PodNominator = n\n}","line":{"from":378,"to":380}} {"id":100011091,"name":"getScoreWeights","signature":"func getScoreWeights(f *frameworkImpl, pluginsMap map[string]framework.Plugin, plugins []config.Plugin) error","file":"pkg/scheduler/framework/runtime/framework.go","code":"// getScoreWeights makes sure that, between MultiPoint-Score plugin weights and individual Score\n// plugin weights there is not an overflow of MaxTotalScore.\nfunc getScoreWeights(f *frameworkImpl, pluginsMap map[string]framework.Plugin, plugins []config.Plugin) error {\n\tvar totalPriority int64\n\tscorePlugins := reflect.ValueOf(\u0026f.scorePlugins).Elem()\n\tpluginType := scorePlugins.Type().Elem()\n\tfor _, e := range plugins {\n\t\tpg := pluginsMap[e.Name]\n\t\tif !reflect.TypeOf(pg).Implements(pluginType) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// We append MultiPoint plugins to the list of Score plugins. So if this plugin has already been\n\t\t// encountered, let the individual Score weight take precedence.\n\t\tif _, ok := f.scorePluginWeight[e.Name]; ok {\n\t\t\tcontinue\n\t\t}\n\t\t// a weight of zero is not permitted, plugins can be disabled explicitly\n\t\t// when configured.\n\t\tf.scorePluginWeight[e.Name] = int(e.Weight)\n\t\tif f.scorePluginWeight[e.Name] == 0 {\n\t\t\tf.scorePluginWeight[e.Name] = 1\n\t\t}\n\n\t\t// Checks totalPriority against MaxTotalScore to avoid overflow\n\t\tif int64(f.scorePluginWeight[e.Name])*framework.MaxNodeScore \u003e framework.MaxTotalScore-totalPriority {\n\t\t\treturn fmt.Errorf(\"total score of Score plugins could overflow\")\n\t\t}\n\t\ttotalPriority += int64(f.scorePluginWeight[e.Name]) * framework.MaxNodeScore\n\t}\n\treturn nil\n}","line":{"from":382,"to":413}} {"id":100011092,"name":"newOrderedSet","signature":"func newOrderedSet() *orderedSet","file":"pkg/scheduler/framework/runtime/framework.go","code":"func newOrderedSet() *orderedSet {\n\treturn \u0026orderedSet{set: make(map[string]int)}\n}","line":{"from":421,"to":423}} {"id":100011093,"name":"insert","signature":"func (os *orderedSet) insert(s string)","file":"pkg/scheduler/framework/runtime/framework.go","code":"func (os *orderedSet) insert(s string) {\n\tif os.has(s) {\n\t\treturn\n\t}\n\tos.set[s] = len(os.list)\n\tos.list = append(os.list, s)\n}","line":{"from":425,"to":431}} {"id":100011094,"name":"has","signature":"func (os *orderedSet) has(s string) bool","file":"pkg/scheduler/framework/runtime/framework.go","code":"func (os *orderedSet) has(s string) bool {\n\t_, found := os.set[s]\n\treturn found\n}","line":{"from":433,"to":436}} {"id":100011095,"name":"delete","signature":"func (os *orderedSet) delete(s string)","file":"pkg/scheduler/framework/runtime/framework.go","code":"func (os *orderedSet) delete(s string) {\n\tif i, found := os.set[s]; found {\n\t\tdelete(os.set, s)\n\t\tos.list = append(os.list[:i-os.deletionCnt], os.list[i+1-os.deletionCnt:]...)\n\t\tos.deletionCnt++\n\t}\n}","line":{"from":438,"to":444}} {"id":100011096,"name":"expandMultiPointPlugins","signature":"func (f *frameworkImpl) expandMultiPointPlugins(profile *config.KubeSchedulerProfile, pluginsMap map[string]framework.Plugin) error","file":"pkg/scheduler/framework/runtime/framework.go","code":"func (f *frameworkImpl) expandMultiPointPlugins(profile *config.KubeSchedulerProfile, pluginsMap map[string]framework.Plugin) error {\n\t// initialize MultiPoint plugins\n\tfor _, e := range f.getExtensionPoints(profile.Plugins) {\n\t\tplugins := reflect.ValueOf(e.slicePtr).Elem()\n\t\tpluginType := plugins.Type().Elem()\n\t\t// build enabledSet of plugins already registered via normal extension points\n\t\t// to check double registration\n\t\tenabledSet := newOrderedSet()\n\t\tfor _, plugin := range e.plugins.Enabled {\n\t\t\tenabledSet.insert(plugin.Name)\n\t\t}\n\n\t\tdisabledSet := sets.NewString()\n\t\tfor _, disabledPlugin := range e.plugins.Disabled {\n\t\t\tdisabledSet.Insert(disabledPlugin.Name)\n\t\t}\n\t\tif disabledSet.Has(\"*\") {\n\t\t\tklog.V(4).InfoS(\"all plugins disabled for extension point, skipping MultiPoint expansion\", \"extension\", pluginType)\n\t\t\tcontinue\n\t\t}\n\n\t\t// track plugins enabled via multipoint separately from those enabled by specific extensions,\n\t\t// so that we can distinguish between double-registration and explicit overrides\n\t\tmultiPointEnabled := newOrderedSet()\n\t\toverridePlugins := newOrderedSet()\n\t\tfor _, ep := range profile.Plugins.MultiPoint.Enabled {\n\t\t\tpg, ok := pluginsMap[ep.Name]\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"%s %q does not exist\", pluginType.Name(), ep.Name)\n\t\t\t}\n\n\t\t\t// if this plugin doesn't implement the type for the current extension we're trying to expand, skip\n\t\t\tif !reflect.TypeOf(pg).Implements(pluginType) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// a plugin that's enabled via MultiPoint can still be disabled for specific extension points\n\t\t\tif disabledSet.Has(ep.Name) {\n\t\t\t\tklog.V(4).InfoS(\"plugin disabled for extension point\", \"plugin\", ep.Name, \"extension\", pluginType)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// if this plugin has already been enabled by the specific extension point,\n\t\t\t// the user intent is to override the default plugin or make some other explicit setting.\n\t\t\t// Either way, discard the MultiPoint value for this plugin.\n\t\t\t// This maintains expected behavior for overriding default plugins (see https://github.com/kubernetes/kubernetes/pull/99582)\n\t\t\tif enabledSet.has(ep.Name) {\n\t\t\t\toverridePlugins.insert(ep.Name)\n\t\t\t\tklog.InfoS(\"MultiPoint plugin is explicitly re-configured; overriding\", \"plugin\", ep.Name)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// if this plugin is already registered via MultiPoint, then this is\n\t\t\t// a double registration and an error in the config.\n\t\t\tif multiPointEnabled.has(ep.Name) {\n\t\t\t\treturn fmt.Errorf(\"plugin %q already registered as %q\", ep.Name, pluginType.Name())\n\t\t\t}\n\n\t\t\t// we only need to update the multipoint set, since we already have the specific extension set from above\n\t\t\tmultiPointEnabled.insert(ep.Name)\n\t\t}\n\n\t\t// Reorder plugins. Here is the expected order:\n\t\t// - part 1: overridePlugins. Their order stay intact as how they're specified in regular extension point.\n\t\t// - part 2: multiPointEnabled - i.e., plugin defined in multipoint but not in regular extension point.\n\t\t// - part 3: other plugins (excluded by part 1 \u0026 2) in regular extension point.\n\t\tnewPlugins := reflect.New(reflect.TypeOf(e.slicePtr).Elem()).Elem()\n\t\t// part 1\n\t\tfor _, name := range enabledSet.list {\n\t\t\tif overridePlugins.has(name) {\n\t\t\t\tnewPlugins = reflect.Append(newPlugins, reflect.ValueOf(pluginsMap[name]))\n\t\t\t\tenabledSet.delete(name)\n\t\t\t}\n\t\t}\n\t\t// part 2\n\t\tfor _, name := range multiPointEnabled.list {\n\t\t\tnewPlugins = reflect.Append(newPlugins, reflect.ValueOf(pluginsMap[name]))\n\t\t}\n\t\t// part 3\n\t\tfor _, name := range enabledSet.list {\n\t\t\tnewPlugins = reflect.Append(newPlugins, reflect.ValueOf(pluginsMap[name]))\n\t\t}\n\t\tplugins.Set(newPlugins)\n\t}\n\treturn nil\n}","line":{"from":446,"to":531}} {"id":100011097,"name":"fillEventToPluginMap","signature":"func fillEventToPluginMap(p framework.Plugin, eventToPlugins map[framework.ClusterEvent]sets.String)","file":"pkg/scheduler/framework/runtime/framework.go","code":"func fillEventToPluginMap(p framework.Plugin, eventToPlugins map[framework.ClusterEvent]sets.String) {\n\text, ok := p.(framework.EnqueueExtensions)\n\tif !ok {\n\t\t// If interface EnqueueExtensions is not implemented, register the default events\n\t\t// to the plugin. This is to ensure backward compatibility.\n\t\tregisterClusterEvents(p.Name(), eventToPlugins, allClusterEvents)\n\t\treturn\n\t}\n\n\tevents := ext.EventsToRegister()\n\t// It's rare that a plugin implements EnqueueExtensions but returns nil.\n\t// We treat it as: the plugin is not interested in any event, and hence pod failed by that plugin\n\t// cannot be moved by any regular cluster event.\n\tif len(events) == 0 {\n\t\tklog.InfoS(\"Plugin's EventsToRegister() returned nil\", \"plugin\", p.Name())\n\t\treturn\n\t}\n\t// The most common case: a plugin implements EnqueueExtensions and returns non-nil result.\n\tregisterClusterEvents(p.Name(), eventToPlugins, events)\n}","line":{"from":533,"to":552}} {"id":100011098,"name":"registerClusterEvents","signature":"func registerClusterEvents(name string, eventToPlugins map[framework.ClusterEvent]sets.String, evts []framework.ClusterEvent)","file":"pkg/scheduler/framework/runtime/framework.go","code":"func registerClusterEvents(name string, eventToPlugins map[framework.ClusterEvent]sets.String, evts []framework.ClusterEvent) {\n\tfor _, evt := range evts {\n\t\tif eventToPlugins[evt] == nil {\n\t\t\teventToPlugins[evt] = sets.NewString(name)\n\t\t} else {\n\t\t\teventToPlugins[evt].Insert(name)\n\t\t}\n\t}\n}","line":{"from":554,"to":562}} {"id":100011099,"name":"updatePluginList","signature":"func updatePluginList(pluginList interface{}, pluginSet config.PluginSet, pluginsMap map[string]framework.Plugin) error","file":"pkg/scheduler/framework/runtime/framework.go","code":"func updatePluginList(pluginList interface{}, pluginSet config.PluginSet, pluginsMap map[string]framework.Plugin) error {\n\tplugins := reflect.ValueOf(pluginList).Elem()\n\tpluginType := plugins.Type().Elem()\n\tset := sets.NewString()\n\tfor _, ep := range pluginSet.Enabled {\n\t\tpg, ok := pluginsMap[ep.Name]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"%s %q does not exist\", pluginType.Name(), ep.Name)\n\t\t}\n\n\t\tif !reflect.TypeOf(pg).Implements(pluginType) {\n\t\t\treturn fmt.Errorf(\"plugin %q does not extend %s plugin\", ep.Name, pluginType.Name())\n\t\t}\n\n\t\tif set.Has(ep.Name) {\n\t\t\treturn fmt.Errorf(\"plugin %q already registered as %q\", ep.Name, pluginType.Name())\n\t\t}\n\n\t\tset.Insert(ep.Name)\n\n\t\tnewPlugins := reflect.Append(plugins, reflect.ValueOf(pg))\n\t\tplugins.Set(newPlugins)\n\t}\n\treturn nil\n}","line":{"from":564,"to":588}} {"id":100011100,"name":"PreEnqueuePlugins","signature":"func (f *frameworkImpl) PreEnqueuePlugins() []framework.PreEnqueuePlugin","file":"pkg/scheduler/framework/runtime/framework.go","code":"// EnqueuePlugins returns the registered enqueue plugins.\nfunc (f *frameworkImpl) PreEnqueuePlugins() []framework.PreEnqueuePlugin {\n\treturn f.preEnqueuePlugins\n}","line":{"from":590,"to":593}} {"id":100011101,"name":"QueueSortFunc","signature":"func (f *frameworkImpl) QueueSortFunc() framework.LessFunc","file":"pkg/scheduler/framework/runtime/framework.go","code":"// QueueSortFunc returns the function to sort pods in scheduling queue\nfunc (f *frameworkImpl) QueueSortFunc() framework.LessFunc {\n\tif f == nil {\n\t\t// If frameworkImpl is nil, simply keep their order unchanged.\n\t\t// NOTE: this is primarily for tests.\n\t\treturn func(_, _ *framework.QueuedPodInfo) bool { return false }\n\t}\n\n\tif len(f.queueSortPlugins) == 0 {\n\t\tpanic(\"No QueueSort plugin is registered in the frameworkImpl.\")\n\t}\n\n\t// Only one QueueSort plugin can be enabled.\n\treturn f.queueSortPlugins[0].Less\n}","line":{"from":595,"to":609}} {"id":100011102,"name":"RunPreFilterPlugins","signature":"func (f *frameworkImpl) RunPreFilterPlugins(ctx context.Context, state *framework.CycleState, pod *v1.Pod) (_ *framework.PreFilterResult, status *framework.Status)","file":"pkg/scheduler/framework/runtime/framework.go","code":"// RunPreFilterPlugins runs the set of configured PreFilter plugins. It returns\n// *Status and its code is set to non-success if any of the plugins returns\n// anything but Success/Skip.\n// When it returns Skip status, returned PreFilterResult and other fields in status are just ignored,\n// and coupled Filter plugin/PreFilterExtensions() will be skipped in this scheduling cycle.\n// If a non-success status is returned, then the scheduling cycle is aborted.\nfunc (f *frameworkImpl) RunPreFilterPlugins(ctx context.Context, state *framework.CycleState, pod *v1.Pod) (_ *framework.PreFilterResult, status *framework.Status) {\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tmetrics.FrameworkExtensionPointDuration.WithLabelValues(metrics.PreFilter, status.Code().String(), f.profileName).Observe(metrics.SinceInSeconds(startTime))\n\t}()\n\tvar result *framework.PreFilterResult\n\tvar pluginsWithNodes []string\n\tskipPlugins := sets.New[string]()\n\tfor _, pl := range f.preFilterPlugins {\n\t\tr, s := f.runPreFilterPlugin(ctx, pl, state, pod)\n\t\tif s.IsSkip() {\n\t\t\tskipPlugins.Insert(pl.Name())\n\t\t\tcontinue\n\t\t}\n\t\tif !s.IsSuccess() {\n\t\t\ts.SetFailedPlugin(pl.Name())\n\t\t\tif s.IsUnschedulable() {\n\t\t\t\treturn nil, s\n\t\t\t}\n\t\t\treturn nil, framework.AsStatus(fmt.Errorf(\"running PreFilter plugin %q: %w\", pl.Name(), s.AsError())).WithFailedPlugin(pl.Name())\n\t\t}\n\t\tif !r.AllNodes() {\n\t\t\tpluginsWithNodes = append(pluginsWithNodes, pl.Name())\n\t\t}\n\t\tresult = result.Merge(r)\n\t\tif !result.AllNodes() \u0026\u0026 len(result.NodeNames) == 0 {\n\t\t\tmsg := fmt.Sprintf(\"node(s) didn't satisfy plugin(s) %v simultaneously\", pluginsWithNodes)\n\t\t\tif len(pluginsWithNodes) == 1 {\n\t\t\t\tmsg = fmt.Sprintf(\"node(s) didn't satisfy plugin %v\", pluginsWithNodes[0])\n\t\t\t}\n\t\t\treturn nil, framework.NewStatus(framework.Unschedulable, msg)\n\t\t}\n\t}\n\tstate.SkipFilterPlugins = skipPlugins\n\treturn result, nil\n}","line":{"from":611,"to":652}} {"id":100011103,"name":"runPreFilterPlugin","signature":"func (f *frameworkImpl) runPreFilterPlugin(ctx context.Context, pl framework.PreFilterPlugin, state *framework.CycleState, pod *v1.Pod) (*framework.PreFilterResult, *framework.Status)","file":"pkg/scheduler/framework/runtime/framework.go","code":"func (f *frameworkImpl) runPreFilterPlugin(ctx context.Context, pl framework.PreFilterPlugin, state *framework.CycleState, pod *v1.Pod) (*framework.PreFilterResult, *framework.Status) {\n\tif !state.ShouldRecordPluginMetrics() {\n\t\treturn pl.PreFilter(ctx, state, pod)\n\t}\n\tstartTime := time.Now()\n\tresult, status := pl.PreFilter(ctx, state, pod)\n\tf.metricsRecorder.ObservePluginDurationAsync(metrics.PreFilter, pl.Name(), status.Code().String(), metrics.SinceInSeconds(startTime))\n\treturn result, status\n}","line":{"from":654,"to":662}} {"id":100011104,"name":"RunPreFilterExtensionAddPod","signature":"func (f *frameworkImpl) RunPreFilterExtensionAddPod(","file":"pkg/scheduler/framework/runtime/framework.go","code":"// RunPreFilterExtensionAddPod calls the AddPod interface for the set of configured\n// PreFilter plugins. It returns directly if any of the plugins return any\n// status other than Success.\nfunc (f *frameworkImpl) RunPreFilterExtensionAddPod(\n\tctx context.Context,\n\tstate *framework.CycleState,\n\tpodToSchedule *v1.Pod,\n\tpodInfoToAdd *framework.PodInfo,\n\tnodeInfo *framework.NodeInfo,\n) (status *framework.Status) {\n\tfor _, pl := range f.preFilterPlugins {\n\t\tif pl.PreFilterExtensions() == nil || state.SkipFilterPlugins.Has(pl.Name()) {\n\t\t\tcontinue\n\t\t}\n\t\tstatus = f.runPreFilterExtensionAddPod(ctx, pl, state, podToSchedule, podInfoToAdd, nodeInfo)\n\t\tif !status.IsSuccess() {\n\t\t\terr := status.AsError()\n\t\t\tklog.ErrorS(err, \"Failed running AddPod on PreFilter plugin\", \"plugin\", pl.Name(), \"pod\", klog.KObj(podToSchedule))\n\t\t\treturn framework.AsStatus(fmt.Errorf(\"running AddPod on PreFilter plugin %q: %w\", pl.Name(), err))\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":664,"to":687}} {"id":100011105,"name":"runPreFilterExtensionAddPod","signature":"func (f *frameworkImpl) runPreFilterExtensionAddPod(ctx context.Context, pl framework.PreFilterPlugin, state *framework.CycleState, podToSchedule *v1.Pod, podInfoToAdd *framework.PodInfo, nodeInfo *framework.NodeInfo) *framework.Status","file":"pkg/scheduler/framework/runtime/framework.go","code":"func (f *frameworkImpl) runPreFilterExtensionAddPod(ctx context.Context, pl framework.PreFilterPlugin, state *framework.CycleState, podToSchedule *v1.Pod, podInfoToAdd *framework.PodInfo, nodeInfo *framework.NodeInfo) *framework.Status {\n\tif !state.ShouldRecordPluginMetrics() {\n\t\treturn pl.PreFilterExtensions().AddPod(ctx, state, podToSchedule, podInfoToAdd, nodeInfo)\n\t}\n\tstartTime := time.Now()\n\tstatus := pl.PreFilterExtensions().AddPod(ctx, state, podToSchedule, podInfoToAdd, nodeInfo)\n\tf.metricsRecorder.ObservePluginDurationAsync(metrics.PreFilterExtensionAddPod, pl.Name(), status.Code().String(), metrics.SinceInSeconds(startTime))\n\treturn status\n}","line":{"from":689,"to":697}} {"id":100011106,"name":"RunPreFilterExtensionRemovePod","signature":"func (f *frameworkImpl) RunPreFilterExtensionRemovePod(","file":"pkg/scheduler/framework/runtime/framework.go","code":"// RunPreFilterExtensionRemovePod calls the RemovePod interface for the set of configured\n// PreFilter plugins. It returns directly if any of the plugins return any\n// status other than Success.\nfunc (f *frameworkImpl) RunPreFilterExtensionRemovePod(\n\tctx context.Context,\n\tstate *framework.CycleState,\n\tpodToSchedule *v1.Pod,\n\tpodInfoToRemove *framework.PodInfo,\n\tnodeInfo *framework.NodeInfo,\n) (status *framework.Status) {\n\tfor _, pl := range f.preFilterPlugins {\n\t\tif pl.PreFilterExtensions() == nil || state.SkipFilterPlugins.Has(pl.Name()) {\n\t\t\tcontinue\n\t\t}\n\t\tstatus = f.runPreFilterExtensionRemovePod(ctx, pl, state, podToSchedule, podInfoToRemove, nodeInfo)\n\t\tif !status.IsSuccess() {\n\t\t\terr := status.AsError()\n\t\t\tklog.ErrorS(err, \"Failed running RemovePod on PreFilter plugin\", \"plugin\", pl.Name(), \"pod\", klog.KObj(podToSchedule))\n\t\t\treturn framework.AsStatus(fmt.Errorf(\"running RemovePod on PreFilter plugin %q: %w\", pl.Name(), err))\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":699,"to":722}} {"id":100011107,"name":"runPreFilterExtensionRemovePod","signature":"func (f *frameworkImpl) runPreFilterExtensionRemovePod(ctx context.Context, pl framework.PreFilterPlugin, state *framework.CycleState, podToSchedule *v1.Pod, podInfoToRemove *framework.PodInfo, nodeInfo *framework.NodeInfo) *framework.Status","file":"pkg/scheduler/framework/runtime/framework.go","code":"func (f *frameworkImpl) runPreFilterExtensionRemovePod(ctx context.Context, pl framework.PreFilterPlugin, state *framework.CycleState, podToSchedule *v1.Pod, podInfoToRemove *framework.PodInfo, nodeInfo *framework.NodeInfo) *framework.Status {\n\tif !state.ShouldRecordPluginMetrics() {\n\t\treturn pl.PreFilterExtensions().RemovePod(ctx, state, podToSchedule, podInfoToRemove, nodeInfo)\n\t}\n\tstartTime := time.Now()\n\tstatus := pl.PreFilterExtensions().RemovePod(ctx, state, podToSchedule, podInfoToRemove, nodeInfo)\n\tf.metricsRecorder.ObservePluginDurationAsync(metrics.PreFilterExtensionRemovePod, pl.Name(), status.Code().String(), metrics.SinceInSeconds(startTime))\n\treturn status\n}","line":{"from":724,"to":732}} {"id":100011108,"name":"RunFilterPlugins","signature":"func (f *frameworkImpl) RunFilterPlugins(","file":"pkg/scheduler/framework/runtime/framework.go","code":"// RunFilterPlugins runs the set of configured Filter plugins for pod on\n// the given node. If any of these plugins doesn't return \"Success\", the\n// given node is not suitable for running pod.\n// Meanwhile, the failure message and status are set for the given node.\nfunc (f *frameworkImpl) RunFilterPlugins(\n\tctx context.Context,\n\tstate *framework.CycleState,\n\tpod *v1.Pod,\n\tnodeInfo *framework.NodeInfo,\n) *framework.Status {\n\tfor _, pl := range f.filterPlugins {\n\t\tif state.SkipFilterPlugins.Has(pl.Name()) {\n\t\t\tcontinue\n\t\t}\n\t\tif status := f.runFilterPlugin(ctx, pl, state, pod, nodeInfo); !status.IsSuccess() {\n\t\t\tif !status.IsUnschedulable() {\n\t\t\t\t// Filter plugins are not supposed to return any status other than\n\t\t\t\t// Success or Unschedulable.\n\t\t\t\tstatus = framework.AsStatus(fmt.Errorf(\"running %q filter plugin: %w\", pl.Name(), status.AsError()))\n\t\t\t}\n\t\t\tstatus.SetFailedPlugin(pl.Name())\n\t\t\treturn status\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":734,"to":760}} {"id":100011109,"name":"runFilterPlugin","signature":"func (f *frameworkImpl) runFilterPlugin(ctx context.Context, pl framework.FilterPlugin, state *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status","file":"pkg/scheduler/framework/runtime/framework.go","code":"func (f *frameworkImpl) runFilterPlugin(ctx context.Context, pl framework.FilterPlugin, state *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status {\n\tif !state.ShouldRecordPluginMetrics() {\n\t\treturn pl.Filter(ctx, state, pod, nodeInfo)\n\t}\n\tstartTime := time.Now()\n\tstatus := pl.Filter(ctx, state, pod, nodeInfo)\n\tf.metricsRecorder.ObservePluginDurationAsync(metrics.Filter, pl.Name(), status.Code().String(), metrics.SinceInSeconds(startTime))\n\treturn status\n}","line":{"from":762,"to":770}} {"id":100011110,"name":"RunPostFilterPlugins","signature":"func (f *frameworkImpl) RunPostFilterPlugins(ctx context.Context, state *framework.CycleState, pod *v1.Pod, filteredNodeStatusMap framework.NodeToStatusMap) (_ *framework.PostFilterResult, status *framework.Status)","file":"pkg/scheduler/framework/runtime/framework.go","code":"// RunPostFilterPlugins runs the set of configured PostFilter plugins until the first\n// Success, Error or UnschedulableAndUnresolvable is met; otherwise continues to execute all plugins.\nfunc (f *frameworkImpl) RunPostFilterPlugins(ctx context.Context, state *framework.CycleState, pod *v1.Pod, filteredNodeStatusMap framework.NodeToStatusMap) (_ *framework.PostFilterResult, status *framework.Status) {\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tmetrics.FrameworkExtensionPointDuration.WithLabelValues(metrics.PostFilter, status.Code().String(), f.profileName).Observe(metrics.SinceInSeconds(startTime))\n\t}()\n\n\t// `result` records the last meaningful(non-noop) PostFilterResult.\n\tvar result *framework.PostFilterResult\n\tvar reasons []string\n\tvar failedPlugin string\n\tfor _, pl := range f.postFilterPlugins {\n\t\tr, s := f.runPostFilterPlugin(ctx, pl, state, pod, filteredNodeStatusMap)\n\t\tif s.IsSuccess() {\n\t\t\treturn r, s\n\t\t} else if s.Code() == framework.UnschedulableAndUnresolvable {\n\t\t\treturn r, s.WithFailedPlugin(pl.Name())\n\t\t} else if !s.IsUnschedulable() {\n\t\t\t// Any status other than Success, Unschedulable or UnschedulableAndUnresolvable is Error.\n\t\t\treturn nil, framework.AsStatus(s.AsError()).WithFailedPlugin(pl.Name())\n\t\t} else if r != nil \u0026\u0026 r.Mode() != framework.ModeNoop {\n\t\t\tresult = r\n\t\t}\n\n\t\treasons = append(reasons, s.Reasons()...)\n\t\t// Record the first failed plugin unless we proved that\n\t\t// the latter is more relevant.\n\t\tif len(failedPlugin) == 0 {\n\t\t\tfailedPlugin = pl.Name()\n\t\t}\n\t}\n\n\treturn result, framework.NewStatus(framework.Unschedulable, reasons...).WithFailedPlugin(failedPlugin)\n}","line":{"from":772,"to":806}} {"id":100011111,"name":"runPostFilterPlugin","signature":"func (f *frameworkImpl) runPostFilterPlugin(ctx context.Context, pl framework.PostFilterPlugin, state *framework.CycleState, pod *v1.Pod, filteredNodeStatusMap framework.NodeToStatusMap) (*framework.PostFilterResult, *framework.Status)","file":"pkg/scheduler/framework/runtime/framework.go","code":"func (f *frameworkImpl) runPostFilterPlugin(ctx context.Context, pl framework.PostFilterPlugin, state *framework.CycleState, pod *v1.Pod, filteredNodeStatusMap framework.NodeToStatusMap) (*framework.PostFilterResult, *framework.Status) {\n\tif !state.ShouldRecordPluginMetrics() {\n\t\treturn pl.PostFilter(ctx, state, pod, filteredNodeStatusMap)\n\t}\n\tstartTime := time.Now()\n\tr, s := pl.PostFilter(ctx, state, pod, filteredNodeStatusMap)\n\tf.metricsRecorder.ObservePluginDurationAsync(metrics.PostFilter, pl.Name(), s.Code().String(), metrics.SinceInSeconds(startTime))\n\treturn r, s\n}","line":{"from":808,"to":816}} {"id":100011112,"name":"RunFilterPluginsWithNominatedPods","signature":"func (f *frameworkImpl) RunFilterPluginsWithNominatedPods(ctx context.Context, state *framework.CycleState, pod *v1.Pod, info *framework.NodeInfo) *framework.Status","file":"pkg/scheduler/framework/runtime/framework.go","code":"// RunFilterPluginsWithNominatedPods runs the set of configured filter plugins\n// for nominated pod on the given node.\n// This function is called from two different places: Schedule and Preempt.\n// When it is called from Schedule, we want to test whether the pod is\n// schedulable on the node with all the existing pods on the node plus higher\n// and equal priority pods nominated to run on the node.\n// When it is called from Preempt, we should remove the victims of preemption\n// and add the nominated pods. Removal of the victims is done by\n// SelectVictimsOnNode(). Preempt removes victims from PreFilter state and\n// NodeInfo before calling this function.\nfunc (f *frameworkImpl) RunFilterPluginsWithNominatedPods(ctx context.Context, state *framework.CycleState, pod *v1.Pod, info *framework.NodeInfo) *framework.Status {\n\tvar status *framework.Status\n\n\tpodsAdded := false\n\t// We run filters twice in some cases. If the node has greater or equal priority\n\t// nominated pods, we run them when those pods are added to PreFilter state and nodeInfo.\n\t// If all filters succeed in this pass, we run them again when these\n\t// nominated pods are not added. This second pass is necessary because some\n\t// filters such as inter-pod affinity may not pass without the nominated pods.\n\t// If there are no nominated pods for the node or if the first run of the\n\t// filters fail, we don't run the second pass.\n\t// We consider only equal or higher priority pods in the first pass, because\n\t// those are the current \"pod\" must yield to them and not take a space opened\n\t// for running them. It is ok if the current \"pod\" take resources freed for\n\t// lower priority pods.\n\t// Requiring that the new pod is schedulable in both circumstances ensures that\n\t// we are making a conservative decision: filters like resources and inter-pod\n\t// anti-affinity are more likely to fail when the nominated pods are treated\n\t// as running, while filters like pod affinity are more likely to fail when\n\t// the nominated pods are treated as not running. We can't just assume the\n\t// nominated pods are running because they are not running right now and in fact,\n\t// they may end up getting scheduled to a different node.\n\tfor i := 0; i \u003c 2; i++ {\n\t\tstateToUse := state\n\t\tnodeInfoToUse := info\n\t\tif i == 0 {\n\t\t\tvar err error\n\t\t\tpodsAdded, stateToUse, nodeInfoToUse, err = addNominatedPods(ctx, f, pod, state, info)\n\t\t\tif err != nil {\n\t\t\t\treturn framework.AsStatus(err)\n\t\t\t}\n\t\t} else if !podsAdded || !status.IsSuccess() {\n\t\t\tbreak\n\t\t}\n\n\t\tstatus = f.RunFilterPlugins(ctx, stateToUse, pod, nodeInfoToUse)\n\t\tif !status.IsSuccess() \u0026\u0026 !status.IsUnschedulable() {\n\t\t\treturn status\n\t\t}\n\t}\n\n\treturn status\n}","line":{"from":818,"to":870}} {"id":100011113,"name":"addNominatedPods","signature":"func addNominatedPods(ctx context.Context, fh framework.Handle, pod *v1.Pod, state *framework.CycleState, nodeInfo *framework.NodeInfo) (bool, *framework.CycleState, *framework.NodeInfo, error)","file":"pkg/scheduler/framework/runtime/framework.go","code":"// addNominatedPods adds pods with equal or greater priority which are nominated\n// to run on the node. It returns 1) whether any pod was added, 2) augmented cycleState,\n// 3) augmented nodeInfo.\nfunc addNominatedPods(ctx context.Context, fh framework.Handle, pod *v1.Pod, state *framework.CycleState, nodeInfo *framework.NodeInfo) (bool, *framework.CycleState, *framework.NodeInfo, error) {\n\tif fh == nil || nodeInfo.Node() == nil {\n\t\t// This may happen only in tests.\n\t\treturn false, state, nodeInfo, nil\n\t}\n\tnominatedPodInfos := fh.NominatedPodsForNode(nodeInfo.Node().Name)\n\tif len(nominatedPodInfos) == 0 {\n\t\treturn false, state, nodeInfo, nil\n\t}\n\tnodeInfoOut := nodeInfo.Clone()\n\tstateOut := state.Clone()\n\tpodsAdded := false\n\tfor _, pi := range nominatedPodInfos {\n\t\tif corev1.PodPriority(pi.Pod) \u003e= corev1.PodPriority(pod) \u0026\u0026 pi.Pod.UID != pod.UID {\n\t\t\tnodeInfoOut.AddPodInfo(pi)\n\t\t\tstatus := fh.RunPreFilterExtensionAddPod(ctx, stateOut, pod, pi, nodeInfoOut)\n\t\t\tif !status.IsSuccess() {\n\t\t\t\treturn false, state, nodeInfo, status.AsError()\n\t\t\t}\n\t\t\tpodsAdded = true\n\t\t}\n\t}\n\treturn podsAdded, stateOut, nodeInfoOut, nil\n}","line":{"from":872,"to":898}} {"id":100011114,"name":"RunPreScorePlugins","signature":"func (f *frameworkImpl) RunPreScorePlugins(","file":"pkg/scheduler/framework/runtime/framework.go","code":"// RunPreScorePlugins runs the set of configured pre-score plugins. If any\n// of these plugins returns any status other than Success/Skip, the given pod is rejected.\n// When it returns Skip status, other fields in status are just ignored,\n// and coupled Score plugin will be skipped in this scheduling cycle.\nfunc (f *frameworkImpl) RunPreScorePlugins(\n\tctx context.Context,\n\tstate *framework.CycleState,\n\tpod *v1.Pod,\n\tnodes []*v1.Node,\n) (status *framework.Status) {\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tmetrics.FrameworkExtensionPointDuration.WithLabelValues(metrics.PreScore, status.Code().String(), f.profileName).Observe(metrics.SinceInSeconds(startTime))\n\t}()\n\tskipPlugins := sets.New[string]()\n\tfor _, pl := range f.preScorePlugins {\n\t\tstatus = f.runPreScorePlugin(ctx, pl, state, pod, nodes)\n\t\tif status.IsSkip() {\n\t\t\tskipPlugins.Insert(pl.Name())\n\t\t\tcontinue\n\t\t}\n\t\tif !status.IsSuccess() {\n\t\t\treturn framework.AsStatus(fmt.Errorf(\"running PreScore plugin %q: %w\", pl.Name(), status.AsError()))\n\t\t}\n\t}\n\tstate.SkipScorePlugins = skipPlugins\n\treturn nil\n}","line":{"from":900,"to":927}} {"id":100011115,"name":"runPreScorePlugin","signature":"func (f *frameworkImpl) runPreScorePlugin(ctx context.Context, pl framework.PreScorePlugin, state *framework.CycleState, pod *v1.Pod, nodes []*v1.Node) *framework.Status","file":"pkg/scheduler/framework/runtime/framework.go","code":"func (f *frameworkImpl) runPreScorePlugin(ctx context.Context, pl framework.PreScorePlugin, state *framework.CycleState, pod *v1.Pod, nodes []*v1.Node) *framework.Status {\n\tif !state.ShouldRecordPluginMetrics() {\n\t\treturn pl.PreScore(ctx, state, pod, nodes)\n\t}\n\tstartTime := time.Now()\n\tstatus := pl.PreScore(ctx, state, pod, nodes)\n\tf.metricsRecorder.ObservePluginDurationAsync(metrics.PreScore, pl.Name(), status.Code().String(), metrics.SinceInSeconds(startTime))\n\treturn status\n}","line":{"from":929,"to":937}} {"id":100011116,"name":"RunScorePlugins","signature":"func (f *frameworkImpl) RunScorePlugins(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodes []*v1.Node) (ns []framework.NodePluginScores, status *framework.Status)","file":"pkg/scheduler/framework/runtime/framework.go","code":"// RunScorePlugins runs the set of configured scoring plugins.\n// It returns a list that stores scores from each plugin and total score for each Node.\n// It also returns *Status, which is set to non-success if any of the plugins returns\n// a non-success status.\nfunc (f *frameworkImpl) RunScorePlugins(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodes []*v1.Node) (ns []framework.NodePluginScores, status *framework.Status) {\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tmetrics.FrameworkExtensionPointDuration.WithLabelValues(metrics.Score, status.Code().String(), f.profileName).Observe(metrics.SinceInSeconds(startTime))\n\t}()\n\tallNodePluginScores := make([]framework.NodePluginScores, len(nodes))\n\tnumPlugins := len(f.scorePlugins) - state.SkipScorePlugins.Len()\n\tplugins := make([]framework.ScorePlugin, 0, numPlugins)\n\tpluginToNodeScores := make(map[string]framework.NodeScoreList, numPlugins)\n\tfor _, pl := range f.scorePlugins {\n\t\tif state.SkipScorePlugins.Has(pl.Name()) {\n\t\t\tcontinue\n\t\t}\n\t\tplugins = append(plugins, pl)\n\t\tpluginToNodeScores[pl.Name()] = make(framework.NodeScoreList, len(nodes))\n\t}\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\terrCh := parallelize.NewErrorChannel()\n\n\tif len(plugins) \u003e 0 {\n\t\t// Run Score method for each node in parallel.\n\t\tf.Parallelizer().Until(ctx, len(nodes), func(index int) {\n\t\t\tnodeName := nodes[index].Name\n\t\t\tfor _, pl := range plugins {\n\t\t\t\ts, status := f.runScorePlugin(ctx, pl, state, pod, nodeName)\n\t\t\t\tif !status.IsSuccess() {\n\t\t\t\t\terr := fmt.Errorf(\"plugin %q failed with: %w\", pl.Name(), status.AsError())\n\t\t\t\t\terrCh.SendErrorWithCancel(err, cancel)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tpluginToNodeScores[pl.Name()][index] = framework.NodeScore{\n\t\t\t\t\tName: nodeName,\n\t\t\t\t\tScore: s,\n\t\t\t\t}\n\t\t\t}\n\t\t}, metrics.Score)\n\t\tif err := errCh.ReceiveError(); err != nil {\n\t\t\treturn nil, framework.AsStatus(fmt.Errorf(\"running Score plugins: %w\", err))\n\t\t}\n\t}\n\n\t// Run NormalizeScore method for each ScorePlugin in parallel.\n\tf.Parallelizer().Until(ctx, len(plugins), func(index int) {\n\t\tpl := plugins[index]\n\t\tif pl.ScoreExtensions() == nil {\n\t\t\treturn\n\t\t}\n\t\tnodeScoreList := pluginToNodeScores[pl.Name()]\n\t\tstatus := f.runScoreExtension(ctx, pl, state, pod, nodeScoreList)\n\t\tif !status.IsSuccess() {\n\t\t\terr := fmt.Errorf(\"plugin %q failed with: %w\", pl.Name(), status.AsError())\n\t\t\terrCh.SendErrorWithCancel(err, cancel)\n\t\t\treturn\n\t\t}\n\t}, metrics.Score)\n\tif err := errCh.ReceiveError(); err != nil {\n\t\treturn nil, framework.AsStatus(fmt.Errorf(\"running Normalize on Score plugins: %w\", err))\n\t}\n\n\t// Apply score weight for each ScorePlugin in parallel,\n\t// and then, build allNodePluginScores.\n\tf.Parallelizer().Until(ctx, len(nodes), func(index int) {\n\t\tnodePluginScores := framework.NodePluginScores{\n\t\t\tName: nodes[index].Name,\n\t\t\tScores: make([]framework.PluginScore, len(plugins)),\n\t\t}\n\n\t\tfor i, pl := range plugins {\n\t\t\tweight := f.scorePluginWeight[pl.Name()]\n\t\t\tnodeScoreList := pluginToNodeScores[pl.Name()]\n\t\t\tscore := nodeScoreList[index].Score\n\n\t\t\tif score \u003e framework.MaxNodeScore || score \u003c framework.MinNodeScore {\n\t\t\t\terr := fmt.Errorf(\"plugin %q returns an invalid score %v, it should in the range of [%v, %v] after normalizing\", pl.Name(), score, framework.MinNodeScore, framework.MaxNodeScore)\n\t\t\t\terrCh.SendErrorWithCancel(err, cancel)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tweightedScore := score * int64(weight)\n\t\t\tnodePluginScores.Scores[i] = framework.PluginScore{\n\t\t\t\tName: pl.Name(),\n\t\t\t\tScore: weightedScore,\n\t\t\t}\n\t\t\tnodePluginScores.TotalScore += weightedScore\n\t\t}\n\t\tallNodePluginScores[index] = nodePluginScores\n\t}, metrics.Score)\n\tif err := errCh.ReceiveError(); err != nil {\n\t\treturn nil, framework.AsStatus(fmt.Errorf(\"applying score defaultWeights on Score plugins: %w\", err))\n\t}\n\n\treturn allNodePluginScores, nil\n}","line":{"from":939,"to":1035}} {"id":100011117,"name":"runScorePlugin","signature":"func (f *frameworkImpl) runScorePlugin(ctx context.Context, pl framework.ScorePlugin, state *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status)","file":"pkg/scheduler/framework/runtime/framework.go","code":"func (f *frameworkImpl) runScorePlugin(ctx context.Context, pl framework.ScorePlugin, state *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status) {\n\tif !state.ShouldRecordPluginMetrics() {\n\t\treturn pl.Score(ctx, state, pod, nodeName)\n\t}\n\tstartTime := time.Now()\n\ts, status := pl.Score(ctx, state, pod, nodeName)\n\tf.metricsRecorder.ObservePluginDurationAsync(metrics.Score, pl.Name(), status.Code().String(), metrics.SinceInSeconds(startTime))\n\treturn s, status\n}","line":{"from":1037,"to":1045}} {"id":100011118,"name":"runScoreExtension","signature":"func (f *frameworkImpl) runScoreExtension(ctx context.Context, pl framework.ScorePlugin, state *framework.CycleState, pod *v1.Pod, nodeScoreList framework.NodeScoreList) *framework.Status","file":"pkg/scheduler/framework/runtime/framework.go","code":"func (f *frameworkImpl) runScoreExtension(ctx context.Context, pl framework.ScorePlugin, state *framework.CycleState, pod *v1.Pod, nodeScoreList framework.NodeScoreList) *framework.Status {\n\tif !state.ShouldRecordPluginMetrics() {\n\t\treturn pl.ScoreExtensions().NormalizeScore(ctx, state, pod, nodeScoreList)\n\t}\n\tstartTime := time.Now()\n\tstatus := pl.ScoreExtensions().NormalizeScore(ctx, state, pod, nodeScoreList)\n\tf.metricsRecorder.ObservePluginDurationAsync(metrics.ScoreExtensionNormalize, pl.Name(), status.Code().String(), metrics.SinceInSeconds(startTime))\n\treturn status\n}","line":{"from":1047,"to":1055}} {"id":100011119,"name":"RunPreBindPlugins","signature":"func (f *frameworkImpl) RunPreBindPlugins(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (status *framework.Status)","file":"pkg/scheduler/framework/runtime/framework.go","code":"// RunPreBindPlugins runs the set of configured prebind plugins. It returns a\n// failure (bool) if any of the plugins returns an error. It also returns an\n// error containing the rejection message or the error occurred in the plugin.\nfunc (f *frameworkImpl) RunPreBindPlugins(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (status *framework.Status) {\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tmetrics.FrameworkExtensionPointDuration.WithLabelValues(metrics.PreBind, status.Code().String(), f.profileName).Observe(metrics.SinceInSeconds(startTime))\n\t}()\n\tfor _, pl := range f.preBindPlugins {\n\t\tstatus = f.runPreBindPlugin(ctx, pl, state, pod, nodeName)\n\t\tif !status.IsSuccess() {\n\t\t\tif status.IsUnschedulable() {\n\t\t\t\tklog.V(4).InfoS(\"Pod rejected by PreBind plugin\", \"pod\", klog.KObj(pod), \"node\", nodeName, \"plugin\", pl.Name(), \"status\", status.Message())\n\t\t\t\tstatus.SetFailedPlugin(pl.Name())\n\t\t\t\treturn status\n\t\t\t}\n\t\t\terr := status.AsError()\n\t\t\tklog.ErrorS(err, \"Failed running PreBind plugin\", \"plugin\", pl.Name(), \"pod\", klog.KObj(pod), \"node\", nodeName)\n\t\t\treturn framework.AsStatus(fmt.Errorf(\"running PreBind plugin %q: %w\", pl.Name(), err))\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":1057,"to":1079}} {"id":100011120,"name":"runPreBindPlugin","signature":"func (f *frameworkImpl) runPreBindPlugin(ctx context.Context, pl framework.PreBindPlugin, state *framework.CycleState, pod *v1.Pod, nodeName string) *framework.Status","file":"pkg/scheduler/framework/runtime/framework.go","code":"func (f *frameworkImpl) runPreBindPlugin(ctx context.Context, pl framework.PreBindPlugin, state *framework.CycleState, pod *v1.Pod, nodeName string) *framework.Status {\n\tif !state.ShouldRecordPluginMetrics() {\n\t\treturn pl.PreBind(ctx, state, pod, nodeName)\n\t}\n\tstartTime := time.Now()\n\tstatus := pl.PreBind(ctx, state, pod, nodeName)\n\tf.metricsRecorder.ObservePluginDurationAsync(metrics.PreBind, pl.Name(), status.Code().String(), metrics.SinceInSeconds(startTime))\n\treturn status\n}","line":{"from":1081,"to":1089}} {"id":100011121,"name":"RunBindPlugins","signature":"func (f *frameworkImpl) RunBindPlugins(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (status *framework.Status)","file":"pkg/scheduler/framework/runtime/framework.go","code":"// RunBindPlugins runs the set of configured bind plugins until one returns a non `Skip` status.\nfunc (f *frameworkImpl) RunBindPlugins(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (status *framework.Status) {\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tmetrics.FrameworkExtensionPointDuration.WithLabelValues(metrics.Bind, status.Code().String(), f.profileName).Observe(metrics.SinceInSeconds(startTime))\n\t}()\n\tif len(f.bindPlugins) == 0 {\n\t\treturn framework.NewStatus(framework.Skip, \"\")\n\t}\n\tfor _, pl := range f.bindPlugins {\n\t\tstatus = f.runBindPlugin(ctx, pl, state, pod, nodeName)\n\t\tif status.IsSkip() {\n\t\t\tcontinue\n\t\t}\n\t\tif !status.IsSuccess() {\n\t\t\tif status.IsUnschedulable() {\n\t\t\t\tklog.V(4).InfoS(\"Pod rejected by Bind plugin\", \"pod\", klog.KObj(pod), \"node\", nodeName, \"plugin\", pl.Name(), \"status\", status.Message())\n\t\t\t\tstatus.SetFailedPlugin(pl.Name())\n\t\t\t\treturn status\n\t\t\t}\n\t\t\terr := status.AsError()\n\t\t\tklog.ErrorS(err, \"Failed running Bind plugin\", \"plugin\", pl.Name(), \"pod\", klog.KObj(pod), \"node\", nodeName)\n\t\t\treturn framework.AsStatus(fmt.Errorf(\"running Bind plugin %q: %w\", pl.Name(), err))\n\t\t}\n\t\treturn status\n\t}\n\treturn status\n}","line":{"from":1091,"to":1118}} {"id":100011122,"name":"runBindPlugin","signature":"func (f *frameworkImpl) runBindPlugin(ctx context.Context, bp framework.BindPlugin, state *framework.CycleState, pod *v1.Pod, nodeName string) *framework.Status","file":"pkg/scheduler/framework/runtime/framework.go","code":"func (f *frameworkImpl) runBindPlugin(ctx context.Context, bp framework.BindPlugin, state *framework.CycleState, pod *v1.Pod, nodeName string) *framework.Status {\n\tif !state.ShouldRecordPluginMetrics() {\n\t\treturn bp.Bind(ctx, state, pod, nodeName)\n\t}\n\tstartTime := time.Now()\n\tstatus := bp.Bind(ctx, state, pod, nodeName)\n\tf.metricsRecorder.ObservePluginDurationAsync(metrics.Bind, bp.Name(), status.Code().String(), metrics.SinceInSeconds(startTime))\n\treturn status\n}","line":{"from":1120,"to":1128}} {"id":100011123,"name":"RunPostBindPlugins","signature":"func (f *frameworkImpl) RunPostBindPlugins(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string)","file":"pkg/scheduler/framework/runtime/framework.go","code":"// RunPostBindPlugins runs the set of configured postbind plugins.\nfunc (f *frameworkImpl) RunPostBindPlugins(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) {\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tmetrics.FrameworkExtensionPointDuration.WithLabelValues(metrics.PostBind, framework.Success.String(), f.profileName).Observe(metrics.SinceInSeconds(startTime))\n\t}()\n\tfor _, pl := range f.postBindPlugins {\n\t\tf.runPostBindPlugin(ctx, pl, state, pod, nodeName)\n\t}\n}","line":{"from":1130,"to":1139}} {"id":100011124,"name":"runPostBindPlugin","signature":"func (f *frameworkImpl) runPostBindPlugin(ctx context.Context, pl framework.PostBindPlugin, state *framework.CycleState, pod *v1.Pod, nodeName string)","file":"pkg/scheduler/framework/runtime/framework.go","code":"func (f *frameworkImpl) runPostBindPlugin(ctx context.Context, pl framework.PostBindPlugin, state *framework.CycleState, pod *v1.Pod, nodeName string) {\n\tif !state.ShouldRecordPluginMetrics() {\n\t\tpl.PostBind(ctx, state, pod, nodeName)\n\t\treturn\n\t}\n\tstartTime := time.Now()\n\tpl.PostBind(ctx, state, pod, nodeName)\n\tf.metricsRecorder.ObservePluginDurationAsync(metrics.PostBind, pl.Name(), framework.Success.String(), metrics.SinceInSeconds(startTime))\n}","line":{"from":1141,"to":1149}} {"id":100011125,"name":"RunReservePluginsReserve","signature":"func (f *frameworkImpl) RunReservePluginsReserve(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (status *framework.Status)","file":"pkg/scheduler/framework/runtime/framework.go","code":"// RunReservePluginsReserve runs the Reserve method in the set of configured\n// reserve plugins. If any of these plugins returns an error, it does not\n// continue running the remaining ones and returns the error. In such a case,\n// the pod will not be scheduled and the caller will be expected to call\n// RunReservePluginsUnreserve.\nfunc (f *frameworkImpl) RunReservePluginsReserve(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (status *framework.Status) {\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tmetrics.FrameworkExtensionPointDuration.WithLabelValues(metrics.Reserve, status.Code().String(), f.profileName).Observe(metrics.SinceInSeconds(startTime))\n\t}()\n\tfor _, pl := range f.reservePlugins {\n\t\tstatus = f.runReservePluginReserve(ctx, pl, state, pod, nodeName)\n\t\tif !status.IsSuccess() {\n\t\t\terr := status.AsError()\n\t\t\tklog.ErrorS(err, \"Failed running Reserve plugin\", \"plugin\", pl.Name(), \"pod\", klog.KObj(pod))\n\t\t\treturn framework.AsStatus(fmt.Errorf(\"running Reserve plugin %q: %w\", pl.Name(), err))\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":1151,"to":1170}} {"id":100011126,"name":"runReservePluginReserve","signature":"func (f *frameworkImpl) runReservePluginReserve(ctx context.Context, pl framework.ReservePlugin, state *framework.CycleState, pod *v1.Pod, nodeName string) *framework.Status","file":"pkg/scheduler/framework/runtime/framework.go","code":"func (f *frameworkImpl) runReservePluginReserve(ctx context.Context, pl framework.ReservePlugin, state *framework.CycleState, pod *v1.Pod, nodeName string) *framework.Status {\n\tif !state.ShouldRecordPluginMetrics() {\n\t\treturn pl.Reserve(ctx, state, pod, nodeName)\n\t}\n\tstartTime := time.Now()\n\tstatus := pl.Reserve(ctx, state, pod, nodeName)\n\tf.metricsRecorder.ObservePluginDurationAsync(metrics.Reserve, pl.Name(), status.Code().String(), metrics.SinceInSeconds(startTime))\n\treturn status\n}","line":{"from":1172,"to":1180}} {"id":100011127,"name":"RunReservePluginsUnreserve","signature":"func (f *frameworkImpl) RunReservePluginsUnreserve(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string)","file":"pkg/scheduler/framework/runtime/framework.go","code":"// RunReservePluginsUnreserve runs the Unreserve method in the set of\n// configured reserve plugins.\nfunc (f *frameworkImpl) RunReservePluginsUnreserve(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) {\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tmetrics.FrameworkExtensionPointDuration.WithLabelValues(metrics.Unreserve, framework.Success.String(), f.profileName).Observe(metrics.SinceInSeconds(startTime))\n\t}()\n\t// Execute the Unreserve operation of each reserve plugin in the\n\t// *reverse* order in which the Reserve operation was executed.\n\tfor i := len(f.reservePlugins) - 1; i \u003e= 0; i-- {\n\t\tf.runReservePluginUnreserve(ctx, f.reservePlugins[i], state, pod, nodeName)\n\t}\n}","line":{"from":1182,"to":1194}} {"id":100011128,"name":"runReservePluginUnreserve","signature":"func (f *frameworkImpl) runReservePluginUnreserve(ctx context.Context, pl framework.ReservePlugin, state *framework.CycleState, pod *v1.Pod, nodeName string)","file":"pkg/scheduler/framework/runtime/framework.go","code":"func (f *frameworkImpl) runReservePluginUnreserve(ctx context.Context, pl framework.ReservePlugin, state *framework.CycleState, pod *v1.Pod, nodeName string) {\n\tif !state.ShouldRecordPluginMetrics() {\n\t\tpl.Unreserve(ctx, state, pod, nodeName)\n\t\treturn\n\t}\n\tstartTime := time.Now()\n\tpl.Unreserve(ctx, state, pod, nodeName)\n\tf.metricsRecorder.ObservePluginDurationAsync(metrics.Unreserve, pl.Name(), framework.Success.String(), metrics.SinceInSeconds(startTime))\n}","line":{"from":1196,"to":1204}} {"id":100011129,"name":"RunPermitPlugins","signature":"func (f *frameworkImpl) RunPermitPlugins(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (status *framework.Status)","file":"pkg/scheduler/framework/runtime/framework.go","code":"// RunPermitPlugins runs the set of configured permit plugins. If any of these\n// plugins returns a status other than \"Success\" or \"Wait\", it does not continue\n// running the remaining plugins and returns an error. Otherwise, if any of the\n// plugins returns \"Wait\", then this function will create and add waiting pod\n// to a map of currently waiting pods and return status with \"Wait\" code.\n// Pod will remain waiting pod for the minimum duration returned by the permit plugins.\nfunc (f *frameworkImpl) RunPermitPlugins(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (status *framework.Status) {\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tmetrics.FrameworkExtensionPointDuration.WithLabelValues(metrics.Permit, status.Code().String(), f.profileName).Observe(metrics.SinceInSeconds(startTime))\n\t}()\n\tpluginsWaitTime := make(map[string]time.Duration)\n\tstatusCode := framework.Success\n\tfor _, pl := range f.permitPlugins {\n\t\tstatus, timeout := f.runPermitPlugin(ctx, pl, state, pod, nodeName)\n\t\tif !status.IsSuccess() {\n\t\t\tif status.IsUnschedulable() {\n\t\t\t\tklog.V(4).InfoS(\"Pod rejected by permit plugin\", \"pod\", klog.KObj(pod), \"plugin\", pl.Name(), \"status\", status.Message())\n\t\t\t\tstatus.SetFailedPlugin(pl.Name())\n\t\t\t\treturn status\n\t\t\t}\n\t\t\tif status.IsWait() {\n\t\t\t\t// Not allowed to be greater than maxTimeout.\n\t\t\t\tif timeout \u003e maxTimeout {\n\t\t\t\t\ttimeout = maxTimeout\n\t\t\t\t}\n\t\t\t\tpluginsWaitTime[pl.Name()] = timeout\n\t\t\t\tstatusCode = framework.Wait\n\t\t\t} else {\n\t\t\t\terr := status.AsError()\n\t\t\t\tklog.ErrorS(err, \"Failed running Permit plugin\", \"plugin\", pl.Name(), \"pod\", klog.KObj(pod))\n\t\t\t\treturn framework.AsStatus(fmt.Errorf(\"running Permit plugin %q: %w\", pl.Name(), err)).WithFailedPlugin(pl.Name())\n\t\t\t}\n\t\t}\n\t}\n\tif statusCode == framework.Wait {\n\t\twaitingPod := newWaitingPod(pod, pluginsWaitTime)\n\t\tf.waitingPods.add(waitingPod)\n\t\tmsg := fmt.Sprintf(\"one or more plugins asked to wait and no plugin rejected pod %q\", pod.Name)\n\t\tklog.V(4).InfoS(\"One or more plugins asked to wait and no plugin rejected pod\", \"pod\", klog.KObj(pod))\n\t\treturn framework.NewStatus(framework.Wait, msg)\n\t}\n\treturn nil\n}","line":{"from":1206,"to":1249}} {"id":100011130,"name":"runPermitPlugin","signature":"func (f *frameworkImpl) runPermitPlugin(ctx context.Context, pl framework.PermitPlugin, state *framework.CycleState, pod *v1.Pod, nodeName string) (*framework.Status, time.Duration)","file":"pkg/scheduler/framework/runtime/framework.go","code":"func (f *frameworkImpl) runPermitPlugin(ctx context.Context, pl framework.PermitPlugin, state *framework.CycleState, pod *v1.Pod, nodeName string) (*framework.Status, time.Duration) {\n\tif !state.ShouldRecordPluginMetrics() {\n\t\treturn pl.Permit(ctx, state, pod, nodeName)\n\t}\n\tstartTime := time.Now()\n\tstatus, timeout := pl.Permit(ctx, state, pod, nodeName)\n\tf.metricsRecorder.ObservePluginDurationAsync(metrics.Permit, pl.Name(), status.Code().String(), metrics.SinceInSeconds(startTime))\n\treturn status, timeout\n}","line":{"from":1251,"to":1259}} {"id":100011131,"name":"WaitOnPermit","signature":"func (f *frameworkImpl) WaitOnPermit(ctx context.Context, pod *v1.Pod) *framework.Status","file":"pkg/scheduler/framework/runtime/framework.go","code":"// WaitOnPermit will block, if the pod is a waiting pod, until the waiting pod is rejected or allowed.\nfunc (f *frameworkImpl) WaitOnPermit(ctx context.Context, pod *v1.Pod) *framework.Status {\n\twaitingPod := f.waitingPods.get(pod.UID)\n\tif waitingPod == nil {\n\t\treturn nil\n\t}\n\tdefer f.waitingPods.remove(pod.UID)\n\tklog.V(4).InfoS(\"Pod waiting on permit\", \"pod\", klog.KObj(pod))\n\n\tstartTime := time.Now()\n\ts := \u003c-waitingPod.s\n\tmetrics.PermitWaitDuration.WithLabelValues(s.Code().String()).Observe(metrics.SinceInSeconds(startTime))\n\n\tif !s.IsSuccess() {\n\t\tif s.IsUnschedulable() {\n\t\t\tklog.V(4).InfoS(\"Pod rejected while waiting on permit\", \"pod\", klog.KObj(pod), \"status\", s.Message())\n\t\t\treturn s\n\t\t}\n\t\terr := s.AsError()\n\t\tklog.ErrorS(err, \"Failed waiting on permit for pod\", \"pod\", klog.KObj(pod))\n\t\treturn framework.AsStatus(fmt.Errorf(\"waiting on permit for pod: %w\", err)).WithFailedPlugin(s.FailedPlugin())\n\t}\n\treturn nil\n}","line":{"from":1261,"to":1284}} {"id":100011132,"name":"SnapshotSharedLister","signature":"func (f *frameworkImpl) SnapshotSharedLister() framework.SharedLister","file":"pkg/scheduler/framework/runtime/framework.go","code":"// SnapshotSharedLister returns the scheduler's SharedLister of the latest NodeInfo\n// snapshot. The snapshot is taken at the beginning of a scheduling cycle and remains\n// unchanged until a pod finishes \"Reserve\". There is no guarantee that the information\n// remains unchanged after \"Reserve\".\nfunc (f *frameworkImpl) SnapshotSharedLister() framework.SharedLister {\n\treturn f.snapshotSharedLister\n}","line":{"from":1286,"to":1292}} {"id":100011133,"name":"IterateOverWaitingPods","signature":"func (f *frameworkImpl) IterateOverWaitingPods(callback func(framework.WaitingPod))","file":"pkg/scheduler/framework/runtime/framework.go","code":"// IterateOverWaitingPods acquires a read lock and iterates over the WaitingPods map.\nfunc (f *frameworkImpl) IterateOverWaitingPods(callback func(framework.WaitingPod)) {\n\tf.waitingPods.iterate(callback)\n}","line":{"from":1294,"to":1297}} {"id":100011134,"name":"GetWaitingPod","signature":"func (f *frameworkImpl) GetWaitingPod(uid types.UID) framework.WaitingPod","file":"pkg/scheduler/framework/runtime/framework.go","code":"// GetWaitingPod returns a reference to a WaitingPod given its UID.\nfunc (f *frameworkImpl) GetWaitingPod(uid types.UID) framework.WaitingPod {\n\tif wp := f.waitingPods.get(uid); wp != nil {\n\t\treturn wp\n\t}\n\treturn nil // Returning nil instead of *waitingPod(nil).\n}","line":{"from":1299,"to":1305}} {"id":100011135,"name":"RejectWaitingPod","signature":"func (f *frameworkImpl) RejectWaitingPod(uid types.UID) bool","file":"pkg/scheduler/framework/runtime/framework.go","code":"// RejectWaitingPod rejects a WaitingPod given its UID.\n// The returned value indicates if the given pod is waiting or not.\nfunc (f *frameworkImpl) RejectWaitingPod(uid types.UID) bool {\n\tif waitingPod := f.waitingPods.get(uid); waitingPod != nil {\n\t\twaitingPod.Reject(\"\", \"removed\")\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":1307,"to":1315}} {"id":100011136,"name":"HasFilterPlugins","signature":"func (f *frameworkImpl) HasFilterPlugins() bool","file":"pkg/scheduler/framework/runtime/framework.go","code":"// HasFilterPlugins returns true if at least one filter plugin is defined.\nfunc (f *frameworkImpl) HasFilterPlugins() bool {\n\treturn len(f.filterPlugins) \u003e 0\n}","line":{"from":1317,"to":1320}} {"id":100011137,"name":"HasPostFilterPlugins","signature":"func (f *frameworkImpl) HasPostFilterPlugins() bool","file":"pkg/scheduler/framework/runtime/framework.go","code":"// HasPostFilterPlugins returns true if at least one postFilter plugin is defined.\nfunc (f *frameworkImpl) HasPostFilterPlugins() bool {\n\treturn len(f.postFilterPlugins) \u003e 0\n}","line":{"from":1322,"to":1325}} {"id":100011138,"name":"HasScorePlugins","signature":"func (f *frameworkImpl) HasScorePlugins() bool","file":"pkg/scheduler/framework/runtime/framework.go","code":"// HasScorePlugins returns true if at least one score plugin is defined.\nfunc (f *frameworkImpl) HasScorePlugins() bool {\n\treturn len(f.scorePlugins) \u003e 0\n}","line":{"from":1327,"to":1330}} {"id":100011139,"name":"ListPlugins","signature":"func (f *frameworkImpl) ListPlugins() *config.Plugins","file":"pkg/scheduler/framework/runtime/framework.go","code":"// ListPlugins returns a map of extension point name to plugin names configured at each extension\n// point. Returns nil if no plugins where configured.\nfunc (f *frameworkImpl) ListPlugins() *config.Plugins {\n\tm := config.Plugins{}\n\n\tfor _, e := range f.getExtensionPoints(\u0026m) {\n\t\tplugins := reflect.ValueOf(e.slicePtr).Elem()\n\t\textName := plugins.Type().Elem().Name()\n\t\tvar cfgs []config.Plugin\n\t\tfor i := 0; i \u003c plugins.Len(); i++ {\n\t\t\tname := plugins.Index(i).Interface().(framework.Plugin).Name()\n\t\t\tp := config.Plugin{Name: name}\n\t\t\tif extName == \"ScorePlugin\" {\n\t\t\t\t// Weights apply only to score plugins.\n\t\t\t\tp.Weight = int32(f.scorePluginWeight[name])\n\t\t\t}\n\t\t\tcfgs = append(cfgs, p)\n\t\t}\n\t\tif len(cfgs) \u003e 0 {\n\t\t\te.plugins.Enabled = cfgs\n\t\t}\n\t}\n\treturn \u0026m\n}","line":{"from":1332,"to":1355}} {"id":100011140,"name":"ClientSet","signature":"func (f *frameworkImpl) ClientSet() clientset.Interface","file":"pkg/scheduler/framework/runtime/framework.go","code":"// ClientSet returns a kubernetes clientset.\nfunc (f *frameworkImpl) ClientSet() clientset.Interface {\n\treturn f.clientSet\n}","line":{"from":1357,"to":1360}} {"id":100011141,"name":"KubeConfig","signature":"func (f *frameworkImpl) KubeConfig() *restclient.Config","file":"pkg/scheduler/framework/runtime/framework.go","code":"// KubeConfig returns a kubernetes config.\nfunc (f *frameworkImpl) KubeConfig() *restclient.Config {\n\treturn f.kubeConfig\n}","line":{"from":1362,"to":1365}} {"id":100011142,"name":"EventRecorder","signature":"func (f *frameworkImpl) EventRecorder() events.EventRecorder","file":"pkg/scheduler/framework/runtime/framework.go","code":"// EventRecorder returns an event recorder.\nfunc (f *frameworkImpl) EventRecorder() events.EventRecorder {\n\treturn f.eventRecorder\n}","line":{"from":1367,"to":1370}} {"id":100011143,"name":"SharedInformerFactory","signature":"func (f *frameworkImpl) SharedInformerFactory() informers.SharedInformerFactory","file":"pkg/scheduler/framework/runtime/framework.go","code":"// SharedInformerFactory returns a shared informer factory.\nfunc (f *frameworkImpl) SharedInformerFactory() informers.SharedInformerFactory {\n\treturn f.informerFactory\n}","line":{"from":1372,"to":1375}} {"id":100011144,"name":"pluginsNeeded","signature":"func (f *frameworkImpl) pluginsNeeded(plugins *config.Plugins) sets.String","file":"pkg/scheduler/framework/runtime/framework.go","code":"func (f *frameworkImpl) pluginsNeeded(plugins *config.Plugins) sets.String {\n\tpgSet := sets.String{}\n\n\tif plugins == nil {\n\t\treturn pgSet\n\t}\n\n\tfind := func(pgs *config.PluginSet) {\n\t\tfor _, pg := range pgs.Enabled {\n\t\t\tpgSet.Insert(pg.Name)\n\t\t}\n\t}\n\n\tfor _, e := range f.getExtensionPoints(plugins) {\n\t\tfind(e.plugins)\n\t}\n\t// Parse MultiPoint separately since they are not returned by f.getExtensionPoints()\n\tfind(\u0026plugins.MultiPoint)\n\n\treturn pgSet\n}","line":{"from":1377,"to":1397}} {"id":100011145,"name":"ProfileName","signature":"func (f *frameworkImpl) ProfileName() string","file":"pkg/scheduler/framework/runtime/framework.go","code":"// ProfileName returns the profile name associated to this framework.\nfunc (f *frameworkImpl) ProfileName() string {\n\treturn f.profileName\n}","line":{"from":1399,"to":1402}} {"id":100011146,"name":"PercentageOfNodesToScore","signature":"func (f *frameworkImpl) PercentageOfNodesToScore() *int32","file":"pkg/scheduler/framework/runtime/framework.go","code":"// PercentageOfNodesToScore returns percentageOfNodesToScore associated to a profile.\nfunc (f *frameworkImpl) PercentageOfNodesToScore() *int32 {\n\treturn f.percentageOfNodesToScore\n}","line":{"from":1404,"to":1407}} {"id":100011147,"name":"Parallelizer","signature":"func (f *frameworkImpl) Parallelizer() parallelize.Parallelizer","file":"pkg/scheduler/framework/runtime/framework.go","code":"// Parallelizer returns a parallelizer holding parallelism for scheduler.\nfunc (f *frameworkImpl) Parallelizer() parallelize.Parallelizer {\n\treturn f.parallelizer\n}","line":{"from":1409,"to":1412}} {"id":100011148,"name":"Filter","signature":"func (p *instrumentedFilterPlugin) Filter(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status","file":"pkg/scheduler/framework/runtime/instrumented_plugins.go","code":"func (p *instrumentedFilterPlugin) Filter(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeInfo *framework.NodeInfo) *framework.Status {\n\tp.metric.Inc()\n\treturn p.FilterPlugin.Filter(ctx, state, pod, nodeInfo)\n}","line":{"from":35,"to":38}} {"id":100011149,"name":"PreFilter","signature":"func (p *instrumentedPreFilterPlugin) PreFilter(ctx context.Context, state *framework.CycleState, pod *v1.Pod) (*framework.PreFilterResult, *framework.Status)","file":"pkg/scheduler/framework/runtime/instrumented_plugins.go","code":"func (p *instrumentedPreFilterPlugin) PreFilter(ctx context.Context, state *framework.CycleState, pod *v1.Pod) (*framework.PreFilterResult, *framework.Status) {\n\tresult, status := p.PreFilterPlugin.PreFilter(ctx, state, pod)\n\tif !status.IsSkip() {\n\t\tp.metric.Inc()\n\t}\n\treturn result, status\n}","line":{"from":48,"to":54}} {"id":100011150,"name":"FactoryAdapter","signature":"func FactoryAdapter(fts plfeature.Features, withFts PluginFactoryWithFts) PluginFactory","file":"pkg/scheduler/framework/runtime/registry.go","code":"// FactoryAdapter can be used to inject feature gates for a plugin that needs\n// them when the caller expects the older PluginFactory method.\nfunc FactoryAdapter(fts plfeature.Features, withFts PluginFactoryWithFts) PluginFactory {\n\treturn func(plArgs runtime.Object, fh framework.Handle) (framework.Plugin, error) {\n\t\treturn withFts(plArgs, fh, fts)\n\t}\n}","line":{"from":35,"to":41}} {"id":100011151,"name":"DecodeInto","signature":"func DecodeInto(obj runtime.Object, into interface{}) error","file":"pkg/scheduler/framework/runtime/registry.go","code":"// DecodeInto decodes configuration whose type is *runtime.Unknown to the interface into.\nfunc DecodeInto(obj runtime.Object, into interface{}) error {\n\tif obj == nil {\n\t\treturn nil\n\t}\n\tconfiguration, ok := obj.(*runtime.Unknown)\n\tif !ok {\n\t\treturn fmt.Errorf(\"want args of type runtime.Unknown, got %T\", obj)\n\t}\n\tif configuration.Raw == nil {\n\t\treturn nil\n\t}\n\n\tswitch configuration.ContentType {\n\t// If ContentType is empty, it means ContentTypeJSON by default.\n\tcase runtime.ContentTypeJSON, \"\":\n\t\treturn json.Unmarshal(configuration.Raw, into)\n\tcase runtime.ContentTypeYAML:\n\t\treturn yaml.Unmarshal(configuration.Raw, into)\n\tdefault:\n\t\treturn fmt.Errorf(\"not supported content type %s\", configuration.ContentType)\n\t}\n}","line":{"from":43,"to":65}} {"id":100011152,"name":"Register","signature":"func (r Registry) Register(name string, factory PluginFactory) error","file":"pkg/scheduler/framework/runtime/registry.go","code":"// Register adds a new plugin to the registry. If a plugin with the same name\n// exists, it returns an error.\nfunc (r Registry) Register(name string, factory PluginFactory) error {\n\tif _, ok := r[name]; ok {\n\t\treturn fmt.Errorf(\"a plugin named %v already exists\", name)\n\t}\n\tr[name] = factory\n\treturn nil\n}","line":{"from":72,"to":80}} {"id":100011153,"name":"Unregister","signature":"func (r Registry) Unregister(name string) error","file":"pkg/scheduler/framework/runtime/registry.go","code":"// Unregister removes an existing plugin from the registry. If no plugin with\n// the provided name exists, it returns an error.\nfunc (r Registry) Unregister(name string) error {\n\tif _, ok := r[name]; !ok {\n\t\treturn fmt.Errorf(\"no plugin named %v exists\", name)\n\t}\n\tdelete(r, name)\n\treturn nil\n}","line":{"from":82,"to":90}} {"id":100011154,"name":"Merge","signature":"func (r Registry) Merge(in Registry) error","file":"pkg/scheduler/framework/runtime/registry.go","code":"// Merge merges the provided registry to the current one.\nfunc (r Registry) Merge(in Registry) error {\n\tfor name, factory := range in {\n\t\tif err := r.Register(name, factory); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":92,"to":100}} {"id":100011155,"name":"newWaitingPodsMap","signature":"func newWaitingPodsMap() *waitingPodsMap","file":"pkg/scheduler/framework/runtime/waiting_pods_map.go","code":"// newWaitingPodsMap returns a new waitingPodsMap.\nfunc newWaitingPodsMap() *waitingPodsMap {\n\treturn \u0026waitingPodsMap{\n\t\tpods: make(map[types.UID]*waitingPod),\n\t}\n}","line":{"from":35,"to":40}} {"id":100011156,"name":"add","signature":"func (m *waitingPodsMap) add(wp *waitingPod)","file":"pkg/scheduler/framework/runtime/waiting_pods_map.go","code":"// add a new WaitingPod to the map.\nfunc (m *waitingPodsMap) add(wp *waitingPod) {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\tm.pods[wp.GetPod().UID] = wp\n}","line":{"from":42,"to":47}} {"id":100011157,"name":"remove","signature":"func (m *waitingPodsMap) remove(uid types.UID)","file":"pkg/scheduler/framework/runtime/waiting_pods_map.go","code":"// remove a WaitingPod from the map.\nfunc (m *waitingPodsMap) remove(uid types.UID) {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\tdelete(m.pods, uid)\n}","line":{"from":49,"to":54}} {"id":100011158,"name":"get","signature":"func (m *waitingPodsMap) get(uid types.UID) *waitingPod","file":"pkg/scheduler/framework/runtime/waiting_pods_map.go","code":"// get a WaitingPod from the map.\nfunc (m *waitingPodsMap) get(uid types.UID) *waitingPod {\n\tm.mu.RLock()\n\tdefer m.mu.RUnlock()\n\treturn m.pods[uid]\n}","line":{"from":56,"to":61}} {"id":100011159,"name":"iterate","signature":"func (m *waitingPodsMap) iterate(callback func(framework.WaitingPod))","file":"pkg/scheduler/framework/runtime/waiting_pods_map.go","code":"// iterate acquires a read lock and iterates over the WaitingPods map.\nfunc (m *waitingPodsMap) iterate(callback func(framework.WaitingPod)) {\n\tm.mu.RLock()\n\tdefer m.mu.RUnlock()\n\tfor _, v := range m.pods {\n\t\tcallback(v)\n\t}\n}","line":{"from":63,"to":70}} {"id":100011160,"name":"newWaitingPod","signature":"func newWaitingPod(pod *v1.Pod, pluginsMaxWaitTime map[string]time.Duration) *waitingPod","file":"pkg/scheduler/framework/runtime/waiting_pods_map.go","code":"// newWaitingPod returns a new waitingPod instance.\nfunc newWaitingPod(pod *v1.Pod, pluginsMaxWaitTime map[string]time.Duration) *waitingPod {\n\twp := \u0026waitingPod{\n\t\tpod: pod,\n\t\t// Allow() and Reject() calls are non-blocking. This property is guaranteed\n\t\t// by using non-blocking send to this channel. This channel has a buffer of size 1\n\t\t// to ensure that non-blocking send will not be ignored - possible situation when\n\t\t// receiving from this channel happens after non-blocking send.\n\t\ts: make(chan *framework.Status, 1),\n\t}\n\n\twp.pendingPlugins = make(map[string]*time.Timer, len(pluginsMaxWaitTime))\n\t// The time.AfterFunc calls wp.Reject which iterates through pendingPlugins map. Acquire the\n\t// lock here so that time.AfterFunc can only execute after newWaitingPod finishes.\n\twp.mu.Lock()\n\tdefer wp.mu.Unlock()\n\tfor k, v := range pluginsMaxWaitTime {\n\t\tplugin, waitTime := k, v\n\t\twp.pendingPlugins[plugin] = time.AfterFunc(waitTime, func() {\n\t\t\tmsg := fmt.Sprintf(\"rejected due to timeout after waiting %v at plugin %v\",\n\t\t\t\twaitTime, plugin)\n\t\t\twp.Reject(plugin, msg)\n\t\t})\n\t}\n\n\treturn wp\n}","line":{"from":82,"to":108}} {"id":100011161,"name":"GetPod","signature":"func (w *waitingPod) GetPod() *v1.Pod","file":"pkg/scheduler/framework/runtime/waiting_pods_map.go","code":"// GetPod returns a reference to the waiting pod.\nfunc (w *waitingPod) GetPod() *v1.Pod {\n\treturn w.pod\n}","line":{"from":110,"to":113}} {"id":100011162,"name":"GetPendingPlugins","signature":"func (w *waitingPod) GetPendingPlugins() []string","file":"pkg/scheduler/framework/runtime/waiting_pods_map.go","code":"// GetPendingPlugins returns a list of pending permit plugin's name.\nfunc (w *waitingPod) GetPendingPlugins() []string {\n\tw.mu.RLock()\n\tdefer w.mu.RUnlock()\n\tplugins := make([]string, 0, len(w.pendingPlugins))\n\tfor p := range w.pendingPlugins {\n\t\tplugins = append(plugins, p)\n\t}\n\n\treturn plugins\n}","line":{"from":115,"to":125}} {"id":100011163,"name":"Allow","signature":"func (w *waitingPod) Allow(pluginName string)","file":"pkg/scheduler/framework/runtime/waiting_pods_map.go","code":"// Allow declares the waiting pod is allowed to be scheduled by plugin pluginName.\n// If this is the last remaining plugin to allow, then a success signal is delivered\n// to unblock the pod.\nfunc (w *waitingPod) Allow(pluginName string) {\n\tw.mu.Lock()\n\tdefer w.mu.Unlock()\n\tif timer, exist := w.pendingPlugins[pluginName]; exist {\n\t\ttimer.Stop()\n\t\tdelete(w.pendingPlugins, pluginName)\n\t}\n\n\t// Only signal success status after all plugins have allowed\n\tif len(w.pendingPlugins) != 0 {\n\t\treturn\n\t}\n\n\t// The select clause works as a non-blocking send.\n\t// If there is no receiver, it's a no-op (default case).\n\tselect {\n\tcase w.s \u003c- framework.NewStatus(framework.Success, \"\"):\n\tdefault:\n\t}\n}","line":{"from":127,"to":149}} {"id":100011164,"name":"Reject","signature":"func (w *waitingPod) Reject(pluginName, msg string)","file":"pkg/scheduler/framework/runtime/waiting_pods_map.go","code":"// Reject declares the waiting pod unschedulable.\nfunc (w *waitingPod) Reject(pluginName, msg string) {\n\tw.mu.RLock()\n\tdefer w.mu.RUnlock()\n\tfor _, timer := range w.pendingPlugins {\n\t\ttimer.Stop()\n\t}\n\n\t// The select clause works as a non-blocking send.\n\t// If there is no receiver, it's a no-op (default case).\n\tselect {\n\tcase w.s \u003c- framework.NewStatus(framework.Unschedulable, msg).WithFailedPlugin(pluginName):\n\tdefault:\n\t}\n}","line":{"from":151,"to":165}} {"id":100011165,"name":"IsWildCard","signature":"func (ce ClusterEvent) IsWildCard() bool","file":"pkg/scheduler/framework/types.go","code":"// IsWildCard returns true if ClusterEvent follows WildCard semantics\nfunc (ce ClusterEvent) IsWildCard() bool {\n\treturn ce.Resource == WildCard \u0026\u0026 ce.ActionType == All\n}","line":{"from":90,"to":93}} {"id":100011166,"name":"DeepCopy","signature":"func (pqi *QueuedPodInfo) DeepCopy() *QueuedPodInfo","file":"pkg/scheduler/framework/types.go","code":"// DeepCopy returns a deep copy of the QueuedPodInfo object.\nfunc (pqi *QueuedPodInfo) DeepCopy() *QueuedPodInfo {\n\treturn \u0026QueuedPodInfo{\n\t\tPodInfo: pqi.PodInfo.DeepCopy(),\n\t\tTimestamp: pqi.Timestamp,\n\t\tAttempts: pqi.Attempts,\n\t\tInitialAttemptTimestamp: pqi.InitialAttemptTimestamp,\n\t\tUnschedulablePlugins: pqi.UnschedulablePlugins.Clone(),\n\t\tGated: pqi.Gated,\n\t}\n}","line":{"from":116,"to":126}} {"id":100011167,"name":"DeepCopy","signature":"func (pi *PodInfo) DeepCopy() *PodInfo","file":"pkg/scheduler/framework/types.go","code":"// DeepCopy returns a deep copy of the PodInfo object.\nfunc (pi *PodInfo) DeepCopy() *PodInfo {\n\treturn \u0026PodInfo{\n\t\tPod: pi.Pod.DeepCopy(),\n\t\tRequiredAffinityTerms: pi.RequiredAffinityTerms,\n\t\tRequiredAntiAffinityTerms: pi.RequiredAntiAffinityTerms,\n\t\tPreferredAffinityTerms: pi.PreferredAffinityTerms,\n\t\tPreferredAntiAffinityTerms: pi.PreferredAntiAffinityTerms,\n\t}\n}","line":{"from":139,"to":148}} {"id":100011168,"name":"Update","signature":"func (pi *PodInfo) Update(pod *v1.Pod) error","file":"pkg/scheduler/framework/types.go","code":"// Update creates a full new PodInfo by default. And only updates the pod when the PodInfo\n// has been instantiated and the passed pod is the exact same one as the original pod.\nfunc (pi *PodInfo) Update(pod *v1.Pod) error {\n\tif pod != nil \u0026\u0026 pi.Pod != nil \u0026\u0026 pi.Pod.UID == pod.UID {\n\t\t// PodInfo includes immutable information, and so it is safe to update the pod in place if it is\n\t\t// the exact same pod\n\t\tpi.Pod = pod\n\t\treturn nil\n\t}\n\tvar preferredAffinityTerms []v1.WeightedPodAffinityTerm\n\tvar preferredAntiAffinityTerms []v1.WeightedPodAffinityTerm\n\tif affinity := pod.Spec.Affinity; affinity != nil {\n\t\tif a := affinity.PodAffinity; a != nil {\n\t\t\tpreferredAffinityTerms = a.PreferredDuringSchedulingIgnoredDuringExecution\n\t\t}\n\t\tif a := affinity.PodAntiAffinity; a != nil {\n\t\t\tpreferredAntiAffinityTerms = a.PreferredDuringSchedulingIgnoredDuringExecution\n\t\t}\n\t}\n\n\t// Attempt to parse the affinity terms\n\tvar parseErrs []error\n\trequiredAffinityTerms, err := getAffinityTerms(pod, getPodAffinityTerms(pod.Spec.Affinity))\n\tif err != nil {\n\t\tparseErrs = append(parseErrs, fmt.Errorf(\"requiredAffinityTerms: %w\", err))\n\t}\n\trequiredAntiAffinityTerms, err := getAffinityTerms(pod,\n\t\tgetPodAntiAffinityTerms(pod.Spec.Affinity))\n\tif err != nil {\n\t\tparseErrs = append(parseErrs, fmt.Errorf(\"requiredAntiAffinityTerms: %w\", err))\n\t}\n\tweightedAffinityTerms, err := getWeightedAffinityTerms(pod, preferredAffinityTerms)\n\tif err != nil {\n\t\tparseErrs = append(parseErrs, fmt.Errorf(\"preferredAffinityTerms: %w\", err))\n\t}\n\tweightedAntiAffinityTerms, err := getWeightedAffinityTerms(pod, preferredAntiAffinityTerms)\n\tif err != nil {\n\t\tparseErrs = append(parseErrs, fmt.Errorf(\"preferredAntiAffinityTerms: %w\", err))\n\t}\n\n\tpi.Pod = pod\n\tpi.RequiredAffinityTerms = requiredAffinityTerms\n\tpi.RequiredAntiAffinityTerms = requiredAntiAffinityTerms\n\tpi.PreferredAffinityTerms = weightedAffinityTerms\n\tpi.PreferredAntiAffinityTerms = weightedAntiAffinityTerms\n\treturn utilerrors.NewAggregate(parseErrs)\n}","line":{"from":150,"to":196}} {"id":100011169,"name":"Matches","signature":"func (at *AffinityTerm) Matches(pod *v1.Pod, nsLabels labels.Set) bool","file":"pkg/scheduler/framework/types.go","code":"// Matches returns true if the pod matches the label selector and namespaces or namespace selector.\nfunc (at *AffinityTerm) Matches(pod *v1.Pod, nsLabels labels.Set) bool {\n\tif at.Namespaces.Has(pod.Namespace) || at.NamespaceSelector.Matches(nsLabels) {\n\t\treturn at.Selector.Matches(labels.Set(pod.Labels))\n\t}\n\treturn false\n}","line":{"from":206,"to":212}} {"id":100011170,"name":"Error","signature":"func (f *FitError) Error() string","file":"pkg/scheduler/framework/types.go","code":"// Error returns detailed information of why the pod failed to fit on each node.\n// A message format is \"0/X nodes are available: \u003cPreFilterMsg\u003e. \u003cFilterMsg\u003e. \u003cPostFilterMsg\u003e.\"\nfunc (f *FitError) Error() string {\n\treasons := make(map[string]int)\n\tfor _, status := range f.Diagnosis.NodeToStatusMap {\n\t\tfor _, reason := range status.Reasons() {\n\t\t\treasons[reason]++\n\t\t}\n\t}\n\n\treasonMsg := fmt.Sprintf(NoNodeAvailableMsg+\":\", f.NumAllNodes)\n\t// Add the messages from PreFilter plugins to reasonMsg.\n\tpreFilterMsg := f.Diagnosis.PreFilterMsg\n\tif preFilterMsg != \"\" {\n\t\treasonMsg += fmt.Sprintf(SeparatorFormat, preFilterMsg)\n\t}\n\tsortReasonsHistogram := func() []string {\n\t\tvar reasonStrings []string\n\t\tfor k, v := range reasons {\n\t\t\treasonStrings = append(reasonStrings, fmt.Sprintf(\"%v %v\", v, k))\n\t\t}\n\t\tsort.Strings(reasonStrings)\n\t\treturn reasonStrings\n\t}\n\tsortedFilterMsg := sortReasonsHistogram()\n\tif len(sortedFilterMsg) != 0 {\n\t\treasonMsg += fmt.Sprintf(SeparatorFormat, strings.Join(sortedFilterMsg, \", \"))\n\t}\n\t// Add the messages from PostFilter plugins to reasonMsg.\n\tpostFilterMsg := f.Diagnosis.PostFilterMsg\n\tif postFilterMsg != \"\" {\n\t\treasonMsg += fmt.Sprintf(SeparatorFormat, postFilterMsg)\n\t}\n\treturn reasonMsg\n}","line":{"from":244,"to":278}} {"id":100011171,"name":"newAffinityTerm","signature":"func newAffinityTerm(pod *v1.Pod, term *v1.PodAffinityTerm) (*AffinityTerm, error)","file":"pkg/scheduler/framework/types.go","code":"func newAffinityTerm(pod *v1.Pod, term *v1.PodAffinityTerm) (*AffinityTerm, error) {\n\tselector, err := metav1.LabelSelectorAsSelector(term.LabelSelector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnamespaces := getNamespacesFromPodAffinityTerm(pod, term)\n\tnsSelector, err := metav1.LabelSelectorAsSelector(term.NamespaceSelector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026AffinityTerm{Namespaces: namespaces, Selector: selector, TopologyKey: term.TopologyKey, NamespaceSelector: nsSelector}, nil\n}","line":{"from":280,"to":293}} {"id":100011172,"name":"getAffinityTerms","signature":"func getAffinityTerms(pod *v1.Pod, v1Terms []v1.PodAffinityTerm) ([]AffinityTerm, error)","file":"pkg/scheduler/framework/types.go","code":"// getAffinityTerms receives a Pod and affinity terms and returns the namespaces and\n// selectors of the terms.\nfunc getAffinityTerms(pod *v1.Pod, v1Terms []v1.PodAffinityTerm) ([]AffinityTerm, error) {\n\tif v1Terms == nil {\n\t\treturn nil, nil\n\t}\n\n\tvar terms []AffinityTerm\n\tfor i := range v1Terms {\n\t\tt, err := newAffinityTerm(pod, \u0026v1Terms[i])\n\t\tif err != nil {\n\t\t\t// We get here if the label selector failed to process\n\t\t\treturn nil, err\n\t\t}\n\t\tterms = append(terms, *t)\n\t}\n\treturn terms, nil\n}","line":{"from":295,"to":312}} {"id":100011173,"name":"getWeightedAffinityTerms","signature":"func getWeightedAffinityTerms(pod *v1.Pod, v1Terms []v1.WeightedPodAffinityTerm) ([]WeightedAffinityTerm, error)","file":"pkg/scheduler/framework/types.go","code":"// getWeightedAffinityTerms returns the list of processed affinity terms.\nfunc getWeightedAffinityTerms(pod *v1.Pod, v1Terms []v1.WeightedPodAffinityTerm) ([]WeightedAffinityTerm, error) {\n\tif v1Terms == nil {\n\t\treturn nil, nil\n\t}\n\n\tvar terms []WeightedAffinityTerm\n\tfor i := range v1Terms {\n\t\tt, err := newAffinityTerm(pod, \u0026v1Terms[i].PodAffinityTerm)\n\t\tif err != nil {\n\t\t\t// We get here if the label selector failed to process\n\t\t\treturn nil, err\n\t\t}\n\t\tterms = append(terms, WeightedAffinityTerm{AffinityTerm: *t, Weight: v1Terms[i].Weight})\n\t}\n\treturn terms, nil\n}","line":{"from":314,"to":330}} {"id":100011174,"name":"NewPodInfo","signature":"func NewPodInfo(pod *v1.Pod) (*PodInfo, error)","file":"pkg/scheduler/framework/types.go","code":"// NewPodInfo returns a new PodInfo.\nfunc NewPodInfo(pod *v1.Pod) (*PodInfo, error) {\n\tpInfo := \u0026PodInfo{}\n\terr := pInfo.Update(pod)\n\treturn pInfo, err\n}","line":{"from":332,"to":337}} {"id":100011175,"name":"getPodAffinityTerms","signature":"func getPodAffinityTerms(affinity *v1.Affinity) (terms []v1.PodAffinityTerm)","file":"pkg/scheduler/framework/types.go","code":"func getPodAffinityTerms(affinity *v1.Affinity) (terms []v1.PodAffinityTerm) {\n\tif affinity != nil \u0026\u0026 affinity.PodAffinity != nil {\n\t\tif len(affinity.PodAffinity.RequiredDuringSchedulingIgnoredDuringExecution) != 0 {\n\t\t\tterms = affinity.PodAffinity.RequiredDuringSchedulingIgnoredDuringExecution\n\t\t}\n\t\t// TODO: Uncomment this block when implement RequiredDuringSchedulingRequiredDuringExecution.\n\t\t// if len(affinity.PodAffinity.RequiredDuringSchedulingRequiredDuringExecution) != 0 {\n\t\t//\tterms = append(terms, affinity.PodAffinity.RequiredDuringSchedulingRequiredDuringExecution...)\n\t\t// }\n\t}\n\treturn terms\n}","line":{"from":339,"to":350}} {"id":100011176,"name":"getPodAntiAffinityTerms","signature":"func getPodAntiAffinityTerms(affinity *v1.Affinity) (terms []v1.PodAffinityTerm)","file":"pkg/scheduler/framework/types.go","code":"func getPodAntiAffinityTerms(affinity *v1.Affinity) (terms []v1.PodAffinityTerm) {\n\tif affinity != nil \u0026\u0026 affinity.PodAntiAffinity != nil {\n\t\tif len(affinity.PodAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution) != 0 {\n\t\t\tterms = affinity.PodAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution\n\t\t}\n\t\t// TODO: Uncomment this block when implement RequiredDuringSchedulingRequiredDuringExecution.\n\t\t// if len(affinity.PodAntiAffinity.RequiredDuringSchedulingRequiredDuringExecution) != 0 {\n\t\t//\tterms = append(terms, affinity.PodAntiAffinity.RequiredDuringSchedulingRequiredDuringExecution...)\n\t\t// }\n\t}\n\treturn terms\n}","line":{"from":352,"to":363}} {"id":100011177,"name":"getNamespacesFromPodAffinityTerm","signature":"func getNamespacesFromPodAffinityTerm(pod *v1.Pod, podAffinityTerm *v1.PodAffinityTerm) sets.String","file":"pkg/scheduler/framework/types.go","code":"// returns a set of names according to the namespaces indicated in podAffinityTerm.\n// If namespaces is empty it considers the given pod's namespace.\nfunc getNamespacesFromPodAffinityTerm(pod *v1.Pod, podAffinityTerm *v1.PodAffinityTerm) sets.String {\n\tnames := sets.String{}\n\tif len(podAffinityTerm.Namespaces) == 0 \u0026\u0026 podAffinityTerm.NamespaceSelector == nil {\n\t\tnames.Insert(pod.Namespace)\n\t} else {\n\t\tnames.Insert(podAffinityTerm.Namespaces...)\n\t}\n\treturn names\n}","line":{"from":365,"to":375}} {"id":100011178,"name":"nextGeneration","signature":"func nextGeneration() int64","file":"pkg/scheduler/framework/types.go","code":"// nextGeneration: Let's make sure history never forgets the name...\n// Increments the generation number monotonically ensuring that generation numbers never collide.\n// Collision of the generation numbers would be particularly problematic if a node was deleted and\n// added back with the same name. See issue#63262.\nfunc nextGeneration() int64 {\n\treturn atomic.AddInt64(\u0026generation, 1)\n}","line":{"from":428,"to":434}} {"id":100011179,"name":"NewResource","signature":"func NewResource(rl v1.ResourceList) *Resource","file":"pkg/scheduler/framework/types.go","code":"// NewResource creates a Resource from ResourceList\nfunc NewResource(rl v1.ResourceList) *Resource {\n\tr := \u0026Resource{}\n\tr.Add(rl)\n\treturn r\n}","line":{"from":448,"to":453}} {"id":100011180,"name":"Add","signature":"func (r *Resource) Add(rl v1.ResourceList)","file":"pkg/scheduler/framework/types.go","code":"// Add adds ResourceList into Resource.\nfunc (r *Resource) Add(rl v1.ResourceList) {\n\tif r == nil {\n\t\treturn\n\t}\n\n\tfor rName, rQuant := range rl {\n\t\tswitch rName {\n\t\tcase v1.ResourceCPU:\n\t\t\tr.MilliCPU += rQuant.MilliValue()\n\t\tcase v1.ResourceMemory:\n\t\t\tr.Memory += rQuant.Value()\n\t\tcase v1.ResourcePods:\n\t\t\tr.AllowedPodNumber += int(rQuant.Value())\n\t\tcase v1.ResourceEphemeralStorage:\n\t\t\tr.EphemeralStorage += rQuant.Value()\n\t\tdefault:\n\t\t\tif schedutil.IsScalarResourceName(rName) {\n\t\t\t\tr.AddScalar(rName, rQuant.Value())\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":455,"to":477}} {"id":100011181,"name":"Clone","signature":"func (r *Resource) Clone() *Resource","file":"pkg/scheduler/framework/types.go","code":"// Clone returns a copy of this resource.\nfunc (r *Resource) Clone() *Resource {\n\tres := \u0026Resource{\n\t\tMilliCPU: r.MilliCPU,\n\t\tMemory: r.Memory,\n\t\tAllowedPodNumber: r.AllowedPodNumber,\n\t\tEphemeralStorage: r.EphemeralStorage,\n\t}\n\tif r.ScalarResources != nil {\n\t\tres.ScalarResources = make(map[v1.ResourceName]int64, len(r.ScalarResources))\n\t\tfor k, v := range r.ScalarResources {\n\t\t\tres.ScalarResources[k] = v\n\t\t}\n\t}\n\treturn res\n}","line":{"from":479,"to":494}} {"id":100011182,"name":"AddScalar","signature":"func (r *Resource) AddScalar(name v1.ResourceName, quantity int64)","file":"pkg/scheduler/framework/types.go","code":"// AddScalar adds a resource by a scalar value of this resource.\nfunc (r *Resource) AddScalar(name v1.ResourceName, quantity int64) {\n\tr.SetScalar(name, r.ScalarResources[name]+quantity)\n}","line":{"from":496,"to":499}} {"id":100011183,"name":"SetScalar","signature":"func (r *Resource) SetScalar(name v1.ResourceName, quantity int64)","file":"pkg/scheduler/framework/types.go","code":"// SetScalar sets a resource by a scalar value of this resource.\nfunc (r *Resource) SetScalar(name v1.ResourceName, quantity int64) {\n\t// Lazily allocate scalar resource map.\n\tif r.ScalarResources == nil {\n\t\tr.ScalarResources = map[v1.ResourceName]int64{}\n\t}\n\tr.ScalarResources[name] = quantity\n}","line":{"from":501,"to":508}} {"id":100011184,"name":"SetMaxResource","signature":"func (r *Resource) SetMaxResource(rl v1.ResourceList)","file":"pkg/scheduler/framework/types.go","code":"// SetMaxResource compares with ResourceList and takes max value for each Resource.\nfunc (r *Resource) SetMaxResource(rl v1.ResourceList) {\n\tif r == nil {\n\t\treturn\n\t}\n\n\tfor rName, rQuantity := range rl {\n\t\tswitch rName {\n\t\tcase v1.ResourceMemory:\n\t\t\tr.Memory = max(r.Memory, rQuantity.Value())\n\t\tcase v1.ResourceCPU:\n\t\t\tr.MilliCPU = max(r.MilliCPU, rQuantity.MilliValue())\n\t\tcase v1.ResourceEphemeralStorage:\n\t\t\tr.EphemeralStorage = max(r.EphemeralStorage, rQuantity.Value())\n\t\tdefault:\n\t\t\tif schedutil.IsScalarResourceName(rName) {\n\t\t\t\tr.SetScalar(rName, max(r.ScalarResources[rName], rQuantity.Value()))\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":510,"to":530}} {"id":100011185,"name":"NewNodeInfo","signature":"func NewNodeInfo(pods ...*v1.Pod) *NodeInfo","file":"pkg/scheduler/framework/types.go","code":"// NewNodeInfo returns a ready to use empty NodeInfo object.\n// If any pods are given in arguments, their information will be aggregated in\n// the returned object.\nfunc NewNodeInfo(pods ...*v1.Pod) *NodeInfo {\n\tni := \u0026NodeInfo{\n\t\tRequested: \u0026Resource{},\n\t\tNonZeroRequested: \u0026Resource{},\n\t\tAllocatable: \u0026Resource{},\n\t\tGeneration: nextGeneration(),\n\t\tUsedPorts: make(HostPortInfo),\n\t\tImageStates: make(map[string]*ImageStateSummary),\n\t\tPVCRefCounts: make(map[string]int),\n\t}\n\tfor _, pod := range pods {\n\t\tni.AddPod(pod)\n\t}\n\treturn ni\n}","line":{"from":532,"to":549}} {"id":100011186,"name":"Node","signature":"func (n *NodeInfo) Node() *v1.Node","file":"pkg/scheduler/framework/types.go","code":"// Node returns overall information about this node.\nfunc (n *NodeInfo) Node() *v1.Node {\n\tif n == nil {\n\t\treturn nil\n\t}\n\treturn n.node\n}","line":{"from":551,"to":557}} {"id":100011187,"name":"Clone","signature":"func (n *NodeInfo) Clone() *NodeInfo","file":"pkg/scheduler/framework/types.go","code":"// Clone returns a copy of this node.\nfunc (n *NodeInfo) Clone() *NodeInfo {\n\tclone := \u0026NodeInfo{\n\t\tnode: n.node,\n\t\tRequested: n.Requested.Clone(),\n\t\tNonZeroRequested: n.NonZeroRequested.Clone(),\n\t\tAllocatable: n.Allocatable.Clone(),\n\t\tUsedPorts: make(HostPortInfo),\n\t\tImageStates: n.ImageStates,\n\t\tPVCRefCounts: make(map[string]int),\n\t\tGeneration: n.Generation,\n\t}\n\tif len(n.Pods) \u003e 0 {\n\t\tclone.Pods = append([]*PodInfo(nil), n.Pods...)\n\t}\n\tif len(n.UsedPorts) \u003e 0 {\n\t\t// HostPortInfo is a map-in-map struct\n\t\t// make sure it's deep copied\n\t\tfor ip, portMap := range n.UsedPorts {\n\t\t\tclone.UsedPorts[ip] = make(map[ProtocolPort]struct{})\n\t\t\tfor protocolPort, v := range portMap {\n\t\t\t\tclone.UsedPorts[ip][protocolPort] = v\n\t\t\t}\n\t\t}\n\t}\n\tif len(n.PodsWithAffinity) \u003e 0 {\n\t\tclone.PodsWithAffinity = append([]*PodInfo(nil), n.PodsWithAffinity...)\n\t}\n\tif len(n.PodsWithRequiredAntiAffinity) \u003e 0 {\n\t\tclone.PodsWithRequiredAntiAffinity = append([]*PodInfo(nil), n.PodsWithRequiredAntiAffinity...)\n\t}\n\tfor key, value := range n.PVCRefCounts {\n\t\tclone.PVCRefCounts[key] = value\n\t}\n\treturn clone\n}","line":{"from":559,"to":594}} {"id":100011188,"name":"String","signature":"func (n *NodeInfo) String() string","file":"pkg/scheduler/framework/types.go","code":"// String returns representation of human readable format of this NodeInfo.\nfunc (n *NodeInfo) String() string {\n\tpodKeys := make([]string, len(n.Pods))\n\tfor i, p := range n.Pods {\n\t\tpodKeys[i] = p.Pod.Name\n\t}\n\treturn fmt.Sprintf(\"\u0026NodeInfo{Pods:%v, RequestedResource:%#v, NonZeroRequest: %#v, UsedPort: %#v, AllocatableResource:%#v}\",\n\t\tpodKeys, n.Requested, n.NonZeroRequested, n.UsedPorts, n.Allocatable)\n}","line":{"from":596,"to":604}} {"id":100011189,"name":"AddPodInfo","signature":"func (n *NodeInfo) AddPodInfo(podInfo *PodInfo)","file":"pkg/scheduler/framework/types.go","code":"// AddPodInfo adds pod information to this NodeInfo.\n// Consider using this instead of AddPod if a PodInfo is already computed.\nfunc (n *NodeInfo) AddPodInfo(podInfo *PodInfo) {\n\tn.Pods = append(n.Pods, podInfo)\n\tif podWithAffinity(podInfo.Pod) {\n\t\tn.PodsWithAffinity = append(n.PodsWithAffinity, podInfo)\n\t}\n\tif podWithRequiredAntiAffinity(podInfo.Pod) {\n\t\tn.PodsWithRequiredAntiAffinity = append(n.PodsWithRequiredAntiAffinity, podInfo)\n\t}\n\tn.update(podInfo.Pod, 1)\n}","line":{"from":606,"to":617}} {"id":100011190,"name":"AddPod","signature":"func (n *NodeInfo) AddPod(pod *v1.Pod)","file":"pkg/scheduler/framework/types.go","code":"// AddPod is a wrapper around AddPodInfo.\nfunc (n *NodeInfo) AddPod(pod *v1.Pod) {\n\t// ignore this err since apiserver doesn't properly validate affinity terms\n\t// and we can't fix the validation for backwards compatibility.\n\tpodInfo, _ := NewPodInfo(pod)\n\tn.AddPodInfo(podInfo)\n}","line":{"from":619,"to":625}} {"id":100011191,"name":"podWithAffinity","signature":"func podWithAffinity(p *v1.Pod) bool","file":"pkg/scheduler/framework/types.go","code":"func podWithAffinity(p *v1.Pod) bool {\n\taffinity := p.Spec.Affinity\n\treturn affinity != nil \u0026\u0026 (affinity.PodAffinity != nil || affinity.PodAntiAffinity != nil)\n}","line":{"from":627,"to":630}} {"id":100011192,"name":"podWithRequiredAntiAffinity","signature":"func podWithRequiredAntiAffinity(p *v1.Pod) bool","file":"pkg/scheduler/framework/types.go","code":"func podWithRequiredAntiAffinity(p *v1.Pod) bool {\n\taffinity := p.Spec.Affinity\n\treturn affinity != nil \u0026\u0026 affinity.PodAntiAffinity != nil \u0026\u0026\n\t\tlen(affinity.PodAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution) != 0\n}","line":{"from":632,"to":636}} {"id":100011193,"name":"removeFromSlice","signature":"func removeFromSlice(s []*PodInfo, k string) []*PodInfo","file":"pkg/scheduler/framework/types.go","code":"func removeFromSlice(s []*PodInfo, k string) []*PodInfo {\n\tfor i := range s {\n\t\tk2, err := GetPodKey(s[i].Pod)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Cannot get pod key\", \"pod\", klog.KObj(s[i].Pod))\n\t\t\tcontinue\n\t\t}\n\t\tif k == k2 {\n\t\t\t// delete the element\n\t\t\ts[i] = s[len(s)-1]\n\t\t\ts = s[:len(s)-1]\n\t\t\tbreak\n\t\t}\n\t}\n\treturn s\n}","line":{"from":638,"to":653}} {"id":100011194,"name":"RemovePod","signature":"func (n *NodeInfo) RemovePod(pod *v1.Pod) error","file":"pkg/scheduler/framework/types.go","code":"// RemovePod subtracts pod information from this NodeInfo.\nfunc (n *NodeInfo) RemovePod(pod *v1.Pod) error {\n\tk, err := GetPodKey(pod)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif podWithAffinity(pod) {\n\t\tn.PodsWithAffinity = removeFromSlice(n.PodsWithAffinity, k)\n\t}\n\tif podWithRequiredAntiAffinity(pod) {\n\t\tn.PodsWithRequiredAntiAffinity = removeFromSlice(n.PodsWithRequiredAntiAffinity, k)\n\t}\n\n\tfor i := range n.Pods {\n\t\tk2, err := GetPodKey(n.Pods[i].Pod)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Cannot get pod key\", \"pod\", klog.KObj(n.Pods[i].Pod))\n\t\t\tcontinue\n\t\t}\n\t\tif k == k2 {\n\t\t\t// delete the element\n\t\t\tn.Pods[i] = n.Pods[len(n.Pods)-1]\n\t\t\tn.Pods = n.Pods[:len(n.Pods)-1]\n\n\t\t\tn.update(pod, -1)\n\t\t\tn.resetSlicesIfEmpty()\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"no corresponding pod %s in pods of node %s\", pod.Name, n.node.Name)\n}","line":{"from":655,"to":685}} {"id":100011195,"name":"update","signature":"func (n *NodeInfo) update(pod *v1.Pod, sign int64)","file":"pkg/scheduler/framework/types.go","code":"// update node info based on the pod and sign.\n// The sign will be set to `+1` when AddPod and to `-1` when RemovePod.\nfunc (n *NodeInfo) update(pod *v1.Pod, sign int64) {\n\tres, non0CPU, non0Mem := calculateResource(pod)\n\tn.Requested.MilliCPU += sign * res.MilliCPU\n\tn.Requested.Memory += sign * res.Memory\n\tn.Requested.EphemeralStorage += sign * res.EphemeralStorage\n\tif n.Requested.ScalarResources == nil \u0026\u0026 len(res.ScalarResources) \u003e 0 {\n\t\tn.Requested.ScalarResources = map[v1.ResourceName]int64{}\n\t}\n\tfor rName, rQuant := range res.ScalarResources {\n\t\tn.Requested.ScalarResources[rName] += sign * rQuant\n\t}\n\tn.NonZeroRequested.MilliCPU += sign * non0CPU\n\tn.NonZeroRequested.Memory += sign * non0Mem\n\n\t// Consume ports when pod added or release ports when pod removed.\n\tn.updateUsedPorts(pod, sign \u003e 0)\n\tn.updatePVCRefCounts(pod, sign \u003e 0)\n\n\tn.Generation = nextGeneration()\n}","line":{"from":687,"to":708}} {"id":100011196,"name":"resetSlicesIfEmpty","signature":"func (n *NodeInfo) resetSlicesIfEmpty()","file":"pkg/scheduler/framework/types.go","code":"// resets the slices to nil so that we can do DeepEqual in unit tests.\nfunc (n *NodeInfo) resetSlicesIfEmpty() {\n\tif len(n.PodsWithAffinity) == 0 {\n\t\tn.PodsWithAffinity = nil\n\t}\n\tif len(n.PodsWithRequiredAntiAffinity) == 0 {\n\t\tn.PodsWithRequiredAntiAffinity = nil\n\t}\n\tif len(n.Pods) == 0 {\n\t\tn.Pods = nil\n\t}\n}","line":{"from":710,"to":721}} {"id":100011197,"name":"max","signature":"func max(a, b int64) int64","file":"pkg/scheduler/framework/types.go","code":"func max(a, b int64) int64 {\n\tif a \u003e= b {\n\t\treturn a\n\t}\n\treturn b\n}","line":{"from":723,"to":728}} {"id":100011198,"name":"calculateResource","signature":"func calculateResource(pod *v1.Pod) (Resource, int64, int64)","file":"pkg/scheduler/framework/types.go","code":"func calculateResource(pod *v1.Pod) (Resource, int64, int64) {\n\tvar non0InitCPU, non0InitMem int64\n\tvar non0CPU, non0Mem int64\n\trequests := resourcehelper.PodRequests(pod, resourcehelper.PodResourcesOptions{\n\t\tInPlacePodVerticalScalingEnabled: utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling),\n\t\tContainerFn: func(requests v1.ResourceList, containerType podutil.ContainerType) {\n\t\t\tnon0CPUReq, non0MemReq := schedutil.GetNonzeroRequests(\u0026requests)\n\t\t\tswitch containerType {\n\t\t\tcase podutil.Containers:\n\t\t\t\tnon0CPU += non0CPUReq\n\t\t\t\tnon0Mem += non0MemReq\n\t\t\tcase podutil.InitContainers:\n\t\t\t\tnon0InitCPU = max(non0InitCPU, non0CPUReq)\n\t\t\t\tnon0InitMem = max(non0InitMem, non0MemReq)\n\t\t\t}\n\t\t},\n\t})\n\n\tnon0CPU = max(non0CPU, non0InitCPU)\n\tnon0Mem = max(non0Mem, non0InitMem)\n\n\t// If Overhead is being utilized, add to the non-zero cpu/memory tracking for the pod. It has already been added\n\t// into ScalarResources since it is part of requests\n\tif pod.Spec.Overhead != nil {\n\t\tif _, found := pod.Spec.Overhead[v1.ResourceCPU]; found {\n\t\t\tnon0CPU += pod.Spec.Overhead.Cpu().MilliValue()\n\t\t}\n\n\t\tif _, found := pod.Spec.Overhead[v1.ResourceMemory]; found {\n\t\t\tnon0Mem += pod.Spec.Overhead.Memory().Value()\n\t\t}\n\t}\n\tvar res Resource\n\tres.Add(requests)\n\treturn res, non0CPU, non0Mem\n}","line":{"from":730,"to":765}} {"id":100011199,"name":"updateUsedPorts","signature":"func (n *NodeInfo) updateUsedPorts(pod *v1.Pod, add bool)","file":"pkg/scheduler/framework/types.go","code":"// updateUsedPorts updates the UsedPorts of NodeInfo.\nfunc (n *NodeInfo) updateUsedPorts(pod *v1.Pod, add bool) {\n\tfor _, container := range pod.Spec.Containers {\n\t\tfor _, podPort := range container.Ports {\n\t\t\tif add {\n\t\t\t\tn.UsedPorts.Add(podPort.HostIP, string(podPort.Protocol), podPort.HostPort)\n\t\t\t} else {\n\t\t\t\tn.UsedPorts.Remove(podPort.HostIP, string(podPort.Protocol), podPort.HostPort)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":767,"to":778}} {"id":100011200,"name":"updatePVCRefCounts","signature":"func (n *NodeInfo) updatePVCRefCounts(pod *v1.Pod, add bool)","file":"pkg/scheduler/framework/types.go","code":"// updatePVCRefCounts updates the PVCRefCounts of NodeInfo.\nfunc (n *NodeInfo) updatePVCRefCounts(pod *v1.Pod, add bool) {\n\tfor _, v := range pod.Spec.Volumes {\n\t\tif v.PersistentVolumeClaim == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tkey := GetNamespacedName(pod.Namespace, v.PersistentVolumeClaim.ClaimName)\n\t\tif add {\n\t\t\tn.PVCRefCounts[key] += 1\n\t\t} else {\n\t\t\tn.PVCRefCounts[key] -= 1\n\t\t\tif n.PVCRefCounts[key] \u003c= 0 {\n\t\t\t\tdelete(n.PVCRefCounts, key)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":780,"to":797}} {"id":100011201,"name":"SetNode","signature":"func (n *NodeInfo) SetNode(node *v1.Node)","file":"pkg/scheduler/framework/types.go","code":"// SetNode sets the overall node information.\nfunc (n *NodeInfo) SetNode(node *v1.Node) {\n\tn.node = node\n\tn.Allocatable = NewResource(node.Status.Allocatable)\n\tn.Generation = nextGeneration()\n}","line":{"from":799,"to":804}} {"id":100011202,"name":"RemoveNode","signature":"func (n *NodeInfo) RemoveNode()","file":"pkg/scheduler/framework/types.go","code":"// RemoveNode removes the node object, leaving all other tracking information.\nfunc (n *NodeInfo) RemoveNode() {\n\tn.node = nil\n\tn.Generation = nextGeneration()\n}","line":{"from":806,"to":810}} {"id":100011203,"name":"GetPodKey","signature":"func GetPodKey(pod *v1.Pod) (string, error)","file":"pkg/scheduler/framework/types.go","code":"// GetPodKey returns the string key of a pod.\nfunc GetPodKey(pod *v1.Pod) (string, error) {\n\tuid := string(pod.UID)\n\tif len(uid) == 0 {\n\t\treturn \"\", errors.New(\"cannot get cache key for pod with empty UID\")\n\t}\n\treturn uid, nil\n}","line":{"from":812,"to":819}} {"id":100011204,"name":"GetNamespacedName","signature":"func GetNamespacedName(namespace, name string) string","file":"pkg/scheduler/framework/types.go","code":"// GetNamespacedName returns the string format of a namespaced resource name.\nfunc GetNamespacedName(namespace, name string) string {\n\treturn fmt.Sprintf(\"%s/%s\", namespace, name)\n}","line":{"from":821,"to":824}} {"id":100011205,"name":"NewProtocolPort","signature":"func NewProtocolPort(protocol string, port int32) *ProtocolPort","file":"pkg/scheduler/framework/types.go","code":"// NewProtocolPort creates a ProtocolPort instance.\nfunc NewProtocolPort(protocol string, port int32) *ProtocolPort {\n\tpp := \u0026ProtocolPort{\n\t\tProtocol: protocol,\n\t\tPort: port,\n\t}\n\n\tif len(pp.Protocol) == 0 {\n\t\tpp.Protocol = string(v1.ProtocolTCP)\n\t}\n\n\treturn pp\n}","line":{"from":835,"to":847}} {"id":100011206,"name":"Add","signature":"func (h HostPortInfo) Add(ip, protocol string, port int32)","file":"pkg/scheduler/framework/types.go","code":"// Add adds (ip, protocol, port) to HostPortInfo\nfunc (h HostPortInfo) Add(ip, protocol string, port int32) {\n\tif port \u003c= 0 {\n\t\treturn\n\t}\n\n\th.sanitize(\u0026ip, \u0026protocol)\n\n\tpp := NewProtocolPort(protocol, port)\n\tif _, ok := h[ip]; !ok {\n\t\th[ip] = map[ProtocolPort]struct{}{\n\t\t\t*pp: {},\n\t\t}\n\t\treturn\n\t}\n\n\th[ip][*pp] = struct{}{}\n}","line":{"from":852,"to":869}} {"id":100011207,"name":"Remove","signature":"func (h HostPortInfo) Remove(ip, protocol string, port int32)","file":"pkg/scheduler/framework/types.go","code":"// Remove removes (ip, protocol, port) from HostPortInfo\nfunc (h HostPortInfo) Remove(ip, protocol string, port int32) {\n\tif port \u003c= 0 {\n\t\treturn\n\t}\n\n\th.sanitize(\u0026ip, \u0026protocol)\n\n\tpp := NewProtocolPort(protocol, port)\n\tif m, ok := h[ip]; ok {\n\t\tdelete(m, *pp)\n\t\tif len(h[ip]) == 0 {\n\t\t\tdelete(h, ip)\n\t\t}\n\t}\n}","line":{"from":871,"to":886}} {"id":100011208,"name":"Len","signature":"func (h HostPortInfo) Len() int","file":"pkg/scheduler/framework/types.go","code":"// Len returns the total number of (ip, protocol, port) tuple in HostPortInfo\nfunc (h HostPortInfo) Len() int {\n\tlength := 0\n\tfor _, m := range h {\n\t\tlength += len(m)\n\t}\n\treturn length\n}","line":{"from":888,"to":895}} {"id":100011209,"name":"CheckConflict","signature":"func (h HostPortInfo) CheckConflict(ip, protocol string, port int32) bool","file":"pkg/scheduler/framework/types.go","code":"// CheckConflict checks if the input (ip, protocol, port) conflicts with the existing\n// ones in HostPortInfo.\nfunc (h HostPortInfo) CheckConflict(ip, protocol string, port int32) bool {\n\tif port \u003c= 0 {\n\t\treturn false\n\t}\n\n\th.sanitize(\u0026ip, \u0026protocol)\n\n\tpp := NewProtocolPort(protocol, port)\n\n\t// If ip is 0.0.0.0 check all IP's (protocol, port) pair\n\tif ip == DefaultBindAllHostIP {\n\t\tfor _, m := range h {\n\t\t\tif _, ok := m[*pp]; ok {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\t// If ip isn't 0.0.0.0, only check IP and 0.0.0.0's (protocol, port) pair\n\tfor _, key := range []string{DefaultBindAllHostIP, ip} {\n\t\tif m, ok := h[key]; ok {\n\t\t\tif _, ok2 := m[*pp]; ok2 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":897,"to":928}} {"id":100011210,"name":"sanitize","signature":"func (h HostPortInfo) sanitize(ip, protocol *string)","file":"pkg/scheduler/framework/types.go","code":"// sanitize the parameters\nfunc (h HostPortInfo) sanitize(ip, protocol *string) {\n\tif len(*ip) == 0 {\n\t\t*ip = DefaultBindAllHostIP\n\t}\n\tif len(*protocol) == 0 {\n\t\t*protocol = string(v1.ProtocolTCP)\n\t}\n}","line":{"from":930,"to":938}} {"id":100011211,"name":"New","signature":"func New(ttl time.Duration, stop \u003c-chan struct{}) Cache","file":"pkg/scheduler/internal/cache/cache.go","code":"// New returns a Cache implementation.\n// It automatically starts a go routine that manages expiration of assumed pods.\n// \"ttl\" is how long the assumed pod will get expired, \"0\" means pod will never expire.\n// \"stop\" is the channel that would close the background goroutine.\nfunc New(ttl time.Duration, stop \u003c-chan struct{}) Cache {\n\tcache := newCache(ttl, cleanAssumedPeriod, stop)\n\tcache.run()\n\treturn cache\n}","line":{"from":36,"to":44}} {"id":100011212,"name":"createImageStateSummary","signature":"func (cache *cacheImpl) createImageStateSummary(state *imageState) *framework.ImageStateSummary","file":"pkg/scheduler/internal/cache/cache.go","code":"// createImageStateSummary returns a summarizing snapshot of the given image's state.\nfunc (cache *cacheImpl) createImageStateSummary(state *imageState) *framework.ImageStateSummary {\n\treturn \u0026framework.ImageStateSummary{\n\t\tSize: state.size,\n\t\tNumNodes: len(state.nodes),\n\t}\n}","line":{"from":92,"to":98}} {"id":100011213,"name":"newCache","signature":"func newCache(ttl, period time.Duration, stop \u003c-chan struct{}) *cacheImpl","file":"pkg/scheduler/internal/cache/cache.go","code":"func newCache(ttl, period time.Duration, stop \u003c-chan struct{}) *cacheImpl {\n\treturn \u0026cacheImpl{\n\t\tttl: ttl,\n\t\tperiod: period,\n\t\tstop: stop,\n\n\t\tnodes: make(map[string]*nodeInfoListItem),\n\t\tnodeTree: newNodeTree(nil),\n\t\tassumedPods: make(sets.String),\n\t\tpodStates: make(map[string]*podState),\n\t\timageStates: make(map[string]*imageState),\n\t}\n}","line":{"from":100,"to":112}} {"id":100011214,"name":"newNodeInfoListItem","signature":"func newNodeInfoListItem(ni *framework.NodeInfo) *nodeInfoListItem","file":"pkg/scheduler/internal/cache/cache.go","code":"// newNodeInfoListItem initializes a new nodeInfoListItem.\nfunc newNodeInfoListItem(ni *framework.NodeInfo) *nodeInfoListItem {\n\treturn \u0026nodeInfoListItem{\n\t\tinfo: ni,\n\t}\n}","line":{"from":114,"to":119}} {"id":100011215,"name":"moveNodeInfoToHead","signature":"func (cache *cacheImpl) moveNodeInfoToHead(name string)","file":"pkg/scheduler/internal/cache/cache.go","code":"// moveNodeInfoToHead moves a NodeInfo to the head of \"cache.nodes\" doubly\n// linked list. The head is the most recently updated NodeInfo.\n// We assume cache lock is already acquired.\nfunc (cache *cacheImpl) moveNodeInfoToHead(name string) {\n\tni, ok := cache.nodes[name]\n\tif !ok {\n\t\tklog.ErrorS(nil, \"No node info with given name found in the cache\", \"node\", klog.KRef(\"\", name))\n\t\treturn\n\t}\n\t// if the node info list item is already at the head, we are done.\n\tif ni == cache.headNode {\n\t\treturn\n\t}\n\n\tif ni.prev != nil {\n\t\tni.prev.next = ni.next\n\t}\n\tif ni.next != nil {\n\t\tni.next.prev = ni.prev\n\t}\n\tif cache.headNode != nil {\n\t\tcache.headNode.prev = ni\n\t}\n\tni.next = cache.headNode\n\tni.prev = nil\n\tcache.headNode = ni\n}","line":{"from":121,"to":147}} {"id":100011216,"name":"removeNodeInfoFromList","signature":"func (cache *cacheImpl) removeNodeInfoFromList(name string)","file":"pkg/scheduler/internal/cache/cache.go","code":"// removeNodeInfoFromList removes a NodeInfo from the \"cache.nodes\" doubly\n// linked list.\n// We assume cache lock is already acquired.\nfunc (cache *cacheImpl) removeNodeInfoFromList(name string) {\n\tni, ok := cache.nodes[name]\n\tif !ok {\n\t\tklog.ErrorS(nil, \"No node info with given name found in the cache\", \"node\", klog.KRef(\"\", name))\n\t\treturn\n\t}\n\n\tif ni.prev != nil {\n\t\tni.prev.next = ni.next\n\t}\n\tif ni.next != nil {\n\t\tni.next.prev = ni.prev\n\t}\n\t// if the removed item was at the head, we must update the head.\n\tif ni == cache.headNode {\n\t\tcache.headNode = ni.next\n\t}\n\tdelete(cache.nodes, name)\n}","line":{"from":149,"to":170}} {"id":100011217,"name":"Dump","signature":"func (cache *cacheImpl) Dump() *Dump","file":"pkg/scheduler/internal/cache/cache.go","code":"// Dump produces a dump of the current scheduler cache. This is used for\n// debugging purposes only and shouldn't be confused with UpdateSnapshot\n// function.\n// This method is expensive, and should be only used in non-critical path.\nfunc (cache *cacheImpl) Dump() *Dump {\n\tcache.mu.RLock()\n\tdefer cache.mu.RUnlock()\n\n\tnodes := make(map[string]*framework.NodeInfo, len(cache.nodes))\n\tfor k, v := range cache.nodes {\n\t\tnodes[k] = v.info.Clone()\n\t}\n\n\treturn \u0026Dump{\n\t\tNodes: nodes,\n\t\tAssumedPods: cache.assumedPods.Union(nil),\n\t}\n}","line":{"from":172,"to":189}} {"id":100011218,"name":"UpdateSnapshot","signature":"func (cache *cacheImpl) UpdateSnapshot(nodeSnapshot *Snapshot) error","file":"pkg/scheduler/internal/cache/cache.go","code":"// UpdateSnapshot takes a snapshot of cached NodeInfo map. This is called at\n// beginning of every scheduling cycle.\n// The snapshot only includes Nodes that are not deleted at the time this function is called.\n// nodeInfo.Node() is guaranteed to be not nil for all the nodes in the snapshot.\n// This function tracks generation number of NodeInfo and updates only the\n// entries of an existing snapshot that have changed after the snapshot was taken.\nfunc (cache *cacheImpl) UpdateSnapshot(nodeSnapshot *Snapshot) error {\n\tcache.mu.Lock()\n\tdefer cache.mu.Unlock()\n\n\t// Get the last generation of the snapshot.\n\tsnapshotGeneration := nodeSnapshot.generation\n\n\t// NodeInfoList and HavePodsWithAffinityNodeInfoList must be re-created if a node was added\n\t// or removed from the cache.\n\tupdateAllLists := false\n\t// HavePodsWithAffinityNodeInfoList must be re-created if a node changed its\n\t// status from having pods with affinity to NOT having pods with affinity or the other\n\t// way around.\n\tupdateNodesHavePodsWithAffinity := false\n\t// HavePodsWithRequiredAntiAffinityNodeInfoList must be re-created if a node changed its\n\t// status from having pods with required anti-affinity to NOT having pods with required\n\t// anti-affinity or the other way around.\n\tupdateNodesHavePodsWithRequiredAntiAffinity := false\n\t// usedPVCSet must be re-created whenever the head node generation is greater than\n\t// last snapshot generation.\n\tupdateUsedPVCSet := false\n\n\t// Start from the head of the NodeInfo doubly linked list and update snapshot\n\t// of NodeInfos updated after the last snapshot.\n\tfor node := cache.headNode; node != nil; node = node.next {\n\t\tif node.info.Generation \u003c= snapshotGeneration {\n\t\t\t// all the nodes are updated before the existing snapshot. We are done.\n\t\t\tbreak\n\t\t}\n\t\tif np := node.info.Node(); np != nil {\n\t\t\texisting, ok := nodeSnapshot.nodeInfoMap[np.Name]\n\t\t\tif !ok {\n\t\t\t\tupdateAllLists = true\n\t\t\t\texisting = \u0026framework.NodeInfo{}\n\t\t\t\tnodeSnapshot.nodeInfoMap[np.Name] = existing\n\t\t\t}\n\t\t\tclone := node.info.Clone()\n\t\t\t// We track nodes that have pods with affinity, here we check if this node changed its\n\t\t\t// status from having pods with affinity to NOT having pods with affinity or the other\n\t\t\t// way around.\n\t\t\tif (len(existing.PodsWithAffinity) \u003e 0) != (len(clone.PodsWithAffinity) \u003e 0) {\n\t\t\t\tupdateNodesHavePodsWithAffinity = true\n\t\t\t}\n\t\t\tif (len(existing.PodsWithRequiredAntiAffinity) \u003e 0) != (len(clone.PodsWithRequiredAntiAffinity) \u003e 0) {\n\t\t\t\tupdateNodesHavePodsWithRequiredAntiAffinity = true\n\t\t\t}\n\t\t\tif !updateUsedPVCSet {\n\t\t\t\tif len(existing.PVCRefCounts) != len(clone.PVCRefCounts) {\n\t\t\t\t\tupdateUsedPVCSet = true\n\t\t\t\t} else {\n\t\t\t\t\tfor pvcKey := range clone.PVCRefCounts {\n\t\t\t\t\t\tif _, found := existing.PVCRefCounts[pvcKey]; !found {\n\t\t\t\t\t\t\tupdateUsedPVCSet = true\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// We need to preserve the original pointer of the NodeInfo struct since it\n\t\t\t// is used in the NodeInfoList, which we may not update.\n\t\t\t*existing = *clone\n\t\t}\n\t}\n\t// Update the snapshot generation with the latest NodeInfo generation.\n\tif cache.headNode != nil {\n\t\tnodeSnapshot.generation = cache.headNode.info.Generation\n\t}\n\n\t// Comparing to pods in nodeTree.\n\t// Deleted nodes get removed from the tree, but they might remain in the nodes map\n\t// if they still have non-deleted Pods.\n\tif len(nodeSnapshot.nodeInfoMap) \u003e cache.nodeTree.numNodes {\n\t\tcache.removeDeletedNodesFromSnapshot(nodeSnapshot)\n\t\tupdateAllLists = true\n\t}\n\n\tif updateAllLists || updateNodesHavePodsWithAffinity || updateNodesHavePodsWithRequiredAntiAffinity || updateUsedPVCSet {\n\t\tcache.updateNodeInfoSnapshotList(nodeSnapshot, updateAllLists)\n\t}\n\n\tif len(nodeSnapshot.nodeInfoList) != cache.nodeTree.numNodes {\n\t\terrMsg := fmt.Sprintf(\"snapshot state is not consistent, length of NodeInfoList=%v not equal to length of nodes in tree=%v \"+\n\t\t\t\", length of NodeInfoMap=%v, length of nodes in cache=%v\"+\n\t\t\t\", trying to recover\",\n\t\t\tlen(nodeSnapshot.nodeInfoList), cache.nodeTree.numNodes,\n\t\t\tlen(nodeSnapshot.nodeInfoMap), len(cache.nodes))\n\t\tklog.ErrorS(nil, errMsg)\n\t\t// We will try to recover by re-creating the lists for the next scheduling cycle, but still return an\n\t\t// error to surface the problem, the error will likely cause a failure to the current scheduling cycle.\n\t\tcache.updateNodeInfoSnapshotList(nodeSnapshot, true)\n\t\treturn fmt.Errorf(errMsg)\n\t}\n\n\treturn nil\n}","line":{"from":191,"to":291}} {"id":100011219,"name":"updateNodeInfoSnapshotList","signature":"func (cache *cacheImpl) updateNodeInfoSnapshotList(snapshot *Snapshot, updateAll bool)","file":"pkg/scheduler/internal/cache/cache.go","code":"func (cache *cacheImpl) updateNodeInfoSnapshotList(snapshot *Snapshot, updateAll bool) {\n\tsnapshot.havePodsWithAffinityNodeInfoList = make([]*framework.NodeInfo, 0, cache.nodeTree.numNodes)\n\tsnapshot.havePodsWithRequiredAntiAffinityNodeInfoList = make([]*framework.NodeInfo, 0, cache.nodeTree.numNodes)\n\tsnapshot.usedPVCSet = sets.NewString()\n\tif updateAll {\n\t\t// Take a snapshot of the nodes order in the tree\n\t\tsnapshot.nodeInfoList = make([]*framework.NodeInfo, 0, cache.nodeTree.numNodes)\n\t\tnodesList, err := cache.nodeTree.list()\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Error occurred while retrieving the list of names of the nodes from node tree\")\n\t\t}\n\t\tfor _, nodeName := range nodesList {\n\t\t\tif nodeInfo := snapshot.nodeInfoMap[nodeName]; nodeInfo != nil {\n\t\t\t\tsnapshot.nodeInfoList = append(snapshot.nodeInfoList, nodeInfo)\n\t\t\t\tif len(nodeInfo.PodsWithAffinity) \u003e 0 {\n\t\t\t\t\tsnapshot.havePodsWithAffinityNodeInfoList = append(snapshot.havePodsWithAffinityNodeInfoList, nodeInfo)\n\t\t\t\t}\n\t\t\t\tif len(nodeInfo.PodsWithRequiredAntiAffinity) \u003e 0 {\n\t\t\t\t\tsnapshot.havePodsWithRequiredAntiAffinityNodeInfoList = append(snapshot.havePodsWithRequiredAntiAffinityNodeInfoList, nodeInfo)\n\t\t\t\t}\n\t\t\t\tfor key := range nodeInfo.PVCRefCounts {\n\t\t\t\t\tsnapshot.usedPVCSet.Insert(key)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tklog.ErrorS(nil, \"Node exists in nodeTree but not in NodeInfoMap, this should not happen\", \"node\", klog.KRef(\"\", nodeName))\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor _, nodeInfo := range snapshot.nodeInfoList {\n\t\t\tif len(nodeInfo.PodsWithAffinity) \u003e 0 {\n\t\t\t\tsnapshot.havePodsWithAffinityNodeInfoList = append(snapshot.havePodsWithAffinityNodeInfoList, nodeInfo)\n\t\t\t}\n\t\t\tif len(nodeInfo.PodsWithRequiredAntiAffinity) \u003e 0 {\n\t\t\t\tsnapshot.havePodsWithRequiredAntiAffinityNodeInfoList = append(snapshot.havePodsWithRequiredAntiAffinityNodeInfoList, nodeInfo)\n\t\t\t}\n\t\t\tfor key := range nodeInfo.PVCRefCounts {\n\t\t\t\tsnapshot.usedPVCSet.Insert(key)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":293,"to":333}} {"id":100011220,"name":"removeDeletedNodesFromSnapshot","signature":"func (cache *cacheImpl) removeDeletedNodesFromSnapshot(snapshot *Snapshot)","file":"pkg/scheduler/internal/cache/cache.go","code":"// If certain nodes were deleted after the last snapshot was taken, we should remove them from the snapshot.\nfunc (cache *cacheImpl) removeDeletedNodesFromSnapshot(snapshot *Snapshot) {\n\ttoDelete := len(snapshot.nodeInfoMap) - cache.nodeTree.numNodes\n\tfor name := range snapshot.nodeInfoMap {\n\t\tif toDelete \u003c= 0 {\n\t\t\tbreak\n\t\t}\n\t\tif n, ok := cache.nodes[name]; !ok || n.info.Node() == nil {\n\t\t\tdelete(snapshot.nodeInfoMap, name)\n\t\t\ttoDelete--\n\t\t}\n\t}\n}","line":{"from":335,"to":347}} {"id":100011221,"name":"NodeCount","signature":"func (cache *cacheImpl) NodeCount() int","file":"pkg/scheduler/internal/cache/cache.go","code":"// NodeCount returns the number of nodes in the cache.\n// DO NOT use outside of tests.\nfunc (cache *cacheImpl) NodeCount() int {\n\tcache.mu.RLock()\n\tdefer cache.mu.RUnlock()\n\treturn len(cache.nodes)\n}","line":{"from":349,"to":355}} {"id":100011222,"name":"PodCount","signature":"func (cache *cacheImpl) PodCount() (int, error)","file":"pkg/scheduler/internal/cache/cache.go","code":"// PodCount returns the number of pods in the cache (including those from deleted nodes).\n// DO NOT use outside of tests.\nfunc (cache *cacheImpl) PodCount() (int, error) {\n\tcache.mu.RLock()\n\tdefer cache.mu.RUnlock()\n\t// podFilter is expected to return true for most or all of the pods. We\n\t// can avoid expensive array growth without wasting too much memory by\n\t// pre-allocating capacity.\n\tcount := 0\n\tfor _, n := range cache.nodes {\n\t\tcount += len(n.info.Pods)\n\t}\n\treturn count, nil\n}","line":{"from":357,"to":370}} {"id":100011223,"name":"AssumePod","signature":"func (cache *cacheImpl) AssumePod(pod *v1.Pod) error","file":"pkg/scheduler/internal/cache/cache.go","code":"func (cache *cacheImpl) AssumePod(pod *v1.Pod) error {\n\tkey, err := framework.GetPodKey(pod)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcache.mu.Lock()\n\tdefer cache.mu.Unlock()\n\tif _, ok := cache.podStates[key]; ok {\n\t\treturn fmt.Errorf(\"pod %v(%v) is in the cache, so can't be assumed\", key, klog.KObj(pod))\n\t}\n\n\treturn cache.addPod(pod, true)\n}","line":{"from":372,"to":385}} {"id":100011224,"name":"FinishBinding","signature":"func (cache *cacheImpl) FinishBinding(pod *v1.Pod) error","file":"pkg/scheduler/internal/cache/cache.go","code":"func (cache *cacheImpl) FinishBinding(pod *v1.Pod) error {\n\treturn cache.finishBinding(pod, time.Now())\n}","line":{"from":387,"to":389}} {"id":100011225,"name":"finishBinding","signature":"func (cache *cacheImpl) finishBinding(pod *v1.Pod, now time.Time) error","file":"pkg/scheduler/internal/cache/cache.go","code":"// finishBinding exists to make tests deterministic by injecting now as an argument\nfunc (cache *cacheImpl) finishBinding(pod *v1.Pod, now time.Time) error {\n\tkey, err := framework.GetPodKey(pod)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcache.mu.RLock()\n\tdefer cache.mu.RUnlock()\n\n\tklog.V(5).InfoS(\"Finished binding for pod, can be expired\", \"podKey\", key, \"pod\", klog.KObj(pod))\n\tcurrState, ok := cache.podStates[key]\n\tif ok \u0026\u0026 cache.assumedPods.Has(key) {\n\t\tif cache.ttl == time.Duration(0) {\n\t\t\tcurrState.deadline = nil\n\t\t} else {\n\t\t\tdl := now.Add(cache.ttl)\n\t\t\tcurrState.deadline = \u0026dl\n\t\t}\n\t\tcurrState.bindingFinished = true\n\t}\n\treturn nil\n}","line":{"from":391,"to":413}} {"id":100011226,"name":"ForgetPod","signature":"func (cache *cacheImpl) ForgetPod(pod *v1.Pod) error","file":"pkg/scheduler/internal/cache/cache.go","code":"func (cache *cacheImpl) ForgetPod(pod *v1.Pod) error {\n\tkey, err := framework.GetPodKey(pod)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcache.mu.Lock()\n\tdefer cache.mu.Unlock()\n\n\tcurrState, ok := cache.podStates[key]\n\tif ok \u0026\u0026 currState.pod.Spec.NodeName != pod.Spec.NodeName {\n\t\treturn fmt.Errorf(\"pod %v(%v) was assumed on %v but assigned to %v\", key, klog.KObj(pod), pod.Spec.NodeName, currState.pod.Spec.NodeName)\n\t}\n\n\t// Only assumed pod can be forgotten.\n\tif ok \u0026\u0026 cache.assumedPods.Has(key) {\n\t\treturn cache.removePod(pod)\n\t}\n\treturn fmt.Errorf(\"pod %v(%v) wasn't assumed so cannot be forgotten\", key, klog.KObj(pod))\n}","line":{"from":415,"to":434}} {"id":100011227,"name":"addPod","signature":"func (cache *cacheImpl) addPod(pod *v1.Pod, assumePod bool) error","file":"pkg/scheduler/internal/cache/cache.go","code":"// Assumes that lock is already acquired.\nfunc (cache *cacheImpl) addPod(pod *v1.Pod, assumePod bool) error {\n\tkey, err := framework.GetPodKey(pod)\n\tif err != nil {\n\t\treturn err\n\t}\n\tn, ok := cache.nodes[pod.Spec.NodeName]\n\tif !ok {\n\t\tn = newNodeInfoListItem(framework.NewNodeInfo())\n\t\tcache.nodes[pod.Spec.NodeName] = n\n\t}\n\tn.info.AddPod(pod)\n\tcache.moveNodeInfoToHead(pod.Spec.NodeName)\n\tps := \u0026podState{\n\t\tpod: pod,\n\t}\n\tcache.podStates[key] = ps\n\tif assumePod {\n\t\tcache.assumedPods.Insert(key)\n\t}\n\treturn nil\n}","line":{"from":436,"to":457}} {"id":100011228,"name":"updatePod","signature":"func (cache *cacheImpl) updatePod(oldPod, newPod *v1.Pod) error","file":"pkg/scheduler/internal/cache/cache.go","code":"// Assumes that lock is already acquired.\nfunc (cache *cacheImpl) updatePod(oldPod, newPod *v1.Pod) error {\n\tif err := cache.removePod(oldPod); err != nil {\n\t\treturn err\n\t}\n\treturn cache.addPod(newPod, false)\n}","line":{"from":459,"to":465}} {"id":100011229,"name":"removePod","signature":"func (cache *cacheImpl) removePod(pod *v1.Pod) error","file":"pkg/scheduler/internal/cache/cache.go","code":"// Assumes that lock is already acquired.\n// Removes a pod from the cached node info. If the node information was already\n// removed and there are no more pods left in the node, cleans up the node from\n// the cache.\nfunc (cache *cacheImpl) removePod(pod *v1.Pod) error {\n\tkey, err := framework.GetPodKey(pod)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tn, ok := cache.nodes[pod.Spec.NodeName]\n\tif !ok {\n\t\tklog.ErrorS(nil, \"Node not found when trying to remove pod\", \"node\", klog.KRef(\"\", pod.Spec.NodeName), \"podKey\", key, \"pod\", klog.KObj(pod))\n\n\t} else {\n\t\tif err := n.info.RemovePod(pod); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(n.info.Pods) == 0 \u0026\u0026 n.info.Node() == nil {\n\t\t\tcache.removeNodeInfoFromList(pod.Spec.NodeName)\n\t\t} else {\n\t\t\tcache.moveNodeInfoToHead(pod.Spec.NodeName)\n\t\t}\n\t}\n\n\tdelete(cache.podStates, key)\n\tdelete(cache.assumedPods, key)\n\treturn nil\n}","line":{"from":467,"to":495}} {"id":100011230,"name":"AddPod","signature":"func (cache *cacheImpl) AddPod(pod *v1.Pod) error","file":"pkg/scheduler/internal/cache/cache.go","code":"func (cache *cacheImpl) AddPod(pod *v1.Pod) error {\n\tkey, err := framework.GetPodKey(pod)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcache.mu.Lock()\n\tdefer cache.mu.Unlock()\n\n\tcurrState, ok := cache.podStates[key]\n\tswitch {\n\tcase ok \u0026\u0026 cache.assumedPods.Has(key):\n\t\t// When assuming, we've already added the Pod to cache,\n\t\t// Just update here to make sure the Pod's status is up-to-date.\n\t\tif err = cache.updatePod(currState.pod, pod); err != nil {\n\t\t\tklog.ErrorS(err, \"Error occurred while updating pod\")\n\t\t}\n\t\tif currState.pod.Spec.NodeName != pod.Spec.NodeName {\n\t\t\t// The pod was added to a different node than it was assumed to.\n\t\t\tklog.InfoS(\"Pod was added to a different node than it was assumed\", \"podKey\", key, \"pod\", klog.KObj(pod), \"assumedNode\", klog.KRef(\"\", pod.Spec.NodeName), \"currentNode\", klog.KRef(\"\", currState.pod.Spec.NodeName))\n\t\t\treturn nil\n\t\t}\n\tcase !ok:\n\t\t// Pod was expired. We should add it back.\n\t\tif err = cache.addPod(pod, false); err != nil {\n\t\t\tklog.ErrorS(err, \"Error occurred while adding pod\")\n\t\t}\n\tdefault:\n\t\treturn fmt.Errorf(\"pod %v(%v) was already in added state\", key, klog.KObj(pod))\n\t}\n\treturn nil\n}","line":{"from":497,"to":528}} {"id":100011231,"name":"UpdatePod","signature":"func (cache *cacheImpl) UpdatePod(oldPod, newPod *v1.Pod) error","file":"pkg/scheduler/internal/cache/cache.go","code":"func (cache *cacheImpl) UpdatePod(oldPod, newPod *v1.Pod) error {\n\tkey, err := framework.GetPodKey(oldPod)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcache.mu.Lock()\n\tdefer cache.mu.Unlock()\n\n\tcurrState, ok := cache.podStates[key]\n\tif !ok {\n\t\treturn fmt.Errorf(\"pod %v(%v) is not added to scheduler cache, so cannot be updated\", key, klog.KObj(oldPod))\n\t}\n\n\t// An assumed pod won't have Update/Remove event. It needs to have Add event\n\t// before Update event, in which case the state would change from Assumed to Added.\n\tif cache.assumedPods.Has(key) {\n\t\treturn fmt.Errorf(\"assumed pod %v(%v) should not be updated\", key, klog.KObj(oldPod))\n\t}\n\n\tif currState.pod.Spec.NodeName != newPod.Spec.NodeName {\n\t\tklog.ErrorS(nil, \"Pod updated on a different node than previously added to\", \"podKey\", key, \"pod\", klog.KObj(oldPod))\n\t\tklog.ErrorS(nil, \"scheduler cache is corrupted and can badly affect scheduling decisions\")\n\t\tklog.FlushAndExit(klog.ExitFlushTimeout, 1)\n\t}\n\treturn cache.updatePod(oldPod, newPod)\n}","line":{"from":530,"to":556}} {"id":100011232,"name":"RemovePod","signature":"func (cache *cacheImpl) RemovePod(pod *v1.Pod) error","file":"pkg/scheduler/internal/cache/cache.go","code":"func (cache *cacheImpl) RemovePod(pod *v1.Pod) error {\n\tkey, err := framework.GetPodKey(pod)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcache.mu.Lock()\n\tdefer cache.mu.Unlock()\n\n\tcurrState, ok := cache.podStates[key]\n\tif !ok {\n\t\treturn fmt.Errorf(\"pod %v(%v) is not found in scheduler cache, so cannot be removed from it\", key, klog.KObj(pod))\n\t}\n\tif currState.pod.Spec.NodeName != pod.Spec.NodeName {\n\t\tklog.ErrorS(nil, \"Pod was added to a different node than it was assumed\", \"podKey\", key, \"pod\", klog.KObj(pod), \"assumedNode\", klog.KRef(\"\", pod.Spec.NodeName), \"currentNode\", klog.KRef(\"\", currState.pod.Spec.NodeName))\n\t\tif pod.Spec.NodeName != \"\" {\n\t\t\t// An empty NodeName is possible when the scheduler misses a Delete\n\t\t\t// event and it gets the last known state from the informer cache.\n\t\t\tklog.ErrorS(nil, \"scheduler cache is corrupted and can badly affect scheduling decisions\")\n\t\t\tklog.FlushAndExit(klog.ExitFlushTimeout, 1)\n\t\t}\n\t}\n\treturn cache.removePod(currState.pod)\n}","line":{"from":558,"to":581}} {"id":100011233,"name":"IsAssumedPod","signature":"func (cache *cacheImpl) IsAssumedPod(pod *v1.Pod) (bool, error)","file":"pkg/scheduler/internal/cache/cache.go","code":"func (cache *cacheImpl) IsAssumedPod(pod *v1.Pod) (bool, error) {\n\tkey, err := framework.GetPodKey(pod)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tcache.mu.RLock()\n\tdefer cache.mu.RUnlock()\n\n\treturn cache.assumedPods.Has(key), nil\n}","line":{"from":583,"to":593}} {"id":100011234,"name":"GetPod","signature":"func (cache *cacheImpl) GetPod(pod *v1.Pod) (*v1.Pod, error)","file":"pkg/scheduler/internal/cache/cache.go","code":"// GetPod might return a pod for which its node has already been deleted from\n// the main cache. This is useful to properly process pod update events.\nfunc (cache *cacheImpl) GetPod(pod *v1.Pod) (*v1.Pod, error) {\n\tkey, err := framework.GetPodKey(pod)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcache.mu.RLock()\n\tdefer cache.mu.RUnlock()\n\n\tpodState, ok := cache.podStates[key]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"pod %v(%v) does not exist in scheduler cache\", key, klog.KObj(pod))\n\t}\n\n\treturn podState.pod, nil\n}","line":{"from":595,"to":612}} {"id":100011235,"name":"AddNode","signature":"func (cache *cacheImpl) AddNode(node *v1.Node) *framework.NodeInfo","file":"pkg/scheduler/internal/cache/cache.go","code":"func (cache *cacheImpl) AddNode(node *v1.Node) *framework.NodeInfo {\n\tcache.mu.Lock()\n\tdefer cache.mu.Unlock()\n\n\tn, ok := cache.nodes[node.Name]\n\tif !ok {\n\t\tn = newNodeInfoListItem(framework.NewNodeInfo())\n\t\tcache.nodes[node.Name] = n\n\t} else {\n\t\tcache.removeNodeImageStates(n.info.Node())\n\t}\n\tcache.moveNodeInfoToHead(node.Name)\n\n\tcache.nodeTree.addNode(node)\n\tcache.addNodeImageStates(node, n.info)\n\tn.info.SetNode(node)\n\treturn n.info.Clone()\n}","line":{"from":614,"to":631}} {"id":100011236,"name":"UpdateNode","signature":"func (cache *cacheImpl) UpdateNode(oldNode, newNode *v1.Node) *framework.NodeInfo","file":"pkg/scheduler/internal/cache/cache.go","code":"func (cache *cacheImpl) UpdateNode(oldNode, newNode *v1.Node) *framework.NodeInfo {\n\tcache.mu.Lock()\n\tdefer cache.mu.Unlock()\n\n\tn, ok := cache.nodes[newNode.Name]\n\tif !ok {\n\t\tn = newNodeInfoListItem(framework.NewNodeInfo())\n\t\tcache.nodes[newNode.Name] = n\n\t\tcache.nodeTree.addNode(newNode)\n\t} else {\n\t\tcache.removeNodeImageStates(n.info.Node())\n\t}\n\tcache.moveNodeInfoToHead(newNode.Name)\n\n\tcache.nodeTree.updateNode(oldNode, newNode)\n\tcache.addNodeImageStates(newNode, n.info)\n\tn.info.SetNode(newNode)\n\treturn n.info.Clone()\n}","line":{"from":633,"to":651}} {"id":100011237,"name":"RemoveNode","signature":"func (cache *cacheImpl) RemoveNode(node *v1.Node) error","file":"pkg/scheduler/internal/cache/cache.go","code":"// RemoveNode removes a node from the cache's tree.\n// The node might still have pods because their deletion events didn't arrive\n// yet. Those pods are considered removed from the cache, being the node tree\n// the source of truth.\n// However, we keep a ghost node with the list of pods until all pod deletion\n// events have arrived. A ghost node is skipped from snapshots.\nfunc (cache *cacheImpl) RemoveNode(node *v1.Node) error {\n\tcache.mu.Lock()\n\tdefer cache.mu.Unlock()\n\n\tn, ok := cache.nodes[node.Name]\n\tif !ok {\n\t\treturn fmt.Errorf(\"node %v is not found\", node.Name)\n\t}\n\tn.info.RemoveNode()\n\t// We remove NodeInfo for this node only if there aren't any pods on this node.\n\t// We can't do it unconditionally, because notifications about pods are delivered\n\t// in a different watch, and thus can potentially be observed later, even though\n\t// they happened before node removal.\n\tif len(n.info.Pods) == 0 {\n\t\tcache.removeNodeInfoFromList(node.Name)\n\t} else {\n\t\tcache.moveNodeInfoToHead(node.Name)\n\t}\n\tif err := cache.nodeTree.removeNode(node); err != nil {\n\t\treturn err\n\t}\n\tcache.removeNodeImageStates(node)\n\treturn nil\n}","line":{"from":653,"to":682}} {"id":100011238,"name":"addNodeImageStates","signature":"func (cache *cacheImpl) addNodeImageStates(node *v1.Node, nodeInfo *framework.NodeInfo)","file":"pkg/scheduler/internal/cache/cache.go","code":"// addNodeImageStates adds states of the images on given node to the given nodeInfo and update the imageStates in\n// scheduler cache. This function assumes the lock to scheduler cache has been acquired.\nfunc (cache *cacheImpl) addNodeImageStates(node *v1.Node, nodeInfo *framework.NodeInfo) {\n\tnewSum := make(map[string]*framework.ImageStateSummary)\n\n\tfor _, image := range node.Status.Images {\n\t\tfor _, name := range image.Names {\n\t\t\t// update the entry in imageStates\n\t\t\tstate, ok := cache.imageStates[name]\n\t\t\tif !ok {\n\t\t\t\tstate = \u0026imageState{\n\t\t\t\t\tsize: image.SizeBytes,\n\t\t\t\t\tnodes: sets.NewString(node.Name),\n\t\t\t\t}\n\t\t\t\tcache.imageStates[name] = state\n\t\t\t} else {\n\t\t\t\tstate.nodes.Insert(node.Name)\n\t\t\t}\n\t\t\t// create the imageStateSummary for this image\n\t\t\tif _, ok := newSum[name]; !ok {\n\t\t\t\tnewSum[name] = cache.createImageStateSummary(state)\n\t\t\t}\n\t\t}\n\t}\n\tnodeInfo.ImageStates = newSum\n}","line":{"from":684,"to":709}} {"id":100011239,"name":"removeNodeImageStates","signature":"func (cache *cacheImpl) removeNodeImageStates(node *v1.Node)","file":"pkg/scheduler/internal/cache/cache.go","code":"// removeNodeImageStates removes the given node record from image entries having the node\n// in imageStates cache. After the removal, if any image becomes free, i.e., the image\n// is no longer available on any node, the image entry will be removed from imageStates.\nfunc (cache *cacheImpl) removeNodeImageStates(node *v1.Node) {\n\tif node == nil {\n\t\treturn\n\t}\n\n\tfor _, image := range node.Status.Images {\n\t\tfor _, name := range image.Names {\n\t\t\tstate, ok := cache.imageStates[name]\n\t\t\tif ok {\n\t\t\t\tstate.nodes.Delete(node.Name)\n\t\t\t\tif len(state.nodes) == 0 {\n\t\t\t\t\t// Remove the unused image to make sure the length of\n\t\t\t\t\t// imageStates represents the total number of different\n\t\t\t\t\t// images on all nodes\n\t\t\t\t\tdelete(cache.imageStates, name)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":711,"to":733}} {"id":100011240,"name":"run","signature":"func (cache *cacheImpl) run()","file":"pkg/scheduler/internal/cache/cache.go","code":"func (cache *cacheImpl) run() {\n\tgo wait.Until(cache.cleanupExpiredAssumedPods, cache.period, cache.stop)\n}","line":{"from":735,"to":737}} {"id":100011241,"name":"cleanupExpiredAssumedPods","signature":"func (cache *cacheImpl) cleanupExpiredAssumedPods()","file":"pkg/scheduler/internal/cache/cache.go","code":"func (cache *cacheImpl) cleanupExpiredAssumedPods() {\n\tcache.cleanupAssumedPods(time.Now())\n}","line":{"from":739,"to":741}} {"id":100011242,"name":"cleanupAssumedPods","signature":"func (cache *cacheImpl) cleanupAssumedPods(now time.Time)","file":"pkg/scheduler/internal/cache/cache.go","code":"// cleanupAssumedPods exists for making test deterministic by taking time as input argument.\n// It also reports metrics on the cache size for nodes, pods, and assumed pods.\nfunc (cache *cacheImpl) cleanupAssumedPods(now time.Time) {\n\tcache.mu.Lock()\n\tdefer cache.mu.Unlock()\n\tdefer cache.updateMetrics()\n\n\t// The size of assumedPods should be small\n\tfor key := range cache.assumedPods {\n\t\tps, ok := cache.podStates[key]\n\t\tif !ok {\n\t\t\tklog.ErrorS(nil, \"Key found in assumed set but not in podStates, potentially a logical error\")\n\t\t\tklog.FlushAndExit(klog.ExitFlushTimeout, 1)\n\t\t}\n\t\tif !ps.bindingFinished {\n\t\t\tklog.V(5).InfoS(\"Could not expire cache for pod as binding is still in progress\", \"podKey\", key, \"pod\", klog.KObj(ps.pod))\n\t\t\tcontinue\n\t\t}\n\t\tif cache.ttl != 0 \u0026\u0026 now.After(*ps.deadline) {\n\t\t\tklog.InfoS(\"Pod expired\", \"podKey\", key, \"pod\", klog.KObj(ps.pod))\n\t\t\tif err := cache.removePod(ps.pod); err != nil {\n\t\t\t\tklog.ErrorS(err, \"ExpirePod failed\", \"podKey\", key, \"pod\", klog.KObj(ps.pod))\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":743,"to":768}} {"id":100011243,"name":"updateMetrics","signature":"func (cache *cacheImpl) updateMetrics()","file":"pkg/scheduler/internal/cache/cache.go","code":"// updateMetrics updates cache size metric values for pods, assumed pods, and nodes\nfunc (cache *cacheImpl) updateMetrics() {\n\tmetrics.CacheSize.WithLabelValues(\"assumed_pods\").Set(float64(len(cache.assumedPods)))\n\tmetrics.CacheSize.WithLabelValues(\"pods\").Set(float64(len(cache.podStates)))\n\tmetrics.CacheSize.WithLabelValues(\"nodes\").Set(float64(len(cache.nodes)))\n}","line":{"from":770,"to":775}} {"id":100011244,"name":"Compare","signature":"func (c *CacheComparer) Compare() error","file":"pkg/scheduler/internal/cache/debugger/comparer.go","code":"// Compare compares the nodes and pods of NodeLister with Cache.Snapshot.\nfunc (c *CacheComparer) Compare() error {\n\tklog.V(3).InfoS(\"Cache comparer started\")\n\tdefer klog.V(3).InfoS(\"Cache comparer finished\")\n\n\tnodes, err := c.NodeLister.List(labels.Everything())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpods, err := c.PodLister.List(labels.Everything())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdump := c.Cache.Dump()\n\n\tpendingPods, _ := c.PodQueue.PendingPods()\n\n\tif missed, redundant := c.CompareNodes(nodes, dump.Nodes); len(missed)+len(redundant) != 0 {\n\t\tklog.InfoS(\"Cache mismatch\", \"missedNodes\", missed, \"redundantNodes\", redundant)\n\t}\n\n\tif missed, redundant := c.ComparePods(pods, pendingPods, dump.Nodes); len(missed)+len(redundant) != 0 {\n\t\tklog.InfoS(\"Cache mismatch\", \"missedPods\", missed, \"redundantPods\", redundant)\n\t}\n\n\treturn nil\n}","line":{"from":40,"to":68}} {"id":100011245,"name":"CompareNodes","signature":"func (c *CacheComparer) CompareNodes(nodes []*v1.Node, nodeinfos map[string]*framework.NodeInfo) (missed, redundant []string)","file":"pkg/scheduler/internal/cache/debugger/comparer.go","code":"// CompareNodes compares actual nodes with cached nodes.\nfunc (c *CacheComparer) CompareNodes(nodes []*v1.Node, nodeinfos map[string]*framework.NodeInfo) (missed, redundant []string) {\n\tactual := []string{}\n\tfor _, node := range nodes {\n\t\tactual = append(actual, node.Name)\n\t}\n\n\tcached := []string{}\n\tfor nodeName := range nodeinfos {\n\t\tcached = append(cached, nodeName)\n\t}\n\n\treturn compareStrings(actual, cached)\n}","line":{"from":70,"to":83}} {"id":100011246,"name":"ComparePods","signature":"func (c *CacheComparer) ComparePods(pods, waitingPods []*v1.Pod, nodeinfos map[string]*framework.NodeInfo) (missed, redundant []string)","file":"pkg/scheduler/internal/cache/debugger/comparer.go","code":"// ComparePods compares actual pods with cached pods.\nfunc (c *CacheComparer) ComparePods(pods, waitingPods []*v1.Pod, nodeinfos map[string]*framework.NodeInfo) (missed, redundant []string) {\n\tactual := []string{}\n\tfor _, pod := range pods {\n\t\tactual = append(actual, string(pod.UID))\n\t}\n\n\tcached := []string{}\n\tfor _, nodeinfo := range nodeinfos {\n\t\tfor _, p := range nodeinfo.Pods {\n\t\t\tcached = append(cached, string(p.Pod.UID))\n\t\t}\n\t}\n\tfor _, pod := range waitingPods {\n\t\tcached = append(cached, string(pod.UID))\n\t}\n\n\treturn compareStrings(actual, cached)\n}","line":{"from":85,"to":103}} {"id":100011247,"name":"compareStrings","signature":"func compareStrings(actual, cached []string) (missed, redundant []string)","file":"pkg/scheduler/internal/cache/debugger/comparer.go","code":"func compareStrings(actual, cached []string) (missed, redundant []string) {\n\tmissed, redundant = []string{}, []string{}\n\n\tsort.Strings(actual)\n\tsort.Strings(cached)\n\n\tcompare := func(i, j int) int {\n\t\tif i == len(actual) {\n\t\t\treturn 1\n\t\t} else if j == len(cached) {\n\t\t\treturn -1\n\t\t}\n\t\treturn strings.Compare(actual[i], cached[j])\n\t}\n\n\tfor i, j := 0, 0; i \u003c len(actual) || j \u003c len(cached); {\n\t\tswitch compare(i, j) {\n\t\tcase 0:\n\t\t\ti++\n\t\t\tj++\n\t\tcase -1:\n\t\t\tmissed = append(missed, actual[i])\n\t\t\ti++\n\t\tcase 1:\n\t\t\tredundant = append(redundant, cached[j])\n\t\t\tj++\n\t\t}\n\t}\n\n\treturn\n}","line":{"from":105,"to":135}} {"id":100011248,"name":"New","signature":"func New(","file":"pkg/scheduler/internal/cache/debugger/debugger.go","code":"// New creates a CacheDebugger.\nfunc New(\n\tnodeLister corelisters.NodeLister,\n\tpodLister corelisters.PodLister,\n\tcache internalcache.Cache,\n\tpodQueue internalqueue.SchedulingQueue,\n) *CacheDebugger {\n\treturn \u0026CacheDebugger{\n\t\tComparer: CacheComparer{\n\t\t\tNodeLister: nodeLister,\n\t\t\tPodLister: podLister,\n\t\t\tCache: cache,\n\t\t\tPodQueue: podQueue,\n\t\t},\n\t\tDumper: CacheDumper{\n\t\t\tcache: cache,\n\t\t\tpodQueue: podQueue,\n\t\t},\n\t}\n}","line":{"from":34,"to":53}} {"id":100011249,"name":"ListenForSignal","signature":"func (d *CacheDebugger) ListenForSignal(stopCh \u003c-chan struct{})","file":"pkg/scheduler/internal/cache/debugger/debugger.go","code":"// ListenForSignal starts a goroutine that will trigger the CacheDebugger's\n// behavior when the process receives SIGINT (Windows) or SIGUSER2 (non-Windows).\nfunc (d *CacheDebugger) ListenForSignal(stopCh \u003c-chan struct{}) {\n\tch := make(chan os.Signal, 1)\n\tsignal.Notify(ch, compareSignal)\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase \u003c-stopCh:\n\t\t\t\treturn\n\t\t\tcase \u003c-ch:\n\t\t\t\td.Comparer.Compare()\n\t\t\t\td.Dumper.DumpAll()\n\t\t\t}\n\t\t}\n\t}()\n}","line":{"from":55,"to":72}} {"id":100011250,"name":"DumpAll","signature":"func (d *CacheDumper) DumpAll()","file":"pkg/scheduler/internal/cache/debugger/dumper.go","code":"// DumpAll writes cached nodes and scheduling queue information to the scheduler logs.\nfunc (d *CacheDumper) DumpAll() {\n\td.dumpNodes()\n\td.dumpSchedulingQueue()\n}","line":{"from":38,"to":42}} {"id":100011251,"name":"dumpNodes","signature":"func (d *CacheDumper) dumpNodes()","file":"pkg/scheduler/internal/cache/debugger/dumper.go","code":"// dumpNodes writes NodeInfo to the scheduler logs.\nfunc (d *CacheDumper) dumpNodes() {\n\tdump := d.cache.Dump()\n\tnodeInfos := make([]string, 0, len(dump.Nodes))\n\tfor name, nodeInfo := range dump.Nodes {\n\t\tnodeInfos = append(nodeInfos, d.printNodeInfo(name, nodeInfo))\n\t}\n\t// Extra blank line added between node entries for readability.\n\tklog.InfoS(\"Dump of cached NodeInfo\", \"nodes\", strings.Join(nodeInfos, \"\\n\\n\"))\n}","line":{"from":44,"to":53}} {"id":100011252,"name":"dumpSchedulingQueue","signature":"func (d *CacheDumper) dumpSchedulingQueue()","file":"pkg/scheduler/internal/cache/debugger/dumper.go","code":"// dumpSchedulingQueue writes pods in the scheduling queue to the scheduler logs.\nfunc (d *CacheDumper) dumpSchedulingQueue() {\n\tpendingPods, s := d.podQueue.PendingPods()\n\tvar podData strings.Builder\n\tfor _, p := range pendingPods {\n\t\tpodData.WriteString(printPod(p))\n\t}\n\tklog.InfoS(\"Dump of scheduling queue\", \"summary\", s, \"pods\", podData.String())\n}","line":{"from":55,"to":63}} {"id":100011253,"name":"printNodeInfo","signature":"func (d *CacheDumper) printNodeInfo(name string, n *framework.NodeInfo) string","file":"pkg/scheduler/internal/cache/debugger/dumper.go","code":"// printNodeInfo writes parts of NodeInfo to a string.\nfunc (d *CacheDumper) printNodeInfo(name string, n *framework.NodeInfo) string {\n\tvar nodeData strings.Builder\n\tnodeData.WriteString(fmt.Sprintf(\"Node name: %s\\nDeleted: %t\\nRequested Resources: %+v\\nAllocatable Resources:%+v\\nScheduled Pods(number: %v):\\n\",\n\t\tname, n.Node() == nil, n.Requested, n.Allocatable, len(n.Pods)))\n\t// Dumping Pod Info\n\tfor _, p := range n.Pods {\n\t\tnodeData.WriteString(printPod(p.Pod))\n\t}\n\t// Dumping nominated pods info on the node\n\tnominatedPodInfos := d.podQueue.NominatedPodsForNode(name)\n\tif len(nominatedPodInfos) != 0 {\n\t\tnodeData.WriteString(fmt.Sprintf(\"Nominated Pods(number: %v):\\n\", len(nominatedPodInfos)))\n\t\tfor _, pi := range nominatedPodInfos {\n\t\t\tnodeData.WriteString(printPod(pi.Pod))\n\t\t}\n\t}\n\treturn nodeData.String()\n}","line":{"from":65,"to":83}} {"id":100011254,"name":"printPod","signature":"func printPod(p *v1.Pod) string","file":"pkg/scheduler/internal/cache/debugger/dumper.go","code":"// printPod writes parts of a Pod object to a string.\nfunc printPod(p *v1.Pod) string {\n\treturn fmt.Sprintf(\"name: %v, namespace: %v, uid: %v, phase: %v, nominated node: %v\\n\", p.Name, p.Namespace, p.UID, p.Status.Phase, p.Status.NominatedNodeName)\n}","line":{"from":85,"to":88}} {"id":100011255,"name":"newNodeTree","signature":"func newNodeTree(nodes []*v1.Node) *nodeTree","file":"pkg/scheduler/internal/cache/node_tree.go","code":"// newNodeTree creates a NodeTree from nodes.\nfunc newNodeTree(nodes []*v1.Node) *nodeTree {\n\tnt := \u0026nodeTree{\n\t\ttree: make(map[string][]string, len(nodes)),\n\t}\n\tfor _, n := range nodes {\n\t\tnt.addNode(n)\n\t}\n\treturn nt\n}","line":{"from":38,"to":47}} {"id":100011256,"name":"addNode","signature":"func (nt *nodeTree) addNode(n *v1.Node)","file":"pkg/scheduler/internal/cache/node_tree.go","code":"// addNode adds a node and its corresponding zone to the tree. If the zone already exists, the node\n// is added to the array of nodes in that zone.\nfunc (nt *nodeTree) addNode(n *v1.Node) {\n\tzone := utilnode.GetZoneKey(n)\n\tif na, ok := nt.tree[zone]; ok {\n\t\tfor _, nodeName := range na {\n\t\t\tif nodeName == n.Name {\n\t\t\t\tklog.InfoS(\"Node already exists in the NodeTree\", \"node\", klog.KObj(n))\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tnt.tree[zone] = append(na, n.Name)\n\t} else {\n\t\tnt.zones = append(nt.zones, zone)\n\t\tnt.tree[zone] = []string{n.Name}\n\t}\n\tklog.V(2).InfoS(\"Added node in listed group to NodeTree\", \"node\", klog.KObj(n), \"zone\", zone)\n\tnt.numNodes++\n}","line":{"from":49,"to":67}} {"id":100011257,"name":"removeNode","signature":"func (nt *nodeTree) removeNode(n *v1.Node) error","file":"pkg/scheduler/internal/cache/node_tree.go","code":"// removeNode removes a node from the NodeTree.\nfunc (nt *nodeTree) removeNode(n *v1.Node) error {\n\tzone := utilnode.GetZoneKey(n)\n\tif na, ok := nt.tree[zone]; ok {\n\t\tfor i, nodeName := range na {\n\t\t\tif nodeName == n.Name {\n\t\t\t\tnt.tree[zone] = append(na[:i], na[i+1:]...)\n\t\t\t\tif len(nt.tree[zone]) == 0 {\n\t\t\t\t\tnt.removeZone(zone)\n\t\t\t\t}\n\t\t\t\tklog.V(2).InfoS(\"Removed node in listed group from NodeTree\", \"node\", klog.KObj(n), \"zone\", zone)\n\t\t\t\tnt.numNodes--\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\tklog.ErrorS(nil, \"Node in listed group was not found\", \"node\", klog.KObj(n), \"zone\", zone)\n\treturn fmt.Errorf(\"node %q in group %q was not found\", n.Name, zone)\n}","line":{"from":69,"to":87}} {"id":100011258,"name":"removeZone","signature":"func (nt *nodeTree) removeZone(zone string)","file":"pkg/scheduler/internal/cache/node_tree.go","code":"// removeZone removes a zone from tree.\n// This function must be called while writer locks are hold.\nfunc (nt *nodeTree) removeZone(zone string) {\n\tdelete(nt.tree, zone)\n\tfor i, z := range nt.zones {\n\t\tif z == zone {\n\t\t\tnt.zones = append(nt.zones[:i], nt.zones[i+1:]...)\n\t\t\treturn\n\t\t}\n\t}\n}","line":{"from":89,"to":99}} {"id":100011259,"name":"updateNode","signature":"func (nt *nodeTree) updateNode(old, new *v1.Node)","file":"pkg/scheduler/internal/cache/node_tree.go","code":"// updateNode updates a node in the NodeTree.\nfunc (nt *nodeTree) updateNode(old, new *v1.Node) {\n\tvar oldZone string\n\tif old != nil {\n\t\toldZone = utilnode.GetZoneKey(old)\n\t}\n\tnewZone := utilnode.GetZoneKey(new)\n\t// If the zone ID of the node has not changed, we don't need to do anything. Name of the node\n\t// cannot be changed in an update.\n\tif oldZone == newZone {\n\t\treturn\n\t}\n\tnt.removeNode(old) // No error checking. We ignore whether the old node exists or not.\n\tnt.addNode(new)\n}","line":{"from":101,"to":115}} {"id":100011260,"name":"list","signature":"func (nt *nodeTree) list() ([]string, error)","file":"pkg/scheduler/internal/cache/node_tree.go","code":"// list returns the list of names of the node. NodeTree iterates over zones and in each zone iterates\n// over nodes in a round robin fashion.\nfunc (nt *nodeTree) list() ([]string, error) {\n\tif len(nt.zones) == 0 {\n\t\treturn nil, nil\n\t}\n\tnodesList := make([]string, 0, nt.numNodes)\n\tnumExhaustedZones := 0\n\tnodeIndex := 0\n\tfor len(nodesList) \u003c nt.numNodes {\n\t\tif numExhaustedZones \u003e= len(nt.zones) { // all zones are exhausted.\n\t\t\treturn nodesList, errors.New(\"all zones exhausted before reaching count of nodes expected\")\n\t\t}\n\t\tfor zoneIndex := 0; zoneIndex \u003c len(nt.zones); zoneIndex++ {\n\t\t\tna := nt.tree[nt.zones[zoneIndex]]\n\t\t\tif nodeIndex \u003e= len(na) { // If the zone is exhausted, continue\n\t\t\t\tif nodeIndex == len(na) { // If it is the first time the zone is exhausted\n\t\t\t\t\tnumExhaustedZones++\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnodesList = append(nodesList, na[nodeIndex])\n\t\t}\n\t\tnodeIndex++\n\t}\n\treturn nodesList, nil\n}","line":{"from":117,"to":143}} {"id":100011261,"name":"NewEmptySnapshot","signature":"func NewEmptySnapshot() *Snapshot","file":"pkg/scheduler/internal/cache/snapshot.go","code":"// NewEmptySnapshot initializes a Snapshot struct and returns it.\nfunc NewEmptySnapshot() *Snapshot {\n\treturn \u0026Snapshot{\n\t\tnodeInfoMap: make(map[string]*framework.NodeInfo),\n\t\tusedPVCSet: sets.NewString(),\n\t}\n}","line":{"from":47,"to":53}} {"id":100011262,"name":"NewSnapshot","signature":"func NewSnapshot(pods []*v1.Pod, nodes []*v1.Node) *Snapshot","file":"pkg/scheduler/internal/cache/snapshot.go","code":"// NewSnapshot initializes a Snapshot struct and returns it.\nfunc NewSnapshot(pods []*v1.Pod, nodes []*v1.Node) *Snapshot {\n\tnodeInfoMap := createNodeInfoMap(pods, nodes)\n\tnodeInfoList := make([]*framework.NodeInfo, 0, len(nodeInfoMap))\n\thavePodsWithAffinityNodeInfoList := make([]*framework.NodeInfo, 0, len(nodeInfoMap))\n\thavePodsWithRequiredAntiAffinityNodeInfoList := make([]*framework.NodeInfo, 0, len(nodeInfoMap))\n\tfor _, v := range nodeInfoMap {\n\t\tnodeInfoList = append(nodeInfoList, v)\n\t\tif len(v.PodsWithAffinity) \u003e 0 {\n\t\t\thavePodsWithAffinityNodeInfoList = append(havePodsWithAffinityNodeInfoList, v)\n\t\t}\n\t\tif len(v.PodsWithRequiredAntiAffinity) \u003e 0 {\n\t\t\thavePodsWithRequiredAntiAffinityNodeInfoList = append(havePodsWithRequiredAntiAffinityNodeInfoList, v)\n\t\t}\n\t}\n\n\ts := NewEmptySnapshot()\n\ts.nodeInfoMap = nodeInfoMap\n\ts.nodeInfoList = nodeInfoList\n\ts.havePodsWithAffinityNodeInfoList = havePodsWithAffinityNodeInfoList\n\ts.havePodsWithRequiredAntiAffinityNodeInfoList = havePodsWithRequiredAntiAffinityNodeInfoList\n\ts.usedPVCSet = createUsedPVCSet(pods)\n\n\treturn s\n}","line":{"from":55,"to":79}} {"id":100011263,"name":"createNodeInfoMap","signature":"func createNodeInfoMap(pods []*v1.Pod, nodes []*v1.Node) map[string]*framework.NodeInfo","file":"pkg/scheduler/internal/cache/snapshot.go","code":"// createNodeInfoMap obtains a list of pods and pivots that list into a map\n// where the keys are node names and the values are the aggregated information\n// for that node.\nfunc createNodeInfoMap(pods []*v1.Pod, nodes []*v1.Node) map[string]*framework.NodeInfo {\n\tnodeNameToInfo := make(map[string]*framework.NodeInfo)\n\tfor _, pod := range pods {\n\t\tnodeName := pod.Spec.NodeName\n\t\tif _, ok := nodeNameToInfo[nodeName]; !ok {\n\t\t\tnodeNameToInfo[nodeName] = framework.NewNodeInfo()\n\t\t}\n\t\tnodeNameToInfo[nodeName].AddPod(pod)\n\t}\n\timageExistenceMap := createImageExistenceMap(nodes)\n\n\tfor _, node := range nodes {\n\t\tif _, ok := nodeNameToInfo[node.Name]; !ok {\n\t\t\tnodeNameToInfo[node.Name] = framework.NewNodeInfo()\n\t\t}\n\t\tnodeInfo := nodeNameToInfo[node.Name]\n\t\tnodeInfo.SetNode(node)\n\t\tnodeInfo.ImageStates = getNodeImageStates(node, imageExistenceMap)\n\t}\n\treturn nodeNameToInfo\n}","line":{"from":81,"to":104}} {"id":100011264,"name":"createUsedPVCSet","signature":"func createUsedPVCSet(pods []*v1.Pod) sets.String","file":"pkg/scheduler/internal/cache/snapshot.go","code":"func createUsedPVCSet(pods []*v1.Pod) sets.String {\n\tusedPVCSet := sets.NewString()\n\tfor _, pod := range pods {\n\t\tif pod.Spec.NodeName == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, v := range pod.Spec.Volumes {\n\t\t\tif v.PersistentVolumeClaim == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tkey := framework.GetNamespacedName(pod.Namespace, v.PersistentVolumeClaim.ClaimName)\n\t\t\tusedPVCSet.Insert(key)\n\t\t}\n\t}\n\treturn usedPVCSet\n}","line":{"from":106,"to":123}} {"id":100011265,"name":"getNodeImageStates","signature":"func getNodeImageStates(node *v1.Node, imageExistenceMap map[string]sets.String) map[string]*framework.ImageStateSummary","file":"pkg/scheduler/internal/cache/snapshot.go","code":"// getNodeImageStates returns the given node's image states based on the given imageExistence map.\nfunc getNodeImageStates(node *v1.Node, imageExistenceMap map[string]sets.String) map[string]*framework.ImageStateSummary {\n\timageStates := make(map[string]*framework.ImageStateSummary)\n\n\tfor _, image := range node.Status.Images {\n\t\tfor _, name := range image.Names {\n\t\t\timageStates[name] = \u0026framework.ImageStateSummary{\n\t\t\t\tSize: image.SizeBytes,\n\t\t\t\tNumNodes: len(imageExistenceMap[name]),\n\t\t\t}\n\t\t}\n\t}\n\treturn imageStates\n}","line":{"from":125,"to":138}} {"id":100011266,"name":"createImageExistenceMap","signature":"func createImageExistenceMap(nodes []*v1.Node) map[string]sets.String","file":"pkg/scheduler/internal/cache/snapshot.go","code":"// createImageExistenceMap returns a map recording on which nodes the images exist, keyed by the images' names.\nfunc createImageExistenceMap(nodes []*v1.Node) map[string]sets.String {\n\timageExistenceMap := make(map[string]sets.String)\n\tfor _, node := range nodes {\n\t\tfor _, image := range node.Status.Images {\n\t\t\tfor _, name := range image.Names {\n\t\t\t\tif _, ok := imageExistenceMap[name]; !ok {\n\t\t\t\t\timageExistenceMap[name] = sets.NewString(node.Name)\n\t\t\t\t} else {\n\t\t\t\t\timageExistenceMap[name].Insert(node.Name)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn imageExistenceMap\n}","line":{"from":140,"to":155}} {"id":100011267,"name":"NodeInfos","signature":"func (s *Snapshot) NodeInfos() framework.NodeInfoLister","file":"pkg/scheduler/internal/cache/snapshot.go","code":"// NodeInfos returns a NodeInfoLister.\nfunc (s *Snapshot) NodeInfos() framework.NodeInfoLister {\n\treturn s\n}","line":{"from":157,"to":160}} {"id":100011268,"name":"StorageInfos","signature":"func (s *Snapshot) StorageInfos() framework.StorageInfoLister","file":"pkg/scheduler/internal/cache/snapshot.go","code":"// StorageInfos returns a StorageInfoLister.\nfunc (s *Snapshot) StorageInfos() framework.StorageInfoLister {\n\treturn s\n}","line":{"from":162,"to":165}} {"id":100011269,"name":"NumNodes","signature":"func (s *Snapshot) NumNodes() int","file":"pkg/scheduler/internal/cache/snapshot.go","code":"// NumNodes returns the number of nodes in the snapshot.\nfunc (s *Snapshot) NumNodes() int {\n\treturn len(s.nodeInfoList)\n}","line":{"from":167,"to":170}} {"id":100011270,"name":"List","signature":"func (s *Snapshot) List() ([]*framework.NodeInfo, error)","file":"pkg/scheduler/internal/cache/snapshot.go","code":"// List returns the list of nodes in the snapshot.\nfunc (s *Snapshot) List() ([]*framework.NodeInfo, error) {\n\treturn s.nodeInfoList, nil\n}","line":{"from":172,"to":175}} {"id":100011271,"name":"HavePodsWithAffinityList","signature":"func (s *Snapshot) HavePodsWithAffinityList() ([]*framework.NodeInfo, error)","file":"pkg/scheduler/internal/cache/snapshot.go","code":"// HavePodsWithAffinityList returns the list of nodes with at least one pod with inter-pod affinity\nfunc (s *Snapshot) HavePodsWithAffinityList() ([]*framework.NodeInfo, error) {\n\treturn s.havePodsWithAffinityNodeInfoList, nil\n}","line":{"from":177,"to":180}} {"id":100011272,"name":"HavePodsWithRequiredAntiAffinityList","signature":"func (s *Snapshot) HavePodsWithRequiredAntiAffinityList() ([]*framework.NodeInfo, error)","file":"pkg/scheduler/internal/cache/snapshot.go","code":"// HavePodsWithRequiredAntiAffinityList returns the list of nodes with at least one pod with\n// required inter-pod anti-affinity\nfunc (s *Snapshot) HavePodsWithRequiredAntiAffinityList() ([]*framework.NodeInfo, error) {\n\treturn s.havePodsWithRequiredAntiAffinityNodeInfoList, nil\n}","line":{"from":182,"to":186}} {"id":100011273,"name":"Get","signature":"func (s *Snapshot) Get(nodeName string) (*framework.NodeInfo, error)","file":"pkg/scheduler/internal/cache/snapshot.go","code":"// Get returns the NodeInfo of the given node name.\nfunc (s *Snapshot) Get(nodeName string) (*framework.NodeInfo, error) {\n\tif v, ok := s.nodeInfoMap[nodeName]; ok \u0026\u0026 v.Node() != nil {\n\t\treturn v, nil\n\t}\n\treturn nil, fmt.Errorf(\"nodeinfo not found for node name %q\", nodeName)\n}","line":{"from":188,"to":194}} {"id":100011274,"name":"IsPVCUsedByPods","signature":"func (s *Snapshot) IsPVCUsedByPods(key string) bool","file":"pkg/scheduler/internal/cache/snapshot.go","code":"func (s *Snapshot) IsPVCUsedByPods(key string) bool {\n\treturn s.usedPVCSet.Has(key)\n}","line":{"from":196,"to":198}} {"id":100011275,"name":"Less","signature":"func (h *data) Less(i, j int) bool","file":"pkg/scheduler/internal/heap/heap.go","code":"// Less compares two objects and returns true if the first one should go\n// in front of the second one in the heap.\nfunc (h *data) Less(i, j int) bool {\n\tif i \u003e len(h.queue) || j \u003e len(h.queue) {\n\t\treturn false\n\t}\n\titemi, ok := h.items[h.queue[i]]\n\tif !ok {\n\t\treturn false\n\t}\n\titemj, ok := h.items[h.queue[j]]\n\tif !ok {\n\t\treturn false\n\t}\n\treturn h.lessFunc(itemi.obj, itemj.obj)\n}","line":{"from":66,"to":81}} {"id":100011276,"name":"Len","signature":"func (h *data) Len() int { return len(h.queue) }","file":"pkg/scheduler/internal/heap/heap.go","code":"// Len returns the number of items in the Heap.\nfunc (h *data) Len() int { return len(h.queue) }","line":{"from":83,"to":84}} {"id":100011277,"name":"Swap","signature":"func (h *data) Swap(i, j int)","file":"pkg/scheduler/internal/heap/heap.go","code":"// Swap implements swapping of two elements in the heap. This is a part of standard\n// heap interface and should never be called directly.\nfunc (h *data) Swap(i, j int) {\n\th.queue[i], h.queue[j] = h.queue[j], h.queue[i]\n\titem := h.items[h.queue[i]]\n\titem.index = i\n\titem = h.items[h.queue[j]]\n\titem.index = j\n}","line":{"from":86,"to":94}} {"id":100011278,"name":"Push","signature":"func (h *data) Push(kv interface{})","file":"pkg/scheduler/internal/heap/heap.go","code":"// Push is supposed to be called by heap.Push only.\nfunc (h *data) Push(kv interface{}) {\n\tkeyValue := kv.(*itemKeyValue)\n\tn := len(h.queue)\n\th.items[keyValue.key] = \u0026heapItem{keyValue.obj, n}\n\th.queue = append(h.queue, keyValue.key)\n}","line":{"from":96,"to":102}} {"id":100011279,"name":"Pop","signature":"func (h *data) Pop() interface{}","file":"pkg/scheduler/internal/heap/heap.go","code":"// Pop is supposed to be called by heap.Pop only.\nfunc (h *data) Pop() interface{} {\n\tkey := h.queue[len(h.queue)-1]\n\th.queue = h.queue[0 : len(h.queue)-1]\n\titem, ok := h.items[key]\n\tif !ok {\n\t\t// This is an error\n\t\treturn nil\n\t}\n\tdelete(h.items, key)\n\treturn item.obj\n}","line":{"from":104,"to":115}} {"id":100011280,"name":"Peek","signature":"func (h *data) Peek() interface{}","file":"pkg/scheduler/internal/heap/heap.go","code":"// Peek is supposed to be called by heap.Peek only.\nfunc (h *data) Peek() interface{} {\n\tif len(h.queue) \u003e 0 {\n\t\treturn h.items[h.queue[0]].obj\n\t}\n\treturn nil\n}","line":{"from":117,"to":123}} {"id":100011281,"name":"Add","signature":"func (h *Heap) Add(obj interface{}) error","file":"pkg/scheduler/internal/heap/heap.go","code":"// Add inserts an item, and puts it in the queue. The item is updated if it\n// already exists.\nfunc (h *Heap) Add(obj interface{}) error {\n\tkey, err := h.data.keyFunc(obj)\n\tif err != nil {\n\t\treturn cache.KeyError{Obj: obj, Err: err}\n\t}\n\tif _, exists := h.data.items[key]; exists {\n\t\th.data.items[key].obj = obj\n\t\theap.Fix(h.data, h.data.items[key].index)\n\t} else {\n\t\theap.Push(h.data, \u0026itemKeyValue{key, obj})\n\t\tif h.metricRecorder != nil {\n\t\t\th.metricRecorder.Inc()\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":136,"to":153}} {"id":100011282,"name":"Update","signature":"func (h *Heap) Update(obj interface{}) error","file":"pkg/scheduler/internal/heap/heap.go","code":"// Update is the same as Add in this implementation. When the item does not\n// exist, it is added.\nfunc (h *Heap) Update(obj interface{}) error {\n\treturn h.Add(obj)\n}","line":{"from":155,"to":159}} {"id":100011283,"name":"Delete","signature":"func (h *Heap) Delete(obj interface{}) error","file":"pkg/scheduler/internal/heap/heap.go","code":"// Delete removes an item.\nfunc (h *Heap) Delete(obj interface{}) error {\n\tkey, err := h.data.keyFunc(obj)\n\tif err != nil {\n\t\treturn cache.KeyError{Obj: obj, Err: err}\n\t}\n\tif item, ok := h.data.items[key]; ok {\n\t\theap.Remove(h.data, item.index)\n\t\tif h.metricRecorder != nil {\n\t\t\th.metricRecorder.Dec()\n\t\t}\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"object not found\")\n}","line":{"from":161,"to":175}} {"id":100011284,"name":"Peek","signature":"func (h *Heap) Peek() interface{}","file":"pkg/scheduler/internal/heap/heap.go","code":"// Peek returns the head of the heap without removing it.\nfunc (h *Heap) Peek() interface{} {\n\treturn h.data.Peek()\n}","line":{"from":177,"to":180}} {"id":100011285,"name":"Pop","signature":"func (h *Heap) Pop() (interface{}, error)","file":"pkg/scheduler/internal/heap/heap.go","code":"// Pop returns the head of the heap and removes it.\nfunc (h *Heap) Pop() (interface{}, error) {\n\tobj := heap.Pop(h.data)\n\tif obj != nil {\n\t\tif h.metricRecorder != nil {\n\t\t\th.metricRecorder.Dec()\n\t\t}\n\t\treturn obj, nil\n\t}\n\treturn nil, fmt.Errorf(\"object was removed from heap data\")\n}","line":{"from":182,"to":192}} {"id":100011286,"name":"Get","signature":"func (h *Heap) Get(obj interface{}) (interface{}, bool, error)","file":"pkg/scheduler/internal/heap/heap.go","code":"// Get returns the requested item, or sets exists=false.\nfunc (h *Heap) Get(obj interface{}) (interface{}, bool, error) {\n\tkey, err := h.data.keyFunc(obj)\n\tif err != nil {\n\t\treturn nil, false, cache.KeyError{Obj: obj, Err: err}\n\t}\n\treturn h.GetByKey(key)\n}","line":{"from":194,"to":201}} {"id":100011287,"name":"GetByKey","signature":"func (h *Heap) GetByKey(key string) (interface{}, bool, error)","file":"pkg/scheduler/internal/heap/heap.go","code":"// GetByKey returns the requested item, or sets exists=false.\nfunc (h *Heap) GetByKey(key string) (interface{}, bool, error) {\n\titem, exists := h.data.items[key]\n\tif !exists {\n\t\treturn nil, false, nil\n\t}\n\treturn item.obj, true, nil\n}","line":{"from":203,"to":210}} {"id":100011288,"name":"List","signature":"func (h *Heap) List() []interface{}","file":"pkg/scheduler/internal/heap/heap.go","code":"// List returns a list of all the items.\nfunc (h *Heap) List() []interface{} {\n\tlist := make([]interface{}, 0, len(h.data.items))\n\tfor _, item := range h.data.items {\n\t\tlist = append(list, item.obj)\n\t}\n\treturn list\n}","line":{"from":212,"to":219}} {"id":100011289,"name":"Len","signature":"func (h *Heap) Len() int","file":"pkg/scheduler/internal/heap/heap.go","code":"// Len returns the number of items in the heap.\nfunc (h *Heap) Len() int {\n\treturn len(h.data.queue)\n}","line":{"from":221,"to":224}} {"id":100011290,"name":"New","signature":"func New(keyFn KeyFunc, lessFn lessFunc) *Heap","file":"pkg/scheduler/internal/heap/heap.go","code":"// New returns a Heap which can be used to queue up items to process.\nfunc New(keyFn KeyFunc, lessFn lessFunc) *Heap {\n\treturn NewWithRecorder(keyFn, lessFn, nil)\n}","line":{"from":226,"to":229}} {"id":100011291,"name":"NewWithRecorder","signature":"func NewWithRecorder(keyFn KeyFunc, lessFn lessFunc, metricRecorder metrics.MetricRecorder) *Heap","file":"pkg/scheduler/internal/heap/heap.go","code":"// NewWithRecorder wraps an optional metricRecorder to compose a Heap object.\nfunc NewWithRecorder(keyFn KeyFunc, lessFn lessFunc, metricRecorder metrics.MetricRecorder) *Heap {\n\treturn \u0026Heap{\n\t\tdata: \u0026data{\n\t\t\titems: map[string]*heapItem{},\n\t\t\tqueue: []string{},\n\t\t\tkeyFunc: keyFn,\n\t\t\tlessFunc: lessFn,\n\t\t},\n\t\tmetricRecorder: metricRecorder,\n\t}\n}","line":{"from":231,"to":242}} {"id":100011292,"name":"NewSchedulingQueue","signature":"func NewSchedulingQueue(","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// NewSchedulingQueue initializes a priority queue as a new scheduling queue.\nfunc NewSchedulingQueue(\n\tlessFn framework.LessFunc,\n\tinformerFactory informers.SharedInformerFactory,\n\topts ...Option) SchedulingQueue {\n\treturn NewPriorityQueue(lessFn, informerFactory, opts...)\n}","line":{"from":123,"to":129}} {"id":100011293,"name":"NominatedNodeName","signature":"func NominatedNodeName(pod *v1.Pod) string","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// NominatedNodeName returns nominated node name of a Pod.\nfunc NominatedNodeName(pod *v1.Pod) string {\n\treturn pod.Status.NominatedNodeName\n}","line":{"from":131,"to":134}} {"id":100011294,"name":"WithClock","signature":"func WithClock(clock clock.Clock) Option","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// WithClock sets clock for PriorityQueue, the default clock is clock.RealClock.\nfunc WithClock(clock clock.Clock) Option {\n\treturn func(o *priorityQueueOptions) {\n\t\to.clock = clock\n\t}\n}","line":{"from":207,"to":212}} {"id":100011295,"name":"WithPodInitialBackoffDuration","signature":"func WithPodInitialBackoffDuration(duration time.Duration) Option","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// WithPodInitialBackoffDuration sets pod initial backoff duration for PriorityQueue.\nfunc WithPodInitialBackoffDuration(duration time.Duration) Option {\n\treturn func(o *priorityQueueOptions) {\n\t\to.podInitialBackoffDuration = duration\n\t}\n}","line":{"from":214,"to":219}} {"id":100011296,"name":"WithPodMaxBackoffDuration","signature":"func WithPodMaxBackoffDuration(duration time.Duration) Option","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// WithPodMaxBackoffDuration sets pod max backoff duration for PriorityQueue.\nfunc WithPodMaxBackoffDuration(duration time.Duration) Option {\n\treturn func(o *priorityQueueOptions) {\n\t\to.podMaxBackoffDuration = duration\n\t}\n}","line":{"from":221,"to":226}} {"id":100011297,"name":"WithPodLister","signature":"func WithPodLister(pl listersv1.PodLister) Option","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// WithPodLister sets pod lister for PriorityQueue.\nfunc WithPodLister(pl listersv1.PodLister) Option {\n\treturn func(o *priorityQueueOptions) {\n\t\to.podLister = pl\n\t}\n}","line":{"from":228,"to":233}} {"id":100011298,"name":"WithClusterEventMap","signature":"func WithClusterEventMap(m map[framework.ClusterEvent]sets.String) Option","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// WithClusterEventMap sets clusterEventMap for PriorityQueue.\nfunc WithClusterEventMap(m map[framework.ClusterEvent]sets.String) Option {\n\treturn func(o *priorityQueueOptions) {\n\t\to.clusterEventMap = m\n\t}\n}","line":{"from":235,"to":240}} {"id":100011299,"name":"WithPodMaxInUnschedulablePodsDuration","signature":"func WithPodMaxInUnschedulablePodsDuration(duration time.Duration) Option","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// WithPodMaxInUnschedulablePodsDuration sets podMaxInUnschedulablePodsDuration for PriorityQueue.\nfunc WithPodMaxInUnschedulablePodsDuration(duration time.Duration) Option {\n\treturn func(o *priorityQueueOptions) {\n\t\to.podMaxInUnschedulablePodsDuration = duration\n\t}\n}","line":{"from":242,"to":247}} {"id":100011300,"name":"WithPreEnqueuePluginMap","signature":"func WithPreEnqueuePluginMap(m map[string][]framework.PreEnqueuePlugin) Option","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// WithPreEnqueuePluginMap sets preEnqueuePluginMap for PriorityQueue.\nfunc WithPreEnqueuePluginMap(m map[string][]framework.PreEnqueuePlugin) Option {\n\treturn func(o *priorityQueueOptions) {\n\t\to.preEnqueuePluginMap = m\n\t}\n}","line":{"from":249,"to":254}} {"id":100011301,"name":"WithMetricsRecorder","signature":"func WithMetricsRecorder(recorder metrics.MetricAsyncRecorder) Option","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// WithMetricsRecorder sets metrics recorder.\nfunc WithMetricsRecorder(recorder metrics.MetricAsyncRecorder) Option {\n\treturn func(o *priorityQueueOptions) {\n\t\to.metricsRecorder = recorder\n\t}\n}","line":{"from":256,"to":261}} {"id":100011302,"name":"WithPluginMetricsSamplePercent","signature":"func WithPluginMetricsSamplePercent(percent int) Option","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// WithPluginMetricsSamplePercent sets the percentage of plugin metrics to be sampled.\nfunc WithPluginMetricsSamplePercent(percent int) Option {\n\treturn func(o *priorityQueueOptions) {\n\t\to.pluginMetricsSamplePercent = percent\n\t}\n}","line":{"from":263,"to":268}} {"id":100011303,"name":"newQueuedPodInfoForLookup","signature":"func newQueuedPodInfoForLookup(pod *v1.Pod, plugins ...string) *framework.QueuedPodInfo","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// newQueuedPodInfoForLookup builds a QueuedPodInfo object for a lookup in the queue.\nfunc newQueuedPodInfoForLookup(pod *v1.Pod, plugins ...string) *framework.QueuedPodInfo {\n\t// Since this is only used for a lookup in the queue, we only need to set the Pod,\n\t// and so we avoid creating a full PodInfo, which is expensive to instantiate frequently.\n\treturn \u0026framework.QueuedPodInfo{\n\t\tPodInfo: \u0026framework.PodInfo{Pod: pod},\n\t\tUnschedulablePlugins: sets.NewString(plugins...),\n\t}\n}","line":{"from":280,"to":288}} {"id":100011304,"name":"NewPriorityQueue","signature":"func NewPriorityQueue(","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// NewPriorityQueue creates a PriorityQueue object.\nfunc NewPriorityQueue(\n\tlessFn framework.LessFunc,\n\tinformerFactory informers.SharedInformerFactory,\n\topts ...Option,\n) *PriorityQueue {\n\toptions := defaultPriorityQueueOptions\n\tif options.podLister == nil {\n\t\toptions.podLister = informerFactory.Core().V1().Pods().Lister()\n\t}\n\tfor _, opt := range opts {\n\t\topt(\u0026options)\n\t}\n\n\tcomp := func(podInfo1, podInfo2 interface{}) bool {\n\t\tpInfo1 := podInfo1.(*framework.QueuedPodInfo)\n\t\tpInfo2 := podInfo2.(*framework.QueuedPodInfo)\n\t\treturn lessFn(pInfo1, pInfo2)\n\t}\n\n\tpq := \u0026PriorityQueue{\n\t\tnominator: newPodNominator(options.podLister),\n\t\tclock: options.clock,\n\t\tstop: make(chan struct{}),\n\t\tpodInitialBackoffDuration: options.podInitialBackoffDuration,\n\t\tpodMaxBackoffDuration: options.podMaxBackoffDuration,\n\t\tpodMaxInUnschedulablePodsDuration: options.podMaxInUnschedulablePodsDuration,\n\t\tactiveQ: heap.NewWithRecorder(podInfoKeyFunc, comp, metrics.NewActivePodsRecorder()),\n\t\tunschedulablePods: newUnschedulablePods(metrics.NewUnschedulablePodsRecorder(), metrics.NewGatedPodsRecorder()),\n\t\tmoveRequestCycle: -1,\n\t\tclusterEventMap: options.clusterEventMap,\n\t\tpreEnqueuePluginMap: options.preEnqueuePluginMap,\n\t\tmetricsRecorder: options.metricsRecorder,\n\t\tpluginMetricsSamplePercent: options.pluginMetricsSamplePercent,\n\t}\n\tpq.cond.L = \u0026pq.lock\n\tpq.podBackoffQ = heap.NewWithRecorder(podInfoKeyFunc, pq.podsCompareBackoffCompleted, metrics.NewBackoffPodsRecorder())\n\tpq.nsLister = informerFactory.Core().V1().Namespaces().Lister()\n\n\treturn pq\n}","line":{"from":290,"to":330}} {"id":100011305,"name":"Run","signature":"func (p *PriorityQueue) Run()","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// Run starts the goroutine to pump from podBackoffQ to activeQ\nfunc (p *PriorityQueue) Run() {\n\tgo wait.Until(p.flushBackoffQCompleted, 1.0*time.Second, p.stop)\n\tgo wait.Until(p.flushUnschedulablePodsLeftover, 30*time.Second, p.stop)\n}","line":{"from":332,"to":336}} {"id":100011306,"name":"runPreEnqueuePlugins","signature":"func (p *PriorityQueue) runPreEnqueuePlugins(ctx context.Context, pInfo *framework.QueuedPodInfo) bool","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// runPreEnqueuePlugins iterates PreEnqueue function in each registered PreEnqueuePlugin.\n// It returns true if all PreEnqueue function run successfully; otherwise returns false\n// upon the first failure.\n// Note: we need to associate the failed plugin to `pInfo`, so that the pod can be moved back\n// to activeQ by related cluster event.\nfunc (p *PriorityQueue) runPreEnqueuePlugins(ctx context.Context, pInfo *framework.QueuedPodInfo) bool {\n\tvar s *framework.Status\n\tpod := pInfo.Pod\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tmetrics.FrameworkExtensionPointDuration.WithLabelValues(preEnqueue, s.Code().String(), pod.Spec.SchedulerName).Observe(metrics.SinceInSeconds(startTime))\n\t}()\n\n\tshouldRecordMetric := rand.Intn(100) \u003c p.pluginMetricsSamplePercent\n\tfor _, pl := range p.preEnqueuePluginMap[pod.Spec.SchedulerName] {\n\t\ts = p.runPreEnqueuePlugin(ctx, pl, pod, shouldRecordMetric)\n\t\tif s.IsSuccess() {\n\t\t\tcontinue\n\t\t}\n\t\tpInfo.UnschedulablePlugins.Insert(pl.Name())\n\t\tmetrics.UnschedulableReason(pl.Name(), pod.Spec.SchedulerName).Inc()\n\t\tif s.Code() == framework.Error {\n\t\t\tklog.ErrorS(s.AsError(), \"Unexpected error running PreEnqueue plugin\", \"pod\", klog.KObj(pod), \"plugin\", pl.Name())\n\t\t} else {\n\t\t\tklog.V(5).InfoS(\"Status after running PreEnqueue plugin\", \"pod\", klog.KObj(pod), \"plugin\", pl.Name(), \"status\", s)\n\t\t}\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":338,"to":367}} {"id":100011307,"name":"runPreEnqueuePlugin","signature":"func (p *PriorityQueue) runPreEnqueuePlugin(ctx context.Context, pl framework.PreEnqueuePlugin, pod *v1.Pod, shouldRecordMetric bool) *framework.Status","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"func (p *PriorityQueue) runPreEnqueuePlugin(ctx context.Context, pl framework.PreEnqueuePlugin, pod *v1.Pod, shouldRecordMetric bool) *framework.Status {\n\tif !shouldRecordMetric {\n\t\treturn pl.PreEnqueue(ctx, pod)\n\t}\n\tstartTime := p.clock.Now()\n\ts := pl.PreEnqueue(ctx, pod)\n\tp.metricsRecorder.ObservePluginDurationAsync(preEnqueue, pl.Name(), s.Code().String(), p.clock.Since(startTime).Seconds())\n\treturn s\n}","line":{"from":369,"to":377}} {"id":100011308,"name":"addToActiveQ","signature":"func (p *PriorityQueue) addToActiveQ(pInfo *framework.QueuedPodInfo) (bool, error)","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// addToActiveQ tries to add pod to active queue. It returns 2 parameters:\n// 1. a boolean flag to indicate whether the pod is added successfully.\n// 2. an error for the caller to act on.\nfunc (p *PriorityQueue) addToActiveQ(pInfo *framework.QueuedPodInfo) (bool, error) {\n\tpInfo.Gated = !p.runPreEnqueuePlugins(context.Background(), pInfo)\n\tif pInfo.Gated {\n\t\t// Add the Pod to unschedulablePods if it's not passing PreEnqueuePlugins.\n\t\tp.unschedulablePods.addOrUpdate(pInfo)\n\t\treturn false, nil\n\t}\n\tif pInfo.InitialAttemptTimestamp == nil {\n\t\tnow := p.clock.Now()\n\t\tpInfo.InitialAttemptTimestamp = \u0026now\n\t}\n\tif err := p.activeQ.Add(pInfo); err != nil {\n\t\tklog.ErrorS(err, \"Error adding pod to the active queue\", \"pod\", klog.KObj(pInfo.Pod))\n\t\treturn false, err\n\t}\n\treturn true, nil\n}","line":{"from":379,"to":398}} {"id":100011309,"name":"Add","signature":"func (p *PriorityQueue) Add(pod *v1.Pod) error","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// Add adds a pod to the active queue. It should be called only when a new pod\n// is added so there is no chance the pod is already in active/unschedulable/backoff queues\nfunc (p *PriorityQueue) Add(pod *v1.Pod) error {\n\tp.lock.Lock()\n\tdefer p.lock.Unlock()\n\n\tpInfo := p.newQueuedPodInfo(pod)\n\tgated := pInfo.Gated\n\tif added, err := p.addToActiveQ(pInfo); !added {\n\t\treturn err\n\t}\n\tif p.unschedulablePods.get(pod) != nil {\n\t\tklog.ErrorS(nil, \"Error: pod is already in the unschedulable queue\", \"pod\", klog.KObj(pod))\n\t\tp.unschedulablePods.delete(pod, gated)\n\t}\n\t// Delete pod from backoffQ if it is backing off\n\tif err := p.podBackoffQ.Delete(pInfo); err == nil {\n\t\tklog.ErrorS(nil, \"Error: pod is already in the podBackoff queue\", \"pod\", klog.KObj(pod))\n\t}\n\tklog.V(5).InfoS(\"Pod moved to an internal scheduling queue\", \"pod\", klog.KObj(pod), \"event\", PodAdd, \"queue\", activeQName)\n\tmetrics.SchedulerQueueIncomingPods.WithLabelValues(\"active\", PodAdd).Inc()\n\tp.addNominatedPodUnlocked(pInfo.PodInfo, nil)\n\tp.cond.Broadcast()\n\n\treturn nil\n}","line":{"from":400,"to":425}} {"id":100011310,"name":"Activate","signature":"func (p *PriorityQueue) Activate(pods map[string]*v1.Pod)","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// Activate moves the given pods to activeQ iff they're in unschedulablePods or backoffQ.\nfunc (p *PriorityQueue) Activate(pods map[string]*v1.Pod) {\n\tp.lock.Lock()\n\tdefer p.lock.Unlock()\n\n\tactivated := false\n\tfor _, pod := range pods {\n\t\tif p.activate(pod) {\n\t\t\tactivated = true\n\t\t}\n\t}\n\n\tif activated {\n\t\tp.cond.Broadcast()\n\t}\n}","line":{"from":427,"to":442}} {"id":100011311,"name":"activate","signature":"func (p *PriorityQueue) activate(pod *v1.Pod) bool","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"func (p *PriorityQueue) activate(pod *v1.Pod) bool {\n\t// Verify if the pod is present in activeQ.\n\tif _, exists, _ := p.activeQ.Get(newQueuedPodInfoForLookup(pod)); exists {\n\t\t// No need to activate if it's already present in activeQ.\n\t\treturn false\n\t}\n\tvar pInfo *framework.QueuedPodInfo\n\t// Verify if the pod is present in unschedulablePods or backoffQ.\n\tif pInfo = p.unschedulablePods.get(pod); pInfo == nil {\n\t\t// If the pod doesn't belong to unschedulablePods or backoffQ, don't activate it.\n\t\tif obj, exists, _ := p.podBackoffQ.Get(newQueuedPodInfoForLookup(pod)); !exists {\n\t\t\tklog.ErrorS(nil, \"To-activate pod does not exist in unschedulablePods or backoffQ\", \"pod\", klog.KObj(pod))\n\t\t\treturn false\n\t\t} else {\n\t\t\tpInfo = obj.(*framework.QueuedPodInfo)\n\t\t}\n\t}\n\n\tif pInfo == nil {\n\t\t// Redundant safe check. We shouldn't reach here.\n\t\tklog.ErrorS(nil, \"Internal error: cannot obtain pInfo\")\n\t\treturn false\n\t}\n\n\tgated := pInfo.Gated\n\tif added, _ := p.addToActiveQ(pInfo); !added {\n\t\treturn false\n\t}\n\tp.unschedulablePods.delete(pInfo.Pod, gated)\n\tp.podBackoffQ.Delete(pInfo)\n\tmetrics.SchedulerQueueIncomingPods.WithLabelValues(\"active\", ForceActivate).Inc()\n\tp.addNominatedPodUnlocked(pInfo.PodInfo, nil)\n\treturn true\n}","line":{"from":444,"to":477}} {"id":100011312,"name":"isPodBackingoff","signature":"func (p *PriorityQueue) isPodBackingoff(podInfo *framework.QueuedPodInfo) bool","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// isPodBackingoff returns true if a pod is still waiting for its backoff timer.\n// If this returns true, the pod should not be re-tried.\nfunc (p *PriorityQueue) isPodBackingoff(podInfo *framework.QueuedPodInfo) bool {\n\tif podInfo.Gated {\n\t\treturn false\n\t}\n\tboTime := p.getBackoffTime(podInfo)\n\treturn boTime.After(p.clock.Now())\n}","line":{"from":479,"to":487}} {"id":100011313,"name":"SchedulingCycle","signature":"func (p *PriorityQueue) SchedulingCycle() int64","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// SchedulingCycle returns current scheduling cycle.\nfunc (p *PriorityQueue) SchedulingCycle() int64 {\n\tp.lock.RLock()\n\tdefer p.lock.RUnlock()\n\treturn p.schedulingCycle\n}","line":{"from":489,"to":494}} {"id":100011314,"name":"AddUnschedulableIfNotPresent","signature":"func (p *PriorityQueue) AddUnschedulableIfNotPresent(pInfo *framework.QueuedPodInfo, podSchedulingCycle int64) error","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// AddUnschedulableIfNotPresent inserts a pod that cannot be scheduled into\n// the queue, unless it is already in the queue. Normally, PriorityQueue puts\n// unschedulable pods in `unschedulablePods`. But if there has been a recent move\n// request, then the pod is put in `podBackoffQ`.\nfunc (p *PriorityQueue) AddUnschedulableIfNotPresent(pInfo *framework.QueuedPodInfo, podSchedulingCycle int64) error {\n\tp.lock.Lock()\n\tdefer p.lock.Unlock()\n\tpod := pInfo.Pod\n\tif p.unschedulablePods.get(pod) != nil {\n\t\treturn fmt.Errorf(\"Pod %v is already present in unschedulable queue\", klog.KObj(pod))\n\t}\n\n\tif _, exists, _ := p.activeQ.Get(pInfo); exists {\n\t\treturn fmt.Errorf(\"Pod %v is already present in the active queue\", klog.KObj(pod))\n\t}\n\tif _, exists, _ := p.podBackoffQ.Get(pInfo); exists {\n\t\treturn fmt.Errorf(\"Pod %v is already present in the backoff queue\", klog.KObj(pod))\n\t}\n\n\t// Refresh the timestamp since the pod is re-added.\n\tpInfo.Timestamp = p.clock.Now()\n\n\t// If a move request has been received, move it to the BackoffQ, otherwise move\n\t// it to unschedulablePods.\n\tfor plugin := range pInfo.UnschedulablePlugins {\n\t\tmetrics.UnschedulableReason(plugin, pInfo.Pod.Spec.SchedulerName).Inc()\n\t}\n\tif p.moveRequestCycle \u003e= podSchedulingCycle {\n\t\tif err := p.podBackoffQ.Add(pInfo); err != nil {\n\t\t\treturn fmt.Errorf(\"error adding pod %v to the backoff queue: %v\", klog.KObj(pod), err)\n\t\t}\n\t\tklog.V(5).InfoS(\"Pod moved to an internal scheduling queue\", \"pod\", klog.KObj(pod), \"event\", ScheduleAttemptFailure, \"queue\", backoffQName)\n\t\tmetrics.SchedulerQueueIncomingPods.WithLabelValues(\"backoff\", ScheduleAttemptFailure).Inc()\n\t} else {\n\t\tp.unschedulablePods.addOrUpdate(pInfo)\n\t\tklog.V(5).InfoS(\"Pod moved to an internal scheduling queue\", \"pod\", klog.KObj(pod), \"event\", ScheduleAttemptFailure, \"queue\", unschedulablePods)\n\t\tmetrics.SchedulerQueueIncomingPods.WithLabelValues(\"unschedulable\", ScheduleAttemptFailure).Inc()\n\n\t}\n\n\tp.addNominatedPodUnlocked(pInfo.PodInfo, nil)\n\treturn nil\n}","line":{"from":496,"to":538}} {"id":100011315,"name":"flushBackoffQCompleted","signature":"func (p *PriorityQueue) flushBackoffQCompleted()","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// flushBackoffQCompleted Moves all pods from backoffQ which have completed backoff in to activeQ\nfunc (p *PriorityQueue) flushBackoffQCompleted() {\n\tp.lock.Lock()\n\tdefer p.lock.Unlock()\n\tactivated := false\n\tfor {\n\t\trawPodInfo := p.podBackoffQ.Peek()\n\t\tif rawPodInfo == nil {\n\t\t\tbreak\n\t\t}\n\t\tpInfo := rawPodInfo.(*framework.QueuedPodInfo)\n\t\tpod := pInfo.Pod\n\t\tif p.isPodBackingoff(pInfo) {\n\t\t\tbreak\n\t\t}\n\t\t_, err := p.podBackoffQ.Pop()\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Unable to pop pod from backoff queue despite backoff completion\", \"pod\", klog.KObj(pod))\n\t\t\tbreak\n\t\t}\n\t\tif added, _ := p.addToActiveQ(pInfo); added {\n\t\t\tklog.V(5).InfoS(\"Pod moved to an internal scheduling queue\", \"pod\", klog.KObj(pod), \"event\", BackoffComplete, \"queue\", activeQName)\n\t\t\tmetrics.SchedulerQueueIncomingPods.WithLabelValues(\"active\", BackoffComplete).Inc()\n\t\t\tactivated = true\n\t\t}\n\t}\n\n\tif activated {\n\t\tp.cond.Broadcast()\n\t}\n}","line":{"from":540,"to":570}} {"id":100011316,"name":"flushUnschedulablePodsLeftover","signature":"func (p *PriorityQueue) flushUnschedulablePodsLeftover()","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// flushUnschedulablePodsLeftover moves pods which stay in unschedulablePods\n// longer than podMaxInUnschedulablePodsDuration to backoffQ or activeQ.\nfunc (p *PriorityQueue) flushUnschedulablePodsLeftover() {\n\tp.lock.Lock()\n\tdefer p.lock.Unlock()\n\n\tvar podsToMove []*framework.QueuedPodInfo\n\tcurrentTime := p.clock.Now()\n\tfor _, pInfo := range p.unschedulablePods.podInfoMap {\n\t\tlastScheduleTime := pInfo.Timestamp\n\t\tif currentTime.Sub(lastScheduleTime) \u003e p.podMaxInUnschedulablePodsDuration {\n\t\t\tpodsToMove = append(podsToMove, pInfo)\n\t\t}\n\t}\n\n\tif len(podsToMove) \u003e 0 {\n\t\tp.movePodsToActiveOrBackoffQueue(podsToMove, UnschedulableTimeout)\n\t}\n}","line":{"from":572,"to":590}} {"id":100011317,"name":"Pop","signature":"func (p *PriorityQueue) Pop() (*framework.QueuedPodInfo, error)","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// Pop removes the head of the active queue and returns it. It blocks if the\n// activeQ is empty and waits until a new item is added to the queue. It\n// increments scheduling cycle when a pod is popped.\nfunc (p *PriorityQueue) Pop() (*framework.QueuedPodInfo, error) {\n\tp.lock.Lock()\n\tdefer p.lock.Unlock()\n\tfor p.activeQ.Len() == 0 {\n\t\t// When the queue is empty, invocation of Pop() is blocked until new item is enqueued.\n\t\t// When Close() is called, the p.closed is set and the condition is broadcast,\n\t\t// which causes this loop to continue and return from the Pop().\n\t\tif p.closed {\n\t\t\treturn nil, fmt.Errorf(queueClosed)\n\t\t}\n\t\tp.cond.Wait()\n\t}\n\tobj, err := p.activeQ.Pop()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpInfo := obj.(*framework.QueuedPodInfo)\n\tpInfo.Attempts++\n\tp.schedulingCycle++\n\treturn pInfo, nil\n}","line":{"from":592,"to":615}} {"id":100011318,"name":"isPodUpdated","signature":"func isPodUpdated(oldPod, newPod *v1.Pod) bool","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// isPodUpdated checks if the pod is updated in a way that it may have become\n// schedulable. It drops status of the pod and compares it with old version.\nfunc isPodUpdated(oldPod, newPod *v1.Pod) bool {\n\tstrip := func(pod *v1.Pod) *v1.Pod {\n\t\tp := pod.DeepCopy()\n\t\tp.ResourceVersion = \"\"\n\t\tp.Generation = 0\n\t\tp.Status = v1.PodStatus{}\n\t\tp.ManagedFields = nil\n\t\tp.Finalizers = nil\n\t\treturn p\n\t}\n\treturn !reflect.DeepEqual(strip(oldPod), strip(newPod))\n}","line":{"from":617,"to":630}} {"id":100011319,"name":"Update","signature":"func (p *PriorityQueue) Update(oldPod, newPod *v1.Pod) error","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// Update updates a pod in the active or backoff queue if present. Otherwise, it removes\n// the item from the unschedulable queue if pod is updated in a way that it may\n// become schedulable and adds the updated one to the active queue.\n// If pod is not present in any of the queues, it is added to the active queue.\nfunc (p *PriorityQueue) Update(oldPod, newPod *v1.Pod) error {\n\tp.lock.Lock()\n\tdefer p.lock.Unlock()\n\n\tif oldPod != nil {\n\t\toldPodInfo := newQueuedPodInfoForLookup(oldPod)\n\t\t// If the pod is already in the active queue, just update it there.\n\t\tif oldPodInfo, exists, _ := p.activeQ.Get(oldPodInfo); exists {\n\t\t\tpInfo := updatePod(oldPodInfo, newPod)\n\t\t\tp.updateNominatedPodUnlocked(oldPod, pInfo.PodInfo)\n\t\t\treturn p.activeQ.Update(pInfo)\n\t\t}\n\n\t\t// If the pod is in the backoff queue, update it there.\n\t\tif oldPodInfo, exists, _ := p.podBackoffQ.Get(oldPodInfo); exists {\n\t\t\tpInfo := updatePod(oldPodInfo, newPod)\n\t\t\tp.updateNominatedPodUnlocked(oldPod, pInfo.PodInfo)\n\t\t\treturn p.podBackoffQ.Update(pInfo)\n\t\t}\n\t}\n\n\t// If the pod is in the unschedulable queue, updating it may make it schedulable.\n\tif usPodInfo := p.unschedulablePods.get(newPod); usPodInfo != nil {\n\t\tpInfo := updatePod(usPodInfo, newPod)\n\t\tp.updateNominatedPodUnlocked(oldPod, pInfo.PodInfo)\n\t\tif isPodUpdated(oldPod, newPod) {\n\t\t\tgated := usPodInfo.Gated\n\t\t\tif p.isPodBackingoff(usPodInfo) {\n\t\t\t\tif err := p.podBackoffQ.Add(pInfo); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tp.unschedulablePods.delete(usPodInfo.Pod, gated)\n\t\t\t\tklog.V(5).InfoS(\"Pod moved to an internal scheduling queue\", \"pod\", klog.KObj(pInfo.Pod), \"event\", PodUpdate, \"queue\", backoffQName)\n\t\t\t} else {\n\t\t\t\tif added, err := p.addToActiveQ(pInfo); !added {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tp.unschedulablePods.delete(usPodInfo.Pod, gated)\n\t\t\t\tklog.V(5).InfoS(\"Pod moved to an internal scheduling queue\", \"pod\", klog.KObj(pInfo.Pod), \"event\", BackoffComplete, \"queue\", activeQName)\n\t\t\t\tp.cond.Broadcast()\n\t\t\t}\n\t\t} else {\n\t\t\t// Pod update didn't make it schedulable, keep it in the unschedulable queue.\n\t\t\tp.unschedulablePods.addOrUpdate(pInfo)\n\t\t}\n\n\t\treturn nil\n\t}\n\t// If pod is not in any of the queues, we put it in the active queue.\n\tpInfo := p.newQueuedPodInfo(newPod)\n\tif added, err := p.addToActiveQ(pInfo); !added {\n\t\treturn err\n\t}\n\tp.addNominatedPodUnlocked(pInfo.PodInfo, nil)\n\tklog.V(5).InfoS(\"Pod moved to an internal scheduling queue\", \"pod\", klog.KObj(pInfo.Pod), \"event\", PodUpdate, \"queue\", activeQName)\n\tp.cond.Broadcast()\n\treturn nil\n}","line":{"from":632,"to":693}} {"id":100011320,"name":"Delete","signature":"func (p *PriorityQueue) Delete(pod *v1.Pod) error","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// Delete deletes the item from either of the two queues. It assumes the pod is\n// only in one queue.\nfunc (p *PriorityQueue) Delete(pod *v1.Pod) error {\n\tp.lock.Lock()\n\tdefer p.lock.Unlock()\n\tp.deleteNominatedPodIfExistsUnlocked(pod)\n\tpInfo := newQueuedPodInfoForLookup(pod)\n\tif err := p.activeQ.Delete(pInfo); err != nil {\n\t\t// The item was probably not found in the activeQ.\n\t\tp.podBackoffQ.Delete(pInfo)\n\t\tif pInfo = p.unschedulablePods.get(pod); pInfo != nil {\n\t\t\tp.unschedulablePods.delete(pod, pInfo.Gated)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":695,"to":710}} {"id":100011321,"name":"AssignedPodAdded","signature":"func (p *PriorityQueue) AssignedPodAdded(pod *v1.Pod)","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// AssignedPodAdded is called when a bound pod is added. Creation of this pod\n// may make pending pods with matching affinity terms schedulable.\nfunc (p *PriorityQueue) AssignedPodAdded(pod *v1.Pod) {\n\tp.lock.Lock()\n\tp.movePodsToActiveOrBackoffQueue(p.getUnschedulablePodsWithMatchingAffinityTerm(pod), AssignedPodAdd)\n\tp.lock.Unlock()\n}","line":{"from":712,"to":718}} {"id":100011322,"name":"isPodResourcesResizedDown","signature":"func isPodResourcesResizedDown(pod *v1.Pod) bool","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// isPodResourcesResizedDown returns true if a pod CPU and/or memory resize request has been\n// admitted by kubelet, is 'InProgress', and results in a net sizing down of updated resources.\n// It returns false if either CPU or memory resource is net resized up, or if no resize is in progress.\nfunc isPodResourcesResizedDown(pod *v1.Pod) bool {\n\tif utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) {\n\t\t// TODO(vinaykul,wangchen615,InPlacePodVerticalScaling): Fix this to determine when a\n\t\t// pod is truly resized down (might need oldPod if we cannot determine from Status alone)\n\t\tif pod.Status.Resize == v1.PodResizeStatusInProgress {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":720,"to":732}} {"id":100011323,"name":"AssignedPodUpdated","signature":"func (p *PriorityQueue) AssignedPodUpdated(pod *v1.Pod)","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// AssignedPodUpdated is called when a bound pod is updated. Change of labels\n// may make pending pods with matching affinity terms schedulable.\nfunc (p *PriorityQueue) AssignedPodUpdated(pod *v1.Pod) {\n\tp.lock.Lock()\n\tif isPodResourcesResizedDown(pod) {\n\t\tp.moveAllToActiveOrBackoffQueue(AssignedPodUpdate, nil)\n\t} else {\n\t\tp.movePodsToActiveOrBackoffQueue(p.getUnschedulablePodsWithMatchingAffinityTerm(pod), AssignedPodUpdate)\n\t}\n\tp.lock.Unlock()\n}","line":{"from":734,"to":744}} {"id":100011324,"name":"moveAllToActiveOrBackoffQueue","signature":"func (p *PriorityQueue) moveAllToActiveOrBackoffQueue(event framework.ClusterEvent, preCheck PreEnqueueCheck)","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// NOTE: this function assumes a lock has been acquired in the caller.\n// moveAllToActiveOrBackoffQueue moves all pods from unschedulablePods to activeQ or backoffQ.\n// This function adds all pods and then signals the condition variable to ensure that\n// if Pop() is waiting for an item, it receives the signal after all the pods are in the\n// queue and the head is the highest priority pod.\nfunc (p *PriorityQueue) moveAllToActiveOrBackoffQueue(event framework.ClusterEvent, preCheck PreEnqueueCheck) {\n\tunschedulablePods := make([]*framework.QueuedPodInfo, 0, len(p.unschedulablePods.podInfoMap))\n\tfor _, pInfo := range p.unschedulablePods.podInfoMap {\n\t\tif preCheck == nil || preCheck(pInfo.Pod) {\n\t\t\tunschedulablePods = append(unschedulablePods, pInfo)\n\t\t}\n\t}\n\tp.movePodsToActiveOrBackoffQueue(unschedulablePods, event)\n}","line":{"from":746,"to":759}} {"id":100011325,"name":"MoveAllToActiveOrBackoffQueue","signature":"func (p *PriorityQueue) MoveAllToActiveOrBackoffQueue(event framework.ClusterEvent, preCheck PreEnqueueCheck)","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// MoveAllToActiveOrBackoffQueue moves all pods from unschedulablePods to activeQ or backoffQ.\n// This function adds all pods and then signals the condition variable to ensure that\n// if Pop() is waiting for an item, it receives the signal after all the pods are in the\n// queue and the head is the highest priority pod.\nfunc (p *PriorityQueue) MoveAllToActiveOrBackoffQueue(event framework.ClusterEvent, preCheck PreEnqueueCheck) {\n\tp.lock.Lock()\n\tdefer p.lock.Unlock()\n\tp.moveAllToActiveOrBackoffQueue(event, preCheck)\n}","line":{"from":761,"to":769}} {"id":100011326,"name":"movePodsToActiveOrBackoffQueue","signature":"func (p *PriorityQueue) movePodsToActiveOrBackoffQueue(podInfoList []*framework.QueuedPodInfo, event framework.ClusterEvent)","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// NOTE: this function assumes lock has been acquired in caller\nfunc (p *PriorityQueue) movePodsToActiveOrBackoffQueue(podInfoList []*framework.QueuedPodInfo, event framework.ClusterEvent) {\n\tactivated := false\n\tfor _, pInfo := range podInfoList {\n\t\t// If the event doesn't help making the Pod schedulable, continue.\n\t\t// Note: we don't run the check if pInfo.UnschedulablePlugins is nil, which denotes\n\t\t// either there is some abnormal error, or scheduling the pod failed by plugins other than PreFilter, Filter and Permit.\n\t\t// In that case, it's desired to move it anyways.\n\t\tif len(pInfo.UnschedulablePlugins) != 0 \u0026\u0026 !p.podMatchesEvent(pInfo, event) {\n\t\t\tcontinue\n\t\t}\n\t\tpod := pInfo.Pod\n\t\tif p.isPodBackingoff(pInfo) {\n\t\t\tif err := p.podBackoffQ.Add(pInfo); err != nil {\n\t\t\t\tklog.ErrorS(err, \"Error adding pod to the backoff queue\", \"pod\", klog.KObj(pod))\n\t\t\t} else {\n\t\t\t\tklog.V(5).InfoS(\"Pod moved to an internal scheduling queue\", \"pod\", klog.KObj(pInfo.Pod), \"event\", event, \"queue\", backoffQName)\n\t\t\t\tmetrics.SchedulerQueueIncomingPods.WithLabelValues(\"backoff\", event.Label).Inc()\n\t\t\t\tp.unschedulablePods.delete(pod, pInfo.Gated)\n\t\t\t}\n\t\t} else {\n\t\t\tgated := pInfo.Gated\n\t\t\tif added, _ := p.addToActiveQ(pInfo); added {\n\t\t\t\tklog.V(5).InfoS(\"Pod moved to an internal scheduling queue\", \"pod\", klog.KObj(pInfo.Pod), \"event\", event, \"queue\", activeQName)\n\t\t\t\tactivated = true\n\t\t\t\tmetrics.SchedulerQueueIncomingPods.WithLabelValues(\"active\", event.Label).Inc()\n\t\t\t\tp.unschedulablePods.delete(pod, gated)\n\t\t\t}\n\t\t}\n\t}\n\tp.moveRequestCycle = p.schedulingCycle\n\tif activated {\n\t\tp.cond.Broadcast()\n\t}\n}","line":{"from":771,"to":805}} {"id":100011327,"name":"getUnschedulablePodsWithMatchingAffinityTerm","signature":"func (p *PriorityQueue) getUnschedulablePodsWithMatchingAffinityTerm(pod *v1.Pod) []*framework.QueuedPodInfo","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// getUnschedulablePodsWithMatchingAffinityTerm returns unschedulable pods which have\n// any affinity term that matches \"pod\".\n// NOTE: this function assumes lock has been acquired in caller.\nfunc (p *PriorityQueue) getUnschedulablePodsWithMatchingAffinityTerm(pod *v1.Pod) []*framework.QueuedPodInfo {\n\tnsLabels := interpodaffinity.GetNamespaceLabelsSnapshot(pod.Namespace, p.nsLister)\n\n\tvar podsToMove []*framework.QueuedPodInfo\n\tfor _, pInfo := range p.unschedulablePods.podInfoMap {\n\t\tfor _, term := range pInfo.RequiredAffinityTerms {\n\t\t\tif term.Matches(pod, nsLabels) {\n\t\t\t\tpodsToMove = append(podsToMove, pInfo)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t}\n\treturn podsToMove\n}","line":{"from":807,"to":824}} {"id":100011328,"name":"PendingPods","signature":"func (p *PriorityQueue) PendingPods() ([]*v1.Pod, string)","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// PendingPods returns all the pending pods in the queue; accompanied by a debugging string\n// recording showing the number of pods in each queue respectively.\n// This function is used for debugging purposes in the scheduler cache dumper and comparer.\nfunc (p *PriorityQueue) PendingPods() ([]*v1.Pod, string) {\n\tp.lock.RLock()\n\tdefer p.lock.RUnlock()\n\tvar result []*v1.Pod\n\tfor _, pInfo := range p.activeQ.List() {\n\t\tresult = append(result, pInfo.(*framework.QueuedPodInfo).Pod)\n\t}\n\tfor _, pInfo := range p.podBackoffQ.List() {\n\t\tresult = append(result, pInfo.(*framework.QueuedPodInfo).Pod)\n\t}\n\tfor _, pInfo := range p.unschedulablePods.podInfoMap {\n\t\tresult = append(result, pInfo.Pod)\n\t}\n\treturn result, fmt.Sprintf(pendingPodsSummary, p.activeQ.Len(), p.podBackoffQ.Len(), len(p.unschedulablePods.podInfoMap))\n}","line":{"from":828,"to":845}} {"id":100011329,"name":"Close","signature":"func (p *PriorityQueue) Close()","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// Close closes the priority queue.\nfunc (p *PriorityQueue) Close() {\n\tp.lock.Lock()\n\tdefer p.lock.Unlock()\n\tclose(p.stop)\n\tp.closed = true\n\tp.cond.Broadcast()\n}","line":{"from":847,"to":854}} {"id":100011330,"name":"DeleteNominatedPodIfExists","signature":"func (npm *nominator) DeleteNominatedPodIfExists(pod *v1.Pod)","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// DeleteNominatedPodIfExists deletes \u003cpod\u003e from nominatedPods.\nfunc (npm *nominator) DeleteNominatedPodIfExists(pod *v1.Pod) {\n\tnpm.lock.Lock()\n\tnpm.deleteNominatedPodIfExistsUnlocked(pod)\n\tnpm.lock.Unlock()\n}","line":{"from":856,"to":861}} {"id":100011331,"name":"deleteNominatedPodIfExistsUnlocked","signature":"func (npm *nominator) deleteNominatedPodIfExistsUnlocked(pod *v1.Pod)","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"func (npm *nominator) deleteNominatedPodIfExistsUnlocked(pod *v1.Pod) {\n\tnpm.delete(pod)\n}","line":{"from":863,"to":865}} {"id":100011332,"name":"AddNominatedPod","signature":"func (npm *nominator) AddNominatedPod(pi *framework.PodInfo, nominatingInfo *framework.NominatingInfo)","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// AddNominatedPod adds a pod to the nominated pods of the given node.\n// This is called during the preemption process after a node is nominated to run\n// the pod. We update the structure before sending a request to update the pod\n// object to avoid races with the following scheduling cycles.\nfunc (npm *nominator) AddNominatedPod(pi *framework.PodInfo, nominatingInfo *framework.NominatingInfo) {\n\tnpm.lock.Lock()\n\tnpm.addNominatedPodUnlocked(pi, nominatingInfo)\n\tnpm.lock.Unlock()\n}","line":{"from":867,"to":875}} {"id":100011333,"name":"NominatedPodsForNode","signature":"func (npm *nominator) NominatedPodsForNode(nodeName string) []*framework.PodInfo","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// NominatedPodsForNode returns a copy of pods that are nominated to run on the given node,\n// but they are waiting for other pods to be removed from the node.\nfunc (npm *nominator) NominatedPodsForNode(nodeName string) []*framework.PodInfo {\n\tnpm.lock.RLock()\n\tdefer npm.lock.RUnlock()\n\t// Make a copy of the nominated Pods so the caller can mutate safely.\n\tpods := make([]*framework.PodInfo, len(npm.nominatedPods[nodeName]))\n\tfor i := 0; i \u003c len(pods); i++ {\n\t\tpods[i] = npm.nominatedPods[nodeName][i].DeepCopy()\n\t}\n\treturn pods\n}","line":{"from":877,"to":888}} {"id":100011334,"name":"podsCompareBackoffCompleted","signature":"func (p *PriorityQueue) podsCompareBackoffCompleted(podInfo1, podInfo2 interface{}) bool","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"func (p *PriorityQueue) podsCompareBackoffCompleted(podInfo1, podInfo2 interface{}) bool {\n\tpInfo1 := podInfo1.(*framework.QueuedPodInfo)\n\tpInfo2 := podInfo2.(*framework.QueuedPodInfo)\n\tbo1 := p.getBackoffTime(pInfo1)\n\tbo2 := p.getBackoffTime(pInfo2)\n\treturn bo1.Before(bo2)\n}","line":{"from":890,"to":896}} {"id":100011335,"name":"newQueuedPodInfo","signature":"func (p *PriorityQueue) newQueuedPodInfo(pod *v1.Pod, plugins ...string) *framework.QueuedPodInfo","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// newQueuedPodInfo builds a QueuedPodInfo object.\nfunc (p *PriorityQueue) newQueuedPodInfo(pod *v1.Pod, plugins ...string) *framework.QueuedPodInfo {\n\tnow := p.clock.Now()\n\t// ignore this err since apiserver doesn't properly validate affinity terms\n\t// and we can't fix the validation for backwards compatibility.\n\tpodInfo, _ := framework.NewPodInfo(pod)\n\treturn \u0026framework.QueuedPodInfo{\n\t\tPodInfo: podInfo,\n\t\tTimestamp: now,\n\t\tInitialAttemptTimestamp: nil,\n\t\tUnschedulablePlugins: sets.NewString(plugins...),\n\t}\n}","line":{"from":898,"to":910}} {"id":100011336,"name":"getBackoffTime","signature":"func (p *PriorityQueue) getBackoffTime(podInfo *framework.QueuedPodInfo) time.Time","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// getBackoffTime returns the time that podInfo completes backoff\nfunc (p *PriorityQueue) getBackoffTime(podInfo *framework.QueuedPodInfo) time.Time {\n\tduration := p.calculateBackoffDuration(podInfo)\n\tbackoffTime := podInfo.Timestamp.Add(duration)\n\treturn backoffTime\n}","line":{"from":912,"to":917}} {"id":100011337,"name":"calculateBackoffDuration","signature":"func (p *PriorityQueue) calculateBackoffDuration(podInfo *framework.QueuedPodInfo) time.Duration","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// calculateBackoffDuration is a helper function for calculating the backoffDuration\n// based on the number of attempts the pod has made.\nfunc (p *PriorityQueue) calculateBackoffDuration(podInfo *framework.QueuedPodInfo) time.Duration {\n\tduration := p.podInitialBackoffDuration\n\tfor i := 1; i \u003c podInfo.Attempts; i++ {\n\t\t// Use subtraction instead of addition or multiplication to avoid overflow.\n\t\tif duration \u003e p.podMaxBackoffDuration-duration {\n\t\t\treturn p.podMaxBackoffDuration\n\t\t}\n\t\tduration += duration\n\t}\n\treturn duration\n}","line":{"from":919,"to":931}} {"id":100011338,"name":"updatePod","signature":"func updatePod(oldPodInfo interface{}, newPod *v1.Pod) *framework.QueuedPodInfo","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"func updatePod(oldPodInfo interface{}, newPod *v1.Pod) *framework.QueuedPodInfo {\n\tpInfo := oldPodInfo.(*framework.QueuedPodInfo)\n\tpInfo.Update(newPod)\n\treturn pInfo\n}","line":{"from":933,"to":937}} {"id":100011339,"name":"addOrUpdate","signature":"func (u *UnschedulablePods) addOrUpdate(pInfo *framework.QueuedPodInfo)","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// addOrUpdate adds a pod to the unschedulable podInfoMap.\nfunc (u *UnschedulablePods) addOrUpdate(pInfo *framework.QueuedPodInfo) {\n\tpodID := u.keyFunc(pInfo.Pod)\n\tif _, exists := u.podInfoMap[podID]; !exists {\n\t\tif pInfo.Gated \u0026\u0026 u.gatedRecorder != nil {\n\t\t\tu.gatedRecorder.Inc()\n\t\t} else if !pInfo.Gated \u0026\u0026 u.unschedulableRecorder != nil {\n\t\t\tu.unschedulableRecorder.Inc()\n\t\t}\n\t}\n\tu.podInfoMap[podID] = pInfo\n}","line":{"from":950,"to":961}} {"id":100011340,"name":"delete","signature":"func (u *UnschedulablePods) delete(pod *v1.Pod, gated bool)","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// delete deletes a pod from the unschedulable podInfoMap.\n// The `gated` parameter is used to figure out which metric should be decreased.\nfunc (u *UnschedulablePods) delete(pod *v1.Pod, gated bool) {\n\tpodID := u.keyFunc(pod)\n\tif _, exists := u.podInfoMap[podID]; exists {\n\t\tif gated \u0026\u0026 u.gatedRecorder != nil {\n\t\t\tu.gatedRecorder.Dec()\n\t\t} else if !gated \u0026\u0026 u.unschedulableRecorder != nil {\n\t\t\tu.unschedulableRecorder.Dec()\n\t\t}\n\t}\n\tdelete(u.podInfoMap, podID)\n}","line":{"from":963,"to":975}} {"id":100011341,"name":"get","signature":"func (u *UnschedulablePods) get(pod *v1.Pod) *framework.QueuedPodInfo","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// get returns the QueuedPodInfo if a pod with the same key as the key of the given \"pod\"\n// is found in the map. It returns nil otherwise.\nfunc (u *UnschedulablePods) get(pod *v1.Pod) *framework.QueuedPodInfo {\n\tpodKey := u.keyFunc(pod)\n\tif pInfo, exists := u.podInfoMap[podKey]; exists {\n\t\treturn pInfo\n\t}\n\treturn nil\n}","line":{"from":977,"to":985}} {"id":100011342,"name":"clear","signature":"func (u *UnschedulablePods) clear()","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// clear removes all the entries from the unschedulable podInfoMap.\nfunc (u *UnschedulablePods) clear() {\n\tu.podInfoMap = make(map[string]*framework.QueuedPodInfo)\n\tif u.unschedulableRecorder != nil {\n\t\tu.unschedulableRecorder.Clear()\n\t}\n\tif u.gatedRecorder != nil {\n\t\tu.gatedRecorder.Clear()\n\t}\n}","line":{"from":987,"to":996}} {"id":100011343,"name":"newUnschedulablePods","signature":"func newUnschedulablePods(unschedulableRecorder, gatedRecorder metrics.MetricRecorder) *UnschedulablePods","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// newUnschedulablePods initializes a new object of UnschedulablePods.\nfunc newUnschedulablePods(unschedulableRecorder, gatedRecorder metrics.MetricRecorder) *UnschedulablePods {\n\treturn \u0026UnschedulablePods{\n\t\tpodInfoMap: make(map[string]*framework.QueuedPodInfo),\n\t\tkeyFunc: util.GetPodFullName,\n\t\tunschedulableRecorder: unschedulableRecorder,\n\t\tgatedRecorder: gatedRecorder,\n\t}\n}","line":{"from":998,"to":1006}} {"id":100011344,"name":"addNominatedPodUnlocked","signature":"func (npm *nominator) addNominatedPodUnlocked(pi *framework.PodInfo, nominatingInfo *framework.NominatingInfo)","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"func (npm *nominator) addNominatedPodUnlocked(pi *framework.PodInfo, nominatingInfo *framework.NominatingInfo) {\n\t// Always delete the pod if it already exists, to ensure we never store more than\n\t// one instance of the pod.\n\tnpm.delete(pi.Pod)\n\n\tvar nodeName string\n\tif nominatingInfo.Mode() == framework.ModeOverride {\n\t\tnodeName = nominatingInfo.NominatedNodeName\n\t} else if nominatingInfo.Mode() == framework.ModeNoop {\n\t\tif pi.Pod.Status.NominatedNodeName == \"\" {\n\t\t\treturn\n\t\t}\n\t\tnodeName = pi.Pod.Status.NominatedNodeName\n\t}\n\n\tif npm.podLister != nil {\n\t\t// If the pod was removed or if it was already scheduled, don't nominate it.\n\t\tupdatedPod, err := npm.podLister.Pods(pi.Pod.Namespace).Get(pi.Pod.Name)\n\t\tif err != nil {\n\t\t\tklog.V(4).InfoS(\"Pod doesn't exist in podLister, aborted adding it to the nominator\", \"pod\", klog.KObj(pi.Pod))\n\t\t\treturn\n\t\t}\n\t\tif updatedPod.Spec.NodeName != \"\" {\n\t\t\tklog.V(4).InfoS(\"Pod is already scheduled to a node, aborted adding it to the nominator\", \"pod\", klog.KObj(pi.Pod), \"node\", updatedPod.Spec.NodeName)\n\t\t\treturn\n\t\t}\n\t}\n\n\tnpm.nominatedPodToNode[pi.Pod.UID] = nodeName\n\tfor _, npi := range npm.nominatedPods[nodeName] {\n\t\tif npi.Pod.UID == pi.Pod.UID {\n\t\t\tklog.V(4).InfoS(\"Pod already exists in the nominator\", \"pod\", klog.KObj(npi.Pod))\n\t\t\treturn\n\t\t}\n\t}\n\tnpm.nominatedPods[nodeName] = append(npm.nominatedPods[nodeName], pi)\n}","line":{"from":1026,"to":1062}} {"id":100011345,"name":"delete","signature":"func (npm *nominator) delete(p *v1.Pod)","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"func (npm *nominator) delete(p *v1.Pod) {\n\tnnn, ok := npm.nominatedPodToNode[p.UID]\n\tif !ok {\n\t\treturn\n\t}\n\tfor i, np := range npm.nominatedPods[nnn] {\n\t\tif np.Pod.UID == p.UID {\n\t\t\tnpm.nominatedPods[nnn] = append(npm.nominatedPods[nnn][:i], npm.nominatedPods[nnn][i+1:]...)\n\t\t\tif len(npm.nominatedPods[nnn]) == 0 {\n\t\t\t\tdelete(npm.nominatedPods, nnn)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\tdelete(npm.nominatedPodToNode, p.UID)\n}","line":{"from":1064,"to":1079}} {"id":100011346,"name":"UpdateNominatedPod","signature":"func (npm *nominator) UpdateNominatedPod(oldPod *v1.Pod, newPodInfo *framework.PodInfo)","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// UpdateNominatedPod updates the \u003coldPod\u003e with \u003cnewPod\u003e.\nfunc (npm *nominator) UpdateNominatedPod(oldPod *v1.Pod, newPodInfo *framework.PodInfo) {\n\tnpm.lock.Lock()\n\tdefer npm.lock.Unlock()\n\tnpm.updateNominatedPodUnlocked(oldPod, newPodInfo)\n}","line":{"from":1081,"to":1086}} {"id":100011347,"name":"updateNominatedPodUnlocked","signature":"func (npm *nominator) updateNominatedPodUnlocked(oldPod *v1.Pod, newPodInfo *framework.PodInfo)","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"func (npm *nominator) updateNominatedPodUnlocked(oldPod *v1.Pod, newPodInfo *framework.PodInfo) {\n\t// In some cases, an Update event with no \"NominatedNode\" present is received right\n\t// after a node(\"NominatedNode\") is reserved for this pod in memory.\n\t// In this case, we need to keep reserving the NominatedNode when updating the pod pointer.\n\tvar nominatingInfo *framework.NominatingInfo\n\t// We won't fall into below `if` block if the Update event represents:\n\t// (1) NominatedNode info is added\n\t// (2) NominatedNode info is updated\n\t// (3) NominatedNode info is removed\n\tif NominatedNodeName(oldPod) == \"\" \u0026\u0026 NominatedNodeName(newPodInfo.Pod) == \"\" {\n\t\tif nnn, ok := npm.nominatedPodToNode[oldPod.UID]; ok {\n\t\t\t// This is the only case we should continue reserving the NominatedNode\n\t\t\tnominatingInfo = \u0026framework.NominatingInfo{\n\t\t\t\tNominatingMode: framework.ModeOverride,\n\t\t\t\tNominatedNodeName: nnn,\n\t\t\t}\n\t\t}\n\t}\n\t// We update irrespective of the nominatedNodeName changed or not, to ensure\n\t// that pod pointer is updated.\n\tnpm.delete(oldPod)\n\tnpm.addNominatedPodUnlocked(newPodInfo, nominatingInfo)\n}","line":{"from":1088,"to":1110}} {"id":100011348,"name":"NewPodNominator","signature":"func NewPodNominator(podLister listersv1.PodLister) framework.PodNominator","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// NewPodNominator creates a nominator as a backing of framework.PodNominator.\n// A podLister is passed in so as to check if the pod exists\n// before adding its nominatedNode info.\nfunc NewPodNominator(podLister listersv1.PodLister) framework.PodNominator {\n\treturn newPodNominator(podLister)\n}","line":{"from":1112,"to":1117}} {"id":100011349,"name":"newPodNominator","signature":"func newPodNominator(podLister listersv1.PodLister) *nominator","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"func newPodNominator(podLister listersv1.PodLister) *nominator {\n\treturn \u0026nominator{\n\t\tpodLister: podLister,\n\t\tnominatedPods: make(map[string][]*framework.PodInfo),\n\t\tnominatedPodToNode: make(map[types.UID]string),\n\t}\n}","line":{"from":1119,"to":1125}} {"id":100011350,"name":"MakeNextPodFunc","signature":"func MakeNextPodFunc(queue SchedulingQueue) func() *framework.QueuedPodInfo","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// MakeNextPodFunc returns a function to retrieve the next pod from a given\n// scheduling queue\nfunc MakeNextPodFunc(queue SchedulingQueue) func() *framework.QueuedPodInfo {\n\treturn func() *framework.QueuedPodInfo {\n\t\tpodInfo, err := queue.Pop()\n\t\tif err == nil {\n\t\t\tklog.V(4).InfoS(\"About to try and schedule pod\", \"pod\", klog.KObj(podInfo.Pod))\n\t\t\tfor plugin := range podInfo.UnschedulablePlugins {\n\t\t\t\tmetrics.UnschedulableReason(plugin, podInfo.Pod.Spec.SchedulerName).Dec()\n\t\t\t}\n\t\t\treturn podInfo\n\t\t}\n\t\tklog.ErrorS(err, \"Error while retrieving next pod from scheduling queue\")\n\t\treturn nil\n\t}\n}","line":{"from":1127,"to":1142}} {"id":100011351,"name":"podInfoKeyFunc","signature":"func podInfoKeyFunc(obj interface{}) (string, error)","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"func podInfoKeyFunc(obj interface{}) (string, error) {\n\treturn cache.MetaNamespaceKeyFunc(obj.(*framework.QueuedPodInfo).Pod)\n}","line":{"from":1144,"to":1146}} {"id":100011352,"name":"podMatchesEvent","signature":"func (p *PriorityQueue) podMatchesEvent(podInfo *framework.QueuedPodInfo, clusterEvent framework.ClusterEvent) bool","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"// Checks if the Pod may become schedulable upon the event.\n// This is achieved by looking up the global clusterEventMap registry.\nfunc (p *PriorityQueue) podMatchesEvent(podInfo *framework.QueuedPodInfo, clusterEvent framework.ClusterEvent) bool {\n\tif clusterEvent.IsWildCard() {\n\t\treturn true\n\t}\n\n\tfor evt, nameSet := range p.clusterEventMap {\n\t\t// Firstly verify if the two ClusterEvents match:\n\t\t// - either the registered event from plugin side is a WildCardEvent,\n\t\t// - or the two events have identical Resource fields and *compatible* ActionType.\n\t\t// Note the ActionTypes don't need to be *identical*. We check if the ANDed value\n\t\t// is zero or not. In this way, it's easy to tell Update\u0026Delete is not compatible,\n\t\t// but Update\u0026All is.\n\t\tevtMatch := evt.IsWildCard() ||\n\t\t\t(evt.Resource == clusterEvent.Resource \u0026\u0026 evt.ActionType\u0026clusterEvent.ActionType != 0)\n\n\t\t// Secondly verify the plugin name matches.\n\t\t// Note that if it doesn't match, we shouldn't continue to search.\n\t\tif evtMatch \u0026\u0026 intersect(nameSet, podInfo.UnschedulablePlugins) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":1148,"to":1173}} {"id":100011353,"name":"intersect","signature":"func intersect(x, y sets.String) bool","file":"pkg/scheduler/internal/queue/scheduling_queue.go","code":"func intersect(x, y sets.String) bool {\n\tif len(x) \u003e len(y) {\n\t\tx, y = y, x\n\t}\n\tfor v := range x {\n\t\tif y.Has(v) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":1175,"to":1185}} {"id":100011354,"name":"NewActivePodsRecorder","signature":"func NewActivePodsRecorder() *PendingPodsRecorder","file":"pkg/scheduler/metrics/metric_recorder.go","code":"// NewActivePodsRecorder returns ActivePods in a Prometheus metric fashion\nfunc NewActivePodsRecorder() *PendingPodsRecorder {\n\treturn \u0026PendingPodsRecorder{\n\t\trecorder: ActivePods(),\n\t}\n}","line":{"from":40,"to":45}} {"id":100011355,"name":"NewUnschedulablePodsRecorder","signature":"func NewUnschedulablePodsRecorder() *PendingPodsRecorder","file":"pkg/scheduler/metrics/metric_recorder.go","code":"// NewUnschedulablePodsRecorder returns UnschedulablePods in a Prometheus metric fashion\nfunc NewUnschedulablePodsRecorder() *PendingPodsRecorder {\n\treturn \u0026PendingPodsRecorder{\n\t\trecorder: UnschedulablePods(),\n\t}\n}","line":{"from":47,"to":52}} {"id":100011356,"name":"NewBackoffPodsRecorder","signature":"func NewBackoffPodsRecorder() *PendingPodsRecorder","file":"pkg/scheduler/metrics/metric_recorder.go","code":"// NewBackoffPodsRecorder returns BackoffPods in a Prometheus metric fashion\nfunc NewBackoffPodsRecorder() *PendingPodsRecorder {\n\treturn \u0026PendingPodsRecorder{\n\t\trecorder: BackoffPods(),\n\t}\n}","line":{"from":54,"to":59}} {"id":100011357,"name":"NewGatedPodsRecorder","signature":"func NewGatedPodsRecorder() *PendingPodsRecorder","file":"pkg/scheduler/metrics/metric_recorder.go","code":"// NewGatedPodsRecorder returns GatedPods in a Prometheus metric fashion\nfunc NewGatedPodsRecorder() *PendingPodsRecorder {\n\treturn \u0026PendingPodsRecorder{\n\t\trecorder: GatedPods(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100011358,"name":"Inc","signature":"func (r *PendingPodsRecorder) Inc()","file":"pkg/scheduler/metrics/metric_recorder.go","code":"// Inc increases a metric counter by 1, in an atomic way\nfunc (r *PendingPodsRecorder) Inc() {\n\tr.recorder.Inc()\n}","line":{"from":68,"to":71}} {"id":100011359,"name":"Dec","signature":"func (r *PendingPodsRecorder) Dec()","file":"pkg/scheduler/metrics/metric_recorder.go","code":"// Dec decreases a metric counter by 1, in an atomic way\nfunc (r *PendingPodsRecorder) Dec() {\n\tr.recorder.Dec()\n}","line":{"from":73,"to":76}} {"id":100011360,"name":"Clear","signature":"func (r *PendingPodsRecorder) Clear()","file":"pkg/scheduler/metrics/metric_recorder.go","code":"// Clear set a metric counter to 0, in an atomic way\nfunc (r *PendingPodsRecorder) Clear() {\n\tr.recorder.Set(float64(0))\n}","line":{"from":78,"to":81}} {"id":100011361,"name":"NewMetricsAsyncRecorder","signature":"func NewMetricsAsyncRecorder(bufferSize int, interval time.Duration, stopCh \u003c-chan struct{}) *MetricAsyncRecorder","file":"pkg/scheduler/metrics/metric_recorder.go","code":"func NewMetricsAsyncRecorder(bufferSize int, interval time.Duration, stopCh \u003c-chan struct{}) *MetricAsyncRecorder {\n\trecorder := \u0026MetricAsyncRecorder{\n\t\tbufferCh: make(chan *metric, bufferSize),\n\t\tbufferSize: bufferSize,\n\t\tinterval: interval,\n\t\tstopCh: stopCh,\n\t\tIsStoppedCh: make(chan struct{}),\n\t}\n\tgo recorder.run()\n\treturn recorder\n}","line":{"from":107,"to":117}} {"id":100011362,"name":"ObservePluginDurationAsync","signature":"func (r *MetricAsyncRecorder) ObservePluginDurationAsync(extensionPoint, pluginName, status string, value float64)","file":"pkg/scheduler/metrics/metric_recorder.go","code":"// ObservePluginDurationAsync observes the plugin_execution_duration_seconds metric.\n// The metric will be flushed to Prometheus asynchronously.\nfunc (r *MetricAsyncRecorder) ObservePluginDurationAsync(extensionPoint, pluginName, status string, value float64) {\n\tnewMetric := \u0026metric{\n\t\tmetric: PluginExecutionDuration,\n\t\tlabelValues: []string{pluginName, extensionPoint, status},\n\t\tvalue: value,\n\t}\n\tselect {\n\tcase r.bufferCh \u003c- newMetric:\n\tdefault:\n\t}\n}","line":{"from":119,"to":131}} {"id":100011363,"name":"run","signature":"func (r *MetricAsyncRecorder) run()","file":"pkg/scheduler/metrics/metric_recorder.go","code":"// run flushes buffered metrics into Prometheus every second.\nfunc (r *MetricAsyncRecorder) run() {\n\tfor {\n\t\tselect {\n\t\tcase \u003c-r.stopCh:\n\t\t\tclose(r.IsStoppedCh)\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\t\tr.FlushMetrics()\n\t\ttime.Sleep(r.interval)\n\t}\n}","line":{"from":133,"to":145}} {"id":100011364,"name":"FlushMetrics","signature":"func (r *MetricAsyncRecorder) FlushMetrics()","file":"pkg/scheduler/metrics/metric_recorder.go","code":"// FlushMetrics tries to clean up the bufferCh by reading at most bufferSize metrics.\nfunc (r *MetricAsyncRecorder) FlushMetrics() {\n\tfor i := 0; i \u003c r.bufferSize; i++ {\n\t\tselect {\n\t\tcase m := \u003c-r.bufferCh:\n\t\t\tm.metric.WithLabelValues(m.labelValues...).Observe(m.value)\n\t\tdefault:\n\t\t\treturn\n\t\t}\n\t}\n}","line":{"from":147,"to":157}} {"id":100011365,"name":"Register","signature":"func Register()","file":"pkg/scheduler/metrics/metrics.go","code":"// Register all metrics.\nfunc Register() {\n\t// Register the metrics.\n\tregisterMetrics.Do(func() {\n\t\tRegisterMetrics(metricsList...)\n\t\tvolumebindingmetrics.RegisterVolumeSchedulingMetrics()\n\t})\n}","line":{"from":234,"to":241}} {"id":100011366,"name":"RegisterMetrics","signature":"func RegisterMetrics(extraMetrics ...metrics.Registerable)","file":"pkg/scheduler/metrics/metrics.go","code":"// RegisterMetrics registers a list of metrics.\n// This function is exported because it is intended to be used by out-of-tree plugins to register their custom metrics.\nfunc RegisterMetrics(extraMetrics ...metrics.Registerable) {\n\tfor _, metric := range extraMetrics {\n\t\tlegacyregistry.MustRegister(metric)\n\t}\n}","line":{"from":243,"to":249}} {"id":100011367,"name":"GetGather","signature":"func GetGather() metrics.Gatherer","file":"pkg/scheduler/metrics/metrics.go","code":"// GetGather returns the gatherer. It used by test case outside current package.\nfunc GetGather() metrics.Gatherer {\n\treturn legacyregistry.DefaultGatherer\n}","line":{"from":251,"to":254}} {"id":100011368,"name":"ActivePods","signature":"func ActivePods() metrics.GaugeMetric","file":"pkg/scheduler/metrics/metrics.go","code":"// ActivePods returns the pending pods metrics with the label active\nfunc ActivePods() metrics.GaugeMetric {\n\treturn pendingPods.With(metrics.Labels{\"queue\": \"active\"})\n}","line":{"from":256,"to":259}} {"id":100011369,"name":"BackoffPods","signature":"func BackoffPods() metrics.GaugeMetric","file":"pkg/scheduler/metrics/metrics.go","code":"// BackoffPods returns the pending pods metrics with the label backoff\nfunc BackoffPods() metrics.GaugeMetric {\n\treturn pendingPods.With(metrics.Labels{\"queue\": \"backoff\"})\n}","line":{"from":261,"to":264}} {"id":100011370,"name":"UnschedulablePods","signature":"func UnschedulablePods() metrics.GaugeMetric","file":"pkg/scheduler/metrics/metrics.go","code":"// UnschedulablePods returns the pending pods metrics with the label unschedulable\nfunc UnschedulablePods() metrics.GaugeMetric {\n\treturn pendingPods.With(metrics.Labels{\"queue\": \"unschedulable\"})\n}","line":{"from":266,"to":269}} {"id":100011371,"name":"GatedPods","signature":"func GatedPods() metrics.GaugeMetric","file":"pkg/scheduler/metrics/metrics.go","code":"// GatedPods returns the pending pods metrics with the label gated\nfunc GatedPods() metrics.GaugeMetric {\n\treturn pendingPods.With(metrics.Labels{\"queue\": \"gated\"})\n}","line":{"from":271,"to":274}} {"id":100011372,"name":"SinceInSeconds","signature":"func SinceInSeconds(start time.Time) float64","file":"pkg/scheduler/metrics/metrics.go","code":"// SinceInSeconds gets the time since the specified start in seconds.\nfunc SinceInSeconds(start time.Time) float64 {\n\treturn time.Since(start).Seconds()\n}","line":{"from":276,"to":279}} {"id":100011373,"name":"UnschedulableReason","signature":"func UnschedulableReason(plugin string, profile string) metrics.GaugeMetric","file":"pkg/scheduler/metrics/metrics.go","code":"func UnschedulableReason(plugin string, profile string) metrics.GaugeMetric {\n\treturn unschedulableReasons.With(metrics.Labels{\"plugin\": plugin, \"profile\": profile})\n}","line":{"from":281,"to":283}} {"id":100011374,"name":"PodScheduled","signature":"func PodScheduled(profile string, duration float64)","file":"pkg/scheduler/metrics/profile_metrics.go","code":"// PodScheduled can records a successful scheduling attempt and the duration\n// since `start`.\nfunc PodScheduled(profile string, duration float64) {\n\tobserveScheduleAttemptAndLatency(scheduledResult, profile, duration)\n}","line":{"from":27,"to":31}} {"id":100011375,"name":"PodUnschedulable","signature":"func PodUnschedulable(profile string, duration float64)","file":"pkg/scheduler/metrics/profile_metrics.go","code":"// PodUnschedulable can records a scheduling attempt for an unschedulable pod\n// and the duration since `start`.\nfunc PodUnschedulable(profile string, duration float64) {\n\tobserveScheduleAttemptAndLatency(unschedulableResult, profile, duration)\n}","line":{"from":33,"to":37}} {"id":100011376,"name":"PodScheduleError","signature":"func PodScheduleError(profile string, duration float64)","file":"pkg/scheduler/metrics/profile_metrics.go","code":"// PodScheduleError can records a scheduling attempt that had an error and the\n// duration since `start`.\nfunc PodScheduleError(profile string, duration float64) {\n\tobserveScheduleAttemptAndLatency(errorResult, profile, duration)\n}","line":{"from":39,"to":43}} {"id":100011377,"name":"observeScheduleAttemptAndLatency","signature":"func observeScheduleAttemptAndLatency(result, profile string, duration float64)","file":"pkg/scheduler/metrics/profile_metrics.go","code":"func observeScheduleAttemptAndLatency(result, profile string, duration float64) {\n\tschedulingLatency.WithLabelValues(result, profile).Observe(duration)\n\tscheduleAttempts.WithLabelValues(result, profile).Inc()\n}","line":{"from":45,"to":48}} {"id":100011378,"name":"Describe","signature":"func (d resourceLifecycleDescriptors) Describe(ch chan\u003c- *metrics.Desc)","file":"pkg/scheduler/metrics/resources/resources.go","code":"func (d resourceLifecycleDescriptors) Describe(ch chan\u003c- *metrics.Desc) {\n\tch \u003c- d.total\n}","line":{"from":40,"to":42}} {"id":100011379,"name":"Describe","signature":"func (d resourceMetricsDescriptors) Describe(ch chan\u003c- *metrics.Desc)","file":"pkg/scheduler/metrics/resources/resources.go","code":"func (d resourceMetricsDescriptors) Describe(ch chan\u003c- *metrics.Desc) {\n\td.requests.Describe(ch)\n\td.limits.Describe(ch)\n}","line":{"from":49,"to":52}} {"id":100011380,"name":"Handler","signature":"func Handler(podLister corelisters.PodLister) http.Handler","file":"pkg/scheduler/metrics/resources/resources.go","code":"// Handler creates a collector from the provided podLister and returns an http.Handler that\n// will report the requested metrics in the prometheus format. It does not include any other\n// metrics.\nfunc Handler(podLister corelisters.PodLister) http.Handler {\n\tcollector := NewPodResourcesMetricsCollector(podLister)\n\tregistry := metrics.NewKubeRegistry()\n\tregistry.CustomMustRegister(collector)\n\treturn metrics.HandlerWithReset(registry, metrics.HandlerOpts{})\n}","line":{"from":73,"to":81}} {"id":100011381,"name":"NewPodResourcesMetricsCollector","signature":"func NewPodResourcesMetricsCollector(podLister corelisters.PodLister) metrics.StableCollector","file":"pkg/scheduler/metrics/resources/resources.go","code":"// NewPodResourcesMetricsCollector registers a O(pods) cardinality metric that\n// reports the current resources requested by all pods on the cluster within\n// the Kubernetes resource model. Metrics are broken down by pod, node, resource,\n// and phase of lifecycle. Each pod returns two series per resource - one for\n// their aggregate usage (required to schedule) and one for their phase specific\n// usage. This allows admins to assess the cost per resource at different phases\n// of startup and compare to actual resource usage.\nfunc NewPodResourcesMetricsCollector(podLister corelisters.PodLister) metrics.StableCollector {\n\treturn \u0026podResourceCollector{\n\t\tlister: podLister,\n\t}\n}","line":{"from":86,"to":97}} {"id":100011382,"name":"DescribeWithStability","signature":"func (c *podResourceCollector) DescribeWithStability(ch chan\u003c- *metrics.Desc)","file":"pkg/scheduler/metrics/resources/resources.go","code":"func (c *podResourceCollector) DescribeWithStability(ch chan\u003c- *metrics.Desc) {\n\tpodResourceDesc.Describe(ch)\n}","line":{"from":104,"to":106}} {"id":100011383,"name":"CollectWithStability","signature":"func (c *podResourceCollector) CollectWithStability(ch chan\u003c- metrics.Metric)","file":"pkg/scheduler/metrics/resources/resources.go","code":"func (c *podResourceCollector) CollectWithStability(ch chan\u003c- metrics.Metric) {\n\tpods, err := c.lister.List(labels.Everything())\n\tif err != nil {\n\t\treturn\n\t}\n\treuseReqs, reuseLimits := make(v1.ResourceList, 4), make(v1.ResourceList, 4)\n\tfor _, p := range pods {\n\t\treqs, limits, terminal := podRequestsAndLimitsByLifecycle(p, reuseReqs, reuseLimits)\n\t\tif terminal {\n\t\t\t// terminal pods are excluded from resource usage calculations\n\t\t\tcontinue\n\t\t}\n\t\tfor _, t := range []struct {\n\t\t\tdesc resourceLifecycleDescriptors\n\t\t\ttotal v1.ResourceList\n\t\t}{\n\t\t\t{\n\t\t\t\tdesc: podResourceDesc.requests,\n\t\t\t\ttotal: reqs,\n\t\t\t},\n\t\t\t{\n\t\t\t\tdesc: podResourceDesc.limits,\n\t\t\t\ttotal: limits,\n\t\t\t},\n\t\t} {\n\t\t\tfor resourceName, val := range t.total {\n\t\t\t\tvar unitName string\n\t\t\t\tswitch resourceName {\n\t\t\t\tcase v1.ResourceCPU:\n\t\t\t\t\tunitName = \"cores\"\n\t\t\t\tcase v1.ResourceMemory:\n\t\t\t\t\tunitName = \"bytes\"\n\t\t\t\tcase v1.ResourceStorage:\n\t\t\t\t\tunitName = \"bytes\"\n\t\t\t\tcase v1.ResourceEphemeralStorage:\n\t\t\t\t\tunitName = \"bytes\"\n\t\t\t\tdefault:\n\t\t\t\t\tswitch {\n\t\t\t\t\tcase v1helper.IsHugePageResourceName(resourceName):\n\t\t\t\t\t\tunitName = \"bytes\"\n\t\t\t\t\tcase v1helper.IsAttachableVolumeResourceName(resourceName):\n\t\t\t\t\t\tunitName = \"integer\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tvar priority string\n\t\t\t\tif p.Spec.Priority != nil {\n\t\t\t\t\tpriority = strconv.FormatInt(int64(*p.Spec.Priority), 10)\n\t\t\t\t}\n\t\t\t\trecordMetricWithUnit(ch, t.desc.total, p.Namespace, p.Name, p.Spec.NodeName, p.Spec.SchedulerName, priority, resourceName, unitName, val)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":108,"to":160}} {"id":100011384,"name":"recordMetricWithUnit","signature":"func recordMetricWithUnit(","file":"pkg/scheduler/metrics/resources/resources.go","code":"func recordMetricWithUnit(\n\tch chan\u003c- metrics.Metric,\n\tdesc *metrics.Desc,\n\tnamespace, name, nodeName, schedulerName, priority string,\n\tresourceName v1.ResourceName,\n\tunit string,\n\tval resource.Quantity,\n) {\n\tif val.IsZero() {\n\t\treturn\n\t}\n\tch \u003c- metrics.NewLazyConstMetric(desc, metrics.GaugeValue,\n\t\tval.AsApproximateFloat64(),\n\t\tnamespace, name, nodeName, schedulerName, priority, string(resourceName), unit,\n\t)\n}","line":{"from":162,"to":177}} {"id":100011385,"name":"podRequestsAndLimitsByLifecycle","signature":"func podRequestsAndLimitsByLifecycle(pod *v1.Pod, reuseReqs, reuseLimits v1.ResourceList) (reqs, limits v1.ResourceList, terminal bool)","file":"pkg/scheduler/metrics/resources/resources.go","code":"// podRequestsAndLimitsByLifecycle returns a dictionary of all defined resources summed up for all\n// containers of the pod. Pod overhead is added to the\n// total container resource requests and to the total container limits which have a\n// non-zero quantity. The caller may avoid allocations of resource lists by passing\n// a requests and limits list to the function, which will be cleared before use.\n// This method is the same as v1resource.PodRequestsAndLimits but avoids allocating in several\n// scenarios for efficiency.\nfunc podRequestsAndLimitsByLifecycle(pod *v1.Pod, reuseReqs, reuseLimits v1.ResourceList) (reqs, limits v1.ResourceList, terminal bool) {\n\tswitch {\n\tcase len(pod.Spec.NodeName) == 0:\n\t\t// unscheduled pods cannot be terminal\n\tcase pod.Status.Phase == v1.PodSucceeded, pod.Status.Phase == v1.PodFailed:\n\t\tterminal = true\n\t\t// TODO: resolve https://github.com/kubernetes/kubernetes/issues/96515 and add a condition here\n\t\t// for checking that terminal state\n\t}\n\tif terminal {\n\t\treturn\n\t}\n\n\treqs = v1resource.PodRequests(pod, v1resource.PodResourcesOptions{Reuse: reuseReqs})\n\tlimits = v1resource.PodLimits(pod, v1resource.PodResourcesOptions{Reuse: reuseLimits})\n\treturn\n}","line":{"from":179,"to":202}} {"id":100011386,"name":"newProfile","signature":"func newProfile(cfg config.KubeSchedulerProfile, r frameworkruntime.Registry, recorderFact RecorderFactory,","file":"pkg/scheduler/profile/profile.go","code":"// newProfile builds a Profile for the given configuration.\nfunc newProfile(cfg config.KubeSchedulerProfile, r frameworkruntime.Registry, recorderFact RecorderFactory,\n\tstopCh \u003c-chan struct{}, opts ...frameworkruntime.Option) (framework.Framework, error) {\n\trecorder := recorderFact(cfg.SchedulerName)\n\topts = append(opts, frameworkruntime.WithEventRecorder(recorder))\n\treturn frameworkruntime.NewFramework(r, \u0026cfg, stopCh, opts...)\n}","line":{"from":36,"to":42}} {"id":100011387,"name":"NewMap","signature":"func NewMap(cfgs []config.KubeSchedulerProfile, r frameworkruntime.Registry, recorderFact RecorderFactory,","file":"pkg/scheduler/profile/profile.go","code":"// NewMap builds the frameworks given by the configuration, indexed by name.\nfunc NewMap(cfgs []config.KubeSchedulerProfile, r frameworkruntime.Registry, recorderFact RecorderFactory,\n\tstopCh \u003c-chan struct{}, opts ...frameworkruntime.Option) (Map, error) {\n\tm := make(Map)\n\tv := cfgValidator{m: m}\n\n\tfor _, cfg := range cfgs {\n\t\tp, err := newProfile(cfg, r, recorderFact, stopCh, opts...)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"creating profile for scheduler name %s: %v\", cfg.SchedulerName, err)\n\t\t}\n\t\tif err := v.validate(cfg, p); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tm[cfg.SchedulerName] = p\n\t}\n\treturn m, nil\n}","line":{"from":47,"to":64}} {"id":100011388,"name":"HandlesSchedulerName","signature":"func (m Map) HandlesSchedulerName(name string) bool","file":"pkg/scheduler/profile/profile.go","code":"// HandlesSchedulerName returns whether a profile handles the given scheduler name.\nfunc (m Map) HandlesSchedulerName(name string) bool {\n\t_, ok := m[name]\n\treturn ok\n}","line":{"from":66,"to":70}} {"id":100011389,"name":"NewRecorderFactory","signature":"func NewRecorderFactory(b events.EventBroadcaster) RecorderFactory","file":"pkg/scheduler/profile/profile.go","code":"// NewRecorderFactory returns a RecorderFactory for the broadcaster.\nfunc NewRecorderFactory(b events.EventBroadcaster) RecorderFactory {\n\treturn func(name string) events.EventRecorder {\n\t\treturn b.NewRecorder(scheme.Scheme, name)\n\t}\n}","line":{"from":72,"to":77}} {"id":100011390,"name":"validate","signature":"func (v *cfgValidator) validate(cfg config.KubeSchedulerProfile, f framework.Framework) error","file":"pkg/scheduler/profile/profile.go","code":"func (v *cfgValidator) validate(cfg config.KubeSchedulerProfile, f framework.Framework) error {\n\tif len(f.ProfileName()) == 0 {\n\t\treturn errors.New(\"scheduler name is needed\")\n\t}\n\tif cfg.Plugins == nil {\n\t\treturn fmt.Errorf(\"plugins required for profile with scheduler name %q\", f.ProfileName())\n\t}\n\tif v.m[f.ProfileName()] != nil {\n\t\treturn fmt.Errorf(\"duplicate profile with scheduler name %q\", f.ProfileName())\n\t}\n\n\tqueueSort := f.ListPlugins().QueueSort.Enabled[0].Name\n\tvar queueSortArgs runtime.Object\n\tfor _, plCfg := range cfg.PluginConfig {\n\t\tif plCfg.Name == queueSort {\n\t\t\tqueueSortArgs = plCfg.Args\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(v.queueSort) == 0 {\n\t\tv.queueSort = queueSort\n\t\tv.queueSortArgs = queueSortArgs\n\t\treturn nil\n\t}\n\tif v.queueSort != queueSort {\n\t\treturn fmt.Errorf(\"different queue sort plugins for profile %q: %q, first: %q\", cfg.SchedulerName, queueSort, v.queueSort)\n\t}\n\tif !cmp.Equal(v.queueSortArgs, queueSortArgs) {\n\t\treturn fmt.Errorf(\"different queue sort plugin args for profile %q\", cfg.SchedulerName)\n\t}\n\treturn nil\n}","line":{"from":85,"to":116}} {"id":100011391,"name":"scheduleOne","signature":"func (sched *Scheduler) scheduleOne(ctx context.Context)","file":"pkg/scheduler/schedule_one.go","code":"// scheduleOne does the entire scheduling workflow for a single pod. It is serialized on the scheduling algorithm's host fitting.\nfunc (sched *Scheduler) scheduleOne(ctx context.Context) {\n\tpodInfo := sched.NextPod()\n\t// pod could be nil when schedulerQueue is closed\n\tif podInfo == nil || podInfo.Pod == nil {\n\t\treturn\n\t}\n\tpod := podInfo.Pod\n\tfwk, err := sched.frameworkForPod(pod)\n\tif err != nil {\n\t\t// This shouldn't happen, because we only accept for scheduling the pods\n\t\t// which specify a scheduler name that matches one of the profiles.\n\t\tklog.ErrorS(err, \"Error occurred\")\n\t\treturn\n\t}\n\tif sched.skipPodSchedule(fwk, pod) {\n\t\treturn\n\t}\n\n\tklog.V(3).InfoS(\"Attempting to schedule pod\", \"pod\", klog.KObj(pod))\n\n\t// Synchronously attempt to find a fit for the pod.\n\tstart := time.Now()\n\tstate := framework.NewCycleState()\n\tstate.SetRecordPluginMetrics(rand.Intn(100) \u003c pluginMetricsSamplePercent)\n\n\t// Initialize an empty podsToActivate struct, which will be filled up by plugins or stay empty.\n\tpodsToActivate := framework.NewPodsToActivate()\n\tstate.Write(framework.PodsToActivateKey, podsToActivate)\n\n\tschedulingCycleCtx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\tscheduleResult, assumedPodInfo, status := sched.schedulingCycle(schedulingCycleCtx, state, fwk, podInfo, start, podsToActivate)\n\tif !status.IsSuccess() {\n\t\tsched.FailureHandler(schedulingCycleCtx, fwk, assumedPodInfo, status, scheduleResult.nominatingInfo, start)\n\t\treturn\n\t}\n\n\t// bind the pod to its host asynchronously (we can do this b/c of the assumption step above).\n\tgo func() {\n\t\tbindingCycleCtx, cancel := context.WithCancel(ctx)\n\t\tdefer cancel()\n\n\t\tmetrics.SchedulerGoroutines.WithLabelValues(metrics.Binding).Inc()\n\t\tdefer metrics.SchedulerGoroutines.WithLabelValues(metrics.Binding).Dec()\n\t\tmetrics.Goroutines.WithLabelValues(metrics.Binding).Inc()\n\t\tdefer metrics.Goroutines.WithLabelValues(metrics.Binding).Dec()\n\n\t\tstatus := sched.bindingCycle(bindingCycleCtx, state, fwk, scheduleResult, assumedPodInfo, start, podsToActivate)\n\t\tif !status.IsSuccess() {\n\t\t\tsched.handleBindingCycleError(bindingCycleCtx, state, fwk, assumedPodInfo, start, scheduleResult, status)\n\t\t}\n\t}()\n}","line":{"from":61,"to":115}} {"id":100011392,"name":"schedulingCycle","signature":"func (sched *Scheduler) schedulingCycle(","file":"pkg/scheduler/schedule_one.go","code":"// schedulingCycle tries to schedule a single Pod.\nfunc (sched *Scheduler) schedulingCycle(\n\tctx context.Context,\n\tstate *framework.CycleState,\n\tfwk framework.Framework,\n\tpodInfo *framework.QueuedPodInfo,\n\tstart time.Time,\n\tpodsToActivate *framework.PodsToActivate,\n) (ScheduleResult, *framework.QueuedPodInfo, *framework.Status) {\n\tpod := podInfo.Pod\n\tscheduleResult, err := sched.SchedulePod(ctx, fwk, state, pod)\n\tif err != nil {\n\t\tif err == ErrNoNodesAvailable {\n\t\t\tstatus := framework.NewStatus(framework.UnschedulableAndUnresolvable).WithError(err)\n\t\t\treturn ScheduleResult{nominatingInfo: clearNominatedNode}, podInfo, status\n\t\t}\n\n\t\tfitError, ok := err.(*framework.FitError)\n\t\tif !ok {\n\t\t\tklog.ErrorS(err, \"Error selecting node for pod\", \"pod\", klog.KObj(pod))\n\t\t\treturn ScheduleResult{nominatingInfo: clearNominatedNode}, podInfo, framework.AsStatus(err)\n\t\t}\n\n\t\t// SchedulePod() may have failed because the pod would not fit on any host, so we try to\n\t\t// preempt, with the expectation that the next time the pod is tried for scheduling it\n\t\t// will fit due to the preemption. It is also possible that a different pod will schedule\n\t\t// into the resources that were preempted, but this is harmless.\n\n\t\tif !fwk.HasPostFilterPlugins() {\n\t\t\tklog.V(3).InfoS(\"No PostFilter plugins are registered, so no preemption will be performed\")\n\t\t\treturn ScheduleResult{}, podInfo, framework.NewStatus(framework.Unschedulable).WithError(err)\n\t\t}\n\n\t\t// Run PostFilter plugins to attempt to make the pod schedulable in a future scheduling cycle.\n\t\tresult, status := fwk.RunPostFilterPlugins(ctx, state, pod, fitError.Diagnosis.NodeToStatusMap)\n\t\tmsg := status.Message()\n\t\tfitError.Diagnosis.PostFilterMsg = msg\n\t\tif status.Code() == framework.Error {\n\t\t\tklog.ErrorS(nil, \"Status after running PostFilter plugins for pod\", \"pod\", klog.KObj(pod), \"status\", msg)\n\t\t} else {\n\t\t\tklog.V(5).InfoS(\"Status after running PostFilter plugins for pod\", \"pod\", klog.KObj(pod), \"status\", msg)\n\t\t}\n\n\t\tvar nominatingInfo *framework.NominatingInfo\n\t\tif result != nil {\n\t\t\tnominatingInfo = result.NominatingInfo\n\t\t}\n\t\treturn ScheduleResult{nominatingInfo: nominatingInfo}, podInfo, framework.NewStatus(framework.Unschedulable).WithError(err)\n\t}\n\n\tmetrics.SchedulingAlgorithmLatency.Observe(metrics.SinceInSeconds(start))\n\t// Tell the cache to assume that a pod now is running on a given node, even though it hasn't been bound yet.\n\t// This allows us to keep scheduling without waiting on binding to occur.\n\tassumedPodInfo := podInfo.DeepCopy()\n\tassumedPod := assumedPodInfo.Pod\n\t// assume modifies `assumedPod` by setting NodeName=scheduleResult.SuggestedHost\n\terr = sched.assume(assumedPod, scheduleResult.SuggestedHost)\n\tif err != nil {\n\t\t// This is most probably result of a BUG in retrying logic.\n\t\t// We report an error here so that pod scheduling can be retried.\n\t\t// This relies on the fact that Error will check if the pod has been bound\n\t\t// to a node and if so will not add it back to the unscheduled pods queue\n\t\t// (otherwise this would cause an infinite loop).\n\t\treturn ScheduleResult{nominatingInfo: clearNominatedNode},\n\t\t\tassumedPodInfo,\n\t\t\tframework.AsStatus(err)\n\t}\n\n\t// Run the Reserve method of reserve plugins.\n\tif sts := fwk.RunReservePluginsReserve(ctx, state, assumedPod, scheduleResult.SuggestedHost); !sts.IsSuccess() {\n\t\t// trigger un-reserve to clean up state associated with the reserved Pod\n\t\tfwk.RunReservePluginsUnreserve(ctx, state, assumedPod, scheduleResult.SuggestedHost)\n\t\tif forgetErr := sched.Cache.ForgetPod(assumedPod); forgetErr != nil {\n\t\t\tklog.ErrorS(forgetErr, \"Scheduler cache ForgetPod failed\")\n\t\t}\n\n\t\treturn ScheduleResult{nominatingInfo: clearNominatedNode},\n\t\t\tassumedPodInfo,\n\t\t\tsts\n\t}\n\n\t// Run \"permit\" plugins.\n\trunPermitStatus := fwk.RunPermitPlugins(ctx, state, assumedPod, scheduleResult.SuggestedHost)\n\tif !runPermitStatus.IsWait() \u0026\u0026 !runPermitStatus.IsSuccess() {\n\t\t// trigger un-reserve to clean up state associated with the reserved Pod\n\t\tfwk.RunReservePluginsUnreserve(ctx, state, assumedPod, scheduleResult.SuggestedHost)\n\t\tif forgetErr := sched.Cache.ForgetPod(assumedPod); forgetErr != nil {\n\t\t\tklog.ErrorS(forgetErr, \"Scheduler cache ForgetPod failed\")\n\t\t}\n\n\t\treturn ScheduleResult{nominatingInfo: clearNominatedNode},\n\t\t\tassumedPodInfo,\n\t\t\trunPermitStatus\n\t}\n\n\t// At the end of a successful scheduling cycle, pop and move up Pods if needed.\n\tif len(podsToActivate.Map) != 0 {\n\t\tsched.SchedulingQueue.Activate(podsToActivate.Map)\n\t\t// Clear the entries after activation.\n\t\tpodsToActivate.Map = make(map[string]*v1.Pod)\n\t}\n\n\treturn scheduleResult, assumedPodInfo, nil\n}","line":{"from":119,"to":222}} {"id":100011393,"name":"bindingCycle","signature":"func (sched *Scheduler) bindingCycle(","file":"pkg/scheduler/schedule_one.go","code":"// bindingCycle tries to bind an assumed Pod.\nfunc (sched *Scheduler) bindingCycle(\n\tctx context.Context,\n\tstate *framework.CycleState,\n\tfwk framework.Framework,\n\tscheduleResult ScheduleResult,\n\tassumedPodInfo *framework.QueuedPodInfo,\n\tstart time.Time,\n\tpodsToActivate *framework.PodsToActivate) *framework.Status {\n\n\tassumedPod := assumedPodInfo.Pod\n\n\t// Run \"permit\" plugins.\n\tif status := fwk.WaitOnPermit(ctx, assumedPod); !status.IsSuccess() {\n\t\treturn status\n\t}\n\n\t// Run \"prebind\" plugins.\n\tif status := fwk.RunPreBindPlugins(ctx, state, assumedPod, scheduleResult.SuggestedHost); !status.IsSuccess() {\n\t\treturn status\n\t}\n\n\t// Run \"bind\" plugins.\n\tif status := sched.bind(ctx, fwk, assumedPod, scheduleResult.SuggestedHost, state); !status.IsSuccess() {\n\t\treturn status\n\t}\n\n\t// Calculating nodeResourceString can be heavy. Avoid it if klog verbosity is below 2.\n\tklog.V(2).InfoS(\"Successfully bound pod to node\", \"pod\", klog.KObj(assumedPod), \"node\", scheduleResult.SuggestedHost, \"evaluatedNodes\", scheduleResult.EvaluatedNodes, \"feasibleNodes\", scheduleResult.FeasibleNodes)\n\tmetrics.PodScheduled(fwk.ProfileName(), metrics.SinceInSeconds(start))\n\tmetrics.PodSchedulingAttempts.Observe(float64(assumedPodInfo.Attempts))\n\tif assumedPodInfo.InitialAttemptTimestamp != nil {\n\t\tmetrics.PodSchedulingDuration.WithLabelValues(getAttemptsLabel(assumedPodInfo)).Observe(metrics.SinceInSeconds(*assumedPodInfo.InitialAttemptTimestamp))\n\t}\n\t// Run \"postbind\" plugins.\n\tfwk.RunPostBindPlugins(ctx, state, assumedPod, scheduleResult.SuggestedHost)\n\n\t// At the end of a successful binding cycle, move up Pods if needed.\n\tif len(podsToActivate.Map) != 0 {\n\t\tsched.SchedulingQueue.Activate(podsToActivate.Map)\n\t\t// Unlike the logic in schedulingCycle(), we don't bother deleting the entries\n\t\t// as `podsToActivate.Map` is no longer consumed.\n\t}\n\n\treturn nil\n}","line":{"from":224,"to":269}} {"id":100011394,"name":"handleBindingCycleError","signature":"func (sched *Scheduler) handleBindingCycleError(","file":"pkg/scheduler/schedule_one.go","code":"func (sched *Scheduler) handleBindingCycleError(\n\tctx context.Context,\n\tstate *framework.CycleState,\n\tfwk framework.Framework,\n\tpodInfo *framework.QueuedPodInfo,\n\tstart time.Time,\n\tscheduleResult ScheduleResult,\n\tstatus *framework.Status) {\n\n\tassumedPod := podInfo.Pod\n\t// trigger un-reserve plugins to clean up state associated with the reserved Pod\n\tfwk.RunReservePluginsUnreserve(ctx, state, assumedPod, scheduleResult.SuggestedHost)\n\tif forgetErr := sched.Cache.ForgetPod(assumedPod); forgetErr != nil {\n\t\tklog.ErrorS(forgetErr, \"scheduler cache ForgetPod failed\")\n\t} else {\n\t\t// \"Forget\"ing an assumed Pod in binding cycle should be treated as a PodDelete event,\n\t\t// as the assumed Pod had occupied a certain amount of resources in scheduler cache.\n\t\t//\n\t\t// Avoid moving the assumed Pod itself as it's always Unschedulable.\n\t\t// It's intentional to \"defer\" this operation; otherwise MoveAllToActiveOrBackoffQueue() would\n\t\t// update `q.moveRequest` and thus move the assumed pod to backoffQ anyways.\n\t\tif status.IsUnschedulable() {\n\t\t\tdefer sched.SchedulingQueue.MoveAllToActiveOrBackoffQueue(internalqueue.AssignedPodDelete, func(pod *v1.Pod) bool {\n\t\t\t\treturn assumedPod.UID != pod.UID\n\t\t\t})\n\t\t} else {\n\t\t\tsched.SchedulingQueue.MoveAllToActiveOrBackoffQueue(internalqueue.AssignedPodDelete, nil)\n\t\t}\n\t}\n\n\tsched.FailureHandler(ctx, fwk, podInfo, status, clearNominatedNode, start)\n}","line":{"from":271,"to":302}} {"id":100011395,"name":"frameworkForPod","signature":"func (sched *Scheduler) frameworkForPod(pod *v1.Pod) (framework.Framework, error)","file":"pkg/scheduler/schedule_one.go","code":"func (sched *Scheduler) frameworkForPod(pod *v1.Pod) (framework.Framework, error) {\n\tfwk, ok := sched.Profiles[pod.Spec.SchedulerName]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"profile not found for scheduler name %q\", pod.Spec.SchedulerName)\n\t}\n\treturn fwk, nil\n}","line":{"from":304,"to":310}} {"id":100011396,"name":"skipPodSchedule","signature":"func (sched *Scheduler) skipPodSchedule(fwk framework.Framework, pod *v1.Pod) bool","file":"pkg/scheduler/schedule_one.go","code":"// skipPodSchedule returns true if we could skip scheduling the pod for specified cases.\nfunc (sched *Scheduler) skipPodSchedule(fwk framework.Framework, pod *v1.Pod) bool {\n\t// Case 1: pod is being deleted.\n\tif pod.DeletionTimestamp != nil {\n\t\tfwk.EventRecorder().Eventf(pod, nil, v1.EventTypeWarning, \"FailedScheduling\", \"Scheduling\", \"skip schedule deleting pod: %v/%v\", pod.Namespace, pod.Name)\n\t\tklog.V(3).InfoS(\"Skip schedule deleting pod\", \"pod\", klog.KObj(pod))\n\t\treturn true\n\t}\n\n\t// Case 2: pod that has been assumed could be skipped.\n\t// An assumed pod can be added again to the scheduling queue if it got an update event\n\t// during its previous scheduling cycle but before getting assumed.\n\tisAssumed, err := sched.Cache.IsAssumedPod(pod)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"failed to check whether pod %s/%s is assumed: %v\", pod.Namespace, pod.Name, err))\n\t\treturn false\n\t}\n\treturn isAssumed\n}","line":{"from":312,"to":330}} {"id":100011397,"name":"schedulePod","signature":"func (sched *Scheduler) schedulePod(ctx context.Context, fwk framework.Framework, state *framework.CycleState, pod *v1.Pod) (result ScheduleResult, err error)","file":"pkg/scheduler/schedule_one.go","code":"// schedulePod tries to schedule the given pod to one of the nodes in the node list.\n// If it succeeds, it will return the name of the node.\n// If it fails, it will return a FitError with reasons.\nfunc (sched *Scheduler) schedulePod(ctx context.Context, fwk framework.Framework, state *framework.CycleState, pod *v1.Pod) (result ScheduleResult, err error) {\n\ttrace := utiltrace.New(\"Scheduling\", utiltrace.Field{Key: \"namespace\", Value: pod.Namespace}, utiltrace.Field{Key: \"name\", Value: pod.Name})\n\tdefer trace.LogIfLong(100 * time.Millisecond)\n\n\tif err := sched.Cache.UpdateSnapshot(sched.nodeInfoSnapshot); err != nil {\n\t\treturn result, err\n\t}\n\ttrace.Step(\"Snapshotting scheduler cache and node infos done\")\n\n\tif sched.nodeInfoSnapshot.NumNodes() == 0 {\n\t\treturn result, ErrNoNodesAvailable\n\t}\n\n\tfeasibleNodes, diagnosis, err := sched.findNodesThatFitPod(ctx, fwk, state, pod)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\ttrace.Step(\"Computing predicates done\")\n\n\tif len(feasibleNodes) == 0 {\n\t\treturn result, \u0026framework.FitError{\n\t\t\tPod: pod,\n\t\t\tNumAllNodes: sched.nodeInfoSnapshot.NumNodes(),\n\t\t\tDiagnosis: diagnosis,\n\t\t}\n\t}\n\n\t// When only one node after predicate, just use it.\n\tif len(feasibleNodes) == 1 {\n\t\treturn ScheduleResult{\n\t\t\tSuggestedHost: feasibleNodes[0].Name,\n\t\t\tEvaluatedNodes: 1 + len(diagnosis.NodeToStatusMap),\n\t\t\tFeasibleNodes: 1,\n\t\t}, nil\n\t}\n\n\tpriorityList, err := prioritizeNodes(ctx, sched.Extenders, fwk, state, pod, feasibleNodes)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\n\thost, err := selectHost(priorityList)\n\ttrace.Step(\"Prioritizing done\")\n\n\treturn ScheduleResult{\n\t\tSuggestedHost: host,\n\t\tEvaluatedNodes: len(feasibleNodes) + len(diagnosis.NodeToStatusMap),\n\t\tFeasibleNodes: len(feasibleNodes),\n\t}, err\n}","line":{"from":332,"to":384}} {"id":100011398,"name":"findNodesThatFitPod","signature":"func (sched *Scheduler) findNodesThatFitPod(ctx context.Context, fwk framework.Framework, state *framework.CycleState, pod *v1.Pod) ([]*v1.Node, framework.Diagnosis, error)","file":"pkg/scheduler/schedule_one.go","code":"// Filters the nodes to find the ones that fit the pod based on the framework\n// filter plugins and filter extenders.\nfunc (sched *Scheduler) findNodesThatFitPod(ctx context.Context, fwk framework.Framework, state *framework.CycleState, pod *v1.Pod) ([]*v1.Node, framework.Diagnosis, error) {\n\tdiagnosis := framework.Diagnosis{\n\t\tNodeToStatusMap: make(framework.NodeToStatusMap),\n\t\tUnschedulablePlugins: sets.NewString(),\n\t}\n\n\tallNodes, err := sched.nodeInfoSnapshot.NodeInfos().List()\n\tif err != nil {\n\t\treturn nil, diagnosis, err\n\t}\n\t// Run \"prefilter\" plugins.\n\tpreRes, s := fwk.RunPreFilterPlugins(ctx, state, pod)\n\tif !s.IsSuccess() {\n\t\tif !s.IsUnschedulable() {\n\t\t\treturn nil, diagnosis, s.AsError()\n\t\t}\n\t\t// Record the messages from PreFilter in Diagnosis.PreFilterMsg.\n\t\tmsg := s.Message()\n\t\tdiagnosis.PreFilterMsg = msg\n\t\tklog.V(5).InfoS(\"Status after running PreFilter plugins for pod\", \"pod\", klog.KObj(pod), \"status\", msg)\n\t\t// Status satisfying IsUnschedulable() gets injected into diagnosis.UnschedulablePlugins.\n\t\tif s.FailedPlugin() != \"\" {\n\t\t\tdiagnosis.UnschedulablePlugins.Insert(s.FailedPlugin())\n\t\t}\n\t\treturn nil, diagnosis, nil\n\t}\n\n\t// \"NominatedNodeName\" can potentially be set in a previous scheduling cycle as a result of preemption.\n\t// This node is likely the only candidate that will fit the pod, and hence we try it first before iterating over all nodes.\n\tif len(pod.Status.NominatedNodeName) \u003e 0 {\n\t\tfeasibleNodes, err := sched.evaluateNominatedNode(ctx, pod, fwk, state, diagnosis)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Evaluation failed on nominated node\", \"pod\", klog.KObj(pod), \"node\", pod.Status.NominatedNodeName)\n\t\t}\n\t\t// Nominated node passes all the filters, scheduler is good to assign this node to the pod.\n\t\tif len(feasibleNodes) != 0 {\n\t\t\treturn feasibleNodes, diagnosis, nil\n\t\t}\n\t}\n\n\tnodes := allNodes\n\tif !preRes.AllNodes() {\n\t\tnodes = make([]*framework.NodeInfo, 0, len(preRes.NodeNames))\n\t\tfor n := range preRes.NodeNames {\n\t\t\tnInfo, err := sched.nodeInfoSnapshot.NodeInfos().Get(n)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, diagnosis, err\n\t\t\t}\n\t\t\tnodes = append(nodes, nInfo)\n\t\t}\n\t}\n\tfeasibleNodes, err := sched.findNodesThatPassFilters(ctx, fwk, state, pod, diagnosis, nodes)\n\t// always try to update the sched.nextStartNodeIndex regardless of whether an error has occurred\n\t// this is helpful to make sure that all the nodes have a chance to be searched\n\tprocessedNodes := len(feasibleNodes) + len(diagnosis.NodeToStatusMap)\n\tsched.nextStartNodeIndex = (sched.nextStartNodeIndex + processedNodes) % len(nodes)\n\tif err != nil {\n\t\treturn nil, diagnosis, err\n\t}\n\n\tfeasibleNodes, err = findNodesThatPassExtenders(sched.Extenders, pod, feasibleNodes, diagnosis.NodeToStatusMap)\n\tif err != nil {\n\t\treturn nil, diagnosis, err\n\t}\n\treturn feasibleNodes, diagnosis, nil\n}","line":{"from":386,"to":453}} {"id":100011399,"name":"evaluateNominatedNode","signature":"func (sched *Scheduler) evaluateNominatedNode(ctx context.Context, pod *v1.Pod, fwk framework.Framework, state *framework.CycleState, diagnosis framework.Diagnosis) ([]*v1.Node, error)","file":"pkg/scheduler/schedule_one.go","code":"func (sched *Scheduler) evaluateNominatedNode(ctx context.Context, pod *v1.Pod, fwk framework.Framework, state *framework.CycleState, diagnosis framework.Diagnosis) ([]*v1.Node, error) {\n\tnnn := pod.Status.NominatedNodeName\n\tnodeInfo, err := sched.nodeInfoSnapshot.Get(nnn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnode := []*framework.NodeInfo{nodeInfo}\n\tfeasibleNodes, err := sched.findNodesThatPassFilters(ctx, fwk, state, pod, diagnosis, node)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfeasibleNodes, err = findNodesThatPassExtenders(sched.Extenders, pod, feasibleNodes, diagnosis.NodeToStatusMap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn feasibleNodes, nil\n}","line":{"from":455,"to":473}} {"id":100011400,"name":"findNodesThatPassFilters","signature":"func (sched *Scheduler) findNodesThatPassFilters(","file":"pkg/scheduler/schedule_one.go","code":"// findNodesThatPassFilters finds the nodes that fit the filter plugins.\nfunc (sched *Scheduler) findNodesThatPassFilters(\n\tctx context.Context,\n\tfwk framework.Framework,\n\tstate *framework.CycleState,\n\tpod *v1.Pod,\n\tdiagnosis framework.Diagnosis,\n\tnodes []*framework.NodeInfo) ([]*v1.Node, error) {\n\tnumAllNodes := len(nodes)\n\tnumNodesToFind := sched.numFeasibleNodesToFind(fwk.PercentageOfNodesToScore(), int32(numAllNodes))\n\n\t// Create feasible list with enough space to avoid growing it\n\t// and allow assigning.\n\tfeasibleNodes := make([]*v1.Node, numNodesToFind)\n\n\tif !fwk.HasFilterPlugins() {\n\t\tfor i := range feasibleNodes {\n\t\t\tfeasibleNodes[i] = nodes[(sched.nextStartNodeIndex+i)%numAllNodes].Node()\n\t\t}\n\t\treturn feasibleNodes, nil\n\t}\n\n\terrCh := parallelize.NewErrorChannel()\n\tvar statusesLock sync.Mutex\n\tvar feasibleNodesLen int32\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\tcheckNode := func(i int) {\n\t\t// We check the nodes starting from where we left off in the previous scheduling cycle,\n\t\t// this is to make sure all nodes have the same chance of being examined across pods.\n\t\tnodeInfo := nodes[(sched.nextStartNodeIndex+i)%numAllNodes]\n\t\tstatus := fwk.RunFilterPluginsWithNominatedPods(ctx, state, pod, nodeInfo)\n\t\tif status.Code() == framework.Error {\n\t\t\terrCh.SendErrorWithCancel(status.AsError(), cancel)\n\t\t\treturn\n\t\t}\n\t\tif status.IsSuccess() {\n\t\t\tlength := atomic.AddInt32(\u0026feasibleNodesLen, 1)\n\t\t\tif length \u003e numNodesToFind {\n\t\t\t\tcancel()\n\t\t\t\tatomic.AddInt32(\u0026feasibleNodesLen, -1)\n\t\t\t} else {\n\t\t\t\tfeasibleNodes[length-1] = nodeInfo.Node()\n\t\t\t}\n\t\t} else {\n\t\t\tstatusesLock.Lock()\n\t\t\tdiagnosis.NodeToStatusMap[nodeInfo.Node().Name] = status\n\t\t\tdiagnosis.UnschedulablePlugins.Insert(status.FailedPlugin())\n\t\t\tstatusesLock.Unlock()\n\t\t}\n\t}\n\n\tbeginCheckNode := time.Now()\n\tstatusCode := framework.Success\n\tdefer func() {\n\t\t// We record Filter extension point latency here instead of in framework.go because framework.RunFilterPlugins\n\t\t// function is called for each node, whereas we want to have an overall latency for all nodes per scheduling cycle.\n\t\t// Note that this latency also includes latency for `addNominatedPods`, which calls framework.RunPreFilterAddPod.\n\t\tmetrics.FrameworkExtensionPointDuration.WithLabelValues(metrics.Filter, statusCode.String(), fwk.ProfileName()).Observe(metrics.SinceInSeconds(beginCheckNode))\n\t}()\n\n\t// Stops searching for more nodes once the configured number of feasible nodes\n\t// are found.\n\tfwk.Parallelizer().Until(ctx, numAllNodes, checkNode, metrics.Filter)\n\tfeasibleNodes = feasibleNodes[:feasibleNodesLen]\n\tif err := errCh.ReceiveError(); err != nil {\n\t\tstatusCode = framework.Error\n\t\treturn feasibleNodes, err\n\t}\n\treturn feasibleNodes, nil\n}","line":{"from":475,"to":545}} {"id":100011401,"name":"numFeasibleNodesToFind","signature":"func (sched *Scheduler) numFeasibleNodesToFind(percentageOfNodesToScore *int32, numAllNodes int32) (numNodes int32)","file":"pkg/scheduler/schedule_one.go","code":"// numFeasibleNodesToFind returns the number of feasible nodes that once found, the scheduler stops\n// its search for more feasible nodes.\nfunc (sched *Scheduler) numFeasibleNodesToFind(percentageOfNodesToScore *int32, numAllNodes int32) (numNodes int32) {\n\tif numAllNodes \u003c minFeasibleNodesToFind {\n\t\treturn numAllNodes\n\t}\n\n\t// Use profile percentageOfNodesToScore if it's set. Otherwise, use global percentageOfNodesToScore.\n\tvar percentage int32\n\tif percentageOfNodesToScore != nil {\n\t\tpercentage = *percentageOfNodesToScore\n\t} else {\n\t\tpercentage = sched.percentageOfNodesToScore\n\t}\n\n\tif percentage == 0 {\n\t\tpercentage = int32(50) - numAllNodes/125\n\t\tif percentage \u003c minFeasibleNodesPercentageToFind {\n\t\t\tpercentage = minFeasibleNodesPercentageToFind\n\t\t}\n\t}\n\n\tnumNodes = numAllNodes * percentage / 100\n\tif numNodes \u003c minFeasibleNodesToFind {\n\t\treturn minFeasibleNodesToFind\n\t}\n\n\treturn numNodes\n}","line":{"from":547,"to":575}} {"id":100011402,"name":"findNodesThatPassExtenders","signature":"func findNodesThatPassExtenders(extenders []framework.Extender, pod *v1.Pod, feasibleNodes []*v1.Node, statuses framework.NodeToStatusMap) ([]*v1.Node, error)","file":"pkg/scheduler/schedule_one.go","code":"func findNodesThatPassExtenders(extenders []framework.Extender, pod *v1.Pod, feasibleNodes []*v1.Node, statuses framework.NodeToStatusMap) ([]*v1.Node, error) {\n\t// Extenders are called sequentially.\n\t// Nodes in original feasibleNodes can be excluded in one extender, and pass on to the next\n\t// extender in a decreasing manner.\n\tfor _, extender := range extenders {\n\t\tif len(feasibleNodes) == 0 {\n\t\t\tbreak\n\t\t}\n\t\tif !extender.IsInterested(pod) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Status of failed nodes in failedAndUnresolvableMap will be added or overwritten in \u003cstatuses\u003e,\n\t\t// so that the scheduler framework can respect the UnschedulableAndUnresolvable status for\n\t\t// particular nodes, and this may eventually improve preemption efficiency.\n\t\t// Note: users are recommended to configure the extenders that may return UnschedulableAndUnresolvable\n\t\t// status ahead of others.\n\t\tfeasibleList, failedMap, failedAndUnresolvableMap, err := extender.Filter(pod, feasibleNodes)\n\t\tif err != nil {\n\t\t\tif extender.IsIgnorable() {\n\t\t\t\tklog.InfoS(\"Skipping extender as it returned error and has ignorable flag set\", \"extender\", extender, \"err\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor failedNodeName, failedMsg := range failedAndUnresolvableMap {\n\t\t\tvar aggregatedReasons []string\n\t\t\tif _, found := statuses[failedNodeName]; found {\n\t\t\t\taggregatedReasons = statuses[failedNodeName].Reasons()\n\t\t\t}\n\t\t\taggregatedReasons = append(aggregatedReasons, failedMsg)\n\t\t\tstatuses[failedNodeName] = framework.NewStatus(framework.UnschedulableAndUnresolvable, aggregatedReasons...)\n\t\t}\n\n\t\tfor failedNodeName, failedMsg := range failedMap {\n\t\t\tif _, found := failedAndUnresolvableMap[failedNodeName]; found {\n\t\t\t\t// failedAndUnresolvableMap takes precedence over failedMap\n\t\t\t\t// note that this only happens if the extender returns the node in both maps\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif _, found := statuses[failedNodeName]; !found {\n\t\t\t\tstatuses[failedNodeName] = framework.NewStatus(framework.Unschedulable, failedMsg)\n\t\t\t} else {\n\t\t\t\tstatuses[failedNodeName].AppendReason(failedMsg)\n\t\t\t}\n\t\t}\n\n\t\tfeasibleNodes = feasibleList\n\t}\n\treturn feasibleNodes, nil\n}","line":{"from":577,"to":628}} {"id":100011403,"name":"prioritizeNodes","signature":"func prioritizeNodes(","file":"pkg/scheduler/schedule_one.go","code":"// prioritizeNodes prioritizes the nodes by running the score plugins,\n// which return a score for each node from the call to RunScorePlugins().\n// The scores from each plugin are added together to make the score for that node, then\n// any extenders are run as well.\n// All scores are finally combined (added) to get the total weighted scores of all nodes\nfunc prioritizeNodes(\n\tctx context.Context,\n\textenders []framework.Extender,\n\tfwk framework.Framework,\n\tstate *framework.CycleState,\n\tpod *v1.Pod,\n\tnodes []*v1.Node,\n) ([]framework.NodePluginScores, error) {\n\t// If no priority configs are provided, then all nodes will have a score of one.\n\t// This is required to generate the priority list in the required format\n\tif len(extenders) == 0 \u0026\u0026 !fwk.HasScorePlugins() {\n\t\tresult := make([]framework.NodePluginScores, 0, len(nodes))\n\t\tfor i := range nodes {\n\t\t\tresult = append(result, framework.NodePluginScores{\n\t\t\t\tName: nodes[i].Name,\n\t\t\t\tTotalScore: 1,\n\t\t\t})\n\t\t}\n\t\treturn result, nil\n\t}\n\n\t// Run PreScore plugins.\n\tpreScoreStatus := fwk.RunPreScorePlugins(ctx, state, pod, nodes)\n\tif !preScoreStatus.IsSuccess() {\n\t\treturn nil, preScoreStatus.AsError()\n\t}\n\n\t// Run the Score plugins.\n\tnodesScores, scoreStatus := fwk.RunScorePlugins(ctx, state, pod, nodes)\n\tif !scoreStatus.IsSuccess() {\n\t\treturn nil, scoreStatus.AsError()\n\t}\n\n\t// Additional details logged at level 10 if enabled.\n\tklogV := klog.V(10)\n\tif klogV.Enabled() {\n\t\tfor _, nodeScore := range nodesScores {\n\t\t\tfor _, pluginScore := range nodeScore.Scores {\n\t\t\t\tklogV.InfoS(\"Plugin scored node for pod\", \"pod\", klog.KObj(pod), \"plugin\", pluginScore.Name, \"node\", nodeScore.Name, \"score\", pluginScore.Score)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(extenders) != 0 \u0026\u0026 nodes != nil {\n\t\t// allNodeExtendersScores has all extenders scores for all nodes.\n\t\t// It is keyed with node name.\n\t\tallNodeExtendersScores := make(map[string]*framework.NodePluginScores, len(nodes))\n\t\tvar mu sync.Mutex\n\t\tvar wg sync.WaitGroup\n\t\tfor i := range extenders {\n\t\t\tif !extenders[i].IsInterested(pod) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\twg.Add(1)\n\t\t\tgo func(extIndex int) {\n\t\t\t\tmetrics.SchedulerGoroutines.WithLabelValues(metrics.PrioritizingExtender).Inc()\n\t\t\t\tmetrics.Goroutines.WithLabelValues(metrics.PrioritizingExtender).Inc()\n\t\t\t\tdefer func() {\n\t\t\t\t\tmetrics.SchedulerGoroutines.WithLabelValues(metrics.PrioritizingExtender).Dec()\n\t\t\t\t\tmetrics.Goroutines.WithLabelValues(metrics.PrioritizingExtender).Dec()\n\t\t\t\t\twg.Done()\n\t\t\t\t}()\n\t\t\t\tprioritizedList, weight, err := extenders[extIndex].Prioritize(pod, nodes)\n\t\t\t\tif err != nil {\n\t\t\t\t\t// Prioritization errors from extender can be ignored, let k8s/other extenders determine the priorities\n\t\t\t\t\tklog.V(5).InfoS(\"Failed to run extender's priority function. No score given by this extender.\", \"error\", err, \"pod\", klog.KObj(pod), \"extender\", extenders[extIndex].Name())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tmu.Lock()\n\t\t\t\tdefer mu.Unlock()\n\t\t\t\tfor i := range *prioritizedList {\n\t\t\t\t\tnodename := (*prioritizedList)[i].Host\n\t\t\t\t\tscore := (*prioritizedList)[i].Score\n\t\t\t\t\tif klogV.Enabled() {\n\t\t\t\t\t\tklogV.InfoS(\"Extender scored node for pod\", \"pod\", klog.KObj(pod), \"extender\", extenders[extIndex].Name(), \"node\", nodename, \"score\", score)\n\t\t\t\t\t}\n\n\t\t\t\t\t// MaxExtenderPriority may diverge from the max priority used in the scheduler and defined by MaxNodeScore,\n\t\t\t\t\t// therefore we need to scale the score returned by extenders to the score range used by the scheduler.\n\t\t\t\t\tfinalscore := score * weight * (framework.MaxNodeScore / extenderv1.MaxExtenderPriority)\n\n\t\t\t\t\tif allNodeExtendersScores[nodename] == nil {\n\t\t\t\t\t\tallNodeExtendersScores[nodename] = \u0026framework.NodePluginScores{\n\t\t\t\t\t\t\tName: nodename,\n\t\t\t\t\t\t\tScores: make([]framework.PluginScore, 0, len(extenders)),\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tallNodeExtendersScores[nodename].Scores = append(allNodeExtendersScores[nodename].Scores, framework.PluginScore{\n\t\t\t\t\t\tName: extenders[extIndex].Name(),\n\t\t\t\t\t\tScore: finalscore,\n\t\t\t\t\t})\n\t\t\t\t\tallNodeExtendersScores[nodename].TotalScore += finalscore\n\t\t\t\t}\n\t\t\t}(i)\n\t\t}\n\t\t// wait for all go routines to finish\n\t\twg.Wait()\n\t\tfor i := range nodesScores {\n\t\t\tif score, ok := allNodeExtendersScores[nodes[i].Name]; ok {\n\t\t\t\tnodesScores[i].Scores = append(nodesScores[i].Scores, score.Scores...)\n\t\t\t\tnodesScores[i].TotalScore += score.TotalScore\n\t\t\t}\n\t\t}\n\t}\n\n\tif klogV.Enabled() {\n\t\tfor i := range nodesScores {\n\t\t\tklogV.InfoS(\"Calculated node's final score for pod\", \"pod\", klog.KObj(pod), \"node\", nodesScores[i].Name, \"score\", nodesScores[i].TotalScore)\n\t\t}\n\t}\n\treturn nodesScores, nil\n}","line":{"from":630,"to":746}} {"id":100011404,"name":"selectHost","signature":"func selectHost(nodeScores []framework.NodePluginScores) (string, error)","file":"pkg/scheduler/schedule_one.go","code":"// selectHost takes a prioritized list of nodes and then picks one\n// in a reservoir sampling manner from the nodes that had the highest score.\nfunc selectHost(nodeScores []framework.NodePluginScores) (string, error) {\n\tif len(nodeScores) == 0 {\n\t\treturn \"\", fmt.Errorf(\"empty priorityList\")\n\t}\n\tmaxScore := nodeScores[0].TotalScore\n\tselected := nodeScores[0].Name\n\tcntOfMaxScore := 1\n\tfor _, ns := range nodeScores[1:] {\n\t\tif ns.TotalScore \u003e maxScore {\n\t\t\tmaxScore = ns.TotalScore\n\t\t\tselected = ns.Name\n\t\t\tcntOfMaxScore = 1\n\t\t} else if ns.TotalScore == maxScore {\n\t\t\tcntOfMaxScore++\n\t\t\tif rand.Intn(cntOfMaxScore) == 0 {\n\t\t\t\t// Replace the candidate with probability of 1/cntOfMaxScore\n\t\t\t\tselected = ns.Name\n\t\t\t}\n\t\t}\n\t}\n\treturn selected, nil\n}","line":{"from":748,"to":771}} {"id":100011405,"name":"assume","signature":"func (sched *Scheduler) assume(assumed *v1.Pod, host string) error","file":"pkg/scheduler/schedule_one.go","code":"// assume signals to the cache that a pod is already in the cache, so that binding can be asynchronous.\n// assume modifies `assumed`.\nfunc (sched *Scheduler) assume(assumed *v1.Pod, host string) error {\n\t// Optimistically assume that the binding will succeed and send it to apiserver\n\t// in the background.\n\t// If the binding fails, scheduler will release resources allocated to assumed pod\n\t// immediately.\n\tassumed.Spec.NodeName = host\n\n\tif err := sched.Cache.AssumePod(assumed); err != nil {\n\t\tklog.ErrorS(err, \"Scheduler cache AssumePod failed\")\n\t\treturn err\n\t}\n\t// if \"assumed\" is a nominated pod, we should remove it from internal cache\n\tif sched.SchedulingQueue != nil {\n\t\tsched.SchedulingQueue.DeleteNominatedPodIfExists(assumed)\n\t}\n\n\treturn nil\n}","line":{"from":773,"to":792}} {"id":100011406,"name":"bind","signature":"func (sched *Scheduler) bind(ctx context.Context, fwk framework.Framework, assumed *v1.Pod, targetNode string, state *framework.CycleState) (status *framework.Status)","file":"pkg/scheduler/schedule_one.go","code":"// bind binds a pod to a given node defined in a binding object.\n// The precedence for binding is: (1) extenders and (2) framework plugins.\n// We expect this to run asynchronously, so we handle binding metrics internally.\nfunc (sched *Scheduler) bind(ctx context.Context, fwk framework.Framework, assumed *v1.Pod, targetNode string, state *framework.CycleState) (status *framework.Status) {\n\tdefer func() {\n\t\tsched.finishBinding(fwk, assumed, targetNode, status)\n\t}()\n\n\tbound, err := sched.extendersBinding(assumed, targetNode)\n\tif bound {\n\t\treturn framework.AsStatus(err)\n\t}\n\treturn fwk.RunBindPlugins(ctx, state, assumed, targetNode)\n}","line":{"from":794,"to":807}} {"id":100011407,"name":"extendersBinding","signature":"func (sched *Scheduler) extendersBinding(pod *v1.Pod, node string) (bool, error)","file":"pkg/scheduler/schedule_one.go","code":"// TODO(#87159): Move this to a Plugin.\nfunc (sched *Scheduler) extendersBinding(pod *v1.Pod, node string) (bool, error) {\n\tfor _, extender := range sched.Extenders {\n\t\tif !extender.IsBinder() || !extender.IsInterested(pod) {\n\t\t\tcontinue\n\t\t}\n\t\treturn true, extender.Bind(\u0026v1.Binding{\n\t\t\tObjectMeta: metav1.ObjectMeta{Namespace: pod.Namespace, Name: pod.Name, UID: pod.UID},\n\t\t\tTarget: v1.ObjectReference{Kind: \"Node\", Name: node},\n\t\t})\n\t}\n\treturn false, nil\n}","line":{"from":809,"to":821}} {"id":100011408,"name":"finishBinding","signature":"func (sched *Scheduler) finishBinding(fwk framework.Framework, assumed *v1.Pod, targetNode string, status *framework.Status)","file":"pkg/scheduler/schedule_one.go","code":"func (sched *Scheduler) finishBinding(fwk framework.Framework, assumed *v1.Pod, targetNode string, status *framework.Status) {\n\tif finErr := sched.Cache.FinishBinding(assumed); finErr != nil {\n\t\tklog.ErrorS(finErr, \"Scheduler cache FinishBinding failed\")\n\t}\n\tif !status.IsSuccess() {\n\t\tklog.V(1).InfoS(\"Failed to bind pod\", \"pod\", klog.KObj(assumed))\n\t\treturn\n\t}\n\n\tfwk.EventRecorder().Eventf(assumed, nil, v1.EventTypeNormal, \"Scheduled\", \"Binding\", \"Successfully assigned %v/%v to %v\", assumed.Namespace, assumed.Name, targetNode)\n}","line":{"from":823,"to":833}} {"id":100011409,"name":"getAttemptsLabel","signature":"func getAttemptsLabel(p *framework.QueuedPodInfo) string","file":"pkg/scheduler/schedule_one.go","code":"func getAttemptsLabel(p *framework.QueuedPodInfo) string {\n\t// We breakdown the pod scheduling duration by attempts capped to a limit\n\t// to avoid ending up with a high cardinality metric.\n\tif p.Attempts \u003e= 15 {\n\t\treturn \"15+\"\n\t}\n\treturn strconv.Itoa(p.Attempts)\n}","line":{"from":835,"to":842}} {"id":100011410,"name":"handleSchedulingFailure","signature":"func (sched *Scheduler) handleSchedulingFailure(ctx context.Context, fwk framework.Framework, podInfo *framework.QueuedPodInfo, status *framework.Status, nominatingInfo *framework.NominatingInfo, start time.Time)","file":"pkg/scheduler/schedule_one.go","code":"// handleSchedulingFailure records an event for the pod that indicates the\n// pod has failed to schedule. Also, update the pod condition and nominated node name if set.\nfunc (sched *Scheduler) handleSchedulingFailure(ctx context.Context, fwk framework.Framework, podInfo *framework.QueuedPodInfo, status *framework.Status, nominatingInfo *framework.NominatingInfo, start time.Time) {\n\treason := v1.PodReasonSchedulerError\n\tif status.IsUnschedulable() {\n\t\treason = v1.PodReasonUnschedulable\n\t}\n\n\tswitch reason {\n\tcase v1.PodReasonUnschedulable:\n\t\tmetrics.PodUnschedulable(fwk.ProfileName(), metrics.SinceInSeconds(start))\n\tcase v1.PodReasonSchedulerError:\n\t\tmetrics.PodScheduleError(fwk.ProfileName(), metrics.SinceInSeconds(start))\n\t}\n\n\tpod := podInfo.Pod\n\terr := status.AsError()\n\terrMsg := status.Message()\n\n\tif err == ErrNoNodesAvailable {\n\t\tklog.V(2).InfoS(\"Unable to schedule pod; no nodes are registered to the cluster; waiting\", \"pod\", klog.KObj(pod), \"err\", err)\n\t} else if fitError, ok := err.(*framework.FitError); ok {\n\t\t// Inject UnschedulablePlugins to PodInfo, which will be used later for moving Pods between queues efficiently.\n\t\tpodInfo.UnschedulablePlugins = fitError.Diagnosis.UnschedulablePlugins\n\t\tklog.V(2).InfoS(\"Unable to schedule pod; no fit; waiting\", \"pod\", klog.KObj(pod), \"err\", errMsg)\n\t} else if apierrors.IsNotFound(err) {\n\t\tklog.V(2).InfoS(\"Unable to schedule pod, possibly due to node not found; waiting\", \"pod\", klog.KObj(pod), \"err\", errMsg)\n\t\tif errStatus, ok := err.(apierrors.APIStatus); ok \u0026\u0026 errStatus.Status().Details.Kind == \"node\" {\n\t\t\tnodeName := errStatus.Status().Details.Name\n\t\t\t// when node is not found, We do not remove the node right away. Trying again to get\n\t\t\t// the node and if the node is still not found, then remove it from the scheduler cache.\n\t\t\t_, err := fwk.ClientSet().CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{})\n\t\t\tif err != nil \u0026\u0026 apierrors.IsNotFound(err) {\n\t\t\t\tnode := v1.Node{ObjectMeta: metav1.ObjectMeta{Name: nodeName}}\n\t\t\t\tif err := sched.Cache.RemoveNode(\u0026node); err != nil {\n\t\t\t\t\tklog.V(4).InfoS(\"Node is not found; failed to remove it from the cache\", \"node\", node.Name)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tklog.ErrorS(err, \"Error scheduling pod; retrying\", \"pod\", klog.KObj(pod))\n\t}\n\n\t// Check if the Pod exists in informer cache.\n\tpodLister := fwk.SharedInformerFactory().Core().V1().Pods().Lister()\n\tcachedPod, e := podLister.Pods(pod.Namespace).Get(pod.Name)\n\tif e != nil {\n\t\tklog.InfoS(\"Pod doesn't exist in informer cache\", \"pod\", klog.KObj(pod), \"err\", e)\n\t} else {\n\t\t// In the case of extender, the pod may have been bound successfully, but timed out returning its response to the scheduler.\n\t\t// It could result in the live version to carry .spec.nodeName, and that's inconsistent with the internal-queued version.\n\t\tif len(cachedPod.Spec.NodeName) != 0 {\n\t\t\tklog.InfoS(\"Pod has been assigned to node. Abort adding it back to queue.\", \"pod\", klog.KObj(pod), \"node\", cachedPod.Spec.NodeName)\n\t\t} else {\n\t\t\t// As \u003ccachedPod\u003e is from SharedInformer, we need to do a DeepCopy() here.\n\t\t\t// ignore this err since apiserver doesn't properly validate affinity terms\n\t\t\t// and we can't fix the validation for backwards compatibility.\n\t\t\tpodInfo.PodInfo, _ = framework.NewPodInfo(cachedPod.DeepCopy())\n\t\t\tif err := sched.SchedulingQueue.AddUnschedulableIfNotPresent(podInfo, sched.SchedulingQueue.SchedulingCycle()); err != nil {\n\t\t\t\tklog.ErrorS(err, \"Error occurred\")\n\t\t\t}\n\t\t}\n\t}\n\n\t// Update the scheduling queue with the nominated pod information. Without\n\t// this, there would be a race condition between the next scheduling cycle\n\t// and the time the scheduler receives a Pod Update for the nominated pod.\n\t// Here we check for nil only for tests.\n\tif sched.SchedulingQueue != nil {\n\t\tsched.SchedulingQueue.AddNominatedPod(podInfo.PodInfo, nominatingInfo)\n\t}\n\n\tif err == nil {\n\t\t// Only tests can reach here.\n\t\treturn\n\t}\n\n\tmsg := truncateMessage(errMsg)\n\tfwk.EventRecorder().Eventf(pod, nil, v1.EventTypeWarning, \"FailedScheduling\", \"Scheduling\", msg)\n\tif err := updatePod(ctx, sched.client, pod, \u0026v1.PodCondition{\n\t\tType: v1.PodScheduled,\n\t\tStatus: v1.ConditionFalse,\n\t\tReason: reason,\n\t\tMessage: errMsg,\n\t}, nominatingInfo); err != nil {\n\t\tklog.ErrorS(err, \"Error updating pod\", \"pod\", klog.KObj(pod))\n\t}\n}","line":{"from":844,"to":931}} {"id":100011411,"name":"truncateMessage","signature":"func truncateMessage(message string) string","file":"pkg/scheduler/schedule_one.go","code":"// truncateMessage truncates a message if it hits the NoteLengthLimit.\nfunc truncateMessage(message string) string {\n\tmax := validation.NoteLengthLimit\n\tif len(message) \u003c= max {\n\t\treturn message\n\t}\n\tsuffix := \" ...\"\n\treturn message[:max-len(suffix)] + suffix\n}","line":{"from":933,"to":941}} {"id":100011412,"name":"updatePod","signature":"func updatePod(ctx context.Context, client clientset.Interface, pod *v1.Pod, condition *v1.PodCondition, nominatingInfo *framework.NominatingInfo) error","file":"pkg/scheduler/schedule_one.go","code":"func updatePod(ctx context.Context, client clientset.Interface, pod *v1.Pod, condition *v1.PodCondition, nominatingInfo *framework.NominatingInfo) error {\n\tklog.V(3).InfoS(\"Updating pod condition\", \"pod\", klog.KObj(pod), \"conditionType\", condition.Type, \"conditionStatus\", condition.Status, \"conditionReason\", condition.Reason)\n\tpodStatusCopy := pod.Status.DeepCopy()\n\t// NominatedNodeName is updated only if we are trying to set it, and the value is\n\t// different from the existing one.\n\tnnnNeedsUpdate := nominatingInfo.Mode() == framework.ModeOverride \u0026\u0026 pod.Status.NominatedNodeName != nominatingInfo.NominatedNodeName\n\tif !podutil.UpdatePodCondition(podStatusCopy, condition) \u0026\u0026 !nnnNeedsUpdate {\n\t\treturn nil\n\t}\n\tif nnnNeedsUpdate {\n\t\tpodStatusCopy.NominatedNodeName = nominatingInfo.NominatedNodeName\n\t}\n\treturn util.PatchPodStatus(ctx, client, pod, podStatusCopy)\n}","line":{"from":943,"to":956}} {"id":100011413,"name":"applyDefaultHandlers","signature":"func (s *Scheduler) applyDefaultHandlers()","file":"pkg/scheduler/scheduler.go","code":"func (s *Scheduler) applyDefaultHandlers() {\n\ts.SchedulePod = s.schedulePod\n\ts.FailureHandler = s.handleSchedulingFailure\n}","line":{"from":101,"to":104}} {"id":100011414,"name":"WithComponentConfigVersion","signature":"func WithComponentConfigVersion(apiVersion string) Option","file":"pkg/scheduler/scheduler.go","code":"// WithComponentConfigVersion sets the component config version to the\n// KubeSchedulerConfiguration version used. The string should be the full\n// scheme group/version of the external type we converted from (for example\n// \"kubescheduler.config.k8s.io/v1\")\nfunc WithComponentConfigVersion(apiVersion string) Option {\n\treturn func(o *schedulerOptions) {\n\t\to.componentConfigVersion = apiVersion\n\t}\n}","line":{"from":139,"to":147}} {"id":100011415,"name":"WithKubeConfig","signature":"func WithKubeConfig(cfg *restclient.Config) Option","file":"pkg/scheduler/scheduler.go","code":"// WithKubeConfig sets the kube config for Scheduler.\nfunc WithKubeConfig(cfg *restclient.Config) Option {\n\treturn func(o *schedulerOptions) {\n\t\to.kubeConfig = cfg\n\t}\n}","line":{"from":149,"to":154}} {"id":100011416,"name":"WithProfiles","signature":"func WithProfiles(p ...schedulerapi.KubeSchedulerProfile) Option","file":"pkg/scheduler/scheduler.go","code":"// WithProfiles sets profiles for Scheduler. By default, there is one profile\n// with the name \"default-scheduler\".\nfunc WithProfiles(p ...schedulerapi.KubeSchedulerProfile) Option {\n\treturn func(o *schedulerOptions) {\n\t\to.profiles = p\n\t\to.applyDefaultProfile = false\n\t}\n}","line":{"from":156,"to":163}} {"id":100011417,"name":"WithParallelism","signature":"func WithParallelism(threads int32) Option","file":"pkg/scheduler/scheduler.go","code":"// WithParallelism sets the parallelism for all scheduler algorithms. Default is 16.\nfunc WithParallelism(threads int32) Option {\n\treturn func(o *schedulerOptions) {\n\t\to.parallelism = threads\n\t}\n}","line":{"from":165,"to":170}} {"id":100011418,"name":"WithPercentageOfNodesToScore","signature":"func WithPercentageOfNodesToScore(percentageOfNodesToScore *int32) Option","file":"pkg/scheduler/scheduler.go","code":"// WithPercentageOfNodesToScore sets percentageOfNodesToScore for Scheduler.\n// The default value of 0 will use an adaptive percentage: 50 - (num of nodes)/125.\nfunc WithPercentageOfNodesToScore(percentageOfNodesToScore *int32) Option {\n\treturn func(o *schedulerOptions) {\n\t\tif percentageOfNodesToScore != nil {\n\t\t\to.percentageOfNodesToScore = *percentageOfNodesToScore\n\t\t}\n\t}\n}","line":{"from":172,"to":180}} {"id":100011419,"name":"WithFrameworkOutOfTreeRegistry","signature":"func WithFrameworkOutOfTreeRegistry(registry frameworkruntime.Registry) Option","file":"pkg/scheduler/scheduler.go","code":"// WithFrameworkOutOfTreeRegistry sets the registry for out-of-tree plugins. Those plugins\n// will be appended to the default registry.\nfunc WithFrameworkOutOfTreeRegistry(registry frameworkruntime.Registry) Option {\n\treturn func(o *schedulerOptions) {\n\t\to.frameworkOutOfTreeRegistry = registry\n\t}\n}","line":{"from":182,"to":188}} {"id":100011420,"name":"WithPodInitialBackoffSeconds","signature":"func WithPodInitialBackoffSeconds(podInitialBackoffSeconds int64) Option","file":"pkg/scheduler/scheduler.go","code":"// WithPodInitialBackoffSeconds sets podInitialBackoffSeconds for Scheduler, the default value is 1\nfunc WithPodInitialBackoffSeconds(podInitialBackoffSeconds int64) Option {\n\treturn func(o *schedulerOptions) {\n\t\to.podInitialBackoffSeconds = podInitialBackoffSeconds\n\t}\n}","line":{"from":190,"to":195}} {"id":100011421,"name":"WithPodMaxBackoffSeconds","signature":"func WithPodMaxBackoffSeconds(podMaxBackoffSeconds int64) Option","file":"pkg/scheduler/scheduler.go","code":"// WithPodMaxBackoffSeconds sets podMaxBackoffSeconds for Scheduler, the default value is 10\nfunc WithPodMaxBackoffSeconds(podMaxBackoffSeconds int64) Option {\n\treturn func(o *schedulerOptions) {\n\t\to.podMaxBackoffSeconds = podMaxBackoffSeconds\n\t}\n}","line":{"from":197,"to":202}} {"id":100011422,"name":"WithPodMaxInUnschedulablePodsDuration","signature":"func WithPodMaxInUnschedulablePodsDuration(duration time.Duration) Option","file":"pkg/scheduler/scheduler.go","code":"// WithPodMaxInUnschedulablePodsDuration sets podMaxInUnschedulablePodsDuration for PriorityQueue.\nfunc WithPodMaxInUnschedulablePodsDuration(duration time.Duration) Option {\n\treturn func(o *schedulerOptions) {\n\t\to.podMaxInUnschedulablePodsDuration = duration\n\t}\n}","line":{"from":204,"to":209}} {"id":100011423,"name":"WithExtenders","signature":"func WithExtenders(e ...schedulerapi.Extender) Option","file":"pkg/scheduler/scheduler.go","code":"// WithExtenders sets extenders for the Scheduler\nfunc WithExtenders(e ...schedulerapi.Extender) Option {\n\treturn func(o *schedulerOptions) {\n\t\to.extenders = e\n\t}\n}","line":{"from":211,"to":216}} {"id":100011424,"name":"WithBuildFrameworkCapturer","signature":"func WithBuildFrameworkCapturer(fc FrameworkCapturer) Option","file":"pkg/scheduler/scheduler.go","code":"// WithBuildFrameworkCapturer sets a notify function for getting buildFramework details.\nfunc WithBuildFrameworkCapturer(fc FrameworkCapturer) Option {\n\treturn func(o *schedulerOptions) {\n\t\to.frameworkCapturer = fc\n\t}\n}","line":{"from":221,"to":226}} {"id":100011425,"name":"New","signature":"func New(client clientset.Interface,","file":"pkg/scheduler/scheduler.go","code":"// New returns a Scheduler\nfunc New(client clientset.Interface,\n\tinformerFactory informers.SharedInformerFactory,\n\tdynInformerFactory dynamicinformer.DynamicSharedInformerFactory,\n\trecorderFactory profile.RecorderFactory,\n\tstopCh \u003c-chan struct{},\n\topts ...Option) (*Scheduler, error) {\n\n\tstopEverything := stopCh\n\tif stopEverything == nil {\n\t\tstopEverything = wait.NeverStop\n\t}\n\n\toptions := defaultSchedulerOptions\n\tfor _, opt := range opts {\n\t\topt(\u0026options)\n\t}\n\n\tif options.applyDefaultProfile {\n\t\tvar versionedCfg configv1.KubeSchedulerConfiguration\n\t\tscheme.Scheme.Default(\u0026versionedCfg)\n\t\tcfg := schedulerapi.KubeSchedulerConfiguration{}\n\t\tif err := scheme.Scheme.Convert(\u0026versionedCfg, \u0026cfg, nil); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\toptions.profiles = cfg.Profiles\n\t}\n\n\tregistry := frameworkplugins.NewInTreeRegistry()\n\tif err := registry.Merge(options.frameworkOutOfTreeRegistry); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmetrics.Register()\n\n\textenders, err := buildExtenders(options.extenders, options.profiles)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"couldn't build extenders: %w\", err)\n\t}\n\n\tpodLister := informerFactory.Core().V1().Pods().Lister()\n\tnodeLister := informerFactory.Core().V1().Nodes().Lister()\n\n\tsnapshot := internalcache.NewEmptySnapshot()\n\tclusterEventMap := make(map[framework.ClusterEvent]sets.String)\n\tmetricsRecorder := metrics.NewMetricsAsyncRecorder(1000, time.Second, stopCh)\n\n\tprofiles, err := profile.NewMap(options.profiles, registry, recorderFactory, stopCh,\n\t\tframeworkruntime.WithComponentConfigVersion(options.componentConfigVersion),\n\t\tframeworkruntime.WithClientSet(client),\n\t\tframeworkruntime.WithKubeConfig(options.kubeConfig),\n\t\tframeworkruntime.WithInformerFactory(informerFactory),\n\t\tframeworkruntime.WithSnapshotSharedLister(snapshot),\n\t\tframeworkruntime.WithCaptureProfile(frameworkruntime.CaptureProfile(options.frameworkCapturer)),\n\t\tframeworkruntime.WithClusterEventMap(clusterEventMap),\n\t\tframeworkruntime.WithClusterEventMap(clusterEventMap),\n\t\tframeworkruntime.WithParallelism(int(options.parallelism)),\n\t\tframeworkruntime.WithExtenders(extenders),\n\t\tframeworkruntime.WithMetricsRecorder(metricsRecorder),\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"initializing profiles: %v\", err)\n\t}\n\n\tif len(profiles) == 0 {\n\t\treturn nil, errors.New(\"at least one profile is required\")\n\t}\n\n\tpreEnqueuePluginMap := make(map[string][]framework.PreEnqueuePlugin)\n\tfor profileName, profile := range profiles {\n\t\tpreEnqueuePluginMap[profileName] = profile.PreEnqueuePlugins()\n\t}\n\tpodQueue := internalqueue.NewSchedulingQueue(\n\t\tprofiles[options.profiles[0].SchedulerName].QueueSortFunc(),\n\t\tinformerFactory,\n\t\tinternalqueue.WithPodInitialBackoffDuration(time.Duration(options.podInitialBackoffSeconds)*time.Second),\n\t\tinternalqueue.WithPodMaxBackoffDuration(time.Duration(options.podMaxBackoffSeconds)*time.Second),\n\t\tinternalqueue.WithPodLister(podLister),\n\t\tinternalqueue.WithClusterEventMap(clusterEventMap),\n\t\tinternalqueue.WithPodMaxInUnschedulablePodsDuration(options.podMaxInUnschedulablePodsDuration),\n\t\tinternalqueue.WithPreEnqueuePluginMap(preEnqueuePluginMap),\n\t\tinternalqueue.WithPluginMetricsSamplePercent(pluginMetricsSamplePercent),\n\t\tinternalqueue.WithMetricsRecorder(*metricsRecorder),\n\t)\n\n\tfor _, fwk := range profiles {\n\t\tfwk.SetPodNominator(podQueue)\n\t}\n\n\tschedulerCache := internalcache.New(durationToExpireAssumedPod, stopEverything)\n\n\t// Setup cache debugger.\n\tdebugger := cachedebugger.New(nodeLister, podLister, schedulerCache, podQueue)\n\tdebugger.ListenForSignal(stopEverything)\n\n\tsched := \u0026Scheduler{\n\t\tCache: schedulerCache,\n\t\tclient: client,\n\t\tnodeInfoSnapshot: snapshot,\n\t\tpercentageOfNodesToScore: options.percentageOfNodesToScore,\n\t\tExtenders: extenders,\n\t\tNextPod: internalqueue.MakeNextPodFunc(podQueue),\n\t\tStopEverything: stopEverything,\n\t\tSchedulingQueue: podQueue,\n\t\tProfiles: profiles,\n\t}\n\tsched.applyDefaultHandlers()\n\n\taddAllEventHandlers(sched, informerFactory, dynInformerFactory, unionedGVKs(clusterEventMap))\n\n\treturn sched, nil\n}","line":{"from":241,"to":352}} {"id":100011426,"name":"Run","signature":"func (sched *Scheduler) Run(ctx context.Context)","file":"pkg/scheduler/scheduler.go","code":"// Run begins watching and scheduling. It starts scheduling and blocked until the context is done.\nfunc (sched *Scheduler) Run(ctx context.Context) {\n\tsched.SchedulingQueue.Run()\n\n\t// We need to start scheduleOne loop in a dedicated goroutine,\n\t// because scheduleOne function hangs on getting the next item\n\t// from the SchedulingQueue.\n\t// If there are no new pods to schedule, it will be hanging there\n\t// and if done in this goroutine it will be blocking closing\n\t// SchedulingQueue, in effect causing a deadlock on shutdown.\n\tgo wait.UntilWithContext(ctx, sched.scheduleOne, 0)\n\n\t\u003c-ctx.Done()\n\tsched.SchedulingQueue.Close()\n}","line":{"from":354,"to":368}} {"id":100011427,"name":"NewInformerFactory","signature":"func NewInformerFactory(cs clientset.Interface, resyncPeriod time.Duration) informers.SharedInformerFactory","file":"pkg/scheduler/scheduler.go","code":"// NewInformerFactory creates a SharedInformerFactory and initializes a scheduler specific\n// in-place podInformer.\nfunc NewInformerFactory(cs clientset.Interface, resyncPeriod time.Duration) informers.SharedInformerFactory {\n\tinformerFactory := informers.NewSharedInformerFactory(cs, resyncPeriod)\n\tinformerFactory.InformerFor(\u0026v1.Pod{}, newPodInformer)\n\treturn informerFactory\n}","line":{"from":370,"to":376}} {"id":100011428,"name":"buildExtenders","signature":"func buildExtenders(extenders []schedulerapi.Extender, profiles []schedulerapi.KubeSchedulerProfile) ([]framework.Extender, error)","file":"pkg/scheduler/scheduler.go","code":"func buildExtenders(extenders []schedulerapi.Extender, profiles []schedulerapi.KubeSchedulerProfile) ([]framework.Extender, error) {\n\tvar fExtenders []framework.Extender\n\tif len(extenders) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tvar ignoredExtendedResources []string\n\tvar ignorableExtenders []framework.Extender\n\tfor i := range extenders {\n\t\tklog.V(2).InfoS(\"Creating extender\", \"extender\", extenders[i])\n\t\textender, err := NewHTTPExtender(\u0026extenders[i])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !extender.IsIgnorable() {\n\t\t\tfExtenders = append(fExtenders, extender)\n\t\t} else {\n\t\t\tignorableExtenders = append(ignorableExtenders, extender)\n\t\t}\n\t\tfor _, r := range extenders[i].ManagedResources {\n\t\t\tif r.IgnoredByScheduler {\n\t\t\t\tignoredExtendedResources = append(ignoredExtendedResources, r.Name)\n\t\t\t}\n\t\t}\n\t}\n\t// place ignorable extenders to the tail of extenders\n\tfExtenders = append(fExtenders, ignorableExtenders...)\n\n\t// If there are any extended resources found from the Extenders, append them to the pluginConfig for each profile.\n\t// This should only have an effect on ComponentConfig, where it is possible to configure Extenders and\n\t// plugin args (and in which case the extender ignored resources take precedence).\n\tif len(ignoredExtendedResources) == 0 {\n\t\treturn fExtenders, nil\n\t}\n\n\tfor i := range profiles {\n\t\tprof := \u0026profiles[i]\n\t\tvar found = false\n\t\tfor k := range prof.PluginConfig {\n\t\t\tif prof.PluginConfig[k].Name == noderesources.Name {\n\t\t\t\t// Update the existing args\n\t\t\t\tpc := \u0026prof.PluginConfig[k]\n\t\t\t\targs, ok := pc.Args.(*schedulerapi.NodeResourcesFitArgs)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, fmt.Errorf(\"want args to be of type NodeResourcesFitArgs, got %T\", pc.Args)\n\t\t\t\t}\n\t\t\t\targs.IgnoredResources = ignoredExtendedResources\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"can't find NodeResourcesFitArgs in plugin config\")\n\t\t}\n\t}\n\treturn fExtenders, nil\n}","line":{"from":378,"to":434}} {"id":100011429,"name":"unionedGVKs","signature":"func unionedGVKs(m map[framework.ClusterEvent]sets.String) map[framework.GVK]framework.ActionType","file":"pkg/scheduler/scheduler.go","code":"func unionedGVKs(m map[framework.ClusterEvent]sets.String) map[framework.GVK]framework.ActionType {\n\tgvkMap := make(map[framework.GVK]framework.ActionType)\n\tfor evt := range m {\n\t\tif _, ok := gvkMap[evt.Resource]; ok {\n\t\t\tgvkMap[evt.Resource] |= evt.ActionType\n\t\t} else {\n\t\t\tgvkMap[evt.Resource] = evt.ActionType\n\t\t}\n\t}\n\treturn gvkMap\n}","line":{"from":438,"to":448}} {"id":100011430,"name":"newPodInformer","signature":"func newPodInformer(cs clientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"pkg/scheduler/scheduler.go","code":"// newPodInformer creates a shared index informer that returns only non-terminal pods.\n// The PodInformer allows indexers to be added, but note that only non-conflict indexers are allowed.\nfunc newPodInformer(cs clientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\tselector := fmt.Sprintf(\"status.phase!=%v,status.phase!=%v\", v1.PodSucceeded, v1.PodFailed)\n\ttweakListOptions := func(options *metav1.ListOptions) {\n\t\toptions.FieldSelector = selector\n\t}\n\treturn coreinformers.NewFilteredPodInformer(cs, metav1.NamespaceAll, resyncPeriod, cache.Indexers{}, tweakListOptions)\n}","line":{"from":450,"to":458}} {"id":100011431,"name":"GetNonzeroRequests","signature":"func GetNonzeroRequests(requests *v1.ResourceList) (int64, int64)","file":"pkg/scheduler/util/pod_resources.go","code":"// GetNonzeroRequests returns the default cpu in milli-cpu and memory in bytes resource requests if none is found or\n// what is provided on the request.\nfunc GetNonzeroRequests(requests *v1.ResourceList) (int64, int64) {\n\tcpu := GetRequestForResource(v1.ResourceCPU, requests, true)\n\tmem := GetRequestForResource(v1.ResourceMemory, requests, true)\n\treturn cpu.MilliValue(), mem.Value()\n\n}","line":{"from":39,"to":46}} {"id":100011432,"name":"GetRequestForResource","signature":"func GetRequestForResource(resourceName v1.ResourceName, requests *v1.ResourceList, nonZero bool) resource.Quantity","file":"pkg/scheduler/util/pod_resources.go","code":"// GetRequestForResource returns the requested values unless nonZero is true and there is no defined request\n// for CPU and memory.\n// If nonZero is true and the resource has no defined request for CPU or memory, it returns a default value.\nfunc GetRequestForResource(resourceName v1.ResourceName, requests *v1.ResourceList, nonZero bool) resource.Quantity {\n\tif requests == nil {\n\t\treturn resource.Quantity{}\n\t}\n\tswitch resourceName {\n\tcase v1.ResourceCPU:\n\t\t// Override if un-set, but not if explicitly set to zero\n\t\tif _, found := (*requests)[v1.ResourceCPU]; !found \u0026\u0026 nonZero {\n\t\t\treturn *resource.NewMilliQuantity(DefaultMilliCPURequest, resource.DecimalSI)\n\t\t}\n\t\treturn requests.Cpu().DeepCopy()\n\tcase v1.ResourceMemory:\n\t\t// Override if un-set, but not if explicitly set to zero\n\t\tif _, found := (*requests)[v1.ResourceMemory]; !found \u0026\u0026 nonZero {\n\t\t\treturn *resource.NewQuantity(DefaultMemoryRequest, resource.DecimalSI)\n\t\t}\n\t\treturn requests.Memory().DeepCopy()\n\tcase v1.ResourceEphemeralStorage:\n\t\tquantity, found := (*requests)[v1.ResourceEphemeralStorage]\n\t\tif !found {\n\t\t\treturn resource.Quantity{}\n\t\t}\n\t\treturn quantity.DeepCopy()\n\tdefault:\n\t\tquantity, found := (*requests)[resourceName]\n\t\tif !found {\n\t\t\treturn resource.Quantity{}\n\t\t}\n\t\treturn quantity.DeepCopy()\n\t}\n}","line":{"from":48,"to":81}} {"id":100011433,"name":"GetPodFullName","signature":"func GetPodFullName(pod *v1.Pod) string","file":"pkg/scheduler/util/utils.go","code":"// GetPodFullName returns a name that uniquely identifies a pod.\nfunc GetPodFullName(pod *v1.Pod) string {\n\t// Use underscore as the delimiter because it is not allowed in pod name\n\t// (DNS subdomain format).\n\treturn pod.Name + \"_\" + pod.Namespace\n}","line":{"from":40,"to":45}} {"id":100011434,"name":"GetPodStartTime","signature":"func GetPodStartTime(pod *v1.Pod) *metav1.Time","file":"pkg/scheduler/util/utils.go","code":"// GetPodStartTime returns start time of the given pod or current timestamp\n// if it hasn't started yet.\nfunc GetPodStartTime(pod *v1.Pod) *metav1.Time {\n\tif pod.Status.StartTime != nil {\n\t\treturn pod.Status.StartTime\n\t}\n\t// Assumed pods and bound pods that haven't started don't have a StartTime yet.\n\treturn \u0026metav1.Time{Time: time.Now()}\n}","line":{"from":47,"to":55}} {"id":100011435,"name":"GetEarliestPodStartTime","signature":"func GetEarliestPodStartTime(victims *extenderv1.Victims) *metav1.Time","file":"pkg/scheduler/util/utils.go","code":"// GetEarliestPodStartTime returns the earliest start time of all pods that\n// have the highest priority among all victims.\nfunc GetEarliestPodStartTime(victims *extenderv1.Victims) *metav1.Time {\n\tif len(victims.Pods) == 0 {\n\t\t// should not reach here.\n\t\tklog.Background().Error(nil, \"victims.Pods is empty. Should not reach here\")\n\t\treturn nil\n\t}\n\n\tearliestPodStartTime := GetPodStartTime(victims.Pods[0])\n\tmaxPriority := corev1helpers.PodPriority(victims.Pods[0])\n\n\tfor _, pod := range victims.Pods {\n\t\tif corev1helpers.PodPriority(pod) == maxPriority {\n\t\t\tif GetPodStartTime(pod).Before(earliestPodStartTime) {\n\t\t\t\tearliestPodStartTime = GetPodStartTime(pod)\n\t\t\t}\n\t\t} else if corev1helpers.PodPriority(pod) \u003e maxPriority {\n\t\t\tmaxPriority = corev1helpers.PodPriority(pod)\n\t\t\tearliestPodStartTime = GetPodStartTime(pod)\n\t\t}\n\t}\n\n\treturn earliestPodStartTime\n}","line":{"from":57,"to":81}} {"id":100011436,"name":"MoreImportantPod","signature":"func MoreImportantPod(pod1, pod2 *v1.Pod) bool","file":"pkg/scheduler/util/utils.go","code":"// MoreImportantPod return true when priority of the first pod is higher than\n// the second one. If two pods' priorities are equal, compare their StartTime.\n// It takes arguments of the type \"interface{}\" to be used with SortableList,\n// but expects those arguments to be *v1.Pod.\nfunc MoreImportantPod(pod1, pod2 *v1.Pod) bool {\n\tp1 := corev1helpers.PodPriority(pod1)\n\tp2 := corev1helpers.PodPriority(pod2)\n\tif p1 != p2 {\n\t\treturn p1 \u003e p2\n\t}\n\treturn GetPodStartTime(pod1).Before(GetPodStartTime(pod2))\n}","line":{"from":83,"to":94}} {"id":100011437,"name":"Retriable","signature":"func Retriable(err error) bool","file":"pkg/scheduler/util/utils.go","code":"// Retriable defines the retriable errors during a scheduling cycle.\nfunc Retriable(err error) bool {\n\treturn apierrors.IsInternalError(err) || apierrors.IsServiceUnavailable(err) ||\n\t\tnet.IsConnectionRefused(err)\n}","line":{"from":96,"to":100}} {"id":100011438,"name":"PatchPodStatus","signature":"func PatchPodStatus(ctx context.Context, cs kubernetes.Interface, old *v1.Pod, newStatus *v1.PodStatus) error","file":"pkg/scheduler/util/utils.go","code":"// PatchPodStatus calculates the delta bytes change from \u003cold.Status\u003e to \u003cnewStatus\u003e,\n// and then submit a request to API server to patch the pod changes.\nfunc PatchPodStatus(ctx context.Context, cs kubernetes.Interface, old *v1.Pod, newStatus *v1.PodStatus) error {\n\tif newStatus == nil {\n\t\treturn nil\n\t}\n\n\toldData, err := json.Marshal(v1.Pod{Status: old.Status})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnewData, err := json.Marshal(v1.Pod{Status: *newStatus})\n\tif err != nil {\n\t\treturn err\n\t}\n\tpatchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, \u0026v1.Pod{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create merge patch for pod %q/%q: %v\", old.Namespace, old.Name, err)\n\t}\n\n\tif \"{}\" == string(patchBytes) {\n\t\treturn nil\n\t}\n\n\tpatchFn := func() error {\n\t\t_, err := cs.CoreV1().Pods(old.Namespace).Patch(ctx, old.Name, types.StrategicMergePatchType, patchBytes, metav1.PatchOptions{}, \"status\")\n\t\treturn err\n\t}\n\n\treturn retry.OnError(retry.DefaultBackoff, Retriable, patchFn)\n}","line":{"from":102,"to":133}} {"id":100011439,"name":"DeletePod","signature":"func DeletePod(ctx context.Context, cs kubernetes.Interface, pod *v1.Pod) error","file":"pkg/scheduler/util/utils.go","code":"// DeletePod deletes the given \u003cpod\u003e from API server\nfunc DeletePod(ctx context.Context, cs kubernetes.Interface, pod *v1.Pod) error {\n\treturn cs.CoreV1().Pods(pod.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{})\n}","line":{"from":135,"to":138}} {"id":100011440,"name":"ClearNominatedNodeName","signature":"func ClearNominatedNodeName(ctx context.Context, cs kubernetes.Interface, pods ...*v1.Pod) utilerrors.Aggregate","file":"pkg/scheduler/util/utils.go","code":"// ClearNominatedNodeName internally submit a patch request to API server\n// to set each pods[*].Status.NominatedNodeName\u003e to \"\".\nfunc ClearNominatedNodeName(ctx context.Context, cs kubernetes.Interface, pods ...*v1.Pod) utilerrors.Aggregate {\n\tvar errs []error\n\tfor _, p := range pods {\n\t\tif len(p.Status.NominatedNodeName) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tpodStatusCopy := p.Status.DeepCopy()\n\t\tpodStatusCopy.NominatedNodeName = \"\"\n\t\tif err := PatchPodStatus(ctx, cs, p, podStatusCopy); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\treturn utilerrors.NewAggregate(errs)\n}","line":{"from":140,"to":155}} {"id":100011441,"name":"IsScalarResourceName","signature":"func IsScalarResourceName(name v1.ResourceName) bool","file":"pkg/scheduler/util/utils.go","code":"// IsScalarResourceName validates the resource for Extended, Hugepages, Native and AttachableVolume resources\nfunc IsScalarResourceName(name v1.ResourceName) bool {\n\treturn v1helper.IsExtendedResourceName(name) || v1helper.IsHugePageResourceName(name) ||\n\t\tv1helper.IsPrefixedNativeResource(name) || v1helper.IsAttachableVolumeResourceName(name)\n}","line":{"from":157,"to":161}} {"id":100011442,"name":"isRequired","signature":"func isRequired(pod *v1.Pod) bool","file":"pkg/security/apparmor/helpers.go","code":"// Checks whether app armor is required for pod to be run.\nfunc isRequired(pod *v1.Pod) bool {\n\tfor key, value := range pod.Annotations {\n\t\tif strings.HasPrefix(key, v1.AppArmorBetaContainerAnnotationKeyPrefix) {\n\t\t\treturn value != v1.AppArmorBetaProfileNameUnconfined\n\t\t}\n\t}\n\treturn false\n}","line":{"from":25,"to":33}} {"id":100011443,"name":"GetProfileName","signature":"func GetProfileName(pod *v1.Pod, containerName string) string","file":"pkg/security/apparmor/helpers.go","code":"// GetProfileName returns the name of the profile to use with the container.\nfunc GetProfileName(pod *v1.Pod, containerName string) string {\n\treturn GetProfileNameFromPodAnnotations(pod.Annotations, containerName)\n}","line":{"from":35,"to":38}} {"id":100011444,"name":"GetProfileNameFromPodAnnotations","signature":"func GetProfileNameFromPodAnnotations(annotations map[string]string, containerName string) string","file":"pkg/security/apparmor/helpers.go","code":"// GetProfileNameFromPodAnnotations gets the name of the profile to use with container from\n// pod annotations\nfunc GetProfileNameFromPodAnnotations(annotations map[string]string, containerName string) string {\n\treturn annotations[v1.AppArmorBetaContainerAnnotationKeyPrefix+containerName]\n}","line":{"from":40,"to":44}} {"id":100011445,"name":"NewValidator","signature":"func NewValidator() Validator","file":"pkg/security/apparmor/validate.go","code":"// NewValidator is in order to find AppArmor FS\nfunc NewValidator() Validator {\n\tif err := validateHost(); err != nil {\n\t\treturn \u0026validator{validateHostErr: err}\n\t}\n\treturn \u0026validator{}\n}","line":{"from":42,"to":48}} {"id":100011446,"name":"Validate","signature":"func (v *validator) Validate(pod *v1.Pod) error","file":"pkg/security/apparmor/validate.go","code":"func (v *validator) Validate(pod *v1.Pod) error {\n\tif !isRequired(pod) {\n\t\treturn nil\n\t}\n\n\tif v.ValidateHost() != nil {\n\t\treturn v.validateHostErr\n\t}\n\n\tvar retErr error\n\tpodutil.VisitContainers(\u0026pod.Spec, podutil.AllContainers, func(container *v1.Container, containerType podutil.ContainerType) bool {\n\t\tprofile := GetProfileName(pod, container.Name)\n\t\tretErr = validation.ValidateAppArmorProfileFormat(profile)\n\t\tif retErr != nil {\n\t\t\treturn false\n\t\t}\n\t\t// TODO(#64841): This would ideally be part of validation.ValidateAppArmorProfileFormat, but\n\t\t// that is called for API validation, and this is tightening validation.\n\t\tif strings.HasPrefix(profile, v1.AppArmorBetaProfileNamePrefix) {\n\t\t\tif strings.TrimSpace(strings.TrimPrefix(profile, v1.AppArmorBetaProfileNamePrefix)) == \"\" {\n\t\t\t\tretErr = fmt.Errorf(\"invalid empty AppArmor profile name: %q\", profile)\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n\n\treturn retErr\n}","line":{"from":54,"to":82}} {"id":100011447,"name":"ValidateHost","signature":"func (v *validator) ValidateHost() error","file":"pkg/security/apparmor/validate.go","code":"// ValidateHost verifies that the host and runtime is capable of enforcing AppArmor profiles.\n// Note, this is intentionally only check the host at kubelet startup and never re-evaluates the host\n// as the expectation is that the kubelet restart will be needed to enable or disable AppArmor support.\nfunc (v *validator) ValidateHost() error {\n\treturn v.validateHostErr\n}","line":{"from":84,"to":89}} {"id":100011448,"name":"validateHost","signature":"func validateHost() error","file":"pkg/security/apparmor/validate.go","code":"// validateHost verifies that the host and runtime is capable of enforcing AppArmor profiles.\nfunc validateHost() error {\n\t// Check feature-gates\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.AppArmor) {\n\t\treturn errors.New(\"AppArmor disabled by feature-gate\")\n\t}\n\n\t// Check build support.\n\tif isDisabledBuild {\n\t\treturn errors.New(\"binary not compiled for linux\")\n\t}\n\n\t// Check kernel support.\n\tif !apparmor.IsEnabled() {\n\t\treturn errors.New(\"AppArmor is not enabled on the host\")\n\t}\n\n\treturn nil\n}","line":{"from":91,"to":109}} {"id":100011449,"name":"init","signature":"func init()","file":"pkg/security/apparmor/validate_disabled.go","code":"func init() {\n\t// If Kubernetes was not built for linux, apparmor is always disabled.\n\tisDisabledBuild = true\n}","line":{"from":22,"to":25}} {"id":100011450,"name":"NewPodSecurityContextAccessor","signature":"func NewPodSecurityContextAccessor(podSC *api.PodSecurityContext) PodSecurityContextAccessor","file":"pkg/securitycontext/accessors.go","code":"// NewPodSecurityContextAccessor returns an accessor for the given pod security context.\n// May be initialized with a nil PodSecurityContext.\nfunc NewPodSecurityContextAccessor(podSC *api.PodSecurityContext) PodSecurityContextAccessor {\n\treturn \u0026podSecurityContextWrapper{podSC: podSC}\n}","line":{"from":58,"to":62}} {"id":100011451,"name":"NewPodSecurityContextMutator","signature":"func NewPodSecurityContextMutator(podSC *api.PodSecurityContext) PodSecurityContextMutator","file":"pkg/securitycontext/accessors.go","code":"// NewPodSecurityContextMutator returns a mutator for the given pod security context.\n// May be initialized with a nil PodSecurityContext.\nfunc NewPodSecurityContextMutator(podSC *api.PodSecurityContext) PodSecurityContextMutator {\n\treturn \u0026podSecurityContextWrapper{podSC: podSC}\n}","line":{"from":64,"to":68}} {"id":100011452,"name":"PodSecurityContext","signature":"func (w *podSecurityContextWrapper) PodSecurityContext() *api.PodSecurityContext","file":"pkg/securitycontext/accessors.go","code":"func (w *podSecurityContextWrapper) PodSecurityContext() *api.PodSecurityContext {\n\treturn w.podSC\n}","line":{"from":74,"to":76}} {"id":100011453,"name":"ensurePodSC","signature":"func (w *podSecurityContextWrapper) ensurePodSC()","file":"pkg/securitycontext/accessors.go","code":"func (w *podSecurityContextWrapper) ensurePodSC() {\n\tif w.podSC == nil {\n\t\tw.podSC = \u0026api.PodSecurityContext{}\n\t}\n}","line":{"from":78,"to":82}} {"id":100011454,"name":"HostNetwork","signature":"func (w *podSecurityContextWrapper) HostNetwork() bool","file":"pkg/securitycontext/accessors.go","code":"func (w *podSecurityContextWrapper) HostNetwork() bool {\n\tif w.podSC == nil {\n\t\treturn false\n\t}\n\treturn w.podSC.HostNetwork\n}","line":{"from":84,"to":89}} {"id":100011455,"name":"SetHostNetwork","signature":"func (w *podSecurityContextWrapper) SetHostNetwork(v bool)","file":"pkg/securitycontext/accessors.go","code":"func (w *podSecurityContextWrapper) SetHostNetwork(v bool) {\n\tif w.podSC == nil \u0026\u0026 v == false {\n\t\treturn\n\t}\n\tw.ensurePodSC()\n\tw.podSC.HostNetwork = v\n}","line":{"from":90,"to":96}} {"id":100011456,"name":"HostPID","signature":"func (w *podSecurityContextWrapper) HostPID() bool","file":"pkg/securitycontext/accessors.go","code":"func (w *podSecurityContextWrapper) HostPID() bool {\n\tif w.podSC == nil {\n\t\treturn false\n\t}\n\treturn w.podSC.HostPID\n}","line":{"from":97,"to":102}} {"id":100011457,"name":"SetHostPID","signature":"func (w *podSecurityContextWrapper) SetHostPID(v bool)","file":"pkg/securitycontext/accessors.go","code":"func (w *podSecurityContextWrapper) SetHostPID(v bool) {\n\tif w.podSC == nil \u0026\u0026 v == false {\n\t\treturn\n\t}\n\tw.ensurePodSC()\n\tw.podSC.HostPID = v\n}","line":{"from":103,"to":109}} {"id":100011458,"name":"HostIPC","signature":"func (w *podSecurityContextWrapper) HostIPC() bool","file":"pkg/securitycontext/accessors.go","code":"func (w *podSecurityContextWrapper) HostIPC() bool {\n\tif w.podSC == nil {\n\t\treturn false\n\t}\n\treturn w.podSC.HostIPC\n}","line":{"from":110,"to":115}} {"id":100011459,"name":"SetHostIPC","signature":"func (w *podSecurityContextWrapper) SetHostIPC(v bool)","file":"pkg/securitycontext/accessors.go","code":"func (w *podSecurityContextWrapper) SetHostIPC(v bool) {\n\tif w.podSC == nil \u0026\u0026 v == false {\n\t\treturn\n\t}\n\tw.ensurePodSC()\n\tw.podSC.HostIPC = v\n}","line":{"from":116,"to":122}} {"id":100011460,"name":"SELinuxOptions","signature":"func (w *podSecurityContextWrapper) SELinuxOptions() *api.SELinuxOptions","file":"pkg/securitycontext/accessors.go","code":"func (w *podSecurityContextWrapper) SELinuxOptions() *api.SELinuxOptions {\n\tif w.podSC == nil {\n\t\treturn nil\n\t}\n\treturn w.podSC.SELinuxOptions\n}","line":{"from":123,"to":128}} {"id":100011461,"name":"SetSELinuxOptions","signature":"func (w *podSecurityContextWrapper) SetSELinuxOptions(v *api.SELinuxOptions)","file":"pkg/securitycontext/accessors.go","code":"func (w *podSecurityContextWrapper) SetSELinuxOptions(v *api.SELinuxOptions) {\n\tif w.podSC == nil \u0026\u0026 v == nil {\n\t\treturn\n\t}\n\tw.ensurePodSC()\n\tw.podSC.SELinuxOptions = v\n}","line":{"from":129,"to":135}} {"id":100011462,"name":"RunAsUser","signature":"func (w *podSecurityContextWrapper) RunAsUser() *int64","file":"pkg/securitycontext/accessors.go","code":"func (w *podSecurityContextWrapper) RunAsUser() *int64 {\n\tif w.podSC == nil {\n\t\treturn nil\n\t}\n\treturn w.podSC.RunAsUser\n}","line":{"from":136,"to":141}} {"id":100011463,"name":"SetRunAsUser","signature":"func (w *podSecurityContextWrapper) SetRunAsUser(v *int64)","file":"pkg/securitycontext/accessors.go","code":"func (w *podSecurityContextWrapper) SetRunAsUser(v *int64) {\n\tif w.podSC == nil \u0026\u0026 v == nil {\n\t\treturn\n\t}\n\tw.ensurePodSC()\n\tw.podSC.RunAsUser = v\n}","line":{"from":142,"to":148}} {"id":100011464,"name":"RunAsGroup","signature":"func (w *podSecurityContextWrapper) RunAsGroup() *int64","file":"pkg/securitycontext/accessors.go","code":"func (w *podSecurityContextWrapper) RunAsGroup() *int64 {\n\tif w.podSC == nil {\n\t\treturn nil\n\t}\n\treturn w.podSC.RunAsGroup\n}","line":{"from":149,"to":154}} {"id":100011465,"name":"SetRunAsGroup","signature":"func (w *podSecurityContextWrapper) SetRunAsGroup(v *int64)","file":"pkg/securitycontext/accessors.go","code":"func (w *podSecurityContextWrapper) SetRunAsGroup(v *int64) {\n\tif w.podSC == nil \u0026\u0026 v == nil {\n\t\treturn\n\t}\n\tw.ensurePodSC()\n\tw.podSC.RunAsGroup = v\n}","line":{"from":155,"to":161}} {"id":100011466,"name":"RunAsNonRoot","signature":"func (w *podSecurityContextWrapper) RunAsNonRoot() *bool","file":"pkg/securitycontext/accessors.go","code":"func (w *podSecurityContextWrapper) RunAsNonRoot() *bool {\n\tif w.podSC == nil {\n\t\treturn nil\n\t}\n\treturn w.podSC.RunAsNonRoot\n}","line":{"from":163,"to":168}} {"id":100011467,"name":"SetRunAsNonRoot","signature":"func (w *podSecurityContextWrapper) SetRunAsNonRoot(v *bool)","file":"pkg/securitycontext/accessors.go","code":"func (w *podSecurityContextWrapper) SetRunAsNonRoot(v *bool) {\n\tif w.podSC == nil \u0026\u0026 v == nil {\n\t\treturn\n\t}\n\tw.ensurePodSC()\n\tw.podSC.RunAsNonRoot = v\n}","line":{"from":169,"to":175}} {"id":100011468,"name":"SeccompProfile","signature":"func (w *podSecurityContextWrapper) SeccompProfile() *api.SeccompProfile","file":"pkg/securitycontext/accessors.go","code":"func (w *podSecurityContextWrapper) SeccompProfile() *api.SeccompProfile {\n\tif w.podSC == nil {\n\t\treturn nil\n\t}\n\treturn w.podSC.SeccompProfile\n}","line":{"from":176,"to":181}} {"id":100011469,"name":"SetSeccompProfile","signature":"func (w *podSecurityContextWrapper) SetSeccompProfile(p *api.SeccompProfile)","file":"pkg/securitycontext/accessors.go","code":"func (w *podSecurityContextWrapper) SetSeccompProfile(p *api.SeccompProfile) {\n\tif w.podSC == nil \u0026\u0026 p == nil {\n\t\treturn\n\t}\n\tw.ensurePodSC()\n\tw.podSC.SeccompProfile = p\n}","line":{"from":182,"to":188}} {"id":100011470,"name":"SupplementalGroups","signature":"func (w *podSecurityContextWrapper) SupplementalGroups() []int64","file":"pkg/securitycontext/accessors.go","code":"func (w *podSecurityContextWrapper) SupplementalGroups() []int64 {\n\tif w.podSC == nil {\n\t\treturn nil\n\t}\n\treturn w.podSC.SupplementalGroups\n}","line":{"from":189,"to":194}} {"id":100011471,"name":"SetSupplementalGroups","signature":"func (w *podSecurityContextWrapper) SetSupplementalGroups(v []int64)","file":"pkg/securitycontext/accessors.go","code":"func (w *podSecurityContextWrapper) SetSupplementalGroups(v []int64) {\n\tif w.podSC == nil \u0026\u0026 len(v) == 0 {\n\t\treturn\n\t}\n\tw.ensurePodSC()\n\tif len(v) == 0 \u0026\u0026 len(w.podSC.SupplementalGroups) == 0 {\n\t\treturn\n\t}\n\tw.podSC.SupplementalGroups = v\n}","line":{"from":195,"to":204}} {"id":100011472,"name":"FSGroup","signature":"func (w *podSecurityContextWrapper) FSGroup() *int64","file":"pkg/securitycontext/accessors.go","code":"func (w *podSecurityContextWrapper) FSGroup() *int64 {\n\tif w.podSC == nil {\n\t\treturn nil\n\t}\n\treturn w.podSC.FSGroup\n}","line":{"from":205,"to":210}} {"id":100011473,"name":"SetFSGroup","signature":"func (w *podSecurityContextWrapper) SetFSGroup(v *int64)","file":"pkg/securitycontext/accessors.go","code":"func (w *podSecurityContextWrapper) SetFSGroup(v *int64) {\n\tif w.podSC == nil \u0026\u0026 v == nil {\n\t\treturn\n\t}\n\tw.ensurePodSC()\n\tw.podSC.FSGroup = v\n}","line":{"from":211,"to":217}} {"id":100011474,"name":"NewContainerSecurityContextAccessor","signature":"func NewContainerSecurityContextAccessor(containerSC *api.SecurityContext) ContainerSecurityContextAccessor","file":"pkg/securitycontext/accessors.go","code":"// NewContainerSecurityContextAccessor returns an accessor for the provided container security context\n// May be initialized with a nil SecurityContext\nfunc NewContainerSecurityContextAccessor(containerSC *api.SecurityContext) ContainerSecurityContextAccessor {\n\treturn \u0026containerSecurityContextWrapper{containerSC: containerSC}\n}","line":{"from":250,"to":254}} {"id":100011475,"name":"NewContainerSecurityContextMutator","signature":"func NewContainerSecurityContextMutator(containerSC *api.SecurityContext) ContainerSecurityContextMutator","file":"pkg/securitycontext/accessors.go","code":"// NewContainerSecurityContextMutator returns a mutator for the provided container security context\n// May be initialized with a nil SecurityContext\nfunc NewContainerSecurityContextMutator(containerSC *api.SecurityContext) ContainerSecurityContextMutator {\n\treturn \u0026containerSecurityContextWrapper{containerSC: containerSC}\n}","line":{"from":256,"to":260}} {"id":100011476,"name":"ContainerSecurityContext","signature":"func (w *containerSecurityContextWrapper) ContainerSecurityContext() *api.SecurityContext","file":"pkg/securitycontext/accessors.go","code":"func (w *containerSecurityContextWrapper) ContainerSecurityContext() *api.SecurityContext {\n\treturn w.containerSC\n}","line":{"from":266,"to":268}} {"id":100011477,"name":"ensureContainerSC","signature":"func (w *containerSecurityContextWrapper) ensureContainerSC()","file":"pkg/securitycontext/accessors.go","code":"func (w *containerSecurityContextWrapper) ensureContainerSC() {\n\tif w.containerSC == nil {\n\t\tw.containerSC = \u0026api.SecurityContext{}\n\t}\n}","line":{"from":270,"to":274}} {"id":100011478,"name":"Capabilities","signature":"func (w *containerSecurityContextWrapper) Capabilities() *api.Capabilities","file":"pkg/securitycontext/accessors.go","code":"func (w *containerSecurityContextWrapper) Capabilities() *api.Capabilities {\n\tif w.containerSC == nil {\n\t\treturn nil\n\t}\n\treturn w.containerSC.Capabilities\n}","line":{"from":276,"to":281}} {"id":100011479,"name":"SetCapabilities","signature":"func (w *containerSecurityContextWrapper) SetCapabilities(v *api.Capabilities)","file":"pkg/securitycontext/accessors.go","code":"func (w *containerSecurityContextWrapper) SetCapabilities(v *api.Capabilities) {\n\tif w.containerSC == nil \u0026\u0026 v == nil {\n\t\treturn\n\t}\n\tw.ensureContainerSC()\n\tw.containerSC.Capabilities = v\n}","line":{"from":282,"to":288}} {"id":100011480,"name":"Privileged","signature":"func (w *containerSecurityContextWrapper) Privileged() *bool","file":"pkg/securitycontext/accessors.go","code":"func (w *containerSecurityContextWrapper) Privileged() *bool {\n\tif w.containerSC == nil {\n\t\treturn nil\n\t}\n\treturn w.containerSC.Privileged\n}","line":{"from":289,"to":294}} {"id":100011481,"name":"SetPrivileged","signature":"func (w *containerSecurityContextWrapper) SetPrivileged(v *bool)","file":"pkg/securitycontext/accessors.go","code":"func (w *containerSecurityContextWrapper) SetPrivileged(v *bool) {\n\tif w.containerSC == nil \u0026\u0026 v == nil {\n\t\treturn\n\t}\n\tw.ensureContainerSC()\n\tw.containerSC.Privileged = v\n}","line":{"from":295,"to":301}} {"id":100011482,"name":"ProcMount","signature":"func (w *containerSecurityContextWrapper) ProcMount() api.ProcMountType","file":"pkg/securitycontext/accessors.go","code":"func (w *containerSecurityContextWrapper) ProcMount() api.ProcMountType {\n\tif w.containerSC == nil {\n\t\treturn api.DefaultProcMount\n\t}\n\tif w.containerSC.ProcMount == nil {\n\t\treturn api.DefaultProcMount\n\t}\n\treturn *w.containerSC.ProcMount\n}","line":{"from":302,"to":310}} {"id":100011483,"name":"SELinuxOptions","signature":"func (w *containerSecurityContextWrapper) SELinuxOptions() *api.SELinuxOptions","file":"pkg/securitycontext/accessors.go","code":"func (w *containerSecurityContextWrapper) SELinuxOptions() *api.SELinuxOptions {\n\tif w.containerSC == nil {\n\t\treturn nil\n\t}\n\treturn w.containerSC.SELinuxOptions\n}","line":{"from":311,"to":316}} {"id":100011484,"name":"SetSELinuxOptions","signature":"func (w *containerSecurityContextWrapper) SetSELinuxOptions(v *api.SELinuxOptions)","file":"pkg/securitycontext/accessors.go","code":"func (w *containerSecurityContextWrapper) SetSELinuxOptions(v *api.SELinuxOptions) {\n\tif w.containerSC == nil \u0026\u0026 v == nil {\n\t\treturn\n\t}\n\tw.ensureContainerSC()\n\tw.containerSC.SELinuxOptions = v\n}","line":{"from":317,"to":323}} {"id":100011485,"name":"RunAsUser","signature":"func (w *containerSecurityContextWrapper) RunAsUser() *int64","file":"pkg/securitycontext/accessors.go","code":"func (w *containerSecurityContextWrapper) RunAsUser() *int64 {\n\tif w.containerSC == nil {\n\t\treturn nil\n\t}\n\treturn w.containerSC.RunAsUser\n}","line":{"from":324,"to":329}} {"id":100011486,"name":"SetRunAsUser","signature":"func (w *containerSecurityContextWrapper) SetRunAsUser(v *int64)","file":"pkg/securitycontext/accessors.go","code":"func (w *containerSecurityContextWrapper) SetRunAsUser(v *int64) {\n\tif w.containerSC == nil \u0026\u0026 v == nil {\n\t\treturn\n\t}\n\tw.ensureContainerSC()\n\tw.containerSC.RunAsUser = v\n}","line":{"from":330,"to":336}} {"id":100011487,"name":"RunAsGroup","signature":"func (w *containerSecurityContextWrapper) RunAsGroup() *int64","file":"pkg/securitycontext/accessors.go","code":"func (w *containerSecurityContextWrapper) RunAsGroup() *int64 {\n\tif w.containerSC == nil {\n\t\treturn nil\n\t}\n\treturn w.containerSC.RunAsGroup\n}","line":{"from":337,"to":342}} {"id":100011488,"name":"SetRunAsGroup","signature":"func (w *containerSecurityContextWrapper) SetRunAsGroup(v *int64)","file":"pkg/securitycontext/accessors.go","code":"func (w *containerSecurityContextWrapper) SetRunAsGroup(v *int64) {\n\tif w.containerSC == nil \u0026\u0026 v == nil {\n\t\treturn\n\t}\n\tw.ensureContainerSC()\n\tw.containerSC.RunAsGroup = v\n}","line":{"from":343,"to":349}} {"id":100011489,"name":"RunAsNonRoot","signature":"func (w *containerSecurityContextWrapper) RunAsNonRoot() *bool","file":"pkg/securitycontext/accessors.go","code":"func (w *containerSecurityContextWrapper) RunAsNonRoot() *bool {\n\tif w.containerSC == nil {\n\t\treturn nil\n\t}\n\treturn w.containerSC.RunAsNonRoot\n}","line":{"from":351,"to":356}} {"id":100011490,"name":"SetRunAsNonRoot","signature":"func (w *containerSecurityContextWrapper) SetRunAsNonRoot(v *bool)","file":"pkg/securitycontext/accessors.go","code":"func (w *containerSecurityContextWrapper) SetRunAsNonRoot(v *bool) {\n\tif w.containerSC == nil \u0026\u0026 v == nil {\n\t\treturn\n\t}\n\tw.ensureContainerSC()\n\tw.containerSC.RunAsNonRoot = v\n}","line":{"from":357,"to":363}} {"id":100011491,"name":"ReadOnlyRootFilesystem","signature":"func (w *containerSecurityContextWrapper) ReadOnlyRootFilesystem() *bool","file":"pkg/securitycontext/accessors.go","code":"func (w *containerSecurityContextWrapper) ReadOnlyRootFilesystem() *bool {\n\tif w.containerSC == nil {\n\t\treturn nil\n\t}\n\treturn w.containerSC.ReadOnlyRootFilesystem\n}","line":{"from":364,"to":369}} {"id":100011492,"name":"SetReadOnlyRootFilesystem","signature":"func (w *containerSecurityContextWrapper) SetReadOnlyRootFilesystem(v *bool)","file":"pkg/securitycontext/accessors.go","code":"func (w *containerSecurityContextWrapper) SetReadOnlyRootFilesystem(v *bool) {\n\tif w.containerSC == nil \u0026\u0026 v == nil {\n\t\treturn\n\t}\n\tw.ensureContainerSC()\n\tw.containerSC.ReadOnlyRootFilesystem = v\n}","line":{"from":370,"to":376}} {"id":100011493,"name":"SeccompProfile","signature":"func (w *containerSecurityContextWrapper) SeccompProfile() *api.SeccompProfile","file":"pkg/securitycontext/accessors.go","code":"func (w *containerSecurityContextWrapper) SeccompProfile() *api.SeccompProfile {\n\tif w.containerSC == nil {\n\t\treturn nil\n\t}\n\treturn w.containerSC.SeccompProfile\n}","line":{"from":377,"to":382}} {"id":100011494,"name":"SetSeccompProfile","signature":"func (w *containerSecurityContextWrapper) SetSeccompProfile(p *api.SeccompProfile)","file":"pkg/securitycontext/accessors.go","code":"func (w *containerSecurityContextWrapper) SetSeccompProfile(p *api.SeccompProfile) {\n\tif w.containerSC == nil \u0026\u0026 p == nil {\n\t\treturn\n\t}\n\tw.ensureContainerSC()\n\tw.containerSC.SeccompProfile = p\n}","line":{"from":383,"to":389}} {"id":100011495,"name":"AllowPrivilegeEscalation","signature":"func (w *containerSecurityContextWrapper) AllowPrivilegeEscalation() *bool","file":"pkg/securitycontext/accessors.go","code":"func (w *containerSecurityContextWrapper) AllowPrivilegeEscalation() *bool {\n\tif w.containerSC == nil {\n\t\treturn nil\n\t}\n\treturn w.containerSC.AllowPrivilegeEscalation\n}","line":{"from":391,"to":396}} {"id":100011496,"name":"SetAllowPrivilegeEscalation","signature":"func (w *containerSecurityContextWrapper) SetAllowPrivilegeEscalation(v *bool)","file":"pkg/securitycontext/accessors.go","code":"func (w *containerSecurityContextWrapper) SetAllowPrivilegeEscalation(v *bool) {\n\tif w.containerSC == nil \u0026\u0026 v == nil {\n\t\treturn\n\t}\n\tw.ensureContainerSC()\n\tw.containerSC.AllowPrivilegeEscalation = v\n}","line":{"from":397,"to":403}} {"id":100011497,"name":"NewEffectiveContainerSecurityContextAccessor","signature":"func NewEffectiveContainerSecurityContextAccessor(podSC PodSecurityContextAccessor, containerSC ContainerSecurityContextMutator) ContainerSecurityContextAccessor","file":"pkg/securitycontext/accessors.go","code":"// NewEffectiveContainerSecurityContextAccessor returns an accessor for reading effective values\n// for the provided pod security context and container security context\nfunc NewEffectiveContainerSecurityContextAccessor(podSC PodSecurityContextAccessor, containerSC ContainerSecurityContextMutator) ContainerSecurityContextAccessor {\n\treturn \u0026effectiveContainerSecurityContextWrapper{podSC: podSC, containerSC: containerSC}\n}","line":{"from":405,"to":409}} {"id":100011498,"name":"NewEffectiveContainerSecurityContextMutator","signature":"func NewEffectiveContainerSecurityContextMutator(podSC PodSecurityContextAccessor, containerSC ContainerSecurityContextMutator) ContainerSecurityContextMutator","file":"pkg/securitycontext/accessors.go","code":"// NewEffectiveContainerSecurityContextMutator returns a mutator for reading and writing effective values\n// for the provided pod security context and container security context\nfunc NewEffectiveContainerSecurityContextMutator(podSC PodSecurityContextAccessor, containerSC ContainerSecurityContextMutator) ContainerSecurityContextMutator {\n\treturn \u0026effectiveContainerSecurityContextWrapper{podSC: podSC, containerSC: containerSC}\n}","line":{"from":411,"to":415}} {"id":100011499,"name":"ContainerSecurityContext","signature":"func (w *effectiveContainerSecurityContextWrapper) ContainerSecurityContext() *api.SecurityContext","file":"pkg/securitycontext/accessors.go","code":"func (w *effectiveContainerSecurityContextWrapper) ContainerSecurityContext() *api.SecurityContext {\n\treturn w.containerSC.ContainerSecurityContext()\n}","line":{"from":422,"to":424}} {"id":100011500,"name":"Capabilities","signature":"func (w *effectiveContainerSecurityContextWrapper) Capabilities() *api.Capabilities","file":"pkg/securitycontext/accessors.go","code":"func (w *effectiveContainerSecurityContextWrapper) Capabilities() *api.Capabilities {\n\treturn w.containerSC.Capabilities()\n}","line":{"from":426,"to":428}} {"id":100011501,"name":"SetCapabilities","signature":"func (w *effectiveContainerSecurityContextWrapper) SetCapabilities(v *api.Capabilities)","file":"pkg/securitycontext/accessors.go","code":"func (w *effectiveContainerSecurityContextWrapper) SetCapabilities(v *api.Capabilities) {\n\tif !reflect.DeepEqual(w.Capabilities(), v) {\n\t\tw.containerSC.SetCapabilities(v)\n\t}\n}","line":{"from":429,"to":433}} {"id":100011502,"name":"Privileged","signature":"func (w *effectiveContainerSecurityContextWrapper) Privileged() *bool","file":"pkg/securitycontext/accessors.go","code":"func (w *effectiveContainerSecurityContextWrapper) Privileged() *bool {\n\treturn w.containerSC.Privileged()\n}","line":{"from":434,"to":436}} {"id":100011503,"name":"SetPrivileged","signature":"func (w *effectiveContainerSecurityContextWrapper) SetPrivileged(v *bool)","file":"pkg/securitycontext/accessors.go","code":"func (w *effectiveContainerSecurityContextWrapper) SetPrivileged(v *bool) {\n\tif !reflect.DeepEqual(w.Privileged(), v) {\n\t\tw.containerSC.SetPrivileged(v)\n\t}\n}","line":{"from":437,"to":441}} {"id":100011504,"name":"ProcMount","signature":"func (w *effectiveContainerSecurityContextWrapper) ProcMount() api.ProcMountType","file":"pkg/securitycontext/accessors.go","code":"func (w *effectiveContainerSecurityContextWrapper) ProcMount() api.ProcMountType {\n\treturn w.containerSC.ProcMount()\n}","line":{"from":442,"to":444}} {"id":100011505,"name":"SELinuxOptions","signature":"func (w *effectiveContainerSecurityContextWrapper) SELinuxOptions() *api.SELinuxOptions","file":"pkg/securitycontext/accessors.go","code":"func (w *effectiveContainerSecurityContextWrapper) SELinuxOptions() *api.SELinuxOptions {\n\tif v := w.containerSC.SELinuxOptions(); v != nil {\n\t\treturn v\n\t}\n\treturn w.podSC.SELinuxOptions()\n}","line":{"from":445,"to":450}} {"id":100011506,"name":"SetSELinuxOptions","signature":"func (w *effectiveContainerSecurityContextWrapper) SetSELinuxOptions(v *api.SELinuxOptions)","file":"pkg/securitycontext/accessors.go","code":"func (w *effectiveContainerSecurityContextWrapper) SetSELinuxOptions(v *api.SELinuxOptions) {\n\tif !reflect.DeepEqual(w.SELinuxOptions(), v) {\n\t\tw.containerSC.SetSELinuxOptions(v)\n\t}\n}","line":{"from":451,"to":455}} {"id":100011507,"name":"RunAsUser","signature":"func (w *effectiveContainerSecurityContextWrapper) RunAsUser() *int64","file":"pkg/securitycontext/accessors.go","code":"func (w *effectiveContainerSecurityContextWrapper) RunAsUser() *int64 {\n\tif v := w.containerSC.RunAsUser(); v != nil {\n\t\treturn v\n\t}\n\treturn w.podSC.RunAsUser()\n}","line":{"from":456,"to":461}} {"id":100011508,"name":"SetRunAsUser","signature":"func (w *effectiveContainerSecurityContextWrapper) SetRunAsUser(v *int64)","file":"pkg/securitycontext/accessors.go","code":"func (w *effectiveContainerSecurityContextWrapper) SetRunAsUser(v *int64) {\n\tif !reflect.DeepEqual(w.RunAsUser(), v) {\n\t\tw.containerSC.SetRunAsUser(v)\n\t}\n}","line":{"from":462,"to":466}} {"id":100011509,"name":"RunAsGroup","signature":"func (w *effectiveContainerSecurityContextWrapper) RunAsGroup() *int64","file":"pkg/securitycontext/accessors.go","code":"func (w *effectiveContainerSecurityContextWrapper) RunAsGroup() *int64 {\n\tif v := w.containerSC.RunAsGroup(); v != nil {\n\t\treturn v\n\t}\n\treturn w.podSC.RunAsGroup()\n}","line":{"from":467,"to":472}} {"id":100011510,"name":"SetRunAsGroup","signature":"func (w *effectiveContainerSecurityContextWrapper) SetRunAsGroup(v *int64)","file":"pkg/securitycontext/accessors.go","code":"func (w *effectiveContainerSecurityContextWrapper) SetRunAsGroup(v *int64) {\n\tif !reflect.DeepEqual(w.RunAsGroup(), v) {\n\t\tw.containerSC.SetRunAsGroup(v)\n\t}\n}","line":{"from":473,"to":477}} {"id":100011511,"name":"RunAsNonRoot","signature":"func (w *effectiveContainerSecurityContextWrapper) RunAsNonRoot() *bool","file":"pkg/securitycontext/accessors.go","code":"func (w *effectiveContainerSecurityContextWrapper) RunAsNonRoot() *bool {\n\tif v := w.containerSC.RunAsNonRoot(); v != nil {\n\t\treturn v\n\t}\n\treturn w.podSC.RunAsNonRoot()\n}","line":{"from":479,"to":484}} {"id":100011512,"name":"SetRunAsNonRoot","signature":"func (w *effectiveContainerSecurityContextWrapper) SetRunAsNonRoot(v *bool)","file":"pkg/securitycontext/accessors.go","code":"func (w *effectiveContainerSecurityContextWrapper) SetRunAsNonRoot(v *bool) {\n\tif !reflect.DeepEqual(w.RunAsNonRoot(), v) {\n\t\tw.containerSC.SetRunAsNonRoot(v)\n\t}\n}","line":{"from":485,"to":489}} {"id":100011513,"name":"ReadOnlyRootFilesystem","signature":"func (w *effectiveContainerSecurityContextWrapper) ReadOnlyRootFilesystem() *bool","file":"pkg/securitycontext/accessors.go","code":"func (w *effectiveContainerSecurityContextWrapper) ReadOnlyRootFilesystem() *bool {\n\treturn w.containerSC.ReadOnlyRootFilesystem()\n}","line":{"from":490,"to":492}} {"id":100011514,"name":"SetReadOnlyRootFilesystem","signature":"func (w *effectiveContainerSecurityContextWrapper) SetReadOnlyRootFilesystem(v *bool)","file":"pkg/securitycontext/accessors.go","code":"func (w *effectiveContainerSecurityContextWrapper) SetReadOnlyRootFilesystem(v *bool) {\n\tif !reflect.DeepEqual(w.ReadOnlyRootFilesystem(), v) {\n\t\tw.containerSC.SetReadOnlyRootFilesystem(v)\n\t}\n}","line":{"from":493,"to":497}} {"id":100011515,"name":"SeccompProfile","signature":"func (w *effectiveContainerSecurityContextWrapper) SeccompProfile() *api.SeccompProfile","file":"pkg/securitycontext/accessors.go","code":"func (w *effectiveContainerSecurityContextWrapper) SeccompProfile() *api.SeccompProfile {\n\treturn w.containerSC.SeccompProfile()\n}","line":{"from":498,"to":500}} {"id":100011516,"name":"SetSeccompProfile","signature":"func (w *effectiveContainerSecurityContextWrapper) SetSeccompProfile(p *api.SeccompProfile)","file":"pkg/securitycontext/accessors.go","code":"func (w *effectiveContainerSecurityContextWrapper) SetSeccompProfile(p *api.SeccompProfile) {\n\tif !reflect.DeepEqual(w.SeccompProfile(), p) {\n\t\tw.containerSC.SetSeccompProfile(p)\n\t}\n}","line":{"from":501,"to":505}} {"id":100011517,"name":"AllowPrivilegeEscalation","signature":"func (w *effectiveContainerSecurityContextWrapper) AllowPrivilegeEscalation() *bool","file":"pkg/securitycontext/accessors.go","code":"func (w *effectiveContainerSecurityContextWrapper) AllowPrivilegeEscalation() *bool {\n\treturn w.containerSC.AllowPrivilegeEscalation()\n}","line":{"from":506,"to":508}} {"id":100011518,"name":"SetAllowPrivilegeEscalation","signature":"func (w *effectiveContainerSecurityContextWrapper) SetAllowPrivilegeEscalation(v *bool)","file":"pkg/securitycontext/accessors.go","code":"func (w *effectiveContainerSecurityContextWrapper) SetAllowPrivilegeEscalation(v *bool) {\n\tif !reflect.DeepEqual(w.AllowPrivilegeEscalation(), v) {\n\t\tw.containerSC.SetAllowPrivilegeEscalation(v)\n\t}\n}","line":{"from":509,"to":513}} {"id":100011519,"name":"HasWindowsHostProcessRequest","signature":"func HasWindowsHostProcessRequest(pod *v1.Pod, container *v1.Container) bool","file":"pkg/securitycontext/util.go","code":"// HasWindowsHostProcessRequest returns true if container should run as HostProcess container,\n// taking into account nils\nfunc HasWindowsHostProcessRequest(pod *v1.Pod, container *v1.Container) bool {\n\teffectiveSc := DetermineEffectiveSecurityContext(pod, container)\n\n\tif effectiveSc.WindowsOptions == nil {\n\t\treturn false\n\t}\n\tif effectiveSc.WindowsOptions.HostProcess == nil {\n\t\treturn false\n\t}\n\treturn *effectiveSc.WindowsOptions.HostProcess\n}","line":{"from":23,"to":35}} {"id":100011520,"name":"DetermineEffectiveSecurityContext","signature":"func DetermineEffectiveSecurityContext(pod *v1.Pod, container *v1.Container) *v1.SecurityContext","file":"pkg/securitycontext/util.go","code":"// DetermineEffectiveSecurityContext returns a synthesized SecurityContext for reading effective configurations\n// from the provided pod's and container's security context. Container's fields take precedence in cases where both\n// are set\nfunc DetermineEffectiveSecurityContext(pod *v1.Pod, container *v1.Container) *v1.SecurityContext {\n\teffectiveSc := securityContextFromPodSecurityContext(pod)\n\tcontainerSc := container.SecurityContext\n\n\tif effectiveSc == nil \u0026\u0026 containerSc == nil {\n\t\treturn \u0026v1.SecurityContext{}\n\t}\n\tif effectiveSc != nil \u0026\u0026 containerSc == nil {\n\t\treturn effectiveSc\n\t}\n\tif effectiveSc == nil \u0026\u0026 containerSc != nil {\n\t\treturn containerSc\n\t}\n\n\tif containerSc.SELinuxOptions != nil {\n\t\teffectiveSc.SELinuxOptions = new(v1.SELinuxOptions)\n\t\t*effectiveSc.SELinuxOptions = *containerSc.SELinuxOptions\n\t}\n\n\tif containerSc.WindowsOptions != nil {\n\t\t// only override fields that are set at the container level, not the whole thing\n\t\tif effectiveSc.WindowsOptions == nil {\n\t\t\teffectiveSc.WindowsOptions = \u0026v1.WindowsSecurityContextOptions{}\n\t\t}\n\t\tif containerSc.WindowsOptions.GMSACredentialSpecName != nil || containerSc.WindowsOptions.GMSACredentialSpec != nil {\n\t\t\t// both GMSA fields go hand in hand\n\t\t\teffectiveSc.WindowsOptions.GMSACredentialSpecName = containerSc.WindowsOptions.GMSACredentialSpecName\n\t\t\teffectiveSc.WindowsOptions.GMSACredentialSpec = containerSc.WindowsOptions.GMSACredentialSpec\n\t\t}\n\t\tif containerSc.WindowsOptions.RunAsUserName != nil {\n\t\t\teffectiveSc.WindowsOptions.RunAsUserName = containerSc.WindowsOptions.RunAsUserName\n\t\t}\n\t\tif containerSc.WindowsOptions.HostProcess != nil {\n\t\t\teffectiveSc.WindowsOptions.HostProcess = containerSc.WindowsOptions.HostProcess\n\t\t}\n\t}\n\n\tif containerSc.Capabilities != nil {\n\t\teffectiveSc.Capabilities = new(v1.Capabilities)\n\t\t*effectiveSc.Capabilities = *containerSc.Capabilities\n\t}\n\n\tif containerSc.Privileged != nil {\n\t\teffectiveSc.Privileged = new(bool)\n\t\t*effectiveSc.Privileged = *containerSc.Privileged\n\t}\n\n\tif containerSc.RunAsUser != nil {\n\t\teffectiveSc.RunAsUser = new(int64)\n\t\t*effectiveSc.RunAsUser = *containerSc.RunAsUser\n\t}\n\n\tif containerSc.RunAsGroup != nil {\n\t\teffectiveSc.RunAsGroup = new(int64)\n\t\t*effectiveSc.RunAsGroup = *containerSc.RunAsGroup\n\t}\n\n\tif containerSc.RunAsNonRoot != nil {\n\t\teffectiveSc.RunAsNonRoot = new(bool)\n\t\t*effectiveSc.RunAsNonRoot = *containerSc.RunAsNonRoot\n\t}\n\n\tif containerSc.ReadOnlyRootFilesystem != nil {\n\t\teffectiveSc.ReadOnlyRootFilesystem = new(bool)\n\t\t*effectiveSc.ReadOnlyRootFilesystem = *containerSc.ReadOnlyRootFilesystem\n\t}\n\n\tif containerSc.AllowPrivilegeEscalation != nil {\n\t\teffectiveSc.AllowPrivilegeEscalation = new(bool)\n\t\t*effectiveSc.AllowPrivilegeEscalation = *containerSc.AllowPrivilegeEscalation\n\t}\n\n\tif containerSc.ProcMount != nil {\n\t\teffectiveSc.ProcMount = new(v1.ProcMountType)\n\t\t*effectiveSc.ProcMount = *containerSc.ProcMount\n\t}\n\n\treturn effectiveSc\n}","line":{"from":37,"to":118}} {"id":100011521,"name":"DetermineEffectiveRunAsUser","signature":"func DetermineEffectiveRunAsUser(pod *v1.Pod, container *v1.Container) (*int64, bool)","file":"pkg/securitycontext/util.go","code":"// DetermineEffectiveRunAsUser returns a pointer of UID from the provided pod's\n// and container's security context and a bool value to indicate if it is absent.\n// Container's runAsUser take precedence in cases where both are set.\nfunc DetermineEffectiveRunAsUser(pod *v1.Pod, container *v1.Container) (*int64, bool) {\n\tvar runAsUser *int64\n\tif pod.Spec.SecurityContext != nil \u0026\u0026 pod.Spec.SecurityContext.RunAsUser != nil {\n\t\trunAsUser = new(int64)\n\t\t*runAsUser = *pod.Spec.SecurityContext.RunAsUser\n\t}\n\tif container.SecurityContext != nil \u0026\u0026 container.SecurityContext.RunAsUser != nil {\n\t\trunAsUser = new(int64)\n\t\t*runAsUser = *container.SecurityContext.RunAsUser\n\t}\n\tif runAsUser == nil {\n\t\treturn nil, false\n\t}\n\treturn runAsUser, true\n}","line":{"from":120,"to":137}} {"id":100011522,"name":"securityContextFromPodSecurityContext","signature":"func securityContextFromPodSecurityContext(pod *v1.Pod) *v1.SecurityContext","file":"pkg/securitycontext/util.go","code":"func securityContextFromPodSecurityContext(pod *v1.Pod) *v1.SecurityContext {\n\tif pod.Spec.SecurityContext == nil {\n\t\treturn nil\n\t}\n\n\tsynthesized := \u0026v1.SecurityContext{}\n\n\tif pod.Spec.SecurityContext.SELinuxOptions != nil {\n\t\tsynthesized.SELinuxOptions = \u0026v1.SELinuxOptions{}\n\t\t*synthesized.SELinuxOptions = *pod.Spec.SecurityContext.SELinuxOptions\n\t}\n\n\tif pod.Spec.SecurityContext.WindowsOptions != nil {\n\t\tsynthesized.WindowsOptions = \u0026v1.WindowsSecurityContextOptions{}\n\t\t*synthesized.WindowsOptions = *pod.Spec.SecurityContext.WindowsOptions\n\t}\n\n\tif pod.Spec.SecurityContext.RunAsUser != nil {\n\t\tsynthesized.RunAsUser = new(int64)\n\t\t*synthesized.RunAsUser = *pod.Spec.SecurityContext.RunAsUser\n\t}\n\n\tif pod.Spec.SecurityContext.RunAsGroup != nil {\n\t\tsynthesized.RunAsGroup = new(int64)\n\t\t*synthesized.RunAsGroup = *pod.Spec.SecurityContext.RunAsGroup\n\t}\n\n\tif pod.Spec.SecurityContext.RunAsNonRoot != nil {\n\t\tsynthesized.RunAsNonRoot = new(bool)\n\t\t*synthesized.RunAsNonRoot = *pod.Spec.SecurityContext.RunAsNonRoot\n\t}\n\n\treturn synthesized\n}","line":{"from":139,"to":172}} {"id":100011523,"name":"AddNoNewPrivileges","signature":"func AddNoNewPrivileges(sc *v1.SecurityContext) bool","file":"pkg/securitycontext/util.go","code":"// AddNoNewPrivileges returns if we should add the no_new_privs option.\nfunc AddNoNewPrivileges(sc *v1.SecurityContext) bool {\n\tif sc == nil {\n\t\treturn false\n\t}\n\n\t// handle the case where the user did not set the default and did not explicitly set allowPrivilegeEscalation\n\tif sc.AllowPrivilegeEscalation == nil {\n\t\treturn false\n\t}\n\n\t// handle the case where defaultAllowPrivilegeEscalation is false or the user explicitly set allowPrivilegeEscalation to true/false\n\treturn !*sc.AllowPrivilegeEscalation\n}","line":{"from":174,"to":187}} {"id":100011524,"name":"ConvertToRuntimeMaskedPaths","signature":"func ConvertToRuntimeMaskedPaths(opt *v1.ProcMountType) []string","file":"pkg/securitycontext/util.go","code":"// ConvertToRuntimeMaskedPaths converts the ProcMountType to the specified or default\n// masked paths.\nfunc ConvertToRuntimeMaskedPaths(opt *v1.ProcMountType) []string {\n\tif opt != nil \u0026\u0026 *opt == v1.UnmaskedProcMount {\n\t\t// Unmasked proc mount should have no paths set as masked.\n\t\treturn []string{}\n\t}\n\n\t// Otherwise, add the default masked paths to the runtime security context.\n\treturn defaultMaskedPaths\n}","line":{"from":214,"to":224}} {"id":100011525,"name":"ConvertToRuntimeReadonlyPaths","signature":"func ConvertToRuntimeReadonlyPaths(opt *v1.ProcMountType) []string","file":"pkg/securitycontext/util.go","code":"// ConvertToRuntimeReadonlyPaths converts the ProcMountType to the specified or default\n// readonly paths.\nfunc ConvertToRuntimeReadonlyPaths(opt *v1.ProcMountType) []string {\n\tif opt != nil \u0026\u0026 *opt == v1.UnmaskedProcMount {\n\t\t// Unmasked proc mount should have no paths set as readonly.\n\t\treturn []string{}\n\t}\n\n\t// Otherwise, add the default readonly paths to the runtime security context.\n\treturn defaultReadonlyPaths\n}","line":{"from":226,"to":236}} {"id":100011526,"name":"Claims","signature":"func Claims(sa core.ServiceAccount, pod *core.Pod, secret *core.Secret, expirationSeconds, warnafter int64, audience []string) (*jwt.Claims, interface{})","file":"pkg/serviceaccount/claims.go","code":"func Claims(sa core.ServiceAccount, pod *core.Pod, secret *core.Secret, expirationSeconds, warnafter int64, audience []string) (*jwt.Claims, interface{}) {\n\tnow := now()\n\tsc := \u0026jwt.Claims{\n\t\tSubject: apiserverserviceaccount.MakeUsername(sa.Namespace, sa.Name),\n\t\tAudience: jwt.Audience(audience),\n\t\tIssuedAt: jwt.NewNumericDate(now),\n\t\tNotBefore: jwt.NewNumericDate(now),\n\t\tExpiry: jwt.NewNumericDate(now.Add(time.Duration(expirationSeconds) * time.Second)),\n\t}\n\tpc := \u0026privateClaims{\n\t\tKubernetes: kubernetes{\n\t\t\tNamespace: sa.Namespace,\n\t\t\tSvcacct: ref{\n\t\t\t\tName: sa.Name,\n\t\t\t\tUID: string(sa.UID),\n\t\t\t},\n\t\t},\n\t}\n\tswitch {\n\tcase pod != nil:\n\t\tpc.Kubernetes.Pod = \u0026ref{\n\t\t\tName: pod.Name,\n\t\t\tUID: string(pod.UID),\n\t\t}\n\tcase secret != nil:\n\t\tpc.Kubernetes.Secret = \u0026ref{\n\t\t\tName: secret.Name,\n\t\t\tUID: string(secret.UID),\n\t\t}\n\t}\n\n\tif warnafter != 0 {\n\t\tpc.Kubernetes.WarnAfter = jwt.NewNumericDate(now.Add(time.Duration(warnafter) * time.Second))\n\t}\n\n\treturn sc, pc\n}","line":{"from":61,"to":97}} {"id":100011527,"name":"NewValidator","signature":"func NewValidator(getter ServiceAccountTokenGetter) Validator","file":"pkg/serviceaccount/claims.go","code":"func NewValidator(getter ServiceAccountTokenGetter) Validator {\n\treturn \u0026validator{\n\t\tgetter: getter,\n\t}\n}","line":{"from":99,"to":103}} {"id":100011528,"name":"Validate","signature":"func (v *validator) Validate(ctx context.Context, _ string, public *jwt.Claims, privateObj interface{}) (*apiserverserviceaccount.ServiceAccountInfo, error)","file":"pkg/serviceaccount/claims.go","code":"func (v *validator) Validate(ctx context.Context, _ string, public *jwt.Claims, privateObj interface{}) (*apiserverserviceaccount.ServiceAccountInfo, error) {\n\tprivate, ok := privateObj.(*privateClaims)\n\tif !ok {\n\t\tklog.Errorf(\"service account jwt validator expected private claim of type *privateClaims but got: %T\", privateObj)\n\t\treturn nil, errors.New(\"service account token claims could not be validated due to unexpected private claim\")\n\t}\n\tnowTime := now()\n\terr := public.Validate(jwt.Expected{\n\t\tTime: nowTime,\n\t})\n\tswitch err {\n\tcase nil:\n\t\t// successful validation\n\n\tcase jwt.ErrExpired:\n\t\treturn nil, errors.New(\"service account token has expired\")\n\n\tcase jwt.ErrNotValidYet:\n\t\treturn nil, errors.New(\"service account token is not valid yet\")\n\n\tcase jwt.ErrIssuedInTheFuture:\n\t\treturn nil, errors.New(\"service account token is issued in the future\")\n\n\t// our current use of jwt.Expected above should make these cases impossible to hit\n\tcase jwt.ErrInvalidAudience, jwt.ErrInvalidID, jwt.ErrInvalidIssuer, jwt.ErrInvalidSubject:\n\t\tklog.Errorf(\"service account token claim validation got unexpected validation failure: %v\", err)\n\t\treturn nil, fmt.Errorf(\"service account token claims could not be validated: %w\", err) // safe to pass these errors back to the user\n\n\tdefault:\n\t\tklog.Errorf(\"service account token claim validation got unexpected error type: %T\", err) // avoid leaking unexpected information into the logs\n\t\treturn nil, errors.New(\"service account token claims could not be validated due to unexpected validation error\") // return an opaque error\n\t}\n\n\t// consider things deleted prior to now()-leeway to be invalid\n\tinvalidIfDeletedBefore := nowTime.Add(-jwt.DefaultLeeway)\n\tnamespace := private.Kubernetes.Namespace\n\tsaref := private.Kubernetes.Svcacct\n\tpodref := private.Kubernetes.Pod\n\tsecref := private.Kubernetes.Secret\n\t// Make sure service account still exists (name and UID)\n\tserviceAccount, err := v.getter.GetServiceAccount(namespace, saref.Name)\n\tif err != nil {\n\t\tklog.V(4).Infof(\"Could not retrieve service account %s/%s: %v\", namespace, saref.Name, err)\n\t\treturn nil, err\n\t}\n\tif serviceAccount.DeletionTimestamp != nil \u0026\u0026 serviceAccount.DeletionTimestamp.Time.Before(invalidIfDeletedBefore) {\n\t\tklog.V(4).Infof(\"Service account has been deleted %s/%s\", namespace, saref.Name)\n\t\treturn nil, fmt.Errorf(\"service account %s/%s has been deleted\", namespace, saref.Name)\n\t}\n\tif string(serviceAccount.UID) != saref.UID {\n\t\tklog.V(4).Infof(\"Service account UID no longer matches %s/%s: %q != %q\", namespace, saref.Name, string(serviceAccount.UID), saref.UID)\n\t\treturn nil, fmt.Errorf(\"service account UID (%s) does not match claim (%s)\", serviceAccount.UID, saref.UID)\n\t}\n\n\tif secref != nil {\n\t\t// Make sure token hasn't been invalidated by deletion of the secret\n\t\tsecret, err := v.getter.GetSecret(namespace, secref.Name)\n\t\tif err != nil {\n\t\t\tklog.V(4).Infof(\"Could not retrieve bound secret %s/%s for service account %s/%s: %v\", namespace, secref.Name, namespace, saref.Name, err)\n\t\t\treturn nil, errors.New(\"service account token has been invalidated\")\n\t\t}\n\t\tif secret.DeletionTimestamp != nil \u0026\u0026 secret.DeletionTimestamp.Time.Before(invalidIfDeletedBefore) {\n\t\t\tklog.V(4).Infof(\"Bound secret is deleted and awaiting removal: %s/%s for service account %s/%s\", namespace, secref.Name, namespace, saref.Name)\n\t\t\treturn nil, errors.New(\"service account token has been invalidated\")\n\t\t}\n\t\tif secref.UID != string(secret.UID) {\n\t\t\tklog.V(4).Infof(\"Secret UID no longer matches %s/%s: %q != %q\", namespace, secref.Name, string(secret.UID), secref.UID)\n\t\t\treturn nil, fmt.Errorf(\"secret UID (%s) does not match service account secret ref claim (%s)\", secret.UID, secref.UID)\n\t\t}\n\t}\n\n\tvar podName, podUID string\n\tif podref != nil {\n\t\t// Make sure token hasn't been invalidated by deletion of the pod\n\t\tpod, err := v.getter.GetPod(namespace, podref.Name)\n\t\tif err != nil {\n\t\t\tklog.V(4).Infof(\"Could not retrieve bound pod %s/%s for service account %s/%s: %v\", namespace, podref.Name, namespace, saref.Name, err)\n\t\t\treturn nil, errors.New(\"service account token has been invalidated\")\n\t\t}\n\t\tif pod.DeletionTimestamp != nil \u0026\u0026 pod.DeletionTimestamp.Time.Before(invalidIfDeletedBefore) {\n\t\t\tklog.V(4).Infof(\"Bound pod is deleted and awaiting removal: %s/%s for service account %s/%s\", namespace, podref.Name, namespace, saref.Name)\n\t\t\treturn nil, errors.New(\"service account token has been invalidated\")\n\t\t}\n\t\tif podref.UID != string(pod.UID) {\n\t\t\tklog.V(4).Infof(\"Pod UID no longer matches %s/%s: %q != %q\", namespace, podref.Name, string(pod.UID), podref.UID)\n\t\t\treturn nil, fmt.Errorf(\"pod UID (%s) does not match service account pod ref claim (%s)\", pod.UID, podref.UID)\n\t\t}\n\t\tpodName = podref.Name\n\t\tpodUID = podref.UID\n\t}\n\n\t// Check special 'warnafter' field for projected service account token transition.\n\twarnafter := private.Kubernetes.WarnAfter\n\tif warnafter != nil \u0026\u0026 *warnafter != 0 {\n\t\tif nowTime.After(warnafter.Time()) {\n\t\t\tsecondsAfterWarn := nowTime.Unix() - warnafter.Time().Unix()\n\t\t\tauditInfo := fmt.Sprintf(\"subject: %s, seconds after warning threshold: %d\", public.Subject, secondsAfterWarn)\n\t\t\taudit.AddAuditAnnotation(ctx, \"authentication.k8s.io/stale-token\", auditInfo)\n\t\t\tstaleTokensTotal.WithContext(ctx).Inc()\n\t\t} else {\n\t\t\tvalidTokensTotal.WithContext(ctx).Inc()\n\t\t}\n\t}\n\n\treturn \u0026apiserverserviceaccount.ServiceAccountInfo{\n\t\tNamespace: private.Kubernetes.Namespace,\n\t\tName: private.Kubernetes.Svcacct.Name,\n\t\tUID: private.Kubernetes.Svcacct.UID,\n\t\tPodName: podName,\n\t\tPodUID: podUID,\n\t}, nil\n}","line":{"from":111,"to":222}} {"id":100011529,"name":"NewPrivateClaims","signature":"func (v *validator) NewPrivateClaims() interface{}","file":"pkg/serviceaccount/claims.go","code":"func (v *validator) NewPrivateClaims() interface{} {\n\treturn \u0026privateClaims{}\n}","line":{"from":224,"to":226}} {"id":100011530,"name":"JWTTokenGenerator","signature":"func JWTTokenGenerator(iss string, privateKey interface{}) (TokenGenerator, error)","file":"pkg/serviceaccount/jwt.go","code":"// JWTTokenGenerator returns a TokenGenerator that generates signed JWT tokens, using the given privateKey.\n// privateKey is a PEM-encoded byte array of a private RSA key.\nfunc JWTTokenGenerator(iss string, privateKey interface{}) (TokenGenerator, error) {\n\tvar signer jose.Signer\n\tvar err error\n\tswitch pk := privateKey.(type) {\n\tcase *rsa.PrivateKey:\n\t\tsigner, err = signerFromRSAPrivateKey(pk)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"could not generate signer for RSA keypair: %v\", err)\n\t\t}\n\tcase *ecdsa.PrivateKey:\n\t\tsigner, err = signerFromECDSAPrivateKey(pk)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"could not generate signer for ECDSA keypair: %v\", err)\n\t\t}\n\tcase jose.OpaqueSigner:\n\t\tsigner, err = signerFromOpaqueSigner(pk)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"could not generate signer for OpaqueSigner: %v\", err)\n\t\t}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown private key type %T, must be *rsa.PrivateKey, *ecdsa.PrivateKey, or jose.OpaqueSigner\", privateKey)\n\t}\n\n\treturn \u0026jwtTokenGenerator{\n\t\tiss: iss,\n\t\tsigner: signer,\n\t}, nil\n}","line":{"from":58,"to":87}} {"id":100011531,"name":"keyIDFromPublicKey","signature":"func keyIDFromPublicKey(publicKey interface{}) (string, error)","file":"pkg/serviceaccount/jwt.go","code":"// keyIDFromPublicKey derives a key ID non-reversibly from a public key.\n//\n// The Key ID is field on a given on JWTs and JWKs that help relying parties\n// pick the correct key for verification when the identity party advertises\n// multiple keys.\n//\n// Making the derivation non-reversible makes it impossible for someone to\n// accidentally obtain the real key from the key ID and use it for token\n// validation.\nfunc keyIDFromPublicKey(publicKey interface{}) (string, error) {\n\tpublicKeyDERBytes, err := x509.MarshalPKIXPublicKey(publicKey)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to serialize public key to DER format: %v\", err)\n\t}\n\n\thasher := crypto.SHA256.New()\n\thasher.Write(publicKeyDERBytes)\n\tpublicKeyDERHash := hasher.Sum(nil)\n\n\tkeyID := base64.RawURLEncoding.EncodeToString(publicKeyDERHash)\n\n\treturn keyID, nil\n}","line":{"from":89,"to":111}} {"id":100011532,"name":"signerFromRSAPrivateKey","signature":"func signerFromRSAPrivateKey(keyPair *rsa.PrivateKey) (jose.Signer, error)","file":"pkg/serviceaccount/jwt.go","code":"func signerFromRSAPrivateKey(keyPair *rsa.PrivateKey) (jose.Signer, error) {\n\tkeyID, err := keyIDFromPublicKey(\u0026keyPair.PublicKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to derive keyID: %v\", err)\n\t}\n\n\t// IMPORTANT: If this function is updated to support additional key sizes,\n\t// algorithmForPublicKey in serviceaccount/openidmetadata.go must also be\n\t// updated to support the same key sizes. Today we only support RS256.\n\n\t// Wrap the RSA keypair in a JOSE JWK with the designated key ID.\n\tprivateJWK := \u0026jose.JSONWebKey{\n\t\tAlgorithm: string(jose.RS256),\n\t\tKey: keyPair,\n\t\tKeyID: keyID,\n\t\tUse: \"sig\",\n\t}\n\n\tsigner, err := jose.NewSigner(\n\t\tjose.SigningKey{\n\t\t\tAlgorithm: jose.RS256,\n\t\t\tKey: privateJWK,\n\t\t},\n\t\tnil,\n\t)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create signer: %v\", err)\n\t}\n\n\treturn signer, nil\n}","line":{"from":113,"to":144}} {"id":100011533,"name":"signerFromECDSAPrivateKey","signature":"func signerFromECDSAPrivateKey(keyPair *ecdsa.PrivateKey) (jose.Signer, error)","file":"pkg/serviceaccount/jwt.go","code":"func signerFromECDSAPrivateKey(keyPair *ecdsa.PrivateKey) (jose.Signer, error) {\n\tvar alg jose.SignatureAlgorithm\n\tswitch keyPair.Curve {\n\tcase elliptic.P256():\n\t\talg = jose.ES256\n\tcase elliptic.P384():\n\t\talg = jose.ES384\n\tcase elliptic.P521():\n\t\talg = jose.ES512\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown private key curve, must be 256, 384, or 521\")\n\t}\n\n\tkeyID, err := keyIDFromPublicKey(\u0026keyPair.PublicKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to derive keyID: %v\", err)\n\t}\n\n\t// Wrap the ECDSA keypair in a JOSE JWK with the designated key ID.\n\tprivateJWK := \u0026jose.JSONWebKey{\n\t\tAlgorithm: string(alg),\n\t\tKey: keyPair,\n\t\tKeyID: keyID,\n\t\tUse: \"sig\",\n\t}\n\n\tsigner, err := jose.NewSigner(\n\t\tjose.SigningKey{\n\t\t\tAlgorithm: alg,\n\t\t\tKey: privateJWK,\n\t\t},\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create signer: %v\", err)\n\t}\n\n\treturn signer, nil\n}","line":{"from":146,"to":184}} {"id":100011534,"name":"signerFromOpaqueSigner","signature":"func signerFromOpaqueSigner(opaqueSigner jose.OpaqueSigner) (jose.Signer, error)","file":"pkg/serviceaccount/jwt.go","code":"func signerFromOpaqueSigner(opaqueSigner jose.OpaqueSigner) (jose.Signer, error) {\n\talg := jose.SignatureAlgorithm(opaqueSigner.Public().Algorithm)\n\n\tsigner, err := jose.NewSigner(\n\t\tjose.SigningKey{\n\t\t\tAlgorithm: alg,\n\t\t\tKey: \u0026jose.JSONWebKey{\n\t\t\t\tAlgorithm: string(alg),\n\t\t\t\tKey: opaqueSigner,\n\t\t\t\tKeyID: opaqueSigner.Public().KeyID,\n\t\t\t\tUse: \"sig\",\n\t\t\t},\n\t\t},\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create signer: %v\", err)\n\t}\n\n\treturn signer, nil\n}","line":{"from":186,"to":206}} {"id":100011535,"name":"GenerateToken","signature":"func (j *jwtTokenGenerator) GenerateToken(claims *jwt.Claims, privateClaims interface{}) (string, error)","file":"pkg/serviceaccount/jwt.go","code":"func (j *jwtTokenGenerator) GenerateToken(claims *jwt.Claims, privateClaims interface{}) (string, error) {\n\t// claims are applied in reverse precedence\n\treturn jwt.Signed(j.signer).\n\t\tClaims(privateClaims).\n\t\tClaims(claims).\n\t\tClaims(\u0026jwt.Claims{\n\t\t\tIssuer: j.iss,\n\t\t}).\n\t\tCompactSerialize()\n}","line":{"from":213,"to":222}} {"id":100011536,"name":"JWTTokenAuthenticator","signature":"func JWTTokenAuthenticator(issuers []string, keys []interface{}, implicitAuds authenticator.Audiences, validator Validator) authenticator.Token","file":"pkg/serviceaccount/jwt.go","code":"// JWTTokenAuthenticator authenticates tokens as JWT tokens produced by JWTTokenGenerator\n// Token signatures are verified using each of the given public keys until one works (allowing key rotation)\n// If lookup is true, the service account and secret referenced as claims inside the token are retrieved and verified with the provided ServiceAccountTokenGetter\nfunc JWTTokenAuthenticator(issuers []string, keys []interface{}, implicitAuds authenticator.Audiences, validator Validator) authenticator.Token {\n\tissuersMap := make(map[string]bool)\n\tfor _, issuer := range issuers {\n\t\tissuersMap[issuer] = true\n\t}\n\treturn \u0026jwtTokenAuthenticator{\n\t\tissuers: issuersMap,\n\t\tkeys: keys,\n\t\timplicitAuds: implicitAuds,\n\t\tvalidator: validator,\n\t}\n}","line":{"from":224,"to":238}} {"id":100011537,"name":"AuthenticateToken","signature":"func (j *jwtTokenAuthenticator) AuthenticateToken(ctx context.Context, tokenData string) (*authenticator.Response, bool, error)","file":"pkg/serviceaccount/jwt.go","code":"func (j *jwtTokenAuthenticator) AuthenticateToken(ctx context.Context, tokenData string) (*authenticator.Response, bool, error) {\n\tif !j.hasCorrectIssuer(tokenData) {\n\t\treturn nil, false, nil\n\t}\n\n\ttok, err := jwt.ParseSigned(tokenData)\n\tif err != nil {\n\t\treturn nil, false, nil\n\t}\n\n\tpublic := \u0026jwt.Claims{}\n\tprivate := j.validator.NewPrivateClaims()\n\n\t// TODO: Pick the key that has the same key ID as `tok`, if one exists.\n\tvar (\n\t\tfound bool\n\t\terrlist []error\n\t)\n\tfor _, key := range j.keys {\n\t\tif err := tok.Claims(key, public, private); err != nil {\n\t\t\terrlist = append(errlist, err)\n\t\t\tcontinue\n\t\t}\n\t\tfound = true\n\t\tbreak\n\t}\n\n\tif !found {\n\t\treturn nil, false, utilerrors.NewAggregate(errlist)\n\t}\n\n\ttokenAudiences := authenticator.Audiences(public.Audience)\n\tif len(tokenAudiences) == 0 {\n\t\t// only apiserver audiences are allowed for legacy tokens\n\t\taudit.AddAuditAnnotation(ctx, \"authentication.k8s.io/legacy-token\", public.Subject)\n\t\tlegacyTokensTotal.WithContext(ctx).Inc()\n\t\ttokenAudiences = j.implicitAuds\n\t}\n\n\trequestedAudiences, ok := authenticator.AudiencesFrom(ctx)\n\tif !ok {\n\t\t// default to apiserver audiences\n\t\trequestedAudiences = j.implicitAuds\n\t}\n\n\tauds := authenticator.Audiences(tokenAudiences).Intersect(requestedAudiences)\n\tif len(auds) == 0 \u0026\u0026 len(j.implicitAuds) != 0 {\n\t\treturn nil, false, fmt.Errorf(\"token audiences %q is invalid for the target audiences %q\", tokenAudiences, requestedAudiences)\n\t}\n\n\t// If we get here, we have a token with a recognized signature and\n\t// issuer string.\n\tsa, err := j.validator.Validate(ctx, tokenData, public, private)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\treturn \u0026authenticator.Response{\n\t\tUser: sa.UserInfo(),\n\t\tAudiences: auds,\n\t}, true, nil\n}","line":{"from":262,"to":323}} {"id":100011538,"name":"hasCorrectIssuer","signature":"func (j *jwtTokenAuthenticator) hasCorrectIssuer(tokenData string) bool","file":"pkg/serviceaccount/jwt.go","code":"// hasCorrectIssuer returns true if tokenData is a valid JWT in compact\n// serialization format and the \"iss\" claim matches the iss field of this token\n// authenticator, and otherwise returns false.\n//\n// Note: go-jose currently does not allow access to unverified JWS payloads.\n// See https://github.com/square/go-jose/issues/169\nfunc (j *jwtTokenAuthenticator) hasCorrectIssuer(tokenData string) bool {\n\tparts := strings.Split(tokenData, \".\")\n\tif len(parts) != 3 {\n\t\treturn false\n\t}\n\tpayload, err := base64.RawURLEncoding.DecodeString(parts[1])\n\tif err != nil {\n\t\treturn false\n\t}\n\tclaims := struct {\n\t\t// WARNING: this JWT is not verified. Do not trust these claims.\n\t\tIssuer string `json:\"iss\"`\n\t}{}\n\tif err := json.Unmarshal(payload, \u0026claims); err != nil {\n\t\treturn false\n\t}\n\treturn j.issuers[claims.Issuer]\n}","line":{"from":325,"to":348}} {"id":100011539,"name":"LegacyClaims","signature":"func LegacyClaims(serviceAccount v1.ServiceAccount, secret v1.Secret) (*jwt.Claims, interface{})","file":"pkg/serviceaccount/legacy.go","code":"func LegacyClaims(serviceAccount v1.ServiceAccount, secret v1.Secret) (*jwt.Claims, interface{}) {\n\treturn \u0026jwt.Claims{\n\t\t\tSubject: apiserverserviceaccount.MakeUsername(serviceAccount.Namespace, serviceAccount.Name),\n\t\t}, \u0026legacyPrivateClaims{\n\t\t\tNamespace: serviceAccount.Namespace,\n\t\t\tServiceAccountName: serviceAccount.Name,\n\t\t\tServiceAccountUID: string(serviceAccount.UID),\n\t\t\tSecretName: secret.Name,\n\t\t}\n}","line":{"from":40,"to":49}} {"id":100011540,"name":"NewLegacyValidator","signature":"func NewLegacyValidator(lookup bool, getter ServiceAccountTokenGetter, secretsWriter typedv1core.SecretsGetter) (Validator, error)","file":"pkg/serviceaccount/legacy.go","code":"func NewLegacyValidator(lookup bool, getter ServiceAccountTokenGetter, secretsWriter typedv1core.SecretsGetter) (Validator, error) {\n\tif lookup \u0026\u0026 getter == nil {\n\t\treturn nil, errors.New(\"ServiceAccountTokenGetter must be provided\")\n\t}\n\tif lookup \u0026\u0026 secretsWriter == nil \u0026\u0026 utilfeature.DefaultFeatureGate.Enabled(kubefeatures.LegacyServiceAccountTokenTracking) {\n\t\treturn nil, errors.New(\"SecretsWriter must be provided\")\n\t}\n\treturn \u0026legacyValidator{\n\t\tlookup: lookup,\n\t\tgetter: getter,\n\t\tsecretsWriter: secretsWriter,\n\t}, nil\n}","line":{"from":63,"to":75}} {"id":100011541,"name":"Validate","signature":"func (v *legacyValidator) Validate(ctx context.Context, tokenData string, public *jwt.Claims, privateObj interface{}) (*apiserverserviceaccount.ServiceAccountInfo, error)","file":"pkg/serviceaccount/legacy.go","code":"func (v *legacyValidator) Validate(ctx context.Context, tokenData string, public *jwt.Claims, privateObj interface{}) (*apiserverserviceaccount.ServiceAccountInfo, error) {\n\tprivate, ok := privateObj.(*legacyPrivateClaims)\n\tif !ok {\n\t\tklog.Errorf(\"jwt validator expected private claim of type *legacyPrivateClaims but got: %T\", privateObj)\n\t\treturn nil, errors.New(\"Token could not be validated.\")\n\t}\n\n\t// Make sure the claims we need exist\n\tif len(public.Subject) == 0 {\n\t\treturn nil, errors.New(\"sub claim is missing\")\n\t}\n\tnamespace := private.Namespace\n\tif len(namespace) == 0 {\n\t\treturn nil, errors.New(\"namespace claim is missing\")\n\t}\n\tsecretName := private.SecretName\n\tif len(secretName) == 0 {\n\t\treturn nil, errors.New(\"secretName claim is missing\")\n\t}\n\tserviceAccountName := private.ServiceAccountName\n\tif len(serviceAccountName) == 0 {\n\t\treturn nil, errors.New(\"serviceAccountName claim is missing\")\n\t}\n\tserviceAccountUID := private.ServiceAccountUID\n\tif len(serviceAccountUID) == 0 {\n\t\treturn nil, errors.New(\"serviceAccountUID claim is missing\")\n\t}\n\n\tsubjectNamespace, subjectName, err := apiserverserviceaccount.SplitUsername(public.Subject)\n\tif err != nil || subjectNamespace != namespace || subjectName != serviceAccountName {\n\t\treturn nil, errors.New(\"sub claim is invalid\")\n\t}\n\n\tif v.lookup {\n\t\t// Make sure token hasn't been invalidated by deletion of the secret\n\t\tsecret, err := v.getter.GetSecret(namespace, secretName)\n\t\tif err != nil {\n\t\t\tklog.V(4).Infof(\"Could not retrieve token %s/%s for service account %s/%s: %v\", namespace, secretName, namespace, serviceAccountName, err)\n\t\t\treturn nil, errors.New(\"Token has been invalidated\")\n\t\t}\n\t\tif secret.DeletionTimestamp != nil {\n\t\t\tklog.V(4).Infof(\"Token is deleted and awaiting removal: %s/%s for service account %s/%s\", namespace, secretName, namespace, serviceAccountName)\n\t\t\treturn nil, errors.New(\"Token has been invalidated\")\n\t\t}\n\t\tif !bytes.Equal(secret.Data[v1.ServiceAccountTokenKey], []byte(tokenData)) {\n\t\t\tklog.V(4).Infof(\"Token contents no longer matches %s/%s for service account %s/%s\", namespace, secretName, namespace, serviceAccountName)\n\t\t\treturn nil, errors.New(\"Token does not match server's copy\")\n\t\t}\n\n\t\t// Make sure service account still exists (name and UID)\n\t\tserviceAccount, err := v.getter.GetServiceAccount(namespace, serviceAccountName)\n\t\tif err != nil {\n\t\t\tklog.V(4).Infof(\"Could not retrieve service account %s/%s: %v\", namespace, serviceAccountName, err)\n\t\t\treturn nil, err\n\t\t}\n\t\tif serviceAccount.DeletionTimestamp != nil {\n\t\t\tklog.V(4).Infof(\"Service account has been deleted %s/%s\", namespace, serviceAccountName)\n\t\t\treturn nil, fmt.Errorf(\"ServiceAccount %s/%s has been deleted\", namespace, serviceAccountName)\n\t\t}\n\t\tif string(serviceAccount.UID) != serviceAccountUID {\n\t\t\tklog.V(4).Infof(\"Service account UID no longer matches %s/%s: %q != %q\", namespace, serviceAccountName, string(serviceAccount.UID), serviceAccountUID)\n\t\t\treturn nil, fmt.Errorf(\"ServiceAccount UID (%s) does not match claim (%s)\", serviceAccount.UID, serviceAccountUID)\n\t\t}\n\n\t\tif utilfeature.DefaultFeatureGate.Enabled(kubefeatures.LegacyServiceAccountTokenTracking) {\n\t\t\tfor _, ref := range serviceAccount.Secrets {\n\t\t\t\tif ref.Name == secret.Name {\n\t\t\t\t\twarning.AddWarning(ctx, \"\", \"Use tokens from the TokenRequest API or manually created secret-based tokens instead of auto-generated secret-based tokens.\")\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tnow := time.Now().UTC()\n\t\t\ttoday := now.Format(\"2006-01-02\")\n\t\t\ttomorrow := now.AddDate(0, 0, 1).Format(\"2006-01-02\")\n\t\t\tlastUsed := secret.Labels[LastUsedLabelKey]\n\t\t\tif lastUsed != today \u0026\u0026 lastUsed != tomorrow {\n\t\t\t\tpatchContent, err := json.Marshal(applyv1.Secret(secret.Name, secret.Namespace).WithLabels(map[string]string{LastUsedLabelKey: today}))\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Errorf(\"Failed to marshal legacy service account token tracking labels, err: %v\", err)\n\t\t\t\t} else {\n\t\t\t\t\tif _, err := v.secretsWriter.Secrets(namespace).Patch(ctx, secret.Name, types.MergePatchType, patchContent, metav1.PatchOptions{}); err != nil {\n\t\t\t\t\t\tklog.Errorf(\"Failed to label legacy service account token secret with last-used, err: %v\", err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \u0026apiserverserviceaccount.ServiceAccountInfo{\n\t\tNamespace: private.Namespace,\n\t\tName: private.ServiceAccountName,\n\t\tUID: private.ServiceAccountUID,\n\t}, nil\n}","line":{"from":85,"to":178}} {"id":100011542,"name":"NewPrivateClaims","signature":"func (v *legacyValidator) NewPrivateClaims() interface{}","file":"pkg/serviceaccount/legacy.go","code":"func (v *legacyValidator) NewPrivateClaims() interface{} {\n\treturn \u0026legacyPrivateClaims{}\n}","line":{"from":180,"to":182}} {"id":100011543,"name":"RegisterMetrics","signature":"func RegisterMetrics()","file":"pkg/serviceaccount/metrics.go","code":"func RegisterMetrics() {\n\tregisterMetricsOnce.Do(func() {\n\t\tlegacyregistry.MustRegister(legacyTokensTotal)\n\t\tlegacyregistry.MustRegister(staleTokensTotal)\n\t\tlegacyregistry.MustRegister(validTokensTotal)\n\t})\n}","line":{"from":63,"to":69}} {"id":100011544,"name":"NewOpenIDMetadata","signature":"func NewOpenIDMetadata(issuerURL, jwksURI, defaultExternalAddress string, pubKeys []interface{}) (*OpenIDMetadata, error)","file":"pkg/serviceaccount/openidmetadata.go","code":"// NewOpenIDMetadata returns the pre-rendered JSON responses for the OIDC discovery\n// endpoints, or an error if they could not be constructed. Callers should note\n// that this function may perform additional validation on inputs that is not\n// backwards-compatible with all command-line validation. The recommendation is\n// to log the error and skip installing the OIDC discovery endpoints.\nfunc NewOpenIDMetadata(issuerURL, jwksURI, defaultExternalAddress string, pubKeys []interface{}) (*OpenIDMetadata, error) {\n\tif issuerURL == \"\" {\n\t\treturn nil, fmt.Errorf(\"empty issuer URL\")\n\t}\n\tif jwksURI == \"\" \u0026\u0026 defaultExternalAddress == \"\" {\n\t\treturn nil, fmt.Errorf(\"either the JWKS URI or the default external address, or both, must be set\")\n\t}\n\tif len(pubKeys) == 0 {\n\t\treturn nil, fmt.Errorf(\"no keys provided for validating keyset\")\n\t}\n\n\t// Ensure the issuer URL meets the OIDC spec (this is the additional\n\t// validation the doc comment warns about).\n\t// https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata\n\tiss, err := url.Parse(issuerURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif iss.Scheme != \"https\" {\n\t\treturn nil, fmt.Errorf(\"issuer URL must use https scheme, got: %s\", issuerURL)\n\t}\n\tif iss.RawQuery != \"\" {\n\t\treturn nil, fmt.Errorf(\"issuer URL may not include a query, got: %s\", issuerURL)\n\t}\n\tif iss.Fragment != \"\" {\n\t\treturn nil, fmt.Errorf(\"issuer URL may not include a fragment, got: %s\", issuerURL)\n\t}\n\n\t// Either use the provided JWKS URI or default to ExternalAddress plus\n\t// the JWKS path.\n\tif jwksURI == \"\" {\n\t\tconst msg = \"attempted to build jwks_uri from external \" +\n\t\t\t\"address %s, but could not construct a valid URL. Error: %v\"\n\n\t\tif defaultExternalAddress == \"\" {\n\t\t\treturn nil, fmt.Errorf(msg, defaultExternalAddress,\n\t\t\t\tfmt.Errorf(\"empty address\"))\n\t\t}\n\n\t\tu := \u0026url.URL{\n\t\t\tScheme: \"https\",\n\t\t\tHost: defaultExternalAddress,\n\t\t\tPath: JWKSPath,\n\t\t}\n\t\tjwksURI = u.String()\n\n\t\t// TODO(mtaufen): I think we can probably expect ExternalAddress is\n\t\t// at most just host + port and skip the sanity check, but want to be\n\t\t// careful until that is confirmed.\n\n\t\t// Sanity check that the jwksURI we produced is the valid URL we expect.\n\t\t// This is just in case ExternalAddress came in as something weird,\n\t\t// like a scheme + host + port, instead of just host + port.\n\t\tparsed, err := url.Parse(jwksURI)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(msg, defaultExternalAddress, err)\n\t\t} else if u.Scheme != parsed.Scheme ||\n\t\t\tu.Host != parsed.Host ||\n\t\t\tu.Path != parsed.Path {\n\t\t\treturn nil, fmt.Errorf(msg, defaultExternalAddress,\n\t\t\t\tfmt.Errorf(\"got %v, expected %v\", parsed, u))\n\t\t}\n\t} else {\n\t\t// Double-check that jwksURI is an https URL\n\t\tif u, err := url.Parse(jwksURI); err != nil {\n\t\t\treturn nil, err\n\t\t} else if u.Scheme != \"https\" {\n\t\t\treturn nil, fmt.Errorf(\"jwksURI requires https scheme, parsed as: %v\", u.String())\n\t\t}\n\t}\n\n\tconfigJSON, err := openIDConfigJSON(issuerURL, jwksURI, pubKeys)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not marshal issuer discovery JSON, error: %v\", err)\n\t}\n\n\tkeysetJSON, err := openIDKeysetJSON(pubKeys)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not marshal issuer keys JSON, error: %v\", err)\n\t}\n\n\treturn \u0026OpenIDMetadata{\n\t\tConfigJSON: configJSON,\n\t\tPublicKeysetJSON: keysetJSON,\n\t}, nil\n}","line":{"from":53,"to":143}} {"id":100011545,"name":"openIDConfigJSON","signature":"func openIDConfigJSON(iss, jwksURI string, keys []interface{}) ([]byte, error)","file":"pkg/serviceaccount/openidmetadata.go","code":"// openIDConfigJSON returns the JSON OIDC Discovery Doc for the service\n// account issuer.\nfunc openIDConfigJSON(iss, jwksURI string, keys []interface{}) ([]byte, error) {\n\tkeyset, errs := publicJWKSFromKeys(keys)\n\tif errs != nil {\n\t\treturn nil, errs\n\t}\n\n\tmetadata := openIDMetadata{\n\t\tIssuer: iss,\n\t\tJWKSURI: jwksURI,\n\t\tResponseTypes: []string{\"id_token\"}, // Kubernetes only produces ID tokens\n\t\tSubjectTypes: []string{\"public\"}, // https://openid.net/specs/openid-connect-core-1_0.html#SubjectIDTypes\n\t\tSigningAlgs: getAlgs(keyset), // REQUIRED by OIDC\n\t}\n\n\tmetadataJSON, err := json.Marshal(metadata)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to marshal service account issuer metadata: %v\", err)\n\t}\n\n\treturn metadataJSON, nil\n}","line":{"from":160,"to":182}} {"id":100011546,"name":"openIDKeysetJSON","signature":"func openIDKeysetJSON(keys []interface{}) ([]byte, error)","file":"pkg/serviceaccount/openidmetadata.go","code":"// openIDKeysetJSON returns the JSON Web Key Set for the service account\n// issuer's keys.\nfunc openIDKeysetJSON(keys []interface{}) ([]byte, error) {\n\tkeyset, errs := publicJWKSFromKeys(keys)\n\tif errs != nil {\n\t\treturn nil, errs\n\t}\n\n\tkeysetJSON, err := json.Marshal(keyset)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to marshal service account issuer JWKS: %v\", err)\n\t}\n\n\treturn keysetJSON, nil\n}","line":{"from":184,"to":198}} {"id":100011547,"name":"getAlgs","signature":"func getAlgs(keys *jose.JSONWebKeySet) []string","file":"pkg/serviceaccount/openidmetadata.go","code":"func getAlgs(keys *jose.JSONWebKeySet) []string {\n\talgs := sets.NewString()\n\tfor _, k := range keys.Keys {\n\t\talgs.Insert(k.Algorithm)\n\t}\n\t// Note: List returns a sorted slice.\n\treturn algs.List()\n}","line":{"from":200,"to":207}} {"id":100011548,"name":"publicJWKSFromKeys","signature":"func publicJWKSFromKeys(in []interface{}) (*jose.JSONWebKeySet, errors.Aggregate)","file":"pkg/serviceaccount/openidmetadata.go","code":"// publicJWKSFromKeys constructs a JSONWebKeySet from a list of keys. The key\n// set will only contain the public keys associated with the input keys.\nfunc publicJWKSFromKeys(in []interface{}) (*jose.JSONWebKeySet, errors.Aggregate) {\n\t// Decode keys into a JWKS.\n\tvar keys jose.JSONWebKeySet\n\tvar errs []error\n\tfor i, key := range in {\n\t\tvar pubkey *jose.JSONWebKey\n\t\tvar err error\n\n\t\tswitch k := key.(type) {\n\t\tcase publicKeyGetter:\n\t\t\t// This is a private key. Get its public key\n\t\t\tpubkey, err = jwkFromPublicKey(k.Public())\n\t\tdefault:\n\t\t\tpubkey, err = jwkFromPublicKey(k)\n\t\t}\n\t\tif err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"error constructing JWK for key #%d: %v\", i, err))\n\t\t\tcontinue\n\t\t}\n\n\t\tif !pubkey.Valid() {\n\t\t\terrs = append(errs, fmt.Errorf(\"key #%d not valid\", i))\n\t\t\tcontinue\n\t\t}\n\t\tkeys.Keys = append(keys.Keys, *pubkey)\n\t}\n\tif len(errs) != 0 {\n\t\treturn nil, errors.NewAggregate(errs)\n\t}\n\treturn \u0026keys, nil\n}","line":{"from":213,"to":245}} {"id":100011549,"name":"jwkFromPublicKey","signature":"func jwkFromPublicKey(publicKey crypto.PublicKey) (*jose.JSONWebKey, error)","file":"pkg/serviceaccount/openidmetadata.go","code":"func jwkFromPublicKey(publicKey crypto.PublicKey) (*jose.JSONWebKey, error) {\n\talg, err := algorithmFromPublicKey(publicKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkeyID, err := keyIDFromPublicKey(publicKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tjwk := \u0026jose.JSONWebKey{\n\t\tAlgorithm: string(alg),\n\t\tKey: publicKey,\n\t\tKeyID: keyID,\n\t\tUse: \"sig\",\n\t}\n\n\tif !jwk.IsPublic() {\n\t\treturn nil, fmt.Errorf(\"JWK was not a public key! JWK: %v\", jwk)\n\t}\n\n\treturn jwk, nil\n}","line":{"from":247,"to":270}} {"id":100011550,"name":"algorithmFromPublicKey","signature":"func algorithmFromPublicKey(publicKey crypto.PublicKey) (jose.SignatureAlgorithm, error)","file":"pkg/serviceaccount/openidmetadata.go","code":"func algorithmFromPublicKey(publicKey crypto.PublicKey) (jose.SignatureAlgorithm, error) {\n\tswitch pk := publicKey.(type) {\n\tcase *rsa.PublicKey:\n\t\t// IMPORTANT: If this function is updated to support additional key sizes,\n\t\t// signerFromRSAPrivateKey in serviceaccount/jwt.go must also be\n\t\t// updated to support the same key sizes. Today we only support RS256.\n\t\treturn jose.RS256, nil\n\tcase *ecdsa.PublicKey:\n\t\tswitch pk.Curve {\n\t\tcase elliptic.P256():\n\t\t\treturn jose.ES256, nil\n\t\tcase elliptic.P384():\n\t\t\treturn jose.ES384, nil\n\t\tcase elliptic.P521():\n\t\t\treturn jose.ES512, nil\n\t\tdefault:\n\t\t\treturn \"\", fmt.Errorf(\"unknown private key curve, must be 256, 384, or 521\")\n\t\t}\n\tcase jose.OpaqueSigner:\n\t\treturn jose.SignatureAlgorithm(pk.Public().Algorithm), nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"unknown public key type, must be *rsa.PublicKey, *ecdsa.PublicKey, or jose.OpaqueSigner\")\n\t}\n}","line":{"from":272,"to":295}} {"id":100011551,"name":"TryAccept","signature":"func (nullLimiter) TryAccept() bool","file":"pkg/util/async/bounded_frequency_runner.go","code":"func (nullLimiter) TryAccept() bool {\n\treturn true\n}","line":{"from":57,"to":59}} {"id":100011552,"name":"Stop","signature":"func (nullLimiter) Stop() {}","file":"pkg/util/async/bounded_frequency_runner.go","code":"func (nullLimiter) Stop() {}","line":{"from":61,"to":61}} {"id":100011553,"name":"C","signature":"func (rt *realTimer) C() \u003c-chan time.Time","file":"pkg/util/async/bounded_frequency_runner.go","code":"func (rt *realTimer) C() \u003c-chan time.Time {\n\treturn rt.timer.C\n}","line":{"from":95,"to":97}} {"id":100011554,"name":"Reset","signature":"func (rt *realTimer) Reset(d time.Duration) bool","file":"pkg/util/async/bounded_frequency_runner.go","code":"func (rt *realTimer) Reset(d time.Duration) bool {\n\trt.next = time.Now().Add(d)\n\treturn rt.timer.Reset(d)\n}","line":{"from":99,"to":102}} {"id":100011555,"name":"Stop","signature":"func (rt *realTimer) Stop() bool","file":"pkg/util/async/bounded_frequency_runner.go","code":"func (rt *realTimer) Stop() bool {\n\treturn rt.timer.Stop()\n}","line":{"from":104,"to":106}} {"id":100011556,"name":"Now","signature":"func (rt *realTimer) Now() time.Time","file":"pkg/util/async/bounded_frequency_runner.go","code":"func (rt *realTimer) Now() time.Time {\n\treturn time.Now()\n}","line":{"from":108,"to":110}} {"id":100011557,"name":"Remaining","signature":"func (rt *realTimer) Remaining() time.Duration","file":"pkg/util/async/bounded_frequency_runner.go","code":"func (rt *realTimer) Remaining() time.Duration {\n\treturn rt.next.Sub(time.Now())\n}","line":{"from":112,"to":114}} {"id":100011558,"name":"Since","signature":"func (rt *realTimer) Since(t time.Time) time.Duration","file":"pkg/util/async/bounded_frequency_runner.go","code":"func (rt *realTimer) Since(t time.Time) time.Duration {\n\treturn time.Since(t)\n}","line":{"from":116,"to":118}} {"id":100011559,"name":"Sleep","signature":"func (rt *realTimer) Sleep(d time.Duration)","file":"pkg/util/async/bounded_frequency_runner.go","code":"func (rt *realTimer) Sleep(d time.Duration) {\n\ttime.Sleep(d)\n}","line":{"from":120,"to":122}} {"id":100011560,"name":"NewBoundedFrequencyRunner","signature":"func NewBoundedFrequencyRunner(name string, fn func(), minInterval, maxInterval time.Duration, burstRuns int) *BoundedFrequencyRunner","file":"pkg/util/async/bounded_frequency_runner.go","code":"// NewBoundedFrequencyRunner creates a new BoundedFrequencyRunner instance,\n// which will manage runs of the specified function.\n//\n// All runs will be async to the caller of BoundedFrequencyRunner.Run, but\n// multiple runs are serialized. If the function needs to hold locks, it must\n// take them internally.\n//\n// Runs of the function will have at least minInterval between them (from\n// completion to next start), except that up to bursts may be allowed. Burst\n// runs are \"accumulated\" over time, one per minInterval up to burstRuns total.\n// This can be used, for example, to mitigate the impact of expensive operations\n// being called in response to user-initiated operations. Run requests that\n// would violate the minInterval are coalesced and run at the next opportunity.\n//\n// The function will be run at least once per maxInterval. For example, this can\n// force periodic refreshes of state in the absence of anyone calling Run.\n//\n// Examples:\n//\n// NewBoundedFrequencyRunner(\"name\", fn, time.Second, 5*time.Second, 1)\n// - fn will have at least 1 second between runs\n// - fn will have no more than 5 seconds between runs\n//\n// NewBoundedFrequencyRunner(\"name\", fn, 3*time.Second, 10*time.Second, 3)\n// - fn will have at least 3 seconds between runs, with up to 3 burst runs\n// - fn will have no more than 10 seconds between runs\n//\n// The maxInterval must be greater than or equal to the minInterval, If the\n// caller passes a maxInterval less than minInterval, this function will panic.\nfunc NewBoundedFrequencyRunner(name string, fn func(), minInterval, maxInterval time.Duration, burstRuns int) *BoundedFrequencyRunner {\n\ttimer := \u0026realTimer{timer: time.NewTimer(0)} // will tick immediately\n\t\u003c-timer.C() // consume the first tick\n\treturn construct(name, fn, minInterval, maxInterval, burstRuns, timer)\n}","line":{"from":126,"to":159}} {"id":100011561,"name":"construct","signature":"func construct(name string, fn func(), minInterval, maxInterval time.Duration, burstRuns int, timer timer) *BoundedFrequencyRunner","file":"pkg/util/async/bounded_frequency_runner.go","code":"// Make an instance with dependencies injected.\nfunc construct(name string, fn func(), minInterval, maxInterval time.Duration, burstRuns int, timer timer) *BoundedFrequencyRunner {\n\tif maxInterval \u003c minInterval {\n\t\tpanic(fmt.Sprintf(\"%s: maxInterval (%v) must be \u003e= minInterval (%v)\", name, maxInterval, minInterval))\n\t}\n\tif timer == nil {\n\t\tpanic(fmt.Sprintf(\"%s: timer must be non-nil\", name))\n\t}\n\n\tbfr := \u0026BoundedFrequencyRunner{\n\t\tname: name,\n\t\tfn: fn,\n\t\tminInterval: minInterval,\n\t\tmaxInterval: maxInterval,\n\t\trun: make(chan struct{}, 1),\n\t\tretry: make(chan struct{}, 1),\n\t\ttimer: timer,\n\t}\n\tif minInterval == 0 {\n\t\tbfr.limiter = nullLimiter{}\n\t} else {\n\t\t// allow burst updates in short succession\n\t\tqps := float32(time.Second) / float32(minInterval)\n\t\tbfr.limiter = flowcontrol.NewTokenBucketRateLimiterWithClock(qps, burstRuns, timer)\n\t}\n\treturn bfr\n}","line":{"from":161,"to":187}} {"id":100011562,"name":"Loop","signature":"func (bfr *BoundedFrequencyRunner) Loop(stop \u003c-chan struct{})","file":"pkg/util/async/bounded_frequency_runner.go","code":"// Loop handles the periodic timer and run requests. This is expected to be\n// called as a goroutine.\nfunc (bfr *BoundedFrequencyRunner) Loop(stop \u003c-chan struct{}) {\n\tklog.V(3).Infof(\"%s Loop running\", bfr.name)\n\tbfr.timer.Reset(bfr.maxInterval)\n\tfor {\n\t\tselect {\n\t\tcase \u003c-stop:\n\t\t\tbfr.stop()\n\t\t\tklog.V(3).Infof(\"%s Loop stopping\", bfr.name)\n\t\t\treturn\n\t\tcase \u003c-bfr.timer.C():\n\t\t\tbfr.tryRun()\n\t\tcase \u003c-bfr.run:\n\t\t\tbfr.tryRun()\n\t\tcase \u003c-bfr.retry:\n\t\t\tbfr.doRetry()\n\t\t}\n\t}\n}","line":{"from":189,"to":208}} {"id":100011563,"name":"Run","signature":"func (bfr *BoundedFrequencyRunner) Run()","file":"pkg/util/async/bounded_frequency_runner.go","code":"// Run the function as soon as possible. If this is called while Loop is not\n// running, the call may be deferred indefinitely.\n// If there is already a queued request to call the underlying function, it\n// may be dropped - it is just guaranteed that we will try calling the\n// underlying function as soon as possible starting from now.\nfunc (bfr *BoundedFrequencyRunner) Run() {\n\t// If it takes a lot of time to run the underlying function, noone is really\n\t// processing elements from \u003crun\u003e channel. So to avoid blocking here on the\n\t// putting element to it, we simply skip it if there is already an element\n\t// in it.\n\tselect {\n\tcase bfr.run \u003c- struct{}{}:\n\tdefault:\n\t}\n}","line":{"from":210,"to":224}} {"id":100011564,"name":"RetryAfter","signature":"func (bfr *BoundedFrequencyRunner) RetryAfter(interval time.Duration)","file":"pkg/util/async/bounded_frequency_runner.go","code":"// RetryAfter ensures that the function will run again after no later than interval. This\n// can be called from inside a run of the BoundedFrequencyRunner's function, or\n// asynchronously.\nfunc (bfr *BoundedFrequencyRunner) RetryAfter(interval time.Duration) {\n\t// This could be called either with or without bfr.mu held, so we can't grab that\n\t// lock, and therefore we can't update the timer directly.\n\n\t// If the Loop thread is currently running fn then it may be a while before it\n\t// processes our retry request. But we want to retry at interval from now, not at\n\t// interval from \"whenever doRetry eventually gets called\". So we convert to\n\t// absolute time.\n\tretryTime := bfr.timer.Now().Add(interval)\n\n\t// We can't just write retryTime to a channel because there could be multiple\n\t// RetryAfter calls before Loop gets a chance to read from the channel. So we\n\t// record the soonest requested retry time in bfr.retryTime and then only signal\n\t// the Loop thread once, just like Run does.\n\tbfr.retryMu.Lock()\n\tdefer bfr.retryMu.Unlock()\n\tif !bfr.retryTime.IsZero() \u0026\u0026 bfr.retryTime.Before(retryTime) {\n\t\treturn\n\t}\n\tbfr.retryTime = retryTime\n\n\tselect {\n\tcase bfr.retry \u003c- struct{}{}:\n\tdefault:\n\t}\n}","line":{"from":226,"to":254}} {"id":100011565,"name":"stop","signature":"func (bfr *BoundedFrequencyRunner) stop()","file":"pkg/util/async/bounded_frequency_runner.go","code":"// assumes the lock is not held\nfunc (bfr *BoundedFrequencyRunner) stop() {\n\tbfr.mu.Lock()\n\tdefer bfr.mu.Unlock()\n\tbfr.limiter.Stop()\n\tbfr.timer.Stop()\n}","line":{"from":256,"to":262}} {"id":100011566,"name":"doRetry","signature":"func (bfr *BoundedFrequencyRunner) doRetry()","file":"pkg/util/async/bounded_frequency_runner.go","code":"// assumes the lock is not held\nfunc (bfr *BoundedFrequencyRunner) doRetry() {\n\tbfr.mu.Lock()\n\tdefer bfr.mu.Unlock()\n\tbfr.retryMu.Lock()\n\tdefer bfr.retryMu.Unlock()\n\n\tif bfr.retryTime.IsZero() {\n\t\treturn\n\t}\n\n\t// Timer wants an interval not an absolute time, so convert retryTime back now\n\tretryInterval := bfr.retryTime.Sub(bfr.timer.Now())\n\tbfr.retryTime = time.Time{}\n\tif retryInterval \u003c bfr.timer.Remaining() {\n\t\tklog.V(3).Infof(\"%s: retrying in %v\", bfr.name, retryInterval)\n\t\tbfr.timer.Stop()\n\t\tbfr.timer.Reset(retryInterval)\n\t}\n}","line":{"from":264,"to":283}} {"id":100011567,"name":"tryRun","signature":"func (bfr *BoundedFrequencyRunner) tryRun()","file":"pkg/util/async/bounded_frequency_runner.go","code":"// assumes the lock is not held\nfunc (bfr *BoundedFrequencyRunner) tryRun() {\n\tbfr.mu.Lock()\n\tdefer bfr.mu.Unlock()\n\n\tif bfr.limiter.TryAccept() {\n\t\t// We're allowed to run the function right now.\n\t\tbfr.fn()\n\t\tbfr.lastRun = bfr.timer.Now()\n\t\tbfr.timer.Stop()\n\t\tbfr.timer.Reset(bfr.maxInterval)\n\t\tklog.V(3).Infof(\"%s: ran, next possible in %v, periodic in %v\", bfr.name, bfr.minInterval, bfr.maxInterval)\n\t\treturn\n\t}\n\n\t// It can't run right now, figure out when it can run next.\n\telapsed := bfr.timer.Since(bfr.lastRun) // how long since last run\n\tnextPossible := bfr.minInterval - elapsed // time to next possible run\n\tnextScheduled := bfr.timer.Remaining() // time to next scheduled run\n\tklog.V(4).Infof(\"%s: %v since last run, possible in %v, scheduled in %v\", bfr.name, elapsed, nextPossible, nextScheduled)\n\n\t// It's hard to avoid race conditions in the unit tests unless we always reset\n\t// the timer here, even when it's unchanged\n\tif nextPossible \u003c nextScheduled {\n\t\tnextScheduled = nextPossible\n\t}\n\tbfr.timer.Stop()\n\tbfr.timer.Reset(nextScheduled)\n}","line":{"from":285,"to":313}} {"id":100011568,"name":"NewRunner","signature":"func NewRunner(f ...func(stop chan struct{})) *Runner","file":"pkg/util/async/runner.go","code":"// NewRunner makes a runner for the given function(s). The function(s) should loop until\n// the channel is closed.\nfunc NewRunner(f ...func(stop chan struct{})) *Runner {\n\treturn \u0026Runner{loopFuncs: f}\n}","line":{"from":31,"to":35}} {"id":100011569,"name":"Start","signature":"func (r *Runner) Start()","file":"pkg/util/async/runner.go","code":"// Start begins running.\nfunc (r *Runner) Start() {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\tif r.stop == nil {\n\t\tc := make(chan struct{})\n\t\tr.stop = \u0026c\n\t\tfor i := range r.loopFuncs {\n\t\t\tgo r.loopFuncs[i](*r.stop)\n\t\t}\n\t}\n}","line":{"from":37,"to":48}} {"id":100011570,"name":"Stop","signature":"func (r *Runner) Stop()","file":"pkg/util/async/runner.go","code":"// Stop stops running.\nfunc (r *Runner) Stop() {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\tif r.stop != nil {\n\t\tclose(*r.stop)\n\t\tr.stop = nil\n\t}\n}","line":{"from":50,"to":58}} {"id":100011571,"name":"Merge","signature":"func (f MergeFunc) Merge(source string, update interface{}) error","file":"pkg/util/config/config.go","code":"func (f MergeFunc) Merge(source string, update interface{}) error {\n\treturn f(source, update)\n}","line":{"from":36,"to":38}} {"id":100011572,"name":"NewMux","signature":"func NewMux(merger Merger) *Mux","file":"pkg/util/config/config.go","code":"// NewMux creates a new mux that can merge changes from multiple sources.\nfunc NewMux(merger Merger) *Mux {\n\tmux := \u0026Mux{\n\t\tsources: make(map[string]chan interface{}),\n\t\tmerger: merger,\n\t}\n\treturn mux\n}","line":{"from":52,"to":59}} {"id":100011573,"name":"ChannelWithContext","signature":"func (m *Mux) ChannelWithContext(ctx context.Context, source string) chan interface{}","file":"pkg/util/config/config.go","code":"// ChannelWithContext returns a channel where a configuration source\n// can send updates of new configurations. Multiple calls with the same\n// source will return the same channel. This allows change and state based sources\n// to use the same channel. Different source names however will be treated as a\n// union.\nfunc (m *Mux) ChannelWithContext(ctx context.Context, source string) chan interface{} {\n\tif len(source) == 0 {\n\t\tpanic(\"Channel given an empty name\")\n\t}\n\tm.sourceLock.Lock()\n\tdefer m.sourceLock.Unlock()\n\tchannel, exists := m.sources[source]\n\tif exists {\n\t\treturn channel\n\t}\n\tnewChannel := make(chan interface{})\n\tm.sources[source] = newChannel\n\n\tgo wait.Until(func() { m.listen(source, newChannel) }, 0, ctx.Done())\n\treturn newChannel\n}","line":{"from":61,"to":81}} {"id":100011574,"name":"listen","signature":"func (m *Mux) listen(source string, listenChannel \u003c-chan interface{})","file":"pkg/util/config/config.go","code":"func (m *Mux) listen(source string, listenChannel \u003c-chan interface{}) {\n\tfor update := range listenChannel {\n\t\tm.merger.Merge(source, update)\n\t}\n}","line":{"from":83,"to":87}} {"id":100011575,"name":"MergedState","signature":"func (f AccessorFunc) MergedState() interface{}","file":"pkg/util/config/config.go","code":"func (f AccessorFunc) MergedState() interface{} {\n\treturn f()\n}","line":{"from":99,"to":101}} {"id":100011576,"name":"OnUpdate","signature":"func (f ListenerFunc) OnUpdate(instance interface{})","file":"pkg/util/config/config.go","code":"func (f ListenerFunc) OnUpdate(instance interface{}) {\n\tf(instance)\n}","line":{"from":111,"to":113}} {"id":100011577,"name":"NewBroadcaster","signature":"func NewBroadcaster() *Broadcaster","file":"pkg/util/config/config.go","code":"// NewBroadcaster registers a set of listeners that support the Listener interface\n// and notifies them all on changes.\nfunc NewBroadcaster() *Broadcaster {\n\treturn \u0026Broadcaster{}\n}","line":{"from":121,"to":125}} {"id":100011578,"name":"Add","signature":"func (b *Broadcaster) Add(listener Listener)","file":"pkg/util/config/config.go","code":"// Add registers listener to receive updates of changes.\nfunc (b *Broadcaster) Add(listener Listener) {\n\tb.listenerLock.Lock()\n\tdefer b.listenerLock.Unlock()\n\tb.listeners = append(b.listeners, listener)\n}","line":{"from":127,"to":132}} {"id":100011579,"name":"Notify","signature":"func (b *Broadcaster) Notify(instance interface{})","file":"pkg/util/config/config.go","code":"// Notify notifies all listeners.\nfunc (b *Broadcaster) Notify(instance interface{}) {\n\tb.listenerLock.RLock()\n\tlisteners := b.listeners\n\tb.listenerLock.RUnlock()\n\tfor _, listener := range listeners {\n\t\tlistener.OnUpdate(instance)\n\t}\n}","line":{"from":134,"to":142}} {"id":100011580,"name":"protoStr","signature":"func protoStr(proto v1.Protocol) string","file":"pkg/util/conntrack/conntrack.go","code":"func protoStr(proto v1.Protocol) string {\n\treturn strings.ToLower(string(proto))\n}","line":{"from":35,"to":37}} {"id":100011581,"name":"parametersWithFamily","signature":"func parametersWithFamily(isIPv6 bool, parameters ...string) []string","file":"pkg/util/conntrack/conntrack.go","code":"func parametersWithFamily(isIPv6 bool, parameters ...string) []string {\n\tif isIPv6 {\n\t\tparameters = append(parameters, \"-f\", \"ipv6\")\n\t}\n\treturn parameters\n}","line":{"from":39,"to":44}} {"id":100011582,"name":"ClearEntriesForIP","signature":"func ClearEntriesForIP(execer exec.Interface, ip string, protocol v1.Protocol) error","file":"pkg/util/conntrack/conntrack.go","code":"// ClearEntriesForIP uses the conntrack tool to delete the conntrack entries\n// for the UDP connections specified by the given service IP\nfunc ClearEntriesForIP(execer exec.Interface, ip string, protocol v1.Protocol) error {\n\tparameters := parametersWithFamily(utilnet.IsIPv6String(ip), \"-D\", \"--orig-dst\", ip, \"-p\", protoStr(protocol))\n\terr := Exec(execer, parameters...)\n\tif err != nil \u0026\u0026 !strings.Contains(err.Error(), NoConnectionToDelete) {\n\t\t// TODO: Better handling for deletion failure. When failure occur, stale udp connection may not get flushed.\n\t\t// These stale udp connection will keep black hole traffic. Making this a best effort operation for now, since it\n\t\t// is expensive to baby-sit all udp connections to kubernetes services.\n\t\treturn fmt.Errorf(\"error deleting connection tracking state for UDP service IP: %s, error: %v\", ip, err)\n\t}\n\treturn nil\n}","line":{"from":46,"to":58}} {"id":100011583,"name":"Exec","signature":"func Exec(execer exec.Interface, parameters ...string) error","file":"pkg/util/conntrack/conntrack.go","code":"// Exec executes the conntrack tool using the given parameters\nfunc Exec(execer exec.Interface, parameters ...string) error {\n\tconntrackPath, err := execer.LookPath(\"conntrack\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error looking for path of conntrack: %v\", err)\n\t}\n\tklog.V(4).Infof(\"Clearing conntrack entries %v\", parameters)\n\toutput, err := execer.Command(conntrackPath, parameters...).CombinedOutput()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"conntrack command returned: %q, error message: %s\", string(output), err)\n\t}\n\tklog.V(4).Infof(\"Conntrack entries deleted %s\", string(output))\n\treturn nil\n}","line":{"from":60,"to":73}} {"id":100011584,"name":"ClearEntriesForPort","signature":"func ClearEntriesForPort(execer exec.Interface, port int, isIPv6 bool, protocol v1.Protocol) error","file":"pkg/util/conntrack/conntrack.go","code":"// ClearEntriesForPort uses the conntrack tool to delete the conntrack entries\n// for connections specified by the port.\n// When a packet arrives, it will not go through NAT table again, because it is not \"the first\" packet.\n// The solution is clearing the conntrack. Known issues:\n// https://github.com/docker/docker/issues/8795\n// https://github.com/kubernetes/kubernetes/issues/31983\nfunc ClearEntriesForPort(execer exec.Interface, port int, isIPv6 bool, protocol v1.Protocol) error {\n\tif port \u003c= 0 {\n\t\treturn fmt.Errorf(\"wrong port number. The port number must be greater than zero\")\n\t}\n\tparameters := parametersWithFamily(isIPv6, \"-D\", \"-p\", protoStr(protocol), \"--dport\", strconv.Itoa(port))\n\terr := Exec(execer, parameters...)\n\tif err != nil \u0026\u0026 !strings.Contains(err.Error(), NoConnectionToDelete) {\n\t\treturn fmt.Errorf(\"error deleting conntrack entries for UDP port: %d, error: %v\", port, err)\n\t}\n\treturn nil\n}","line":{"from":75,"to":91}} {"id":100011585,"name":"ClearEntriesForNAT","signature":"func ClearEntriesForNAT(execer exec.Interface, origin, dest string, protocol v1.Protocol) error","file":"pkg/util/conntrack/conntrack.go","code":"// ClearEntriesForNAT uses the conntrack tool to delete the conntrack entries\n// for connections specified by the {origin, dest} IP pair.\nfunc ClearEntriesForNAT(execer exec.Interface, origin, dest string, protocol v1.Protocol) error {\n\tparameters := parametersWithFamily(utilnet.IsIPv6String(origin), \"-D\", \"--orig-dst\", origin, \"--dst-nat\", dest,\n\t\t\"-p\", protoStr(protocol))\n\terr := Exec(execer, parameters...)\n\tif err != nil \u0026\u0026 !strings.Contains(err.Error(), NoConnectionToDelete) {\n\t\t// TODO: Better handling for deletion failure. When failure occur, stale udp connection may not get flushed.\n\t\t// These stale udp connection will keep black hole traffic. Making this a best effort operation for now, since it\n\t\t// is expensive to baby sit all udp connections to kubernetes services.\n\t\treturn fmt.Errorf(\"error deleting conntrack entries for UDP peer {%s, %s}, error: %v\", origin, dest, err)\n\t}\n\treturn nil\n}","line":{"from":93,"to":106}} {"id":100011586,"name":"ClearEntriesForPortNAT","signature":"func ClearEntriesForPortNAT(execer exec.Interface, dest string, port int, protocol v1.Protocol) error","file":"pkg/util/conntrack/conntrack.go","code":"// ClearEntriesForPortNAT uses the conntrack tool to delete the conntrack entries\n// for connections specified by the {dest IP, port} pair.\n// Known issue:\n// https://github.com/kubernetes/kubernetes/issues/59368\nfunc ClearEntriesForPortNAT(execer exec.Interface, dest string, port int, protocol v1.Protocol) error {\n\tif port \u003c= 0 {\n\t\treturn fmt.Errorf(\"wrong port number. The port number must be greater than zero\")\n\t}\n\tparameters := parametersWithFamily(utilnet.IsIPv6String(dest), \"-D\", \"-p\", protoStr(protocol), \"--dport\", strconv.Itoa(port), \"--dst-nat\", dest)\n\terr := Exec(execer, parameters...)\n\tif err != nil \u0026\u0026 !strings.Contains(err.Error(), NoConnectionToDelete) {\n\t\treturn fmt.Errorf(\"error deleting conntrack entries for UDP port: %d, error: %v\", port, err)\n\t}\n\treturn nil\n}","line":{"from":108,"to":122}} {"id":100011587,"name":"tempCoveragePath","signature":"func tempCoveragePath() string","file":"pkg/util/coverage/coverage.go","code":"// tempCoveragePath returns a temporary file to write coverage information to.\n// The file is in the same directory as the destination, ensuring os.Rename will work.\nfunc tempCoveragePath() string {\n\treturn coverageFile + \".tmp\"\n}","line":{"from":37,"to":41}} {"id":100011588,"name":"InitCoverage","signature":"func InitCoverage(name string)","file":"pkg/util/coverage/coverage.go","code":"// InitCoverage is called from the dummy unit test to prepare Go's coverage framework.\n// Clients should never need to call it.\nfunc InitCoverage(name string) {\n\t// We read the coverage destination in from the KUBE_COVERAGE_FILE env var,\n\t// or if it's empty we just use a default in /tmp\n\tcoverageFile = os.Getenv(\"KUBE_COVERAGE_FILE\")\n\tif coverageFile == \"\" {\n\t\tcoverageFile = \"/tmp/k8s-\" + name + \".cov\"\n\t}\n\tfmt.Println(\"Dumping coverage information to \" + coverageFile)\n\n\tflushInterval := 5 * time.Second\n\trequestedInterval := os.Getenv(\"KUBE_COVERAGE_FLUSH_INTERVAL\")\n\tif requestedInterval != \"\" {\n\t\tif duration, err := time.ParseDuration(requestedInterval); err == nil {\n\t\t\tflushInterval = duration\n\t\t} else {\n\t\t\tpanic(\"Invalid KUBE_COVERAGE_FLUSH_INTERVAL value; try something like '30s'.\")\n\t\t}\n\t}\n\n\t// Set up the unit test framework with the required arguments to activate test coverage.\n\tflag.CommandLine.Parse([]string{\"-test.coverprofile\", tempCoveragePath()})\n\n\t// Begin periodic logging\n\tgo wait.Forever(FlushCoverage, flushInterval)\n}","line":{"from":43,"to":69}} {"id":100011589,"name":"FlushCoverage","signature":"func FlushCoverage()","file":"pkg/util/coverage/coverage.go","code":"// FlushCoverage flushes collected coverage information to disk.\n// The destination file is configured at startup and cannot be changed.\n// Calling this function also sends a line like \"coverage: 5% of statements\" to stdout.\nfunc FlushCoverage() {\n\t// We're not actually going to run any tests, but we need Go to think we did so it writes\n\t// coverage information to disk. To achieve this, we create a bunch of empty test suites and\n\t// have it \"run\" them.\n\ttests := []testing.InternalTest{}\n\tbenchmarks := []testing.InternalBenchmark{}\n\texamples := []testing.InternalExample{}\n\tfuzztargets := []testing.InternalFuzzTarget{}\n\n\tvar deps fakeTestDeps\n\n\tdummyRun := testing.MainStart(deps, tests, benchmarks, fuzztargets, examples)\n\tdummyRun.Run()\n\n\t// Once it writes to the temporary path, we move it to the intended path.\n\t// This gets us atomic updates from the perspective of another process trying to access\n\t// the file.\n\tif err := os.Rename(tempCoveragePath(), coverageFile); err != nil {\n\t\tklog.Errorf(\"Couldn't move coverage file from %s to %s\", coverageFile, tempCoveragePath())\n\t}\n}","line":{"from":71,"to":94}} {"id":100011590,"name":"InitCoverage","signature":"func InitCoverage(name string)","file":"pkg/util/coverage/coverage_disabled.go","code":"// InitCoverage is illegal when not running with coverage.\nfunc InitCoverage(name string) {\n\tpanic(\"Called InitCoverage when not built with coverage instrumentation.\")\n}","line":{"from":22,"to":25}} {"id":100011591,"name":"FlushCoverage","signature":"func FlushCoverage()","file":"pkg/util/coverage/coverage_disabled.go","code":"// FlushCoverage is a no-op when not running with coverage.\nfunc FlushCoverage() {\n\n}","line":{"from":27,"to":30}} {"id":100011592,"name":"GetEnvAsStringOrFallback","signature":"func GetEnvAsStringOrFallback(key, defaultValue string) string","file":"pkg/util/env/env.go","code":"// GetEnvAsStringOrFallback returns the env variable for the given key\n// and falls back to the given defaultValue if not set\nfunc GetEnvAsStringOrFallback(key, defaultValue string) string {\n\tif v := os.Getenv(key); v != \"\" {\n\t\treturn v\n\t}\n\treturn defaultValue\n}","line":{"from":24,"to":31}} {"id":100011593,"name":"GetEnvAsIntOrFallback","signature":"func GetEnvAsIntOrFallback(key string, defaultValue int) (int, error)","file":"pkg/util/env/env.go","code":"// GetEnvAsIntOrFallback returns the env variable (parsed as integer) for\n// the given key and falls back to the given defaultValue if not set\nfunc GetEnvAsIntOrFallback(key string, defaultValue int) (int, error) {\n\tif v := os.Getenv(key); v != \"\" {\n\t\tvalue, err := strconv.Atoi(v)\n\t\tif err != nil {\n\t\t\treturn defaultValue, err\n\t\t}\n\t\treturn value, nil\n\t}\n\treturn defaultValue, nil\n}","line":{"from":33,"to":44}} {"id":100011594,"name":"GetEnvAsFloat64OrFallback","signature":"func GetEnvAsFloat64OrFallback(key string, defaultValue float64) (float64, error)","file":"pkg/util/env/env.go","code":"// GetEnvAsFloat64OrFallback returns the env variable (parsed as float64) for\n// the given key and falls back to the given defaultValue if not set\nfunc GetEnvAsFloat64OrFallback(key string, defaultValue float64) (float64, error) {\n\tif v := os.Getenv(key); v != \"\" {\n\t\tvalue, err := strconv.ParseFloat(v, 64)\n\t\tif err != nil {\n\t\t\treturn defaultValue, err\n\t\t}\n\t\treturn value, nil\n\t}\n\treturn defaultValue, nil\n}","line":{"from":46,"to":57}} {"id":100011595,"name":"NewTempFs","signature":"func NewTempFs() Filesystem","file":"pkg/util/filesystem/defaultfs.go","code":"// NewTempFs returns a fake Filesystem in temporary directory, useful for unit tests\nfunc NewTempFs() Filesystem {\n\tpath, _ := os.MkdirTemp(\"\", \"tmpfs\")\n\treturn \u0026DefaultFs{\n\t\troot: path,\n\t}\n}","line":{"from":33,"to":39}} {"id":100011596,"name":"prefix","signature":"func (fs *DefaultFs) prefix(path string) string","file":"pkg/util/filesystem/defaultfs.go","code":"func (fs *DefaultFs) prefix(path string) string {\n\tif len(fs.root) == 0 {\n\t\treturn path\n\t}\n\treturn filepath.Join(fs.root, path)\n}","line":{"from":41,"to":46}} {"id":100011597,"name":"Stat","signature":"func (fs *DefaultFs) Stat(name string) (os.FileInfo, error)","file":"pkg/util/filesystem/defaultfs.go","code":"// Stat via os.Stat\nfunc (fs *DefaultFs) Stat(name string) (os.FileInfo, error) {\n\treturn os.Stat(fs.prefix(name))\n}","line":{"from":48,"to":51}} {"id":100011598,"name":"Create","signature":"func (fs *DefaultFs) Create(name string) (File, error)","file":"pkg/util/filesystem/defaultfs.go","code":"// Create via os.Create\nfunc (fs *DefaultFs) Create(name string) (File, error) {\n\tfile, err := os.Create(fs.prefix(name))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026defaultFile{file}, nil\n}","line":{"from":53,"to":60}} {"id":100011599,"name":"Rename","signature":"func (fs *DefaultFs) Rename(oldpath, newpath string) error","file":"pkg/util/filesystem/defaultfs.go","code":"// Rename via os.Rename\nfunc (fs *DefaultFs) Rename(oldpath, newpath string) error {\n\tif !strings.HasPrefix(oldpath, fs.root) {\n\t\toldpath = fs.prefix(oldpath)\n\t}\n\tif !strings.HasPrefix(newpath, fs.root) {\n\t\tnewpath = fs.prefix(newpath)\n\t}\n\treturn os.Rename(oldpath, newpath)\n}","line":{"from":62,"to":71}} {"id":100011600,"name":"MkdirAll","signature":"func (fs *DefaultFs) MkdirAll(path string, perm os.FileMode) error","file":"pkg/util/filesystem/defaultfs.go","code":"// MkdirAll via os.MkdirAll\nfunc (fs *DefaultFs) MkdirAll(path string, perm os.FileMode) error {\n\treturn os.MkdirAll(fs.prefix(path), perm)\n}","line":{"from":73,"to":76}} {"id":100011601,"name":"Chtimes","signature":"func (fs *DefaultFs) Chtimes(name string, atime time.Time, mtime time.Time) error","file":"pkg/util/filesystem/defaultfs.go","code":"// Chtimes via os.Chtimes\nfunc (fs *DefaultFs) Chtimes(name string, atime time.Time, mtime time.Time) error {\n\treturn os.Chtimes(fs.prefix(name), atime, mtime)\n}","line":{"from":78,"to":81}} {"id":100011602,"name":"RemoveAll","signature":"func (fs *DefaultFs) RemoveAll(path string) error","file":"pkg/util/filesystem/defaultfs.go","code":"// RemoveAll via os.RemoveAll\nfunc (fs *DefaultFs) RemoveAll(path string) error {\n\treturn os.RemoveAll(fs.prefix(path))\n}","line":{"from":83,"to":86}} {"id":100011603,"name":"Remove","signature":"func (fs *DefaultFs) Remove(name string) error","file":"pkg/util/filesystem/defaultfs.go","code":"// Remove via os.RemoveAll\nfunc (fs *DefaultFs) Remove(name string) error {\n\treturn os.Remove(fs.prefix(name))\n}","line":{"from":88,"to":91}} {"id":100011604,"name":"ReadFile","signature":"func (fs *DefaultFs) ReadFile(filename string) ([]byte, error)","file":"pkg/util/filesystem/defaultfs.go","code":"// ReadFile via os.ReadFile\nfunc (fs *DefaultFs) ReadFile(filename string) ([]byte, error) {\n\treturn os.ReadFile(fs.prefix(filename))\n}","line":{"from":93,"to":96}} {"id":100011605,"name":"TempDir","signature":"func (fs *DefaultFs) TempDir(dir, prefix string) (string, error)","file":"pkg/util/filesystem/defaultfs.go","code":"// TempDir via os.MkdirTemp\nfunc (fs *DefaultFs) TempDir(dir, prefix string) (string, error) {\n\treturn os.MkdirTemp(fs.prefix(dir), prefix)\n}","line":{"from":98,"to":101}} {"id":100011606,"name":"TempFile","signature":"func (fs *DefaultFs) TempFile(dir, prefix string) (File, error)","file":"pkg/util/filesystem/defaultfs.go","code":"// TempFile via os.CreateTemp\nfunc (fs *DefaultFs) TempFile(dir, prefix string) (File, error) {\n\tfile, err := os.CreateTemp(fs.prefix(dir), prefix)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026defaultFile{file}, nil\n}","line":{"from":103,"to":110}} {"id":100011607,"name":"ReadDir","signature":"func (fs *DefaultFs) ReadDir(dirname string) ([]os.DirEntry, error)","file":"pkg/util/filesystem/defaultfs.go","code":"// ReadDir via os.ReadDir\nfunc (fs *DefaultFs) ReadDir(dirname string) ([]os.DirEntry, error) {\n\treturn os.ReadDir(fs.prefix(dirname))\n}","line":{"from":112,"to":115}} {"id":100011608,"name":"Walk","signature":"func (fs *DefaultFs) Walk(root string, walkFn filepath.WalkFunc) error","file":"pkg/util/filesystem/defaultfs.go","code":"// Walk via filepath.Walk\nfunc (fs *DefaultFs) Walk(root string, walkFn filepath.WalkFunc) error {\n\treturn filepath.Walk(fs.prefix(root), walkFn)\n}","line":{"from":117,"to":120}} {"id":100011609,"name":"Name","signature":"func (file *defaultFile) Name() string","file":"pkg/util/filesystem/defaultfs.go","code":"// Name via os.File.Name\nfunc (file *defaultFile) Name() string {\n\treturn file.file.Name()\n}","line":{"from":127,"to":130}} {"id":100011610,"name":"Write","signature":"func (file *defaultFile) Write(b []byte) (n int, err error)","file":"pkg/util/filesystem/defaultfs.go","code":"// Write via os.File.Write\nfunc (file *defaultFile) Write(b []byte) (n int, err error) {\n\treturn file.file.Write(b)\n}","line":{"from":132,"to":135}} {"id":100011611,"name":"Sync","signature":"func (file *defaultFile) Sync() error","file":"pkg/util/filesystem/defaultfs.go","code":"// Sync via os.File.Sync\nfunc (file *defaultFile) Sync() error {\n\treturn file.file.Sync()\n}","line":{"from":137,"to":140}} {"id":100011612,"name":"Close","signature":"func (file *defaultFile) Close() error","file":"pkg/util/filesystem/defaultfs.go","code":"// Close via os.File.Close\nfunc (file *defaultFile) Close() error {\n\treturn file.file.Close()\n}","line":{"from":142,"to":145}} {"id":100011613,"name":"NewFsnotifyWatcher","signature":"func NewFsnotifyWatcher() FSWatcher","file":"pkg/util/filesystem/watcher.go","code":"// NewFsnotifyWatcher returns an implementation of FSWatcher that continuously listens for\n// fsnotify events and calls the event handler as soon as an event is received.\nfunc NewFsnotifyWatcher() FSWatcher {\n\treturn \u0026fsnotifyWatcher{}\n}","line":{"from":51,"to":55}} {"id":100011614,"name":"AddWatch","signature":"func (w *fsnotifyWatcher) AddWatch(path string) error","file":"pkg/util/filesystem/watcher.go","code":"func (w *fsnotifyWatcher) AddWatch(path string) error {\n\treturn w.watcher.Add(path)\n}","line":{"from":57,"to":59}} {"id":100011615,"name":"Init","signature":"func (w *fsnotifyWatcher) Init(eventHandler FSEventHandler, errorHandler FSErrorHandler) error","file":"pkg/util/filesystem/watcher.go","code":"func (w *fsnotifyWatcher) Init(eventHandler FSEventHandler, errorHandler FSErrorHandler) error {\n\tvar err error\n\tw.watcher, err = fsnotify.NewWatcher()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tw.eventHandler = eventHandler\n\tw.errorHandler = errorHandler\n\treturn nil\n}","line":{"from":61,"to":71}} {"id":100011616,"name":"Run","signature":"func (w *fsnotifyWatcher) Run()","file":"pkg/util/filesystem/watcher.go","code":"func (w *fsnotifyWatcher) Run() {\n\tgo func() {\n\t\tdefer w.watcher.Close()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event := \u003c-w.watcher.Events:\n\t\t\t\tif w.eventHandler != nil {\n\t\t\t\t\tw.eventHandler(event)\n\t\t\t\t}\n\t\t\tcase err := \u003c-w.watcher.Errors:\n\t\t\t\tif w.errorHandler != nil {\n\t\t\t\t\tw.errorHandler(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n}","line":{"from":73,"to":89}} {"id":100011617,"name":"Set","signature":"func (v *IPVar) Set(s string) error","file":"pkg/util/flag/flags.go","code":"// Set sets the flag value\nfunc (v *IPVar) Set(s string) error {\n\tif len(s) == 0 {\n\t\tv.Val = nil\n\t\treturn nil\n\t}\n\tif netutils.ParseIPSloppy(s) == nil {\n\t\treturn fmt.Errorf(\"%q is not a valid IP address\", s)\n\t}\n\tif v.Val == nil {\n\t\t// it's okay to panic here since this is programmer error\n\t\tpanic(\"the string pointer passed into IPVar should not be nil\")\n\t}\n\t*v.Val = s\n\treturn nil\n}","line":{"from":52,"to":67}} {"id":100011618,"name":"String","signature":"func (v *IPVar) String() string","file":"pkg/util/flag/flags.go","code":"// String returns the flag value\nfunc (v *IPVar) String() string {\n\tif v.Val == nil {\n\t\treturn \"\"\n\t}\n\treturn *v.Val\n}","line":{"from":69,"to":75}} {"id":100011619,"name":"Type","signature":"func (v *IPVar) Type() string","file":"pkg/util/flag/flags.go","code":"// Type gets the flag type\nfunc (v *IPVar) Type() string {\n\treturn \"ip\"\n}","line":{"from":77,"to":80}} {"id":100011620,"name":"Set","signature":"func (v *IPPortVar) Set(s string) error","file":"pkg/util/flag/flags.go","code":"// Set sets the flag value\nfunc (v *IPPortVar) Set(s string) error {\n\tif len(s) == 0 {\n\t\tv.Val = nil\n\t\treturn nil\n\t}\n\n\tif v.Val == nil {\n\t\t// it's okay to panic here since this is programmer error\n\t\tpanic(\"the string pointer passed into IPPortVar should not be nil\")\n\t}\n\n\t// Both IP and IP:port are valid.\n\t// Attempt to parse into IP first.\n\tif netutils.ParseIPSloppy(s) != nil {\n\t\t*v.Val = s\n\t\treturn nil\n\t}\n\n\t// Can not parse into IP, now assume IP:port.\n\thost, port, err := net.SplitHostPort(s)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%q is not in a valid format (ip or ip:port): %v\", s, err)\n\t}\n\tif netutils.ParseIPSloppy(host) == nil {\n\t\treturn fmt.Errorf(\"%q is not a valid IP address\", host)\n\t}\n\tif _, err := netutils.ParsePort(port, true); err != nil {\n\t\treturn fmt.Errorf(\"%q is not a valid number\", port)\n\t}\n\t*v.Val = s\n\treturn nil\n}","line":{"from":87,"to":119}} {"id":100011621,"name":"String","signature":"func (v *IPPortVar) String() string","file":"pkg/util/flag/flags.go","code":"// String returns the flag value\nfunc (v *IPPortVar) String() string {\n\tif v.Val == nil {\n\t\treturn \"\"\n\t}\n\treturn *v.Val\n}","line":{"from":121,"to":127}} {"id":100011622,"name":"Type","signature":"func (v *IPPortVar) Type() string","file":"pkg/util/flag/flags.go","code":"// Type gets the flag type\nfunc (v *IPPortVar) Type() string {\n\treturn \"ipport\"\n}","line":{"from":129,"to":132}} {"id":100011623,"name":"Set","signature":"func (v PortRangeVar) Set(s string) error","file":"pkg/util/flag/flags.go","code":"// Set sets the flag value\nfunc (v PortRangeVar) Set(s string) error {\n\tif _, err := utilnet.ParsePortRange(s); err != nil {\n\t\treturn fmt.Errorf(\"%q is not a valid port range: %v\", s, err)\n\t}\n\tif v.Val == nil {\n\t\t// it's okay to panic here since this is programmer error\n\t\tpanic(\"the string pointer passed into PortRangeVar should not be nil\")\n\t}\n\t*v.Val = s\n\treturn nil\n}","line":{"from":139,"to":150}} {"id":100011624,"name":"String","signature":"func (v PortRangeVar) String() string","file":"pkg/util/flag/flags.go","code":"// String returns the flag value\nfunc (v PortRangeVar) String() string {\n\tif v.Val == nil {\n\t\treturn \"\"\n\t}\n\treturn *v.Val\n}","line":{"from":152,"to":158}} {"id":100011625,"name":"Type","signature":"func (v PortRangeVar) Type() string","file":"pkg/util/flag/flags.go","code":"// Type gets the flag type\nfunc (v PortRangeVar) Type() string {\n\treturn \"port-range\"\n}","line":{"from":160,"to":163}} {"id":100011626,"name":"Set","signature":"func (v *ReservedMemoryVar) Set(s string) error","file":"pkg/util/flag/flags.go","code":"// Set sets the flag value\nfunc (v *ReservedMemoryVar) Set(s string) error {\n\tif v.Value == nil {\n\t\treturn fmt.Errorf(\"no target (nil pointer to *[]MemoryReservation\")\n\t}\n\n\tif s == \"\" {\n\t\tv.Value = nil\n\t\treturn nil\n\t}\n\n\tif !v.initialized || *v.Value == nil {\n\t\t*v.Value = make([]kubeletconfig.MemoryReservation, 0)\n\t\tv.initialized = true\n\t}\n\n\tif s == \"\" {\n\t\treturn nil\n\t}\n\n\tnumaNodeReservations := strings.Split(s, \";\")\n\tfor _, reservation := range numaNodeReservations {\n\t\tnumaNodeReservation := strings.Split(reservation, \":\")\n\t\tif len(numaNodeReservation) != 2 {\n\t\t\treturn fmt.Errorf(\"the reserved memory has incorrect format, expected numaNodeID:type=quantity[,type=quantity...], got %s\", reservation)\n\t\t}\n\t\tmemoryTypeReservations := strings.Split(numaNodeReservation[1], \",\")\n\t\tif len(memoryTypeReservations) \u003c 1 {\n\t\t\treturn fmt.Errorf(\"the reserved memory has incorrect format, expected numaNodeID:type=quantity[,type=quantity...], got %s\", reservation)\n\t\t}\n\t\tnumaNodeID, err := strconv.Atoi(numaNodeReservation[0])\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to convert the NUMA node ID, exptected integer, got %s\", numaNodeReservation[0])\n\t\t}\n\n\t\tmemoryReservation := kubeletconfig.MemoryReservation{\n\t\t\tNumaNode: int32(numaNodeID),\n\t\t\tLimits: map[v1.ResourceName]resource.Quantity{},\n\t\t}\n\n\t\tfor _, memoryTypeReservation := range memoryTypeReservations {\n\t\t\tlimit := strings.Split(memoryTypeReservation, \"=\")\n\t\t\tif len(limit) != 2 {\n\t\t\t\treturn fmt.Errorf(\"the reserved limit has incorrect value, expected type=quantatity, got %s\", memoryTypeReservation)\n\t\t\t}\n\n\t\t\tresourceName := v1.ResourceName(limit[0])\n\t\t\tif resourceName != v1.ResourceMemory \u0026\u0026 !corev1helper.IsHugePageResourceName(resourceName) {\n\t\t\t\treturn fmt.Errorf(\"memory type conversion error, unknown type: %q\", resourceName)\n\t\t\t}\n\n\t\t\tq, err := resource.ParseQuantity(limit[1])\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to parse the quantatity, expected quantatity, got %s\", limit[1])\n\t\t\t}\n\n\t\t\tmemoryReservation.Limits[v1.ResourceName(limit[0])] = q\n\t\t}\n\t\t*v.Value = append(*v.Value, memoryReservation)\n\t}\n\treturn nil\n}","line":{"from":171,"to":232}} {"id":100011627,"name":"String","signature":"func (v *ReservedMemoryVar) String() string","file":"pkg/util/flag/flags.go","code":"// String returns the flag value\nfunc (v *ReservedMemoryVar) String() string {\n\tif v == nil || v.Value == nil {\n\t\treturn \"\"\n\t}\n\n\tvar slices []string\n\tfor _, reservedMemory := range *v.Value {\n\t\tvar limits []string\n\t\tfor resourceName, q := range reservedMemory.Limits {\n\t\t\tlimits = append(limits, fmt.Sprintf(\"%s=%s\", resourceName, q.String()))\n\t\t}\n\n\t\tsort.Strings(limits)\n\t\tslices = append(slices, fmt.Sprintf(\"%d:%s\", reservedMemory.NumaNode, strings.Join(limits, \",\")))\n\t}\n\n\tsort.Strings(slices)\n\treturn strings.Join(slices, \",\")\n}","line":{"from":234,"to":253}} {"id":100011628,"name":"Type","signature":"func (v *ReservedMemoryVar) Type() string","file":"pkg/util/flag/flags.go","code":"// Type gets the flag type\nfunc (v *ReservedMemoryVar) Type() string {\n\treturn \"reserved-memory\"\n}","line":{"from":255,"to":258}} {"id":100011629,"name":"Set","signature":"func (t RegisterWithTaintsVar) Set(s string) error","file":"pkg/util/flag/flags.go","code":"// Set sets the flag value\nfunc (t RegisterWithTaintsVar) Set(s string) error {\n\tif len(s) == 0 {\n\t\t*t.Value = nil\n\t\treturn nil\n\t}\n\tsts := strings.Split(s, \",\")\n\tcorev1Taints, _, err := utiltaints.ParseTaints(sts)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar taints []v1.Taint\n\tfor _, ct := range corev1Taints {\n\t\ttaints = append(taints, v1.Taint{Key: ct.Key, Value: ct.Value, Effect: ct.Effect})\n\t}\n\t*t.Value = taints\n\treturn nil\n}","line":{"from":265,"to":282}} {"id":100011630,"name":"String","signature":"func (t RegisterWithTaintsVar) String() string","file":"pkg/util/flag/flags.go","code":"// String returns the flag value\nfunc (t RegisterWithTaintsVar) String() string {\n\tif len(*t.Value) == 0 {\n\t\treturn \"\"\n\t}\n\tvar taints []string\n\tfor _, taint := range *t.Value {\n\t\ttaints = append(taints, fmt.Sprintf(\"%s=%s:%s\", taint.Key, taint.Value, taint.Effect))\n\t}\n\treturn strings.Join(taints, \",\")\n}","line":{"from":284,"to":294}} {"id":100011631,"name":"Type","signature":"func (t RegisterWithTaintsVar) Type() string","file":"pkg/util/flag/flags.go","code":"// Type gets the flag type\nfunc (t RegisterWithTaintsVar) Type() string {\n\treturn \"[]v1.Taint\"\n}","line":{"from":296,"to":299}} {"id":100011632,"name":"Acquire","signature":"func Acquire(path string) error","file":"pkg/util/flock/flock_other.go","code":"// Acquire is not implemented on non-unix systems.\nfunc Acquire(path string) error {\n\treturn nil\n}","line":{"from":22,"to":25}} {"id":100011633,"name":"Acquire","signature":"func Acquire(path string) error","file":"pkg/util/flock/flock_unix.go","code":"// Acquire acquires a lock on a file for the duration of the process. This method\n// is reentrant.\nfunc Acquire(path string) error {\n\tfd, err := unix.Open(path, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// We don't need to close the fd since we should hold\n\t// it until the process exits.\n\n\treturn unix.Flock(fd, unix.LOCK_EX)\n}","line":{"from":24,"to":36}} {"id":100011634,"name":"SafeToRetry","signature":"func (expBackoff *ExponentialBackoff) SafeToRetry(operationName string) error","file":"pkg/util/goroutinemap/exponentialbackoff/exponential_backoff.go","code":"// SafeToRetry returns an error if the durationBeforeRetry period for the given\n// lastErrorTime has not yet expired. Otherwise it returns nil.\nfunc (expBackoff *ExponentialBackoff) SafeToRetry(operationName string) error {\n\tif time.Since(expBackoff.lastErrorTime) \u003c= expBackoff.durationBeforeRetry {\n\t\treturn NewExponentialBackoffError(operationName, *expBackoff)\n\t}\n\n\treturn nil\n}","line":{"from":48,"to":56}} {"id":100011635,"name":"Update","signature":"func (expBackoff *ExponentialBackoff) Update(err *error)","file":"pkg/util/goroutinemap/exponentialbackoff/exponential_backoff.go","code":"func (expBackoff *ExponentialBackoff) Update(err *error) {\n\tif expBackoff.durationBeforeRetry == 0 {\n\t\texpBackoff.durationBeforeRetry = initialDurationBeforeRetry\n\t} else {\n\t\texpBackoff.durationBeforeRetry = 2 * expBackoff.durationBeforeRetry\n\t\tif expBackoff.durationBeforeRetry \u003e maxDurationBeforeRetry {\n\t\t\texpBackoff.durationBeforeRetry = maxDurationBeforeRetry\n\t\t}\n\t}\n\n\texpBackoff.lastError = *err\n\texpBackoff.lastErrorTime = time.Now()\n}","line":{"from":58,"to":70}} {"id":100011636,"name":"GenerateNoRetriesPermittedMsg","signature":"func (expBackoff *ExponentialBackoff) GenerateNoRetriesPermittedMsg(operationName string) string","file":"pkg/util/goroutinemap/exponentialbackoff/exponential_backoff.go","code":"func (expBackoff *ExponentialBackoff) GenerateNoRetriesPermittedMsg(operationName string) string {\n\treturn fmt.Sprintf(\"Operation for %q failed. No retries permitted until %v (durationBeforeRetry %v). Error: %v\",\n\t\toperationName,\n\t\texpBackoff.lastErrorTime.Add(expBackoff.durationBeforeRetry),\n\t\texpBackoff.durationBeforeRetry,\n\t\texpBackoff.lastError)\n}","line":{"from":72,"to":78}} {"id":100011637,"name":"NewExponentialBackoffError","signature":"func NewExponentialBackoffError(","file":"pkg/util/goroutinemap/exponentialbackoff/exponential_backoff.go","code":"// NewExponentialBackoffError returns a new instance of ExponentialBackoff error.\nfunc NewExponentialBackoffError(\n\toperationName string, expBackoff ExponentialBackoff) error {\n\treturn exponentialBackoffError{\n\t\toperationName: operationName,\n\t\texpBackoff: expBackoff,\n\t}\n}","line":{"from":80,"to":87}} {"id":100011638,"name":"IsExponentialBackoff","signature":"func IsExponentialBackoff(err error) bool","file":"pkg/util/goroutinemap/exponentialbackoff/exponential_backoff.go","code":"// IsExponentialBackoff returns true if an error returned from GoroutineMap\n// indicates that a new operation can not be started because\n// exponentialBackOffOnError is enabled and a previous operation with the same\n// operation failed within the durationBeforeRetry period.\nfunc IsExponentialBackoff(err error) bool {\n\tswitch err.(type) {\n\tcase exponentialBackoffError:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":89,"to":100}} {"id":100011639,"name":"Error","signature":"func (err exponentialBackoffError) Error() string","file":"pkg/util/goroutinemap/exponentialbackoff/exponential_backoff.go","code":"func (err exponentialBackoffError) Error() string {\n\treturn fmt.Sprintf(\n\t\t\"Failed to create operation with name %q. An operation with that name failed at %v. No retries permitted until %v (%v). Last error: %q.\",\n\t\terr.operationName,\n\t\terr.expBackoff.lastErrorTime,\n\t\terr.expBackoff.lastErrorTime.Add(err.expBackoff.durationBeforeRetry),\n\t\terr.expBackoff.durationBeforeRetry,\n\t\terr.expBackoff.lastError)\n}","line":{"from":113,"to":121}} {"id":100011640,"name":"NewGoRoutineMap","signature":"func NewGoRoutineMap(exponentialBackOffOnError bool) GoRoutineMap","file":"pkg/util/goroutinemap/goroutinemap.go","code":"// NewGoRoutineMap returns a new instance of GoRoutineMap.\nfunc NewGoRoutineMap(exponentialBackOffOnError bool) GoRoutineMap {\n\tg := \u0026goRoutineMap{\n\t\toperations: make(map[string]operation),\n\t\texponentialBackOffOnError: exponentialBackOffOnError,\n\t}\n\n\tg.cond = sync.NewCond(\u0026g.lock)\n\treturn g\n}","line":{"from":62,"to":71}} {"id":100011641,"name":"Run","signature":"func (grm *goRoutineMap) Run(","file":"pkg/util/goroutinemap/goroutinemap.go","code":"func (grm *goRoutineMap) Run(\n\toperationName string,\n\toperationFunc func() error) error {\n\tgrm.lock.Lock()\n\tdefer grm.lock.Unlock()\n\n\texistingOp, exists := grm.operations[operationName]\n\tif exists {\n\t\t// Operation with name exists\n\t\tif existingOp.operationPending {\n\t\t\treturn NewAlreadyExistsError(operationName)\n\t\t}\n\n\t\tif err := existingOp.expBackoff.SafeToRetry(operationName); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tgrm.operations[operationName] = operation{\n\t\toperationPending: true,\n\t\texpBackoff: existingOp.expBackoff,\n\t}\n\tgo func() (err error) {\n\t\t// Handle unhandled panics (very unlikely)\n\t\tdefer k8sRuntime.HandleCrash()\n\t\t// Handle completion of and error, if any, from operationFunc()\n\t\tdefer grm.operationComplete(operationName, \u0026err)\n\t\t// Handle panic, if any, from operationFunc()\n\t\tdefer k8sRuntime.RecoverFromPanic(\u0026err)\n\t\treturn operationFunc()\n\t}()\n\n\treturn nil\n}","line":{"from":86,"to":119}} {"id":100011642,"name":"operationComplete","signature":"func (grm *goRoutineMap) operationComplete(","file":"pkg/util/goroutinemap/goroutinemap.go","code":"// operationComplete handles the completion of a goroutine run in the\n// goRoutineMap.\nfunc (grm *goRoutineMap) operationComplete(\n\toperationName string, err *error) {\n\t// Defer operations are executed in Last-In is First-Out order. In this case\n\t// the lock is acquired first when operationCompletes begins, and is\n\t// released when the method finishes, after the lock is released cond is\n\t// signaled to wake waiting goroutine.\n\tdefer grm.cond.Signal()\n\tgrm.lock.Lock()\n\tdefer grm.lock.Unlock()\n\n\tif *err == nil || !grm.exponentialBackOffOnError {\n\t\t// Operation completed without error, or exponentialBackOffOnError disabled\n\t\tdelete(grm.operations, operationName)\n\t\tif *err != nil {\n\t\t\t// Log error\n\t\t\tklog.Errorf(\"operation for %q failed with: %v\",\n\t\t\t\toperationName,\n\t\t\t\t*err)\n\t\t}\n\t} else {\n\t\t// Operation completed with error and exponentialBackOffOnError Enabled\n\t\texistingOp := grm.operations[operationName]\n\t\texistingOp.expBackoff.Update(err)\n\t\texistingOp.operationPending = false\n\t\tgrm.operations[operationName] = existingOp\n\n\t\t// Log error\n\t\tklog.Errorf(\"%v\",\n\t\t\texistingOp.expBackoff.GenerateNoRetriesPermittedMsg(operationName))\n\t}\n}","line":{"from":121,"to":153}} {"id":100011643,"name":"IsOperationPending","signature":"func (grm *goRoutineMap) IsOperationPending(operationName string) bool","file":"pkg/util/goroutinemap/goroutinemap.go","code":"func (grm *goRoutineMap) IsOperationPending(operationName string) bool {\n\tgrm.lock.RLock()\n\tdefer grm.lock.RUnlock()\n\texistingOp, exists := grm.operations[operationName]\n\tif exists \u0026\u0026 existingOp.operationPending {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":155,"to":163}} {"id":100011644,"name":"Wait","signature":"func (grm *goRoutineMap) Wait()","file":"pkg/util/goroutinemap/goroutinemap.go","code":"func (grm *goRoutineMap) Wait() {\n\tgrm.lock.Lock()\n\tdefer grm.lock.Unlock()\n\n\tfor len(grm.operations) \u003e 0 {\n\t\tgrm.cond.Wait()\n\t}\n}","line":{"from":165,"to":172}} {"id":100011645,"name":"WaitForCompletion","signature":"func (grm *goRoutineMap) WaitForCompletion()","file":"pkg/util/goroutinemap/goroutinemap.go","code":"func (grm *goRoutineMap) WaitForCompletion() {\n\tgrm.lock.Lock()\n\tdefer grm.lock.Unlock()\n\n\tfor {\n\t\tif len(grm.operations) == 0 || grm.nothingPending() {\n\t\t\tbreak\n\t\t} else {\n\t\t\tgrm.cond.Wait()\n\t\t}\n\t}\n}","line":{"from":174,"to":185}} {"id":100011646,"name":"nothingPending","signature":"func (grm *goRoutineMap) nothingPending() bool","file":"pkg/util/goroutinemap/goroutinemap.go","code":"// Check if any operation is pending. Already assumes caller has the\n// necessary locks\nfunc (grm *goRoutineMap) nothingPending() bool {\n\tnothingIsPending := true\n\tfor _, operation := range grm.operations {\n\t\tif operation.operationPending {\n\t\t\tnothingIsPending = false\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nothingIsPending\n}","line":{"from":187,"to":198}} {"id":100011647,"name":"NewAlreadyExistsError","signature":"func NewAlreadyExistsError(operationName string) error","file":"pkg/util/goroutinemap/goroutinemap.go","code":"// NewAlreadyExistsError returns a new instance of AlreadyExists error.\nfunc NewAlreadyExistsError(operationName string) error {\n\treturn alreadyExistsError{operationName}\n}","line":{"from":200,"to":203}} {"id":100011648,"name":"IsAlreadyExists","signature":"func IsAlreadyExists(err error) bool","file":"pkg/util/goroutinemap/goroutinemap.go","code":"// IsAlreadyExists returns true if an error returned from GoRoutineMap indicates\n// a new operation can not be started because an operation with the same\n// operation name is already executing.\nfunc IsAlreadyExists(err error) bool {\n\tswitch err.(type) {\n\tcase alreadyExistsError:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":205,"to":215}} {"id":100011649,"name":"Error","signature":"func (err alreadyExistsError) Error() string","file":"pkg/util/goroutinemap/goroutinemap.go","code":"func (err alreadyExistsError) Error() string {\n\treturn fmt.Sprintf(\n\t\t\"Failed to create operation with name %q. An operation with that name is already executing.\",\n\t\terr.operationName)\n}","line":{"from":226,"to":230}} {"id":100011650,"name":"DeepHashObject","signature":"func DeepHashObject(hasher hash.Hash, objectToWrite interface{})","file":"pkg/util/hash/hash.go","code":"// DeepHashObject writes specified object to hash using the spew library\n// which follows pointers and prints actual values of the nested objects\n// ensuring the hash does not change when a pointer changes.\nfunc DeepHashObject(hasher hash.Hash, objectToWrite interface{}) {\n\thasher.Reset()\n\tprinter := spew.ConfigState{\n\t\tIndent: \" \",\n\t\tSortKeys: true,\n\t\tDisableMethods: true,\n\t\tSpewKeys: true,\n\t}\n\tprinter.Fprintf(hasher, \"%#v\", objectToWrite)\n}","line":{"from":25,"to":37}} {"id":100011651,"name":"New","signature":"func New(final func(os.Signal), notify ...func()) *Handler","file":"pkg/util/interrupt/interrupt.go","code":"// New creates a new handler that guarantees all notify functions are run after the critical\n// section exits (or is interrupted by the OS), then invokes the final handler. If no final\n// handler is specified, the default final is `os.Exit(1)`. A handler can only be used for\n// one critical section.\nfunc New(final func(os.Signal), notify ...func()) *Handler {\n\treturn \u0026Handler{\n\t\tfinal: final,\n\t\tnotify: notify,\n\t}\n}","line":{"from":39,"to":48}} {"id":100011652,"name":"Close","signature":"func (h *Handler) Close()","file":"pkg/util/interrupt/interrupt.go","code":"// Close executes all the notification handlers if they have not yet been executed.\nfunc (h *Handler) Close() {\n\th.once.Do(func() {\n\t\tfor _, fn := range h.notify {\n\t\t\tfn()\n\t\t}\n\t})\n}","line":{"from":50,"to":57}} {"id":100011653,"name":"Signal","signature":"func (h *Handler) Signal(s os.Signal)","file":"pkg/util/interrupt/interrupt.go","code":"// Signal is called when an os.Signal is received, and guarantees that all notifications\n// are executed, then the final handler is executed. This function should only be called once\n// per Handler instance.\nfunc (h *Handler) Signal(s os.Signal) {\n\th.once.Do(func() {\n\t\tfor _, fn := range h.notify {\n\t\t\tfn()\n\t\t}\n\t\tif h.final == nil {\n\t\t\tos.Exit(1)\n\t\t}\n\t\th.final(s)\n\t})\n}","line":{"from":59,"to":72}} {"id":100011654,"name":"Run","signature":"func (h *Handler) Run(fn func() error) error","file":"pkg/util/interrupt/interrupt.go","code":"// Run ensures that any notifications are invoked after the provided fn exits (even if the\n// process is interrupted by an OS termination signal). Notifications are only invoked once\n// per Handler instance, so calling Run more than once will not behave as the user expects.\nfunc (h *Handler) Run(fn func() error) error {\n\tch := make(chan os.Signal, 1)\n\tsignal.Notify(ch, terminationSignals...)\n\tdefer func() {\n\t\tsignal.Stop(ch)\n\t\tclose(ch)\n\t}()\n\tgo func() {\n\t\tsig, ok := \u003c-ch\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\t\th.Signal(sig)\n\t}()\n\tdefer h.Close()\n\treturn fn()\n}","line":{"from":74,"to":93}} {"id":100011655,"name":"Validate","signature":"func (set *IPSet) Validate() error","file":"pkg/util/ipset/ipset.go","code":"// Validate checks if a given ipset is valid or not.\nfunc (set *IPSet) Validate() error {\n\t// Check if protocol is valid for `HashIPPort`, `HashIPPortIP` and `HashIPPortNet` type set.\n\tif set.SetType == HashIPPort || set.SetType == HashIPPortIP || set.SetType == HashIPPortNet {\n\t\tif err := validateHashFamily(set.HashFamily); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// check set type\n\tif err := validateIPSetType(set.SetType); err != nil {\n\t\treturn err\n\t}\n\t// check port range for bitmap type set\n\tif set.SetType == BitmapPort {\n\t\tif err := validatePortRange(set.PortRange); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// check hash size value of ipset\n\tif set.HashSize \u003c= 0 {\n\t\treturn fmt.Errorf(\"invalid HashSize: %d\", set.HashSize)\n\t}\n\t// check max elem value of ipset\n\tif set.MaxElem \u003c= 0 {\n\t\treturn fmt.Errorf(\"invalid MaxElem %d\", set.MaxElem)\n\t}\n\n\treturn nil\n}","line":{"from":94,"to":122}} {"id":100011656,"name":"setIPSetDefaults","signature":"func (set *IPSet) setIPSetDefaults()","file":"pkg/util/ipset/ipset.go","code":"// setIPSetDefaults sets some IPSet fields if not present to their default values.\nfunc (set *IPSet) setIPSetDefaults() {\n\t// Setting default values if not present\n\tif set.HashSize == 0 {\n\t\tset.HashSize = 1024\n\t}\n\tif set.MaxElem == 0 {\n\t\tset.MaxElem = 65536\n\t}\n\t// Default protocol is IPv4\n\tif set.HashFamily == \"\" {\n\t\tset.HashFamily = ProtocolFamilyIPV4\n\t}\n\t// Default ipset type is \"hash:ip,port\"\n\tif len(set.SetType) == 0 {\n\t\tset.SetType = HashIPPort\n\t}\n\tif len(set.PortRange) == 0 {\n\t\tset.PortRange = DefaultPortRange\n\t}\n}","line":{"from":124,"to":144}} {"id":100011657,"name":"Validate","signature":"func (e *Entry) Validate(set *IPSet) bool","file":"pkg/util/ipset/ipset.go","code":"// Validate checks if a given ipset entry is valid or not. The set parameter is the ipset that entry belongs to.\nfunc (e *Entry) Validate(set *IPSet) bool {\n\tif e.Port \u003c 0 {\n\t\tklog.Errorf(\"Entry %v port number %d should be \u003e=0 for ipset %v\", e, e.Port, set)\n\t\treturn false\n\t}\n\tswitch e.SetType {\n\tcase HashIP:\n\t\t//check if IP of Entry is valid.\n\t\tif valid := e.checkIP(set); !valid {\n\t\t\treturn false\n\t\t}\n\tcase HashIPPort:\n\t\t//check if IP and Protocol of Entry is valid.\n\t\tif valid := e.checkIPandProtocol(set); !valid {\n\t\t\treturn false\n\t\t}\n\tcase HashIPPortIP:\n\t\t//check if IP and Protocol of Entry is valid.\n\t\tif valid := e.checkIPandProtocol(set); !valid {\n\t\t\treturn false\n\t\t}\n\n\t\t// IP2 can not be empty for `hash:ip,port,ip` type ip set\n\t\tif netutils.ParseIPSloppy(e.IP2) == nil {\n\t\t\tklog.Errorf(\"Error parsing entry %v second ip address %v for ipset %v\", e, e.IP2, set)\n\t\t\treturn false\n\t\t}\n\tcase HashIPPortNet:\n\t\t//check if IP and Protocol of Entry is valid.\n\t\tif valid := e.checkIPandProtocol(set); !valid {\n\t\t\treturn false\n\t\t}\n\n\t\t// Net can not be empty for `hash:ip,port,net` type ip set\n\t\tif _, ipNet, err := netutils.ParseCIDRSloppy(e.Net); ipNet == nil {\n\t\t\tklog.Errorf(\"Error parsing entry %v ip net %v for ipset %v, error: %v\", e, e.Net, set, err)\n\t\t\treturn false\n\t\t}\n\tcase BitmapPort:\n\t\t// check if port number satisfies its ipset's requirement of port range\n\t\tif set == nil {\n\t\t\tklog.Errorf(\"Unable to reference ip set where the entry %v exists\", e)\n\t\t\treturn false\n\t\t}\n\t\tbegin, end, err := parsePortRange(set.PortRange)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to parse set %v port range %s for ipset %v, error: %v\", set, set.PortRange, set, err)\n\t\t\treturn false\n\t\t}\n\t\tif e.Port \u003c begin || e.Port \u003e end {\n\t\t\tklog.Errorf(\"Entry %v port number %d is not in the port range %s of its ipset %v\", e, e.Port, set.PortRange, set)\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}","line":{"from":165,"to":222}} {"id":100011658,"name":"String","signature":"func (e *Entry) String() string","file":"pkg/util/ipset/ipset.go","code":"// String returns the string format for ipset entry.\nfunc (e *Entry) String() string {\n\tswitch e.SetType {\n\tcase HashIP:\n\t\t// Entry{192.168.1.1} -\u003e 192.168.1.1\n\t\treturn fmt.Sprintf(\"%s\", e.IP)\n\tcase HashIPPort:\n\t\t// Entry{192.168.1.1, udp, 53} -\u003e 192.168.1.1,udp:53\n\t\t// Entry{192.168.1.2, tcp, 8080} -\u003e 192.168.1.2,tcp:8080\n\t\treturn fmt.Sprintf(\"%s,%s:%s\", e.IP, e.Protocol, strconv.Itoa(e.Port))\n\tcase HashIPPortIP:\n\t\t// Entry{192.168.1.1, udp, 53, 10.0.0.1} -\u003e 192.168.1.1,udp:53,10.0.0.1\n\t\t// Entry{192.168.1.2, tcp, 8080, 192.168.1.2} -\u003e 192.168.1.2,tcp:8080,192.168.1.2\n\t\treturn fmt.Sprintf(\"%s,%s:%s,%s\", e.IP, e.Protocol, strconv.Itoa(e.Port), e.IP2)\n\tcase HashIPPortNet:\n\t\t// Entry{192.168.1.2, udp, 80, 10.0.1.0/24} -\u003e 192.168.1.2,udp:80,10.0.1.0/24\n\t\t// Entry{192.168.2,25, tcp, 8080, 10.1.0.0/16} -\u003e 192.168.2,25,tcp:8080,10.1.0.0/16\n\t\treturn fmt.Sprintf(\"%s,%s:%s,%s\", e.IP, e.Protocol, strconv.Itoa(e.Port), e.Net)\n\tcase BitmapPort:\n\t\t// Entry{53} -\u003e 53\n\t\t// Entry{8080} -\u003e 8080\n\t\treturn strconv.Itoa(e.Port)\n\t}\n\treturn \"\"\n}","line":{"from":224,"to":248}} {"id":100011659,"name":"checkIPandProtocol","signature":"func (e *Entry) checkIPandProtocol(set *IPSet) bool","file":"pkg/util/ipset/ipset.go","code":"// checkIPandProtocol checks if IP and Protocol of Entry is valid.\nfunc (e *Entry) checkIPandProtocol(set *IPSet) bool {\n\t// set default protocol to tcp if empty\n\tif len(e.Protocol) == 0 {\n\t\te.Protocol = ProtocolTCP\n\t} else if !validateProtocol(e.Protocol) {\n\t\treturn false\n\t}\n\treturn e.checkIP(set)\n}","line":{"from":250,"to":259}} {"id":100011660,"name":"checkIP","signature":"func (e *Entry) checkIP(set *IPSet) bool","file":"pkg/util/ipset/ipset.go","code":"// checkIP checks if IP of Entry is valid.\nfunc (e *Entry) checkIP(set *IPSet) bool {\n\tif netutils.ParseIPSloppy(e.IP) == nil {\n\t\tklog.Errorf(\"Error parsing entry %v ip address %v for ipset %v\", e, e.IP, set)\n\t\treturn false\n\t}\n\n\treturn true\n}","line":{"from":261,"to":269}} {"id":100011661,"name":"New","signature":"func New(exec utilexec.Interface) Interface","file":"pkg/util/ipset/ipset.go","code":"// New returns a new Interface which will exec ipset.\nfunc New(exec utilexec.Interface) Interface {\n\treturn \u0026runner{\n\t\texec: exec,\n\t}\n}","line":{"from":275,"to":280}} {"id":100011662,"name":"CreateSet","signature":"func (runner *runner) CreateSet(set *IPSet, ignoreExistErr bool) error","file":"pkg/util/ipset/ipset.go","code":"// CreateSet creates a new set, it will ignore error when the set already exists if ignoreExistErr=true.\nfunc (runner *runner) CreateSet(set *IPSet, ignoreExistErr bool) error {\n\t// sets some IPSet fields if not present to their default values.\n\tset.setIPSetDefaults()\n\n\t// Validate ipset before creating\n\tif err := set.Validate(); err != nil {\n\t\treturn err\n\t}\n\treturn runner.createSet(set, ignoreExistErr)\n}","line":{"from":282,"to":292}} {"id":100011663,"name":"createSet","signature":"func (runner *runner) createSet(set *IPSet, ignoreExistErr bool) error","file":"pkg/util/ipset/ipset.go","code":"// If ignoreExistErr is set to true, then the -exist option of ipset will be specified, ipset ignores the error\n// otherwise raised when the same set (setname and create parameters are identical) already exists.\nfunc (runner *runner) createSet(set *IPSet, ignoreExistErr bool) error {\n\targs := []string{\"create\", set.Name, string(set.SetType)}\n\tif set.SetType == HashIPPortIP || set.SetType == HashIPPort || set.SetType == HashIPPortNet || set.SetType == HashIP {\n\t\targs = append(args,\n\t\t\t\"family\", set.HashFamily,\n\t\t\t\"hashsize\", strconv.Itoa(set.HashSize),\n\t\t\t\"maxelem\", strconv.Itoa(set.MaxElem),\n\t\t)\n\t}\n\tif set.SetType == BitmapPort {\n\t\targs = append(args, \"range\", set.PortRange)\n\t}\n\tif ignoreExistErr {\n\t\targs = append(args, \"-exist\")\n\t}\n\tif _, err := runner.exec.Command(IPSetCmd, args...).CombinedOutput(); err != nil {\n\t\treturn fmt.Errorf(\"error creating ipset %s, error: %v\", set.Name, err)\n\t}\n\treturn nil\n}","line":{"from":294,"to":315}} {"id":100011664,"name":"AddEntry","signature":"func (runner *runner) AddEntry(entry string, set *IPSet, ignoreExistErr bool) error","file":"pkg/util/ipset/ipset.go","code":"// AddEntry adds a new entry to the named set.\n// If the -exist option is specified, ipset ignores the error otherwise raised when\n// the same set (setname and create parameters are identical) already exists.\nfunc (runner *runner) AddEntry(entry string, set *IPSet, ignoreExistErr bool) error {\n\targs := []string{\"add\", set.Name, entry}\n\tif ignoreExistErr {\n\t\targs = append(args, \"-exist\")\n\t}\n\tif out, err := runner.exec.Command(IPSetCmd, args...).CombinedOutput(); err != nil {\n\t\treturn fmt.Errorf(\"error adding entry %s, error: %v (%s)\", entry, err, out)\n\t}\n\treturn nil\n}","line":{"from":317,"to":329}} {"id":100011665,"name":"DelEntry","signature":"func (runner *runner) DelEntry(entry string, set string) error","file":"pkg/util/ipset/ipset.go","code":"// DelEntry is used to delete the specified entry from the set.\nfunc (runner *runner) DelEntry(entry string, set string) error {\n\tif out, err := runner.exec.Command(IPSetCmd, \"del\", set, entry).CombinedOutput(); err != nil {\n\t\treturn fmt.Errorf(\"error deleting entry %s: from set: %s, error: %v (%s)\", entry, set, err, out)\n\t}\n\treturn nil\n}","line":{"from":331,"to":337}} {"id":100011666,"name":"TestEntry","signature":"func (runner *runner) TestEntry(entry string, set string) (bool, error)","file":"pkg/util/ipset/ipset.go","code":"// TestEntry is used to check whether the specified entry is in the set or not.\nfunc (runner *runner) TestEntry(entry string, set string) (bool, error) {\n\tif out, err := runner.exec.Command(IPSetCmd, \"test\", set, entry).CombinedOutput(); err == nil {\n\t\treg, e := regexp.Compile(\"is NOT in set \" + set)\n\t\tif e == nil \u0026\u0026 reg.MatchString(string(out)) {\n\t\t\treturn false, nil\n\t\t} else if e == nil {\n\t\t\treturn true, nil\n\t\t} else {\n\t\t\treturn false, fmt.Errorf(\"error testing entry: %s, error: %v\", entry, e)\n\t\t}\n\t} else {\n\t\treturn false, fmt.Errorf(\"error testing entry %s: %v (%s)\", entry, err, out)\n\t}\n}","line":{"from":339,"to":353}} {"id":100011667,"name":"FlushSet","signature":"func (runner *runner) FlushSet(set string) error","file":"pkg/util/ipset/ipset.go","code":"// FlushSet deletes all entries from a named set.\nfunc (runner *runner) FlushSet(set string) error {\n\tif _, err := runner.exec.Command(IPSetCmd, \"flush\", set).CombinedOutput(); err != nil {\n\t\treturn fmt.Errorf(\"error flushing set: %s, error: %v\", set, err)\n\t}\n\treturn nil\n}","line":{"from":355,"to":361}} {"id":100011668,"name":"DestroySet","signature":"func (runner *runner) DestroySet(set string) error","file":"pkg/util/ipset/ipset.go","code":"// DestroySet is used to destroy a named set.\nfunc (runner *runner) DestroySet(set string) error {\n\tif out, err := runner.exec.Command(IPSetCmd, \"destroy\", set).CombinedOutput(); err != nil {\n\t\treturn fmt.Errorf(\"error destroying set %s, error: %v(%s)\", set, err, out)\n\t}\n\treturn nil\n}","line":{"from":363,"to":369}} {"id":100011669,"name":"DestroyAllSets","signature":"func (runner *runner) DestroyAllSets() error","file":"pkg/util/ipset/ipset.go","code":"// DestroyAllSets is used to destroy all sets.\nfunc (runner *runner) DestroyAllSets() error {\n\tif _, err := runner.exec.Command(IPSetCmd, \"destroy\").CombinedOutput(); err != nil {\n\t\treturn fmt.Errorf(\"error destroying all sets, error: %v\", err)\n\t}\n\treturn nil\n}","line":{"from":371,"to":377}} {"id":100011670,"name":"ListSets","signature":"func (runner *runner) ListSets() ([]string, error)","file":"pkg/util/ipset/ipset.go","code":"// ListSets list all set names from kernel\nfunc (runner *runner) ListSets() ([]string, error) {\n\tout, err := runner.exec.Command(IPSetCmd, \"list\", \"-n\").CombinedOutput()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error listing all sets, error: %v\", err)\n\t}\n\treturn strings.Split(string(out), \"\\n\"), nil\n}","line":{"from":379,"to":386}} {"id":100011671,"name":"ListEntries","signature":"func (runner *runner) ListEntries(set string) ([]string, error)","file":"pkg/util/ipset/ipset.go","code":"// ListEntries lists all the entries from a named set.\nfunc (runner *runner) ListEntries(set string) ([]string, error) {\n\tif len(set) == 0 {\n\t\treturn nil, fmt.Errorf(\"set name can't be nil\")\n\t}\n\tout, err := runner.exec.Command(IPSetCmd, \"list\", set).CombinedOutput()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error listing set: %s, error: %v\", set, err)\n\t}\n\tmemberMatcher := regexp.MustCompile(EntryMemberPattern)\n\tlist := memberMatcher.ReplaceAllString(string(out[:]), \"\")\n\tstrs := strings.Split(list, \"\\n\")\n\tresults := make([]string, 0)\n\tfor i := range strs {\n\t\tif len(strs[i]) \u003e 0 {\n\t\t\tresults = append(results, strs[i])\n\t\t}\n\t}\n\treturn results, nil\n}","line":{"from":388,"to":407}} {"id":100011672,"name":"GetVersion","signature":"func (runner *runner) GetVersion() (string, error)","file":"pkg/util/ipset/ipset.go","code":"// GetVersion returns the version string.\nfunc (runner *runner) GetVersion() (string, error) {\n\treturn getIPSetVersionString(runner.exec)\n}","line":{"from":409,"to":412}} {"id":100011673,"name":"getIPSetVersionString","signature":"func getIPSetVersionString(exec utilexec.Interface) (string, error)","file":"pkg/util/ipset/ipset.go","code":"// getIPSetVersionString runs \"ipset --version\" to get the version string\n// in the form of \"X.Y\", i.e \"6.19\"\nfunc getIPSetVersionString(exec utilexec.Interface) (string, error) {\n\tcmd := exec.Command(IPSetCmd, \"--version\")\n\tcmd.SetStdin(bytes.NewReader([]byte{}))\n\tbytes, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tversionMatcher := regexp.MustCompile(VersionPattern)\n\tmatch := versionMatcher.FindStringSubmatch(string(bytes))\n\tif match == nil {\n\t\treturn \"\", fmt.Errorf(\"no ipset version found in string: %s\", bytes)\n\t}\n\treturn match[0], nil\n}","line":{"from":414,"to":429}} {"id":100011674,"name":"validatePortRange","signature":"func validatePortRange(portRange string) error","file":"pkg/util/ipset/ipset.go","code":"// checks if port range is valid. The begin port number is not necessarily less than\n// end port number - ipset util can accept it. It means both 1-100 and 100-1 are valid.\nfunc validatePortRange(portRange string) error {\n\tstrs := strings.Split(portRange, \"-\")\n\tif len(strs) != 2 {\n\t\treturn fmt.Errorf(\"invalid PortRange: %q\", portRange)\n\t}\n\tfor i := range strs {\n\t\tnum, err := strconv.Atoi(strs[i])\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid PortRange: %q\", portRange)\n\t\t}\n\t\tif num \u003c 0 {\n\t\t\treturn fmt.Errorf(\"invalid PortRange: %q\", portRange)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":431,"to":448}} {"id":100011675,"name":"validateIPSetType","signature":"func validateIPSetType(set Type) error","file":"pkg/util/ipset/ipset.go","code":"// checks if the given ipset type is valid.\nfunc validateIPSetType(set Type) error {\n\tfor _, valid := range ValidIPSetTypes {\n\t\tif set == valid {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"unsupported SetType: %q\", set)\n}","line":{"from":450,"to":458}} {"id":100011676,"name":"validateHashFamily","signature":"func validateHashFamily(family string) error","file":"pkg/util/ipset/ipset.go","code":"// checks if given hash family is supported in ipset\nfunc validateHashFamily(family string) error {\n\tif family == ProtocolFamilyIPV4 || family == ProtocolFamilyIPV6 {\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"unsupported HashFamily %q\", family)\n}","line":{"from":460,"to":466}} {"id":100011677,"name":"IsNotFoundError","signature":"func IsNotFoundError(err error) bool","file":"pkg/util/ipset/ipset.go","code":"// IsNotFoundError returns true if the error indicates \"not found\". It parses\n// the error string looking for known values, which is imperfect but works in\n// practice.\nfunc IsNotFoundError(err error) bool {\n\tes := err.Error()\n\tif strings.Contains(es, \"does not exist\") {\n\t\t// set with the same name already exists\n\t\t// xref: https://github.com/Olipro/ipset/blob/master/lib/errcode.c#L32-L33\n\t\treturn true\n\t}\n\tif strings.Contains(es, \"element is missing\") {\n\t\t// entry is missing from the set\n\t\t// xref: https://github.com/Olipro/ipset/blob/master/lib/parse.c#L1904\n\t\t// https://github.com/Olipro/ipset/blob/master/lib/parse.c#L1925\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":468,"to":485}} {"id":100011678,"name":"validateProtocol","signature":"func validateProtocol(protocol string) bool","file":"pkg/util/ipset/ipset.go","code":"// checks if given protocol is supported in entry\nfunc validateProtocol(protocol string) bool {\n\tif protocol == ProtocolTCP || protocol == ProtocolUDP || protocol == ProtocolSCTP {\n\t\treturn true\n\t}\n\tklog.Errorf(\"Invalid entry's protocol: %s, supported protocols are [%s, %s, %s]\", protocol, ProtocolTCP, ProtocolUDP, ProtocolSCTP)\n\treturn false\n}","line":{"from":487,"to":494}} {"id":100011679,"name":"parsePortRange","signature":"func parsePortRange(portRange string) (beginPort int, endPort int, err error)","file":"pkg/util/ipset/ipset.go","code":"// parsePortRange parse the begin and end port from a raw string(format: a-b). beginPort \u003c= endPort\n// in the return value.\nfunc parsePortRange(portRange string) (beginPort int, endPort int, err error) {\n\tif len(portRange) == 0 {\n\t\tportRange = DefaultPortRange\n\t}\n\n\tstrs := strings.Split(portRange, \"-\")\n\tif len(strs) != 2 {\n\t\t// port number -1 indicates invalid\n\t\treturn -1, -1, fmt.Errorf(\"port range should be in the format of `a-b`\")\n\t}\n\tfor i := range strs {\n\t\tnum, err := strconv.Atoi(strs[i])\n\t\tif err != nil {\n\t\t\t// port number -1 indicates invalid\n\t\t\treturn -1, -1, err\n\t\t}\n\t\tif num \u003c 0 {\n\t\t\t// port number -1 indicates invalid\n\t\t\treturn -1, -1, fmt.Errorf(\"port number %d should be \u003e=0\", num)\n\t\t}\n\t\tif i == 0 {\n\t\t\tbeginPort = num\n\t\t\tcontinue\n\t\t}\n\t\tendPort = num\n\t\t// switch when first port number \u003e second port number\n\t\tif beginPort \u003e endPort {\n\t\t\tendPort = beginPort\n\t\t\tbeginPort = num\n\t\t}\n\t}\n\treturn beginPort, endPort, nil\n}","line":{"from":496,"to":530}} {"id":100011680,"name":"newInternal","signature":"func newInternal(exec utilexec.Interface, protocol Protocol, lockfilePath14x, lockfilePath16x string) Interface","file":"pkg/util/iptables/iptables.go","code":"// newInternal returns a new Interface which will exec iptables, and allows the\n// caller to change the iptables-restore lockfile path\nfunc newInternal(exec utilexec.Interface, protocol Protocol, lockfilePath14x, lockfilePath16x string) Interface {\n\tversion, err := getIPTablesVersion(exec, protocol)\n\tif err != nil {\n\t\tklog.InfoS(\"Error checking iptables version, assuming version at least\", \"version\", MinCheckVersion, \"err\", err)\n\t\tversion = MinCheckVersion\n\t}\n\n\tif lockfilePath16x == \"\" {\n\t\tlockfilePath16x = LockfilePath16x\n\t}\n\tif lockfilePath14x == \"\" {\n\t\tlockfilePath14x = LockfilePath14x\n\t}\n\n\trunner := \u0026runner{\n\t\texec: exec,\n\t\tprotocol: protocol,\n\t\thasCheck: version.AtLeast(MinCheckVersion),\n\t\thasRandomFully: version.AtLeast(RandomFullyMinVersion),\n\t\twaitFlag: getIPTablesWaitFlag(version),\n\t\trestoreWaitFlag: getIPTablesRestoreWaitFlag(version, exec, protocol),\n\t\tlockfilePath14x: lockfilePath14x,\n\t\tlockfilePath16x: lockfilePath16x,\n\t}\n\treturn runner\n}","line":{"from":216,"to":243}} {"id":100011681,"name":"New","signature":"func New(exec utilexec.Interface, protocol Protocol) Interface","file":"pkg/util/iptables/iptables.go","code":"// New returns a new Interface which will exec iptables.\nfunc New(exec utilexec.Interface, protocol Protocol) Interface {\n\treturn newInternal(exec, protocol, \"\", \"\")\n}","line":{"from":245,"to":248}} {"id":100011682,"name":"EnsureChain","signature":"func (runner *runner) EnsureChain(table Table, chain Chain) (bool, error)","file":"pkg/util/iptables/iptables.go","code":"// EnsureChain is part of Interface.\nfunc (runner *runner) EnsureChain(table Table, chain Chain) (bool, error) {\n\tfullArgs := makeFullArgs(table, chain)\n\n\trunner.mu.Lock()\n\tdefer runner.mu.Unlock()\n\n\tout, err := runner.run(opCreateChain, fullArgs)\n\tif err != nil {\n\t\tif ee, ok := err.(utilexec.ExitError); ok {\n\t\t\tif ee.Exited() \u0026\u0026 ee.ExitStatus() == 1 {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\t\treturn false, fmt.Errorf(\"error creating chain %q: %v: %s\", chain, err, out)\n\t}\n\treturn false, nil\n}","line":{"from":250,"to":267}} {"id":100011683,"name":"FlushChain","signature":"func (runner *runner) FlushChain(table Table, chain Chain) error","file":"pkg/util/iptables/iptables.go","code":"// FlushChain is part of Interface.\nfunc (runner *runner) FlushChain(table Table, chain Chain) error {\n\tfullArgs := makeFullArgs(table, chain)\n\n\trunner.mu.Lock()\n\tdefer runner.mu.Unlock()\n\n\tout, err := runner.run(opFlushChain, fullArgs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error flushing chain %q: %v: %s\", chain, err, out)\n\t}\n\treturn nil\n}","line":{"from":269,"to":281}} {"id":100011684,"name":"DeleteChain","signature":"func (runner *runner) DeleteChain(table Table, chain Chain) error","file":"pkg/util/iptables/iptables.go","code":"// DeleteChain is part of Interface.\nfunc (runner *runner) DeleteChain(table Table, chain Chain) error {\n\tfullArgs := makeFullArgs(table, chain)\n\n\trunner.mu.Lock()\n\tdefer runner.mu.Unlock()\n\n\tout, err := runner.run(opDeleteChain, fullArgs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error deleting chain %q: %v: %s\", chain, err, out)\n\t}\n\treturn nil\n}","line":{"from":283,"to":295}} {"id":100011685,"name":"EnsureRule","signature":"func (runner *runner) EnsureRule(position RulePosition, table Table, chain Chain, args ...string) (bool, error)","file":"pkg/util/iptables/iptables.go","code":"// EnsureRule is part of Interface.\nfunc (runner *runner) EnsureRule(position RulePosition, table Table, chain Chain, args ...string) (bool, error) {\n\tfullArgs := makeFullArgs(table, chain, args...)\n\n\trunner.mu.Lock()\n\tdefer runner.mu.Unlock()\n\n\texists, err := runner.checkRule(table, chain, args...)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif exists {\n\t\treturn true, nil\n\t}\n\tout, err := runner.run(operation(position), fullArgs)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"error appending rule: %v: %s\", err, out)\n\t}\n\treturn false, nil\n}","line":{"from":297,"to":316}} {"id":100011686,"name":"DeleteRule","signature":"func (runner *runner) DeleteRule(table Table, chain Chain, args ...string) error","file":"pkg/util/iptables/iptables.go","code":"// DeleteRule is part of Interface.\nfunc (runner *runner) DeleteRule(table Table, chain Chain, args ...string) error {\n\tfullArgs := makeFullArgs(table, chain, args...)\n\n\trunner.mu.Lock()\n\tdefer runner.mu.Unlock()\n\n\texists, err := runner.checkRule(table, chain, args...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !exists {\n\t\treturn nil\n\t}\n\tout, err := runner.run(opDeleteRule, fullArgs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error deleting rule: %v: %s\", err, out)\n\t}\n\treturn nil\n}","line":{"from":318,"to":337}} {"id":100011687,"name":"IsIPv6","signature":"func (runner *runner) IsIPv6() bool","file":"pkg/util/iptables/iptables.go","code":"func (runner *runner) IsIPv6() bool {\n\treturn runner.protocol == ProtocolIPv6\n}","line":{"from":339,"to":341}} {"id":100011688,"name":"Protocol","signature":"func (runner *runner) Protocol() Protocol","file":"pkg/util/iptables/iptables.go","code":"func (runner *runner) Protocol() Protocol {\n\treturn runner.protocol\n}","line":{"from":343,"to":345}} {"id":100011689,"name":"SaveInto","signature":"func (runner *runner) SaveInto(table Table, buffer *bytes.Buffer) error","file":"pkg/util/iptables/iptables.go","code":"// SaveInto is part of Interface.\nfunc (runner *runner) SaveInto(table Table, buffer *bytes.Buffer) error {\n\trunner.mu.Lock()\n\tdefer runner.mu.Unlock()\n\n\ttrace := utiltrace.New(\"iptables save\")\n\tdefer trace.LogIfLong(2 * time.Second)\n\n\t// run and return\n\tiptablesSaveCmd := iptablesSaveCommand(runner.protocol)\n\targs := []string{\"-t\", string(table)}\n\tklog.V(4).InfoS(\"Running\", \"command\", iptablesSaveCmd, \"arguments\", args)\n\tcmd := runner.exec.Command(iptablesSaveCmd, args...)\n\tcmd.SetStdout(buffer)\n\tstderrBuffer := bytes.NewBuffer(nil)\n\tcmd.SetStderr(stderrBuffer)\n\n\terr := cmd.Run()\n\tif err != nil {\n\t\tstderrBuffer.WriteTo(buffer) // ignore error, since we need to return the original error\n\t}\n\treturn err\n}","line":{"from":347,"to":369}} {"id":100011690,"name":"Restore","signature":"func (runner *runner) Restore(table Table, data []byte, flush FlushFlag, counters RestoreCountersFlag) error","file":"pkg/util/iptables/iptables.go","code":"// Restore is part of Interface.\nfunc (runner *runner) Restore(table Table, data []byte, flush FlushFlag, counters RestoreCountersFlag) error {\n\t// setup args\n\targs := []string{\"-T\", string(table)}\n\treturn runner.restoreInternal(args, data, flush, counters)\n}","line":{"from":371,"to":376}} {"id":100011691,"name":"RestoreAll","signature":"func (runner *runner) RestoreAll(data []byte, flush FlushFlag, counters RestoreCountersFlag) error","file":"pkg/util/iptables/iptables.go","code":"// RestoreAll is part of Interface.\nfunc (runner *runner) RestoreAll(data []byte, flush FlushFlag, counters RestoreCountersFlag) error {\n\t// setup args\n\targs := make([]string, 0)\n\treturn runner.restoreInternal(args, data, flush, counters)\n}","line":{"from":378,"to":383}} {"id":100011692,"name":"restoreInternal","signature":"func (runner *runner) restoreInternal(args []string, data []byte, flush FlushFlag, counters RestoreCountersFlag) error","file":"pkg/util/iptables/iptables.go","code":"// restoreInternal is the shared part of Restore/RestoreAll\nfunc (runner *runner) restoreInternal(args []string, data []byte, flush FlushFlag, counters RestoreCountersFlag) error {\n\trunner.mu.Lock()\n\tdefer runner.mu.Unlock()\n\n\ttrace := utiltrace.New(\"iptables restore\")\n\tdefer trace.LogIfLong(2 * time.Second)\n\n\tif !flush {\n\t\targs = append(args, \"--noflush\")\n\t}\n\tif counters {\n\t\targs = append(args, \"--counters\")\n\t}\n\n\t// Grab the iptables lock to prevent iptables-restore and iptables\n\t// from stepping on each other. iptables-restore 1.6.2 will have\n\t// a --wait option like iptables itself, but that's not widely deployed.\n\tif len(runner.restoreWaitFlag) == 0 {\n\t\tlocker, err := grabIptablesLocks(runner.lockfilePath14x, runner.lockfilePath16x)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttrace.Step(\"Locks grabbed\")\n\t\tdefer func(locker iptablesLocker) {\n\t\t\tif err := locker.Close(); err != nil {\n\t\t\t\tklog.ErrorS(err, \"Failed to close iptables locks\")\n\t\t\t}\n\t\t}(locker)\n\t}\n\n\t// run the command and return the output or an error including the output and error\n\tfullArgs := append(runner.restoreWaitFlag, args...)\n\tiptablesRestoreCmd := iptablesRestoreCommand(runner.protocol)\n\tklog.V(4).InfoS(\"Running\", \"command\", iptablesRestoreCmd, \"arguments\", fullArgs)\n\tcmd := runner.exec.Command(iptablesRestoreCmd, fullArgs...)\n\tcmd.SetStdin(bytes.NewBuffer(data))\n\tb, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tpErr, ok := parseRestoreError(string(b))\n\t\tif ok {\n\t\t\treturn pErr\n\t\t}\n\t\treturn fmt.Errorf(\"%w: %s\", err, b)\n\t}\n\treturn nil\n}","line":{"from":389,"to":435}} {"id":100011693,"name":"iptablesSaveCommand","signature":"func iptablesSaveCommand(protocol Protocol) string","file":"pkg/util/iptables/iptables.go","code":"func iptablesSaveCommand(protocol Protocol) string {\n\tif protocol == ProtocolIPv6 {\n\t\treturn cmdIP6TablesSave\n\t}\n\treturn cmdIPTablesSave\n}","line":{"from":437,"to":442}} {"id":100011694,"name":"iptablesRestoreCommand","signature":"func iptablesRestoreCommand(protocol Protocol) string","file":"pkg/util/iptables/iptables.go","code":"func iptablesRestoreCommand(protocol Protocol) string {\n\tif protocol == ProtocolIPv6 {\n\t\treturn cmdIP6TablesRestore\n\t}\n\treturn cmdIPTablesRestore\n\n}","line":{"from":444,"to":450}} {"id":100011695,"name":"iptablesCommand","signature":"func iptablesCommand(protocol Protocol) string","file":"pkg/util/iptables/iptables.go","code":"func iptablesCommand(protocol Protocol) string {\n\tif protocol == ProtocolIPv6 {\n\t\treturn cmdIP6Tables\n\t}\n\treturn cmdIPTables\n}","line":{"from":452,"to":457}} {"id":100011696,"name":"run","signature":"func (runner *runner) run(op operation, args []string) ([]byte, error)","file":"pkg/util/iptables/iptables.go","code":"func (runner *runner) run(op operation, args []string) ([]byte, error) {\n\treturn runner.runContext(context.TODO(), op, args)\n}","line":{"from":459,"to":461}} {"id":100011697,"name":"runContext","signature":"func (runner *runner) runContext(ctx context.Context, op operation, args []string) ([]byte, error)","file":"pkg/util/iptables/iptables.go","code":"func (runner *runner) runContext(ctx context.Context, op operation, args []string) ([]byte, error) {\n\tiptablesCmd := iptablesCommand(runner.protocol)\n\tfullArgs := append(runner.waitFlag, string(op))\n\tfullArgs = append(fullArgs, args...)\n\tklog.V(5).InfoS(\"Running\", \"command\", iptablesCmd, \"arguments\", fullArgs)\n\tif ctx == nil {\n\t\treturn runner.exec.Command(iptablesCmd, fullArgs...).CombinedOutput()\n\t}\n\treturn runner.exec.CommandContext(ctx, iptablesCmd, fullArgs...).CombinedOutput()\n\t// Don't log err here - callers might not think it is an error.\n}","line":{"from":463,"to":473}} {"id":100011698,"name":"checkRule","signature":"func (runner *runner) checkRule(table Table, chain Chain, args ...string) (bool, error)","file":"pkg/util/iptables/iptables.go","code":"// Returns (bool, nil) if it was able to check the existence of the rule, or\n// (\u003cundefined\u003e, error) if the process of checking failed.\nfunc (runner *runner) checkRule(table Table, chain Chain, args ...string) (bool, error) {\n\tif runner.hasCheck {\n\t\treturn runner.checkRuleUsingCheck(makeFullArgs(table, chain, args...))\n\t}\n\treturn runner.checkRuleWithoutCheck(table, chain, args...)\n}","line":{"from":475,"to":482}} {"id":100011699,"name":"trimhex","signature":"func trimhex(s string) string","file":"pkg/util/iptables/iptables.go","code":"func trimhex(s string) string {\n\treturn hexnumRE.ReplaceAllString(s, \"0x$1\")\n}","line":{"from":486,"to":488}} {"id":100011700,"name":"checkRuleWithoutCheck","signature":"func (runner *runner) checkRuleWithoutCheck(table Table, chain Chain, args ...string) (bool, error)","file":"pkg/util/iptables/iptables.go","code":"// Executes the rule check without using the \"-C\" flag, instead parsing iptables-save.\n// Present for compatibility with \u003c1.4.11 versions of iptables. This is full\n// of hack and half-measures. We should nix this ASAP.\nfunc (runner *runner) checkRuleWithoutCheck(table Table, chain Chain, args ...string) (bool, error) {\n\tiptablesSaveCmd := iptablesSaveCommand(runner.protocol)\n\tklog.V(1).InfoS(\"Running\", \"command\", iptablesSaveCmd, \"table\", string(table))\n\tout, err := runner.exec.Command(iptablesSaveCmd, \"-t\", string(table)).CombinedOutput()\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"error checking rule: %v\", err)\n\t}\n\n\t// Sadly, iptables has inconsistent quoting rules for comments. Just remove all quotes.\n\t// Also, quoted multi-word comments (which are counted as a single arg)\n\t// will be unpacked into multiple args,\n\t// in order to compare against iptables-save output (which will be split at whitespace boundary)\n\t// e.g. a single arg('\"this must be before the NodePort rules\"') will be unquoted and unpacked into 7 args.\n\tvar argsCopy []string\n\tfor i := range args {\n\t\ttmpField := strings.Trim(args[i], \"\\\"\")\n\t\ttmpField = trimhex(tmpField)\n\t\targsCopy = append(argsCopy, strings.Fields(tmpField)...)\n\t}\n\targset := sets.NewString(argsCopy...)\n\n\tfor _, line := range strings.Split(string(out), \"\\n\") {\n\t\tvar fields = strings.Fields(line)\n\n\t\t// Check that this is a rule for the correct chain, and that it has\n\t\t// the correct number of argument (+2 for \"-A \u003cchain name\u003e\")\n\t\tif !strings.HasPrefix(line, fmt.Sprintf(\"-A %s\", string(chain))) || len(fields) != len(argsCopy)+2 {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Sadly, iptables has inconsistent quoting rules for comments.\n\t\t// Just remove all quotes.\n\t\tfor i := range fields {\n\t\t\tfields[i] = strings.Trim(fields[i], \"\\\"\")\n\t\t\tfields[i] = trimhex(fields[i])\n\t\t}\n\n\t\t// TODO: This misses reorderings e.g. \"-x foo ! -y bar\" will match \"! -x foo -y bar\"\n\t\tif sets.NewString(fields...).IsSuperset(argset) {\n\t\t\treturn true, nil\n\t\t}\n\t\tklog.V(5).InfoS(\"DBG: fields is not a superset of args\", \"fields\", fields, \"arguments\", args)\n\t}\n\n\treturn false, nil\n}","line":{"from":490,"to":538}} {"id":100011701,"name":"checkRuleUsingCheck","signature":"func (runner *runner) checkRuleUsingCheck(args []string) (bool, error)","file":"pkg/util/iptables/iptables.go","code":"// Executes the rule check using the \"-C\" flag\nfunc (runner *runner) checkRuleUsingCheck(args []string) (bool, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)\n\tdefer cancel()\n\n\tout, err := runner.runContext(ctx, opCheckRule, args)\n\tif ctx.Err() == context.DeadlineExceeded {\n\t\treturn false, fmt.Errorf(\"timed out while checking rules\")\n\t}\n\tif err == nil {\n\t\treturn true, nil\n\t}\n\tif ee, ok := err.(utilexec.ExitError); ok {\n\t\t// iptables uses exit(1) to indicate a failure of the operation,\n\t\t// as compared to a malformed commandline, for example.\n\t\tif ee.Exited() \u0026\u0026 ee.ExitStatus() == 1 {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\treturn false, fmt.Errorf(\"error checking rule: %v: %s\", err, out)\n}","line":{"from":540,"to":560}} {"id":100011702,"name":"Monitor","signature":"func (runner *runner) Monitor(canary Chain, tables []Table, reloadFunc func(), interval time.Duration, stopCh \u003c-chan struct{})","file":"pkg/util/iptables/iptables.go","code":"// Monitor is part of Interface\nfunc (runner *runner) Monitor(canary Chain, tables []Table, reloadFunc func(), interval time.Duration, stopCh \u003c-chan struct{}) {\n\tfor {\n\t\t_ = utilwait.PollImmediateUntil(interval, func() (bool, error) {\n\t\t\tfor _, table := range tables {\n\t\t\t\tif _, err := runner.EnsureChain(table, canary); err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"Could not set up iptables canary\", \"table\", table, \"chain\", canary)\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true, nil\n\t\t}, stopCh)\n\n\t\t// Poll until stopCh is closed or iptables is flushed\n\t\terr := utilwait.PollUntil(interval, func() (bool, error) {\n\t\t\tif exists, err := runner.ChainExists(tables[0], canary); exists {\n\t\t\t\treturn false, nil\n\t\t\t} else if isResourceError(err) {\n\t\t\t\tklog.ErrorS(err, \"Could not check for iptables canary\", \"table\", tables[0], \"chain\", canary)\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\tklog.V(2).InfoS(\"IPTables canary deleted\", \"table\", tables[0], \"chain\", canary)\n\t\t\t// Wait for the other canaries to be deleted too before returning\n\t\t\t// so we don't start reloading too soon.\n\t\t\terr := utilwait.PollImmediate(iptablesFlushPollTime, iptablesFlushTimeout, func() (bool, error) {\n\t\t\t\tfor i := 1; i \u003c len(tables); i++ {\n\t\t\t\t\tif exists, err := runner.ChainExists(tables[i], canary); exists || isResourceError(err) {\n\t\t\t\t\t\treturn false, nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn true, nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tklog.InfoS(\"Inconsistent iptables state detected\")\n\t\t\t}\n\t\t\treturn true, nil\n\t\t}, stopCh)\n\n\t\tif err != nil {\n\t\t\t// stopCh was closed\n\t\t\tfor _, table := range tables {\n\t\t\t\t_ = runner.DeleteChain(table, canary)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tklog.V(2).InfoS(\"Reloading after iptables flush\")\n\t\treloadFunc()\n\t}\n}","line":{"from":569,"to":618}} {"id":100011703,"name":"ChainExists","signature":"func (runner *runner) ChainExists(table Table, chain Chain) (bool, error)","file":"pkg/util/iptables/iptables.go","code":"// ChainExists is part of Interface\nfunc (runner *runner) ChainExists(table Table, chain Chain) (bool, error) {\n\tfullArgs := makeFullArgs(table, chain)\n\n\trunner.mu.Lock()\n\tdefer runner.mu.Unlock()\n\n\ttrace := utiltrace.New(\"iptables ChainExists\")\n\tdefer trace.LogIfLong(2 * time.Second)\n\n\t_, err := runner.run(opListChain, fullArgs)\n\treturn err == nil, err\n}","line":{"from":620,"to":632}} {"id":100011704,"name":"makeFullArgs","signature":"func makeFullArgs(table Table, chain Chain, args ...string) []string","file":"pkg/util/iptables/iptables.go","code":"func makeFullArgs(table Table, chain Chain, args ...string) []string {\n\treturn append([]string{string(chain), \"-t\", string(table)}, args...)\n}","line":{"from":645,"to":647}} {"id":100011705,"name":"getIPTablesVersion","signature":"func getIPTablesVersion(exec utilexec.Interface, protocol Protocol) (*utilversion.Version, error)","file":"pkg/util/iptables/iptables.go","code":"// getIPTablesVersion runs \"iptables --version\" and parses the returned version\nfunc getIPTablesVersion(exec utilexec.Interface, protocol Protocol) (*utilversion.Version, error) {\n\t// this doesn't access mutable state so we don't need to use the interface / runner\n\tiptablesCmd := iptablesCommand(protocol)\n\tbytes, err := exec.Command(iptablesCmd, \"--version\").CombinedOutput()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tversionMatcher := regexp.MustCompile(iptablesVersionPattern)\n\tmatch := versionMatcher.FindStringSubmatch(string(bytes))\n\tif match == nil {\n\t\treturn nil, fmt.Errorf(\"no iptables version found in string: %s\", bytes)\n\t}\n\tversion, err := utilversion.ParseGeneric(match[1])\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"iptables version %q is not a valid version string: %v\", match[1], err)\n\t}\n\n\treturn version, nil\n}","line":{"from":651,"to":670}} {"id":100011706,"name":"getIPTablesWaitFlag","signature":"func getIPTablesWaitFlag(version *utilversion.Version) []string","file":"pkg/util/iptables/iptables.go","code":"// Checks if iptables version has a \"wait\" flag\nfunc getIPTablesWaitFlag(version *utilversion.Version) []string {\n\tswitch {\n\tcase version.AtLeast(WaitIntervalMinVersion):\n\t\treturn []string{WaitString, WaitSecondsValue, WaitIntervalString, WaitIntervalUsecondsValue}\n\tcase version.AtLeast(WaitSecondsMinVersion):\n\t\treturn []string{WaitString, WaitSecondsValue}\n\tcase version.AtLeast(WaitMinVersion):\n\t\treturn []string{WaitString}\n\tdefault:\n\t\treturn nil\n\t}\n}","line":{"from":672,"to":684}} {"id":100011707,"name":"getIPTablesRestoreWaitFlag","signature":"func getIPTablesRestoreWaitFlag(version *utilversion.Version, exec utilexec.Interface, protocol Protocol) []string","file":"pkg/util/iptables/iptables.go","code":"// Checks if iptables-restore has a \"wait\" flag\nfunc getIPTablesRestoreWaitFlag(version *utilversion.Version, exec utilexec.Interface, protocol Protocol) []string {\n\tif version.AtLeast(WaitRestoreMinVersion) {\n\t\treturn []string{WaitString, WaitSecondsValue, WaitIntervalString, WaitIntervalUsecondsValue}\n\t}\n\n\t// Older versions may have backported features; if iptables-restore supports\n\t// --version, assume it also supports --wait\n\tvstring, err := getIPTablesRestoreVersionString(exec, protocol)\n\tif err != nil || vstring == \"\" {\n\t\tklog.V(3).InfoS(\"Couldn't get iptables-restore version; assuming it doesn't support --wait\")\n\t\treturn nil\n\t}\n\tif _, err := utilversion.ParseGeneric(vstring); err != nil {\n\t\tklog.V(3).InfoS(\"Couldn't parse iptables-restore version; assuming it doesn't support --wait\")\n\t\treturn nil\n\t}\n\treturn []string{WaitString}\n}","line":{"from":686,"to":704}} {"id":100011708,"name":"getIPTablesRestoreVersionString","signature":"func getIPTablesRestoreVersionString(exec utilexec.Interface, protocol Protocol) (string, error)","file":"pkg/util/iptables/iptables.go","code":"// getIPTablesRestoreVersionString runs \"iptables-restore --version\" to get the version string\n// in the form \"X.X.X\"\nfunc getIPTablesRestoreVersionString(exec utilexec.Interface, protocol Protocol) (string, error) {\n\t// this doesn't access mutable state so we don't need to use the interface / runner\n\n\t// iptables-restore hasn't always had --version, and worse complains\n\t// about unrecognized commands but doesn't exit when it gets them.\n\t// Work around that by setting stdin to nothing so it exits immediately.\n\tiptablesRestoreCmd := iptablesRestoreCommand(protocol)\n\tcmd := exec.Command(iptablesRestoreCmd, \"--version\")\n\tcmd.SetStdin(bytes.NewReader([]byte{}))\n\tbytes, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tversionMatcher := regexp.MustCompile(iptablesVersionPattern)\n\tmatch := versionMatcher.FindStringSubmatch(string(bytes))\n\tif match == nil {\n\t\treturn \"\", fmt.Errorf(\"no iptables version found in string: %s\", bytes)\n\t}\n\treturn match[1], nil\n}","line":{"from":706,"to":727}} {"id":100011709,"name":"HasRandomFully","signature":"func (runner *runner) HasRandomFully() bool","file":"pkg/util/iptables/iptables.go","code":"func (runner *runner) HasRandomFully() bool {\n\treturn runner.hasRandomFully\n}","line":{"from":729,"to":731}} {"id":100011710,"name":"Present","signature":"func (runner *runner) Present() bool","file":"pkg/util/iptables/iptables.go","code":"// Present tests if iptable is supported on current kernel by checking the existence\n// of default table and chain\nfunc (runner *runner) Present() bool {\n\tif _, err := runner.ChainExists(TableNAT, ChainPostrouting); err != nil {\n\t\treturn false\n\t}\n\n\treturn true\n}","line":{"from":733,"to":741}} {"id":100011711,"name":"IsNotFoundError","signature":"func IsNotFoundError(err error) bool","file":"pkg/util/iptables/iptables.go","code":"// IsNotFoundError returns true if the error indicates \"not found\". It parses\n// the error string looking for known values, which is imperfect; beware using\n// this function for anything beyond deciding between logging or ignoring an\n// error.\nfunc IsNotFoundError(err error) bool {\n\tes := err.Error()\n\tfor _, str := range iptablesNotFoundStrings {\n\t\tif strings.Contains(es, str) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":766,"to":778}} {"id":100011712,"name":"isResourceError","signature":"func isResourceError(err error) bool","file":"pkg/util/iptables/iptables.go","code":"// isResourceError returns true if the error indicates that iptables ran into a \"resource\n// problem\" and was unable to attempt the request. In particular, this will be true if it\n// times out trying to get the iptables lock.\nfunc isResourceError(err error) bool {\n\tif ee, isExitError := err.(utilexec.ExitError); isExitError {\n\t\treturn ee.ExitStatus() == iptablesStatusResourceProblem\n\t}\n\treturn false\n}","line":{"from":782,"to":790}} {"id":100011713,"name":"Line","signature":"func (e parseError) Line() int","file":"pkg/util/iptables/iptables.go","code":"func (e parseError) Line() int {\n\treturn e.line\n}","line":{"from":806,"to":808}} {"id":100011714,"name":"Error","signature":"func (e parseError) Error() string","file":"pkg/util/iptables/iptables.go","code":"func (e parseError) Error() string {\n\treturn fmt.Sprintf(\"%s: input error on line %d: \", e.cmd, e.line)\n}","line":{"from":810,"to":812}} {"id":100011715,"name":"parseRestoreError","signature":"func parseRestoreError(str string) (ParseError, bool)","file":"pkg/util/iptables/iptables.go","code":"// parseRestoreError extracts the line from the error, if it matches returns parseError\n// for example:\n// input: iptables-restore: line 51 failed\n// output: parseError: cmd = iptables-restore, line = 51\n// NOTE: parseRestoreError depends on the error format of iptables, if it ever changes\n// we need to update this function\nfunc parseRestoreError(str string) (ParseError, bool) {\n\terrors := strings.Split(str, \":\")\n\tif len(errors) != 2 {\n\t\treturn nil, false\n\t}\n\tcmd := errors[0]\n\tmatches := regexpParseError.FindStringSubmatch(errors[1])\n\tif len(matches) != 2 {\n\t\treturn nil, false\n\t}\n\tline, errMsg := strconv.Atoi(matches[1])\n\tif errMsg != nil {\n\t\treturn nil, false\n\t}\n\treturn parseError{cmd: cmd, line: line}, true\n}","line":{"from":824,"to":845}} {"id":100011716,"name":"ExtractLines","signature":"func ExtractLines(lines []byte, line, count int) []LineData","file":"pkg/util/iptables/iptables.go","code":"// ExtractLines extracts the -count and +count data from the lineNum row of lines and return\n// NOTE: lines start from line 1\nfunc ExtractLines(lines []byte, line, count int) []LineData {\n\t// first line is line 1, so line can't be smaller than 1\n\tif line \u003c 1 {\n\t\treturn nil\n\t}\n\tstart := line - count\n\tif start \u003c= 0 {\n\t\tstart = 1\n\t}\n\tend := line + count + 1\n\n\toffset := 1\n\tscanner := bufio.NewScanner(bytes.NewBuffer(lines))\n\textractLines := make([]LineData, 0, count*2)\n\tfor scanner.Scan() {\n\t\tif offset \u003e= start \u0026\u0026 offset \u003c end {\n\t\t\textractLines = append(extractLines, LineData{\n\t\t\t\tLine: offset,\n\t\t\t\tData: scanner.Text(),\n\t\t\t})\n\t\t}\n\t\tif offset == end {\n\t\t\tbreak\n\t\t}\n\t\toffset++\n\t}\n\treturn extractLines\n}","line":{"from":847,"to":876}} {"id":100011717,"name":"Close","signature":"func (l *locker) Close() error","file":"pkg/util/iptables/iptables_linux.go","code":"func (l *locker) Close() error {\n\terrList := []error{}\n\tif l.lock16 != nil {\n\t\tif err := l.lock16.Close(); err != nil {\n\t\t\terrList = append(errList, err)\n\t\t}\n\t}\n\tif l.lock14 != nil {\n\t\tif err := l.lock14.Close(); err != nil {\n\t\t\terrList = append(errList, err)\n\t\t}\n\t}\n\treturn utilerrors.NewAggregate(errList)\n}","line":{"from":38,"to":51}} {"id":100011718,"name":"grabIptablesLocks","signature":"func grabIptablesLocks(lockfilePath14x, lockfilePath16x string) (iptablesLocker, error)","file":"pkg/util/iptables/iptables_linux.go","code":"func grabIptablesLocks(lockfilePath14x, lockfilePath16x string) (iptablesLocker, error) {\n\tvar err error\n\tvar success bool\n\n\tl := \u0026locker{}\n\tdefer func(l *locker) {\n\t\t// Clean up immediately on failure\n\t\tif !success {\n\t\t\tl.Close()\n\t\t}\n\t}(l)\n\n\t// Grab both 1.6.x and 1.4.x-style locks; we don't know what the\n\t// iptables-restore version is if it doesn't support --wait, so we\n\t// can't assume which lock method it'll use.\n\n\t// Roughly duplicate iptables 1.6.x xtables_lock() function.\n\tl.lock16, err = os.OpenFile(lockfilePath16x, os.O_CREATE, 0600)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open iptables lock %s: %v\", lockfilePath16x, err)\n\t}\n\n\tif err := wait.PollImmediate(200*time.Millisecond, 2*time.Second, func() (bool, error) {\n\t\tif err := grabIptablesFileLock(l.lock16); err != nil {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t}); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to acquire new iptables lock: %v\", err)\n\t}\n\n\t// Roughly duplicate iptables 1.4.x xtables_lock() function.\n\tif err := wait.PollImmediate(200*time.Millisecond, 2*time.Second, func() (bool, error) {\n\t\tl.lock14, err = net.ListenUnix(\"unix\", \u0026net.UnixAddr{Name: lockfilePath14x, Net: \"unix\"})\n\t\tif err != nil {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t}); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to acquire old iptables lock: %v\", err)\n\t}\n\n\tsuccess = true\n\treturn l, nil\n}","line":{"from":53,"to":97}} {"id":100011719,"name":"grabIptablesFileLock","signature":"func grabIptablesFileLock(f *os.File) error","file":"pkg/util/iptables/iptables_linux.go","code":"func grabIptablesFileLock(f *os.File) error {\n\treturn unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB)\n}","line":{"from":99,"to":101}} {"id":100011720,"name":"grabIptablesLocks","signature":"func grabIptablesLocks(lock14filePath, lock16filePath string) (iptablesLocker, error)","file":"pkg/util/iptables/iptables_unsupported.go","code":"func grabIptablesLocks(lock14filePath, lock16filePath string) (iptablesLocker, error) {\n\treturn nil, fmt.Errorf(\"iptables unsupported on this platform\")\n}","line":{"from":27,"to":29}} {"id":100011721,"name":"grabIptablesFileLock","signature":"func grabIptablesFileLock(f *os.File) error","file":"pkg/util/iptables/iptables_unsupported.go","code":"func grabIptablesFileLock(f *os.File) error {\n\treturn fmt.Errorf(\"iptables unsupported on this platform\")\n}","line":{"from":31,"to":33}} {"id":100011722,"name":"MakeChainLine","signature":"func MakeChainLine(chain Chain) string","file":"pkg/util/iptables/save_restore.go","code":"// MakeChainLine return an iptables-save/restore formatted chain line given a Chain\nfunc MakeChainLine(chain Chain) string {\n\treturn fmt.Sprintf(\":%s - [0:0]\", chain)\n}","line":{"from":24,"to":27}} {"id":100011723,"name":"GetChainsFromTable","signature":"func GetChainsFromTable(save []byte) map[Chain]struct{}","file":"pkg/util/iptables/save_restore.go","code":"// GetChainsFromTable parses iptables-save data to find the chains that are defined. It\n// assumes that save contains a single table's data, and returns a map with keys for every\n// chain defined in that table.\nfunc GetChainsFromTable(save []byte) map[Chain]struct{} {\n\tchainsMap := make(map[Chain]struct{})\n\n\tfor {\n\t\ti := bytes.Index(save, []byte(\"\\n:\"))\n\t\tif i == -1 {\n\t\t\tbreak\n\t\t}\n\t\tstart := i + 2\n\t\tsave = save[start:]\n\t\tend := bytes.Index(save, []byte(\" \"))\n\t\tif i == -1 {\n\t\t\t// shouldn't happen, but...\n\t\t\tbreak\n\t\t}\n\t\tchain := Chain(save[:end])\n\t\tchainsMap[chain] = struct{}{}\n\t\tsave = save[end:]\n\t}\n\treturn chainsMap\n}","line":{"from":29,"to":52}} {"id":100011724,"name":"Equal","signature":"func (svc *VirtualServer) Equal(other *VirtualServer) bool","file":"pkg/util/ipvs/ipvs.go","code":"// Equal check the equality of virtual server.\n// We don't use struct == since it doesn't work because of slice.\nfunc (svc *VirtualServer) Equal(other *VirtualServer) bool {\n\treturn svc.Address.Equal(other.Address) \u0026\u0026\n\t\tsvc.Protocol == other.Protocol \u0026\u0026\n\t\tsvc.Port == other.Port \u0026\u0026\n\t\tsvc.Scheduler == other.Scheduler \u0026\u0026\n\t\tsvc.Flags == other.Flags \u0026\u0026\n\t\tsvc.Timeout == other.Timeout\n}","line":{"from":74,"to":83}} {"id":100011725,"name":"String","signature":"func (svc *VirtualServer) String() string","file":"pkg/util/ipvs/ipvs.go","code":"func (svc *VirtualServer) String() string {\n\treturn net.JoinHostPort(svc.Address.String(), strconv.Itoa(int(svc.Port))) + \"/\" + svc.Protocol\n}","line":{"from":85,"to":87}} {"id":100011726,"name":"String","signature":"func (rs *RealServer) String() string","file":"pkg/util/ipvs/ipvs.go","code":"func (rs *RealServer) String() string {\n\treturn net.JoinHostPort(rs.Address.String(), strconv.Itoa(int(rs.Port)))\n}","line":{"from":98,"to":100}} {"id":100011727,"name":"Equal","signature":"func (rs *RealServer) Equal(other *RealServer) bool","file":"pkg/util/ipvs/ipvs.go","code":"// Equal check the equality of real server.\n// We don't use struct == since it doesn't work because of slice.\nfunc (rs *RealServer) Equal(other *RealServer) bool {\n\treturn rs.Address.Equal(other.Address) \u0026\u0026\n\t\trs.Port == other.Port\n}","line":{"from":102,"to":107}} {"id":100011728,"name":"IsRsGracefulTerminationNeeded","signature":"func IsRsGracefulTerminationNeeded(proto string) bool","file":"pkg/util/ipvs/ipvs.go","code":"// IsRsGracefulTerminationNeeded returns true if protocol requires graceful termination for the stale connections\nfunc IsRsGracefulTerminationNeeded(proto string) bool {\n\treturn !strings.EqualFold(proto, \"UDP\") \u0026\u0026 !strings.EqualFold(proto, \"SCTP\")\n}","line":{"from":109,"to":112}} {"id":100011729,"name":"New","signature":"func New() Interface","file":"pkg/util/ipvs/ipvs_linux.go","code":"// New returns a new Interface which will call ipvs APIs.\nfunc New() Interface {\n\thandle, err := libipvs.New(\"\")\n\tif err != nil {\n\t\tklog.Errorf(\"IPVS interface can't be initialized, error: %v\", err)\n\t\treturn nil\n\t}\n\treturn \u0026runner{\n\t\tipvsHandle: handle,\n\t}\n}","line":{"from":45,"to":55}} {"id":100011730,"name":"AddVirtualServer","signature":"func (runner *runner) AddVirtualServer(vs *VirtualServer) error","file":"pkg/util/ipvs/ipvs_linux.go","code":"// AddVirtualServer is part of ipvs.Interface.\nfunc (runner *runner) AddVirtualServer(vs *VirtualServer) error {\n\tsvc, err := toIPVSService(vs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not convert local virtual server to IPVS service: %w\", err)\n\t}\n\trunner.mu.Lock()\n\tdefer runner.mu.Unlock()\n\treturn runner.ipvsHandle.NewService(svc)\n}","line":{"from":57,"to":66}} {"id":100011731,"name":"UpdateVirtualServer","signature":"func (runner *runner) UpdateVirtualServer(vs *VirtualServer) error","file":"pkg/util/ipvs/ipvs_linux.go","code":"// UpdateVirtualServer is part of ipvs.Interface.\nfunc (runner *runner) UpdateVirtualServer(vs *VirtualServer) error {\n\tsvc, err := toIPVSService(vs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not convert local virtual server to IPVS service: %w\", err)\n\t}\n\trunner.mu.Lock()\n\tdefer runner.mu.Unlock()\n\treturn runner.ipvsHandle.UpdateService(svc)\n}","line":{"from":68,"to":77}} {"id":100011732,"name":"DeleteVirtualServer","signature":"func (runner *runner) DeleteVirtualServer(vs *VirtualServer) error","file":"pkg/util/ipvs/ipvs_linux.go","code":"// DeleteVirtualServer is part of ipvs.Interface.\nfunc (runner *runner) DeleteVirtualServer(vs *VirtualServer) error {\n\tsvc, err := toIPVSService(vs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not convert local virtual server to IPVS service: %w\", err)\n\t}\n\trunner.mu.Lock()\n\tdefer runner.mu.Unlock()\n\treturn runner.ipvsHandle.DelService(svc)\n}","line":{"from":79,"to":88}} {"id":100011733,"name":"GetVirtualServer","signature":"func (runner *runner) GetVirtualServer(vs *VirtualServer) (*VirtualServer, error)","file":"pkg/util/ipvs/ipvs_linux.go","code":"// GetVirtualServer is part of ipvs.Interface.\nfunc (runner *runner) GetVirtualServer(vs *VirtualServer) (*VirtualServer, error) {\n\tsvc, err := toIPVSService(vs)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not convert local virtual server to IPVS service: %w\", err)\n\t}\n\trunner.mu.Lock()\n\tipvsSvc, err := runner.ipvsHandle.GetService(svc)\n\trunner.mu.Unlock()\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not get IPVS service: %w\", err)\n\t}\n\tvServ, err := toVirtualServer(ipvsSvc)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not convert IPVS service to local virtual server: %w\", err)\n\t}\n\treturn vServ, nil\n}","line":{"from":90,"to":108}} {"id":100011734,"name":"GetVirtualServers","signature":"func (runner *runner) GetVirtualServers() ([]*VirtualServer, error)","file":"pkg/util/ipvs/ipvs_linux.go","code":"// GetVirtualServers is part of ipvs.Interface.\nfunc (runner *runner) GetVirtualServers() ([]*VirtualServer, error) {\n\trunner.mu.Lock()\n\tipvsSvcs, err := runner.ipvsHandle.GetServices()\n\trunner.mu.Unlock()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not get IPVS services: %w\", err)\n\t}\n\tvss := make([]*VirtualServer, 0)\n\tfor _, ipvsSvc := range ipvsSvcs {\n\t\tvs, err := toVirtualServer(ipvsSvc)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"could not convert IPVS service to local virtual server: %w\", err)\n\t\t}\n\t\tvss = append(vss, vs)\n\t}\n\treturn vss, nil\n}","line":{"from":110,"to":127}} {"id":100011735,"name":"Flush","signature":"func (runner *runner) Flush() error","file":"pkg/util/ipvs/ipvs_linux.go","code":"// Flush is part of ipvs.Interface. Currently we delete IPVS services one by one\nfunc (runner *runner) Flush() error {\n\trunner.mu.Lock()\n\tdefer runner.mu.Unlock()\n\treturn runner.ipvsHandle.Flush()\n}","line":{"from":129,"to":134}} {"id":100011736,"name":"AddRealServer","signature":"func (runner *runner) AddRealServer(vs *VirtualServer, rs *RealServer) error","file":"pkg/util/ipvs/ipvs_linux.go","code":"// AddRealServer is part of ipvs.Interface.\nfunc (runner *runner) AddRealServer(vs *VirtualServer, rs *RealServer) error {\n\tsvc, err := toIPVSService(vs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not convert local virtual server to IPVS service: %w\", err)\n\t}\n\tdst, err := toIPVSDestination(rs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not convert local real server to IPVS destination: %w\", err)\n\t}\n\trunner.mu.Lock()\n\tdefer runner.mu.Unlock()\n\treturn runner.ipvsHandle.NewDestination(svc, dst)\n}","line":{"from":136,"to":149}} {"id":100011737,"name":"DeleteRealServer","signature":"func (runner *runner) DeleteRealServer(vs *VirtualServer, rs *RealServer) error","file":"pkg/util/ipvs/ipvs_linux.go","code":"// DeleteRealServer is part of ipvs.Interface.\nfunc (runner *runner) DeleteRealServer(vs *VirtualServer, rs *RealServer) error {\n\tsvc, err := toIPVSService(vs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not convert local virtual server to IPVS service: %w\", err)\n\t}\n\tdst, err := toIPVSDestination(rs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not convert local real server to IPVS destination: %w\", err)\n\t}\n\trunner.mu.Lock()\n\tdefer runner.mu.Unlock()\n\treturn runner.ipvsHandle.DelDestination(svc, dst)\n}","line":{"from":151,"to":164}} {"id":100011738,"name":"UpdateRealServer","signature":"func (runner *runner) UpdateRealServer(vs *VirtualServer, rs *RealServer) error","file":"pkg/util/ipvs/ipvs_linux.go","code":"func (runner *runner) UpdateRealServer(vs *VirtualServer, rs *RealServer) error {\n\tsvc, err := toIPVSService(vs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not convert local virtual server to IPVS service: %w\", err)\n\t}\n\tdst, err := toIPVSDestination(rs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not convert local real server to IPVS destination: %w\", err)\n\t}\n\trunner.mu.Lock()\n\tdefer runner.mu.Unlock()\n\treturn runner.ipvsHandle.UpdateDestination(svc, dst)\n}","line":{"from":166,"to":178}} {"id":100011739,"name":"GetRealServers","signature":"func (runner *runner) GetRealServers(vs *VirtualServer) ([]*RealServer, error)","file":"pkg/util/ipvs/ipvs_linux.go","code":"// GetRealServers is part of ipvs.Interface.\nfunc (runner *runner) GetRealServers(vs *VirtualServer) ([]*RealServer, error) {\n\tsvc, err := toIPVSService(vs)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not convert local virtual server to IPVS service: %w\", err)\n\t}\n\trunner.mu.Lock()\n\tdsts, err := runner.ipvsHandle.GetDestinations(svc)\n\trunner.mu.Unlock()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not get IPVS destination for service: %w\", err)\n\t}\n\trss := make([]*RealServer, 0)\n\tfor _, dst := range dsts {\n\t\tdst, err := toRealServer(dst)\n\t\t// TODO: aggregate errors?\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"could not convert IPVS destination to local real server: %w\", err)\n\t\t}\n\t\trss = append(rss, dst)\n\t}\n\treturn rss, nil\n}","line":{"from":180,"to":202}} {"id":100011740,"name":"ConfigureTimeouts","signature":"func (runner *runner) ConfigureTimeouts(tcpTimeout, tcpFinTimeout, udpTimeout time.Duration) error","file":"pkg/util/ipvs/ipvs_linux.go","code":"// ConfigureTimeouts is the equivalent to running \"ipvsadm --set\" to configure tcp, tcpfin and udp timeouts\nfunc (runner *runner) ConfigureTimeouts(tcpTimeout, tcpFinTimeout, udpTimeout time.Duration) error {\n\tipvsConfig := \u0026libipvs.Config{\n\t\tTimeoutTCP: tcpTimeout,\n\t\tTimeoutTCPFin: tcpFinTimeout,\n\t\tTimeoutUDP: udpTimeout,\n\t}\n\n\treturn runner.ipvsHandle.SetConfig(ipvsConfig)\n}","line":{"from":204,"to":213}} {"id":100011741,"name":"toVirtualServer","signature":"func toVirtualServer(svc *libipvs.Service) (*VirtualServer, error)","file":"pkg/util/ipvs/ipvs_linux.go","code":"// toVirtualServer converts an IPVS Service to the equivalent VirtualServer structure.\nfunc toVirtualServer(svc *libipvs.Service) (*VirtualServer, error) {\n\tif svc == nil {\n\t\treturn nil, errors.New(\"ipvs svc should not be empty\")\n\t}\n\tvs := \u0026VirtualServer{\n\t\tAddress: svc.Address,\n\t\tPort: svc.Port,\n\t\tScheduler: svc.SchedName,\n\t\tProtocol: protocolToString(Protocol(svc.Protocol)),\n\t\tTimeout: svc.Timeout,\n\t}\n\n\t// Test FlagHashed (0x2). A valid flag must include FlagHashed\n\tif svc.Flags\u0026FlagHashed == 0 {\n\t\treturn nil, fmt.Errorf(\"Flags of successfully created IPVS service should enable the flag (%x) since every service is hashed into the service table\", FlagHashed)\n\t}\n\t// Sub Flags to 0x2\n\t// 011 -\u003e 001, 010 -\u003e 000\n\tvs.Flags = ServiceFlags(svc.Flags \u0026^ uint32(FlagHashed))\n\n\tif vs.Address == nil {\n\t\tif svc.AddressFamily == unix.AF_INET {\n\t\t\tvs.Address = net.IPv4zero\n\t\t} else {\n\t\t\tvs.Address = net.IPv6zero\n\t\t}\n\t}\n\treturn vs, nil\n}","line":{"from":215,"to":244}} {"id":100011742,"name":"toRealServer","signature":"func toRealServer(dst *libipvs.Destination) (*RealServer, error)","file":"pkg/util/ipvs/ipvs_linux.go","code":"// toRealServer converts an IPVS Destination to the equivalent RealServer structure.\nfunc toRealServer(dst *libipvs.Destination) (*RealServer, error) {\n\tif dst == nil {\n\t\treturn nil, errors.New(\"ipvs destination should not be empty\")\n\t}\n\treturn \u0026RealServer{\n\t\tAddress: dst.Address,\n\t\tPort: dst.Port,\n\t\tWeight: dst.Weight,\n\t\tActiveConn: dst.ActiveConnections,\n\t\tInactiveConn: dst.InactiveConnections,\n\t}, nil\n}","line":{"from":246,"to":258}} {"id":100011743,"name":"toIPVSService","signature":"func toIPVSService(vs *VirtualServer) (*libipvs.Service, error)","file":"pkg/util/ipvs/ipvs_linux.go","code":"// toIPVSService converts a VirtualServer to the equivalent IPVS Service structure.\nfunc toIPVSService(vs *VirtualServer) (*libipvs.Service, error) {\n\tif vs == nil {\n\t\treturn nil, errors.New(\"virtual server should not be empty\")\n\t}\n\tipvsSvc := \u0026libipvs.Service{\n\t\tAddress: vs.Address,\n\t\tProtocol: stringToProtocol(vs.Protocol),\n\t\tPort: vs.Port,\n\t\tSchedName: vs.Scheduler,\n\t\tFlags: uint32(vs.Flags),\n\t\tTimeout: vs.Timeout,\n\t}\n\n\tif ip4 := vs.Address.To4(); ip4 != nil {\n\t\tipvsSvc.AddressFamily = unix.AF_INET\n\t\tipvsSvc.Netmask = 0xffffffff\n\t} else {\n\t\tipvsSvc.AddressFamily = unix.AF_INET6\n\t\tipvsSvc.Netmask = 128\n\t}\n\treturn ipvsSvc, nil\n}","line":{"from":260,"to":282}} {"id":100011744,"name":"toIPVSDestination","signature":"func toIPVSDestination(rs *RealServer) (*libipvs.Destination, error)","file":"pkg/util/ipvs/ipvs_linux.go","code":"// toIPVSDestination converts a RealServer to the equivalent IPVS Destination structure.\nfunc toIPVSDestination(rs *RealServer) (*libipvs.Destination, error) {\n\tif rs == nil {\n\t\treturn nil, errors.New(\"real server should not be empty\")\n\t}\n\treturn \u0026libipvs.Destination{\n\t\tAddress: rs.Address,\n\t\tPort: rs.Port,\n\t\tWeight: rs.Weight,\n\t}, nil\n}","line":{"from":284,"to":294}} {"id":100011745,"name":"stringToProtocol","signature":"func stringToProtocol(protocol string) uint16","file":"pkg/util/ipvs/ipvs_linux.go","code":"// stringToProtocolType returns the protocol type for the given name\nfunc stringToProtocol(protocol string) uint16 {\n\tswitch strings.ToLower(protocol) {\n\tcase \"tcp\":\n\t\treturn uint16(unix.IPPROTO_TCP)\n\tcase \"udp\":\n\t\treturn uint16(unix.IPPROTO_UDP)\n\tcase \"sctp\":\n\t\treturn uint16(unix.IPPROTO_SCTP)\n\t}\n\treturn uint16(0)\n}","line":{"from":296,"to":307}} {"id":100011746,"name":"protocolToString","signature":"func protocolToString(proto Protocol) string","file":"pkg/util/ipvs/ipvs_linux.go","code":"// protocolTypeToString returns the name for the given protocol.\nfunc protocolToString(proto Protocol) string {\n\tswitch proto {\n\tcase unix.IPPROTO_TCP:\n\t\treturn \"TCP\"\n\tcase unix.IPPROTO_UDP:\n\t\treturn \"UDP\"\n\tcase unix.IPPROTO_SCTP:\n\t\treturn \"SCTP\"\n\t}\n\treturn \"\"\n}","line":{"from":309,"to":320}} {"id":100011747,"name":"New","signature":"func New() Interface","file":"pkg/util/ipvs/ipvs_unsupported.go","code":"// New returns a dummy Interface for unsupported platform.\nfunc New() Interface {\n\treturn \u0026runner{}\n}","line":{"from":27,"to":30}} {"id":100011748,"name":"Flush","signature":"func (runner *runner) Flush() error","file":"pkg/util/ipvs/ipvs_unsupported.go","code":"func (runner *runner) Flush() error {\n\treturn fmt.Errorf(\"IPVS not supported for this platform\")\n}","line":{"from":35,"to":37}} {"id":100011749,"name":"AddVirtualServer","signature":"func (runner *runner) AddVirtualServer(*VirtualServer) error","file":"pkg/util/ipvs/ipvs_unsupported.go","code":"func (runner *runner) AddVirtualServer(*VirtualServer) error {\n\treturn fmt.Errorf(\"IPVS not supported for this platform\")\n}","line":{"from":39,"to":41}} {"id":100011750,"name":"UpdateVirtualServer","signature":"func (runner *runner) UpdateVirtualServer(*VirtualServer) error","file":"pkg/util/ipvs/ipvs_unsupported.go","code":"func (runner *runner) UpdateVirtualServer(*VirtualServer) error {\n\treturn fmt.Errorf(\"IPVS not supported for this platform\")\n}","line":{"from":43,"to":45}} {"id":100011751,"name":"DeleteVirtualServer","signature":"func (runner *runner) DeleteVirtualServer(*VirtualServer) error","file":"pkg/util/ipvs/ipvs_unsupported.go","code":"func (runner *runner) DeleteVirtualServer(*VirtualServer) error {\n\treturn fmt.Errorf(\"IPVS not supported for this platform\")\n}","line":{"from":47,"to":49}} {"id":100011752,"name":"GetVirtualServer","signature":"func (runner *runner) GetVirtualServer(*VirtualServer) (*VirtualServer, error)","file":"pkg/util/ipvs/ipvs_unsupported.go","code":"func (runner *runner) GetVirtualServer(*VirtualServer) (*VirtualServer, error) {\n\treturn nil, fmt.Errorf(\"IPVS not supported for this platform\")\n}","line":{"from":51,"to":53}} {"id":100011753,"name":"GetVirtualServers","signature":"func (runner *runner) GetVirtualServers() ([]*VirtualServer, error)","file":"pkg/util/ipvs/ipvs_unsupported.go","code":"func (runner *runner) GetVirtualServers() ([]*VirtualServer, error) {\n\treturn nil, fmt.Errorf(\"IPVS not supported for this platform\")\n}","line":{"from":55,"to":57}} {"id":100011754,"name":"AddRealServer","signature":"func (runner *runner) AddRealServer(*VirtualServer, *RealServer) error","file":"pkg/util/ipvs/ipvs_unsupported.go","code":"func (runner *runner) AddRealServer(*VirtualServer, *RealServer) error {\n\treturn fmt.Errorf(\"IPVS not supported for this platform\")\n}","line":{"from":59,"to":61}} {"id":100011755,"name":"GetRealServers","signature":"func (runner *runner) GetRealServers(*VirtualServer) ([]*RealServer, error)","file":"pkg/util/ipvs/ipvs_unsupported.go","code":"func (runner *runner) GetRealServers(*VirtualServer) ([]*RealServer, error) {\n\treturn nil, fmt.Errorf(\"IPVS not supported for this platform\")\n}","line":{"from":63,"to":65}} {"id":100011756,"name":"DeleteRealServer","signature":"func (runner *runner) DeleteRealServer(*VirtualServer, *RealServer) error","file":"pkg/util/ipvs/ipvs_unsupported.go","code":"func (runner *runner) DeleteRealServer(*VirtualServer, *RealServer) error {\n\treturn fmt.Errorf(\"IPVS not supported for this platform\")\n}","line":{"from":67,"to":69}} {"id":100011757,"name":"UpdateRealServer","signature":"func (runner *runner) UpdateRealServer(*VirtualServer, *RealServer) error","file":"pkg/util/ipvs/ipvs_unsupported.go","code":"func (runner *runner) UpdateRealServer(*VirtualServer, *RealServer) error {\n\treturn fmt.Errorf(\"IPVS not supported for this platform\")\n}","line":{"from":71,"to":73}} {"id":100011758,"name":"ConfigureTimeouts","signature":"func (runner *runner) ConfigureTimeouts(time.Duration, time.Duration, time.Duration) error","file":"pkg/util/ipvs/ipvs_unsupported.go","code":"func (runner *runner) ConfigureTimeouts(time.Duration, time.Duration, time.Duration) error {\n\treturn fmt.Errorf(\"IPVS not supported for this platform\")\n}","line":{"from":75,"to":77}} {"id":100011759,"name":"CloneAndAddLabel","signature":"func CloneAndAddLabel(labels map[string]string, labelKey, labelValue string) map[string]string","file":"pkg/util/labels/labels.go","code":"// Clones the given map and returns a new map with the given key and value added.\n// Returns the given map, if labelKey is empty.\nfunc CloneAndAddLabel(labels map[string]string, labelKey, labelValue string) map[string]string {\n\tif labelKey == \"\" {\n\t\t// Don't need to add a label.\n\t\treturn labels\n\t}\n\t// Clone.\n\tnewLabels := map[string]string{}\n\tfor key, value := range labels {\n\t\tnewLabels[key] = value\n\t}\n\tnewLabels[labelKey] = labelValue\n\treturn newLabels\n}","line":{"from":23,"to":37}} {"id":100011760,"name":"CloneAndRemoveLabel","signature":"func CloneAndRemoveLabel(labels map[string]string, labelKey string) map[string]string","file":"pkg/util/labels/labels.go","code":"// CloneAndRemoveLabel clones the given map and returns a new map with the given key removed.\n// Returns the given map, if labelKey is empty.\nfunc CloneAndRemoveLabel(labels map[string]string, labelKey string) map[string]string {\n\tif labelKey == \"\" {\n\t\t// Don't need to add a label.\n\t\treturn labels\n\t}\n\t// Clone.\n\tnewLabels := map[string]string{}\n\tfor key, value := range labels {\n\t\tnewLabels[key] = value\n\t}\n\tdelete(newLabels, labelKey)\n\treturn newLabels\n}","line":{"from":39,"to":53}} {"id":100011761,"name":"AddLabel","signature":"func AddLabel(labels map[string]string, labelKey, labelValue string) map[string]string","file":"pkg/util/labels/labels.go","code":"// AddLabel returns a map with the given key and value added to the given map.\nfunc AddLabel(labels map[string]string, labelKey, labelValue string) map[string]string {\n\tif labelKey == \"\" {\n\t\t// Don't need to add a label.\n\t\treturn labels\n\t}\n\tif labels == nil {\n\t\tlabels = make(map[string]string)\n\t}\n\tlabels[labelKey] = labelValue\n\treturn labels\n}","line":{"from":55,"to":66}} {"id":100011762,"name":"CloneSelectorAndAddLabel","signature":"func CloneSelectorAndAddLabel(selector *metav1.LabelSelector, labelKey, labelValue string) *metav1.LabelSelector","file":"pkg/util/labels/labels.go","code":"// Clones the given selector and returns a new selector with the given key and value added.\n// Returns the given selector, if labelKey is empty.\nfunc CloneSelectorAndAddLabel(selector *metav1.LabelSelector, labelKey, labelValue string) *metav1.LabelSelector {\n\tif labelKey == \"\" {\n\t\t// Don't need to add a label.\n\t\treturn selector\n\t}\n\n\t// Clone.\n\tnewSelector := new(metav1.LabelSelector)\n\n\t// TODO(madhusudancs): Check if you can use deepCopy_extensions_LabelSelector here.\n\tnewSelector.MatchLabels = make(map[string]string)\n\tif selector.MatchLabels != nil {\n\t\tfor key, val := range selector.MatchLabels {\n\t\t\tnewSelector.MatchLabels[key] = val\n\t\t}\n\t}\n\tnewSelector.MatchLabels[labelKey] = labelValue\n\n\tif selector.MatchExpressions != nil {\n\t\tnewMExps := make([]metav1.LabelSelectorRequirement, len(selector.MatchExpressions))\n\t\tfor i, me := range selector.MatchExpressions {\n\t\t\tnewMExps[i].Key = me.Key\n\t\t\tnewMExps[i].Operator = me.Operator\n\t\t\tif me.Values != nil {\n\t\t\t\tnewMExps[i].Values = make([]string, len(me.Values))\n\t\t\t\tcopy(newMExps[i].Values, me.Values)\n\t\t\t} else {\n\t\t\t\tnewMExps[i].Values = nil\n\t\t\t}\n\t\t}\n\t\tnewSelector.MatchExpressions = newMExps\n\t} else {\n\t\tnewSelector.MatchExpressions = nil\n\t}\n\n\treturn newSelector\n}","line":{"from":68,"to":106}} {"id":100011763,"name":"AddLabelToSelector","signature":"func AddLabelToSelector(selector *metav1.LabelSelector, labelKey, labelValue string) *metav1.LabelSelector","file":"pkg/util/labels/labels.go","code":"// AddLabelToSelector returns a selector with the given key and value added to the given selector's MatchLabels.\nfunc AddLabelToSelector(selector *metav1.LabelSelector, labelKey, labelValue string) *metav1.LabelSelector {\n\tif labelKey == \"\" {\n\t\t// Don't need to add a label.\n\t\treturn selector\n\t}\n\tif selector.MatchLabels == nil {\n\t\tselector.MatchLabels = make(map[string]string)\n\t}\n\tselector.MatchLabels[labelKey] = labelValue\n\treturn selector\n}","line":{"from":108,"to":119}} {"id":100011764,"name":"SelectorHasLabel","signature":"func SelectorHasLabel(selector *metav1.LabelSelector, labelKey string) bool","file":"pkg/util/labels/labels.go","code":"// SelectorHasLabel checks if the given selector contains the given label key in its MatchLabels\nfunc SelectorHasLabel(selector *metav1.LabelSelector, labelKey string) bool {\n\treturn len(selector.MatchLabels[labelKey]) \u003e 0\n}","line":{"from":121,"to":124}} {"id":100011765,"name":"Error","signature":"func (e *NoMatchError) Error() string","file":"pkg/util/node/node.go","code":"// Error is the implementation of the conventional interface for\n// representing an error condition, with the nil value representing no error.\nfunc (e *NoMatchError) Error() string {\n\treturn fmt.Sprintf(\"no preferred addresses found; known addresses: %v\", e.addresses)\n}","line":{"from":48,"to":52}} {"id":100011766,"name":"GetPreferredNodeAddress","signature":"func GetPreferredNodeAddress(node *v1.Node, preferredAddressTypes []v1.NodeAddressType) (string, error)","file":"pkg/util/node/node.go","code":"// GetPreferredNodeAddress returns the address of the provided node, using the provided preference order.\n// If none of the preferred address types are found, an error is returned.\nfunc GetPreferredNodeAddress(node *v1.Node, preferredAddressTypes []v1.NodeAddressType) (string, error) {\n\tfor _, addressType := range preferredAddressTypes {\n\t\tfor _, address := range node.Status.Addresses {\n\t\t\tif address.Type == addressType {\n\t\t\t\treturn address.Address, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", \u0026NoMatchError{addresses: node.Status.Addresses}\n}","line":{"from":54,"to":65}} {"id":100011767,"name":"GetNodeHostIPs","signature":"func GetNodeHostIPs(node *v1.Node) ([]net.IP, error)","file":"pkg/util/node/node.go","code":"// GetNodeHostIPs returns the provided node's IP(s); either a single \"primary IP\" for the\n// node in a single-stack cluster, or a dual-stack pair of IPs in a dual-stack cluster\n// (for nodes that actually have dual-stack IPs). Among other things, the IPs returned\n// from this function are used as the `.status.PodIPs` values for host-network pods on the\n// node, and the first IP is used as the `.status.HostIP` for all pods on the node.\nfunc GetNodeHostIPs(node *v1.Node) ([]net.IP, error) {\n\t// Re-sort the addresses with InternalIPs first and then ExternalIPs\n\tallIPs := make([]net.IP, 0, len(node.Status.Addresses))\n\tfor _, addr := range node.Status.Addresses {\n\t\tif addr.Type == v1.NodeInternalIP {\n\t\t\tip := netutils.ParseIPSloppy(addr.Address)\n\t\t\tif ip != nil {\n\t\t\t\tallIPs = append(allIPs, ip)\n\t\t\t}\n\t\t}\n\t}\n\tfor _, addr := range node.Status.Addresses {\n\t\tif addr.Type == v1.NodeExternalIP {\n\t\t\tip := netutils.ParseIPSloppy(addr.Address)\n\t\t\tif ip != nil {\n\t\t\t\tallIPs = append(allIPs, ip)\n\t\t\t}\n\t\t}\n\t}\n\tif len(allIPs) == 0 {\n\t\treturn nil, fmt.Errorf(\"host IP unknown; known addresses: %v\", node.Status.Addresses)\n\t}\n\n\tnodeIPs := []net.IP{allIPs[0]}\n\tfor _, ip := range allIPs {\n\t\tif netutils.IsIPv6(ip) != netutils.IsIPv6(nodeIPs[0]) {\n\t\t\tnodeIPs = append(nodeIPs, ip)\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn nodeIPs, nil\n}","line":{"from":67,"to":104}} {"id":100011768,"name":"GetNodeHostIP","signature":"func GetNodeHostIP(node *v1.Node) (net.IP, error)","file":"pkg/util/node/node.go","code":"// GetNodeHostIP returns the provided node's \"primary\" IP; see GetNodeHostIPs for more details\nfunc GetNodeHostIP(node *v1.Node) (net.IP, error) {\n\tips, err := GetNodeHostIPs(node)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// GetNodeHostIPs always returns at least one IP if it didn't return an error\n\treturn ips[0], nil\n}","line":{"from":106,"to":114}} {"id":100011769,"name":"GetNodeIP","signature":"func GetNodeIP(client clientset.Interface, name string) net.IP","file":"pkg/util/node/node.go","code":"// GetNodeIP returns an IP (as with GetNodeHostIP) for the node with the provided name.\n// If required, it will wait for the node to be created.\nfunc GetNodeIP(client clientset.Interface, name string) net.IP {\n\tvar nodeIP net.IP\n\tbackoff := wait.Backoff{\n\t\tSteps: 6,\n\t\tDuration: 1 * time.Second,\n\t\tFactor: 2.0,\n\t\tJitter: 0.2,\n\t}\n\n\terr := wait.ExponentialBackoff(backoff, func() (bool, error) {\n\t\tnode, err := client.CoreV1().Nodes().Get(context.TODO(), name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to retrieve node info: %v\", err)\n\t\t\treturn false, nil\n\t\t}\n\t\tnodeIP, err = GetNodeHostIP(node)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to retrieve node IP: %v\", err)\n\t\t\treturn false, err\n\t\t}\n\t\treturn true, nil\n\t})\n\tif err == nil {\n\t\tklog.Infof(\"Successfully retrieved node IP: %v\", nodeIP)\n\t}\n\treturn nodeIP\n}","line":{"from":116,"to":144}} {"id":100011770,"name":"IsNodeReady","signature":"func IsNodeReady(node *v1.Node) bool","file":"pkg/util/node/node.go","code":"// IsNodeReady returns true if a node is ready; false otherwise.\nfunc IsNodeReady(node *v1.Node) bool {\n\tfor _, c := range node.Status.Conditions {\n\t\tif c.Type == v1.NodeReady {\n\t\t\treturn c.Status == v1.ConditionTrue\n\t\t}\n\t}\n\treturn false\n}","line":{"from":146,"to":154}} {"id":100011771,"name":"NewOOMAdjuster","signature":"func NewOOMAdjuster() *OOMAdjuster","file":"pkg/util/oom/oom_linux.go","code":"func NewOOMAdjuster() *OOMAdjuster {\n\toomAdjuster := \u0026OOMAdjuster{\n\t\tpidLister: getPids,\n\t\tApplyOOMScoreAdj: applyOOMScoreAdj,\n\t}\n\toomAdjuster.ApplyOOMScoreAdjContainer = oomAdjuster.applyOOMScoreAdjContainer\n\treturn oomAdjuster\n}","line":{"from":35,"to":42}} {"id":100011772,"name":"getPids","signature":"func getPids(cgroupName string) ([]int, error)","file":"pkg/util/oom/oom_linux.go","code":"func getPids(cgroupName string) ([]int, error) {\n\treturn cmutil.GetPids(filepath.Join(\"/\", cgroupName))\n}","line":{"from":44,"to":46}} {"id":100011773,"name":"applyOOMScoreAdj","signature":"func applyOOMScoreAdj(pid int, oomScoreAdj int) error","file":"pkg/util/oom/oom_linux.go","code":"// Writes 'value' to /proc/\u003cpid\u003e/oom_score_adj. PID = 0 means self\n// Returns os.ErrNotExist if the `pid` does not exist.\nfunc applyOOMScoreAdj(pid int, oomScoreAdj int) error {\n\tif pid \u003c 0 {\n\t\treturn fmt.Errorf(\"invalid PID %d specified for oom_score_adj\", pid)\n\t}\n\n\tvar pidStr string\n\tif pid == 0 {\n\t\tpidStr = \"self\"\n\t} else {\n\t\tpidStr = strconv.Itoa(pid)\n\t}\n\n\tmaxTries := 2\n\toomScoreAdjPath := path.Join(\"/proc\", pidStr, \"oom_score_adj\")\n\tvalue := strconv.Itoa(oomScoreAdj)\n\tklog.V(4).Infof(\"attempting to set %q to %q\", oomScoreAdjPath, value)\n\tvar err error\n\tfor i := 0; i \u003c maxTries; i++ {\n\t\terr = os.WriteFile(oomScoreAdjPath, []byte(value), 0700)\n\t\tif err != nil {\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\tklog.V(2).Infof(\"%q does not exist\", oomScoreAdjPath)\n\t\t\t\treturn os.ErrNotExist\n\t\t\t}\n\n\t\t\tklog.V(3).Info(err)\n\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t\tcontinue\n\t\t}\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\tklog.V(2).Infof(\"failed to set %q to %q: %v\", oomScoreAdjPath, value, err)\n\t}\n\treturn err\n}","line":{"from":48,"to":85}} {"id":100011774,"name":"applyOOMScoreAdjContainer","signature":"func (oomAdjuster *OOMAdjuster) applyOOMScoreAdjContainer(cgroupName string, oomScoreAdj, maxTries int) error","file":"pkg/util/oom/oom_linux.go","code":"// Writes 'value' to /proc/\u003cpid\u003e/oom_score_adj for all processes in cgroup cgroupName.\n// Keeps trying to write until the process list of the cgroup stabilizes, or until maxTries tries.\nfunc (oomAdjuster *OOMAdjuster) applyOOMScoreAdjContainer(cgroupName string, oomScoreAdj, maxTries int) error {\n\tadjustedProcessSet := make(map[int]bool)\n\tfor i := 0; i \u003c maxTries; i++ {\n\t\tcontinueAdjusting := false\n\t\tpidList, err := oomAdjuster.pidLister(cgroupName)\n\t\tif err != nil {\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\t// Nothing to do since the container doesn't exist anymore.\n\t\t\t\treturn os.ErrNotExist\n\t\t\t}\n\t\t\tcontinueAdjusting = true\n\t\t\tklog.V(10).Infof(\"Error getting process list for cgroup %s: %+v\", cgroupName, err)\n\t\t} else if len(pidList) == 0 {\n\t\t\tklog.V(10).Infof(\"Pid list is empty\")\n\t\t\tcontinueAdjusting = true\n\t\t} else {\n\t\t\tfor _, pid := range pidList {\n\t\t\t\tif !adjustedProcessSet[pid] {\n\t\t\t\t\tklog.V(10).Infof(\"pid %d needs to be set\", pid)\n\t\t\t\t\tif err = oomAdjuster.ApplyOOMScoreAdj(pid, oomScoreAdj); err == nil {\n\t\t\t\t\t\tadjustedProcessSet[pid] = true\n\t\t\t\t\t} else if err == os.ErrNotExist {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else {\n\t\t\t\t\t\tklog.V(10).Infof(\"cannot adjust oom score for pid %d - %v\", pid, err)\n\t\t\t\t\t\tcontinueAdjusting = true\n\t\t\t\t\t}\n\t\t\t\t\t// Processes can come and go while we try to apply oom score adjust value. So ignore errors here.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif !continueAdjusting {\n\t\t\treturn nil\n\t\t}\n\t\t// There's a slight race. A process might have forked just before we write its OOM score adjust.\n\t\t// The fork might copy the parent process's old OOM score, then this function might execute and\n\t\t// update the parent's OOM score, but the forked process id might not be reflected in cgroup.procs\n\t\t// for a short amount of time. So this function might return without changing the forked process's\n\t\t// OOM score. Very unlikely race, so ignoring this for now.\n\t}\n\treturn fmt.Errorf(\"exceeded maxTries, some processes might not have desired OOM score\")\n}","line":{"from":87,"to":130}} {"id":100011775,"name":"NewOOMAdjuster","signature":"func NewOOMAdjuster() *OOMAdjuster","file":"pkg/util/oom/oom_unsupported.go","code":"func NewOOMAdjuster() *OOMAdjuster {\n\treturn \u0026OOMAdjuster{\n\t\tApplyOOMScoreAdj: unsupportedApplyOOMScoreAdj,\n\t\tApplyOOMScoreAdjContainer: unsupportedApplyOOMScoreAdjContainer,\n\t}\n}","line":{"from":28,"to":33}} {"id":100011776,"name":"unsupportedApplyOOMScoreAdj","signature":"func unsupportedApplyOOMScoreAdj(pid int, oomScoreAdj int) error","file":"pkg/util/oom/oom_unsupported.go","code":"func unsupportedApplyOOMScoreAdj(pid int, oomScoreAdj int) error {\n\treturn unsupportedErr\n}","line":{"from":35,"to":37}} {"id":100011777,"name":"unsupportedApplyOOMScoreAdjContainer","signature":"func unsupportedApplyOOMScoreAdjContainer(cgroupName string, oomScoreAdj, maxTries int) error","file":"pkg/util/oom/oom_unsupported.go","code":"func unsupportedApplyOOMScoreAdjContainer(cgroupName string, oomScoreAdj, maxTries int) error {\n\treturn unsupportedErr\n}","line":{"from":39,"to":41}} {"id":100011778,"name":"ParseImageName","signature":"func ParseImageName(image string) (string, string, string, error)","file":"pkg/util/parsers/parsers.go","code":"// ParseImageName parses a docker image string into three parts: repo, tag and digest.\n// If both tag and digest are empty, a default image tag will be returned.\nfunc ParseImageName(image string) (string, string, string, error) {\n\tnamed, err := dockerref.ParseNormalizedNamed(image)\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", fmt.Errorf(\"couldn't parse image name: %v\", err)\n\t}\n\n\trepoToPull := named.Name()\n\tvar tag, digest string\n\n\ttagged, ok := named.(dockerref.Tagged)\n\tif ok {\n\t\ttag = tagged.Tag()\n\t}\n\n\tdigested, ok := named.(dockerref.Digested)\n\tif ok {\n\t\tdigest = digested.Digest().String()\n\t}\n\t// If no tag was specified, use the default \"latest\".\n\tif len(tag) == 0 \u0026\u0026 len(digest) == 0 {\n\t\ttag = \"latest\"\n\t}\n\treturn repoToPull, tag, digest, nil\n}","line":{"from":29,"to":54}} {"id":100011779,"name":"PatchPodStatus","signature":"func PatchPodStatus(ctx context.Context, c clientset.Interface, namespace, name string, uid types.UID, oldPodStatus, newPodStatus v1.PodStatus) (*v1.Pod, []byte, bool, error)","file":"pkg/util/pod/pod.go","code":"// PatchPodStatus patches pod status. It returns true and avoids an update if the patch contains no changes.\nfunc PatchPodStatus(ctx context.Context, c clientset.Interface, namespace, name string, uid types.UID, oldPodStatus, newPodStatus v1.PodStatus) (*v1.Pod, []byte, bool, error) {\n\tpatchBytes, unchanged, err := preparePatchBytesForPodStatus(namespace, name, uid, oldPodStatus, newPodStatus)\n\tif err != nil {\n\t\treturn nil, nil, false, err\n\t}\n\tif unchanged {\n\t\treturn nil, patchBytes, true, nil\n\t}\n\n\tupdatedPod, err := c.CoreV1().Pods(namespace).Patch(ctx, name, types.StrategicMergePatchType, patchBytes, metav1.PatchOptions{}, \"status\")\n\tif err != nil {\n\t\treturn nil, nil, false, fmt.Errorf(\"failed to patch status %q for pod %q/%q: %v\", patchBytes, namespace, name, err)\n\t}\n\treturn updatedPod, patchBytes, false, nil\n}","line":{"from":33,"to":48}} {"id":100011780,"name":"preparePatchBytesForPodStatus","signature":"func preparePatchBytesForPodStatus(namespace, name string, uid types.UID, oldPodStatus, newPodStatus v1.PodStatus) ([]byte, bool, error)","file":"pkg/util/pod/pod.go","code":"func preparePatchBytesForPodStatus(namespace, name string, uid types.UID, oldPodStatus, newPodStatus v1.PodStatus) ([]byte, bool, error) {\n\toldData, err := json.Marshal(v1.Pod{\n\t\tStatus: oldPodStatus,\n\t})\n\tif err != nil {\n\t\treturn nil, false, fmt.Errorf(\"failed to Marshal oldData for pod %q/%q: %v\", namespace, name, err)\n\t}\n\n\tnewData, err := json.Marshal(v1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{UID: uid}, // only put the uid in the new object to ensure it appears in the patch as a precondition\n\t\tStatus: newPodStatus,\n\t})\n\tif err != nil {\n\t\treturn nil, false, fmt.Errorf(\"failed to Marshal newData for pod %q/%q: %v\", namespace, name, err)\n\t}\n\n\tpatchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, v1.Pod{})\n\tif err != nil {\n\t\treturn nil, false, fmt.Errorf(\"failed to CreateTwoWayMergePatch for pod %q/%q: %v\", namespace, name, err)\n\t}\n\treturn patchBytes, bytes.Equal(patchBytes, []byte(fmt.Sprintf(`{\"metadata\":{\"uid\":%q}}`, uid))), nil\n}","line":{"from":50,"to":71}} {"id":100011781,"name":"ReplaceOrAppendPodCondition","signature":"func ReplaceOrAppendPodCondition(conditions []v1.PodCondition, condition *v1.PodCondition) []v1.PodCondition","file":"pkg/util/pod/pod.go","code":"// ReplaceOrAppendPodCondition replaces the first pod condition with equal type or appends if there is none\nfunc ReplaceOrAppendPodCondition(conditions []v1.PodCondition, condition *v1.PodCondition) []v1.PodCondition {\n\tif i, _ := podutil.GetPodConditionFromList(conditions, condition.Type); i \u003e= 0 {\n\t\tconditions[i] = *condition\n\t} else {\n\t\tconditions = append(conditions, *condition)\n\t}\n\treturn conditions\n}","line":{"from":73,"to":81}} {"id":100011782,"name":"containerNameFromProcCgroup","signature":"func containerNameFromProcCgroup(content string) (string, error)","file":"pkg/util/procfs/procfs_linux.go","code":"func containerNameFromProcCgroup(content string) (string, error) {\n\tlines := strings.Split(content, \"\\n\")\n\tfor _, line := range lines {\n\t\tentries := strings.SplitN(line, \":\", 3)\n\t\tif len(entries) == 3 \u0026\u0026 entries[1] == \"devices\" {\n\t\t\treturn strings.TrimSpace(entries[2]), nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"could not find devices cgroup location\")\n}","line":{"from":42,"to":51}} {"id":100011783,"name":"GetFullContainerName","signature":"func (pfs *ProcFS) GetFullContainerName(pid int) (string, error)","file":"pkg/util/procfs/procfs_linux.go","code":"// GetFullContainerName gets the container name given the root process id of the container.\n// E.g. if the devices cgroup for the container is stored in /sys/fs/cgroup/devices/docker/nginx,\n// return docker/nginx. Assumes that the process is part of exactly one cgroup hierarchy.\nfunc (pfs *ProcFS) GetFullContainerName(pid int) (string, error) {\n\tfilePath := path.Join(\"/proc\", strconv.Itoa(pid), \"cgroup\")\n\tcontent, err := os.ReadFile(filePath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn \"\", os.ErrNotExist\n\t\t}\n\t\treturn \"\", err\n\t}\n\treturn containerNameFromProcCgroup(string(content))\n}","line":{"from":53,"to":66}} {"id":100011784,"name":"PKill","signature":"func PKill(name string, sig syscall.Signal) error","file":"pkg/util/procfs/procfs_linux.go","code":"// PKill finds process(es) using a regular expression and send a specified\n// signal to each process.\nfunc PKill(name string, sig syscall.Signal) error {\n\tif len(name) == 0 {\n\t\treturn fmt.Errorf(\"name should not be empty\")\n\t}\n\tre, err := regexp.Compile(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpids := getPids(re)\n\tif len(pids) == 0 {\n\t\treturn fmt.Errorf(\"unable to fetch pids for process name : %q\", name)\n\t}\n\terrList := []error{}\n\tfor _, pid := range pids {\n\t\tif err = syscall.Kill(pid, sig); err != nil {\n\t\t\terrList = append(errList, err)\n\t\t}\n\t}\n\treturn utilerrors.NewAggregate(errList)\n}","line":{"from":68,"to":89}} {"id":100011785,"name":"PidOf","signature":"func PidOf(name string) ([]int, error)","file":"pkg/util/procfs/procfs_linux.go","code":"// PidOf finds process(es) with a specified name (regexp match)\n// and return their pid(s).\nfunc PidOf(name string) ([]int, error) {\n\tif len(name) == 0 {\n\t\treturn []int{}, fmt.Errorf(\"name should not be empty\")\n\t}\n\tre, err := regexp.Compile(\"(^|/)\" + name + \"$\")\n\tif err != nil {\n\t\treturn []int{}, err\n\t}\n\treturn getPids(re), nil\n}","line":{"from":91,"to":102}} {"id":100011786,"name":"getPids","signature":"func getPids(re *regexp.Regexp) []int","file":"pkg/util/procfs/procfs_linux.go","code":"func getPids(re *regexp.Regexp) []int {\n\tpids := []int{}\n\n\tdirFD, err := os.Open(\"/proc\")\n\tif err != nil {\n\t\treturn nil\n\t}\n\tdefer dirFD.Close()\n\n\tfor {\n\t\t// Read a small number at a time in case there are many entries, we don't want to\n\t\t// allocate a lot here.\n\t\tls, err := dirFD.Readdir(10)\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tfor _, entry := range ls {\n\t\t\tif !entry.IsDir() {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// If the directory is not a number (i.e. not a PID), skip it\n\t\t\tpid, err := strconv.Atoi(entry.Name())\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcmdline, err := os.ReadFile(filepath.Join(\"/proc\", entry.Name(), \"cmdline\"))\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Error reading file %s: %+v\", filepath.Join(\"/proc\", entry.Name(), \"cmdline\"), err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// The bytes we read have '\\0' as a separator for the command line\n\t\t\tparts := bytes.SplitN(cmdline, []byte{0}, 2)\n\t\t\tif len(parts) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Split the command line itself we are interested in just the first part\n\t\t\texe := strings.FieldsFunc(string(parts[0]), func(c rune) bool {\n\t\t\t\treturn unicode.IsSpace(c) || c == ':'\n\t\t\t})\n\t\t\tif len(exe) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Check if the name of the executable is what we are looking for\n\t\t\tif re.MatchString(exe[0]) {\n\t\t\t\t// Grab the PID from the directory path\n\t\t\t\tpids = append(pids, pid)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn pids\n}","line":{"from":104,"to":162}} {"id":100011787,"name":"NewProcFS","signature":"func NewProcFS() ProcFSInterface","file":"pkg/util/procfs/procfs_unsupported.go","code":"func NewProcFS() ProcFSInterface {\n\treturn \u0026ProcFS{}\n}","line":{"from":29,"to":31}} {"id":100011788,"name":"GetFullContainerName","signature":"func (pfs *ProcFS) GetFullContainerName(pid int) (string, error)","file":"pkg/util/procfs/procfs_unsupported.go","code":"// GetFullContainerName gets the container name given the root process id of the container.\nfunc (pfs *ProcFS) GetFullContainerName(pid int) (string, error) {\n\treturn \"\", fmt.Errorf(\"GetFullContainerName is unsupported in this build\")\n}","line":{"from":33,"to":36}} {"id":100011789,"name":"PKill","signature":"func PKill(name string, sig syscall.Signal) error","file":"pkg/util/procfs/procfs_unsupported.go","code":"// Find process(es) using a regular expression and send a specified\n// signal to each process\nfunc PKill(name string, sig syscall.Signal) error {\n\treturn fmt.Errorf(\"PKill is unsupported in this build\")\n}","line":{"from":38,"to":42}} {"id":100011790,"name":"PidOf","signature":"func PidOf(name string) ([]int, error)","file":"pkg/util/procfs/procfs_unsupported.go","code":"// Find process(es) with a specified name (exact match)\n// and return their pid(s)\nfunc PidOf(name string) ([]int, error) {\n\treturn []int{}, fmt.Errorf(\"PidOf is unsupported in this build\")\n}","line":{"from":44,"to":48}} {"id":100011791,"name":"RemoveAllOneFilesystemCommon","signature":"func RemoveAllOneFilesystemCommon(mounter mount.Interface, path string, remove func(string) error) error","file":"pkg/util/removeall/removeall.go","code":"// RemoveAllOneFilesystemCommon removes the path and any children it contains,\n// using the provided remove function. It removes everything it can but returns\n// the first error it encounters. If the path does not exist, RemoveAll\n// returns nil (no error).\n// It makes sure it does not cross mount boundary, i.e. it does *not* remove\n// files from another filesystems. Like 'rm -rf --one-file-system'.\n// It is copied from RemoveAll() sources, with IsLikelyNotMountPoint\nfunc RemoveAllOneFilesystemCommon(mounter mount.Interface, path string, remove func(string) error) error {\n\t// Simple case: if Remove works, we're done.\n\terr := remove(path)\n\tif err == nil || os.IsNotExist(err) {\n\t\treturn nil\n\t}\n\n\t// Otherwise, is this a directory we need to recurse into?\n\tdir, serr := os.Lstat(path)\n\tif serr != nil {\n\t\tif serr, ok := serr.(*os.PathError); ok \u0026\u0026 (os.IsNotExist(serr.Err) || serr.Err == syscall.ENOTDIR) {\n\t\t\treturn nil\n\t\t}\n\t\treturn serr\n\t}\n\tif !dir.IsDir() {\n\t\t// Not a directory; return the error from remove.\n\t\treturn err\n\t}\n\n\t// Directory.\n\tisNotMount, err := mounter.IsLikelyNotMountPoint(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !isNotMount {\n\t\treturn fmt.Errorf(\"cannot delete directory %s: it is a mount point\", path)\n\t}\n\n\tfd, err := os.Open(path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\t// Race. It was deleted between the Lstat and Open.\n\t\t\t// Return nil per RemoveAll's docs.\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\t// Remove contents \u0026 return first error.\n\terr = nil\n\tfor {\n\t\tnames, err1 := fd.Readdirnames(100)\n\t\tfor _, name := range names {\n\t\t\terr1 := RemoveAllOneFilesystemCommon(mounter, path+string(os.PathSeparator)+name, remove)\n\t\t\tif err == nil {\n\t\t\t\terr = err1\n\t\t\t}\n\t\t}\n\t\tif err1 == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\t// If Readdirnames returned an error, use it.\n\t\tif err == nil {\n\t\t\terr = err1\n\t\t}\n\t\tif len(names) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Close directory, because windows won't remove opened directory.\n\tfd.Close()\n\n\t// Remove directory.\n\terr1 := remove(path)\n\tif err1 == nil || os.IsNotExist(err1) {\n\t\treturn nil\n\t}\n\tif err == nil {\n\t\terr = err1\n\t}\n\treturn err\n}","line":{"from":28,"to":108}} {"id":100011792,"name":"RemoveAllOneFilesystem","signature":"func RemoveAllOneFilesystem(mounter mount.Interface, path string) error","file":"pkg/util/removeall/removeall.go","code":"// RemoveAllOneFilesystem removes the path and any children it contains, using\n// the os.Remove function. It makes sure it does not cross mount boundaries,\n// i.e. it returns an error rather than remove files from another filesystem.\n// It removes everything it can but returns the first error it encounters.\n// If the path does not exist, it returns nil (no error).\nfunc RemoveAllOneFilesystem(mounter mount.Interface, path string) error {\n\treturn RemoveAllOneFilesystemCommon(mounter, path, os.Remove)\n}","line":{"from":110,"to":117}} {"id":100011793,"name":"RemoveDirsOneFilesystem","signature":"func RemoveDirsOneFilesystem(mounter mount.Interface, path string) error","file":"pkg/util/removeall/removeall.go","code":"// RemoveDirsOneFilesystem removes the path and any empty subdirectories it\n// contains, using the syscall.Rmdir function. Unlike RemoveAllOneFilesystem,\n// RemoveDirsOneFilesystem will remove only directories and returns an error if\n// it encounters any files in the directory tree. It makes sure it does not\n// cross mount boundaries, i.e. it returns an error rather than remove dirs\n// from another filesystem. It removes everything it can but returns the first\n// error it encounters. If the path does not exist, it returns nil (no error).\nfunc RemoveDirsOneFilesystem(mounter mount.Interface, path string) error {\n\treturn RemoveAllOneFilesystemCommon(mounter, path, syscall.Rmdir)\n}","line":{"from":119,"to":128}} {"id":100011794,"name":"SetNumFiles","signature":"func SetNumFiles(maxOpenFiles uint64) error","file":"pkg/util/rlimit/rlimit_linux.go","code":"// SetNumFiles sets the linux rlimit for the maximum open files.\nfunc SetNumFiles(maxOpenFiles uint64) error {\n\treturn unix.Setrlimit(unix.RLIMIT_NOFILE, \u0026unix.Rlimit{Max: maxOpenFiles, Cur: maxOpenFiles})\n}","line":{"from":26,"to":29}} {"id":100011795,"name":"SetNumFiles","signature":"func SetNumFiles(maxOpenFiles uint64) error","file":"pkg/util/rlimit/rlimit_unsupported.go","code":"// SetNumFiles sets the rlimit for the maximum open files.\nfunc SetNumFiles(maxOpenFiles uint64) error {\n\treturn errors.New(\"SetRLimit unsupported in this platform\")\n}","line":{"from":26,"to":29}} {"id":100011796,"name":"CopyStrings","signature":"func CopyStrings(s []string) []string","file":"pkg/util/slice/slice.go","code":"// CopyStrings copies the contents of the specified string slice\n// into a new slice.\nfunc CopyStrings(s []string) []string {\n\tif s == nil {\n\t\treturn nil\n\t}\n\tc := make([]string, len(s))\n\tcopy(c, s)\n\treturn c\n}","line":{"from":24,"to":33}} {"id":100011797,"name":"SortStrings","signature":"func SortStrings(s []string) []string","file":"pkg/util/slice/slice.go","code":"// SortStrings sorts the specified string slice in place. It returns the same\n// slice that was provided in order to facilitate method chaining.\nfunc SortStrings(s []string) []string {\n\tsort.Strings(s)\n\treturn s\n}","line":{"from":35,"to":40}} {"id":100011798,"name":"ContainsString","signature":"func ContainsString(slice []string, s string, modifier func(s string) string) bool","file":"pkg/util/slice/slice.go","code":"// ContainsString checks if a given slice of strings contains the provided string.\n// If a modifier func is provided, it is called with the slice item before the comparation.\nfunc ContainsString(slice []string, s string, modifier func(s string) string) bool {\n\tfor _, item := range slice {\n\t\tif item == s {\n\t\t\treturn true\n\t\t}\n\t\tif modifier != nil \u0026\u0026 modifier(item) == s {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":42,"to":54}} {"id":100011799,"name":"RemoveString","signature":"func RemoveString(slice []string, s string, modifier func(s string) string) []string","file":"pkg/util/slice/slice.go","code":"// RemoveString returns a newly created []string that contains all items from slice that\n// are not equal to s and modifier(s) in case modifier func is provided.\nfunc RemoveString(slice []string, s string, modifier func(s string) string) []string {\n\tnewSlice := make([]string, 0)\n\tfor _, item := range slice {\n\t\tif item == s {\n\t\t\tcontinue\n\t\t}\n\t\tif modifier != nil \u0026\u0026 modifier(item) == s {\n\t\t\tcontinue\n\t\t}\n\t\tnewSlice = append(newSlice, item)\n\t}\n\tif len(newSlice) == 0 {\n\t\t// Sanitize for unit tests so we don't need to distinguish empty array\n\t\t// and nil.\n\t\tnewSlice = nil\n\t}\n\treturn newSlice\n}","line":{"from":56,"to":75}} {"id":100011800,"name":"ReadAtMost","signature":"func ReadAtMost(path string, max int64) ([]byte, bool, error)","file":"pkg/util/tail/tail.go","code":"// ReadAtMost reads at most max bytes from the end of the file identified by path or\n// returns an error. It returns true if the file was longer than max. It will\n// allocate up to max bytes.\nfunc ReadAtMost(path string, max int64) ([]byte, bool, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\tdefer f.Close()\n\tfi, err := f.Stat()\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\tsize := fi.Size()\n\tif size == 0 {\n\t\treturn nil, false, nil\n\t}\n\tif size \u003c max {\n\t\tmax = size\n\t}\n\toffset, err := f.Seek(-max, io.SeekEnd)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\tdata, err := io.ReadAll(f)\n\treturn data, offset \u003e 0, err\n}","line":{"from":35,"to":61}} {"id":100011801,"name":"FindTailLineStartIndex","signature":"func FindTailLineStartIndex(f io.ReadSeeker, n int64) (int64, error)","file":"pkg/util/tail/tail.go","code":"// FindTailLineStartIndex returns the start of last nth line.\n// * If n \u003c 0, return the beginning of the file.\n// * If n \u003e= 0, return the beginning of last nth line.\n// Notice that if the last line is incomplete (no end-of-line), it will not be counted\n// as one line.\nfunc FindTailLineStartIndex(f io.ReadSeeker, n int64) (int64, error) {\n\tif n \u003c 0 {\n\t\treturn 0, nil\n\t}\n\tsize, err := f.Seek(0, io.SeekEnd)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tvar left, cnt int64\n\tbuf := make([]byte, blockSize)\n\tfor right := size; right \u003e 0 \u0026\u0026 cnt \u003c= n; right -= blockSize {\n\t\tleft = right - blockSize\n\t\tif left \u003c 0 {\n\t\t\tleft = 0\n\t\t\tbuf = make([]byte, right)\n\t\t}\n\t\tif _, err := f.Seek(left, io.SeekStart); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tif _, err := f.Read(buf); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tcnt += int64(bytes.Count(buf, eol))\n\t}\n\tfor ; cnt \u003e n; cnt-- {\n\t\tidx := bytes.Index(buf, eol) + 1\n\t\tbuf = buf[idx:]\n\t\tleft += int64(idx)\n\t}\n\treturn left, nil\n}","line":{"from":63,"to":98}} {"id":100011802,"name":"parseTaint","signature":"func parseTaint(st string) (v1.Taint, error)","file":"pkg/util/taints/taints.go","code":"// parseTaint parses a taint from a string, whose form must be either\n// '\u003ckey\u003e=\u003cvalue\u003e:\u003ceffect\u003e', '\u003ckey\u003e:\u003ceffect\u003e', or '\u003ckey\u003e'.\nfunc parseTaint(st string) (v1.Taint, error) {\n\tvar taint v1.Taint\n\n\tvar key string\n\tvar value string\n\tvar effect v1.TaintEffect\n\n\tparts := strings.Split(st, \":\")\n\tswitch len(parts) {\n\tcase 1:\n\t\tkey = parts[0]\n\tcase 2:\n\t\teffect = v1.TaintEffect(parts[1])\n\t\tif err := validateTaintEffect(effect); err != nil {\n\t\t\treturn taint, err\n\t\t}\n\n\t\tpartsKV := strings.Split(parts[0], \"=\")\n\t\tif len(partsKV) \u003e 2 {\n\t\t\treturn taint, fmt.Errorf(\"invalid taint spec: %v\", st)\n\t\t}\n\t\tkey = partsKV[0]\n\t\tif len(partsKV) == 2 {\n\t\t\tvalue = partsKV[1]\n\t\t\tif errs := validation.IsValidLabelValue(value); len(errs) \u003e 0 {\n\t\t\t\treturn taint, fmt.Errorf(\"invalid taint spec: %v, %s\", st, strings.Join(errs, \"; \"))\n\t\t\t}\n\t\t}\n\tdefault:\n\t\treturn taint, fmt.Errorf(\"invalid taint spec: %v\", st)\n\t}\n\n\tif errs := validation.IsQualifiedName(key); len(errs) \u003e 0 {\n\t\treturn taint, fmt.Errorf(\"invalid taint spec: %v, %s\", st, strings.Join(errs, \"; \"))\n\t}\n\n\ttaint.Key = key\n\ttaint.Value = value\n\ttaint.Effect = effect\n\n\treturn taint, nil\n}","line":{"from":36,"to":79}} {"id":100011803,"name":"validateTaintEffect","signature":"func validateTaintEffect(effect v1.TaintEffect) error","file":"pkg/util/taints/taints.go","code":"func validateTaintEffect(effect v1.TaintEffect) error {\n\tif effect != v1.TaintEffectNoSchedule \u0026\u0026 effect != v1.TaintEffectPreferNoSchedule \u0026\u0026 effect != v1.TaintEffectNoExecute {\n\t\treturn fmt.Errorf(\"invalid taint effect: %v, unsupported taint effect\", effect)\n\t}\n\n\treturn nil\n}","line":{"from":81,"to":87}} {"id":100011804,"name":"ParseTaints","signature":"func ParseTaints(spec []string) ([]v1.Taint, []v1.Taint, error)","file":"pkg/util/taints/taints.go","code":"// ParseTaints takes a spec which is an array and creates slices for new taints to be added, taints to be deleted.\n// It also validates the spec. For example, the form `\u003ckey\u003e` may be used to remove a taint, but not to add one.\nfunc ParseTaints(spec []string) ([]v1.Taint, []v1.Taint, error) {\n\tvar taints, taintsToRemove []v1.Taint\n\tuniqueTaints := map[v1.TaintEffect]sets.String{}\n\n\tfor _, taintSpec := range spec {\n\t\tif strings.HasSuffix(taintSpec, \"-\") {\n\t\t\ttaintToRemove, err := parseTaint(strings.TrimSuffix(taintSpec, \"-\"))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\ttaintsToRemove = append(taintsToRemove, v1.Taint{Key: taintToRemove.Key, Effect: taintToRemove.Effect})\n\t\t} else {\n\t\t\tnewTaint, err := parseTaint(taintSpec)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\t// validate that the taint has an effect, which is required to add the taint\n\t\t\tif len(newTaint.Effect) == 0 {\n\t\t\t\treturn nil, nil, fmt.Errorf(\"invalid taint spec: %v\", taintSpec)\n\t\t\t}\n\t\t\t// validate if taint is unique by \u003ckey, effect\u003e\n\t\t\tif len(uniqueTaints[newTaint.Effect]) \u003e 0 \u0026\u0026 uniqueTaints[newTaint.Effect].Has(newTaint.Key) {\n\t\t\t\treturn nil, nil, fmt.Errorf(\"duplicated taints with the same key and effect: %v\", newTaint)\n\t\t\t}\n\t\t\t// add taint to existingTaints for uniqueness check\n\t\t\tif len(uniqueTaints[newTaint.Effect]) == 0 {\n\t\t\t\tuniqueTaints[newTaint.Effect] = sets.String{}\n\t\t\t}\n\t\t\tuniqueTaints[newTaint.Effect].Insert(newTaint.Key)\n\n\t\t\ttaints = append(taints, newTaint)\n\t\t}\n\t}\n\treturn taints, taintsToRemove, nil\n}","line":{"from":89,"to":125}} {"id":100011805,"name":"CheckIfTaintsAlreadyExists","signature":"func CheckIfTaintsAlreadyExists(oldTaints []v1.Taint, taints []v1.Taint) string","file":"pkg/util/taints/taints.go","code":"// CheckIfTaintsAlreadyExists checks if the node already has taints that we want to add and returns a string with taint keys.\nfunc CheckIfTaintsAlreadyExists(oldTaints []v1.Taint, taints []v1.Taint) string {\n\tvar existingTaintList = make([]string, 0)\n\tfor _, taint := range taints {\n\t\tfor _, oldTaint := range oldTaints {\n\t\t\tif taint.Key == oldTaint.Key \u0026\u0026 taint.Effect == oldTaint.Effect {\n\t\t\t\texistingTaintList = append(existingTaintList, taint.Key)\n\t\t\t}\n\t\t}\n\t}\n\treturn strings.Join(existingTaintList, \",\")\n}","line":{"from":127,"to":138}} {"id":100011806,"name":"DeleteTaintsByKey","signature":"func DeleteTaintsByKey(taints []v1.Taint, taintKey string) ([]v1.Taint, bool)","file":"pkg/util/taints/taints.go","code":"// DeleteTaintsByKey removes all the taints that have the same key to given taintKey\nfunc DeleteTaintsByKey(taints []v1.Taint, taintKey string) ([]v1.Taint, bool) {\n\tnewTaints := []v1.Taint{}\n\tdeleted := false\n\tfor i := range taints {\n\t\tif taintKey == taints[i].Key {\n\t\t\tdeleted = true\n\t\t\tcontinue\n\t\t}\n\t\tnewTaints = append(newTaints, taints[i])\n\t}\n\treturn newTaints, deleted\n}","line":{"from":140,"to":152}} {"id":100011807,"name":"DeleteTaint","signature":"func DeleteTaint(taints []v1.Taint, taintToDelete *v1.Taint) ([]v1.Taint, bool)","file":"pkg/util/taints/taints.go","code":"// DeleteTaint removes all the taints that have the same key and effect to given taintToDelete.\nfunc DeleteTaint(taints []v1.Taint, taintToDelete *v1.Taint) ([]v1.Taint, bool) {\n\tnewTaints := []v1.Taint{}\n\tdeleted := false\n\tfor i := range taints {\n\t\tif taintToDelete.MatchTaint(\u0026taints[i]) {\n\t\t\tdeleted = true\n\t\t\tcontinue\n\t\t}\n\t\tnewTaints = append(newTaints, taints[i])\n\t}\n\treturn newTaints, deleted\n}","line":{"from":154,"to":166}} {"id":100011808,"name":"RemoveTaint","signature":"func RemoveTaint(node *v1.Node, taint *v1.Taint) (*v1.Node, bool, error)","file":"pkg/util/taints/taints.go","code":"// RemoveTaint tries to remove a taint from annotations list. Returns a new copy of updated Node and true if something was updated\n// false otherwise.\nfunc RemoveTaint(node *v1.Node, taint *v1.Taint) (*v1.Node, bool, error) {\n\tnewNode := node.DeepCopy()\n\tnodeTaints := newNode.Spec.Taints\n\tif len(nodeTaints) == 0 {\n\t\treturn newNode, false, nil\n\t}\n\n\tif !TaintExists(nodeTaints, taint) {\n\t\treturn newNode, false, nil\n\t}\n\n\tnewTaints, _ := DeleteTaint(nodeTaints, taint)\n\tnewNode.Spec.Taints = newTaints\n\treturn newNode, true, nil\n}","line":{"from":168,"to":184}} {"id":100011809,"name":"AddOrUpdateTaint","signature":"func AddOrUpdateTaint(node *v1.Node, taint *v1.Taint) (*v1.Node, bool, error)","file":"pkg/util/taints/taints.go","code":"// AddOrUpdateTaint tries to add a taint to annotations list. Returns a new copy of updated Node and true if something was updated\n// false otherwise.\nfunc AddOrUpdateTaint(node *v1.Node, taint *v1.Taint) (*v1.Node, bool, error) {\n\tnewNode := node.DeepCopy()\n\tnodeTaints := newNode.Spec.Taints\n\n\tvar newTaints []v1.Taint\n\tupdated := false\n\tfor i := range nodeTaints {\n\t\tif taint.MatchTaint(\u0026nodeTaints[i]) {\n\t\t\tif helper.Semantic.DeepEqual(*taint, nodeTaints[i]) {\n\t\t\t\treturn newNode, false, nil\n\t\t\t}\n\t\t\tnewTaints = append(newTaints, *taint)\n\t\t\tupdated = true\n\t\t\tcontinue\n\t\t}\n\n\t\tnewTaints = append(newTaints, nodeTaints[i])\n\t}\n\n\tif !updated {\n\t\tnewTaints = append(newTaints, *taint)\n\t}\n\n\tnewNode.Spec.Taints = newTaints\n\treturn newNode, true, nil\n}","line":{"from":186,"to":213}} {"id":100011810,"name":"TaintExists","signature":"func TaintExists(taints []v1.Taint, taintToFind *v1.Taint) bool","file":"pkg/util/taints/taints.go","code":"// TaintExists checks if the given taint exists in list of taints. Returns true if exists false otherwise.\nfunc TaintExists(taints []v1.Taint, taintToFind *v1.Taint) bool {\n\tfor _, taint := range taints {\n\t\tif taint.MatchTaint(taintToFind) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":215,"to":223}} {"id":100011811,"name":"TaintKeyExists","signature":"func TaintKeyExists(taints []v1.Taint, taintKeyToMatch string) bool","file":"pkg/util/taints/taints.go","code":"// TaintKeyExists checks if the given taint key exists in list of taints. Returns true if exists false otherwise.\nfunc TaintKeyExists(taints []v1.Taint, taintKeyToMatch string) bool {\n\tfor _, taint := range taints {\n\t\tif taint.Key == taintKeyToMatch {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":225,"to":233}} {"id":100011812,"name":"TaintSetDiff","signature":"func TaintSetDiff(taintsNew, taintsOld []v1.Taint) (taintsToAdd []*v1.Taint, taintsToRemove []*v1.Taint)","file":"pkg/util/taints/taints.go","code":"// TaintSetDiff finds the difference between two taint slices and\n// returns all new and removed elements of the new slice relative to the old slice.\n// for example:\n// input: taintsNew=[a b] taintsOld=[a c]\n// output: taintsToAdd=[b] taintsToRemove=[c]\nfunc TaintSetDiff(taintsNew, taintsOld []v1.Taint) (taintsToAdd []*v1.Taint, taintsToRemove []*v1.Taint) {\n\tfor _, taint := range taintsNew {\n\t\tif !TaintExists(taintsOld, \u0026taint) {\n\t\t\tt := taint\n\t\t\ttaintsToAdd = append(taintsToAdd, \u0026t)\n\t\t}\n\t}\n\n\tfor _, taint := range taintsOld {\n\t\tif !TaintExists(taintsNew, \u0026taint) {\n\t\t\tt := taint\n\t\t\ttaintsToRemove = append(taintsToRemove, \u0026t)\n\t\t}\n\t}\n\n\treturn\n}","line":{"from":235,"to":256}} {"id":100011813,"name":"TaintSetFilter","signature":"func TaintSetFilter(taints []v1.Taint, fn func(*v1.Taint) bool) []v1.Taint","file":"pkg/util/taints/taints.go","code":"// TaintSetFilter filters from the taint slice according to the passed fn function to get the filtered taint slice.\nfunc TaintSetFilter(taints []v1.Taint, fn func(*v1.Taint) bool) []v1.Taint {\n\tres := []v1.Taint{}\n\n\tfor _, taint := range taints {\n\t\tif fn(\u0026taint) {\n\t\t\tres = append(res, taint)\n\t\t}\n\t}\n\n\treturn res\n}","line":{"from":258,"to":269}} {"id":100011814,"name":"CheckTaintValidation","signature":"func CheckTaintValidation(taint v1.Taint) error","file":"pkg/util/taints/taints.go","code":"// CheckTaintValidation checks if the given taint is valid.\n// Returns error if the given taint is invalid.\nfunc CheckTaintValidation(taint v1.Taint) error {\n\tif errs := validation.IsQualifiedName(taint.Key); len(errs) \u003e 0 {\n\t\treturn fmt.Errorf(\"invalid taint key: %s\", strings.Join(errs, \"; \"))\n\t}\n\tif taint.Value != \"\" {\n\t\tif errs := validation.IsValidLabelValue(taint.Value); len(errs) \u003e 0 {\n\t\t\treturn fmt.Errorf(\"invalid taint value: %s\", strings.Join(errs, \"; \"))\n\t\t}\n\t}\n\tif taint.Effect != \"\" {\n\t\tif err := validateTaintEffect(taint.Effect); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":271,"to":289}} {"id":100011815,"name":"VerifyAgainstWhitelist","signature":"func VerifyAgainstWhitelist(tolerations, whitelist []api.Toleration) bool","file":"pkg/util/tolerations/tolerations.go","code":"// VerifyAgainstWhitelist checks if the provided tolerations\n// satisfy the provided whitelist and returns true, otherwise returns false\nfunc VerifyAgainstWhitelist(tolerations, whitelist []api.Toleration) bool {\n\tif len(whitelist) == 0 || len(tolerations) == 0 {\n\t\treturn true\n\t}\n\nnext:\n\tfor _, t := range tolerations {\n\t\tfor _, w := range whitelist {\n\t\t\tif isSuperset(w, t) {\n\t\t\t\tcontinue next\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\treturn true\n}","line":{"from":25,"to":43}} {"id":100011816,"name":"MergeTolerations","signature":"func MergeTolerations(first, second []api.Toleration) []api.Toleration","file":"pkg/util/tolerations/tolerations.go","code":"// MergeTolerations merges two sets of tolerations into one. If one toleration is a superset of\n// another, only the superset is kept.\nfunc MergeTolerations(first, second []api.Toleration) []api.Toleration {\n\tall := append(first, second...)\n\tvar merged []api.Toleration\n\nnext:\n\tfor i, t := range all {\n\t\tfor _, t2 := range merged {\n\t\t\tif isSuperset(t2, t) {\n\t\t\t\tcontinue next // t is redundant; ignore it\n\t\t\t}\n\t\t}\n\t\tif i+1 \u003c len(all) {\n\t\t\tfor _, t2 := range all[i+1:] {\n\t\t\t\t// If the tolerations are equal, prefer the first.\n\t\t\t\tif !apiequality.Semantic.DeepEqual(\u0026t, \u0026t2) \u0026\u0026 isSuperset(t2, t) {\n\t\t\t\t\tcontinue next // t is redundant; ignore it\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tmerged = append(merged, t)\n\t}\n\n\treturn merged\n}","line":{"from":45,"to":70}} {"id":100011817,"name":"isSuperset","signature":"func isSuperset(ss, t api.Toleration) bool","file":"pkg/util/tolerations/tolerations.go","code":"// isSuperset checks whether ss tolerates a superset of t.\nfunc isSuperset(ss, t api.Toleration) bool {\n\tif apiequality.Semantic.DeepEqual(\u0026t, \u0026ss) {\n\t\treturn true\n\t}\n\n\tif t.Key != ss.Key \u0026\u0026\n\t\t// An empty key with Exists operator means match all keys \u0026 values.\n\t\t(ss.Key != \"\" || ss.Operator != api.TolerationOpExists) {\n\t\treturn false\n\t}\n\n\t// An empty effect means match all effects.\n\tif t.Effect != ss.Effect \u0026\u0026 ss.Effect != \"\" {\n\t\treturn false\n\t}\n\n\tif ss.Effect == api.TaintEffectNoExecute {\n\t\tif ss.TolerationSeconds != nil {\n\t\t\tif t.TolerationSeconds == nil ||\n\t\t\t\t*t.TolerationSeconds \u003e *ss.TolerationSeconds {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch ss.Operator {\n\tcase api.TolerationOpEqual, \"\": // empty operator means Equal\n\t\treturn t.Operator == api.TolerationOpEqual \u0026\u0026 t.Value == ss.Value\n\tcase api.TolerationOpExists:\n\t\treturn true\n\tdefault:\n\t\tklog.Errorf(\"Unknown toleration operator: %s\", ss.Operator)\n\t\treturn false\n\t}\n}","line":{"from":72,"to":107}} {"id":100011818,"name":"ProbeVolumePlugins","signature":"func ProbeVolumePlugins() []volume.VolumePlugin","file":"pkg/volume/azure_file/azure_file.go","code":"// ProbeVolumePlugins is the primary endpoint for volume plugins\nfunc ProbeVolumePlugins() []volume.VolumePlugin {\n\treturn []volume.VolumePlugin{\u0026azureFilePlugin{nil}}\n}","line":{"from":45,"to":48}} {"id":100011819,"name":"getPath","signature":"func getPath(uid types.UID, volName string, host volume.VolumeHost) string","file":"pkg/volume/azure_file/azure_file.go","code":"func getPath(uid types.UID, volName string, host volume.VolumeHost) string {\n\treturn host.GetPodVolumeDir(uid, utilstrings.EscapeQualifiedName(azureFilePluginName), volName)\n}","line":{"from":63,"to":65}} {"id":100011820,"name":"Init","signature":"func (plugin *azureFilePlugin) Init(host volume.VolumeHost) error","file":"pkg/volume/azure_file/azure_file.go","code":"func (plugin *azureFilePlugin) Init(host volume.VolumeHost) error {\n\tplugin.host = host\n\treturn nil\n}","line":{"from":67,"to":70}} {"id":100011821,"name":"GetPluginName","signature":"func (plugin *azureFilePlugin) GetPluginName() string","file":"pkg/volume/azure_file/azure_file.go","code":"func (plugin *azureFilePlugin) GetPluginName() string {\n\treturn azureFilePluginName\n}","line":{"from":72,"to":74}} {"id":100011822,"name":"GetVolumeName","signature":"func (plugin *azureFilePlugin) GetVolumeName(spec *volume.Spec) (string, error)","file":"pkg/volume/azure_file/azure_file.go","code":"func (plugin *azureFilePlugin) GetVolumeName(spec *volume.Spec) (string, error) {\n\tshare, _, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn share, nil\n}","line":{"from":76,"to":83}} {"id":100011823,"name":"CanSupport","signature":"func (plugin *azureFilePlugin) CanSupport(spec *volume.Spec) bool","file":"pkg/volume/azure_file/azure_file.go","code":"func (plugin *azureFilePlugin) CanSupport(spec *volume.Spec) bool {\n\t//TODO: check if mount.cifs is there\n\treturn (spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.AzureFile != nil) ||\n\t\t(spec.Volume != nil \u0026\u0026 spec.Volume.AzureFile != nil)\n}","line":{"from":85,"to":89}} {"id":100011824,"name":"RequiresRemount","signature":"func (plugin *azureFilePlugin) RequiresRemount(spec *volume.Spec) bool","file":"pkg/volume/azure_file/azure_file.go","code":"func (plugin *azureFilePlugin) RequiresRemount(spec *volume.Spec) bool {\n\treturn false\n}","line":{"from":91,"to":93}} {"id":100011825,"name":"SupportsMountOption","signature":"func (plugin *azureFilePlugin) SupportsMountOption() bool","file":"pkg/volume/azure_file/azure_file.go","code":"func (plugin *azureFilePlugin) SupportsMountOption() bool {\n\treturn true\n}","line":{"from":95,"to":97}} {"id":100011826,"name":"SupportsBulkVolumeVerification","signature":"func (plugin *azureFilePlugin) SupportsBulkVolumeVerification() bool","file":"pkg/volume/azure_file/azure_file.go","code":"func (plugin *azureFilePlugin) SupportsBulkVolumeVerification() bool {\n\treturn false\n}","line":{"from":99,"to":101}} {"id":100011827,"name":"SupportsSELinuxContextMount","signature":"func (plugin *azureFilePlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/azure_file/azure_file.go","code":"func (plugin *azureFilePlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error) {\n\treturn false, nil\n}","line":{"from":103,"to":105}} {"id":100011828,"name":"GetAccessModes","signature":"func (plugin *azureFilePlugin) GetAccessModes() []v1.PersistentVolumeAccessMode","file":"pkg/volume/azure_file/azure_file.go","code":"func (plugin *azureFilePlugin) GetAccessModes() []v1.PersistentVolumeAccessMode {\n\treturn []v1.PersistentVolumeAccessMode{\n\t\tv1.ReadWriteOnce,\n\t\tv1.ReadOnlyMany,\n\t\tv1.ReadWriteMany,\n\t}\n}","line":{"from":107,"to":113}} {"id":100011829,"name":"NewMounter","signature":"func (plugin *azureFilePlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error)","file":"pkg/volume/azure_file/azure_file.go","code":"func (plugin *azureFilePlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) {\n\treturn plugin.newMounterInternal(spec, pod, \u0026azureSvc{}, plugin.host.GetMounter(plugin.GetPluginName()))\n}","line":{"from":115,"to":117}} {"id":100011830,"name":"newMounterInternal","signature":"func (plugin *azureFilePlugin) newMounterInternal(spec *volume.Spec, pod *v1.Pod, util azureUtil, mounter mount.Interface) (volume.Mounter, error)","file":"pkg/volume/azure_file/azure_file.go","code":"func (plugin *azureFilePlugin) newMounterInternal(spec *volume.Spec, pod *v1.Pod, util azureUtil, mounter mount.Interface) (volume.Mounter, error) {\n\tshare, readOnly, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsecretName, secretNamespace, err := getSecretNameAndNamespace(spec, pod.Namespace)\n\tif err != nil {\n\t\t// Log-and-continue instead of returning an error for now\n\t\t// due to unspecified backwards compatibility concerns (a subject to revise)\n\t\tklog.Errorf(\"get secret name and namespace from pod(%s) return with error: %v\", pod.Name, err)\n\t}\n\treturn \u0026azureFileMounter{\n\t\tazureFile: \u0026azureFile{\n\t\t\tvolName: spec.Name(),\n\t\t\tmounter: mounter,\n\t\t\tpod: pod,\n\t\t\tplugin: plugin,\n\t\t\tMetricsProvider: volume.NewMetricsStatFS(getPath(pod.UID, spec.Name(), plugin.host)),\n\t\t},\n\t\tutil: util,\n\t\tsecretNamespace: secretNamespace,\n\t\tsecretName: secretName,\n\t\tshareName: share,\n\t\treadOnly: readOnly,\n\t\tmountOptions: volutil.MountOptionFromSpec(spec),\n\t}, nil\n}","line":{"from":119,"to":145}} {"id":100011831,"name":"NewUnmounter","signature":"func (plugin *azureFilePlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error)","file":"pkg/volume/azure_file/azure_file.go","code":"func (plugin *azureFilePlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error) {\n\treturn plugin.newUnmounterInternal(volName, podUID, plugin.host.GetMounter(plugin.GetPluginName()))\n}","line":{"from":147,"to":149}} {"id":100011832,"name":"newUnmounterInternal","signature":"func (plugin *azureFilePlugin) newUnmounterInternal(volName string, podUID types.UID, mounter mount.Interface) (volume.Unmounter, error)","file":"pkg/volume/azure_file/azure_file.go","code":"func (plugin *azureFilePlugin) newUnmounterInternal(volName string, podUID types.UID, mounter mount.Interface) (volume.Unmounter, error) {\n\treturn \u0026azureFileUnmounter{\u0026azureFile{\n\t\tvolName: volName,\n\t\tmounter: mounter,\n\t\tpod: \u0026v1.Pod{ObjectMeta: metav1.ObjectMeta{UID: podUID}},\n\t\tplugin: plugin,\n\t\tMetricsProvider: volume.NewMetricsStatFS(getPath(podUID, volName, plugin.host)),\n\t}}, nil\n}","line":{"from":151,"to":159}} {"id":100011833,"name":"RequiresFSResize","signature":"func (plugin *azureFilePlugin) RequiresFSResize() bool","file":"pkg/volume/azure_file/azure_file.go","code":"func (plugin *azureFilePlugin) RequiresFSResize() bool {\n\treturn false\n}","line":{"from":161,"to":163}} {"id":100011834,"name":"ExpandVolumeDevice","signature":"func (plugin *azureFilePlugin) ExpandVolumeDevice(","file":"pkg/volume/azure_file/azure_file.go","code":"func (plugin *azureFilePlugin) ExpandVolumeDevice(\n\tspec *volume.Spec,\n\tnewSize resource.Quantity,\n\toldSize resource.Quantity) (resource.Quantity, error) {\n\n\tif spec.PersistentVolume == nil || spec.PersistentVolume.Spec.AzureFile == nil {\n\t\treturn oldSize, fmt.Errorf(\"invalid PV spec\")\n\t}\n\tshareName := spec.PersistentVolume.Spec.AzureFile.ShareName\n\tazure, resourceGroup, err := getAzureCloudProvider(plugin.host.GetCloudProvider())\n\tif err != nil {\n\t\treturn oldSize, err\n\t}\n\tif spec.PersistentVolume.ObjectMeta.Annotations[resourceGroupAnnotation] != \"\" {\n\t\tresourceGroup = spec.PersistentVolume.ObjectMeta.Annotations[resourceGroupAnnotation]\n\t}\n\n\tsecretName, secretNamespace, err := getSecretNameAndNamespace(spec, spec.PersistentVolume.Spec.ClaimRef.Namespace)\n\tif err != nil {\n\t\treturn oldSize, err\n\t}\n\n\taccountName, _, err := (\u0026azureSvc{}).GetAzureCredentials(plugin.host, secretNamespace, secretName)\n\tif err != nil {\n\t\treturn oldSize, err\n\t}\n\n\trequestGiB, err := volumehelpers.RoundUpToGiBInt(newSize)\n\n\tif err != nil {\n\t\treturn oldSize, err\n\t}\n\n\tif err := azure.ResizeFileShare(resourceGroup, accountName, shareName, requestGiB); err != nil {\n\t\treturn oldSize, err\n\t}\n\n\treturn newSize, nil\n}","line":{"from":165,"to":203}} {"id":100011835,"name":"ConstructVolumeSpec","signature":"func (plugin *azureFilePlugin) ConstructVolumeSpec(volName, mountPath string) (volume.ReconstructedVolume, error)","file":"pkg/volume/azure_file/azure_file.go","code":"func (plugin *azureFilePlugin) ConstructVolumeSpec(volName, mountPath string) (volume.ReconstructedVolume, error) {\n\tazureVolume := \u0026v1.Volume{\n\t\tName: volName,\n\t\tVolumeSource: v1.VolumeSource{\n\t\t\tAzureFile: \u0026v1.AzureFileVolumeSource{\n\t\t\t\tSecretName: volName,\n\t\t\t\tShareName: volName,\n\t\t\t},\n\t\t},\n\t}\n\treturn volume.ReconstructedVolume{\n\t\tSpec: volume.NewSpecFromVolume(azureVolume),\n\t}, nil\n}","line":{"from":205,"to":218}} {"id":100011836,"name":"GetPath","signature":"func (azureFileVolume *azureFile) GetPath() string","file":"pkg/volume/azure_file/azure_file.go","code":"func (azureFileVolume *azureFile) GetPath() string {\n\treturn getPath(azureFileVolume.pod.UID, azureFileVolume.volName, azureFileVolume.plugin.host)\n}","line":{"from":230,"to":232}} {"id":100011837,"name":"GetAttributes","signature":"func (b *azureFileMounter) GetAttributes() volume.Attributes","file":"pkg/volume/azure_file/azure_file.go","code":"func (b *azureFileMounter) GetAttributes() volume.Attributes {\n\treturn volume.Attributes{\n\t\tReadOnly: b.readOnly,\n\t\tManaged: !b.readOnly,\n\t\tSELinuxRelabel: false,\n\t}\n}","line":{"from":246,"to":252}} {"id":100011838,"name":"SetUp","signature":"func (b *azureFileMounter) SetUp(mounterArgs volume.MounterArgs) error","file":"pkg/volume/azure_file/azure_file.go","code":"// SetUp attaches the disk and bind mounts to the volume path.\nfunc (b *azureFileMounter) SetUp(mounterArgs volume.MounterArgs) error {\n\treturn b.SetUpAt(b.GetPath(), mounterArgs)\n}","line":{"from":254,"to":257}} {"id":100011839,"name":"SetUpAt","signature":"func (b *azureFileMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error","file":"pkg/volume/azure_file/azure_file.go","code":"func (b *azureFileMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {\n\tnotMnt, err := b.mounter.IsLikelyNotMountPoint(dir)\n\tklog.V(4).Infof(\"AzureFile mount set up: %s %v %v\", dir, !notMnt, err)\n\tif err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\tif !notMnt {\n\t\t// testing original mount point, make sure the mount link is valid\n\t\tif _, err := ioutil.ReadDir(dir); err == nil {\n\t\t\tklog.V(4).Infof(\"azureFile - already mounted to target %s\", dir)\n\t\t\treturn nil\n\t\t}\n\t\t// mount link is invalid, now unmount and remount later\n\t\tklog.Warningf(\"azureFile - ReadDir %s failed with %v, unmount this directory\", dir, err)\n\t\tif err := b.mounter.Unmount(dir); err != nil {\n\t\t\tklog.Errorf(\"azureFile - Unmount directory %s failed with %v\", dir, err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tvar accountKey, accountName string\n\tif accountName, accountKey, err = b.util.GetAzureCredentials(b.plugin.host, b.secretNamespace, b.secretName); err != nil {\n\t\treturn err\n\t}\n\n\tvar mountOptions []string\n\tvar sensitiveMountOptions []string\n\tsource := \"\"\n\tosSeparator := string(os.PathSeparator)\n\tsource = fmt.Sprintf(\"%s%s%s.file.%s%s%s\", osSeparator, osSeparator, accountName, getStorageEndpointSuffix(b.plugin.host.GetCloudProvider()), osSeparator, b.shareName)\n\n\tif runtime.GOOS == \"windows\" {\n\t\tmountOptions = []string{fmt.Sprintf(\"AZURE\\\\%s\", accountName)}\n\t\tsensitiveMountOptions = []string{accountKey}\n\t} else {\n\t\tif err := os.MkdirAll(dir, 0700); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// parameters suggested by https://azure.microsoft.com/en-us/documentation/articles/storage-how-to-use-files-linux/\n\t\toptions := []string{}\n\t\tsensitiveMountOptions = []string{fmt.Sprintf(\"username=%s,password=%s\", accountName, accountKey)}\n\t\tif b.readOnly {\n\t\t\toptions = append(options, \"ro\")\n\t\t}\n\t\tmountOptions = volutil.JoinMountOptions(b.mountOptions, options)\n\t\tmountOptions = appendDefaultMountOptions(mountOptions, mounterArgs.FsGroup)\n\t}\n\n\tmountComplete := false\n\terr = wait.PollImmediate(1*time.Second, 2*time.Minute, func() (bool, error) {\n\t\terr := b.mounter.MountSensitiveWithoutSystemd(source, dir, \"cifs\", mountOptions, sensitiveMountOptions)\n\t\tmountComplete = true\n\t\treturn true, err\n\t})\n\tif !mountComplete {\n\t\treturn fmt.Errorf(\"volume(%s) mount on %s timeout(10m)\", source, dir)\n\t}\n\tif err != nil {\n\t\tnotMnt, mntErr := b.mounter.IsLikelyNotMountPoint(dir)\n\t\tif mntErr != nil {\n\t\t\tklog.Errorf(\"IsLikelyNotMountPoint check failed: %v\", mntErr)\n\t\t\treturn err\n\t\t}\n\t\tif !notMnt {\n\t\t\tif mntErr = b.mounter.Unmount(dir); mntErr != nil {\n\t\t\t\tklog.Errorf(\"Failed to unmount: %v\", mntErr)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tnotMnt, mntErr := b.mounter.IsLikelyNotMountPoint(dir)\n\t\t\tif mntErr != nil {\n\t\t\t\tklog.Errorf(\"IsLikelyNotMountPoint check failed: %v\", mntErr)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !notMnt {\n\t\t\t\t// This is very odd, we don't expect it. We'll try again next sync loop.\n\t\t\t\tklog.Errorf(\"%s is still mounted, despite call to unmount(). Will try again next sync loop.\", dir)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tos.Remove(dir)\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":259,"to":342}} {"id":100011840,"name":"TearDown","signature":"func (c *azureFileUnmounter) TearDown() error","file":"pkg/volume/azure_file/azure_file.go","code":"func (c *azureFileUnmounter) TearDown() error {\n\treturn c.TearDownAt(c.GetPath())\n}","line":{"from":350,"to":352}} {"id":100011841,"name":"TearDownAt","signature":"func (c *azureFileUnmounter) TearDownAt(dir string) error","file":"pkg/volume/azure_file/azure_file.go","code":"func (c *azureFileUnmounter) TearDownAt(dir string) error {\n\treturn mount.CleanupMountPoint(dir, c.mounter, false)\n}","line":{"from":354,"to":356}} {"id":100011842,"name":"getVolumeSource","signature":"func getVolumeSource(spec *volume.Spec) (string, bool, error)","file":"pkg/volume/azure_file/azure_file.go","code":"func getVolumeSource(spec *volume.Spec) (string, bool, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.AzureFile != nil {\n\t\tshare := spec.Volume.AzureFile.ShareName\n\t\treadOnly := spec.Volume.AzureFile.ReadOnly\n\t\treturn share, readOnly, nil\n\t} else if spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.AzureFile != nil {\n\t\tshare := spec.PersistentVolume.Spec.AzureFile.ShareName\n\t\treadOnly := spec.ReadOnly\n\t\treturn share, readOnly, nil\n\t}\n\treturn \"\", false, fmt.Errorf(\"Spec does not reference an AzureFile volume type\")\n}","line":{"from":358,"to":370}} {"id":100011843,"name":"getSecretNameAndNamespace","signature":"func getSecretNameAndNamespace(spec *volume.Spec, defaultNamespace string) (string, string, error)","file":"pkg/volume/azure_file/azure_file.go","code":"func getSecretNameAndNamespace(spec *volume.Spec, defaultNamespace string) (string, string, error) {\n\tsecretName := \"\"\n\tsecretNamespace := \"\"\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.AzureFile != nil {\n\t\tsecretName = spec.Volume.AzureFile.SecretName\n\t\tsecretNamespace = defaultNamespace\n\n\t} else if spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.AzureFile != nil {\n\t\tsecretNamespace = defaultNamespace\n\t\tif spec.PersistentVolume.Spec.AzureFile.SecretNamespace != nil {\n\t\t\tsecretNamespace = *spec.PersistentVolume.Spec.AzureFile.SecretNamespace\n\t\t}\n\t\tsecretName = spec.PersistentVolume.Spec.AzureFile.SecretName\n\t} else {\n\t\treturn \"\", \"\", fmt.Errorf(\"Spec does not reference an AzureFile volume type\")\n\t}\n\n\tif len(secretNamespace) == 0 {\n\t\treturn \"\", \"\", fmt.Errorf(\"invalid Azure volume: nil namespace\")\n\t}\n\treturn secretName, secretNamespace, nil\n\n}","line":{"from":372,"to":395}} {"id":100011844,"name":"getAzureCloud","signature":"func getAzureCloud(cloudProvider cloudprovider.Interface) (*azure.Cloud, error)","file":"pkg/volume/azure_file/azure_file.go","code":"func getAzureCloud(cloudProvider cloudprovider.Interface) (*azure.Cloud, error) {\n\tazure, ok := cloudProvider.(*azure.Cloud)\n\tif !ok || azure == nil {\n\t\treturn nil, fmt.Errorf(\"failed to get Azure Cloud Provider. GetCloudProvider returned %v instead\", cloudProvider)\n\t}\n\n\treturn azure, nil\n}","line":{"from":397,"to":404}} {"id":100011845,"name":"getStorageEndpointSuffix","signature":"func getStorageEndpointSuffix(cloudprovider cloudprovider.Interface) string","file":"pkg/volume/azure_file/azure_file.go","code":"func getStorageEndpointSuffix(cloudprovider cloudprovider.Interface) string {\n\tconst publicCloudStorageEndpointSuffix = \"core.windows.net\"\n\tazure, err := getAzureCloud(cloudprovider)\n\tif err != nil {\n\t\tklog.Warningf(\"No Azure cloud provider found. Using the Azure public cloud endpoint: %s\", publicCloudStorageEndpointSuffix)\n\t\treturn publicCloudStorageEndpointSuffix\n\t}\n\treturn azure.Environment.StorageEndpointSuffix\n}","line":{"from":406,"to":414}} {"id":100011846,"name":"NewDeleter","signature":"func (plugin *azureFilePlugin) NewDeleter(logger klog.Logger, spec *volume.Spec) (volume.Deleter, error)","file":"pkg/volume/azure_file/azure_provision.go","code":"func (plugin *azureFilePlugin) NewDeleter(logger klog.Logger, spec *volume.Spec) (volume.Deleter, error) {\n\tazure, resourceGroup, err := getAzureCloudProvider(plugin.host.GetCloudProvider())\n\tif err != nil {\n\t\tklog.V(4).Infof(\"failed to get azure provider\")\n\t\treturn nil, err\n\t}\n\tif spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.ObjectMeta.Annotations[resourceGroupAnnotation] != \"\" {\n\t\tresourceGroup = spec.PersistentVolume.ObjectMeta.Annotations[resourceGroupAnnotation]\n\t}\n\n\treturn plugin.newDeleterInternal(spec, \u0026azureSvc{}, azure, resourceGroup)\n}","line":{"from":64,"to":75}} {"id":100011847,"name":"newDeleterInternal","signature":"func (plugin *azureFilePlugin) newDeleterInternal(spec *volume.Spec, util azureUtil, azure azureCloudProvider, resourceGroup string) (volume.Deleter, error)","file":"pkg/volume/azure_file/azure_provision.go","code":"func (plugin *azureFilePlugin) newDeleterInternal(spec *volume.Spec, util azureUtil, azure azureCloudProvider, resourceGroup string) (volume.Deleter, error) {\n\tif spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.AzureFile == nil {\n\t\treturn nil, fmt.Errorf(\"invalid PV spec\")\n\t}\n\n\tsecretName, secretNamespace, err := getSecretNameAndNamespace(spec, spec.PersistentVolume.Spec.ClaimRef.Namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tshareName := spec.PersistentVolume.Spec.AzureFile.ShareName\n\tif accountName, _, err := util.GetAzureCredentials(plugin.host, secretNamespace, secretName); err != nil {\n\t\treturn nil, err\n\t} else {\n\n\t\treturn \u0026azureFileDeleter{\n\t\t\tazureFile: \u0026azureFile{\n\t\t\t\tvolName: spec.Name(),\n\t\t\t\tplugin: plugin,\n\t\t\t},\n\t\t\tresourceGroup: resourceGroup,\n\t\t\tshareName: shareName,\n\t\t\taccountName: accountName,\n\t\t\tazureProvider: azure,\n\t\t}, nil\n\t}\n}","line":{"from":77,"to":102}} {"id":100011848,"name":"NewProvisioner","signature":"func (plugin *azureFilePlugin) NewProvisioner(logger klog.Logger, options volume.VolumeOptions) (volume.Provisioner, error)","file":"pkg/volume/azure_file/azure_provision.go","code":"func (plugin *azureFilePlugin) NewProvisioner(logger klog.Logger, options volume.VolumeOptions) (volume.Provisioner, error) {\n\tazure, resourceGroup, err := getAzureCloudProvider(plugin.host.GetCloudProvider())\n\tif err != nil {\n\t\tklog.V(4).Infof(\"failed to get azure provider\")\n\t\treturn nil, err\n\t}\n\tif len(options.PVC.Spec.AccessModes) == 0 {\n\t\toptions.PVC.Spec.AccessModes = plugin.GetAccessModes()\n\t}\n\tif resourceGroup != \"\" {\n\t\toptions.PVC.ObjectMeta.Annotations[resourceGroupAnnotation] = resourceGroup\n\t}\n\treturn plugin.newProvisionerInternal(options, azure)\n}","line":{"from":104,"to":117}} {"id":100011849,"name":"newProvisionerInternal","signature":"func (plugin *azureFilePlugin) newProvisionerInternal(options volume.VolumeOptions, azure azureCloudProvider) (volume.Provisioner, error)","file":"pkg/volume/azure_file/azure_provision.go","code":"func (plugin *azureFilePlugin) newProvisionerInternal(options volume.VolumeOptions, azure azureCloudProvider) (volume.Provisioner, error) {\n\treturn \u0026azureFileProvisioner{\n\t\tazureFile: \u0026azureFile{\n\t\t\tplugin: plugin,\n\t\t},\n\t\tazureProvider: azure,\n\t\tutil: \u0026azureSvc{},\n\t\toptions: options,\n\t}, nil\n}","line":{"from":119,"to":128}} {"id":100011850,"name":"GetPath","signature":"func (f *azureFileDeleter) GetPath() string","file":"pkg/volume/azure_file/azure_provision.go","code":"func (f *azureFileDeleter) GetPath() string {\n\tname := azureFilePluginName\n\treturn f.plugin.host.GetPodVolumeDir(f.podUID, utilstrings.EscapeQualifiedName(name), f.volName)\n}","line":{"from":132,"to":135}} {"id":100011851,"name":"Delete","signature":"func (f *azureFileDeleter) Delete() error","file":"pkg/volume/azure_file/azure_provision.go","code":"func (f *azureFileDeleter) Delete() error {\n\tklog.V(4).Infof(\"deleting volume %s\", f.shareName)\n\treturn f.azureProvider.DeleteFileShare(f.resourceGroup, f.accountName, f.shareName)\n}","line":{"from":137,"to":140}} {"id":100011852,"name":"Provision","signature":"func (a *azureFileProvisioner) Provision(selectedNode *v1.Node, allowedTopologies []v1.TopologySelectorTerm) (*v1.PersistentVolume, error)","file":"pkg/volume/azure_file/azure_provision.go","code":"func (a *azureFileProvisioner) Provision(selectedNode *v1.Node, allowedTopologies []v1.TopologySelectorTerm) (*v1.PersistentVolume, error) {\n\tif !util.ContainsAllAccessModes(a.plugin.GetAccessModes(), a.options.PVC.Spec.AccessModes) {\n\t\treturn nil, fmt.Errorf(\"invalid AccessModes %v: only AccessModes %v are supported\", a.options.PVC.Spec.AccessModes, a.plugin.GetAccessModes())\n\t}\n\tif util.CheckPersistentVolumeClaimModeBlock(a.options.PVC) {\n\t\treturn nil, fmt.Errorf(\"%s does not support block volume provisioning\", a.plugin.GetPluginName())\n\t}\n\n\tvar sku, resourceGroup, location, account, shareName, customTags string\n\n\tcapacity := a.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]\n\trequestGiB, err := volumehelpers.RoundUpToGiBInt(capacity)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsecretNamespace := a.options.PVC.Namespace\n\t// Apply ProvisionerParameters (case-insensitive). We leave validation of\n\t// the values to the cloud provider.\n\tfor k, v := range a.options.Parameters {\n\t\tswitch strings.ToLower(k) {\n\t\tcase \"skuname\":\n\t\t\tsku = v\n\t\tcase \"location\":\n\t\t\tlocation = v\n\t\tcase \"storageaccount\":\n\t\t\taccount = v\n\t\tcase \"secretnamespace\":\n\t\t\tsecretNamespace = v\n\t\tcase \"resourcegroup\":\n\t\t\tresourceGroup = v\n\t\tcase \"sharename\":\n\t\t\tshareName = v\n\t\tcase \"tags\":\n\t\t\tcustomTags = v\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"invalid option %q for volume plugin %s\", k, a.plugin.GetPluginName())\n\t\t}\n\t}\n\t// TODO: implement c.options.ProvisionerSelector parsing\n\tif a.options.PVC.Spec.Selector != nil {\n\t\treturn nil, fmt.Errorf(\"claim.Spec.Selector is not supported for dynamic provisioning on Azure file\")\n\t}\n\n\ttags, err := azure.ConvertTagsToMap(customTags)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif shareName == \"\" {\n\t\t// File share name has a length limit of 63, it cannot contain two consecutive '-'s, and all letters must be lower case.\n\t\tname := util.GenerateVolumeName(a.options.ClusterName, a.options.PVName, 63)\n\t\tshareName = strings.Replace(name, \"--\", \"-\", -1)\n\t\tshareName = strings.ToLower(shareName)\n\t}\n\n\tif resourceGroup == \"\" {\n\t\tresourceGroup = a.options.PVC.ObjectMeta.Annotations[resourceGroupAnnotation]\n\t}\n\n\tfileShareSize := int(requestGiB)\n\t// when use azure file premium, account kind should be specified as FileStorage\n\taccountKind := string(storage.StorageV2)\n\tif strings.HasPrefix(strings.ToLower(sku), \"premium\") {\n\t\taccountKind = string(storage.FileStorage)\n\t\t// when using azure file premium, the shares have a minimum size\n\t\tif fileShareSize \u003c minimumPremiumShareSize {\n\t\t\tfileShareSize = minimumPremiumShareSize\n\t\t}\n\t}\n\n\taccountOptions := \u0026azure.AccountOptions{\n\t\tName: account,\n\t\tType: sku,\n\t\tKind: accountKind,\n\t\tResourceGroup: resourceGroup,\n\t\tLocation: location,\n\t\tTags: tags,\n\t}\n\n\tshareOptions := \u0026fileclient.ShareOptions{\n\t\tName: shareName,\n\t\tProtocol: storage.SMB,\n\t\tRequestGiB: fileShareSize,\n\t}\n\n\taccount, key, err := a.azureProvider.CreateFileShare(accountOptions, shareOptions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create a secret for storage account and key\n\tsecretName, err := a.util.SetAzureCredentials(a.plugin.host, secretNamespace, account, key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// create PV\n\tpv := \u0026v1.PersistentVolume{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: a.options.PVName,\n\t\t\tLabels: map[string]string{},\n\t\t\tAnnotations: map[string]string{\n\t\t\t\tutil.VolumeDynamicallyCreatedByKey: \"azure-file-dynamic-provisioner\",\n\t\t\t\tresourceGroupAnnotation: resourceGroup,\n\t\t\t},\n\t\t},\n\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\tPersistentVolumeReclaimPolicy: a.options.PersistentVolumeReclaimPolicy,\n\t\t\tAccessModes: a.options.PVC.Spec.AccessModes,\n\t\t\tCapacity: v1.ResourceList{\n\t\t\t\tv1.ResourceName(v1.ResourceStorage): resource.MustParse(fmt.Sprintf(\"%dGi\", fileShareSize)),\n\t\t\t},\n\t\t\tPersistentVolumeSource: v1.PersistentVolumeSource{\n\t\t\t\tAzureFile: \u0026v1.AzureFilePersistentVolumeSource{\n\t\t\t\t\tSecretName: secretName,\n\t\t\t\t\tShareName: shareName,\n\t\t\t\t\tSecretNamespace: \u0026secretNamespace,\n\t\t\t\t},\n\t\t\t},\n\t\t\tMountOptions: a.options.MountOptions,\n\t\t},\n\t}\n\treturn pv, nil\n}","line":{"from":151,"to":274}} {"id":100011853,"name":"getAzureCloudProvider","signature":"func getAzureCloudProvider(cloudProvider cloudprovider.Interface) (azureCloudProvider, string, error)","file":"pkg/volume/azure_file/azure_provision.go","code":"// Return cloud provider\nfunc getAzureCloudProvider(cloudProvider cloudprovider.Interface) (azureCloudProvider, string, error) {\n\tazureCloudProvider, ok := cloudProvider.(*azure.Cloud)\n\tif !ok || azureCloudProvider == nil {\n\t\treturn nil, \"\", fmt.Errorf(\"failed to get Azure Cloud Provider. GetCloudProvider returned %v instead\", cloudProvider)\n\t}\n\n\treturn azureCloudProvider, azureCloudProvider.ResourceGroup, nil\n}","line":{"from":276,"to":284}} {"id":100011854,"name":"GetAzureCredentials","signature":"func (s *azureSvc) GetAzureCredentials(host volume.VolumeHost, nameSpace, secretName string) (string, string, error)","file":"pkg/volume/azure_file/azure_util.go","code":"func (s *azureSvc) GetAzureCredentials(host volume.VolumeHost, nameSpace, secretName string) (string, string, error) {\n\tvar accountKey, accountName string\n\tkubeClient := host.GetKubeClient()\n\tif kubeClient == nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"cannot get kube client\")\n\t}\n\n\tkeys, err := kubeClient.CoreV1().Secrets(nameSpace).Get(context.TODO(), secretName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"couldn't get secret %v/%v\", nameSpace, secretName)\n\t}\n\tfor name, data := range keys.Data {\n\t\tif name == \"azurestorageaccountname\" {\n\t\t\taccountName = string(data)\n\t\t}\n\t\tif name == \"azurestorageaccountkey\" {\n\t\t\taccountKey = string(data)\n\t\t}\n\t}\n\tif accountName == \"\" || accountKey == \"\" {\n\t\treturn \"\", \"\", fmt.Errorf(\"invalid %v/%v, couldn't extract azurestorageaccountname or azurestorageaccountkey\", nameSpace, secretName)\n\t}\n\taccountName = strings.TrimSpace(accountName)\n\treturn accountName, accountKey, nil\n}","line":{"from":54,"to":78}} {"id":100011855,"name":"SetAzureCredentials","signature":"func (s *azureSvc) SetAzureCredentials(host volume.VolumeHost, nameSpace, accountName, accountKey string) (string, error)","file":"pkg/volume/azure_file/azure_util.go","code":"func (s *azureSvc) SetAzureCredentials(host volume.VolumeHost, nameSpace, accountName, accountKey string) (string, error) {\n\tkubeClient := host.GetKubeClient()\n\tif kubeClient == nil {\n\t\treturn \"\", fmt.Errorf(\"cannot get kube client\")\n\t}\n\tsecretName := \"azure-storage-account-\" + accountName + \"-secret\"\n\tsecret := \u0026v1.Secret{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: nameSpace,\n\t\t\tName: secretName,\n\t\t},\n\t\tData: map[string][]byte{\n\t\t\t\"azurestorageaccountname\": []byte(accountName),\n\t\t\t\"azurestorageaccountkey\": []byte(accountKey),\n\t\t},\n\t\tType: \"Opaque\",\n\t}\n\t_, err := kubeClient.CoreV1().Secrets(nameSpace).Create(context.TODO(), secret, metav1.CreateOptions{})\n\tif errors.IsAlreadyExists(err) {\n\t\terr = nil\n\t}\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"couldn't create secret %v\", err)\n\t}\n\treturn secretName, err\n}","line":{"from":80,"to":105}} {"id":100011856,"name":"appendDefaultMountOptions","signature":"func appendDefaultMountOptions(mountOptions []string, fsGroup *int64) []string","file":"pkg/volume/azure_file/azure_util.go","code":"// check whether mountOptions contain file_mode, dir_mode, vers, gid, if not, append default mode\nfunc appendDefaultMountOptions(mountOptions []string, fsGroup *int64) []string {\n\tfileModeFlag := false\n\tdirModeFlag := false\n\tversFlag := false\n\tgidFlag := false\n\tactimeoFlag := false\n\tmfsymlinksFlag := false\n\n\tfor _, mountOption := range mountOptions {\n\t\tif strings.HasPrefix(mountOption, fileMode) {\n\t\t\tfileModeFlag = true\n\t\t}\n\t\tif strings.HasPrefix(mountOption, dirMode) {\n\t\t\tdirModeFlag = true\n\t\t}\n\t\tif strings.HasPrefix(mountOption, vers) {\n\t\t\tversFlag = true\n\t\t}\n\t\tif strings.HasPrefix(mountOption, gid) {\n\t\t\tgidFlag = true\n\t\t}\n\t\tif strings.HasPrefix(mountOption, actimeo) {\n\t\t\tactimeoFlag = true\n\t\t}\n\t\tif strings.HasPrefix(mountOption, mfsymlinks) {\n\t\t\tmfsymlinksFlag = true\n\t\t}\n\t}\n\n\tallMountOptions := mountOptions\n\tif !fileModeFlag {\n\t\tallMountOptions = append(allMountOptions, fmt.Sprintf(\"%s=%s\", fileMode, defaultFileMode))\n\t}\n\n\tif !dirModeFlag {\n\t\tallMountOptions = append(allMountOptions, fmt.Sprintf(\"%s=%s\", dirMode, defaultDirMode))\n\t}\n\n\tif !versFlag {\n\t\tallMountOptions = append(allMountOptions, fmt.Sprintf(\"%s=%s\", vers, defaultVers))\n\t}\n\n\tif !gidFlag \u0026\u0026 fsGroup != nil {\n\t\tallMountOptions = append(allMountOptions, fmt.Sprintf(\"%s=%d\", gid, *fsGroup))\n\t}\n\n\tif !actimeoFlag {\n\t\tallMountOptions = append(allMountOptions, fmt.Sprintf(\"%s=%s\", actimeo, defaultActimeo))\n\t}\n\n\tif !mfsymlinksFlag {\n\t\tallMountOptions = append(allMountOptions, mfsymlinks)\n\t}\n\treturn allMountOptions\n}","line":{"from":107,"to":162}} {"id":100011857,"name":"ProbeVolumePlugins","signature":"func ProbeVolumePlugins() []volume.VolumePlugin","file":"pkg/volume/cephfs/cephfs.go","code":"// ProbeVolumePlugins is the primary entrypoint for volume plugins.\nfunc ProbeVolumePlugins() []volume.VolumePlugin {\n\treturn []volume.VolumePlugin{\u0026cephfsPlugin{nil}}\n}","line":{"from":39,"to":42}} {"id":100011858,"name":"Init","signature":"func (plugin *cephfsPlugin) Init(host volume.VolumeHost) error","file":"pkg/volume/cephfs/cephfs.go","code":"func (plugin *cephfsPlugin) Init(host volume.VolumeHost) error {\n\tplugin.host = host\n\treturn nil\n}","line":{"from":54,"to":57}} {"id":100011859,"name":"GetPluginName","signature":"func (plugin *cephfsPlugin) GetPluginName() string","file":"pkg/volume/cephfs/cephfs.go","code":"func (plugin *cephfsPlugin) GetPluginName() string {\n\treturn cephfsPluginName\n}","line":{"from":59,"to":61}} {"id":100011860,"name":"GetVolumeName","signature":"func (plugin *cephfsPlugin) GetVolumeName(spec *volume.Spec) (string, error)","file":"pkg/volume/cephfs/cephfs.go","code":"func (plugin *cephfsPlugin) GetVolumeName(spec *volume.Spec) (string, error) {\n\tmon, _, _, _, _, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn fmt.Sprintf(\"%v\", mon), nil\n}","line":{"from":63,"to":70}} {"id":100011861,"name":"CanSupport","signature":"func (plugin *cephfsPlugin) CanSupport(spec *volume.Spec) bool","file":"pkg/volume/cephfs/cephfs.go","code":"func (plugin *cephfsPlugin) CanSupport(spec *volume.Spec) bool {\n\treturn (spec.Volume != nil \u0026\u0026 spec.Volume.CephFS != nil) || (spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.CephFS != nil)\n}","line":{"from":72,"to":74}} {"id":100011862,"name":"RequiresRemount","signature":"func (plugin *cephfsPlugin) RequiresRemount(spec *volume.Spec) bool","file":"pkg/volume/cephfs/cephfs.go","code":"func (plugin *cephfsPlugin) RequiresRemount(spec *volume.Spec) bool {\n\treturn false\n}","line":{"from":76,"to":78}} {"id":100011863,"name":"SupportsMountOption","signature":"func (plugin *cephfsPlugin) SupportsMountOption() bool","file":"pkg/volume/cephfs/cephfs.go","code":"func (plugin *cephfsPlugin) SupportsMountOption() bool {\n\treturn true\n}","line":{"from":80,"to":82}} {"id":100011864,"name":"SupportsBulkVolumeVerification","signature":"func (plugin *cephfsPlugin) SupportsBulkVolumeVerification() bool","file":"pkg/volume/cephfs/cephfs.go","code":"func (plugin *cephfsPlugin) SupportsBulkVolumeVerification() bool {\n\treturn false\n}","line":{"from":84,"to":86}} {"id":100011865,"name":"SupportsSELinuxContextMount","signature":"func (plugin *cephfsPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/cephfs/cephfs.go","code":"func (plugin *cephfsPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error) {\n\treturn false, nil\n}","line":{"from":88,"to":90}} {"id":100011866,"name":"GetAccessModes","signature":"func (plugin *cephfsPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode","file":"pkg/volume/cephfs/cephfs.go","code":"func (plugin *cephfsPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode {\n\treturn []v1.PersistentVolumeAccessMode{\n\t\tv1.ReadWriteOnce,\n\t\tv1.ReadOnlyMany,\n\t\tv1.ReadWriteMany,\n\t}\n}","line":{"from":92,"to":98}} {"id":100011867,"name":"NewMounter","signature":"func (plugin *cephfsPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error)","file":"pkg/volume/cephfs/cephfs.go","code":"func (plugin *cephfsPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) {\n\tsecretName, secretNs, err := getSecretNameAndNamespace(spec, pod.Namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsecret := \"\"\n\tif len(secretName) \u003e 0 \u0026\u0026 len(secretNs) \u003e 0 {\n\t\t// if secret is provideded, retrieve it\n\t\tkubeClient := plugin.host.GetKubeClient()\n\t\tif kubeClient == nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot get kube client\")\n\t\t}\n\t\tsecrets, err := kubeClient.CoreV1().Secrets(secretNs).Get(context.TODO(), secretName, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"couldn't get secret %v/%v err: %w\", secretNs, secretName, err)\n\t\t\treturn nil, err\n\t\t}\n\t\tfor name, data := range secrets.Data {\n\t\t\tsecret = string(data)\n\t\t\tklog.V(4).Infof(\"found ceph secret info: %s\", name)\n\t\t}\n\t}\n\treturn plugin.newMounterInternal(spec, pod.UID, plugin.host.GetMounter(plugin.GetPluginName()), secret)\n}","line":{"from":100,"to":123}} {"id":100011868,"name":"newMounterInternal","signature":"func (plugin *cephfsPlugin) newMounterInternal(spec *volume.Spec, podUID types.UID, mounter mount.Interface, secret string) (volume.Mounter, error)","file":"pkg/volume/cephfs/cephfs.go","code":"func (plugin *cephfsPlugin) newMounterInternal(spec *volume.Spec, podUID types.UID, mounter mount.Interface, secret string) (volume.Mounter, error) {\n\tmon, path, id, secretFile, readOnly, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif id == \"\" {\n\t\tid = \"admin\"\n\t}\n\tif path == \"\" {\n\t\tpath = \"/\"\n\t}\n\tif !strings.HasPrefix(path, \"/\") {\n\t\tpath = \"/\" + path\n\t}\n\n\tif secretFile == \"\" {\n\t\tsecretFile = \"/etc/ceph/\" + id + \".secret\"\n\t}\n\n\treturn \u0026cephfsMounter{\n\t\tcephfs: \u0026cephfs{\n\t\t\tpodUID: podUID,\n\t\t\tvolName: spec.Name(),\n\t\t\tmon: mon,\n\t\t\tpath: path,\n\t\t\tsecret: secret,\n\t\t\tid: id,\n\t\t\tsecretFile: secretFile,\n\t\t\treadonly: readOnly,\n\t\t\tmounter: mounter,\n\t\t\tplugin: plugin,\n\t\t\tmountOptions: util.MountOptionFromSpec(spec),\n\t\t},\n\t}, nil\n}","line":{"from":125,"to":160}} {"id":100011869,"name":"NewUnmounter","signature":"func (plugin *cephfsPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error)","file":"pkg/volume/cephfs/cephfs.go","code":"func (plugin *cephfsPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error) {\n\treturn plugin.newUnmounterInternal(volName, podUID, plugin.host.GetMounter(plugin.GetPluginName()))\n}","line":{"from":162,"to":164}} {"id":100011870,"name":"newUnmounterInternal","signature":"func (plugin *cephfsPlugin) newUnmounterInternal(volName string, podUID types.UID, mounter mount.Interface) (volume.Unmounter, error)","file":"pkg/volume/cephfs/cephfs.go","code":"func (plugin *cephfsPlugin) newUnmounterInternal(volName string, podUID types.UID, mounter mount.Interface) (volume.Unmounter, error) {\n\treturn \u0026cephfsUnmounter{\n\t\tcephfs: \u0026cephfs{\n\t\t\tpodUID: podUID,\n\t\t\tvolName: volName,\n\t\t\tmounter: mounter,\n\t\t\tplugin: plugin},\n\t}, nil\n}","line":{"from":166,"to":174}} {"id":100011871,"name":"ConstructVolumeSpec","signature":"func (plugin *cephfsPlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error)","file":"pkg/volume/cephfs/cephfs.go","code":"func (plugin *cephfsPlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error) {\n\tcephfsVolume := \u0026v1.Volume{\n\t\tName: volumeName,\n\t\tVolumeSource: v1.VolumeSource{\n\t\t\tCephFS: \u0026v1.CephFSVolumeSource{\n\t\t\t\tMonitors: []string{},\n\t\t\t\tPath: mountPath,\n\t\t\t},\n\t\t},\n\t}\n\treturn volume.ReconstructedVolume{\n\t\tSpec: volume.NewSpecFromVolume(cephfsVolume),\n\t}, nil\n}","line":{"from":176,"to":189}} {"id":100011872,"name":"GetAttributes","signature":"func (cephfsVolume *cephfsMounter) GetAttributes() volume.Attributes","file":"pkg/volume/cephfs/cephfs.go","code":"func (cephfsVolume *cephfsMounter) GetAttributes() volume.Attributes {\n\treturn volume.Attributes{\n\t\tReadOnly: cephfsVolume.readonly,\n\t\tManaged: false,\n\t\tSELinuxRelabel: false,\n\t}\n}","line":{"from":213,"to":219}} {"id":100011873,"name":"SetUp","signature":"func (cephfsVolume *cephfsMounter) SetUp(mounterArgs volume.MounterArgs) error","file":"pkg/volume/cephfs/cephfs.go","code":"// SetUp attaches the disk and bind mounts to the volume path.\nfunc (cephfsVolume *cephfsMounter) SetUp(mounterArgs volume.MounterArgs) error {\n\treturn cephfsVolume.SetUpAt(cephfsVolume.GetPath(), mounterArgs)\n}","line":{"from":221,"to":224}} {"id":100011874,"name":"SetUpAt","signature":"func (cephfsVolume *cephfsMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error","file":"pkg/volume/cephfs/cephfs.go","code":"// SetUpAt attaches the disk and bind mounts to the volume path.\nfunc (cephfsVolume *cephfsMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {\n\tnotMnt, err := cephfsVolume.mounter.IsLikelyNotMountPoint(dir)\n\tklog.V(4).Infof(\"CephFS mount set up: %s %v %v\", dir, !notMnt, err)\n\tif err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\tif !notMnt {\n\t\treturn nil\n\t}\n\n\tif err := os.MkdirAll(dir, 0750); err != nil {\n\t\treturn err\n\t}\n\n\t// check whether it belongs to fuse, if not, default to use kernel mount.\n\tif cephfsVolume.checkFuseMount() {\n\t\tklog.V(4).Info(\"CephFS fuse mount.\")\n\t\terr = cephfsVolume.execFuseMount(dir)\n\t\t// cleanup no matter if fuse mount fail.\n\t\tkeyringPath := cephfsVolume.GetKeyringPath()\n\t\t_, StatErr := os.Stat(keyringPath)\n\t\tif !os.IsNotExist(StatErr) {\n\t\t\tos.RemoveAll(keyringPath)\n\t\t}\n\t\tif err == nil {\n\t\t\t// cephfs fuse mount succeeded.\n\t\t\treturn nil\n\t\t}\n\t\t// if cephfs fuse mount failed, fallback to kernel mount.\n\t\tklog.V(2).Infof(\"CephFS fuse mount failed: %v, fallback to kernel mount.\", err)\n\n\t}\n\tklog.V(4).Info(\"CephFS kernel mount.\")\n\n\terr = cephfsVolume.execMount(dir)\n\tif err != nil {\n\t\t// cleanup upon failure.\n\t\tmount.CleanupMountPoint(dir, cephfsVolume.mounter, false)\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":226,"to":268}} {"id":100011875,"name":"TearDown","signature":"func (cephfsVolume *cephfsUnmounter) TearDown() error","file":"pkg/volume/cephfs/cephfs.go","code":"// TearDown unmounts the bind mount\nfunc (cephfsVolume *cephfsUnmounter) TearDown() error {\n\treturn cephfsVolume.TearDownAt(cephfsVolume.GetPath())\n}","line":{"from":276,"to":279}} {"id":100011876,"name":"TearDownAt","signature":"func (cephfsVolume *cephfsUnmounter) TearDownAt(dir string) error","file":"pkg/volume/cephfs/cephfs.go","code":"// TearDownAt unmounts the bind mount\nfunc (cephfsVolume *cephfsUnmounter) TearDownAt(dir string) error {\n\treturn mount.CleanupMountPoint(dir, cephfsVolume.mounter, false)\n}","line":{"from":281,"to":284}} {"id":100011877,"name":"GetPath","signature":"func (cephfsVolume *cephfs) GetPath() string","file":"pkg/volume/cephfs/cephfs.go","code":"// GetPath creates global mount path\nfunc (cephfsVolume *cephfs) GetPath() string {\n\tname := cephfsPluginName\n\treturn cephfsVolume.plugin.host.GetPodVolumeDir(cephfsVolume.podUID, utilstrings.EscapeQualifiedName(name), cephfsVolume.volName)\n}","line":{"from":286,"to":290}} {"id":100011878,"name":"GetKeyringPath","signature":"func (cephfsVolume *cephfs) GetKeyringPath() string","file":"pkg/volume/cephfs/cephfs.go","code":"// GetKeyringPath creates cephfuse keyring path\nfunc (cephfsVolume *cephfs) GetKeyringPath() string {\n\tname := cephfsPluginName\n\tvolumeDir := cephfsVolume.plugin.host.GetPodVolumeDir(cephfsVolume.podUID, utilstrings.EscapeQualifiedName(name), cephfsVolume.volName)\n\tvolumeKeyringDir := volumeDir + \"~keyring\"\n\treturn volumeKeyringDir\n}","line":{"from":292,"to":298}} {"id":100011879,"name":"execMount","signature":"func (cephfsVolume *cephfs) execMount(mountpoint string) error","file":"pkg/volume/cephfs/cephfs.go","code":"func (cephfsVolume *cephfs) execMount(mountpoint string) error {\n\t// cephfs mount option\n\tcephSensitiveOpt := []string{\"name=\" + cephfsVolume.id}\n\t// override secretfile if secret is provided\n\tif cephfsVolume.secret != \"\" {\n\t\tcephSensitiveOpt = append(cephSensitiveOpt, \"secret=\"+cephfsVolume.secret)\n\t} else {\n\t\tcephSensitiveOpt = append(cephSensitiveOpt, \"secretfile=\"+cephfsVolume.secretFile)\n\t}\n\t// build option array\n\topt := []string{}\n\tif cephfsVolume.readonly {\n\t\topt = append(opt, \"ro\")\n\t}\n\n\t// build src like mon1:6789,mon2:6789,mon3:6789:/\n\tsrc := strings.Join(cephfsVolume.mon, \",\") + \":\" + cephfsVolume.path\n\n\topt = util.JoinMountOptions(cephfsVolume.mountOptions, opt)\n\tif err := cephfsVolume.mounter.MountSensitive(src, mountpoint, \"ceph\", opt, cephSensitiveOpt); err != nil {\n\t\treturn fmt.Errorf(\"CephFS: mount failed: %v\", err)\n\t}\n\n\treturn nil\n}","line":{"from":300,"to":324}} {"id":100011880,"name":"checkFuseMount","signature":"func (cephfsVolume *cephfsMounter) checkFuseMount() bool","file":"pkg/volume/cephfs/cephfs.go","code":"func (cephfsVolume *cephfsMounter) checkFuseMount() bool {\n\texecute := cephfsVolume.plugin.host.GetExec(cephfsVolume.plugin.GetPluginName())\n\tswitch runtime.GOOS {\n\tcase \"linux\":\n\t\tif _, err := execute.Command(\"/usr/bin/test\", \"-x\", \"/sbin/mount.fuse.ceph\").CombinedOutput(); err == nil {\n\t\t\tklog.V(4).Info(\"/sbin/mount.fuse.ceph exists, it should be fuse mount.\")\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\treturn false\n}","line":{"from":326,"to":337}} {"id":100011881,"name":"execFuseMount","signature":"func (cephfsVolume *cephfs) execFuseMount(mountpoint string) error","file":"pkg/volume/cephfs/cephfs.go","code":"func (cephfsVolume *cephfs) execFuseMount(mountpoint string) error {\n\t// cephfs keyring file\n\tkeyringFile := \"\"\n\t// override secretfile if secret is provided\n\tif cephfsVolume.secret != \"\" {\n\t\t// TODO: cephfs fuse currently doesn't support secret option,\n\t\t// remove keyring file create once secret option is supported.\n\t\tklog.V(4).Info(\"cephfs mount begin using fuse.\")\n\n\t\tkeyringPath := cephfsVolume.GetKeyringPath()\n\t\tif err := os.MkdirAll(keyringPath, 0750); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tpayload := make(map[string]util.FileProjection, 1)\n\t\tvar fileProjection util.FileProjection\n\n\t\tkeyring := fmt.Sprintf(\"[client.%s]\\nkey = %s\\n\", cephfsVolume.id, cephfsVolume.secret)\n\n\t\tfileProjection.Data = []byte(keyring)\n\t\tfileProjection.Mode = int32(0644)\n\t\tfileName := cephfsVolume.id + \".keyring\"\n\n\t\tpayload[fileName] = fileProjection\n\n\t\twriterContext := fmt.Sprintf(\"cephfuse:%v.keyring\", cephfsVolume.id)\n\t\twriter, err := util.NewAtomicWriter(keyringPath, writerContext)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"failed to create atomic writer: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\terr = writer.Write(payload, nil /*setPerms*/)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"failed to write payload to dir: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\tkeyringFile = filepath.Join(keyringPath, fileName)\n\n\t} else {\n\t\tkeyringFile = cephfsVolume.secretFile\n\t}\n\t// build src like mon1:6789,mon2:6789,mon3:6789:/\n\tsrc := strings.Join(cephfsVolume.mon, \",\")\n\n\tmountArgs := []string{}\n\tmountArgs = append(mountArgs, \"-k\")\n\tmountArgs = append(mountArgs, keyringFile)\n\tmountArgs = append(mountArgs, \"-m\")\n\tmountArgs = append(mountArgs, src)\n\tmountArgs = append(mountArgs, mountpoint)\n\tmountArgs = append(mountArgs, \"-r\")\n\tmountArgs = append(mountArgs, cephfsVolume.path)\n\tmountArgs = append(mountArgs, \"--id\")\n\tmountArgs = append(mountArgs, cephfsVolume.id)\n\n\t// build option array\n\topt := []string{}\n\tif cephfsVolume.readonly {\n\t\topt = append(opt, \"ro\")\n\t}\n\topt = util.JoinMountOptions(cephfsVolume.mountOptions, opt)\n\tif len(opt) \u003e 0 {\n\t\tmountArgs = append(mountArgs, \"-o\")\n\t\tmountArgs = append(mountArgs, strings.Join(opt, \",\"))\n\t}\n\n\tklog.V(4).Infof(\"Mounting cmd ceph-fuse with arguments (%s)\", mountArgs)\n\tcommand := exec.Command(\"ceph-fuse\", mountArgs...)\n\toutput, err := command.CombinedOutput()\n\tif err != nil || !(strings.Contains(string(output), \"starting fuse\")) {\n\t\treturn fmt.Errorf(\"Ceph-fuse failed: %v\\narguments: %s\\nOutput: %s\", err, mountArgs, string(output))\n\t}\n\n\treturn nil\n}","line":{"from":339,"to":415}} {"id":100011882,"name":"getVolumeSource","signature":"func getVolumeSource(spec *volume.Spec) ([]string, string, string, string, bool, error)","file":"pkg/volume/cephfs/cephfs.go","code":"func getVolumeSource(spec *volume.Spec) ([]string, string, string, string, bool, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.CephFS != nil {\n\t\tmon := spec.Volume.CephFS.Monitors\n\t\tpath := spec.Volume.CephFS.Path\n\t\tuser := spec.Volume.CephFS.User\n\t\tsecretFile := spec.Volume.CephFS.SecretFile\n\t\treadOnly := spec.Volume.CephFS.ReadOnly\n\t\treturn mon, path, user, secretFile, readOnly, nil\n\t} else if spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.CephFS != nil {\n\t\tmon := spec.PersistentVolume.Spec.CephFS.Monitors\n\t\tpath := spec.PersistentVolume.Spec.CephFS.Path\n\t\tuser := spec.PersistentVolume.Spec.CephFS.User\n\t\tsecretFile := spec.PersistentVolume.Spec.CephFS.SecretFile\n\t\treadOnly := spec.PersistentVolume.Spec.CephFS.ReadOnly\n\t\treturn mon, path, user, secretFile, readOnly, nil\n\t}\n\n\treturn nil, \"\", \"\", \"\", false, fmt.Errorf(\"Spec does not reference a CephFS volume type\")\n}","line":{"from":417,"to":436}} {"id":100011883,"name":"getSecretNameAndNamespace","signature":"func getSecretNameAndNamespace(spec *volume.Spec, defaultNamespace string) (string, string, error)","file":"pkg/volume/cephfs/cephfs.go","code":"func getSecretNameAndNamespace(spec *volume.Spec, defaultNamespace string) (string, string, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.CephFS != nil {\n\t\tlocalSecretRef := spec.Volume.CephFS.SecretRef\n\t\tif localSecretRef != nil {\n\t\t\treturn localSecretRef.Name, defaultNamespace, nil\n\t\t}\n\t\treturn \"\", \"\", nil\n\n\t} else if spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.CephFS != nil {\n\t\tsecretRef := spec.PersistentVolume.Spec.CephFS.SecretRef\n\t\tsecretNs := defaultNamespace\n\t\tif secretRef != nil {\n\t\t\tif len(secretRef.Namespace) != 0 {\n\t\t\t\tsecretNs = secretRef.Namespace\n\t\t\t}\n\t\t\treturn secretRef.Name, secretNs, nil\n\t\t}\n\t\treturn \"\", \"\", nil\n\t}\n\treturn \"\", \"\", fmt.Errorf(\"Spec does not reference an CephFS volume type\")\n}","line":{"from":438,"to":459}} {"id":100011884,"name":"ProbeVolumePlugins","signature":"func ProbeVolumePlugins() []volume.VolumePlugin","file":"pkg/volume/configmap/configmap.go","code":"// ProbeVolumePlugins is the entry point for plugin detection in a package.\nfunc ProbeVolumePlugins() []volume.VolumePlugin {\n\treturn []volume.VolumePlugin{\u0026configMapPlugin{}}\n}","line":{"from":34,"to":37}} {"id":100011885,"name":"getPath","signature":"func getPath(uid types.UID, volName string, host volume.VolumeHost) string","file":"pkg/volume/configmap/configmap.go","code":"func getPath(uid types.UID, volName string, host volume.VolumeHost) string {\n\treturn host.GetPodVolumeDir(uid, utilstrings.EscapeQualifiedName(configMapPluginName), volName)\n}","line":{"from":51,"to":53}} {"id":100011886,"name":"Init","signature":"func (plugin *configMapPlugin) Init(host volume.VolumeHost) error","file":"pkg/volume/configmap/configmap.go","code":"func (plugin *configMapPlugin) Init(host volume.VolumeHost) error {\n\tplugin.host = host\n\tplugin.getConfigMap = host.GetConfigMapFunc()\n\treturn nil\n}","line":{"from":55,"to":59}} {"id":100011887,"name":"GetPluginName","signature":"func (plugin *configMapPlugin) GetPluginName() string","file":"pkg/volume/configmap/configmap.go","code":"func (plugin *configMapPlugin) GetPluginName() string {\n\treturn configMapPluginName\n}","line":{"from":61,"to":63}} {"id":100011888,"name":"GetVolumeName","signature":"func (plugin *configMapPlugin) GetVolumeName(spec *volume.Spec) (string, error)","file":"pkg/volume/configmap/configmap.go","code":"func (plugin *configMapPlugin) GetVolumeName(spec *volume.Spec) (string, error) {\n\tvolumeSource, _ := getVolumeSource(spec)\n\tif volumeSource == nil {\n\t\treturn \"\", fmt.Errorf(\"Spec does not reference a ConfigMap volume type\")\n\t}\n\n\treturn fmt.Sprintf(\n\t\t\"%v/%v\",\n\t\tspec.Name(),\n\t\tvolumeSource.Name), nil\n}","line":{"from":65,"to":75}} {"id":100011889,"name":"CanSupport","signature":"func (plugin *configMapPlugin) CanSupport(spec *volume.Spec) bool","file":"pkg/volume/configmap/configmap.go","code":"func (plugin *configMapPlugin) CanSupport(spec *volume.Spec) bool {\n\treturn spec.Volume != nil \u0026\u0026 spec.Volume.ConfigMap != nil\n}","line":{"from":77,"to":79}} {"id":100011890,"name":"RequiresRemount","signature":"func (plugin *configMapPlugin) RequiresRemount(spec *volume.Spec) bool","file":"pkg/volume/configmap/configmap.go","code":"func (plugin *configMapPlugin) RequiresRemount(spec *volume.Spec) bool {\n\treturn true\n}","line":{"from":81,"to":83}} {"id":100011891,"name":"SupportsMountOption","signature":"func (plugin *configMapPlugin) SupportsMountOption() bool","file":"pkg/volume/configmap/configmap.go","code":"func (plugin *configMapPlugin) SupportsMountOption() bool {\n\treturn false\n}","line":{"from":85,"to":87}} {"id":100011892,"name":"SupportsBulkVolumeVerification","signature":"func (plugin *configMapPlugin) SupportsBulkVolumeVerification() bool","file":"pkg/volume/configmap/configmap.go","code":"func (plugin *configMapPlugin) SupportsBulkVolumeVerification() bool {\n\treturn false\n}","line":{"from":89,"to":91}} {"id":100011893,"name":"SupportsSELinuxContextMount","signature":"func (plugin *configMapPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/configmap/configmap.go","code":"func (plugin *configMapPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error) {\n\treturn false, nil\n}","line":{"from":93,"to":95}} {"id":100011894,"name":"NewMounter","signature":"func (plugin *configMapPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error)","file":"pkg/volume/configmap/configmap.go","code":"func (plugin *configMapPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error) {\n\treturn \u0026configMapVolumeMounter{\n\t\tconfigMapVolume: \u0026configMapVolume{\n\t\t\tspec.Name(),\n\t\t\tpod.UID,\n\t\t\tplugin,\n\t\t\tplugin.host.GetMounter(plugin.GetPluginName()),\n\t\t\tvolume.NewCachedMetrics(volume.NewMetricsDu(getPath(pod.UID, spec.Name(), plugin.host))),\n\t\t},\n\t\tsource: *spec.Volume.ConfigMap,\n\t\tpod: *pod,\n\t\topts: \u0026opts,\n\t\tgetConfigMap: plugin.getConfigMap,\n\t}, nil\n}","line":{"from":97,"to":111}} {"id":100011895,"name":"NewUnmounter","signature":"func (plugin *configMapPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error)","file":"pkg/volume/configmap/configmap.go","code":"func (plugin *configMapPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error) {\n\treturn \u0026configMapVolumeUnmounter{\n\t\t\u0026configMapVolume{\n\t\t\tvolName,\n\t\t\tpodUID,\n\t\t\tplugin,\n\t\t\tplugin.host.GetMounter(plugin.GetPluginName()),\n\t\t\tvolume.NewCachedMetrics(volume.NewMetricsDu(getPath(podUID, volName, plugin.host))),\n\t\t},\n\t}, nil\n}","line":{"from":113,"to":123}} {"id":100011896,"name":"ConstructVolumeSpec","signature":"func (plugin *configMapPlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error)","file":"pkg/volume/configmap/configmap.go","code":"func (plugin *configMapPlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error) {\n\tconfigMapVolume := \u0026v1.Volume{\n\t\tName: volumeName,\n\t\tVolumeSource: v1.VolumeSource{\n\t\t\tConfigMap: \u0026v1.ConfigMapVolumeSource{},\n\t\t},\n\t}\n\treturn volume.ReconstructedVolume{\n\t\tSpec: volume.NewSpecFromVolume(configMapVolume),\n\t}, nil\n}","line":{"from":125,"to":135}} {"id":100011897,"name":"GetPath","signature":"func (sv *configMapVolume) GetPath() string","file":"pkg/volume/configmap/configmap.go","code":"func (sv *configMapVolume) GetPath() string {\n\treturn sv.plugin.host.GetPodVolumeDir(sv.podUID, utilstrings.EscapeQualifiedName(configMapPluginName), sv.volName)\n}","line":{"from":147,"to":149}} {"id":100011898,"name":"GetAttributes","signature":"func (sv *configMapVolume) GetAttributes() volume.Attributes","file":"pkg/volume/configmap/configmap.go","code":"func (sv *configMapVolume) GetAttributes() volume.Attributes {\n\treturn volume.Attributes{\n\t\tReadOnly: true,\n\t\tManaged: true,\n\t\tSELinuxRelabel: true,\n\t}\n}","line":{"from":164,"to":170}} {"id":100011899,"name":"wrappedVolumeSpec","signature":"func wrappedVolumeSpec() volume.Spec","file":"pkg/volume/configmap/configmap.go","code":"func wrappedVolumeSpec() volume.Spec {\n\t// This is the spec for the volume that this plugin wraps.\n\treturn volume.Spec{\n\t\t// This should be on a tmpfs instead of the local disk; the problem is\n\t\t// charging the memory for the tmpfs to the right cgroup. We should make\n\t\t// this a tmpfs when we can do the accounting correctly.\n\t\tVolume: \u0026v1.Volume{VolumeSource: v1.VolumeSource{EmptyDir: \u0026v1.EmptyDirVolumeSource{}}},\n\t}\n}","line":{"from":172,"to":180}} {"id":100011900,"name":"SetUp","signature":"func (b *configMapVolumeMounter) SetUp(mounterArgs volume.MounterArgs) error","file":"pkg/volume/configmap/configmap.go","code":"func (b *configMapVolumeMounter) SetUp(mounterArgs volume.MounterArgs) error {\n\treturn b.SetUpAt(b.GetPath(), mounterArgs)\n}","line":{"from":182,"to":184}} {"id":100011901,"name":"SetUpAt","signature":"func (b *configMapVolumeMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error","file":"pkg/volume/configmap/configmap.go","code":"func (b *configMapVolumeMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {\n\tklog.V(3).Infof(\"Setting up volume %v for pod %v at %v\", b.volName, b.pod.UID, dir)\n\n\t// Wrap EmptyDir, let it do the setup.\n\twrapped, err := b.plugin.host.NewWrapperMounter(b.volName, wrappedVolumeSpec(), \u0026b.pod, *b.opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\toptional := b.source.Optional != nil \u0026\u0026 *b.source.Optional\n\tconfigMap, err := b.getConfigMap(b.pod.Namespace, b.source.Name)\n\tif err != nil {\n\t\tif !(errors.IsNotFound(err) \u0026\u0026 optional) {\n\t\t\tklog.Errorf(\"Couldn't get configMap %v/%v: %v\", b.pod.Namespace, b.source.Name, err)\n\t\t\treturn err\n\t\t}\n\t\tconfigMap = \u0026v1.ConfigMap{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: b.pod.Namespace,\n\t\t\t\tName: b.source.Name,\n\t\t\t},\n\t\t}\n\t}\n\n\ttotalBytes := totalBytes(configMap)\n\tklog.V(3).Infof(\"Received configMap %v/%v containing (%v) pieces of data, %v total bytes\",\n\t\tb.pod.Namespace,\n\t\tb.source.Name,\n\t\tlen(configMap.Data)+len(configMap.BinaryData),\n\t\ttotalBytes)\n\n\tpayload, err := MakePayload(b.source.Items, configMap, b.source.DefaultMode, optional)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsetupSuccess := false\n\tif err := wrapped.SetUpAt(dir, mounterArgs); err != nil {\n\t\treturn err\n\t}\n\tif err := volumeutil.MakeNestedMountpoints(b.volName, dir, b.pod); err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\t// Clean up directories if setup fails\n\t\tif !setupSuccess {\n\t\t\tunmounter, unmountCreateErr := b.plugin.NewUnmounter(b.volName, b.podUID)\n\t\t\tif unmountCreateErr != nil {\n\t\t\t\tklog.Errorf(\"error cleaning up mount %s after failure. Create unmounter failed with %v\", b.volName, unmountCreateErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\ttearDownErr := unmounter.TearDown()\n\t\t\tif tearDownErr != nil {\n\t\t\t\tklog.Errorf(\"Error tearing down volume %s with : %v\", b.volName, tearDownErr)\n\t\t\t}\n\t\t}\n\t}()\n\n\twriterContext := fmt.Sprintf(\"pod %v/%v volume %v\", b.pod.Namespace, b.pod.Name, b.volName)\n\twriter, err := volumeutil.NewAtomicWriter(dir, writerContext)\n\tif err != nil {\n\t\tklog.Errorf(\"Error creating atomic writer: %v\", err)\n\t\treturn err\n\t}\n\n\tsetPerms := func(_ string) error {\n\t\t// This may be the first time writing and new files get created outside the timestamp subdirectory:\n\t\t// change the permissions on the whole volume and not only in the timestamp directory.\n\t\treturn volume.SetVolumeOwnership(b, dir, mounterArgs.FsGroup, nil /*fsGroupChangePolicy*/, volumeutil.FSGroupCompleteHook(b.plugin, nil))\n\t}\n\terr = writer.Write(payload, setPerms)\n\tif err != nil {\n\t\tklog.Errorf(\"Error writing payload to dir: %v\", err)\n\t\treturn err\n\t}\n\n\tsetupSuccess = true\n\treturn nil\n}","line":{"from":186,"to":265}} {"id":100011902,"name":"MakePayload","signature":"func MakePayload(mappings []v1.KeyToPath, configMap *v1.ConfigMap, defaultMode *int32, optional bool) (map[string]volumeutil.FileProjection, error)","file":"pkg/volume/configmap/configmap.go","code":"// MakePayload function is exported so that it can be called from the projection volume driver\nfunc MakePayload(mappings []v1.KeyToPath, configMap *v1.ConfigMap, defaultMode *int32, optional bool) (map[string]volumeutil.FileProjection, error) {\n\tif defaultMode == nil {\n\t\treturn nil, fmt.Errorf(\"no defaultMode used, not even the default value for it\")\n\t}\n\n\tpayload := make(map[string]volumeutil.FileProjection, (len(configMap.Data) + len(configMap.BinaryData)))\n\tvar fileProjection volumeutil.FileProjection\n\n\tif len(mappings) == 0 {\n\t\tfor name, data := range configMap.Data {\n\t\t\tfileProjection.Data = []byte(data)\n\t\t\tfileProjection.Mode = *defaultMode\n\t\t\tpayload[name] = fileProjection\n\t\t}\n\t\tfor name, data := range configMap.BinaryData {\n\t\t\tfileProjection.Data = data\n\t\t\tfileProjection.Mode = *defaultMode\n\t\t\tpayload[name] = fileProjection\n\t\t}\n\t} else {\n\t\tfor _, ktp := range mappings {\n\t\t\tif stringData, ok := configMap.Data[ktp.Key]; ok {\n\t\t\t\tfileProjection.Data = []byte(stringData)\n\t\t\t} else if binaryData, ok := configMap.BinaryData[ktp.Key]; ok {\n\t\t\t\tfileProjection.Data = binaryData\n\t\t\t} else {\n\t\t\t\tif optional {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\treturn nil, fmt.Errorf(\"configmap references non-existent config key: %s\", ktp.Key)\n\t\t\t}\n\n\t\t\tif ktp.Mode != nil {\n\t\t\t\tfileProjection.Mode = *ktp.Mode\n\t\t\t} else {\n\t\t\t\tfileProjection.Mode = *defaultMode\n\t\t\t}\n\t\t\tpayload[ktp.Path] = fileProjection\n\t\t}\n\t}\n\n\treturn payload, nil\n}","line":{"from":267,"to":310}} {"id":100011903,"name":"totalBytes","signature":"func totalBytes(configMap *v1.ConfigMap) int","file":"pkg/volume/configmap/configmap.go","code":"func totalBytes(configMap *v1.ConfigMap) int {\n\ttotalSize := 0\n\tfor _, value := range configMap.Data {\n\t\ttotalSize += len(value)\n\t}\n\tfor _, value := range configMap.BinaryData {\n\t\ttotalSize += len(value)\n\t}\n\n\treturn totalSize\n}","line":{"from":312,"to":322}} {"id":100011904,"name":"TearDown","signature":"func (c *configMapVolumeUnmounter) TearDown() error","file":"pkg/volume/configmap/configmap.go","code":"func (c *configMapVolumeUnmounter) TearDown() error {\n\treturn c.TearDownAt(c.GetPath())\n}","line":{"from":331,"to":333}} {"id":100011905,"name":"TearDownAt","signature":"func (c *configMapVolumeUnmounter) TearDownAt(dir string) error","file":"pkg/volume/configmap/configmap.go","code":"func (c *configMapVolumeUnmounter) TearDownAt(dir string) error {\n\treturn volumeutil.UnmountViaEmptyDir(dir, c.plugin.host, c.volName, wrappedVolumeSpec(), c.podUID)\n}","line":{"from":335,"to":337}} {"id":100011906,"name":"getVolumeSource","signature":"func getVolumeSource(spec *volume.Spec) (*v1.ConfigMapVolumeSource, bool)","file":"pkg/volume/configmap/configmap.go","code":"func getVolumeSource(spec *volume.Spec) (*v1.ConfigMapVolumeSource, bool) {\n\tvar readOnly bool\n\tvar volumeSource *v1.ConfigMapVolumeSource\n\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.ConfigMap != nil {\n\t\tvolumeSource = spec.Volume.ConfigMap\n\t\treadOnly = spec.ReadOnly\n\t}\n\n\treturn volumeSource, readOnly\n}","line":{"from":339,"to":349}} {"id":100011907,"name":"Attach","signature":"func (c *csiAttacher) Attach(spec *volume.Spec, nodeName types.NodeName) (string, error)","file":"pkg/volume/csi/csi_attacher.go","code":"func (c *csiAttacher) Attach(spec *volume.Spec, nodeName types.NodeName) (string, error) {\n\t_, ok := c.plugin.host.(volume.KubeletVolumeHost)\n\tif ok {\n\t\treturn \"\", errors.New(\"attaching volumes from the kubelet is not supported\")\n\t}\n\n\tif spec == nil {\n\t\tklog.Error(log(\"attacher.Attach missing volume.Spec\"))\n\t\treturn \"\", errors.New(\"missing spec\")\n\t}\n\n\tpvSrc, err := getPVSourceFromSpec(spec)\n\tif err != nil {\n\t\treturn \"\", errors.New(log(\"attacher.Attach failed to get CSIPersistentVolumeSource: %v\", err))\n\t}\n\n\tnode := string(nodeName)\n\tattachID := getAttachmentName(pvSrc.VolumeHandle, pvSrc.Driver, node)\n\n\tattachment, err := c.plugin.volumeAttachmentLister.Get(attachID)\n\tif err != nil \u0026\u0026 !apierrors.IsNotFound(err) {\n\t\treturn \"\", errors.New(log(\"failed to get volume attachment from lister: %v\", err))\n\t}\n\n\tif attachment == nil {\n\t\tvar vaSrc storage.VolumeAttachmentSource\n\t\tif spec.InlineVolumeSpecForCSIMigration {\n\t\t\t// inline PV scenario - use PV spec to populate VA source.\n\t\t\t// The volume spec will be populated by CSI translation API\n\t\t\t// for inline volumes. This allows fields required by the CSI\n\t\t\t// attacher such as AccessMode and MountOptions (in addition to\n\t\t\t// fields in the CSI persistent volume source) to be populated\n\t\t\t// as part of CSI translation for inline volumes.\n\t\t\tvaSrc = storage.VolumeAttachmentSource{\n\t\t\t\tInlineVolumeSpec: \u0026spec.PersistentVolume.Spec,\n\t\t\t}\n\t\t} else {\n\t\t\t// regular PV scenario - use PV name to populate VA source\n\t\t\tpvName := spec.PersistentVolume.GetName()\n\t\t\tvaSrc = storage.VolumeAttachmentSource{\n\t\t\t\tPersistentVolumeName: \u0026pvName,\n\t\t\t}\n\t\t}\n\n\t\tattachment := \u0026storage.VolumeAttachment{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: attachID,\n\t\t\t},\n\t\t\tSpec: storage.VolumeAttachmentSpec{\n\t\t\t\tNodeName: node,\n\t\t\t\tAttacher: pvSrc.Driver,\n\t\t\t\tSource: vaSrc,\n\t\t\t},\n\t\t}\n\n\t\t_, err = c.k8s.StorageV1().VolumeAttachments().Create(context.TODO(), attachment, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\tif !apierrors.IsAlreadyExists(err) {\n\t\t\t\treturn \"\", errors.New(log(\"attacher.Attach failed: %v\", err))\n\t\t\t}\n\t\t\tklog.V(4).Info(log(\"attachment [%v] for volume [%v] already exists (will not be recreated)\", attachID, pvSrc.VolumeHandle))\n\t\t} else {\n\t\t\tklog.V(4).Info(log(\"attachment [%v] for volume [%v] created successfully\", attachID, pvSrc.VolumeHandle))\n\t\t}\n\t}\n\n\t// Attach and detach functionality is exclusive to the CSI plugin that runs in the AttachDetachController,\n\t// and has access to a VolumeAttachment lister that can be polled for the current status.\n\tif err := c.waitForVolumeAttachmentWithLister(spec, pvSrc.VolumeHandle, attachID, c.watchTimeout); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tklog.V(4).Info(log(\"attacher.Attach finished OK with VolumeAttachment object [%s]\", attachID))\n\n\t// Don't return attachID as a devicePath. We can reconstruct the attachID using getAttachmentName()\n\treturn \"\", nil\n}","line":{"from":65,"to":141}} {"id":100011908,"name":"WaitForAttach","signature":"func (c *csiAttacher) WaitForAttach(spec *volume.Spec, _ string, pod *v1.Pod, timeout time.Duration) (string, error)","file":"pkg/volume/csi/csi_attacher.go","code":"func (c *csiAttacher) WaitForAttach(spec *volume.Spec, _ string, pod *v1.Pod, timeout time.Duration) (string, error) {\n\tsource, err := getPVSourceFromSpec(spec)\n\tif err != nil {\n\t\treturn \"\", errors.New(log(\"attacher.WaitForAttach failed to extract CSI volume source: %v\", err))\n\t}\n\n\tattachID := getAttachmentName(source.VolumeHandle, source.Driver, string(c.plugin.host.GetNodeName()))\n\n\treturn c.waitForVolumeAttachment(source.VolumeHandle, attachID, timeout)\n}","line":{"from":143,"to":152}} {"id":100011909,"name":"waitForVolumeAttachment","signature":"func (c *csiAttacher) waitForVolumeAttachment(volumeHandle, attachID string, timeout time.Duration) (string, error)","file":"pkg/volume/csi/csi_attacher.go","code":"func (c *csiAttacher) waitForVolumeAttachment(volumeHandle, attachID string, timeout time.Duration) (string, error) {\n\tklog.V(4).Info(log(\"probing for updates from CSI driver for [attachment.ID=%v]\", attachID))\n\n\ttimer := time.NewTimer(timeout) // TODO (vladimirvivien) investigate making this configurable\n\tdefer timer.Stop()\n\n\treturn c.waitForVolumeAttachmentInternal(volumeHandle, attachID, timer, timeout)\n}","line":{"from":154,"to":161}} {"id":100011910,"name":"waitForVolumeAttachmentInternal","signature":"func (c *csiAttacher) waitForVolumeAttachmentInternal(volumeHandle, attachID string, timer *time.Timer, timeout time.Duration) (string, error)","file":"pkg/volume/csi/csi_attacher.go","code":"func (c *csiAttacher) waitForVolumeAttachmentInternal(volumeHandle, attachID string, timer *time.Timer, timeout time.Duration) (string, error) {\n\n\tklog.V(4).Info(log(\"probing VolumeAttachment [id=%v]\", attachID))\n\tattach, err := c.k8s.StorageV1().VolumeAttachments().Get(context.TODO(), attachID, metav1.GetOptions{})\n\tif err != nil {\n\t\tklog.Error(log(\"attacher.WaitForAttach failed for volume [%s] (will continue to try): %v\", volumeHandle, err))\n\t\treturn \"\", fmt.Errorf(\"volume %v has GET error for volume attachment %v: %v\", volumeHandle, attachID, err)\n\t}\n\terr = c.waitForVolumeAttachDetachStatus(attach, volumeHandle, attachID, timer, timeout, verifyAttachmentStatus)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn attach.Name, nil\n}","line":{"from":163,"to":176}} {"id":100011911,"name":"waitForVolumeAttachmentWithLister","signature":"func (c *csiAttacher) waitForVolumeAttachmentWithLister(spec *volume.Spec, volumeHandle, attachID string, timeout time.Duration) error","file":"pkg/volume/csi/csi_attacher.go","code":"func (c *csiAttacher) waitForVolumeAttachmentWithLister(spec *volume.Spec, volumeHandle, attachID string, timeout time.Duration) error {\n\tklog.V(4).Info(log(\"probing VolumeAttachment [id=%v]\", attachID))\n\n\tverifyStatus := func() (bool, error) {\n\t\tvolumeAttachment, err := c.plugin.volumeAttachmentLister.Get(attachID)\n\t\tif err != nil {\n\t\t\t// Ignore \"not found\" errors in case the VolumeAttachment was just created and hasn't yet made it into the lister.\n\t\t\tif !apierrors.IsNotFound(err) {\n\t\t\t\tklog.Error(log(\"unexpected error waiting for volume attachment, %v\", err))\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\t// The VolumeAttachment is not available yet and we will have to try again.\n\t\t\treturn false, nil\n\t\t}\n\n\t\tsuccessful, err := verifyAttachmentStatus(volumeAttachment, volumeHandle)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\treturn successful, nil\n\t}\n\n\treturn c.waitForVolumeAttachDetachStatusWithLister(spec, volumeHandle, attachID, timeout, verifyStatus, \"Attach\")\n}","line":{"from":178,"to":202}} {"id":100011912,"name":"VolumesAreAttached","signature":"func (c *csiAttacher) VolumesAreAttached(specs []*volume.Spec, nodeName types.NodeName) (map[*volume.Spec]bool, error)","file":"pkg/volume/csi/csi_attacher.go","code":"func (c *csiAttacher) VolumesAreAttached(specs []*volume.Spec, nodeName types.NodeName) (map[*volume.Spec]bool, error) {\n\tklog.V(4).Info(log(\"probing attachment status for %d volume(s) \", len(specs)))\n\n\tattached := make(map[*volume.Spec]bool)\n\n\tfor _, spec := range specs {\n\t\tif spec == nil {\n\t\t\tklog.Error(log(\"attacher.VolumesAreAttached missing volume.Spec\"))\n\t\t\treturn nil, errors.New(\"missing spec\")\n\t\t}\n\t\tpvSrc, err := getPVSourceFromSpec(spec)\n\t\tif err != nil {\n\t\t\tattached[spec] = false\n\t\t\tklog.Error(log(\"attacher.VolumesAreAttached failed to get CSIPersistentVolumeSource: %v\", err))\n\t\t\tcontinue\n\t\t}\n\t\tdriverName := pvSrc.Driver\n\t\tvolumeHandle := pvSrc.VolumeHandle\n\n\t\tskip, err := c.plugin.skipAttach(driverName)\n\t\tif err != nil {\n\t\t\tklog.Error(log(\"Failed to check CSIDriver for %s: %s\", driverName, err))\n\t\t} else {\n\t\t\tif skip {\n\t\t\t\t// This volume is not attachable, pretend it's attached\n\t\t\t\tattached[spec] = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tattachID := getAttachmentName(volumeHandle, driverName, string(nodeName))\n\t\tvar attach *storage.VolumeAttachment\n\t\tif c.plugin.volumeAttachmentLister != nil {\n\t\t\tattach, err = c.plugin.volumeAttachmentLister.Get(attachID)\n\t\t\tif err == nil {\n\t\t\t\tattached[spec] = attach.Status.Attached\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tklog.V(4).Info(log(\"attacher.VolumesAreAttached failed in AttachmentLister for attach.ID=%v: %v. Probing the API server.\", attachID, err))\n\t\t}\n\t\t// The cache lookup is not setup or the object is not found in the cache.\n\t\t// Get the object from the API server.\n\t\tklog.V(4).Info(log(\"probing attachment status for VolumeAttachment %v\", attachID))\n\t\tattach, err = c.k8s.StorageV1().VolumeAttachments().Get(context.TODO(), attachID, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\tattached[spec] = false\n\t\t\tklog.Error(log(\"attacher.VolumesAreAttached failed for attach.ID=%v: %v\", attachID, err))\n\t\t\tcontinue\n\t\t}\n\t\tklog.V(4).Info(log(\"attacher.VolumesAreAttached attachment [%v] has status.attached=%t\", attachID, attach.Status.Attached))\n\t\tattached[spec] = attach.Status.Attached\n\t}\n\n\treturn attached, nil\n}","line":{"from":204,"to":258}} {"id":100011913,"name":"GetDeviceMountPath","signature":"func (c *csiAttacher) GetDeviceMountPath(spec *volume.Spec) (string, error)","file":"pkg/volume/csi/csi_attacher.go","code":"func (c *csiAttacher) GetDeviceMountPath(spec *volume.Spec) (string, error) {\n\tklog.V(4).Info(log(\"attacher.GetDeviceMountPath(%v)\", spec))\n\tdeviceMountPath, err := makeDeviceMountPath(c.plugin, spec)\n\tif err != nil {\n\t\treturn \"\", errors.New(log(\"attacher.GetDeviceMountPath failed to make device mount path: %v\", err))\n\t}\n\tklog.V(4).Infof(\"attacher.GetDeviceMountPath succeeded, deviceMountPath: %s\", deviceMountPath)\n\treturn deviceMountPath, nil\n}","line":{"from":260,"to":268}} {"id":100011914,"name":"MountDevice","signature":"func (c *csiAttacher) MountDevice(spec *volume.Spec, devicePath string, deviceMountPath string, deviceMounterArgs volume.DeviceMounterArgs) error","file":"pkg/volume/csi/csi_attacher.go","code":"func (c *csiAttacher) MountDevice(spec *volume.Spec, devicePath string, deviceMountPath string, deviceMounterArgs volume.DeviceMounterArgs) error {\n\tklog.V(4).Infof(log(\"attacher.MountDevice(%s, %s)\", devicePath, deviceMountPath))\n\n\tif deviceMountPath == \"\" {\n\t\treturn errors.New(log(\"attacher.MountDevice failed, deviceMountPath is empty\"))\n\t}\n\n\t// Setup\n\tif spec == nil {\n\t\treturn errors.New(log(\"attacher.MountDevice failed, spec is nil\"))\n\t}\n\tcsiSource, err := getPVSourceFromSpec(spec)\n\tif err != nil {\n\t\treturn errors.New(log(\"attacher.MountDevice failed to get CSIPersistentVolumeSource: %v\", err))\n\t}\n\n\t// lets check if node/unstage is supported\n\tif c.csiClient == nil {\n\t\tc.csiClient, err = newCsiDriverClient(csiDriverName(csiSource.Driver))\n\t\tif err != nil {\n\t\t\treturn errors.New(log(\"attacher.MountDevice failed to create newCsiDriverClient: %v\", err))\n\t\t}\n\t}\n\tcsi := c.csiClient\n\n\tctx, cancel := createCSIOperationContext(spec, c.watchTimeout)\n\tdefer cancel()\n\t// Check whether \"STAGE_UNSTAGE_VOLUME\" is set\n\tstageUnstageSet, err := csi.NodeSupportsStageUnstage(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Get secrets and publish context required for mountDevice\n\tnodeName := string(c.plugin.host.GetNodeName())\n\tpublishContext, err := c.plugin.getPublishContext(c.k8s, csiSource.VolumeHandle, csiSource.Driver, nodeName)\n\n\tif err != nil {\n\t\treturn volumetypes.NewTransientOperationFailure(err.Error())\n\t}\n\n\tnodeStageSecrets := map[string]string{}\n\t// we only require secrets if csiSource has them and volume has NodeStage capability\n\tif csiSource.NodeStageSecretRef != nil \u0026\u0026 stageUnstageSet {\n\t\tnodeStageSecrets, err = getCredentialsFromSecret(c.k8s, csiSource.NodeStageSecretRef)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"fetching NodeStageSecretRef %s/%s failed: %v\",\n\t\t\t\tcsiSource.NodeStageSecretRef.Namespace, csiSource.NodeStageSecretRef.Name, err)\n\t\t\t// if we failed to fetch secret then that could be a transient error\n\t\t\treturn volumetypes.NewTransientOperationFailure(err.Error())\n\t\t}\n\t}\n\n\tvar mountOptions []string\n\tif spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.MountOptions != nil {\n\t\tmountOptions = spec.PersistentVolume.Spec.MountOptions\n\t}\n\n\tvar seLinuxSupported bool\n\tif utilfeature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {\n\t\tsupport, err := c.plugin.SupportsSELinuxContextMount(spec)\n\t\tif err != nil {\n\t\t\treturn errors.New(log(\"failed to query for SELinuxMount support: %s\", err))\n\t\t}\n\t\tif support \u0026\u0026 deviceMounterArgs.SELinuxLabel != \"\" {\n\t\t\tmountOptions = util.AddSELinuxMountOption(mountOptions, deviceMounterArgs.SELinuxLabel)\n\t\t\tseLinuxSupported = true\n\t\t}\n\t}\n\n\t// Store volume metadata for UnmountDevice. Keep it around even if the\n\t// driver does not support NodeStage, UnmountDevice still needs it.\n\tif err = os.MkdirAll(deviceMountPath, 0750); err != nil {\n\t\treturn errors.New(log(\"attacher.MountDevice failed to create dir %#v: %v\", deviceMountPath, err))\n\t}\n\tklog.V(4).Info(log(\"created target path successfully [%s]\", deviceMountPath))\n\tdataDir := filepath.Dir(deviceMountPath)\n\tdata := map[string]string{\n\t\tvolDataKey.volHandle: csiSource.VolumeHandle,\n\t\tvolDataKey.driverName: csiSource.Driver,\n\t}\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) \u0026\u0026 seLinuxSupported {\n\t\tdata[volDataKey.seLinuxMountContext] = deviceMounterArgs.SELinuxLabel\n\t}\n\n\terr = saveVolumeData(dataDir, volDataFileName, data)\n\tdefer func() {\n\t\t// Only if there was an error and volume operation was considered\n\t\t// finished, we should remove the directory.\n\t\tif err != nil \u0026\u0026 volumetypes.IsOperationFinishedError(err) {\n\t\t\t// clean up metadata\n\t\t\tklog.Errorf(log(\"attacher.MountDevice failed: %v\", err))\n\t\t\tif err := removeMountDir(c.plugin, deviceMountPath); err != nil {\n\t\t\t\tklog.Error(log(\"attacher.MountDevice failed to remove mount dir after error [%s]: %v\", deviceMountPath, err))\n\t\t\t}\n\t\t}\n\t}()\n\n\tif err != nil {\n\t\terrMsg := log(\"failed to save volume info data: %v\", err)\n\t\tklog.Error(errMsg)\n\t\treturn errors.New(errMsg)\n\t}\n\n\tif !stageUnstageSet {\n\t\tklog.Infof(log(\"attacher.MountDevice STAGE_UNSTAGE_VOLUME capability not set. Skipping MountDevice...\"))\n\t\t// defer does *not* remove the metadata file and it's correct - UnmountDevice needs it there.\n\t\treturn nil\n\t}\n\n\t//TODO (vladimirvivien) implement better AccessModes mapping between k8s and CSI\n\taccessMode := v1.ReadWriteOnce\n\tif spec.PersistentVolume.Spec.AccessModes != nil {\n\t\taccessMode = spec.PersistentVolume.Spec.AccessModes[0]\n\t}\n\n\tvar nodeStageFSGroupArg *int64\n\tdriverSupportsCSIVolumeMountGroup, err := csi.NodeSupportsVolumeMountGroup(ctx)\n\tif err != nil {\n\t\treturn volumetypes.NewTransientOperationFailure(log(\"attacher.MountDevice failed to determine if the node service has VOLUME_MOUNT_GROUP capability: %v\", err))\n\t}\n\n\tif driverSupportsCSIVolumeMountGroup {\n\t\tklog.V(3).Infof(\"Driver %s supports applying FSGroup (has VOLUME_MOUNT_GROUP node capability). Delegating FSGroup application to the driver through NodeStageVolume.\", csiSource.Driver)\n\t\tnodeStageFSGroupArg = deviceMounterArgs.FsGroup\n\t}\n\n\tfsType := csiSource.FSType\n\terr = csi.NodeStageVolume(ctx,\n\t\tcsiSource.VolumeHandle,\n\t\tpublishContext,\n\t\tdeviceMountPath,\n\t\tfsType,\n\t\taccessMode,\n\t\tnodeStageSecrets,\n\t\tcsiSource.VolumeAttributes,\n\t\tmountOptions,\n\t\tnodeStageFSGroupArg)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tklog.V(4).Infof(log(\"attacher.MountDevice successfully requested NodeStageVolume [%s]\", deviceMountPath))\n\treturn err\n}","line":{"from":270,"to":416}} {"id":100011915,"name":"Detach","signature":"func (c *csiAttacher) Detach(volumeName string, nodeName types.NodeName) error","file":"pkg/volume/csi/csi_attacher.go","code":"func (c *csiAttacher) Detach(volumeName string, nodeName types.NodeName) error {\n\t_, ok := c.plugin.host.(volume.KubeletVolumeHost)\n\tif ok {\n\t\treturn errors.New(\"detaching volumes from the kubelet is not supported\")\n\t}\n\n\tvar attachID string\n\tvar volID string\n\n\tif volumeName == \"\" {\n\t\tklog.Error(log(\"detacher.Detach missing value for parameter volumeName\"))\n\t\treturn errors.New(\"missing expected parameter volumeName\")\n\t}\n\n\t// volumeName in format driverName\u003cSEP\u003evolumeHandle generated by plugin.GetVolumeName()\n\tparts := strings.Split(volumeName, volNameSep)\n\tif len(parts) != 2 {\n\t\tklog.Error(log(\"detacher.Detach insufficient info encoded in volumeName\"))\n\t\treturn errors.New(\"volumeName missing expected data\")\n\t}\n\n\tdriverName := parts[0]\n\tvolID = parts[1]\n\tattachID = getAttachmentName(volID, driverName, string(nodeName))\n\n\tif err := c.k8s.StorageV1().VolumeAttachments().Delete(context.TODO(), attachID, metav1.DeleteOptions{}); err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\t// object deleted or never existed, done\n\t\t\tklog.V(4).Info(log(\"VolumeAttachment object [%v] for volume [%v] not found, object deleted\", attachID, volID))\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.New(log(\"detacher.Detach failed to delete VolumeAttachment [%s]: %v\", attachID, err))\n\t}\n\n\tklog.V(4).Info(log(\"detacher deleted ok VolumeAttachment.ID=%s\", attachID))\n\n\t// Attach and detach functionality is exclusive to the CSI plugin that runs in the AttachDetachController,\n\t// and has access to a VolumeAttachment lister that can be polled for the current status.\n\treturn c.waitForVolumeDetachmentWithLister(volID, attachID, c.watchTimeout)\n}","line":{"from":422,"to":461}} {"id":100011916,"name":"waitForVolumeDetachmentWithLister","signature":"func (c *csiAttacher) waitForVolumeDetachmentWithLister(volumeHandle, attachID string, timeout time.Duration) error","file":"pkg/volume/csi/csi_attacher.go","code":"func (c *csiAttacher) waitForVolumeDetachmentWithLister(volumeHandle, attachID string, timeout time.Duration) error {\n\tklog.V(4).Info(log(\"probing VolumeAttachment [id=%v]\", attachID))\n\n\tverifyStatus := func() (bool, error) {\n\t\tvolumeAttachment, err := c.plugin.volumeAttachmentLister.Get(attachID)\n\t\tif err != nil {\n\t\t\tif !apierrors.IsNotFound(err) {\n\t\t\t\treturn false, errors.New(log(\"detacher.WaitForDetach failed for volume [%s] (will continue to try): %v\", volumeHandle, err))\n\t\t\t}\n\n\t\t\t// Detachment successful.\n\t\t\tklog.V(4).Info(log(\"VolumeAttachment object [%v] for volume [%v] not found, object deleted\", attachID, volumeHandle))\n\t\t\treturn true, nil\n\t\t}\n\n\t\t// Detachment is only \"successful\" once the VolumeAttachment is deleted, however we perform\n\t\t// this check to make sure the object does not contain any detach errors.\n\t\tsuccessful, err := verifyDetachmentStatus(volumeAttachment, volumeHandle)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\treturn successful, nil\n\t}\n\n\treturn c.waitForVolumeAttachDetachStatusWithLister(nil, volumeHandle, attachID, timeout, verifyStatus, \"Detach\")\n}","line":{"from":463,"to":488}} {"id":100011917,"name":"waitForVolumeAttachDetachStatusWithLister","signature":"func (c *csiAttacher) waitForVolumeAttachDetachStatusWithLister(spec *volume.Spec, volumeHandle, attachID string, timeout time.Duration, verifyStatus func() (bool, error), operation string) error","file":"pkg/volume/csi/csi_attacher.go","code":"func (c *csiAttacher) waitForVolumeAttachDetachStatusWithLister(spec *volume.Spec, volumeHandle, attachID string, timeout time.Duration, verifyStatus func() (bool, error), operation string) error {\n\tvar (\n\t\tinitBackoff = 500 * time.Millisecond\n\t\t// This is approximately the duration between consecutive ticks after two minutes (CSI timeout).\n\t\tmaxBackoff = 7 * time.Second\n\t\tresetDuration = time.Minute\n\t\tbackoffFactor = 1.05\n\t\tjitter = 0.1\n\t\tclock = \u0026clock.RealClock{}\n\t)\n\tbackoffMgr := wait.NewExponentialBackoffManager(initBackoff, maxBackoff, resetDuration, backoffFactor, jitter, clock)\n\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\tdefer cancel()\n\n\t// Get driver name from spec for better log messages. During detach spec can be nil, and it's ok for driver to be unknown.\n\tcsiDriverName, err := GetCSIDriverName(spec)\n\tif err != nil {\n\t\tcsiDriverName = \"unknown\"\n\t\tklog.V(4).Info(log(\"Could not find CSI driver name in spec for volume [%v]\", volumeHandle))\n\t}\n\n\tfor {\n\t\tt := backoffMgr.Backoff()\n\t\tselect {\n\t\tcase \u003c-t.C():\n\t\t\tsuccessful, err := verifyStatus()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif successful {\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase \u003c-ctx.Done():\n\t\t\tt.Stop()\n\t\t\tklog.Error(log(\"%s timeout after %v [volume=%v; attachment.ID=%v]\", operation, timeout, volumeHandle, attachID))\n\t\t\treturn fmt.Errorf(\"timed out waiting for external-attacher of %v CSI driver to %v volume %v\", csiDriverName, strings.ToLower(operation), volumeHandle)\n\t\t}\n\t}\n}","line":{"from":490,"to":529}} {"id":100011918,"name":"waitForVolumeAttachDetachStatus","signature":"func (c *csiAttacher) waitForVolumeAttachDetachStatus(attach *storage.VolumeAttachment, volumeHandle, attachID string,","file":"pkg/volume/csi/csi_attacher.go","code":"func (c *csiAttacher) waitForVolumeAttachDetachStatus(attach *storage.VolumeAttachment, volumeHandle, attachID string,\n\ttimer *time.Timer, timeout time.Duration, verifyStatus verifyAttachDetachStatus) error {\n\tsuccessful, err := verifyStatus(attach, volumeHandle)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif successful {\n\t\treturn nil\n\t}\n\n\twatcher, err := c.k8s.StorageV1().VolumeAttachments().Watch(context.TODO(), metav1.SingleObject(metav1.ObjectMeta{Name: attachID, ResourceVersion: attach.ResourceVersion}))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"watch error:%v for volume %v\", err, volumeHandle)\n\t}\n\n\tch := watcher.ResultChan()\n\tdefer watcher.Stop()\n\tfor {\n\t\tselect {\n\t\tcase event, ok := \u003c-ch:\n\t\t\tif !ok {\n\t\t\t\tklog.Errorf(\"[attachment.ID=%v] watch channel had been closed\", attachID)\n\t\t\t\treturn errors.New(\"volume attachment watch channel had been closed\")\n\t\t\t}\n\n\t\t\tswitch event.Type {\n\t\t\tcase watch.Added, watch.Modified:\n\t\t\t\tattach, _ := event.Object.(*storage.VolumeAttachment)\n\t\t\t\tsuccessful, err := verifyStatus(attach, volumeHandle)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif successful {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\tcase watch.Deleted:\n\t\t\t\t// set attach nil to get different results\n\t\t\t\t// for detachment, a deleted event means successful detachment, should return success\n\t\t\t\t// for attachment, should return fail\n\t\t\t\tif successful, err := verifyStatus(nil, volumeHandle); !successful {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tklog.V(4).Info(log(\"VolumeAttachment object [%v] for volume [%v] has been deleted\", attachID, volumeHandle))\n\t\t\t\treturn nil\n\n\t\t\tcase watch.Error:\n\t\t\t\tklog.Warningf(\"waitForVolumeAttachDetachInternal received watch error: %v\", event)\n\t\t\t}\n\n\t\tcase \u003c-timer.C:\n\t\t\tklog.Error(log(\"attachdetacher.WaitForDetach timeout after %v [volume=%v; attachment.ID=%v]\", timeout, volumeHandle, attachID))\n\t\t\treturn fmt.Errorf(\"attachdetachment timeout for volume %v\", volumeHandle)\n\t\t}\n\t}\n}","line":{"from":531,"to":585}} {"id":100011919,"name":"UnmountDevice","signature":"func (c *csiAttacher) UnmountDevice(deviceMountPath string) error","file":"pkg/volume/csi/csi_attacher.go","code":"func (c *csiAttacher) UnmountDevice(deviceMountPath string) error {\n\tklog.V(4).Info(log(\"attacher.UnmountDevice(%s)\", deviceMountPath))\n\n\t// Setup\n\tvar driverName, volID string\n\tdataDir := filepath.Dir(deviceMountPath)\n\tdata, err := loadVolumeData(dataDir, volDataFileName)\n\tif err == nil {\n\t\tdriverName = data[volDataKey.driverName]\n\t\tvolID = data[volDataKey.volHandle]\n\t} else {\n\t\tif errors.Is(err, os.ErrNotExist) {\n\t\t\tklog.V(4).Info(log(\"attacher.UnmountDevice skipped because volume data file [%s] does not exist\", dataDir))\n\t\t\treturn nil\n\t\t}\n\n\t\tklog.Errorf(log(\"attacher.UnmountDevice failed to get driver and volume name from device mount path: %v\", err))\n\t\treturn err\n\t}\n\n\tif c.csiClient == nil {\n\t\tc.csiClient, err = newCsiDriverClient(csiDriverName(driverName))\n\t\tif err != nil {\n\t\t\treturn errors.New(log(\"attacher.UnmountDevice failed to create newCsiDriverClient: %v\", err))\n\t\t}\n\t}\n\tcsi := c.csiClient\n\n\t// could not get whether this is migrated because there is no spec\n\tctx, cancel := createCSIOperationContext(nil, csiTimeout)\n\tdefer cancel()\n\t// Check whether \"STAGE_UNSTAGE_VOLUME\" is set\n\tstageUnstageSet, err := csi.NodeSupportsStageUnstage(ctx)\n\tif err != nil {\n\t\treturn errors.New(log(\"attacher.UnmountDevice failed to check whether STAGE_UNSTAGE_VOLUME set: %v\", err))\n\t}\n\tif !stageUnstageSet {\n\t\tklog.Infof(log(\"attacher.UnmountDevice STAGE_UNSTAGE_VOLUME capability not set. Skipping UnmountDevice...\"))\n\t\t// Just\tdelete the global directory + json file\n\t\tif err := removeMountDir(c.plugin, deviceMountPath); err != nil {\n\t\t\treturn errors.New(log(\"failed to clean up global mount %s: %s\", dataDir, err))\n\t\t}\n\n\t\treturn nil\n\t}\n\n\t// Start UnmountDevice\n\terr = csi.NodeUnstageVolume(ctx,\n\t\tvolID,\n\t\tdeviceMountPath)\n\n\tif err != nil {\n\t\treturn errors.New(log(\"attacher.UnmountDevice failed: %v\", err))\n\t}\n\n\t// Delete the global directory + json file\n\tif err := removeMountDir(c.plugin, deviceMountPath); err != nil {\n\t\treturn errors.New(log(\"failed to clean up global mount %s: %s\", dataDir, err))\n\t}\n\n\tklog.V(4).Infof(log(\"attacher.UnmountDevice successfully requested NodeUnStageVolume [%s]\", deviceMountPath))\n\treturn nil\n}","line":{"from":587,"to":649}} {"id":100011920,"name":"getAttachmentName","signature":"func getAttachmentName(volName, csiDriverName, nodeName string) string","file":"pkg/volume/csi/csi_attacher.go","code":"// getAttachmentName returns csi-\u003csha256(volName,csiDriverName,NodeName)\u003e\nfunc getAttachmentName(volName, csiDriverName, nodeName string) string {\n\tresult := sha256.Sum256([]byte(fmt.Sprintf(\"%s%s%s\", volName, csiDriverName, nodeName)))\n\treturn fmt.Sprintf(\"csi-%x\", result)\n}","line":{"from":651,"to":655}} {"id":100011921,"name":"makeDeviceMountPath","signature":"func makeDeviceMountPath(plugin *csiPlugin, spec *volume.Spec) (string, error)","file":"pkg/volume/csi/csi_attacher.go","code":"func makeDeviceMountPath(plugin *csiPlugin, spec *volume.Spec) (string, error) {\n\tif spec == nil {\n\t\treturn \"\", errors.New(\"makeDeviceMountPath failed, spec is nil\")\n\t}\n\n\tdriver, err := GetCSIDriverName(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif driver == \"\" {\n\t\treturn \"\", errors.New(\"makeDeviceMountPath failed, csi source driver name is empty\")\n\t}\n\n\tcsiSource, err := getPVSourceFromSpec(spec)\n\tif err != nil {\n\t\treturn \"\", errors.New(log(\"makeDeviceMountPath failed to get CSIPersistentVolumeSource: %v\", err))\n\t}\n\n\tif csiSource.VolumeHandle == \"\" {\n\t\treturn \"\", errors.New(\"makeDeviceMountPath failed, CSIPersistentVolumeSource volume handle is empty\")\n\t}\n\n\tresult := sha256.Sum256([]byte(fmt.Sprintf(\"%s\", csiSource.VolumeHandle)))\n\tvolSha := fmt.Sprintf(\"%x\", result)\n\treturn filepath.Join(plugin.host.GetPluginDir(plugin.GetPluginName()), driver, volSha, globalMountInGlobalPath), nil\n}","line":{"from":657,"to":682}} {"id":100011922,"name":"verifyAttachmentStatus","signature":"func verifyAttachmentStatus(attachment *storage.VolumeAttachment, volumeHandle string) (bool, error)","file":"pkg/volume/csi/csi_attacher.go","code":"func verifyAttachmentStatus(attachment *storage.VolumeAttachment, volumeHandle string) (bool, error) {\n\t// when we received a deleted event during attachment, fail fast\n\tif attachment == nil {\n\t\tklog.Error(log(\"VolumeAttachment [%s] has been deleted, will not continue to wait for attachment\", volumeHandle))\n\t\treturn false, errors.New(\"volume attachment has been deleted\")\n\t}\n\t// if being deleted, fail fast\n\tif attachment.GetDeletionTimestamp() != nil {\n\t\tklog.Error(log(\"VolumeAttachment [%s] has deletion timestamp, will not continue to wait for attachment\", attachment.Name))\n\t\treturn false, errors.New(\"volume attachment is being deleted\")\n\t}\n\t// attachment OK\n\tif attachment.Status.Attached {\n\t\treturn true, nil\n\t}\n\t// driver reports attach error\n\tattachErr := attachment.Status.AttachError\n\tif attachErr != nil {\n\t\tklog.Error(log(\"attachment for %v failed: %v\", volumeHandle, attachErr.Message))\n\t\treturn false, errors.New(attachErr.Message)\n\t}\n\treturn false, nil\n}","line":{"from":684,"to":706}} {"id":100011923,"name":"verifyDetachmentStatus","signature":"func verifyDetachmentStatus(attachment *storage.VolumeAttachment, volumeHandle string) (bool, error)","file":"pkg/volume/csi/csi_attacher.go","code":"func verifyDetachmentStatus(attachment *storage.VolumeAttachment, volumeHandle string) (bool, error) {\n\t// when we received a deleted event during detachment\n\t// it means we have successfully detached it.\n\tif attachment == nil {\n\t\treturn true, nil\n\t}\n\t// driver reports detach error\n\tdetachErr := attachment.Status.DetachError\n\tif detachErr != nil {\n\t\tklog.Error(log(\"detachment for VolumeAttachment for volume [%s] failed: %v\", volumeHandle, detachErr.Message))\n\t\treturn false, errors.New(detachErr.Message)\n\t}\n\treturn false, nil\n}","line":{"from":708,"to":721}} {"id":100011924,"name":"GetGlobalMapPath","signature":"func (m *csiBlockMapper) GetGlobalMapPath(spec *volume.Spec) (string, error)","file":"pkg/volume/csi/csi_block.go","code":"// GetGlobalMapPath returns a global map path (on the node) to a device file which will be symlinked to\n// Example: plugins/kubernetes.io/csi/volumeDevices/{specName}/dev\nfunc (m *csiBlockMapper) GetGlobalMapPath(spec *volume.Spec) (string, error) {\n\tdir := getVolumeDevicePluginDir(m.specName, m.plugin.host)\n\tklog.V(4).Infof(log(\"blockMapper.GetGlobalMapPath = %s\", dir))\n\treturn dir, nil\n}","line":{"from":104,"to":110}} {"id":100011925,"name":"GetStagingPath","signature":"func (m *csiBlockMapper) GetStagingPath() string","file":"pkg/volume/csi/csi_block.go","code":"// GetStagingPath returns a staging path for a directory (on the node) that should be used on NodeStageVolume/NodeUnstageVolume\n// Example: plugins/kubernetes.io/csi/volumeDevices/staging/{specName}\nfunc (m *csiBlockMapper) GetStagingPath() string {\n\treturn filepath.Join(m.plugin.host.GetVolumeDevicePluginDir(CSIPluginName), \"staging\", m.specName)\n}","line":{"from":112,"to":116}} {"id":100011926,"name":"SupportsMetrics","signature":"func (m *csiBlockMapper) SupportsMetrics() bool","file":"pkg/volume/csi/csi_block.go","code":"// SupportsMetrics returns true for csiBlockMapper as it initializes the\n// MetricsProvider.\nfunc (m *csiBlockMapper) SupportsMetrics() bool {\n\treturn true\n}","line":{"from":118,"to":122}} {"id":100011927,"name":"getPublishDir","signature":"func (m *csiBlockMapper) getPublishDir() string","file":"pkg/volume/csi/csi_block.go","code":"// getPublishDir returns path to a directory, where the volume is published to each pod.\n// Example: plugins/kubernetes.io/csi/volumeDevices/publish/{specName}\nfunc (m *csiBlockMapper) getPublishDir() string {\n\treturn filepath.Join(m.plugin.host.GetVolumeDevicePluginDir(CSIPluginName), \"publish\", m.specName)\n}","line":{"from":124,"to":128}} {"id":100011928,"name":"getPublishPath","signature":"func (m *csiBlockMapper) getPublishPath() string","file":"pkg/volume/csi/csi_block.go","code":"// getPublishPath returns a publish path for a file (on the node) that should be used on NodePublishVolume/NodeUnpublishVolume\n// Example: plugins/kubernetes.io/csi/volumeDevices/publish/{specName}/{podUID}\nfunc (m *csiBlockMapper) getPublishPath() string {\n\treturn filepath.Join(m.getPublishDir(), string(m.podUID))\n}","line":{"from":130,"to":134}} {"id":100011929,"name":"GetPodDeviceMapPath","signature":"func (m *csiBlockMapper) GetPodDeviceMapPath() (string, string)","file":"pkg/volume/csi/csi_block.go","code":"// GetPodDeviceMapPath returns pod's device file which will be mapped to a volume\n// returns: pods/{podUID}/volumeDevices/kubernetes.io~csi, {specName}\nfunc (m *csiBlockMapper) GetPodDeviceMapPath() (string, string) {\n\tpath := m.plugin.host.GetPodVolumeDeviceDir(m.podUID, utilstrings.EscapeQualifiedName(CSIPluginName))\n\tklog.V(4).Infof(log(\"blockMapper.GetPodDeviceMapPath [path=%s; name=%s]\", path, m.specName))\n\treturn path, m.specName\n}","line":{"from":136,"to":142}} {"id":100011930,"name":"stageVolumeForBlock","signature":"func (m *csiBlockMapper) stageVolumeForBlock(","file":"pkg/volume/csi/csi_block.go","code":"// stageVolumeForBlock stages a block volume to stagingPath\nfunc (m *csiBlockMapper) stageVolumeForBlock(\n\tctx context.Context,\n\tcsi csiClient,\n\taccessMode v1.PersistentVolumeAccessMode,\n\tcsiSource *v1.CSIPersistentVolumeSource,\n\tattachment *storage.VolumeAttachment,\n) (string, error) {\n\tklog.V(4).Infof(log(\"blockMapper.stageVolumeForBlock called\"))\n\n\tstagingPath := m.GetStagingPath()\n\tklog.V(4).Infof(log(\"blockMapper.stageVolumeForBlock stagingPath set [%s]\", stagingPath))\n\n\t// Check whether \"STAGE_UNSTAGE_VOLUME\" is set\n\tstageUnstageSet, err := csi.NodeSupportsStageUnstage(ctx)\n\tif err != nil {\n\t\treturn \"\", errors.New(log(\"blockMapper.stageVolumeForBlock failed to check STAGE_UNSTAGE_VOLUME capability: %v\", err))\n\t}\n\tif !stageUnstageSet {\n\t\tklog.Infof(log(\"blockMapper.stageVolumeForBlock STAGE_UNSTAGE_VOLUME capability not set. Skipping MountDevice...\"))\n\t\treturn \"\", nil\n\t}\n\tpublishVolumeInfo := map[string]string{}\n\tif attachment != nil {\n\t\tpublishVolumeInfo = attachment.Status.AttachmentMetadata\n\t}\n\tnodeStageSecrets := map[string]string{}\n\tif csiSource.NodeStageSecretRef != nil {\n\t\tnodeStageSecrets, err = getCredentialsFromSecret(m.k8s, csiSource.NodeStageSecretRef)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to get NodeStageSecretRef %s/%s: %v\",\n\t\t\t\tcsiSource.NodeStageSecretRef.Namespace, csiSource.NodeStageSecretRef.Name, err)\n\t\t}\n\t}\n\n\t// Creating a stagingPath directory before call to NodeStageVolume\n\tif err := os.MkdirAll(stagingPath, 0750); err != nil {\n\t\treturn \"\", errors.New(log(\"blockMapper.stageVolumeForBlock failed to create dir %s: %v\", stagingPath, err))\n\t}\n\tklog.V(4).Info(log(\"blockMapper.stageVolumeForBlock created stagingPath directory successfully [%s]\", stagingPath))\n\n\t// Request to stage a block volume to stagingPath.\n\t// Expected implementation for driver is creating driver specific resource on stagingPath and\n\t// attaching the block volume to the node.\n\terr = csi.NodeStageVolume(ctx,\n\t\tcsiSource.VolumeHandle,\n\t\tpublishVolumeInfo,\n\t\tstagingPath,\n\t\tfsTypeBlockName,\n\t\taccessMode,\n\t\tnodeStageSecrets,\n\t\tcsiSource.VolumeAttributes,\n\t\tnil, /* MountOptions */\n\t\tnil /* fsGroup */)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tklog.V(4).Infof(log(\"blockMapper.stageVolumeForBlock successfully requested NodeStageVolume [%s]\", stagingPath))\n\treturn stagingPath, nil\n}","line":{"from":144,"to":205}} {"id":100011931,"name":"publishVolumeForBlock","signature":"func (m *csiBlockMapper) publishVolumeForBlock(","file":"pkg/volume/csi/csi_block.go","code":"// publishVolumeForBlock publishes a block volume to publishPath\nfunc (m *csiBlockMapper) publishVolumeForBlock(\n\tctx context.Context,\n\tcsi csiClient,\n\taccessMode v1.PersistentVolumeAccessMode,\n\tcsiSource *v1.CSIPersistentVolumeSource,\n\tattachment *storage.VolumeAttachment,\n) (string, error) {\n\tklog.V(4).Infof(log(\"blockMapper.publishVolumeForBlock called\"))\n\n\tpublishVolumeInfo := map[string]string{}\n\tif attachment != nil {\n\t\tpublishVolumeInfo = attachment.Status.AttachmentMetadata\n\t}\n\n\t// Inject pod information into volume_attributes\n\tvolAttribs := csiSource.VolumeAttributes\n\tpodInfoEnabled, err := m.plugin.podInfoEnabled(string(m.driverName))\n\tif err != nil {\n\t\treturn \"\", errors.New(log(\"blockMapper.publishVolumeForBlock failed to assemble volume attributes: %v\", err))\n\t}\n\tvolumeLifecycleMode, err := m.plugin.getVolumeLifecycleMode(m.spec)\n\tif err != nil {\n\t\treturn \"\", errors.New(log(\"blockMapper.publishVolumeForBlock failed to get VolumeLifecycleMode: %v\", err))\n\t}\n\tif podInfoEnabled {\n\t\tvolAttribs = mergeMap(volAttribs, getPodInfoAttrs(m.pod, volumeLifecycleMode))\n\t}\n\n\tnodePublishSecrets := map[string]string{}\n\tif csiSource.NodePublishSecretRef != nil {\n\t\tnodePublishSecrets, err = getCredentialsFromSecret(m.k8s, csiSource.NodePublishSecretRef)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.New(log(\"blockMapper.publishVolumeForBlock failed to get NodePublishSecretRef %s/%s: %v\",\n\t\t\t\tcsiSource.NodePublishSecretRef.Namespace, csiSource.NodePublishSecretRef.Name, err))\n\t\t}\n\t}\n\n\tpublishPath := m.getPublishPath()\n\t// Setup a parent directory for publishPath before call to NodePublishVolume\n\tpublishDir := filepath.Dir(publishPath)\n\tif err := os.MkdirAll(publishDir, 0750); err != nil {\n\t\treturn \"\", errors.New(log(\"blockMapper.publishVolumeForBlock failed to create dir %s: %v\", publishDir, err))\n\t}\n\tklog.V(4).Info(log(\"blockMapper.publishVolumeForBlock created directory for publishPath successfully [%s]\", publishDir))\n\n\t// Request to publish a block volume to publishPath.\n\t// Expectation for driver is to place a block volume on the publishPath, by bind-mounting the device file on the publishPath or\n\t// creating device file on the publishPath.\n\t// Parent directory for publishPath is created by k8s, but driver is responsible for creating publishPath itself.\n\t// If driver doesn't implement NodeStageVolume, attaching the block volume to the node may be done, here.\n\terr = csi.NodePublishVolume(\n\t\tctx,\n\t\tm.volumeID,\n\t\tm.readOnly,\n\t\tm.GetStagingPath(),\n\t\tpublishPath,\n\t\taccessMode,\n\t\tpublishVolumeInfo,\n\t\tvolAttribs,\n\t\tnodePublishSecrets,\n\t\tfsTypeBlockName,\n\t\t[]string{}, /* mountOptions */\n\t\tnil, /* fsGroup */\n\t)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn publishPath, nil\n}","line":{"from":207,"to":278}} {"id":100011932,"name":"SetUpDevice","signature":"func (m *csiBlockMapper) SetUpDevice() (string, error)","file":"pkg/volume/csi/csi_block.go","code":"// SetUpDevice ensures the device is attached returns path where the device is located.\nfunc (m *csiBlockMapper) SetUpDevice() (string, error) {\n\tklog.V(4).Infof(log(\"blockMapper.SetUpDevice called\"))\n\n\t// Get csiSource from spec\n\tif m.spec == nil {\n\t\treturn \"\", errors.New(log(\"blockMapper.SetUpDevice spec is nil\"))\n\t}\n\n\tcsiSource, err := getCSISourceFromSpec(m.spec)\n\tif err != nil {\n\t\treturn \"\", errors.New(log(\"blockMapper.SetUpDevice failed to get CSI persistent source: %v\", err))\n\t}\n\n\tdriverName := csiSource.Driver\n\tskip, err := m.plugin.skipAttach(driverName)\n\tif err != nil {\n\t\treturn \"\", errors.New(log(\"blockMapper.SetupDevice failed to check CSIDriver for %s: %v\", driverName, err))\n\t}\n\n\tvar attachment *storage.VolumeAttachment\n\tif !skip {\n\t\t// Search for attachment by VolumeAttachment.Spec.Source.PersistentVolumeName\n\t\tnodeName := string(m.plugin.host.GetNodeName())\n\t\tattachID := getAttachmentName(csiSource.VolumeHandle, csiSource.Driver, nodeName)\n\t\tattachment, err = m.k8s.StorageV1().VolumeAttachments().Get(context.TODO(), attachID, meta.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn \"\", errors.New(log(\"blockMapper.SetupDevice failed to get volume attachment [id=%v]: %v\", attachID, err))\n\t\t}\n\t}\n\n\t//TODO (vladimirvivien) implement better AccessModes mapping between k8s and CSI\n\taccessMode := v1.ReadWriteOnce\n\tif m.spec.PersistentVolume.Spec.AccessModes != nil {\n\t\taccessMode = m.spec.PersistentVolume.Spec.AccessModes[0]\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), csiTimeout)\n\tdefer cancel()\n\n\tcsiClient, err := m.csiClientGetter.Get()\n\tif err != nil {\n\t\treturn \"\", errors.New(log(\"blockMapper.SetUpDevice failed to get CSI client: %v\", err))\n\t}\n\n\t// Call NodeStageVolume\n\tstagingPath, err := m.stageVolumeForBlock(ctx, csiClient, accessMode, csiSource, attachment)\n\tif err != nil {\n\t\tif volumetypes.IsOperationFinishedError(err) {\n\t\t\tcleanupErr := m.cleanupOrphanDeviceFiles()\n\t\t\tif cleanupErr != nil {\n\t\t\t\t// V(4) for not so serious error\n\t\t\t\tklog.V(4).Infof(\"Failed to clean up block volume directory %s\", cleanupErr)\n\t\t\t}\n\t\t}\n\t\treturn \"\", err\n\t}\n\n\treturn stagingPath, nil\n}","line":{"from":280,"to":339}} {"id":100011933,"name":"MapPodDevice","signature":"func (m *csiBlockMapper) MapPodDevice() (string, error)","file":"pkg/volume/csi/csi_block.go","code":"func (m *csiBlockMapper) MapPodDevice() (string, error) {\n\tklog.V(4).Infof(log(\"blockMapper.MapPodDevice called\"))\n\n\t// Get csiSource from spec\n\tif m.spec == nil {\n\t\treturn \"\", errors.New(log(\"blockMapper.MapPodDevice spec is nil\"))\n\t}\n\n\tcsiSource, err := getCSISourceFromSpec(m.spec)\n\tif err != nil {\n\t\treturn \"\", errors.New(log(\"blockMapper.MapPodDevice failed to get CSI persistent source: %v\", err))\n\t}\n\n\tdriverName := csiSource.Driver\n\tskip, err := m.plugin.skipAttach(driverName)\n\tif err != nil {\n\t\treturn \"\", errors.New(log(\"blockMapper.MapPodDevice failed to check CSIDriver for %s: %v\", driverName, err))\n\t}\n\n\tvar attachment *storage.VolumeAttachment\n\tif !skip {\n\t\t// Search for attachment by VolumeAttachment.Spec.Source.PersistentVolumeName\n\t\tnodeName := string(m.plugin.host.GetNodeName())\n\t\tattachID := getAttachmentName(csiSource.VolumeHandle, csiSource.Driver, nodeName)\n\t\tattachment, err = m.k8s.StorageV1().VolumeAttachments().Get(context.TODO(), attachID, meta.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn \"\", errors.New(log(\"blockMapper.MapPodDevice failed to get volume attachment [id=%v]: %v\", attachID, err))\n\t\t}\n\t}\n\n\t//TODO (vladimirvivien) implement better AccessModes mapping between k8s and CSI\n\taccessMode := v1.ReadWriteOnce\n\tif m.spec.PersistentVolume.Spec.AccessModes != nil {\n\t\taccessMode = m.spec.PersistentVolume.Spec.AccessModes[0]\n\t}\n\n\tctx, cancel := createCSIOperationContext(m.spec, csiTimeout)\n\tdefer cancel()\n\n\tcsiClient, err := m.csiClientGetter.Get()\n\tif err != nil {\n\t\treturn \"\", errors.New(log(\"blockMapper.MapPodDevice failed to get CSI client: %v\", err))\n\t}\n\n\t// Call NodePublishVolume\n\tpublishPath, err := m.publishVolumeForBlock(ctx, csiClient, accessMode, csiSource, attachment)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn publishPath, nil\n}","line":{"from":341,"to":392}} {"id":100011934,"name":"unpublishVolumeForBlock","signature":"func (m *csiBlockMapper) unpublishVolumeForBlock(ctx context.Context, csi csiClient, publishPath string) error","file":"pkg/volume/csi/csi_block.go","code":"// unpublishVolumeForBlock unpublishes a block volume from publishPath\nfunc (m *csiBlockMapper) unpublishVolumeForBlock(ctx context.Context, csi csiClient, publishPath string) error {\n\t// Request to unpublish a block volume from publishPath.\n\t// Expectation for driver is to remove block volume from the publishPath, by unmounting bind-mounted device file\n\t// or deleting device file.\n\t// Driver is responsible for deleting publishPath itself.\n\t// If driver doesn't implement NodeUnstageVolume, detaching the block volume from the node may be done, here.\n\tif err := csi.NodeUnpublishVolume(ctx, m.volumeID, publishPath); err != nil {\n\t\treturn errors.New(log(\"blockMapper.unpublishVolumeForBlock failed: %v\", err))\n\t}\n\tklog.V(4).Infof(log(\"blockMapper.unpublishVolumeForBlock NodeUnpublished successfully [%s]\", publishPath))\n\n\treturn nil\n}","line":{"from":397,"to":410}} {"id":100011935,"name":"unstageVolumeForBlock","signature":"func (m *csiBlockMapper) unstageVolumeForBlock(ctx context.Context, csi csiClient, stagingPath string) error","file":"pkg/volume/csi/csi_block.go","code":"// unstageVolumeForBlock unstages a block volume from stagingPath\nfunc (m *csiBlockMapper) unstageVolumeForBlock(ctx context.Context, csi csiClient, stagingPath string) error {\n\t// Check whether \"STAGE_UNSTAGE_VOLUME\" is set\n\tstageUnstageSet, err := csi.NodeSupportsStageUnstage(ctx)\n\tif err != nil {\n\t\treturn errors.New(log(\"blockMapper.unstageVolumeForBlock failed to check STAGE_UNSTAGE_VOLUME capability: %v\", err))\n\t}\n\tif !stageUnstageSet {\n\t\tklog.Infof(log(\"blockMapper.unstageVolumeForBlock STAGE_UNSTAGE_VOLUME capability not set. Skipping unstageVolumeForBlock ...\"))\n\t\treturn nil\n\t}\n\n\t// Request to unstage a block volume from stagingPath.\n\t// Expected implementation for driver is removing driver specific resource in stagingPath and\n\t// detaching the block volume from the node.\n\tif err := csi.NodeUnstageVolume(ctx, m.volumeID, stagingPath); err != nil {\n\t\treturn errors.New(log(\"blockMapper.unstageVolumeForBlock failed: %v\", err))\n\t}\n\tklog.V(4).Infof(log(\"blockMapper.unstageVolumeForBlock NodeUnstageVolume successfully [%s]\", stagingPath))\n\n\t// Remove stagingPath directory and its contents\n\tif err := os.RemoveAll(stagingPath); err != nil {\n\t\treturn errors.New(log(\"blockMapper.unstageVolumeForBlock failed to remove staging path after NodeUnstageVolume() error [%s]: %v\", stagingPath, err))\n\t}\n\n\treturn nil\n}","line":{"from":412,"to":438}} {"id":100011936,"name":"TearDownDevice","signature":"func (m *csiBlockMapper) TearDownDevice(globalMapPath, devicePath string) error","file":"pkg/volume/csi/csi_block.go","code":"// TearDownDevice removes traces of the SetUpDevice.\nfunc (m *csiBlockMapper) TearDownDevice(globalMapPath, devicePath string) error {\n\tctx, cancel := createCSIOperationContext(m.spec, csiTimeout)\n\tdefer cancel()\n\n\tcsiClient, err := m.csiClientGetter.Get()\n\tif err != nil {\n\t\treturn errors.New(log(\"blockMapper.TearDownDevice failed to get CSI client: %v\", err))\n\t}\n\n\t// Call NodeUnstageVolume\n\tstagingPath := m.GetStagingPath()\n\tif _, err := os.Stat(stagingPath); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tklog.V(4).Infof(log(\"blockMapper.TearDownDevice stagingPath(%s) has already been deleted, skip calling NodeUnstageVolume\", stagingPath))\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\terr := m.unstageVolumeForBlock(ctx, csiClient, stagingPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif err = m.cleanupOrphanDeviceFiles(); err != nil {\n\t\t// V(4) for not so serious error\n\t\tklog.V(4).Infof(\"Failed to clean up block volume directory %s\", err)\n\t}\n\n\treturn nil\n}","line":{"from":440,"to":470}} {"id":100011937,"name":"cleanupOrphanDeviceFiles","signature":"func (m *csiBlockMapper) cleanupOrphanDeviceFiles() error","file":"pkg/volume/csi/csi_block.go","code":"// Clean up any orphan files / directories when a block volume is being unstaged.\n// At this point we can be sure that there is no pod using the volume and all\n// files are indeed orphaned.\nfunc (m *csiBlockMapper) cleanupOrphanDeviceFiles() error {\n\t// Remove artifacts of NodePublish.\n\t// publishDir: xxx/plugins/kubernetes.io/csi/volumeDevices/publish/\u003cvolume name\u003e\n\t// Each PublishVolume() created a subdirectory there. Since everything should be\n\t// already unpublished at this point, the directory should be empty by now.\n\tpublishDir := m.getPublishDir()\n\tif err := os.Remove(publishDir); err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\treturn errors.New(log(\"failed to remove publish directory [%s]: %v\", publishDir, err))\n\t}\n\n\t// Remove artifacts of NodeStage.\n\t// stagingPath: xxx/plugins/kubernetes.io/csi/volumeDevices/staging/\u003cvolume name\u003e\n\tstagingPath := m.GetStagingPath()\n\tif err := os.Remove(stagingPath); err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\treturn errors.New(log(\"failed to delete volume staging path [%s]: %v\", stagingPath, err))\n\t}\n\n\t// Remove everything under xxx/plugins/kubernetes.io/csi/volumeDevices/\u003cvolume name\u003e.\n\t// At this point it contains only \"data/vol_data.json\" and empty \"dev/\".\n\tvolumeDir := getVolumePluginDir(m.specName, m.plugin.host)\n\tmounter := m.plugin.host.GetMounter(m.plugin.GetPluginName())\n\tif err := removeall.RemoveAllOneFilesystem(mounter, volumeDir); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":472,"to":501}} {"id":100011938,"name":"UnmapPodDevice","signature":"func (m *csiBlockMapper) UnmapPodDevice() error","file":"pkg/volume/csi/csi_block.go","code":"// UnmapPodDevice unmaps the block device path.\nfunc (m *csiBlockMapper) UnmapPodDevice() error {\n\tpublishPath := m.getPublishPath()\n\n\tcsiClient, err := m.csiClientGetter.Get()\n\tif err != nil {\n\t\treturn errors.New(log(\"blockMapper.UnmapPodDevice failed to get CSI client: %v\", err))\n\t}\n\n\tctx, cancel := createCSIOperationContext(m.spec, csiTimeout)\n\tdefer cancel()\n\n\t// Call NodeUnpublishVolume.\n\t// Even if publishPath does not exist - previous NodePublish may have timed out\n\t// and Kubernetes makes sure that the operation is finished.\n\treturn m.unpublishVolumeForBlock(ctx, csiClient, publishPath)\n}","line":{"from":503,"to":519}} {"id":100011939,"name":"newV1NodeClient","signature":"func newV1NodeClient(addr csiAddr, metricsManager *MetricsManager) (nodeClient csipbv1.NodeClient, closer io.Closer, err error)","file":"pkg/volume/csi/csi_client.go","code":"// newV1NodeClient creates a new NodeClient with the internally used gRPC\n// connection set up. It also returns a closer which must be called to close\n// the gRPC connection when the NodeClient is not used anymore.\n// This is the default implementation for the nodeV1ClientCreator, used in\n// newCsiDriverClient.\nfunc newV1NodeClient(addr csiAddr, metricsManager *MetricsManager) (nodeClient csipbv1.NodeClient, closer io.Closer, err error) {\n\tvar conn *grpc.ClientConn\n\tconn, err = newGrpcConn(addr, metricsManager)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tnodeClient = csipbv1.NewNodeClient(conn)\n\treturn nodeClient, conn, nil\n}","line":{"from":137,"to":151}} {"id":100011940,"name":"newCsiDriverClient","signature":"func newCsiDriverClient(driverName csiDriverName) (*csiDriverClient, error)","file":"pkg/volume/csi/csi_client.go","code":"func newCsiDriverClient(driverName csiDriverName) (*csiDriverClient, error) {\n\tif driverName == \"\" {\n\t\treturn nil, fmt.Errorf(\"driver name is empty\")\n\t}\n\n\texistingDriver, driverExists := csiDrivers.Get(string(driverName))\n\tif !driverExists {\n\t\treturn nil, fmt.Errorf(\"driver name %s not found in the list of registered CSI drivers\", driverName)\n\t}\n\n\tnodeV1ClientCreator := newV1NodeClient\n\treturn \u0026csiDriverClient{\n\t\tdriverName: driverName,\n\t\taddr: csiAddr(existingDriver.endpoint),\n\t\tnodeV1ClientCreator: nodeV1ClientCreator,\n\t\tmetricsManager: NewCSIMetricsManager(string(driverName)),\n\t}, nil\n}","line":{"from":153,"to":170}} {"id":100011941,"name":"NodeGetInfo","signature":"func (c *csiDriverClient) NodeGetInfo(ctx context.Context) (","file":"pkg/volume/csi/csi_client.go","code":"func (c *csiDriverClient) NodeGetInfo(ctx context.Context) (\n\tnodeID string,\n\tmaxVolumePerNode int64,\n\taccessibleTopology map[string]string,\n\terr error) {\n\tklog.V(4).InfoS(log(\"calling NodeGetInfo rpc\"))\n\n\tvar getNodeInfoError error\n\tnodeID, maxVolumePerNode, accessibleTopology, getNodeInfoError = c.nodeGetInfoV1(ctx)\n\tif getNodeInfoError != nil {\n\t\tklog.InfoS(\"Error calling CSI NodeGetInfo()\", \"err\", getNodeInfoError.Error())\n\t}\n\treturn nodeID, maxVolumePerNode, accessibleTopology, getNodeInfoError\n}","line":{"from":172,"to":185}} {"id":100011942,"name":"nodeGetInfoV1","signature":"func (c *csiDriverClient) nodeGetInfoV1(ctx context.Context) (","file":"pkg/volume/csi/csi_client.go","code":"func (c *csiDriverClient) nodeGetInfoV1(ctx context.Context) (\n\tnodeID string,\n\tmaxVolumePerNode int64,\n\taccessibleTopology map[string]string,\n\terr error) {\n\n\tnodeClient, closer, err := c.nodeV1ClientCreator(c.addr, c.metricsManager)\n\tif err != nil {\n\t\treturn \"\", 0, nil, err\n\t}\n\tdefer closer.Close()\n\n\tres, err := nodeClient.NodeGetInfo(ctx, \u0026csipbv1.NodeGetInfoRequest{})\n\tif err != nil {\n\t\treturn \"\", 0, nil, err\n\t}\n\n\ttopology := res.GetAccessibleTopology()\n\tif topology != nil {\n\t\taccessibleTopology = topology.Segments\n\t}\n\treturn res.GetNodeId(), res.GetMaxVolumesPerNode(), accessibleTopology, nil\n}","line":{"from":187,"to":209}} {"id":100011943,"name":"NodePublishVolume","signature":"func (c *csiDriverClient) NodePublishVolume(","file":"pkg/volume/csi/csi_client.go","code":"func (c *csiDriverClient) NodePublishVolume(\n\tctx context.Context,\n\tvolID string,\n\treadOnly bool,\n\tstagingTargetPath string,\n\ttargetPath string,\n\taccessMode api.PersistentVolumeAccessMode,\n\tpublishContext map[string]string,\n\tvolumeContext map[string]string,\n\tsecrets map[string]string,\n\tfsType string,\n\tmountOptions []string,\n\tfsGroup *int64,\n) error {\n\tklog.V(4).InfoS(log(\"calling NodePublishVolume rpc\"), \"volID\", volID, \"targetPath\", targetPath)\n\tif volID == \"\" {\n\t\treturn errors.New(\"missing volume id\")\n\t}\n\tif targetPath == \"\" {\n\t\treturn errors.New(\"missing target path\")\n\t}\n\n\tif c.nodeV1ClientCreator == nil {\n\t\treturn errors.New(\"failed to call NodePublishVolume. nodeV1ClientCreator is nil\")\n\t}\n\n\taccessModeMapper, err := c.getNodeV1AccessModeMapper(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnodeClient, closer, err := c.nodeV1ClientCreator(c.addr, c.metricsManager)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer closer.Close()\n\n\treq := \u0026csipbv1.NodePublishVolumeRequest{\n\t\tVolumeId: volID,\n\t\tTargetPath: targetPath,\n\t\tReadonly: readOnly,\n\t\tPublishContext: publishContext,\n\t\tVolumeContext: volumeContext,\n\t\tSecrets: secrets,\n\t\tVolumeCapability: \u0026csipbv1.VolumeCapability{\n\t\t\tAccessMode: \u0026csipbv1.VolumeCapability_AccessMode{\n\t\t\t\tMode: accessModeMapper(accessMode),\n\t\t\t},\n\t\t},\n\t}\n\tif stagingTargetPath != \"\" {\n\t\treq.StagingTargetPath = stagingTargetPath\n\t}\n\n\tif fsType == fsTypeBlockName {\n\t\treq.VolumeCapability.AccessType = \u0026csipbv1.VolumeCapability_Block{\n\t\t\tBlock: \u0026csipbv1.VolumeCapability_BlockVolume{},\n\t\t}\n\t} else {\n\t\tmountVolume := \u0026csipbv1.VolumeCapability_MountVolume{\n\t\t\tFsType: fsType,\n\t\t\tMountFlags: mountOptions,\n\t\t}\n\t\tif fsGroup != nil {\n\t\t\tmountVolume.VolumeMountGroup = strconv.FormatInt(*fsGroup, 10 /* base */)\n\t\t}\n\t\treq.VolumeCapability.AccessType = \u0026csipbv1.VolumeCapability_Mount{\n\t\t\tMount: mountVolume,\n\t\t}\n\t}\n\n\t_, err = nodeClient.NodePublishVolume(ctx, req)\n\tif err != nil \u0026\u0026 !isFinalError(err) {\n\t\treturn volumetypes.NewUncertainProgressError(err.Error())\n\t}\n\treturn err\n}","line":{"from":211,"to":287}} {"id":100011944,"name":"NodeExpandVolume","signature":"func (c *csiDriverClient) NodeExpandVolume(ctx context.Context, opts csiResizeOptions) (resource.Quantity, error)","file":"pkg/volume/csi/csi_client.go","code":"func (c *csiDriverClient) NodeExpandVolume(ctx context.Context, opts csiResizeOptions) (resource.Quantity, error) {\n\tif c.nodeV1ClientCreator == nil {\n\t\treturn opts.newSize, fmt.Errorf(\"version of CSI driver does not support volume expansion\")\n\t}\n\n\tif opts.volumeID == \"\" {\n\t\treturn opts.newSize, errors.New(\"missing volume id\")\n\t}\n\tif opts.volumePath == \"\" {\n\t\treturn opts.newSize, errors.New(\"missing volume path\")\n\t}\n\n\tif opts.newSize.Value() \u003c 0 {\n\t\treturn opts.newSize, errors.New(\"size can not be less than 0\")\n\t}\n\n\taccessModeMapper, err := c.getNodeV1AccessModeMapper(ctx)\n\tif err != nil {\n\t\treturn opts.newSize, err\n\t}\n\n\tnodeClient, closer, err := c.nodeV1ClientCreator(c.addr, c.metricsManager)\n\tif err != nil {\n\t\treturn opts.newSize, err\n\t}\n\tdefer closer.Close()\n\n\treq := \u0026csipbv1.NodeExpandVolumeRequest{\n\t\tVolumeId: opts.volumeID,\n\t\tVolumePath: opts.volumePath,\n\t\tCapacityRange: \u0026csipbv1.CapacityRange{RequiredBytes: opts.newSize.Value()},\n\t\tVolumeCapability: \u0026csipbv1.VolumeCapability{\n\t\t\tAccessMode: \u0026csipbv1.VolumeCapability_AccessMode{\n\t\t\t\tMode: accessModeMapper(opts.accessMode),\n\t\t\t},\n\t\t},\n\t\tSecrets: opts.secrets,\n\t}\n\n\t// not all CSI drivers support NodeStageUnstage and hence the StagingTargetPath\n\t// should only be set when available\n\tif opts.stagingTargetPath != \"\" {\n\t\treq.StagingTargetPath = opts.stagingTargetPath\n\t}\n\n\tif opts.fsType == fsTypeBlockName {\n\t\treq.VolumeCapability.AccessType = \u0026csipbv1.VolumeCapability_Block{\n\t\t\tBlock: \u0026csipbv1.VolumeCapability_BlockVolume{},\n\t\t}\n\t} else {\n\t\treq.VolumeCapability.AccessType = \u0026csipbv1.VolumeCapability_Mount{\n\t\t\tMount: \u0026csipbv1.VolumeCapability_MountVolume{\n\t\t\t\tFsType: opts.fsType,\n\t\t\t\tMountFlags: opts.mountOptions,\n\t\t\t},\n\t\t}\n\t}\n\n\tresp, err := nodeClient.NodeExpandVolume(ctx, req)\n\tif err != nil {\n\t\tif !isFinalError(err) {\n\t\t\treturn opts.newSize, volumetypes.NewUncertainProgressError(err.Error())\n\t\t}\n\t\treturn opts.newSize, err\n\t}\n\n\tupdatedQuantity := resource.NewQuantity(resp.CapacityBytes, resource.BinarySI)\n\treturn *updatedQuantity, nil\n}","line":{"from":289,"to":357}} {"id":100011945,"name":"NodeUnpublishVolume","signature":"func (c *csiDriverClient) NodeUnpublishVolume(ctx context.Context, volID string, targetPath string) error","file":"pkg/volume/csi/csi_client.go","code":"func (c *csiDriverClient) NodeUnpublishVolume(ctx context.Context, volID string, targetPath string) error {\n\tklog.V(4).InfoS(log(\"calling NodeUnpublishVolume rpc\"), \"volID\", volID, \"targetPath\", targetPath)\n\tif volID == \"\" {\n\t\treturn errors.New(\"missing volume id\")\n\t}\n\tif targetPath == \"\" {\n\t\treturn errors.New(\"missing target path\")\n\t}\n\tif c.nodeV1ClientCreator == nil {\n\t\treturn errors.New(\"nodeV1ClientCreate is nil\")\n\t}\n\n\tnodeClient, closer, err := c.nodeV1ClientCreator(c.addr, c.metricsManager)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer closer.Close()\n\n\treq := \u0026csipbv1.NodeUnpublishVolumeRequest{\n\t\tVolumeId: volID,\n\t\tTargetPath: targetPath,\n\t}\n\n\t_, err = nodeClient.NodeUnpublishVolume(ctx, req)\n\treturn err\n}","line":{"from":359,"to":384}} {"id":100011946,"name":"NodeStageVolume","signature":"func (c *csiDriverClient) NodeStageVolume(ctx context.Context,","file":"pkg/volume/csi/csi_client.go","code":"func (c *csiDriverClient) NodeStageVolume(ctx context.Context,\n\tvolID string,\n\tpublishContext map[string]string,\n\tstagingTargetPath string,\n\tfsType string,\n\taccessMode api.PersistentVolumeAccessMode,\n\tsecrets map[string]string,\n\tvolumeContext map[string]string,\n\tmountOptions []string,\n\tfsGroup *int64,\n) error {\n\tklog.V(4).InfoS(log(\"calling NodeStageVolume rpc\"), \"volID\", volID, \"stagingTargetPath\", stagingTargetPath)\n\tif volID == \"\" {\n\t\treturn errors.New(\"missing volume id\")\n\t}\n\tif stagingTargetPath == \"\" {\n\t\treturn errors.New(\"missing staging target path\")\n\t}\n\tif c.nodeV1ClientCreator == nil {\n\t\treturn errors.New(\"nodeV1ClientCreate is nil\")\n\t}\n\n\taccessModeMapper, err := c.getNodeV1AccessModeMapper(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnodeClient, closer, err := c.nodeV1ClientCreator(c.addr, c.metricsManager)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer closer.Close()\n\n\treq := \u0026csipbv1.NodeStageVolumeRequest{\n\t\tVolumeId: volID,\n\t\tPublishContext: publishContext,\n\t\tStagingTargetPath: stagingTargetPath,\n\t\tVolumeCapability: \u0026csipbv1.VolumeCapability{\n\t\t\tAccessMode: \u0026csipbv1.VolumeCapability_AccessMode{\n\t\t\t\tMode: accessModeMapper(accessMode),\n\t\t\t},\n\t\t},\n\t\tSecrets: secrets,\n\t\tVolumeContext: volumeContext,\n\t}\n\n\tif fsType == fsTypeBlockName {\n\t\treq.VolumeCapability.AccessType = \u0026csipbv1.VolumeCapability_Block{\n\t\t\tBlock: \u0026csipbv1.VolumeCapability_BlockVolume{},\n\t\t}\n\t} else {\n\t\tmountVolume := \u0026csipbv1.VolumeCapability_MountVolume{\n\t\t\tFsType: fsType,\n\t\t\tMountFlags: mountOptions,\n\t\t}\n\t\tif fsGroup != nil {\n\t\t\tmountVolume.VolumeMountGroup = strconv.FormatInt(*fsGroup, 10 /* base */)\n\t\t}\n\t\treq.VolumeCapability.AccessType = \u0026csipbv1.VolumeCapability_Mount{\n\t\t\tMount: mountVolume,\n\t\t}\n\t}\n\n\t_, err = nodeClient.NodeStageVolume(ctx, req)\n\tif err != nil \u0026\u0026 !isFinalError(err) {\n\t\treturn volumetypes.NewUncertainProgressError(err.Error())\n\t}\n\treturn err\n}","line":{"from":386,"to":454}} {"id":100011947,"name":"NodeUnstageVolume","signature":"func (c *csiDriverClient) NodeUnstageVolume(ctx context.Context, volID, stagingTargetPath string) error","file":"pkg/volume/csi/csi_client.go","code":"func (c *csiDriverClient) NodeUnstageVolume(ctx context.Context, volID, stagingTargetPath string) error {\n\tklog.V(4).InfoS(log(\"calling NodeUnstageVolume rpc\"), \"volID\", volID, \"stagingTargetPath\", stagingTargetPath)\n\tif volID == \"\" {\n\t\treturn errors.New(\"missing volume id\")\n\t}\n\tif stagingTargetPath == \"\" {\n\t\treturn errors.New(\"missing staging target path\")\n\t}\n\tif c.nodeV1ClientCreator == nil {\n\t\treturn errors.New(\"nodeV1ClientCreate is nil\")\n\t}\n\n\tnodeClient, closer, err := c.nodeV1ClientCreator(c.addr, c.metricsManager)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer closer.Close()\n\n\treq := \u0026csipbv1.NodeUnstageVolumeRequest{\n\t\tVolumeId: volID,\n\t\tStagingTargetPath: stagingTargetPath,\n\t}\n\t_, err = nodeClient.NodeUnstageVolume(ctx, req)\n\treturn err\n}","line":{"from":456,"to":480}} {"id":100011948,"name":"NodeSupportsNodeExpand","signature":"func (c *csiDriverClient) NodeSupportsNodeExpand(ctx context.Context) (bool, error)","file":"pkg/volume/csi/csi_client.go","code":"func (c *csiDriverClient) NodeSupportsNodeExpand(ctx context.Context) (bool, error) {\n\treturn c.nodeSupportsCapability(ctx, csipbv1.NodeServiceCapability_RPC_EXPAND_VOLUME)\n}","line":{"from":482,"to":484}} {"id":100011949,"name":"NodeSupportsStageUnstage","signature":"func (c *csiDriverClient) NodeSupportsStageUnstage(ctx context.Context) (bool, error)","file":"pkg/volume/csi/csi_client.go","code":"func (c *csiDriverClient) NodeSupportsStageUnstage(ctx context.Context) (bool, error) {\n\treturn c.nodeSupportsCapability(ctx, csipbv1.NodeServiceCapability_RPC_STAGE_UNSTAGE_VOLUME)\n}","line":{"from":486,"to":488}} {"id":100011950,"name":"getNodeV1AccessModeMapper","signature":"func (c *csiDriverClient) getNodeV1AccessModeMapper(ctx context.Context) (nodeV1AccessModeMapper, error)","file":"pkg/volume/csi/csi_client.go","code":"func (c *csiDriverClient) getNodeV1AccessModeMapper(ctx context.Context) (nodeV1AccessModeMapper, error) {\n\tsupported, err := c.NodeSupportsSingleNodeMultiWriterAccessMode(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif supported {\n\t\treturn asSingleNodeMultiWriterCapableCSIAccessModeV1, nil\n\t}\n\treturn asCSIAccessModeV1, nil\n}","line":{"from":490,"to":499}} {"id":100011951,"name":"asCSIAccessModeV1","signature":"func asCSIAccessModeV1(am api.PersistentVolumeAccessMode) csipbv1.VolumeCapability_AccessMode_Mode","file":"pkg/volume/csi/csi_client.go","code":"func asCSIAccessModeV1(am api.PersistentVolumeAccessMode) csipbv1.VolumeCapability_AccessMode_Mode {\n\tswitch am {\n\tcase api.ReadWriteOnce:\n\t\treturn csipbv1.VolumeCapability_AccessMode_SINGLE_NODE_WRITER\n\tcase api.ReadOnlyMany:\n\t\treturn csipbv1.VolumeCapability_AccessMode_MULTI_NODE_READER_ONLY\n\tcase api.ReadWriteMany:\n\t\treturn csipbv1.VolumeCapability_AccessMode_MULTI_NODE_MULTI_WRITER\n\t// This mapping exists to enable CSI drivers that lack the\n\t// SINGLE_NODE_MULTI_WRITER capability to work with the\n\t// ReadWriteOncePod access mode.\n\tcase api.ReadWriteOncePod:\n\t\treturn csipbv1.VolumeCapability_AccessMode_SINGLE_NODE_WRITER\n\t}\n\treturn csipbv1.VolumeCapability_AccessMode_UNKNOWN\n}","line":{"from":501,"to":516}} {"id":100011952,"name":"asSingleNodeMultiWriterCapableCSIAccessModeV1","signature":"func asSingleNodeMultiWriterCapableCSIAccessModeV1(am api.PersistentVolumeAccessMode) csipbv1.VolumeCapability_AccessMode_Mode","file":"pkg/volume/csi/csi_client.go","code":"func asSingleNodeMultiWriterCapableCSIAccessModeV1(am api.PersistentVolumeAccessMode) csipbv1.VolumeCapability_AccessMode_Mode {\n\tswitch am {\n\tcase api.ReadWriteOnce:\n\t\treturn csipbv1.VolumeCapability_AccessMode_SINGLE_NODE_MULTI_WRITER\n\tcase api.ReadOnlyMany:\n\t\treturn csipbv1.VolumeCapability_AccessMode_MULTI_NODE_READER_ONLY\n\tcase api.ReadWriteMany:\n\t\treturn csipbv1.VolumeCapability_AccessMode_MULTI_NODE_MULTI_WRITER\n\tcase api.ReadWriteOncePod:\n\t\treturn csipbv1.VolumeCapability_AccessMode_SINGLE_NODE_SINGLE_WRITER\n\t}\n\treturn csipbv1.VolumeCapability_AccessMode_UNKNOWN\n}","line":{"from":518,"to":530}} {"id":100011953,"name":"newGrpcConn","signature":"func newGrpcConn(addr csiAddr, metricsManager *MetricsManager) (*grpc.ClientConn, error)","file":"pkg/volume/csi/csi_client.go","code":"func newGrpcConn(addr csiAddr, metricsManager *MetricsManager) (*grpc.ClientConn, error) {\n\tnetwork := \"unix\"\n\tklog.V(4).InfoS(log(\"creating new gRPC connection\"), \"protocol\", network, \"endpoint\", addr)\n\n\treturn grpc.Dial(\n\t\tstring(addr),\n\t\tgrpc.WithAuthority(\"localhost\"),\n\t\tgrpc.WithTransportCredentials(insecure.NewCredentials()),\n\t\tgrpc.WithContextDialer(func(ctx context.Context, target string) (net.Conn, error) {\n\t\t\treturn (\u0026net.Dialer{}).DialContext(ctx, network, target)\n\t\t}),\n\t\tgrpc.WithChainUnaryInterceptor(metricsManager.RecordMetricsInterceptor),\n\t)\n}","line":{"from":532,"to":545}} {"id":100011954,"name":"Get","signature":"func (c *csiClientGetter) Get() (csiClient, error)","file":"pkg/volume/csi/csi_client.go","code":"func (c *csiClientGetter) Get() (csiClient, error) {\n\tc.RLock()\n\tif c.csiClient != nil {\n\t\tc.RUnlock()\n\t\treturn c.csiClient, nil\n\t}\n\tc.RUnlock()\n\tc.Lock()\n\tdefer c.Unlock()\n\t// Double-checking locking criterion.\n\tif c.csiClient != nil {\n\t\treturn c.csiClient, nil\n\t}\n\tcsi, err := newCsiDriverClient(c.driverName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.csiClient = csi\n\treturn c.csiClient, nil\n}","line":{"from":559,"to":578}} {"id":100011955,"name":"NodeSupportsVolumeStats","signature":"func (c *csiDriverClient) NodeSupportsVolumeStats(ctx context.Context) (bool, error)","file":"pkg/volume/csi/csi_client.go","code":"func (c *csiDriverClient) NodeSupportsVolumeStats(ctx context.Context) (bool, error) {\n\treturn c.nodeSupportsCapability(ctx, csipbv1.NodeServiceCapability_RPC_GET_VOLUME_STATS)\n}","line":{"from":580,"to":582}} {"id":100011956,"name":"NodeSupportsSingleNodeMultiWriterAccessMode","signature":"func (c *csiDriverClient) NodeSupportsSingleNodeMultiWriterAccessMode(ctx context.Context) (bool, error)","file":"pkg/volume/csi/csi_client.go","code":"func (c *csiDriverClient) NodeSupportsSingleNodeMultiWriterAccessMode(ctx context.Context) (bool, error) {\n\treturn c.nodeSupportsCapability(ctx, csipbv1.NodeServiceCapability_RPC_SINGLE_NODE_MULTI_WRITER)\n}","line":{"from":584,"to":586}} {"id":100011957,"name":"NodeGetVolumeStats","signature":"func (c *csiDriverClient) NodeGetVolumeStats(ctx context.Context, volID string, targetPath string) (*volume.Metrics, error)","file":"pkg/volume/csi/csi_client.go","code":"func (c *csiDriverClient) NodeGetVolumeStats(ctx context.Context, volID string, targetPath string) (*volume.Metrics, error) {\n\tklog.V(4).InfoS(log(\"calling NodeGetVolumeStats rpc\"), \"volID\", volID, \"targetPath\", targetPath)\n\tif volID == \"\" {\n\t\treturn nil, errors.New(\"missing volume id\")\n\t}\n\tif targetPath == \"\" {\n\t\treturn nil, errors.New(\"missing target path\")\n\t}\n\tif c.nodeV1ClientCreator == nil {\n\t\treturn nil, errors.New(\"nodeV1ClientCreate is nil\")\n\t}\n\n\tnodeClient, closer, err := c.nodeV1ClientCreator(c.addr, c.metricsManager)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer closer.Close()\n\n\treq := \u0026csipbv1.NodeGetVolumeStatsRequest{\n\t\tVolumeId: volID,\n\t\tVolumePath: targetPath,\n\t}\n\n\tresp, err := nodeClient.NodeGetVolumeStats(ctx, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tusages := resp.GetUsage()\n\tif usages == nil {\n\t\treturn nil, fmt.Errorf(\"failed to get usage from response. usage is nil\")\n\t}\n\tmetrics := \u0026volume.Metrics{\n\t\tUsed: resource.NewQuantity(int64(0), resource.BinarySI),\n\t\tCapacity: resource.NewQuantity(int64(0), resource.BinarySI),\n\t\tAvailable: resource.NewQuantity(int64(0), resource.BinarySI),\n\t\tInodesUsed: resource.NewQuantity(int64(0), resource.BinarySI),\n\t\tInodes: resource.NewQuantity(int64(0), resource.BinarySI),\n\t\tInodesFree: resource.NewQuantity(int64(0), resource.BinarySI),\n\t}\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.CSIVolumeHealth) {\n\t\tisSupportNodeVolumeCondition, err := c.nodeSupportsVolumeCondition(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif isSupportNodeVolumeCondition {\n\t\t\tabnormal, message := resp.VolumeCondition.GetAbnormal(), resp.VolumeCondition.GetMessage()\n\t\t\tmetrics.Abnormal, metrics.Message = \u0026abnormal, \u0026message\n\t\t}\n\t}\n\n\tfor _, usage := range usages {\n\t\tif usage == nil {\n\t\t\tcontinue\n\t\t}\n\t\tunit := usage.GetUnit()\n\t\tswitch unit {\n\t\tcase csipbv1.VolumeUsage_BYTES:\n\t\t\tmetrics.Available = resource.NewQuantity(usage.GetAvailable(), resource.BinarySI)\n\t\t\tmetrics.Capacity = resource.NewQuantity(usage.GetTotal(), resource.BinarySI)\n\t\t\tmetrics.Used = resource.NewQuantity(usage.GetUsed(), resource.BinarySI)\n\t\tcase csipbv1.VolumeUsage_INODES:\n\t\t\tmetrics.InodesFree = resource.NewQuantity(usage.GetAvailable(), resource.BinarySI)\n\t\t\tmetrics.Inodes = resource.NewQuantity(usage.GetTotal(), resource.BinarySI)\n\t\t\tmetrics.InodesUsed = resource.NewQuantity(usage.GetUsed(), resource.BinarySI)\n\t\tdefault:\n\t\t\tklog.ErrorS(nil, \"unknown unit in VolumeUsage\", \"unit\", unit.String())\n\t\t}\n\n\t}\n\treturn metrics, nil\n}","line":{"from":588,"to":660}} {"id":100011958,"name":"nodeSupportsVolumeCondition","signature":"func (c *csiDriverClient) nodeSupportsVolumeCondition(ctx context.Context) (bool, error)","file":"pkg/volume/csi/csi_client.go","code":"func (c *csiDriverClient) nodeSupportsVolumeCondition(ctx context.Context) (bool, error) {\n\treturn c.nodeSupportsCapability(ctx, csipbv1.NodeServiceCapability_RPC_VOLUME_CONDITION)\n}","line":{"from":662,"to":664}} {"id":100011959,"name":"NodeSupportsVolumeMountGroup","signature":"func (c *csiDriverClient) NodeSupportsVolumeMountGroup(ctx context.Context) (bool, error)","file":"pkg/volume/csi/csi_client.go","code":"func (c *csiDriverClient) NodeSupportsVolumeMountGroup(ctx context.Context) (bool, error) {\n\treturn c.nodeSupportsCapability(ctx, csipbv1.NodeServiceCapability_RPC_VOLUME_MOUNT_GROUP)\n}","line":{"from":666,"to":668}} {"id":100011960,"name":"nodeSupportsCapability","signature":"func (c *csiDriverClient) nodeSupportsCapability(ctx context.Context, capabilityType csipbv1.NodeServiceCapability_RPC_Type) (bool, error)","file":"pkg/volume/csi/csi_client.go","code":"func (c *csiDriverClient) nodeSupportsCapability(ctx context.Context, capabilityType csipbv1.NodeServiceCapability_RPC_Type) (bool, error) {\n\tklog.V(4).Info(log(\"calling NodeGetCapabilities rpc to determine if the node service has %s capability\", capabilityType))\n\tcapabilities, err := c.nodeGetCapabilities(ctx)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tfor _, capability := range capabilities {\n\t\tif capability == nil || capability.GetRpc() == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif capability.GetRpc().GetType() == capabilityType {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}","line":{"from":670,"to":686}} {"id":100011961,"name":"nodeGetCapabilities","signature":"func (c *csiDriverClient) nodeGetCapabilities(ctx context.Context) ([]*csipbv1.NodeServiceCapability, error)","file":"pkg/volume/csi/csi_client.go","code":"func (c *csiDriverClient) nodeGetCapabilities(ctx context.Context) ([]*csipbv1.NodeServiceCapability, error) {\n\tif c.nodeV1ClientCreator == nil {\n\t\treturn []*csipbv1.NodeServiceCapability{}, errors.New(\"nodeV1ClientCreate is nil\")\n\t}\n\n\tnodeClient, closer, err := c.nodeV1ClientCreator(c.addr, c.metricsManager)\n\tif err != nil {\n\t\treturn []*csipbv1.NodeServiceCapability{}, err\n\t}\n\tdefer closer.Close()\n\n\treq := \u0026csipbv1.NodeGetCapabilitiesRequest{}\n\tresp, err := nodeClient.NodeGetCapabilities(ctx, req)\n\tif err != nil {\n\t\treturn []*csipbv1.NodeServiceCapability{}, err\n\t}\n\treturn resp.GetCapabilities(), nil\n}","line":{"from":688,"to":705}} {"id":100011962,"name":"isFinalError","signature":"func isFinalError(err error) bool","file":"pkg/volume/csi/csi_client.go","code":"func isFinalError(err error) bool {\n\t// Sources:\n\t// https://github.com/grpc/grpc/blob/master/doc/statuscodes.md\n\t// https://github.com/container-storage-interface/spec/blob/master/spec.md\n\tst, ok := status.FromError(err)\n\tif !ok {\n\t\t// This is not gRPC error. The operation must have failed before gRPC\n\t\t// method was called, otherwise we would get gRPC error.\n\t\t// We don't know if any previous volume operation is in progress, be on the safe side.\n\t\treturn false\n\t}\n\tswitch st.Code() {\n\tcase codes.Canceled, // gRPC: Client Application cancelled the request\n\t\tcodes.DeadlineExceeded, // gRPC: Timeout\n\t\tcodes.Unavailable, // gRPC: Server shutting down, TCP connection broken - previous volume operation may be still in progress.\n\t\tcodes.ResourceExhausted, // gRPC: Server temporarily out of resources - previous volume operation may be still in progress.\n\t\tcodes.Aborted: // CSI: Operation pending for volume\n\t\treturn false\n\t}\n\t// All other errors mean that operation either did not\n\t// even start or failed. It is for sure not in progress.\n\treturn true\n}","line":{"from":707,"to":729}} {"id":100011963,"name":"Get","signature":"func (s *DriversStore) Get(driverName string) (Driver, bool)","file":"pkg/volume/csi/csi_drivers_store.go","code":"// Get lets you retrieve a CSI Driver by name.\n// This method is protected by a mutex.\nfunc (s *DriversStore) Get(driverName string) (Driver, bool) {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tdriver, ok := s.store[driverName]\n\treturn driver, ok\n}","line":{"from":40,"to":48}} {"id":100011964,"name":"Set","signature":"func (s *DriversStore) Set(driverName string, driver Driver)","file":"pkg/volume/csi/csi_drivers_store.go","code":"// Set lets you save a CSI Driver to the list and give it a specific name.\n// This method is protected by a mutex.\nfunc (s *DriversStore) Set(driverName string, driver Driver) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tif s.store == nil {\n\t\ts.store = store{}\n\t}\n\n\ts.store[driverName] = driver\n}","line":{"from":50,"to":61}} {"id":100011965,"name":"Delete","signature":"func (s *DriversStore) Delete(driverName string)","file":"pkg/volume/csi/csi_drivers_store.go","code":"// Delete lets you delete a CSI Driver by name.\n// This method is protected by a mutex.\nfunc (s *DriversStore) Delete(driverName string) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tdelete(s.store, driverName)\n}","line":{"from":63,"to":70}} {"id":100011966,"name":"Clear","signature":"func (s *DriversStore) Clear()","file":"pkg/volume/csi/csi_drivers_store.go","code":"// Clear deletes all entries in the store.\n// This methiod is protected by a mutex.\nfunc (s *DriversStore) Clear() {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\ts.store = store{}\n}","line":{"from":72,"to":79}} {"id":100011967,"name":"NewMetricsCsi","signature":"func NewMetricsCsi(volumeID string, targetPath string, driverName csiDriverName) volume.MetricsProvider","file":"pkg/volume/csi/csi_metrics.go","code":"// NewMetricsCsi creates a new metricsCsi with the Volume ID and path.\nfunc NewMetricsCsi(volumeID string, targetPath string, driverName csiDriverName) volume.MetricsProvider {\n\tmc := \u0026metricsCsi{volumeID: volumeID, targetPath: targetPath}\n\tmc.csiClientGetter.driverName = driverName\n\treturn mc\n}","line":{"from":47,"to":52}} {"id":100011968,"name":"GetMetrics","signature":"func (mc *metricsCsi) GetMetrics() (*volume.Metrics, error)","file":"pkg/volume/csi/csi_metrics.go","code":"func (mc *metricsCsi) GetMetrics() (*volume.Metrics, error) {\n\tstartTime := time.Now()\n\tdefer servermetrics.CollectVolumeStatCalDuration(string(mc.csiClientGetter.driverName), startTime)\n\tcurrentTime := metav1.Now()\n\tctx, cancel := context.WithTimeout(context.Background(), csiTimeout)\n\tdefer cancel()\n\t// Get CSI client\n\tcsiClient, err := mc.csiClientGetter.Get()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Check whether \"GET_VOLUME_STATS\" is set\n\tvolumeStatsSet, err := csiClient.NodeSupportsVolumeStats(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// if plugin doesnot support volume status, return.\n\tif !volumeStatsSet {\n\t\treturn nil, volume.NewNotSupportedErrorWithDriverName(\n\t\t\tstring(mc.csiClientGetter.driverName))\n\t}\n\t// Get Volumestatus\n\tmetrics, err := csiClient.NodeGetVolumeStats(ctx, mc.volumeID, mc.targetPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif metrics == nil {\n\t\treturn nil, fmt.Errorf(\"csi.NodeGetVolumeStats returned nil metrics for volume %s\", mc.volumeID)\n\t}\n\t//set recorded time\n\tmetrics.Time = currentTime\n\treturn metrics, nil\n}","line":{"from":54,"to":87}} {"id":100011969,"name":"NewCSIMetricsManager","signature":"func NewCSIMetricsManager(driverName string) *MetricsManager","file":"pkg/volume/csi/csi_metrics.go","code":"// NewCSIMetricsManager creates a CSIMetricsManager object\nfunc NewCSIMetricsManager(driverName string) *MetricsManager {\n\tcmm := MetricsManager{\n\t\tdriverName: driverName,\n\t}\n\treturn \u0026cmm\n}","line":{"from":94,"to":100}} {"id":100011970,"name":"RecordMetricsInterceptor","signature":"func (cmm *MetricsManager) RecordMetricsInterceptor(","file":"pkg/volume/csi/csi_metrics.go","code":"// RecordMetricsInterceptor is a grpc interceptor that is used to\n// record CSI operation\nfunc (cmm *MetricsManager) RecordMetricsInterceptor(\n\tctx context.Context,\n\tmethod string,\n\treq, reply interface{},\n\tcc *grpc.ClientConn,\n\tinvoker grpc.UnaryInvoker,\n\topts ...grpc.CallOption) error {\n\tstart := time.Now()\n\terr := invoker(ctx, method, req, reply, cc, opts...)\n\tduration := time.Since(start)\n\t// Check if this is migrated operation\n\tadditionalInfoVal := ctx.Value(additionalInfoKey)\n\tmigrated := \"false\"\n\tif additionalInfoVal != nil {\n\t\tadditionalInfoVal, ok := additionalInfoVal.(additionalInfo)\n\t\tif !ok {\n\t\t\treturn err\n\t\t}\n\t\tmigrated = additionalInfoVal.Migrated\n\t}\n\t// Record the metric latency\n\tvolumeutil.RecordCSIOperationLatencyMetrics(cmm.driverName, method, err, duration, migrated)\n\n\treturn err\n}","line":{"from":109,"to":135}} {"id":100011971,"name":"GetPath","signature":"func (c *csiMountMgr) GetPath() string","file":"pkg/volume/csi/csi_mounter.go","code":"func (c *csiMountMgr) GetPath() string {\n\tdir := GetCSIMounterPath(filepath.Join(getTargetPath(c.podUID, c.specVolumeID, c.plugin.host)))\n\tklog.V(4).Info(log(\"mounter.GetPath generated [%s]\", dir))\n\treturn dir\n}","line":{"from":85,"to":89}} {"id":100011972,"name":"getTargetPath","signature":"func getTargetPath(uid types.UID, specVolumeID string, host volume.VolumeHost) string","file":"pkg/volume/csi/csi_mounter.go","code":"func getTargetPath(uid types.UID, specVolumeID string, host volume.VolumeHost) string {\n\tspecVolID := utilstrings.EscapeQualifiedName(specVolumeID)\n\treturn host.GetPodVolumeDir(uid, utilstrings.EscapeQualifiedName(CSIPluginName), specVolID)\n}","line":{"from":91,"to":94}} {"id":100011973,"name":"SetUp","signature":"func (c *csiMountMgr) SetUp(mounterArgs volume.MounterArgs) error","file":"pkg/volume/csi/csi_mounter.go","code":"func (c *csiMountMgr) SetUp(mounterArgs volume.MounterArgs) error {\n\treturn c.SetUpAt(c.GetPath(), mounterArgs)\n}","line":{"from":99,"to":101}} {"id":100011974,"name":"SetUpAt","signature":"func (c *csiMountMgr) SetUpAt(dir string, mounterArgs volume.MounterArgs) error","file":"pkg/volume/csi/csi_mounter.go","code":"func (c *csiMountMgr) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {\n\tklog.V(4).Infof(log(\"Mounter.SetUpAt(%s)\", dir))\n\n\tcsi, err := c.csiClientGetter.Get()\n\tif err != nil {\n\t\treturn volumetypes.NewTransientOperationFailure(log(\"mounter.SetUpAt failed to get CSI client: %v\", err))\n\t}\n\n\tctx, cancel := createCSIOperationContext(c.spec, csiTimeout)\n\tdefer cancel()\n\n\tvolSrc, pvSrc, err := getSourceFromSpec(c.spec)\n\tif err != nil {\n\t\treturn errors.New(log(\"mounter.SetupAt failed to get CSI persistent source: %v\", err))\n\t}\n\n\t// Check CSIDriver.Spec.Mode to ensure that the CSI driver\n\t// supports the current volumeLifecycleMode.\n\tif err := c.supportsVolumeLifecycleMode(); err != nil {\n\t\treturn volumetypes.NewTransientOperationFailure(log(\"mounter.SetupAt failed to check volume lifecycle mode: %s\", err))\n\t}\n\n\tfsGroupPolicy, err := c.getFSGroupPolicy()\n\tif err != nil {\n\t\treturn volumetypes.NewTransientOperationFailure(log(\"mounter.SetupAt failed to check fsGroup policy: %s\", err))\n\t}\n\n\tdriverName := c.driverName\n\tvolumeHandle := c.volumeID\n\treadOnly := c.readOnly\n\taccessMode := api.ReadWriteOnce\n\n\tvar (\n\t\tfsType string\n\t\tvolAttribs map[string]string\n\t\tnodePublishSecrets map[string]string\n\t\tpublishContext map[string]string\n\t\tmountOptions []string\n\t\tdeviceMountPath string\n\t\tsecretRef *api.SecretReference\n\t)\n\n\tswitch {\n\tcase volSrc != nil:\n\t\tif c.volumeLifecycleMode != storage.VolumeLifecycleEphemeral {\n\t\t\treturn fmt.Errorf(\"unexpected volume mode: %s\", c.volumeLifecycleMode)\n\t\t}\n\t\tif volSrc.FSType != nil {\n\t\t\tfsType = *volSrc.FSType\n\t\t}\n\n\t\tvolAttribs = volSrc.VolumeAttributes\n\n\t\tif volSrc.NodePublishSecretRef != nil {\n\t\t\tsecretName := volSrc.NodePublishSecretRef.Name\n\t\t\tns := c.pod.Namespace\n\t\t\tsecretRef = \u0026api.SecretReference{Name: secretName, Namespace: ns}\n\t\t}\n\tcase pvSrc != nil:\n\t\tif c.volumeLifecycleMode != storage.VolumeLifecyclePersistent {\n\t\t\treturn fmt.Errorf(\"unexpected driver mode: %s\", c.volumeLifecycleMode)\n\t\t}\n\n\t\tfsType = pvSrc.FSType\n\n\t\tvolAttribs = pvSrc.VolumeAttributes\n\n\t\tif pvSrc.NodePublishSecretRef != nil {\n\t\t\tsecretRef = pvSrc.NodePublishSecretRef\n\t\t}\n\n\t\t//TODO (vladimirvivien) implement better AccessModes mapping between k8s and CSI\n\t\tif c.spec.PersistentVolume.Spec.AccessModes != nil {\n\t\t\taccessMode = c.spec.PersistentVolume.Spec.AccessModes[0]\n\t\t}\n\n\t\tmountOptions = c.spec.PersistentVolume.Spec.MountOptions\n\n\t\t// Check for STAGE_UNSTAGE_VOLUME set and populate deviceMountPath if so\n\t\tstageUnstageSet, err := csi.NodeSupportsStageUnstage(ctx)\n\t\tif err != nil {\n\t\t\treturn errors.New(log(\"mounter.SetUpAt failed to check for STAGE_UNSTAGE_VOLUME capability: %v\", err))\n\t\t}\n\n\t\tif stageUnstageSet {\n\t\t\tdeviceMountPath, err = makeDeviceMountPath(c.plugin, c.spec)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.New(log(\"mounter.SetUpAt failed to make device mount path: %v\", err))\n\t\t\t}\n\t\t}\n\n\t\t// search for attachment by VolumeAttachment.Spec.Source.PersistentVolumeName\n\t\tif c.publishContext == nil {\n\t\t\tnodeName := string(c.plugin.host.GetNodeName())\n\t\t\tc.publishContext, err = c.plugin.getPublishContext(c.k8s, volumeHandle, string(driverName), nodeName)\n\t\t\tif err != nil {\n\t\t\t\t// we could have a transient error associated with fetching publish context\n\t\t\t\treturn volumetypes.NewTransientOperationFailure(log(\"mounter.SetUpAt failed to fetch publishContext: %v\", err))\n\t\t\t}\n\t\t\tpublishContext = c.publishContext\n\t\t}\n\n\tdefault:\n\t\treturn fmt.Errorf(\"volume source not found in volume.Spec\")\n\t}\n\n\t// create target_dir before call to NodePublish\n\tparentDir := filepath.Dir(dir)\n\tif err := os.MkdirAll(parentDir, 0750); err != nil {\n\t\treturn errors.New(log(\"mounter.SetUpAt failed to create dir %#v: %v\", parentDir, err))\n\t}\n\tklog.V(4).Info(log(\"created target path successfully [%s]\", parentDir))\n\n\tnodePublishSecrets = map[string]string{}\n\tif secretRef != nil {\n\t\tnodePublishSecrets, err = getCredentialsFromSecret(c.k8s, secretRef)\n\t\tif err != nil {\n\t\t\treturn volumetypes.NewTransientOperationFailure(fmt.Sprintf(\"fetching NodePublishSecretRef %s/%s failed: %v\",\n\t\t\t\tsecretRef.Namespace, secretRef.Name, err))\n\t\t}\n\n\t}\n\n\t// Inject pod information into volume_attributes\n\tpodInfoEnabled, err := c.plugin.podInfoEnabled(string(c.driverName))\n\tif err != nil {\n\t\treturn volumetypes.NewTransientOperationFailure(log(\"mounter.SetUpAt failed to assemble volume attributes: %v\", err))\n\t}\n\tif podInfoEnabled {\n\t\tvolAttribs = mergeMap(volAttribs, getPodInfoAttrs(c.pod, c.volumeLifecycleMode))\n\t}\n\n\t// Inject pod service account token into volume attributes\n\tserviceAccountTokenAttrs, err := c.podServiceAccountTokenAttrs()\n\tif err != nil {\n\t\treturn volumetypes.NewTransientOperationFailure(log(\"mounter.SetUpAt failed to get service accoount token attributes: %v\", err))\n\t}\n\tvolAttribs = mergeMap(volAttribs, serviceAccountTokenAttrs)\n\n\tdriverSupportsCSIVolumeMountGroup := false\n\tvar nodePublishFSGroupArg *int64\n\tdriverSupportsCSIVolumeMountGroup, err = csi.NodeSupportsVolumeMountGroup(ctx)\n\tif err != nil {\n\t\treturn volumetypes.NewTransientOperationFailure(log(\"mounter.SetUpAt failed to determine if the node service has VOLUME_MOUNT_GROUP capability: %v\", err))\n\t}\n\n\tif driverSupportsCSIVolumeMountGroup {\n\t\tklog.V(3).Infof(\"Driver %s supports applying FSGroup (has VOLUME_MOUNT_GROUP node capability). Delegating FSGroup application to the driver through NodePublishVolume.\", c.driverName)\n\t\tnodePublishFSGroupArg = mounterArgs.FsGroup\n\t}\n\n\tvar selinuxLabelMount bool\n\tif utilfeature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {\n\t\tsupport, err := c.plugin.SupportsSELinuxContextMount(c.spec)\n\t\tif err != nil {\n\t\t\treturn errors.New(log(\"failed to query for SELinuxMount support: %s\", err))\n\t\t}\n\t\tif support \u0026\u0026 mounterArgs.SELinuxLabel != \"\" {\n\t\t\tmountOptions = util.AddSELinuxMountOption(mountOptions, mounterArgs.SELinuxLabel)\n\t\t\tselinuxLabelMount = true\n\t\t}\n\t}\n\n\t// Save volume info in pod dir\n\t// persist volume info data for teardown\n\tnodeName := string(c.plugin.host.GetNodeName())\n\tvolData := map[string]string{\n\t\tvolDataKey.specVolID: c.spec.Name(),\n\t\tvolDataKey.volHandle: volumeHandle,\n\t\tvolDataKey.driverName: string(c.driverName),\n\t\tvolDataKey.nodeName: nodeName,\n\t\tvolDataKey.volumeLifecycleMode: string(c.volumeLifecycleMode),\n\t\tvolDataKey.attachmentID: getAttachmentName(volumeHandle, string(c.driverName), nodeName),\n\t}\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) \u0026\u0026 selinuxLabelMount {\n\t\tvolData[volDataKey.seLinuxMountContext] = mounterArgs.SELinuxLabel\n\t}\n\n\terr = saveVolumeData(parentDir, volDataFileName, volData)\n\tdefer func() {\n\t\t// Only if there was an error and volume operation was considered\n\t\t// finished, we should remove the directory.\n\t\tif err != nil \u0026\u0026 volumetypes.IsOperationFinishedError(err) {\n\t\t\t// attempt to cleanup volume mount dir\n\t\t\tif removeerr := removeMountDir(c.plugin, dir); removeerr != nil {\n\t\t\t\tklog.Error(log(\"mounter.SetUpAt failed to remove mount dir after error [%s]: %v\", dir, removeerr))\n\t\t\t}\n\t\t}\n\t}()\n\tif err != nil {\n\t\terrorMsg := log(\"mounter.SetUpAt failed to save volume info data: %v\", err)\n\t\tklog.Error(errorMsg)\n\t\treturn volumetypes.NewTransientOperationFailure(errorMsg)\n\t}\n\n\terr = csi.NodePublishVolume(\n\t\tctx,\n\t\tvolumeHandle,\n\t\treadOnly,\n\t\tdeviceMountPath,\n\t\tdir,\n\t\taccessMode,\n\t\tpublishContext,\n\t\tvolAttribs,\n\t\tnodePublishSecrets,\n\t\tfsType,\n\t\tmountOptions,\n\t\tnodePublishFSGroupArg,\n\t)\n\n\tif err != nil {\n\t\t// If operation finished with error then we can remove the mount directory.\n\t\tif volumetypes.IsOperationFinishedError(err) {\n\t\t\tif removeMountDirErr := removeMountDir(c.plugin, dir); removeMountDirErr != nil {\n\t\t\t\tklog.Error(log(\"mounter.SetupAt failed to remove mount dir after a NodePublish() error [%s]: %v\", dir, removeMountDirErr))\n\t\t\t}\n\t\t}\n\t\treturn err\n\t}\n\n\tif !selinuxLabelMount {\n\t\tc.needSELinuxRelabel, err = c.kubeVolHost.GetHostUtil().GetSELinuxSupport(dir)\n\t\tif err != nil {\n\t\t\t// The volume is mounted. Return UncertainProgressError, so kubelet will unmount it when user deletes the pod.\n\t\t\treturn volumetypes.NewUncertainProgressError(fmt.Sprintf(\"error checking for SELinux support: %s\", err))\n\t\t}\n\t}\n\n\tif !driverSupportsCSIVolumeMountGroup \u0026\u0026 c.supportsFSGroup(fsType, mounterArgs.FsGroup, fsGroupPolicy) {\n\t\t// Driver doesn't support applying FSGroup. Kubelet must apply it instead.\n\n\t\t// fullPluginName helps to distinguish different driver from csi plugin\n\t\terr := volume.SetVolumeOwnership(c, dir, mounterArgs.FsGroup, mounterArgs.FSGroupChangePolicy, util.FSGroupCompleteHook(c.plugin, c.spec))\n\t\tif err != nil {\n\t\t\t// At this point mount operation is successful:\n\t\t\t// 1. Since volume can not be used by the pod because of invalid permissions, we must return error\n\t\t\t// 2. Since mount is successful, we must record volume as mounted in uncertain state, so it can be\n\t\t\t// cleaned up.\n\t\t\treturn volumetypes.NewUncertainProgressError(fmt.Sprintf(\"applyFSGroup failed for vol %s: %v\", c.volumeID, err))\n\t\t}\n\t\tklog.V(4).Info(log(\"mounter.SetupAt fsGroup [%d] applied successfully to %s\", *mounterArgs.FsGroup, c.volumeID))\n\t}\n\n\tklog.V(4).Infof(log(\"mounter.SetUp successfully requested NodePublish [%s]\", dir))\n\treturn nil\n}","line":{"from":103,"to":349}} {"id":100011975,"name":"podServiceAccountTokenAttrs","signature":"func (c *csiMountMgr) podServiceAccountTokenAttrs() (map[string]string, error)","file":"pkg/volume/csi/csi_mounter.go","code":"func (c *csiMountMgr) podServiceAccountTokenAttrs() (map[string]string, error) {\n\tif c.plugin.serviceAccountTokenGetter == nil {\n\t\treturn nil, errors.New(\"ServiceAccountTokenGetter is nil\")\n\t}\n\n\tcsiDriver, err := c.plugin.csiDriverLister.Get(string(c.driverName))\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\tklog.V(5).Infof(log(\"CSIDriver %q not found, not adding service account token information\", c.driverName))\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tif len(csiDriver.Spec.TokenRequests) == 0 {\n\t\treturn nil, nil\n\t}\n\n\toutputs := map[string]authenticationv1.TokenRequestStatus{}\n\tfor _, tokenRequest := range csiDriver.Spec.TokenRequests {\n\t\taudience := tokenRequest.Audience\n\t\taudiences := []string{audience}\n\t\tif audience == \"\" {\n\t\t\taudiences = []string{}\n\t\t}\n\t\ttr, err := c.plugin.serviceAccountTokenGetter(c.pod.Namespace, c.pod.Spec.ServiceAccountName, \u0026authenticationv1.TokenRequest{\n\t\t\tSpec: authenticationv1.TokenRequestSpec{\n\t\t\t\tAudiences: audiences,\n\t\t\t\tExpirationSeconds: tokenRequest.ExpirationSeconds,\n\t\t\t\tBoundObjectRef: \u0026authenticationv1.BoundObjectReference{\n\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t\tKind: \"Pod\",\n\t\t\t\t\tName: c.pod.Name,\n\t\t\t\t\tUID: c.pod.UID,\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\toutputs[audience] = tr.Status\n\t}\n\n\tklog.V(4).Infof(log(\"Fetched service account token attrs for CSIDriver %q\", c.driverName))\n\ttokens, _ := json.Marshal(outputs)\n\treturn map[string]string{\n\t\t\"csi.storage.k8s.io/serviceAccount.tokens\": string(tokens),\n\t}, nil\n}","line":{"from":351,"to":400}} {"id":100011976,"name":"GetAttributes","signature":"func (c *csiMountMgr) GetAttributes() volume.Attributes","file":"pkg/volume/csi/csi_mounter.go","code":"func (c *csiMountMgr) GetAttributes() volume.Attributes {\n\treturn volume.Attributes{\n\t\tReadOnly: c.readOnly,\n\t\tManaged: !c.readOnly,\n\t\tSELinuxRelabel: c.needSELinuxRelabel,\n\t}\n}","line":{"from":402,"to":408}} {"id":100011977,"name":"TearDown","signature":"func (c *csiMountMgr) TearDown() error","file":"pkg/volume/csi/csi_mounter.go","code":"func (c *csiMountMgr) TearDown() error {\n\treturn c.TearDownAt(c.GetPath())\n}","line":{"from":413,"to":415}} {"id":100011978,"name":"TearDownAt","signature":"func (c *csiMountMgr) TearDownAt(dir string) error","file":"pkg/volume/csi/csi_mounter.go","code":"func (c *csiMountMgr) TearDownAt(dir string) error {\n\tklog.V(4).Infof(log(\"Unmounter.TearDownAt(%s)\", dir))\n\n\tvolID := c.volumeID\n\tcsi, err := c.csiClientGetter.Get()\n\tif err != nil {\n\t\treturn errors.New(log(\"Unmounter.TearDownAt failed to get CSI client: %v\", err))\n\t}\n\n\t// Could not get spec info on whether this is a migrated operation because c.spec is nil\n\tctx, cancel := createCSIOperationContext(c.spec, csiTimeout)\n\tdefer cancel()\n\n\tif err := csi.NodeUnpublishVolume(ctx, volID, dir); err != nil {\n\t\treturn errors.New(log(\"Unmounter.TearDownAt failed: %v\", err))\n\t}\n\n\t// Deprecation: Removal of target_path provided in the NodePublish RPC call\n\t// (in this case location `dir`) MUST be done by the CSI plugin according\n\t// to the spec. This will no longer be done directly as part of TearDown\n\t// by the kubelet in the future. Kubelet will only be responsible for\n\t// removal of json data files it creates and parent directories.\n\tif err := removeMountDir(c.plugin, dir); err != nil {\n\t\treturn errors.New(log(\"Unmounter.TearDownAt failed to clean mount dir [%s]: %v\", dir, err))\n\t}\n\tklog.V(4).Infof(log(\"Unmounter.TearDownAt successfully unmounted dir [%s]\", dir))\n\n\treturn nil\n}","line":{"from":416,"to":444}} {"id":100011979,"name":"supportsFSGroup","signature":"func (c *csiMountMgr) supportsFSGroup(fsType string, fsGroup *int64, driverPolicy storage.FSGroupPolicy) bool","file":"pkg/volume/csi/csi_mounter.go","code":"func (c *csiMountMgr) supportsFSGroup(fsType string, fsGroup *int64, driverPolicy storage.FSGroupPolicy) bool {\n\tif fsGroup == nil || driverPolicy == storage.NoneFSGroupPolicy || c.readOnly {\n\t\treturn false\n\t}\n\n\tif driverPolicy == storage.FileFSGroupPolicy {\n\t\treturn true\n\t}\n\n\tif fsType == \"\" {\n\t\tklog.V(4).Info(log(\"mounter.SetupAt WARNING: skipping fsGroup, fsType not provided\"))\n\t\treturn false\n\t}\n\n\tif c.spec.PersistentVolume != nil {\n\t\tif c.spec.PersistentVolume.Spec.AccessModes == nil {\n\t\t\tklog.V(4).Info(log(\"mounter.SetupAt WARNING: skipping fsGroup, access modes not provided\"))\n\t\t\treturn false\n\t\t}\n\t\tif !hasReadWriteOnce(c.spec.PersistentVolume.Spec.AccessModes) {\n\t\t\tklog.V(4).Info(log(\"mounter.SetupAt WARNING: skipping fsGroup, only support ReadWriteOnce access mode\"))\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t} else if c.spec.Volume != nil \u0026\u0026 c.spec.Volume.CSI != nil {\n\t\t// Inline CSI volumes are always mounted with RWO AccessMode by SetUpAt\n\t\treturn true\n\t}\n\n\tklog.V(4).Info(log(\"mounter.SetupAt WARNING: skipping fsGroup, unsupported volume type\"))\n\treturn false\n}","line":{"from":446,"to":477}} {"id":100011980,"name":"getFSGroupPolicy","signature":"func (c *csiMountMgr) getFSGroupPolicy() (storage.FSGroupPolicy, error)","file":"pkg/volume/csi/csi_mounter.go","code":"// getFSGroupPolicy returns if the CSI driver supports a volume in the given mode.\n// An error indicates that it isn't supported and explains why.\nfunc (c *csiMountMgr) getFSGroupPolicy() (storage.FSGroupPolicy, error) {\n\t// Retrieve CSIDriver. It's not an error if that isn't\n\t// possible (we don't have the lister if CSIDriverRegistry is\n\t// disabled) or the driver isn't found (CSIDriver is\n\t// optional)\n\tvar csiDriver *storage.CSIDriver\n\tdriver := string(c.driverName)\n\tif c.plugin.csiDriverLister != nil {\n\t\tc, err := c.plugin.getCSIDriver(driver)\n\t\tif err != nil \u0026\u0026 !apierrors.IsNotFound(err) {\n\t\t\t// Some internal error.\n\t\t\treturn storage.ReadWriteOnceWithFSTypeFSGroupPolicy, err\n\t\t}\n\t\tcsiDriver = c\n\t}\n\n\t// If the csiDriver isn't defined, return the default behavior\n\tif csiDriver == nil {\n\t\treturn storage.ReadWriteOnceWithFSTypeFSGroupPolicy, nil\n\t}\n\t// If the csiDriver exists but the fsGroupPolicy isn't defined, return an error\n\tif csiDriver.Spec.FSGroupPolicy == nil || *csiDriver.Spec.FSGroupPolicy == \"\" {\n\t\treturn storage.ReadWriteOnceWithFSTypeFSGroupPolicy, errors.New(log(\"expected valid fsGroupPolicy, received nil value or empty string\"))\n\t}\n\treturn *csiDriver.Spec.FSGroupPolicy, nil\n}","line":{"from":479,"to":506}} {"id":100011981,"name":"supportsVolumeLifecycleMode","signature":"func (c *csiMountMgr) supportsVolumeLifecycleMode() error","file":"pkg/volume/csi/csi_mounter.go","code":"// supportsVolumeMode checks whether the CSI driver supports a volume in the given mode.\n// An error indicates that it isn't supported and explains why.\nfunc (c *csiMountMgr) supportsVolumeLifecycleMode() error {\n\t// Retrieve CSIDriver. It's not an error if that isn't\n\t// possible (we don't have the lister if CSIDriverRegistry is\n\t// disabled) or the driver isn't found (CSIDriver is\n\t// optional), but then only persistent volumes are supported.\n\tvar csiDriver *storage.CSIDriver\n\tdriver := string(c.driverName)\n\tif c.plugin.csiDriverLister != nil {\n\t\tc, err := c.plugin.getCSIDriver(driver)\n\t\tif err != nil \u0026\u0026 !apierrors.IsNotFound(err) {\n\t\t\t// Some internal error.\n\t\t\treturn err\n\t\t}\n\t\tcsiDriver = c\n\t}\n\n\t// The right response depends on whether we have information\n\t// about the driver and the volume mode.\n\tswitch {\n\tcase csiDriver == nil \u0026\u0026 c.volumeLifecycleMode == storage.VolumeLifecyclePersistent:\n\t\t// No information, but that's okay for persistent volumes (and only those).\n\t\treturn nil\n\tcase csiDriver == nil:\n\t\treturn fmt.Errorf(\"volume mode %q not supported by driver %s (no CSIDriver object)\", c.volumeLifecycleMode, driver)\n\tcase containsVolumeMode(csiDriver.Spec.VolumeLifecycleModes, c.volumeLifecycleMode):\n\t\t// Explicitly listed.\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"volume mode %q not supported by driver %s (only supports %q)\", c.volumeLifecycleMode, driver, csiDriver.Spec.VolumeLifecycleModes)\n\t}\n}","line":{"from":508,"to":540}} {"id":100011982,"name":"containsVolumeMode","signature":"func containsVolumeMode(modes []storage.VolumeLifecycleMode, mode storage.VolumeLifecycleMode) bool","file":"pkg/volume/csi/csi_mounter.go","code":"// containsVolumeMode checks whether the given volume mode is listed.\nfunc containsVolumeMode(modes []storage.VolumeLifecycleMode, mode storage.VolumeLifecycleMode) bool {\n\tfor _, m := range modes {\n\t\tif m == mode {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":542,"to":550}} {"id":100011983,"name":"isDirMounted","signature":"func isDirMounted(plug *csiPlugin, dir string) (bool, error)","file":"pkg/volume/csi/csi_mounter.go","code":"// isDirMounted returns the !notMounted result from IsLikelyNotMountPoint check\nfunc isDirMounted(plug *csiPlugin, dir string) (bool, error) {\n\tmounter := plug.host.GetMounter(plug.GetPluginName())\n\tnotMnt, err := mounter.IsLikelyNotMountPoint(dir)\n\tif err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\tklog.Error(log(\"isDirMounted IsLikelyNotMountPoint test failed for dir [%v]\", dir))\n\t\treturn false, err\n\t}\n\treturn !notMnt, nil\n}","line":{"from":552,"to":561}} {"id":100011984,"name":"isCorruptedDir","signature":"func isCorruptedDir(dir string) bool","file":"pkg/volume/csi/csi_mounter.go","code":"func isCorruptedDir(dir string) bool {\n\t_, pathErr := mount.PathExists(dir)\n\treturn pathErr != nil \u0026\u0026 mount.IsCorruptedMnt(pathErr)\n}","line":{"from":563,"to":566}} {"id":100011985,"name":"removeMountDir","signature":"func removeMountDir(plug *csiPlugin, mountPath string) error","file":"pkg/volume/csi/csi_mounter.go","code":"// removeMountDir cleans the mount dir when dir is not mounted and removed the volume data file in dir\nfunc removeMountDir(plug *csiPlugin, mountPath string) error {\n\tklog.V(4).Info(log(\"removing mount path [%s]\", mountPath))\n\n\tmnt, err := isDirMounted(plug, mountPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !mnt {\n\t\tklog.V(4).Info(log(\"dir not mounted, deleting it [%s]\", mountPath))\n\t\tif err := os.Remove(mountPath); err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\t\treturn errors.New(log(\"failed to remove dir [%s]: %v\", mountPath, err))\n\t\t}\n\t\t// remove volume data file as well\n\t\tvolPath := filepath.Dir(mountPath)\n\t\tdataFile := filepath.Join(volPath, volDataFileName)\n\t\tklog.V(4).Info(log(\"also deleting volume info data file [%s]\", dataFile))\n\t\tif err := os.Remove(dataFile); err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\t\treturn errors.New(log(\"failed to delete volume data file [%s]: %v\", dataFile, err))\n\t\t}\n\t\t// remove volume path\n\t\tklog.V(4).Info(log(\"deleting volume path [%s]\", volPath))\n\t\tif err := os.Remove(volPath); err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\t\treturn errors.New(log(\"failed to delete volume path [%s]: %v\", volPath, err))\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":568,"to":595}} {"id":100011986,"name":"makeVolumeHandle","signature":"func makeVolumeHandle(podUID, volSourceSpecName string) string","file":"pkg/volume/csi/csi_mounter.go","code":"// makeVolumeHandle returns csi-\u003csha256(podUID,volSourceSpecName)\u003e\nfunc makeVolumeHandle(podUID, volSourceSpecName string) string {\n\tresult := sha256.Sum256([]byte(fmt.Sprintf(\"%s%s\", podUID, volSourceSpecName)))\n\treturn fmt.Sprintf(\"csi-%x\", result)\n}","line":{"from":597,"to":601}} {"id":100011987,"name":"mergeMap","signature":"func mergeMap(first, second map[string]string) map[string]string","file":"pkg/volume/csi/csi_mounter.go","code":"func mergeMap(first, second map[string]string) map[string]string {\n\tif first == nil {\n\t\treturn second\n\t}\n\tfor k, v := range second {\n\t\tfirst[k] = v\n\t}\n\treturn first\n}","line":{"from":603,"to":611}} {"id":100011988,"name":"ProbeVolumePlugins","signature":"func ProbeVolumePlugins() []volume.VolumePlugin","file":"pkg/volume/csi/csi_plugin.go","code":"// ProbeVolumePlugins returns implemented plugins\nfunc ProbeVolumePlugins() []volume.VolumePlugin {\n\tp := \u0026csiPlugin{\n\t\thost: nil,\n\t}\n\treturn []volume.VolumePlugin{p}\n}","line":{"from":70,"to":76}} {"id":100011989,"name":"ValidatePlugin","signature":"func (h *RegistrationHandler) ValidatePlugin(pluginName string, endpoint string, versions []string) error","file":"pkg/volume/csi/csi_plugin.go","code":"// ValidatePlugin is called by kubelet's plugin watcher upon detection\n// of a new registration socket opened by CSI Driver registrar side car.\nfunc (h *RegistrationHandler) ValidatePlugin(pluginName string, endpoint string, versions []string) error {\n\tklog.Infof(log(\"Trying to validate a new CSI Driver with name: %s endpoint: %s versions: %s\",\n\t\tpluginName, endpoint, strings.Join(versions, \",\")))\n\n\t_, err := h.validateVersions(\"ValidatePlugin\", pluginName, endpoint, versions)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"validation failed for CSI Driver %s at endpoint %s: %v\", pluginName, endpoint, err)\n\t}\n\n\treturn err\n}","line":{"from":96,"to":108}} {"id":100011990,"name":"RegisterPlugin","signature":"func (h *RegistrationHandler) RegisterPlugin(pluginName string, endpoint string, versions []string) error","file":"pkg/volume/csi/csi_plugin.go","code":"// RegisterPlugin is called when a plugin can be registered\nfunc (h *RegistrationHandler) RegisterPlugin(pluginName string, endpoint string, versions []string) error {\n\tklog.Infof(log(\"Register new plugin with name: %s at endpoint: %s\", pluginName, endpoint))\n\n\thighestSupportedVersion, err := h.validateVersions(\"RegisterPlugin\", pluginName, endpoint, versions)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Storing endpoint of newly registered CSI driver into the map, where CSI driver name will be the key\n\t// all other CSI components will be able to get the actual socket of CSI drivers by its name.\n\tcsiDrivers.Set(pluginName, Driver{\n\t\tendpoint: endpoint,\n\t\thighestSupportedVersion: highestSupportedVersion,\n\t})\n\n\t// Get node info from the driver.\n\tcsi, err := newCsiDriverClient(csiDriverName(pluginName))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), csiTimeout)\n\tdefer cancel()\n\n\tdriverNodeID, maxVolumePerNode, accessibleTopology, err := csi.NodeGetInfo(ctx)\n\tif err != nil {\n\t\tif unregErr := unregisterDriver(pluginName); unregErr != nil {\n\t\t\tklog.Error(log(\"registrationHandler.RegisterPlugin failed to unregister plugin due to previous error: %v\", unregErr))\n\t\t}\n\t\treturn err\n\t}\n\n\terr = nim.InstallCSIDriver(pluginName, driverNodeID, maxVolumePerNode, accessibleTopology)\n\tif err != nil {\n\t\tif unregErr := unregisterDriver(pluginName); unregErr != nil {\n\t\t\tklog.Error(log(\"registrationHandler.RegisterPlugin failed to unregister plugin due to previous error: %v\", unregErr))\n\t\t}\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":110,"to":152}} {"id":100011991,"name":"validateVersions","signature":"func (h *RegistrationHandler) validateVersions(callerName, pluginName string, endpoint string, versions []string) (*utilversion.Version, error)","file":"pkg/volume/csi/csi_plugin.go","code":"func (h *RegistrationHandler) validateVersions(callerName, pluginName string, endpoint string, versions []string) (*utilversion.Version, error) {\n\tif len(versions) == 0 {\n\t\treturn nil, errors.New(log(\"%s for CSI driver %q failed. Plugin returned an empty list for supported versions\", callerName, pluginName))\n\t}\n\n\t// Validate version\n\tnewDriverHighestVersion, err := highestSupportedVersion(versions)\n\tif err != nil {\n\t\treturn nil, errors.New(log(\"%s for CSI driver %q failed. None of the versions specified %q are supported. err=%v\", callerName, pluginName, versions, err))\n\t}\n\n\texistingDriver, driverExists := csiDrivers.Get(pluginName)\n\tif driverExists {\n\t\tif !existingDriver.highestSupportedVersion.LessThan(newDriverHighestVersion) {\n\t\t\treturn nil, errors.New(log(\"%s for CSI driver %q failed. Another driver with the same name is already registered with a higher supported version: %q\", callerName, pluginName, existingDriver.highestSupportedVersion))\n\t\t}\n\t}\n\n\treturn newDriverHighestVersion, nil\n}","line":{"from":154,"to":173}} {"id":100011992,"name":"DeRegisterPlugin","signature":"func (h *RegistrationHandler) DeRegisterPlugin(pluginName string)","file":"pkg/volume/csi/csi_plugin.go","code":"// DeRegisterPlugin is called when a plugin removed its socket, signaling\n// it is no longer available\nfunc (h *RegistrationHandler) DeRegisterPlugin(pluginName string) {\n\tklog.Info(log(\"registrationHandler.DeRegisterPlugin request for plugin %s\", pluginName))\n\tif err := unregisterDriver(pluginName); err != nil {\n\t\tklog.Error(log(\"registrationHandler.DeRegisterPlugin failed: %v\", err))\n\t}\n}","line":{"from":175,"to":182}} {"id":100011993,"name":"Init","signature":"func (p *csiPlugin) Init(host volume.VolumeHost) error","file":"pkg/volume/csi/csi_plugin.go","code":"func (p *csiPlugin) Init(host volume.VolumeHost) error {\n\tp.host = host\n\n\tcsiClient := host.GetKubeClient()\n\tif csiClient == nil {\n\t\tklog.Warning(log(\"kubeclient not set, assuming standalone kubelet\"))\n\t} else {\n\t\t// set CSIDriverLister and volumeAttachmentLister\n\t\tadcHost, ok := host.(volume.AttachDetachVolumeHost)\n\t\tif ok {\n\t\t\tp.csiDriverLister = adcHost.CSIDriverLister()\n\t\t\tif p.csiDriverLister == nil {\n\t\t\t\tklog.Error(log(\"CSIDriverLister not found on AttachDetachVolumeHost\"))\n\t\t\t}\n\t\t\tp.volumeAttachmentLister = adcHost.VolumeAttachmentLister()\n\t\t\tif p.volumeAttachmentLister == nil {\n\t\t\t\tklog.Error(log(\"VolumeAttachmentLister not found on AttachDetachVolumeHost\"))\n\t\t\t}\n\t\t}\n\t\tkletHost, ok := host.(volume.KubeletVolumeHost)\n\t\tif ok {\n\t\t\tp.csiDriverLister = kletHost.CSIDriverLister()\n\t\t\tif p.csiDriverLister == nil {\n\t\t\t\tklog.Error(log(\"CSIDriverLister not found on KubeletVolumeHost\"))\n\t\t\t}\n\t\t\tp.serviceAccountTokenGetter = host.GetServiceAccountTokenFunc()\n\t\t\tif p.serviceAccountTokenGetter == nil {\n\t\t\t\tklog.Error(log(\"ServiceAccountTokenGetter not found on KubeletVolumeHost\"))\n\t\t\t}\n\t\t\t// We don't run the volumeAttachmentLister in the kubelet context\n\t\t\tp.volumeAttachmentLister = nil\n\t\t}\n\t}\n\n\tvar migratedPlugins = map[string](func() bool){\n\t\tcsitranslationplugins.GCEPDInTreePluginName: func() bool {\n\t\t\treturn utilfeature.DefaultFeatureGate.Enabled(features.CSIMigrationGCE)\n\t\t},\n\t\tcsitranslationplugins.AWSEBSInTreePluginName: func() bool {\n\t\t\treturn true\n\t\t},\n\t\tcsitranslationplugins.CinderInTreePluginName: func() bool {\n\t\t\treturn true\n\t\t},\n\t\tcsitranslationplugins.AzureDiskInTreePluginName: func() bool {\n\t\t\treturn true\n\t\t},\n\t\tcsitranslationplugins.AzureFileInTreePluginName: func() bool {\n\t\t\treturn utilfeature.DefaultFeatureGate.Enabled(features.CSIMigrationAzureFile)\n\t\t},\n\t\tcsitranslationplugins.VSphereInTreePluginName: func() bool {\n\t\t\treturn utilfeature.DefaultFeatureGate.Enabled(features.CSIMigrationvSphere)\n\t\t},\n\t\tcsitranslationplugins.PortworxVolumePluginName: func() bool {\n\t\t\treturn utilfeature.DefaultFeatureGate.Enabled(features.CSIMigrationPortworx)\n\t\t},\n\t\tcsitranslationplugins.RBDVolumePluginName: func() bool {\n\t\t\treturn utilfeature.DefaultFeatureGate.Enabled(features.CSIMigrationRBD)\n\t\t},\n\t}\n\n\t// Initializing the label management channels\n\tnim = nodeinfomanager.NewNodeInfoManager(host.GetNodeName(), host, migratedPlugins)\n\n\t// This function prevents Kubelet from posting Ready status until CSINode\n\t// is both installed and initialized\n\tif err := initializeCSINode(host); err != nil {\n\t\treturn errors.New(log(\"failed to initialize CSINode: %v\", err))\n\t}\n\n\treturn nil\n}","line":{"from":184,"to":255}} {"id":100011994,"name":"initializeCSINode","signature":"func initializeCSINode(host volume.VolumeHost) error","file":"pkg/volume/csi/csi_plugin.go","code":"func initializeCSINode(host volume.VolumeHost) error {\n\tkvh, ok := host.(volume.KubeletVolumeHost)\n\tif !ok {\n\t\tklog.V(4).Info(\"Cast from VolumeHost to KubeletVolumeHost failed. Skipping CSINode initialization, not running on kubelet\")\n\t\treturn nil\n\t}\n\tkubeClient := host.GetKubeClient()\n\tif kubeClient == nil {\n\t\t// Kubelet running in standalone mode. Skip CSINode initialization\n\t\tklog.Warning(\"Skipping CSINode initialization, kubelet running in standalone mode\")\n\t\treturn nil\n\t}\n\n\tkvh.SetKubeletError(errors.New(\"CSINode is not yet initialized\"))\n\n\tgo func() {\n\t\tdefer utilruntime.HandleCrash()\n\n\t\t// First wait indefinitely to talk to Kube APIServer\n\t\tnodeName := host.GetNodeName()\n\t\terr := waitForAPIServerForever(kubeClient, nodeName)\n\t\tif err != nil {\n\t\t\tklog.Fatalf(\"Failed to initialize CSINode while waiting for API server to report ok: %v\", err)\n\t\t}\n\n\t\t// Backoff parameters tuned to retry over 140 seconds. Will fail and restart the Kubelet\n\t\t// after max retry steps.\n\t\tinitBackoff := wait.Backoff{\n\t\t\tSteps: 6,\n\t\t\tDuration: 15 * time.Millisecond,\n\t\t\tFactor: 6.0,\n\t\t\tJitter: 0.1,\n\t\t}\n\t\terr = wait.ExponentialBackoff(initBackoff, func() (bool, error) {\n\t\t\tklog.V(4).Infof(\"Initializing migrated drivers on CSINode\")\n\t\t\terr := nim.InitializeCSINodeWithAnnotation()\n\t\t\tif err != nil {\n\t\t\t\tkvh.SetKubeletError(fmt.Errorf(\"failed to initialize CSINode: %v\", err))\n\t\t\t\tklog.Errorf(\"Failed to initialize CSINode: %v\", err)\n\t\t\t\treturn false, nil\n\t\t\t}\n\n\t\t\t// Successfully initialized drivers, allow Kubelet to post Ready\n\t\t\tkvh.SetKubeletError(nil)\n\t\t\treturn true, nil\n\t\t})\n\t\tif err != nil {\n\t\t\t// 2 releases after CSIMigration and all CSIMigrationX (where X is a volume plugin)\n\t\t\t// are permanently enabled the apiserver/controllers can assume that the kubelet is\n\t\t\t// using CSI for all Migrated volume plugins. Then all the CSINode initialization\n\t\t\t// code can be dropped from Kubelet.\n\t\t\t// Kill the Kubelet process and allow it to restart to retry initialization\n\t\t\tklog.Fatalf(\"Failed to initialize CSINode after retrying: %v\", err)\n\t\t}\n\t}()\n\treturn nil\n}","line":{"from":257,"to":313}} {"id":100011995,"name":"GetPluginName","signature":"func (p *csiPlugin) GetPluginName() string","file":"pkg/volume/csi/csi_plugin.go","code":"func (p *csiPlugin) GetPluginName() string {\n\treturn CSIPluginName\n}","line":{"from":315,"to":317}} {"id":100011996,"name":"GetVolumeName","signature":"func (p *csiPlugin) GetVolumeName(spec *volume.Spec) (string, error)","file":"pkg/volume/csi/csi_plugin.go","code":"// GetvolumeName returns a concatenated string of CSIVolumeSource.Driver\u003cvolNameSe\u003eCSIVolumeSource.VolumeHandle\n// That string value is used in Detach() to extract driver name and volumeName.\nfunc (p *csiPlugin) GetVolumeName(spec *volume.Spec) (string, error) {\n\tcsi, err := getPVSourceFromSpec(spec)\n\tif err != nil {\n\t\treturn \"\", errors.New(log(\"plugin.GetVolumeName failed to extract volume source from spec: %v\", err))\n\t}\n\n\t// return driverName\u003cseparator\u003evolumeHandle\n\treturn fmt.Sprintf(\"%s%s%s\", csi.Driver, volNameSep, csi.VolumeHandle), nil\n}","line":{"from":319,"to":329}} {"id":100011997,"name":"CanSupport","signature":"func (p *csiPlugin) CanSupport(spec *volume.Spec) bool","file":"pkg/volume/csi/csi_plugin.go","code":"func (p *csiPlugin) CanSupport(spec *volume.Spec) bool {\n\t// TODO (vladimirvivien) CanSupport should also take into account\n\t// the availability/registration of specified Driver in the volume source\n\tif spec == nil {\n\t\treturn false\n\t}\n\treturn (spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.CSI != nil) ||\n\t\t(spec.Volume != nil \u0026\u0026 spec.Volume.CSI != nil)\n}","line":{"from":331,"to":339}} {"id":100011998,"name":"RequiresRemount","signature":"func (p *csiPlugin) RequiresRemount(spec *volume.Spec) bool","file":"pkg/volume/csi/csi_plugin.go","code":"func (p *csiPlugin) RequiresRemount(spec *volume.Spec) bool {\n\tif p.csiDriverLister == nil {\n\t\treturn false\n\t}\n\tdriverName, err := GetCSIDriverName(spec)\n\tif err != nil {\n\t\tklog.V(5).Info(log(\"Failed to mark %q as republish required, err: %v\", spec.Name(), err))\n\t\treturn false\n\t}\n\tcsiDriver, err := p.getCSIDriver(driverName)\n\tif err != nil {\n\t\tklog.V(5).Info(log(\"Failed to mark %q as republish required, err: %v\", spec.Name(), err))\n\t\treturn false\n\t}\n\treturn *csiDriver.Spec.RequiresRepublish\n}","line":{"from":341,"to":356}} {"id":100011999,"name":"NewMounter","signature":"func (p *csiPlugin) NewMounter(","file":"pkg/volume/csi/csi_plugin.go","code":"func (p *csiPlugin) NewMounter(\n\tspec *volume.Spec,\n\tpod *api.Pod,\n\t_ volume.VolumeOptions) (volume.Mounter, error) {\n\n\tvolSrc, pvSrc, err := getSourceFromSpec(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar (\n\t\tdriverName string\n\t\tvolumeHandle string\n\t\treadOnly bool\n\t)\n\n\tswitch {\n\tcase volSrc != nil:\n\t\tvolumeHandle = makeVolumeHandle(string(pod.UID), spec.Name())\n\t\tdriverName = volSrc.Driver\n\t\tif volSrc.ReadOnly != nil {\n\t\t\treadOnly = *volSrc.ReadOnly\n\t\t}\n\tcase pvSrc != nil:\n\t\tdriverName = pvSrc.Driver\n\t\tvolumeHandle = pvSrc.VolumeHandle\n\t\treadOnly = spec.ReadOnly\n\tdefault:\n\t\treturn nil, errors.New(log(\"volume source not found in volume.Spec\"))\n\t}\n\n\tvolumeLifecycleMode, err := p.getVolumeLifecycleMode(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tk8s := p.host.GetKubeClient()\n\tif k8s == nil {\n\t\treturn nil, errors.New(log(\"failed to get a kubernetes client\"))\n\t}\n\n\tkvh, ok := p.host.(volume.KubeletVolumeHost)\n\tif !ok {\n\t\treturn nil, errors.New(log(\"cast from VolumeHost to KubeletVolumeHost failed\"))\n\t}\n\n\tmounter := \u0026csiMountMgr{\n\t\tplugin: p,\n\t\tk8s: k8s,\n\t\tspec: spec,\n\t\tpod: pod,\n\t\tpodUID: pod.UID,\n\t\tdriverName: csiDriverName(driverName),\n\t\tvolumeLifecycleMode: volumeLifecycleMode,\n\t\tvolumeID: volumeHandle,\n\t\tspecVolumeID: spec.Name(),\n\t\treadOnly: readOnly,\n\t\tkubeVolHost: kvh,\n\t}\n\tmounter.csiClientGetter.driverName = csiDriverName(driverName)\n\n\tdir := mounter.GetPath()\n\tmounter.MetricsProvider = NewMetricsCsi(volumeHandle, dir, csiDriverName(driverName))\n\tklog.V(4).Info(log(\"mounter created successfully\"))\n\treturn mounter, nil\n}","line":{"from":358,"to":423}} {"id":100012000,"name":"NewUnmounter","signature":"func (p *csiPlugin) NewUnmounter(specName string, podUID types.UID) (volume.Unmounter, error)","file":"pkg/volume/csi/csi_plugin.go","code":"func (p *csiPlugin) NewUnmounter(specName string, podUID types.UID) (volume.Unmounter, error) {\n\tklog.V(4).Infof(log(\"setting up unmounter for [name=%v, podUID=%v]\", specName, podUID))\n\n\tkvh, ok := p.host.(volume.KubeletVolumeHost)\n\tif !ok {\n\t\treturn nil, errors.New(log(\"cast from VolumeHost to KubeletVolumeHost failed\"))\n\t}\n\n\tunmounter := \u0026csiMountMgr{\n\t\tplugin: p,\n\t\tpodUID: podUID,\n\t\tspecVolumeID: specName,\n\t\tkubeVolHost: kvh,\n\t}\n\n\t// load volume info from file\n\tdir := unmounter.GetPath()\n\tdataDir := filepath.Dir(dir) // dropoff /mount at end\n\tdata, err := loadVolumeData(dataDir, volDataFileName)\n\tif err != nil {\n\t\treturn nil, errors.New(log(\"unmounter failed to load volume data file [%s]: %v\", dir, err))\n\t}\n\tunmounter.driverName = csiDriverName(data[volDataKey.driverName])\n\tunmounter.volumeID = data[volDataKey.volHandle]\n\tunmounter.csiClientGetter.driverName = unmounter.driverName\n\n\treturn unmounter, nil\n}","line":{"from":425,"to":452}} {"id":100012001,"name":"ConstructVolumeSpec","signature":"func (p *csiPlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error)","file":"pkg/volume/csi/csi_plugin.go","code":"func (p *csiPlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error) {\n\tklog.V(4).Info(log(\"plugin.ConstructVolumeSpec [pv.Name=%v, path=%v]\", volumeName, mountPath))\n\n\tvolData, err := loadVolumeData(mountPath, volDataFileName)\n\tif err != nil {\n\t\treturn volume.ReconstructedVolume{}, errors.New(log(\"plugin.ConstructVolumeSpec failed loading volume data using [%s]: %v\", mountPath, err))\n\t}\n\tklog.V(4).Info(log(\"plugin.ConstructVolumeSpec extracted [%#v]\", volData))\n\n\tvar ret volume.ReconstructedVolume\n\tif utilfeature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {\n\t\tret.SELinuxMountContext = volData[volDataKey.seLinuxMountContext]\n\t}\n\n\t// If mode is VolumeLifecycleEphemeral, use constructVolSourceSpec\n\t// to construct volume source spec. If mode is VolumeLifecyclePersistent,\n\t// use constructPVSourceSpec to construct volume construct pv source spec.\n\tif storage.VolumeLifecycleMode(volData[volDataKey.volumeLifecycleMode]) == storage.VolumeLifecycleEphemeral {\n\t\tret.Spec = p.constructVolSourceSpec(volData[volDataKey.specVolID], volData[volDataKey.driverName])\n\t\treturn ret, nil\n\t}\n\n\tret.Spec = p.constructPVSourceSpec(volData[volDataKey.specVolID], volData[volDataKey.driverName], volData[volDataKey.volHandle])\n\treturn ret, nil\n}","line":{"from":454,"to":478}} {"id":100012002,"name":"constructVolSourceSpec","signature":"func (p *csiPlugin) constructVolSourceSpec(volSpecName, driverName string) *volume.Spec","file":"pkg/volume/csi/csi_plugin.go","code":"// constructVolSourceSpec constructs volume.Spec with CSIVolumeSource\nfunc (p *csiPlugin) constructVolSourceSpec(volSpecName, driverName string) *volume.Spec {\n\tvol := \u0026api.Volume{\n\t\tName: volSpecName,\n\t\tVolumeSource: api.VolumeSource{\n\t\t\tCSI: \u0026api.CSIVolumeSource{\n\t\t\t\tDriver: driverName,\n\t\t\t},\n\t\t},\n\t}\n\treturn volume.NewSpecFromVolume(vol)\n}","line":{"from":480,"to":491}} {"id":100012003,"name":"constructPVSourceSpec","signature":"func (p *csiPlugin) constructPVSourceSpec(volSpecName, driverName, volumeHandle string) *volume.Spec","file":"pkg/volume/csi/csi_plugin.go","code":"// constructPVSourceSpec constructs volume.Spec with CSIPersistentVolumeSource\nfunc (p *csiPlugin) constructPVSourceSpec(volSpecName, driverName, volumeHandle string) *volume.Spec {\n\tfsMode := api.PersistentVolumeFilesystem\n\tpv := \u0026api.PersistentVolume{\n\t\tObjectMeta: meta.ObjectMeta{\n\t\t\tName: volSpecName,\n\t\t},\n\t\tSpec: api.PersistentVolumeSpec{\n\t\t\tPersistentVolumeSource: api.PersistentVolumeSource{\n\t\t\t\tCSI: \u0026api.CSIPersistentVolumeSource{\n\t\t\t\t\tDriver: driverName,\n\t\t\t\t\tVolumeHandle: volumeHandle,\n\t\t\t\t},\n\t\t\t},\n\t\t\tVolumeMode: \u0026fsMode,\n\t\t},\n\t}\n\treturn volume.NewSpecFromPersistentVolume(pv, false)\n}","line":{"from":493,"to":511}} {"id":100012004,"name":"SupportsMountOption","signature":"func (p *csiPlugin) SupportsMountOption() bool","file":"pkg/volume/csi/csi_plugin.go","code":"func (p *csiPlugin) SupportsMountOption() bool {\n\t// TODO (vladimirvivien) use CSI VolumeCapability.MountVolume.mount_flags\n\t// to probe for the result for this method\n\t// (bswartz) Until the CSI spec supports probing, our only option is to\n\t// make plugins register their support for mount options or lack thereof\n\t// directly with kubernetes.\n\treturn true\n}","line":{"from":513,"to":520}} {"id":100012005,"name":"SupportsBulkVolumeVerification","signature":"func (p *csiPlugin) SupportsBulkVolumeVerification() bool","file":"pkg/volume/csi/csi_plugin.go","code":"func (p *csiPlugin) SupportsBulkVolumeVerification() bool {\n\treturn false\n}","line":{"from":522,"to":524}} {"id":100012006,"name":"SupportsSELinuxContextMount","signature":"func (p *csiPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/csi/csi_plugin.go","code":"func (p *csiPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error) {\n\tif utilfeature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {\n\t\tdriver, err := GetCSIDriverName(spec)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tcsiDriver, err := p.getCSIDriver(driver)\n\t\tif err != nil {\n\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn false, err\n\t\t}\n\t\tif csiDriver.Spec.SELinuxMount != nil {\n\t\t\treturn *csiDriver.Spec.SELinuxMount, nil\n\t\t}\n\t\treturn false, nil\n\t}\n\treturn false, nil\n}","line":{"from":526,"to":545}} {"id":100012007,"name":"NewAttacher","signature":"func (p *csiPlugin) NewAttacher() (volume.Attacher, error)","file":"pkg/volume/csi/csi_plugin.go","code":"func (p *csiPlugin) NewAttacher() (volume.Attacher, error) {\n\treturn p.newAttacherDetacher()\n}","line":{"from":552,"to":554}} {"id":100012008,"name":"NewDeviceMounter","signature":"func (p *csiPlugin) NewDeviceMounter() (volume.DeviceMounter, error)","file":"pkg/volume/csi/csi_plugin.go","code":"func (p *csiPlugin) NewDeviceMounter() (volume.DeviceMounter, error) {\n\treturn p.NewAttacher()\n}","line":{"from":556,"to":558}} {"id":100012009,"name":"NewDetacher","signature":"func (p *csiPlugin) NewDetacher() (volume.Detacher, error)","file":"pkg/volume/csi/csi_plugin.go","code":"func (p *csiPlugin) NewDetacher() (volume.Detacher, error) {\n\treturn p.newAttacherDetacher()\n}","line":{"from":560,"to":562}} {"id":100012010,"name":"CanAttach","signature":"func (p *csiPlugin) CanAttach(spec *volume.Spec) (bool, error)","file":"pkg/volume/csi/csi_plugin.go","code":"func (p *csiPlugin) CanAttach(spec *volume.Spec) (bool, error) {\n\tvolumeLifecycleMode, err := p.getVolumeLifecycleMode(spec)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif volumeLifecycleMode == storage.VolumeLifecycleEphemeral {\n\t\tklog.V(5).Info(log(\"plugin.CanAttach = false, ephemeral mode detected for spec %v\", spec.Name()))\n\t\treturn false, nil\n\t}\n\n\tpvSrc, err := getCSISourceFromSpec(spec)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tdriverName := pvSrc.Driver\n\n\tskipAttach, err := p.skipAttach(driverName)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn !skipAttach, nil\n}","line":{"from":564,"to":588}} {"id":100012011,"name":"CanDeviceMount","signature":"func (p *csiPlugin) CanDeviceMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/csi/csi_plugin.go","code":"// CanDeviceMount returns true if the spec supports device mount\nfunc (p *csiPlugin) CanDeviceMount(spec *volume.Spec) (bool, error) {\n\tvolumeLifecycleMode, err := p.getVolumeLifecycleMode(spec)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif volumeLifecycleMode == storage.VolumeLifecycleEphemeral {\n\t\tklog.V(5).Info(log(\"plugin.CanDeviceMount skipped ephemeral mode detected for spec %v\", spec.Name()))\n\t\treturn false, nil\n\t}\n\n\t// Persistent volumes support device mount.\n\treturn true, nil\n}","line":{"from":590,"to":604}} {"id":100012012,"name":"NewDeviceUnmounter","signature":"func (p *csiPlugin) NewDeviceUnmounter() (volume.DeviceUnmounter, error)","file":"pkg/volume/csi/csi_plugin.go","code":"func (p *csiPlugin) NewDeviceUnmounter() (volume.DeviceUnmounter, error) {\n\treturn p.NewDetacher()\n}","line":{"from":606,"to":608}} {"id":100012013,"name":"GetDeviceMountRefs","signature":"func (p *csiPlugin) GetDeviceMountRefs(deviceMountPath string) ([]string, error)","file":"pkg/volume/csi/csi_plugin.go","code":"func (p *csiPlugin) GetDeviceMountRefs(deviceMountPath string) ([]string, error) {\n\tm := p.host.GetMounter(p.GetPluginName())\n\treturn m.GetMountRefs(deviceMountPath)\n}","line":{"from":610,"to":613}} {"id":100012014,"name":"NewBlockVolumeMapper","signature":"func (p *csiPlugin) NewBlockVolumeMapper(spec *volume.Spec, podRef *api.Pod, opts volume.VolumeOptions) (volume.BlockVolumeMapper, error)","file":"pkg/volume/csi/csi_plugin.go","code":"func (p *csiPlugin) NewBlockVolumeMapper(spec *volume.Spec, podRef *api.Pod, opts volume.VolumeOptions) (volume.BlockVolumeMapper, error) {\n\tpvSource, err := getCSISourceFromSpec(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treadOnly, err := getReadOnlyFromSpec(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tklog.V(4).Info(log(\"setting up block mapper for [volume=%v,driver=%v]\", pvSource.VolumeHandle, pvSource.Driver))\n\n\tk8s := p.host.GetKubeClient()\n\tif k8s == nil {\n\t\treturn nil, errors.New(log(\"failed to get a kubernetes client\"))\n\t}\n\n\tmapper := \u0026csiBlockMapper{\n\t\tk8s: k8s,\n\t\tplugin: p,\n\t\tvolumeID: pvSource.VolumeHandle,\n\t\tdriverName: csiDriverName(pvSource.Driver),\n\t\treadOnly: readOnly,\n\t\tspec: spec,\n\t\tspecName: spec.Name(),\n\t\tpod: podRef,\n\t\tpodUID: podRef.UID,\n\t}\n\tmapper.csiClientGetter.driverName = csiDriverName(pvSource.Driver)\n\n\t// Save volume info in pod dir\n\tdataDir := getVolumeDeviceDataDir(spec.Name(), p.host)\n\n\tif err := os.MkdirAll(dataDir, 0750); err != nil {\n\t\treturn nil, errors.New(log(\"failed to create data dir %s: %v\", dataDir, err))\n\t}\n\tklog.V(4).Info(log(\"created path successfully [%s]\", dataDir))\n\n\tblockPath, err := mapper.GetGlobalMapPath(spec)\n\tif err != nil {\n\t\treturn nil, errors.New(log(\"failed to get device path: %v\", err))\n\t}\n\n\tmapper.MetricsProvider = NewMetricsCsi(pvSource.VolumeHandle, blockPath+\"/\"+string(podRef.UID), csiDriverName(pvSource.Driver))\n\n\t// persist volume info data for teardown\n\tnode := string(p.host.GetNodeName())\n\tattachID := getAttachmentName(pvSource.VolumeHandle, pvSource.Driver, node)\n\tvolData := map[string]string{\n\t\tvolDataKey.specVolID: spec.Name(),\n\t\tvolDataKey.volHandle: pvSource.VolumeHandle,\n\t\tvolDataKey.driverName: pvSource.Driver,\n\t\tvolDataKey.nodeName: node,\n\t\tvolDataKey.attachmentID: attachID,\n\t}\n\n\terr = saveVolumeData(dataDir, volDataFileName, volData)\n\tdefer func() {\n\t\t// Only if there was an error and volume operation was considered\n\t\t// finished, we should remove the directory.\n\t\tif err != nil \u0026\u0026 volumetypes.IsOperationFinishedError(err) {\n\t\t\t// attempt to cleanup volume mount dir.\n\t\t\tif err = removeMountDir(p, dataDir); err != nil {\n\t\t\t\tklog.Error(log(\"attacher.MountDevice failed to remove mount dir after error [%s]: %v\", dataDir, err))\n\t\t\t}\n\t\t}\n\t}()\n\tif err != nil {\n\t\terrorMsg := log(\"csi.NewBlockVolumeMapper failed to save volume info data: %v\", err)\n\t\tklog.Error(errorMsg)\n\t\treturn nil, errors.New(errorMsg)\n\t}\n\n\treturn mapper, nil\n}","line":{"from":618,"to":692}} {"id":100012015,"name":"NewBlockVolumeUnmapper","signature":"func (p *csiPlugin) NewBlockVolumeUnmapper(volName string, podUID types.UID) (volume.BlockVolumeUnmapper, error)","file":"pkg/volume/csi/csi_plugin.go","code":"func (p *csiPlugin) NewBlockVolumeUnmapper(volName string, podUID types.UID) (volume.BlockVolumeUnmapper, error) {\n\tklog.V(4).Infof(log(\"setting up block unmapper for [Spec=%v, podUID=%v]\", volName, podUID))\n\tunmapper := \u0026csiBlockMapper{\n\t\tplugin: p,\n\t\tpodUID: podUID,\n\t\tspecName: volName,\n\t}\n\n\t// load volume info from file\n\tdataDir := getVolumeDeviceDataDir(unmapper.specName, p.host)\n\tdata, err := loadVolumeData(dataDir, volDataFileName)\n\tif err != nil {\n\t\treturn nil, errors.New(log(\"unmapper failed to load volume data file [%s]: %v\", dataDir, err))\n\t}\n\tunmapper.driverName = csiDriverName(data[volDataKey.driverName])\n\tunmapper.volumeID = data[volDataKey.volHandle]\n\tunmapper.csiClientGetter.driverName = unmapper.driverName\n\n\treturn unmapper, nil\n}","line":{"from":694,"to":713}} {"id":100012016,"name":"ConstructBlockVolumeSpec","signature":"func (p *csiPlugin) ConstructBlockVolumeSpec(podUID types.UID, specVolName, mapPath string) (*volume.Spec, error)","file":"pkg/volume/csi/csi_plugin.go","code":"func (p *csiPlugin) ConstructBlockVolumeSpec(podUID types.UID, specVolName, mapPath string) (*volume.Spec, error) {\n\tklog.V(4).Infof(\"plugin.ConstructBlockVolumeSpec [podUID=%s, specVolName=%s, path=%s]\", string(podUID), specVolName, mapPath)\n\n\tdataDir := getVolumeDeviceDataDir(specVolName, p.host)\n\tvolData, err := loadVolumeData(dataDir, volDataFileName)\n\tif err != nil {\n\t\treturn nil, errors.New(log(\"plugin.ConstructBlockVolumeSpec failed loading volume data using [%s]: %v\", mapPath, err))\n\t}\n\n\tklog.V(4).Info(log(\"plugin.ConstructBlockVolumeSpec extracted [%#v]\", volData))\n\n\tblockMode := api.PersistentVolumeBlock\n\tpv := \u0026api.PersistentVolume{\n\t\tObjectMeta: meta.ObjectMeta{\n\t\t\tName: volData[volDataKey.specVolID],\n\t\t},\n\t\tSpec: api.PersistentVolumeSpec{\n\t\t\tPersistentVolumeSource: api.PersistentVolumeSource{\n\t\t\t\tCSI: \u0026api.CSIPersistentVolumeSource{\n\t\t\t\t\tDriver: volData[volDataKey.driverName],\n\t\t\t\t\tVolumeHandle: volData[volDataKey.volHandle],\n\t\t\t\t},\n\t\t\t},\n\t\t\tVolumeMode: \u0026blockMode,\n\t\t},\n\t}\n\n\treturn volume.NewSpecFromPersistentVolume(pv, false), nil\n}","line":{"from":715,"to":743}} {"id":100012017,"name":"skipAttach","signature":"func (p *csiPlugin) skipAttach(driver string) (bool, error)","file":"pkg/volume/csi/csi_plugin.go","code":"// skipAttach looks up CSIDriver object associated with driver name\n// to determine if driver requires attachment volume operation\nfunc (p *csiPlugin) skipAttach(driver string) (bool, error) {\n\tcsiDriver, err := p.getCSIDriver(driver)\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\t// Don't skip attach if CSIDriver does not exist\n\t\t\treturn false, nil\n\t\t}\n\t\treturn false, err\n\t}\n\tif csiDriver.Spec.AttachRequired != nil \u0026\u0026 *csiDriver.Spec.AttachRequired == false {\n\t\treturn true, nil\n\t}\n\treturn false, nil\n}","line":{"from":745,"to":760}} {"id":100012018,"name":"getCSIDriver","signature":"func (p *csiPlugin) getCSIDriver(driver string) (*storage.CSIDriver, error)","file":"pkg/volume/csi/csi_plugin.go","code":"func (p *csiPlugin) getCSIDriver(driver string) (*storage.CSIDriver, error) {\n\tkletHost, ok := p.host.(volume.KubeletVolumeHost)\n\tif ok {\n\t\tif err := kletHost.WaitForCacheSync(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif p.csiDriverLister == nil {\n\t\treturn nil, errors.New(\"CSIDriver lister does not exist\")\n\t}\n\tcsiDriver, err := p.csiDriverLister.Get(driver)\n\treturn csiDriver, err\n}","line":{"from":762,"to":775}} {"id":100012019,"name":"getVolumeLifecycleMode","signature":"func (p *csiPlugin) getVolumeLifecycleMode(spec *volume.Spec) (storage.VolumeLifecycleMode, error)","file":"pkg/volume/csi/csi_plugin.go","code":"// getVolumeLifecycleMode returns the mode for the specified spec: {persistent|ephemeral}.\n// 1) If mode cannot be determined, it will default to \"persistent\".\n// 2) If Mode cannot be resolved to either {persistent | ephemeral}, an error is returned\n// See https://github.com/kubernetes/enhancements/blob/master/keps/sig-storage/596-csi-inline-volumes/README.md\nfunc (p *csiPlugin) getVolumeLifecycleMode(spec *volume.Spec) (storage.VolumeLifecycleMode, error) {\n\t// 1) if volume.Spec.Volume.CSI != nil -\u003e mode is ephemeral\n\t// 2) if volume.Spec.PersistentVolume.Spec.CSI != nil -\u003e persistent\n\tvolSrc, _, err := getSourceFromSpec(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif volSrc != nil {\n\t\treturn storage.VolumeLifecycleEphemeral, nil\n\t}\n\treturn storage.VolumeLifecyclePersistent, nil\n}","line":{"from":777,"to":793}} {"id":100012020,"name":"getPublishContext","signature":"func (p *csiPlugin) getPublishContext(client clientset.Interface, handle, driver, nodeName string) (map[string]string, error)","file":"pkg/volume/csi/csi_plugin.go","code":"func (p *csiPlugin) getPublishContext(client clientset.Interface, handle, driver, nodeName string) (map[string]string, error) {\n\tskip, err := p.skipAttach(driver)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif skip {\n\t\treturn nil, nil\n\t}\n\n\tattachID := getAttachmentName(handle, driver, nodeName)\n\n\t// search for attachment by VolumeAttachment.Spec.Source.PersistentVolumeName\n\tattachment, err := client.StorageV1().VolumeAttachments().Get(context.TODO(), attachID, meta.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err // This err already has enough context (\"VolumeAttachment xyz not found\")\n\t}\n\n\tif attachment == nil {\n\t\terr = errors.New(\"no existing VolumeAttachment found\")\n\t\treturn nil, err\n\t}\n\treturn attachment.Status.AttachmentMetadata, nil\n}","line":{"from":795,"to":817}} {"id":100012021,"name":"newAttacherDetacher","signature":"func (p *csiPlugin) newAttacherDetacher() (*csiAttacher, error)","file":"pkg/volume/csi/csi_plugin.go","code":"func (p *csiPlugin) newAttacherDetacher() (*csiAttacher, error) {\n\tk8s := p.host.GetKubeClient()\n\tif k8s == nil {\n\t\treturn nil, errors.New(log(\"unable to get kubernetes client from host\"))\n\t}\n\n\treturn \u0026csiAttacher{\n\t\tplugin: p,\n\t\tk8s: k8s,\n\t\twatchTimeout: csiTimeout,\n\t}, nil\n}","line":{"from":819,"to":830}} {"id":100012022,"name":"podInfoEnabled","signature":"func (p *csiPlugin) podInfoEnabled(driverName string) (bool, error)","file":"pkg/volume/csi/csi_plugin.go","code":"// podInfoEnabled check CSIDriver enabled pod info flag\nfunc (p *csiPlugin) podInfoEnabled(driverName string) (bool, error) {\n\tcsiDriver, err := p.getCSIDriver(driverName)\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\tklog.V(4).Infof(log(\"CSIDriver %q not found, not adding pod information\", driverName))\n\t\t\treturn false, nil\n\t\t}\n\t\treturn false, err\n\t}\n\n\t// if PodInfoOnMount is not set or false we do not set pod attributes\n\tif csiDriver.Spec.PodInfoOnMount == nil || *csiDriver.Spec.PodInfoOnMount == false {\n\t\tklog.V(4).Infof(log(\"CSIDriver %q does not require pod information\", driverName))\n\t\treturn false, nil\n\t}\n\treturn true, nil\n}","line":{"from":832,"to":849}} {"id":100012023,"name":"unregisterDriver","signature":"func unregisterDriver(driverName string) error","file":"pkg/volume/csi/csi_plugin.go","code":"func unregisterDriver(driverName string) error {\n\tcsiDrivers.Delete(driverName)\n\n\tif err := nim.UninstallCSIDriver(driverName); err != nil {\n\t\treturn errors.New(log(\"Error uninstalling CSI driver: %v\", err))\n\t}\n\n\treturn nil\n}","line":{"from":851,"to":859}} {"id":100012024,"name":"highestSupportedVersion","signature":"func highestSupportedVersion(versions []string) (*utilversion.Version, error)","file":"pkg/volume/csi/csi_plugin.go","code":"// Return the highest supported version\nfunc highestSupportedVersion(versions []string) (*utilversion.Version, error) {\n\tif len(versions) == 0 {\n\t\treturn nil, errors.New(log(\"CSI driver reporting empty array for supported versions\"))\n\t}\n\n\tvar highestSupportedVersion *utilversion.Version\n\tvar theErr error\n\tfor i := len(versions) - 1; i \u003e= 0; i-- {\n\t\tcurrentHighestVer, err := utilversion.ParseGeneric(versions[i])\n\t\tif err != nil {\n\t\t\ttheErr = err\n\t\t\tcontinue\n\t\t}\n\t\tif currentHighestVer.Major() \u003e 1 {\n\t\t\t// CSI currently only has version 0.x and 1.x (see https://github.com/container-storage-interface/spec/releases).\n\t\t\t// Therefore any driver claiming version 2.x+ is ignored as an unsupported versions.\n\t\t\t// Future 1.x versions of CSI are supposed to be backwards compatible so this version of Kubernetes will work with any 1.x driver\n\t\t\t// (or 0.x), but it may not work with 2.x drivers (because 2.x does not have to be backwards compatible with 1.x).\n\t\t\tcontinue\n\t\t}\n\t\tif highestSupportedVersion == nil || highestSupportedVersion.LessThan(currentHighestVer) {\n\t\t\thighestSupportedVersion = currentHighestVer\n\t\t}\n\t}\n\n\tif highestSupportedVersion == nil {\n\t\treturn nil, fmt.Errorf(\"could not find a highest supported version from versions (%v) reported by this driver: %v\", versions, theErr)\n\t}\n\n\tif highestSupportedVersion.Major() != 1 {\n\t\t// CSI v0.x is no longer supported as of Kubernetes v1.17 in\n\t\t// accordance with deprecation policy set out in Kubernetes v1.13\n\t\treturn nil, fmt.Errorf(\"highest supported version reported by driver is %v, must be v1.x\", highestSupportedVersion)\n\t}\n\treturn highestSupportedVersion, nil\n}","line":{"from":861,"to":897}} {"id":100012025,"name":"waitForAPIServerForever","signature":"func waitForAPIServerForever(client clientset.Interface, nodeName types.NodeName) error","file":"pkg/volume/csi/csi_plugin.go","code":"// waitForAPIServerForever waits forever to get a CSINode instance as a proxy\n// for a healthy APIServer\nfunc waitForAPIServerForever(client clientset.Interface, nodeName types.NodeName) error {\n\tvar lastErr error\n\terr := wait.PollImmediateInfinite(time.Second, func() (bool, error) {\n\t\t// Get a CSINode from API server to make sure 1) kubelet can reach API server\n\t\t// and 2) it has enough permissions. Kubelet may have restricted permissions\n\t\t// when it's bootstrapping TLS.\n\t\t// https://kubernetes.io/docs/reference/command-line-tools-reference/kubelet-tls-bootstrapping/\n\t\t_, lastErr = client.StorageV1().CSINodes().Get(context.TODO(), string(nodeName), meta.GetOptions{})\n\t\tif lastErr == nil || apierrors.IsNotFound(lastErr) {\n\t\t\t// API server contacted\n\t\t\treturn true, nil\n\t\t}\n\t\tklog.V(2).Infof(\"Failed to contact API server when waiting for CSINode publishing: %s\", lastErr)\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\t// In theory this is unreachable, but just in case:\n\t\treturn fmt.Errorf(\"%v: %v\", err, lastErr)\n\t}\n\n\treturn nil\n}","line":{"from":899,"to":922}} {"id":100012026,"name":"getCredentialsFromSecret","signature":"func getCredentialsFromSecret(k8s kubernetes.Interface, secretRef *api.SecretReference) (map[string]string, error)","file":"pkg/volume/csi/csi_util.go","code":"func getCredentialsFromSecret(k8s kubernetes.Interface, secretRef *api.SecretReference) (map[string]string, error) {\n\tcredentials := map[string]string{}\n\tsecret, err := k8s.CoreV1().Secrets(secretRef.Namespace).Get(context.TODO(), secretRef.Name, meta.GetOptions{})\n\tif err != nil {\n\t\treturn credentials, errors.New(log(\"failed to find the secret %s in the namespace %s with error: %v\", secretRef.Name, secretRef.Namespace, err))\n\t}\n\tfor key, value := range secret.Data {\n\t\tcredentials[key] = string(value)\n\t}\n\n\treturn credentials, nil\n}","line":{"from":45,"to":56}} {"id":100012027,"name":"saveVolumeData","signature":"func saveVolumeData(dir string, fileName string, data map[string]string) error","file":"pkg/volume/csi/csi_util.go","code":"// saveVolumeData persists parameter data as json file at the provided location\nfunc saveVolumeData(dir string, fileName string, data map[string]string) error {\n\tdataFilePath := filepath.Join(dir, fileName)\n\tklog.V(4).Info(log(\"saving volume data file [%s]\", dataFilePath))\n\tfile, err := os.Create(dataFilePath)\n\tif err != nil {\n\t\treturn errors.New(log(\"failed to save volume data file %s: %v\", dataFilePath, err))\n\t}\n\tdefer file.Close()\n\tif err := json.NewEncoder(file).Encode(data); err != nil {\n\t\treturn errors.New(log(\"failed to save volume data file %s: %v\", dataFilePath, err))\n\t}\n\tklog.V(4).Info(log(\"volume data file saved successfully [%s]\", dataFilePath))\n\treturn nil\n}","line":{"from":58,"to":72}} {"id":100012028,"name":"loadVolumeData","signature":"func loadVolumeData(dir string, fileName string) (map[string]string, error)","file":"pkg/volume/csi/csi_util.go","code":"// loadVolumeData loads volume info from specified json file/location\nfunc loadVolumeData(dir string, fileName string) (map[string]string, error) {\n\t// remove /mount at the end\n\tdataFileName := filepath.Join(dir, fileName)\n\tklog.V(4).Info(log(\"loading volume data file [%s]\", dataFileName))\n\n\tfile, err := os.Open(dataFileName)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%s: %w\", log(\"failed to open volume data file [%s]\", dataFileName), err)\n\t}\n\tdefer file.Close()\n\tdata := map[string]string{}\n\tif err := json.NewDecoder(file).Decode(\u0026data); err != nil {\n\t\treturn nil, errors.New(log(\"failed to parse volume data file [%s]: %v\", dataFileName, err))\n\t}\n\n\treturn data, nil\n}","line":{"from":74,"to":91}} {"id":100012029,"name":"getCSISourceFromSpec","signature":"func getCSISourceFromSpec(spec *volume.Spec) (*api.CSIPersistentVolumeSource, error)","file":"pkg/volume/csi/csi_util.go","code":"func getCSISourceFromSpec(spec *volume.Spec) (*api.CSIPersistentVolumeSource, error) {\n\treturn getPVSourceFromSpec(spec)\n}","line":{"from":93,"to":95}} {"id":100012030,"name":"getReadOnlyFromSpec","signature":"func getReadOnlyFromSpec(spec *volume.Spec) (bool, error)","file":"pkg/volume/csi/csi_util.go","code":"func getReadOnlyFromSpec(spec *volume.Spec) (bool, error) {\n\tif spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.CSI != nil {\n\t\treturn spec.ReadOnly, nil\n\t}\n\n\treturn false, fmt.Errorf(\"CSIPersistentVolumeSource not defined in spec\")\n}","line":{"from":97,"to":104}} {"id":100012031,"name":"log","signature":"func log(msg string, parts ...interface{}) string","file":"pkg/volume/csi/csi_util.go","code":"// log prepends log string with `kubernetes.io/csi`\nfunc log(msg string, parts ...interface{}) string {\n\treturn fmt.Sprintf(fmt.Sprintf(\"%s: %s\", CSIPluginName, msg), parts...)\n}","line":{"from":106,"to":109}} {"id":100012032,"name":"getVolumePluginDir","signature":"func getVolumePluginDir(specVolID string, host volume.VolumeHost) string","file":"pkg/volume/csi/csi_util.go","code":"// getVolumePluginDir returns the path where CSI plugin keeps metadata for given volume\nfunc getVolumePluginDir(specVolID string, host volume.VolumeHost) string {\n\tsanitizedSpecVolID := utilstrings.EscapeQualifiedName(specVolID)\n\treturn filepath.Join(host.GetVolumeDevicePluginDir(CSIPluginName), sanitizedSpecVolID)\n}","line":{"from":111,"to":115}} {"id":100012033,"name":"getVolumeDevicePluginDir","signature":"func getVolumeDevicePluginDir(specVolID string, host volume.VolumeHost) string","file":"pkg/volume/csi/csi_util.go","code":"// getVolumeDevicePluginDir returns the path where the CSI plugin keeps the\n// symlink for a block device associated with a given specVolumeID.\n// path: plugins/kubernetes.io/csi/volumeDevices/{specVolumeID}/dev\nfunc getVolumeDevicePluginDir(specVolID string, host volume.VolumeHost) string {\n\treturn filepath.Join(getVolumePluginDir(specVolID, host), \"dev\")\n}","line":{"from":117,"to":122}} {"id":100012034,"name":"getVolumeDeviceDataDir","signature":"func getVolumeDeviceDataDir(specVolID string, host volume.VolumeHost) string","file":"pkg/volume/csi/csi_util.go","code":"// getVolumeDeviceDataDir returns the path where the CSI plugin keeps the\n// volume data for a block device associated with a given specVolumeID.\n// path: plugins/kubernetes.io/csi/volumeDevices/{specVolumeID}/data\nfunc getVolumeDeviceDataDir(specVolID string, host volume.VolumeHost) string {\n\treturn filepath.Join(getVolumePluginDir(specVolID, host), \"data\")\n}","line":{"from":124,"to":129}} {"id":100012035,"name":"hasReadWriteOnce","signature":"func hasReadWriteOnce(modes []api.PersistentVolumeAccessMode) bool","file":"pkg/volume/csi/csi_util.go","code":"// hasReadWriteOnce returns true if modes contains v1.ReadWriteOnce\nfunc hasReadWriteOnce(modes []api.PersistentVolumeAccessMode) bool {\n\tif modes == nil {\n\t\treturn false\n\t}\n\tfor _, mode := range modes {\n\t\tif mode == api.ReadWriteOnce {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":131,"to":142}} {"id":100012036,"name":"getSourceFromSpec","signature":"func getSourceFromSpec(spec *volume.Spec) (*api.CSIVolumeSource, *api.CSIPersistentVolumeSource, error)","file":"pkg/volume/csi/csi_util.go","code":"// getSourceFromSpec returns either CSIVolumeSource or CSIPersistentVolumeSource, but not both\nfunc getSourceFromSpec(spec *volume.Spec) (*api.CSIVolumeSource, *api.CSIPersistentVolumeSource, error) {\n\tif spec == nil {\n\t\treturn nil, nil, fmt.Errorf(\"volume.Spec nil\")\n\t}\n\tif spec.Volume != nil \u0026\u0026 spec.PersistentVolume != nil {\n\t\treturn nil, nil, fmt.Errorf(\"volume.Spec has both volume and persistent volume sources\")\n\t}\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.CSI != nil {\n\t\treturn spec.Volume.CSI, nil, nil\n\t}\n\tif spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.CSI != nil {\n\t\treturn nil, spec.PersistentVolume.Spec.CSI, nil\n\t}\n\n\treturn nil, nil, fmt.Errorf(\"volume source not found in volume.Spec\")\n}","line":{"from":144,"to":161}} {"id":100012037,"name":"getPVSourceFromSpec","signature":"func getPVSourceFromSpec(spec *volume.Spec) (*api.CSIPersistentVolumeSource, error)","file":"pkg/volume/csi/csi_util.go","code":"// getPVSourceFromSpec ensures only CSIPersistentVolumeSource is present in volume.Spec\nfunc getPVSourceFromSpec(spec *volume.Spec) (*api.CSIPersistentVolumeSource, error) {\n\tvolSrc, pvSrc, err := getSourceFromSpec(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif volSrc != nil {\n\t\treturn nil, fmt.Errorf(\"unexpected api.CSIVolumeSource found in volume.Spec\")\n\t}\n\treturn pvSrc, nil\n}","line":{"from":163,"to":173}} {"id":100012038,"name":"GetCSIMounterPath","signature":"func GetCSIMounterPath(path string) string","file":"pkg/volume/csi/csi_util.go","code":"// GetCSIMounterPath returns the mounter path given the base path.\nfunc GetCSIMounterPath(path string) string {\n\treturn filepath.Join(path, \"/mount\")\n}","line":{"from":175,"to":178}} {"id":100012039,"name":"GetCSIDriverName","signature":"func GetCSIDriverName(spec *volume.Spec) (string, error)","file":"pkg/volume/csi/csi_util.go","code":"// GetCSIDriverName returns the csi driver name\nfunc GetCSIDriverName(spec *volume.Spec) (string, error) {\n\tvolSrc, pvSrc, err := getSourceFromSpec(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tswitch {\n\tcase volSrc != nil:\n\t\treturn volSrc.Driver, nil\n\tcase pvSrc != nil:\n\t\treturn pvSrc.Driver, nil\n\tdefault:\n\t\treturn \"\", errors.New(log(\"volume source not found in volume.Spec\"))\n\t}\n}","line":{"from":180,"to":195}} {"id":100012040,"name":"createCSIOperationContext","signature":"func createCSIOperationContext(volumeSpec *volume.Spec, timeout time.Duration) (context.Context, context.CancelFunc)","file":"pkg/volume/csi/csi_util.go","code":"func createCSIOperationContext(volumeSpec *volume.Spec, timeout time.Duration) (context.Context, context.CancelFunc) {\n\tmigrated := false\n\tif volumeSpec != nil {\n\t\tmigrated = volumeSpec.Migrated\n\t}\n\tctx := context.WithValue(context.Background(), additionalInfoKey, additionalInfo{Migrated: strconv.FormatBool(migrated)})\n\treturn context.WithTimeout(ctx, timeout)\n}","line":{"from":197,"to":204}} {"id":100012041,"name":"getPodInfoAttrs","signature":"func getPodInfoAttrs(pod *api.Pod, volumeMode storage.VolumeLifecycleMode) map[string]string","file":"pkg/volume/csi/csi_util.go","code":"// getPodInfoAttrs returns pod info for NodePublish\nfunc getPodInfoAttrs(pod *api.Pod, volumeMode storage.VolumeLifecycleMode) map[string]string {\n\tattrs := map[string]string{\n\t\t\"csi.storage.k8s.io/pod.name\": pod.Name,\n\t\t\"csi.storage.k8s.io/pod.namespace\": pod.Namespace,\n\t\t\"csi.storage.k8s.io/pod.uid\": string(pod.UID),\n\t\t\"csi.storage.k8s.io/serviceAccount.name\": pod.Spec.ServiceAccountName,\n\t\t\"csi.storage.k8s.io/ephemeral\": strconv.FormatBool(volumeMode == storage.VolumeLifecycleEphemeral),\n\t}\n\treturn attrs\n}","line":{"from":206,"to":216}} {"id":100012042,"name":"RequiresFSResize","signature":"func (c *csiPlugin) RequiresFSResize() bool","file":"pkg/volume/csi/expander.go","code":"func (c *csiPlugin) RequiresFSResize() bool {\n\treturn true\n}","line":{"from":36,"to":38}} {"id":100012043,"name":"NodeExpand","signature":"func (c *csiPlugin) NodeExpand(resizeOptions volume.NodeResizeOptions) (bool, error)","file":"pkg/volume/csi/expander.go","code":"func (c *csiPlugin) NodeExpand(resizeOptions volume.NodeResizeOptions) (bool, error) {\n\tklog.V(4).Infof(log(\"Expander.NodeExpand(%s)\", resizeOptions.DeviceMountPath))\n\tcsiSource, err := getCSISourceFromSpec(resizeOptions.VolumeSpec)\n\tif err != nil {\n\t\treturn false, errors.New(log(\"Expander.NodeExpand failed to get CSI persistent source: %v\", err))\n\t}\n\n\tcsClient, err := newCsiDriverClient(csiDriverName(csiSource.Driver))\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tfsVolume, err := util.CheckVolumeModeFilesystem(resizeOptions.VolumeSpec)\n\tif err != nil {\n\t\treturn false, errors.New(log(\"Expander.NodeExpand failed to check VolumeMode of source: %v\", err))\n\t}\n\n\treturn c.nodeExpandWithClient(resizeOptions, csiSource, csClient, fsVolume)\n}","line":{"from":40,"to":57}} {"id":100012044,"name":"nodeExpandWithClient","signature":"func (c *csiPlugin) nodeExpandWithClient(","file":"pkg/volume/csi/expander.go","code":"func (c *csiPlugin) nodeExpandWithClient(\n\tresizeOptions volume.NodeResizeOptions,\n\tcsiSource *api.CSIPersistentVolumeSource,\n\tcsClient csiClient,\n\tfsVolume bool) (bool, error) {\n\tdriverName := csiSource.Driver\n\n\tctx, cancel := createCSIOperationContext(resizeOptions.VolumeSpec, csiTimeout)\n\tdefer cancel()\n\n\tnodeExpandSet, err := csClient.NodeSupportsNodeExpand(ctx)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"Expander.NodeExpand failed to check if node supports expansion : %v\", err)\n\t}\n\n\tif !nodeExpandSet {\n\t\treturn false, fmt.Errorf(\"Expander.NodeExpand found CSI plugin %s/%s to not support node expansion\", c.GetPluginName(), driverName)\n\t}\n\n\tpv := resizeOptions.VolumeSpec.PersistentVolume\n\tif pv == nil {\n\t\treturn false, fmt.Errorf(\"Expander.NodeExpand failed to find associated PersistentVolume for plugin %s\", c.GetPluginName())\n\t}\n\tnodeExpandSecrets := map[string]string{}\n\texpandClient := c.host.GetKubeClient()\n\tif utilfeature.DefaultFeatureGate.Enabled(features.CSINodeExpandSecret) {\n\t\tif csiSource.NodeExpandSecretRef != nil {\n\t\t\tnodeExpandSecrets, err = getCredentialsFromSecret(expandClient, csiSource.NodeExpandSecretRef)\n\t\t\tif err != nil {\n\t\t\t\treturn false, fmt.Errorf(\"expander.NodeExpand failed to get NodeExpandSecretRef %s/%s: %v\",\n\t\t\t\t\tcsiSource.NodeExpandSecretRef.Namespace, csiSource.NodeExpandSecretRef.Name, err)\n\t\t\t}\n\t\t}\n\t}\n\n\topts := csiResizeOptions{\n\t\tvolumePath: resizeOptions.DeviceMountPath,\n\t\tstagingTargetPath: resizeOptions.DeviceStagePath,\n\t\tvolumeID: csiSource.VolumeHandle,\n\t\tnewSize: resizeOptions.NewSize,\n\t\tfsType: csiSource.FSType,\n\t\taccessMode: api.ReadWriteOnce,\n\t\tmountOptions: pv.Spec.MountOptions,\n\t\tsecrets: nodeExpandSecrets,\n\t}\n\n\tif !fsVolume {\n\t\t// for block volumes the volumePath in CSI NodeExpandvolumeRequest is\n\t\t// basically same as DevicePath because block devices are not mounted and hence\n\t\t// DeviceMountPath does not get populated in resizeOptions.DeviceMountPath\n\t\topts.volumePath = resizeOptions.DevicePath\n\t\topts.fsType = fsTypeBlockName\n\t}\n\n\tif pv.Spec.AccessModes != nil {\n\t\topts.accessMode = pv.Spec.AccessModes[0]\n\t}\n\n\t_, err = csClient.NodeExpandVolume(ctx, opts)\n\tif err != nil {\n\t\tif inUseError(err) {\n\t\t\tfailedConditionErr := fmt.Errorf(\"Expander.NodeExpand failed to expand the volume : %w\", volumetypes.NewFailedPreconditionError(err.Error()))\n\t\t\treturn false, failedConditionErr\n\t\t}\n\t\treturn false, fmt.Errorf(\"Expander.NodeExpand failed to expand the volume : %w\", err)\n\t}\n\treturn true, nil\n}","line":{"from":59,"to":126}} {"id":100012045,"name":"inUseError","signature":"func inUseError(err error) bool","file":"pkg/volume/csi/expander.go","code":"func inUseError(err error) bool {\n\tst, ok := status.FromError(err)\n\tif !ok {\n\t\t// not a grpc error\n\t\treturn false\n\t}\n\t// if this is a failed precondition error then that means driver does not support expansion\n\t// of in-use volumes\n\t// More info - https://github.com/container-storage-interface/spec/blob/master/spec.md#controllerexpandvolume-errors\n\treturn st.Code() == codes.FailedPrecondition\n}","line":{"from":128,"to":138}} {"id":100012046,"name":"NewNodeInfoManager","signature":"func NewNodeInfoManager(","file":"pkg/volume/csi/nodeinfomanager/nodeinfomanager.go","code":"// NewNodeInfoManager initializes nodeInfoManager\nfunc NewNodeInfoManager(\n\tnodeName types.NodeName,\n\tvolumeHost volume.VolumeHost,\n\tmigratedPlugins map[string](func() bool)) Interface {\n\treturn \u0026nodeInfoManager{\n\t\tnodeName: nodeName,\n\t\tvolumeHost: volumeHost,\n\t\tmigratedPlugins: migratedPlugins,\n\t}\n}","line":{"from":93,"to":103}} {"id":100012047,"name":"InstallCSIDriver","signature":"func (nim *nodeInfoManager) InstallCSIDriver(driverName string, driverNodeID string, maxAttachLimit int64, topology map[string]string) error","file":"pkg/volume/csi/nodeinfomanager/nodeinfomanager.go","code":"// InstallCSIDriver updates the node ID annotation in the Node object and CSIDrivers field in the\n// CSINode object. If the CSINode object doesn't yet exist, it will be created.\n// If multiple calls to InstallCSIDriver() are made in parallel, some calls might receive Node or\n// CSINode update conflicts, which causes the function to retry the corresponding update.\nfunc (nim *nodeInfoManager) InstallCSIDriver(driverName string, driverNodeID string, maxAttachLimit int64, topology map[string]string) error {\n\tif driverNodeID == \"\" {\n\t\treturn fmt.Errorf(\"error adding CSI driver node info: driverNodeID must not be empty\")\n\t}\n\n\tnodeUpdateFuncs := []nodeUpdateFunc{\n\t\tupdateNodeIDInNode(driverName, driverNodeID),\n\t\tupdateTopologyLabels(topology),\n\t}\n\n\terr := nim.updateNode(nodeUpdateFuncs...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error updating Node object with CSI driver node info: %v\", err)\n\t}\n\n\terr = nim.updateCSINode(driverName, driverNodeID, maxAttachLimit, topology)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error updating CSINode object with CSI driver node info: %v\", err)\n\t}\n\n\treturn nil\n}","line":{"from":105,"to":130}} {"id":100012048,"name":"UninstallCSIDriver","signature":"func (nim *nodeInfoManager) UninstallCSIDriver(driverName string) error","file":"pkg/volume/csi/nodeinfomanager/nodeinfomanager.go","code":"// UninstallCSIDriver removes the node ID annotation from the Node object and CSIDrivers field from the\n// CSINode object. If the CSINodeInfo object contains no CSIDrivers, it will be deleted.\n// If multiple calls to UninstallCSIDriver() are made in parallel, some calls might receive Node or\n// CSINode update conflicts, which causes the function to retry the corresponding update.\nfunc (nim *nodeInfoManager) UninstallCSIDriver(driverName string) error {\n\terr := nim.uninstallDriverFromCSINode(driverName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error uninstalling CSI driver from CSINode object %v\", err)\n\t}\n\n\terr = nim.updateNode(\n\t\tremoveMaxAttachLimit(driverName),\n\t\tremoveNodeIDFromNode(driverName),\n\t)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error removing CSI driver node info from Node object %v\", err)\n\t}\n\treturn nil\n}","line":{"from":132,"to":150}} {"id":100012049,"name":"updateNode","signature":"func (nim *nodeInfoManager) updateNode(updateFuncs ...nodeUpdateFunc) error","file":"pkg/volume/csi/nodeinfomanager/nodeinfomanager.go","code":"func (nim *nodeInfoManager) updateNode(updateFuncs ...nodeUpdateFunc) error {\n\tvar updateErrs []error\n\terr := wait.ExponentialBackoff(updateBackoff, func() (bool, error) {\n\t\tif err := nim.tryUpdateNode(updateFuncs...); err != nil {\n\t\t\tupdateErrs = append(updateErrs, err)\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error updating node: %v; caused by: %v\", err, utilerrors.NewAggregate(updateErrs))\n\t}\n\treturn nil\n}","line":{"from":152,"to":165}} {"id":100012050,"name":"tryUpdateNode","signature":"func (nim *nodeInfoManager) tryUpdateNode(updateFuncs ...nodeUpdateFunc) error","file":"pkg/volume/csi/nodeinfomanager/nodeinfomanager.go","code":"// updateNode repeatedly attempts to update the corresponding node object\n// which is modified by applying the given update functions sequentially.\n// Because updateFuncs are applied sequentially, later updateFuncs should take into account\n// the effects of previous updateFuncs to avoid potential conflicts. For example, if multiple\n// functions update the same field, updates in the last function are persisted.\nfunc (nim *nodeInfoManager) tryUpdateNode(updateFuncs ...nodeUpdateFunc) error {\n\tnim.lock.Lock()\n\tdefer nim.lock.Unlock()\n\n\t// Retrieve the latest version of Node before attempting update, so that\n\t// existing changes are not overwritten.\n\n\tkubeClient := nim.volumeHost.GetKubeClient()\n\tif kubeClient == nil {\n\t\treturn fmt.Errorf(\"error getting kube client\")\n\t}\n\n\tnodeClient := kubeClient.CoreV1().Nodes()\n\toriginalNode, err := nodeClient.Get(context.TODO(), string(nim.nodeName), metav1.GetOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\tnode := originalNode.DeepCopy()\n\n\tneedUpdate := false\n\tfor _, update := range updateFuncs {\n\t\tnewNode, updated, err := update(node)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnode = newNode\n\t\tneedUpdate = needUpdate || updated\n\t}\n\n\tif needUpdate {\n\t\t// PatchNodeStatus can update both node's status and labels or annotations\n\t\t// Updating status by directly updating node does not work\n\t\t_, _, updateErr := nodeutil.PatchNodeStatus(kubeClient.CoreV1(), types.NodeName(node.Name), originalNode, node)\n\t\treturn updateErr\n\t}\n\n\treturn nil\n}","line":{"from":167,"to":209}} {"id":100012051,"name":"buildNodeIDMapFromAnnotation","signature":"func buildNodeIDMapFromAnnotation(node *v1.Node) (map[string]string, error)","file":"pkg/volume/csi/nodeinfomanager/nodeinfomanager.go","code":"// Guarantees the map is non-nil if no error is returned.\nfunc buildNodeIDMapFromAnnotation(node *v1.Node) (map[string]string, error) {\n\tvar previousAnnotationValue string\n\tif node.ObjectMeta.Annotations != nil {\n\t\tpreviousAnnotationValue =\n\t\t\tnode.ObjectMeta.Annotations[annotationKeyNodeID]\n\t}\n\n\tvar existingDriverMap map[string]string\n\tif previousAnnotationValue != \"\" {\n\t\t// Parse previousAnnotationValue as JSON\n\t\tif err := json.Unmarshal([]byte(previousAnnotationValue), \u0026existingDriverMap); err != nil {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"failed to parse node's %q annotation value (%q) err=%v\",\n\t\t\t\tannotationKeyNodeID,\n\t\t\t\tpreviousAnnotationValue,\n\t\t\t\terr)\n\t\t}\n\t}\n\n\tif existingDriverMap == nil {\n\t\treturn make(map[string]string), nil\n\t}\n\treturn existingDriverMap, nil\n}","line":{"from":211,"to":235}} {"id":100012052,"name":"updateNodeIDInNode","signature":"func updateNodeIDInNode(","file":"pkg/volume/csi/nodeinfomanager/nodeinfomanager.go","code":"// updateNodeIDInNode returns a function that updates a Node object with the given\n// Node ID information.\nfunc updateNodeIDInNode(\n\tcsiDriverName string,\n\tcsiDriverNodeID string) nodeUpdateFunc {\n\treturn func(node *v1.Node) (*v1.Node, bool, error) {\n\t\texistingDriverMap, err := buildNodeIDMapFromAnnotation(node)\n\t\tif err != nil {\n\t\t\treturn nil, false, err\n\t\t}\n\n\t\tif val, ok := existingDriverMap[csiDriverName]; ok {\n\t\t\tif val == csiDriverNodeID {\n\t\t\t\t// Value already exists in node annotation, nothing more to do\n\t\t\t\treturn node, false, nil\n\t\t\t}\n\t\t}\n\n\t\t// Add/update annotation value\n\t\texistingDriverMap[csiDriverName] = csiDriverNodeID\n\t\tjsonObj, err := json.Marshal(existingDriverMap)\n\t\tif err != nil {\n\t\t\treturn nil, false, fmt.Errorf(\n\t\t\t\t\"error while marshalling node ID map updated with driverName=%q, nodeID=%q: %v\",\n\t\t\t\tcsiDriverName,\n\t\t\t\tcsiDriverNodeID,\n\t\t\t\terr)\n\t\t}\n\n\t\tif node.ObjectMeta.Annotations == nil {\n\t\t\tnode.ObjectMeta.Annotations = make(map[string]string)\n\t\t}\n\t\tnode.ObjectMeta.Annotations[annotationKeyNodeID] = string(jsonObj)\n\n\t\treturn node, true, nil\n\t}\n}","line":{"from":237,"to":273}} {"id":100012053,"name":"removeNodeIDFromNode","signature":"func removeNodeIDFromNode(csiDriverName string) nodeUpdateFunc","file":"pkg/volume/csi/nodeinfomanager/nodeinfomanager.go","code":"// removeNodeIDFromNode returns a function that removes node ID information matching the given\n// driver name from a Node object.\nfunc removeNodeIDFromNode(csiDriverName string) nodeUpdateFunc {\n\treturn func(node *v1.Node) (*v1.Node, bool, error) {\n\t\tvar previousAnnotationValue string\n\t\tif node.ObjectMeta.Annotations != nil {\n\t\t\tpreviousAnnotationValue =\n\t\t\t\tnode.ObjectMeta.Annotations[annotationKeyNodeID]\n\t\t}\n\n\t\tif previousAnnotationValue == \"\" {\n\t\t\treturn node, false, nil\n\t\t}\n\n\t\t// Parse previousAnnotationValue as JSON\n\t\texistingDriverMap := map[string]string{}\n\t\tif err := json.Unmarshal([]byte(previousAnnotationValue), \u0026existingDriverMap); err != nil {\n\t\t\treturn nil, false, fmt.Errorf(\n\t\t\t\t\"failed to parse node's %q annotation value (%q) err=%v\",\n\t\t\t\tannotationKeyNodeID,\n\t\t\t\tpreviousAnnotationValue,\n\t\t\t\terr)\n\t\t}\n\n\t\tif _, ok := existingDriverMap[csiDriverName]; !ok {\n\t\t\t// Value is already missing in node annotation, nothing more to do\n\t\t\treturn node, false, nil\n\t\t}\n\n\t\t// Delete annotation value\n\t\tdelete(existingDriverMap, csiDriverName)\n\t\tif len(existingDriverMap) == 0 {\n\t\t\tdelete(node.ObjectMeta.Annotations, annotationKeyNodeID)\n\t\t} else {\n\t\t\tjsonObj, err := json.Marshal(existingDriverMap)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, false, fmt.Errorf(\n\t\t\t\t\t\"failed while trying to remove key %q from node %q annotation. Existing data: %v\",\n\t\t\t\t\tcsiDriverName,\n\t\t\t\t\tannotationKeyNodeID,\n\t\t\t\t\tpreviousAnnotationValue)\n\t\t\t}\n\n\t\t\tnode.ObjectMeta.Annotations[annotationKeyNodeID] = string(jsonObj)\n\t\t}\n\n\t\treturn node, true, nil\n\t}\n}","line":{"from":275,"to":323}} {"id":100012054,"name":"updateTopologyLabels","signature":"func updateTopologyLabels(topology map[string]string) nodeUpdateFunc","file":"pkg/volume/csi/nodeinfomanager/nodeinfomanager.go","code":"// updateTopologyLabels returns a function that updates labels of a Node object with the given\n// topology information.\nfunc updateTopologyLabels(topology map[string]string) nodeUpdateFunc {\n\treturn func(node *v1.Node) (*v1.Node, bool, error) {\n\t\tif len(topology) == 0 {\n\t\t\treturn node, false, nil\n\t\t}\n\n\t\tfor k, v := range topology {\n\t\t\tif curVal, exists := node.Labels[k]; exists \u0026\u0026 curVal != v {\n\t\t\t\treturn nil, false, fmt.Errorf(\"detected topology value collision: driver reported %q:%q but existing label is %q:%q\", k, v, k, curVal)\n\t\t\t}\n\t\t}\n\n\t\tif node.Labels == nil {\n\t\t\tnode.Labels = make(map[string]string)\n\t\t}\n\t\tfor k, v := range topology {\n\t\t\tnode.Labels[k] = v\n\t\t}\n\t\treturn node, true, nil\n\t}\n}","line":{"from":325,"to":347}} {"id":100012055,"name":"updateCSINode","signature":"func (nim *nodeInfoManager) updateCSINode(","file":"pkg/volume/csi/nodeinfomanager/nodeinfomanager.go","code":"func (nim *nodeInfoManager) updateCSINode(\n\tdriverName string,\n\tdriverNodeID string,\n\tmaxAttachLimit int64,\n\ttopology map[string]string) error {\n\n\tcsiKubeClient := nim.volumeHost.GetKubeClient()\n\tif csiKubeClient == nil {\n\t\treturn fmt.Errorf(\"error getting CSI client\")\n\t}\n\n\tvar updateErrs []error\n\terr := wait.ExponentialBackoff(updateBackoff, func() (bool, error) {\n\t\tif err := nim.tryUpdateCSINode(csiKubeClient, driverName, driverNodeID, maxAttachLimit, topology); err != nil {\n\t\t\tupdateErrs = append(updateErrs, err)\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error updating CSINode: %v; caused by: %v\", err, utilerrors.NewAggregate(updateErrs))\n\t}\n\treturn nil\n}","line":{"from":349,"to":372}} {"id":100012056,"name":"tryUpdateCSINode","signature":"func (nim *nodeInfoManager) tryUpdateCSINode(","file":"pkg/volume/csi/nodeinfomanager/nodeinfomanager.go","code":"func (nim *nodeInfoManager) tryUpdateCSINode(\n\tcsiKubeClient clientset.Interface,\n\tdriverName string,\n\tdriverNodeID string,\n\tmaxAttachLimit int64,\n\ttopology map[string]string) error {\n\n\tnodeInfo, err := csiKubeClient.StorageV1().CSINodes().Get(context.TODO(), string(nim.nodeName), metav1.GetOptions{})\n\tif nodeInfo == nil || errors.IsNotFound(err) {\n\t\tnodeInfo, err = nim.CreateCSINode()\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nim.installDriverToCSINode(nodeInfo, driverName, driverNodeID, maxAttachLimit, topology)\n}","line":{"from":374,"to":390}} {"id":100012057,"name":"InitializeCSINodeWithAnnotation","signature":"func (nim *nodeInfoManager) InitializeCSINodeWithAnnotation() error","file":"pkg/volume/csi/nodeinfomanager/nodeinfomanager.go","code":"func (nim *nodeInfoManager) InitializeCSINodeWithAnnotation() error {\n\tcsiKubeClient := nim.volumeHost.GetKubeClient()\n\tif csiKubeClient == nil {\n\t\treturn goerrors.New(\"error getting CSI client\")\n\t}\n\n\tvar lastErr error\n\terr := wait.ExponentialBackoff(updateBackoff, func() (bool, error) {\n\t\tif lastErr = nim.tryInitializeCSINodeWithAnnotation(csiKubeClient); lastErr != nil {\n\t\t\tklog.V(2).Infof(\"Failed to publish CSINode: %v\", lastErr)\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error updating CSINode annotation: %v; caused by: %v\", err, lastErr)\n\t}\n\n\treturn nil\n}","line":{"from":392,"to":411}} {"id":100012058,"name":"tryInitializeCSINodeWithAnnotation","signature":"func (nim *nodeInfoManager) tryInitializeCSINodeWithAnnotation(csiKubeClient clientset.Interface) error","file":"pkg/volume/csi/nodeinfomanager/nodeinfomanager.go","code":"func (nim *nodeInfoManager) tryInitializeCSINodeWithAnnotation(csiKubeClient clientset.Interface) error {\n\tnodeInfo, err := csiKubeClient.StorageV1().CSINodes().Get(context.TODO(), string(nim.nodeName), metav1.GetOptions{})\n\tif nodeInfo == nil || errors.IsNotFound(err) {\n\t\t// CreateCSINode will set the annotation\n\t\t_, err = nim.CreateCSINode()\n\t\treturn err\n\t} else if err != nil {\n\t\treturn err\n\t}\n\n\tannotationModified := setMigrationAnnotation(nim.migratedPlugins, nodeInfo)\n\n\tif annotationModified {\n\t\t_, err := csiKubeClient.StorageV1().CSINodes().Update(context.TODO(), nodeInfo, metav1.UpdateOptions{})\n\t\treturn err\n\t}\n\treturn nil\n\n}","line":{"from":413,"to":431}} {"id":100012059,"name":"CreateCSINode","signature":"func (nim *nodeInfoManager) CreateCSINode() (*storagev1.CSINode, error)","file":"pkg/volume/csi/nodeinfomanager/nodeinfomanager.go","code":"func (nim *nodeInfoManager) CreateCSINode() (*storagev1.CSINode, error) {\n\n\tcsiKubeClient := nim.volumeHost.GetKubeClient()\n\tif csiKubeClient == nil {\n\t\treturn nil, fmt.Errorf(\"error getting CSI client\")\n\t}\n\n\tnode, err := csiKubeClient.CoreV1().Nodes().Get(context.TODO(), string(nim.nodeName), metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnodeInfo := \u0026storagev1.CSINode{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: string(nim.nodeName),\n\t\t\tOwnerReferences: []metav1.OwnerReference{\n\t\t\t\t{\n\t\t\t\t\tAPIVersion: nodeKind.Version,\n\t\t\t\t\tKind: nodeKind.Kind,\n\t\t\t\t\tName: node.Name,\n\t\t\t\t\tUID: node.UID,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tSpec: storagev1.CSINodeSpec{\n\t\t\tDrivers: []storagev1.CSINodeDriver{},\n\t\t},\n\t}\n\n\tsetMigrationAnnotation(nim.migratedPlugins, nodeInfo)\n\n\treturn csiKubeClient.StorageV1().CSINodes().Create(context.TODO(), nodeInfo, metav1.CreateOptions{})\n}","line":{"from":433,"to":465}} {"id":100012060,"name":"setMigrationAnnotation","signature":"func setMigrationAnnotation(migratedPlugins map[string](func() bool), nodeInfo *storagev1.CSINode) (modified bool)","file":"pkg/volume/csi/nodeinfomanager/nodeinfomanager.go","code":"func setMigrationAnnotation(migratedPlugins map[string](func() bool), nodeInfo *storagev1.CSINode) (modified bool) {\n\tif migratedPlugins == nil {\n\t\treturn false\n\t}\n\n\tnodeInfoAnnotations := nodeInfo.GetAnnotations()\n\tif nodeInfoAnnotations == nil {\n\t\tnodeInfoAnnotations = map[string]string{}\n\t}\n\n\tvar oldAnnotationSet sets.String\n\tmpa := nodeInfoAnnotations[v1.MigratedPluginsAnnotationKey]\n\ttok := strings.Split(mpa, \",\")\n\tif len(mpa) == 0 {\n\t\toldAnnotationSet = sets.NewString()\n\t} else {\n\t\toldAnnotationSet = sets.NewString(tok...)\n\t}\n\n\tnewAnnotationSet := sets.NewString()\n\tfor pluginName, migratedFunc := range migratedPlugins {\n\t\tif migratedFunc() {\n\t\t\tnewAnnotationSet.Insert(pluginName)\n\t\t}\n\t}\n\n\tif oldAnnotationSet.Equal(newAnnotationSet) {\n\t\treturn false\n\t}\n\n\tnas := strings.Join(newAnnotationSet.List(), \",\")\n\tif len(nas) != 0 {\n\t\tnodeInfoAnnotations[v1.MigratedPluginsAnnotationKey] = nas\n\t} else {\n\t\tdelete(nodeInfoAnnotations, v1.MigratedPluginsAnnotationKey)\n\t}\n\n\tnodeInfo.Annotations = nodeInfoAnnotations\n\treturn true\n}","line":{"from":467,"to":506}} {"id":100012061,"name":"keepAllocatableCount","signature":"func keepAllocatableCount(driverInfoSpec storagev1.CSINodeDriver, maxAttachLimit int64) bool","file":"pkg/volume/csi/nodeinfomanager/nodeinfomanager.go","code":"// Returns true if and only if new maxAttachLimit doesn't require CSINode update\nfunc keepAllocatableCount(driverInfoSpec storagev1.CSINodeDriver, maxAttachLimit int64) bool {\n\tif maxAttachLimit == 0 {\n\t\treturn driverInfoSpec.Allocatable == nil || driverInfoSpec.Allocatable.Count == nil\n\t}\n\n\treturn driverInfoSpec.Allocatable != nil \u0026\u0026 driverInfoSpec.Allocatable.Count != nil \u0026\u0026 int64(*driverInfoSpec.Allocatable.Count) == maxAttachLimit\n}","line":{"from":508,"to":515}} {"id":100012062,"name":"installDriverToCSINode","signature":"func (nim *nodeInfoManager) installDriverToCSINode(","file":"pkg/volume/csi/nodeinfomanager/nodeinfomanager.go","code":"func (nim *nodeInfoManager) installDriverToCSINode(\n\tnodeInfo *storagev1.CSINode,\n\tdriverName string,\n\tdriverNodeID string,\n\tmaxAttachLimit int64,\n\ttopology map[string]string) error {\n\n\tcsiKubeClient := nim.volumeHost.GetKubeClient()\n\tif csiKubeClient == nil {\n\t\treturn fmt.Errorf(\"error getting CSI client\")\n\t}\n\n\ttopologyKeys := make(sets.String)\n\tfor k := range topology {\n\t\ttopologyKeys.Insert(k)\n\t}\n\n\tspecModified := true\n\t// Clone driver list, omitting the driver that matches the given driverName\n\tnewDriverSpecs := []storagev1.CSINodeDriver{}\n\tfor _, driverInfoSpec := range nodeInfo.Spec.Drivers {\n\t\tif driverInfoSpec.Name == driverName {\n\t\t\tif driverInfoSpec.NodeID == driverNodeID \u0026\u0026\n\t\t\t\tsets.NewString(driverInfoSpec.TopologyKeys...).Equal(topologyKeys) \u0026\u0026\n\t\t\t\tkeepAllocatableCount(driverInfoSpec, maxAttachLimit) {\n\t\t\t\tspecModified = false\n\t\t\t}\n\t\t} else {\n\t\t\t// Omit driverInfoSpec matching given driverName\n\t\t\tnewDriverSpecs = append(newDriverSpecs, driverInfoSpec)\n\t\t}\n\t}\n\n\tannotationModified := setMigrationAnnotation(nim.migratedPlugins, nodeInfo)\n\n\tif !specModified \u0026\u0026 !annotationModified {\n\t\treturn nil\n\t}\n\n\t// Append new driver\n\tdriverSpec := storagev1.CSINodeDriver{\n\t\tName: driverName,\n\t\tNodeID: driverNodeID,\n\t\tTopologyKeys: topologyKeys.List(),\n\t}\n\n\tif maxAttachLimit \u003e 0 {\n\t\tif maxAttachLimit \u003e math.MaxInt32 {\n\t\t\tklog.Warningf(\"Exceeded max supported attach limit value, truncating it to %d\", math.MaxInt32)\n\t\t\tmaxAttachLimit = math.MaxInt32\n\t\t}\n\t\tm := int32(maxAttachLimit)\n\t\tdriverSpec.Allocatable = \u0026storagev1.VolumeNodeResources{Count: \u0026m}\n\t} else if maxAttachLimit != 0 {\n\t\tklog.Errorf(\"Invalid attach limit value %d cannot be added to CSINode object for %q\", maxAttachLimit, driverName)\n\t}\n\n\tnewDriverSpecs = append(newDriverSpecs, driverSpec)\n\tnodeInfo.Spec.Drivers = newDriverSpecs\n\n\t_, err := csiKubeClient.StorageV1().CSINodes().Update(context.TODO(), nodeInfo, metav1.UpdateOptions{})\n\treturn err\n}","line":{"from":517,"to":579}} {"id":100012063,"name":"uninstallDriverFromCSINode","signature":"func (nim *nodeInfoManager) uninstallDriverFromCSINode(","file":"pkg/volume/csi/nodeinfomanager/nodeinfomanager.go","code":"func (nim *nodeInfoManager) uninstallDriverFromCSINode(\n\tcsiDriverName string) error {\n\n\tcsiKubeClient := nim.volumeHost.GetKubeClient()\n\tif csiKubeClient == nil {\n\t\treturn fmt.Errorf(\"error getting CSI client\")\n\t}\n\n\tvar updateErrs []error\n\terr := wait.ExponentialBackoff(updateBackoff, func() (bool, error) {\n\t\tif err := nim.tryUninstallDriverFromCSINode(csiKubeClient, csiDriverName); err != nil {\n\t\t\tupdateErrs = append(updateErrs, err)\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error updating CSINode: %v; caused by: %v\", err, utilerrors.NewAggregate(updateErrs))\n\t}\n\treturn nil\n}","line":{"from":581,"to":601}} {"id":100012064,"name":"tryUninstallDriverFromCSINode","signature":"func (nim *nodeInfoManager) tryUninstallDriverFromCSINode(","file":"pkg/volume/csi/nodeinfomanager/nodeinfomanager.go","code":"func (nim *nodeInfoManager) tryUninstallDriverFromCSINode(\n\tcsiKubeClient clientset.Interface,\n\tcsiDriverName string) error {\n\n\tnodeInfoClient := csiKubeClient.StorageV1().CSINodes()\n\tnodeInfo, err := nodeInfoClient.Get(context.TODO(), string(nim.nodeName), metav1.GetOptions{})\n\tif err != nil \u0026\u0026 errors.IsNotFound(err) {\n\t\treturn nil\n\t} else if err != nil {\n\t\treturn err\n\t}\n\n\thasModified := false\n\t// Uninstall CSINodeDriver with name csiDriverName\n\tdrivers := nodeInfo.Spec.Drivers[:0]\n\tfor _, driver := range nodeInfo.Spec.Drivers {\n\t\tif driver.Name != csiDriverName {\n\t\t\tdrivers = append(drivers, driver)\n\t\t} else {\n\t\t\t// Found a driver with name csiDriverName\n\t\t\t// Set hasModified to true because it will be removed\n\t\t\thasModified = true\n\t\t}\n\t}\n\n\tif !hasModified {\n\t\t// No changes, don't update\n\t\treturn nil\n\t}\n\tnodeInfo.Spec.Drivers = drivers\n\n\t_, err = nodeInfoClient.Update(context.TODO(), nodeInfo, metav1.UpdateOptions{})\n\n\treturn err // do not wrap error\n\n}","line":{"from":603,"to":638}} {"id":100012065,"name":"removeMaxAttachLimit","signature":"func removeMaxAttachLimit(driverName string) nodeUpdateFunc","file":"pkg/volume/csi/nodeinfomanager/nodeinfomanager.go","code":"func removeMaxAttachLimit(driverName string) nodeUpdateFunc {\n\treturn func(node *v1.Node) (*v1.Node, bool, error) {\n\t\tlimitKey := v1.ResourceName(util.GetCSIAttachLimitKey(driverName))\n\n\t\tcapacityExists := false\n\t\tif node.Status.Capacity != nil {\n\t\t\t_, capacityExists = node.Status.Capacity[limitKey]\n\t\t}\n\n\t\tallocatableExists := false\n\t\tif node.Status.Allocatable != nil {\n\t\t\t_, allocatableExists = node.Status.Allocatable[limitKey]\n\t\t}\n\n\t\tif !capacityExists \u0026\u0026 !allocatableExists {\n\t\t\treturn node, false, nil\n\t\t}\n\n\t\tdelete(node.Status.Capacity, limitKey)\n\t\tif len(node.Status.Capacity) == 0 {\n\t\t\tnode.Status.Capacity = nil\n\t\t}\n\n\t\tdelete(node.Status.Allocatable, limitKey)\n\t\tif len(node.Status.Allocatable) == 0 {\n\t\t\tnode.Status.Allocatable = nil\n\t\t}\n\n\t\treturn node, true, nil\n\t}\n}","line":{"from":640,"to":670}} {"id":100012066,"name":"NewPluginManager","signature":"func NewPluginManager(m PluginNameMapper, featureGate featuregate.FeatureGate) PluginManager","file":"pkg/volume/csimigration/plugin_manager.go","code":"// NewPluginManager returns a new PluginManager instance\nfunc NewPluginManager(m PluginNameMapper, featureGate featuregate.FeatureGate) PluginManager {\n\treturn PluginManager{\n\t\tPluginNameMapper: m,\n\t\tfeatureGate: featureGate,\n\t}\n}","line":{"from":43,"to":49}} {"id":100012067,"name":"IsMigrationCompleteForPlugin","signature":"func (pm PluginManager) IsMigrationCompleteForPlugin(pluginName string) bool","file":"pkg/volume/csimigration/plugin_manager.go","code":"// IsMigrationCompleteForPlugin indicates whether CSI migration has been completed\n// for a particular storage plugin. A complete migration will need to:\n// 1. Enable CSIMigrationXX for the plugin\n// 2. Unregister the in-tree plugin by setting the InTreePluginXXUnregister feature gate\nfunc (pm PluginManager) IsMigrationCompleteForPlugin(pluginName string) bool {\n\t// CSIMigration feature and plugin specific InTreePluginUnregister feature flags should\n\t// be enabled for plugin specific migration completion to be take effect\n\tif !pm.IsMigrationEnabledForPlugin(pluginName) {\n\t\treturn false\n\t}\n\n\tswitch pluginName {\n\tcase csilibplugins.AWSEBSInTreePluginName:\n\t\treturn pm.featureGate.Enabled(features.InTreePluginAWSUnregister)\n\tcase csilibplugins.GCEPDInTreePluginName:\n\t\treturn pm.featureGate.Enabled(features.InTreePluginGCEUnregister)\n\tcase csilibplugins.AzureFileInTreePluginName:\n\t\treturn pm.featureGate.Enabled(features.InTreePluginAzureFileUnregister)\n\tcase csilibplugins.AzureDiskInTreePluginName:\n\t\treturn pm.featureGate.Enabled(features.InTreePluginAzureDiskUnregister)\n\tcase csilibplugins.CinderInTreePluginName:\n\t\treturn pm.featureGate.Enabled(features.InTreePluginOpenStackUnregister)\n\tcase csilibplugins.VSphereInTreePluginName:\n\t\treturn pm.featureGate.Enabled(features.InTreePluginvSphereUnregister)\n\tcase csilibplugins.PortworxVolumePluginName:\n\t\treturn pm.featureGate.Enabled(features.InTreePluginPortworxUnregister)\n\tcase csilibplugins.RBDVolumePluginName:\n\t\treturn pm.featureGate.Enabled(features.InTreePluginRBDUnregister)\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":51,"to":82}} {"id":100012068,"name":"IsMigrationEnabledForPlugin","signature":"func (pm PluginManager) IsMigrationEnabledForPlugin(pluginName string) bool","file":"pkg/volume/csimigration/plugin_manager.go","code":"// IsMigrationEnabledForPlugin indicates whether CSI migration has been enabled\n// for a particular storage plugin\nfunc (pm PluginManager) IsMigrationEnabledForPlugin(pluginName string) bool {\n\t// CSIMigration feature should be enabled along with the plugin-specific one\n\t// CSIMigration has been GA. It will be enabled by default.\n\n\tswitch pluginName {\n\tcase csilibplugins.AWSEBSInTreePluginName:\n\t\treturn true\n\tcase csilibplugins.GCEPDInTreePluginName:\n\t\treturn pm.featureGate.Enabled(features.CSIMigrationGCE)\n\tcase csilibplugins.AzureFileInTreePluginName:\n\t\treturn pm.featureGate.Enabled(features.CSIMigrationAzureFile)\n\tcase csilibplugins.AzureDiskInTreePluginName:\n\t\treturn true\n\tcase csilibplugins.CinderInTreePluginName:\n\t\treturn true\n\tcase csilibplugins.VSphereInTreePluginName:\n\t\treturn pm.featureGate.Enabled(features.CSIMigrationvSphere)\n\tcase csilibplugins.PortworxVolumePluginName:\n\t\treturn pm.featureGate.Enabled(features.CSIMigrationPortworx)\n\tcase csilibplugins.RBDVolumePluginName:\n\t\treturn pm.featureGate.Enabled(features.CSIMigrationRBD)\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":84,"to":110}} {"id":100012069,"name":"IsMigratable","signature":"func (pm PluginManager) IsMigratable(spec *volume.Spec) (bool, error)","file":"pkg/volume/csimigration/plugin_manager.go","code":"// IsMigratable indicates whether CSI migration has been enabled for a volume\n// plugin that the spec refers to\nfunc (pm PluginManager) IsMigratable(spec *volume.Spec) (bool, error) {\n\tif spec == nil {\n\t\treturn false, fmt.Errorf(\"could not find if plugin is migratable because volume spec is nil\")\n\t}\n\n\tpluginName, _ := pm.GetInTreePluginNameFromSpec(spec.PersistentVolume, spec.Volume)\n\tif pluginName == \"\" {\n\t\treturn false, nil\n\t}\n\t// found an in-tree plugin that supports the spec\n\treturn pm.IsMigrationEnabledForPlugin(pluginName), nil\n}","line":{"from":112,"to":125}} {"id":100012070,"name":"TranslateInTreeSpecToCSI","signature":"func TranslateInTreeSpecToCSI(spec *volume.Spec, podNamespace string, translator InTreeToCSITranslator) (*volume.Spec, error)","file":"pkg/volume/csimigration/plugin_manager.go","code":"// TranslateInTreeSpecToCSI translates a volume spec (either PV or inline volume)\n// supported by an in-tree plugin to CSI\nfunc TranslateInTreeSpecToCSI(spec *volume.Spec, podNamespace string, translator InTreeToCSITranslator) (*volume.Spec, error) {\n\tvar csiPV *v1.PersistentVolume\n\tvar err error\n\tinlineVolume := false\n\tif spec.PersistentVolume != nil {\n\t\tcsiPV, err = translator.TranslateInTreePVToCSI(spec.PersistentVolume)\n\t} else if spec.Volume != nil {\n\t\tcsiPV, err = translator.TranslateInTreeInlineVolumeToCSI(spec.Volume, podNamespace)\n\t\tinlineVolume = true\n\t} else {\n\t\terr = errors.New(\"not a valid volume spec\")\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to translate in-tree pv to CSI: %v\", err)\n\t}\n\treturn \u0026volume.Spec{\n\t\tMigrated: true,\n\t\tPersistentVolume: csiPV,\n\t\tReadOnly: spec.ReadOnly,\n\t\tInlineVolumeSpecForCSIMigration: inlineVolume,\n\t}, nil\n}","line":{"from":134,"to":157}} {"id":100012071,"name":"CheckMigrationFeatureFlags","signature":"func CheckMigrationFeatureFlags(f featuregate.FeatureGate, pluginMigration,","file":"pkg/volume/csimigration/plugin_manager.go","code":"// CheckMigrationFeatureFlags checks the configuration of feature flags related\n// to CSI Migration is valid. It will return whether the migration is complete\n// by looking up the pluginUnregister flag\nfunc CheckMigrationFeatureFlags(f featuregate.FeatureGate, pluginMigration,\n\tpluginUnregister featuregate.Feature) (migrationComplete bool, err error) {\n\t// This is for in-tree plugin that get migration finished\n\tif f.Enabled(pluginMigration) \u0026\u0026 f.Enabled(pluginUnregister) {\n\t\treturn true, nil\n\t}\n\treturn false, nil\n}","line":{"from":159,"to":169}} {"id":100012072,"name":"ProbeVolumePlugins","signature":"func ProbeVolumePlugins() []volume.VolumePlugin","file":"pkg/volume/downwardapi/downwardapi.go","code":"// ProbeVolumePlugins is the entry point for plugin detection in a package.\nfunc ProbeVolumePlugins() []volume.VolumePlugin {\n\treturn []volume.VolumePlugin{\u0026downwardAPIPlugin{}}\n}","line":{"from":34,"to":37}} {"id":100012073,"name":"getPath","signature":"func getPath(uid types.UID, volName string, host volume.VolumeHost) string","file":"pkg/volume/downwardapi/downwardapi.go","code":"func getPath(uid types.UID, volName string, host volume.VolumeHost) string {\n\treturn host.GetPodVolumeDir(uid, utilstrings.EscapeQualifiedName(downwardAPIPluginName), volName)\n}","line":{"from":50,"to":52}} {"id":100012074,"name":"wrappedVolumeSpec","signature":"func wrappedVolumeSpec() volume.Spec","file":"pkg/volume/downwardapi/downwardapi.go","code":"func wrappedVolumeSpec() volume.Spec {\n\treturn volume.Spec{\n\t\tVolume: \u0026v1.Volume{VolumeSource: v1.VolumeSource{EmptyDir: \u0026v1.EmptyDirVolumeSource{Medium: v1.StorageMediumMemory}}},\n\t}\n}","line":{"from":54,"to":58}} {"id":100012075,"name":"Init","signature":"func (plugin *downwardAPIPlugin) Init(host volume.VolumeHost) error","file":"pkg/volume/downwardapi/downwardapi.go","code":"func (plugin *downwardAPIPlugin) Init(host volume.VolumeHost) error {\n\tplugin.host = host\n\treturn nil\n}","line":{"from":60,"to":63}} {"id":100012076,"name":"GetPluginName","signature":"func (plugin *downwardAPIPlugin) GetPluginName() string","file":"pkg/volume/downwardapi/downwardapi.go","code":"func (plugin *downwardAPIPlugin) GetPluginName() string {\n\treturn downwardAPIPluginName\n}","line":{"from":65,"to":67}} {"id":100012077,"name":"GetVolumeName","signature":"func (plugin *downwardAPIPlugin) GetVolumeName(spec *volume.Spec) (string, error)","file":"pkg/volume/downwardapi/downwardapi.go","code":"func (plugin *downwardAPIPlugin) GetVolumeName(spec *volume.Spec) (string, error) {\n\tvolumeSource, _ := getVolumeSource(spec)\n\tif volumeSource == nil {\n\t\treturn \"\", fmt.Errorf(\"Spec does not reference a DownwardAPI volume type\")\n\t}\n\n\t// Return user defined volume name, since this is an ephemeral volume type\n\treturn spec.Name(), nil\n}","line":{"from":69,"to":77}} {"id":100012078,"name":"CanSupport","signature":"func (plugin *downwardAPIPlugin) CanSupport(spec *volume.Spec) bool","file":"pkg/volume/downwardapi/downwardapi.go","code":"func (plugin *downwardAPIPlugin) CanSupport(spec *volume.Spec) bool {\n\treturn spec.Volume != nil \u0026\u0026 spec.Volume.DownwardAPI != nil\n}","line":{"from":79,"to":81}} {"id":100012079,"name":"RequiresRemount","signature":"func (plugin *downwardAPIPlugin) RequiresRemount(spec *volume.Spec) bool","file":"pkg/volume/downwardapi/downwardapi.go","code":"func (plugin *downwardAPIPlugin) RequiresRemount(spec *volume.Spec) bool {\n\treturn true\n}","line":{"from":83,"to":85}} {"id":100012080,"name":"SupportsMountOption","signature":"func (plugin *downwardAPIPlugin) SupportsMountOption() bool","file":"pkg/volume/downwardapi/downwardapi.go","code":"func (plugin *downwardAPIPlugin) SupportsMountOption() bool {\n\treturn false\n}","line":{"from":87,"to":89}} {"id":100012081,"name":"SupportsBulkVolumeVerification","signature":"func (plugin *downwardAPIPlugin) SupportsBulkVolumeVerification() bool","file":"pkg/volume/downwardapi/downwardapi.go","code":"func (plugin *downwardAPIPlugin) SupportsBulkVolumeVerification() bool {\n\treturn false\n}","line":{"from":91,"to":93}} {"id":100012082,"name":"SupportsSELinuxContextMount","signature":"func (plugin *downwardAPIPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/downwardapi/downwardapi.go","code":"func (plugin *downwardAPIPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error) {\n\treturn false, nil\n}","line":{"from":95,"to":97}} {"id":100012083,"name":"NewMounter","signature":"func (plugin *downwardAPIPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error)","file":"pkg/volume/downwardapi/downwardapi.go","code":"func (plugin *downwardAPIPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error) {\n\tv := \u0026downwardAPIVolume{\n\t\tvolName: spec.Name(),\n\t\titems: spec.Volume.DownwardAPI.Items,\n\t\tpod: pod,\n\t\tpodUID: pod.UID,\n\t\tplugin: plugin,\n\t\tMetricsProvider: volume.NewCachedMetrics(volume.NewMetricsDu(getPath(pod.UID, spec.Name(), plugin.host))),\n\t}\n\treturn \u0026downwardAPIVolumeMounter{\n\t\tdownwardAPIVolume: v,\n\t\tsource: *spec.Volume.DownwardAPI,\n\t\topts: \u0026opts,\n\t}, nil\n}","line":{"from":99,"to":113}} {"id":100012084,"name":"NewUnmounter","signature":"func (plugin *downwardAPIPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error)","file":"pkg/volume/downwardapi/downwardapi.go","code":"func (plugin *downwardAPIPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error) {\n\treturn \u0026downwardAPIVolumeUnmounter{\n\t\t\u0026downwardAPIVolume{\n\t\t\tvolName: volName,\n\t\t\tpodUID: podUID,\n\t\t\tplugin: plugin,\n\t\t\tMetricsProvider: volume.NewCachedMetrics(volume.NewMetricsDu(getPath(podUID, volName, plugin.host))),\n\t\t},\n\t}, nil\n}","line":{"from":115,"to":124}} {"id":100012085,"name":"ConstructVolumeSpec","signature":"func (plugin *downwardAPIPlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error)","file":"pkg/volume/downwardapi/downwardapi.go","code":"func (plugin *downwardAPIPlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error) {\n\tdownwardAPIVolume := \u0026v1.Volume{\n\t\tName: volumeName,\n\t\tVolumeSource: v1.VolumeSource{\n\t\t\tDownwardAPI: \u0026v1.DownwardAPIVolumeSource{},\n\t\t},\n\t}\n\treturn volume.ReconstructedVolume{\n\t\tSpec: volume.NewSpecFromVolume(downwardAPIVolume),\n\t}, nil\n}","line":{"from":126,"to":136}} {"id":100012086,"name":"GetAttributes","signature":"func (d *downwardAPIVolume) GetAttributes() volume.Attributes","file":"pkg/volume/downwardapi/downwardapi.go","code":"// downward API volumes are always ReadOnlyManaged\nfunc (d *downwardAPIVolume) GetAttributes() volume.Attributes {\n\treturn volume.Attributes{\n\t\tReadOnly: true,\n\t\tManaged: true,\n\t\tSELinuxRelabel: true,\n\t}\n}","line":{"from":159,"to":166}} {"id":100012087,"name":"SetUp","signature":"func (b *downwardAPIVolumeMounter) SetUp(mounterArgs volume.MounterArgs) error","file":"pkg/volume/downwardapi/downwardapi.go","code":"// SetUp puts in place the volume plugin.\n// This function is not idempotent by design. We want the data to be refreshed periodically.\n// The internal sync interval of kubelet will drive the refresh of data.\n// TODO: Add volume specific ticker and refresh loop\nfunc (b *downwardAPIVolumeMounter) SetUp(mounterArgs volume.MounterArgs) error {\n\treturn b.SetUpAt(b.GetPath(), mounterArgs)\n}","line":{"from":168,"to":174}} {"id":100012088,"name":"SetUpAt","signature":"func (b *downwardAPIVolumeMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error","file":"pkg/volume/downwardapi/downwardapi.go","code":"func (b *downwardAPIVolumeMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {\n\tklog.V(3).Infof(\"Setting up a downwardAPI volume %v for pod %v/%v at %v\", b.volName, b.pod.Namespace, b.pod.Name, dir)\n\t// Wrap EmptyDir. Here we rely on the idempotency of the wrapped plugin to avoid repeatedly mounting\n\twrapped, err := b.plugin.host.NewWrapperMounter(b.volName, wrappedVolumeSpec(), b.pod, *b.opts)\n\tif err != nil {\n\t\tklog.Errorf(\"Couldn't setup downwardAPI volume %v for pod %v/%v: %s\", b.volName, b.pod.Namespace, b.pod.Name, err.Error())\n\t\treturn err\n\t}\n\n\tdata, err := CollectData(b.source.Items, b.pod, b.plugin.host, b.source.DefaultMode)\n\tif err != nil {\n\t\tklog.Errorf(\"Error preparing data for downwardAPI volume %v for pod %v/%v: %s\", b.volName, b.pod.Namespace, b.pod.Name, err.Error())\n\t\treturn err\n\t}\n\n\tsetupSuccess := false\n\tif err := wrapped.SetUpAt(dir, mounterArgs); err != nil {\n\t\tklog.Errorf(\"Unable to setup downwardAPI volume %v for pod %v/%v: %s\", b.volName, b.pod.Namespace, b.pod.Name, err.Error())\n\t\treturn err\n\t}\n\n\tif err := volumeutil.MakeNestedMountpoints(b.volName, dir, *b.pod); err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\t// Clean up directories if setup fails\n\t\tif !setupSuccess {\n\t\t\tunmounter, unmountCreateErr := b.plugin.NewUnmounter(b.volName, b.podUID)\n\t\t\tif unmountCreateErr != nil {\n\t\t\t\tklog.Errorf(\"error cleaning up mount %s after failure. Create unmounter failed with %v\", b.volName, unmountCreateErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\ttearDownErr := unmounter.TearDown()\n\t\t\tif tearDownErr != nil {\n\t\t\t\tklog.Errorf(\"error tearing down volume %s with : %v\", b.volName, tearDownErr)\n\t\t\t}\n\t\t}\n\t}()\n\n\twriterContext := fmt.Sprintf(\"pod %v/%v volume %v\", b.pod.Namespace, b.pod.Name, b.volName)\n\twriter, err := volumeutil.NewAtomicWriter(dir, writerContext)\n\tif err != nil {\n\t\tklog.Errorf(\"Error creating atomic writer: %v\", err)\n\t\treturn err\n\t}\n\n\tsetPerms := func(_ string) error {\n\t\t// This may be the first time writing and new files get created outside the timestamp subdirectory:\n\t\t// change the permissions on the whole volume and not only in the timestamp directory.\n\t\treturn volume.SetVolumeOwnership(b, dir, mounterArgs.FsGroup, nil /*fsGroupChangePolicy*/, volumeutil.FSGroupCompleteHook(b.plugin, nil))\n\t}\n\terr = writer.Write(data, setPerms)\n\tif err != nil {\n\t\tklog.Errorf(\"Error writing payload to dir: %v\", err)\n\t\treturn err\n\t}\n\n\tsetupSuccess = true\n\treturn nil\n}","line":{"from":176,"to":236}} {"id":100012089,"name":"CollectData","signature":"func CollectData(items []v1.DownwardAPIVolumeFile, pod *v1.Pod, host volume.VolumeHost, defaultMode *int32) (map[string]volumeutil.FileProjection, error)","file":"pkg/volume/downwardapi/downwardapi.go","code":"// CollectData collects requested downwardAPI in data map.\n// Map's key is the requested name of file to dump\n// Map's value is the (sorted) content of the field to be dumped in the file.\n//\n// Note: this function is exported so that it can be called from the projection volume driver\nfunc CollectData(items []v1.DownwardAPIVolumeFile, pod *v1.Pod, host volume.VolumeHost, defaultMode *int32) (map[string]volumeutil.FileProjection, error) {\n\tif defaultMode == nil {\n\t\treturn nil, fmt.Errorf(\"no defaultMode used, not even the default value for it\")\n\t}\n\n\terrlist := []error{}\n\tdata := make(map[string]volumeutil.FileProjection)\n\tfor _, fileInfo := range items {\n\t\tvar fileProjection volumeutil.FileProjection\n\t\tfPath := filepath.Clean(fileInfo.Path)\n\t\tif fileInfo.Mode != nil {\n\t\t\tfileProjection.Mode = *fileInfo.Mode\n\t\t} else {\n\t\t\tfileProjection.Mode = *defaultMode\n\t\t}\n\t\tif fileInfo.FieldRef != nil {\n\t\t\t// TODO: unify with Kubelet.podFieldSelectorRuntimeValue\n\t\t\tif values, err := fieldpath.ExtractFieldPathAsString(pod, fileInfo.FieldRef.FieldPath); err != nil {\n\t\t\t\tklog.Errorf(\"Unable to extract field %s: %s\", fileInfo.FieldRef.FieldPath, err.Error())\n\t\t\t\terrlist = append(errlist, err)\n\t\t\t} else {\n\t\t\t\tfileProjection.Data = []byte(values)\n\t\t\t}\n\t\t} else if fileInfo.ResourceFieldRef != nil {\n\t\t\tcontainerName := fileInfo.ResourceFieldRef.ContainerName\n\t\t\tnodeAllocatable, err := host.GetNodeAllocatable()\n\t\t\tif err != nil {\n\t\t\t\terrlist = append(errlist, err)\n\t\t\t} else if values, err := resource.ExtractResourceValueByContainerNameAndNodeAllocatable(fileInfo.ResourceFieldRef, pod, containerName, nodeAllocatable); err != nil {\n\t\t\t\tklog.Errorf(\"Unable to extract field %s: %s\", fileInfo.ResourceFieldRef.Resource, err.Error())\n\t\t\t\terrlist = append(errlist, err)\n\t\t\t} else {\n\t\t\t\tfileProjection.Data = []byte(values)\n\t\t\t}\n\t\t}\n\n\t\tdata[fPath] = fileProjection\n\t}\n\treturn data, utilerrors.NewAggregate(errlist)\n}","line":{"from":238,"to":282}} {"id":100012090,"name":"GetPath","signature":"func (d *downwardAPIVolume) GetPath() string","file":"pkg/volume/downwardapi/downwardapi.go","code":"func (d *downwardAPIVolume) GetPath() string {\n\treturn d.plugin.host.GetPodVolumeDir(d.podUID, utilstrings.EscapeQualifiedName(downwardAPIPluginName), d.volName)\n}","line":{"from":284,"to":286}} {"id":100012091,"name":"TearDown","signature":"func (c *downwardAPIVolumeUnmounter) TearDown() error","file":"pkg/volume/downwardapi/downwardapi.go","code":"func (c *downwardAPIVolumeUnmounter) TearDown() error {\n\treturn c.TearDownAt(c.GetPath())\n}","line":{"from":296,"to":298}} {"id":100012092,"name":"TearDownAt","signature":"func (c *downwardAPIVolumeUnmounter) TearDownAt(dir string) error","file":"pkg/volume/downwardapi/downwardapi.go","code":"func (c *downwardAPIVolumeUnmounter) TearDownAt(dir string) error {\n\treturn volumeutil.UnmountViaEmptyDir(dir, c.plugin.host, c.volName, wrappedVolumeSpec(), c.podUID)\n}","line":{"from":300,"to":302}} {"id":100012093,"name":"getVolumeSource","signature":"func getVolumeSource(spec *volume.Spec) (*v1.DownwardAPIVolumeSource, bool)","file":"pkg/volume/downwardapi/downwardapi.go","code":"func getVolumeSource(spec *volume.Spec) (*v1.DownwardAPIVolumeSource, bool) {\n\tvar readOnly bool\n\tvar volumeSource *v1.DownwardAPIVolumeSource\n\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.DownwardAPI != nil {\n\t\tvolumeSource = spec.Volume.DownwardAPI\n\t\treadOnly = spec.ReadOnly\n\t}\n\n\treturn volumeSource, readOnly\n}","line":{"from":304,"to":314}} {"id":100012094,"name":"ProbeVolumePlugins","signature":"func ProbeVolumePlugins() []volume.VolumePlugin","file":"pkg/volume/emptydir/empty_dir.go","code":"// ProbeVolumePlugins is the primary entrypoint for volume plugins.\nfunc ProbeVolumePlugins() []volume.VolumePlugin {\n\treturn []volume.VolumePlugin{\n\t\t\u0026emptyDirPlugin{nil},\n\t}\n}","line":{"from":48,"to":53}} {"id":100012095,"name":"getPath","signature":"func getPath(uid types.UID, volName string, host volume.VolumeHost) string","file":"pkg/volume/emptydir/empty_dir.go","code":"func getPath(uid types.UID, volName string, host volume.VolumeHost) string {\n\treturn host.GetPodVolumeDir(uid, utilstrings.EscapeQualifiedName(emptyDirPluginName), volName)\n}","line":{"from":66,"to":68}} {"id":100012096,"name":"Init","signature":"func (plugin *emptyDirPlugin) Init(host volume.VolumeHost) error","file":"pkg/volume/emptydir/empty_dir.go","code":"func (plugin *emptyDirPlugin) Init(host volume.VolumeHost) error {\n\tplugin.host = host\n\n\treturn nil\n}","line":{"from":70,"to":74}} {"id":100012097,"name":"GetPluginName","signature":"func (plugin *emptyDirPlugin) GetPluginName() string","file":"pkg/volume/emptydir/empty_dir.go","code":"func (plugin *emptyDirPlugin) GetPluginName() string {\n\treturn emptyDirPluginName\n}","line":{"from":76,"to":78}} {"id":100012098,"name":"GetVolumeName","signature":"func (plugin *emptyDirPlugin) GetVolumeName(spec *volume.Spec) (string, error)","file":"pkg/volume/emptydir/empty_dir.go","code":"func (plugin *emptyDirPlugin) GetVolumeName(spec *volume.Spec) (string, error) {\n\tvolumeSource, _ := getVolumeSource(spec)\n\tif volumeSource == nil {\n\t\treturn \"\", fmt.Errorf(\"Spec does not reference an EmptyDir volume type\")\n\t}\n\n\t// Return user defined volume name, since this is an ephemeral volume type\n\treturn spec.Name(), nil\n}","line":{"from":80,"to":88}} {"id":100012099,"name":"CanSupport","signature":"func (plugin *emptyDirPlugin) CanSupport(spec *volume.Spec) bool","file":"pkg/volume/emptydir/empty_dir.go","code":"func (plugin *emptyDirPlugin) CanSupport(spec *volume.Spec) bool {\n\treturn spec.Volume != nil \u0026\u0026 spec.Volume.EmptyDir != nil\n}","line":{"from":90,"to":92}} {"id":100012100,"name":"RequiresRemount","signature":"func (plugin *emptyDirPlugin) RequiresRemount(spec *volume.Spec) bool","file":"pkg/volume/emptydir/empty_dir.go","code":"func (plugin *emptyDirPlugin) RequiresRemount(spec *volume.Spec) bool {\n\treturn false\n}","line":{"from":94,"to":96}} {"id":100012101,"name":"SupportsMountOption","signature":"func (plugin *emptyDirPlugin) SupportsMountOption() bool","file":"pkg/volume/emptydir/empty_dir.go","code":"func (plugin *emptyDirPlugin) SupportsMountOption() bool {\n\treturn false\n}","line":{"from":98,"to":100}} {"id":100012102,"name":"SupportsBulkVolumeVerification","signature":"func (plugin *emptyDirPlugin) SupportsBulkVolumeVerification() bool","file":"pkg/volume/emptydir/empty_dir.go","code":"func (plugin *emptyDirPlugin) SupportsBulkVolumeVerification() bool {\n\treturn false\n}","line":{"from":102,"to":104}} {"id":100012103,"name":"SupportsSELinuxContextMount","signature":"func (plugin *emptyDirPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/emptydir/empty_dir.go","code":"func (plugin *emptyDirPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error) {\n\treturn false, nil\n}","line":{"from":106,"to":108}} {"id":100012104,"name":"NewMounter","signature":"func (plugin *emptyDirPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error)","file":"pkg/volume/emptydir/empty_dir.go","code":"func (plugin *emptyDirPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error) {\n\treturn plugin.newMounterInternal(spec, pod, plugin.host.GetMounter(plugin.GetPluginName()), \u0026realMountDetector{plugin.host.GetMounter(plugin.GetPluginName())}, opts)\n}","line":{"from":110,"to":112}} {"id":100012105,"name":"calculateEmptyDirMemorySize","signature":"func calculateEmptyDirMemorySize(nodeAllocatableMemory *resource.Quantity, spec *volume.Spec, pod *v1.Pod) *resource.Quantity","file":"pkg/volume/emptydir/empty_dir.go","code":"func calculateEmptyDirMemorySize(nodeAllocatableMemory *resource.Quantity, spec *volume.Spec, pod *v1.Pod) *resource.Quantity {\n\t// if feature is disabled, continue the default behavior of linux host default\n\tsizeLimit := \u0026resource.Quantity{}\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.SizeMemoryBackedVolumes) {\n\t\treturn sizeLimit\n\t}\n\n\t// size limit defaults to node allocatable (pods can't consume more memory than all pods)\n\tsizeLimit = nodeAllocatableMemory\n\tzero := resource.MustParse(\"0\")\n\n\t// determine pod resource allocation\n\t// we use the same function for pod cgroup assignment to maintain consistent behavior\n\t// NOTE: this could be nil on systems that do not support pod memory containment (i.e. windows)\n\tpodResourceConfig := cm.ResourceConfigForPod(pod, false, uint64(100000), false)\n\tif podResourceConfig != nil \u0026\u0026 podResourceConfig.Memory != nil {\n\t\tpodMemoryLimit := resource.NewQuantity(*(podResourceConfig.Memory), resource.BinarySI)\n\t\t// ensure 0 \u003c value \u003c size\n\t\tif podMemoryLimit.Cmp(zero) \u003e 0 \u0026\u0026 podMemoryLimit.Cmp(*sizeLimit) \u003c 1 {\n\t\t\tsizeLimit = podMemoryLimit\n\t\t}\n\t}\n\n\t// volume local size is used if and only if less than what pod could consume\n\tif spec.Volume.EmptyDir.SizeLimit != nil {\n\t\tvolumeSizeLimit := spec.Volume.EmptyDir.SizeLimit\n\t\t// ensure 0 \u003c value \u003c size\n\t\tif volumeSizeLimit.Cmp(zero) \u003e 0 \u0026\u0026 volumeSizeLimit.Cmp(*sizeLimit) \u003c 1 {\n\t\t\tsizeLimit = volumeSizeLimit\n\t\t}\n\t}\n\treturn sizeLimit\n}","line":{"from":114,"to":146}} {"id":100012106,"name":"newMounterInternal","signature":"func (plugin *emptyDirPlugin) newMounterInternal(spec *volume.Spec, pod *v1.Pod, mounter mount.Interface, mountDetector mountDetector, opts volume.VolumeOptions) (volume.Mounter, error)","file":"pkg/volume/emptydir/empty_dir.go","code":"func (plugin *emptyDirPlugin) newMounterInternal(spec *volume.Spec, pod *v1.Pod, mounter mount.Interface, mountDetector mountDetector, opts volume.VolumeOptions) (volume.Mounter, error) {\n\tmedium := v1.StorageMediumDefault\n\tsizeLimit := \u0026resource.Quantity{}\n\tif spec.Volume.EmptyDir != nil { // Support a non-specified source as EmptyDir.\n\t\tmedium = spec.Volume.EmptyDir.Medium\n\t\tif medium == v1.StorageMediumMemory {\n\t\t\tnodeAllocatable, err := plugin.host.GetNodeAllocatable()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tsizeLimit = calculateEmptyDirMemorySize(nodeAllocatable.Memory(), spec, pod)\n\t\t}\n\t}\n\treturn \u0026emptyDir{\n\t\tpod: pod,\n\t\tvolName: spec.Name(),\n\t\tmedium: medium,\n\t\tsizeLimit: sizeLimit,\n\t\tmounter: mounter,\n\t\tmountDetector: mountDetector,\n\t\tplugin: plugin,\n\t\tMetricsProvider: volume.NewMetricsDu(getPath(pod.UID, spec.Name(), plugin.host)),\n\t}, nil\n}","line":{"from":148,"to":171}} {"id":100012107,"name":"NewUnmounter","signature":"func (plugin *emptyDirPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error)","file":"pkg/volume/emptydir/empty_dir.go","code":"func (plugin *emptyDirPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error) {\n\t// Inject real implementations here, test through the internal function.\n\treturn plugin.newUnmounterInternal(volName, podUID, plugin.host.GetMounter(plugin.GetPluginName()), \u0026realMountDetector{plugin.host.GetMounter(plugin.GetPluginName())})\n}","line":{"from":173,"to":176}} {"id":100012108,"name":"newUnmounterInternal","signature":"func (plugin *emptyDirPlugin) newUnmounterInternal(volName string, podUID types.UID, mounter mount.Interface, mountDetector mountDetector) (volume.Unmounter, error)","file":"pkg/volume/emptydir/empty_dir.go","code":"func (plugin *emptyDirPlugin) newUnmounterInternal(volName string, podUID types.UID, mounter mount.Interface, mountDetector mountDetector) (volume.Unmounter, error) {\n\ted := \u0026emptyDir{\n\t\tpod: \u0026v1.Pod{ObjectMeta: metav1.ObjectMeta{UID: podUID}},\n\t\tvolName: volName,\n\t\tmedium: v1.StorageMediumDefault, // might be changed later\n\t\tmounter: mounter,\n\t\tmountDetector: mountDetector,\n\t\tplugin: plugin,\n\t\tMetricsProvider: volume.NewMetricsDu(getPath(podUID, volName, plugin.host)),\n\t}\n\treturn ed, nil\n}","line":{"from":178,"to":189}} {"id":100012109,"name":"ConstructVolumeSpec","signature":"func (plugin *emptyDirPlugin) ConstructVolumeSpec(volName, mountPath string) (volume.ReconstructedVolume, error)","file":"pkg/volume/emptydir/empty_dir.go","code":"func (plugin *emptyDirPlugin) ConstructVolumeSpec(volName, mountPath string) (volume.ReconstructedVolume, error) {\n\temptyDirVolume := \u0026v1.Volume{\n\t\tName: volName,\n\t\tVolumeSource: v1.VolumeSource{\n\t\t\tEmptyDir: \u0026v1.EmptyDirVolumeSource{},\n\t\t},\n\t}\n\treturn volume.ReconstructedVolume{\n\t\tSpec: volume.NewSpecFromVolume(emptyDirVolume),\n\t}, nil\n}","line":{"from":191,"to":201}} {"id":100012110,"name":"GetAttributes","signature":"func (ed *emptyDir) GetAttributes() volume.Attributes","file":"pkg/volume/emptydir/empty_dir.go","code":"func (ed *emptyDir) GetAttributes() volume.Attributes {\n\treturn volume.Attributes{\n\t\tReadOnly: false,\n\t\tManaged: true,\n\t\tSELinuxRelabel: true,\n\t}\n}","line":{"from":226,"to":232}} {"id":100012111,"name":"SetUp","signature":"func (ed *emptyDir) SetUp(mounterArgs volume.MounterArgs) error","file":"pkg/volume/emptydir/empty_dir.go","code":"// SetUp creates new directory.\nfunc (ed *emptyDir) SetUp(mounterArgs volume.MounterArgs) error {\n\treturn ed.SetUpAt(ed.GetPath(), mounterArgs)\n}","line":{"from":234,"to":237}} {"id":100012112,"name":"SetUpAt","signature":"func (ed *emptyDir) SetUpAt(dir string, mounterArgs volume.MounterArgs) error","file":"pkg/volume/emptydir/empty_dir.go","code":"// SetUpAt creates new directory.\nfunc (ed *emptyDir) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {\n\tnotMnt, err := ed.mounter.IsLikelyNotMountPoint(dir)\n\t// Getting an os.IsNotExist err from is a contingency; the directory\n\t// may not exist yet, in which case, setup should run.\n\tif err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\n\t// If the plugin readiness file is present for this volume, and the\n\t// storage medium is the default, then the volume is ready. If the\n\t// medium is memory, and a mountpoint is present, then the volume is\n\t// ready.\n\treadyDir := ed.getMetaDir()\n\tif volumeutil.IsReady(readyDir) {\n\t\tif ed.medium == v1.StorageMediumMemory \u0026\u0026 !notMnt {\n\t\t\treturn nil\n\t\t} else if ed.medium == v1.StorageMediumDefault {\n\t\t\t// Further check dir exists\n\t\t\tif _, err := os.Stat(dir); err == nil {\n\t\t\t\tklog.V(6).InfoS(\"Dir exists, so check and assign quota if the underlying medium supports quotas\", \"dir\", dir)\n\t\t\t\terr = ed.assignQuota(dir, mounterArgs.DesiredSize)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// This situation should not happen unless user manually delete volume dir.\n\t\t\t// In this case, delete ready file and print a warning for it.\n\t\t\tklog.Warningf(\"volume ready file dir %s exist, but volume dir %s does not. Remove ready dir\", readyDir, dir)\n\t\t\tif err := os.RemoveAll(readyDir); err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\t\t\tklog.Warningf(\"failed to remove ready dir [%s]: %v\", readyDir, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch {\n\tcase ed.medium == v1.StorageMediumDefault:\n\t\terr = ed.setupDir(dir)\n\tcase ed.medium == v1.StorageMediumMemory:\n\t\terr = ed.setupTmpfs(dir)\n\tcase v1helper.IsHugePageMedium(ed.medium):\n\t\terr = ed.setupHugepages(dir)\n\tdefault:\n\t\terr = fmt.Errorf(\"unknown storage medium %q\", ed.medium)\n\t}\n\n\tvolume.SetVolumeOwnership(ed, dir, mounterArgs.FsGroup, nil /*fsGroupChangePolicy*/, volumeutil.FSGroupCompleteHook(ed.plugin, nil))\n\n\t// If setting up the quota fails, just log a message but don't actually error out.\n\t// We'll use the old du mechanism in this case, at least until we support\n\t// enforcement.\n\tif err == nil {\n\t\tvolumeutil.SetReady(ed.getMetaDir())\n\t\terr = ed.assignQuota(dir, mounterArgs.DesiredSize)\n\t}\n\treturn err\n}","line":{"from":239,"to":293}} {"id":100012113,"name":"assignQuota","signature":"func (ed *emptyDir) assignQuota(dir string, mounterSize *resource.Quantity) error","file":"pkg/volume/emptydir/empty_dir.go","code":"// assignQuota checks if the underlying medium supports quotas and if so, sets\nfunc (ed *emptyDir) assignQuota(dir string, mounterSize *resource.Quantity) error {\n\tif mounterSize != nil {\n\t\t// Deliberately shadow the outer use of err as noted\n\t\t// above.\n\t\thasQuotas, err := fsquota.SupportsQuotas(ed.mounter, dir)\n\t\tif err != nil {\n\t\t\tklog.V(3).Infof(\"Unable to check for quota support on %s: %s\", dir, err.Error())\n\t\t} else if hasQuotas {\n\t\t\tklog.V(4).Infof(\"emptydir trying to assign quota %v on %s\", mounterSize, dir)\n\t\t\tif err := fsquota.AssignQuota(ed.mounter, dir, ed.pod.UID, mounterSize); err != nil {\n\t\t\t\tklog.V(3).Infof(\"Set quota on %s failed %s\", dir, err.Error())\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":295,"to":313}} {"id":100012114,"name":"setupTmpfs","signature":"func (ed *emptyDir) setupTmpfs(dir string) error","file":"pkg/volume/emptydir/empty_dir.go","code":"// setupTmpfs creates a tmpfs mount at the specified directory.\nfunc (ed *emptyDir) setupTmpfs(dir string) error {\n\tif ed.mounter == nil {\n\t\treturn fmt.Errorf(\"memory storage requested, but mounter is nil\")\n\t}\n\tif err := ed.setupDir(dir); err != nil {\n\t\treturn err\n\t}\n\t// Make SetUp idempotent.\n\tmedium, isMnt, _, err := ed.mountDetector.GetMountMedium(dir, ed.medium)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// If the directory is a mountpoint with medium memory, there is no\n\t// work to do since we are already in the desired state.\n\tif isMnt \u0026\u0026 medium == v1.StorageMediumMemory {\n\t\treturn nil\n\t}\n\n\tvar options []string\n\t// Linux system default is 50% of capacity.\n\tif ed.sizeLimit != nil \u0026\u0026 ed.sizeLimit.Value() \u003e 0 {\n\t\toptions = []string{fmt.Sprintf(\"size=%d\", ed.sizeLimit.Value())}\n\t}\n\n\tklog.V(3).Infof(\"pod %v: mounting tmpfs for volume %v\", ed.pod.UID, ed.volName)\n\treturn ed.mounter.MountSensitiveWithoutSystemd(\"tmpfs\", dir, \"tmpfs\", options, nil)\n}","line":{"from":315,"to":342}} {"id":100012115,"name":"setupHugepages","signature":"func (ed *emptyDir) setupHugepages(dir string) error","file":"pkg/volume/emptydir/empty_dir.go","code":"// setupHugepages creates a hugepage mount at the specified directory.\nfunc (ed *emptyDir) setupHugepages(dir string) error {\n\tif ed.mounter == nil {\n\t\treturn fmt.Errorf(\"memory storage requested, but mounter is nil\")\n\t}\n\tif err := ed.setupDir(dir); err != nil {\n\t\treturn err\n\t}\n\t// Make SetUp idempotent.\n\tmedium, isMnt, mountPageSize, err := ed.mountDetector.GetMountMedium(dir, ed.medium)\n\tklog.V(3).Infof(\"pod %v: setupHugepages: medium: %s, isMnt: %v, dir: %s, err: %v\", ed.pod.UID, medium, isMnt, dir, err)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// If the directory is a mountpoint with medium hugepages of the same page size,\n\t// there is no work to do since we are already in the desired state.\n\tif isMnt \u0026\u0026 v1helper.IsHugePageMedium(medium) {\n\t\t// Medium is: Hugepages\n\t\tif ed.medium == v1.StorageMediumHugePages {\n\t\t\treturn nil\n\t\t}\n\t\tif mountPageSize == nil {\n\t\t\treturn fmt.Errorf(\"pod %v: mounted dir %s pagesize is not determined\", ed.pod.UID, dir)\n\t\t}\n\t\t// Medium is: Hugepages-\u003csize\u003e\n\t\t// Mounted page size and medium size must be equal\n\t\tmediumSize, err := v1helper.HugePageSizeFromMedium(ed.medium)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif mountPageSize == nil || mediumSize.Cmp(*mountPageSize) != 0 {\n\t\t\treturn fmt.Errorf(\"pod %v: mounted dir %s pagesize '%s' and requested medium size '%s' differ\", ed.pod.UID, dir, mountPageSize.String(), mediumSize.String())\n\t\t}\n\t\treturn nil\n\t}\n\n\tpageSizeMountOption, err := getPageSizeMountOption(ed.medium, ed.pod)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tklog.V(3).Infof(\"pod %v: mounting hugepages for volume %v\", ed.pod.UID, ed.volName)\n\treturn ed.mounter.MountSensitiveWithoutSystemd(\"nodev\", dir, \"hugetlbfs\", []string{pageSizeMountOption}, nil)\n}","line":{"from":344,"to":387}} {"id":100012116,"name":"getPageSizeMountOption","signature":"func getPageSizeMountOption(medium v1.StorageMedium, pod *v1.Pod) (string, error)","file":"pkg/volume/emptydir/empty_dir.go","code":"// getPageSizeMountOption retrieves pageSize mount option from Pod's resources\n// and medium and validates pageSize options in all containers of given Pod.\nfunc getPageSizeMountOption(medium v1.StorageMedium, pod *v1.Pod) (string, error) {\n\tpageSizeFound := false\n\tpageSize := resource.Quantity{}\n\n\tvar mediumPageSize resource.Quantity\n\tif medium != v1.StorageMediumHugePages {\n\t\t// medium is: Hugepages-\u003csize\u003e\n\t\tvar err error\n\t\tmediumPageSize, err = v1helper.HugePageSizeFromMedium(medium)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\t// In some rare cases init containers can also consume Huge pages\n\tfor _, container := range append(pod.Spec.Containers, pod.Spec.InitContainers...) {\n\t\t// We can take request because limit and requests must match.\n\t\tfor requestName := range container.Resources.Requests {\n\t\t\tif !v1helper.IsHugePageResourceName(requestName) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcurrentPageSize, err := v1helper.HugePageSizeFromResourceName(requestName)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\tif medium == v1.StorageMediumHugePages { // medium is: Hugepages, size is not specified\n\t\t\t\t// PageSize for all volumes in a POD must be equal if medium is \"Hugepages\"\n\t\t\t\tif pageSizeFound \u0026\u0026 pageSize.Cmp(currentPageSize) != 0 {\n\t\t\t\t\treturn \"\", fmt.Errorf(\"medium: %s can't be used if container requests multiple huge page sizes\", medium)\n\t\t\t\t}\n\n\t\t\t\tpageSizeFound = true\n\t\t\t\tpageSize = currentPageSize\n\t\t\t} else { // medium is: Hugepages-\u003csize\u003e\n\t\t\t\tif currentPageSize.Cmp(mediumPageSize) == 0 {\n\t\t\t\t\tpageSizeFound = true\n\t\t\t\t\tpageSize = currentPageSize\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif !pageSizeFound {\n\t\treturn \"\", fmt.Errorf(\"medium %s: hugePages storage requested, but there is no resource request for huge pages\", medium)\n\t}\n\n\treturn fmt.Sprintf(\"%s=%s\", hugePagesPageSizeMountOption, pageSize.String()), nil\n\n}","line":{"from":389,"to":439}} {"id":100012117,"name":"setupDir","signature":"func (ed *emptyDir) setupDir(dir string) error","file":"pkg/volume/emptydir/empty_dir.go","code":"// setupDir creates the directory with the default permissions specified by the perm constant.\nfunc (ed *emptyDir) setupDir(dir string) error {\n\t// Create the directory if it doesn't already exist.\n\tif err := os.MkdirAll(dir, perm); err != nil {\n\t\treturn err\n\t}\n\n\t// stat the directory to read permission bits\n\tfileinfo, err := os.Lstat(dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif fileinfo.Mode().Perm() != perm.Perm() {\n\t\t// If the permissions on the created directory are wrong, the\n\t\t// kubelet is probably running with a umask set. In order to\n\t\t// avoid clearing the umask for the entire process or locking\n\t\t// the thread, clearing the umask, creating the dir, restoring\n\t\t// the umask, and unlocking the thread, we do a chmod to set\n\t\t// the specific bits we need.\n\t\terr := os.Chmod(dir, perm)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfileinfo, err = os.Lstat(dir)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif fileinfo.Mode().Perm() != perm.Perm() {\n\t\t\tklog.Errorf(\"Expected directory %q permissions to be: %s; got: %s\", dir, perm.Perm(), fileinfo.Mode().Perm())\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":441,"to":477}} {"id":100012118,"name":"GetPath","signature":"func (ed *emptyDir) GetPath() string","file":"pkg/volume/emptydir/empty_dir.go","code":"func (ed *emptyDir) GetPath() string {\n\treturn getPath(ed.pod.UID, ed.volName, ed.plugin.host)\n}","line":{"from":479,"to":481}} {"id":100012119,"name":"TearDown","signature":"func (ed *emptyDir) TearDown() error","file":"pkg/volume/emptydir/empty_dir.go","code":"// TearDown simply discards everything in the directory.\nfunc (ed *emptyDir) TearDown() error {\n\treturn ed.TearDownAt(ed.GetPath())\n}","line":{"from":483,"to":486}} {"id":100012120,"name":"TearDownAt","signature":"func (ed *emptyDir) TearDownAt(dir string) error","file":"pkg/volume/emptydir/empty_dir.go","code":"// TearDownAt simply discards everything in the directory.\nfunc (ed *emptyDir) TearDownAt(dir string) error {\n\t// First remove ready dir which created in SetUp func\n\treadyDir := ed.getMetaDir()\n\tif removeErr := os.RemoveAll(readyDir); removeErr != nil \u0026\u0026 !os.IsNotExist(removeErr) {\n\t\treturn fmt.Errorf(\"failed to remove ready dir [%s]: %v\", readyDir, removeErr)\n\t}\n\n\tif pathExists, pathErr := mount.PathExists(dir); pathErr != nil {\n\t\treturn fmt.Errorf(\"error checking if path exists: %w\", pathErr)\n\t} else if !pathExists {\n\t\tklog.Warningf(\"Warning: Unmount skipped because path does not exist: %v\", dir)\n\t\treturn nil\n\t}\n\n\t// Figure out the medium.\n\tmedium, isMnt, _, err := ed.mountDetector.GetMountMedium(dir, ed.medium)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif isMnt {\n\t\tif medium == v1.StorageMediumMemory {\n\t\t\ted.medium = v1.StorageMediumMemory\n\t\t\treturn ed.teardownTmpfsOrHugetlbfs(dir)\n\t\t} else if medium == v1.StorageMediumHugePages {\n\t\t\ted.medium = v1.StorageMediumHugePages\n\t\t\treturn ed.teardownTmpfsOrHugetlbfs(dir)\n\t\t}\n\t}\n\t// assume StorageMediumDefault\n\treturn ed.teardownDefault(dir)\n}","line":{"from":488,"to":519}} {"id":100012121,"name":"teardownDefault","signature":"func (ed *emptyDir) teardownDefault(dir string) error","file":"pkg/volume/emptydir/empty_dir.go","code":"func (ed *emptyDir) teardownDefault(dir string) error {\n\t// Remove any quota\n\terr := fsquota.ClearQuota(ed.mounter, dir)\n\tif err != nil {\n\t\tklog.Warningf(\"Warning: Failed to clear quota on %s: %v\", dir, err)\n\t}\n\t// Renaming the directory is not required anymore because the operation executor\n\t// now handles duplicate operations on the same volume\n\treturn os.RemoveAll(dir)\n}","line":{"from":521,"to":530}} {"id":100012122,"name":"teardownTmpfsOrHugetlbfs","signature":"func (ed *emptyDir) teardownTmpfsOrHugetlbfs(dir string) error","file":"pkg/volume/emptydir/empty_dir.go","code":"func (ed *emptyDir) teardownTmpfsOrHugetlbfs(dir string) error {\n\tif ed.mounter == nil {\n\t\treturn fmt.Errorf(\"memory storage requested, but mounter is nil\")\n\t}\n\tif err := ed.mounter.Unmount(dir); err != nil {\n\t\treturn err\n\t}\n\tif err := os.RemoveAll(dir); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":532,"to":543}} {"id":100012123,"name":"getMetaDir","signature":"func (ed *emptyDir) getMetaDir() string","file":"pkg/volume/emptydir/empty_dir.go","code":"func (ed *emptyDir) getMetaDir() string {\n\treturn filepath.Join(ed.plugin.host.GetPodPluginDir(ed.pod.UID, utilstrings.EscapeQualifiedName(emptyDirPluginName)), ed.volName)\n}","line":{"from":545,"to":547}} {"id":100012124,"name":"getVolumeSource","signature":"func getVolumeSource(spec *volume.Spec) (*v1.EmptyDirVolumeSource, bool)","file":"pkg/volume/emptydir/empty_dir.go","code":"func getVolumeSource(spec *volume.Spec) (*v1.EmptyDirVolumeSource, bool) {\n\tvar readOnly bool\n\tvar volumeSource *v1.EmptyDirVolumeSource\n\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.EmptyDir != nil {\n\t\tvolumeSource = spec.Volume.EmptyDir\n\t\treadOnly = spec.ReadOnly\n\t}\n\n\treturn volumeSource, readOnly\n}","line":{"from":549,"to":559}} {"id":100012125,"name":"getPageSize","signature":"func getPageSize(path string, mounter mount.Interface) (*resource.Quantity, error)","file":"pkg/volume/emptydir/empty_dir_linux.go","code":"// getPageSize obtains page size from the 'pagesize' mount option of the\n// mounted volume\nfunc getPageSize(path string, mounter mount.Interface) (*resource.Quantity, error) {\n\t// Get mount point data for the path\n\tmountPoints, err := mounter.List()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error listing mount points: %v\", err)\n\t}\n\t// Find mount point for the path\n\tmountPoint, err := func(mps []mount.MountPoint, mpPath string) (*mount.MountPoint, error) {\n\t\tfor _, mp := range mps {\n\t\t\tif mp.Path == mpPath {\n\t\t\t\treturn \u0026mp, nil\n\t\t\t}\n\t\t}\n\t\treturn nil, fmt.Errorf(\"mount point for %s not found\", mpPath)\n\t}(mountPoints, path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Get page size from the 'pagesize' option value\n\tfor _, opt := range mountPoint.Opts {\n\t\topt = strings.TrimSpace(opt)\n\t\tprefix := \"pagesize=\"\n\t\tif strings.HasPrefix(opt, prefix) {\n\t\t\t// NOTE: Adding suffix 'i' as result should be comparable with a medium size.\n\t\t\t// pagesize mount option is specified without a suffix,\n\t\t\t// e.g. pagesize=2M or pagesize=1024M for x86 CPUs\n\t\t\ttrimmedOpt := strings.TrimPrefix(opt, prefix)\n\t\t\tif !strings.HasSuffix(trimmedOpt, \"i\") {\n\t\t\t\ttrimmedOpt = trimmedOpt + \"i\"\n\t\t\t}\n\t\t\tpageSize, err := resource.ParseQuantity(trimmedOpt)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error getting page size from '%s' mount option: %v\", opt, err)\n\t\t\t}\n\t\t\treturn \u0026pageSize, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"no pagesize option specified for %s mount\", mountPoint.Path)\n}","line":{"from":45,"to":85}} {"id":100012126,"name":"GetMountMedium","signature":"func (m *realMountDetector) GetMountMedium(path string, requestedMedium v1.StorageMedium) (v1.StorageMedium, bool, *resource.Quantity, error)","file":"pkg/volume/emptydir/empty_dir_linux.go","code":"func (m *realMountDetector) GetMountMedium(path string, requestedMedium v1.StorageMedium) (v1.StorageMedium, bool, *resource.Quantity, error) {\n\tklog.V(5).Infof(\"Determining mount medium of %v\", path)\n\tnotMnt, err := m.mounter.IsLikelyNotMountPoint(path)\n\tif err != nil {\n\t\treturn v1.StorageMediumDefault, false, nil, fmt.Errorf(\"IsLikelyNotMountPoint(%q): %v\", path, err)\n\t}\n\n\tbuf := unix.Statfs_t{}\n\tif err := unix.Statfs(path, \u0026buf); err != nil {\n\t\treturn v1.StorageMediumDefault, false, nil, fmt.Errorf(\"statfs(%q): %v\", path, err)\n\t}\n\n\tklog.V(3).Infof(\"Statfs_t of %v: %+v\", path, buf)\n\n\tif buf.Type == linuxTmpfsMagic {\n\t\treturn v1.StorageMediumMemory, !notMnt, nil, nil\n\t} else if int64(buf.Type) == linuxHugetlbfsMagic {\n\t\t// Skip page size detection if requested medium doesn't have size specified\n\t\tif requestedMedium == v1.StorageMediumHugePages {\n\t\t\treturn v1.StorageMediumHugePages, !notMnt, nil, nil\n\t\t}\n\t\t// Get page size for the volume mount\n\t\tpageSize, err := getPageSize(path, m.mounter)\n\t\tif err != nil {\n\t\t\treturn v1.StorageMediumHugePages, !notMnt, nil, err\n\t\t}\n\t\treturn v1.StorageMediumHugePages, !notMnt, pageSize, nil\n\t}\n\treturn v1.StorageMediumDefault, !notMnt, nil, nil\n}","line":{"from":87,"to":116}} {"id":100012127,"name":"GetMountMedium","signature":"func (m *realMountDetector) GetMountMedium(path string, requestedMedium v1.StorageMedium) (v1.StorageMedium, bool, *resource.Quantity, error)","file":"pkg/volume/emptydir/empty_dir_unsupported.go","code":"func (m *realMountDetector) GetMountMedium(path string, requestedMedium v1.StorageMedium) (v1.StorageMedium, bool, *resource.Quantity, error) {\n\treturn v1.StorageMediumDefault, false, nil, nil\n}","line":{"from":34,"to":36}} {"id":100012128,"name":"NewAttacher","signature":"func (plugin *fcPlugin) NewAttacher() (volume.Attacher, error)","file":"pkg/volume/fc/attacher.go","code":"func (plugin *fcPlugin) NewAttacher() (volume.Attacher, error) {\n\treturn \u0026fcAttacher{\n\t\thost: plugin.host,\n\t\tmanager: \u0026fcUtil{},\n\t}, nil\n}","line":{"from":48,"to":53}} {"id":100012129,"name":"NewDeviceMounter","signature":"func (plugin *fcPlugin) NewDeviceMounter() (volume.DeviceMounter, error)","file":"pkg/volume/fc/attacher.go","code":"func (plugin *fcPlugin) NewDeviceMounter() (volume.DeviceMounter, error) {\n\treturn plugin.NewAttacher()\n}","line":{"from":55,"to":57}} {"id":100012130,"name":"GetDeviceMountRefs","signature":"func (plugin *fcPlugin) GetDeviceMountRefs(deviceMountPath string) ([]string, error)","file":"pkg/volume/fc/attacher.go","code":"func (plugin *fcPlugin) GetDeviceMountRefs(deviceMountPath string) ([]string, error) {\n\tmounter := plugin.host.GetMounter(plugin.GetPluginName())\n\treturn mounter.GetMountRefs(deviceMountPath)\n}","line":{"from":59,"to":62}} {"id":100012131,"name":"Attach","signature":"func (attacher *fcAttacher) Attach(spec *volume.Spec, nodeName types.NodeName) (string, error)","file":"pkg/volume/fc/attacher.go","code":"func (attacher *fcAttacher) Attach(spec *volume.Spec, nodeName types.NodeName) (string, error) {\n\treturn \"\", nil\n}","line":{"from":64,"to":66}} {"id":100012132,"name":"VolumesAreAttached","signature":"func (attacher *fcAttacher) VolumesAreAttached(specs []*volume.Spec, nodeName types.NodeName) (map[*volume.Spec]bool, error)","file":"pkg/volume/fc/attacher.go","code":"func (attacher *fcAttacher) VolumesAreAttached(specs []*volume.Spec, nodeName types.NodeName) (map[*volume.Spec]bool, error) {\n\tvolumesAttachedCheck := make(map[*volume.Spec]bool)\n\tfor _, spec := range specs {\n\t\tvolumesAttachedCheck[spec] = true\n\t}\n\n\treturn volumesAttachedCheck, nil\n}","line":{"from":68,"to":75}} {"id":100012133,"name":"WaitForAttach","signature":"func (attacher *fcAttacher) WaitForAttach(spec *volume.Spec, devicePath string, _ *v1.Pod, timeout time.Duration) (string, error)","file":"pkg/volume/fc/attacher.go","code":"func (attacher *fcAttacher) WaitForAttach(spec *volume.Spec, devicePath string, _ *v1.Pod, timeout time.Duration) (string, error) {\n\tmounter, err := volumeSpecToMounter(spec, attacher.host)\n\tif err != nil {\n\t\tklog.Warningf(\"failed to get fc mounter: %v\", err)\n\t\treturn \"\", err\n\t}\n\treturn attacher.manager.AttachDisk(*mounter)\n}","line":{"from":77,"to":84}} {"id":100012134,"name":"GetDeviceMountPath","signature":"func (attacher *fcAttacher) GetDeviceMountPath(","file":"pkg/volume/fc/attacher.go","code":"func (attacher *fcAttacher) GetDeviceMountPath(\n\tspec *volume.Spec) (string, error) {\n\tmounter, err := volumeSpecToMounter(spec, attacher.host)\n\tif err != nil {\n\t\tklog.Warningf(\"failed to get fc mounter: %v\", err)\n\t\treturn \"\", err\n\t}\n\n\treturn attacher.manager.MakeGlobalPDName(*mounter.fcDisk), nil\n}","line":{"from":86,"to":95}} {"id":100012135,"name":"MountDevice","signature":"func (attacher *fcAttacher) MountDevice(spec *volume.Spec, devicePath string, deviceMountPath string, mountArgs volume.DeviceMounterArgs) error","file":"pkg/volume/fc/attacher.go","code":"func (attacher *fcAttacher) MountDevice(spec *volume.Spec, devicePath string, deviceMountPath string, mountArgs volume.DeviceMounterArgs) error {\n\tmounter := attacher.host.GetMounter(fcPluginName)\n\tnotMnt, err := mounter.IsLikelyNotMountPoint(deviceMountPath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tif err := os.MkdirAll(deviceMountPath, 0750); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tnotMnt = true\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tvolumeSource, readOnly, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\toptions := []string{}\n\tif readOnly {\n\t\toptions = append(options, \"ro\")\n\t}\n\tif mountArgs.SELinuxLabel != \"\" {\n\t\toptions = volumeutil.AddSELinuxMountOption(options, mountArgs.SELinuxLabel)\n\t}\n\tif notMnt {\n\t\tdiskMounter := \u0026mount.SafeFormatAndMount{Interface: mounter, Exec: attacher.host.GetExec(fcPluginName)}\n\t\tmountOptions := volumeutil.MountOptionFromSpec(spec, options...)\n\t\terr = diskMounter.FormatAndMount(devicePath, deviceMountPath, volumeSource.FSType, mountOptions)\n\t\tif err != nil {\n\t\t\tos.Remove(deviceMountPath)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":97,"to":133}} {"id":100012136,"name":"NewDetacher","signature":"func (plugin *fcPlugin) NewDetacher() (volume.Detacher, error)","file":"pkg/volume/fc/attacher.go","code":"func (plugin *fcPlugin) NewDetacher() (volume.Detacher, error) {\n\treturn \u0026fcDetacher{\n\t\tmounter: plugin.host.GetMounter(plugin.GetPluginName()),\n\t\tmanager: \u0026fcUtil{},\n\t\thost: plugin.host,\n\t}, nil\n}","line":{"from":145,"to":151}} {"id":100012137,"name":"NewDeviceUnmounter","signature":"func (plugin *fcPlugin) NewDeviceUnmounter() (volume.DeviceUnmounter, error)","file":"pkg/volume/fc/attacher.go","code":"func (plugin *fcPlugin) NewDeviceUnmounter() (volume.DeviceUnmounter, error) {\n\treturn plugin.NewDetacher()\n}","line":{"from":153,"to":155}} {"id":100012138,"name":"Detach","signature":"func (detacher *fcDetacher) Detach(volumeName string, nodeName types.NodeName) error","file":"pkg/volume/fc/attacher.go","code":"func (detacher *fcDetacher) Detach(volumeName string, nodeName types.NodeName) error {\n\treturn nil\n}","line":{"from":157,"to":159}} {"id":100012139,"name":"UnmountDevice","signature":"func (detacher *fcDetacher) UnmountDevice(deviceMountPath string) error","file":"pkg/volume/fc/attacher.go","code":"func (detacher *fcDetacher) UnmountDevice(deviceMountPath string) error {\n\t// Specify device name for DetachDisk later\n\tdevName, _, err := mount.GetDeviceNameFromMount(detacher.mounter, deviceMountPath)\n\tif err != nil {\n\t\tklog.Errorf(\"fc: failed to get device from mnt: %s\\nError: %v\", deviceMountPath, err)\n\t\treturn err\n\t}\n\t// Unmount for deviceMountPath(=globalPDPath)\n\terr = mount.CleanupMountPoint(deviceMountPath, detacher.mounter, false)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"fc: failed to unmount: %s\\nError: %v\", deviceMountPath, err)\n\t}\n\t// GetDeviceNameFromMount from above returns an empty string if deviceMountPath is not a mount point\n\t// There is no need to DetachDisk if this is the case (and DetachDisk will throw an error if we attempt)\n\tif devName == \"\" {\n\t\treturn nil\n\t}\n\n\tunMounter := volumeSpecToUnmounter(detacher.mounter, detacher.host)\n\t// The device is unmounted now. If UnmountDevice was retried, GetDeviceNameFromMount\n\t// won't find any mount and won't return DetachDisk below.\n\t// Therefore implement our own retry mechanism here.\n\t// E.g. DetachDisk sometimes fails to flush a multipath device with \"device is busy\" when it was\n\t// just unmounted.\n\t// 2 minutes should be enough within 6 minute force detach timeout.\n\tvar detachError error\n\terr = wait.PollImmediate(10*time.Second, 2*time.Minute, func() (bool, error) {\n\t\tdetachError = detacher.manager.DetachDisk(*unMounter, devName)\n\t\tif detachError != nil {\n\t\t\tklog.V(4).Infof(\"fc: failed to detach disk %s (%s): %v\", devName, deviceMountPath, detachError)\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"fc: failed to detach disk: %s: %v\", devName, detachError)\n\t}\n\n\tklog.V(2).Infof(\"fc: successfully detached disk: %s\", devName)\n\treturn nil\n}","line":{"from":161,"to":201}} {"id":100012140,"name":"CanAttach","signature":"func (plugin *fcPlugin) CanAttach(spec *volume.Spec) (bool, error)","file":"pkg/volume/fc/attacher.go","code":"func (plugin *fcPlugin) CanAttach(spec *volume.Spec) (bool, error) {\n\treturn true, nil\n}","line":{"from":203,"to":205}} {"id":100012141,"name":"CanDeviceMount","signature":"func (plugin *fcPlugin) CanDeviceMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/fc/attacher.go","code":"func (plugin *fcPlugin) CanDeviceMount(spec *volume.Spec) (bool, error) {\n\treturn true, nil\n}","line":{"from":207,"to":209}} {"id":100012142,"name":"volumeSpecToMounter","signature":"func volumeSpecToMounter(spec *volume.Spec, host volume.VolumeHost) (*fcDiskMounter, error)","file":"pkg/volume/fc/attacher.go","code":"func volumeSpecToMounter(spec *volume.Spec, host volume.VolumeHost) (*fcDiskMounter, error) {\n\tfc, readOnly, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar lun string\n\tvar wwids []string\n\tif fc.Lun != nil \u0026\u0026 len(fc.TargetWWNs) != 0 {\n\t\tlun = strconv.Itoa(int(*fc.Lun))\n\t} else if len(fc.WWIDs) != 0 {\n\t\tfor _, wwid := range fc.WWIDs {\n\t\t\twwids = append(wwids, strings.Replace(wwid, \" \", \"_\", -1))\n\t\t}\n\t} else {\n\t\treturn nil, fmt.Errorf(\"fc: no fc disk information found. failed to make a new mounter\")\n\t}\n\tfcDisk := \u0026fcDisk{\n\t\tplugin: \u0026fcPlugin{\n\t\t\thost: host,\n\t\t},\n\t\twwns: fc.TargetWWNs,\n\t\tlun: lun,\n\t\twwids: wwids,\n\t\tio: \u0026osIOHandler{},\n\t}\n\n\tvolumeMode, err := volumeutil.GetVolumeMode(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tklog.V(5).Infof(\"fc: volumeSpecToMounter volumeMode %s\", volumeMode)\n\treturn \u0026fcDiskMounter{\n\t\tfcDisk: fcDisk,\n\t\tfsType: fc.FSType,\n\t\tvolumeMode: volumeMode,\n\t\treadOnly: readOnly,\n\t\tmounter: volumeutil.NewSafeFormatAndMountFromHost(fcPluginName, host),\n\t\tdeviceUtil: volumeutil.NewDeviceHandler(volumeutil.NewIOHandler()),\n\t\tmountOptions: volumeutil.MountOptionFromSpec(spec),\n\t}, nil\n}","line":{"from":211,"to":252}} {"id":100012143,"name":"volumeSpecToUnmounter","signature":"func volumeSpecToUnmounter(mounter mount.Interface, host volume.VolumeHost) *fcDiskUnmounter","file":"pkg/volume/fc/attacher.go","code":"func volumeSpecToUnmounter(mounter mount.Interface, host volume.VolumeHost) *fcDiskUnmounter {\n\treturn \u0026fcDiskUnmounter{\n\t\tfcDisk: \u0026fcDisk{\n\t\t\tio: \u0026osIOHandler{},\n\t\t},\n\t\tmounter: mounter,\n\t\tdeviceUtil: volumeutil.NewDeviceHandler(volumeutil.NewIOHandler()),\n\t\texec: host.GetExec(fcPluginName),\n\t}\n}","line":{"from":254,"to":263}} {"id":100012144,"name":"diskSetUp","signature":"func diskSetUp(manager diskManager, b fcDiskMounter, volPath string, mounter mount.Interface, fsGroup *int64, fsGroupChangePolicy *v1.PodFSGroupChangePolicy) error","file":"pkg/volume/fc/disk_manager.go","code":"// utility to mount a disk based filesystem\nfunc diskSetUp(manager diskManager, b fcDiskMounter, volPath string, mounter mount.Interface, fsGroup *int64, fsGroupChangePolicy *v1.PodFSGroupChangePolicy) error {\n\tglobalPDPath := manager.MakeGlobalPDName(*b.fcDisk)\n\tnoMnt, err := mounter.IsLikelyNotMountPoint(volPath)\n\n\tif err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\tklog.Errorf(\"cannot validate mountpoint: %s\", volPath)\n\t\treturn err\n\t}\n\tif !noMnt {\n\t\treturn nil\n\t}\n\tif err := os.MkdirAll(volPath, 0750); err != nil {\n\t\tklog.Errorf(\"failed to mkdir:%s\", volPath)\n\t\treturn err\n\t}\n\t// Perform a bind mount to the full path to allow duplicate mounts of the same disk.\n\toptions := []string{\"bind\"}\n\tif b.readOnly {\n\t\toptions = append(options, \"ro\")\n\t}\n\tmountOptions := util.JoinMountOptions(options, b.mountOptions)\n\terr = mounter.MountSensitiveWithoutSystemd(globalPDPath, volPath, \"\", mountOptions, nil)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to bind mount: source:%s, target:%s, err:%v\", globalPDPath, volPath, err)\n\t\tnoMnt, mntErr := b.mounter.IsLikelyNotMountPoint(volPath)\n\t\tif mntErr != nil {\n\t\t\tklog.Errorf(\"IsLikelyNotMountPoint check failed: %v\", mntErr)\n\t\t\treturn err\n\t\t}\n\t\tif !noMnt {\n\t\t\tif mntErr = b.mounter.Unmount(volPath); mntErr != nil {\n\t\t\t\tklog.Errorf(\"Failed to unmount: %v\", mntErr)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tnoMnt, mntErr = b.mounter.IsLikelyNotMountPoint(volPath)\n\t\t\tif mntErr != nil {\n\t\t\t\tklog.Errorf(\"IsLikelyNotMountPoint check failed: %v\", mntErr)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !noMnt {\n\t\t\t\t// will most likely retry on next sync loop.\n\t\t\t\tklog.Errorf(\"%s is still mounted, despite call to unmount(). Will try again next sync loop.\", volPath)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tos.Remove(volPath)\n\n\t\treturn err\n\t}\n\n\tif !b.readOnly {\n\t\tvolume.SetVolumeOwnership(\u0026b, volPath, fsGroup, fsGroupChangePolicy, util.FSGroupCompleteHook(b.plugin, nil))\n\t}\n\n\treturn nil\n}","line":{"from":42,"to":98}} {"id":100012145,"name":"ProbeVolumePlugins","signature":"func ProbeVolumePlugins() []volume.VolumePlugin","file":"pkg/volume/fc/fc.go","code":"// ProbeVolumePlugins is the primary entrypoint for volume plugins.\nfunc ProbeVolumePlugins() []volume.VolumePlugin {\n\treturn []volume.VolumePlugin{\u0026fcPlugin{nil}}\n}","line":{"from":42,"to":45}} {"id":100012146,"name":"Init","signature":"func (plugin *fcPlugin) Init(host volume.VolumeHost) error","file":"pkg/volume/fc/fc.go","code":"func (plugin *fcPlugin) Init(host volume.VolumeHost) error {\n\tplugin.host = host\n\treturn nil\n}","line":{"from":59,"to":62}} {"id":100012147,"name":"GetPluginName","signature":"func (plugin *fcPlugin) GetPluginName() string","file":"pkg/volume/fc/fc.go","code":"func (plugin *fcPlugin) GetPluginName() string {\n\treturn fcPluginName\n}","line":{"from":64,"to":66}} {"id":100012148,"name":"GetVolumeName","signature":"func (plugin *fcPlugin) GetVolumeName(spec *volume.Spec) (string, error)","file":"pkg/volume/fc/fc.go","code":"func (plugin *fcPlugin) GetVolumeName(spec *volume.Spec) (string, error) {\n\tvolumeSource, _, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// API server validates these parameters beforehand but attach/detach\n\t// controller creates volumespec without validation. They may be nil\n\t// or zero length. We should check again to avoid unexpected conditions.\n\tif len(volumeSource.TargetWWNs) != 0 \u0026\u0026 volumeSource.Lun != nil {\n\t\t// TargetWWNs are the FibreChannel target worldwide names\n\t\treturn fmt.Sprintf(\"%v:%v\", volumeSource.TargetWWNs, *volumeSource.Lun), nil\n\t} else if len(volumeSource.WWIDs) != 0 {\n\t\t// WWIDs are the FibreChannel World Wide Identifiers\n\t\treturn fmt.Sprintf(\"%v\", volumeSource.WWIDs), nil\n\t}\n\n\treturn \"\", err\n}","line":{"from":68,"to":86}} {"id":100012149,"name":"CanSupport","signature":"func (plugin *fcPlugin) CanSupport(spec *volume.Spec) bool","file":"pkg/volume/fc/fc.go","code":"func (plugin *fcPlugin) CanSupport(spec *volume.Spec) bool {\n\treturn (spec.Volume != nil \u0026\u0026 spec.Volume.FC != nil) || (spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.FC != nil)\n}","line":{"from":88,"to":90}} {"id":100012150,"name":"RequiresRemount","signature":"func (plugin *fcPlugin) RequiresRemount(spec *volume.Spec) bool","file":"pkg/volume/fc/fc.go","code":"func (plugin *fcPlugin) RequiresRemount(spec *volume.Spec) bool {\n\treturn false\n}","line":{"from":92,"to":94}} {"id":100012151,"name":"SupportsMountOption","signature":"func (plugin *fcPlugin) SupportsMountOption() bool","file":"pkg/volume/fc/fc.go","code":"func (plugin *fcPlugin) SupportsMountOption() bool {\n\treturn true\n}","line":{"from":96,"to":98}} {"id":100012152,"name":"SupportsBulkVolumeVerification","signature":"func (plugin *fcPlugin) SupportsBulkVolumeVerification() bool","file":"pkg/volume/fc/fc.go","code":"func (plugin *fcPlugin) SupportsBulkVolumeVerification() bool {\n\treturn false\n}","line":{"from":100,"to":102}} {"id":100012153,"name":"SupportsSELinuxContextMount","signature":"func (plugin *fcPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/fc/fc.go","code":"func (plugin *fcPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error) {\n\treturn true, nil\n}","line":{"from":104,"to":106}} {"id":100012154,"name":"GetAccessModes","signature":"func (plugin *fcPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode","file":"pkg/volume/fc/fc.go","code":"func (plugin *fcPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode {\n\treturn []v1.PersistentVolumeAccessMode{\n\t\tv1.ReadWriteOnce,\n\t\tv1.ReadOnlyMany,\n\t}\n}","line":{"from":108,"to":113}} {"id":100012155,"name":"NewMounter","signature":"func (plugin *fcPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error)","file":"pkg/volume/fc/fc.go","code":"func (plugin *fcPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) {\n\t// Inject real implementations here, test through the internal function.\n\treturn plugin.newMounterInternal(spec, pod.UID, \u0026fcUtil{}, plugin.host.GetMounter(plugin.GetPluginName()), plugin.host.GetExec(plugin.GetPluginName()))\n}","line":{"from":115,"to":118}} {"id":100012156,"name":"newMounterInternal","signature":"func (plugin *fcPlugin) newMounterInternal(spec *volume.Spec, podUID types.UID, manager diskManager, mounter mount.Interface, exec utilexec.Interface) (volume.Mounter, error)","file":"pkg/volume/fc/fc.go","code":"func (plugin *fcPlugin) newMounterInternal(spec *volume.Spec, podUID types.UID, manager diskManager, mounter mount.Interface, exec utilexec.Interface) (volume.Mounter, error) {\n\t// fc volumes used directly in a pod have a ReadOnly flag set by the pod author.\n\t// fc volumes used as a PersistentVolume gets the ReadOnly flag indirectly through the persistent-claim volume used to mount the PV\n\tfc, readOnly, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twwns, lun, wwids, err := getWwnsLunWwids(fc)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"fc: no fc disk information found. failed to make a new mounter\")\n\t}\n\tfcDisk := \u0026fcDisk{\n\t\tpodUID: podUID,\n\t\tvolName: spec.Name(),\n\t\twwns: wwns,\n\t\tlun: lun,\n\t\twwids: wwids,\n\t\tmanager: manager,\n\t\tio: \u0026osIOHandler{},\n\t\tplugin: plugin,\n\t}\n\n\tvolumeMode, err := util.GetVolumeMode(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tklog.V(5).Infof(\"fc: newMounterInternal volumeMode %s\", volumeMode)\n\treturn \u0026fcDiskMounter{\n\t\tfcDisk: fcDisk,\n\t\tfsType: fc.FSType,\n\t\tvolumeMode: volumeMode,\n\t\treadOnly: readOnly,\n\t\tmounter: \u0026mount.SafeFormatAndMount{Interface: mounter, Exec: exec},\n\t\tdeviceUtil: util.NewDeviceHandler(util.NewIOHandler()),\n\t\tmountOptions: util.MountOptionFromSpec(spec),\n\t}, nil\n}","line":{"from":120,"to":158}} {"id":100012157,"name":"NewBlockVolumeMapper","signature":"func (plugin *fcPlugin) NewBlockVolumeMapper(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.BlockVolumeMapper, error)","file":"pkg/volume/fc/fc.go","code":"func (plugin *fcPlugin) NewBlockVolumeMapper(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.BlockVolumeMapper, error) {\n\t// If this called via GenerateUnmapDeviceFunc(), pod is nil.\n\t// Pass empty string as dummy uid since uid isn't used in the case.\n\tvar uid types.UID\n\tif pod != nil {\n\t\tuid = pod.UID\n\t}\n\treturn plugin.newBlockVolumeMapperInternal(spec, uid, \u0026fcUtil{}, plugin.host.GetMounter(plugin.GetPluginName()), plugin.host.GetExec(plugin.GetPluginName()))\n}","line":{"from":160,"to":168}} {"id":100012158,"name":"newBlockVolumeMapperInternal","signature":"func (plugin *fcPlugin) newBlockVolumeMapperInternal(spec *volume.Spec, podUID types.UID, manager diskManager, mounter mount.Interface, exec utilexec.Interface) (volume.BlockVolumeMapper, error)","file":"pkg/volume/fc/fc.go","code":"func (plugin *fcPlugin) newBlockVolumeMapperInternal(spec *volume.Spec, podUID types.UID, manager diskManager, mounter mount.Interface, exec utilexec.Interface) (volume.BlockVolumeMapper, error) {\n\tfc, readOnly, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twwns, lun, wwids, err := getWwnsLunWwids(fc)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"fc: no fc disk information found. failed to make a new mapper\")\n\t}\n\n\tmapper := \u0026fcDiskMapper{\n\t\tfcDisk: \u0026fcDisk{\n\t\t\tpodUID: podUID,\n\t\t\tvolName: spec.Name(),\n\t\t\twwns: wwns,\n\t\t\tlun: lun,\n\t\t\twwids: wwids,\n\t\t\tmanager: manager,\n\t\t\tio: \u0026osIOHandler{},\n\t\t\tplugin: plugin},\n\t\treadOnly: readOnly,\n\t\tmounter: \u0026mount.SafeFormatAndMount{Interface: mounter, Exec: exec},\n\t\tdeviceUtil: util.NewDeviceHandler(util.NewIOHandler()),\n\t}\n\n\tblockPath, err := mapper.GetGlobalMapPath(spec)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get device path: %v\", err)\n\t}\n\tmapper.MetricsProvider = volume.NewMetricsBlock(filepath.Join(blockPath, string(podUID)))\n\n\treturn mapper, nil\n}","line":{"from":170,"to":203}} {"id":100012159,"name":"NewUnmounter","signature":"func (plugin *fcPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error)","file":"pkg/volume/fc/fc.go","code":"func (plugin *fcPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error) {\n\t// Inject real implementations here, test through the internal function.\n\treturn plugin.newUnmounterInternal(volName, podUID, \u0026fcUtil{}, plugin.host.GetMounter(plugin.GetPluginName()), plugin.host.GetExec(plugin.GetPluginName()))\n}","line":{"from":205,"to":208}} {"id":100012160,"name":"newUnmounterInternal","signature":"func (plugin *fcPlugin) newUnmounterInternal(volName string, podUID types.UID, manager diskManager, mounter mount.Interface, exec utilexec.Interface) (volume.Unmounter, error)","file":"pkg/volume/fc/fc.go","code":"func (plugin *fcPlugin) newUnmounterInternal(volName string, podUID types.UID, manager diskManager, mounter mount.Interface, exec utilexec.Interface) (volume.Unmounter, error) {\n\treturn \u0026fcDiskUnmounter{\n\t\tfcDisk: \u0026fcDisk{\n\t\t\tpodUID: podUID,\n\t\t\tvolName: volName,\n\t\t\tmanager: manager,\n\t\t\tplugin: plugin,\n\t\t\tio: \u0026osIOHandler{},\n\t\t},\n\t\tmounter: mounter,\n\t\tdeviceUtil: util.NewDeviceHandler(util.NewIOHandler()),\n\t\texec: exec,\n\t}, nil\n}","line":{"from":210,"to":223}} {"id":100012161,"name":"NewBlockVolumeUnmapper","signature":"func (plugin *fcPlugin) NewBlockVolumeUnmapper(volName string, podUID types.UID) (volume.BlockVolumeUnmapper, error)","file":"pkg/volume/fc/fc.go","code":"func (plugin *fcPlugin) NewBlockVolumeUnmapper(volName string, podUID types.UID) (volume.BlockVolumeUnmapper, error) {\n\treturn plugin.newUnmapperInternal(volName, podUID, \u0026fcUtil{}, plugin.host.GetExec(plugin.GetPluginName()))\n}","line":{"from":225,"to":227}} {"id":100012162,"name":"newUnmapperInternal","signature":"func (plugin *fcPlugin) newUnmapperInternal(volName string, podUID types.UID, manager diskManager, exec utilexec.Interface) (volume.BlockVolumeUnmapper, error)","file":"pkg/volume/fc/fc.go","code":"func (plugin *fcPlugin) newUnmapperInternal(volName string, podUID types.UID, manager diskManager, exec utilexec.Interface) (volume.BlockVolumeUnmapper, error) {\n\treturn \u0026fcDiskUnmapper{\n\t\tfcDisk: \u0026fcDisk{\n\t\t\tpodUID: podUID,\n\t\t\tvolName: volName,\n\t\t\tmanager: manager,\n\t\t\tplugin: plugin,\n\t\t\tio: \u0026osIOHandler{},\n\t\t},\n\t\texec: exec,\n\t\tdeviceUtil: util.NewDeviceHandler(util.NewIOHandler()),\n\t}, nil\n}","line":{"from":229,"to":241}} {"id":100012163,"name":"ConstructVolumeSpec","signature":"func (plugin *fcPlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error)","file":"pkg/volume/fc/fc.go","code":"func (plugin *fcPlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error) {\n\t// Find globalPDPath from pod volume directory(mountPath)\n\t// examples:\n\t// mountPath: pods/{podUid}/volumes/kubernetes.io~fc/{volumeName}\n\t// globalPDPath : plugins/kubernetes.io/fc/50060e801049cfd1-lun-0\n\tvar globalPDPath string\n\n\tmounter := plugin.host.GetMounter(plugin.GetPluginName())\n\t// Try really hard to get the global mount of the volume, an error returned from here would\n\t// leave the global mount still mounted, while marking the volume as unused.\n\t// The volume can then be mounted on several nodes, resulting in volume\n\t// corruption.\n\tpaths, err := util.GetReliableMountRefs(mounter, mountPath)\n\tif io.IsInconsistentReadError(err) {\n\t\tklog.Errorf(\"Failed to read mount refs from /proc/mounts for %s: %s\", mountPath, err)\n\t\tklog.Errorf(\"Kubelet cannot unmount volume at %s, please unmount it manually\", mountPath)\n\t\treturn volume.ReconstructedVolume{}, err\n\t}\n\tif err != nil {\n\t\treturn volume.ReconstructedVolume{}, err\n\t}\n\tfor _, path := range paths {\n\t\tif strings.Contains(path, plugin.host.GetPluginDir(fcPluginName)) {\n\t\t\tglobalPDPath = path\n\t\t\tbreak\n\t\t}\n\t}\n\t// Couldn't fetch globalPDPath\n\tif len(globalPDPath) == 0 {\n\t\treturn volume.ReconstructedVolume{}, fmt.Errorf(\"couldn't fetch globalPDPath. failed to obtain volume spec\")\n\t}\n\n\twwns, lun, wwids, err := parsePDName(globalPDPath)\n\tif err != nil {\n\t\treturn volume.ReconstructedVolume{}, fmt.Errorf(\"failed to retrieve volume plugin information from globalPDPath: %s\", err)\n\t}\n\t// Create volume from wwn+lun or wwid\n\tfcVolume := \u0026v1.Volume{\n\t\tName: volumeName,\n\t\tVolumeSource: v1.VolumeSource{\n\t\t\tFC: \u0026v1.FCVolumeSource{WWIDs: wwids, Lun: \u0026lun, TargetWWNs: wwns},\n\t\t},\n\t}\n\n\tvar mountContext string\n\tif utilfeature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {\n\t\tkvh, ok := plugin.host.(volume.KubeletVolumeHost)\n\t\tif !ok {\n\t\t\treturn volume.ReconstructedVolume{}, fmt.Errorf(\"plugin volume host does not implement KubeletVolumeHost interface\")\n\t\t}\n\t\thu := kvh.GetHostUtil()\n\t\tmountContext, err = hu.GetSELinuxMountContext(mountPath)\n\t\tif err != nil {\n\t\t\treturn volume.ReconstructedVolume{}, err\n\t\t}\n\t}\n\n\tklog.V(5).Infof(\"ConstructVolumeSpec: TargetWWNs: %v, Lun: %v, WWIDs: %v\",\n\t\tfcVolume.VolumeSource.FC.TargetWWNs, *fcVolume.VolumeSource.FC.Lun, fcVolume.VolumeSource.FC.WWIDs)\n\treturn volume.ReconstructedVolume{\n\t\tSpec: volume.NewSpecFromVolume(fcVolume),\n\t\tSELinuxMountContext: mountContext,\n\t}, nil\n}","line":{"from":243,"to":306}} {"id":100012164,"name":"ConstructBlockVolumeSpec","signature":"func (plugin *fcPlugin) ConstructBlockVolumeSpec(podUID types.UID, volumeName, mapPath string) (*volume.Spec, error)","file":"pkg/volume/fc/fc.go","code":"// ConstructBlockVolumeSpec creates a new volume.Spec with following steps.\n// - Searches a file whose name is {pod uuid} under volume plugin directory.\n// - If a file is found, then retrieves volumePluginDependentPath from globalMapPathUUID.\n// - Once volumePluginDependentPath is obtained, store volume information to VolumeSource\n//\n// examples:\n//\n//\tmapPath: pods/{podUid}/{DefaultKubeletVolumeDevicesDirName}/{escapeQualifiedPluginName}/{volumeName}\n//\tglobalMapPathUUID : plugins/kubernetes.io/{PluginName}/{DefaultKubeletVolumeDevicesDirName}/{volumePluginDependentPath}/{pod uuid}\nfunc (plugin *fcPlugin) ConstructBlockVolumeSpec(podUID types.UID, volumeName, mapPath string) (*volume.Spec, error) {\n\tpluginDir := plugin.host.GetVolumeDevicePluginDir(fcPluginName)\n\tblkutil := volumepathhandler.NewBlockVolumePathHandler()\n\tglobalMapPathUUID, err := blkutil.FindGlobalMapPathUUIDFromPod(pluginDir, mapPath, podUID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tklog.V(5).Infof(\"globalMapPathUUID: %v, err: %v\", globalMapPathUUID, err)\n\n\t// Retrieve globalPDPath from globalMapPathUUID\n\t// globalMapPathUUID examples:\n\t// wwn+lun: plugins/kubernetes.io/fc/volumeDevices/50060e801049cfd1-lun-0/{pod uuid}\n\t// wwid: plugins/kubernetes.io/fc/volumeDevices/3600508b400105e210000900000490000/{pod uuid}\n\tglobalPDPath := filepath.Dir(globalMapPathUUID)\n\t// Create volume from wwn+lun or wwid\n\twwns, lun, wwids, err := parsePDName(globalPDPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to retrieve volume plugin information from globalPDPath: %s\", err)\n\t}\n\tfcPV := createPersistentVolumeFromFCVolumeSource(volumeName,\n\t\tv1.FCVolumeSource{TargetWWNs: wwns, Lun: \u0026lun, WWIDs: wwids})\n\tklog.V(5).Infof(\"ConstructBlockVolumeSpec: TargetWWNs: %v, Lun: %v, WWIDs: %v\",\n\t\tfcPV.Spec.PersistentVolumeSource.FC.TargetWWNs,\n\t\t*fcPV.Spec.PersistentVolumeSource.FC.Lun,\n\t\tfcPV.Spec.PersistentVolumeSource.FC.WWIDs)\n\n\treturn volume.NewSpecFromPersistentVolume(fcPV, false), nil\n}","line":{"from":308,"to":344}} {"id":100012165,"name":"GetPath","signature":"func (fc *fcDisk) GetPath() string","file":"pkg/volume/fc/fc.go","code":"func (fc *fcDisk) GetPath() string {\n\t// safe to use PodVolumeDir now: volume teardown occurs before pod is cleaned up\n\treturn fc.plugin.host.GetPodVolumeDir(fc.podUID, utilstrings.EscapeQualifiedName(fcPluginName), fc.volName)\n}","line":{"from":360,"to":363}} {"id":100012166,"name":"fcGlobalMapPath","signature":"func (fc *fcDisk) fcGlobalMapPath(spec *volume.Spec) (string, error)","file":"pkg/volume/fc/fc.go","code":"func (fc *fcDisk) fcGlobalMapPath(spec *volume.Spec) (string, error) {\n\tmounter, err := volumeSpecToMounter(spec, fc.plugin.host)\n\tif err != nil {\n\t\tklog.Warningf(\"failed to get fc mounter: %v\", err)\n\t\treturn \"\", err\n\t}\n\treturn fc.manager.MakeGlobalVDPDName(*mounter.fcDisk), nil\n}","line":{"from":365,"to":372}} {"id":100012167,"name":"fcPodDeviceMapPath","signature":"func (fc *fcDisk) fcPodDeviceMapPath() (string, string)","file":"pkg/volume/fc/fc.go","code":"func (fc *fcDisk) fcPodDeviceMapPath() (string, string) {\n\treturn fc.plugin.host.GetPodVolumeDeviceDir(fc.podUID, utilstrings.EscapeQualifiedName(fcPluginName)), fc.volName\n}","line":{"from":374,"to":376}} {"id":100012168,"name":"GetAttributes","signature":"func (b *fcDiskMounter) GetAttributes() volume.Attributes","file":"pkg/volume/fc/fc.go","code":"func (b *fcDiskMounter) GetAttributes() volume.Attributes {\n\treturn volume.Attributes{\n\t\tReadOnly: b.readOnly,\n\t\tManaged: !b.readOnly,\n\t\tSELinuxRelabel: !b.mountedWithSELinuxContext,\n\t}\n}","line":{"from":391,"to":397}} {"id":100012169,"name":"SetUp","signature":"func (b *fcDiskMounter) SetUp(mounterArgs volume.MounterArgs) error","file":"pkg/volume/fc/fc.go","code":"func (b *fcDiskMounter) SetUp(mounterArgs volume.MounterArgs) error {\n\treturn b.SetUpAt(b.GetPath(), mounterArgs)\n}","line":{"from":399,"to":401}} {"id":100012170,"name":"SetUpAt","signature":"func (b *fcDiskMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error","file":"pkg/volume/fc/fc.go","code":"func (b *fcDiskMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {\n\t// diskSetUp checks mountpoints and prevent repeated calls\n\terr := diskSetUp(b.manager, *b, dir, b.mounter, mounterArgs.FsGroup, mounterArgs.FSGroupChangePolicy)\n\tif err != nil {\n\t\tklog.Errorf(\"fc: failed to setup\")\n\t}\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {\n\t\t// The volume must have been mounted in MountDevice with -o context.\n\t\tb.mountedWithSELinuxContext = mounterArgs.SELinuxLabel != \"\"\n\t}\n\treturn err\n}","line":{"from":403,"to":415}} {"id":100012171,"name":"TearDown","signature":"func (c *fcDiskUnmounter) TearDown() error","file":"pkg/volume/fc/fc.go","code":"// Unmounts the bind mount, and detaches the disk only if the disk\n// resource was the last reference to that disk on the kubelet.\nfunc (c *fcDiskUnmounter) TearDown() error {\n\treturn c.TearDownAt(c.GetPath())\n}","line":{"from":426,"to":430}} {"id":100012172,"name":"TearDownAt","signature":"func (c *fcDiskUnmounter) TearDownAt(dir string) error","file":"pkg/volume/fc/fc.go","code":"func (c *fcDiskUnmounter) TearDownAt(dir string) error {\n\treturn mount.CleanupMountPoint(dir, c.mounter, false)\n}","line":{"from":432,"to":434}} {"id":100012173,"name":"TearDownDevice","signature":"func (c *fcDiskUnmapper) TearDownDevice(mapPath, devicePath string) error","file":"pkg/volume/fc/fc.go","code":"func (c *fcDiskUnmapper) TearDownDevice(mapPath, devicePath string) error {\n\terr := c.manager.DetachBlockFCDisk(*c, mapPath, devicePath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"fc: failed to detach disk: %s\\nError: %v\", mapPath, err)\n\t}\n\tklog.V(4).Infof(\"fc: %s is unmounted, deleting the directory\", mapPath)\n\tif err = os.RemoveAll(mapPath); err != nil {\n\t\treturn fmt.Errorf(\"fc: failed to delete the directory: %s\\nError: %v\", mapPath, err)\n\t}\n\tklog.V(4).Infof(\"fc: successfully detached disk: %s\", mapPath)\n\treturn nil\n}","line":{"from":456,"to":467}} {"id":100012174,"name":"UnmapPodDevice","signature":"func (c *fcDiskUnmapper) UnmapPodDevice() error","file":"pkg/volume/fc/fc.go","code":"func (c *fcDiskUnmapper) UnmapPodDevice() error {\n\treturn nil\n}","line":{"from":469,"to":471}} {"id":100012175,"name":"GetGlobalMapPath","signature":"func (fc *fcDisk) GetGlobalMapPath(spec *volume.Spec) (string, error)","file":"pkg/volume/fc/fc.go","code":"// GetGlobalMapPath returns global map path and error\n// path: plugins/kubernetes.io/{PluginName}/volumeDevices/{WWID}/{podUid}\nfunc (fc *fcDisk) GetGlobalMapPath(spec *volume.Spec) (string, error) {\n\treturn fc.fcGlobalMapPath(spec)\n}","line":{"from":473,"to":477}} {"id":100012176,"name":"GetPodDeviceMapPath","signature":"func (fc *fcDisk) GetPodDeviceMapPath() (string, string)","file":"pkg/volume/fc/fc.go","code":"// GetPodDeviceMapPath returns pod device map path and volume name\n// path: pods/{podUid}/volumeDevices/kubernetes.io~fc\n// volumeName: pv0001\nfunc (fc *fcDisk) GetPodDeviceMapPath() (string, string) {\n\treturn fc.fcPodDeviceMapPath()\n}","line":{"from":479,"to":484}} {"id":100012177,"name":"getVolumeSource","signature":"func getVolumeSource(spec *volume.Spec) (*v1.FCVolumeSource, bool, error)","file":"pkg/volume/fc/fc.go","code":"func getVolumeSource(spec *volume.Spec) (*v1.FCVolumeSource, bool, error) {\n\t// fc volumes used directly in a pod have a ReadOnly flag set by the pod author.\n\t// fc volumes used as a PersistentVolume gets the ReadOnly flag indirectly through the persistent-claim volume used to mount the PV\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.FC != nil {\n\t\treturn spec.Volume.FC, spec.Volume.FC.ReadOnly, nil\n\t} else if spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.FC != nil {\n\t\treturn spec.PersistentVolume.Spec.FC, spec.ReadOnly, nil\n\t}\n\n\treturn nil, false, fmt.Errorf(\"Spec does not reference a FibreChannel volume type\")\n}","line":{"from":486,"to":497}} {"id":100012178,"name":"createPersistentVolumeFromFCVolumeSource","signature":"func createPersistentVolumeFromFCVolumeSource(volumeName string, fc v1.FCVolumeSource) *v1.PersistentVolume","file":"pkg/volume/fc/fc.go","code":"func createPersistentVolumeFromFCVolumeSource(volumeName string, fc v1.FCVolumeSource) *v1.PersistentVolume {\n\tblock := v1.PersistentVolumeBlock\n\treturn \u0026v1.PersistentVolume{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: volumeName,\n\t\t},\n\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\tPersistentVolumeSource: v1.PersistentVolumeSource{\n\t\t\t\tFC: \u0026fc,\n\t\t\t},\n\t\t\tVolumeMode: \u0026block,\n\t\t},\n\t}\n}","line":{"from":499,"to":512}} {"id":100012179,"name":"getWwnsLunWwids","signature":"func getWwnsLunWwids(fc *v1.FCVolumeSource) ([]string, string, []string, error)","file":"pkg/volume/fc/fc.go","code":"func getWwnsLunWwids(fc *v1.FCVolumeSource) ([]string, string, []string, error) {\n\tvar lun string\n\tvar wwids []string\n\tif fc.Lun != nil \u0026\u0026 len(fc.TargetWWNs) != 0 {\n\t\tlun = strconv.Itoa(int(*fc.Lun))\n\t\treturn fc.TargetWWNs, lun, wwids, nil\n\t}\n\tif len(fc.WWIDs) != 0 {\n\t\tfor _, wwid := range fc.WWIDs {\n\t\t\twwids = append(wwids, strings.Replace(wwid, \" \", \"_\", -1))\n\t\t}\n\t\treturn fc.TargetWWNs, lun, wwids, nil\n\t}\n\treturn nil, \"\", nil, fmt.Errorf(\"fc: no fc disk information found\")\n}","line":{"from":514,"to":528}} {"id":100012180,"name":"ReadDir","signature":"func (handler *osIOHandler) ReadDir(dirname string) ([]os.FileInfo, error)","file":"pkg/volume/fc/fc_util.go","code":"func (handler *osIOHandler) ReadDir(dirname string) ([]os.FileInfo, error) {\n\treturn ioutil.ReadDir(dirname)\n}","line":{"from":50,"to":52}} {"id":100012181,"name":"Lstat","signature":"func (handler *osIOHandler) Lstat(name string) (os.FileInfo, error)","file":"pkg/volume/fc/fc_util.go","code":"func (handler *osIOHandler) Lstat(name string) (os.FileInfo, error) {\n\treturn os.Lstat(name)\n}","line":{"from":53,"to":55}} {"id":100012182,"name":"EvalSymlinks","signature":"func (handler *osIOHandler) EvalSymlinks(path string) (string, error)","file":"pkg/volume/fc/fc_util.go","code":"func (handler *osIOHandler) EvalSymlinks(path string) (string, error) {\n\treturn filepath.EvalSymlinks(path)\n}","line":{"from":56,"to":58}} {"id":100012183,"name":"WriteFile","signature":"func (handler *osIOHandler) WriteFile(filename string, data []byte, perm os.FileMode) error","file":"pkg/volume/fc/fc_util.go","code":"func (handler *osIOHandler) WriteFile(filename string, data []byte, perm os.FileMode) error {\n\treturn ioutil.WriteFile(filename, data, perm)\n}","line":{"from":59,"to":61}} {"id":100012184,"name":"findDisk","signature":"func findDisk(wwn, lun string, io ioHandler, deviceUtil volumeutil.DeviceUtil) (string, string)","file":"pkg/volume/fc/fc_util.go","code":"// given a wwn and lun, find the device and associated devicemapper parent\nfunc findDisk(wwn, lun string, io ioHandler, deviceUtil volumeutil.DeviceUtil) (string, string) {\n\tfcPathExp := \"^(pci-.*-fc|fc)-0x\" + wwn + \"-lun-\" + lun + \"$\"\n\tr := regexp.MustCompile(fcPathExp)\n\tdevPath := byPath\n\tif dirs, err := io.ReadDir(devPath); err == nil {\n\t\tfor _, f := range dirs {\n\t\t\tname := f.Name()\n\t\t\tif r.MatchString(name) {\n\t\t\t\tif disk, err1 := io.EvalSymlinks(devPath + name); err1 == nil {\n\t\t\t\t\tdm := deviceUtil.FindMultipathDeviceForDevice(disk)\n\t\t\t\t\tklog.Infof(\"fc: find disk: %v, dm: %v, fc path: %v\", disk, dm, name)\n\t\t\t\t\treturn disk, dm\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", \"\"\n}","line":{"from":63,"to":81}} {"id":100012185,"name":"findDiskWWIDs","signature":"func findDiskWWIDs(wwid string, io ioHandler, deviceUtil volumeutil.DeviceUtil) (string, string)","file":"pkg/volume/fc/fc_util.go","code":"// given a wwid, find the device and associated devicemapper parent\nfunc findDiskWWIDs(wwid string, io ioHandler, deviceUtil volumeutil.DeviceUtil) (string, string) {\n\t// Example wwid format:\n\t// 3600508b400105e210000900000490000\n\t// \u003cVENDOR NAME\u003e \u003cIDENTIFIER NUMBER\u003e\n\t// Example of symlink under by-id:\n\t// /dev/by-id/scsi-3600508b400105e210000900000490000\n\t// /dev/by-id/scsi-\u003cVENDOR NAME\u003e_\u003cIDENTIFIER NUMBER\u003e\n\t// The wwid could contain white space and it will be replaced\n\t// underscore when wwid is exposed under /dev/by-id.\n\n\tfcPath := \"scsi-\" + wwid\n\tdevID := byID\n\tif dirs, err := io.ReadDir(devID); err == nil {\n\t\tfor _, f := range dirs {\n\t\t\tname := f.Name()\n\t\t\tif name == fcPath {\n\t\t\t\tdisk, err := io.EvalSymlinks(devID + name)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.V(2).Infof(\"fc: failed to find a corresponding disk from symlink[%s], error %v\", devID+name, err)\n\t\t\t\t\treturn \"\", \"\"\n\t\t\t\t}\n\t\t\t\tdm := deviceUtil.FindMultipathDeviceForDevice(disk)\n\t\t\t\tklog.Infof(\"fc: find disk: %v, dm: %v\", disk, dm)\n\t\t\t\treturn disk, dm\n\t\t\t}\n\t\t}\n\t}\n\tklog.V(2).Infof(\"fc: failed to find a disk [%s]\", devID+fcPath)\n\treturn \"\", \"\"\n}","line":{"from":83,"to":113}} {"id":100012186,"name":"flushDevice","signature":"func flushDevice(deviceName string, exec utilexec.Interface)","file":"pkg/volume/fc/fc_util.go","code":"// Flushes any outstanding I/O to the device\nfunc flushDevice(deviceName string, exec utilexec.Interface) {\n\tout, err := exec.Command(\"blockdev\", \"--flushbufs\", deviceName).CombinedOutput()\n\tif err != nil {\n\t\t// Ignore the error and continue deleting the device. There is will be no retry on error.\n\t\tklog.Warningf(\"Failed to flush device %s: %s\\n%s\", deviceName, err, string(out))\n\t}\n\tklog.V(4).Infof(\"Flushed device %s\", deviceName)\n}","line":{"from":115,"to":123}} {"id":100012187,"name":"removeFromScsiSubsystem","signature":"func removeFromScsiSubsystem(deviceName string, io ioHandler)","file":"pkg/volume/fc/fc_util.go","code":"// Removes a scsi device based upon /dev/sdX name\nfunc removeFromScsiSubsystem(deviceName string, io ioHandler) {\n\tfileName := \"/sys/block/\" + deviceName + \"/device/delete\"\n\tklog.V(4).Infof(\"fc: remove device from scsi-subsystem: path: %s\", fileName)\n\tdata := []byte(\"1\")\n\tio.WriteFile(fileName, data, 0666)\n}","line":{"from":125,"to":131}} {"id":100012188,"name":"scsiHostRescan","signature":"func scsiHostRescan(io ioHandler)","file":"pkg/volume/fc/fc_util.go","code":"// rescan scsi bus\nfunc scsiHostRescan(io ioHandler) {\n\tscsiPath := \"/sys/class/scsi_host/\"\n\tif dirs, err := io.ReadDir(scsiPath); err == nil {\n\t\tfor _, f := range dirs {\n\t\t\tname := scsiPath + f.Name() + \"/scan\"\n\t\t\tdata := []byte(\"- - -\")\n\t\t\tio.WriteFile(name, data, 0666)\n\t\t}\n\t}\n}","line":{"from":133,"to":143}} {"id":100012189,"name":"makePDNameInternal","signature":"func makePDNameInternal(host volume.VolumeHost, wwns []string, lun string, wwids []string) string","file":"pkg/volume/fc/fc_util.go","code":"// make a directory like /var/lib/kubelet/plugins/kubernetes.io/fc/target1-target2-lun-0\nfunc makePDNameInternal(host volume.VolumeHost, wwns []string, lun string, wwids []string) string {\n\tif len(wwns) != 0 {\n\t\tw := strings.Join(wwns, \"-\")\n\t\treturn filepath.Join(host.GetPluginDir(fcPluginName), w+\"-lun-\"+lun)\n\t}\n\treturn filepath.Join(host.GetPluginDir(fcPluginName), strings.Join(wwids, \"-\"))\n}","line":{"from":145,"to":152}} {"id":100012190,"name":"makeVDPDNameInternal","signature":"func makeVDPDNameInternal(host volume.VolumeHost, wwns []string, lun string, wwids []string) string","file":"pkg/volume/fc/fc_util.go","code":"// make a directory like /var/lib/kubelet/plugins/kubernetes.io/fc/volumeDevices/target-lun-0\nfunc makeVDPDNameInternal(host volume.VolumeHost, wwns []string, lun string, wwids []string) string {\n\tif len(wwns) != 0 {\n\t\tw := strings.Join(wwns, \"-\")\n\t\treturn filepath.Join(host.GetVolumeDevicePluginDir(fcPluginName), w+\"-lun-\"+lun)\n\t}\n\treturn filepath.Join(host.GetVolumeDevicePluginDir(fcPluginName), strings.Join(wwids, \"-\"))\n}","line":{"from":154,"to":161}} {"id":100012191,"name":"parsePDName","signature":"func parsePDName(path string) (wwns []string, lun int32, wwids []string, err error)","file":"pkg/volume/fc/fc_util.go","code":"func parsePDName(path string) (wwns []string, lun int32, wwids []string, err error) {\n\t// parse directory name created by makePDNameInternal or makeVDPDNameInternal\n\tdirname := filepath.Base(path)\n\tcomponents := strings.Split(dirname, \"-\")\n\tl := len(components)\n\tif l == 1 {\n\t\t// No '-', it must be single WWID\n\t\treturn nil, 0, components, nil\n\t}\n\tif components[l-2] == \"lun\" {\n\t\t// it has -lun-, it's list of WWNs + lun number as the last component\n\t\tif l == 2 {\n\t\t\treturn nil, 0, nil, fmt.Errorf(\"no wwn in: %s\", dirname)\n\t\t}\n\t\tlun, err := strconv.Atoi(components[l-1])\n\t\tif err != nil {\n\t\t\treturn nil, 0, nil, err\n\t\t}\n\n\t\treturn components[:l-2], int32(lun), nil, nil\n\t}\n\t// no -lun-, it's just list of WWIDs\n\treturn nil, 0, components, nil\n}","line":{"from":163,"to":186}} {"id":100012192,"name":"MakeGlobalPDName","signature":"func (util *fcUtil) MakeGlobalPDName(fc fcDisk) string","file":"pkg/volume/fc/fc_util.go","code":"func (util *fcUtil) MakeGlobalPDName(fc fcDisk) string {\n\treturn makePDNameInternal(fc.plugin.host, fc.wwns, fc.lun, fc.wwids)\n}","line":{"from":190,"to":192}} {"id":100012193,"name":"MakeGlobalVDPDName","signature":"func (util *fcUtil) MakeGlobalVDPDName(fc fcDisk) string","file":"pkg/volume/fc/fc_util.go","code":"// Global volume device plugin dir\nfunc (util *fcUtil) MakeGlobalVDPDName(fc fcDisk) string {\n\treturn makeVDPDNameInternal(fc.plugin.host, fc.wwns, fc.lun, fc.wwids)\n}","line":{"from":194,"to":197}} {"id":100012194,"name":"searchDisk","signature":"func searchDisk(b fcDiskMounter) (string, error)","file":"pkg/volume/fc/fc_util.go","code":"func searchDisk(b fcDiskMounter) (string, error) {\n\tvar diskIDs []string\n\tvar disk string\n\tvar dm string\n\tio := b.io\n\twwids := b.wwids\n\twwns := b.wwns\n\tlun := b.lun\n\n\tif len(wwns) != 0 {\n\t\tdiskIDs = wwns\n\t} else {\n\t\tdiskIDs = wwids\n\t}\n\n\trescanned := false\n\t// two-phase search:\n\t// first phase, search existing device path, if a multipath dm is found, exit loop\n\t// otherwise, in second phase, rescan scsi bus and search again, return with any findings\n\tfor true {\n\t\tfor _, diskID := range diskIDs {\n\t\t\tif len(wwns) != 0 {\n\t\t\t\tdisk, dm = findDisk(diskID, lun, io, b.deviceUtil)\n\t\t\t} else {\n\t\t\t\tdisk, dm = findDiskWWIDs(diskID, io, b.deviceUtil)\n\t\t\t}\n\t\t\t// if multipath device is found, break\n\t\t\tif dm != \"\" {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\t// if a dm is found, exit loop\n\t\tif rescanned || dm != \"\" {\n\t\t\tbreak\n\t\t}\n\t\t// rescan and search again\n\t\t// rescan scsi bus\n\t\tscsiHostRescan(io)\n\t\trescanned = true\n\t}\n\t// if no disk matches input wwn and lun, exit\n\tif disk == \"\" \u0026\u0026 dm == \"\" {\n\t\treturn \"\", fmt.Errorf(\"no fc disk found\")\n\t}\n\n\t// if multipath devicemapper device is found, use it; otherwise use raw disk\n\tif dm != \"\" {\n\t\treturn dm, nil\n\t}\n\treturn disk, nil\n}","line":{"from":199,"to":249}} {"id":100012195,"name":"AttachDisk","signature":"func (util *fcUtil) AttachDisk(b fcDiskMounter) (string, error)","file":"pkg/volume/fc/fc_util.go","code":"func (util *fcUtil) AttachDisk(b fcDiskMounter) (string, error) {\n\tdevicePath, err := searchDisk(b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\texists, err := mount.PathExists(devicePath)\n\tif exists \u0026\u0026 err == nil {\n\t\treturn devicePath, nil\n\t}\n\tif exists == false {\n\t\treturn \"\", fmt.Errorf(\"device %s does not exist\", devicePath)\n\t} else {\n\t\treturn \"\", err\n\t}\n}","line":{"from":251,"to":266}} {"id":100012196,"name":"DetachDisk","signature":"func (util *fcUtil) DetachDisk(c fcDiskUnmounter, devicePath string) error","file":"pkg/volume/fc/fc_util.go","code":"// DetachDisk removes scsi device file such as /dev/sdX from the node.\nfunc (util *fcUtil) DetachDisk(c fcDiskUnmounter, devicePath string) error {\n\tvar devices []string\n\t// devicePath might be like /dev/mapper/mpathX. Find destination.\n\tdstPath, err := c.io.EvalSymlinks(devicePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Find slave\n\tif strings.HasPrefix(dstPath, \"/dev/dm-\") {\n\t\tdevices = c.deviceUtil.FindSlaveDevicesOnMultipath(dstPath)\n\t\tif err := util.deleteMultipathDevice(c.exec, dstPath); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t// Add single devicepath to devices\n\t\tdevices = append(devices, dstPath)\n\t}\n\tklog.V(4).Infof(\"fc: DetachDisk devicePath: %v, dstPath: %v, devices: %v\", devicePath, dstPath, devices)\n\tvar lastErr error\n\tfor _, device := range devices {\n\t\terr := util.detachFCDisk(c.io, c.exec, device)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"fc: detachFCDisk failed. device: %v err: %v\", device, err)\n\t\t\tlastErr = fmt.Errorf(\"fc: detachFCDisk failed. device: %v err: %v\", device, err)\n\t\t}\n\t}\n\tif lastErr != nil {\n\t\tklog.Errorf(\"fc: last error occurred during detach disk:\\n%v\", lastErr)\n\t\treturn lastErr\n\t}\n\treturn nil\n}","line":{"from":268,"to":300}} {"id":100012197,"name":"detachFCDisk","signature":"func (util *fcUtil) detachFCDisk(io ioHandler, exec utilexec.Interface, devicePath string) error","file":"pkg/volume/fc/fc_util.go","code":"// detachFCDisk removes scsi device file such as /dev/sdX from the node.\nfunc (util *fcUtil) detachFCDisk(io ioHandler, exec utilexec.Interface, devicePath string) error {\n\t// Remove scsi device from the node.\n\tif !strings.HasPrefix(devicePath, \"/dev/\") {\n\t\treturn fmt.Errorf(\"fc detach disk: invalid device name: %s\", devicePath)\n\t}\n\tflushDevice(devicePath, exec)\n\tarr := strings.Split(devicePath, \"/\")\n\tdev := arr[len(arr)-1]\n\tremoveFromScsiSubsystem(dev, io)\n\treturn nil\n}","line":{"from":302,"to":313}} {"id":100012198,"name":"DetachBlockFCDisk","signature":"func (util *fcUtil) DetachBlockFCDisk(c fcDiskUnmapper, mapPath, devicePath string) error","file":"pkg/volume/fc/fc_util.go","code":"// DetachBlockFCDisk detaches a volume from kubelet node, removes scsi device file\n// such as /dev/sdX from the node, and then removes loopback for the scsi device.\nfunc (util *fcUtil) DetachBlockFCDisk(c fcDiskUnmapper, mapPath, devicePath string) error {\n\t// Check if devicePath is valid\n\tif len(devicePath) != 0 {\n\t\tif pathExists, pathErr := checkPathExists(devicePath); !pathExists || pathErr != nil {\n\t\t\treturn pathErr\n\t\t}\n\t} else {\n\t\t// TODO: FC plugin can't obtain the devicePath from kubelet because devicePath\n\t\t// in volume object isn't updated when volume is attached to kubelet node.\n\t\tklog.Infof(\"fc: devicePath is empty. Try to retrieve FC configuration from global map path: %v\", mapPath)\n\t}\n\n\t// Check if global map path is valid\n\t// global map path examples:\n\t// wwn+lun: plugins/kubernetes.io/fc/volumeDevices/50060e801049cfd1-lun-0/\n\t// wwid: plugins/kubernetes.io/fc/volumeDevices/3600508b400105e210000900000490000/\n\tif pathExists, pathErr := checkPathExists(mapPath); !pathExists || pathErr != nil {\n\t\treturn pathErr\n\t}\n\n\t// Retrieve volume plugin dependent path like '50060e801049cfd1-lun-0' from global map path\n\tarr := strings.Split(mapPath, \"/\")\n\tif len(arr) \u003c 1 {\n\t\treturn fmt.Errorf(\"failed to retrieve volume plugin information from global map path: %v\", mapPath)\n\t}\n\tvolumeInfo := arr[len(arr)-1]\n\n\t// Search symbolic link which matches volumeInfo under /dev/disk/by-path or /dev/disk/by-id\n\t// then find destination device path from the link\n\tsearchPath := byID\n\tif strings.Contains(volumeInfo, \"-lun-\") {\n\t\tsearchPath = byPath\n\t}\n\tfis, err := ioutil.ReadDir(searchPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, fi := range fis {\n\t\tif strings.Contains(fi.Name(), volumeInfo) {\n\t\t\tdevicePath = filepath.Join(searchPath, fi.Name())\n\t\t\tklog.V(5).Infof(\"fc: updated devicePath: %s\", devicePath)\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(devicePath) == 0 {\n\t\treturn fmt.Errorf(\"fc: failed to find corresponding device from searchPath: %v\", searchPath)\n\t}\n\tdstPath, err := c.io.EvalSymlinks(devicePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tklog.V(4).Infof(\"fc: find destination device path from symlink: %v\", dstPath)\n\n\tvar devices []string\n\tdm := c.deviceUtil.FindMultipathDeviceForDevice(dstPath)\n\tif len(dm) != 0 {\n\t\tdstPath = dm\n\t}\n\n\t// Detach volume from kubelet node\n\tif len(dm) != 0 {\n\t\t// Find all devices which are managed by multipath\n\t\tdevices = c.deviceUtil.FindSlaveDevicesOnMultipath(dm)\n\t\tif err := util.deleteMultipathDevice(c.exec, dm); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t// Add single device path to devices\n\t\tdevices = append(devices, dstPath)\n\t}\n\tvar lastErr error\n\tfor _, device := range devices {\n\t\terr = util.detachFCDisk(c.io, c.exec, device)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"fc: detachFCDisk failed. device: %v err: %v\", device, err)\n\t\t\tlastErr = fmt.Errorf(\"fc: detachFCDisk failed. device: %v err: %v\", device, err)\n\t\t}\n\t}\n\tif lastErr != nil {\n\t\tklog.Errorf(\"fc: last error occurred during detach disk:\\n%v\", lastErr)\n\t\treturn lastErr\n\t}\n\treturn nil\n}","line":{"from":315,"to":400}} {"id":100012199,"name":"deleteMultipathDevice","signature":"func (util *fcUtil) deleteMultipathDevice(exec utilexec.Interface, dmDevice string) error","file":"pkg/volume/fc/fc_util.go","code":"func (util *fcUtil) deleteMultipathDevice(exec utilexec.Interface, dmDevice string) error {\n\tout, err := exec.Command(\"multipath\", \"-f\", dmDevice).CombinedOutput()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to flush multipath device %s: %s\\n%s\", dmDevice, err, string(out))\n\t}\n\tklog.V(4).Infof(\"Flushed multipath device: %s\", dmDevice)\n\treturn nil\n}","line":{"from":402,"to":409}} {"id":100012200,"name":"checkPathExists","signature":"func checkPathExists(path string) (bool, error)","file":"pkg/volume/fc/fc_util.go","code":"func checkPathExists(path string) (bool, error) {\n\tif pathExists, pathErr := mount.PathExists(path); pathErr != nil {\n\t\treturn pathExists, fmt.Errorf(\"error checking if path exists: %w\", pathErr)\n\t} else if !pathExists {\n\t\tklog.Warningf(\"Warning: Unmap skipped because path does not exist: %v\", path)\n\t\treturn pathExists, nil\n\t}\n\treturn true, nil\n}","line":{"from":411,"to":419}} {"id":100012201,"name":"Attach","signature":"func (a *attacherDefaults) Attach(spec *volume.Spec, hostName types.NodeName) (string, error)","file":"pkg/volume/flexvolume/attacher-defaults.go","code":"// Attach is part of the volume.Attacher interface\nfunc (a *attacherDefaults) Attach(spec *volume.Spec, hostName types.NodeName) (string, error) {\n\tklog.Warning(logPrefix(a.plugin.flexVolumePlugin), \"using default Attach for volume \", spec.Name(), \", host \", hostName)\n\treturn \"\", nil\n}","line":{"from":31,"to":35}} {"id":100012202,"name":"WaitForAttach","signature":"func (a *attacherDefaults) WaitForAttach(spec *volume.Spec, devicePath string, timeout time.Duration) (string, error)","file":"pkg/volume/flexvolume/attacher-defaults.go","code":"// WaitForAttach is part of the volume.Attacher interface\nfunc (a *attacherDefaults) WaitForAttach(spec *volume.Spec, devicePath string, timeout time.Duration) (string, error) {\n\tklog.Warning(logPrefix(a.plugin.flexVolumePlugin), \"using default WaitForAttach for volume \", spec.Name(), \", device \", devicePath)\n\treturn devicePath, nil\n}","line":{"from":37,"to":41}} {"id":100012203,"name":"GetDeviceMountPath","signature":"func (a *attacherDefaults) GetDeviceMountPath(spec *volume.Spec, mountsDir string) (string, error)","file":"pkg/volume/flexvolume/attacher-defaults.go","code":"// GetDeviceMountPath is part of the volume.Attacher interface\nfunc (a *attacherDefaults) GetDeviceMountPath(spec *volume.Spec, mountsDir string) (string, error) {\n\treturn a.plugin.getDeviceMountPath(spec)\n}","line":{"from":43,"to":46}} {"id":100012204,"name":"MountDevice","signature":"func (a *attacherDefaults) MountDevice(spec *volume.Spec, devicePath string, deviceMountPath string, mounter mount.Interface) error","file":"pkg/volume/flexvolume/attacher-defaults.go","code":"// MountDevice is part of the volume.Attacher interface\nfunc (a *attacherDefaults) MountDevice(spec *volume.Spec, devicePath string, deviceMountPath string, mounter mount.Interface) error {\n\tklog.Warning(logPrefix(a.plugin.flexVolumePlugin), \"using default MountDevice for volume \", spec.Name(), \", device \", devicePath, \", deviceMountPath \", deviceMountPath)\n\n\tvolSourceFSType, err := getFSType(spec)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treadOnly, err := getReadOnly(spec)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\toptions := make([]string, 0)\n\n\tif readOnly {\n\t\toptions = append(options, \"ro\")\n\t} else {\n\t\toptions = append(options, \"rw\")\n\t}\n\n\tdiskMounter := \u0026mount.SafeFormatAndMount{Interface: mounter, Exec: a.plugin.host.GetExec(a.plugin.GetPluginName())}\n\n\treturn diskMounter.FormatAndMount(devicePath, deviceMountPath, volSourceFSType, options)\n}","line":{"from":48,"to":73}} {"id":100012205,"name":"Attach","signature":"func (a *flexVolumeAttacher) Attach(spec *volume.Spec, hostName types.NodeName) (string, error)","file":"pkg/volume/flexvolume/attacher.go","code":"// Attach is part of the volume.Attacher interface\nfunc (a *flexVolumeAttacher) Attach(spec *volume.Spec, hostName types.NodeName) (string, error) {\n\n\tcall := a.plugin.NewDriverCall(attachCmd)\n\tcall.AppendSpec(spec, a.plugin.host, nil)\n\tcall.Append(string(hostName))\n\n\tstatus, err := call.Run()\n\tif isCmdNotSupportedErr(err) {\n\t\treturn (*attacherDefaults)(a).Attach(spec, hostName)\n\t} else if err != nil {\n\t\treturn \"\", err\n\t}\n\treturn status.DevicePath, err\n}","line":{"from":36,"to":50}} {"id":100012206,"name":"WaitForAttach","signature":"func (a *flexVolumeAttacher) WaitForAttach(spec *volume.Spec, devicePath string, _ *v1.Pod, timeout time.Duration) (string, error)","file":"pkg/volume/flexvolume/attacher.go","code":"// WaitForAttach is part of the volume.Attacher interface\nfunc (a *flexVolumeAttacher) WaitForAttach(spec *volume.Spec, devicePath string, _ *v1.Pod, timeout time.Duration) (string, error) {\n\tcall := a.plugin.NewDriverCallWithTimeout(waitForAttachCmd, timeout)\n\tcall.Append(devicePath)\n\tcall.AppendSpec(spec, a.plugin.host, nil)\n\n\tstatus, err := call.Run()\n\tif isCmdNotSupportedErr(err) {\n\t\treturn (*attacherDefaults)(a).WaitForAttach(spec, devicePath, timeout)\n\t} else if err != nil {\n\t\treturn \"\", err\n\t}\n\treturn status.DevicePath, nil\n}","line":{"from":52,"to":65}} {"id":100012207,"name":"GetDeviceMountPath","signature":"func (a *flexVolumeAttacher) GetDeviceMountPath(spec *volume.Spec) (string, error)","file":"pkg/volume/flexvolume/attacher.go","code":"// GetDeviceMountPath is part of the volume.Attacher interface\nfunc (a *flexVolumeAttacher) GetDeviceMountPath(spec *volume.Spec) (string, error) {\n\treturn a.plugin.getDeviceMountPath(spec)\n}","line":{"from":67,"to":70}} {"id":100012208,"name":"MountDevice","signature":"func (a *flexVolumeAttacher) MountDevice(spec *volume.Spec, devicePath string, deviceMountPath string, _ volume.DeviceMounterArgs) error","file":"pkg/volume/flexvolume/attacher.go","code":"// MountDevice is part of the volume.Attacher interface\nfunc (a *flexVolumeAttacher) MountDevice(spec *volume.Spec, devicePath string, deviceMountPath string, _ volume.DeviceMounterArgs) error {\n\t// Mount only once.\n\talreadyMounted, err := prepareForMount(a.plugin.host.GetMounter(a.plugin.GetPluginName()), deviceMountPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif alreadyMounted {\n\t\treturn nil\n\t}\n\n\tcall := a.plugin.NewDriverCall(mountDeviceCmd)\n\tcall.Append(deviceMountPath)\n\tcall.Append(devicePath)\n\tcall.AppendSpec(spec, a.plugin.host, nil)\n\n\t_, err = call.Run()\n\tif isCmdNotSupportedErr(err) {\n\t\t// Devicepath is empty if the plugin does not support attach calls. Ignore mountDevice calls if the\n\t\t// plugin does not implement attach interface.\n\t\tif devicePath != \"\" {\n\t\t\treturn (*attacherDefaults)(a).MountDevice(spec, devicePath, deviceMountPath, a.plugin.host.GetMounter(a.plugin.GetPluginName()))\n\t\t}\n\t\treturn nil\n\t}\n\treturn err\n}","line":{"from":72,"to":98}} {"id":100012209,"name":"VolumesAreAttached","signature":"func (a *flexVolumeAttacher) VolumesAreAttached(specs []*volume.Spec, nodeName types.NodeName) (map[*volume.Spec]bool, error)","file":"pkg/volume/flexvolume/attacher.go","code":"func (a *flexVolumeAttacher) VolumesAreAttached(specs []*volume.Spec, nodeName types.NodeName) (map[*volume.Spec]bool, error) {\n\tvolumesAttachedCheck := make(map[*volume.Spec]bool)\n\tfor _, spec := range specs {\n\t\tvolumesAttachedCheck[spec] = true\n\n\t\tcall := a.plugin.NewDriverCall(isAttached)\n\t\tcall.AppendSpec(spec, a.plugin.host, nil)\n\t\tcall.Append(string(nodeName))\n\n\t\tstatus, err := call.Run()\n\t\tif isCmdNotSupportedErr(err) {\n\t\t\treturn nil, nil\n\t\t} else if err == nil {\n\t\t\tif !status.Attached {\n\t\t\t\tvolumesAttachedCheck[spec] = false\n\t\t\t\tklog.V(2).Infof(\"VolumesAreAttached: check volume (%q) is no longer attached\", spec.Name())\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn volumesAttachedCheck, nil\n}","line":{"from":100,"to":122}} {"id":100012210,"name":"Detach","signature":"func (d *detacherDefaults) Detach(volumeName string, hostName types.NodeName) error","file":"pkg/volume/flexvolume/detacher-defaults.go","code":"// Detach is part of the volume.Detacher interface.\nfunc (d *detacherDefaults) Detach(volumeName string, hostName types.NodeName) error {\n\tklog.Warning(logPrefix(d.plugin.flexVolumePlugin), \"using default Detach for volume \", volumeName, \", host \", hostName)\n\treturn nil\n}","line":{"from":30,"to":34}} {"id":100012211,"name":"WaitForDetach","signature":"func (d *detacherDefaults) WaitForDetach(devicePath string, timeout time.Duration) error","file":"pkg/volume/flexvolume/detacher-defaults.go","code":"// WaitForDetach is part of the volume.Detacher interface.\nfunc (d *detacherDefaults) WaitForDetach(devicePath string, timeout time.Duration) error {\n\tklog.Warning(logPrefix(d.plugin.flexVolumePlugin), \"using default WaitForDetach for device \", devicePath)\n\treturn nil\n}","line":{"from":36,"to":40}} {"id":100012212,"name":"UnmountDevice","signature":"func (d *detacherDefaults) UnmountDevice(deviceMountPath string) error","file":"pkg/volume/flexvolume/detacher-defaults.go","code":"// UnmountDevice is part of the volume.Detacher interface.\nfunc (d *detacherDefaults) UnmountDevice(deviceMountPath string) error {\n\tklog.Warning(logPrefix(d.plugin.flexVolumePlugin), \"using default UnmountDevice for device mount path \", deviceMountPath)\n\treturn mount.CleanupMountPoint(deviceMountPath, d.plugin.host.GetMounter(d.plugin.GetPluginName()), false)\n}","line":{"from":42,"to":46}} {"id":100012213,"name":"Detach","signature":"func (d *flexVolumeDetacher) Detach(volumeName string, hostName types.NodeName) error","file":"pkg/volume/flexvolume/detacher.go","code":"// Detach is part of the volume.Detacher interface.\nfunc (d *flexVolumeDetacher) Detach(volumeName string, hostName types.NodeName) error {\n\n\tcall := d.plugin.NewDriverCall(detachCmd)\n\tcall.Append(volumeName)\n\tcall.Append(string(hostName))\n\n\t_, err := call.Run()\n\tif isCmdNotSupportedErr(err) {\n\t\treturn (*detacherDefaults)(d).Detach(volumeName, hostName)\n\t}\n\treturn err\n}","line":{"from":38,"to":50}} {"id":100012214,"name":"UnmountDevice","signature":"func (d *flexVolumeDetacher) UnmountDevice(deviceMountPath string) error","file":"pkg/volume/flexvolume/detacher.go","code":"// UnmountDevice is part of the volume.Detacher interface.\nfunc (d *flexVolumeDetacher) UnmountDevice(deviceMountPath string) error {\n\n\tpathExists, pathErr := mount.PathExists(deviceMountPath)\n\tif !pathExists {\n\t\tklog.Warningf(\"Warning: Unmount skipped because path does not exist: %v\", deviceMountPath)\n\t\treturn nil\n\t}\n\tif pathErr != nil \u0026\u0026 !mount.IsCorruptedMnt(pathErr) {\n\t\treturn fmt.Errorf(\"error checking path: %w\", pathErr)\n\t}\n\n\tnotmnt, err := isNotMounted(d.plugin.host.GetMounter(d.plugin.GetPluginName()), deviceMountPath)\n\tif err != nil {\n\t\tif mount.IsCorruptedMnt(err) {\n\t\t\tnotmnt = false // Corrupted error is assumed to be mounted.\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif notmnt {\n\t\tklog.Warningf(\"Warning: Path: %v already unmounted\", deviceMountPath)\n\t} else {\n\t\tcall := d.plugin.NewDriverCall(unmountDeviceCmd)\n\t\tcall.Append(deviceMountPath)\n\n\t\t_, err := call.Run()\n\t\tif isCmdNotSupportedErr(err) {\n\t\t\terr = (*detacherDefaults)(d).UnmountDevice(deviceMountPath)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Flexvolume driver may remove the directory. Ignore if it does.\n\tif pathExists, pathErr := mount.PathExists(deviceMountPath); pathErr != nil {\n\t\treturn fmt.Errorf(\"error checking if path exists: %w\", pathErr)\n\t} else if !pathExists {\n\t\treturn nil\n\t}\n\treturn os.Remove(deviceMountPath)\n}","line":{"from":52,"to":95}} {"id":100012215,"name":"NewDriverCall","signature":"func (plugin *flexVolumePlugin) NewDriverCall(command string) *DriverCall","file":"pkg/volume/flexvolume/driver-call.go","code":"func (plugin *flexVolumePlugin) NewDriverCall(command string) *DriverCall {\n\treturn plugin.NewDriverCallWithTimeout(command, 0)\n}","line":{"from":84,"to":86}} {"id":100012216,"name":"NewDriverCallWithTimeout","signature":"func (plugin *flexVolumePlugin) NewDriverCallWithTimeout(command string, timeout time.Duration) *DriverCall","file":"pkg/volume/flexvolume/driver-call.go","code":"func (plugin *flexVolumePlugin) NewDriverCallWithTimeout(command string, timeout time.Duration) *DriverCall {\n\treturn \u0026DriverCall{\n\t\tCommand: command,\n\t\tTimeout: timeout,\n\t\tplugin: plugin,\n\t\targs: []string{command},\n\t}\n}","line":{"from":88,"to":95}} {"id":100012217,"name":"Append","signature":"func (dc *DriverCall) Append(arg string)","file":"pkg/volume/flexvolume/driver-call.go","code":"// Append appends arg into driver call argument list\nfunc (dc *DriverCall) Append(arg string) {\n\tdc.args = append(dc.args, arg)\n}","line":{"from":97,"to":100}} {"id":100012218,"name":"AppendSpec","signature":"func (dc *DriverCall) AppendSpec(spec *volume.Spec, host volume.VolumeHost, extraOptions map[string]string) error","file":"pkg/volume/flexvolume/driver-call.go","code":"// AppendSpec appends volume spec to driver call argument list\nfunc (dc *DriverCall) AppendSpec(spec *volume.Spec, host volume.VolumeHost, extraOptions map[string]string) error {\n\toptionsForDriver, err := NewOptionsForDriver(spec, host, extraOptions)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tjsonBytes, err := json.Marshal(optionsForDriver)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal spec, error: %s\", err.Error())\n\t}\n\n\tdc.Append(string(jsonBytes))\n\treturn nil\n}","line":{"from":102,"to":116}} {"id":100012219,"name":"Run","signature":"func (dc *DriverCall) Run() (*DriverStatus, error)","file":"pkg/volume/flexvolume/driver-call.go","code":"// Run executes the driver call\nfunc (dc *DriverCall) Run() (*DriverStatus, error) {\n\tif dc.plugin.isUnsupported(dc.Command) {\n\t\treturn nil, errors.New(StatusNotSupported)\n\t}\n\texecPath := dc.plugin.getExecutable()\n\n\tcmd := dc.plugin.runner.Command(execPath, dc.args...)\n\n\ttimeout := false\n\tif dc.Timeout \u003e 0 {\n\t\ttimer := time.AfterFunc(dc.Timeout, func() {\n\t\t\ttimeout = true\n\t\t\tcmd.Stop()\n\t\t})\n\t\tdefer timer.Stop()\n\t}\n\n\toutput, execErr := cmd.CombinedOutput()\n\tif execErr != nil {\n\t\tif timeout {\n\t\t\treturn nil, errTimeout\n\t\t}\n\t\t_, err := handleCmdResponse(dc.Command, output)\n\t\tif err == nil {\n\t\t\tklog.Errorf(\"FlexVolume: driver bug: %s: exec error (%s) but no error in response.\", execPath, execErr)\n\t\t\treturn nil, execErr\n\t\t}\n\t\tif isCmdNotSupportedErr(err) {\n\t\t\tdc.plugin.unsupported(dc.Command)\n\t\t} else {\n\t\t\tklog.Warningf(\"FlexVolume: driver call failed: executable: %s, args: %s, error: %s, output: %q\", execPath, dc.args, execErr.Error(), output)\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tstatus, err := handleCmdResponse(dc.Command, output)\n\tif err != nil {\n\t\tif isCmdNotSupportedErr(err) {\n\t\t\tdc.plugin.unsupported(dc.Command)\n\t\t}\n\t\treturn nil, err\n\t}\n\n\treturn status, nil\n}","line":{"from":118,"to":163}} {"id":100012220,"name":"NewOptionsForDriver","signature":"func NewOptionsForDriver(spec *volume.Spec, host volume.VolumeHost, extraOptions map[string]string) (OptionsForDriver, error)","file":"pkg/volume/flexvolume/driver-call.go","code":"// NewOptionsForDriver create driver options given volume spec\nfunc NewOptionsForDriver(spec *volume.Spec, host volume.VolumeHost, extraOptions map[string]string) (OptionsForDriver, error) {\n\n\tvolSourceFSType, err := getFSType(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treadOnly, err := getReadOnly(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvolSourceOptions, err := getOptions(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\toptions := map[string]string{}\n\n\toptions[optionFSType] = volSourceFSType\n\n\tif readOnly {\n\t\toptions[optionReadWrite] = \"ro\"\n\t} else {\n\t\toptions[optionReadWrite] = \"rw\"\n\t}\n\n\toptions[optionPVorVolumeName] = spec.Name()\n\n\tfor key, value := range extraOptions {\n\t\toptions[key] = value\n\t}\n\n\tfor key, value := range volSourceOptions {\n\t\toptions[key] = value\n\t}\n\n\treturn OptionsForDriver(options), nil\n}","line":{"from":168,"to":207}} {"id":100012221,"name":"defaultCapabilities","signature":"func defaultCapabilities() *DriverCapabilities","file":"pkg/volume/flexvolume/driver-call.go","code":"func defaultCapabilities() *DriverCapabilities {\n\treturn \u0026DriverCapabilities{\n\t\tAttach: true,\n\t\tSELinuxRelabel: true,\n\t\tSupportsMetrics: false,\n\t\tFSGroup: true,\n\t\tRequiresFSResize: true,\n\t}\n}","line":{"from":239,"to":247}} {"id":100012222,"name":"isCmdNotSupportedErr","signature":"func isCmdNotSupportedErr(err error) bool","file":"pkg/volume/flexvolume/driver-call.go","code":"// isCmdNotSupportedErr checks if the error corresponds to command not supported by\n// driver.\nfunc isCmdNotSupportedErr(err error) bool {\n\treturn err != nil \u0026\u0026 err.Error() == StatusNotSupported\n}","line":{"from":249,"to":253}} {"id":100012223,"name":"handleCmdResponse","signature":"func handleCmdResponse(cmd string, output []byte) (*DriverStatus, error)","file":"pkg/volume/flexvolume/driver-call.go","code":"// handleCmdResponse processes the command output and returns the appropriate\n// error code or message.\nfunc handleCmdResponse(cmd string, output []byte) (*DriverStatus, error) {\n\tstatus := DriverStatus{\n\t\tCapabilities: defaultCapabilities(),\n\t}\n\tif err := json.Unmarshal(output, \u0026status); err != nil {\n\t\tklog.Errorf(\"Failed to unmarshal output for command: %s, output: %q, error: %s\", cmd, string(output), err.Error())\n\t\treturn nil, err\n\t} else if status.Status == StatusNotSupported {\n\t\tklog.V(5).Infof(\"%s command is not supported by the driver\", cmd)\n\t\treturn nil, errors.New(status.Status)\n\t} else if status.Status != StatusSuccess {\n\t\terrMsg := fmt.Sprintf(\"%s command failed, status: %s, reason: %s\", cmd, status.Status, status.Message)\n\t\tklog.Errorf(errMsg)\n\t\treturn nil, fmt.Errorf(\"%s\", errMsg)\n\t}\n\n\treturn \u0026status, nil\n}","line":{"from":255,"to":274}} {"id":100012224,"name":"newExpanderDefaults","signature":"func newExpanderDefaults(plugin *flexVolumePlugin) *expanderDefaults","file":"pkg/volume/flexvolume/expander-defaults.go","code":"func newExpanderDefaults(plugin *flexVolumePlugin) *expanderDefaults {\n\treturn \u0026expanderDefaults{plugin}\n}","line":{"from":32,"to":34}} {"id":100012225,"name":"ExpandVolumeDevice","signature":"func (e *expanderDefaults) ExpandVolumeDevice(spec *volume.Spec, newSize resource.Quantity, oldSize resource.Quantity) (resource.Quantity, error)","file":"pkg/volume/flexvolume/expander-defaults.go","code":"func (e *expanderDefaults) ExpandVolumeDevice(spec *volume.Spec, newSize resource.Quantity, oldSize resource.Quantity) (resource.Quantity, error) {\n\tklog.Warning(logPrefix(e.plugin), \"using default expand for volume \", spec.Name(), \", to size \", newSize, \" from \", oldSize)\n\treturn newSize, nil\n}","line":{"from":36,"to":39}} {"id":100012226,"name":"NodeExpand","signature":"func (e *expanderDefaults) NodeExpand(rsOpt volume.NodeResizeOptions) (bool, error)","file":"pkg/volume/flexvolume/expander-defaults.go","code":"// the defaults for NodeExpand return a generic resize indicator that will trigger the operation executor to go ahead with\n// generic filesystem resize\nfunc (e *expanderDefaults) NodeExpand(rsOpt volume.NodeResizeOptions) (bool, error) {\n\tklog.Warning(logPrefix(e.plugin), \"using default filesystem resize for volume \", rsOpt.VolumeSpec.Name(), \", at \", rsOpt.DevicePath)\n\tfsVolume, err := util.CheckVolumeModeFilesystem(rsOpt.VolumeSpec)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"error checking VolumeMode: %v\", err)\n\t}\n\t// if volume is not a fs file system, there is nothing for us to do here.\n\tif !fsVolume {\n\t\treturn true, nil\n\t}\n\n\t_, err = util.GenericResizeFS(e.plugin.host, e.plugin.GetPluginName(), rsOpt.DevicePath, rsOpt.DeviceMountPath)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn true, nil\n}","line":{"from":41,"to":59}} {"id":100012227,"name":"ExpandVolumeDevice","signature":"func (plugin *flexVolumePlugin) ExpandVolumeDevice(spec *volume.Spec, newSize resource.Quantity, oldSize resource.Quantity) (resource.Quantity, error)","file":"pkg/volume/flexvolume/expander.go","code":"func (plugin *flexVolumePlugin) ExpandVolumeDevice(spec *volume.Spec, newSize resource.Quantity, oldSize resource.Quantity) (resource.Quantity, error) {\n\tcall := plugin.NewDriverCall(expandVolumeCmd)\n\tcall.AppendSpec(spec, plugin.host, nil)\n\n\tdevicePath, err := plugin.getDeviceMountPath(spec)\n\tif err != nil {\n\t\treturn newSize, err\n\t}\n\tcall.Append(devicePath)\n\tcall.Append(strconv.FormatInt(newSize.Value(), 10))\n\tcall.Append(strconv.FormatInt(oldSize.Value(), 10))\n\n\t_, err = call.Run()\n\tif isCmdNotSupportedErr(err) {\n\t\treturn newExpanderDefaults(plugin).ExpandVolumeDevice(spec, newSize, oldSize)\n\t}\n\treturn newSize, err\n}","line":{"from":27,"to":44}} {"id":100012228,"name":"NodeExpand","signature":"func (plugin *flexVolumePlugin) NodeExpand(rsOpt volume.NodeResizeOptions) (bool, error)","file":"pkg/volume/flexvolume/expander.go","code":"func (plugin *flexVolumePlugin) NodeExpand(rsOpt volume.NodeResizeOptions) (bool, error) {\n\t// This method is called after we spec.PersistentVolume.Spec.Capacity\n\t// has been updated to the new size. The underlying driver thus sees\n\t// the _new_ (requested) size and can find out the _current_ size from\n\t// its underlying storage implementation\n\n\tif rsOpt.VolumeSpec.PersistentVolume == nil {\n\t\treturn false, fmt.Errorf(\"PersistentVolume not found for spec: %s\", rsOpt.VolumeSpec.Name())\n\t}\n\n\tcall := plugin.NewDriverCall(expandFSCmd)\n\tcall.AppendSpec(rsOpt.VolumeSpec, plugin.host, nil)\n\tcall.Append(rsOpt.DevicePath)\n\tcall.Append(rsOpt.DeviceMountPath)\n\tcall.Append(strconv.FormatInt(rsOpt.NewSize.Value(), 10))\n\tcall.Append(strconv.FormatInt(rsOpt.OldSize.Value(), 10))\n\n\t_, err := call.Run()\n\tif isCmdNotSupportedErr(err) {\n\t\treturn newExpanderDefaults(plugin).NodeExpand(rsOpt)\n\t}\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn true, nil\n}","line":{"from":46,"to":71}} {"id":100012229,"name":"SetUpAt","signature":"func (f *mounterDefaults) SetUpAt(dir string, mounterArgs volume.MounterArgs) error","file":"pkg/volume/flexvolume/mounter-defaults.go","code":"// SetUpAt is part of the volume.Mounter interface.\n// This implementation relies on the attacher's device mount path and does a bind mount to dir.\nfunc (f *mounterDefaults) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {\n\tklog.Warning(logPrefix(f.plugin), \"using default SetUpAt to \", dir)\n\n\tsrc, err := f.plugin.getDeviceMountPath(f.spec)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := doMount(f.mounter, src, dir, \"auto\", []string{\"bind\"}); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":27,"to":42}} {"id":100012230,"name":"GetAttributes","signature":"func (f *mounterDefaults) GetAttributes() volume.Attributes","file":"pkg/volume/flexvolume/mounter-defaults.go","code":"// Returns the default volume attributes.\nfunc (f *mounterDefaults) GetAttributes() volume.Attributes {\n\tklog.V(5).Info(logPrefix(f.plugin), \"using default GetAttributes\")\n\treturn volume.Attributes{\n\t\tReadOnly: f.readOnly,\n\t\tManaged: !f.readOnly,\n\t\tSELinuxRelabel: f.flexVolume.plugin.capabilities.SELinuxRelabel,\n\t}\n}","line":{"from":44,"to":52}} {"id":100012231,"name":"SetUp","signature":"func (f *flexVolumeMounter) SetUp(mounterArgs volume.MounterArgs) error","file":"pkg/volume/flexvolume/mounter.go","code":"// SetUp creates new directory.\nfunc (f *flexVolumeMounter) SetUp(mounterArgs volume.MounterArgs) error {\n\treturn f.SetUpAt(f.GetPath(), mounterArgs)\n}","line":{"from":42,"to":45}} {"id":100012232,"name":"SetUpAt","signature":"func (f *flexVolumeMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error","file":"pkg/volume/flexvolume/mounter.go","code":"// SetUpAt creates new directory.\nfunc (f *flexVolumeMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {\n\t// Mount only once.\n\talreadyMounted, err := prepareForMount(f.mounter, dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif alreadyMounted {\n\t\treturn nil\n\t}\n\n\tcall := f.plugin.NewDriverCall(mountCmd)\n\n\t// Interface parameters\n\tcall.Append(dir)\n\n\textraOptions := make(map[string]string)\n\n\t// pod metadata\n\textraOptions[optionKeyPodName] = f.podName\n\textraOptions[optionKeyPodNamespace] = f.podNamespace\n\textraOptions[optionKeyPodUID] = string(f.podUID)\n\t// service account metadata\n\textraOptions[optionKeyServiceAccountName] = f.podServiceAccountName\n\n\t// Extract secret and pass it as options.\n\tif err := addSecretsToOptions(extraOptions, f.spec, f.podNamespace, f.driverName, f.plugin.host); err != nil {\n\t\tos.Remove(dir)\n\t\treturn err\n\t}\n\n\t// Implicit parameters\n\tif mounterArgs.FsGroup != nil {\n\t\textraOptions[optionFSGroup] = strconv.FormatInt(int64(*mounterArgs.FsGroup), 10)\n\t}\n\n\tcall.AppendSpec(f.spec, f.plugin.host, extraOptions)\n\n\t_, err = call.Run()\n\tif isCmdNotSupportedErr(err) {\n\t\terr = (*mounterDefaults)(f).SetUpAt(dir, mounterArgs)\n\t}\n\n\tif err != nil {\n\t\tos.Remove(dir)\n\t\treturn err\n\t}\n\n\tif !f.readOnly {\n\t\tif f.plugin.capabilities.FSGroup {\n\t\t\t// fullPluginName helps to distinguish different driver from flex volume plugin\n\t\t\tvolume.SetVolumeOwnership(f, dir, mounterArgs.FsGroup, mounterArgs.FSGroupChangePolicy, util.FSGroupCompleteHook(f.plugin, f.spec))\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":47,"to":103}} {"id":100012233,"name":"GetAttributes","signature":"func (f *flexVolumeMounter) GetAttributes() volume.Attributes","file":"pkg/volume/flexvolume/mounter.go","code":"// GetAttributes get the flex volume attributes. The attributes will be queried\n// using plugin callout after we finalize the callout syntax.\nfunc (f *flexVolumeMounter) GetAttributes() volume.Attributes {\n\treturn (*mounterDefaults)(f).GetAttributes()\n}","line":{"from":105,"to":109}} {"id":100012234,"name":"logPrefix","signature":"func logPrefix(plugin *flexVolumePlugin) string","file":"pkg/volume/flexvolume/plugin-defaults.go","code":"func logPrefix(plugin *flexVolumePlugin) string {\n\treturn \"flexVolume driver \" + plugin.driverName + \": \"\n}","line":{"from":27,"to":29}} {"id":100012235,"name":"GetVolumeName","signature":"func (plugin *pluginDefaults) GetVolumeName(spec *volume.Spec) (string, error)","file":"pkg/volume/flexvolume/plugin-defaults.go","code":"func (plugin *pluginDefaults) GetVolumeName(spec *volume.Spec) (string, error) {\n\tklog.V(4).Info(logPrefix((*flexVolumePlugin)(plugin)), \"using default GetVolumeName for volume \", spec.Name())\n\treturn spec.Name(), nil\n}","line":{"from":31,"to":34}} {"id":100012236,"name":"NewFlexVolumePlugin","signature":"func (pluginFactory) NewFlexVolumePlugin(pluginDir, name string, runner exec.Interface) (volume.VolumePlugin, error)","file":"pkg/volume/flexvolume/plugin.go","code":"func (pluginFactory) NewFlexVolumePlugin(pluginDir, name string, runner exec.Interface) (volume.VolumePlugin, error) {\n\texecPath := filepath.Join(pluginDir, name)\n\n\tdriverName := utilstrings.UnescapeQualifiedName(name)\n\n\tflexPlugin := \u0026flexVolumePlugin{\n\t\tdriverName: driverName,\n\t\texecPath: execPath,\n\t\trunner: runner,\n\t\tunsupportedCommands: []string{},\n\t}\n\n\t// Initialize the plugin and probe the capabilities\n\tcall := flexPlugin.NewDriverCall(initCmd)\n\tds, err := call.Run()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tflexPlugin.capabilities = *ds.Capabilities\n\n\tif flexPlugin.capabilities.Attach {\n\t\t// Plugin supports attach/detach, so return flexVolumeAttachablePlugin\n\t\treturn \u0026flexVolumeAttachablePlugin{flexVolumePlugin: flexPlugin}, nil\n\t}\n\treturn flexPlugin, nil\n}","line":{"from":70,"to":95}} {"id":100012237,"name":"Init","signature":"func (plugin *flexVolumePlugin) Init(host volume.VolumeHost) error","file":"pkg/volume/flexvolume/plugin.go","code":"// Init is part of the volume.VolumePlugin interface.\nfunc (plugin *flexVolumePlugin) Init(host volume.VolumeHost) error {\n\tplugin.host = host\n\t// Hardwired 'success' as any errors from calling init() will be caught by NewFlexVolumePlugin()\n\treturn nil\n}","line":{"from":97,"to":102}} {"id":100012238,"name":"getExecutable","signature":"func (plugin *flexVolumePlugin) getExecutable() string","file":"pkg/volume/flexvolume/plugin.go","code":"func (plugin *flexVolumePlugin) getExecutable() string {\n\tparts := strings.Split(plugin.driverName, \"/\")\n\texecName := parts[len(parts)-1]\n\texecPath := filepath.Join(plugin.execPath, execName)\n\tif runtime.GOOS == \"windows\" {\n\t\texecPath = util.GetWindowsPath(execPath)\n\t}\n\treturn execPath\n}","line":{"from":104,"to":112}} {"id":100012239,"name":"GetPluginName","signature":"func (plugin *flexVolumePlugin) GetPluginName() string","file":"pkg/volume/flexvolume/plugin.go","code":"// Name is part of the volume.VolumePlugin interface.\nfunc (plugin *flexVolumePlugin) GetPluginName() string {\n\treturn plugin.driverName\n}","line":{"from":114,"to":117}} {"id":100012240,"name":"GetVolumeName","signature":"func (plugin *flexVolumePlugin) GetVolumeName(spec *volume.Spec) (string, error)","file":"pkg/volume/flexvolume/plugin.go","code":"// GetVolumeName is part of the volume.VolumePlugin interface.\nfunc (plugin *flexVolumePlugin) GetVolumeName(spec *volume.Spec) (string, error) {\n\tcall := plugin.NewDriverCall(getVolumeNameCmd)\n\tcall.AppendSpec(spec, plugin.host, nil)\n\n\t_, err := call.Run()\n\tif isCmdNotSupportedErr(err) {\n\t\treturn (*pluginDefaults)(plugin).GetVolumeName(spec)\n\t} else if err != nil {\n\t\treturn \"\", err\n\t}\n\n\tname, err := (*pluginDefaults)(plugin).GetVolumeName(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tklog.V(4).Info(logPrefix(plugin), \"GetVolumeName is not supported yet. Defaulting to PV or volume name: \", name)\n\n\treturn name, nil\n}","line":{"from":119,"to":139}} {"id":100012241,"name":"CanSupport","signature":"func (plugin *flexVolumePlugin) CanSupport(spec *volume.Spec) bool","file":"pkg/volume/flexvolume/plugin.go","code":"// CanSupport is part of the volume.VolumePlugin interface.\nfunc (plugin *flexVolumePlugin) CanSupport(spec *volume.Spec) bool {\n\tsourceDriver, err := getDriver(spec)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn sourceDriver == plugin.driverName\n}","line":{"from":141,"to":148}} {"id":100012242,"name":"RequiresRemount","signature":"func (plugin *flexVolumePlugin) RequiresRemount(spec *volume.Spec) bool","file":"pkg/volume/flexvolume/plugin.go","code":"// RequiresRemount is part of the volume.VolumePlugin interface.\nfunc (plugin *flexVolumePlugin) RequiresRemount(spec *volume.Spec) bool {\n\treturn false\n}","line":{"from":150,"to":153}} {"id":100012243,"name":"GetAccessModes","signature":"func (plugin *flexVolumePlugin) GetAccessModes() []api.PersistentVolumeAccessMode","file":"pkg/volume/flexvolume/plugin.go","code":"// GetAccessModes gets the allowed access modes for this plugin.\nfunc (plugin *flexVolumePlugin) GetAccessModes() []api.PersistentVolumeAccessMode {\n\treturn []api.PersistentVolumeAccessMode{\n\t\tapi.ReadWriteOnce,\n\t\tapi.ReadOnlyMany,\n\t}\n}","line":{"from":155,"to":161}} {"id":100012244,"name":"NewMounter","signature":"func (plugin *flexVolumePlugin) NewMounter(spec *volume.Spec, pod *api.Pod, _ volume.VolumeOptions) (volume.Mounter, error)","file":"pkg/volume/flexvolume/plugin.go","code":"// NewMounter is part of the volume.VolumePlugin interface.\nfunc (plugin *flexVolumePlugin) NewMounter(spec *volume.Spec, pod *api.Pod, _ volume.VolumeOptions) (volume.Mounter, error) {\n\treturn plugin.newMounterInternal(spec, pod, plugin.host.GetMounter(plugin.GetPluginName()), plugin.runner)\n}","line":{"from":163,"to":166}} {"id":100012245,"name":"newMounterInternal","signature":"func (plugin *flexVolumePlugin) newMounterInternal(spec *volume.Spec, pod *api.Pod, mounter mount.Interface, runner exec.Interface) (volume.Mounter, error)","file":"pkg/volume/flexvolume/plugin.go","code":"// newMounterInternal is the internal mounter routine to build the volume.\nfunc (plugin *flexVolumePlugin) newMounterInternal(spec *volume.Spec, pod *api.Pod, mounter mount.Interface, runner exec.Interface) (volume.Mounter, error) {\n\tsourceDriver, err := getDriver(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treadOnly, err := getReadOnly(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar metricsProvider volume.MetricsProvider\n\tif plugin.capabilities.SupportsMetrics {\n\t\tmetricsProvider = volume.NewMetricsStatFS(plugin.host.GetPodVolumeDir(\n\t\t\tpod.UID, utilstrings.EscapeQualifiedName(sourceDriver), spec.Name()))\n\t} else {\n\t\tmetricsProvider = \u0026volume.MetricsNil{}\n\t}\n\n\treturn \u0026flexVolumeMounter{\n\t\tflexVolume: \u0026flexVolume{\n\t\t\tdriverName: sourceDriver,\n\t\t\texecPath: plugin.getExecutable(),\n\t\t\tmounter: mounter,\n\t\t\tplugin: plugin,\n\t\t\tpodName: pod.Name,\n\t\t\tpodUID: pod.UID,\n\t\t\tpodNamespace: pod.Namespace,\n\t\t\tpodServiceAccountName: pod.Spec.ServiceAccountName,\n\t\t\tvolName: spec.Name(),\n\t\t\tMetricsProvider: metricsProvider,\n\t\t},\n\t\trunner: runner,\n\t\tspec: spec,\n\t\treadOnly: readOnly,\n\t}, nil\n}","line":{"from":168,"to":205}} {"id":100012246,"name":"NewUnmounter","signature":"func (plugin *flexVolumePlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error)","file":"pkg/volume/flexvolume/plugin.go","code":"// NewUnmounter is part of the volume.VolumePlugin interface.\nfunc (plugin *flexVolumePlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error) {\n\treturn plugin.newUnmounterInternal(volName, podUID, plugin.host.GetMounter(plugin.GetPluginName()), plugin.runner)\n}","line":{"from":207,"to":210}} {"id":100012247,"name":"newUnmounterInternal","signature":"func (plugin *flexVolumePlugin) newUnmounterInternal(volName string, podUID types.UID, mounter mount.Interface, runner exec.Interface) (volume.Unmounter, error)","file":"pkg/volume/flexvolume/plugin.go","code":"// newUnmounterInternal is the internal unmounter routine to clean the volume.\nfunc (plugin *flexVolumePlugin) newUnmounterInternal(volName string, podUID types.UID, mounter mount.Interface, runner exec.Interface) (volume.Unmounter, error) {\n\tvar metricsProvider volume.MetricsProvider\n\tif plugin.capabilities.SupportsMetrics {\n\t\tmetricsProvider = volume.NewMetricsStatFS(plugin.host.GetPodVolumeDir(\n\t\t\tpodUID, utilstrings.EscapeQualifiedName(plugin.driverName), volName))\n\t} else {\n\t\tmetricsProvider = \u0026volume.MetricsNil{}\n\t}\n\n\treturn \u0026flexVolumeUnmounter{\n\t\tflexVolume: \u0026flexVolume{\n\t\t\tdriverName: plugin.driverName,\n\t\t\texecPath: plugin.getExecutable(),\n\t\t\tmounter: mounter,\n\t\t\tplugin: plugin,\n\t\t\tpodUID: podUID,\n\t\t\tvolName: volName,\n\t\t\tMetricsProvider: metricsProvider,\n\t\t},\n\t\trunner: runner,\n\t}, nil\n}","line":{"from":212,"to":234}} {"id":100012248,"name":"NewAttacher","signature":"func (plugin *flexVolumeAttachablePlugin) NewAttacher() (volume.Attacher, error)","file":"pkg/volume/flexvolume/plugin.go","code":"// NewAttacher is part of the volume.AttachableVolumePlugin interface.\nfunc (plugin *flexVolumeAttachablePlugin) NewAttacher() (volume.Attacher, error) {\n\treturn \u0026flexVolumeAttacher{plugin}, nil\n}","line":{"from":236,"to":239}} {"id":100012249,"name":"NewDeviceMounter","signature":"func (plugin *flexVolumeAttachablePlugin) NewDeviceMounter() (volume.DeviceMounter, error)","file":"pkg/volume/flexvolume/plugin.go","code":"func (plugin *flexVolumeAttachablePlugin) NewDeviceMounter() (volume.DeviceMounter, error) {\n\treturn plugin.NewAttacher()\n}","line":{"from":241,"to":243}} {"id":100012250,"name":"NewDetacher","signature":"func (plugin *flexVolumeAttachablePlugin) NewDetacher() (volume.Detacher, error)","file":"pkg/volume/flexvolume/plugin.go","code":"// NewDetacher is part of the volume.AttachableVolumePlugin interface.\nfunc (plugin *flexVolumeAttachablePlugin) NewDetacher() (volume.Detacher, error) {\n\treturn \u0026flexVolumeDetacher{plugin}, nil\n}","line":{"from":245,"to":248}} {"id":100012251,"name":"NewDeviceUnmounter","signature":"func (plugin *flexVolumeAttachablePlugin) NewDeviceUnmounter() (volume.DeviceUnmounter, error)","file":"pkg/volume/flexvolume/plugin.go","code":"func (plugin *flexVolumeAttachablePlugin) NewDeviceUnmounter() (volume.DeviceUnmounter, error) {\n\treturn plugin.NewDetacher()\n}","line":{"from":250,"to":252}} {"id":100012252,"name":"CanAttach","signature":"func (plugin *flexVolumeAttachablePlugin) CanAttach(spec *volume.Spec) (bool, error)","file":"pkg/volume/flexvolume/plugin.go","code":"func (plugin *flexVolumeAttachablePlugin) CanAttach(spec *volume.Spec) (bool, error) {\n\treturn true, nil\n}","line":{"from":254,"to":256}} {"id":100012253,"name":"CanDeviceMount","signature":"func (plugin *flexVolumeAttachablePlugin) CanDeviceMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/flexvolume/plugin.go","code":"func (plugin *flexVolumeAttachablePlugin) CanDeviceMount(spec *volume.Spec) (bool, error) {\n\treturn true, nil\n}","line":{"from":258,"to":260}} {"id":100012254,"name":"ConstructVolumeSpec","signature":"func (plugin *flexVolumePlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error)","file":"pkg/volume/flexvolume/plugin.go","code":"// ConstructVolumeSpec is part of the volume.AttachableVolumePlugin interface.\nfunc (plugin *flexVolumePlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error) {\n\tflexVolume := \u0026api.Volume{\n\t\tName: volumeName,\n\t\tVolumeSource: api.VolumeSource{\n\t\t\tFlexVolume: \u0026api.FlexVolumeSource{\n\t\t\t\tDriver: plugin.driverName,\n\t\t\t},\n\t\t},\n\t}\n\treturn volume.ReconstructedVolume{\n\t\tSpec: volume.NewSpecFromVolume(flexVolume),\n\t}, nil\n}","line":{"from":262,"to":275}} {"id":100012255,"name":"SupportsMountOption","signature":"func (plugin *flexVolumePlugin) SupportsMountOption() bool","file":"pkg/volume/flexvolume/plugin.go","code":"func (plugin *flexVolumePlugin) SupportsMountOption() bool {\n\treturn false\n}","line":{"from":277,"to":279}} {"id":100012256,"name":"unsupported","signature":"func (plugin *flexVolumePlugin) unsupported(commands ...string)","file":"pkg/volume/flexvolume/plugin.go","code":"// Mark the given commands as unsupported.\nfunc (plugin *flexVolumePlugin) unsupported(commands ...string) {\n\tplugin.Lock()\n\tdefer plugin.Unlock()\n\tplugin.unsupportedCommands = append(plugin.unsupportedCommands, commands...)\n}","line":{"from":281,"to":286}} {"id":100012257,"name":"SupportsBulkVolumeVerification","signature":"func (plugin *flexVolumePlugin) SupportsBulkVolumeVerification() bool","file":"pkg/volume/flexvolume/plugin.go","code":"func (plugin *flexVolumePlugin) SupportsBulkVolumeVerification() bool {\n\treturn false\n}","line":{"from":288,"to":290}} {"id":100012258,"name":"SupportsSELinuxContextMount","signature":"func (plugin *flexVolumePlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/flexvolume/plugin.go","code":"func (plugin *flexVolumePlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error) {\n\treturn false, nil\n}","line":{"from":292,"to":294}} {"id":100012259,"name":"isUnsupported","signature":"func (plugin *flexVolumePlugin) isUnsupported(command string) bool","file":"pkg/volume/flexvolume/plugin.go","code":"// Returns true iff the given command is known to be unsupported.\nfunc (plugin *flexVolumePlugin) isUnsupported(command string) bool {\n\tplugin.Lock()\n\tdefer plugin.Unlock()\n\tfor _, unsupportedCommand := range plugin.unsupportedCommands {\n\t\tif command == unsupportedCommand {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":296,"to":306}} {"id":100012260,"name":"GetDeviceMountRefs","signature":"func (plugin *flexVolumePlugin) GetDeviceMountRefs(deviceMountPath string) ([]string, error)","file":"pkg/volume/flexvolume/plugin.go","code":"func (plugin *flexVolumePlugin) GetDeviceMountRefs(deviceMountPath string) ([]string, error) {\n\tmounter := plugin.host.GetMounter(plugin.GetPluginName())\n\treturn mounter.GetMountRefs(deviceMountPath)\n}","line":{"from":308,"to":311}} {"id":100012261,"name":"getDeviceMountPath","signature":"func (plugin *flexVolumePlugin) getDeviceMountPath(spec *volume.Spec) (string, error)","file":"pkg/volume/flexvolume/plugin.go","code":"func (plugin *flexVolumePlugin) getDeviceMountPath(spec *volume.Spec) (string, error) {\n\tvolumeName, err := plugin.GetVolumeName(spec)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"GetVolumeName failed from getDeviceMountPath: %s\", err)\n\t}\n\n\tmountsDir := filepath.Join(plugin.host.GetPluginDir(flexVolumePluginName), plugin.driverName, \"mounts\")\n\treturn filepath.Join(mountsDir, volumeName), nil\n}","line":{"from":313,"to":321}} {"id":100012262,"name":"RequiresFSResize","signature":"func (plugin *flexVolumePlugin) RequiresFSResize() bool","file":"pkg/volume/flexvolume/plugin.go","code":"func (plugin *flexVolumePlugin) RequiresFSResize() bool {\n\treturn plugin.capabilities.RequiresFSResize\n}","line":{"from":323,"to":325}} {"id":100012263,"name":"GetDynamicPluginProber","signature":"func GetDynamicPluginProber(pluginDir string, runner exec.Interface) volume.DynamicPluginProber","file":"pkg/volume/flexvolume/probe.go","code":"// GetDynamicPluginProber creates dynamic plugin prober\nfunc GetDynamicPluginProber(pluginDir string, runner exec.Interface) volume.DynamicPluginProber {\n\treturn \u0026flexVolumeProber{\n\t\tpluginDir: pluginDir,\n\t\twatcher: utilfs.NewFsnotifyWatcher(),\n\t\tfactory: pluginFactory{},\n\t\trunner: runner,\n\t\tfs: \u0026utilfs.DefaultFs{},\n\t}\n}","line":{"from":46,"to":55}} {"id":100012264,"name":"Init","signature":"func (prober *flexVolumeProber) Init() error","file":"pkg/volume/flexvolume/probe.go","code":"func (prober *flexVolumeProber) Init() error {\n\tprober.testAndSetProbeAllNeeded(true)\n\tprober.eventsMap = map[string]volume.ProbeOperation{}\n\n\tif err := prober.createPluginDir(); err != nil {\n\t\treturn err\n\t}\n\tif err := prober.initWatcher(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":57,"to":69}} {"id":100012265,"name":"Probe","signature":"func (prober *flexVolumeProber) Probe() (events []volume.ProbeEvent, err error)","file":"pkg/volume/flexvolume/probe.go","code":"// If probeAllNeeded is true, probe all pluginDir\n// else probe events in eventsMap\nfunc (prober *flexVolumeProber) Probe() (events []volume.ProbeEvent, err error) {\n\tif prober.probeAllNeeded {\n\t\tprober.testAndSetProbeAllNeeded(false)\n\t\treturn prober.probeAll()\n\t}\n\n\treturn prober.probeMap()\n}","line":{"from":71,"to":80}} {"id":100012266,"name":"probeMap","signature":"func (prober *flexVolumeProber) probeMap() (events []volume.ProbeEvent, err error)","file":"pkg/volume/flexvolume/probe.go","code":"func (prober *flexVolumeProber) probeMap() (events []volume.ProbeEvent, err error) {\n\t// TODO use a concurrent map to avoid Locking the entire map\n\tprober.mutex.Lock()\n\tdefer prober.mutex.Unlock()\n\tprobeEvents := []volume.ProbeEvent{}\n\tallErrs := []error{}\n\tfor driverDirPathAbs, op := range prober.eventsMap {\n\t\tdriverDirName := filepath.Base(driverDirPathAbs) // e.g. driverDirName = vendor~cifs\n\t\tprobeEvent, pluginErr := prober.newProbeEvent(driverDirName, op)\n\t\tif pluginErr != nil {\n\t\t\tallErrs = append(allErrs, pluginErr)\n\t\t\tcontinue\n\t\t}\n\t\tprobeEvents = append(probeEvents, probeEvent)\n\n\t\tdelete(prober.eventsMap, driverDirPathAbs)\n\t}\n\treturn probeEvents, errors.NewAggregate(allErrs)\n}","line":{"from":82,"to":100}} {"id":100012267,"name":"probeAll","signature":"func (prober *flexVolumeProber) probeAll() (events []volume.ProbeEvent, err error)","file":"pkg/volume/flexvolume/probe.go","code":"func (prober *flexVolumeProber) probeAll() (events []volume.ProbeEvent, err error) {\n\tprobeEvents := []volume.ProbeEvent{}\n\tallErrs := []error{}\n\tfiles, err := prober.fs.ReadDir(prober.pluginDir)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading the Flexvolume directory: %s\", err)\n\t}\n\tfor _, f := range files {\n\t\t// only directories with names that do not begin with '.' are counted as plugins\n\t\t// and pluginDir/dirname/dirname should be an executable\n\t\t// unless dirname contains '~' for escaping namespace\n\t\t// e.g. dirname = vendor~cifs\n\t\t// then, executable will be pluginDir/dirname/cifs\n\t\tif f.IsDir() \u0026\u0026 filepath.Base(f.Name())[0] != '.' {\n\t\t\tprobeEvent, pluginErr := prober.newProbeEvent(f.Name(), volume.ProbeAddOrUpdate)\n\t\t\tif pluginErr != nil {\n\t\t\t\tallErrs = append(allErrs, pluginErr)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tprobeEvents = append(probeEvents, probeEvent)\n\t\t}\n\t}\n\treturn probeEvents, errors.NewAggregate(allErrs)\n}","line":{"from":102,"to":125}} {"id":100012268,"name":"newProbeEvent","signature":"func (prober *flexVolumeProber) newProbeEvent(driverDirName string, op volume.ProbeOperation) (volume.ProbeEvent, error)","file":"pkg/volume/flexvolume/probe.go","code":"func (prober *flexVolumeProber) newProbeEvent(driverDirName string, op volume.ProbeOperation) (volume.ProbeEvent, error) {\n\tprobeEvent := volume.ProbeEvent{\n\t\tOp: op,\n\t}\n\tif op == volume.ProbeAddOrUpdate {\n\t\tplugin, pluginErr := prober.factory.NewFlexVolumePlugin(prober.pluginDir, driverDirName, prober.runner)\n\t\tif pluginErr != nil {\n\t\t\tpluginErr = fmt.Errorf(\n\t\t\t\t\"error creating Flexvolume plugin from directory %s, skipping. Error: %s\",\n\t\t\t\tdriverDirName, pluginErr)\n\t\t\treturn probeEvent, pluginErr\n\t\t}\n\t\tprobeEvent.Plugin = plugin\n\t\tprobeEvent.PluginName = plugin.GetPluginName()\n\t} else if op == volume.ProbeRemove {\n\t\tdriverName := utilstrings.UnescapeQualifiedName(driverDirName)\n\t\tprobeEvent.PluginName = driverName\n\n\t} else {\n\t\treturn probeEvent, fmt.Errorf(\"Unknown Operation on directory: %s. \", driverDirName)\n\t}\n\treturn probeEvent, nil\n}","line":{"from":127,"to":149}} {"id":100012269,"name":"handleWatchEvent","signature":"func (prober *flexVolumeProber) handleWatchEvent(event fsnotify.Event) error","file":"pkg/volume/flexvolume/probe.go","code":"func (prober *flexVolumeProber) handleWatchEvent(event fsnotify.Event) error {\n\t// event.Name is the watched path.\n\tif filepath.Base(event.Name)[0] == '.' {\n\t\t// Ignore files beginning with '.'\n\t\treturn nil\n\t}\n\n\teventPathAbs, err := filepath.Abs(event.Name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tparentPathAbs := filepath.Dir(eventPathAbs)\n\tpluginDirAbs, err := filepath.Abs(prober.pluginDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// event of pluginDirAbs\n\tif eventPathAbs == pluginDirAbs {\n\t\t// If the Flexvolume plugin directory is removed, need to recreate it\n\t\t// in order to keep it under watch.\n\t\tif event.Has(fsnotify.Remove) {\n\t\t\tif err := prober.createPluginDir(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := prober.addWatchRecursive(pluginDirAbs); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\t// watch newly added subdirectories inside a driver directory\n\tif event.Has(fsnotify.Create) {\n\t\tif err := prober.addWatchRecursive(eventPathAbs); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\teventRelPathToPluginDir, err := filepath.Rel(pluginDirAbs, eventPathAbs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// event inside specific driver dir\n\tif len(eventRelPathToPluginDir) \u003e 0 {\n\t\tdriverDirName := strings.Split(eventRelPathToPluginDir, string(os.PathSeparator))[0]\n\t\tdriverDirAbs := filepath.Join(pluginDirAbs, driverDirName)\n\t\t// executable is removed, will trigger ProbeRemove event\n\t\tif event.Has(fsnotify.Remove) \u0026\u0026 (eventRelPathToPluginDir == getExecutablePathRel(driverDirName) || parentPathAbs == pluginDirAbs) {\n\t\t\tprober.updateEventsMap(driverDirAbs, volume.ProbeRemove)\n\t\t} else {\n\t\t\tprober.updateEventsMap(driverDirAbs, volume.ProbeAddOrUpdate)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":151,"to":208}} {"id":100012270,"name":"getExecutablePathRel","signature":"func getExecutablePathRel(driverDirName string) string","file":"pkg/volume/flexvolume/probe.go","code":"// getExecutableName returns the executableName of a flex plugin\nfunc getExecutablePathRel(driverDirName string) string {\n\tparts := strings.Split(driverDirName, \"~\")\n\treturn filepath.Join(driverDirName, parts[len(parts)-1])\n}","line":{"from":210,"to":214}} {"id":100012271,"name":"updateEventsMap","signature":"func (prober *flexVolumeProber) updateEventsMap(eventDirAbs string, op volume.ProbeOperation)","file":"pkg/volume/flexvolume/probe.go","code":"func (prober *flexVolumeProber) updateEventsMap(eventDirAbs string, op volume.ProbeOperation) {\n\tprober.mutex.Lock()\n\tdefer prober.mutex.Unlock()\n\tif prober.probeAllNeeded {\n\t\treturn\n\t}\n\tprober.eventsMap[eventDirAbs] = op\n}","line":{"from":216,"to":223}} {"id":100012272,"name":"addWatchRecursive","signature":"func (prober *flexVolumeProber) addWatchRecursive(filename string) error","file":"pkg/volume/flexvolume/probe.go","code":"// Recursively adds to watch all directories inside and including the file specified by the given filename.\n// If the file is a symlink to a directory, it will watch the symlink but not any of the subdirectories.\n//\n// Each file or directory change triggers two events: one from the watch on itself, another from the watch\n// on its parent directory.\nfunc (prober *flexVolumeProber) addWatchRecursive(filename string) error {\n\taddWatch := func(path string, info os.FileInfo, err error) error {\n\t\tif err == nil \u0026\u0026 info.IsDir() {\n\t\t\tif err := prober.watcher.AddWatch(path); err != nil {\n\t\t\t\tklog.Errorf(\"Error recursively adding watch: %v\", err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\treturn prober.fs.Walk(filename, addWatch)\n}","line":{"from":225,"to":240}} {"id":100012273,"name":"initWatcher","signature":"func (prober *flexVolumeProber) initWatcher() error","file":"pkg/volume/flexvolume/probe.go","code":"// Creates a new filesystem watcher and adds watches for the plugin directory\n// and all of its subdirectories.\nfunc (prober *flexVolumeProber) initWatcher() error {\n\terr := prober.watcher.Init(func(event fsnotify.Event) {\n\t\tif err := prober.handleWatchEvent(event); err != nil {\n\t\t\tklog.Errorf(\"Flexvolume prober watch: %s\", err)\n\t\t}\n\t}, func(err error) {\n\t\tklog.Errorf(\"Received an error from watcher: %s\", err)\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error initializing watcher: %s\", err)\n\t}\n\n\tif err := prober.addWatchRecursive(prober.pluginDir); err != nil {\n\t\treturn fmt.Errorf(\"error adding watch on Flexvolume directory: %s\", err)\n\t}\n\n\tprober.watcher.Run()\n\n\treturn nil\n}","line":{"from":242,"to":263}} {"id":100012274,"name":"createPluginDir","signature":"func (prober *flexVolumeProber) createPluginDir() error","file":"pkg/volume/flexvolume/probe.go","code":"// Creates the plugin directory, if it doesn't already exist.\nfunc (prober *flexVolumeProber) createPluginDir() error {\n\tif _, err := prober.fs.Stat(prober.pluginDir); os.IsNotExist(err) {\n\t\tklog.Warningf(\"Flexvolume plugin directory at %s does not exist. Recreating.\", prober.pluginDir)\n\t\terr := prober.fs.MkdirAll(prober.pluginDir, 0755)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error (re-)creating driver directory: %s\", err)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":265,"to":276}} {"id":100012275,"name":"testAndSetProbeAllNeeded","signature":"func (prober *flexVolumeProber) testAndSetProbeAllNeeded(newval bool) (oldval bool)","file":"pkg/volume/flexvolume/probe.go","code":"func (prober *flexVolumeProber) testAndSetProbeAllNeeded(newval bool) (oldval bool) {\n\tprober.mutex.Lock()\n\tdefer prober.mutex.Unlock()\n\toldval, prober.probeAllNeeded = prober.probeAllNeeded, newval\n\treturn\n}","line":{"from":278,"to":283}} {"id":100012276,"name":"TearDownAt","signature":"func (f *unmounterDefaults) TearDownAt(dir string) error","file":"pkg/volume/flexvolume/unmounter-defaults.go","code":"func (f *unmounterDefaults) TearDownAt(dir string) error {\n\tklog.Warning(logPrefix(f.plugin), \"using default TearDownAt for \", dir)\n\treturn mount.CleanupMountPoint(dir, f.mounter, false)\n}","line":{"from":26,"to":29}} {"id":100012277,"name":"TearDown","signature":"func (f *flexVolumeUnmounter) TearDown() error","file":"pkg/volume/flexvolume/unmounter.go","code":"// Unmounter interface\nfunc (f *flexVolumeUnmounter) TearDown() error {\n\tpath := f.GetPath()\n\treturn f.TearDownAt(path)\n}","line":{"from":39,"to":43}} {"id":100012278,"name":"TearDownAt","signature":"func (f *flexVolumeUnmounter) TearDownAt(dir string) error","file":"pkg/volume/flexvolume/unmounter.go","code":"func (f *flexVolumeUnmounter) TearDownAt(dir string) error {\n\tpathExists, pathErr := mount.PathExists(dir)\n\tif pathErr != nil {\n\t\t// only log warning here since plugins should anyways have to deal with errors\n\t\tklog.Warningf(\"Error checking path: %v\", pathErr)\n\t} else {\n\t\tif !pathExists {\n\t\t\tklog.Warningf(\"Warning: Unmount skipped because path does not exist: %v\", dir)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tcall := f.plugin.NewDriverCall(unmountCmd)\n\tcall.Append(dir)\n\t_, err := call.Run()\n\tif isCmdNotSupportedErr(err) {\n\t\terr = (*unmounterDefaults)(f).TearDownAt(dir)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Flexvolume driver may remove the directory. Ignore if it does.\n\tif pathExists, pathErr := mount.PathExists(dir); pathErr != nil {\n\t\treturn fmt.Errorf(\"error checking if path exists: %w\", pathErr)\n\t} else if !pathExists {\n\t\treturn nil\n\t}\n\treturn os.Remove(dir)\n}","line":{"from":45,"to":74}} {"id":100012279,"name":"addSecretsToOptions","signature":"func addSecretsToOptions(options map[string]string, spec *volume.Spec, namespace string, driverName string, host volume.VolumeHost) error","file":"pkg/volume/flexvolume/util.go","code":"func addSecretsToOptions(options map[string]string, spec *volume.Spec, namespace string, driverName string, host volume.VolumeHost) error {\n\tsecretName, secretNamespace, err := getSecretNameAndNamespace(spec, namespace)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(secretName) == 0 || len(secretNamespace) == 0 {\n\t\treturn nil\n\t}\n\n\tkubeClient := host.GetKubeClient()\n\tif kubeClient == nil {\n\t\treturn fmt.Errorf(\"cannot get kube client\")\n\t}\n\n\tsecrets, err := util.GetSecretForPV(secretNamespace, secretName, driverName, host.GetKubeClient())\n\tif err != nil {\n\t\terr = fmt.Errorf(\"couldn't get secret %v/%v err: %w\", secretNamespace, secretName, err)\n\t\treturn err\n\t}\n\tfor name, data := range secrets {\n\t\toptions[optionKeySecret+\"/\"+name] = base64.StdEncoding.EncodeToString([]byte(data))\n\t\tklog.V(1).Infof(\"found flex volume secret info: %s\", name)\n\t}\n\n\treturn nil\n}","line":{"from":31,"to":57}} {"id":100012280,"name":"getDriver","signature":"func getDriver(spec *volume.Spec) (string, error)","file":"pkg/volume/flexvolume/util.go","code":"func getDriver(spec *volume.Spec) (string, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.FlexVolume != nil {\n\t\treturn spec.Volume.FlexVolume.Driver, nil\n\t}\n\tif spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.FlexVolume != nil {\n\t\treturn spec.PersistentVolume.Spec.FlexVolume.Driver, nil\n\t}\n\treturn \"\", errNotFlexVolume\n}","line":{"from":61,"to":69}} {"id":100012281,"name":"getFSType","signature":"func getFSType(spec *volume.Spec) (string, error)","file":"pkg/volume/flexvolume/util.go","code":"func getFSType(spec *volume.Spec) (string, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.FlexVolume != nil {\n\t\treturn spec.Volume.FlexVolume.FSType, nil\n\t}\n\tif spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.FlexVolume != nil {\n\t\treturn spec.PersistentVolume.Spec.FlexVolume.FSType, nil\n\t}\n\treturn \"\", errNotFlexVolume\n}","line":{"from":71,"to":79}} {"id":100012282,"name":"getSecretNameAndNamespace","signature":"func getSecretNameAndNamespace(spec *volume.Spec, podNamespace string) (string, string, error)","file":"pkg/volume/flexvolume/util.go","code":"func getSecretNameAndNamespace(spec *volume.Spec, podNamespace string) (string, string, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.FlexVolume != nil {\n\t\tif spec.Volume.FlexVolume.SecretRef == nil {\n\t\t\treturn \"\", \"\", nil\n\t\t}\n\t\treturn spec.Volume.FlexVolume.SecretRef.Name, podNamespace, nil\n\t}\n\tif spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.FlexVolume != nil {\n\t\tif spec.PersistentVolume.Spec.FlexVolume.SecretRef == nil {\n\t\t\treturn \"\", \"\", nil\n\t\t}\n\t\tsecretName := spec.PersistentVolume.Spec.FlexVolume.SecretRef.Name\n\t\tsecretNamespace := spec.PersistentVolume.Spec.FlexVolume.SecretRef.Namespace\n\t\tif len(secretNamespace) == 0 {\n\t\t\tsecretNamespace = podNamespace\n\t\t}\n\t\treturn secretName, secretNamespace, nil\n\t}\n\treturn \"\", \"\", errNotFlexVolume\n}","line":{"from":81,"to":100}} {"id":100012283,"name":"getReadOnly","signature":"func getReadOnly(spec *volume.Spec) (bool, error)","file":"pkg/volume/flexvolume/util.go","code":"func getReadOnly(spec *volume.Spec) (bool, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.FlexVolume != nil {\n\t\treturn spec.Volume.FlexVolume.ReadOnly, nil\n\t}\n\tif spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.FlexVolume != nil {\n\t\t// ReadOnly is specified at the PV level\n\t\treturn spec.ReadOnly, nil\n\t}\n\treturn false, errNotFlexVolume\n}","line":{"from":102,"to":111}} {"id":100012284,"name":"getOptions","signature":"func getOptions(spec *volume.Spec) (map[string]string, error)","file":"pkg/volume/flexvolume/util.go","code":"func getOptions(spec *volume.Spec) (map[string]string, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.FlexVolume != nil {\n\t\treturn spec.Volume.FlexVolume.Options, nil\n\t}\n\tif spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.FlexVolume != nil {\n\t\treturn spec.PersistentVolume.Spec.FlexVolume.Options, nil\n\t}\n\treturn nil, errNotFlexVolume\n}","line":{"from":113,"to":121}} {"id":100012285,"name":"prepareForMount","signature":"func prepareForMount(mounter mount.Interface, deviceMountPath string) (bool, error)","file":"pkg/volume/flexvolume/util.go","code":"func prepareForMount(mounter mount.Interface, deviceMountPath string) (bool, error) {\n\n\tnotMnt, err := mounter.IsLikelyNotMountPoint(deviceMountPath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tif err := os.MkdirAll(deviceMountPath, 0750); err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tnotMnt = true\n\t\t} else {\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\treturn !notMnt, nil\n}","line":{"from":123,"to":138}} {"id":100012286,"name":"doMount","signature":"func doMount(mounter mount.Interface, devicePath, deviceMountPath, fsType string, options []string) error","file":"pkg/volume/flexvolume/util.go","code":"// Mounts the device at the given path.\n// It is expected that prepareForMount has been called before.\nfunc doMount(mounter mount.Interface, devicePath, deviceMountPath, fsType string, options []string) error {\n\terr := mounter.MountSensitiveWithoutSystemd(devicePath, deviceMountPath, fsType, options, nil)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to mount the volume at %s, device: %s, error: %s\", deviceMountPath, devicePath, err.Error())\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":140,"to":149}} {"id":100012287,"name":"isNotMounted","signature":"func isNotMounted(mounter mount.Interface, deviceMountPath string) (bool, error)","file":"pkg/volume/flexvolume/util.go","code":"func isNotMounted(mounter mount.Interface, deviceMountPath string) (bool, error) {\n\tnotmnt, err := mounter.IsLikelyNotMountPoint(deviceMountPath)\n\tif err != nil {\n\t\tklog.Errorf(\"Error checking mount point %s, error: %v\", deviceMountPath, err)\n\t\treturn false, err\n\t}\n\treturn notmnt, nil\n}","line":{"from":151,"to":158}} {"id":100012288,"name":"GetPath","signature":"func (f *flexVolume) GetPath() string","file":"pkg/volume/flexvolume/volume.go","code":"func (f *flexVolume) GetPath() string {\n\tname := f.driverName\n\treturn f.plugin.host.GetPodVolumeDir(f.podUID, utilstrings.EscapeQualifiedName(name), f.volName)\n}","line":{"from":53,"to":56}} {"id":100012289,"name":"NewAttacher","signature":"func (plugin *gcePersistentDiskPlugin) NewAttacher() (volume.Attacher, error)","file":"pkg/volume/gcepd/attacher.go","code":"func (plugin *gcePersistentDiskPlugin) NewAttacher() (volume.Attacher, error) {\n\tgceCloud, err := getCloudProvider(plugin.host.GetCloudProvider())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026gcePersistentDiskAttacher{\n\t\thost: plugin.host,\n\t\tgceDisks: gceCloud,\n\t}, nil\n}","line":{"from":58,"to":68}} {"id":100012290,"name":"NewDeviceMounter","signature":"func (plugin *gcePersistentDiskPlugin) NewDeviceMounter() (volume.DeviceMounter, error)","file":"pkg/volume/gcepd/attacher.go","code":"func (plugin *gcePersistentDiskPlugin) NewDeviceMounter() (volume.DeviceMounter, error) {\n\treturn plugin.NewAttacher()\n}","line":{"from":70,"to":72}} {"id":100012291,"name":"GetDeviceMountRefs","signature":"func (plugin *gcePersistentDiskPlugin) GetDeviceMountRefs(deviceMountPath string) ([]string, error)","file":"pkg/volume/gcepd/attacher.go","code":"func (plugin *gcePersistentDiskPlugin) GetDeviceMountRefs(deviceMountPath string) ([]string, error) {\n\tmounter := plugin.host.GetMounter(plugin.GetPluginName())\n\treturn mounter.GetMountRefs(deviceMountPath)\n}","line":{"from":74,"to":77}} {"id":100012292,"name":"Attach","signature":"func (attacher *gcePersistentDiskAttacher) Attach(spec *volume.Spec, nodeName types.NodeName) (string, error)","file":"pkg/volume/gcepd/attacher.go","code":"// Attach checks with the GCE cloud provider if the specified volume is already\n// attached to the node with the specified Name.\n// If the volume is attached, it succeeds (returns nil).\n// If it is not, Attach issues a call to the GCE cloud provider to attach it.\n// Callers are responsible for retrying on failure.\n// Callers are responsible for thread safety between concurrent attach and\n// detach operations.\nfunc (attacher *gcePersistentDiskAttacher) Attach(spec *volume.Spec, nodeName types.NodeName) (string, error) {\n\tvolumeSource, readOnly, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tpdName := volumeSource.PDName\n\n\tattached, err := attacher.gceDisks.DiskIsAttached(pdName, nodeName)\n\tif err != nil {\n\t\t// Log error and continue with attach\n\t\tklog.Errorf(\n\t\t\t\"Error checking if PD (%q) is already attached to current node (%q). Will continue and try attach anyway. err=%v\",\n\t\t\tpdName, nodeName, err)\n\t}\n\n\tif err == nil \u0026\u0026 attached {\n\t\t// Volume is already attached to node.\n\t\tklog.Infof(\"Attach operation is successful. PD %q is already attached to node %q.\", pdName, nodeName)\n\t} else {\n\t\tif err := attacher.gceDisks.AttachDisk(pdName, nodeName, readOnly, isRegionalPD(spec)); err != nil {\n\t\t\tklog.Errorf(\"Error attaching PD %q to node %q: %+v\", pdName, nodeName, err)\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\treturn filepath.Join(diskByIDPath, diskGooglePrefix+pdName), nil\n}","line":{"from":79,"to":113}} {"id":100012293,"name":"VolumesAreAttached","signature":"func (attacher *gcePersistentDiskAttacher) VolumesAreAttached(specs []*volume.Spec, nodeName types.NodeName) (map[*volume.Spec]bool, error)","file":"pkg/volume/gcepd/attacher.go","code":"func (attacher *gcePersistentDiskAttacher) VolumesAreAttached(specs []*volume.Spec, nodeName types.NodeName) (map[*volume.Spec]bool, error) {\n\tvolumesAttachedCheck := make(map[*volume.Spec]bool)\n\tvolumePdNameMap := make(map[string]*volume.Spec)\n\tpdNameList := []string{}\n\tfor _, spec := range specs {\n\t\tvolumeSource, _, err := getVolumeSource(spec)\n\t\t// If error is occurred, skip this volume and move to the next one\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Error getting volume (%q) source : %v\", spec.Name(), err)\n\t\t\tcontinue\n\t\t}\n\t\tpdNameList = append(pdNameList, volumeSource.PDName)\n\t\tvolumesAttachedCheck[spec] = true\n\t\tvolumePdNameMap[volumeSource.PDName] = spec\n\t}\n\tattachedResult, err := attacher.gceDisks.DisksAreAttached(pdNameList, nodeName)\n\tif err != nil {\n\t\t// Log error and continue with attach\n\t\tklog.Errorf(\n\t\t\t\"Error checking if PDs (%v) are already attached to current node (%q). err=%v\",\n\t\t\tpdNameList, nodeName, err)\n\t\treturn volumesAttachedCheck, err\n\t}\n\n\tfor pdName, attached := range attachedResult {\n\t\tif !attached {\n\t\t\tspec := volumePdNameMap[pdName]\n\t\t\tvolumesAttachedCheck[spec] = false\n\t\t\tklog.V(2).Infof(\"VolumesAreAttached: check volume %q (specName: %q) is no longer attached\", pdName, spec.Name())\n\t\t}\n\t}\n\treturn volumesAttachedCheck, nil\n}","line":{"from":115,"to":147}} {"id":100012294,"name":"BulkVerifyVolumes","signature":"func (attacher *gcePersistentDiskAttacher) BulkVerifyVolumes(volumesByNode map[types.NodeName][]*volume.Spec) (map[types.NodeName]map[*volume.Spec]bool, error)","file":"pkg/volume/gcepd/attacher.go","code":"func (attacher *gcePersistentDiskAttacher) BulkVerifyVolumes(volumesByNode map[types.NodeName][]*volume.Spec) (map[types.NodeName]map[*volume.Spec]bool, error) {\n\tvolumesAttachedCheck := make(map[types.NodeName]map[*volume.Spec]bool)\n\tdiskNamesByNode := make(map[types.NodeName][]string)\n\tvolumeSpecToDiskName := make(map[*volume.Spec]string)\n\n\tfor nodeName, volumeSpecs := range volumesByNode {\n\t\tdiskNames := []string{}\n\t\tfor _, spec := range volumeSpecs {\n\t\t\tvolumeSource, _, err := getVolumeSource(spec)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"Error getting volume (%q) source : %v\", spec.Name(), err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdiskNames = append(diskNames, volumeSource.PDName)\n\t\t\tvolumeSpecToDiskName[spec] = volumeSource.PDName\n\t\t}\n\t\tdiskNamesByNode[nodeName] = diskNames\n\t}\n\n\tattachedDisksByNode, err := attacher.gceDisks.BulkDisksAreAttached(diskNamesByNode)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor nodeName, volumeSpecs := range volumesByNode {\n\t\tvolumesAreAttachedToNode := make(map[*volume.Spec]bool)\n\t\tfor _, spec := range volumeSpecs {\n\t\t\tdiskName := volumeSpecToDiskName[spec]\n\t\t\tvolumesAreAttachedToNode[spec] = attachedDisksByNode[nodeName][diskName]\n\t\t}\n\t\tvolumesAttachedCheck[nodeName] = volumesAreAttachedToNode\n\t}\n\treturn volumesAttachedCheck, nil\n}","line":{"from":149,"to":182}} {"id":100012295,"name":"getDiskID","signature":"func getDiskID(pdName string, exec utilexec.Interface) (string, error)","file":"pkg/volume/gcepd/attacher.go","code":"// search Windows disk number by LUN\nfunc getDiskID(pdName string, exec utilexec.Interface) (string, error) {\n\t// TODO: replace Get-GcePdName with native windows support of Get-Disk, see issue #74674\n\tcmd := `Get-GcePdName | select Name, DeviceId | ConvertTo-Json`\n\toutput, err := exec.Command(\"powershell\", \"/c\", cmd).CombinedOutput()\n\tif err != nil {\n\t\tklog.Errorf(\"Get-GcePdName failed, error: %v, output: %q\", err, string(output))\n\t\terr = errors.New(err.Error() + \" \" + string(output))\n\t\treturn \"\", err\n\t}\n\n\tvar data []map[string]interface{}\n\tif err = json.Unmarshal(output, \u0026data); err != nil {\n\t\tklog.Errorf(\"Get-Disk output is not a json array, output: %q\", string(output))\n\t\treturn \"\", err\n\t}\n\n\tfor _, pd := range data {\n\t\tif jsonName, ok := pd[\"Name\"]; ok {\n\t\t\tif name, ok := jsonName.(string); ok {\n\t\t\t\tif name == pdName {\n\t\t\t\t\tklog.Infof(\"found the disk %q\", name)\n\t\t\t\t\tif diskNum, ok := pd[\"DeviceId\"]; ok {\n\t\t\t\t\t\tswitch v := diskNum.(type) {\n\t\t\t\t\t\tcase int:\n\t\t\t\t\t\t\treturn strconv.Itoa(v), nil\n\t\t\t\t\t\tcase float64:\n\t\t\t\t\t\t\treturn strconv.Itoa(int(v)), nil\n\t\t\t\t\t\tcase string:\n\t\t\t\t\t\t\treturn v, nil\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t// diskNum isn't one of the types above\n\t\t\t\t\t\t\tklog.Warningf(\"Disk %q found, but disknumber (%q) is not in one of the recongnized type\", name, diskNum)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"could not found disk number for disk %q\", pdName)\n}","line":{"from":184,"to":225}} {"id":100012296,"name":"WaitForAttach","signature":"func (attacher *gcePersistentDiskAttacher) WaitForAttach(spec *volume.Spec, devicePath string, _ *v1.Pod, timeout time.Duration) (string, error)","file":"pkg/volume/gcepd/attacher.go","code":"func (attacher *gcePersistentDiskAttacher) WaitForAttach(spec *volume.Spec, devicePath string, _ *v1.Pod, timeout time.Duration) (string, error) {\n\tticker := time.NewTicker(checkSleepDuration)\n\tdefer ticker.Stop()\n\ttimer := time.NewTimer(timeout)\n\tdefer timer.Stop()\n\n\tvolumeSource, _, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tpdName := volumeSource.PDName\n\n\tif runtime.GOOS == \"windows\" {\n\t\texec := attacher.host.GetExec(gcePersistentDiskPluginName)\n\t\tid, err := getDiskID(pdName, exec)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"WaitForAttach (windows) failed with error %s\", err)\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn id, nil\n\t}\n\n\tpartition := \"\"\n\tif volumeSource.Partition != 0 {\n\t\tpartition = strconv.Itoa(int(volumeSource.Partition))\n\t}\n\n\tsdBefore, err := filepath.Glob(diskSDPattern)\n\tif err != nil {\n\t\tklog.Errorf(\"Error filepath.Glob(\\\"%s\\\"): %v\\r\\n\", diskSDPattern, err)\n\t}\n\tsdBeforeSet := sets.NewString(sdBefore...)\n\n\tdevicePaths := getDiskByIDPaths(pdName, partition)\n\tfor {\n\t\tselect {\n\t\tcase \u003c-ticker.C:\n\t\t\tklog.V(5).Infof(\"Checking GCE PD %q is attached.\", pdName)\n\t\t\tpath, err := verifyDevicePath(devicePaths, sdBeforeSet, pdName)\n\t\t\tif err != nil {\n\t\t\t\t// Log error, if any, and continue checking periodically. See issue #11321\n\t\t\t\tklog.Errorf(\"Error verifying GCE PD (%q) is attached: %v\", pdName, err)\n\t\t\t} else if path != \"\" {\n\t\t\t\t// A device path has successfully been created for the PD\n\t\t\t\tklog.Infof(\"Successfully found attached GCE PD %q.\", pdName)\n\t\t\t\treturn path, nil\n\t\t\t} else {\n\t\t\t\tklog.V(4).Infof(\"could not verify GCE PD (%q) is attached, device path does not exist\", pdName)\n\t\t\t}\n\t\tcase \u003c-timer.C:\n\t\t\treturn \"\", fmt.Errorf(\"could not find attached GCE PD %q. Timeout waiting for mount paths to be created\", pdName)\n\t\t}\n\t}\n}","line":{"from":227,"to":281}} {"id":100012297,"name":"GetDeviceMountPath","signature":"func (attacher *gcePersistentDiskAttacher) GetDeviceMountPath(","file":"pkg/volume/gcepd/attacher.go","code":"func (attacher *gcePersistentDiskAttacher) GetDeviceMountPath(\n\tspec *volume.Spec) (string, error) {\n\tvolumeSource, _, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn makeGlobalPDName(attacher.host, volumeSource.PDName), nil\n}","line":{"from":283,"to":291}} {"id":100012298,"name":"MountDevice","signature":"func (attacher *gcePersistentDiskAttacher) MountDevice(spec *volume.Spec, devicePath string, deviceMountPath string, _ volume.DeviceMounterArgs) error","file":"pkg/volume/gcepd/attacher.go","code":"func (attacher *gcePersistentDiskAttacher) MountDevice(spec *volume.Spec, devicePath string, deviceMountPath string, _ volume.DeviceMounterArgs) error {\n\t// Only mount the PD globally once.\n\tmounter := attacher.host.GetMounter(gcePersistentDiskPluginName)\n\tnotMnt, err := mounter.IsLikelyNotMountPoint(deviceMountPath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tdir := deviceMountPath\n\t\t\tif runtime.GOOS == \"windows\" {\n\t\t\t\t// in windows, as we use mklink, only need to MkdirAll for parent directory\n\t\t\t\tdir = filepath.Dir(deviceMountPath)\n\t\t\t}\n\t\t\tif err := os.MkdirAll(dir, 0750); err != nil {\n\t\t\t\treturn fmt.Errorf(\"MountDevice:CreateDirectory failed with %s\", err)\n\t\t\t}\n\t\t\tnotMnt = true\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tvolumeSource, readOnly, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\toptions := []string{}\n\tif readOnly {\n\t\toptions = append(options, \"ro\")\n\t}\n\tif notMnt {\n\t\tdiskMounter := volumeutil.NewSafeFormatAndMountFromHost(gcePersistentDiskPluginName, attacher.host)\n\t\tmountOptions := volumeutil.MountOptionFromSpec(spec, options...)\n\t\terr = diskMounter.FormatAndMount(devicePath, deviceMountPath, volumeSource.FSType, mountOptions)\n\t\tif err != nil {\n\t\t\tos.Remove(deviceMountPath)\n\t\t\treturn err\n\t\t}\n\t\tklog.V(4).Infof(\"formatting spec %v devicePath %v deviceMountPath %v fs %v with options %+v\", spec.Name(), devicePath, deviceMountPath, volumeSource.FSType, options)\n\t}\n\treturn nil\n}","line":{"from":293,"to":333}} {"id":100012299,"name":"NewDetacher","signature":"func (plugin *gcePersistentDiskPlugin) NewDetacher() (volume.Detacher, error)","file":"pkg/volume/gcepd/attacher.go","code":"func (plugin *gcePersistentDiskPlugin) NewDetacher() (volume.Detacher, error) {\n\tgceCloud, err := getCloudProvider(plugin.host.GetCloudProvider())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026gcePersistentDiskDetacher{\n\t\thost: plugin.host,\n\t\tgceDisks: gceCloud,\n\t}, nil\n}","line":{"from":344,"to":354}} {"id":100012300,"name":"NewDeviceUnmounter","signature":"func (plugin *gcePersistentDiskPlugin) NewDeviceUnmounter() (volume.DeviceUnmounter, error)","file":"pkg/volume/gcepd/attacher.go","code":"func (plugin *gcePersistentDiskPlugin) NewDeviceUnmounter() (volume.DeviceUnmounter, error) {\n\treturn plugin.NewDetacher()\n}","line":{"from":356,"to":358}} {"id":100012301,"name":"Detach","signature":"func (detacher *gcePersistentDiskDetacher) Detach(volumeName string, nodeName types.NodeName) error","file":"pkg/volume/gcepd/attacher.go","code":"// Detach checks with the GCE cloud provider if the specified volume is already\n// attached to the specified node. If the volume is not attached, it succeeds\n// (returns nil). If it is attached, Detach issues a call to the GCE cloud\n// provider to attach it.\n// Callers are responsible for retrying on failure.\n// Callers are responsible for thread safety between concurrent attach and detach\n// operations.\nfunc (detacher *gcePersistentDiskDetacher) Detach(volumeName string, nodeName types.NodeName) error {\n\tpdName := path.Base(volumeName)\n\n\tattached, err := detacher.gceDisks.DiskIsAttached(pdName, nodeName)\n\tif err != nil {\n\t\t// Log error and continue with detach\n\t\tklog.Errorf(\n\t\t\t\"Error checking if PD (%q) is already attached to current node (%q). Will continue and try detach anyway. err=%v\",\n\t\t\tpdName, nodeName, err)\n\t}\n\n\tif err == nil \u0026\u0026 !attached {\n\t\t// Volume is not attached to node. Success!\n\t\tklog.Infof(\"Detach operation is successful. PD %q was not attached to node %q.\", pdName, nodeName)\n\t\treturn nil\n\t}\n\n\tif err = detacher.gceDisks.DetachDisk(pdName, nodeName); err != nil {\n\t\tklog.Errorf(\"Error detaching PD %q from node %q: %v\", pdName, nodeName, err)\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":360,"to":390}} {"id":100012302,"name":"UnmountDevice","signature":"func (detacher *gcePersistentDiskDetacher) UnmountDevice(deviceMountPath string) error","file":"pkg/volume/gcepd/attacher.go","code":"func (detacher *gcePersistentDiskDetacher) UnmountDevice(deviceMountPath string) error {\n\tif runtime.GOOS == \"windows\" {\n\t\t// Flush data cache for windows because it does not do so automatically during unmount device\n\t\texec := detacher.host.GetExec(gcePersistentDiskPluginName)\n\t\terr := volumeutil.WriteVolumeCache(deviceMountPath, exec)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn mount.CleanupMountPoint(deviceMountPath, detacher.host.GetMounter(gcePersistentDiskPluginName), false)\n}","line":{"from":392,"to":402}} {"id":100012303,"name":"CanAttach","signature":"func (plugin *gcePersistentDiskPlugin) CanAttach(spec *volume.Spec) (bool, error)","file":"pkg/volume/gcepd/attacher.go","code":"func (plugin *gcePersistentDiskPlugin) CanAttach(spec *volume.Spec) (bool, error) {\n\treturn true, nil\n}","line":{"from":404,"to":406}} {"id":100012304,"name":"CanDeviceMount","signature":"func (plugin *gcePersistentDiskPlugin) CanDeviceMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/gcepd/attacher.go","code":"func (plugin *gcePersistentDiskPlugin) CanDeviceMount(spec *volume.Spec) (bool, error) {\n\treturn true, nil\n}","line":{"from":408,"to":410}} {"id":100012305,"name":"ProbeVolumePlugins","signature":"func ProbeVolumePlugins() []volume.VolumePlugin","file":"pkg/volume/gcepd/gce_pd.go","code":"// ProbeVolumePlugins is the primary entrypoint for volume plugins.\nfunc ProbeVolumePlugins() []volume.VolumePlugin {\n\treturn []volume.VolumePlugin{\u0026gcePersistentDiskPlugin{nil}}\n}","line":{"from":44,"to":47}} {"id":100012306,"name":"getPath","signature":"func getPath(uid types.UID, volName string, host volume.VolumeHost) string","file":"pkg/volume/gcepd/gce_pd.go","code":"func getPath(uid types.UID, volName string, host volume.VolumeHost) string {\n\treturn host.GetPodVolumeDir(uid, utilstrings.EscapeQualifiedName(gcePersistentDiskPluginName), volName)\n}","line":{"from":75,"to":77}} {"id":100012307,"name":"Init","signature":"func (plugin *gcePersistentDiskPlugin) Init(host volume.VolumeHost) error","file":"pkg/volume/gcepd/gce_pd.go","code":"func (plugin *gcePersistentDiskPlugin) Init(host volume.VolumeHost) error {\n\tplugin.host = host\n\treturn nil\n}","line":{"from":79,"to":82}} {"id":100012308,"name":"GetPluginName","signature":"func (plugin *gcePersistentDiskPlugin) GetPluginName() string","file":"pkg/volume/gcepd/gce_pd.go","code":"func (plugin *gcePersistentDiskPlugin) GetPluginName() string {\n\treturn gcePersistentDiskPluginName\n}","line":{"from":84,"to":86}} {"id":100012309,"name":"GetVolumeName","signature":"func (plugin *gcePersistentDiskPlugin) GetVolumeName(spec *volume.Spec) (string, error)","file":"pkg/volume/gcepd/gce_pd.go","code":"func (plugin *gcePersistentDiskPlugin) GetVolumeName(spec *volume.Spec) (string, error) {\n\tvolumeSource, _, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn volumeSource.PDName, nil\n}","line":{"from":88,"to":95}} {"id":100012310,"name":"CanSupport","signature":"func (plugin *gcePersistentDiskPlugin) CanSupport(spec *volume.Spec) bool","file":"pkg/volume/gcepd/gce_pd.go","code":"func (plugin *gcePersistentDiskPlugin) CanSupport(spec *volume.Spec) bool {\n\treturn (spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.GCEPersistentDisk != nil) ||\n\t\t(spec.Volume != nil \u0026\u0026 spec.Volume.GCEPersistentDisk != nil)\n}","line":{"from":97,"to":100}} {"id":100012311,"name":"RequiresRemount","signature":"func (plugin *gcePersistentDiskPlugin) RequiresRemount(spec *volume.Spec) bool","file":"pkg/volume/gcepd/gce_pd.go","code":"func (plugin *gcePersistentDiskPlugin) RequiresRemount(spec *volume.Spec) bool {\n\treturn false\n}","line":{"from":102,"to":104}} {"id":100012312,"name":"SupportsMountOption","signature":"func (plugin *gcePersistentDiskPlugin) SupportsMountOption() bool","file":"pkg/volume/gcepd/gce_pd.go","code":"func (plugin *gcePersistentDiskPlugin) SupportsMountOption() bool {\n\treturn true\n}","line":{"from":106,"to":108}} {"id":100012313,"name":"SupportsBulkVolumeVerification","signature":"func (plugin *gcePersistentDiskPlugin) SupportsBulkVolumeVerification() bool","file":"pkg/volume/gcepd/gce_pd.go","code":"func (plugin *gcePersistentDiskPlugin) SupportsBulkVolumeVerification() bool {\n\treturn true\n}","line":{"from":110,"to":112}} {"id":100012314,"name":"SupportsSELinuxContextMount","signature":"func (plugin *gcePersistentDiskPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/gcepd/gce_pd.go","code":"func (plugin *gcePersistentDiskPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error) {\n\treturn false, nil\n}","line":{"from":114,"to":116}} {"id":100012315,"name":"GetAccessModes","signature":"func (plugin *gcePersistentDiskPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode","file":"pkg/volume/gcepd/gce_pd.go","code":"func (plugin *gcePersistentDiskPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode {\n\treturn []v1.PersistentVolumeAccessMode{\n\t\tv1.ReadWriteOnce,\n\t\tv1.ReadOnlyMany,\n\t}\n}","line":{"from":118,"to":123}} {"id":100012316,"name":"GetVolumeLimits","signature":"func (plugin *gcePersistentDiskPlugin) GetVolumeLimits() (map[string]int64, error)","file":"pkg/volume/gcepd/gce_pd.go","code":"func (plugin *gcePersistentDiskPlugin) GetVolumeLimits() (map[string]int64, error) {\n\tvolumeLimits := map[string]int64{\n\t\tutil.GCEVolumeLimitKey: volumeLimitSmall,\n\t}\n\tcloud := plugin.host.GetCloudProvider()\n\n\t// if we can't fetch cloudprovider we return an error\n\t// hoping external CCM or admin can set it. Returning\n\t// default values from here will mean, no one can\n\t// override them.\n\tif cloud == nil {\n\t\treturn nil, fmt.Errorf(\"no cloudprovider present\")\n\t}\n\n\tif cloud.ProviderName() != gcecloud.ProviderName {\n\t\treturn nil, fmt.Errorf(\"expected gce cloud got %s\", cloud.ProviderName())\n\t}\n\n\tinstances, ok := cloud.Instances()\n\tif !ok {\n\t\tklog.Warning(\"Failed to get instances from cloud provider\")\n\t\treturn volumeLimits, nil\n\t}\n\n\tinstanceType, err := instances.InstanceType(context.TODO(), plugin.host.GetNodeName())\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get instance type from GCE cloud provider\")\n\t\treturn volumeLimits, nil\n\t}\n\tsmallMachineTypes := []string{\"f1-micro\", \"g1-small\", \"e2-micro\", \"e2-small\", \"e2-medium\"}\n\tfor _, small := range smallMachineTypes {\n\t\tif instanceType == small {\n\t\t\tvolumeLimits[util.GCEVolumeLimitKey] = volumeLimitSmall\n\t\t\treturn volumeLimits, nil\n\t\t}\n\t}\n\tvolumeLimits[util.GCEVolumeLimitKey] = volumeLimitBig\n\treturn volumeLimits, nil\n}","line":{"from":125,"to":163}} {"id":100012317,"name":"VolumeLimitKey","signature":"func (plugin *gcePersistentDiskPlugin) VolumeLimitKey(spec *volume.Spec) string","file":"pkg/volume/gcepd/gce_pd.go","code":"func (plugin *gcePersistentDiskPlugin) VolumeLimitKey(spec *volume.Spec) string {\n\treturn util.GCEVolumeLimitKey\n}","line":{"from":165,"to":167}} {"id":100012318,"name":"NewMounter","signature":"func (plugin *gcePersistentDiskPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error)","file":"pkg/volume/gcepd/gce_pd.go","code":"func (plugin *gcePersistentDiskPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) {\n\t// Inject real implementations here, test through the internal function.\n\treturn plugin.newMounterInternal(spec, pod.UID, \u0026GCEDiskUtil{}, plugin.host.GetMounter(plugin.GetPluginName()))\n}","line":{"from":169,"to":172}} {"id":100012319,"name":"getVolumeSource","signature":"func getVolumeSource(","file":"pkg/volume/gcepd/gce_pd.go","code":"func getVolumeSource(\n\tspec *volume.Spec) (*v1.GCEPersistentDiskVolumeSource, bool, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.GCEPersistentDisk != nil {\n\t\treturn spec.Volume.GCEPersistentDisk, spec.Volume.GCEPersistentDisk.ReadOnly, nil\n\t} else if spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.GCEPersistentDisk != nil {\n\t\treturn spec.PersistentVolume.Spec.GCEPersistentDisk, spec.ReadOnly, nil\n\t}\n\n\treturn nil, false, fmt.Errorf(\"spec does not reference a GCE volume type\")\n}","line":{"from":174,"to":184}} {"id":100012320,"name":"newMounterInternal","signature":"func (plugin *gcePersistentDiskPlugin) newMounterInternal(spec *volume.Spec, podUID types.UID, manager pdManager, mounter mount.Interface) (volume.Mounter, error)","file":"pkg/volume/gcepd/gce_pd.go","code":"func (plugin *gcePersistentDiskPlugin) newMounterInternal(spec *volume.Spec, podUID types.UID, manager pdManager, mounter mount.Interface) (volume.Mounter, error) {\n\t// GCEPDs used directly in a pod have a ReadOnly flag set by the pod author.\n\t// GCEPDs used as a PersistentVolume gets the ReadOnly flag indirectly through the persistent-claim volume used to mount the PV\n\tvolumeSource, readOnly, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpdName := volumeSource.PDName\n\tpartition := \"\"\n\tif volumeSource.Partition != 0 {\n\t\tpartition = strconv.Itoa(int(volumeSource.Partition))\n\t}\n\n\treturn \u0026gcePersistentDiskMounter{\n\t\tgcePersistentDisk: \u0026gcePersistentDisk{\n\t\t\tpodUID: podUID,\n\t\t\tvolName: spec.Name(),\n\t\t\tpdName: pdName,\n\t\t\tpartition: partition,\n\t\t\tmounter: mounter,\n\t\t\tmanager: manager,\n\t\t\tplugin: plugin,\n\t\t\tMetricsProvider: volume.NewMetricsStatFS(getPath(podUID, spec.Name(), plugin.host)),\n\t\t},\n\t\tmountOptions: util.MountOptionFromSpec(spec),\n\t\treadOnly: readOnly}, nil\n}","line":{"from":186,"to":213}} {"id":100012321,"name":"NewUnmounter","signature":"func (plugin *gcePersistentDiskPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error)","file":"pkg/volume/gcepd/gce_pd.go","code":"func (plugin *gcePersistentDiskPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error) {\n\t// Inject real implementations here, test through the internal function.\n\treturn plugin.newUnmounterInternal(volName, podUID, \u0026GCEDiskUtil{}, plugin.host.GetMounter(plugin.GetPluginName()))\n}","line":{"from":215,"to":218}} {"id":100012322,"name":"newUnmounterInternal","signature":"func (plugin *gcePersistentDiskPlugin) newUnmounterInternal(volName string, podUID types.UID, manager pdManager, mounter mount.Interface) (volume.Unmounter, error)","file":"pkg/volume/gcepd/gce_pd.go","code":"func (plugin *gcePersistentDiskPlugin) newUnmounterInternal(volName string, podUID types.UID, manager pdManager, mounter mount.Interface) (volume.Unmounter, error) {\n\treturn \u0026gcePersistentDiskUnmounter{\u0026gcePersistentDisk{\n\t\tpodUID: podUID,\n\t\tvolName: volName,\n\t\tmanager: manager,\n\t\tmounter: mounter,\n\t\tplugin: plugin,\n\t\tMetricsProvider: volume.NewMetricsStatFS(getPath(podUID, volName, plugin.host)),\n\t}}, nil\n}","line":{"from":220,"to":229}} {"id":100012323,"name":"NewDeleter","signature":"func (plugin *gcePersistentDiskPlugin) NewDeleter(logger klog.Logger, spec *volume.Spec) (volume.Deleter, error)","file":"pkg/volume/gcepd/gce_pd.go","code":"func (plugin *gcePersistentDiskPlugin) NewDeleter(logger klog.Logger, spec *volume.Spec) (volume.Deleter, error) {\n\treturn plugin.newDeleterInternal(spec, \u0026GCEDiskUtil{})\n}","line":{"from":231,"to":233}} {"id":100012324,"name":"newDeleterInternal","signature":"func (plugin *gcePersistentDiskPlugin) newDeleterInternal(spec *volume.Spec, manager pdManager) (volume.Deleter, error)","file":"pkg/volume/gcepd/gce_pd.go","code":"func (plugin *gcePersistentDiskPlugin) newDeleterInternal(spec *volume.Spec, manager pdManager) (volume.Deleter, error) {\n\tif spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.GCEPersistentDisk == nil {\n\t\treturn nil, fmt.Errorf(\"spec.PersistentVolumeSource.GCEPersistentDisk is nil\")\n\t}\n\treturn \u0026gcePersistentDiskDeleter{\n\t\tgcePersistentDisk: \u0026gcePersistentDisk{\n\t\t\tvolName: spec.Name(),\n\t\t\tpdName: spec.PersistentVolume.Spec.GCEPersistentDisk.PDName,\n\t\t\tmanager: manager,\n\t\t\tplugin: plugin,\n\t\t}}, nil\n}","line":{"from":235,"to":246}} {"id":100012325,"name":"NewProvisioner","signature":"func (plugin *gcePersistentDiskPlugin) NewProvisioner(logger klog.Logger, options volume.VolumeOptions) (volume.Provisioner, error)","file":"pkg/volume/gcepd/gce_pd.go","code":"func (plugin *gcePersistentDiskPlugin) NewProvisioner(logger klog.Logger, options volume.VolumeOptions) (volume.Provisioner, error) {\n\treturn plugin.newProvisionerInternal(options, \u0026GCEDiskUtil{})\n}","line":{"from":248,"to":250}} {"id":100012326,"name":"newProvisionerInternal","signature":"func (plugin *gcePersistentDiskPlugin) newProvisionerInternal(options volume.VolumeOptions, manager pdManager) (volume.Provisioner, error)","file":"pkg/volume/gcepd/gce_pd.go","code":"func (plugin *gcePersistentDiskPlugin) newProvisionerInternal(options volume.VolumeOptions, manager pdManager) (volume.Provisioner, error) {\n\treturn \u0026gcePersistentDiskProvisioner{\n\t\tgcePersistentDisk: \u0026gcePersistentDisk{\n\t\t\tmanager: manager,\n\t\t\tplugin: plugin,\n\t\t},\n\t\toptions: options,\n\t}, nil\n}","line":{"from":252,"to":260}} {"id":100012327,"name":"RequiresFSResize","signature":"func (plugin *gcePersistentDiskPlugin) RequiresFSResize() bool","file":"pkg/volume/gcepd/gce_pd.go","code":"func (plugin *gcePersistentDiskPlugin) RequiresFSResize() bool {\n\treturn true\n}","line":{"from":262,"to":264}} {"id":100012328,"name":"ExpandVolumeDevice","signature":"func (plugin *gcePersistentDiskPlugin) ExpandVolumeDevice(","file":"pkg/volume/gcepd/gce_pd.go","code":"func (plugin *gcePersistentDiskPlugin) ExpandVolumeDevice(\n\tspec *volume.Spec,\n\tnewSize resource.Quantity,\n\toldSize resource.Quantity) (resource.Quantity, error) {\n\tcloud, err := getCloudProvider(plugin.host.GetCloudProvider())\n\n\tif err != nil {\n\t\treturn oldSize, err\n\t}\n\tpdName := spec.PersistentVolume.Spec.GCEPersistentDisk.PDName\n\tupdatedQuantity, err := cloud.ResizeDisk(pdName, oldSize, newSize)\n\n\tif err != nil {\n\t\treturn oldSize, err\n\t}\n\treturn updatedQuantity, nil\n}","line":{"from":266,"to":282}} {"id":100012329,"name":"NodeExpand","signature":"func (plugin *gcePersistentDiskPlugin) NodeExpand(resizeOptions volume.NodeResizeOptions) (bool, error)","file":"pkg/volume/gcepd/gce_pd.go","code":"func (plugin *gcePersistentDiskPlugin) NodeExpand(resizeOptions volume.NodeResizeOptions) (bool, error) {\n\tfsVolume, err := util.CheckVolumeModeFilesystem(resizeOptions.VolumeSpec)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"error checking VolumeMode: %v\", err)\n\t}\n\t// if volume is not a fs file system, there is nothing for us to do here.\n\tif !fsVolume {\n\t\treturn true, nil\n\t}\n\t_, err = util.GenericResizeFS(plugin.host, plugin.GetPluginName(), resizeOptions.DevicePath, resizeOptions.DeviceMountPath)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn true, nil\n}","line":{"from":284,"to":298}} {"id":100012330,"name":"ConstructVolumeSpec","signature":"func (plugin *gcePersistentDiskPlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error)","file":"pkg/volume/gcepd/gce_pd.go","code":"func (plugin *gcePersistentDiskPlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error) {\n\tmounter := plugin.host.GetMounter(plugin.GetPluginName())\n\tkvh, ok := plugin.host.(volume.KubeletVolumeHost)\n\tif !ok {\n\t\treturn volume.ReconstructedVolume{}, fmt.Errorf(\"plugin volume host does not implement KubeletVolumeHost interface\")\n\t}\n\thu := kvh.GetHostUtil()\n\tpluginMntDir := util.GetPluginMountDir(plugin.host, plugin.GetPluginName())\n\tsourceName, err := hu.GetDeviceNameFromMount(mounter, mountPath, pluginMntDir)\n\tif err != nil {\n\t\treturn volume.ReconstructedVolume{}, err\n\t}\n\tgceVolume := \u0026v1.Volume{\n\t\tName: volumeName,\n\t\tVolumeSource: v1.VolumeSource{\n\t\t\tGCEPersistentDisk: \u0026v1.GCEPersistentDiskVolumeSource{\n\t\t\t\tPDName: sourceName,\n\t\t\t},\n\t\t},\n\t}\n\treturn volume.ReconstructedVolume{\n\t\tSpec: volume.NewSpecFromVolume(gceVolume),\n\t}, nil\n}","line":{"from":302,"to":325}} {"id":100012331,"name":"GetAttributes","signature":"func (b *gcePersistentDiskMounter) GetAttributes() volume.Attributes","file":"pkg/volume/gcepd/gce_pd.go","code":"func (b *gcePersistentDiskMounter) GetAttributes() volume.Attributes {\n\treturn volume.Attributes{\n\t\tReadOnly: b.readOnly,\n\t\tManaged: !b.readOnly,\n\t\tSELinuxRelabel: true,\n\t}\n}","line":{"from":361,"to":367}} {"id":100012332,"name":"SetUp","signature":"func (b *gcePersistentDiskMounter) SetUp(mounterArgs volume.MounterArgs) error","file":"pkg/volume/gcepd/gce_pd.go","code":"// SetUp bind mounts the disk global mount to the volume path.\nfunc (b *gcePersistentDiskMounter) SetUp(mounterArgs volume.MounterArgs) error {\n\treturn b.SetUpAt(b.GetPath(), mounterArgs)\n}","line":{"from":369,"to":372}} {"id":100012333,"name":"SetUpAt","signature":"func (b *gcePersistentDiskMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error","file":"pkg/volume/gcepd/gce_pd.go","code":"// SetUp bind mounts the disk global mount to the give volume path.\nfunc (b *gcePersistentDiskMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {\n\t// TODO: handle failed mounts here.\n\tnotMnt, err := b.mounter.IsLikelyNotMountPoint(dir)\n\tklog.V(4).Infof(\"GCE PersistentDisk set up: Dir (%s) PD name (%q) Mounted (%t) Error (%v), ReadOnly (%t)\", dir, b.pdName, !notMnt, err, b.readOnly)\n\tif err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"cannot validate mount point: %s %v\", dir, err)\n\t}\n\tif !notMnt {\n\t\treturn nil\n\t}\n\n\tif runtime.GOOS != \"windows\" {\n\t\t// in windows, we will use mklink to mount, will MkdirAll in Mount func\n\t\tif err := os.MkdirAll(dir, 0750); err != nil {\n\t\t\treturn fmt.Errorf(\"mkdir failed on disk %s (%v)\", dir, err)\n\t\t}\n\t}\n\n\t// Perform a bind mount to the full path to allow duplicate mounts of the same PD.\n\toptions := []string{\"bind\"}\n\tif b.readOnly {\n\t\toptions = append(options, \"ro\")\n\t}\n\n\tglobalPDPath := makeGlobalPDName(b.plugin.host, b.pdName)\n\tklog.V(4).Infof(\"attempting to mount %s\", dir)\n\n\tmountOptions := util.JoinMountOptions(b.mountOptions, options)\n\n\terr = b.mounter.MountSensitiveWithoutSystemd(globalPDPath, dir, \"\", mountOptions, nil)\n\tif err != nil {\n\t\tnotMnt, mntErr := b.mounter.IsLikelyNotMountPoint(dir)\n\t\tif mntErr != nil {\n\t\t\treturn fmt.Errorf(\"failed to mount: %v. Cleanup IsLikelyNotMountPoint check failed: %v\", err, mntErr)\n\t\t}\n\t\tif !notMnt {\n\t\t\tif mntErr = b.mounter.Unmount(dir); mntErr != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to mount: %v. Cleanup failed to unmount: %v\", err, mntErr)\n\t\t\t}\n\t\t\tnotMnt, mntErr := b.mounter.IsLikelyNotMountPoint(dir)\n\t\t\tif mntErr != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to mount: %v. Cleanup IsLikelyNotMountPoint check failed: %v\", err, mntErr)\n\t\t\t}\n\t\t\tif !notMnt {\n\t\t\t\t// This is very odd, we don't expect it. We'll try again next sync loop.\n\t\t\t\treturn fmt.Errorf(\"%s is still mounted, despite call to unmount(). Will try again next sync loop\", dir)\n\t\t\t}\n\t\t}\n\t\tmntErr = os.Remove(dir)\n\t\tif mntErr != nil {\n\t\t\treturn fmt.Errorf(\"failed to mount: %v. Cleanup os Remove(%s) failed: %v\", err, dir, mntErr)\n\t\t}\n\n\t\treturn fmt.Errorf(\"mount of disk %s failed: %v\", dir, err)\n\t}\n\n\tklog.V(4).Infof(\"mount of disk %s succeeded\", dir)\n\tif !b.readOnly {\n\t\tif err := volume.SetVolumeOwnership(b, dir, mounterArgs.FsGroup, mounterArgs.FSGroupChangePolicy, util.FSGroupCompleteHook(b.plugin, nil)); err != nil {\n\t\t\tklog.Errorf(\"SetVolumeOwnership returns error %v\", err)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":374,"to":438}} {"id":100012334,"name":"makeGlobalPDName","signature":"func makeGlobalPDName(host volume.VolumeHost, devName string) string","file":"pkg/volume/gcepd/gce_pd.go","code":"func makeGlobalPDName(host volume.VolumeHost, devName string) string {\n\treturn filepath.Join(host.GetPluginDir(gcePersistentDiskPluginName), util.MountsInGlobalPDPath, devName)\n}","line":{"from":440,"to":442}} {"id":100012335,"name":"GetPath","signature":"func (b *gcePersistentDiskMounter) GetPath() string","file":"pkg/volume/gcepd/gce_pd.go","code":"func (b *gcePersistentDiskMounter) GetPath() string {\n\treturn getPath(b.podUID, b.volName, b.plugin.host)\n}","line":{"from":444,"to":446}} {"id":100012336,"name":"GetPath","signature":"func (c *gcePersistentDiskUnmounter) GetPath() string","file":"pkg/volume/gcepd/gce_pd.go","code":"func (c *gcePersistentDiskUnmounter) GetPath() string {\n\treturn getPath(c.podUID, c.volName, c.plugin.host)\n}","line":{"from":454,"to":456}} {"id":100012337,"name":"TearDown","signature":"func (c *gcePersistentDiskUnmounter) TearDown() error","file":"pkg/volume/gcepd/gce_pd.go","code":"// Unmounts the bind mount, and detaches the disk only if the PD\n// resource was the last reference to that disk on the kubelet.\nfunc (c *gcePersistentDiskUnmounter) TearDown() error {\n\treturn c.TearDownAt(c.GetPath())\n}","line":{"from":458,"to":462}} {"id":100012338,"name":"TearDownAt","signature":"func (c *gcePersistentDiskUnmounter) TearDownAt(dir string) error","file":"pkg/volume/gcepd/gce_pd.go","code":"// TearDownAt unmounts the bind mount\nfunc (c *gcePersistentDiskUnmounter) TearDownAt(dir string) error {\n\treturn mount.CleanupMountPoint(dir, c.mounter, false)\n}","line":{"from":464,"to":467}} {"id":100012339,"name":"GetPath","signature":"func (d *gcePersistentDiskDeleter) GetPath() string","file":"pkg/volume/gcepd/gce_pd.go","code":"func (d *gcePersistentDiskDeleter) GetPath() string {\n\treturn getPath(d.podUID, d.volName, d.plugin.host)\n}","line":{"from":475,"to":477}} {"id":100012340,"name":"Delete","signature":"func (d *gcePersistentDiskDeleter) Delete() error","file":"pkg/volume/gcepd/gce_pd.go","code":"func (d *gcePersistentDiskDeleter) Delete() error {\n\treturn d.manager.DeleteVolume(d)\n}","line":{"from":479,"to":481}} {"id":100012341,"name":"Provision","signature":"func (c *gcePersistentDiskProvisioner) Provision(selectedNode *v1.Node, allowedTopologies []v1.TopologySelectorTerm) (*v1.PersistentVolume, error)","file":"pkg/volume/gcepd/gce_pd.go","code":"func (c *gcePersistentDiskProvisioner) Provision(selectedNode *v1.Node, allowedTopologies []v1.TopologySelectorTerm) (*v1.PersistentVolume, error) {\n\tif !util.ContainsAllAccessModes(c.plugin.GetAccessModes(), c.options.PVC.Spec.AccessModes) {\n\t\treturn nil, fmt.Errorf(\"invalid AccessModes %v: only AccessModes %v are supported\", c.options.PVC.Spec.AccessModes, c.plugin.GetAccessModes())\n\t}\n\n\tvolumeID, sizeGB, labels, fstype, err := c.manager.CreateVolume(c, selectedNode, allowedTopologies)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif fstype == \"\" {\n\t\tfstype = \"ext4\"\n\t}\n\n\tvolumeMode := c.options.PVC.Spec.VolumeMode\n\tif volumeMode != nil \u0026\u0026 *volumeMode == v1.PersistentVolumeBlock {\n\t\t// Block volumes should not have any FSType\n\t\tfstype = \"\"\n\t}\n\n\tpv := \u0026v1.PersistentVolume{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: c.options.PVName,\n\t\t\tLabels: map[string]string{},\n\t\t\tAnnotations: map[string]string{\n\t\t\t\tutil.VolumeDynamicallyCreatedByKey: \"gce-pd-dynamic-provisioner\",\n\t\t\t},\n\t\t},\n\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\tPersistentVolumeReclaimPolicy: c.options.PersistentVolumeReclaimPolicy,\n\t\t\tAccessModes: c.options.PVC.Spec.AccessModes,\n\t\t\tCapacity: v1.ResourceList{\n\t\t\t\tv1.ResourceName(v1.ResourceStorage): resource.MustParse(fmt.Sprintf(\"%dGi\", sizeGB)),\n\t\t\t},\n\t\t\tVolumeMode: volumeMode,\n\t\t\tPersistentVolumeSource: v1.PersistentVolumeSource{\n\t\t\t\tGCEPersistentDisk: \u0026v1.GCEPersistentDiskVolumeSource{\n\t\t\t\t\tPDName: volumeID,\n\t\t\t\t\tPartition: 0,\n\t\t\t\t\tReadOnly: false,\n\t\t\t\t\tFSType: fstype,\n\t\t\t\t},\n\t\t\t},\n\t\t\tMountOptions: c.options.MountOptions,\n\t\t},\n\t}\n\tif len(c.options.PVC.Spec.AccessModes) == 0 {\n\t\tpv.Spec.AccessModes = c.plugin.GetAccessModes()\n\t}\n\n\trequirements := make([]v1.NodeSelectorRequirement, 0)\n\tif len(labels) != 0 {\n\t\tif pv.Labels == nil {\n\t\t\tpv.Labels = make(map[string]string)\n\t\t}\n\t\tfor k, v := range labels {\n\t\t\tpv.Labels[k] = v\n\t\t\tvar values []string\n\t\t\tif k == v1.LabelTopologyZone {\n\t\t\t\tvalues, err = volumehelpers.LabelZonesToList(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"failed to convert label string for Zone: %s to a List: %v\", v, err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tvalues = []string{v}\n\t\t\t}\n\t\t\trequirements = append(requirements, v1.NodeSelectorRequirement{Key: k, Operator: v1.NodeSelectorOpIn, Values: values})\n\t\t}\n\t}\n\n\tif len(requirements) \u003e 0 {\n\t\tpv.Spec.NodeAffinity = new(v1.VolumeNodeAffinity)\n\t\tpv.Spec.NodeAffinity.Required = new(v1.NodeSelector)\n\t\tpv.Spec.NodeAffinity.Required.NodeSelectorTerms = make([]v1.NodeSelectorTerm, 1)\n\t\tpv.Spec.NodeAffinity.Required.NodeSelectorTerms[0].MatchExpressions = requirements\n\t}\n\n\treturn pv, nil\n}","line":{"from":490,"to":568}} {"id":100012342,"name":"ConstructBlockVolumeSpec","signature":"func (plugin *gcePersistentDiskPlugin) ConstructBlockVolumeSpec(podUID types.UID, volumeName, mapPath string) (*volume.Spec, error)","file":"pkg/volume/gcepd/gce_pd_block.go","code":"func (plugin *gcePersistentDiskPlugin) ConstructBlockVolumeSpec(podUID types.UID, volumeName, mapPath string) (*volume.Spec, error) {\n\tpluginDir := plugin.host.GetVolumeDevicePluginDir(gcePersistentDiskPluginName)\n\tblkutil := volumepathhandler.NewBlockVolumePathHandler()\n\tglobalMapPathUUID, err := blkutil.FindGlobalMapPathUUIDFromPod(pluginDir, mapPath, podUID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tklog.V(5).Infof(\"globalMapPathUUID: %v, err: %v\", globalMapPathUUID, err)\n\n\tglobalMapPath := filepath.Dir(globalMapPathUUID)\n\tif len(globalMapPath) \u003c= 1 {\n\t\treturn nil, fmt.Errorf(\"failed to get volume plugin information from globalMapPathUUID: %v\", globalMapPathUUID)\n\t}\n\n\treturn getVolumeSpecFromGlobalMapPath(volumeName, globalMapPath)\n}","line":{"from":45,"to":60}} {"id":100012343,"name":"getVolumeSpecFromGlobalMapPath","signature":"func getVolumeSpecFromGlobalMapPath(volumeName, globalMapPath string) (*volume.Spec, error)","file":"pkg/volume/gcepd/gce_pd_block.go","code":"func getVolumeSpecFromGlobalMapPath(volumeName, globalMapPath string) (*volume.Spec, error) {\n\t// Get volume spec information from globalMapPath\n\t// globalMapPath example:\n\t// plugins/kubernetes.io/{PluginName}/{DefaultKubeletVolumeDevicesDirName}/{volumeID}\n\t// plugins/kubernetes.io/gce-pd/volumeDevices/vol-XXXXXX\n\tpdName := filepath.Base(globalMapPath)\n\tif len(pdName) \u003c= 1 {\n\t\treturn nil, fmt.Errorf(\"failed to get pd name from global path=%s\", globalMapPath)\n\t}\n\tblock := v1.PersistentVolumeBlock\n\tgceVolume := \u0026v1.PersistentVolume{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: volumeName,\n\t\t},\n\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\tPersistentVolumeSource: v1.PersistentVolumeSource{\n\t\t\t\tGCEPersistentDisk: \u0026v1.GCEPersistentDiskVolumeSource{\n\t\t\t\t\tPDName: pdName,\n\t\t\t\t},\n\t\t\t},\n\t\t\tVolumeMode: \u0026block,\n\t\t},\n\t}\n\n\treturn volume.NewSpecFromPersistentVolume(gceVolume, true), nil\n}","line":{"from":62,"to":87}} {"id":100012344,"name":"NewBlockVolumeMapper","signature":"func (plugin *gcePersistentDiskPlugin) NewBlockVolumeMapper(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.BlockVolumeMapper, error)","file":"pkg/volume/gcepd/gce_pd_block.go","code":"// NewBlockVolumeMapper creates a new volume.BlockVolumeMapper from an API specification.\nfunc (plugin *gcePersistentDiskPlugin) NewBlockVolumeMapper(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.BlockVolumeMapper, error) {\n\t// If this is called via GenerateUnmapDeviceFunc(), pod is nil.\n\t// Pass empty string as dummy uid since uid isn't used in the case.\n\tvar uid types.UID\n\tif pod != nil {\n\t\tuid = pod.UID\n\t}\n\n\treturn plugin.newBlockVolumeMapperInternal(spec, uid, \u0026GCEDiskUtil{}, plugin.host.GetMounter(plugin.GetPluginName()))\n}","line":{"from":89,"to":99}} {"id":100012345,"name":"newBlockVolumeMapperInternal","signature":"func (plugin *gcePersistentDiskPlugin) newBlockVolumeMapperInternal(spec *volume.Spec, podUID types.UID, manager pdManager, mounter mount.Interface) (volume.BlockVolumeMapper, error)","file":"pkg/volume/gcepd/gce_pd_block.go","code":"func (plugin *gcePersistentDiskPlugin) newBlockVolumeMapperInternal(spec *volume.Spec, podUID types.UID, manager pdManager, mounter mount.Interface) (volume.BlockVolumeMapper, error) {\n\tvolumeSource, readOnly, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpdName := volumeSource.PDName\n\tpartition := \"\"\n\tif volumeSource.Partition != 0 {\n\t\tpartition = strconv.Itoa(int(volumeSource.Partition))\n\t}\n\n\tmapper := \u0026gcePersistentDiskMapper{\n\t\tgcePersistentDisk: \u0026gcePersistentDisk{\n\t\t\tvolName: spec.Name(),\n\t\t\tpodUID: podUID,\n\t\t\tpdName: pdName,\n\t\t\tpartition: partition,\n\t\t\tmanager: manager,\n\t\t\tmounter: mounter,\n\t\t\tplugin: plugin,\n\t\t},\n\t\treadOnly: readOnly,\n\t}\n\n\tblockPath, err := mapper.GetGlobalMapPath(spec)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get device path: %v\", err)\n\t}\n\tmapper.MetricsProvider = volume.NewMetricsBlock(filepath.Join(blockPath, string(podUID)))\n\n\treturn mapper, nil\n}","line":{"from":101,"to":132}} {"id":100012346,"name":"NewBlockVolumeUnmapper","signature":"func (plugin *gcePersistentDiskPlugin) NewBlockVolumeUnmapper(volName string, podUID types.UID) (volume.BlockVolumeUnmapper, error)","file":"pkg/volume/gcepd/gce_pd_block.go","code":"func (plugin *gcePersistentDiskPlugin) NewBlockVolumeUnmapper(volName string, podUID types.UID) (volume.BlockVolumeUnmapper, error) {\n\treturn plugin.newUnmapperInternal(volName, podUID, \u0026GCEDiskUtil{})\n}","line":{"from":134,"to":136}} {"id":100012347,"name":"newUnmapperInternal","signature":"func (plugin *gcePersistentDiskPlugin) newUnmapperInternal(volName string, podUID types.UID, manager pdManager) (volume.BlockVolumeUnmapper, error)","file":"pkg/volume/gcepd/gce_pd_block.go","code":"func (plugin *gcePersistentDiskPlugin) newUnmapperInternal(volName string, podUID types.UID, manager pdManager) (volume.BlockVolumeUnmapper, error) {\n\treturn \u0026gcePersistentDiskUnmapper{\n\t\tgcePersistentDisk: \u0026gcePersistentDisk{\n\t\t\tvolName: volName,\n\t\t\tpodUID: podUID,\n\t\t\tpdName: volName,\n\t\t\tmanager: manager,\n\t\t\tplugin: plugin,\n\t\t}}, nil\n}","line":{"from":138,"to":147}} {"id":100012348,"name":"GetGlobalMapPath","signature":"func (pd *gcePersistentDisk) GetGlobalMapPath(spec *volume.Spec) (string, error)","file":"pkg/volume/gcepd/gce_pd_block.go","code":"// GetGlobalMapPath returns global map path and error\n// path: plugins/kubernetes.io/{PluginName}/volumeDevices/pdName\nfunc (pd *gcePersistentDisk) GetGlobalMapPath(spec *volume.Spec) (string, error) {\n\tvolumeSource, _, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Join(pd.plugin.host.GetVolumeDevicePluginDir(gcePersistentDiskPluginName), string(volumeSource.PDName)), nil\n}","line":{"from":162,"to":170}} {"id":100012349,"name":"GetPodDeviceMapPath","signature":"func (pd *gcePersistentDisk) GetPodDeviceMapPath() (string, string)","file":"pkg/volume/gcepd/gce_pd_block.go","code":"// GetPodDeviceMapPath returns pod device map path and volume name\n// path: pods/{podUid}/volumeDevices/kubernetes.io~aws\nfunc (pd *gcePersistentDisk) GetPodDeviceMapPath() (string, string) {\n\tname := gcePersistentDiskPluginName\n\treturn pd.plugin.host.GetPodVolumeDeviceDir(pd.podUID, utilstrings.EscapeQualifiedName(name)), pd.volName\n}","line":{"from":172,"to":177}} {"id":100012350,"name":"SupportsMetrics","signature":"func (pd *gcePersistentDisk) SupportsMetrics() bool","file":"pkg/volume/gcepd/gce_pd_block.go","code":"// SupportsMetrics returns true for gcePersistentDisk as it initializes the\n// MetricsProvider.\nfunc (pd *gcePersistentDisk) SupportsMetrics() bool {\n\treturn true\n}","line":{"from":179,"to":183}} {"id":100012351,"name":"DeleteVolume","signature":"func (util *GCEDiskUtil) DeleteVolume(d *gcePersistentDiskDeleter) error","file":"pkg/volume/gcepd/gce_util.go","code":"// DeleteVolume deletes a GCE PD\n// Returns: error\nfunc (util *GCEDiskUtil) DeleteVolume(d *gcePersistentDiskDeleter) error {\n\tcloud, err := getCloudProvider(d.gcePersistentDisk.plugin.host.GetCloudProvider())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = cloud.DeleteDisk(d.pdName); err != nil {\n\t\tklog.V(2).Infof(\"Error deleting GCE PD volume %s: %v\", d.pdName, err)\n\t\t// GCE cloud provider returns volume.deletedVolumeInUseError when\n\t\t// necessary, no handling needed here.\n\t\treturn err\n\t}\n\tklog.V(2).Infof(\"Successfully deleted GCE PD volume %s\", d.pdName)\n\treturn nil\n}","line":{"from":76,"to":92}} {"id":100012352,"name":"CreateVolume","signature":"func (util *GCEDiskUtil) CreateVolume(c *gcePersistentDiskProvisioner, node *v1.Node, allowedTopologies []v1.TopologySelectorTerm) (string, int, map[string]string, string, error)","file":"pkg/volume/gcepd/gce_util.go","code":"// CreateVolume creates a GCE PD.\n// Returns: gcePDName, volumeSizeGB, labels, fsType, error\nfunc (util *GCEDiskUtil) CreateVolume(c *gcePersistentDiskProvisioner, node *v1.Node, allowedTopologies []v1.TopologySelectorTerm) (string, int, map[string]string, string, error) {\n\tcloud, err := getCloudProvider(c.gcePersistentDisk.plugin.host.GetCloudProvider())\n\tif err != nil {\n\t\treturn \"\", 0, nil, \"\", err\n\t}\n\n\tname := volumeutil.GenerateVolumeName(c.options.ClusterName, c.options.PVName, 63) // GCE PD name can have up to 63 characters\n\tcapacity := c.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]\n\t// GCE PDs are allocated in chunks of GiBs\n\trequestGB, err := volumehelpers.RoundUpToGiB(capacity)\n\tif err != nil {\n\t\treturn \"\", 0, nil, \"\", err\n\t}\n\n\t// Apply Parameters.\n\t// Values for parameter \"replication-type\" are canonicalized to lower case.\n\t// Values for other parameters are case-insensitive, and we leave validation of these values\n\t// to the cloud provider.\n\tdiskType := \"\"\n\tconfiguredZone := \"\"\n\tvar configuredZones sets.String\n\tzonePresent := false\n\tzonesPresent := false\n\treplicationType := replicationTypeNone\n\tfstype := \"\"\n\tfor k, v := range c.options.Parameters {\n\t\tswitch strings.ToLower(k) {\n\t\tcase \"type\":\n\t\t\tdiskType = v\n\t\tcase \"zone\":\n\t\t\tzonePresent = true\n\t\t\tconfiguredZone = v\n\t\tcase \"zones\":\n\t\t\tzonesPresent = true\n\t\t\tconfiguredZones, err = volumehelpers.ZonesToSet(v)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", 0, nil, \"\", err\n\t\t\t}\n\t\tcase \"replication-type\":\n\t\t\treplicationType = strings.ToLower(v)\n\t\tcase volume.VolumeParameterFSType:\n\t\t\tfstype = v\n\t\tdefault:\n\t\t\treturn \"\", 0, nil, \"\", fmt.Errorf(\"invalid option %q for volume plugin %s\", k, c.plugin.GetPluginName())\n\t\t}\n\t}\n\n\t// TODO: implement PVC.Selector parsing\n\tif c.options.PVC.Spec.Selector != nil {\n\t\treturn \"\", 0, nil, \"\", fmt.Errorf(\"claim.Spec.Selector is not supported for dynamic provisioning on GCE\")\n\t}\n\n\tvar activezones sets.String\n\tactivezones, err = cloud.GetAllCurrentZones()\n\tif err != nil {\n\t\treturn \"\", 0, nil, \"\", err\n\t}\n\n\tvar disk *gcecloud.Disk\n\tswitch replicationType {\n\tcase replicationTypeRegionalPD:\n\t\tselectedZones, err := volumehelpers.SelectZonesForVolume(zonePresent, zonesPresent, configuredZone, configuredZones, activezones, node, allowedTopologies, c.options.PVC.Name, maxRegionalPDZones)\n\t\tif err != nil {\n\t\t\tklog.V(2).Infof(\"Error selecting zones for regional GCE PD volume: %v\", err)\n\t\t\treturn \"\", 0, nil, \"\", err\n\t\t}\n\t\tdisk, err = cloud.CreateRegionalDisk(\n\t\t\tname,\n\t\t\tdiskType,\n\t\t\tselectedZones,\n\t\t\trequestGB,\n\t\t\t*c.options.CloudTags)\n\t\tif err != nil {\n\t\t\tklog.V(2).Infof(\"Error creating regional GCE PD volume: %v\", err)\n\t\t\treturn \"\", 0, nil, \"\", err\n\t\t}\n\t\tklog.V(2).Infof(\"Successfully created Regional GCE PD volume %s\", name)\n\n\tcase replicationTypeNone:\n\t\tselectedZone, err := volumehelpers.SelectZoneForVolume(zonePresent, zonesPresent, configuredZone, configuredZones, activezones, node, allowedTopologies, c.options.PVC.Name)\n\t\tif err != nil {\n\t\t\treturn \"\", 0, nil, \"\", err\n\t\t}\n\t\tdisk, err = cloud.CreateDisk(\n\t\t\tname,\n\t\t\tdiskType,\n\t\t\tselectedZone,\n\t\t\trequestGB,\n\t\t\t*c.options.CloudTags)\n\t\tif err != nil {\n\t\t\tklog.V(2).Infof(\"Error creating single-zone GCE PD volume: %v\", err)\n\t\t\treturn \"\", 0, nil, \"\", err\n\t\t}\n\t\tklog.V(2).Infof(\"Successfully created single-zone GCE PD volume %s\", name)\n\n\tdefault:\n\t\treturn \"\", 0, nil, \"\", fmt.Errorf(\"replication-type of '%s' is not supported\", replicationType)\n\t}\n\n\tlabels, err := cloud.GetAutoLabelsForPD(disk)\n\tif err != nil {\n\t\t// We don't really want to leak the volume here...\n\t\tklog.Errorf(\"error getting labels for volume %q: %v\", name, err)\n\t}\n\n\treturn name, int(requestGB), labels, fstype, nil\n}","line":{"from":94,"to":202}} {"id":100012353,"name":"verifyDevicePath","signature":"func verifyDevicePath(devicePaths []string, sdBeforeSet sets.String, diskName string) (string, error)","file":"pkg/volume/gcepd/gce_util.go","code":"// Returns the first path that exists, or empty string if none exist.\nfunc verifyDevicePath(devicePaths []string, sdBeforeSet sets.String, diskName string) (string, error) {\n\tif err := udevadmChangeToNewDrives(sdBeforeSet); err != nil {\n\t\t// It's possible udevadm was called on other disks so it should not block this\n\t\t// call. If it did fail on this disk, then the devicePath will either\n\t\t// not exist or be wrong. If it's wrong, then the scsi_id check below will fail.\n\t\tklog.Errorf(\"udevadmChangeToNewDrives failed with: %v\", err)\n\t}\n\n\tfor _, path := range devicePaths {\n\t\tif pathExists, err := mount.PathExists(path); err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"error checking if path exists: %v\", err)\n\t\t} else if pathExists {\n\t\t\t// validate that the path actually resolves to the correct disk\n\t\t\tserial, err := getScsiSerial(path, diskName)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", fmt.Errorf(\"failed to get scsi serial %v\", err)\n\t\t\t}\n\t\t\tif serial != diskName {\n\t\t\t\t// The device link is not pointing to the correct device\n\t\t\t\t// Trigger udev on this device to try to fix the link\n\t\t\t\tif udevErr := udevadmChangeToDrive(path); udevErr != nil {\n\t\t\t\t\tklog.Errorf(\"udevadmChangeToDrive %q failed with: %v\", path, err)\n\t\t\t\t}\n\n\t\t\t\t// Return error to retry WaitForAttach and verifyDevicePath\n\t\t\t\treturn \"\", fmt.Errorf(\"scsi_id serial %q for device %q doesn't match disk %q\", serial, path, diskName)\n\t\t\t}\n\t\t\t// The device link is correct\n\t\t\treturn path, nil\n\t\t}\n\t}\n\n\treturn \"\", nil\n}","line":{"from":204,"to":238}} {"id":100012354,"name":"getScsiSerial","signature":"func getScsiSerial(devicePath, diskName string) (string, error)","file":"pkg/volume/gcepd/gce_util.go","code":"// Calls scsi_id on the given devicePath to get the serial number reported by that device.\nfunc getScsiSerial(devicePath, diskName string) (string, error) {\n\texists, err := utilpath.Exists(utilpath.CheckFollowSymlink, \"/lib/udev/scsi_id\")\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to check scsi_id existence: %v\", err)\n\t}\n\n\tif !exists {\n\t\tklog.V(6).Infof(\"scsi_id doesn't exist; skipping check for %v\", devicePath)\n\t\treturn diskName, nil\n\t}\n\n\tout, err := exec.New().Command(\n\t\t\"/lib/udev/scsi_id\",\n\t\t\"--page=0x83\",\n\t\t\"--whitelisted\",\n\t\tfmt.Sprintf(\"--device=%v\", devicePath)).CombinedOutput()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"scsi_id failed for device %q with %v\", devicePath, err)\n\t}\n\n\treturn parseScsiSerial(string(out))\n}","line":{"from":240,"to":262}} {"id":100012355,"name":"parseScsiSerial","signature":"func parseScsiSerial(output string) (string, error)","file":"pkg/volume/gcepd/gce_util.go","code":"// Parse the output returned by scsi_id and extract the serial number\nfunc parseScsiSerial(output string) (string, error) {\n\tsubstrings := scsiRegex.FindStringSubmatch(output)\n\tif substrings == nil {\n\t\treturn \"\", fmt.Errorf(\"scsi_id output cannot be parsed: %q\", output)\n\t}\n\n\treturn substrings[1], nil\n}","line":{"from":264,"to":272}} {"id":100012356,"name":"getDiskByIDPaths","signature":"func getDiskByIDPaths(pdName string, partition string) []string","file":"pkg/volume/gcepd/gce_util.go","code":"// Returns list of all /dev/disk/by-id/* paths for given PD.\nfunc getDiskByIDPaths(pdName string, partition string) []string {\n\tdevicePaths := []string{\n\t\tfilepath.Join(diskByIDPath, diskGooglePrefix+pdName),\n\t\tfilepath.Join(diskByIDPath, diskScsiGooglePrefix+pdName),\n\t}\n\n\tif partition != \"\" {\n\t\tfor i, path := range devicePaths {\n\t\t\tdevicePaths[i] = path + diskPartitionSuffix + partition\n\t\t}\n\t}\n\n\treturn devicePaths\n}","line":{"from":274,"to":288}} {"id":100012357,"name":"getCloudProvider","signature":"func getCloudProvider(cloudProvider cloudprovider.Interface) (*gcecloud.Cloud, error)","file":"pkg/volume/gcepd/gce_util.go","code":"// Return cloud provider\nfunc getCloudProvider(cloudProvider cloudprovider.Interface) (*gcecloud.Cloud, error) {\n\tvar err error\n\tfor numRetries := 0; numRetries \u003c maxRetries; numRetries++ {\n\t\tgceCloudProvider, ok := cloudProvider.(*gcecloud.Cloud)\n\t\tif !ok || gceCloudProvider == nil {\n\t\t\t// Retry on error. See issue #11321\n\t\t\tklog.Errorf(\"Failed to get GCE Cloud Provider. plugin.host.GetCloudProvider returned %v instead\", cloudProvider)\n\t\t\ttime.Sleep(errorSleepDuration)\n\t\t\tcontinue\n\t\t}\n\n\t\treturn gceCloudProvider, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"failed to get GCE GCECloudProvider with error %v\", err)\n}","line":{"from":290,"to":306}} {"id":100012358,"name":"udevadmChangeToNewDrives","signature":"func udevadmChangeToNewDrives(sdBeforeSet sets.String) error","file":"pkg/volume/gcepd/gce_util.go","code":"// Triggers the application of udev rules by calling \"udevadm trigger\n// --action=change\" for newly created \"/dev/sd*\" drives (exist only in\n// after set). This is workaround for Issue #7972. Once the underlying\n// issue has been resolved, this may be removed.\nfunc udevadmChangeToNewDrives(sdBeforeSet sets.String) error {\n\tsdAfter, err := filepath.Glob(diskSDPattern)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error filepath.Glob(\\\"%s\\\"): %v\\r\", diskSDPattern, err)\n\t}\n\n\tfor _, sd := range sdAfter {\n\t\tif !sdBeforeSet.Has(sd) {\n\t\t\treturn udevadmChangeToDrive(sd)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":308,"to":325}} {"id":100012359,"name":"udevadmChangeToDrive","signature":"func udevadmChangeToDrive(drivePath string) error","file":"pkg/volume/gcepd/gce_util.go","code":"// Calls \"udevadm trigger --action=change\" on the specified drive.\n// drivePath must be the block device path to trigger on, in the format \"/dev/sd*\", or a symlink to it.\n// This is workaround for Issue #7972. Once the underlying issue has been resolved, this may be removed.\nfunc udevadmChangeToDrive(drivePath string) error {\n\tklog.V(5).Infof(\"udevadmChangeToDrive: drive=%q\", drivePath)\n\n\t// Evaluate symlink, if any\n\tdrive, err := filepath.EvalSymlinks(drivePath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"udevadmChangeToDrive: filepath.EvalSymlinks(%q) failed with %v\", drivePath, err)\n\t}\n\tklog.V(5).Infof(\"udevadmChangeToDrive: symlink path is %q\", drive)\n\n\t// Check to make sure input is \"/dev/sd*\"\n\tif !strings.Contains(drive, diskSDPath) {\n\t\treturn fmt.Errorf(\"udevadmChangeToDrive: expected input in the form \\\"%s\\\" but drive is %q\", diskSDPattern, drive)\n\t}\n\n\t// Call \"udevadm trigger --action=change --property-match=DEVNAME=/dev/sd...\"\n\t_, err = exec.New().Command(\n\t\t\"udevadm\",\n\t\t\"trigger\",\n\t\t\"--action=change\",\n\t\tfmt.Sprintf(\"--property-match=DEVNAME=%s\", drive)).CombinedOutput()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"udevadmChangeToDrive: udevadm trigger failed for drive %q with %v\", drive, err)\n\t}\n\treturn nil\n}","line":{"from":327,"to":355}} {"id":100012360,"name":"isRegionalPD","signature":"func isRegionalPD(spec *volume.Spec) bool","file":"pkg/volume/gcepd/gce_util.go","code":"// Checks whether the given GCE PD volume spec is associated with a regional PD.\nfunc isRegionalPD(spec *volume.Spec) bool {\n\tif spec.PersistentVolume != nil {\n\t\tzonesLabel := spec.PersistentVolume.Labels[v1.LabelTopologyZone]\n\t\tif zonesLabel == \"\" {\n\t\t\tzonesLabel = spec.PersistentVolume.Labels[v1.LabelFailureDomainBetaZone]\n\t\t}\n\t\tzones := strings.Split(zonesLabel, cloudvolume.LabelMultiZoneDelimiter)\n\t\treturn len(zones) \u003e 1\n\t}\n\treturn false\n}","line":{"from":357,"to":368}} {"id":100012361,"name":"ProbeVolumePlugins","signature":"func ProbeVolumePlugins() []volume.VolumePlugin","file":"pkg/volume/git_repo/git_repo.go","code":"// This is the primary entrypoint for volume plugins.\nfunc ProbeVolumePlugins() []volume.VolumePlugin {\n\treturn []volume.VolumePlugin{\u0026gitRepoPlugin{nil}}\n}","line":{"from":33,"to":36}} {"id":100012362,"name":"wrappedVolumeSpec","signature":"func wrappedVolumeSpec() volume.Spec","file":"pkg/volume/git_repo/git_repo.go","code":"func wrappedVolumeSpec() volume.Spec {\n\treturn volume.Spec{\n\t\tVolume: \u0026v1.Volume{VolumeSource: v1.VolumeSource{EmptyDir: \u0026v1.EmptyDirVolumeSource{}}},\n\t}\n}","line":{"from":44,"to":48}} {"id":100012363,"name":"Init","signature":"func (plugin *gitRepoPlugin) Init(host volume.VolumeHost) error","file":"pkg/volume/git_repo/git_repo.go","code":"func (plugin *gitRepoPlugin) Init(host volume.VolumeHost) error {\n\tplugin.host = host\n\treturn nil\n}","line":{"from":54,"to":57}} {"id":100012364,"name":"GetPluginName","signature":"func (plugin *gitRepoPlugin) GetPluginName() string","file":"pkg/volume/git_repo/git_repo.go","code":"func (plugin *gitRepoPlugin) GetPluginName() string {\n\treturn gitRepoPluginName\n}","line":{"from":59,"to":61}} {"id":100012365,"name":"GetVolumeName","signature":"func (plugin *gitRepoPlugin) GetVolumeName(spec *volume.Spec) (string, error)","file":"pkg/volume/git_repo/git_repo.go","code":"func (plugin *gitRepoPlugin) GetVolumeName(spec *volume.Spec) (string, error) {\n\tvolumeSource, _ := getVolumeSource(spec)\n\tif volumeSource == nil {\n\t\treturn \"\", fmt.Errorf(\"Spec does not reference a Git repo volume type\")\n\t}\n\n\treturn fmt.Sprintf(\n\t\t\"%v:%v:%v\",\n\t\tvolumeSource.Repository,\n\t\tvolumeSource.Revision,\n\t\tvolumeSource.Directory), nil\n}","line":{"from":63,"to":74}} {"id":100012366,"name":"CanSupport","signature":"func (plugin *gitRepoPlugin) CanSupport(spec *volume.Spec) bool","file":"pkg/volume/git_repo/git_repo.go","code":"func (plugin *gitRepoPlugin) CanSupport(spec *volume.Spec) bool {\n\treturn spec.Volume != nil \u0026\u0026 spec.Volume.GitRepo != nil\n}","line":{"from":76,"to":78}} {"id":100012367,"name":"RequiresRemount","signature":"func (plugin *gitRepoPlugin) RequiresRemount(spec *volume.Spec) bool","file":"pkg/volume/git_repo/git_repo.go","code":"func (plugin *gitRepoPlugin) RequiresRemount(spec *volume.Spec) bool {\n\treturn false\n}","line":{"from":80,"to":82}} {"id":100012368,"name":"SupportsMountOption","signature":"func (plugin *gitRepoPlugin) SupportsMountOption() bool","file":"pkg/volume/git_repo/git_repo.go","code":"func (plugin *gitRepoPlugin) SupportsMountOption() bool {\n\treturn false\n}","line":{"from":84,"to":86}} {"id":100012369,"name":"SupportsBulkVolumeVerification","signature":"func (plugin *gitRepoPlugin) SupportsBulkVolumeVerification() bool","file":"pkg/volume/git_repo/git_repo.go","code":"func (plugin *gitRepoPlugin) SupportsBulkVolumeVerification() bool {\n\treturn false\n}","line":{"from":88,"to":90}} {"id":100012370,"name":"SupportsSELinuxContextMount","signature":"func (plugin *gitRepoPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/git_repo/git_repo.go","code":"func (plugin *gitRepoPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error) {\n\treturn false, nil\n}","line":{"from":92,"to":94}} {"id":100012371,"name":"NewMounter","signature":"func (plugin *gitRepoPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error)","file":"pkg/volume/git_repo/git_repo.go","code":"func (plugin *gitRepoPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error) {\n\tif err := validateVolume(spec.Volume.GitRepo); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026gitRepoVolumeMounter{\n\t\tgitRepoVolume: \u0026gitRepoVolume{\n\t\t\tvolName: spec.Name(),\n\t\t\tpodUID: pod.UID,\n\t\t\tplugin: plugin,\n\t\t},\n\t\tpod: *pod,\n\t\tsource: spec.Volume.GitRepo.Repository,\n\t\trevision: spec.Volume.GitRepo.Revision,\n\t\ttarget: spec.Volume.GitRepo.Directory,\n\t\texec: exec.New(),\n\t\topts: opts,\n\t}, nil\n}","line":{"from":96,"to":114}} {"id":100012372,"name":"NewUnmounter","signature":"func (plugin *gitRepoPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error)","file":"pkg/volume/git_repo/git_repo.go","code":"func (plugin *gitRepoPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error) {\n\treturn \u0026gitRepoVolumeUnmounter{\n\t\t\u0026gitRepoVolume{\n\t\t\tvolName: volName,\n\t\t\tpodUID: podUID,\n\t\t\tplugin: plugin,\n\t\t},\n\t}, nil\n}","line":{"from":116,"to":124}} {"id":100012373,"name":"ConstructVolumeSpec","signature":"func (plugin *gitRepoPlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error)","file":"pkg/volume/git_repo/git_repo.go","code":"func (plugin *gitRepoPlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error) {\n\tgitVolume := \u0026v1.Volume{\n\t\tName: volumeName,\n\t\tVolumeSource: v1.VolumeSource{\n\t\t\tGitRepo: \u0026v1.GitRepoVolumeSource{},\n\t\t},\n\t}\n\treturn volume.ReconstructedVolume{\n\t\tSpec: volume.NewSpecFromVolume(gitVolume),\n\t}, nil\n}","line":{"from":126,"to":136}} {"id":100012374,"name":"GetPath","signature":"func (gr *gitRepoVolume) GetPath() string","file":"pkg/volume/git_repo/git_repo.go","code":"func (gr *gitRepoVolume) GetPath() string {\n\tname := gitRepoPluginName\n\treturn gr.plugin.host.GetPodVolumeDir(gr.podUID, utilstrings.EscapeQualifiedName(name), gr.volName)\n}","line":{"from":149,"to":152}} {"id":100012375,"name":"GetAttributes","signature":"func (b *gitRepoVolumeMounter) GetAttributes() volume.Attributes","file":"pkg/volume/git_repo/git_repo.go","code":"func (b *gitRepoVolumeMounter) GetAttributes() volume.Attributes {\n\treturn volume.Attributes{\n\t\tReadOnly: false,\n\t\tManaged: true,\n\t\tSELinuxRelabel: true, // xattr change should be okay, TODO: double check\n\t}\n}","line":{"from":168,"to":174}} {"id":100012376,"name":"SetUp","signature":"func (b *gitRepoVolumeMounter) SetUp(mounterArgs volume.MounterArgs) error","file":"pkg/volume/git_repo/git_repo.go","code":"// SetUp creates new directory and clones a git repo.\nfunc (b *gitRepoVolumeMounter) SetUp(mounterArgs volume.MounterArgs) error {\n\treturn b.SetUpAt(b.GetPath(), mounterArgs)\n}","line":{"from":176,"to":179}} {"id":100012377,"name":"SetUpAt","signature":"func (b *gitRepoVolumeMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error","file":"pkg/volume/git_repo/git_repo.go","code":"// SetUpAt creates new directory and clones a git repo.\nfunc (b *gitRepoVolumeMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {\n\tif volumeutil.IsReady(b.getMetaDir()) {\n\t\treturn nil\n\t}\n\n\t// Wrap EmptyDir, let it do the setup.\n\twrapped, err := b.plugin.host.NewWrapperMounter(b.volName, wrappedVolumeSpec(), \u0026b.pod, b.opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := wrapped.SetUpAt(dir, mounterArgs); err != nil {\n\t\treturn err\n\t}\n\n\targs := []string{\"clone\", \"--\", b.source}\n\n\tif len(b.target) != 0 {\n\t\targs = append(args, b.target)\n\t}\n\tif output, err := b.execCommand(\"git\", args, dir); err != nil {\n\t\treturn fmt.Errorf(\"failed to exec 'git %s': %s: %v\",\n\t\t\tstrings.Join(args, \" \"), output, err)\n\t}\n\n\tfiles, err := ioutil.ReadDir(dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(b.revision) == 0 {\n\t\t// Done!\n\t\tvolumeutil.SetReady(b.getMetaDir())\n\t\treturn nil\n\t}\n\n\tvar subdir string\n\n\tswitch {\n\tcase len(b.target) != 0 \u0026\u0026 filepath.Clean(b.target) == \".\":\n\t\t// if target dir is '.', use the current dir\n\t\tsubdir = filepath.Join(dir)\n\tcase len(files) == 1:\n\t\t// if target is not '.', use the generated folder\n\t\tsubdir = filepath.Join(dir, files[0].Name())\n\tdefault:\n\t\t// if target is not '.', but generated many files, it's wrong\n\t\treturn fmt.Errorf(\"unexpected directory contents: %v\", files)\n\t}\n\n\tif output, err := b.execCommand(\"git\", []string{\"checkout\", b.revision}, subdir); err != nil {\n\t\treturn fmt.Errorf(\"failed to exec 'git checkout %s': %s: %v\", b.revision, output, err)\n\t}\n\tif output, err := b.execCommand(\"git\", []string{\"reset\", \"--hard\"}, subdir); err != nil {\n\t\treturn fmt.Errorf(\"failed to exec 'git reset --hard': %s: %v\", output, err)\n\t}\n\n\tvolume.SetVolumeOwnership(b, dir, mounterArgs.FsGroup, nil /*fsGroupChangePolicy*/, volumeutil.FSGroupCompleteHook(b.plugin, nil))\n\n\tvolumeutil.SetReady(b.getMetaDir())\n\treturn nil\n}","line":{"from":181,"to":242}} {"id":100012378,"name":"getMetaDir","signature":"func (b *gitRepoVolumeMounter) getMetaDir() string","file":"pkg/volume/git_repo/git_repo.go","code":"func (b *gitRepoVolumeMounter) getMetaDir() string {\n\treturn filepath.Join(b.plugin.host.GetPodPluginDir(b.podUID, utilstrings.EscapeQualifiedName(gitRepoPluginName)), b.volName)\n}","line":{"from":244,"to":246}} {"id":100012379,"name":"execCommand","signature":"func (b *gitRepoVolumeMounter) execCommand(command string, args []string, dir string) ([]byte, error)","file":"pkg/volume/git_repo/git_repo.go","code":"func (b *gitRepoVolumeMounter) execCommand(command string, args []string, dir string) ([]byte, error) {\n\tcmd := b.exec.Command(command, args...)\n\tcmd.SetDir(dir)\n\treturn cmd.CombinedOutput()\n}","line":{"from":248,"to":252}} {"id":100012380,"name":"validateVolume","signature":"func validateVolume(src *v1.GitRepoVolumeSource) error","file":"pkg/volume/git_repo/git_repo.go","code":"func validateVolume(src *v1.GitRepoVolumeSource) error {\n\tif err := validateNonFlagArgument(src.Repository, \"repository\"); err != nil {\n\t\treturn err\n\t}\n\tif err := validateNonFlagArgument(src.Revision, \"revision\"); err != nil {\n\t\treturn err\n\t}\n\tif err := validateNonFlagArgument(src.Directory, \"directory\"); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":254,"to":265}} {"id":100012381,"name":"TearDown","signature":"func (c *gitRepoVolumeUnmounter) TearDown() error","file":"pkg/volume/git_repo/git_repo.go","code":"// TearDown simply deletes everything in the directory.\nfunc (c *gitRepoVolumeUnmounter) TearDown() error {\n\treturn c.TearDownAt(c.GetPath())\n}","line":{"from":274,"to":277}} {"id":100012382,"name":"TearDownAt","signature":"func (c *gitRepoVolumeUnmounter) TearDownAt(dir string) error","file":"pkg/volume/git_repo/git_repo.go","code":"// TearDownAt simply deletes everything in the directory.\nfunc (c *gitRepoVolumeUnmounter) TearDownAt(dir string) error {\n\treturn volumeutil.UnmountViaEmptyDir(dir, c.plugin.host, c.volName, wrappedVolumeSpec(), c.podUID)\n}","line":{"from":279,"to":282}} {"id":100012383,"name":"getVolumeSource","signature":"func getVolumeSource(spec *volume.Spec) (*v1.GitRepoVolumeSource, bool)","file":"pkg/volume/git_repo/git_repo.go","code":"func getVolumeSource(spec *volume.Spec) (*v1.GitRepoVolumeSource, bool) {\n\tvar readOnly bool\n\tvar volumeSource *v1.GitRepoVolumeSource\n\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.GitRepo != nil {\n\t\tvolumeSource = spec.Volume.GitRepo\n\t\treadOnly = spec.ReadOnly\n\t}\n\n\treturn volumeSource, readOnly\n}","line":{"from":284,"to":294}} {"id":100012384,"name":"validateNonFlagArgument","signature":"func validateNonFlagArgument(arg, argName string) error","file":"pkg/volume/git_repo/git_repo.go","code":"func validateNonFlagArgument(arg, argName string) error {\n\tif len(arg) \u003e 0 \u0026\u0026 arg[0] == '-' {\n\t\treturn fmt.Errorf(\"%q is an invalid value for %s\", arg, argName)\n\t}\n\treturn nil\n}","line":{"from":296,"to":301}} {"id":100012385,"name":"ProbeVolumePlugins","signature":"func ProbeVolumePlugins(volumeConfig volume.VolumeConfig) []volume.VolumePlugin","file":"pkg/volume/hostpath/host_path.go","code":"// ProbeVolumePlugins is the primary entrypoint for volume plugins.\n// The volumeConfig arg provides the ability to configure volume behavior. It is implemented as a pointer to allow nils.\n// The hostPathPlugin is used to store the volumeConfig and give it, when needed, to the func that Recycles.\n// Tests that exercise recycling should not use this func but instead use ProbeRecyclablePlugins() to override default behavior.\nfunc ProbeVolumePlugins(volumeConfig volume.VolumeConfig) []volume.VolumePlugin {\n\treturn []volume.VolumePlugin{\n\t\t\u0026hostPathPlugin{\n\t\t\thost: nil,\n\t\t\tconfig: volumeConfig,\n\t\t},\n\t}\n}","line":{"from":40,"to":51}} {"id":100012386,"name":"FakeProbeVolumePlugins","signature":"func FakeProbeVolumePlugins(volumeConfig volume.VolumeConfig) []volume.VolumePlugin","file":"pkg/volume/hostpath/host_path.go","code":"func FakeProbeVolumePlugins(volumeConfig volume.VolumeConfig) []volume.VolumePlugin {\n\treturn []volume.VolumePlugin{\n\t\t\u0026hostPathPlugin{\n\t\t\thost: nil,\n\t\t\tconfig: volumeConfig,\n\t\t\tnoTypeChecker: true,\n\t\t},\n\t}\n}","line":{"from":53,"to":61}} {"id":100012387,"name":"Init","signature":"func (plugin *hostPathPlugin) Init(host volume.VolumeHost) error","file":"pkg/volume/hostpath/host_path.go","code":"func (plugin *hostPathPlugin) Init(host volume.VolumeHost) error {\n\tplugin.host = host\n\treturn nil\n}","line":{"from":79,"to":82}} {"id":100012388,"name":"GetPluginName","signature":"func (plugin *hostPathPlugin) GetPluginName() string","file":"pkg/volume/hostpath/host_path.go","code":"func (plugin *hostPathPlugin) GetPluginName() string {\n\treturn hostPathPluginName\n}","line":{"from":84,"to":86}} {"id":100012389,"name":"GetVolumeName","signature":"func (plugin *hostPathPlugin) GetVolumeName(spec *volume.Spec) (string, error)","file":"pkg/volume/hostpath/host_path.go","code":"func (plugin *hostPathPlugin) GetVolumeName(spec *volume.Spec) (string, error) {\n\tvolumeSource, _, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn volumeSource.Path, nil\n}","line":{"from":88,"to":95}} {"id":100012390,"name":"CanSupport","signature":"func (plugin *hostPathPlugin) CanSupport(spec *volume.Spec) bool","file":"pkg/volume/hostpath/host_path.go","code":"func (plugin *hostPathPlugin) CanSupport(spec *volume.Spec) bool {\n\treturn (spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.HostPath != nil) ||\n\t\t(spec.Volume != nil \u0026\u0026 spec.Volume.HostPath != nil)\n}","line":{"from":97,"to":100}} {"id":100012391,"name":"RequiresRemount","signature":"func (plugin *hostPathPlugin) RequiresRemount(spec *volume.Spec) bool","file":"pkg/volume/hostpath/host_path.go","code":"func (plugin *hostPathPlugin) RequiresRemount(spec *volume.Spec) bool {\n\treturn false\n}","line":{"from":102,"to":104}} {"id":100012392,"name":"SupportsMountOption","signature":"func (plugin *hostPathPlugin) SupportsMountOption() bool","file":"pkg/volume/hostpath/host_path.go","code":"func (plugin *hostPathPlugin) SupportsMountOption() bool {\n\treturn false\n}","line":{"from":106,"to":108}} {"id":100012393,"name":"SupportsBulkVolumeVerification","signature":"func (plugin *hostPathPlugin) SupportsBulkVolumeVerification() bool","file":"pkg/volume/hostpath/host_path.go","code":"func (plugin *hostPathPlugin) SupportsBulkVolumeVerification() bool {\n\treturn false\n}","line":{"from":110,"to":112}} {"id":100012394,"name":"SupportsSELinuxContextMount","signature":"func (plugin *hostPathPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/hostpath/host_path.go","code":"func (plugin *hostPathPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error) {\n\treturn false, nil\n}","line":{"from":114,"to":116}} {"id":100012395,"name":"GetAccessModes","signature":"func (plugin *hostPathPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode","file":"pkg/volume/hostpath/host_path.go","code":"func (plugin *hostPathPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode {\n\treturn []v1.PersistentVolumeAccessMode{\n\t\tv1.ReadWriteOnce,\n\t}\n}","line":{"from":118,"to":122}} {"id":100012396,"name":"NewMounter","signature":"func (plugin *hostPathPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error)","file":"pkg/volume/hostpath/host_path.go","code":"func (plugin *hostPathPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error) {\n\thostPathVolumeSource, readOnly, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpath := hostPathVolumeSource.Path\n\tpathType := new(v1.HostPathType)\n\tif hostPathVolumeSource.Type == nil {\n\t\t*pathType = v1.HostPathUnset\n\t} else {\n\t\tpathType = hostPathVolumeSource.Type\n\t}\n\tkvh, ok := plugin.host.(volume.KubeletVolumeHost)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"plugin volume host does not implement KubeletVolumeHost interface\")\n\t}\n\treturn \u0026hostPathMounter{\n\t\thostPath: \u0026hostPath{path: path, pathType: pathType},\n\t\treadOnly: readOnly,\n\t\tmounter: plugin.host.GetMounter(plugin.GetPluginName()),\n\t\thu: kvh.GetHostUtil(),\n\t\tnoTypeChecker: plugin.noTypeChecker,\n\t}, nil\n}","line":{"from":124,"to":148}} {"id":100012397,"name":"NewUnmounter","signature":"func (plugin *hostPathPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error)","file":"pkg/volume/hostpath/host_path.go","code":"func (plugin *hostPathPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error) {\n\treturn \u0026hostPathUnmounter{\u0026hostPath{\n\t\tpath: \"\",\n\t}}, nil\n}","line":{"from":150,"to":154}} {"id":100012398,"name":"Recycle","signature":"func (plugin *hostPathPlugin) Recycle(pvName string, spec *volume.Spec, eventRecorder recyclerclient.RecycleEventRecorder) error","file":"pkg/volume/hostpath/host_path.go","code":"// Recycle recycles/scrubs clean a HostPath volume.\n// Recycle blocks until the pod has completed or any error occurs.\n// HostPath recycling only works in single node clusters and is meant for testing purposes only.\nfunc (plugin *hostPathPlugin) Recycle(pvName string, spec *volume.Spec, eventRecorder recyclerclient.RecycleEventRecorder) error {\n\tif spec.PersistentVolume == nil || spec.PersistentVolume.Spec.HostPath == nil {\n\t\treturn fmt.Errorf(\"spec.PersistentVolume.Spec.HostPath is nil\")\n\t}\n\n\tpod := plugin.config.RecyclerPodTemplate\n\ttimeout := util.CalculateTimeoutForVolume(plugin.config.RecyclerMinimumTimeout, plugin.config.RecyclerTimeoutIncrement, spec.PersistentVolume)\n\t// overrides\n\tpod.Spec.ActiveDeadlineSeconds = \u0026timeout\n\tpod.Spec.Volumes[0].VolumeSource = v1.VolumeSource{\n\t\tHostPath: \u0026v1.HostPathVolumeSource{\n\t\t\tPath: spec.PersistentVolume.Spec.HostPath.Path,\n\t\t},\n\t}\n\treturn recyclerclient.RecycleVolumeByWatchingPodUntilCompletion(pvName, pod, plugin.host.GetKubeClient(), eventRecorder)\n}","line":{"from":156,"to":174}} {"id":100012399,"name":"NewDeleter","signature":"func (plugin *hostPathPlugin) NewDeleter(logger klog.Logger, spec *volume.Spec) (volume.Deleter, error)","file":"pkg/volume/hostpath/host_path.go","code":"func (plugin *hostPathPlugin) NewDeleter(logger klog.Logger, spec *volume.Spec) (volume.Deleter, error) {\n\treturn newDeleter(spec, plugin.host)\n}","line":{"from":176,"to":178}} {"id":100012400,"name":"NewProvisioner","signature":"func (plugin *hostPathPlugin) NewProvisioner(logger klog.Logger, options volume.VolumeOptions) (volume.Provisioner, error)","file":"pkg/volume/hostpath/host_path.go","code":"func (plugin *hostPathPlugin) NewProvisioner(logger klog.Logger, options volume.VolumeOptions) (volume.Provisioner, error) {\n\tif !plugin.config.ProvisioningEnabled {\n\t\treturn nil, fmt.Errorf(\"provisioning in volume plugin %q is disabled\", plugin.GetPluginName())\n\t}\n\treturn newProvisioner(options, plugin.host, plugin)\n}","line":{"from":180,"to":185}} {"id":100012401,"name":"ConstructVolumeSpec","signature":"func (plugin *hostPathPlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error)","file":"pkg/volume/hostpath/host_path.go","code":"func (plugin *hostPathPlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error) {\n\thostPathVolume := \u0026v1.Volume{\n\t\tName: volumeName,\n\t\tVolumeSource: v1.VolumeSource{\n\t\t\tHostPath: \u0026v1.HostPathVolumeSource{\n\t\t\t\tPath: volumeName,\n\t\t\t},\n\t\t},\n\t}\n\treturn volume.ReconstructedVolume{\n\t\tSpec: volume.NewSpecFromVolume(hostPathVolume),\n\t}, nil\n}","line":{"from":187,"to":199}} {"id":100012402,"name":"newDeleter","signature":"func newDeleter(spec *volume.Spec, host volume.VolumeHost) (volume.Deleter, error)","file":"pkg/volume/hostpath/host_path.go","code":"func newDeleter(spec *volume.Spec, host volume.VolumeHost) (volume.Deleter, error) {\n\tif spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.HostPath == nil {\n\t\treturn nil, fmt.Errorf(\"spec.PersistentVolumeSource.HostPath is nil\")\n\t}\n\tpath := spec.PersistentVolume.Spec.HostPath.Path\n\treturn \u0026hostPathDeleter{name: spec.Name(), path: path, host: host}, nil\n}","line":{"from":201,"to":207}} {"id":100012403,"name":"newProvisioner","signature":"func newProvisioner(options volume.VolumeOptions, host volume.VolumeHost, plugin *hostPathPlugin) (volume.Provisioner, error)","file":"pkg/volume/hostpath/host_path.go","code":"func newProvisioner(options volume.VolumeOptions, host volume.VolumeHost, plugin *hostPathPlugin) (volume.Provisioner, error) {\n\treturn \u0026hostPathProvisioner{options: options, host: host, plugin: plugin, basePath: \"hostpath_pv\"}, nil\n}","line":{"from":209,"to":211}} {"id":100012404,"name":"GetPath","signature":"func (hp *hostPath) GetPath() string","file":"pkg/volume/hostpath/host_path.go","code":"func (hp *hostPath) GetPath() string {\n\treturn hp.path\n}","line":{"from":221,"to":223}} {"id":100012405,"name":"GetAttributes","signature":"func (b *hostPathMounter) GetAttributes() volume.Attributes","file":"pkg/volume/hostpath/host_path.go","code":"func (b *hostPathMounter) GetAttributes() volume.Attributes {\n\treturn volume.Attributes{\n\t\tReadOnly: b.readOnly,\n\t\tManaged: false,\n\t\tSELinuxRelabel: false,\n\t}\n}","line":{"from":235,"to":241}} {"id":100012406,"name":"SetUp","signature":"func (b *hostPathMounter) SetUp(mounterArgs volume.MounterArgs) error","file":"pkg/volume/hostpath/host_path.go","code":"// SetUp does nothing.\nfunc (b *hostPathMounter) SetUp(mounterArgs volume.MounterArgs) error {\n\terr := validation.ValidatePathNoBacksteps(b.GetPath())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"invalid HostPath `%s`: %v\", b.GetPath(), err)\n\t}\n\n\tif *b.pathType == v1.HostPathUnset {\n\t\treturn nil\n\t}\n\tif b.noTypeChecker {\n\t\treturn nil\n\t} else {\n\t\treturn checkType(b.GetPath(), b.pathType, b.hu)\n\t}\n}","line":{"from":243,"to":258}} {"id":100012407,"name":"SetUpAt","signature":"func (b *hostPathMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error","file":"pkg/volume/hostpath/host_path.go","code":"// SetUpAt does not make sense for host paths - probably programmer error.\nfunc (b *hostPathMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {\n\treturn fmt.Errorf(\"SetUpAt() does not make sense for host paths\")\n}","line":{"from":260,"to":263}} {"id":100012408,"name":"GetPath","signature":"func (b *hostPathMounter) GetPath() string","file":"pkg/volume/hostpath/host_path.go","code":"func (b *hostPathMounter) GetPath() string {\n\treturn b.path\n}","line":{"from":265,"to":267}} {"id":100012409,"name":"TearDown","signature":"func (c *hostPathUnmounter) TearDown() error","file":"pkg/volume/hostpath/host_path.go","code":"// TearDown does nothing.\nfunc (c *hostPathUnmounter) TearDown() error {\n\treturn nil\n}","line":{"from":275,"to":278}} {"id":100012410,"name":"TearDownAt","signature":"func (c *hostPathUnmounter) TearDownAt(dir string) error","file":"pkg/volume/hostpath/host_path.go","code":"// TearDownAt does not make sense for host paths - probably programmer error.\nfunc (c *hostPathUnmounter) TearDownAt(dir string) error {\n\treturn fmt.Errorf(\"TearDownAt() does not make sense for host paths\")\n}","line":{"from":280,"to":283}} {"id":100012411,"name":"Provision","signature":"func (r *hostPathProvisioner) Provision(selectedNode *v1.Node, allowedTopologies []v1.TopologySelectorTerm) (*v1.PersistentVolume, error)","file":"pkg/volume/hostpath/host_path.go","code":"// Create for hostPath simply creates a local /tmp/%/%s directory as a new PersistentVolume, default /tmp/hostpath_pv/%s.\n// This Provisioner is meant for development and testing only and WILL NOT WORK in a multi-node cluster.\nfunc (r *hostPathProvisioner) Provision(selectedNode *v1.Node, allowedTopologies []v1.TopologySelectorTerm) (*v1.PersistentVolume, error) {\n\tif util.CheckPersistentVolumeClaimModeBlock(r.options.PVC) {\n\t\treturn nil, fmt.Errorf(\"%s does not support block volume provisioning\", r.plugin.GetPluginName())\n\t}\n\n\tfullpath := fmt.Sprintf(\"/tmp/%s/%s\", r.basePath, uuid.NewUUID())\n\n\tcapacity := r.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]\n\tpv := \u0026v1.PersistentVolume{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: r.options.PVName,\n\t\t\tAnnotations: map[string]string{\n\t\t\t\tutil.VolumeDynamicallyCreatedByKey: \"hostpath-dynamic-provisioner\",\n\t\t\t},\n\t\t},\n\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\tPersistentVolumeReclaimPolicy: r.options.PersistentVolumeReclaimPolicy,\n\t\t\tAccessModes: r.options.PVC.Spec.AccessModes,\n\t\t\tCapacity: v1.ResourceList{\n\t\t\t\tv1.ResourceName(v1.ResourceStorage): capacity,\n\t\t\t},\n\t\t\tPersistentVolumeSource: v1.PersistentVolumeSource{\n\t\t\t\tHostPath: \u0026v1.HostPathVolumeSource{\n\t\t\t\t\tPath: fullpath,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tif len(r.options.PVC.Spec.AccessModes) == 0 {\n\t\tpv.Spec.AccessModes = r.plugin.GetAccessModes()\n\t}\n\n\tif err := os.MkdirAll(pv.Spec.HostPath.Path, 0750); err != nil {\n\t\treturn nil, err\n\t}\n\tif selinux.GetEnabled() {\n\t\terr := selinux.SetFileLabel(pv.Spec.HostPath.Path, config.KubeletContainersSharedSELinuxLabel)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to set selinux label for %q: %v\", pv.Spec.HostPath.Path, err)\n\t\t}\n\t}\n\n\treturn pv, nil\n}","line":{"from":294,"to":339}} {"id":100012412,"name":"GetPath","signature":"func (r *hostPathDeleter) GetPath() string","file":"pkg/volume/hostpath/host_path.go","code":"func (r *hostPathDeleter) GetPath() string {\n\treturn r.path\n}","line":{"from":350,"to":352}} {"id":100012413,"name":"Delete","signature":"func (r *hostPathDeleter) Delete() error","file":"pkg/volume/hostpath/host_path.go","code":"// Delete for hostPath removes the local directory so long as it is beneath /tmp/*.\n// THIS IS FOR TESTING AND LOCAL DEVELOPMENT ONLY! This message should scare you away from using\n// this deleter for anything other than development and testing.\nfunc (r *hostPathDeleter) Delete() error {\n\tregexp := regexp.MustCompile(\"/tmp/.+\")\n\tif !regexp.MatchString(r.GetPath()) {\n\t\treturn fmt.Errorf(\"host_path deleter only supports /tmp/.+ but received provided %s\", r.GetPath())\n\t}\n\treturn os.RemoveAll(r.GetPath())\n}","line":{"from":354,"to":363}} {"id":100012414,"name":"getVolumeSource","signature":"func getVolumeSource(spec *volume.Spec) (*v1.HostPathVolumeSource, bool, error)","file":"pkg/volume/hostpath/host_path.go","code":"func getVolumeSource(spec *volume.Spec) (*v1.HostPathVolumeSource, bool, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.HostPath != nil {\n\t\treturn spec.Volume.HostPath, spec.ReadOnly, nil\n\t} else if spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.HostPath != nil {\n\t\treturn spec.PersistentVolume.Spec.HostPath, spec.ReadOnly, nil\n\t}\n\n\treturn nil, false, fmt.Errorf(\"spec does not reference an HostPath volume type\")\n}","line":{"from":365,"to":374}} {"id":100012415,"name":"Exists","signature":"func (ftc *fileTypeChecker) Exists() bool","file":"pkg/volume/hostpath/host_path.go","code":"func (ftc *fileTypeChecker) Exists() bool {\n\texists, err := ftc.hu.PathExists(ftc.path)\n\treturn exists \u0026\u0026 err == nil\n}","line":{"from":393,"to":396}} {"id":100012416,"name":"IsFile","signature":"func (ftc *fileTypeChecker) IsFile() bool","file":"pkg/volume/hostpath/host_path.go","code":"func (ftc *fileTypeChecker) IsFile() bool {\n\tif !ftc.Exists() {\n\t\treturn false\n\t}\n\tpathType, err := ftc.hu.GetFileType(ftc.path)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn string(pathType) == string(v1.HostPathFile)\n}","line":{"from":398,"to":407}} {"id":100012417,"name":"MakeFile","signature":"func (ftc *fileTypeChecker) MakeFile() error","file":"pkg/volume/hostpath/host_path.go","code":"func (ftc *fileTypeChecker) MakeFile() error {\n\treturn makeFile(ftc.path)\n}","line":{"from":409,"to":411}} {"id":100012418,"name":"IsDir","signature":"func (ftc *fileTypeChecker) IsDir() bool","file":"pkg/volume/hostpath/host_path.go","code":"func (ftc *fileTypeChecker) IsDir() bool {\n\tif !ftc.Exists() {\n\t\treturn false\n\t}\n\tpathType, err := ftc.hu.GetFileType(ftc.path)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn string(pathType) == string(v1.HostPathDirectory)\n}","line":{"from":413,"to":422}} {"id":100012419,"name":"MakeDir","signature":"func (ftc *fileTypeChecker) MakeDir() error","file":"pkg/volume/hostpath/host_path.go","code":"func (ftc *fileTypeChecker) MakeDir() error {\n\treturn makeDir(ftc.path)\n}","line":{"from":424,"to":426}} {"id":100012420,"name":"IsBlock","signature":"func (ftc *fileTypeChecker) IsBlock() bool","file":"pkg/volume/hostpath/host_path.go","code":"func (ftc *fileTypeChecker) IsBlock() bool {\n\tblkDevType, err := ftc.hu.GetFileType(ftc.path)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn string(blkDevType) == string(v1.HostPathBlockDev)\n}","line":{"from":428,"to":434}} {"id":100012421,"name":"IsChar","signature":"func (ftc *fileTypeChecker) IsChar() bool","file":"pkg/volume/hostpath/host_path.go","code":"func (ftc *fileTypeChecker) IsChar() bool {\n\tcharDevType, err := ftc.hu.GetFileType(ftc.path)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn string(charDevType) == string(v1.HostPathCharDev)\n}","line":{"from":436,"to":442}} {"id":100012422,"name":"IsSocket","signature":"func (ftc *fileTypeChecker) IsSocket() bool","file":"pkg/volume/hostpath/host_path.go","code":"func (ftc *fileTypeChecker) IsSocket() bool {\n\tsocketType, err := ftc.hu.GetFileType(ftc.path)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn string(socketType) == string(v1.HostPathSocket)\n}","line":{"from":444,"to":450}} {"id":100012423,"name":"GetPath","signature":"func (ftc *fileTypeChecker) GetPath() string","file":"pkg/volume/hostpath/host_path.go","code":"func (ftc *fileTypeChecker) GetPath() string {\n\treturn ftc.path\n}","line":{"from":452,"to":454}} {"id":100012424,"name":"newFileTypeChecker","signature":"func newFileTypeChecker(path string, hu hostutil.HostUtils) hostPathTypeChecker","file":"pkg/volume/hostpath/host_path.go","code":"func newFileTypeChecker(path string, hu hostutil.HostUtils) hostPathTypeChecker {\n\treturn \u0026fileTypeChecker{path: path, hu: hu}\n}","line":{"from":456,"to":458}} {"id":100012425,"name":"checkType","signature":"func checkType(path string, pathType *v1.HostPathType, hu hostutil.HostUtils) error","file":"pkg/volume/hostpath/host_path.go","code":"// checkType checks whether the given path is the exact pathType\nfunc checkType(path string, pathType *v1.HostPathType, hu hostutil.HostUtils) error {\n\treturn checkTypeInternal(newFileTypeChecker(path, hu), pathType)\n}","line":{"from":460,"to":463}} {"id":100012426,"name":"checkTypeInternal","signature":"func checkTypeInternal(ftc hostPathTypeChecker, pathType *v1.HostPathType) error","file":"pkg/volume/hostpath/host_path.go","code":"func checkTypeInternal(ftc hostPathTypeChecker, pathType *v1.HostPathType) error {\n\tswitch *pathType {\n\tcase v1.HostPathDirectoryOrCreate:\n\t\tif !ftc.Exists() {\n\t\t\treturn ftc.MakeDir()\n\t\t}\n\t\tfallthrough\n\tcase v1.HostPathDirectory:\n\t\tif !ftc.IsDir() {\n\t\t\treturn fmt.Errorf(\"hostPath type check failed: %s is not a directory\", ftc.GetPath())\n\t\t}\n\tcase v1.HostPathFileOrCreate:\n\t\tif !ftc.Exists() {\n\t\t\treturn ftc.MakeFile()\n\t\t}\n\t\tfallthrough\n\tcase v1.HostPathFile:\n\t\tif !ftc.IsFile() {\n\t\t\treturn fmt.Errorf(\"hostPath type check failed: %s is not a file\", ftc.GetPath())\n\t\t}\n\tcase v1.HostPathSocket:\n\t\tif !ftc.IsSocket() {\n\t\t\treturn fmt.Errorf(\"hostPath type check failed: %s is not a socket file\", ftc.GetPath())\n\t\t}\n\tcase v1.HostPathCharDev:\n\t\tif !ftc.IsChar() {\n\t\t\treturn fmt.Errorf(\"hostPath type check failed: %s is not a character device\", ftc.GetPath())\n\t\t}\n\tcase v1.HostPathBlockDev:\n\t\tif !ftc.IsBlock() {\n\t\t\treturn fmt.Errorf(\"hostPath type check failed: %s is not a block device\", ftc.GetPath())\n\t\t}\n\tdefault:\n\t\treturn fmt.Errorf(\"%s is an invalid volume type\", *pathType)\n\t}\n\n\treturn nil\n}","line":{"from":465,"to":502}} {"id":100012427,"name":"makeDir","signature":"func makeDir(pathname string) error","file":"pkg/volume/hostpath/host_path.go","code":"// makeDir creates a new directory.\n// If pathname already exists as a directory, no error is returned.\n// If pathname already exists as a file, an error is returned.\nfunc makeDir(pathname string) error {\n\terr := os.MkdirAll(pathname, os.FileMode(0755))\n\tif err != nil {\n\t\tif !os.IsExist(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":504,"to":515}} {"id":100012428,"name":"makeFile","signature":"func makeFile(pathname string) error","file":"pkg/volume/hostpath/host_path.go","code":"// makeFile creates an empty file.\n// If pathname already exists, whether a file or directory, no error is returned.\nfunc makeFile(pathname string) error {\n\tf, err := os.OpenFile(pathname, os.O_CREATE, os.FileMode(0644))\n\tif f != nil {\n\t\tf.Close()\n\t}\n\tif err != nil {\n\t\tif !os.IsExist(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":517,"to":530}} {"id":100012429,"name":"NewAttacher","signature":"func (plugin *iscsiPlugin) NewAttacher() (volume.Attacher, error)","file":"pkg/volume/iscsi/attacher.go","code":"func (plugin *iscsiPlugin) NewAttacher() (volume.Attacher, error) {\n\treturn \u0026iscsiAttacher{\n\t\thost: plugin.host,\n\t\ttargetLocks: plugin.targetLocks,\n\t\tmanager: \u0026ISCSIUtil{},\n\t}, nil\n}","line":{"from":48,"to":54}} {"id":100012430,"name":"NewDeviceMounter","signature":"func (plugin *iscsiPlugin) NewDeviceMounter() (volume.DeviceMounter, error)","file":"pkg/volume/iscsi/attacher.go","code":"func (plugin *iscsiPlugin) NewDeviceMounter() (volume.DeviceMounter, error) {\n\treturn plugin.NewAttacher()\n}","line":{"from":56,"to":58}} {"id":100012431,"name":"GetDeviceMountRefs","signature":"func (plugin *iscsiPlugin) GetDeviceMountRefs(deviceMountPath string) ([]string, error)","file":"pkg/volume/iscsi/attacher.go","code":"func (plugin *iscsiPlugin) GetDeviceMountRefs(deviceMountPath string) ([]string, error) {\n\tmounter := plugin.host.GetMounter(iscsiPluginName)\n\treturn mounter.GetMountRefs(deviceMountPath)\n}","line":{"from":60,"to":63}} {"id":100012432,"name":"Attach","signature":"func (attacher *iscsiAttacher) Attach(spec *volume.Spec, nodeName types.NodeName) (string, error)","file":"pkg/volume/iscsi/attacher.go","code":"func (attacher *iscsiAttacher) Attach(spec *volume.Spec, nodeName types.NodeName) (string, error) {\n\treturn \"\", nil\n}","line":{"from":65,"to":67}} {"id":100012433,"name":"VolumesAreAttached","signature":"func (attacher *iscsiAttacher) VolumesAreAttached(specs []*volume.Spec, nodeName types.NodeName) (map[*volume.Spec]bool, error)","file":"pkg/volume/iscsi/attacher.go","code":"func (attacher *iscsiAttacher) VolumesAreAttached(specs []*volume.Spec, nodeName types.NodeName) (map[*volume.Spec]bool, error) {\n\tvolumesAttachedCheck := make(map[*volume.Spec]bool)\n\tfor _, spec := range specs {\n\t\tvolumesAttachedCheck[spec] = true\n\t}\n\n\treturn volumesAttachedCheck, nil\n}","line":{"from":69,"to":76}} {"id":100012434,"name":"WaitForAttach","signature":"func (attacher *iscsiAttacher) WaitForAttach(spec *volume.Spec, devicePath string, pod *v1.Pod, timeout time.Duration) (string, error)","file":"pkg/volume/iscsi/attacher.go","code":"func (attacher *iscsiAttacher) WaitForAttach(spec *volume.Spec, devicePath string, pod *v1.Pod, timeout time.Duration) (string, error) {\n\tmounter, err := volumeSpecToMounter(spec, attacher.host, attacher.targetLocks, pod)\n\tif err != nil {\n\t\tklog.Warningf(\"failed to get iscsi mounter: %v\", err)\n\t\treturn \"\", err\n\t}\n\treturn attacher.manager.AttachDisk(*mounter)\n}","line":{"from":78,"to":85}} {"id":100012435,"name":"GetDeviceMountPath","signature":"func (attacher *iscsiAttacher) GetDeviceMountPath(","file":"pkg/volume/iscsi/attacher.go","code":"func (attacher *iscsiAttacher) GetDeviceMountPath(\n\tspec *volume.Spec) (string, error) {\n\tmounter, err := volumeSpecToMounter(spec, attacher.host, attacher.targetLocks, nil)\n\tif err != nil {\n\t\tklog.Warningf(\"failed to get iscsi mounter: %v\", err)\n\t\treturn \"\", err\n\t}\n\tif mounter.InitiatorName != \"\" {\n\t\t// new iface name is \u003ctarget portal\u003e:\u003cvolume name\u003e\n\t\tmounter.Iface = mounter.Portals[0] + \":\" + mounter.VolName\n\t}\n\treturn attacher.manager.MakeGlobalPDName(*mounter.iscsiDisk), nil\n}","line":{"from":87,"to":99}} {"id":100012436,"name":"MountDevice","signature":"func (attacher *iscsiAttacher) MountDevice(spec *volume.Spec, devicePath string, deviceMountPath string, mountArgs volume.DeviceMounterArgs) error","file":"pkg/volume/iscsi/attacher.go","code":"func (attacher *iscsiAttacher) MountDevice(spec *volume.Spec, devicePath string, deviceMountPath string, mountArgs volume.DeviceMounterArgs) error {\n\tmounter := attacher.host.GetMounter(iscsiPluginName)\n\tnotMnt, err := mounter.IsLikelyNotMountPoint(deviceMountPath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tif err := os.MkdirAll(deviceMountPath, 0750); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tnotMnt = true\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\treadOnly, fsType, err := getISCSIVolumeInfo(spec)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\toptions := []string{}\n\tif readOnly {\n\t\toptions = append(options, \"ro\")\n\t}\n\tif mountArgs.SELinuxLabel != \"\" {\n\t\toptions = volumeutil.AddSELinuxMountOption(options, mountArgs.SELinuxLabel)\n\t}\n\tif notMnt {\n\t\tdiskMounter := \u0026mount.SafeFormatAndMount{Interface: mounter, Exec: attacher.host.GetExec(iscsiPluginName)}\n\t\tmountOptions := volumeutil.MountOptionFromSpec(spec, options...)\n\t\terr = diskMounter.FormatAndMount(devicePath, deviceMountPath, fsType, mountOptions)\n\t\tif err != nil {\n\t\t\tos.Remove(deviceMountPath)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":101,"to":136}} {"id":100012437,"name":"NewDetacher","signature":"func (plugin *iscsiPlugin) NewDetacher() (volume.Detacher, error)","file":"pkg/volume/iscsi/attacher.go","code":"func (plugin *iscsiPlugin) NewDetacher() (volume.Detacher, error) {\n\treturn \u0026iscsiDetacher{\n\t\thost: plugin.host,\n\t\tmounter: plugin.host.GetMounter(iscsiPluginName),\n\t\tmanager: \u0026ISCSIUtil{},\n\t\tplugin: plugin,\n\t}, nil\n}","line":{"from":149,"to":156}} {"id":100012438,"name":"NewDeviceUnmounter","signature":"func (plugin *iscsiPlugin) NewDeviceUnmounter() (volume.DeviceUnmounter, error)","file":"pkg/volume/iscsi/attacher.go","code":"func (plugin *iscsiPlugin) NewDeviceUnmounter() (volume.DeviceUnmounter, error) {\n\treturn plugin.NewDetacher()\n}","line":{"from":158,"to":160}} {"id":100012439,"name":"Detach","signature":"func (detacher *iscsiDetacher) Detach(volumeName string, nodeName types.NodeName) error","file":"pkg/volume/iscsi/attacher.go","code":"func (detacher *iscsiDetacher) Detach(volumeName string, nodeName types.NodeName) error {\n\treturn nil\n}","line":{"from":162,"to":164}} {"id":100012440,"name":"UnmountDevice","signature":"func (detacher *iscsiDetacher) UnmountDevice(deviceMountPath string) error","file":"pkg/volume/iscsi/attacher.go","code":"func (detacher *iscsiDetacher) UnmountDevice(deviceMountPath string) error {\n\tunMounter := volumeSpecToUnmounter(detacher.mounter, detacher.host, detacher.plugin)\n\terr := detacher.manager.DetachDisk(*unMounter, deviceMountPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"iscsi: failed to detach disk: %s\\nError: %v\", deviceMountPath, err)\n\t}\n\tklog.V(4).Infof(\"iscsi: %q is unmounted, deleting the directory\", deviceMountPath)\n\terr = os.RemoveAll(deviceMountPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"iscsi: failed to delete the directory: %s\\nError: %v\", deviceMountPath, err)\n\t}\n\tklog.V(4).Infof(\"iscsi: successfully detached disk: %s\", deviceMountPath)\n\treturn nil\n}","line":{"from":166,"to":179}} {"id":100012441,"name":"CanAttach","signature":"func (plugin *iscsiPlugin) CanAttach(spec *volume.Spec) (bool, error)","file":"pkg/volume/iscsi/attacher.go","code":"func (plugin *iscsiPlugin) CanAttach(spec *volume.Spec) (bool, error) {\n\treturn true, nil\n}","line":{"from":181,"to":183}} {"id":100012442,"name":"CanDeviceMount","signature":"func (plugin *iscsiPlugin) CanDeviceMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/iscsi/attacher.go","code":"func (plugin *iscsiPlugin) CanDeviceMount(spec *volume.Spec) (bool, error) {\n\treturn true, nil\n}","line":{"from":185,"to":187}} {"id":100012443,"name":"volumeSpecToMounter","signature":"func volumeSpecToMounter(spec *volume.Spec, host volume.VolumeHost, targetLocks keymutex.KeyMutex, pod *v1.Pod) (*iscsiDiskMounter, error)","file":"pkg/volume/iscsi/attacher.go","code":"func volumeSpecToMounter(spec *volume.Spec, host volume.VolumeHost, targetLocks keymutex.KeyMutex, pod *v1.Pod) (*iscsiDiskMounter, error) {\n\tvar secret map[string]string\n\treadOnly, fsType, err := getISCSIVolumeInfo(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar podUID types.UID\n\tif pod != nil {\n\t\tsecret, err = createSecretMap(spec, \u0026iscsiPlugin{host: host, targetLocks: targetLocks}, pod.Namespace)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpodUID = pod.UID\n\t}\n\tiscsiDisk, err := createISCSIDisk(spec,\n\t\tpodUID,\n\t\t\u0026iscsiPlugin{host: host, targetLocks: targetLocks},\n\t\t\u0026ISCSIUtil{},\n\t\tsecret,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\texec := host.GetExec(iscsiPluginName)\n\n\tvolumeMode, err := volumeutil.GetVolumeMode(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tklog.V(5).Infof(\"iscsi: VolumeSpecToMounter volumeMode %s\", volumeMode)\n\treturn \u0026iscsiDiskMounter{\n\t\tiscsiDisk: iscsiDisk,\n\t\tfsType: fsType,\n\t\tvolumeMode: volumeMode,\n\t\treadOnly: readOnly,\n\t\tmounter: \u0026mount.SafeFormatAndMount{Interface: host.GetMounter(iscsiPluginName), Exec: exec},\n\t\texec: exec,\n\t\tdeviceUtil: volumeutil.NewDeviceHandler(volumeutil.NewIOHandler()),\n\t}, nil\n}","line":{"from":189,"to":229}} {"id":100012444,"name":"volumeSpecToUnmounter","signature":"func volumeSpecToUnmounter(mounter mount.Interface, host volume.VolumeHost, plugin *iscsiPlugin) *iscsiDiskUnmounter","file":"pkg/volume/iscsi/attacher.go","code":"func volumeSpecToUnmounter(mounter mount.Interface, host volume.VolumeHost, plugin *iscsiPlugin) *iscsiDiskUnmounter {\n\texec := host.GetExec(iscsiPluginName)\n\treturn \u0026iscsiDiskUnmounter{\n\t\tiscsiDisk: \u0026iscsiDisk{\n\t\t\tplugin: plugin,\n\t\t},\n\t\tmounter: mounter,\n\t\texec: exec,\n\t\tdeviceUtil: volumeutil.NewDeviceHandler(volumeutil.NewIOHandler()),\n\t}\n}","line":{"from":231,"to":241}} {"id":100012445,"name":"diskSetUp","signature":"func diskSetUp(manager diskManager, b iscsiDiskMounter, volPath string, mounter mount.Interface, fsGroup *int64, fsGroupChangePolicy *v1.PodFSGroupChangePolicy) error","file":"pkg/volume/iscsi/disk_manager.go","code":"// utility to mount a disk based filesystem\n// globalPDPath: global mount path like, /var/lib/kubelet/plugins/kubernetes.io/iscsi/{ifaceName}/{portal-some_iqn-lun-lun_id}\n// volPath: pod volume dir path like, /var/lib/kubelet/pods/{podUID}/volumes/kubernetes.io~iscsi/{volumeName}\nfunc diskSetUp(manager diskManager, b iscsiDiskMounter, volPath string, mounter mount.Interface, fsGroup *int64, fsGroupChangePolicy *v1.PodFSGroupChangePolicy) error {\n\tnotMnt, err := mounter.IsLikelyNotMountPoint(volPath)\n\tif err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\tklog.Errorf(\"cannot validate mountpoint: %s\", volPath)\n\t\treturn err\n\t}\n\tif !notMnt {\n\t\treturn nil\n\t}\n\n\tif err := os.MkdirAll(volPath, 0750); err != nil {\n\t\tklog.Errorf(\"failed to mkdir:%s\", volPath)\n\t\treturn err\n\t}\n\t// Perform a bind mount to the full path to allow duplicate mounts of the same disk.\n\toptions := []string{\"bind\"}\n\tif b.readOnly {\n\t\toptions = append(options, \"ro\")\n\t}\n\tif b.iscsiDisk.InitiatorName != \"\" {\n\t\t// new iface name is \u003ctarget portal\u003e:\u003cvolume name\u003e\n\t\tb.iscsiDisk.Iface = b.iscsiDisk.Portals[0] + \":\" + b.iscsiDisk.VolName\n\t}\n\tglobalPDPath := manager.MakeGlobalPDName(*b.iscsiDisk)\n\tmountOptions := util.JoinMountOptions(b.mountOptions, options)\n\terr = mounter.MountSensitiveWithoutSystemd(globalPDPath, volPath, \"\", mountOptions, nil)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to bind mount: source:%s, target:%s, err:%v\", globalPDPath, volPath, err)\n\t\tnoMnt, mntErr := b.mounter.IsLikelyNotMountPoint(volPath)\n\t\tif mntErr != nil {\n\t\t\tklog.Errorf(\"IsLikelyNotMountPoint check failed: %v\", mntErr)\n\t\t\treturn err\n\t\t}\n\t\tif !noMnt {\n\t\t\tif mntErr = b.mounter.Unmount(volPath); mntErr != nil {\n\t\t\t\tklog.Errorf(\"Failed to unmount: %v\", mntErr)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tnoMnt, mntErr = b.mounter.IsLikelyNotMountPoint(volPath)\n\t\t\tif mntErr != nil {\n\t\t\t\tklog.Errorf(\"IsLikelyNotMountPoint check failed: %v\", mntErr)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !noMnt {\n\t\t\t\t// will most likely retry on next sync loop.\n\t\t\t\tklog.Errorf(\"%s is still mounted, despite call to unmount(). Will try again next sync loop.\", volPath)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tos.Remove(volPath)\n\t\treturn err\n\t}\n\n\tif !b.readOnly {\n\t\tvolume.SetVolumeOwnership(\u0026b, volPath, fsGroup, fsGroupChangePolicy, util.FSGroupCompleteHook(b.plugin, nil))\n\t}\n\n\treturn nil\n}","line":{"from":42,"to":103}} {"id":100012446,"name":"ProbeVolumePlugins","signature":"func ProbeVolumePlugins() []volume.VolumePlugin","file":"pkg/volume/iscsi/iscsi.go","code":"// ProbeVolumePlugins is the primary entrypoint for volume plugins.\nfunc ProbeVolumePlugins() []volume.VolumePlugin {\n\treturn []volume.VolumePlugin{\u0026iscsiPlugin{}}\n}","line":{"from":44,"to":47}} {"id":100012447,"name":"Init","signature":"func (plugin *iscsiPlugin) Init(host volume.VolumeHost) error","file":"pkg/volume/iscsi/iscsi.go","code":"func (plugin *iscsiPlugin) Init(host volume.VolumeHost) error {\n\tplugin.host = host\n\tplugin.targetLocks = keymutex.NewHashed(0)\n\treturn nil\n}","line":{"from":62,"to":66}} {"id":100012448,"name":"GetPluginName","signature":"func (plugin *iscsiPlugin) GetPluginName() string","file":"pkg/volume/iscsi/iscsi.go","code":"func (plugin *iscsiPlugin) GetPluginName() string {\n\treturn iscsiPluginName\n}","line":{"from":68,"to":70}} {"id":100012449,"name":"GetVolumeName","signature":"func (plugin *iscsiPlugin) GetVolumeName(spec *volume.Spec) (string, error)","file":"pkg/volume/iscsi/iscsi.go","code":"func (plugin *iscsiPlugin) GetVolumeName(spec *volume.Spec) (string, error) {\n\ttp, _, iqn, lun, err := getISCSITargetInfo(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn fmt.Sprintf(\"%v:%v:%v\", tp, iqn, lun), nil\n}","line":{"from":72,"to":79}} {"id":100012450,"name":"CanSupport","signature":"func (plugin *iscsiPlugin) CanSupport(spec *volume.Spec) bool","file":"pkg/volume/iscsi/iscsi.go","code":"func (plugin *iscsiPlugin) CanSupport(spec *volume.Spec) bool {\n\treturn (spec.Volume != nil \u0026\u0026 spec.Volume.ISCSI != nil) || (spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.ISCSI != nil)\n}","line":{"from":81,"to":83}} {"id":100012451,"name":"RequiresRemount","signature":"func (plugin *iscsiPlugin) RequiresRemount(spec *volume.Spec) bool","file":"pkg/volume/iscsi/iscsi.go","code":"func (plugin *iscsiPlugin) RequiresRemount(spec *volume.Spec) bool {\n\treturn false\n}","line":{"from":85,"to":87}} {"id":100012452,"name":"SupportsMountOption","signature":"func (plugin *iscsiPlugin) SupportsMountOption() bool","file":"pkg/volume/iscsi/iscsi.go","code":"func (plugin *iscsiPlugin) SupportsMountOption() bool {\n\treturn true\n}","line":{"from":89,"to":91}} {"id":100012453,"name":"SupportsBulkVolumeVerification","signature":"func (plugin *iscsiPlugin) SupportsBulkVolumeVerification() bool","file":"pkg/volume/iscsi/iscsi.go","code":"func (plugin *iscsiPlugin) SupportsBulkVolumeVerification() bool {\n\treturn false\n}","line":{"from":93,"to":95}} {"id":100012454,"name":"SupportsSELinuxContextMount","signature":"func (plugin *iscsiPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/iscsi/iscsi.go","code":"func (plugin *iscsiPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error) {\n\treturn true, nil\n}","line":{"from":97,"to":99}} {"id":100012455,"name":"GetAccessModes","signature":"func (plugin *iscsiPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode","file":"pkg/volume/iscsi/iscsi.go","code":"func (plugin *iscsiPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode {\n\treturn []v1.PersistentVolumeAccessMode{\n\t\tv1.ReadWriteOnce,\n\t\tv1.ReadOnlyMany,\n\t}\n}","line":{"from":101,"to":106}} {"id":100012456,"name":"NewMounter","signature":"func (plugin *iscsiPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error)","file":"pkg/volume/iscsi/iscsi.go","code":"func (plugin *iscsiPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) {\n\tif pod == nil {\n\t\treturn nil, fmt.Errorf(\"nil pod\")\n\t}\n\tsecret, err := createSecretMap(spec, plugin, pod.Namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn plugin.newMounterInternal(spec, pod.UID, \u0026ISCSIUtil{}, plugin.host.GetMounter(plugin.GetPluginName()), plugin.host.GetExec(plugin.GetPluginName()), secret)\n}","line":{"from":108,"to":117}} {"id":100012457,"name":"newMounterInternal","signature":"func (plugin *iscsiPlugin) newMounterInternal(spec *volume.Spec, podUID types.UID, manager diskManager, mounter mount.Interface, exec utilexec.Interface, secret map[string]string) (volume.Mounter, error)","file":"pkg/volume/iscsi/iscsi.go","code":"func (plugin *iscsiPlugin) newMounterInternal(spec *volume.Spec, podUID types.UID, manager diskManager, mounter mount.Interface, exec utilexec.Interface, secret map[string]string) (volume.Mounter, error) {\n\treadOnly, fsType, err := getISCSIVolumeInfo(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tiscsiDisk, err := createISCSIDisk(spec, podUID, plugin, manager, secret)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif iscsiDisk != nil {\n\n\t\t//Add volume metrics\n\t\tiscsiDisk.MetricsProvider = volume.NewMetricsStatFS(iscsiDisk.GetPath())\n\t}\n\treturn \u0026iscsiDiskMounter{\n\t\tiscsiDisk: iscsiDisk,\n\t\tfsType: fsType,\n\t\treadOnly: readOnly,\n\t\tmounter: \u0026mount.SafeFormatAndMount{Interface: mounter, Exec: exec},\n\t\texec: exec,\n\t\tdeviceUtil: ioutil.NewDeviceHandler(ioutil.NewIOHandler()),\n\t\tmountOptions: ioutil.MountOptionFromSpec(spec),\n\t}, nil\n}","line":{"from":119,"to":143}} {"id":100012458,"name":"NewBlockVolumeMapper","signature":"func (plugin *iscsiPlugin) NewBlockVolumeMapper(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.BlockVolumeMapper, error)","file":"pkg/volume/iscsi/iscsi.go","code":"// NewBlockVolumeMapper creates a new volume.BlockVolumeMapper from an API specification.\nfunc (plugin *iscsiPlugin) NewBlockVolumeMapper(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.BlockVolumeMapper, error) {\n\t// If this is called via GenerateUnmapDeviceFunc(), pod is nil.\n\t// Pass empty string as dummy uid since uid isn't used in the case.\n\tvar uid types.UID\n\tvar secret map[string]string\n\tvar err error\n\tif pod != nil {\n\t\tuid = pod.UID\n\t\tsecret, err = createSecretMap(spec, plugin, pod.Namespace)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn plugin.newBlockVolumeMapperInternal(spec, uid, \u0026ISCSIUtil{}, plugin.host.GetMounter(plugin.GetPluginName()), plugin.host.GetExec(plugin.GetPluginName()), secret)\n}","line":{"from":145,"to":160}} {"id":100012459,"name":"newBlockVolumeMapperInternal","signature":"func (plugin *iscsiPlugin) newBlockVolumeMapperInternal(spec *volume.Spec, podUID types.UID, manager diskManager, mounter mount.Interface, exec utilexec.Interface, secret map[string]string) (volume.BlockVolumeMapper, error)","file":"pkg/volume/iscsi/iscsi.go","code":"func (plugin *iscsiPlugin) newBlockVolumeMapperInternal(spec *volume.Spec, podUID types.UID, manager diskManager, mounter mount.Interface, exec utilexec.Interface, secret map[string]string) (volume.BlockVolumeMapper, error) {\n\treadOnly, _, err := getISCSIVolumeInfo(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tiscsiDisk, err := createISCSIDisk(spec, podUID, plugin, manager, secret)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmapper := \u0026iscsiDiskMapper{\n\t\tiscsiDisk: iscsiDisk,\n\t\treadOnly: readOnly,\n\t\texec: exec,\n\t\tdeviceUtil: ioutil.NewDeviceHandler(ioutil.NewIOHandler()),\n\t}\n\n\tblockPath, err := mapper.GetGlobalMapPath(spec)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get device path: %v\", err)\n\t}\n\tmapper.MetricsProvider = volume.NewMetricsBlock(filepath.Join(blockPath, string(podUID)))\n\n\treturn mapper, nil\n}","line":{"from":162,"to":185}} {"id":100012460,"name":"NewUnmounter","signature":"func (plugin *iscsiPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error)","file":"pkg/volume/iscsi/iscsi.go","code":"func (plugin *iscsiPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error) {\n\treturn plugin.newUnmounterInternal(volName, podUID, \u0026ISCSIUtil{}, plugin.host.GetMounter(plugin.GetPluginName()), plugin.host.GetExec(plugin.GetPluginName()))\n}","line":{"from":187,"to":189}} {"id":100012461,"name":"newUnmounterInternal","signature":"func (plugin *iscsiPlugin) newUnmounterInternal(volName string, podUID types.UID, manager diskManager, mounter mount.Interface, exec utilexec.Interface) (volume.Unmounter, error)","file":"pkg/volume/iscsi/iscsi.go","code":"func (plugin *iscsiPlugin) newUnmounterInternal(volName string, podUID types.UID, manager diskManager, mounter mount.Interface, exec utilexec.Interface) (volume.Unmounter, error) {\n\treturn \u0026iscsiDiskUnmounter{\n\t\tiscsiDisk: \u0026iscsiDisk{\n\t\t\tpodUID: podUID,\n\t\t\tVolName: volName,\n\t\t\tmanager: manager,\n\t\t\tplugin: plugin,\n\t\t\tMetricsProvider: volume.NewMetricsStatFS(plugin.host.GetPodVolumeDir(podUID, utilstrings.EscapeQualifiedName(iscsiPluginName), volName)),\n\t\t},\n\t\tmounter: mounter,\n\t\texec: exec,\n\t\tdeviceUtil: ioutil.NewDeviceHandler(ioutil.NewIOHandler()),\n\t}, nil\n}","line":{"from":191,"to":204}} {"id":100012462,"name":"NewBlockVolumeUnmapper","signature":"func (plugin *iscsiPlugin) NewBlockVolumeUnmapper(volName string, podUID types.UID) (volume.BlockVolumeUnmapper, error)","file":"pkg/volume/iscsi/iscsi.go","code":"// NewBlockVolumeUnmapper creates a new volume.BlockVolumeUnmapper from recoverable state.\nfunc (plugin *iscsiPlugin) NewBlockVolumeUnmapper(volName string, podUID types.UID) (volume.BlockVolumeUnmapper, error) {\n\treturn plugin.newUnmapperInternal(volName, podUID, \u0026ISCSIUtil{}, plugin.host.GetExec(plugin.GetPluginName()))\n}","line":{"from":206,"to":209}} {"id":100012463,"name":"newUnmapperInternal","signature":"func (plugin *iscsiPlugin) newUnmapperInternal(volName string, podUID types.UID, manager diskManager, exec utilexec.Interface) (volume.BlockVolumeUnmapper, error)","file":"pkg/volume/iscsi/iscsi.go","code":"func (plugin *iscsiPlugin) newUnmapperInternal(volName string, podUID types.UID, manager diskManager, exec utilexec.Interface) (volume.BlockVolumeUnmapper, error) {\n\treturn \u0026iscsiDiskUnmapper{\n\t\tiscsiDisk: \u0026iscsiDisk{\n\t\t\tpodUID: podUID,\n\t\t\tVolName: volName,\n\t\t\tmanager: manager,\n\t\t\tplugin: plugin,\n\t\t},\n\t\texec: exec,\n\t\tdeviceUtil: ioutil.NewDeviceHandler(ioutil.NewIOHandler()),\n\t}, nil\n}","line":{"from":211,"to":222}} {"id":100012464,"name":"ConstructVolumeSpec","signature":"func (plugin *iscsiPlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error)","file":"pkg/volume/iscsi/iscsi.go","code":"func (plugin *iscsiPlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error) {\n\t// Find globalPDPath from pod volume directory(mountPath)\n\tvar globalPDPath string\n\tmounter := plugin.host.GetMounter(plugin.GetPluginName())\n\t// Try really hard to get the global mount of the volume, an error returned from here would\n\t// leave the global mount still mounted, while marking the volume as unused.\n\t// The volume can then be mounted on several nodes, resulting in volume\n\t// corruption.\n\tpaths, err := ioutil.GetReliableMountRefs(mounter, mountPath)\n\tif io.IsInconsistentReadError(err) {\n\t\tklog.Errorf(\"Failed to read mount refs from /proc/mounts for %s: %s\", mountPath, err)\n\t\tklog.Errorf(\"Kubelet cannot unmount volume at %s, please unmount it and all mounts of the same device manually.\", mountPath)\n\t\treturn volume.ReconstructedVolume{}, err\n\t}\n\tif err != nil {\n\t\treturn volume.ReconstructedVolume{}, err\n\t}\n\n\tfor _, path := range paths {\n\t\tif strings.Contains(path, plugin.host.GetPluginDir(iscsiPluginName)) {\n\t\t\tglobalPDPath = path\n\t\t\tbreak\n\t\t}\n\t}\n\t// Couldn't fetch globalPDPath\n\tif len(globalPDPath) == 0 {\n\t\treturn volume.ReconstructedVolume{}, fmt.Errorf(\"couldn't fetch globalPDPath. failed to obtain volume spec\")\n\t}\n\n\t// Obtain iscsi disk configurations from globalPDPath\n\tdevice, _, err := extractDeviceAndPrefix(globalPDPath)\n\tif err != nil {\n\t\treturn volume.ReconstructedVolume{}, err\n\t}\n\tbkpPortal, iqn, err := extractPortalAndIqn(device)\n\tif err != nil {\n\t\treturn volume.ReconstructedVolume{}, err\n\t}\n\tarr := strings.Split(device, \"-lun-\")\n\tif len(arr) \u003c 2 {\n\t\treturn volume.ReconstructedVolume{}, fmt.Errorf(\"failed to retrieve lun from globalPDPath: %v\", globalPDPath)\n\t}\n\tlun, err := strconv.Atoi(arr[1])\n\tif err != nil {\n\t\treturn volume.ReconstructedVolume{}, err\n\t}\n\tiface, _ := extractIface(globalPDPath)\n\tiscsiVolume := \u0026v1.Volume{\n\t\tName: volumeName,\n\t\tVolumeSource: v1.VolumeSource{\n\t\t\tISCSI: \u0026v1.ISCSIVolumeSource{\n\t\t\t\tTargetPortal: bkpPortal,\n\t\t\t\tIQN: iqn,\n\t\t\t\tLun: int32(lun),\n\t\t\t\tISCSIInterface: iface,\n\t\t\t},\n\t\t},\n\t}\n\n\tvar mountContext string\n\tif utilfeature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {\n\t\tkvh, ok := plugin.host.(volume.KubeletVolumeHost)\n\t\tif !ok {\n\t\t\treturn volume.ReconstructedVolume{}, fmt.Errorf(\"plugin volume host does not implement KubeletVolumeHost interface\")\n\t\t}\n\t\thu := kvh.GetHostUtil()\n\t\tmountContext, err = hu.GetSELinuxMountContext(mountPath)\n\t\tif err != nil {\n\t\t\treturn volume.ReconstructedVolume{}, err\n\t\t}\n\t}\n\n\treturn volume.ReconstructedVolume{\n\t\tSpec: volume.NewSpecFromVolume(iscsiVolume),\n\t\tSELinuxMountContext: mountContext,\n\t}, nil\n}","line":{"from":224,"to":300}} {"id":100012465,"name":"ConstructBlockVolumeSpec","signature":"func (plugin *iscsiPlugin) ConstructBlockVolumeSpec(podUID types.UID, volumeName, mapPath string) (*volume.Spec, error)","file":"pkg/volume/iscsi/iscsi.go","code":"func (plugin *iscsiPlugin) ConstructBlockVolumeSpec(podUID types.UID, volumeName, mapPath string) (*volume.Spec, error) {\n\tpluginDir := plugin.host.GetVolumeDevicePluginDir(iscsiPluginName)\n\tblkutil := volumepathhandler.NewBlockVolumePathHandler()\n\tglobalMapPathUUID, err := blkutil.FindGlobalMapPathUUIDFromPod(pluginDir, mapPath, podUID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tklog.V(5).Infof(\"globalMapPathUUID: %v, err: %v\", globalMapPathUUID, err)\n\t// Retrieve volume information from globalMapPathUUID\n\t// globalMapPathUUID example:\n\t// plugins/kubernetes.io/{PluginName}/{DefaultKubeletVolumeDevicesDirName}/{volumePluginDependentPath}/{pod uuid}\n\t// plugins/kubernetes.io/iscsi/volumeDevices/iface-default/192.168.0.10:3260-iqn.2017-05.com.example:test-lun-0/{pod uuid}\n\tglobalMapPath := filepath.Dir(globalMapPathUUID)\n\treturn getVolumeSpecFromGlobalMapPath(volumeName, globalMapPath)\n}","line":{"from":302,"to":316}} {"id":100012466,"name":"GetPath","signature":"func (iscsi *iscsiDisk) GetPath() string","file":"pkg/volume/iscsi/iscsi.go","code":"func (iscsi *iscsiDisk) GetPath() string {\n\tname := iscsiPluginName\n\t// safe to use PodVolumeDir now: volume teardown occurs before pod is cleaned up\n\treturn iscsi.plugin.host.GetPodVolumeDir(iscsi.podUID, utilstrings.EscapeQualifiedName(name), iscsi.VolName)\n}","line":{"from":336,"to":340}} {"id":100012467,"name":"iscsiGlobalMapPath","signature":"func (iscsi *iscsiDisk) iscsiGlobalMapPath(spec *volume.Spec) (string, error)","file":"pkg/volume/iscsi/iscsi.go","code":"func (iscsi *iscsiDisk) iscsiGlobalMapPath(spec *volume.Spec) (string, error) {\n\tmounter, err := volumeSpecToMounter(spec, iscsi.plugin.host, iscsi.plugin.targetLocks, nil /* pod */)\n\tif err != nil {\n\t\tklog.Warningf(\"failed to get iscsi mounter: %v\", err)\n\t\treturn \"\", err\n\t}\n\treturn iscsi.manager.MakeGlobalVDPDName(*mounter.iscsiDisk), nil\n}","line":{"from":342,"to":349}} {"id":100012468,"name":"iscsiPodDeviceMapPath","signature":"func (iscsi *iscsiDisk) iscsiPodDeviceMapPath() (string, string)","file":"pkg/volume/iscsi/iscsi.go","code":"func (iscsi *iscsiDisk) iscsiPodDeviceMapPath() (string, string) {\n\tname := iscsiPluginName\n\treturn iscsi.plugin.host.GetPodVolumeDeviceDir(iscsi.podUID, utilstrings.EscapeQualifiedName(name)), iscsi.VolName\n}","line":{"from":351,"to":354}} {"id":100012469,"name":"GetAttributes","signature":"func (b *iscsiDiskMounter) GetAttributes() volume.Attributes","file":"pkg/volume/iscsi/iscsi.go","code":"func (b *iscsiDiskMounter) GetAttributes() volume.Attributes {\n\treturn volume.Attributes{\n\t\tReadOnly: b.readOnly,\n\t\tManaged: !b.readOnly,\n\t\tSELinuxRelabel: !b.mountedWithSELinuxContext,\n\t}\n}","line":{"from":370,"to":376}} {"id":100012470,"name":"SetUp","signature":"func (b *iscsiDiskMounter) SetUp(mounterArgs volume.MounterArgs) error","file":"pkg/volume/iscsi/iscsi.go","code":"func (b *iscsiDiskMounter) SetUp(mounterArgs volume.MounterArgs) error {\n\treturn b.SetUpAt(b.GetPath(), mounterArgs)\n}","line":{"from":378,"to":380}} {"id":100012471,"name":"SetUpAt","signature":"func (b *iscsiDiskMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error","file":"pkg/volume/iscsi/iscsi.go","code":"func (b *iscsiDiskMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {\n\t// diskSetUp checks mountpoints and prevent repeated calls\n\terr := diskSetUp(b.manager, *b, dir, b.mounter, mounterArgs.FsGroup, mounterArgs.FSGroupChangePolicy)\n\tif err != nil {\n\t\tklog.Errorf(\"iscsi: failed to setup\")\n\t}\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {\n\t\t// The volume must have been mounted in MountDevice with -o context.\n\t\t// TODO: extract from mount table in GetAttributes() to be sure?\n\t\tb.mountedWithSELinuxContext = mounterArgs.SELinuxLabel != \"\"\n\t}\n\treturn err\n}","line":{"from":382,"to":395}} {"id":100012472,"name":"TearDown","signature":"func (c *iscsiDiskUnmounter) TearDown() error","file":"pkg/volume/iscsi/iscsi.go","code":"// Unmounts the bind mount, and detaches the disk only if the disk\n// resource was the last reference to that disk on the kubelet.\nfunc (c *iscsiDiskUnmounter) TearDown() error {\n\treturn c.TearDownAt(c.GetPath())\n}","line":{"from":406,"to":410}} {"id":100012473,"name":"TearDownAt","signature":"func (c *iscsiDiskUnmounter) TearDownAt(dir string) error","file":"pkg/volume/iscsi/iscsi.go","code":"func (c *iscsiDiskUnmounter) TearDownAt(dir string) error {\n\treturn mount.CleanupMountPoint(dir, c.mounter, false)\n}","line":{"from":412,"to":414}} {"id":100012474,"name":"SupportsMetrics","signature":"func (idm *iscsiDiskMapper) SupportsMetrics() bool","file":"pkg/volume/iscsi/iscsi.go","code":"// SupportsMetrics returns true for SupportsMetrics as it initializes the\n// MetricsProvider.\nfunc (idm *iscsiDiskMapper) SupportsMetrics() bool {\n\treturn true\n}","line":{"from":433,"to":437}} {"id":100012475,"name":"TearDownDevice","signature":"func (c *iscsiDiskUnmapper) TearDownDevice(mapPath, _ string) error","file":"pkg/volume/iscsi/iscsi.go","code":"// Even though iSCSI plugin has attacher/detacher implementation, iSCSI plugin\n// needs volume detach operation during TearDownDevice(). This method is only\n// chance that operations are done on kubelet node during volume teardown sequences.\nfunc (c *iscsiDiskUnmapper) TearDownDevice(mapPath, _ string) error {\n\terr := c.manager.DetachBlockISCSIDisk(*c, mapPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"iscsi: failed to detach disk: %s\\nError: %v\", mapPath, err)\n\t}\n\tklog.V(4).Infof(\"iscsi: %q is unmounted, deleting the directory\", mapPath)\n\terr = os.RemoveAll(mapPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"iscsi: failed to delete the directory: %s\\nError: %v\", mapPath, err)\n\t}\n\tklog.V(4).Infof(\"iscsi: successfully detached disk: %s\", mapPath)\n\treturn nil\n}","line":{"from":442,"to":457}} {"id":100012476,"name":"UnmapPodDevice","signature":"func (c *iscsiDiskUnmapper) UnmapPodDevice() error","file":"pkg/volume/iscsi/iscsi.go","code":"func (c *iscsiDiskUnmapper) UnmapPodDevice() error {\n\treturn nil\n}","line":{"from":459,"to":461}} {"id":100012477,"name":"GetGlobalMapPath","signature":"func (iscsi *iscsiDisk) GetGlobalMapPath(spec *volume.Spec) (string, error)","file":"pkg/volume/iscsi/iscsi.go","code":"// GetGlobalMapPath returns global map path and error\n// path: plugins/kubernetes.io/{PluginName}/volumeDevices/{ifaceName}/{portal-some_iqn-lun-lun_id}\nfunc (iscsi *iscsiDisk) GetGlobalMapPath(spec *volume.Spec) (string, error) {\n\treturn iscsi.iscsiGlobalMapPath(spec)\n}","line":{"from":463,"to":467}} {"id":100012478,"name":"GetPodDeviceMapPath","signature":"func (iscsi *iscsiDisk) GetPodDeviceMapPath() (string, string)","file":"pkg/volume/iscsi/iscsi.go","code":"// GetPodDeviceMapPath returns pod device map path and volume name\n// path: pods/{podUid}/volumeDevices/kubernetes.io~iscsi\n// volumeName: pv0001\nfunc (iscsi *iscsiDisk) GetPodDeviceMapPath() (string, string) {\n\treturn iscsi.iscsiPodDeviceMapPath()\n}","line":{"from":469,"to":474}} {"id":100012479,"name":"portalMounter","signature":"func portalMounter(portal string) string","file":"pkg/volume/iscsi/iscsi.go","code":"func portalMounter(portal string) string {\n\tif !strings.Contains(portal, \":\") {\n\t\tportal = portal + \":3260\"\n\t}\n\treturn portal\n}","line":{"from":476,"to":481}} {"id":100012480,"name":"getISCSIVolumeInfo","signature":"func getISCSIVolumeInfo(spec *volume.Spec) (bool, string, error)","file":"pkg/volume/iscsi/iscsi.go","code":"// get iSCSI volume info: readOnly and fstype\nfunc getISCSIVolumeInfo(spec *volume.Spec) (bool, string, error) {\n\t// for volume source, readonly is in volume spec\n\t// for PV, readonly is in PV spec. PV gets the ReadOnly flag indirectly through the PVC source\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.ISCSI != nil {\n\t\treturn spec.Volume.ISCSI.ReadOnly, spec.Volume.ISCSI.FSType, nil\n\t} else if spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.ISCSI != nil {\n\t\treturn spec.ReadOnly, spec.PersistentVolume.Spec.ISCSI.FSType, nil\n\t}\n\n\treturn false, \"\", fmt.Errorf(\"Spec does not reference an ISCSI volume type\")\n}","line":{"from":483,"to":495}} {"id":100012481,"name":"getISCSITargetInfo","signature":"func getISCSITargetInfo(spec *volume.Spec) (string, []string, string, int32, error)","file":"pkg/volume/iscsi/iscsi.go","code":"// get iSCSI target info: target portal, portals, iqn, and lun\nfunc getISCSITargetInfo(spec *volume.Spec) (string, []string, string, int32, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.ISCSI != nil {\n\t\treturn spec.Volume.ISCSI.TargetPortal, spec.Volume.ISCSI.Portals, spec.Volume.ISCSI.IQN, spec.Volume.ISCSI.Lun, nil\n\t} else if spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.ISCSI != nil {\n\t\treturn spec.PersistentVolume.Spec.ISCSI.TargetPortal, spec.PersistentVolume.Spec.ISCSI.Portals, spec.PersistentVolume.Spec.ISCSI.IQN, spec.PersistentVolume.Spec.ISCSI.Lun, nil\n\t}\n\n\treturn \"\", nil, \"\", 0, fmt.Errorf(\"Spec does not reference an ISCSI volume type\")\n}","line":{"from":497,"to":507}} {"id":100012482,"name":"getISCSIInitiatorInfo","signature":"func getISCSIInitiatorInfo(spec *volume.Spec) (string, *string, error)","file":"pkg/volume/iscsi/iscsi.go","code":"// get iSCSI initiator info: iface and initiator name\nfunc getISCSIInitiatorInfo(spec *volume.Spec) (string, *string, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.ISCSI != nil {\n\t\treturn spec.Volume.ISCSI.ISCSIInterface, spec.Volume.ISCSI.InitiatorName, nil\n\t} else if spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.ISCSI != nil {\n\t\treturn spec.PersistentVolume.Spec.ISCSI.ISCSIInterface, spec.PersistentVolume.Spec.ISCSI.InitiatorName, nil\n\t}\n\n\treturn \"\", nil, fmt.Errorf(\"Spec does not reference an ISCSI volume type\")\n}","line":{"from":509,"to":519}} {"id":100012483,"name":"getISCSIDiscoveryCHAPInfo","signature":"func getISCSIDiscoveryCHAPInfo(spec *volume.Spec) (bool, error)","file":"pkg/volume/iscsi/iscsi.go","code":"// get iSCSI Discovery CHAP boolean\nfunc getISCSIDiscoveryCHAPInfo(spec *volume.Spec) (bool, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.ISCSI != nil {\n\t\treturn spec.Volume.ISCSI.DiscoveryCHAPAuth, nil\n\t} else if spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.ISCSI != nil {\n\t\treturn spec.PersistentVolume.Spec.ISCSI.DiscoveryCHAPAuth, nil\n\t}\n\n\treturn false, fmt.Errorf(\"Spec does not reference an ISCSI volume type\")\n}","line":{"from":521,"to":531}} {"id":100012484,"name":"getISCSISessionCHAPInfo","signature":"func getISCSISessionCHAPInfo(spec *volume.Spec) (bool, error)","file":"pkg/volume/iscsi/iscsi.go","code":"// get iSCSI Session CHAP boolean\nfunc getISCSISessionCHAPInfo(spec *volume.Spec) (bool, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.ISCSI != nil {\n\t\treturn spec.Volume.ISCSI.SessionCHAPAuth, nil\n\t} else if spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.ISCSI != nil {\n\t\treturn spec.PersistentVolume.Spec.ISCSI.SessionCHAPAuth, nil\n\t}\n\n\treturn false, fmt.Errorf(\"Spec does not reference an ISCSI volume type\")\n}","line":{"from":533,"to":543}} {"id":100012485,"name":"getISCSISecretNameAndNamespace","signature":"func getISCSISecretNameAndNamespace(spec *volume.Spec, defaultSecretNamespace string) (string, string, error)","file":"pkg/volume/iscsi/iscsi.go","code":"// get iSCSI CHAP Secret info: secret name and namespace\nfunc getISCSISecretNameAndNamespace(spec *volume.Spec, defaultSecretNamespace string) (string, string, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.ISCSI != nil {\n\t\tif spec.Volume.ISCSI.SecretRef != nil {\n\t\t\treturn spec.Volume.ISCSI.SecretRef.Name, defaultSecretNamespace, nil\n\t\t}\n\t\treturn \"\", \"\", nil\n\t} else if spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.ISCSI != nil {\n\t\tsecretRef := spec.PersistentVolume.Spec.ISCSI.SecretRef\n\t\tsecretNs := defaultSecretNamespace\n\t\tif secretRef != nil {\n\t\t\tif len(secretRef.Namespace) != 0 {\n\t\t\t\tsecretNs = secretRef.Namespace\n\t\t\t}\n\t\t\treturn secretRef.Name, secretNs, nil\n\t\t}\n\t\treturn \"\", \"\", nil\n\t}\n\n\treturn \"\", \"\", fmt.Errorf(\"Spec does not reference an ISCSI volume type\")\n}","line":{"from":545,"to":566}} {"id":100012486,"name":"createISCSIDisk","signature":"func createISCSIDisk(spec *volume.Spec, podUID types.UID, plugin *iscsiPlugin, manager diskManager, secret map[string]string) (*iscsiDisk, error)","file":"pkg/volume/iscsi/iscsi.go","code":"func createISCSIDisk(spec *volume.Spec, podUID types.UID, plugin *iscsiPlugin, manager diskManager, secret map[string]string) (*iscsiDisk, error) {\n\ttp, portals, iqn, lunStr, err := getISCSITargetInfo(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlun := strconv.Itoa(int(lunStr))\n\tportal := portalMounter(tp)\n\tvar bkportal []string\n\tbkportal = append(bkportal, portal)\n\tfor _, p := range portals {\n\t\tbkportal = append(bkportal, portalMounter(string(p)))\n\t}\n\n\tiface, initiatorNamePtr, err := getISCSIInitiatorInfo(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar initiatorName string\n\tif initiatorNamePtr != nil {\n\t\tinitiatorName = *initiatorNamePtr\n\t}\n\tchapDiscovery, err := getISCSIDiscoveryCHAPInfo(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tchapSession, err := getISCSISessionCHAPInfo(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinitIface := iface\n\tif initiatorName != \"\" {\n\t\tiface = bkportal[0] + \":\" + spec.Name()\n\t}\n\n\treturn \u0026iscsiDisk{\n\t\tpodUID: podUID,\n\t\tVolName: spec.Name(),\n\t\tPortals: bkportal,\n\t\tIqn: iqn,\n\t\tLun: lun,\n\t\tInitIface: initIface,\n\t\tIface: iface,\n\t\tchapDiscovery: chapDiscovery,\n\t\tchapSession: chapSession,\n\t\tsecret: secret,\n\t\tInitiatorName: initiatorName,\n\t\tmanager: manager,\n\t\tplugin: plugin}, nil\n}","line":{"from":568,"to":619}} {"id":100012487,"name":"createSecretMap","signature":"func createSecretMap(spec *volume.Spec, plugin *iscsiPlugin, namespace string) (map[string]string, error)","file":"pkg/volume/iscsi/iscsi.go","code":"func createSecretMap(spec *volume.Spec, plugin *iscsiPlugin, namespace string) (map[string]string, error) {\n\tvar secret map[string]string\n\tchapDiscover, err := getISCSIDiscoveryCHAPInfo(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tchapSession, err := getISCSISessionCHAPInfo(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif chapDiscover || chapSession {\n\t\tsecretName, secretNamespace, err := getISCSISecretNameAndNamespace(spec, namespace)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif len(secretName) \u003e 0 \u0026\u0026 len(secretNamespace) \u003e 0 {\n\t\t\t// if secret is provideded, retrieve it\n\t\t\tkubeClient := plugin.host.GetKubeClient()\n\t\t\tif kubeClient == nil {\n\t\t\t\treturn nil, fmt.Errorf(\"cannot get kube client\")\n\t\t\t}\n\t\t\tsecretObj, err := kubeClient.CoreV1().Secrets(secretNamespace).Get(context.TODO(), secretName, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"couldn't get secret %v/%v error: %w\", secretNamespace, secretName, err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tsecret = make(map[string]string)\n\t\t\tfor name, data := range secretObj.Data {\n\t\t\t\tklog.V(4).Infof(\"retrieving CHAP secret name: %s\", name)\n\t\t\t\tsecret[name] = string(data)\n\t\t\t}\n\t\t}\n\t}\n\treturn secret, err\n}","line":{"from":621,"to":656}} {"id":100012488,"name":"createPersistentVolumeFromISCSIPVSource","signature":"func createPersistentVolumeFromISCSIPVSource(volumeName string, iscsi v1.ISCSIPersistentVolumeSource) *v1.PersistentVolume","file":"pkg/volume/iscsi/iscsi.go","code":"func createPersistentVolumeFromISCSIPVSource(volumeName string, iscsi v1.ISCSIPersistentVolumeSource) *v1.PersistentVolume {\n\tblock := v1.PersistentVolumeBlock\n\treturn \u0026v1.PersistentVolume{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: volumeName,\n\t\t},\n\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\tPersistentVolumeSource: v1.PersistentVolumeSource{\n\t\t\t\tISCSI: \u0026iscsi,\n\t\t\t},\n\t\t\tVolumeMode: \u0026block,\n\t\t},\n\t}\n}","line":{"from":658,"to":671}} {"id":100012489,"name":"getVolumeSpecFromGlobalMapPath","signature":"func getVolumeSpecFromGlobalMapPath(volumeName, globalMapPath string) (*volume.Spec, error)","file":"pkg/volume/iscsi/iscsi.go","code":"func getVolumeSpecFromGlobalMapPath(volumeName, globalMapPath string) (*volume.Spec, error) {\n\t// Retrieve volume spec information from globalMapPath\n\t// globalMapPath example:\n\t// plugins/kubernetes.io/{PluginName}/{DefaultKubeletVolumeDevicesDirName}/{volumePluginDependentPath}\n\t// plugins/kubernetes.io/iscsi/volumeDevices/iface-default/192.168.0.10:3260-iqn.2017-05.com.example:test-lun-0\n\n\t// device: 192.168.0.10:3260-iqn.2017-05.com.example:test-lun-0\n\tdevice, _, err := extractDeviceAndPrefix(globalMapPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbkpPortal, iqn, err := extractPortalAndIqn(device)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tarr := strings.Split(device, \"-lun-\")\n\tif len(arr) \u003c 2 {\n\t\treturn nil, fmt.Errorf(\"failed to retrieve lun from globalMapPath: %v\", globalMapPath)\n\t}\n\tlun, err := strconv.Atoi(arr[1])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tiface, found := extractIface(globalMapPath)\n\tif !found {\n\t\treturn nil, fmt.Errorf(\"failed to retrieve iface from globalMapPath: %v\", globalMapPath)\n\t}\n\tiscsiPV := createPersistentVolumeFromISCSIPVSource(volumeName,\n\t\tv1.ISCSIPersistentVolumeSource{\n\t\t\tTargetPortal: bkpPortal,\n\t\t\tIQN: iqn,\n\t\t\tLun: int32(lun),\n\t\t\tISCSIInterface: iface,\n\t\t},\n\t)\n\tklog.V(5).Infof(\"ConstructBlockVolumeSpec: TargetPortal: %v, IQN: %v, Lun: %v, ISCSIInterface: %v\",\n\t\tiscsiPV.Spec.PersistentVolumeSource.ISCSI.TargetPortal,\n\t\tiscsiPV.Spec.PersistentVolumeSource.ISCSI.IQN,\n\t\tiscsiPV.Spec.PersistentVolumeSource.ISCSI.Lun,\n\t\tiscsiPV.Spec.PersistentVolumeSource.ISCSI.ISCSIInterface,\n\t)\n\treturn volume.NewSpecFromPersistentVolume(iscsiPV, false), nil\n}","line":{"from":673,"to":715}} {"id":100012490,"name":"updateISCSIDiscoverydb","signature":"func updateISCSIDiscoverydb(b iscsiDiskMounter, tp string) error","file":"pkg/volume/iscsi/iscsi_util.go","code":"func updateISCSIDiscoverydb(b iscsiDiskMounter, tp string) error {\n\tif !b.chapDiscovery {\n\t\treturn nil\n\t}\n\tout, err := execWithLog(b, \"iscsiadm\", \"-m\", \"discoverydb\", \"-t\", \"sendtargets\", \"-p\", tp, \"-I\", b.Iface, \"-o\", \"update\", \"-n\", \"discovery.sendtargets.auth.authmethod\", \"-v\", \"CHAP\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"iscsi: failed to update discoverydb with CHAP, output: %v\", out)\n\t}\n\n\tfor _, k := range chapSt {\n\t\tv := b.secret[k]\n\t\tif len(v) \u003e 0 {\n\t\t\t// explicitly not using execWithLog so secrets are not logged\n\t\t\tout, err := b.exec.Command(\"iscsiadm\", \"-m\", \"discoverydb\", \"-t\", \"sendtargets\", \"-p\", tp, \"-I\", b.Iface, \"-o\", \"update\", \"-n\", k, \"-v\", v).CombinedOutput()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"iscsi: failed to update discoverydb key %q error: %v\", k, string(out))\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":87,"to":107}} {"id":100012491,"name":"updateISCSINode","signature":"func updateISCSINode(b iscsiDiskMounter, tp string) error","file":"pkg/volume/iscsi/iscsi_util.go","code":"func updateISCSINode(b iscsiDiskMounter, tp string) error {\n\t// setting node.session.scan to manual to handle https://github.com/kubernetes/kubernetes/issues/90982\n\tout, err := execWithLog(b, \"iscsiadm\", \"-m\", \"node\", \"-p\", tp, \"-T\", b.Iqn, \"-I\", b.Iface, \"-o\", \"update\", \"-n\", \"node.session.scan\", \"-v\", \"manual\")\n\tif err != nil {\n\t\t// don't fail if iscsiadm fails or the version does not support node.session.scan - log a warning to highlight the potential exposure\n\t\tklog.Warningf(\"iscsi: failed to update node with node.session.scan=manual, possible exposure to issue 90982: %v\", out)\n\t}\n\n\tif !b.chapSession {\n\t\treturn nil\n\t}\n\n\tout, err = execWithLog(b, \"iscsiadm\", \"-m\", \"node\", \"-p\", tp, \"-T\", b.Iqn, \"-I\", b.Iface, \"-o\", \"update\", \"-n\", \"node.session.auth.authmethod\", \"-v\", \"CHAP\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"iscsi: failed to update node with CHAP, output: %v\", out)\n\t}\n\n\tfor _, k := range chapSess {\n\t\tv := b.secret[k]\n\t\tif len(v) \u003e 0 {\n\t\t\t// explicitly not using execWithLog so secrets are not logged\n\t\t\tout, err := b.exec.Command(\"iscsiadm\", \"-m\", \"node\", \"-p\", tp, \"-T\", b.Iqn, \"-I\", b.Iface, \"-o\", \"update\", \"-n\", k, \"-v\", v).CombinedOutput()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"iscsi: failed to update node session key %q error: %v\", k, string(out))\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":109,"to":137}} {"id":100012492,"name":"waitForPathToExist","signature":"func waitForPathToExist(devicePath *string, maxRetries int, deviceTransport string) bool","file":"pkg/volume/iscsi/iscsi_util.go","code":"func waitForPathToExist(devicePath *string, maxRetries int, deviceTransport string) bool {\n\t// This makes unit testing a lot easier\n\treturn waitForPathToExistInternal(devicePath, maxRetries, deviceTransport, os.Stat, filepath.Glob)\n}","line":{"from":144,"to":147}} {"id":100012493,"name":"waitForPathToExistInternal","signature":"func waitForPathToExistInternal(devicePath *string, maxRetries int, deviceTransport string, osStat StatFunc, filepathGlob GlobFunc) bool","file":"pkg/volume/iscsi/iscsi_util.go","code":"func waitForPathToExistInternal(devicePath *string, maxRetries int, deviceTransport string, osStat StatFunc, filepathGlob GlobFunc) bool {\n\tif devicePath == nil {\n\t\treturn false\n\t}\n\n\tfor i := 0; i \u003c maxRetries; i++ {\n\t\tvar err error\n\t\tif deviceTransport == \"tcp\" {\n\t\t\t_, err = osStat(*devicePath)\n\t\t} else {\n\t\t\tfpath, _ := filepathGlob(*devicePath)\n\t\t\tif fpath == nil {\n\t\t\t\terr = os.ErrNotExist\n\t\t\t} else {\n\t\t\t\t// There might be a case that fpath contains multiple device paths if\n\t\t\t\t// multiple PCI devices connect to same iscsi target. We handle this\n\t\t\t\t// case at subsequent logic. Pick up only first path here.\n\t\t\t\t*devicePath = fpath[0]\n\t\t\t}\n\t\t}\n\t\tif err == nil {\n\t\t\treturn true\n\t\t}\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn false\n\t\t}\n\t\tif i == maxRetries-1 {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(time.Second)\n\t}\n\treturn false\n}","line":{"from":149,"to":181}} {"id":100012494,"name":"makePDNameInternal","signature":"func makePDNameInternal(host volume.VolumeHost, portal string, iqn string, lun string, iface string) string","file":"pkg/volume/iscsi/iscsi_util.go","code":"// make a directory like /var/lib/kubelet/plugins/kubernetes.io/iscsi/iface_name/portal-some_iqn-lun-lun_id\nfunc makePDNameInternal(host volume.VolumeHost, portal string, iqn string, lun string, iface string) string {\n\treturn filepath.Join(host.GetPluginDir(iscsiPluginName), \"iface-\"+iface, portal+\"-\"+iqn+\"-lun-\"+lun)\n}","line":{"from":183,"to":186}} {"id":100012495,"name":"makeVDPDNameInternal","signature":"func makeVDPDNameInternal(host volume.VolumeHost, portal string, iqn string, lun string, iface string) string","file":"pkg/volume/iscsi/iscsi_util.go","code":"// make a directory like /var/lib/kubelet/plugins/kubernetes.io/iscsi/volumeDevices/iface_name/portal-some_iqn-lun-lun_id\nfunc makeVDPDNameInternal(host volume.VolumeHost, portal string, iqn string, lun string, iface string) string {\n\treturn filepath.Join(host.GetVolumeDevicePluginDir(iscsiPluginName), \"iface-\"+iface, portal+\"-\"+iqn+\"-lun-\"+lun)\n}","line":{"from":188,"to":191}} {"id":100012496,"name":"MakeGlobalPDName","signature":"func (util *ISCSIUtil) MakeGlobalPDName(iscsi iscsiDisk) string","file":"pkg/volume/iscsi/iscsi_util.go","code":"// MakeGlobalPDName returns path of global plugin dir\nfunc (util *ISCSIUtil) MakeGlobalPDName(iscsi iscsiDisk) string {\n\treturn makePDNameInternal(iscsi.plugin.host, iscsi.Portals[0], iscsi.Iqn, iscsi.Lun, iscsi.Iface)\n}","line":{"from":195,"to":198}} {"id":100012497,"name":"MakeGlobalVDPDName","signature":"func (util *ISCSIUtil) MakeGlobalVDPDName(iscsi iscsiDisk) string","file":"pkg/volume/iscsi/iscsi_util.go","code":"// MakeGlobalVDPDName returns path of global volume device plugin dir\nfunc (util *ISCSIUtil) MakeGlobalVDPDName(iscsi iscsiDisk) string {\n\treturn makeVDPDNameInternal(iscsi.plugin.host, iscsi.Portals[0], iscsi.Iqn, iscsi.Lun, iscsi.Iface)\n}","line":{"from":200,"to":203}} {"id":100012498,"name":"persistISCSIFile","signature":"func (util *ISCSIUtil) persistISCSIFile(conf iscsiDisk, mnt string) error","file":"pkg/volume/iscsi/iscsi_util.go","code":"// persistISCSIFile saves iSCSI volume configuration for DetachDisk\n// into given directory.\nfunc (util *ISCSIUtil) persistISCSIFile(conf iscsiDisk, mnt string) error {\n\tfile := filepath.Join(mnt, \"iscsi.json\")\n\tfp, err := os.Create(file)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"iscsi: create %s err %s\", file, err)\n\t}\n\tdefer fp.Close()\n\tencoder := json.NewEncoder(fp)\n\tif err = encoder.Encode(conf); err != nil {\n\t\treturn fmt.Errorf(\"iscsi: encode err: %v\", err)\n\t}\n\treturn nil\n}","line":{"from":205,"to":219}} {"id":100012499,"name":"loadISCSI","signature":"func (util *ISCSIUtil) loadISCSI(conf *iscsiDisk, mnt string) error","file":"pkg/volume/iscsi/iscsi_util.go","code":"func (util *ISCSIUtil) loadISCSI(conf *iscsiDisk, mnt string) error {\n\tfile := filepath.Join(mnt, \"iscsi.json\")\n\tfp, err := os.Open(file)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"iscsi: open %s err %s\", file, err)\n\t}\n\tdefer fp.Close()\n\tdecoder := json.NewDecoder(fp)\n\tif err = decoder.Decode(conf); err != nil {\n\t\treturn fmt.Errorf(\"iscsi: decode err: %v\", err)\n\t}\n\treturn nil\n}","line":{"from":221,"to":233}} {"id":100012500,"name":"scanOneLun","signature":"func scanOneLun(hostNumber int, lunNumber int) error","file":"pkg/volume/iscsi/iscsi_util.go","code":"// scanOneLun scans a single LUN on one SCSI bus\n// Use this to avoid scanning the whole SCSI bus for all of the LUNs, which\n// would result in the kernel on this node discovering LUNs that it shouldn't\n// know about. Extraneous LUNs cause problems because they may get deleted\n// without us getting notified, since we were never supposed to know about\n// them. When LUNs are deleted without proper cleanup in the kernel, I/O errors\n// and timeouts result, which can noticeably degrade performance of future\n// operations.\nfunc scanOneLun(hostNumber int, lunNumber int) error {\n\tfilename := fmt.Sprintf(\"/sys/class/scsi_host/host%d/scan\", hostNumber)\n\tfd, err := os.OpenFile(filename, os.O_WRONLY, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fd.Close()\n\n\t// Channel/Target are always 0 for iSCSI\n\tscanCmd := fmt.Sprintf(\"0 0 %d\", lunNumber)\n\tif written, err := fd.WriteString(scanCmd); err != nil {\n\t\treturn err\n\t} else if 0 == written {\n\t\treturn fmt.Errorf(\"no data written to file: %s\", filename)\n\t}\n\n\tklog.V(3).Infof(\"Scanned SCSI host %d LUN %d\", hostNumber, lunNumber)\n\treturn nil\n}","line":{"from":235,"to":261}} {"id":100012501,"name":"waitForMultiPathToExist","signature":"func waitForMultiPathToExist(devicePaths []string, maxRetries int, deviceUtil volumeutil.DeviceUtil) string","file":"pkg/volume/iscsi/iscsi_util.go","code":"func waitForMultiPathToExist(devicePaths []string, maxRetries int, deviceUtil volumeutil.DeviceUtil) string {\n\tif 0 == len(devicePaths) {\n\t\treturn \"\"\n\t}\n\n\tfor i := 0; i \u003c maxRetries; i++ {\n\t\tfor _, path := range devicePaths {\n\t\t\t// There shouldn't be any empty device paths. However adding this check\n\t\t\t// for safer side to avoid the possibility of an empty entry.\n\t\t\tif path == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// check if the dev is using mpio and if so mount it via the dm-XX device\n\t\t\tif mappedDevicePath := deviceUtil.FindMultipathDeviceForDevice(path); mappedDevicePath != \"\" {\n\t\t\t\treturn mappedDevicePath\n\t\t\t}\n\t\t}\n\t\tif i == maxRetries-1 {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(time.Second)\n\t}\n\treturn \"\"\n}","line":{"from":263,"to":286}} {"id":100012502,"name":"AttachDisk","signature":"func (util *ISCSIUtil) AttachDisk(b iscsiDiskMounter) (string, error)","file":"pkg/volume/iscsi/iscsi_util.go","code":"// AttachDisk returns devicePath of volume if attach succeeded otherwise returns error\nfunc (util *ISCSIUtil) AttachDisk(b iscsiDiskMounter) (string, error) {\n\tvar devicePath string\n\tdevicePaths := map[string]string{}\n\tvar iscsiTransport string\n\tvar lastErr error\n\n\tout, err := execWithLog(b, \"iscsiadm\", \"-m\", \"iface\", \"-I\", b.InitIface, \"-o\", \"show\")\n\tif err != nil {\n\t\tklog.Errorf(\"iscsi: could not read iface %s error: %s\", b.InitIface, out)\n\t\treturn \"\", err\n\t}\n\n\tiscsiTransport = extractTransportname(out)\n\n\tbkpPortal := b.Portals\n\n\t// If the initiator name was set, the iface isn't created yet,\n\t// so create it and copy parameters from the pre-configured one\n\tif b.InitiatorName != \"\" {\n\t\tif err = cloneIface(b); err != nil {\n\t\t\tklog.Errorf(\"iscsi: failed to clone iface: %s error: %v\", b.InitIface, err)\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\t// Lock the target while we login to avoid races between 2 volumes that share the same\n\t// target both logging in or one logging out while another logs in.\n\tb.plugin.targetLocks.LockKey(b.Iqn)\n\tdefer b.plugin.targetLocks.UnlockKey(b.Iqn)\n\n\t// Build a map of SCSI hosts for each target portal. We will need this to\n\t// issue the bus rescans.\n\tportalHostMap, err := b.deviceUtil.GetISCSIPortalHostMapForTarget(b.Iqn)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tklog.V(4).Infof(\"AttachDisk portal-\u003ehost map for %s is %v\", b.Iqn, portalHostMap)\n\n\tfor i := 1; i \u003c= maxAttachAttempts; i++ {\n\t\tfor _, tp := range bkpPortal {\n\t\t\tif _, found := devicePaths[tp]; found {\n\t\t\t\tklog.V(4).Infof(\"Device for portal %q already known\", tp)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\thostNumber, loggedIn := portalHostMap[tp]\n\t\t\tif !loggedIn {\n\t\t\t\tklog.V(4).Infof(\"Could not get SCSI host number for portal %s, will attempt login\", tp)\n\n\t\t\t\t// build discoverydb and discover iscsi target\n\t\t\t\texecWithLog(b, \"iscsiadm\", \"-m\", \"discoverydb\", \"-t\", \"sendtargets\", \"-p\", tp, \"-I\", b.Iface, \"-o\", \"new\")\n\n\t\t\t\t// update discoverydb with CHAP secret\n\t\t\t\terr = updateISCSIDiscoverydb(b, tp)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlastErr = fmt.Errorf(\"iscsi: failed to update discoverydb to portal %s error: %v\", tp, err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tout, err = execWithLog(b, \"iscsiadm\", \"-m\", \"discoverydb\", \"-t\", \"sendtargets\", \"-p\", tp, \"-I\", b.Iface, \"--discover\")\n\t\t\t\tif err != nil {\n\t\t\t\t\t// delete discoverydb record\n\t\t\t\t\texecWithLog(b, \"iscsiadm\", \"-m\", \"discoverydb\", \"-t\", \"sendtargets\", \"-p\", tp, \"-I\", b.Iface, \"-o\", \"delete\")\n\t\t\t\t\tlastErr = fmt.Errorf(\"iscsi: failed to sendtargets to portal %s output: %s, err %v\", tp, out, err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\terr = updateISCSINode(b, tp)\n\t\t\t\tif err != nil {\n\t\t\t\t\t// failure to update node db is rare. But deleting record will likely impact those who already start using it.\n\t\t\t\t\tlastErr = fmt.Errorf(\"iscsi: failed to update iscsi node to portal %s error: %v\", tp, err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// login to iscsi target\n\t\t\t\tout, err = execWithLog(b, \"iscsiadm\", \"-m\", \"node\", \"-p\", tp, \"-T\", b.Iqn, \"-I\", b.Iface, \"--login\")\n\t\t\t\tif err != nil {\n\t\t\t\t\t// delete the node record from database\n\t\t\t\t\texecWithLog(b, \"iscsiadm\", \"-m\", \"node\", \"-p\", tp, \"-I\", b.Iface, \"-T\", b.Iqn, \"-o\", \"delete\")\n\t\t\t\t\tlastErr = fmt.Errorf(\"iscsi: failed to attach disk: Error: %s (%v)\", out, err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// in case of node failure/restart, explicitly set to manual login so it doesn't hang on boot\n\t\t\t\t_, err = execWithLog(b, \"iscsiadm\", \"-m\", \"node\", \"-p\", tp, \"-T\", b.Iqn, \"-o\", \"update\", \"-n\", \"node.startup\", \"-v\", \"manual\")\n\t\t\t\tif err != nil {\n\t\t\t\t\t// don't fail if we can't set startup mode, but log warning so there is a clue\n\t\t\t\t\tklog.Warningf(\"Warning: Failed to set iSCSI login mode to manual. Error: %v\", err)\n\t\t\t\t}\n\n\t\t\t\t// Rebuild the host map after logging in\n\t\t\t\tportalHostMap, err := b.deviceUtil.GetISCSIPortalHostMapForTarget(b.Iqn)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn \"\", err\n\t\t\t\t}\n\t\t\t\tklog.V(6).Infof(\"AttachDisk portal-\u003ehost map for %s is %v\", b.Iqn, portalHostMap)\n\n\t\t\t\thostNumber, loggedIn = portalHostMap[tp]\n\t\t\t\tif !loggedIn {\n\t\t\t\t\tklog.Warningf(\"Could not get SCSI host number for portal %s after logging in\", tp)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tklog.V(5).Infof(\"AttachDisk: scanning SCSI host %d LUN %s\", hostNumber, b.Lun)\n\t\t\tlunNumber, err := strconv.Atoi(b.Lun)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", fmt.Errorf(\"AttachDisk: lun is not a number: %s\\nError: %v\", b.Lun, err)\n\t\t\t}\n\n\t\t\t// Scan the iSCSI bus for the LUN\n\t\t\terr = scanOneLun(hostNumber, lunNumber)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\n\t\t\tif iscsiTransport == \"\" {\n\t\t\t\tklog.Errorf(\"iscsi: could not find transport name in iface %s\", b.Iface)\n\t\t\t\treturn \"\", fmt.Errorf(\"could not parse iface file for %s\", b.Iface)\n\t\t\t}\n\n\t\t\taddr := tp\n\t\t\tif strings.HasPrefix(tp, \"[\") {\n\t\t\t\t// Delete [] from IP address, links in /dev/disk/by-path do not have it.\n\t\t\t\taddr = strings.NewReplacer(\"[\", \"\", \"]\", \"\").Replace(tp)\n\t\t\t}\n\t\t\tif iscsiTransport == \"tcp\" {\n\t\t\t\tdevicePath = strings.Join([]string{\"/dev/disk/by-path/ip\", addr, \"iscsi\", b.Iqn, \"lun\", b.Lun}, \"-\")\n\t\t\t} else {\n\t\t\t\tdevicePath = strings.Join([]string{\"/dev/disk/by-path/pci\", \"*\", \"ip\", addr, \"iscsi\", b.Iqn, \"lun\", b.Lun}, \"-\")\n\t\t\t}\n\n\t\t\tif exist := waitForPathToExist(\u0026devicePath, deviceDiscoveryTimeout, iscsiTransport); !exist {\n\t\t\t\tmsg := fmt.Sprintf(\"Timed out waiting for device at path %s after %ds\", devicePath, deviceDiscoveryTimeout)\n\t\t\t\tklog.Error(msg)\n\t\t\t\t// update last error\n\t\t\t\tlastErr = errors.New(msg)\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tdevicePaths[tp] = devicePath\n\t\t\t}\n\t\t}\n\t\tklog.V(4).Infof(\"iscsi: tried all devices for %q %d times, %d paths found\", b.Iqn, i, len(devicePaths))\n\t\tif len(devicePaths) == 0 {\n\t\t\t// No path attached, report error and stop trying. kubelet will try again in a short while\n\t\t\t// delete cloned iface\n\t\t\texecWithLog(b, \"iscsiadm\", \"-m\", \"iface\", \"-I\", b.Iface, \"-o\", \"delete\")\n\t\t\tklog.Errorf(\"iscsi: failed to get any path for iscsi disk, last err seen:\\n%v\", lastErr)\n\t\t\treturn \"\", fmt.Errorf(\"failed to get any path for iscsi disk, last err seen:\\n%v\", lastErr)\n\t\t}\n\t\tif len(devicePaths) == len(bkpPortal) {\n\t\t\t// We have all paths\n\t\t\tklog.V(4).Infof(\"iscsi: all devices for %q found\", b.Iqn)\n\t\t\tbreak\n\t\t}\n\t\tif len(devicePaths) \u003e= minMultipathCount \u0026\u0026 i \u003e= minAttachAttempts {\n\t\t\t// We have at least two paths for multipath and we tried the other paths long enough\n\t\t\tklog.V(4).Infof(\"%d devices found for %q\", len(devicePaths), b.Iqn)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif lastErr != nil {\n\t\tklog.Errorf(\"iscsi: last error occurred during iscsi init:\\n%v\", lastErr)\n\t}\n\n\tdevicePathList := []string{}\n\tfor _, path := range devicePaths {\n\t\tdevicePathList = append(devicePathList, path)\n\t}\n\t// Try to find a multipath device for the volume\n\tif len(bkpPortal) \u003e 1 {\n\t\t// Multipath volume was requested. Wait up to multipathDeviceTimeout seconds for the multipath device to appear.\n\t\tdevicePath = waitForMultiPathToExist(devicePathList, multipathDeviceTimeout, b.deviceUtil)\n\t} else {\n\t\t// For PVs with 1 portal, just try one time to find the multipath device. This\n\t\t// avoids a long pause when the multipath device will never get created, and\n\t\t// matches legacy behavior.\n\t\tdevicePath = waitForMultiPathToExist(devicePathList, 1, b.deviceUtil)\n\t}\n\n\t// When no multipath device is found, just use the first (and presumably only) device\n\tif devicePath == \"\" {\n\t\tdevicePath = devicePathList[0]\n\t}\n\n\tklog.V(5).Infof(\"iscsi: AttachDisk devicePath: %s\", devicePath)\n\n\tif err = util.persistISCSI(b); err != nil {\n\t\t// Return uncertain error so kubelet calls Unmount / Unmap when the pod\n\t\t// is deleted.\n\t\treturn \"\", types.NewUncertainProgressError(err.Error())\n\t}\n\treturn devicePath, nil\n}","line":{"from":288,"to":483}} {"id":100012503,"name":"persistISCSI","signature":"func (util *ISCSIUtil) persistISCSI(b iscsiDiskMounter) error","file":"pkg/volume/iscsi/iscsi_util.go","code":"// persistISCSI saves iSCSI volume configuration for DetachDisk into global\n// mount / map directory.\nfunc (util *ISCSIUtil) persistISCSI(b iscsiDiskMounter) error {\n\tklog.V(5).Infof(\"iscsi: AttachDisk volumeMode: %s\", b.volumeMode)\n\tvar globalPDPath string\n\tif b.volumeMode == v1.PersistentVolumeBlock {\n\t\tglobalPDPath = b.manager.MakeGlobalVDPDName(*b.iscsiDisk)\n\t} else {\n\t\tglobalPDPath = b.manager.MakeGlobalPDName(*b.iscsiDisk)\n\t}\n\n\tif err := os.MkdirAll(globalPDPath, 0750); err != nil {\n\t\tklog.Errorf(\"iscsi: failed to mkdir %s, error\", globalPDPath)\n\t\treturn err\n\t}\n\n\tif b.volumeMode == v1.PersistentVolumeFilesystem {\n\t\tnotMnt, err := b.mounter.IsLikelyNotMountPoint(globalPDPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !notMnt {\n\t\t\t// The volume is already mounted, therefore the previous WaitForAttach must have\n\t\t\t// persisted the volume metadata. In addition, the metadata is actually *inside*\n\t\t\t// globalPDPath and we can't write it here, because it was shadowed by the volume\n\t\t\t// mount.\n\t\t\tklog.V(4).Infof(\"Skipping persistISCSI, the volume is already mounted at %s\", globalPDPath)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t// Persist iscsi disk config to json file for DetachDisk path\n\treturn util.persistISCSIFile(*(b.iscsiDisk), globalPDPath)\n}","line":{"from":485,"to":518}} {"id":100012504,"name":"deleteDevice","signature":"func deleteDevice(deviceName string) error","file":"pkg/volume/iscsi/iscsi_util.go","code":"// Delete 1 block device of the form \"sd*\"\nfunc deleteDevice(deviceName string) error {\n\tfilename := fmt.Sprintf(\"/sys/block/%s/device/delete\", deviceName)\n\tfd, err := os.OpenFile(filename, os.O_WRONLY, 0)\n\tif err != nil {\n\t\t// The file was not present, so just return without error\n\t\treturn nil\n\t}\n\tdefer fd.Close()\n\n\tif written, err := fd.WriteString(\"1\"); err != nil {\n\t\treturn err\n\t} else if 0 == written {\n\t\treturn fmt.Errorf(\"no data written to file: %s\", filename)\n\t}\n\tklog.V(4).Infof(\"Deleted block device: %s\", deviceName)\n\treturn nil\n}","line":{"from":520,"to":537}} {"id":100012505,"name":"deleteDevices","signature":"func deleteDevices(c iscsiDiskUnmounter) error","file":"pkg/volume/iscsi/iscsi_util.go","code":"// deleteDevices tries to remove all the block devices and multipath map devices\n// associated with a given iscsi device\nfunc deleteDevices(c iscsiDiskUnmounter) error {\n\tlunNumber, err := strconv.Atoi(c.iscsiDisk.Lun)\n\tif err != nil {\n\t\tklog.Errorf(\"iscsi delete devices: lun is not a number: %s\\nError: %v\", c.iscsiDisk.Lun, err)\n\t\treturn err\n\t}\n\t// Enumerate the devices so we can delete them\n\tdeviceNames, err := c.deviceUtil.FindDevicesForISCSILun(c.iscsiDisk.Iqn, lunNumber)\n\tif err != nil {\n\t\tklog.Errorf(\"iscsi delete devices: could not get devices associated with LUN %d on target %s\\nError: %v\",\n\t\t\tlunNumber, c.iscsiDisk.Iqn, err)\n\t\treturn err\n\t}\n\t// Find the multipath device path(s)\n\tmpathDevices := make(map[string]bool)\n\tfor _, deviceName := range deviceNames {\n\t\tpath := \"/dev/\" + deviceName\n\t\t// check if the dev is using mpio and if so mount it via the dm-XX device\n\t\tif mappedDevicePath := c.deviceUtil.FindMultipathDeviceForDevice(path); mappedDevicePath != \"\" {\n\t\t\tmpathDevices[mappedDevicePath] = true\n\t\t}\n\t}\n\t// Flush any multipath device maps\n\tfor mpathDevice := range mpathDevices {\n\t\t_, err = c.exec.Command(\"multipath\", \"-f\", mpathDevice).CombinedOutput()\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"Warning: Failed to flush multipath device map: %s\\nError: %v\", mpathDevice, err)\n\t\t\t// Fall through -- keep deleting the block devices\n\t\t}\n\t\tklog.V(4).Infof(\"Flushed multipath device: %s\", mpathDevice)\n\t}\n\tfor _, deviceName := range deviceNames {\n\t\terr = deleteDevice(deviceName)\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"Warning: Failed to delete block device: %s\\nError: %v\", deviceName, err)\n\t\t\t// Fall through -- keep deleting other block devices\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":539,"to":580}} {"id":100012506,"name":"DetachDisk","signature":"func (util *ISCSIUtil) DetachDisk(c iscsiDiskUnmounter, mntPath string) error","file":"pkg/volume/iscsi/iscsi_util.go","code":"// DetachDisk unmounts and detaches a volume from node\nfunc (util *ISCSIUtil) DetachDisk(c iscsiDiskUnmounter, mntPath string) error {\n\tif pathExists, pathErr := mount.PathExists(mntPath); pathErr != nil {\n\t\treturn fmt.Errorf(\"error checking if path exists: %w\", pathErr)\n\t} else if !pathExists {\n\t\tklog.Warningf(\"Warning: Unmount skipped because path does not exist: %v\", mntPath)\n\t\treturn nil\n\t}\n\n\tnotMnt, err := c.mounter.IsLikelyNotMountPoint(mntPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !notMnt {\n\t\tif err := c.mounter.Unmount(mntPath); err != nil {\n\t\t\tklog.Errorf(\"iscsi detach disk: failed to unmount: %s\\nError: %v\", mntPath, err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// if device is no longer used, see if need to logout the target\n\tdevice, _, err := extractDeviceAndPrefix(mntPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar bkpPortal []string\n\tvar volName, iqn, iface, initiatorName string\n\tfound := true\n\n\t// load iscsi disk config from json file\n\tif err := util.loadISCSI(c.iscsiDisk, mntPath); err == nil {\n\t\tbkpPortal, iqn, iface, volName = c.iscsiDisk.Portals, c.iscsiDisk.Iqn, c.iscsiDisk.Iface, c.iscsiDisk.VolName\n\t\tinitiatorName = c.iscsiDisk.InitiatorName\n\t} else {\n\t\t// If the iscsi disk config is not found, fall back to the original behavior.\n\t\t// This portal/iqn/iface is no longer referenced, log out.\n\t\t// Extract the portal and iqn from device path.\n\t\tbkpPortal = make([]string, 1)\n\t\tbkpPortal[0], iqn, err = extractPortalAndIqn(device)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Extract the iface from the mountPath and use it to log out. If the iface\n\t\t// is not found, maintain the previous behavior to facilitate kubelet upgrade.\n\t\t// Logout may fail as no session may exist for the portal/IQN on the specified interface.\n\t\tiface, found = extractIface(mntPath)\n\t}\n\n\t// Delete all the scsi devices and any multipath devices after unmounting\n\tif err = deleteDevices(c); err != nil {\n\t\tklog.Warningf(\"iscsi detach disk: failed to delete devices\\nError: %v\", err)\n\t\t// Fall through -- even if deleting fails, a logout may fix problems\n\t}\n\n\t// Lock the target while we determine if we can safely log out or not\n\tc.plugin.targetLocks.LockKey(iqn)\n\tdefer c.plugin.targetLocks.UnlockKey(iqn)\n\n\tportals := removeDuplicate(bkpPortal)\n\tif len(portals) == 0 {\n\t\treturn fmt.Errorf(\"iscsi detach disk: failed to detach iscsi disk. Couldn't get connected portals from configurations\")\n\t}\n\n\t// If device is no longer used, see if need to logout the target\n\tif isSessionBusy(c.iscsiDisk.plugin.host, portals[0], iqn) {\n\t\treturn nil\n\t}\n\n\terr = util.detachISCSIDisk(c.exec, portals, iqn, iface, volName, initiatorName, found)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to finish detachISCSIDisk, err: %v\", err)\n\t}\n\treturn nil\n}","line":{"from":582,"to":656}} {"id":100012507,"name":"DetachBlockISCSIDisk","signature":"func (util *ISCSIUtil) DetachBlockISCSIDisk(c iscsiDiskUnmapper, mapPath string) error","file":"pkg/volume/iscsi/iscsi_util.go","code":"// DetachBlockISCSIDisk removes loopback device for a volume and detaches a volume from node\nfunc (util *ISCSIUtil) DetachBlockISCSIDisk(c iscsiDiskUnmapper, mapPath string) error {\n\tif pathExists, pathErr := mount.PathExists(mapPath); pathErr != nil {\n\t\treturn fmt.Errorf(\"error checking if path exists: %w\", pathErr)\n\t} else if !pathExists {\n\t\tklog.Warningf(\"Warning: Unmap skipped because path does not exist: %v\", mapPath)\n\t\treturn nil\n\t}\n\t// If we arrive here, device is no longer used, see if need to logout the target\n\t// device: 192.168.0.10:3260-iqn.2017-05.com.example:test-lun-0\n\tdevice, _, err := extractDeviceAndPrefix(mapPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar bkpPortal []string\n\tvar volName, iqn, lun, iface, initiatorName string\n\tfound := true\n\t// load iscsi disk config from json file\n\tif err := util.loadISCSI(c.iscsiDisk, mapPath); err == nil {\n\t\tbkpPortal, iqn, lun, iface, volName = c.iscsiDisk.Portals, c.iscsiDisk.Iqn, c.iscsiDisk.Lun, c.iscsiDisk.Iface, c.iscsiDisk.VolName\n\t\tinitiatorName = c.iscsiDisk.InitiatorName\n\t} else {\n\t\t// If the iscsi disk config is not found, fall back to the original behavior.\n\t\t// This portal/iqn/iface is no longer referenced, log out.\n\t\t// Extract the portal and iqn from device path.\n\t\tbkpPortal = make([]string, 1)\n\t\tbkpPortal[0], iqn, err = extractPortalAndIqn(device)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tarr := strings.Split(device, \"-lun-\")\n\t\tif len(arr) \u003c 2 {\n\t\t\treturn fmt.Errorf(\"failed to retrieve lun from mapPath: %v\", mapPath)\n\t\t}\n\t\tlun = arr[1]\n\t\t// Extract the iface from the mountPath and use it to log out. If the iface\n\t\t// is not found, maintain the previous behavior to facilitate kubelet upgrade.\n\t\t// Logout may fail as no session may exist for the portal/IQN on the specified interface.\n\t\tiface, found = extractIface(mapPath)\n\t}\n\tportals := removeDuplicate(bkpPortal)\n\tif len(portals) == 0 {\n\t\treturn fmt.Errorf(\"iscsi detach disk: failed to detach iscsi disk. Couldn't get connected portals from configurations\")\n\t}\n\n\tdevicePath := getDevByPath(portals[0], iqn, lun)\n\tklog.V(5).Infof(\"iscsi: devicePath: %s\", devicePath)\n\tif _, err = os.Stat(devicePath); err != nil {\n\t\treturn fmt.Errorf(\"failed to validate devicePath: %s\", devicePath)\n\t}\n\n\t// Lock the target while we determine if we can safely log out or not\n\tc.plugin.targetLocks.LockKey(iqn)\n\tdefer c.plugin.targetLocks.UnlockKey(iqn)\n\n\t// If device is no longer used, see if need to logout the target\n\tif isSessionBusy(c.iscsiDisk.plugin.host, portals[0], iqn) {\n\t\treturn nil\n\t}\n\n\t// Detach a volume from kubelet node\n\terr = util.detachISCSIDisk(c.exec, portals, iqn, iface, volName, initiatorName, found)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to finish detachISCSIDisk, err: %v\", err)\n\t}\n\treturn nil\n}","line":{"from":658,"to":724}} {"id":100012508,"name":"detachISCSIDisk","signature":"func (util *ISCSIUtil) detachISCSIDisk(exec utilexec.Interface, portals []string, iqn, iface, volName, initiatorName string, found bool) error","file":"pkg/volume/iscsi/iscsi_util.go","code":"func (util *ISCSIUtil) detachISCSIDisk(exec utilexec.Interface, portals []string, iqn, iface, volName, initiatorName string, found bool) error {\n\tfor _, portal := range portals {\n\t\tlogoutArgs := []string{\"-m\", \"node\", \"-p\", portal, \"-T\", iqn, \"--logout\"}\n\t\tdeleteArgs := []string{\"-m\", \"node\", \"-p\", portal, \"-T\", iqn, \"-o\", \"delete\"}\n\t\tif found {\n\t\t\tlogoutArgs = append(logoutArgs, []string{\"-I\", iface}...)\n\t\t\tdeleteArgs = append(deleteArgs, []string{\"-I\", iface}...)\n\t\t}\n\t\tklog.Infof(\"iscsi: log out target %s iqn %s iface %s\", portal, iqn, iface)\n\t\tout, err := exec.Command(\"iscsiadm\", logoutArgs...).CombinedOutput()\n\t\terr = ignoreExitCodes(err, exit_ISCSI_ERR_NO_OBJS_FOUND, exit_ISCSI_ERR_SESS_NOT_FOUND)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"iscsi: failed to detach disk Error: %s\", string(out))\n\t\t\treturn err\n\t\t}\n\t\t// Delete the node record\n\t\tklog.Infof(\"iscsi: delete node record target %s iqn %s\", portal, iqn)\n\t\tout, err = exec.Command(\"iscsiadm\", deleteArgs...).CombinedOutput()\n\t\terr = ignoreExitCodes(err, exit_ISCSI_ERR_NO_OBJS_FOUND, exit_ISCSI_ERR_SESS_NOT_FOUND)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"iscsi: failed to delete node record Error: %s\", string(out))\n\t\t\treturn err\n\t\t}\n\t}\n\t// Delete the iface after all sessions have logged out\n\t// If the iface is not created via iscsi plugin, skip to delete\n\tif initiatorName != \"\" \u0026\u0026 found \u0026\u0026 iface == (portals[0]+\":\"+volName) {\n\t\tdeleteArgs := []string{\"-m\", \"iface\", \"-I\", iface, \"-o\", \"delete\"}\n\t\tout, err := exec.Command(\"iscsiadm\", deleteArgs...).CombinedOutput()\n\t\terr = ignoreExitCodes(err, exit_ISCSI_ERR_NO_OBJS_FOUND, exit_ISCSI_ERR_SESS_NOT_FOUND)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"iscsi: failed to delete iface Error: %s\", string(out))\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":726,"to":763}} {"id":100012509,"name":"getDevByPath","signature":"func getDevByPath(portal, iqn, lun string) string","file":"pkg/volume/iscsi/iscsi_util.go","code":"func getDevByPath(portal, iqn, lun string) string {\n\treturn \"/dev/disk/by-path/ip-\" + portal + \"-iscsi-\" + iqn + \"-lun-\" + lun\n}","line":{"from":765,"to":767}} {"id":100012510,"name":"extractTransportname","signature":"func extractTransportname(ifaceOutput string) (iscsiTransport string)","file":"pkg/volume/iscsi/iscsi_util.go","code":"func extractTransportname(ifaceOutput string) (iscsiTransport string) {\n\trexOutput := ifaceTransportNameRe.FindStringSubmatch(ifaceOutput)\n\tif rexOutput == nil {\n\t\treturn \"\"\n\t}\n\tiscsiTransport = rexOutput[1]\n\n\t// While iface.transport_name is a required parameter, handle it being unspecified anyways\n\tif iscsiTransport == \"\u003cempty\u003e\" {\n\t\tiscsiTransport = \"tcp\"\n\t}\n\treturn iscsiTransport\n}","line":{"from":769,"to":781}} {"id":100012511,"name":"extractDeviceAndPrefix","signature":"func extractDeviceAndPrefix(mntPath string) (string, string, error)","file":"pkg/volume/iscsi/iscsi_util.go","code":"func extractDeviceAndPrefix(mntPath string) (string, string, error) {\n\tind := strings.LastIndex(mntPath, \"/\")\n\tif ind \u003c 0 {\n\t\treturn \"\", \"\", fmt.Errorf(\"iscsi detach disk: malformatted mnt path: %s\", mntPath)\n\t}\n\tdevice := mntPath[(ind + 1):]\n\t// strip -lun- from mount path\n\tind = strings.LastIndex(mntPath, \"-lun-\")\n\tif ind \u003c 0 {\n\t\treturn \"\", \"\", fmt.Errorf(\"iscsi detach disk: malformatted mnt path: %s\", mntPath)\n\t}\n\tprefix := mntPath[:ind]\n\treturn device, prefix, nil\n}","line":{"from":783,"to":796}} {"id":100012512,"name":"extractIface","signature":"func extractIface(mntPath string) (string, bool)","file":"pkg/volume/iscsi/iscsi_util.go","code":"func extractIface(mntPath string) (string, bool) {\n\treOutput := ifaceRe.FindStringSubmatch(mntPath)\n\tif len(reOutput) \u003e 1 {\n\t\treturn reOutput[1], true\n\t}\n\n\treturn \"\", false\n}","line":{"from":798,"to":805}} {"id":100012513,"name":"extractPortalAndIqn","signature":"func extractPortalAndIqn(device string) (string, string, error)","file":"pkg/volume/iscsi/iscsi_util.go","code":"func extractPortalAndIqn(device string) (string, string, error) {\n\tind1 := strings.Index(device, \"-\")\n\tif ind1 \u003c 0 {\n\t\treturn \"\", \"\", fmt.Errorf(\"iscsi detach disk: no portal in %s\", device)\n\t}\n\tportal := device[0:ind1]\n\tind2 := strings.Index(device, \"iqn.\")\n\tif ind2 \u003c 0 {\n\t\tind2 = strings.Index(device, \"eui.\")\n\t}\n\tif ind2 \u003c 0 {\n\t\treturn \"\", \"\", fmt.Errorf(\"iscsi detach disk: no iqn in %s\", device)\n\t}\n\tind := strings.LastIndex(device, \"-lun-\")\n\tiqn := device[ind2:ind]\n\treturn portal, iqn, nil\n}","line":{"from":807,"to":823}} {"id":100012514,"name":"removeDuplicate","signature":"func removeDuplicate(s []string) []string","file":"pkg/volume/iscsi/iscsi_util.go","code":"// Remove duplicates or string\nfunc removeDuplicate(s []string) []string {\n\tm := map[string]bool{}\n\tfor _, v := range s {\n\t\tif v != \"\" \u0026\u0026 !m[v] {\n\t\t\ts[len(m)] = v\n\t\t\tm[v] = true\n\t\t}\n\t}\n\ts = s[:len(m)]\n\treturn s\n}","line":{"from":825,"to":836}} {"id":100012515,"name":"parseIscsiadmShow","signature":"func parseIscsiadmShow(output string) (map[string]string, error)","file":"pkg/volume/iscsi/iscsi_util.go","code":"func parseIscsiadmShow(output string) (map[string]string, error) {\n\tparams := make(map[string]string)\n\tslice := strings.Split(output, \"\\n\")\n\tfor _, line := range slice {\n\t\tif !strings.HasPrefix(line, \"iface.\") || strings.Contains(line, \"\u003cempty\u003e\") {\n\t\t\tcontinue\n\t\t}\n\t\tiface := strings.Fields(line)\n\t\tif len(iface) != 3 || iface[1] != \"=\" {\n\t\t\treturn nil, fmt.Errorf(\"error: invalid iface setting: %v\", iface)\n\t\t}\n\t\t// iscsi_ifacename is immutable once the iface is created\n\t\tif iface[0] == \"iface.iscsi_ifacename\" {\n\t\t\tcontinue\n\t\t}\n\t\tparams[iface[0]] = iface[2]\n\t}\n\treturn params, nil\n}","line":{"from":838,"to":856}} {"id":100012516,"name":"cloneIface","signature":"func cloneIface(b iscsiDiskMounter) error","file":"pkg/volume/iscsi/iscsi_util.go","code":"func cloneIface(b iscsiDiskMounter) error {\n\tvar lastErr error\n\tif b.InitIface == b.Iface {\n\t\treturn fmt.Errorf(\"iscsi: cannot clone iface with same name: %s\", b.InitIface)\n\t}\n\t// get pre-configured iface records\n\tout, err := execWithLog(b, \"iscsiadm\", \"-m\", \"iface\", \"-I\", b.InitIface, \"-o\", \"show\")\n\tif err != nil {\n\t\tlastErr = fmt.Errorf(\"iscsi: failed to show iface records: %s (%v)\", out, err)\n\t\treturn lastErr\n\t}\n\t// parse obtained records\n\tparams, err := parseIscsiadmShow(out)\n\tif err != nil {\n\t\tlastErr = fmt.Errorf(\"iscsi: failed to parse iface records: %s (%v)\", out, err)\n\t\treturn lastErr\n\t}\n\t// update initiatorname\n\tparams[\"iface.initiatorname\"] = b.InitiatorName\n\t// create new iface\n\tout, err = execWithLog(b, \"iscsiadm\", \"-m\", \"iface\", \"-I\", b.Iface, \"-o\", \"new\")\n\tif err != nil {\n\t\texit, ok := err.(utilexec.ExitError)\n\t\tif ok \u0026\u0026 exit.ExitStatus() == iscsiadmErrorSessExists {\n\t\t\tklog.Infof(\"iscsi: there is a session already logged in with iface %s\", b.Iface)\n\t\t} else {\n\t\t\tlastErr = fmt.Errorf(\"iscsi: failed to create new iface: %s (%v)\", out, err)\n\t\t\treturn lastErr\n\t\t}\n\t}\n\t// Get and sort keys to maintain a stable iteration order\n\tvar keys []string\n\tfor k := range params {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\t// update new iface records\n\tfor _, key := range keys {\n\t\t_, err = execWithLog(b, \"iscsiadm\", \"-m\", \"iface\", \"-I\", b.Iface, \"-o\", \"update\", \"-n\", key, \"-v\", params[key])\n\t\tif err != nil {\n\t\t\texecWithLog(b, \"iscsiadm\", \"-m\", \"iface\", \"-I\", b.Iface, \"-o\", \"delete\")\n\t\t\tlastErr = fmt.Errorf(\"iscsi: failed to update iface records: %s (%v). iface(%s) will be used\", out, err, b.InitIface)\n\t\t\tbreak\n\t\t}\n\t}\n\treturn lastErr\n}","line":{"from":858,"to":904}} {"id":100012517,"name":"isSessionBusy","signature":"func isSessionBusy(host volume.VolumeHost, portal, iqn string) bool","file":"pkg/volume/iscsi/iscsi_util.go","code":"// isSessionBusy determines if the iSCSI session is busy by counting both FS and block volumes in use.\nfunc isSessionBusy(host volume.VolumeHost, portal, iqn string) bool {\n\tfsDir := host.GetPluginDir(iscsiPluginName)\n\tcountFS, err := getVolCount(fsDir, portal, iqn)\n\tif err != nil {\n\t\tklog.Errorf(\"iscsi: could not determine FS volumes in use: %v\", err)\n\t\treturn true\n\t}\n\n\tblockDir := host.GetVolumeDevicePluginDir(iscsiPluginName)\n\tcountBlock, err := getVolCount(blockDir, portal, iqn)\n\tif err != nil {\n\t\tklog.Errorf(\"iscsi: could not determine block volumes in use: %v\", err)\n\t\treturn true\n\t}\n\n\treturn countFS+countBlock \u003e 1\n}","line":{"from":906,"to":923}} {"id":100012518,"name":"getVolCount","signature":"func getVolCount(dir, portal, iqn string) (int, error)","file":"pkg/volume/iscsi/iscsi_util.go","code":"// getVolCount returns the number of volumes in use by the kubelet.\n// It does so by counting the number of directories prefixed by the given portal and IQN.\nfunc getVolCount(dir, portal, iqn string) (int, error) {\n\t// For FileSystem volumes, the topmost dirs are named after the ifaces, e.g., iface-default or iface-127.0.0.1:3260:pv0.\n\t// For Block volumes, the default topmost dir is volumeDevices.\n\tcontents, err := ioutil.ReadDir(dir)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn 0, nil\n\t\t}\n\t\treturn 0, err\n\t}\n\n\t// Inside each iface dir, we look for volume dirs prefixed by the given\n\t// portal + iqn, e.g., 127.0.0.1:3260-iqn.2003-01.io.k8s:e2e.volume-1-lun-2\n\tvar counter int\n\tfor _, c := range contents {\n\t\tif !c.IsDir() || c.Name() == config.DefaultKubeletVolumeDevicesDirName {\n\t\t\tcontinue\n\t\t}\n\n\t\tmounts, err := ioutil.ReadDir(filepath.Join(dir, c.Name()))\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tfor _, m := range mounts {\n\t\t\tvolumeMount := m.Name()\n\t\t\tprefix := portal + \"-\" + iqn\n\t\t\tif strings.HasPrefix(volumeMount, prefix) {\n\t\t\t\tcounter++\n\t\t\t}\n\t\t}\n\t}\n\n\treturn counter, nil\n}","line":{"from":925,"to":961}} {"id":100012519,"name":"ignoreExitCodes","signature":"func ignoreExitCodes(err error, ignoredExitCodes ...int) error","file":"pkg/volume/iscsi/iscsi_util.go","code":"func ignoreExitCodes(err error, ignoredExitCodes ...int) error {\n\texitError, ok := err.(utilexec.ExitError)\n\tif !ok {\n\t\treturn err\n\t}\n\tfor _, code := range ignoredExitCodes {\n\t\tif exitError.ExitStatus() == code {\n\t\t\tklog.V(4).Infof(\"ignored iscsiadm exit code %d\", code)\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn err\n}","line":{"from":963,"to":975}} {"id":100012520,"name":"execWithLog","signature":"func execWithLog(b iscsiDiskMounter, cmd string, args ...string) (string, error)","file":"pkg/volume/iscsi/iscsi_util.go","code":"func execWithLog(b iscsiDiskMounter, cmd string, args ...string) (string, error) {\n\tstart := time.Now()\n\tout, err := b.exec.Command(cmd, args...).CombinedOutput()\n\tif klogV := klog.V(5); klogV.Enabled() {\n\t\td := time.Since(start)\n\t\tklogV.Infof(\"Executed %s %v in %v, err: %v\", cmd, args, d, err)\n\t\tklogV.Infof(\"Output: %s\", string(out))\n\t}\n\treturn string(out), err\n}","line":{"from":977,"to":986}} {"id":100012521,"name":"ProbeVolumePlugins","signature":"func ProbeVolumePlugins() []volume.VolumePlugin","file":"pkg/volume/local/local.go","code":"// ProbeVolumePlugins is the primary entrypoint for volume plugins.\nfunc ProbeVolumePlugins() []volume.VolumePlugin {\n\treturn []volume.VolumePlugin{\u0026localVolumePlugin{}}\n}","line":{"from":46,"to":49}} {"id":100012522,"name":"Init","signature":"func (plugin *localVolumePlugin) Init(host volume.VolumeHost) error","file":"pkg/volume/local/local.go","code":"func (plugin *localVolumePlugin) Init(host volume.VolumeHost) error {\n\tplugin.host = host\n\tplugin.volumeLocks = keymutex.NewHashed(0)\n\tplugin.recorder = host.GetEventRecorder()\n\treturn nil\n}","line":{"from":66,"to":71}} {"id":100012523,"name":"GetPluginName","signature":"func (plugin *localVolumePlugin) GetPluginName() string","file":"pkg/volume/local/local.go","code":"func (plugin *localVolumePlugin) GetPluginName() string {\n\treturn localVolumePluginName\n}","line":{"from":73,"to":75}} {"id":100012524,"name":"GetVolumeName","signature":"func (plugin *localVolumePlugin) GetVolumeName(spec *volume.Spec) (string, error)","file":"pkg/volume/local/local.go","code":"func (plugin *localVolumePlugin) GetVolumeName(spec *volume.Spec) (string, error) {\n\t// This volume is only supported as a PersistentVolumeSource, so the PV name is unique\n\treturn spec.Name(), nil\n}","line":{"from":77,"to":80}} {"id":100012525,"name":"CanSupport","signature":"func (plugin *localVolumePlugin) CanSupport(spec *volume.Spec) bool","file":"pkg/volume/local/local.go","code":"func (plugin *localVolumePlugin) CanSupport(spec *volume.Spec) bool {\n\t// This volume is only supported as a PersistentVolumeSource\n\treturn (spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.Local != nil)\n}","line":{"from":82,"to":85}} {"id":100012526,"name":"RequiresRemount","signature":"func (plugin *localVolumePlugin) RequiresRemount(spec *volume.Spec) bool","file":"pkg/volume/local/local.go","code":"func (plugin *localVolumePlugin) RequiresRemount(spec *volume.Spec) bool {\n\treturn false\n}","line":{"from":87,"to":89}} {"id":100012527,"name":"SupportsMountOption","signature":"func (plugin *localVolumePlugin) SupportsMountOption() bool","file":"pkg/volume/local/local.go","code":"func (plugin *localVolumePlugin) SupportsMountOption() bool {\n\treturn true\n}","line":{"from":91,"to":93}} {"id":100012528,"name":"SupportsBulkVolumeVerification","signature":"func (plugin *localVolumePlugin) SupportsBulkVolumeVerification() bool","file":"pkg/volume/local/local.go","code":"func (plugin *localVolumePlugin) SupportsBulkVolumeVerification() bool {\n\treturn false\n}","line":{"from":95,"to":97}} {"id":100012529,"name":"SupportsSELinuxContextMount","signature":"func (plugin *localVolumePlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/local/local.go","code":"func (plugin *localVolumePlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error) {\n\treturn false, nil\n}","line":{"from":99,"to":101}} {"id":100012530,"name":"GetAccessModes","signature":"func (plugin *localVolumePlugin) GetAccessModes() []v1.PersistentVolumeAccessMode","file":"pkg/volume/local/local.go","code":"func (plugin *localVolumePlugin) GetAccessModes() []v1.PersistentVolumeAccessMode {\n\t// The current meaning of AccessMode is how many nodes can attach to it, not how many pods can mount it\n\treturn []v1.PersistentVolumeAccessMode{\n\t\tv1.ReadWriteOnce,\n\t}\n}","line":{"from":103,"to":108}} {"id":100012531,"name":"getVolumeSource","signature":"func getVolumeSource(spec *volume.Spec) (*v1.LocalVolumeSource, bool, error)","file":"pkg/volume/local/local.go","code":"func getVolumeSource(spec *volume.Spec) (*v1.LocalVolumeSource, bool, error) {\n\tif spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.Local != nil {\n\t\treturn spec.PersistentVolume.Spec.Local, spec.ReadOnly, nil\n\t}\n\n\treturn nil, false, fmt.Errorf(\"Spec does not reference a Local volume type\")\n}","line":{"from":110,"to":116}} {"id":100012532,"name":"NewMounter","signature":"func (plugin *localVolumePlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error)","file":"pkg/volume/local/local.go","code":"func (plugin *localVolumePlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) {\n\t_, readOnly, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tglobalLocalPath, err := plugin.getGlobalLocalPath(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkvh, ok := plugin.host.(volume.KubeletVolumeHost)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"plugin volume host does not implement KubeletVolumeHost interface\")\n\t}\n\n\treturn \u0026localVolumeMounter{\n\t\tlocalVolume: \u0026localVolume{\n\t\t\tpod: pod,\n\t\t\tpodUID: pod.UID,\n\t\t\tvolName: spec.Name(),\n\t\t\tmounter: plugin.host.GetMounter(plugin.GetPluginName()),\n\t\t\thostUtil: kvh.GetHostUtil(),\n\t\t\tplugin: plugin,\n\t\t\tglobalPath: globalLocalPath,\n\t\t\tMetricsProvider: volume.NewMetricsStatFS(plugin.host.GetPodVolumeDir(pod.UID, utilstrings.EscapeQualifiedName(localVolumePluginName), spec.Name())),\n\t\t},\n\t\tmountOptions: util.MountOptionFromSpec(spec),\n\t\treadOnly: readOnly,\n\t}, nil\n\n}","line":{"from":118,"to":149}} {"id":100012533,"name":"NewUnmounter","signature":"func (plugin *localVolumePlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error)","file":"pkg/volume/local/local.go","code":"func (plugin *localVolumePlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error) {\n\treturn \u0026localVolumeUnmounter{\n\t\tlocalVolume: \u0026localVolume{\n\t\t\tpodUID: podUID,\n\t\t\tvolName: volName,\n\t\t\tmounter: plugin.host.GetMounter(plugin.GetPluginName()),\n\t\t\tplugin: plugin,\n\t\t},\n\t}, nil\n}","line":{"from":151,"to":160}} {"id":100012534,"name":"NewBlockVolumeMapper","signature":"func (plugin *localVolumePlugin) NewBlockVolumeMapper(spec *volume.Spec, pod *v1.Pod,","file":"pkg/volume/local/local.go","code":"func (plugin *localVolumePlugin) NewBlockVolumeMapper(spec *volume.Spec, pod *v1.Pod,\n\t_ volume.VolumeOptions) (volume.BlockVolumeMapper, error) {\n\tvolumeSource, readOnly, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmapper := \u0026localVolumeMapper{\n\t\tlocalVolume: \u0026localVolume{\n\t\t\tpodUID: pod.UID,\n\t\t\tvolName: spec.Name(),\n\t\t\tglobalPath: volumeSource.Path,\n\t\t\tplugin: plugin,\n\t\t},\n\t\treadOnly: readOnly,\n\t}\n\n\tblockPath, err := mapper.GetGlobalMapPath(spec)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get device path: %v\", err)\n\t}\n\tmapper.MetricsProvider = volume.NewMetricsBlock(filepath.Join(blockPath, string(pod.UID)))\n\n\treturn mapper, nil\n}","line":{"from":162,"to":186}} {"id":100012535,"name":"NewBlockVolumeUnmapper","signature":"func (plugin *localVolumePlugin) NewBlockVolumeUnmapper(volName string,","file":"pkg/volume/local/local.go","code":"func (plugin *localVolumePlugin) NewBlockVolumeUnmapper(volName string,\n\tpodUID types.UID) (volume.BlockVolumeUnmapper, error) {\n\treturn \u0026localVolumeUnmapper{\n\t\tlocalVolume: \u0026localVolume{\n\t\t\tpodUID: podUID,\n\t\t\tvolName: volName,\n\t\t\tplugin: plugin,\n\t\t},\n\t}, nil\n}","line":{"from":188,"to":197}} {"id":100012536,"name":"ConstructVolumeSpec","signature":"func (plugin *localVolumePlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error)","file":"pkg/volume/local/local.go","code":"// TODO: check if no path and no topology constraints are ok\nfunc (plugin *localVolumePlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error) {\n\tfs := v1.PersistentVolumeFilesystem\n\t// The main purpose of reconstructed volume is to clean unused mount points\n\t// and directories.\n\t// For filesystem volume with directory source, no global mount path is\n\t// needed to clean. Empty path is ok.\n\t// For filesystem volume with block source, we should resolve to its device\n\t// path if global mount path exists.\n\tvar path string\n\tmounter := plugin.host.GetMounter(plugin.GetPluginName())\n\trefs, err := mounter.GetMountRefs(mountPath)\n\tif err != nil {\n\t\treturn volume.ReconstructedVolume{}, err\n\t}\n\tbaseMountPath := plugin.generateBlockDeviceBaseGlobalPath()\n\tfor _, ref := range refs {\n\t\tif mount.PathWithinBase(ref, baseMountPath) {\n\t\t\t// If the global mount for block device exists, the source is block\n\t\t\t// device.\n\t\t\t// The resolved device path may not be the exact same as path in\n\t\t\t// local PV object if symbolic link is used. However, it's the true\n\t\t\t// source and can be used in reconstructed volume.\n\t\t\tpath, _, err = mount.GetDeviceNameFromMount(mounter, ref)\n\t\t\tif err != nil {\n\t\t\t\treturn volume.ReconstructedVolume{}, err\n\t\t\t}\n\t\t\tklog.V(4).Infof(\"local: reconstructing volume %q (pod volume mount: %q) with device %q\", volumeName, mountPath, path)\n\t\t\tbreak\n\t\t}\n\t}\n\tlocalVolume := \u0026v1.PersistentVolume{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: volumeName,\n\t\t},\n\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\tPersistentVolumeSource: v1.PersistentVolumeSource{\n\t\t\t\tLocal: \u0026v1.LocalVolumeSource{\n\t\t\t\t\tPath: path,\n\t\t\t\t},\n\t\t\t},\n\t\t\tVolumeMode: \u0026fs,\n\t\t},\n\t}\n\treturn volume.ReconstructedVolume{\n\t\tSpec: volume.NewSpecFromPersistentVolume(localVolume, false),\n\t}, nil\n}","line":{"from":199,"to":246}} {"id":100012537,"name":"ConstructBlockVolumeSpec","signature":"func (plugin *localVolumePlugin) ConstructBlockVolumeSpec(podUID types.UID, volumeName,","file":"pkg/volume/local/local.go","code":"func (plugin *localVolumePlugin) ConstructBlockVolumeSpec(podUID types.UID, volumeName,\n\tmapPath string) (*volume.Spec, error) {\n\tblock := v1.PersistentVolumeBlock\n\n\tlocalVolume := \u0026v1.PersistentVolume{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: volumeName,\n\t\t},\n\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\tPersistentVolumeSource: v1.PersistentVolumeSource{\n\t\t\t\tLocal: \u0026v1.LocalVolumeSource{\n\t\t\t\t\t// Not needed because we don't need to detach local device from the host.\n\t\t\t\t\tPath: \"\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tVolumeMode: \u0026block,\n\t\t},\n\t}\n\n\treturn volume.NewSpecFromPersistentVolume(localVolume, false), nil\n}","line":{"from":248,"to":268}} {"id":100012538,"name":"generateBlockDeviceBaseGlobalPath","signature":"func (plugin *localVolumePlugin) generateBlockDeviceBaseGlobalPath() string","file":"pkg/volume/local/local.go","code":"func (plugin *localVolumePlugin) generateBlockDeviceBaseGlobalPath() string {\n\treturn filepath.Join(plugin.host.GetPluginDir(localVolumePluginName), util.MountsInGlobalPDPath)\n}","line":{"from":270,"to":272}} {"id":100012539,"name":"getGlobalLocalPath","signature":"func (plugin *localVolumePlugin) getGlobalLocalPath(spec *volume.Spec) (string, error)","file":"pkg/volume/local/local.go","code":"func (plugin *localVolumePlugin) getGlobalLocalPath(spec *volume.Spec) (string, error) {\n\tif spec.PersistentVolume.Spec.Local == nil || len(spec.PersistentVolume.Spec.Local.Path) == 0 {\n\t\treturn \"\", fmt.Errorf(\"local volume source is nil or local path is not set\")\n\t}\n\n\tkvh, ok := plugin.host.(volume.KubeletVolumeHost)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"plugin volume host does not implement KubeletVolumeHost interface\")\n\t}\n\n\tfileType, err := kvh.GetHostUtil().GetFileType(spec.PersistentVolume.Spec.Local.Path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tswitch fileType {\n\tcase hostutil.FileTypeDirectory:\n\t\treturn spec.PersistentVolume.Spec.Local.Path, nil\n\tcase hostutil.FileTypeBlockDev:\n\t\treturn filepath.Join(plugin.generateBlockDeviceBaseGlobalPath(), spec.Name()), nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"only directory and block device are supported\")\n\t}\n}","line":{"from":274,"to":296}} {"id":100012540,"name":"CanDeviceMount","signature":"func (plugin *localVolumePlugin) CanDeviceMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/local/local.go","code":"func (plugin *localVolumePlugin) CanDeviceMount(spec *volume.Spec) (bool, error) {\n\treturn true, nil\n}","line":{"from":308,"to":310}} {"id":100012541,"name":"NewDeviceMounter","signature":"func (plugin *localVolumePlugin) NewDeviceMounter() (volume.DeviceMounter, error)","file":"pkg/volume/local/local.go","code":"func (plugin *localVolumePlugin) NewDeviceMounter() (volume.DeviceMounter, error) {\n\tkvh, ok := plugin.host.(volume.KubeletVolumeHost)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"plugin volume host does not implement KubeletVolumeHost interface\")\n\t}\n\treturn \u0026deviceMounter{\n\t\tplugin: plugin,\n\t\tmounter: util.NewSafeFormatAndMountFromHost(plugin.GetPluginName(), plugin.host),\n\t\thostUtil: kvh.GetHostUtil(),\n\t}, nil\n}","line":{"from":312,"to":322}} {"id":100012542,"name":"mountLocalBlockDevice","signature":"func (dm *deviceMounter) mountLocalBlockDevice(spec *volume.Spec, devicePath string, deviceMountPath string) error","file":"pkg/volume/local/local.go","code":"func (dm *deviceMounter) mountLocalBlockDevice(spec *volume.Spec, devicePath string, deviceMountPath string) error {\n\tklog.V(4).Infof(\"local: mounting device %s to %s\", devicePath, deviceMountPath)\n\tnotMnt, err := dm.mounter.IsLikelyNotMountPoint(deviceMountPath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tif err := os.MkdirAll(deviceMountPath, 0750); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tnotMnt = true\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\tif !notMnt {\n\t\treturn nil\n\t}\n\tfstype, err := getVolumeSourceFSType(spec)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tro, err := getVolumeSourceReadOnly(spec)\n\tif err != nil {\n\t\treturn err\n\t}\n\toptions := []string{}\n\tif ro {\n\t\toptions = append(options, \"ro\")\n\t}\n\tmountOptions := util.MountOptionFromSpec(spec, options...)\n\terr = dm.mounter.FormatAndMount(devicePath, deviceMountPath, fstype, mountOptions)\n\tif err != nil {\n\t\tif rmErr := os.Remove(deviceMountPath); rmErr != nil {\n\t\t\tklog.Warningf(\"local: failed to remove %s: %v\", deviceMountPath, rmErr)\n\t\t}\n\t\treturn fmt.Errorf(\"local: failed to mount device %s at %s (fstype: %s), error %w\", devicePath, deviceMountPath, fstype, err)\n\t}\n\tklog.V(3).Infof(\"local: successfully mount device %s at %s (fstype: %s)\", devicePath, deviceMountPath, fstype)\n\treturn nil\n}","line":{"from":324,"to":363}} {"id":100012543,"name":"MountDevice","signature":"func (dm *deviceMounter) MountDevice(spec *volume.Spec, devicePath string, deviceMountPath string, _ volume.DeviceMounterArgs) error","file":"pkg/volume/local/local.go","code":"func (dm *deviceMounter) MountDevice(spec *volume.Spec, devicePath string, deviceMountPath string, _ volume.DeviceMounterArgs) error {\n\tif spec.PersistentVolume.Spec.Local == nil || len(spec.PersistentVolume.Spec.Local.Path) == 0 {\n\t\treturn fmt.Errorf(\"local volume source is nil or local path is not set\")\n\t}\n\tfileType, err := dm.hostUtil.GetFileType(spec.PersistentVolume.Spec.Local.Path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch fileType {\n\tcase hostutil.FileTypeBlockDev:\n\t\t// local volume plugin does not implement AttachableVolumePlugin interface, so set devicePath to Path in PV spec directly\n\t\treturn dm.mountLocalBlockDevice(spec, spec.PersistentVolume.Spec.Local.Path, deviceMountPath)\n\tcase hostutil.FileTypeDirectory:\n\t\t// if the given local volume path is of already filesystem directory, return directly\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"only directory and block device are supported\")\n\t}\n}","line":{"from":365,"to":384}} {"id":100012544,"name":"RequiresFSResize","signature":"func (plugin *localVolumePlugin) RequiresFSResize() bool","file":"pkg/volume/local/local.go","code":"func (plugin *localVolumePlugin) RequiresFSResize() bool {\n\treturn true\n}","line":{"from":386,"to":388}} {"id":100012545,"name":"NodeExpand","signature":"func (plugin *localVolumePlugin) NodeExpand(resizeOptions volume.NodeResizeOptions) (bool, error)","file":"pkg/volume/local/local.go","code":"func (plugin *localVolumePlugin) NodeExpand(resizeOptions volume.NodeResizeOptions) (bool, error) {\n\tfsVolume, err := util.CheckVolumeModeFilesystem(resizeOptions.VolumeSpec)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"error checking VolumeMode: %v\", err)\n\t}\n\tif !fsVolume {\n\t\treturn true, nil\n\t}\n\n\tlocalDevicePath := resizeOptions.VolumeSpec.PersistentVolume.Spec.Local.Path\n\n\tkvh, ok := plugin.host.(volume.KubeletVolumeHost)\n\tif !ok {\n\t\treturn false, fmt.Errorf(\"plugin volume host does not implement KubeletVolumeHost interface\")\n\t}\n\n\tfileType, err := kvh.GetHostUtil().GetFileType(localDevicePath)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tswitch fileType {\n\tcase hostutil.FileTypeBlockDev:\n\t\t_, err = util.GenericResizeFS(plugin.host, plugin.GetPluginName(), localDevicePath, resizeOptions.DeviceMountPath)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\treturn true, nil\n\tcase hostutil.FileTypeDirectory:\n\t\t// if the given local volume path is of already filesystem directory, return directly because\n\t\t// we do not want to prevent mount operation from succeeding.\n\t\tklog.InfoS(\"Expansion of directory based local volumes is NO-OP\", \"localVolumePath\", localDevicePath)\n\t\treturn true, nil\n\tdefault:\n\t\treturn false, fmt.Errorf(\"only directory and block device are supported\")\n\t}\n}","line":{"from":390,"to":426}} {"id":100012546,"name":"getVolumeSourceFSType","signature":"func getVolumeSourceFSType(spec *volume.Spec) (string, error)","file":"pkg/volume/local/local.go","code":"func getVolumeSourceFSType(spec *volume.Spec) (string, error) {\n\tif spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.Local != nil {\n\t\tif spec.PersistentVolume.Spec.Local.FSType != nil {\n\t\t\treturn *spec.PersistentVolume.Spec.Local.FSType, nil\n\t\t}\n\t\t// if the FSType is not set in local PV spec, setting it to default (\"ext4\")\n\t\treturn defaultFSType, nil\n\t}\n\n\treturn \"\", fmt.Errorf(\"spec does not reference a Local volume type\")\n}","line":{"from":428,"to":439}} {"id":100012547,"name":"getVolumeSourceReadOnly","signature":"func getVolumeSourceReadOnly(spec *volume.Spec) (bool, error)","file":"pkg/volume/local/local.go","code":"func getVolumeSourceReadOnly(spec *volume.Spec) (bool, error) {\n\tif spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.Local != nil {\n\t\t// local volumes used as a PersistentVolume gets the ReadOnly flag indirectly through\n\t\t// the persistent-claim volume used to mount the PV\n\t\treturn spec.ReadOnly, nil\n\t}\n\n\treturn false, fmt.Errorf(\"spec does not reference a Local volume type\")\n}","line":{"from":441,"to":450}} {"id":100012548,"name":"GetDeviceMountPath","signature":"func (dm *deviceMounter) GetDeviceMountPath(spec *volume.Spec) (string, error)","file":"pkg/volume/local/local.go","code":"func (dm *deviceMounter) GetDeviceMountPath(spec *volume.Spec) (string, error) {\n\treturn dm.plugin.getGlobalLocalPath(spec)\n}","line":{"from":452,"to":454}} {"id":100012549,"name":"NewDeviceUnmounter","signature":"func (plugin *localVolumePlugin) NewDeviceUnmounter() (volume.DeviceUnmounter, error)","file":"pkg/volume/local/local.go","code":"func (plugin *localVolumePlugin) NewDeviceUnmounter() (volume.DeviceUnmounter, error) {\n\treturn \u0026deviceMounter{\n\t\tplugin: plugin,\n\t\tmounter: util.NewSafeFormatAndMountFromHost(plugin.GetPluginName(), plugin.host),\n\t}, nil\n}","line":{"from":456,"to":461}} {"id":100012550,"name":"GetDeviceMountRefs","signature":"func (plugin *localVolumePlugin) GetDeviceMountRefs(deviceMountPath string) ([]string, error)","file":"pkg/volume/local/local.go","code":"func (plugin *localVolumePlugin) GetDeviceMountRefs(deviceMountPath string) ([]string, error) {\n\tmounter := plugin.host.GetMounter(plugin.GetPluginName())\n\treturn mounter.GetMountRefs(deviceMountPath)\n}","line":{"from":463,"to":466}} {"id":100012551,"name":"UnmountDevice","signature":"func (dm *deviceMounter) UnmountDevice(deviceMountPath string) error","file":"pkg/volume/local/local.go","code":"func (dm *deviceMounter) UnmountDevice(deviceMountPath string) error {\n\t// If the local PV is a block device,\n\t// The deviceMountPath is generated to the format like :/var/lib/kubelet/plugins/kubernetes.io/local-volume/mounts/localpv.spec.Name;\n\t// If it is a filesystem directory, then the deviceMountPath is set directly to pvSpec.Local.Path\n\t// We only need to unmount block device here, so we need to check if the deviceMountPath passed here\n\t// has base mount path: /var/lib/kubelet/plugins/kubernetes.io/local-volume/mounts\n\tbasemountPath := dm.plugin.generateBlockDeviceBaseGlobalPath()\n\tif mount.PathWithinBase(deviceMountPath, basemountPath) {\n\t\treturn mount.CleanupMountPoint(deviceMountPath, dm.mounter, false)\n\t}\n\n\treturn nil\n}","line":{"from":470,"to":482}} {"id":100012552,"name":"GetPath","signature":"func (l *localVolume) GetPath() string","file":"pkg/volume/local/local.go","code":"func (l *localVolume) GetPath() string {\n\treturn l.plugin.host.GetPodVolumeDir(l.podUID, utilstrings.EscapeQualifiedName(localVolumePluginName), l.volName)\n}","line":{"from":499,"to":501}} {"id":100012553,"name":"GetAttributes","signature":"func (m *localVolumeMounter) GetAttributes() volume.Attributes","file":"pkg/volume/local/local.go","code":"func (m *localVolumeMounter) GetAttributes() volume.Attributes {\n\treturn volume.Attributes{\n\t\tReadOnly: m.readOnly,\n\t\tManaged: !m.readOnly,\n\t\tSELinuxRelabel: true,\n\t}\n}","line":{"from":511,"to":517}} {"id":100012554,"name":"SetUp","signature":"func (m *localVolumeMounter) SetUp(mounterArgs volume.MounterArgs) error","file":"pkg/volume/local/local.go","code":"// SetUp bind mounts the directory to the volume path\nfunc (m *localVolumeMounter) SetUp(mounterArgs volume.MounterArgs) error {\n\treturn m.SetUpAt(m.GetPath(), mounterArgs)\n}","line":{"from":519,"to":522}} {"id":100012555,"name":"SetUpAt","signature":"func (m *localVolumeMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error","file":"pkg/volume/local/local.go","code":"// SetUpAt bind mounts the directory to the volume path and sets up volume ownership\nfunc (m *localVolumeMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {\n\tm.plugin.volumeLocks.LockKey(m.globalPath)\n\tdefer m.plugin.volumeLocks.UnlockKey(m.globalPath)\n\n\tif m.globalPath == \"\" {\n\t\treturn fmt.Errorf(\"LocalVolume volume %q path is empty\", m.volName)\n\t}\n\n\terr := validation.ValidatePathNoBacksteps(m.globalPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"invalid path: %s %v\", m.globalPath, err)\n\t}\n\n\tnotMnt, err := mount.IsNotMountPoint(m.mounter, dir)\n\tklog.V(4).Infof(\"LocalVolume mount setup: PodDir(%s) VolDir(%s) Mounted(%t) Error(%v), ReadOnly(%t)\", dir, m.globalPath, !notMnt, err, m.readOnly)\n\tif err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\tklog.Errorf(\"cannot validate mount point: %s %v\", dir, err)\n\t\treturn err\n\t}\n\n\tif !notMnt {\n\t\treturn nil\n\t}\n\trefs, err := m.mounter.GetMountRefs(m.globalPath)\n\tif mounterArgs.FsGroup != nil {\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"cannot collect mounting information: %s %v\", m.globalPath, err)\n\t\t\treturn err\n\t\t}\n\n\t\t// Only count mounts from other pods\n\t\trefs = m.filterPodMounts(refs)\n\t\tif len(refs) \u003e 0 {\n\t\t\tfsGroupNew := int64(*mounterArgs.FsGroup)\n\t\t\t_, fsGroupOld, err := m.hostUtil.GetOwner(m.globalPath)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to check fsGroup for %s (%v)\", m.globalPath, err)\n\t\t\t}\n\t\t\tif fsGroupNew != fsGroupOld {\n\t\t\t\tm.plugin.recorder.Eventf(m.pod, v1.EventTypeWarning, events.WarnAlreadyMountedVolume, \"The requested fsGroup is %d, but the volume %s has GID %d. The volume may not be shareable.\", fsGroupNew, m.volName, fsGroupOld)\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif runtime.GOOS != \"windows\" {\n\t\t// skip below MkdirAll for windows since the \"bind mount\" logic is implemented differently in mount_wiondows.go\n\t\tif err := os.MkdirAll(dir, 0750); err != nil {\n\t\t\tklog.Errorf(\"mkdir failed on disk %s (%v)\", dir, err)\n\t\t\treturn err\n\t\t}\n\t}\n\t// Perform a bind mount to the full path to allow duplicate mounts of the same volume.\n\toptions := []string{\"bind\"}\n\tif m.readOnly {\n\t\toptions = append(options, \"ro\")\n\t}\n\tmountOptions := util.JoinMountOptions(options, m.mountOptions)\n\n\tklog.V(4).Infof(\"attempting to mount %s\", dir)\n\tglobalPath := util.MakeAbsolutePath(runtime.GOOS, m.globalPath)\n\terr = m.mounter.MountSensitiveWithoutSystemd(globalPath, dir, \"\", mountOptions, nil)\n\tif err != nil {\n\t\tklog.Errorf(\"Mount of volume %s failed: %v\", dir, err)\n\t\tnotMnt, mntErr := mount.IsNotMountPoint(m.mounter, dir)\n\t\tif mntErr != nil {\n\t\t\tklog.Errorf(\"IsNotMountPoint check failed: %v\", mntErr)\n\t\t\treturn err\n\t\t}\n\t\tif !notMnt {\n\t\t\tif mntErr = m.mounter.Unmount(dir); mntErr != nil {\n\t\t\t\tklog.Errorf(\"Failed to unmount: %v\", mntErr)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tnotMnt, mntErr = mount.IsNotMountPoint(m.mounter, dir)\n\t\t\tif mntErr != nil {\n\t\t\t\tklog.Errorf(\"IsNotMountPoint check failed: %v\", mntErr)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !notMnt {\n\t\t\t\t// This is very odd, we don't expect it. We'll try again next sync loop.\n\t\t\t\tklog.Errorf(\"%s is still mounted, despite call to unmount(). Will try again next sync loop.\", dir)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif rmErr := os.Remove(dir); rmErr != nil {\n\t\t\tklog.Warningf(\"failed to remove %s: %v\", dir, rmErr)\n\t\t}\n\t\treturn err\n\t}\n\tif !m.readOnly {\n\t\t// Volume owner will be written only once on the first volume mount\n\t\tif len(refs) == 0 {\n\t\t\treturn volume.SetVolumeOwnership(m, dir, mounterArgs.FsGroup, mounterArgs.FSGroupChangePolicy, util.FSGroupCompleteHook(m.plugin, nil))\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":524,"to":622}} {"id":100012556,"name":"filterPodMounts","signature":"func (m *localVolumeMounter) filterPodMounts(refs []string) []string","file":"pkg/volume/local/local.go","code":"// filterPodMounts only returns mount paths inside the kubelet pod directory\nfunc (m *localVolumeMounter) filterPodMounts(refs []string) []string {\n\tfiltered := []string{}\n\tfor _, r := range refs {\n\t\tif strings.HasPrefix(r, m.plugin.host.GetPodsDir()+string(os.PathSeparator)) {\n\t\t\tfiltered = append(filtered, r)\n\t\t}\n\t}\n\treturn filtered\n}","line":{"from":624,"to":633}} {"id":100012557,"name":"TearDown","signature":"func (u *localVolumeUnmounter) TearDown() error","file":"pkg/volume/local/local.go","code":"// TearDown unmounts the bind mount\nfunc (u *localVolumeUnmounter) TearDown() error {\n\treturn u.TearDownAt(u.GetPath())\n}","line":{"from":641,"to":644}} {"id":100012558,"name":"TearDownAt","signature":"func (u *localVolumeUnmounter) TearDownAt(dir string) error","file":"pkg/volume/local/local.go","code":"// TearDownAt unmounts the bind mount\nfunc (u *localVolumeUnmounter) TearDownAt(dir string) error {\n\tklog.V(4).Infof(\"Unmounting volume %q at path %q\\n\", u.volName, dir)\n\treturn mount.CleanupMountPoint(dir, u.mounter, true) /* extensiveMountPointCheck = true */\n}","line":{"from":646,"to":650}} {"id":100012559,"name":"SetUpDevice","signature":"func (m *localVolumeMapper) SetUpDevice() (string, error)","file":"pkg/volume/local/local.go","code":"// SetUpDevice prepares the volume to the node by the plugin specific way.\nfunc (m *localVolumeMapper) SetUpDevice() (string, error) {\n\treturn \"\", nil\n}","line":{"from":661,"to":664}} {"id":100012560,"name":"MapPodDevice","signature":"func (m *localVolumeMapper) MapPodDevice() (string, error)","file":"pkg/volume/local/local.go","code":"// MapPodDevice provides physical device path for the local PV.\nfunc (m *localVolumeMapper) MapPodDevice() (string, error) {\n\tglobalPath := util.MakeAbsolutePath(runtime.GOOS, m.globalPath)\n\tklog.V(4).Infof(\"MapPodDevice returning path %s\", globalPath)\n\treturn globalPath, nil\n}","line":{"from":666,"to":671}} {"id":100012561,"name":"GetStagingPath","signature":"func (m *localVolumeMapper) GetStagingPath() string","file":"pkg/volume/local/local.go","code":"// GetStagingPath returns\nfunc (m *localVolumeMapper) GetStagingPath() string {\n\treturn \"\"\n}","line":{"from":673,"to":676}} {"id":100012562,"name":"SupportsMetrics","signature":"func (m *localVolumeMapper) SupportsMetrics() bool","file":"pkg/volume/local/local.go","code":"// SupportsMetrics returns true for SupportsMetrics as it initializes the\n// MetricsProvider.\nfunc (m *localVolumeMapper) SupportsMetrics() bool {\n\treturn true\n}","line":{"from":678,"to":682}} {"id":100012563,"name":"GetGlobalMapPath","signature":"func (l *localVolume) GetGlobalMapPath(spec *volume.Spec) (string, error)","file":"pkg/volume/local/local.go","code":"// GetGlobalMapPath returns global map path and error.\n// path: plugins/kubernetes.io/kubernetes.io/local-volume/volumeDevices/{volumeName}\nfunc (l *localVolume) GetGlobalMapPath(spec *volume.Spec) (string, error) {\n\treturn filepath.Join(l.plugin.host.GetVolumeDevicePluginDir(utilstrings.EscapeQualifiedName(localVolumePluginName)),\n\t\tl.volName), nil\n}","line":{"from":692,"to":697}} {"id":100012564,"name":"GetPodDeviceMapPath","signature":"func (l *localVolume) GetPodDeviceMapPath() (string, string)","file":"pkg/volume/local/local.go","code":"// GetPodDeviceMapPath returns pod device map path and volume name.\n// path: pods/{podUid}/volumeDevices/kubernetes.io~local-volume\n// volName: local-pv-ff0d6d4\nfunc (l *localVolume) GetPodDeviceMapPath() (string, string) {\n\treturn l.plugin.host.GetPodVolumeDeviceDir(l.podUID,\n\t\tutilstrings.EscapeQualifiedName(localVolumePluginName)), l.volName\n}","line":{"from":699,"to":705}} {"id":100012565,"name":"NewMetricsBlock","signature":"func NewMetricsBlock(device string) MetricsProvider","file":"pkg/volume/metrics_block.go","code":"// NewMetricsStatfs creates a new metricsBlock with the device node of the\n// Volume.\nfunc NewMetricsBlock(device string) MetricsProvider {\n\treturn \u0026metricsBlock{device}\n}","line":{"from":40,"to":44}} {"id":100012566,"name":"GetMetrics","signature":"func (mb *metricsBlock) GetMetrics() (*Metrics, error)","file":"pkg/volume/metrics_block.go","code":"// See MetricsProvider.GetMetrics\n// GetMetrics detects the size of the BlockMode volume for the device node\n// where the Volume is attached.\n//\n// Note that only the capacity of the device can be detected with standard\n// tools. Storage systems may have more information that they can provide by\n// going through specialized APIs.\nfunc (mb *metricsBlock) GetMetrics() (*Metrics, error) {\n\tstartTime := time.Now()\n\tdefer servermetrics.CollectVolumeStatCalDuration(\"block\", startTime)\n\n\t// TODO: Windows does not yet support VolumeMode=Block\n\tif runtime.GOOS == \"windows\" {\n\t\treturn nil, NewNotImplementedError(\"Windows does not support Block volumes\")\n\t}\n\n\tmetrics := \u0026Metrics{Time: metav1.Now()}\n\tif mb.device == \"\" {\n\t\treturn metrics, NewNoPathDefinedError()\n\t}\n\n\terr := mb.getBlockInfo(metrics)\n\tif err != nil {\n\t\treturn metrics, err\n\t}\n\n\treturn metrics, nil\n}","line":{"from":46,"to":73}} {"id":100012567,"name":"getBlockInfo","signature":"func (mb *metricsBlock) getBlockInfo(metrics *Metrics) error","file":"pkg/volume/metrics_block.go","code":"// getBlockInfo fetches metrics.Capacity by opening the device and seeking to\n// the end.\nfunc (mb *metricsBlock) getBlockInfo(metrics *Metrics) error {\n\tdev, err := os.Open(mb.device)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to open device %q: %w\", mb.device, err)\n\t}\n\tdefer dev.Close()\n\n\tend, err := dev.Seek(0, io.SeekEnd)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to detect size of %q: %w\", mb.device, err)\n\t}\n\n\tmetrics.Capacity = resource.NewQuantity(end, resource.BinarySI)\n\n\treturn nil\n}","line":{"from":75,"to":92}} {"id":100012568,"name":"NewCachedMetrics","signature":"func NewCachedMetrics(provider MetricsProvider) MetricsProvider","file":"pkg/volume/metrics_cached.go","code":"// NewCachedMetrics creates a new cachedMetrics wrapping another\n// MetricsProvider and caching the results.\nfunc NewCachedMetrics(provider MetricsProvider) MetricsProvider {\n\treturn \u0026cachedMetrics{wrapped: provider}\n}","line":{"from":35,"to":39}} {"id":100012569,"name":"GetMetrics","signature":"func (md *cachedMetrics) GetMetrics() (*Metrics, error)","file":"pkg/volume/metrics_cached.go","code":"// GetMetrics runs the wrapped metrics provider's GetMetrics method once and\n// caches the result. Will not cache result if there is an error.\n// See MetricsProvider.GetMetrics\nfunc (md *cachedMetrics) GetMetrics() (*Metrics, error) {\n\tmd.once.cache(func() error {\n\t\tmd.resultMetrics, md.resultError = md.wrapped.GetMetrics()\n\t\treturn md.resultError\n\t})\n\treturn md.resultMetrics, md.resultError\n}","line":{"from":41,"to":50}} {"id":100012570,"name":"cache","signature":"func (o *cacheOnce) cache(f func() error)","file":"pkg/volume/metrics_cached.go","code":"// Copied from sync.Once but we don't want to cache the results if there is an\n// error\nfunc (o *cacheOnce) cache(f func() error) {\n\tif atomic.LoadUint32(\u0026o.done) == 1 {\n\t\treturn\n\t}\n\t// Slow-path.\n\to.m.Lock()\n\tdefer o.m.Unlock()\n\tif o.done == 0 {\n\t\terr := f()\n\t\tif err == nil {\n\t\t\tatomic.StoreUint32(\u0026o.done, 1)\n\t\t}\n\t}\n}","line":{"from":59,"to":74}} {"id":100012571,"name":"NewMetricsDu","signature":"func NewMetricsDu(path string) MetricsProvider","file":"pkg/volume/metrics_du.go","code":"// NewMetricsDu creates a new metricsDu with the Volume path.\nfunc NewMetricsDu(path string) MetricsProvider {\n\treturn \u0026metricsDu{path}\n}","line":{"from":35,"to":38}} {"id":100012572,"name":"GetMetrics","signature":"func (md *metricsDu) GetMetrics() (*Metrics, error)","file":"pkg/volume/metrics_du.go","code":"// GetMetrics calculates the volume usage and device free space by executing \"du\"\n// and gathering filesystem info for the Volume path.\n// See MetricsProvider.GetMetrics\nfunc (md *metricsDu) GetMetrics() (*Metrics, error) {\n\tmetrics := \u0026Metrics{Time: metav1.Now()}\n\tif md.path == \"\" {\n\t\treturn metrics, NewNoPathDefinedError()\n\t}\n\n\terr := md.getDiskUsage(metrics)\n\tif err != nil {\n\t\treturn metrics, err\n\t}\n\n\terr = md.getFsInfo(metrics)\n\tif err != nil {\n\t\treturn metrics, err\n\t}\n\n\treturn metrics, nil\n}","line":{"from":40,"to":60}} {"id":100012573,"name":"getDiskUsage","signature":"func (md *metricsDu) getDiskUsage(metrics *Metrics) error","file":"pkg/volume/metrics_du.go","code":"// getDiskUsage writes metrics.Used and metric.InodesUsed from fs.DiskUsage\nfunc (md *metricsDu) getDiskUsage(metrics *Metrics) error {\n\tusage, err := fs.DiskUsage(md.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmetrics.Used = resource.NewQuantity(usage.Bytes, resource.BinarySI)\n\tmetrics.InodesUsed = resource.NewQuantity(usage.Inodes, resource.BinarySI)\n\treturn nil\n}","line":{"from":62,"to":71}} {"id":100012574,"name":"getFsInfo","signature":"func (md *metricsDu) getFsInfo(metrics *Metrics) error","file":"pkg/volume/metrics_du.go","code":"// getFsInfo writes metrics.Capacity and metrics.Available from the filesystem\n// info\nfunc (md *metricsDu) getFsInfo(metrics *Metrics) error {\n\tavailable, capacity, _, inodes, inodesFree, _, err := fs.Info(md.path)\n\tif err != nil {\n\t\treturn NewFsInfoFailedError(err)\n\t}\n\tmetrics.Available = resource.NewQuantity(available, resource.BinarySI)\n\tmetrics.Capacity = resource.NewQuantity(capacity, resource.BinarySI)\n\tmetrics.Inodes = resource.NewQuantity(inodes, resource.BinarySI)\n\tmetrics.InodesFree = resource.NewQuantity(inodesFree, resource.BinarySI)\n\treturn nil\n}","line":{"from":73,"to":85}} {"id":100012575,"name":"NewNotSupportedError","signature":"func NewNotSupportedError() *MetricsError","file":"pkg/volume/metrics_errors.go","code":"// NewNotSupportedError creates a new MetricsError with code NotSupported.\nfunc NewNotSupportedError() *MetricsError {\n\treturn \u0026MetricsError{\n\t\tCode: ErrCodeNotSupported,\n\t\tMsg: \"metrics are not supported for MetricsNil Volumes\",\n\t}\n}","line":{"from":30,"to":36}} {"id":100012576,"name":"NewNotImplementedError","signature":"func NewNotImplementedError(reason string) *MetricsError","file":"pkg/volume/metrics_errors.go","code":"// NewNotImplementedError creates a new MetricsError with code NotSupported.\nfunc NewNotImplementedError(reason string) *MetricsError {\n\treturn \u0026MetricsError{\n\t\tCode: ErrCodeNotSupported,\n\t\tMsg: fmt.Sprintf(\"metrics support is not implemented: %s\", reason),\n\t}\n}","line":{"from":38,"to":44}} {"id":100012577,"name":"NewNotSupportedErrorWithDriverName","signature":"func NewNotSupportedErrorWithDriverName(name string) *MetricsError","file":"pkg/volume/metrics_errors.go","code":"// NewNotSupportedErrorWithDriverName creates a new MetricsError with code NotSupported.\n// driver name is added to the error message.\nfunc NewNotSupportedErrorWithDriverName(name string) *MetricsError {\n\treturn \u0026MetricsError{\n\t\tCode: ErrCodeNotSupported,\n\t\tMsg: fmt.Sprintf(\"metrics are not supported for %s volumes\", name),\n\t}\n}","line":{"from":46,"to":53}} {"id":100012578,"name":"NewNoPathDefinedError","signature":"func NewNoPathDefinedError() *MetricsError","file":"pkg/volume/metrics_errors.go","code":"// NewNoPathDefinedError creates a new MetricsError with code NoPathDefined.\nfunc NewNoPathDefinedError() *MetricsError {\n\treturn \u0026MetricsError{\n\t\tCode: ErrCodeNoPathDefined,\n\t\tMsg: \"no path defined for disk usage metrics.\",\n\t}\n}","line":{"from":55,"to":61}} {"id":100012579,"name":"NewFsInfoFailedError","signature":"func NewFsInfoFailedError(err error) *MetricsError","file":"pkg/volume/metrics_errors.go","code":"// NewFsInfoFailedError creates a new MetricsError with code FsInfoFailed.\nfunc NewFsInfoFailedError(err error) *MetricsError {\n\treturn \u0026MetricsError{\n\t\tCode: ErrCodeFsInfoFailed,\n\t\tMsg: fmt.Sprintf(\"failed to get FsInfo due to error %v\", err),\n\t}\n}","line":{"from":63,"to":69}} {"id":100012580,"name":"Error","signature":"func (e *MetricsError) Error() string","file":"pkg/volume/metrics_errors.go","code":"func (e *MetricsError) Error() string {\n\treturn e.Msg\n}","line":{"from":77,"to":79}} {"id":100012581,"name":"IsNotSupported","signature":"func IsNotSupported(err error) bool","file":"pkg/volume/metrics_errors.go","code":"// IsNotSupported returns true if and only if err is \"key\" not found error.\nfunc IsNotSupported(err error) bool {\n\treturn isErrCode(err, ErrCodeNotSupported)\n}","line":{"from":81,"to":84}} {"id":100012582,"name":"isErrCode","signature":"func isErrCode(err error, code int) bool","file":"pkg/volume/metrics_errors.go","code":"func isErrCode(err error, code int) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\tif e, ok := err.(*MetricsError); ok {\n\t\treturn e.Code == code\n\t}\n\treturn false\n}","line":{"from":86,"to":94}} {"id":100012583,"name":"SupportsMetrics","signature":"func (*MetricsNil) SupportsMetrics() bool","file":"pkg/volume/metrics_nil.go","code":"// SupportsMetrics returns false for the MetricsNil type.\nfunc (*MetricsNil) SupportsMetrics() bool {\n\treturn false\n}","line":{"from":26,"to":29}} {"id":100012584,"name":"GetMetrics","signature":"func (*MetricsNil) GetMetrics() (*Metrics, error)","file":"pkg/volume/metrics_nil.go","code":"// GetMetrics returns an empty Metrics and an error.\n// See MetricsProvider.GetMetrics\nfunc (*MetricsNil) GetMetrics() (*Metrics, error) {\n\treturn \u0026Metrics{}, NewNotSupportedError()\n}","line":{"from":31,"to":35}} {"id":100012585,"name":"NewMetricsStatFS","signature":"func NewMetricsStatFS(path string) MetricsProvider","file":"pkg/volume/metrics_statfs.go","code":"// NewMetricsStatfs creates a new metricsStatFS with the Volume path.\nfunc NewMetricsStatFS(path string) MetricsProvider {\n\treturn \u0026metricsStatFS{path}\n}","line":{"from":37,"to":40}} {"id":100012586,"name":"GetMetrics","signature":"func (md *metricsStatFS) GetMetrics() (*Metrics, error)","file":"pkg/volume/metrics_statfs.go","code":"// See MetricsProvider.GetMetrics\n// GetMetrics calculates the volume usage and device free space by executing \"du\"\n// and gathering filesystem info for the Volume path.\nfunc (md *metricsStatFS) GetMetrics() (*Metrics, error) {\n\tstartTime := time.Now()\n\tdefer servermetrics.CollectVolumeStatCalDuration(\"statfs\", startTime)\n\n\tmetrics := \u0026Metrics{Time: metav1.Now()}\n\tif md.path == \"\" {\n\t\treturn metrics, NewNoPathDefinedError()\n\t}\n\n\terr := md.getFsInfo(metrics)\n\tif err != nil {\n\t\treturn metrics, err\n\t}\n\n\treturn metrics, nil\n}","line":{"from":42,"to":60}} {"id":100012587,"name":"getFsInfo","signature":"func (md *metricsStatFS) getFsInfo(metrics *Metrics) error","file":"pkg/volume/metrics_statfs.go","code":"// getFsInfo writes metrics.Capacity, metrics.Used and metrics.Available from the filesystem info\nfunc (md *metricsStatFS) getFsInfo(metrics *Metrics) error {\n\tavailable, capacity, usage, inodes, inodesFree, inodesUsed, err := fs.Info(md.path)\n\tif err != nil {\n\t\treturn NewFsInfoFailedError(err)\n\t}\n\tmetrics.Available = resource.NewQuantity(available, resource.BinarySI)\n\tmetrics.Capacity = resource.NewQuantity(capacity, resource.BinarySI)\n\tmetrics.Used = resource.NewQuantity(usage, resource.BinarySI)\n\tmetrics.Inodes = resource.NewQuantity(inodes, resource.BinarySI)\n\tmetrics.InodesFree = resource.NewQuantity(inodesFree, resource.BinarySI)\n\tmetrics.InodesUsed = resource.NewQuantity(inodesUsed, resource.BinarySI)\n\treturn nil\n}","line":{"from":62,"to":75}} {"id":100012588,"name":"getPath","signature":"func getPath(uid types.UID, volName string, host volume.VolumeHost) string","file":"pkg/volume/nfs/nfs.go","code":"func getPath(uid types.UID, volName string, host volume.VolumeHost) string {\n\treturn host.GetPodVolumeDir(uid, utilstrings.EscapeQualifiedName(nfsPluginName), volName)\n}","line":{"from":38,"to":40}} {"id":100012589,"name":"ProbeVolumePlugins","signature":"func ProbeVolumePlugins(volumeConfig volume.VolumeConfig) []volume.VolumePlugin","file":"pkg/volume/nfs/nfs.go","code":"// ProbeVolumePlugins is the primary entrypoint for volume plugins.\n// This is the primary entrypoint for volume plugins.\n// The volumeConfig arg provides the ability to configure recycler behavior. It is implemented as a pointer to allow nils.\n// The nfsPlugin is used to store the volumeConfig and give it, when needed, to the func that creates NFS Recyclers.\n// Tests that exercise recycling should not use this func but instead use ProbeRecyclablePlugins() to override default behavior.\nfunc ProbeVolumePlugins(volumeConfig volume.VolumeConfig) []volume.VolumePlugin {\n\treturn []volume.VolumePlugin{\n\t\t\u0026nfsPlugin{\n\t\t\thost: nil,\n\t\t\tconfig: volumeConfig,\n\t\t},\n\t}\n}","line":{"from":42,"to":54}} {"id":100012590,"name":"Init","signature":"func (plugin *nfsPlugin) Init(host volume.VolumeHost) error","file":"pkg/volume/nfs/nfs.go","code":"func (plugin *nfsPlugin) Init(host volume.VolumeHost) error {\n\tplugin.host = host\n\treturn nil\n}","line":{"from":70,"to":73}} {"id":100012591,"name":"GetPluginName","signature":"func (plugin *nfsPlugin) GetPluginName() string","file":"pkg/volume/nfs/nfs.go","code":"func (plugin *nfsPlugin) GetPluginName() string {\n\treturn nfsPluginName\n}","line":{"from":75,"to":77}} {"id":100012592,"name":"GetVolumeName","signature":"func (plugin *nfsPlugin) GetVolumeName(spec *volume.Spec) (string, error)","file":"pkg/volume/nfs/nfs.go","code":"func (plugin *nfsPlugin) GetVolumeName(spec *volume.Spec) (string, error) {\n\tvolumeSource, _, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn fmt.Sprintf(\n\t\t\"%v/%v\",\n\t\tvolumeSource.Server,\n\t\tvolumeSource.Path), nil\n}","line":{"from":79,"to":89}} {"id":100012593,"name":"CanSupport","signature":"func (plugin *nfsPlugin) CanSupport(spec *volume.Spec) bool","file":"pkg/volume/nfs/nfs.go","code":"func (plugin *nfsPlugin) CanSupport(spec *volume.Spec) bool {\n\treturn (spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.NFS != nil) ||\n\t\t(spec.Volume != nil \u0026\u0026 spec.Volume.NFS != nil)\n}","line":{"from":91,"to":94}} {"id":100012594,"name":"RequiresRemount","signature":"func (plugin *nfsPlugin) RequiresRemount(spec *volume.Spec) bool","file":"pkg/volume/nfs/nfs.go","code":"func (plugin *nfsPlugin) RequiresRemount(spec *volume.Spec) bool {\n\treturn false\n}","line":{"from":96,"to":98}} {"id":100012595,"name":"SupportsMountOption","signature":"func (plugin *nfsPlugin) SupportsMountOption() bool","file":"pkg/volume/nfs/nfs.go","code":"func (plugin *nfsPlugin) SupportsMountOption() bool {\n\treturn true\n}","line":{"from":100,"to":102}} {"id":100012596,"name":"SupportsBulkVolumeVerification","signature":"func (plugin *nfsPlugin) SupportsBulkVolumeVerification() bool","file":"pkg/volume/nfs/nfs.go","code":"func (plugin *nfsPlugin) SupportsBulkVolumeVerification() bool {\n\treturn false\n}","line":{"from":104,"to":106}} {"id":100012597,"name":"SupportsSELinuxContextMount","signature":"func (plugin *nfsPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/nfs/nfs.go","code":"func (plugin *nfsPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error) {\n\treturn false, nil\n}","line":{"from":108,"to":110}} {"id":100012598,"name":"GetAccessModes","signature":"func (plugin *nfsPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode","file":"pkg/volume/nfs/nfs.go","code":"func (plugin *nfsPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode {\n\treturn []v1.PersistentVolumeAccessMode{\n\t\tv1.ReadWriteOnce,\n\t\tv1.ReadOnlyMany,\n\t\tv1.ReadWriteMany,\n\t}\n}","line":{"from":112,"to":118}} {"id":100012599,"name":"NewMounter","signature":"func (plugin *nfsPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error)","file":"pkg/volume/nfs/nfs.go","code":"func (plugin *nfsPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) {\n\treturn plugin.newMounterInternal(spec, pod, plugin.host.GetMounter(plugin.GetPluginName()))\n}","line":{"from":120,"to":122}} {"id":100012600,"name":"newMounterInternal","signature":"func (plugin *nfsPlugin) newMounterInternal(spec *volume.Spec, pod *v1.Pod, mounter mount.Interface) (volume.Mounter, error)","file":"pkg/volume/nfs/nfs.go","code":"func (plugin *nfsPlugin) newMounterInternal(spec *volume.Spec, pod *v1.Pod, mounter mount.Interface) (volume.Mounter, error) {\n\tsource, readOnly, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026nfsMounter{\n\t\tnfs: \u0026nfs{\n\t\t\tvolName: spec.Name(),\n\t\t\tmounter: mounter,\n\t\t\tpod: pod,\n\t\t\tplugin: plugin,\n\t\t\tMetricsProvider: volume.NewMetricsStatFS(getPath(pod.UID, spec.Name(), plugin.host)),\n\t\t},\n\t\tserver: getServerFromSource(source),\n\t\texportPath: source.Path,\n\t\treadOnly: readOnly,\n\t\tmountOptions: util.MountOptionFromSpec(spec),\n\t}, nil\n}","line":{"from":124,"to":142}} {"id":100012601,"name":"NewUnmounter","signature":"func (plugin *nfsPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error)","file":"pkg/volume/nfs/nfs.go","code":"func (plugin *nfsPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error) {\n\treturn plugin.newUnmounterInternal(volName, podUID, plugin.host.GetMounter(plugin.GetPluginName()))\n}","line":{"from":144,"to":146}} {"id":100012602,"name":"newUnmounterInternal","signature":"func (plugin *nfsPlugin) newUnmounterInternal(volName string, podUID types.UID, mounter mount.Interface) (volume.Unmounter, error)","file":"pkg/volume/nfs/nfs.go","code":"func (plugin *nfsPlugin) newUnmounterInternal(volName string, podUID types.UID, mounter mount.Interface) (volume.Unmounter, error) {\n\treturn \u0026nfsUnmounter{\u0026nfs{\n\t\tvolName: volName,\n\t\tmounter: mounter,\n\t\tpod: \u0026v1.Pod{ObjectMeta: metav1.ObjectMeta{UID: podUID}},\n\t\tplugin: plugin,\n\t\tMetricsProvider: volume.NewMetricsStatFS(getPath(podUID, volName, plugin.host)),\n\t}}, nil\n}","line":{"from":148,"to":156}} {"id":100012603,"name":"Recycle","signature":"func (plugin *nfsPlugin) Recycle(pvName string, spec *volume.Spec, eventRecorder recyclerclient.RecycleEventRecorder) error","file":"pkg/volume/nfs/nfs.go","code":"// Recycle recycles/scrubs clean an NFS volume.\n// Recycle blocks until the pod has completed or any error occurs.\nfunc (plugin *nfsPlugin) Recycle(pvName string, spec *volume.Spec, eventRecorder recyclerclient.RecycleEventRecorder) error {\n\tif spec.PersistentVolume == nil || spec.PersistentVolume.Spec.NFS == nil {\n\t\treturn fmt.Errorf(\"spec.PersistentVolumeSource.NFS is nil\")\n\t}\n\n\tpod := plugin.config.RecyclerPodTemplate\n\ttimeout := util.CalculateTimeoutForVolume(plugin.config.RecyclerMinimumTimeout, plugin.config.RecyclerTimeoutIncrement, spec.PersistentVolume)\n\t// overrides\n\tpod.Spec.ActiveDeadlineSeconds = \u0026timeout\n\tpod.GenerateName = \"pv-recycler-nfs-\"\n\tpod.Spec.Volumes[0].VolumeSource = v1.VolumeSource{\n\t\tNFS: \u0026v1.NFSVolumeSource{\n\t\t\tServer: spec.PersistentVolume.Spec.NFS.Server,\n\t\t\tPath: spec.PersistentVolume.Spec.NFS.Path,\n\t\t},\n\t}\n\treturn recyclerclient.RecycleVolumeByWatchingPodUntilCompletion(pvName, pod, plugin.host.GetKubeClient(), eventRecorder)\n}","line":{"from":158,"to":177}} {"id":100012604,"name":"ConstructVolumeSpec","signature":"func (plugin *nfsPlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error)","file":"pkg/volume/nfs/nfs.go","code":"func (plugin *nfsPlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error) {\n\tnfsVolume := \u0026v1.Volume{\n\t\tName: volumeName,\n\t\tVolumeSource: v1.VolumeSource{\n\t\t\tNFS: \u0026v1.NFSVolumeSource{\n\t\t\t\tPath: volumeName,\n\t\t\t},\n\t\t},\n\t}\n\treturn volume.ReconstructedVolume{\n\t\tSpec: volume.NewSpecFromVolume(nfsVolume),\n\t}, nil\n}","line":{"from":179,"to":191}} {"id":100012605,"name":"GetPath","signature":"func (nfsVolume *nfs) GetPath() string","file":"pkg/volume/nfs/nfs.go","code":"func (nfsVolume *nfs) GetPath() string {\n\tname := nfsPluginName\n\treturn nfsVolume.plugin.host.GetPodVolumeDir(nfsVolume.pod.UID, utilstrings.EscapeQualifiedName(name), nfsVolume.volName)\n}","line":{"from":202,"to":205}} {"id":100012606,"name":"GetAttributes","signature":"func (nfsMounter *nfsMounter) GetAttributes() volume.Attributes","file":"pkg/volume/nfs/nfs.go","code":"func (nfsMounter *nfsMounter) GetAttributes() volume.Attributes {\n\treturn volume.Attributes{\n\t\tReadOnly: nfsMounter.readOnly,\n\t\tManaged: false,\n\t\tSELinuxRelabel: false,\n\t}\n}","line":{"from":217,"to":223}} {"id":100012607,"name":"SetUp","signature":"func (nfsMounter *nfsMounter) SetUp(mounterArgs volume.MounterArgs) error","file":"pkg/volume/nfs/nfs.go","code":"// SetUp attaches the disk and bind mounts to the volume path.\nfunc (nfsMounter *nfsMounter) SetUp(mounterArgs volume.MounterArgs) error {\n\treturn nfsMounter.SetUpAt(nfsMounter.GetPath(), mounterArgs)\n}","line":{"from":225,"to":228}} {"id":100012608,"name":"SetUpAt","signature":"func (nfsMounter *nfsMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error","file":"pkg/volume/nfs/nfs.go","code":"func (nfsMounter *nfsMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {\n\tnotMnt, err := mount.IsNotMountPoint(nfsMounter.mounter, dir)\n\tklog.V(4).Infof(\"NFS mount set up: %s %v %v\", dir, !notMnt, err)\n\tif err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\tif !notMnt {\n\t\treturn nil\n\t}\n\tif err := os.MkdirAll(dir, 0750); err != nil {\n\t\treturn err\n\t}\n\tsource := fmt.Sprintf(\"%s:%s\", nfsMounter.server, nfsMounter.exportPath)\n\toptions := []string{}\n\tif nfsMounter.readOnly {\n\t\toptions = append(options, \"ro\")\n\t}\n\tmountOptions := util.JoinMountOptions(nfsMounter.mountOptions, options)\n\terr = nfsMounter.mounter.MountSensitiveWithoutSystemd(source, dir, \"nfs\", mountOptions, nil)\n\tif err != nil {\n\t\tnotMnt, mntErr := mount.IsNotMountPoint(nfsMounter.mounter, dir)\n\t\tif mntErr != nil {\n\t\t\tklog.Errorf(\"IsNotMountPoint check failed: %v\", mntErr)\n\t\t\treturn err\n\t\t}\n\t\tif !notMnt {\n\t\t\tif mntErr = nfsMounter.mounter.Unmount(dir); mntErr != nil {\n\t\t\t\tklog.Errorf(\"Failed to unmount: %v\", mntErr)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tnotMnt, mntErr := mount.IsNotMountPoint(nfsMounter.mounter, dir)\n\t\t\tif mntErr != nil {\n\t\t\t\tklog.Errorf(\"IsNotMountPoint check failed: %v\", mntErr)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !notMnt {\n\t\t\t\t// This is very odd, we don't expect it. We'll try again next sync loop.\n\t\t\t\tklog.Errorf(\"%s is still mounted, despite call to unmount(). Will try again next sync loop.\", dir)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tos.Remove(dir)\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":230,"to":275}} {"id":100012609,"name":"TearDown","signature":"func (c *nfsUnmounter) TearDown() error","file":"pkg/volume/nfs/nfs.go","code":"func (c *nfsUnmounter) TearDown() error {\n\treturn c.TearDownAt(c.GetPath())\n}","line":{"from":283,"to":285}} {"id":100012610,"name":"TearDownAt","signature":"func (c *nfsUnmounter) TearDownAt(dir string) error","file":"pkg/volume/nfs/nfs.go","code":"func (c *nfsUnmounter) TearDownAt(dir string) error {\n\t// Use extensiveMountPointCheck to consult /proc/mounts. We can't use faster\n\t// IsLikelyNotMountPoint (lstat()), since there may be root_squash on the\n\t// NFS server and kubelet may not be able to do lstat/stat() there.\n\tforceUnmounter, ok := c.mounter.(mount.MounterForceUnmounter)\n\tif ok {\n\t\tklog.V(4).Infof(\"Using force unmounter interface\")\n\t\treturn mount.CleanupMountWithForce(dir, forceUnmounter, true /* extensiveMountPointCheck */, unMountTimeout)\n\t}\n\treturn mount.CleanupMountPoint(dir, c.mounter, true /* extensiveMountPointCheck */)\n}","line":{"from":287,"to":297}} {"id":100012611,"name":"getVolumeSource","signature":"func getVolumeSource(spec *volume.Spec) (*v1.NFSVolumeSource, bool, error)","file":"pkg/volume/nfs/nfs.go","code":"func getVolumeSource(spec *volume.Spec) (*v1.NFSVolumeSource, bool, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.NFS != nil {\n\t\treturn spec.Volume.NFS, spec.Volume.NFS.ReadOnly, nil\n\t} else if spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.NFS != nil {\n\t\treturn spec.PersistentVolume.Spec.NFS, spec.ReadOnly, nil\n\t}\n\n\treturn nil, false, fmt.Errorf(\"Spec does not reference a NFS volume type\")\n}","line":{"from":299,"to":308}} {"id":100012612,"name":"getServerFromSource","signature":"func getServerFromSource(source *v1.NFSVolumeSource) string","file":"pkg/volume/nfs/nfs.go","code":"func getServerFromSource(source *v1.NFSVolumeSource) string {\n\tif netutil.IsIPv6String(source.Server) {\n\t\treturn fmt.Sprintf(\"[%s]\", source.Server)\n\t}\n\treturn source.Server\n}","line":{"from":310,"to":315}} {"id":100012613,"name":"ExpandVolumeDevice","signature":"func (n *noopExpandableVolumePluginInstance) ExpandVolumeDevice(spec *Spec, newSize resource.Quantity, oldSize resource.Quantity) (resource.Quantity, error)","file":"pkg/volume/noop_expandable_plugin.go","code":"func (n *noopExpandableVolumePluginInstance) ExpandVolumeDevice(spec *Spec, newSize resource.Quantity, oldSize resource.Quantity) (resource.Quantity, error) {\n\treturn newSize, nil\n}","line":{"from":31,"to":33}} {"id":100012614,"name":"Init","signature":"func (n *noopExpandableVolumePluginInstance) Init(host VolumeHost) error","file":"pkg/volume/noop_expandable_plugin.go","code":"func (n *noopExpandableVolumePluginInstance) Init(host VolumeHost) error {\n\treturn nil\n}","line":{"from":35,"to":37}} {"id":100012615,"name":"GetPluginName","signature":"func (n *noopExpandableVolumePluginInstance) GetPluginName() string","file":"pkg/volume/noop_expandable_plugin.go","code":"func (n *noopExpandableVolumePluginInstance) GetPluginName() string {\n\treturn n.spec.KubeletExpandablePluginName()\n}","line":{"from":39,"to":41}} {"id":100012616,"name":"GetVolumeName","signature":"func (n *noopExpandableVolumePluginInstance) GetVolumeName(spec *Spec) (string, error)","file":"pkg/volume/noop_expandable_plugin.go","code":"func (n *noopExpandableVolumePluginInstance) GetVolumeName(spec *Spec) (string, error) {\n\treturn n.spec.Name(), nil\n}","line":{"from":43,"to":45}} {"id":100012617,"name":"CanSupport","signature":"func (n *noopExpandableVolumePluginInstance) CanSupport(spec *Spec) bool","file":"pkg/volume/noop_expandable_plugin.go","code":"func (n *noopExpandableVolumePluginInstance) CanSupport(spec *Spec) bool {\n\treturn true\n}","line":{"from":47,"to":49}} {"id":100012618,"name":"RequiresRemount","signature":"func (n *noopExpandableVolumePluginInstance) RequiresRemount(spec *Spec) bool","file":"pkg/volume/noop_expandable_plugin.go","code":"func (n *noopExpandableVolumePluginInstance) RequiresRemount(spec *Spec) bool {\n\treturn false\n}","line":{"from":51,"to":53}} {"id":100012619,"name":"NewMounter","signature":"func (n *noopExpandableVolumePluginInstance) NewMounter(spec *Spec, podRef *v1.Pod, opts VolumeOptions) (Mounter, error)","file":"pkg/volume/noop_expandable_plugin.go","code":"func (n *noopExpandableVolumePluginInstance) NewMounter(spec *Spec, podRef *v1.Pod, opts VolumeOptions) (Mounter, error) {\n\treturn nil, nil\n}","line":{"from":55,"to":57}} {"id":100012620,"name":"NewUnmounter","signature":"func (n *noopExpandableVolumePluginInstance) NewUnmounter(name string, podUID types.UID) (Unmounter, error)","file":"pkg/volume/noop_expandable_plugin.go","code":"func (n *noopExpandableVolumePluginInstance) NewUnmounter(name string, podUID types.UID) (Unmounter, error) {\n\treturn nil, nil\n}","line":{"from":59,"to":61}} {"id":100012621,"name":"ConstructVolumeSpec","signature":"func (n *noopExpandableVolumePluginInstance) ConstructVolumeSpec(volumeName, mountPath string) (ReconstructedVolume, error)","file":"pkg/volume/noop_expandable_plugin.go","code":"func (n *noopExpandableVolumePluginInstance) ConstructVolumeSpec(volumeName, mountPath string) (ReconstructedVolume, error) {\n\treturn ReconstructedVolume{Spec: n.spec}, nil\n}","line":{"from":63,"to":65}} {"id":100012622,"name":"SupportsMountOption","signature":"func (n *noopExpandableVolumePluginInstance) SupportsMountOption() bool","file":"pkg/volume/noop_expandable_plugin.go","code":"func (n *noopExpandableVolumePluginInstance) SupportsMountOption() bool {\n\treturn true\n}","line":{"from":67,"to":69}} {"id":100012623,"name":"SupportsBulkVolumeVerification","signature":"func (n *noopExpandableVolumePluginInstance) SupportsBulkVolumeVerification() bool","file":"pkg/volume/noop_expandable_plugin.go","code":"func (n *noopExpandableVolumePluginInstance) SupportsBulkVolumeVerification() bool {\n\treturn false\n}","line":{"from":71,"to":73}} {"id":100012624,"name":"RequiresFSResize","signature":"func (n *noopExpandableVolumePluginInstance) RequiresFSResize() bool","file":"pkg/volume/noop_expandable_plugin.go","code":"func (n *noopExpandableVolumePluginInstance) RequiresFSResize() bool {\n\treturn true\n}","line":{"from":75,"to":77}} {"id":100012625,"name":"SupportsSELinuxContextMount","signature":"func (n *noopExpandableVolumePluginInstance) SupportsSELinuxContextMount(spec *Spec) (bool, error)","file":"pkg/volume/noop_expandable_plugin.go","code":"func (n *noopExpandableVolumePluginInstance) SupportsSELinuxContextMount(spec *Spec) (bool, error) {\n\treturn false, nil\n}","line":{"from":79,"to":81}} {"id":100012626,"name":"Name","signature":"func (spec *Spec) Name() string","file":"pkg/volume/plugins.go","code":"// Name returns the name of either Volume or PersistentVolume, one of which must not be nil.\nfunc (spec *Spec) Name() string {\n\tswitch {\n\tcase spec.Volume != nil:\n\t\treturn spec.Volume.Name\n\tcase spec.PersistentVolume != nil:\n\t\treturn spec.PersistentVolume.Name\n\tdefault:\n\t\treturn \"\"\n\t}\n}","line":{"from":470,"to":480}} {"id":100012627,"name":"IsKubeletExpandable","signature":"func (spec *Spec) IsKubeletExpandable() bool","file":"pkg/volume/plugins.go","code":"// IsKubeletExpandable returns true for volume types that can be expanded only by the node\n// and not the controller. Currently Flex volume is the only one in this category since\n// it is typically not installed on the controller\nfunc (spec *Spec) IsKubeletExpandable() bool {\n\tswitch {\n\tcase spec.Volume != nil:\n\t\treturn spec.Volume.FlexVolume != nil\n\tcase spec.PersistentVolume != nil:\n\t\treturn spec.PersistentVolume.Spec.FlexVolume != nil\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":482,"to":494}} {"id":100012628,"name":"KubeletExpandablePluginName","signature":"func (spec *Spec) KubeletExpandablePluginName() string","file":"pkg/volume/plugins.go","code":"// KubeletExpandablePluginName creates and returns a name for the plugin\n// this is used in context on the controller where the plugin lookup fails\n// as volume expansion on controller isn't supported, but a plugin name is\n// required\nfunc (spec *Spec) KubeletExpandablePluginName() string {\n\tswitch {\n\tcase spec.Volume != nil \u0026\u0026 spec.Volume.FlexVolume != nil:\n\t\treturn spec.Volume.FlexVolume.Driver\n\tcase spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.FlexVolume != nil:\n\t\treturn spec.PersistentVolume.Spec.FlexVolume.Driver\n\tdefault:\n\t\treturn \"\"\n\t}\n}","line":{"from":496,"to":509}} {"id":100012629,"name":"NewSpecFromVolume","signature":"func NewSpecFromVolume(vs *v1.Volume) *Spec","file":"pkg/volume/plugins.go","code":"// NewSpecFromVolume creates an Spec from an v1.Volume\nfunc NewSpecFromVolume(vs *v1.Volume) *Spec {\n\treturn \u0026Spec{\n\t\tVolume: vs,\n\t}\n}","line":{"from":576,"to":581}} {"id":100012630,"name":"NewSpecFromPersistentVolume","signature":"func NewSpecFromPersistentVolume(pv *v1.PersistentVolume, readOnly bool) *Spec","file":"pkg/volume/plugins.go","code":"// NewSpecFromPersistentVolume creates an Spec from an v1.PersistentVolume\nfunc NewSpecFromPersistentVolume(pv *v1.PersistentVolume, readOnly bool) *Spec {\n\treturn \u0026Spec{\n\t\tPersistentVolume: pv,\n\t\tReadOnly: readOnly,\n\t}\n}","line":{"from":583,"to":589}} {"id":100012631,"name":"InitPlugins","signature":"func (pm *VolumePluginMgr) InitPlugins(plugins []VolumePlugin, prober DynamicPluginProber, host VolumeHost) error","file":"pkg/volume/plugins.go","code":"// InitPlugins initializes each plugin. All plugins must have unique names.\n// This must be called exactly once before any New* methods are called on any\n// plugins.\nfunc (pm *VolumePluginMgr) InitPlugins(plugins []VolumePlugin, prober DynamicPluginProber, host VolumeHost) error {\n\tpm.mutex.Lock()\n\tdefer pm.mutex.Unlock()\n\n\tpm.Host = host\n\tpm.loggedDeprecationWarnings = sets.NewString()\n\n\tif prober == nil {\n\t\t// Use a dummy prober to prevent nil deference.\n\t\tpm.prober = \u0026dummyPluginProber{}\n\t} else {\n\t\tpm.prober = prober\n\t}\n\tif err := pm.prober.Init(); err != nil {\n\t\t// Prober init failure should not affect the initialization of other plugins.\n\t\tklog.ErrorS(err, \"Error initializing dynamic plugin prober\")\n\t\tpm.prober = \u0026dummyPluginProber{}\n\t}\n\n\tif pm.plugins == nil {\n\t\tpm.plugins = map[string]VolumePlugin{}\n\t}\n\tif pm.probedPlugins == nil {\n\t\tpm.probedPlugins = map[string]VolumePlugin{}\n\t}\n\n\tallErrs := []error{}\n\tfor _, plugin := range plugins {\n\t\tname := plugin.GetPluginName()\n\t\tif errs := validation.IsQualifiedName(name); len(errs) != 0 {\n\t\t\tallErrs = append(allErrs, fmt.Errorf(\"volume plugin has invalid name: %q: %s\", name, strings.Join(errs, \";\")))\n\t\t\tcontinue\n\t\t}\n\n\t\tif _, found := pm.plugins[name]; found {\n\t\t\tallErrs = append(allErrs, fmt.Errorf(\"volume plugin %q was registered more than once\", name))\n\t\t\tcontinue\n\t\t}\n\t\terr := plugin.Init(host)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to load volume plugin\", \"pluginName\", name)\n\t\t\tallErrs = append(allErrs, err)\n\t\t\tcontinue\n\t\t}\n\t\tpm.plugins[name] = plugin\n\t\tklog.V(1).InfoS(\"Loaded volume plugin\", \"pluginName\", name)\n\t}\n\treturn utilerrors.NewAggregate(allErrs)\n}","line":{"from":591,"to":642}} {"id":100012632,"name":"initProbedPlugin","signature":"func (pm *VolumePluginMgr) initProbedPlugin(probedPlugin VolumePlugin) error","file":"pkg/volume/plugins.go","code":"func (pm *VolumePluginMgr) initProbedPlugin(probedPlugin VolumePlugin) error {\n\tname := probedPlugin.GetPluginName()\n\tif errs := validation.IsQualifiedName(name); len(errs) != 0 {\n\t\treturn fmt.Errorf(\"volume plugin has invalid name: %q: %s\", name, strings.Join(errs, \";\"))\n\t}\n\n\terr := probedPlugin.Init(pm.Host)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to load volume plugin %s, error: %s\", name, err.Error())\n\t}\n\n\tklog.V(1).InfoS(\"Loaded volume plugin\", \"pluginName\", name)\n\treturn nil\n}","line":{"from":644,"to":657}} {"id":100012633,"name":"FindPluginBySpec","signature":"func (pm *VolumePluginMgr) FindPluginBySpec(spec *Spec) (VolumePlugin, error)","file":"pkg/volume/plugins.go","code":"// FindPluginBySpec looks for a plugin that can support a given volume\n// specification. If no plugins can support or more than one plugin can\n// support it, return error.\nfunc (pm *VolumePluginMgr) FindPluginBySpec(spec *Spec) (VolumePlugin, error) {\n\tpm.mutex.RLock()\n\tdefer pm.mutex.RUnlock()\n\n\tif spec == nil {\n\t\treturn nil, fmt.Errorf(\"could not find plugin because volume spec is nil\")\n\t}\n\n\tvar match VolumePlugin\n\tmatchedPluginNames := []string{}\n\tfor _, v := range pm.plugins {\n\t\tif v.CanSupport(spec) {\n\t\t\tmatch = v\n\t\t\tmatchedPluginNames = append(matchedPluginNames, v.GetPluginName())\n\t\t}\n\t}\n\n\tpm.refreshProbedPlugins()\n\tfor _, plugin := range pm.probedPlugins {\n\t\tif plugin.CanSupport(spec) {\n\t\t\tmatch = plugin\n\t\t\tmatchedPluginNames = append(matchedPluginNames, plugin.GetPluginName())\n\t\t}\n\t}\n\n\tif len(matchedPluginNames) == 0 {\n\t\treturn nil, fmt.Errorf(\"no volume plugin matched\")\n\t}\n\tif len(matchedPluginNames) \u003e 1 {\n\t\treturn nil, fmt.Errorf(\"multiple volume plugins matched: %s\", strings.Join(matchedPluginNames, \",\"))\n\t}\n\n\treturn match, nil\n}","line":{"from":659,"to":695}} {"id":100012634,"name":"FindPluginByName","signature":"func (pm *VolumePluginMgr) FindPluginByName(name string) (VolumePlugin, error)","file":"pkg/volume/plugins.go","code":"// FindPluginByName fetches a plugin by name or by legacy name. If no plugin\n// is found, returns error.\nfunc (pm *VolumePluginMgr) FindPluginByName(name string) (VolumePlugin, error) {\n\tpm.mutex.RLock()\n\tdefer pm.mutex.RUnlock()\n\n\t// Once we can get rid of legacy names we can reduce this to a map lookup.\n\tvar match VolumePlugin\n\tif v, found := pm.plugins[name]; found {\n\t\tmatch = v\n\t}\n\n\tpm.refreshProbedPlugins()\n\tif plugin, found := pm.probedPlugins[name]; found {\n\t\tif match != nil {\n\t\t\treturn nil, fmt.Errorf(\"multiple volume plugins matched: %s and %s\", match.GetPluginName(), plugin.GetPluginName())\n\t\t}\n\t\tmatch = plugin\n\t}\n\n\tif match == nil {\n\t\treturn nil, fmt.Errorf(\"no volume plugin matched name: %s\", name)\n\t}\n\treturn match, nil\n}","line":{"from":697,"to":721}} {"id":100012635,"name":"refreshProbedPlugins","signature":"func (pm *VolumePluginMgr) refreshProbedPlugins()","file":"pkg/volume/plugins.go","code":"// Check if probedPlugin cache update is required.\n// If it is, initialize all probed plugins and replace the cache with them.\nfunc (pm *VolumePluginMgr) refreshProbedPlugins() {\n\tevents, err := pm.prober.Probe()\n\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Error dynamically probing plugins\")\n\t}\n\n\t// because the probe function can return a list of valid plugins\n\t// even when an error is present we still must add the plugins\n\t// or they will be skipped because each event only fires once\n\tfor _, event := range events {\n\t\tif event.Op == ProbeAddOrUpdate {\n\t\t\tif err := pm.initProbedPlugin(event.Plugin); err != nil {\n\t\t\t\tklog.ErrorS(err, \"Error initializing dynamically probed plugin\",\n\t\t\t\t\t\"pluginName\", event.Plugin.GetPluginName())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpm.probedPlugins[event.Plugin.GetPluginName()] = event.Plugin\n\t\t} else if event.Op == ProbeRemove {\n\t\t\t// Plugin is not available on ProbeRemove event, only PluginName\n\t\t\tdelete(pm.probedPlugins, event.PluginName)\n\t\t} else {\n\t\t\tklog.ErrorS(nil, \"Unknown Operation on PluginName.\",\n\t\t\t\t\"pluginName\", event.Plugin.GetPluginName())\n\t\t}\n\t}\n}","line":{"from":723,"to":751}} {"id":100012636,"name":"ListVolumePluginWithLimits","signature":"func (pm *VolumePluginMgr) ListVolumePluginWithLimits() []VolumePluginWithAttachLimits","file":"pkg/volume/plugins.go","code":"// ListVolumePluginWithLimits returns plugins that have volume limits on nodes\nfunc (pm *VolumePluginMgr) ListVolumePluginWithLimits() []VolumePluginWithAttachLimits {\n\tpm.mutex.RLock()\n\tdefer pm.mutex.RUnlock()\n\n\tmatchedPlugins := []VolumePluginWithAttachLimits{}\n\tfor _, v := range pm.plugins {\n\t\tif plugin, ok := v.(VolumePluginWithAttachLimits); ok {\n\t\t\tmatchedPlugins = append(matchedPlugins, plugin)\n\t\t}\n\t}\n\treturn matchedPlugins\n}","line":{"from":753,"to":765}} {"id":100012637,"name":"FindPersistentPluginBySpec","signature":"func (pm *VolumePluginMgr) FindPersistentPluginBySpec(spec *Spec) (PersistentVolumePlugin, error)","file":"pkg/volume/plugins.go","code":"// FindPersistentPluginBySpec looks for a persistent volume plugin that can\n// support a given volume specification. If no plugin is found, return an\n// error\nfunc (pm *VolumePluginMgr) FindPersistentPluginBySpec(spec *Spec) (PersistentVolumePlugin, error) {\n\tvolumePlugin, err := pm.FindPluginBySpec(spec)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not find volume plugin for spec: %#v\", spec)\n\t}\n\tif persistentVolumePlugin, ok := volumePlugin.(PersistentVolumePlugin); ok {\n\t\treturn persistentVolumePlugin, nil\n\t}\n\treturn nil, fmt.Errorf(\"no persistent volume plugin matched\")\n}","line":{"from":767,"to":779}} {"id":100012638,"name":"FindVolumePluginWithLimitsBySpec","signature":"func (pm *VolumePluginMgr) FindVolumePluginWithLimitsBySpec(spec *Spec) (VolumePluginWithAttachLimits, error)","file":"pkg/volume/plugins.go","code":"// FindVolumePluginWithLimitsBySpec returns volume plugin that has a limit on how many\n// of them can be attached to a node\nfunc (pm *VolumePluginMgr) FindVolumePluginWithLimitsBySpec(spec *Spec) (VolumePluginWithAttachLimits, error) {\n\tvolumePlugin, err := pm.FindPluginBySpec(spec)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not find volume plugin for spec : %#v\", spec)\n\t}\n\n\tif limitedPlugin, ok := volumePlugin.(VolumePluginWithAttachLimits); ok {\n\t\treturn limitedPlugin, nil\n\t}\n\treturn nil, fmt.Errorf(\"no plugin with limits found\")\n}","line":{"from":781,"to":793}} {"id":100012639,"name":"FindPersistentPluginByName","signature":"func (pm *VolumePluginMgr) FindPersistentPluginByName(name string) (PersistentVolumePlugin, error)","file":"pkg/volume/plugins.go","code":"// FindPersistentPluginByName fetches a persistent volume plugin by name. If\n// no plugin is found, returns error.\nfunc (pm *VolumePluginMgr) FindPersistentPluginByName(name string) (PersistentVolumePlugin, error) {\n\tvolumePlugin, err := pm.FindPluginByName(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif persistentVolumePlugin, ok := volumePlugin.(PersistentVolumePlugin); ok {\n\t\treturn persistentVolumePlugin, nil\n\t}\n\treturn nil, fmt.Errorf(\"no persistent volume plugin matched\")\n}","line":{"from":795,"to":806}} {"id":100012640,"name":"FindRecyclablePluginBySpec","signature":"func (pm *VolumePluginMgr) FindRecyclablePluginBySpec(spec *Spec) (RecyclableVolumePlugin, error)","file":"pkg/volume/plugins.go","code":"// FindRecyclablePluginByName fetches a persistent volume plugin by name. If\n// no plugin is found, returns error.\nfunc (pm *VolumePluginMgr) FindRecyclablePluginBySpec(spec *Spec) (RecyclableVolumePlugin, error) {\n\tvolumePlugin, err := pm.FindPluginBySpec(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif recyclableVolumePlugin, ok := volumePlugin.(RecyclableVolumePlugin); ok {\n\t\treturn recyclableVolumePlugin, nil\n\t}\n\treturn nil, fmt.Errorf(\"no recyclable volume plugin matched\")\n}","line":{"from":808,"to":819}} {"id":100012641,"name":"FindProvisionablePluginByName","signature":"func (pm *VolumePluginMgr) FindProvisionablePluginByName(name string) (ProvisionableVolumePlugin, error)","file":"pkg/volume/plugins.go","code":"// FindProvisionablePluginByName fetches a persistent volume plugin by name. If\n// no plugin is found, returns error.\nfunc (pm *VolumePluginMgr) FindProvisionablePluginByName(name string) (ProvisionableVolumePlugin, error) {\n\tvolumePlugin, err := pm.FindPluginByName(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif provisionableVolumePlugin, ok := volumePlugin.(ProvisionableVolumePlugin); ok {\n\t\treturn provisionableVolumePlugin, nil\n\t}\n\treturn nil, fmt.Errorf(\"no provisionable volume plugin matched\")\n}","line":{"from":821,"to":832}} {"id":100012642,"name":"FindDeletablePluginBySpec","signature":"func (pm *VolumePluginMgr) FindDeletablePluginBySpec(spec *Spec) (DeletableVolumePlugin, error)","file":"pkg/volume/plugins.go","code":"// FindDeletablePluginBySpec fetches a persistent volume plugin by spec. If\n// no plugin is found, returns error.\nfunc (pm *VolumePluginMgr) FindDeletablePluginBySpec(spec *Spec) (DeletableVolumePlugin, error) {\n\tvolumePlugin, err := pm.FindPluginBySpec(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif deletableVolumePlugin, ok := volumePlugin.(DeletableVolumePlugin); ok {\n\t\treturn deletableVolumePlugin, nil\n\t}\n\treturn nil, fmt.Errorf(\"no deletable volume plugin matched\")\n}","line":{"from":834,"to":845}} {"id":100012643,"name":"FindDeletablePluginByName","signature":"func (pm *VolumePluginMgr) FindDeletablePluginByName(name string) (DeletableVolumePlugin, error)","file":"pkg/volume/plugins.go","code":"// FindDeletablePluginByName fetches a persistent volume plugin by name. If\n// no plugin is found, returns error.\nfunc (pm *VolumePluginMgr) FindDeletablePluginByName(name string) (DeletableVolumePlugin, error) {\n\tvolumePlugin, err := pm.FindPluginByName(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif deletableVolumePlugin, ok := volumePlugin.(DeletableVolumePlugin); ok {\n\t\treturn deletableVolumePlugin, nil\n\t}\n\treturn nil, fmt.Errorf(\"no deletable volume plugin matched\")\n}","line":{"from":847,"to":858}} {"id":100012644,"name":"FindCreatablePluginBySpec","signature":"func (pm *VolumePluginMgr) FindCreatablePluginBySpec(spec *Spec) (ProvisionableVolumePlugin, error)","file":"pkg/volume/plugins.go","code":"// FindCreatablePluginBySpec fetches a persistent volume plugin by name. If\n// no plugin is found, returns error.\nfunc (pm *VolumePluginMgr) FindCreatablePluginBySpec(spec *Spec) (ProvisionableVolumePlugin, error) {\n\tvolumePlugin, err := pm.FindPluginBySpec(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif provisionableVolumePlugin, ok := volumePlugin.(ProvisionableVolumePlugin); ok {\n\t\treturn provisionableVolumePlugin, nil\n\t}\n\treturn nil, fmt.Errorf(\"no creatable volume plugin matched\")\n}","line":{"from":860,"to":871}} {"id":100012645,"name":"FindAttachablePluginBySpec","signature":"func (pm *VolumePluginMgr) FindAttachablePluginBySpec(spec *Spec) (AttachableVolumePlugin, error)","file":"pkg/volume/plugins.go","code":"// FindAttachablePluginBySpec fetches a persistent volume plugin by spec.\n// Unlike the other \"FindPlugin\" methods, this does not return error if no\n// plugin is found. All volumes require a mounter and unmounter, but not\n// every volume will have an attacher/detacher.\nfunc (pm *VolumePluginMgr) FindAttachablePluginBySpec(spec *Spec) (AttachableVolumePlugin, error) {\n\tvolumePlugin, err := pm.FindPluginBySpec(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif attachableVolumePlugin, ok := volumePlugin.(AttachableVolumePlugin); ok {\n\t\tif canAttach, err := attachableVolumePlugin.CanAttach(spec); err != nil {\n\t\t\treturn nil, err\n\t\t} else if canAttach {\n\t\t\treturn attachableVolumePlugin, nil\n\t\t}\n\t}\n\treturn nil, nil\n}","line":{"from":873,"to":890}} {"id":100012646,"name":"FindAttachablePluginByName","signature":"func (pm *VolumePluginMgr) FindAttachablePluginByName(name string) (AttachableVolumePlugin, error)","file":"pkg/volume/plugins.go","code":"// FindAttachablePluginByName fetches an attachable volume plugin by name.\n// Unlike the other \"FindPlugin\" methods, this does not return error if no\n// plugin is found. All volumes require a mounter and unmounter, but not\n// every volume will have an attacher/detacher.\nfunc (pm *VolumePluginMgr) FindAttachablePluginByName(name string) (AttachableVolumePlugin, error) {\n\tvolumePlugin, err := pm.FindPluginByName(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif attachablePlugin, ok := volumePlugin.(AttachableVolumePlugin); ok {\n\t\treturn attachablePlugin, nil\n\t}\n\treturn nil, nil\n}","line":{"from":892,"to":905}} {"id":100012647,"name":"FindDeviceMountablePluginBySpec","signature":"func (pm *VolumePluginMgr) FindDeviceMountablePluginBySpec(spec *Spec) (DeviceMountableVolumePlugin, error)","file":"pkg/volume/plugins.go","code":"// FindDeviceMountablePluginBySpec fetches a persistent volume plugin by spec.\nfunc (pm *VolumePluginMgr) FindDeviceMountablePluginBySpec(spec *Spec) (DeviceMountableVolumePlugin, error) {\n\tvolumePlugin, err := pm.FindPluginBySpec(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif deviceMountableVolumePlugin, ok := volumePlugin.(DeviceMountableVolumePlugin); ok {\n\t\tif canMount, err := deviceMountableVolumePlugin.CanDeviceMount(spec); err != nil {\n\t\t\treturn nil, err\n\t\t} else if canMount {\n\t\t\treturn deviceMountableVolumePlugin, nil\n\t\t}\n\t}\n\treturn nil, nil\n}","line":{"from":907,"to":921}} {"id":100012648,"name":"FindDeviceMountablePluginByName","signature":"func (pm *VolumePluginMgr) FindDeviceMountablePluginByName(name string) (DeviceMountableVolumePlugin, error)","file":"pkg/volume/plugins.go","code":"// FindDeviceMountablePluginByName fetches a devicemountable volume plugin by name.\nfunc (pm *VolumePluginMgr) FindDeviceMountablePluginByName(name string) (DeviceMountableVolumePlugin, error) {\n\tvolumePlugin, err := pm.FindPluginByName(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif deviceMountableVolumePlugin, ok := volumePlugin.(DeviceMountableVolumePlugin); ok {\n\t\treturn deviceMountableVolumePlugin, nil\n\t}\n\treturn nil, nil\n}","line":{"from":923,"to":933}} {"id":100012649,"name":"FindExpandablePluginBySpec","signature":"func (pm *VolumePluginMgr) FindExpandablePluginBySpec(spec *Spec) (ExpandableVolumePlugin, error)","file":"pkg/volume/plugins.go","code":"// FindExpandablePluginBySpec fetches a persistent volume plugin by spec.\nfunc (pm *VolumePluginMgr) FindExpandablePluginBySpec(spec *Spec) (ExpandableVolumePlugin, error) {\n\tvolumePlugin, err := pm.FindPluginBySpec(spec)\n\tif err != nil {\n\t\tif spec.IsKubeletExpandable() {\n\t\t\t// for kubelet expandable volumes, return a noop plugin that\n\t\t\t// returns success for expand on the controller\n\t\t\tklog.V(4).InfoS(\"FindExpandablePluginBySpec -\u003e returning noopExpandableVolumePluginInstance\", \"specName\", spec.Name())\n\t\t\treturn \u0026noopExpandableVolumePluginInstance{spec}, nil\n\t\t}\n\t\tklog.V(4).InfoS(\"FindExpandablePluginBySpec -\u003e err\", \"specName\", spec.Name(), \"err\", err)\n\t\treturn nil, err\n\t}\n\n\tif expandableVolumePlugin, ok := volumePlugin.(ExpandableVolumePlugin); ok {\n\t\treturn expandableVolumePlugin, nil\n\t}\n\treturn nil, nil\n}","line":{"from":935,"to":953}} {"id":100012650,"name":"FindExpandablePluginByName","signature":"func (pm *VolumePluginMgr) FindExpandablePluginByName(name string) (ExpandableVolumePlugin, error)","file":"pkg/volume/plugins.go","code":"// FindExpandablePluginBySpec fetches a persistent volume plugin by name.\nfunc (pm *VolumePluginMgr) FindExpandablePluginByName(name string) (ExpandableVolumePlugin, error) {\n\tvolumePlugin, err := pm.FindPluginByName(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif expandableVolumePlugin, ok := volumePlugin.(ExpandableVolumePlugin); ok {\n\t\treturn expandableVolumePlugin, nil\n\t}\n\treturn nil, nil\n}","line":{"from":955,"to":966}} {"id":100012651,"name":"FindMapperPluginBySpec","signature":"func (pm *VolumePluginMgr) FindMapperPluginBySpec(spec *Spec) (BlockVolumePlugin, error)","file":"pkg/volume/plugins.go","code":"// FindMapperPluginBySpec fetches a block volume plugin by spec.\nfunc (pm *VolumePluginMgr) FindMapperPluginBySpec(spec *Spec) (BlockVolumePlugin, error) {\n\tvolumePlugin, err := pm.FindPluginBySpec(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif blockVolumePlugin, ok := volumePlugin.(BlockVolumePlugin); ok {\n\t\treturn blockVolumePlugin, nil\n\t}\n\treturn nil, nil\n}","line":{"from":968,"to":979}} {"id":100012652,"name":"FindMapperPluginByName","signature":"func (pm *VolumePluginMgr) FindMapperPluginByName(name string) (BlockVolumePlugin, error)","file":"pkg/volume/plugins.go","code":"// FindMapperPluginByName fetches a block volume plugin by name.\nfunc (pm *VolumePluginMgr) FindMapperPluginByName(name string) (BlockVolumePlugin, error) {\n\tvolumePlugin, err := pm.FindPluginByName(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif blockVolumePlugin, ok := volumePlugin.(BlockVolumePlugin); ok {\n\t\treturn blockVolumePlugin, nil\n\t}\n\treturn nil, nil\n}","line":{"from":981,"to":992}} {"id":100012653,"name":"FindNodeExpandablePluginBySpec","signature":"func (pm *VolumePluginMgr) FindNodeExpandablePluginBySpec(spec *Spec) (NodeExpandableVolumePlugin, error)","file":"pkg/volume/plugins.go","code":"// FindNodeExpandablePluginBySpec fetches a persistent volume plugin by spec\nfunc (pm *VolumePluginMgr) FindNodeExpandablePluginBySpec(spec *Spec) (NodeExpandableVolumePlugin, error) {\n\tvolumePlugin, err := pm.FindPluginBySpec(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif fsResizablePlugin, ok := volumePlugin.(NodeExpandableVolumePlugin); ok {\n\t\treturn fsResizablePlugin, nil\n\t}\n\treturn nil, nil\n}","line":{"from":994,"to":1004}} {"id":100012654,"name":"FindNodeExpandablePluginByName","signature":"func (pm *VolumePluginMgr) FindNodeExpandablePluginByName(name string) (NodeExpandableVolumePlugin, error)","file":"pkg/volume/plugins.go","code":"// FindNodeExpandablePluginByName fetches a persistent volume plugin by name\nfunc (pm *VolumePluginMgr) FindNodeExpandablePluginByName(name string) (NodeExpandableVolumePlugin, error) {\n\tvolumePlugin, err := pm.FindPluginByName(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif fsResizablePlugin, ok := volumePlugin.(NodeExpandableVolumePlugin); ok {\n\t\treturn fsResizablePlugin, nil\n\t}\n\n\treturn nil, nil\n}","line":{"from":1006,"to":1018}} {"id":100012655,"name":"Run","signature":"func (pm *VolumePluginMgr) Run(stopCh \u003c-chan struct{})","file":"pkg/volume/plugins.go","code":"func (pm *VolumePluginMgr) Run(stopCh \u003c-chan struct{}) {\n\tkletHost, ok := pm.Host.(KubeletVolumeHost)\n\tif ok {\n\t\t// start informer for CSIDriver\n\t\tinformerFactory := kletHost.GetInformerFactory()\n\t\tinformerFactory.Start(stopCh)\n\t\tinformerFactory.WaitForCacheSync(stopCh)\n\t}\n}","line":{"from":1020,"to":1028}} {"id":100012656,"name":"NewPersistentVolumeRecyclerPodTemplate","signature":"func NewPersistentVolumeRecyclerPodTemplate() *v1.Pod","file":"pkg/volume/plugins.go","code":"// NewPersistentVolumeRecyclerPodTemplate creates a template for a recycler\n// pod. By default, a recycler pod simply runs \"rm -rf\" on a volume and tests\n// for emptiness. Most attributes of the template will be correct for most\n// plugin implementations. The following attributes can be overridden per\n// plugin via configuration:\n//\n// 1. pod.Spec.Volumes[0].VolumeSource must be overridden. Recycler\n// implementations without a valid VolumeSource will fail.\n// 2. pod.GenerateName helps distinguish recycler pods by name. Recommended.\n// Default is \"pv-recycler-\".\n// 3. pod.Spec.ActiveDeadlineSeconds gives the recycler pod a maximum timeout\n// before failing. Recommended. Default is 60 seconds.\n//\n// See HostPath and NFS for working recycler examples\nfunc NewPersistentVolumeRecyclerPodTemplate() *v1.Pod {\n\ttimeout := int64(60)\n\tpod := \u0026v1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tGenerateName: \"pv-recycler-\",\n\t\t\tNamespace: metav1.NamespaceDefault,\n\t\t},\n\t\tSpec: v1.PodSpec{\n\t\t\tActiveDeadlineSeconds: \u0026timeout,\n\t\t\tRestartPolicy: v1.RestartPolicyNever,\n\t\t\tVolumes: []v1.Volume{\n\t\t\t\t{\n\t\t\t\t\tName: \"vol\",\n\t\t\t\t\t// IMPORTANT! All plugins using this template MUST\n\t\t\t\t\t// override pod.Spec.Volumes[0].VolumeSource Recycler\n\t\t\t\t\t// implementations without a valid VolumeSource will fail.\n\t\t\t\t\tVolumeSource: v1.VolumeSource{},\n\t\t\t\t},\n\t\t\t},\n\t\t\tContainers: []v1.Container{\n\t\t\t\t{\n\t\t\t\t\tName: \"pv-recycler\",\n\t\t\t\t\tImage: \"registry.k8s.io/debian-base:v2.0.0\",\n\t\t\t\t\tCommand: []string{\"/bin/sh\"},\n\t\t\t\t\tArgs: []string{\"-c\", \"test -e /scrub \u0026\u0026 rm -rf /scrub/..?* /scrub/.[!.]* /scrub/* \u0026\u0026 test -z \\\"$(ls -A /scrub)\\\" || exit 1\"},\n\t\t\t\t\tVolumeMounts: []v1.VolumeMount{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"vol\",\n\t\t\t\t\t\t\tMountPath: \"/scrub\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\treturn pod\n}","line":{"from":1030,"to":1080}} {"id":100012657,"name":"ValidateRecyclerPodTemplate","signature":"func ValidateRecyclerPodTemplate(pod *v1.Pod) error","file":"pkg/volume/plugins.go","code":"// Check validity of recycle pod template\n// List of checks:\n// - at least one volume is defined in the recycle pod template\n// If successful, returns nil\n// if unsuccessful, returns an error.\nfunc ValidateRecyclerPodTemplate(pod *v1.Pod) error {\n\tif len(pod.Spec.Volumes) \u003c 1 {\n\t\treturn fmt.Errorf(\"does not contain any volume(s)\")\n\t}\n\treturn nil\n}","line":{"from":1082,"to":1092}} {"id":100012658,"name":"Init","signature":"func (*dummyPluginProber) Init() error { return nil }","file":"pkg/volume/plugins.go","code":"func (*dummyPluginProber) Init() error { return nil }","line":{"from":1096,"to":1096}} {"id":100012659,"name":"Probe","signature":"func (*dummyPluginProber) Probe() ([]ProbeEvent, error) { return nil, nil }","file":"pkg/volume/plugins.go","code":"func (*dummyPluginProber) Probe() ([]ProbeEvent, error) { return nil, nil }","line":{"from":1097,"to":1097}} {"id":100012660,"name":"ProbeVolumePlugins","signature":"func ProbeVolumePlugins() []volume.VolumePlugin","file":"pkg/volume/portworx/portworx.go","code":"// ProbeVolumePlugins is the primary entrypoint for volume plugins.\nfunc ProbeVolumePlugins() []volume.VolumePlugin {\n\treturn []volume.VolumePlugin{\u0026portworxVolumePlugin{nil, nil}}\n}","line":{"from":45,"to":48}} {"id":100012661,"name":"getPath","signature":"func getPath(uid types.UID, volName string, host volume.VolumeHost) string","file":"pkg/volume/portworx/portworx.go","code":"func getPath(uid types.UID, volName string, host volume.VolumeHost) string {\n\treturn host.GetPodVolumeDir(uid, utilstrings.EscapeQualifiedName(portworxVolumePluginName), volName)\n}","line":{"from":65,"to":67}} {"id":100012662,"name":"IsMigratedToCSI","signature":"func (plugin *portworxVolumePlugin) IsMigratedToCSI() bool","file":"pkg/volume/portworx/portworx.go","code":"func (plugin *portworxVolumePlugin) IsMigratedToCSI() bool {\n\treturn utilfeature.DefaultFeatureGate.Enabled(features.CSIMigrationPortworx)\n}","line":{"from":69,"to":71}} {"id":100012663,"name":"Init","signature":"func (plugin *portworxVolumePlugin) Init(host volume.VolumeHost) error","file":"pkg/volume/portworx/portworx.go","code":"func (plugin *portworxVolumePlugin) Init(host volume.VolumeHost) error {\n\tclient, err := volumeclient.NewDriverClient(\n\t\tfmt.Sprintf(\"http://%s\", net.JoinHostPort(host.GetHostName(), strconv.Itoa(osdMgmtDefaultPort))),\n\t\tpxdDriverName, osdDriverVersion, pxDriverName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tplugin.host = host\n\tplugin.util = \u0026portworxVolumeUtil{\n\t\tportworxClient: client,\n\t}\n\n\treturn nil\n}","line":{"from":73,"to":87}} {"id":100012664,"name":"GetPluginName","signature":"func (plugin *portworxVolumePlugin) GetPluginName() string","file":"pkg/volume/portworx/portworx.go","code":"func (plugin *portworxVolumePlugin) GetPluginName() string {\n\treturn portworxVolumePluginName\n}","line":{"from":89,"to":91}} {"id":100012665,"name":"GetVolumeName","signature":"func (plugin *portworxVolumePlugin) GetVolumeName(spec *volume.Spec) (string, error)","file":"pkg/volume/portworx/portworx.go","code":"func (plugin *portworxVolumePlugin) GetVolumeName(spec *volume.Spec) (string, error) {\n\tvolumeSource, _, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn volumeSource.VolumeID, nil\n}","line":{"from":93,"to":100}} {"id":100012666,"name":"CanSupport","signature":"func (plugin *portworxVolumePlugin) CanSupport(spec *volume.Spec) bool","file":"pkg/volume/portworx/portworx.go","code":"func (plugin *portworxVolumePlugin) CanSupport(spec *volume.Spec) bool {\n\treturn (spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.PortworxVolume != nil) ||\n\t\t(spec.Volume != nil \u0026\u0026 spec.Volume.PortworxVolume != nil)\n}","line":{"from":102,"to":105}} {"id":100012667,"name":"RequiresRemount","signature":"func (plugin *portworxVolumePlugin) RequiresRemount(spec *volume.Spec) bool","file":"pkg/volume/portworx/portworx.go","code":"func (plugin *portworxVolumePlugin) RequiresRemount(spec *volume.Spec) bool {\n\treturn false\n}","line":{"from":107,"to":109}} {"id":100012668,"name":"GetAccessModes","signature":"func (plugin *portworxVolumePlugin) GetAccessModes() []v1.PersistentVolumeAccessMode","file":"pkg/volume/portworx/portworx.go","code":"func (plugin *portworxVolumePlugin) GetAccessModes() []v1.PersistentVolumeAccessMode {\n\treturn []v1.PersistentVolumeAccessMode{\n\t\tv1.ReadWriteOnce,\n\t\tv1.ReadWriteMany,\n\t}\n}","line":{"from":111,"to":116}} {"id":100012669,"name":"NewMounter","signature":"func (plugin *portworxVolumePlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error)","file":"pkg/volume/portworx/portworx.go","code":"func (plugin *portworxVolumePlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) {\n\treturn plugin.newMounterInternal(spec, pod.UID, plugin.util, plugin.host.GetMounter(plugin.GetPluginName()))\n}","line":{"from":118,"to":120}} {"id":100012670,"name":"newMounterInternal","signature":"func (plugin *portworxVolumePlugin) newMounterInternal(spec *volume.Spec, podUID types.UID, manager portworxManager, mounter mount.Interface) (volume.Mounter, error)","file":"pkg/volume/portworx/portworx.go","code":"func (plugin *portworxVolumePlugin) newMounterInternal(spec *volume.Spec, podUID types.UID, manager portworxManager, mounter mount.Interface) (volume.Mounter, error) {\n\tpwx, readOnly, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvolumeID := pwx.VolumeID\n\tfsType := pwx.FSType\n\n\treturn \u0026portworxVolumeMounter{\n\t\tportworxVolume: \u0026portworxVolume{\n\t\t\tpodUID: podUID,\n\t\t\tvolName: spec.Name(),\n\t\t\tvolumeID: volumeID,\n\t\t\tmanager: manager,\n\t\t\tmounter: mounter,\n\t\t\tplugin: plugin,\n\t\t\tMetricsProvider: volume.NewMetricsStatFS(getPath(podUID, spec.Name(), plugin.host)),\n\t\t},\n\t\tfsType: fsType,\n\t\treadOnly: readOnly,\n\t\tdiskMounter: util.NewSafeFormatAndMountFromHost(plugin.GetPluginName(), plugin.host)}, nil\n}","line":{"from":122,"to":144}} {"id":100012671,"name":"NewUnmounter","signature":"func (plugin *portworxVolumePlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error)","file":"pkg/volume/portworx/portworx.go","code":"func (plugin *portworxVolumePlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error) {\n\treturn plugin.newUnmounterInternal(volName, podUID, plugin.util, plugin.host.GetMounter(plugin.GetPluginName()))\n}","line":{"from":146,"to":148}} {"id":100012672,"name":"newUnmounterInternal","signature":"func (plugin *portworxVolumePlugin) newUnmounterInternal(volName string, podUID types.UID, manager portworxManager,","file":"pkg/volume/portworx/portworx.go","code":"func (plugin *portworxVolumePlugin) newUnmounterInternal(volName string, podUID types.UID, manager portworxManager,\n\tmounter mount.Interface) (volume.Unmounter, error) {\n\treturn \u0026portworxVolumeUnmounter{\n\t\t\u0026portworxVolume{\n\t\t\tpodUID: podUID,\n\t\t\tvolName: volName,\n\t\t\tmanager: manager,\n\t\t\tmounter: mounter,\n\t\t\tplugin: plugin,\n\t\t\tMetricsProvider: volume.NewMetricsStatFS(getPath(podUID, volName, plugin.host)),\n\t\t}}, nil\n}","line":{"from":150,"to":161}} {"id":100012673,"name":"NewDeleter","signature":"func (plugin *portworxVolumePlugin) NewDeleter(logger klog.Logger, spec *volume.Spec) (volume.Deleter, error)","file":"pkg/volume/portworx/portworx.go","code":"func (plugin *portworxVolumePlugin) NewDeleter(logger klog.Logger, spec *volume.Spec) (volume.Deleter, error) {\n\treturn plugin.newDeleterInternal(spec, plugin.util)\n}","line":{"from":163,"to":165}} {"id":100012674,"name":"newDeleterInternal","signature":"func (plugin *portworxVolumePlugin) newDeleterInternal(spec *volume.Spec, manager portworxManager) (volume.Deleter, error)","file":"pkg/volume/portworx/portworx.go","code":"func (plugin *portworxVolumePlugin) newDeleterInternal(spec *volume.Spec, manager portworxManager) (volume.Deleter, error) {\n\tif spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.PortworxVolume == nil {\n\t\treturn nil, fmt.Errorf(\"spec.PersistentVolumeSource.PortworxVolume is nil\")\n\t}\n\n\treturn \u0026portworxVolumeDeleter{\n\t\tportworxVolume: \u0026portworxVolume{\n\t\t\tvolName: spec.Name(),\n\t\t\tvolumeID: spec.PersistentVolume.Spec.PortworxVolume.VolumeID,\n\t\t\tmanager: manager,\n\t\t\tplugin: plugin,\n\t\t}}, nil\n}","line":{"from":167,"to":179}} {"id":100012675,"name":"NewProvisioner","signature":"func (plugin *portworxVolumePlugin) NewProvisioner(logger klog.Logger, options volume.VolumeOptions) (volume.Provisioner, error)","file":"pkg/volume/portworx/portworx.go","code":"func (plugin *portworxVolumePlugin) NewProvisioner(logger klog.Logger, options volume.VolumeOptions) (volume.Provisioner, error) {\n\treturn plugin.newProvisionerInternal(options, plugin.util)\n}","line":{"from":181,"to":183}} {"id":100012676,"name":"newProvisionerInternal","signature":"func (plugin *portworxVolumePlugin) newProvisionerInternal(options volume.VolumeOptions, manager portworxManager) (volume.Provisioner, error)","file":"pkg/volume/portworx/portworx.go","code":"func (plugin *portworxVolumePlugin) newProvisionerInternal(options volume.VolumeOptions, manager portworxManager) (volume.Provisioner, error) {\n\treturn \u0026portworxVolumeProvisioner{\n\t\tportworxVolume: \u0026portworxVolume{\n\t\t\tmanager: manager,\n\t\t\tplugin: plugin,\n\t\t},\n\t\toptions: options,\n\t}, nil\n}","line":{"from":185,"to":193}} {"id":100012677,"name":"RequiresFSResize","signature":"func (plugin *portworxVolumePlugin) RequiresFSResize() bool","file":"pkg/volume/portworx/portworx.go","code":"func (plugin *portworxVolumePlugin) RequiresFSResize() bool {\n\treturn false\n}","line":{"from":195,"to":197}} {"id":100012678,"name":"ExpandVolumeDevice","signature":"func (plugin *portworxVolumePlugin) ExpandVolumeDevice(","file":"pkg/volume/portworx/portworx.go","code":"func (plugin *portworxVolumePlugin) ExpandVolumeDevice(\n\tspec *volume.Spec,\n\tnewSize resource.Quantity,\n\toldSize resource.Quantity) (resource.Quantity, error) {\n\tklog.V(4).Infof(\"Expanding: %s from %v to %v\", spec.Name(), oldSize, newSize)\n\terr := plugin.util.ResizeVolume(spec, newSize, plugin.host)\n\tif err != nil {\n\t\treturn oldSize, err\n\t}\n\n\tklog.V(4).Infof(\"Successfully resized %s to %v\", spec.Name(), newSize)\n\treturn newSize, nil\n}","line":{"from":199,"to":211}} {"id":100012679,"name":"ConstructVolumeSpec","signature":"func (plugin *portworxVolumePlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error)","file":"pkg/volume/portworx/portworx.go","code":"func (plugin *portworxVolumePlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error) {\n\tportworxVolume := \u0026v1.Volume{\n\t\tName: volumeName,\n\t\tVolumeSource: v1.VolumeSource{\n\t\t\tPortworxVolume: \u0026v1.PortworxVolumeSource{\n\t\t\t\tVolumeID: volumeName,\n\t\t\t},\n\t\t},\n\t}\n\treturn volume.ReconstructedVolume{\n\t\tSpec: volume.NewSpecFromVolume(portworxVolume),\n\t}, nil\n}","line":{"from":213,"to":225}} {"id":100012680,"name":"SupportsMountOption","signature":"func (plugin *portworxVolumePlugin) SupportsMountOption() bool","file":"pkg/volume/portworx/portworx.go","code":"func (plugin *portworxVolumePlugin) SupportsMountOption() bool {\n\treturn false\n}","line":{"from":227,"to":229}} {"id":100012681,"name":"SupportsBulkVolumeVerification","signature":"func (plugin *portworxVolumePlugin) SupportsBulkVolumeVerification() bool","file":"pkg/volume/portworx/portworx.go","code":"func (plugin *portworxVolumePlugin) SupportsBulkVolumeVerification() bool {\n\treturn false\n}","line":{"from":231,"to":233}} {"id":100012682,"name":"SupportsSELinuxContextMount","signature":"func (plugin *portworxVolumePlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/portworx/portworx.go","code":"func (plugin *portworxVolumePlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error) {\n\treturn false, nil\n}","line":{"from":235,"to":237}} {"id":100012683,"name":"getVolumeSource","signature":"func getVolumeSource(","file":"pkg/volume/portworx/portworx.go","code":"func getVolumeSource(\n\tspec *volume.Spec) (*v1.PortworxVolumeSource, bool, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.PortworxVolume != nil {\n\t\treturn spec.Volume.PortworxVolume, spec.Volume.PortworxVolume.ReadOnly, nil\n\t} else if spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.PortworxVolume != nil {\n\t\treturn spec.PersistentVolume.Spec.PortworxVolume, spec.ReadOnly, nil\n\t}\n\n\treturn nil, false, fmt.Errorf(\"Spec does not reference a Portworx Volume type\")\n}","line":{"from":239,"to":249}} {"id":100012684,"name":"GetAttributes","signature":"func (b *portworxVolumeMounter) GetAttributes() volume.Attributes","file":"pkg/volume/portworx/portworx.go","code":"func (b *portworxVolumeMounter) GetAttributes() volume.Attributes {\n\treturn volume.Attributes{\n\t\tReadOnly: b.readOnly,\n\t\tManaged: !b.readOnly,\n\t\tSELinuxRelabel: false,\n\t}\n}","line":{"from":296,"to":302}} {"id":100012685,"name":"SetUp","signature":"func (b *portworxVolumeMounter) SetUp(mounterArgs volume.MounterArgs) error","file":"pkg/volume/portworx/portworx.go","code":"// SetUp attaches the disk and bind mounts to the volume path.\nfunc (b *portworxVolumeMounter) SetUp(mounterArgs volume.MounterArgs) error {\n\treturn b.SetUpAt(b.GetPath(), mounterArgs)\n}","line":{"from":304,"to":307}} {"id":100012686,"name":"SetUpAt","signature":"func (b *portworxVolumeMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error","file":"pkg/volume/portworx/portworx.go","code":"// SetUpAt attaches the disk and bind mounts to the volume path.\nfunc (b *portworxVolumeMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {\n\tnotMnt, err := b.mounter.IsLikelyNotMountPoint(dir)\n\tklog.Infof(\"Portworx Volume set up. Dir: %s %v %v\", dir, !notMnt, err)\n\tif err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\tklog.Errorf(\"Cannot validate mountpoint: %s\", dir)\n\t\treturn err\n\t}\n\tif !notMnt {\n\t\treturn nil\n\t}\n\n\tattachOptions := make(map[string]string)\n\tattachOptions[attachContextKey] = dir\n\tattachOptions[attachHostKey] = b.plugin.host.GetHostName()\n\tif _, err := b.manager.AttachVolume(b, attachOptions); err != nil {\n\t\treturn err\n\t}\n\n\tklog.V(4).Infof(\"Portworx Volume %s attached\", b.volumeID)\n\n\tif err := os.MkdirAll(dir, 0750); err != nil {\n\t\treturn err\n\t}\n\n\tif err := b.manager.MountVolume(b, dir); err != nil {\n\t\treturn err\n\t}\n\tif !b.readOnly {\n\t\tvolume.SetVolumeOwnership(b, dir, mounterArgs.FsGroup, mounterArgs.FSGroupChangePolicy, util.FSGroupCompleteHook(b.plugin, nil))\n\t}\n\tklog.Infof(\"Portworx Volume %s setup at %s\", b.volumeID, dir)\n\treturn nil\n}","line":{"from":309,"to":342}} {"id":100012687,"name":"GetPath","signature":"func (pwx *portworxVolume) GetPath() string","file":"pkg/volume/portworx/portworx.go","code":"func (pwx *portworxVolume) GetPath() string {\n\treturn getPath(pwx.podUID, pwx.volName, pwx.plugin.host)\n}","line":{"from":344,"to":346}} {"id":100012688,"name":"TearDown","signature":"func (c *portworxVolumeUnmounter) TearDown() error","file":"pkg/volume/portworx/portworx.go","code":"// Unmounts the bind mount, and detaches the disk only if the PD\n// resource was the last reference to that disk on the kubelet.\nfunc (c *portworxVolumeUnmounter) TearDown() error {\n\treturn c.TearDownAt(c.GetPath())\n}","line":{"from":354,"to":358}} {"id":100012689,"name":"TearDownAt","signature":"func (c *portworxVolumeUnmounter) TearDownAt(dir string) error","file":"pkg/volume/portworx/portworx.go","code":"// Unmounts the bind mount, and detaches the disk only if the PD\n// resource was the last reference to that disk on the kubelet.\nfunc (c *portworxVolumeUnmounter) TearDownAt(dir string) error {\n\tklog.Infof(\"Portworx Volume TearDown of %s\", dir)\n\n\tif err := c.manager.UnmountVolume(c, dir); err != nil {\n\t\treturn err\n\t}\n\n\t// Call Portworx Detach Volume.\n\tif err := c.manager.DetachVolume(c); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":360,"to":375}} {"id":100012690,"name":"GetPath","signature":"func (d *portworxVolumeDeleter) GetPath() string","file":"pkg/volume/portworx/portworx.go","code":"func (d *portworxVolumeDeleter) GetPath() string {\n\treturn getPath(d.podUID, d.volName, d.plugin.host)\n}","line":{"from":383,"to":385}} {"id":100012691,"name":"Delete","signature":"func (d *portworxVolumeDeleter) Delete() error","file":"pkg/volume/portworx/portworx.go","code":"func (d *portworxVolumeDeleter) Delete() error {\n\treturn d.manager.DeleteVolume(d)\n}","line":{"from":387,"to":389}} {"id":100012692,"name":"Provision","signature":"func (c *portworxVolumeProvisioner) Provision(selectedNode *v1.Node, allowedTopologies []v1.TopologySelectorTerm) (*v1.PersistentVolume, error)","file":"pkg/volume/portworx/portworx.go","code":"func (c *portworxVolumeProvisioner) Provision(selectedNode *v1.Node, allowedTopologies []v1.TopologySelectorTerm) (*v1.PersistentVolume, error) {\n\tif !util.ContainsAllAccessModes(c.plugin.GetAccessModes(), c.options.PVC.Spec.AccessModes) {\n\t\treturn nil, fmt.Errorf(\"invalid AccessModes %v: only AccessModes %v are supported\", c.options.PVC.Spec.AccessModes, c.plugin.GetAccessModes())\n\t}\n\n\tif util.CheckPersistentVolumeClaimModeBlock(c.options.PVC) {\n\t\treturn nil, fmt.Errorf(\"%s does not support block volume provisioning\", c.plugin.GetPluginName())\n\t}\n\n\tvolumeID, sizeGiB, labels, err := c.manager.CreateVolume(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpv := \u0026v1.PersistentVolume{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: c.options.PVName,\n\t\t\tLabels: map[string]string{},\n\t\t\tAnnotations: map[string]string{\n\t\t\t\tutil.VolumeDynamicallyCreatedByKey: \"portworx-volume-dynamic-provisioner\",\n\t\t\t},\n\t\t},\n\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\tPersistentVolumeReclaimPolicy: c.options.PersistentVolumeReclaimPolicy,\n\t\t\tAccessModes: c.options.PVC.Spec.AccessModes,\n\t\t\tCapacity: v1.ResourceList{\n\t\t\t\tv1.ResourceName(v1.ResourceStorage): resource.MustParse(fmt.Sprintf(\"%dGi\", sizeGiB)),\n\t\t\t},\n\t\t\tPersistentVolumeSource: v1.PersistentVolumeSource{\n\t\t\t\tPortworxVolume: \u0026v1.PortworxVolumeSource{\n\t\t\t\t\tVolumeID: volumeID,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tif len(labels) != 0 {\n\t\tif pv.Labels == nil {\n\t\t\tpv.Labels = make(map[string]string)\n\t\t}\n\t\tfor k, v := range labels {\n\t\t\tpv.Labels[k] = v\n\t\t}\n\t}\n\n\tif len(c.options.PVC.Spec.AccessModes) == 0 {\n\t\tpv.Spec.AccessModes = c.plugin.GetAccessModes()\n\t}\n\n\treturn pv, nil\n}","line":{"from":398,"to":448}} {"id":100012693,"name":"CreateVolume","signature":"func (util *portworxVolumeUtil) CreateVolume(p *portworxVolumeProvisioner) (string, int64, map[string]string, error)","file":"pkg/volume/portworx/portworx_util.go","code":"// CreateVolume creates a Portworx volume.\nfunc (util *portworxVolumeUtil) CreateVolume(p *portworxVolumeProvisioner) (string, int64, map[string]string, error) {\n\tdriver, err := util.getPortworxDriver(p.plugin.host)\n\tif err != nil || driver == nil {\n\t\tklog.Errorf(\"Failed to get portworx driver. Err: %v\", err)\n\t\treturn \"\", 0, nil, err\n\t}\n\n\tklog.Infof(\"Creating Portworx volume for PVC: %v\", p.options.PVC.Name)\n\n\tcapacity := p.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]\n\t// Portworx Volumes are specified in GiB\n\trequestGiB, err := volumehelpers.RoundUpToGiB(capacity)\n\tif err != nil {\n\t\treturn \"\", 0, nil, err\n\t}\n\n\t// Perform a best-effort parsing of parameters. Portworx 1.2.9 and later parses volume parameters from\n\t// spec.VolumeLabels. So even if below SpecFromOpts() fails to parse certain parameters or\n\t// doesn't support new parameters, the server-side processing will parse it correctly.\n\t// We still need to call SpecFromOpts() here to handle cases where someone is running Portworx 1.2.8 and lower.\n\tspecHandler := osdspec.NewSpecHandler()\n\tspec, locator, source, _ := specHandler.SpecFromOpts(p.options.Parameters)\n\tif spec == nil {\n\t\tspec = specHandler.DefaultSpec()\n\t}\n\n\t// Pass all parameters as volume labels for Portworx server-side processing\n\tif spec.VolumeLabels == nil {\n\t\tspec.VolumeLabels = make(map[string]string, 0)\n\t}\n\n\tfor k, v := range p.options.Parameters {\n\t\tspec.VolumeLabels[k] = v\n\t}\n\n\t// Update the requested size in the spec\n\tspec.Size = uint64(requestGiB * volumehelpers.GiB)\n\n\t// Change the Portworx Volume name to PV name\n\tif locator == nil {\n\t\tlocator = \u0026osdapi.VolumeLocator{\n\t\t\tVolumeLabels: make(map[string]string),\n\t\t}\n\t}\n\tlocator.Name = p.options.PVName\n\n\t// Add claim Name as a part of Portworx Volume Labels\n\tlocator.VolumeLabels[pvcClaimLabel] = p.options.PVC.Name\n\tlocator.VolumeLabels[pvcNamespaceLabel] = p.options.PVC.Namespace\n\n\tfor k, v := range p.options.PVC.Annotations {\n\t\tif _, present := spec.VolumeLabels[k]; present {\n\t\t\tklog.Warningf(\"not saving annotation: %s=%s in spec labels due to an existing key\", k, v)\n\t\t\tcontinue\n\t\t}\n\t\tspec.VolumeLabels[k] = v\n\t}\n\n\tvolumeID, err := driver.Create(locator, source, spec)\n\tif err != nil {\n\t\tklog.Errorf(\"Error creating Portworx Volume : %v\", err)\n\t\treturn \"\", 0, nil, err\n\t}\n\n\tklog.Infof(\"Successfully created Portworx volume for PVC: %v\", p.options.PVC.Name)\n\treturn volumeID, requestGiB, nil, err\n}","line":{"from":54,"to":121}} {"id":100012694,"name":"DeleteVolume","signature":"func (util *portworxVolumeUtil) DeleteVolume(d *portworxVolumeDeleter) error","file":"pkg/volume/portworx/portworx_util.go","code":"// DeleteVolume deletes a Portworx volume\nfunc (util *portworxVolumeUtil) DeleteVolume(d *portworxVolumeDeleter) error {\n\tdriver, err := util.getPortworxDriver(d.plugin.host)\n\tif err != nil || driver == nil {\n\t\tklog.Errorf(\"Failed to get portworx driver. Err: %v\", err)\n\t\treturn err\n\t}\n\n\terr = driver.Delete(d.volumeID)\n\tif err != nil {\n\t\tklog.Errorf(\"Error deleting Portworx Volume (%v): %v\", d.volName, err)\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":123,"to":137}} {"id":100012695,"name":"AttachVolume","signature":"func (util *portworxVolumeUtil) AttachVolume(m *portworxVolumeMounter, attachOptions map[string]string) (string, error)","file":"pkg/volume/portworx/portworx_util.go","code":"// AttachVolume attaches a Portworx Volume\nfunc (util *portworxVolumeUtil) AttachVolume(m *portworxVolumeMounter, attachOptions map[string]string) (string, error) {\n\tdriver, err := util.getLocalPortworxDriver(m.plugin.host)\n\tif err != nil || driver == nil {\n\t\tklog.Errorf(\"Failed to get portworx driver. Err: %v\", err)\n\t\treturn \"\", err\n\t}\n\n\tdevicePath, err := driver.Attach(m.volName, attachOptions)\n\tif err != nil {\n\t\tklog.Errorf(\"Error attaching Portworx Volume (%v): %v\", m.volName, err)\n\t\treturn \"\", err\n\t}\n\treturn devicePath, nil\n}","line":{"from":139,"to":153}} {"id":100012696,"name":"DetachVolume","signature":"func (util *portworxVolumeUtil) DetachVolume(u *portworxVolumeUnmounter) error","file":"pkg/volume/portworx/portworx_util.go","code":"// DetachVolume detaches a Portworx Volume\nfunc (util *portworxVolumeUtil) DetachVolume(u *portworxVolumeUnmounter) error {\n\tdriver, err := util.getLocalPortworxDriver(u.plugin.host)\n\tif err != nil || driver == nil {\n\t\tklog.Errorf(\"Failed to get portworx driver. Err: %v\", err)\n\t\treturn err\n\t}\n\n\terr = driver.Detach(u.volName, false /*doNotForceDetach*/)\n\tif err != nil {\n\t\tklog.Errorf(\"Error detaching Portworx Volume (%v): %v\", u.volName, err)\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":155,"to":169}} {"id":100012697,"name":"MountVolume","signature":"func (util *portworxVolumeUtil) MountVolume(m *portworxVolumeMounter, mountPath string) error","file":"pkg/volume/portworx/portworx_util.go","code":"// MountVolume mounts a Portworx Volume on the specified mountPath\nfunc (util *portworxVolumeUtil) MountVolume(m *portworxVolumeMounter, mountPath string) error {\n\tdriver, err := util.getLocalPortworxDriver(m.plugin.host)\n\tif err != nil || driver == nil {\n\t\tklog.Errorf(\"Failed to get portworx driver. Err: %v\", err)\n\t\treturn err\n\t}\n\n\terr = driver.Mount(m.volName, mountPath)\n\tif err != nil {\n\t\tklog.Errorf(\"Error mounting Portworx Volume (%v) on Path (%v): %v\", m.volName, mountPath, err)\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":171,"to":185}} {"id":100012698,"name":"UnmountVolume","signature":"func (util *portworxVolumeUtil) UnmountVolume(u *portworxVolumeUnmounter, mountPath string) error","file":"pkg/volume/portworx/portworx_util.go","code":"// UnmountVolume unmounts a Portworx Volume\nfunc (util *portworxVolumeUtil) UnmountVolume(u *portworxVolumeUnmounter, mountPath string) error {\n\tdriver, err := util.getLocalPortworxDriver(u.plugin.host)\n\tif err != nil || driver == nil {\n\t\tklog.Errorf(\"Failed to get portworx driver. Err: %v\", err)\n\t\treturn err\n\t}\n\n\terr = driver.Unmount(u.volName, mountPath)\n\tif err != nil {\n\t\tklog.Errorf(\"Error unmounting Portworx Volume (%v) on Path (%v): %v\", u.volName, mountPath, err)\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":187,"to":201}} {"id":100012699,"name":"ResizeVolume","signature":"func (util *portworxVolumeUtil) ResizeVolume(spec *volume.Spec, newSize resource.Quantity, volumeHost volume.VolumeHost) error","file":"pkg/volume/portworx/portworx_util.go","code":"func (util *portworxVolumeUtil) ResizeVolume(spec *volume.Spec, newSize resource.Quantity, volumeHost volume.VolumeHost) error {\n\tdriver, err := util.getPortworxDriver(volumeHost)\n\tif err != nil || driver == nil {\n\t\tklog.Errorf(\"Failed to get portworx driver. Err: %v\", err)\n\t\treturn err\n\t}\n\n\tvols, err := driver.Inspect([]string{spec.Name()})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(vols) != 1 {\n\t\treturn fmt.Errorf(\"failed to inspect Portworx volume: %s. Found: %d volumes\", spec.Name(), len(vols))\n\t}\n\n\tvol := vols[0]\n\ttBytes, err := volumehelpers.RoundUpToB(newSize)\n\tif err != nil {\n\t\treturn err\n\t}\n\tnewSizeInBytes := uint64(tBytes)\n\tif vol.Spec.Size \u003e= newSizeInBytes {\n\t\tklog.Infof(\"Portworx volume: %s already at size: %d greater than or equal to new \"+\n\t\t\t\"requested size: %d. Skipping resize.\", spec.Name(), vol.Spec.Size, newSizeInBytes)\n\t\treturn nil\n\t}\n\n\tvol.Spec.Size = newSizeInBytes\n\terr = driver.Set(spec.Name(), vol.Locator, vol.Spec)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// check if the volume's size actually got updated\n\tvols, err = driver.Inspect([]string{spec.Name()})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(vols) != 1 {\n\t\treturn fmt.Errorf(\"failed to inspect resized Portworx volume: %s. Found: %d volumes\", spec.Name(), len(vols))\n\t}\n\n\tupdatedVol := vols[0]\n\tif updatedVol.Spec.Size \u003c vol.Spec.Size {\n\t\treturn fmt.Errorf(\"Portworx volume: %s doesn't match expected size after resize. expected:%v actual:%v\",\n\t\t\tspec.Name(), vol.Spec.Size, updatedVol.Spec.Size)\n\t}\n\n\treturn nil\n}","line":{"from":203,"to":254}} {"id":100012700,"name":"isClientValid","signature":"func isClientValid(client *osdclient.Client) (bool, error)","file":"pkg/volume/portworx/portworx_util.go","code":"func isClientValid(client *osdclient.Client) (bool, error) {\n\tif client == nil {\n\t\treturn false, nil\n\t}\n\n\t_, err := client.Versions(osdapi.OsdVolumePath)\n\tif err != nil {\n\t\tklog.Errorf(\"portworx client failed driver versions check. Err: %v\", err)\n\t\treturn false, err\n\t}\n\n\treturn true, nil\n}","line":{"from":256,"to":268}} {"id":100012701,"name":"createDriverClient","signature":"func createDriverClient(hostname string, port int32) (*osdclient.Client, error)","file":"pkg/volume/portworx/portworx_util.go","code":"func createDriverClient(hostname string, port int32) (*osdclient.Client, error) {\n\tclient, err := volumeclient.NewDriverClient(fmt.Sprintf(\"http://%s\", net.JoinHostPort(hostname, strconv.Itoa(int(port)))),\n\t\tpxdDriverName, osdDriverVersion, pxDriverName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tisValid, err := isClientValid(client)\n\tif isValid {\n\t\treturn client, nil\n\t}\n\treturn nil, err\n}","line":{"from":270,"to":282}} {"id":100012702,"name":"getPortworxDriver","signature":"func (util *portworxVolumeUtil) getPortworxDriver(volumeHost volume.VolumeHost) (volumeapi.VolumeDriver, error)","file":"pkg/volume/portworx/portworx_util.go","code":"// getPortworxDriver returns a Portworx volume driver which can be used for cluster wide operations.\n//\n//\tOperations like create and delete volume don't need to be restricted to local volume host since\n//\tany node in the Portworx cluster can coordinate the create/delete request and forward the operations to\n//\tthe Portworx node that will own/owns the data.\nfunc (util *portworxVolumeUtil) getPortworxDriver(volumeHost volume.VolumeHost) (volumeapi.VolumeDriver, error) {\n\t// check if existing saved client is valid\n\tif isValid, _ := isClientValid(util.portworxClient); isValid {\n\t\treturn volumeclient.VolumeDriver(util.portworxClient), nil\n\t}\n\n\t// create new client\n\tvar err error\n\tutil.portworxClient, err = createDriverClient(volumeHost.GetHostName(), osdMgmtDefaultPort) // for backward compatibility\n\tif err != nil || util.portworxClient == nil {\n\t\t// Create client from portworx k8s service.\n\t\tsvc, err := getPortworxService(volumeHost)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// The port here is always the default one since it's the service port\n\t\tutil.portworxClient, err = createDriverClient(svc.Spec.ClusterIP, osdMgmtDefaultPort)\n\t\tif err != nil || util.portworxClient == nil {\n\t\t\tklog.Errorf(\"Failed to connect to portworx service. Err: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\tklog.Infof(\"Using portworx cluster service at: %v:%d as api endpoint\",\n\t\t\tsvc.Spec.ClusterIP, osdMgmtDefaultPort)\n\t} else {\n\t\tklog.Infof(\"Using portworx service at: %v:%d as api endpoint\",\n\t\t\tvolumeHost.GetHostName(), osdMgmtDefaultPort)\n\t}\n\n\treturn volumeclient.VolumeDriver(util.portworxClient), nil\n}","line":{"from":284,"to":320}} {"id":100012703,"name":"getLocalPortworxDriver","signature":"func (util *portworxVolumeUtil) getLocalPortworxDriver(volumeHost volume.VolumeHost) (volumeapi.VolumeDriver, error)","file":"pkg/volume/portworx/portworx_util.go","code":"// getLocalPortworxDriver returns driver connected to Portworx API server on volume host.\n//\n//\tThis is required to force certain operations (mount, unmount, detach, attach) to\n//\tgo to the volume host instead of the k8s service which might route it to any host. This pertains to how\n//\tPortworx mounts and attaches a volume to the running container. The node getting these requests needs to\n//\tsee the pod container mounts (specifically /var/lib/kubelet/pods/\u003cpod_id\u003e)\nfunc (util *portworxVolumeUtil) getLocalPortworxDriver(volumeHost volume.VolumeHost) (volumeapi.VolumeDriver, error) {\n\tif util.portworxClient != nil {\n\t\t// check if existing saved client is valid\n\t\tif isValid, _ := isClientValid(util.portworxClient); isValid {\n\t\t\treturn volumeclient.VolumeDriver(util.portworxClient), nil\n\t\t}\n\t}\n\n\t// Lookup port\n\tsvc, err := getPortworxService(volumeHost)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tosgMgmtPort := lookupPXAPIPortFromService(svc)\n\tutil.portworxClient, err = createDriverClient(volumeHost.GetHostName(), osgMgmtPort)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tklog.Infof(\"Using portworx local service at: %v:%d as api endpoint\",\n\t\tvolumeHost.GetHostName(), osgMgmtPort)\n\treturn volumeclient.VolumeDriver(util.portworxClient), nil\n}","line":{"from":322,"to":351}} {"id":100012704,"name":"lookupPXAPIPortFromService","signature":"func lookupPXAPIPortFromService(svc *v1.Service) int32","file":"pkg/volume/portworx/portworx_util.go","code":"// lookupPXAPIPortFromService goes over all the ports in the given service and returns the target\n// port for osdMgmtDefaultPort\nfunc lookupPXAPIPortFromService(svc *v1.Service) int32 {\n\tfor _, p := range svc.Spec.Ports {\n\t\tif p.Port == osdMgmtDefaultPort {\n\t\t\treturn p.TargetPort.IntVal\n\t\t}\n\t}\n\treturn osdMgmtDefaultPort // default\n}","line":{"from":353,"to":362}} {"id":100012705,"name":"getPortworxService","signature":"func getPortworxService(host volume.VolumeHost) (*v1.Service, error)","file":"pkg/volume/portworx/portworx_util.go","code":"// getPortworxService returns the portworx cluster service from the API server\nfunc getPortworxService(host volume.VolumeHost) (*v1.Service, error) {\n\tkubeClient := host.GetKubeClient()\n\tif kubeClient == nil {\n\t\terr := fmt.Errorf(\"failed to get kubeclient when creating portworx client\")\n\t\tklog.Errorf(err.Error())\n\t\treturn nil, err\n\t}\n\n\topts := metav1.GetOptions{}\n\tsvc, err := kubeClient.CoreV1().Services(api.NamespaceSystem).Get(context.TODO(), pxServiceName, opts)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get service. Err: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tif svc == nil {\n\t\terr = fmt.Errorf(\"service: %v not found. Consult Portworx docs to deploy it\", pxServiceName)\n\t\tklog.Errorf(err.Error())\n\t\treturn nil, err\n\t}\n\n\treturn svc, nil\n}","line":{"from":364,"to":387}} {"id":100012706,"name":"ProbeVolumePlugins","signature":"func ProbeVolumePlugins() []volume.VolumePlugin","file":"pkg/volume/projected/projected.go","code":"// ProbeVolumePlugins is the entry point for plugin detection in a package.\nfunc ProbeVolumePlugins() []volume.VolumePlugin {\n\treturn []volume.VolumePlugin{\u0026projectedPlugin{}}\n}","line":{"from":37,"to":40}} {"id":100012707,"name":"wrappedVolumeSpec","signature":"func wrappedVolumeSpec() volume.Spec","file":"pkg/volume/projected/projected.go","code":"func wrappedVolumeSpec() volume.Spec {\n\treturn volume.Spec{\n\t\tVolume: \u0026v1.Volume{\n\t\t\tVolumeSource: v1.VolumeSource{\n\t\t\t\tEmptyDir: \u0026v1.EmptyDirVolumeSource{Medium: v1.StorageMediumMemory},\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":56,"to":64}} {"id":100012708,"name":"getPath","signature":"func getPath(uid types.UID, volName string, host volume.VolumeHost) string","file":"pkg/volume/projected/projected.go","code":"func getPath(uid types.UID, volName string, host volume.VolumeHost) string {\n\treturn host.GetPodVolumeDir(uid, utilstrings.EscapeQualifiedName(projectedPluginName), volName)\n}","line":{"from":66,"to":68}} {"id":100012709,"name":"Init","signature":"func (plugin *projectedPlugin) Init(host volume.VolumeHost) error","file":"pkg/volume/projected/projected.go","code":"func (plugin *projectedPlugin) Init(host volume.VolumeHost) error {\n\tplugin.host = host\n\tplugin.getSecret = host.GetSecretFunc()\n\tplugin.getConfigMap = host.GetConfigMapFunc()\n\tplugin.getServiceAccountToken = host.GetServiceAccountTokenFunc()\n\tplugin.deleteServiceAccountToken = host.DeleteServiceAccountTokenFunc()\n\treturn nil\n}","line":{"from":70,"to":77}} {"id":100012710,"name":"GetPluginName","signature":"func (plugin *projectedPlugin) GetPluginName() string","file":"pkg/volume/projected/projected.go","code":"func (plugin *projectedPlugin) GetPluginName() string {\n\treturn projectedPluginName\n}","line":{"from":79,"to":81}} {"id":100012711,"name":"GetVolumeName","signature":"func (plugin *projectedPlugin) GetVolumeName(spec *volume.Spec) (string, error)","file":"pkg/volume/projected/projected.go","code":"func (plugin *projectedPlugin) GetVolumeName(spec *volume.Spec) (string, error) {\n\t_, _, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn spec.Name(), nil\n}","line":{"from":83,"to":90}} {"id":100012712,"name":"CanSupport","signature":"func (plugin *projectedPlugin) CanSupport(spec *volume.Spec) bool","file":"pkg/volume/projected/projected.go","code":"func (plugin *projectedPlugin) CanSupport(spec *volume.Spec) bool {\n\treturn spec.Volume != nil \u0026\u0026 spec.Volume.Projected != nil\n}","line":{"from":92,"to":94}} {"id":100012713,"name":"RequiresRemount","signature":"func (plugin *projectedPlugin) RequiresRemount(spec *volume.Spec) bool","file":"pkg/volume/projected/projected.go","code":"func (plugin *projectedPlugin) RequiresRemount(spec *volume.Spec) bool {\n\treturn true\n}","line":{"from":96,"to":98}} {"id":100012714,"name":"SupportsMountOption","signature":"func (plugin *projectedPlugin) SupportsMountOption() bool","file":"pkg/volume/projected/projected.go","code":"func (plugin *projectedPlugin) SupportsMountOption() bool {\n\treturn false\n}","line":{"from":100,"to":102}} {"id":100012715,"name":"SupportsBulkVolumeVerification","signature":"func (plugin *projectedPlugin) SupportsBulkVolumeVerification() bool","file":"pkg/volume/projected/projected.go","code":"func (plugin *projectedPlugin) SupportsBulkVolumeVerification() bool {\n\treturn false\n}","line":{"from":104,"to":106}} {"id":100012716,"name":"SupportsSELinuxContextMount","signature":"func (plugin *projectedPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/projected/projected.go","code":"func (plugin *projectedPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error) {\n\treturn false, nil\n}","line":{"from":108,"to":110}} {"id":100012717,"name":"NewMounter","signature":"func (plugin *projectedPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error)","file":"pkg/volume/projected/projected.go","code":"func (plugin *projectedPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error) {\n\treturn \u0026projectedVolumeMounter{\n\t\tprojectedVolume: \u0026projectedVolume{\n\t\t\tvolName: spec.Name(),\n\t\t\tsources: spec.Volume.Projected.Sources,\n\t\t\tpodUID: pod.UID,\n\t\t\tplugin: plugin,\n\t\t\tMetricsProvider: volume.NewCachedMetrics(volume.NewMetricsDu(getPath(pod.UID, spec.Name(), plugin.host))),\n\t\t},\n\t\tsource: *spec.Volume.Projected,\n\t\tpod: pod,\n\t\topts: \u0026opts,\n\t}, nil\n}","line":{"from":112,"to":125}} {"id":100012718,"name":"NewUnmounter","signature":"func (plugin *projectedPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error)","file":"pkg/volume/projected/projected.go","code":"func (plugin *projectedPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error) {\n\treturn \u0026projectedVolumeUnmounter{\n\t\t\u0026projectedVolume{\n\t\t\tvolName: volName,\n\t\t\tpodUID: podUID,\n\t\t\tplugin: plugin,\n\t\t\tMetricsProvider: volume.NewCachedMetrics(volume.NewMetricsDu(getPath(podUID, volName, plugin.host))),\n\t\t},\n\t}, nil\n}","line":{"from":127,"to":136}} {"id":100012719,"name":"ConstructVolumeSpec","signature":"func (plugin *projectedPlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error)","file":"pkg/volume/projected/projected.go","code":"func (plugin *projectedPlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error) {\n\tprojectedVolume := \u0026v1.Volume{\n\t\tName: volumeName,\n\t\tVolumeSource: v1.VolumeSource{\n\t\t\tProjected: \u0026v1.ProjectedVolumeSource{},\n\t\t},\n\t}\n\n\treturn volume.ReconstructedVolume{\n\t\tSpec: volume.NewSpecFromVolume(projectedVolume),\n\t}, nil\n}","line":{"from":138,"to":149}} {"id":100012720,"name":"GetPath","signature":"func (sv *projectedVolume) GetPath() string","file":"pkg/volume/projected/projected.go","code":"func (sv *projectedVolume) GetPath() string {\n\treturn getPath(sv.podUID, sv.volName, sv.plugin.host)\n}","line":{"from":161,"to":163}} {"id":100012721,"name":"GetAttributes","signature":"func (sv *projectedVolume) GetAttributes() volume.Attributes","file":"pkg/volume/projected/projected.go","code":"func (sv *projectedVolume) GetAttributes() volume.Attributes {\n\treturn volume.Attributes{\n\t\tReadOnly: true,\n\t\tManaged: true,\n\t\tSELinuxRelabel: true,\n\t}\n\n}","line":{"from":175,"to":182}} {"id":100012722,"name":"SetUp","signature":"func (s *projectedVolumeMounter) SetUp(mounterArgs volume.MounterArgs) error","file":"pkg/volume/projected/projected.go","code":"func (s *projectedVolumeMounter) SetUp(mounterArgs volume.MounterArgs) error {\n\treturn s.SetUpAt(s.GetPath(), mounterArgs)\n}","line":{"from":184,"to":186}} {"id":100012723,"name":"SetUpAt","signature":"func (s *projectedVolumeMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error","file":"pkg/volume/projected/projected.go","code":"func (s *projectedVolumeMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {\n\tklog.V(3).Infof(\"Setting up volume %v for pod %v at %v\", s.volName, s.pod.UID, dir)\n\n\twrapped, err := s.plugin.host.NewWrapperMounter(s.volName, wrappedVolumeSpec(), s.pod, *s.opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdata, err := s.collectData(mounterArgs)\n\tif err != nil {\n\t\tklog.Errorf(\"Error preparing data for projected volume %v for pod %v/%v: %s\", s.volName, s.pod.Namespace, s.pod.Name, err.Error())\n\t\treturn err\n\t}\n\n\tsetupSuccess := false\n\tif err := wrapped.SetUpAt(dir, mounterArgs); err != nil {\n\t\treturn err\n\t}\n\n\tif err := volumeutil.MakeNestedMountpoints(s.volName, dir, *s.pod); err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\t// Clean up directories if setup fails\n\t\tif !setupSuccess {\n\t\t\tunmounter, unmountCreateErr := s.plugin.NewUnmounter(s.volName, s.podUID)\n\t\t\tif unmountCreateErr != nil {\n\t\t\t\tklog.Errorf(\"error cleaning up mount %s after failure. Create unmounter failed with %v\", s.volName, unmountCreateErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\ttearDownErr := unmounter.TearDown()\n\t\t\tif tearDownErr != nil {\n\t\t\t\tklog.Errorf(\"error tearing down volume %s with : %v\", s.volName, tearDownErr)\n\t\t\t}\n\t\t}\n\t}()\n\n\twriterContext := fmt.Sprintf(\"pod %v/%v volume %v\", s.pod.Namespace, s.pod.Name, s.volName)\n\twriter, err := volumeutil.NewAtomicWriter(dir, writerContext)\n\tif err != nil {\n\t\tklog.Errorf(\"Error creating atomic writer: %v\", err)\n\t\treturn err\n\t}\n\n\tsetPerms := func(_ string) error {\n\t\t// This may be the first time writing and new files get created outside the timestamp subdirectory:\n\t\t// change the permissions on the whole volume and not only in the timestamp directory.\n\t\treturn volume.SetVolumeOwnership(s, dir, mounterArgs.FsGroup, nil /*fsGroupChangePolicy*/, volumeutil.FSGroupCompleteHook(s.plugin, nil))\n\t}\n\terr = writer.Write(data, setPerms)\n\tif err != nil {\n\t\tklog.Errorf(\"Error writing payload to dir: %v\", err)\n\t\treturn err\n\t}\n\n\tsetupSuccess = true\n\treturn nil\n}","line":{"from":188,"to":246}} {"id":100012724,"name":"collectData","signature":"func (s *projectedVolumeMounter) collectData(mounterArgs volume.MounterArgs) (map[string]volumeutil.FileProjection, error)","file":"pkg/volume/projected/projected.go","code":"func (s *projectedVolumeMounter) collectData(mounterArgs volume.MounterArgs) (map[string]volumeutil.FileProjection, error) {\n\tif s.source.DefaultMode == nil {\n\t\treturn nil, fmt.Errorf(\"no defaultMode used, not even the default value for it\")\n\t}\n\n\tkubeClient := s.plugin.host.GetKubeClient()\n\tif kubeClient == nil {\n\t\treturn nil, fmt.Errorf(\"cannot setup projected volume %v because kube client is not configured\", s.volName)\n\t}\n\n\terrlist := []error{}\n\tpayload := make(map[string]volumeutil.FileProjection)\n\tfor _, source := range s.source.Sources {\n\t\tswitch {\n\t\tcase source.Secret != nil:\n\t\t\toptional := source.Secret.Optional != nil \u0026\u0026 *source.Secret.Optional\n\t\t\tsecretapi, err := s.plugin.getSecret(s.pod.Namespace, source.Secret.Name)\n\t\t\tif err != nil {\n\t\t\t\tif !(errors.IsNotFound(err) \u0026\u0026 optional) {\n\t\t\t\t\tklog.Errorf(\"Couldn't get secret %v/%v: %v\", s.pod.Namespace, source.Secret.Name, err)\n\t\t\t\t\terrlist = append(errlist, err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tsecretapi = \u0026v1.Secret{\n\t\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\t\tNamespace: s.pod.Namespace,\n\t\t\t\t\t\tName: source.Secret.Name,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t\tsecretPayload, err := secret.MakePayload(source.Secret.Items, secretapi, s.source.DefaultMode, optional)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"Couldn't get secret payload %v/%v: %v\", s.pod.Namespace, source.Secret.Name, err)\n\t\t\t\terrlist = append(errlist, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor k, v := range secretPayload {\n\t\t\t\tpayload[k] = v\n\t\t\t}\n\t\tcase source.ConfigMap != nil:\n\t\t\toptional := source.ConfigMap.Optional != nil \u0026\u0026 *source.ConfigMap.Optional\n\t\t\tconfigMap, err := s.plugin.getConfigMap(s.pod.Namespace, source.ConfigMap.Name)\n\t\t\tif err != nil {\n\t\t\t\tif !(errors.IsNotFound(err) \u0026\u0026 optional) {\n\t\t\t\t\tklog.Errorf(\"Couldn't get configMap %v/%v: %v\", s.pod.Namespace, source.ConfigMap.Name, err)\n\t\t\t\t\terrlist = append(errlist, err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tconfigMap = \u0026v1.ConfigMap{\n\t\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\t\tNamespace: s.pod.Namespace,\n\t\t\t\t\t\tName: source.ConfigMap.Name,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t\tconfigMapPayload, err := configmap.MakePayload(source.ConfigMap.Items, configMap, s.source.DefaultMode, optional)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"Couldn't get configMap payload %v/%v: %v\", s.pod.Namespace, source.ConfigMap.Name, err)\n\t\t\t\terrlist = append(errlist, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor k, v := range configMapPayload {\n\t\t\t\tpayload[k] = v\n\t\t\t}\n\t\tcase source.DownwardAPI != nil:\n\t\t\tdownwardAPIPayload, err := downwardapi.CollectData(source.DownwardAPI.Items, s.pod, s.plugin.host, s.source.DefaultMode)\n\t\t\tif err != nil {\n\t\t\t\terrlist = append(errlist, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor k, v := range downwardAPIPayload {\n\t\t\t\tpayload[k] = v\n\t\t\t}\n\t\tcase source.ServiceAccountToken != nil:\n\t\t\ttp := source.ServiceAccountToken\n\n\t\t\t// When FsGroup is set, we depend on SetVolumeOwnership to\n\t\t\t// change from 0600 to 0640.\n\t\t\tmode := *s.source.DefaultMode\n\t\t\tif mounterArgs.FsUser != nil || mounterArgs.FsGroup != nil {\n\t\t\t\tmode = 0600\n\t\t\t}\n\n\t\t\tvar auds []string\n\t\t\tif len(tp.Audience) != 0 {\n\t\t\t\tauds = []string{tp.Audience}\n\t\t\t}\n\t\t\ttr, err := s.plugin.getServiceAccountToken(s.pod.Namespace, s.pod.Spec.ServiceAccountName, \u0026authenticationv1.TokenRequest{\n\t\t\t\tSpec: authenticationv1.TokenRequestSpec{\n\t\t\t\t\tAudiences: auds,\n\t\t\t\t\tExpirationSeconds: tp.ExpirationSeconds,\n\t\t\t\t\tBoundObjectRef: \u0026authenticationv1.BoundObjectReference{\n\t\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t\t\tKind: \"Pod\",\n\t\t\t\t\t\tName: s.pod.Name,\n\t\t\t\t\t\tUID: s.pod.UID,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\terrlist = append(errlist, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpayload[tp.Path] = volumeutil.FileProjection{\n\t\t\t\tData: []byte(tr.Status.Token),\n\t\t\t\tMode: mode,\n\t\t\t\tFsUser: mounterArgs.FsUser,\n\t\t\t}\n\t\t}\n\t}\n\treturn payload, utilerrors.NewAggregate(errlist)\n}","line":{"from":248,"to":359}} {"id":100012725,"name":"TearDown","signature":"func (c *projectedVolumeUnmounter) TearDown() error","file":"pkg/volume/projected/projected.go","code":"func (c *projectedVolumeUnmounter) TearDown() error {\n\treturn c.TearDownAt(c.GetPath())\n}","line":{"from":367,"to":369}} {"id":100012726,"name":"TearDownAt","signature":"func (c *projectedVolumeUnmounter) TearDownAt(dir string) error","file":"pkg/volume/projected/projected.go","code":"func (c *projectedVolumeUnmounter) TearDownAt(dir string) error {\n\tklog.V(3).Infof(\"Tearing down volume %v for pod %v at %v\", c.volName, c.podUID, dir)\n\n\twrapped, err := c.plugin.host.NewWrapperUnmounter(c.volName, wrappedVolumeSpec(), c.podUID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = wrapped.TearDownAt(dir); err != nil {\n\t\treturn err\n\t}\n\n\tc.plugin.deleteServiceAccountToken(c.podUID)\n\treturn nil\n}","line":{"from":371,"to":384}} {"id":100012727,"name":"getVolumeSource","signature":"func getVolumeSource(spec *volume.Spec) (*v1.ProjectedVolumeSource, bool, error)","file":"pkg/volume/projected/projected.go","code":"func getVolumeSource(spec *volume.Spec) (*v1.ProjectedVolumeSource, bool, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.Projected != nil {\n\t\treturn spec.Volume.Projected, spec.ReadOnly, nil\n\t}\n\n\treturn nil, false, fmt.Errorf(\"Spec does not reference a projected volume type\")\n}","line":{"from":386,"to":392}} {"id":100012728,"name":"NewAttacher","signature":"func (plugin *rbdPlugin) NewAttacher() (volume.Attacher, error)","file":"pkg/volume/rbd/attacher.go","code":"// NewAttacher implements AttachableVolumePlugin.NewAttacher.\nfunc (plugin *rbdPlugin) NewAttacher() (volume.Attacher, error) {\n\treturn plugin.newAttacherInternal(\u0026rbdUtil{})\n}","line":{"from":33,"to":36}} {"id":100012729,"name":"NewDeviceMounter","signature":"func (plugin *rbdPlugin) NewDeviceMounter() (volume.DeviceMounter, error)","file":"pkg/volume/rbd/attacher.go","code":"// NewDeviceMounter implements DeviceMountableVolumePlugin.NewDeviceMounter\nfunc (plugin *rbdPlugin) NewDeviceMounter() (volume.DeviceMounter, error) {\n\treturn plugin.NewAttacher()\n}","line":{"from":38,"to":41}} {"id":100012730,"name":"newAttacherInternal","signature":"func (plugin *rbdPlugin) newAttacherInternal(manager diskManager) (volume.Attacher, error)","file":"pkg/volume/rbd/attacher.go","code":"func (plugin *rbdPlugin) newAttacherInternal(manager diskManager) (volume.Attacher, error) {\n\treturn \u0026rbdAttacher{\n\t\tplugin: plugin,\n\t\tmanager: manager,\n\t\tmounter: volutil.NewSafeFormatAndMountFromHost(plugin.GetPluginName(), plugin.host),\n\t}, nil\n}","line":{"from":43,"to":49}} {"id":100012731,"name":"NewDetacher","signature":"func (plugin *rbdPlugin) NewDetacher() (volume.Detacher, error)","file":"pkg/volume/rbd/attacher.go","code":"// NewDetacher implements AttachableVolumePlugin.NewDetacher.\nfunc (plugin *rbdPlugin) NewDetacher() (volume.Detacher, error) {\n\treturn plugin.newDetacherInternal(\u0026rbdUtil{})\n}","line":{"from":51,"to":54}} {"id":100012732,"name":"NewDeviceUnmounter","signature":"func (plugin *rbdPlugin) NewDeviceUnmounter() (volume.DeviceUnmounter, error)","file":"pkg/volume/rbd/attacher.go","code":"// NewDeviceUnmounter implements DeviceMountableVolumePlugin.NewDeviceUnmounter\nfunc (plugin *rbdPlugin) NewDeviceUnmounter() (volume.DeviceUnmounter, error) {\n\treturn plugin.NewDetacher()\n}","line":{"from":56,"to":59}} {"id":100012733,"name":"newDetacherInternal","signature":"func (plugin *rbdPlugin) newDetacherInternal(manager diskManager) (volume.Detacher, error)","file":"pkg/volume/rbd/attacher.go","code":"func (plugin *rbdPlugin) newDetacherInternal(manager diskManager) (volume.Detacher, error) {\n\treturn \u0026rbdDetacher{\n\t\tplugin: plugin,\n\t\tmanager: manager,\n\t\tmounter: volutil.NewSafeFormatAndMountFromHost(plugin.GetPluginName(), plugin.host),\n\t}, nil\n}","line":{"from":61,"to":67}} {"id":100012734,"name":"GetDeviceMountRefs","signature":"func (plugin *rbdPlugin) GetDeviceMountRefs(deviceMountPath string) ([]string, error)","file":"pkg/volume/rbd/attacher.go","code":"// GetDeviceMountRefs implements AttachableVolumePlugin.GetDeviceMountRefs.\nfunc (plugin *rbdPlugin) GetDeviceMountRefs(deviceMountPath string) ([]string, error) {\n\tmounter := plugin.host.GetMounter(plugin.GetPluginName())\n\treturn mounter.GetMountRefs(deviceMountPath)\n}","line":{"from":69,"to":73}} {"id":100012735,"name":"CanAttach","signature":"func (plugin *rbdPlugin) CanAttach(spec *volume.Spec) (bool, error)","file":"pkg/volume/rbd/attacher.go","code":"func (plugin *rbdPlugin) CanAttach(spec *volume.Spec) (bool, error) {\n\treturn true, nil\n}","line":{"from":75,"to":77}} {"id":100012736,"name":"CanDeviceMount","signature":"func (plugin *rbdPlugin) CanDeviceMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/rbd/attacher.go","code":"func (plugin *rbdPlugin) CanDeviceMount(spec *volume.Spec) (bool, error) {\n\treturn true, nil\n}","line":{"from":79,"to":81}} {"id":100012737,"name":"Attach","signature":"func (attacher *rbdAttacher) Attach(spec *volume.Spec, nodeName types.NodeName) (string, error)","file":"pkg/volume/rbd/attacher.go","code":"// Attach implements Attacher.Attach.\n// We do not lock image here, because it requires kube-controller-manager to\n// access external `rbd` utility. And there is no need since AttachDetach\n// controller will not try to attach RWO volumes which are already attached to\n// other nodes.\nfunc (attacher *rbdAttacher) Attach(spec *volume.Spec, nodeName types.NodeName) (string, error) {\n\treturn \"\", nil\n}","line":{"from":94,"to":101}} {"id":100012738,"name":"VolumesAreAttached","signature":"func (attacher *rbdAttacher) VolumesAreAttached(specs []*volume.Spec, nodeName types.NodeName) (map[*volume.Spec]bool, error)","file":"pkg/volume/rbd/attacher.go","code":"// VolumesAreAttached implements Attacher.VolumesAreAttached.\n// There is no way to confirm whether the volume is attached or not from\n// outside of the kubelet node. This method needs to return true always, like\n// iSCSI, FC plugin.\nfunc (attacher *rbdAttacher) VolumesAreAttached(specs []*volume.Spec, nodeName types.NodeName) (map[*volume.Spec]bool, error) {\n\tvolumesAttachedCheck := make(map[*volume.Spec]bool)\n\tfor _, spec := range specs {\n\t\tvolumesAttachedCheck[spec] = true\n\t}\n\treturn volumesAttachedCheck, nil\n}","line":{"from":103,"to":113}} {"id":100012739,"name":"WaitForAttach","signature":"func (attacher *rbdAttacher) WaitForAttach(spec *volume.Spec, devicePath string, pod *v1.Pod, timeout time.Duration) (string, error)","file":"pkg/volume/rbd/attacher.go","code":"// WaitForAttach implements Attacher.WaitForAttach. It's called by kubelet to\n// attach volume onto the node.\n// This method is idempotent, callers are responsible for retrying on failure.\nfunc (attacher *rbdAttacher) WaitForAttach(spec *volume.Spec, devicePath string, pod *v1.Pod, timeout time.Duration) (string, error) {\n\tklog.V(4).Infof(\"rbd: waiting for attach volume (name: %s) for pod (name: %s, uid: %s)\", spec.Name(), pod.Name, pod.UID)\n\tmounter, err := attacher.plugin.createMounterFromVolumeSpecAndPod(spec, pod)\n\tif err != nil {\n\t\tklog.Warningf(\"failed to create mounter: %v\", spec)\n\t\treturn \"\", err\n\t}\n\trealDevicePath, err := attacher.manager.AttachDisk(*mounter)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tklog.V(3).Infof(\"rbd: successfully wait for attach volume (spec: %s, pool: %s, image: %s) at %s\", spec.Name(), mounter.Pool, mounter.Image, realDevicePath)\n\treturn realDevicePath, nil\n}","line":{"from":115,"to":131}} {"id":100012740,"name":"GetDeviceMountPath","signature":"func (attacher *rbdAttacher) GetDeviceMountPath(spec *volume.Spec) (string, error)","file":"pkg/volume/rbd/attacher.go","code":"// GetDeviceMountPath implements Attacher.GetDeviceMountPath.\nfunc (attacher *rbdAttacher) GetDeviceMountPath(spec *volume.Spec) (string, error) {\n\timg, err := getVolumeSourceImage(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tpool, err := getVolumeSourcePool(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn makePDNameInternal(attacher.plugin.host, pool, img), nil\n}","line":{"from":133,"to":144}} {"id":100012741,"name":"MountDevice","signature":"func (attacher *rbdAttacher) MountDevice(spec *volume.Spec, devicePath string, deviceMountPath string, mountArgs volume.DeviceMounterArgs) error","file":"pkg/volume/rbd/attacher.go","code":"// MountDevice implements Attacher.MountDevice. It is called by the kubelet to\n// mount device at the given mount path.\n// This method is idempotent, callers are responsible for retrying on failure.\nfunc (attacher *rbdAttacher) MountDevice(spec *volume.Spec, devicePath string, deviceMountPath string, mountArgs volume.DeviceMounterArgs) error {\n\tklog.V(4).Infof(\"rbd: mouting device %s to %s\", devicePath, deviceMountPath)\n\tnotMnt, err := attacher.mounter.IsLikelyNotMountPoint(deviceMountPath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tif err := os.MkdirAll(deviceMountPath, 0750); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tnotMnt = true\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\tif !notMnt {\n\t\treturn nil\n\t}\n\tfstype, err := getVolumeSourceFSType(spec)\n\tif err != nil {\n\t\treturn err\n\t}\n\tro, err := getVolumeSourceReadOnly(spec)\n\tif err != nil {\n\t\treturn err\n\t}\n\toptions := []string{}\n\tif ro {\n\t\toptions = append(options, \"ro\")\n\t}\n\tif mountArgs.SELinuxLabel != \"\" {\n\t\toptions = volutil.AddSELinuxMountOption(options, mountArgs.SELinuxLabel)\n\t}\n\tmountOptions := volutil.MountOptionFromSpec(spec, options...)\n\n\terr = attacher.mounter.FormatAndMount(devicePath, deviceMountPath, fstype, mountOptions)\n\tif err != nil {\n\t\tos.Remove(deviceMountPath)\n\t\treturn fmt.Errorf(\"rbd: failed to mount device %s at %s (fstype: %s), error %v\", devicePath, deviceMountPath, fstype, err)\n\t}\n\tklog.V(3).Infof(\"rbd: successfully mount device %s at %s (fstype: %s)\", devicePath, deviceMountPath, fstype)\n\treturn nil\n}","line":{"from":146,"to":189}} {"id":100012742,"name":"UnmountDevice","signature":"func (detacher *rbdDetacher) UnmountDevice(deviceMountPath string) error","file":"pkg/volume/rbd/attacher.go","code":"// UnmountDevice implements Detacher.UnmountDevice. It unmounts the global\n// mount of the RBD image. This is called once all bind mounts have been\n// unmounted.\n// Internally, it does four things:\n// - Unmount device from deviceMountPath.\n// - Detach device from the node.\n// - Remove lock if found. (No need to check volume readonly or not, because\n// device is not on the node anymore, it's safe to remove lock.)\n// - Remove the deviceMountPath at last.\n//\n// This method is idempotent, callers are responsible for retrying on failure.\nfunc (detacher *rbdDetacher) UnmountDevice(deviceMountPath string) error {\n\tif pathExists, pathErr := mount.PathExists(deviceMountPath); pathErr != nil {\n\t\treturn fmt.Errorf(\"error checking if path exists: %v\", pathErr)\n\t} else if !pathExists {\n\t\tklog.Warningf(\"Warning: Unmount skipped because path does not exist: %v\", deviceMountPath)\n\t\treturn nil\n\t}\n\tdevicePath, _, err := mount.GetDeviceNameFromMount(detacher.mounter, deviceMountPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Unmount the device from the device mount point.\n\tnotMnt, err := detacher.mounter.IsLikelyNotMountPoint(deviceMountPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !notMnt {\n\t\tklog.V(4).Infof(\"rbd: unmouting device mountpoint %s\", deviceMountPath)\n\t\tif err = detacher.mounter.Unmount(deviceMountPath); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tklog.V(3).Infof(\"rbd: successfully unmount device mountpath %s\", deviceMountPath)\n\t}\n\n\t// Get devicePath from deviceMountPath if devicePath is empty\n\tif devicePath == \"\" {\n\t\trbdImageInfo, err := getRbdImageInfo(deviceMountPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfound := false\n\t\tdevicePath, found = getRbdDevFromImageAndPool(rbdImageInfo.pool, rbdImageInfo.name)\n\t\tif !found {\n\t\t\tklog.Warningf(\"rbd: can't found devicePath for %v. Device is already unmounted, Image %v, Pool %v\", deviceMountPath, rbdImageInfo.pool, rbdImageInfo.name)\n\t\t}\n\t}\n\n\tif devicePath != \"\" {\n\t\tklog.V(4).Infof(\"rbd: detaching device %s\", devicePath)\n\t\terr = detacher.manager.DetachDisk(detacher.plugin, deviceMountPath, devicePath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tklog.V(3).Infof(\"rbd: successfully detach device %s\", devicePath)\n\t}\n\terr = os.Remove(deviceMountPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tklog.V(3).Infof(\"rbd: successfully remove device mount point %s\", deviceMountPath)\n\treturn nil\n}","line":{"from":202,"to":264}} {"id":100012743,"name":"Detach","signature":"func (detacher *rbdDetacher) Detach(volumeName string, nodeName types.NodeName) error","file":"pkg/volume/rbd/attacher.go","code":"// Detach implements Detacher.Detach.\nfunc (detacher *rbdDetacher) Detach(volumeName string, nodeName types.NodeName) error {\n\treturn nil\n}","line":{"from":266,"to":269}} {"id":100012744,"name":"diskSetUp","signature":"func diskSetUp(manager diskManager, b rbdMounter, volPath string, mounter mount.Interface, fsGroup *int64, fsGroupChangePolicy *v1.PodFSGroupChangePolicy) error","file":"pkg/volume/rbd/disk_manager.go","code":"// utility to mount a disk based filesystem\nfunc diskSetUp(manager diskManager, b rbdMounter, volPath string, mounter mount.Interface, fsGroup *int64, fsGroupChangePolicy *v1.PodFSGroupChangePolicy) error {\n\tglobalPDPath := manager.MakeGlobalPDName(*b.rbd)\n\tnotMnt, err := mounter.IsLikelyNotMountPoint(globalPDPath)\n\tif err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\tklog.Errorf(\"cannot validate mountpoint: %s\", globalPDPath)\n\t\treturn err\n\t}\n\tif notMnt {\n\t\treturn fmt.Errorf(\"no device is mounted at %s\", globalPDPath)\n\t}\n\n\tnotMnt, err = mounter.IsLikelyNotMountPoint(volPath)\n\tif err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\tklog.Errorf(\"cannot validate mountpoint: %s\", volPath)\n\t\treturn err\n\t}\n\tif !notMnt {\n\t\treturn nil\n\t}\n\n\tif err := os.MkdirAll(volPath, 0750); err != nil {\n\t\tklog.Errorf(\"failed to mkdir:%s\", volPath)\n\t\treturn err\n\t}\n\t// Perform a bind mount to the full path to allow duplicate mounts of the same disk.\n\toptions := []string{\"bind\"}\n\tif (\u0026b).GetAttributes().ReadOnly {\n\t\toptions = append(options, \"ro\")\n\t}\n\tmountOptions := util.JoinMountOptions(b.mountOptions, options)\n\terr = mounter.Mount(globalPDPath, volPath, \"\", mountOptions)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to bind mount:%s\", globalPDPath)\n\t\treturn err\n\t}\n\tklog.V(3).Infof(\"rbd: successfully bind mount %s to %s with options %v\", globalPDPath, volPath, mountOptions)\n\n\tif !b.ReadOnly {\n\t\tvolume.SetVolumeOwnership(\u0026b, volPath, fsGroup, fsGroupChangePolicy, util.FSGroupCompleteHook(b.plugin, nil))\n\t}\n\n\treturn nil\n}","line":{"from":60,"to":103}} {"id":100012745,"name":"diskTearDown","signature":"func diskTearDown(manager diskManager, c rbdUnmounter, volPath string, mounter mount.Interface) error","file":"pkg/volume/rbd/disk_manager.go","code":"// utility to tear down a disk based filesystem\nfunc diskTearDown(manager diskManager, c rbdUnmounter, volPath string, mounter mount.Interface) error {\n\tnotMnt, err := mounter.IsLikelyNotMountPoint(volPath)\n\tif err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\tklog.Errorf(\"cannot validate mountpoint: %s\", volPath)\n\t\treturn err\n\t}\n\tif notMnt {\n\t\tklog.V(3).Infof(\"volume path %s is not a mountpoint, deleting\", volPath)\n\t\treturn os.Remove(volPath)\n\t}\n\n\t// Unmount the bind-mount inside this pod.\n\tif err := mounter.Unmount(volPath); err != nil {\n\t\tklog.Errorf(\"failed to unmount %s\", volPath)\n\t\treturn err\n\t}\n\n\tnotMnt, mntErr := mounter.IsLikelyNotMountPoint(volPath)\n\tif mntErr != nil \u0026\u0026 !os.IsNotExist(mntErr) {\n\t\tklog.Errorf(\"IsLikelyNotMountPoint check failed: %v\", mntErr)\n\t\treturn mntErr\n\t}\n\tif notMnt {\n\t\tif err := os.Remove(volPath); err != nil {\n\t\t\tklog.V(2).Infof(\"Error removing mountpoint %s: %v\", volPath, err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":105,"to":135}} {"id":100012746,"name":"ProbeVolumePlugins","signature":"func ProbeVolumePlugins() []volume.VolumePlugin","file":"pkg/volume/rbd/rbd.go","code":"// ProbeVolumePlugins is the primary entrypoint for volume plugins.\nfunc ProbeVolumePlugins() []volume.VolumePlugin {\n\treturn []volume.VolumePlugin{\u0026rbdPlugin{}}\n}","line":{"from":50,"to":53}} {"id":100012747,"name":"getPath","signature":"func getPath(uid types.UID, volName string, host volume.VolumeHost) string","file":"pkg/volume/rbd/rbd.go","code":"func getPath(uid types.UID, volName string, host volume.VolumeHost) string {\n\treturn host.GetPodVolumeDir(uid, utilstrings.EscapeQualifiedName(rbdPluginName), volName)\n}","line":{"from":79,"to":81}} {"id":100012748,"name":"IsMigratedToCSI","signature":"func (plugin *rbdPlugin) IsMigratedToCSI() bool","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) IsMigratedToCSI() bool {\n\treturn utilfeature.DefaultFeatureGate.Enabled(features.CSIMigrationRBD)\n}","line":{"from":83,"to":85}} {"id":100012749,"name":"Init","signature":"func (plugin *rbdPlugin) Init(host volume.VolumeHost) error","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) Init(host volume.VolumeHost) error {\n\tplugin.host = host\n\treturn nil\n}","line":{"from":87,"to":90}} {"id":100012750,"name":"GetPluginName","signature":"func (plugin *rbdPlugin) GetPluginName() string","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) GetPluginName() string {\n\treturn rbdPluginName\n}","line":{"from":92,"to":94}} {"id":100012751,"name":"GetVolumeName","signature":"func (plugin *rbdPlugin) GetVolumeName(spec *volume.Spec) (string, error)","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) GetVolumeName(spec *volume.Spec) (string, error) {\n\tpool, err := getVolumeSourcePool(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\timg, err := getVolumeSourceImage(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn fmt.Sprintf(\n\t\t\"%v:%v\",\n\t\tpool,\n\t\timg), nil\n}","line":{"from":96,"to":110}} {"id":100012752,"name":"CanSupport","signature":"func (plugin *rbdPlugin) CanSupport(spec *volume.Spec) bool","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) CanSupport(spec *volume.Spec) bool {\n\treturn (spec.Volume != nil \u0026\u0026 spec.Volume.RBD != nil) || (spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.RBD != nil)\n}","line":{"from":112,"to":114}} {"id":100012753,"name":"RequiresRemount","signature":"func (plugin *rbdPlugin) RequiresRemount(spec *volume.Spec) bool","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) RequiresRemount(spec *volume.Spec) bool {\n\treturn false\n}","line":{"from":116,"to":118}} {"id":100012754,"name":"SupportsMountOption","signature":"func (plugin *rbdPlugin) SupportsMountOption() bool","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) SupportsMountOption() bool {\n\treturn true\n}","line":{"from":120,"to":122}} {"id":100012755,"name":"SupportsBulkVolumeVerification","signature":"func (plugin *rbdPlugin) SupportsBulkVolumeVerification() bool","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) SupportsBulkVolumeVerification() bool {\n\treturn false\n}","line":{"from":124,"to":126}} {"id":100012756,"name":"SupportsSELinuxContextMount","signature":"func (plugin *rbdPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error) {\n\treturn true, nil\n}","line":{"from":128,"to":130}} {"id":100012757,"name":"GetAccessModes","signature":"func (plugin *rbdPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode {\n\treturn []v1.PersistentVolumeAccessMode{\n\t\tv1.ReadWriteOnce,\n\t\tv1.ReadOnlyMany,\n\t}\n}","line":{"from":132,"to":137}} {"id":100012758,"name":"getAdminAndSecret","signature":"func (plugin *rbdPlugin) getAdminAndSecret(spec *volume.Spec) (string, string, error)","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) getAdminAndSecret(spec *volume.Spec) (string, string, error) {\n\tclass, err := volutil.GetClassForVolume(plugin.host.GetKubeClient(), spec.PersistentVolume)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tadminSecretName := \"\"\n\tadminSecretNamespace := rbdDefaultAdminSecretNamespace\n\tadmin := \"\"\n\n\tfor k, v := range class.Parameters {\n\t\tswitch dstrings.ToLower(k) {\n\t\tcase \"adminid\":\n\t\t\tadmin = v\n\t\tcase \"adminsecretname\":\n\t\t\tadminSecretName = v\n\t\tcase \"adminsecretnamespace\":\n\t\t\tadminSecretNamespace = v\n\t\t}\n\t}\n\n\tif admin == \"\" {\n\t\tadmin = rbdDefaultAdminID\n\t}\n\tsecret, err := parsePVSecret(adminSecretNamespace, adminSecretName, plugin.host.GetKubeClient())\n\tif err != nil {\n\t\treturn admin, \"\", fmt.Errorf(\"failed to get admin secret from [%q/%q]: %v\", adminSecretNamespace, adminSecretName, err)\n\t}\n\n\treturn admin, secret, nil\n}","line":{"from":143,"to":172}} {"id":100012759,"name":"ExpandVolumeDevice","signature":"func (plugin *rbdPlugin) ExpandVolumeDevice(spec *volume.Spec, newSize resource.Quantity, oldSize resource.Quantity) (resource.Quantity, error)","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) ExpandVolumeDevice(spec *volume.Spec, newSize resource.Quantity, oldSize resource.Quantity) (resource.Quantity, error) {\n\tif spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.RBD == nil {\n\t\treturn oldSize, fmt.Errorf(\"spec.PersistentVolume.Spec.RBD is nil\")\n\t}\n\n\t// get admin and secret\n\tadmin, secret, err := plugin.getAdminAndSecret(spec)\n\tif err != nil {\n\t\treturn oldSize, err\n\t}\n\n\texpander := \u0026rbdVolumeExpander{\n\t\trbdMounter: \u0026rbdMounter{\n\t\t\trbd: \u0026rbd{\n\t\t\t\tvolName: spec.Name(),\n\t\t\t\tImage: spec.PersistentVolume.Spec.RBD.RBDImage,\n\t\t\t\tPool: spec.PersistentVolume.Spec.RBD.RBDPool,\n\t\t\t\tplugin: plugin,\n\t\t\t\tmanager: \u0026rbdUtil{},\n\t\t\t\tmounter: \u0026mount.SafeFormatAndMount{Interface: plugin.host.GetMounter(plugin.GetPluginName())},\n\t\t\t\texec: plugin.host.GetExec(plugin.GetPluginName()),\n\t\t\t},\n\t\t\tMon: spec.PersistentVolume.Spec.RBD.CephMonitors,\n\t\t\tadminID: admin,\n\t\t\tadminSecret: secret,\n\t\t},\n\t}\n\n\texpandedSize, err := expander.ResizeImage(oldSize, newSize)\n\tif err != nil {\n\t\treturn oldSize, err\n\t}\n\treturn expandedSize, nil\n\n}","line":{"from":174,"to":208}} {"id":100012760,"name":"NodeExpand","signature":"func (plugin *rbdPlugin) NodeExpand(resizeOptions volume.NodeResizeOptions) (bool, error)","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) NodeExpand(resizeOptions volume.NodeResizeOptions) (bool, error) {\n\tfsVolume, err := volutil.CheckVolumeModeFilesystem(resizeOptions.VolumeSpec)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"error checking VolumeMode: %v\", err)\n\t}\n\t// if volume is not a fs file system, there is nothing for us to do here.\n\tif !fsVolume {\n\t\treturn true, nil\n\t}\n\t_, err = volutil.GenericResizeFS(plugin.host, plugin.GetPluginName(), resizeOptions.DevicePath, resizeOptions.DeviceMountPath)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn true, nil\n}","line":{"from":210,"to":224}} {"id":100012761,"name":"ResizeImage","signature":"func (expander *rbdVolumeExpander) ResizeImage(oldSize resource.Quantity, newSize resource.Quantity) (resource.Quantity, error)","file":"pkg/volume/rbd/rbd.go","code":"func (expander *rbdVolumeExpander) ResizeImage(oldSize resource.Quantity, newSize resource.Quantity) (resource.Quantity, error) {\n\treturn expander.manager.ExpandImage(expander, oldSize, newSize)\n}","line":{"from":228,"to":230}} {"id":100012762,"name":"RequiresFSResize","signature":"func (plugin *rbdPlugin) RequiresFSResize() bool","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) RequiresFSResize() bool {\n\treturn true\n}","line":{"from":232,"to":234}} {"id":100012763,"name":"createMounterFromVolumeSpecAndPod","signature":"func (plugin *rbdPlugin) createMounterFromVolumeSpecAndPod(spec *volume.Spec, pod *v1.Pod) (*rbdMounter, error)","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) createMounterFromVolumeSpecAndPod(spec *volume.Spec, pod *v1.Pod) (*rbdMounter, error) {\n\tvar err error\n\tmon, err := getVolumeSourceMonitors(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\timg, err := getVolumeSourceImage(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfstype, err := getVolumeSourceFSType(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpool, err := getVolumeSourcePool(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tid, err := getVolumeSourceUser(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkeyring, err := getVolumeSourceKeyRing(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tro, err := getVolumeSourceReadOnly(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tams, err := getVolumeAccessModes(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsecretName, secretNs, err := getSecretNameAndNamespace(spec, pod.Namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsecret := \"\"\n\tif len(secretName) \u003e 0 \u0026\u0026 len(secretNs) \u003e 0 {\n\t\t// if secret is provideded, retrieve it\n\t\tkubeClient := plugin.host.GetKubeClient()\n\t\tif kubeClient == nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot get kube client\")\n\t\t}\n\t\tsecrets, err := kubeClient.CoreV1().Secrets(secretNs).Get(context.TODO(), secretName, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"couldn't get secret %v/%v err: %v\", secretNs, secretName, err)\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, data := range secrets.Data {\n\t\t\tsecret = string(data)\n\t\t}\n\t}\n\n\treturn \u0026rbdMounter{\n\t\trbd: newRBD(\"\", spec.Name(), img, pool, ro, plugin, \u0026rbdUtil{}),\n\t\tMon: mon,\n\t\tID: id,\n\t\tKeyring: keyring,\n\t\tSecret: secret,\n\t\tfsType: fstype,\n\t\taccessModes: ams,\n\t}, nil\n}","line":{"from":236,"to":301}} {"id":100012764,"name":"NewMounter","signature":"func (plugin *rbdPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error)","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) {\n\tsecretName, secretNs, err := getSecretNameAndNamespace(spec, pod.Namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsecret := \"\"\n\tif len(secretName) \u003e 0 \u0026\u0026 len(secretNs) \u003e 0 {\n\t\t// if secret is provideded, retrieve it\n\t\tkubeClient := plugin.host.GetKubeClient()\n\t\tif kubeClient == nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot get kube client\")\n\t\t}\n\t\tsecrets, err := kubeClient.CoreV1().Secrets(secretNs).Get(context.TODO(), secretName, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"couldn't get secret %v/%v err: %v\", secretNs, secretName, err)\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, data := range secrets.Data {\n\t\t\tsecret = string(data)\n\t\t}\n\t}\n\n\t// Inject real implementations here, test through the internal function.\n\treturn plugin.newMounterInternal(spec, pod.UID, \u0026rbdUtil{}, secret)\n}","line":{"from":303,"to":327}} {"id":100012765,"name":"newMounterInternal","signature":"func (plugin *rbdPlugin) newMounterInternal(spec *volume.Spec, podUID types.UID, manager diskManager, secret string) (volume.Mounter, error)","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) newMounterInternal(spec *volume.Spec, podUID types.UID, manager diskManager, secret string) (volume.Mounter, error) {\n\tmon, err := getVolumeSourceMonitors(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\timg, err := getVolumeSourceImage(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfstype, err := getVolumeSourceFSType(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpool, err := getVolumeSourcePool(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tid, err := getVolumeSourceUser(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkeyring, err := getVolumeSourceKeyRing(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tro, err := getVolumeSourceReadOnly(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tams, err := getVolumeAccessModes(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026rbdMounter{\n\t\trbd: newRBD(podUID, spec.Name(), img, pool, ro, plugin, manager),\n\t\tMon: mon,\n\t\tID: id,\n\t\tKeyring: keyring,\n\t\tSecret: secret,\n\t\tfsType: fstype,\n\t\tmountOptions: volutil.MountOptionFromSpec(spec),\n\t\taccessModes: ams,\n\t}, nil\n}","line":{"from":329,"to":373}} {"id":100012766,"name":"NewUnmounter","signature":"func (plugin *rbdPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error)","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error) {\n\t// Inject real implementations here, test through the internal function.\n\treturn plugin.newUnmounterInternal(volName, podUID, \u0026rbdUtil{})\n}","line":{"from":375,"to":378}} {"id":100012767,"name":"newUnmounterInternal","signature":"func (plugin *rbdPlugin) newUnmounterInternal(volName string, podUID types.UID, manager diskManager) (volume.Unmounter, error)","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) newUnmounterInternal(volName string, podUID types.UID, manager diskManager) (volume.Unmounter, error) {\n\treturn \u0026rbdUnmounter{\n\t\trbdMounter: \u0026rbdMounter{\n\t\t\trbd: newRBD(podUID, volName, \"\", \"\", false, plugin, manager),\n\t\t\tMon: make([]string, 0),\n\t\t},\n\t}, nil\n}","line":{"from":380,"to":387}} {"id":100012768,"name":"ConstructVolumeSpec","signature":"func (plugin *rbdPlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error)","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error) {\n\tmounter := plugin.host.GetMounter(plugin.GetPluginName())\n\tkvh, ok := plugin.host.(volume.KubeletVolumeHost)\n\tif !ok {\n\t\treturn volume.ReconstructedVolume{}, fmt.Errorf(\"plugin volume host does not implement KubeletVolumeHost interface\")\n\t}\n\thu := kvh.GetHostUtil()\n\tpluginMntDir := volutil.GetPluginMountDir(plugin.host, plugin.GetPluginName())\n\tsourceName, err := hu.GetDeviceNameFromMount(mounter, mountPath, pluginMntDir)\n\tif err != nil {\n\t\treturn volume.ReconstructedVolume{}, err\n\t}\n\ts := dstrings.Split(sourceName, \"-image-\")\n\tif len(s) != 2 {\n\t\t// The mountPath parameter is the volume mount path for a specific pod, its format\n\t\t// is /var/lib/kubelet/pods/{podUID}/volumes/{volumePluginName}/{volumeName}.\n\t\t// mounter.GetDeviceNameFromMount will find the device path(such as /dev/rbd0) by\n\t\t// mountPath first, and then try to find the global device mount path from the mounted\n\t\t// path list of this device. sourceName is extracted from this global device mount path.\n\t\t// mounter.GetDeviceNameFromMount expects the global device mount path conforms to canonical\n\t\t// format: /var/lib/kubelet/plugins/kubernetes.io/rbd/mounts/{pool}-image-{image}.\n\t\t// If this assertion failed, it means that the global device mount path is created by\n\t\t// the deprecated format: /var/lib/kubelet/plugins/kubernetes.io/rbd/rbd/{pool}-image-{image}.\n\t\t// So we will try to check whether this old style global device mount path exist or not.\n\t\t// If existed, extract the sourceName from this old style path, otherwise return an error.\n\t\tklog.V(3).Infof(\"SourceName %s wrong, fallback to old format\", sourceName)\n\t\tsourceName, err = plugin.getDeviceNameFromOldMountPath(mounter, mountPath)\n\t\tif err != nil {\n\t\t\treturn volume.ReconstructedVolume{}, err\n\t\t}\n\t\ts = dstrings.Split(sourceName, \"-image-\")\n\t\tif len(s) != 2 {\n\t\t\treturn volume.ReconstructedVolume{}, fmt.Errorf(\"sourceName %s wrong, should be pool+\\\"-image-\\\"+imageName\", sourceName)\n\t\t}\n\t}\n\trbdVolume := \u0026v1.Volume{\n\t\tName: volumeName,\n\t\tVolumeSource: v1.VolumeSource{\n\t\t\tRBD: \u0026v1.RBDVolumeSource{\n\t\t\t\tRBDPool: s[0],\n\t\t\t\tRBDImage: s[1],\n\t\t\t},\n\t\t},\n\t}\n\n\tvar mountContext string\n\tif utilfeature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {\n\t\tmountContext, err = hu.GetSELinuxMountContext(mountPath)\n\t\tif err != nil {\n\t\t\treturn volume.ReconstructedVolume{}, err\n\t\t}\n\t}\n\n\treturn volume.ReconstructedVolume{\n\t\tSpec: volume.NewSpecFromVolume(rbdVolume),\n\t\tSELinuxMountContext: mountContext,\n\t}, nil\n}","line":{"from":389,"to":446}} {"id":100012769,"name":"ConstructBlockVolumeSpec","signature":"func (plugin *rbdPlugin) ConstructBlockVolumeSpec(podUID types.UID, volumeName, mapPath string) (*volume.Spec, error)","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) ConstructBlockVolumeSpec(podUID types.UID, volumeName, mapPath string) (*volume.Spec, error) {\n\tpluginDir := plugin.host.GetVolumeDevicePluginDir(rbdPluginName)\n\tblkutil := volumepathhandler.NewBlockVolumePathHandler()\n\n\tglobalMapPathUUID, err := blkutil.FindGlobalMapPathUUIDFromPod(pluginDir, mapPath, podUID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tklog.V(5).Infof(\"globalMapPathUUID: %v, err: %v\", globalMapPathUUID, err)\n\tglobalMapPath := filepath.Dir(globalMapPathUUID)\n\tif len(globalMapPath) == 1 {\n\t\treturn nil, fmt.Errorf(\"failed to retrieve volume plugin information from globalMapPathUUID: %v\", globalMapPathUUID)\n\t}\n\treturn getVolumeSpecFromGlobalMapPath(globalMapPath, volumeName)\n}","line":{"from":448,"to":462}} {"id":100012770,"name":"getVolumeSpecFromGlobalMapPath","signature":"func getVolumeSpecFromGlobalMapPath(globalMapPath, volumeName string) (*volume.Spec, error)","file":"pkg/volume/rbd/rbd.go","code":"func getVolumeSpecFromGlobalMapPath(globalMapPath, volumeName string) (*volume.Spec, error) {\n\t// Retrieve volume spec information from globalMapPath\n\t// globalMapPath example:\n\t// plugins/kubernetes.io/{PluginName}/{DefaultKubeletVolumeDevicesDirName}/{volumePluginDependentPath}\n\tpool, image, err := getPoolAndImageFromMapPath(globalMapPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tblock := v1.PersistentVolumeBlock\n\trbdVolume := \u0026v1.PersistentVolume{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: volumeName,\n\t\t},\n\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\tPersistentVolumeSource: v1.PersistentVolumeSource{\n\t\t\t\tRBD: \u0026v1.RBDPersistentVolumeSource{\n\t\t\t\t\tRBDImage: image,\n\t\t\t\t\tRBDPool: pool,\n\t\t\t\t},\n\t\t\t},\n\t\t\tVolumeMode: \u0026block,\n\t\t},\n\t}\n\n\treturn volume.NewSpecFromPersistentVolume(rbdVolume, true), nil\n}","line":{"from":464,"to":489}} {"id":100012771,"name":"NewBlockVolumeMapper","signature":"func (plugin *rbdPlugin) NewBlockVolumeMapper(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.BlockVolumeMapper, error)","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) NewBlockVolumeMapper(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.BlockVolumeMapper, error) {\n\n\tvar uid types.UID\n\tif pod != nil {\n\t\tuid = pod.UID\n\t}\n\tsecret := \"\"\n\tif pod != nil {\n\t\tsecretName, secretNs, err := getSecretNameAndNamespace(spec, pod.Namespace)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(secretName) \u003e 0 \u0026\u0026 len(secretNs) \u003e 0 {\n\t\t\t// if secret is provideded, retrieve it\n\t\t\tkubeClient := plugin.host.GetKubeClient()\n\t\t\tif kubeClient == nil {\n\t\t\t\treturn nil, fmt.Errorf(\"cannot get kube client\")\n\t\t\t}\n\t\t\tsecrets, err := kubeClient.CoreV1().Secrets(secretNs).Get(context.TODO(), secretName, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"couldn't get secret %v/%v err: %v\", secretNs, secretName, err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfor _, data := range secrets.Data {\n\t\t\t\tsecret = string(data)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn plugin.newBlockVolumeMapperInternal(spec, uid, \u0026rbdUtil{}, secret, plugin.host.GetMounter(plugin.GetPluginName()), plugin.host.GetExec(plugin.GetPluginName()))\n}","line":{"from":491,"to":521}} {"id":100012772,"name":"newBlockVolumeMapperInternal","signature":"func (plugin *rbdPlugin) newBlockVolumeMapperInternal(spec *volume.Spec, podUID types.UID, manager diskManager, secret string, mounter mount.Interface, exec utilexec.Interface) (volume.BlockVolumeMapper, error)","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) newBlockVolumeMapperInternal(spec *volume.Spec, podUID types.UID, manager diskManager, secret string, mounter mount.Interface, exec utilexec.Interface) (volume.BlockVolumeMapper, error) {\n\tmon, err := getVolumeSourceMonitors(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\timg, err := getVolumeSourceImage(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpool, err := getVolumeSourcePool(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tid, err := getVolumeSourceUser(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkeyring, err := getVolumeSourceKeyRing(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tro, err := getVolumeSourceReadOnly(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmapper := \u0026rbdDiskMapper{\n\t\trbd: newRBD(podUID, spec.Name(), img, pool, ro, plugin, manager),\n\t\tmon: mon,\n\t\tid: id,\n\t\tkeyring: keyring,\n\t\tsecret: secret,\n\t}\n\n\tblockPath, err := mapper.GetGlobalMapPath(spec)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get device path: %v\", err)\n\t}\n\tmapper.MetricsProvider = volume.NewMetricsBlock(filepath.Join(blockPath, string(podUID)))\n\n\treturn mapper, nil\n}","line":{"from":523,"to":564}} {"id":100012773,"name":"NewBlockVolumeUnmapper","signature":"func (plugin *rbdPlugin) NewBlockVolumeUnmapper(volName string, podUID types.UID) (volume.BlockVolumeUnmapper, error)","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) NewBlockVolumeUnmapper(volName string, podUID types.UID) (volume.BlockVolumeUnmapper, error) {\n\treturn plugin.newUnmapperInternal(volName, podUID, \u0026rbdUtil{})\n}","line":{"from":566,"to":568}} {"id":100012774,"name":"newUnmapperInternal","signature":"func (plugin *rbdPlugin) newUnmapperInternal(volName string, podUID types.UID, manager diskManager) (volume.BlockVolumeUnmapper, error)","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) newUnmapperInternal(volName string, podUID types.UID, manager diskManager) (volume.BlockVolumeUnmapper, error) {\n\treturn \u0026rbdDiskUnmapper{\n\t\trbdDiskMapper: \u0026rbdDiskMapper{\n\t\t\trbd: newRBD(podUID, volName, \"\", \"\", false, plugin, manager),\n\t\t\tmon: make([]string, 0),\n\t\t},\n\t}, nil\n}","line":{"from":570,"to":577}} {"id":100012775,"name":"getDeviceNameFromOldMountPath","signature":"func (plugin *rbdPlugin) getDeviceNameFromOldMountPath(mounter mount.Interface, mountPath string) (string, error)","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) getDeviceNameFromOldMountPath(mounter mount.Interface, mountPath string) (string, error) {\n\trefs, err := mounter.GetMountRefs(mountPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// baseMountPath is the prefix of deprecated device global mounted path,\n\t// such as: /var/lib/kubelet/plugins/kubernetes.io/rbd/rbd\n\tbaseMountPath := filepath.Join(plugin.host.GetPluginDir(rbdPluginName), \"rbd\")\n\tfor _, ref := range refs {\n\t\tif dstrings.HasPrefix(ref, baseMountPath) {\n\t\t\treturn filepath.Rel(baseMountPath, ref)\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"can't find source name from mounted path: %s\", mountPath)\n}","line":{"from":579,"to":593}} {"id":100012776,"name":"NewDeleter","signature":"func (plugin *rbdPlugin) NewDeleter(logger klog.Logger, spec *volume.Spec) (volume.Deleter, error)","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) NewDeleter(logger klog.Logger, spec *volume.Spec) (volume.Deleter, error) {\n\tif spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.RBD == nil {\n\t\treturn nil, fmt.Errorf(\"spec.PersistentVolume.Spec.RBD is nil\")\n\t}\n\n\tadmin, secret, err := plugin.getAdminAndSecret(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn plugin.newDeleterInternal(spec, admin, secret, \u0026rbdUtil{})\n}","line":{"from":595,"to":606}} {"id":100012777,"name":"newDeleterInternal","signature":"func (plugin *rbdPlugin) newDeleterInternal(spec *volume.Spec, admin, secret string, manager diskManager) (volume.Deleter, error)","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) newDeleterInternal(spec *volume.Spec, admin, secret string, manager diskManager) (volume.Deleter, error) {\n\treturn \u0026rbdVolumeDeleter{\n\t\trbdMounter: \u0026rbdMounter{\n\t\t\trbd: newRBD(\"\", spec.Name(), spec.PersistentVolume.Spec.RBD.RBDImage, spec.PersistentVolume.Spec.RBD.RBDPool, false, plugin, manager),\n\t\t\tMon: spec.PersistentVolume.Spec.RBD.CephMonitors,\n\t\t\tadminID: admin,\n\t\t\tadminSecret: secret,\n\t\t}}, nil\n}","line":{"from":608,"to":616}} {"id":100012778,"name":"NewProvisioner","signature":"func (plugin *rbdPlugin) NewProvisioner(logger klog.Logger, options volume.VolumeOptions) (volume.Provisioner, error)","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) NewProvisioner(logger klog.Logger, options volume.VolumeOptions) (volume.Provisioner, error) {\n\treturn plugin.newProvisionerInternal(options, \u0026rbdUtil{})\n}","line":{"from":618,"to":620}} {"id":100012779,"name":"newProvisionerInternal","signature":"func (plugin *rbdPlugin) newProvisionerInternal(options volume.VolumeOptions, manager diskManager) (volume.Provisioner, error)","file":"pkg/volume/rbd/rbd.go","code":"func (plugin *rbdPlugin) newProvisionerInternal(options volume.VolumeOptions, manager diskManager) (volume.Provisioner, error) {\n\treturn \u0026rbdVolumeProvisioner{\n\t\trbdMounter: \u0026rbdMounter{\n\t\t\trbd: newRBD(\"\", \"\", \"\", \"\", false, plugin, manager),\n\t\t},\n\t\toptions: options,\n\t}, nil\n}","line":{"from":622,"to":629}} {"id":100012780,"name":"Provision","signature":"func (r *rbdVolumeProvisioner) Provision(selectedNode *v1.Node, allowedTopologies []v1.TopologySelectorTerm) (*v1.PersistentVolume, error)","file":"pkg/volume/rbd/rbd.go","code":"func (r *rbdVolumeProvisioner) Provision(selectedNode *v1.Node, allowedTopologies []v1.TopologySelectorTerm) (*v1.PersistentVolume, error) {\n\tif !volutil.ContainsAllAccessModes(r.plugin.GetAccessModes(), r.options.PVC.Spec.AccessModes) {\n\t\treturn nil, fmt.Errorf(\"invalid AccessModes %v: only AccessModes %v are supported\", r.options.PVC.Spec.AccessModes, r.plugin.GetAccessModes())\n\t}\n\n\tif r.options.PVC.Spec.Selector != nil {\n\t\treturn nil, fmt.Errorf(\"claim Selector is not supported\")\n\t}\n\tvar err error\n\tadminSecretName := \"\"\n\tadminSecretNamespace := rbdDefaultAdminSecretNamespace\n\tsecret := \"\"\n\tsecretName := \"\"\n\tsecretNamespace := \"\"\n\tkeyring := \"\"\n\timageFormat := rbdImageFormat2\n\tfstype := \"\"\n\n\tfor k, v := range r.options.Parameters {\n\t\tswitch dstrings.ToLower(k) {\n\t\tcase \"monitors\":\n\t\t\tarr := dstrings.Split(v, \",\")\n\t\t\tr.Mon = append(r.Mon, arr...)\n\t\tcase \"adminid\":\n\t\t\tr.adminID = v\n\t\tcase \"adminsecretname\":\n\t\t\tadminSecretName = v\n\t\tcase \"adminsecretnamespace\":\n\t\t\tadminSecretNamespace = v\n\t\tcase \"userid\":\n\t\t\tr.ID = v\n\t\tcase \"pool\":\n\t\t\tr.Pool = v\n\t\tcase \"usersecretname\":\n\t\t\tsecretName = v\n\t\tcase \"usersecretnamespace\":\n\t\t\tsecretNamespace = v\n\t\tcase \"keyring\":\n\t\t\tkeyring = v\n\t\tcase \"imageformat\":\n\t\t\timageFormat = v\n\t\tcase \"imagefeatures\":\n\t\t\tarr := dstrings.Split(v, \",\")\n\t\t\tfor _, f := range arr {\n\t\t\t\tif !supportedFeatures.Has(f) {\n\t\t\t\t\treturn nil, fmt.Errorf(\"invalid feature %q for volume plugin %s, supported features are: %v\", f, r.plugin.GetPluginName(), supportedFeatures)\n\t\t\t\t}\n\t\t\t\tr.imageFeatures = append(r.imageFeatures, f)\n\t\t\t}\n\t\tcase volume.VolumeParameterFSType:\n\t\t\tfstype = v\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"invalid option %q for volume plugin %s\", k, r.plugin.GetPluginName())\n\t\t}\n\t}\n\t// sanity check\n\tif imageFormat != rbdImageFormat1 \u0026\u0026 imageFormat != rbdImageFormat2 {\n\t\treturn nil, fmt.Errorf(\"invalid ceph imageformat %s, expecting %s or %s\",\n\t\t\timageFormat, rbdImageFormat1, rbdImageFormat2)\n\t}\n\tr.imageFormat = imageFormat\n\tif adminSecretName == \"\" {\n\t\treturn nil, fmt.Errorf(\"missing Ceph admin secret name\")\n\t}\n\tif secret, err = parsePVSecret(adminSecretNamespace, adminSecretName, r.plugin.host.GetKubeClient()); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get admin secret from [%q/%q]: %v\", adminSecretNamespace, adminSecretName, err)\n\t}\n\tr.adminSecret = secret\n\tif len(r.Mon) \u003c 1 {\n\t\treturn nil, fmt.Errorf(\"missing Ceph monitors\")\n\t}\n\tif secretName == \"\" \u0026\u0026 keyring == \"\" {\n\t\treturn nil, fmt.Errorf(\"must specify either keyring or user secret name\")\n\t}\n\tif r.adminID == \"\" {\n\t\tr.adminID = rbdDefaultAdminID\n\t}\n\tif r.Pool == \"\" {\n\t\tr.Pool = rbdDefaultPool\n\t}\n\tif r.ID == \"\" {\n\t\tr.ID = r.adminID\n\t}\n\n\t// create random image name\n\timage := fmt.Sprintf(\"kubernetes-dynamic-pvc-%s\", uuid.NewUUID())\n\tr.rbdMounter.Image = image\n\trbd, sizeMB, err := r.manager.CreateImage(r)\n\tif err != nil {\n\t\tklog.Errorf(\"rbd: create volume failed, err: %v\", err)\n\t\treturn nil, err\n\t}\n\tklog.Infof(\"successfully created rbd image %q\", image)\n\tpv := new(v1.PersistentVolume)\n\tmetav1.SetMetaDataAnnotation(\u0026pv.ObjectMeta, volutil.VolumeDynamicallyCreatedByKey, \"rbd-dynamic-provisioner\")\n\n\tif secretName != \"\" {\n\t\trbd.SecretRef = new(v1.SecretReference)\n\t\trbd.SecretRef.Name = secretName\n\t\trbd.SecretRef.Namespace = secretNamespace\n\t} else {\n\t\tvar filePathRegex = regexp.MustCompile(`^(?:/[^/!;` + \"`\" + ` ]+)+$`)\n\t\tif keyring != \"\" \u0026\u0026 !filePathRegex.MatchString(keyring) {\n\t\t\treturn nil, fmt.Errorf(\"keyring field must contain a path to a file\")\n\t\t}\n\t\trbd.Keyring = keyring\n\t}\n\n\tvolumeMode := r.options.PVC.Spec.VolumeMode\n\tif volumeMode != nil \u0026\u0026 *volumeMode == v1.PersistentVolumeBlock {\n\t\t// Block volumes should not have any FSType\n\t\tfstype = \"\"\n\t}\n\n\trbd.RadosUser = r.ID\n\trbd.FSType = fstype\n\tpv.Spec.PersistentVolumeSource.RBD = rbd\n\tpv.Spec.PersistentVolumeReclaimPolicy = r.options.PersistentVolumeReclaimPolicy\n\tpv.Spec.AccessModes = r.options.PVC.Spec.AccessModes\n\tif len(pv.Spec.AccessModes) == 0 {\n\t\tpv.Spec.AccessModes = r.plugin.GetAccessModes()\n\t}\n\tpv.Spec.Capacity = v1.ResourceList{\n\t\tv1.ResourceName(v1.ResourceStorage): resource.MustParse(fmt.Sprintf(\"%dMi\", sizeMB)),\n\t}\n\tpv.Spec.MountOptions = r.options.MountOptions\n\tpv.Spec.VolumeMode = volumeMode\n\n\treturn pv, nil\n}","line":{"from":639,"to":768}} {"id":100012781,"name":"GetPath","signature":"func (r *rbdVolumeDeleter) GetPath() string","file":"pkg/volume/rbd/rbd.go","code":"func (r *rbdVolumeDeleter) GetPath() string {\n\treturn getPath(r.podUID, r.volName, r.plugin.host)\n}","line":{"from":777,"to":779}} {"id":100012782,"name":"Delete","signature":"func (r *rbdVolumeDeleter) Delete() error","file":"pkg/volume/rbd/rbd.go","code":"func (r *rbdVolumeDeleter) Delete() error {\n\treturn r.manager.DeleteImage(r)\n}","line":{"from":781,"to":783}} {"id":100012783,"name":"GetPath","signature":"func (rbd *rbd) GetPath() string","file":"pkg/volume/rbd/rbd.go","code":"func (rbd *rbd) GetPath() string {\n\t// safe to use PodVolumeDir now: volume teardown occurs before pod is cleaned up\n\treturn getPath(rbd.podUID, rbd.volName, rbd.plugin.host)\n}","line":{"from":804,"to":807}} {"id":100012784,"name":"newRBD","signature":"func newRBD(podUID types.UID, volName string, image string, pool string, readOnly bool, plugin *rbdPlugin, manager diskManager) *rbd","file":"pkg/volume/rbd/rbd.go","code":"// newRBD creates a new rbd.\nfunc newRBD(podUID types.UID, volName string, image string, pool string, readOnly bool, plugin *rbdPlugin, manager diskManager) *rbd {\n\treturn \u0026rbd{\n\t\tpodUID: podUID,\n\t\tvolName: volName,\n\t\tImage: image,\n\t\tPool: pool,\n\t\tReadOnly: readOnly,\n\t\tplugin: plugin,\n\t\tmounter: volutil.NewSafeFormatAndMountFromHost(plugin.GetPluginName(), plugin.host),\n\t\texec: plugin.host.GetExec(plugin.GetPluginName()),\n\t\tmanager: manager,\n\t\tMetricsProvider: volume.NewMetricsStatFS(getPath(podUID, volName, plugin.host)),\n\t}\n}","line":{"from":809,"to":823}} {"id":100012785,"name":"GetAttributes","signature":"func (rbd *rbd) GetAttributes() volume.Attributes","file":"pkg/volume/rbd/rbd.go","code":"func (rbd *rbd) GetAttributes() volume.Attributes {\n\treturn volume.Attributes{\n\t\tReadOnly: rbd.ReadOnly,\n\t\tManaged: !rbd.ReadOnly,\n\t\tSELinuxRelabel: !rbd.mountedWithSELinuxContext,\n\t}\n}","line":{"from":849,"to":855}} {"id":100012786,"name":"SetUp","signature":"func (b *rbdMounter) SetUp(mounterArgs volume.MounterArgs) error","file":"pkg/volume/rbd/rbd.go","code":"func (b *rbdMounter) SetUp(mounterArgs volume.MounterArgs) error {\n\treturn b.SetUpAt(b.GetPath(), mounterArgs)\n}","line":{"from":857,"to":859}} {"id":100012787,"name":"SetUpAt","signature":"func (b *rbdMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error","file":"pkg/volume/rbd/rbd.go","code":"func (b *rbdMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {\n\t// diskSetUp checks mountpoints and prevent repeated calls\n\tklog.V(4).Infof(\"rbd: attempting to setup at %s\", dir)\n\terr := diskSetUp(b.manager, *b, dir, b.mounter, mounterArgs.FsGroup, mounterArgs.FSGroupChangePolicy)\n\tif err != nil {\n\t\tklog.Errorf(\"rbd: failed to setup at %s %v\", dir, err)\n\t\treturn err\n\t}\n\tif utilfeature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {\n\t\t// The volume must have been mounted in MountDevice with -o context.\n\t\tb.mountedWithSELinuxContext = mounterArgs.SELinuxLabel != \"\"\n\t}\n\n\tklog.V(3).Infof(\"rbd: successfully setup at %s\", dir)\n\treturn err\n}","line":{"from":861,"to":876}} {"id":100012788,"name":"TearDown","signature":"func (c *rbdUnmounter) TearDown() error","file":"pkg/volume/rbd/rbd.go","code":"// Unmounts the bind mount, and detaches the disk only if the disk\n// resource was the last reference to that disk on the kubelet.\nfunc (c *rbdUnmounter) TearDown() error {\n\treturn c.TearDownAt(c.GetPath())\n}","line":{"from":885,"to":889}} {"id":100012789,"name":"TearDownAt","signature":"func (c *rbdUnmounter) TearDownAt(dir string) error","file":"pkg/volume/rbd/rbd.go","code":"func (c *rbdUnmounter) TearDownAt(dir string) error {\n\tklog.V(4).Infof(\"rbd: attempting to teardown at %s\", dir)\n\tif pathExists, pathErr := mount.PathExists(dir); pathErr != nil {\n\t\treturn fmt.Errorf(\"error checking if path exists: %v\", pathErr)\n\t} else if !pathExists {\n\t\tklog.Warningf(\"Warning: Unmount skipped because path does not exist: %v\", dir)\n\t\treturn nil\n\t}\n\terr := diskTearDown(c.manager, *c, dir, c.mounter)\n\tif err != nil {\n\t\treturn err\n\t}\n\tklog.V(3).Infof(\"rbd: successfully teardown at %s\", dir)\n\treturn nil\n}","line":{"from":891,"to":905}} {"id":100012790,"name":"GetGlobalMapPath","signature":"func (rbd *rbd) GetGlobalMapPath(spec *volume.Spec) (string, error)","file":"pkg/volume/rbd/rbd.go","code":"// GetGlobalMapPath returns global map path and error\n// path: plugins/kubernetes.io/{PluginName}/volumeDevices/{rbd pool}-image-{rbd image-name}/{podUid}\nfunc (rbd *rbd) GetGlobalMapPath(spec *volume.Spec) (string, error) {\n\treturn rbd.rbdGlobalMapPath(spec)\n}","line":{"from":920,"to":924}} {"id":100012791,"name":"GetPodDeviceMapPath","signature":"func (rbd *rbd) GetPodDeviceMapPath() (string, string)","file":"pkg/volume/rbd/rbd.go","code":"// GetPodDeviceMapPath returns pod device map path and volume name\n// path: pods/{podUid}/volumeDevices/kubernetes.io~rbd\n// volumeName: pv0001\nfunc (rbd *rbd) GetPodDeviceMapPath() (string, string) {\n\treturn rbd.rbdPodDeviceMapPath()\n}","line":{"from":926,"to":931}} {"id":100012792,"name":"rbdGlobalMapPath","signature":"func (rbd *rbd) rbdGlobalMapPath(spec *volume.Spec) (string, error)","file":"pkg/volume/rbd/rbd.go","code":"func (rbd *rbd) rbdGlobalMapPath(spec *volume.Spec) (string, error) {\n\tmon, err := getVolumeSourceMonitors(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\timg, err := getVolumeSourceImage(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tpool, err := getVolumeSourcePool(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tro, err := getVolumeSourceReadOnly(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tmounter := \u0026rbdMounter{\n\t\trbd: newRBD(\"\", spec.Name(), img, pool, ro, rbd.plugin, \u0026rbdUtil{}),\n\t\tMon: mon,\n\t}\n\treturn rbd.manager.MakeGlobalVDPDName(*mounter.rbd), nil\n}","line":{"from":933,"to":956}} {"id":100012793,"name":"rbdPodDeviceMapPath","signature":"func (rbd *rbd) rbdPodDeviceMapPath() (string, string)","file":"pkg/volume/rbd/rbd.go","code":"func (rbd *rbd) rbdPodDeviceMapPath() (string, string) {\n\tname := rbdPluginName\n\treturn rbd.plugin.host.GetPodVolumeDeviceDir(rbd.podUID, utilstrings.EscapeQualifiedName(name)), rbd.volName\n}","line":{"from":958,"to":961}} {"id":100012794,"name":"SupportsMetrics","signature":"func (rdm *rbdDiskMapper) SupportsMetrics() bool","file":"pkg/volume/rbd/rbd.go","code":"// SupportsMetrics returns true for rbdDiskMapper as it initializes the\n// MetricsProvider.\nfunc (rdm *rbdDiskMapper) SupportsMetrics() bool {\n\treturn true\n}","line":{"from":963,"to":967}} {"id":100012795,"name":"getPoolAndImageFromMapPath","signature":"func getPoolAndImageFromMapPath(mapPath string) (string, string, error)","file":"pkg/volume/rbd/rbd.go","code":"func getPoolAndImageFromMapPath(mapPath string) (string, string, error) {\n\n\tpathParts := dstrings.Split(mapPath, pathSeparator)\n\tif len(pathParts) \u003c 2 {\n\t\treturn \"\", \"\", fmt.Errorf(\"corrupted mapPath\")\n\t}\n\trbdParts := dstrings.Split(pathParts[len(pathParts)-1], \"-image-\")\n\n\tif len(rbdParts) \u003c 2 {\n\t\treturn \"\", \"\", fmt.Errorf(\"corrupted mapPath\")\n\t}\n\treturn string(rbdParts[0]), string(rbdParts[1]), nil\n}","line":{"from":973,"to":985}} {"id":100012796,"name":"getBlockVolumeDevice","signature":"func getBlockVolumeDevice(mapPath string) (string, error)","file":"pkg/volume/rbd/rbd.go","code":"func getBlockVolumeDevice(mapPath string) (string, error) {\n\tpool, image, err := getPoolAndImageFromMapPath(mapPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// Getting full device path\n\tdevice, found := getDevFromImageAndPool(pool, image)\n\tif !found {\n\t\treturn \"\", err\n\t}\n\treturn device, nil\n}","line":{"from":987,"to":998}} {"id":100012797,"name":"TearDownDevice","signature":"func (rbd *rbdDiskUnmapper) TearDownDevice(mapPath, _ string) error","file":"pkg/volume/rbd/rbd.go","code":"func (rbd *rbdDiskUnmapper) TearDownDevice(mapPath, _ string) error {\n\n\tdevice, err := getBlockVolumeDevice(mapPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"rbd: failed to get loopback for device: %v, err: %v\", device, err)\n\t}\n\n\terr = rbd.manager.DetachBlockDisk(*rbd, mapPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"rbd: failed to detach disk: %s\\nError: %v\", mapPath, err)\n\t}\n\tklog.V(4).Infof(\"rbd: %q is unmapped, deleting the directory\", mapPath)\n\n\terr = os.RemoveAll(mapPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"rbd: failed to delete the directory: %s\\nError: %v\", mapPath, err)\n\t}\n\tklog.V(4).Infof(\"rbd: successfully detached disk: %s\", mapPath)\n\n\treturn nil\n}","line":{"from":1000,"to":1020}} {"id":100012798,"name":"UnmapPodDevice","signature":"func (rbd *rbdDiskUnmapper) UnmapPodDevice() error","file":"pkg/volume/rbd/rbd.go","code":"func (rbd *rbdDiskUnmapper) UnmapPodDevice() error {\n\treturn nil\n}","line":{"from":1022,"to":1024}} {"id":100012799,"name":"getVolumeSourceMonitors","signature":"func getVolumeSourceMonitors(spec *volume.Spec) ([]string, error)","file":"pkg/volume/rbd/rbd.go","code":"func getVolumeSourceMonitors(spec *volume.Spec) ([]string, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.RBD != nil {\n\t\treturn spec.Volume.RBD.CephMonitors, nil\n\t} else if spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.RBD != nil {\n\t\treturn spec.PersistentVolume.Spec.RBD.CephMonitors, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"spec does not reference a RBD volume type\")\n}","line":{"from":1026,"to":1035}} {"id":100012800,"name":"getVolumeSourceImage","signature":"func getVolumeSourceImage(spec *volume.Spec) (string, error)","file":"pkg/volume/rbd/rbd.go","code":"func getVolumeSourceImage(spec *volume.Spec) (string, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.RBD != nil {\n\t\treturn spec.Volume.RBD.RBDImage, nil\n\t} else if spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.RBD != nil {\n\t\treturn spec.PersistentVolume.Spec.RBD.RBDImage, nil\n\t}\n\n\treturn \"\", fmt.Errorf(\"spec does not reference a RBD volume type\")\n}","line":{"from":1037,"to":1046}} {"id":100012801,"name":"getVolumeSourceFSType","signature":"func getVolumeSourceFSType(spec *volume.Spec) (string, error)","file":"pkg/volume/rbd/rbd.go","code":"func getVolumeSourceFSType(spec *volume.Spec) (string, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.RBD != nil {\n\t\treturn spec.Volume.RBD.FSType, nil\n\t} else if spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.RBD != nil {\n\t\treturn spec.PersistentVolume.Spec.RBD.FSType, nil\n\t}\n\n\treturn \"\", fmt.Errorf(\"spec does not reference a RBD volume type\")\n}","line":{"from":1048,"to":1057}} {"id":100012802,"name":"getVolumeSourcePool","signature":"func getVolumeSourcePool(spec *volume.Spec) (string, error)","file":"pkg/volume/rbd/rbd.go","code":"func getVolumeSourcePool(spec *volume.Spec) (string, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.RBD != nil {\n\t\treturn spec.Volume.RBD.RBDPool, nil\n\t} else if spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.RBD != nil {\n\t\treturn spec.PersistentVolume.Spec.RBD.RBDPool, nil\n\t}\n\n\treturn \"\", fmt.Errorf(\"spec does not reference a RBD volume type\")\n}","line":{"from":1059,"to":1068}} {"id":100012803,"name":"getVolumeSourceUser","signature":"func getVolumeSourceUser(spec *volume.Spec) (string, error)","file":"pkg/volume/rbd/rbd.go","code":"func getVolumeSourceUser(spec *volume.Spec) (string, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.RBD != nil {\n\t\treturn spec.Volume.RBD.RadosUser, nil\n\t} else if spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.RBD != nil {\n\t\treturn spec.PersistentVolume.Spec.RBD.RadosUser, nil\n\t}\n\n\treturn \"\", fmt.Errorf(\"spec does not reference a RBD volume type\")\n}","line":{"from":1070,"to":1079}} {"id":100012804,"name":"getVolumeSourceKeyRing","signature":"func getVolumeSourceKeyRing(spec *volume.Spec) (string, error)","file":"pkg/volume/rbd/rbd.go","code":"func getVolumeSourceKeyRing(spec *volume.Spec) (string, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.RBD != nil {\n\t\treturn spec.Volume.RBD.Keyring, nil\n\t} else if spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.RBD != nil {\n\t\treturn spec.PersistentVolume.Spec.RBD.Keyring, nil\n\t}\n\n\treturn \"\", fmt.Errorf(\"spec does not reference a RBD volume type\")\n}","line":{"from":1081,"to":1090}} {"id":100012805,"name":"getVolumeSourceReadOnly","signature":"func getVolumeSourceReadOnly(spec *volume.Spec) (bool, error)","file":"pkg/volume/rbd/rbd.go","code":"func getVolumeSourceReadOnly(spec *volume.Spec) (bool, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.RBD != nil {\n\t\treturn spec.Volume.RBD.ReadOnly, nil\n\t} else if spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.RBD != nil {\n\t\t// rbd volumes used as a PersistentVolume gets the ReadOnly flag indirectly through\n\t\t// the persistent-claim volume used to mount the PV\n\t\treturn spec.ReadOnly, nil\n\t}\n\n\treturn false, fmt.Errorf(\"spec does not reference a RBD volume type\")\n}","line":{"from":1092,"to":1103}} {"id":100012806,"name":"getVolumeAccessModes","signature":"func getVolumeAccessModes(spec *volume.Spec) ([]v1.PersistentVolumeAccessMode, error)","file":"pkg/volume/rbd/rbd.go","code":"func getVolumeAccessModes(spec *volume.Spec) ([]v1.PersistentVolumeAccessMode, error) {\n\t// Only PersistentVolumeSpec has AccessModes\n\tif spec.PersistentVolume != nil {\n\t\tif spec.PersistentVolume.Spec.RBD != nil {\n\t\t\treturn spec.PersistentVolume.Spec.AccessModes, nil\n\t\t}\n\t\treturn nil, fmt.Errorf(\"spec does not reference a RBD volume type\")\n\t}\n\n\treturn nil, nil\n}","line":{"from":1105,"to":1115}} {"id":100012807,"name":"parsePVSecret","signature":"func parsePVSecret(namespace, secretName string, kubeClient clientset.Interface) (string, error)","file":"pkg/volume/rbd/rbd.go","code":"func parsePVSecret(namespace, secretName string, kubeClient clientset.Interface) (string, error) {\n\tsecret, err := volutil.GetSecretForPV(namespace, secretName, rbdPluginName, kubeClient)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to get secret from [%q/%q]: %+v\", namespace, secretName, err)\n\t\treturn \"\", fmt.Errorf(\"failed to get secret from [%q/%q]: %+v\", namespace, secretName, err)\n\t}\n\treturn parseSecretMap(secret)\n}","line":{"from":1117,"to":1124}} {"id":100012808,"name":"parseSecretMap","signature":"func parseSecretMap(secretMap map[string]string) (string, error)","file":"pkg/volume/rbd/rbd.go","code":"// parseSecretMap locates the secret by key name.\nfunc parseSecretMap(secretMap map[string]string) (string, error) {\n\tif len(secretMap) == 0 {\n\t\treturn \"\", fmt.Errorf(\"empty secret map\")\n\t}\n\tsecret := \"\"\n\tfor k, v := range secretMap {\n\t\tif k == secretKeyName {\n\t\t\treturn v, nil\n\t\t}\n\t\tsecret = v\n\t}\n\t// If not found, the last secret in the map wins as done before\n\treturn secret, nil\n}","line":{"from":1126,"to":1140}} {"id":100012809,"name":"getSecretNameAndNamespace","signature":"func getSecretNameAndNamespace(spec *volume.Spec, defaultNamespace string) (string, string, error)","file":"pkg/volume/rbd/rbd.go","code":"func getSecretNameAndNamespace(spec *volume.Spec, defaultNamespace string) (string, string, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.RBD != nil {\n\t\tlocalSecretRef := spec.Volume.RBD.SecretRef\n\t\tif localSecretRef != nil {\n\t\t\treturn localSecretRef.Name, defaultNamespace, nil\n\t\t}\n\t\treturn \"\", \"\", nil\n\n\t} else if spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.RBD != nil {\n\t\tsecretRef := spec.PersistentVolume.Spec.RBD.SecretRef\n\t\tsecretNs := defaultNamespace\n\t\tif secretRef != nil {\n\t\t\tif len(secretRef.Namespace) != 0 {\n\t\t\t\tsecretNs = secretRef.Namespace\n\t\t\t}\n\t\t\treturn secretRef.Name, secretNs, nil\n\t\t}\n\t\treturn \"\", \"\", nil\n\t}\n\treturn \"\", \"\", fmt.Errorf(\"spec does not reference an RBD volume type\")\n}","line":{"from":1142,"to":1163}} {"id":100012810,"name":"getDevFromImageAndPool","signature":"func getDevFromImageAndPool(pool, image string) (string, bool)","file":"pkg/volume/rbd/rbd_util.go","code":"func getDevFromImageAndPool(pool, image string) (string, bool) {\n\tdevice, found := getRbdDevFromImageAndPool(pool, image)\n\tif found {\n\t\treturn device, true\n\t}\n\tdevice, found = getNbdDevFromImageAndPool(pool, image)\n\tif found {\n\t\treturn device, true\n\t}\n\treturn \"\", false\n}","line":{"from":67,"to":77}} {"id":100012811,"name":"getRbdDevFromImageAndPool","signature":"func getRbdDevFromImageAndPool(pool string, image string) (string, bool)","file":"pkg/volume/rbd/rbd_util.go","code":"// Search /sys/bus for rbd device that matches given pool and image.\nfunc getRbdDevFromImageAndPool(pool string, image string) (string, bool) {\n\t// /sys/bus/rbd/devices/X/name and /sys/bus/rbd/devices/X/pool\n\tsysPath := \"/sys/bus/rbd/devices\"\n\tif dirs, err := ioutil.ReadDir(sysPath); err == nil {\n\t\tfor _, f := range dirs {\n\t\t\t// Pool and name format:\n\t\t\t// see rbd_pool_show() and rbd_name_show() at\n\t\t\t// https://github.com/torvalds/linux/blob/master/drivers/block/rbd.c\n\t\t\tname := f.Name()\n\t\t\t// First match pool, then match name.\n\t\t\tpoolFile := filepath.Join(sysPath, name, \"pool\")\n\t\t\tpoolBytes, err := ioutil.ReadFile(poolFile)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"error reading %s: %v\", poolFile, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif strings.TrimSpace(string(poolBytes)) != pool {\n\t\t\t\tklog.V(4).Infof(\"device %s is not %q: %q\", name, pool, string(poolBytes))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\timgFile := filepath.Join(sysPath, name, \"name\")\n\t\t\timgBytes, err := ioutil.ReadFile(imgFile)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"error reading %s: %v\", imgFile, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif strings.TrimSpace(string(imgBytes)) != image {\n\t\t\t\tklog.V(4).Infof(\"device %s is not %q: %q\", name, image, string(imgBytes))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Found a match, check if device exists.\n\t\t\tdevicePath := \"/dev/rbd\" + name\n\t\t\tif _, err := os.Lstat(devicePath); err == nil {\n\t\t\t\treturn devicePath, true\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", false\n}","line":{"from":79,"to":118}} {"id":100012812,"name":"getMaxNbds","signature":"func getMaxNbds() (int, error)","file":"pkg/volume/rbd/rbd_util.go","code":"func getMaxNbds() (int, error) {\n\n\t// the max number of nbd devices may be found in maxNbdsPath\n\t// we will check sysfs for possible nbd devices even if this is not available\n\tmaxNbdsPath := \"/sys/module/nbd/parameters/nbds_max\"\n\t_, err := os.Lstat(maxNbdsPath)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"rbd-nbd: failed to retrieve max_nbds from %s err: %q\", maxNbdsPath, err)\n\t}\n\n\tklog.V(4).Infof(\"found nbds max parameters file at %s\", maxNbdsPath)\n\n\tmaxNbdBytes, err := ioutil.ReadFile(maxNbdsPath)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"rbd-nbd: failed to read max_nbds from %s err: %q\", maxNbdsPath, err)\n\t}\n\n\tmaxNbds, err := strconv.Atoi(strings.TrimSpace(string(maxNbdBytes)))\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"rbd-nbd: failed to read max_nbds err: %q\", err)\n\t}\n\n\tklog.V(4).Infof(\"rbd-nbd: max_nbds: %d\", maxNbds)\n\treturn maxNbds, nil\n}","line":{"from":120,"to":144}} {"id":100012813,"name":"getNbdDevFromImageAndPool","signature":"func getNbdDevFromImageAndPool(pool string, image string) (string, bool)","file":"pkg/volume/rbd/rbd_util.go","code":"// Locate any existing rbd-nbd process mapping given a \u003cpool, image\u003e.\n// Recent versions of rbd-nbd tool can correctly provide this info using list-mapped\n// but older versions of list-mapped don't.\n// The implementation below peeks at the command line of nbd bound processes\n// to figure out any mapped images.\nfunc getNbdDevFromImageAndPool(pool string, image string) (string, bool) {\n\t// nbd module exports the pid of serving process in sysfs\n\tbasePath := \"/sys/block/nbd\"\n\t// Do not change imgPath format - some tools like rbd-nbd are strict about it.\n\timgPath := fmt.Sprintf(\"%s/%s\", pool, image)\n\n\tmaxNbds, maxNbdsErr := getMaxNbds()\n\tif maxNbdsErr != nil {\n\t\tklog.V(4).Infof(\"error reading nbds_max %v\", maxNbdsErr)\n\t\treturn \"\", false\n\t}\n\n\tfor i := 0; i \u003c maxNbds; i++ {\n\t\tnbdPath := basePath + strconv.Itoa(i)\n\t\t_, err := os.Lstat(nbdPath)\n\t\tif err != nil {\n\t\t\tklog.V(4).Infof(\"error reading nbd info directory %s: %v\", nbdPath, err)\n\t\t\tcontinue\n\t\t}\n\t\tpidBytes, err := ioutil.ReadFile(filepath.Join(nbdPath, \"pid\"))\n\t\tif err != nil {\n\t\t\tklog.V(5).Infof(\"did not find valid pid file in dir %s: %v\", nbdPath, err)\n\t\t\tcontinue\n\t\t}\n\t\tcmdlineFileName := filepath.Join(\"/proc\", strings.TrimSpace(string(pidBytes)), \"cmdline\")\n\t\trawCmdline, err := ioutil.ReadFile(cmdlineFileName)\n\t\tif err != nil {\n\t\t\tklog.V(4).Infof(\"failed to read cmdline file %s: %v\", cmdlineFileName, err)\n\t\t\tcontinue\n\t\t}\n\t\tcmdlineArgs := strings.FieldsFunc(string(rawCmdline), func(r rune) bool {\n\t\t\treturn r == '\\u0000'\n\t\t})\n\t\t// Check if this process is mapping a rbd device.\n\t\t// Only accepted pattern of cmdline is from execRbdMap:\n\t\t// rbd-nbd map pool/image ...\n\t\tif len(cmdlineArgs) \u003c 3 || cmdlineArgs[0] != \"rbd-nbd\" || cmdlineArgs[1] != \"map\" {\n\t\t\tklog.V(4).Infof(\"nbd device %s is not used by rbd\", nbdPath)\n\t\t\tcontinue\n\t\t}\n\t\tif cmdlineArgs[2] != imgPath {\n\t\t\tklog.V(4).Infof(\"rbd-nbd device %s did not match expected image path: %s with path found: %s\",\n\t\t\t\tnbdPath, imgPath, cmdlineArgs[2])\n\t\t\tcontinue\n\t\t}\n\t\tdevicePath := filepath.Join(\"/dev\", \"nbd\"+strconv.Itoa(i))\n\t\tif _, err := os.Lstat(devicePath); err != nil {\n\t\t\tklog.Warningf(\"Stat device %s for imgpath %s failed %v\", devicePath, imgPath, err)\n\t\t\tcontinue\n\t\t}\n\t\treturn devicePath, true\n\t}\n\treturn \"\", false\n}","line":{"from":146,"to":204}} {"id":100012814,"name":"waitForPath","signature":"func waitForPath(pool, image string, maxRetries int, useNbdDriver bool) (string, bool)","file":"pkg/volume/rbd/rbd_util.go","code":"// Stat a path, if it doesn't exist, retry maxRetries times.\nfunc waitForPath(pool, image string, maxRetries int, useNbdDriver bool) (string, bool) {\n\tfor i := 0; i \u003c maxRetries; i++ {\n\t\tif i != 0 {\n\t\t\ttime.Sleep(time.Second)\n\t\t}\n\t\tif useNbdDriver {\n\t\t\tif devicePath, found := getNbdDevFromImageAndPool(pool, image); found {\n\t\t\t\treturn devicePath, true\n\t\t\t}\n\t\t} else {\n\t\t\tif devicePath, found := getRbdDevFromImageAndPool(pool, image); found {\n\t\t\t\treturn devicePath, true\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", false\n}","line":{"from":206,"to":223}} {"id":100012815,"name":"execRbdMap","signature":"func execRbdMap(b rbdMounter, rbdCmd string, mon string) ([]byte, error)","file":"pkg/volume/rbd/rbd_util.go","code":"// Execute command to map a rbd device for mounter.\n// rbdCmd is driver dependent and either \"rbd\" or \"rbd-nbd\".\nfunc execRbdMap(b rbdMounter, rbdCmd string, mon string) ([]byte, error) {\n\t// Commandline: rbdCmd map imgPath ...\n\t// do not change this format - some tools like rbd-nbd are strict about it.\n\timgPath := fmt.Sprintf(\"%s/%s\", b.Pool, b.Image)\n\tif b.Secret != \"\" {\n\t\treturn b.exec.Command(rbdCmd,\n\t\t\t\"map\", imgPath, \"--id\", b.ID, \"-m\", mon, \"--key=\"+b.Secret).CombinedOutput()\n\t}\n\treturn b.exec.Command(rbdCmd,\n\t\t\"map\", imgPath, \"--id\", b.ID, \"-m\", mon, \"-k\", b.Keyring).CombinedOutput()\n}","line":{"from":225,"to":237}} {"id":100012816,"name":"checkRbdNbdTools","signature":"func checkRbdNbdTools(e utilexec.Interface) bool","file":"pkg/volume/rbd/rbd_util.go","code":"// Check if rbd-nbd tools are installed.\nfunc checkRbdNbdTools(e utilexec.Interface) bool {\n\t_, err := e.Command(\"modprobe\", \"nbd\").CombinedOutput()\n\tif err != nil {\n\t\tklog.V(5).Infof(\"rbd-nbd: nbd modprobe failed with error %v\", err)\n\t\treturn false\n\t}\n\tif _, err := e.Command(\"rbd-nbd\", \"--version\").CombinedOutput(); err != nil {\n\t\tklog.V(5).Infof(\"rbd-nbd: getting rbd-nbd version failed with error %v\", err)\n\t\treturn false\n\t}\n\tklog.V(3).Infof(\"rbd-nbd tools were found.\")\n\treturn true\n}","line":{"from":239,"to":252}} {"id":100012817,"name":"makePDNameInternal","signature":"func makePDNameInternal(host volume.VolumeHost, pool string, image string) string","file":"pkg/volume/rbd/rbd_util.go","code":"// Make a directory like /var/lib/kubelet/plugins/kubernetes.io/rbd/mounts/pool-image-image.\nfunc makePDNameInternal(host volume.VolumeHost, pool string, image string) string {\n\t// Backward compatibility for the deprecated format: /var/lib/kubelet/plugins/kubernetes.io/rbd/rbd/pool-image-image.\n\tdeprecatedDir := filepath.Join(host.GetPluginDir(rbdPluginName), \"rbd\", pool+\"-image-\"+image)\n\tinfo, err := os.Stat(deprecatedDir)\n\tif err == nil \u0026\u0026 info.IsDir() {\n\t\t// The device mount path has already been created with the deprecated format, return it.\n\t\tklog.V(5).Infof(\"Deprecated format path %s found\", deprecatedDir)\n\t\treturn deprecatedDir\n\t}\n\t// Return the canonical format path.\n\treturn filepath.Join(host.GetPluginDir(rbdPluginName), volutil.MountsInGlobalPDPath, pool+\"-image-\"+image)\n}","line":{"from":254,"to":266}} {"id":100012818,"name":"makeVDPDNameInternal","signature":"func makeVDPDNameInternal(host volume.VolumeHost, pool string, image string) string","file":"pkg/volume/rbd/rbd_util.go","code":"// Make a directory like /var/lib/kubelet/plugins/kubernetes.io/rbd/volumeDevices/pool-image-image.\nfunc makeVDPDNameInternal(host volume.VolumeHost, pool string, image string) string {\n\treturn filepath.Join(host.GetVolumeDevicePluginDir(rbdPluginName), pool+\"-image-\"+image)\n}","line":{"from":268,"to":271}} {"id":100012819,"name":"MakeGlobalPDName","signature":"func (util *rbdUtil) MakeGlobalPDName(rbd rbd) string","file":"pkg/volume/rbd/rbd_util.go","code":"// MakeGlobalPDName makes a plugin directory.\nfunc (util *rbdUtil) MakeGlobalPDName(rbd rbd) string {\n\treturn makePDNameInternal(rbd.plugin.host, rbd.Pool, rbd.Image)\n}","line":{"from":278,"to":281}} {"id":100012820,"name":"MakeGlobalVDPDName","signature":"func (util *rbdUtil) MakeGlobalVDPDName(rbd rbd) string","file":"pkg/volume/rbd/rbd_util.go","code":"// MakeGlobalVDPDName makes a volume device plugin directory.\nfunc (util *rbdUtil) MakeGlobalVDPDName(rbd rbd) string {\n\treturn makeVDPDNameInternal(rbd.plugin.host, rbd.Pool, rbd.Image)\n}","line":{"from":283,"to":286}} {"id":100012821,"name":"rbdErrors","signature":"func rbdErrors(runErr, resultErr error) error","file":"pkg/volume/rbd/rbd_util.go","code":"func rbdErrors(runErr, resultErr error) error {\n\tif err, ok := runErr.(*exec.Error); ok {\n\t\tif err.Err == exec.ErrNotFound {\n\t\t\treturn fmt.Errorf(\"rbd: rbd cmd not found\")\n\t\t}\n\t}\n\treturn resultErr\n}","line":{"from":288,"to":295}} {"id":100012822,"name":"kernelRBDMonitorsOpt","signature":"func (util *rbdUtil) kernelRBDMonitorsOpt(mons []string) string","file":"pkg/volume/rbd/rbd_util.go","code":"// 'rbd' utility builds a comma-separated list of monitor addresses from '-m' /\n// '--mon_host` parameter (comma, semi-colon, or white-space delimited monitor\n// addresses) and send it to kernel rbd/libceph modules, which can accept\n// comma-separated list of monitor addresses (e.g. ip1[:port1][,ip2[:port2]...])\n// in their first version in linux (see\n// https://github.com/torvalds/linux/blob/602adf400201636e95c3fed9f31fba54a3d7e844/net/ceph/ceph_common.c#L239).\n// Also, libceph module chooses monitor randomly, so we can simply pass all\n// addresses without randomization (see\n// https://github.com/torvalds/linux/blob/602adf400201636e95c3fed9f31fba54a3d7e844/net/ceph/mon_client.c#L132).\nfunc (util *rbdUtil) kernelRBDMonitorsOpt(mons []string) string {\n\treturn strings.Join(mons, \",\")\n}","line":{"from":297,"to":308}} {"id":100012823,"name":"rbdUnlock","signature":"func (util *rbdUtil) rbdUnlock(b rbdMounter) error","file":"pkg/volume/rbd/rbd_util.go","code":"// rbdUnlock releases a lock on image if found.\nfunc (util *rbdUtil) rbdUnlock(b rbdMounter) error {\n\tvar err error\n\tvar output, locker string\n\tvar cmd []byte\n\tvar secretOpt []string\n\n\tif b.Secret != \"\" {\n\t\tsecretOpt = []string{\"--key=\" + b.Secret}\n\t} else {\n\t\tsecretOpt = []string{\"-k\", b.Keyring}\n\t}\n\tif len(b.adminID) == 0 {\n\t\tb.adminID = b.ID\n\t}\n\tif len(b.adminSecret) == 0 {\n\t\tb.adminSecret = b.Secret\n\t}\n\n\t// Construct lock id using host name and a magic prefix.\n\thostName, err := nodeutil.GetHostname(\"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tlockID := kubeLockMagic + hostName\n\n\tmon := util.kernelRBDMonitorsOpt(b.Mon)\n\n\t// Get the locker name, something like \"client.1234\".\n\targs := []string{\"lock\", \"list\", b.Image, \"--pool\", b.Pool, \"--id\", b.ID, \"-m\", mon}\n\targs = append(args, secretOpt...)\n\tcmd, err = b.exec.Command(\"rbd\", args...).CombinedOutput()\n\toutput = string(cmd)\n\tklog.V(4).Infof(\"lock list output %q\", output)\n\tif err != nil {\n\t\treturn err\n\t}\n\tind := strings.LastIndex(output, lockID) - 1\n\tfor i := ind; i \u003e= 0; i-- {\n\t\tif output[i] == '\\n' {\n\t\t\tlocker = output[(i + 1):ind]\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Remove a lock if found: rbd lock remove.\n\tif len(locker) \u003e 0 {\n\t\targs := []string{\"lock\", \"remove\", b.Image, lockID, locker, \"--pool\", b.Pool, \"--id\", b.ID, \"-m\", mon}\n\t\targs = append(args, secretOpt...)\n\t\t_, err = b.exec.Command(\"rbd\", args...).CombinedOutput()\n\t\tif err == nil {\n\t\t\tklog.V(4).Infof(\"rbd: successfully remove lock (locker_id: %s) on image: %s/%s with id %s mon %s\", lockID, b.Pool, b.Image, b.ID, mon)\n\t\t} else {\n\t\t\tklog.Warningf(\"rbd: failed to remove lock (lockID: %s) on image: %s/%s with id %s mon %s: %v\", lockID, b.Pool, b.Image, b.ID, mon, err)\n\t\t}\n\t}\n\n\treturn err\n}","line":{"from":310,"to":368}} {"id":100012824,"name":"AttachDisk","signature":"func (util *rbdUtil) AttachDisk(b rbdMounter) (string, error)","file":"pkg/volume/rbd/rbd_util.go","code":"// AttachDisk attaches the disk on the node.\nfunc (util *rbdUtil) AttachDisk(b rbdMounter) (string, error) {\n\tvar output []byte\n\n\tglobalPDPath := util.MakeGlobalPDName(*b.rbd)\n\tif pathExists, pathErr := mount.PathExists(globalPDPath); pathErr != nil {\n\t\treturn \"\", fmt.Errorf(\"error checking if path exists: %v\", pathErr)\n\t} else if !pathExists {\n\t\tif err := os.MkdirAll(globalPDPath, 0750); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\t// Evaluate whether this device was mapped with rbd.\n\tdevicePath, mapped := waitForPath(b.Pool, b.Image, 1 /*maxRetries*/, false /*useNbdDriver*/)\n\n\t// If rbd-nbd tools are found, we will fallback to it should the default krbd driver fail.\n\tnbdToolsFound := false\n\n\tif !mapped {\n\t\tnbdToolsFound = checkRbdNbdTools(b.exec)\n\t\tif nbdToolsFound {\n\t\t\tdevicePath, mapped = waitForPath(b.Pool, b.Image, 1 /*maxRetries*/, true /*useNbdDriver*/)\n\t\t}\n\t}\n\n\tif !mapped {\n\t\t// Currently, we don't acquire advisory lock on image, but for backward\n\t\t// compatibility, we need to check if the image is being used by nodes running old kubelet.\n\t\t// osd_client_watch_timeout defaults to 30 seconds, if the watcher stays active longer than 30 seconds,\n\t\t// rbd image does not get mounted and failure message gets generated.\n\t\tbackoff := wait.Backoff{\n\t\t\tDuration: rbdImageWatcherInitDelay,\n\t\t\tFactor: rbdImageWatcherFactor,\n\t\t\tSteps: rbdImageWatcherSteps,\n\t\t}\n\t\tneedValidUsed := true\n\t\tif b.accessModes != nil {\n\t\t\t// If accessModes only contains ReadOnlyMany, we don't need check rbd status of being used.\n\t\t\tif len(b.accessModes) == 1 \u0026\u0026 b.accessModes[0] == v1.ReadOnlyMany {\n\t\t\t\tneedValidUsed = false\n\t\t\t}\n\t\t}\n\t\t// If accessModes is nil, the volume is referenced by in-line volume.\n\t\t// We can assume the AccessModes to be {\"RWO\" and \"ROX\"}, which is what the volume plugin supports.\n\t\t// We do not need to consider ReadOnly here, because it is used for VolumeMounts.\n\n\t\tif needValidUsed {\n\t\t\terr := wait.ExponentialBackoff(backoff, func() (bool, error) {\n\t\t\t\tused, rbdOutput, err := util.rbdStatus(\u0026b)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, fmt.Errorf(\"fail to check rbd image status with: (%v), rbd output: (%s)\", err, rbdOutput)\n\t\t\t\t}\n\t\t\t\treturn !used, nil\n\t\t\t})\n\t\t\t// Return error if rbd image has not become available for the specified timeout.\n\t\t\tif err == wait.ErrWaitTimeout {\n\t\t\t\treturn \"\", fmt.Errorf(\"rbd image %s/%s is still being used\", b.Pool, b.Image)\n\t\t\t}\n\t\t\t// Return error if any other errors were encountered during waiting for the image to become available.\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t}\n\n\t\tmon := util.kernelRBDMonitorsOpt(b.Mon)\n\t\tklog.V(1).Infof(\"rbd: map mon %s\", mon)\n\n\t\t_, err := b.exec.Command(\"modprobe\", \"rbd\").CombinedOutput()\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"rbd: failed to load rbd kernel module:%v\", err)\n\t\t}\n\t\toutput, err = execRbdMap(b, \"rbd\", mon)\n\t\tif err != nil {\n\t\t\tif !nbdToolsFound {\n\t\t\t\tklog.V(1).Infof(\"rbd: map error %v, rbd output: %s\", err, string(output))\n\t\t\t\treturn \"\", fmt.Errorf(\"rbd: map failed %v, rbd output: %s\", err, string(output))\n\t\t\t}\n\t\t\tklog.V(3).Infof(\"rbd: map failed with %v, %s. Retrying with rbd-nbd\", err, string(output))\n\t\t\terrList := []error{err}\n\t\t\toutputList := output\n\t\t\toutput, err = execRbdMap(b, \"rbd-nbd\", mon)\n\t\t\tif err != nil {\n\t\t\t\terrList = append(errList, err)\n\t\t\t\toutputList = append(outputList, output...)\n\t\t\t\treturn \"\", fmt.Errorf(\"rbd: map failed %v, rbd output: %s\", errors.NewAggregate(errList), string(outputList))\n\t\t\t}\n\t\t\tdevicePath, mapped = waitForPath(b.Pool, b.Image, 10 /*maxRetries*/, true /*useNbdDrive*/)\n\t\t} else {\n\t\t\tdevicePath, mapped = waitForPath(b.Pool, b.Image, 10 /*maxRetries*/, false /*useNbdDriver*/)\n\t\t}\n\t\tif !mapped {\n\t\t\treturn \"\", fmt.Errorf(\"could not map image %s/%s, Timeout after 10s\", b.Pool, b.Image)\n\t\t}\n\t}\n\treturn devicePath, nil\n}","line":{"from":370,"to":466}} {"id":100012825,"name":"DetachDisk","signature":"func (util *rbdUtil) DetachDisk(plugin *rbdPlugin, deviceMountPath string, device string) error","file":"pkg/volume/rbd/rbd_util.go","code":"// DetachDisk detaches the disk from the node.\n// It detaches device from the node if device is provided, and removes the lock\n// if there is persisted RBD info under deviceMountPath.\nfunc (util *rbdUtil) DetachDisk(plugin *rbdPlugin, deviceMountPath string, device string) error {\n\tif len(device) == 0 {\n\t\treturn fmt.Errorf(\"DetachDisk failed , device is empty\")\n\t}\n\n\texec := plugin.host.GetExec(plugin.GetPluginName())\n\n\tvar rbdCmd string\n\n\t// Unlike map, we cannot fallthrough for unmap\n\t// the tool to unmap is based on device type\n\tif strings.HasPrefix(device, \"/dev/nbd\") {\n\t\trbdCmd = \"rbd-nbd\"\n\t} else {\n\t\trbdCmd = \"rbd\"\n\t}\n\n\t// rbd unmap\n\toutput, err := exec.Command(rbdCmd, \"unmap\", device).CombinedOutput()\n\tif err != nil {\n\t\treturn rbdErrors(err, fmt.Errorf(\"rbd: failed to unmap device %s, error %v, rbd output: %s\", device, err, string(output)))\n\t}\n\tklog.V(3).Infof(\"rbd: successfully unmap device %s\", device)\n\n\t// Currently, we don't persist rbd info on the disk, but for backward\n\t// compatibility, we need to clean it if found.\n\trbdFile := filepath.Join(deviceMountPath, \"rbd.json\")\n\texists, err := utilpath.Exists(utilpath.CheckFollowSymlink, rbdFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif exists {\n\t\tklog.V(3).Infof(\"rbd: old rbd.json is found under %s, cleaning it\", deviceMountPath)\n\t\terr = util.cleanOldRBDFile(plugin, rbdFile)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"rbd: failed to clean %s\", rbdFile)\n\t\t\treturn err\n\t\t}\n\t\tklog.V(3).Infof(\"rbd: successfully remove %s\", rbdFile)\n\t}\n\treturn nil\n}","line":{"from":468,"to":512}} {"id":100012826,"name":"DetachBlockDisk","signature":"func (util *rbdUtil) DetachBlockDisk(disk rbdDiskUnmapper, mapPath string) error","file":"pkg/volume/rbd/rbd_util.go","code":"// DetachBlockDisk detaches the disk from the node.\nfunc (util *rbdUtil) DetachBlockDisk(disk rbdDiskUnmapper, mapPath string) error {\n\n\tif pathExists, pathErr := mount.PathExists(mapPath); pathErr != nil {\n\t\treturn fmt.Errorf(\"error checking if path exists: %v\", pathErr)\n\t} else if !pathExists {\n\t\tklog.Warningf(\"Warning: Unmap skipped because path does not exist: %v\", mapPath)\n\t\treturn nil\n\t}\n\t// If we arrive here, device is no longer used, see if we need to logout of the target\n\tdevice, err := getBlockVolumeDevice(mapPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(device) == 0 {\n\t\treturn fmt.Errorf(\"DetachDisk failed , device is empty\")\n\t}\n\n\texec := disk.plugin.host.GetExec(disk.plugin.GetPluginName())\n\n\tvar rbdCmd string\n\n\t// Unlike map, we cannot fallthrough here.\n\t// Any nbd device must be unmapped by rbd-nbd\n\tif strings.HasPrefix(device, \"/dev/nbd\") {\n\t\trbdCmd = \"rbd-nbd\"\n\t\tklog.V(4).Infof(\"rbd: using rbd-nbd for unmap function\")\n\t} else {\n\t\trbdCmd = \"rbd\"\n\t\tklog.V(4).Infof(\"rbd: using rbd for unmap function\")\n\t}\n\n\t// rbd unmap\n\toutput, err := exec.Command(rbdCmd, \"unmap\", device).CombinedOutput()\n\tif err != nil {\n\t\treturn rbdErrors(err, fmt.Errorf(\"rbd: failed to unmap device %s, error %v, rbd output: %s\", device, err, string(output)))\n\t}\n\tklog.V(3).Infof(\"rbd: successfully unmap device %s\", device)\n\n\treturn nil\n}","line":{"from":514,"to":555}} {"id":100012827,"name":"cleanOldRBDFile","signature":"func (util *rbdUtil) cleanOldRBDFile(plugin *rbdPlugin, rbdFile string) error","file":"pkg/volume/rbd/rbd_util.go","code":"// cleanOldRBDFile read rbd info from rbd.json file and removes lock if found.\n// At last, it removes rbd.json file.\nfunc (util *rbdUtil) cleanOldRBDFile(plugin *rbdPlugin, rbdFile string) error {\n\tmounter := \u0026rbdMounter{\n\t\t// util.rbdUnlock needs it to run command.\n\t\trbd: newRBD(\"\", \"\", \"\", \"\", false, plugin, util),\n\t}\n\tfp, err := os.Open(rbdFile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"rbd: open err %s/%s\", rbdFile, err)\n\t}\n\tdefer fp.Close()\n\n\tdecoder := json.NewDecoder(fp)\n\tif err = decoder.Decode(mounter); err != nil {\n\t\treturn fmt.Errorf(\"rbd: decode err: %v\", err)\n\t}\n\n\t// Remove rbd lock if found.\n\t// The disk is not attached to this node anymore, so the lock on image\n\t// for this node can be removed safely.\n\terr = util.rbdUnlock(*mounter)\n\tif err == nil {\n\t\tos.Remove(rbdFile)\n\t}\n\treturn err\n}","line":{"from":557,"to":583}} {"id":100012828,"name":"CreateImage","signature":"func (util *rbdUtil) CreateImage(p *rbdVolumeProvisioner) (r *v1.RBDPersistentVolumeSource, size int, err error)","file":"pkg/volume/rbd/rbd_util.go","code":"// CreateImage creates a RBD image.\nfunc (util *rbdUtil) CreateImage(p *rbdVolumeProvisioner) (r *v1.RBDPersistentVolumeSource, size int, err error) {\n\tvar output []byte\n\tcapacity := p.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]\n\t// Convert to MB that rbd defaults on.\n\tsz, err := volumehelpers.RoundUpToMiBInt(capacity)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tvolSz := fmt.Sprintf(\"%d\", sz)\n\tmon := util.kernelRBDMonitorsOpt(p.Mon)\n\tif p.rbdMounter.imageFormat == rbdImageFormat2 {\n\t\tklog.V(4).Infof(\"rbd: create %s size %s format %s (features: %s) using mon %s, pool %s id %s key \u003cmasked\u003e\", p.rbdMounter.Image, volSz, p.rbdMounter.imageFormat, p.rbdMounter.imageFeatures, mon, p.rbdMounter.Pool, p.rbdMounter.adminID)\n\t} else {\n\t\tklog.V(4).Infof(\"rbd: create %s size %s format %s using mon %s, pool %s id %s key \u003cmasked\u003e\", p.rbdMounter.Image, volSz, p.rbdMounter.imageFormat, mon, p.rbdMounter.Pool, p.rbdMounter.adminID)\n\t}\n\targs := []string{\"create\", p.rbdMounter.Image, \"--size\", volSz, \"--pool\", p.rbdMounter.Pool, \"--id\", p.rbdMounter.adminID, \"-m\", mon, \"--key=\" + p.rbdMounter.adminSecret, \"--image-format\", p.rbdMounter.imageFormat}\n\tif p.rbdMounter.imageFormat == rbdImageFormat2 {\n\t\t// If no image features is provided, it results in empty string\n\t\t// which disable all RBD image format 2 features as expected.\n\t\tfeatures := strings.Join(p.rbdMounter.imageFeatures, \",\")\n\t\targs = append(args, \"--image-feature\", features)\n\t}\n\toutput, err = p.exec.Command(\"rbd\", args...).CombinedOutput()\n\n\tif err != nil {\n\t\tklog.Warningf(\"failed to create rbd image, output %v\", string(output))\n\t\treturn nil, 0, fmt.Errorf(\"failed to create rbd image: %v, command output: %s\", err, string(output))\n\t}\n\n\treturn \u0026v1.RBDPersistentVolumeSource{\n\t\tCephMonitors: p.rbdMounter.Mon,\n\t\tRBDImage: p.rbdMounter.Image,\n\t\tRBDPool: p.rbdMounter.Pool,\n\t}, sz, nil\n}","line":{"from":585,"to":620}} {"id":100012829,"name":"DeleteImage","signature":"func (util *rbdUtil) DeleteImage(p *rbdVolumeDeleter) error","file":"pkg/volume/rbd/rbd_util.go","code":"// DeleteImage deletes a RBD image.\nfunc (util *rbdUtil) DeleteImage(p *rbdVolumeDeleter) error {\n\tvar output []byte\n\tfound, rbdOutput, err := util.rbdStatus(p.rbdMounter)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error %v, rbd output: %v\", err, rbdOutput)\n\t}\n\tif found {\n\t\tklog.Infof(\"rbd %s is still being used \", p.rbdMounter.Image)\n\t\treturn fmt.Errorf(\"rbd image %s/%s is still being used, rbd output: %v\", p.rbdMounter.Pool, p.rbdMounter.Image, rbdOutput)\n\t}\n\t// rbd rm.\n\tmon := util.kernelRBDMonitorsOpt(p.rbdMounter.Mon)\n\tklog.V(4).Infof(\"rbd: rm %s using mon %s, pool %s id %s key \u003cmasked\u003e\", p.rbdMounter.Image, mon, p.rbdMounter.Pool, p.rbdMounter.adminID)\n\toutput, err = p.exec.Command(\"rbd\",\n\t\t\"rm\", p.rbdMounter.Image, \"--pool\", p.rbdMounter.Pool, \"--id\", p.rbdMounter.adminID, \"-m\", mon, \"--key=\"+p.rbdMounter.adminSecret).CombinedOutput()\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\tklog.Errorf(\"failed to delete rbd image: %v, command output: %s\", err, string(output))\n\treturn fmt.Errorf(\"error %v, rbd output: %v\", err, string(output))\n}","line":{"from":622,"to":644}} {"id":100012830,"name":"ExpandImage","signature":"func (util *rbdUtil) ExpandImage(rbdExpander *rbdVolumeExpander, oldSize resource.Quantity, newSize resource.Quantity) (resource.Quantity, error)","file":"pkg/volume/rbd/rbd_util.go","code":"// ExpandImage runs rbd resize command to resize the specified image.\nfunc (util *rbdUtil) ExpandImage(rbdExpander *rbdVolumeExpander, oldSize resource.Quantity, newSize resource.Quantity) (resource.Quantity, error) {\n\tvar output []byte\n\tvar err error\n\n\t// Convert to MB that rbd defaults on.\n\tsz, err := volumehelpers.RoundUpToMiBInt(newSize)\n\tif err != nil {\n\t\treturn oldSize, err\n\t}\n\n\tnewVolSz := fmt.Sprintf(\"%d\", sz)\n\tnewSizeQuant := resource.MustParse(fmt.Sprintf(\"%dMi\", sz))\n\n\t// Check the current size of rbd image, if equals to or greater that the new request size, do nothing.\n\tcurSize, infoErr := util.rbdInfo(rbdExpander.rbdMounter)\n\tif infoErr != nil {\n\t\treturn oldSize, fmt.Errorf(\"rbd info failed, error: %v\", infoErr)\n\t}\n\tif curSize \u003e= sz {\n\t\treturn newSizeQuant, nil\n\t}\n\n\t// rbd resize.\n\tmon := util.kernelRBDMonitorsOpt(rbdExpander.rbdMounter.Mon)\n\tklog.V(4).Infof(\"rbd: resize %s using mon %s, pool %s id %s key \u003cmasked\u003e\", rbdExpander.rbdMounter.Image, mon, rbdExpander.rbdMounter.Pool, rbdExpander.rbdMounter.adminID)\n\toutput, err = rbdExpander.exec.Command(\"rbd\",\n\t\t\"resize\", rbdExpander.rbdMounter.Image, \"--size\", newVolSz, \"--pool\", rbdExpander.rbdMounter.Pool, \"--id\", rbdExpander.rbdMounter.adminID, \"-m\", mon, \"--key=\"+rbdExpander.rbdMounter.adminSecret).CombinedOutput()\n\tif err == nil {\n\t\treturn newSizeQuant, nil\n\t}\n\n\tklog.Errorf(\"failed to resize rbd image: %v, command output: %s\", err, string(output))\n\treturn oldSize, err\n}","line":{"from":646,"to":680}} {"id":100012831,"name":"rbdInfo","signature":"func (util *rbdUtil) rbdInfo(b *rbdMounter) (int, error)","file":"pkg/volume/rbd/rbd_util.go","code":"// rbdInfo runs `rbd info` command to get the current image size in MB.\nfunc (util *rbdUtil) rbdInfo(b *rbdMounter) (int, error) {\n\tvar err error\n\tvar output []byte\n\n\t// If we don't have admin id/secret (e.g. attaching), fallback to user id/secret.\n\tid := b.adminID\n\tsecret := b.adminSecret\n\tif id == \"\" {\n\t\tid = b.ID\n\t\tsecret = b.Secret\n\t}\n\n\tmon := util.kernelRBDMonitorsOpt(b.Mon)\n\t// cmd \"rbd info\" get the image info with the following output:\n\t//\n\t// # image exists (exit=0)\n\t// rbd info volume-4a5bcc8b-2b55-46da-ba04-0d3dc5227f08\n\t// size 1024 MB in 256 objects\n\t// order 22 (4096 kB objects)\n\t// \t block_name_prefix: rbd_data.1253ac238e1f29\n\t// format: 2\n\t// ...\n\t//\n\t// rbd info volume-4a5bcc8b-2b55-46da-ba04-0d3dc5227f08 --format json\n\t// {\"name\":\"volume-4a5bcc8b-2b55-46da-ba04-0d3dc5227f08\",\"size\":1073741824,\"objects\":256,\"order\":22,\"object_size\":4194304,\"block_name_prefix\":\"rbd_data.1253ac238e1f29\",\"format\":2,\"features\":[\"layering\",\"exclusive-lock\",\"object-map\",\"fast-diff\",\"deep-flatten\"],\"flags\":[]}\n\t//\n\t//\n\t// # image does not exist (exit=2)\n\t// rbd: error opening image 1234: (2) No such file or directory\n\t//\n\tklog.V(4).Infof(\"rbd: info %s using mon %s, pool %s id %s key \u003cmasked\u003e\", b.Image, mon, b.Pool, id)\n\toutput, err = b.exec.Command(\"rbd\",\n\t\t\"info\", b.Image, \"--pool\", b.Pool, \"-m\", mon, \"--id\", id, \"--key=\"+secret, \"-k=/dev/null\", \"--format=json\").Output()\n\n\tif err, ok := err.(*exec.Error); ok {\n\t\tif err.Err == exec.ErrNotFound {\n\t\t\tklog.Errorf(\"rbd cmd not found\")\n\t\t\t// fail fast if rbd command is not found.\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\t// If command never succeed, returns its last error.\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif len(output) == 0 {\n\t\treturn 0, fmt.Errorf(\"can not get image size info %s: %s\", b.Image, string(output))\n\t}\n\n\treturn getRbdImageSize(output)\n}","line":{"from":682,"to":735}} {"id":100012832,"name":"getRbdImageSize","signature":"func getRbdImageSize(output []byte) (int, error)","file":"pkg/volume/rbd/rbd_util.go","code":"func getRbdImageSize(output []byte) (int, error) {\n\tinfo := struct {\n\t\tSize int64 `json:\"size\"`\n\t}{}\n\tif err := json.Unmarshal(output, \u0026info); err != nil {\n\t\treturn 0, fmt.Errorf(\"parse rbd info output failed: %s, %v\", string(output), err)\n\t}\n\treturn int(info.Size / rbdImageSizeUnitMiB), nil\n}","line":{"from":737,"to":745}} {"id":100012833,"name":"rbdStatus","signature":"func (util *rbdUtil) rbdStatus(b *rbdMounter) (bool, string, error)","file":"pkg/volume/rbd/rbd_util.go","code":"// rbdStatus runs `rbd status` command to check if there is watcher on the image.\nfunc (util *rbdUtil) rbdStatus(b *rbdMounter) (bool, string, error) {\n\tvar err error\n\tvar output string\n\tvar cmd []byte\n\n\t// If we don't have admin id/secret (e.g. attaching), fallback to user id/secret.\n\tid := b.adminID\n\tsecret := b.adminSecret\n\tif id == \"\" {\n\t\tid = b.ID\n\t\tsecret = b.Secret\n\t}\n\n\tmon := util.kernelRBDMonitorsOpt(b.Mon)\n\t// cmd \"rbd status\" list the rbd client watch with the following output:\n\t//\n\t// # there is a watcher (exit=0)\n\t// Watchers:\n\t// watcher=10.16.153.105:0/710245699 client.14163 cookie=1\n\t//\n\t// # there is no watcher (exit=0)\n\t// Watchers: none\n\t//\n\t// Otherwise, exit is non-zero, for example:\n\t//\n\t// # image does not exist (exit=2)\n\t// rbd: error opening image kubernetes-dynamic-pvc-\u003cUUID\u003e: (2) No such file or directory\n\t//\n\tklog.V(4).Infof(\"rbd: status %s using mon %s, pool %s id %s key \u003cmasked\u003e\", b.Image, mon, b.Pool, id)\n\tcmd, err = b.exec.Command(\"rbd\",\n\t\t\"status\", b.Image, \"--pool\", b.Pool, \"-m\", mon, \"--id\", id, \"--key=\"+secret).CombinedOutput()\n\toutput = string(cmd)\n\n\tif err, ok := err.(*exec.Error); ok {\n\t\tif err.Err == exec.ErrNotFound {\n\t\t\tklog.Errorf(\"rbd cmd not found\")\n\t\t\t// fail fast if command not found\n\t\t\treturn false, output, err\n\t\t}\n\t}\n\n\t// If command never succeed, returns its last error.\n\tif err != nil {\n\t\treturn false, output, err\n\t}\n\n\tif strings.Contains(output, imageWatcherStr) {\n\t\tklog.V(4).Infof(\"rbd: watchers on %s: %s\", b.Image, output)\n\t\treturn true, output, nil\n\t}\n\tklog.Warningf(\"rbd: no watchers on %s\", b.Image)\n\treturn false, output, nil\n}","line":{"from":747,"to":800}} {"id":100012834,"name":"getRbdImageInfo","signature":"func getRbdImageInfo(deviceMountPath string) (*rbdImageInfo, error)","file":"pkg/volume/rbd/rbd_util.go","code":"// getRbdImageInfo try to get rbdImageInfo from deviceMountPath.\nfunc getRbdImageInfo(deviceMountPath string) (*rbdImageInfo, error) {\n\tdeviceMountedPathSeps := strings.Split(filepath.Base(deviceMountPath), \"-image-\")\n\tif len(deviceMountedPathSeps) != 2 {\n\t\treturn nil, fmt.Errorf(\"can't found devicePath for %s \", deviceMountPath)\n\t}\n\treturn \u0026rbdImageInfo{\n\t\tpool: deviceMountedPathSeps[0],\n\t\tname: deviceMountedPathSeps[1],\n\t}, nil\n}","line":{"from":802,"to":812}} {"id":100012835,"name":"ProbeVolumePlugins","signature":"func ProbeVolumePlugins() []volume.VolumePlugin","file":"pkg/volume/secret/secret.go","code":"// ProbeVolumePlugins is the entry point for plugin detection in a package.\nfunc ProbeVolumePlugins() []volume.VolumePlugin {\n\treturn []volume.VolumePlugin{\u0026secretPlugin{}}\n}","line":{"from":34,"to":37}} {"id":100012836,"name":"wrappedVolumeSpec","signature":"func wrappedVolumeSpec() volume.Spec","file":"pkg/volume/secret/secret.go","code":"func wrappedVolumeSpec() volume.Spec {\n\treturn volume.Spec{\n\t\tVolume: \u0026v1.Volume{VolumeSource: v1.VolumeSource{EmptyDir: \u0026v1.EmptyDirVolumeSource{Medium: v1.StorageMediumMemory}}},\n\t}\n}","line":{"from":51,"to":55}} {"id":100012837,"name":"getPath","signature":"func getPath(uid types.UID, volName string, host volume.VolumeHost) string","file":"pkg/volume/secret/secret.go","code":"func getPath(uid types.UID, volName string, host volume.VolumeHost) string {\n\treturn host.GetPodVolumeDir(uid, utilstrings.EscapeQualifiedName(secretPluginName), volName)\n}","line":{"from":57,"to":59}} {"id":100012838,"name":"Init","signature":"func (plugin *secretPlugin) Init(host volume.VolumeHost) error","file":"pkg/volume/secret/secret.go","code":"func (plugin *secretPlugin) Init(host volume.VolumeHost) error {\n\tplugin.host = host\n\tplugin.getSecret = host.GetSecretFunc()\n\treturn nil\n}","line":{"from":61,"to":65}} {"id":100012839,"name":"GetPluginName","signature":"func (plugin *secretPlugin) GetPluginName() string","file":"pkg/volume/secret/secret.go","code":"func (plugin *secretPlugin) GetPluginName() string {\n\treturn secretPluginName\n}","line":{"from":67,"to":69}} {"id":100012840,"name":"GetVolumeName","signature":"func (plugin *secretPlugin) GetVolumeName(spec *volume.Spec) (string, error)","file":"pkg/volume/secret/secret.go","code":"func (plugin *secretPlugin) GetVolumeName(spec *volume.Spec) (string, error) {\n\tvolumeSource, _ := getVolumeSource(spec)\n\tif volumeSource == nil {\n\t\treturn \"\", fmt.Errorf(\"Spec does not reference a Secret volume type\")\n\t}\n\n\treturn volumeSource.SecretName, nil\n}","line":{"from":71,"to":78}} {"id":100012841,"name":"CanSupport","signature":"func (plugin *secretPlugin) CanSupport(spec *volume.Spec) bool","file":"pkg/volume/secret/secret.go","code":"func (plugin *secretPlugin) CanSupport(spec *volume.Spec) bool {\n\treturn spec.Volume != nil \u0026\u0026 spec.Volume.Secret != nil\n}","line":{"from":80,"to":82}} {"id":100012842,"name":"RequiresRemount","signature":"func (plugin *secretPlugin) RequiresRemount(spec *volume.Spec) bool","file":"pkg/volume/secret/secret.go","code":"func (plugin *secretPlugin) RequiresRemount(spec *volume.Spec) bool {\n\treturn true\n}","line":{"from":84,"to":86}} {"id":100012843,"name":"SupportsMountOption","signature":"func (plugin *secretPlugin) SupportsMountOption() bool","file":"pkg/volume/secret/secret.go","code":"func (plugin *secretPlugin) SupportsMountOption() bool {\n\treturn false\n}","line":{"from":88,"to":90}} {"id":100012844,"name":"SupportsBulkVolumeVerification","signature":"func (plugin *secretPlugin) SupportsBulkVolumeVerification() bool","file":"pkg/volume/secret/secret.go","code":"func (plugin *secretPlugin) SupportsBulkVolumeVerification() bool {\n\treturn false\n}","line":{"from":92,"to":94}} {"id":100012845,"name":"SupportsSELinuxContextMount","signature":"func (plugin *secretPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/secret/secret.go","code":"func (plugin *secretPlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error) {\n\treturn false, nil\n}","line":{"from":96,"to":98}} {"id":100012846,"name":"NewMounter","signature":"func (plugin *secretPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error)","file":"pkg/volume/secret/secret.go","code":"func (plugin *secretPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, opts volume.VolumeOptions) (volume.Mounter, error) {\n\treturn \u0026secretVolumeMounter{\n\t\tsecretVolume: \u0026secretVolume{\n\t\t\tspec.Name(),\n\t\t\tpod.UID,\n\t\t\tplugin,\n\t\t\tplugin.host.GetMounter(plugin.GetPluginName()),\n\t\t\tvolume.NewCachedMetrics(volume.NewMetricsDu(getPath(pod.UID, spec.Name(), plugin.host))),\n\t\t},\n\t\tsource: *spec.Volume.Secret,\n\t\tpod: *pod,\n\t\topts: \u0026opts,\n\t\tgetSecret: plugin.getSecret,\n\t}, nil\n}","line":{"from":100,"to":114}} {"id":100012847,"name":"NewUnmounter","signature":"func (plugin *secretPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error)","file":"pkg/volume/secret/secret.go","code":"func (plugin *secretPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error) {\n\treturn \u0026secretVolumeUnmounter{\n\t\t\u0026secretVolume{\n\t\t\tvolName,\n\t\t\tpodUID,\n\t\t\tplugin,\n\t\t\tplugin.host.GetMounter(plugin.GetPluginName()),\n\t\t\tvolume.NewCachedMetrics(volume.NewMetricsDu(getPath(podUID, volName, plugin.host))),\n\t\t},\n\t}, nil\n}","line":{"from":116,"to":126}} {"id":100012848,"name":"ConstructVolumeSpec","signature":"func (plugin *secretPlugin) ConstructVolumeSpec(volName, mountPath string) (volume.ReconstructedVolume, error)","file":"pkg/volume/secret/secret.go","code":"func (plugin *secretPlugin) ConstructVolumeSpec(volName, mountPath string) (volume.ReconstructedVolume, error) {\n\tsecretVolume := \u0026v1.Volume{\n\t\tName: volName,\n\t\tVolumeSource: v1.VolumeSource{\n\t\t\tSecret: \u0026v1.SecretVolumeSource{\n\t\t\t\tSecretName: volName,\n\t\t\t},\n\t\t},\n\t}\n\treturn volume.ReconstructedVolume{\n\t\tSpec: volume.NewSpecFromVolume(secretVolume),\n\t}, nil\n}","line":{"from":128,"to":140}} {"id":100012849,"name":"GetPath","signature":"func (sv *secretVolume) GetPath() string","file":"pkg/volume/secret/secret.go","code":"func (sv *secretVolume) GetPath() string {\n\treturn getPath(sv.podUID, sv.volName, sv.plugin.host)\n}","line":{"from":152,"to":154}} {"id":100012850,"name":"GetAttributes","signature":"func (sv *secretVolume) GetAttributes() volume.Attributes","file":"pkg/volume/secret/secret.go","code":"func (sv *secretVolume) GetAttributes() volume.Attributes {\n\treturn volume.Attributes{\n\t\tReadOnly: true,\n\t\tManaged: true,\n\t\tSELinuxRelabel: true,\n\t}\n}","line":{"from":169,"to":175}} {"id":100012851,"name":"SetUp","signature":"func (b *secretVolumeMounter) SetUp(mounterArgs volume.MounterArgs) error","file":"pkg/volume/secret/secret.go","code":"func (b *secretVolumeMounter) SetUp(mounterArgs volume.MounterArgs) error {\n\treturn b.SetUpAt(b.GetPath(), mounterArgs)\n}","line":{"from":177,"to":179}} {"id":100012852,"name":"SetUpAt","signature":"func (b *secretVolumeMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error","file":"pkg/volume/secret/secret.go","code":"func (b *secretVolumeMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {\n\tklog.V(3).Infof(\"Setting up volume %v for pod %v at %v\", b.volName, b.pod.UID, dir)\n\n\t// Wrap EmptyDir, let it do the setup.\n\twrapped, err := b.plugin.host.NewWrapperMounter(b.volName, wrappedVolumeSpec(), \u0026b.pod, *b.opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\toptional := b.source.Optional != nil \u0026\u0026 *b.source.Optional\n\tsecret, err := b.getSecret(b.pod.Namespace, b.source.SecretName)\n\tif err != nil {\n\t\tif !(errors.IsNotFound(err) \u0026\u0026 optional) {\n\t\t\tklog.Errorf(\"Couldn't get secret %v/%v: %v\", b.pod.Namespace, b.source.SecretName, err)\n\t\t\treturn err\n\t\t}\n\t\tsecret = \u0026v1.Secret{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: b.pod.Namespace,\n\t\t\t\tName: b.source.SecretName,\n\t\t\t},\n\t\t}\n\t}\n\n\ttotalBytes := totalSecretBytes(secret)\n\tklog.V(3).Infof(\"Received secret %v/%v containing (%v) pieces of data, %v total bytes\",\n\t\tb.pod.Namespace,\n\t\tb.source.SecretName,\n\t\tlen(secret.Data),\n\t\ttotalBytes)\n\n\tpayload, err := MakePayload(b.source.Items, secret, b.source.DefaultMode, optional)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsetupSuccess := false\n\tif err := wrapped.SetUpAt(dir, mounterArgs); err != nil {\n\t\treturn err\n\t}\n\tif err := volumeutil.MakeNestedMountpoints(b.volName, dir, b.pod); err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\t// Clean up directories if setup fails\n\t\tif !setupSuccess {\n\t\t\tunmounter, unmountCreateErr := b.plugin.NewUnmounter(b.volName, b.podUID)\n\t\t\tif unmountCreateErr != nil {\n\t\t\t\tklog.Errorf(\"error cleaning up mount %s after failure. Create unmounter failed with %v\", b.volName, unmountCreateErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\ttearDownErr := unmounter.TearDown()\n\t\t\tif tearDownErr != nil {\n\t\t\t\tklog.Errorf(\"error tearing down volume %s with : %v\", b.volName, tearDownErr)\n\t\t\t}\n\t\t}\n\t}()\n\n\twriterContext := fmt.Sprintf(\"pod %v/%v volume %v\", b.pod.Namespace, b.pod.Name, b.volName)\n\twriter, err := volumeutil.NewAtomicWriter(dir, writerContext)\n\tif err != nil {\n\t\tklog.Errorf(\"Error creating atomic writer: %v\", err)\n\t\treturn err\n\t}\n\n\tsetPerms := func(_ string) error {\n\t\t// This may be the first time writing and new files get created outside the timestamp subdirectory:\n\t\t// change the permissions on the whole volume and not only in the timestamp directory.\n\t\treturn volume.SetVolumeOwnership(b, dir, mounterArgs.FsGroup, nil /*fsGroupChangePolicy*/, volumeutil.FSGroupCompleteHook(b.plugin, nil))\n\t}\n\terr = writer.Write(payload, setPerms)\n\tif err != nil {\n\t\tklog.Errorf(\"Error writing payload to dir: %v\", err)\n\t\treturn err\n\t}\n\n\tsetupSuccess = true\n\treturn nil\n}","line":{"from":181,"to":260}} {"id":100012853,"name":"MakePayload","signature":"func MakePayload(mappings []v1.KeyToPath, secret *v1.Secret, defaultMode *int32, optional bool) (map[string]volumeutil.FileProjection, error)","file":"pkg/volume/secret/secret.go","code":"// MakePayload function is exported so that it can be called from the projection volume driver\nfunc MakePayload(mappings []v1.KeyToPath, secret *v1.Secret, defaultMode *int32, optional bool) (map[string]volumeutil.FileProjection, error) {\n\tif defaultMode == nil {\n\t\treturn nil, fmt.Errorf(\"no defaultMode used, not even the default value for it\")\n\t}\n\n\tpayload := make(map[string]volumeutil.FileProjection, len(secret.Data))\n\tvar fileProjection volumeutil.FileProjection\n\n\tif len(mappings) == 0 {\n\t\tfor name, data := range secret.Data {\n\t\t\tfileProjection.Data = []byte(data)\n\t\t\tfileProjection.Mode = *defaultMode\n\t\t\tpayload[name] = fileProjection\n\t\t}\n\t} else {\n\t\tfor _, ktp := range mappings {\n\t\t\tcontent, ok := secret.Data[ktp.Key]\n\t\t\tif !ok {\n\t\t\t\tif optional {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\terrMsg := fmt.Sprintf(\"references non-existent secret key: %s\", ktp.Key)\n\t\t\t\tklog.Errorf(errMsg)\n\t\t\t\treturn nil, fmt.Errorf(errMsg)\n\t\t\t}\n\n\t\t\tfileProjection.Data = []byte(content)\n\t\t\tif ktp.Mode != nil {\n\t\t\t\tfileProjection.Mode = *ktp.Mode\n\t\t\t} else {\n\t\t\t\tfileProjection.Mode = *defaultMode\n\t\t\t}\n\t\t\tpayload[ktp.Path] = fileProjection\n\t\t}\n\t}\n\treturn payload, nil\n}","line":{"from":262,"to":299}} {"id":100012854,"name":"totalSecretBytes","signature":"func totalSecretBytes(secret *v1.Secret) int","file":"pkg/volume/secret/secret.go","code":"func totalSecretBytes(secret *v1.Secret) int {\n\ttotalSize := 0\n\tfor _, bytes := range secret.Data {\n\t\ttotalSize += len(bytes)\n\t}\n\n\treturn totalSize\n}","line":{"from":301,"to":308}} {"id":100012855,"name":"TearDown","signature":"func (c *secretVolumeUnmounter) TearDown() error","file":"pkg/volume/secret/secret.go","code":"func (c *secretVolumeUnmounter) TearDown() error {\n\treturn c.TearDownAt(c.GetPath())\n}","line":{"from":317,"to":319}} {"id":100012856,"name":"TearDownAt","signature":"func (c *secretVolumeUnmounter) TearDownAt(dir string) error","file":"pkg/volume/secret/secret.go","code":"func (c *secretVolumeUnmounter) TearDownAt(dir string) error {\n\treturn volumeutil.UnmountViaEmptyDir(dir, c.plugin.host, c.volName, wrappedVolumeSpec(), c.podUID)\n}","line":{"from":321,"to":323}} {"id":100012857,"name":"getVolumeSource","signature":"func getVolumeSource(spec *volume.Spec) (*v1.SecretVolumeSource, bool)","file":"pkg/volume/secret/secret.go","code":"func getVolumeSource(spec *volume.Spec) (*v1.SecretVolumeSource, bool) {\n\tvar readOnly bool\n\tvar volumeSource *v1.SecretVolumeSource\n\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.Secret != nil {\n\t\tvolumeSource = spec.Volume.Secret\n\t\treadOnly = spec.ReadOnly\n\t}\n\n\treturn volumeSource, readOnly\n}","line":{"from":325,"to":335}} {"id":100012858,"name":"NewAtomicWriter","signature":"func NewAtomicWriter(targetDir string, logContext string) (*AtomicWriter, error)","file":"pkg/volume/util/atomic_writer.go","code":"// NewAtomicWriter creates a new AtomicWriter configured to write to the given\n// target directory, or returns an error if the target directory does not exist.\nfunc NewAtomicWriter(targetDir string, logContext string) (*AtomicWriter, error) {\n\t_, err := os.Stat(targetDir)\n\tif os.IsNotExist(err) {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026AtomicWriter{targetDir: targetDir, logContext: logContext}, nil\n}","line":{"from":71,"to":80}} {"id":100012859,"name":"Write","signature":"func (w *AtomicWriter) Write(payload map[string]FileProjection, setPerms func(subPath string) error) error","file":"pkg/volume/util/atomic_writer.go","code":"// Write does an atomic projection of the given payload into the writer's target\n// directory. Input paths must not begin with '..'.\n// setPerms is an optional pointer to a function that caller can provide to set the\n// permissions of the newly created files before they are published. The function is\n// passed subPath which is the name of the timestamped directory that was created\n// under target directory.\n//\n// The Write algorithm is:\n//\n// 1. The payload is validated; if the payload is invalid, the function returns\n//\n// 2. The current timestamped directory is detected by reading the data directory\n// symlink\n//\n// 3. The old version of the volume is walked to determine whether any\n// portion of the payload was deleted and is still present on disk.\n//\n// 4. The data in the current timestamped directory is compared to the projected\n// data to determine if an update is required.\n//\n// 5. A new timestamped dir is created.\n//\n// 6. The payload is written to the new timestamped directory.\n//\n// 7. Permissions are set (if setPerms is not nil) on the new timestamped directory and files.\n//\n// 8. A symlink to the new timestamped directory ..data_tmp is created that will\n// become the new data directory.\n//\n// 9. The new data directory symlink is renamed to the data directory; rename is atomic.\n//\n// 10. Symlinks and directory for new user-visible files are created (if needed).\n//\n// For example, consider the files:\n// \u003ctarget-dir\u003e/podName\n// \u003ctarget-dir\u003e/user/labels\n// \u003ctarget-dir\u003e/k8s/annotations\n//\n// The user visible files are symbolic links into the internal data directory:\n// \u003ctarget-dir\u003e/podName -\u003e ..data/podName\n// \u003ctarget-dir\u003e/usr -\u003e ..data/usr\n// \u003ctarget-dir\u003e/k8s -\u003e ..data/k8s\n//\n// The data directory itself is a link to a timestamped directory with\n// the real data:\n// \u003ctarget-dir\u003e/..data -\u003e ..2016_02_01_15_04_05.12345678/\n// NOTE(claudiub): We need to create these symlinks AFTER we've finished creating and\n// linking everything else. On Windows, if a target does not exist, the created symlink\n// will not work properly if the target ends up being a directory.\n//\n// 11. Old paths are removed from the user-visible portion of the target directory.\n//\n// 12. The previous timestamped directory is removed, if it exists.\nfunc (w *AtomicWriter) Write(payload map[string]FileProjection, setPerms func(subPath string) error) error {\n\t// (1)\n\tcleanPayload, err := validatePayload(payload)\n\tif err != nil {\n\t\tklog.Errorf(\"%s: invalid payload: %v\", w.logContext, err)\n\t\treturn err\n\t}\n\n\t// (2)\n\tdataDirPath := filepath.Join(w.targetDir, dataDirName)\n\toldTsDir, err := os.Readlink(dataDirPath)\n\tif err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\tklog.Errorf(\"%s: error reading link for data directory: %v\", w.logContext, err)\n\t\t\treturn err\n\t\t}\n\t\t// although Readlink() returns \"\" on err, don't be fragile by relying on it (since it's not specified in docs)\n\t\t// empty oldTsDir indicates that it didn't exist\n\t\toldTsDir = \"\"\n\t}\n\toldTsPath := filepath.Join(w.targetDir, oldTsDir)\n\n\tvar pathsToRemove sets.String\n\t// if there was no old version, there's nothing to remove\n\tif len(oldTsDir) != 0 {\n\t\t// (3)\n\t\tpathsToRemove, err = w.pathsToRemove(cleanPayload, oldTsPath)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"%s: error determining user-visible files to remove: %v\", w.logContext, err)\n\t\t\treturn err\n\t\t}\n\n\t\t// (4)\n\t\tif should, err := shouldWritePayload(cleanPayload, oldTsPath); err != nil {\n\t\t\tklog.Errorf(\"%s: error determining whether payload should be written to disk: %v\", w.logContext, err)\n\t\t\treturn err\n\t\t} else if !should \u0026\u0026 len(pathsToRemove) == 0 {\n\t\t\tklog.V(4).Infof(\"%s: no update required for target directory %v\", w.logContext, w.targetDir)\n\t\t\treturn nil\n\t\t} else {\n\t\t\tklog.V(4).Infof(\"%s: write required for target directory %v\", w.logContext, w.targetDir)\n\t\t}\n\t}\n\n\t// (5)\n\ttsDir, err := w.newTimestampDir()\n\tif err != nil {\n\t\tklog.V(4).Infof(\"%s: error creating new ts data directory: %v\", w.logContext, err)\n\t\treturn err\n\t}\n\ttsDirName := filepath.Base(tsDir)\n\n\t// (6)\n\tif err = w.writePayloadToDir(cleanPayload, tsDir); err != nil {\n\t\tklog.Errorf(\"%s: error writing payload to ts data directory %s: %v\", w.logContext, tsDir, err)\n\t\treturn err\n\t}\n\tklog.V(4).Infof(\"%s: performed write of new data to ts data directory: %s\", w.logContext, tsDir)\n\n\t// (7)\n\tif setPerms != nil {\n\t\tif err := setPerms(tsDirName); err != nil {\n\t\t\tklog.Errorf(\"%s: error applying ownership settings: %v\", w.logContext, err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// (8)\n\tnewDataDirPath := filepath.Join(w.targetDir, newDataDirName)\n\tif err = os.Symlink(tsDirName, newDataDirPath); err != nil {\n\t\tos.RemoveAll(tsDir)\n\t\tklog.Errorf(\"%s: error creating symbolic link for atomic update: %v\", w.logContext, err)\n\t\treturn err\n\t}\n\n\t// (9)\n\tif runtime.GOOS == \"windows\" {\n\t\tos.Remove(dataDirPath)\n\t\terr = os.Symlink(tsDirName, dataDirPath)\n\t\tos.Remove(newDataDirPath)\n\t} else {\n\t\terr = os.Rename(newDataDirPath, dataDirPath)\n\t}\n\tif err != nil {\n\t\tos.Remove(newDataDirPath)\n\t\tos.RemoveAll(tsDir)\n\t\tklog.Errorf(\"%s: error renaming symbolic link for data directory %s: %v\", w.logContext, newDataDirPath, err)\n\t\treturn err\n\t}\n\n\t// (10)\n\tif err = w.createUserVisibleFiles(cleanPayload); err != nil {\n\t\tklog.Errorf(\"%s: error creating visible symlinks in %s: %v\", w.logContext, w.targetDir, err)\n\t\treturn err\n\t}\n\n\t// (11)\n\tif err = w.removeUserVisiblePaths(pathsToRemove); err != nil {\n\t\tklog.Errorf(\"%s: error removing old visible symlinks: %v\", w.logContext, err)\n\t\treturn err\n\t}\n\n\t// (12)\n\tif len(oldTsDir) \u003e 0 {\n\t\tif err = os.RemoveAll(oldTsPath); err != nil {\n\t\t\tklog.Errorf(\"%s: error removing old data directory %s: %v\", w.logContext, oldTsDir, err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":87,"to":251}} {"id":100012860,"name":"validatePayload","signature":"func validatePayload(payload map[string]FileProjection) (map[string]FileProjection, error)","file":"pkg/volume/util/atomic_writer.go","code":"// validatePayload returns an error if any path in the payload returns a copy of the payload with the paths cleaned.\nfunc validatePayload(payload map[string]FileProjection) (map[string]FileProjection, error) {\n\tcleanPayload := make(map[string]FileProjection)\n\tfor k, content := range payload {\n\t\tif err := validatePath(k); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tcleanPayload[filepath.Clean(k)] = content\n\t}\n\n\treturn cleanPayload, nil\n}","line":{"from":253,"to":265}} {"id":100012861,"name":"validatePath","signature":"func validatePath(targetPath string) error","file":"pkg/volume/util/atomic_writer.go","code":"// validatePath validates a single path, returning an error if the path is\n// invalid. paths may not:\n//\n// 1. be absolute\n// 2. contain '..' as an element\n// 3. start with '..'\n// 4. contain filenames larger than 255 characters\n// 5. be longer than 4096 characters\nfunc validatePath(targetPath string) error {\n\t// TODO: somehow unify this with the similar api validation,\n\t// validateVolumeSourcePath; the error semantics are just different enough\n\t// from this that it was time-prohibitive trying to find the right\n\t// refactoring to re-use.\n\tif targetPath == \"\" {\n\t\treturn fmt.Errorf(\"invalid path: must not be empty: %q\", targetPath)\n\t}\n\tif path.IsAbs(targetPath) {\n\t\treturn fmt.Errorf(\"invalid path: must be relative path: %s\", targetPath)\n\t}\n\n\tif len(targetPath) \u003e maxPathLength {\n\t\treturn fmt.Errorf(\"invalid path: must be less than or equal to %d characters\", maxPathLength)\n\t}\n\n\titems := strings.Split(targetPath, string(os.PathSeparator))\n\tfor _, item := range items {\n\t\tif item == \"..\" {\n\t\t\treturn fmt.Errorf(\"invalid path: must not contain '..': %s\", targetPath)\n\t\t}\n\t\tif len(item) \u003e maxFileNameLength {\n\t\t\treturn fmt.Errorf(\"invalid path: filenames must be less than or equal to %d characters\", maxFileNameLength)\n\t\t}\n\t}\n\tif strings.HasPrefix(items[0], \"..\") \u0026\u0026 len(items[0]) \u003e 2 {\n\t\treturn fmt.Errorf(\"invalid path: must not start with '..': %s\", targetPath)\n\t}\n\n\treturn nil\n}","line":{"from":267,"to":305}} {"id":100012862,"name":"shouldWritePayload","signature":"func shouldWritePayload(payload map[string]FileProjection, oldTsDir string) (bool, error)","file":"pkg/volume/util/atomic_writer.go","code":"// shouldWritePayload returns whether the payload should be written to disk.\nfunc shouldWritePayload(payload map[string]FileProjection, oldTsDir string) (bool, error) {\n\tfor userVisiblePath, fileProjection := range payload {\n\t\tshouldWrite, err := shouldWriteFile(filepath.Join(oldTsDir, userVisiblePath), fileProjection.Data)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tif shouldWrite {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, nil\n}","line":{"from":307,"to":321}} {"id":100012863,"name":"shouldWriteFile","signature":"func shouldWriteFile(path string, content []byte) (bool, error)","file":"pkg/volume/util/atomic_writer.go","code":"// shouldWriteFile returns whether a new version of a file should be written to disk.\nfunc shouldWriteFile(path string, content []byte) (bool, error) {\n\t_, err := os.Lstat(path)\n\tif os.IsNotExist(err) {\n\t\treturn true, nil\n\t}\n\n\tcontentOnFs, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn !bytes.Equal(content, contentOnFs), nil\n}","line":{"from":323,"to":336}} {"id":100012864,"name":"pathsToRemove","signature":"func (w *AtomicWriter) pathsToRemove(payload map[string]FileProjection, oldTsDir string) (sets.String, error)","file":"pkg/volume/util/atomic_writer.go","code":"// pathsToRemove walks the current version of the data directory and\n// determines which paths should be removed (if any) after the payload is\n// written to the target directory.\nfunc (w *AtomicWriter) pathsToRemove(payload map[string]FileProjection, oldTsDir string) (sets.String, error) {\n\tpaths := sets.NewString()\n\tvisitor := func(path string, info os.FileInfo, err error) error {\n\t\trelativePath := strings.TrimPrefix(path, oldTsDir)\n\t\trelativePath = strings.TrimPrefix(relativePath, string(os.PathSeparator))\n\t\tif relativePath == \"\" {\n\t\t\treturn nil\n\t\t}\n\n\t\tpaths.Insert(relativePath)\n\t\treturn nil\n\t}\n\n\terr := filepath.Walk(oldTsDir, visitor)\n\tif os.IsNotExist(err) {\n\t\treturn nil, nil\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\tklog.V(5).Infof(\"%s: current paths: %+v\", w.targetDir, paths.List())\n\n\tnewPaths := sets.NewString()\n\tfor file := range payload {\n\t\t// add all subpaths for the payload to the set of new paths\n\t\t// to avoid attempting to remove non-empty dirs\n\t\tfor subPath := file; subPath != \"\"; {\n\t\t\tnewPaths.Insert(subPath)\n\t\t\tsubPath, _ = filepath.Split(subPath)\n\t\t\tsubPath = strings.TrimSuffix(subPath, string(os.PathSeparator))\n\t\t}\n\t}\n\tklog.V(5).Infof(\"%s: new paths: %+v\", w.targetDir, newPaths.List())\n\n\tresult := paths.Difference(newPaths)\n\tklog.V(5).Infof(\"%s: paths to remove: %+v\", w.targetDir, result)\n\n\treturn result, nil\n}","line":{"from":338,"to":378}} {"id":100012865,"name":"newTimestampDir","signature":"func (w *AtomicWriter) newTimestampDir() (string, error)","file":"pkg/volume/util/atomic_writer.go","code":"// newTimestampDir creates a new timestamp directory\nfunc (w *AtomicWriter) newTimestampDir() (string, error) {\n\ttsDir, err := ioutil.TempDir(w.targetDir, time.Now().UTC().Format(\"..2006_01_02_15_04_05.\"))\n\tif err != nil {\n\t\tklog.Errorf(\"%s: unable to create new temp directory: %v\", w.logContext, err)\n\t\treturn \"\", err\n\t}\n\n\t// 0755 permissions are needed to allow 'group' and 'other' to recurse the\n\t// directory tree. do a chmod here to ensure that permissions are set correctly\n\t// regardless of the process' umask.\n\terr = os.Chmod(tsDir, 0755)\n\tif err != nil {\n\t\tklog.Errorf(\"%s: unable to set mode on new temp directory: %v\", w.logContext, err)\n\t\treturn \"\", err\n\t}\n\n\treturn tsDir, nil\n}","line":{"from":380,"to":398}} {"id":100012866,"name":"writePayloadToDir","signature":"func (w *AtomicWriter) writePayloadToDir(payload map[string]FileProjection, dir string) error","file":"pkg/volume/util/atomic_writer.go","code":"// writePayloadToDir writes the given payload to the given directory. The\n// directory must exist.\nfunc (w *AtomicWriter) writePayloadToDir(payload map[string]FileProjection, dir string) error {\n\tfor userVisiblePath, fileProjection := range payload {\n\t\tcontent := fileProjection.Data\n\t\tmode := os.FileMode(fileProjection.Mode)\n\t\tfullPath := filepath.Join(dir, userVisiblePath)\n\t\tbaseDir, _ := filepath.Split(fullPath)\n\n\t\tif err := os.MkdirAll(baseDir, os.ModePerm); err != nil {\n\t\t\tklog.Errorf(\"%s: unable to create directory %s: %v\", w.logContext, baseDir, err)\n\t\t\treturn err\n\t\t}\n\n\t\tif err := ioutil.WriteFile(fullPath, content, mode); err != nil {\n\t\t\tklog.Errorf(\"%s: unable to write file %s with mode %v: %v\", w.logContext, fullPath, mode, err)\n\t\t\treturn err\n\t\t}\n\t\t// Chmod is needed because ioutil.WriteFile() ends up calling\n\t\t// open(2) to create the file, so the final mode used is \"mode \u0026\n\t\t// ~umask\". But we want to make sure the specified mode is used\n\t\t// in the file no matter what the umask is.\n\t\tif err := os.Chmod(fullPath, mode); err != nil {\n\t\t\tklog.Errorf(\"%s: unable to change file %s with mode %v: %v\", w.logContext, fullPath, mode, err)\n\t\t\treturn err\n\t\t}\n\n\t\tif fileProjection.FsUser == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif err := os.Chown(fullPath, int(*fileProjection.FsUser), -1); err != nil {\n\t\t\tklog.Errorf(\"%s: unable to change file %s with owner %v: %v\", w.logContext, fullPath, int(*fileProjection.FsUser), err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":400,"to":437}} {"id":100012867,"name":"createUserVisibleFiles","signature":"func (w *AtomicWriter) createUserVisibleFiles(payload map[string]FileProjection) error","file":"pkg/volume/util/atomic_writer.go","code":"// createUserVisibleFiles creates the relative symlinks for all the\n// files configured in the payload. If the directory in a file path does not\n// exist, it is created.\n//\n// Viz:\n// For files: \"bar\", \"foo/bar\", \"baz/bar\", \"foo/baz/blah\"\n// the following symlinks are created:\n// bar -\u003e ..data/bar\n// foo -\u003e ..data/foo\n// baz -\u003e ..data/baz\nfunc (w *AtomicWriter) createUserVisibleFiles(payload map[string]FileProjection) error {\n\tfor userVisiblePath := range payload {\n\t\tslashpos := strings.Index(userVisiblePath, string(os.PathSeparator))\n\t\tif slashpos == -1 {\n\t\t\tslashpos = len(userVisiblePath)\n\t\t}\n\t\tlinkname := userVisiblePath[:slashpos]\n\t\t_, err := os.Readlink(filepath.Join(w.targetDir, linkname))\n\t\tif err != nil \u0026\u0026 os.IsNotExist(err) {\n\t\t\t// The link into the data directory for this path doesn't exist; create it\n\t\t\tvisibleFile := filepath.Join(w.targetDir, linkname)\n\t\t\tdataDirFile := filepath.Join(dataDirName, linkname)\n\n\t\t\terr = os.Symlink(dataDirFile, visibleFile)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":439,"to":469}} {"id":100012868,"name":"removeUserVisiblePaths","signature":"func (w *AtomicWriter) removeUserVisiblePaths(paths sets.String) error","file":"pkg/volume/util/atomic_writer.go","code":"// removeUserVisiblePaths removes the set of paths from the user-visible\n// portion of the writer's target directory.\nfunc (w *AtomicWriter) removeUserVisiblePaths(paths sets.String) error {\n\tps := string(os.PathSeparator)\n\tvar lasterr error\n\tfor p := range paths {\n\t\t// only remove symlinks from the volume root directory (i.e. items that don't contain '/')\n\t\tif strings.Contains(p, ps) {\n\t\t\tcontinue\n\t\t}\n\t\tif err := os.Remove(filepath.Join(w.targetDir, p)); err != nil {\n\t\t\tklog.Errorf(\"%s: error pruning old user-visible path %s: %v\", w.logContext, p, err)\n\t\t\tlasterr = err\n\t\t}\n\t}\n\n\treturn lasterr\n}","line":{"from":471,"to":488}} {"id":100012869,"name":"GetCSIAttachLimitKey","signature":"func GetCSIAttachLimitKey(driverName string) string","file":"pkg/volume/util/attach_limit.go","code":"// GetCSIAttachLimitKey returns limit key used for CSI volumes\nfunc GetCSIAttachLimitKey(driverName string) string {\n\tcsiPrefixLength := len(CSIAttachLimitPrefix)\n\ttotalkeyLength := csiPrefixLength + len(driverName)\n\tif totalkeyLength \u003e= ResourceNameLengthLimit {\n\t\tcharsFromDriverName := driverName[:23]\n\t\thash := sha1.New()\n\t\thash.Write([]byte(driverName))\n\t\thashed := hex.EncodeToString(hash.Sum(nil))\n\t\thashed = hashed[:16]\n\t\treturn CSIAttachLimitPrefix + charsFromDriverName + hashed\n\t}\n\treturn CSIAttachLimitPrefix + driverName\n}","line":{"from":57,"to":70}} {"id":100012870,"name":"NewDeviceHandler","signature":"func NewDeviceHandler(io IoUtil) DeviceUtil","file":"pkg/volume/util/device_util.go","code":"// NewDeviceHandler Create a new IoHandler implementation\nfunc NewDeviceHandler(io IoUtil) DeviceUtil {\n\treturn \u0026deviceHandler{getIo: io}\n}","line":{"from":31,"to":34}} {"id":100012871,"name":"FindMultipathDeviceForDevice","signature":"func (handler *deviceHandler) FindMultipathDeviceForDevice(device string) string","file":"pkg/volume/util/device_util_linux.go","code":"// FindMultipathDeviceForDevice given a device name like /dev/sdx, find the devicemapper parent\nfunc (handler *deviceHandler) FindMultipathDeviceForDevice(device string) string {\n\tio := handler.getIo\n\tdisk, err := findDeviceForPath(device, io)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\tsysPath := \"/sys/block/\"\n\tif dirs, err := io.ReadDir(sysPath); err == nil {\n\t\tfor _, f := range dirs {\n\t\t\tname := f.Name()\n\t\t\tif strings.HasPrefix(name, \"dm-\") {\n\t\t\t\tif _, err1 := io.Lstat(sysPath + name + \"/slaves/\" + disk); err1 == nil {\n\t\t\t\t\treturn \"/dev/\" + name\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\"\n}","line":{"from":34,"to":53}} {"id":100012872,"name":"findDeviceForPath","signature":"func findDeviceForPath(path string, io IoUtil) (string, error)","file":"pkg/volume/util/device_util_linux.go","code":"// findDeviceForPath Find the underlying disk for a linked path such as /dev/disk/by-path/XXXX or /dev/mapper/XXXX\n// will return sdX or hdX etc, if /dev/sdX is passed in then sdX will be returned\nfunc findDeviceForPath(path string, io IoUtil) (string, error) {\n\tdevicePath, err := io.EvalSymlinks(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// if path /dev/hdX split into \"\", \"dev\", \"hdX\" then we will\n\t// return just the last part\n\tparts := strings.Split(devicePath, \"/\")\n\tif len(parts) == 3 \u0026\u0026 strings.HasPrefix(parts[1], \"dev\") {\n\t\treturn parts[2], nil\n\t}\n\treturn \"\", errors.New(\"Illegal path for device \" + devicePath)\n}","line":{"from":55,"to":69}} {"id":100012873,"name":"FindSlaveDevicesOnMultipath","signature":"func (handler *deviceHandler) FindSlaveDevicesOnMultipath(dm string) []string","file":"pkg/volume/util/device_util_linux.go","code":"// FindSlaveDevicesOnMultipath given a dm name like /dev/dm-1, find all devices\n// which are managed by the devicemapper dm-1.\nfunc (handler *deviceHandler) FindSlaveDevicesOnMultipath(dm string) []string {\n\tvar devices []string\n\tio := handler.getIo\n\t// Split path /dev/dm-1 into \"\", \"dev\", \"dm-1\"\n\tparts := strings.Split(dm, \"/\")\n\tif len(parts) != 3 || !strings.HasPrefix(parts[1], \"dev\") {\n\t\treturn devices\n\t}\n\tdisk := parts[2]\n\tslavesPath := filepath.Join(\"/sys/block/\", disk, \"/slaves/\")\n\tif files, err := io.ReadDir(slavesPath); err == nil {\n\t\tfor _, f := range files {\n\t\t\tdevices = append(devices, filepath.Join(\"/dev/\", f.Name()))\n\t\t}\n\t}\n\treturn devices\n}","line":{"from":71,"to":89}} {"id":100012874,"name":"GetISCSIPortalHostMapForTarget","signature":"func (handler *deviceHandler) GetISCSIPortalHostMapForTarget(targetIqn string) (map[string]int, error)","file":"pkg/volume/util/device_util_linux.go","code":"// GetISCSIPortalHostMapForTarget given a target iqn, find all the scsi hosts logged into\n// that target. Returns a map of iSCSI portals (string) to SCSI host numbers (integers).\n//\n//\tFor example: {\n//\t \"192.168.30.7:3260\": 2,\n//\t \"192.168.30.8:3260\": 3,\n//\t}\nfunc (handler *deviceHandler) GetISCSIPortalHostMapForTarget(targetIqn string) (map[string]int, error) {\n\tportalHostMap := make(map[string]int)\n\tio := handler.getIo\n\n\t// Iterate over all the iSCSI hosts in sysfs\n\tsysPath := \"/sys/class/iscsi_host\"\n\thostDirs, err := io.ReadDir(sysPath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn portalHostMap, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\tfor _, hostDir := range hostDirs {\n\t\t// iSCSI hosts are always of the format \"host%d\"\n\t\t// See drivers/scsi/hosts.c in Linux\n\t\thostName := hostDir.Name()\n\t\tif !strings.HasPrefix(hostName, \"host\") {\n\t\t\tcontinue\n\t\t}\n\t\thostNumber, err := strconv.Atoi(strings.TrimPrefix(hostName, \"host\"))\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Could not get number from iSCSI host: %s\", hostName)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Iterate over the children of the iscsi_host device\n\t\t// We are looking for the associated session\n\t\tdevicePath := sysPath + \"/\" + hostName + \"/device\"\n\t\tdeviceDirs, err := io.ReadDir(devicePath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, deviceDir := range deviceDirs {\n\t\t\t// Skip over files that aren't the session\n\t\t\t// Sessions are of the format \"session%u\"\n\t\t\t// See drivers/scsi/scsi_transport_iscsi.c in Linux\n\t\t\tsessionName := deviceDir.Name()\n\t\t\tif !strings.HasPrefix(sessionName, \"session\") {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tsessionPath := devicePath + \"/\" + sessionName\n\n\t\t\t// Read the target name for the iSCSI session\n\t\t\ttargetNamePath := sessionPath + \"/iscsi_session/\" + sessionName + \"/targetname\"\n\t\t\ttargetName, err := io.ReadFile(targetNamePath)\n\t\t\tif err != nil {\n\t\t\t\tklog.Infof(\"Failed to process session %s, assuming this session is unavailable: %s\", sessionName, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Ignore hosts that don't matchthe target we were looking for.\n\t\t\tif strings.TrimSpace(string(targetName)) != targetIqn {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Iterate over the children of the iSCSI session looking\n\t\t\t// for the iSCSI connection.\n\t\t\tdirs2, err := io.ReadDir(sessionPath)\n\t\t\tif err != nil {\n\t\t\t\tklog.Infof(\"Failed to process session %s, assuming this session is unavailable: %s\", sessionName, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor _, dir2 := range dirs2 {\n\t\t\t\t// Skip over files that aren't the connection\n\t\t\t\t// Connections are of the format \"connection%d:%u\"\n\t\t\t\t// See drivers/scsi/scsi_transport_iscsi.c in Linux\n\t\t\t\tdirName := dir2.Name()\n\t\t\t\tif !strings.HasPrefix(dirName, \"connection\") {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tconnectionPath := sessionPath + \"/\" + dirName + \"/iscsi_connection/\" + dirName\n\n\t\t\t\t// Read the current and persistent portal information for the connection.\n\t\t\t\taddrPath := connectionPath + \"/address\"\n\t\t\t\taddr, err := io.ReadFile(addrPath)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Infof(\"Failed to process connection %s, assuming this connection is unavailable: %s\", dirName, err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tportPath := connectionPath + \"/port\"\n\t\t\t\tport, err := io.ReadFile(portPath)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Infof(\"Failed to process connection %s, assuming this connection is unavailable: %s\", dirName, err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tpersistentAddrPath := connectionPath + \"/persistent_address\"\n\t\t\t\tpersistentAddr, err := io.ReadFile(persistentAddrPath)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Infof(\"Failed to process connection %s, assuming this connection is unavailable: %s\", dirName, err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tpersistentPortPath := connectionPath + \"/persistent_port\"\n\t\t\t\tpersistentPort, err := io.ReadFile(persistentPortPath)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Infof(\"Failed to process connection %s, assuming this connection is unavailable: %s\", dirName, err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Add entries to the map for both the current and persistent portals\n\t\t\t\t// pointing to the SCSI host for those connections\n\t\t\t\t// JoinHostPort will add `[]` around IPv6 addresses.\n\t\t\t\tportal := net.JoinHostPort(strings.TrimSpace(string(addr)), strings.TrimSpace(string(port)))\n\t\t\t\tportalHostMap[portal] = hostNumber\n\n\t\t\t\tpersistentPortal := net.JoinHostPort(strings.TrimSpace(string(persistentAddr)), strings.TrimSpace(string(persistentPort)))\n\t\t\t\tportalHostMap[persistentPortal] = hostNumber\n\t\t\t}\n\t\t}\n\t}\n\n\treturn portalHostMap, nil\n}","line":{"from":91,"to":215}} {"id":100012875,"name":"FindDevicesForISCSILun","signature":"func (handler *deviceHandler) FindDevicesForISCSILun(targetIqn string, lun int) ([]string, error)","file":"pkg/volume/util/device_util_linux.go","code":"// FindDevicesForISCSILun given an iqn, and lun number, find all the devices\n// corresponding to that LUN.\nfunc (handler *deviceHandler) FindDevicesForISCSILun(targetIqn string, lun int) ([]string, error) {\n\tdevices := make([]string, 0)\n\tio := handler.getIo\n\n\t// Iterate over all the iSCSI hosts in sysfs\n\tsysPath := \"/sys/class/iscsi_host\"\n\thostDirs, err := io.ReadDir(sysPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, hostDir := range hostDirs {\n\t\t// iSCSI hosts are always of the format \"host%d\"\n\t\t// See drivers/scsi/hosts.c in Linux\n\t\thostName := hostDir.Name()\n\t\tif !strings.HasPrefix(hostName, \"host\") {\n\t\t\tcontinue\n\t\t}\n\t\thostNumber, err := strconv.Atoi(strings.TrimPrefix(hostName, \"host\"))\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Could not get number from iSCSI host: %s\", hostName)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Iterate over the children of the iscsi_host device\n\t\t// We are looking for the associated session\n\t\tdevicePath := sysPath + \"/\" + hostName + \"/device\"\n\t\tdeviceDirs, err := io.ReadDir(devicePath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, deviceDir := range deviceDirs {\n\t\t\t// Skip over files that aren't the session\n\t\t\t// Sessions are of the format \"session%u\"\n\t\t\t// See drivers/scsi/scsi_transport_iscsi.c in Linux\n\t\t\tsessionName := deviceDir.Name()\n\t\t\tif !strings.HasPrefix(sessionName, \"session\") {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Read the target name for the iSCSI session\n\t\t\ttargetNamePath := devicePath + \"/\" + sessionName + \"/iscsi_session/\" + sessionName + \"/targetname\"\n\t\t\ttargetName, err := io.ReadFile(targetNamePath)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t// Only if the session matches the target we were looking for,\n\t\t\t// add it to the map\n\t\t\tif strings.TrimSpace(string(targetName)) != targetIqn {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// The list of block devices on the scsi bus will be in a\n\t\t\t// directory called \"target%d:%d:%d\".\n\t\t\t// See drivers/scsi/scsi_scan.c in Linux\n\t\t\t// We assume the channel/bus and device/controller are always zero for iSCSI\n\t\t\ttargetPath := devicePath + \"/\" + sessionName + fmt.Sprintf(\"/target%d:0:0\", hostNumber)\n\n\t\t\t// The block device for a given lun will be \"%d:%d:%d:%d\" --\n\t\t\t// host:channel:bus:LUN\n\t\t\tblockDevicePath := targetPath + fmt.Sprintf(\"/%d:0:0:%d\", hostNumber, lun)\n\n\t\t\t// If the LUN doesn't exist on this bus, continue on\n\t\t\t_, err = io.Lstat(blockDevicePath)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Read the block directory, there should only be one child --\n\t\t\t// the block device \"sd*\"\n\t\t\tpath := blockDevicePath + \"/block\"\n\t\t\tdirs, err := io.ReadDir(path)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif 0 \u003c len(dirs) {\n\t\t\t\tdevices = append(devices, dirs[0].Name())\n\t\t\t}\n\t\t}\n\t}\n\n\treturn devices, nil\n}","line":{"from":217,"to":301}} {"id":100012876,"name":"FindMultipathDeviceForDevice","signature":"func (handler *deviceHandler) FindMultipathDeviceForDevice(device string) string","file":"pkg/volume/util/device_util_unsupported.go","code":"// FindMultipathDeviceForDevice unsupported returns \"\"\nfunc (handler *deviceHandler) FindMultipathDeviceForDevice(device string) string {\n\treturn \"\"\n}","line":{"from":22,"to":25}} {"id":100012877,"name":"FindSlaveDevicesOnMultipath","signature":"func (handler *deviceHandler) FindSlaveDevicesOnMultipath(disk string) []string","file":"pkg/volume/util/device_util_unsupported.go","code":"// FindSlaveDevicesOnMultipath unsupported returns \"\"\nfunc (handler *deviceHandler) FindSlaveDevicesOnMultipath(disk string) []string {\n\tout := []string{}\n\treturn out\n}","line":{"from":27,"to":31}} {"id":100012878,"name":"GetISCSIPortalHostMapForTarget","signature":"func (handler *deviceHandler) GetISCSIPortalHostMapForTarget(targetIqn string) (map[string]int, error)","file":"pkg/volume/util/device_util_unsupported.go","code":"// GetISCSIPortalHostMapForTarget unsupported returns nil\nfunc (handler *deviceHandler) GetISCSIPortalHostMapForTarget(targetIqn string) (map[string]int, error) {\n\tportalHostMap := make(map[string]int)\n\treturn portalHostMap, nil\n}","line":{"from":33,"to":37}} {"id":100012879,"name":"FindDevicesForISCSILun","signature":"func (handler *deviceHandler) FindDevicesForISCSILun(targetIqn string, lun int) ([]string, error)","file":"pkg/volume/util/device_util_unsupported.go","code":"// FindDevicesForISCSILun unsupported returns nil\nfunc (handler *deviceHandler) FindDevicesForISCSILun(targetIqn string, lun int) ([]string, error) {\n\tdevices := []string{}\n\treturn devices, nil\n}","line":{"from":39,"to":43}} {"id":100012880,"name":"Info","signature":"func Info(path string) (int64, int64, int64, int64, int64, int64, error)","file":"pkg/volume/util/fs/fs.go","code":"// Info linux returns (available bytes, byte capacity, byte usage, total inodes, inodes free, inode usage, error)\n// for the filesystem that path resides upon.\nfunc Info(path string) (int64, int64, int64, int64, int64, int64, error) {\n\tstatfs := \u0026unix.Statfs_t{}\n\terr := unix.Statfs(path, statfs)\n\tif err != nil {\n\t\treturn 0, 0, 0, 0, 0, 0, err\n\t}\n\n\t// Available is blocks available * fragment size\n\tavailable := int64(statfs.Bavail) * int64(statfs.Bsize)\n\n\t// Capacity is total block count * fragment size\n\tcapacity := int64(statfs.Blocks) * int64(statfs.Bsize)\n\n\t// Usage is block being used * fragment size (aka block size).\n\tusage := (int64(statfs.Blocks) - int64(statfs.Bfree)) * int64(statfs.Bsize)\n\n\tinodes := int64(statfs.Files)\n\tinodesFree := int64(statfs.Ffree)\n\tinodesUsed := inodes - inodesFree\n\n\treturn available, capacity, usage, inodes, inodesFree, inodesUsed, nil\n}","line":{"from":40,"to":63}} {"id":100012881,"name":"DiskUsage","signature":"func DiskUsage(path string) (UsageInfo, error)","file":"pkg/volume/util/fs/fs.go","code":"// DiskUsage calculates the number of inodes and disk usage for a given directory\nfunc DiskUsage(path string) (UsageInfo, error) {\n\tvar usage UsageInfo\n\n\tif path == \"\" {\n\t\treturn usage, fmt.Errorf(\"invalid directory\")\n\t}\n\n\t// First check whether the quota system knows about this directory\n\t// A nil quantity or error means that the path does not support quotas\n\t// or xfs_quota tool is missing and we should use other mechanisms.\n\tstartTime := time.Now()\n\tconsumption, _ := fsquota.GetConsumption(path)\n\tif consumption != nil {\n\t\tusage.Bytes = consumption.Value()\n\t\tdefer servermetrics.CollectVolumeStatCalDuration(\"fsquota\", startTime)\n\t} else {\n\t\tdefer servermetrics.CollectVolumeStatCalDuration(\"du\", startTime)\n\t}\n\n\tinodes, _ := fsquota.GetInodes(path)\n\tif inodes != nil {\n\t\tusage.Inodes = inodes.Value()\n\t}\n\n\tif inodes != nil \u0026\u0026 consumption != nil {\n\t\treturn usage, nil\n\t}\n\n\ttopLevelStat := \u0026unix.Stat_t{}\n\terr := unix.Stat(path, topLevelStat)\n\tif err != nil {\n\t\treturn usage, err\n\t}\n\n\t// dedupedInode stores inodes that could be duplicates (nlink \u003e 1)\n\tdedupedInodes := make(map[uint64]struct{})\n\n\terr = filepath.Walk(path, func(path string, info os.FileInfo, err error) error {\n\t\t// ignore files that have been deleted after directory was read\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to count inodes for %s: %s\", path, err)\n\t\t}\n\n\t\t// according to the docs, Sys can be nil\n\t\tif info.Sys() == nil {\n\t\t\treturn fmt.Errorf(\"fileinfo Sys is nil\")\n\t\t}\n\n\t\ts, ok := info.Sys().(*syscall.Stat_t)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unsupported fileinfo; could not convert to stat_t\")\n\t\t}\n\n\t\tif s.Dev != topLevelStat.Dev {\n\t\t\t// don't descend into directories on other devices\n\t\t\treturn filepath.SkipDir\n\t\t}\n\n\t\t// Dedupe hardlinks\n\t\tif s.Nlink \u003e 1 {\n\t\t\tif _, ok := dedupedInodes[s.Ino]; !ok {\n\t\t\t\tdedupedInodes[s.Ino] = struct{}{}\n\t\t\t} else {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\tif consumption == nil {\n\t\t\tusage.Bytes += int64(s.Blocks) * int64(512) // blocksize in bytes\n\t\t}\n\n\t\tif inodes == nil {\n\t\t\tusage.Inodes++\n\t\t}\n\n\t\treturn nil\n\t})\n\n\treturn usage, err\n}","line":{"from":65,"to":148}} {"id":100012882,"name":"Info","signature":"func Info(path string) (int64, int64, int64, int64, int64, int64, error)","file":"pkg/volume/util/fs/fs_unsupported.go","code":"// Info unsupported returns 0 values for available and capacity and an error.\nfunc Info(path string) (int64, int64, int64, int64, int64, int64, error) {\n\treturn 0, 0, 0, 0, 0, 0, fmt.Errorf(\"fsinfo not supported for this build\")\n}","line":{"from":31,"to":34}} {"id":100012883,"name":"DiskUsage","signature":"func DiskUsage(path string) (UsageInfo, error)","file":"pkg/volume/util/fs/fs_unsupported.go","code":"// DiskUsage gets disk usage of specified path.\nfunc DiskUsage(path string) (UsageInfo, error) {\n\tvar usage UsageInfo\n\treturn usage, fmt.Errorf(\"directory disk usage not supported for this build.\")\n}","line":{"from":36,"to":40}} {"id":100012884,"name":"Info","signature":"func Info(path string) (int64, int64, int64, int64, int64, int64, error)","file":"pkg/volume/util/fs/fs_windows.go","code":"// Info returns (available bytes, byte capacity, byte usage, total inodes, inodes free, inode usage, error)\n// for the filesystem that path resides upon.\nfunc Info(path string) (int64, int64, int64, int64, int64, int64, error) {\n\tvar freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes int64\n\tvar err error\n\n\t// The equivalent linux call supports calls against files but the syscall for windows\n\t// fails for files with error code: The directory name is invalid. (#99173)\n\t// https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-\n\t// By always ensuring the directory path we meet all uses cases of this function\n\tpath = filepath.Dir(path)\n\tret, _, err := syscall.Syscall6(\n\t\tprocGetDiskFreeSpaceEx.Addr(),\n\t\t4,\n\t\tuintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(path))),\n\t\tuintptr(unsafe.Pointer(\u0026freeBytesAvailable)),\n\t\tuintptr(unsafe.Pointer(\u0026totalNumberOfBytes)),\n\t\tuintptr(unsafe.Pointer(\u0026totalNumberOfFreeBytes)),\n\t\t0,\n\t\t0,\n\t)\n\tif ret == 0 {\n\t\treturn 0, 0, 0, 0, 0, 0, err\n\t}\n\n\treturn freeBytesAvailable, totalNumberOfBytes, totalNumberOfBytes - freeBytesAvailable, 0, 0, 0, nil\n}","line":{"from":41,"to":67}} {"id":100012885,"name":"DiskUsage","signature":"func DiskUsage(path string) (UsageInfo, error)","file":"pkg/volume/util/fs/fs_windows.go","code":"// DiskUsage gets disk usage of specified path.\nfunc DiskUsage(path string) (UsageInfo, error) {\n\tvar usage UsageInfo\n\tinfo, err := os.Lstat(path)\n\tif err != nil {\n\t\treturn usage, err\n\t}\n\n\tusage.Bytes, err = diskUsage(path, info)\n\treturn usage, err\n}","line":{"from":69,"to":79}} {"id":100012886,"name":"diskUsage","signature":"func diskUsage(currPath string, info os.FileInfo) (int64, error)","file":"pkg/volume/util/fs/fs_windows.go","code":"func diskUsage(currPath string, info os.FileInfo) (int64, error) {\n\tvar size int64\n\n\tif info.Mode()\u0026os.ModeSymlink != 0 {\n\t\treturn size, nil\n\t}\n\n\tsize += info.Size()\n\n\tif !info.IsDir() {\n\t\treturn size, nil\n\t}\n\n\tdir, err := os.Open(currPath)\n\tif err != nil {\n\t\treturn size, err\n\t}\n\tdefer dir.Close()\n\n\tfiles, err := dir.Readdir(-1)\n\tif err != nil {\n\t\treturn size, err\n\t}\n\n\tfor _, file := range files {\n\t\tif file.IsDir() {\n\t\t\ts, err := diskUsage(filepath.Join(currPath, file.Name()), file)\n\t\t\tif err != nil {\n\t\t\t\treturn size, err\n\t\t\t}\n\t\t\tsize += s\n\t\t} else {\n\t\t\tsize += file.Size()\n\t\t}\n\t}\n\treturn size, nil\n}","line":{"from":81,"to":117}} {"id":100012887,"name":"GetQuotaApplier","signature":"func (*VolumeProvider) GetQuotaApplier(mountpoint string, backingDev string) LinuxVolumeQuotaApplier","file":"pkg/volume/util/fsquota/common/quota_common_linux_impl.go","code":"// GetQuotaApplier -- does this backing device support quotas that\n// can be applied to directories?\nfunc (*VolumeProvider) GetQuotaApplier(mountpoint string, backingDev string) LinuxVolumeQuotaApplier {\n\tfor _, fsType := range linuxSupportedFilesystems {\n\t\tif isFilesystemOfType(mountpoint, backingDev, fsType.typeMagic) {\n\t\t\treturn linuxVolumeQuotaApplier{mountpoint: mountpoint,\n\t\t\t\tmaxQuota: fsType.maxQuota,\n\t\t\t\tallowEmptyOutput: fsType.allowEmptyOutput,\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":84,"to":96}} {"id":100012888,"name":"getXFSQuotaCmd","signature":"func getXFSQuotaCmd() (string, error)","file":"pkg/volume/util/fsquota/common/quota_common_linux_impl.go","code":"func getXFSQuotaCmd() (string, error) {\n\tquotaCmdLock.Lock()\n\tdefer quotaCmdLock.Unlock()\n\tif quotaCmdInitialized {\n\t\treturn quotaCmd, nil\n\t}\n\tfor _, program := range quotaCmds {\n\t\tfileinfo, err := os.Stat(program)\n\t\tif err == nil \u0026\u0026 ((fileinfo.Mode().Perm() \u0026 (1 \u003c\u003c 6)) != 0) {\n\t\t\tklog.V(3).Infof(\"Found xfs_quota program %s\", program)\n\t\t\tquotaCmd = program\n\t\t\tquotaCmdInitialized = true\n\t\t\treturn quotaCmd, nil\n\t\t}\n\t}\n\tquotaCmdInitialized = true\n\treturn \"\", fmt.Errorf(\"no xfs_quota program found\")\n}","line":{"from":104,"to":121}} {"id":100012889,"name":"doRunXFSQuotaCommand","signature":"func doRunXFSQuotaCommand(mountpoint string, mountsFile, command string) (string, error)","file":"pkg/volume/util/fsquota/common/quota_common_linux_impl.go","code":"func doRunXFSQuotaCommand(mountpoint string, mountsFile, command string) (string, error) {\n\tquotaCmd, err := getXFSQuotaCmd()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// We're using numeric project IDs directly; no need to scan\n\t// /etc/projects or /etc/projid\n\tklog.V(4).Infof(\"runXFSQuotaCommand %s -t %s -P/dev/null -D/dev/null -x -f %s -c %s\", quotaCmd, mountsFile, mountpoint, command)\n\tcmd := exec.Command(quotaCmd, \"-t\", mountsFile, \"-P/dev/null\", \"-D/dev/null\", \"-x\", \"-f\", mountpoint, \"-c\", command)\n\n\tdata, err := cmd.Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tklog.V(4).Infof(\"runXFSQuotaCommand output %q\", string(data))\n\treturn string(data), nil\n}","line":{"from":123,"to":139}} {"id":100012890,"name":"runXFSQuotaCommand","signature":"func runXFSQuotaCommand(mountpoint string, command string) (string, error)","file":"pkg/volume/util/fsquota/common/quota_common_linux_impl.go","code":"// Extract the mountpoint we care about into a temporary mounts file so that xfs_quota does\n// not attempt to scan every mount on the filesystem, which could hang if e. g.\n// a stuck NFS mount is present.\n// See https://bugzilla.redhat.com/show_bug.cgi?id=237120 for an example\n// of the problem that could be caused if this were to happen.\nfunc runXFSQuotaCommand(mountpoint string, command string) (string, error) {\n\ttmpMounts, err := ioutil.TempFile(\"\", \"mounts\")\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"cannot create temporary mount file: %v\", err)\n\t}\n\ttmpMountsFileName := tmpMounts.Name()\n\tdefer tmpMounts.Close()\n\tdefer os.Remove(tmpMountsFileName)\n\n\tmounts, err := os.Open(MountsFile)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"cannot open mounts file %s: %v\", MountsFile, err)\n\t}\n\tdefer mounts.Close()\n\n\tscanner := bufio.NewScanner(mounts)\n\tfor scanner.Scan() {\n\t\tmatch := MountParseRegexp.FindStringSubmatch(scanner.Text())\n\t\tif match != nil {\n\t\t\tmount := match[2]\n\t\t\tif mount == mountpoint {\n\t\t\t\tif _, err := tmpMounts.WriteString(fmt.Sprintf(\"%s\\n\", scanner.Text())); err != nil {\n\t\t\t\t\treturn \"\", fmt.Errorf(\"cannot write temporary mounts file: %v\", err)\n\t\t\t\t}\n\t\t\t\tif err := tmpMounts.Sync(); err != nil {\n\t\t\t\t\treturn \"\", fmt.Errorf(\"cannot sync temporary mounts file: %v\", err)\n\t\t\t\t}\n\t\t\t\treturn doRunXFSQuotaCommand(mountpoint, tmpMountsFileName, command)\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"cannot run xfs_quota: cannot find mount point %s in %s\", mountpoint, MountsFile)\n}","line":{"from":141,"to":178}} {"id":100012891,"name":"SupportsQuotas","signature":"func SupportsQuotas(mountpoint string, qType QuotaType) (bool, error)","file":"pkg/volume/util/fsquota/common/quota_common_linux_impl.go","code":"// SupportsQuotas determines whether the filesystem supports quotas.\nfunc SupportsQuotas(mountpoint string, qType QuotaType) (bool, error) {\n\tdata, err := runXFSQuotaCommand(mountpoint, \"state -p\")\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif qType == FSQuotaEnforcing {\n\t\treturn strings.Contains(data, \"Enforcement: ON\"), nil\n\t}\n\treturn strings.Contains(data, \"Accounting: ON\"), nil\n}","line":{"from":180,"to":190}} {"id":100012892,"name":"isFilesystemOfType","signature":"func isFilesystemOfType(mountpoint string, backingDev string, typeMagic int64) bool","file":"pkg/volume/util/fsquota/common/quota_common_linux_impl.go","code":"func isFilesystemOfType(mountpoint string, backingDev string, typeMagic int64) bool {\n\tvar buf syscall.Statfs_t\n\terr := syscall.Statfs(mountpoint, \u0026buf)\n\tif err != nil {\n\t\tklog.Warningf(\"Warning: Unable to statfs %s: %v\", mountpoint, err)\n\t\treturn false\n\t}\n\tif int64(buf.Type) != typeMagic {\n\t\treturn false\n\t}\n\tif answer, _ := SupportsQuotas(mountpoint, FSQuotaAccounting); answer {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":192,"to":206}} {"id":100012893,"name":"GetQuotaOnDir","signature":"func (v linuxVolumeQuotaApplier) GetQuotaOnDir(path string) (QuotaID, error)","file":"pkg/volume/util/fsquota/common/quota_common_linux_impl.go","code":"// GetQuotaOnDir retrieves the quota ID (if any) associated with the specified directory\n// If we can't make system calls, all we can say is that we don't know whether\n// it has a quota, and higher levels have to make the call.\nfunc (v linuxVolumeQuotaApplier) GetQuotaOnDir(path string) (QuotaID, error) {\n\tcmd := exec.Command(lsattrCmd, \"-pd\", path)\n\tdata, err := cmd.Output()\n\tif err != nil {\n\t\treturn BadQuotaID, fmt.Errorf(\"cannot run lsattr: %v\", err)\n\t}\n\tmatch := lsattrParseRegexp.FindStringSubmatch(string(data))\n\tif match == nil {\n\t\treturn BadQuotaID, fmt.Errorf(\"unable to parse lsattr -pd %s output %s\", path, string(data))\n\t}\n\tif match[2] != path {\n\t\treturn BadQuotaID, fmt.Errorf(\"mismatch between supplied and returned path (%s != %s)\", path, match[2])\n\t}\n\tprojid, err := strconv.ParseInt(match[1], 10, 32)\n\tif err != nil {\n\t\treturn BadQuotaID, fmt.Errorf(\"unable to parse project ID from %s (%v)\", match[1], err)\n\t}\n\treturn QuotaID(projid), nil\n}","line":{"from":208,"to":229}} {"id":100012894,"name":"SetQuotaOnDir","signature":"func (v linuxVolumeQuotaApplier) SetQuotaOnDir(path string, id QuotaID, bytes int64) error","file":"pkg/volume/util/fsquota/common/quota_common_linux_impl.go","code":"// SetQuotaOnDir applies a quota to the specified directory under the specified mountpoint.\nfunc (v linuxVolumeQuotaApplier) SetQuotaOnDir(path string, id QuotaID, bytes int64) error {\n\tif bytes \u003c 0 || bytes \u003e v.maxQuota {\n\t\tbytes = v.maxQuota\n\t}\n\t_, err := runXFSQuotaCommand(v.mountpoint, fmt.Sprintf(\"limit -p bhard=%v bsoft=%v %v\", bytes, bytes, id))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = runXFSQuotaCommand(v.mountpoint, fmt.Sprintf(\"project -s -p %s %v\", path, id))\n\treturn err\n}","line":{"from":231,"to":243}} {"id":100012895,"name":"getQuantity","signature":"func getQuantity(mountpoint string, id QuotaID, xfsQuotaArg string, multiplier int64, allowEmptyOutput bool) (int64, error)","file":"pkg/volume/util/fsquota/common/quota_common_linux_impl.go","code":"func getQuantity(mountpoint string, id QuotaID, xfsQuotaArg string, multiplier int64, allowEmptyOutput bool) (int64, error) {\n\tdata, err := runXFSQuotaCommand(mountpoint, fmt.Sprintf(\"quota -p -N -n -v %s %v\", xfsQuotaArg, id))\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"unable to run xfs_quota: %v\", err)\n\t}\n\tif data == \"\" \u0026\u0026 allowEmptyOutput {\n\t\treturn 0, nil\n\t}\n\tmatch := quotaParseRegexp.FindStringSubmatch(data)\n\tif match == nil {\n\t\treturn 0, fmt.Errorf(\"unable to parse quota output '%s'\", data)\n\t}\n\tsize, err := strconv.ParseInt(match[1], 10, 64)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"unable to parse data size '%s' from '%s': %v\", match[1], data, err)\n\t}\n\tklog.V(4).Infof(\"getQuantity %s %d %s %d =\u003e %d %v\", mountpoint, id, xfsQuotaArg, multiplier, size, err)\n\treturn size * multiplier, nil\n}","line":{"from":245,"to":263}} {"id":100012896,"name":"GetConsumption","signature":"func (v linuxVolumeQuotaApplier) GetConsumption(_ string, id QuotaID) (int64, error)","file":"pkg/volume/util/fsquota/common/quota_common_linux_impl.go","code":"// GetConsumption returns the consumption in bytes if available via quotas\nfunc (v linuxVolumeQuotaApplier) GetConsumption(_ string, id QuotaID) (int64, error) {\n\treturn getQuantity(v.mountpoint, id, \"-b\", 1024, v.allowEmptyOutput)\n}","line":{"from":265,"to":268}} {"id":100012897,"name":"GetInodes","signature":"func (v linuxVolumeQuotaApplier) GetInodes(_ string, id QuotaID) (int64, error)","file":"pkg/volume/util/fsquota/common/quota_common_linux_impl.go","code":"// GetInodes returns the inodes in use if available via quotas\nfunc (v linuxVolumeQuotaApplier) GetInodes(_ string, id QuotaID) (int64, error) {\n\treturn getQuantity(v.mountpoint, id, \"-i\", 1, v.allowEmptyOutput)\n}","line":{"from":270,"to":273}} {"id":100012898,"name":"QuotaIDIsInUse","signature":"func (v linuxVolumeQuotaApplier) QuotaIDIsInUse(id QuotaID) (bool, error)","file":"pkg/volume/util/fsquota/common/quota_common_linux_impl.go","code":"// QuotaIDIsInUse checks whether the specified quota ID is in use on the specified\n// filesystem\nfunc (v linuxVolumeQuotaApplier) QuotaIDIsInUse(id QuotaID) (bool, error) {\n\tbytes, err := v.GetConsumption(v.mountpoint, id)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif bytes \u003e 0 {\n\t\treturn true, nil\n\t}\n\tinodes, err := v.GetInodes(v.mountpoint, id)\n\treturn inodes \u003e 0, err\n}","line":{"from":275,"to":287}} {"id":100012899,"name":"projFilesAreOK","signature":"func projFilesAreOK() error","file":"pkg/volume/util/fsquota/project.go","code":"func projFilesAreOK() error {\n\tif sf, err := os.Lstat(projectsFile); err != nil || sf.Mode().IsRegular() {\n\t\tif sf, err := os.Lstat(projidFile); err != nil || sf.Mode().IsRegular() {\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"%s exists but is not a plain file, cannot continue\", projidFile)\n\t}\n\treturn fmt.Errorf(\"%s exists but is not a plain file, cannot continue\", projectsFile)\n}","line":{"from":58,"to":66}} {"id":100012900,"name":"lockFile","signature":"func lockFile(file *os.File) error","file":"pkg/volume/util/fsquota/project.go","code":"func lockFile(file *os.File) error {\n\treturn unix.Flock(int(file.Fd()), unix.LOCK_EX)\n}","line":{"from":68,"to":70}} {"id":100012901,"name":"unlockFile","signature":"func unlockFile(file *os.File) error","file":"pkg/volume/util/fsquota/project.go","code":"func unlockFile(file *os.File) error {\n\treturn unix.Flock(int(file.Fd()), unix.LOCK_UN)\n}","line":{"from":72,"to":74}} {"id":100012902,"name":"openAndLockProjectFiles","signature":"func openAndLockProjectFiles() (*os.File, *os.File, error)","file":"pkg/volume/util/fsquota/project.go","code":"// openAndLockProjectFiles opens /etc/projects and /etc/projid locked.\n// Creates them if they don't exist\nfunc openAndLockProjectFiles() (*os.File, *os.File, error) {\n\t// Make sure neither project-related file is a symlink!\n\tif err := projFilesAreOK(); err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"system project files failed verification: %v\", err)\n\t}\n\t// We don't actually modify the original files; we create temporaries and\n\t// move them over the originals\n\tfProjects, err := os.OpenFile(projectsFile, os.O_RDONLY|os.O_CREATE, 0644)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"unable to open %s: %v\", projectsFile, err)\n\t\treturn nil, nil, err\n\t}\n\tfProjid, err := os.OpenFile(projidFile, os.O_RDONLY|os.O_CREATE, 0644)\n\tif err == nil {\n\t\t// Check once more, to ensure nothing got changed out from under us\n\t\tif err = projFilesAreOK(); err == nil {\n\t\t\terr = lockFile(fProjects)\n\t\t\tif err == nil {\n\t\t\t\terr = lockFile(fProjid)\n\t\t\t\tif err == nil {\n\t\t\t\t\treturn fProjects, fProjid, nil\n\t\t\t\t}\n\t\t\t\t// Nothing useful we can do if we get an error here\n\t\t\t\terr = fmt.Errorf(\"unable to lock %s: %v\", projidFile, err)\n\t\t\t\tunlockFile(fProjects)\n\t\t\t} else {\n\t\t\t\terr = fmt.Errorf(\"unable to lock %s: %v\", projectsFile, err)\n\t\t\t}\n\t\t} else {\n\t\t\terr = fmt.Errorf(\"system project files failed re-verification: %v\", err)\n\t\t}\n\t\tfProjid.Close()\n\t} else {\n\t\terr = fmt.Errorf(\"unable to open %s: %v\", projidFile, err)\n\t}\n\tfProjects.Close()\n\treturn nil, nil, err\n}","line":{"from":76,"to":115}} {"id":100012903,"name":"closeProjectFiles","signature":"func closeProjectFiles(fProjects *os.File, fProjid *os.File) error","file":"pkg/volume/util/fsquota/project.go","code":"func closeProjectFiles(fProjects *os.File, fProjid *os.File) error {\n\t// Nothing useful we can do if either of these fail,\n\t// but we have to close (and thereby unlock) the files anyway.\n\tvar err error\n\tvar err1 error\n\tif fProjid != nil {\n\t\terr = fProjid.Close()\n\t}\n\tif fProjects != nil {\n\t\terr1 = fProjects.Close()\n\t}\n\tif err == nil {\n\t\treturn err1\n\t}\n\treturn err\n}","line":{"from":117,"to":132}} {"id":100012904,"name":"parseProject","signature":"func parseProject(l string) projectType","file":"pkg/volume/util/fsquota/project.go","code":"func parseProject(l string) projectType {\n\tif match := projectsParseRegexp.FindStringSubmatch(l); match != nil {\n\t\ti, err := strconv.Atoi(match[1])\n\t\tif err == nil {\n\t\t\treturn projectType{true, common.QuotaID(i), match[2], l}\n\t\t}\n\t}\n\treturn projectType{true, common.BadQuotaID, \"\", l}\n}","line":{"from":134,"to":142}} {"id":100012905,"name":"parseProjid","signature":"func parseProjid(l string) projectType","file":"pkg/volume/util/fsquota/project.go","code":"func parseProjid(l string) projectType {\n\tif match := projidParseRegexp.FindStringSubmatch(l); match != nil {\n\t\ti, err := strconv.Atoi(match[2])\n\t\tif err == nil {\n\t\t\treturn projectType{true, common.QuotaID(i), match[1], l}\n\t\t}\n\t}\n\treturn projectType{true, common.BadQuotaID, \"\", l}\n}","line":{"from":144,"to":152}} {"id":100012906,"name":"parseProjFile","signature":"func parseProjFile(f *os.File, parser func(l string) projectType) []projectType","file":"pkg/volume/util/fsquota/project.go","code":"func parseProjFile(f *os.File, parser func(l string) projectType) []projectType {\n\tvar answer []projectType\n\tscanner := bufio.NewScanner(f)\n\tfor scanner.Scan() {\n\t\tanswer = append(answer, parser(scanner.Text()))\n\t}\n\treturn answer\n}","line":{"from":154,"to":161}} {"id":100012907,"name":"readProjectFiles","signature":"func readProjectFiles(projects *os.File, projid *os.File) projectsList","file":"pkg/volume/util/fsquota/project.go","code":"func readProjectFiles(projects *os.File, projid *os.File) projectsList {\n\treturn projectsList{parseProjFile(projects, parseProject), parseProjFile(projid, parseProjid)}\n}","line":{"from":163,"to":165}} {"id":100012908,"name":"findAvailableQuota","signature":"func findAvailableQuota(path string, idMap map[common.QuotaID]bool) (common.QuotaID, error)","file":"pkg/volume/util/fsquota/project.go","code":"// findAvailableQuota finds the next available quota from the FirstQuota\n// it returns error if QuotaIDIsInUse returns error when getting quota id in use;\n// it searches at most maxUnusedQuotasToSearch(128) time\nfunc findAvailableQuota(path string, idMap map[common.QuotaID]bool) (common.QuotaID, error) {\n\tunusedQuotasSearched := 0\n\tfor id := common.FirstQuota; true; id++ {\n\t\tif _, ok := idMap[id]; !ok {\n\t\t\tisInUse, err := getApplier(path).QuotaIDIsInUse(id)\n\t\t\tif err != nil {\n\t\t\t\treturn common.BadQuotaID, err\n\t\t\t} else if !isInUse {\n\t\t\t\treturn id, nil\n\t\t\t}\n\t\t\tunusedQuotasSearched++\n\t\t\tif unusedQuotasSearched \u003e maxUnusedQuotasToSearch {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn common.BadQuotaID, fmt.Errorf(\"cannot find available quota ID\")\n}","line":{"from":167,"to":187}} {"id":100012909,"name":"addDirToProject","signature":"func addDirToProject(path string, id common.QuotaID, list *projectsList) (common.QuotaID, bool, error)","file":"pkg/volume/util/fsquota/project.go","code":"func addDirToProject(path string, id common.QuotaID, list *projectsList) (common.QuotaID, bool, error) {\n\tidMap := make(map[common.QuotaID]bool)\n\tfor _, project := range list.projects {\n\t\tif project.data == path {\n\t\t\tif id != common.BadQuotaID \u0026\u0026 id != project.id {\n\t\t\t\treturn common.BadQuotaID, false, fmt.Errorf(\"attempt to reassign project ID for %s\", path)\n\t\t\t}\n\t\t\t// Trying to reassign a directory to the project it's\n\t\t\t// already in. Maybe this should be an error, but for\n\t\t\t// now treat it as an idempotent operation\n\t\t\treturn project.id, false, nil\n\t\t}\n\t\tidMap[project.id] = true\n\t}\n\tvar needToAddProjid = true\n\tfor _, projid := range list.projid {\n\t\tidMap[projid.id] = true\n\t\tif projid.id == id \u0026\u0026 id != common.BadQuotaID {\n\t\t\tneedToAddProjid = false\n\t\t}\n\t}\n\tvar err error\n\tif id == common.BadQuotaID {\n\t\tid, err = findAvailableQuota(path, idMap)\n\t\tif err != nil {\n\t\t\treturn common.BadQuotaID, false, err\n\t\t}\n\t\tneedToAddProjid = true\n\t}\n\tif needToAddProjid {\n\t\tname := fmt.Sprintf(\"volume%v\", id)\n\t\tline := fmt.Sprintf(\"%s:%v\", name, id)\n\t\tlist.projid = append(list.projid, projectType{true, id, name, line})\n\t}\n\tline := fmt.Sprintf(\"%v:%s\", id, path)\n\tlist.projects = append(list.projects, projectType{true, id, path, line})\n\treturn id, needToAddProjid, nil\n}","line":{"from":189,"to":226}} {"id":100012910,"name":"removeDirFromProject","signature":"func removeDirFromProject(path string, id common.QuotaID, list *projectsList) (bool, error)","file":"pkg/volume/util/fsquota/project.go","code":"func removeDirFromProject(path string, id common.QuotaID, list *projectsList) (bool, error) {\n\tif id == common.BadQuotaID {\n\t\treturn false, fmt.Errorf(\"attempt to remove invalid quota ID from %s\", path)\n\t}\n\tfoundAt := -1\n\tcountByID := make(map[common.QuotaID]int)\n\tfor i, project := range list.projects {\n\t\tif project.data == path {\n\t\t\tif id != project.id {\n\t\t\t\treturn false, fmt.Errorf(\"attempting to remove quota ID %v from path %s, but expecting ID %v\", id, path, project.id)\n\t\t\t} else if foundAt != -1 {\n\t\t\t\treturn false, fmt.Errorf(\"found multiple quota IDs for path %s\", path)\n\t\t\t}\n\t\t\t// Faster and easier than deleting an element\n\t\t\tlist.projects[i].isValid = false\n\t\t\tfoundAt = i\n\t\t}\n\t\tcountByID[project.id]++\n\t}\n\tif foundAt == -1 {\n\t\treturn false, fmt.Errorf(\"cannot find quota associated with path %s\", path)\n\t}\n\tif countByID[id] \u003c= 1 {\n\t\t// Removing the last entry means that we're no longer using\n\t\t// the quota ID, so remove that as well\n\t\tfor i, projid := range list.projid {\n\t\t\tif projid.id == id {\n\t\t\t\tlist.projid[i].isValid = false\n\t\t\t}\n\t\t}\n\t\treturn true, nil\n\t}\n\treturn false, nil\n}","line":{"from":228,"to":261}} {"id":100012911,"name":"writeProjectFile","signature":"func writeProjectFile(base *os.File, projects []projectType) (string, error)","file":"pkg/volume/util/fsquota/project.go","code":"func writeProjectFile(base *os.File, projects []projectType) (string, error) {\n\toname := base.Name()\n\tstat, err := base.Stat()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tmode := stat.Mode() \u0026 os.ModePerm\n\tf, err := ioutil.TempFile(filepath.Dir(oname), filepath.Base(oname))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfilename := f.Name()\n\tif err := os.Chmod(filename, mode); err != nil {\n\t\treturn \"\", err\n\t}\n\tfor _, proj := range projects {\n\t\tif proj.isValid {\n\t\t\tif _, err := f.WriteString(fmt.Sprintf(\"%s\\n\", proj.line)); err != nil {\n\t\t\t\tf.Close()\n\t\t\t\tos.Remove(filename)\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t}\n\t}\n\tif err := f.Close(); err != nil {\n\t\tos.Remove(filename)\n\t\treturn \"\", err\n\t}\n\treturn filename, nil\n}","line":{"from":263,"to":292}} {"id":100012912,"name":"writeProjectFiles","signature":"func writeProjectFiles(fProjects *os.File, fProjid *os.File, writeProjid bool, list projectsList) error","file":"pkg/volume/util/fsquota/project.go","code":"func writeProjectFiles(fProjects *os.File, fProjid *os.File, writeProjid bool, list projectsList) error {\n\ttmpProjects, err := writeProjectFile(fProjects, list.projects)\n\tif err == nil {\n\t\t// Ensure that both files are written before we try to rename either.\n\t\tif writeProjid {\n\t\t\ttmpProjid, err := writeProjectFile(fProjid, list.projid)\n\t\t\tif err == nil {\n\t\t\t\terr = os.Rename(tmpProjid, fProjid.Name())\n\t\t\t\tif err != nil {\n\t\t\t\t\tos.Remove(tmpProjid)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif err == nil {\n\t\t\terr = os.Rename(tmpProjects, fProjects.Name())\n\t\t\tif err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t// We're in a bit of trouble here; at this\n\t\t\t// point we've successfully renamed tmpProjid\n\t\t\t// to the real thing, but renaming tmpProject\n\t\t\t// to the real file failed. There's not much we\n\t\t\t// can do in this position. Anything we could do\n\t\t\t// to try to undo it would itself be likely to fail.\n\t\t}\n\t\tos.Remove(tmpProjects)\n\t}\n\treturn fmt.Errorf(\"unable to write project files: %v\", err)\n}","line":{"from":294,"to":322}} {"id":100012913,"name":"createProjectID","signature":"func createProjectID(path string, ID common.QuotaID) (common.QuotaID, error)","file":"pkg/volume/util/fsquota/project.go","code":"// if ID is common.BadQuotaID, generate new project id if the dir is not in a project\nfunc createProjectID(path string, ID common.QuotaID) (common.QuotaID, error) {\n\tquotaIDLock.Lock()\n\tdefer quotaIDLock.Unlock()\n\tfProjects, fProjid, err := openAndLockProjectFiles()\n\tif err == nil {\n\t\tdefer closeProjectFiles(fProjects, fProjid)\n\t\tlist := readProjectFiles(fProjects, fProjid)\n\t\tvar writeProjid bool\n\t\tID, writeProjid, err = addDirToProject(path, ID, \u0026list)\n\t\tif err == nil \u0026\u0026 ID != common.BadQuotaID {\n\t\t\tif err = writeProjectFiles(fProjects, fProjid, writeProjid, list); err == nil {\n\t\t\t\treturn ID, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn common.BadQuotaID, fmt.Errorf(\"createProjectID %s %v failed %v\", path, ID, err)\n}","line":{"from":324,"to":341}} {"id":100012914,"name":"removeProjectID","signature":"func removeProjectID(path string, ID common.QuotaID) error","file":"pkg/volume/util/fsquota/project.go","code":"func removeProjectID(path string, ID common.QuotaID) error {\n\tif ID == common.BadQuotaID {\n\t\treturn fmt.Errorf(\"attempting to remove invalid quota ID %v\", ID)\n\t}\n\tquotaIDLock.Lock()\n\tdefer quotaIDLock.Unlock()\n\tfProjects, fProjid, err := openAndLockProjectFiles()\n\tif err == nil {\n\t\tdefer closeProjectFiles(fProjects, fProjid)\n\t\tlist := readProjectFiles(fProjects, fProjid)\n\t\tvar writeProjid bool\n\t\twriteProjid, err = removeDirFromProject(path, ID, \u0026list)\n\t\tif err == nil {\n\t\t\tif err = writeProjectFiles(fProjects, fProjid, writeProjid, list); err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\treturn fmt.Errorf(\"removeProjectID %s %v failed %v\", path, ID, err)\n}","line":{"from":343,"to":362}} {"id":100012915,"name":"enabledQuotasForMonitoring","signature":"func enabledQuotasForMonitoring() bool","file":"pkg/volume/util/fsquota/quota.go","code":"func enabledQuotasForMonitoring() bool {\n\treturn utilfeature.DefaultFeatureGate.Enabled(features.LocalStorageCapacityIsolationFSQuotaMonitoring)\n}","line":{"from":53,"to":55}} {"id":100012916,"name":"detectBackingDevInternal","signature":"func detectBackingDevInternal(mountpoint string, mounts string) (string, error)","file":"pkg/volume/util/fsquota/quota_linux.go","code":"// Separate the innards for ease of testing\nfunc detectBackingDevInternal(mountpoint string, mounts string) (string, error) {\n\tfile, err := os.Open(mounts)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer file.Close()\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\tmatch := common.MountParseRegexp.FindStringSubmatch(scanner.Text())\n\t\tif match != nil {\n\t\t\tdevice := match[1]\n\t\t\tmount := match[2]\n\t\t\tif mount == mountpoint {\n\t\t\t\treturn device, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"couldn't find backing device for %s\", mountpoint)\n}","line":{"from":82,"to":101}} {"id":100012917,"name":"detectBackingDev","signature":"func detectBackingDev(_ mount.Interface, mountpoint string) (string, error)","file":"pkg/volume/util/fsquota/quota_linux.go","code":"// detectBackingDev assumes that the mount point provided is valid\nfunc detectBackingDev(_ mount.Interface, mountpoint string) (string, error) {\n\treturn detectBackingDevInternal(mountpoint, common.MountsFile)\n}","line":{"from":103,"to":106}} {"id":100012918,"name":"clearBackingDev","signature":"func clearBackingDev(path string)","file":"pkg/volume/util/fsquota/quota_linux.go","code":"func clearBackingDev(path string) {\n\tbackingDevLock.Lock()\n\tdefer backingDevLock.Unlock()\n\tdelete(backingDevMap, path)\n}","line":{"from":108,"to":112}} {"id":100012919,"name":"detectMountpointInternal","signature":"func detectMountpointInternal(m mount.Interface, path string) (string, error)","file":"pkg/volume/util/fsquota/quota_linux.go","code":"// Assumes that the path has been fully canonicalized\n// Breaking this up helps with testing\nfunc detectMountpointInternal(m mount.Interface, path string) (string, error) {\n\tfor path != \"\" \u0026\u0026 path != \"/\" {\n\t\t// per k8s.io/mount-utils/mount_linux this detects all but\n\t\t// a bind mount from one part of a mount to another.\n\t\t// For our purposes that's fine; we simply want the \"true\"\n\t\t// mount point\n\t\t//\n\t\t// IsNotMountPoint proved much more troublesome; it actually\n\t\t// scans the mounts, and when a lot of mount/unmount\n\t\t// activity takes place, it is not able to get a consistent\n\t\t// view of /proc/self/mounts, causing it to time out and\n\t\t// report incorrectly.\n\t\tisNotMount, err := m.IsLikelyNotMountPoint(path)\n\t\tif err != nil {\n\t\t\treturn \"/\", err\n\t\t}\n\t\tif !isNotMount {\n\t\t\treturn path, nil\n\t\t}\n\t\tpath = filepath.Dir(path)\n\t}\n\treturn \"/\", nil\n}","line":{"from":114,"to":138}} {"id":100012920,"name":"detectMountpoint","signature":"func detectMountpoint(m mount.Interface, path string) (string, error)","file":"pkg/volume/util/fsquota/quota_linux.go","code":"func detectMountpoint(m mount.Interface, path string) (string, error) {\n\txpath, err := filepath.Abs(path)\n\tif err != nil {\n\t\treturn \"/\", err\n\t}\n\txpath, err = filepath.EvalSymlinks(xpath)\n\tif err != nil {\n\t\treturn \"/\", err\n\t}\n\tif xpath, err = detectMountpointInternal(m, xpath); err == nil {\n\t\treturn xpath, nil\n\t}\n\treturn \"/\", err\n}","line":{"from":140,"to":153}} {"id":100012921,"name":"clearMountpoint","signature":"func clearMountpoint(path string)","file":"pkg/volume/util/fsquota/quota_linux.go","code":"func clearMountpoint(path string) {\n\tmountpointLock.Lock()\n\tdefer mountpointLock.Unlock()\n\tdelete(mountpointMap, path)\n}","line":{"from":155,"to":159}} {"id":100012922,"name":"getFSInfo","signature":"func getFSInfo(m mount.Interface, path string) (string, string, error)","file":"pkg/volume/util/fsquota/quota_linux.go","code":"// getFSInfo Returns mountpoint and backing device\n// getFSInfo should cache the mountpoint and backing device for the\n// path.\nfunc getFSInfo(m mount.Interface, path string) (string, string, error) {\n\tmountpointLock.Lock()\n\tdefer mountpointLock.Unlock()\n\n\tbackingDevLock.Lock()\n\tdefer backingDevLock.Unlock()\n\n\tvar err error\n\n\tmountpoint, okMountpoint := mountpointMap[path]\n\tif !okMountpoint {\n\t\tmountpoint, err = detectMountpoint(m, path)\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", fmt.Errorf(\"cannot determine mountpoint for %s: %v\", path, err)\n\t\t}\n\t}\n\n\tbackingDev, okBackingDev := backingDevMap[path]\n\tif !okBackingDev {\n\t\tbackingDev, err = detectBackingDev(m, mountpoint)\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", fmt.Errorf(\"cannot determine backing device for %s: %v\", path, err)\n\t\t}\n\t}\n\tmountpointMap[path] = mountpoint\n\tbackingDevMap[path] = backingDev\n\treturn mountpoint, backingDev, nil\n}","line":{"from":161,"to":191}} {"id":100012923,"name":"clearFSInfo","signature":"func clearFSInfo(path string)","file":"pkg/volume/util/fsquota/quota_linux.go","code":"func clearFSInfo(path string) {\n\tclearMountpoint(path)\n\tclearBackingDev(path)\n}","line":{"from":193,"to":196}} {"id":100012924,"name":"getApplier","signature":"func getApplier(path string) common.LinuxVolumeQuotaApplier","file":"pkg/volume/util/fsquota/quota_linux.go","code":"func getApplier(path string) common.LinuxVolumeQuotaApplier {\n\tdirApplierLock.Lock()\n\tdefer dirApplierLock.Unlock()\n\treturn dirApplierMap[path]\n}","line":{"from":198,"to":202}} {"id":100012925,"name":"setApplier","signature":"func setApplier(path string, applier common.LinuxVolumeQuotaApplier)","file":"pkg/volume/util/fsquota/quota_linux.go","code":"func setApplier(path string, applier common.LinuxVolumeQuotaApplier) {\n\tdirApplierLock.Lock()\n\tdefer dirApplierLock.Unlock()\n\tdirApplierMap[path] = applier\n}","line":{"from":204,"to":208}} {"id":100012926,"name":"clearApplier","signature":"func clearApplier(path string)","file":"pkg/volume/util/fsquota/quota_linux.go","code":"func clearApplier(path string) {\n\tdirApplierLock.Lock()\n\tdefer dirApplierLock.Unlock()\n\tdelete(dirApplierMap, path)\n}","line":{"from":210,"to":214}} {"id":100012927,"name":"setQuotaOnDir","signature":"func setQuotaOnDir(path string, id common.QuotaID, bytes int64) error","file":"pkg/volume/util/fsquota/quota_linux.go","code":"func setQuotaOnDir(path string, id common.QuotaID, bytes int64) error {\n\treturn getApplier(path).SetQuotaOnDir(path, id, bytes)\n}","line":{"from":216,"to":218}} {"id":100012928,"name":"GetQuotaOnDir","signature":"func GetQuotaOnDir(m mount.Interface, path string) (common.QuotaID, error)","file":"pkg/volume/util/fsquota/quota_linux.go","code":"func GetQuotaOnDir(m mount.Interface, path string) (common.QuotaID, error) {\n\t_, _, err := getFSInfo(m, path)\n\tif err != nil {\n\t\treturn common.BadQuotaID, err\n\t}\n\treturn getApplier(path).GetQuotaOnDir(path)\n}","line":{"from":220,"to":226}} {"id":100012929,"name":"clearQuotaOnDir","signature":"func clearQuotaOnDir(m mount.Interface, path string) error","file":"pkg/volume/util/fsquota/quota_linux.go","code":"func clearQuotaOnDir(m mount.Interface, path string) error {\n\t// Since we may be called without path being in the map,\n\t// we explicitly have to check in this case.\n\tklog.V(4).Infof(\"clearQuotaOnDir %s\", path)\n\tsupportsQuotas, err := SupportsQuotas(m, path)\n\tif err != nil {\n\t\t// Log-and-continue instead of returning an error for now\n\t\t// due to unspecified backwards compatibility concerns (a subject to revise)\n\t\tklog.V(3).Infof(\"Attempt to check for quota support failed: %v\", err)\n\t}\n\tif !supportsQuotas {\n\t\treturn nil\n\t}\n\tprojid, err := GetQuotaOnDir(m, path)\n\tif err == nil \u0026\u0026 projid != common.BadQuotaID {\n\t\t// This means that we have a quota on the directory but\n\t\t// we can't clear it. That's not good.\n\t\terr = setQuotaOnDir(path, projid, 0)\n\t\tif err != nil {\n\t\t\tklog.V(3).Infof(\"Attempt to clear quota failed: %v\", err)\n\t\t}\n\t\t// Even if clearing the quota failed, we still need to\n\t\t// try to remove the project ID, or that may be left dangling.\n\t\terr1 := removeProjectID(path, projid)\n\t\tif err1 != nil {\n\t\t\tklog.V(3).Infof(\"Attempt to remove quota ID from system files failed: %v\", err1)\n\t\t}\n\t\tclearFSInfo(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn err1\n\t}\n\t// If we couldn't get a quota, that's fine -- there may\n\t// never have been one, and we have no way to know otherwise\n\tklog.V(3).Infof(\"clearQuotaOnDir fails %v\", err)\n\treturn nil\n}","line":{"from":228,"to":265}} {"id":100012930,"name":"SupportsQuotas","signature":"func SupportsQuotas(m mount.Interface, path string) (bool, error)","file":"pkg/volume/util/fsquota/quota_linux.go","code":"// SupportsQuotas -- Does the path support quotas\n// Cache the applier for paths that support quotas. For paths that don't,\n// don't cache the result because nothing will clean it up.\n// However, do cache the device-\u003eapplier map; the number of devices\n// is bounded.\nfunc SupportsQuotas(m mount.Interface, path string) (bool, error) {\n\tif !enabledQuotasForMonitoring() {\n\t\tklog.V(3).Info(\"SupportsQuotas called, but quotas disabled\")\n\t\treturn false, nil\n\t}\n\tsupportsQuotasLock.Lock()\n\tdefer supportsQuotasLock.Unlock()\n\tif supportsQuotas, ok := supportsQuotasMap[path]; ok {\n\t\treturn supportsQuotas, nil\n\t}\n\tmount, dev, err := getFSInfo(m, path)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\t// Do we know about this device?\n\tapplier, ok := devApplierMap[mount]\n\tif !ok {\n\t\tfor _, provider := range providers {\n\t\t\tif applier = provider.GetQuotaApplier(mount, dev); applier != nil {\n\t\t\t\tdevApplierMap[mount] = applier\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif applier != nil {\n\t\tsupportsQuotasMap[path] = true\n\t\tsetApplier(path, applier)\n\t\treturn true, nil\n\t}\n\tdelete(backingDevMap, path)\n\tdelete(mountpointMap, path)\n\treturn false, nil\n}","line":{"from":267,"to":304}} {"id":100012931,"name":"AssignQuota","signature":"func AssignQuota(m mount.Interface, path string, poduid types.UID, bytes *resource.Quantity) error { //nolint:staticcheck","file":"pkg/volume/util/fsquota/quota_linux.go","code":"// AssignQuota -- assign a quota to the specified directory.\n// AssignQuota chooses the quota ID based on the pod UID and path.\n// If the pod UID is identical to another one known, it may (but presently\n// doesn't) choose the same quota ID as other volumes in the pod.\nfunc AssignQuota(m mount.Interface, path string, poduid types.UID, bytes *resource.Quantity) error { //nolint:staticcheck\n\tif bytes == nil {\n\t\treturn fmt.Errorf(\"attempting to assign null quota to %s\", path)\n\t}\n\tibytes := bytes.Value()\n\tif ok, err := SupportsQuotas(m, path); !ok {\n\t\treturn fmt.Errorf(\"quotas not supported on %s: %v\", path, err)\n\t}\n\tquotaLock.Lock()\n\tdefer quotaLock.Unlock()\n\t// Current policy is to set individual quotas on each volume,\n\t// for each new volume we generate a random UUID and we use that as\n\t// the internal pod uid.\n\t// From fsquota point of view each volume is attached to a\n\t// single unique pod.\n\t// If we decide later that we want to assign one quota for all\n\t// volumes in a pod, we can simply use poduid parameter directly\n\t// If and when we decide permanently that we're going to adopt\n\t// one quota per volume, we can rip all of the pod code out.\n\texternalPodUid := poduid\n\tinternalPodUid, ok := dirPodMap[path]\n\tif ok {\n\t\tif podUidMap[internalPodUid] != externalPodUid {\n\t\t\treturn fmt.Errorf(\"requesting quota on existing directory %s but different pod %s %s\", path, podUidMap[internalPodUid], externalPodUid)\n\t\t}\n\t} else {\n\t\tinternalPodUid = types.UID(uuid.NewUUID())\n\t}\n\toid, ok := podQuotaMap[internalPodUid]\n\tif ok {\n\t\tif quotaSizeMap[oid] != ibytes {\n\t\t\treturn fmt.Errorf(\"requesting quota of different size: old %v new %v\", quotaSizeMap[oid], bytes)\n\t\t}\n\t\tif _, ok := dirPodMap[path]; ok {\n\t\t\treturn nil\n\t\t}\n\t} else {\n\t\toid = common.BadQuotaID\n\t}\n\tid, err := createProjectID(path, oid)\n\tif err == nil {\n\t\tif oid != common.BadQuotaID \u0026\u0026 oid != id {\n\t\t\treturn fmt.Errorf(\"attempt to reassign quota %v to %v\", oid, id)\n\t\t}\n\t\t// When enforcing quotas are enabled, we'll condition this\n\t\t// on their being disabled also.\n\t\tif ibytes \u003e 0 {\n\t\t\tibytes = -1\n\t\t}\n\t\tif err = setQuotaOnDir(path, id, ibytes); err == nil {\n\t\t\tquotaPodMap[id] = internalPodUid\n\t\t\tquotaSizeMap[id] = ibytes\n\t\t\tpodQuotaMap[internalPodUid] = id\n\t\t\tdirQuotaMap[path] = id\n\t\t\tdirPodMap[path] = internalPodUid\n\t\t\tpodUidMap[internalPodUid] = externalPodUid\n\t\t\tpodDirCountMap[internalPodUid]++\n\t\t\tklog.V(4).Infof(\"Assigning quota ID %d (%d) to %s\", id, ibytes, path)\n\t\t\treturn nil\n\t\t}\n\t\tremoveProjectID(path, id)\n\t}\n\treturn fmt.Errorf(\"assign quota FAILED %v\", err)\n}","line":{"from":306,"to":373}} {"id":100012932,"name":"GetConsumption","signature":"func GetConsumption(path string) (*resource.Quantity, error)","file":"pkg/volume/util/fsquota/quota_linux.go","code":"// GetConsumption -- retrieve the consumption (in bytes) of the directory\nfunc GetConsumption(path string) (*resource.Quantity, error) {\n\t// Note that we actually need to hold the lock at least through\n\t// running the quota command, so it can't get recycled behind our back\n\tquotaLock.Lock()\n\tdefer quotaLock.Unlock()\n\tapplier := getApplier(path)\n\t// No applier means directory is not under quota management\n\tif applier == nil {\n\t\treturn nil, nil\n\t}\n\tibytes, err := applier.GetConsumption(path, dirQuotaMap[path])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resource.NewQuantity(ibytes, resource.DecimalSI), nil\n}","line":{"from":375,"to":391}} {"id":100012933,"name":"GetInodes","signature":"func GetInodes(path string) (*resource.Quantity, error)","file":"pkg/volume/util/fsquota/quota_linux.go","code":"// GetInodes -- retrieve the number of inodes in use under the directory\nfunc GetInodes(path string) (*resource.Quantity, error) {\n\t// Note that we actually need to hold the lock at least through\n\t// running the quota command, so it can't get recycled behind our back\n\tquotaLock.Lock()\n\tdefer quotaLock.Unlock()\n\tapplier := getApplier(path)\n\t// No applier means directory is not under quota management\n\tif applier == nil {\n\t\treturn nil, nil\n\t}\n\tinodes, err := applier.GetInodes(path, dirQuotaMap[path])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resource.NewQuantity(inodes, resource.DecimalSI), nil\n}","line":{"from":393,"to":409}} {"id":100012934,"name":"ClearQuota","signature":"func ClearQuota(m mount.Interface, path string) error","file":"pkg/volume/util/fsquota/quota_linux.go","code":"// ClearQuota -- remove the quota assigned to a directory\nfunc ClearQuota(m mount.Interface, path string) error {\n\tklog.V(3).Infof(\"ClearQuota %s\", path)\n\tif !enabledQuotasForMonitoring() {\n\t\treturn fmt.Errorf(\"clearQuota called, but quotas disabled\")\n\t}\n\tquotaLock.Lock()\n\tdefer quotaLock.Unlock()\n\tpoduid, ok := dirPodMap[path]\n\tif !ok {\n\t\t// Nothing in the map either means that there was no\n\t\t// quota to begin with or that we're clearing a\n\t\t// stale directory, so if we find a quota, just remove it.\n\t\t// The process of clearing the quota requires that an applier\n\t\t// be found, which needs to be cleaned up.\n\t\tdefer delete(supportsQuotasMap, path)\n\t\tdefer clearApplier(path)\n\t\treturn clearQuotaOnDir(m, path)\n\t}\n\t_, ok = podQuotaMap[poduid]\n\tif !ok {\n\t\treturn fmt.Errorf(\"clearQuota: No quota available for %s\", path)\n\t}\n\tprojid, err := GetQuotaOnDir(m, path)\n\tif err != nil {\n\t\t// Log-and-continue instead of returning an error for now\n\t\t// due to unspecified backwards compatibility concerns (a subject to revise)\n\t\tklog.V(3).Infof(\"Attempt to check quota ID %v on dir %s failed: %v\", dirQuotaMap[path], path, err)\n\t}\n\tif projid != dirQuotaMap[path] {\n\t\treturn fmt.Errorf(\"expected quota ID %v on dir %s does not match actual %v\", dirQuotaMap[path], path, projid)\n\t}\n\tcount, ok := podDirCountMap[poduid]\n\tif count \u003c= 1 || !ok {\n\t\terr = clearQuotaOnDir(m, path)\n\t\t// This error should be noted; we still need to clean up\n\t\t// and otherwise handle in the same way.\n\t\tif err != nil {\n\t\t\tklog.V(3).Infof(\"Unable to clear quota %v %s: %v\", dirQuotaMap[path], path, err)\n\t\t}\n\t\tdelete(quotaSizeMap, podQuotaMap[poduid])\n\t\tdelete(quotaPodMap, podQuotaMap[poduid])\n\t\tdelete(podDirCountMap, poduid)\n\t\tdelete(podQuotaMap, poduid)\n\t\tdelete(podUidMap, poduid)\n\t} else {\n\t\terr = removeProjectID(path, projid)\n\t\tpodDirCountMap[poduid]--\n\t\tklog.V(4).Infof(\"Not clearing quota for pod %s; still %v dirs outstanding\", poduid, podDirCountMap[poduid])\n\t}\n\tdelete(dirPodMap, path)\n\tdelete(dirQuotaMap, path)\n\tdelete(supportsQuotasMap, path)\n\tclearApplier(path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to clear quota for %s: %v\", path, err)\n\t}\n\treturn nil\n}","line":{"from":411,"to":469}} {"id":100012935,"name":"GetQuotaOnDir","signature":"func GetQuotaOnDir(_ mount.Interface, _ string) (common.QuotaID, error)","file":"pkg/volume/util/fsquota/quota_unsupported.go","code":"func GetQuotaOnDir(_ mount.Interface, _ string) (common.QuotaID, error) {\n\treturn common.BadQuotaID, errNotImplemented\n}","line":{"from":37,"to":39}} {"id":100012936,"name":"SupportsQuotas","signature":"func SupportsQuotas(_ mount.Interface, _ string) (bool, error)","file":"pkg/volume/util/fsquota/quota_unsupported.go","code":"// SupportsQuotas -- dummy implementation\nfunc SupportsQuotas(_ mount.Interface, _ string) (bool, error) {\n\treturn false, errNotImplemented\n}","line":{"from":41,"to":44}} {"id":100012937,"name":"AssignQuota","signature":"func AssignQuota(_ mount.Interface, _ string, _ types.UID, _ *resource.Quantity) error","file":"pkg/volume/util/fsquota/quota_unsupported.go","code":"// AssignQuota -- dummy implementation\nfunc AssignQuota(_ mount.Interface, _ string, _ types.UID, _ *resource.Quantity) error {\n\treturn errNotImplemented\n}","line":{"from":46,"to":49}} {"id":100012938,"name":"GetConsumption","signature":"func GetConsumption(_ string) (*resource.Quantity, error)","file":"pkg/volume/util/fsquota/quota_unsupported.go","code":"// GetConsumption -- dummy implementation\nfunc GetConsumption(_ string) (*resource.Quantity, error) {\n\treturn nil, errNotImplemented\n}","line":{"from":51,"to":54}} {"id":100012939,"name":"GetInodes","signature":"func GetInodes(_ string) (*resource.Quantity, error)","file":"pkg/volume/util/fsquota/quota_unsupported.go","code":"// GetInodes -- dummy implementation\nfunc GetInodes(_ string) (*resource.Quantity, error) {\n\treturn nil, errNotImplemented\n}","line":{"from":56,"to":59}} {"id":100012940,"name":"ClearQuota","signature":"func ClearQuota(_ mount.Interface, _ string) error","file":"pkg/volume/util/fsquota/quota_unsupported.go","code":"// ClearQuota -- dummy implementation\nfunc ClearQuota(_ mount.Interface, _ string) error {\n\treturn errNotImplemented\n}","line":{"from":61,"to":64}} {"id":100012941,"name":"getFileType","signature":"func getFileType(pathname string) (FileType, error)","file":"pkg/volume/util/hostutil/hostutil.go","code":"// getFileType checks for file/directory/socket and block/character devices.\nfunc getFileType(pathname string) (FileType, error) {\n\tvar pathType FileType\n\tinfo, err := os.Stat(pathname)\n\tif os.IsNotExist(err) {\n\t\treturn pathType, fmt.Errorf(\"path %q does not exist\", pathname)\n\t}\n\t// err in call to os.Stat\n\tif err != nil {\n\t\treturn pathType, err\n\t}\n\n\t// checks whether the mode is the target mode.\n\tisSpecificMode := func(mode, targetMode os.FileMode) bool {\n\t\treturn mode\u0026targetMode == targetMode\n\t}\n\n\tmode := info.Mode()\n\tif mode.IsDir() {\n\t\treturn FileTypeDirectory, nil\n\t} else if mode.IsRegular() {\n\t\treturn FileTypeFile, nil\n\t} else if isSpecificMode(mode, os.ModeSocket) {\n\t\treturn FileTypeSocket, nil\n\t} else if isSpecificMode(mode, os.ModeDevice) {\n\t\tif isSpecificMode(mode, os.ModeCharDevice) {\n\t\t\treturn FileTypeCharDev, nil\n\t\t}\n\t\treturn FileTypeBlockDev, nil\n\t}\n\n\treturn pathType, fmt.Errorf(\"only recognise file, directory, socket, block device and character device\")\n}","line":{"from":80,"to":112}} {"id":100012942,"name":"NewHostUtil","signature":"func NewHostUtil() *HostUtil","file":"pkg/volume/util/hostutil/hostutil_linux.go","code":"// NewHostUtil returns a struct that implements the HostUtils interface on\n// linux platforms\nfunc NewHostUtil() *HostUtil {\n\treturn \u0026HostUtil{}\n}","line":{"from":46,"to":50}} {"id":100012943,"name":"DeviceOpened","signature":"func (hu *HostUtil) DeviceOpened(pathname string) (bool, error)","file":"pkg/volume/util/hostutil/hostutil_linux.go","code":"// DeviceOpened checks if block device in use by calling Open with O_EXCL flag.\n// If pathname is not a device, log and return false with nil error.\n// If open returns errno EBUSY, return true with nil error.\n// If open returns nil, return false with nil error.\n// Otherwise, return false with error\nfunc (hu *HostUtil) DeviceOpened(pathname string) (bool, error) {\n\treturn ExclusiveOpenFailsOnDevice(pathname)\n}","line":{"from":52,"to":59}} {"id":100012944,"name":"PathIsDevice","signature":"func (hu *HostUtil) PathIsDevice(pathname string) (bool, error)","file":"pkg/volume/util/hostutil/hostutil_linux.go","code":"// PathIsDevice uses FileInfo returned from os.Stat to check if path refers\n// to a device.\nfunc (hu *HostUtil) PathIsDevice(pathname string) (bool, error) {\n\tpathType, err := hu.GetFileType(pathname)\n\tisDevice := pathType == FileTypeCharDev || pathType == FileTypeBlockDev\n\treturn isDevice, err\n}","line":{"from":61,"to":67}} {"id":100012945,"name":"ExclusiveOpenFailsOnDevice","signature":"func ExclusiveOpenFailsOnDevice(pathname string) (bool, error)","file":"pkg/volume/util/hostutil/hostutil_linux.go","code":"// ExclusiveOpenFailsOnDevice is shared with NsEnterMounter\nfunc ExclusiveOpenFailsOnDevice(pathname string) (bool, error) {\n\tvar isDevice bool\n\tfinfo, err := os.Stat(pathname)\n\tif os.IsNotExist(err) {\n\t\tisDevice = false\n\t}\n\t// err in call to os.Stat\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\n\t\t\t\"PathIsDevice failed for path %q: %v\",\n\t\t\tpathname,\n\t\t\terr)\n\t}\n\t// path refers to a device\n\tif finfo.Mode()\u0026os.ModeDevice != 0 {\n\t\tisDevice = true\n\t}\n\n\tif !isDevice {\n\t\tklog.Errorf(\"Path %q is not referring to a device.\", pathname)\n\t\treturn false, nil\n\t}\n\tfd, errno := unix.Open(pathname, unix.O_RDONLY|unix.O_EXCL|unix.O_CLOEXEC, 0)\n\t// If the device is in use, open will return an invalid fd.\n\t// When this happens, it is expected that Close will fail and throw an error.\n\tdefer unix.Close(fd)\n\tif errno == nil {\n\t\t// device not in use\n\t\treturn false, nil\n\t} else if errno == unix.EBUSY {\n\t\t// device is in use\n\t\treturn true, nil\n\t}\n\t// error during call to Open\n\treturn false, errno\n}","line":{"from":69,"to":105}} {"id":100012946,"name":"GetDeviceNameFromMount","signature":"func (hu *HostUtil) GetDeviceNameFromMount(mounter mount.Interface, mountPath, pluginMountDir string) (string, error)","file":"pkg/volume/util/hostutil/hostutil_linux.go","code":"// GetDeviceNameFromMount given a mount point, find the device name from its global mount point\nfunc (hu *HostUtil) GetDeviceNameFromMount(mounter mount.Interface, mountPath, pluginMountDir string) (string, error) {\n\treturn getDeviceNameFromMount(mounter, mountPath, pluginMountDir)\n}","line":{"from":107,"to":110}} {"id":100012947,"name":"getDeviceNameFromMount","signature":"func getDeviceNameFromMount(mounter mount.Interface, mountPath, pluginMountDir string) (string, error)","file":"pkg/volume/util/hostutil/hostutil_linux.go","code":"// getDeviceNameFromMountLinux find the device name from /proc/mounts in which\n// the mount path reference should match the given plugin mount directory. In case no mount path reference\n// matches, returns the volume name taken from its given mountPath\nfunc getDeviceNameFromMount(mounter mount.Interface, mountPath, pluginMountDir string) (string, error) {\n\trefs, err := mounter.GetMountRefs(mountPath)\n\tif err != nil {\n\t\tklog.V(4).Infof(\"GetMountRefs failed for mount path %q: %v\", mountPath, err)\n\t\treturn \"\", err\n\t}\n\tif len(refs) == 0 {\n\t\tklog.V(4).Infof(\"Directory %s is not mounted\", mountPath)\n\t\treturn \"\", fmt.Errorf(\"directory %s is not mounted\", mountPath)\n\t}\n\tfor _, ref := range refs {\n\t\tif strings.HasPrefix(ref, pluginMountDir) {\n\t\t\tvolumeID, err := filepath.Rel(pluginMountDir, ref)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"Failed to get volume id from mount %s - %v\", mountPath, err)\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\treturn volumeID, nil\n\t\t}\n\t}\n\n\treturn path.Base(mountPath), nil\n}","line":{"from":112,"to":137}} {"id":100012948,"name":"MakeRShared","signature":"func (hu *HostUtil) MakeRShared(path string) error","file":"pkg/volume/util/hostutil/hostutil_linux.go","code":"// MakeRShared checks that given path is on a mount with 'rshared' mount\n// propagation. If not, it bind-mounts the path as rshared.\nfunc (hu *HostUtil) MakeRShared(path string) error {\n\treturn DoMakeRShared(path, procMountInfoPath)\n}","line":{"from":139,"to":143}} {"id":100012949,"name":"GetFileType","signature":"func (hu *HostUtil) GetFileType(pathname string) (FileType, error)","file":"pkg/volume/util/hostutil/hostutil_linux.go","code":"// GetFileType checks for file/directory/socket/block/character devices.\nfunc (hu *HostUtil) GetFileType(pathname string) (FileType, error) {\n\treturn getFileType(pathname)\n}","line":{"from":145,"to":148}} {"id":100012950,"name":"PathExists","signature":"func (hu *HostUtil) PathExists(pathname string) (bool, error)","file":"pkg/volume/util/hostutil/hostutil_linux.go","code":"// PathExists tests if the given path already exists\n// Error is returned on any other error than \"file not found\".\nfunc (hu *HostUtil) PathExists(pathname string) (bool, error) {\n\treturn utilpath.Exists(utilpath.CheckFollowSymlink, pathname)\n}","line":{"from":150,"to":154}} {"id":100012951,"name":"EvalHostSymlinks","signature":"func (hu *HostUtil) EvalHostSymlinks(pathname string) (string, error)","file":"pkg/volume/util/hostutil/hostutil_linux.go","code":"// EvalHostSymlinks returns the path name after evaluating symlinks.\n// TODO once the nsenter implementation is removed, this method can be removed\n// from the interface and filepath.EvalSymlinks used directly\nfunc (hu *HostUtil) EvalHostSymlinks(pathname string) (string, error) {\n\treturn filepath.EvalSymlinks(pathname)\n}","line":{"from":156,"to":161}} {"id":100012952,"name":"FindMountInfo","signature":"func (hu *HostUtil) FindMountInfo(path string) (mount.MountInfo, error)","file":"pkg/volume/util/hostutil/hostutil_linux.go","code":"// FindMountInfo returns the mount info on the given path.\nfunc (hu *HostUtil) FindMountInfo(path string) (mount.MountInfo, error) {\n\treturn findMountInfo(path, procMountInfoPath)\n}","line":{"from":163,"to":166}} {"id":100012953,"name":"isShared","signature":"func isShared(mount string, mountInfoPath string) (bool, error)","file":"pkg/volume/util/hostutil/hostutil_linux.go","code":"// isShared returns true, if given path is on a mount point that has shared\n// mount propagation.\nfunc isShared(mount string, mountInfoPath string) (bool, error) {\n\tinfo, err := findMountInfo(mount, mountInfoPath)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t// parse optional parameters\n\tfor _, opt := range info.OptionalFields {\n\t\tif strings.HasPrefix(opt, \"shared:\") {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}","line":{"from":168,"to":183}} {"id":100012954,"name":"findMountInfo","signature":"func findMountInfo(path, mountInfoPath string) (mount.MountInfo, error)","file":"pkg/volume/util/hostutil/hostutil_linux.go","code":"func findMountInfo(path, mountInfoPath string) (mount.MountInfo, error) {\n\tinfos, err := mount.ParseMountInfo(mountInfoPath)\n\tif err != nil {\n\t\treturn mount.MountInfo{}, err\n\t}\n\n\t// process /proc/xxx/mountinfo in backward order and find the first mount\n\t// point that is prefix of 'path' - that's the mount where path resides\n\tvar info *mount.MountInfo\n\tfor i := len(infos) - 1; i \u003e= 0; i-- {\n\t\tif mount.PathWithinBase(path, infos[i].MountPoint) {\n\t\t\tinfo = \u0026infos[i]\n\t\t\tbreak\n\t\t}\n\t}\n\tif info == nil {\n\t\treturn mount.MountInfo{}, fmt.Errorf(\"cannot find mount point for %q\", path)\n\t}\n\treturn *info, nil\n}","line":{"from":185,"to":204}} {"id":100012955,"name":"DoMakeRShared","signature":"func DoMakeRShared(path string, mountInfoFilename string) error","file":"pkg/volume/util/hostutil/hostutil_linux.go","code":"// DoMakeRShared is common implementation of MakeRShared on Linux. It checks if\n// path is shared and bind-mounts it as rshared if needed. mountCmd and\n// mountArgs are expected to contain mount-like command, DoMakeRShared will add\n// '--bind \u003cpath\u003e \u003cpath\u003e' and '--make-rshared \u003cpath\u003e' to mountArgs.\nfunc DoMakeRShared(path string, mountInfoFilename string) error {\n\tshared, err := isShared(path, mountInfoFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif shared {\n\t\tklog.V(4).Infof(\"Directory %s is already on a shared mount\", path)\n\t\treturn nil\n\t}\n\n\tklog.V(2).Infof(\"Bind-mounting %q with shared mount propagation\", path)\n\t// mount --bind /var/lib/kubelet /var/lib/kubelet\n\tif err := syscall.Mount(path, path, \"\" /*fstype*/, syscall.MS_BIND, \"\" /*data*/); err != nil {\n\t\treturn fmt.Errorf(\"failed to bind-mount %s: %v\", path, err)\n\t}\n\n\t// mount --make-rshared /var/lib/kubelet\n\tif err := syscall.Mount(path, path, \"\" /*fstype*/, syscall.MS_SHARED|syscall.MS_REC, \"\" /*data*/); err != nil {\n\t\treturn fmt.Errorf(\"failed to make %s rshared: %v\", path, err)\n\t}\n\n\treturn nil\n}","line":{"from":206,"to":232}} {"id":100012956,"name":"GetSELinux","signature":"func GetSELinux(path string, mountInfoFilename string, selinuxEnabled seLinuxEnabledFunc) (bool, error)","file":"pkg/volume/util/hostutil/hostutil_linux.go","code":"// GetSELinux is common implementation of GetSELinuxSupport on Linux.\nfunc GetSELinux(path string, mountInfoFilename string, selinuxEnabled seLinuxEnabledFunc) (bool, error) {\n\t// Skip /proc/mounts parsing if SELinux is disabled.\n\tif !selinuxEnabled() {\n\t\treturn false, nil\n\t}\n\n\tinfo, err := findMountInfo(path, mountInfoFilename)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t// \"seclabel\" can be both in mount options and super options.\n\tfor _, opt := range info.SuperOptions {\n\t\tif opt == \"seclabel\" {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\tfor _, opt := range info.MountOptions {\n\t\tif opt == \"seclabel\" {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}","line":{"from":237,"to":261}} {"id":100012957,"name":"GetSELinuxSupport","signature":"func (hu *HostUtil) GetSELinuxSupport(pathname string) (bool, error)","file":"pkg/volume/util/hostutil/hostutil_linux.go","code":"// GetSELinuxSupport returns true if given path is on a mount that supports\n// SELinux.\nfunc (hu *HostUtil) GetSELinuxSupport(pathname string) (bool, error) {\n\treturn GetSELinux(pathname, procMountInfoPath, selinux.GetEnabled)\n}","line":{"from":263,"to":267}} {"id":100012958,"name":"GetOwner","signature":"func (hu *HostUtil) GetOwner(pathname string) (int64, int64, error)","file":"pkg/volume/util/hostutil/hostutil_linux.go","code":"// GetOwner returns the integer ID for the user and group of the given path\nfunc (hu *HostUtil) GetOwner(pathname string) (int64, int64, error) {\n\trealpath, err := filepath.EvalSymlinks(pathname)\n\tif err != nil {\n\t\treturn -1, -1, err\n\t}\n\treturn GetOwnerLinux(realpath)\n}","line":{"from":269,"to":276}} {"id":100012959,"name":"GetMode","signature":"func (hu *HostUtil) GetMode(pathname string) (os.FileMode, error)","file":"pkg/volume/util/hostutil/hostutil_linux.go","code":"// GetMode returns permissions of the path.\nfunc (hu *HostUtil) GetMode(pathname string) (os.FileMode, error) {\n\treturn GetModeLinux(pathname)\n}","line":{"from":278,"to":281}} {"id":100012960,"name":"GetOwnerLinux","signature":"func GetOwnerLinux(pathname string) (int64, int64, error)","file":"pkg/volume/util/hostutil/hostutil_linux.go","code":"// GetOwnerLinux is shared between Linux and NsEnterMounter\n// pathname must already be evaluated for symlinks\nfunc GetOwnerLinux(pathname string) (int64, int64, error) {\n\tinfo, err := os.Stat(pathname)\n\tif err != nil {\n\t\treturn -1, -1, err\n\t}\n\tstat := info.Sys().(*syscall.Stat_t)\n\treturn int64(stat.Uid), int64(stat.Gid), nil\n}","line":{"from":283,"to":292}} {"id":100012961,"name":"GetModeLinux","signature":"func GetModeLinux(pathname string) (os.FileMode, error)","file":"pkg/volume/util/hostutil/hostutil_linux.go","code":"// GetModeLinux is shared between Linux and NsEnterMounter\nfunc GetModeLinux(pathname string) (os.FileMode, error) {\n\tinfo, err := os.Stat(pathname)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn info.Mode(), nil\n}","line":{"from":294,"to":301}} {"id":100012962,"name":"GetSELinuxMountContext","signature":"func (hu *HostUtil) GetSELinuxMountContext(pathname string) (string, error)","file":"pkg/volume/util/hostutil/hostutil_linux.go","code":"// GetSELinuxMountContext returns value of -o context=XYZ mount option on\n// given mount point.\nfunc (hu *HostUtil) GetSELinuxMountContext(pathname string) (string, error) {\n\treturn getSELinuxMountContext(pathname, procMountInfoPath, selinux.GetEnabled)\n}","line":{"from":303,"to":307}} {"id":100012963,"name":"getSELinuxMountContext","signature":"func getSELinuxMountContext(path string, mountInfoFilename string, selinuxEnabled seLinuxEnabledFunc) (string, error)","file":"pkg/volume/util/hostutil/hostutil_linux.go","code":"// getSELinux is common implementation of GetSELinuxSupport on Linux.\n// Using an extra function for unit tests.\nfunc getSELinuxMountContext(path string, mountInfoFilename string, selinuxEnabled seLinuxEnabledFunc) (string, error) {\n\t// Skip /proc/mounts parsing if SELinux is disabled.\n\tif !selinuxEnabled() {\n\t\treturn \"\", nil\n\t}\n\n\tinfo, err := findMountInfo(path, mountInfoFilename)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, opt := range info.SuperOptions {\n\t\tif !strings.HasPrefix(opt, \"context=\") {\n\t\t\tcontinue\n\t\t}\n\t\t// Remove context=\n\t\tcontext := strings.TrimPrefix(opt, \"context=\")\n\t\t// Remove double quotes\n\t\tcontext = strings.Trim(context, \"\\\"\")\n\t\treturn context, nil\n\t}\n\treturn \"\", nil\n}","line":{"from":309,"to":333}} {"id":100012964,"name":"NewHostUtil","signature":"func NewHostUtil() *HostUtil","file":"pkg/volume/util/hostutil/hostutil_unsupported.go","code":"// NewHostUtil returns a struct that implements the HostUtils interface on\n// unsupported platforms\nfunc NewHostUtil() *HostUtil {\n\treturn \u0026HostUtil{}\n}","line":{"from":33,"to":37}} {"id":100012965,"name":"DeviceOpened","signature":"func (hu *HostUtil) DeviceOpened(pathname string) (bool, error)","file":"pkg/volume/util/hostutil/hostutil_unsupported.go","code":"// DeviceOpened always returns an error on unsupported platforms\nfunc (hu *HostUtil) DeviceOpened(pathname string) (bool, error) {\n\treturn false, errUnsupported\n}","line":{"from":41,"to":44}} {"id":100012966,"name":"PathIsDevice","signature":"func (hu *HostUtil) PathIsDevice(pathname string) (bool, error)","file":"pkg/volume/util/hostutil/hostutil_unsupported.go","code":"// PathIsDevice always returns an error on unsupported platforms\nfunc (hu *HostUtil) PathIsDevice(pathname string) (bool, error) {\n\treturn true, errUnsupported\n}","line":{"from":46,"to":49}} {"id":100012967,"name":"GetDeviceNameFromMount","signature":"func (hu *HostUtil) GetDeviceNameFromMount(mounter mount.Interface, mountPath, pluginMountDir string) (string, error)","file":"pkg/volume/util/hostutil/hostutil_unsupported.go","code":"// GetDeviceNameFromMount always returns an error on unsupported platforms\nfunc (hu *HostUtil) GetDeviceNameFromMount(mounter mount.Interface, mountPath, pluginMountDir string) (string, error) {\n\treturn getDeviceNameFromMount(mounter, mountPath, pluginMountDir)\n}","line":{"from":51,"to":54}} {"id":100012968,"name":"MakeRShared","signature":"func (hu *HostUtil) MakeRShared(path string) error","file":"pkg/volume/util/hostutil/hostutil_unsupported.go","code":"// MakeRShared always returns an error on unsupported platforms\nfunc (hu *HostUtil) MakeRShared(path string) error {\n\treturn errUnsupported\n}","line":{"from":56,"to":59}} {"id":100012969,"name":"GetFileType","signature":"func (hu *HostUtil) GetFileType(pathname string) (FileType, error)","file":"pkg/volume/util/hostutil/hostutil_unsupported.go","code":"// GetFileType always returns an error on unsupported platforms\nfunc (hu *HostUtil) GetFileType(pathname string) (FileType, error) {\n\treturn FileType(\"fake\"), errUnsupported\n}","line":{"from":61,"to":64}} {"id":100012970,"name":"MakeFile","signature":"func (hu *HostUtil) MakeFile(pathname string) error","file":"pkg/volume/util/hostutil/hostutil_unsupported.go","code":"// MakeFile always returns an error on unsupported platforms\nfunc (hu *HostUtil) MakeFile(pathname string) error {\n\treturn errUnsupported\n}","line":{"from":66,"to":69}} {"id":100012971,"name":"MakeDir","signature":"func (hu *HostUtil) MakeDir(pathname string) error","file":"pkg/volume/util/hostutil/hostutil_unsupported.go","code":"// MakeDir always returns an error on unsupported platforms\nfunc (hu *HostUtil) MakeDir(pathname string) error {\n\treturn errUnsupported\n}","line":{"from":71,"to":74}} {"id":100012972,"name":"PathExists","signature":"func (hu *HostUtil) PathExists(pathname string) (bool, error)","file":"pkg/volume/util/hostutil/hostutil_unsupported.go","code":"// PathExists always returns an error on unsupported platforms\nfunc (hu *HostUtil) PathExists(pathname string) (bool, error) {\n\treturn true, errUnsupported\n}","line":{"from":76,"to":79}} {"id":100012973,"name":"EvalHostSymlinks","signature":"func (hu *HostUtil) EvalHostSymlinks(pathname string) (string, error)","file":"pkg/volume/util/hostutil/hostutil_unsupported.go","code":"// EvalHostSymlinks always returns an error on unsupported platforms\nfunc (hu *HostUtil) EvalHostSymlinks(pathname string) (string, error) {\n\treturn \"\", errUnsupported\n}","line":{"from":81,"to":84}} {"id":100012974,"name":"GetOwner","signature":"func (hu *HostUtil) GetOwner(pathname string) (int64, int64, error)","file":"pkg/volume/util/hostutil/hostutil_unsupported.go","code":"// GetOwner always returns an error on unsupported platforms\nfunc (hu *HostUtil) GetOwner(pathname string) (int64, int64, error) {\n\treturn -1, -1, errUnsupported\n}","line":{"from":86,"to":89}} {"id":100012975,"name":"GetSELinuxSupport","signature":"func (hu *HostUtil) GetSELinuxSupport(pathname string) (bool, error)","file":"pkg/volume/util/hostutil/hostutil_unsupported.go","code":"// GetSELinuxSupport always returns an error on unsupported platforms\nfunc (hu *HostUtil) GetSELinuxSupport(pathname string) (bool, error) {\n\treturn false, errUnsupported\n}","line":{"from":91,"to":94}} {"id":100012976,"name":"GetMode","signature":"func (hu *HostUtil) GetMode(pathname string) (os.FileMode, error)","file":"pkg/volume/util/hostutil/hostutil_unsupported.go","code":"// GetMode always returns an error on unsupported platforms\nfunc (hu *HostUtil) GetMode(pathname string) (os.FileMode, error) {\n\treturn 0, errUnsupported\n}","line":{"from":96,"to":99}} {"id":100012977,"name":"getDeviceNameFromMount","signature":"func getDeviceNameFromMount(mounter mount.Interface, mountPath, pluginMountDir string) (string, error)","file":"pkg/volume/util/hostutil/hostutil_unsupported.go","code":"func getDeviceNameFromMount(mounter mount.Interface, mountPath, pluginMountDir string) (string, error) {\n\treturn \"\", errUnsupported\n}","line":{"from":101,"to":103}} {"id":100012978,"name":"GetSELinuxMountContext","signature":"func (hu *HostUtil) GetSELinuxMountContext(pathname string) (string, error)","file":"pkg/volume/util/hostutil/hostutil_unsupported.go","code":"// GetSELinuxMountContext returns value of -o context=XYZ mount option on\n// given mount point.\nfunc (hu *HostUtil) GetSELinuxMountContext(pathname string) (string, error) {\n\treturn \"\", errUnsupported\n}","line":{"from":105,"to":109}} {"id":100012979,"name":"NewHostUtil","signature":"func NewHostUtil() *HostUtil","file":"pkg/volume/util/hostutil/hostutil_windows.go","code":"// NewHostUtil returns a struct that implements HostUtils on Windows platforms\nfunc NewHostUtil() *HostUtil {\n\treturn \u0026HostUtil{}\n}","line":{"from":37,"to":40}} {"id":100012980,"name":"GetDeviceNameFromMount","signature":"func (hu *HostUtil) GetDeviceNameFromMount(mounter mount.Interface, mountPath, pluginMountDir string) (string, error)","file":"pkg/volume/util/hostutil/hostutil_windows.go","code":"// GetDeviceNameFromMount given a mnt point, find the device\nfunc (hu *HostUtil) GetDeviceNameFromMount(mounter mount.Interface, mountPath, pluginMountDir string) (string, error) {\n\treturn getDeviceNameFromMount(mounter, mountPath, pluginMountDir)\n}","line":{"from":42,"to":45}} {"id":100012981,"name":"getDeviceNameFromMount","signature":"func getDeviceNameFromMount(mounter mount.Interface, mountPath, pluginMountDir string) (string, error)","file":"pkg/volume/util/hostutil/hostutil_windows.go","code":"// getDeviceNameFromMount find the device(drive) name in which\n// the mount path reference should match the given plugin mount directory. In case no mount path reference\n// matches, returns the volume name taken from its given mountPath\nfunc getDeviceNameFromMount(mounter mount.Interface, mountPath, pluginMountDir string) (string, error) {\n\trefs, err := mounter.GetMountRefs(mountPath)\n\tif err != nil {\n\t\tklog.V(4).Infof(\"GetMountRefs failed for mount path %q: %v\", mountPath, err)\n\t\treturn \"\", err\n\t}\n\tif len(refs) == 0 {\n\t\treturn \"\", fmt.Errorf(\"directory %s is not mounted\", mountPath)\n\t}\n\tbasemountPath := mount.NormalizeWindowsPath(pluginMountDir)\n\tfor _, ref := range refs {\n\t\tif strings.Contains(ref, basemountPath) {\n\t\t\tvolumeID, err := filepath.Rel(mount.NormalizeWindowsPath(basemountPath), ref)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"Failed to get volume id from mount %s - %v\", mountPath, err)\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\treturn volumeID, nil\n\t\t}\n\t}\n\n\treturn path.Base(mountPath), nil\n}","line":{"from":47,"to":72}} {"id":100012982,"name":"DeviceOpened","signature":"func (hu *HostUtil) DeviceOpened(pathname string) (bool, error)","file":"pkg/volume/util/hostutil/hostutil_windows.go","code":"// DeviceOpened determines if the device is in use elsewhere\nfunc (hu *HostUtil) DeviceOpened(pathname string) (bool, error) {\n\treturn false, nil\n}","line":{"from":74,"to":77}} {"id":100012983,"name":"PathIsDevice","signature":"func (hu *HostUtil) PathIsDevice(pathname string) (bool, error)","file":"pkg/volume/util/hostutil/hostutil_windows.go","code":"// PathIsDevice determines if a path is a device.\nfunc (hu *HostUtil) PathIsDevice(pathname string) (bool, error) {\n\treturn false, nil\n}","line":{"from":79,"to":82}} {"id":100012984,"name":"MakeRShared","signature":"func (hu *HostUtil) MakeRShared(path string) error","file":"pkg/volume/util/hostutil/hostutil_windows.go","code":"// MakeRShared checks that given path is on a mount with 'rshared' mount\n// propagation. Empty implementation here.\nfunc (hu *HostUtil) MakeRShared(path string) error {\n\treturn nil\n}","line":{"from":84,"to":88}} {"id":100012985,"name":"GetFileType","signature":"func (hu *(HostUtil)) GetFileType(pathname string) (FileType, error)","file":"pkg/volume/util/hostutil/hostutil_windows.go","code":"// GetFileType checks for sockets/block/character devices\nfunc (hu *(HostUtil)) GetFileType(pathname string) (FileType, error) {\n\treturn getFileType(pathname)\n}","line":{"from":90,"to":93}} {"id":100012986,"name":"PathExists","signature":"func (hu *HostUtil) PathExists(pathname string) (bool, error)","file":"pkg/volume/util/hostutil/hostutil_windows.go","code":"// PathExists checks whether the path exists\nfunc (hu *HostUtil) PathExists(pathname string) (bool, error) {\n\treturn utilpath.Exists(utilpath.CheckFollowSymlink, pathname)\n}","line":{"from":95,"to":98}} {"id":100012987,"name":"EvalHostSymlinks","signature":"func (hu *HostUtil) EvalHostSymlinks(pathname string) (string, error)","file":"pkg/volume/util/hostutil/hostutil_windows.go","code":"// EvalHostSymlinks returns the path name after evaluating symlinks\nfunc (hu *HostUtil) EvalHostSymlinks(pathname string) (string, error) {\n\treturn filepath.EvalSymlinks(pathname)\n}","line":{"from":100,"to":103}} {"id":100012988,"name":"GetOwner","signature":"func (hu *HostUtil) GetOwner(pathname string) (int64, int64, error)","file":"pkg/volume/util/hostutil/hostutil_windows.go","code":"// GetOwner returns the integer ID for the user and group of the given path\n// Note that on windows, it always returns 0. We actually don't set Group on\n// windows platform, see SetVolumeOwnership implementation.\nfunc (hu *HostUtil) GetOwner(pathname string) (int64, int64, error) {\n\treturn -1, -1, nil\n}","line":{"from":105,"to":110}} {"id":100012989,"name":"GetSELinuxSupport","signature":"func (hu *HostUtil) GetSELinuxSupport(pathname string) (bool, error)","file":"pkg/volume/util/hostutil/hostutil_windows.go","code":"// GetSELinuxSupport returns a boolean indicating support for SELinux.\n// Windows does not support SELinux.\nfunc (hu *HostUtil) GetSELinuxSupport(pathname string) (bool, error) {\n\treturn false, nil\n}","line":{"from":112,"to":116}} {"id":100012990,"name":"GetMode","signature":"func (hu *HostUtil) GetMode(pathname string) (os.FileMode, error)","file":"pkg/volume/util/hostutil/hostutil_windows.go","code":"// GetMode returns permissions of the path.\nfunc (hu *HostUtil) GetMode(pathname string) (os.FileMode, error) {\n\tinfo, err := os.Stat(pathname)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn info.Mode(), nil\n}","line":{"from":118,"to":125}} {"id":100012991,"name":"GetSELinuxMountContext","signature":"func (hu *HostUtil) GetSELinuxMountContext(pathname string) (string, error)","file":"pkg/volume/util/hostutil/hostutil_windows.go","code":"// GetSELinuxMountContext returns value of -o context=XYZ mount option on\n// given mount point.\nfunc (hu *HostUtil) GetSELinuxMountContext(pathname string) (string, error) {\n\treturn \"\", nil\n}","line":{"from":127,"to":131}} {"id":100012992,"name":"NewIOHandler","signature":"func NewIOHandler() IoUtil","file":"pkg/volume/util/io_util.go","code":"// NewIOHandler Create a new IoHandler implementation\nfunc NewIOHandler() IoUtil {\n\treturn \u0026osIOHandler{}\n}","line":{"from":35,"to":38}} {"id":100012993,"name":"ReadFile","signature":"func (handler *osIOHandler) ReadFile(filename string) ([]byte, error)","file":"pkg/volume/util/io_util.go","code":"func (handler *osIOHandler) ReadFile(filename string) ([]byte, error) {\n\treturn ioutil.ReadFile(filename)\n}","line":{"from":40,"to":42}} {"id":100012994,"name":"ReadDir","signature":"func (handler *osIOHandler) ReadDir(dirname string) ([]os.FileInfo, error)","file":"pkg/volume/util/io_util.go","code":"func (handler *osIOHandler) ReadDir(dirname string) ([]os.FileInfo, error) {\n\treturn ioutil.ReadDir(dirname)\n}","line":{"from":43,"to":45}} {"id":100012995,"name":"Lstat","signature":"func (handler *osIOHandler) Lstat(name string) (os.FileInfo, error)","file":"pkg/volume/util/io_util.go","code":"func (handler *osIOHandler) Lstat(name string) (os.FileInfo, error) {\n\treturn os.Lstat(name)\n}","line":{"from":46,"to":48}} {"id":100012996,"name":"EvalSymlinks","signature":"func (handler *osIOHandler) EvalSymlinks(path string) (string, error)","file":"pkg/volume/util/io_util.go","code":"func (handler *osIOHandler) EvalSymlinks(path string) (string, error) {\n\treturn filepath.EvalSymlinks(path)\n}","line":{"from":49,"to":51}} {"id":100012997,"name":"init","signature":"func init()","file":"pkg/volume/util/metrics.go","code":"func init() {\n\tregisterMetrics()\n}","line":{"from":77,"to":79}} {"id":100012998,"name":"registerMetrics","signature":"func registerMetrics()","file":"pkg/volume/util/metrics.go","code":"func registerMetrics() {\n\t// legacyregistry is the internal k8s wrapper around the prometheus\n\t// global registry, used specifically for metric stability enforcement\n\tlegacyregistry.MustRegister(StorageOperationMetric)\n\tlegacyregistry.MustRegister(storageOperationEndToEndLatencyMetric)\n\tlegacyregistry.MustRegister(csiOperationsLatencyMetric)\n}","line":{"from":81,"to":87}} {"id":100012999,"name":"OperationCompleteHook","signature":"func OperationCompleteHook(plugin, operationName string) func(types.CompleteFuncParam)","file":"pkg/volume/util/metrics.go","code":"// OperationCompleteHook returns a hook to call when an operation is completed\nfunc OperationCompleteHook(plugin, operationName string) func(types.CompleteFuncParam) {\n\trequestTime := time.Now()\n\topComplete := func(c types.CompleteFuncParam) {\n\t\ttimeTaken := time.Since(requestTime).Seconds()\n\t\t// Create metric with operation name and plugin name\n\t\tstatus := statusSuccess\n\t\tif *c.Err != nil {\n\t\t\t// TODO: Establish well-known error codes to be able to distinguish\n\t\t\t// user configuration errors from system errors.\n\t\t\tstatus = statusFailUnknown\n\t\t}\n\t\tmigrated := false\n\t\tif c.Migrated != nil {\n\t\t\tmigrated = *c.Migrated\n\t\t}\n\t\tStorageOperationMetric.WithLabelValues(plugin, operationName, status, strconv.FormatBool(migrated)).Observe(timeTaken)\n\t}\n\treturn opComplete\n}","line":{"from":89,"to":108}} {"id":100013000,"name":"FSGroupCompleteHook","signature":"func FSGroupCompleteHook(plugin volume.VolumePlugin, spec *volume.Spec) func(types.CompleteFuncParam)","file":"pkg/volume/util/metrics.go","code":"// FSGroupCompleteHook returns a hook to call when volume recursive permission is changed\nfunc FSGroupCompleteHook(plugin volume.VolumePlugin, spec *volume.Spec) func(types.CompleteFuncParam) {\n\treturn OperationCompleteHook(GetFullQualifiedPluginNameForVolume(plugin.GetPluginName(), spec), \"volume_apply_access_control\")\n}","line":{"from":110,"to":113}} {"id":100013001,"name":"GetFullQualifiedPluginNameForVolume","signature":"func GetFullQualifiedPluginNameForVolume(pluginName string, spec *volume.Spec) string","file":"pkg/volume/util/metrics.go","code":"// GetFullQualifiedPluginNameForVolume returns full qualified plugin name for\n// given volume. For CSI plugin, it appends plugin driver name at the end of\n// plugin name, e.g. kubernetes.io/csi:csi-hostpath. It helps to distinguish\n// between metrics emitted for CSI volumes which may be handled by different\n// CSI plugin drivers.\nfunc GetFullQualifiedPluginNameForVolume(pluginName string, spec *volume.Spec) string {\n\tif spec != nil {\n\t\tif spec.Volume != nil \u0026\u0026 spec.Volume.CSI != nil {\n\t\t\treturn fmt.Sprintf(\"%s:%s\", pluginName, spec.Volume.CSI.Driver)\n\t\t}\n\t\tif spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.CSI != nil {\n\t\t\treturn fmt.Sprintf(\"%s:%s\", pluginName, spec.PersistentVolume.Spec.CSI.Driver)\n\t\t}\n\t}\n\treturn pluginName\n}","line":{"from":115,"to":130}} {"id":100013002,"name":"RecordOperationLatencyMetric","signature":"func RecordOperationLatencyMetric(plugin, operationName string, secondsTaken float64)","file":"pkg/volume/util/metrics.go","code":"// RecordOperationLatencyMetric records the end to end latency for certain operation\n// into metric volume_operation_total_seconds\nfunc RecordOperationLatencyMetric(plugin, operationName string, secondsTaken float64) {\n\tstorageOperationEndToEndLatencyMetric.WithLabelValues(plugin, operationName).Observe(secondsTaken)\n}","line":{"from":132,"to":136}} {"id":100013003,"name":"RecordCSIOperationLatencyMetrics","signature":"func RecordCSIOperationLatencyMetrics(driverName string,","file":"pkg/volume/util/metrics.go","code":"// RecordCSIOperationLatencyMetrics records the CSI operation latency and grpc status\n// into metric csi_kubelet_operations_seconds\nfunc RecordCSIOperationLatencyMetrics(driverName string,\n\toperationName string,\n\toperationErr error,\n\toperationDuration time.Duration,\n\tmigrated string) {\n\tcsiOperationsLatencyMetric.WithLabelValues(driverName, operationName, getErrorCode(operationErr), migrated).Observe(operationDuration.Seconds())\n}","line":{"from":138,"to":146}} {"id":100013004,"name":"getErrorCode","signature":"func getErrorCode(err error) string","file":"pkg/volume/util/metrics.go","code":"func getErrorCode(err error) string {\n\tif err == nil {\n\t\treturn codes.OK.String()\n\t}\n\n\tst, ok := status.FromError(err)\n\tif !ok {\n\t\t// This is not gRPC error. The operation must have failed before gRPC\n\t\t// method was called, otherwise we would get gRPC error.\n\t\treturn \"unknown-non-grpc\"\n\t}\n\n\treturn st.Code().String()\n}","line":{"from":148,"to":161}} {"id":100013005,"name":"getNestedMountpoints","signature":"func getNestedMountpoints(name, baseDir string, pod v1.Pod) ([]string, error)","file":"pkg/volume/util/nested_volumes.go","code":"// getNestedMountpoints returns a list of mountpoint directories that should be created\n// for the volume indicated by name.\n// note: the returned list is relative to baseDir\nfunc getNestedMountpoints(name, baseDir string, pod v1.Pod) ([]string, error) {\n\tvar retval []string\n\tcheckContainer := func(container *v1.Container) error {\n\t\tvar allMountPoints []string // all mount points in this container\n\t\tvar myMountPoints []string // mount points that match name\n\t\tfor _, vol := range container.VolumeMounts {\n\t\t\tcleaned := filepath.Clean(vol.MountPath)\n\t\t\tallMountPoints = append(allMountPoints, cleaned)\n\t\t\tif vol.Name == name {\n\t\t\t\tmyMountPoints = append(myMountPoints, cleaned)\n\t\t\t}\n\t\t}\n\t\tsort.Strings(allMountPoints)\n\t\tparentPrefix := \"..\" + string(os.PathSeparator)\n\t\t// Examine each place where this volume is mounted\n\t\tfor _, myMountPoint := range myMountPoints {\n\t\t\tif strings.HasPrefix(myMountPoint, parentPrefix) {\n\t\t\t\t// Don't let a container trick us into creating directories outside of its rootfs\n\t\t\t\treturn fmt.Errorf(\"invalid container mount point %v\", myMountPoint)\n\t\t\t}\n\t\t\tmyMPSlash := myMountPoint + string(os.PathSeparator)\n\t\t\t// The previously found nested mountpoints.\n\t\t\t// NOTE: We can't simply rely on sort.Strings to have all the mountpoints sorted and\n\t\t\t// grouped. For example, the following strings are sorted in this exact order:\n\t\t\t// /dir/nested, /dir/nested-vol, /dir/nested.vol, /dir/nested/double, /dir/nested2\n\t\t\t// The issue is a bit worse for Windows paths, since the \\'s value is higher than /'s:\n\t\t\t// \\dir\\nested, \\dir\\nested-vol, \\dir\\nested.vol, \\dir\\nested2, \\dir\\nested\\double\n\t\t\t// Because of this, we should use a list of previously mounted mountpoints, rather than only one.\n\t\t\tprevNestedMPs := []string{}\n\t\t\t// examine each mount point to see if it's nested beneath this volume\n\t\t\t// (but skip any that are double-nested beneath this volume)\n\t\t\t// For example, if this volume is mounted as /dir and other volumes are mounted\n\t\t\t// as /dir/nested and /dir/nested/other, only create /dir/nested.\n\t\t\tfor _, mp := range allMountPoints {\n\t\t\t\tif !strings.HasPrefix(mp, myMPSlash) {\n\t\t\t\t\tcontinue // skip -- not nested beneath myMountPoint\n\t\t\t\t}\n\n\t\t\t\tisNested := false\n\t\t\t\tfor _, prevNestedMP := range prevNestedMPs {\n\t\t\t\t\tif strings.HasPrefix(mp, prevNestedMP) {\n\t\t\t\t\t\tisNested = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif isNested {\n\t\t\t\t\tcontinue // skip -- double nested beneath myMountPoint\n\t\t\t\t}\n\t\t\t\t// since this mount point is nested, remember it so that we can check that following ones aren't nested beneath this one\n\t\t\t\tprevNestedMPs = append(prevNestedMPs, mp+string(os.PathSeparator))\n\t\t\t\tretval = append(retval, mp[len(myMPSlash):])\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\tvar retErr error\n\tpodutil.VisitContainers(\u0026pod.Spec, podutil.AllFeatureEnabledContainers(), func(c *v1.Container, containerType podutil.ContainerType) bool {\n\t\tretErr = checkContainer(c)\n\t\treturn retErr == nil\n\t})\n\tif retErr != nil {\n\t\treturn nil, retErr\n\t}\n\n\treturn retval, nil\n}","line":{"from":30,"to":99}} {"id":100013006,"name":"MakeNestedMountpoints","signature":"func MakeNestedMountpoints(name, baseDir string, pod v1.Pod) error","file":"pkg/volume/util/nested_volumes.go","code":"// MakeNestedMountpoints creates mount points in baseDir for volumes mounted beneath name\nfunc MakeNestedMountpoints(name, baseDir string, pod v1.Pod) error {\n\tdirs, err := getNestedMountpoints(name, baseDir, pod)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, dir := range dirs {\n\t\terr := os.MkdirAll(filepath.Join(baseDir, dir), 0755)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to create nested volume mountpoints: %v\", err)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":101,"to":114}} {"id":100013007,"name":"NewNestedPendingOperations","signature":"func NewNestedPendingOperations(exponentialBackOffOnError bool) NestedPendingOperations","file":"pkg/volume/util/nestedpendingoperations/nestedpendingoperations.go","code":"// NewNestedPendingOperations returns a new instance of NestedPendingOperations.\nfunc NewNestedPendingOperations(exponentialBackOffOnError bool) NestedPendingOperations {\n\tg := \u0026nestedPendingOperations{\n\t\toperations: []operation{},\n\t\texponentialBackOffOnError: exponentialBackOffOnError,\n\t}\n\tg.cond = sync.NewCond(\u0026g.lock)\n\treturn g\n}","line":{"from":118,"to":126}} {"id":100013008,"name":"Run","signature":"func (grm *nestedPendingOperations) Run(","file":"pkg/volume/util/nestedpendingoperations/nestedpendingoperations.go","code":"func (grm *nestedPendingOperations) Run(\n\tvolumeName v1.UniqueVolumeName,\n\tpodName volumetypes.UniquePodName,\n\tnodeName types.NodeName,\n\tgeneratedOperations volumetypes.GeneratedOperations) error {\n\tgrm.lock.Lock()\n\tdefer grm.lock.Unlock()\n\n\topKey := operationKey{volumeName, podName, nodeName}\n\n\topExists, previousOpIndex := grm.isOperationExists(opKey)\n\tif opExists {\n\t\tpreviousOp := grm.operations[previousOpIndex]\n\t\t// Operation already exists\n\t\tif previousOp.operationPending {\n\t\t\t// Operation is pending\n\t\t\treturn NewAlreadyExistsError(opKey)\n\t\t}\n\n\t\tbackOffErr := previousOp.expBackoff.SafeToRetry(fmt.Sprintf(\"%+v\", opKey))\n\t\tif backOffErr != nil {\n\t\t\tif previousOp.operationName == generatedOperations.OperationName {\n\t\t\t\treturn backOffErr\n\t\t\t}\n\t\t\t// previous operation and new operation are different. reset op. name and exp. backoff\n\t\t\tgrm.operations[previousOpIndex].operationName = generatedOperations.OperationName\n\t\t\tgrm.operations[previousOpIndex].expBackoff = exponentialbackoff.ExponentialBackoff{}\n\t\t}\n\n\t\t// Update existing operation to mark as pending.\n\t\tgrm.operations[previousOpIndex].operationPending = true\n\t\tgrm.operations[previousOpIndex].key = opKey\n\t} else {\n\t\t// Create a new operation\n\t\tgrm.operations = append(grm.operations,\n\t\t\toperation{\n\t\t\t\tkey: opKey,\n\t\t\t\toperationPending: true,\n\t\t\t\toperationName: generatedOperations.OperationName,\n\t\t\t\texpBackoff: exponentialbackoff.ExponentialBackoff{},\n\t\t\t})\n\t}\n\n\tgo func() (eventErr, detailedErr error) {\n\t\t// Handle unhandled panics (very unlikely)\n\t\tdefer k8sRuntime.HandleCrash()\n\t\t// Handle completion of and error, if any, from operationFunc()\n\t\tdefer grm.operationComplete(opKey, \u0026detailedErr)\n\t\treturn generatedOperations.Run()\n\t}()\n\n\treturn nil\n}","line":{"from":142,"to":194}} {"id":100013009,"name":"IsOperationSafeToRetry","signature":"func (grm *nestedPendingOperations) IsOperationSafeToRetry(","file":"pkg/volume/util/nestedpendingoperations/nestedpendingoperations.go","code":"func (grm *nestedPendingOperations) IsOperationSafeToRetry(\n\tvolumeName v1.UniqueVolumeName,\n\tpodName volumetypes.UniquePodName,\n\tnodeName types.NodeName,\n\toperationName string) bool {\n\n\tgrm.lock.RLock()\n\tdefer grm.lock.RUnlock()\n\n\topKey := operationKey{volumeName, podName, nodeName}\n\texist, previousOpIndex := grm.isOperationExists(opKey)\n\tif !exist {\n\t\treturn true\n\t}\n\tpreviousOp := grm.operations[previousOpIndex]\n\tif previousOp.operationPending {\n\t\treturn false\n\t}\n\tbackOffErr := previousOp.expBackoff.SafeToRetry(fmt.Sprintf(\"%+v\", opKey))\n\tif backOffErr != nil {\n\t\tif previousOp.operationName == operationName {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}","line":{"from":195,"to":221}} {"id":100013010,"name":"IsOperationPending","signature":"func (grm *nestedPendingOperations) IsOperationPending(","file":"pkg/volume/util/nestedpendingoperations/nestedpendingoperations.go","code":"func (grm *nestedPendingOperations) IsOperationPending(\n\tvolumeName v1.UniqueVolumeName,\n\tpodName volumetypes.UniquePodName,\n\tnodeName types.NodeName) bool {\n\n\tgrm.lock.RLock()\n\tdefer grm.lock.RUnlock()\n\n\topKey := operationKey{volumeName, podName, nodeName}\n\texist, previousOpIndex := grm.isOperationExists(opKey)\n\tif exist \u0026\u0026 grm.operations[previousOpIndex].operationPending {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":223,"to":237}} {"id":100013011,"name":"isOperationExists","signature":"func (grm *nestedPendingOperations) isOperationExists(key operationKey) (bool, int)","file":"pkg/volume/util/nestedpendingoperations/nestedpendingoperations.go","code":"// This is an internal function and caller should acquire and release the lock\nfunc (grm *nestedPendingOperations) isOperationExists(key operationKey) (bool, int) {\n\n\t// If volumeName is empty, operation can be executed concurrently\n\tif key.volumeName == EmptyUniqueVolumeName {\n\t\treturn false, -1\n\t}\n\n\topIndex := -1\n\tfor previousOpIndex, previousOp := range grm.operations {\n\t\tvolumeNameMatch := previousOp.key.volumeName == key.volumeName\n\n\t\tpodNameMatch := previousOp.key.podName == EmptyUniquePodName ||\n\t\t\tkey.podName == EmptyUniquePodName ||\n\t\t\tpreviousOp.key.podName == key.podName\n\n\t\tpodNameExactMatch := previousOp.key.podName == key.podName\n\n\t\tnodeNameMatch := previousOp.key.nodeName == EmptyNodeName ||\n\t\t\tkey.nodeName == EmptyNodeName ||\n\t\t\tpreviousOp.key.nodeName == key.nodeName\n\n\t\tnodeNameExactMatch := previousOp.key.nodeName == key.nodeName\n\n\t\tif volumeNameMatch \u0026\u0026 podNameMatch \u0026\u0026 nodeNameMatch {\n\t\t\t// nonExactMatch pending first\n\t\t\tif previousOp.operationPending {\n\t\t\t\treturn true, previousOpIndex\n\t\t\t}\n\t\t\t// nonExactMatch with no pending, set opIndex to the first nonExactMatch\n\t\t\t// exactMatch can override opIndex to expected\n\t\t\tif opIndex == -1 || (podNameExactMatch \u0026\u0026 nodeNameExactMatch) {\n\t\t\t\topIndex = previousOpIndex\n\t\t\t}\n\t\t}\n\t}\n\treturn opIndex != -1, opIndex\n\n}","line":{"from":239,"to":277}} {"id":100013012,"name":"getOperation","signature":"func (grm *nestedPendingOperations) getOperation(key operationKey) (uint, error)","file":"pkg/volume/util/nestedpendingoperations/nestedpendingoperations.go","code":"func (grm *nestedPendingOperations) getOperation(key operationKey) (uint, error) {\n\t// Assumes lock has been acquired by caller.\n\n\tfor i, op := range grm.operations {\n\t\tif op.key.volumeName == key.volumeName \u0026\u0026\n\t\t\top.key.podName == key.podName \u0026\u0026\n\t\t\top.key.nodeName == key.nodeName {\n\t\t\treturn uint(i), nil\n\t\t}\n\t}\n\n\treturn 0, fmt.Errorf(\"operation %+v not found\", key)\n}","line":{"from":279,"to":291}} {"id":100013013,"name":"deleteOperation","signature":"func (grm *nestedPendingOperations) deleteOperation(key operationKey)","file":"pkg/volume/util/nestedpendingoperations/nestedpendingoperations.go","code":"func (grm *nestedPendingOperations) deleteOperation(key operationKey) {\n\t// Assumes lock has been acquired by caller.\n\n\topIndex := -1\n\tfor i, op := range grm.operations {\n\t\tif op.key.volumeName == key.volumeName \u0026\u0026\n\t\t\top.key.podName == key.podName \u0026\u0026\n\t\t\top.key.nodeName == key.nodeName {\n\t\t\topIndex = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif opIndex \u003c 0 {\n\t\treturn\n\t}\n\n\t// Delete index without preserving order\n\tgrm.operations[opIndex] = grm.operations[len(grm.operations)-1]\n\tgrm.operations = grm.operations[:len(grm.operations)-1]\n}","line":{"from":293,"to":313}} {"id":100013014,"name":"operationComplete","signature":"func (grm *nestedPendingOperations) operationComplete(key operationKey, err *error)","file":"pkg/volume/util/nestedpendingoperations/nestedpendingoperations.go","code":"func (grm *nestedPendingOperations) operationComplete(key operationKey, err *error) {\n\t// Defer operations are executed in Last-In is First-Out order. In this case\n\t// the lock is acquired first when operationCompletes begins, and is\n\t// released when the method finishes, after the lock is released cond is\n\t// signaled to wake waiting goroutine.\n\tdefer grm.cond.Signal()\n\tgrm.lock.Lock()\n\tdefer grm.lock.Unlock()\n\n\tif *err == nil || !grm.exponentialBackOffOnError {\n\t\t// Operation completed without error, or exponentialBackOffOnError disabled\n\t\tgrm.deleteOperation(key)\n\t\tif *err != nil {\n\t\t\t// Log error\n\t\t\tklog.Errorf(\"operation %+v failed with: %v\", key, *err)\n\t\t}\n\t\treturn\n\t}\n\n\t// Operation completed with error and exponentialBackOffOnError Enabled\n\texistingOpIndex, getOpErr := grm.getOperation(key)\n\tif getOpErr != nil {\n\t\t// Failed to find existing operation\n\t\tklog.Errorf(\"Operation %+v completed. error: %v. exponentialBackOffOnError is enabled, but failed to get operation to update.\",\n\t\t\tkey,\n\t\t\t*err)\n\t\treturn\n\t}\n\n\tgrm.operations[existingOpIndex].expBackoff.Update(err)\n\tgrm.operations[existingOpIndex].operationPending = false\n\n\t// Log error\n\tklog.Errorf(\"%v\", grm.operations[existingOpIndex].expBackoff.\n\t\tGenerateNoRetriesPermittedMsg(fmt.Sprintf(\"%+v\", key)))\n}","line":{"from":315,"to":350}} {"id":100013015,"name":"Wait","signature":"func (grm *nestedPendingOperations) Wait()","file":"pkg/volume/util/nestedpendingoperations/nestedpendingoperations.go","code":"func (grm *nestedPendingOperations) Wait() {\n\tgrm.lock.Lock()\n\tdefer grm.lock.Unlock()\n\n\tfor len(grm.operations) \u003e 0 {\n\t\tgrm.cond.Wait()\n\t}\n}","line":{"from":352,"to":359}} {"id":100013016,"name":"NewAlreadyExistsError","signature":"func NewAlreadyExistsError(key operationKey) error","file":"pkg/volume/util/nestedpendingoperations/nestedpendingoperations.go","code":"// NewAlreadyExistsError returns a new instance of AlreadyExists error.\nfunc NewAlreadyExistsError(key operationKey) error {\n\treturn alreadyExistsError{key}\n}","line":{"from":367,"to":370}} {"id":100013017,"name":"IsAlreadyExists","signature":"func IsAlreadyExists(err error) bool","file":"pkg/volume/util/nestedpendingoperations/nestedpendingoperations.go","code":"// IsAlreadyExists returns true if an error returned from\n// NestedPendingOperations indicates a new operation can not be started because\n// an operation with the same operation name is already executing.\nfunc IsAlreadyExists(err error) bool {\n\tswitch err.(type) {\n\tcase alreadyExistsError:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":372,"to":382}} {"id":100013018,"name":"Error","signature":"func (err alreadyExistsError) Error() string","file":"pkg/volume/util/nestedpendingoperations/nestedpendingoperations.go","code":"func (err alreadyExistsError) Error() string {\n\treturn fmt.Sprintf(\n\t\t\"Failed to create operation with name %+v. An operation with that name is already executing.\",\n\t\terr.operationKey)\n}","line":{"from":393,"to":397}} {"id":100013019,"name":"newNodeExpander","signature":"func newNodeExpander(resizeOp nodeResizeOperationOpts, client clientset.Interface, recorder record.EventRecorder) *NodeExpander","file":"pkg/volume/util/operationexecutor/node_expander.go","code":"func newNodeExpander(resizeOp nodeResizeOperationOpts, client clientset.Interface, recorder record.EventRecorder) *NodeExpander {\n\treturn \u0026NodeExpander{\n\t\tkubeClient: client,\n\t\tnodeResizeOperationOpts: resizeOp,\n\t\trecorder: recorder,\n\t}\n}","line":{"from":48,"to":54}} {"id":100013020,"name":"runPreCheck","signature":"func (ne *NodeExpander) runPreCheck() bool","file":"pkg/volume/util/operationexecutor/node_expander.go","code":"// runPreCheck performs some sanity checks before expansion can be performed on the PVC.\nfunc (ne *NodeExpander) runPreCheck() bool {\n\tne.pvcStatusCap = ne.pvc.Status.Capacity[v1.ResourceStorage]\n\tne.pvCap = ne.pv.Spec.Capacity[v1.ResourceStorage]\n\n\tne.resizeStatus = ne.pvc.Status.ResizeStatus\n\n\t// PVC is already expanded but we are still trying to expand the volume because\n\t// last recorded size in ASOW is older. This can happen for RWX volume types.\n\tif ne.pvcStatusCap.Cmp(ne.pluginResizeOpts.NewSize) \u003e= 0 \u0026\u0026 (ne.resizeStatus == nil || *ne.resizeStatus == v1.PersistentVolumeClaimNoExpansionInProgress) {\n\t\tne.pvcAlreadyUpdated = true\n\t}\n\n\t// if resizestatus is nil or NodeExpansionInProgress or NodeExpansionPending then we\n\t// should allow volume expansion on the node to proceed. We are making an exception for\n\t// resizeStatus being nil because it will support use cases where\n\t// resizeStatus may not be set (old control-plane expansion controller etc).\n\tif ne.resizeStatus == nil ||\n\t\tne.pvcAlreadyUpdated ||\n\t\t*ne.resizeStatus == v1.PersistentVolumeClaimNodeExpansionPending ||\n\t\t*ne.resizeStatus == v1.PersistentVolumeClaimNodeExpansionInProgress {\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":70,"to":95}} {"id":100013021,"name":"expandOnPlugin","signature":"func (ne *NodeExpander) expandOnPlugin() (bool, error, testResponseData)","file":"pkg/volume/util/operationexecutor/node_expander.go","code":"func (ne *NodeExpander) expandOnPlugin() (bool, error, testResponseData) {\n\tallowExpansion := ne.runPreCheck()\n\tif !allowExpansion {\n\t\treturn false, nil, testResponseData{false, true}\n\t}\n\n\tvar err error\n\tnodeName := ne.vmt.Pod.Spec.NodeName\n\n\tif !ne.pvcAlreadyUpdated {\n\t\tne.pvc, err = util.MarkNodeExpansionInProgress(ne.pvc, ne.kubeClient)\n\n\t\tif err != nil {\n\t\t\tmsg := ne.vmt.GenerateErrorDetailed(\"MountVolume.NodeExpandVolume failed to mark node expansion in progress: %v\", err)\n\t\t\tklog.Errorf(msg.Error())\n\t\t\treturn false, err, testResponseData{}\n\t\t}\n\t}\n\t_, resizeErr := ne.volumePlugin.NodeExpand(ne.pluginResizeOpts)\n\tif resizeErr != nil {\n\t\tif volumetypes.IsOperationFinishedError(resizeErr) {\n\t\t\tvar markFailedError error\n\t\t\tne.pvc, markFailedError = util.MarkNodeExpansionFailed(ne.pvc, ne.kubeClient)\n\t\t\tif markFailedError != nil {\n\t\t\t\tklog.Errorf(ne.vmt.GenerateErrorDetailed(\"MountMount.NodeExpandVolume failed to mark node expansion as failed: %v\", err).Error())\n\t\t\t}\n\t\t}\n\n\t\t// if driver returned FailedPrecondition error that means\n\t\t// volume expansion should not be retried on this node but\n\t\t// expansion operation should not block mounting\n\t\tif volumetypes.IsFailedPreconditionError(resizeErr) {\n\t\t\tne.actualStateOfWorld.MarkForInUseExpansionError(ne.vmt.VolumeName)\n\t\t\tklog.Errorf(ne.vmt.GenerateErrorDetailed(\"MountVolume.NodeExapndVolume failed with %v\", resizeErr).Error())\n\t\t\treturn false, nil, testResponseData{assumeResizeFinished: true, resizeCalledOnPlugin: true}\n\t\t}\n\t\treturn false, resizeErr, testResponseData{assumeResizeFinished: true, resizeCalledOnPlugin: true}\n\t}\n\tsimpleMsg, detailedMsg := ne.vmt.GenerateMsg(\"MountVolume.NodeExpandVolume succeeded\", nodeName)\n\tne.recorder.Eventf(ne.vmt.Pod, v1.EventTypeNormal, kevents.FileSystemResizeSuccess, simpleMsg)\n\tne.recorder.Eventf(ne.pvc, v1.EventTypeNormal, kevents.FileSystemResizeSuccess, simpleMsg)\n\tklog.InfoS(detailedMsg, \"pod\", klog.KObj(ne.vmt.Pod))\n\n\t// no need to update PVC object if we already updated it\n\tif ne.pvcAlreadyUpdated {\n\t\treturn true, nil, testResponseData{true, true}\n\t}\n\n\t// File system resize succeeded, now update the PVC's Capacity to match the PV's\n\tne.pvc, err = util.MarkFSResizeFinished(ne.pvc, ne.pluginResizeOpts.NewSize, ne.kubeClient)\n\tif err != nil {\n\t\treturn true, fmt.Errorf(\"mountVolume.NodeExpandVolume update pvc status failed: %v\", err), testResponseData{true, true}\n\t}\n\treturn true, nil, testResponseData{true, true}\n}","line":{"from":97,"to":151}} {"id":100013022,"name":"NewOperationExecutor","signature":"func NewOperationExecutor(","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"// NewOperationExecutor returns a new instance of OperationExecutor.\nfunc NewOperationExecutor(\n\toperationGenerator OperationGenerator) OperationExecutor {\n\n\treturn \u0026operationExecutor{\n\t\tpendingOperations: nestedpendingoperations.NewNestedPendingOperations(\n\t\t\ttrue /* exponentialBackOffOnError */),\n\t\toperationGenerator: operationGenerator,\n\t}\n}","line":{"from":158,"to":167}} {"id":100013023,"name":"errSuffix","signature":"func errSuffix(err error) string","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"// Generates an error string with the format \": \u003cerr\u003e\" if err exists\nfunc errSuffix(err error) string {\n\terrStr := \"\"\n\tif err != nil {\n\t\terrStr = fmt.Sprintf(\": %v\", err)\n\t}\n\treturn errStr\n}","line":{"from":294,"to":301}} {"id":100013024,"name":"generateVolumeMsgDetailed","signature":"func generateVolumeMsgDetailed(prefixMsg, suffixMsg, volumeName, details string) (detailedMsg string)","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"// Generate a detailed error msg for logs\nfunc generateVolumeMsgDetailed(prefixMsg, suffixMsg, volumeName, details string) (detailedMsg string) {\n\treturn fmt.Sprintf(\"%v for volume %q %v %v\", prefixMsg, volumeName, details, suffixMsg)\n}","line":{"from":303,"to":306}} {"id":100013025,"name":"generateVolumeMsg","signature":"func generateVolumeMsg(prefixMsg, suffixMsg, volumeName, details string) (simpleMsg, detailedMsg string)","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"// Generate a simplified error msg for events and a detailed error msg for logs\nfunc generateVolumeMsg(prefixMsg, suffixMsg, volumeName, details string) (simpleMsg, detailedMsg string) {\n\tsimpleMsg = fmt.Sprintf(\"%v for volume %q %v\", prefixMsg, volumeName, suffixMsg)\n\treturn simpleMsg, generateVolumeMsgDetailed(prefixMsg, suffixMsg, volumeName, details)\n}","line":{"from":308,"to":312}} {"id":100013026,"name":"GenerateMsgDetailed","signature":"func (volume *VolumeToAttach) GenerateMsgDetailed(prefixMsg, suffixMsg string) (detailedMsg string)","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"// GenerateMsgDetailed returns detailed msgs for volumes to attach\nfunc (volume *VolumeToAttach) GenerateMsgDetailed(prefixMsg, suffixMsg string) (detailedMsg string) {\n\tdetailedStr := fmt.Sprintf(\"(UniqueName: %q) from node %q\", volume.VolumeName, volume.NodeName)\n\tvolumeSpecName := \"nil\"\n\tif volume.VolumeSpec != nil {\n\t\tvolumeSpecName = volume.VolumeSpec.Name()\n\t}\n\treturn generateVolumeMsgDetailed(prefixMsg, suffixMsg, volumeSpecName, detailedStr)\n}","line":{"from":339,"to":347}} {"id":100013027,"name":"GenerateMsg","signature":"func (volume *VolumeToAttach) GenerateMsg(prefixMsg, suffixMsg string) (simpleMsg, detailedMsg string)","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"// GenerateMsg returns simple and detailed msgs for volumes to attach\nfunc (volume *VolumeToAttach) GenerateMsg(prefixMsg, suffixMsg string) (simpleMsg, detailedMsg string) {\n\tdetailedStr := fmt.Sprintf(\"(UniqueName: %q) from node %q\", volume.VolumeName, volume.NodeName)\n\tvolumeSpecName := \"nil\"\n\tif volume.VolumeSpec != nil {\n\t\tvolumeSpecName = volume.VolumeSpec.Name()\n\t}\n\treturn generateVolumeMsg(prefixMsg, suffixMsg, volumeSpecName, detailedStr)\n}","line":{"from":349,"to":357}} {"id":100013028,"name":"GenerateErrorDetailed","signature":"func (volume *VolumeToAttach) GenerateErrorDetailed(prefixMsg string, err error) (detailedErr error)","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"// GenerateErrorDetailed returns detailed errors for volumes to attach\nfunc (volume *VolumeToAttach) GenerateErrorDetailed(prefixMsg string, err error) (detailedErr error) {\n\treturn fmt.Errorf(volume.GenerateMsgDetailed(prefixMsg, errSuffix(err)))\n}","line":{"from":359,"to":362}} {"id":100013029,"name":"GenerateError","signature":"func (volume *VolumeToAttach) GenerateError(prefixMsg string, err error) (simpleErr, detailedErr error)","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"// GenerateError returns simple and detailed errors for volumes to attach\nfunc (volume *VolumeToAttach) GenerateError(prefixMsg string, err error) (simpleErr, detailedErr error) {\n\tsimpleMsg, detailedMsg := volume.GenerateMsg(prefixMsg, errSuffix(err))\n\treturn fmt.Errorf(simpleMsg), fmt.Errorf(detailedMsg)\n}","line":{"from":364,"to":368}} {"id":100013030,"name":"String","signature":"func (volume *VolumeToAttach) String() string","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"// String combines key fields of the volume for logging in text format.\nfunc (volume *VolumeToAttach) String() string {\n\tvolumeSpecName := \"nil\"\n\tif volume.VolumeSpec != nil {\n\t\tvolumeSpecName = volume.VolumeSpec.Name()\n\t}\n\treturn fmt.Sprintf(\"%s (UniqueName: %s) from node %s\", volumeSpecName, volume.VolumeName, volume.NodeName)\n}","line":{"from":370,"to":377}} {"id":100013031,"name":"MarshalLog","signature":"func (volume *VolumeToAttach) MarshalLog() interface{}","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"// MarshalLog combines key fields of the volume for logging in a structured format.\nfunc (volume *VolumeToAttach) MarshalLog() interface{} {\n\tvolumeSpecName := \"nil\"\n\tif volume.VolumeSpec != nil {\n\t\tvolumeSpecName = volume.VolumeSpec.Name()\n\t}\n\treturn struct {\n\t\tVolumeName, UniqueName, NodeName string\n\t}{\n\t\tVolumeName: volumeSpecName,\n\t\tUniqueName: string(volume.VolumeName),\n\t\tNodeName: string(volume.NodeName),\n\t}\n}","line":{"from":379,"to":392}} {"id":100013032,"name":"Error","signature":"func (err *MountPreConditionFailed) Error() string","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"func (err *MountPreConditionFailed) Error() string {\n\treturn err.msg\n}","line":{"from":488,"to":490}} {"id":100013033,"name":"NewMountPreConditionFailedError","signature":"func NewMountPreConditionFailedError(msg string) *MountPreConditionFailed","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"func NewMountPreConditionFailedError(msg string) *MountPreConditionFailed {\n\treturn \u0026MountPreConditionFailed{msg: msg}\n}","line":{"from":492,"to":494}} {"id":100013034,"name":"IsMountFailedPreconditionError","signature":"func IsMountFailedPreconditionError(err error) bool","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"func IsMountFailedPreconditionError(err error) bool {\n\tvar failedPreconditionError *MountPreConditionFailed\n\treturn errors.As(err, \u0026failedPreconditionError)\n}","line":{"from":496,"to":499}} {"id":100013035,"name":"GenerateMsgDetailed","signature":"func (volume *VolumeToMount) GenerateMsgDetailed(prefixMsg, suffixMsg string) (detailedMsg string)","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"// GenerateMsgDetailed returns detailed msgs for volumes to mount\nfunc (volume *VolumeToMount) GenerateMsgDetailed(prefixMsg, suffixMsg string) (detailedMsg string) {\n\tdetailedStr := fmt.Sprintf(\"(UniqueName: %q) pod %q (UID: %q)\", volume.VolumeName, volume.Pod.Name, volume.Pod.UID)\n\tvolumeSpecName := \"nil\"\n\tif volume.VolumeSpec != nil {\n\t\tvolumeSpecName = volume.VolumeSpec.Name()\n\t}\n\treturn generateVolumeMsgDetailed(prefixMsg, suffixMsg, volumeSpecName, detailedStr)\n}","line":{"from":501,"to":509}} {"id":100013036,"name":"GenerateMsg","signature":"func (volume *VolumeToMount) GenerateMsg(prefixMsg, suffixMsg string) (simpleMsg, detailedMsg string)","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"// GenerateMsg returns simple and detailed msgs for volumes to mount\nfunc (volume *VolumeToMount) GenerateMsg(prefixMsg, suffixMsg string) (simpleMsg, detailedMsg string) {\n\tdetailedStr := fmt.Sprintf(\"(UniqueName: %q) pod %q (UID: %q)\", volume.VolumeName, volume.Pod.Name, volume.Pod.UID)\n\tvolumeSpecName := \"nil\"\n\tif volume.VolumeSpec != nil {\n\t\tvolumeSpecName = volume.VolumeSpec.Name()\n\t}\n\treturn generateVolumeMsg(prefixMsg, suffixMsg, volumeSpecName, detailedStr)\n}","line":{"from":511,"to":519}} {"id":100013037,"name":"GenerateErrorDetailed","signature":"func (volume *VolumeToMount) GenerateErrorDetailed(prefixMsg string, err error) (detailedErr error)","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"// GenerateErrorDetailed returns detailed errors for volumes to mount\nfunc (volume *VolumeToMount) GenerateErrorDetailed(prefixMsg string, err error) (detailedErr error) {\n\treturn fmt.Errorf(volume.GenerateMsgDetailed(prefixMsg, errSuffix(err)))\n}","line":{"from":521,"to":524}} {"id":100013038,"name":"GenerateError","signature":"func (volume *VolumeToMount) GenerateError(prefixMsg string, err error) (simpleErr, detailedErr error)","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"// GenerateError returns simple and detailed errors for volumes to mount\nfunc (volume *VolumeToMount) GenerateError(prefixMsg string, err error) (simpleErr, detailedErr error) {\n\tsimpleMsg, detailedMsg := volume.GenerateMsg(prefixMsg, errSuffix(err))\n\treturn fmt.Errorf(simpleMsg), fmt.Errorf(detailedMsg)\n}","line":{"from":526,"to":530}} {"id":100013039,"name":"GenerateMsgDetailed","signature":"func (volume *AttachedVolume) GenerateMsgDetailed(prefixMsg, suffixMsg string) (detailedMsg string)","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"// GenerateMsgDetailed returns detailed msgs for attached volumes\nfunc (volume *AttachedVolume) GenerateMsgDetailed(prefixMsg, suffixMsg string) (detailedMsg string) {\n\tdetailedStr := fmt.Sprintf(\"(UniqueName: %q) on node %q\", volume.VolumeName, volume.NodeName)\n\tvolumeSpecName := \"nil\"\n\tif volume.VolumeSpec != nil {\n\t\tvolumeSpecName = volume.VolumeSpec.Name()\n\t}\n\treturn generateVolumeMsgDetailed(prefixMsg, suffixMsg, volumeSpecName, detailedStr)\n}","line":{"from":563,"to":571}} {"id":100013040,"name":"GenerateMsg","signature":"func (volume *AttachedVolume) GenerateMsg(prefixMsg, suffixMsg string) (simpleMsg, detailedMsg string)","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"// GenerateMsg returns simple and detailed msgs for attached volumes\nfunc (volume *AttachedVolume) GenerateMsg(prefixMsg, suffixMsg string) (simpleMsg, detailedMsg string) {\n\tdetailedStr := fmt.Sprintf(\"(UniqueName: %q) on node %q\", volume.VolumeName, volume.NodeName)\n\tvolumeSpecName := \"nil\"\n\tif volume.VolumeSpec != nil {\n\t\tvolumeSpecName = volume.VolumeSpec.Name()\n\t}\n\treturn generateVolumeMsg(prefixMsg, suffixMsg, volumeSpecName, detailedStr)\n}","line":{"from":573,"to":581}} {"id":100013041,"name":"GenerateErrorDetailed","signature":"func (volume *AttachedVolume) GenerateErrorDetailed(prefixMsg string, err error) (detailedErr error)","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"// GenerateErrorDetailed returns detailed errors for attached volumes\nfunc (volume *AttachedVolume) GenerateErrorDetailed(prefixMsg string, err error) (detailedErr error) {\n\treturn fmt.Errorf(volume.GenerateMsgDetailed(prefixMsg, errSuffix(err)))\n}","line":{"from":583,"to":586}} {"id":100013042,"name":"GenerateError","signature":"func (volume *AttachedVolume) GenerateError(prefixMsg string, err error) (simpleErr, detailedErr error)","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"// GenerateError returns simple and detailed errors for attached volumes\nfunc (volume *AttachedVolume) GenerateError(prefixMsg string, err error) (simpleErr, detailedErr error) {\n\tsimpleMsg, detailedMsg := volume.GenerateMsg(prefixMsg, errSuffix(err))\n\treturn fmt.Errorf(simpleMsg), fmt.Errorf(detailedMsg)\n}","line":{"from":588,"to":592}} {"id":100013043,"name":"String","signature":"func (volume *AttachedVolume) String() string","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"// String combines key fields of the volume for logging in text format.\nfunc (volume *AttachedVolume) String() string {\n\tvolumeSpecName := \"nil\"\n\tif volume.VolumeSpec != nil {\n\t\tvolumeSpecName = volume.VolumeSpec.Name()\n\t}\n\treturn fmt.Sprintf(\"%s (UniqueName: %s) from node %s\", volumeSpecName, volume.VolumeName, volume.NodeName)\n}","line":{"from":594,"to":601}} {"id":100013044,"name":"MarshalLog","signature":"func (volume *AttachedVolume) MarshalLog() interface{}","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"// MarshalLog combines key fields of the volume for logging in a structured format.\nfunc (volume *AttachedVolume) MarshalLog() interface{} {\n\tvolumeSpecName := \"nil\"\n\tif volume.VolumeSpec != nil {\n\t\tvolumeSpecName = volume.VolumeSpec.Name()\n\t}\n\treturn struct {\n\t\tVolumeName, UniqueName, NodeName string\n\t}{\n\t\tVolumeName: volumeSpecName,\n\t\tUniqueName: string(volume.VolumeName),\n\t\tNodeName: string(volume.NodeName),\n\t}\n}","line":{"from":603,"to":616}} {"id":100013045,"name":"GenerateMsgDetailed","signature":"func (volume *MountedVolume) GenerateMsgDetailed(prefixMsg, suffixMsg string) (detailedMsg string)","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"// GenerateMsgDetailed returns detailed msgs for mounted volumes\nfunc (volume *MountedVolume) GenerateMsgDetailed(prefixMsg, suffixMsg string) (detailedMsg string) {\n\tdetailedStr := fmt.Sprintf(\"(UniqueName: %q) pod %q (UID: %q)\", volume.VolumeName, volume.PodName, volume.PodUID)\n\treturn generateVolumeMsgDetailed(prefixMsg, suffixMsg, volume.OuterVolumeSpecName, detailedStr)\n}","line":{"from":743,"to":747}} {"id":100013046,"name":"GenerateMsg","signature":"func (volume *MountedVolume) GenerateMsg(prefixMsg, suffixMsg string) (simpleMsg, detailedMsg string)","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"// GenerateMsg returns simple and detailed msgs for mounted volumes\nfunc (volume *MountedVolume) GenerateMsg(prefixMsg, suffixMsg string) (simpleMsg, detailedMsg string) {\n\tdetailedStr := fmt.Sprintf(\"(UniqueName: %q) pod %q (UID: %q)\", volume.VolumeName, volume.PodName, volume.PodUID)\n\treturn generateVolumeMsg(prefixMsg, suffixMsg, volume.OuterVolumeSpecName, detailedStr)\n}","line":{"from":749,"to":753}} {"id":100013047,"name":"GenerateErrorDetailed","signature":"func (volume *MountedVolume) GenerateErrorDetailed(prefixMsg string, err error) (detailedErr error)","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"// GenerateErrorDetailed returns simple and detailed errors for mounted volumes\nfunc (volume *MountedVolume) GenerateErrorDetailed(prefixMsg string, err error) (detailedErr error) {\n\treturn fmt.Errorf(volume.GenerateMsgDetailed(prefixMsg, errSuffix(err)))\n}","line":{"from":755,"to":758}} {"id":100013048,"name":"GenerateError","signature":"func (volume *MountedVolume) GenerateError(prefixMsg string, err error) (simpleErr, detailedErr error)","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"// GenerateError returns simple and detailed errors for mounted volumes\nfunc (volume *MountedVolume) GenerateError(prefixMsg string, err error) (simpleErr, detailedErr error) {\n\tsimpleMsg, detailedMsg := volume.GenerateMsg(prefixMsg, errSuffix(err))\n\treturn fmt.Errorf(simpleMsg), fmt.Errorf(detailedMsg)\n}","line":{"from":760,"to":764}} {"id":100013049,"name":"IsOperationPending","signature":"func (oe *operationExecutor) IsOperationPending(","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"func (oe *operationExecutor) IsOperationPending(\n\tvolumeName v1.UniqueVolumeName,\n\tpodName volumetypes.UniquePodName,\n\tnodeName types.NodeName) bool {\n\treturn oe.pendingOperations.IsOperationPending(volumeName, podName, nodeName)\n}","line":{"from":776,"to":781}} {"id":100013050,"name":"IsOperationSafeToRetry","signature":"func (oe *operationExecutor) IsOperationSafeToRetry(","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"func (oe *operationExecutor) IsOperationSafeToRetry(\n\tvolumeName v1.UniqueVolumeName,\n\tpodName volumetypes.UniquePodName,\n\tnodeName types.NodeName,\n\toperationName string) bool {\n\treturn oe.pendingOperations.IsOperationSafeToRetry(volumeName, podName, nodeName, operationName)\n}","line":{"from":783,"to":789}} {"id":100013051,"name":"AttachVolume","signature":"func (oe *operationExecutor) AttachVolume(","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"func (oe *operationExecutor) AttachVolume(\n\tlogger klog.Logger,\n\tvolumeToAttach VolumeToAttach,\n\tactualStateOfWorld ActualStateOfWorldAttacherUpdater) error {\n\tgeneratedOperations :=\n\t\toe.operationGenerator.GenerateAttachVolumeFunc(logger, volumeToAttach, actualStateOfWorld)\n\n\tif util.IsMultiAttachAllowed(volumeToAttach.VolumeSpec) {\n\t\treturn oe.pendingOperations.Run(\n\t\t\tvolumeToAttach.VolumeName, \"\" /* podName */, volumeToAttach.NodeName, generatedOperations)\n\t}\n\n\treturn oe.pendingOperations.Run(\n\t\tvolumeToAttach.VolumeName, \"\" /* podName */, \"\" /* nodeName */, generatedOperations)\n}","line":{"from":791,"to":805}} {"id":100013052,"name":"DetachVolume","signature":"func (oe *operationExecutor) DetachVolume(","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"func (oe *operationExecutor) DetachVolume(\n\tlogger klog.Logger,\n\tvolumeToDetach AttachedVolume,\n\tverifySafeToDetach bool,\n\tactualStateOfWorld ActualStateOfWorldAttacherUpdater) error {\n\tgeneratedOperations, err :=\n\t\toe.operationGenerator.GenerateDetachVolumeFunc(logger, volumeToDetach, verifySafeToDetach, actualStateOfWorld)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif util.IsMultiAttachAllowed(volumeToDetach.VolumeSpec) {\n\t\treturn oe.pendingOperations.Run(\n\t\t\tvolumeToDetach.VolumeName, \"\" /* podName */, volumeToDetach.NodeName, generatedOperations)\n\t}\n\treturn oe.pendingOperations.Run(\n\t\tvolumeToDetach.VolumeName, \"\" /* podName */, \"\" /* nodeName */, generatedOperations)\n\n}","line":{"from":807,"to":825}} {"id":100013053,"name":"VerifyVolumesAreAttached","signature":"func (oe *operationExecutor) VerifyVolumesAreAttached(","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"func (oe *operationExecutor) VerifyVolumesAreAttached(\n\tattachedVolumes map[types.NodeName][]AttachedVolume,\n\tactualStateOfWorld ActualStateOfWorldAttacherUpdater) {\n\n\t// A map of plugin names and nodes on which they exist with volumes they manage\n\tbulkVerifyPluginsByNode := make(map[string]map[types.NodeName][]*volume.Spec)\n\tvolumeSpecMapByPlugin := make(map[string]map[*volume.Spec]v1.UniqueVolumeName)\n\n\tfor node, nodeAttachedVolumes := range attachedVolumes {\n\t\tneedIndividualVerifyVolumes := []AttachedVolume{}\n\t\tfor _, volumeAttached := range nodeAttachedVolumes {\n\t\t\tif volumeAttached.VolumeSpec == nil {\n\t\t\t\tklog.Errorf(\"VerifyVolumesAreAttached: nil spec for volume %s\", volumeAttached.VolumeName)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvolumePlugin, err :=\n\t\t\t\toe.operationGenerator.GetVolumePluginMgr().FindPluginBySpec(volumeAttached.VolumeSpec)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\n\t\t\t\t\t\"VolumesAreAttached.FindPluginBySpec failed for volume %q (spec.Name: %q) on node %q with error: %v\",\n\t\t\t\t\tvolumeAttached.VolumeName,\n\t\t\t\t\tvolumeAttached.VolumeSpec.Name(),\n\t\t\t\t\tvolumeAttached.NodeName,\n\t\t\t\t\terr)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif volumePlugin == nil {\n\t\t\t\t// should never happen since FindPluginBySpec always returns error if volumePlugin = nil\n\t\t\t\tklog.Errorf(\n\t\t\t\t\t\"Failed to find volume plugin for volume %q (spec.Name: %q) on node %q\",\n\t\t\t\t\tvolumeAttached.VolumeName,\n\t\t\t\t\tvolumeAttached.VolumeSpec.Name(),\n\t\t\t\t\tvolumeAttached.NodeName)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tpluginName := volumePlugin.GetPluginName()\n\n\t\t\tif volumePlugin.SupportsBulkVolumeVerification() {\n\t\t\t\tpluginNodes, pluginNodesExist := bulkVerifyPluginsByNode[pluginName]\n\n\t\t\t\tif !pluginNodesExist {\n\t\t\t\t\tpluginNodes = make(map[types.NodeName][]*volume.Spec)\n\t\t\t\t}\n\n\t\t\t\tvolumeSpecList, nodeExists := pluginNodes[node]\n\t\t\t\tif !nodeExists {\n\t\t\t\t\tvolumeSpecList = []*volume.Spec{}\n\t\t\t\t}\n\t\t\t\tvolumeSpecList = append(volumeSpecList, volumeAttached.VolumeSpec)\n\t\t\t\tpluginNodes[node] = volumeSpecList\n\n\t\t\t\tbulkVerifyPluginsByNode[pluginName] = pluginNodes\n\t\t\t\tvolumeSpecMap, mapExists := volumeSpecMapByPlugin[pluginName]\n\n\t\t\t\tif !mapExists {\n\t\t\t\t\tvolumeSpecMap = make(map[*volume.Spec]v1.UniqueVolumeName)\n\t\t\t\t}\n\t\t\t\tvolumeSpecMap[volumeAttached.VolumeSpec] = volumeAttached.VolumeName\n\t\t\t\tvolumeSpecMapByPlugin[pluginName] = volumeSpecMap\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// If node doesn't support Bulk volume polling it is best to poll individually\n\t\t\tneedIndividualVerifyVolumes = append(needIndividualVerifyVolumes, volumeAttached)\n\t\t}\n\t\tnodeError := oe.VerifyVolumesAreAttachedPerNode(needIndividualVerifyVolumes, node, actualStateOfWorld)\n\t\tif nodeError != nil {\n\t\t\tklog.Errorf(\"VerifyVolumesAreAttached failed for volumes %v, node %q with error %v\", needIndividualVerifyVolumes, node, nodeError)\n\t\t}\n\t}\n\n\tfor pluginName, pluginNodeVolumes := range bulkVerifyPluginsByNode {\n\t\tgeneratedOperations, err := oe.operationGenerator.GenerateBulkVolumeVerifyFunc(\n\t\t\tpluginNodeVolumes,\n\t\t\tpluginName,\n\t\t\tvolumeSpecMapByPlugin[pluginName],\n\t\t\tactualStateOfWorld)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"BulkVerifyVolumes.GenerateBulkVolumeVerifyFunc error bulk verifying volumes for plugin %q with %v\", pluginName, err)\n\t\t}\n\n\t\t// Ugly hack to ensure - we don't do parallel bulk polling of same volume plugin\n\t\tuniquePluginName := v1.UniqueVolumeName(pluginName)\n\t\terr = oe.pendingOperations.Run(uniquePluginName, \"\" /* Pod Name */, \"\" /* nodeName */, generatedOperations)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"BulkVerifyVolumes.Run Error bulk volume verification for plugin %q with %v\", pluginName, err)\n\t\t}\n\t}\n}","line":{"from":827,"to":916}} {"id":100013054,"name":"VerifyVolumesAreAttachedPerNode","signature":"func (oe *operationExecutor) VerifyVolumesAreAttachedPerNode(","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"func (oe *operationExecutor) VerifyVolumesAreAttachedPerNode(\n\tattachedVolumes []AttachedVolume,\n\tnodeName types.NodeName,\n\tactualStateOfWorld ActualStateOfWorldAttacherUpdater) error {\n\tgeneratedOperations, err :=\n\t\toe.operationGenerator.GenerateVolumesAreAttachedFunc(attachedVolumes, nodeName, actualStateOfWorld)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Give an empty UniqueVolumeName so that this operation could be executed concurrently.\n\treturn oe.pendingOperations.Run(\"\" /* volumeName */, \"\" /* podName */, \"\" /* nodeName */, generatedOperations)\n}","line":{"from":918,"to":930}} {"id":100013055,"name":"MountVolume","signature":"func (oe *operationExecutor) MountVolume(","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"func (oe *operationExecutor) MountVolume(\n\twaitForAttachTimeout time.Duration,\n\tvolumeToMount VolumeToMount,\n\tactualStateOfWorld ActualStateOfWorldMounterUpdater,\n\tisRemount bool) error {\n\tfsVolume, err := util.CheckVolumeModeFilesystem(volumeToMount.VolumeSpec)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar generatedOperations volumetypes.GeneratedOperations\n\tif fsVolume {\n\t\t// Filesystem volume case\n\t\t// Mount/remount a volume when a volume is attached\n\t\tgeneratedOperations = oe.operationGenerator.GenerateMountVolumeFunc(\n\t\t\twaitForAttachTimeout, volumeToMount, actualStateOfWorld, isRemount)\n\n\t} else {\n\t\t// Block volume case\n\t\t// Creates a map to device if a volume is attached\n\t\tgeneratedOperations, err = oe.operationGenerator.GenerateMapVolumeFunc(\n\t\t\twaitForAttachTimeout, volumeToMount, actualStateOfWorld)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Avoid executing mount/map from multiple pods referencing the\n\t// same volume in parallel\n\tpodName := nestedpendingoperations.EmptyUniquePodName\n\n\t// TODO: remove this -- not necessary\n\tif !volumeToMount.PluginIsAttachable \u0026\u0026 !volumeToMount.PluginIsDeviceMountable {\n\t\t// volume plugins which are Non-attachable and Non-deviceMountable can execute mount for multiple pods\n\t\t// referencing the same volume in parallel\n\t\tpodName = util.GetUniquePodName(volumeToMount.Pod)\n\t}\n\n\t// TODO mount_device\n\treturn oe.pendingOperations.Run(\n\t\tvolumeToMount.VolumeName, podName, \"\" /* nodeName */, generatedOperations)\n}","line":{"from":932,"to":971}} {"id":100013056,"name":"UnmountVolume","signature":"func (oe *operationExecutor) UnmountVolume(","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"func (oe *operationExecutor) UnmountVolume(\n\tvolumeToUnmount MountedVolume,\n\tactualStateOfWorld ActualStateOfWorldMounterUpdater,\n\tpodsDir string) error {\n\tfsVolume, err := util.CheckVolumeModeFilesystem(volumeToUnmount.VolumeSpec)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar generatedOperations volumetypes.GeneratedOperations\n\tif fsVolume {\n\t\t// Filesystem volume case\n\t\t// Unmount a volume if a volume is mounted\n\t\tgeneratedOperations, err = oe.operationGenerator.GenerateUnmountVolumeFunc(\n\t\t\tvolumeToUnmount, actualStateOfWorld, podsDir)\n\t} else {\n\t\t// Block volume case\n\t\t// Unmap a volume if a volume is mapped\n\t\tgeneratedOperations, err = oe.operationGenerator.GenerateUnmapVolumeFunc(\n\t\t\tvolumeToUnmount, actualStateOfWorld)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\t// All volume plugins can execute unmount/unmap for multiple pods referencing the\n\t// same volume in parallel\n\tpodName := volumetypes.UniquePodName(volumeToUnmount.PodUID)\n\n\treturn oe.pendingOperations.Run(\n\t\tvolumeToUnmount.VolumeName, podName, \"\" /* nodeName */, generatedOperations)\n}","line":{"from":973,"to":1002}} {"id":100013057,"name":"UnmountDevice","signature":"func (oe *operationExecutor) UnmountDevice(","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"func (oe *operationExecutor) UnmountDevice(\n\tdeviceToDetach AttachedVolume,\n\tactualStateOfWorld ActualStateOfWorldMounterUpdater,\n\thostutil hostutil.HostUtils) error {\n\tfsVolume, err := util.CheckVolumeModeFilesystem(deviceToDetach.VolumeSpec)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar generatedOperations volumetypes.GeneratedOperations\n\tif fsVolume {\n\t\t// Filesystem volume case\n\t\t// Unmount and detach a device if a volume isn't referenced\n\t\tgeneratedOperations, err = oe.operationGenerator.GenerateUnmountDeviceFunc(\n\t\t\tdeviceToDetach, actualStateOfWorld, hostutil)\n\t} else {\n\t\t// Block volume case\n\t\t// Detach a device and remove loopback if a volume isn't referenced\n\t\tgeneratedOperations, err = oe.operationGenerator.GenerateUnmapDeviceFunc(\n\t\t\tdeviceToDetach, actualStateOfWorld, hostutil)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Avoid executing unmount/unmap device from multiple pods referencing\n\t// the same volume in parallel\n\tpodName := nestedpendingoperations.EmptyUniquePodName\n\n\treturn oe.pendingOperations.Run(\n\t\tdeviceToDetach.VolumeName, podName, \"\" /* nodeName */, generatedOperations)\n}","line":{"from":1004,"to":1033}} {"id":100013058,"name":"ExpandInUseVolume","signature":"func (oe *operationExecutor) ExpandInUseVolume(volumeToMount VolumeToMount, actualStateOfWorld ActualStateOfWorldMounterUpdater, currentSize resource.Quantity) error","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"func (oe *operationExecutor) ExpandInUseVolume(volumeToMount VolumeToMount, actualStateOfWorld ActualStateOfWorldMounterUpdater, currentSize resource.Quantity) error {\n\tgeneratedOperations, err := oe.operationGenerator.GenerateExpandInUseVolumeFunc(volumeToMount, actualStateOfWorld, currentSize)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn oe.pendingOperations.Run(volumeToMount.VolumeName, \"\", \"\" /* nodeName */, generatedOperations)\n}","line":{"from":1035,"to":1041}} {"id":100013059,"name":"VerifyControllerAttachedVolume","signature":"func (oe *operationExecutor) VerifyControllerAttachedVolume(","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"func (oe *operationExecutor) VerifyControllerAttachedVolume(\n\tlogger klog.Logger,\n\tvolumeToMount VolumeToMount,\n\tnodeName types.NodeName,\n\tactualStateOfWorld ActualStateOfWorldAttacherUpdater) error {\n\tgeneratedOperations, err :=\n\t\toe.operationGenerator.GenerateVerifyControllerAttachedVolumeFunc(logger, volumeToMount, nodeName, actualStateOfWorld)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn oe.pendingOperations.Run(\n\t\tvolumeToMount.VolumeName, \"\" /* podName */, \"\" /* nodeName */, generatedOperations)\n}","line":{"from":1043,"to":1056}} {"id":100013060,"name":"ReconstructVolumeOperation","signature":"func (oe *operationExecutor) ReconstructVolumeOperation(","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"// ReconstructVolumeOperation return a func to create volumeSpec from mount path\nfunc (oe *operationExecutor) ReconstructVolumeOperation(\n\tvolumeMode v1.PersistentVolumeMode,\n\tplugin volume.VolumePlugin,\n\tmapperPlugin volume.BlockVolumePlugin,\n\tuid types.UID,\n\tpodName volumetypes.UniquePodName,\n\tvolumeSpecName string,\n\tvolumePath string,\n\tpluginName string) (volume.ReconstructedVolume, error) {\n\n\t// Filesystem Volume case\n\tif volumeMode == v1.PersistentVolumeFilesystem {\n\t\t// Create volumeSpec from mount path\n\t\tklog.V(5).Infof(\"Starting operationExecutor.ReconstructVolume for file volume on pod %q\", podName)\n\t\treconstructed, err := plugin.ConstructVolumeSpec(volumeSpecName, volumePath)\n\t\tif err != nil {\n\t\t\treturn volume.ReconstructedVolume{}, err\n\t\t}\n\t\treturn reconstructed, nil\n\t}\n\n\t// Block Volume case\n\t// Create volumeSpec from mount path\n\tklog.V(5).Infof(\"Starting operationExecutor.ReconstructVolume for block volume on pod %q\", podName)\n\n\t// volumePath contains volumeName on the path. In the case of block volume, {volumeName} is symbolic link\n\t// corresponding to raw block device.\n\t// ex. volumePath: pods/{podUid}}/{DefaultKubeletVolumeDevicesDirName}/{escapeQualifiedPluginName}/{volumeName}\n\tvolumeSpec, err := mapperPlugin.ConstructBlockVolumeSpec(uid, volumeSpecName, volumePath)\n\tif err != nil {\n\t\treturn volume.ReconstructedVolume{}, err\n\t}\n\treturn volume.ReconstructedVolume{\n\t\tSpec: volumeSpec,\n\t}, nil\n}","line":{"from":1058,"to":1094}} {"id":100013061,"name":"CheckVolumeExistenceOperation","signature":"func (oe *operationExecutor) CheckVolumeExistenceOperation(","file":"pkg/volume/util/operationexecutor/operation_executor.go","code":"// CheckVolumeExistenceOperation checks mount path directory if volume still exists\nfunc (oe *operationExecutor) CheckVolumeExistenceOperation(\n\tvolumeSpec *volume.Spec,\n\tmountPath, volumeName string,\n\tmounter mount.Interface,\n\tuniqueVolumeName v1.UniqueVolumeName,\n\tpodName volumetypes.UniquePodName,\n\tpodUID types.UID,\n\tattachable volume.AttachableVolumePlugin) (bool, error) {\n\tfsVolume, err := util.CheckVolumeModeFilesystem(volumeSpec)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t// Filesystem Volume case\n\t// For attachable volume case, check mount path directory if volume is still existing and mounted.\n\t// Return true if volume is mounted.\n\tif fsVolume {\n\t\tif attachable != nil {\n\t\t\tvar isNotMount bool\n\t\t\tvar mountCheckErr error\n\t\t\tif mounter == nil {\n\t\t\t\treturn false, fmt.Errorf(\"mounter was not set for a filesystem volume\")\n\t\t\t}\n\t\t\tif isNotMount, mountCheckErr = mount.IsNotMountPoint(mounter, mountPath); mountCheckErr != nil {\n\t\t\t\treturn false, fmt.Errorf(\"could not check whether the volume %q (spec.Name: %q) pod %q (UID: %q) is mounted with: %v\",\n\t\t\t\t\tuniqueVolumeName,\n\t\t\t\t\tvolumeName,\n\t\t\t\t\tpodName,\n\t\t\t\t\tpodUID,\n\t\t\t\t\tmountCheckErr)\n\t\t\t}\n\t\t\treturn !isNotMount, nil\n\t\t}\n\t\t// For non-attachable volume case, skip check and return true without mount point check\n\t\t// since plugins may not have volume mount point.\n\t\treturn true, nil\n\t}\n\n\t// Block Volume case\n\t// Check mount path directory if volume still exists, then return true if volume\n\t// is there. Either plugin is attachable or non-attachable, the plugin should\n\t// have symbolic link associated to raw block device under pod device map\n\t// if volume exists.\n\tblkutil := volumepathhandler.NewBlockVolumePathHandler()\n\tvar islinkExist bool\n\tvar checkErr error\n\tif islinkExist, checkErr = blkutil.IsSymlinkExist(mountPath); checkErr != nil {\n\t\treturn false, fmt.Errorf(\"could not check whether the block volume %q (spec.Name: %q) pod %q (UID: %q) is mapped to: %v\",\n\t\t\tuniqueVolumeName,\n\t\t\tvolumeName,\n\t\t\tpodName,\n\t\t\tpodUID,\n\t\t\tcheckErr)\n\t}\n\treturn islinkExist, nil\n}","line":{"from":1096,"to":1152}} {"id":100013062,"name":"NewOperationGenerator","signature":"func NewOperationGenerator(kubeClient clientset.Interface,","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"// NewOperationGenerator is returns instance of operationGenerator\nfunc NewOperationGenerator(kubeClient clientset.Interface,\n\tvolumePluginMgr *volume.VolumePluginMgr,\n\trecorder record.EventRecorder,\n\tblkUtil volumepathhandler.BlockVolumePathHandler) OperationGenerator {\n\n\treturn \u0026operationGenerator{\n\t\tkubeClient: kubeClient,\n\t\tvolumePluginMgr: volumePluginMgr,\n\t\trecorder: recorder,\n\t\tblkUtil: blkUtil,\n\t\ttranslator: csitrans.New(),\n\t}\n}","line":{"from":100,"to":113}} {"id":100013063,"name":"GenerateVolumesAreAttachedFunc","signature":"func (og *operationGenerator) GenerateVolumesAreAttachedFunc(","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) GenerateVolumesAreAttachedFunc(\n\tattachedVolumes []AttachedVolume,\n\tnodeName types.NodeName,\n\tactualStateOfWorld ActualStateOfWorldAttacherUpdater) (volumetypes.GeneratedOperations, error) {\n\t// volumesPerPlugin maps from a volume plugin to a list of volume specs which belong\n\t// to this type of plugin\n\tvolumesPerPlugin := make(map[string][]*volume.Spec)\n\t// volumeSpecMap maps from a volume spec to its unique volumeName which will be used\n\t// when calling MarkVolumeAsDetached\n\tvolumeSpecMap := make(map[*volume.Spec]v1.UniqueVolumeName)\n\n\t// Iterate each volume spec and put them into a map index by the pluginName\n\tfor _, volumeAttached := range attachedVolumes {\n\t\tif volumeAttached.VolumeSpec == nil {\n\t\t\tklog.Errorf(\"VerifyVolumesAreAttached.GenerateVolumesAreAttachedFunc: nil spec for volume %s\", volumeAttached.VolumeName)\n\t\t\tcontinue\n\t\t}\n\t\tvolumePlugin, err :=\n\t\t\tog.volumePluginMgr.FindPluginBySpec(volumeAttached.VolumeSpec)\n\t\tif err != nil || volumePlugin == nil {\n\t\t\tklog.Errorf(volumeAttached.GenerateErrorDetailed(\"VolumesAreAttached.FindPluginBySpec failed\", err).Error())\n\t\t\tcontinue\n\t\t}\n\t\tvolumeSpecList, pluginExists := volumesPerPlugin[volumePlugin.GetPluginName()]\n\t\tif !pluginExists {\n\t\t\tvolumeSpecList = []*volume.Spec{}\n\t\t}\n\t\tvolumeSpecList = append(volumeSpecList, volumeAttached.VolumeSpec)\n\t\tvolumesPerPlugin[volumePlugin.GetPluginName()] = volumeSpecList\n\t\t// Migration: VolumeSpecMap contains original VolumeName for use in ActualStateOfWorld\n\t\tvolumeSpecMap[volumeAttached.VolumeSpec] = volumeAttached.VolumeName\n\t}\n\n\tvolumesAreAttachedFunc := func() volumetypes.OperationContext {\n\n\t\t// For each volume plugin, pass the list of volume specs to VolumesAreAttached to check\n\t\t// whether the volumes are still attached.\n\t\tfor pluginName, volumesSpecs := range volumesPerPlugin {\n\t\t\tattachableVolumePlugin, err :=\n\t\t\t\tog.volumePluginMgr.FindAttachablePluginByName(pluginName)\n\t\t\tif err != nil || attachableVolumePlugin == nil {\n\t\t\t\tklog.Errorf(\n\t\t\t\t\t\"VolumeAreAttached.FindAttachablePluginBySpec failed for plugin %q with: %v\",\n\t\t\t\t\tpluginName,\n\t\t\t\t\terr)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvolumeAttacher, newAttacherErr := attachableVolumePlugin.NewAttacher()\n\t\t\tif newAttacherErr != nil {\n\t\t\t\tklog.Errorf(\n\t\t\t\t\t\"VolumesAreAttached.NewAttacher failed for getting plugin %q with: %v\",\n\t\t\t\t\tpluginName,\n\t\t\t\t\tnewAttacherErr)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tattached, areAttachedErr := volumeAttacher.VolumesAreAttached(volumesSpecs, nodeName)\n\t\t\tif areAttachedErr != nil {\n\t\t\t\tklog.Errorf(\n\t\t\t\t\t\"VolumesAreAttached failed for checking on node %q with: %v\",\n\t\t\t\t\tnodeName,\n\t\t\t\t\tareAttachedErr)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor spec, check := range attached {\n\t\t\t\tif !check {\n\t\t\t\t\tactualStateOfWorld.MarkVolumeAsDetached(volumeSpecMap[spec], nodeName)\n\t\t\t\t\tklog.V(1).Infof(\"VerifyVolumesAreAttached determined volume %q (spec.Name: %q) is no longer attached to node %q, therefore it was marked as detached.\",\n\t\t\t\t\t\tvolumeSpecMap[spec], spec.Name(), nodeName)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// It is hard to differentiate migrated status for all volumes for verify_volumes_are_attached_per_node\n\t\treturn volumetypes.NewOperationContext(nil, nil, false)\n\t}\n\n\treturn volumetypes.GeneratedOperations{\n\t\tOperationName: \"verify_volumes_are_attached_per_node\",\n\t\tOperationFunc: volumesAreAttachedFunc,\n\t\tCompleteFunc: util.OperationCompleteHook(util.GetFullQualifiedPluginNameForVolume(\"\u003cn/a\u003e\", nil), \"verify_volumes_are_attached_per_node\"),\n\t\tEventRecorderFunc: nil, // nil because we do not want to generate event on error\n\t}, nil\n}","line":{"from":185,"to":270}} {"id":100013064,"name":"GenerateBulkVolumeVerifyFunc","signature":"func (og *operationGenerator) GenerateBulkVolumeVerifyFunc(","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) GenerateBulkVolumeVerifyFunc(\n\tpluginNodeVolumes map[types.NodeName][]*volume.Spec,\n\tpluginName string,\n\tvolumeSpecMap map[*volume.Spec]v1.UniqueVolumeName,\n\tactualStateOfWorld ActualStateOfWorldAttacherUpdater) (volumetypes.GeneratedOperations, error) {\n\n\t// Migration: All inputs already should be translated by caller for this\n\t// function except volumeSpecMap which contains original volume names for\n\t// use with actualStateOfWorld\n\n\tbulkVolumeVerifyFunc := func() volumetypes.OperationContext {\n\t\tattachableVolumePlugin, err :=\n\t\t\tog.volumePluginMgr.FindAttachablePluginByName(pluginName)\n\t\tif err != nil || attachableVolumePlugin == nil {\n\t\t\tklog.Errorf(\n\t\t\t\t\"BulkVerifyVolume.FindAttachablePluginBySpec failed for plugin %q with: %v\",\n\t\t\t\tpluginName,\n\t\t\t\terr)\n\t\t\treturn volumetypes.NewOperationContext(nil, nil, false)\n\t\t}\n\n\t\tvolumeAttacher, newAttacherErr := attachableVolumePlugin.NewAttacher()\n\n\t\tif newAttacherErr != nil {\n\t\t\tklog.Errorf(\n\t\t\t\t\"BulkVerifyVolume.NewAttacher failed for getting plugin %q with: %v\",\n\t\t\t\tattachableVolumePlugin,\n\t\t\t\tnewAttacherErr)\n\t\t\treturn volumetypes.NewOperationContext(nil, nil, false)\n\t\t}\n\t\tbulkVolumeVerifier, ok := volumeAttacher.(volume.BulkVolumeVerifier)\n\n\t\tif !ok {\n\t\t\tklog.Errorf(\"BulkVerifyVolume failed to type assert attacher %q\", bulkVolumeVerifier)\n\t\t\treturn volumetypes.NewOperationContext(nil, nil, false)\n\t\t}\n\n\t\tattached, bulkAttachErr := bulkVolumeVerifier.BulkVerifyVolumes(pluginNodeVolumes)\n\t\tif bulkAttachErr != nil {\n\t\t\tklog.Errorf(\"BulkVerifyVolume.BulkVerifyVolumes Error checking volumes are attached with %v\", bulkAttachErr)\n\t\t\treturn volumetypes.NewOperationContext(nil, nil, false)\n\t\t}\n\n\t\tfor nodeName, volumeSpecs := range pluginNodeVolumes {\n\t\t\tfor _, volumeSpec := range volumeSpecs {\n\t\t\t\tnodeVolumeSpecs, nodeChecked := attached[nodeName]\n\n\t\t\t\tif !nodeChecked {\n\t\t\t\t\tklog.V(2).Infof(\"VerifyVolumesAreAttached.BulkVerifyVolumes failed for node %q and leaving volume %q as attached\",\n\t\t\t\t\t\tnodeName,\n\t\t\t\t\t\tvolumeSpec.Name())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tcheck := nodeVolumeSpecs[volumeSpec]\n\n\t\t\t\tif !check {\n\t\t\t\t\tklog.V(2).Infof(\"VerifyVolumesAreAttached.BulkVerifyVolumes failed for node %q and volume %q\",\n\t\t\t\t\t\tnodeName,\n\t\t\t\t\t\tvolumeSpec.Name())\n\t\t\t\t\tactualStateOfWorld.MarkVolumeAsDetached(volumeSpecMap[volumeSpec], nodeName)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// It is hard to differentiate migrated status for all volumes for verify_volumes_are_attached\n\t\treturn volumetypes.NewOperationContext(nil, nil, false)\n\t}\n\n\treturn volumetypes.GeneratedOperations{\n\t\tOperationName: \"verify_volumes_are_attached\",\n\t\tOperationFunc: bulkVolumeVerifyFunc,\n\t\tCompleteFunc: util.OperationCompleteHook(util.GetFullQualifiedPluginNameForVolume(pluginName, nil), \"verify_volumes_are_attached\"),\n\t\tEventRecorderFunc: nil, // nil because we do not want to generate event on error\n\t}, nil\n\n}","line":{"from":272,"to":348}} {"id":100013065,"name":"GenerateAttachVolumeFunc","signature":"func (og *operationGenerator) GenerateAttachVolumeFunc(","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) GenerateAttachVolumeFunc(\n\tlogger klog.Logger,\n\tvolumeToAttach VolumeToAttach,\n\tactualStateOfWorld ActualStateOfWorldAttacherUpdater) volumetypes.GeneratedOperations {\n\n\tattachVolumeFunc := func() volumetypes.OperationContext {\n\t\tattachableVolumePlugin, err :=\n\t\t\tog.volumePluginMgr.FindAttachablePluginBySpec(volumeToAttach.VolumeSpec)\n\n\t\tmigrated := getMigratedStatusBySpec(volumeToAttach.VolumeSpec)\n\n\t\tif err != nil || attachableVolumePlugin == nil {\n\t\t\teventErr, detailedErr := volumeToAttach.GenerateError(\"AttachVolume.FindAttachablePluginBySpec failed\", err)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\tvolumeAttacher, newAttacherErr := attachableVolumePlugin.NewAttacher()\n\t\tif newAttacherErr != nil {\n\t\t\teventErr, detailedErr := volumeToAttach.GenerateError(\"AttachVolume.NewAttacher failed\", newAttacherErr)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\t// Execute attach\n\t\tdevicePath, attachErr := volumeAttacher.Attach(\n\t\t\tvolumeToAttach.VolumeSpec, volumeToAttach.NodeName)\n\n\t\tif attachErr != nil {\n\t\t\tuncertainNode := volumeToAttach.NodeName\n\t\t\tif derr, ok := attachErr.(*volerr.DanglingAttachError); ok {\n\t\t\t\tuncertainNode = derr.CurrentNode\n\t\t\t}\n\t\t\taddErr := actualStateOfWorld.MarkVolumeAsUncertain(\n\t\t\t\tlogger,\n\t\t\t\tvolumeToAttach.VolumeName,\n\t\t\t\tvolumeToAttach.VolumeSpec,\n\t\t\t\tuncertainNode)\n\t\t\tif addErr != nil {\n\t\t\t\tklog.Errorf(\"AttachVolume.MarkVolumeAsUncertain fail to add the volume %q to actual state with %s\", volumeToAttach.VolumeName, addErr)\n\t\t\t}\n\n\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\teventErr, detailedErr := volumeToAttach.GenerateError(\"AttachVolume.Attach failed\", attachErr)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\t// Successful attach event is useful for user debugging\n\t\tsimpleMsg, _ := volumeToAttach.GenerateMsg(\"AttachVolume.Attach succeeded\", \"\")\n\t\tfor _, pod := range volumeToAttach.ScheduledPods {\n\t\t\tog.recorder.Eventf(pod, v1.EventTypeNormal, kevents.SuccessfulAttachVolume, simpleMsg)\n\t\t}\n\t\tklog.Infof(volumeToAttach.GenerateMsgDetailed(\"AttachVolume.Attach succeeded\", \"\"))\n\n\t\t// Update actual state of world\n\t\taddVolumeNodeErr := actualStateOfWorld.MarkVolumeAsAttached(\n\t\t\tlogger, v1.UniqueVolumeName(\"\"), volumeToAttach.VolumeSpec, volumeToAttach.NodeName, devicePath)\n\t\tif addVolumeNodeErr != nil {\n\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\teventErr, detailedErr := volumeToAttach.GenerateError(\"AttachVolume.MarkVolumeAsAttached failed\", addVolumeNodeErr)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\treturn volumetypes.NewOperationContext(nil, nil, migrated)\n\t}\n\n\teventRecorderFunc := func(err *error) {\n\t\tif *err != nil {\n\t\t\tfor _, pod := range volumeToAttach.ScheduledPods {\n\t\t\t\tog.recorder.Eventf(pod, v1.EventTypeWarning, kevents.FailedAttachVolume, (*err).Error())\n\t\t\t}\n\t\t}\n\t}\n\n\tattachableVolumePluginName := unknownAttachableVolumePlugin\n\n\t// Get attacher plugin\n\tattachableVolumePlugin, err :=\n\t\tog.volumePluginMgr.FindAttachablePluginBySpec(volumeToAttach.VolumeSpec)\n\t// It's ok to ignore the error, returning error is not expected from this function.\n\t// If an error case occurred during the function generation, this error case(skipped one) will also trigger an error\n\t// while the generated function is executed. And those errors will be handled during the execution of the generated\n\t// function with a back off policy.\n\tif err == nil \u0026\u0026 attachableVolumePlugin != nil {\n\t\tattachableVolumePluginName = attachableVolumePlugin.GetPluginName()\n\t}\n\n\treturn volumetypes.GeneratedOperations{\n\t\tOperationName: \"volume_attach\",\n\t\tOperationFunc: attachVolumeFunc,\n\t\tEventRecorderFunc: eventRecorderFunc,\n\t\tCompleteFunc: util.OperationCompleteHook(util.GetFullQualifiedPluginNameForVolume(attachableVolumePluginName, volumeToAttach.VolumeSpec), \"volume_attach\"),\n\t}\n}","line":{"from":350,"to":441}} {"id":100013066,"name":"GetVolumePluginMgr","signature":"func (og *operationGenerator) GetVolumePluginMgr() *volume.VolumePluginMgr","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) GetVolumePluginMgr() *volume.VolumePluginMgr {\n\treturn og.volumePluginMgr\n}","line":{"from":443,"to":445}} {"id":100013067,"name":"GetCSITranslator","signature":"func (og *operationGenerator) GetCSITranslator() InTreeToCSITranslator","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) GetCSITranslator() InTreeToCSITranslator {\n\treturn og.translator\n}","line":{"from":447,"to":449}} {"id":100013068,"name":"GenerateDetachVolumeFunc","signature":"func (og *operationGenerator) GenerateDetachVolumeFunc(","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) GenerateDetachVolumeFunc(\n\tlogger klog.Logger,\n\tvolumeToDetach AttachedVolume,\n\tverifySafeToDetach bool,\n\tactualStateOfWorld ActualStateOfWorldAttacherUpdater) (volumetypes.GeneratedOperations, error) {\n\tvar volumeName string\n\tvar attachableVolumePlugin volume.AttachableVolumePlugin\n\tvar pluginName string\n\tvar err error\n\n\tif volumeToDetach.VolumeSpec != nil {\n\t\tattachableVolumePlugin, err = findDetachablePluginBySpec(volumeToDetach.VolumeSpec, og.volumePluginMgr)\n\t\tif err != nil || attachableVolumePlugin == nil {\n\t\t\treturn volumetypes.GeneratedOperations{}, volumeToDetach.GenerateErrorDetailed(\"DetachVolume.findDetachablePluginBySpec failed\", err)\n\t\t}\n\n\t\tvolumeName, err =\n\t\t\tattachableVolumePlugin.GetVolumeName(volumeToDetach.VolumeSpec)\n\t\tif err != nil {\n\t\t\treturn volumetypes.GeneratedOperations{}, volumeToDetach.GenerateErrorDetailed(\"DetachVolume.GetVolumeName failed\", err)\n\t\t}\n\t} else {\n\t\t// Get attacher plugin and the volumeName by splitting the volume unique name in case\n\t\t// there's no VolumeSpec: this happens only on attach/detach controller crash recovery\n\t\t// when a pod has been deleted during the controller downtime\n\t\tpluginName, volumeName, err = util.SplitUniqueName(volumeToDetach.VolumeName)\n\t\tif err != nil {\n\t\t\treturn volumetypes.GeneratedOperations{}, volumeToDetach.GenerateErrorDetailed(\"DetachVolume.SplitUniqueName failed\", err)\n\t\t}\n\n\t\tattachableVolumePlugin, err = og.volumePluginMgr.FindAttachablePluginByName(pluginName)\n\t\tif err != nil || attachableVolumePlugin == nil {\n\t\t\treturn volumetypes.GeneratedOperations{}, volumeToDetach.GenerateErrorDetailed(\"DetachVolume.FindAttachablePluginByName failed\", err)\n\t\t}\n\n\t}\n\n\tif pluginName == \"\" {\n\t\tpluginName = attachableVolumePlugin.GetPluginName()\n\t}\n\n\tvolumeDetacher, err := attachableVolumePlugin.NewDetacher()\n\tif err != nil {\n\t\treturn volumetypes.GeneratedOperations{}, volumeToDetach.GenerateErrorDetailed(\"DetachVolume.NewDetacher failed\", err)\n\t}\n\n\tdetachVolumeFunc := func() volumetypes.OperationContext {\n\t\tvar err error\n\t\tif verifySafeToDetach {\n\t\t\terr = og.verifyVolumeIsSafeToDetach(volumeToDetach)\n\t\t}\n\t\tif err == nil {\n\t\t\terr = volumeDetacher.Detach(volumeName, volumeToDetach.NodeName)\n\t\t}\n\n\t\tmigrated := getMigratedStatusBySpec(volumeToDetach.VolumeSpec)\n\n\t\tif err != nil {\n\t\t\t// On failure, add volume back to ReportAsAttached list\n\t\t\tactualStateOfWorld.AddVolumeToReportAsAttached(\n\t\t\t\tlogger, volumeToDetach.VolumeName, volumeToDetach.NodeName)\n\t\t\teventErr, detailedErr := volumeToDetach.GenerateError(\"DetachVolume.Detach failed\", err)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\tklog.Infof(volumeToDetach.GenerateMsgDetailed(\"DetachVolume.Detach succeeded\", \"\"))\n\n\t\t// Update actual state of world\n\t\tactualStateOfWorld.MarkVolumeAsDetached(\n\t\t\tvolumeToDetach.VolumeName, volumeToDetach.NodeName)\n\n\t\treturn volumetypes.NewOperationContext(nil, nil, migrated)\n\t}\n\n\treturn volumetypes.GeneratedOperations{\n\t\tOperationName: DetachOperationName,\n\t\tOperationFunc: detachVolumeFunc,\n\t\tCompleteFunc: util.OperationCompleteHook(util.GetFullQualifiedPluginNameForVolume(pluginName, volumeToDetach.VolumeSpec), DetachOperationName),\n\t\tEventRecorderFunc: nil, // nil because we do not want to generate event on error\n\t}, nil\n}","line":{"from":451,"to":531}} {"id":100013069,"name":"GenerateMountVolumeFunc","signature":"func (og *operationGenerator) GenerateMountVolumeFunc(","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) GenerateMountVolumeFunc(\n\twaitForAttachTimeout time.Duration,\n\tvolumeToMount VolumeToMount,\n\tactualStateOfWorld ActualStateOfWorldMounterUpdater,\n\tisRemount bool) volumetypes.GeneratedOperations {\n\n\tvolumePluginName := unknownVolumePlugin\n\tvolumePlugin, err :=\n\t\tog.volumePluginMgr.FindPluginBySpec(volumeToMount.VolumeSpec)\n\tif err == nil \u0026\u0026 volumePlugin != nil {\n\t\tvolumePluginName = volumePlugin.GetPluginName()\n\t}\n\n\tmountVolumeFunc := func() volumetypes.OperationContext {\n\t\t// Get mounter plugin\n\t\tvolumePlugin, err := og.volumePluginMgr.FindPluginBySpec(volumeToMount.VolumeSpec)\n\n\t\tmigrated := getMigratedStatusBySpec(volumeToMount.VolumeSpec)\n\n\t\tif err != nil || volumePlugin == nil {\n\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MountVolume.FindPluginBySpec failed\", err)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\taffinityErr := checkNodeAffinity(og, volumeToMount)\n\t\tif affinityErr != nil {\n\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MountVolume.NodeAffinity check failed\", affinityErr)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\tvolumeMounter, newMounterErr := volumePlugin.NewMounter(\n\t\t\tvolumeToMount.VolumeSpec,\n\t\t\tvolumeToMount.Pod,\n\t\t\tvolume.VolumeOptions{})\n\t\tif newMounterErr != nil {\n\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MountVolume.NewMounter initialization failed\", newMounterErr)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\tmountCheckError := checkMountOptionSupport(og, volumeToMount, volumePlugin)\n\t\tif mountCheckError != nil {\n\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MountVolume.MountOptionSupport check failed\", mountCheckError)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\t// Enforce ReadWriteOncePod access mode if it is the only one present. This is also enforced during scheduling.\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.ReadWriteOncePod) \u0026\u0026\n\t\t\tactualStateOfWorld.IsVolumeMountedElsewhere(volumeToMount.VolumeName, volumeToMount.PodName) \u0026\u0026\n\t\t\t// Because we do not know what access mode the pod intends to use if there are multiple.\n\t\t\tlen(volumeToMount.VolumeSpec.PersistentVolume.Spec.AccessModes) == 1 \u0026\u0026\n\t\t\tv1helper.ContainsAccessMode(volumeToMount.VolumeSpec.PersistentVolume.Spec.AccessModes, v1.ReadWriteOncePod) {\n\n\t\t\terr = goerrors.New(\"volume uses the ReadWriteOncePod access mode and is already in use by another pod\")\n\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MountVolume.SetUp failed\", err)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\t// Get attacher, if possible\n\t\tattachableVolumePlugin, _ :=\n\t\t\tog.volumePluginMgr.FindAttachablePluginBySpec(volumeToMount.VolumeSpec)\n\t\tvar volumeAttacher volume.Attacher\n\t\tif attachableVolumePlugin != nil {\n\t\t\tvolumeAttacher, _ = attachableVolumePlugin.NewAttacher()\n\t\t}\n\n\t\t// get deviceMounter, if possible\n\t\tdeviceMountableVolumePlugin, _ := og.volumePluginMgr.FindDeviceMountablePluginBySpec(volumeToMount.VolumeSpec)\n\t\tvar volumeDeviceMounter volume.DeviceMounter\n\t\tif deviceMountableVolumePlugin != nil {\n\t\t\tvolumeDeviceMounter, _ = deviceMountableVolumePlugin.NewDeviceMounter()\n\t\t}\n\n\t\tvar fsGroup *int64\n\t\tvar fsGroupChangePolicy *v1.PodFSGroupChangePolicy\n\t\tif podSc := volumeToMount.Pod.Spec.SecurityContext; podSc != nil {\n\t\t\tif podSc.FSGroup != nil {\n\t\t\t\tfsGroup = podSc.FSGroup\n\t\t\t}\n\t\t\tif podSc.FSGroupChangePolicy != nil {\n\t\t\t\tfsGroupChangePolicy = podSc.FSGroupChangePolicy\n\t\t\t}\n\t\t}\n\n\t\tdevicePath := volumeToMount.DevicePath\n\t\tif volumeAttacher != nil {\n\t\t\t// Wait for attachable volumes to finish attaching\n\t\t\tklog.InfoS(volumeToMount.GenerateMsgDetailed(\"MountVolume.WaitForAttach entering\", fmt.Sprintf(\"DevicePath %q\", volumeToMount.DevicePath)), \"pod\", klog.KObj(volumeToMount.Pod))\n\n\t\t\tdevicePath, err = volumeAttacher.WaitForAttach(\n\t\t\t\tvolumeToMount.VolumeSpec, devicePath, volumeToMount.Pod, waitForAttachTimeout)\n\t\t\tif err != nil {\n\t\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MountVolume.WaitForAttach failed\", err)\n\t\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t\t}\n\n\t\t\tklog.InfoS(volumeToMount.GenerateMsgDetailed(\"MountVolume.WaitForAttach succeeded\", fmt.Sprintf(\"DevicePath %q\", devicePath)), \"pod\", klog.KObj(volumeToMount.Pod))\n\t\t}\n\n\t\tvar resizeError error\n\t\tresizeOptions := volume.NodeResizeOptions{\n\t\t\tDevicePath: devicePath,\n\t\t}\n\n\t\tif volumeDeviceMounter != nil \u0026\u0026 actualStateOfWorld.GetDeviceMountState(volumeToMount.VolumeName) != DeviceGloballyMounted {\n\t\t\tdeviceMountPath, err :=\n\t\t\t\tvolumeDeviceMounter.GetDeviceMountPath(volumeToMount.VolumeSpec)\n\t\t\tif err != nil {\n\t\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MountVolume.GetDeviceMountPath failed\", err)\n\t\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t\t}\n\n\t\t\t// Mount device to global mount path\n\t\t\terr = volumeDeviceMounter.MountDevice(\n\t\t\t\tvolumeToMount.VolumeSpec,\n\t\t\t\tdevicePath,\n\t\t\t\tdeviceMountPath,\n\t\t\t\tvolume.DeviceMounterArgs{FsGroup: fsGroup, SELinuxLabel: volumeToMount.SELinuxLabel},\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tog.checkForFailedMount(volumeToMount, err)\n\t\t\t\tog.markDeviceErrorState(volumeToMount, devicePath, deviceMountPath, err, actualStateOfWorld)\n\t\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MountVolume.MountDevice failed\", err)\n\t\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t\t}\n\n\t\t\tklog.InfoS(volumeToMount.GenerateMsgDetailed(\"MountVolume.MountDevice succeeded\", fmt.Sprintf(\"device mount path %q\", deviceMountPath)), \"pod\", klog.KObj(volumeToMount.Pod))\n\n\t\t\t// Update actual state of world to reflect volume is globally mounted\n\t\t\tmarkDeviceMountedErr := actualStateOfWorld.MarkDeviceAsMounted(\n\t\t\t\tvolumeToMount.VolumeName, devicePath, deviceMountPath, volumeToMount.SELinuxLabel)\n\t\t\tif markDeviceMountedErr != nil {\n\t\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MountVolume.MarkDeviceAsMounted failed\", markDeviceMountedErr)\n\t\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t\t}\n\t\t\t// set staging path for volume expansion\n\t\t\tresizeOptions.DeviceStagePath = deviceMountPath\n\t\t}\n\n\t\tif volumeDeviceMounter != nil \u0026\u0026 resizeOptions.DeviceStagePath == \"\" {\n\t\t\tdeviceStagePath, err := volumeDeviceMounter.GetDeviceMountPath(volumeToMount.VolumeSpec)\n\t\t\tif err != nil {\n\t\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MountVolume.GetDeviceMountPath failed for expansion\", err)\n\t\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t\t}\n\t\t\tresizeOptions.DeviceStagePath = deviceStagePath\n\t\t}\n\n\t\t// Execute mount\n\t\tmountErr := volumeMounter.SetUp(volume.MounterArgs{\n\t\t\tFsUser: util.FsUserFrom(volumeToMount.Pod),\n\t\t\tFsGroup: fsGroup,\n\t\t\tDesiredSize: volumeToMount.DesiredSizeLimit,\n\t\t\tFSGroupChangePolicy: fsGroupChangePolicy,\n\t\t\tSELinuxLabel: volumeToMount.SELinuxLabel,\n\t\t})\n\t\t// Update actual state of world\n\t\tmarkOpts := MarkVolumeOpts{\n\t\t\tPodName: volumeToMount.PodName,\n\t\t\tPodUID: volumeToMount.Pod.UID,\n\t\t\tVolumeName: volumeToMount.VolumeName,\n\t\t\tMounter: volumeMounter,\n\t\t\tOuterVolumeSpecName: volumeToMount.OuterVolumeSpecName,\n\t\t\tVolumeGidVolume: volumeToMount.VolumeGidValue,\n\t\t\tVolumeSpec: volumeToMount.VolumeSpec,\n\t\t\tVolumeMountState: VolumeMounted,\n\t\t\tSELinuxMountContext: volumeToMount.SELinuxLabel,\n\t\t}\n\t\tif mountErr != nil {\n\t\t\tog.checkForFailedMount(volumeToMount, mountErr)\n\t\t\tog.markVolumeErrorState(volumeToMount, markOpts, mountErr, actualStateOfWorld)\n\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MountVolume.SetUp failed\", mountErr)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\tdetailedMsg := volumeToMount.GenerateMsgDetailed(\"MountVolume.SetUp succeeded\", \"\")\n\t\tverbosity := klog.Level(1)\n\t\tif isRemount {\n\t\t\tverbosity = klog.Level(4)\n\t\t}\n\t\tklog.V(verbosity).InfoS(detailedMsg, \"pod\", klog.KObj(volumeToMount.Pod))\n\t\tresizeOptions.DeviceMountPath = volumeMounter.GetPath()\n\n\t\t_, resizeError = og.expandVolumeDuringMount(volumeToMount, actualStateOfWorld, resizeOptions)\n\t\tif resizeError != nil {\n\t\t\tklog.Errorf(\"MountVolume.NodeExpandVolume failed with %v\", resizeError)\n\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MountVolume.Setup failed while expanding volume\", resizeError)\n\t\t\t// At this point, MountVolume.Setup already succeeded, we should add volume into actual state\n\t\t\t// so that reconciler can clean up volume when needed. However, volume resize failed,\n\t\t\t// we should not mark the volume as mounted to avoid pod starts using it.\n\t\t\t// Considering the above situations, we mark volume as uncertain here so that reconciler will trigger\n\t\t\t// volume tear down when pod is deleted, and also makes sure pod will not start using it.\n\t\t\tif err := actualStateOfWorld.MarkVolumeMountAsUncertain(markOpts); err != nil {\n\t\t\t\tklog.Errorf(volumeToMount.GenerateErrorDetailed(\"MountVolume.MarkVolumeMountAsUncertain failed\", err).Error())\n\t\t\t}\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\t// record total time it takes to mount a volume. This is end to end time that includes waiting for volume to attach, node to be update\n\t\t// plugin call to succeed\n\t\tmountRequestTime := volumeToMount.MountRequestTime\n\t\ttotalTimeTaken := time.Since(mountRequestTime).Seconds()\n\t\tutil.RecordOperationLatencyMetric(util.GetFullQualifiedPluginNameForVolume(volumePluginName, volumeToMount.VolumeSpec), \"overall_volume_mount\", totalTimeTaken)\n\n\t\tmarkVolMountedErr := actualStateOfWorld.MarkVolumeAsMounted(markOpts)\n\t\tif markVolMountedErr != nil {\n\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MountVolume.MarkVolumeAsMounted failed\", markVolMountedErr)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\t\treturn volumetypes.NewOperationContext(nil, nil, migrated)\n\t}\n\n\teventRecorderFunc := func(err *error) {\n\t\tif *err != nil {\n\t\t\tog.recorder.Eventf(volumeToMount.Pod, v1.EventTypeWarning, kevents.FailedMountVolume, (*err).Error())\n\t\t}\n\t}\n\n\treturn volumetypes.GeneratedOperations{\n\t\tOperationName: \"volume_mount\",\n\t\tOperationFunc: mountVolumeFunc,\n\t\tEventRecorderFunc: eventRecorderFunc,\n\t\tCompleteFunc: util.OperationCompleteHook(util.GetFullQualifiedPluginNameForVolume(volumePluginName, volumeToMount.VolumeSpec), \"volume_mount\"),\n\t}\n}","line":{"from":533,"to":763}} {"id":100013070,"name":"checkForFailedMount","signature":"func (og *operationGenerator) checkForFailedMount(volumeToMount VolumeToMount, mountError error)","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) checkForFailedMount(volumeToMount VolumeToMount, mountError error) {\n\tpv := volumeToMount.VolumeSpec.PersistentVolume\n\tif pv == nil {\n\t\treturn\n\t}\n\n\tif volumetypes.IsFilesystemMismatchError(mountError) {\n\t\tsimpleMsg, _ := volumeToMount.GenerateMsg(\"MountVolume failed\", mountError.Error())\n\t\tog.recorder.Eventf(pv, v1.EventTypeWarning, kevents.FailedMountOnFilesystemMismatch, simpleMsg)\n\t}\n}","line":{"from":765,"to":775}} {"id":100013071,"name":"markDeviceErrorState","signature":"func (og *operationGenerator) markDeviceErrorState(volumeToMount VolumeToMount, devicePath, deviceMountPath string, mountError error, actualStateOfWorld ActualStateOfWorldMounterUpdater)","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) markDeviceErrorState(volumeToMount VolumeToMount, devicePath, deviceMountPath string, mountError error, actualStateOfWorld ActualStateOfWorldMounterUpdater) {\n\tif volumetypes.IsOperationFinishedError(mountError) \u0026\u0026\n\t\tactualStateOfWorld.GetDeviceMountState(volumeToMount.VolumeName) == DeviceMountUncertain {\n\t\t// Only devices which were uncertain can be marked as unmounted\n\t\tmarkDeviceUnmountError := actualStateOfWorld.MarkDeviceAsUnmounted(volumeToMount.VolumeName)\n\t\tif markDeviceUnmountError != nil {\n\t\t\tklog.Errorf(volumeToMount.GenerateErrorDetailed(\"MountDevice.MarkDeviceAsUnmounted failed\", markDeviceUnmountError).Error())\n\t\t}\n\t\treturn\n\t}\n\n\tif volumetypes.IsUncertainProgressError(mountError) \u0026\u0026\n\t\tactualStateOfWorld.GetDeviceMountState(volumeToMount.VolumeName) == DeviceNotMounted {\n\t\t// only devices which are not mounted can be marked as uncertain. We do not want to mark a device\n\t\t// which was previously marked as mounted here as uncertain.\n\t\tmarkDeviceUncertainError := actualStateOfWorld.MarkDeviceAsUncertain(volumeToMount.VolumeName, devicePath, deviceMountPath, volumeToMount.SELinuxLabel)\n\t\tif markDeviceUncertainError != nil {\n\t\t\tklog.Errorf(volumeToMount.GenerateErrorDetailed(\"MountDevice.MarkDeviceAsUncertain failed\", markDeviceUncertainError).Error())\n\t\t}\n\t}\n\n}","line":{"from":777,"to":798}} {"id":100013072,"name":"markVolumeErrorState","signature":"func (og *operationGenerator) markVolumeErrorState(volumeToMount VolumeToMount, markOpts MarkVolumeOpts, mountError error, actualStateOfWorld ActualStateOfWorldMounterUpdater)","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) markVolumeErrorState(volumeToMount VolumeToMount, markOpts MarkVolumeOpts, mountError error, actualStateOfWorld ActualStateOfWorldMounterUpdater) {\n\tif volumetypes.IsOperationFinishedError(mountError) \u0026\u0026\n\t\tactualStateOfWorld.GetVolumeMountState(volumeToMount.VolumeName, markOpts.PodName) == VolumeMountUncertain {\n\t\t// if volume was previously reconstructed we are not going to change its state as unmounted even\n\t\t// if mount operation fails.\n\t\tif actualStateOfWorld.IsVolumeReconstructed(volumeToMount.VolumeName, volumeToMount.PodName) {\n\t\t\tklog.V(3).InfoS(\"MountVolume.markVolumeErrorState leaving volume uncertain\", \"volumeName\", volumeToMount.VolumeName)\n\t\t\treturn\n\t\t}\n\n\t\tt := actualStateOfWorld.MarkVolumeAsUnmounted(volumeToMount.PodName, volumeToMount.VolumeName)\n\t\tif t != nil {\n\t\t\tklog.Errorf(volumeToMount.GenerateErrorDetailed(\"MountVolume.MarkVolumeAsUnmounted failed\", t).Error())\n\t\t}\n\t\treturn\n\n\t}\n\n\tif volumetypes.IsUncertainProgressError(mountError) \u0026\u0026\n\t\tactualStateOfWorld.GetVolumeMountState(volumeToMount.VolumeName, markOpts.PodName) == VolumeNotMounted {\n\t\tt := actualStateOfWorld.MarkVolumeMountAsUncertain(markOpts)\n\t\tif t != nil {\n\t\t\tklog.Errorf(volumeToMount.GenerateErrorDetailed(\"MountVolume.MarkVolumeMountAsUncertain failed\", t).Error())\n\t\t}\n\t}\n}","line":{"from":800,"to":825}} {"id":100013073,"name":"GenerateUnmountVolumeFunc","signature":"func (og *operationGenerator) GenerateUnmountVolumeFunc(","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) GenerateUnmountVolumeFunc(\n\tvolumeToUnmount MountedVolume,\n\tactualStateOfWorld ActualStateOfWorldMounterUpdater,\n\tpodsDir string) (volumetypes.GeneratedOperations, error) {\n\t// Get mountable plugin\n\tvolumePlugin, err := og.volumePluginMgr.FindPluginByName(volumeToUnmount.PluginName)\n\tif err != nil || volumePlugin == nil {\n\t\treturn volumetypes.GeneratedOperations{}, volumeToUnmount.GenerateErrorDetailed(\"UnmountVolume.FindPluginByName failed\", err)\n\t}\n\tvolumeUnmounter, newUnmounterErr := volumePlugin.NewUnmounter(\n\t\tvolumeToUnmount.InnerVolumeSpecName, volumeToUnmount.PodUID)\n\tif newUnmounterErr != nil {\n\t\treturn volumetypes.GeneratedOperations{}, volumeToUnmount.GenerateErrorDetailed(\"UnmountVolume.NewUnmounter failed\", newUnmounterErr)\n\t}\n\n\tunmountVolumeFunc := func() volumetypes.OperationContext {\n\t\tsubpather := og.volumePluginMgr.Host.GetSubpather()\n\n\t\tmigrated := getMigratedStatusBySpec(volumeToUnmount.VolumeSpec)\n\n\t\t// Remove all bind-mounts for subPaths\n\t\tpodDir := filepath.Join(podsDir, string(volumeToUnmount.PodUID))\n\t\tif err := subpather.CleanSubPaths(podDir, volumeToUnmount.InnerVolumeSpecName); err != nil {\n\t\t\teventErr, detailedErr := volumeToUnmount.GenerateError(\"error cleaning subPath mounts\", err)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\t// Execute unmount\n\t\tunmountErr := volumeUnmounter.TearDown()\n\t\tif unmountErr != nil {\n\t\t\t// Mark the volume as uncertain, so SetUp is called for new pods. Teardown may be already in progress.\n\t\t\topts := MarkVolumeOpts{\n\t\t\t\tPodName: volumeToUnmount.PodName,\n\t\t\t\tPodUID: volumeToUnmount.PodUID,\n\t\t\t\tVolumeName: volumeToUnmount.VolumeName,\n\t\t\t\tOuterVolumeSpecName: volumeToUnmount.OuterVolumeSpecName,\n\t\t\t\tVolumeGidVolume: volumeToUnmount.VolumeGidValue,\n\t\t\t\tVolumeSpec: volumeToUnmount.VolumeSpec,\n\t\t\t\tVolumeMountState: VolumeMountUncertain,\n\t\t\t}\n\t\t\tmarkMountUncertainErr := actualStateOfWorld.MarkVolumeMountAsUncertain(opts)\n\t\t\tif markMountUncertainErr != nil {\n\t\t\t\t// There is nothing else we can do. Hope that UnmountVolume will be re-tried shortly.\n\t\t\t\tklog.Errorf(volumeToUnmount.GenerateErrorDetailed(\"UnmountVolume.MarkVolumeMountAsUncertain failed\", markMountUncertainErr).Error())\n\t\t\t}\n\n\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\teventErr, detailedErr := volumeToUnmount.GenerateError(\"UnmountVolume.TearDown failed\", unmountErr)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\tklog.Infof(\n\t\t\t\"UnmountVolume.TearDown succeeded for volume %q (OuterVolumeSpecName: %q) pod %q (UID: %q). InnerVolumeSpecName %q. PluginName %q, VolumeGidValue %q\",\n\t\t\tvolumeToUnmount.VolumeName,\n\t\t\tvolumeToUnmount.OuterVolumeSpecName,\n\t\t\tvolumeToUnmount.PodName,\n\t\t\tvolumeToUnmount.PodUID,\n\t\t\tvolumeToUnmount.InnerVolumeSpecName,\n\t\t\tvolumeToUnmount.PluginName,\n\t\t\tvolumeToUnmount.VolumeGidValue)\n\n\t\t// Update actual state of world\n\t\tmarkVolMountedErr := actualStateOfWorld.MarkVolumeAsUnmounted(\n\t\t\tvolumeToUnmount.PodName, volumeToUnmount.VolumeName)\n\t\tif markVolMountedErr != nil {\n\t\t\t// On failure, just log and exit\n\t\t\tklog.Errorf(volumeToUnmount.GenerateErrorDetailed(\"UnmountVolume.MarkVolumeAsUnmounted failed\", markVolMountedErr).Error())\n\t\t}\n\n\t\treturn volumetypes.NewOperationContext(nil, nil, migrated)\n\t}\n\n\treturn volumetypes.GeneratedOperations{\n\t\tOperationName: \"volume_unmount\",\n\t\tOperationFunc: unmountVolumeFunc,\n\t\tCompleteFunc: util.OperationCompleteHook(util.GetFullQualifiedPluginNameForVolume(volumePlugin.GetPluginName(), volumeToUnmount.VolumeSpec), \"volume_unmount\"),\n\t\tEventRecorderFunc: nil, // nil because we do not want to generate event on error\n\t}, nil\n}","line":{"from":827,"to":905}} {"id":100013074,"name":"GenerateUnmountDeviceFunc","signature":"func (og *operationGenerator) GenerateUnmountDeviceFunc(","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) GenerateUnmountDeviceFunc(\n\tdeviceToDetach AttachedVolume,\n\tactualStateOfWorld ActualStateOfWorldMounterUpdater,\n\thostutil hostutil.HostUtils) (volumetypes.GeneratedOperations, error) {\n\t// Get DeviceMounter plugin\n\tdeviceMountableVolumePlugin, err :=\n\t\tog.volumePluginMgr.FindDeviceMountablePluginByName(deviceToDetach.PluginName)\n\tif err != nil || deviceMountableVolumePlugin == nil {\n\t\treturn volumetypes.GeneratedOperations{}, deviceToDetach.GenerateErrorDetailed(\"UnmountDevice.FindDeviceMountablePluginByName failed\", err)\n\t}\n\n\tvolumeDeviceUnmounter, err := deviceMountableVolumePlugin.NewDeviceUnmounter()\n\tif err != nil {\n\t\treturn volumetypes.GeneratedOperations{}, deviceToDetach.GenerateErrorDetailed(\"UnmountDevice.NewDeviceUnmounter failed\", err)\n\t}\n\n\tvolumeDeviceMounter, err := deviceMountableVolumePlugin.NewDeviceMounter()\n\tif err != nil {\n\t\treturn volumetypes.GeneratedOperations{}, deviceToDetach.GenerateErrorDetailed(\"UnmountDevice.NewDeviceMounter failed\", err)\n\t}\n\n\tunmountDeviceFunc := func() volumetypes.OperationContext {\n\n\t\tmigrated := getMigratedStatusBySpec(deviceToDetach.VolumeSpec)\n\n\t\t//deviceMountPath := deviceToDetach.DeviceMountPath\n\t\tdeviceMountPath, err :=\n\t\t\tvolumeDeviceMounter.GetDeviceMountPath(deviceToDetach.VolumeSpec)\n\t\tif err != nil {\n\t\t\t// On failure other than \"does not exist\", return error. Caller will log and retry.\n\t\t\tif !strings.Contains(err.Error(), \"does not exist\") {\n\t\t\t\teventErr, detailedErr := deviceToDetach.GenerateError(\"GetDeviceMountPath failed\", err)\n\t\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t\t}\n\t\t\t// If the mount path could not be found, don't fail the unmount, but instead log a warning and proceed,\n\t\t\t// using the value from deviceToDetach.DeviceMountPath, so that the device can be marked as unmounted\n\t\t\tdeviceMountPath = deviceToDetach.DeviceMountPath\n\t\t\tklog.Warningf(deviceToDetach.GenerateMsgDetailed(fmt.Sprintf(\n\t\t\t\t\"GetDeviceMountPath failed, but unmount operation will proceed using deviceMountPath=%s: %v\", deviceMountPath, err), \"\"))\n\t\t}\n\t\trefs, err := deviceMountableVolumePlugin.GetDeviceMountRefs(deviceMountPath)\n\n\t\tif err != nil || util.HasMountRefs(deviceMountPath, refs) {\n\t\t\tif err == nil {\n\t\t\t\terr = fmt.Errorf(\"the device mount path %q is still mounted by other references %v\", deviceMountPath, refs)\n\t\t\t}\n\t\t\teventErr, detailedErr := deviceToDetach.GenerateError(\"GetDeviceMountRefs check failed\", err)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\t\t// Execute unmount\n\t\tunmountDeviceErr := volumeDeviceUnmounter.UnmountDevice(deviceMountPath)\n\t\tif unmountDeviceErr != nil {\n\t\t\t// Mark the device as uncertain, so MountDevice is called for new pods. UnmountDevice may be already in progress.\n\t\t\tmarkDeviceUncertainErr := actualStateOfWorld.MarkDeviceAsUncertain(deviceToDetach.VolumeName, deviceToDetach.DevicePath, deviceMountPath, deviceToDetach.SELinuxMountContext)\n\t\t\tif markDeviceUncertainErr != nil {\n\t\t\t\t// There is nothing else we can do. Hope that UnmountDevice will be re-tried shortly.\n\t\t\t\tklog.Errorf(deviceToDetach.GenerateErrorDetailed(\"UnmountDevice.MarkDeviceAsUncertain failed\", markDeviceUncertainErr).Error())\n\t\t\t}\n\n\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\teventErr, detailedErr := deviceToDetach.GenerateError(\"UnmountDevice failed\", unmountDeviceErr)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\t\t// Before logging that UnmountDevice succeeded and moving on,\n\t\t// use hostutil.PathIsDevice to check if the path is a device,\n\t\t// if so use hostutil.DeviceOpened to check if the device is in use anywhere\n\t\t// else on the system. Retry if it returns true.\n\t\tdeviceOpened, deviceOpenedErr := isDeviceOpened(deviceToDetach, hostutil)\n\t\tif deviceOpenedErr != nil {\n\t\t\treturn volumetypes.NewOperationContext(nil, deviceOpenedErr, migrated)\n\t\t}\n\t\t// The device is still in use elsewhere. Caller will log and retry.\n\t\tif deviceOpened {\n\t\t\t// Mark the device as uncertain, so MountDevice is called for new pods.\n\t\t\tmarkDeviceUncertainErr := actualStateOfWorld.MarkDeviceAsUncertain(deviceToDetach.VolumeName, deviceToDetach.DevicePath, deviceMountPath, deviceToDetach.SELinuxMountContext)\n\t\t\tif markDeviceUncertainErr != nil {\n\t\t\t\t// There is nothing else we can do. Hope that UnmountDevice will be re-tried shortly.\n\t\t\t\tklog.Errorf(deviceToDetach.GenerateErrorDetailed(\"UnmountDevice.MarkDeviceAsUncertain failed\", markDeviceUncertainErr).Error())\n\t\t\t}\n\t\t\teventErr, detailedErr := deviceToDetach.GenerateError(\n\t\t\t\t\"UnmountDevice failed\",\n\t\t\t\tgoerrors.New(\"the device is in use when it was no longer expected to be in use\"))\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\tklog.Info(deviceToDetach.GenerateMsgDetailed(\"UnmountDevice succeeded\", \"\"))\n\n\t\t// Update actual state of world\n\t\tmarkDeviceUnmountedErr := actualStateOfWorld.MarkDeviceAsUnmounted(\n\t\t\tdeviceToDetach.VolumeName)\n\t\tif markDeviceUnmountedErr != nil {\n\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\teventErr, detailedErr := deviceToDetach.GenerateError(\"MarkDeviceAsUnmounted failed\", markDeviceUnmountedErr)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\treturn volumetypes.NewOperationContext(nil, nil, migrated)\n\t}\n\n\treturn volumetypes.GeneratedOperations{\n\t\tOperationName: \"unmount_device\",\n\t\tOperationFunc: unmountDeviceFunc,\n\t\tCompleteFunc: util.OperationCompleteHook(util.GetFullQualifiedPluginNameForVolume(deviceMountableVolumePlugin.GetPluginName(), deviceToDetach.VolumeSpec), \"unmount_device\"),\n\t\tEventRecorderFunc: nil, // nil because we do not want to generate event on error\n\t}, nil\n}","line":{"from":907,"to":1012}} {"id":100013075,"name":"GenerateMapVolumeFunc","signature":"func (og *operationGenerator) GenerateMapVolumeFunc(","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"// GenerateMapVolumeFunc marks volume as mounted based on following steps.\n// If plugin is attachable, call WaitForAttach() and then mark the device\n// as mounted. On next step, SetUpDevice is called without dependent of\n// plugin type, but this method mainly is targeted for none attachable plugin.\n// After setup is done, create symbolic links on both global map path and pod\n// device map path. Once symbolic links are created, take fd lock by\n// loopback for the device to avoid silent volume replacement. This lock\n// will be released once no one uses the device.\n// If all steps are completed, the volume is marked as mounted.\nfunc (og *operationGenerator) GenerateMapVolumeFunc(\n\twaitForAttachTimeout time.Duration,\n\tvolumeToMount VolumeToMount,\n\tactualStateOfWorld ActualStateOfWorldMounterUpdater) (volumetypes.GeneratedOperations, error) {\n\n\t// Get block volume mapper plugin\n\tblockVolumePlugin, err :=\n\t\tog.volumePluginMgr.FindMapperPluginBySpec(volumeToMount.VolumeSpec)\n\tif err != nil {\n\t\treturn volumetypes.GeneratedOperations{}, volumeToMount.GenerateErrorDetailed(\"MapVolume.FindMapperPluginBySpec failed\", err)\n\t}\n\n\tif blockVolumePlugin == nil {\n\t\treturn volumetypes.GeneratedOperations{}, volumeToMount.GenerateErrorDetailed(\"MapVolume.FindMapperPluginBySpec failed to find BlockVolumeMapper plugin. Volume plugin is nil.\", nil)\n\t}\n\n\taffinityErr := checkNodeAffinity(og, volumeToMount)\n\tif affinityErr != nil {\n\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MapVolume.NodeAffinity check failed\", affinityErr)\n\t\tog.recorder.Eventf(volumeToMount.Pod, v1.EventTypeWarning, kevents.FailedMountVolume, eventErr.Error())\n\t\treturn volumetypes.GeneratedOperations{}, detailedErr\n\t}\n\tblockVolumeMapper, newMapperErr := blockVolumePlugin.NewBlockVolumeMapper(\n\t\tvolumeToMount.VolumeSpec,\n\t\tvolumeToMount.Pod,\n\t\tvolume.VolumeOptions{})\n\tif newMapperErr != nil {\n\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MapVolume.NewBlockVolumeMapper initialization failed\", newMapperErr)\n\t\tog.recorder.Eventf(volumeToMount.Pod, v1.EventTypeWarning, kevents.FailedMapVolume, eventErr.Error())\n\t\treturn volumetypes.GeneratedOperations{}, detailedErr\n\t}\n\n\t// Get attacher, if possible\n\tattachableVolumePlugin, _ :=\n\t\tog.volumePluginMgr.FindAttachablePluginBySpec(volumeToMount.VolumeSpec)\n\tvar volumeAttacher volume.Attacher\n\tif attachableVolumePlugin != nil {\n\t\tvolumeAttacher, _ = attachableVolumePlugin.NewAttacher()\n\t}\n\n\tmapVolumeFunc := func() (operationContext volumetypes.OperationContext) {\n\t\tvar devicePath string\n\t\tvar stagingPath string\n\n\t\tmigrated := getMigratedStatusBySpec(volumeToMount.VolumeSpec)\n\n\t\t// Enforce ReadWriteOncePod access mode. This is also enforced during scheduling.\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.ReadWriteOncePod) \u0026\u0026\n\t\t\tactualStateOfWorld.IsVolumeMountedElsewhere(volumeToMount.VolumeName, volumeToMount.PodName) \u0026\u0026\n\t\t\t// Because we do not know what access mode the pod intends to use if there are multiple.\n\t\t\tlen(volumeToMount.VolumeSpec.PersistentVolume.Spec.AccessModes) == 1 \u0026\u0026\n\t\t\tv1helper.ContainsAccessMode(volumeToMount.VolumeSpec.PersistentVolume.Spec.AccessModes, v1.ReadWriteOncePod) {\n\n\t\t\terr = goerrors.New(\"volume uses the ReadWriteOncePod access mode and is already in use by another pod\")\n\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MapVolume.SetUpDevice failed\", err)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\t// Set up global map path under the given plugin directory using symbolic link\n\t\tglobalMapPath, err :=\n\t\t\tblockVolumeMapper.GetGlobalMapPath(volumeToMount.VolumeSpec)\n\t\tif err != nil {\n\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MapVolume.GetGlobalMapPath failed\", err)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\t\tif volumeAttacher != nil {\n\t\t\t// Wait for attachable volumes to finish attaching\n\t\t\tklog.InfoS(volumeToMount.GenerateMsgDetailed(\"MapVolume.WaitForAttach entering\", fmt.Sprintf(\"DevicePath %q\", volumeToMount.DevicePath)), \"pod\", klog.KObj(volumeToMount.Pod))\n\n\t\t\tdevicePath, err = volumeAttacher.WaitForAttach(\n\t\t\t\tvolumeToMount.VolumeSpec, volumeToMount.DevicePath, volumeToMount.Pod, waitForAttachTimeout)\n\t\t\tif err != nil {\n\t\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MapVolume.WaitForAttach failed\", err)\n\t\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t\t}\n\n\t\t\tklog.InfoS(volumeToMount.GenerateMsgDetailed(\"MapVolume.WaitForAttach succeeded\", fmt.Sprintf(\"DevicePath %q\", devicePath)), \"pod\", klog.KObj(volumeToMount.Pod))\n\n\t\t}\n\t\t// Call SetUpDevice if blockVolumeMapper implements CustomBlockVolumeMapper\n\t\tif customBlockVolumeMapper, ok := blockVolumeMapper.(volume.CustomBlockVolumeMapper); ok \u0026\u0026 actualStateOfWorld.GetDeviceMountState(volumeToMount.VolumeName) != DeviceGloballyMounted {\n\t\t\tvar mapErr error\n\t\t\tstagingPath, mapErr = customBlockVolumeMapper.SetUpDevice()\n\t\t\tif mapErr != nil {\n\t\t\t\tog.markDeviceErrorState(volumeToMount, devicePath, globalMapPath, mapErr, actualStateOfWorld)\n\t\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MapVolume.SetUpDevice failed\", mapErr)\n\t\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t\t}\n\t\t}\n\n\t\t// Update actual state of world to reflect volume is globally mounted\n\t\tmarkedDevicePath := devicePath\n\t\tmarkDeviceMappedErr := actualStateOfWorld.MarkDeviceAsMounted(\n\t\t\tvolumeToMount.VolumeName, markedDevicePath, globalMapPath, \"\")\n\t\tif markDeviceMappedErr != nil {\n\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MapVolume.MarkDeviceAsMounted failed\", markDeviceMappedErr)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\tmarkVolumeOpts := MarkVolumeOpts{\n\t\t\tPodName: volumeToMount.PodName,\n\t\t\tPodUID: volumeToMount.Pod.UID,\n\t\t\tVolumeName: volumeToMount.VolumeName,\n\t\t\tBlockVolumeMapper: blockVolumeMapper,\n\t\t\tOuterVolumeSpecName: volumeToMount.OuterVolumeSpecName,\n\t\t\tVolumeGidVolume: volumeToMount.VolumeGidValue,\n\t\t\tVolumeSpec: volumeToMount.VolumeSpec,\n\t\t\tVolumeMountState: VolumeMounted,\n\t\t}\n\n\t\t// Call MapPodDevice if blockVolumeMapper implements CustomBlockVolumeMapper\n\t\tif customBlockVolumeMapper, ok := blockVolumeMapper.(volume.CustomBlockVolumeMapper); ok {\n\t\t\t// Execute driver specific map\n\t\t\tpluginDevicePath, mapErr := customBlockVolumeMapper.MapPodDevice()\n\t\t\tif mapErr != nil {\n\t\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\t\tog.markVolumeErrorState(volumeToMount, markVolumeOpts, mapErr, actualStateOfWorld)\n\t\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MapVolume.MapPodDevice failed\", mapErr)\n\t\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t\t}\n\n\t\t\t// From now on, the volume is mapped. Mark it as uncertain on error,\n\t\t\t// so it is is unmapped when corresponding pod is deleted.\n\t\t\tdefer func() {\n\t\t\t\tif operationContext.EventErr != nil {\n\t\t\t\t\terrText := operationContext.EventErr.Error()\n\t\t\t\t\tog.markVolumeErrorState(volumeToMount, markVolumeOpts, volumetypes.NewUncertainProgressError(errText), actualStateOfWorld)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\t// if pluginDevicePath is provided, assume attacher may not provide device\n\t\t\t// or attachment flow uses SetupDevice to get device path\n\t\t\tif len(pluginDevicePath) != 0 {\n\t\t\t\tdevicePath = pluginDevicePath\n\t\t\t}\n\t\t\tif len(devicePath) == 0 {\n\t\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MapVolume failed\", goerrors.New(\"device path of the volume is empty\"))\n\t\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t\t}\n\t\t}\n\n\t\t// When kubelet is containerized, devicePath may be a symlink at a place unavailable to\n\t\t// kubelet, so evaluate it on the host and expect that it links to a device in /dev,\n\t\t// which will be available to containerized kubelet. If still it does not exist,\n\t\t// AttachFileDevice will fail. If kubelet is not containerized, eval it anyway.\n\t\tkvh, ok := og.GetVolumePluginMgr().Host.(volume.KubeletVolumeHost)\n\t\tif !ok {\n\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MapVolume type assertion error\", fmt.Errorf(\"volume host does not implement KubeletVolumeHost interface\"))\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\t\thu := kvh.GetHostUtil()\n\t\tdevicePath, err = hu.EvalHostSymlinks(devicePath)\n\t\tif err != nil {\n\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MapVolume.EvalHostSymlinks failed\", err)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\t// Update actual state of world with the devicePath again, if devicePath has changed from markedDevicePath\n\t\t// TODO: This can be improved after #82492 is merged and ASW has state.\n\t\tif markedDevicePath != devicePath {\n\t\t\tmarkDeviceMappedErr := actualStateOfWorld.MarkDeviceAsMounted(\n\t\t\t\tvolumeToMount.VolumeName, devicePath, globalMapPath, \"\")\n\t\t\tif markDeviceMappedErr != nil {\n\t\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MapVolume.MarkDeviceAsMounted failed\", markDeviceMappedErr)\n\t\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t\t}\n\t\t}\n\n\t\t// Execute common map\n\t\tvolumeMapPath, volName := blockVolumeMapper.GetPodDeviceMapPath()\n\t\tmapErr := util.MapBlockVolume(og.blkUtil, devicePath, globalMapPath, volumeMapPath, volName, volumeToMount.Pod.UID)\n\t\tif mapErr != nil {\n\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MapVolume.MapBlockVolume failed\", mapErr)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\t// Device mapping for global map path succeeded\n\t\tsimpleMsg, detailedMsg := volumeToMount.GenerateMsg(\"MapVolume.MapPodDevice succeeded\", fmt.Sprintf(\"globalMapPath %q\", globalMapPath))\n\t\tverbosity := klog.Level(4)\n\t\tog.recorder.Eventf(volumeToMount.Pod, v1.EventTypeNormal, kevents.SuccessfulMountVolume, simpleMsg)\n\t\tklog.V(verbosity).InfoS(detailedMsg, \"pod\", klog.KObj(volumeToMount.Pod))\n\n\t\t// Device mapping for pod device map path succeeded\n\t\tsimpleMsg, detailedMsg = volumeToMount.GenerateMsg(\"MapVolume.MapPodDevice succeeded\", fmt.Sprintf(\"volumeMapPath %q\", volumeMapPath))\n\t\tverbosity = klog.Level(1)\n\t\tog.recorder.Eventf(volumeToMount.Pod, v1.EventTypeNormal, kevents.SuccessfulMountVolume, simpleMsg)\n\t\tklog.V(verbosity).InfoS(detailedMsg, \"pod\", klog.KObj(volumeToMount.Pod))\n\n\t\tresizeOptions := volume.NodeResizeOptions{\n\t\t\tDevicePath: devicePath,\n\t\t\tDeviceStagePath: stagingPath,\n\t\t}\n\t\t_, resizeError := og.expandVolumeDuringMount(volumeToMount, actualStateOfWorld, resizeOptions)\n\t\tif resizeError != nil {\n\t\t\tklog.Errorf(\"MapVolume.NodeExpandVolume failed with %v\", resizeError)\n\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MapVolume.MarkVolumeAsMounted failed while expanding volume\", resizeError)\n\t\t\t// At this point, MountVolume.Setup already succeeded, we should add volume into actual state\n\t\t\t// so that reconciler can clean up volume when needed. However, if nodeExpandVolume failed,\n\t\t\t// we should not mark the volume as mounted to avoid pod starts using it.\n\t\t\t// Considering the above situations, we mark volume as uncertain here so that reconciler will trigger\n\t\t\t// volume tear down when pod is deleted, and also makes sure pod will not start using it.\n\t\t\tif err := actualStateOfWorld.MarkVolumeMountAsUncertain(markVolumeOpts); err != nil {\n\t\t\t\tklog.Errorf(volumeToMount.GenerateErrorDetailed(\"MountVolume.MarkVolumeMountAsUncertain failed\", err).Error())\n\t\t\t}\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\tmarkVolMountedErr := actualStateOfWorld.MarkVolumeAsMounted(markVolumeOpts)\n\t\tif markVolMountedErr != nil {\n\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"MapVolume.MarkVolumeAsMounted failed\", markVolMountedErr)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\treturn volumetypes.NewOperationContext(nil, nil, migrated)\n\t}\n\n\teventRecorderFunc := func(err *error) {\n\t\tif *err != nil {\n\t\t\tog.recorder.Eventf(volumeToMount.Pod, v1.EventTypeWarning, kevents.FailedMapVolume, (*err).Error())\n\t\t}\n\t}\n\n\treturn volumetypes.GeneratedOperations{\n\t\tOperationName: \"map_volume\",\n\t\tOperationFunc: mapVolumeFunc,\n\t\tEventRecorderFunc: eventRecorderFunc,\n\t\tCompleteFunc: util.OperationCompleteHook(util.GetFullQualifiedPluginNameForVolume(blockVolumePlugin.GetPluginName(), volumeToMount.VolumeSpec), \"map_volume\"),\n\t}, nil\n}","line":{"from":1014,"to":1258}} {"id":100013076,"name":"GenerateUnmapVolumeFunc","signature":"func (og *operationGenerator) GenerateUnmapVolumeFunc(","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"// GenerateUnmapVolumeFunc marks volume as unmonuted based on following steps.\n// Remove symbolic links from pod device map path dir and global map path dir.\n// Once those cleanups are done, remove pod device map path dir.\n// If all steps are completed, the volume is marked as unmounted.\nfunc (og *operationGenerator) GenerateUnmapVolumeFunc(\n\tvolumeToUnmount MountedVolume,\n\tactualStateOfWorld ActualStateOfWorldMounterUpdater) (volumetypes.GeneratedOperations, error) {\n\n\t// Get block volume unmapper plugin\n\tblockVolumePlugin, err :=\n\t\tog.volumePluginMgr.FindMapperPluginByName(volumeToUnmount.PluginName)\n\tif err != nil {\n\t\treturn volumetypes.GeneratedOperations{}, volumeToUnmount.GenerateErrorDetailed(\"UnmapVolume.FindMapperPluginByName failed\", err)\n\t}\n\tif blockVolumePlugin == nil {\n\t\treturn volumetypes.GeneratedOperations{}, volumeToUnmount.GenerateErrorDetailed(\"UnmapVolume.FindMapperPluginByName failed to find BlockVolumeMapper plugin. Volume plugin is nil.\", nil)\n\t}\n\tblockVolumeUnmapper, newUnmapperErr := blockVolumePlugin.NewBlockVolumeUnmapper(\n\t\tvolumeToUnmount.InnerVolumeSpecName, volumeToUnmount.PodUID)\n\tif newUnmapperErr != nil {\n\t\treturn volumetypes.GeneratedOperations{}, volumeToUnmount.GenerateErrorDetailed(\"UnmapVolume.NewUnmapper failed\", newUnmapperErr)\n\t}\n\n\tunmapVolumeFunc := func() volumetypes.OperationContext {\n\n\t\tmigrated := getMigratedStatusBySpec(volumeToUnmount.VolumeSpec)\n\n\t\t// pods/{podUid}/volumeDevices/{escapeQualifiedPluginName}/{volumeName}\n\t\tpodDeviceUnmapPath, volName := blockVolumeUnmapper.GetPodDeviceMapPath()\n\t\t// plugins/kubernetes.io/{PluginName}/volumeDevices/{volumePluginDependentPath}/{podUID}\n\t\tglobalUnmapPath := volumeToUnmount.DeviceMountPath\n\n\t\t// Mark the device as uncertain to make sure kubelet calls UnmapDevice again in all the \"return err\"\n\t\t// cases below. The volume is marked as fully un-mapped at the end of this function, when everything\n\t\t// succeeds.\n\t\tmarkVolumeOpts := MarkVolumeOpts{\n\t\t\tPodName: volumeToUnmount.PodName,\n\t\t\tPodUID: volumeToUnmount.PodUID,\n\t\t\tVolumeName: volumeToUnmount.VolumeName,\n\t\t\tOuterVolumeSpecName: volumeToUnmount.OuterVolumeSpecName,\n\t\t\tVolumeGidVolume: volumeToUnmount.VolumeGidValue,\n\t\t\tVolumeSpec: volumeToUnmount.VolumeSpec,\n\t\t\tVolumeMountState: VolumeMountUncertain,\n\t\t}\n\t\tmarkVolumeUncertainErr := actualStateOfWorld.MarkVolumeMountAsUncertain(markVolumeOpts)\n\t\tif markVolumeUncertainErr != nil {\n\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\teventErr, detailedErr := volumeToUnmount.GenerateError(\"UnmapVolume.MarkDeviceAsUncertain failed\", markVolumeUncertainErr)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\t// Execute common unmap\n\t\tunmapErr := util.UnmapBlockVolume(og.blkUtil, globalUnmapPath, podDeviceUnmapPath, volName, volumeToUnmount.PodUID)\n\t\tif unmapErr != nil {\n\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\teventErr, detailedErr := volumeToUnmount.GenerateError(\"UnmapVolume.UnmapBlockVolume failed\", unmapErr)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\t// Call UnmapPodDevice if blockVolumeUnmapper implements CustomBlockVolumeUnmapper\n\t\tif customBlockVolumeUnmapper, ok := blockVolumeUnmapper.(volume.CustomBlockVolumeUnmapper); ok {\n\t\t\t// Execute plugin specific unmap\n\t\t\tunmapErr = customBlockVolumeUnmapper.UnmapPodDevice()\n\t\t\tif unmapErr != nil {\n\t\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\t\teventErr, detailedErr := volumeToUnmount.GenerateError(\"UnmapVolume.UnmapPodDevice failed\", unmapErr)\n\t\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t\t}\n\t\t}\n\n\t\tklog.Infof(\n\t\t\t\"UnmapVolume succeeded for volume %q (OuterVolumeSpecName: %q) pod %q (UID: %q). InnerVolumeSpecName %q. PluginName %q, VolumeGidValue %q\",\n\t\t\tvolumeToUnmount.VolumeName,\n\t\t\tvolumeToUnmount.OuterVolumeSpecName,\n\t\t\tvolumeToUnmount.PodName,\n\t\t\tvolumeToUnmount.PodUID,\n\t\t\tvolumeToUnmount.InnerVolumeSpecName,\n\t\t\tvolumeToUnmount.PluginName,\n\t\t\tvolumeToUnmount.VolumeGidValue)\n\n\t\t// Update actual state of world\n\t\tmarkVolUnmountedErr := actualStateOfWorld.MarkVolumeAsUnmounted(\n\t\t\tvolumeToUnmount.PodName, volumeToUnmount.VolumeName)\n\t\tif markVolUnmountedErr != nil {\n\t\t\t// On failure, just log and exit\n\t\t\tklog.Errorf(volumeToUnmount.GenerateErrorDetailed(\"UnmapVolume.MarkVolumeAsUnmounted failed\", markVolUnmountedErr).Error())\n\t\t}\n\n\t\treturn volumetypes.NewOperationContext(nil, nil, migrated)\n\t}\n\n\treturn volumetypes.GeneratedOperations{\n\t\tOperationName: \"unmap_volume\",\n\t\tOperationFunc: unmapVolumeFunc,\n\t\tCompleteFunc: util.OperationCompleteHook(util.GetFullQualifiedPluginNameForVolume(blockVolumePlugin.GetPluginName(), volumeToUnmount.VolumeSpec), \"unmap_volume\"),\n\t\tEventRecorderFunc: nil, // nil because we do not want to generate event on error\n\t}, nil\n}","line":{"from":1260,"to":1357}} {"id":100013077,"name":"GenerateUnmapDeviceFunc","signature":"func (og *operationGenerator) GenerateUnmapDeviceFunc(","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"// GenerateUnmapDeviceFunc marks device as unmounted based on following steps.\n// Check under globalMapPath dir if there isn't pod's symbolic links in it.\n// If symbolic link isn't there, the device isn't referenced from Pods.\n// Call plugin TearDownDevice to clean-up device connection, stored data under\n// globalMapPath, these operations depend on plugin implementation.\n// Once TearDownDevice is completed, remove globalMapPath dir.\n// After globalMapPath is removed, fd lock by loopback for the device can\n// be released safely because no one can consume the device at this point.\n// At last, device open status will be checked just in case.\n// If all steps are completed, the device is marked as unmounted.\nfunc (og *operationGenerator) GenerateUnmapDeviceFunc(\n\tdeviceToDetach AttachedVolume,\n\tactualStateOfWorld ActualStateOfWorldMounterUpdater,\n\thostutil hostutil.HostUtils) (volumetypes.GeneratedOperations, error) {\n\n\tblockVolumePlugin, err :=\n\t\tog.volumePluginMgr.FindMapperPluginByName(deviceToDetach.PluginName)\n\tif err != nil {\n\t\treturn volumetypes.GeneratedOperations{}, deviceToDetach.GenerateErrorDetailed(\"UnmapDevice.FindMapperPluginByName failed\", err)\n\t}\n\n\tif blockVolumePlugin == nil {\n\t\treturn volumetypes.GeneratedOperations{}, deviceToDetach.GenerateErrorDetailed(\"UnmapDevice.FindMapperPluginByName failed to find BlockVolumeMapper plugin. Volume plugin is nil.\", nil)\n\t}\n\n\tblockVolumeUnmapper, newUnmapperErr := blockVolumePlugin.NewBlockVolumeUnmapper(\n\t\tdeviceToDetach.VolumeSpec.Name(),\n\t\t\"\" /* podUID */)\n\tif newUnmapperErr != nil {\n\t\treturn volumetypes.GeneratedOperations{}, deviceToDetach.GenerateErrorDetailed(\"UnmapDevice.NewUnmapper failed\", newUnmapperErr)\n\t}\n\n\tunmapDeviceFunc := func() volumetypes.OperationContext {\n\t\tmigrated := getMigratedStatusBySpec(deviceToDetach.VolumeSpec)\n\t\t// Search under globalMapPath dir if all symbolic links from pods have been removed already.\n\t\t// If symbolic links are there, pods may still refer the volume.\n\t\tglobalMapPath := deviceToDetach.DeviceMountPath\n\t\trefs, err := og.blkUtil.GetDeviceBindMountRefs(deviceToDetach.DevicePath, globalMapPath)\n\t\tif err != nil {\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\t// Looks like SetupDevice did not complete. Fall through to TearDownDevice and mark the device as unmounted.\n\t\t\t\trefs = nil\n\t\t\t} else {\n\t\t\t\teventErr, detailedErr := deviceToDetach.GenerateError(\"UnmapDevice.GetDeviceBindMountRefs check failed\", err)\n\t\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t\t}\n\t\t}\n\t\tif len(refs) \u003e 0 {\n\t\t\terr = fmt.Errorf(\"the device %q is still referenced from other Pods %v\", globalMapPath, refs)\n\t\t\teventErr, detailedErr := deviceToDetach.GenerateError(\"UnmapDevice failed\", err)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\t// Mark the device as uncertain to make sure kubelet calls UnmapDevice again in all the \"return err\"\n\t\t// cases below. The volume is marked as fully un-mapped at the end of this function, when everything\n\t\t// succeeds.\n\t\tmarkDeviceUncertainErr := actualStateOfWorld.MarkDeviceAsUncertain(\n\t\t\tdeviceToDetach.VolumeName, deviceToDetach.DevicePath, globalMapPath, \"\" /* seLinuxMountContext */)\n\t\tif markDeviceUncertainErr != nil {\n\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\teventErr, detailedErr := deviceToDetach.GenerateError(\"UnmapDevice.MarkDeviceAsUncertain failed\", markDeviceUncertainErr)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\t// Call TearDownDevice if blockVolumeUnmapper implements CustomBlockVolumeUnmapper\n\t\tif customBlockVolumeUnmapper, ok := blockVolumeUnmapper.(volume.CustomBlockVolumeUnmapper); ok {\n\t\t\t// Execute tear down device\n\t\t\tunmapErr := customBlockVolumeUnmapper.TearDownDevice(globalMapPath, deviceToDetach.DevicePath)\n\t\t\tif unmapErr != nil {\n\t\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\t\teventErr, detailedErr := deviceToDetach.GenerateError(\"UnmapDevice.TearDownDevice failed\", unmapErr)\n\t\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t\t}\n\t\t}\n\n\t\t// Plugin finished TearDownDevice(). Now globalMapPath dir and plugin's stored data\n\t\t// on the dir are unnecessary, clean up it.\n\t\tremoveMapPathErr := og.blkUtil.RemoveMapPath(globalMapPath)\n\t\tif removeMapPathErr != nil {\n\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\teventErr, detailedErr := deviceToDetach.GenerateError(\"UnmapDevice.RemoveMapPath failed\", removeMapPathErr)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\t// Before logging that UnmapDevice succeeded and moving on,\n\t\t// use hostutil.PathIsDevice to check if the path is a device,\n\t\t// if so use hostutil.DeviceOpened to check if the device is in use anywhere\n\t\t// else on the system. Retry if it returns true.\n\t\tdeviceOpened, deviceOpenedErr := isDeviceOpened(deviceToDetach, hostutil)\n\t\tif deviceOpenedErr != nil {\n\t\t\treturn volumetypes.NewOperationContext(nil, deviceOpenedErr, migrated)\n\t\t}\n\t\t// The device is still in use elsewhere. Caller will log and retry.\n\t\tif deviceOpened {\n\t\t\teventErr, detailedErr := deviceToDetach.GenerateError(\n\t\t\t\t\"UnmapDevice failed\",\n\t\t\t\tfmt.Errorf(\"the device is in use when it was no longer expected to be in use\"))\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\tklog.Infof(deviceToDetach.GenerateMsgDetailed(\"UnmapDevice succeeded\", \"\"))\n\n\t\t// Update actual state of world\n\t\tmarkDeviceUnmountedErr := actualStateOfWorld.MarkDeviceAsUnmounted(\n\t\t\tdeviceToDetach.VolumeName)\n\t\tif markDeviceUnmountedErr != nil {\n\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\teventErr, detailedErr := deviceToDetach.GenerateError(\"MarkDeviceAsUnmounted failed\", markDeviceUnmountedErr)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\treturn volumetypes.NewOperationContext(nil, nil, migrated)\n\t}\n\n\treturn volumetypes.GeneratedOperations{\n\t\tOperationName: \"unmap_device\",\n\t\tOperationFunc: unmapDeviceFunc,\n\t\tCompleteFunc: util.OperationCompleteHook(util.GetFullQualifiedPluginNameForVolume(blockVolumePlugin.GetPluginName(), deviceToDetach.VolumeSpec), \"unmap_device\"),\n\t\tEventRecorderFunc: nil, // nil because we do not want to generate event on error\n\t}, nil\n}","line":{"from":1359,"to":1479}} {"id":100013078,"name":"GenerateVerifyControllerAttachedVolumeFunc","signature":"func (og *operationGenerator) GenerateVerifyControllerAttachedVolumeFunc(","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) GenerateVerifyControllerAttachedVolumeFunc(\n\tlogger klog.Logger,\n\tvolumeToMount VolumeToMount,\n\tnodeName types.NodeName,\n\tactualStateOfWorld ActualStateOfWorldAttacherUpdater) (volumetypes.GeneratedOperations, error) {\n\tvolumePlugin, err :=\n\t\tog.volumePluginMgr.FindPluginBySpec(volumeToMount.VolumeSpec)\n\tif err != nil || volumePlugin == nil {\n\t\treturn volumetypes.GeneratedOperations{}, volumeToMount.GenerateErrorDetailed(\"VerifyControllerAttachedVolume.FindPluginBySpec failed\", err)\n\t}\n\n\t// For attachable volume types, lets check if volume is attached by reading from node lister.\n\t// This would avoid exponential back-off and creation of goroutine unnecessarily. We still\n\t// verify status of attached volume by directly reading from API server later on.This is necessarily\n\t// to ensure any race conditions because of cached state in the informer.\n\tif volumeToMount.PluginIsAttachable {\n\t\tcachedAttachedVolumes, _ := og.volumePluginMgr.Host.GetAttachedVolumesFromNodeStatus()\n\t\tif cachedAttachedVolumes != nil {\n\t\t\t_, volumeFound := cachedAttachedVolumes[volumeToMount.VolumeName]\n\t\t\tif !volumeFound {\n\t\t\t\treturn volumetypes.GeneratedOperations{}, NewMountPreConditionFailedError(fmt.Sprintf(\"volume %s is not yet in node's status\", volumeToMount.VolumeName))\n\t\t\t}\n\t\t}\n\t}\n\n\tverifyControllerAttachedVolumeFunc := func() volumetypes.OperationContext {\n\t\tmigrated := getMigratedStatusBySpec(volumeToMount.VolumeSpec)\n\t\tclaimSize := actualStateOfWorld.GetClaimSize(volumeToMount.VolumeName)\n\n\t\t// only fetch claimSize if it was not set previously\n\t\tif volumeToMount.VolumeSpec.PersistentVolume != nil \u0026\u0026 claimSize == nil \u0026\u0026 !volumeToMount.VolumeSpec.InlineVolumeSpecForCSIMigration {\n\t\t\tpv := volumeToMount.VolumeSpec.PersistentVolume\n\t\t\tpvc, err := og.kubeClient.CoreV1().PersistentVolumeClaims(pv.Spec.ClaimRef.Namespace).Get(context.TODO(), pv.Spec.ClaimRef.Name, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"VerifyControllerAttachedVolume fetching pvc failed\", err)\n\t\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t\t}\n\t\t\tpvcStatusSize := pvc.Status.Capacity.Storage()\n\t\t\tif pvcStatusSize != nil {\n\t\t\t\tclaimSize = pvcStatusSize\n\t\t\t}\n\t\t}\n\n\t\tif !volumeToMount.PluginIsAttachable {\n\t\t\t// If the volume does not implement the attacher interface, it is\n\t\t\t// assumed to be attached and the actual state of the world is\n\t\t\t// updated accordingly.\n\n\t\t\taddVolumeNodeErr := actualStateOfWorld.MarkVolumeAsAttached(\n\t\t\t\tlogger, volumeToMount.VolumeName, volumeToMount.VolumeSpec, nodeName, \"\" /* devicePath */)\n\t\t\tif addVolumeNodeErr != nil {\n\t\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"VerifyControllerAttachedVolume.MarkVolumeAsAttachedByUniqueVolumeName failed\", addVolumeNodeErr)\n\t\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t\t}\n\t\t\tactualStateOfWorld.InitializeClaimSize(logger, volumeToMount.VolumeName, claimSize)\n\t\t\treturn volumetypes.NewOperationContext(nil, nil, migrated)\n\t\t}\n\n\t\tif !volumeToMount.ReportedInUse {\n\t\t\t// If the given volume has not yet been added to the list of\n\t\t\t// VolumesInUse in the node's volume status, do not proceed, return\n\t\t\t// error. Caller will log and retry. The node status is updated\n\t\t\t// periodically by kubelet, so it may take as much as 10 seconds\n\t\t\t// before this clears.\n\t\t\t// Issue #28141 to enable on demand status updates.\n\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"Volume has not been added to the list of VolumesInUse in the node's volume status\", nil)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\t// Fetch current node object\n\t\tnode, fetchErr := og.kubeClient.CoreV1().Nodes().Get(context.TODO(), string(nodeName), metav1.GetOptions{})\n\t\tif fetchErr != nil {\n\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"VerifyControllerAttachedVolume failed fetching node from API server\", fetchErr)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\tif node == nil {\n\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\n\t\t\t\t\"VerifyControllerAttachedVolume failed\",\n\t\t\t\tfmt.Errorf(\"node object retrieved from API server is nil\"))\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\tfor _, attachedVolume := range node.Status.VolumesAttached {\n\t\t\tif attachedVolume.Name == volumeToMount.VolumeName {\n\t\t\t\taddVolumeNodeErr := actualStateOfWorld.MarkVolumeAsAttached(\n\t\t\t\t\tlogger, v1.UniqueVolumeName(\"\"), volumeToMount.VolumeSpec, nodeName, attachedVolume.DevicePath)\n\t\t\t\tklog.InfoS(volumeToMount.GenerateMsgDetailed(\"Controller attach succeeded\", fmt.Sprintf(\"device path: %q\", attachedVolume.DevicePath)), \"pod\", klog.KObj(volumeToMount.Pod))\n\t\t\t\tif addVolumeNodeErr != nil {\n\t\t\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\t\t\teventErr, detailedErr := volumeToMount.GenerateError(\"VerifyControllerAttachedVolume.MarkVolumeAsAttached failed\", addVolumeNodeErr)\n\t\t\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t\t\t}\n\t\t\t\tactualStateOfWorld.InitializeClaimSize(logger, volumeToMount.VolumeName, claimSize)\n\t\t\t\treturn volumetypes.NewOperationContext(nil, nil, migrated)\n\t\t\t}\n\t\t}\n\n\t\t// Volume not attached, return error. Caller will log and retry.\n\t\teventErr, detailedErr := volumeToMount.GenerateError(\"Volume not attached according to node status\", nil)\n\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t}\n\n\treturn volumetypes.GeneratedOperations{\n\t\tOperationName: VerifyControllerAttachedVolumeOpName,\n\t\tOperationFunc: verifyControllerAttachedVolumeFunc,\n\t\tCompleteFunc: util.OperationCompleteHook(util.GetFullQualifiedPluginNameForVolume(volumePlugin.GetPluginName(), volumeToMount.VolumeSpec), \"verify_controller_attached_volume\"),\n\t\tEventRecorderFunc: nil, // nil because we do not want to generate event on error\n\t}, nil\n\n}","line":{"from":1481,"to":1594}} {"id":100013079,"name":"verifyVolumeIsSafeToDetach","signature":"func (og *operationGenerator) verifyVolumeIsSafeToDetach(","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) verifyVolumeIsSafeToDetach(\n\tvolumeToDetach AttachedVolume) error {\n\t// Fetch current node object\n\tnode, fetchErr := og.kubeClient.CoreV1().Nodes().Get(context.TODO(), string(volumeToDetach.NodeName), metav1.GetOptions{})\n\tif fetchErr != nil {\n\t\tif errors.IsNotFound(fetchErr) {\n\t\t\tklog.Warningf(volumeToDetach.GenerateMsgDetailed(\"Node not found on API server. DetachVolume will skip safe to detach check\", \"\"))\n\t\t\treturn nil\n\t\t}\n\n\t\t// On failure, return error. Caller will log and retry.\n\t\treturn volumeToDetach.GenerateErrorDetailed(\"DetachVolume failed fetching node from API server\", fetchErr)\n\t}\n\n\tif node == nil {\n\t\t// On failure, return error. Caller will log and retry.\n\t\treturn volumeToDetach.GenerateErrorDetailed(\n\t\t\t\"DetachVolume failed fetching node from API server\",\n\t\t\tfmt.Errorf(\"node object retrieved from API server is nil\"))\n\t}\n\n\tfor _, inUseVolume := range node.Status.VolumesInUse {\n\t\tif inUseVolume == volumeToDetach.VolumeName {\n\t\t\treturn volumeToDetach.GenerateErrorDetailed(\n\t\t\t\t\"DetachVolume failed\",\n\t\t\t\tfmt.Errorf(\"volume is still in use by node, according to Node status\"))\n\t\t}\n\t}\n\n\t// Volume is not marked as in use by node\n\tklog.Infof(volumeToDetach.GenerateMsgDetailed(\"Verified volume is safe to detach\", \"\"))\n\treturn nil\n}","line":{"from":1596,"to":1628}} {"id":100013080,"name":"GenerateExpandVolumeFunc","signature":"func (og *operationGenerator) GenerateExpandVolumeFunc(","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) GenerateExpandVolumeFunc(\n\tpvc *v1.PersistentVolumeClaim,\n\tpv *v1.PersistentVolume) (volumetypes.GeneratedOperations, error) {\n\n\tvolumeSpec := volume.NewSpecFromPersistentVolume(pv, false)\n\n\tvolumePlugin, err := og.volumePluginMgr.FindExpandablePluginBySpec(volumeSpec)\n\tif err != nil {\n\t\treturn volumetypes.GeneratedOperations{}, fmt.Errorf(\"error finding plugin for expanding volume: %q with error %v\", util.GetPersistentVolumeClaimQualifiedName(pvc), err)\n\t}\n\n\tif volumePlugin == nil {\n\t\treturn volumetypes.GeneratedOperations{}, fmt.Errorf(\"can not find plugin for expanding volume: %q\", util.GetPersistentVolumeClaimQualifiedName(pvc))\n\t}\n\n\texpandVolumeFunc := func() volumetypes.OperationContext {\n\t\tmigrated := false\n\n\t\tnewSize := pvc.Spec.Resources.Requests[v1.ResourceStorage]\n\t\tstatusSize := pvc.Status.Capacity[v1.ResourceStorage]\n\t\tpvSize := pv.Spec.Capacity[v1.ResourceStorage]\n\t\tif pvSize.Cmp(newSize) \u003c 0 {\n\t\t\tupdatedSize, expandErr := volumePlugin.ExpandVolumeDevice(\n\t\t\t\tvolumeSpec,\n\t\t\t\tnewSize,\n\t\t\t\tstatusSize)\n\t\t\tif expandErr != nil {\n\t\t\t\tdetailedErr := fmt.Errorf(\"error expanding volume %q of plugin %q: %v\", util.GetPersistentVolumeClaimQualifiedName(pvc), volumePlugin.GetPluginName(), expandErr)\n\t\t\t\treturn volumetypes.NewOperationContext(detailedErr, detailedErr, migrated)\n\t\t\t}\n\n\t\t\tklog.Infof(\"ExpandVolume succeeded for volume %s\", util.GetPersistentVolumeClaimQualifiedName(pvc))\n\n\t\t\tnewSize = updatedSize\n\t\t\t// k8s doesn't have transactions, we can't guarantee that after updating PV - updating PVC will be\n\t\t\t// successful, that is why all PVCs for which pvc.Spec.Size \u003e pvc.Status.Size must be reprocessed\n\t\t\t// until they reflect user requested size in pvc.Status.Size\n\t\t\t_, updateErr := util.UpdatePVSize(pv, newSize, og.kubeClient)\n\t\t\tif updateErr != nil {\n\t\t\t\tdetailedErr := fmt.Errorf(\"error updating PV spec capacity for volume %q with : %v\", util.GetPersistentVolumeClaimQualifiedName(pvc), updateErr)\n\t\t\t\treturn volumetypes.NewOperationContext(detailedErr, detailedErr, migrated)\n\t\t\t}\n\n\t\t\tklog.Infof(\"ExpandVolume.UpdatePV succeeded for volume %s\", util.GetPersistentVolumeClaimQualifiedName(pvc))\n\t\t}\n\n\t\tfsVolume, _ := util.CheckVolumeModeFilesystem(volumeSpec)\n\t\t// No Cloudprovider resize needed, lets mark resizing as done\n\t\t// Rest of the volume expand controller code will assume PVC as *not* resized until pvc.Status.Size\n\t\t// reflects user requested size.\n\t\tif !volumePlugin.RequiresFSResize() || !fsVolume {\n\t\t\tklog.V(4).Infof(\"Controller resizing done for PVC %s\", util.GetPersistentVolumeClaimQualifiedName(pvc))\n\t\t\t_, err := util.MarkResizeFinished(pvc, newSize, og.kubeClient)\n\t\t\tif err != nil {\n\t\t\t\tdetailedErr := fmt.Errorf(\"error marking pvc %s as resized : %v\", util.GetPersistentVolumeClaimQualifiedName(pvc), err)\n\t\t\t\treturn volumetypes.NewOperationContext(detailedErr, detailedErr, migrated)\n\t\t\t}\n\t\t\tsuccessMsg := fmt.Sprintf(\"ExpandVolume succeeded for volume %s\", util.GetPersistentVolumeClaimQualifiedName(pvc))\n\t\t\tog.recorder.Eventf(pvc, v1.EventTypeNormal, kevents.VolumeResizeSuccess, successMsg)\n\t\t} else {\n\t\t\t_, err := util.MarkForFSResize(pvc, og.kubeClient)\n\t\t\tif err != nil {\n\t\t\t\tdetailedErr := fmt.Errorf(\"error updating pvc %s condition for fs resize : %v\", util.GetPersistentVolumeClaimQualifiedName(pvc), err)\n\t\t\t\tklog.Warning(detailedErr)\n\t\t\t\treturn volumetypes.NewOperationContext(nil, nil, migrated)\n\t\t\t}\n\t\t\toldCapacity := pvc.Status.Capacity[v1.ResourceStorage]\n\t\t\terr = util.AddAnnPreResizeCapacity(pv, oldCapacity, og.kubeClient)\n\t\t\tif err != nil {\n\t\t\t\tdetailedErr := fmt.Errorf(\"error updating pv %s annotation (%s) with pre-resize capacity %s: %v\", pv.ObjectMeta.Name, util.AnnPreResizeCapacity, oldCapacity.String(), err)\n\t\t\t\tklog.Warning(detailedErr)\n\t\t\t\treturn volumetypes.NewOperationContext(nil, nil, migrated)\n\t\t\t}\n\n\t\t}\n\t\treturn volumetypes.NewOperationContext(nil, nil, migrated)\n\t}\n\n\teventRecorderFunc := func(err *error) {\n\t\tif *err != nil {\n\t\t\tog.recorder.Eventf(pvc, v1.EventTypeWarning, kevents.VolumeResizeFailed, (*err).Error())\n\t\t}\n\t}\n\n\treturn volumetypes.GeneratedOperations{\n\t\tOperationName: \"expand_volume\",\n\t\tOperationFunc: expandVolumeFunc,\n\t\tEventRecorderFunc: eventRecorderFunc,\n\t\tCompleteFunc: util.OperationCompleteHook(util.GetFullQualifiedPluginNameForVolume(volumePlugin.GetPluginName(), volumeSpec), \"expand_volume\"),\n\t}, nil\n}","line":{"from":1630,"to":1720}} {"id":100013081,"name":"GenerateExpandAndRecoverVolumeFunc","signature":"func (og *operationGenerator) GenerateExpandAndRecoverVolumeFunc(","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) GenerateExpandAndRecoverVolumeFunc(\n\tpvc *v1.PersistentVolumeClaim,\n\tpv *v1.PersistentVolume, resizerName string) (volumetypes.GeneratedOperations, error) {\n\n\tvolumeSpec := volume.NewSpecFromPersistentVolume(pv, false)\n\n\tvolumePlugin, err := og.volumePluginMgr.FindExpandablePluginBySpec(volumeSpec)\n\tif err != nil {\n\t\treturn volumetypes.GeneratedOperations{}, fmt.Errorf(\"error finding plugin for expanding volume: %q with error %v\", util.GetPersistentVolumeClaimQualifiedName(pvc), err)\n\t}\n\n\tif volumePlugin == nil {\n\t\treturn volumetypes.GeneratedOperations{}, fmt.Errorf(\"can not find plugin for expanding volume: %q\", util.GetPersistentVolumeClaimQualifiedName(pvc))\n\t}\n\n\texpandVolumeFunc := func() volumetypes.OperationContext {\n\t\tresizeOpts := inTreeResizeOpts{\n\t\t\tpvc: pvc,\n\t\t\tpv: pv,\n\t\t\tresizerName: resizerName,\n\t\t\tvolumePlugin: volumePlugin,\n\t\t\tvolumeSpec: volumeSpec,\n\t\t}\n\t\tmigrated := false\n\t\tresp := og.expandAndRecoverFunction(resizeOpts)\n\t\tif resp.err != nil {\n\t\t\treturn volumetypes.NewOperationContext(resp.err, resp.err, migrated)\n\t\t}\n\t\treturn volumetypes.NewOperationContext(nil, nil, migrated)\n\t}\n\n\teventRecorderFunc := func(err *error) {\n\t\tif *err != nil {\n\t\t\tog.recorder.Eventf(pvc, v1.EventTypeWarning, kevents.VolumeResizeFailed, (*err).Error())\n\t\t}\n\t}\n\n\treturn volumetypes.GeneratedOperations{\n\t\tOperationName: \"expand_volume\",\n\t\tOperationFunc: expandVolumeFunc,\n\t\tEventRecorderFunc: eventRecorderFunc,\n\t\tCompleteFunc: util.OperationCompleteHook(util.GetFullQualifiedPluginNameForVolume(volumePlugin.GetPluginName(), volumeSpec), \"expand_volume\"),\n\t}, nil\n}","line":{"from":1722,"to":1765}} {"id":100013082,"name":"expandAndRecoverFunction","signature":"func (og *operationGenerator) expandAndRecoverFunction(resizeOpts inTreeResizeOpts) inTreeResizeResponse","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) expandAndRecoverFunction(resizeOpts inTreeResizeOpts) inTreeResizeResponse {\n\tpvc := resizeOpts.pvc\n\tpv := resizeOpts.pv\n\tresizerName := resizeOpts.resizerName\n\tvolumePlugin := resizeOpts.volumePlugin\n\tvolumeSpec := resizeOpts.volumeSpec\n\n\tpvcSpecSize := pvc.Spec.Resources.Requests[v1.ResourceStorage]\n\tpvcStatusSize := pvc.Status.Capacity[v1.ResourceStorage]\n\tpvSize := pv.Spec.Capacity[v1.ResourceStorage]\n\n\tresizeResponse := inTreeResizeResponse{\n\t\tpvc: pvc,\n\t\tpv: pv,\n\t\tresizeCalled: false,\n\t}\n\n\t// by default we are expanding to full-fill size requested in pvc.Spec.Resources\n\tnewSize := pvcSpecSize\n\tresizeStatus := v1.PersistentVolumeClaimNoExpansionInProgress\n\tif pvc.Status.ResizeStatus != nil {\n\t\tresizeStatus = *pvc.Status.ResizeStatus\n\t}\n\tvar allocatedSize *resource.Quantity\n\tt, ok := pvc.Status.AllocatedResources[v1.ResourceStorage]\n\tif ok {\n\t\tallocatedSize = \u0026t\n\t}\n\tvar err error\n\n\tif pvSize.Cmp(pvcSpecSize) \u003c 0 {\n\t\t// pv is not of requested size yet and hence will require expanding\n\n\t\tswitch resizeStatus {\n\t\tcase v1.PersistentVolumeClaimControllerExpansionInProgress:\n\t\tcase v1.PersistentVolumeClaimNodeExpansionPending:\n\t\tcase v1.PersistentVolumeClaimNodeExpansionInProgress:\n\t\tcase v1.PersistentVolumeClaimNodeExpansionFailed:\n\t\t\tif allocatedSize != nil {\n\t\t\t\tnewSize = *allocatedSize\n\t\t\t}\n\t\tdefault:\n\t\t\tnewSize = pvcSpecSize\n\t\t}\n\t} else {\n\t\t// PV has already been expanded and hence we can be here for following reasons:\n\t\t// 1. If expansion is pending on the node and this was just a spurious update event\n\t\t// we don't need to do anything and let kubelet handle it.\n\t\t// 2. It could be that - although we successfully expanded the volume, we failed to\n\t\t// record our work in API objects, in which case - we should resume resizing operation\n\t\t// and let API objects be updated.\n\t\t// 3. Controller successfully expanded the volume, but expansion is failing on the node\n\t\t// and before kubelet can retry failed node expansion - controller must verify if it is\n\t\t// safe to do so.\n\t\t// 4. While expansion was still pending on the node, user reduced the pvc size.\n\t\tswitch resizeStatus {\n\t\tcase v1.PersistentVolumeClaimNodeExpansionInProgress:\n\t\tcase v1.PersistentVolumeClaimNodeExpansionPending:\n\t\t\t// we don't need to do any work. We could be here because of a spurious update event.\n\t\t\t// This is case #1\n\t\t\treturn resizeResponse\n\t\tcase v1.PersistentVolumeClaimNodeExpansionFailed:\n\t\t\t// This is case#3\n\t\t\tpvc, err = og.markForPendingNodeExpansion(pvc, pv)\n\t\t\tresizeResponse.pvc = pvc\n\t\t\tresizeResponse.err = err\n\t\t\treturn resizeResponse\n\t\tcase v1.PersistentVolumeClaimControllerExpansionInProgress:\n\t\tcase v1.PersistentVolumeClaimControllerExpansionFailed:\n\t\tcase v1.PersistentVolumeClaimNoExpansionInProgress:\n\t\t\t// This is case#2 or it could also be case#4 when user manually shrunk the PVC\n\t\t\t// after expanding it.\n\t\t\tif allocatedSize != nil {\n\t\t\t\tnewSize = *allocatedSize\n\t\t\t}\n\t\tdefault:\n\t\t\t// It is impossible for ResizeStatus to be nil and allocatedSize to be not nil but somehow\n\t\t\t// if we do end up in this state, it is safest to resume expansion to last recorded size in\n\t\t\t// allocatedSize variable.\n\t\t\tif pvc.Status.ResizeStatus == nil \u0026\u0026 allocatedSize != nil {\n\t\t\t\tnewSize = *allocatedSize\n\t\t\t} else {\n\t\t\t\tnewSize = pvcSpecSize\n\t\t\t}\n\t\t}\n\t}\n\n\tpvc, err = util.MarkControllerReisizeInProgress(pvc, resizerName, newSize, og.kubeClient)\n\tif err != nil {\n\t\tmsg := fmt.Errorf(\"error updating pvc %s with resize in progress: %v\", util.GetPersistentVolumeClaimQualifiedName(pvc), err)\n\t\tresizeResponse.err = msg\n\t\tresizeResponse.pvc = pvc\n\t\treturn resizeResponse\n\t}\n\n\tupdatedSize, err := volumePlugin.ExpandVolumeDevice(volumeSpec, newSize, pvcStatusSize)\n\tresizeResponse.resizeCalled = true\n\n\tif err != nil {\n\t\tmsg := fmt.Errorf(\"error expanding pvc %s: %v\", util.GetPersistentVolumeClaimQualifiedName(pvc), err)\n\t\tresizeResponse.err = msg\n\t\tresizeResponse.pvc = pvc\n\t\treturn resizeResponse\n\t}\n\n\t// update PV size\n\tvar updateErr error\n\tpv, updateErr = util.UpdatePVSize(pv, updatedSize, og.kubeClient)\n\t// if updating PV failed, we are going to leave the PVC in ControllerExpansionInProgress state, so as expansion can be retried to previously set allocatedSize value.\n\tif updateErr != nil {\n\t\tmsg := fmt.Errorf(\"error updating pv for pvc %s: %v\", util.GetPersistentVolumeClaimQualifiedName(pvc), updateErr)\n\t\tresizeResponse.err = msg\n\t\treturn resizeResponse\n\t}\n\tresizeResponse.pv = pv\n\n\tfsVolume, _ := util.CheckVolumeModeFilesystem(volumeSpec)\n\n\tif !volumePlugin.RequiresFSResize() || !fsVolume {\n\t\tpvc, err = util.MarkResizeFinished(pvc, updatedSize, og.kubeClient)\n\t\tif err != nil {\n\t\t\tmsg := fmt.Errorf(\"error marking pvc %s as resized: %v\", util.GetPersistentVolumeClaimQualifiedName(pvc), err)\n\t\t\tresizeResponse.err = msg\n\t\t\treturn resizeResponse\n\t\t}\n\t\tresizeResponse.pvc = pvc\n\t\tsuccessMsg := fmt.Sprintf(\"ExpandVolume succeeded for volume %s\", util.GetPersistentVolumeClaimQualifiedName(pvc))\n\t\tog.recorder.Eventf(pvc, v1.EventTypeNormal, kevents.VolumeResizeSuccess, successMsg)\n\t} else {\n\t\tpvc, err = og.markForPendingNodeExpansion(pvc, pv)\n\t\tresizeResponse.pvc = pvc\n\t\tif err != nil {\n\t\t\tmsg := fmt.Errorf(\"error marking pvc %s for node expansion: %v\", util.GetPersistentVolumeClaimQualifiedName(pvc), err)\n\t\t\tresizeResponse.err = msg\n\t\t\treturn resizeResponse\n\t\t}\n\t}\n\treturn resizeResponse\n}","line":{"from":1767,"to":1905}} {"id":100013083,"name":"markForPendingNodeExpansion","signature":"func (og *operationGenerator) markForPendingNodeExpansion(pvc *v1.PersistentVolumeClaim, pv *v1.PersistentVolume) (*v1.PersistentVolumeClaim, error)","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) markForPendingNodeExpansion(pvc *v1.PersistentVolumeClaim, pv *v1.PersistentVolume) (*v1.PersistentVolumeClaim, error) {\n\tvar err error\n\tpvc, err = util.MarkForFSResize(pvc, og.kubeClient)\n\tif err != nil {\n\t\tmsg := fmt.Errorf(\"error marking pvc %s for node expansion: %v\", util.GetPersistentVolumeClaimQualifiedName(pvc), err)\n\t\treturn pvc, msg\n\t}\n\t// store old PVC capacity in pv, so as if PVC gets deleted while node expansion was pending\n\t// we can restore size of pvc from PV annotation and still perform expansion on the node\n\toldCapacity := pvc.Status.Capacity[v1.ResourceStorage]\n\terr = util.AddAnnPreResizeCapacity(pv, oldCapacity, og.kubeClient)\n\tif err != nil {\n\t\tdetailedErr := fmt.Errorf(\"error updating pv %s annotation (%s) with pre-resize capacity %s: %v\", pv.ObjectMeta.Name, util.AnnPreResizeCapacity, oldCapacity.String(), err)\n\t\tklog.Warning(detailedErr)\n\t\treturn pvc, detailedErr\n\t}\n\treturn pvc, nil\n}","line":{"from":1907,"to":1924}} {"id":100013084,"name":"GenerateExpandInUseVolumeFunc","signature":"func (og *operationGenerator) GenerateExpandInUseVolumeFunc(","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) GenerateExpandInUseVolumeFunc(\n\tvolumeToMount VolumeToMount,\n\tactualStateOfWorld ActualStateOfWorldMounterUpdater, currentSize resource.Quantity) (volumetypes.GeneratedOperations, error) {\n\n\tvolumePlugin, err :=\n\t\tog.volumePluginMgr.FindPluginBySpec(volumeToMount.VolumeSpec)\n\tif err != nil || volumePlugin == nil {\n\t\treturn volumetypes.GeneratedOperations{}, volumeToMount.GenerateErrorDetailed(\"NodeExpandVolume.FindPluginBySpec failed\", err)\n\t}\n\n\tfsResizeFunc := func() volumetypes.OperationContext {\n\t\tvar resizeDone bool\n\t\tvar eventErr, detailedErr error\n\t\tmigrated := false\n\n\t\tif currentSize.IsZero() || volumeToMount.PersistentVolumeSize.IsZero() {\n\t\t\terr := fmt.Errorf(\"current or new size of the volume is not set\")\n\t\t\teventErr, detailedErr = volumeToMount.GenerateError(\"NodeExpandvolume.expansion failed\", err)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\tresizeOptions := volume.NodeResizeOptions{\n\t\t\tVolumeSpec: volumeToMount.VolumeSpec,\n\t\t\tDevicePath: volumeToMount.DevicePath,\n\t\t\tOldSize: currentSize,\n\t\t\tNewSize: volumeToMount.PersistentVolumeSize,\n\t\t}\n\t\tfsVolume, err := util.CheckVolumeModeFilesystem(volumeToMount.VolumeSpec)\n\t\tif err != nil {\n\t\t\teventErr, detailedErr = volumeToMount.GenerateError(\"NodeExpandvolume.CheckVolumeModeFilesystem failed\", err)\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\n\t\tif fsVolume {\n\t\t\tvolumeMounter, newMounterErr := volumePlugin.NewMounter(\n\t\t\t\tvolumeToMount.VolumeSpec,\n\t\t\t\tvolumeToMount.Pod,\n\t\t\t\tvolume.VolumeOptions{})\n\t\t\tif newMounterErr != nil {\n\t\t\t\teventErr, detailedErr = volumeToMount.GenerateError(\"NodeExpandVolume.NewMounter initialization failed\", newMounterErr)\n\t\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t\t}\n\n\t\t\tresizeOptions.DeviceMountPath = volumeMounter.GetPath()\n\n\t\t\tdeviceMountableVolumePlugin, _ := og.volumePluginMgr.FindDeviceMountablePluginBySpec(volumeToMount.VolumeSpec)\n\t\t\tvar volumeDeviceMounter volume.DeviceMounter\n\t\t\tif deviceMountableVolumePlugin != nil {\n\t\t\t\tvolumeDeviceMounter, _ = deviceMountableVolumePlugin.NewDeviceMounter()\n\t\t\t}\n\n\t\t\tif volumeDeviceMounter != nil {\n\t\t\t\tdeviceStagePath, err := volumeDeviceMounter.GetDeviceMountPath(volumeToMount.VolumeSpec)\n\t\t\t\tif err != nil {\n\t\t\t\t\teventErr, detailedErr = volumeToMount.GenerateError(\"NodeExpandVolume.GetDeviceMountPath failed\", err)\n\t\t\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t\t\t}\n\t\t\t\tresizeOptions.DeviceStagePath = deviceStagePath\n\t\t\t}\n\t\t} else {\n\t\t\t// Get block volume mapper plugin\n\t\t\tblockVolumePlugin, err :=\n\t\t\t\tog.volumePluginMgr.FindMapperPluginBySpec(volumeToMount.VolumeSpec)\n\t\t\tif err != nil {\n\t\t\t\teventErr, detailedErr = volumeToMount.GenerateError(\"MapVolume.FindMapperPluginBySpec failed\", err)\n\t\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t\t}\n\n\t\t\tif blockVolumePlugin == nil {\n\t\t\t\teventErr, detailedErr = volumeToMount.GenerateError(\"MapVolume.FindMapperPluginBySpec failed to find BlockVolumeMapper plugin. Volume plugin is nil.\", nil)\n\t\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t\t}\n\n\t\t\tblockVolumeMapper, newMapperErr := blockVolumePlugin.NewBlockVolumeMapper(\n\t\t\t\tvolumeToMount.VolumeSpec,\n\t\t\t\tvolumeToMount.Pod,\n\t\t\t\tvolume.VolumeOptions{})\n\t\t\tif newMapperErr != nil {\n\t\t\t\teventErr, detailedErr = volumeToMount.GenerateError(\"MapVolume.NewBlockVolumeMapper initialization failed\", newMapperErr)\n\t\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t\t}\n\n\t\t\t// if plugin supports custom mappers lets add DeviceStagePath\n\t\t\tif customBlockVolumeMapper, ok := blockVolumeMapper.(volume.CustomBlockVolumeMapper); ok {\n\t\t\t\tresizeOptions.DeviceStagePath = customBlockVolumeMapper.GetStagingPath()\n\t\t\t}\n\t\t}\n\n\t\t// if we are doing online expansion then volume is already published\n\t\tresizeDone, eventErr, detailedErr = og.doOnlineExpansion(volumeToMount, actualStateOfWorld, resizeOptions)\n\t\tif eventErr != nil || detailedErr != nil {\n\t\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t\t}\n\t\tif resizeDone {\n\t\t\treturn volumetypes.NewOperationContext(nil, nil, migrated)\n\t\t}\n\t\t// This is a placeholder error - we should NEVER reach here.\n\t\terr = fmt.Errorf(\"volume resizing failed for unknown reason\")\n\t\teventErr, detailedErr = volumeToMount.GenerateError(\"NodeExpandVolume.NodeExpandVolume failed to resize volume\", err)\n\t\treturn volumetypes.NewOperationContext(eventErr, detailedErr, migrated)\n\t}\n\n\teventRecorderFunc := func(err *error) {\n\t\tif *err != nil {\n\t\t\tog.recorder.Eventf(volumeToMount.Pod, v1.EventTypeWarning, kevents.VolumeResizeFailed, (*err).Error())\n\t\t}\n\t}\n\n\treturn volumetypes.GeneratedOperations{\n\t\tOperationName: \"volume_fs_resize\",\n\t\tOperationFunc: fsResizeFunc,\n\t\tEventRecorderFunc: eventRecorderFunc,\n\t\tCompleteFunc: util.OperationCompleteHook(util.GetFullQualifiedPluginNameForVolume(volumePlugin.GetPluginName(), volumeToMount.VolumeSpec), \"volume_fs_resize\"),\n\t}, nil\n}","line":{"from":1926,"to":2040}} {"id":100013085,"name":"doOnlineExpansion","signature":"func (og *operationGenerator) doOnlineExpansion(volumeToMount VolumeToMount,","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) doOnlineExpansion(volumeToMount VolumeToMount,\n\tactualStateOfWorld ActualStateOfWorldMounterUpdater,\n\tresizeOptions volume.NodeResizeOptions) (bool, error, error) {\n\n\tresizeDone, err := og.nodeExpandVolume(volumeToMount, actualStateOfWorld, resizeOptions)\n\tif err != nil {\n\t\te1, e2 := volumeToMount.GenerateError(\"NodeExpandVolume.NodeExpandVolume failed\", err)\n\t\tklog.Errorf(e2.Error())\n\t\treturn false, e1, e2\n\t}\n\tif resizeDone {\n\t\tmarkingDone := actualStateOfWorld.MarkVolumeAsResized(volumeToMount.VolumeName, \u0026resizeOptions.NewSize)\n\t\tif !markingDone {\n\t\t\t// On failure, return error. Caller will log and retry.\n\t\t\tgenericFailureError := fmt.Errorf(\"unable to mark volume as resized\")\n\t\t\te1, e2 := volumeToMount.GenerateError(\"NodeExpandVolume.MarkVolumeAsResized failed\", genericFailureError)\n\t\t\treturn false, e1, e2\n\t\t}\n\t\treturn true, nil, nil\n\t}\n\treturn false, nil, nil\n}","line":{"from":2042,"to":2063}} {"id":100013086,"name":"expandVolumeDuringMount","signature":"func (og *operationGenerator) expandVolumeDuringMount(volumeToMount VolumeToMount, actualStateOfWorld ActualStateOfWorldMounterUpdater, rsOpts volume.NodeResizeOptions) (bool, error)","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) expandVolumeDuringMount(volumeToMount VolumeToMount, actualStateOfWorld ActualStateOfWorldMounterUpdater, rsOpts volume.NodeResizeOptions) (bool, error) {\n\tsupportsExpansion, expandablePlugin := og.checkIfSupportsNodeExpansion(volumeToMount)\n\tif supportsExpansion {\n\t\tpv := volumeToMount.VolumeSpec.PersistentVolume\n\t\tpvc, err := og.kubeClient.CoreV1().PersistentVolumeClaims(pv.Spec.ClaimRef.Namespace).Get(context.TODO(), pv.Spec.ClaimRef.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\t// Return error rather than leave the file system un-resized, caller will log and retry\n\t\t\treturn false, fmt.Errorf(\"mountVolume.NodeExpandVolume get PVC failed : %v\", err)\n\t\t}\n\n\t\tif volumeToMount.VolumeSpec.ReadOnly {\n\t\t\tsimpleMsg, detailedMsg := volumeToMount.GenerateMsg(\"MountVolume.NodeExpandVolume failed\", \"requested read-only file system\")\n\t\t\tklog.Warningf(detailedMsg)\n\t\t\tog.recorder.Eventf(volumeToMount.Pod, v1.EventTypeWarning, kevents.FileSystemResizeFailed, simpleMsg)\n\t\t\tog.recorder.Eventf(pvc, v1.EventTypeWarning, kevents.FileSystemResizeFailed, simpleMsg)\n\t\t\treturn true, nil\n\t\t}\n\t\tpvcStatusCap := pvc.Status.Capacity[v1.ResourceStorage]\n\t\tpvSpecCap := pv.Spec.Capacity[v1.ResourceStorage]\n\t\tif pvcStatusCap.Cmp(pvSpecCap) \u003c 0 {\n\t\t\trsOpts.NewSize = pvSpecCap\n\t\t\trsOpts.OldSize = pvcStatusCap\n\t\t\tresizeOp := nodeResizeOperationOpts{\n\t\t\t\tvmt: volumeToMount,\n\t\t\t\tpvc: pvc,\n\t\t\t\tpv: pv,\n\t\t\t\tpluginResizeOpts: rsOpts,\n\t\t\t\tvolumePlugin: expandablePlugin,\n\t\t\t\tactualStateOfWorld: actualStateOfWorld,\n\t\t\t}\n\t\t\tif og.checkForRecoveryFromExpansion(pvc, volumeToMount) {\n\t\t\t\tnodeExpander := newNodeExpander(resizeOp, og.kubeClient, og.recorder)\n\t\t\t\tresizeFinished, err, _ := nodeExpander.expandOnPlugin()\n\t\t\t\treturn resizeFinished, err\n\t\t\t} else {\n\t\t\t\treturn og.legacyCallNodeExpandOnPlugin(resizeOp)\n\t\t\t}\n\t\t}\n\t}\n\treturn true, nil\n}","line":{"from":2065,"to":2105}} {"id":100013087,"name":"checkIfSupportsNodeExpansion","signature":"func (og *operationGenerator) checkIfSupportsNodeExpansion(volumeToMount VolumeToMount) (bool, volume.NodeExpandableVolumePlugin)","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) checkIfSupportsNodeExpansion(volumeToMount VolumeToMount) (bool, volume.NodeExpandableVolumePlugin) {\n\tif volumeToMount.VolumeSpec != nil \u0026\u0026\n\t\tvolumeToMount.VolumeSpec.InlineVolumeSpecForCSIMigration {\n\t\tklog.V(4).Infof(\"This volume %s is a migrated inline volume and is not resizable\", volumeToMount.VolumeName)\n\t\treturn false, nil\n\t}\n\n\t// Get expander, if possible\n\texpandableVolumePlugin, _ :=\n\t\tog.volumePluginMgr.FindNodeExpandablePluginBySpec(volumeToMount.VolumeSpec)\n\tif expandableVolumePlugin != nil \u0026\u0026\n\t\texpandableVolumePlugin.RequiresFSResize() \u0026\u0026\n\t\tvolumeToMount.VolumeSpec.PersistentVolume != nil {\n\t\treturn true, expandableVolumePlugin\n\t}\n\treturn false, nil\n}","line":{"from":2107,"to":2123}} {"id":100013088,"name":"nodeExpandVolume","signature":"func (og *operationGenerator) nodeExpandVolume(","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) nodeExpandVolume(\n\tvolumeToMount VolumeToMount,\n\tactualStateOfWorld ActualStateOfWorldMounterUpdater,\n\trsOpts volume.NodeResizeOptions) (bool, error) {\n\n\tsupportsExpansion, expandableVolumePlugin := og.checkIfSupportsNodeExpansion(volumeToMount)\n\n\tif supportsExpansion {\n\t\t// lets use sizes handed over to us by caller for comparison\n\t\tif rsOpts.NewSize.Cmp(rsOpts.OldSize) \u003e 0 {\n\t\t\tpv := volumeToMount.VolumeSpec.PersistentVolume\n\t\t\tpvc, err := og.kubeClient.CoreV1().PersistentVolumeClaims(pv.Spec.ClaimRef.Namespace).Get(context.TODO(), pv.Spec.ClaimRef.Name, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\t// Return error rather than leave the file system un-resized, caller will log and retry\n\t\t\t\treturn false, fmt.Errorf(\"mountVolume.NodeExpandVolume get PVC failed : %v\", err)\n\t\t\t}\n\n\t\t\tif volumeToMount.VolumeSpec.ReadOnly {\n\t\t\t\tsimpleMsg, detailedMsg := volumeToMount.GenerateMsg(\"MountVolume.NodeExpandVolume failed\", \"requested read-only file system\")\n\t\t\t\tklog.Warningf(detailedMsg)\n\t\t\t\tog.recorder.Eventf(volumeToMount.Pod, v1.EventTypeWarning, kevents.FileSystemResizeFailed, simpleMsg)\n\t\t\t\tog.recorder.Eventf(pvc, v1.EventTypeWarning, kevents.FileSystemResizeFailed, simpleMsg)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\tresizeOp := nodeResizeOperationOpts{\n\t\t\t\tvmt: volumeToMount,\n\t\t\t\tpvc: pvc,\n\t\t\t\tpv: pv,\n\t\t\t\tpluginResizeOpts: rsOpts,\n\t\t\t\tvolumePlugin: expandableVolumePlugin,\n\t\t\t\tactualStateOfWorld: actualStateOfWorld,\n\t\t\t}\n\n\t\t\tif og.checkForRecoveryFromExpansion(pvc, volumeToMount) {\n\t\t\t\tnodeExpander := newNodeExpander(resizeOp, og.kubeClient, og.recorder)\n\t\t\t\tresizeFinished, err, _ := nodeExpander.expandOnPlugin()\n\t\t\t\treturn resizeFinished, err\n\t\t\t} else {\n\t\t\t\treturn og.legacyCallNodeExpandOnPlugin(resizeOp)\n\t\t\t}\n\t\t}\n\t}\n\treturn true, nil\n}","line":{"from":2125,"to":2168}} {"id":100013089,"name":"checkForRecoveryFromExpansion","signature":"func (og *operationGenerator) checkForRecoveryFromExpansion(pvc *v1.PersistentVolumeClaim, volumeToMount VolumeToMount) bool","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"func (og *operationGenerator) checkForRecoveryFromExpansion(pvc *v1.PersistentVolumeClaim, volumeToMount VolumeToMount) bool {\n\tresizeStatus := pvc.Status.ResizeStatus\n\tallocatedResource := pvc.Status.AllocatedResources\n\tfeatureGateStatus := utilfeature.DefaultFeatureGate.Enabled(features.RecoverVolumeExpansionFailure)\n\n\tif !featureGateStatus {\n\t\treturn false\n\t}\n\n\t// Even though RecoverVolumeExpansionFailure feature gate is enabled, it appears that we are running with older version\n\t// of resize controller, which will not populate allocatedResource and resizeStatus. This can happen because of version skew\n\t// and hence we are going to keep expanding using older logic.\n\tif resizeStatus == nil \u0026\u0026 allocatedResource == nil {\n\t\t_, detailedMsg := volumeToMount.GenerateMsg(\"MountVolume.NodeExpandVolume running with\", \"older external resize controller\")\n\t\tklog.Warningf(detailedMsg)\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":2170,"to":2188}} {"id":100013090,"name":"legacyCallNodeExpandOnPlugin","signature":"func (og *operationGenerator) legacyCallNodeExpandOnPlugin(resizeOp nodeResizeOperationOpts) (bool, error)","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"// legacyCallNodeExpandOnPlugin is old version of calling node expansion on plugin, which does not support\n// recovery from volume expansion failure\n// TODO: Removing this code when RecoverVolumeExpansionFailure feature goes GA.\nfunc (og *operationGenerator) legacyCallNodeExpandOnPlugin(resizeOp nodeResizeOperationOpts) (bool, error) {\n\tpvc := resizeOp.pvc\n\tvolumeToMount := resizeOp.vmt\n\trsOpts := resizeOp.pluginResizeOpts\n\tactualStateOfWorld := resizeOp.actualStateOfWorld\n\texpandableVolumePlugin := resizeOp.volumePlugin\n\n\tpvcStatusCap := pvc.Status.Capacity[v1.ResourceStorage]\n\n\tnodeName := volumeToMount.Pod.Spec.NodeName\n\n\tvar err error\n\n\t// File system resize was requested, proceed\n\tklog.V(4).InfoS(volumeToMount.GenerateMsgDetailed(\"MountVolume.NodeExpandVolume entering\", fmt.Sprintf(\"DevicePath %q\", volumeToMount.DevicePath)), \"pod\", klog.KObj(volumeToMount.Pod))\n\n\trsOpts.VolumeSpec = volumeToMount.VolumeSpec\n\n\t_, resizeErr := expandableVolumePlugin.NodeExpand(rsOpts)\n\tif resizeErr != nil {\n\t\t// if driver returned FailedPrecondition error that means\n\t\t// volume expansion should not be retried on this node but\n\t\t// expansion operation should not block mounting\n\t\tif volumetypes.IsFailedPreconditionError(resizeErr) {\n\t\t\tactualStateOfWorld.MarkForInUseExpansionError(volumeToMount.VolumeName)\n\t\t\tklog.Errorf(volumeToMount.GenerateErrorDetailed(\"MountVolume.NodeExapndVolume failed\", resizeErr).Error())\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, resizeErr\n\t}\n\n\tsimpleMsg, detailedMsg := volumeToMount.GenerateMsg(\"MountVolume.NodeExpandVolume succeeded\", nodeName)\n\tog.recorder.Eventf(volumeToMount.Pod, v1.EventTypeNormal, kevents.FileSystemResizeSuccess, simpleMsg)\n\tog.recorder.Eventf(pvc, v1.EventTypeNormal, kevents.FileSystemResizeSuccess, simpleMsg)\n\tklog.InfoS(detailedMsg, \"pod\", klog.KObj(volumeToMount.Pod))\n\n\t// if PVC already has new size, there is no need to update it.\n\tif pvcStatusCap.Cmp(rsOpts.NewSize) \u003e= 0 {\n\t\treturn true, nil\n\t}\n\n\t// File system resize succeeded, now update the PVC's Capacity to match the PV's\n\t_, err = util.MarkFSResizeFinished(pvc, rsOpts.NewSize, og.kubeClient)\n\tif err != nil {\n\t\t// On retry, NodeExpandVolume will be called again but do nothing\n\t\treturn false, fmt.Errorf(\"mountVolume.NodeExpandVolume update PVC status failed : %v\", err)\n\t}\n\treturn true, nil\n}","line":{"from":2190,"to":2241}} {"id":100013091,"name":"checkMountOptionSupport","signature":"func checkMountOptionSupport(og *operationGenerator, volumeToMount VolumeToMount, plugin volume.VolumePlugin) error","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"func checkMountOptionSupport(og *operationGenerator, volumeToMount VolumeToMount, plugin volume.VolumePlugin) error {\n\tmountOptions := util.MountOptionFromSpec(volumeToMount.VolumeSpec)\n\n\tif len(mountOptions) \u003e 0 \u0026\u0026 !plugin.SupportsMountOption() {\n\t\treturn fmt.Errorf(\"mount options are not supported for this volume type\")\n\t}\n\treturn nil\n}","line":{"from":2243,"to":2250}} {"id":100013092,"name":"checkNodeAffinity","signature":"func checkNodeAffinity(og *operationGenerator, volumeToMount VolumeToMount) error","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"// checkNodeAffinity looks at the PV node affinity, and checks if the node has the same corresponding labels\n// This ensures that we don't mount a volume that doesn't belong to this node\nfunc checkNodeAffinity(og *operationGenerator, volumeToMount VolumeToMount) error {\n\tpv := volumeToMount.VolumeSpec.PersistentVolume\n\tif pv != nil {\n\t\tnodeLabels, err := og.volumePluginMgr.Host.GetNodeLabels()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = storagehelpers.CheckNodeAffinity(pv, nodeLabels)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":2252,"to":2267}} {"id":100013093,"name":"isDeviceOpened","signature":"func isDeviceOpened(deviceToDetach AttachedVolume, hostUtil hostutil.HostUtils) (bool, error)","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"// isDeviceOpened checks the device status if the device is in use anywhere else on the system\nfunc isDeviceOpened(deviceToDetach AttachedVolume, hostUtil hostutil.HostUtils) (bool, error) {\n\tisDevicePath, devicePathErr := hostUtil.PathIsDevice(deviceToDetach.DevicePath)\n\tvar deviceOpened bool\n\tvar deviceOpenedErr error\n\tif !isDevicePath \u0026\u0026 devicePathErr == nil ||\n\t\t(devicePathErr != nil \u0026\u0026 strings.Contains(devicePathErr.Error(), \"does not exist\")) {\n\t\t// not a device path or path doesn't exist\n\t\t//TODO: refer to #36092\n\t\tklog.V(3).Infof(\"The path isn't device path or doesn't exist. Skip checking device path: %s\", deviceToDetach.DevicePath)\n\t\tdeviceOpened = false\n\t} else if devicePathErr != nil {\n\t\treturn false, deviceToDetach.GenerateErrorDetailed(\"PathIsDevice failed\", devicePathErr)\n\t} else {\n\t\tdeviceOpened, deviceOpenedErr = hostUtil.DeviceOpened(deviceToDetach.DevicePath)\n\t\tif deviceOpenedErr != nil {\n\t\t\treturn false, deviceToDetach.GenerateErrorDetailed(\"DeviceOpened failed\", deviceOpenedErr)\n\t\t}\n\t}\n\treturn deviceOpened, nil\n}","line":{"from":2269,"to":2289}} {"id":100013094,"name":"findDetachablePluginBySpec","signature":"func findDetachablePluginBySpec(spec *volume.Spec, pm *volume.VolumePluginMgr) (volume.AttachableVolumePlugin, error)","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"// findDetachablePluginBySpec is a variant of VolumePluginMgr.FindAttachablePluginByName() function.\n// The difference is that it bypass the CanAttach() check for CSI plugin, i.e. it assumes all CSI plugin supports detach.\n// The intention here is that a CSI plugin volume can end up in an Uncertain state, so that a detach\n// operation will help it to detach no matter it actually has the ability to attach/detach.\nfunc findDetachablePluginBySpec(spec *volume.Spec, pm *volume.VolumePluginMgr) (volume.AttachableVolumePlugin, error) {\n\tvolumePlugin, err := pm.FindPluginBySpec(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif attachableVolumePlugin, ok := volumePlugin.(volume.AttachableVolumePlugin); ok {\n\t\tif attachableVolumePlugin.GetPluginName() == \"kubernetes.io/csi\" {\n\t\t\treturn attachableVolumePlugin, nil\n\t\t}\n\t\tif canAttach, err := attachableVolumePlugin.CanAttach(spec); err != nil {\n\t\t\treturn nil, err\n\t\t} else if canAttach {\n\t\t\treturn attachableVolumePlugin, nil\n\t\t}\n\t}\n\treturn nil, nil\n}","line":{"from":2291,"to":2311}} {"id":100013095,"name":"getMigratedStatusBySpec","signature":"func getMigratedStatusBySpec(spec *volume.Spec) bool","file":"pkg/volume/util/operationexecutor/operation_generator.go","code":"func getMigratedStatusBySpec(spec *volume.Spec) bool {\n\tmigrated := false\n\tif spec != nil {\n\t\tmigrated = spec.Migrated\n\t}\n\treturn migrated\n}","line":{"from":2313,"to":2319}} {"id":100013096,"name":"RecycleVolumeByWatchingPodUntilCompletion","signature":"func RecycleVolumeByWatchingPodUntilCompletion(pvName string, pod *v1.Pod, kubeClient clientset.Interface, recorder RecycleEventRecorder) error","file":"pkg/volume/util/recyclerclient/recycler_client.go","code":"// RecycleVolumeByWatchingPodUntilCompletion is intended for use with volume\n// Recyclers. This function will save the given Pod to the API and watch it\n// until it completes, fails, or the pod's ActiveDeadlineSeconds is exceeded,\n// whichever comes first. An attempt to delete a recycler pod is always\n// attempted before returning.\n//\n// In case there is a pod with the same namespace+name already running, this\n// function deletes it as it is not able to judge if it is an old recycler\n// or user has forged a fake recycler to block Kubernetes from recycling.//\n//\n//\t pod - the pod designed by a volume plugin to recycle the volume. pod.Name\n//\t will be overwritten with unique name based on PV.Name.\n//\t\tclient - kube client for API operations.\nfunc RecycleVolumeByWatchingPodUntilCompletion(pvName string, pod *v1.Pod, kubeClient clientset.Interface, recorder RecycleEventRecorder) error {\n\treturn internalRecycleVolumeByWatchingPodUntilCompletion(pvName, pod, newRecyclerClient(kubeClient, recorder))\n}","line":{"from":36,"to":51}} {"id":100013097,"name":"internalRecycleVolumeByWatchingPodUntilCompletion","signature":"func internalRecycleVolumeByWatchingPodUntilCompletion(pvName string, pod *v1.Pod, recyclerClient recyclerClient) error","file":"pkg/volume/util/recyclerclient/recycler_client.go","code":"// same as above func comments, except 'recyclerClient' is a narrower pod API\n// interface to ease testing\nfunc internalRecycleVolumeByWatchingPodUntilCompletion(pvName string, pod *v1.Pod, recyclerClient recyclerClient) error {\n\tklog.V(5).Infof(\"creating recycler pod for volume %s\\n\", pod.Name)\n\n\t// Generate unique name for the recycler pod - we need to get \"already\n\t// exists\" error when a previous controller has already started recycling\n\t// the volume. Here we assume that pv.Name is already unique.\n\tpod.Name = \"recycler-for-\" + pvName\n\tpod.GenerateName = \"\"\n\n\tstopChannel := make(chan struct{})\n\tdefer close(stopChannel)\n\tpodCh, err := recyclerClient.WatchPod(pod.Name, pod.Namespace, stopChannel)\n\tif err != nil {\n\t\tklog.V(4).Infof(\"cannot start watcher for pod %s/%s: %v\", pod.Namespace, pod.Name, err)\n\t\treturn err\n\t}\n\n\t// Start the pod\n\t_, err = recyclerClient.CreatePod(pod)\n\tif err != nil {\n\t\tif errors.IsAlreadyExists(err) {\n\t\t\tdeleteErr := recyclerClient.DeletePod(pod.Name, pod.Namespace)\n\t\t\tif deleteErr != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to delete old recycler pod %s/%s: %s\", pod.Namespace, pod.Name, deleteErr)\n\t\t\t}\n\t\t\t// Recycler will try again and the old pod will be hopefully deleted\n\t\t\t// at that time.\n\t\t\treturn fmt.Errorf(\"old recycler pod found, will retry later\")\n\t\t}\n\t\treturn fmt.Errorf(\"unexpected error creating recycler pod: %+v\", err)\n\t}\n\terr = waitForPod(pod, recyclerClient, podCh)\n\n\t// In all cases delete the recycler pod and log its result.\n\tklog.V(2).Infof(\"deleting recycler pod %s/%s\", pod.Namespace, pod.Name)\n\tdeleteErr := recyclerClient.DeletePod(pod.Name, pod.Namespace)\n\tif deleteErr != nil {\n\t\tklog.Errorf(\"failed to delete recycler pod %s/%s: %v\", pod.Namespace, pod.Name, err)\n\t}\n\n\t// Returning recycler error is preferred, the pod will be deleted again on\n\t// the next retry.\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to recycle volume: %s\", err)\n\t}\n\n\t// Recycle succeeded but we failed to delete the recycler pod. Report it,\n\t// the controller will re-try recycling the PV again shortly.\n\tif deleteErr != nil {\n\t\treturn fmt.Errorf(\"failed to delete recycler pod: %s\", deleteErr)\n\t}\n\n\treturn nil\n}","line":{"from":53,"to":108}} {"id":100013098,"name":"waitForPod","signature":"func waitForPod(pod *v1.Pod, recyclerClient recyclerClient, podCh \u003c-chan watch.Event) error","file":"pkg/volume/util/recyclerclient/recycler_client.go","code":"// waitForPod watches the pod it until it finishes and send all events on the\n// pod to the PV.\nfunc waitForPod(pod *v1.Pod, recyclerClient recyclerClient, podCh \u003c-chan watch.Event) error {\n\tfor {\n\t\tevent, ok := \u003c-podCh\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"recycler pod %q watch channel had been closed\", pod.Name)\n\t\t}\n\t\tswitch event.Object.(type) {\n\t\tcase *v1.Pod:\n\t\t\t// POD changed\n\t\t\tpod := event.Object.(*v1.Pod)\n\t\t\tklog.V(4).Infof(\"recycler pod update received: %s %s/%s %s\", event.Type, pod.Namespace, pod.Name, pod.Status.Phase)\n\t\t\tswitch event.Type {\n\t\t\tcase watch.Added, watch.Modified:\n\t\t\t\tif pod.Status.Phase == v1.PodSucceeded {\n\t\t\t\t\t// Recycle succeeded.\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\tif pod.Status.Phase == v1.PodFailed {\n\t\t\t\t\tif pod.Status.Message != \"\" {\n\t\t\t\t\t\treturn fmt.Errorf(pod.Status.Message)\n\t\t\t\t\t}\n\t\t\t\t\treturn fmt.Errorf(\"pod failed, pod.Status.Message unknown\")\n\t\t\t\t}\n\n\t\t\tcase watch.Deleted:\n\t\t\t\treturn fmt.Errorf(\"recycler pod was deleted\")\n\n\t\t\tcase watch.Error:\n\t\t\t\treturn fmt.Errorf(\"recycler pod watcher failed\")\n\t\t\t}\n\n\t\tcase *v1.Event:\n\t\t\t// Event received\n\t\t\tpodEvent := event.Object.(*v1.Event)\n\t\t\tklog.V(4).Infof(\"recycler event received: %s %s/%s %s/%s %s\", event.Type, podEvent.Namespace, podEvent.Name, podEvent.InvolvedObject.Namespace, podEvent.InvolvedObject.Name, podEvent.Message)\n\t\t\tif event.Type == watch.Added {\n\t\t\t\trecyclerClient.Event(podEvent.Type, podEvent.Message)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":110,"to":152}} {"id":100013099,"name":"newRecyclerClient","signature":"func newRecyclerClient(client clientset.Interface, recorder RecycleEventRecorder) recyclerClient","file":"pkg/volume/util/recyclerclient/recycler_client.go","code":"func newRecyclerClient(client clientset.Interface, recorder RecycleEventRecorder) recyclerClient {\n\treturn \u0026realRecyclerClient{\n\t\tclient,\n\t\trecorder,\n\t}\n}","line":{"from":168,"to":173}} {"id":100013100,"name":"CreatePod","signature":"func (c *realRecyclerClient) CreatePod(pod *v1.Pod) (*v1.Pod, error)","file":"pkg/volume/util/recyclerclient/recycler_client.go","code":"func (c *realRecyclerClient) CreatePod(pod *v1.Pod) (*v1.Pod, error) {\n\treturn c.client.CoreV1().Pods(pod.Namespace).Create(context.TODO(), pod, metav1.CreateOptions{})\n}","line":{"from":180,"to":182}} {"id":100013101,"name":"GetPod","signature":"func (c *realRecyclerClient) GetPod(name, namespace string) (*v1.Pod, error)","file":"pkg/volume/util/recyclerclient/recycler_client.go","code":"func (c *realRecyclerClient) GetPod(name, namespace string) (*v1.Pod, error) {\n\treturn c.client.CoreV1().Pods(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n}","line":{"from":184,"to":186}} {"id":100013102,"name":"DeletePod","signature":"func (c *realRecyclerClient) DeletePod(name, namespace string) error","file":"pkg/volume/util/recyclerclient/recycler_client.go","code":"func (c *realRecyclerClient) DeletePod(name, namespace string) error {\n\treturn c.client.CoreV1().Pods(namespace).Delete(context.TODO(), name, metav1.DeleteOptions{})\n}","line":{"from":188,"to":190}} {"id":100013103,"name":"Event","signature":"func (c *realRecyclerClient) Event(eventtype, message string)","file":"pkg/volume/util/recyclerclient/recycler_client.go","code":"func (c *realRecyclerClient) Event(eventtype, message string) {\n\tc.recorder(eventtype, message)\n}","line":{"from":192,"to":194}} {"id":100013104,"name":"WatchPod","signature":"func (c *realRecyclerClient) WatchPod(name, namespace string, stopChannel chan struct{}) (\u003c-chan watch.Event, error)","file":"pkg/volume/util/recyclerclient/recycler_client.go","code":"// WatchPod watches a pod and events related to it. It sends pod updates and events over the returned channel\n// It will continue until stopChannel is closed\nfunc (c *realRecyclerClient) WatchPod(name, namespace string, stopChannel chan struct{}) (\u003c-chan watch.Event, error) {\n\tpodSelector, err := fields.ParseSelector(\"metadata.name=\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\toptions := metav1.ListOptions{\n\t\tFieldSelector: podSelector.String(),\n\t\tWatch: true,\n\t}\n\n\tpodWatch, err := c.client.CoreV1().Pods(namespace).Watch(context.TODO(), options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\teventSelector, _ := fields.ParseSelector(\"involvedObject.name=\" + name)\n\teventWatch, err := c.client.CoreV1().Events(namespace).Watch(context.TODO(), metav1.ListOptions{\n\t\tFieldSelector: eventSelector.String(),\n\t\tWatch: true,\n\t})\n\tif err != nil {\n\t\tpodWatch.Stop()\n\t\treturn nil, err\n\t}\n\n\teventCh := make(chan watch.Event, 30)\n\tvar wg sync.WaitGroup\n\twg.Add(2)\n\n\tgo func() {\n\t\tdefer close(eventCh)\n\t\twg.Wait()\n\t}()\n\n\tgo func() {\n\t\tdefer eventWatch.Stop()\n\t\tdefer wg.Done()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase \u003c-stopChannel:\n\t\t\t\treturn\n\t\t\tcase eventEvent, ok := \u003c-eventWatch.ResultChan():\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\teventCh \u003c- eventEvent\n\t\t\t}\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tdefer podWatch.Stop()\n\t\tdefer wg.Done()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase \u003c-stopChannel:\n\t\t\t\treturn\n\n\t\t\tcase podEvent, ok := \u003c-podWatch.ResultChan():\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\teventCh \u003c- podEvent\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn eventCh, nil\n}","line":{"from":196,"to":266}} {"id":100013105,"name":"UpdatePVSize","signature":"func UpdatePVSize(","file":"pkg/volume/util/resize_util.go","code":"// UpdatePVSize updates just pv size after cloudprovider resizing is successful\nfunc UpdatePVSize(\n\tpv *v1.PersistentVolume,\n\tnewSize resource.Quantity,\n\tkubeClient clientset.Interface) (*v1.PersistentVolume, error) {\n\tpvClone := pv.DeepCopy()\n\tpvClone.Spec.Capacity[v1.ResourceStorage] = newSize\n\n\treturn PatchPV(pv, pvClone, kubeClient)\n}","line":{"from":57,"to":66}} {"id":100013106,"name":"AddAnnPreResizeCapacity","signature":"func AddAnnPreResizeCapacity(","file":"pkg/volume/util/resize_util.go","code":"// AddAnnPreResizeCapacity adds volume.alpha.kubernetes.io/pre-resize-capacity from the pv\nfunc AddAnnPreResizeCapacity(\n\tpv *v1.PersistentVolume,\n\toldCapacity resource.Quantity,\n\tkubeClient clientset.Interface) error {\n\t// if the pv already has a resize annotation skip the process\n\tif metav1.HasAnnotation(pv.ObjectMeta, AnnPreResizeCapacity) {\n\t\treturn nil\n\t}\n\n\tpvClone := pv.DeepCopy()\n\tif pvClone.ObjectMeta.Annotations == nil {\n\t\tpvClone.ObjectMeta.Annotations = make(map[string]string)\n\t}\n\tpvClone.ObjectMeta.Annotations[AnnPreResizeCapacity] = oldCapacity.String()\n\n\t_, err := PatchPV(pv, pvClone, kubeClient)\n\treturn err\n}","line":{"from":68,"to":86}} {"id":100013107,"name":"DeleteAnnPreResizeCapacity","signature":"func DeleteAnnPreResizeCapacity(","file":"pkg/volume/util/resize_util.go","code":"// DeleteAnnPreResizeCapacity deletes volume.alpha.kubernetes.io/pre-resize-capacity from the pv\nfunc DeleteAnnPreResizeCapacity(\n\tpv *v1.PersistentVolume,\n\tkubeClient clientset.Interface) error {\n\t// if the pv does not have a resize annotation skip the entire process\n\tif !metav1.HasAnnotation(pv.ObjectMeta, AnnPreResizeCapacity) {\n\t\treturn nil\n\t}\n\tpvClone := pv.DeepCopy()\n\tdelete(pvClone.ObjectMeta.Annotations, AnnPreResizeCapacity)\n\t_, err := PatchPV(pv, pvClone, kubeClient)\n\treturn err\n}","line":{"from":88,"to":100}} {"id":100013108,"name":"PatchPV","signature":"func PatchPV(","file":"pkg/volume/util/resize_util.go","code":"// PatchPV creates and executes a patch for pv\nfunc PatchPV(\n\toldPV *v1.PersistentVolume,\n\tnewPV *v1.PersistentVolume,\n\tkubeClient clientset.Interface) (*v1.PersistentVolume, error) {\n\toldData, err := json.Marshal(oldPV)\n\tif err != nil {\n\t\treturn oldPV, fmt.Errorf(\"unexpected error marshaling old PV %q with error : %v\", oldPV.Name, err)\n\t}\n\n\tnewData, err := json.Marshal(newPV)\n\tif err != nil {\n\t\treturn oldPV, fmt.Errorf(\"unexpected error marshaling new PV %q with error : %v\", newPV.Name, err)\n\t}\n\n\tpatchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, oldPV)\n\tif err != nil {\n\t\treturn oldPV, fmt.Errorf(\"error Creating two way merge patch for PV %q with error : %v\", oldPV.Name, err)\n\t}\n\n\tupdatedPV, err := kubeClient.CoreV1().PersistentVolumes().Patch(context.TODO(), oldPV.Name, types.StrategicMergePatchType, patchBytes, metav1.PatchOptions{})\n\tif err != nil {\n\t\treturn oldPV, fmt.Errorf(\"error Patching PV %q with error : %v\", oldPV.Name, err)\n\t}\n\treturn updatedPV, nil\n}","line":{"from":102,"to":127}} {"id":100013109,"name":"MarkResizeInProgressWithResizer","signature":"func MarkResizeInProgressWithResizer(","file":"pkg/volume/util/resize_util.go","code":"// MarkResizeInProgressWithResizer marks cloudprovider resizing as in progress\n// and also annotates the PVC with the name of the resizer.\nfunc MarkResizeInProgressWithResizer(\n\tpvc *v1.PersistentVolumeClaim,\n\tresizerName string,\n\tkubeClient clientset.Interface) (*v1.PersistentVolumeClaim, error) {\n\t// Mark PVC as Resize Started\n\tprogressCondition := v1.PersistentVolumeClaimCondition{\n\t\tType: v1.PersistentVolumeClaimResizing,\n\t\tStatus: v1.ConditionTrue,\n\t\tLastTransitionTime: metav1.Now(),\n\t}\n\tconditions := []v1.PersistentVolumeClaimCondition{progressCondition}\n\tnewPVC := pvc.DeepCopy()\n\tnewPVC = MergeResizeConditionOnPVC(newPVC, conditions)\n\tnewPVC = setResizer(newPVC, resizerName)\n\treturn PatchPVCStatus(pvc /*oldPVC*/, newPVC, kubeClient)\n}","line":{"from":129,"to":146}} {"id":100013110,"name":"MarkControllerReisizeInProgress","signature":"func MarkControllerReisizeInProgress(pvc *v1.PersistentVolumeClaim, resizerName string, newSize resource.Quantity, kubeClient clientset.Interface) (*v1.PersistentVolumeClaim, error)","file":"pkg/volume/util/resize_util.go","code":"func MarkControllerReisizeInProgress(pvc *v1.PersistentVolumeClaim, resizerName string, newSize resource.Quantity, kubeClient clientset.Interface) (*v1.PersistentVolumeClaim, error) {\n\t// Mark PVC as Resize Started\n\tprogressCondition := v1.PersistentVolumeClaimCondition{\n\t\tType: v1.PersistentVolumeClaimResizing,\n\t\tStatus: v1.ConditionTrue,\n\t\tLastTransitionTime: metav1.Now(),\n\t}\n\tcontrollerExpansionInProgress := v1.PersistentVolumeClaimControllerExpansionInProgress\n\tconditions := []v1.PersistentVolumeClaimCondition{progressCondition}\n\tnewPVC := pvc.DeepCopy()\n\tnewPVC = MergeResizeConditionOnPVC(newPVC, conditions)\n\tnewPVC.Status.ResizeStatus = \u0026controllerExpansionInProgress\n\tnewPVC.Status.AllocatedResources = v1.ResourceList{v1.ResourceStorage: newSize}\n\tnewPVC = setResizer(newPVC, resizerName)\n\treturn PatchPVCStatus(pvc /*oldPVC*/, newPVC, kubeClient)\n}","line":{"from":148,"to":163}} {"id":100013111,"name":"SetClaimResizer","signature":"func SetClaimResizer(","file":"pkg/volume/util/resize_util.go","code":"// SetClaimResizer sets resizer annotation on PVC\nfunc SetClaimResizer(\n\tpvc *v1.PersistentVolumeClaim,\n\tresizerName string,\n\tkubeClient clientset.Interface) (*v1.PersistentVolumeClaim, error) {\n\tnewPVC := pvc.DeepCopy()\n\tnewPVC = setResizer(newPVC, resizerName)\n\treturn PatchPVCStatus(pvc /*oldPVC*/, newPVC, kubeClient)\n}","line":{"from":165,"to":173}} {"id":100013112,"name":"setResizer","signature":"func setResizer(pvc *v1.PersistentVolumeClaim, resizerName string) *v1.PersistentVolumeClaim","file":"pkg/volume/util/resize_util.go","code":"func setResizer(pvc *v1.PersistentVolumeClaim, resizerName string) *v1.PersistentVolumeClaim {\n\tif val, ok := pvc.Annotations[volumetypes.VolumeResizerKey]; ok \u0026\u0026 val == resizerName {\n\t\treturn pvc\n\t}\n\tmetav1.SetMetaDataAnnotation(\u0026pvc.ObjectMeta, volumetypes.VolumeResizerKey, resizerName)\n\treturn pvc\n}","line":{"from":175,"to":181}} {"id":100013113,"name":"MarkForFSResize","signature":"func MarkForFSResize(","file":"pkg/volume/util/resize_util.go","code":"// MarkForFSResize marks file system resizing as pending\nfunc MarkForFSResize(\n\tpvc *v1.PersistentVolumeClaim,\n\tkubeClient clientset.Interface) (*v1.PersistentVolumeClaim, error) {\n\tpvcCondition := v1.PersistentVolumeClaimCondition{\n\t\tType: v1.PersistentVolumeClaimFileSystemResizePending,\n\t\tStatus: v1.ConditionTrue,\n\t\tLastTransitionTime: metav1.Now(),\n\t\tMessage: \"Waiting for user to (re-)start a pod to finish file system resize of volume on node.\",\n\t}\n\tconditions := []v1.PersistentVolumeClaimCondition{pvcCondition}\n\tnewPVC := pvc.DeepCopy()\n\tif utilfeature.DefaultFeatureGate.Enabled(features.RecoverVolumeExpansionFailure) {\n\t\texpansionPendingOnNode := v1.PersistentVolumeClaimNodeExpansionPending\n\t\tnewPVC.Status.ResizeStatus = \u0026expansionPendingOnNode\n\t}\n\tnewPVC = MergeResizeConditionOnPVC(newPVC, conditions)\n\tupdatedPVC, err := PatchPVCStatus(pvc /*oldPVC*/, newPVC, kubeClient)\n\treturn updatedPVC, err\n}","line":{"from":183,"to":202}} {"id":100013114,"name":"MarkResizeFinished","signature":"func MarkResizeFinished(","file":"pkg/volume/util/resize_util.go","code":"// MarkResizeFinished marks all resizing as done\nfunc MarkResizeFinished(\n\tpvc *v1.PersistentVolumeClaim,\n\tnewSize resource.Quantity,\n\tkubeClient clientset.Interface) (*v1.PersistentVolumeClaim, error) {\n\treturn MarkFSResizeFinished(pvc, newSize, kubeClient)\n}","line":{"from":204,"to":210}} {"id":100013115,"name":"MarkFSResizeFinished","signature":"func MarkFSResizeFinished(","file":"pkg/volume/util/resize_util.go","code":"// MarkFSResizeFinished marks file system resizing as done\nfunc MarkFSResizeFinished(\n\tpvc *v1.PersistentVolumeClaim,\n\tnewSize resource.Quantity,\n\tkubeClient clientset.Interface) (*v1.PersistentVolumeClaim, error) {\n\tnewPVC := pvc.DeepCopy()\n\n\tnewPVC.Status.Capacity[v1.ResourceStorage] = newSize\n\n\t// if RecoverVolumeExpansionFailure is enabled, we need to reset ResizeStatus back to nil\n\tif utilfeature.DefaultFeatureGate.Enabled(features.RecoverVolumeExpansionFailure) {\n\t\texpansionFinished := v1.PersistentVolumeClaimNoExpansionInProgress\n\t\tnewPVC.Status.ResizeStatus = \u0026expansionFinished\n\t}\n\n\tnewPVC = MergeResizeConditionOnPVC(newPVC, []v1.PersistentVolumeClaimCondition{})\n\tupdatedPVC, err := PatchPVCStatus(pvc /*oldPVC*/, newPVC, kubeClient)\n\treturn updatedPVC, err\n}","line":{"from":212,"to":230}} {"id":100013116,"name":"MarkNodeExpansionFailed","signature":"func MarkNodeExpansionFailed(pvc *v1.PersistentVolumeClaim, kubeClient clientset.Interface) (*v1.PersistentVolumeClaim, error)","file":"pkg/volume/util/resize_util.go","code":"// MarkNodeExpansionFailed marks a PVC for node expansion as failed. Kubelet should not retry expansion\n// of volumes which are in failed state.\nfunc MarkNodeExpansionFailed(pvc *v1.PersistentVolumeClaim, kubeClient clientset.Interface) (*v1.PersistentVolumeClaim, error) {\n\texpansionFailedOnNode := v1.PersistentVolumeClaimNodeExpansionFailed\n\tnewPVC := pvc.DeepCopy()\n\tnewPVC.Status.ResizeStatus = \u0026expansionFailedOnNode\n\tpatchBytes, err := createPVCPatch(pvc, newPVC, false /* addResourceVersionCheck */)\n\tif err != nil {\n\t\treturn pvc, fmt.Errorf(\"patchPVCStatus failed to patch PVC %q: %v\", pvc.Name, err)\n\t}\n\n\tupdatedClaim, updateErr := kubeClient.CoreV1().PersistentVolumeClaims(pvc.Namespace).\n\t\tPatch(context.TODO(), pvc.Name, types.StrategicMergePatchType, patchBytes, metav1.PatchOptions{}, \"status\")\n\tif updateErr != nil {\n\t\treturn pvc, fmt.Errorf(\"patchPVCStatus failed to patch PVC %q: %v\", pvc.Name, updateErr)\n\t}\n\treturn updatedClaim, nil\n}","line":{"from":232,"to":249}} {"id":100013117,"name":"MarkNodeExpansionInProgress","signature":"func MarkNodeExpansionInProgress(pvc *v1.PersistentVolumeClaim, kubeClient clientset.Interface) (*v1.PersistentVolumeClaim, error)","file":"pkg/volume/util/resize_util.go","code":"// MarkNodeExpansionInProgress marks pvc expansion in progress on node\nfunc MarkNodeExpansionInProgress(pvc *v1.PersistentVolumeClaim, kubeClient clientset.Interface) (*v1.PersistentVolumeClaim, error) {\n\tnodeExpansionInProgress := v1.PersistentVolumeClaimNodeExpansionInProgress\n\tnewPVC := pvc.DeepCopy()\n\tnewPVC.Status.ResizeStatus = \u0026nodeExpansionInProgress\n\tupdatedPVC, err := PatchPVCStatus(pvc /* oldPVC */, newPVC, kubeClient)\n\treturn updatedPVC, err\n}","line":{"from":251,"to":258}} {"id":100013118,"name":"PatchPVCStatus","signature":"func PatchPVCStatus(","file":"pkg/volume/util/resize_util.go","code":"// PatchPVCStatus updates PVC status using PATCH verb\n// Don't use Update because this can be called from kubelet and if kubelet has an older client its\n// Updates will overwrite new fields. And to avoid writing to a stale object, add ResourceVersion\n// to the patch so that Patch will fail if the patch's RV != actual up-to-date RV like Update would\nfunc PatchPVCStatus(\n\toldPVC *v1.PersistentVolumeClaim,\n\tnewPVC *v1.PersistentVolumeClaim,\n\tkubeClient clientset.Interface) (*v1.PersistentVolumeClaim, error) {\n\tpatchBytes, err := createPVCPatch(oldPVC, newPVC, true /* addResourceVersionCheck */)\n\tif err != nil {\n\t\treturn oldPVC, fmt.Errorf(\"patchPVCStatus failed to patch PVC %q: %v\", oldPVC.Name, err)\n\t}\n\n\tupdatedClaim, updateErr := kubeClient.CoreV1().PersistentVolumeClaims(oldPVC.Namespace).\n\t\tPatch(context.TODO(), oldPVC.Name, types.StrategicMergePatchType, patchBytes, metav1.PatchOptions{}, \"status\")\n\tif updateErr != nil {\n\t\treturn oldPVC, fmt.Errorf(\"patchPVCStatus failed to patch PVC %q: %v\", oldPVC.Name, updateErr)\n\t}\n\treturn updatedClaim, nil\n}","line":{"from":260,"to":279}} {"id":100013119,"name":"createPVCPatch","signature":"func createPVCPatch(","file":"pkg/volume/util/resize_util.go","code":"func createPVCPatch(\n\toldPVC *v1.PersistentVolumeClaim,\n\tnewPVC *v1.PersistentVolumeClaim, addResourceVersionCheck bool) ([]byte, error) {\n\toldData, err := json.Marshal(oldPVC)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to marshal old data: %v\", err)\n\t}\n\n\tnewData, err := json.Marshal(newPVC)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to marshal new data: %v\", err)\n\t}\n\n\tpatchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, oldPVC)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create 2 way merge patch: %v\", err)\n\t}\n\n\tif addResourceVersionCheck {\n\t\tpatchBytes, err = addResourceVersion(patchBytes, oldPVC.ResourceVersion)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to add resource version: %v\", err)\n\t\t}\n\t}\n\n\treturn patchBytes, nil\n}","line":{"from":281,"to":307}} {"id":100013120,"name":"addResourceVersion","signature":"func addResourceVersion(patchBytes []byte, resourceVersion string) ([]byte, error)","file":"pkg/volume/util/resize_util.go","code":"func addResourceVersion(patchBytes []byte, resourceVersion string) ([]byte, error) {\n\tvar patchMap map[string]interface{}\n\terr := json.Unmarshal(patchBytes, \u0026patchMap)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error unmarshalling patch: %v\", err)\n\t}\n\tu := unstructured.Unstructured{Object: patchMap}\n\ta, err := meta.Accessor(\u0026u)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating accessor: %v\", err)\n\t}\n\ta.SetResourceVersion(resourceVersion)\n\tversionBytes, err := json.Marshal(patchMap)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error marshalling json patch: %v\", err)\n\t}\n\treturn versionBytes, nil\n}","line":{"from":309,"to":326}} {"id":100013121,"name":"MergeResizeConditionOnPVC","signature":"func MergeResizeConditionOnPVC(","file":"pkg/volume/util/resize_util.go","code":"// MergeResizeConditionOnPVC updates pvc with requested resize conditions\n// leaving other conditions untouched.\nfunc MergeResizeConditionOnPVC(\n\tpvc *v1.PersistentVolumeClaim,\n\tresizeConditions []v1.PersistentVolumeClaimCondition) *v1.PersistentVolumeClaim {\n\tresizeConditionMap := map[v1.PersistentVolumeClaimConditionType]*resizeProcessStatus{}\n\n\tfor _, condition := range resizeConditions {\n\t\tresizeConditionMap[condition.Type] = \u0026resizeProcessStatus{condition, false}\n\t}\n\n\toldConditions := pvc.Status.Conditions\n\tnewConditions := []v1.PersistentVolumeClaimCondition{}\n\tfor _, condition := range oldConditions {\n\t\t// If Condition is of not resize type, we keep it.\n\t\tif _, ok := knownResizeConditions[condition.Type]; !ok {\n\t\t\tnewConditions = append(newConditions, condition)\n\t\t\tcontinue\n\t\t}\n\n\t\tif newCondition, ok := resizeConditionMap[condition.Type]; ok {\n\t\t\tif newCondition.condition.Status != condition.Status {\n\t\t\t\tnewConditions = append(newConditions, newCondition.condition)\n\t\t\t} else {\n\t\t\t\tnewConditions = append(newConditions, condition)\n\t\t\t}\n\t\t\tnewCondition.processed = true\n\t\t}\n\t}\n\n\t// append all unprocessed conditions\n\tfor _, newCondition := range resizeConditionMap {\n\t\tif !newCondition.processed {\n\t\t\tnewConditions = append(newConditions, newCondition.condition)\n\t\t}\n\t}\n\tpvc.Status.Conditions = newConditions\n\treturn pvc\n}","line":{"from":328,"to":366}} {"id":100013122,"name":"GenericResizeFS","signature":"func GenericResizeFS(host volume.VolumeHost, pluginName, devicePath, deviceMountPath string) (bool, error)","file":"pkg/volume/util/resize_util.go","code":"// GenericResizeFS : call generic filesystem resizer for plugins that don't have any special filesystem resize requirements\nfunc GenericResizeFS(host volume.VolumeHost, pluginName, devicePath, deviceMountPath string) (bool, error) {\n\tresizer := mount.NewResizeFs(host.GetExec(pluginName))\n\treturn resizer.Resize(devicePath, deviceMountPath)\n}","line":{"from":368,"to":372}} {"id":100013123,"name":"NewSELinuxLabelTranslator","signature":"func NewSELinuxLabelTranslator() SELinuxLabelTranslator","file":"pkg/volume/util/selinux.go","code":"// NewSELinuxLabelTranslator returns new SELinuxLabelTranslator for the platform.\nfunc NewSELinuxLabelTranslator() SELinuxLabelTranslator {\n\treturn \u0026translator{}\n}","line":{"from":50,"to":53}} {"id":100013124,"name":"SELinuxOptionsToFileLabel","signature":"func (l *translator) SELinuxOptionsToFileLabel(opts *v1.SELinuxOptions) (string, error)","file":"pkg/volume/util/selinux.go","code":"// SELinuxOptionsToFileLabel returns SELinux file label for given SELinuxOptions\n// of a container process.\n// When Role, User or Type are empty, they're read from the system defaults.\n// It returns \"\" and no error on platforms that do not have SELinux enabled\n// or don't support SELinux at all.\nfunc (l *translator) SELinuxOptionsToFileLabel(opts *v1.SELinuxOptions) (string, error) {\n\tif opts == nil {\n\t\treturn \"\", nil\n\t}\n\n\targs := contextOptions(opts)\n\tif len(args) == 0 {\n\t\treturn \"\", nil\n\t}\n\n\tprocessLabel, fileLabel, err := label.InitLabels(args)\n\tif err != nil {\n\t\t// In theory, this should be unreachable. InitLabels can fail only when args contain an unknown option,\n\t\t// and all options returned by contextOptions are known.\n\t\treturn \"\", err\n\t}\n\t// InitLabels() may allocate a new unique SELinux label in kubelet memory. The label is *not* allocated\n\t// in the container runtime. Clear it to avoid memory problems.\n\t// ReleaseLabel on non-allocated label is NOOP.\n\tselinux.ReleaseLabel(processLabel)\n\n\treturn fileLabel, nil\n}","line":{"from":55,"to":82}} {"id":100013125,"name":"contextOptions","signature":"func contextOptions(opts *v1.SELinuxOptions) []string","file":"pkg/volume/util/selinux.go","code":"// Convert SELinuxOptions to []string accepted by label.InitLabels\nfunc contextOptions(opts *v1.SELinuxOptions) []string {\n\tif opts == nil {\n\t\treturn nil\n\t}\n\targs := make([]string, 0, 3)\n\tif opts.User != \"\" {\n\t\targs = append(args, \"user:\"+opts.User)\n\t}\n\tif opts.Role != \"\" {\n\t\targs = append(args, \"role:\"+opts.Role)\n\t}\n\tif opts.Type != \"\" {\n\t\targs = append(args, \"type:\"+opts.Type)\n\t}\n\tif opts.Level != \"\" {\n\t\targs = append(args, \"level:\"+opts.Level)\n\t}\n\treturn args\n}","line":{"from":84,"to":103}} {"id":100013126,"name":"SELinuxEnabled","signature":"func (l *translator) SELinuxEnabled() bool","file":"pkg/volume/util/selinux.go","code":"func (l *translator) SELinuxEnabled() bool {\n\treturn selinux.GetEnabled()\n}","line":{"from":105,"to":107}} {"id":100013127,"name":"NewFakeSELinuxLabelTranslator","signature":"func NewFakeSELinuxLabelTranslator() SELinuxLabelTranslator","file":"pkg/volume/util/selinux.go","code":"// NewFakeSELinuxLabelTranslator returns a fake translator for unit tests.\n// It imitates a real translator on platforms that do not have SELinux enabled\n// or don't support SELinux at all.\nfunc NewFakeSELinuxLabelTranslator() SELinuxLabelTranslator {\n\treturn \u0026fakeTranslator{}\n}","line":{"from":114,"to":119}} {"id":100013128,"name":"SELinuxOptionsToFileLabel","signature":"func (l *fakeTranslator) SELinuxOptionsToFileLabel(opts *v1.SELinuxOptions) (string, error)","file":"pkg/volume/util/selinux.go","code":"// SELinuxOptionsToFileLabel returns SELinux file label for given options.\nfunc (l *fakeTranslator) SELinuxOptionsToFileLabel(opts *v1.SELinuxOptions) (string, error) {\n\tif opts == nil {\n\t\treturn \"\", nil\n\t}\n\t// Fill empty values from \"system defaults\" (taken from Fedora Linux).\n\tuser := opts.User\n\tif user == \"\" {\n\t\tuser = \"system_u\"\n\t}\n\n\trole := opts.Role\n\tif role == \"\" {\n\t\trole = \"object_r\"\n\t}\n\n\t// opts is context of the *process* to run in a container. Translate\n\t// process type \"container_t\" to file label type \"container_file_t\".\n\t// (The rest of the context is the same for processes and files).\n\tfileType := opts.Type\n\tif fileType == \"\" || fileType == \"container_t\" {\n\t\tfileType = \"container_file_t\"\n\t}\n\n\tlevel := opts.Level\n\tif level == \"\" {\n\t\t// If empty, level is allocated randomly.\n\t\tlevel = \"s0:c998,c999\"\n\t}\n\n\tctx := fmt.Sprintf(\"%s:%s:%s:%s\", user, role, fileType, level)\n\treturn ctx, nil\n}","line":{"from":121,"to":153}} {"id":100013129,"name":"SELinuxEnabled","signature":"func (l *fakeTranslator) SELinuxEnabled() bool","file":"pkg/volume/util/selinux.go","code":"func (l *fakeTranslator) SELinuxEnabled() bool {\n\treturn true\n}","line":{"from":155,"to":157}} {"id":100013130,"name":"SupportsSELinuxContextMount","signature":"func SupportsSELinuxContextMount(volumeSpec *volume.Spec, volumePluginMgr *volume.VolumePluginMgr) (bool, error)","file":"pkg/volume/util/selinux.go","code":"// SupportsSELinuxContextMount checks if the given volumeSpec supports with mount -o context\nfunc SupportsSELinuxContextMount(volumeSpec *volume.Spec, volumePluginMgr *volume.VolumePluginMgr) (bool, error) {\n\tplugin, _ := volumePluginMgr.FindPluginBySpec(volumeSpec)\n\tif plugin != nil {\n\t\treturn plugin.SupportsSELinuxContextMount(volumeSpec)\n\t}\n\n\treturn false, nil\n}","line":{"from":159,"to":167}} {"id":100013131,"name":"VolumeSupportsSELinuxMount","signature":"func VolumeSupportsSELinuxMount(volumeSpec *volume.Spec) bool","file":"pkg/volume/util/selinux.go","code":"// VolumeSupportsSELinuxMount returns true if given volume access mode can support mount with SELinux mount options.\nfunc VolumeSupportsSELinuxMount(volumeSpec *volume.Spec) bool {\n\t// Right now, SELinux mount is supported only for ReadWriteOncePod volumes.\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.ReadWriteOncePod) {\n\t\treturn false\n\t}\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {\n\t\treturn false\n\t}\n\tif volumeSpec.PersistentVolume == nil {\n\t\treturn false\n\t}\n\tif len(volumeSpec.PersistentVolume.Spec.AccessModes) != 1 {\n\t\treturn false\n\t}\n\tif !v1helper.ContainsAccessMode(volumeSpec.PersistentVolume.Spec.AccessModes, v1.ReadWriteOncePod) {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":169,"to":188}} {"id":100013132,"name":"AddSELinuxMountOption","signature":"func AddSELinuxMountOption(options []string, seLinuxContext string) []string","file":"pkg/volume/util/selinux.go","code":"// AddSELinuxMountOption adds -o context=\"XYZ\" mount option to a given list\nfunc AddSELinuxMountOption(options []string, seLinuxContext string) []string {\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {\n\t\treturn options\n\t}\n\t// Use double quotes to support a comma \",\" in the SELinux context string.\n\t// For example: dirsync,context=\"system_u:object_r:container_file_t:s0:c15,c25\",noatime\n\treturn append(options, fmt.Sprintf(\"context=%q\", seLinuxContext))\n}","line":{"from":190,"to":198}} {"id":100013133,"name":"GetDefaultClass","signature":"func GetDefaultClass(lister storagev1listers.StorageClassLister) (*storagev1.StorageClass, error)","file":"pkg/volume/util/storageclass.go","code":"// GetDefaultClass returns the default StorageClass from the store, or nil.\nfunc GetDefaultClass(lister storagev1listers.StorageClassLister) (*storagev1.StorageClass, error) {\n\tlist, err := lister.List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefaultClasses := []*storagev1.StorageClass{}\n\tfor _, class := range list {\n\t\tif IsDefaultAnnotation(class.ObjectMeta) {\n\t\t\tdefaultClasses = append(defaultClasses, class)\n\t\t\tklog.V(4).Infof(\"GetDefaultClass added: %s\", class.Name)\n\t\t}\n\t}\n\n\tif len(defaultClasses) == 0 {\n\t\treturn nil, nil\n\t}\n\n\t// Primary sort by creation timestamp, newest first\n\t// Secondary sort by class name, ascending order\n\tsort.Slice(defaultClasses, func(i, j int) bool {\n\t\tif defaultClasses[i].CreationTimestamp.UnixNano() == defaultClasses[j].CreationTimestamp.UnixNano() {\n\t\t\treturn defaultClasses[i].Name \u003c defaultClasses[j].Name\n\t\t}\n\t\treturn defaultClasses[i].CreationTimestamp.UnixNano() \u003e defaultClasses[j].CreationTimestamp.UnixNano()\n\t})\n\tif len(defaultClasses) \u003e 1 {\n\t\tklog.V(4).Infof(\"%d default StorageClasses were found, choosing the newest: %s\", len(defaultClasses), defaultClasses[0].Name)\n\t}\n\n\treturn defaultClasses[0], nil\n}","line":{"from":39,"to":71}} {"id":100013134,"name":"IsDefaultAnnotation","signature":"func IsDefaultAnnotation(obj metav1.ObjectMeta) bool","file":"pkg/volume/util/storageclass.go","code":"// IsDefaultAnnotation returns a boolean if the default storage class\n// annotation is set\n// TODO: remove Beta when no longer needed\nfunc IsDefaultAnnotation(obj metav1.ObjectMeta) bool {\n\tif obj.Annotations[IsDefaultStorageClassAnnotation] == \"true\" {\n\t\treturn true\n\t}\n\tif obj.Annotations[BetaIsDefaultStorageClassAnnotation] == \"true\" {\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":73,"to":85}} {"id":100013135,"name":"PrepareSafeSubpath","signature":"func (fs *FakeSubpath) PrepareSafeSubpath(subPath Subpath) (newHostPath string, cleanupAction func(), err error)","file":"pkg/volume/util/subpath/subpath.go","code":"// PrepareSafeSubpath is a fake implementation of PrepareSafeSubpath. Always returns\n// newHostPath == subPath.Path\nfunc (fs *FakeSubpath) PrepareSafeSubpath(subPath Subpath) (newHostPath string, cleanupAction func(), err error) {\n\treturn subPath.Path, nil, nil\n}","line":{"from":78,"to":82}} {"id":100013136,"name":"CleanSubPaths","signature":"func (fs *FakeSubpath) CleanSubPaths(podDir string, volumeName string) error","file":"pkg/volume/util/subpath/subpath.go","code":"// CleanSubPaths is a fake implementation of CleanSubPaths. It is a noop\nfunc (fs *FakeSubpath) CleanSubPaths(podDir string, volumeName string) error {\n\treturn nil\n}","line":{"from":84,"to":87}} {"id":100013137,"name":"SafeMakeDir","signature":"func (fs *FakeSubpath) SafeMakeDir(pathname string, base string, perm os.FileMode) error","file":"pkg/volume/util/subpath/subpath.go","code":"// SafeMakeDir is a fake implementation of SafeMakeDir. It is a noop\nfunc (fs *FakeSubpath) SafeMakeDir(pathname string, base string, perm os.FileMode) error {\n\treturn nil\n}","line":{"from":89,"to":92}} {"id":100013138,"name":"New","signature":"func New(mounter mount.Interface) Interface","file":"pkg/volume/util/subpath/subpath_linux.go","code":"// New returns a subpath.Interface for the current system\nfunc New(mounter mount.Interface) Interface {\n\treturn \u0026subpath{\n\t\tmounter: mounter,\n\t}\n}","line":{"from":50,"to":55}} {"id":100013139,"name":"CleanSubPaths","signature":"func (sp *subpath) CleanSubPaths(podDir string, volumeName string) error","file":"pkg/volume/util/subpath/subpath_linux.go","code":"func (sp *subpath) CleanSubPaths(podDir string, volumeName string) error {\n\treturn doCleanSubPaths(sp.mounter, podDir, volumeName)\n}","line":{"from":57,"to":59}} {"id":100013140,"name":"SafeMakeDir","signature":"func (sp *subpath) SafeMakeDir(subdir string, base string, perm os.FileMode) error","file":"pkg/volume/util/subpath/subpath_linux.go","code":"func (sp *subpath) SafeMakeDir(subdir string, base string, perm os.FileMode) error {\n\trealBase, err := filepath.EvalSymlinks(base)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error resolving symlinks in %s: %s\", base, err)\n\t}\n\n\trealFullPath := filepath.Join(realBase, subdir)\n\n\treturn doSafeMakeDir(realFullPath, realBase, perm)\n}","line":{"from":61,"to":70}} {"id":100013141,"name":"PrepareSafeSubpath","signature":"func (sp *subpath) PrepareSafeSubpath(subPath Subpath) (newHostPath string, cleanupAction func(), err error)","file":"pkg/volume/util/subpath/subpath_linux.go","code":"func (sp *subpath) PrepareSafeSubpath(subPath Subpath) (newHostPath string, cleanupAction func(), err error) {\n\tnewHostPath, err = doBindSubPath(sp.mounter, subPath)\n\n\t// There is no action when the container starts. Bind-mount will be cleaned\n\t// when container stops by CleanSubPaths.\n\tcleanupAction = nil\n\treturn newHostPath, cleanupAction, err\n}","line":{"from":72,"to":79}} {"id":100013142,"name":"safeOpenSubPath","signature":"func safeOpenSubPath(mounter mount.Interface, subpath Subpath) (int, error)","file":"pkg/volume/util/subpath/subpath_linux.go","code":"// This implementation is shared between Linux and NsEnter\nfunc safeOpenSubPath(mounter mount.Interface, subpath Subpath) (int, error) {\n\tif !mount.PathWithinBase(subpath.Path, subpath.VolumePath) {\n\t\treturn -1, fmt.Errorf(\"subpath %q not within volume path %q\", subpath.Path, subpath.VolumePath)\n\t}\n\tfd, err := doSafeOpen(subpath.Path, subpath.VolumePath)\n\tif err != nil {\n\t\treturn -1, fmt.Errorf(\"error opening subpath %v: %v\", subpath.Path, err)\n\t}\n\treturn fd, nil\n}","line":{"from":81,"to":91}} {"id":100013143,"name":"prepareSubpathTarget","signature":"func prepareSubpathTarget(mounter mount.Interface, subpath Subpath) (bool, string, error)","file":"pkg/volume/util/subpath/subpath_linux.go","code":"// prepareSubpathTarget creates target for bind-mount of subpath. It returns\n// \"true\" when the target already exists and something is mounted there.\n// Given Subpath must have all paths with already resolved symlinks and with\n// paths relevant to kubelet (when it runs in a container).\n// This function is called also by NsEnterMounter. It works because\n// /var/lib/kubelet is mounted from the host into the container with Kubelet as\n// /var/lib/kubelet too.\nfunc prepareSubpathTarget(mounter mount.Interface, subpath Subpath) (bool, string, error) {\n\t// Early check for already bind-mounted subpath.\n\tbindPathTarget := getSubpathBindTarget(subpath)\n\tnotMount, err := mount.IsNotMountPoint(mounter, bindPathTarget)\n\tif err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn false, \"\", fmt.Errorf(\"error checking path %s for mount: %s\", bindPathTarget, err)\n\t\t}\n\t\t// Ignore ErrorNotExist: the file/directory will be created below if it does not exist yet.\n\t\tnotMount = true\n\t}\n\tif !notMount {\n\t\t// It's already mounted, so check if it's bind-mounted to the same path\n\t\tsamePath, err := checkSubPathFileEqual(subpath, bindPathTarget)\n\t\tif err != nil {\n\t\t\treturn false, \"\", fmt.Errorf(\"error checking subpath mount info for %s: %s\", bindPathTarget, err)\n\t\t}\n\t\tif !samePath {\n\t\t\t// It's already mounted but not what we want, unmount it\n\t\t\tif err = mounter.Unmount(bindPathTarget); err != nil {\n\t\t\t\treturn false, \"\", fmt.Errorf(\"error ummounting %s: %s\", bindPathTarget, err)\n\t\t\t}\n\t\t} else {\n\t\t\t// It's already mounted\n\t\t\tklog.V(5).Infof(\"Skipping bind-mounting subpath %s: already mounted\", bindPathTarget)\n\t\t\treturn true, bindPathTarget, nil\n\t\t}\n\t}\n\n\t// bindPathTarget is in /var/lib/kubelet and thus reachable without any\n\t// translation even to containerized kubelet.\n\tbindParent := filepath.Dir(bindPathTarget)\n\terr = os.MkdirAll(bindParent, 0750)\n\tif err != nil \u0026\u0026 !os.IsExist(err) {\n\t\treturn false, \"\", fmt.Errorf(\"error creating directory %s: %s\", bindParent, err)\n\t}\n\n\tt, err := os.Lstat(subpath.Path)\n\tif err != nil {\n\t\treturn false, \"\", fmt.Errorf(\"lstat %s failed: %s\", subpath.Path, err)\n\t}\n\n\tif t.Mode()\u0026os.ModeDir \u003e 0 {\n\t\tif err = os.Mkdir(bindPathTarget, 0750); err != nil \u0026\u0026 !os.IsExist(err) {\n\t\t\treturn false, \"\", fmt.Errorf(\"error creating directory %s: %s\", bindPathTarget, err)\n\t\t}\n\t} else {\n\t\t// \"/bin/touch \u003cbindPathTarget\u003e\".\n\t\t// A file is enough for all possible targets (symlink, device, pipe,\n\t\t// socket, ...), bind-mounting them into a file correctly changes type\n\t\t// of the target file.\n\t\tif err = ioutil.WriteFile(bindPathTarget, []byte{}, 0640); err != nil {\n\t\t\treturn false, \"\", fmt.Errorf(\"error creating file %s: %s\", bindPathTarget, err)\n\t\t}\n\t}\n\treturn false, bindPathTarget, nil\n}","line":{"from":93,"to":156}} {"id":100013144,"name":"checkSubPathFileEqual","signature":"func checkSubPathFileEqual(subpath Subpath, bindMountTarget string) (bool, error)","file":"pkg/volume/util/subpath/subpath_linux.go","code":"func checkSubPathFileEqual(subpath Subpath, bindMountTarget string) (bool, error) {\n\ts, err := os.Lstat(subpath.Path)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"stat %s failed: %s\", subpath.Path, err)\n\t}\n\n\tt, err := os.Lstat(bindMountTarget)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"lstat %s failed: %s\", bindMountTarget, err)\n\t}\n\n\tif !os.SameFile(s, t) {\n\t\treturn false, nil\n\t}\n\treturn true, nil\n}","line":{"from":158,"to":173}} {"id":100013145,"name":"getSubpathBindTarget","signature":"func getSubpathBindTarget(subpath Subpath) string","file":"pkg/volume/util/subpath/subpath_linux.go","code":"func getSubpathBindTarget(subpath Subpath) string {\n\t// containerName is DNS label, i.e. safe as a directory name.\n\treturn filepath.Join(subpath.PodDir, containerSubPathDirectoryName, subpath.VolumeName, subpath.ContainerName, strconv.Itoa(subpath.VolumeMountIndex))\n}","line":{"from":175,"to":178}} {"id":100013146,"name":"doBindSubPath","signature":"func doBindSubPath(mounter mount.Interface, subpath Subpath) (hostPath string, err error)","file":"pkg/volume/util/subpath/subpath_linux.go","code":"func doBindSubPath(mounter mount.Interface, subpath Subpath) (hostPath string, err error) {\n\t// Linux, kubelet runs on the host:\n\t// - safely open the subpath\n\t// - bind-mount /proc/\u003cpid of kubelet\u003e/fd/\u003cfd\u003e to subpath target\n\t// User can't change /proc/\u003cpid of kubelet\u003e/fd/\u003cfd\u003e to point to a bad place.\n\n\t// Evaluate all symlinks here once for all subsequent functions.\n\tnewVolumePath, err := filepath.EvalSymlinks(subpath.VolumePath)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error resolving symlinks in %q: %v\", subpath.VolumePath, err)\n\t}\n\tnewPath, err := filepath.EvalSymlinks(subpath.Path)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error resolving symlinks in %q: %v\", subpath.Path, err)\n\t}\n\tklog.V(5).Infof(\"doBindSubPath %q (%q) for volumepath %q\", subpath.Path, newPath, subpath.VolumePath)\n\tsubpath.VolumePath = newVolumePath\n\tsubpath.Path = newPath\n\n\tfd, err := safeOpenSubPath(mounter, subpath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer syscall.Close(fd)\n\n\talreadyMounted, bindPathTarget, err := prepareSubpathTarget(mounter, subpath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif alreadyMounted {\n\t\treturn bindPathTarget, nil\n\t}\n\n\tsuccess := false\n\tdefer func() {\n\t\t// Cleanup subpath on error\n\t\tif !success {\n\t\t\tklog.V(4).Infof(\"doBindSubPath() failed for %q, cleaning up subpath\", bindPathTarget)\n\t\t\tif cleanErr := cleanSubPath(mounter, subpath); cleanErr != nil {\n\t\t\t\tklog.Errorf(\"Failed to clean subpath %q: %v\", bindPathTarget, cleanErr)\n\t\t\t}\n\t\t}\n\t}()\n\n\tkubeletPid := os.Getpid()\n\tmountSource := fmt.Sprintf(\"/proc/%d/fd/%v\", kubeletPid, fd)\n\n\t// Do the bind mount\n\toptions := []string{\"bind\"}\n\tmountFlags := []string{\"--no-canonicalize\"}\n\tklog.V(5).Infof(\"bind mounting %q at %q\", mountSource, bindPathTarget)\n\tif err = mounter.MountSensitiveWithoutSystemdWithMountFlags(mountSource, bindPathTarget, \"\" /*fstype*/, options, nil /* sensitiveOptions */, mountFlags); err != nil {\n\t\treturn \"\", fmt.Errorf(\"error mounting %s: %s\", subpath.Path, err)\n\t}\n\tsuccess = true\n\n\tklog.V(3).Infof(\"Bound SubPath %s into %s\", subpath.Path, bindPathTarget)\n\treturn bindPathTarget, nil\n}","line":{"from":180,"to":238}} {"id":100013147,"name":"doCleanSubPaths","signature":"func doCleanSubPaths(mounter mount.Interface, podDir string, volumeName string) error","file":"pkg/volume/util/subpath/subpath_linux.go","code":"// This implementation is shared between Linux and NsEnter\nfunc doCleanSubPaths(mounter mount.Interface, podDir string, volumeName string) error {\n\t// scan /var/lib/kubelet/pods/\u003cuid\u003e/volume-subpaths/\u003cvolume\u003e/*\n\tsubPathDir := filepath.Join(podDir, containerSubPathDirectoryName, volumeName)\n\tklog.V(4).Infof(\"Cleaning up subpath mounts for %s\", subPathDir)\n\n\tcontainerDirs, err := ioutil.ReadDir(subPathDir)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"error reading %s: %s\", subPathDir, err)\n\t}\n\n\tfor _, containerDir := range containerDirs {\n\t\tif !containerDir.IsDir() {\n\t\t\tklog.V(4).Infof(\"Container file is not a directory: %s\", containerDir.Name())\n\t\t\tcontinue\n\t\t}\n\t\tklog.V(4).Infof(\"Cleaning up subpath mounts for container %s\", containerDir.Name())\n\n\t\t// scan /var/lib/kubelet/pods/\u003cuid\u003e/volume-subpaths/\u003cvolume\u003e/\u003ccontainer name\u003e/*\n\t\tfullContainerDirPath := filepath.Join(subPathDir, containerDir.Name())\n\t\t// The original traversal method here was ReadDir, which was not so robust to handle some error such as \"stale NFS file handle\",\n\t\t// so it was replaced with filepath.Walk in a later patch, which can pass through error and handled by the callback WalkFunc.\n\t\t// After go 1.16, WalkDir was introduced, it's more effective than Walk because the callback WalkDirFunc is called before\n\t\t// reading a directory, making it save some time when a container's subPath contains lots of dirs.\n\t\t// See https://github.com/kubernetes/kubernetes/pull/71804 and https://github.com/kubernetes/kubernetes/issues/107667 for more details.\n\t\terr = filepath.WalkDir(fullContainerDirPath, func(path string, info os.DirEntry, _ error) error {\n\t\t\tif path == fullContainerDirPath {\n\t\t\t\t// Skip top level directory\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\t// pass through errors and let doCleanSubPath handle them\n\t\t\tif err = doCleanSubPath(mounter, fullContainerDirPath, filepath.Base(path)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// We need to check that info is not nil. This may happen when the incoming err is not nil due to stale mounts or permission errors.\n\t\t\tif info != nil \u0026\u0026 info.IsDir() {\n\t\t\t\t// skip subdirs of the volume: it only matters the first level to unmount, otherwise it would try to unmount subdir of the volume\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error processing %s: %s\", fullContainerDirPath, err)\n\t\t}\n\n\t\t// Whole container has been processed, remove its directory.\n\t\tif err := os.Remove(fullContainerDirPath); err != nil {\n\t\t\treturn fmt.Errorf(\"error deleting %s: %s\", fullContainerDirPath, err)\n\t\t}\n\t\tklog.V(5).Infof(\"Removed %s\", fullContainerDirPath)\n\t}\n\t// Whole pod volume subpaths have been cleaned up, remove its subpath directory.\n\tif err := os.Remove(subPathDir); err != nil {\n\t\treturn fmt.Errorf(\"error deleting %s: %s\", subPathDir, err)\n\t}\n\tklog.V(5).Infof(\"Removed %s\", subPathDir)\n\n\t// Remove entire subpath directory if it's the last one\n\tpodSubPathDir := filepath.Join(podDir, containerSubPathDirectoryName)\n\tif err := os.Remove(podSubPathDir); err != nil \u0026\u0026 !os.IsExist(err) {\n\t\treturn fmt.Errorf(\"error deleting %s: %s\", podSubPathDir, err)\n\t}\n\tklog.V(5).Infof(\"Removed %s\", podSubPathDir)\n\treturn nil\n}","line":{"from":240,"to":310}} {"id":100013148,"name":"doCleanSubPath","signature":"func doCleanSubPath(mounter mount.Interface, fullContainerDirPath, subPathIndex string) error","file":"pkg/volume/util/subpath/subpath_linux.go","code":"// doCleanSubPath tears down the single subpath bind mount\nfunc doCleanSubPath(mounter mount.Interface, fullContainerDirPath, subPathIndex string) error {\n\t// process /var/lib/kubelet/pods/\u003cuid\u003e/volume-subpaths/\u003cvolume\u003e/\u003ccontainer name\u003e/\u003csubPathName\u003e\n\tklog.V(4).Infof(\"Cleaning up subpath mounts for subpath %v\", subPathIndex)\n\tfullSubPath := filepath.Join(fullContainerDirPath, subPathIndex)\n\n\tif err := mount.CleanupMountPoint(fullSubPath, mounter, true); err != nil {\n\t\treturn fmt.Errorf(\"error cleaning subpath mount %s: %s\", fullSubPath, err)\n\t}\n\n\tklog.V(4).Infof(\"Successfully cleaned subpath directory %s\", fullSubPath)\n\treturn nil\n}","line":{"from":312,"to":324}} {"id":100013149,"name":"cleanSubPath","signature":"func cleanSubPath(mounter mount.Interface, subpath Subpath) error","file":"pkg/volume/util/subpath/subpath_linux.go","code":"// cleanSubPath will teardown the subpath bind mount and any remove any directories if empty\nfunc cleanSubPath(mounter mount.Interface, subpath Subpath) error {\n\tcontainerDir := filepath.Join(subpath.PodDir, containerSubPathDirectoryName, subpath.VolumeName, subpath.ContainerName)\n\n\t// Clean subdir bindmount\n\tif err := doCleanSubPath(mounter, containerDir, strconv.Itoa(subpath.VolumeMountIndex)); err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\n\t// Recusively remove directories if empty\n\tif err := removeEmptyDirs(subpath.PodDir, containerDir); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":326,"to":341}} {"id":100013150,"name":"removeEmptyDirs","signature":"func removeEmptyDirs(baseDir, endDir string) error","file":"pkg/volume/util/subpath/subpath_linux.go","code":"// removeEmptyDirs works backwards from endDir to baseDir and removes each directory\n// if it is empty. It stops once it encounters a directory that has content\nfunc removeEmptyDirs(baseDir, endDir string) error {\n\tif !mount.PathWithinBase(endDir, baseDir) {\n\t\treturn fmt.Errorf(\"endDir %q is not within baseDir %q\", endDir, baseDir)\n\t}\n\n\tfor curDir := endDir; curDir != baseDir; curDir = filepath.Dir(curDir) {\n\t\ts, err := os.Stat(curDir)\n\t\tif err != nil {\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\tklog.V(5).Infof(\"curDir %q doesn't exist, skipping\", curDir)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"error stat %q: %v\", curDir, err)\n\t\t}\n\t\tif !s.IsDir() {\n\t\t\treturn fmt.Errorf(\"path %q not a directory\", curDir)\n\t\t}\n\n\t\terr = os.Remove(curDir)\n\t\tif os.IsExist(err) {\n\t\t\tklog.V(5).Infof(\"Directory %q not empty, not removing\", curDir)\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn fmt.Errorf(\"error removing directory %q: %v\", curDir, err)\n\t\t}\n\t\tklog.V(5).Infof(\"Removed directory %q\", curDir)\n\t}\n\treturn nil\n}","line":{"from":343,"to":373}} {"id":100013151,"name":"doSafeMakeDir","signature":"func doSafeMakeDir(pathname string, base string, perm os.FileMode) error","file":"pkg/volume/util/subpath/subpath_linux.go","code":"// This implementation is shared between Linux and NsEnterMounter. Both pathname\n// and base must be either already resolved symlinks or thet will be resolved in\n// kubelet's mount namespace (in case it runs containerized).\nfunc doSafeMakeDir(pathname string, base string, perm os.FileMode) error {\n\tklog.V(4).Infof(\"Creating directory %q within base %q\", pathname, base)\n\n\tif !mount.PathWithinBase(pathname, base) {\n\t\treturn fmt.Errorf(\"path %s is outside of allowed base %s\", pathname, base)\n\t}\n\n\t// Quick check if the directory already exists\n\ts, err := os.Stat(pathname)\n\tif err == nil {\n\t\t// Path exists\n\t\tif s.IsDir() {\n\t\t\t// The directory already exists. It can be outside of the parent,\n\t\t\t// but there is no race-proof check.\n\t\t\tklog.V(4).Infof(\"Directory %s already exists\", pathname)\n\t\t\treturn nil\n\t\t}\n\t\treturn \u0026os.PathError{Op: \"mkdir\", Path: pathname, Err: syscall.ENOTDIR}\n\t}\n\n\t// Find all existing directories\n\texistingPath, toCreate, err := findExistingPrefix(base, pathname)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error opening directory %s: %s\", pathname, err)\n\t}\n\t// Ensure the existing directory is inside allowed base\n\tfullExistingPath, err := filepath.EvalSymlinks(existingPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error opening directory %s: %s\", existingPath, err)\n\t}\n\tif !mount.PathWithinBase(fullExistingPath, base) {\n\t\treturn fmt.Errorf(\"path %s is outside of allowed base %s\", fullExistingPath, err)\n\t}\n\n\tklog.V(4).Infof(\"%q already exists, %q to create\", fullExistingPath, filepath.Join(toCreate...))\n\tparentFD, err := doSafeOpen(fullExistingPath, base)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot open directory %s: %s\", existingPath, err)\n\t}\n\tchildFD := -1\n\tdefer func() {\n\t\tif parentFD != -1 {\n\t\t\tif err = syscall.Close(parentFD); err != nil {\n\t\t\t\tklog.V(4).Infof(\"Closing FD %v failed for safemkdir(%v): %v\", parentFD, pathname, err)\n\t\t\t}\n\t\t}\n\t\tif childFD != -1 {\n\t\t\tif err = syscall.Close(childFD); err != nil {\n\t\t\t\tklog.V(4).Infof(\"Closing FD %v failed for safemkdir(%v): %v\", childFD, pathname, err)\n\t\t\t}\n\t\t}\n\t}()\n\n\tcurrentPath := fullExistingPath\n\t// create the directories one by one, making sure nobody can change\n\t// created directory into symlink.\n\tfor _, dir := range toCreate {\n\t\tcurrentPath = filepath.Join(currentPath, dir)\n\t\tklog.V(4).Infof(\"Creating %s\", dir)\n\t\terr = syscall.Mkdirat(parentFD, currentPath, uint32(perm))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"cannot create directory %s: %s\", currentPath, err)\n\t\t}\n\t\t// Dive into the created directory\n\t\tchildFD, err = syscall.Openat(parentFD, dir, nofollowFlags|unix.O_CLOEXEC, 0)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"cannot open %s: %s\", currentPath, err)\n\t\t}\n\t\t// We can be sure that childFD is safe to use. It could be changed\n\t\t// by user after Mkdirat() and before Openat(), however:\n\t\t// - it could not be changed to symlink - we use nofollowFlags\n\t\t// - it could be changed to a file (or device, pipe, socket, ...)\n\t\t// but either subsequent Mkdirat() fails or we mount this file\n\t\t// to user's container. Security is no violated in both cases\n\t\t// and user either gets error or the file that it can already access.\n\n\t\tif err = syscall.Close(parentFD); err != nil {\n\t\t\tklog.V(4).Infof(\"Closing FD %v failed for safemkdir(%v): %v\", parentFD, pathname, err)\n\t\t}\n\t\tparentFD = childFD\n\t\tchildFD = -1\n\n\t\t// Everything was created. mkdirat(..., perm) above was affected by current\n\t\t// umask and we must apply the right permissions to the all created directory.\n\t\t// (that's the one that will be available to the container as subpath)\n\t\t// so user can read/write it.\n\t\t// parentFD is the last created directory.\n\n\t\t// Translate perm (os.FileMode) to uint32 that fchmod() expects\n\t\tkernelPerm := uint32(perm \u0026 os.ModePerm)\n\t\tif perm\u0026os.ModeSetgid \u003e 0 {\n\t\t\tkernelPerm |= syscall.S_ISGID\n\t\t}\n\t\tif perm\u0026os.ModeSetuid \u003e 0 {\n\t\t\tkernelPerm |= syscall.S_ISUID\n\t\t}\n\t\tif perm\u0026os.ModeSticky \u003e 0 {\n\t\t\tkernelPerm |= syscall.S_ISVTX\n\t\t}\n\t\tif err = syscall.Fchmod(parentFD, kernelPerm); err != nil {\n\t\t\treturn fmt.Errorf(\"chmod %q failed: %s\", currentPath, err)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":375,"to":483}} {"id":100013152,"name":"findExistingPrefix","signature":"func findExistingPrefix(base, pathname string) (string, []string, error)","file":"pkg/volume/util/subpath/subpath_linux.go","code":"// findExistingPrefix finds prefix of pathname that exists. In addition, it\n// returns list of remaining directories that don't exist yet.\nfunc findExistingPrefix(base, pathname string) (string, []string, error) {\n\trel, err := filepath.Rel(base, pathname)\n\tif err != nil {\n\t\treturn base, nil, err\n\t}\n\tdirs := strings.Split(rel, string(filepath.Separator))\n\n\t// Do OpenAt in a loop to find the first non-existing dir. Resolve symlinks.\n\t// This should be faster than looping through all dirs and calling os.Stat()\n\t// on each of them, as the symlinks are resolved only once with OpenAt().\n\tcurrentPath := base\n\tfd, err := syscall.Open(currentPath, syscall.O_RDONLY|syscall.O_CLOEXEC, 0)\n\tif err != nil {\n\t\treturn pathname, nil, fmt.Errorf(\"error opening %s: %s\", currentPath, err)\n\t}\n\tdefer func() {\n\t\tif err = syscall.Close(fd); err != nil {\n\t\t\tklog.V(4).Infof(\"Closing FD %v failed for findExistingPrefix(%v): %v\", fd, pathname, err)\n\t\t}\n\t}()\n\tfor i, dir := range dirs {\n\t\t// Using O_PATH here will prevent hangs in case user replaces directory with\n\t\t// fifo\n\t\tchildFD, err := syscall.Openat(fd, dir, unix.O_PATH|unix.O_CLOEXEC, 0)\n\t\tif err != nil {\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\treturn currentPath, dirs[i:], nil\n\t\t\t}\n\t\t\treturn base, nil, err\n\t\t}\n\t\tif err = syscall.Close(fd); err != nil {\n\t\t\tklog.V(4).Infof(\"Closing FD %v failed for findExistingPrefix(%v): %v\", fd, pathname, err)\n\t\t}\n\t\tfd = childFD\n\t\tcurrentPath = filepath.Join(currentPath, dir)\n\t}\n\treturn pathname, []string{}, nil\n}","line":{"from":485,"to":524}} {"id":100013153,"name":"doSafeOpen","signature":"func doSafeOpen(pathname string, base string) (int, error)","file":"pkg/volume/util/subpath/subpath_linux.go","code":"// This implementation is shared between Linux and NsEnterMounter\n// Open path and return its fd.\n// Symlinks are disallowed (pathname must already resolve symlinks),\n// and the path must be within the base directory.\nfunc doSafeOpen(pathname string, base string) (int, error) {\n\tpathname = filepath.Clean(pathname)\n\tbase = filepath.Clean(base)\n\n\t// Calculate segments to follow\n\tsubpath, err := filepath.Rel(base, pathname)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\tsegments := strings.Split(subpath, string(filepath.Separator))\n\n\t// Assumption: base is the only directory that we have under control.\n\t// Base dir is not allowed to be a symlink.\n\tparentFD, err := syscall.Open(base, nofollowFlags|unix.O_CLOEXEC, 0)\n\tif err != nil {\n\t\treturn -1, fmt.Errorf(\"cannot open directory %s: %s\", base, err)\n\t}\n\tdefer func() {\n\t\tif parentFD != -1 {\n\t\t\tif err = syscall.Close(parentFD); err != nil {\n\t\t\t\tklog.V(4).Infof(\"Closing FD %v failed for safeopen(%v): %v\", parentFD, pathname, err)\n\t\t\t}\n\t\t}\n\t}()\n\n\tchildFD := -1\n\tdefer func() {\n\t\tif childFD != -1 {\n\t\t\tif err = syscall.Close(childFD); err != nil {\n\t\t\t\tklog.V(4).Infof(\"Closing FD %v failed for safeopen(%v): %v\", childFD, pathname, err)\n\t\t\t}\n\t\t}\n\t}()\n\n\tcurrentPath := base\n\n\t// Follow the segments one by one using openat() to make\n\t// sure the user cannot change already existing directories into symlinks.\n\tfor _, seg := range segments {\n\t\tvar deviceStat unix.Stat_t\n\n\t\tcurrentPath = filepath.Join(currentPath, seg)\n\t\tif !mount.PathWithinBase(currentPath, base) {\n\t\t\treturn -1, fmt.Errorf(\"path %s is outside of allowed base %s\", currentPath, base)\n\t\t}\n\n\t\t// Trigger auto mount if it's an auto-mounted directory, ignore error if not a directory.\n\t\t// Notice the trailing slash is mandatory, see \"automount\" in openat(2) and open_by_handle_at(2).\n\t\tunix.Fstatat(parentFD, seg+\"/\", \u0026deviceStat, unix.AT_SYMLINK_NOFOLLOW)\n\n\t\tklog.V(5).Infof(\"Opening path %s\", currentPath)\n\t\tchildFD, err = syscall.Openat(parentFD, seg, openFDFlags|unix.O_CLOEXEC, 0)\n\t\tif err != nil {\n\t\t\treturn -1, fmt.Errorf(\"cannot open %s: %s\", currentPath, err)\n\t\t}\n\n\t\terr := unix.Fstat(childFD, \u0026deviceStat)\n\t\tif err != nil {\n\t\t\treturn -1, fmt.Errorf(\"error running fstat on %s with %v\", currentPath, err)\n\t\t}\n\t\tfileFmt := deviceStat.Mode \u0026 syscall.S_IFMT\n\t\tif fileFmt == syscall.S_IFLNK {\n\t\t\treturn -1, fmt.Errorf(\"unexpected symlink found %s\", currentPath)\n\t\t}\n\n\t\t// Close parentFD\n\t\tif err = syscall.Close(parentFD); err != nil {\n\t\t\treturn -1, fmt.Errorf(\"closing fd for %q failed: %v\", filepath.Dir(currentPath), err)\n\t\t}\n\t\t// Set child to new parent\n\t\tparentFD = childFD\n\t\tchildFD = -1\n\t}\n\n\t// We made it to the end, return this fd, don't close it\n\tfinalFD := parentFD\n\tparentFD = -1\n\n\treturn finalFD, nil\n}","line":{"from":526,"to":609}} {"id":100013154,"name":"New","signature":"func New(mount.Interface) Interface","file":"pkg/volume/util/subpath/subpath_unsupported.go","code":"// New returns a subpath.Interface for the current system.\nfunc New(mount.Interface) Interface {\n\treturn \u0026subpath{}\n}","line":{"from":34,"to":37}} {"id":100013155,"name":"NewNSEnter","signature":"func NewNSEnter(mounter mount.Interface, ne *nsenter.Nsenter, rootDir string) Interface","file":"pkg/volume/util/subpath/subpath_unsupported.go","code":"// NewNSEnter is to satisfy the compiler for having NewSubpathNSEnter exist for all\n// OS choices. however, NSEnter is only valid on Linux\nfunc NewNSEnter(mounter mount.Interface, ne *nsenter.Nsenter, rootDir string) Interface {\n\treturn nil\n}","line":{"from":39,"to":43}} {"id":100013156,"name":"PrepareSafeSubpath","signature":"func (sp *subpath) PrepareSafeSubpath(subPath Subpath) (newHostPath string, cleanupAction func(), err error)","file":"pkg/volume/util/subpath/subpath_unsupported.go","code":"func (sp *subpath) PrepareSafeSubpath(subPath Subpath) (newHostPath string, cleanupAction func(), err error) {\n\treturn subPath.Path, nil, errUnsupported\n}","line":{"from":45,"to":47}} {"id":100013157,"name":"CleanSubPaths","signature":"func (sp *subpath) CleanSubPaths(podDir string, volumeName string) error","file":"pkg/volume/util/subpath/subpath_unsupported.go","code":"func (sp *subpath) CleanSubPaths(podDir string, volumeName string) error {\n\treturn errUnsupported\n}","line":{"from":49,"to":51}} {"id":100013158,"name":"SafeMakeDir","signature":"func (sp *subpath) SafeMakeDir(pathname string, base string, perm os.FileMode) error","file":"pkg/volume/util/subpath/subpath_unsupported.go","code":"func (sp *subpath) SafeMakeDir(pathname string, base string, perm os.FileMode) error {\n\treturn errUnsupported\n}","line":{"from":53,"to":55}} {"id":100013159,"name":"New","signature":"func New(mount.Interface) Interface","file":"pkg/volume/util/subpath/subpath_windows.go","code":"// New returns a subpath.Interface for the current system\nfunc New(mount.Interface) Interface {\n\treturn \u0026subpath{}\n}","line":{"from":41,"to":44}} {"id":100013160,"name":"NewNSEnter","signature":"func NewNSEnter(mounter mount.Interface, ne *nsenter.Nsenter, rootDir string) Interface","file":"pkg/volume/util/subpath/subpath_windows.go","code":"// NewNSEnter is to satisfy the compiler for having NewSubpathNSEnter exist for all\n// OS choices. however, NSEnter is only valid on Linux\nfunc NewNSEnter(mounter mount.Interface, ne *nsenter.Nsenter, rootDir string) Interface {\n\treturn nil\n}","line":{"from":46,"to":50}} {"id":100013161,"name":"isDriveLetterorEmptyPath","signature":"func isDriveLetterorEmptyPath(path string) bool","file":"pkg/volume/util/subpath/subpath_windows.go","code":"// isDriveLetterPath returns true if the given path is empty or it ends with \":\" or \":\\\" or \":\\\\\"\nfunc isDriveLetterorEmptyPath(path string) bool {\n\tif path == \"\" || strings.HasSuffix(path, \":\\\\\\\\\") || strings.HasSuffix(path, \":\") || strings.HasSuffix(path, \":\\\\\") {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":52,"to":58}} {"id":100013162,"name":"isDeviceOrUncPath","signature":"func isDeviceOrUncPath(path string) bool","file":"pkg/volume/util/subpath/subpath_windows.go","code":"// isVolumePrefix returns true if the given path name starts with \"Volume\" or volume prefix including\n// \"\\\\.\\\", \"\\\\?\\\" for device path or \"UNC\" or \"\\\\\" for UNC path. Otherwise, it returns false.\nfunc isDeviceOrUncPath(path string) bool {\n\tif strings.HasPrefix(path, \"Volume\") || strings.HasPrefix(path, \"\\\\\\\\?\\\\\") || strings.HasPrefix(path, \"\\\\\\\\.\\\\\") || strings.HasPrefix(path, \"UNC\") {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":60,"to":67}} {"id":100013163,"name":"getUpperPath","signature":"func getUpperPath(path string) string","file":"pkg/volume/util/subpath/subpath_windows.go","code":"// getUpperPath removes the last level of directory.\nfunc getUpperPath(path string) string {\n\tsep := fmt.Sprintf(\"%c\", filepath.Separator)\n\tupperpath := strings.TrimSuffix(path, sep)\n\treturn filepath.Dir(upperpath)\n}","line":{"from":69,"to":74}} {"id":100013164,"name":"isLinkPath","signature":"func isLinkPath(path string) (bool, error)","file":"pkg/volume/util/subpath/subpath_windows.go","code":"// Check whether a directory/file is a link type or not\n// LinkType could be SymbolicLink, Junction, or HardLink\nfunc isLinkPath(path string) (bool, error) {\n\tcmd := fmt.Sprintf(\"(Get-Item -LiteralPath %q).LinkType\", path)\n\toutput, err := exec.Command(\"powershell\", \"/c\", cmd).CombinedOutput()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif strings.TrimSpace(string(output)) != \"\" {\n\t\treturn true, nil\n\t}\n\treturn false, nil\n}","line":{"from":76,"to":88}} {"id":100013165,"name":"evalSymlink","signature":"func evalSymlink(path string) (string, error)","file":"pkg/volume/util/subpath/subpath_windows.go","code":"// evalSymlink returns the path name after the evaluation of any symbolic links.\n// If the path after evaluation is a device path or network connection, the original path is returned\nfunc evalSymlink(path string) (string, error) {\n\tpath = mount.NormalizeWindowsPath(path)\n\tif isDeviceOrUncPath(path) || isDriveLetterorEmptyPath(path) {\n\t\tklog.V(4).Infof(\"Path '%s' is not a symlink, return its original form.\", path)\n\t\treturn path, nil\n\t}\n\tupperpath := path\n\tbase := \"\"\n\tfor i := 0; i \u003c MaxPathLength; i++ {\n\t\tisLink, err := isLinkPath(upperpath)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif isLink {\n\t\t\tbreak\n\t\t}\n\t\t// continue to check next layer\n\t\tbase = filepath.Join(filepath.Base(upperpath), base)\n\t\tupperpath = getUpperPath(upperpath)\n\t\tif isDriveLetterorEmptyPath(upperpath) {\n\t\t\tklog.V(4).Infof(\"Path '%s' is not a symlink, return its original form.\", path)\n\t\t\treturn path, nil\n\t\t}\n\t}\n\t// This command will give the target path of a given symlink\n\t// The -Force parameter will allow Get-Item to also evaluate hidden folders, like AppData.\n\tcmd := fmt.Sprintf(\"(Get-Item -Force -LiteralPath %q).Target\", upperpath)\n\toutput, err := exec.Command(\"powershell\", \"/c\", cmd).CombinedOutput()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tklog.V(4).Infof(\"evaluate path %s: symlink from %s to %s\", path, upperpath, string(output))\n\tlinkedPath := strings.TrimSpace(string(output))\n\tif linkedPath == \"\" || isDeviceOrUncPath(linkedPath) {\n\t\tklog.V(4).Infof(\"Path '%s' has a target %s. Return its original form.\", path, linkedPath)\n\t\treturn path, nil\n\t}\n\t// If the target is not an absolute path, join iit with the current upperpath\n\tif !filepath.IsAbs(linkedPath) {\n\t\tlinkedPath = filepath.Join(getUpperPath(upperpath), linkedPath)\n\t}\n\tnextLink, err := evalSymlink(linkedPath)\n\tif err != nil {\n\t\treturn path, err\n\t}\n\treturn filepath.Join(nextLink, base), nil\n}","line":{"from":90,"to":138}} {"id":100013166,"name":"lockAndCheckSubPath","signature":"func lockAndCheckSubPath(volumePath, hostPath string) ([]uintptr, error)","file":"pkg/volume/util/subpath/subpath_windows.go","code":"// check whether hostPath is within volume path\n// this func will lock all intermediate subpath directories, need to close handle outside of this func after container started\nfunc lockAndCheckSubPath(volumePath, hostPath string) ([]uintptr, error) {\n\tif len(volumePath) == 0 || len(hostPath) == 0 {\n\t\treturn []uintptr{}, nil\n\t}\n\n\tfinalSubPath, err := evalSymlink(hostPath)\n\tif err != nil {\n\t\treturn []uintptr{}, fmt.Errorf(\"cannot evaluate link %s: %s\", hostPath, err)\n\t}\n\n\tfinalVolumePath, err := evalSymlink(volumePath)\n\tif err != nil {\n\t\treturn []uintptr{}, fmt.Errorf(\"cannot read link %s: %s\", volumePath, err)\n\t}\n\n\treturn lockAndCheckSubPathWithoutSymlink(finalVolumePath, finalSubPath)\n}","line":{"from":140,"to":158}} {"id":100013167,"name":"lockAndCheckSubPathWithoutSymlink","signature":"func lockAndCheckSubPathWithoutSymlink(volumePath, subPath string) ([]uintptr, error)","file":"pkg/volume/util/subpath/subpath_windows.go","code":"// lock all intermediate subPath directories and check they are all within volumePath\n// volumePath \u0026 subPath should not contain any symlink, otherwise it will return error\nfunc lockAndCheckSubPathWithoutSymlink(volumePath, subPath string) ([]uintptr, error) {\n\tif len(volumePath) == 0 || len(subPath) == 0 {\n\t\treturn []uintptr{}, nil\n\t}\n\n\t// get relative path to volumePath\n\trelSubPath, err := filepath.Rel(volumePath, subPath)\n\tif err != nil {\n\t\treturn []uintptr{}, fmt.Errorf(\"Rel(%s, %s) error: %v\", volumePath, subPath, err)\n\t}\n\tif mount.StartsWithBackstep(relSubPath) {\n\t\treturn []uintptr{}, fmt.Errorf(\"SubPath %q not within volume path %q\", subPath, volumePath)\n\t}\n\n\tif relSubPath == \".\" {\n\t\t// volumePath and subPath are equal\n\t\treturn []uintptr{}, nil\n\t}\n\n\tfileHandles := []uintptr{}\n\tvar errorResult error\n\n\tcurrentFullPath := volumePath\n\tdirs := strings.Split(relSubPath, string(os.PathSeparator))\n\tfor _, dir := range dirs {\n\t\t// lock intermediate subPath directory first\n\t\tcurrentFullPath = filepath.Join(currentFullPath, dir)\n\t\thandle, err := lockPath(currentFullPath)\n\t\tif err != nil {\n\t\t\terrorResult = fmt.Errorf(\"cannot lock path %s: %s\", currentFullPath, err)\n\t\t\tbreak\n\t\t}\n\t\tfileHandles = append(fileHandles, handle)\n\n\t\t// make sure intermediate subPath directory does not contain symlink any more\n\t\tstat, err := os.Lstat(currentFullPath)\n\t\tif err != nil {\n\t\t\terrorResult = fmt.Errorf(\"Lstat(%q) error: %v\", currentFullPath, err)\n\t\t\tbreak\n\t\t}\n\t\tif stat.Mode()\u0026os.ModeSymlink != 0 {\n\t\t\terrorResult = fmt.Errorf(\"subpath %q is an unexpected symlink after EvalSymlinks\", currentFullPath)\n\t\t\tbreak\n\t\t}\n\n\t\tif !mount.PathWithinBase(currentFullPath, volumePath) {\n\t\t\terrorResult = fmt.Errorf(\"SubPath %q not within volume path %q\", currentFullPath, volumePath)\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn fileHandles, errorResult\n}","line":{"from":160,"to":214}} {"id":100013168,"name":"unlockPath","signature":"func unlockPath(fileHandles []uintptr)","file":"pkg/volume/util/subpath/subpath_windows.go","code":"// unlockPath unlock directories\nfunc unlockPath(fileHandles []uintptr) {\n\tif fileHandles != nil {\n\t\tfor _, handle := range fileHandles {\n\t\t\tsyscall.CloseHandle(syscall.Handle(handle))\n\t\t}\n\t}\n}","line":{"from":216,"to":223}} {"id":100013169,"name":"lockPath","signature":"func lockPath(path string) (uintptr, error)","file":"pkg/volume/util/subpath/subpath_windows.go","code":"// lockPath locks a directory or symlink, return handle, exec \"syscall.CloseHandle(handle)\" to unlock the path\nfunc lockPath(path string) (uintptr, error) {\n\tif len(path) == 0 {\n\t\treturn uintptr(syscall.InvalidHandle), syscall.ERROR_FILE_NOT_FOUND\n\t}\n\tpathp, err := syscall.UTF16PtrFromString(path)\n\tif err != nil {\n\t\treturn uintptr(syscall.InvalidHandle), err\n\t}\n\taccess := uint32(syscall.GENERIC_READ)\n\tsharemode := uint32(syscall.FILE_SHARE_READ)\n\tcreatemode := uint32(syscall.OPEN_EXISTING)\n\tflags := uint32(syscall.FILE_FLAG_BACKUP_SEMANTICS | syscall.FILE_FLAG_OPEN_REPARSE_POINT)\n\tfd, err := syscall.CreateFile(pathp, access, sharemode, nil, createmode, flags, 0)\n\treturn uintptr(fd), err\n}","line":{"from":225,"to":240}} {"id":100013170,"name":"PrepareSafeSubpath","signature":"func (sp *subpath) PrepareSafeSubpath(subPath Subpath) (newHostPath string, cleanupAction func(), err error)","file":"pkg/volume/util/subpath/subpath_windows.go","code":"// Lock all directories in subPath and check they're not symlinks.\nfunc (sp *subpath) PrepareSafeSubpath(subPath Subpath) (newHostPath string, cleanupAction func(), err error) {\n\thandles, err := lockAndCheckSubPath(subPath.VolumePath, subPath.Path)\n\n\t// Unlock the directories when the container starts\n\tcleanupAction = func() {\n\t\tunlockPath(handles)\n\t}\n\treturn subPath.Path, cleanupAction, err\n}","line":{"from":242,"to":251}} {"id":100013171,"name":"CleanSubPaths","signature":"func (sp *subpath) CleanSubPaths(podDir string, volumeName string) error","file":"pkg/volume/util/subpath/subpath_windows.go","code":"// No bind-mounts for subpaths are necessary on Windows\nfunc (sp *subpath) CleanSubPaths(podDir string, volumeName string) error {\n\treturn nil\n}","line":{"from":253,"to":256}} {"id":100013172,"name":"SafeMakeDir","signature":"func (sp *subpath) SafeMakeDir(subdir string, base string, perm os.FileMode) error","file":"pkg/volume/util/subpath/subpath_windows.go","code":"// SafeMakeDir makes sure that the created directory does not escape given base directory mis-using symlinks.\nfunc (sp *subpath) SafeMakeDir(subdir string, base string, perm os.FileMode) error {\n\trealBase, err := evalSymlink(base)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error resolving symlinks in %s: %s\", base, err)\n\t}\n\n\trealFullPath := filepath.Join(realBase, subdir)\n\treturn doSafeMakeDir(realFullPath, realBase, perm)\n}","line":{"from":258,"to":267}} {"id":100013173,"name":"doSafeMakeDir","signature":"func doSafeMakeDir(pathname string, base string, perm os.FileMode) error","file":"pkg/volume/util/subpath/subpath_windows.go","code":"func doSafeMakeDir(pathname string, base string, perm os.FileMode) error {\n\tklog.V(4).Infof(\"Creating directory %q within base %q\", pathname, base)\n\n\tif !mount.PathWithinBase(pathname, base) {\n\t\treturn fmt.Errorf(\"path %s is outside of allowed base %s\", pathname, base)\n\t}\n\n\t// Quick check if the directory already exists\n\ts, err := os.Stat(pathname)\n\tif err == nil {\n\t\t// Path exists\n\t\tif s.IsDir() {\n\t\t\t// The directory already exists. It can be outside of the parent,\n\t\t\t// but there is no race-proof check.\n\t\t\tklog.V(4).Infof(\"Directory %s already exists\", pathname)\n\t\t\treturn nil\n\t\t}\n\t\treturn \u0026os.PathError{Op: \"mkdir\", Path: pathname, Err: syscall.ENOTDIR}\n\t}\n\n\t// Find all existing directories\n\texistingPath, toCreate, err := findExistingPrefix(base, pathname)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error opening directory %s: %s\", pathname, err)\n\t}\n\tif len(toCreate) == 0 {\n\t\treturn nil\n\t}\n\n\t// Ensure the existing directory is inside allowed base\n\tfullExistingPath, err := evalSymlink(existingPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error opening existing directory %s: %s\", existingPath, err)\n\t}\n\tfullBasePath, err := evalSymlink(base)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot read link %s: %s\", base, err)\n\t}\n\tif !mount.PathWithinBase(fullExistingPath, fullBasePath) {\n\t\treturn fmt.Errorf(\"path %s is outside of allowed base %s\", fullExistingPath, err)\n\t}\n\n\t// lock all intermediate directories from fullBasePath to fullExistingPath (top to bottom)\n\tfileHandles, err := lockAndCheckSubPathWithoutSymlink(fullBasePath, fullExistingPath)\n\tdefer unlockPath(fileHandles)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tklog.V(4).Infof(\"%q already exists, %q to create\", fullExistingPath, filepath.Join(toCreate...))\n\tcurrentPath := fullExistingPath\n\t// create the directories one by one, making sure nobody can change\n\t// created directory into symlink by lock that directory immediately\n\tfor _, dir := range toCreate {\n\t\tcurrentPath = filepath.Join(currentPath, dir)\n\t\tklog.V(4).Infof(\"Creating %s\", dir)\n\t\tif err := os.Mkdir(currentPath, perm); err != nil {\n\t\t\treturn fmt.Errorf(\"cannot create directory %s: %s\", currentPath, err)\n\t\t}\n\t\thandle, err := lockPath(currentPath)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"cannot lock path %s: %s\", currentPath, err)\n\t\t}\n\t\tdefer syscall.CloseHandle(syscall.Handle(handle))\n\t\t// make sure newly created directory does not contain symlink after lock\n\t\tstat, err := os.Lstat(currentPath)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Lstat(%q) error: %v\", currentPath, err)\n\t\t}\n\t\tif stat.Mode()\u0026os.ModeSymlink != 0 {\n\t\t\treturn fmt.Errorf(\"subpath %q is an unexpected symlink after Mkdir\", currentPath)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":269,"to":344}} {"id":100013174,"name":"findExistingPrefix","signature":"func findExistingPrefix(base, pathname string) (string, []string, error)","file":"pkg/volume/util/subpath/subpath_windows.go","code":"// findExistingPrefix finds prefix of pathname that exists. In addition, it\n// returns list of remaining directories that don't exist yet.\nfunc findExistingPrefix(base, pathname string) (string, []string, error) {\n\trel, err := filepath.Rel(base, pathname)\n\tif err != nil {\n\t\treturn base, nil, err\n\t}\n\n\tif mount.StartsWithBackstep(rel) {\n\t\treturn base, nil, fmt.Errorf(\"pathname(%s) is not within base(%s)\", pathname, base)\n\t}\n\n\tif rel == \".\" {\n\t\t// base and pathname are equal\n\t\treturn pathname, []string{}, nil\n\t}\n\n\tdirs := strings.Split(rel, string(filepath.Separator))\n\n\tvar parent string\n\tcurrentPath := base\n\tfor i, dir := range dirs {\n\t\tparent = currentPath\n\t\tcurrentPath = filepath.Join(parent, dir)\n\t\tif _, err := os.Lstat(currentPath); err != nil {\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\treturn parent, dirs[i:], nil\n\t\t\t}\n\t\t\treturn base, nil, err\n\t\t}\n\t}\n\n\treturn pathname, []string{}, nil\n}","line":{"from":346,"to":379}} {"id":100013175,"name":"NewOperationContext","signature":"func NewOperationContext(eventErr, detailedErr error, migrated bool) OperationContext","file":"pkg/volume/util/types/types.go","code":"func NewOperationContext(eventErr, detailedErr error, migrated bool) OperationContext {\n\treturn OperationContext{\n\t\tEventErr: eventErr,\n\t\tDetailedErr: detailedErr,\n\t\tMigrated: migrated,\n\t}\n}","line":{"from":50,"to":56}} {"id":100013176,"name":"Run","signature":"func (o *GeneratedOperations) Run() (eventErr, detailedErr error)","file":"pkg/volume/util/types/types.go","code":"// Run executes the operations and its supporting functions\nfunc (o *GeneratedOperations) Run() (eventErr, detailedErr error) {\n\tvar context OperationContext\n\tif o.CompleteFunc != nil {\n\t\tc := CompleteFuncParam{\n\t\t\tErr: \u0026context.DetailedErr,\n\t\t\tMigrated: \u0026context.Migrated,\n\t\t}\n\t\tdefer o.CompleteFunc(c)\n\t}\n\tif o.EventRecorderFunc != nil {\n\t\tdefer o.EventRecorderFunc(\u0026eventErr)\n\t}\n\t// Handle panic, if any, from operationFunc()\n\tdefer runtime.RecoverFromPanic(\u0026detailedErr)\n\n\tcontext = o.OperationFunc()\n\treturn context.EventErr, context.DetailedErr\n}","line":{"from":63,"to":81}} {"id":100013177,"name":"Error","signature":"func (err *FailedPrecondition) Error() string","file":"pkg/volume/util/types/types.go","code":"func (err *FailedPrecondition) Error() string {\n\treturn err.msg\n}","line":{"from":89,"to":91}} {"id":100013178,"name":"NewFailedPreconditionError","signature":"func NewFailedPreconditionError(msg string) *FailedPrecondition","file":"pkg/volume/util/types/types.go","code":"// NewFailedPreconditionError returns a new FailedPrecondition error instance\nfunc NewFailedPreconditionError(msg string) *FailedPrecondition {\n\treturn \u0026FailedPrecondition{msg: msg}\n}","line":{"from":93,"to":96}} {"id":100013179,"name":"IsFailedPreconditionError","signature":"func IsFailedPreconditionError(err error) bool","file":"pkg/volume/util/types/types.go","code":"// IsFailedPreconditionError checks if given error is of type that indicates\n// operation failed with precondition\nfunc IsFailedPreconditionError(err error) bool {\n\tvar failedPreconditionError *FailedPrecondition\n\treturn errors.As(err, \u0026failedPreconditionError)\n}","line":{"from":98,"to":103}} {"id":100013180,"name":"Error","signature":"func (err *TransientOperationFailure) Error() string","file":"pkg/volume/util/types/types.go","code":"func (err *TransientOperationFailure) Error() string {\n\treturn err.msg\n}","line":{"from":111,"to":113}} {"id":100013181,"name":"NewTransientOperationFailure","signature":"func NewTransientOperationFailure(msg string) *TransientOperationFailure","file":"pkg/volume/util/types/types.go","code":"// NewTransientOperationFailure creates an instance of TransientOperationFailure error\nfunc NewTransientOperationFailure(msg string) *TransientOperationFailure {\n\treturn \u0026TransientOperationFailure{msg: msg}\n}","line":{"from":115,"to":118}} {"id":100013182,"name":"Error","signature":"func (err *UncertainProgressError) Error() string","file":"pkg/volume/util/types/types.go","code":"func (err *UncertainProgressError) Error() string {\n\treturn err.msg\n}","line":{"from":126,"to":128}} {"id":100013183,"name":"NewUncertainProgressError","signature":"func NewUncertainProgressError(msg string) *UncertainProgressError","file":"pkg/volume/util/types/types.go","code":"// NewUncertainProgressError creates an instance of UncertainProgressError type\nfunc NewUncertainProgressError(msg string) *UncertainProgressError {\n\treturn \u0026UncertainProgressError{msg: msg}\n}","line":{"from":130,"to":133}} {"id":100013184,"name":"IsOperationFinishedError","signature":"func IsOperationFinishedError(err error) bool","file":"pkg/volume/util/types/types.go","code":"// IsOperationFinishedError checks if given error is of type that indicates\n// operation is finished with a FINAL error.\nfunc IsOperationFinishedError(err error) bool {\n\tif _, ok := err.(*UncertainProgressError); ok {\n\t\treturn false\n\t}\n\tif _, ok := err.(*TransientOperationFailure); ok {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":135,"to":145}} {"id":100013185,"name":"IsFilesystemMismatchError","signature":"func IsFilesystemMismatchError(err error) bool","file":"pkg/volume/util/types/types.go","code":"// IsFilesystemMismatchError checks if mount failed because requested filesystem\n// on PVC and actual filesystem on disk did not match\nfunc IsFilesystemMismatchError(err error) bool {\n\tmountError := mount.MountError{}\n\treturn errors.As(err, \u0026mountError) \u0026\u0026 mountError.Type == mount.FilesystemMismatch\n}","line":{"from":147,"to":152}} {"id":100013186,"name":"IsUncertainProgressError","signature":"func IsUncertainProgressError(err error) bool","file":"pkg/volume/util/types/types.go","code":"// IsUncertainProgressError checks if given error is of type that indicates\n// operation might be in-progress in background.\nfunc IsUncertainProgressError(err error) bool {\n\tif _, ok := err.(*UncertainProgressError); ok {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":154,"to":161}} {"id":100013187,"name":"IsReady","signature":"func IsReady(dir string) bool","file":"pkg/volume/util/util.go","code":"// IsReady checks for the existence of a regular file\n// called 'ready' in the given directory and returns\n// true if that file exists.\nfunc IsReady(dir string) bool {\n\treadyFile := filepath.Join(dir, readyFileName)\n\ts, err := os.Stat(readyFile)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tif !s.Mode().IsRegular() {\n\t\tklog.Errorf(\"ready-file is not a file: %s\", readyFile)\n\t\treturn false\n\t}\n\n\treturn true\n}","line":{"from":83,"to":99}} {"id":100013188,"name":"SetReady","signature":"func SetReady(dir string)","file":"pkg/volume/util/util.go","code":"// SetReady creates a file called 'ready' in the given\n// directory. It logs an error if the file cannot be\n// created.\nfunc SetReady(dir string) {\n\tif err := os.MkdirAll(dir, 0750); err != nil \u0026\u0026 !os.IsExist(err) {\n\t\tklog.Errorf(\"Can't mkdir %s: %v\", dir, err)\n\t\treturn\n\t}\n\n\treadyFile := filepath.Join(dir, readyFileName)\n\tfile, err := os.Create(readyFile)\n\tif err != nil {\n\t\tklog.Errorf(\"Can't touch %s: %v\", readyFile, err)\n\t\treturn\n\t}\n\tfile.Close()\n}","line":{"from":101,"to":117}} {"id":100013189,"name":"GetSecretForPod","signature":"func GetSecretForPod(pod *v1.Pod, secretName string, kubeClient clientset.Interface) (map[string]string, error)","file":"pkg/volume/util/util.go","code":"// GetSecretForPod locates secret by name in the pod's namespace and returns secret map\nfunc GetSecretForPod(pod *v1.Pod, secretName string, kubeClient clientset.Interface) (map[string]string, error) {\n\tsecret := make(map[string]string)\n\tif kubeClient == nil {\n\t\treturn secret, fmt.Errorf(\"cannot get kube client\")\n\t}\n\tsecrets, err := kubeClient.CoreV1().Secrets(pod.Namespace).Get(context.TODO(), secretName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn secret, err\n\t}\n\tfor name, data := range secrets.Data {\n\t\tsecret[name] = string(data)\n\t}\n\treturn secret, nil\n}","line":{"from":119,"to":133}} {"id":100013190,"name":"GetSecretForPV","signature":"func GetSecretForPV(secretNamespace, secretName, volumePluginName string, kubeClient clientset.Interface) (map[string]string, error)","file":"pkg/volume/util/util.go","code":"// GetSecretForPV locates secret by name and namespace, verifies the secret type, and returns secret map\nfunc GetSecretForPV(secretNamespace, secretName, volumePluginName string, kubeClient clientset.Interface) (map[string]string, error) {\n\tsecret := make(map[string]string)\n\tif kubeClient == nil {\n\t\treturn secret, fmt.Errorf(\"cannot get kube client\")\n\t}\n\tsecrets, err := kubeClient.CoreV1().Secrets(secretNamespace).Get(context.TODO(), secretName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn secret, err\n\t}\n\tif secrets.Type != v1.SecretType(volumePluginName) {\n\t\treturn secret, fmt.Errorf(\"cannot get secret of type %s\", volumePluginName)\n\t}\n\tfor name, data := range secrets.Data {\n\t\tsecret[name] = string(data)\n\t}\n\treturn secret, nil\n}","line":{"from":135,"to":152}} {"id":100013191,"name":"GetClassForVolume","signature":"func GetClassForVolume(kubeClient clientset.Interface, pv *v1.PersistentVolume) (*storage.StorageClass, error)","file":"pkg/volume/util/util.go","code":"// GetClassForVolume locates storage class by persistent volume\nfunc GetClassForVolume(kubeClient clientset.Interface, pv *v1.PersistentVolume) (*storage.StorageClass, error) {\n\tif kubeClient == nil {\n\t\treturn nil, fmt.Errorf(\"cannot get kube client\")\n\t}\n\tclassName := storagehelpers.GetPersistentVolumeClass(pv)\n\tif className == \"\" {\n\t\treturn nil, fmt.Errorf(\"volume has no storage class\")\n\t}\n\n\tclass, err := kubeClient.StorageV1().StorageClasses().Get(context.TODO(), className, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn class, nil\n}","line":{"from":154,"to":169}} {"id":100013192,"name":"LoadPodFromFile","signature":"func LoadPodFromFile(filePath string) (*v1.Pod, error)","file":"pkg/volume/util/util.go","code":"// LoadPodFromFile will read, decode, and return a Pod from a file.\nfunc LoadPodFromFile(filePath string) (*v1.Pod, error) {\n\tif filePath == \"\" {\n\t\treturn nil, fmt.Errorf(\"file path not specified\")\n\t}\n\tpodDef, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read file path %s: %+v\", filePath, err)\n\t}\n\tif len(podDef) == 0 {\n\t\treturn nil, fmt.Errorf(\"file was empty: %s\", filePath)\n\t}\n\tpod := \u0026v1.Pod{}\n\n\tcodec := legacyscheme.Codecs.UniversalDecoder()\n\tif err := apiruntime.DecodeInto(codec, podDef, pod); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed decoding file: %v\", err)\n\t}\n\treturn pod, nil\n}","line":{"from":171,"to":190}} {"id":100013193,"name":"CalculateTimeoutForVolume","signature":"func CalculateTimeoutForVolume(minimumTimeout, timeoutIncrement int, pv *v1.PersistentVolume) int64","file":"pkg/volume/util/util.go","code":"// CalculateTimeoutForVolume calculates time for a Recycler pod to complete a\n// recycle operation. The calculation and return value is either the\n// minimumTimeout or the timeoutIncrement per Gi of storage size, whichever is\n// greater.\nfunc CalculateTimeoutForVolume(minimumTimeout, timeoutIncrement int, pv *v1.PersistentVolume) int64 {\n\tgiQty := resource.MustParse(\"1Gi\")\n\tpvQty := pv.Spec.Capacity[v1.ResourceStorage]\n\tgiSize := giQty.Value()\n\tpvSize := pvQty.Value()\n\ttimeout := (pvSize / giSize) * int64(timeoutIncrement)\n\tif timeout \u003c int64(minimumTimeout) {\n\t\treturn int64(minimumTimeout)\n\t}\n\treturn timeout\n}","line":{"from":192,"to":206}} {"id":100013194,"name":"GenerateVolumeName","signature":"func GenerateVolumeName(clusterName, pvName string, maxLength int) string","file":"pkg/volume/util/util.go","code":"// GenerateVolumeName returns a PV name with clusterName prefix. The function\n// should be used to generate a name of GCE PD or Cinder volume. It basically\n// adds \"\u003cclusterName\u003e-dynamic-\" before the PV name, making sure the resulting\n// string fits given length and cuts \"dynamic\" if not.\nfunc GenerateVolumeName(clusterName, pvName string, maxLength int) string {\n\tprefix := clusterName + \"-dynamic\"\n\tpvLen := len(pvName)\n\n\t// cut the \"\u003cclusterName\u003e-dynamic\" to fit full pvName into maxLength\n\t// +1 for the '-' dash\n\tif pvLen+1+len(prefix) \u003e maxLength {\n\t\tprefix = prefix[:maxLength-pvLen-1]\n\t}\n\treturn prefix + \"-\" + pvName\n}","line":{"from":208,"to":222}} {"id":100013195,"name":"GetPath","signature":"func GetPath(mounter volume.Mounter) (string, error)","file":"pkg/volume/util/util.go","code":"// GetPath checks if the path from the mounter is empty.\nfunc GetPath(mounter volume.Mounter) (string, error) {\n\tpath := mounter.GetPath()\n\tif path == \"\" {\n\t\treturn \"\", fmt.Errorf(\"path is empty %s\", reflect.TypeOf(mounter).String())\n\t}\n\treturn path, nil\n}","line":{"from":224,"to":231}} {"id":100013196,"name":"UnmountViaEmptyDir","signature":"func UnmountViaEmptyDir(dir string, host volume.VolumeHost, volName string, volSpec volume.Spec, podUID utypes.UID) error","file":"pkg/volume/util/util.go","code":"// UnmountViaEmptyDir delegates the tear down operation for secret, configmap, git_repo and downwardapi\n// to empty_dir\nfunc UnmountViaEmptyDir(dir string, host volume.VolumeHost, volName string, volSpec volume.Spec, podUID utypes.UID) error {\n\tklog.V(3).Infof(\"Tearing down volume %v for pod %v at %v\", volName, podUID, dir)\n\n\t// Wrap EmptyDir, let it do the teardown.\n\twrapped, err := host.NewWrapperUnmounter(volName, volSpec, podUID)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn wrapped.TearDownAt(dir)\n}","line":{"from":233,"to":244}} {"id":100013197,"name":"MountOptionFromSpec","signature":"func MountOptionFromSpec(spec *volume.Spec, options ...string) []string","file":"pkg/volume/util/util.go","code":"// MountOptionFromSpec extracts and joins mount options from volume spec with supplied options\nfunc MountOptionFromSpec(spec *volume.Spec, options ...string) []string {\n\tpv := spec.PersistentVolume\n\n\tif pv != nil {\n\t\t// Use beta annotation first\n\t\tif mo, ok := pv.Annotations[v1.MountOptionAnnotation]; ok {\n\t\t\tmoList := strings.Split(mo, \",\")\n\t\t\treturn JoinMountOptions(moList, options)\n\t\t}\n\n\t\tif len(pv.Spec.MountOptions) \u003e 0 {\n\t\t\treturn JoinMountOptions(pv.Spec.MountOptions, options)\n\t\t}\n\t}\n\n\treturn options\n}","line":{"from":246,"to":263}} {"id":100013198,"name":"JoinMountOptions","signature":"func JoinMountOptions(userOptions []string, systemOptions []string) []string","file":"pkg/volume/util/util.go","code":"// JoinMountOptions joins mount options eliminating duplicates\nfunc JoinMountOptions(userOptions []string, systemOptions []string) []string {\n\tallMountOptions := sets.NewString()\n\n\tfor _, mountOption := range userOptions {\n\t\tif len(mountOption) \u003e 0 {\n\t\t\tallMountOptions.Insert(mountOption)\n\t\t}\n\t}\n\n\tfor _, mountOption := range systemOptions {\n\t\tallMountOptions.Insert(mountOption)\n\t}\n\treturn allMountOptions.List()\n}","line":{"from":265,"to":279}} {"id":100013199,"name":"ContainsAccessMode","signature":"func ContainsAccessMode(modes []v1.PersistentVolumeAccessMode, mode v1.PersistentVolumeAccessMode) bool","file":"pkg/volume/util/util.go","code":"// ContainsAccessMode returns whether the requested mode is contained by modes\nfunc ContainsAccessMode(modes []v1.PersistentVolumeAccessMode, mode v1.PersistentVolumeAccessMode) bool {\n\tfor _, m := range modes {\n\t\tif m == mode {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":281,"to":289}} {"id":100013200,"name":"ContainsAllAccessModes","signature":"func ContainsAllAccessModes(indexedModes []v1.PersistentVolumeAccessMode, requestedModes []v1.PersistentVolumeAccessMode) bool","file":"pkg/volume/util/util.go","code":"// ContainsAllAccessModes returns whether all of the requested modes are contained by modes\nfunc ContainsAllAccessModes(indexedModes []v1.PersistentVolumeAccessMode, requestedModes []v1.PersistentVolumeAccessMode) bool {\n\tfor _, mode := range requestedModes {\n\t\tif !ContainsAccessMode(indexedModes, mode) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":291,"to":299}} {"id":100013201,"name":"GetWindowsPath","signature":"func GetWindowsPath(path string) string","file":"pkg/volume/util/util.go","code":"// GetWindowsPath get a windows path\nfunc GetWindowsPath(path string) string {\n\twindowsPath := strings.Replace(path, \"/\", \"\\\\\", -1)\n\tif strings.HasPrefix(windowsPath, \"\\\\\") {\n\t\twindowsPath = \"c:\" + windowsPath\n\t}\n\treturn windowsPath\n}","line":{"from":301,"to":308}} {"id":100013202,"name":"GetUniquePodName","signature":"func GetUniquePodName(pod *v1.Pod) types.UniquePodName","file":"pkg/volume/util/util.go","code":"// GetUniquePodName returns a unique identifier to reference a pod by\nfunc GetUniquePodName(pod *v1.Pod) types.UniquePodName {\n\treturn types.UniquePodName(pod.UID)\n}","line":{"from":310,"to":313}} {"id":100013203,"name":"GetUniqueVolumeName","signature":"func GetUniqueVolumeName(pluginName, volumeName string) v1.UniqueVolumeName","file":"pkg/volume/util/util.go","code":"// GetUniqueVolumeName returns a unique name representing the volume/plugin.\n// Caller should ensure that volumeName is a name/ID uniquely identifying the\n// actual backing device, directory, path, etc. for a particular volume.\n// The returned name can be used to uniquely reference the volume, for example,\n// to prevent operations (attach/detach or mount/unmount) from being triggered\n// on the same volume.\nfunc GetUniqueVolumeName(pluginName, volumeName string) v1.UniqueVolumeName {\n\treturn v1.UniqueVolumeName(fmt.Sprintf(\"%s/%s\", pluginName, volumeName))\n}","line":{"from":315,"to":323}} {"id":100013204,"name":"GetUniqueVolumeNameFromSpecWithPod","signature":"func GetUniqueVolumeNameFromSpecWithPod(","file":"pkg/volume/util/util.go","code":"// GetUniqueVolumeNameFromSpecWithPod returns a unique volume name with pod\n// name included. This is useful to generate different names for different pods\n// on same volume.\nfunc GetUniqueVolumeNameFromSpecWithPod(\n\tpodName types.UniquePodName, volumePlugin volume.VolumePlugin, volumeSpec *volume.Spec) v1.UniqueVolumeName {\n\treturn v1.UniqueVolumeName(\n\t\tfmt.Sprintf(\"%s/%v-%s\", volumePlugin.GetPluginName(), podName, volumeSpec.Name()))\n}","line":{"from":325,"to":332}} {"id":100013205,"name":"GetUniqueVolumeNameFromSpec","signature":"func GetUniqueVolumeNameFromSpec(","file":"pkg/volume/util/util.go","code":"// GetUniqueVolumeNameFromSpec uses the given VolumePlugin to generate a unique\n// name representing the volume defined in the specified volume spec.\n// This returned name can be used to uniquely reference the actual backing\n// device, directory, path, etc. referenced by the given volumeSpec.\n// If the given plugin does not support the volume spec, this returns an error.\nfunc GetUniqueVolumeNameFromSpec(\n\tvolumePlugin volume.VolumePlugin,\n\tvolumeSpec *volume.Spec) (v1.UniqueVolumeName, error) {\n\tif volumePlugin == nil {\n\t\treturn \"\", fmt.Errorf(\n\t\t\t\"volumePlugin should not be nil. volumeSpec.Name=%q\",\n\t\t\tvolumeSpec.Name())\n\t}\n\n\tvolumeName, err := volumePlugin.GetVolumeName(volumeSpec)\n\tif err != nil || volumeName == \"\" {\n\t\treturn \"\", fmt.Errorf(\n\t\t\t\"failed to GetVolumeName from volumePlugin for volumeSpec %q err=%v\",\n\t\t\tvolumeSpec.Name(),\n\t\t\terr)\n\t}\n\n\treturn GetUniqueVolumeName(\n\t\t\tvolumePlugin.GetPluginName(),\n\t\t\tvolumeName),\n\t\tnil\n}","line":{"from":334,"to":360}} {"id":100013206,"name":"IsPodTerminated","signature":"func IsPodTerminated(pod *v1.Pod, podStatus v1.PodStatus) bool","file":"pkg/volume/util/util.go","code":"// IsPodTerminated checks if pod is terminated\nfunc IsPodTerminated(pod *v1.Pod, podStatus v1.PodStatus) bool {\n\t// TODO: the guarantees provided by kubelet status are not sufficient to guarantee it's safe to ignore a deleted pod,\n\t// even if everything is notRunning (kubelet does not guarantee that when pod status is waiting that it isn't trying\n\t// to start a container).\n\treturn podStatus.Phase == v1.PodFailed || podStatus.Phase == v1.PodSucceeded || (pod.DeletionTimestamp != nil \u0026\u0026 notRunning(podStatus.InitContainerStatuses) \u0026\u0026 notRunning(podStatus.ContainerStatuses) \u0026\u0026 notRunning(podStatus.EphemeralContainerStatuses))\n}","line":{"from":362,"to":368}} {"id":100013207,"name":"notRunning","signature":"func notRunning(statuses []v1.ContainerStatus) bool","file":"pkg/volume/util/util.go","code":"// notRunning returns true if every status is terminated or waiting, or the status list\n// is empty.\nfunc notRunning(statuses []v1.ContainerStatus) bool {\n\tfor _, status := range statuses {\n\t\tif status.State.Terminated == nil \u0026\u0026 status.State.Waiting == nil {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":370,"to":379}} {"id":100013208,"name":"SplitUniqueName","signature":"func SplitUniqueName(uniqueName v1.UniqueVolumeName) (string, string, error)","file":"pkg/volume/util/util.go","code":"// SplitUniqueName splits the unique name to plugin name and volume name strings. It expects the uniqueName to follow\n// the format plugin_name/volume_name and the plugin name must be namespaced as described by the plugin interface,\n// i.e. namespace/plugin containing exactly one '/'. This means the unique name will always be in the form of\n// plugin_namespace/plugin/volume_name, see k8s.io/kubernetes/pkg/volume/plugins.go VolumePlugin interface\n// description and pkg/volume/util/volumehelper/volumehelper.go GetUniqueVolumeNameFromSpec that constructs\n// the unique volume names.\nfunc SplitUniqueName(uniqueName v1.UniqueVolumeName) (string, string, error) {\n\tcomponents := strings.SplitN(string(uniqueName), \"/\", 3)\n\tif len(components) != 3 {\n\t\treturn \"\", \"\", fmt.Errorf(\"cannot split volume unique name %s to plugin/volume components\", uniqueName)\n\t}\n\tpluginName := fmt.Sprintf(\"%s/%s\", components[0], components[1])\n\treturn pluginName, components[2], nil\n}","line":{"from":381,"to":394}} {"id":100013209,"name":"NewSafeFormatAndMountFromHost","signature":"func NewSafeFormatAndMountFromHost(pluginName string, host volume.VolumeHost) *mount.SafeFormatAndMount","file":"pkg/volume/util/util.go","code":"// NewSafeFormatAndMountFromHost creates a new SafeFormatAndMount with Mounter\n// and Exec taken from given VolumeHost.\nfunc NewSafeFormatAndMountFromHost(pluginName string, host volume.VolumeHost) *mount.SafeFormatAndMount {\n\tmounter := host.GetMounter(pluginName)\n\texec := host.GetExec(pluginName)\n\treturn \u0026mount.SafeFormatAndMount{Interface: mounter, Exec: exec}\n}","line":{"from":396,"to":402}} {"id":100013210,"name":"GetVolumeMode","signature":"func GetVolumeMode(volumeSpec *volume.Spec) (v1.PersistentVolumeMode, error)","file":"pkg/volume/util/util.go","code":"// GetVolumeMode retrieves VolumeMode from pv.\n// If the volume doesn't have PersistentVolume, it's an inline volume,\n// should return volumeMode as filesystem to keep existing behavior.\nfunc GetVolumeMode(volumeSpec *volume.Spec) (v1.PersistentVolumeMode, error) {\n\tif volumeSpec == nil || volumeSpec.PersistentVolume == nil {\n\t\treturn v1.PersistentVolumeFilesystem, nil\n\t}\n\tif volumeSpec.PersistentVolume.Spec.VolumeMode != nil {\n\t\treturn *volumeSpec.PersistentVolume.Spec.VolumeMode, nil\n\t}\n\treturn \"\", fmt.Errorf(\"cannot get volumeMode for volume: %v\", volumeSpec.Name())\n}","line":{"from":404,"to":415}} {"id":100013211,"name":"GetPersistentVolumeClaimQualifiedName","signature":"func GetPersistentVolumeClaimQualifiedName(claim *v1.PersistentVolumeClaim) string","file":"pkg/volume/util/util.go","code":"// GetPersistentVolumeClaimQualifiedName returns a qualified name for pvc.\nfunc GetPersistentVolumeClaimQualifiedName(claim *v1.PersistentVolumeClaim) string {\n\treturn utilstrings.JoinQualifiedName(claim.GetNamespace(), claim.GetName())\n}","line":{"from":417,"to":420}} {"id":100013212,"name":"CheckVolumeModeFilesystem","signature":"func CheckVolumeModeFilesystem(volumeSpec *volume.Spec) (bool, error)","file":"pkg/volume/util/util.go","code":"// CheckVolumeModeFilesystem checks VolumeMode.\n// If the mode is Filesystem, return true otherwise return false.\nfunc CheckVolumeModeFilesystem(volumeSpec *volume.Spec) (bool, error) {\n\tvolumeMode, err := GetVolumeMode(volumeSpec)\n\tif err != nil {\n\t\treturn true, err\n\t}\n\tif volumeMode == v1.PersistentVolumeBlock {\n\t\treturn false, nil\n\t}\n\treturn true, nil\n}","line":{"from":422,"to":433}} {"id":100013213,"name":"CheckPersistentVolumeClaimModeBlock","signature":"func CheckPersistentVolumeClaimModeBlock(pvc *v1.PersistentVolumeClaim) bool","file":"pkg/volume/util/util.go","code":"// CheckPersistentVolumeClaimModeBlock checks VolumeMode.\n// If the mode is Block, return true otherwise return false.\nfunc CheckPersistentVolumeClaimModeBlock(pvc *v1.PersistentVolumeClaim) bool {\n\treturn pvc.Spec.VolumeMode != nil \u0026\u0026 *pvc.Spec.VolumeMode == v1.PersistentVolumeBlock\n}","line":{"from":435,"to":439}} {"id":100013214,"name":"IsWindowsUNCPath","signature":"func IsWindowsUNCPath(goos, path string) bool","file":"pkg/volume/util/util.go","code":"// IsWindowsUNCPath checks if path is prefixed with \\\\\n// This can be used to skip any processing of paths\n// that point to SMB shares, local named pipes and local UNC path\nfunc IsWindowsUNCPath(goos, path string) bool {\n\tif goos != \"windows\" {\n\t\treturn false\n\t}\n\t// Check for UNC prefix \\\\\n\tif strings.HasPrefix(path, `\\\\`) {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":441,"to":453}} {"id":100013215,"name":"IsWindowsLocalPath","signature":"func IsWindowsLocalPath(goos, path string) bool","file":"pkg/volume/util/util.go","code":"// IsWindowsLocalPath checks if path is a local path\n// prefixed with \"/\" or \"\\\" like \"/foo/bar\" or \"\\foo\\bar\"\nfunc IsWindowsLocalPath(goos, path string) bool {\n\tif goos != \"windows\" {\n\t\treturn false\n\t}\n\tif IsWindowsUNCPath(goos, path) {\n\t\treturn false\n\t}\n\tif strings.Contains(path, \":\") {\n\t\treturn false\n\t}\n\tif !(strings.HasPrefix(path, `/`) || strings.HasPrefix(path, `\\`)) {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":455,"to":471}} {"id":100013216,"name":"MakeAbsolutePath","signature":"func MakeAbsolutePath(goos, path string) string","file":"pkg/volume/util/util.go","code":"// MakeAbsolutePath convert path to absolute path according to GOOS\nfunc MakeAbsolutePath(goos, path string) string {\n\tif goos != \"windows\" {\n\t\treturn filepath.Clean(\"/\" + path)\n\t}\n\t// These are all for windows\n\t// If there is a colon, give up.\n\tif strings.Contains(path, \":\") {\n\t\treturn path\n\t}\n\t// If there is a slash, but no drive, add 'c:'\n\tif strings.HasPrefix(path, \"/\") || strings.HasPrefix(path, \"\\\\\") {\n\t\treturn \"c:\" + path\n\t}\n\t// Otherwise, add 'c:\\'\n\treturn \"c:\\\\\" + path\n}","line":{"from":473,"to":489}} {"id":100013217,"name":"MapBlockVolume","signature":"func MapBlockVolume(","file":"pkg/volume/util/util.go","code":"// MapBlockVolume is a utility function to provide a common way of mapping\n// block device path for a specified volume and pod. This function should be\n// called by volume plugins that implements volume.BlockVolumeMapper.Map() method.\nfunc MapBlockVolume(\n\tblkUtil volumepathhandler.BlockVolumePathHandler,\n\tdevicePath,\n\tglobalMapPath,\n\tpodVolumeMapPath,\n\tvolumeMapName string,\n\tpodUID utypes.UID,\n) error {\n\t// map devicePath to global node path as bind mount\n\tmapErr := blkUtil.MapDevice(devicePath, globalMapPath, string(podUID), true /* bindMount */)\n\tif mapErr != nil {\n\t\treturn fmt.Errorf(\"blkUtil.MapDevice failed. devicePath: %s, globalMapPath:%s, podUID: %s, bindMount: %v: %v\",\n\t\t\tdevicePath, globalMapPath, string(podUID), true, mapErr)\n\t}\n\n\t// map devicePath to pod volume path\n\tmapErr = blkUtil.MapDevice(devicePath, podVolumeMapPath, volumeMapName, false /* bindMount */)\n\tif mapErr != nil {\n\t\treturn fmt.Errorf(\"blkUtil.MapDevice failed. devicePath: %s, podVolumeMapPath:%s, volumeMapName: %s, bindMount: %v: %v\",\n\t\t\tdevicePath, podVolumeMapPath, volumeMapName, false, mapErr)\n\t}\n\n\t// Take file descriptor lock to keep a block device opened. Otherwise, there is a case\n\t// that the block device is silently removed and attached another device with the same name.\n\t// Container runtime can't handle this problem. To avoid unexpected condition fd lock\n\t// for the block device is required.\n\t_, mapErr = blkUtil.AttachFileDevice(filepath.Join(globalMapPath, string(podUID)))\n\tif mapErr != nil {\n\t\treturn fmt.Errorf(\"blkUtil.AttachFileDevice failed. globalMapPath:%s, podUID: %s: %v\",\n\t\t\tglobalMapPath, string(podUID), mapErr)\n\t}\n\n\treturn nil\n}","line":{"from":491,"to":527}} {"id":100013218,"name":"UnmapBlockVolume","signature":"func UnmapBlockVolume(","file":"pkg/volume/util/util.go","code":"// UnmapBlockVolume is a utility function to provide a common way of unmapping\n// block device path for a specified volume and pod. This function should be\n// called by volume plugins that implements volume.BlockVolumeMapper.Map() method.\nfunc UnmapBlockVolume(\n\tblkUtil volumepathhandler.BlockVolumePathHandler,\n\tglobalUnmapPath,\n\tpodDeviceUnmapPath,\n\tvolumeMapName string,\n\tpodUID utypes.UID,\n) error {\n\t// Release file descriptor lock.\n\terr := blkUtil.DetachFileDevice(filepath.Join(globalUnmapPath, string(podUID)))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"blkUtil.DetachFileDevice failed. globalUnmapPath:%s, podUID: %s: %v\",\n\t\t\tglobalUnmapPath, string(podUID), err)\n\t}\n\n\t// unmap devicePath from pod volume path\n\tunmapDeviceErr := blkUtil.UnmapDevice(podDeviceUnmapPath, volumeMapName, false /* bindMount */)\n\tif unmapDeviceErr != nil {\n\t\treturn fmt.Errorf(\"blkUtil.DetachFileDevice failed. podDeviceUnmapPath:%s, volumeMapName: %s, bindMount: %v: %v\",\n\t\t\tpodDeviceUnmapPath, volumeMapName, false, unmapDeviceErr)\n\t}\n\n\t// unmap devicePath from global node path\n\tunmapDeviceErr = blkUtil.UnmapDevice(globalUnmapPath, string(podUID), true /* bindMount */)\n\tif unmapDeviceErr != nil {\n\t\treturn fmt.Errorf(\"blkUtil.DetachFileDevice failed. globalUnmapPath:%s, podUID: %s, bindMount: %v: %v\",\n\t\t\tglobalUnmapPath, string(podUID), true, unmapDeviceErr)\n\t}\n\treturn nil\n}","line":{"from":529,"to":560}} {"id":100013219,"name":"GetPluginMountDir","signature":"func GetPluginMountDir(host volume.VolumeHost, name string) string","file":"pkg/volume/util/util.go","code":"// GetPluginMountDir returns the global mount directory name appended\n// to the given plugin name's plugin directory\nfunc GetPluginMountDir(host volume.VolumeHost, name string) string {\n\tmntDir := filepath.Join(host.GetPluginDir(name), MountsInGlobalPDPath)\n\treturn mntDir\n}","line":{"from":562,"to":567}} {"id":100013220,"name":"IsLocalEphemeralVolume","signature":"func IsLocalEphemeralVolume(volume v1.Volume) bool","file":"pkg/volume/util/util.go","code":"// IsLocalEphemeralVolume determines whether the argument is a local ephemeral\n// volume vs. some other type\n// Local means the volume is using storage from the local disk that is managed by kubelet.\n// Ephemeral means the lifecycle of the volume is the same as the Pod.\nfunc IsLocalEphemeralVolume(volume v1.Volume) bool {\n\treturn volume.GitRepo != nil ||\n\t\t(volume.EmptyDir != nil \u0026\u0026 volume.EmptyDir.Medium == v1.StorageMediumDefault) ||\n\t\tvolume.ConfigMap != nil\n}","line":{"from":569,"to":577}} {"id":100013221,"name":"GetLocalPersistentVolumeNodeNames","signature":"func GetLocalPersistentVolumeNodeNames(pv *v1.PersistentVolume) []string","file":"pkg/volume/util/util.go","code":"// GetLocalPersistentVolumeNodeNames returns the node affinity node name(s) for\n// local PersistentVolumes. nil is returned if the PV does not have any\n// specific node affinity node selector terms and match expressions.\n// PersistentVolume with node affinity has select and match expressions\n// in the form of:\n//\n//\tnodeAffinity:\n//\t required:\n//\t nodeSelectorTerms:\n//\t - matchExpressions:\n//\t - key: kubernetes.io/hostname\n//\t operator: In\n//\t values:\n//\t - \u003cnode1\u003e\n//\t - \u003cnode2\u003e\nfunc GetLocalPersistentVolumeNodeNames(pv *v1.PersistentVolume) []string {\n\tif pv == nil || pv.Spec.NodeAffinity == nil || pv.Spec.NodeAffinity.Required == nil {\n\t\treturn nil\n\t}\n\n\tvar result sets.Set[string]\n\tfor _, term := range pv.Spec.NodeAffinity.Required.NodeSelectorTerms {\n\t\tvar nodes sets.Set[string]\n\t\tfor _, matchExpr := range term.MatchExpressions {\n\t\t\tif matchExpr.Key == v1.LabelHostname \u0026\u0026 matchExpr.Operator == v1.NodeSelectorOpIn {\n\t\t\t\tif nodes == nil {\n\t\t\t\t\tnodes = sets.New(matchExpr.Values...)\n\t\t\t\t} else {\n\t\t\t\t\tnodes = nodes.Intersection(sets.New(matchExpr.Values...))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tresult = result.Union(nodes)\n\t}\n\n\treturn sets.List(result)\n}","line":{"from":579,"to":615}} {"id":100013222,"name":"GetPodVolumeNames","signature":"func GetPodVolumeNames(pod *v1.Pod) (mounts sets.String, devices sets.String, seLinuxContainerContexts map[string][]*v1.SELinuxOptions)","file":"pkg/volume/util/util.go","code":"// GetPodVolumeNames returns names of volumes that are used in a pod,\n// either as filesystem mount or raw block device, together with list\n// of all SELinux contexts of all containers that use the volumes.\nfunc GetPodVolumeNames(pod *v1.Pod) (mounts sets.String, devices sets.String, seLinuxContainerContexts map[string][]*v1.SELinuxOptions) {\n\tmounts = sets.NewString()\n\tdevices = sets.NewString()\n\tseLinuxContainerContexts = make(map[string][]*v1.SELinuxOptions)\n\n\tpodutil.VisitContainers(\u0026pod.Spec, podutil.AllFeatureEnabledContainers(), func(container *v1.Container, containerType podutil.ContainerType) bool {\n\t\tvar seLinuxOptions *v1.SELinuxOptions\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) {\n\t\t\teffectiveContainerSecurity := securitycontext.DetermineEffectiveSecurityContext(pod, container)\n\t\t\tif effectiveContainerSecurity != nil {\n\t\t\t\t// No DeepCopy, SELinuxOptions is already a copy of Pod's or container's SELinuxOptions\n\t\t\t\tseLinuxOptions = effectiveContainerSecurity.SELinuxOptions\n\t\t\t}\n\t\t}\n\n\t\tif container.VolumeMounts != nil {\n\t\t\tfor _, mount := range container.VolumeMounts {\n\t\t\t\tmounts.Insert(mount.Name)\n\t\t\t\tif seLinuxOptions != nil {\n\t\t\t\t\tseLinuxContainerContexts[mount.Name] = append(seLinuxContainerContexts[mount.Name], seLinuxOptions.DeepCopy())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif container.VolumeDevices != nil {\n\t\t\tfor _, device := range container.VolumeDevices {\n\t\t\t\tdevices.Insert(device.Name)\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n\treturn\n}","line":{"from":617,"to":651}} {"id":100013223,"name":"FsUserFrom","signature":"func FsUserFrom(pod *v1.Pod) *int64","file":"pkg/volume/util/util.go","code":"// FsUserFrom returns FsUser of pod, which is determined by the runAsUser\n// attributes.\nfunc FsUserFrom(pod *v1.Pod) *int64 {\n\tvar fsUser *int64\n\t// Exclude ephemeral containers because SecurityContext is not allowed.\n\tpodutil.VisitContainers(\u0026pod.Spec, podutil.InitContainers|podutil.Containers, func(container *v1.Container, containerType podutil.ContainerType) bool {\n\t\trunAsUser, ok := securitycontext.DetermineEffectiveRunAsUser(pod, container)\n\t\t// One container doesn't specify user or there are more than one\n\t\t// non-root UIDs.\n\t\tif !ok || (fsUser != nil \u0026\u0026 *fsUser != *runAsUser) {\n\t\t\tfsUser = nil\n\t\t\treturn false\n\t\t}\n\t\tif fsUser == nil {\n\t\t\tfsUser = runAsUser\n\t\t}\n\t\treturn true\n\t})\n\treturn fsUser\n}","line":{"from":653,"to":672}} {"id":100013224,"name":"HasMountRefs","signature":"func HasMountRefs(mountPath string, mountRefs []string) bool","file":"pkg/volume/util/util.go","code":"// HasMountRefs checks if the given mountPath has mountRefs.\n// TODO: this is a workaround for the unmount device issue caused by gci mounter.\n// In GCI cluster, if gci mounter is used for mounting, the container started by mounter\n// script will cause additional mounts created in the container. Since these mounts are\n// irrelevant to the original mounts, they should be not considered when checking the\n// mount references. The current solution is to filter out those mount paths that contain\n// the k8s plugin suffix of original mount path.\nfunc HasMountRefs(mountPath string, mountRefs []string) bool {\n\t// A mountPath typically is like\n\t// /var/lib/kubelet/plugins/kubernetes.io/some-plugin/mounts/volume-XXXX\n\t// Mount refs can look like\n\t// /home/somewhere/var/lib/kubelet/plugins/kubernetes.io/some-plugin/...\n\t// but if /var/lib/kubelet is mounted to a different device a ref might be like\n\t// /mnt/some-other-place/kubelet/plugins/kubernetes.io/some-plugin/...\n\t// Neither of the above should be counted as a mount ref as those are handled\n\t// by the kubelet. What we're concerned about is a path like\n\t// /data/local/some/manual/mount\n\t// As unmonting could interrupt usage from that mountpoint.\n\t//\n\t// So instead of looking for the entire /var/lib/... path, the plugins/kuberentes.io/\n\t// suffix is trimmed off and searched for.\n\t//\n\t// If there isn't a /plugins/... path, the whole mountPath is used instead.\n\tpathToFind := mountPath\n\tif i := strings.Index(mountPath, kubernetesPluginPathPrefix); i \u003e -1 {\n\t\tpathToFind = mountPath[i:]\n\t}\n\tfor _, ref := range mountRefs {\n\t\tif !strings.Contains(ref, pathToFind) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":674,"to":707}} {"id":100013225,"name":"WriteVolumeCache","signature":"func WriteVolumeCache(deviceMountPath string, exec utilexec.Interface) error","file":"pkg/volume/util/util.go","code":"// WriteVolumeCache flush disk data given the spcified mount path\nfunc WriteVolumeCache(deviceMountPath string, exec utilexec.Interface) error {\n\t// If runtime os is windows, execute Write-VolumeCache powershell command on the disk\n\tif runtime.GOOS == \"windows\" {\n\t\tcmd := fmt.Sprintf(\"Get-Volume -FilePath %s | Write-Volumecache\", deviceMountPath)\n\t\toutput, err := exec.Command(\"powershell\", \"/c\", cmd).CombinedOutput()\n\t\tklog.Infof(\"command (%q) execeuted: %v, output: %q\", cmd, err, string(output))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"command (%q) failed: %v, output: %q\", cmd, err, string(output))\n\t\t}\n\t}\n\t// For linux runtime, it skips because unmount will automatically flush disk data\n\treturn nil\n}","line":{"from":709,"to":722}} {"id":100013226,"name":"IsMultiAttachAllowed","signature":"func IsMultiAttachAllowed(volumeSpec *volume.Spec) bool","file":"pkg/volume/util/util.go","code":"// IsMultiAttachAllowed checks if attaching this volume to multiple nodes is definitely not allowed/possible.\n// In its current form, this function can only reliably say for which volumes it's definitely forbidden. If it returns\n// false, it is not guaranteed that multi-attach is actually supported by the volume type and we must rely on the\n// attacher to fail fast in such cases.\n// Please see https://github.com/kubernetes/kubernetes/issues/40669 and https://github.com/kubernetes/kubernetes/pull/40148#discussion_r98055047\nfunc IsMultiAttachAllowed(volumeSpec *volume.Spec) bool {\n\tif volumeSpec == nil {\n\t\t// we don't know if it's supported or not and let the attacher fail later in cases it's not supported\n\t\treturn true\n\t}\n\n\tif volumeSpec.Volume != nil {\n\t\t// Check for volume types which are known to fail slow or cause trouble when trying to multi-attach\n\t\tif volumeSpec.Volume.AzureDisk != nil ||\n\t\t\tvolumeSpec.Volume.Cinder != nil {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// Only if this volume is a persistent volume, we have reliable information on whether it's allowed or not to\n\t// multi-attach. We trust in the individual volume implementations to not allow unsupported access modes\n\tif volumeSpec.PersistentVolume != nil {\n\t\t// Check for persistent volume types which do not fail when trying to multi-attach\n\t\tif len(volumeSpec.PersistentVolume.Spec.AccessModes) == 0 {\n\t\t\t// No access mode specified so we don't know for sure. Let the attacher fail if needed\n\t\t\treturn true\n\t\t}\n\n\t\t// check if this volume is allowed to be attached to multiple PODs/nodes, if yes, return false\n\t\tfor _, accessMode := range volumeSpec.PersistentVolume.Spec.AccessModes {\n\t\t\tif accessMode == v1.ReadWriteMany || accessMode == v1.ReadOnlyMany {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\t// we don't know if it's supported or not and let the attacher fail later in cases it's not supported\n\treturn true\n}","line":{"from":724,"to":763}} {"id":100013227,"name":"IsAttachableVolume","signature":"func IsAttachableVolume(volumeSpec *volume.Spec, volumePluginMgr *volume.VolumePluginMgr) bool","file":"pkg/volume/util/util.go","code":"// IsAttachableVolume checks if the given volumeSpec is an attachable volume or not\nfunc IsAttachableVolume(volumeSpec *volume.Spec, volumePluginMgr *volume.VolumePluginMgr) bool {\n\tattachableVolumePlugin, _ := volumePluginMgr.FindAttachablePluginBySpec(volumeSpec)\n\tif attachableVolumePlugin != nil {\n\t\tvolumeAttacher, err := attachableVolumePlugin.NewAttacher()\n\t\tif err == nil \u0026\u0026 volumeAttacher != nil {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":765,"to":776}} {"id":100013228,"name":"IsDeviceMountableVolume","signature":"func IsDeviceMountableVolume(volumeSpec *volume.Spec, volumePluginMgr *volume.VolumePluginMgr) bool","file":"pkg/volume/util/util.go","code":"// IsDeviceMountableVolume checks if the given volumeSpec is an device mountable volume or not\nfunc IsDeviceMountableVolume(volumeSpec *volume.Spec, volumePluginMgr *volume.VolumePluginMgr) bool {\n\tdeviceMountableVolumePlugin, _ := volumePluginMgr.FindDeviceMountablePluginBySpec(volumeSpec)\n\tif deviceMountableVolumePlugin != nil {\n\t\tvolumeDeviceMounter, err := deviceMountableVolumePlugin.NewDeviceMounter()\n\t\tif err == nil \u0026\u0026 volumeDeviceMounter != nil {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":778,"to":789}} {"id":100013229,"name":"GetReliableMountRefs","signature":"func GetReliableMountRefs(mounter mount.Interface, mountPath string) ([]string, error)","file":"pkg/volume/util/util.go","code":"// GetReliableMountRefs calls mounter.GetMountRefs and retries on IsInconsistentReadError.\n// To be used in volume reconstruction of volume plugins that don't have any protection\n// against mounting a single volume on multiple nodes (such as attach/detach).\nfunc GetReliableMountRefs(mounter mount.Interface, mountPath string) ([]string, error) {\n\tvar paths []string\n\tvar lastErr error\n\terr := wait.PollImmediate(10*time.Millisecond, time.Minute, func() (bool, error) {\n\t\tvar err error\n\t\tpaths, err = mounter.GetMountRefs(mountPath)\n\t\tif io.IsInconsistentReadError(err) {\n\t\t\tlastErr = err\n\t\t\treturn false, nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\treturn true, nil\n\t})\n\tif err == wait.ErrWaitTimeout {\n\t\treturn nil, lastErr\n\t}\n\treturn paths, err\n}","line":{"from":791,"to":813}} {"id":100013230,"name":"NewBlockVolumePathHandler","signature":"func NewBlockVolumePathHandler() BlockVolumePathHandler","file":"pkg/volume/util/volumepathhandler/volume_path_handler.go","code":"// NewBlockVolumePathHandler returns a new instance of BlockVolumeHandler.\nfunc NewBlockVolumePathHandler() BlockVolumePathHandler {\n\tvar volumePathHandler VolumePathHandler\n\treturn volumePathHandler\n}","line":{"from":64,"to":68}} {"id":100013231,"name":"MapDevice","signature":"func (v VolumePathHandler) MapDevice(devicePath string, mapPath string, linkName string, bindMount bool) error","file":"pkg/volume/util/volumepathhandler/volume_path_handler.go","code":"// MapDevice creates a symbolic link to block device under specified map path\nfunc (v VolumePathHandler) MapDevice(devicePath string, mapPath string, linkName string, bindMount bool) error {\n\t// Example of global map path:\n\t// globalMapPath/linkName: plugins/kubernetes.io/{PluginName}/{DefaultKubeletVolumeDevicesDirName}/{volumePluginDependentPath}/{podUid}\n\t// linkName: {podUid}\n\t//\n\t// Example of pod device map path:\n\t// podDeviceMapPath/linkName: pods/{podUid}/{DefaultKubeletVolumeDevicesDirName}/{escapeQualifiedPluginName}/{volumeName}\n\t// linkName: {volumeName}\n\tif len(devicePath) == 0 {\n\t\treturn fmt.Errorf(\"failed to map device to map path. devicePath is empty\")\n\t}\n\tif len(mapPath) == 0 {\n\t\treturn fmt.Errorf(\"failed to map device to map path. mapPath is empty\")\n\t}\n\tif !filepath.IsAbs(mapPath) {\n\t\treturn fmt.Errorf(\"the map path should be absolute: map path: %s\", mapPath)\n\t}\n\tklog.V(5).Infof(\"MapDevice: devicePath %s\", devicePath)\n\tklog.V(5).Infof(\"MapDevice: mapPath %s\", mapPath)\n\tklog.V(5).Infof(\"MapDevice: linkName %s\", linkName)\n\n\t// Check and create mapPath\n\t_, err := os.Stat(mapPath)\n\tif err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"cannot validate map path: %s: %v\", mapPath, err)\n\t}\n\tif err = os.MkdirAll(mapPath, 0750); err != nil {\n\t\treturn fmt.Errorf(\"failed to mkdir %s: %v\", mapPath, err)\n\t}\n\n\tif bindMount {\n\t\treturn mapBindMountDevice(v, devicePath, mapPath, linkName)\n\t}\n\treturn mapSymlinkDevice(v, devicePath, mapPath, linkName)\n}","line":{"from":74,"to":109}} {"id":100013232,"name":"mapBindMountDevice","signature":"func mapBindMountDevice(v VolumePathHandler, devicePath string, mapPath string, linkName string) error","file":"pkg/volume/util/volumepathhandler/volume_path_handler.go","code":"func mapBindMountDevice(v VolumePathHandler, devicePath string, mapPath string, linkName string) error {\n\t// Check bind mount exists\n\tlinkPath := filepath.Join(mapPath, string(linkName))\n\n\tfile, err := os.Stat(linkPath)\n\tif err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn fmt.Errorf(\"failed to stat file %s: %v\", linkPath, err)\n\t\t}\n\n\t\t// Create file\n\t\tnewFile, err := os.OpenFile(linkPath, os.O_CREATE|os.O_RDWR, 0750)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to open file %s: %v\", linkPath, err)\n\t\t}\n\t\tif err := newFile.Close(); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to close file %s: %v\", linkPath, err)\n\t\t}\n\t} else {\n\t\t// Check if device file\n\t\t// TODO: Need to check if this device file is actually the expected bind mount\n\t\tif file.Mode()\u0026os.ModeDevice == os.ModeDevice {\n\t\t\tklog.Warningf(\"Warning: Map skipped because bind mount already exist on the path: %v\", linkPath)\n\t\t\treturn nil\n\t\t}\n\n\t\tklog.Warningf(\"Warning: file %s is already exist but not mounted, skip creating file\", linkPath)\n\t}\n\n\t// Bind mount file\n\tmounter := \u0026mount.SafeFormatAndMount{Interface: mount.New(\"\"), Exec: utilexec.New()}\n\tif err := mounter.MountSensitiveWithoutSystemd(devicePath, linkPath, \"\" /* fsType */, []string{\"bind\"}, nil); err != nil {\n\t\treturn fmt.Errorf(\"failed to bind mount devicePath: %s to linkPath %s: %v\", devicePath, linkPath, err)\n\t}\n\n\treturn nil\n}","line":{"from":111,"to":147}} {"id":100013233,"name":"mapSymlinkDevice","signature":"func mapSymlinkDevice(v VolumePathHandler, devicePath string, mapPath string, linkName string) error","file":"pkg/volume/util/volumepathhandler/volume_path_handler.go","code":"func mapSymlinkDevice(v VolumePathHandler, devicePath string, mapPath string, linkName string) error {\n\t// Remove old symbolic link(or file) then create new one.\n\t// This should be done because current symbolic link is\n\t// stale across node reboot.\n\tlinkPath := filepath.Join(mapPath, string(linkName))\n\tif err := os.Remove(linkPath); err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"failed to remove file %s: %v\", linkPath, err)\n\t}\n\treturn os.Symlink(devicePath, linkPath)\n}","line":{"from":149,"to":158}} {"id":100013234,"name":"UnmapDevice","signature":"func (v VolumePathHandler) UnmapDevice(mapPath string, linkName string, bindMount bool) error","file":"pkg/volume/util/volumepathhandler/volume_path_handler.go","code":"// UnmapDevice removes a symbolic link associated to block device under specified map path\nfunc (v VolumePathHandler) UnmapDevice(mapPath string, linkName string, bindMount bool) error {\n\tif len(mapPath) == 0 {\n\t\treturn fmt.Errorf(\"failed to unmap device from map path. mapPath is empty\")\n\t}\n\tklog.V(5).Infof(\"UnmapDevice: mapPath %s\", mapPath)\n\tklog.V(5).Infof(\"UnmapDevice: linkName %s\", linkName)\n\n\tif bindMount {\n\t\treturn unmapBindMountDevice(v, mapPath, linkName)\n\t}\n\treturn unmapSymlinkDevice(v, mapPath, linkName)\n}","line":{"from":160,"to":172}} {"id":100013235,"name":"unmapBindMountDevice","signature":"func unmapBindMountDevice(v VolumePathHandler, mapPath string, linkName string) error","file":"pkg/volume/util/volumepathhandler/volume_path_handler.go","code":"func unmapBindMountDevice(v VolumePathHandler, mapPath string, linkName string) error {\n\t// Check bind mount exists\n\tlinkPath := filepath.Join(mapPath, string(linkName))\n\tif isMountExist, checkErr := v.IsDeviceBindMountExist(linkPath); checkErr != nil {\n\t\treturn checkErr\n\t} else if !isMountExist {\n\t\tklog.Warningf(\"Warning: Unmap skipped because bind mount does not exist on the path: %v\", linkPath)\n\n\t\t// Check if linkPath still exists\n\t\tif _, err := os.Stat(linkPath); err != nil {\n\t\t\tif !os.IsNotExist(err) {\n\t\t\t\treturn fmt.Errorf(\"failed to check if path %s exists: %v\", linkPath, err)\n\t\t\t}\n\t\t\t// linkPath has already been removed\n\t\t\treturn nil\n\t\t}\n\t\t// Remove file\n\t\tif err := os.Remove(linkPath); err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\t\treturn fmt.Errorf(\"failed to remove file %s: %v\", linkPath, err)\n\t\t}\n\t\treturn nil\n\t}\n\n\t// Unmount file\n\tmounter := \u0026mount.SafeFormatAndMount{Interface: mount.New(\"\"), Exec: utilexec.New()}\n\tif err := mounter.Unmount(linkPath); err != nil {\n\t\treturn fmt.Errorf(\"failed to unmount linkPath %s: %v\", linkPath, err)\n\t}\n\n\t// Remove file\n\tif err := os.Remove(linkPath); err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"failed to remove file %s: %v\", linkPath, err)\n\t}\n\n\treturn nil\n}","line":{"from":174,"to":209}} {"id":100013236,"name":"unmapSymlinkDevice","signature":"func unmapSymlinkDevice(v VolumePathHandler, mapPath string, linkName string) error","file":"pkg/volume/util/volumepathhandler/volume_path_handler.go","code":"func unmapSymlinkDevice(v VolumePathHandler, mapPath string, linkName string) error {\n\t// Check symbolic link exists\n\tlinkPath := filepath.Join(mapPath, string(linkName))\n\tif islinkExist, checkErr := v.IsSymlinkExist(linkPath); checkErr != nil {\n\t\treturn checkErr\n\t} else if !islinkExist {\n\t\tklog.Warningf(\"Warning: Unmap skipped because symlink does not exist on the path: %v\", linkPath)\n\t\treturn nil\n\t}\n\treturn os.Remove(linkPath)\n}","line":{"from":211,"to":221}} {"id":100013237,"name":"RemoveMapPath","signature":"func (v VolumePathHandler) RemoveMapPath(mapPath string) error","file":"pkg/volume/util/volumepathhandler/volume_path_handler.go","code":"// RemoveMapPath removes a file or directory on specified map path\nfunc (v VolumePathHandler) RemoveMapPath(mapPath string) error {\n\tif len(mapPath) == 0 {\n\t\treturn fmt.Errorf(\"failed to remove map path. mapPath is empty\")\n\t}\n\tklog.V(5).Infof(\"RemoveMapPath: mapPath %s\", mapPath)\n\terr := os.RemoveAll(mapPath)\n\tif err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"failed to remove directory %s: %v\", mapPath, err)\n\t}\n\treturn nil\n}","line":{"from":223,"to":234}} {"id":100013238,"name":"IsSymlinkExist","signature":"func (v VolumePathHandler) IsSymlinkExist(mapPath string) (bool, error)","file":"pkg/volume/util/volumepathhandler/volume_path_handler.go","code":"// IsSymlinkExist returns true if specified file exists and the type is symbolik link.\n// If file doesn't exist, or file exists but not symbolic link, return false with no error.\n// On other cases, return false with error from Lstat().\nfunc (v VolumePathHandler) IsSymlinkExist(mapPath string) (bool, error) {\n\tfi, err := os.Lstat(mapPath)\n\tif err != nil {\n\t\t// If file doesn't exist, return false and no error\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false, nil\n\t\t}\n\t\t// Return error from Lstat()\n\t\treturn false, fmt.Errorf(\"failed to Lstat file %s: %v\", mapPath, err)\n\t}\n\t// If file exits and it's symbolic link, return true and no error\n\tif fi.Mode()\u0026os.ModeSymlink == os.ModeSymlink {\n\t\treturn true, nil\n\t}\n\t// If file exits but it's not symbolic link, return false and no error\n\treturn false, nil\n}","line":{"from":236,"to":255}} {"id":100013239,"name":"IsDeviceBindMountExist","signature":"func (v VolumePathHandler) IsDeviceBindMountExist(mapPath string) (bool, error)","file":"pkg/volume/util/volumepathhandler/volume_path_handler.go","code":"// IsDeviceBindMountExist returns true if specified file exists and the type is device.\n// If file doesn't exist, or file exists but not device, return false with no error.\n// On other cases, return false with error from Lstat().\nfunc (v VolumePathHandler) IsDeviceBindMountExist(mapPath string) (bool, error) {\n\tfi, err := os.Lstat(mapPath)\n\tif err != nil {\n\t\t// If file doesn't exist, return false and no error\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false, nil\n\t\t}\n\n\t\t// Return error from Lstat()\n\t\treturn false, fmt.Errorf(\"failed to Lstat file %s: %v\", mapPath, err)\n\t}\n\t// If file exits and it's device, return true and no error\n\tif fi.Mode()\u0026os.ModeDevice == os.ModeDevice {\n\t\treturn true, nil\n\t}\n\t// If file exits but it's not device, return false and no error\n\treturn false, nil\n}","line":{"from":257,"to":277}} {"id":100013240,"name":"GetDeviceBindMountRefs","signature":"func (v VolumePathHandler) GetDeviceBindMountRefs(devPath string, mapPath string) ([]string, error)","file":"pkg/volume/util/volumepathhandler/volume_path_handler.go","code":"// GetDeviceBindMountRefs searches bind mounts under global map path\nfunc (v VolumePathHandler) GetDeviceBindMountRefs(devPath string, mapPath string) ([]string, error) {\n\tvar refs []string\n\tfiles, err := ioutil.ReadDir(mapPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, file := range files {\n\t\tif file.Mode()\u0026os.ModeDevice != os.ModeDevice {\n\t\t\tcontinue\n\t\t}\n\t\tfilename := file.Name()\n\t\t// TODO: Might need to check if the file is actually linked to devPath\n\t\trefs = append(refs, filepath.Join(mapPath, filename))\n\t}\n\tklog.V(5).Infof(\"GetDeviceBindMountRefs: refs %v\", refs)\n\treturn refs, nil\n}","line":{"from":279,"to":296}} {"id":100013241,"name":"AttachFileDevice","signature":"func (v VolumePathHandler) AttachFileDevice(path string) (string, error)","file":"pkg/volume/util/volumepathhandler/volume_path_handler_linux.go","code":"// AttachFileDevice takes a path to a regular file and makes it available as an\n// attached block device.\nfunc (v VolumePathHandler) AttachFileDevice(path string) (string, error) {\n\tblockDevicePath, err := v.GetLoopDevice(path)\n\tif err != nil \u0026\u0026 err.Error() != ErrDeviceNotFound {\n\t\treturn \"\", fmt.Errorf(\"GetLoopDevice failed for path %s: %v\", path, err)\n\t}\n\n\t// If no existing loop device for the path, create one\n\tif blockDevicePath == \"\" {\n\t\tklog.V(4).Infof(\"Creating device for path: %s\", path)\n\t\tblockDevicePath, err = makeLoopDevice(path)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"makeLoopDevice failed for path %s: %v\", path, err)\n\t\t}\n\t}\n\treturn blockDevicePath, nil\n}","line":{"from":37,"to":54}} {"id":100013242,"name":"DetachFileDevice","signature":"func (v VolumePathHandler) DetachFileDevice(path string) error","file":"pkg/volume/util/volumepathhandler/volume_path_handler_linux.go","code":"// DetachFileDevice takes a path to the attached block device and\n// detach it from block device.\nfunc (v VolumePathHandler) DetachFileDevice(path string) error {\n\tloopPath, err := v.GetLoopDevice(path)\n\tif err != nil {\n\t\tif err.Error() == ErrDeviceNotFound {\n\t\t\tklog.Warningf(\"couldn't find loopback device which takes file descriptor lock. Skip detaching device. device path: %q\", path)\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"GetLoopDevice failed for path %s: %v\", path, err)\n\t\t}\n\t} else {\n\t\tif len(loopPath) != 0 {\n\t\t\terr = removeLoopDevice(loopPath)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"removeLoopDevice failed for path %s: %v\", path, err)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":56,"to":75}} {"id":100013243,"name":"GetLoopDevice","signature":"func (v VolumePathHandler) GetLoopDevice(path string) (string, error)","file":"pkg/volume/util/volumepathhandler/volume_path_handler_linux.go","code":"// GetLoopDevice returns the full path to the loop device associated with the given path.\nfunc (v VolumePathHandler) GetLoopDevice(path string) (string, error) {\n\t_, err := os.Stat(path)\n\tif os.IsNotExist(err) {\n\t\treturn \"\", errors.New(ErrDeviceNotFound)\n\t}\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"not attachable: %v\", err)\n\t}\n\n\treturn getLoopDeviceFromSysfs(path)\n}","line":{"from":77,"to":88}} {"id":100013244,"name":"makeLoopDevice","signature":"func makeLoopDevice(path string) (string, error)","file":"pkg/volume/util/volumepathhandler/volume_path_handler_linux.go","code":"func makeLoopDevice(path string) (string, error) {\n\targs := []string{\"-f\", path}\n\tcmd := exec.Command(losetupPath, args...)\n\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tklog.V(2).Infof(\"Failed device create command for path: %s %v %s\", path, err, out)\n\t\treturn \"\", fmt.Errorf(\"losetup %s failed: %v\", strings.Join(args, \" \"), err)\n\t}\n\n\treturn getLoopDeviceFromSysfs(path)\n}","line":{"from":90,"to":101}} {"id":100013245,"name":"removeLoopDevice","signature":"func removeLoopDevice(device string) error","file":"pkg/volume/util/volumepathhandler/volume_path_handler_linux.go","code":"// removeLoopDevice removes specified loopback device\nfunc removeLoopDevice(device string) error {\n\targs := []string{\"-d\", device}\n\tcmd := exec.Command(losetupPath, args...)\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tif _, err := os.Stat(device); os.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\t\tklog.V(2).Infof(\"Failed to remove loopback device: %s: %v %s\", device, err, out)\n\t\treturn fmt.Errorf(\"losetup -d %s failed: %v\", device, err)\n\t}\n\treturn nil\n}","line":{"from":103,"to":116}} {"id":100013246,"name":"getLoopDeviceFromSysfs","signature":"func getLoopDeviceFromSysfs(path string) (string, error)","file":"pkg/volume/util/volumepathhandler/volume_path_handler_linux.go","code":"// getLoopDeviceFromSysfs finds the backing file for a loop\n// device from sysfs via \"/sys/block/loop*/loop/backing_file\".\nfunc getLoopDeviceFromSysfs(path string) (string, error) {\n\t// If the file is a symlink.\n\trealPath, err := filepath.EvalSymlinks(path)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to evaluate path %s: %s\", path, err)\n\t}\n\n\tdevices, err := filepath.Glob(\"/sys/block/loop*\")\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to list loop devices in sysfs: %s\", err)\n\t}\n\n\tfor _, device := range devices {\n\t\tbackingFile := fmt.Sprintf(\"%s/loop/backing_file\", device)\n\n\t\t// The contents of this file is the absolute path of \"path\".\n\t\tdata, err := ioutil.ReadFile(backingFile)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Return the first match.\n\t\tbackingFilePath := cleanBackingFilePath(string(data))\n\t\tif backingFilePath == path || backingFilePath == realPath {\n\t\t\treturn fmt.Sprintf(\"/dev/%s\", filepath.Base(device)), nil\n\t\t}\n\t}\n\n\treturn \"\", errors.New(ErrDeviceNotFound)\n}","line":{"from":118,"to":149}} {"id":100013247,"name":"cleanBackingFilePath","signature":"func cleanBackingFilePath(path string) string","file":"pkg/volume/util/volumepathhandler/volume_path_handler_linux.go","code":"// cleanPath remove any trailing substrings that are not part of the backing file path.\nfunc cleanBackingFilePath(path string) string {\n\t// If the block device was deleted, the path will contain a \"(deleted)\" suffix\n\tpath = strings.TrimSpace(path)\n\tpath = strings.TrimSuffix(path, \"(deleted)\")\n\treturn strings.TrimSpace(path)\n}","line":{"from":151,"to":157}} {"id":100013248,"name":"FindGlobalMapPathUUIDFromPod","signature":"func (v VolumePathHandler) FindGlobalMapPathUUIDFromPod(pluginDir, mapPath string, podUID types.UID) (string, error)","file":"pkg/volume/util/volumepathhandler/volume_path_handler_linux.go","code":"// FindGlobalMapPathUUIDFromPod finds {pod uuid} bind mount under globalMapPath\n// corresponding to map path symlink, and then return global map path with pod uuid.\n// (See pkg/volume/volume.go for details on a global map path and a pod device map path.)\n// ex. mapPath symlink: pods/{podUid}}/{DefaultKubeletVolumeDevicesDirName}/{escapeQualifiedPluginName}/{volumeName} -\u003e /dev/sdX\n//\n//\tglobalMapPath/{pod uuid} bind mount: plugins/kubernetes.io/{PluginName}/{DefaultKubeletVolumeDevicesDirName}/{volumePluginDependentPath}/{pod uuid} -\u003e /dev/sdX\nfunc (v VolumePathHandler) FindGlobalMapPathUUIDFromPod(pluginDir, mapPath string, podUID types.UID) (string, error) {\n\tvar globalMapPathUUID string\n\t// Find symbolic link named pod uuid under plugin dir\n\terr := filepath.Walk(pluginDir, func(path string, fi os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif (fi.Mode()\u0026os.ModeDevice == os.ModeDevice) \u0026\u0026 (fi.Name() == string(podUID)) {\n\t\t\tklog.V(5).Infof(\"FindGlobalMapPathFromPod: path %s, mapPath %s\", path, mapPath)\n\t\t\tif res, err := compareBindMountAndSymlinks(path, mapPath); err == nil \u0026\u0026 res {\n\t\t\t\tglobalMapPathUUID = path\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"FindGlobalMapPathUUIDFromPod failed: %v\", err)\n\t}\n\tklog.V(5).Infof(\"FindGlobalMapPathFromPod: globalMapPathUUID %s\", globalMapPathUUID)\n\t// Return path contains global map path + {pod uuid}\n\treturn globalMapPathUUID, nil\n}","line":{"from":159,"to":186}} {"id":100013249,"name":"compareBindMountAndSymlinks","signature":"func compareBindMountAndSymlinks(global, pod string) (bool, error)","file":"pkg/volume/util/volumepathhandler/volume_path_handler_linux.go","code":"// compareBindMountAndSymlinks returns if global path (bind mount) and\n// pod path (symlink) are pointing to the same device.\n// If there is an error in checking it returns error.\nfunc compareBindMountAndSymlinks(global, pod string) (bool, error) {\n\t// To check if bind mount and symlink are pointing to the same device,\n\t// we need to check if they are pointing to the devices that have same major/minor number.\n\n\t// Get the major/minor number for global path\n\tdevNumGlobal, err := getDeviceMajorMinor(global)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"getDeviceMajorMinor failed for path %s: %v\", global, err)\n\t}\n\n\t// Get the symlinked device from the pod path\n\tdevPod, err := os.Readlink(pod)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"failed to readlink path %s: %v\", pod, err)\n\t}\n\t// Get the major/minor number for the symlinked device from the pod path\n\tdevNumPod, err := getDeviceMajorMinor(devPod)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"getDeviceMajorMinor failed for path %s: %v\", devPod, err)\n\t}\n\tklog.V(5).Infof(\"CompareBindMountAndSymlinks: devNumGlobal %s, devNumPod %s\", devNumGlobal, devNumPod)\n\n\t// Check if the major/minor number are the same\n\tif devNumGlobal == devNumPod {\n\t\treturn true, nil\n\t}\n\treturn false, nil\n}","line":{"from":188,"to":218}} {"id":100013250,"name":"getDeviceMajorMinor","signature":"func getDeviceMajorMinor(path string) (string, error)","file":"pkg/volume/util/volumepathhandler/volume_path_handler_linux.go","code":"// getDeviceMajorMinor returns major/minor number for the path with below format:\n// major:minor (in hex)\n// ex)\n//\n//\tfc:10\nfunc getDeviceMajorMinor(path string) (string, error) {\n\tvar stat unix.Stat_t\n\n\tif err := unix.Stat(path, \u0026stat); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to stat path %s: %v\", path, err)\n\t}\n\n\tdevNumber := uint64(stat.Rdev)\n\tmajor := unix.Major(devNumber)\n\tminor := unix.Minor(devNumber)\n\n\treturn fmt.Sprintf(\"%x:%x\", major, minor), nil\n}","line":{"from":220,"to":237}} {"id":100013251,"name":"AttachFileDevice","signature":"func (v VolumePathHandler) AttachFileDevice(path string) (string, error)","file":"pkg/volume/util/volumepathhandler/volume_path_handler_unsupported.go","code":"// AttachFileDevice takes a path to a regular file and makes it available as an\n// attached block device.\nfunc (v VolumePathHandler) AttachFileDevice(path string) (string, error) {\n\treturn \"\", fmt.Errorf(\"AttachFileDevice not supported for this build.\")\n}","line":{"from":28,"to":32}} {"id":100013252,"name":"DetachFileDevice","signature":"func (v VolumePathHandler) DetachFileDevice(path string) error","file":"pkg/volume/util/volumepathhandler/volume_path_handler_unsupported.go","code":"// DetachFileDevice takes a path to the attached block device and\n// detach it from block device.\nfunc (v VolumePathHandler) DetachFileDevice(path string) error {\n\treturn fmt.Errorf(\"DetachFileDevice not supported for this build.\")\n}","line":{"from":34,"to":38}} {"id":100013253,"name":"GetLoopDevice","signature":"func (v VolumePathHandler) GetLoopDevice(path string) (string, error)","file":"pkg/volume/util/volumepathhandler/volume_path_handler_unsupported.go","code":"// GetLoopDevice returns the full path to the loop device associated with the given path.\nfunc (v VolumePathHandler) GetLoopDevice(path string) (string, error) {\n\treturn \"\", fmt.Errorf(\"GetLoopDevice not supported for this build.\")\n}","line":{"from":40,"to":43}} {"id":100013254,"name":"FindGlobalMapPathUUIDFromPod","signature":"func (v VolumePathHandler) FindGlobalMapPathUUIDFromPod(pluginDir, mapPath string, podUID types.UID) (string, error)","file":"pkg/volume/util/volumepathhandler/volume_path_handler_unsupported.go","code":"// FindGlobalMapPathUUIDFromPod finds {pod uuid} bind mount under globalMapPath\n// corresponding to map path symlink, and then return global map path with pod uuid.\nfunc (v VolumePathHandler) FindGlobalMapPathUUIDFromPod(pluginDir, mapPath string, podUID types.UID) (string, error) {\n\treturn \"\", fmt.Errorf(\"FindGlobalMapPathUUIDFromPod not supported for this build.\")\n}","line":{"from":45,"to":49}} {"id":100013255,"name":"ValidatePersistentVolume","signature":"func ValidatePersistentVolume(pv *api.PersistentVolume) field.ErrorList","file":"pkg/volume/validation/pv_validation.go","code":"// ValidatePersistentVolume validates PV object for plugin specific validation\n// We can put here validations which are specific to volume types.\nfunc ValidatePersistentVolume(pv *api.PersistentVolume) field.ErrorList {\n\treturn checkMountOption(pv)\n}","line":{"from":28,"to":32}} {"id":100013256,"name":"checkMountOption","signature":"func checkMountOption(pv *api.PersistentVolume) field.ErrorList","file":"pkg/volume/validation/pv_validation.go","code":"func checkMountOption(pv *api.PersistentVolume) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\t// if PV is of these types we don't return errors\n\t// since mount options is supported\n\tif pv.Spec.GCEPersistentDisk != nil ||\n\t\tpv.Spec.AWSElasticBlockStore != nil ||\n\t\tpv.Spec.Glusterfs != nil ||\n\t\tpv.Spec.NFS != nil ||\n\t\tpv.Spec.RBD != nil ||\n\t\tpv.Spec.Quobyte != nil ||\n\t\tpv.Spec.ISCSI != nil ||\n\t\tpv.Spec.Cinder != nil ||\n\t\tpv.Spec.CephFS != nil ||\n\t\tpv.Spec.AzureFile != nil ||\n\t\tpv.Spec.VsphereVolume != nil ||\n\t\tpv.Spec.AzureDisk != nil ||\n\t\tpv.Spec.PhotonPersistentDisk != nil {\n\t\treturn allErrs\n\t}\n\t// any other type if mount option is present lets return error\n\tif _, ok := pv.Annotations[api.MountOptionAnnotation]; ok {\n\t\tmetaField := field.NewPath(\"metadata\")\n\t\tallErrs = append(allErrs, field.Forbidden(metaField.Child(\"annotations\", api.MountOptionAnnotation), \"may not specify mount options for this volume type\"))\n\t}\n\treturn allErrs\n}","line":{"from":34,"to":59}} {"id":100013257,"name":"ValidatePathNoBacksteps","signature":"func ValidatePathNoBacksteps(targetPath string) error","file":"pkg/volume/validation/pv_validation.go","code":"// ValidatePathNoBacksteps will make sure the targetPath does not have any element which is \"..\"\nfunc ValidatePathNoBacksteps(targetPath string) error {\n\tparts := strings.Split(filepath.ToSlash(targetPath), \"/\")\n\tfor _, item := range parts {\n\t\tif item == \"..\" {\n\t\t\treturn errors.New(\"must not contain '..'\")\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":61,"to":71}} {"id":100013258,"name":"SetVolumeOwnership","signature":"func SetVolumeOwnership(mounter Mounter, dir string, fsGroup *int64, fsGroupChangePolicy *v1.PodFSGroupChangePolicy, completeFunc func(types.CompleteFuncParam)) error","file":"pkg/volume/volume_linux.go","code":"// SetVolumeOwnership modifies the given volume to be owned by\n// fsGroup, and sets SetGid so that newly created files are owned by\n// fsGroup. If fsGroup is nil nothing is done.\nfunc SetVolumeOwnership(mounter Mounter, dir string, fsGroup *int64, fsGroupChangePolicy *v1.PodFSGroupChangePolicy, completeFunc func(types.CompleteFuncParam)) error {\n\tif fsGroup == nil {\n\t\treturn nil\n\t}\n\n\ttimer := time.AfterFunc(30*time.Second, func() {\n\t\tklog.Warningf(\"Setting volume ownership for %s and fsGroup set. If the volume has a lot of files then setting volume ownership could be slow, see https://github.com/kubernetes/kubernetes/issues/69699\", dir)\n\t})\n\tdefer timer.Stop()\n\n\tif skipPermissionChange(mounter, dir, fsGroup, fsGroupChangePolicy) {\n\t\tklog.V(3).InfoS(\"Skipping permission and ownership change for volume\", \"path\", dir)\n\t\treturn nil\n\t}\n\n\terr := walkDeep(dir, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn changeFilePermission(path, fsGroup, mounter.GetAttributes().ReadOnly, info)\n\t})\n\tif completeFunc != nil {\n\t\tcompleteFunc(types.CompleteFuncParam{\n\t\t\tErr: \u0026err,\n\t\t})\n\t}\n\treturn err\n}","line":{"from":40,"to":70}} {"id":100013259,"name":"changeFilePermission","signature":"func changeFilePermission(filename string, fsGroup *int64, readonly bool, info os.FileInfo) error","file":"pkg/volume/volume_linux.go","code":"func changeFilePermission(filename string, fsGroup *int64, readonly bool, info os.FileInfo) error {\n\terr := os.Lchown(filename, -1, int(*fsGroup))\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Lchown failed\", \"path\", filename)\n\t}\n\n\t// chmod passes through to the underlying file for symlinks.\n\t// Symlinks have a mode of 777 but this really doesn't mean anything.\n\t// The permissions of the underlying file are what matter.\n\t// However, if one reads the mode of a symlink then chmods the symlink\n\t// with that mode, it changes the mode of the underlying file, overridden\n\t// the defaultMode and permissions initialized by the volume plugin, which\n\t// is not what we want; thus, we skip chmod for symlinks.\n\tif info.Mode()\u0026os.ModeSymlink != 0 {\n\t\treturn nil\n\t}\n\n\tmask := rwMask\n\tif readonly {\n\t\tmask = roMask\n\t}\n\n\tif info.IsDir() {\n\t\tmask |= os.ModeSetgid\n\t\tmask |= execMask\n\t}\n\n\terr = os.Chmod(filename, info.Mode()|mask)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"chmod failed\", \"path\", filename)\n\t}\n\n\treturn nil\n}","line":{"from":72,"to":105}} {"id":100013260,"name":"skipPermissionChange","signature":"func skipPermissionChange(mounter Mounter, dir string, fsGroup *int64, fsGroupChangePolicy *v1.PodFSGroupChangePolicy) bool","file":"pkg/volume/volume_linux.go","code":"func skipPermissionChange(mounter Mounter, dir string, fsGroup *int64, fsGroupChangePolicy *v1.PodFSGroupChangePolicy) bool {\n\tif fsGroupChangePolicy == nil || *fsGroupChangePolicy != v1.FSGroupChangeOnRootMismatch {\n\t\tklog.V(4).InfoS(\"Perform recursive ownership change for directory\", \"path\", dir)\n\t\treturn false\n\t}\n\treturn !requiresPermissionChange(dir, fsGroup, mounter.GetAttributes().ReadOnly)\n}","line":{"from":107,"to":113}} {"id":100013261,"name":"requiresPermissionChange","signature":"func requiresPermissionChange(rootDir string, fsGroup *int64, readonly bool) bool","file":"pkg/volume/volume_linux.go","code":"func requiresPermissionChange(rootDir string, fsGroup *int64, readonly bool) bool {\n\tfsInfo, err := os.Stat(rootDir)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Performing recursive ownership change on rootDir because reading permissions of root volume failed\", \"path\", rootDir)\n\t\treturn true\n\t}\n\tstat, ok := fsInfo.Sys().(*syscall.Stat_t)\n\tif !ok || stat == nil {\n\t\tklog.ErrorS(nil, \"Performing recursive ownership change on rootDir because reading permissions of root volume failed\", \"path\", rootDir)\n\t\treturn true\n\t}\n\n\tif int(stat.Gid) != int(*fsGroup) {\n\t\tklog.V(4).InfoS(\"Expected group ownership of volume did not match with Gid\", \"path\", rootDir, \"GID\", stat.Gid)\n\t\treturn true\n\t}\n\tunixPerms := rwMask\n\n\tif readonly {\n\t\tunixPerms = roMask\n\t}\n\n\t// if rootDir is not a directory then we should apply permission change anyways\n\tif !fsInfo.IsDir() {\n\t\treturn true\n\t}\n\tunixPerms |= execMask\n\tfilePerm := fsInfo.Mode().Perm()\n\n\t// We need to check if actual permissions of root directory is a superset of permissions required by unixPerms.\n\t// This is done by checking if permission bits expected in unixPerms is set in actual permissions of the directory.\n\t// We use bitwise AND operation to check set bits. For example:\n\t// unixPerms: 770, filePerms: 775 : 770\u0026775 = 770 (perms on directory is a superset)\n\t// unixPerms: 770, filePerms: 770 : 770\u0026770 = 770 (perms on directory is a superset)\n\t// unixPerms: 770, filePerms: 750 : 770\u0026750 = 750 (perms on directory is NOT a superset)\n\t// We also need to check if setgid bits are set in permissions of the directory.\n\tif (unixPerms\u0026filePerm != unixPerms) || (fsInfo.Mode()\u0026os.ModeSetgid == 0) {\n\t\tklog.V(4).InfoS(\"Performing recursive ownership change on rootDir because of mismatching mode\", \"path\", rootDir)\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":115,"to":156}} {"id":100013262,"name":"readDirNames","signature":"func readDirNames(dirname string) ([]string, error)","file":"pkg/volume/volume_linux.go","code":"// readDirNames reads the directory named by dirname and returns\n// a list of directory entries.\n// We are not using filepath.readDirNames because we do not want to sort files found in a directory before changing\n// permissions for performance reasons.\nfunc readDirNames(dirname string) ([]string, error) {\n\tf, err := os.Open(dirname)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnames, err := f.Readdirnames(-1)\n\tf.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn names, nil\n}","line":{"from":158,"to":173}} {"id":100013263,"name":"walkDeep","signature":"func walkDeep(root string, walkFunc filepath.WalkFunc) error","file":"pkg/volume/volume_linux.go","code":"// walkDeep can be used to traverse directories and has two minor differences\n// from filepath.Walk:\n// - List of files/dirs is not sorted for performance reasons\n// - callback walkFunc is invoked on root directory after visiting children dirs and files\nfunc walkDeep(root string, walkFunc filepath.WalkFunc) error {\n\tinfo, err := os.Lstat(root)\n\tif err != nil {\n\t\treturn walkFunc(root, nil, err)\n\t}\n\treturn walk(root, info, walkFunc)\n}","line":{"from":175,"to":185}} {"id":100013264,"name":"walk","signature":"func walk(path string, info os.FileInfo, walkFunc filepath.WalkFunc) error","file":"pkg/volume/volume_linux.go","code":"func walk(path string, info os.FileInfo, walkFunc filepath.WalkFunc) error {\n\tif !info.IsDir() {\n\t\treturn walkFunc(path, info, nil)\n\t}\n\tnames, err := readDirNames(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, name := range names {\n\t\tfilename := filepath.Join(path, name)\n\t\tfileInfo, err := os.Lstat(filename)\n\t\tif err != nil {\n\t\t\tif err := walkFunc(filename, fileInfo, err); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\terr = walk(filename, fileInfo, walkFunc)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn walkFunc(path, info, nil)\n}","line":{"from":187,"to":210}} {"id":100013265,"name":"SetVolumeOwnership","signature":"func SetVolumeOwnership(mounter Mounter, dir string, fsGroup *int64, fsGroupChangePolicy *v1.PodFSGroupChangePolicy, completeFunc func(types.CompleteFuncParam)) error","file":"pkg/volume/volume_unsupported.go","code":"func SetVolumeOwnership(mounter Mounter, dir string, fsGroup *int64, fsGroupChangePolicy *v1.PodFSGroupChangePolicy, completeFunc func(types.CompleteFuncParam)) error {\n\treturn nil\n}","line":{"from":27,"to":29}} {"id":100013266,"name":"NewAttacher","signature":"func (plugin *vsphereVolumePlugin) NewAttacher() (volume.Attacher, error)","file":"pkg/volume/vsphere_volume/attacher.go","code":"func (plugin *vsphereVolumePlugin) NewAttacher() (volume.Attacher, error) {\n\tvsphereCloud, err := getCloudProvider(plugin.host.GetCloudProvider())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026vsphereVMDKAttacher{\n\t\thost: plugin.host,\n\t\tvsphereVolumes: vsphereCloud,\n\t}, nil\n}","line":{"from":56,"to":66}} {"id":100013267,"name":"NewDeviceMounter","signature":"func (plugin *vsphereVolumePlugin) NewDeviceMounter() (volume.DeviceMounter, error)","file":"pkg/volume/vsphere_volume/attacher.go","code":"func (plugin *vsphereVolumePlugin) NewDeviceMounter() (volume.DeviceMounter, error) {\n\treturn plugin.NewAttacher()\n}","line":{"from":68,"to":70}} {"id":100013268,"name":"Attach","signature":"func (attacher *vsphereVMDKAttacher) Attach(spec *volume.Spec, nodeName types.NodeName) (string, error)","file":"pkg/volume/vsphere_volume/attacher.go","code":"// Attaches the volume specified by the given spec to the given host.\n// On success, returns the device path where the device was attached on the\n// node.\n// Callers are responsible for retryinging on failure.\n// Callers are responsible for thread safety between concurrent attach and\n// detach operations.\nfunc (attacher *vsphereVMDKAttacher) Attach(spec *volume.Spec, nodeName types.NodeName) (string, error) {\n\tvolumeSource, _, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tklog.V(4).Infof(\"vSphere: Attach disk called for node %s\", nodeName)\n\n\t// Keeps concurrent attach operations to same host atomic\n\tattachdetachMutex.LockKey(string(nodeName))\n\tdefer attachdetachMutex.UnlockKey(string(nodeName))\n\n\t// vsphereCloud.AttachDisk checks if disk is already attached to host and\n\t// succeeds in that case, so no need to do that separately.\n\tdiskUUID, err := attacher.vsphereVolumes.AttachDisk(volumeSource.VolumePath, volumeSource.StoragePolicyName, nodeName)\n\tif err != nil {\n\t\tklog.Errorf(\"Error attaching volume %q to node %q: %+v\", volumeSource.VolumePath, nodeName, err)\n\t\treturn \"\", err\n\t}\n\n\treturn filepath.Join(diskByIDPath, diskSCSIPrefix+diskUUID), nil\n}","line":{"from":72,"to":99}} {"id":100013269,"name":"VolumesAreAttached","signature":"func (attacher *vsphereVMDKAttacher) VolumesAreAttached(specs []*volume.Spec, nodeName types.NodeName) (map[*volume.Spec]bool, error)","file":"pkg/volume/vsphere_volume/attacher.go","code":"func (attacher *vsphereVMDKAttacher) VolumesAreAttached(specs []*volume.Spec, nodeName types.NodeName) (map[*volume.Spec]bool, error) {\n\tklog.Warningf(\"Attacher.VolumesAreAttached called for node %q - Please use BulkVerifyVolumes for vSphere\", nodeName)\n\tvolumeNodeMap := map[types.NodeName][]*volume.Spec{\n\t\tnodeName: specs,\n\t}\n\tnodeVolumesResult := make(map[*volume.Spec]bool)\n\tnodesVerificationMap, err := attacher.BulkVerifyVolumes(volumeNodeMap)\n\tif err != nil {\n\t\tklog.Errorf(\"Attacher.VolumesAreAttached - error checking volumes for node %q with %v\", nodeName, err)\n\t\treturn nodeVolumesResult, err\n\t}\n\tif result, ok := nodesVerificationMap[nodeName]; ok {\n\t\treturn result, nil\n\t}\n\treturn nodeVolumesResult, nil\n}","line":{"from":101,"to":116}} {"id":100013270,"name":"BulkVerifyVolumes","signature":"func (attacher *vsphereVMDKAttacher) BulkVerifyVolumes(volumesByNode map[types.NodeName][]*volume.Spec) (map[types.NodeName]map[*volume.Spec]bool, error)","file":"pkg/volume/vsphere_volume/attacher.go","code":"func (attacher *vsphereVMDKAttacher) BulkVerifyVolumes(volumesByNode map[types.NodeName][]*volume.Spec) (map[types.NodeName]map[*volume.Spec]bool, error) {\n\tvolumesAttachedCheck := make(map[types.NodeName]map[*volume.Spec]bool)\n\tvolumePathsByNode := make(map[types.NodeName][]string)\n\tvolumeSpecMap := make(map[string]*volume.Spec)\n\n\tfor nodeName, volumeSpecs := range volumesByNode {\n\t\tfor _, volumeSpec := range volumeSpecs {\n\t\t\tvolumeSource, _, err := getVolumeSource(volumeSpec)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"Error getting volume (%q) source : %v\", volumeSpec.Name(), err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvolPath := volumeSource.VolumePath\n\t\t\tvolumePathsByNode[nodeName] = append(volumePathsByNode[nodeName], volPath)\n\t\t\tnodeVolume, nodeVolumeExists := volumesAttachedCheck[nodeName]\n\t\t\tif !nodeVolumeExists {\n\t\t\t\tnodeVolume = make(map[*volume.Spec]bool)\n\t\t\t}\n\t\t\tnodeVolume[volumeSpec] = true\n\t\t\tvolumeSpecMap[volPath] = volumeSpec\n\t\t\tvolumesAttachedCheck[nodeName] = nodeVolume\n\t\t}\n\t}\n\tattachedResult, err := attacher.vsphereVolumes.DisksAreAttached(volumePathsByNode)\n\tif err != nil {\n\t\tklog.Errorf(\"Error checking if volumes are attached to nodes: %+v. err: %v\", volumePathsByNode, err)\n\t\treturn volumesAttachedCheck, err\n\t}\n\n\tfor nodeName, nodeVolumes := range attachedResult {\n\t\tfor volumePath, attached := range nodeVolumes {\n\t\t\tif !attached {\n\t\t\t\tspec := volumeSpecMap[volumePath]\n\t\t\t\tsetNodeVolume(volumesAttachedCheck, spec, nodeName, false)\n\t\t\t}\n\t\t}\n\t}\n\treturn volumesAttachedCheck, nil\n}","line":{"from":118,"to":156}} {"id":100013271,"name":"WaitForAttach","signature":"func (attacher *vsphereVMDKAttacher) WaitForAttach(spec *volume.Spec, devicePath string, _ *v1.Pod, timeout time.Duration) (string, error)","file":"pkg/volume/vsphere_volume/attacher.go","code":"func (attacher *vsphereVMDKAttacher) WaitForAttach(spec *volume.Spec, devicePath string, _ *v1.Pod, timeout time.Duration) (string, error) {\n\tvolumeSource, _, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif devicePath == \"\" {\n\t\treturn \"\", fmt.Errorf(\"WaitForAttach failed for VMDK %q: devicePath is empty\", volumeSource.VolumePath)\n\t}\n\n\tticker := time.NewTicker(checkSleepDuration)\n\tdefer ticker.Stop()\n\n\ttimer := time.NewTimer(timeout)\n\tdefer timer.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase \u003c-ticker.C:\n\t\t\tklog.V(5).Infof(\"Checking VMDK %q is attached\", volumeSource.VolumePath)\n\t\t\tpath, err := verifyDevicePath(devicePath)\n\t\t\tif err != nil {\n\t\t\t\t// Log error, if any, and continue checking periodically. See issue #11321\n\t\t\t\tklog.Warningf(\"Error verifying VMDK (%q) is attached: %v\", volumeSource.VolumePath, err)\n\t\t\t} else if path != \"\" {\n\t\t\t\t// A device path has successfully been created for the VMDK\n\t\t\t\tklog.Infof(\"Successfully found attached VMDK %q.\", volumeSource.VolumePath)\n\t\t\t\treturn path, nil\n\t\t\t}\n\t\tcase \u003c-timer.C:\n\t\t\treturn \"\", fmt.Errorf(\"could not find attached VMDK %q. Timeout waiting for mount paths to be created\", volumeSource.VolumePath)\n\t\t}\n\t}\n}","line":{"from":158,"to":191}} {"id":100013272,"name":"GetDeviceMountPath","signature":"func (attacher *vsphereVMDKAttacher) GetDeviceMountPath(spec *volume.Spec) (string, error)","file":"pkg/volume/vsphere_volume/attacher.go","code":"// GetDeviceMountPath returns a path where the device should\n// point which should be bind mounted for individual volumes.\nfunc (attacher *vsphereVMDKAttacher) GetDeviceMountPath(spec *volume.Spec) (string, error) {\n\tvolumeSource, _, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn makeGlobalPDPath(attacher.host, volumeSource.VolumePath), nil\n}","line":{"from":193,"to":202}} {"id":100013273,"name":"GetDeviceMountRefs","signature":"func (plugin *vsphereVolumePlugin) GetDeviceMountRefs(deviceMountPath string) ([]string, error)","file":"pkg/volume/vsphere_volume/attacher.go","code":"// GetMountDeviceRefs finds all other references to the device referenced\n// by deviceMountPath; returns a list of paths.\nfunc (plugin *vsphereVolumePlugin) GetDeviceMountRefs(deviceMountPath string) ([]string, error) {\n\tmounter := plugin.host.GetMounter(plugin.GetPluginName())\n\treturn mounter.GetMountRefs(deviceMountPath)\n}","line":{"from":204,"to":209}} {"id":100013274,"name":"MountDevice","signature":"func (attacher *vsphereVMDKAttacher) MountDevice(spec *volume.Spec, devicePath string, deviceMountPath string, _ volume.DeviceMounterArgs) error","file":"pkg/volume/vsphere_volume/attacher.go","code":"// MountDevice mounts device to global mount point.\nfunc (attacher *vsphereVMDKAttacher) MountDevice(spec *volume.Spec, devicePath string, deviceMountPath string, _ volume.DeviceMounterArgs) error {\n\tklog.Infof(\"vsphere MountDevice mount %s to %s\", devicePath, deviceMountPath)\n\tmounter := attacher.host.GetMounter(vsphereVolumePluginName)\n\tnotMnt, err := mounter.IsLikelyNotMountPoint(deviceMountPath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tdir := deviceMountPath\n\t\t\tif runtime.GOOS == \"windows\" {\n\t\t\t\tdir = filepath.Dir(deviceMountPath)\n\t\t\t}\n\t\t\tif err := os.MkdirAll(dir, 0750); err != nil {\n\t\t\t\tklog.Errorf(\"Failed to create directory at %#v. err: %s\", dir, err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tnotMnt = true\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tvolumeSource, _, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\toptions := []string{}\n\n\tif notMnt {\n\t\tdiskMounter := volumeutil.NewSafeFormatAndMountFromHost(vsphereVolumePluginName, attacher.host)\n\t\tmountOptions := volumeutil.MountOptionFromSpec(spec, options...)\n\t\terr = diskMounter.FormatAndMount(devicePath, deviceMountPath, volumeSource.FSType, mountOptions)\n\t\tif err != nil {\n\t\t\tos.Remove(deviceMountPath)\n\t\t\treturn err\n\t\t}\n\t\tklog.V(4).Infof(\"formatting spec %v devicePath %v deviceMountPath %v fs %v with options %+v\", spec.Name(), devicePath, deviceMountPath, volumeSource.FSType, options)\n\t}\n\treturn nil\n}","line":{"from":211,"to":250}} {"id":100013275,"name":"NewDetacher","signature":"func (plugin *vsphereVolumePlugin) NewDetacher() (volume.Detacher, error)","file":"pkg/volume/vsphere_volume/attacher.go","code":"func (plugin *vsphereVolumePlugin) NewDetacher() (volume.Detacher, error) {\n\tvsphereCloud, err := getCloudProvider(plugin.host.GetCloudProvider())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026vsphereVMDKDetacher{\n\t\tmounter: plugin.host.GetMounter(plugin.GetPluginName()),\n\t\tvsphereVolumes: vsphereCloud,\n\t}, nil\n}","line":{"from":261,"to":271}} {"id":100013276,"name":"NewDeviceUnmounter","signature":"func (plugin *vsphereVolumePlugin) NewDeviceUnmounter() (volume.DeviceUnmounter, error)","file":"pkg/volume/vsphere_volume/attacher.go","code":"func (plugin *vsphereVolumePlugin) NewDeviceUnmounter() (volume.DeviceUnmounter, error) {\n\treturn plugin.NewDetacher()\n}","line":{"from":273,"to":275}} {"id":100013277,"name":"Detach","signature":"func (detacher *vsphereVMDKDetacher) Detach(volumeName string, nodeName types.NodeName) error","file":"pkg/volume/vsphere_volume/attacher.go","code":"// Detach the given device from the given node.\nfunc (detacher *vsphereVMDKDetacher) Detach(volumeName string, nodeName types.NodeName) error {\n\tvolPath := getVolPathfromVolumeName(volumeName)\n\tattached, newVolumePath, err := detacher.vsphereVolumes.DiskIsAttached(volPath, nodeName)\n\tif err != nil {\n\t\t// Log error and continue with detach\n\t\tklog.Errorf(\n\t\t\t\"Error checking if volume (%q) is already attached to current node (%q). Will continue and try detach anyway. err=%v\",\n\t\t\tvolPath, nodeName, err)\n\t}\n\n\tif err == nil \u0026\u0026 !attached {\n\t\t// Volume is already detached from node.\n\t\tklog.Infof(\"detach operation was successful. volume %q is already detached from node %q.\", volPath, nodeName)\n\t\treturn nil\n\t}\n\n\tattachdetachMutex.LockKey(string(nodeName))\n\tdefer attachdetachMutex.UnlockKey(string(nodeName))\n\tif err := detacher.vsphereVolumes.DetachDisk(newVolumePath, nodeName); err != nil {\n\t\tklog.Errorf(\"Error detaching volume %q: %v\", volPath, err)\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":277,"to":301}} {"id":100013278,"name":"UnmountDevice","signature":"func (detacher *vsphereVMDKDetacher) UnmountDevice(deviceMountPath string) error","file":"pkg/volume/vsphere_volume/attacher.go","code":"func (detacher *vsphereVMDKDetacher) UnmountDevice(deviceMountPath string) error {\n\treturn mount.CleanupMountPoint(deviceMountPath, detacher.mounter, false)\n}","line":{"from":303,"to":305}} {"id":100013279,"name":"CanAttach","signature":"func (plugin *vsphereVolumePlugin) CanAttach(spec *volume.Spec) (bool, error)","file":"pkg/volume/vsphere_volume/attacher.go","code":"func (plugin *vsphereVolumePlugin) CanAttach(spec *volume.Spec) (bool, error) {\n\treturn true, nil\n}","line":{"from":307,"to":309}} {"id":100013280,"name":"CanDeviceMount","signature":"func (plugin *vsphereVolumePlugin) CanDeviceMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/vsphere_volume/attacher.go","code":"func (plugin *vsphereVolumePlugin) CanDeviceMount(spec *volume.Spec) (bool, error) {\n\treturn true, nil\n}","line":{"from":311,"to":313}} {"id":100013281,"name":"setNodeVolume","signature":"func setNodeVolume(","file":"pkg/volume/vsphere_volume/attacher.go","code":"func setNodeVolume(\n\tnodeVolumeMap map[types.NodeName]map[*volume.Spec]bool,\n\tvolumeSpec *volume.Spec,\n\tnodeName types.NodeName,\n\tcheck bool) {\n\n\tvolumeMap := nodeVolumeMap[nodeName]\n\tif volumeMap == nil {\n\t\tvolumeMap = make(map[*volume.Spec]bool)\n\t\tnodeVolumeMap[nodeName] = volumeMap\n\t}\n\tvolumeMap[volumeSpec] = check\n}","line":{"from":315,"to":327}} {"id":100013282,"name":"ProbeVolumePlugins","signature":"func ProbeVolumePlugins() []volume.VolumePlugin","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"// This is the primary entrypoint for volume plugins.\nfunc ProbeVolumePlugins() []volume.VolumePlugin {\n\treturn []volume.VolumePlugin{\u0026vsphereVolumePlugin{}}\n}","line":{"from":45,"to":48}} {"id":100013283,"name":"getPath","signature":"func getPath(uid types.UID, volName string, host volume.VolumeHost) string","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"func getPath(uid types.UID, volName string, host volume.VolumeHost) string {\n\treturn host.GetPodVolumeDir(uid, utilstrings.EscapeQualifiedName(vsphereVolumePluginName), volName)\n}","line":{"from":63,"to":65}} {"id":100013284,"name":"Init","signature":"func (plugin *vsphereVolumePlugin) Init(host volume.VolumeHost) error","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"// vSphere Volume Plugin\nfunc (plugin *vsphereVolumePlugin) Init(host volume.VolumeHost) error {\n\tplugin.host = host\n\treturn nil\n}","line":{"from":67,"to":71}} {"id":100013285,"name":"GetPluginName","signature":"func (plugin *vsphereVolumePlugin) GetPluginName() string","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"func (plugin *vsphereVolumePlugin) GetPluginName() string {\n\treturn vsphereVolumePluginName\n}","line":{"from":73,"to":75}} {"id":100013286,"name":"IsMigratedToCSI","signature":"func (plugin *vsphereVolumePlugin) IsMigratedToCSI() bool","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"func (plugin *vsphereVolumePlugin) IsMigratedToCSI() bool {\n\treturn utilfeature.DefaultFeatureGate.Enabled(features.CSIMigrationvSphere)\n}","line":{"from":77,"to":79}} {"id":100013287,"name":"GetVolumeName","signature":"func (plugin *vsphereVolumePlugin) GetVolumeName(spec *volume.Spec) (string, error)","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"func (plugin *vsphereVolumePlugin) GetVolumeName(spec *volume.Spec) (string, error) {\n\tvolumeSource, _, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn volumeSource.VolumePath, nil\n}","line":{"from":81,"to":88}} {"id":100013288,"name":"CanSupport","signature":"func (plugin *vsphereVolumePlugin) CanSupport(spec *volume.Spec) bool","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"func (plugin *vsphereVolumePlugin) CanSupport(spec *volume.Spec) bool {\n\treturn (spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.VsphereVolume != nil) ||\n\t\t(spec.Volume != nil \u0026\u0026 spec.Volume.VsphereVolume != nil)\n}","line":{"from":90,"to":93}} {"id":100013289,"name":"RequiresRemount","signature":"func (plugin *vsphereVolumePlugin) RequiresRemount(spec *volume.Spec) bool","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"func (plugin *vsphereVolumePlugin) RequiresRemount(spec *volume.Spec) bool {\n\treturn false\n}","line":{"from":95,"to":97}} {"id":100013290,"name":"SupportsMountOption","signature":"func (plugin *vsphereVolumePlugin) SupportsMountOption() bool","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"func (plugin *vsphereVolumePlugin) SupportsMountOption() bool {\n\treturn true\n}","line":{"from":99,"to":101}} {"id":100013291,"name":"SupportsBulkVolumeVerification","signature":"func (plugin *vsphereVolumePlugin) SupportsBulkVolumeVerification() bool","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"func (plugin *vsphereVolumePlugin) SupportsBulkVolumeVerification() bool {\n\treturn true\n}","line":{"from":103,"to":105}} {"id":100013292,"name":"SupportsSELinuxContextMount","signature":"func (plugin *vsphereVolumePlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error)","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"func (plugin *vsphereVolumePlugin) SupportsSELinuxContextMount(spec *volume.Spec) (bool, error) {\n\treturn false, nil\n}","line":{"from":107,"to":109}} {"id":100013293,"name":"NewMounter","signature":"func (plugin *vsphereVolumePlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error)","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"func (plugin *vsphereVolumePlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) {\n\treturn plugin.newMounterInternal(spec, pod.UID, \u0026VsphereDiskUtil{}, plugin.host.GetMounter(plugin.GetPluginName()))\n}","line":{"from":111,"to":113}} {"id":100013294,"name":"NewUnmounter","signature":"func (plugin *vsphereVolumePlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error)","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"func (plugin *vsphereVolumePlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error) {\n\treturn plugin.newUnmounterInternal(volName, podUID, \u0026VsphereDiskUtil{}, plugin.host.GetMounter(plugin.GetPluginName()))\n}","line":{"from":115,"to":117}} {"id":100013295,"name":"newMounterInternal","signature":"func (plugin *vsphereVolumePlugin) newMounterInternal(spec *volume.Spec, podUID types.UID, manager vdManager, mounter mount.Interface) (volume.Mounter, error)","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"func (plugin *vsphereVolumePlugin) newMounterInternal(spec *volume.Spec, podUID types.UID, manager vdManager, mounter mount.Interface) (volume.Mounter, error) {\n\tvvol, _, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvolPath := vvol.VolumePath\n\tfsType := vvol.FSType\n\n\treturn \u0026vsphereVolumeMounter{\n\t\tvsphereVolume: \u0026vsphereVolume{\n\t\t\tpodUID: podUID,\n\t\t\tvolName: spec.Name(),\n\t\t\tvolPath: volPath,\n\t\t\tmanager: manager,\n\t\t\tmounter: mounter,\n\t\t\tplugin: plugin,\n\t\t\tMetricsProvider: volume.NewMetricsStatFS(getPath(podUID, spec.Name(), plugin.host)),\n\t\t},\n\t\tfsType: fsType,\n\t\tdiskMounter: util.NewSafeFormatAndMountFromHost(plugin.GetPluginName(), plugin.host),\n\t\tmountOptions: util.MountOptionFromSpec(spec),\n\t}, nil\n}","line":{"from":119,"to":142}} {"id":100013296,"name":"newUnmounterInternal","signature":"func (plugin *vsphereVolumePlugin) newUnmounterInternal(volName string, podUID types.UID, manager vdManager, mounter mount.Interface) (volume.Unmounter, error)","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"func (plugin *vsphereVolumePlugin) newUnmounterInternal(volName string, podUID types.UID, manager vdManager, mounter mount.Interface) (volume.Unmounter, error) {\n\treturn \u0026vsphereVolumeUnmounter{\n\t\t\u0026vsphereVolume{\n\t\t\tpodUID: podUID,\n\t\t\tvolName: volName,\n\t\t\tmanager: manager,\n\t\t\tmounter: mounter,\n\t\t\tplugin: plugin,\n\t\t\tMetricsProvider: volume.NewMetricsStatFS(getPath(podUID, volName, plugin.host)),\n\t\t}}, nil\n}","line":{"from":144,"to":154}} {"id":100013297,"name":"ConstructVolumeSpec","signature":"func (plugin *vsphereVolumePlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error)","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"func (plugin *vsphereVolumePlugin) ConstructVolumeSpec(volumeName, mountPath string) (volume.ReconstructedVolume, error) {\n\tmounter := plugin.host.GetMounter(plugin.GetPluginName())\n\tkvh, ok := plugin.host.(volume.KubeletVolumeHost)\n\tif !ok {\n\t\treturn volume.ReconstructedVolume{}, fmt.Errorf(\"plugin volume host does not implement KubeletVolumeHost interface\")\n\t}\n\thu := kvh.GetHostUtil()\n\tpluginMntDir := util.GetPluginMountDir(plugin.host, plugin.GetPluginName())\n\tvolumePath, err := hu.GetDeviceNameFromMount(mounter, mountPath, pluginMntDir)\n\tif err != nil {\n\t\treturn volume.ReconstructedVolume{}, err\n\t}\n\tvolumePath = strings.Replace(volumePath, \"\\\\040\", \" \", -1)\n\tklog.V(5).Infof(\"vSphere volume path is %q\", volumePath)\n\tvsphereVolume := \u0026v1.Volume{\n\t\tName: volumeName,\n\t\tVolumeSource: v1.VolumeSource{\n\t\t\tVsphereVolume: \u0026v1.VsphereVirtualDiskVolumeSource{\n\t\t\t\tVolumePath: volumePath,\n\t\t\t},\n\t\t},\n\t}\n\treturn volume.ReconstructedVolume{\n\t\tSpec: volume.NewSpecFromVolume(vsphereVolume),\n\t}, nil\n}","line":{"from":156,"to":181}} {"id":100013298,"name":"GetAttributes","signature":"func (b *vsphereVolumeMounter) GetAttributes() volume.Attributes","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"func (b *vsphereVolumeMounter) GetAttributes() volume.Attributes {\n\treturn volume.Attributes{\n\t\tSELinuxRelabel: true,\n\t\tManaged: true,\n\t}\n}","line":{"from":214,"to":219}} {"id":100013299,"name":"SetUp","signature":"func (b *vsphereVolumeMounter) SetUp(mounterArgs volume.MounterArgs) error","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"// SetUp attaches the disk and bind mounts to the volume path.\nfunc (b *vsphereVolumeMounter) SetUp(mounterArgs volume.MounterArgs) error {\n\treturn b.SetUpAt(b.GetPath(), mounterArgs)\n}","line":{"from":221,"to":224}} {"id":100013300,"name":"SetUpAt","signature":"func (b *vsphereVolumeMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"// SetUp attaches the disk and bind mounts to the volume path.\nfunc (b *vsphereVolumeMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {\n\tklog.V(5).Infof(\"vSphere volume setup %s to %s\", b.volPath, dir)\n\n\t// TODO: handle failed mounts here.\n\tnotmnt, err := b.mounter.IsLikelyNotMountPoint(dir)\n\tif err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\tklog.V(4).Infof(\"IsLikelyNotMountPoint failed: %v\", err)\n\t\treturn err\n\t}\n\tif !notmnt {\n\t\tklog.V(4).Infof(\"Something is already mounted to target %s\", dir)\n\t\treturn nil\n\t}\n\n\tif runtime.GOOS != \"windows\" {\n\t\t// On Windows, Mount will create the parent of dir and mklink (create a symbolic link) at dir later, so don't create a\n\t\t// directory at dir now. Otherwise mklink will error: \"Cannot create a file when that file already exists\".\n\t\tif err := os.MkdirAll(dir, 0750); err != nil {\n\t\t\tklog.Errorf(\"Could not create directory %s: %v\", dir, err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\toptions := []string{\"bind\"}\n\n\t// Perform a bind mount to the full path to allow duplicate mounts of the same PD.\n\tglobalPDPath := makeGlobalPDPath(b.plugin.host, b.volPath)\n\tmountOptions := util.JoinMountOptions(options, b.mountOptions)\n\terr = b.mounter.MountSensitiveWithoutSystemd(globalPDPath, dir, \"\", mountOptions, nil)\n\tif err != nil {\n\t\tnotmnt, mntErr := b.mounter.IsLikelyNotMountPoint(dir)\n\t\tif mntErr != nil {\n\t\t\tklog.Errorf(\"IsLikelyNotMountPoint check failed: %v\", mntErr)\n\t\t\treturn err\n\t\t}\n\t\tif !notmnt {\n\t\t\tif mntErr = b.mounter.Unmount(dir); mntErr != nil {\n\t\t\t\tklog.Errorf(\"Failed to unmount: %v\", mntErr)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tnotmnt, mntErr := b.mounter.IsLikelyNotMountPoint(dir)\n\t\t\tif mntErr != nil {\n\t\t\t\tklog.Errorf(\"IsLikelyNotMountPoint check failed: %v\", mntErr)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !notmnt {\n\t\t\t\tklog.Errorf(\"%s is still mounted, despite call to unmount(). Will try again next sync loop.\", b.GetPath())\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tos.Remove(dir)\n\t\treturn err\n\t}\n\tvolume.SetVolumeOwnership(b, dir, mounterArgs.FsGroup, mounterArgs.FSGroupChangePolicy, util.FSGroupCompleteHook(b.plugin, nil))\n\tklog.V(3).Infof(\"vSphere volume %s mounted to %s\", b.volPath, dir)\n\n\treturn nil\n}","line":{"from":226,"to":284}} {"id":100013301,"name":"TearDown","signature":"func (v *vsphereVolumeUnmounter) TearDown() error","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"// Unmounts the bind mount, and detaches the disk only if the PD\n// resource was the last reference to that disk on the kubelet.\nfunc (v *vsphereVolumeUnmounter) TearDown() error {\n\treturn v.TearDownAt(v.GetPath())\n}","line":{"from":292,"to":296}} {"id":100013302,"name":"TearDownAt","signature":"func (v *vsphereVolumeUnmounter) TearDownAt(dir string) error","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"// Unmounts the bind mount, and detaches the disk only if the PD\n// resource was the last reference to that disk on the kubelet.\nfunc (v *vsphereVolumeUnmounter) TearDownAt(dir string) error {\n\treturn mount.CleanupMountPoint(dir, v.mounter, false)\n}","line":{"from":298,"to":302}} {"id":100013303,"name":"makeGlobalPDPath","signature":"func makeGlobalPDPath(host volume.VolumeHost, devName string) string","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"func makeGlobalPDPath(host volume.VolumeHost, devName string) string {\n\treturn filepath.Join(host.GetPluginDir(vsphereVolumePluginName), util.MountsInGlobalPDPath, devName)\n}","line":{"from":304,"to":306}} {"id":100013304,"name":"GetPath","signature":"func (vv *vsphereVolume) GetPath() string","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"func (vv *vsphereVolume) GetPath() string {\n\tname := vsphereVolumePluginName\n\treturn vv.plugin.host.GetPodVolumeDir(vv.podUID, utilstrings.EscapeQualifiedName(name), vv.volName)\n}","line":{"from":308,"to":311}} {"id":100013305,"name":"GetAccessModes","signature":"func (plugin *vsphereVolumePlugin) GetAccessModes() []v1.PersistentVolumeAccessMode","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"// vSphere Persistent Volume Plugin\nfunc (plugin *vsphereVolumePlugin) GetAccessModes() []v1.PersistentVolumeAccessMode {\n\treturn []v1.PersistentVolumeAccessMode{\n\t\tv1.ReadWriteOnce,\n\t}\n}","line":{"from":313,"to":318}} {"id":100013306,"name":"NewDeleter","signature":"func (plugin *vsphereVolumePlugin) NewDeleter(logger klog.Logger, spec *volume.Spec) (volume.Deleter, error)","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"func (plugin *vsphereVolumePlugin) NewDeleter(logger klog.Logger, spec *volume.Spec) (volume.Deleter, error) {\n\treturn plugin.newDeleterInternal(spec, \u0026VsphereDiskUtil{})\n}","line":{"from":327,"to":329}} {"id":100013307,"name":"newDeleterInternal","signature":"func (plugin *vsphereVolumePlugin) newDeleterInternal(spec *volume.Spec, manager vdManager) (volume.Deleter, error)","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"func (plugin *vsphereVolumePlugin) newDeleterInternal(spec *volume.Spec, manager vdManager) (volume.Deleter, error) {\n\tif spec.PersistentVolume != nil \u0026\u0026 spec.PersistentVolume.Spec.VsphereVolume == nil {\n\t\treturn nil, fmt.Errorf(\"spec.PersistentVolumeSource.VsphereVolume is nil\")\n\t}\n\treturn \u0026vsphereVolumeDeleter{\n\t\t\u0026vsphereVolume{\n\t\t\tvolName: spec.Name(),\n\t\t\tvolPath: spec.PersistentVolume.Spec.VsphereVolume.VolumePath,\n\t\t\tmanager: manager,\n\t\t\tplugin: plugin,\n\t\t}}, nil\n}","line":{"from":331,"to":342}} {"id":100013308,"name":"Delete","signature":"func (r *vsphereVolumeDeleter) Delete() error","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"func (r *vsphereVolumeDeleter) Delete() error {\n\treturn r.manager.DeleteVolume(r)\n}","line":{"from":344,"to":346}} {"id":100013309,"name":"NewProvisioner","signature":"func (plugin *vsphereVolumePlugin) NewProvisioner(logger klog.Logger, options volume.VolumeOptions) (volume.Provisioner, error)","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"func (plugin *vsphereVolumePlugin) NewProvisioner(logger klog.Logger, options volume.VolumeOptions) (volume.Provisioner, error) {\n\treturn plugin.newProvisionerInternal(options, \u0026VsphereDiskUtil{})\n}","line":{"from":356,"to":358}} {"id":100013310,"name":"newProvisionerInternal","signature":"func (plugin *vsphereVolumePlugin) newProvisionerInternal(options volume.VolumeOptions, manager vdManager) (volume.Provisioner, error)","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"func (plugin *vsphereVolumePlugin) newProvisionerInternal(options volume.VolumeOptions, manager vdManager) (volume.Provisioner, error) {\n\treturn \u0026vsphereVolumeProvisioner{\n\t\tvsphereVolume: \u0026vsphereVolume{\n\t\t\tmanager: manager,\n\t\t\tplugin: plugin,\n\t\t},\n\t\toptions: options,\n\t}, nil\n}","line":{"from":360,"to":368}} {"id":100013311,"name":"Provision","signature":"func (v *vsphereVolumeProvisioner) Provision(selectedNode *v1.Node, allowedTopologies []v1.TopologySelectorTerm) (*v1.PersistentVolume, error)","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"func (v *vsphereVolumeProvisioner) Provision(selectedNode *v1.Node, allowedTopologies []v1.TopologySelectorTerm) (*v1.PersistentVolume, error) {\n\tif !util.ContainsAllAccessModes(v.plugin.GetAccessModes(), v.options.PVC.Spec.AccessModes) {\n\t\treturn nil, fmt.Errorf(\"invalid AccessModes %v: only AccessModes %v are supported\", v.options.PVC.Spec.AccessModes, v.plugin.GetAccessModes())\n\t}\n\tklog.V(1).Infof(\"Provision with selectedNode: %s and allowedTopologies : %s\", getNodeName(selectedNode), allowedTopologies)\n\tselectedZones, err := volumehelpers.ZonesFromAllowedTopologies(allowedTopologies)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tklog.V(4).Infof(\"Selected zones for volume : %s\", selectedZones)\n\tvolSpec, err := v.manager.CreateVolume(v, selectedNode, selectedZones.List())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif volSpec.Fstype == \"\" {\n\t\tvolSpec.Fstype = \"ext4\"\n\t}\n\n\tvolumeMode := v.options.PVC.Spec.VolumeMode\n\tif volumeMode != nil \u0026\u0026 *volumeMode == v1.PersistentVolumeBlock {\n\t\tklog.V(5).Infof(\"vSphere block volume should not have any FSType\")\n\t\tvolSpec.Fstype = \"\"\n\t}\n\n\tpv := \u0026v1.PersistentVolume{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: v.options.PVName,\n\t\t\tLabels: map[string]string{},\n\t\t\tAnnotations: map[string]string{\n\t\t\t\tutil.VolumeDynamicallyCreatedByKey: \"vsphere-volume-dynamic-provisioner\",\n\t\t\t},\n\t\t},\n\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\tPersistentVolumeReclaimPolicy: v.options.PersistentVolumeReclaimPolicy,\n\t\t\tAccessModes: v.options.PVC.Spec.AccessModes,\n\t\t\tCapacity: v1.ResourceList{\n\t\t\t\tv1.ResourceName(v1.ResourceStorage): resource.MustParse(fmt.Sprintf(\"%dKi\", volSpec.Size)),\n\t\t\t},\n\t\t\tVolumeMode: volumeMode,\n\t\t\tPersistentVolumeSource: v1.PersistentVolumeSource{\n\t\t\t\tVsphereVolume: \u0026v1.VsphereVirtualDiskVolumeSource{\n\t\t\t\t\tVolumePath: volSpec.Path,\n\t\t\t\t\tFSType: volSpec.Fstype,\n\t\t\t\t\tStoragePolicyName: volSpec.StoragePolicyName,\n\t\t\t\t\tStoragePolicyID: volSpec.StoragePolicyID,\n\t\t\t\t},\n\t\t\t},\n\t\t\tMountOptions: v.options.MountOptions,\n\t\t},\n\t}\n\tif len(v.options.PVC.Spec.AccessModes) == 0 {\n\t\tpv.Spec.AccessModes = v.plugin.GetAccessModes()\n\t}\n\n\tlabels := volSpec.Labels\n\trequirements := make([]v1.NodeSelectorRequirement, 0)\n\tif len(labels) != 0 {\n\t\tif pv.Labels == nil {\n\t\t\tpv.Labels = make(map[string]string)\n\t\t}\n\t\tfor k, v := range labels {\n\t\t\tpv.Labels[k] = v\n\t\t\tvar values []string\n\t\t\tif k == v1.LabelTopologyZone || k == v1.LabelFailureDomainBetaZone {\n\t\t\t\tvalues, err = volumehelpers.LabelZonesToList(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"failed to convert label string for Zone: %s to a List: %v\", v, err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tvalues = []string{v}\n\t\t\t}\n\t\t\trequirements = append(requirements, v1.NodeSelectorRequirement{Key: k, Operator: v1.NodeSelectorOpIn, Values: values})\n\t\t}\n\t}\n\n\tif len(requirements) \u003e 0 {\n\t\tpv.Spec.NodeAffinity = new(v1.VolumeNodeAffinity)\n\t\tpv.Spec.NodeAffinity.Required = new(v1.NodeSelector)\n\t\tpv.Spec.NodeAffinity.Required.NodeSelectorTerms = make([]v1.NodeSelectorTerm, 1)\n\t\tpv.Spec.NodeAffinity.Required.NodeSelectorTerms[0].MatchExpressions = requirements\n\t}\n\n\treturn pv, nil\n}","line":{"from":370,"to":455}} {"id":100013312,"name":"getVolumeSource","signature":"func getVolumeSource(","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"func getVolumeSource(\n\tspec *volume.Spec) (*v1.VsphereVirtualDiskVolumeSource, bool, error) {\n\tif spec.Volume != nil \u0026\u0026 spec.Volume.VsphereVolume != nil {\n\t\treturn spec.Volume.VsphereVolume, spec.ReadOnly, nil\n\t} else if spec.PersistentVolume != nil \u0026\u0026\n\t\tspec.PersistentVolume.Spec.VsphereVolume != nil {\n\t\treturn spec.PersistentVolume.Spec.VsphereVolume, spec.ReadOnly, nil\n\t}\n\n\treturn nil, false, fmt.Errorf(\"spec does not reference a VSphere volume type\")\n}","line":{"from":457,"to":467}} {"id":100013313,"name":"getNodeName","signature":"func getNodeName(node *v1.Node) string","file":"pkg/volume/vsphere_volume/vsphere_volume.go","code":"func getNodeName(node *v1.Node) string {\n\tif node == nil {\n\t\treturn \"\"\n\t}\n\treturn node.Name\n}","line":{"from":469,"to":474}} {"id":100013314,"name":"ConstructBlockVolumeSpec","signature":"func (plugin *vsphereVolumePlugin) ConstructBlockVolumeSpec(podUID types.UID, volumeName, mapPath string) (*volume.Spec, error)","file":"pkg/volume/vsphere_volume/vsphere_volume_block.go","code":"func (plugin *vsphereVolumePlugin) ConstructBlockVolumeSpec(podUID types.UID, volumeName, mapPath string) (*volume.Spec, error) {\n\n\tpluginDir := plugin.host.GetPluginDir(plugin.GetPluginName())\n\tblkUtil := volumepathhandler.NewBlockVolumePathHandler()\n\tglobalMapPathUUID, err := blkUtil.FindGlobalMapPathUUIDFromPod(pluginDir, mapPath, podUID)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to find GlobalMapPathUUID from Pod: %s with error: %+v\", podUID, err)\n\t\treturn nil, err\n\t}\n\tklog.V(5).Infof(\"globalMapPathUUID: %v\", globalMapPathUUID)\n\tglobalMapPath := filepath.Dir(globalMapPathUUID)\n\tif len(globalMapPath) \u003c= 1 {\n\t\treturn nil, fmt.Errorf(\"failed to get volume plugin information from globalMapPathUUID: %v\", globalMapPathUUID)\n\t}\n\treturn getVolumeSpecFromGlobalMapPath(volumeName, globalMapPath)\n}","line":{"from":40,"to":55}} {"id":100013315,"name":"getVolumeSpecFromGlobalMapPath","signature":"func getVolumeSpecFromGlobalMapPath(volumeName, globalMapPath string) (*volume.Spec, error)","file":"pkg/volume/vsphere_volume/vsphere_volume_block.go","code":"func getVolumeSpecFromGlobalMapPath(volumeName, globalMapPath string) (*volume.Spec, error) {\n\t// Construct volume spec from globalMapPath\n\t// globalMapPath example:\n\t// plugins/kubernetes.io/{PluginName}/{DefaultKubeletVolumeDevicesDirName}/{volumeID}\n\t// plugins/kubernetes.io/vsphere-volume/volumeDevices/[datastore1]\\\\040volumes/myDisk\n\tvolPath := filepath.Base(globalMapPath)\n\tvolPath = strings.Replace(volPath, \"\\\\040\", \"\", -1)\n\tif len(volPath) \u003c= 1 {\n\t\treturn nil, fmt.Errorf(\"failed to get volume path from global path=%s\", globalMapPath)\n\t}\n\tblock := v1.PersistentVolumeBlock\n\tvsphereVolume := \u0026v1.PersistentVolume{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: volumeName,\n\t\t},\n\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\tPersistentVolumeSource: v1.PersistentVolumeSource{\n\t\t\t\tVsphereVolume: \u0026v1.VsphereVirtualDiskVolumeSource{\n\t\t\t\t\tVolumePath: volPath,\n\t\t\t\t},\n\t\t\t},\n\t\t\tVolumeMode: \u0026block,\n\t\t},\n\t}\n\treturn volume.NewSpecFromPersistentVolume(vsphereVolume, true), nil\n}","line":{"from":57,"to":82}} {"id":100013316,"name":"NewBlockVolumeMapper","signature":"func (plugin *vsphereVolumePlugin) NewBlockVolumeMapper(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.BlockVolumeMapper, error)","file":"pkg/volume/vsphere_volume/vsphere_volume_block.go","code":"func (plugin *vsphereVolumePlugin) NewBlockVolumeMapper(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.BlockVolumeMapper, error) {\n\t// If this called via GenerateUnmapDeviceFunc(), pod is nil.\n\t// Pass empty string as dummy uid since uid isn't used in the case.\n\tvar uid types.UID\n\tif pod != nil {\n\t\tuid = pod.UID\n\t}\n\treturn plugin.newBlockVolumeMapperInternal(spec, uid, \u0026VsphereDiskUtil{}, plugin.host.GetMounter(plugin.GetPluginName()))\n}","line":{"from":84,"to":92}} {"id":100013317,"name":"newBlockVolumeMapperInternal","signature":"func (plugin *vsphereVolumePlugin) newBlockVolumeMapperInternal(spec *volume.Spec, podUID types.UID, manager vdManager, mounter mount.Interface) (volume.BlockVolumeMapper, error)","file":"pkg/volume/vsphere_volume/vsphere_volume_block.go","code":"func (plugin *vsphereVolumePlugin) newBlockVolumeMapperInternal(spec *volume.Spec, podUID types.UID, manager vdManager, mounter mount.Interface) (volume.BlockVolumeMapper, error) {\n\tvolumeSource, _, err := getVolumeSource(spec)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get Volume source from volume Spec: %+v with error: %+v\", *spec, err)\n\t\treturn nil, err\n\t}\n\tvolPath := volumeSource.VolumePath\n\tmapper := \u0026vsphereBlockVolumeMapper{\n\t\tvsphereVolume: \u0026vsphereVolume{\n\t\t\tvolName: spec.Name(),\n\t\t\tpodUID: podUID,\n\t\t\tvolPath: volPath,\n\t\t\tmanager: manager,\n\t\t\tmounter: mounter,\n\t\t\tplugin: plugin,\n\t\t\tMetricsProvider: volume.NewMetricsStatFS(getPath(podUID, spec.Name(), plugin.host)),\n\t\t},\n\t}\n\n\tblockPath, err := mapper.GetGlobalMapPath(spec)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get device path: %v\", err)\n\t}\n\tmapper.MetricsProvider = volume.NewMetricsBlock(filepath.Join(blockPath, string(podUID)))\n\n\treturn mapper, nil\n}","line":{"from":94,"to":120}} {"id":100013318,"name":"NewBlockVolumeUnmapper","signature":"func (plugin *vsphereVolumePlugin) NewBlockVolumeUnmapper(volName string, podUID types.UID) (volume.BlockVolumeUnmapper, error)","file":"pkg/volume/vsphere_volume/vsphere_volume_block.go","code":"func (plugin *vsphereVolumePlugin) NewBlockVolumeUnmapper(volName string, podUID types.UID) (volume.BlockVolumeUnmapper, error) {\n\treturn plugin.newUnmapperInternal(volName, podUID, \u0026VsphereDiskUtil{})\n}","line":{"from":122,"to":124}} {"id":100013319,"name":"newUnmapperInternal","signature":"func (plugin *vsphereVolumePlugin) newUnmapperInternal(volName string, podUID types.UID, manager vdManager) (volume.BlockVolumeUnmapper, error)","file":"pkg/volume/vsphere_volume/vsphere_volume_block.go","code":"func (plugin *vsphereVolumePlugin) newUnmapperInternal(volName string, podUID types.UID, manager vdManager) (volume.BlockVolumeUnmapper, error) {\n\treturn \u0026vsphereBlockVolumeUnmapper{\n\t\tvsphereVolume: \u0026vsphereVolume{\n\t\t\tvolName: volName,\n\t\t\tpodUID: podUID,\n\t\t\tvolPath: volName,\n\t\t\tmanager: manager,\n\t\t\tplugin: plugin,\n\t\t},\n\t}, nil\n}","line":{"from":126,"to":136}} {"id":100013320,"name":"GetGlobalMapPath","signature":"func (v *vsphereVolume) GetGlobalMapPath(spec *volume.Spec) (string, error)","file":"pkg/volume/vsphere_volume/vsphere_volume_block.go","code":"// GetGlobalMapPath returns global map path and error\n// path: plugins/kubernetes.io/{PluginName}/volumeDevices/volumePath\nfunc (v *vsphereVolume) GetGlobalMapPath(spec *volume.Spec) (string, error) {\n\tvolumeSource, _, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Join(v.plugin.host.GetVolumeDevicePluginDir(vsphereVolumePluginName), string(volumeSource.VolumePath)), nil\n}","line":{"from":151,"to":159}} {"id":100013321,"name":"GetPodDeviceMapPath","signature":"func (v *vsphereVolume) GetPodDeviceMapPath() (string, string)","file":"pkg/volume/vsphere_volume/vsphere_volume_block.go","code":"func (v *vsphereVolume) GetPodDeviceMapPath() (string, string) {\n\treturn v.plugin.host.GetPodVolumeDeviceDir(v.podUID, utilstrings.EscapeQualifiedName(vsphereVolumePluginName)), v.volName\n}","line":{"from":161,"to":163}} {"id":100013322,"name":"SupportsMetrics","signature":"func (vbvm *vsphereBlockVolumeMapper) SupportsMetrics() bool","file":"pkg/volume/vsphere_volume/vsphere_volume_block.go","code":"// SupportsMetrics returns true for vsphereBlockVolumeMapper as it initializes the\n// MetricsProvider.\nfunc (vbvm *vsphereBlockVolumeMapper) SupportsMetrics() bool {\n\treturn true\n}","line":{"from":165,"to":169}} {"id":100013323,"name":"CreateVolume","signature":"func (util *VsphereDiskUtil) CreateVolume(v *vsphereVolumeProvisioner, selectedNode *v1.Node, selectedZone []string) (volSpec *VolumeSpec, err error)","file":"pkg/volume/vsphere_volume/vsphere_volume_util.go","code":"// CreateVolume creates a vSphere volume.\nfunc (util *VsphereDiskUtil) CreateVolume(v *vsphereVolumeProvisioner, selectedNode *v1.Node, selectedZone []string) (volSpec *VolumeSpec, err error) {\n\tvar fstype string\n\tcloud, err := getCloudProvider(v.plugin.host.GetCloudProvider())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcapacity := v.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]\n\t// vSphere works with KiB, but its minimum allocation unit is 1 MiB\n\tvolSizeMiB, err := volumehelpers.RoundUpToMiBInt(capacity)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvolSizeKiB := volSizeMiB * 1024\n\tname := volumeutil.GenerateVolumeName(v.options.ClusterName, v.options.PVName, maxVolumeLength)\n\tvolumeOptions := \u0026vclib.VolumeOptions{\n\t\tCapacityKB: volSizeKiB,\n\t\tTags: *v.options.CloudTags,\n\t\tName: name,\n\t}\n\n\tvolumeOptions.Zone = selectedZone\n\tvolumeOptions.SelectedNode = selectedNode\n\t// Apply Parameters (case-insensitive). We leave validation of\n\t// the values to the cloud provider.\n\tfor parameter, value := range v.options.Parameters {\n\t\tswitch strings.ToLower(parameter) {\n\t\tcase diskformat:\n\t\t\tvolumeOptions.DiskFormat = value\n\t\tcase datastore:\n\t\t\tvolumeOptions.Datastore = value\n\t\tcase volume.VolumeParameterFSType:\n\t\t\tfstype = value\n\t\t\tklog.V(4).Infof(\"Setting fstype as %q\", fstype)\n\t\tcase StoragePolicyName:\n\t\t\tvolumeOptions.StoragePolicyName = value\n\t\t\tklog.V(4).Infof(\"Setting StoragePolicyName as %q\", volumeOptions.StoragePolicyName)\n\t\tcase HostFailuresToTolerateCapability, ForceProvisioningCapability,\n\t\t\tCacheReservationCapability, DiskStripesCapability,\n\t\t\tObjectSpaceReservationCapability, IopsLimitCapability:\n\t\t\tcapabilityData, err := validateVSANCapability(strings.ToLower(parameter), value)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tvolumeOptions.VSANStorageProfileData += capabilityData\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"invalid option %q for volume plugin %s\", parameter, v.plugin.GetPluginName())\n\t\t}\n\t}\n\n\tif volumeOptions.VSANStorageProfileData != \"\" {\n\t\tif volumeOptions.StoragePolicyName != \"\" {\n\t\t\treturn nil, fmt.Errorf(\"cannot specify storage policy capabilities along with storage policy name. Please specify only one\")\n\t\t}\n\t\tvolumeOptions.VSANStorageProfileData = \"(\" + volumeOptions.VSANStorageProfileData + \")\"\n\t}\n\tklog.V(4).Infof(\"VSANStorageProfileData in vsphere volume %q\", volumeOptions.VSANStorageProfileData)\n\t// TODO: implement PVC.Selector parsing\n\tif v.options.PVC.Spec.Selector != nil {\n\t\treturn nil, fmt.Errorf(\"claim.Spec.Selector is not supported for dynamic provisioning on vSphere\")\n\t}\n\n\tvmDiskPath, err := cloud.CreateVolume(volumeOptions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlabels, err := cloud.GetVolumeLabels(vmDiskPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvolSpec = \u0026VolumeSpec{\n\t\tPath: vmDiskPath,\n\t\tSize: volSizeKiB,\n\t\tFstype: fstype,\n\t\tStoragePolicyName: volumeOptions.StoragePolicyName,\n\t\tStoragePolicyID: volumeOptions.StoragePolicyID,\n\t\tLabels: labels,\n\t}\n\tklog.V(2).Infof(\"Successfully created vsphere volume %s\", name)\n\treturn volSpec, nil\n}","line":{"from":95,"to":176}} {"id":100013324,"name":"DeleteVolume","signature":"func (util *VsphereDiskUtil) DeleteVolume(vd *vsphereVolumeDeleter) error","file":"pkg/volume/vsphere_volume/vsphere_volume_util.go","code":"// DeleteVolume deletes a vSphere volume.\nfunc (util *VsphereDiskUtil) DeleteVolume(vd *vsphereVolumeDeleter) error {\n\tcloud, err := getCloudProvider(vd.plugin.host.GetCloudProvider())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = cloud.DeleteVolume(vd.volPath); err != nil {\n\t\tklog.V(2).Infof(\"Error deleting vsphere volume %s: %v\", vd.volPath, err)\n\t\treturn err\n\t}\n\tklog.V(2).Infof(\"Successfully deleted vsphere volume %s\", vd.volPath)\n\treturn nil\n}","line":{"from":178,"to":191}} {"id":100013325,"name":"getVolPathfromVolumeName","signature":"func getVolPathfromVolumeName(deviceMountPath string) string","file":"pkg/volume/vsphere_volume/vsphere_volume_util.go","code":"func getVolPathfromVolumeName(deviceMountPath string) string {\n\t// Assumption: No file or folder is named starting with '[' in datastore\n\tvolPath := deviceMountPath[strings.LastIndex(deviceMountPath, \"[\"):]\n\t// space between datastore and vmdk name in volumePath is encoded as '\\040' when returned by GetMountRefs().\n\t// volumePath eg: \"[local] xxx.vmdk\" provided to attach/mount\n\t// replacing \\040 with space to match the actual volumePath\n\treturn strings.Replace(volPath, \"\\\\040\", \" \", -1)\n}","line":{"from":193,"to":200}} {"id":100013326,"name":"getCloudProvider","signature":"func getCloudProvider(cloud cloudprovider.Interface) (*vsphere.VSphere, error)","file":"pkg/volume/vsphere_volume/vsphere_volume_util.go","code":"func getCloudProvider(cloud cloudprovider.Interface) (*vsphere.VSphere, error) {\n\tif cloud == nil {\n\t\tklog.Errorf(\"Cloud provider not initialized properly\")\n\t\treturn nil, errors.New(\"cloud provider not initialized properly\")\n\t}\n\n\tvs, ok := cloud.(*vsphere.VSphere)\n\tif !ok || vs == nil {\n\t\treturn nil, errors.New(\"invalid cloud provider: expected vSphere\")\n\t}\n\treturn vs, nil\n}","line":{"from":202,"to":213}} {"id":100013327,"name":"validateVSANCapability","signature":"func validateVSANCapability(capabilityName string, capabilityValue string) (string, error)","file":"pkg/volume/vsphere_volume/vsphere_volume_util.go","code":"// Validate the capability requirement for the user specified policy attributes.\nfunc validateVSANCapability(capabilityName string, capabilityValue string) (string, error) {\n\tvar capabilityData string\n\tcapabilityIntVal, ok := verifyCapabilityValueIsInteger(capabilityValue)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"invalid value for %s. The capabilityValue: %s must be a valid integer value\", capabilityName, capabilityValue)\n\t}\n\tswitch strings.ToLower(capabilityName) {\n\tcase HostFailuresToTolerateCapability:\n\t\tif capabilityIntVal \u003e= HostFailuresToTolerateCapabilityMin \u0026\u0026 capabilityIntVal \u003c= HostFailuresToTolerateCapabilityMax {\n\t\t\tcapabilityData = \" (\\\"hostFailuresToTolerate\\\" i\" + capabilityValue + \")\"\n\t\t} else {\n\t\t\treturn \"\", fmt.Errorf(`invalid value for hostFailuresToTolerate.\n\t\t\t\tThe default value is %d, minimum value is %d and maximum value is %d`,\n\t\t\t\t1, HostFailuresToTolerateCapabilityMin, HostFailuresToTolerateCapabilityMax)\n\t\t}\n\tcase ForceProvisioningCapability:\n\t\tif capabilityIntVal \u003e= ForceProvisioningCapabilityMin \u0026\u0026 capabilityIntVal \u003c= ForceProvisioningCapabilityMax {\n\t\t\tcapabilityData = \" (\\\"forceProvisioning\\\" i\" + capabilityValue + \")\"\n\t\t} else {\n\t\t\treturn \"\", fmt.Errorf(`invalid value for forceProvisioning.\n\t\t\t\tThe value can be either %d or %d`,\n\t\t\t\tForceProvisioningCapabilityMin, ForceProvisioningCapabilityMax)\n\t\t}\n\tcase CacheReservationCapability:\n\t\tif capabilityIntVal \u003e= CacheReservationCapabilityMin \u0026\u0026 capabilityIntVal \u003c= CacheReservationCapabilityMax {\n\t\t\tcapabilityData = \" (\\\"cacheReservation\\\" i\" + strconv.Itoa(capabilityIntVal*10000) + \")\"\n\t\t} else {\n\t\t\treturn \"\", fmt.Errorf(`invalid value for cacheReservation.\n\t\t\t\tThe minimum percentage is %d and maximum percentage is %d`,\n\t\t\t\tCacheReservationCapabilityMin, CacheReservationCapabilityMax)\n\t\t}\n\tcase DiskStripesCapability:\n\t\tif capabilityIntVal \u003e= DiskStripesCapabilityMin \u0026\u0026 capabilityIntVal \u003c= DiskStripesCapabilityMax {\n\t\t\tcapabilityData = \" (\\\"stripeWidth\\\" i\" + capabilityValue + \")\"\n\t\t} else {\n\t\t\treturn \"\", fmt.Errorf(`invalid value for diskStripes.\n\t\t\t\tThe minimum value is %d and maximum value is %d`,\n\t\t\t\tDiskStripesCapabilityMin, DiskStripesCapabilityMax)\n\t\t}\n\tcase ObjectSpaceReservationCapability:\n\t\tif capabilityIntVal \u003e= ObjectSpaceReservationCapabilityMin \u0026\u0026 capabilityIntVal \u003c= ObjectSpaceReservationCapabilityMax {\n\t\t\tcapabilityData = \" (\\\"proportionalCapacity\\\" i\" + capabilityValue + \")\"\n\t\t} else {\n\t\t\treturn \"\", fmt.Errorf(`invalid value for ObjectSpaceReservation.\n\t\t\t\tThe minimum percentage is %d and maximum percentage is %d`,\n\t\t\t\tObjectSpaceReservationCapabilityMin, ObjectSpaceReservationCapabilityMax)\n\t\t}\n\tcase IopsLimitCapability:\n\t\tif capabilityIntVal \u003e= IopsLimitCapabilityMin {\n\t\t\tcapabilityData = \" (\\\"iopsLimit\\\" i\" + capabilityValue + \")\"\n\t\t} else {\n\t\t\treturn \"\", fmt.Errorf(`invalid value for iopsLimit.\n\t\t\t\tThe value should be greater than %d`, IopsLimitCapabilityMin)\n\t\t}\n\t}\n\treturn capabilityData, nil\n}","line":{"from":215,"to":272}} {"id":100013328,"name":"verifyCapabilityValueIsInteger","signature":"func verifyCapabilityValueIsInteger(capabilityValue string) (int, bool)","file":"pkg/volume/vsphere_volume/vsphere_volume_util.go","code":"// Verify if the capability value is of type integer.\nfunc verifyCapabilityValueIsInteger(capabilityValue string) (int, bool) {\n\ti, err := strconv.Atoi(capabilityValue)\n\tif err != nil {\n\t\treturn -1, false\n\t}\n\treturn i, true\n}","line":{"from":274,"to":281}} {"id":100013329,"name":"verifyDevicePath","signature":"func verifyDevicePath(path string) (string, error)","file":"pkg/volume/vsphere_volume/vsphere_volume_util_linux.go","code":"func verifyDevicePath(path string) (string, error) {\n\tif pathExists, err := mount.PathExists(path); err != nil {\n\t\treturn \"\", fmt.Errorf(\"error checking if path exists: %w\", err)\n\t} else if pathExists {\n\t\treturn path, nil\n\t}\n\n\treturn \"\", nil\n}","line":{"from":28,"to":36}} {"id":100013330,"name":"verifyDevicePath","signature":"func verifyDevicePath(path string) (string, error)","file":"pkg/volume/vsphere_volume/vsphere_volume_util_unsupported.go","code":"func verifyDevicePath(path string) (string, error) {\n\treturn \"\", errors.New(\"unsupported\")\n}","line":{"from":24,"to":26}} {"id":100013331,"name":"verifyDevicePath","signature":"func verifyDevicePath(path string) (string, error)","file":"pkg/volume/vsphere_volume/vsphere_volume_util_windows.go","code":"func verifyDevicePath(path string) (string, error) {\n\tif !strings.Contains(path, diskByIDPath) {\n\t\t// If this volume has already been mounted then\n\t\t// its devicePath will have already been converted to a disk number\n\t\tklog.V(4).Infof(\"Found vSphere disk attached with disk number %v\", path)\n\t\treturn path, nil\n\t}\n\tcmd := exec.Command(\"powershell\", \"/c\", \"Get-Disk | Select Number, SerialNumber | ConvertTo-JSON\")\n\toutput, err := cmd.Output()\n\tif err != nil {\n\t\tklog.Errorf(\"Get-Disk failed, error: %v, output: %q\", err, string(output))\n\t\treturn \"\", err\n\t}\n\n\tvar results []diskInfoResult\n\tif err = json.Unmarshal(output, \u0026results); err != nil {\n\t\tklog.Errorf(\"Failed to unmarshal Get-Disk json, output: %q\", string(output))\n\t\treturn \"\", err\n\t}\n\tserialNumber := strings.TrimPrefix(path, diskByIDPath+diskSCSIPrefix)\n\tfor _, v := range results {\n\t\tif v.SerialNumber == serialNumber {\n\t\t\tklog.V(4).Infof(\"Found vSphere disk attached with serial %v\", serialNumber)\n\t\t\treturn v.Number.String(), nil\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"unable to find vSphere disk with serial %v\", serialNumber)\n}","line":{"from":36,"to":64}} {"id":100013332,"name":"InitService","signature":"func InitService(serviceName string) error","file":"pkg/windows/service/service.go","code":"// InitService is the entry point for running the daemon as a Windows\n// service. It returns an indication of whether it is running as a service;\n// and an error.\nfunc InitService(serviceName string) error {\n\th := \u0026handler{\n\t\ttosvc: make(chan bool),\n\t\tfromsvc: make(chan error),\n\t}\n\n\tvar err error\n\tgo func() {\n\t\terr = svc.Run(serviceName, h)\n\t\th.fromsvc \u003c- err\n\t}()\n\n\t// Wait for the first signal from the service handler.\n\terr = \u003c-h.fromsvc\n\tif err != nil {\n\t\treturn err\n\t}\n\tklog.Infof(\"Running %s as a Windows service!\", serviceName)\n\treturn nil\n}","line":{"from":38,"to":60}} {"id":100013333,"name":"Execute","signature":"func (h *handler) Execute(_ []string, r \u003c-chan svc.ChangeRequest, s chan\u003c- svc.Status) (bool, uint32)","file":"pkg/windows/service/service.go","code":"func (h *handler) Execute(_ []string, r \u003c-chan svc.ChangeRequest, s chan\u003c- svc.Status) (bool, uint32) {\n\ts \u003c- svc.Status{State: svc.StartPending, Accepts: 0}\n\t// Unblock initService()\n\th.fromsvc \u003c- nil\n\n\ts \u003c- svc.Status{State: svc.Running, Accepts: svc.AcceptStop | svc.AcceptShutdown | svc.Accepted(windows.SERVICE_ACCEPT_PARAMCHANGE)}\n\tklog.Infof(\"Service running\")\nLoop:\n\tfor {\n\t\tselect {\n\t\tcase \u003c-h.tosvc:\n\t\t\tbreak Loop\n\t\tcase c := \u003c-r:\n\t\t\tswitch c.Cmd {\n\t\t\tcase svc.Cmd(windows.SERVICE_CONTROL_PARAMCHANGE):\n\t\t\t\ts \u003c- c.CurrentStatus\n\t\t\tcase svc.Interrogate:\n\t\t\t\ts \u003c- c.CurrentStatus\n\t\t\tcase svc.Stop, svc.Shutdown:\n\t\t\t\tklog.Infof(\"Service stopping\")\n\t\t\t\t// We need to translate this request into a signal that can be handled by the signal handler\n\t\t\t\t// handling shutdowns normally (currently apiserver/pkg/server/signal.go).\n\t\t\t\t// If we do not do this, our main threads won't be notified of the upcoming shutdown.\n\t\t\t\t// Since Windows services do not use any console, we cannot simply generate a CTRL_BREAK_EVENT\n\t\t\t\t// but need a dedicated notification mechanism.\n\t\t\t\tgraceful := server.RequestShutdown()\n\n\t\t\t\t// Free up the control handler and let us terminate as gracefully as possible.\n\t\t\t\t// If that takes too long, the service controller will kill the remaining threads.\n\t\t\t\t// As per https://docs.microsoft.com/en-us/windows/desktop/services/service-control-handler-function\n\t\t\t\ts \u003c- svc.Status{State: svc.StopPending}\n\n\t\t\t\t// If we cannot exit gracefully, we really only can exit our process, so at least the\n\t\t\t\t// service manager will think that we gracefully exited. At the time of writing this comment this is\n\t\t\t\t// needed for applications that do not use signals (e.g. kube-proxy)\n\t\t\t\tif !graceful {\n\t\t\t\t\tgo func() {\n\t\t\t\t\t\t// Ensure the SCM was notified (The operation above (send to s) was received and communicated to the\n\t\t\t\t\t\t// service control manager - so it doesn't look like the service crashes)\n\t\t\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t\t\t\tos.Exit(0)\n\t\t\t\t\t}()\n\t\t\t\t}\n\t\t\t\tbreak Loop\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false, 0\n}","line":{"from":62,"to":111}} {"id":100013334,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/admit/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\treturn NewAlwaysAdmit(), nil\n\t})\n}","line":{"from":30,"to":35}} {"id":100013335,"name":"Admit","signature":"func (alwaysAdmit) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error)","file":"plugin/pkg/admission/admit/admission.go","code":"// Admit makes an admission decision based on the request attributes\nfunc (alwaysAdmit) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {\n\treturn nil\n}","line":{"from":43,"to":46}} {"id":100013336,"name":"Validate","signature":"func (alwaysAdmit) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error)","file":"plugin/pkg/admission/admit/admission.go","code":"// Validate makes an admission decision based on the request attributes. It is NOT allowed to mutate.\nfunc (alwaysAdmit) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {\n\treturn nil\n}","line":{"from":48,"to":51}} {"id":100013337,"name":"Handles","signature":"func (alwaysAdmit) Handles(operation admission.Operation) bool","file":"plugin/pkg/admission/admit/admission.go","code":"// Handles returns true if this admission controller can handle the given operation\n// where operation can be one of CREATE, UPDATE, DELETE, or CONNECT\nfunc (alwaysAdmit) Handles(operation admission.Operation) bool {\n\treturn true\n}","line":{"from":53,"to":57}} {"id":100013338,"name":"NewAlwaysAdmit","signature":"func NewAlwaysAdmit() admission.Interface","file":"plugin/pkg/admission/admit/admission.go","code":"// NewAlwaysAdmit creates a new always admit admission handler\nfunc NewAlwaysAdmit() admission.Interface {\n\t// DEPRECATED: AlwaysAdmit admit all admission request, it is no use.\n\tklog.Warningf(\"%s admission controller is deprecated. \"+\n\t\t\"Please remove this controller from your configuration files and scripts.\", PluginName)\n\treturn new(alwaysAdmit)\n}","line":{"from":59,"to":65}} {"id":100013339,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/alwayspullimages/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\treturn NewAlwaysPullImages(), nil\n\t})\n}","line":{"from":44,"to":49}} {"id":100013340,"name":"Admit","signature":"func (a *AlwaysPullImages) Admit(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) (err error)","file":"plugin/pkg/admission/alwayspullimages/admission.go","code":"// Admit makes an admission decision based on the request attributes\nfunc (a *AlwaysPullImages) Admit(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) (err error) {\n\t// Ignore all calls to subresources or resources other than pods.\n\tif shouldIgnore(attributes) {\n\t\treturn nil\n\t}\n\tpod, ok := attributes.GetObject().(*api.Pod)\n\tif !ok {\n\t\treturn apierrors.NewBadRequest(\"Resource was marked with kind Pod but was unable to be converted\")\n\t}\n\n\tpods.VisitContainersWithPath(\u0026pod.Spec, field.NewPath(\"spec\"), func(c *api.Container, _ *field.Path) bool {\n\t\tc.ImagePullPolicy = api.PullAlways\n\t\treturn true\n\t})\n\n\treturn nil\n}","line":{"from":60,"to":77}} {"id":100013341,"name":"Validate","signature":"func (*AlwaysPullImages) Validate(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) (err error)","file":"plugin/pkg/admission/alwayspullimages/admission.go","code":"// Validate makes sure that all containers are set to always pull images\nfunc (*AlwaysPullImages) Validate(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) (err error) {\n\tif shouldIgnore(attributes) {\n\t\treturn nil\n\t}\n\n\tpod, ok := attributes.GetObject().(*api.Pod)\n\tif !ok {\n\t\treturn apierrors.NewBadRequest(\"Resource was marked with kind Pod but was unable to be converted\")\n\t}\n\n\tvar allErrs []error\n\tpods.VisitContainersWithPath(\u0026pod.Spec, field.NewPath(\"spec\"), func(c *api.Container, p *field.Path) bool {\n\t\tif c.ImagePullPolicy != api.PullAlways {\n\t\t\tallErrs = append(allErrs, admission.NewForbidden(attributes,\n\t\t\t\tfield.NotSupported(p.Child(\"imagePullPolicy\"), c.ImagePullPolicy, []string{string(api.PullAlways)}),\n\t\t\t))\n\t\t}\n\t\treturn true\n\t})\n\tif len(allErrs) \u003e 0 {\n\t\treturn utilerrors.NewAggregate(allErrs)\n\t}\n\n\treturn nil\n}","line":{"from":79,"to":104}} {"id":100013342,"name":"isUpdateWithNoNewImages","signature":"func isUpdateWithNoNewImages(attributes admission.Attributes) bool","file":"plugin/pkg/admission/alwayspullimages/admission.go","code":"// check if it's update and it doesn't change the images referenced by the pod spec\nfunc isUpdateWithNoNewImages(attributes admission.Attributes) bool {\n\tif attributes.GetOperation() != admission.Update {\n\t\treturn false\n\t}\n\n\tpod, ok := attributes.GetObject().(*api.Pod)\n\tif !ok {\n\t\tklog.Warningf(\"Resource was marked with kind Pod but pod was unable to be converted.\")\n\t\treturn false\n\t}\n\n\toldPod, ok := attributes.GetOldObject().(*api.Pod)\n\tif !ok {\n\t\tklog.Warningf(\"Resource was marked with kind Pod but old pod was unable to be converted.\")\n\t\treturn false\n\t}\n\n\toldImages := sets.NewString()\n\tpods.VisitContainersWithPath(\u0026oldPod.Spec, field.NewPath(\"spec\"), func(c *api.Container, _ *field.Path) bool {\n\t\toldImages.Insert(c.Image)\n\t\treturn true\n\t})\n\n\thasNewImage := false\n\tpods.VisitContainersWithPath(\u0026pod.Spec, field.NewPath(\"spec\"), func(c *api.Container, _ *field.Path) bool {\n\t\tif !oldImages.Has(c.Image) {\n\t\t\thasNewImage = true\n\t\t}\n\t\treturn !hasNewImage\n\t})\n\treturn !hasNewImage\n}","line":{"from":106,"to":138}} {"id":100013343,"name":"shouldIgnore","signature":"func shouldIgnore(attributes admission.Attributes) bool","file":"plugin/pkg/admission/alwayspullimages/admission.go","code":"func shouldIgnore(attributes admission.Attributes) bool {\n\t// Ignore all calls to subresources or resources other than pods.\n\tif len(attributes.GetSubresource()) != 0 || attributes.GetResource().GroupResource() != api.Resource(\"pods\") {\n\t\treturn true\n\t}\n\n\tif isUpdateWithNoNewImages(attributes) {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":140,"to":150}} {"id":100013344,"name":"NewAlwaysPullImages","signature":"func NewAlwaysPullImages() *AlwaysPullImages","file":"plugin/pkg/admission/alwayspullimages/admission.go","code":"// NewAlwaysPullImages creates a new always pull images admission control handler\nfunc NewAlwaysPullImages() *AlwaysPullImages {\n\treturn \u0026AlwaysPullImages{\n\t\tHandler: admission.NewHandler(admission.Create, admission.Update),\n\t}\n}","line":{"from":152,"to":157}} {"id":100013345,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/antiaffinity/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\treturn NewInterPodAntiAffinity(), nil\n\t})\n}","line":{"from":33,"to":38}} {"id":100013346,"name":"NewInterPodAntiAffinity","signature":"func NewInterPodAntiAffinity() *Plugin","file":"plugin/pkg/admission/antiaffinity/admission.go","code":"// NewInterPodAntiAffinity creates a new instance of the LimitPodHardAntiAffinityTopology admission controller\nfunc NewInterPodAntiAffinity() *Plugin {\n\treturn \u0026Plugin{\n\t\tHandler: admission.NewHandler(admission.Create, admission.Update),\n\t}\n}","line":{"from":47,"to":52}} {"id":100013347,"name":"Validate","signature":"func (p *Plugin) Validate(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) (err error)","file":"plugin/pkg/admission/antiaffinity/admission.go","code":"// Validate will deny any pod that defines AntiAffinity topology key other than v1.LabelHostname i.e. \"kubernetes.io/hostname\"\n// in requiredDuringSchedulingRequiredDuringExecution and requiredDuringSchedulingIgnoredDuringExecution.\nfunc (p *Plugin) Validate(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) (err error) {\n\t// Ignore all calls to subresources or resources other than pods.\n\tif len(attributes.GetSubresource()) != 0 || attributes.GetResource().GroupResource() != api.Resource(\"pods\") {\n\t\treturn nil\n\t}\n\tpod, ok := attributes.GetObject().(*api.Pod)\n\tif !ok {\n\t\treturn apierrors.NewBadRequest(\"Resource was marked with kind Pod but was unable to be converted\")\n\t}\n\taffinity := pod.Spec.Affinity\n\tif affinity != nil \u0026\u0026 affinity.PodAntiAffinity != nil {\n\t\tvar podAntiAffinityTerms []api.PodAffinityTerm\n\t\tif len(affinity.PodAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution) != 0 {\n\t\t\tpodAntiAffinityTerms = affinity.PodAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution\n\t\t}\n\t\t// TODO: Uncomment this block when implement RequiredDuringSchedulingRequiredDuringExecution.\n\t\t//if len(affinity.PodAntiAffinity.RequiredDuringSchedulingRequiredDuringExecution) != 0 {\n\t\t// podAntiAffinityTerms = append(podAntiAffinityTerms, affinity.PodAntiAffinity.RequiredDuringSchedulingRequiredDuringExecution...)\n\t\t//}\n\t\tfor _, v := range podAntiAffinityTerms {\n\t\t\tif v.TopologyKey != v1.LabelHostname {\n\t\t\t\treturn apierrors.NewForbidden(attributes.GetResource().GroupResource(), pod.Name, fmt.Errorf(\"affinity.PodAntiAffinity.RequiredDuringScheduling has TopologyKey %v but only key %v is allowed\", v.TopologyKey, v1.LabelHostname))\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":54,"to":82}} {"id":100013348,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/certificates/approval/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\treturn NewPlugin(), nil\n\t})\n}","line":{"from":37,"to":42}} {"id":100013349,"name":"SetAuthorizer","signature":"func (p *Plugin) SetAuthorizer(authz authorizer.Authorizer)","file":"plugin/pkg/admission/certificates/approval/admission.go","code":"// SetAuthorizer sets the authorizer.\nfunc (p *Plugin) SetAuthorizer(authz authorizer.Authorizer) {\n\tp.authz = authz\n}","line":{"from":50,"to":53}} {"id":100013350,"name":"ValidateInitialization","signature":"func (p *Plugin) ValidateInitialization() error","file":"plugin/pkg/admission/certificates/approval/admission.go","code":"// ValidateInitialization ensures an authorizer is set.\nfunc (p *Plugin) ValidateInitialization() error {\n\tif p.authz == nil {\n\t\treturn fmt.Errorf(\"%s requires an authorizer\", PluginName)\n\t}\n\treturn nil\n}","line":{"from":55,"to":61}} {"id":100013351,"name":"NewPlugin","signature":"func NewPlugin() *Plugin","file":"plugin/pkg/admission/certificates/approval/admission.go","code":"// NewPlugin creates a new CSR approval admission plugin\nfunc NewPlugin() *Plugin {\n\treturn \u0026Plugin{\n\t\tHandler: admission.NewHandler(admission.Update),\n\t}\n}","line":{"from":66,"to":71}} {"id":100013352,"name":"Validate","signature":"func (p *Plugin) Validate(ctx context.Context, a admission.Attributes, _ admission.ObjectInterfaces) error","file":"plugin/pkg/admission/certificates/approval/admission.go","code":"// Validate verifies that the requesting user has permission to approve\n// CertificateSigningRequests for the specified signerName.\nfunc (p *Plugin) Validate(ctx context.Context, a admission.Attributes, _ admission.ObjectInterfaces) error {\n\t// Ignore all calls to anything other than 'certificatesigningrequests/approval'.\n\t// Ignore all operations other than UPDATE.\n\tif a.GetSubresource() != \"approval\" ||\n\t\ta.GetResource().GroupResource() != csrGroupResource {\n\t\treturn nil\n\t}\n\n\t// We check permissions against the *old* version of the resource, in case\n\t// a user is attempting to update the SignerName when calling the approval\n\t// endpoint (which is an invalid/not allowed operation)\n\tcsr, ok := a.GetOldObject().(*api.CertificateSigningRequest)\n\tif !ok {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"expected type CertificateSigningRequest, got: %T\", a.GetOldObject()))\n\t}\n\n\tif !certificates.IsAuthorizedForSignerName(ctx, p.authz, a.GetUserInfo(), \"approve\", csr.Spec.SignerName) {\n\t\tklog.V(4).Infof(\"user not permitted to approve CertificateSigningRequest %q with signerName %q\", csr.Name, csr.Spec.SignerName)\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"user not permitted to approve requests with signerName %q\", csr.Spec.SignerName))\n\t}\n\n\treturn nil\n}","line":{"from":75,"to":99}} {"id":100013353,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/certificates/signing/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\treturn NewPlugin(), nil\n\t})\n}","line":{"from":38,"to":43}} {"id":100013354,"name":"SetAuthorizer","signature":"func (p *Plugin) SetAuthorizer(authz authorizer.Authorizer)","file":"plugin/pkg/admission/certificates/signing/admission.go","code":"// SetAuthorizer sets the authorizer.\nfunc (p *Plugin) SetAuthorizer(authz authorizer.Authorizer) {\n\tp.authz = authz\n}","line":{"from":51,"to":54}} {"id":100013355,"name":"ValidateInitialization","signature":"func (p *Plugin) ValidateInitialization() error","file":"plugin/pkg/admission/certificates/signing/admission.go","code":"// ValidateInitialization ensures an authorizer is set.\nfunc (p *Plugin) ValidateInitialization() error {\n\tif p.authz == nil {\n\t\treturn fmt.Errorf(\"%s requires an authorizer\", PluginName)\n\t}\n\treturn nil\n}","line":{"from":56,"to":62}} {"id":100013356,"name":"NewPlugin","signature":"func NewPlugin() *Plugin","file":"plugin/pkg/admission/certificates/signing/admission.go","code":"// NewPlugin creates a new CSR approval admission plugin\nfunc NewPlugin() *Plugin {\n\treturn \u0026Plugin{\n\t\tHandler: admission.NewHandler(admission.Update),\n\t}\n}","line":{"from":67,"to":72}} {"id":100013357,"name":"Validate","signature":"func (p *Plugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error","file":"plugin/pkg/admission/certificates/signing/admission.go","code":"// Validate verifies that the requesting user has permission to sign\n// CertificateSigningRequests for the specified signerName.\nfunc (p *Plugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {\n\t// Ignore all calls to anything other than 'certificatesigningrequests/status'.\n\t// Ignore all operations other than UPDATE.\n\tif a.GetSubresource() != \"status\" ||\n\t\ta.GetResource().GroupResource() != csrGroupResource {\n\t\treturn nil\n\t}\n\n\toldCSR, ok := a.GetOldObject().(*api.CertificateSigningRequest)\n\tif !ok {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"expected type CertificateSigningRequest, got: %T\", a.GetOldObject()))\n\t}\n\tcsr, ok := a.GetObject().(*api.CertificateSigningRequest)\n\tif !ok {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"expected type CertificateSigningRequest, got: %T\", a.GetObject()))\n\t}\n\n\t// only run if the status.certificate or status.conditions field has been changed\n\tif reflect.DeepEqual(oldCSR.Status.Certificate, csr.Status.Certificate) \u0026\u0026 apiequality.Semantic.DeepEqual(oldCSR.Status.Conditions, csr.Status.Conditions) {\n\t\treturn nil\n\t}\n\n\tif !certificates.IsAuthorizedForSignerName(ctx, p.authz, a.GetUserInfo(), \"sign\", oldCSR.Spec.SignerName) {\n\t\tklog.V(4).Infof(\"user not permitted to sign CertificateSigningRequest %q with signerName %q\", oldCSR.Name, oldCSR.Spec.SignerName)\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"user not permitted to sign requests with signerName %q\", oldCSR.Spec.SignerName))\n\t}\n\n\treturn nil\n}","line":{"from":76,"to":106}} {"id":100013358,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/certificates/subjectrestriction/admission.go","code":"// Register registers the plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\treturn NewPlugin(), nil\n\t})\n}","line":{"from":33,"to":38}} {"id":100013359,"name":"ValidateInitialization","signature":"func (p *Plugin) ValidateInitialization() error","file":"plugin/pkg/admission/certificates/subjectrestriction/admission.go","code":"// ValidateInitialization always returns nil.\nfunc (p *Plugin) ValidateInitialization() error {\n\treturn nil\n}","line":{"from":45,"to":48}} {"id":100013360,"name":"NewPlugin","signature":"func NewPlugin() *Plugin","file":"plugin/pkg/admission/certificates/subjectrestriction/admission.go","code":"// NewPlugin constructs a new instance of the CertificateSubjectRestrictions admission interface.\nfunc NewPlugin() *Plugin {\n\treturn \u0026Plugin{\n\t\tHandler: admission.NewHandler(admission.Create),\n\t}\n}","line":{"from":52,"to":57}} {"id":100013361,"name":"Validate","signature":"func (p *Plugin) Validate(_ context.Context, a admission.Attributes, _ admission.ObjectInterfaces) error","file":"plugin/pkg/admission/certificates/subjectrestriction/admission.go","code":"// Validate ensures that if the signerName on a CSR is set to\n// `kubernetes.io/kube-apiserver-client`, that its organization (group)\n// attribute is not set to `system:masters`.\nfunc (p *Plugin) Validate(_ context.Context, a admission.Attributes, _ admission.ObjectInterfaces) error {\n\tif a.GetResource().GroupResource() != csrGroupResource || a.GetSubresource() != \"\" {\n\t\treturn nil\n\t}\n\n\tcsr, ok := a.GetObject().(*certificatesapi.CertificateSigningRequest)\n\tif !ok {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"expected type CertificateSigningRequest, got: %T\", a.GetObject()))\n\t}\n\n\tif csr.Spec.SignerName != certificatesv1beta1.KubeAPIServerClientSignerName {\n\t\treturn nil\n\t}\n\n\tcsrParsed, err := certificatesapi.ParseCSR(csr.Spec.Request)\n\tif err != nil {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"failed to parse CSR: %v\", err))\n\t}\n\n\tfor _, group := range csrParsed.Subject.Organization {\n\t\tif group == \"system:masters\" {\n\t\t\tklog.V(4).Infof(\"CSR %s rejected by admission plugin %s for attempting to use signer %s with system:masters group\",\n\t\t\t\tcsr.Name, PluginName, certificatesv1beta1.KubeAPIServerClientSignerName)\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"use of %s signer with system:masters group is not allowed\",\n\t\t\t\tcertificatesv1beta1.KubeAPIServerClientSignerName))\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":61,"to":93}} {"id":100013362,"name":"IsAuthorizedForSignerName","signature":"func IsAuthorizedForSignerName(ctx context.Context, authz authorizer.Authorizer, info user.Info, verb, signerName string) bool","file":"plugin/pkg/admission/certificates/util.go","code":"// IsAuthorizedForSignerName returns true if 'info' is authorized to perform the given\n// 'verb' on the synthetic 'signers' resource with the given signerName.\n// If the user does not have permission to perform the 'verb' on the given signerName,\n// it will also perform an authorization check against {domain portion}/*, for example\n// `kubernetes.io/*`. This allows an entity to be granted permission to 'verb' on all\n// signerNames with a given 'domain portion'.\nfunc IsAuthorizedForSignerName(ctx context.Context, authz authorizer.Authorizer, info user.Info, verb, signerName string) bool {\n\t// First check if the user has explicit permission to 'verb' for the given signerName.\n\tattr := buildAttributes(info, verb, signerName)\n\tdecision, reason, err := authz.Authorize(ctx, attr)\n\tswitch {\n\tcase err != nil:\n\t\tklog.V(3).Infof(\"cannot authorize %q %q for policy: %v,%v\", verb, attr.GetName(), reason, err)\n\tcase decision == authorizer.DecisionAllow:\n\t\treturn true\n\t}\n\n\t// If not, check if the user has wildcard permissions to 'verb' for the domain portion of the signerName, e.g.\n\t// 'kubernetes.io/*'.\n\tattr = buildWildcardAttributes(info, verb, signerName)\n\tdecision, reason, err = authz.Authorize(ctx, attr)\n\tswitch {\n\tcase err != nil:\n\t\tklog.V(3).Infof(\"cannot authorize %q %q for policy: %v,%v\", verb, attr.GetName(), reason, err)\n\tcase decision == authorizer.DecisionAllow:\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":28,"to":57}} {"id":100013363,"name":"buildAttributes","signature":"func buildAttributes(info user.Info, verb, signerName string) authorizer.Attributes","file":"plugin/pkg/admission/certificates/util.go","code":"func buildAttributes(info user.Info, verb, signerName string) authorizer.Attributes {\n\treturn authorizer.AttributesRecord{\n\t\tUser: info,\n\t\tVerb: verb,\n\t\tName: signerName,\n\t\tAPIGroup: \"certificates.k8s.io\",\n\t\tAPIVersion: \"*\",\n\t\tResource: \"signers\",\n\t\tResourceRequest: true,\n\t}\n}","line":{"from":59,"to":69}} {"id":100013364,"name":"buildWildcardAttributes","signature":"func buildWildcardAttributes(info user.Info, verb, signerName string) authorizer.Attributes","file":"plugin/pkg/admission/certificates/util.go","code":"func buildWildcardAttributes(info user.Info, verb, signerName string) authorizer.Attributes {\n\tparts := strings.Split(signerName, \"/\")\n\tdomain := parts[0]\n\treturn buildAttributes(info, verb, domain+\"/*\")\n}","line":{"from":71,"to":75}} {"id":100013365,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/defaulttolerationseconds/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\treturn NewDefaultTolerationSeconds(), nil\n\t})\n}","line":{"from":58,"to":63}} {"id":100013366,"name":"NewDefaultTolerationSeconds","signature":"func NewDefaultTolerationSeconds() *Plugin","file":"plugin/pkg/admission/defaulttolerationseconds/admission.go","code":"// NewDefaultTolerationSeconds creates a new instance of the DefaultTolerationSeconds admission controller\nfunc NewDefaultTolerationSeconds() *Plugin {\n\treturn \u0026Plugin{\n\t\tHandler: admission.NewHandler(admission.Create, admission.Update),\n\t}\n}","line":{"from":77,"to":82}} {"id":100013367,"name":"Admit","signature":"func (p *Plugin) Admit(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) (err error)","file":"plugin/pkg/admission/defaulttolerationseconds/admission.go","code":"// Admit makes an admission decision based on the request attributes\nfunc (p *Plugin) Admit(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) (err error) {\n\tif attributes.GetResource().GroupResource() != api.Resource(\"pods\") {\n\t\treturn nil\n\t}\n\n\tif len(attributes.GetSubresource()) \u003e 0 {\n\t\t// only run the checks below on pods proper and not subresources\n\t\treturn nil\n\t}\n\n\tpod, ok := attributes.GetObject().(*api.Pod)\n\tif !ok {\n\t\treturn errors.NewBadRequest(fmt.Sprintf(\"expected *api.Pod but got %T\", attributes.GetObject()))\n\t}\n\n\ttolerations := pod.Spec.Tolerations\n\n\ttoleratesNodeNotReady := false\n\ttoleratesNodeUnreachable := false\n\tfor _, toleration := range tolerations {\n\t\tif (toleration.Key == v1.TaintNodeNotReady || len(toleration.Key) == 0) \u0026\u0026\n\t\t\t(toleration.Effect == api.TaintEffectNoExecute || len(toleration.Effect) == 0) {\n\t\t\ttoleratesNodeNotReady = true\n\t\t}\n\n\t\tif (toleration.Key == v1.TaintNodeUnreachable || len(toleration.Key) == 0) \u0026\u0026\n\t\t\t(toleration.Effect == api.TaintEffectNoExecute || len(toleration.Effect) == 0) {\n\t\t\ttoleratesNodeUnreachable = true\n\t\t}\n\t}\n\n\tif !toleratesNodeNotReady {\n\t\tpod.Spec.Tolerations = append(pod.Spec.Tolerations, notReadyToleration)\n\t}\n\n\tif !toleratesNodeUnreachable {\n\t\tpod.Spec.Tolerations = append(pod.Spec.Tolerations, unreachableToleration)\n\t}\n\n\treturn nil\n}","line":{"from":84,"to":125}} {"id":100013368,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/deny/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\treturn NewAlwaysDeny(), nil\n\t})\n}","line":{"from":32,"to":37}} {"id":100013369,"name":"Admit","signature":"func (alwaysDeny) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error)","file":"plugin/pkg/admission/deny/admission.go","code":"// Admit makes an admission decision based on the request attributes.\nfunc (alwaysDeny) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {\n\treturn admission.NewForbidden(a, errors.New(\"admission control is denying all modifications\"))\n}","line":{"from":45,"to":48}} {"id":100013370,"name":"Validate","signature":"func (alwaysDeny) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error)","file":"plugin/pkg/admission/deny/admission.go","code":"// Validate makes an admission decision based on the request attributes. It is NOT allowed to mutate.\nfunc (alwaysDeny) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {\n\treturn admission.NewForbidden(a, errors.New(\"admission control is denying all modifications\"))\n}","line":{"from":50,"to":53}} {"id":100013371,"name":"Handles","signature":"func (alwaysDeny) Handles(operation admission.Operation) bool","file":"plugin/pkg/admission/deny/admission.go","code":"// Handles returns true if this admission controller can handle the given operation\n// where operation can be one of CREATE, UPDATE, DELETE, or CONNECT\nfunc (alwaysDeny) Handles(operation admission.Operation) bool {\n\treturn true\n}","line":{"from":55,"to":59}} {"id":100013372,"name":"NewAlwaysDeny","signature":"func NewAlwaysDeny() admission.Interface","file":"plugin/pkg/admission/deny/admission.go","code":"// NewAlwaysDeny creates an always deny admission handler\nfunc NewAlwaysDeny() admission.Interface {\n\t// DEPRECATED: AlwaysDeny denys all admission request, it is no use.\n\tklog.Warningf(\"%s admission controller is deprecated. \"+\n\t\t\"Please remove this controller from your configuration files and scripts.\", PluginName)\n\treturn new(alwaysDeny)\n}","line":{"from":61,"to":67}} {"id":100013373,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/eventratelimit/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName,\n\t\tfunc(config io.Reader) (admission.Interface, error) {\n\t\t\t// load the configuration provided (if any)\n\t\t\tconfiguration, err := LoadConfiguration(config)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\t// validate the configuration (if any)\n\t\t\tif configuration != nil {\n\t\t\t\tif errs := validation.ValidateConfiguration(configuration); len(errs) != 0 {\n\t\t\t\t\treturn nil, errs.ToAggregate()\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn newEventRateLimit(configuration, clock.RealClock{})\n\t\t})\n}","line":{"from":36,"to":53}} {"id":100013374,"name":"newEventRateLimit","signature":"func newEventRateLimit(config *eventratelimitapi.Configuration, clock flowcontrol.Clock) (*Plugin, error)","file":"plugin/pkg/admission/eventratelimit/admission.go","code":"// newEventRateLimit configures an admission controller that can enforce event rate limits\nfunc newEventRateLimit(config *eventratelimitapi.Configuration, clock flowcontrol.Clock) (*Plugin, error) {\n\tlimitEnforcers := make([]*limitEnforcer, 0, len(config.Limits))\n\tfor _, limitConfig := range config.Limits {\n\t\tenforcer, err := newLimitEnforcer(limitConfig, clock)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlimitEnforcers = append(limitEnforcers, enforcer)\n\t}\n\n\teventRateLimitAdmission := \u0026Plugin{\n\t\tHandler: admission.NewHandler(admission.Create, admission.Update),\n\t\tlimitEnforcers: limitEnforcers,\n\t}\n\n\treturn eventRateLimitAdmission, nil\n}","line":{"from":66,"to":83}} {"id":100013375,"name":"Validate","signature":"func (a *Plugin) Validate(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) (err error)","file":"plugin/pkg/admission/eventratelimit/admission.go","code":"// Validate makes admission decisions while enforcing event rate limits\nfunc (a *Plugin) Validate(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) (err error) {\n\t// ignore all operations that do not correspond to an Event kind\n\tif attr.GetKind().GroupKind() != api.Kind(\"Event\") {\n\t\treturn nil\n\t}\n\n\t// ignore all requests that specify dry-run\n\t// because they don't correspond to any calls to etcd,\n\t// they should not be affected by the ratelimit\n\tif attr.IsDryRun() {\n\t\treturn nil\n\t}\n\n\tvar errors []error\n\t// give each limit enforcer a chance to reject the event\n\tfor _, enforcer := range a.limitEnforcers {\n\t\tif err := enforcer.accept(attr); err != nil {\n\t\t\terrors = append(errors, err)\n\t\t}\n\t}\n\n\tif aggregatedErr := utilerrors.NewAggregate(errors); aggregatedErr != nil {\n\t\treturn apierrors.NewTooManyRequestsError(aggregatedErr.Error())\n\t}\n\n\treturn nil\n}","line":{"from":85,"to":112}} {"id":100013376,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"plugin/pkg/admission/eventratelimit/apis/eventratelimit/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(internalapi.AddToScheme(scheme))\n\tutilruntime.Must(versionedapi.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(versionedapi.SchemeGroupVersion))\n}","line":{"from":28,"to":33}} {"id":100013377,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"plugin/pkg/admission/eventratelimit/apis/eventratelimit/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":37,"to":40}} {"id":100013378,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"plugin/pkg/admission/eventratelimit/apis/eventratelimit/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":42,"to":45}} {"id":100013379,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"plugin/pkg/admission/eventratelimit/apis/eventratelimit/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\t// TODO this will get cleaned up with the scheme types are fixed\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Configuration{},\n\t)\n\treturn nil\n}","line":{"from":47,"to":53}} {"id":100013380,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *kruntime.Scheme) error","file":"plugin/pkg/admission/eventratelimit/apis/eventratelimit/v1alpha1/defaults.go","code":"func addDefaultingFuncs(scheme *kruntime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":21,"to":23}} {"id":100013381,"name":"SetDefaults_Configuration","signature":"func SetDefaults_Configuration(obj *Configuration) {}","file":"plugin/pkg/admission/eventratelimit/apis/eventratelimit/v1alpha1/defaults.go","code":"func SetDefaults_Configuration(obj *Configuration) {}","line":{"from":25,"to":25}} {"id":100013382,"name":"init","signature":"func init()","file":"plugin/pkg/admission/eventratelimit/apis/eventratelimit/v1alpha1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addKnownTypes, addDefaultingFuncs)\n}","line":{"from":41,"to":46}} {"id":100013383,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"plugin/pkg/admission/eventratelimit/apis/eventratelimit/v1alpha1/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Configuration{},\n\t)\n\treturn nil\n}","line":{"from":48,"to":53}} {"id":100013384,"name":"ValidateConfiguration","signature":"func ValidateConfiguration(config *eventratelimitapi.Configuration) field.ErrorList","file":"plugin/pkg/admission/eventratelimit/apis/eventratelimit/validation/validation.go","code":"// ValidateConfiguration validates the configuration.\nfunc ValidateConfiguration(config *eventratelimitapi.Configuration) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tlimitsPath := field.NewPath(\"limits\")\n\tif len(config.Limits) == 0 {\n\t\tallErrs = append(allErrs, field.Invalid(limitsPath, config.Limits, \"must not be empty\"))\n\t}\n\tfor i, limit := range config.Limits {\n\t\tidxPath := limitsPath.Index(i)\n\t\tif !limitTypes[limit.Type] {\n\t\t\tallowedValues := make([]string, len(limitTypes))\n\t\t\ti := 0\n\t\t\tfor limitType := range limitTypes {\n\t\t\t\tallowedValues[i] = string(limitType)\n\t\t\t\ti++\n\t\t\t}\n\t\t\tallErrs = append(allErrs, field.NotSupported(idxPath.Child(\"type\"), limit.Type, allowedValues))\n\t\t}\n\t\tif limit.Burst \u003c= 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"burst\"), limit.Burst, \"must be positive\"))\n\t\t}\n\t\tif limit.QPS \u003c= 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"qps\"), limit.QPS, \"must be positive\"))\n\t\t}\n\t\tif limit.Type != eventratelimitapi.ServerLimitType {\n\t\t\tif limit.CacheSize \u003c 0 {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(idxPath.Child(\"cacheSize\"), limit.CacheSize, \"must not be negative\"))\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":32,"to":63}} {"id":100013385,"name":"get","signature":"func (c *singleCache) get(key interface{}) flowcontrol.RateLimiter","file":"plugin/pkg/admission/eventratelimit/cache.go","code":"func (c *singleCache) get(key interface{}) flowcontrol.RateLimiter {\n\treturn c.rateLimiter\n}","line":{"from":36,"to":38}} {"id":100013386,"name":"get","signature":"func (c *lruCache) get(key interface{}) flowcontrol.RateLimiter","file":"plugin/pkg/admission/eventratelimit/cache.go","code":"func (c *lruCache) get(key interface{}) flowcontrol.RateLimiter {\n\tvalue, found := c.cache.Get(key)\n\tif !found {\n\t\trateLimter := c.rateLimiterFactory()\n\t\tc.cache.Add(key, rateLimter)\n\t\treturn rateLimter\n\t}\n\treturn value.(flowcontrol.RateLimiter)\n}","line":{"from":48,"to":56}} {"id":100013387,"name":"init","signature":"func init()","file":"plugin/pkg/admission/eventratelimit/config.go","code":"func init() {\n\tinstall.Install(scheme)\n}","line":{"from":36,"to":38}} {"id":100013388,"name":"LoadConfiguration","signature":"func LoadConfiguration(config io.Reader) (*eventratelimitapi.Configuration, error)","file":"plugin/pkg/admission/eventratelimit/config.go","code":"// LoadConfiguration loads the provided configuration.\nfunc LoadConfiguration(config io.Reader) (*eventratelimitapi.Configuration, error) {\n\t// if no config is provided, return a default configuration\n\tif config == nil {\n\t\texternalConfig := \u0026eventratelimitv1alpha1.Configuration{}\n\t\tscheme.Default(externalConfig)\n\t\tinternalConfig := \u0026eventratelimitapi.Configuration{}\n\t\tif err := scheme.Convert(externalConfig, internalConfig, nil); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn internalConfig, nil\n\t}\n\t// we have a config so parse it.\n\tdata, err := ioutil.ReadAll(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdecoder := codecs.UniversalDecoder()\n\tdecodedObj, err := runtime.Decode(decoder, data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresourceQuotaConfiguration, ok := decodedObj.(*eventratelimitapi.Configuration)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unexpected type: %T\", decodedObj)\n\t}\n\treturn resourceQuotaConfiguration, nil\n}","line":{"from":40,"to":67}} {"id":100013389,"name":"newLimitEnforcer","signature":"func newLimitEnforcer(config eventratelimitapi.Limit, clock flowcontrol.Clock) (*limitEnforcer, error)","file":"plugin/pkg/admission/eventratelimit/limitenforcer.go","code":"func newLimitEnforcer(config eventratelimitapi.Limit, clock flowcontrol.Clock) (*limitEnforcer, error) {\n\trateLimiterFactory := func() flowcontrol.RateLimiter {\n\t\treturn flowcontrol.NewTokenBucketRateLimiterWithClock(float32(config.QPS), int(config.Burst), clock)\n\t}\n\n\tif config.Type == eventratelimitapi.ServerLimitType {\n\t\treturn \u0026limitEnforcer{\n\t\t\tlimitType: config.Type,\n\t\t\tcache: \u0026singleCache{\n\t\t\t\trateLimiter: rateLimiterFactory(),\n\t\t\t},\n\t\t\tkeyFunc: getServerKey,\n\t\t}, nil\n\t}\n\n\tcacheSize := int(config.CacheSize)\n\tif cacheSize == 0 {\n\t\tcacheSize = defaultCacheSize\n\t}\n\tunderlyingCache := lru.New(cacheSize)\n\tcache := \u0026lruCache{\n\t\trateLimiterFactory: rateLimiterFactory,\n\t\tcache: underlyingCache,\n\t}\n\n\tvar keyFunc func(admission.Attributes) string\n\tswitch t := config.Type; t {\n\tcase eventratelimitapi.NamespaceLimitType:\n\t\tkeyFunc = getNamespaceKey\n\tcase eventratelimitapi.UserLimitType:\n\t\tkeyFunc = getUserKey\n\tcase eventratelimitapi.SourceAndObjectLimitType:\n\t\tkeyFunc = getSourceAndObjectKey\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown event rate limit type: %v\", t)\n\t}\n\n\treturn \u0026limitEnforcer{\n\t\tlimitType: config.Type,\n\t\tcache: cache,\n\t\tkeyFunc: keyFunc,\n\t}, nil\n}","line":{"from":45,"to":87}} {"id":100013390,"name":"accept","signature":"func (enforcer *limitEnforcer) accept(attr admission.Attributes) error","file":"plugin/pkg/admission/eventratelimit/limitenforcer.go","code":"func (enforcer *limitEnforcer) accept(attr admission.Attributes) error {\n\tkey := enforcer.keyFunc(attr)\n\trateLimiter := enforcer.cache.get(key)\n\n\t// ensure we have available rate\n\tallow := rateLimiter.TryAccept()\n\n\tif !allow {\n\t\treturn fmt.Errorf(\"limit reached on type %v for key %v\", enforcer.limitType, key)\n\t}\n\n\treturn nil\n}","line":{"from":89,"to":101}} {"id":100013391,"name":"getServerKey","signature":"func getServerKey(attr admission.Attributes) string","file":"plugin/pkg/admission/eventratelimit/limitenforcer.go","code":"func getServerKey(attr admission.Attributes) string {\n\treturn \"\"\n}","line":{"from":103,"to":105}} {"id":100013392,"name":"getNamespaceKey","signature":"func getNamespaceKey(attr admission.Attributes) string","file":"plugin/pkg/admission/eventratelimit/limitenforcer.go","code":"// getNamespaceKey returns a cache key that is based on the namespace of the event request\nfunc getNamespaceKey(attr admission.Attributes) string {\n\treturn attr.GetNamespace()\n}","line":{"from":107,"to":110}} {"id":100013393,"name":"getUserKey","signature":"func getUserKey(attr admission.Attributes) string","file":"plugin/pkg/admission/eventratelimit/limitenforcer.go","code":"// getUserKey returns a cache key that is based on the user of the event request\nfunc getUserKey(attr admission.Attributes) string {\n\tuserInfo := attr.GetUserInfo()\n\tif userInfo == nil {\n\t\treturn \"\"\n\t}\n\treturn userInfo.GetName()\n}","line":{"from":112,"to":119}} {"id":100013394,"name":"getSourceAndObjectKey","signature":"func getSourceAndObjectKey(attr admission.Attributes) string","file":"plugin/pkg/admission/eventratelimit/limitenforcer.go","code":"// getSourceAndObjectKey returns a cache key that is based on the source+object of the event\nfunc getSourceAndObjectKey(attr admission.Attributes) string {\n\tobject := attr.GetObject()\n\tif object == nil {\n\t\treturn \"\"\n\t}\n\tevent, ok := object.(*api.Event)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn strings.Join([]string{\n\t\tevent.Source.Component,\n\t\tevent.Source.Host,\n\t\tevent.InvolvedObject.Kind,\n\t\tevent.InvolvedObject.Namespace,\n\t\tevent.InvolvedObject.Name,\n\t\tstring(event.InvolvedObject.UID),\n\t\tevent.InvolvedObject.APIVersion,\n\t}, \"\")\n}","line":{"from":121,"to":140}} {"id":100013395,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/extendedresourcetoleration/admission.go","code":"// Register is called by the apiserver to register the plugin factory.\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\treturn newExtendedResourceToleration(), nil\n\t})\n}","line":{"from":34,"to":39}} {"id":100013396,"name":"newExtendedResourceToleration","signature":"func newExtendedResourceToleration() *plugin","file":"plugin/pkg/admission/extendedresourcetoleration/admission.go","code":"// newExtendedResourceToleration creates a new instance of the ExtendedResourceToleration admission controller.\nfunc newExtendedResourceToleration() *plugin {\n\treturn \u0026plugin{\n\t\tHandler: admission.NewHandler(admission.Create, admission.Update),\n\t}\n}","line":{"from":41,"to":46}} {"id":100013397,"name":"Admit","signature":"func (p *plugin) Admit(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) error","file":"plugin/pkg/admission/extendedresourcetoleration/admission.go","code":"// Admit updates the toleration of a pod based on the resources requested by it.\n// If an extended resource of name \"example.com/device\" is requested, it adds\n// a toleration with key \"example.com/device\", operator \"Exists\" and effect \"NoSchedule\".\n// The rationale for this is described in:\n// https://github.com/kubernetes/kubernetes/issues/55080\nfunc (p *plugin) Admit(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) error {\n\t// Ignore all calls to subresources or resources other than pods.\n\tif len(attributes.GetSubresource()) != 0 || attributes.GetResource().GroupResource() != core.Resource(\"pods\") {\n\t\treturn nil\n\t}\n\n\tpod, ok := attributes.GetObject().(*core.Pod)\n\tif !ok {\n\t\treturn errors.NewBadRequest(fmt.Sprintf(\"expected *core.Pod but got %T\", attributes.GetObject()))\n\t}\n\n\tresources := sets.String{}\n\tfor _, container := range pod.Spec.Containers {\n\t\tfor resourceName := range container.Resources.Requests {\n\t\t\tif helper.IsExtendedResourceName(resourceName) {\n\t\t\t\tresources.Insert(string(resourceName))\n\t\t\t}\n\t\t}\n\t}\n\tfor _, container := range pod.Spec.InitContainers {\n\t\tfor resourceName := range container.Resources.Requests {\n\t\t\tif helper.IsExtendedResourceName(resourceName) {\n\t\t\t\tresources.Insert(string(resourceName))\n\t\t\t}\n\t\t}\n\t}\n\n\t// Doing .List() so that we get a stable sorted list.\n\t// This allows us to test adding tolerations for multiple extended resources.\n\tfor _, resource := range resources.List() {\n\t\thelper.AddOrUpdateTolerationInPod(pod, \u0026core.Toleration{\n\t\t\tKey: resource,\n\t\t\tOperator: core.TolerationOpExists,\n\t\t\tEffect: core.TaintEffectNoSchedule,\n\t\t})\n\t}\n\n\treturn nil\n}","line":{"from":55,"to":98}} {"id":100013398,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/gc/gc_admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\t// the pods/status endpoint is ignored by this plugin since old kubelets\n\t\t// corrupt them. the pod status strategy ensures status updates cannot mutate\n\t\t// ownerRef.\n\t\twhiteList := []whiteListItem{\n\t\t\t{\n\t\t\t\tgroupResource: schema.GroupResource{Resource: \"pods\"},\n\t\t\t\tsubresource: \"status\",\n\t\t\t},\n\t\t}\n\t\treturn \u0026gcPermissionsEnforcement{\n\t\t\tHandler: admission.NewHandler(admission.Create, admission.Update),\n\t\t\twhiteList: whiteList,\n\t\t}, nil\n\t})\n}","line":{"from":38,"to":55}} {"id":100013399,"name":"isWhiteListed","signature":"func (a *gcPermissionsEnforcement) isWhiteListed(groupResource schema.GroupResource, subresource string) bool","file":"plugin/pkg/admission/gc/gc_admission.go","code":"// isWhiteListed returns true if the specified item is in the whitelist.\nfunc (a *gcPermissionsEnforcement) isWhiteListed(groupResource schema.GroupResource, subresource string) bool {\n\tfor _, item := range a.whiteList {\n\t\tif item.groupResource == groupResource \u0026\u0026 item.subresource == subresource {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":79,"to":87}} {"id":100013400,"name":"Validate","signature":"func (a *gcPermissionsEnforcement) Validate(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) (err error)","file":"plugin/pkg/admission/gc/gc_admission.go","code":"func (a *gcPermissionsEnforcement) Validate(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) (err error) {\n\t// // if the request is in the whitelist, we skip mutation checks for this resource.\n\tif a.isWhiteListed(attributes.GetResource().GroupResource(), attributes.GetSubresource()) {\n\t\treturn nil\n\t}\n\n\t// if we aren't changing owner references, then the edit is always allowed\n\tif !isChangingOwnerReference(attributes.GetObject(), attributes.GetOldObject()) {\n\t\treturn nil\n\t}\n\n\t// if you are creating a thing, you should always be allowed to set an owner ref since you logically had the power\n\t// to never create it. We still need to check block owner deletion below, because the power to delete does not\n\t// imply the power to prevent deletion on other resources.\n\tif attributes.GetOperation() != admission.Create {\n\t\tdeleteAttributes := authorizer.AttributesRecord{\n\t\t\tUser: attributes.GetUserInfo(),\n\t\t\tVerb: \"delete\",\n\t\t\tNamespace: attributes.GetNamespace(),\n\t\t\tAPIGroup: attributes.GetResource().Group,\n\t\t\tAPIVersion: attributes.GetResource().Version,\n\t\t\tResource: attributes.GetResource().Resource,\n\t\t\tSubresource: attributes.GetSubresource(),\n\t\t\tName: attributes.GetName(),\n\t\t\tResourceRequest: true,\n\t\t\tPath: \"\",\n\t\t}\n\t\tdecision, reason, err := a.authorizer.Authorize(ctx, deleteAttributes)\n\t\tif decision != authorizer.DecisionAllow {\n\t\t\treturn admission.NewForbidden(attributes, fmt.Errorf(\"cannot set an ownerRef on a resource you can't delete: %v, %v\", reason, err))\n\t\t}\n\t}\n\n\t// Further check if the user is setting ownerReference.blockOwnerDeletion to\n\t// true. If so, only allows the change if the user has delete permission of\n\t// the _OWNER_\n\tnewBlockingRefs := newBlockingOwnerDeletionRefs(attributes.GetObject(), attributes.GetOldObject())\n\tif len(newBlockingRefs) == 0 {\n\t\treturn nil\n\t}\n\n\t// There can be a case where a restMapper tries to hit discovery endpoints and times out if the network is inaccessible.\n\t// This can prevent creating the pod to run the network to be able to do discovery and it appears as a timeout, not a rejection.\n\t// Because the timeout is wrapper on admission/request, we can run a single check to see if the user can finalize any\n\t// possible resource.\n\tif decision, _, _ := a.authorizer.Authorize(ctx, finalizeAnythingRecord(attributes.GetUserInfo())); decision == authorizer.DecisionAllow {\n\t\treturn nil\n\t}\n\n\tfor _, ref := range newBlockingRefs {\n\t\trecords, err := a.ownerRefToDeleteAttributeRecords(ref, attributes)\n\t\tif err != nil {\n\t\t\treturn admission.NewForbidden(attributes, fmt.Errorf(\"cannot set blockOwnerDeletion in this case because cannot find RESTMapping for APIVersion %s Kind %s: %v\", ref.APIVersion, ref.Kind, err))\n\t\t}\n\t\t// Multiple records are returned if ref.Kind could map to multiple\n\t\t// resources. User needs to have delete permission on all the\n\t\t// matched Resources.\n\t\tfor _, record := range records {\n\t\t\tdecision, reason, err := a.authorizer.Authorize(ctx, record)\n\t\t\tif decision != authorizer.DecisionAllow {\n\t\t\t\treturn admission.NewForbidden(attributes, fmt.Errorf(\"cannot set blockOwnerDeletion if an ownerReference refers to a resource you can't set finalizers on: %v, %v\", reason, err))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n\n}","line":{"from":89,"to":156}} {"id":100013401,"name":"isChangingOwnerReference","signature":"func isChangingOwnerReference(newObj, oldObj runtime.Object) bool","file":"plugin/pkg/admission/gc/gc_admission.go","code":"func isChangingOwnerReference(newObj, oldObj runtime.Object) bool {\n\tnewMeta, err := meta.Accessor(newObj)\n\tif err != nil {\n\t\t// if we don't have objectmeta, we don't have the object reference\n\t\treturn false\n\t}\n\n\tif oldObj == nil {\n\t\treturn len(newMeta.GetOwnerReferences()) \u003e 0\n\t}\n\toldMeta, err := meta.Accessor(oldObj)\n\tif err != nil {\n\t\t// if we don't have objectmeta, we don't have the object reference\n\t\treturn false\n\t}\n\n\t// compare the old and new. If they aren't the same, then we're trying to change an ownerRef\n\toldOwners := oldMeta.GetOwnerReferences()\n\tnewOwners := newMeta.GetOwnerReferences()\n\tif len(oldOwners) != len(newOwners) {\n\t\treturn true\n\t}\n\tfor i := range oldOwners {\n\t\tif !apiequality.Semantic.DeepEqual(oldOwners[i], newOwners[i]) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":158,"to":187}} {"id":100013402,"name":"finalizeAnythingRecord","signature":"func finalizeAnythingRecord(userInfo user.Info) authorizer.AttributesRecord","file":"plugin/pkg/admission/gc/gc_admission.go","code":"func finalizeAnythingRecord(userInfo user.Info) authorizer.AttributesRecord {\n\treturn authorizer.AttributesRecord{\n\t\tUser: userInfo,\n\t\tVerb: \"update\",\n\t\tAPIGroup: \"*\",\n\t\tAPIVersion: \"*\",\n\t\tResource: \"*\",\n\t\tSubresource: \"finalizers\",\n\t\tName: \"*\",\n\t\tResourceRequest: true,\n\t\tPath: \"\",\n\t}\n}","line":{"from":189,"to":201}} {"id":100013403,"name":"ownerRefToDeleteAttributeRecords","signature":"func (a *gcPermissionsEnforcement) ownerRefToDeleteAttributeRecords(ref metav1.OwnerReference, attributes admission.Attributes) ([]authorizer.AttributesRecord, error)","file":"plugin/pkg/admission/gc/gc_admission.go","code":"// Translates ref to a DeleteAttribute deleting the object referred by the ref.\n// OwnerReference only records the object kind, which might map to multiple\n// resources, so multiple DeleteAttribute might be returned.\nfunc (a *gcPermissionsEnforcement) ownerRefToDeleteAttributeRecords(ref metav1.OwnerReference, attributes admission.Attributes) ([]authorizer.AttributesRecord, error) {\n\tvar ret []authorizer.AttributesRecord\n\tgroupVersion, err := schema.ParseGroupVersion(ref.APIVersion)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\tmappings, err := a.restMapper.RESTMappings(schema.GroupKind{Group: groupVersion.Group, Kind: ref.Kind}, groupVersion.Version)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\tfor _, mapping := range mappings {\n\t\tar := authorizer.AttributesRecord{\n\t\t\tUser: attributes.GetUserInfo(),\n\t\t\tVerb: \"update\",\n\t\t\tAPIGroup: mapping.Resource.Group,\n\t\t\tAPIVersion: mapping.Resource.Version,\n\t\t\tResource: mapping.Resource.Resource,\n\t\t\tSubresource: \"finalizers\",\n\t\t\tName: ref.Name,\n\t\t\tResourceRequest: true,\n\t\t\tPath: \"\",\n\t\t}\n\t\tif mapping.Scope.Name() == meta.RESTScopeNameNamespace {\n\t\t\t// if the owner is namespaced, it must be in the same namespace as the dependent is.\n\t\t\tar.Namespace = attributes.GetNamespace()\n\t\t}\n\t\tret = append(ret, ar)\n\t}\n\treturn ret, nil\n}","line":{"from":203,"to":235}} {"id":100013404,"name":"blockingOwnerRefs","signature":"func blockingOwnerRefs(refs []metav1.OwnerReference) []metav1.OwnerReference","file":"plugin/pkg/admission/gc/gc_admission.go","code":"// only keeps the blocking refs\nfunc blockingOwnerRefs(refs []metav1.OwnerReference) []metav1.OwnerReference {\n\tvar ret []metav1.OwnerReference\n\tfor _, ref := range refs {\n\t\tif ref.BlockOwnerDeletion != nil \u0026\u0026 *ref.BlockOwnerDeletion == true {\n\t\t\tret = append(ret, ref)\n\t\t}\n\t}\n\treturn ret\n}","line":{"from":237,"to":246}} {"id":100013405,"name":"indexByUID","signature":"func indexByUID(refs []metav1.OwnerReference) map[types.UID]metav1.OwnerReference","file":"plugin/pkg/admission/gc/gc_admission.go","code":"func indexByUID(refs []metav1.OwnerReference) map[types.UID]metav1.OwnerReference {\n\tret := make(map[types.UID]metav1.OwnerReference)\n\tfor _, ref := range refs {\n\t\tret[ref.UID] = ref\n\t}\n\treturn ret\n}","line":{"from":248,"to":254}} {"id":100013406,"name":"newBlockingOwnerDeletionRefs","signature":"func newBlockingOwnerDeletionRefs(newObj, oldObj runtime.Object) []metav1.OwnerReference","file":"plugin/pkg/admission/gc/gc_admission.go","code":"// Returns new blocking ownerReferences, and references whose blockOwnerDeletion\n// field is changed from nil or false to true.\nfunc newBlockingOwnerDeletionRefs(newObj, oldObj runtime.Object) []metav1.OwnerReference {\n\tnewMeta, err := meta.Accessor(newObj)\n\tif err != nil {\n\t\t// if we don't have objectmeta, we don't have the object reference\n\t\treturn nil\n\t}\n\tnewRefs := newMeta.GetOwnerReferences()\n\tblockingNewRefs := blockingOwnerRefs(newRefs)\n\tif len(blockingNewRefs) == 0 {\n\t\treturn nil\n\t}\n\n\tif oldObj == nil {\n\t\treturn blockingNewRefs\n\t}\n\toldMeta, err := meta.Accessor(oldObj)\n\tif err != nil {\n\t\t// if we don't have objectmeta, treat it as if all the ownerReference are newly created\n\t\treturn blockingNewRefs\n\t}\n\n\tvar ret []metav1.OwnerReference\n\tindexedOldRefs := indexByUID(oldMeta.GetOwnerReferences())\n\tfor _, ref := range blockingNewRefs {\n\t\toldRef, ok := indexedOldRefs[ref.UID]\n\t\tif !ok {\n\t\t\t// if ref is newly added, and it's blocking, then returns it.\n\t\t\tret = append(ret, ref)\n\t\t\tcontinue\n\t\t}\n\t\twasNotBlocking := oldRef.BlockOwnerDeletion == nil || *oldRef.BlockOwnerDeletion == false\n\t\tif wasNotBlocking {\n\t\t\tret = append(ret, ref)\n\t\t}\n\t}\n\treturn ret\n}","line":{"from":256,"to":294}} {"id":100013407,"name":"SetAuthorizer","signature":"func (a *gcPermissionsEnforcement) SetAuthorizer(authorizer authorizer.Authorizer)","file":"plugin/pkg/admission/gc/gc_admission.go","code":"func (a *gcPermissionsEnforcement) SetAuthorizer(authorizer authorizer.Authorizer) {\n\ta.authorizer = authorizer\n}","line":{"from":296,"to":298}} {"id":100013408,"name":"SetRESTMapper","signature":"func (a *gcPermissionsEnforcement) SetRESTMapper(restMapper meta.RESTMapper)","file":"plugin/pkg/admission/gc/gc_admission.go","code":"func (a *gcPermissionsEnforcement) SetRESTMapper(restMapper meta.RESTMapper) {\n\ta.restMapper = restMapper\n}","line":{"from":300,"to":302}} {"id":100013409,"name":"ValidateInitialization","signature":"func (a *gcPermissionsEnforcement) ValidateInitialization() error","file":"plugin/pkg/admission/gc/gc_admission.go","code":"func (a *gcPermissionsEnforcement) ValidateInitialization() error {\n\tif a.authorizer == nil {\n\t\treturn fmt.Errorf(\"missing authorizer\")\n\t}\n\tif a.restMapper == nil {\n\t\treturn fmt.Errorf(\"missing restMapper\")\n\t}\n\treturn nil\n}","line":{"from":304,"to":312}} {"id":100013410,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/imagepolicy/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\tnewImagePolicyWebhook, err := NewImagePolicyWebhook(config)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn newImagePolicyWebhook, nil\n\t})\n}","line":{"from":70,"to":79}} {"id":100013411,"name":"statusTTL","signature":"func (a *Plugin) statusTTL(status v1alpha1.ImageReviewStatus) time.Duration","file":"plugin/pkg/admission/imagepolicy/admission.go","code":"func (a *Plugin) statusTTL(status v1alpha1.ImageReviewStatus) time.Duration {\n\tif status.Allowed {\n\t\treturn a.allowTTL\n\t}\n\treturn a.denyTTL\n}","line":{"from":93,"to":98}} {"id":100013412,"name":"filterAnnotations","signature":"func (a *Plugin) filterAnnotations(allAnnotations map[string]string) map[string]string","file":"plugin/pkg/admission/imagepolicy/admission.go","code":"// Filter out annotations that don't match *.image-policy.k8s.io/*\nfunc (a *Plugin) filterAnnotations(allAnnotations map[string]string) map[string]string {\n\tannotations := make(map[string]string)\n\tfor k, v := range allAnnotations {\n\t\tif strings.Contains(k, \".image-policy.k8s.io/\") {\n\t\t\tannotations[k] = v\n\t\t}\n\t}\n\treturn annotations\n}","line":{"from":100,"to":109}} {"id":100013413,"name":"webhookError","signature":"func (a *Plugin) webhookError(pod *api.Pod, attributes admission.Attributes, err error) error","file":"plugin/pkg/admission/imagepolicy/admission.go","code":"// Function to call on webhook failure; behavior determined by defaultAllow flag\nfunc (a *Plugin) webhookError(pod *api.Pod, attributes admission.Attributes, err error) error {\n\tif err != nil {\n\t\tklog.V(2).Infof(\"error contacting webhook backend: %s\", err)\n\t\tif a.defaultAllow {\n\t\t\tattributes.AddAnnotation(AuditKeyPrefix+ImagePolicyFailedOpenKeySuffix, \"true\")\n\t\t\t// TODO(wteiken): Remove the annotation code for the 1.13 release\n\t\t\tannotations := pod.GetAnnotations()\n\t\t\tif annotations == nil {\n\t\t\t\tannotations = make(map[string]string)\n\t\t\t}\n\t\t\tannotations[api.ImagePolicyFailedOpenKey] = \"true\"\n\t\t\tpod.ObjectMeta.SetAnnotations(annotations)\n\n\t\t\tklog.V(2).Infof(\"resource allowed in spite of webhook backend failure\")\n\t\t\treturn nil\n\t\t}\n\t\tklog.V(2).Infof(\"resource not allowed due to webhook backend failure \")\n\t\treturn admission.NewForbidden(attributes, err)\n\t}\n\treturn nil\n}","line":{"from":111,"to":132}} {"id":100013414,"name":"Validate","signature":"func (a *Plugin) Validate(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) (err error)","file":"plugin/pkg/admission/imagepolicy/admission.go","code":"// Validate makes an admission decision based on the request attributes\nfunc (a *Plugin) Validate(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) (err error) {\n\t// Ignore all calls to subresources other than ephemeralcontainers or calls to resources other than pods.\n\tsubresource := attributes.GetSubresource()\n\tif (subresource != \"\" \u0026\u0026 subresource != ephemeralcontainers) || attributes.GetResource().GroupResource() != api.Resource(\"pods\") {\n\t\treturn nil\n\t}\n\n\tpod, ok := attributes.GetObject().(*api.Pod)\n\tif !ok {\n\t\treturn apierrors.NewBadRequest(\"Resource was marked with kind Pod but was unable to be converted\")\n\t}\n\n\t// Build list of ImageReviewContainerSpec\n\tvar imageReviewContainerSpecs []v1alpha1.ImageReviewContainerSpec\n\tif subresource == \"\" {\n\t\tcontainers := make([]api.Container, 0, len(pod.Spec.Containers)+len(pod.Spec.InitContainers))\n\t\tcontainers = append(containers, pod.Spec.Containers...)\n\t\tcontainers = append(containers, pod.Spec.InitContainers...)\n\t\tfor _, c := range containers {\n\t\t\timageReviewContainerSpecs = append(imageReviewContainerSpecs, v1alpha1.ImageReviewContainerSpec{\n\t\t\t\tImage: c.Image,\n\t\t\t})\n\t\t}\n\t} else if subresource == ephemeralcontainers {\n\t\tfor _, c := range pod.Spec.EphemeralContainers {\n\t\t\timageReviewContainerSpecs = append(imageReviewContainerSpecs, v1alpha1.ImageReviewContainerSpec{\n\t\t\t\tImage: c.Image,\n\t\t\t})\n\t\t}\n\t}\n\timageReview := v1alpha1.ImageReview{\n\t\tSpec: v1alpha1.ImageReviewSpec{\n\t\t\tContainers: imageReviewContainerSpecs,\n\t\t\tAnnotations: a.filterAnnotations(pod.Annotations),\n\t\t\tNamespace: attributes.GetNamespace(),\n\t\t},\n\t}\n\tif err := a.admitPod(ctx, pod, attributes, \u0026imageReview); err != nil {\n\t\treturn admission.NewForbidden(attributes, err)\n\t}\n\treturn nil\n}","line":{"from":134,"to":176}} {"id":100013415,"name":"admitPod","signature":"func (a *Plugin) admitPod(ctx context.Context, pod *api.Pod, attributes admission.Attributes, review *v1alpha1.ImageReview) error","file":"plugin/pkg/admission/imagepolicy/admission.go","code":"func (a *Plugin) admitPod(ctx context.Context, pod *api.Pod, attributes admission.Attributes, review *v1alpha1.ImageReview) error {\n\tcacheKey, err := json.Marshal(review.Spec)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif entry, ok := a.responseCache.Get(string(cacheKey)); ok {\n\t\treview.Status = entry.(v1alpha1.ImageReviewStatus)\n\t} else {\n\t\tresult := a.webhook.WithExponentialBackoff(ctx, func() rest.Result {\n\t\t\treturn a.webhook.RestClient.Post().Body(review).Do(ctx)\n\t\t})\n\n\t\tif err := result.Error(); err != nil {\n\t\t\treturn a.webhookError(pod, attributes, err)\n\t\t}\n\t\tvar statusCode int\n\t\tif result.StatusCode(\u0026statusCode); statusCode \u003c 200 || statusCode \u003e= 300 {\n\t\t\treturn a.webhookError(pod, attributes, fmt.Errorf(\"Error contacting webhook: %d\", statusCode))\n\t\t}\n\n\t\tif err := result.Into(review); err != nil {\n\t\t\treturn a.webhookError(pod, attributes, err)\n\t\t}\n\n\t\ta.responseCache.Add(string(cacheKey), review.Status, a.statusTTL(review.Status))\n\t}\n\n\tfor k, v := range review.Status.AuditAnnotations {\n\t\tif err := attributes.AddAnnotation(AuditKeyPrefix+k, v); err != nil {\n\t\t\tklog.Warningf(\"failed to set admission audit annotation %s to %s: %v\", AuditKeyPrefix+k, v, err)\n\t\t}\n\t}\n\tif !review.Status.Allowed {\n\t\tif len(review.Status.Reason) \u003e 0 {\n\t\t\treturn fmt.Errorf(\"image policy webhook backend denied one or more images: %s\", review.Status.Reason)\n\t\t}\n\t\treturn errors.New(\"one or more images rejected by webhook backend\")\n\t}\n\treturn nil\n}","line":{"from":178,"to":217}} {"id":100013416,"name":"NewImagePolicyWebhook","signature":"func NewImagePolicyWebhook(configFile io.Reader) (*Plugin, error)","file":"plugin/pkg/admission/imagepolicy/admission.go","code":"// NewImagePolicyWebhook a new ImagePolicyWebhook plugin from the provided config file.\n// The config file is specified by --admission-control-config-file and has the\n// following format for a webhook:\n//\n//\t{\n//\t \"imagePolicy\": {\n//\t \"kubeConfigFile\": \"path/to/kubeconfig/for/backend\",\n//\t \"allowTTL\": 30, # time in s to cache approval\n//\t \"denyTTL\": 30, # time in s to cache denial\n//\t \"retryBackoff\": 500, # time in ms to wait between retries\n//\t \"defaultAllow\": true # determines behavior if the webhook backend fails\n//\t }\n//\t}\n//\n// The config file may be json or yaml.\n//\n// The kubeconfig property refers to another file in the kubeconfig format which\n// specifies how to connect to the webhook backend.\n//\n// The kubeconfig's cluster field is used to refer to the remote service, user refers to the returned authorizer.\n//\n//\t# clusters refers to the remote service.\n//\tclusters:\n//\t- name: name-of-remote-imagepolicy-service\n//\t cluster:\n//\t certificate-authority: /path/to/ca.pem # CA for verifying the remote service.\n//\t server: https://images.example.com/policy # URL of remote service to query. Must use 'https'.\n//\n//\t# users refers to the API server's webhook configuration.\n//\tusers:\n//\t- name: name-of-api-server\n//\t user:\n//\t client-certificate: /path/to/cert.pem # cert for the webhook plugin to use\n//\t client-key: /path/to/key.pem # key matching the cert\n//\n// For additional HTTP configuration, refer to the kubeconfig documentation\n// http://kubernetes.io/v1.1/docs/user-guide/kubeconfig-file.html.\nfunc NewImagePolicyWebhook(configFile io.Reader) (*Plugin, error) {\n\tif configFile == nil {\n\t\treturn nil, fmt.Errorf(\"no config specified\")\n\t}\n\n\t// TODO: move this to a versioned configuration file format\n\tvar config AdmissionConfig\n\td := yaml.NewYAMLOrJSONDecoder(configFile, 4096)\n\terr := d.Decode(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twhConfig := config.ImagePolicyWebhook\n\tif err := normalizeWebhookConfig(\u0026whConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\tclientConfig, err := webhook.LoadKubeconfig(whConfig.KubeConfigFile, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tretryBackoff := webhook.DefaultRetryBackoffWithInitialDelay(whConfig.RetryBackoff)\n\tgw, err := webhook.NewGenericWebhook(legacyscheme.Scheme, legacyscheme.Codecs, clientConfig, groupVersions, retryBackoff)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026Plugin{\n\t\tHandler: admission.NewHandler(admission.Create, admission.Update),\n\t\twebhook: gw,\n\t\tresponseCache: cache.NewLRUExpireCache(1024),\n\t\tallowTTL: whConfig.AllowTTL,\n\t\tdenyTTL: whConfig.DenyTTL,\n\t\tdefaultAllow: whConfig.DefaultAllow,\n\t}, nil\n}","line":{"from":219,"to":291}} {"id":100013417,"name":"normalizeWebhookConfig","signature":"func normalizeWebhookConfig(config *imagePolicyWebhookConfig) (err error)","file":"plugin/pkg/admission/imagepolicy/config.go","code":"func normalizeWebhookConfig(config *imagePolicyWebhookConfig) (err error) {\n\tconfig.RetryBackoff, err = normalizeConfigDuration(\"backoff\", time.Millisecond, config.RetryBackoff, minRetryBackoff, maxRetryBackoff, defaultRetryBackoff)\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfig.AllowTTL, err = normalizeConfigDuration(\"allow cache\", time.Second, config.AllowTTL, minAllowTTL, maxAllowTTL, defaultAllowTTL)\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfig.DenyTTL, err = normalizeConfigDuration(\"deny cache\", time.Second, config.DenyTTL, minDenyTTL, maxDenyTTL, defaultDenyTTL)\n\treturn err\n}","line":{"from":56,"to":67}} {"id":100013418,"name":"normalizeConfigDuration","signature":"func normalizeConfigDuration(name string, scale, value, min, max, defaultValue time.Duration) (time.Duration, error)","file":"plugin/pkg/admission/imagepolicy/config.go","code":"func normalizeConfigDuration(name string, scale, value, min, max, defaultValue time.Duration) (time.Duration, error) {\n\t// disable with -1 sentinel\n\tif value == disableTTL {\n\t\tklog.V(2).Infof(\"image policy webhook %s disabled\", name)\n\t\treturn time.Duration(0), nil\n\t}\n\n\t// use default with 0 sentinel\n\tif value == useDefault {\n\t\tklog.V(2).Infof(\"image policy webhook %s using default value\", name)\n\t\treturn defaultValue, nil\n\t}\n\n\t// convert to s; unmarshalling gives ns\n\tvalue *= scale\n\n\t// check value is within range\n\tif value \u003c min || value \u003e max {\n\t\treturn value, fmt.Errorf(\"valid value is between %v and %v, got %v\", min, max, value)\n\t}\n\treturn value, nil\n}","line":{"from":69,"to":90}} {"id":100013419,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/limitranger/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\treturn NewLimitRanger(\u0026DefaultLimitRangerActions{})\n\t})\n}","line":{"from":50,"to":55}} {"id":100013420,"name":"SetExternalKubeInformerFactory","signature":"func (l *LimitRanger) SetExternalKubeInformerFactory(f informers.SharedInformerFactory)","file":"plugin/pkg/admission/limitranger/admission.go","code":"// SetExternalKubeInformerFactory registers an informer factory into the LimitRanger\nfunc (l *LimitRanger) SetExternalKubeInformerFactory(f informers.SharedInformerFactory) {\n\tlimitRangeInformer := f.Core().V1().LimitRanges()\n\tl.SetReadyFunc(limitRangeInformer.Informer().HasSynced)\n\tl.lister = limitRangeInformer.Lister()\n}","line":{"from":83,"to":88}} {"id":100013421,"name":"SetExternalKubeClientSet","signature":"func (l *LimitRanger) SetExternalKubeClientSet(client kubernetes.Interface)","file":"plugin/pkg/admission/limitranger/admission.go","code":"// SetExternalKubeClientSet registers the client into LimitRanger\nfunc (l *LimitRanger) SetExternalKubeClientSet(client kubernetes.Interface) {\n\tl.client = client\n}","line":{"from":90,"to":93}} {"id":100013422,"name":"ValidateInitialization","signature":"func (l *LimitRanger) ValidateInitialization() error","file":"plugin/pkg/admission/limitranger/admission.go","code":"// ValidateInitialization verifies the LimitRanger object has been properly initialized\nfunc (l *LimitRanger) ValidateInitialization() error {\n\tif l.lister == nil {\n\t\treturn fmt.Errorf(\"missing limitRange lister\")\n\t}\n\tif l.client == nil {\n\t\treturn fmt.Errorf(\"missing client\")\n\t}\n\treturn nil\n}","line":{"from":95,"to":104}} {"id":100013423,"name":"Admit","signature":"func (l *LimitRanger) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error)","file":"plugin/pkg/admission/limitranger/admission.go","code":"// Admit admits resources into cluster that do not violate any defined LimitRange in the namespace\nfunc (l *LimitRanger) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {\n\treturn l.runLimitFunc(a, l.actions.MutateLimit)\n}","line":{"from":106,"to":109}} {"id":100013424,"name":"Validate","signature":"func (l *LimitRanger) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error)","file":"plugin/pkg/admission/limitranger/admission.go","code":"// Validate admits resources into cluster that do not violate any defined LimitRange in the namespace\nfunc (l *LimitRanger) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {\n\treturn l.runLimitFunc(a, l.actions.ValidateLimit)\n}","line":{"from":111,"to":114}} {"id":100013425,"name":"runLimitFunc","signature":"func (l *LimitRanger) runLimitFunc(a admission.Attributes, limitFn func(limitRange *corev1.LimitRange, kind string, obj runtime.Object) error) (err error)","file":"plugin/pkg/admission/limitranger/admission.go","code":"func (l *LimitRanger) runLimitFunc(a admission.Attributes, limitFn func(limitRange *corev1.LimitRange, kind string, obj runtime.Object) error) (err error) {\n\tif !l.actions.SupportsAttributes(a) {\n\t\treturn nil\n\t}\n\n\t// ignore all objects marked for deletion\n\toldObj := a.GetOldObject()\n\tif oldObj != nil {\n\t\toldAccessor, err := meta.Accessor(oldObj)\n\t\tif err != nil {\n\t\t\treturn admission.NewForbidden(a, err)\n\t\t}\n\t\tif oldAccessor.GetDeletionTimestamp() != nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\titems, err := l.GetLimitRanges(a)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// ensure it meets each prescribed min/max\n\tfor i := range items {\n\t\tlimitRange := items[i]\n\n\t\tif !l.actions.SupportsLimit(limitRange) {\n\t\t\tcontinue\n\t\t}\n\n\t\terr = limitFn(limitRange, a.GetResource().Resource, a.GetObject())\n\t\tif err != nil {\n\t\t\treturn admission.NewForbidden(a, err)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":116,"to":152}} {"id":100013426,"name":"GetLimitRanges","signature":"func (l *LimitRanger) GetLimitRanges(a admission.Attributes) ([]*corev1.LimitRange, error)","file":"plugin/pkg/admission/limitranger/admission.go","code":"// GetLimitRanges returns a LimitRange object with the items held in\n// the indexer if available, or do alive lookup of the value.\nfunc (l *LimitRanger) GetLimitRanges(a admission.Attributes) ([]*corev1.LimitRange, error) {\n\titems, err := l.lister.LimitRanges(a.GetNamespace()).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, admission.NewForbidden(a, fmt.Errorf(\"unable to %s %v at this time because there was an error enforcing limit ranges\", a.GetOperation(), a.GetResource()))\n\t}\n\n\t// if there are no items held in our indexer, check our live-lookup LRU, if that misses, do the live lookup to prime it.\n\tif len(items) == 0 {\n\t\tlruItemObj, ok := l.liveLookupCache.Get(a.GetNamespace())\n\t\tif !ok || lruItemObj.(liveLookupEntry).expiry.Before(time.Now()) {\n\t\t\t// Fixed: #22422\n\t\t\t// use singleflight to alleviate simultaneous calls to\n\t\t\tlruItemObj, err, _ = l.group.Do(a.GetNamespace(), func() (interface{}, error) {\n\t\t\t\tliveList, err := l.client.CoreV1().LimitRanges(a.GetNamespace()).List(context.TODO(), metav1.ListOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, admission.NewForbidden(a, err)\n\t\t\t\t}\n\t\t\t\tnewEntry := liveLookupEntry{expiry: time.Now().Add(l.liveTTL)}\n\t\t\t\tfor i := range liveList.Items {\n\t\t\t\t\tnewEntry.items = append(newEntry.items, \u0026liveList.Items[i])\n\t\t\t\t}\n\t\t\t\tl.liveLookupCache.Add(a.GetNamespace(), newEntry)\n\t\t\t\treturn newEntry, nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\tlruEntry := lruItemObj.(liveLookupEntry)\n\n\t\tfor i := range lruEntry.items {\n\t\t\titems = append(items, lruEntry.items[i])\n\t\t}\n\n\t}\n\n\treturn items, nil\n}","line":{"from":154,"to":193}} {"id":100013427,"name":"NewLimitRanger","signature":"func NewLimitRanger(actions LimitRangerActions) (*LimitRanger, error)","file":"plugin/pkg/admission/limitranger/admission.go","code":"// NewLimitRanger returns an object that enforces limits based on the supplied limit function\nfunc NewLimitRanger(actions LimitRangerActions) (*LimitRanger, error) {\n\tliveLookupCache := lru.New(10000)\n\n\tif actions == nil {\n\t\tactions = \u0026DefaultLimitRangerActions{}\n\t}\n\n\treturn \u0026LimitRanger{\n\t\tHandler: admission.NewHandler(admission.Create, admission.Update),\n\t\tactions: actions,\n\t\tliveLookupCache: liveLookupCache,\n\t\tliveTTL: time.Duration(30 * time.Second),\n\t}, nil\n}","line":{"from":195,"to":209}} {"id":100013428,"name":"defaultContainerResourceRequirements","signature":"func defaultContainerResourceRequirements(limitRange *corev1.LimitRange) api.ResourceRequirements","file":"plugin/pkg/admission/limitranger/admission.go","code":"// defaultContainerResourceRequirements returns the default requirements for a container\n// the requirement.Limits are taken from the LimitRange defaults (if specified)\n// the requirement.Requests are taken from the LimitRange default request (if specified)\nfunc defaultContainerResourceRequirements(limitRange *corev1.LimitRange) api.ResourceRequirements {\n\trequirements := api.ResourceRequirements{}\n\trequirements.Requests = api.ResourceList{}\n\trequirements.Limits = api.ResourceList{}\n\n\tfor i := range limitRange.Spec.Limits {\n\t\tlimit := limitRange.Spec.Limits[i]\n\t\tif limit.Type == corev1.LimitTypeContainer {\n\t\t\tfor k, v := range limit.DefaultRequest {\n\t\t\t\trequirements.Requests[api.ResourceName(k)] = v.DeepCopy()\n\t\t\t}\n\t\t\tfor k, v := range limit.Default {\n\t\t\t\trequirements.Limits[api.ResourceName(k)] = v.DeepCopy()\n\t\t\t}\n\t\t}\n\t}\n\treturn requirements\n}","line":{"from":211,"to":231}} {"id":100013429,"name":"mergeContainerResources","signature":"func mergeContainerResources(container *api.Container, defaultRequirements *api.ResourceRequirements, annotationPrefix string, annotations []string) []string","file":"plugin/pkg/admission/limitranger/admission.go","code":"// mergeContainerResources handles defaulting all of the resources on a container.\nfunc mergeContainerResources(container *api.Container, defaultRequirements *api.ResourceRequirements, annotationPrefix string, annotations []string) []string {\n\tsetRequests := []string{}\n\tsetLimits := []string{}\n\tif container.Resources.Limits == nil {\n\t\tcontainer.Resources.Limits = api.ResourceList{}\n\t}\n\tif container.Resources.Requests == nil {\n\t\tcontainer.Resources.Requests = api.ResourceList{}\n\t}\n\tfor k, v := range defaultRequirements.Limits {\n\t\t_, found := container.Resources.Limits[k]\n\t\tif !found {\n\t\t\tcontainer.Resources.Limits[k] = v.DeepCopy()\n\t\t\tsetLimits = append(setLimits, string(k))\n\t\t}\n\t}\n\tfor k, v := range defaultRequirements.Requests {\n\t\t_, found := container.Resources.Requests[k]\n\t\tif !found {\n\t\t\tcontainer.Resources.Requests[k] = v.DeepCopy()\n\t\t\tsetRequests = append(setRequests, string(k))\n\t\t}\n\t}\n\tif len(setRequests) \u003e 0 {\n\t\tsort.Strings(setRequests)\n\t\ta := strings.Join(setRequests, \", \") + fmt.Sprintf(\" request for %s %s\", annotationPrefix, container.Name)\n\t\tannotations = append(annotations, a)\n\t}\n\tif len(setLimits) \u003e 0 {\n\t\tsort.Strings(setLimits)\n\t\ta := strings.Join(setLimits, \", \") + fmt.Sprintf(\" limit for %s %s\", annotationPrefix, container.Name)\n\t\tannotations = append(annotations, a)\n\t}\n\treturn annotations\n}","line":{"from":233,"to":268}} {"id":100013430,"name":"mergePodResourceRequirements","signature":"func mergePodResourceRequirements(pod *api.Pod, defaultRequirements *api.ResourceRequirements)","file":"plugin/pkg/admission/limitranger/admission.go","code":"// mergePodResourceRequirements merges enumerated requirements with default requirements\n// it annotates the pod with information about what requirements were modified\nfunc mergePodResourceRequirements(pod *api.Pod, defaultRequirements *api.ResourceRequirements) {\n\tannotations := []string{}\n\n\tfor i := range pod.Spec.Containers {\n\t\tannotations = mergeContainerResources(\u0026pod.Spec.Containers[i], defaultRequirements, \"container\", annotations)\n\t}\n\n\tfor i := range pod.Spec.InitContainers {\n\t\tannotations = mergeContainerResources(\u0026pod.Spec.InitContainers[i], defaultRequirements, \"init container\", annotations)\n\t}\n\n\tif len(annotations) \u003e 0 {\n\t\tif pod.ObjectMeta.Annotations == nil {\n\t\t\tpod.ObjectMeta.Annotations = make(map[string]string)\n\t\t}\n\t\tval := \"LimitRanger plugin set: \" + strings.Join(annotations, \"; \")\n\t\tpod.ObjectMeta.Annotations[limitRangerAnnotation] = val\n\t}\n}","line":{"from":270,"to":290}} {"id":100013431,"name":"requestLimitEnforcedValues","signature":"func requestLimitEnforcedValues(requestQuantity, limitQuantity, enforcedQuantity resource.Quantity) (request, limit, enforced int64)","file":"plugin/pkg/admission/limitranger/admission.go","code":"// requestLimitEnforcedValues returns the specified values at a common precision to support comparability\nfunc requestLimitEnforcedValues(requestQuantity, limitQuantity, enforcedQuantity resource.Quantity) (request, limit, enforced int64) {\n\trequest = requestQuantity.Value()\n\tlimit = limitQuantity.Value()\n\tenforced = enforcedQuantity.Value()\n\t// do a more precise comparison if possible (if the value won't overflow)\n\tif request \u003c= resource.MaxMilliValue \u0026\u0026 limit \u003c= resource.MaxMilliValue \u0026\u0026 enforced \u003c= resource.MaxMilliValue {\n\t\trequest = requestQuantity.MilliValue()\n\t\tlimit = limitQuantity.MilliValue()\n\t\tenforced = enforcedQuantity.MilliValue()\n\t}\n\treturn\n}","line":{"from":292,"to":304}} {"id":100013432,"name":"minConstraint","signature":"func minConstraint(limitType string, resourceName string, enforced resource.Quantity, request api.ResourceList, limit api.ResourceList) error","file":"plugin/pkg/admission/limitranger/admission.go","code":"// minConstraint enforces the min constraint over the specified resource\nfunc minConstraint(limitType string, resourceName string, enforced resource.Quantity, request api.ResourceList, limit api.ResourceList) error {\n\treq, reqExists := request[api.ResourceName(resourceName)]\n\tlim, limExists := limit[api.ResourceName(resourceName)]\n\tobservedReqValue, observedLimValue, enforcedValue := requestLimitEnforcedValues(req, lim, enforced)\n\n\tif !reqExists {\n\t\treturn fmt.Errorf(\"minimum %s usage per %s is %s. No request is specified\", resourceName, limitType, enforced.String())\n\t}\n\tif observedReqValue \u003c enforcedValue {\n\t\treturn fmt.Errorf(\"minimum %s usage per %s is %s, but request is %s\", resourceName, limitType, enforced.String(), req.String())\n\t}\n\tif limExists \u0026\u0026 (observedLimValue \u003c enforcedValue) {\n\t\treturn fmt.Errorf(\"minimum %s usage per %s is %s, but limit is %s\", resourceName, limitType, enforced.String(), lim.String())\n\t}\n\treturn nil\n}","line":{"from":306,"to":322}} {"id":100013433,"name":"maxRequestConstraint","signature":"func maxRequestConstraint(limitType string, resourceName string, enforced resource.Quantity, request api.ResourceList) error","file":"plugin/pkg/admission/limitranger/admission.go","code":"// maxRequestConstraint enforces the max constraint over the specified resource\n// use when specify LimitType resource doesn't recognize limit values\nfunc maxRequestConstraint(limitType string, resourceName string, enforced resource.Quantity, request api.ResourceList) error {\n\treq, reqExists := request[api.ResourceName(resourceName)]\n\tobservedReqValue, _, enforcedValue := requestLimitEnforcedValues(req, resource.Quantity{}, enforced)\n\n\tif !reqExists {\n\t\treturn fmt.Errorf(\"maximum %s usage per %s is %s. No request is specified\", resourceName, limitType, enforced.String())\n\t}\n\tif observedReqValue \u003e enforcedValue {\n\t\treturn fmt.Errorf(\"maximum %s usage per %s is %s, but request is %s\", resourceName, limitType, enforced.String(), req.String())\n\t}\n\treturn nil\n}","line":{"from":324,"to":337}} {"id":100013434,"name":"maxConstraint","signature":"func maxConstraint(limitType string, resourceName string, enforced resource.Quantity, request api.ResourceList, limit api.ResourceList) error","file":"plugin/pkg/admission/limitranger/admission.go","code":"// maxConstraint enforces the max constraint over the specified resource\nfunc maxConstraint(limitType string, resourceName string, enforced resource.Quantity, request api.ResourceList, limit api.ResourceList) error {\n\treq, reqExists := request[api.ResourceName(resourceName)]\n\tlim, limExists := limit[api.ResourceName(resourceName)]\n\tobservedReqValue, observedLimValue, enforcedValue := requestLimitEnforcedValues(req, lim, enforced)\n\n\tif !limExists {\n\t\treturn fmt.Errorf(\"maximum %s usage per %s is %s. No limit is specified\", resourceName, limitType, enforced.String())\n\t}\n\tif observedLimValue \u003e enforcedValue {\n\t\treturn fmt.Errorf(\"maximum %s usage per %s is %s, but limit is %s\", resourceName, limitType, enforced.String(), lim.String())\n\t}\n\tif reqExists \u0026\u0026 (observedReqValue \u003e enforcedValue) {\n\t\treturn fmt.Errorf(\"maximum %s usage per %s is %s, but request is %s\", resourceName, limitType, enforced.String(), req.String())\n\t}\n\treturn nil\n}","line":{"from":339,"to":355}} {"id":100013435,"name":"limitRequestRatioConstraint","signature":"func limitRequestRatioConstraint(limitType string, resourceName string, enforced resource.Quantity, request api.ResourceList, limit api.ResourceList) error","file":"plugin/pkg/admission/limitranger/admission.go","code":"// limitRequestRatioConstraint enforces the limit to request ratio over the specified resource\nfunc limitRequestRatioConstraint(limitType string, resourceName string, enforced resource.Quantity, request api.ResourceList, limit api.ResourceList) error {\n\treq, reqExists := request[api.ResourceName(resourceName)]\n\tlim, limExists := limit[api.ResourceName(resourceName)]\n\tobservedReqValue, observedLimValue, _ := requestLimitEnforcedValues(req, lim, enforced)\n\n\tif !reqExists || (observedReqValue == int64(0)) {\n\t\treturn fmt.Errorf(\"%s max limit to request ratio per %s is %s, but no request is specified or request is 0\", resourceName, limitType, enforced.String())\n\t}\n\tif !limExists || (observedLimValue == int64(0)) {\n\t\treturn fmt.Errorf(\"%s max limit to request ratio per %s is %s, but no limit is specified or limit is 0\", resourceName, limitType, enforced.String())\n\t}\n\n\tobservedRatio := float64(observedLimValue) / float64(observedReqValue)\n\tdisplayObservedRatio := observedRatio\n\tmaxLimitRequestRatio := float64(enforced.Value())\n\tif enforced.Value() \u003c= resource.MaxMilliValue {\n\t\tobservedRatio = observedRatio * 1000\n\t\tmaxLimitRequestRatio = float64(enforced.MilliValue())\n\t}\n\n\tif observedRatio \u003e maxLimitRequestRatio {\n\t\treturn fmt.Errorf(\"%s max limit to request ratio per %s is %s, but provided ratio is %f\", resourceName, limitType, enforced.String(), displayObservedRatio)\n\t}\n\n\treturn nil\n}","line":{"from":357,"to":383}} {"id":100013436,"name":"sum","signature":"func sum(inputs []api.ResourceList) api.ResourceList","file":"plugin/pkg/admission/limitranger/admission.go","code":"// sum takes the total of each named resource across all inputs\n// if a key is not in each input, then the output resource list will omit the key\nfunc sum(inputs []api.ResourceList) api.ResourceList {\n\tresult := api.ResourceList{}\n\tkeys := []api.ResourceName{}\n\tfor i := range inputs {\n\t\tfor k := range inputs[i] {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t}\n\tfor _, key := range keys {\n\t\ttotal, isSet := int64(0), true\n\n\t\tfor i := range inputs {\n\t\t\tinput := inputs[i]\n\t\t\tv, exists := input[key]\n\t\t\tif exists {\n\t\t\t\tif key == api.ResourceCPU {\n\t\t\t\t\ttotal = total + v.MilliValue()\n\t\t\t\t} else {\n\t\t\t\t\ttotal = total + v.Value()\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tisSet = false\n\t\t\t}\n\t\t}\n\n\t\tif isSet {\n\t\t\tif key == api.ResourceCPU {\n\t\t\t\tresult[key] = *(resource.NewMilliQuantity(total, resource.DecimalSI))\n\t\t\t} else {\n\t\t\t\tresult[key] = *(resource.NewQuantity(total, resource.DecimalSI))\n\t\t\t}\n\n\t\t}\n\t}\n\treturn result\n}","line":{"from":385,"to":422}} {"id":100013437,"name":"MutateLimit","signature":"func (d *DefaultLimitRangerActions) MutateLimit(limitRange *corev1.LimitRange, resourceName string, obj runtime.Object) error","file":"plugin/pkg/admission/limitranger/admission.go","code":"// MutateLimit enforces resource requirements of incoming resources\n// against enumerated constraints on the LimitRange. It may modify\n// the incoming object to apply default resource requirements if not\n// specified, and enumerated on the LimitRange\nfunc (d *DefaultLimitRangerActions) MutateLimit(limitRange *corev1.LimitRange, resourceName string, obj runtime.Object) error {\n\tswitch resourceName {\n\tcase \"pods\":\n\t\treturn PodMutateLimitFunc(limitRange, obj.(*api.Pod))\n\t}\n\treturn nil\n}","line":{"from":430,"to":440}} {"id":100013438,"name":"ValidateLimit","signature":"func (d *DefaultLimitRangerActions) ValidateLimit(limitRange *corev1.LimitRange, resourceName string, obj runtime.Object) error","file":"plugin/pkg/admission/limitranger/admission.go","code":"// ValidateLimit verifies the resource requirements of incoming\n// resources against enumerated constraints on the LimitRange are\n// valid\nfunc (d *DefaultLimitRangerActions) ValidateLimit(limitRange *corev1.LimitRange, resourceName string, obj runtime.Object) error {\n\tswitch resourceName {\n\tcase \"pods\":\n\t\treturn PodValidateLimitFunc(limitRange, obj.(*api.Pod))\n\tcase \"persistentvolumeclaims\":\n\t\treturn PersistentVolumeClaimValidateLimitFunc(limitRange, obj.(*api.PersistentVolumeClaim))\n\t}\n\treturn nil\n}","line":{"from":442,"to":453}} {"id":100013439,"name":"SupportsAttributes","signature":"func (d *DefaultLimitRangerActions) SupportsAttributes(a admission.Attributes) bool","file":"plugin/pkg/admission/limitranger/admission.go","code":"// SupportsAttributes ignores all calls that do not deal with pod resources or storage requests (PVCs).\n// Also ignores any call that has a subresource defined.\nfunc (d *DefaultLimitRangerActions) SupportsAttributes(a admission.Attributes) bool {\n\tif a.GetSubresource() != \"\" {\n\t\treturn false\n\t}\n\n\t// Since containers and initContainers cannot currently be added, removed, or updated, it is unnecessary\n\t// to mutate and validate limitrange on pod updates. Trying to mutate containers or initContainers on a pod\n\t// update request will always fail pod validation because those fields are immutable once the object is created.\n\tif a.GetKind().GroupKind() == api.Kind(\"Pod\") \u0026\u0026 a.GetOperation() == admission.Update {\n\t\treturn false\n\t}\n\n\treturn a.GetKind().GroupKind() == api.Kind(\"Pod\") || a.GetKind().GroupKind() == api.Kind(\"PersistentVolumeClaim\")\n}","line":{"from":455,"to":470}} {"id":100013440,"name":"SupportsLimit","signature":"func (d *DefaultLimitRangerActions) SupportsLimit(limitRange *corev1.LimitRange) bool","file":"plugin/pkg/admission/limitranger/admission.go","code":"// SupportsLimit always returns true.\nfunc (d *DefaultLimitRangerActions) SupportsLimit(limitRange *corev1.LimitRange) bool {\n\treturn true\n}","line":{"from":472,"to":475}} {"id":100013441,"name":"PersistentVolumeClaimValidateLimitFunc","signature":"func PersistentVolumeClaimValidateLimitFunc(limitRange *corev1.LimitRange, pvc *api.PersistentVolumeClaim) error","file":"plugin/pkg/admission/limitranger/admission.go","code":"// PersistentVolumeClaimValidateLimitFunc enforces storage limits for PVCs.\n// Users request storage via pvc.Spec.Resources.Requests. Min/Max is enforced by an admin with LimitRange.\n// Claims will not be modified with default values because storage is a required part of pvc.Spec.\n// All storage enforced values *only* apply to pvc.Spec.Resources.Requests.\nfunc PersistentVolumeClaimValidateLimitFunc(limitRange *corev1.LimitRange, pvc *api.PersistentVolumeClaim) error {\n\tvar errs []error\n\tfor i := range limitRange.Spec.Limits {\n\t\tlimit := limitRange.Spec.Limits[i]\n\t\tlimitType := limit.Type\n\t\tif limitType == corev1.LimitTypePersistentVolumeClaim {\n\t\t\tfor k, v := range limit.Min {\n\t\t\t\t// normal usage of minConstraint. pvc.Spec.Resources.Limits is not recognized as user input\n\t\t\t\tif err := minConstraint(string(limitType), string(k), v, pvc.Spec.Resources.Requests, api.ResourceList{}); err != nil {\n\t\t\t\t\terrs = append(errs, err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor k, v := range limit.Max {\n\t\t\t\t// We want to enforce the max of the LimitRange against what\n\t\t\t\t// the user requested.\n\t\t\t\tif err := maxRequestConstraint(string(limitType), string(k), v, pvc.Spec.Resources.Requests); err != nil {\n\t\t\t\t\terrs = append(errs, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn utilerrors.NewAggregate(errs)\n}","line":{"from":477,"to":503}} {"id":100013442,"name":"PodMutateLimitFunc","signature":"func PodMutateLimitFunc(limitRange *corev1.LimitRange, pod *api.Pod) error","file":"plugin/pkg/admission/limitranger/admission.go","code":"// PodMutateLimitFunc sets resource requirements enumerated by the pod against\n// the specified LimitRange. The pod may be modified to apply default resource\n// requirements if not specified, and enumerated on the LimitRange\nfunc PodMutateLimitFunc(limitRange *corev1.LimitRange, pod *api.Pod) error {\n\tdefaultResources := defaultContainerResourceRequirements(limitRange)\n\tmergePodResourceRequirements(pod, \u0026defaultResources)\n\treturn nil\n}","line":{"from":505,"to":512}} {"id":100013443,"name":"PodValidateLimitFunc","signature":"func PodValidateLimitFunc(limitRange *corev1.LimitRange, pod *api.Pod) error","file":"plugin/pkg/admission/limitranger/admission.go","code":"// PodValidateLimitFunc enforces resource requirements enumerated by the pod against\n// the specified LimitRange.\nfunc PodValidateLimitFunc(limitRange *corev1.LimitRange, pod *api.Pod) error {\n\tvar errs []error\n\n\tfor i := range limitRange.Spec.Limits {\n\t\tlimit := limitRange.Spec.Limits[i]\n\t\tlimitType := limit.Type\n\t\t// enforce container limits\n\t\tif limitType == corev1.LimitTypeContainer {\n\t\t\tfor j := range pod.Spec.Containers {\n\t\t\t\tcontainer := \u0026pod.Spec.Containers[j]\n\t\t\t\tfor k, v := range limit.Min {\n\t\t\t\t\tif err := minConstraint(string(limitType), string(k), v, container.Resources.Requests, container.Resources.Limits); err != nil {\n\t\t\t\t\t\terrs = append(errs, err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor k, v := range limit.Max {\n\t\t\t\t\tif err := maxConstraint(string(limitType), string(k), v, container.Resources.Requests, container.Resources.Limits); err != nil {\n\t\t\t\t\t\terrs = append(errs, err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor k, v := range limit.MaxLimitRequestRatio {\n\t\t\t\t\tif err := limitRequestRatioConstraint(string(limitType), string(k), v, container.Resources.Requests, container.Resources.Limits); err != nil {\n\t\t\t\t\t\terrs = append(errs, err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor j := range pod.Spec.InitContainers {\n\t\t\t\tcontainer := \u0026pod.Spec.InitContainers[j]\n\t\t\t\tfor k, v := range limit.Min {\n\t\t\t\t\tif err := minConstraint(string(limitType), string(k), v, container.Resources.Requests, container.Resources.Limits); err != nil {\n\t\t\t\t\t\terrs = append(errs, err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor k, v := range limit.Max {\n\t\t\t\t\tif err := maxConstraint(string(limitType), string(k), v, container.Resources.Requests, container.Resources.Limits); err != nil {\n\t\t\t\t\t\terrs = append(errs, err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor k, v := range limit.MaxLimitRequestRatio {\n\t\t\t\t\tif err := limitRequestRatioConstraint(string(limitType), string(k), v, container.Resources.Requests, container.Resources.Limits); err != nil {\n\t\t\t\t\t\terrs = append(errs, err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// enforce pod limits on init containers\n\t\tif limitType == corev1.LimitTypePod {\n\t\t\t// TODO: look into re-using resourcehelper.PodRequests/resourcehelper.PodLimits instead of duplicating\n\t\t\t// that calculation\n\t\t\tcontainerRequests, containerLimits := []api.ResourceList{}, []api.ResourceList{}\n\t\t\tfor j := range pod.Spec.Containers {\n\t\t\t\tcontainer := \u0026pod.Spec.Containers[j]\n\t\t\t\tcontainerRequests = append(containerRequests, container.Resources.Requests)\n\t\t\t\tcontainerLimits = append(containerLimits, container.Resources.Limits)\n\t\t\t}\n\t\t\tpodRequests := sum(containerRequests)\n\t\t\tpodLimits := sum(containerLimits)\n\t\t\tfor j := range pod.Spec.InitContainers {\n\t\t\t\tcontainer := \u0026pod.Spec.InitContainers[j]\n\t\t\t\t// take max(sum_containers, any_init_container)\n\t\t\t\tfor k, v := range container.Resources.Requests {\n\t\t\t\t\tif v2, ok := podRequests[k]; ok {\n\t\t\t\t\t\tif v.Cmp(v2) \u003e 0 {\n\t\t\t\t\t\t\tpodRequests[k] = v\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpodRequests[k] = v\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor k, v := range container.Resources.Limits {\n\t\t\t\t\tif v2, ok := podLimits[k]; ok {\n\t\t\t\t\t\tif v.Cmp(v2) \u003e 0 {\n\t\t\t\t\t\t\tpodLimits[k] = v\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpodLimits[k] = v\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor k, v := range limit.Min {\n\t\t\t\tif err := minConstraint(string(limitType), string(k), v, podRequests, podLimits); err != nil {\n\t\t\t\t\terrs = append(errs, err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor k, v := range limit.Max {\n\t\t\t\tif err := maxConstraint(string(limitType), string(k), v, podRequests, podLimits); err != nil {\n\t\t\t\t\terrs = append(errs, err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor k, v := range limit.MaxLimitRequestRatio {\n\t\t\t\tif err := limitRequestRatioConstraint(string(limitType), string(k), v, podRequests, podLimits); err != nil {\n\t\t\t\t\terrs = append(errs, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn utilerrors.NewAggregate(errs)\n}","line":{"from":514,"to":614}} {"id":100013444,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/namespace/autoprovision/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\treturn NewProvision(), nil\n\t})\n}","line":{"from":38,"to":43}} {"id":100013445,"name":"Admit","signature":"func (p *Provision) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error","file":"plugin/pkg/admission/namespace/autoprovision/admission.go","code":"// Admit makes an admission decision based on the request attributes\nfunc (p *Provision) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {\n\t// Don't create a namespace if the request is for a dry-run.\n\tif a.IsDryRun() {\n\t\treturn nil\n\t}\n\n\t// if we're here, then we've already passed authentication, so we're allowed to do what we're trying to do\n\t// if we're here, then the API server has found a route, which means that if we have a non-empty namespace\n\t// its a namespaced resource.\n\tif len(a.GetNamespace()) == 0 || a.GetKind().GroupKind() == api.Kind(\"Namespace\") {\n\t\treturn nil\n\t}\n\t// we need to wait for our caches to warm\n\tif !p.WaitForReady() {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"not yet ready to handle request\"))\n\t}\n\n\t_, err := p.namespaceLister.Get(a.GetNamespace())\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\tif !errors.IsNotFound(err) {\n\t\treturn admission.NewForbidden(a, err)\n\t}\n\n\tnamespace := \u0026corev1.Namespace{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: a.GetNamespace(),\n\t\t\tNamespace: \"\",\n\t\t},\n\t\tStatus: corev1.NamespaceStatus{},\n\t}\n\n\t_, err = p.client.CoreV1().Namespaces().Create(context.TODO(), namespace, metav1.CreateOptions{})\n\tif err != nil \u0026\u0026 !errors.IsAlreadyExists(err) {\n\t\treturn admission.NewForbidden(a, err)\n\t}\n\n\treturn nil\n}","line":{"from":58,"to":99}} {"id":100013446,"name":"NewProvision","signature":"func NewProvision() *Provision","file":"plugin/pkg/admission/namespace/autoprovision/admission.go","code":"// NewProvision creates a new namespace provision admission control handler\nfunc NewProvision() *Provision {\n\treturn \u0026Provision{\n\t\tHandler: admission.NewHandler(admission.Create),\n\t}\n}","line":{"from":101,"to":106}} {"id":100013447,"name":"SetExternalKubeClientSet","signature":"func (p *Provision) SetExternalKubeClientSet(client kubernetes.Interface)","file":"plugin/pkg/admission/namespace/autoprovision/admission.go","code":"// SetExternalKubeClientSet implements the WantsExternalKubeClientSet interface.\nfunc (p *Provision) SetExternalKubeClientSet(client kubernetes.Interface) {\n\tp.client = client\n}","line":{"from":108,"to":111}} {"id":100013448,"name":"SetExternalKubeInformerFactory","signature":"func (p *Provision) SetExternalKubeInformerFactory(f informers.SharedInformerFactory)","file":"plugin/pkg/admission/namespace/autoprovision/admission.go","code":"// SetExternalKubeInformerFactory implements the WantsExternalKubeInformerFactory interface.\nfunc (p *Provision) SetExternalKubeInformerFactory(f informers.SharedInformerFactory) {\n\tnamespaceInformer := f.Core().V1().Namespaces()\n\tp.namespaceLister = namespaceInformer.Lister()\n\tp.SetReadyFunc(namespaceInformer.Informer().HasSynced)\n}","line":{"from":113,"to":118}} {"id":100013449,"name":"ValidateInitialization","signature":"func (p *Provision) ValidateInitialization() error","file":"plugin/pkg/admission/namespace/autoprovision/admission.go","code":"// ValidateInitialization implements the InitializationValidator interface.\nfunc (p *Provision) ValidateInitialization() error {\n\tif p.namespaceLister == nil {\n\t\treturn fmt.Errorf(\"missing namespaceLister\")\n\t}\n\tif p.client == nil {\n\t\treturn fmt.Errorf(\"missing client\")\n\t}\n\treturn nil\n}","line":{"from":120,"to":129}} {"id":100013450,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/namespace/exists/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\treturn NewExists(), nil\n\t})\n}","line":{"from":37,"to":42}} {"id":100013451,"name":"Validate","signature":"func (e *Exists) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error","file":"plugin/pkg/admission/namespace/exists/admission.go","code":"// Validate makes an admission decision based on the request attributes\nfunc (e *Exists) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {\n\t// if we're here, then we've already passed authentication, so we're allowed to do what we're trying to do\n\t// if we're here, then the API server has found a route, which means that if we have a non-empty namespace\n\t// its a namespaced resource.\n\tif len(a.GetNamespace()) == 0 || a.GetKind().GroupKind() == api.Kind(\"Namespace\") {\n\t\treturn nil\n\t}\n\n\t// we need to wait for our caches to warm\n\tif !e.WaitForReady() {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"not yet ready to handle request\"))\n\t}\n\t_, err := e.namespaceLister.Get(a.GetNamespace())\n\tif err == nil {\n\t\treturn nil\n\t}\n\tif !errors.IsNotFound(err) {\n\t\treturn errors.NewInternalError(err)\n\t}\n\n\t// in case of latency in our caches, make a call direct to storage to verify that it truly exists or not\n\t_, err = e.client.CoreV1().Namespaces().Get(context.TODO(), a.GetNamespace(), metav1.GetOptions{})\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\treturn err\n\t\t}\n\t\treturn errors.NewInternalError(err)\n\t}\n\n\treturn nil\n}","line":{"from":57,"to":88}} {"id":100013452,"name":"NewExists","signature":"func NewExists() *Exists","file":"plugin/pkg/admission/namespace/exists/admission.go","code":"// NewExists creates a new namespace exists admission control handler\nfunc NewExists() *Exists {\n\treturn \u0026Exists{\n\t\tHandler: admission.NewHandler(admission.Create, admission.Update, admission.Delete),\n\t}\n}","line":{"from":90,"to":95}} {"id":100013453,"name":"SetExternalKubeClientSet","signature":"func (e *Exists) SetExternalKubeClientSet(client kubernetes.Interface)","file":"plugin/pkg/admission/namespace/exists/admission.go","code":"// SetExternalKubeClientSet implements the WantsExternalKubeClientSet interface.\nfunc (e *Exists) SetExternalKubeClientSet(client kubernetes.Interface) {\n\te.client = client\n}","line":{"from":97,"to":100}} {"id":100013454,"name":"SetExternalKubeInformerFactory","signature":"func (e *Exists) SetExternalKubeInformerFactory(f informers.SharedInformerFactory)","file":"plugin/pkg/admission/namespace/exists/admission.go","code":"// SetExternalKubeInformerFactory implements the WantsExternalKubeInformerFactory interface.\nfunc (e *Exists) SetExternalKubeInformerFactory(f informers.SharedInformerFactory) {\n\tnamespaceInformer := f.Core().V1().Namespaces()\n\te.namespaceLister = namespaceInformer.Lister()\n\te.SetReadyFunc(namespaceInformer.Informer().HasSynced)\n}","line":{"from":102,"to":107}} {"id":100013455,"name":"ValidateInitialization","signature":"func (e *Exists) ValidateInitialization() error","file":"plugin/pkg/admission/namespace/exists/admission.go","code":"// ValidateInitialization implements the InitializationValidator interface.\nfunc (e *Exists) ValidateInitialization() error {\n\tif e.namespaceLister == nil {\n\t\treturn fmt.Errorf(\"missing namespaceLister\")\n\t}\n\tif e.client == nil {\n\t\treturn fmt.Errorf(\"missing client\")\n\t}\n\treturn nil\n}","line":{"from":109,"to":118}} {"id":100013456,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/network/defaultingressclass/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\tplugin := newPlugin()\n\t\treturn plugin, nil\n\t})\n}","line":{"from":42,"to":48}} {"id":100013457,"name":"newPlugin","signature":"func newPlugin() *classDefaulterPlugin","file":"plugin/pkg/admission/network/defaultingressclass/admission.go","code":"// newPlugin creates a new admission plugin.\nfunc newPlugin() *classDefaulterPlugin {\n\treturn \u0026classDefaulterPlugin{\n\t\tHandler: admission.NewHandler(admission.Create),\n\t}\n}","line":{"from":60,"to":65}} {"id":100013458,"name":"SetExternalKubeInformerFactory","signature":"func (a *classDefaulterPlugin) SetExternalKubeInformerFactory(f informers.SharedInformerFactory)","file":"plugin/pkg/admission/network/defaultingressclass/admission.go","code":"// SetExternalKubeInformerFactory sets a lister and readyFunc for this\n// classDefaulterPlugin using the provided SharedInformerFactory.\nfunc (a *classDefaulterPlugin) SetExternalKubeInformerFactory(f informers.SharedInformerFactory) {\n\tinformer := f.Networking().V1().IngressClasses()\n\ta.lister = informer.Lister()\n\ta.SetReadyFunc(informer.Informer().HasSynced)\n}","line":{"from":67,"to":73}} {"id":100013459,"name":"ValidateInitialization","signature":"func (a *classDefaulterPlugin) ValidateInitialization() error","file":"plugin/pkg/admission/network/defaultingressclass/admission.go","code":"// ValidateInitialization ensures lister is set.\nfunc (a *classDefaulterPlugin) ValidateInitialization() error {\n\tif a.lister == nil {\n\t\treturn fmt.Errorf(\"missing lister\")\n\t}\n\treturn nil\n}","line":{"from":75,"to":81}} {"id":100013460,"name":"Admit","signature":"func (a *classDefaulterPlugin) Admit(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) error","file":"plugin/pkg/admission/network/defaultingressclass/admission.go","code":"// Admit sets the default value of a Ingress's class if the user did not specify\n// a class.\nfunc (a *classDefaulterPlugin) Admit(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) error {\n\tif attr.GetResource().GroupResource() != networkingv1.Resource(\"ingresses\") {\n\t\treturn nil\n\t}\n\n\tif len(attr.GetSubresource()) != 0 {\n\t\treturn nil\n\t}\n\n\tingress, ok := attr.GetObject().(*networking.Ingress)\n\t// if we can't convert then we don't handle this object so just return\n\tif !ok {\n\t\tklog.V(3).Infof(\"Expected Ingress resource, got: %v\", attr.GetKind())\n\t\treturn errors.NewInternalError(fmt.Errorf(\"Expected Ingress resource, got: %v\", attr.GetKind()))\n\t}\n\n\t// IngressClassName field has been set, no need to set a default value.\n\tif ingress.Spec.IngressClassName != nil {\n\t\treturn nil\n\t}\n\n\t// Ingress class annotation has been set, no need to set a default value.\n\tif _, ok := ingress.Annotations[networkingv1beta1.AnnotationIngressClass]; ok {\n\t\treturn nil\n\t}\n\n\tklog.V(4).Infof(\"No class specified on Ingress %s\", ingress.Name)\n\n\tdefaultClass, err := getDefaultClass(a.lister)\n\tif err != nil {\n\t\treturn admission.NewForbidden(attr, err)\n\t}\n\n\t// No default class specified, no need to set a default value.\n\tif defaultClass == nil {\n\t\treturn nil\n\t}\n\n\tklog.V(4).Infof(\"Defaulting class for Ingress %s to %s\", ingress.Name, defaultClass.Name)\n\tingress.Spec.IngressClassName = \u0026defaultClass.Name\n\treturn nil\n}","line":{"from":83,"to":126}} {"id":100013461,"name":"getDefaultClass","signature":"func getDefaultClass(lister networkingv1listers.IngressClassLister) (*networkingv1.IngressClass, error)","file":"plugin/pkg/admission/network/defaultingressclass/admission.go","code":"// getDefaultClass returns the default IngressClass from the store, or nil.\nfunc getDefaultClass(lister networkingv1listers.IngressClassLister) (*networkingv1.IngressClass, error) {\n\tlist, err := lister.List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefaultClasses := []*networkingv1.IngressClass{}\n\tfor _, class := range list {\n\t\tif class.Annotations[networkingv1.AnnotationIsDefaultIngressClass] == \"true\" {\n\t\t\tdefaultClasses = append(defaultClasses, class)\n\t\t}\n\t}\n\n\tif len(defaultClasses) == 0 {\n\t\treturn nil, nil\n\t}\n\tsort.Slice(defaultClasses, func(i, j int) bool {\n\t\tif defaultClasses[i].CreationTimestamp.UnixNano() == defaultClasses[j].CreationTimestamp.UnixNano() {\n\t\t\treturn defaultClasses[i].Name \u003c defaultClasses[j].Name\n\t\t}\n\t\treturn defaultClasses[i].CreationTimestamp.UnixNano() \u003e defaultClasses[j].CreationTimestamp.UnixNano()\n\t})\n\tif len(defaultClasses) \u003e 1 {\n\t\tklog.V(4).Infof(\"%d default IngressClasses were found, choosing the newest: %s\", len(defaultClasses), defaultClasses[0].Name)\n\t}\n\n\treturn defaultClasses[0], nil\n}","line":{"from":128,"to":156}} {"id":100013462,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/network/denyserviceexternalips/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\tplugin := newPlugin()\n\t\treturn plugin, nil\n\t})\n}","line":{"from":35,"to":41}} {"id":100013463,"name":"newPlugin","signature":"func newPlugin() *externalIPsDenierPlugin","file":"plugin/pkg/admission/network/denyserviceexternalips/admission.go","code":"// newPlugin creates a new admission plugin.\nfunc newPlugin() *externalIPsDenierPlugin {\n\treturn \u0026externalIPsDenierPlugin{\n\t\tHandler: admission.NewHandler(admission.Create, admission.Update),\n\t}\n}","line":{"from":51,"to":56}} {"id":100013464,"name":"Validate","signature":"func (plug *externalIPsDenierPlugin) Validate(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) error","file":"plugin/pkg/admission/network/denyserviceexternalips/admission.go","code":"// Admit ensures that modifications of the Service.Spec.ExternalIPs field are\n// denied\nfunc (plug *externalIPsDenierPlugin) Validate(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) error {\n\tif attr.GetResource().GroupResource() != core.Resource(\"services\") {\n\t\treturn nil\n\t}\n\n\tif len(attr.GetSubresource()) != 0 {\n\t\treturn nil\n\t}\n\n\t// if we can't convert then we don't handle this object so just return\n\tnewSvc, ok := attr.GetObject().(*core.Service)\n\tif !ok {\n\t\tklog.V(3).Infof(\"Expected Service resource, got: %v\", attr.GetKind())\n\t\treturn errors.NewInternalError(fmt.Errorf(\"Expected Service resource, got: %v\", attr.GetKind()))\n\t}\n\n\tvar oldSvc *core.Service\n\tif old := attr.GetOldObject(); old != nil {\n\t\ttmp, ok := old.(*core.Service)\n\t\tif !ok {\n\t\t\tklog.V(3).Infof(\"Expected Service resource, got: %v\", attr.GetKind())\n\t\t\treturn errors.NewInternalError(fmt.Errorf(\"Expected Service resource, got: %v\", attr.GetKind()))\n\t\t}\n\t\toldSvc = tmp\n\t}\n\n\tif isSubset(newSvc, oldSvc) {\n\t\treturn nil\n\t}\n\n\tklog.V(4).Infof(\"Denying new use of ExternalIPs on Service %s/%s\", newSvc.Namespace, newSvc.Name)\n\treturn admission.NewForbidden(attr, fmt.Errorf(\"Use of external IPs is denied by admission control\"))\n}","line":{"from":58,"to":92}} {"id":100013465,"name":"isSubset","signature":"func isSubset(newSvc, oldSvc *core.Service) bool","file":"plugin/pkg/admission/network/denyserviceexternalips/admission.go","code":"func isSubset(newSvc, oldSvc *core.Service) bool {\n\t// If new has none, it's a subset.\n\tif len(newSvc.Spec.ExternalIPs) == 0 {\n\t\treturn true\n\t}\n\t// If we have some but it's not an update, it's not a subset.\n\tif oldSvc == nil {\n\t\treturn false\n\t}\n\toldIPs := map[string]bool{}\n\tfor _, ip := range oldSvc.Spec.ExternalIPs {\n\t\toldIPs[ip] = true\n\t}\n\t// Every IP in newSvc must be in oldSvc\n\tfor _, ip := range newSvc.Spec.ExternalIPs {\n\t\tif oldIPs[ip] == false {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":94,"to":114}} {"id":100013466,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/noderestriction/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\treturn NewPlugin(nodeidentifier.NewDefaultNodeIdentifier()), nil\n\t})\n}","line":{"from":51,"to":56}} {"id":100013467,"name":"NewPlugin","signature":"func NewPlugin(nodeIdentifier nodeidentifier.NodeIdentifier) *Plugin","file":"plugin/pkg/admission/noderestriction/admission.go","code":"// NewPlugin creates a new NodeRestriction admission plugin.\n// This plugin identifies requests from nodes\nfunc NewPlugin(nodeIdentifier nodeidentifier.NodeIdentifier) *Plugin {\n\treturn \u0026Plugin{\n\t\tHandler: admission.NewHandler(admission.Create, admission.Update, admission.Delete),\n\t\tnodeIdentifier: nodeIdentifier,\n\t}\n}","line":{"from":58,"to":65}} {"id":100013468,"name":"InspectFeatureGates","signature":"func (p *Plugin) InspectFeatureGates(featureGates featuregate.FeatureGate)","file":"plugin/pkg/admission/noderestriction/admission.go","code":"// InspectFeatureGates allows setting bools without taking a dep on a global variable\nfunc (p *Plugin) InspectFeatureGates(featureGates featuregate.FeatureGate) {\n\tp.expansionRecoveryEnabled = featureGates.Enabled(features.RecoverVolumeExpansionFailure)\n}","line":{"from":83,"to":86}} {"id":100013469,"name":"SetExternalKubeInformerFactory","signature":"func (p *Plugin) SetExternalKubeInformerFactory(f informers.SharedInformerFactory)","file":"plugin/pkg/admission/noderestriction/admission.go","code":"// SetExternalKubeInformerFactory registers an informer factory into Plugin\nfunc (p *Plugin) SetExternalKubeInformerFactory(f informers.SharedInformerFactory) {\n\tp.podsGetter = f.Core().V1().Pods().Lister()\n\tp.nodesGetter = f.Core().V1().Nodes().Lister()\n}","line":{"from":88,"to":92}} {"id":100013470,"name":"ValidateInitialization","signature":"func (p *Plugin) ValidateInitialization() error","file":"plugin/pkg/admission/noderestriction/admission.go","code":"// ValidateInitialization validates the Plugin was initialized properly\nfunc (p *Plugin) ValidateInitialization() error {\n\tif p.nodeIdentifier == nil {\n\t\treturn fmt.Errorf(\"%s requires a node identifier\", PluginName)\n\t}\n\tif p.podsGetter == nil {\n\t\treturn fmt.Errorf(\"%s requires a pod getter\", PluginName)\n\t}\n\tif p.nodesGetter == nil {\n\t\treturn fmt.Errorf(\"%s requires a node getter\", PluginName)\n\t}\n\treturn nil\n}","line":{"from":94,"to":106}} {"id":100013471,"name":"Admit","signature":"func (p *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error","file":"plugin/pkg/admission/noderestriction/admission.go","code":"// Admit checks the admission policy and triggers corresponding actions\nfunc (p *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {\n\tnodeName, isNode := p.nodeIdentifier.NodeIdentity(a.GetUserInfo())\n\n\t// Our job is just to restrict nodes\n\tif !isNode {\n\t\treturn nil\n\t}\n\n\tif len(nodeName) == 0 {\n\t\t// disallow requests we cannot match to a particular node\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"could not determine node from user %q\", a.GetUserInfo().GetName()))\n\t}\n\n\t// TODO: if node doesn't exist and this isn't a create node request, then reject.\n\n\tswitch a.GetResource().GroupResource() {\n\tcase podResource:\n\t\tswitch a.GetSubresource() {\n\t\tcase \"\":\n\t\t\treturn p.admitPod(nodeName, a)\n\t\tcase \"status\":\n\t\t\treturn p.admitPodStatus(nodeName, a)\n\t\tcase \"eviction\":\n\t\t\treturn p.admitPodEviction(nodeName, a)\n\t\tdefault:\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"unexpected pod subresource %q, only 'status' and 'eviction' are allowed\", a.GetSubresource()))\n\t\t}\n\n\tcase nodeResource:\n\t\treturn p.admitNode(nodeName, a)\n\n\tcase pvcResource:\n\t\tswitch a.GetSubresource() {\n\t\tcase \"status\":\n\t\t\treturn p.admitPVCStatus(nodeName, a)\n\t\tdefault:\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"may only update PVC status\"))\n\t\t}\n\n\tcase svcacctResource:\n\t\treturn p.admitServiceAccount(nodeName, a)\n\n\tcase leaseResource:\n\t\treturn p.admitLease(nodeName, a)\n\n\tcase csiNodeResource:\n\t\treturn p.admitCSINode(nodeName, a)\n\n\tdefault:\n\t\treturn nil\n\t}\n}","line":{"from":117,"to":169}} {"id":100013472,"name":"admitPod","signature":"func (p *Plugin) admitPod(nodeName string, a admission.Attributes) error","file":"plugin/pkg/admission/noderestriction/admission.go","code":"// admitPod allows creating or deleting a pod if it is assigned to the\n// current node and fulfills related criteria.\nfunc (p *Plugin) admitPod(nodeName string, a admission.Attributes) error {\n\tswitch a.GetOperation() {\n\tcase admission.Create:\n\t\treturn p.admitPodCreate(nodeName, a)\n\n\tcase admission.Delete:\n\t\t// get the existing pod\n\t\texistingPod, err := p.podsGetter.Pods(a.GetNamespace()).Get(a.GetName())\n\t\tif errors.IsNotFound(err) {\n\t\t\treturn err\n\t\t}\n\t\tif err != nil {\n\t\t\treturn admission.NewForbidden(a, err)\n\t\t}\n\t\t// only allow a node to delete a pod bound to itself\n\t\tif existingPod.Spec.NodeName != nodeName {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"node %q can only delete pods with spec.nodeName set to itself\", nodeName))\n\t\t}\n\t\treturn nil\n\n\tdefault:\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"unexpected operation %q, node %q can only create and delete mirror pods\", a.GetOperation(), nodeName))\n\t}\n}","line":{"from":171,"to":196}} {"id":100013473,"name":"admitPodCreate","signature":"func (p *Plugin) admitPodCreate(nodeName string, a admission.Attributes) error","file":"plugin/pkg/admission/noderestriction/admission.go","code":"func (p *Plugin) admitPodCreate(nodeName string, a admission.Attributes) error {\n\t// require a pod object\n\tpod, ok := a.GetObject().(*api.Pod)\n\tif !ok {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"unexpected type %T\", a.GetObject()))\n\t}\n\n\t// only allow nodes to create mirror pods\n\tif _, isMirrorPod := pod.Annotations[api.MirrorPodAnnotationKey]; !isMirrorPod {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"pod does not have %q annotation, node %q can only create mirror pods\", api.MirrorPodAnnotationKey, nodeName))\n\t}\n\n\t// only allow nodes to create a pod bound to itself\n\tif pod.Spec.NodeName != nodeName {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"node %q can only create pods with spec.nodeName set to itself\", nodeName))\n\t}\n\tif len(pod.OwnerReferences) \u003e 1 {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"node %q can only create pods with a single owner reference set to itself\", nodeName))\n\t}\n\tif len(pod.OwnerReferences) == 0 {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"node %q can only create pods with an owner reference set to itself\", nodeName))\n\t}\n\tif len(pod.OwnerReferences) == 1 {\n\t\towner := pod.OwnerReferences[0]\n\t\tif owner.APIVersion != v1.SchemeGroupVersion.String() ||\n\t\t\towner.Kind != \"Node\" ||\n\t\t\towner.Name != nodeName {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"node %q can only create pods with an owner reference set to itself\", nodeName))\n\t\t}\n\t\tif owner.Controller == nil || !*owner.Controller {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"node %q can only create pods with a controller owner reference set to itself\", nodeName))\n\t\t}\n\t\tif owner.BlockOwnerDeletion != nil \u0026\u0026 *owner.BlockOwnerDeletion {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"node %q must not set blockOwnerDeletion on an owner reference\", nodeName))\n\t\t}\n\n\t\t// Verify the node UID.\n\t\tnode, err := p.nodesGetter.Get(nodeName)\n\t\tif errors.IsNotFound(err) {\n\t\t\treturn err\n\t\t}\n\t\tif err != nil {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"error looking up node %s to verify uid: %v\", nodeName, err))\n\t\t}\n\t\tif owner.UID != node.UID {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"node %s UID mismatch: expected %s got %s\", nodeName, owner.UID, node.UID))\n\t\t}\n\t}\n\n\t// don't allow a node to create a pod that references any other API objects\n\tif pod.Spec.ServiceAccountName != \"\" {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"node %q can not create pods that reference a service account\", nodeName))\n\t}\n\thasSecrets := false\n\tpodutil.VisitPodSecretNames(pod, func(name string) (shouldContinue bool) { hasSecrets = true; return false }, podutil.AllContainers)\n\tif hasSecrets {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"node %q can not create pods that reference secrets\", nodeName))\n\t}\n\thasConfigMaps := false\n\tpodutil.VisitPodConfigmapNames(pod, func(name string) (shouldContinue bool) { hasConfigMaps = true; return false }, podutil.AllContainers)\n\tif hasConfigMaps {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"node %q can not create pods that reference configmaps\", nodeName))\n\t}\n\tfor _, v := range pod.Spec.Volumes {\n\t\tif v.PersistentVolumeClaim != nil {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"node %q can not create pods that reference persistentvolumeclaims\", nodeName))\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":198,"to":268}} {"id":100013474,"name":"admitPodStatus","signature":"func (p *Plugin) admitPodStatus(nodeName string, a admission.Attributes) error","file":"plugin/pkg/admission/noderestriction/admission.go","code":"// admitPodStatus allows to update the status of a pod if it is\n// assigned to the current node.\nfunc (p *Plugin) admitPodStatus(nodeName string, a admission.Attributes) error {\n\tswitch a.GetOperation() {\n\tcase admission.Update:\n\t\t// require an existing pod\n\t\toldPod, ok := a.GetOldObject().(*api.Pod)\n\t\tif !ok {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"unexpected type %T\", a.GetOldObject()))\n\t\t}\n\t\t// only allow a node to update status of a pod bound to itself\n\t\tif oldPod.Spec.NodeName != nodeName {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"node %q can only update pod status for pods with spec.nodeName set to itself\", nodeName))\n\t\t}\n\t\tnewPod, ok := a.GetObject().(*api.Pod)\n\t\tif !ok {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"unexpected type %T\", a.GetObject()))\n\t\t}\n\t\tif !labels.Equals(oldPod.Labels, newPod.Labels) {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"node %q cannot update labels through pod status\", nodeName))\n\t\t}\n\t\treturn nil\n\n\tdefault:\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"unexpected operation %q\", a.GetOperation()))\n\t}\n}","line":{"from":270,"to":296}} {"id":100013475,"name":"admitPodEviction","signature":"func (p *Plugin) admitPodEviction(nodeName string, a admission.Attributes) error","file":"plugin/pkg/admission/noderestriction/admission.go","code":"// admitPodEviction allows to evict a pod if it is assigned to the current node.\nfunc (p *Plugin) admitPodEviction(nodeName string, a admission.Attributes) error {\n\tswitch a.GetOperation() {\n\tcase admission.Create:\n\t\t// require eviction to an existing pod object\n\t\teviction, ok := a.GetObject().(*policy.Eviction)\n\t\tif !ok {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"unexpected type %T\", a.GetObject()))\n\t\t}\n\t\t// use pod name from the admission attributes, if set, rather than from the submitted Eviction object\n\t\tpodName := a.GetName()\n\t\tif len(podName) == 0 {\n\t\t\tif len(eviction.Name) == 0 {\n\t\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"could not determine pod from request data\"))\n\t\t\t}\n\t\t\tpodName = eviction.Name\n\t\t}\n\t\t// get the existing pod\n\t\texistingPod, err := p.podsGetter.Pods(a.GetNamespace()).Get(podName)\n\t\tif errors.IsNotFound(err) {\n\t\t\treturn err\n\t\t}\n\t\tif err != nil {\n\t\t\treturn admission.NewForbidden(a, err)\n\t\t}\n\t\t// only allow a node to evict a pod bound to itself\n\t\tif existingPod.Spec.NodeName != nodeName {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"node %s can only evict pods with spec.nodeName set to itself\", nodeName))\n\t\t}\n\t\treturn nil\n\n\tdefault:\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"unexpected operation %s\", a.GetOperation()))\n\t}\n}","line":{"from":298,"to":332}} {"id":100013476,"name":"admitPVCStatus","signature":"func (p *Plugin) admitPVCStatus(nodeName string, a admission.Attributes) error","file":"plugin/pkg/admission/noderestriction/admission.go","code":"func (p *Plugin) admitPVCStatus(nodeName string, a admission.Attributes) error {\n\tswitch a.GetOperation() {\n\tcase admission.Update:\n\t\toldPVC, ok := a.GetOldObject().(*api.PersistentVolumeClaim)\n\t\tif !ok {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"unexpected type %T\", a.GetOldObject()))\n\t\t}\n\n\t\tnewPVC, ok := a.GetObject().(*api.PersistentVolumeClaim)\n\t\tif !ok {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"unexpected type %T\", a.GetObject()))\n\t\t}\n\n\t\t// make copies for comparison\n\t\toldPVC = oldPVC.DeepCopy()\n\t\tnewPVC = newPVC.DeepCopy()\n\n\t\t// zero out resourceVersion to avoid comparing differences,\n\t\t// since the new object could leave it empty to indicate an unconditional update\n\t\toldPVC.ObjectMeta.ResourceVersion = \"\"\n\t\tnewPVC.ObjectMeta.ResourceVersion = \"\"\n\n\t\toldPVC.Status.Capacity = nil\n\t\tnewPVC.Status.Capacity = nil\n\n\t\toldPVC.Status.Conditions = nil\n\t\tnewPVC.Status.Conditions = nil\n\n\t\tif p.expansionRecoveryEnabled {\n\t\t\toldPVC.Status.ResizeStatus = nil\n\t\t\tnewPVC.Status.ResizeStatus = nil\n\n\t\t\toldPVC.Status.AllocatedResources = nil\n\t\t\tnewPVC.Status.AllocatedResources = nil\n\t\t}\n\n\t\t// TODO(apelisse): We don't have a good mechanism to\n\t\t// verify that only the things that should have changed\n\t\t// have changed. Ignore it for now.\n\t\toldPVC.ObjectMeta.ManagedFields = nil\n\t\tnewPVC.ObjectMeta.ManagedFields = nil\n\n\t\t// ensure no metadata changed. nodes should not be able to relabel, add finalizers/owners, etc\n\t\tif !apiequality.Semantic.DeepEqual(oldPVC, newPVC) {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"node %q is not allowed to update fields other than status.capacity and status.conditions: %v\", nodeName, diff.ObjectReflectDiff(oldPVC, newPVC)))\n\t\t}\n\n\t\treturn nil\n\n\tdefault:\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"unexpected operation %q\", a.GetOperation()))\n\t}\n}","line":{"from":334,"to":386}} {"id":100013477,"name":"admitNode","signature":"func (p *Plugin) admitNode(nodeName string, a admission.Attributes) error","file":"plugin/pkg/admission/noderestriction/admission.go","code":"func (p *Plugin) admitNode(nodeName string, a admission.Attributes) error {\n\trequestedName := a.GetName()\n\n\tif requestedName != nodeName {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"node %q is not allowed to modify node %q\", nodeName, requestedName))\n\t}\n\n\tif a.GetOperation() == admission.Create {\n\t\tnode, ok := a.GetObject().(*api.Node)\n\t\tif !ok {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"unexpected type %T\", a.GetObject()))\n\t\t}\n\n\t\t// Don't allow a node to create its Node API object with the config source set.\n\t\t// We scope node access to things listed in the Node.Spec, so allowing this would allow a view escalation.\n\t\tif node.Spec.ConfigSource != nil {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"node %q is not allowed to create pods with a non-nil configSource\", nodeName))\n\t\t}\n\n\t\t// Don't allow a node to register with labels outside the allowed set.\n\t\t// This would allow a node to add or modify its labels in a way that would let it steer privileged workloads to itself.\n\t\tmodifiedLabels := getModifiedLabels(node.Labels, nil)\n\t\tif forbiddenLabels := p.getForbiddenLabels(modifiedLabels); len(forbiddenLabels) \u003e 0 {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"node %q is not allowed to set the following labels: %s\", nodeName, strings.Join(forbiddenLabels.List(), \", \")))\n\t\t}\n\t}\n\n\tif a.GetOperation() == admission.Update {\n\t\tnode, ok := a.GetObject().(*api.Node)\n\t\tif !ok {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"unexpected type %T\", a.GetObject()))\n\t\t}\n\t\toldNode, ok := a.GetOldObject().(*api.Node)\n\t\tif !ok {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"unexpected type %T\", a.GetObject()))\n\t\t}\n\n\t\t// Don't allow a node to update the config source on its Node API object.\n\t\t// We scope node access to things listed in the Node.Spec, so allowing this would allow a view escalation.\n\t\t// We only do the check if the new node's configSource is non-nil; old kubelets might drop the field during a status update.\n\t\tif node.Spec.ConfigSource != nil \u0026\u0026 !apiequality.Semantic.DeepEqual(node.Spec.ConfigSource, oldNode.Spec.ConfigSource) {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"node %q is not allowed to update configSource to a new non-nil configSource\", nodeName))\n\t\t}\n\n\t\t// Don't allow a node to update its own taints. This would allow a node to remove or modify its\n\t\t// taints in a way that would let it steer disallowed workloads to itself.\n\t\tif !apiequality.Semantic.DeepEqual(node.Spec.Taints, oldNode.Spec.Taints) {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"node %q is not allowed to modify taints\", nodeName))\n\t\t}\n\n\t\t// Don't allow a node to update labels outside the allowed set.\n\t\t// This would allow a node to add or modify its labels in a way that would let it steer privileged workloads to itself.\n\t\tmodifiedLabels := getModifiedLabels(node.Labels, oldNode.Labels)\n\t\tif forbiddenUpdateLabels := p.getForbiddenLabels(modifiedLabels); len(forbiddenUpdateLabels) \u003e 0 {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"is not allowed to modify labels: %s\", strings.Join(forbiddenUpdateLabels.List(), \", \")))\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":388,"to":447}} {"id":100013478,"name":"getModifiedLabels","signature":"func getModifiedLabels(a, b map[string]string) sets.String","file":"plugin/pkg/admission/noderestriction/admission.go","code":"// getModifiedLabels returns the set of label keys that are different between the two maps\nfunc getModifiedLabels(a, b map[string]string) sets.String {\n\tmodified := sets.NewString()\n\tfor k, v1 := range a {\n\t\tif v2, ok := b[k]; !ok || v1 != v2 {\n\t\t\tmodified.Insert(k)\n\t\t}\n\t}\n\tfor k, v1 := range b {\n\t\tif v2, ok := a[k]; !ok || v1 != v2 {\n\t\t\tmodified.Insert(k)\n\t\t}\n\t}\n\treturn modified\n}","line":{"from":449,"to":463}} {"id":100013479,"name":"isKubernetesLabel","signature":"func isKubernetesLabel(key string) bool","file":"plugin/pkg/admission/noderestriction/admission.go","code":"func isKubernetesLabel(key string) bool {\n\tnamespace := getLabelNamespace(key)\n\tif namespace == \"kubernetes.io\" || strings.HasSuffix(namespace, \".kubernetes.io\") {\n\t\treturn true\n\t}\n\tif namespace == \"k8s.io\" || strings.HasSuffix(namespace, \".k8s.io\") {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":465,"to":474}} {"id":100013480,"name":"getLabelNamespace","signature":"func getLabelNamespace(key string) string","file":"plugin/pkg/admission/noderestriction/admission.go","code":"func getLabelNamespace(key string) string {\n\tif parts := strings.SplitN(key, \"/\", 2); len(parts) == 2 {\n\t\treturn parts[0]\n\t}\n\treturn \"\"\n}","line":{"from":476,"to":481}} {"id":100013481,"name":"getForbiddenLabels","signature":"func (p *Plugin) getForbiddenLabels(modifiedLabels sets.String) sets.String","file":"plugin/pkg/admission/noderestriction/admission.go","code":"// getForbiddenLabels returns the set of labels that may not be added, removed, or modified by the node on create or update.\nfunc (p *Plugin) getForbiddenLabels(modifiedLabels sets.String) sets.String {\n\tif len(modifiedLabels) == 0 {\n\t\treturn nil\n\t}\n\n\tforbiddenLabels := sets.NewString()\n\tfor label := range modifiedLabels {\n\t\tnamespace := getLabelNamespace(label)\n\t\t// forbid kubelets from setting node-restriction labels\n\t\tif namespace == v1.LabelNamespaceNodeRestriction || strings.HasSuffix(namespace, \".\"+v1.LabelNamespaceNodeRestriction) {\n\t\t\tforbiddenLabels.Insert(label)\n\t\t}\n\t\t// forbid kubelets from setting unknown kubernetes.io and k8s.io labels on update\n\t\tif isKubernetesLabel(label) \u0026\u0026 !kubeletapis.IsKubeletLabel(label) {\n\t\t\t// TODO: defer to label policy once available\n\t\t\tforbiddenLabels.Insert(label)\n\t\t}\n\t}\n\treturn forbiddenLabels\n}","line":{"from":483,"to":503}} {"id":100013482,"name":"admitServiceAccount","signature":"func (p *Plugin) admitServiceAccount(nodeName string, a admission.Attributes) error","file":"plugin/pkg/admission/noderestriction/admission.go","code":"func (p *Plugin) admitServiceAccount(nodeName string, a admission.Attributes) error {\n\tif a.GetOperation() != admission.Create {\n\t\treturn nil\n\t}\n\tif a.GetSubresource() != \"token\" {\n\t\treturn nil\n\t}\n\ttr, ok := a.GetObject().(*authenticationapi.TokenRequest)\n\tif !ok {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"unexpected type %T\", a.GetObject()))\n\t}\n\n\t// TokenRequests from a node must have a pod binding. That pod must be\n\t// scheduled on the node.\n\tref := tr.Spec.BoundObjectRef\n\tif ref == nil ||\n\t\tref.APIVersion != \"v1\" ||\n\t\tref.Kind != \"Pod\" ||\n\t\tref.Name == \"\" {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"node requested token not bound to a pod\"))\n\t}\n\tif ref.UID == \"\" {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"node requested token with a pod binding without a uid\"))\n\t}\n\tpod, err := p.podsGetter.Pods(a.GetNamespace()).Get(ref.Name)\n\tif errors.IsNotFound(err) {\n\t\treturn err\n\t}\n\tif err != nil {\n\t\treturn admission.NewForbidden(a, err)\n\t}\n\tif ref.UID != pod.UID {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"the UID in the bound object reference (%s) does not match the UID in record. The object might have been deleted and then recreated\", ref.UID))\n\t}\n\tif pod.Spec.NodeName != nodeName {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"node requested token bound to a pod scheduled on a different node\"))\n\t}\n\n\treturn nil\n}","line":{"from":505,"to":544}} {"id":100013483,"name":"admitLease","signature":"func (p *Plugin) admitLease(nodeName string, a admission.Attributes) error","file":"plugin/pkg/admission/noderestriction/admission.go","code":"func (p *Plugin) admitLease(nodeName string, a admission.Attributes) error {\n\t// the request must be against the system namespace reserved for node leases\n\tif a.GetNamespace() != api.NamespaceNodeLease {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"can only access leases in the %q system namespace\", api.NamespaceNodeLease))\n\t}\n\n\t// the request must come from a node with the same name as the lease\n\tif a.GetOperation() == admission.Create {\n\t\t// a.GetName() won't return the name on create, so we drill down to the proposed object\n\t\tlease, ok := a.GetObject().(*coordapi.Lease)\n\t\tif !ok {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"unexpected type %T\", a.GetObject()))\n\t\t}\n\t\tif lease.Name != nodeName {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"can only access node lease with the same name as the requesting node\"))\n\t\t}\n\t} else {\n\t\tif a.GetName() != nodeName {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"can only access node lease with the same name as the requesting node\"))\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":546,"to":569}} {"id":100013484,"name":"admitCSINode","signature":"func (p *Plugin) admitCSINode(nodeName string, a admission.Attributes) error","file":"plugin/pkg/admission/noderestriction/admission.go","code":"func (p *Plugin) admitCSINode(nodeName string, a admission.Attributes) error {\n\t// the request must come from a node with the same name as the CSINode object\n\tif a.GetOperation() == admission.Create {\n\t\t// a.GetName() won't return the name on create, so we drill down to the proposed object\n\t\taccessor, err := meta.Accessor(a.GetObject())\n\t\tif err != nil {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"unable to access the object name\"))\n\t\t}\n\t\tif accessor.GetName() != nodeName {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"can only access CSINode with the same name as the requesting node\"))\n\t\t}\n\t} else {\n\t\tif a.GetName() != nodeName {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"can only access CSINode with the same name as the requesting node\"))\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":571,"to":589}} {"id":100013485,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/nodetaint/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\treturn NewPlugin(), nil\n\t})\n}","line":{"from":34,"to":39}} {"id":100013486,"name":"NewPlugin","signature":"func NewPlugin() *Plugin","file":"plugin/pkg/admission/nodetaint/admission.go","code":"// NewPlugin creates a new NodeTaint admission plugin.\n// This plugin identifies requests from nodes\nfunc NewPlugin() *Plugin {\n\treturn \u0026Plugin{\n\t\tHandler: admission.NewHandler(admission.Create),\n\t}\n}","line":{"from":41,"to":47}} {"id":100013487,"name":"Admit","signature":"func (p *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error","file":"plugin/pkg/admission/nodetaint/admission.go","code":"// Admit is the main function that checks node identity and adds taints as needed.\nfunc (p *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {\n\t// Our job is just to taint nodes.\n\tif a.GetResource().GroupResource() != nodeResource || a.GetSubresource() != \"\" {\n\t\treturn nil\n\t}\n\n\tnode, ok := a.GetObject().(*api.Node)\n\tif !ok {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"unexpected type %T\", a.GetObject()))\n\t}\n\n\t// Taint node with NotReady taint at creation. This is needed to make sure\n\t// that nodes are added to the cluster with the NotReady taint. Otherwise,\n\t// a new node may receive the taint with some delay causing pods to be\n\t// scheduled on a not-ready node. Node controller will remove the taint\n\t// when the node becomes ready.\n\taddNotReadyTaint(node)\n\treturn nil\n}","line":{"from":62,"to":81}} {"id":100013488,"name":"addNotReadyTaint","signature":"func addNotReadyTaint(node *api.Node)","file":"plugin/pkg/admission/nodetaint/admission.go","code":"func addNotReadyTaint(node *api.Node) {\n\tnotReadyTaint := api.Taint{\n\t\tKey: v1.TaintNodeNotReady,\n\t\tEffect: api.TaintEffectNoSchedule,\n\t}\n\tfor _, taint := range node.Spec.Taints {\n\t\tif taint.MatchTaint(notReadyTaint) {\n\t\t\t// the taint already exists.\n\t\t\treturn\n\t\t}\n\t}\n\tnode.Spec.Taints = append(node.Spec.Taints, notReadyTaint)\n}","line":{"from":83,"to":95}} {"id":100013489,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/podnodeselector/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\t// TODO move this to a versioned configuration file format.\n\t\tpluginConfig := readConfig(config)\n\t\tplugin := NewPodNodeSelector(pluginConfig.PodNodeSelectorPluginConfig)\n\t\treturn plugin, nil\n\t})\n}","line":{"from":48,"to":56}} {"id":100013490,"name":"readConfig","signature":"func readConfig(config io.Reader) *pluginConfig","file":"plugin/pkg/admission/podnodeselector/admission.go","code":"// readConfig reads default value of clusterDefaultNodeSelector\n// from the file provided with --admission-control-config-file\n// If the file is not supplied, it defaults to \"\"\n// The format in a file:\n// podNodeSelectorPluginConfig:\n//\n//\tclusterDefaultNodeSelector: \u003cnode-selectors-labels\u003e\n//\tnamespace1: \u003cnode-selectors-labels\u003e\n//\tnamespace2: \u003cnode-selectors-labels\u003e\nfunc readConfig(config io.Reader) *pluginConfig {\n\tdefaultConfig := \u0026pluginConfig{}\n\tif config == nil || reflect.ValueOf(config).IsNil() {\n\t\treturn defaultConfig\n\t}\n\td := yaml.NewYAMLOrJSONDecoder(config, 4096)\n\tfor {\n\t\tif err := d.Decode(defaultConfig); err != nil {\n\t\t\tif err != io.EOF {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tbreak\n\t}\n\treturn defaultConfig\n}","line":{"from":74,"to":98}} {"id":100013491,"name":"Admit","signature":"func (p *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error","file":"plugin/pkg/admission/podnodeselector/admission.go","code":"// Admit enforces that pod and its namespace node label selectors matches at least a node in the cluster.\nfunc (p *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {\n\tif shouldIgnore(a) {\n\t\treturn nil\n\t}\n\tif !p.WaitForReady() {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"not yet ready to handle request\"))\n\t}\n\n\tresource := a.GetResource().GroupResource()\n\tpod := a.GetObject().(*api.Pod)\n\tnamespaceNodeSelector, err := p.getNamespaceNodeSelectorMap(a.GetNamespace())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif labels.Conflicts(namespaceNodeSelector, labels.Set(pod.Spec.NodeSelector)) {\n\t\treturn errors.NewForbidden(resource, pod.Name, fmt.Errorf(\"pod node label selector conflicts with its namespace node label selector\"))\n\t}\n\n\t// Merge pod node selector = namespace node selector + current pod node selector\n\t// second selector wins\n\tpodNodeSelectorLabels := labels.Merge(namespaceNodeSelector, pod.Spec.NodeSelector)\n\tpod.Spec.NodeSelector = map[string]string(podNodeSelectorLabels)\n\treturn p.Validate(ctx, a, o)\n}","line":{"from":100,"to":125}} {"id":100013492,"name":"Validate","signature":"func (p *Plugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error","file":"plugin/pkg/admission/podnodeselector/admission.go","code":"// Validate ensures that the pod node selector is allowed\nfunc (p *Plugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {\n\tif shouldIgnore(a) {\n\t\treturn nil\n\t}\n\tif !p.WaitForReady() {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"not yet ready to handle request\"))\n\t}\n\n\tresource := a.GetResource().GroupResource()\n\tpod := a.GetObject().(*api.Pod)\n\n\tnamespaceNodeSelector, err := p.getNamespaceNodeSelectorMap(a.GetNamespace())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif labels.Conflicts(namespaceNodeSelector, labels.Set(pod.Spec.NodeSelector)) {\n\t\treturn errors.NewForbidden(resource, pod.Name, fmt.Errorf(\"pod node label selector conflicts with its namespace node label selector\"))\n\t}\n\n\t// whitelist verification\n\twhitelist, err := labels.ConvertSelectorToLabelsMap(p.clusterNodeSelectors[a.GetNamespace()])\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !isSubset(pod.Spec.NodeSelector, whitelist) {\n\t\treturn errors.NewForbidden(resource, pod.Name, fmt.Errorf(\"pod node label selector labels conflict with its namespace whitelist\"))\n\t}\n\n\treturn nil\n}","line":{"from":127,"to":157}} {"id":100013493,"name":"getNamespaceNodeSelectorMap","signature":"func (p *Plugin) getNamespaceNodeSelectorMap(namespaceName string) (labels.Set, error)","file":"plugin/pkg/admission/podnodeselector/admission.go","code":"func (p *Plugin) getNamespaceNodeSelectorMap(namespaceName string) (labels.Set, error) {\n\tnamespace, err := p.namespaceLister.Get(namespaceName)\n\tif errors.IsNotFound(err) {\n\t\tnamespace, err = p.defaultGetNamespace(namespaceName)\n\t\tif err != nil {\n\t\t\tif errors.IsNotFound(err) {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn nil, errors.NewInternalError(err)\n\t\t}\n\t} else if err != nil {\n\t\treturn nil, errors.NewInternalError(err)\n\t}\n\n\treturn p.getNodeSelectorMap(namespace)\n}","line":{"from":159,"to":174}} {"id":100013494,"name":"shouldIgnore","signature":"func shouldIgnore(a admission.Attributes) bool","file":"plugin/pkg/admission/podnodeselector/admission.go","code":"func shouldIgnore(a admission.Attributes) bool {\n\tresource := a.GetResource().GroupResource()\n\tif resource != api.Resource(\"pods\") {\n\t\treturn true\n\t}\n\tif a.GetSubresource() != \"\" {\n\t\t// only run the checks below on pods proper and not subresources\n\t\treturn true\n\t}\n\n\t_, ok := a.GetObject().(*api.Pod)\n\tif !ok {\n\t\tklog.Errorf(\"expected pod but got %s\", a.GetKind().Kind)\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":176,"to":193}} {"id":100013495,"name":"NewPodNodeSelector","signature":"func NewPodNodeSelector(clusterNodeSelectors map[string]string) *Plugin","file":"plugin/pkg/admission/podnodeselector/admission.go","code":"// NewPodNodeSelector initializes a podNodeSelector\nfunc NewPodNodeSelector(clusterNodeSelectors map[string]string) *Plugin {\n\treturn \u0026Plugin{\n\t\tHandler: admission.NewHandler(admission.Create),\n\t\tclusterNodeSelectors: clusterNodeSelectors,\n\t}\n}","line":{"from":195,"to":201}} {"id":100013496,"name":"SetExternalKubeClientSet","signature":"func (p *Plugin) SetExternalKubeClientSet(client kubernetes.Interface)","file":"plugin/pkg/admission/podnodeselector/admission.go","code":"// SetExternalKubeClientSet sets the plugin's client\nfunc (p *Plugin) SetExternalKubeClientSet(client kubernetes.Interface) {\n\tp.client = client\n}","line":{"from":203,"to":206}} {"id":100013497,"name":"SetExternalKubeInformerFactory","signature":"func (p *Plugin) SetExternalKubeInformerFactory(f informers.SharedInformerFactory)","file":"plugin/pkg/admission/podnodeselector/admission.go","code":"// SetExternalKubeInformerFactory configures the plugin's informer factory\nfunc (p *Plugin) SetExternalKubeInformerFactory(f informers.SharedInformerFactory) {\n\tnamespaceInformer := f.Core().V1().Namespaces()\n\tp.namespaceLister = namespaceInformer.Lister()\n\tp.SetReadyFunc(namespaceInformer.Informer().HasSynced)\n}","line":{"from":208,"to":213}} {"id":100013498,"name":"ValidateInitialization","signature":"func (p *Plugin) ValidateInitialization() error","file":"plugin/pkg/admission/podnodeselector/admission.go","code":"// ValidateInitialization verifies the object has been properly initialized\nfunc (p *Plugin) ValidateInitialization() error {\n\tif p.namespaceLister == nil {\n\t\treturn fmt.Errorf(\"missing namespaceLister\")\n\t}\n\tif p.client == nil {\n\t\treturn fmt.Errorf(\"missing client\")\n\t}\n\treturn nil\n}","line":{"from":215,"to":224}} {"id":100013499,"name":"defaultGetNamespace","signature":"func (p *Plugin) defaultGetNamespace(name string) (*corev1.Namespace, error)","file":"plugin/pkg/admission/podnodeselector/admission.go","code":"func (p *Plugin) defaultGetNamespace(name string) (*corev1.Namespace, error) {\n\tnamespace, err := p.client.CoreV1().Namespaces().Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"namespace %s does not exist\", name)\n\t}\n\treturn namespace, nil\n}","line":{"from":226,"to":232}} {"id":100013500,"name":"getNodeSelectorMap","signature":"func (p *Plugin) getNodeSelectorMap(namespace *corev1.Namespace) (labels.Set, error)","file":"plugin/pkg/admission/podnodeselector/admission.go","code":"func (p *Plugin) getNodeSelectorMap(namespace *corev1.Namespace) (labels.Set, error) {\n\tselector := labels.Set{}\n\tvar err error\n\tfound := false\n\tif len(namespace.ObjectMeta.Annotations) \u003e 0 {\n\t\tfor _, annotation := range NamespaceNodeSelectors {\n\t\t\tif ns, ok := namespace.ObjectMeta.Annotations[annotation]; ok {\n\t\t\t\tlabelsMap, err := labels.ConvertSelectorToLabelsMap(ns)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn labels.Set{}, err\n\t\t\t\t}\n\n\t\t\t\tif labels.Conflicts(selector, labelsMap) {\n\t\t\t\t\tnsName := namespace.ObjectMeta.Name\n\t\t\t\t\treturn labels.Set{}, fmt.Errorf(\"%s annotations' node label selectors conflict\", nsName)\n\t\t\t\t}\n\t\t\t\tselector = labels.Merge(selector, labelsMap)\n\t\t\t\tfound = true\n\t\t\t}\n\t\t}\n\t}\n\tif !found {\n\t\tselector, err = labels.ConvertSelectorToLabelsMap(p.clusterNodeSelectors[\"clusterDefaultNodeSelector\"])\n\t\tif err != nil {\n\t\t\treturn labels.Set{}, err\n\t\t}\n\t}\n\treturn selector, nil\n}","line":{"from":234,"to":262}} {"id":100013501,"name":"isSubset","signature":"func isSubset(subSet, superSet labels.Set) bool","file":"plugin/pkg/admission/podnodeselector/admission.go","code":"func isSubset(subSet, superSet labels.Set) bool {\n\tif len(superSet) == 0 {\n\t\treturn true\n\t}\n\n\tfor k, v := range subSet {\n\t\tvalue, ok := superSet[k]\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\tif value != v {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":264,"to":279}} {"id":100013502,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/podtolerationrestriction/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\tpluginConfig, err := loadConfiguration(config)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn NewPodTolerationsPlugin(pluginConfig), nil\n\t})\n}","line":{"from":45,"to":54}} {"id":100013503,"name":"Admit","signature":"func (p *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error","file":"plugin/pkg/admission/podtolerationrestriction/admission.go","code":"// Admit checks the admission policy and triggers corresponding actions\nfunc (p *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {\n\tif shouldIgnore(a) {\n\t\treturn nil\n\t}\n\n\tif !p.WaitForReady() {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"not yet ready to handle request\"))\n\t}\n\n\tpod := a.GetObject().(*api.Pod)\n\tvar extraTolerations []api.Toleration\n\tif a.GetOperation() == admission.Create {\n\t\tts, err := p.getNamespaceDefaultTolerations(a.GetNamespace())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// If the namespace has not specified its default tolerations,\n\t\t// fall back to cluster's default tolerations.\n\t\tif ts == nil {\n\t\t\tts = p.pluginConfig.Default\n\t\t}\n\n\t\textraTolerations = ts\n\t}\n\n\tif qoshelper.GetPodQOS(pod) != api.PodQOSBestEffort {\n\t\textraTolerations = append(extraTolerations, api.Toleration{\n\t\t\tKey: corev1.TaintNodeMemoryPressure,\n\t\t\tOperator: api.TolerationOpExists,\n\t\t\tEffect: api.TaintEffectNoSchedule,\n\t\t})\n\t}\n\t// Final merge of tolerations irrespective of pod type.\n\tif len(extraTolerations) \u003e 0 {\n\t\tpod.Spec.Tolerations = tolerations.MergeTolerations(pod.Spec.Tolerations, extraTolerations)\n\t}\n\treturn p.Validate(ctx, a, o)\n}","line":{"from":75,"to":114}} {"id":100013504,"name":"Validate","signature":"func (p *Plugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error","file":"plugin/pkg/admission/podtolerationrestriction/admission.go","code":"// Validate we can obtain a whitelist of tolerations\nfunc (p *Plugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {\n\tif shouldIgnore(a) {\n\t\treturn nil\n\t}\n\n\tif !p.WaitForReady() {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"not yet ready to handle request\"))\n\t}\n\n\t// whitelist verification.\n\tpod := a.GetObject().(*api.Pod)\n\tif len(pod.Spec.Tolerations) \u003e 0 {\n\t\twhitelist, err := p.getNamespaceTolerationsWhitelist(a.GetNamespace())\n\t\twhitelistScope := \"namespace\"\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// If the namespace has not specified its tolerations whitelist,\n\t\t// fall back to cluster's whitelist of tolerations.\n\t\tif whitelist == nil {\n\t\t\twhitelist = p.pluginConfig.Whitelist\n\t\t\twhitelistScope = \"cluster\"\n\t\t}\n\n\t\tif len(whitelist) \u003e 0 {\n\t\t\t// check if the merged pod tolerations satisfy its namespace whitelist\n\t\t\tif !tolerations.VerifyAgainstWhitelist(pod.Spec.Tolerations, whitelist) {\n\t\t\t\treturn fmt.Errorf(\"pod tolerations (possibly merged with namespace default tolerations) conflict with its %s whitelist\", whitelistScope)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":116,"to":151}} {"id":100013505,"name":"shouldIgnore","signature":"func shouldIgnore(a admission.Attributes) bool","file":"plugin/pkg/admission/podtolerationrestriction/admission.go","code":"func shouldIgnore(a admission.Attributes) bool {\n\tresource := a.GetResource().GroupResource()\n\tif resource != api.Resource(\"pods\") {\n\t\treturn true\n\t}\n\tif a.GetSubresource() != \"\" {\n\t\t// only run the checks below on pods proper and not subresources\n\t\treturn true\n\t}\n\n\tobj := a.GetObject()\n\t_, ok := obj.(*api.Pod)\n\tif !ok {\n\t\tklog.Errorf(\"expected pod but got %s\", a.GetKind().Kind)\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":153,"to":171}} {"id":100013506,"name":"NewPodTolerationsPlugin","signature":"func NewPodTolerationsPlugin(pluginConfig *pluginapi.Configuration) *Plugin","file":"plugin/pkg/admission/podtolerationrestriction/admission.go","code":"// NewPodTolerationsPlugin initializes a Plugin\nfunc NewPodTolerationsPlugin(pluginConfig *pluginapi.Configuration) *Plugin {\n\treturn \u0026Plugin{\n\t\tHandler: admission.NewHandler(admission.Create, admission.Update),\n\t\tpluginConfig: pluginConfig,\n\t}\n}","line":{"from":173,"to":179}} {"id":100013507,"name":"SetExternalKubeClientSet","signature":"func (p *Plugin) SetExternalKubeClientSet(client kubernetes.Interface)","file":"plugin/pkg/admission/podtolerationrestriction/admission.go","code":"// SetExternalKubeClientSet sets th client\nfunc (p *Plugin) SetExternalKubeClientSet(client kubernetes.Interface) {\n\tp.client = client\n}","line":{"from":181,"to":184}} {"id":100013508,"name":"SetExternalKubeInformerFactory","signature":"func (p *Plugin) SetExternalKubeInformerFactory(f informers.SharedInformerFactory)","file":"plugin/pkg/admission/podtolerationrestriction/admission.go","code":"// SetExternalKubeInformerFactory initializes the Informer Factory\nfunc (p *Plugin) SetExternalKubeInformerFactory(f informers.SharedInformerFactory) {\n\tnamespaceInformer := f.Core().V1().Namespaces()\n\tp.namespaceLister = namespaceInformer.Lister()\n\tp.SetReadyFunc(namespaceInformer.Informer().HasSynced)\n\n}","line":{"from":186,"to":192}} {"id":100013509,"name":"ValidateInitialization","signature":"func (p *Plugin) ValidateInitialization() error","file":"plugin/pkg/admission/podtolerationrestriction/admission.go","code":"// ValidateInitialization checks the object is properly initialized\nfunc (p *Plugin) ValidateInitialization() error {\n\tif p.namespaceLister == nil {\n\t\treturn fmt.Errorf(\"missing namespaceLister\")\n\t}\n\tif p.client == nil {\n\t\treturn fmt.Errorf(\"missing client\")\n\t}\n\treturn nil\n}","line":{"from":194,"to":203}} {"id":100013510,"name":"getNamespace","signature":"func (p *Plugin) getNamespace(nsName string) (*corev1.Namespace, error)","file":"plugin/pkg/admission/podtolerationrestriction/admission.go","code":"// in exceptional cases, this can result in two live calls, but once the cache catches up, that will stop.\nfunc (p *Plugin) getNamespace(nsName string) (*corev1.Namespace, error) {\n\tnamespace, err := p.namespaceLister.Get(nsName)\n\tif errors.IsNotFound(err) {\n\t\t// in case of latency in our caches, make a call direct to storage to verify that it truly exists or not\n\t\tnamespace, err = p.client.CoreV1().Namespaces().Get(context.TODO(), nsName, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\tif errors.IsNotFound(err) {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn nil, errors.NewInternalError(err)\n\t\t}\n\t} else if err != nil {\n\t\treturn nil, errors.NewInternalError(err)\n\t}\n\n\treturn namespace, nil\n}","line":{"from":205,"to":222}} {"id":100013511,"name":"getNamespaceDefaultTolerations","signature":"func (p *Plugin) getNamespaceDefaultTolerations(nsName string) ([]api.Toleration, error)","file":"plugin/pkg/admission/podtolerationrestriction/admission.go","code":"func (p *Plugin) getNamespaceDefaultTolerations(nsName string) ([]api.Toleration, error) {\n\tns, err := p.getNamespace(nsName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn extractNSTolerations(ns, NSDefaultTolerations)\n}","line":{"from":224,"to":230}} {"id":100013512,"name":"getNamespaceTolerationsWhitelist","signature":"func (p *Plugin) getNamespaceTolerationsWhitelist(nsName string) ([]api.Toleration, error)","file":"plugin/pkg/admission/podtolerationrestriction/admission.go","code":"func (p *Plugin) getNamespaceTolerationsWhitelist(nsName string) ([]api.Toleration, error) {\n\tns, err := p.getNamespace(nsName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn extractNSTolerations(ns, NSWLTolerations)\n}","line":{"from":232,"to":238}} {"id":100013513,"name":"extractNSTolerations","signature":"func extractNSTolerations(ns *corev1.Namespace, key string) ([]api.Toleration, error)","file":"plugin/pkg/admission/podtolerationrestriction/admission.go","code":"// extractNSTolerations extracts default or whitelist of tolerations from\n// following namespace annotations keys: \"scheduler.alpha.kubernetes.io/defaultTolerations\"\n// and \"scheduler.alpha.kubernetes.io/tolerationsWhitelist\". If these keys are\n// unset (nil), extractNSTolerations returns nil. If the value to these\n// keys are set to empty, an empty toleration is returned, otherwise\n// configured tolerations are returned.\nfunc extractNSTolerations(ns *corev1.Namespace, key string) ([]api.Toleration, error) {\n\t// if a namespace does not have any annotations\n\tif len(ns.Annotations) == 0 {\n\t\treturn nil, nil\n\t}\n\n\t// if NSWLTolerations or NSDefaultTolerations does not exist\n\tif _, ok := ns.Annotations[key]; !ok {\n\t\treturn nil, nil\n\t}\n\n\t// if value is set to empty\n\tif len(ns.Annotations[key]) == 0 {\n\t\treturn []api.Toleration{}, nil\n\t}\n\n\tvar v1Tolerations []corev1.Toleration\n\terr := json.Unmarshal([]byte(ns.Annotations[key]), \u0026v1Tolerations)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tts := make([]api.Toleration, len(v1Tolerations))\n\tfor i := range v1Tolerations {\n\t\tif err := k8s_api_v1.Convert_v1_Toleration_To_core_Toleration(\u0026v1Tolerations[i], \u0026ts[i], nil); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn ts, nil\n}","line":{"from":240,"to":276}} {"id":100013514,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"plugin/pkg/admission/podtolerationrestriction/apis/podtolerationrestriction/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(internalapi.AddToScheme(scheme))\n\tutilruntime.Must(versionedapi.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(versionedapi.SchemeGroupVersion))\n}","line":{"from":28,"to":33}} {"id":100013515,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"plugin/pkg/admission/podtolerationrestriction/apis/podtolerationrestriction/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":37,"to":40}} {"id":100013516,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"plugin/pkg/admission/podtolerationrestriction/apis/podtolerationrestriction/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":42,"to":45}} {"id":100013517,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"plugin/pkg/admission/podtolerationrestriction/apis/podtolerationrestriction/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Configuration{},\n\t)\n\treturn nil\n}","line":{"from":47,"to":52}} {"id":100013518,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"plugin/pkg/admission/podtolerationrestriction/apis/podtolerationrestriction/v1alpha1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":21,"to":23}} {"id":100013519,"name":"init","signature":"func init()","file":"plugin/pkg/admission/podtolerationrestriction/apis/podtolerationrestriction/v1alpha1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addKnownTypes, addDefaultingFuncs)\n}","line":{"from":41,"to":46}} {"id":100013520,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"plugin/pkg/admission/podtolerationrestriction/apis/podtolerationrestriction/v1alpha1/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Configuration{},\n\t)\n\treturn nil\n}","line":{"from":48,"to":53}} {"id":100013521,"name":"ValidateConfiguration","signature":"func ValidateConfiguration(config *internalapi.Configuration) error","file":"plugin/pkg/admission/podtolerationrestriction/apis/podtolerationrestriction/validation/validation.go","code":"// ValidateConfiguration validates the configuration.\nfunc ValidateConfiguration(config *internalapi.Configuration) error {\n\tallErrs := field.ErrorList{}\n\tfldpath := field.NewPath(\"podtolerationrestriction\")\n\tallErrs = append(allErrs, validation.ValidateTolerations(config.Default, fldpath.Child(\"default\"))...)\n\tallErrs = append(allErrs, validation.ValidateTolerations(config.Whitelist, fldpath.Child(\"whitelist\"))...)\n\tif len(allErrs) \u003e 0 {\n\t\treturn fmt.Errorf(\"invalid config: %v\", allErrs)\n\t}\n\treturn nil\n}","line":{"from":27,"to":37}} {"id":100013522,"name":"init","signature":"func init()","file":"plugin/pkg/admission/podtolerationrestriction/config.go","code":"func init() {\n\tinstall.Install(scheme)\n}","line":{"from":37,"to":39}} {"id":100013523,"name":"loadConfiguration","signature":"func loadConfiguration(config io.Reader) (*internalapi.Configuration, error)","file":"plugin/pkg/admission/podtolerationrestriction/config.go","code":"// LoadConfiguration loads the provided configuration.\nfunc loadConfiguration(config io.Reader) (*internalapi.Configuration, error) {\n\t// if no config is provided, return a default configuration\n\tif config == nil {\n\t\texternalConfig := \u0026versionedapi.Configuration{}\n\t\tscheme.Default(externalConfig)\n\t\tinternalConfig := \u0026internalapi.Configuration{}\n\t\tif err := scheme.Convert(externalConfig, internalConfig, nil); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn internalConfig, nil\n\t}\n\t// we have a config so parse it.\n\tdata, err := ioutil.ReadAll(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdecoder := codecs.UniversalDecoder()\n\tdecodedObj, err := runtime.Decode(decoder, data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\texternalConfig, ok := decodedObj.(*internalapi.Configuration)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unexpected type: %T\", decodedObj)\n\t}\n\n\tif err := validation.ValidateConfiguration(externalConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn externalConfig, nil\n}","line":{"from":41,"to":73}} {"id":100013524,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/priority/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\treturn NewPlugin(), nil\n\t})\n}","line":{"from":42,"to":47}} {"id":100013525,"name":"NewPlugin","signature":"func NewPlugin() *Plugin","file":"plugin/pkg/admission/priority/admission.go","code":"// NewPlugin creates a new priority admission plugin.\nfunc NewPlugin() *Plugin {\n\treturn \u0026Plugin{\n\t\tHandler: admission.NewHandler(admission.Create, admission.Update, admission.Delete),\n\t}\n}","line":{"from":61,"to":66}} {"id":100013526,"name":"ValidateInitialization","signature":"func (p *Plugin) ValidateInitialization() error","file":"plugin/pkg/admission/priority/admission.go","code":"// ValidateInitialization implements the InitializationValidator interface.\nfunc (p *Plugin) ValidateInitialization() error {\n\tif p.client == nil {\n\t\treturn fmt.Errorf(\"%s requires a client\", PluginName)\n\t}\n\tif p.lister == nil {\n\t\treturn fmt.Errorf(\"%s requires a lister\", PluginName)\n\t}\n\treturn nil\n}","line":{"from":68,"to":77}} {"id":100013527,"name":"SetExternalKubeClientSet","signature":"func (p *Plugin) SetExternalKubeClientSet(client kubernetes.Interface)","file":"plugin/pkg/admission/priority/admission.go","code":"// SetExternalKubeClientSet implements the WantsInternalKubeClientSet interface.\nfunc (p *Plugin) SetExternalKubeClientSet(client kubernetes.Interface) {\n\tp.client = client\n}","line":{"from":79,"to":82}} {"id":100013528,"name":"SetExternalKubeInformerFactory","signature":"func (p *Plugin) SetExternalKubeInformerFactory(f informers.SharedInformerFactory)","file":"plugin/pkg/admission/priority/admission.go","code":"// SetExternalKubeInformerFactory implements the WantsInternalKubeInformerFactory interface.\nfunc (p *Plugin) SetExternalKubeInformerFactory(f informers.SharedInformerFactory) {\n\tpriorityInformer := f.Scheduling().V1().PriorityClasses()\n\tp.lister = priorityInformer.Lister()\n\tp.SetReadyFunc(priorityInformer.Informer().HasSynced)\n}","line":{"from":84,"to":89}} {"id":100013529,"name":"Admit","signature":"func (p *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error","file":"plugin/pkg/admission/priority/admission.go","code":"// Admit checks Pods and admits or rejects them. It also resolves the priority of pods based on their PriorityClass.\n// Note that pod validation mechanism prevents update of a pod priority.\nfunc (p *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {\n\toperation := a.GetOperation()\n\t// Ignore all calls to subresources\n\tif len(a.GetSubresource()) != 0 {\n\t\treturn nil\n\t}\n\tswitch a.GetResource().GroupResource() {\n\tcase podResource:\n\t\tif operation == admission.Create || operation == admission.Update {\n\t\t\treturn p.admitPod(a)\n\t\t}\n\t\treturn nil\n\n\tdefault:\n\t\treturn nil\n\t}\n}","line":{"from":96,"to":114}} {"id":100013530,"name":"Validate","signature":"func (p *Plugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error","file":"plugin/pkg/admission/priority/admission.go","code":"// Validate checks PriorityClasses and admits or rejects them.\nfunc (p *Plugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {\n\toperation := a.GetOperation()\n\t// Ignore all calls to subresources\n\tif len(a.GetSubresource()) != 0 {\n\t\treturn nil\n\t}\n\n\tswitch a.GetResource().GroupResource() {\n\tcase priorityClassResource:\n\t\tif operation == admission.Create || operation == admission.Update {\n\t\t\treturn p.validatePriorityClass(a)\n\t\t}\n\t\treturn nil\n\n\tdefault:\n\t\treturn nil\n\t}\n}","line":{"from":116,"to":134}} {"id":100013531,"name":"admitPod","signature":"func (p *Plugin) admitPod(a admission.Attributes) error","file":"plugin/pkg/admission/priority/admission.go","code":"// admitPod makes sure a new pod does not set spec.Priority field. It also makes sure that the PriorityClassName exists if it is provided and resolves the pod priority from the PriorityClassName.\nfunc (p *Plugin) admitPod(a admission.Attributes) error {\n\toperation := a.GetOperation()\n\tpod, ok := a.GetObject().(*core.Pod)\n\tif !ok {\n\t\treturn errors.NewBadRequest(\"resource was marked with kind Pod but was unable to be converted\")\n\t}\n\n\tif operation == admission.Update {\n\t\toldPod, ok := a.GetOldObject().(*core.Pod)\n\t\tif !ok {\n\t\t\treturn errors.NewBadRequest(\"resource was marked with kind Pod but was unable to be converted\")\n\t\t}\n\n\t\t// This admission plugin set pod.Spec.Priority on create.\n\t\t// Ensure the existing priority is preserved on update.\n\t\t// API validation prevents mutations to Priority and PriorityClassName, so any other changes will fail update validation and not be persisted.\n\t\tif pod.Spec.Priority == nil \u0026\u0026 oldPod.Spec.Priority != nil {\n\t\t\tpod.Spec.Priority = oldPod.Spec.Priority\n\t\t}\n\t\tif pod.Spec.PreemptionPolicy == nil \u0026\u0026 oldPod.Spec.PreemptionPolicy != nil {\n\t\t\tpod.Spec.PreemptionPolicy = oldPod.Spec.PreemptionPolicy\n\t\t}\n\t\treturn nil\n\t}\n\n\tif operation == admission.Create {\n\t\tvar priority int32\n\t\tvar preemptionPolicy *apiv1.PreemptionPolicy\n\t\tif len(pod.Spec.PriorityClassName) == 0 {\n\t\t\tvar err error\n\t\t\tvar pcName string\n\t\t\tpcName, priority, preemptionPolicy, err = p.getDefaultPriority()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to get default priority class: %v\", err)\n\t\t\t}\n\t\t\tpod.Spec.PriorityClassName = pcName\n\t\t} else {\n\t\t\t// Try resolving the priority class name.\n\t\t\tpc, err := p.lister.Get(pod.Spec.PriorityClassName)\n\t\t\tif err != nil {\n\t\t\t\tif errors.IsNotFound(err) {\n\t\t\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"no PriorityClass with name %v was found\", pod.Spec.PriorityClassName))\n\t\t\t\t}\n\n\t\t\t\treturn fmt.Errorf(\"failed to get PriorityClass with name %s: %v\", pod.Spec.PriorityClassName, err)\n\t\t\t}\n\n\t\t\tpriority = pc.Value\n\t\t\tpreemptionPolicy = pc.PreemptionPolicy\n\t\t}\n\t\t// if the pod contained a priority that differs from the one computed from the priority class, error\n\t\tif pod.Spec.Priority != nil \u0026\u0026 *pod.Spec.Priority != priority {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"the integer value of priority (%d) must not be provided in pod spec; priority admission controller computed %d from the given PriorityClass name\", *pod.Spec.Priority, priority))\n\t\t}\n\t\tpod.Spec.Priority = \u0026priority\n\n\t\tvar corePolicy core.PreemptionPolicy\n\t\tif preemptionPolicy != nil {\n\t\t\tcorePolicy = core.PreemptionPolicy(*preemptionPolicy)\n\t\t\tif pod.Spec.PreemptionPolicy != nil \u0026\u0026 *pod.Spec.PreemptionPolicy != corePolicy {\n\t\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"the string value of PreemptionPolicy (%s) must not be provided in pod spec; priority admission controller computed %s from the given PriorityClass name\", *pod.Spec.PreemptionPolicy, corePolicy))\n\t\t\t}\n\t\t\tpod.Spec.PreemptionPolicy = \u0026corePolicy\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":136,"to":203}} {"id":100013532,"name":"validatePriorityClass","signature":"func (p *Plugin) validatePriorityClass(a admission.Attributes) error","file":"plugin/pkg/admission/priority/admission.go","code":"// validatePriorityClass ensures that the value field is not larger than the highest user definable priority. If the GlobalDefault is set, it ensures that there is no other PriorityClass whose GlobalDefault is set.\nfunc (p *Plugin) validatePriorityClass(a admission.Attributes) error {\n\toperation := a.GetOperation()\n\tpc, ok := a.GetObject().(*scheduling.PriorityClass)\n\tif !ok {\n\t\treturn errors.NewBadRequest(\"resource was marked with kind PriorityClass but was unable to be converted\")\n\t}\n\t// If the new PriorityClass tries to be the default priority, make sure that no other priority class is marked as default.\n\tif pc.GlobalDefault {\n\t\tdpc, err := p.getDefaultPriorityClass()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get default priority class: %v\", err)\n\t\t}\n\t\tif dpc != nil {\n\t\t\t// Throw an error if a second default priority class is being created, or an existing priority class is being marked as default, while another default already exists.\n\t\t\tif operation == admission.Create || (operation == admission.Update \u0026\u0026 dpc.GetName() != pc.GetName()) {\n\t\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"PriorityClass %v is already marked as default. Only one default can exist\", dpc.GetName()))\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":205,"to":226}} {"id":100013533,"name":"getDefaultPriorityClass","signature":"func (p *Plugin) getDefaultPriorityClass() (*schedulingv1.PriorityClass, error)","file":"plugin/pkg/admission/priority/admission.go","code":"func (p *Plugin) getDefaultPriorityClass() (*schedulingv1.PriorityClass, error) {\n\tlist, err := p.lister.List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// In case more than one global default priority class is added as a result of a race condition,\n\t// we pick the one with the lowest priority value.\n\tvar defaultPC *schedulingv1.PriorityClass\n\tfor _, pci := range list {\n\t\tif pci.GlobalDefault {\n\t\t\tif defaultPC == nil || defaultPC.Value \u003e pci.Value {\n\t\t\t\tdefaultPC = pci\n\t\t\t}\n\t\t}\n\t}\n\treturn defaultPC, nil\n}","line":{"from":228,"to":244}} {"id":100013534,"name":"getDefaultPriority","signature":"func (p *Plugin) getDefaultPriority() (string, int32, *apiv1.PreemptionPolicy, error)","file":"plugin/pkg/admission/priority/admission.go","code":"func (p *Plugin) getDefaultPriority() (string, int32, *apiv1.PreemptionPolicy, error) {\n\tdpc, err := p.getDefaultPriorityClass()\n\tif err != nil {\n\t\treturn \"\", 0, nil, err\n\t}\n\tif dpc != nil {\n\t\treturn dpc.Name, dpc.Value, dpc.PreemptionPolicy, nil\n\t}\n\tpreemptLowerPriority := apiv1.PreemptLowerPriority\n\treturn \"\", int32(scheduling.DefaultPriorityWhenNoDefaultClassExists), \u0026preemptLowerPriority, nil\n}","line":{"from":246,"to":256}} {"id":100013535,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/runtimeclass/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\treturn NewRuntimeClass(), nil\n\t})\n}","line":{"from":48,"to":53}} {"id":100013536,"name":"SetExternalKubeClientSet","signature":"func (r *RuntimeClass) SetExternalKubeClientSet(client kubernetes.Interface)","file":"plugin/pkg/admission/runtimeclass/admission.go","code":"// SetExternalKubeClientSet sets the client for the plugin\nfunc (r *RuntimeClass) SetExternalKubeClientSet(client kubernetes.Interface) {\n\tr.runtimeClassClient = client.NodeV1().RuntimeClasses()\n}","line":{"from":71,"to":74}} {"id":100013537,"name":"SetExternalKubeInformerFactory","signature":"func (r *RuntimeClass) SetExternalKubeInformerFactory(f informers.SharedInformerFactory)","file":"plugin/pkg/admission/runtimeclass/admission.go","code":"// SetExternalKubeInformerFactory implements the WantsExternalKubeInformerFactory interface.\nfunc (r *RuntimeClass) SetExternalKubeInformerFactory(f informers.SharedInformerFactory) {\n\truntimeClassInformer := f.Node().V1().RuntimeClasses()\n\tr.SetReadyFunc(runtimeClassInformer.Informer().HasSynced)\n\tr.runtimeClassLister = runtimeClassInformer.Lister()\n}","line":{"from":76,"to":81}} {"id":100013538,"name":"ValidateInitialization","signature":"func (r *RuntimeClass) ValidateInitialization() error","file":"plugin/pkg/admission/runtimeclass/admission.go","code":"// ValidateInitialization implements the WantsExternalKubeInformerFactory interface.\nfunc (r *RuntimeClass) ValidateInitialization() error {\n\tif r.runtimeClassLister == nil {\n\t\treturn fmt.Errorf(\"missing RuntimeClass lister\")\n\t}\n\tif r.runtimeClassClient == nil {\n\t\treturn fmt.Errorf(\"missing RuntimeClass client\")\n\t}\n\treturn nil\n}","line":{"from":83,"to":92}} {"id":100013539,"name":"Admit","signature":"func (r *RuntimeClass) Admit(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) error","file":"plugin/pkg/admission/runtimeclass/admission.go","code":"// Admit makes an admission decision based on the request attributes\nfunc (r *RuntimeClass) Admit(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) error {\n\t// Ignore all calls to subresources or resources other than pods.\n\tif shouldIgnore(attributes) {\n\t\treturn nil\n\t}\n\n\tpod, runtimeClass, err := r.prepareObjects(ctx, attributes)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := setOverhead(attributes, pod, runtimeClass); err != nil {\n\t\treturn err\n\t}\n\n\tif err := setScheduling(attributes, pod, runtimeClass); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":94,"to":114}} {"id":100013540,"name":"Validate","signature":"func (r *RuntimeClass) Validate(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) error","file":"plugin/pkg/admission/runtimeclass/admission.go","code":"// Validate makes sure that pod adhere's to RuntimeClass's definition\nfunc (r *RuntimeClass) Validate(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) error {\n\t// Ignore all calls to subresources or resources other than pods.\n\tif shouldIgnore(attributes) {\n\t\treturn nil\n\t}\n\n\tpod, runtimeClass, err := r.prepareObjects(ctx, attributes)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := validateOverhead(attributes, pod, runtimeClass); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":116,"to":132}} {"id":100013541,"name":"NewRuntimeClass","signature":"func NewRuntimeClass() *RuntimeClass","file":"plugin/pkg/admission/runtimeclass/admission.go","code":"// NewRuntimeClass creates a new RuntimeClass admission control handler\nfunc NewRuntimeClass() *RuntimeClass {\n\treturn \u0026RuntimeClass{\n\t\tHandler: admission.NewHandler(admission.Create),\n\t}\n}","line":{"from":134,"to":139}} {"id":100013542,"name":"prepareObjects","signature":"func (r *RuntimeClass) prepareObjects(ctx context.Context, attributes admission.Attributes) (pod *api.Pod, runtimeClass *nodev1.RuntimeClass, err error)","file":"plugin/pkg/admission/runtimeclass/admission.go","code":"// prepareObjects returns pod and runtimeClass types from the given admission attributes\nfunc (r *RuntimeClass) prepareObjects(ctx context.Context, attributes admission.Attributes) (pod *api.Pod, runtimeClass *nodev1.RuntimeClass, err error) {\n\tpod, ok := attributes.GetObject().(*api.Pod)\n\tif !ok {\n\t\treturn nil, nil, apierrors.NewBadRequest(\"Resource was marked with kind Pod but was unable to be converted\")\n\t}\n\n\tif pod.Spec.RuntimeClassName == nil {\n\t\treturn pod, nil, nil\n\t}\n\n\t// get RuntimeClass object\n\truntimeClass, err = r.runtimeClassLister.Get(*pod.Spec.RuntimeClassName)\n\tif apierrors.IsNotFound(err) {\n\t\t// if not found, our informer cache could be lagging, do a live lookup\n\t\truntimeClass, err = r.runtimeClassClient.Get(ctx, *pod.Spec.RuntimeClassName, metav1.GetOptions{})\n\t\tif apierrors.IsNotFound(err) {\n\t\t\treturn pod, nil, admission.NewForbidden(attributes, fmt.Errorf(\"pod rejected: RuntimeClass %q not found\", *pod.Spec.RuntimeClassName))\n\t\t}\n\t}\n\n\t// return the pod and runtimeClass.\n\treturn pod, runtimeClass, err\n}","line":{"from":141,"to":164}} {"id":100013543,"name":"setOverhead","signature":"func setOverhead(a admission.Attributes, pod *api.Pod, runtimeClass *nodev1.RuntimeClass) (err error)","file":"plugin/pkg/admission/runtimeclass/admission.go","code":"func setOverhead(a admission.Attributes, pod *api.Pod, runtimeClass *nodev1.RuntimeClass) (err error) {\n\tif runtimeClass == nil || runtimeClass.Overhead == nil {\n\t\treturn nil\n\t}\n\n\t// convert to internal type and assign to pod's Overhead\n\tnodeOverhead := \u0026node.Overhead{}\n\tif err = apinodev1.Convert_v1_Overhead_To_node_Overhead(runtimeClass.Overhead, nodeOverhead, nil); err != nil {\n\t\treturn err\n\t}\n\n\t// reject pod if Overhead is already set that differs from what is defined in RuntimeClass\n\tif pod.Spec.Overhead != nil \u0026\u0026 !apiequality.Semantic.DeepEqual(nodeOverhead.PodFixed, pod.Spec.Overhead) {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"pod rejected: Pod's Overhead doesn't match RuntimeClass's defined Overhead\"))\n\t}\n\n\tpod.Spec.Overhead = nodeOverhead.PodFixed\n\n\treturn nil\n}","line":{"from":166,"to":185}} {"id":100013544,"name":"setScheduling","signature":"func setScheduling(a admission.Attributes, pod *api.Pod, runtimeClass *nodev1.RuntimeClass) (err error)","file":"plugin/pkg/admission/runtimeclass/admission.go","code":"func setScheduling(a admission.Attributes, pod *api.Pod, runtimeClass *nodev1.RuntimeClass) (err error) {\n\tif runtimeClass == nil || runtimeClass.Scheduling == nil {\n\t\treturn nil\n\t}\n\n\t// convert to internal type and assign to pod's Scheduling\n\tnodeScheduling := \u0026node.Scheduling{}\n\tif err = apinodev1.Convert_v1_Scheduling_To_node_Scheduling(runtimeClass.Scheduling, nodeScheduling, nil); err != nil {\n\t\treturn err\n\t}\n\n\truntimeNodeSelector := nodeScheduling.NodeSelector\n\tnewNodeSelector := pod.Spec.NodeSelector\n\tif newNodeSelector == nil {\n\t\tnewNodeSelector = runtimeNodeSelector\n\t} else {\n\t\tfor key, runtimeClassValue := range runtimeNodeSelector {\n\t\t\tif podValue, ok := newNodeSelector[key]; ok \u0026\u0026 podValue != runtimeClassValue {\n\t\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"conflict: runtimeClass.scheduling.nodeSelector[%s] = %s; pod.spec.nodeSelector[%s] = %s\", key, runtimeClassValue, key, podValue))\n\t\t\t}\n\t\t\tnewNodeSelector[key] = runtimeClassValue\n\t\t}\n\t}\n\n\tnewTolerations := tolerations.MergeTolerations(pod.Spec.Tolerations, nodeScheduling.Tolerations)\n\n\tpod.Spec.NodeSelector = newNodeSelector\n\tpod.Spec.Tolerations = newTolerations\n\n\treturn nil\n}","line":{"from":187,"to":217}} {"id":100013545,"name":"validateOverhead","signature":"func validateOverhead(a admission.Attributes, pod *api.Pod, runtimeClass *nodev1.RuntimeClass) (err error)","file":"plugin/pkg/admission/runtimeclass/admission.go","code":"func validateOverhead(a admission.Attributes, pod *api.Pod, runtimeClass *nodev1.RuntimeClass) (err error) {\n\tif runtimeClass != nil \u0026\u0026 runtimeClass.Overhead != nil {\n\t\t// If the Overhead set doesn't match what is provided in the RuntimeClass definition, reject the pod\n\t\tnodeOverhead := \u0026node.Overhead{}\n\t\tif err := apinodev1.Convert_v1_Overhead_To_node_Overhead(runtimeClass.Overhead, nodeOverhead, nil); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !apiequality.Semantic.DeepEqual(nodeOverhead.PodFixed, pod.Spec.Overhead) {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"pod rejected: Pod's Overhead doesn't match RuntimeClass's defined Overhead\"))\n\t\t}\n\t} else {\n\t\t// If RuntimeClass with Overhead is not defined but an Overhead is set for pod, reject the pod\n\t\tif pod.Spec.Overhead != nil {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"pod rejected: Pod Overhead set without corresponding RuntimeClass defined Overhead\"))\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":219,"to":237}} {"id":100013546,"name":"shouldIgnore","signature":"func shouldIgnore(attributes admission.Attributes) bool","file":"plugin/pkg/admission/runtimeclass/admission.go","code":"func shouldIgnore(attributes admission.Attributes) bool {\n\t// Ignore all calls to subresources or resources other than pods.\n\tif len(attributes.GetSubresource()) != 0 || attributes.GetResource().GroupResource() != api.Resource(\"pods\") {\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":239,"to":246}} {"id":100013547,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/security/podsecurity/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(reader io.Reader) (admission.Interface, error) {\n\t\treturn newPlugin(reader)\n\t})\n}","line":{"from":61,"to":66}} {"id":100013548,"name":"getDefaultRecorder","signature":"func getDefaultRecorder() metrics.Recorder","file":"plugin/pkg/admission/security/podsecurity/admission.go","code":"func getDefaultRecorder() metrics.Recorder {\n\t// initialize and register to legacy metrics once\n\tdefaultRecorderInit.Do(func() {\n\t\tdefaultRecorder = metrics.NewPrometheusRecorder(podsecurityadmissionapi.GetAPIVersion())\n\t\tdefaultRecorder.MustRegister(legacyregistry.MustRegister)\n\t})\n\treturn defaultRecorder\n}","line":{"from":90,"to":97}} {"id":100013549,"name":"newPlugin","signature":"func newPlugin(reader io.Reader) (*Plugin, error)","file":"plugin/pkg/admission/security/podsecurity/admission.go","code":"// newPlugin creates a new admission plugin.\nfunc newPlugin(reader io.Reader) (*Plugin, error) {\n\tconfig, err := podsecurityconfigloader.LoadFromReader(reader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tevaluator, err := policy.NewEvaluator(policy.DefaultChecks())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not create PodSecurityRegistry: %w\", err)\n\t}\n\n\treturn \u0026Plugin{\n\t\tHandler: admission.NewHandler(admission.Create, admission.Update),\n\t\tdelegate: \u0026podsecurityadmission.Admission{\n\t\t\tConfiguration: config,\n\t\t\tEvaluator: evaluator,\n\t\t\tMetrics: getDefaultRecorder(),\n\t\t\tPodSpecExtractor: podsecurityadmission.DefaultPodSpecExtractor{},\n\t\t},\n\t}, nil\n}","line":{"from":99,"to":120}} {"id":100013550,"name":"SetExternalKubeInformerFactory","signature":"func (p *Plugin) SetExternalKubeInformerFactory(f informers.SharedInformerFactory)","file":"plugin/pkg/admission/security/podsecurity/admission.go","code":"// SetExternalKubeInformerFactory registers an informer\nfunc (p *Plugin) SetExternalKubeInformerFactory(f informers.SharedInformerFactory) {\n\tnamespaceInformer := f.Core().V1().Namespaces()\n\tp.namespaceLister = namespaceInformer.Lister()\n\tp.podLister = f.Core().V1().Pods().Lister()\n\tp.SetReadyFunc(namespaceInformer.Informer().HasSynced)\n\tp.updateDelegate()\n}","line":{"from":122,"to":129}} {"id":100013551,"name":"SetExternalKubeClientSet","signature":"func (p *Plugin) SetExternalKubeClientSet(client kubernetes.Interface)","file":"plugin/pkg/admission/security/podsecurity/admission.go","code":"// SetExternalKubeClientSet sets the plugin's client\nfunc (p *Plugin) SetExternalKubeClientSet(client kubernetes.Interface) {\n\tp.client = client\n\tp.updateDelegate()\n}","line":{"from":131,"to":135}} {"id":100013552,"name":"updateDelegate","signature":"func (p *Plugin) updateDelegate()","file":"plugin/pkg/admission/security/podsecurity/admission.go","code":"func (p *Plugin) updateDelegate() {\n\t// return early if we don't have what we need to set up the admission delegate\n\tif p.namespaceLister == nil {\n\t\treturn\n\t}\n\tif p.podLister == nil {\n\t\treturn\n\t}\n\tif p.client == nil {\n\t\treturn\n\t}\n\tp.delegate.PodLister = podsecurityadmission.PodListerFromInformer(p.podLister)\n\tp.delegate.NamespaceGetter = podsecurityadmission.NamespaceGetterFromListerAndClient(p.namespaceLister, p.client)\n}","line":{"from":137,"to":150}} {"id":100013553,"name":"InspectFeatureGates","signature":"func (c *Plugin) InspectFeatureGates(featureGates featuregate.FeatureGate)","file":"plugin/pkg/admission/security/podsecurity/admission.go","code":"func (c *Plugin) InspectFeatureGates(featureGates featuregate.FeatureGate) {\n\tc.inspectedFeatureGates = true\n}","line":{"from":152,"to":154}} {"id":100013554,"name":"ValidateInitialization","signature":"func (p *Plugin) ValidateInitialization() error","file":"plugin/pkg/admission/security/podsecurity/admission.go","code":"// ValidateInitialization ensures all required options are set\nfunc (p *Plugin) ValidateInitialization() error {\n\tif !p.inspectedFeatureGates {\n\t\treturn fmt.Errorf(\"%s did not see feature gates\", PluginName)\n\t}\n\tif err := p.delegate.CompleteConfiguration(); err != nil {\n\t\treturn fmt.Errorf(\"%s configuration error: %w\", PluginName, err)\n\t}\n\tif err := p.delegate.ValidateConfiguration(); err != nil {\n\t\treturn fmt.Errorf(\"%s invalid: %w\", PluginName, err)\n\t}\n\treturn nil\n}","line":{"from":156,"to":168}} {"id":100013555,"name":"Validate","signature":"func (p *Plugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error","file":"plugin/pkg/admission/security/podsecurity/admission.go","code":"func (p *Plugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {\n\tgr := a.GetResource().GroupResource()\n\tif !applicableResources[gr] \u0026\u0026 !p.delegate.PodSpecExtractor.HasPodSpec(gr) {\n\t\treturn nil\n\t}\n\n\tresult := p.delegate.Validate(ctx, \u0026lazyConvertingAttributes{Attributes: a})\n\tfor _, w := range result.Warnings {\n\t\twarning.AddWarning(ctx, \"\", w)\n\t}\n\tif len(result.AuditAnnotations) \u003e 0 {\n\t\tannotations := make([]string, len(result.AuditAnnotations)*2)\n\t\ti := 0\n\t\tfor k, v := range result.AuditAnnotations {\n\t\t\tannotations[i], annotations[i+1] = podsecurityadmissionapi.AuditAnnotationPrefix+k, v\n\t\t\ti += 2\n\t\t}\n\t\taudit.AddAuditAnnotations(ctx, annotations...)\n\t}\n\tif !result.Allowed {\n\t\t// start with a generic forbidden error\n\t\tretval := admission.NewForbidden(a, errors.New(\"Not allowed by PodSecurity\")).(*apierrors.StatusError)\n\t\t// use message/reason/details/code from admission library if populated\n\t\tif result.Result != nil {\n\t\t\tif len(result.Result.Message) \u003e 0 {\n\t\t\t\tretval.ErrStatus.Message = result.Result.Message\n\t\t\t}\n\t\t\tif len(result.Result.Reason) \u003e 0 {\n\t\t\t\tretval.ErrStatus.Reason = result.Result.Reason\n\t\t\t}\n\t\t\tif result.Result.Details != nil {\n\t\t\t\tretval.ErrStatus.Details = result.Result.Details\n\t\t\t}\n\t\t\tif result.Result.Code != 0 {\n\t\t\t\tretval.ErrStatus.Code = result.Result.Code\n\t\t\t}\n\t\t}\n\t\treturn retval\n\t}\n\treturn nil\n}","line":{"from":177,"to":217}} {"id":100013556,"name":"GetObject","signature":"func (l *lazyConvertingAttributes) GetObject() (runtime.Object, error)","file":"plugin/pkg/admission/security/podsecurity/admission.go","code":"func (l *lazyConvertingAttributes) GetObject() (runtime.Object, error) {\n\tl.convertObjectOnce.Do(func() {\n\t\tl.convertedObject, l.convertedObjectError = convert(l.Attributes.GetObject())\n\t})\n\treturn l.convertedObject, l.convertedObjectError\n}","line":{"from":231,"to":236}} {"id":100013557,"name":"GetOldObject","signature":"func (l *lazyConvertingAttributes) GetOldObject() (runtime.Object, error)","file":"plugin/pkg/admission/security/podsecurity/admission.go","code":"func (l *lazyConvertingAttributes) GetOldObject() (runtime.Object, error) {\n\tl.convertOldObjectOnce.Do(func() {\n\t\tl.convertedOldObject, l.convertedOldObjectError = convert(l.Attributes.GetOldObject())\n\t})\n\treturn l.convertedOldObject, l.convertedOldObjectError\n}","line":{"from":238,"to":243}} {"id":100013558,"name":"GetOperation","signature":"func (l *lazyConvertingAttributes) GetOperation() admissionv1.Operation","file":"plugin/pkg/admission/security/podsecurity/admission.go","code":"func (l *lazyConvertingAttributes) GetOperation() admissionv1.Operation {\n\treturn admissionv1.Operation(l.Attributes.GetOperation())\n}","line":{"from":245,"to":247}} {"id":100013559,"name":"GetUserName","signature":"func (l *lazyConvertingAttributes) GetUserName() string","file":"plugin/pkg/admission/security/podsecurity/admission.go","code":"func (l *lazyConvertingAttributes) GetUserName() string {\n\treturn l.GetUserInfo().GetName()\n}","line":{"from":249,"to":251}} {"id":100013560,"name":"convert","signature":"func convert(in runtime.Object) (runtime.Object, error)","file":"plugin/pkg/admission/security/podsecurity/admission.go","code":"func convert(in runtime.Object) (runtime.Object, error) {\n\tvar out runtime.Object\n\tswitch in.(type) {\n\tcase *core.Namespace:\n\t\tout = \u0026corev1.Namespace{}\n\tcase *core.Pod:\n\t\tout = \u0026corev1.Pod{}\n\tcase *core.ReplicationController:\n\t\tout = \u0026corev1.ReplicationController{}\n\tcase *core.PodTemplate:\n\t\tout = \u0026corev1.PodTemplate{}\n\tcase *apps.ReplicaSet:\n\t\tout = \u0026appsv1.ReplicaSet{}\n\tcase *apps.Deployment:\n\t\tout = \u0026appsv1.Deployment{}\n\tcase *apps.StatefulSet:\n\t\tout = \u0026appsv1.StatefulSet{}\n\tcase *apps.DaemonSet:\n\t\tout = \u0026appsv1.DaemonSet{}\n\tcase *batch.Job:\n\t\tout = \u0026batchv1.Job{}\n\tcase *batch.CronJob:\n\t\tout = \u0026batchv1.CronJob{}\n\tdefault:\n\t\treturn in, fmt.Errorf(\"unexpected type %T\", in)\n\t}\n\tif err := legacyscheme.Scheme.Convert(in, out, nil); err != nil {\n\t\treturn in, err\n\t}\n\treturn out, nil\n}","line":{"from":253,"to":283}} {"id":100013561,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/securitycontext/scdeny/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.SecurityContextDeny) {\n\t\t\treturn NewSecurityContextDeny(), nil\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"%s admission controller is an alpha feature, planned to be removed, and requires the SecurityContextDeny feature gate to be enabled, see %s for more information\", PluginName, docLink)\n\t\t}\n\t})\n}","line":{"from":37,"to":46}} {"id":100013562,"name":"NewSecurityContextDeny","signature":"func NewSecurityContextDeny() *Plugin","file":"plugin/pkg/admission/securitycontext/scdeny/admission.go","code":"// NewSecurityContextDeny creates a new instance of the SecurityContextDeny admission controller\nfunc NewSecurityContextDeny() *Plugin {\n\t// DEPRECATED: SecurityContextDeny will be removed in favor of PodSecurity admission.\n\tklog.Warningf(\"%s admission controller is deprecated. \"+\n\t\t\"Please remove this controller from your configuration files and scripts. \"+\n\t\t\"See %s for more information.\",\n\t\tPluginName, docLink)\n\treturn \u0026Plugin{\n\t\tHandler: admission.NewHandler(admission.Create, admission.Update),\n\t}\n}","line":{"from":55,"to":65}} {"id":100013563,"name":"Validate","signature":"func (p *Plugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error)","file":"plugin/pkg/admission/securitycontext/scdeny/admission.go","code":"// Validate will deny any pod that defines SupplementalGroups, SELinuxOptions, RunAsUser or FSGroup\nfunc (p *Plugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {\n\tif a.GetSubresource() != \"\" || a.GetResource().GroupResource() != api.Resource(\"pods\") {\n\t\treturn nil\n\t}\n\n\tpod, ok := a.GetObject().(*api.Pod)\n\tif !ok {\n\t\treturn apierrors.NewBadRequest(\"Resource was marked with kind Pod but was unable to be converted\")\n\t}\n\n\tif pod.Spec.SecurityContext != nil {\n\t\tif pod.Spec.SecurityContext.SupplementalGroups != nil {\n\t\t\treturn apierrors.NewForbidden(a.GetResource().GroupResource(), pod.Name, fmt.Errorf(\"pod.Spec.SecurityContext.SupplementalGroups is forbidden\"))\n\t\t}\n\t\tif pod.Spec.SecurityContext.SELinuxOptions != nil {\n\t\t\treturn apierrors.NewForbidden(a.GetResource().GroupResource(), pod.Name, fmt.Errorf(\"pod.Spec.SecurityContext.SELinuxOptions is forbidden\"))\n\t\t}\n\t\tif pod.Spec.SecurityContext.RunAsUser != nil {\n\t\t\treturn apierrors.NewForbidden(a.GetResource().GroupResource(), pod.Name, fmt.Errorf(\"pod.Spec.SecurityContext.RunAsUser is forbidden\"))\n\t\t}\n\t\tif pod.Spec.SecurityContext.FSGroup != nil {\n\t\t\treturn apierrors.NewForbidden(a.GetResource().GroupResource(), pod.Name, fmt.Errorf(\"pod.Spec.SecurityContext.FSGroup is forbidden\"))\n\t\t}\n\t}\n\n\tfor _, v := range pod.Spec.InitContainers {\n\t\tif v.SecurityContext != nil {\n\t\t\tif v.SecurityContext.SELinuxOptions != nil {\n\t\t\t\treturn apierrors.NewForbidden(a.GetResource().GroupResource(), pod.Name, fmt.Errorf(\"SecurityContext.SELinuxOptions is forbidden\"))\n\t\t\t}\n\t\t\tif v.SecurityContext.RunAsUser != nil {\n\t\t\t\treturn apierrors.NewForbidden(a.GetResource().GroupResource(), pod.Name, fmt.Errorf(\"SecurityContext.RunAsUser is forbidden\"))\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, v := range pod.Spec.Containers {\n\t\tif v.SecurityContext != nil {\n\t\t\tif v.SecurityContext.SELinuxOptions != nil {\n\t\t\t\treturn apierrors.NewForbidden(a.GetResource().GroupResource(), pod.Name, fmt.Errorf(\"SecurityContext.SELinuxOptions is forbidden\"))\n\t\t\t}\n\t\t\tif v.SecurityContext.RunAsUser != nil {\n\t\t\t\treturn apierrors.NewForbidden(a.GetResource().GroupResource(), pod.Name, fmt.Errorf(\"SecurityContext.RunAsUser is forbidden\"))\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":67,"to":115}} {"id":100013564,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/serviceaccount/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\tserviceAccountAdmission := NewServiceAccount()\n\t\treturn serviceAccountAdmission, nil\n\t})\n}","line":{"from":63,"to":69}} {"id":100013565,"name":"NewServiceAccount","signature":"func NewServiceAccount() *Plugin","file":"plugin/pkg/admission/serviceaccount/admission.go","code":"// NewServiceAccount returns an admission.Interface implementation which limits admission of Pod CREATE requests based on the pod's ServiceAccount:\n// 1. If the pod does not specify a ServiceAccount, it sets the pod's ServiceAccount to \"default\"\n// 2. It ensures the ServiceAccount referenced by the pod exists\n// 3. If LimitSecretReferences is true, it rejects the pod if the pod references Secret objects which the pod's ServiceAccount does not reference\n// 4. If the pod does not contain any ImagePullSecrets, the ImagePullSecrets of the service account are added.\n// 5. If MountServiceAccountToken is true, it adds a VolumeMount with the pod's ServiceAccount's api token secret to containers\nfunc NewServiceAccount() *Plugin {\n\treturn \u0026Plugin{\n\t\tHandler: admission.NewHandler(admission.Create, admission.Update),\n\t\t// TODO: enable this once we've swept secret usage to account for adding secret references to service accounts\n\t\tLimitSecretReferences: false,\n\t\t// Auto mount service account API token secrets\n\t\tMountServiceAccountToken: true,\n\n\t\tgenerateName: names.SimpleNameGenerator.GenerateName,\n\t}\n}","line":{"from":94,"to":110}} {"id":100013566,"name":"SetExternalKubeClientSet","signature":"func (s *Plugin) SetExternalKubeClientSet(cl kubernetes.Interface)","file":"plugin/pkg/admission/serviceaccount/admission.go","code":"// SetExternalKubeClientSet sets the client for the plugin\nfunc (s *Plugin) SetExternalKubeClientSet(cl kubernetes.Interface) {\n\ts.client = cl\n}","line":{"from":112,"to":115}} {"id":100013567,"name":"SetExternalKubeInformerFactory","signature":"func (s *Plugin) SetExternalKubeInformerFactory(f informers.SharedInformerFactory)","file":"plugin/pkg/admission/serviceaccount/admission.go","code":"// SetExternalKubeInformerFactory registers informers with the plugin\nfunc (s *Plugin) SetExternalKubeInformerFactory(f informers.SharedInformerFactory) {\n\tserviceAccountInformer := f.Core().V1().ServiceAccounts()\n\ts.serviceAccountLister = serviceAccountInformer.Lister()\n\ts.SetReadyFunc(func() bool {\n\t\treturn serviceAccountInformer.Informer().HasSynced()\n\t})\n}","line":{"from":117,"to":124}} {"id":100013568,"name":"ValidateInitialization","signature":"func (s *Plugin) ValidateInitialization() error","file":"plugin/pkg/admission/serviceaccount/admission.go","code":"// ValidateInitialization ensures an authorizer is set.\nfunc (s *Plugin) ValidateInitialization() error {\n\tif s.client == nil {\n\t\treturn fmt.Errorf(\"missing client\")\n\t}\n\tif s.serviceAccountLister == nil {\n\t\treturn fmt.Errorf(\"missing serviceAccountLister\")\n\t}\n\treturn nil\n}","line":{"from":126,"to":135}} {"id":100013569,"name":"Admit","signature":"func (s *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error)","file":"plugin/pkg/admission/serviceaccount/admission.go","code":"// Admit verifies if the pod should be admitted\nfunc (s *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {\n\tif shouldIgnore(a) {\n\t\treturn nil\n\t}\n\tif a.GetOperation() != admission.Create {\n\t\t// we only mutate pods during create requests\n\t\treturn nil\n\t}\n\tpod := a.GetObject().(*api.Pod)\n\n\t// Don't modify the spec of mirror pods.\n\t// That makes the kubelet very angry and confused, and it immediately deletes the pod (because the spec doesn't match)\n\t// That said, don't allow mirror pods to reference ServiceAccounts or SecretVolumeSources either\n\tif _, isMirrorPod := pod.Annotations[api.MirrorPodAnnotationKey]; isMirrorPod {\n\t\treturn s.Validate(ctx, a, o)\n\t}\n\n\t// Set the default service account if needed\n\tif len(pod.Spec.ServiceAccountName) == 0 {\n\t\tpod.Spec.ServiceAccountName = DefaultServiceAccountName\n\t}\n\n\tserviceAccount, err := s.getServiceAccount(a.GetNamespace(), pod.Spec.ServiceAccountName)\n\tif err != nil {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"error looking up service account %s/%s: %w\", a.GetNamespace(), pod.Spec.ServiceAccountName, err))\n\t}\n\tif s.MountServiceAccountToken \u0026\u0026 shouldAutomount(serviceAccount, pod) {\n\t\ts.mountServiceAccountToken(serviceAccount, pod)\n\t}\n\tif len(pod.Spec.ImagePullSecrets) == 0 {\n\t\tpod.Spec.ImagePullSecrets = make([]api.LocalObjectReference, len(serviceAccount.ImagePullSecrets))\n\t\tfor i := 0; i \u003c len(serviceAccount.ImagePullSecrets); i++ {\n\t\t\tpod.Spec.ImagePullSecrets[i].Name = serviceAccount.ImagePullSecrets[i].Name\n\t\t}\n\t}\n\n\treturn s.Validate(ctx, a, o)\n}","line":{"from":137,"to":175}} {"id":100013570,"name":"Validate","signature":"func (s *Plugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error)","file":"plugin/pkg/admission/serviceaccount/admission.go","code":"// Validate the data we obtained\nfunc (s *Plugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {\n\tif shouldIgnore(a) {\n\t\treturn nil\n\t}\n\n\tpod := a.GetObject().(*api.Pod)\n\n\tif a.GetOperation() == admission.Update \u0026\u0026 a.GetSubresource() == \"ephemeralcontainers\" {\n\t\treturn s.limitEphemeralContainerSecretReferences(pod, a)\n\t}\n\n\tif a.GetOperation() != admission.Create {\n\t\t// we only validate pod specs during create requests\n\t\treturn nil\n\t}\n\n\t// Mirror pods have restrictions on what they can reference\n\tif _, isMirrorPod := pod.Annotations[api.MirrorPodAnnotationKey]; isMirrorPod {\n\t\tif len(pod.Spec.ServiceAccountName) != 0 {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"a mirror pod may not reference service accounts\"))\n\t\t}\n\t\thasSecrets := false\n\t\tpodutil.VisitPodSecretNames(pod, func(name string) bool {\n\t\t\thasSecrets = true\n\t\t\treturn false\n\t\t}, podutil.AllContainers)\n\t\tif hasSecrets {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"a mirror pod may not reference secrets\"))\n\t\t}\n\t\tfor _, v := range pod.Spec.Volumes {\n\t\t\tif proj := v.Projected; proj != nil {\n\t\t\t\tfor _, projSource := range proj.Sources {\n\t\t\t\t\tif projSource.ServiceAccountToken != nil {\n\t\t\t\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"a mirror pod may not use ServiceAccountToken volume projections\"))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\t// Require container pods to have service accounts\n\tif len(pod.Spec.ServiceAccountName) == 0 {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"no service account specified for pod %s/%s\", a.GetNamespace(), pod.Name))\n\t}\n\t// Ensure the referenced service account exists\n\tserviceAccount, err := s.getServiceAccount(a.GetNamespace(), pod.Spec.ServiceAccountName)\n\tif err != nil {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"error looking up service account %s/%s: %v\", a.GetNamespace(), pod.Spec.ServiceAccountName, err))\n\t}\n\n\tif s.enforceMountableSecrets(serviceAccount) {\n\t\tif err := s.limitSecretReferences(serviceAccount, pod); err != nil {\n\t\t\treturn admission.NewForbidden(a, err)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":177,"to":236}} {"id":100013571,"name":"shouldIgnore","signature":"func shouldIgnore(a admission.Attributes) bool","file":"plugin/pkg/admission/serviceaccount/admission.go","code":"func shouldIgnore(a admission.Attributes) bool {\n\tif a.GetResource().GroupResource() != api.Resource(\"pods\") || (a.GetSubresource() != \"\" \u0026\u0026 a.GetSubresource() != \"ephemeralcontainers\") {\n\t\treturn true\n\t}\n\tobj := a.GetObject()\n\tif obj == nil {\n\t\treturn true\n\t}\n\t_, ok := obj.(*api.Pod)\n\tif !ok {\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":238,"to":252}} {"id":100013572,"name":"shouldAutomount","signature":"func shouldAutomount(sa *corev1.ServiceAccount, pod *api.Pod) bool","file":"plugin/pkg/admission/serviceaccount/admission.go","code":"func shouldAutomount(sa *corev1.ServiceAccount, pod *api.Pod) bool {\n\t// Pod's preference wins\n\tif pod.Spec.AutomountServiceAccountToken != nil {\n\t\treturn *pod.Spec.AutomountServiceAccountToken\n\t}\n\t// Then service account's\n\tif sa.AutomountServiceAccountToken != nil {\n\t\treturn *sa.AutomountServiceAccountToken\n\t}\n\t// Default to true for backwards compatibility\n\treturn true\n}","line":{"from":254,"to":265}} {"id":100013573,"name":"enforceMountableSecrets","signature":"func (s *Plugin) enforceMountableSecrets(serviceAccount *corev1.ServiceAccount) bool","file":"plugin/pkg/admission/serviceaccount/admission.go","code":"// enforceMountableSecrets indicates whether mountable secrets should be enforced for a particular service account\n// A global setting of true will override any flag set on the individual service account\nfunc (s *Plugin) enforceMountableSecrets(serviceAccount *corev1.ServiceAccount) bool {\n\tif s.LimitSecretReferences {\n\t\treturn true\n\t}\n\n\tif value, ok := serviceAccount.Annotations[EnforceMountableSecretsAnnotation]; ok {\n\t\tenforceMountableSecretCheck, _ := strconv.ParseBool(value)\n\t\treturn enforceMountableSecretCheck\n\t}\n\n\treturn false\n}","line":{"from":267,"to":280}} {"id":100013574,"name":"getServiceAccount","signature":"func (s *Plugin) getServiceAccount(namespace string, name string) (*corev1.ServiceAccount, error)","file":"plugin/pkg/admission/serviceaccount/admission.go","code":"// getServiceAccount returns the ServiceAccount for the given namespace and name if it exists\nfunc (s *Plugin) getServiceAccount(namespace string, name string) (*corev1.ServiceAccount, error) {\n\tserviceAccount, err := s.serviceAccountLister.ServiceAccounts(namespace).Get(name)\n\tif err == nil {\n\t\treturn serviceAccount, nil\n\t}\n\tif !errors.IsNotFound(err) {\n\t\treturn nil, err\n\t}\n\n\t// Could not find in cache, attempt to look up directly\n\tnumAttempts := 1\n\tif name == DefaultServiceAccountName {\n\t\t// If this is the default serviceaccount, attempt more times, since it should be auto-created by the controller\n\t\tnumAttempts = 10\n\t}\n\tretryInterval := time.Duration(rand.Int63n(100)+int64(100)) * time.Millisecond\n\tfor i := 0; i \u003c numAttempts; i++ {\n\t\tif i != 0 {\n\t\t\ttime.Sleep(retryInterval)\n\t\t}\n\t\tserviceAccount, err := s.client.CoreV1().ServiceAccounts(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\t\tif err == nil {\n\t\t\treturn serviceAccount, nil\n\t\t}\n\t\tif !errors.IsNotFound(err) {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn nil, errors.NewNotFound(api.Resource(\"serviceaccount\"), name)\n}","line":{"from":282,"to":313}} {"id":100013575,"name":"limitSecretReferences","signature":"func (s *Plugin) limitSecretReferences(serviceAccount *corev1.ServiceAccount, pod *api.Pod) error","file":"plugin/pkg/admission/serviceaccount/admission.go","code":"func (s *Plugin) limitSecretReferences(serviceAccount *corev1.ServiceAccount, pod *api.Pod) error {\n\t// Ensure all secrets the pod references are allowed by the service account\n\tmountableSecrets := sets.NewString()\n\tfor _, s := range serviceAccount.Secrets {\n\t\tmountableSecrets.Insert(s.Name)\n\t}\n\tfor _, volume := range pod.Spec.Volumes {\n\t\tsource := volume.VolumeSource\n\t\tif source.Secret == nil {\n\t\t\tcontinue\n\t\t}\n\t\tsecretName := source.Secret.SecretName\n\t\tif !mountableSecrets.Has(secretName) {\n\t\t\treturn fmt.Errorf(\"volume with secret.secretName=\\\"%s\\\" is not allowed because service account %s does not reference that secret\", secretName, serviceAccount.Name)\n\t\t}\n\t}\n\n\tfor _, container := range pod.Spec.InitContainers {\n\t\tfor _, env := range container.Env {\n\t\t\tif env.ValueFrom != nil \u0026\u0026 env.ValueFrom.SecretKeyRef != nil {\n\t\t\t\tif !mountableSecrets.Has(env.ValueFrom.SecretKeyRef.Name) {\n\t\t\t\t\treturn fmt.Errorf(\"init container %s with envVar %s referencing secret.secretName=\\\"%s\\\" is not allowed because service account %s does not reference that secret\", container.Name, env.Name, env.ValueFrom.SecretKeyRef.Name, serviceAccount.Name)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, container := range pod.Spec.Containers {\n\t\tfor _, env := range container.Env {\n\t\t\tif env.ValueFrom != nil \u0026\u0026 env.ValueFrom.SecretKeyRef != nil {\n\t\t\t\tif !mountableSecrets.Has(env.ValueFrom.SecretKeyRef.Name) {\n\t\t\t\t\treturn fmt.Errorf(\"container %s with envVar %s referencing secret.secretName=\\\"%s\\\" is not allowed because service account %s does not reference that secret\", container.Name, env.Name, env.ValueFrom.SecretKeyRef.Name, serviceAccount.Name)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// limit pull secret references as well\n\tpullSecrets := sets.NewString()\n\tfor _, s := range serviceAccount.ImagePullSecrets {\n\t\tpullSecrets.Insert(s.Name)\n\t}\n\tfor i, pullSecretRef := range pod.Spec.ImagePullSecrets {\n\t\tif !pullSecrets.Has(pullSecretRef.Name) {\n\t\t\treturn fmt.Errorf(`imagePullSecrets[%d].name=\"%s\" is not allowed because service account %s does not reference that imagePullSecret`, i, pullSecretRef.Name, serviceAccount.Name)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":315,"to":363}} {"id":100013576,"name":"limitEphemeralContainerSecretReferences","signature":"func (s *Plugin) limitEphemeralContainerSecretReferences(pod *api.Pod, a admission.Attributes) error","file":"plugin/pkg/admission/serviceaccount/admission.go","code":"func (s *Plugin) limitEphemeralContainerSecretReferences(pod *api.Pod, a admission.Attributes) error {\n\t// Require ephemeral container pods to have service accounts\n\tif len(pod.Spec.ServiceAccountName) == 0 {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"no service account specified for pod %s/%s\", a.GetNamespace(), pod.Name))\n\t}\n\t// Ensure the referenced service account exists\n\tserviceAccount, err := s.getServiceAccount(a.GetNamespace(), pod.Spec.ServiceAccountName)\n\tif err != nil {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"error looking up service account %s/%s: %w\", a.GetNamespace(), pod.Spec.ServiceAccountName, err))\n\t}\n\tif !s.enforceMountableSecrets(serviceAccount) {\n\t\treturn nil\n\t}\n\t// Ensure all secrets the ephemeral containers reference are allowed by the service account\n\tmountableSecrets := sets.NewString()\n\tfor _, s := range serviceAccount.Secrets {\n\t\tmountableSecrets.Insert(s.Name)\n\t}\n\tfor _, container := range pod.Spec.EphemeralContainers {\n\t\tfor _, env := range container.Env {\n\t\t\tif env.ValueFrom != nil \u0026\u0026 env.ValueFrom.SecretKeyRef != nil {\n\t\t\t\tif !mountableSecrets.Has(env.ValueFrom.SecretKeyRef.Name) {\n\t\t\t\t\treturn fmt.Errorf(\"ephemeral container %s with envVar %s referencing secret.secretName=\\\"%s\\\" is not allowed because service account %s does not reference that secret\", container.Name, env.Name, env.ValueFrom.SecretKeyRef.Name, serviceAccount.Name)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":365,"to":393}} {"id":100013577,"name":"mountServiceAccountToken","signature":"func (s *Plugin) mountServiceAccountToken(serviceAccount *corev1.ServiceAccount, pod *api.Pod)","file":"plugin/pkg/admission/serviceaccount/admission.go","code":"func (s *Plugin) mountServiceAccountToken(serviceAccount *corev1.ServiceAccount, pod *api.Pod) {\n\t// Find the volume and volume name for the ServiceAccountTokenSecret if it already exists\n\ttokenVolumeName := \"\"\n\thasTokenVolume := false\n\tallVolumeNames := sets.NewString()\n\tfor _, volume := range pod.Spec.Volumes {\n\t\tallVolumeNames.Insert(volume.Name)\n\t\tif strings.HasPrefix(volume.Name, ServiceAccountVolumeName+\"-\") {\n\t\t\ttokenVolumeName = volume.Name\n\t\t\thasTokenVolume = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Determine a volume name for the ServiceAccountTokenSecret in case we need it\n\tif len(tokenVolumeName) == 0 {\n\t\ttokenVolumeName = s.generateName(ServiceAccountVolumeName + \"-\")\n\t}\n\n\t// Create the prototypical VolumeMount\n\tvolumeMount := api.VolumeMount{\n\t\tName: tokenVolumeName,\n\t\tReadOnly: true,\n\t\tMountPath: DefaultAPITokenMountPath,\n\t}\n\n\t// Ensure every container mounts the APISecret volume\n\tneedsTokenVolume := false\n\tfor i, container := range pod.Spec.InitContainers {\n\t\texistingContainerMount := false\n\t\tfor _, volumeMount := range container.VolumeMounts {\n\t\t\t// Existing mounts at the default mount path prevent mounting of the API token\n\t\t\tif volumeMount.MountPath == DefaultAPITokenMountPath {\n\t\t\t\texistingContainerMount = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !existingContainerMount {\n\t\t\tpod.Spec.InitContainers[i].VolumeMounts = append(pod.Spec.InitContainers[i].VolumeMounts, volumeMount)\n\t\t\tneedsTokenVolume = true\n\t\t}\n\t}\n\tfor i, container := range pod.Spec.Containers {\n\t\texistingContainerMount := false\n\t\tfor _, volumeMount := range container.VolumeMounts {\n\t\t\t// Existing mounts at the default mount path prevent mounting of the API token\n\t\t\tif volumeMount.MountPath == DefaultAPITokenMountPath {\n\t\t\t\texistingContainerMount = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !existingContainerMount {\n\t\t\tpod.Spec.Containers[i].VolumeMounts = append(pod.Spec.Containers[i].VolumeMounts, volumeMount)\n\t\t\tneedsTokenVolume = true\n\t\t}\n\t}\n\n\t// Add the volume if a container needs it\n\tif !hasTokenVolume \u0026\u0026 needsTokenVolume {\n\t\tpod.Spec.Volumes = append(pod.Spec.Volumes, api.Volume{\n\t\t\tName: tokenVolumeName,\n\t\t\tVolumeSource: api.VolumeSource{\n\t\t\t\tProjected: TokenVolumeSource(),\n\t\t\t},\n\t\t})\n\t}\n}","line":{"from":395,"to":461}} {"id":100013578,"name":"TokenVolumeSource","signature":"func TokenVolumeSource() *api.ProjectedVolumeSource","file":"plugin/pkg/admission/serviceaccount/admission.go","code":"// TokenVolumeSource returns the projected volume source for service account token.\nfunc TokenVolumeSource() *api.ProjectedVolumeSource {\n\treturn \u0026api.ProjectedVolumeSource{\n\t\t// explicitly set default value, see #104464\n\t\tDefaultMode: pointer.Int32(corev1.ProjectedVolumeSourceDefaultMode),\n\t\tSources: []api.VolumeProjection{\n\t\t\t{\n\t\t\t\tServiceAccountToken: \u0026api.ServiceAccountTokenProjection{\n\t\t\t\t\tPath: \"token\",\n\t\t\t\t\tExpirationSeconds: serviceaccount.WarnOnlyBoundTokenExpirationSeconds,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tConfigMap: \u0026api.ConfigMapProjection{\n\t\t\t\t\tLocalObjectReference: api.LocalObjectReference{\n\t\t\t\t\t\tName: \"kube-root-ca.crt\",\n\t\t\t\t\t},\n\t\t\t\t\tItems: []api.KeyToPath{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tKey: \"ca.crt\",\n\t\t\t\t\t\t\tPath: \"ca.crt\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tDownwardAPI: \u0026api.DownwardAPIProjection{\n\t\t\t\t\tItems: []api.DownwardAPIVolumeFile{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tPath: \"namespace\",\n\t\t\t\t\t\t\tFieldRef: \u0026api.ObjectFieldSelector{\n\t\t\t\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t\t\t\t\tFieldPath: \"metadata.namespace\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":463,"to":503}} {"id":100013579,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/storage/persistentvolume/label/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\tpersistentVolumeLabelAdmission := newPersistentVolumeLabel()\n\t\treturn persistentVolumeLabelAdmission, nil\n\t})\n}","line":{"from":45,"to":51}} {"id":100013580,"name":"newPersistentVolumeLabel","signature":"func newPersistentVolumeLabel() *persistentVolumeLabel","file":"plugin/pkg/admission/storage/persistentvolume/label/admission.go","code":"// newPersistentVolumeLabel returns an admission.Interface implementation which adds labels to PersistentVolume CREATE requests,\n// based on the labels provided by the underlying cloud provider.\n//\n// As a side effect, the cloud provider may block invalid or non-existent volumes.\nfunc newPersistentVolumeLabel() *persistentVolumeLabel {\n\t// DEPRECATED: in a future release, we will use mutating admission webhooks to apply PV labels.\n\t// Once the mutating admission webhook is used for Azure, and GCE,\n\t// this admission controller will be removed.\n\tklog.Warning(\"PersistentVolumeLabel admission controller is deprecated. \" +\n\t\t\"Please remove this controller from your configuration files and scripts.\")\n\treturn \u0026persistentVolumeLabel{\n\t\tHandler: admission.NewHandler(admission.Create),\n\t}\n}","line":{"from":68,"to":81}} {"id":100013581,"name":"SetCloudConfig","signature":"func (l *persistentVolumeLabel) SetCloudConfig(cloudConfig []byte)","file":"plugin/pkg/admission/storage/persistentvolume/label/admission.go","code":"func (l *persistentVolumeLabel) SetCloudConfig(cloudConfig []byte) {\n\tl.cloudConfig = cloudConfig\n}","line":{"from":83,"to":85}} {"id":100013582,"name":"nodeSelectorRequirementKeysExistInNodeSelectorTerms","signature":"func nodeSelectorRequirementKeysExistInNodeSelectorTerms(reqs []api.NodeSelectorRequirement, terms []api.NodeSelectorTerm) bool","file":"plugin/pkg/admission/storage/persistentvolume/label/admission.go","code":"func nodeSelectorRequirementKeysExistInNodeSelectorTerms(reqs []api.NodeSelectorRequirement, terms []api.NodeSelectorTerm) bool {\n\tfor _, req := range reqs {\n\t\tfor _, term := range terms {\n\t\t\tfor _, r := range term.MatchExpressions {\n\t\t\t\tif r.Key == req.Key {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":87,"to":98}} {"id":100013583,"name":"Admit","signature":"func (l *persistentVolumeLabel) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error)","file":"plugin/pkg/admission/storage/persistentvolume/label/admission.go","code":"func (l *persistentVolumeLabel) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {\n\tif a.GetResource().GroupResource() != api.Resource(\"persistentvolumes\") {\n\t\treturn nil\n\t}\n\tobj := a.GetObject()\n\tif obj == nil {\n\t\treturn nil\n\t}\n\tvolume, ok := obj.(*api.PersistentVolume)\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tvolumeLabels, err := l.findVolumeLabels(volume)\n\tif err != nil {\n\t\treturn admission.NewForbidden(a, err)\n\t}\n\n\trequirements := make([]api.NodeSelectorRequirement, 0)\n\tif len(volumeLabels) != 0 {\n\t\tif volume.Labels == nil {\n\t\t\tvolume.Labels = make(map[string]string)\n\t\t}\n\t\tfor k, v := range volumeLabels {\n\t\t\t// We (silently) replace labels if they are provided.\n\t\t\t// This should be OK because they are in the kubernetes.io namespace\n\t\t\t// i.e. we own them\n\t\t\tvolume.Labels[k] = v\n\n\t\t\t// Set NodeSelectorRequirements based on the labels\n\t\t\tvar values []string\n\t\t\tif k == v1.LabelTopologyZone || k == v1.LabelFailureDomainBetaZone {\n\t\t\t\tzones, err := volumehelpers.LabelZonesToSet(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"failed to convert label string for Zone: %s to a Set\", v))\n\t\t\t\t}\n\t\t\t\t// zone values here are sorted for better testability.\n\t\t\t\tvalues = zones.List()\n\t\t\t} else {\n\t\t\t\tvalues = []string{v}\n\t\t\t}\n\t\t\trequirements = append(requirements, api.NodeSelectorRequirement{Key: k, Operator: api.NodeSelectorOpIn, Values: values})\n\t\t}\n\n\t\tif volume.Spec.NodeAffinity == nil {\n\t\t\tvolume.Spec.NodeAffinity = new(api.VolumeNodeAffinity)\n\t\t}\n\t\tif volume.Spec.NodeAffinity.Required == nil {\n\t\t\tvolume.Spec.NodeAffinity.Required = new(api.NodeSelector)\n\t\t}\n\t\tif len(volume.Spec.NodeAffinity.Required.NodeSelectorTerms) == 0 {\n\t\t\t// Need at least one term pre-allocated whose MatchExpressions can be appended to\n\t\t\tvolume.Spec.NodeAffinity.Required.NodeSelectorTerms = make([]api.NodeSelectorTerm, 1)\n\t\t}\n\t\tif nodeSelectorRequirementKeysExistInNodeSelectorTerms(requirements, volume.Spec.NodeAffinity.Required.NodeSelectorTerms) {\n\t\t\tklog.V(4).Infof(\"NodeSelectorRequirements for cloud labels %v conflict with existing NodeAffinity %v. Skipping addition of NodeSelectorRequirements for cloud labels.\",\n\t\t\t\trequirements, volume.Spec.NodeAffinity)\n\t\t} else {\n\t\t\tfor _, req := range requirements {\n\t\t\t\tfor i := range volume.Spec.NodeAffinity.Required.NodeSelectorTerms {\n\t\t\t\t\tvolume.Spec.NodeAffinity.Required.NodeSelectorTerms[i].MatchExpressions = append(volume.Spec.NodeAffinity.Required.NodeSelectorTerms[i].MatchExpressions, req)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":100,"to":167}} {"id":100013584,"name":"findVolumeLabels","signature":"func (l *persistentVolumeLabel) findVolumeLabels(volume *api.PersistentVolume) (map[string]string, error)","file":"plugin/pkg/admission/storage/persistentvolume/label/admission.go","code":"func (l *persistentVolumeLabel) findVolumeLabels(volume *api.PersistentVolume) (map[string]string, error) {\n\texistingLabels := volume.Labels\n\n\t// All cloud providers set only these two labels.\n\ttopologyLabelGA := true\n\tdomain, domainOK := existingLabels[v1.LabelTopologyZone]\n\tregion, regionOK := existingLabels[v1.LabelTopologyRegion]\n\t// If they don't have GA labels we should check for failuredomain beta labels\n\t// TODO: remove this once all the cloud provider change to GA topology labels\n\tif !domainOK || !regionOK {\n\t\ttopologyLabelGA = false\n\t\tdomain, domainOK = existingLabels[v1.LabelFailureDomainBetaZone]\n\t\tregion, regionOK = existingLabels[v1.LabelFailureDomainBetaRegion]\n\t}\n\n\tisDynamicallyProvisioned := metav1.HasAnnotation(volume.ObjectMeta, persistentvolume.AnnDynamicallyProvisioned)\n\tif isDynamicallyProvisioned \u0026\u0026 domainOK \u0026\u0026 regionOK {\n\t\t// PV already has all the labels and we can trust the dynamic provisioning that it provided correct values.\n\t\tif topologyLabelGA {\n\t\t\treturn map[string]string{\n\t\t\t\tv1.LabelTopologyZone: domain,\n\t\t\t\tv1.LabelTopologyRegion: region,\n\t\t\t}, nil\n\t\t}\n\t\treturn map[string]string{\n\t\t\tv1.LabelFailureDomainBetaZone: domain,\n\t\t\tv1.LabelFailureDomainBetaRegion: region,\n\t\t}, nil\n\n\t}\n\n\t// Either missing labels or we don't trust the user provided correct values.\n\tswitch {\n\tcase volume.Spec.GCEPersistentDisk != nil:\n\t\tlabels, err := l.findGCEPDLabels(volume)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error querying GCE PD volume %s: %v\", volume.Spec.GCEPersistentDisk.PDName, err)\n\t\t}\n\t\treturn labels, nil\n\tcase volume.Spec.AzureDisk != nil:\n\t\tlabels, err := l.findAzureDiskLabels(volume)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error querying AzureDisk volume %s: %v\", volume.Spec.AzureDisk.DiskName, err)\n\t\t}\n\t\treturn labels, nil\n\tcase volume.Spec.VsphereVolume != nil:\n\t\tlabels, err := l.findVsphereVolumeLabels(volume)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error querying vSphere Volume %s: %v\", volume.Spec.VsphereVolume.VolumePath, err)\n\t\t}\n\t\treturn labels, nil\n\t}\n\t// Unrecognized volume, do not add any labels\n\treturn nil, nil\n}","line":{"from":169,"to":223}} {"id":100013585,"name":"findGCEPDLabels","signature":"func (l *persistentVolumeLabel) findGCEPDLabels(volume *api.PersistentVolume) (map[string]string, error)","file":"plugin/pkg/admission/storage/persistentvolume/label/admission.go","code":"func (l *persistentVolumeLabel) findGCEPDLabels(volume *api.PersistentVolume) (map[string]string, error) {\n\t// Ignore any volumes that are being provisioned\n\tif volume.Spec.GCEPersistentDisk.PDName == cloudvolume.ProvisionedVolumeName {\n\t\treturn nil, nil\n\t}\n\n\tpvlabler, err := l.getGCEPVLabeler()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif pvlabler == nil {\n\t\treturn nil, fmt.Errorf(\"unable to build GCE cloud provider for PD\")\n\t}\n\n\tpv := \u0026v1.PersistentVolume{}\n\terr = k8s_api_v1.Convert_core_PersistentVolume_To_v1_PersistentVolume(volume, pv, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to convert PersistentVolume to core/v1: %q\", err)\n\t}\n\treturn pvlabler.GetLabelsForVolume(context.TODO(), pv)\n}","line":{"from":225,"to":245}} {"id":100013586,"name":"getGCEPVLabeler","signature":"func (l *persistentVolumeLabel) getGCEPVLabeler() (cloudprovider.PVLabeler, error)","file":"plugin/pkg/admission/storage/persistentvolume/label/admission.go","code":"// getGCEPVLabeler returns the GCE implementation of PVLabeler\nfunc (l *persistentVolumeLabel) getGCEPVLabeler() (cloudprovider.PVLabeler, error) {\n\tl.mutex.Lock()\n\tdefer l.mutex.Unlock()\n\n\tif l.gcePVLabeler == nil {\n\t\tvar cloudConfigReader io.Reader\n\t\tif len(l.cloudConfig) \u003e 0 {\n\t\t\tcloudConfigReader = bytes.NewReader(l.cloudConfig)\n\t\t}\n\n\t\tcloudProvider, err := cloudprovider.GetCloudProvider(\"gce\", cloudConfigReader)\n\t\tif err != nil || cloudProvider == nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tgcePVLabeler, ok := cloudProvider.(cloudprovider.PVLabeler)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"GCE cloud provider does not implement PV labeling\")\n\t\t}\n\n\t\tl.gcePVLabeler = gcePVLabeler\n\n\t}\n\treturn l.gcePVLabeler, nil\n}","line":{"from":247,"to":272}} {"id":100013587,"name":"getAzurePVLabeler","signature":"func (l *persistentVolumeLabel) getAzurePVLabeler() (cloudprovider.PVLabeler, error)","file":"plugin/pkg/admission/storage/persistentvolume/label/admission.go","code":"// getAzurePVLabeler returns the Azure implementation of PVLabeler\nfunc (l *persistentVolumeLabel) getAzurePVLabeler() (cloudprovider.PVLabeler, error) {\n\tl.mutex.Lock()\n\tdefer l.mutex.Unlock()\n\n\tif l.azurePVLabeler == nil {\n\t\tvar cloudConfigReader io.Reader\n\t\tif len(l.cloudConfig) \u003e 0 {\n\t\t\tcloudConfigReader = bytes.NewReader(l.cloudConfig)\n\t\t}\n\n\t\tcloudProvider, err := cloudprovider.GetCloudProvider(\"azure\", cloudConfigReader)\n\t\tif err != nil || cloudProvider == nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tazurePVLabeler, ok := cloudProvider.(cloudprovider.PVLabeler)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"Azure cloud provider does not implement PV labeling\")\n\t\t}\n\t\tl.azurePVLabeler = azurePVLabeler\n\t}\n\n\treturn l.azurePVLabeler, nil\n}","line":{"from":274,"to":298}} {"id":100013588,"name":"findAzureDiskLabels","signature":"func (l *persistentVolumeLabel) findAzureDiskLabels(volume *api.PersistentVolume) (map[string]string, error)","file":"plugin/pkg/admission/storage/persistentvolume/label/admission.go","code":"func (l *persistentVolumeLabel) findAzureDiskLabels(volume *api.PersistentVolume) (map[string]string, error) {\n\t// Ignore any volumes that are being provisioned\n\tif volume.Spec.AzureDisk.DiskName == cloudvolume.ProvisionedVolumeName {\n\t\treturn nil, nil\n\t}\n\n\tpvlabler, err := l.getAzurePVLabeler()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif pvlabler == nil {\n\t\treturn nil, fmt.Errorf(\"unable to build Azure cloud provider for AzureDisk\")\n\t}\n\n\tpv := \u0026v1.PersistentVolume{}\n\terr = k8s_api_v1.Convert_core_PersistentVolume_To_v1_PersistentVolume(volume, pv, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to convert PersistentVolume to core/v1: %q\", err)\n\t}\n\treturn pvlabler.GetLabelsForVolume(context.TODO(), pv)\n}","line":{"from":300,"to":320}} {"id":100013589,"name":"findVsphereVolumeLabels","signature":"func (l *persistentVolumeLabel) findVsphereVolumeLabels(volume *api.PersistentVolume) (map[string]string, error)","file":"plugin/pkg/admission/storage/persistentvolume/label/admission.go","code":"func (l *persistentVolumeLabel) findVsphereVolumeLabels(volume *api.PersistentVolume) (map[string]string, error) {\n\tpvlabler, err := l.getVspherePVLabeler()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif pvlabler == nil {\n\t\treturn nil, fmt.Errorf(\"unable to build vSphere cloud provider\")\n\t}\n\n\tpv := \u0026v1.PersistentVolume{}\n\terr = k8s_api_v1.Convert_core_PersistentVolume_To_v1_PersistentVolume(volume, pv, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to convert PersistentVolume to core/v1: %q\", err)\n\t}\n\tlabels, err := pvlabler.GetLabelsForVolume(context.TODO(), pv)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn labels, nil\n}","line":{"from":322,"to":342}} {"id":100013590,"name":"getVspherePVLabeler","signature":"func (l *persistentVolumeLabel) getVspherePVLabeler() (cloudprovider.PVLabeler, error)","file":"plugin/pkg/admission/storage/persistentvolume/label/admission.go","code":"func (l *persistentVolumeLabel) getVspherePVLabeler() (cloudprovider.PVLabeler, error) {\n\tl.mutex.Lock()\n\tdefer l.mutex.Unlock()\n\n\tif l.vspherePVLabeler == nil {\n\t\tvar cloudConfigReader io.Reader\n\t\tif len(l.cloudConfig) \u003e 0 {\n\t\t\tcloudConfigReader = bytes.NewReader(l.cloudConfig)\n\t\t}\n\t\tcloudProvider, err := cloudprovider.GetCloudProvider(\"vsphere\", cloudConfigReader)\n\t\tif err != nil || cloudProvider == nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvspherePVLabeler, ok := cloudProvider.(cloudprovider.PVLabeler)\n\t\tif !ok {\n\t\t\t// GetCloudProvider failed\n\t\t\treturn nil, errors.New(\"vSphere Cloud Provider does not implement PV labeling\")\n\t\t}\n\t\tl.vspherePVLabeler = vspherePVLabeler\n\t}\n\treturn l.vspherePVLabeler, nil\n}","line":{"from":344,"to":365}} {"id":100013591,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/storage/persistentvolume/resize/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\tplugin := newPlugin()\n\t\treturn plugin, nil\n\t})\n}","line":{"from":37,"to":43}} {"id":100013592,"name":"newPlugin","signature":"func newPlugin() *persistentVolumeClaimResize","file":"plugin/pkg/admission/storage/persistentvolume/resize/admission.go","code":"func newPlugin() *persistentVolumeClaimResize {\n\treturn \u0026persistentVolumeClaimResize{\n\t\tHandler: admission.NewHandler(admission.Update),\n\t}\n}","line":{"from":55,"to":59}} {"id":100013593,"name":"SetExternalKubeInformerFactory","signature":"func (pvcr *persistentVolumeClaimResize) SetExternalKubeInformerFactory(f informers.SharedInformerFactory)","file":"plugin/pkg/admission/storage/persistentvolume/resize/admission.go","code":"func (pvcr *persistentVolumeClaimResize) SetExternalKubeInformerFactory(f informers.SharedInformerFactory) {\n\tscInformer := f.Storage().V1().StorageClasses()\n\tpvcr.scLister = scInformer.Lister()\n\tpvcr.SetReadyFunc(scInformer.Informer().HasSynced)\n}","line":{"from":61,"to":65}} {"id":100013594,"name":"ValidateInitialization","signature":"func (pvcr *persistentVolumeClaimResize) ValidateInitialization() error","file":"plugin/pkg/admission/storage/persistentvolume/resize/admission.go","code":"// ValidateInitialization ensures lister is set.\nfunc (pvcr *persistentVolumeClaimResize) ValidateInitialization() error {\n\tif pvcr.scLister == nil {\n\t\treturn fmt.Errorf(\"missing storageclass lister\")\n\t}\n\treturn nil\n}","line":{"from":67,"to":73}} {"id":100013595,"name":"Validate","signature":"func (pvcr *persistentVolumeClaimResize) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error","file":"plugin/pkg/admission/storage/persistentvolume/resize/admission.go","code":"func (pvcr *persistentVolumeClaimResize) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {\n\tif a.GetResource().GroupResource() != api.Resource(\"persistentvolumeclaims\") {\n\t\treturn nil\n\t}\n\n\tif len(a.GetSubresource()) != 0 {\n\t\treturn nil\n\t}\n\n\tpvc, ok := a.GetObject().(*api.PersistentVolumeClaim)\n\t// if we can't convert then we don't handle this object so just return\n\tif !ok {\n\t\treturn nil\n\t}\n\toldPvc, ok := a.GetOldObject().(*api.PersistentVolumeClaim)\n\tif !ok {\n\t\treturn nil\n\t}\n\n\toldSize := oldPvc.Spec.Resources.Requests[api.ResourceStorage]\n\tnewSize := pvc.Spec.Resources.Requests[api.ResourceStorage]\n\n\tif newSize.Cmp(oldSize) \u003c= 0 {\n\t\treturn nil\n\t}\n\n\tif oldPvc.Status.Phase != api.ClaimBound {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"Only bound persistent volume claims can be expanded\"))\n\t}\n\n\t// Growing Persistent volumes is only allowed for PVCs for which their StorageClass\n\t// explicitly allows it\n\tif !pvcr.allowResize(pvc, oldPvc) {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"only dynamically provisioned pvc can be resized and \"+\n\t\t\t\"the storageclass that provisions the pvc must support resize\"))\n\t}\n\n\treturn nil\n}","line":{"from":75,"to":113}} {"id":100013596,"name":"allowResize","signature":"func (pvcr *persistentVolumeClaimResize) allowResize(pvc, oldPvc *api.PersistentVolumeClaim) bool","file":"plugin/pkg/admission/storage/persistentvolume/resize/admission.go","code":"// Growing Persistent volumes is only allowed for PVCs for which their StorageClass\n// explicitly allows it.\nfunc (pvcr *persistentVolumeClaimResize) allowResize(pvc, oldPvc *api.PersistentVolumeClaim) bool {\n\tpvcStorageClass := apihelper.GetPersistentVolumeClaimClass(pvc)\n\toldPvcStorageClass := apihelper.GetPersistentVolumeClaimClass(oldPvc)\n\tif pvcStorageClass == \"\" || oldPvcStorageClass == \"\" || pvcStorageClass != oldPvcStorageClass {\n\t\treturn false\n\t}\n\tsc, err := pvcr.scLister.Get(pvcStorageClass)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif sc.AllowVolumeExpansion != nil {\n\t\treturn *sc.AllowVolumeExpansion\n\t}\n\treturn false\n}","line":{"from":115,"to":131}} {"id":100013597,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/storage/storageclass/setdefault/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\tplugin := newPlugin()\n\t\treturn plugin, nil\n\t})\n}","line":{"from":40,"to":46}} {"id":100013598,"name":"newPlugin","signature":"func newPlugin() *claimDefaulterPlugin","file":"plugin/pkg/admission/storage/storageclass/setdefault/admission.go","code":"// newPlugin creates a new admission plugin.\nfunc newPlugin() *claimDefaulterPlugin {\n\treturn \u0026claimDefaulterPlugin{\n\t\tHandler: admission.NewHandler(admission.Create),\n\t}\n}","line":{"from":59,"to":64}} {"id":100013599,"name":"SetExternalKubeInformerFactory","signature":"func (a *claimDefaulterPlugin) SetExternalKubeInformerFactory(f informers.SharedInformerFactory)","file":"plugin/pkg/admission/storage/storageclass/setdefault/admission.go","code":"func (a *claimDefaulterPlugin) SetExternalKubeInformerFactory(f informers.SharedInformerFactory) {\n\tinformer := f.Storage().V1().StorageClasses()\n\ta.lister = informer.Lister()\n\ta.SetReadyFunc(informer.Informer().HasSynced)\n}","line":{"from":66,"to":70}} {"id":100013600,"name":"ValidateInitialization","signature":"func (a *claimDefaulterPlugin) ValidateInitialization() error","file":"plugin/pkg/admission/storage/storageclass/setdefault/admission.go","code":"// ValidateInitialization ensures lister is set.\nfunc (a *claimDefaulterPlugin) ValidateInitialization() error {\n\tif a.lister == nil {\n\t\treturn fmt.Errorf(\"missing lister\")\n\t}\n\treturn nil\n}","line":{"from":72,"to":78}} {"id":100013601,"name":"Admit","signature":"func (a *claimDefaulterPlugin) Admit(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) error","file":"plugin/pkg/admission/storage/storageclass/setdefault/admission.go","code":"// Admit sets the default value of a PersistentVolumeClaim's storage class, in case the user did\n// not provide a value.\n//\n// 1. Find available StorageClasses.\n// 2. Figure which is the default\n// 3. Write to the PVClaim\nfunc (a *claimDefaulterPlugin) Admit(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) error {\n\tif attr.GetResource().GroupResource() != api.Resource(\"persistentvolumeclaims\") {\n\t\treturn nil\n\t}\n\n\tif len(attr.GetSubresource()) != 0 {\n\t\treturn nil\n\t}\n\n\tpvc, ok := attr.GetObject().(*api.PersistentVolumeClaim)\n\t// if we can't convert then we don't handle this object so just return\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tif helper.PersistentVolumeClaimHasClass(pvc) {\n\t\t// The user asked for a class.\n\t\treturn nil\n\t}\n\n\tklog.V(4).Infof(\"no storage class for claim %s (generate: %s)\", pvc.Name, pvc.GenerateName)\n\n\tdef, err := util.GetDefaultClass(a.lister)\n\tif err != nil {\n\t\treturn admission.NewForbidden(attr, err)\n\t}\n\tif def == nil {\n\t\t// No default class selected, do nothing about the PVC.\n\t\treturn nil\n\t}\n\n\tklog.V(4).Infof(\"defaulting storage class for claim %s (generate: %s) to %s\", pvc.Name, pvc.GenerateName, def.Name)\n\tpvc.Spec.StorageClassName = \u0026def.Name\n\treturn nil\n}","line":{"from":80,"to":120}} {"id":100013602,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"plugin/pkg/admission/storage/storageobjectinuseprotection/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\tplugin := newPlugin()\n\t\treturn plugin, nil\n\t})\n}","line":{"from":34,"to":40}} {"id":100013603,"name":"newPlugin","signature":"func newPlugin() *storageProtectionPlugin","file":"plugin/pkg/admission/storage/storageobjectinuseprotection/admission.go","code":"// newPlugin creates a new admission plugin.\nfunc newPlugin() *storageProtectionPlugin {\n\treturn \u0026storageProtectionPlugin{\n\t\tHandler: admission.NewHandler(admission.Create),\n\t}\n}","line":{"from":49,"to":54}} {"id":100013604,"name":"Admit","signature":"func (c *storageProtectionPlugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error","file":"plugin/pkg/admission/storage/storageobjectinuseprotection/admission.go","code":"// Admit sets finalizer on all PVCs(PVs). The finalizer is removed by\n// PVCProtectionController(PVProtectionController) when it's not referenced.\n//\n// This prevents users from deleting a PVC that's used by a running pod.\n// This also prevents admin from deleting a PV that's bound by a PVC\nfunc (c *storageProtectionPlugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {\n\tswitch a.GetResource().GroupResource() {\n\tcase pvResource:\n\t\treturn c.admitPV(a)\n\tcase pvcResource:\n\t\treturn c.admitPVC(a)\n\n\tdefault:\n\t\treturn nil\n\t}\n}","line":{"from":61,"to":76}} {"id":100013605,"name":"admitPV","signature":"func (c *storageProtectionPlugin) admitPV(a admission.Attributes) error","file":"plugin/pkg/admission/storage/storageobjectinuseprotection/admission.go","code":"func (c *storageProtectionPlugin) admitPV(a admission.Attributes) error {\n\tif len(a.GetSubresource()) != 0 {\n\t\treturn nil\n\t}\n\n\tpv, ok := a.GetObject().(*api.PersistentVolume)\n\t// if we can't convert the obj to PV, just return\n\tif !ok {\n\t\treturn nil\n\t}\n\tfor _, f := range pv.Finalizers {\n\t\tif f == volumeutil.PVProtectionFinalizer {\n\t\t\t// Finalizer is already present, nothing to do\n\t\t\treturn nil\n\t\t}\n\t}\n\tklog.V(4).Infof(\"adding PV protection finalizer to %s\", pv.Name)\n\tpv.Finalizers = append(pv.Finalizers, volumeutil.PVProtectionFinalizer)\n\n\treturn nil\n}","line":{"from":78,"to":98}} {"id":100013606,"name":"admitPVC","signature":"func (c *storageProtectionPlugin) admitPVC(a admission.Attributes) error","file":"plugin/pkg/admission/storage/storageobjectinuseprotection/admission.go","code":"func (c *storageProtectionPlugin) admitPVC(a admission.Attributes) error {\n\tif len(a.GetSubresource()) != 0 {\n\t\treturn nil\n\t}\n\n\tpvc, ok := a.GetObject().(*api.PersistentVolumeClaim)\n\t// if we can't convert the obj to PVC, just return\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tfor _, f := range pvc.Finalizers {\n\t\tif f == volumeutil.PVCProtectionFinalizer {\n\t\t\t// Finalizer is already present, nothing to do\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tklog.V(4).Infof(\"adding PVC protection finalizer to %s/%s\", pvc.Namespace, pvc.Name)\n\tpvc.Finalizers = append(pvc.Finalizers, volumeutil.PVCProtectionFinalizer)\n\treturn nil\n}","line":{"from":100,"to":121}} {"id":100013607,"name":"NewTokenAuthenticator","signature":"func NewTokenAuthenticator(lister corev1listers.SecretNamespaceLister) *TokenAuthenticator","file":"plugin/pkg/auth/authenticator/token/bootstrap/bootstrap.go","code":"// NewTokenAuthenticator initializes a bootstrap token authenticator.\n//\n// Lister is expected to be for the \"kube-system\" namespace.\nfunc NewTokenAuthenticator(lister corev1listers.SecretNamespaceLister) *TokenAuthenticator {\n\treturn \u0026TokenAuthenticator{lister}\n}","line":{"from":44,"to":49}} {"id":100013608,"name":"tokenErrorf","signature":"func tokenErrorf(s *corev1.Secret, format string, i ...interface{})","file":"plugin/pkg/auth/authenticator/token/bootstrap/bootstrap.go","code":"// tokenErrorf prints a error message for a secret that has matched a bearer\n// token but fails to meet some other criteria.\n//\n//\ttokenErrorf(secret, \"has invalid value for key %s\", key)\nfunc tokenErrorf(s *corev1.Secret, format string, i ...interface{}) {\n\tformat = fmt.Sprintf(\"Bootstrap secret %s/%s matching bearer token \", s.Namespace, s.Name) + format\n\tklog.V(3).Infof(format, i...)\n}","line":{"from":56,"to":63}} {"id":100013609,"name":"AuthenticateToken","signature":"func (t *TokenAuthenticator) AuthenticateToken(ctx context.Context, token string) (*authenticator.Response, bool, error)","file":"plugin/pkg/auth/authenticator/token/bootstrap/bootstrap.go","code":"// AuthenticateToken tries to match the provided token to a bootstrap token secret\n// in a given namespace. If found, it authenticates the token in the\n// \"system:bootstrappers\" group and with the \"system:bootstrap:(token-id)\" username.\n//\n// All secrets must be of type \"bootstrap.kubernetes.io/token\". An example secret:\n//\n//\tapiVersion: v1\n//\tkind: Secret\n//\tmetadata:\n//\t # Name MUST be of form \"bootstrap-token-( token id )\".\n//\t name: bootstrap-token-( token id )\n//\t namespace: kube-system\n//\t# Only secrets of this type will be evaluated.\n//\ttype: bootstrap.kubernetes.io/token\n//\tdata:\n//\t token-secret: ( private part of token )\n//\t token-id: ( token id )\n//\t # Required key usage.\n//\t usage-bootstrap-authentication: true\n//\t auth-extra-groups: \"system:bootstrappers:custom-group1,system:bootstrappers:custom-group2\"\n//\t # May also contain an expiry.\n//\n// Tokens are expected to be of the form:\n//\n//\t( token-id ).( token-secret )\nfunc (t *TokenAuthenticator) AuthenticateToken(ctx context.Context, token string) (*authenticator.Response, bool, error) {\n\ttokenID, tokenSecret, err := bootstraptokenutil.ParseToken(token)\n\tif err != nil {\n\t\t// Token isn't of the correct form, ignore it.\n\t\treturn nil, false, nil\n\t}\n\n\tsecretName := bootstrapapi.BootstrapTokenSecretPrefix + tokenID\n\tsecret, err := t.lister.Get(secretName)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\tklog.V(3).Infof(\"No secret of name %s to match bootstrap bearer token\", secretName)\n\t\t\treturn nil, false, nil\n\t\t}\n\t\treturn nil, false, err\n\t}\n\n\tif secret.DeletionTimestamp != nil {\n\t\ttokenErrorf(secret, \"is deleted and awaiting removal\")\n\t\treturn nil, false, nil\n\t}\n\n\tif string(secret.Type) != string(bootstrapapi.SecretTypeBootstrapToken) || secret.Data == nil {\n\t\ttokenErrorf(secret, \"has invalid type, expected %s.\", bootstrapapi.SecretTypeBootstrapToken)\n\t\treturn nil, false, nil\n\t}\n\n\tts := bootstrapsecretutil.GetData(secret, bootstrapapi.BootstrapTokenSecretKey)\n\tif subtle.ConstantTimeCompare([]byte(ts), []byte(tokenSecret)) != 1 {\n\t\ttokenErrorf(secret, \"has invalid value for key %s.\", bootstrapapi.BootstrapTokenSecretKey)\n\t\treturn nil, false, nil\n\t}\n\n\tid := bootstrapsecretutil.GetData(secret, bootstrapapi.BootstrapTokenIDKey)\n\tif id != tokenID {\n\t\ttokenErrorf(secret, \"has invalid value for key %s.\", bootstrapapi.BootstrapTokenIDKey)\n\t\treturn nil, false, nil\n\t}\n\n\tif bootstrapsecretutil.HasExpired(secret, time.Now()) {\n\t\t// logging done in isSecretExpired method.\n\t\treturn nil, false, nil\n\t}\n\n\tif bootstrapsecretutil.GetData(secret, bootstrapapi.BootstrapTokenUsageAuthentication) != \"true\" {\n\t\ttokenErrorf(secret, \"not marked %s=true.\", bootstrapapi.BootstrapTokenUsageAuthentication)\n\t\treturn nil, false, nil\n\t}\n\n\tgroups, err := bootstrapsecretutil.GetGroups(secret)\n\tif err != nil {\n\t\ttokenErrorf(secret, \"has invalid value for key %s: %v.\", bootstrapapi.BootstrapTokenExtraGroupsKey, err)\n\t\treturn nil, false, nil\n\t}\n\n\treturn \u0026authenticator.Response{\n\t\tUser: \u0026user.DefaultInfo{\n\t\t\tName: bootstrapapi.BootstrapUserPrefix + string(id),\n\t\t\tGroups: groups,\n\t\t},\n\t}, true, nil\n}","line":{"from":65,"to":151}} {"id":100013610,"name":"newNamedVertex","signature":"func newNamedVertex(vertexType vertexType, namespace, name string, id int) *namedVertex","file":"plugin/pkg/auth/authorizer/node/graph.go","code":"func newNamedVertex(vertexType vertexType, namespace, name string, id int) *namedVertex {\n\treturn \u0026namedVertex{\n\t\tvertexType: vertexType,\n\t\tname: name,\n\t\tnamespace: namespace,\n\t\tid: id,\n\t}\n}","line":{"from":39,"to":46}} {"id":100013611,"name":"ID","signature":"func (n *namedVertex) ID() int","file":"plugin/pkg/auth/authorizer/node/graph.go","code":"func (n *namedVertex) ID() int {\n\treturn n.id\n}","line":{"from":47,"to":49}} {"id":100013612,"name":"String","signature":"func (n *namedVertex) String() string","file":"plugin/pkg/auth/authorizer/node/graph.go","code":"func (n *namedVertex) String() string {\n\tif len(n.namespace) == 0 {\n\t\treturn vertexTypes[n.vertexType] + \":\" + n.name\n\t}\n\treturn vertexTypes[n.vertexType] + \":\" + n.namespace + \"/\" + n.name\n}","line":{"from":50,"to":55}} {"id":100013613,"name":"newDestinationEdge","signature":"func newDestinationEdge(from, to, destination graph.Node) graph.Edge","file":"plugin/pkg/auth/authorizer/node/graph.go","code":"func newDestinationEdge(from, to, destination graph.Node) graph.Edge {\n\treturn \u0026destinationEdge{F: from, T: to, Destination: destination}\n}","line":{"from":65,"to":67}} {"id":100013614,"name":"From","signature":"func (e *destinationEdge) From() graph.Node { return e.F }","file":"plugin/pkg/auth/authorizer/node/graph.go","code":"func (e *destinationEdge) From() graph.Node { return e.F }","line":{"from":68,"to":68}} {"id":100013615,"name":"To","signature":"func (e *destinationEdge) To() graph.Node { return e.T }","file":"plugin/pkg/auth/authorizer/node/graph.go","code":"func (e *destinationEdge) To() graph.Node { return e.T }","line":{"from":69,"to":69}} {"id":100013616,"name":"Weight","signature":"func (e *destinationEdge) Weight() float64 { return 0 }","file":"plugin/pkg/auth/authorizer/node/graph.go","code":"func (e *destinationEdge) Weight() float64 { return 0 }","line":{"from":70,"to":70}} {"id":100013617,"name":"DestinationID","signature":"func (e *destinationEdge) DestinationID() int { return e.Destination.ID() }","file":"plugin/pkg/auth/authorizer/node/graph.go","code":"func (e *destinationEdge) DestinationID() int { return e.Destination.ID() }","line":{"from":71,"to":71}} {"id":100013618,"name":"NewGraph","signature":"func NewGraph() *Graph","file":"plugin/pkg/auth/authorizer/node/graph.go","code":"func NewGraph() *Graph {\n\treturn \u0026Graph{\n\t\tvertices: map[vertexType]namespaceVertexMapping{},\n\t\tgraph: simple.NewDirectedAcyclicGraph(0, 0),\n\n\t\tdestinationEdgeIndex: map[int]*intSet{},\n\t\t// experimentally determined to be the point at which iteration adds an order of magnitude to the authz check.\n\t\t// since maintaining indexes costs time/memory while processing graph changes, we don't want to make this too low.\n\t\tdestinationEdgeThreshold: 200,\n\t}\n}","line":{"from":98,"to":108}} {"id":100013619,"name":"getOrCreateVertex_locked","signature":"func (g *Graph) getOrCreateVertex_locked(vertexType vertexType, namespace, name string) *namedVertex","file":"plugin/pkg/auth/authorizer/node/graph.go","code":"// must be called under a write lock\nfunc (g *Graph) getOrCreateVertex_locked(vertexType vertexType, namespace, name string) *namedVertex {\n\tif vertex, exists := g.getVertex_rlocked(vertexType, namespace, name); exists {\n\t\treturn vertex\n\t}\n\treturn g.createVertex_locked(vertexType, namespace, name)\n}","line":{"from":136,"to":142}} {"id":100013620,"name":"getVertex_rlocked","signature":"func (g *Graph) getVertex_rlocked(vertexType vertexType, namespace, name string) (*namedVertex, bool)","file":"plugin/pkg/auth/authorizer/node/graph.go","code":"// must be called under a read lock\nfunc (g *Graph) getVertex_rlocked(vertexType vertexType, namespace, name string) (*namedVertex, bool) {\n\tvertex, exists := g.vertices[vertexType][namespace][name]\n\treturn vertex, exists\n}","line":{"from":144,"to":148}} {"id":100013621,"name":"createVertex_locked","signature":"func (g *Graph) createVertex_locked(vertexType vertexType, namespace, name string) *namedVertex","file":"plugin/pkg/auth/authorizer/node/graph.go","code":"// must be called under a write lock\nfunc (g *Graph) createVertex_locked(vertexType vertexType, namespace, name string) *namedVertex {\n\ttypedVertices, exists := g.vertices[vertexType]\n\tif !exists {\n\t\ttypedVertices = namespaceVertexMapping{}\n\t\tg.vertices[vertexType] = typedVertices\n\t}\n\n\tnamespacedVertices, exists := typedVertices[namespace]\n\tif !exists {\n\t\tnamespacedVertices = map[string]*namedVertex{}\n\t\ttypedVertices[namespace] = namespacedVertices\n\t}\n\n\tvertex := newNamedVertex(vertexType, namespace, name, g.graph.NewNodeID())\n\tnamespacedVertices[name] = vertex\n\tg.graph.AddNode(vertex)\n\n\treturn vertex\n}","line":{"from":150,"to":169}} {"id":100013622,"name":"deleteVertex_locked","signature":"func (g *Graph) deleteVertex_locked(vertexType vertexType, namespace, name string)","file":"plugin/pkg/auth/authorizer/node/graph.go","code":"// must be called under write lock\nfunc (g *Graph) deleteVertex_locked(vertexType vertexType, namespace, name string) {\n\tvertex, exists := g.getVertex_rlocked(vertexType, namespace, name)\n\tif !exists {\n\t\treturn\n\t}\n\n\t// find existing neighbors with a single edge (meaning we are their only neighbor)\n\tneighborsToRemove := []graph.Node{}\n\tedgesToRemoveFromIndexes := []graph.Edge{}\n\tg.graph.VisitFrom(vertex, func(neighbor graph.Node) bool {\n\t\t// this downstream neighbor has only one edge (which must be from us), so remove them as well\n\t\tif g.graph.Degree(neighbor) == 1 {\n\t\t\tneighborsToRemove = append(neighborsToRemove, neighbor)\n\t\t}\n\t\treturn true\n\t})\n\tg.graph.VisitTo(vertex, func(neighbor graph.Node) bool {\n\t\tif g.graph.Degree(neighbor) == 1 {\n\t\t\t// this upstream neighbor has only one edge (which must be to us), so remove them as well\n\t\t\tneighborsToRemove = append(neighborsToRemove, neighbor)\n\t\t} else {\n\t\t\t// decrement the destination edge index on this neighbor if the edge between us was a destination edge\n\t\t\tedgesToRemoveFromIndexes = append(edgesToRemoveFromIndexes, g.graph.EdgeBetween(vertex, neighbor))\n\t\t}\n\t\treturn true\n\t})\n\n\t// remove the vertex\n\tg.removeVertex_locked(vertex)\n\n\t// remove neighbors that are now edgeless\n\tfor _, neighbor := range neighborsToRemove {\n\t\tg.removeVertex_locked(neighbor.(*namedVertex))\n\t}\n\n\t// remove edges from destination indexes for neighbors that dropped outbound edges\n\tfor _, edge := range edgesToRemoveFromIndexes {\n\t\tg.removeEdgeFromDestinationIndex_locked(edge)\n\t}\n}","line":{"from":171,"to":211}} {"id":100013623,"name":"deleteEdges_locked","signature":"func (g *Graph) deleteEdges_locked(fromType, toType vertexType, toNamespace, toName string)","file":"plugin/pkg/auth/authorizer/node/graph.go","code":"// must be called under write lock\n// deletes edges from a given vertex type to a specific vertex\n// will delete each orphaned \"from\" vertex, but will never delete the \"to\" vertex\nfunc (g *Graph) deleteEdges_locked(fromType, toType vertexType, toNamespace, toName string) {\n\t// get the \"to\" side\n\ttoVert, exists := g.getVertex_rlocked(toType, toNamespace, toName)\n\tif !exists {\n\t\treturn\n\t}\n\n\t// delete all edges between vertices of fromType and toVert\n\tneighborsToRemove := []*namedVertex{}\n\tedgesToRemove := []graph.Edge{}\n\tg.graph.VisitTo(toVert, func(from graph.Node) bool {\n\t\tfromVert := from.(*namedVertex)\n\t\tif fromVert.vertexType != fromType {\n\t\t\treturn true\n\t\t}\n\t\t// this neighbor has only one edge (which must be to us), so remove them as well\n\t\tif g.graph.Degree(fromVert) == 1 {\n\t\t\tneighborsToRemove = append(neighborsToRemove, fromVert)\n\t\t} else {\n\t\t\tedgesToRemove = append(edgesToRemove, g.graph.EdgeBetween(from, toVert))\n\t\t}\n\t\treturn true\n\t})\n\n\t// clean up orphaned verts\n\tfor _, v := range neighborsToRemove {\n\t\tg.removeVertex_locked(v)\n\t}\n\n\t// remove edges and decrement destination indexes for neighbors that dropped outbound edges\n\tfor _, edge := range edgesToRemove {\n\t\tg.graph.RemoveEdge(edge)\n\t\tg.removeEdgeFromDestinationIndex_locked(edge)\n\t}\n}","line":{"from":213,"to":250}} {"id":100013624,"name":"removeEdgeFromDestinationIndex_locked","signature":"func (g *Graph) removeEdgeFromDestinationIndex_locked(e graph.Edge)","file":"plugin/pkg/auth/authorizer/node/graph.go","code":"// A fastpath for recomputeDestinationIndex_locked for \"removing edge\" case.\nfunc (g *Graph) removeEdgeFromDestinationIndex_locked(e graph.Edge) {\n\tn := e.From()\n\t// don't maintain indices for nodes with few edges\n\tedgeCount := g.graph.Degree(n)\n\tif edgeCount \u003c g.destinationEdgeThreshold {\n\t\tdelete(g.destinationEdgeIndex, n.ID())\n\t\treturn\n\t}\n\n\t// decrement the nodeID-\u003edestinationID refcount in the index, if the index exists\n\tindex := g.destinationEdgeIndex[n.ID()]\n\tif index == nil {\n\t\treturn\n\t}\n\tif destinationEdge, ok := e.(*destinationEdge); ok {\n\t\tindex.decrement(destinationEdge.DestinationID())\n\t}\n}","line":{"from":252,"to":270}} {"id":100013625,"name":"addEdgeToDestinationIndex_locked","signature":"func (g *Graph) addEdgeToDestinationIndex_locked(e graph.Edge)","file":"plugin/pkg/auth/authorizer/node/graph.go","code":"// A fastpath for recomputeDestinationIndex_locked for \"adding edge case\".\nfunc (g *Graph) addEdgeToDestinationIndex_locked(e graph.Edge) {\n\tn := e.From()\n\tindex := g.destinationEdgeIndex[n.ID()]\n\tif index == nil {\n\t\t// There is no index, use the full index computation method\n\t\tg.recomputeDestinationIndex_locked(n)\n\t\treturn\n\t}\n\t// fast-add the new edge to an existing index\n\tif destinationEdge, ok := e.(*destinationEdge); ok {\n\t\tindex.increment(destinationEdge.DestinationID())\n\t}\n}","line":{"from":272,"to":285}} {"id":100013626,"name":"removeVertex_locked","signature":"func (g *Graph) removeVertex_locked(v *namedVertex)","file":"plugin/pkg/auth/authorizer/node/graph.go","code":"// must be called under write lock\n// removeVertex_locked removes the specified vertex from the graph and from the maintained indices.\n// It does nothing to indexes of neighbor vertices.\nfunc (g *Graph) removeVertex_locked(v *namedVertex) {\n\tg.graph.RemoveNode(v)\n\tdelete(g.destinationEdgeIndex, v.ID())\n\tdelete(g.vertices[v.vertexType][v.namespace], v.name)\n\tif len(g.vertices[v.vertexType][v.namespace]) == 0 {\n\t\tdelete(g.vertices[v.vertexType], v.namespace)\n\t}\n}","line":{"from":287,"to":297}} {"id":100013627,"name":"recomputeDestinationIndex_locked","signature":"func (g *Graph) recomputeDestinationIndex_locked(n graph.Node)","file":"plugin/pkg/auth/authorizer/node/graph.go","code":"// must be called under write lock\n// recomputeDestinationIndex_locked recomputes the index of destination ids for the specified vertex\nfunc (g *Graph) recomputeDestinationIndex_locked(n graph.Node) {\n\t// don't maintain indices for nodes with few edges\n\tedgeCount := g.graph.Degree(n)\n\tif edgeCount \u003c g.destinationEdgeThreshold {\n\t\tdelete(g.destinationEdgeIndex, n.ID())\n\t\treturn\n\t}\n\n\t// get or create the index\n\tindex := g.destinationEdgeIndex[n.ID()]\n\tif index == nil {\n\t\tindex = newIntSet()\n\t} else {\n\t\tindex.reset()\n\t}\n\n\t// populate the index\n\tg.graph.VisitFrom(n, func(dest graph.Node) bool {\n\t\tif destinationEdge, ok := g.graph.EdgeBetween(n, dest).(*destinationEdge); ok {\n\t\t\tindex.increment(destinationEdge.DestinationID())\n\t\t}\n\t\treturn true\n\t})\n\tg.destinationEdgeIndex[n.ID()] = index\n}","line":{"from":299,"to":325}} {"id":100013628,"name":"AddPod","signature":"func (g *Graph) AddPod(pod *corev1.Pod)","file":"plugin/pkg/auth/authorizer/node/graph.go","code":"// AddPod should only be called once spec.NodeName is populated.\n// It sets up edges for the following relationships (which are immutable for a pod once bound to a node):\n//\n//\tpod -\u003e node\n//\tsecret -\u003e pod\n//\tconfigmap -\u003e pod\n//\tpvc -\u003e pod\n//\tsvcacct -\u003e pod\nfunc (g *Graph) AddPod(pod *corev1.Pod) {\n\tstart := time.Now()\n\tdefer func() {\n\t\tgraphActionsDuration.WithLabelValues(\"AddPod\").Observe(time.Since(start).Seconds())\n\t}()\n\tg.lock.Lock()\n\tdefer g.lock.Unlock()\n\n\tg.deleteVertex_locked(podVertexType, pod.Namespace, pod.Name)\n\tpodVertex := g.getOrCreateVertex_locked(podVertexType, pod.Namespace, pod.Name)\n\tnodeVertex := g.getOrCreateVertex_locked(nodeVertexType, \"\", pod.Spec.NodeName)\n\tg.graph.SetEdge(newDestinationEdge(podVertex, nodeVertex, nodeVertex))\n\n\t// Short-circuit adding edges to other resources for mirror pods.\n\t// A node must never be able to create a pod that grants them permissions on other API objects.\n\t// The NodeRestriction admission plugin prevents creation of such pods, but short-circuiting here gives us defense in depth.\n\tif _, isMirrorPod := pod.Annotations[corev1.MirrorPodAnnotationKey]; isMirrorPod {\n\t\treturn\n\t}\n\n\t// TODO(mikedanese): If the pod doesn't mount the service account secrets,\n\t// should the node still get access to the service account?\n\t//\n\t// ref https://github.com/kubernetes/kubernetes/issues/58790\n\tif len(pod.Spec.ServiceAccountName) \u003e 0 {\n\t\tserviceAccountVertex := g.getOrCreateVertex_locked(serviceAccountVertexType, pod.Namespace, pod.Spec.ServiceAccountName)\n\t\te := newDestinationEdge(serviceAccountVertex, podVertex, nodeVertex)\n\t\tg.graph.SetEdge(e)\n\t\tg.addEdgeToDestinationIndex_locked(e)\n\t}\n\n\tpodutil.VisitPodSecretNames(pod, func(secret string) bool {\n\t\tsecretVertex := g.getOrCreateVertex_locked(secretVertexType, pod.Namespace, secret)\n\t\te := newDestinationEdge(secretVertex, podVertex, nodeVertex)\n\t\tg.graph.SetEdge(e)\n\t\tg.addEdgeToDestinationIndex_locked(e)\n\t\treturn true\n\t})\n\n\tpodutil.VisitPodConfigmapNames(pod, func(configmap string) bool {\n\t\tconfigmapVertex := g.getOrCreateVertex_locked(configMapVertexType, pod.Namespace, configmap)\n\t\te := newDestinationEdge(configmapVertex, podVertex, nodeVertex)\n\t\tg.graph.SetEdge(e)\n\t\tg.addEdgeToDestinationIndex_locked(e)\n\t\treturn true\n\t})\n\n\tfor _, v := range pod.Spec.Volumes {\n\t\tclaimName := \"\"\n\t\tif v.PersistentVolumeClaim != nil {\n\t\t\tclaimName = v.PersistentVolumeClaim.ClaimName\n\t\t} else if v.Ephemeral != nil {\n\t\t\tclaimName = ephemeral.VolumeClaimName(pod, \u0026v)\n\t\t}\n\t\tif claimName != \"\" {\n\t\t\tpvcVertex := g.getOrCreateVertex_locked(pvcVertexType, pod.Namespace, claimName)\n\t\t\te := newDestinationEdge(pvcVertex, podVertex, nodeVertex)\n\t\t\tg.graph.SetEdge(e)\n\t\t\tg.addEdgeToDestinationIndex_locked(e)\n\t\t}\n\t}\n}","line":{"from":327,"to":396}} {"id":100013629,"name":"DeletePod","signature":"func (g *Graph) DeletePod(name, namespace string)","file":"plugin/pkg/auth/authorizer/node/graph.go","code":"func (g *Graph) DeletePod(name, namespace string) {\n\tstart := time.Now()\n\tdefer func() {\n\t\tgraphActionsDuration.WithLabelValues(\"DeletePod\").Observe(time.Since(start).Seconds())\n\t}()\n\tg.lock.Lock()\n\tdefer g.lock.Unlock()\n\tg.deleteVertex_locked(podVertexType, namespace, name)\n}","line":{"from":397,"to":405}} {"id":100013630,"name":"AddPV","signature":"func (g *Graph) AddPV(pv *corev1.PersistentVolume)","file":"plugin/pkg/auth/authorizer/node/graph.go","code":"// AddPV sets up edges for the following relationships:\n//\n//\tsecret -\u003e pv\n//\n//\tpv -\u003e pvc\nfunc (g *Graph) AddPV(pv *corev1.PersistentVolume) {\n\tstart := time.Now()\n\tdefer func() {\n\t\tgraphActionsDuration.WithLabelValues(\"AddPV\").Observe(time.Since(start).Seconds())\n\t}()\n\tg.lock.Lock()\n\tdefer g.lock.Unlock()\n\n\t// clear existing edges\n\tg.deleteVertex_locked(pvVertexType, \"\", pv.Name)\n\n\t// if we have a pvc, establish new edges\n\tif pv.Spec.ClaimRef != nil {\n\t\tpvVertex := g.getOrCreateVertex_locked(pvVertexType, \"\", pv.Name)\n\n\t\t// since we don't know the other end of the pvc -\u003e pod -\u003e node chain (or it may not even exist yet), we can't decorate these edges with kubernetes node info\n\t\tg.graph.SetEdge(simple.Edge{F: pvVertex, T: g.getOrCreateVertex_locked(pvcVertexType, pv.Spec.ClaimRef.Namespace, pv.Spec.ClaimRef.Name)})\n\t\tpvutil.VisitPVSecretNames(pv, func(namespace, secret string, kubeletVisible bool) bool {\n\t\t\t// This grants access to the named secret in the same namespace as the bound PVC\n\t\t\tif kubeletVisible {\n\t\t\t\tg.graph.SetEdge(simple.Edge{F: g.getOrCreateVertex_locked(secretVertexType, namespace, secret), T: pvVertex})\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t}\n}","line":{"from":407,"to":437}} {"id":100013631,"name":"DeletePV","signature":"func (g *Graph) DeletePV(name string)","file":"plugin/pkg/auth/authorizer/node/graph.go","code":"func (g *Graph) DeletePV(name string) {\n\tstart := time.Now()\n\tdefer func() {\n\t\tgraphActionsDuration.WithLabelValues(\"DeletePV\").Observe(time.Since(start).Seconds())\n\t}()\n\tg.lock.Lock()\n\tdefer g.lock.Unlock()\n\tg.deleteVertex_locked(pvVertexType, \"\", name)\n}","line":{"from":438,"to":446}} {"id":100013632,"name":"AddVolumeAttachment","signature":"func (g *Graph) AddVolumeAttachment(attachmentName, nodeName string)","file":"plugin/pkg/auth/authorizer/node/graph.go","code":"// AddVolumeAttachment sets up edges for the following relationships:\n//\n//\tvolume attachment -\u003e node\nfunc (g *Graph) AddVolumeAttachment(attachmentName, nodeName string) {\n\tstart := time.Now()\n\tdefer func() {\n\t\tgraphActionsDuration.WithLabelValues(\"AddVolumeAttachment\").Observe(time.Since(start).Seconds())\n\t}()\n\tg.lock.Lock()\n\tdefer g.lock.Unlock()\n\n\t// clear existing edges\n\tg.deleteVertex_locked(vaVertexType, \"\", attachmentName)\n\n\t// if we have a node, establish new edges\n\tif len(nodeName) \u003e 0 {\n\t\tvaVertex := g.getOrCreateVertex_locked(vaVertexType, \"\", attachmentName)\n\t\tnodeVertex := g.getOrCreateVertex_locked(nodeVertexType, \"\", nodeName)\n\t\tg.graph.SetEdge(newDestinationEdge(vaVertex, nodeVertex, nodeVertex))\n\t}\n}","line":{"from":448,"to":468}} {"id":100013633,"name":"DeleteVolumeAttachment","signature":"func (g *Graph) DeleteVolumeAttachment(name string)","file":"plugin/pkg/auth/authorizer/node/graph.go","code":"func (g *Graph) DeleteVolumeAttachment(name string) {\n\tstart := time.Now()\n\tdefer func() {\n\t\tgraphActionsDuration.WithLabelValues(\"DeleteVolumeAttachment\").Observe(time.Since(start).Seconds())\n\t}()\n\tg.lock.Lock()\n\tdefer g.lock.Unlock()\n\tg.deleteVertex_locked(vaVertexType, \"\", name)\n}","line":{"from":469,"to":477}} {"id":100013634,"name":"AddGraphEventHandlers","signature":"func AddGraphEventHandlers(","file":"plugin/pkg/auth/authorizer/node/graph_populator.go","code":"func AddGraphEventHandlers(\n\tgraph *Graph,\n\tnodes corev1informers.NodeInformer,\n\tpods corev1informers.PodInformer,\n\tpvs corev1informers.PersistentVolumeInformer,\n\tattachments storageinformers.VolumeAttachmentInformer,\n) {\n\tg := \u0026graphPopulator{\n\t\tgraph: graph,\n\t}\n\n\tpodHandler, _ := pods.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: g.addPod,\n\t\tUpdateFunc: g.updatePod,\n\t\tDeleteFunc: g.deletePod,\n\t})\n\n\tpvsHandler, _ := pvs.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: g.addPV,\n\t\tUpdateFunc: g.updatePV,\n\t\tDeleteFunc: g.deletePV,\n\t})\n\n\tattachHandler, _ := attachments.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: g.addVolumeAttachment,\n\t\tUpdateFunc: g.updateVolumeAttachment,\n\t\tDeleteFunc: g.deleteVolumeAttachment,\n\t})\n\n\tgo cache.WaitForNamedCacheSync(\"node_authorizer\", wait.NeverStop,\n\t\tpodHandler.HasSynced, pvsHandler.HasSynced, attachHandler.HasSynced)\n}","line":{"from":36,"to":67}} {"id":100013635,"name":"addPod","signature":"func (g *graphPopulator) addPod(obj interface{})","file":"plugin/pkg/auth/authorizer/node/graph_populator.go","code":"func (g *graphPopulator) addPod(obj interface{}) {\n\tg.updatePod(nil, obj)\n}","line":{"from":69,"to":71}} {"id":100013636,"name":"updatePod","signature":"func (g *graphPopulator) updatePod(oldObj, obj interface{})","file":"plugin/pkg/auth/authorizer/node/graph_populator.go","code":"func (g *graphPopulator) updatePod(oldObj, obj interface{}) {\n\tpod := obj.(*corev1.Pod)\n\tif len(pod.Spec.NodeName) == 0 {\n\t\t// No node assigned\n\t\tklog.V(5).Infof(\"updatePod %s/%s, no node\", pod.Namespace, pod.Name)\n\t\treturn\n\t}\n\tif oldPod, ok := oldObj.(*corev1.Pod); ok \u0026\u0026 oldPod != nil {\n\t\tif (pod.Spec.NodeName == oldPod.Spec.NodeName) \u0026\u0026 (pod.UID == oldPod.UID) {\n\t\t\t// Node and uid are unchanged, all object references in the pod spec are immutable\n\t\t\tklog.V(5).Infof(\"updatePod %s/%s, node unchanged\", pod.Namespace, pod.Name)\n\t\t\treturn\n\t\t}\n\t}\n\n\tklog.V(4).Infof(\"updatePod %s/%s for node %s\", pod.Namespace, pod.Name, pod.Spec.NodeName)\n\tstartTime := time.Now()\n\tg.graph.AddPod(pod)\n\tklog.V(5).Infof(\"updatePod %s/%s for node %s completed in %v\", pod.Namespace, pod.Name, pod.Spec.NodeName, time.Since(startTime))\n}","line":{"from":73,"to":92}} {"id":100013637,"name":"deletePod","signature":"func (g *graphPopulator) deletePod(obj interface{})","file":"plugin/pkg/auth/authorizer/node/graph_populator.go","code":"func (g *graphPopulator) deletePod(obj interface{}) {\n\tif tombstone, ok := obj.(cache.DeletedFinalStateUnknown); ok {\n\t\tobj = tombstone.Obj\n\t}\n\tpod, ok := obj.(*corev1.Pod)\n\tif !ok {\n\t\tklog.Infof(\"unexpected type %T\", obj)\n\t\treturn\n\t}\n\tif len(pod.Spec.NodeName) == 0 {\n\t\tklog.V(5).Infof(\"deletePod %s/%s, no node\", pod.Namespace, pod.Name)\n\t\treturn\n\t}\n\n\tklog.V(4).Infof(\"deletePod %s/%s for node %s\", pod.Namespace, pod.Name, pod.Spec.NodeName)\n\tstartTime := time.Now()\n\tg.graph.DeletePod(pod.Name, pod.Namespace)\n\tklog.V(5).Infof(\"deletePod %s/%s for node %s completed in %v\", pod.Namespace, pod.Name, pod.Spec.NodeName, time.Since(startTime))\n}","line":{"from":94,"to":112}} {"id":100013638,"name":"addPV","signature":"func (g *graphPopulator) addPV(obj interface{})","file":"plugin/pkg/auth/authorizer/node/graph_populator.go","code":"func (g *graphPopulator) addPV(obj interface{}) {\n\tg.updatePV(nil, obj)\n}","line":{"from":114,"to":116}} {"id":100013639,"name":"updatePV","signature":"func (g *graphPopulator) updatePV(oldObj, obj interface{})","file":"plugin/pkg/auth/authorizer/node/graph_populator.go","code":"func (g *graphPopulator) updatePV(oldObj, obj interface{}) {\n\tpv := obj.(*corev1.PersistentVolume)\n\t// TODO: skip add if uid, pvc, and secrets are all identical between old and new\n\tg.graph.AddPV(pv)\n}","line":{"from":118,"to":122}} {"id":100013640,"name":"deletePV","signature":"func (g *graphPopulator) deletePV(obj interface{})","file":"plugin/pkg/auth/authorizer/node/graph_populator.go","code":"func (g *graphPopulator) deletePV(obj interface{}) {\n\tif tombstone, ok := obj.(cache.DeletedFinalStateUnknown); ok {\n\t\tobj = tombstone.Obj\n\t}\n\tpv, ok := obj.(*corev1.PersistentVolume)\n\tif !ok {\n\t\tklog.Infof(\"unexpected type %T\", obj)\n\t\treturn\n\t}\n\tg.graph.DeletePV(pv.Name)\n}","line":{"from":124,"to":134}} {"id":100013641,"name":"addVolumeAttachment","signature":"func (g *graphPopulator) addVolumeAttachment(obj interface{})","file":"plugin/pkg/auth/authorizer/node/graph_populator.go","code":"func (g *graphPopulator) addVolumeAttachment(obj interface{}) {\n\tg.updateVolumeAttachment(nil, obj)\n}","line":{"from":136,"to":138}} {"id":100013642,"name":"updateVolumeAttachment","signature":"func (g *graphPopulator) updateVolumeAttachment(oldObj, obj interface{})","file":"plugin/pkg/auth/authorizer/node/graph_populator.go","code":"func (g *graphPopulator) updateVolumeAttachment(oldObj, obj interface{}) {\n\tattachment := obj.(*storagev1.VolumeAttachment)\n\tif oldObj != nil {\n\t\t// skip add if node name is identical\n\t\toldAttachment := oldObj.(*storagev1.VolumeAttachment)\n\t\tif oldAttachment.Spec.NodeName == attachment.Spec.NodeName {\n\t\t\treturn\n\t\t}\n\t}\n\tg.graph.AddVolumeAttachment(attachment.Name, attachment.Spec.NodeName)\n}","line":{"from":140,"to":150}} {"id":100013643,"name":"deleteVolumeAttachment","signature":"func (g *graphPopulator) deleteVolumeAttachment(obj interface{})","file":"plugin/pkg/auth/authorizer/node/graph_populator.go","code":"func (g *graphPopulator) deleteVolumeAttachment(obj interface{}) {\n\tif tombstone, ok := obj.(cache.DeletedFinalStateUnknown); ok {\n\t\tobj = tombstone.Obj\n\t}\n\tattachment, ok := obj.(*storagev1.VolumeAttachment)\n\tif !ok {\n\t\tklog.Infof(\"unexpected type %T\", obj)\n\t\treturn\n\t}\n\tg.graph.DeleteVolumeAttachment(attachment.Name)\n}","line":{"from":152,"to":162}} {"id":100013644,"name":"newIntSet","signature":"func newIntSet() *intSet","file":"plugin/pkg/auth/authorizer/node/intset.go","code":"func newIntSet() *intSet {\n\treturn \u0026intSet{members: map[int]int{}}\n}","line":{"from":25,"to":27}} {"id":100013645,"name":"has","signature":"func (s *intSet) has(i int) bool","file":"plugin/pkg/auth/authorizer/node/intset.go","code":"// has returns true if the specified id has a positive refcount.\n// it is safe to call concurrently, but must not be called concurrently with any of the other methods.\nfunc (s *intSet) has(i int) bool {\n\tif s == nil {\n\t\treturn false\n\t}\n\treturn s.members[i] \u003e 0\n}","line":{"from":29,"to":36}} {"id":100013646,"name":"reset","signature":"func (s *intSet) reset()","file":"plugin/pkg/auth/authorizer/node/intset.go","code":"// reset removes all ids, effectively setting their refcounts to 0.\n// it is not thread-safe.\nfunc (s *intSet) reset() {\n\tfor k := range s.members {\n\t\tdelete(s.members, k)\n\t}\n}","line":{"from":38,"to":44}} {"id":100013647,"name":"increment","signature":"func (s *intSet) increment(i int)","file":"plugin/pkg/auth/authorizer/node/intset.go","code":"// increment adds one to the refcount of the specified id.\n// it is not thread-safe.\nfunc (s *intSet) increment(i int) {\n\ts.members[i]++\n}","line":{"from":46,"to":50}} {"id":100013648,"name":"decrement","signature":"func (s *intSet) decrement(i int)","file":"plugin/pkg/auth/authorizer/node/intset.go","code":"// decrement removes one from the refcount of the specified id,\n// and removes the id if the resulting refcount is \u003c= 0.\n// it will not track refcounts lower than zero.\n// it is not thread-safe.\nfunc (s *intSet) decrement(i int) {\n\tif s.members[i] \u003c= 1 {\n\t\tdelete(s.members, i)\n\t} else {\n\t\ts.members[i]--\n\t}\n}","line":{"from":52,"to":62}} {"id":100013649,"name":"RegisterMetrics","signature":"func RegisterMetrics()","file":"plugin/pkg/auth/authorizer/node/metrics.go","code":"// RegisterMetrics registers metrics for node package.\nfunc RegisterMetrics() {\n\tregisterMetrics.Do(func() {\n\t\tlegacyregistry.MustRegister(graphActionsDuration)\n\t})\n}","line":{"from":44,"to":49}} {"id":100013650,"name":"NewAuthorizer","signature":"func NewAuthorizer(graph *Graph, identifier nodeidentifier.NodeIdentifier, rules []rbacv1.PolicyRule) *NodeAuthorizer","file":"plugin/pkg/auth/authorizer/node/node_authorizer.go","code":"// NewAuthorizer returns a new node authorizer\nfunc NewAuthorizer(graph *Graph, identifier nodeidentifier.NodeIdentifier, rules []rbacv1.PolicyRule) *NodeAuthorizer {\n\treturn \u0026NodeAuthorizer{\n\t\tgraph: graph,\n\t\tidentifier: identifier,\n\t\tnodeRules: rules,\n\t\tfeatures: utilfeature.DefaultFeatureGate,\n\t}\n}","line":{"from":64,"to":72}} {"id":100013651,"name":"RulesFor","signature":"func (r *NodeAuthorizer) RulesFor(user user.Info, namespace string) ([]authorizer.ResourceRuleInfo, []authorizer.NonResourceRuleInfo, bool, error)","file":"plugin/pkg/auth/authorizer/node/node_authorizer.go","code":"func (r *NodeAuthorizer) RulesFor(user user.Info, namespace string) ([]authorizer.ResourceRuleInfo, []authorizer.NonResourceRuleInfo, bool, error) {\n\tif _, isNode := r.identifier.NodeIdentity(user); isNode {\n\t\t// indicate nodes do not have fully enumerated permissions\n\t\treturn nil, nil, true, fmt.Errorf(\"node authorizer does not support user rule resolution\")\n\t}\n\treturn nil, nil, false, nil\n}","line":{"from":85,"to":91}} {"id":100013652,"name":"Authorize","signature":"func (r *NodeAuthorizer) Authorize(ctx context.Context, attrs authorizer.Attributes) (authorizer.Decision, string, error)","file":"plugin/pkg/auth/authorizer/node/node_authorizer.go","code":"func (r *NodeAuthorizer) Authorize(ctx context.Context, attrs authorizer.Attributes) (authorizer.Decision, string, error) {\n\tnodeName, isNode := r.identifier.NodeIdentity(attrs.GetUser())\n\tif !isNode {\n\t\t// reject requests from non-nodes\n\t\treturn authorizer.DecisionNoOpinion, \"\", nil\n\t}\n\tif len(nodeName) == 0 {\n\t\t// reject requests from unidentifiable nodes\n\t\tklog.V(2).Infof(\"NODE DENY: unknown node for user %q\", attrs.GetUser().GetName())\n\t\treturn authorizer.DecisionNoOpinion, fmt.Sprintf(\"unknown node for user %q\", attrs.GetUser().GetName()), nil\n\t}\n\n\t// subdivide access to specific resources\n\tif attrs.IsResourceRequest() {\n\t\trequestResource := schema.GroupResource{Group: attrs.GetAPIGroup(), Resource: attrs.GetResource()}\n\t\tswitch requestResource {\n\t\tcase secretResource:\n\t\t\treturn r.authorizeReadNamespacedObject(nodeName, secretVertexType, attrs)\n\t\tcase configMapResource:\n\t\t\treturn r.authorizeReadNamespacedObject(nodeName, configMapVertexType, attrs)\n\t\tcase pvcResource:\n\t\t\tif attrs.GetSubresource() == \"status\" {\n\t\t\t\treturn r.authorizeStatusUpdate(nodeName, pvcVertexType, attrs)\n\t\t\t}\n\t\t\treturn r.authorizeGet(nodeName, pvcVertexType, attrs)\n\t\tcase pvResource:\n\t\t\treturn r.authorizeGet(nodeName, pvVertexType, attrs)\n\t\tcase vaResource:\n\t\t\treturn r.authorizeGet(nodeName, vaVertexType, attrs)\n\t\tcase svcAcctResource:\n\t\t\treturn r.authorizeCreateToken(nodeName, serviceAccountVertexType, attrs)\n\t\tcase leaseResource:\n\t\t\treturn r.authorizeLease(nodeName, attrs)\n\t\tcase csiNodeResource:\n\t\t\treturn r.authorizeCSINode(nodeName, attrs)\n\t\t}\n\n\t}\n\n\t// Access to other resources is not subdivided, so just evaluate against the statically defined node rules\n\tif rbac.RulesAllow(attrs, r.nodeRules...) {\n\t\treturn authorizer.DecisionAllow, \"\", nil\n\t}\n\treturn authorizer.DecisionNoOpinion, \"\", nil\n}","line":{"from":93,"to":137}} {"id":100013653,"name":"authorizeStatusUpdate","signature":"func (r *NodeAuthorizer) authorizeStatusUpdate(nodeName string, startingType vertexType, attrs authorizer.Attributes) (authorizer.Decision, string, error)","file":"plugin/pkg/auth/authorizer/node/node_authorizer.go","code":"// authorizeStatusUpdate authorizes get/update/patch requests to status subresources of the specified type if they are related to the specified node\nfunc (r *NodeAuthorizer) authorizeStatusUpdate(nodeName string, startingType vertexType, attrs authorizer.Attributes) (authorizer.Decision, string, error) {\n\tswitch attrs.GetVerb() {\n\tcase \"update\", \"patch\":\n\t\t// ok\n\tdefault:\n\t\tklog.V(2).Infof(\"NODE DENY: '%s' %#v\", nodeName, attrs)\n\t\treturn authorizer.DecisionNoOpinion, \"can only get/update/patch this type\", nil\n\t}\n\n\tif attrs.GetSubresource() != \"status\" {\n\t\tklog.V(2).Infof(\"NODE DENY: '%s' %#v\", nodeName, attrs)\n\t\treturn authorizer.DecisionNoOpinion, \"can only update status subresource\", nil\n\t}\n\n\treturn r.authorize(nodeName, startingType, attrs)\n}","line":{"from":139,"to":155}} {"id":100013654,"name":"authorizeGet","signature":"func (r *NodeAuthorizer) authorizeGet(nodeName string, startingType vertexType, attrs authorizer.Attributes) (authorizer.Decision, string, error)","file":"plugin/pkg/auth/authorizer/node/node_authorizer.go","code":"// authorizeGet authorizes \"get\" requests to objects of the specified type if they are related to the specified node\nfunc (r *NodeAuthorizer) authorizeGet(nodeName string, startingType vertexType, attrs authorizer.Attributes) (authorizer.Decision, string, error) {\n\tif attrs.GetVerb() != \"get\" {\n\t\tklog.V(2).Infof(\"NODE DENY: '%s' %#v\", nodeName, attrs)\n\t\treturn authorizer.DecisionNoOpinion, \"can only get individual resources of this type\", nil\n\t}\n\tif len(attrs.GetSubresource()) \u003e 0 {\n\t\tklog.V(2).Infof(\"NODE DENY: '%s' %#v\", nodeName, attrs)\n\t\treturn authorizer.DecisionNoOpinion, \"cannot get subresource\", nil\n\t}\n\treturn r.authorize(nodeName, startingType, attrs)\n}","line":{"from":157,"to":168}} {"id":100013655,"name":"authorizeReadNamespacedObject","signature":"func (r *NodeAuthorizer) authorizeReadNamespacedObject(nodeName string, startingType vertexType, attrs authorizer.Attributes) (authorizer.Decision, string, error)","file":"plugin/pkg/auth/authorizer/node/node_authorizer.go","code":"// authorizeReadNamespacedObject authorizes \"get\", \"list\" and \"watch\" requests to single objects of a\n// specified types if they are related to the specified node.\nfunc (r *NodeAuthorizer) authorizeReadNamespacedObject(nodeName string, startingType vertexType, attrs authorizer.Attributes) (authorizer.Decision, string, error) {\n\tswitch attrs.GetVerb() {\n\tcase \"get\", \"list\", \"watch\":\n\t\t//ok\n\tdefault:\n\t\tklog.V(2).Infof(\"NODE DENY: '%s' %#v\", nodeName, attrs)\n\t\treturn authorizer.DecisionNoOpinion, \"can only read resources of this type\", nil\n\t}\n\n\tif len(attrs.GetSubresource()) \u003e 0 {\n\t\tklog.V(2).Infof(\"NODE DENY: '%s' %#v\", nodeName, attrs)\n\t\treturn authorizer.DecisionNoOpinion, \"cannot read subresource\", nil\n\t}\n\tif len(attrs.GetNamespace()) == 0 {\n\t\tklog.V(2).Infof(\"NODE DENY: '%s' %#v\", nodeName, attrs)\n\t\treturn authorizer.DecisionNoOpinion, \"can only read namespaced object of this type\", nil\n\t}\n\treturn r.authorize(nodeName, startingType, attrs)\n}","line":{"from":170,"to":190}} {"id":100013656,"name":"authorize","signature":"func (r *NodeAuthorizer) authorize(nodeName string, startingType vertexType, attrs authorizer.Attributes) (authorizer.Decision, string, error)","file":"plugin/pkg/auth/authorizer/node/node_authorizer.go","code":"func (r *NodeAuthorizer) authorize(nodeName string, startingType vertexType, attrs authorizer.Attributes) (authorizer.Decision, string, error) {\n\tif len(attrs.GetName()) == 0 {\n\t\tklog.V(2).Infof(\"NODE DENY: '%s' %#v\", nodeName, attrs)\n\t\treturn authorizer.DecisionNoOpinion, \"No Object name found\", nil\n\t}\n\n\tok, err := r.hasPathFrom(nodeName, startingType, attrs.GetNamespace(), attrs.GetName())\n\tif err != nil {\n\t\tklog.V(2).InfoS(\"NODE DENY\", \"err\", err)\n\t\treturn authorizer.DecisionNoOpinion, fmt.Sprintf(\"no relationship found between node '%s' and this object\", nodeName), nil\n\t}\n\tif !ok {\n\t\tklog.V(2).Infof(\"NODE DENY: '%s' %#v\", nodeName, attrs)\n\t\treturn authorizer.DecisionNoOpinion, fmt.Sprintf(\"no relationship found between node '%s' and this object\", nodeName), nil\n\t}\n\treturn authorizer.DecisionAllow, \"\", nil\n}","line":{"from":192,"to":208}} {"id":100013657,"name":"authorizeCreateToken","signature":"func (r *NodeAuthorizer) authorizeCreateToken(nodeName string, startingType vertexType, attrs authorizer.Attributes) (authorizer.Decision, string, error)","file":"plugin/pkg/auth/authorizer/node/node_authorizer.go","code":"// authorizeCreateToken authorizes \"create\" requests to serviceaccounts 'token'\n// subresource of pods running on a node\nfunc (r *NodeAuthorizer) authorizeCreateToken(nodeName string, startingType vertexType, attrs authorizer.Attributes) (authorizer.Decision, string, error) {\n\tif attrs.GetVerb() != \"create\" || len(attrs.GetName()) == 0 {\n\t\tklog.V(2).Infof(\"NODE DENY: '%s' %#v\", nodeName, attrs)\n\t\treturn authorizer.DecisionNoOpinion, \"can only create tokens for individual service accounts\", nil\n\t}\n\n\tif attrs.GetSubresource() != \"token\" {\n\t\tklog.V(2).Infof(\"NODE DENY: '%s' %#v\", nodeName, attrs)\n\t\treturn authorizer.DecisionNoOpinion, \"can only create token subresource of serviceaccount\", nil\n\t}\n\n\tok, err := r.hasPathFrom(nodeName, startingType, attrs.GetNamespace(), attrs.GetName())\n\tif err != nil {\n\t\tklog.V(2).Infof(\"NODE DENY: %v\", err)\n\t\treturn authorizer.DecisionNoOpinion, fmt.Sprintf(\"no relationship found between node '%s' and this object\", nodeName), nil\n\t}\n\tif !ok {\n\t\tklog.V(2).Infof(\"NODE DENY: '%s' %#v\", nodeName, attrs)\n\t\treturn authorizer.DecisionNoOpinion, fmt.Sprintf(\"no relationship found between node '%s' and this object\", nodeName), nil\n\t}\n\treturn authorizer.DecisionAllow, \"\", nil\n}","line":{"from":210,"to":233}} {"id":100013658,"name":"authorizeLease","signature":"func (r *NodeAuthorizer) authorizeLease(nodeName string, attrs authorizer.Attributes) (authorizer.Decision, string, error)","file":"plugin/pkg/auth/authorizer/node/node_authorizer.go","code":"// authorizeLease authorizes node requests to coordination.k8s.io/leases.\nfunc (r *NodeAuthorizer) authorizeLease(nodeName string, attrs authorizer.Attributes) (authorizer.Decision, string, error) {\n\t// allowed verbs: get, create, update, patch, delete\n\tverb := attrs.GetVerb()\n\tswitch verb {\n\tcase \"get\", \"create\", \"update\", \"patch\", \"delete\":\n\t\t//ok\n\tdefault:\n\t\tklog.V(2).Infof(\"NODE DENY: '%s' %#v\", nodeName, attrs)\n\t\treturn authorizer.DecisionNoOpinion, \"can only get, create, update, patch, or delete a node lease\", nil\n\t}\n\n\t// the request must be against the system namespace reserved for node leases\n\tif attrs.GetNamespace() != api.NamespaceNodeLease {\n\t\tklog.V(2).Infof(\"NODE DENY: '%s' %#v\", nodeName, attrs)\n\t\treturn authorizer.DecisionNoOpinion, fmt.Sprintf(\"can only access leases in the %q system namespace\", api.NamespaceNodeLease), nil\n\t}\n\n\t// the request must come from a node with the same name as the lease\n\t// note we skip this check for create, since the authorizer doesn't know the name on create\n\t// the noderestriction admission plugin is capable of performing this check at create time\n\tif verb != \"create\" \u0026\u0026 attrs.GetName() != nodeName {\n\t\tklog.V(2).Infof(\"NODE DENY: '%s' %#v\", nodeName, attrs)\n\t\treturn authorizer.DecisionNoOpinion, \"can only access node lease with the same name as the requesting node\", nil\n\t}\n\n\treturn authorizer.DecisionAllow, \"\", nil\n}","line":{"from":235,"to":262}} {"id":100013659,"name":"authorizeCSINode","signature":"func (r *NodeAuthorizer) authorizeCSINode(nodeName string, attrs authorizer.Attributes) (authorizer.Decision, string, error)","file":"plugin/pkg/auth/authorizer/node/node_authorizer.go","code":"// authorizeCSINode authorizes node requests to CSINode storage.k8s.io/csinodes\nfunc (r *NodeAuthorizer) authorizeCSINode(nodeName string, attrs authorizer.Attributes) (authorizer.Decision, string, error) {\n\t// allowed verbs: get, create, update, patch, delete\n\tverb := attrs.GetVerb()\n\tswitch verb {\n\tcase \"get\", \"create\", \"update\", \"patch\", \"delete\":\n\t\t//ok\n\tdefault:\n\t\tklog.V(2).Infof(\"NODE DENY: '%s' %#v\", nodeName, attrs)\n\t\treturn authorizer.DecisionNoOpinion, \"can only get, create, update, patch, or delete a CSINode\", nil\n\t}\n\n\tif len(attrs.GetSubresource()) \u003e 0 {\n\t\tklog.V(2).Infof(\"NODE DENY: '%s' %#v\", nodeName, attrs)\n\t\treturn authorizer.DecisionNoOpinion, \"cannot authorize CSINode subresources\", nil\n\t}\n\n\t// the request must come from a node with the same name as the CSINode\n\t// note we skip this check for create, since the authorizer doesn't know the name on create\n\t// the noderestriction admission plugin is capable of performing this check at create time\n\tif verb != \"create\" \u0026\u0026 attrs.GetName() != nodeName {\n\t\tklog.V(2).Infof(\"NODE DENY: '%s' %#v\", nodeName, attrs)\n\t\treturn authorizer.DecisionNoOpinion, \"can only access CSINode with the same name as the requesting node\", nil\n\t}\n\n\treturn authorizer.DecisionAllow, \"\", nil\n}","line":{"from":264,"to":290}} {"id":100013660,"name":"hasPathFrom","signature":"func (r *NodeAuthorizer) hasPathFrom(nodeName string, startingType vertexType, startingNamespace, startingName string) (bool, error)","file":"plugin/pkg/auth/authorizer/node/node_authorizer.go","code":"// hasPathFrom returns true if there is a directed path from the specified type/namespace/name to the specified Node\nfunc (r *NodeAuthorizer) hasPathFrom(nodeName string, startingType vertexType, startingNamespace, startingName string) (bool, error) {\n\tr.graph.lock.RLock()\n\tdefer r.graph.lock.RUnlock()\n\n\tnodeVertex, exists := r.graph.getVertex_rlocked(nodeVertexType, \"\", nodeName)\n\tif !exists {\n\t\treturn false, fmt.Errorf(\"unknown node '%s' cannot get %s %s/%s\", nodeName, vertexTypes[startingType], startingNamespace, startingName)\n\t}\n\n\tstartingVertex, exists := r.graph.getVertex_rlocked(startingType, startingNamespace, startingName)\n\tif !exists {\n\t\treturn false, fmt.Errorf(\"node '%s' cannot get unknown %s %s/%s\", nodeName, vertexTypes[startingType], startingNamespace, startingName)\n\t}\n\n\t// Fast check to see if we know of a destination edge\n\tif r.graph.destinationEdgeIndex[startingVertex.ID()].has(nodeVertex.ID()) {\n\t\treturn true, nil\n\t}\n\n\tfound := false\n\ttraversal := \u0026traverse.VisitingDepthFirst{\n\t\tEdgeFilter: func(edge graph.Edge) bool {\n\t\t\tif destinationEdge, ok := edge.(*destinationEdge); ok {\n\t\t\t\tif destinationEdge.DestinationID() != nodeVertex.ID() {\n\t\t\t\t\t// Don't follow edges leading to other nodes\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\t// We found an edge leading to the node we want\n\t\t\t\tfound = true\n\t\t\t}\n\t\t\t// Visit this edge\n\t\t\treturn true\n\t\t},\n\t}\n\ttraversal.Walk(r.graph.graph, startingVertex, func(n graph.Node) bool {\n\t\tif n.ID() == nodeVertex.ID() {\n\t\t\t// We found the node we want\n\t\t\tfound = true\n\t\t}\n\t\t// Stop visiting if we've found the node we want\n\t\treturn found\n\t})\n\tif !found {\n\t\treturn false, fmt.Errorf(\"node '%s' cannot get %s %s/%s, no relationship to this object was found in the node authorizer graph\", nodeName, vertexTypes[startingType], startingNamespace, startingName)\n\t}\n\treturn true, nil\n}","line":{"from":292,"to":339}} {"id":100013661,"name":"addControllerRole","signature":"func addControllerRole(controllerRoles *[]rbacv1.ClusterRole, controllerRoleBindings *[]rbacv1.ClusterRoleBinding, role rbacv1.ClusterRole)","file":"plugin/pkg/auth/authorizer/rbac/bootstrappolicy/controller_policy.go","code":"func addControllerRole(controllerRoles *[]rbacv1.ClusterRole, controllerRoleBindings *[]rbacv1.ClusterRoleBinding, role rbacv1.ClusterRole) {\n\tif !strings.HasPrefix(role.Name, saRolePrefix) {\n\t\tklog.Fatalf(`role %q must start with %q`, role.Name, saRolePrefix)\n\t}\n\n\tfor _, existingRole := range *controllerRoles {\n\t\tif role.Name == existingRole.Name {\n\t\t\tklog.Fatalf(\"role %q was already registered\", role.Name)\n\t\t}\n\t}\n\n\t*controllerRoles = append(*controllerRoles, role)\n\taddClusterRoleLabel(*controllerRoles)\n\n\t*controllerRoleBindings = append(*controllerRoleBindings,\n\t\trbacv1helpers.NewClusterBinding(role.Name).SAs(\"kube-system\", role.Name[len(saRolePrefix):]).BindingOrDie())\n\taddClusterRoleBindingLabel(*controllerRoleBindings)\n}","line":{"from":35,"to":52}} {"id":100013662,"name":"eventsRule","signature":"func eventsRule() rbacv1.PolicyRule","file":"plugin/pkg/auth/authorizer/rbac/bootstrappolicy/controller_policy.go","code":"func eventsRule() rbacv1.PolicyRule {\n\treturn rbacv1helpers.NewRule(\"create\", \"update\", \"patch\").Groups(legacyGroup, eventsGroup).Resources(\"events\").RuleOrDie()\n}","line":{"from":54,"to":56}} {"id":100013663,"name":"buildControllerRoles","signature":"func buildControllerRoles() ([]rbacv1.ClusterRole, []rbacv1.ClusterRoleBinding)","file":"plugin/pkg/auth/authorizer/rbac/bootstrappolicy/controller_policy.go","code":"func buildControllerRoles() ([]rbacv1.ClusterRole, []rbacv1.ClusterRoleBinding) {\n\t// controllerRoles is a slice of roles used for controllers\n\tcontrollerRoles := []rbacv1.ClusterRole{}\n\t// controllerRoleBindings is a slice of roles used for controllers\n\tcontrollerRoleBindings := []rbacv1.ClusterRoleBinding{}\n\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, func() rbacv1.ClusterRole {\n\t\trole := rbacv1.ClusterRole{\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"attachdetach-controller\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\trbacv1helpers.NewRule(\"list\", \"watch\").Groups(legacyGroup).Resources(\"persistentvolumes\", \"persistentvolumeclaims\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(legacyGroup).Resources(\"nodes\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"patch\", \"update\").Groups(legacyGroup).Resources(\"nodes/status\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"list\", \"watch\").Groups(legacyGroup).Resources(\"pods\").RuleOrDie(),\n\t\t\t\teventsRule(),\n\t\t\t\trbacv1helpers.NewRule(\"get\", \"create\", \"delete\", \"list\", \"watch\").Groups(storageGroup).Resources(\"volumeattachments\").RuleOrDie(),\n\t\t\t},\n\t\t}\n\n\t\trole.Rules = append(role.Rules, rbacv1helpers.NewRule(\"get\", \"watch\", \"list\").Groups(\"storage.k8s.io\").Resources(\"csidrivers\").RuleOrDie())\n\t\trole.Rules = append(role.Rules, rbacv1helpers.NewRule(\"get\", \"watch\", \"list\").Groups(\"storage.k8s.io\").Resources(\"csinodes\").RuleOrDie())\n\n\t\treturn role\n\t}())\n\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"clusterrole-aggregation-controller\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\t// this controller must have full permissions on clusterroles to allow it to mutate them in any way\n\t\t\trbacv1helpers.NewRule(\"escalate\", \"get\", \"list\", \"watch\", \"update\", \"patch\").Groups(rbacGroup).Resources(\"clusterroles\").RuleOrDie(),\n\t\t},\n\t})\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"cronjob-controller\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\", \"update\").Groups(batchGroup).Resources(\"cronjobs\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\", \"create\", \"update\", \"delete\", \"patch\").Groups(batchGroup).Resources(\"jobs\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"update\").Groups(batchGroup).Resources(\"cronjobs/status\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"update\").Groups(batchGroup).Resources(\"cronjobs/finalizers\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"list\", \"delete\").Groups(legacyGroup).Resources(\"pods\").RuleOrDie(),\n\t\t\teventsRule(),\n\t\t},\n\t})\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"daemon-set-controller\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(extensionsGroup, appsGroup).Resources(\"daemonsets\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"update\").Groups(extensionsGroup, appsGroup).Resources(\"daemonsets/status\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"update\").Groups(extensionsGroup, appsGroup).Resources(\"daemonsets/finalizers\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"list\", \"watch\").Groups(legacyGroup).Resources(\"nodes\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"list\", \"watch\", \"create\", \"delete\", \"patch\").Groups(legacyGroup).Resources(\"pods\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"create\").Groups(legacyGroup).Resources(\"pods/binding\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\", \"create\", \"delete\", \"update\", \"patch\").Groups(appsGroup).Resources(\"controllerrevisions\").RuleOrDie(),\n\t\t\teventsRule(),\n\t\t},\n\t})\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"deployment-controller\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\", \"update\").Groups(extensionsGroup, appsGroup).Resources(\"deployments\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"update\").Groups(extensionsGroup, appsGroup).Resources(\"deployments/status\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"update\").Groups(extensionsGroup, appsGroup).Resources(\"deployments/finalizers\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\", \"create\", \"update\", \"patch\", \"delete\").Groups(appsGroup, extensionsGroup).Resources(\"replicasets\").RuleOrDie(),\n\t\t\t// TODO: remove \"update\" once\n\t\t\t// https://github.com/kubernetes/kubernetes/issues/36897 is resolved.\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\", \"update\").Groups(legacyGroup).Resources(\"pods\").RuleOrDie(),\n\t\t\teventsRule(),\n\t\t},\n\t})\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, func() rbacv1.ClusterRole {\n\t\trole := rbacv1.ClusterRole{\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"disruption-controller\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(extensionsGroup, appsGroup).Resources(\"deployments\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(appsGroup, extensionsGroup).Resources(\"replicasets\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(legacyGroup).Resources(\"replicationcontrollers\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(policyGroup).Resources(\"poddisruptionbudgets\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(appsGroup).Resources(\"statefulsets\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"update\").Groups(policyGroup).Resources(\"poddisruptionbudgets/status\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"get\").Groups(\"*\").Resources(\"*/scale\").RuleOrDie(),\n\t\t\t\teventsRule(),\n\t\t\t},\n\t\t}\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.PodDisruptionConditions) {\n\t\t\trole.Rules = append(role.Rules, rbacv1helpers.NewRule(\"patch\").Groups(legacyGroup).Resources(\"pods/status\").RuleOrDie())\n\t\t}\n\t\treturn role\n\t}())\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"endpoint-controller\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(legacyGroup).Resources(\"services\", \"pods\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"create\", \"update\", \"delete\").Groups(legacyGroup).Resources(\"endpoints\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"create\").Groups(legacyGroup).Resources(\"endpoints/restricted\").RuleOrDie(),\n\t\t\teventsRule(),\n\t\t},\n\t})\n\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"endpointslice-controller\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(legacyGroup).Resources(\"services\", \"pods\", \"nodes\").RuleOrDie(),\n\t\t\t// The controller needs to be able to set a service's finalizers to be able to create an EndpointSlice\n\t\t\t// resource that is owned by the service and sets blockOwnerDeletion=true in its ownerRef.\n\t\t\trbacv1helpers.NewRule(\"update\").Groups(legacyGroup).Resources(\"services/finalizers\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"create\", \"update\", \"delete\").Groups(discoveryGroup).Resources(\"endpointslices\").RuleOrDie(),\n\t\t\teventsRule(),\n\t\t},\n\t})\n\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"endpointslicemirroring-controller\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(legacyGroup).Resources(\"services\", \"endpoints\").RuleOrDie(),\n\t\t\t// The controller needs to be able to set a service's finalizers to be able to create an EndpointSlice\n\t\t\t// resource that is owned by the service and sets blockOwnerDeletion=true in its ownerRef.\n\t\t\trbacv1helpers.NewRule(\"update\").Groups(legacyGroup).Resources(\"services/finalizers\").RuleOrDie(),\n\t\t\t// The controller needs to be able to set a service's finalizers to be able to create an EndpointSlice\n\t\t\t// resource that is owned by the endpoint and sets blockOwnerDeletion=true in its ownerRef.\n\t\t\t// see https://github.com/openshift/kubernetes/blob/8691466059314c3f7d6dcffcbb76d14596ca716c/pkg/controller/endpointslicemirroring/utils.go#L87-L88\n\t\t\trbacv1helpers.NewRule(\"update\").Groups(legacyGroup).Resources(\"endpoints/finalizers\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"create\", \"update\", \"delete\").Groups(discoveryGroup).Resources(\"endpointslices\").RuleOrDie(),\n\t\t\teventsRule(),\n\t\t},\n\t})\n\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"expand-controller\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\", \"update\", \"patch\").Groups(legacyGroup).Resources(\"persistentvolumes\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"update\", \"patch\").Groups(legacyGroup).Resources(\"persistentvolumeclaims/status\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(legacyGroup).Resources(\"persistentvolumeclaims\").RuleOrDie(),\n\t\t\t// glusterfs\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(storageGroup).Resources(\"storageclasses\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"get\").Groups(legacyGroup).Resources(\"services\", \"endpoints\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"get\").Groups(legacyGroup).Resources(\"secrets\").RuleOrDie(),\n\t\t\teventsRule(),\n\t\t},\n\t})\n\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"ephemeral-volume-controller\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(legacyGroup).Resources(\"pods\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"update\").Groups(legacyGroup).Resources(\"pods/finalizers\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\", \"create\").Groups(legacyGroup).Resources(\"persistentvolumeclaims\").RuleOrDie(),\n\t\t\teventsRule(),\n\t\t},\n\t})\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.DynamicResourceAllocation) {\n\t\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"resource-claim-controller\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(legacyGroup).Resources(\"pods\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"update\").Groups(legacyGroup).Resources(\"pods/finalizers\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\", \"create\").Groups(resourceGroup).Resources(\"resourceclaims\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"update\", \"patch\").Groups(resourceGroup).Resources(\"resourceclaims/status\").RuleOrDie(),\n\t\t\t\teventsRule(),\n\t\t\t},\n\t\t})\n\t}\n\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"generic-garbage-collector\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\t// the GC controller needs to run list/watches, selective gets, and updates against any resource\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\", \"patch\", \"update\", \"delete\").Groups(\"*\").Resources(\"*\").RuleOrDie(),\n\t\t\teventsRule(),\n\t\t},\n\t})\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"horizontal-pod-autoscaler\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(autoscalingGroup).Resources(\"horizontalpodautoscalers\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"update\").Groups(autoscalingGroup).Resources(\"horizontalpodautoscalers/status\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"get\", \"update\").Groups(\"*\").Resources(\"*/scale\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"list\").Groups(legacyGroup).Resources(\"pods\").RuleOrDie(),\n\t\t\t// allow listing resource, custom, and external metrics\n\t\t\trbacv1helpers.NewRule(\"list\").Groups(resMetricsGroup).Resources(\"pods\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\").Groups(customMetricsGroup).Resources(\"*\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\").Groups(externalMetricsGroup).Resources(\"*\").RuleOrDie(),\n\t\t\teventsRule(),\n\t\t},\n\t})\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"job-controller\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\", \"update\", \"patch\").Groups(batchGroup).Resources(\"jobs\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"update\").Groups(batchGroup).Resources(\"jobs/status\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"update\").Groups(batchGroup).Resources(\"jobs/finalizers\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"list\", \"watch\", \"create\", \"delete\", \"patch\").Groups(legacyGroup).Resources(\"pods\").RuleOrDie(),\n\t\t\teventsRule(),\n\t\t},\n\t})\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"namespace-controller\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\", \"delete\").Groups(legacyGroup).Resources(\"namespaces\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"update\").Groups(legacyGroup).Resources(\"namespaces/finalize\", \"namespaces/status\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"delete\", \"deletecollection\").Groups(\"*\").Resources(\"*\").RuleOrDie(),\n\t\t},\n\t})\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, func() rbacv1.ClusterRole {\n\t\trole := rbacv1.ClusterRole{\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"node-controller\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"update\", \"delete\", \"patch\").Groups(legacyGroup).Resources(\"nodes\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"patch\", \"update\").Groups(legacyGroup).Resources(\"nodes/status\").RuleOrDie(),\n\t\t\t\t// used for pod deletion\n\t\t\t\trbacv1helpers.NewRule(\"patch\", \"update\").Groups(legacyGroup).Resources(\"pods/status\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"list\", \"delete\").Groups(legacyGroup).Resources(\"pods\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"create\", \"update\").Groups(networkingGroup).Resources(\"clustercidrs\").RuleOrDie(),\n\t\t\t\teventsRule(),\n\t\t\t},\n\t\t}\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.PodDisruptionConditions) {\n\t\t\trole.Rules = append(role.Rules, rbacv1helpers.NewRule(\"get\").Groups(legacyGroup).Resources(\"pods\").RuleOrDie())\n\t\t}\n\t\treturn role\n\t}())\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"persistent-volume-binder\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\", \"update\", \"create\", \"delete\").Groups(legacyGroup).Resources(\"persistentvolumes\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"update\").Groups(legacyGroup).Resources(\"persistentvolumes/status\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\", \"update\").Groups(legacyGroup).Resources(\"persistentvolumeclaims\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"update\").Groups(legacyGroup).Resources(\"persistentvolumeclaims/status\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"list\", \"watch\", \"get\", \"create\", \"delete\").Groups(legacyGroup).Resources(\"pods\").RuleOrDie(),\n\n\t\t\t// glusterfs\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(storageGroup).Resources(\"storageclasses\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"get\", \"create\", \"update\", \"delete\").Groups(legacyGroup).Resources(\"endpoints\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"get\", \"create\", \"delete\").Groups(legacyGroup).Resources(\"services\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"get\").Groups(legacyGroup).Resources(\"secrets\").RuleOrDie(),\n\t\t\t// openstack\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\").Groups(legacyGroup).Resources(\"nodes\").RuleOrDie(),\n\n\t\t\t// recyclerClient.WatchPod\n\t\t\trbacv1helpers.NewRule(\"watch\").Groups(legacyGroup).Resources(\"events\").RuleOrDie(),\n\n\t\t\teventsRule(),\n\t\t},\n\t})\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, func() rbacv1.ClusterRole {\n\t\trole := rbacv1.ClusterRole{\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"pod-garbage-collector\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\trbacv1helpers.NewRule(\"list\", \"watch\", \"delete\").Groups(legacyGroup).Resources(\"pods\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"get\", \"list\").Groups(legacyGroup).Resources(\"nodes\").RuleOrDie(),\n\t\t\t},\n\t\t}\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.PodDisruptionConditions) {\n\t\t\trole.Rules = append(role.Rules, rbacv1helpers.NewRule(\"patch\").Groups(legacyGroup).Resources(\"pods/status\").RuleOrDie())\n\t\t}\n\t\treturn role\n\t}())\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"replicaset-controller\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\", \"update\").Groups(appsGroup, extensionsGroup).Resources(\"replicasets\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"update\").Groups(appsGroup, extensionsGroup).Resources(\"replicasets/status\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"update\").Groups(appsGroup, extensionsGroup).Resources(\"replicasets/finalizers\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"list\", \"watch\", \"patch\", \"create\", \"delete\").Groups(legacyGroup).Resources(\"pods\").RuleOrDie(),\n\t\t\teventsRule(),\n\t\t},\n\t})\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"replication-controller\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\t// 1.0 controllers needed get, update, so without these old controllers break on new servers\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\", \"update\").Groups(legacyGroup).Resources(\"replicationcontrollers\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"update\").Groups(legacyGroup).Resources(\"replicationcontrollers/status\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"update\").Groups(legacyGroup).Resources(\"replicationcontrollers/finalizers\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"list\", \"watch\", \"patch\", \"create\", \"delete\").Groups(legacyGroup).Resources(\"pods\").RuleOrDie(),\n\t\t\teventsRule(),\n\t\t},\n\t})\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"resourcequota-controller\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\t// quota can count quota on anything for reconciliation, so it needs full viewing powers\n\t\t\trbacv1helpers.NewRule(\"list\", \"watch\").Groups(\"*\").Resources(\"*\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"update\").Groups(legacyGroup).Resources(\"resourcequotas/status\").RuleOrDie(),\n\t\t\teventsRule(),\n\t\t},\n\t})\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"route-controller\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"list\", \"watch\").Groups(legacyGroup).Resources(\"nodes\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"patch\").Groups(legacyGroup).Resources(\"nodes/status\").RuleOrDie(),\n\t\t\teventsRule(),\n\t\t},\n\t})\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"service-account-controller\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"create\").Groups(legacyGroup).Resources(\"serviceaccounts\").RuleOrDie(),\n\t\t\teventsRule(),\n\t\t},\n\t})\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"service-controller\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(legacyGroup).Resources(\"services\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"patch\", \"update\").Groups(legacyGroup).Resources(\"services/status\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"list\", \"watch\").Groups(legacyGroup).Resources(\"nodes\").RuleOrDie(),\n\t\t\teventsRule(),\n\t\t},\n\t})\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, func() rbacv1.ClusterRole {\n\t\trole := rbacv1.ClusterRole{\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"statefulset-controller\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\trbacv1helpers.NewRule(\"list\", \"watch\").Groups(legacyGroup).Resources(\"pods\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(appsGroup).Resources(\"statefulsets\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"update\").Groups(appsGroup).Resources(\"statefulsets/status\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"update\").Groups(appsGroup).Resources(\"statefulsets/finalizers\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"get\", \"create\", \"delete\", \"update\", \"patch\").Groups(legacyGroup).Resources(\"pods\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"get\", \"create\", \"delete\", \"update\", \"patch\", \"list\", \"watch\").Groups(appsGroup).Resources(\"controllerrevisions\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"get\", \"create\").Groups(legacyGroup).Resources(\"persistentvolumeclaims\").RuleOrDie(),\n\t\t\t\teventsRule(),\n\t\t\t},\n\t\t}\n\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.StatefulSetAutoDeletePVC) {\n\t\t\trole.Rules = append(role.Rules, rbacv1helpers.NewRule(\"update\", \"delete\").Groups(legacyGroup).Resources(\"persistentvolumeclaims\").RuleOrDie())\n\t\t}\n\n\t\treturn role\n\t}())\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"ttl-controller\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"update\", \"patch\", \"list\", \"watch\").Groups(legacyGroup).Resources(\"nodes\").RuleOrDie(),\n\t\t\teventsRule(),\n\t\t},\n\t})\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"certificate-controller\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\", \"delete\").Groups(certificatesGroup).Resources(\"certificatesigningrequests\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"update\").Groups(certificatesGroup).Resources(\"certificatesigningrequests/status\", \"certificatesigningrequests/approval\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"approve\").Groups(certificatesGroup).Resources(\"signers\").Names(capi.KubeAPIServerClientKubeletSignerName).RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"sign\").Groups(certificatesGroup).Resources(\"signers\").Names(\n\t\t\t\tcapi.LegacyUnknownSignerName,\n\t\t\t\tcapi.KubeAPIServerClientSignerName,\n\t\t\t\tcapi.KubeAPIServerClientKubeletSignerName,\n\t\t\t\tcapi.KubeletServingSignerName,\n\t\t\t).RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"create\").Groups(authorizationGroup).Resources(\"subjectaccessreviews\").RuleOrDie(),\n\t\t\teventsRule(),\n\t\t},\n\t})\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"pvc-protection-controller\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\", \"update\").Groups(legacyGroup).Resources(\"persistentvolumeclaims\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"list\", \"watch\", \"get\").Groups(legacyGroup).Resources(\"pods\").RuleOrDie(),\n\t\t\teventsRule(),\n\t\t},\n\t})\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"pv-protection-controller\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\", \"update\").Groups(legacyGroup).Resources(\"persistentvolumes\").RuleOrDie(),\n\t\t\teventsRule(),\n\t\t},\n\t})\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"ttl-after-finished-controller\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\", \"delete\").Groups(batchGroup).Resources(\"jobs\").RuleOrDie(),\n\t\t\teventsRule(),\n\t\t},\n\t})\n\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"root-ca-cert-publisher\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"create\", \"update\").Groups(legacyGroup).Resources(\"configmaps\").RuleOrDie(),\n\t\t\teventsRule(),\n\t\t},\n\t})\n\tif utilfeature.DefaultFeatureGate.Enabled(genericfeatures.StorageVersionAPI) \u0026\u0026\n\t\tutilfeature.DefaultFeatureGate.Enabled(genericfeatures.APIServerIdentity) {\n\t\taddControllerRole(\u0026controllerRoles, \u0026controllerRoleBindings, rbacv1.ClusterRole{\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"storage-version-garbage-collector\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(coordinationGroup).Resources(\"leases\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\", \"patch\", \"update\", \"delete\").Groups(internalAPIServerGroup).\n\t\t\t\t\tResources(\"storageversions\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"get\", \"patch\", \"update\").Groups(internalAPIServerGroup).\n\t\t\t\t\tResources(\"storageversions/status\").RuleOrDie(),\n\t\t\t},\n\t\t})\n\t}\n\n\treturn controllerRoles, controllerRoleBindings\n}","line":{"from":58,"to":457}} {"id":100013664,"name":"ControllerRoles","signature":"func ControllerRoles() []rbacv1.ClusterRole","file":"plugin/pkg/auth/authorizer/rbac/bootstrappolicy/controller_policy.go","code":"// ControllerRoles returns the cluster roles used by controllers\nfunc ControllerRoles() []rbacv1.ClusterRole {\n\tcontrollerRoles, _ := buildControllerRoles()\n\treturn controllerRoles\n}","line":{"from":459,"to":463}} {"id":100013665,"name":"ControllerRoleBindings","signature":"func ControllerRoleBindings() []rbacv1.ClusterRoleBinding","file":"plugin/pkg/auth/authorizer/rbac/bootstrappolicy/controller_policy.go","code":"// ControllerRoleBindings returns the role bindings used by controllers\nfunc ControllerRoleBindings() []rbacv1.ClusterRoleBinding {\n\t_, controllerRoleBindings := buildControllerRoles()\n\treturn controllerRoleBindings\n}","line":{"from":465,"to":469}} {"id":100013666,"name":"addNamespaceRole","signature":"func addNamespaceRole(namespace string, role rbacv1.Role)","file":"plugin/pkg/auth/authorizer/rbac/bootstrappolicy/namespace_policy.go","code":"func addNamespaceRole(namespace string, role rbacv1.Role) {\n\tif !strings.HasPrefix(namespace, \"kube-\") {\n\t\tklog.Fatalf(`roles can only be bootstrapped into reserved namespaces starting with \"kube-\", not %q`, namespace)\n\t}\n\n\texistingRoles := namespaceRoles[namespace]\n\tfor _, existingRole := range existingRoles {\n\t\tif role.Name == existingRole.Name {\n\t\t\tklog.Fatalf(\"role %q was already registered in %q\", role.Name, namespace)\n\t\t}\n\t}\n\n\trole.Namespace = namespace\n\taddDefaultMetadata(\u0026role)\n\texistingRoles = append(existingRoles, role)\n\tnamespaceRoles[namespace] = existingRoles\n}","line":{"from":38,"to":54}} {"id":100013667,"name":"addNamespaceRoleBinding","signature":"func addNamespaceRoleBinding(namespace string, roleBinding rbacv1.RoleBinding)","file":"plugin/pkg/auth/authorizer/rbac/bootstrappolicy/namespace_policy.go","code":"func addNamespaceRoleBinding(namespace string, roleBinding rbacv1.RoleBinding) {\n\tif !strings.HasPrefix(namespace, \"kube-\") {\n\t\tklog.Fatalf(`rolebindings can only be bootstrapped into reserved namespaces starting with \"kube-\", not %q`, namespace)\n\t}\n\n\texistingRoleBindings := namespaceRoleBindings[namespace]\n\tfor _, existingRoleBinding := range existingRoleBindings {\n\t\tif roleBinding.Name == existingRoleBinding.Name {\n\t\t\tklog.Fatalf(\"rolebinding %q was already registered in %q\", roleBinding.Name, namespace)\n\t\t}\n\t}\n\n\troleBinding.Namespace = namespace\n\taddDefaultMetadata(\u0026roleBinding)\n\texistingRoleBindings = append(existingRoleBindings, roleBinding)\n\tnamespaceRoleBindings[namespace] = existingRoleBindings\n}","line":{"from":56,"to":72}} {"id":100013668,"name":"init","signature":"func init()","file":"plugin/pkg/auth/authorizer/rbac/bootstrappolicy/namespace_policy.go","code":"func init() {\n\taddNamespaceRole(metav1.NamespaceSystem, rbacv1.Role{\n\t\t// role for finding authentication config info for starting a server\n\t\tObjectMeta: metav1.ObjectMeta{Name: \"extension-apiserver-authentication-reader\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\t// this particular config map is exposed and contains authentication configuration information\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(legacyGroup).Resources(\"configmaps\").Names(\"extension-apiserver-authentication\").RuleOrDie(),\n\t\t},\n\t})\n\taddNamespaceRole(metav1.NamespaceSystem, rbacv1.Role{\n\t\t// role for the bootstrap signer to be able to inspect kube-system secrets\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"bootstrap-signer\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(legacyGroup).Resources(\"secrets\").RuleOrDie(),\n\t\t},\n\t})\n\taddNamespaceRole(metav1.NamespaceSystem, rbacv1.Role{\n\t\t// role for the cloud providers to access/create kube-system configmaps\n\t\t// Deprecated starting Kubernetes 1.10 and will be deleted according to GA deprecation policy.\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"cloud-provider\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"create\", \"get\", \"list\", \"watch\").Groups(legacyGroup).Resources(\"configmaps\").RuleOrDie(),\n\t\t},\n\t})\n\taddNamespaceRole(metav1.NamespaceSystem, rbacv1.Role{\n\t\t// role for the token-cleaner to be able to remove secrets, but only in kube-system\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"token-cleaner\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\", \"delete\").Groups(legacyGroup).Resources(\"secrets\").RuleOrDie(),\n\t\t\teventsRule(),\n\t\t},\n\t})\n\t// TODO: Create util on Role+Binding for leader locking if more cases evolve.\n\taddNamespaceRole(metav1.NamespaceSystem, rbacv1.Role{\n\t\t// role for the leader locking on supplied configmap\n\t\tObjectMeta: metav1.ObjectMeta{Name: \"system::leader-locking-kube-controller-manager\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"watch\").Groups(legacyGroup).Resources(\"configmaps\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"get\", \"update\").Groups(legacyGroup).Resources(\"configmaps\").Names(\"kube-controller-manager\").RuleOrDie(),\n\t\t},\n\t})\n\taddNamespaceRole(metav1.NamespaceSystem, rbacv1.Role{\n\t\t// role for the leader locking on supplied configmap\n\t\tObjectMeta: metav1.ObjectMeta{Name: \"system::leader-locking-kube-scheduler\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"watch\").Groups(legacyGroup).Resources(\"configmaps\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"get\", \"update\").Groups(legacyGroup).Resources(\"configmaps\").Names(\"kube-scheduler\").RuleOrDie(),\n\t\t},\n\t})\n\n\tdelegatedAuthBinding := rbacv1helpers.NewRoleBinding(\"extension-apiserver-authentication-reader\", metav1.NamespaceSystem).Users(user.KubeControllerManager, user.KubeScheduler).BindingOrDie()\n\tdelegatedAuthBinding.Name = \"system::extension-apiserver-authentication-reader\"\n\taddNamespaceRoleBinding(metav1.NamespaceSystem, delegatedAuthBinding)\n\n\taddNamespaceRoleBinding(metav1.NamespaceSystem,\n\t\trbacv1helpers.NewRoleBinding(\"system::leader-locking-kube-controller-manager\", metav1.NamespaceSystem).Users(user.KubeControllerManager).SAs(metav1.NamespaceSystem, \"kube-controller-manager\").BindingOrDie())\n\taddNamespaceRoleBinding(metav1.NamespaceSystem,\n\t\trbacv1helpers.NewRoleBinding(\"system::leader-locking-kube-scheduler\", metav1.NamespaceSystem).Users(user.KubeScheduler).SAs(metav1.NamespaceSystem, \"kube-scheduler\").BindingOrDie())\n\taddNamespaceRoleBinding(metav1.NamespaceSystem,\n\t\trbacv1helpers.NewRoleBinding(saRolePrefix+\"bootstrap-signer\", metav1.NamespaceSystem).SAs(metav1.NamespaceSystem, \"bootstrap-signer\").BindingOrDie())\n\t// cloud-provider is deprecated starting Kubernetes 1.10 and will be deleted according to GA deprecation policy.\n\taddNamespaceRoleBinding(metav1.NamespaceSystem,\n\t\trbacv1helpers.NewRoleBinding(saRolePrefix+\"cloud-provider\", metav1.NamespaceSystem).SAs(metav1.NamespaceSystem, \"cloud-provider\").BindingOrDie())\n\taddNamespaceRoleBinding(metav1.NamespaceSystem,\n\t\trbacv1helpers.NewRoleBinding(saRolePrefix+\"token-cleaner\", metav1.NamespaceSystem).SAs(metav1.NamespaceSystem, \"token-cleaner\").BindingOrDie())\n\n\taddNamespaceRole(metav1.NamespacePublic, rbacv1.Role{\n\t\t// role for the bootstrap signer to be able to write its configmap\n\t\tObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"bootstrap-signer\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(legacyGroup).Resources(\"configmaps\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(\"update\").Groups(legacyGroup).Resources(\"configmaps\").Names(\"cluster-info\").RuleOrDie(),\n\t\t\teventsRule(),\n\t\t},\n\t})\n\taddNamespaceRoleBinding(metav1.NamespacePublic,\n\t\trbacv1helpers.NewRoleBinding(saRolePrefix+\"bootstrap-signer\", metav1.NamespacePublic).SAs(metav1.NamespaceSystem, \"bootstrap-signer\").BindingOrDie())\n\n}","line":{"from":74,"to":152}} {"id":100013669,"name":"NamespaceRoles","signature":"func NamespaceRoles() map[string][]rbacv1.Role","file":"plugin/pkg/auth/authorizer/rbac/bootstrappolicy/namespace_policy.go","code":"// NamespaceRoles returns a map of namespace to slice of roles to create\nfunc NamespaceRoles() map[string][]rbacv1.Role {\n\treturn namespaceRoles\n}","line":{"from":154,"to":157}} {"id":100013670,"name":"NamespaceRoleBindings","signature":"func NamespaceRoleBindings() map[string][]rbacv1.RoleBinding","file":"plugin/pkg/auth/authorizer/rbac/bootstrappolicy/namespace_policy.go","code":"// NamespaceRoleBindings returns a map of namespace to slice of roles to create\nfunc NamespaceRoleBindings() map[string][]rbacv1.RoleBinding {\n\treturn namespaceRoleBindings\n}","line":{"from":159,"to":162}} {"id":100013671,"name":"addDefaultMetadata","signature":"func addDefaultMetadata(obj runtime.Object)","file":"plugin/pkg/auth/authorizer/rbac/bootstrappolicy/policy.go","code":"func addDefaultMetadata(obj runtime.Object) {\n\tmetadata, err := meta.Accessor(obj)\n\tif err != nil {\n\t\t// if this happens, then some static code is broken\n\t\tpanic(err)\n\t}\n\n\tlabels := metadata.GetLabels()\n\tif labels == nil {\n\t\tlabels = map[string]string{}\n\t}\n\tfor k, v := range Label {\n\t\tlabels[k] = v\n\t}\n\tmetadata.SetLabels(labels)\n\n\tannotations := metadata.GetAnnotations()\n\tif annotations == nil {\n\t\tannotations = map[string]string{}\n\t}\n\tfor k, v := range Annotation {\n\t\tannotations[k] = v\n\t}\n\tmetadata.SetAnnotations(annotations)\n}","line":{"from":67,"to":91}} {"id":100013672,"name":"addClusterRoleLabel","signature":"func addClusterRoleLabel(roles []rbacv1.ClusterRole)","file":"plugin/pkg/auth/authorizer/rbac/bootstrappolicy/policy.go","code":"func addClusterRoleLabel(roles []rbacv1.ClusterRole) {\n\tfor i := range roles {\n\t\taddDefaultMetadata(\u0026roles[i])\n\t}\n\treturn\n}","line":{"from":93,"to":98}} {"id":100013673,"name":"addClusterRoleBindingLabel","signature":"func addClusterRoleBindingLabel(rolebindings []rbacv1.ClusterRoleBinding)","file":"plugin/pkg/auth/authorizer/rbac/bootstrappolicy/policy.go","code":"func addClusterRoleBindingLabel(rolebindings []rbacv1.ClusterRoleBinding) {\n\tfor i := range rolebindings {\n\t\taddDefaultMetadata(\u0026rolebindings[i])\n\t}\n\treturn\n}","line":{"from":100,"to":105}} {"id":100013674,"name":"NodeRules","signature":"func NodeRules() []rbacv1.PolicyRule","file":"plugin/pkg/auth/authorizer/rbac/bootstrappolicy/policy.go","code":"// NodeRules returns node policy rules, it is slice of rbacv1.PolicyRule.\nfunc NodeRules() []rbacv1.PolicyRule {\n\tnodePolicyRules := []rbacv1.PolicyRule{\n\t\t// Needed to check API access. These creates are non-mutating\n\t\trbacv1helpers.NewRule(\"create\").Groups(authenticationGroup).Resources(\"tokenreviews\").RuleOrDie(),\n\t\trbacv1helpers.NewRule(\"create\").Groups(authorizationGroup).Resources(\"subjectaccessreviews\", \"localsubjectaccessreviews\").RuleOrDie(),\n\n\t\t// Needed to build serviceLister, to populate env vars for services\n\t\trbacv1helpers.NewRule(Read...).Groups(legacyGroup).Resources(\"services\").RuleOrDie(),\n\n\t\t// Nodes can register Node API objects and report status.\n\t\t// Use the NodeRestriction admission plugin to limit a node to creating/updating its own API object.\n\t\trbacv1helpers.NewRule(\"create\", \"get\", \"list\", \"watch\").Groups(legacyGroup).Resources(\"nodes\").RuleOrDie(),\n\t\trbacv1helpers.NewRule(\"update\", \"patch\").Groups(legacyGroup).Resources(\"nodes/status\").RuleOrDie(),\n\t\trbacv1helpers.NewRule(\"update\", \"patch\").Groups(legacyGroup).Resources(\"nodes\").RuleOrDie(),\n\n\t\t// TODO: restrict to the bound node as creator in the NodeRestrictions admission plugin\n\t\trbacv1helpers.NewRule(\"create\", \"update\", \"patch\").Groups(legacyGroup).Resources(\"events\").RuleOrDie(),\n\n\t\t// TODO: restrict to pods scheduled on the bound node once field selectors are supported by list/watch authorization\n\t\trbacv1helpers.NewRule(Read...).Groups(legacyGroup).Resources(\"pods\").RuleOrDie(),\n\n\t\t// Needed for the node to create/delete mirror pods.\n\t\t// Use the NodeRestriction admission plugin to limit a node to creating/deleting mirror pods bound to itself.\n\t\trbacv1helpers.NewRule(\"create\", \"delete\").Groups(legacyGroup).Resources(\"pods\").RuleOrDie(),\n\t\t// Needed for the node to report status of pods it is running.\n\t\t// Use the NodeRestriction admission plugin to limit a node to updating status of pods bound to itself.\n\t\trbacv1helpers.NewRule(\"update\", \"patch\").Groups(legacyGroup).Resources(\"pods/status\").RuleOrDie(),\n\t\t// Needed for the node to create pod evictions.\n\t\t// Use the NodeRestriction admission plugin to limit a node to creating evictions for pods bound to itself.\n\t\trbacv1helpers.NewRule(\"create\").Groups(legacyGroup).Resources(\"pods/eviction\").RuleOrDie(),\n\n\t\t// Needed for imagepullsecrets, rbd/ceph and secret volumes, and secrets in envs\n\t\t// Needed for configmap volume and envs\n\t\t// Use the Node authorization mode to limit a node to get secrets/configmaps referenced by pods bound to itself.\n\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(legacyGroup).Resources(\"secrets\", \"configmaps\").RuleOrDie(),\n\t\t// Needed for persistent volumes\n\t\t// Use the Node authorization mode to limit a node to get pv/pvc objects referenced by pods bound to itself.\n\t\trbacv1helpers.NewRule(\"get\").Groups(legacyGroup).Resources(\"persistentvolumeclaims\", \"persistentvolumes\").RuleOrDie(),\n\n\t\t// TODO: add to the Node authorizer and restrict to endpoints referenced by pods or PVs bound to the node\n\t\t// Needed for glusterfs volumes\n\t\trbacv1helpers.NewRule(\"get\").Groups(legacyGroup).Resources(\"endpoints\").RuleOrDie(),\n\t\t// Used to create a certificatesigningrequest for a node-specific client certificate, and watch\n\t\t// for it to be signed. This allows the kubelet to rotate it's own certificate.\n\t\trbacv1helpers.NewRule(\"create\", \"get\", \"list\", \"watch\").Groups(certificatesGroup).Resources(\"certificatesigningrequests\").RuleOrDie(),\n\n\t\t// Leases\n\t\trbacv1helpers.NewRule(\"get\", \"create\", \"update\", \"patch\", \"delete\").Groups(\"coordination.k8s.io\").Resources(\"leases\").RuleOrDie(),\n\n\t\t// CSI\n\t\trbacv1helpers.NewRule(\"get\").Groups(storageGroup).Resources(\"volumeattachments\").RuleOrDie(),\n\n\t\t// Use the Node authorization to limit a node to create tokens for service accounts running on that node\n\t\t// Use the NodeRestriction admission plugin to limit a node to create tokens bound to pods on that node\n\t\trbacv1helpers.NewRule(\"create\").Groups(legacyGroup).Resources(\"serviceaccounts/token\").RuleOrDie(),\n\t}\n\n\t// Use the Node authorization mode to limit a node to update status of pvc objects referenced by pods bound to itself.\n\t// Use the NodeRestriction admission plugin to limit a node to just update the status stanza.\n\tpvcStatusPolicyRule := rbacv1helpers.NewRule(\"get\", \"update\", \"patch\").Groups(legacyGroup).Resources(\"persistentvolumeclaims/status\").RuleOrDie()\n\tnodePolicyRules = append(nodePolicyRules, pvcStatusPolicyRule)\n\n\t// CSI\n\tcsiDriverRule := rbacv1helpers.NewRule(\"get\", \"watch\", \"list\").Groups(\"storage.k8s.io\").Resources(\"csidrivers\").RuleOrDie()\n\tnodePolicyRules = append(nodePolicyRules, csiDriverRule)\n\tcsiNodeInfoRule := rbacv1helpers.NewRule(\"get\", \"create\", \"update\", \"patch\", \"delete\").Groups(\"storage.k8s.io\").Resources(\"csinodes\").RuleOrDie()\n\tnodePolicyRules = append(nodePolicyRules, csiNodeInfoRule)\n\n\t// RuntimeClass\n\tnodePolicyRules = append(nodePolicyRules, rbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(\"node.k8s.io\").Resources(\"runtimeclasses\").RuleOrDie())\n\n\t// DRA Resource Claims\n\tif utilfeature.DefaultFeatureGate.Enabled(features.DynamicResourceAllocation) {\n\t\tnodePolicyRules = append(nodePolicyRules, rbacv1helpers.NewRule(\"get\").Groups(resourceGroup).Resources(\"resourceclaims\").RuleOrDie())\n\t}\n\t// Kubelet needs access to ClusterTrustBundles to support the pemTrustAnchors volume type.\n\tif utilfeature.DefaultFeatureGate.Enabled(features.ClusterTrustBundle) {\n\t\tnodePolicyRules = append(nodePolicyRules, rbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(certificatesGroup).Resources(\"clustertrustbundles\").RuleOrDie())\n\t}\n\n\treturn nodePolicyRules\n}","line":{"from":107,"to":189}} {"id":100013675,"name":"ClusterRoles","signature":"func ClusterRoles() []rbacv1.ClusterRole","file":"plugin/pkg/auth/authorizer/rbac/bootstrappolicy/policy.go","code":"// ClusterRoles returns the cluster roles to bootstrap an API server with\nfunc ClusterRoles() []rbacv1.ClusterRole {\n\troles := []rbacv1.ClusterRole{\n\t\t{\n\t\t\t// a \"root\" role which can do absolutely anything\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"cluster-admin\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\trbacv1helpers.NewRule(\"*\").Groups(\"*\").Resources(\"*\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"*\").URLs(\"*\").RuleOrDie(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// a role which provides just enough power to determine if the server is\n\t\t\t// ready and discover API versions for negotiation\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:discovery\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\trbacv1helpers.NewRule(\"get\").URLs(\n\t\t\t\t\t\"/livez\", \"/readyz\", \"/healthz\",\n\t\t\t\t\t\"/version\", \"/version/\",\n\t\t\t\t\t\"/openapi\", \"/openapi/*\",\n\t\t\t\t\t\"/api\", \"/api/*\",\n\t\t\t\t\t\"/apis\", \"/apis/*\",\n\t\t\t\t).RuleOrDie(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// a role which provides minimal read access to the monitoring endpoints\n\t\t\t// (i.e. /metrics, /livez/*, /readyz/*, /healthz/*, /livez, /readyz, /healthz)\n\t\t\t// The splatted health check endpoints allow read access to individual health check\n\t\t\t// endpoints which may contain more sensitive cluster information information\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:monitoring\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\trbacv1helpers.NewRule(\"get\").URLs(\n\t\t\t\t\t\"/metrics\", \"/metrics/slis\",\n\t\t\t\t\t\"/livez\", \"/readyz\", \"/healthz\",\n\t\t\t\t\t\"/livez/*\", \"/readyz/*\", \"/healthz/*\",\n\t\t\t\t).RuleOrDie(),\n\t\t\t},\n\t\t},\n\t}\n\n\tbasicUserRules := []rbacv1.PolicyRule{\n\t\trbacv1helpers.NewRule(\"create\").Groups(authorizationGroup).Resources(\"selfsubjectaccessreviews\", \"selfsubjectrulesreviews\").RuleOrDie(),\n\t}\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.APISelfSubjectReview) {\n\t\tbasicUserRules = append(basicUserRules, rbacv1helpers.NewRule(\"create\").Groups(authenticationGroup).Resources(\"selfsubjectreviews\").RuleOrDie())\n\t}\n\n\troles = append(roles, []rbacv1.ClusterRole{\n\t\t{\n\t\t\t// a role which provides minimal resource access to allow a \"normal\" user to learn information about themselves\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:basic-user\"},\n\t\t\tRules: basicUserRules,\n\t\t},\n\t\t{\n\t\t\t// a role which provides just enough power read insensitive cluster information\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:public-info-viewer\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\trbacv1helpers.NewRule(\"get\").URLs(\n\t\t\t\t\t\"/livez\", \"/readyz\", \"/healthz\", \"/version\", \"/version/\",\n\t\t\t\t).RuleOrDie(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// a role for a namespace level admin. It is `edit` plus the power to grant permissions to other users.\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"admin\"},\n\t\t\tAggregationRule: \u0026rbacv1.AggregationRule{\n\t\t\t\tClusterRoleSelectors: []metav1.LabelSelector{\n\t\t\t\t\t{MatchLabels: map[string]string{\"rbac.authorization.k8s.io/aggregate-to-admin\": \"true\"}},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// a role for a namespace level editor. It grants access to all user level actions in a namespace.\n\t\t\t// It does not grant powers for \"privileged\" resources which are domain of the system: `/status`\n\t\t\t// subresources or `quota`/`limits` which are used to control namespaces\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"edit\", Labels: map[string]string{\"rbac.authorization.k8s.io/aggregate-to-admin\": \"true\"}},\n\t\t\tAggregationRule: \u0026rbacv1.AggregationRule{\n\t\t\t\tClusterRoleSelectors: []metav1.LabelSelector{\n\t\t\t\t\t{MatchLabels: map[string]string{\"rbac.authorization.k8s.io/aggregate-to-edit\": \"true\"}},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// a role for namespace level viewing. It grants Read-only access to non-escalating resources in\n\t\t\t// a namespace.\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"view\", Labels: map[string]string{\"rbac.authorization.k8s.io/aggregate-to-edit\": \"true\"}},\n\t\t\tAggregationRule: \u0026rbacv1.AggregationRule{\n\t\t\t\tClusterRoleSelectors: []metav1.LabelSelector{\n\t\t\t\t\t{MatchLabels: map[string]string{\"rbac.authorization.k8s.io/aggregate-to-view\": \"true\"}},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// a role for a namespace level admin. It is `edit` plus the power to grant permissions to other users.\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:aggregate-to-admin\", Labels: map[string]string{\"rbac.authorization.k8s.io/aggregate-to-admin\": \"true\"}},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\t// additional admin powers\n\t\t\t\trbacv1helpers.NewRule(\"create\").Groups(authorizationGroup).Resources(\"localsubjectaccessreviews\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(ReadWrite...).Groups(rbacGroup).Resources(\"roles\", \"rolebindings\").RuleOrDie(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// a role for a namespace level editor. It grants access to all user level actions in a namespace.\n\t\t\t// It does not grant powers for \"privileged\" resources which are domain of the system: `/status`\n\t\t\t// subresources or `quota`/`limits` which are used to control namespaces\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:aggregate-to-edit\", Labels: map[string]string{\"rbac.authorization.k8s.io/aggregate-to-edit\": \"true\"}},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\t// Allow read on escalating resources\n\t\t\t\trbacv1helpers.NewRule(Read...).Groups(legacyGroup).Resources(\"pods/attach\", \"pods/proxy\", \"pods/exec\", \"pods/portforward\", \"secrets\", \"services/proxy\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"impersonate\").Groups(legacyGroup).Resources(\"serviceaccounts\").RuleOrDie(),\n\n\t\t\t\trbacv1helpers.NewRule(Write...).Groups(legacyGroup).Resources(\"pods\", \"pods/attach\", \"pods/proxy\", \"pods/exec\", \"pods/portforward\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"create\").Groups(legacyGroup).Resources(\"pods/eviction\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(Write...).Groups(legacyGroup).Resources(\"replicationcontrollers\", \"replicationcontrollers/scale\", \"serviceaccounts\",\n\t\t\t\t\t\"services\", \"services/proxy\", \"persistentvolumeclaims\", \"configmaps\", \"secrets\", \"events\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"create\").Groups(legacyGroup).Resources(\"serviceaccounts/token\").RuleOrDie(),\n\n\t\t\t\trbacv1helpers.NewRule(Write...).Groups(appsGroup).Resources(\n\t\t\t\t\t\"statefulsets\", \"statefulsets/scale\",\n\t\t\t\t\t\"daemonsets\",\n\t\t\t\t\t\"deployments\", \"deployments/scale\", \"deployments/rollback\",\n\t\t\t\t\t\"replicasets\", \"replicasets/scale\").RuleOrDie(),\n\n\t\t\t\trbacv1helpers.NewRule(Write...).Groups(autoscalingGroup).Resources(\"horizontalpodautoscalers\").RuleOrDie(),\n\n\t\t\t\trbacv1helpers.NewRule(Write...).Groups(batchGroup).Resources(\"jobs\", \"cronjobs\").RuleOrDie(),\n\n\t\t\t\trbacv1helpers.NewRule(Write...).Groups(extensionsGroup).Resources(\"daemonsets\",\n\t\t\t\t\t\"deployments\", \"deployments/scale\", \"deployments/rollback\", \"ingresses\",\n\t\t\t\t\t\"replicasets\", \"replicasets/scale\", \"replicationcontrollers/scale\",\n\t\t\t\t\t\"networkpolicies\").RuleOrDie(),\n\n\t\t\t\trbacv1helpers.NewRule(Write...).Groups(policyGroup).Resources(\"poddisruptionbudgets\").RuleOrDie(),\n\n\t\t\t\trbacv1helpers.NewRule(Write...).Groups(networkingGroup).Resources(\"networkpolicies\", \"ingresses\").RuleOrDie(),\n\n\t\t\t\trbacv1helpers.NewRule(ReadWrite...).Groups(coordinationGroup).Resources(\"leases\").RuleOrDie(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// a role for namespace level viewing. It grants Read-only access to non-escalating resources in\n\t\t\t// a namespace.\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:aggregate-to-view\", Labels: map[string]string{\"rbac.authorization.k8s.io/aggregate-to-view\": \"true\"}},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\trbacv1helpers.NewRule(Read...).Groups(legacyGroup).Resources(\"pods\", \"replicationcontrollers\", \"replicationcontrollers/scale\", \"serviceaccounts\",\n\t\t\t\t\t\"services\", \"services/status\", \"endpoints\", \"persistentvolumeclaims\", \"persistentvolumeclaims/status\", \"configmaps\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(Read...).Groups(legacyGroup).Resources(\"limitranges\", \"resourcequotas\", \"bindings\", \"events\",\n\t\t\t\t\t\"pods/status\", \"resourcequotas/status\", \"namespaces/status\", \"replicationcontrollers/status\", \"pods/log\").RuleOrDie(),\n\t\t\t\t// read access to namespaces at the namespace scope means you can read *this* namespace. This can be used as an\n\t\t\t\t// indicator of which namespaces you have access to.\n\t\t\t\trbacv1helpers.NewRule(Read...).Groups(legacyGroup).Resources(\"namespaces\").RuleOrDie(),\n\n\t\t\t\trbacv1helpers.NewRule(Read...).Groups(discoveryGroup).Resources(\"endpointslices\").RuleOrDie(),\n\n\t\t\t\trbacv1helpers.NewRule(Read...).Groups(appsGroup).Resources(\n\t\t\t\t\t\"controllerrevisions\",\n\t\t\t\t\t\"statefulsets\", \"statefulsets/status\", \"statefulsets/scale\",\n\t\t\t\t\t\"daemonsets\", \"daemonsets/status\",\n\t\t\t\t\t\"deployments\", \"deployments/status\", \"deployments/scale\",\n\t\t\t\t\t\"replicasets\", \"replicasets/status\", \"replicasets/scale\").RuleOrDie(),\n\n\t\t\t\trbacv1helpers.NewRule(Read...).Groups(autoscalingGroup).Resources(\"horizontalpodautoscalers\", \"horizontalpodautoscalers/status\").RuleOrDie(),\n\n\t\t\t\trbacv1helpers.NewRule(Read...).Groups(batchGroup).Resources(\"jobs\", \"cronjobs\", \"cronjobs/status\", \"jobs/status\").RuleOrDie(),\n\n\t\t\t\trbacv1helpers.NewRule(Read...).Groups(extensionsGroup).Resources(\"daemonsets\", \"daemonsets/status\", \"deployments\", \"deployments/scale\", \"deployments/status\",\n\t\t\t\t\t\"ingresses\", \"ingresses/status\", \"replicasets\", \"replicasets/scale\", \"replicasets/status\", \"replicationcontrollers/scale\",\n\t\t\t\t\t\"networkpolicies\").RuleOrDie(),\n\n\t\t\t\trbacv1helpers.NewRule(Read...).Groups(policyGroup).Resources(\"poddisruptionbudgets\", \"poddisruptionbudgets/status\").RuleOrDie(),\n\n\t\t\t\trbacv1helpers.NewRule(Read...).Groups(networkingGroup).Resources(\"networkpolicies\", \"ingresses\", \"ingresses/status\").RuleOrDie(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// a role to use for heapster's connections back to the API server\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:heapster\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\trbacv1helpers.NewRule(Read...).Groups(legacyGroup).Resources(\"events\", \"pods\", \"nodes\", \"namespaces\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(Read...).Groups(extensionsGroup).Resources(\"deployments\").RuleOrDie(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// a role for nodes to use to have the access they need for running pods\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: systemNodeRoleName},\n\t\t\tRules: NodeRules(),\n\t\t},\n\t\t{\n\t\t\t// a role to use for node-problem-detector access. It does not get bound to default location since\n\t\t\t// deployment locations can reasonably vary.\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:node-problem-detector\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\trbacv1helpers.NewRule(\"get\").Groups(legacyGroup).Resources(\"nodes\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"patch\").Groups(legacyGroup).Resources(\"nodes/status\").RuleOrDie(),\n\t\t\t\teventsRule(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// a role to use for full access to the kubelet API\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:kubelet-api-admin\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\t// Allow read-only access to the Node API objects\n\t\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(legacyGroup).Resources(\"nodes\").RuleOrDie(),\n\t\t\t\t// Allow all API calls to the nodes\n\t\t\t\trbacv1helpers.NewRule(\"proxy\").Groups(legacyGroup).Resources(\"nodes\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"*\").Groups(legacyGroup).Resources(\"nodes/proxy\", \"nodes/metrics\", \"nodes/stats\", \"nodes/log\").RuleOrDie(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// a role to use for bootstrapping a node's client certificates\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:node-bootstrapper\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\t// used to create a certificatesigningrequest for a node-specific client certificate, and watch for it to be signed\n\t\t\t\trbacv1helpers.NewRule(\"create\", \"get\", \"list\", \"watch\").Groups(certificatesGroup).Resources(\"certificatesigningrequests\").RuleOrDie(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// a role to use for allowing authentication and authorization delegation\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:auth-delegator\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\t// These creates are non-mutating\n\t\t\t\trbacv1helpers.NewRule(\"create\").Groups(authenticationGroup).Resources(\"tokenreviews\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"create\").Groups(authorizationGroup).Resources(\"subjectaccessreviews\").RuleOrDie(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// a role to use for the API registry, summarization, and proxy handling\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:kube-aggregator\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\t// it needs to see all services so that it knows whether the ones it points to exist or not\n\t\t\t\trbacv1helpers.NewRule(Read...).Groups(legacyGroup).Resources(\"services\", \"endpoints\").RuleOrDie(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// a role to use for bootstrapping the kube-controller-manager so it can create the shared informers\n\t\t\t// service accounts, and secrets that we need to create separate identities for other controllers\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:kube-controller-manager\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\teventsRule(),\n\t\t\t\t// Needed for leader election.\n\t\t\t\trbacv1helpers.NewRule(\"create\").Groups(coordinationGroup).Resources(\"leases\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"get\", \"update\").Groups(coordinationGroup).Resources(\"leases\").Names(\"kube-controller-manager\").RuleOrDie(),\n\t\t\t\t// TODO: Remove once we fully migrate to lease in leader-election.\n\t\t\t\trbacv1helpers.NewRule(\"create\").Groups(legacyGroup).Resources(\"endpoints\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"get\", \"update\").Groups(legacyGroup).Resources(\"endpoints\").Names(\"kube-controller-manager\").RuleOrDie(),\n\t\t\t\t// Fundamental resources.\n\t\t\t\trbacv1helpers.NewRule(\"create\").Groups(legacyGroup).Resources(\"secrets\", \"serviceaccounts\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"delete\").Groups(legacyGroup).Resources(\"secrets\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"get\").Groups(legacyGroup).Resources(\"namespaces\", \"secrets\", \"serviceaccounts\", \"configmaps\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"update\").Groups(legacyGroup).Resources(\"secrets\", \"serviceaccounts\").RuleOrDie(),\n\t\t\t\t// Needed to check API access. These creates are non-mutating\n\t\t\t\trbacv1helpers.NewRule(\"create\").Groups(authenticationGroup).Resources(\"tokenreviews\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"create\").Groups(authorizationGroup).Resources(\"subjectaccessreviews\").RuleOrDie(),\n\t\t\t\t// Needed for all shared informers\n\t\t\t\trbacv1helpers.NewRule(\"list\", \"watch\").Groups(\"*\").Resources(\"*\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(\"create\").Groups(legacyGroup).Resources(\"serviceaccounts/token\").RuleOrDie(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// a role to use for the kube-dns pod\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:kube-dns\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\trbacv1helpers.NewRule(\"list\", \"watch\").Groups(legacyGroup).Resources(\"endpoints\", \"services\").RuleOrDie(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// a role for an external/out-of-tree persistent volume provisioner\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:persistent-volume-provisioner\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\", \"create\", \"delete\").Groups(legacyGroup).Resources(\"persistentvolumes\").RuleOrDie(),\n\t\t\t\t// update is needed in addition to read access for setting lock annotations on PVCs\n\t\t\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\", \"update\").Groups(legacyGroup).Resources(\"persistentvolumeclaims\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(Read...).Groups(storageGroup).Resources(\"storageclasses\").RuleOrDie(),\n\n\t\t\t\t// Needed for watching provisioning success and failure events\n\t\t\t\trbacv1helpers.NewRule(\"watch\").Groups(legacyGroup).Resources(\"events\").RuleOrDie(),\n\n\t\t\t\teventsRule(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// a role making the csrapprover controller approve a node client CSR\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:certificates.k8s.io:certificatesigningrequests:nodeclient\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\trbacv1helpers.NewRule(\"create\").Groups(certificatesGroup).Resources(\"certificatesigningrequests/nodeclient\").RuleOrDie(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// a role making the csrapprover controller approve a node client CSR requested by the node itself\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:certificates.k8s.io:certificatesigningrequests:selfnodeclient\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\trbacv1helpers.NewRule(\"create\").Groups(certificatesGroup).Resources(\"certificatesigningrequests/selfnodeclient\").RuleOrDie(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:volume-scheduler\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\trbacv1helpers.NewRule(ReadUpdate...).Groups(legacyGroup).Resources(\"persistentvolumes\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(Read...).Groups(storageGroup).Resources(\"storageclasses\").RuleOrDie(),\n\t\t\t\trbacv1helpers.NewRule(ReadUpdate...).Groups(legacyGroup).Resources(\"persistentvolumeclaims\").RuleOrDie(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:certificates.k8s.io:legacy-unknown-approver\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\trbacv1helpers.NewRule(\"approve\").Groups(certificatesGroup).Resources(\"signers\").Names(capi.LegacyUnknownSignerName).RuleOrDie(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:certificates.k8s.io:kubelet-serving-approver\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\trbacv1helpers.NewRule(\"approve\").Groups(certificatesGroup).Resources(\"signers\").Names(capi.KubeletServingSignerName).RuleOrDie(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:certificates.k8s.io:kube-apiserver-client-approver\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\trbacv1helpers.NewRule(\"approve\").Groups(certificatesGroup).Resources(\"signers\").Names(capi.KubeAPIServerClientSignerName).RuleOrDie(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:certificates.k8s.io:kube-apiserver-client-kubelet-approver\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\trbacv1helpers.NewRule(\"approve\").Groups(certificatesGroup).Resources(\"signers\").Names(capi.KubeAPIServerClientKubeletSignerName).RuleOrDie(),\n\t\t\t},\n\t\t},\n\t}...)\n\n\t// Add the cluster role for reading the ServiceAccountIssuerDiscovery endpoints\n\troles = append(roles, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:service-account-issuer-discovery\"},\n\t\tRules: []rbacv1.PolicyRule{\n\t\t\trbacv1helpers.NewRule(\"get\").URLs(\n\t\t\t\t\"/.well-known/openid-configuration\",\n\t\t\t\t\"/openid/v1/jwks\",\n\t\t\t).RuleOrDie(),\n\t\t},\n\t})\n\n\t// node-proxier role is used by kube-proxy.\n\tnodeProxierRules := []rbacv1.PolicyRule{\n\t\trbacv1helpers.NewRule(\"list\", \"watch\").Groups(legacyGroup).Resources(\"services\", \"endpoints\").RuleOrDie(),\n\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(legacyGroup).Resources(\"nodes\").RuleOrDie(),\n\n\t\teventsRule(),\n\t}\n\tnodeProxierRules = append(nodeProxierRules, rbacv1helpers.NewRule(\"list\", \"watch\").Groups(discoveryGroup).Resources(\"endpointslices\").RuleOrDie())\n\troles = append(roles, rbacv1.ClusterRole{\n\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:node-proxier\"},\n\t\tRules: nodeProxierRules,\n\t})\n\n\tkubeSchedulerRules := []rbacv1.PolicyRule{\n\t\teventsRule(),\n\t\t// This is for leaderlease access\n\t\t// TODO: scope this to the kube-system namespace\n\t\trbacv1helpers.NewRule(\"create\").Groups(coordinationGroup).Resources(\"leases\").RuleOrDie(),\n\t\trbacv1helpers.NewRule(\"get\", \"update\").Groups(coordinationGroup).Resources(\"leases\").Names(\"kube-scheduler\").RuleOrDie(),\n\t\t// TODO: Remove once we fully migrate to lease in leader-election.\n\t\trbacv1helpers.NewRule(\"create\").Groups(legacyGroup).Resources(\"endpoints\").RuleOrDie(),\n\t\trbacv1helpers.NewRule(\"get\", \"update\").Groups(legacyGroup).Resources(\"endpoints\").Names(\"kube-scheduler\").RuleOrDie(),\n\n\t\t// Fundamental resources\n\t\trbacv1helpers.NewRule(Read...).Groups(legacyGroup).Resources(\"nodes\").RuleOrDie(),\n\t\trbacv1helpers.NewRule(\"get\", \"list\", \"watch\", \"delete\").Groups(legacyGroup).Resources(\"pods\").RuleOrDie(),\n\t\trbacv1helpers.NewRule(\"create\").Groups(legacyGroup).Resources(\"pods/binding\", \"bindings\").RuleOrDie(),\n\t\trbacv1helpers.NewRule(\"patch\", \"update\").Groups(legacyGroup).Resources(\"pods/status\").RuleOrDie(),\n\t\t// Things that select pods\n\t\trbacv1helpers.NewRule(Read...).Groups(legacyGroup).Resources(\"services\", \"replicationcontrollers\").RuleOrDie(),\n\t\trbacv1helpers.NewRule(Read...).Groups(appsGroup, extensionsGroup).Resources(\"replicasets\").RuleOrDie(),\n\t\trbacv1helpers.NewRule(Read...).Groups(appsGroup).Resources(\"statefulsets\").RuleOrDie(),\n\t\t// Things that pods use or applies to them\n\t\trbacv1helpers.NewRule(Read...).Groups(policyGroup).Resources(\"poddisruptionbudgets\").RuleOrDie(),\n\t\trbacv1helpers.NewRule(Read...).Groups(legacyGroup).Resources(\"persistentvolumeclaims\", \"persistentvolumes\").RuleOrDie(),\n\t\t// Needed to check API access. These creates are non-mutating\n\t\trbacv1helpers.NewRule(\"create\").Groups(authenticationGroup).Resources(\"tokenreviews\").RuleOrDie(),\n\t\trbacv1helpers.NewRule(\"create\").Groups(authorizationGroup).Resources(\"subjectaccessreviews\").RuleOrDie(),\n\t\t// Needed for volume limits\n\t\trbacv1helpers.NewRule(Read...).Groups(storageGroup).Resources(\"csinodes\").RuleOrDie(),\n\t\t// Needed for namespaceSelector feature in pod affinity\n\t\trbacv1helpers.NewRule(Read...).Groups(legacyGroup).Resources(\"namespaces\").RuleOrDie(),\n\t\trbacv1helpers.NewRule(Read...).Groups(storageGroup).Resources(\"csidrivers\").RuleOrDie(),\n\t\trbacv1helpers.NewRule(Read...).Groups(storageGroup).Resources(\"csistoragecapacities\").RuleOrDie(),\n\t}\n\t// Needed for dynamic resource allocation.\n\tif utilfeature.DefaultFeatureGate.Enabled(features.DynamicResourceAllocation) {\n\t\tkubeSchedulerRules = append(kubeSchedulerRules,\n\t\t\trbacv1helpers.NewRule(Read...).Groups(resourceGroup).Resources(\"resourceclaims\", \"resourceclasses\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(ReadUpdate...).Groups(resourceGroup).Resources(\"resourceclaims/status\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(ReadWrite...).Groups(resourceGroup).Resources(\"podschedulingcontexts\").RuleOrDie(),\n\t\t\trbacv1helpers.NewRule(Read...).Groups(resourceGroup).Resources(\"podschedulingcontexts/status\").RuleOrDie(),\n\t\t)\n\t}\n\troles = append(roles, rbacv1.ClusterRole{\n\t\t// a role to use for the kube-scheduler\n\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:kube-scheduler\"},\n\t\tRules: kubeSchedulerRules,\n\t})\n\n\t// Default ClusterRole to allow reading ClusterTrustBundle objects\n\tif utilfeature.DefaultFeatureGate.Enabled(features.ClusterTrustBundle) {\n\t\troles = append(roles, rbacv1.ClusterRole{\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"system:cluster-trust-bundle-discovery\"},\n\t\t\tRules: []rbacv1.PolicyRule{\n\t\t\t\trbacv1helpers.NewRule(Read...).Groups(certificatesGroup).Resources(\"clustertrustbundles\").RuleOrDie(),\n\t\t\t},\n\t\t})\n\t}\n\n\taddClusterRoleLabel(roles)\n\treturn roles\n}","line":{"from":191,"to":604}} {"id":100013676,"name":"ClusterRoleBindings","signature":"func ClusterRoleBindings() []rbacv1.ClusterRoleBinding","file":"plugin/pkg/auth/authorizer/rbac/bootstrappolicy/policy.go","code":"// ClusterRoleBindings return default rolebindings to the default roles\nfunc ClusterRoleBindings() []rbacv1.ClusterRoleBinding {\n\trolebindings := []rbacv1.ClusterRoleBinding{\n\t\trbacv1helpers.NewClusterBinding(\"cluster-admin\").Groups(user.SystemPrivilegedGroup).BindingOrDie(),\n\t\trbacv1helpers.NewClusterBinding(\"system:monitoring\").Groups(user.MonitoringGroup).BindingOrDie(),\n\t\trbacv1helpers.NewClusterBinding(\"system:discovery\").Groups(user.AllAuthenticated).BindingOrDie(),\n\t\trbacv1helpers.NewClusterBinding(\"system:basic-user\").Groups(user.AllAuthenticated).BindingOrDie(),\n\t\trbacv1helpers.NewClusterBinding(\"system:public-info-viewer\").Groups(user.AllAuthenticated, user.AllUnauthenticated).BindingOrDie(),\n\t\trbacv1helpers.NewClusterBinding(\"system:node-proxier\").Users(user.KubeProxy).BindingOrDie(),\n\t\trbacv1helpers.NewClusterBinding(\"system:kube-controller-manager\").Users(user.KubeControllerManager).BindingOrDie(),\n\t\trbacv1helpers.NewClusterBinding(\"system:kube-dns\").SAs(\"kube-system\", \"kube-dns\").BindingOrDie(),\n\t\trbacv1helpers.NewClusterBinding(\"system:kube-scheduler\").Users(user.KubeScheduler).BindingOrDie(),\n\t\trbacv1helpers.NewClusterBinding(\"system:volume-scheduler\").Users(user.KubeScheduler).BindingOrDie(),\n\n\t\t// This default binding of the system:node role to the system:nodes group is deprecated in 1.7 with the availability of the Node authorizer.\n\t\t// This leaves the binding, but with an empty set of subjects, so that tightening reconciliation can remove the subject.\n\t\t{\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: systemNodeRoleName},\n\t\t\tRoleRef: rbacv1.RoleRef{APIGroup: rbacv1.GroupName, Kind: \"ClusterRole\", Name: systemNodeRoleName},\n\t\t},\n\t}\n\n\t// Allow all in-cluster workloads (via their service accounts) to read the OIDC discovery endpoints.\n\t// Users with certain forms of write access (create pods, create secrets, create service accounts, etc)\n\t// can gain access to a service account identity which would allow them to access this information.\n\t// This includes the issuer URL, which is already present in the SA token JWT. Similarly, SAs can\n\t// already gain this same info via introspection of their own token. Since this discovery endpoint\n\t// points to what issued all service account tokens, it seems fitting for SAs to have this access.\n\t// Defer to the cluster admin with regard to binding directly to all authenticated and/or\n\t// unauthenticated users.\n\trolebindings = append(rolebindings,\n\t\trbacv1helpers.NewClusterBinding(\"system:service-account-issuer-discovery\").Groups(serviceaccount.AllServiceAccountsGroup).BindingOrDie(),\n\t)\n\n\t// Service accounts can read ClusterTrustBundle objects.\n\tif utilfeature.DefaultFeatureGate.Enabled(features.ClusterTrustBundle) {\n\t\trolebindings = append(rolebindings, rbacv1helpers.NewClusterBinding(\"system:cluster-trust-bundle-discovery\").Groups(serviceaccount.AllServiceAccountsGroup).BindingOrDie())\n\t}\n\n\taddClusterRoleBindingLabel(rolebindings)\n\n\treturn rolebindings\n}","line":{"from":608,"to":650}} {"id":100013677,"name":"ClusterRolesToAggregate","signature":"func ClusterRolesToAggregate() map[string]string","file":"plugin/pkg/auth/authorizer/rbac/bootstrappolicy/policy.go","code":"// ClusterRolesToAggregate maps from previous clusterrole name to the new clusterrole name\nfunc ClusterRolesToAggregate() map[string]string {\n\treturn map[string]string{\n\t\t\"admin\": \"system:aggregate-to-admin\",\n\t\t\"edit\": \"system:aggregate-to-edit\",\n\t\t\"view\": \"system:aggregate-to-view\",\n\t}\n}","line":{"from":652,"to":659}} {"id":100013678,"name":"ClusterRoleBindingsToSplit","signature":"func ClusterRoleBindingsToSplit() map[string]rbacv1.ClusterRoleBinding","file":"plugin/pkg/auth/authorizer/rbac/bootstrappolicy/policy.go","code":"// ClusterRoleBindingsToSplit returns a map of Names of source ClusterRoleBindings\n// to copy Subjects, Annotations, and Labels to destination ClusterRoleBinding templates.\nfunc ClusterRoleBindingsToSplit() map[string]rbacv1.ClusterRoleBinding {\n\tbindingsToSplit := map[string]rbacv1.ClusterRoleBinding{}\n\tfor _, defaultClusterRoleBinding := range ClusterRoleBindings() {\n\t\tswitch defaultClusterRoleBinding.Name {\n\t\tcase \"system:public-info-viewer\":\n\t\t\tbindingsToSplit[\"system:discovery\"] = defaultClusterRoleBinding\n\t\t}\n\t}\n\treturn bindingsToSplit\n}","line":{"from":661,"to":672}} {"id":100013679,"name":"visit","signature":"func (v *authorizingVisitor) visit(source fmt.Stringer, rule *rbacv1.PolicyRule, err error) bool","file":"plugin/pkg/auth/authorizer/rbac/rbac.go","code":"func (v *authorizingVisitor) visit(source fmt.Stringer, rule *rbacv1.PolicyRule, err error) bool {\n\tif rule != nil \u0026\u0026 RuleAllows(v.requestAttributes, rule) {\n\t\tv.allowed = true\n\t\tv.reason = fmt.Sprintf(\"RBAC: allowed by %s\", source.String())\n\t\treturn false\n\t}\n\tif err != nil {\n\t\tv.errors = append(v.errors, err)\n\t}\n\treturn true\n}","line":{"from":63,"to":73}} {"id":100013680,"name":"Authorize","signature":"func (r *RBACAuthorizer) Authorize(ctx context.Context, requestAttributes authorizer.Attributes) (authorizer.Decision, string, error)","file":"plugin/pkg/auth/authorizer/rbac/rbac.go","code":"func (r *RBACAuthorizer) Authorize(ctx context.Context, requestAttributes authorizer.Attributes) (authorizer.Decision, string, error) {\n\truleCheckingVisitor := \u0026authorizingVisitor{requestAttributes: requestAttributes}\n\n\tr.authorizationRuleResolver.VisitRulesFor(requestAttributes.GetUser(), requestAttributes.GetNamespace(), ruleCheckingVisitor.visit)\n\tif ruleCheckingVisitor.allowed {\n\t\treturn authorizer.DecisionAllow, ruleCheckingVisitor.reason, nil\n\t}\n\n\t// Build a detailed log of the denial.\n\t// Make the whole block conditional so we don't do a lot of string-building we won't use.\n\tif klogV := klog.V(5); klogV.Enabled() {\n\t\tvar operation string\n\t\tif requestAttributes.IsResourceRequest() {\n\t\t\tb := \u0026bytes.Buffer{}\n\t\t\tb.WriteString(`\"`)\n\t\t\tb.WriteString(requestAttributes.GetVerb())\n\t\t\tb.WriteString(`\" resource \"`)\n\t\t\tb.WriteString(requestAttributes.GetResource())\n\t\t\tif len(requestAttributes.GetAPIGroup()) \u003e 0 {\n\t\t\t\tb.WriteString(`.`)\n\t\t\t\tb.WriteString(requestAttributes.GetAPIGroup())\n\t\t\t}\n\t\t\tif len(requestAttributes.GetSubresource()) \u003e 0 {\n\t\t\t\tb.WriteString(`/`)\n\t\t\t\tb.WriteString(requestAttributes.GetSubresource())\n\t\t\t}\n\t\t\tb.WriteString(`\"`)\n\t\t\tif len(requestAttributes.GetName()) \u003e 0 {\n\t\t\t\tb.WriteString(` named \"`)\n\t\t\t\tb.WriteString(requestAttributes.GetName())\n\t\t\t\tb.WriteString(`\"`)\n\t\t\t}\n\t\t\toperation = b.String()\n\t\t} else {\n\t\t\toperation = fmt.Sprintf(\"%q nonResourceURL %q\", requestAttributes.GetVerb(), requestAttributes.GetPath())\n\t\t}\n\n\t\tvar scope string\n\t\tif ns := requestAttributes.GetNamespace(); len(ns) \u003e 0 {\n\t\t\tscope = fmt.Sprintf(\"in namespace %q\", ns)\n\t\t} else {\n\t\t\tscope = \"cluster-wide\"\n\t\t}\n\n\t\tklogV.Infof(\"RBAC: no rules authorize user %q with groups %q to %s %s\", requestAttributes.GetUser().GetName(), requestAttributes.GetUser().GetGroups(), operation, scope)\n\t}\n\n\treason := \"\"\n\tif len(ruleCheckingVisitor.errors) \u003e 0 {\n\t\treason = fmt.Sprintf(\"RBAC: %v\", utilerrors.NewAggregate(ruleCheckingVisitor.errors))\n\t}\n\treturn authorizer.DecisionNoOpinion, reason, nil\n}","line":{"from":75,"to":127}} {"id":100013681,"name":"RulesFor","signature":"func (r *RBACAuthorizer) RulesFor(user user.Info, namespace string) ([]authorizer.ResourceRuleInfo, []authorizer.NonResourceRuleInfo, bool, error)","file":"plugin/pkg/auth/authorizer/rbac/rbac.go","code":"func (r *RBACAuthorizer) RulesFor(user user.Info, namespace string) ([]authorizer.ResourceRuleInfo, []authorizer.NonResourceRuleInfo, bool, error) {\n\tvar (\n\t\tresourceRules []authorizer.ResourceRuleInfo\n\t\tnonResourceRules []authorizer.NonResourceRuleInfo\n\t)\n\n\tpolicyRules, err := r.authorizationRuleResolver.RulesFor(user, namespace)\n\tfor _, policyRule := range policyRules {\n\t\tif len(policyRule.Resources) \u003e 0 {\n\t\t\tr := authorizer.DefaultResourceRuleInfo{\n\t\t\t\tVerbs: policyRule.Verbs,\n\t\t\t\tAPIGroups: policyRule.APIGroups,\n\t\t\t\tResources: policyRule.Resources,\n\t\t\t\tResourceNames: policyRule.ResourceNames,\n\t\t\t}\n\t\t\tvar resourceRule authorizer.ResourceRuleInfo = \u0026r\n\t\t\tresourceRules = append(resourceRules, resourceRule)\n\t\t}\n\t\tif len(policyRule.NonResourceURLs) \u003e 0 {\n\t\t\tr := authorizer.DefaultNonResourceRuleInfo{\n\t\t\t\tVerbs: policyRule.Verbs,\n\t\t\t\tNonResourceURLs: policyRule.NonResourceURLs,\n\t\t\t}\n\t\t\tvar nonResourceRule authorizer.NonResourceRuleInfo = \u0026r\n\t\t\tnonResourceRules = append(nonResourceRules, nonResourceRule)\n\t\t}\n\t}\n\treturn resourceRules, nonResourceRules, false, err\n}","line":{"from":129,"to":157}} {"id":100013682,"name":"New","signature":"func New(roles rbacregistryvalidation.RoleGetter, roleBindings rbacregistryvalidation.RoleBindingLister, clusterRoles rbacregistryvalidation.ClusterRoleGetter, clusterRoleBindings rbacregistryvalidation.ClusterRoleBindingLister) *RBACAuthorizer","file":"plugin/pkg/auth/authorizer/rbac/rbac.go","code":"func New(roles rbacregistryvalidation.RoleGetter, roleBindings rbacregistryvalidation.RoleBindingLister, clusterRoles rbacregistryvalidation.ClusterRoleGetter, clusterRoleBindings rbacregistryvalidation.ClusterRoleBindingLister) *RBACAuthorizer {\n\tauthorizer := \u0026RBACAuthorizer{\n\t\tauthorizationRuleResolver: rbacregistryvalidation.NewDefaultRuleResolver(\n\t\t\troles, roleBindings, clusterRoles, clusterRoleBindings,\n\t\t),\n\t}\n\treturn authorizer\n}","line":{"from":159,"to":166}} {"id":100013683,"name":"RulesAllow","signature":"func RulesAllow(requestAttributes authorizer.Attributes, rules ...rbacv1.PolicyRule) bool","file":"plugin/pkg/auth/authorizer/rbac/rbac.go","code":"func RulesAllow(requestAttributes authorizer.Attributes, rules ...rbacv1.PolicyRule) bool {\n\tfor i := range rules {\n\t\tif RuleAllows(requestAttributes, \u0026rules[i]) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":168,"to":176}} {"id":100013684,"name":"RuleAllows","signature":"func RuleAllows(requestAttributes authorizer.Attributes, rule *rbacv1.PolicyRule) bool","file":"plugin/pkg/auth/authorizer/rbac/rbac.go","code":"func RuleAllows(requestAttributes authorizer.Attributes, rule *rbacv1.PolicyRule) bool {\n\tif requestAttributes.IsResourceRequest() {\n\t\tcombinedResource := requestAttributes.GetResource()\n\t\tif len(requestAttributes.GetSubresource()) \u003e 0 {\n\t\t\tcombinedResource = requestAttributes.GetResource() + \"/\" + requestAttributes.GetSubresource()\n\t\t}\n\n\t\treturn rbacv1helpers.VerbMatches(rule, requestAttributes.GetVerb()) \u0026\u0026\n\t\t\trbacv1helpers.APIGroupMatches(rule, requestAttributes.GetAPIGroup()) \u0026\u0026\n\t\t\trbacv1helpers.ResourceMatches(rule, combinedResource, requestAttributes.GetSubresource()) \u0026\u0026\n\t\t\trbacv1helpers.ResourceNameMatches(rule, requestAttributes.GetName())\n\t}\n\n\treturn rbacv1helpers.VerbMatches(rule, requestAttributes.GetVerb()) \u0026\u0026\n\t\trbacv1helpers.NonResourceURLMatches(rule, requestAttributes.GetPath())\n}","line":{"from":178,"to":193}} {"id":100013685,"name":"GetRole","signature":"func (g *RoleGetter) GetRole(namespace, name string) (*rbacv1.Role, error)","file":"plugin/pkg/auth/authorizer/rbac/rbac.go","code":"func (g *RoleGetter) GetRole(namespace, name string) (*rbacv1.Role, error) {\n\treturn g.Lister.Roles(namespace).Get(name)\n}","line":{"from":199,"to":201}} {"id":100013686,"name":"ListRoleBindings","signature":"func (l *RoleBindingLister) ListRoleBindings(namespace string) ([]*rbacv1.RoleBinding, error)","file":"plugin/pkg/auth/authorizer/rbac/rbac.go","code":"func (l *RoleBindingLister) ListRoleBindings(namespace string) ([]*rbacv1.RoleBinding, error) {\n\treturn l.Lister.RoleBindings(namespace).List(labels.Everything())\n}","line":{"from":207,"to":209}} {"id":100013687,"name":"GetClusterRole","signature":"func (g *ClusterRoleGetter) GetClusterRole(name string) (*rbacv1.ClusterRole, error)","file":"plugin/pkg/auth/authorizer/rbac/rbac.go","code":"func (g *ClusterRoleGetter) GetClusterRole(name string) (*rbacv1.ClusterRole, error) {\n\treturn g.Lister.Get(name)\n}","line":{"from":215,"to":217}} {"id":100013688,"name":"ListClusterRoleBindings","signature":"func (l *ClusterRoleBindingLister) ListClusterRoleBindings() ([]*rbacv1.ClusterRoleBinding, error)","file":"plugin/pkg/auth/authorizer/rbac/rbac.go","code":"func (l *ClusterRoleBindingLister) ListClusterRoleBindings() ([]*rbacv1.ClusterRoleBinding, error) {\n\treturn l.Lister.List(labels.Everything())\n}","line":{"from":223,"to":225}} {"id":100013689,"name":"NewSubjectAccessEvaluator","signature":"func NewSubjectAccessEvaluator(roles rbacregistryvalidation.RoleGetter, roleBindings rbacregistryvalidation.RoleBindingLister, clusterRoles rbacregistryvalidation.ClusterRoleGetter, clusterRoleBindings rbacregistryvalidation.ClusterRoleBindingLister, superUser string) *SubjectAccessEvaluator","file":"plugin/pkg/auth/authorizer/rbac/subject_locator.go","code":"func NewSubjectAccessEvaluator(roles rbacregistryvalidation.RoleGetter, roleBindings rbacregistryvalidation.RoleBindingLister, clusterRoles rbacregistryvalidation.ClusterRoleGetter, clusterRoleBindings rbacregistryvalidation.ClusterRoleBindingLister, superUser string) *SubjectAccessEvaluator {\n\tsubjectLocator := \u0026SubjectAccessEvaluator{\n\t\tsuperUser: superUser,\n\t\troleBindingLister: roleBindings,\n\t\tclusterRoleBindingLister: clusterRoleBindings,\n\t\troleToRuleMapper: rbacregistryvalidation.NewDefaultRuleResolver(\n\t\t\troles, roleBindings, clusterRoles, clusterRoleBindings,\n\t\t),\n\t}\n\treturn subjectLocator\n}","line":{"from":48,"to":58}} {"id":100013690,"name":"AllowedSubjects","signature":"func (r *SubjectAccessEvaluator) AllowedSubjects(requestAttributes authorizer.Attributes) ([]rbacv1.Subject, error)","file":"plugin/pkg/auth/authorizer/rbac/subject_locator.go","code":"// AllowedSubjects returns the subjects that can perform an action and any errors encountered while computing the list.\n// It is possible to have both subjects and errors returned if some rolebindings couldn't be resolved, but others could be.\nfunc (r *SubjectAccessEvaluator) AllowedSubjects(requestAttributes authorizer.Attributes) ([]rbacv1.Subject, error) {\n\tsubjects := []rbacv1.Subject{{Kind: rbacv1.GroupKind, APIGroup: rbacv1.GroupName, Name: user.SystemPrivilegedGroup}}\n\tif len(r.superUser) \u003e 0 {\n\t\tsubjects = append(subjects, rbacv1.Subject{Kind: rbacv1.UserKind, APIGroup: rbacv1.GroupName, Name: r.superUser})\n\t}\n\terrorlist := []error{}\n\n\tif clusterRoleBindings, err := r.clusterRoleBindingLister.ListClusterRoleBindings(); err != nil {\n\t\terrorlist = append(errorlist, err)\n\n\t} else {\n\t\tfor _, clusterRoleBinding := range clusterRoleBindings {\n\t\t\trules, err := r.roleToRuleMapper.GetRoleReferenceRules(clusterRoleBinding.RoleRef, \"\")\n\t\t\tif err != nil {\n\t\t\t\t// if we have an error, just keep track of it and keep processing. Since rules are additive,\n\t\t\t\t// missing a reference is bad, but we can continue with other rolebindings and still have a list\n\t\t\t\t// that does not contain any invalid values\n\t\t\t\terrorlist = append(errorlist, err)\n\t\t\t}\n\t\t\tif RulesAllow(requestAttributes, rules...) {\n\t\t\t\tsubjects = append(subjects, clusterRoleBinding.Subjects...)\n\t\t\t}\n\t\t}\n\t}\n\n\tif namespace := requestAttributes.GetNamespace(); len(namespace) \u003e 0 {\n\t\tif roleBindings, err := r.roleBindingLister.ListRoleBindings(namespace); err != nil {\n\t\t\terrorlist = append(errorlist, err)\n\n\t\t} else {\n\t\t\tfor _, roleBinding := range roleBindings {\n\t\t\t\trules, err := r.roleToRuleMapper.GetRoleReferenceRules(roleBinding.RoleRef, namespace)\n\t\t\t\tif err != nil {\n\t\t\t\t\t// if we have an error, just keep track of it and keep processing. Since rules are additive,\n\t\t\t\t\t// missing a reference is bad, but we can continue with other rolebindings and still have a list\n\t\t\t\t\t// that does not contain any invalid values\n\t\t\t\t\terrorlist = append(errorlist, err)\n\t\t\t\t}\n\t\t\t\tif RulesAllow(requestAttributes, rules...) {\n\t\t\t\t\tsubjects = append(subjects, roleBinding.Subjects...)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tdedupedSubjects := []rbacv1.Subject{}\n\tfor _, subject := range subjects {\n\t\tfound := false\n\t\tfor _, curr := range dedupedSubjects {\n\t\t\tif curr == subject {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\tdedupedSubjects = append(dedupedSubjects, subject)\n\t\t}\n\t}\n\n\treturn subjects, utilerrors.NewAggregate(errorlist)\n}","line":{"from":60,"to":123}} {"id":100013691,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/admission/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013692,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/admission/v1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026AdmissionReview{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":46,"to":53}} {"id":100013693,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/admission/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013694,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/admission/v1beta1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026AdmissionReview{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":46,"to":53}} {"id":100013695,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/admissionregistration/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013696,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/admissionregistration/v1/register.go","code":"// Adds the list of known types to scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026ValidatingWebhookConfiguration{},\n\t\t\u0026ValidatingWebhookConfigurationList{},\n\t\t\u0026MutatingWebhookConfiguration{},\n\t\t\u0026MutatingWebhookConfigurationList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":46,"to":56}} {"id":100013697,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/admissionregistration/v1alpha1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013698,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/admissionregistration/v1alpha1/register.go","code":"// Adds the list of known types to scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026ValidatingAdmissionPolicy{},\n\t\t\u0026ValidatingAdmissionPolicyList{},\n\t\t\u0026ValidatingAdmissionPolicyBinding{},\n\t\t\u0026ValidatingAdmissionPolicyBindingList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":46,"to":56}} {"id":100013699,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/admissionregistration/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013700,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/admissionregistration/v1beta1/register.go","code":"// Adds the list of known types to scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026ValidatingWebhookConfiguration{},\n\t\t\u0026ValidatingWebhookConfigurationList{},\n\t\t\u0026MutatingWebhookConfiguration{},\n\t\t\u0026MutatingWebhookConfigurationList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":46,"to":56}} {"id":100013701,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/api/apidiscovery/v2beta1/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":31,"to":34}} {"id":100013702,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/apidiscovery/v2beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":36,"to":39}} {"id":100013703,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/apidiscovery/v2beta1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026APIGroupDiscoveryList{},\n\t\t\u0026APIGroupDiscovery{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":48,"to":56}} {"id":100013704,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/apiserverinternal/v1alpha1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013705,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/apiserverinternal/v1alpha1/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026StorageVersion{},\n\t\t\u0026StorageVersionList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":41,"to":48}} {"id":100013706,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/apps/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013707,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/apps/v1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Deployment{},\n\t\t\u0026DeploymentList{},\n\t\t\u0026StatefulSet{},\n\t\t\u0026StatefulSetList{},\n\t\t\u0026DaemonSet{},\n\t\t\u0026DaemonSetList{},\n\t\t\u0026ReplicaSet{},\n\t\t\u0026ReplicaSetList{},\n\t\t\u0026ControllerRevision{},\n\t\t\u0026ControllerRevisionList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":60}} {"id":100013708,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/apps/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013709,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/apps/v1beta1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Deployment{},\n\t\t\u0026DeploymentList{},\n\t\t\u0026DeploymentRollback{},\n\t\t\u0026Scale{},\n\t\t\u0026StatefulSet{},\n\t\t\u0026StatefulSetList{},\n\t\t\u0026ControllerRevision{},\n\t\t\u0026ControllerRevisionList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":58}} {"id":100013710,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/apps/v1beta2/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013711,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/apps/v1beta2/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Deployment{},\n\t\t\u0026DeploymentList{},\n\t\t\u0026Scale{},\n\t\t\u0026StatefulSet{},\n\t\t\u0026StatefulSetList{},\n\t\t\u0026DaemonSet{},\n\t\t\u0026DaemonSetList{},\n\t\t\u0026ReplicaSet{},\n\t\t\u0026ReplicaSetList{},\n\t\t\u0026ControllerRevision{},\n\t\t\u0026ControllerRevisionList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":61}} {"id":100013712,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/authentication/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013713,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/authentication/v1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026TokenReview{},\n\t\t\u0026TokenRequest{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":52}} {"id":100013714,"name":"String","signature":"func (t ExtraValue) String() string","file":"staging/src/k8s.io/api/authentication/v1/types.go","code":"func (t ExtraValue) String() string {\n\treturn fmt.Sprintf(\"%v\", []string(t))\n}","line":{"from":129,"to":131}} {"id":100013715,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/authentication/v1alpha1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013716,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/authentication/v1alpha1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026SelfSubjectReview{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":51}} {"id":100013717,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/authentication/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013718,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/authentication/v1beta1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026SelfSubjectReview{},\n\t\t\u0026TokenReview{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":52}} {"id":100013719,"name":"String","signature":"func (t ExtraValue) String() string","file":"staging/src/k8s.io/api/authentication/v1beta1/types.go","code":"func (t ExtraValue) String() string {\n\treturn fmt.Sprintf(\"%v\", []string(t))\n}","line":{"from":114,"to":116}} {"id":100013720,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/authorization/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013721,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/authorization/v1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026SelfSubjectRulesReview{},\n\t\t\u0026SelfSubjectAccessReview{},\n\t\t\u0026SubjectAccessReview{},\n\t\t\u0026LocalSubjectAccessReview{},\n\t)\n\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":55}} {"id":100013722,"name":"String","signature":"func (t ExtraValue) String() string","file":"staging/src/k8s.io/api/authorization/v1/types.go","code":"func (t ExtraValue) String() string {\n\treturn fmt.Sprintf(\"%v\", []string(t))\n}","line":{"from":161,"to":163}} {"id":100013723,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/authorization/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013724,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/authorization/v1beta1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026SelfSubjectRulesReview{},\n\t\t\u0026SelfSubjectAccessReview{},\n\t\t\u0026SubjectAccessReview{},\n\t\t\u0026LocalSubjectAccessReview{},\n\t)\n\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":55}} {"id":100013725,"name":"String","signature":"func (t ExtraValue) String() string","file":"staging/src/k8s.io/api/authorization/v1beta1/types.go","code":"func (t ExtraValue) String() string {\n\treturn fmt.Sprintf(\"%v\", []string(t))\n}","line":{"from":170,"to":172}} {"id":100013726,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/autoscaling/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013727,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/autoscaling/v1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026HorizontalPodAutoscaler{},\n\t\t\u0026HorizontalPodAutoscalerList{},\n\t\t\u0026Scale{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":53}} {"id":100013728,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/autoscaling/v2/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013729,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/autoscaling/v2/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026HorizontalPodAutoscaler{},\n\t\t\u0026HorizontalPodAutoscalerList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":42,"to":50}} {"id":100013730,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/autoscaling/v2beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013731,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/autoscaling/v2beta1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026HorizontalPodAutoscaler{},\n\t\t\u0026HorizontalPodAutoscalerList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":52}} {"id":100013732,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/autoscaling/v2beta2/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013733,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/autoscaling/v2beta2/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026HorizontalPodAutoscaler{},\n\t\t\u0026HorizontalPodAutoscalerList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":42,"to":50}} {"id":100013734,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/batch/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013735,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/batch/v1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Job{},\n\t\t\u0026JobList{},\n\t\t\u0026CronJob{},\n\t\t\u0026CronJobList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":54}} {"id":100013736,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/batch/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013737,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/batch/v1beta1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026CronJob{},\n\t\t\u0026CronJobList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":52}} {"id":100013738,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/api/certificates/v1/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":31,"to":34}} {"id":100013739,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/certificates/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":36,"to":39}} {"id":100013740,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/certificates/v1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026CertificateSigningRequest{},\n\t\t\u0026CertificateSigningRequestList{},\n\t)\n\n\t// Add the watch version that applies\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":51,"to":61}} {"id":100013741,"name":"String","signature":"func (t ExtraValue) String() string","file":"staging/src/k8s.io/api/certificates/v1/types.go","code":"func (t ExtraValue) String() string {\n\treturn fmt.Sprintf(\"%v\", []string(t))\n}","line":{"from":169,"to":171}} {"id":100013742,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/api/certificates/v1alpha1/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":31,"to":34}} {"id":100013743,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/certificates/v1alpha1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":36,"to":39}} {"id":100013744,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/certificates/v1alpha1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026ClusterTrustBundle{},\n\t\t\u0026ClusterTrustBundleList{},\n\t)\n\n\t// Add the watch version that applies\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":51,"to":61}} {"id":100013745,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/api/certificates/v1beta1/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":31,"to":34}} {"id":100013746,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/certificates/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":36,"to":39}} {"id":100013747,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/certificates/v1beta1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026CertificateSigningRequest{},\n\t\t\u0026CertificateSigningRequestList{},\n\t)\n\n\t// Add the watch version that applies\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":49,"to":59}} {"id":100013748,"name":"String","signature":"func (t ExtraValue) String() string","file":"staging/src/k8s.io/api/certificates/v1beta1/types.go","code":"func (t ExtraValue) String() string {\n\treturn fmt.Sprintf(\"%v\", []string(t))\n}","line":{"from":169,"to":171}} {"id":100013749,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/coordination/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013750,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/coordination/v1/register.go","code":"// Adds the list of known types to api.Scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Lease{},\n\t\t\u0026LeaseList{},\n\t)\n\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":53}} {"id":100013751,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/coordination/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013752,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/coordination/v1beta1/register.go","code":"// Adds the list of known types to api.Scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Lease{},\n\t\t\u0026LeaseList{},\n\t)\n\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":53}} {"id":100013753,"name":"APILifecycleIntroduced","signature":"func (in *ComponentStatus) APILifecycleIntroduced() (major, minor int)","file":"staging/src/k8s.io/api/core/v1/lifecycle.go","code":"// APILifecycleIntroduced returns the release in which the API struct was introduced as int versions of major and minor for comparison.\nfunc (in *ComponentStatus) APILifecycleIntroduced() (major, minor int) {\n\treturn 1, 0\n}","line":{"from":19,"to":22}} {"id":100013754,"name":"APILifecycleDeprecated","signature":"func (in *ComponentStatus) APILifecycleDeprecated() (major, minor int)","file":"staging/src/k8s.io/api/core/v1/lifecycle.go","code":"// APILifecycleDeprecated returns the release in which the API struct was or will be deprecated as int versions of major and minor for comparison.\nfunc (in *ComponentStatus) APILifecycleDeprecated() (major, minor int) {\n\treturn 1, 19\n}","line":{"from":24,"to":27}} {"id":100013755,"name":"APILifecycleIntroduced","signature":"func (in *ComponentStatusList) APILifecycleIntroduced() (major, minor int)","file":"staging/src/k8s.io/api/core/v1/lifecycle.go","code":"// APILifecycleIntroduced returns the release in which the API struct was introduced as int versions of major and minor for comparison.\nfunc (in *ComponentStatusList) APILifecycleIntroduced() (major, minor int) {\n\treturn 1, 0\n}","line":{"from":29,"to":32}} {"id":100013756,"name":"APILifecycleDeprecated","signature":"func (in *ComponentStatusList) APILifecycleDeprecated() (major, minor int)","file":"staging/src/k8s.io/api/core/v1/lifecycle.go","code":"// APILifecycleDeprecated returns the release in which the API struct was or will be deprecated as int versions of major and minor for comparison.\nfunc (in *ComponentStatusList) APILifecycleDeprecated() (major, minor int) {\n\treturn 1, 19\n}","line":{"from":34,"to":37}} {"id":100013757,"name":"SetGroupVersionKind","signature":"func (obj *ObjectReference) SetGroupVersionKind(gvk schema.GroupVersionKind)","file":"staging/src/k8s.io/api/core/v1/objectreference.go","code":"// IsAnAPIObject allows clients to preemptively get a reference to an API object and pass it to places that\n// intend only to get a reference to that object. This simplifies the event recording interface.\nfunc (obj *ObjectReference) SetGroupVersionKind(gvk schema.GroupVersionKind) {\n\tobj.APIVersion, obj.Kind = gvk.ToAPIVersionAndKind()\n}","line":{"from":23,"to":27}} {"id":100013758,"name":"GroupVersionKind","signature":"func (obj *ObjectReference) GroupVersionKind() schema.GroupVersionKind","file":"staging/src/k8s.io/api/core/v1/objectreference.go","code":"func (obj *ObjectReference) GroupVersionKind() schema.GroupVersionKind {\n\treturn schema.FromAPIVersionAndKind(obj.APIVersion, obj.Kind)\n}","line":{"from":29,"to":31}} {"id":100013759,"name":"GetObjectKind","signature":"func (obj *ObjectReference) GetObjectKind() schema.ObjectKind { return obj }","file":"staging/src/k8s.io/api/core/v1/objectreference.go","code":"func (obj *ObjectReference) GetObjectKind() schema.ObjectKind { return obj }","line":{"from":33,"to":33}} {"id":100013760,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/core/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013761,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/core/v1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Pod{},\n\t\t\u0026PodList{},\n\t\t\u0026PodStatusResult{},\n\t\t\u0026PodTemplate{},\n\t\t\u0026PodTemplateList{},\n\t\t\u0026ReplicationController{},\n\t\t\u0026ReplicationControllerList{},\n\t\t\u0026Service{},\n\t\t\u0026ServiceProxyOptions{},\n\t\t\u0026ServiceList{},\n\t\t\u0026Endpoints{},\n\t\t\u0026EndpointsList{},\n\t\t\u0026Node{},\n\t\t\u0026NodeList{},\n\t\t\u0026NodeProxyOptions{},\n\t\t\u0026Binding{},\n\t\t\u0026Event{},\n\t\t\u0026EventList{},\n\t\t\u0026List{},\n\t\t\u0026LimitRange{},\n\t\t\u0026LimitRangeList{},\n\t\t\u0026ResourceQuota{},\n\t\t\u0026ResourceQuotaList{},\n\t\t\u0026Namespace{},\n\t\t\u0026NamespaceList{},\n\t\t\u0026Secret{},\n\t\t\u0026SecretList{},\n\t\t\u0026ServiceAccount{},\n\t\t\u0026ServiceAccountList{},\n\t\t\u0026PersistentVolume{},\n\t\t\u0026PersistentVolumeList{},\n\t\t\u0026PersistentVolumeClaim{},\n\t\t\u0026PersistentVolumeClaimList{},\n\t\t\u0026PodAttachOptions{},\n\t\t\u0026PodLogOptions{},\n\t\t\u0026PodExecOptions{},\n\t\t\u0026PodPortForwardOptions{},\n\t\t\u0026PodProxyOptions{},\n\t\t\u0026ComponentStatus{},\n\t\t\u0026ComponentStatusList{},\n\t\t\u0026SerializedReference{},\n\t\t\u0026RangeAllocation{},\n\t\t\u0026ConfigMap{},\n\t\t\u0026ConfigMapList{},\n\t)\n\n\t// Add common types\n\tscheme.AddKnownTypes(SchemeGroupVersion, \u0026metav1.Status{})\n\n\t// Add the watch version that applies\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":99}} {"id":100013762,"name":"String","signature":"func (rn ResourceName) String() string","file":"staging/src/k8s.io/api/core/v1/resource.go","code":"// Returns string version of ResourceName.\nfunc (rn ResourceName) String() string {\n\treturn string(rn)\n}","line":{"from":23,"to":26}} {"id":100013763,"name":"Cpu","signature":"func (rl *ResourceList) Cpu() *resource.Quantity","file":"staging/src/k8s.io/api/core/v1/resource.go","code":"// Cpu returns the Cpu limit if specified.\nfunc (rl *ResourceList) Cpu() *resource.Quantity {\n\treturn rl.Name(ResourceCPU, resource.DecimalSI)\n}","line":{"from":28,"to":31}} {"id":100013764,"name":"Memory","signature":"func (rl *ResourceList) Memory() *resource.Quantity","file":"staging/src/k8s.io/api/core/v1/resource.go","code":"// Memory returns the Memory limit if specified.\nfunc (rl *ResourceList) Memory() *resource.Quantity {\n\treturn rl.Name(ResourceMemory, resource.BinarySI)\n}","line":{"from":33,"to":36}} {"id":100013765,"name":"Storage","signature":"func (rl *ResourceList) Storage() *resource.Quantity","file":"staging/src/k8s.io/api/core/v1/resource.go","code":"// Storage returns the Storage limit if specified.\nfunc (rl *ResourceList) Storage() *resource.Quantity {\n\treturn rl.Name(ResourceStorage, resource.BinarySI)\n}","line":{"from":38,"to":41}} {"id":100013766,"name":"Pods","signature":"func (rl *ResourceList) Pods() *resource.Quantity","file":"staging/src/k8s.io/api/core/v1/resource.go","code":"// Pods returns the list of pods\nfunc (rl *ResourceList) Pods() *resource.Quantity {\n\treturn rl.Name(ResourcePods, resource.DecimalSI)\n}","line":{"from":43,"to":46}} {"id":100013767,"name":"StorageEphemeral","signature":"func (rl *ResourceList) StorageEphemeral() *resource.Quantity","file":"staging/src/k8s.io/api/core/v1/resource.go","code":"// StorageEphemeral returns the list of ephemeral storage volumes, if any\nfunc (rl *ResourceList) StorageEphemeral() *resource.Quantity {\n\treturn rl.Name(ResourceEphemeralStorage, resource.BinarySI)\n}","line":{"from":48,"to":51}} {"id":100013768,"name":"Name","signature":"func (rl *ResourceList) Name(name ResourceName, defaultFormat resource.Format) *resource.Quantity","file":"staging/src/k8s.io/api/core/v1/resource.go","code":"// Name returns the resource with name if specified, otherwise it returns a nil quantity with default format.\nfunc (rl *ResourceList) Name(name ResourceName, defaultFormat resource.Format) *resource.Quantity {\n\tif val, ok := (*rl)[name]; ok {\n\t\treturn \u0026val\n\t}\n\treturn \u0026resource.Quantity{Format: defaultFormat}\n}","line":{"from":53,"to":59}} {"id":100013769,"name":"MatchTaint","signature":"func (t *Taint) MatchTaint(taintToMatch *Taint) bool","file":"staging/src/k8s.io/api/core/v1/taint.go","code":"// MatchTaint checks if the taint matches taintToMatch. Taints are unique by key:effect,\n// if the two taints have same key:effect, regard as they match.\nfunc (t *Taint) MatchTaint(taintToMatch *Taint) bool {\n\treturn t.Key == taintToMatch.Key \u0026\u0026 t.Effect == taintToMatch.Effect\n}","line":{"from":21,"to":25}} {"id":100013770,"name":"ToString","signature":"func (t *Taint) ToString() string","file":"staging/src/k8s.io/api/core/v1/taint.go","code":"// taint.ToString() converts taint struct to string in format '\u003ckey\u003e=\u003cvalue\u003e:\u003ceffect\u003e', '\u003ckey\u003e=\u003cvalue\u003e:', '\u003ckey\u003e:\u003ceffect\u003e', or '\u003ckey\u003e'.\nfunc (t *Taint) ToString() string {\n\tif len(t.Effect) == 0 {\n\t\tif len(t.Value) == 0 {\n\t\t\treturn fmt.Sprintf(\"%v\", t.Key)\n\t\t}\n\t\treturn fmt.Sprintf(\"%v=%v:\", t.Key, t.Value)\n\t}\n\tif len(t.Value) == 0 {\n\t\treturn fmt.Sprintf(\"%v:%v\", t.Key, t.Effect)\n\t}\n\treturn fmt.Sprintf(\"%v=%v:%v\", t.Key, t.Value, t.Effect)\n}","line":{"from":27,"to":39}} {"id":100013771,"name":"MatchToleration","signature":"func (t *Toleration) MatchToleration(tolerationToMatch *Toleration) bool","file":"staging/src/k8s.io/api/core/v1/toleration.go","code":"// MatchToleration checks if the toleration matches tolerationToMatch. Tolerations are unique by \u003ckey,effect,operator,value\u003e,\n// if the two tolerations have same \u003ckey,effect,operator,value\u003e combination, regard as they match.\n// TODO: uniqueness check for tolerations in api validations.\nfunc (t *Toleration) MatchToleration(tolerationToMatch *Toleration) bool {\n\treturn t.Key == tolerationToMatch.Key \u0026\u0026\n\t\tt.Effect == tolerationToMatch.Effect \u0026\u0026\n\t\tt.Operator == tolerationToMatch.Operator \u0026\u0026\n\t\tt.Value == tolerationToMatch.Value\n}","line":{"from":19,"to":27}} {"id":100013772,"name":"ToleratesTaint","signature":"func (t *Toleration) ToleratesTaint(taint *Taint) bool","file":"staging/src/k8s.io/api/core/v1/toleration.go","code":"// ToleratesTaint checks if the toleration tolerates the taint.\n// The matching follows the rules below:\n//\n// 1. Empty toleration.effect means to match all taint effects,\n// otherwise taint effect must equal to toleration.effect.\n// 2. If toleration.operator is 'Exists', it means to match all taint values.\n// 3. Empty toleration.key means to match all taint keys.\n// If toleration.key is empty, toleration.operator must be 'Exists';\n// this combination means to match all taint values and all taint keys.\nfunc (t *Toleration) ToleratesTaint(taint *Taint) bool {\n\tif len(t.Effect) \u003e 0 \u0026\u0026 t.Effect != taint.Effect {\n\t\treturn false\n\t}\n\n\tif len(t.Key) \u003e 0 \u0026\u0026 t.Key != taint.Key {\n\t\treturn false\n\t}\n\n\t// TODO: Use proper defaulting when Toleration becomes a field of PodSpec\n\tswitch t.Operator {\n\t// empty operator means Equal\n\tcase \"\", TolerationOpEqual:\n\t\treturn t.Value == taint.Value\n\tcase TolerationOpExists:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":29,"to":57}} {"id":100013773,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/api/discovery/v1/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":31,"to":34}} {"id":100013774,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/discovery/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":36,"to":39}} {"id":100013775,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/discovery/v1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026EndpointSlice{},\n\t\t\u0026EndpointSliceList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":48,"to":56}} {"id":100013776,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/api/discovery/v1beta1/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":31,"to":34}} {"id":100013777,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/discovery/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":36,"to":39}} {"id":100013778,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/discovery/v1beta1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026EndpointSlice{},\n\t\t\u0026EndpointSliceList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":48,"to":56}} {"id":100013779,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/events/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013780,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/events/v1/register.go","code":"// Adds the list of known types to api.Scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Event{},\n\t\t\u0026EventList{},\n\t)\n\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":53}} {"id":100013781,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/events/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013782,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/events/v1beta1/register.go","code":"// Adds the list of known types to api.Scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Event{},\n\t\t\u0026EventList{},\n\t)\n\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":53}} {"id":100013783,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/extensions/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013784,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/extensions/v1beta1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Deployment{},\n\t\t\u0026DeploymentList{},\n\t\t\u0026DeploymentRollback{},\n\t\t\u0026Scale{},\n\t\t\u0026DaemonSetList{},\n\t\t\u0026DaemonSet{},\n\t\t\u0026Ingress{},\n\t\t\u0026IngressList{},\n\t\t\u0026ReplicaSet{},\n\t\t\u0026ReplicaSetList{},\n\t\t\u0026NetworkPolicy{},\n\t\t\u0026NetworkPolicyList{},\n\t)\n\t// Add the watch version that applies\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":63}} {"id":100013785,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/api/flowcontrol/v1alpha1/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":31,"to":34}} {"id":100013786,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/flowcontrol/v1alpha1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":36,"to":39}} {"id":100013787,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/flowcontrol/v1alpha1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026FlowSchema{},\n\t\t\u0026FlowSchemaList{},\n\t\t\u0026PriorityLevelConfiguration{},\n\t\t\u0026PriorityLevelConfigurationList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":48,"to":58}} {"id":100013788,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/api/flowcontrol/v1beta1/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":31,"to":34}} {"id":100013789,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/flowcontrol/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":36,"to":39}} {"id":100013790,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/flowcontrol/v1beta1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026FlowSchema{},\n\t\t\u0026FlowSchemaList{},\n\t\t\u0026PriorityLevelConfiguration{},\n\t\t\u0026PriorityLevelConfigurationList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":48,"to":58}} {"id":100013791,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/api/flowcontrol/v1beta2/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":31,"to":34}} {"id":100013792,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/flowcontrol/v1beta2/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":36,"to":39}} {"id":100013793,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/flowcontrol/v1beta2/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026FlowSchema{},\n\t\t\u0026FlowSchemaList{},\n\t\t\u0026PriorityLevelConfiguration{},\n\t\t\u0026PriorityLevelConfigurationList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":48,"to":58}} {"id":100013794,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/api/flowcontrol/v1beta3/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":31,"to":34}} {"id":100013795,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/flowcontrol/v1beta3/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":36,"to":39}} {"id":100013796,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/flowcontrol/v1beta3/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026FlowSchema{},\n\t\t\u0026FlowSchemaList{},\n\t\t\u0026PriorityLevelConfiguration{},\n\t\t\u0026PriorityLevelConfigurationList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":48,"to":58}} {"id":100013797,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/imagepolicy/v1alpha1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013798,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/imagepolicy/v1alpha1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026ImageReview{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":51}} {"id":100013799,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/networking/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013800,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/networking/v1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Ingress{},\n\t\t\u0026IngressList{},\n\t\t\u0026IngressClass{},\n\t\t\u0026IngressClassList{},\n\t\t\u0026NetworkPolicy{},\n\t\t\u0026NetworkPolicyList{},\n\t)\n\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":57}} {"id":100013801,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/api/networking/v1alpha1/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind.\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":31,"to":34}} {"id":100013802,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/networking/v1alpha1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource.\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":36,"to":39}} {"id":100013803,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/networking/v1alpha1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026ClusterCIDR{},\n\t\t\u0026ClusterCIDRList{},\n\t\t\u0026IPAddress{},\n\t\t\u0026IPAddressList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":52,"to":62}} {"id":100013804,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/networking/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013805,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/networking/v1beta1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Ingress{},\n\t\t\u0026IngressList{},\n\t\t\u0026IngressClass{},\n\t\t\u0026IngressClassList{},\n\t)\n\t// Add the watch version that applies\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":47,"to":58}} {"id":100013806,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/node/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013807,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/node/v1/register.go","code":"// addKnownTypes adds the list of known types to api.Scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026RuntimeClass{},\n\t\t\u0026RuntimeClassList{},\n\t)\n\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":43,"to":52}} {"id":100013808,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/node/v1alpha1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013809,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/node/v1alpha1/register.go","code":"// addKnownTypes adds the list of known types to api.Scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026RuntimeClass{},\n\t\t\u0026RuntimeClassList{},\n\t)\n\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":43,"to":52}} {"id":100013810,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/node/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013811,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/node/v1beta1/register.go","code":"// addKnownTypes adds the list of known types to api.Scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026RuntimeClass{},\n\t\t\u0026RuntimeClassList{},\n\t)\n\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":43,"to":52}} {"id":100013812,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/policy/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013813,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/policy/v1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026PodDisruptionBudget{},\n\t\t\u0026PodDisruptionBudgetList{},\n\t\t\u0026Eviction{},\n\t)\n\t// Add the watch version that applies\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":42,"to":52}} {"id":100013814,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/policy/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013815,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/policy/v1beta1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026PodDisruptionBudget{},\n\t\t\u0026PodDisruptionBudgetList{},\n\t\t\u0026PodSecurityPolicy{},\n\t\t\u0026PodSecurityPolicyList{},\n\t\t\u0026Eviction{},\n\t)\n\t// Add the watch version that applies\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":56}} {"id":100013816,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/rbac/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100013817,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/rbac/v1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Role{},\n\t\t\u0026RoleBinding{},\n\t\t\u0026RoleBindingList{},\n\t\t\u0026RoleList{},\n\n\t\t\u0026ClusterRole{},\n\t\t\u0026ClusterRoleBinding{},\n\t\t\u0026ClusterRoleBindingList{},\n\t\t\u0026ClusterRoleList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":43,"to":58}} {"id":100013818,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/rbac/v1alpha1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100013819,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/rbac/v1alpha1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Role{},\n\t\t\u0026RoleBinding{},\n\t\t\u0026RoleBindingList{},\n\t\t\u0026RoleList{},\n\n\t\t\u0026ClusterRole{},\n\t\t\u0026ClusterRoleBinding{},\n\t\t\u0026ClusterRoleBindingList{},\n\t\t\u0026ClusterRoleList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":43,"to":58}} {"id":100013820,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/rbac/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100013821,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/rbac/v1beta1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Role{},\n\t\t\u0026RoleBinding{},\n\t\t\u0026RoleBindingList{},\n\t\t\u0026RoleList{},\n\n\t\t\u0026ClusterRole{},\n\t\t\u0026ClusterRoleBinding{},\n\t\t\u0026ClusterRoleBindingList{},\n\t\t\u0026ClusterRoleList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":43,"to":58}} {"id":100013822,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/resource/v1alpha2/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013823,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/resource/v1alpha2/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026ResourceClass{},\n\t\t\u0026ResourceClassList{},\n\t\t\u0026ResourceClaim{},\n\t\t\u0026ResourceClaimList{},\n\t\t\u0026ResourceClaimTemplate{},\n\t\t\u0026ResourceClaimTemplateList{},\n\t\t\u0026PodSchedulingContext{},\n\t\t\u0026PodSchedulingContextList{},\n\t)\n\n\t// Add common types\n\tscheme.AddKnownTypes(SchemeGroupVersion, \u0026metav1.Status{})\n\n\t// Add the watch version that applies\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":63}} {"id":100013824,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/scheduling/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013825,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/scheduling/v1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026PriorityClass{},\n\t\t\u0026PriorityClassList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":47,"to":55}} {"id":100013826,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/scheduling/v1alpha1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013827,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/scheduling/v1alpha1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026PriorityClass{},\n\t\t\u0026PriorityClassList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":52}} {"id":100013828,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/scheduling/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013829,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/scheduling/v1beta1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026PriorityClass{},\n\t\t\u0026PriorityClassList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":52}} {"id":100013830,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/storage/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013831,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/storage/v1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026StorageClass{},\n\t\t\u0026StorageClassList{},\n\n\t\t\u0026VolumeAttachment{},\n\t\t\u0026VolumeAttachmentList{},\n\n\t\t\u0026CSINode{},\n\t\t\u0026CSINodeList{},\n\n\t\t\u0026CSIDriver{},\n\t\t\u0026CSIDriverList{},\n\n\t\t\u0026CSIStorageCapacity{},\n\t\t\u0026CSIStorageCapacityList{},\n\t)\n\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":65}} {"id":100013832,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/storage/v1alpha1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013833,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/storage/v1alpha1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026VolumeAttachment{},\n\t\t\u0026VolumeAttachmentList{},\n\t\t\u0026CSIStorageCapacity{},\n\t\t\u0026CSIStorageCapacityList{},\n\t)\n\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":41,"to":52}} {"id":100013834,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/api/storage/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100013835,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/api/storage/v1beta1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026StorageClass{},\n\t\t\u0026StorageClassList{},\n\n\t\t\u0026VolumeAttachment{},\n\t\t\u0026VolumeAttachmentList{},\n\n\t\t\u0026CSIDriver{},\n\t\t\u0026CSIDriverList{},\n\n\t\t\u0026CSINode{},\n\t\t\u0026CSINodeList{},\n\n\t\t\u0026CSIStorageCapacity{},\n\t\t\u0026CSIStorageCapacityList{},\n\t)\n\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":65}} {"id":100013836,"name":"main","signature":"func main()","file":"staging/src/k8s.io/apiextensions-apiserver/main.go","code":"func main() {\n\tstopCh := genericapiserver.SetupSignalHandler()\n\tcmd := server.NewServerCommand(os.Stdout, os.Stderr, stopCh)\n\tcode := cli.Run(cmd)\n\tos.Exit(code)\n}","line":{"from":27,"to":32}} {"id":100013837,"name":"IsProtectedCommunityGroup","signature":"func IsProtectedCommunityGroup(group string) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apihelpers/helpers.go","code":"// IsProtectedCommunityGroup returns whether or not a group specified for a CRD is protected for the community and needs\n// to have the v1beta1.KubeAPIApprovalAnnotation set.\nfunc IsProtectedCommunityGroup(group string) bool {\n\tswitch {\n\tcase group == \"k8s.io\" || strings.HasSuffix(group, \".k8s.io\"):\n\t\treturn true\n\tcase group == \"kubernetes.io\" || strings.HasSuffix(group, \".kubernetes.io\"):\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n\n}","line":{"from":29,"to":41}} {"id":100013838,"name":"GetAPIApprovalState","signature":"func GetAPIApprovalState(annotations map[string]string) (state APIApprovalState, reason string)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apihelpers/helpers.go","code":"// GetAPIApprovalState returns the state of the API approval and reason for that state\nfunc GetAPIApprovalState(annotations map[string]string) (state APIApprovalState, reason string) {\n\tannotation := annotations[apiextensionsv1.KubeAPIApprovedAnnotation]\n\n\t// we use the result of this parsing in the switch/case below\n\turl, annotationURLParseErr := url.ParseRequestURI(annotation)\n\tswitch {\n\tcase len(annotation) == 0:\n\t\treturn APIApprovalMissing, fmt.Sprintf(\"protected groups must have approval annotation %q, see https://github.com/kubernetes/enhancements/pull/1111\", apiextensionsv1.KubeAPIApprovedAnnotation)\n\tcase strings.HasPrefix(annotation, \"unapproved\"):\n\t\treturn APIApprovalBypassed, fmt.Sprintf(\"not approved: %q\", annotation)\n\tcase annotationURLParseErr == nil \u0026\u0026 url != nil \u0026\u0026 len(url.Host) \u003e 0 \u0026\u0026 len(url.Scheme) \u003e 0:\n\t\treturn APIApproved, fmt.Sprintf(\"approved in %v\", annotation)\n\tdefault:\n\t\treturn APIApprovalInvalid, fmt.Sprintf(\"protected groups must have approval annotation %q with either a URL or a reason starting with \\\"unapproved\\\", see https://github.com/kubernetes/enhancements/pull/1111\", apiextensionsv1.KubeAPIApprovedAnnotation)\n\t}\n}","line":{"from":57,"to":73}} {"id":100013839,"name":"SetCRDCondition","signature":"func SetCRDCondition(crd *apiextensionsv1.CustomResourceDefinition, newCondition apiextensionsv1.CustomResourceDefinitionCondition)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apihelpers/helpers.go","code":"// SetCRDCondition sets the status condition. It either overwrites the existing one or creates a new one.\nfunc SetCRDCondition(crd *apiextensionsv1.CustomResourceDefinition, newCondition apiextensionsv1.CustomResourceDefinitionCondition) {\n\tnewCondition.LastTransitionTime = metav1.NewTime(time.Now())\n\n\texistingCondition := FindCRDCondition(crd, newCondition.Type)\n\tif existingCondition == nil {\n\t\tcrd.Status.Conditions = append(crd.Status.Conditions, newCondition)\n\t\treturn\n\t}\n\n\tif existingCondition.Status != newCondition.Status || existingCondition.LastTransitionTime.IsZero() {\n\t\texistingCondition.LastTransitionTime = newCondition.LastTransitionTime\n\t}\n\n\texistingCondition.Status = newCondition.Status\n\texistingCondition.Reason = newCondition.Reason\n\texistingCondition.Message = newCondition.Message\n}","line":{"from":75,"to":92}} {"id":100013840,"name":"RemoveCRDCondition","signature":"func RemoveCRDCondition(crd *apiextensionsv1.CustomResourceDefinition, conditionType apiextensionsv1.CustomResourceDefinitionConditionType)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apihelpers/helpers.go","code":"// RemoveCRDCondition removes the status condition.\nfunc RemoveCRDCondition(crd *apiextensionsv1.CustomResourceDefinition, conditionType apiextensionsv1.CustomResourceDefinitionConditionType) {\n\tnewConditions := []apiextensionsv1.CustomResourceDefinitionCondition{}\n\tfor _, condition := range crd.Status.Conditions {\n\t\tif condition.Type != conditionType {\n\t\t\tnewConditions = append(newConditions, condition)\n\t\t}\n\t}\n\tcrd.Status.Conditions = newConditions\n}","line":{"from":94,"to":103}} {"id":100013841,"name":"FindCRDCondition","signature":"func FindCRDCondition(crd *apiextensionsv1.CustomResourceDefinition, conditionType apiextensionsv1.CustomResourceDefinitionConditionType) *apiextensionsv1.CustomResourceDefinitionCondition","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apihelpers/helpers.go","code":"// FindCRDCondition returns the condition you're looking for or nil.\nfunc FindCRDCondition(crd *apiextensionsv1.CustomResourceDefinition, conditionType apiextensionsv1.CustomResourceDefinitionConditionType) *apiextensionsv1.CustomResourceDefinitionCondition {\n\tfor i := range crd.Status.Conditions {\n\t\tif crd.Status.Conditions[i].Type == conditionType {\n\t\t\treturn \u0026crd.Status.Conditions[i]\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":105,"to":114}} {"id":100013842,"name":"IsCRDConditionTrue","signature":"func IsCRDConditionTrue(crd *apiextensionsv1.CustomResourceDefinition, conditionType apiextensionsv1.CustomResourceDefinitionConditionType) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apihelpers/helpers.go","code":"// IsCRDConditionTrue indicates if the condition is present and strictly true.\nfunc IsCRDConditionTrue(crd *apiextensionsv1.CustomResourceDefinition, conditionType apiextensionsv1.CustomResourceDefinitionConditionType) bool {\n\treturn IsCRDConditionPresentAndEqual(crd, conditionType, apiextensionsv1.ConditionTrue)\n}","line":{"from":116,"to":119}} {"id":100013843,"name":"IsCRDConditionFalse","signature":"func IsCRDConditionFalse(crd *apiextensionsv1.CustomResourceDefinition, conditionType apiextensionsv1.CustomResourceDefinitionConditionType) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apihelpers/helpers.go","code":"// IsCRDConditionFalse indicates if the condition is present and false.\nfunc IsCRDConditionFalse(crd *apiextensionsv1.CustomResourceDefinition, conditionType apiextensionsv1.CustomResourceDefinitionConditionType) bool {\n\treturn IsCRDConditionPresentAndEqual(crd, conditionType, apiextensionsv1.ConditionFalse)\n}","line":{"from":121,"to":124}} {"id":100013844,"name":"IsCRDConditionPresentAndEqual","signature":"func IsCRDConditionPresentAndEqual(crd *apiextensionsv1.CustomResourceDefinition, conditionType apiextensionsv1.CustomResourceDefinitionConditionType, status apiextensionsv1.ConditionStatus) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apihelpers/helpers.go","code":"// IsCRDConditionPresentAndEqual indicates if the condition is present and equal to the given status.\nfunc IsCRDConditionPresentAndEqual(crd *apiextensionsv1.CustomResourceDefinition, conditionType apiextensionsv1.CustomResourceDefinitionConditionType, status apiextensionsv1.ConditionStatus) bool {\n\tfor _, condition := range crd.Status.Conditions {\n\t\tif condition.Type == conditionType {\n\t\t\treturn condition.Status == status\n\t\t}\n\t}\n\treturn false\n}","line":{"from":126,"to":134}} {"id":100013845,"name":"IsCRDConditionEquivalent","signature":"func IsCRDConditionEquivalent(lhs, rhs *apiextensionsv1.CustomResourceDefinitionCondition) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apihelpers/helpers.go","code":"// IsCRDConditionEquivalent returns true if the lhs and rhs are equivalent except for times.\nfunc IsCRDConditionEquivalent(lhs, rhs *apiextensionsv1.CustomResourceDefinitionCondition) bool {\n\tif lhs == nil \u0026\u0026 rhs == nil {\n\t\treturn true\n\t}\n\tif lhs == nil || rhs == nil {\n\t\treturn false\n\t}\n\n\treturn lhs.Message == rhs.Message \u0026\u0026 lhs.Reason == rhs.Reason \u0026\u0026 lhs.Status == rhs.Status \u0026\u0026 lhs.Type == rhs.Type\n}","line":{"from":136,"to":146}} {"id":100013846,"name":"CRDHasFinalizer","signature":"func CRDHasFinalizer(crd *apiextensionsv1.CustomResourceDefinition, needle string) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apihelpers/helpers.go","code":"// CRDHasFinalizer returns true if the finalizer is in the list.\nfunc CRDHasFinalizer(crd *apiextensionsv1.CustomResourceDefinition, needle string) bool {\n\tfor _, finalizer := range crd.Finalizers {\n\t\tif finalizer == needle {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":148,"to":157}} {"id":100013847,"name":"CRDRemoveFinalizer","signature":"func CRDRemoveFinalizer(crd *apiextensionsv1.CustomResourceDefinition, needle string)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apihelpers/helpers.go","code":"// CRDRemoveFinalizer removes the finalizer if present.\nfunc CRDRemoveFinalizer(crd *apiextensionsv1.CustomResourceDefinition, needle string) {\n\tnewFinalizers := []string{}\n\tfor _, finalizer := range crd.Finalizers {\n\t\tif finalizer != needle {\n\t\t\tnewFinalizers = append(newFinalizers, finalizer)\n\t\t}\n\t}\n\tcrd.Finalizers = newFinalizers\n}","line":{"from":159,"to":168}} {"id":100013848,"name":"HasServedCRDVersion","signature":"func HasServedCRDVersion(crd *apiextensionsv1.CustomResourceDefinition, version string) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apihelpers/helpers.go","code":"// HasServedCRDVersion returns true if the given version is in the list of CRD's versions and the Served flag is set.\nfunc HasServedCRDVersion(crd *apiextensionsv1.CustomResourceDefinition, version string) bool {\n\tfor _, v := range crd.Spec.Versions {\n\t\tif v.Name == version {\n\t\t\treturn v.Served\n\t\t}\n\t}\n\treturn false\n}","line":{"from":170,"to":178}} {"id":100013849,"name":"GetCRDStorageVersion","signature":"func GetCRDStorageVersion(crd *apiextensionsv1.CustomResourceDefinition) (string, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apihelpers/helpers.go","code":"// GetCRDStorageVersion returns the storage version for given CRD.\nfunc GetCRDStorageVersion(crd *apiextensionsv1.CustomResourceDefinition) (string, error) {\n\tfor _, v := range crd.Spec.Versions {\n\t\tif v.Storage {\n\t\t\treturn v.Name, nil\n\t\t}\n\t}\n\t// This should not happened if crd is valid\n\treturn \"\", fmt.Errorf(\"invalid apiextensionsv1.CustomResourceDefinition, no storage version\")\n}","line":{"from":180,"to":189}} {"id":100013850,"name":"IsStoredVersion","signature":"func IsStoredVersion(crd *apiextensionsv1.CustomResourceDefinition, version string) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apihelpers/helpers.go","code":"// IsStoredVersion returns whether the given version is the storage version of the CRD.\nfunc IsStoredVersion(crd *apiextensionsv1.CustomResourceDefinition, version string) bool {\n\tfor _, v := range crd.Status.StoredVersions {\n\t\tif version == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":191,"to":199}} {"id":100013851,"name":"GetSchemaForVersion","signature":"func GetSchemaForVersion(crd *apiextensionsv1.CustomResourceDefinition, version string) (*apiextensionsv1.CustomResourceValidation, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apihelpers/helpers.go","code":"// GetSchemaForVersion returns the validation schema for the given version or nil.\nfunc GetSchemaForVersion(crd *apiextensionsv1.CustomResourceDefinition, version string) (*apiextensionsv1.CustomResourceValidation, error) {\n\tfor _, v := range crd.Spec.Versions {\n\t\tif version == v.Name {\n\t\t\treturn v.Schema, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"version %s not found in apiextensionsv1.CustomResourceDefinition: %v\", version, crd.Name)\n}","line":{"from":201,"to":209}} {"id":100013852,"name":"GetSubresourcesForVersion","signature":"func GetSubresourcesForVersion(crd *apiextensionsv1.CustomResourceDefinition, version string) (*apiextensionsv1.CustomResourceSubresources, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apihelpers/helpers.go","code":"// GetSubresourcesForVersion returns the subresources for given version or nil.\nfunc GetSubresourcesForVersion(crd *apiextensionsv1.CustomResourceDefinition, version string) (*apiextensionsv1.CustomResourceSubresources, error) {\n\tfor _, v := range crd.Spec.Versions {\n\t\tif version == v.Name {\n\t\t\treturn v.Subresources, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"version %s not found in apiextensionsv1.CustomResourceDefinition: %v\", version, crd.Name)\n}","line":{"from":211,"to":219}} {"id":100013853,"name":"HasPerVersionSchema","signature":"func HasPerVersionSchema(versions []apiextensionsv1.CustomResourceDefinitionVersion) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apihelpers/helpers.go","code":"// HasPerVersionSchema returns true if a CRD uses per-version schema.\nfunc HasPerVersionSchema(versions []apiextensionsv1.CustomResourceDefinitionVersion) bool {\n\tfor _, v := range versions {\n\t\tif v.Schema != nil {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":221,"to":229}} {"id":100013854,"name":"HasPerVersionSubresources","signature":"func HasPerVersionSubresources(versions []apiextensionsv1.CustomResourceDefinitionVersion) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apihelpers/helpers.go","code":"// HasPerVersionSubresources returns true if a CRD uses per-version subresources.\nfunc HasPerVersionSubresources(versions []apiextensionsv1.CustomResourceDefinitionVersion) bool {\n\tfor _, v := range versions {\n\t\tif v.Subresources != nil {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":231,"to":239}} {"id":100013855,"name":"HasPerVersionColumns","signature":"func HasPerVersionColumns(versions []apiextensionsv1.CustomResourceDefinitionVersion) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apihelpers/helpers.go","code":"// HasPerVersionColumns returns true if a CRD uses per-version columns.\nfunc HasPerVersionColumns(versions []apiextensionsv1.CustomResourceDefinitionVersion) bool {\n\tfor _, v := range versions {\n\t\tif len(v.AdditionalPrinterColumns) \u003e 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":241,"to":249}} {"id":100013856,"name":"HasVersionServed","signature":"func HasVersionServed(crd *apiextensionsv1.CustomResourceDefinition, version string) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apihelpers/helpers.go","code":"// HasVersionServed returns true if given CRD has given version served.\nfunc HasVersionServed(crd *apiextensionsv1.CustomResourceDefinition, version string) bool {\n\tfor _, v := range crd.Spec.Versions {\n\t\tif !v.Served || v.Name != version {\n\t\t\tcontinue\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":251,"to":260}} {"id":100013857,"name":"DeepCopy","signature":"func (in *JSONSchemaProps) DeepCopy() *JSONSchemaProps","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/deepcopy.go","code":"// TODO: Update this after a tag is created for interface fields in DeepCopy\nfunc (in *JSONSchemaProps) DeepCopy() *JSONSchemaProps {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(JSONSchemaProps)\n\n\t*out = *in\n\n\tif in.Default != nil {\n\t\tdefaultJSON := JSON(runtime.DeepCopyJSONValue(*(in.Default)))\n\t\tout.Default = \u0026(defaultJSON)\n\t} else {\n\t\tout.Default = nil\n\t}\n\n\tif in.Example != nil {\n\t\texampleJSON := JSON(runtime.DeepCopyJSONValue(*(in.Example)))\n\t\tout.Example = \u0026(exampleJSON)\n\t} else {\n\t\tout.Example = nil\n\t}\n\n\tif in.Ref != nil {\n\t\tin, out := \u0026in.Ref, \u0026out.Ref\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(string)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.Maximum != nil {\n\t\tin, out := \u0026in.Maximum, \u0026out.Maximum\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(float64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.Minimum != nil {\n\t\tin, out := \u0026in.Minimum, \u0026out.Minimum\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(float64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.MaxLength != nil {\n\t\tin, out := \u0026in.MaxLength, \u0026out.MaxLength\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(int64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.MinLength != nil {\n\t\tin, out := \u0026in.MinLength, \u0026out.MinLength\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(int64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\tif in.MaxItems != nil {\n\t\tin, out := \u0026in.MaxItems, \u0026out.MaxItems\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(int64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.MinItems != nil {\n\t\tin, out := \u0026in.MinItems, \u0026out.MinItems\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(int64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.MultipleOf != nil {\n\t\tin, out := \u0026in.MultipleOf, \u0026out.MultipleOf\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(float64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.Enum != nil {\n\t\tout.Enum = make([]JSON, len(in.Enum))\n\t\tfor i := range in.Enum {\n\t\t\tout.Enum[i] = runtime.DeepCopyJSONValue(in.Enum[i])\n\t\t}\n\t}\n\n\tif in.MaxProperties != nil {\n\t\tin, out := \u0026in.MaxProperties, \u0026out.MaxProperties\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(int64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.MinProperties != nil {\n\t\tin, out := \u0026in.MinProperties, \u0026out.MinProperties\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(int64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.Required != nil {\n\t\tin, out := \u0026in.Required, \u0026out.Required\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\n\tif in.Items != nil {\n\t\tin, out := \u0026in.Items, \u0026out.Items\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(JSONSchemaPropsOrArray)\n\t\t\t(*in).DeepCopyInto(*out)\n\t\t}\n\t}\n\n\tif in.AllOf != nil {\n\t\tin, out := \u0026in.AllOf, \u0026out.AllOf\n\t\t*out = make([]JSONSchemaProps, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(\u0026(*out)[i])\n\t\t}\n\t}\n\n\tif in.OneOf != nil {\n\t\tin, out := \u0026in.OneOf, \u0026out.OneOf\n\t\t*out = make([]JSONSchemaProps, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(\u0026(*out)[i])\n\t\t}\n\t}\n\tif in.AnyOf != nil {\n\t\tin, out := \u0026in.AnyOf, \u0026out.AnyOf\n\t\t*out = make([]JSONSchemaProps, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(\u0026(*out)[i])\n\t\t}\n\t}\n\n\tif in.Not != nil {\n\t\tin, out := \u0026in.Not, \u0026out.Not\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(JSONSchemaProps)\n\t\t\t(*in).DeepCopyInto(*out)\n\t\t}\n\t}\n\n\tif in.Properties != nil {\n\t\tin, out := \u0026in.Properties, \u0026out.Properties\n\t\t*out = make(map[string]JSONSchemaProps, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = *val.DeepCopy()\n\t\t}\n\t}\n\n\tif in.AdditionalProperties != nil {\n\t\tin, out := \u0026in.AdditionalProperties, \u0026out.AdditionalProperties\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(JSONSchemaPropsOrBool)\n\t\t\t(*in).DeepCopyInto(*out)\n\t\t}\n\t}\n\n\tif in.PatternProperties != nil {\n\t\tin, out := \u0026in.PatternProperties, \u0026out.PatternProperties\n\t\t*out = make(map[string]JSONSchemaProps, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = *val.DeepCopy()\n\t\t}\n\t}\n\n\tif in.Dependencies != nil {\n\t\tin, out := \u0026in.Dependencies, \u0026out.Dependencies\n\t\t*out = make(JSONSchemaDependencies, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = *val.DeepCopy()\n\t\t}\n\t}\n\n\tif in.AdditionalItems != nil {\n\t\tin, out := \u0026in.AdditionalItems, \u0026out.AdditionalItems\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(JSONSchemaPropsOrBool)\n\t\t\t(*in).DeepCopyInto(*out)\n\t\t}\n\t}\n\n\tif in.Definitions != nil {\n\t\tin, out := \u0026in.Definitions, \u0026out.Definitions\n\t\t*out = make(JSONSchemaDefinitions, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = *val.DeepCopy()\n\t\t}\n\t}\n\n\tif in.ExternalDocs != nil {\n\t\tin, out := \u0026in.ExternalDocs, \u0026out.ExternalDocs\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(ExternalDocumentation)\n\t\t\t(*in).DeepCopyInto(*out)\n\t\t}\n\t}\n\n\tif in.XPreserveUnknownFields != nil {\n\t\tin, out := \u0026in.XPreserveUnknownFields, \u0026out.XPreserveUnknownFields\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(bool)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.XListMapKeys != nil {\n\t\tin, out := \u0026in.XListMapKeys, \u0026out.XListMapKeys\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\n\tif in.XListType != nil {\n\t\tin, out := \u0026in.XListType, \u0026out.XListType\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(string)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.XMapType != nil {\n\t\tin, out := \u0026in.XMapType, \u0026out.XMapType\n\t\t*out = new(string)\n\t\t**out = **in\n\t}\n\n\tif in.XValidations != nil {\n\t\tin, out := \u0026in.XValidations, \u0026out.XValidations\n\t\t*out = make([]ValidationRule, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\n\treturn out\n}","line":{"from":21,"to":300}} {"id":100013858,"name":"Funcs","signature":"func Funcs(codecs runtimeserializer.CodecFactory) []interface{}","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/fuzzer/fuzzer.go","code":"// Funcs returns the fuzzer functions for the apiextensions apis.\nfunc Funcs(codecs runtimeserializer.CodecFactory) []interface{} {\n\treturn []interface{}{\n\t\tfunc(obj *apiextensions.CustomResourceDefinitionSpec, c fuzz.Continue) {\n\t\t\tc.FuzzNoCustom(obj)\n\n\t\t\t// match our defaulter\n\t\t\tif len(obj.Scope) == 0 {\n\t\t\t\tobj.Scope = apiextensions.NamespaceScoped\n\t\t\t}\n\t\t\tif len(obj.Names.Singular) == 0 {\n\t\t\t\tobj.Names.Singular = strings.ToLower(obj.Names.Kind)\n\t\t\t}\n\t\t\tif len(obj.Names.ListKind) == 0 \u0026\u0026 len(obj.Names.Kind) \u003e 0 {\n\t\t\t\tobj.Names.ListKind = obj.Names.Kind + \"List\"\n\t\t\t}\n\t\t\tif len(obj.Versions) == 0 \u0026\u0026 len(obj.Version) == 0 {\n\t\t\t\t// internal object must have a version to roundtrip all fields\n\t\t\t\tobj.Version = \"v1\"\n\t\t\t}\n\t\t\tif len(obj.Versions) == 0 \u0026\u0026 len(obj.Version) != 0 {\n\t\t\t\tobj.Versions = []apiextensions.CustomResourceDefinitionVersion{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: obj.Version,\n\t\t\t\t\t\tServed: true,\n\t\t\t\t\t\tStorage: true,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t} else if len(obj.Versions) != 0 {\n\t\t\t\tobj.Version = obj.Versions[0].Name\n\t\t\t}\n\t\t\tif len(obj.AdditionalPrinterColumns) == 0 {\n\t\t\t\tobj.AdditionalPrinterColumns = []apiextensions.CustomResourceColumnDefinition{\n\t\t\t\t\t{Name: \"Age\", Type: \"date\", Description: swaggerMetadataDescriptions[\"creationTimestamp\"], JSONPath: \".metadata.creationTimestamp\"},\n\t\t\t\t}\n\t\t\t}\n\t\t\tif obj.Conversion == nil {\n\t\t\t\tobj.Conversion = \u0026apiextensions.CustomResourceConversion{\n\t\t\t\t\tStrategy: apiextensions.NoneConverter,\n\t\t\t\t}\n\t\t\t}\n\t\t\tif obj.Conversion.Strategy == apiextensions.WebhookConverter \u0026\u0026 len(obj.Conversion.ConversionReviewVersions) == 0 {\n\t\t\t\tobj.Conversion.ConversionReviewVersions = []string{\"v1beta1\"}\n\t\t\t}\n\t\t\tif obj.PreserveUnknownFields == nil {\n\t\t\t\tobj.PreserveUnknownFields = pointer.BoolPtr(true)\n\t\t\t}\n\n\t\t\t// Move per-version schema, subresources, additionalPrinterColumns to the top-level.\n\t\t\t// This is required by validation in v1beta1, and by round-tripping in v1.\n\t\t\tif len(obj.Versions) == 1 {\n\t\t\t\tif obj.Versions[0].Schema != nil {\n\t\t\t\t\tobj.Validation = obj.Versions[0].Schema\n\t\t\t\t\tobj.Versions[0].Schema = nil\n\t\t\t\t}\n\t\t\t\tif obj.Versions[0].AdditionalPrinterColumns != nil {\n\t\t\t\t\tobj.AdditionalPrinterColumns = obj.Versions[0].AdditionalPrinterColumns\n\t\t\t\t\tobj.Versions[0].AdditionalPrinterColumns = nil\n\t\t\t\t}\n\t\t\t\tif obj.Versions[0].Subresources != nil {\n\t\t\t\t\tobj.Subresources = obj.Versions[0].Subresources\n\t\t\t\t\tobj.Versions[0].Subresources = nil\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tfunc(obj *apiextensions.CustomResourceDefinition, c fuzz.Continue) {\n\t\t\tc.FuzzNoCustom(obj)\n\n\t\t\tif len(obj.Status.StoredVersions) == 0 {\n\t\t\t\tfor _, v := range obj.Spec.Versions {\n\t\t\t\t\tif v.Storage \u0026\u0026 !apiextensions.IsStoredVersion(obj, v.Name) {\n\t\t\t\t\t\tobj.Status.StoredVersions = append(obj.Status.StoredVersions, v.Name)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tfunc(obj *apiextensions.JSONSchemaProps, c fuzz.Continue) {\n\t\t\t// we cannot use c.FuzzNoCustom because of the interface{} fields. So let's loop with reflection.\n\t\t\tvobj := reflect.ValueOf(obj).Elem()\n\t\t\ttobj := reflect.TypeOf(obj).Elem()\n\t\t\tfor i := 0; i \u003c tobj.NumField(); i++ {\n\t\t\t\tfield := tobj.Field(i)\n\t\t\t\tswitch field.Name {\n\t\t\t\tcase \"Default\", \"Enum\", \"Example\", \"Ref\":\n\t\t\t\t\tcontinue\n\t\t\t\tdefault:\n\t\t\t\t\tisValue := true\n\t\t\t\t\tswitch field.Type.Kind() {\n\t\t\t\t\tcase reflect.Interface, reflect.Map, reflect.Slice, reflect.Pointer:\n\t\t\t\t\t\tisValue = false\n\t\t\t\t\t}\n\t\t\t\t\tif isValue || c.Intn(10) == 0 {\n\t\t\t\t\t\tc.Fuzz(vobj.Field(i).Addr().Interface())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif c.RandBool() {\n\t\t\t\tvalidJSON := apiextensions.JSON(`{\"some\": {\"json\": \"test\"}, \"string\": 42}`)\n\t\t\t\tobj.Default = \u0026validJSON\n\t\t\t}\n\t\t\tif c.RandBool() {\n\t\t\t\tobj.Enum = []apiextensions.JSON{c.Float64(), c.RandString(), c.RandBool()}\n\t\t\t}\n\t\t\tif c.RandBool() {\n\t\t\t\tvalidJSON := apiextensions.JSON(`\"foobarbaz\"`)\n\t\t\t\tobj.Example = \u0026validJSON\n\t\t\t}\n\t\t\tif c.RandBool() {\n\t\t\t\tvalidRef := \"validRef\"\n\t\t\t\tobj.Ref = \u0026validRef\n\t\t\t}\n\t\t\tif len(obj.Type) == 0 {\n\t\t\t\tobj.Nullable = false // because this does not roundtrip through go-openapi\n\t\t\t}\n\t\t\tif obj.XIntOrString {\n\t\t\t\tobj.Type = \"\"\n\t\t\t}\n\t\t},\n\t\tfunc(obj *apiextensions.JSONSchemaPropsOrBool, c fuzz.Continue) {\n\t\t\tif c.RandBool() {\n\t\t\t\tobj.Allows = true\n\t\t\t\tobj.Schema = \u0026apiextensions.JSONSchemaProps{}\n\t\t\t\tc.Fuzz(obj.Schema)\n\t\t\t} else {\n\t\t\t\tobj.Allows = c.RandBool()\n\t\t\t}\n\t\t},\n\t\tfunc(obj *apiextensions.JSONSchemaPropsOrArray, c fuzz.Continue) {\n\t\t\t// disallow both Schema and JSONSchemas to be nil.\n\t\t\tif c.RandBool() {\n\t\t\t\tobj.Schema = \u0026apiextensions.JSONSchemaProps{}\n\t\t\t\tc.Fuzz(obj.Schema)\n\t\t\t} else {\n\t\t\t\tobj.JSONSchemas = make([]apiextensions.JSONSchemaProps, c.Intn(3)+1)\n\t\t\t\tfor i := range obj.JSONSchemas {\n\t\t\t\t\tc.Fuzz(\u0026obj.JSONSchemas[i])\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tfunc(obj *apiextensions.JSONSchemaPropsOrStringArray, c fuzz.Continue) {\n\t\t\tif c.RandBool() {\n\t\t\t\tobj.Schema = \u0026apiextensions.JSONSchemaProps{}\n\t\t\t\tc.Fuzz(obj.Schema)\n\t\t\t} else {\n\t\t\t\tc.Fuzz(\u0026obj.Property)\n\t\t\t}\n\t\t},\n\t\tfunc(obj *int64, c fuzz.Continue) {\n\t\t\t// JSON only supports 53 bits because everything is a float\n\t\t\t*obj = int64(c.Uint64()) \u0026 ((int64(1) \u003c\u003c 53) - 1)\n\t\t},\n\t}\n}","line":{"from":33,"to":185}} {"id":100013859,"name":"SetCRDCondition","signature":"func SetCRDCondition(crd *CustomResourceDefinition, newCondition CustomResourceDefinitionCondition)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/helpers.go","code":"// SetCRDCondition sets the status condition. It either overwrites the existing one or creates a new one.\nfunc SetCRDCondition(crd *CustomResourceDefinition, newCondition CustomResourceDefinitionCondition) {\n\tnewCondition.LastTransitionTime = metav1.NewTime(time.Now())\n\n\texistingCondition := FindCRDCondition(crd, newCondition.Type)\n\tif existingCondition == nil {\n\t\tcrd.Status.Conditions = append(crd.Status.Conditions, newCondition)\n\t\treturn\n\t}\n\n\tif existingCondition.Status != newCondition.Status || existingCondition.LastTransitionTime.IsZero() {\n\t\texistingCondition.LastTransitionTime = newCondition.LastTransitionTime\n\t}\n\n\texistingCondition.Status = newCondition.Status\n\texistingCondition.Reason = newCondition.Reason\n\texistingCondition.Message = newCondition.Message\n}","line":{"from":28,"to":45}} {"id":100013860,"name":"RemoveCRDCondition","signature":"func RemoveCRDCondition(crd *CustomResourceDefinition, conditionType CustomResourceDefinitionConditionType)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/helpers.go","code":"// RemoveCRDCondition removes the status condition.\nfunc RemoveCRDCondition(crd *CustomResourceDefinition, conditionType CustomResourceDefinitionConditionType) {\n\tnewConditions := []CustomResourceDefinitionCondition{}\n\tfor _, condition := range crd.Status.Conditions {\n\t\tif condition.Type != conditionType {\n\t\t\tnewConditions = append(newConditions, condition)\n\t\t}\n\t}\n\tcrd.Status.Conditions = newConditions\n}","line":{"from":47,"to":56}} {"id":100013861,"name":"FindCRDCondition","signature":"func FindCRDCondition(crd *CustomResourceDefinition, conditionType CustomResourceDefinitionConditionType) *CustomResourceDefinitionCondition","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/helpers.go","code":"// FindCRDCondition returns the condition you're looking for or nil.\nfunc FindCRDCondition(crd *CustomResourceDefinition, conditionType CustomResourceDefinitionConditionType) *CustomResourceDefinitionCondition {\n\tfor i := range crd.Status.Conditions {\n\t\tif crd.Status.Conditions[i].Type == conditionType {\n\t\t\treturn \u0026crd.Status.Conditions[i]\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":58,"to":67}} {"id":100013862,"name":"IsCRDConditionTrue","signature":"func IsCRDConditionTrue(crd *CustomResourceDefinition, conditionType CustomResourceDefinitionConditionType) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/helpers.go","code":"// IsCRDConditionTrue indicates if the condition is present and strictly true.\nfunc IsCRDConditionTrue(crd *CustomResourceDefinition, conditionType CustomResourceDefinitionConditionType) bool {\n\treturn IsCRDConditionPresentAndEqual(crd, conditionType, ConditionTrue)\n}","line":{"from":69,"to":72}} {"id":100013863,"name":"IsCRDConditionFalse","signature":"func IsCRDConditionFalse(crd *CustomResourceDefinition, conditionType CustomResourceDefinitionConditionType) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/helpers.go","code":"// IsCRDConditionFalse indicates if the condition is present and false.\nfunc IsCRDConditionFalse(crd *CustomResourceDefinition, conditionType CustomResourceDefinitionConditionType) bool {\n\treturn IsCRDConditionPresentAndEqual(crd, conditionType, ConditionFalse)\n}","line":{"from":74,"to":77}} {"id":100013864,"name":"IsCRDConditionPresentAndEqual","signature":"func IsCRDConditionPresentAndEqual(crd *CustomResourceDefinition, conditionType CustomResourceDefinitionConditionType, status ConditionStatus) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/helpers.go","code":"// IsCRDConditionPresentAndEqual indicates if the condition is present and equal to the given status.\nfunc IsCRDConditionPresentAndEqual(crd *CustomResourceDefinition, conditionType CustomResourceDefinitionConditionType, status ConditionStatus) bool {\n\tfor _, condition := range crd.Status.Conditions {\n\t\tif condition.Type == conditionType {\n\t\t\treturn condition.Status == status\n\t\t}\n\t}\n\treturn false\n}","line":{"from":79,"to":87}} {"id":100013865,"name":"IsCRDConditionEquivalent","signature":"func IsCRDConditionEquivalent(lhs, rhs *CustomResourceDefinitionCondition) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/helpers.go","code":"// IsCRDConditionEquivalent returns true if the lhs and rhs are equivalent except for times.\nfunc IsCRDConditionEquivalent(lhs, rhs *CustomResourceDefinitionCondition) bool {\n\tif lhs == nil \u0026\u0026 rhs == nil {\n\t\treturn true\n\t}\n\tif lhs == nil || rhs == nil {\n\t\treturn false\n\t}\n\n\treturn lhs.Message == rhs.Message \u0026\u0026 lhs.Reason == rhs.Reason \u0026\u0026 lhs.Status == rhs.Status \u0026\u0026 lhs.Type == rhs.Type\n}","line":{"from":89,"to":99}} {"id":100013866,"name":"CRDHasFinalizer","signature":"func CRDHasFinalizer(crd *CustomResourceDefinition, needle string) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/helpers.go","code":"// CRDHasFinalizer returns true if the finalizer is in the list.\nfunc CRDHasFinalizer(crd *CustomResourceDefinition, needle string) bool {\n\tfor _, finalizer := range crd.Finalizers {\n\t\tif finalizer == needle {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":101,"to":110}} {"id":100013867,"name":"CRDRemoveFinalizer","signature":"func CRDRemoveFinalizer(crd *CustomResourceDefinition, needle string)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/helpers.go","code":"// CRDRemoveFinalizer removes the finalizer if present.\nfunc CRDRemoveFinalizer(crd *CustomResourceDefinition, needle string) {\n\tnewFinalizers := []string{}\n\tfor _, finalizer := range crd.Finalizers {\n\t\tif finalizer != needle {\n\t\t\tnewFinalizers = append(newFinalizers, finalizer)\n\t\t}\n\t}\n\tcrd.Finalizers = newFinalizers\n}","line":{"from":112,"to":121}} {"id":100013868,"name":"HasServedCRDVersion","signature":"func HasServedCRDVersion(crd *CustomResourceDefinition, version string) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/helpers.go","code":"// HasServedCRDVersion returns true if the given version is in the list of CRD's versions and the Served flag is set.\nfunc HasServedCRDVersion(crd *CustomResourceDefinition, version string) bool {\n\tfor _, v := range crd.Spec.Versions {\n\t\tif v.Name == version {\n\t\t\treturn v.Served\n\t\t}\n\t}\n\treturn false\n}","line":{"from":123,"to":131}} {"id":100013869,"name":"GetCRDStorageVersion","signature":"func GetCRDStorageVersion(crd *CustomResourceDefinition) (string, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/helpers.go","code":"// GetCRDStorageVersion returns the storage version for given CRD.\nfunc GetCRDStorageVersion(crd *CustomResourceDefinition) (string, error) {\n\tfor _, v := range crd.Spec.Versions {\n\t\tif v.Storage {\n\t\t\treturn v.Name, nil\n\t\t}\n\t}\n\t// This should not happened if crd is valid\n\treturn \"\", fmt.Errorf(\"invalid CustomResourceDefinition, no storage version\")\n}","line":{"from":133,"to":142}} {"id":100013870,"name":"IsStoredVersion","signature":"func IsStoredVersion(crd *CustomResourceDefinition, version string) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/helpers.go","code":"// IsStoredVersion returns whether the given version is the storage version of the CRD.\nfunc IsStoredVersion(crd *CustomResourceDefinition, version string) bool {\n\tfor _, v := range crd.Status.StoredVersions {\n\t\tif version == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":144,"to":152}} {"id":100013871,"name":"GetSchemaForVersion","signature":"func GetSchemaForVersion(crd *CustomResourceDefinition, version string) (*CustomResourceValidation, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/helpers.go","code":"// GetSchemaForVersion returns the validation schema for the given version or nil.\nfunc GetSchemaForVersion(crd *CustomResourceDefinition, version string) (*CustomResourceValidation, error) {\n\tif !HasPerVersionSchema(crd.Spec.Versions) {\n\t\treturn crd.Spec.Validation, nil\n\t}\n\tif crd.Spec.Validation != nil {\n\t\treturn nil, fmt.Errorf(\"malformed CustomResourceDefinition %s version %s: top-level and per-version schemas must be mutual exclusive\", crd.Name, version)\n\t}\n\tfor _, v := range crd.Spec.Versions {\n\t\tif version == v.Name {\n\t\t\treturn v.Schema, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"version %s not found in CustomResourceDefinition: %v\", version, crd.Name)\n}","line":{"from":154,"to":168}} {"id":100013872,"name":"GetSubresourcesForVersion","signature":"func GetSubresourcesForVersion(crd *CustomResourceDefinition, version string) (*CustomResourceSubresources, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/helpers.go","code":"// GetSubresourcesForVersion returns the subresources for given version or nil.\nfunc GetSubresourcesForVersion(crd *CustomResourceDefinition, version string) (*CustomResourceSubresources, error) {\n\tif !HasPerVersionSubresources(crd.Spec.Versions) {\n\t\treturn crd.Spec.Subresources, nil\n\t}\n\tif crd.Spec.Subresources != nil {\n\t\treturn nil, fmt.Errorf(\"malformed CustomResourceDefinition %s version %s: top-level and per-version subresources must be mutual exclusive\", crd.Name, version)\n\t}\n\tfor _, v := range crd.Spec.Versions {\n\t\tif version == v.Name {\n\t\t\treturn v.Subresources, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"version %s not found in CustomResourceDefinition: %v\", version, crd.Name)\n}","line":{"from":170,"to":184}} {"id":100013873,"name":"GetColumnsForVersion","signature":"func GetColumnsForVersion(crd *CustomResourceDefinition, version string) ([]CustomResourceColumnDefinition, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/helpers.go","code":"// GetColumnsForVersion returns the columns for given version or nil.\n// NOTE: the newly logically-defaulted columns is not pointing to the original CRD object.\n// One cannot mutate the original CRD columns using the logically-defaulted columns. Please iterate through\n// the original CRD object instead.\nfunc GetColumnsForVersion(crd *CustomResourceDefinition, version string) ([]CustomResourceColumnDefinition, error) {\n\tif !HasPerVersionColumns(crd.Spec.Versions) {\n\t\treturn serveDefaultColumnsIfEmpty(crd.Spec.AdditionalPrinterColumns), nil\n\t}\n\tif len(crd.Spec.AdditionalPrinterColumns) \u003e 0 {\n\t\treturn nil, fmt.Errorf(\"malformed CustomResourceDefinition %s version %s: top-level and per-version additionalPrinterColumns must be mutual exclusive\", crd.Name, version)\n\t}\n\tfor _, v := range crd.Spec.Versions {\n\t\tif version == v.Name {\n\t\t\treturn serveDefaultColumnsIfEmpty(v.AdditionalPrinterColumns), nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"version %s not found in CustomResourceDefinition: %v\", version, crd.Name)\n}","line":{"from":186,"to":203}} {"id":100013874,"name":"HasPerVersionSchema","signature":"func HasPerVersionSchema(versions []CustomResourceDefinitionVersion) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/helpers.go","code":"// HasPerVersionSchema returns true if a CRD uses per-version schema.\nfunc HasPerVersionSchema(versions []CustomResourceDefinitionVersion) bool {\n\tfor _, v := range versions {\n\t\tif v.Schema != nil {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":205,"to":213}} {"id":100013875,"name":"HasPerVersionSubresources","signature":"func HasPerVersionSubresources(versions []CustomResourceDefinitionVersion) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/helpers.go","code":"// HasPerVersionSubresources returns true if a CRD uses per-version subresources.\nfunc HasPerVersionSubresources(versions []CustomResourceDefinitionVersion) bool {\n\tfor _, v := range versions {\n\t\tif v.Subresources != nil {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":215,"to":223}} {"id":100013876,"name":"HasPerVersionColumns","signature":"func HasPerVersionColumns(versions []CustomResourceDefinitionVersion) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/helpers.go","code":"// HasPerVersionColumns returns true if a CRD uses per-version columns.\nfunc HasPerVersionColumns(versions []CustomResourceDefinitionVersion) bool {\n\tfor _, v := range versions {\n\t\tif len(v.AdditionalPrinterColumns) \u003e 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":225,"to":233}} {"id":100013877,"name":"serveDefaultColumnsIfEmpty","signature":"func serveDefaultColumnsIfEmpty(columns []CustomResourceColumnDefinition) []CustomResourceColumnDefinition","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/helpers.go","code":"// serveDefaultColumnsIfEmpty applies logically defaulting to columns, if the input columns is empty.\n// NOTE: in this way, the newly logically-defaulted columns is not pointing to the original CRD object.\n// One cannot mutate the original CRD columns using the logically-defaulted columns. Please iterate through\n// the original CRD object instead.\nfunc serveDefaultColumnsIfEmpty(columns []CustomResourceColumnDefinition) []CustomResourceColumnDefinition {\n\tif len(columns) \u003e 0 {\n\t\treturn columns\n\t}\n\treturn []CustomResourceColumnDefinition{\n\t\t{Name: \"Age\", Type: \"date\", Description: swaggerMetadataDescriptions[\"creationTimestamp\"], JSONPath: \".metadata.creationTimestamp\"},\n\t}\n}","line":{"from":235,"to":246}} {"id":100013878,"name":"HasVersionServed","signature":"func HasVersionServed(crd *CustomResourceDefinition, version string) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/helpers.go","code":"// HasVersionServed returns true if given CRD has given version served.\nfunc HasVersionServed(crd *CustomResourceDefinition, version string) bool {\n\tfor _, v := range crd.Spec.Versions {\n\t\tif !v.Served || v.Name != version {\n\t\t\tcontinue\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":248,"to":257}} {"id":100013879,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(apiextensions.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1.SchemeGroupVersion, v1beta1.SchemeGroupVersion))\n}","line":{"from":27,"to":33}} {"id":100013880,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/register.go","code":"// Kind takes an unqualified kind and returns back a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":29,"to":32}} {"id":100013881,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/register.go","code":"// Resource takes an unqualified resource and returns back a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":34,"to":37}} {"id":100013882,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026CustomResourceDefinition{},\n\t\t\u0026CustomResourceDefinitionList{},\n\t)\n\treturn nil\n}","line":{"from":44,"to":51}} {"id":100013883,"name":"Convert_apiextensions_JSONSchemaProps_To_v1_JSONSchemaProps","signature":"func Convert_apiextensions_JSONSchemaProps_To_v1_JSONSchemaProps(in *apiextensions.JSONSchemaProps, out *JSONSchemaProps, s conversion.Scope) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/conversion.go","code":"func Convert_apiextensions_JSONSchemaProps_To_v1_JSONSchemaProps(in *apiextensions.JSONSchemaProps, out *JSONSchemaProps, s conversion.Scope) error {\n\tif err := autoConvert_apiextensions_JSONSchemaProps_To_v1_JSONSchemaProps(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tif in.Default != nil \u0026\u0026 *(in.Default) == nil {\n\t\tout.Default = nil\n\t}\n\tif in.Example != nil \u0026\u0026 *(in.Example) == nil {\n\t\tout.Example = nil\n\t}\n\treturn nil\n}","line":{"from":29,"to":40}} {"id":100013884,"name":"Convert_apiextensions_JSON_To_v1_JSON","signature":"func Convert_apiextensions_JSON_To_v1_JSON(in *apiextensions.JSON, out *JSON, s conversion.Scope) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/conversion.go","code":"func Convert_apiextensions_JSON_To_v1_JSON(in *apiextensions.JSON, out *JSON, s conversion.Scope) error {\n\traw, err := json.Marshal(*in)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(raw) == 0 || bytes.Equal(raw, nullLiteral) {\n\t\t// match JSON#UnmarshalJSON treatment of literal nulls\n\t\tout.Raw = nil\n\t} else {\n\t\tout.Raw = raw\n\t}\n\treturn nil\n}","line":{"from":44,"to":56}} {"id":100013885,"name":"Convert_v1_JSON_To_apiextensions_JSON","signature":"func Convert_v1_JSON_To_apiextensions_JSON(in *JSON, out *apiextensions.JSON, s conversion.Scope) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/conversion.go","code":"func Convert_v1_JSON_To_apiextensions_JSON(in *JSON, out *apiextensions.JSON, s conversion.Scope) error {\n\tif in != nil {\n\t\tvar i interface{}\n\t\tif len(in.Raw) \u003e 0 \u0026\u0026 !bytes.Equal(in.Raw, nullLiteral) {\n\t\t\tif err := json.Unmarshal(in.Raw, \u0026i); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\t*out = i\n\t} else {\n\t\tout = nil\n\t}\n\treturn nil\n}","line":{"from":58,"to":71}} {"id":100013886,"name":"Convert_apiextensions_CustomResourceDefinitionSpec_To_v1_CustomResourceDefinitionSpec","signature":"func Convert_apiextensions_CustomResourceDefinitionSpec_To_v1_CustomResourceDefinitionSpec(in *apiextensions.CustomResourceDefinitionSpec, out *CustomResourceDefinitionSpec, s conversion.Scope) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/conversion.go","code":"func Convert_apiextensions_CustomResourceDefinitionSpec_To_v1_CustomResourceDefinitionSpec(in *apiextensions.CustomResourceDefinitionSpec, out *CustomResourceDefinitionSpec, s conversion.Scope) error {\n\tif err := autoConvert_apiextensions_CustomResourceDefinitionSpec_To_v1_CustomResourceDefinitionSpec(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\tif len(out.Versions) == 0 \u0026\u0026 len(in.Version) \u003e 0 {\n\t\t// no versions were specified, and a version name was specified\n\t\tout.Versions = []CustomResourceDefinitionVersion{{Name: in.Version, Served: true, Storage: true}}\n\t}\n\n\t// If spec.{subresources,validation,additionalPrinterColumns} exists, move to versions\n\tif in.Subresources != nil {\n\t\tsubresources := \u0026CustomResourceSubresources{}\n\t\tif err := Convert_apiextensions_CustomResourceSubresources_To_v1_CustomResourceSubresources(in.Subresources, subresources, s); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor i := range out.Versions {\n\t\t\tout.Versions[i].Subresources = subresources\n\t\t}\n\t}\n\tif in.Validation != nil {\n\t\tschema := \u0026CustomResourceValidation{}\n\t\tif err := Convert_apiextensions_CustomResourceValidation_To_v1_CustomResourceValidation(in.Validation, schema, s); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor i := range out.Versions {\n\t\t\tout.Versions[i].Schema = schema\n\t\t}\n\t}\n\tif in.AdditionalPrinterColumns != nil {\n\t\tadditionalPrinterColumns := make([]CustomResourceColumnDefinition, len(in.AdditionalPrinterColumns))\n\t\tfor i := range in.AdditionalPrinterColumns {\n\t\t\tif err := Convert_apiextensions_CustomResourceColumnDefinition_To_v1_CustomResourceColumnDefinition(\u0026in.AdditionalPrinterColumns[i], \u0026additionalPrinterColumns[i], s); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tfor i := range out.Versions {\n\t\t\tout.Versions[i].AdditionalPrinterColumns = additionalPrinterColumns\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":73,"to":114}} {"id":100013887,"name":"Convert_v1_CustomResourceDefinitionSpec_To_apiextensions_CustomResourceDefinitionSpec","signature":"func Convert_v1_CustomResourceDefinitionSpec_To_apiextensions_CustomResourceDefinitionSpec(in *CustomResourceDefinitionSpec, out *apiextensions.CustomResourceDefinitionSpec, s conversion.Scope) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/conversion.go","code":"func Convert_v1_CustomResourceDefinitionSpec_To_apiextensions_CustomResourceDefinitionSpec(in *CustomResourceDefinitionSpec, out *apiextensions.CustomResourceDefinitionSpec, s conversion.Scope) error {\n\tif err := autoConvert_v1_CustomResourceDefinitionSpec_To_apiextensions_CustomResourceDefinitionSpec(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\tif len(out.Versions) == 0 {\n\t\treturn nil\n\t}\n\n\t// Copy versions[0] to version\n\tout.Version = out.Versions[0].Name\n\n\t// If versions[*].{subresources,schema,additionalPrinterColumns} are identical, move to spec\n\tsubresources := out.Versions[0].Subresources\n\tsubresourcesIdentical := true\n\tvalidation := out.Versions[0].Schema\n\tvalidationIdentical := true\n\tadditionalPrinterColumns := out.Versions[0].AdditionalPrinterColumns\n\tadditionalPrinterColumnsIdentical := true\n\n\t// Detect if per-version fields are identical\n\tfor _, v := range out.Versions {\n\t\tif subresourcesIdentical \u0026\u0026 !apiequality.Semantic.DeepEqual(v.Subresources, subresources) {\n\t\t\tsubresourcesIdentical = false\n\t\t}\n\t\tif validationIdentical \u0026\u0026 !apiequality.Semantic.DeepEqual(v.Schema, validation) {\n\t\t\tvalidationIdentical = false\n\t\t}\n\t\tif additionalPrinterColumnsIdentical \u0026\u0026 !apiequality.Semantic.DeepEqual(v.AdditionalPrinterColumns, additionalPrinterColumns) {\n\t\t\tadditionalPrinterColumnsIdentical = false\n\t\t}\n\t}\n\n\t// If they are, set the top-level fields and clear the per-version fields\n\tif subresourcesIdentical {\n\t\tout.Subresources = subresources\n\t}\n\tif validationIdentical {\n\t\tout.Validation = validation\n\t}\n\tif additionalPrinterColumnsIdentical {\n\t\tout.AdditionalPrinterColumns = additionalPrinterColumns\n\t}\n\tfor i := range out.Versions {\n\t\tif subresourcesIdentical {\n\t\t\tout.Versions[i].Subresources = nil\n\t\t}\n\t\tif validationIdentical {\n\t\t\tout.Versions[i].Schema = nil\n\t\t}\n\t\tif additionalPrinterColumnsIdentical {\n\t\t\tout.Versions[i].AdditionalPrinterColumns = nil\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":116,"to":172}} {"id":100013888,"name":"Convert_v1_CustomResourceConversion_To_apiextensions_CustomResourceConversion","signature":"func Convert_v1_CustomResourceConversion_To_apiextensions_CustomResourceConversion(in *CustomResourceConversion, out *apiextensions.CustomResourceConversion, s conversion.Scope) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/conversion.go","code":"func Convert_v1_CustomResourceConversion_To_apiextensions_CustomResourceConversion(in *CustomResourceConversion, out *apiextensions.CustomResourceConversion, s conversion.Scope) error {\n\tif err := autoConvert_v1_CustomResourceConversion_To_apiextensions_CustomResourceConversion(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\tout.WebhookClientConfig = nil\n\tout.ConversionReviewVersions = nil\n\tif in.Webhook != nil {\n\t\tout.ConversionReviewVersions = in.Webhook.ConversionReviewVersions\n\t\tif in.Webhook.ClientConfig != nil {\n\t\t\tout.WebhookClientConfig = \u0026apiextensions.WebhookClientConfig{}\n\t\t\tif err := Convert_v1_WebhookClientConfig_To_apiextensions_WebhookClientConfig(in.Webhook.ClientConfig, out.WebhookClientConfig, s); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":174,"to":191}} {"id":100013889,"name":"Convert_apiextensions_CustomResourceConversion_To_v1_CustomResourceConversion","signature":"func Convert_apiextensions_CustomResourceConversion_To_v1_CustomResourceConversion(in *apiextensions.CustomResourceConversion, out *CustomResourceConversion, s conversion.Scope) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/conversion.go","code":"func Convert_apiextensions_CustomResourceConversion_To_v1_CustomResourceConversion(in *apiextensions.CustomResourceConversion, out *CustomResourceConversion, s conversion.Scope) error {\n\tif err := autoConvert_apiextensions_CustomResourceConversion_To_v1_CustomResourceConversion(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\tout.Webhook = nil\n\tif in.WebhookClientConfig != nil || in.ConversionReviewVersions != nil {\n\t\tout.Webhook = \u0026WebhookConversion{}\n\t\tout.Webhook.ConversionReviewVersions = in.ConversionReviewVersions\n\t\tif in.WebhookClientConfig != nil {\n\t\t\tout.Webhook.ClientConfig = \u0026WebhookClientConfig{}\n\t\t\tif err := Convert_apiextensions_WebhookClientConfig_To_v1_WebhookClientConfig(in.WebhookClientConfig, out.Webhook.ClientConfig, s); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":193,"to":210}} {"id":100013890,"name":"Convert_apiextensions_ValidationRules_To_v1_ValidationRules","signature":"func Convert_apiextensions_ValidationRules_To_v1_ValidationRules(in *apiextensions.ValidationRules, out *ValidationRules, s conversion.Scope) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/conversion.go","code":"func Convert_apiextensions_ValidationRules_To_v1_ValidationRules(in *apiextensions.ValidationRules, out *ValidationRules, s conversion.Scope) error {\n\t*out = *(*ValidationRules)(unsafe.Pointer(in))\n\treturn nil\n}","line":{"from":212,"to":215}} {"id":100013891,"name":"DeepCopy","signature":"func (in *JSONSchemaProps) DeepCopy() *JSONSchemaProps","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/deepcopy.go","code":"// TODO: Update this after a tag is created for interface fields in DeepCopy\nfunc (in *JSONSchemaProps) DeepCopy() *JSONSchemaProps {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(JSONSchemaProps)\n\t*out = *in\n\n\tif in.Ref != nil {\n\t\tin, out := \u0026in.Ref, \u0026out.Ref\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(string)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.Maximum != nil {\n\t\tin, out := \u0026in.Maximum, \u0026out.Maximum\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(float64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.Minimum != nil {\n\t\tin, out := \u0026in.Minimum, \u0026out.Minimum\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(float64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.MaxLength != nil {\n\t\tin, out := \u0026in.MaxLength, \u0026out.MaxLength\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(int64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.MinLength != nil {\n\t\tin, out := \u0026in.MinLength, \u0026out.MinLength\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(int64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\tif in.MaxItems != nil {\n\t\tin, out := \u0026in.MaxItems, \u0026out.MaxItems\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(int64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.MinItems != nil {\n\t\tin, out := \u0026in.MinItems, \u0026out.MinItems\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(int64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.MultipleOf != nil {\n\t\tin, out := \u0026in.MultipleOf, \u0026out.MultipleOf\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(float64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.MaxProperties != nil {\n\t\tin, out := \u0026in.MaxProperties, \u0026out.MaxProperties\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(int64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.MinProperties != nil {\n\t\tin, out := \u0026in.MinProperties, \u0026out.MinProperties\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(int64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.Required != nil {\n\t\tin, out := \u0026in.Required, \u0026out.Required\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\n\tif in.Items != nil {\n\t\tin, out := \u0026in.Items, \u0026out.Items\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(JSONSchemaPropsOrArray)\n\t\t\t(*in).DeepCopyInto(*out)\n\t\t}\n\t}\n\n\tif in.AllOf != nil {\n\t\tin, out := \u0026in.AllOf, \u0026out.AllOf\n\t\t*out = make([]JSONSchemaProps, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(\u0026(*out)[i])\n\t\t}\n\t}\n\n\tif in.OneOf != nil {\n\t\tin, out := \u0026in.OneOf, \u0026out.OneOf\n\t\t*out = make([]JSONSchemaProps, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(\u0026(*out)[i])\n\t\t}\n\t}\n\tif in.AnyOf != nil {\n\t\tin, out := \u0026in.AnyOf, \u0026out.AnyOf\n\t\t*out = make([]JSONSchemaProps, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(\u0026(*out)[i])\n\t\t}\n\t}\n\n\tif in.Not != nil {\n\t\tin, out := \u0026in.Not, \u0026out.Not\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(JSONSchemaProps)\n\t\t\t(*in).DeepCopyInto(*out)\n\t\t}\n\t}\n\n\tif in.Properties != nil {\n\t\tin, out := \u0026in.Properties, \u0026out.Properties\n\t\t*out = make(map[string]JSONSchemaProps, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = *val.DeepCopy()\n\t\t}\n\t}\n\n\tif in.AdditionalProperties != nil {\n\t\tin, out := \u0026in.AdditionalProperties, \u0026out.AdditionalProperties\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(JSONSchemaPropsOrBool)\n\t\t\t(*in).DeepCopyInto(*out)\n\t\t}\n\t}\n\n\tif in.PatternProperties != nil {\n\t\tin, out := \u0026in.PatternProperties, \u0026out.PatternProperties\n\t\t*out = make(map[string]JSONSchemaProps, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = *val.DeepCopy()\n\t\t}\n\t}\n\n\tif in.Dependencies != nil {\n\t\tin, out := \u0026in.Dependencies, \u0026out.Dependencies\n\t\t*out = make(JSONSchemaDependencies, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = *val.DeepCopy()\n\t\t}\n\t}\n\n\tif in.AdditionalItems != nil {\n\t\tin, out := \u0026in.AdditionalItems, \u0026out.AdditionalItems\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(JSONSchemaPropsOrBool)\n\t\t\t(*in).DeepCopyInto(*out)\n\t\t}\n\t}\n\n\tif in.Definitions != nil {\n\t\tin, out := \u0026in.Definitions, \u0026out.Definitions\n\t\t*out = make(JSONSchemaDefinitions, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = *val.DeepCopy()\n\t\t}\n\t}\n\n\tif in.ExternalDocs != nil {\n\t\tin, out := \u0026in.ExternalDocs, \u0026out.ExternalDocs\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(ExternalDocumentation)\n\t\t\t(*in).DeepCopyInto(*out)\n\t\t}\n\t}\n\n\tif in.XPreserveUnknownFields != nil {\n\t\tin, out := \u0026in.XPreserveUnknownFields, \u0026out.XPreserveUnknownFields\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(bool)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.XMapType != nil {\n\t\tin, out := \u0026in.XMapType, \u0026out.XMapType\n\t\t*out = new(string)\n\t\t**out = **in\n\t}\n\n\tif in.XValidations != nil {\n\t\tin, out := \u0026in.XValidations, \u0026out.XValidations\n\t\t*out = make([]ValidationRule, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\n\treturn out\n}","line":{"from":19,"to":260}} {"id":100013892,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":26,"to":28}} {"id":100013893,"name":"SetDefaults_CustomResourceDefinition","signature":"func SetDefaults_CustomResourceDefinition(obj *CustomResourceDefinition)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/defaults.go","code":"func SetDefaults_CustomResourceDefinition(obj *CustomResourceDefinition) {\n\tSetDefaults_CustomResourceDefinitionSpec(\u0026obj.Spec)\n\tif len(obj.Status.StoredVersions) == 0 {\n\t\tfor _, v := range obj.Spec.Versions {\n\t\t\tif v.Storage {\n\t\t\t\tobj.Status.StoredVersions = append(obj.Status.StoredVersions, v.Name)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":30,"to":40}} {"id":100013894,"name":"SetDefaults_CustomResourceDefinitionSpec","signature":"func SetDefaults_CustomResourceDefinitionSpec(obj *CustomResourceDefinitionSpec)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/defaults.go","code":"func SetDefaults_CustomResourceDefinitionSpec(obj *CustomResourceDefinitionSpec) {\n\tif len(obj.Names.Singular) == 0 {\n\t\tobj.Names.Singular = strings.ToLower(obj.Names.Kind)\n\t}\n\tif len(obj.Names.ListKind) == 0 \u0026\u0026 len(obj.Names.Kind) \u003e 0 {\n\t\tobj.Names.ListKind = obj.Names.Kind + \"List\"\n\t}\n\tif obj.Conversion == nil {\n\t\tobj.Conversion = \u0026CustomResourceConversion{\n\t\t\tStrategy: NoneConverter,\n\t\t}\n\t}\n}","line":{"from":42,"to":54}} {"id":100013895,"name":"SetDefaults_ServiceReference","signature":"func SetDefaults_ServiceReference(obj *ServiceReference)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/defaults.go","code":"// SetDefaults_ServiceReference sets defaults for Webhook's ServiceReference\nfunc SetDefaults_ServiceReference(obj *ServiceReference) {\n\tif obj.Port == nil {\n\t\tobj.Port = utilpointer.Int32Ptr(443)\n\t}\n}","line":{"from":56,"to":61}} {"id":100013896,"name":"MarshalJSON","signature":"func (s JSONSchemaPropsOrBool) MarshalJSON() ([]byte, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/marshal.go","code":"func (s JSONSchemaPropsOrBool) MarshalJSON() ([]byte, error) {\n\tif s.Schema != nil {\n\t\treturn json.Marshal(s.Schema)\n\t}\n\n\tif s.Schema == nil \u0026\u0026 !s.Allows {\n\t\treturn jsFalse, nil\n\t}\n\treturn jsTrue, nil\n}","line":{"from":29,"to":38}} {"id":100013897,"name":"UnmarshalJSON","signature":"func (s *JSONSchemaPropsOrBool) UnmarshalJSON(data []byte) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/marshal.go","code":"func (s *JSONSchemaPropsOrBool) UnmarshalJSON(data []byte) error {\n\tvar nw JSONSchemaPropsOrBool\n\tswitch {\n\tcase len(data) == 0:\n\tcase data[0] == '{':\n\t\tvar sch JSONSchemaProps\n\t\tif err := json.Unmarshal(data, \u0026sch); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnw.Allows = true\n\t\tnw.Schema = \u0026sch\n\tcase len(data) == 4 \u0026\u0026 string(data) == \"true\":\n\t\tnw.Allows = true\n\tcase len(data) == 5 \u0026\u0026 string(data) == \"false\":\n\t\tnw.Allows = false\n\tdefault:\n\t\treturn errors.New(\"boolean or JSON schema expected\")\n\t}\n\t*s = nw\n\treturn nil\n}","line":{"from":40,"to":60}} {"id":100013898,"name":"MarshalJSON","signature":"func (s JSONSchemaPropsOrStringArray) MarshalJSON() ([]byte, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/marshal.go","code":"func (s JSONSchemaPropsOrStringArray) MarshalJSON() ([]byte, error) {\n\tif len(s.Property) \u003e 0 {\n\t\treturn json.Marshal(s.Property)\n\t}\n\tif s.Schema != nil {\n\t\treturn json.Marshal(s.Schema)\n\t}\n\treturn []byte(\"null\"), nil\n}","line":{"from":62,"to":70}} {"id":100013899,"name":"UnmarshalJSON","signature":"func (s *JSONSchemaPropsOrStringArray) UnmarshalJSON(data []byte) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/marshal.go","code":"func (s *JSONSchemaPropsOrStringArray) UnmarshalJSON(data []byte) error {\n\tvar first byte\n\tif len(data) \u003e 1 {\n\t\tfirst = data[0]\n\t}\n\tvar nw JSONSchemaPropsOrStringArray\n\tif first == '{' {\n\t\tvar sch JSONSchemaProps\n\t\tif err := json.Unmarshal(data, \u0026sch); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnw.Schema = \u0026sch\n\t}\n\tif first == '[' {\n\t\tif err := json.Unmarshal(data, \u0026nw.Property); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t*s = nw\n\treturn nil\n}","line":{"from":72,"to":92}} {"id":100013900,"name":"MarshalJSON","signature":"func (s JSONSchemaPropsOrArray) MarshalJSON() ([]byte, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/marshal.go","code":"func (s JSONSchemaPropsOrArray) MarshalJSON() ([]byte, error) {\n\tif len(s.JSONSchemas) \u003e 0 {\n\t\treturn json.Marshal(s.JSONSchemas)\n\t}\n\treturn json.Marshal(s.Schema)\n}","line":{"from":94,"to":99}} {"id":100013901,"name":"UnmarshalJSON","signature":"func (s *JSONSchemaPropsOrArray) UnmarshalJSON(data []byte) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/marshal.go","code":"func (s *JSONSchemaPropsOrArray) UnmarshalJSON(data []byte) error {\n\tvar nw JSONSchemaPropsOrArray\n\tvar first byte\n\tif len(data) \u003e 1 {\n\t\tfirst = data[0]\n\t}\n\tif first == '{' {\n\t\tvar sch JSONSchemaProps\n\t\tif err := json.Unmarshal(data, \u0026sch); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnw.Schema = \u0026sch\n\t}\n\tif first == '[' {\n\t\tif err := json.Unmarshal(data, \u0026nw.JSONSchemas); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t*s = nw\n\treturn nil\n}","line":{"from":101,"to":121}} {"id":100013902,"name":"MarshalJSON","signature":"func (s JSON) MarshalJSON() ([]byte, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/marshal.go","code":"func (s JSON) MarshalJSON() ([]byte, error) {\n\tif len(s.Raw) \u003e 0 {\n\t\treturn s.Raw, nil\n\t}\n\treturn []byte(\"null\"), nil\n\n}","line":{"from":123,"to":129}} {"id":100013903,"name":"UnmarshalJSON","signature":"func (s *JSON) UnmarshalJSON(data []byte) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/marshal.go","code":"func (s *JSON) UnmarshalJSON(data []byte) error {\n\tif len(data) \u003e 0 \u0026\u0026 !bytes.Equal(data, nullLiteral) {\n\t\ts.Raw = data\n\t}\n\treturn nil\n}","line":{"from":131,"to":136}} {"id":100013904,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/register.go","code":"// Kind takes an unqualified kind and returns back a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100013905,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/register.go","code":"// Resource takes an unqualified resource and returns back a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100013906,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026CustomResourceDefinition{},\n\t\t\u0026CustomResourceDefinitionList{},\n\t\t\u0026ConversionReview{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":46,"to":55}} {"id":100013907,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":57,"to":62}} {"id":100013908,"name":"OpenAPISchemaType","signature":"func (_ JSON) OpenAPISchemaType() []string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/types_jsonschema.go","code":"// OpenAPISchemaType is used by the kube-openapi generator when constructing\n// the OpenAPI spec of this type.\n//\n// See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators\nfunc (_ JSON) OpenAPISchemaType() []string {\n\t// TODO: return actual types when anyOf is supported\n\treturn nil\n}","line":{"from":258,"to":265}} {"id":100013909,"name":"OpenAPISchemaFormat","signature":"func (_ JSON) OpenAPISchemaFormat() string { return \"\" }","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/types_jsonschema.go","code":"// OpenAPISchemaFormat is used by the kube-openapi generator when constructing\n// the OpenAPI spec of this type.\nfunc (_ JSON) OpenAPISchemaFormat() string { return \"\" }","line":{"from":267,"to":269}} {"id":100013910,"name":"OpenAPISchemaType","signature":"func (_ JSONSchemaPropsOrArray) OpenAPISchemaType() []string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/types_jsonschema.go","code":"// OpenAPISchemaType is used by the kube-openapi generator when constructing\n// the OpenAPI spec of this type.\n//\n// See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators\nfunc (_ JSONSchemaPropsOrArray) OpenAPISchemaType() []string {\n\t// TODO: return actual types when anyOf is supported\n\treturn nil\n}","line":{"from":281,"to":288}} {"id":100013911,"name":"OpenAPISchemaFormat","signature":"func (_ JSONSchemaPropsOrArray) OpenAPISchemaFormat() string { return \"\" }","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/types_jsonschema.go","code":"// OpenAPISchemaFormat is used by the kube-openapi generator when constructing\n// the OpenAPI spec of this type.\nfunc (_ JSONSchemaPropsOrArray) OpenAPISchemaFormat() string { return \"\" }","line":{"from":290,"to":292}} {"id":100013912,"name":"OpenAPISchemaType","signature":"func (_ JSONSchemaPropsOrBool) OpenAPISchemaType() []string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/types_jsonschema.go","code":"// OpenAPISchemaType is used by the kube-openapi generator when constructing\n// the OpenAPI spec of this type.\n//\n// See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators\nfunc (_ JSONSchemaPropsOrBool) OpenAPISchemaType() []string {\n\t// TODO: return actual types when anyOf is supported\n\treturn nil\n}","line":{"from":301,"to":308}} {"id":100013913,"name":"OpenAPISchemaFormat","signature":"func (_ JSONSchemaPropsOrBool) OpenAPISchemaFormat() string { return \"\" }","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/types_jsonschema.go","code":"// OpenAPISchemaFormat is used by the kube-openapi generator when constructing\n// the OpenAPI spec of this type.\nfunc (_ JSONSchemaPropsOrBool) OpenAPISchemaFormat() string { return \"\" }","line":{"from":310,"to":312}} {"id":100013914,"name":"OpenAPISchemaType","signature":"func (_ JSONSchemaPropsOrStringArray) OpenAPISchemaType() []string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/types_jsonschema.go","code":"// OpenAPISchemaType is used by the kube-openapi generator when constructing\n// the OpenAPI spec of this type.\n//\n// See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators\nfunc (_ JSONSchemaPropsOrStringArray) OpenAPISchemaType() []string {\n\t// TODO: return actual types when anyOf is supported\n\treturn nil\n}","line":{"from":323,"to":330}} {"id":100013915,"name":"OpenAPISchemaFormat","signature":"func (_ JSONSchemaPropsOrStringArray) OpenAPISchemaFormat() string { return \"\" }","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/types_jsonschema.go","code":"// OpenAPISchemaFormat is used by the kube-openapi generator when constructing\n// the OpenAPI spec of this type.\nfunc (_ JSONSchemaPropsOrStringArray) OpenAPISchemaFormat() string { return \"\" }","line":{"from":332,"to":334}} {"id":100013916,"name":"Convert_apiextensions_JSONSchemaProps_To_v1beta1_JSONSchemaProps","signature":"func Convert_apiextensions_JSONSchemaProps_To_v1beta1_JSONSchemaProps(in *apiextensions.JSONSchemaProps, out *JSONSchemaProps, s conversion.Scope) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/conversion.go","code":"func Convert_apiextensions_JSONSchemaProps_To_v1beta1_JSONSchemaProps(in *apiextensions.JSONSchemaProps, out *JSONSchemaProps, s conversion.Scope) error {\n\tif err := autoConvert_apiextensions_JSONSchemaProps_To_v1beta1_JSONSchemaProps(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tif in.Default != nil \u0026\u0026 *(in.Default) == nil {\n\t\tout.Default = nil\n\t}\n\tif in.Example != nil \u0026\u0026 *(in.Example) == nil {\n\t\tout.Example = nil\n\t}\n\treturn nil\n}","line":{"from":28,"to":39}} {"id":100013917,"name":"Convert_apiextensions_JSON_To_v1beta1_JSON","signature":"func Convert_apiextensions_JSON_To_v1beta1_JSON(in *apiextensions.JSON, out *JSON, s conversion.Scope) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/conversion.go","code":"func Convert_apiextensions_JSON_To_v1beta1_JSON(in *apiextensions.JSON, out *JSON, s conversion.Scope) error {\n\traw, err := json.Marshal(*in)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(raw) == 0 || bytes.Equal(raw, nullLiteral) {\n\t\t// match JSON#UnmarshalJSON treatment of literal nulls\n\t\tout.Raw = nil\n\t} else {\n\t\tout.Raw = raw\n\t}\n\treturn nil\n}","line":{"from":43,"to":55}} {"id":100013918,"name":"Convert_v1beta1_JSON_To_apiextensions_JSON","signature":"func Convert_v1beta1_JSON_To_apiextensions_JSON(in *JSON, out *apiextensions.JSON, s conversion.Scope) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/conversion.go","code":"func Convert_v1beta1_JSON_To_apiextensions_JSON(in *JSON, out *apiextensions.JSON, s conversion.Scope) error {\n\tif in != nil {\n\t\tvar i interface{}\n\t\tif len(in.Raw) \u003e 0 \u0026\u0026 !bytes.Equal(in.Raw, nullLiteral) {\n\t\t\tif err := json.Unmarshal(in.Raw, \u0026i); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\t*out = i\n\t} else {\n\t\tout = nil\n\t}\n\treturn nil\n}","line":{"from":57,"to":70}} {"id":100013919,"name":"DeepCopy","signature":"func (in *JSONSchemaProps) DeepCopy() *JSONSchemaProps","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/deepcopy.go","code":"// TODO: Update this after a tag is created for interface fields in DeepCopy\nfunc (in *JSONSchemaProps) DeepCopy() *JSONSchemaProps {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(JSONSchemaProps)\n\t*out = *in\n\n\tif in.Ref != nil {\n\t\tin, out := \u0026in.Ref, \u0026out.Ref\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(string)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.Maximum != nil {\n\t\tin, out := \u0026in.Maximum, \u0026out.Maximum\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(float64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.Minimum != nil {\n\t\tin, out := \u0026in.Minimum, \u0026out.Minimum\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(float64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.MaxLength != nil {\n\t\tin, out := \u0026in.MaxLength, \u0026out.MaxLength\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(int64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.MinLength != nil {\n\t\tin, out := \u0026in.MinLength, \u0026out.MinLength\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(int64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\tif in.MaxItems != nil {\n\t\tin, out := \u0026in.MaxItems, \u0026out.MaxItems\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(int64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.MinItems != nil {\n\t\tin, out := \u0026in.MinItems, \u0026out.MinItems\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(int64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.MultipleOf != nil {\n\t\tin, out := \u0026in.MultipleOf, \u0026out.MultipleOf\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(float64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.MaxProperties != nil {\n\t\tin, out := \u0026in.MaxProperties, \u0026out.MaxProperties\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(int64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.MinProperties != nil {\n\t\tin, out := \u0026in.MinProperties, \u0026out.MinProperties\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(int64)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.Required != nil {\n\t\tin, out := \u0026in.Required, \u0026out.Required\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\n\tif in.Items != nil {\n\t\tin, out := \u0026in.Items, \u0026out.Items\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(JSONSchemaPropsOrArray)\n\t\t\t(*in).DeepCopyInto(*out)\n\t\t}\n\t}\n\n\tif in.AllOf != nil {\n\t\tin, out := \u0026in.AllOf, \u0026out.AllOf\n\t\t*out = make([]JSONSchemaProps, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(\u0026(*out)[i])\n\t\t}\n\t}\n\n\tif in.OneOf != nil {\n\t\tin, out := \u0026in.OneOf, \u0026out.OneOf\n\t\t*out = make([]JSONSchemaProps, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(\u0026(*out)[i])\n\t\t}\n\t}\n\tif in.AnyOf != nil {\n\t\tin, out := \u0026in.AnyOf, \u0026out.AnyOf\n\t\t*out = make([]JSONSchemaProps, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(\u0026(*out)[i])\n\t\t}\n\t}\n\n\tif in.Not != nil {\n\t\tin, out := \u0026in.Not, \u0026out.Not\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(JSONSchemaProps)\n\t\t\t(*in).DeepCopyInto(*out)\n\t\t}\n\t}\n\n\tif in.Properties != nil {\n\t\tin, out := \u0026in.Properties, \u0026out.Properties\n\t\t*out = make(map[string]JSONSchemaProps, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = *val.DeepCopy()\n\t\t}\n\t}\n\n\tif in.AdditionalProperties != nil {\n\t\tin, out := \u0026in.AdditionalProperties, \u0026out.AdditionalProperties\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(JSONSchemaPropsOrBool)\n\t\t\t(*in).DeepCopyInto(*out)\n\t\t}\n\t}\n\n\tif in.PatternProperties != nil {\n\t\tin, out := \u0026in.PatternProperties, \u0026out.PatternProperties\n\t\t*out = make(map[string]JSONSchemaProps, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = *val.DeepCopy()\n\t\t}\n\t}\n\n\tif in.Dependencies != nil {\n\t\tin, out := \u0026in.Dependencies, \u0026out.Dependencies\n\t\t*out = make(JSONSchemaDependencies, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = *val.DeepCopy()\n\t\t}\n\t}\n\n\tif in.AdditionalItems != nil {\n\t\tin, out := \u0026in.AdditionalItems, \u0026out.AdditionalItems\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(JSONSchemaPropsOrBool)\n\t\t\t(*in).DeepCopyInto(*out)\n\t\t}\n\t}\n\n\tif in.Definitions != nil {\n\t\tin, out := \u0026in.Definitions, \u0026out.Definitions\n\t\t*out = make(JSONSchemaDefinitions, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = *val.DeepCopy()\n\t\t}\n\t}\n\n\tif in.ExternalDocs != nil {\n\t\tin, out := \u0026in.ExternalDocs, \u0026out.ExternalDocs\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(ExternalDocumentation)\n\t\t\t(*in).DeepCopyInto(*out)\n\t\t}\n\t}\n\n\tif in.XPreserveUnknownFields != nil {\n\t\tin, out := \u0026in.XPreserveUnknownFields, \u0026out.XPreserveUnknownFields\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(bool)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.XListMapKeys != nil {\n\t\tin, out := \u0026in.XListMapKeys, \u0026out.XListMapKeys\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\n\tif in.XListType != nil {\n\t\tin, out := \u0026in.XListType, \u0026out.XListType\n\t\tif *in == nil {\n\t\t\t*out = nil\n\t\t} else {\n\t\t\t*out = new(string)\n\t\t\t**out = **in\n\t\t}\n\t}\n\n\tif in.XMapType != nil {\n\t\tin, out := \u0026in.XMapType, \u0026out.XMapType\n\t\t*out = new(string)\n\t\t**out = **in\n\t}\n\n\tif in.XValidations != nil {\n\t\tin, out := \u0026in.XValidations, \u0026out.XValidations\n\t\t*out = make([]ValidationRule, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\n\treturn out\n}","line":{"from":19,"to":276}} {"id":100013920,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":26,"to":28}} {"id":100013921,"name":"SetDefaults_CustomResourceDefinition","signature":"func SetDefaults_CustomResourceDefinition(obj *CustomResourceDefinition)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/defaults.go","code":"func SetDefaults_CustomResourceDefinition(obj *CustomResourceDefinition) {\n\tSetDefaults_CustomResourceDefinitionSpec(\u0026obj.Spec)\n\tif len(obj.Status.StoredVersions) == 0 {\n\t\tfor _, v := range obj.Spec.Versions {\n\t\t\tif v.Storage {\n\t\t\t\tobj.Status.StoredVersions = append(obj.Status.StoredVersions, v.Name)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":30,"to":40}} {"id":100013922,"name":"SetDefaults_CustomResourceDefinitionSpec","signature":"func SetDefaults_CustomResourceDefinitionSpec(obj *CustomResourceDefinitionSpec)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/defaults.go","code":"func SetDefaults_CustomResourceDefinitionSpec(obj *CustomResourceDefinitionSpec) {\n\tif len(obj.Scope) == 0 {\n\t\tobj.Scope = NamespaceScoped\n\t}\n\tif len(obj.Names.Singular) == 0 {\n\t\tobj.Names.Singular = strings.ToLower(obj.Names.Kind)\n\t}\n\tif len(obj.Names.ListKind) == 0 \u0026\u0026 len(obj.Names.Kind) \u003e 0 {\n\t\tobj.Names.ListKind = obj.Names.Kind + \"List\"\n\t}\n\t// If there is no list of versions, create on using deprecated Version field.\n\tif len(obj.Versions) == 0 \u0026\u0026 len(obj.Version) != 0 {\n\t\tobj.Versions = []CustomResourceDefinitionVersion{{\n\t\t\tName: obj.Version,\n\t\t\tStorage: true,\n\t\t\tServed: true,\n\t\t}}\n\t}\n\t// For backward compatibility set the version field to the first item in versions list.\n\tif len(obj.Version) == 0 \u0026\u0026 len(obj.Versions) != 0 {\n\t\tobj.Version = obj.Versions[0].Name\n\t}\n\tif obj.Conversion == nil {\n\t\tobj.Conversion = \u0026CustomResourceConversion{\n\t\t\tStrategy: NoneConverter,\n\t\t}\n\t}\n\tif obj.Conversion.Strategy == WebhookConverter \u0026\u0026 len(obj.Conversion.ConversionReviewVersions) == 0 {\n\t\tobj.Conversion.ConversionReviewVersions = []string{SchemeGroupVersion.Version}\n\t}\n\tif obj.PreserveUnknownFields == nil {\n\t\tobj.PreserveUnknownFields = utilpointer.BoolPtr(true)\n\t}\n}","line":{"from":42,"to":75}} {"id":100013923,"name":"SetDefaults_ServiceReference","signature":"func SetDefaults_ServiceReference(obj *ServiceReference)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/defaults.go","code":"// SetDefaults_ServiceReference sets defaults for Webhook's ServiceReference\nfunc SetDefaults_ServiceReference(obj *ServiceReference) {\n\tif obj.Port == nil {\n\t\tobj.Port = utilpointer.Int32Ptr(443)\n\t}\n}","line":{"from":77,"to":82}} {"id":100013924,"name":"MarshalJSON","signature":"func (s JSONSchemaPropsOrBool) MarshalJSON() ([]byte, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/marshal.go","code":"func (s JSONSchemaPropsOrBool) MarshalJSON() ([]byte, error) {\n\tif s.Schema != nil {\n\t\treturn json.Marshal(s.Schema)\n\t}\n\n\tif s.Schema == nil \u0026\u0026 !s.Allows {\n\t\treturn jsFalse, nil\n\t}\n\treturn jsTrue, nil\n}","line":{"from":29,"to":38}} {"id":100013925,"name":"UnmarshalJSON","signature":"func (s *JSONSchemaPropsOrBool) UnmarshalJSON(data []byte) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/marshal.go","code":"func (s *JSONSchemaPropsOrBool) UnmarshalJSON(data []byte) error {\n\tvar nw JSONSchemaPropsOrBool\n\tswitch {\n\tcase len(data) == 0:\n\tcase data[0] == '{':\n\t\tvar sch JSONSchemaProps\n\t\tif err := json.Unmarshal(data, \u0026sch); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnw.Allows = true\n\t\tnw.Schema = \u0026sch\n\tcase len(data) == 4 \u0026\u0026 string(data) == \"true\":\n\t\tnw.Allows = true\n\tcase len(data) == 5 \u0026\u0026 string(data) == \"false\":\n\t\tnw.Allows = false\n\tdefault:\n\t\treturn errors.New(\"boolean or JSON schema expected\")\n\t}\n\t*s = nw\n\treturn nil\n}","line":{"from":40,"to":60}} {"id":100013926,"name":"MarshalJSON","signature":"func (s JSONSchemaPropsOrStringArray) MarshalJSON() ([]byte, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/marshal.go","code":"func (s JSONSchemaPropsOrStringArray) MarshalJSON() ([]byte, error) {\n\tif len(s.Property) \u003e 0 {\n\t\treturn json.Marshal(s.Property)\n\t}\n\tif s.Schema != nil {\n\t\treturn json.Marshal(s.Schema)\n\t}\n\treturn []byte(\"null\"), nil\n}","line":{"from":62,"to":70}} {"id":100013927,"name":"UnmarshalJSON","signature":"func (s *JSONSchemaPropsOrStringArray) UnmarshalJSON(data []byte) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/marshal.go","code":"func (s *JSONSchemaPropsOrStringArray) UnmarshalJSON(data []byte) error {\n\tvar first byte\n\tif len(data) \u003e 1 {\n\t\tfirst = data[0]\n\t}\n\tvar nw JSONSchemaPropsOrStringArray\n\tif first == '{' {\n\t\tvar sch JSONSchemaProps\n\t\tif err := json.Unmarshal(data, \u0026sch); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnw.Schema = \u0026sch\n\t}\n\tif first == '[' {\n\t\tif err := json.Unmarshal(data, \u0026nw.Property); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t*s = nw\n\treturn nil\n}","line":{"from":72,"to":92}} {"id":100013928,"name":"MarshalJSON","signature":"func (s JSONSchemaPropsOrArray) MarshalJSON() ([]byte, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/marshal.go","code":"func (s JSONSchemaPropsOrArray) MarshalJSON() ([]byte, error) {\n\tif len(s.JSONSchemas) \u003e 0 {\n\t\treturn json.Marshal(s.JSONSchemas)\n\t}\n\treturn json.Marshal(s.Schema)\n}","line":{"from":94,"to":99}} {"id":100013929,"name":"UnmarshalJSON","signature":"func (s *JSONSchemaPropsOrArray) UnmarshalJSON(data []byte) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/marshal.go","code":"func (s *JSONSchemaPropsOrArray) UnmarshalJSON(data []byte) error {\n\tvar nw JSONSchemaPropsOrArray\n\tvar first byte\n\tif len(data) \u003e 1 {\n\t\tfirst = data[0]\n\t}\n\tif first == '{' {\n\t\tvar sch JSONSchemaProps\n\t\tif err := json.Unmarshal(data, \u0026sch); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnw.Schema = \u0026sch\n\t}\n\tif first == '[' {\n\t\tif err := json.Unmarshal(data, \u0026nw.JSONSchemas); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t*s = nw\n\treturn nil\n}","line":{"from":101,"to":121}} {"id":100013930,"name":"MarshalJSON","signature":"func (s JSON) MarshalJSON() ([]byte, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/marshal.go","code":"func (s JSON) MarshalJSON() ([]byte, error) {\n\tif len(s.Raw) \u003e 0 {\n\t\treturn s.Raw, nil\n\t}\n\treturn []byte(\"null\"), nil\n\n}","line":{"from":123,"to":129}} {"id":100013931,"name":"UnmarshalJSON","signature":"func (s *JSON) UnmarshalJSON(data []byte) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/marshal.go","code":"func (s *JSON) UnmarshalJSON(data []byte) error {\n\tif len(data) \u003e 0 \u0026\u0026 !bytes.Equal(data, nullLiteral) {\n\t\ts.Raw = data\n\t}\n\treturn nil\n}","line":{"from":131,"to":136}} {"id":100013932,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/register.go","code":"// Kind takes an unqualified kind and returns back a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100013933,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns back a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100013934,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026CustomResourceDefinition{},\n\t\t\u0026CustomResourceDefinitionList{},\n\t\t\u0026ConversionReview{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":46,"to":55}} {"id":100013935,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":57,"to":62}} {"id":100013936,"name":"OpenAPISchemaType","signature":"func (_ JSON) OpenAPISchemaType() []string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/types_jsonschema.go","code":"// OpenAPISchemaType is used by the kube-openapi generator when constructing\n// the OpenAPI spec of this type.\n//\n// See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators\nfunc (_ JSON) OpenAPISchemaType() []string {\n\t// TODO: return actual types when anyOf is supported\n\treturn nil\n}","line":{"from":258,"to":265}} {"id":100013937,"name":"OpenAPISchemaFormat","signature":"func (_ JSON) OpenAPISchemaFormat() string { return \"\" }","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/types_jsonschema.go","code":"// OpenAPISchemaFormat is used by the kube-openapi generator when constructing\n// the OpenAPI spec of this type.\nfunc (_ JSON) OpenAPISchemaFormat() string { return \"\" }","line":{"from":267,"to":269}} {"id":100013938,"name":"OpenAPISchemaType","signature":"func (_ JSONSchemaPropsOrArray) OpenAPISchemaType() []string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/types_jsonschema.go","code":"// OpenAPISchemaType is used by the kube-openapi generator when constructing\n// the OpenAPI spec of this type.\n//\n// See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators\nfunc (_ JSONSchemaPropsOrArray) OpenAPISchemaType() []string {\n\t// TODO: return actual types when anyOf is supported\n\treturn nil\n}","line":{"from":281,"to":288}} {"id":100013939,"name":"OpenAPISchemaFormat","signature":"func (_ JSONSchemaPropsOrArray) OpenAPISchemaFormat() string { return \"\" }","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/types_jsonschema.go","code":"// OpenAPISchemaFormat is used by the kube-openapi generator when constructing\n// the OpenAPI spec of this type.\nfunc (_ JSONSchemaPropsOrArray) OpenAPISchemaFormat() string { return \"\" }","line":{"from":290,"to":292}} {"id":100013940,"name":"OpenAPISchemaType","signature":"func (_ JSONSchemaPropsOrBool) OpenAPISchemaType() []string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/types_jsonschema.go","code":"// OpenAPISchemaType is used by the kube-openapi generator when constructing\n// the OpenAPI spec of this type.\n//\n// See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators\nfunc (_ JSONSchemaPropsOrBool) OpenAPISchemaType() []string {\n\t// TODO: return actual types when anyOf is supported\n\treturn nil\n}","line":{"from":301,"to":308}} {"id":100013941,"name":"OpenAPISchemaFormat","signature":"func (_ JSONSchemaPropsOrBool) OpenAPISchemaFormat() string { return \"\" }","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/types_jsonschema.go","code":"// OpenAPISchemaFormat is used by the kube-openapi generator when constructing\n// the OpenAPI spec of this type.\nfunc (_ JSONSchemaPropsOrBool) OpenAPISchemaFormat() string { return \"\" }","line":{"from":310,"to":312}} {"id":100013942,"name":"OpenAPISchemaType","signature":"func (_ JSONSchemaPropsOrStringArray) OpenAPISchemaType() []string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/types_jsonschema.go","code":"// OpenAPISchemaType is used by the kube-openapi generator when constructing\n// the OpenAPI spec of this type.\n//\n// See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators\nfunc (_ JSONSchemaPropsOrStringArray) OpenAPISchemaType() []string {\n\t// TODO: return actual types when anyOf is supported\n\treturn nil\n}","line":{"from":323,"to":330}} {"id":100013943,"name":"OpenAPISchemaFormat","signature":"func (_ JSONSchemaPropsOrStringArray) OpenAPISchemaFormat() string { return \"\" }","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/types_jsonschema.go","code":"// OpenAPISchemaFormat is used by the kube-openapi generator when constructing\n// the OpenAPI spec of this type.\nfunc (_ JSONSchemaPropsOrStringArray) OpenAPISchemaFormat() string { return \"\" }","line":{"from":332,"to":334}} {"id":100013944,"name":"TypeInfo","signature":"func (c *CELSchemaContext) TypeInfo() (*CELTypeInfo, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/cel_validation.go","code":"// TypeInfo returns the CELTypeInfo for this CELSchemaContext node. Returns nil, nil if this CELSchemaContext is nil,\n// or if current level or above does not have x-kubernetes-validations rules. The returned type info is shared and\n// should not be modified by the caller.\nfunc (c *CELSchemaContext) TypeInfo() (*CELTypeInfo, error) {\n\tif c == nil || !c.withinValidationRuleScope {\n\t\treturn nil, nil\n\t}\n\tif c.typeInfo != nil || c.typeInfoErr != nil {\n\t\treturn c.typeInfo, c.typeInfoErr // return already computed result if available\n\t}\n\n\t// If able to get the type info from the parent's type info, prefer this approach\n\t// since it is more efficient.\n\tif c.parent != nil {\n\t\tparentTypeInfo, parentErr := c.parent.TypeInfo()\n\t\tif parentErr != nil {\n\t\t\tc.typeInfoErr = parentErr\n\t\t\treturn nil, parentErr\n\t\t}\n\t\tif parentTypeInfo != nil \u0026\u0026 c.typeInfoAccessor != nil {\n\t\t\tc.typeInfo = c.typeInfoAccessor.accessTypeInfo(parentTypeInfo)\n\t\t\tif c.typeInfo != nil {\n\t\t\t\treturn c.typeInfo, nil\n\t\t\t}\n\t\t}\n\t}\n\t// If unable to get the type info from the parent, convert the jsonSchema to type info.\n\t// This is expensive for large schemas.\n\tc.typeInfo, c.typeInfoErr = c.converter(c.jsonSchema, c.parent == nil || c.jsonSchema.XEmbeddedResource)\n\treturn c.typeInfo, c.typeInfoErr\n}","line":{"from":76,"to":106}} {"id":100013945,"name":"defaultConverter","signature":"func defaultConverter(schema *apiextensions.JSONSchemaProps, isRoot bool) (*CELTypeInfo, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/cel_validation.go","code":"func defaultConverter(schema *apiextensions.JSONSchemaProps, isRoot bool) (*CELTypeInfo, error) {\n\tstructural, err := structuralschema.NewStructural(schema)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdeclType := model.SchemaDeclType(structural, isRoot)\n\tif declType == nil {\n\t\treturn nil, fmt.Errorf(\"unable to convert structural schema to CEL declarations\")\n\t}\n\treturn \u0026CELTypeInfo{structural, declType}, nil\n}","line":{"from":121,"to":131}} {"id":100013946,"name":"RootCELContext","signature":"func RootCELContext(schema *apiextensions.JSONSchemaProps) *CELSchemaContext","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/cel_validation.go","code":"// RootCELContext constructs CELSchemaContext for the given root schema.\nfunc RootCELContext(schema *apiextensions.JSONSchemaProps) *CELSchemaContext {\n\trootCardinality := uint64(1)\n\tr := \u0026CELSchemaContext{\n\t\tjsonSchema: schema,\n\t\twithinValidationRuleScope: len(schema.XValidations) \u003e 0,\n\t\tMaxCardinality: \u0026rootCardinality,\n\t\tTotalCost: \u0026TotalCost{},\n\t\tconverter: defaultConverter,\n\t}\n\treturn r\n}","line":{"from":133,"to":144}} {"id":100013947,"name":"ChildPropertyContext","signature":"func (c *CELSchemaContext) ChildPropertyContext(propSchema *apiextensions.JSONSchemaProps, propertyName string) *CELSchemaContext","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/cel_validation.go","code":"// ChildPropertyContext returns nil, nil if this CELSchemaContext is nil, otherwise constructs and returns a\n// CELSchemaContext for propertyName.\nfunc (c *CELSchemaContext) ChildPropertyContext(propSchema *apiextensions.JSONSchemaProps, propertyName string) *CELSchemaContext {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.childContext(propSchema, propertyTypeInfoAccessor{propertyName: propertyName})\n}","line":{"from":146,"to":153}} {"id":100013948,"name":"ChildAdditionalPropertiesContext","signature":"func (c *CELSchemaContext) ChildAdditionalPropertiesContext(propsSchema *apiextensions.JSONSchemaProps) *CELSchemaContext","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/cel_validation.go","code":"// ChildAdditionalPropertiesContext returns nil, nil if this CELSchemaContext is nil, otherwise it constructs and returns\n// a CELSchemaContext for the properties of an object if this CELSchemaContext is an object.\n// schema must be non-nil and have a non-nil schema.AdditionalProperties.\nfunc (c *CELSchemaContext) ChildAdditionalPropertiesContext(propsSchema *apiextensions.JSONSchemaProps) *CELSchemaContext {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.childContext(propsSchema, additionalItemsTypeInfoAccessor{})\n}","line":{"from":155,"to":163}} {"id":100013949,"name":"ChildItemsContext","signature":"func (c *CELSchemaContext) ChildItemsContext(itemsSchema *apiextensions.JSONSchemaProps) *CELSchemaContext","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/cel_validation.go","code":"// ChildItemsContext returns nil, nil if this CELSchemaContext is nil, otherwise it constructs and returns a CELSchemaContext\n// for the items of an array if this CELSchemaContext is an array.\nfunc (c *CELSchemaContext) ChildItemsContext(itemsSchema *apiextensions.JSONSchemaProps) *CELSchemaContext {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.childContext(itemsSchema, itemsTypeInfoAccessor{})\n}","line":{"from":165,"to":172}} {"id":100013950,"name":"childContext","signature":"func (c *CELSchemaContext) childContext(child *apiextensions.JSONSchemaProps, accessor typeInfoAccessor) *CELSchemaContext","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/cel_validation.go","code":"// childContext returns nil, nil if this CELSchemaContext is nil, otherwise it constructs a new CELSchemaContext for the\n// given child schema of the current schema context.\n// accessor optionally provides a way to access CELTypeInfo of the child from the current schema context's CELTypeInfo.\n// childContext returns a CELSchemaContext where the MaxCardinality is multiplied by the\n// factor that the schema increases the cardinality of its children. If the CELSchemaContext's\n// MaxCardinality is unbounded (nil) or the factor that the schema increase the cardinality\n// is unbounded, the resulting CELSchemaContext's MaxCardinality is also unbounded.\nfunc (c *CELSchemaContext) childContext(child *apiextensions.JSONSchemaProps, accessor typeInfoAccessor) *CELSchemaContext {\n\tresult := \u0026CELSchemaContext{\n\t\tparent: c,\n\t\ttypeInfoAccessor: accessor,\n\t\twithinValidationRuleScope: c.withinValidationRuleScope,\n\t\tTotalCost: c.TotalCost,\n\t\tMaxCardinality: unbounded,\n\t\tconverter: c.converter,\n\t}\n\tif child != nil {\n\t\tresult.jsonSchema = child\n\t\tif len(child.XValidations) \u003e 0 {\n\t\t\tresult.withinValidationRuleScope = true\n\t\t}\n\t}\n\tif c.jsonSchema == nil {\n\t\t// nil schemas can be passed since we call ChildSchemaContext\n\t\t// before ValidateCustomResourceDefinitionOpenAPISchema performs its nil check\n\t\treturn result\n\t}\n\tif c.MaxCardinality == unbounded {\n\t\treturn result\n\t}\n\tmaxElements := extractMaxElements(c.jsonSchema)\n\tif maxElements == unbounded {\n\t\treturn result\n\t}\n\tresult.MaxCardinality = uint64ptr(multiplyWithOverflowGuard(*c.MaxCardinality, *maxElements))\n\treturn result\n}","line":{"from":174,"to":210}} {"id":100013951,"name":"accessTypeInfo","signature":"func (c propertyTypeInfoAccessor) accessTypeInfo(parentTypeInfo *CELTypeInfo) *CELTypeInfo","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/cel_validation.go","code":"func (c propertyTypeInfoAccessor) accessTypeInfo(parentTypeInfo *CELTypeInfo) *CELTypeInfo {\n\tif parentTypeInfo.Schema.Properties != nil {\n\t\tpropSchema := parentTypeInfo.Schema.Properties[c.propertyName]\n\t\tif escapedPropName, ok := cel.Escape(c.propertyName); ok {\n\t\t\tif fieldDeclType, ok := parentTypeInfo.DeclType.Fields[escapedPropName]; ok {\n\t\t\t\treturn \u0026CELTypeInfo{Schema: \u0026propSchema, DeclType: fieldDeclType.Type}\n\t\t\t} // else fields with unknown types are omitted from CEL validation entirely\n\t\t} // fields with unescapable names are expected to be absent\n\t}\n\treturn nil\n}","line":{"from":225,"to":235}} {"id":100013952,"name":"accessTypeInfo","signature":"func (c itemsTypeInfoAccessor) accessTypeInfo(parentTypeInfo *CELTypeInfo) *CELTypeInfo","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/cel_validation.go","code":"func (c itemsTypeInfoAccessor) accessTypeInfo(parentTypeInfo *CELTypeInfo) *CELTypeInfo {\n\tif parentTypeInfo.Schema.Items != nil {\n\t\titemsSchema := parentTypeInfo.Schema.Items\n\t\titemsDeclType := parentTypeInfo.DeclType.ElemType\n\t\treturn \u0026CELTypeInfo{Schema: itemsSchema, DeclType: itemsDeclType}\n\t}\n\treturn nil\n}","line":{"from":239,"to":246}} {"id":100013953,"name":"accessTypeInfo","signature":"func (c additionalItemsTypeInfoAccessor) accessTypeInfo(parentTypeInfo *CELTypeInfo) *CELTypeInfo","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/cel_validation.go","code":"func (c additionalItemsTypeInfoAccessor) accessTypeInfo(parentTypeInfo *CELTypeInfo) *CELTypeInfo {\n\tif parentTypeInfo.Schema.AdditionalProperties != nil {\n\t\tpropsSchema := parentTypeInfo.Schema.AdditionalProperties.Structural\n\t\tvaluesDeclType := parentTypeInfo.DeclType.ElemType\n\t\treturn \u0026CELTypeInfo{Schema: propsSchema, DeclType: valuesDeclType}\n\t}\n\treturn nil\n}","line":{"from":250,"to":257}} {"id":100013954,"name":"ObserveExpressionCost","signature":"func (c *TotalCost) ObserveExpressionCost(path *field.Path, cost uint64)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/cel_validation.go","code":"// ObserveExpressionCost accumulates the cost of evaluating a -kubernetes-validations rule.\nfunc (c *TotalCost) ObserveExpressionCost(path *field.Path, cost uint64) {\n\tif math.MaxUint64-c.Total \u003c cost {\n\t\tc.Total = math.MaxUint64\n\t} else {\n\t\tc.Total += cost\n\t}\n\n\tif cost \u003c StaticEstimatedCRDCostLimit/100 { // ignore rules that contribute \u003c 1% of total cost limit\n\t\treturn\n\t}\n\tc.MostExpensive = append(c.MostExpensive, RuleCost{Path: path, Cost: cost})\n\tsort.Slice(c.MostExpensive, func(i, j int) bool {\n\t\t// sort in descending order so the most expensive rule is first\n\t\treturn c.MostExpensive[i].Cost \u003e c.MostExpensive[j].Cost\n\t})\n\tif len(c.MostExpensive) \u003e 4 {\n\t\tc.MostExpensive = c.MostExpensive[:4]\n\t}\n}","line":{"from":268,"to":287}} {"id":100013955,"name":"extractMaxElements","signature":"func extractMaxElements(schema *apiextensions.JSONSchemaProps) *uint64","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/cel_validation.go","code":"// extractMaxElements returns the factor by which the schema increases the cardinality\n// (number of possible data elements) of its children. If schema is a map and has\n// MaxProperties or an array has MaxItems, the int pointer of the max value is returned.\n// If schema is a map or array and does not have MaxProperties or MaxItems,\n// unbounded (nil) is returned to indicate that there is no limit to the possible\n// number of data elements imposed by the current schema. If the schema is an object, 1 is\n// returned to indicate that there is no increase to the number of possible data elements\n// for its children. Primitives do not have children, but 1 is returned for simplicity.\nfunc extractMaxElements(schema *apiextensions.JSONSchemaProps) *uint64 {\n\tswitch schema.Type {\n\tcase \"object\":\n\t\tif schema.AdditionalProperties != nil {\n\t\t\tif schema.MaxProperties != nil {\n\t\t\t\tmaxProps := uint64(zeroIfNegative(*schema.MaxProperties))\n\t\t\t\treturn \u0026maxProps\n\t\t\t}\n\t\t\treturn unbounded\n\t\t}\n\t\t// return 1 to indicate that all fields of an object exist at most one for\n\t\t// each occurrence of the object they are fields of\n\t\treturn uint64ptr(1)\n\tcase \"array\":\n\t\tif schema.MaxItems != nil {\n\t\t\tmaxItems := uint64(zeroIfNegative(*schema.MaxItems))\n\t\t\treturn \u0026maxItems\n\t\t}\n\t\treturn unbounded\n\tdefault:\n\t\treturn uint64ptr(1)\n\t}\n}","line":{"from":295,"to":325}} {"id":100013956,"name":"zeroIfNegative","signature":"func zeroIfNegative(v int64) int64","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/cel_validation.go","code":"func zeroIfNegative(v int64) int64 {\n\tif v \u003c 0 {\n\t\treturn 0\n\t}\n\treturn v\n}","line":{"from":327,"to":332}} {"id":100013957,"name":"uint64ptr","signature":"func uint64ptr(i uint64) *uint64","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/cel_validation.go","code":"func uint64ptr(i uint64) *uint64 {\n\treturn \u0026i\n}","line":{"from":334,"to":336}} {"id":100013958,"name":"ValidateCustomResourceDefinition","signature":"func ValidateCustomResourceDefinition(ctx context.Context, obj *apiextensions.CustomResourceDefinition) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// ValidateCustomResourceDefinition statically validates\n// context is passed for supporting context cancellation during cel validation when validating defaults\nfunc ValidateCustomResourceDefinition(ctx context.Context, obj *apiextensions.CustomResourceDefinition) field.ErrorList {\n\tnameValidationFn := func(name string, prefix bool) []string {\n\t\tret := genericvalidation.NameIsDNSSubdomain(name, prefix)\n\t\trequiredName := obj.Spec.Names.Plural + \".\" + obj.Spec.Group\n\t\tif name != requiredName {\n\t\t\tret = append(ret, fmt.Sprintf(`must be spec.names.plural+\".\"+spec.group`))\n\t\t}\n\t\treturn ret\n\t}\n\n\topts := validationOptions{\n\t\tallowDefaults: true,\n\t\trequireRecognizedConversionReviewVersion: true,\n\t\trequireImmutableNames: false,\n\t\trequireOpenAPISchema: true,\n\t\trequireValidPropertyType: true,\n\t\trequireStructuralSchema: true,\n\t\trequirePrunedDefaults: true,\n\t\trequireAtomicSetType: true,\n\t\trequireMapListKeysMapSetValidation: true,\n\t}\n\n\tallErrs := genericvalidation.ValidateObjectMeta(\u0026obj.ObjectMeta, false, nameValidationFn, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, validateCustomResourceDefinitionSpec(ctx, \u0026obj.Spec, opts, field.NewPath(\"spec\"))...)\n\tallErrs = append(allErrs, ValidateCustomResourceDefinitionStatus(\u0026obj.Status, field.NewPath(\"status\"))...)\n\tallErrs = append(allErrs, ValidateCustomResourceDefinitionStoredVersions(obj.Status.StoredVersions, obj.Spec.Versions, field.NewPath(\"status\").Child(\"storedVersions\"))...)\n\tallErrs = append(allErrs, validateAPIApproval(obj, nil)...)\n\tallErrs = append(allErrs, validatePreserveUnknownFields(obj, nil)...)\n\treturn allErrs\n}","line":{"from":62,"to":93}} {"id":100013959,"name":"ValidateCustomResourceDefinitionUpdate","signature":"func ValidateCustomResourceDefinitionUpdate(ctx context.Context, obj, oldObj *apiextensions.CustomResourceDefinition) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// ValidateCustomResourceDefinitionUpdate statically validates\n// context is passed for supporting context cancellation during cel validation when validating defaults\nfunc ValidateCustomResourceDefinitionUpdate(ctx context.Context, obj, oldObj *apiextensions.CustomResourceDefinition) field.ErrorList {\n\topts := validationOptions{\n\t\tallowDefaults: true,\n\t\trequireRecognizedConversionReviewVersion: oldObj.Spec.Conversion == nil || hasValidConversionReviewVersionOrEmpty(oldObj.Spec.Conversion.ConversionReviewVersions),\n\t\trequireImmutableNames: apiextensions.IsCRDConditionTrue(oldObj, apiextensions.Established),\n\t\trequireOpenAPISchema: requireOpenAPISchema(\u0026oldObj.Spec),\n\t\trequireValidPropertyType: requireValidPropertyType(\u0026oldObj.Spec),\n\t\trequireStructuralSchema: requireStructuralSchema(\u0026oldObj.Spec),\n\t\trequirePrunedDefaults: requirePrunedDefaults(\u0026oldObj.Spec),\n\t\trequireAtomicSetType: requireAtomicSetType(\u0026oldObj.Spec),\n\t\trequireMapListKeysMapSetValidation: requireMapListKeysMapSetValidation(\u0026oldObj.Spec),\n\t}\n\n\tallErrs := genericvalidation.ValidateObjectMetaUpdate(\u0026obj.ObjectMeta, \u0026oldObj.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, validateCustomResourceDefinitionSpecUpdate(ctx, \u0026obj.Spec, \u0026oldObj.Spec, opts, field.NewPath(\"spec\"))...)\n\tallErrs = append(allErrs, ValidateCustomResourceDefinitionStatus(\u0026obj.Status, field.NewPath(\"status\"))...)\n\tallErrs = append(allErrs, ValidateCustomResourceDefinitionStoredVersions(obj.Status.StoredVersions, obj.Spec.Versions, field.NewPath(\"status\").Child(\"storedVersions\"))...)\n\tallErrs = append(allErrs, validateAPIApproval(obj, oldObj)...)\n\tallErrs = append(allErrs, validatePreserveUnknownFields(obj, oldObj)...)\n\treturn allErrs\n}","line":{"from":121,"to":143}} {"id":100013960,"name":"ValidateCustomResourceDefinitionStoredVersions","signature":"func ValidateCustomResourceDefinitionStoredVersions(storedVersions []string, versions []apiextensions.CustomResourceDefinitionVersion, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// ValidateCustomResourceDefinitionStoredVersions statically validates\nfunc ValidateCustomResourceDefinitionStoredVersions(storedVersions []string, versions []apiextensions.CustomResourceDefinitionVersion, fldPath *field.Path) field.ErrorList {\n\tif len(storedVersions) == 0 {\n\t\treturn field.ErrorList{field.Invalid(fldPath, storedVersions, \"must have at least one stored version\")}\n\t}\n\tallErrs := field.ErrorList{}\n\tstoredVersionsMap := map[string]int{}\n\tfor i, v := range storedVersions {\n\t\tstoredVersionsMap[v] = i\n\t}\n\tfor _, v := range versions {\n\t\t_, ok := storedVersionsMap[v.Name]\n\t\tif v.Storage \u0026\u0026 !ok {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, v, \"must have the storage version \"+v.Name))\n\t\t}\n\t\tif ok {\n\t\t\tdelete(storedVersionsMap, v.Name)\n\t\t}\n\t}\n\n\tfor v, i := range storedVersionsMap {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Index(i), v, \"must appear in spec.versions\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":145,"to":170}} {"id":100013961,"name":"ValidateUpdateCustomResourceDefinitionStatus","signature":"func ValidateUpdateCustomResourceDefinitionStatus(obj, oldObj *apiextensions.CustomResourceDefinition) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// ValidateUpdateCustomResourceDefinitionStatus statically validates\nfunc ValidateUpdateCustomResourceDefinitionStatus(obj, oldObj *apiextensions.CustomResourceDefinition) field.ErrorList {\n\tallErrs := genericvalidation.ValidateObjectMetaUpdate(\u0026obj.ObjectMeta, \u0026oldObj.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateCustomResourceDefinitionStatus(\u0026obj.Status, field.NewPath(\"status\"))...)\n\treturn allErrs\n}","line":{"from":172,"to":177}} {"id":100013962,"name":"validateCustomResourceDefinitionVersion","signature":"func validateCustomResourceDefinitionVersion(ctx context.Context, version *apiextensions.CustomResourceDefinitionVersion, fldPath *field.Path, statusEnabled bool, opts validationOptions) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// validateCustomResourceDefinitionVersion statically validates.\n// context is passed for supporting context cancellation during cel validation when validating defaults\nfunc validateCustomResourceDefinitionVersion(ctx context.Context, version *apiextensions.CustomResourceDefinitionVersion, fldPath *field.Path, statusEnabled bool, opts validationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor _, err := range validateDeprecationWarning(version.Deprecated, version.DeprecationWarning) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"deprecationWarning\"), version.DeprecationWarning, err))\n\t}\n\tallErrs = append(allErrs, validateCustomResourceDefinitionValidation(ctx, version.Schema, statusEnabled, opts, fldPath.Child(\"schema\"))...)\n\tallErrs = append(allErrs, ValidateCustomResourceDefinitionSubresources(version.Subresources, fldPath.Child(\"subresources\"))...)\n\tfor i := range version.AdditionalPrinterColumns {\n\t\tallErrs = append(allErrs, ValidateCustomResourceColumnDefinition(\u0026version.AdditionalPrinterColumns[i], fldPath.Child(\"additionalPrinterColumns\").Index(i))...)\n\t}\n\treturn allErrs\n}","line":{"from":179,"to":192}} {"id":100013963,"name":"validateDeprecationWarning","signature":"func validateDeprecationWarning(deprecated bool, deprecationWarning *string) []string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func validateDeprecationWarning(deprecated bool, deprecationWarning *string) []string {\n\tif !deprecated \u0026\u0026 deprecationWarning != nil {\n\t\treturn []string{\"can only be set for deprecated versions\"}\n\t}\n\tif deprecationWarning == nil {\n\t\treturn nil\n\t}\n\tvar errors []string\n\tif len(*deprecationWarning) \u003e 256 {\n\t\terrors = append(errors, \"must be \u003c= 256 characters long\")\n\t}\n\tif len(*deprecationWarning) == 0 {\n\t\terrors = append(errors, \"must not be an empty string\")\n\t}\n\tfor i, r := range *deprecationWarning {\n\t\tif !unicode.IsPrint(r) {\n\t\t\terrors = append(errors, fmt.Sprintf(\"must only contain printable UTF-8 characters; non-printable character found at index %d\", i))\n\t\t\tbreak\n\t\t}\n\t\tif unicode.IsControl(r) {\n\t\t\terrors = append(errors, fmt.Sprintf(\"must only contain printable UTF-8 characters; control character found at index %d\", i))\n\t\t\tbreak\n\t\t}\n\t}\n\tif !utf8.ValidString(*deprecationWarning) {\n\t\terrors = append(errors, \"must only contain printable UTF-8 characters\")\n\t}\n\treturn errors\n}","line":{"from":194,"to":222}} {"id":100013964,"name":"validateCustomResourceDefinitionSpec","signature":"func validateCustomResourceDefinitionSpec(ctx context.Context, spec *apiextensions.CustomResourceDefinitionSpec, opts validationOptions, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// context is passed for supporting context cancellation during cel validation when validating defaults\nfunc validateCustomResourceDefinitionSpec(ctx context.Context, spec *apiextensions.CustomResourceDefinitionSpec, opts validationOptions, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(spec.Group) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"group\"), \"\"))\n\t} else if errs := utilvalidation.IsDNS1123Subdomain(spec.Group); len(errs) \u003e 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"group\"), spec.Group, strings.Join(errs, \",\")))\n\t} else if len(strings.Split(spec.Group, \".\")) \u003c 2 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"group\"), spec.Group, \"should be a domain with at least one dot\"))\n\t}\n\n\tallErrs = append(allErrs, validateEnumStrings(fldPath.Child(\"scope\"), string(spec.Scope), []string{string(apiextensions.ClusterScoped), string(apiextensions.NamespaceScoped)}, true)...)\n\n\t// enabling pruning requires structural schemas\n\tif spec.PreserveUnknownFields == nil || *spec.PreserveUnknownFields == false {\n\t\topts.requireStructuralSchema = true\n\t}\n\n\tif opts.requireOpenAPISchema {\n\t\t// check that either a global schema or versioned schemas are set in all versions\n\t\tif spec.Validation == nil || spec.Validation.OpenAPIV3Schema == nil {\n\t\t\tfor i, v := range spec.Versions {\n\t\t\t\tif v.Schema == nil || v.Schema.OpenAPIV3Schema == nil {\n\t\t\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"versions\").Index(i).Child(\"schema\").Child(\"openAPIV3Schema\"), \"schemas are required\"))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else if spec.PreserveUnknownFields == nil || *spec.PreserveUnknownFields == false {\n\t\t// check that either a global schema or versioned schemas are set in served versions\n\t\tif spec.Validation == nil || spec.Validation.OpenAPIV3Schema == nil {\n\t\t\tfor i, v := range spec.Versions {\n\t\t\t\tschemaPath := fldPath.Child(\"versions\").Index(i).Child(\"schema\", \"openAPIV3Schema\")\n\t\t\t\tif v.Served \u0026\u0026 (v.Schema == nil || v.Schema.OpenAPIV3Schema == nil) {\n\t\t\t\t\tallErrs = append(allErrs, field.Required(schemaPath, \"because otherwise all fields are pruned\"))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif opts.allowDefaults \u0026\u0026 specHasDefaults(spec) {\n\t\topts.requireStructuralSchema = true\n\t\tif spec.PreserveUnknownFields == nil || *spec.PreserveUnknownFields == true {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"preserveUnknownFields\"), true, \"must be false in order to use defaults in the schema\"))\n\t\t}\n\t}\n\tif specHasKubernetesExtensions(spec) {\n\t\topts.requireStructuralSchema = true\n\t}\n\n\tstorageFlagCount := 0\n\tversionsMap := map[string]bool{}\n\tuniqueNames := true\n\tfor i, version := range spec.Versions {\n\t\tif version.Storage {\n\t\t\tstorageFlagCount++\n\t\t}\n\t\tif versionsMap[version.Name] {\n\t\t\tuniqueNames = false\n\t\t} else {\n\t\t\tversionsMap[version.Name] = true\n\t\t}\n\t\tif errs := utilvalidation.IsDNS1035Label(version.Name); len(errs) \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"versions\").Index(i).Child(\"name\"), spec.Versions[i].Name, strings.Join(errs, \",\")))\n\t\t}\n\t\tsubresources := getSubresourcesForVersion(spec, version.Name)\n\t\tallErrs = append(allErrs, validateCustomResourceDefinitionVersion(ctx, \u0026version, fldPath.Child(\"versions\").Index(i), hasStatusEnabled(subresources), opts)...)\n\t}\n\n\t// The top-level and per-version fields are mutual exclusive\n\tif spec.Validation != nil \u0026\u0026 hasPerVersionSchema(spec.Versions) {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"validation\"), \"top-level and per-version schemas are mutually exclusive\"))\n\t}\n\tif spec.Subresources != nil \u0026\u0026 hasPerVersionSubresources(spec.Versions) {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"subresources\"), \"top-level and per-version subresources are mutually exclusive\"))\n\t}\n\tif len(spec.AdditionalPrinterColumns) \u003e 0 \u0026\u0026 hasPerVersionColumns(spec.Versions) {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"additionalPrinterColumns\"), \"top-level and per-version additionalPrinterColumns are mutually exclusive\"))\n\t}\n\n\t// Per-version fields may not all be set to identical values (top-level field should be used instead)\n\tif hasIdenticalPerVersionSchema(spec.Versions) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"versions\"), spec.Versions, \"per-version schemas may not all be set to identical values (top-level validation should be used instead)\"))\n\t}\n\tif hasIdenticalPerVersionSubresources(spec.Versions) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"versions\"), spec.Versions, \"per-version subresources may not all be set to identical values (top-level subresources should be used instead)\"))\n\t}\n\tif hasIdenticalPerVersionColumns(spec.Versions) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"versions\"), spec.Versions, \"per-version additionalPrinterColumns may not all be set to identical values (top-level additionalPrinterColumns should be used instead)\"))\n\t}\n\n\tif !uniqueNames {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"versions\"), spec.Versions, \"must contain unique version names\"))\n\t}\n\tif storageFlagCount != 1 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"versions\"), spec.Versions, \"must have exactly one version marked as storage version\"))\n\t}\n\tif len(spec.Version) != 0 {\n\t\tif errs := utilvalidation.IsDNS1035Label(spec.Version); len(errs) \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"version\"), spec.Version, strings.Join(errs, \",\")))\n\t\t}\n\t\tif len(spec.Versions) \u003e= 1 \u0026\u0026 spec.Versions[0].Name != spec.Version {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"version\"), spec.Version, \"must match the first version in spec.versions\"))\n\t\t}\n\t}\n\n\t// in addition to the basic name restrictions, some names are required for spec, but not for status\n\tif len(spec.Names.Plural) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"names\", \"plural\"), \"\"))\n\t}\n\tif len(spec.Names.Singular) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"names\", \"singular\"), \"\"))\n\t}\n\tif len(spec.Names.Kind) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"names\", \"kind\"), \"\"))\n\t}\n\tif len(spec.Names.ListKind) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"names\", \"listKind\"), \"\"))\n\t}\n\n\tallErrs = append(allErrs, ValidateCustomResourceDefinitionNames(\u0026spec.Names, fldPath.Child(\"names\"))...)\n\tallErrs = append(allErrs, validateCustomResourceDefinitionValidation(ctx, spec.Validation, hasAnyStatusEnabled(spec), opts, fldPath.Child(\"validation\"))...)\n\tallErrs = append(allErrs, ValidateCustomResourceDefinitionSubresources(spec.Subresources, fldPath.Child(\"subresources\"))...)\n\n\tfor i := range spec.AdditionalPrinterColumns {\n\t\tif errs := ValidateCustomResourceColumnDefinition(\u0026spec.AdditionalPrinterColumns[i], fldPath.Child(\"additionalPrinterColumns\").Index(i)); len(errs) \u003e 0 {\n\t\t\tallErrs = append(allErrs, errs...)\n\t\t}\n\t}\n\n\tif (spec.Conversion != nil \u0026\u0026 spec.Conversion.Strategy != apiextensions.NoneConverter) \u0026\u0026 (spec.PreserveUnknownFields == nil || *spec.PreserveUnknownFields) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"conversion\").Child(\"strategy\"), spec.Conversion.Strategy, \"must be None if spec.preserveUnknownFields is true\"))\n\t}\n\tallErrs = append(allErrs, validateCustomResourceConversion(spec.Conversion, opts.requireRecognizedConversionReviewVersion, fldPath.Child(\"conversion\"))...)\n\n\treturn allErrs\n}","line":{"from":224,"to":359}} {"id":100013965,"name":"validateEnumStrings","signature":"func validateEnumStrings(fldPath *field.Path, value string, accepted []string, required bool) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func validateEnumStrings(fldPath *field.Path, value string, accepted []string, required bool) field.ErrorList {\n\tif value == \"\" {\n\t\tif required {\n\t\t\treturn field.ErrorList{field.Required(fldPath, \"\")}\n\t\t}\n\t\treturn field.ErrorList{}\n\t}\n\tfor _, a := range accepted {\n\t\tif a == value {\n\t\t\treturn field.ErrorList{}\n\t\t}\n\t}\n\treturn field.ErrorList{field.NotSupported(fldPath, value, accepted)}\n}","line":{"from":361,"to":374}} {"id":100013966,"name":"isAcceptedConversionReviewVersion","signature":"func isAcceptedConversionReviewVersion(v string) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func isAcceptedConversionReviewVersion(v string) bool {\n\treturn acceptedConversionReviewVersions.Has(v)\n}","line":{"from":382,"to":384}} {"id":100013967,"name":"validateConversionReviewVersions","signature":"func validateConversionReviewVersions(versions []string, requireRecognizedVersion bool, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func validateConversionReviewVersions(versions []string, requireRecognizedVersion bool, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(versions) \u003c 1 {\n\t\tallErrs = append(allErrs, field.Required(fldPath, \"\"))\n\t} else {\n\t\tseen := map[string]bool{}\n\t\thasAcceptedVersion := false\n\t\tfor i, v := range versions {\n\t\t\tif seen[v] {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Index(i), v, \"duplicate version\"))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tseen[v] = true\n\t\t\tfor _, errString := range utilvalidation.IsDNS1035Label(v) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Index(i), v, errString))\n\t\t\t}\n\t\t\tif isAcceptedConversionReviewVersion(v) {\n\t\t\t\thasAcceptedVersion = true\n\t\t\t}\n\t\t}\n\t\tif requireRecognizedVersion \u0026\u0026 !hasAcceptedVersion {\n\t\t\tallErrs = append(allErrs, field.Invalid(\n\t\t\t\tfldPath, versions,\n\t\t\t\tfmt.Sprintf(\"must include at least one of %v\",\n\t\t\t\t\tstrings.Join(acceptedConversionReviewVersions.List(), \", \"))))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":386,"to":414}} {"id":100013968,"name":"hasValidConversionReviewVersionOrEmpty","signature":"func hasValidConversionReviewVersionOrEmpty(versions []string) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// hasValidConversionReviewVersion return true if there is a valid version or if the list is empty.\nfunc hasValidConversionReviewVersionOrEmpty(versions []string) bool {\n\tif len(versions) \u003c 1 {\n\t\treturn true\n\t}\n\tfor _, v := range versions {\n\t\tif isAcceptedConversionReviewVersion(v) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":416,"to":427}} {"id":100013969,"name":"ValidateCustomResourceConversion","signature":"func ValidateCustomResourceConversion(conversion *apiextensions.CustomResourceConversion, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// ValidateCustomResourceConversion statically validates\nfunc ValidateCustomResourceConversion(conversion *apiextensions.CustomResourceConversion, fldPath *field.Path) field.ErrorList {\n\treturn validateCustomResourceConversion(conversion, true, fldPath)\n}","line":{"from":429,"to":432}} {"id":100013970,"name":"validateCustomResourceConversion","signature":"func validateCustomResourceConversion(conversion *apiextensions.CustomResourceConversion, requireRecognizedVersion bool, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func validateCustomResourceConversion(conversion *apiextensions.CustomResourceConversion, requireRecognizedVersion bool, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif conversion == nil {\n\t\treturn allErrs\n\t}\n\tallErrs = append(allErrs, validateEnumStrings(fldPath.Child(\"strategy\"), string(conversion.Strategy), []string{string(apiextensions.NoneConverter), string(apiextensions.WebhookConverter)}, true)...)\n\tif conversion.Strategy == apiextensions.WebhookConverter {\n\t\tif conversion.WebhookClientConfig == nil {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"webhookClientConfig\"), \"required when strategy is set to Webhook\"))\n\t\t} else {\n\t\t\tcc := conversion.WebhookClientConfig\n\t\t\tswitch {\n\t\t\tcase (cc.URL == nil) == (cc.Service == nil):\n\t\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"webhookClientConfig\"), \"exactly one of url or service is required\"))\n\t\t\tcase cc.URL != nil:\n\t\t\t\tallErrs = append(allErrs, webhook.ValidateWebhookURL(fldPath.Child(\"webhookClientConfig\").Child(\"url\"), *cc.URL, true)...)\n\t\t\tcase cc.Service != nil:\n\t\t\t\tallErrs = append(allErrs, webhook.ValidateWebhookService(fldPath.Child(\"webhookClientConfig\").Child(\"service\"), cc.Service.Name, cc.Service.Namespace, cc.Service.Path, cc.Service.Port)...)\n\t\t\t}\n\t\t}\n\t\tallErrs = append(allErrs, validateConversionReviewVersions(conversion.ConversionReviewVersions, requireRecognizedVersion, fldPath.Child(\"conversionReviewVersions\"))...)\n\t} else {\n\t\tif conversion.WebhookClientConfig != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"webhookClientConfig\"), \"should not be set when strategy is not set to Webhook\"))\n\t\t}\n\t\tif len(conversion.ConversionReviewVersions) \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"conversionReviewVersions\"), \"should not be set when strategy is not set to Webhook\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":434,"to":464}} {"id":100013971,"name":"validateCustomResourceDefinitionSpecUpdate","signature":"func validateCustomResourceDefinitionSpecUpdate(ctx context.Context, spec, oldSpec *apiextensions.CustomResourceDefinitionSpec, opts validationOptions, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// validateCustomResourceDefinitionSpecUpdate statically validates\n// context is passed for supporting context cancellation during cel validation when validating defaults\nfunc validateCustomResourceDefinitionSpecUpdate(ctx context.Context, spec, oldSpec *apiextensions.CustomResourceDefinitionSpec, opts validationOptions, fldPath *field.Path) field.ErrorList {\n\tallErrs := validateCustomResourceDefinitionSpec(ctx, spec, opts, fldPath)\n\n\tif opts.requireImmutableNames {\n\t\t// these effect the storage and cannot be changed therefore\n\t\tallErrs = append(allErrs, genericvalidation.ValidateImmutableField(spec.Scope, oldSpec.Scope, fldPath.Child(\"scope\"))...)\n\t\tallErrs = append(allErrs, genericvalidation.ValidateImmutableField(spec.Names.Kind, oldSpec.Names.Kind, fldPath.Child(\"names\", \"kind\"))...)\n\t}\n\n\t// these affects the resource name, which is always immutable, so this can't be updated.\n\tallErrs = append(allErrs, genericvalidation.ValidateImmutableField(spec.Group, oldSpec.Group, fldPath.Child(\"group\"))...)\n\tallErrs = append(allErrs, genericvalidation.ValidateImmutableField(spec.Names.Plural, oldSpec.Names.Plural, fldPath.Child(\"names\", \"plural\"))...)\n\n\treturn allErrs\n}","line":{"from":466,"to":482}} {"id":100013972,"name":"getSubresourcesForVersion","signature":"func getSubresourcesForVersion(crd *apiextensions.CustomResourceDefinitionSpec, version string) *apiextensions.CustomResourceSubresources","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// getSubresourcesForVersion returns the subresources for given version in given CRD spec.\n// NOTE That this function assumes version always exist since it's used by the validation process\n// that iterates through the existing versions.\nfunc getSubresourcesForVersion(crd *apiextensions.CustomResourceDefinitionSpec, version string) *apiextensions.CustomResourceSubresources {\n\tif !hasPerVersionSubresources(crd.Versions) {\n\t\treturn crd.Subresources\n\t}\n\tfor _, v := range crd.Versions {\n\t\tif version == v.Name {\n\t\t\treturn v.Subresources\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":484,"to":497}} {"id":100013973,"name":"hasAnyStatusEnabled","signature":"func hasAnyStatusEnabled(crd *apiextensions.CustomResourceDefinitionSpec) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// hasAnyStatusEnabled returns true if given CRD spec has at least one Status Subresource set\n// among the top-level and per-version Subresources.\nfunc hasAnyStatusEnabled(crd *apiextensions.CustomResourceDefinitionSpec) bool {\n\tif hasStatusEnabled(crd.Subresources) {\n\t\treturn true\n\t}\n\tfor _, v := range crd.Versions {\n\t\tif hasStatusEnabled(v.Subresources) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":499,"to":511}} {"id":100013974,"name":"hasStatusEnabled","signature":"func hasStatusEnabled(subresources *apiextensions.CustomResourceSubresources) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// hasStatusEnabled returns true if given CRD Subresources has non-nil Status set.\nfunc hasStatusEnabled(subresources *apiextensions.CustomResourceSubresources) bool {\n\tif subresources != nil \u0026\u0026 subresources.Status != nil {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":513,"to":519}} {"id":100013975,"name":"hasPerVersionSchema","signature":"func hasPerVersionSchema(versions []apiextensions.CustomResourceDefinitionVersion) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// hasPerVersionSchema returns true if a CRD uses per-version schema.\nfunc hasPerVersionSchema(versions []apiextensions.CustomResourceDefinitionVersion) bool {\n\tfor _, v := range versions {\n\t\tif v.Schema != nil {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":521,"to":529}} {"id":100013976,"name":"hasPerVersionSubresources","signature":"func hasPerVersionSubresources(versions []apiextensions.CustomResourceDefinitionVersion) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// hasPerVersionSubresources returns true if a CRD uses per-version subresources.\nfunc hasPerVersionSubresources(versions []apiextensions.CustomResourceDefinitionVersion) bool {\n\tfor _, v := range versions {\n\t\tif v.Subresources != nil {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":531,"to":539}} {"id":100013977,"name":"hasPerVersionColumns","signature":"func hasPerVersionColumns(versions []apiextensions.CustomResourceDefinitionVersion) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// hasPerVersionColumns returns true if a CRD uses per-version columns.\nfunc hasPerVersionColumns(versions []apiextensions.CustomResourceDefinitionVersion) bool {\n\tfor _, v := range versions {\n\t\tif len(v.AdditionalPrinterColumns) \u003e 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":541,"to":549}} {"id":100013978,"name":"hasIdenticalPerVersionSchema","signature":"func hasIdenticalPerVersionSchema(versions []apiextensions.CustomResourceDefinitionVersion) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// hasIdenticalPerVersionSchema returns true if a CRD sets identical non-nil values\n// to all per-version schemas\nfunc hasIdenticalPerVersionSchema(versions []apiextensions.CustomResourceDefinitionVersion) bool {\n\tif len(versions) == 0 {\n\t\treturn false\n\t}\n\tvalue := versions[0].Schema\n\tfor _, v := range versions {\n\t\tif v.Schema == nil || !apiequality.Semantic.DeepEqual(v.Schema, value) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":551,"to":564}} {"id":100013979,"name":"hasIdenticalPerVersionSubresources","signature":"func hasIdenticalPerVersionSubresources(versions []apiextensions.CustomResourceDefinitionVersion) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// hasIdenticalPerVersionSubresources returns true if a CRD sets identical non-nil values\n// to all per-version subresources\nfunc hasIdenticalPerVersionSubresources(versions []apiextensions.CustomResourceDefinitionVersion) bool {\n\tif len(versions) == 0 {\n\t\treturn false\n\t}\n\tvalue := versions[0].Subresources\n\tfor _, v := range versions {\n\t\tif v.Subresources == nil || !apiequality.Semantic.DeepEqual(v.Subresources, value) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":566,"to":579}} {"id":100013980,"name":"hasIdenticalPerVersionColumns","signature":"func hasIdenticalPerVersionColumns(versions []apiextensions.CustomResourceDefinitionVersion) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// hasIdenticalPerVersionColumns returns true if a CRD sets identical non-nil values\n// to all per-version columns\nfunc hasIdenticalPerVersionColumns(versions []apiextensions.CustomResourceDefinitionVersion) bool {\n\tif len(versions) == 0 {\n\t\treturn false\n\t}\n\tvalue := versions[0].AdditionalPrinterColumns\n\tfor _, v := range versions {\n\t\tif len(v.AdditionalPrinterColumns) == 0 || !apiequality.Semantic.DeepEqual(v.AdditionalPrinterColumns, value) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":581,"to":594}} {"id":100013981,"name":"ValidateCustomResourceDefinitionStatus","signature":"func ValidateCustomResourceDefinitionStatus(status *apiextensions.CustomResourceDefinitionStatus, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// ValidateCustomResourceDefinitionStatus statically validates\nfunc ValidateCustomResourceDefinitionStatus(status *apiextensions.CustomResourceDefinitionStatus, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, ValidateCustomResourceDefinitionNames(\u0026status.AcceptedNames, fldPath.Child(\"acceptedNames\"))...)\n\treturn allErrs\n}","line":{"from":596,"to":601}} {"id":100013982,"name":"ValidateCustomResourceDefinitionNames","signature":"func ValidateCustomResourceDefinitionNames(names *apiextensions.CustomResourceDefinitionNames, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// ValidateCustomResourceDefinitionNames statically validates\nfunc ValidateCustomResourceDefinitionNames(names *apiextensions.CustomResourceDefinitionNames, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif errs := utilvalidation.IsDNS1035Label(names.Plural); len(names.Plural) \u003e 0 \u0026\u0026 len(errs) \u003e 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"plural\"), names.Plural, strings.Join(errs, \",\")))\n\t}\n\tif errs := utilvalidation.IsDNS1035Label(names.Singular); len(names.Singular) \u003e 0 \u0026\u0026 len(errs) \u003e 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"singular\"), names.Singular, strings.Join(errs, \",\")))\n\t}\n\tif errs := utilvalidation.IsDNS1035Label(strings.ToLower(names.Kind)); len(names.Kind) \u003e 0 \u0026\u0026 len(errs) \u003e 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"kind\"), names.Kind, \"may have mixed case, but should otherwise match: \"+strings.Join(errs, \",\")))\n\t}\n\tif errs := utilvalidation.IsDNS1035Label(strings.ToLower(names.ListKind)); len(names.ListKind) \u003e 0 \u0026\u0026 len(errs) \u003e 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"listKind\"), names.ListKind, \"may have mixed case, but should otherwise match: \"+strings.Join(errs, \",\")))\n\t}\n\n\tfor i, shortName := range names.ShortNames {\n\t\tif errs := utilvalidation.IsDNS1035Label(shortName); len(errs) \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"shortNames\").Index(i), shortName, strings.Join(errs, \",\")))\n\t\t}\n\t}\n\n\t// kind and listKind may not be the same or parsing become ambiguous\n\tif len(names.Kind) \u003e 0 \u0026\u0026 names.Kind == names.ListKind {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"listKind\"), names.ListKind, \"kind and listKind may not be the same\"))\n\t}\n\n\tfor i, category := range names.Categories {\n\t\tif errs := utilvalidation.IsDNS1035Label(category); len(errs) \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"categories\").Index(i), category, strings.Join(errs, \",\")))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":603,"to":637}} {"id":100013983,"name":"ValidateCustomResourceColumnDefinition","signature":"func ValidateCustomResourceColumnDefinition(col *apiextensions.CustomResourceColumnDefinition, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// ValidateCustomResourceColumnDefinition statically validates a printer column.\nfunc ValidateCustomResourceColumnDefinition(col *apiextensions.CustomResourceColumnDefinition, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(col.Name) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"name\"), \"\"))\n\t}\n\n\tif len(col.Type) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"type\"), fmt.Sprintf(\"must be one of %s\", strings.Join(printerColumnDatatypes.List(), \",\"))))\n\t} else if !printerColumnDatatypes.Has(col.Type) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"type\"), col.Type, fmt.Sprintf(\"must be one of %s\", strings.Join(printerColumnDatatypes.List(), \",\"))))\n\t}\n\n\tif len(col.Format) \u003e 0 \u0026\u0026 !customResourceColumnDefinitionFormats.Has(col.Format) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"format\"), col.Format, fmt.Sprintf(\"must be one of %s\", strings.Join(customResourceColumnDefinitionFormats.List(), \",\"))))\n\t}\n\n\tif len(col.JSONPath) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"JSONPath\"), \"\"))\n\t} else if errs := validateSimpleJSONPath(col.JSONPath, fldPath.Child(\"JSONPath\")); len(errs) \u003e 0 {\n\t\tallErrs = append(allErrs, errs...)\n\t}\n\n\treturn allErrs\n}","line":{"from":639,"to":664}} {"id":100013984,"name":"validateCustomResourceDefinitionValidation","signature":"func validateCustomResourceDefinitionValidation(ctx context.Context, customResourceValidation *apiextensions.CustomResourceValidation, statusSubresourceEnabled bool, opts validationOptions, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// validateCustomResourceDefinitionValidation statically validates\n// context is passed for supporting context cancellation during cel validation when validating defaults\nfunc validateCustomResourceDefinitionValidation(ctx context.Context, customResourceValidation *apiextensions.CustomResourceValidation, statusSubresourceEnabled bool, opts validationOptions, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif customResourceValidation == nil {\n\t\treturn allErrs\n\t}\n\n\tif schema := customResourceValidation.OpenAPIV3Schema; schema != nil {\n\t\t// if the status subresource is enabled, only certain fields are allowed inside the root schema.\n\t\t// these fields are chosen such that, if status is extracted as properties[\"status\"], it's validation is not lost.\n\t\tif statusSubresourceEnabled {\n\t\t\tv := reflect.ValueOf(schema).Elem()\n\t\t\tfor i := 0; i \u003c v.NumField(); i++ {\n\t\t\t\t// skip zero values\n\t\t\t\tif value := v.Field(i).Interface(); reflect.DeepEqual(value, reflect.Zero(reflect.TypeOf(value)).Interface()) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tfieldName := v.Type().Field(i).Name\n\n\t\t\t\t// only \"object\" type is valid at root of the schema since validation schema for status is extracted as properties[\"status\"]\n\t\t\t\tif fieldName == \"Type\" {\n\t\t\t\t\tif schema.Type != \"object\" {\n\t\t\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"openAPIV3Schema.type\"), schema.Type, fmt.Sprintf(`only \"object\" is allowed as the type at the root of the schema if the status subresource is enabled`)))\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif !allowedAtRootSchema(fieldName) {\n\t\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"openAPIV3Schema\"), *schema, fmt.Sprintf(`only %v fields are allowed at the root of the schema if the status subresource is enabled`, allowedFieldsAtRootSchema)))\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif schema.Nullable {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"openAPIV3Schema.nullable\"), fmt.Sprintf(`nullable cannot be true at the root`)))\n\t\t}\n\n\t\topenAPIV3Schema := \u0026specStandardValidatorV3{\n\t\t\tallowDefaults: opts.allowDefaults,\n\t\t\tdisallowDefaultsReason: opts.disallowDefaultsReason,\n\t\t\trequireValidPropertyType: opts.requireValidPropertyType,\n\t\t}\n\n\t\tvar celContext *CELSchemaContext\n\t\tvar structuralSchemaInitErrs field.ErrorList\n\t\tif opts.requireStructuralSchema {\n\t\t\tif ss, err := structuralschema.NewStructural(schema); err != nil {\n\t\t\t\t// These validation errors overlap with OpenAPISchema validation errors so we keep track of them\n\t\t\t\t// separately and only show them if OpenAPISchema validation does not report any errors.\n\t\t\t\tstructuralSchemaInitErrs = append(structuralSchemaInitErrs, field.Invalid(fldPath.Child(\"openAPIV3Schema\"), \"\", err.Error()))\n\t\t\t} else if validationErrors := structuralschema.ValidateStructural(fldPath.Child(\"openAPIV3Schema\"), ss); len(validationErrors) \u003e 0 {\n\t\t\t\tallErrs = append(allErrs, validationErrors...)\n\t\t\t} else if validationErrors, err := structuraldefaulting.ValidateDefaults(ctx, fldPath.Child(\"openAPIV3Schema\"), ss, true, opts.requirePrunedDefaults); err != nil {\n\t\t\t\t// this should never happen\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"openAPIV3Schema\"), \"\", err.Error()))\n\t\t\t} else if len(validationErrors) \u003e 0 {\n\t\t\t\tallErrs = append(allErrs, validationErrors...)\n\t\t\t} else {\n\t\t\t\t// Only initialize CEL rule validation context if the structural schemas are valid.\n\t\t\t\t// A nil CELSchemaContext indicates that no CEL validation should be attempted.\n\t\t\t\tcelContext = RootCELContext(schema)\n\t\t\t}\n\t\t}\n\t\tallErrs = append(allErrs, ValidateCustomResourceDefinitionOpenAPISchema(schema, fldPath.Child(\"openAPIV3Schema\"), openAPIV3Schema, true, \u0026opts, celContext).AllErrors()...)\n\n\t\tif len(allErrs) == 0 \u0026\u0026 len(structuralSchemaInitErrs) \u003e 0 {\n\t\t\t// Structural schema initialization errors overlap with OpenAPISchema validation errors so we only show them\n\t\t\t// if there are no OpenAPISchema validation errors.\n\t\t\tallErrs = append(allErrs, structuralSchemaInitErrs...)\n\t\t}\n\n\t\tif celContext != nil \u0026\u0026 celContext.TotalCost != nil {\n\t\t\tif celContext.TotalCost.Total \u003e StaticEstimatedCRDCostLimit {\n\t\t\t\tfor _, expensive := range celContext.TotalCost.MostExpensive {\n\t\t\t\t\tcostErrorMsg := fmt.Sprintf(\"contributed to estimated rule cost total exceeding cost limit for entire OpenAPIv3 schema\")\n\t\t\t\t\tallErrs = append(allErrs, field.Forbidden(expensive.Path, costErrorMsg))\n\t\t\t\t}\n\n\t\t\t\tcostErrorMsg := getCostErrorMessage(\"x-kubernetes-validations estimated rule cost total for entire OpenAPIv3 schema\", celContext.TotalCost.Total, StaticEstimatedCRDCostLimit)\n\t\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"openAPIV3Schema\"), costErrorMsg))\n\t\t\t}\n\t\t}\n\t}\n\n\t// if validation passed otherwise, make sure we can actually construct a schema validator from this custom resource validation.\n\tif len(allErrs) == 0 {\n\t\tif _, _, err := apiservervalidation.NewSchemaValidator(customResourceValidation); err != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, \"\", fmt.Sprintf(\"error building validator: %v\", err)))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":680,"to":776}} {"id":100013985,"name":"AppendErrors","signature":"func (o *OpenAPISchemaErrorList) AppendErrors(list *OpenAPISchemaErrorList)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// AppendErrors appends all errors in the provided list with the errors of this list.\nfunc (o *OpenAPISchemaErrorList) AppendErrors(list *OpenAPISchemaErrorList) {\n\tif o == nil || list == nil {\n\t\treturn\n\t}\n\to.SchemaErrors = append(o.SchemaErrors, list.SchemaErrors...)\n\to.CELErrors = append(o.CELErrors, list.CELErrors...)\n}","line":{"from":787,"to":794}} {"id":100013986,"name":"AllErrors","signature":"func (o *OpenAPISchemaErrorList) AllErrors() field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// AllErrors returns a list containing both schema and CEL errors.\nfunc (o *OpenAPISchemaErrorList) AllErrors() field.ErrorList {\n\tif o == nil {\n\t\treturn field.ErrorList{}\n\t}\n\treturn append(o.SchemaErrors, o.CELErrors...)\n}","line":{"from":796,"to":802}} {"id":100013987,"name":"ValidateCustomResourceDefinitionOpenAPISchema","signature":"func ValidateCustomResourceDefinitionOpenAPISchema(schema *apiextensions.JSONSchemaProps, fldPath *field.Path, ssv specStandardValidator, isRoot bool, opts *validationOptions, celContext *CELSchemaContext) *OpenAPISchemaErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// ValidateCustomResourceDefinitionOpenAPISchema statically validates\nfunc ValidateCustomResourceDefinitionOpenAPISchema(schema *apiextensions.JSONSchemaProps, fldPath *field.Path, ssv specStandardValidator, isRoot bool, opts *validationOptions, celContext *CELSchemaContext) *OpenAPISchemaErrorList {\n\tallErrs := \u0026OpenAPISchemaErrorList{SchemaErrors: field.ErrorList{}, CELErrors: field.ErrorList{}}\n\n\tif schema == nil {\n\t\treturn allErrs\n\t}\n\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, ssv.validate(schema, fldPath)...)\n\n\tif schema.UniqueItems == true {\n\t\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, field.Forbidden(fldPath.Child(\"uniqueItems\"), \"uniqueItems cannot be set to true since the runtime complexity becomes quadratic\"))\n\t}\n\n\t// additionalProperties and properties are mutual exclusive because otherwise they\n\t// contradict Kubernetes' API convention to ignore unknown fields.\n\t//\n\t// In other words:\n\t// - properties are for structs,\n\t// - additionalProperties are for map[string]interface{}\n\t//\n\t// Note: when patternProperties is added to OpenAPI some day, this will have to be\n\t// restricted like additionalProperties.\n\tif schema.AdditionalProperties != nil {\n\t\tif len(schema.Properties) != 0 {\n\t\t\tif schema.AdditionalProperties.Allows == false || schema.AdditionalProperties.Schema != nil {\n\t\t\t\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, field.Forbidden(fldPath.Child(\"additionalProperties\"), \"additionalProperties and properties are mutual exclusive\"))\n\t\t\t}\n\t\t}\n\t\t// Note: we forbid additionalProperties at resource root, both embedded and top-level.\n\t\t// But further inside, additionalProperites is possible, e.g. for labels or annotations.\n\t\tsubSsv := ssv\n\t\tif ssv.insideResourceMeta() {\n\t\t\t// we have to forbid defaults inside additionalProperties because pruning without actual value is ambiguous\n\t\t\tsubSsv = ssv.withForbiddenDefaults(\"inside additionalProperties applying to object metadata\")\n\t\t}\n\t\tallErrs.AppendErrors(ValidateCustomResourceDefinitionOpenAPISchema(schema.AdditionalProperties.Schema, fldPath.Child(\"additionalProperties\"), subSsv, false, opts, celContext.ChildAdditionalPropertiesContext(schema.AdditionalProperties.Schema)))\n\t}\n\n\tif len(schema.Properties) != 0 {\n\t\tfor property, jsonSchema := range schema.Properties {\n\t\t\tsubSsv := ssv\n\n\t\t\tif !cel.MapIsCorrelatable(schema.XMapType) {\n\t\t\t\tsubSsv = subSsv.withForbidOldSelfValidations(fldPath)\n\t\t\t}\n\n\t\t\tif (isRoot || schema.XEmbeddedResource) \u0026\u0026 metaFields.Has(property) {\n\t\t\t\t// we recurse into the schema that applies to ObjectMeta.\n\t\t\t\tsubSsv = subSsv.withInsideResourceMeta()\n\t\t\t\tif isRoot {\n\t\t\t\t\tsubSsv = subSsv.withForbiddenDefaults(fmt.Sprintf(\"in top-level %s\", property))\n\t\t\t\t}\n\t\t\t}\n\t\t\tpropertySchema := jsonSchema\n\t\t\tallErrs.AppendErrors(ValidateCustomResourceDefinitionOpenAPISchema(\u0026propertySchema, fldPath.Child(\"properties\").Key(property), subSsv, false, opts, celContext.ChildPropertyContext(\u0026propertySchema, property)))\n\t\t}\n\t}\n\n\tallErrs.AppendErrors(ValidateCustomResourceDefinitionOpenAPISchema(schema.Not, fldPath.Child(\"not\"), ssv, false, opts, nil))\n\n\tif len(schema.AllOf) != 0 {\n\t\tfor i, jsonSchema := range schema.AllOf {\n\t\t\tallOfSchema := jsonSchema\n\t\t\tallErrs.AppendErrors(ValidateCustomResourceDefinitionOpenAPISchema(\u0026allOfSchema, fldPath.Child(\"allOf\").Index(i), ssv, false, opts, nil))\n\t\t}\n\t}\n\n\tif len(schema.OneOf) != 0 {\n\t\tfor i, jsonSchema := range schema.OneOf {\n\t\t\toneOfSchema := jsonSchema\n\t\t\tallErrs.AppendErrors(ValidateCustomResourceDefinitionOpenAPISchema(\u0026oneOfSchema, fldPath.Child(\"oneOf\").Index(i), ssv, false, opts, nil))\n\t\t}\n\t}\n\n\tif len(schema.AnyOf) != 0 {\n\t\tfor i, jsonSchema := range schema.AnyOf {\n\t\t\tanyOfSchema := jsonSchema\n\t\t\tallErrs.AppendErrors(ValidateCustomResourceDefinitionOpenAPISchema(\u0026anyOfSchema, fldPath.Child(\"anyOf\").Index(i), ssv, false, opts, nil))\n\t\t}\n\t}\n\n\tif len(schema.Definitions) != 0 {\n\t\tfor definition, jsonSchema := range schema.Definitions {\n\t\t\tdefinitionSchema := jsonSchema\n\t\t\tallErrs.AppendErrors(ValidateCustomResourceDefinitionOpenAPISchema(\u0026definitionSchema, fldPath.Child(\"definitions\").Key(definition), ssv, false, opts, nil))\n\t\t}\n\t}\n\n\tif schema.Items != nil {\n\t\tsubSsv := ssv\n\n\t\t// we can only correlate old/new items for \"map\" and \"set\" lists, and correlation of\n\t\t// \"set\" elements by identity is not supported for cel (x-kubernetes-validations)\n\t\t// rules. an unset list type defaults to \"atomic\".\n\t\tif schema.XListType == nil || *schema.XListType != \"map\" {\n\t\t\tsubSsv = subSsv.withForbidOldSelfValidations(fldPath)\n\t\t}\n\n\t\tallErrs.AppendErrors(ValidateCustomResourceDefinitionOpenAPISchema(schema.Items.Schema, fldPath.Child(\"items\"), subSsv, false, opts, celContext.ChildItemsContext(schema.Items.Schema)))\n\t\tif len(schema.Items.JSONSchemas) != 0 {\n\t\t\tfor i, jsonSchema := range schema.Items.JSONSchemas {\n\t\t\t\titemsSchema := jsonSchema\n\t\t\t\tallErrs.AppendErrors(ValidateCustomResourceDefinitionOpenAPISchema(\u0026itemsSchema, fldPath.Child(\"items\").Index(i), subSsv, false, opts, celContext.ChildItemsContext(\u0026itemsSchema)))\n\t\t\t}\n\t\t}\n\t}\n\n\tif schema.Dependencies != nil {\n\t\tfor dependency, jsonSchemaPropsOrStringArray := range schema.Dependencies {\n\t\t\tallErrs.AppendErrors(ValidateCustomResourceDefinitionOpenAPISchema(jsonSchemaPropsOrStringArray.Schema, fldPath.Child(\"dependencies\").Key(dependency), ssv, false, opts, nil))\n\t\t}\n\t}\n\n\tif schema.XPreserveUnknownFields != nil \u0026\u0026 *schema.XPreserveUnknownFields == false {\n\t\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, field.Invalid(fldPath.Child(\"x-kubernetes-preserve-unknown-fields\"), *schema.XPreserveUnknownFields, \"must be true or undefined\"))\n\t}\n\n\tif schema.XMapType != nil \u0026\u0026 schema.Type != \"object\" {\n\t\tif len(schema.Type) == 0 {\n\t\t\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, field.Required(fldPath.Child(\"type\"), \"must be object if x-kubernetes-map-type is specified\"))\n\t\t} else {\n\t\t\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, field.Invalid(fldPath.Child(\"type\"), schema.Type, \"must be object if x-kubernetes-map-type is specified\"))\n\t\t}\n\t}\n\n\tif schema.XMapType != nil \u0026\u0026 *schema.XMapType != \"atomic\" \u0026\u0026 *schema.XMapType != \"granular\" {\n\t\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, field.NotSupported(fldPath.Child(\"x-kubernetes-map-type\"), *schema.XMapType, []string{\"atomic\", \"granular\"}))\n\t}\n\n\tif schema.XListType != nil \u0026\u0026 schema.Type != \"array\" {\n\t\tif len(schema.Type) == 0 {\n\t\t\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, field.Required(fldPath.Child(\"type\"), \"must be array if x-kubernetes-list-type is specified\"))\n\t\t} else {\n\t\t\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, field.Invalid(fldPath.Child(\"type\"), schema.Type, \"must be array if x-kubernetes-list-type is specified\"))\n\t\t}\n\t} else if opts.requireAtomicSetType \u0026\u0026 schema.XListType != nil \u0026\u0026 *schema.XListType == \"set\" \u0026\u0026 schema.Items != nil \u0026\u0026 schema.Items.Schema != nil { // by structural schema items are present\n\t\tis := schema.Items.Schema\n\t\tswitch is.Type {\n\t\tcase \"array\":\n\t\t\tif is.XListType != nil \u0026\u0026 *is.XListType != \"atomic\" { // atomic is the implicit default behaviour if unset, hence != atomic is wrong\n\t\t\t\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, field.Invalid(fldPath.Child(\"items\").Child(\"x-kubernetes-list-type\"), is.XListType, \"must be atomic as item of a list with x-kubernetes-list-type=set\"))\n\t\t\t}\n\t\tcase \"object\":\n\t\t\tif is.XMapType == nil || *is.XMapType != \"atomic\" { // granular is the implicit default behaviour if unset, hence nil and != atomic are wrong\n\t\t\t\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, field.Invalid(fldPath.Child(\"items\").Child(\"x-kubernetes-map-type\"), is.XListType, \"must be atomic as item of a list with x-kubernetes-list-type=set\"))\n\t\t\t}\n\t\t}\n\t}\n\n\tif schema.XListType != nil \u0026\u0026 *schema.XListType != \"atomic\" \u0026\u0026 *schema.XListType != \"set\" \u0026\u0026 *schema.XListType != \"map\" {\n\t\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, field.NotSupported(fldPath.Child(\"x-kubernetes-list-type\"), *schema.XListType, []string{\"atomic\", \"set\", \"map\"}))\n\t}\n\n\tif len(schema.XListMapKeys) \u003e 0 {\n\t\tif schema.XListType == nil {\n\t\t\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, field.Required(fldPath.Child(\"x-kubernetes-list-type\"), \"must be map if x-kubernetes-list-map-keys is non-empty\"))\n\t\t} else if *schema.XListType != \"map\" {\n\t\t\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, field.Invalid(fldPath.Child(\"x-kubernetes-list-type\"), *schema.XListType, \"must be map if x-kubernetes-list-map-keys is non-empty\"))\n\t\t}\n\t}\n\n\tif schema.XListType != nil \u0026\u0026 *schema.XListType == \"map\" {\n\t\tif len(schema.XListMapKeys) == 0 {\n\t\t\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, field.Required(fldPath.Child(\"x-kubernetes-list-map-keys\"), \"must not be empty if x-kubernetes-list-type is map\"))\n\t\t}\n\n\t\tif schema.Items == nil {\n\t\t\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, field.Required(fldPath.Child(\"items\"), \"must have a schema if x-kubernetes-list-type is map\"))\n\t\t}\n\n\t\tif schema.Items != nil \u0026\u0026 schema.Items.Schema == nil {\n\t\t\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, field.Invalid(fldPath.Child(\"items\"), schema.Items, \"must only have a single schema if x-kubernetes-list-type is map\"))\n\t\t}\n\n\t\tif schema.Items != nil \u0026\u0026 schema.Items.Schema != nil \u0026\u0026 schema.Items.Schema.Type != \"object\" {\n\t\t\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, field.Invalid(fldPath.Child(\"items\").Child(\"type\"), schema.Items.Schema.Type, \"must be object if parent array's x-kubernetes-list-type is map\"))\n\t\t}\n\n\t\tif schema.Items != nil \u0026\u0026 schema.Items.Schema != nil \u0026\u0026 schema.Items.Schema.Type == \"object\" {\n\t\t\tkeys := map[string]struct{}{}\n\t\t\tfor _, k := range schema.XListMapKeys {\n\t\t\t\tif s, ok := schema.Items.Schema.Properties[k]; ok {\n\t\t\t\t\tif s.Type == \"array\" || s.Type == \"object\" {\n\t\t\t\t\t\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, field.Invalid(fldPath.Child(\"items\").Child(\"properties\").Key(k).Child(\"type\"), schema.Items.Schema.Type, \"must be a scalar type if parent array's x-kubernetes-list-type is map\"))\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, field.Invalid(fldPath.Child(\"x-kubernetes-list-map-keys\"), schema.XListMapKeys, \"entries must all be names of item properties\"))\n\t\t\t\t}\n\t\t\t\tif _, ok := keys[k]; ok {\n\t\t\t\t\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, field.Invalid(fldPath.Child(\"x-kubernetes-list-map-keys\"), schema.XListMapKeys, \"must not contain duplicate entries\"))\n\t\t\t\t}\n\t\t\t\tkeys[k] = struct{}{}\n\t\t\t}\n\t\t}\n\t}\n\n\tif opts.requireMapListKeysMapSetValidation {\n\t\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, validateMapListKeysMapSet(schema, fldPath)...)\n\t}\n\n\tif len(schema.XValidations) \u003e 0 {\n\t\tfor i, rule := range schema.XValidations {\n\t\t\ttrimmedRule := strings.TrimSpace(rule.Rule)\n\t\t\ttrimmedMsg := strings.TrimSpace(rule.Message)\n\t\t\ttrimmedMsgExpr := strings.TrimSpace(rule.MessageExpression)\n\t\t\tif len(trimmedRule) == 0 {\n\t\t\t\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, field.Required(fldPath.Child(\"x-kubernetes-validations\").Index(i).Child(\"rule\"), \"rule is not specified\"))\n\t\t\t} else if len(rule.Message) \u003e 0 \u0026\u0026 len(trimmedMsg) == 0 {\n\t\t\t\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, field.Invalid(fldPath.Child(\"x-kubernetes-validations\").Index(i).Child(\"message\"), rule.Message, \"message must be non-empty if specified\"))\n\t\t\t} else if hasNewlines(trimmedMsg) {\n\t\t\t\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, field.Invalid(fldPath.Child(\"x-kubernetes-validations\").Index(i).Child(\"message\"), rule.Message, \"message must not contain line breaks\"))\n\t\t\t} else if hasNewlines(trimmedRule) \u0026\u0026 len(trimmedMsg) == 0 {\n\t\t\t\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, field.Required(fldPath.Child(\"x-kubernetes-validations\").Index(i).Child(\"message\"), \"message must be specified if rule contains line breaks\"))\n\t\t\t}\n\t\t\tif len(rule.MessageExpression) \u003e 0 \u0026\u0026 len(trimmedMsgExpr) == 0 {\n\t\t\t\tallErrs.SchemaErrors = append(allErrs.SchemaErrors, field.Required(fldPath.Child(\"x-kubernetes-validations\").Index(i).Child(\"messageExpression\"), \"messageExpression must be non-empty if specified\"))\n\t\t\t}\n\t\t}\n\n\t\t// If any schema related validation errors have been found at this level or deeper, skip CEL expression validation.\n\t\t// Invalid OpenAPISchemas are not always possible to convert into valid CEL DeclTypes, and can lead to CEL\n\t\t// validation error messages that are not actionable (will go away once the schema errors are resolved) and that\n\t\t// are difficult for CEL expression authors to understand.\n\t\tif len(allErrs.SchemaErrors) == 0 \u0026\u0026 celContext != nil {\n\t\t\ttypeInfo, err := celContext.TypeInfo()\n\t\t\tif err != nil {\n\t\t\t\tallErrs.CELErrors = append(allErrs.CELErrors, field.InternalError(fldPath.Child(\"x-kubernetes-validations\"), fmt.Errorf(\"internal error: failed to construct type information for x-kubernetes-validations rules: %s\", err)))\n\t\t\t} else if typeInfo == nil {\n\t\t\t\tallErrs.CELErrors = append(allErrs.CELErrors, field.InternalError(fldPath.Child(\"x-kubernetes-validations\"), fmt.Errorf(\"internal error: failed to retrieve type information for x-kubernetes-validations\")))\n\t\t\t} else {\n\t\t\t\tcompResults, err := cel.Compile(typeInfo.Schema, typeInfo.DeclType, celconfig.PerCallLimit)\n\t\t\t\tif err != nil {\n\t\t\t\t\tallErrs.CELErrors = append(allErrs.CELErrors, field.InternalError(fldPath.Child(\"x-kubernetes-validations\"), err))\n\t\t\t\t} else {\n\t\t\t\t\tfor i, cr := range compResults {\n\t\t\t\t\t\texpressionCost := getExpressionCost(cr, celContext)\n\t\t\t\t\t\tif expressionCost \u003e StaticEstimatedCostLimit {\n\t\t\t\t\t\t\tcostErrorMsg := getCostErrorMessage(\"estimated rule cost\", expressionCost, StaticEstimatedCostLimit)\n\t\t\t\t\t\t\tallErrs.CELErrors = append(allErrs.CELErrors, field.Forbidden(fldPath.Child(\"x-kubernetes-validations\").Index(i).Child(\"rule\"), costErrorMsg))\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif celContext.TotalCost != nil {\n\t\t\t\t\t\t\tcelContext.TotalCost.ObserveExpressionCost(fldPath.Child(\"x-kubernetes-validations\").Index(i).Child(\"rule\"), expressionCost)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif cr.Error != nil {\n\t\t\t\t\t\t\tif cr.Error.Type == apiservercel.ErrorTypeRequired {\n\t\t\t\t\t\t\t\tallErrs.CELErrors = append(allErrs.CELErrors, field.Required(fldPath.Child(\"x-kubernetes-validations\").Index(i).Child(\"rule\"), cr.Error.Detail))\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tallErrs.CELErrors = append(allErrs.CELErrors, field.Invalid(fldPath.Child(\"x-kubernetes-validations\").Index(i).Child(\"rule\"), schema.XValidations[i], cr.Error.Detail))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif cr.MessageExpressionError != nil {\n\t\t\t\t\t\t\tallErrs.CELErrors = append(allErrs.CELErrors, field.Invalid(fldPath.Child(\"x-kubernetes-validations\").Index(i).Child(\"messageExpression\"), schema.XValidations[i], cr.MessageExpressionError.Detail))\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif cr.MessageExpression != nil {\n\t\t\t\t\t\t\t\tif cr.MessageExpressionMaxCost \u003e StaticEstimatedCostLimit {\n\t\t\t\t\t\t\t\t\tcostErrorMsg := getCostErrorMessage(\"estimated messageExpression cost\", cr.MessageExpressionMaxCost, StaticEstimatedCostLimit)\n\t\t\t\t\t\t\t\t\tallErrs.CELErrors = append(allErrs.CELErrors, field.Forbidden(fldPath.Child(\"x-kubernetes-validations\").Index(i).Child(\"messageExpression\"), costErrorMsg))\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif celContext.TotalCost != nil {\n\t\t\t\t\t\t\t\t\tcelContext.TotalCost.ObserveExpressionCost(fldPath.Child(\"x-kubernetes-validations\").Index(i).Child(\"messageExpression\"), cr.MessageExpressionMaxCost)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif cr.TransitionRule {\n\t\t\t\t\t\t\tif uncorrelatablePath := ssv.forbidOldSelfValidations(); uncorrelatablePath != nil {\n\t\t\t\t\t\t\t\tallErrs.CELErrors = append(allErrs.CELErrors, field.Invalid(fldPath.Child(\"x-kubernetes-validations\").Index(i).Child(\"rule\"), schema.XValidations[i].Rule, fmt.Sprintf(\"oldSelf cannot be used on the uncorrelatable portion of the schema within %v\", uncorrelatablePath)))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":804,"to":1079}} {"id":100013988,"name":"multiplyWithOverflowGuard","signature":"func multiplyWithOverflowGuard(baseCost, cardinality uint64) uint64","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// multiplyWithOverflowGuard returns the product of baseCost and cardinality unless that product\n// would exceed math.MaxUint, in which case math.MaxUint is returned.\nfunc multiplyWithOverflowGuard(baseCost, cardinality uint64) uint64 {\n\tif baseCost == 0 {\n\t\t// an empty rule can return 0, so guard for that here\n\t\treturn 0\n\t} else if math.MaxUint/baseCost \u003c cardinality {\n\t\treturn math.MaxUint\n\t}\n\treturn baseCost * cardinality\n}","line":{"from":1081,"to":1091}} {"id":100013989,"name":"getExpressionCost","signature":"func getExpressionCost(cr cel.CompilationResult, cardinalityCost *CELSchemaContext) uint64","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func getExpressionCost(cr cel.CompilationResult, cardinalityCost *CELSchemaContext) uint64 {\n\tif cardinalityCost.MaxCardinality != unbounded {\n\t\treturn multiplyWithOverflowGuard(cr.MaxCost, *cardinalityCost.MaxCardinality)\n\t}\n\treturn multiplyWithOverflowGuard(cr.MaxCost, cr.MaxCardinality)\n}","line":{"from":1093,"to":1098}} {"id":100013990,"name":"getCostErrorMessage","signature":"func getCostErrorMessage(costName string, expressionCost, costLimit uint64) string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func getCostErrorMessage(costName string, expressionCost, costLimit uint64) string {\n\texceedFactor := float64(expressionCost) / float64(costLimit)\n\tvar factor string\n\tif exceedFactor \u003e 100.0 {\n\t\t// if exceedFactor is greater than 2 orders of magnitude, the rule is likely O(n^2) or worse\n\t\t// and will probably never validate without some set limits\n\t\t// also in such cases the cost estimation is generally large enough to not add any value\n\t\tfactor = fmt.Sprintf(\"more than 100x\")\n\t} else if exceedFactor \u003c 1.5 {\n\t\tfactor = fmt.Sprintf(\"%fx\", exceedFactor) // avoid reporting \"exceeds budge by a factor of 1.0x\"\n\t} else {\n\t\tfactor = fmt.Sprintf(\"%.1fx\", exceedFactor)\n\t}\n\treturn fmt.Sprintf(\"%s exceeds budget by factor of %s (try simplifying the rule, or adding maxItems, maxProperties, and maxLength where arrays, maps, and strings are declared)\", costName, factor)\n}","line":{"from":1100,"to":1114}} {"id":100013991,"name":"hasNewlines","signature":"func hasNewlines(s string) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func hasNewlines(s string) bool {\n\treturn newlineMatcher.MatchString(s)\n}","line":{"from":1117,"to":1119}} {"id":100013992,"name":"validateMapListKeysMapSet","signature":"func validateMapListKeysMapSet(schema *apiextensions.JSONSchemaProps, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func validateMapListKeysMapSet(schema *apiextensions.JSONSchemaProps, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif schema.Items == nil || schema.Items.Schema == nil {\n\t\treturn nil\n\t}\n\tif schema.XListType == nil {\n\t\treturn nil\n\t}\n\tif *schema.XListType != \"set\" \u0026\u0026 *schema.XListType != \"map\" {\n\t\treturn nil\n\t}\n\n\t// set and map list items cannot be nullable\n\tif schema.Items.Schema.Nullable {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"items\").Child(\"nullable\"), \"cannot be nullable when x-kubernetes-list-type is \"+*schema.XListType))\n\t}\n\n\tswitch *schema.XListType {\n\tcase \"map\":\n\t\t// ensure all map keys are required or have a default\n\t\tisRequired := make(map[string]bool, len(schema.Items.Schema.Required))\n\t\tfor _, required := range schema.Items.Schema.Required {\n\t\t\tisRequired[required] = true\n\t\t}\n\n\t\tfor _, k := range schema.XListMapKeys {\n\t\t\tobj, ok := schema.Items.Schema.Properties[k]\n\t\t\tif !ok {\n\t\t\t\t// we validate that all XListMapKeys are existing properties in ValidateCustomResourceDefinitionOpenAPISchema, so skipping here is ok\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif isRequired[k] == false \u0026\u0026 obj.Default == nil {\n\t\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"items\").Child(\"properties\").Key(k).Child(\"default\"), \"this property is in x-kubernetes-list-map-keys, so it must have a default or be a required property\"))\n\t\t\t}\n\n\t\t\tif obj.Nullable {\n\t\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"items\").Child(\"properties\").Key(k).Child(\"nullable\"), \"this property is in x-kubernetes-list-map-keys, so it cannot be nullable\"))\n\t\t\t}\n\t\t}\n\tcase \"set\":\n\t\t// no other set-specific validation\n\t}\n\n\treturn allErrs\n}","line":{"from":1121,"to":1167}} {"id":100013993,"name":"withForbiddenDefaults","signature":"func (v *specStandardValidatorV3) withForbiddenDefaults(reason string) specStandardValidator","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func (v *specStandardValidatorV3) withForbiddenDefaults(reason string) specStandardValidator {\n\tclone := *v\n\tclone.disallowDefaultsReason = reason\n\tclone.allowDefaults = false\n\treturn \u0026clone\n}","line":{"from":1177,"to":1182}} {"id":100013994,"name":"withInsideResourceMeta","signature":"func (v *specStandardValidatorV3) withInsideResourceMeta() specStandardValidator","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func (v *specStandardValidatorV3) withInsideResourceMeta() specStandardValidator {\n\tclone := *v\n\tclone.isInsideResourceMeta = true\n\treturn \u0026clone\n}","line":{"from":1184,"to":1188}} {"id":100013995,"name":"insideResourceMeta","signature":"func (v *specStandardValidatorV3) insideResourceMeta() bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func (v *specStandardValidatorV3) insideResourceMeta() bool {\n\treturn v.isInsideResourceMeta\n}","line":{"from":1190,"to":1192}} {"id":100013996,"name":"withForbidOldSelfValidations","signature":"func (v *specStandardValidatorV3) withForbidOldSelfValidations(path *field.Path) specStandardValidator","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func (v *specStandardValidatorV3) withForbidOldSelfValidations(path *field.Path) specStandardValidator {\n\tif v.uncorrelatableOldSelfValidationPath != nil {\n\t\t// oldSelf validations are already forbidden. preserve the highest-level path\n\t\t// causing oldSelf validations to be forbidden\n\t\treturn v\n\t}\n\tclone := *v\n\tclone.uncorrelatableOldSelfValidationPath = path\n\treturn \u0026clone\n}","line":{"from":1194,"to":1203}} {"id":100013997,"name":"forbidOldSelfValidations","signature":"func (v *specStandardValidatorV3) forbidOldSelfValidations() *field.Path","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func (v *specStandardValidatorV3) forbidOldSelfValidations() *field.Path {\n\treturn v.uncorrelatableOldSelfValidationPath\n}","line":{"from":1205,"to":1207}} {"id":100013998,"name":"validate","signature":"func (v *specStandardValidatorV3) validate(schema *apiextensions.JSONSchemaProps, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// validate validates against OpenAPI Schema v3.\nfunc (v *specStandardValidatorV3) validate(schema *apiextensions.JSONSchemaProps, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif schema == nil {\n\t\treturn allErrs\n\t}\n\n\t//\n\t// WARNING: if anything new is allowed below, NewStructural must be adapted to support it.\n\t//\n\n\tif v.requireValidPropertyType \u0026\u0026 len(schema.Type) \u003e 0 \u0026\u0026 !openapiV3Types.Has(schema.Type) {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"type\"), schema.Type, openapiV3Types.List()))\n\t}\n\n\tif schema.Default != nil \u0026\u0026 !v.allowDefaults {\n\t\tdetail := \"must not be set\"\n\t\tif len(v.disallowDefaultsReason) \u003e 0 {\n\t\t\tdetail += \" \" + v.disallowDefaultsReason\n\t\t}\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"default\"), detail))\n\t}\n\n\tif schema.ID != \"\" {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"id\"), \"id is not supported\"))\n\t}\n\n\tif schema.AdditionalItems != nil {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"additionalItems\"), \"additionalItems is not supported\"))\n\t}\n\n\tif len(schema.PatternProperties) != 0 {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"patternProperties\"), \"patternProperties is not supported\"))\n\t}\n\n\tif len(schema.Definitions) != 0 {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"definitions\"), \"definitions is not supported\"))\n\t}\n\n\tif schema.Dependencies != nil {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"dependencies\"), \"dependencies is not supported\"))\n\t}\n\n\tif schema.Ref != nil {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"$ref\"), \"$ref is not supported\"))\n\t}\n\n\tif schema.Type == \"null\" {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"type\"), \"type cannot be set to null, use nullable as an alternative\"))\n\t}\n\n\tif schema.Items != nil \u0026\u0026 len(schema.Items.JSONSchemas) != 0 {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"items\"), \"items must be a schema object and not an array\"))\n\t}\n\n\tif v.isInsideResourceMeta \u0026\u0026 schema.XEmbeddedResource {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"x-kubernetes-embedded-resource\"), \"must not be used inside of resource meta\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":1209,"to":1270}} {"id":100013999,"name":"ValidateCustomResourceDefinitionSubresources","signature":"func ValidateCustomResourceDefinitionSubresources(subresources *apiextensions.CustomResourceSubresources, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// ValidateCustomResourceDefinitionSubresources statically validates\nfunc ValidateCustomResourceDefinitionSubresources(subresources *apiextensions.CustomResourceSubresources, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif subresources == nil {\n\t\treturn allErrs\n\t}\n\n\tif subresources.Scale != nil {\n\t\tif len(subresources.Scale.SpecReplicasPath) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"scale.specReplicasPath\"), \"\"))\n\t\t} else {\n\t\t\t// should be constrained json path under .spec\n\t\t\tif errs := validateSimpleJSONPath(subresources.Scale.SpecReplicasPath, fldPath.Child(\"scale.specReplicasPath\")); len(errs) \u003e 0 {\n\t\t\t\tallErrs = append(allErrs, errs...)\n\t\t\t} else if !strings.HasPrefix(subresources.Scale.SpecReplicasPath, \".spec.\") {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"scale.specReplicasPath\"), subresources.Scale.SpecReplicasPath, \"should be a json path under .spec\"))\n\t\t\t}\n\t\t}\n\n\t\tif len(subresources.Scale.StatusReplicasPath) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"scale.statusReplicasPath\"), \"\"))\n\t\t} else {\n\t\t\t// should be constrained json path under .status\n\t\t\tif errs := validateSimpleJSONPath(subresources.Scale.StatusReplicasPath, fldPath.Child(\"scale.statusReplicasPath\")); len(errs) \u003e 0 {\n\t\t\t\tallErrs = append(allErrs, errs...)\n\t\t\t} else if !strings.HasPrefix(subresources.Scale.StatusReplicasPath, \".status.\") {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"scale.statusReplicasPath\"), subresources.Scale.StatusReplicasPath, \"should be a json path under .status\"))\n\t\t\t}\n\t\t}\n\n\t\t// if labelSelectorPath is present, it should be a constrained json path under .status\n\t\tif subresources.Scale.LabelSelectorPath != nil \u0026\u0026 len(*subresources.Scale.LabelSelectorPath) \u003e 0 {\n\t\t\tif errs := validateSimpleJSONPath(*subresources.Scale.LabelSelectorPath, fldPath.Child(\"scale.labelSelectorPath\")); len(errs) \u003e 0 {\n\t\t\t\tallErrs = append(allErrs, errs...)\n\t\t\t} else if !strings.HasPrefix(*subresources.Scale.LabelSelectorPath, \".spec.\") \u0026\u0026 !strings.HasPrefix(*subresources.Scale.LabelSelectorPath, \".status.\") {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"scale.labelSelectorPath\"), subresources.Scale.LabelSelectorPath, \"should be a json path under either .spec or .status\"))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":1272,"to":1314}} {"id":100014000,"name":"validateSimpleJSONPath","signature":"func validateSimpleJSONPath(s string, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func validateSimpleJSONPath(s string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tswitch {\n\tcase len(s) == 0:\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, s, \"must not be empty\"))\n\tcase s[0] != '.':\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, s, \"must be a simple json path starting with .\"))\n\tcase s != \".\":\n\t\tif cs := strings.Split(s[1:], \".\"); len(cs) \u003c 1 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, s, \"must be a json path in the dot notation\"))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":1316,"to":1331}} {"id":100014001,"name":"allowedAtRootSchema","signature":"func allowedAtRootSchema(field string) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func allowedAtRootSchema(field string) bool {\n\tfor _, v := range allowedFieldsAtRootSchema {\n\t\tif field == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":1335,"to":1342}} {"id":100014002,"name":"requireOpenAPISchema","signature":"func requireOpenAPISchema(oldCRDSpec *apiextensions.CustomResourceDefinitionSpec) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// requireOpenAPISchema returns true if the request group version requires a schema\nfunc requireOpenAPISchema(oldCRDSpec *apiextensions.CustomResourceDefinitionSpec) bool {\n\tif oldCRDSpec != nil \u0026\u0026 !allVersionsSpecifyOpenAPISchema(oldCRDSpec) {\n\t\t// don't tighten validation on existing persisted data\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":1344,"to":1351}} {"id":100014003,"name":"allVersionsSpecifyOpenAPISchema","signature":"func allVersionsSpecifyOpenAPISchema(spec *apiextensions.CustomResourceDefinitionSpec) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func allVersionsSpecifyOpenAPISchema(spec *apiextensions.CustomResourceDefinitionSpec) bool {\n\tif spec.Validation != nil \u0026\u0026 spec.Validation.OpenAPIV3Schema != nil {\n\t\treturn true\n\t}\n\tfor _, v := range spec.Versions {\n\t\tif v.Schema == nil || v.Schema.OpenAPIV3Schema == nil {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":1352,"to":1362}} {"id":100014004,"name":"specHasDefaults","signature":"func specHasDefaults(spec *apiextensions.CustomResourceDefinitionSpec) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func specHasDefaults(spec *apiextensions.CustomResourceDefinitionSpec) bool {\n\treturn HasSchemaWith(spec, schemaHasDefaults)\n}","line":{"from":1364,"to":1366}} {"id":100014005,"name":"schemaHasDefaults","signature":"func schemaHasDefaults(s *apiextensions.JSONSchemaProps) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func schemaHasDefaults(s *apiextensions.JSONSchemaProps) bool {\n\treturn SchemaHas(s, func(s *apiextensions.JSONSchemaProps) bool {\n\t\treturn s.Default != nil\n\t})\n}","line":{"from":1368,"to":1372}} {"id":100014006,"name":"HasSchemaWith","signature":"func HasSchemaWith(spec *apiextensions.CustomResourceDefinitionSpec, pred func(s *apiextensions.JSONSchemaProps) bool) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func HasSchemaWith(spec *apiextensions.CustomResourceDefinitionSpec, pred func(s *apiextensions.JSONSchemaProps) bool) bool {\n\tif spec.Validation != nil \u0026\u0026 spec.Validation.OpenAPIV3Schema != nil \u0026\u0026 pred(spec.Validation.OpenAPIV3Schema) {\n\t\treturn true\n\t}\n\tfor _, v := range spec.Versions {\n\t\tif v.Schema != nil \u0026\u0026 v.Schema.OpenAPIV3Schema != nil \u0026\u0026 pred(v.Schema.OpenAPIV3Schema) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":1374,"to":1384}} {"id":100014007,"name":"schemaHasRecurse","signature":"func schemaHasRecurse(s *apiextensions.JSONSchemaProps, pred func(s *apiextensions.JSONSchemaProps) bool) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func schemaHasRecurse(s *apiextensions.JSONSchemaProps, pred func(s *apiextensions.JSONSchemaProps) bool) bool {\n\tif s == nil {\n\t\treturn false\n\t}\n\tschema := schemaPool.Get().(*apiextensions.JSONSchemaProps)\n\tdefer schemaPool.Put(schema)\n\t*schema = *s\n\treturn SchemaHas(schema, pred)\n}","line":{"from":1392,"to":1400}} {"id":100014008,"name":"SchemaHas","signature":"func SchemaHas(s *apiextensions.JSONSchemaProps, pred func(s *apiextensions.JSONSchemaProps) bool) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// SchemaHas recursively traverses the Schema and calls the `pred`\n// predicate to see if the schema contains specific values.\n//\n// The predicate MUST NOT keep a copy of the json schema NOR modify the\n// schema.\nfunc SchemaHas(s *apiextensions.JSONSchemaProps, pred func(s *apiextensions.JSONSchemaProps) bool) bool {\n\tif s == nil {\n\t\treturn false\n\t}\n\n\tif pred(s) {\n\t\treturn true\n\t}\n\n\tif s.Items != nil {\n\t\tif s.Items != nil \u0026\u0026 schemaHasRecurse(s.Items.Schema, pred) {\n\t\t\treturn true\n\t\t}\n\t\tfor i := range s.Items.JSONSchemas {\n\t\t\tif schemaHasRecurse(\u0026s.Items.JSONSchemas[i], pred) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\tfor i := range s.AllOf {\n\t\tif schemaHasRecurse(\u0026s.AllOf[i], pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor i := range s.AnyOf {\n\t\tif schemaHasRecurse(\u0026s.AnyOf[i], pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor i := range s.OneOf {\n\t\tif schemaHasRecurse(\u0026s.OneOf[i], pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tif schemaHasRecurse(s.Not, pred) {\n\t\treturn true\n\t}\n\tfor _, s := range s.Properties {\n\t\tif schemaHasRecurse(\u0026s, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tif s.AdditionalProperties != nil {\n\t\tif schemaHasRecurse(s.AdditionalProperties.Schema, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor _, s := range s.PatternProperties {\n\t\tif schemaHasRecurse(\u0026s, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tif s.AdditionalItems != nil {\n\t\tif schemaHasRecurse(s.AdditionalItems.Schema, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor _, s := range s.Definitions {\n\t\tif schemaHasRecurse(\u0026s, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor _, d := range s.Dependencies {\n\t\tif schemaHasRecurse(d.Schema, pred) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":1402,"to":1476}} {"id":100014009,"name":"specHasKubernetesExtensions","signature":"func specHasKubernetesExtensions(spec *apiextensions.CustomResourceDefinitionSpec) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func specHasKubernetesExtensions(spec *apiextensions.CustomResourceDefinitionSpec) bool {\n\tif spec.Validation != nil \u0026\u0026 schemaHasKubernetesExtensions(spec.Validation.OpenAPIV3Schema) {\n\t\treturn true\n\t}\n\tfor _, v := range spec.Versions {\n\t\tif v.Schema != nil \u0026\u0026 schemaHasKubernetesExtensions(v.Schema.OpenAPIV3Schema) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":1478,"to":1488}} {"id":100014010,"name":"schemaHasKubernetesExtensions","signature":"func schemaHasKubernetesExtensions(s *apiextensions.JSONSchemaProps) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func schemaHasKubernetesExtensions(s *apiextensions.JSONSchemaProps) bool {\n\treturn SchemaHas(s, func(s *apiextensions.JSONSchemaProps) bool {\n\t\treturn s.XEmbeddedResource || s.XPreserveUnknownFields != nil || s.XIntOrString || len(s.XListMapKeys) \u003e 0 || s.XListType != nil || len(s.XValidations) \u003e 0\n\t})\n}","line":{"from":1490,"to":1494}} {"id":100014011,"name":"requireStructuralSchema","signature":"func requireStructuralSchema(oldCRDSpec *apiextensions.CustomResourceDefinitionSpec) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// requireStructuralSchema returns true if schemas specified must be structural\nfunc requireStructuralSchema(oldCRDSpec *apiextensions.CustomResourceDefinitionSpec) bool {\n\tif oldCRDSpec != nil \u0026\u0026 specHasNonStructuralSchema(oldCRDSpec) {\n\t\t// don't tighten validation on existing persisted data\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":1496,"to":1503}} {"id":100014012,"name":"specHasNonStructuralSchema","signature":"func specHasNonStructuralSchema(spec *apiextensions.CustomResourceDefinitionSpec) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func specHasNonStructuralSchema(spec *apiextensions.CustomResourceDefinitionSpec) bool {\n\tif spec.Validation != nil \u0026\u0026 schemaIsNonStructural(spec.Validation.OpenAPIV3Schema) {\n\t\treturn true\n\t}\n\tfor _, v := range spec.Versions {\n\t\tif v.Schema != nil \u0026\u0026 schemaIsNonStructural(v.Schema.OpenAPIV3Schema) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":1505,"to":1515}} {"id":100014013,"name":"schemaIsNonStructural","signature":"func schemaIsNonStructural(schema *apiextensions.JSONSchemaProps) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func schemaIsNonStructural(schema *apiextensions.JSONSchemaProps) bool {\n\tif schema == nil {\n\t\treturn false\n\t}\n\tss, err := structuralschema.NewStructural(schema)\n\tif err != nil {\n\t\treturn true\n\t}\n\treturn len(structuralschema.ValidateStructural(nil, ss)) \u003e 0\n}","line":{"from":1516,"to":1525}} {"id":100014014,"name":"requirePrunedDefaults","signature":"func requirePrunedDefaults(oldCRDSpec *apiextensions.CustomResourceDefinitionSpec) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// requirePrunedDefaults returns false if there are any unpruned default in oldCRDSpec, and true otherwise.\nfunc requirePrunedDefaults(oldCRDSpec *apiextensions.CustomResourceDefinitionSpec) bool {\n\tif oldCRDSpec.Validation != nil {\n\t\tif has, err := schemaHasUnprunedDefaults(oldCRDSpec.Validation.OpenAPIV3Schema); err == nil \u0026\u0026 has {\n\t\t\treturn false\n\t\t}\n\t}\n\tfor _, v := range oldCRDSpec.Versions {\n\t\tif v.Schema == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif has, err := schemaHasUnprunedDefaults(v.Schema.OpenAPIV3Schema); err == nil \u0026\u0026 has {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":1527,"to":1543}} {"id":100014015,"name":"schemaHasUnprunedDefaults","signature":"func schemaHasUnprunedDefaults(schema *apiextensions.JSONSchemaProps) (bool, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func schemaHasUnprunedDefaults(schema *apiextensions.JSONSchemaProps) (bool, error) {\n\tif schema == nil || !schemaHasDefaults(schema) {\n\t\treturn false, nil\n\t}\n\tss, err := structuralschema.NewStructural(schema)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif errs := structuralschema.ValidateStructural(nil, ss); len(errs) \u003e 0 {\n\t\treturn false, errs.ToAggregate()\n\t}\n\tpruned := ss.DeepCopy()\n\tif err := structuraldefaulting.PruneDefaults(pruned); err != nil {\n\t\treturn false, err\n\t}\n\treturn !reflect.DeepEqual(ss, pruned), nil\n}","line":{"from":1544,"to":1560}} {"id":100014016,"name":"requireAtomicSetType","signature":"func requireAtomicSetType(oldCRDSpec *apiextensions.CustomResourceDefinitionSpec) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// requireAtomicSetType returns true if the old CRD spec as at least one x-kubernetes-list-type=set with non-atomic items type.\nfunc requireAtomicSetType(oldCRDSpec *apiextensions.CustomResourceDefinitionSpec) bool {\n\treturn !HasSchemaWith(oldCRDSpec, hasNonAtomicSetType)\n}","line":{"from":1562,"to":1565}} {"id":100014017,"name":"hasNonAtomicSetType","signature":"func hasNonAtomicSetType(schema *apiextensions.JSONSchemaProps) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// hasNonAtomicSetType recurses over the schema and returns whether any list of type \"set\" as non-atomic item types.\nfunc hasNonAtomicSetType(schema *apiextensions.JSONSchemaProps) bool {\n\treturn SchemaHas(schema, func(schema *apiextensions.JSONSchemaProps) bool {\n\t\tif schema.XListType != nil \u0026\u0026 *schema.XListType == \"set\" \u0026\u0026 schema.Items != nil \u0026\u0026 schema.Items.Schema != nil { // we don't support schema.Items.JSONSchemas\n\t\t\tis := schema.Items.Schema\n\t\t\tswitch is.Type {\n\t\t\tcase \"array\":\n\t\t\t\treturn is.XListType != nil \u0026\u0026 *is.XListType != \"atomic\" // atomic is the implicit default behaviour if unset, hence != atomic is wrong\n\t\t\tcase \"object\":\n\t\t\t\treturn is.XMapType == nil || *is.XMapType != \"atomic\" // granular is the implicit default behaviour if unset, hence nil and != atomic are wrong\n\t\t\tdefault:\n\t\t\t\treturn false // scalar types are always atomic\n\t\t\t}\n\t\t}\n\t\treturn false\n\t})\n}","line":{"from":1567,"to":1583}} {"id":100014018,"name":"requireMapListKeysMapSetValidation","signature":"func requireMapListKeysMapSetValidation(oldCRDSpec *apiextensions.CustomResourceDefinitionSpec) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func requireMapListKeysMapSetValidation(oldCRDSpec *apiextensions.CustomResourceDefinitionSpec) bool {\n\treturn !HasSchemaWith(oldCRDSpec, hasInvalidMapListKeysMapSet)\n}","line":{"from":1585,"to":1587}} {"id":100014019,"name":"hasInvalidMapListKeysMapSet","signature":"func hasInvalidMapListKeysMapSet(schema *apiextensions.JSONSchemaProps) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func hasInvalidMapListKeysMapSet(schema *apiextensions.JSONSchemaProps) bool {\n\treturn SchemaHas(schema, func(schema *apiextensions.JSONSchemaProps) bool {\n\t\treturn len(validateMapListKeysMapSet(schema, field.NewPath(\"\"))) \u003e 0\n\t})\n}","line":{"from":1589,"to":1593}} {"id":100014020,"name":"requireValidPropertyType","signature":"func requireValidPropertyType(oldCRDSpec *apiextensions.CustomResourceDefinitionSpec) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// requireValidPropertyType returns true if valid openapi v3 types should be required for the given API version\nfunc requireValidPropertyType(oldCRDSpec *apiextensions.CustomResourceDefinitionSpec) bool {\n\tif oldCRDSpec != nil \u0026\u0026 specHasInvalidTypes(oldCRDSpec) {\n\t\t// don't tighten validation on existing persisted data\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":1595,"to":1602}} {"id":100014021,"name":"validateAPIApproval","signature":"func validateAPIApproval(newCRD, oldCRD *apiextensions.CustomResourceDefinition) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// validateAPIApproval returns a list of errors if the API approval annotation isn't valid\nfunc validateAPIApproval(newCRD, oldCRD *apiextensions.CustomResourceDefinition) field.ErrorList {\n\t// check to see if we need confirm API approval for kube group.\n\tif !apihelpers.IsProtectedCommunityGroup(newCRD.Spec.Group) {\n\t\t// no-op for non-protected groups\n\t\treturn nil\n\t}\n\n\t// default to a state that allows missing values to continue to be missing\n\tvar oldApprovalState *apihelpers.APIApprovalState\n\tif oldCRD != nil {\n\t\tt, _ := apihelpers.GetAPIApprovalState(oldCRD.Annotations)\n\t\toldApprovalState = \u0026t // +k8s:verify-mutation:reason=clone\n\t}\n\tnewApprovalState, reason := apihelpers.GetAPIApprovalState(newCRD.Annotations)\n\n\t// if the approval state hasn't changed, never fail on approval validation\n\t// this is allowed so that a v1 client that is simply updating spec and not mutating this value doesn't get rejected. Imagine a controller controlling a CRD spec.\n\tif oldApprovalState != nil \u0026\u0026 *oldApprovalState == newApprovalState {\n\t\treturn nil\n\t}\n\n\t// in v1, we require valid approval strings\n\tswitch newApprovalState {\n\tcase apihelpers.APIApprovalInvalid:\n\t\treturn field.ErrorList{field.Invalid(field.NewPath(\"metadata\", \"annotations\").Key(apiextensionsv1beta1.KubeAPIApprovedAnnotation), newCRD.Annotations[apiextensionsv1beta1.KubeAPIApprovedAnnotation], reason)}\n\tcase apihelpers.APIApprovalMissing:\n\t\treturn field.ErrorList{field.Required(field.NewPath(\"metadata\", \"annotations\").Key(apiextensionsv1beta1.KubeAPIApprovedAnnotation), reason)}\n\tcase apihelpers.APIApproved, apihelpers.APIApprovalBypassed:\n\t\t// success\n\t\treturn nil\n\tdefault:\n\t\treturn field.ErrorList{field.Invalid(field.NewPath(\"metadata\", \"annotations\").Key(apiextensionsv1beta1.KubeAPIApprovedAnnotation), newCRD.Annotations[apiextensionsv1beta1.KubeAPIApprovedAnnotation], reason)}\n\t}\n}","line":{"from":1604,"to":1638}} {"id":100014022,"name":"validatePreserveUnknownFields","signature":"func validatePreserveUnknownFields(crd, oldCRD *apiextensions.CustomResourceDefinition) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func validatePreserveUnknownFields(crd, oldCRD *apiextensions.CustomResourceDefinition) field.ErrorList {\n\tif oldCRD != nil \u0026\u0026 oldCRD.Spec.PreserveUnknownFields != nil \u0026\u0026 *oldCRD.Spec.PreserveUnknownFields {\n\t\t// no-op for compatibility with existing data\n\t\treturn nil\n\t}\n\n\tvar errs field.ErrorList\n\tif crd != nil \u0026\u0026 crd.Spec.PreserveUnknownFields != nil \u0026\u0026 *crd.Spec.PreserveUnknownFields {\n\t\t// disallow changing spec.preserveUnknownFields=false to spec.preserveUnknownFields=true\n\t\terrs = append(errs, field.Invalid(field.NewPath(\"spec\").Child(\"preserveUnknownFields\"), crd.Spec.PreserveUnknownFields, \"cannot set to true, set x-kubernetes-preserve-unknown-fields to true in spec.versions[*].schema instead\"))\n\t}\n\treturn errs\n}","line":{"from":1640,"to":1652}} {"id":100014023,"name":"specHasInvalidTypes","signature":"func specHasInvalidTypes(spec *apiextensions.CustomResourceDefinitionSpec) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"func specHasInvalidTypes(spec *apiextensions.CustomResourceDefinitionSpec) bool {\n\tif spec.Validation != nil \u0026\u0026 SchemaHasInvalidTypes(spec.Validation.OpenAPIV3Schema) {\n\t\treturn true\n\t}\n\tfor _, v := range spec.Versions {\n\t\tif v.Schema != nil \u0026\u0026 SchemaHasInvalidTypes(v.Schema.OpenAPIV3Schema) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":1654,"to":1664}} {"id":100014024,"name":"SchemaHasInvalidTypes","signature":"func SchemaHasInvalidTypes(s *apiextensions.JSONSchemaProps) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation/validation.go","code":"// SchemaHasInvalidTypes returns true if it contains invalid offending openapi-v3 specification.\nfunc SchemaHasInvalidTypes(s *apiextensions.JSONSchemaProps) bool {\n\treturn SchemaHas(s, func(s *apiextensions.JSONSchemaProps) bool {\n\t\treturn len(s.Type) \u003e 0 \u0026\u0026 !openapiV3Types.Has(s.Type)\n\t})\n}","line":{"from":1666,"to":1671}} {"id":100014025,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/apiserver.go","code":"func init() {\n\tinstall.Install(Scheme)\n\n\t// we need to add the options to empty v1\n\tmetav1.AddToGroupVersion(Scheme, schema.GroupVersion{Group: \"\", Version: \"v1\"})\n\n\tScheme.AddUnversionedTypes(unversionedVersion, unversionedTypes...)\n}","line":{"from":71,"to":78}} {"id":100014026,"name":"Complete","signature":"func (cfg *Config) Complete() CompletedConfig","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/apiserver.go","code":"// Complete fills in any fields not set that are required to have valid data. It's mutating the receiver.\nfunc (cfg *Config) Complete() CompletedConfig {\n\tc := completedConfig{\n\t\tcfg.GenericConfig.Complete(),\n\t\t\u0026cfg.ExtraConfig,\n\t}\n\n\tc.GenericConfig.EnableDiscovery = false\n\tif c.GenericConfig.Version == nil {\n\t\tc.GenericConfig.Version = \u0026version.Info{\n\t\t\tMajor: \"0\",\n\t\t\tMinor: \"1\",\n\t\t}\n\t}\n\n\treturn CompletedConfig{\u0026c}\n}","line":{"from":115,"to":131}} {"id":100014027,"name":"New","signature":"func (c completedConfig) New(delegationTarget genericapiserver.DelegationTarget) (*CustomResourceDefinitions, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/apiserver.go","code":"// New returns a new instance of CustomResourceDefinitions from the given config.\nfunc (c completedConfig) New(delegationTarget genericapiserver.DelegationTarget) (*CustomResourceDefinitions, error) {\n\tgenericServer, err := c.GenericConfig.New(\"apiextensions-apiserver\", delegationTarget)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// hasCRDInformerSyncedSignal is closed when the CRD informer this server uses has been fully synchronized.\n\t// It ensures that requests to potential custom resource endpoints while the server hasn't installed all known HTTP paths get a 503 error instead of a 404\n\thasCRDInformerSyncedSignal := make(chan struct{})\n\tif err := genericServer.RegisterMuxAndDiscoveryCompleteSignal(\"CRDInformerHasNotSynced\", hasCRDInformerSyncedSignal); err != nil {\n\t\treturn nil, err\n\t}\n\n\ts := \u0026CustomResourceDefinitions{\n\t\tGenericAPIServer: genericServer,\n\t}\n\n\tapiResourceConfig := c.GenericConfig.MergedResourceConfig\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(apiextensions.GroupName, Scheme, metav1.ParameterCodec, Codecs)\n\tstorage := map[string]rest.Storage{}\n\t// customresourcedefinitions\n\tif resource := \"customresourcedefinitions\"; apiResourceConfig.ResourceEnabled(v1.SchemeGroupVersion.WithResource(resource)) {\n\t\tcustomResourceDefinitionStorage, err := customresourcedefinition.NewREST(Scheme, c.GenericConfig.RESTOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstorage[resource] = customResourceDefinitionStorage\n\t\tstorage[resource+\"/status\"] = customresourcedefinition.NewStatusREST(Scheme, customResourceDefinitionStorage)\n\t}\n\tif len(storage) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[v1.SchemeGroupVersion.Version] = storage\n\t}\n\n\tif err := s.GenericAPIServer.InstallAPIGroup(\u0026apiGroupInfo); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcrdClient, err := clientset.NewForConfig(s.GenericAPIServer.LoopbackClientConfig)\n\tif err != nil {\n\t\t// it's really bad that this is leaking here, but until we can fix the test (which I'm pretty sure isn't even testing what it wants to test),\n\t\t// we need to be able to move forward\n\t\treturn nil, fmt.Errorf(\"failed to create clientset: %v\", err)\n\t}\n\ts.Informers = externalinformers.NewSharedInformerFactory(crdClient, 5*time.Minute)\n\n\tdelegateHandler := delegationTarget.UnprotectedHandler()\n\tif delegateHandler == nil {\n\t\tdelegateHandler = http.NotFoundHandler()\n\t}\n\n\tversionDiscoveryHandler := \u0026versionDiscoveryHandler{\n\t\tdiscovery: map[schema.GroupVersion]*discovery.APIVersionHandler{},\n\t\tdelegate: delegateHandler,\n\t}\n\tgroupDiscoveryHandler := \u0026groupDiscoveryHandler{\n\t\tdiscovery: map[string]*discovery.APIGroupHandler{},\n\t\tdelegate: delegateHandler,\n\t}\n\testablishingController := establish.NewEstablishingController(s.Informers.Apiextensions().V1().CustomResourceDefinitions(), crdClient.ApiextensionsV1())\n\tcrdHandler, err := NewCustomResourceDefinitionHandler(\n\t\tversionDiscoveryHandler,\n\t\tgroupDiscoveryHandler,\n\t\ts.Informers.Apiextensions().V1().CustomResourceDefinitions(),\n\t\tdelegateHandler,\n\t\tc.ExtraConfig.CRDRESTOptionsGetter,\n\t\tc.GenericConfig.AdmissionControl,\n\t\testablishingController,\n\t\tc.ExtraConfig.ServiceResolver,\n\t\tc.ExtraConfig.AuthResolverWrapper,\n\t\tc.ExtraConfig.MasterCount,\n\t\ts.GenericAPIServer.Authorizer,\n\t\tc.GenericConfig.RequestTimeout,\n\t\ttime.Duration(c.GenericConfig.MinRequestTimeout)*time.Second,\n\t\tapiGroupInfo.StaticOpenAPISpec,\n\t\tc.GenericConfig.MaxRequestBodyBytes,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.GenericAPIServer.Handler.NonGoRestfulMux.Handle(\"/apis\", crdHandler)\n\ts.GenericAPIServer.Handler.NonGoRestfulMux.HandlePrefix(\"/apis/\", crdHandler)\n\ts.GenericAPIServer.RegisterDestroyFunc(crdHandler.destroy)\n\n\taggregatedDiscoveryManager := genericServer.AggregatedDiscoveryGroupManager\n\tif aggregatedDiscoveryManager != nil {\n\t\taggregatedDiscoveryManager = aggregatedDiscoveryManager.WithSource(aggregated.CRDSource)\n\t}\n\tdiscoveryController := NewDiscoveryController(s.Informers.Apiextensions().V1().CustomResourceDefinitions(), versionDiscoveryHandler, groupDiscoveryHandler, aggregatedDiscoveryManager)\n\tnamingController := status.NewNamingConditionController(s.Informers.Apiextensions().V1().CustomResourceDefinitions(), crdClient.ApiextensionsV1())\n\tnonStructuralSchemaController := nonstructuralschema.NewConditionController(s.Informers.Apiextensions().V1().CustomResourceDefinitions(), crdClient.ApiextensionsV1())\n\tapiApprovalController := apiapproval.NewKubernetesAPIApprovalPolicyConformantConditionController(s.Informers.Apiextensions().V1().CustomResourceDefinitions(), crdClient.ApiextensionsV1())\n\tfinalizingController := finalizer.NewCRDFinalizer(\n\t\ts.Informers.Apiextensions().V1().CustomResourceDefinitions(),\n\t\tcrdClient.ApiextensionsV1(),\n\t\tcrdHandler,\n\t)\n\n\ts.GenericAPIServer.AddPostStartHookOrDie(\"start-apiextensions-informers\", func(context genericapiserver.PostStartHookContext) error {\n\t\ts.Informers.Start(context.StopCh)\n\t\treturn nil\n\t})\n\ts.GenericAPIServer.AddPostStartHookOrDie(\"start-apiextensions-controllers\", func(context genericapiserver.PostStartHookContext) error {\n\t\t// OpenAPIVersionedService and StaticOpenAPISpec are populated in generic apiserver PrepareRun().\n\t\t// Together they serve the /openapi/v2 endpoint on a generic apiserver. A generic apiserver may\n\t\t// choose to not enable OpenAPI by having null openAPIConfig, and thus OpenAPIVersionedService\n\t\t// and StaticOpenAPISpec are both null. In that case we don't run the CRD OpenAPI controller.\n\t\tif s.GenericAPIServer.StaticOpenAPISpec != nil {\n\t\t\tif s.GenericAPIServer.OpenAPIVersionedService != nil {\n\t\t\t\topenapiController := openapicontroller.NewController(s.Informers.Apiextensions().V1().CustomResourceDefinitions())\n\t\t\t\tgo openapiController.Run(s.GenericAPIServer.StaticOpenAPISpec, s.GenericAPIServer.OpenAPIVersionedService, context.StopCh)\n\t\t\t}\n\n\t\t\tif s.GenericAPIServer.OpenAPIV3VersionedService != nil \u0026\u0026 utilfeature.DefaultFeatureGate.Enabled(features.OpenAPIV3) {\n\t\t\t\topenapiv3Controller := openapiv3controller.NewController(s.Informers.Apiextensions().V1().CustomResourceDefinitions())\n\t\t\t\tgo openapiv3Controller.Run(s.GenericAPIServer.OpenAPIV3VersionedService, context.StopCh)\n\t\t\t}\n\t\t}\n\n\t\tgo namingController.Run(context.StopCh)\n\t\tgo establishingController.Run(context.StopCh)\n\t\tgo nonStructuralSchemaController.Run(5, context.StopCh)\n\t\tgo apiApprovalController.Run(5, context.StopCh)\n\t\tgo finalizingController.Run(5, context.StopCh)\n\n\t\tdiscoverySyncedCh := make(chan struct{})\n\t\tgo discoveryController.Run(context.StopCh, discoverySyncedCh)\n\t\tselect {\n\t\tcase \u003c-context.StopCh:\n\t\tcase \u003c-discoverySyncedCh:\n\t\t}\n\n\t\treturn nil\n\t})\n\t// we don't want to report healthy until we can handle all CRDs that have already been registered. Waiting for the informer\n\t// to sync makes sure that the lister will be valid before we begin. There may still be races for CRDs added after startup,\n\t// but we won't go healthy until we can handle the ones already present.\n\ts.GenericAPIServer.AddPostStartHookOrDie(\"crd-informer-synced\", func(context genericapiserver.PostStartHookContext) error {\n\t\treturn wait.PollImmediateUntil(100*time.Millisecond, func() (bool, error) {\n\t\t\tif s.Informers.Apiextensions().V1().CustomResourceDefinitions().Informer().HasSynced() {\n\t\t\t\tclose(hasCRDInformerSyncedSignal)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\treturn false, nil\n\t\t}, context.StopCh)\n\t})\n\n\treturn s, nil\n}","line":{"from":133,"to":281}} {"id":100014028,"name":"DefaultAPIResourceConfigSource","signature":"func DefaultAPIResourceConfigSource() *serverstorage.ResourceConfig","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/apiserver.go","code":"func DefaultAPIResourceConfigSource() *serverstorage.ResourceConfig {\n\tret := serverstorage.NewResourceConfig()\n\t// NOTE: GroupVersions listed here will be enabled by default. Don't put alpha versions in the list.\n\tret.EnableVersions(\n\t\tv1beta1.SchemeGroupVersion,\n\t\tv1.SchemeGroupVersion,\n\t)\n\n\treturn ret\n}","line":{"from":283,"to":292}} {"id":100014029,"name":"NewCRConverterFactory","signature":"func NewCRConverterFactory(serviceResolver webhook.ServiceResolver, authResolverWrapper webhook.AuthenticationInfoResolverWrapper) (*CRConverterFactory, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/conversion/converter.go","code":"// NewCRConverterFactory creates a new CRConverterFactory\nfunc NewCRConverterFactory(serviceResolver webhook.ServiceResolver, authResolverWrapper webhook.AuthenticationInfoResolverWrapper) (*CRConverterFactory, error) {\n\tconverterFactory := \u0026CRConverterFactory{}\n\twebhookConverterFactory, err := newWebhookConverterFactory(serviceResolver, authResolverWrapper)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconverterFactory.webhookConverterFactory = webhookConverterFactory\n\treturn converterFactory, nil\n}","line":{"from":42,"to":51}} {"id":100014030,"name":"NewConverter","signature":"func (m *CRConverterFactory) NewConverter(crd *apiextensionsv1.CustomResourceDefinition) (safe, unsafe runtime.ObjectConvertor, err error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/conversion/converter.go","code":"// NewConverter returns a new CR converter based on the conversion settings in crd object.\nfunc (m *CRConverterFactory) NewConverter(crd *apiextensionsv1.CustomResourceDefinition) (safe, unsafe runtime.ObjectConvertor, err error) {\n\tvalidVersions := map[schema.GroupVersion]bool{}\n\tfor _, version := range crd.Spec.Versions {\n\t\tvalidVersions[schema.GroupVersion{Group: crd.Spec.Group, Version: version.Name}] = true\n\t}\n\n\tvar converter crConverterInterface\n\tswitch crd.Spec.Conversion.Strategy {\n\tcase apiextensionsv1.NoneConverter:\n\t\tconverter = \u0026nopConverter{}\n\tcase apiextensionsv1.WebhookConverter:\n\t\tconverter, err = m.webhookConverterFactory.NewWebhookConverter(crd)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tconverter, err = converterMetricFactorySingleton.addMetrics(crd.Name, converter)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\tdefault:\n\t\treturn nil, nil, fmt.Errorf(\"unknown conversion strategy %q for CRD %s\", crd.Spec.Conversion.Strategy, crd.Name)\n\t}\n\n\t// Determine whether we should expect to be asked to \"convert\" autoscaling/v1 Scale types\n\tconvertScale := false\n\tfor _, version := range crd.Spec.Versions {\n\t\tif version.Subresources != nil \u0026\u0026 version.Subresources.Scale != nil {\n\t\t\tconvertScale = true\n\t\t}\n\t}\n\n\tunsafe = \u0026crConverter{\n\t\tconvertScale: convertScale,\n\t\tvalidVersions: validVersions,\n\t\tclusterScoped: crd.Spec.Scope == apiextensionsv1.ClusterScoped,\n\t\tconverter: converter,\n\t}\n\treturn \u0026safeConverterWrapper{unsafe}, unsafe, nil\n}","line":{"from":53,"to":92}} {"id":100014031,"name":"ConvertFieldLabel","signature":"func (c *crConverter) ConvertFieldLabel(gvk schema.GroupVersionKind, label, value string) (string, string, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/conversion/converter.go","code":"func (c *crConverter) ConvertFieldLabel(gvk schema.GroupVersionKind, label, value string) (string, string, error) {\n\t// We currently only support metadata.namespace and metadata.name.\n\tswitch {\n\tcase label == \"metadata.name\":\n\t\treturn label, value, nil\n\tcase !c.clusterScoped \u0026\u0026 label == \"metadata.namespace\":\n\t\treturn label, value, nil\n\tdefault:\n\t\treturn \"\", \"\", fmt.Errorf(\"field label not supported: %s\", label)\n\t}\n}","line":{"from":111,"to":121}} {"id":100014032,"name":"Convert","signature":"func (c *crConverter) Convert(in, out, context interface{}) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/conversion/converter.go","code":"func (c *crConverter) Convert(in, out, context interface{}) error {\n\t// Special-case typed scale conversion if this custom resource supports a scale endpoint\n\tif c.convertScale {\n\t\t_, isInScale := in.(*autoscalingv1.Scale)\n\t\t_, isOutScale := out.(*autoscalingv1.Scale)\n\t\tif isInScale || isOutScale {\n\t\t\treturn typedscheme.Scheme.Convert(in, out, context)\n\t\t}\n\t}\n\n\tunstructIn, ok := in.(*unstructured.Unstructured)\n\tif !ok {\n\t\treturn fmt.Errorf(\"input type %T in not valid for unstructured conversion to %T\", in, out)\n\t}\n\n\tunstructOut, ok := out.(*unstructured.Unstructured)\n\tif !ok {\n\t\treturn fmt.Errorf(\"output type %T in not valid for unstructured conversion from %T\", out, in)\n\t}\n\n\toutGVK := unstructOut.GroupVersionKind()\n\tconverted, err := c.ConvertToVersion(unstructIn, outGVK.GroupVersion())\n\tif err != nil {\n\t\treturn err\n\t}\n\tunstructuredConverted, ok := converted.(runtime.Unstructured)\n\tif !ok {\n\t\t// this should not happened\n\t\treturn fmt.Errorf(\"CR conversion failed\")\n\t}\n\tunstructOut.SetUnstructuredContent(unstructuredConverted.UnstructuredContent())\n\treturn nil\n}","line":{"from":123,"to":155}} {"id":100014033,"name":"ConvertToVersion","signature":"func (c *crConverter) ConvertToVersion(in runtime.Object, target runtime.GroupVersioner) (runtime.Object, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/conversion/converter.go","code":"// ConvertToVersion converts in object to the given gvk in place and returns the same `in` object.\n// The in object can be a single object or a UnstructuredList. CRD storage implementation creates an\n// UnstructuredList with the request's GV, populates it from storage, then calls conversion to convert\n// the individual items. This function assumes it never gets a v1.List.\nfunc (c *crConverter) ConvertToVersion(in runtime.Object, target runtime.GroupVersioner) (runtime.Object, error) {\n\tfromGVK := in.GetObjectKind().GroupVersionKind()\n\ttoGVK, ok := target.KindForGroupVersionKinds([]schema.GroupVersionKind{fromGVK})\n\tif !ok {\n\t\t// TODO: should this be a typed error?\n\t\treturn nil, fmt.Errorf(\"%v is unstructured and is not suitable for converting to %q\", fromGVK.String(), target)\n\t}\n\t// Special-case typed scale conversion if this custom resource supports a scale endpoint\n\tif c.convertScale {\n\t\tif _, isInScale := in.(*autoscalingv1.Scale); isInScale {\n\t\t\treturn typedscheme.Scheme.ConvertToVersion(in, target)\n\t\t}\n\t}\n\n\tif !c.validVersions[toGVK.GroupVersion()] {\n\t\treturn nil, fmt.Errorf(\"request to convert CR to an invalid group/version: %s\", toGVK.GroupVersion().String())\n\t}\n\t// Note that even if the request is for a list, the GV of the request UnstructuredList is what\n\t// is expected to convert to. As mentioned in the function's document, it is not expected to\n\t// get a v1.List.\n\tif !c.validVersions[fromGVK.GroupVersion()] {\n\t\treturn nil, fmt.Errorf(\"request to convert CR from an invalid group/version: %s\", fromGVK.GroupVersion().String())\n\t}\n\t// Check list item's apiVersion\n\tif list, ok := in.(*unstructured.UnstructuredList); ok {\n\t\tfor i := range list.Items {\n\t\t\texpectedGV := list.Items[i].GroupVersionKind().GroupVersion()\n\t\t\tif !c.validVersions[expectedGV] {\n\t\t\t\treturn nil, fmt.Errorf(\"request to convert CR list failed, list index %d has invalid group/version: %s\", i, expectedGV.String())\n\t\t\t}\n\t\t}\n\t}\n\treturn c.converter.Convert(in, toGVK.GroupVersion())\n}","line":{"from":157,"to":194}} {"id":100014034,"name":"ConvertFieldLabel","signature":"func (c *safeConverterWrapper) ConvertFieldLabel(gvk schema.GroupVersionKind, label, value string) (string, string, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/conversion/converter.go","code":"// ConvertFieldLabel delegate the call to the unsafe converter.\nfunc (c *safeConverterWrapper) ConvertFieldLabel(gvk schema.GroupVersionKind, label, value string) (string, string, error) {\n\treturn c.unsafe.ConvertFieldLabel(gvk, label, value)\n}","line":{"from":203,"to":206}} {"id":100014035,"name":"Convert","signature":"func (c *safeConverterWrapper) Convert(in, out, context interface{}) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/conversion/converter.go","code":"// Convert makes a copy of in object and then delegate the call to the unsafe converter.\nfunc (c *safeConverterWrapper) Convert(in, out, context interface{}) error {\n\tinObject, ok := in.(runtime.Object)\n\tif !ok {\n\t\treturn fmt.Errorf(\"input type %T in not valid for object conversion\", in)\n\t}\n\treturn c.unsafe.Convert(inObject.DeepCopyObject(), out, context)\n}","line":{"from":208,"to":215}} {"id":100014036,"name":"ConvertToVersion","signature":"func (c *safeConverterWrapper) ConvertToVersion(in runtime.Object, target runtime.GroupVersioner) (runtime.Object, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/conversion/converter.go","code":"// ConvertToVersion makes a copy of in object and then delegate the call to the unsafe converter.\nfunc (c *safeConverterWrapper) ConvertToVersion(in runtime.Object, target runtime.GroupVersioner) (runtime.Object, error) {\n\treturn c.unsafe.ConvertToVersion(in.DeepCopyObject(), target)\n}","line":{"from":217,"to":220}} {"id":100014037,"name":"newConverterMetricFactory","signature":"func newConverterMetricFactory() *converterMetricFactory","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/conversion/metrics.go","code":"func newConverterMetricFactory() *converterMetricFactory {\n\treturn \u0026converterMetricFactory{durations: map[string]*metrics.HistogramVec{}, factoryLock: sync.Mutex{}}\n}","line":{"from":42,"to":44}} {"id":100014038,"name":"addMetrics","signature":"func (c *converterMetricFactory) addMetrics(crdName string, converter crConverterInterface) (crConverterInterface, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/conversion/metrics.go","code":"func (c *converterMetricFactory) addMetrics(crdName string, converter crConverterInterface) (crConverterInterface, error) {\n\tc.factoryLock.Lock()\n\tdefer c.factoryLock.Unlock()\n\tmetric, exists := c.durations[\"webhook\"]\n\tif !exists {\n\t\tmetric = metrics.NewHistogramVec(\n\t\t\t\u0026metrics.HistogramOpts{\n\t\t\t\tName: \"apiserver_crd_webhook_conversion_duration_seconds\",\n\t\t\t\tHelp: \"CRD webhook conversion duration in seconds\",\n\t\t\t\tBuckets: latencyBuckets,\n\t\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t\t},\n\t\t\t[]string{\"crd_name\", \"from_version\", \"to_version\", \"succeeded\"})\n\t\terr := legacyregistry.Register(metric)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tc.durations[\"webhook\"] = metric\n\t}\n\treturn \u0026converterMetric{latencies: metric, delegate: converter, crdName: crdName}, nil\n}","line":{"from":54,"to":74}} {"id":100014039,"name":"Convert","signature":"func (m *converterMetric) Convert(in runtime.Object, targetGV schema.GroupVersion) (runtime.Object, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/conversion/metrics.go","code":"func (m *converterMetric) Convert(in runtime.Object, targetGV schema.GroupVersion) (runtime.Object, error) {\n\tstart := time.Now()\n\tobj, err := m.delegate.Convert(in, targetGV)\n\tfromVersion := in.GetObjectKind().GroupVersionKind().Version\n\ttoVersion := targetGV.Version\n\n\t// only record this observation if the version is different\n\tif fromVersion != toVersion {\n\t\tm.latencies.WithLabelValues(\n\t\t\tm.crdName, fromVersion, toVersion, strconv.FormatBool(err == nil)).Observe(time.Since(start).Seconds())\n\t}\n\treturn obj, err\n}","line":{"from":76,"to":88}} {"id":100014040,"name":"Convert","signature":"func (c *nopConverter) Convert(in runtime.Object, targetGV schema.GroupVersion) (runtime.Object, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/conversion/nop_converter.go","code":"// ConvertToVersion converts in object to the given gv in place and returns the same `in` object.\nfunc (c *nopConverter) Convert(in runtime.Object, targetGV schema.GroupVersion) (runtime.Object, error) {\n\t// Run the converter on the list items instead of list itself\n\tif list, ok := in.(*unstructured.UnstructuredList); ok {\n\t\tfor i := range list.Items {\n\t\t\tlist.Items[i].SetGroupVersionKind(targetGV.WithKind(list.Items[i].GroupVersionKind().Kind))\n\t\t}\n\t}\n\tin.GetObjectKind().SetGroupVersionKind(targetGV.WithKind(in.GetObjectKind().GroupVersionKind().Kind))\n\treturn in, nil\n}","line":{"from":31,"to":41}} {"id":100014041,"name":"newWebhookConverterFactory","signature":"func newWebhookConverterFactory(serviceResolver webhook.ServiceResolver, authResolverWrapper webhook.AuthenticationInfoResolverWrapper) (*webhookConverterFactory, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/conversion/webhook_converter.go","code":"func newWebhookConverterFactory(serviceResolver webhook.ServiceResolver, authResolverWrapper webhook.AuthenticationInfoResolverWrapper) (*webhookConverterFactory, error) {\n\tclientManager, err := webhook.NewClientManager(\n\t\t[]schema.GroupVersion{v1.SchemeGroupVersion, v1beta1.SchemeGroupVersion},\n\t\tv1beta1.AddToScheme,\n\t\tv1.AddToScheme,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tauthInfoResolver, err := webhook.NewDefaultAuthenticationInfoResolver(\"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Set defaults which may be overridden later.\n\tclientManager.SetAuthenticationInfoResolver(authInfoResolver)\n\tclientManager.SetAuthenticationInfoResolverWrapper(authResolverWrapper)\n\tclientManager.SetServiceResolver(serviceResolver)\n\treturn \u0026webhookConverterFactory{clientManager}, nil\n}","line":{"from":47,"to":65}} {"id":100014042,"name":"webhookClientConfigForCRD","signature":"func webhookClientConfigForCRD(crd *v1.CustomResourceDefinition) *webhook.ClientConfig","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/conversion/webhook_converter.go","code":"func webhookClientConfigForCRD(crd *v1.CustomResourceDefinition) *webhook.ClientConfig {\n\tapiConfig := crd.Spec.Conversion.Webhook.ClientConfig\n\tret := webhook.ClientConfig{\n\t\tName: fmt.Sprintf(\"conversion_webhook_for_%s\", crd.Name),\n\t\tCABundle: apiConfig.CABundle,\n\t}\n\tif apiConfig.URL != nil {\n\t\tret.URL = *apiConfig.URL\n\t}\n\tif apiConfig.Service != nil {\n\t\tret.Service = \u0026webhook.ClientConfigService{\n\t\t\tName: apiConfig.Service.Name,\n\t\t\tNamespace: apiConfig.Service.Namespace,\n\t\t\tPort: *apiConfig.Service.Port,\n\t\t}\n\t\tif apiConfig.Service.Path != nil {\n\t\t\tret.Service.Path = *apiConfig.Service.Path\n\t\t}\n\t}\n\treturn \u0026ret\n}","line":{"from":77,"to":97}} {"id":100014043,"name":"NewWebhookConverter","signature":"func (f *webhookConverterFactory) NewWebhookConverter(crd *v1.CustomResourceDefinition) (*webhookConverter, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/conversion/webhook_converter.go","code":"func (f *webhookConverterFactory) NewWebhookConverter(crd *v1.CustomResourceDefinition) (*webhookConverter, error) {\n\trestClient, err := f.clientManager.HookClient(*webhookClientConfigForCRD(crd))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026webhookConverter{\n\t\tclientManager: f.clientManager,\n\t\trestClient: restClient,\n\t\tname: crd.Name,\n\t\tnopConverter: nopConverter{},\n\n\t\tconversionReviewVersions: crd.Spec.Conversion.Webhook.ConversionReviewVersions,\n\t}, nil\n}","line":{"from":101,"to":114}} {"id":100014044,"name":"getObjectsToConvert","signature":"func getObjectsToConvert(obj runtime.Object, apiVersion string) []runtime.RawExtension","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/conversion/webhook_converter.go","code":"// getObjectsToConvert returns a list of objects requiring conversion.\n// if obj is a list, getObjectsToConvert returns a (potentially empty) list of the items that are not already in the desired version.\n// if obj is not a list, and is already in the desired version, getObjectsToConvert returns an empty list.\n// if obj is not a list, and is not already in the desired version, getObjectsToConvert returns a list containing only obj.\nfunc getObjectsToConvert(obj runtime.Object, apiVersion string) []runtime.RawExtension {\n\tlistObj, isList := obj.(*unstructured.UnstructuredList)\n\tvar objects []runtime.RawExtension\n\tif isList {\n\t\tfor i := range listObj.Items {\n\t\t\t// Only sent item for conversion, if the apiVersion is different\n\t\t\tif listObj.Items[i].GetAPIVersion() != apiVersion {\n\t\t\t\tobjects = append(objects, runtime.RawExtension{Object: \u0026listObj.Items[i]})\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif obj.GetObjectKind().GroupVersionKind().GroupVersion().String() != apiVersion {\n\t\t\tobjects = []runtime.RawExtension{{Object: obj}}\n\t\t}\n\t}\n\treturn objects\n}","line":{"from":116,"to":136}} {"id":100014045,"name":"createConversionReviewObjects","signature":"func createConversionReviewObjects(conversionReviewVersions []string, objects []runtime.RawExtension, apiVersion string, requestUID types.UID) (request, response runtime.Object, err error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/conversion/webhook_converter.go","code":"// createConversionReviewObjects returns ConversionReview request and response objects for the first supported version found in conversionReviewVersions.\nfunc createConversionReviewObjects(conversionReviewVersions []string, objects []runtime.RawExtension, apiVersion string, requestUID types.UID) (request, response runtime.Object, err error) {\n\tfor _, version := range conversionReviewVersions {\n\t\tswitch version {\n\t\tcase v1beta1.SchemeGroupVersion.Version:\n\t\t\treturn \u0026v1beta1.ConversionReview{\n\t\t\t\tRequest: \u0026v1beta1.ConversionRequest{\n\t\t\t\t\tObjects: objects,\n\t\t\t\t\tDesiredAPIVersion: apiVersion,\n\t\t\t\t\tUID: requestUID,\n\t\t\t\t},\n\t\t\t\tResponse: \u0026v1beta1.ConversionResponse{},\n\t\t\t}, \u0026v1beta1.ConversionReview{}, nil\n\t\tcase v1.SchemeGroupVersion.Version:\n\t\t\treturn \u0026v1.ConversionReview{\n\t\t\t\tRequest: \u0026v1.ConversionRequest{\n\t\t\t\t\tObjects: objects,\n\t\t\t\t\tDesiredAPIVersion: apiVersion,\n\t\t\t\t\tUID: requestUID,\n\t\t\t\t},\n\t\t\t\tResponse: \u0026v1.ConversionResponse{},\n\t\t\t}, \u0026v1.ConversionReview{}, nil\n\t\t}\n\t}\n\treturn nil, nil, fmt.Errorf(\"no supported conversion review versions\")\n}","line":{"from":138,"to":163}} {"id":100014046,"name":"getRawExtensionObject","signature":"func getRawExtensionObject(rx runtime.RawExtension) (runtime.Object, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/conversion/webhook_converter.go","code":"func getRawExtensionObject(rx runtime.RawExtension) (runtime.Object, error) {\n\tif rx.Object != nil {\n\t\treturn rx.Object, nil\n\t}\n\tu := unstructured.Unstructured{}\n\terr := u.UnmarshalJSON(rx.Raw)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026u, nil\n}","line":{"from":165,"to":175}} {"id":100014047,"name":"getConvertedObjectsFromResponse","signature":"func getConvertedObjectsFromResponse(expectedUID types.UID, response runtime.Object) (convertedObjects []runtime.RawExtension, err error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/conversion/webhook_converter.go","code":"// getConvertedObjectsFromResponse validates the response, and returns the converted objects.\n// if the response is malformed, an error is returned instead.\n// if the response does not indicate success, the error message is returned instead.\nfunc getConvertedObjectsFromResponse(expectedUID types.UID, response runtime.Object) (convertedObjects []runtime.RawExtension, err error) {\n\tswitch response := response.(type) {\n\tcase *v1.ConversionReview:\n\t\t// Verify GVK to make sure we decoded what we intended to\n\t\tv1GVK := v1.SchemeGroupVersion.WithKind(\"ConversionReview\")\n\t\tif response.GroupVersionKind() != v1GVK {\n\t\t\treturn nil, fmt.Errorf(\"expected webhook response of %v, got %v\", v1GVK.String(), response.GroupVersionKind().String())\n\t\t}\n\n\t\tif response.Response == nil {\n\t\t\treturn nil, fmt.Errorf(\"no response provided\")\n\t\t}\n\n\t\t// Verify UID to make sure this response was actually meant for the request we sent\n\t\tif response.Response.UID != expectedUID {\n\t\t\treturn nil, fmt.Errorf(\"expected response.uid=%q, got %q\", expectedUID, response.Response.UID)\n\t\t}\n\n\t\tif response.Response.Result.Status != metav1.StatusSuccess {\n\t\t\t// TODO: Return a webhook specific error to be able to convert it to meta.Status\n\t\t\tif len(response.Response.Result.Message) \u003e 0 {\n\t\t\t\treturn nil, errors.New(response.Response.Result.Message)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"response.result.status was '%s', not 'Success'\", response.Response.Result.Status)\n\t\t}\n\n\t\treturn response.Response.ConvertedObjects, nil\n\n\tcase *v1beta1.ConversionReview:\n\t\t// v1beta1 processing did not verify GVK or UID, so skip those for compatibility\n\n\t\tif response.Response == nil {\n\t\t\treturn nil, fmt.Errorf(\"no response provided\")\n\t\t}\n\n\t\tif response.Response.Result.Status != metav1.StatusSuccess {\n\t\t\t// TODO: Return a webhook specific error to be able to convert it to meta.Status\n\t\t\tif len(response.Response.Result.Message) \u003e 0 {\n\t\t\t\treturn nil, errors.New(response.Response.Result.Message)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"response.result.status was '%s', not 'Success'\", response.Response.Result.Status)\n\t\t}\n\n\t\treturn response.Response.ConvertedObjects, nil\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unrecognized response type: %T\", response)\n\t}\n}","line":{"from":177,"to":228}} {"id":100014048,"name":"Convert","signature":"func (c *webhookConverter) Convert(in runtime.Object, toGV schema.GroupVersion) (runtime.Object, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/conversion/webhook_converter.go","code":"func (c *webhookConverter) Convert(in runtime.Object, toGV schema.GroupVersion) (runtime.Object, error) {\n\tctx := context.TODO()\n\t// In general, the webhook should not do any defaulting or validation. A special case of that is an empty object\n\t// conversion that must result an empty object and practically is the same as nopConverter.\n\t// A smoke test in API machinery calls the converter on empty objects. As this case happens consistently\n\t// it special cased here not to call webhook converter. The test initiated here:\n\t// https://github.com/kubernetes/kubernetes/blob/dbb448bbdcb9e440eee57024ffa5f1698956a054/staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go#L201\n\tif isEmptyUnstructuredObject(in) {\n\t\treturn c.nopConverter.Convert(in, toGV)\n\t}\n\n\tlistObj, isList := in.(*unstructured.UnstructuredList)\n\n\trequestUID := uuid.NewUUID()\n\tdesiredAPIVersion := toGV.String()\n\tobjectsToConvert := getObjectsToConvert(in, desiredAPIVersion)\n\trequest, response, err := createConversionReviewObjects(c.conversionReviewVersions, objectsToConvert, desiredAPIVersion, requestUID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tobjCount := len(objectsToConvert)\n\tif objCount == 0 {\n\t\t// no objects needed conversion\n\t\tif !isList {\n\t\t\t// for a single item, return as-is\n\t\t\treturn in, nil\n\t\t}\n\t\t// for a list, set the version of the top-level list object (all individual objects are already in the correct version)\n\t\tout := listObj.DeepCopy()\n\t\tout.SetAPIVersion(toGV.String())\n\t\treturn out, nil\n\t}\n\n\tctx, span := tracing.Start(ctx, \"Call conversion webhook\",\n\t\tattribute.String(\"custom-resource-definition\", c.name),\n\t\tattribute.String(\"desired-api-version\", desiredAPIVersion),\n\t\tattribute.Int(\"object-count\", objCount),\n\t\tattribute.String(\"UID\", string(requestUID)))\n\t// Only log conversion webhook traces that exceed a 8ms per object limit plus a 50ms request overhead allowance.\n\t// The per object limit uses the SLO for conversion webhooks (~4ms per object) plus time to serialize/deserialize\n\t// the conversion request on the apiserver side (~4ms per object).\n\tdefer span.End(time.Duration(50+8*objCount) * time.Millisecond)\n\n\t// TODO: Figure out if adding one second timeout make sense here.\n\tr := c.restClient.Post().Body(request).Do(ctx)\n\tif err := r.Into(response); err != nil {\n\t\t// TODO: Return a webhook specific error to be able to convert it to meta.Status\n\t\treturn nil, fmt.Errorf(\"conversion webhook for %v failed: %v\", in.GetObjectKind().GroupVersionKind(), err)\n\t}\n\tspan.AddEvent(\"Request completed\")\n\n\tconvertedObjects, err := getConvertedObjectsFromResponse(requestUID, response)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"conversion webhook for %v failed: %v\", in.GetObjectKind().GroupVersionKind(), err)\n\t}\n\n\tif len(convertedObjects) != len(objectsToConvert) {\n\t\treturn nil, fmt.Errorf(\"conversion webhook for %v returned %d objects, expected %d\", in.GetObjectKind().GroupVersionKind(), len(convertedObjects), len(objectsToConvert))\n\t}\n\n\tif isList {\n\t\t// start a deepcopy of the input and fill in the converted objects from the response at the right spots.\n\t\t// The response list might be sparse because objects had the right version already.\n\t\tconvertedList := listObj.DeepCopy()\n\t\tconvertedIndex := 0\n\t\tfor i := range convertedList.Items {\n\t\t\toriginal := \u0026convertedList.Items[i]\n\t\t\tif original.GetAPIVersion() == toGV.String() {\n\t\t\t\t// This item has not been sent for conversion, and therefore does not show up in the response.\n\t\t\t\t// convertedList has the right item already.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconverted, err := getRawExtensionObject(convertedObjects[convertedIndex])\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"conversion webhook for %v returned invalid converted object at index %v: %v\", in.GetObjectKind().GroupVersionKind(), convertedIndex, err)\n\t\t\t}\n\t\t\tconvertedIndex++\n\t\t\tif expected, got := toGV, converted.GetObjectKind().GroupVersionKind().GroupVersion(); expected != got {\n\t\t\t\treturn nil, fmt.Errorf(\"conversion webhook for %v returned invalid converted object at index %v: invalid groupVersion (expected %v, received %v)\", in.GetObjectKind().GroupVersionKind(), convertedIndex, expected, got)\n\t\t\t}\n\t\t\tif expected, got := original.GetObjectKind().GroupVersionKind().Kind, converted.GetObjectKind().GroupVersionKind().Kind; expected != got {\n\t\t\t\treturn nil, fmt.Errorf(\"conversion webhook for %v returned invalid converted object at index %v: invalid kind (expected %v, received %v)\", in.GetObjectKind().GroupVersionKind(), convertedIndex, expected, got)\n\t\t\t}\n\t\t\tunstructConverted, ok := converted.(*unstructured.Unstructured)\n\t\t\tif !ok {\n\t\t\t\t// this should not happened\n\t\t\t\treturn nil, fmt.Errorf(\"conversion webhook for %v returned invalid converted object at index %v: invalid type, expected=Unstructured, got=%T\", in.GetObjectKind().GroupVersionKind(), convertedIndex, converted)\n\t\t\t}\n\t\t\tif err := validateConvertedObject(original, unstructConverted); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"conversion webhook for %v returned invalid converted object at index %v: %v\", in.GetObjectKind().GroupVersionKind(), convertedIndex, err)\n\t\t\t}\n\t\t\tif err := restoreObjectMeta(original, unstructConverted); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"conversion webhook for %v returned invalid metadata in object at index %v: %v\", in.GetObjectKind().GroupVersionKind(), convertedIndex, err)\n\t\t\t}\n\t\t\tconvertedList.Items[i] = *unstructConverted\n\t\t}\n\t\tconvertedList.SetAPIVersion(toGV.String())\n\t\treturn convertedList, nil\n\t}\n\n\tif len(convertedObjects) != 1 {\n\t\t// This should not happened\n\t\treturn nil, fmt.Errorf(\"conversion webhook for %v failed, no objects returned\", in.GetObjectKind())\n\t}\n\tconverted, err := getRawExtensionObject(convertedObjects[0])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif e, a := toGV, converted.GetObjectKind().GroupVersionKind().GroupVersion(); e != a {\n\t\treturn nil, fmt.Errorf(\"conversion webhook for %v returned invalid object at index 0: invalid groupVersion (expected %v, received %v)\", in.GetObjectKind().GroupVersionKind(), e, a)\n\t}\n\tif e, a := in.GetObjectKind().GroupVersionKind().Kind, converted.GetObjectKind().GroupVersionKind().Kind; e != a {\n\t\treturn nil, fmt.Errorf(\"conversion webhook for %v returned invalid object at index 0: invalid kind (expected %v, received %v)\", in.GetObjectKind().GroupVersionKind(), e, a)\n\t}\n\tunstructConverted, ok := converted.(*unstructured.Unstructured)\n\tif !ok {\n\t\t// this should not happened\n\t\treturn nil, fmt.Errorf(\"conversion webhook for %v failed, unexpected type %T at index 0\", in.GetObjectKind().GroupVersionKind(), converted)\n\t}\n\tunstructIn, ok := in.(*unstructured.Unstructured)\n\tif !ok {\n\t\t// this should not happened\n\t\treturn nil, fmt.Errorf(\"conversion webhook for %v failed unexpected input type %T\", in.GetObjectKind().GroupVersionKind(), in)\n\t}\n\tif err := validateConvertedObject(unstructIn, unstructConverted); err != nil {\n\t\treturn nil, fmt.Errorf(\"conversion webhook for %v returned invalid object: %v\", in.GetObjectKind().GroupVersionKind(), err)\n\t}\n\tif err := restoreObjectMeta(unstructIn, unstructConverted); err != nil {\n\t\treturn nil, fmt.Errorf(\"conversion webhook for %v returned invalid metadata: %v\", in.GetObjectKind().GroupVersionKind(), err)\n\t}\n\treturn converted, nil\n}","line":{"from":230,"to":362}} {"id":100014049,"name":"validateConvertedObject","signature":"func validateConvertedObject(in, out *unstructured.Unstructured) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/conversion/webhook_converter.go","code":"// validateConvertedObject checks that ObjectMeta fields match, with the exception of\n// labels and annotations.\nfunc validateConvertedObject(in, out *unstructured.Unstructured) error {\n\tif e, a := in.GetKind(), out.GetKind(); e != a {\n\t\treturn fmt.Errorf(\"must have the same kind: %v != %v\", e, a)\n\t}\n\tif e, a := in.GetName(), out.GetName(); e != a {\n\t\treturn fmt.Errorf(\"must have the same name: %v != %v\", e, a)\n\t}\n\tif e, a := in.GetNamespace(), out.GetNamespace(); e != a {\n\t\treturn fmt.Errorf(\"must have the same namespace: %v != %v\", e, a)\n\t}\n\tif e, a := in.GetUID(), out.GetUID(); e != a {\n\t\treturn fmt.Errorf(\"must have the same UID: %v != %v\", e, a)\n\t}\n\treturn nil\n}","line":{"from":364,"to":380}} {"id":100014050,"name":"restoreObjectMeta","signature":"func restoreObjectMeta(original, converted *unstructured.Unstructured) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/conversion/webhook_converter.go","code":"// restoreObjectMeta deep-copies metadata from original into converted, while preserving labels and annotations from converted.\nfunc restoreObjectMeta(original, converted *unstructured.Unstructured) error {\n\tobj, found := converted.Object[\"metadata\"]\n\tif !found {\n\t\treturn fmt.Errorf(\"missing metadata in converted object\")\n\t}\n\tresponseMetaData, ok := obj.(map[string]interface{})\n\tif !ok {\n\t\treturn fmt.Errorf(\"invalid metadata of type %T in converted object\", obj)\n\t}\n\n\tif _, ok := original.Object[\"metadata\"]; !ok {\n\t\t// the original will always have metadata. But just to be safe, let's clear in converted\n\t\t// with an empty object instead of nil, to be able to add labels and annotations below.\n\t\tconverted.Object[\"metadata\"] = map[string]interface{}{}\n\t} else {\n\t\tconverted.Object[\"metadata\"] = runtime.DeepCopyJSONValue(original.Object[\"metadata\"])\n\t}\n\n\tobj = converted.Object[\"metadata\"]\n\tconvertedMetaData, ok := obj.(map[string]interface{})\n\tif !ok {\n\t\treturn fmt.Errorf(\"invalid metadata of type %T in input object\", obj)\n\t}\n\n\tfor _, fld := range []string{\"labels\", \"annotations\"} {\n\t\tobj, found := responseMetaData[fld]\n\t\tif !found || obj == nil {\n\t\t\tdelete(convertedMetaData, fld)\n\t\t\tcontinue\n\t\t}\n\t\tresponseField, ok := obj.(map[string]interface{})\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"invalid metadata.%s of type %T in converted object\", fld, obj)\n\t\t}\n\n\t\toriginalField, ok := convertedMetaData[fld].(map[string]interface{})\n\t\tif !ok \u0026\u0026 convertedMetaData[fld] != nil {\n\t\t\treturn fmt.Errorf(\"invalid metadata.%s of type %T in original object\", fld, convertedMetaData[fld])\n\t\t}\n\n\t\tsomethingChanged := len(originalField) != len(responseField)\n\t\tfor k, v := range responseField {\n\t\t\tif _, ok := v.(string); !ok {\n\t\t\t\treturn fmt.Errorf(\"metadata.%s[%s] must be a string, but is %T in converted object\", fld, k, v)\n\t\t\t}\n\t\t\tif originalField[k] != interface{}(v) {\n\t\t\t\tsomethingChanged = true\n\t\t\t}\n\t\t}\n\n\t\tif somethingChanged {\n\t\t\tstringMap := make(map[string]string, len(responseField))\n\t\t\tfor k, v := range responseField {\n\t\t\t\tstringMap[k] = v.(string)\n\t\t\t}\n\t\t\tvar errs field.ErrorList\n\t\t\tif fld == \"labels\" {\n\t\t\t\terrs = metav1validation.ValidateLabels(stringMap, field.NewPath(\"metadata\", \"labels\"))\n\t\t\t} else {\n\t\t\t\terrs = apivalidation.ValidateAnnotations(stringMap, field.NewPath(\"metadata\", \"annotation\"))\n\t\t\t}\n\t\t\tif len(errs) \u003e 0 {\n\t\t\t\treturn errs.ToAggregate()\n\t\t\t}\n\t\t}\n\n\t\tconvertedMetaData[fld] = responseField\n\t}\n\n\treturn nil\n}","line":{"from":382,"to":453}} {"id":100014051,"name":"isEmptyUnstructuredObject","signature":"func isEmptyUnstructuredObject(in runtime.Object) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/conversion/webhook_converter.go","code":"// isEmptyUnstructuredObject returns true if in is an empty unstructured object, i.e. an unstructured object that does\n// not have any field except apiVersion and kind.\nfunc isEmptyUnstructuredObject(in runtime.Object) bool {\n\tu, ok := in.(*unstructured.Unstructured)\n\tif !ok {\n\t\treturn false\n\t}\n\tif len(u.Object) != 2 {\n\t\treturn false\n\t}\n\tif _, ok := u.Object[\"kind\"]; !ok {\n\t\treturn false\n\t}\n\tif _, ok := u.Object[\"apiVersion\"]; !ok {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":455,"to":472}} {"id":100014052,"name":"ServeHTTP","signature":"func (r *versionDiscoveryHandler) ServeHTTP(w http.ResponseWriter, req *http.Request)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_discovery.go","code":"func (r *versionDiscoveryHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tpathParts := splitPath(req.URL.Path)\n\t// only match /apis/\u003cgroup\u003e/\u003cversion\u003e\n\tif len(pathParts) != 3 || pathParts[0] != \"apis\" {\n\t\tr.delegate.ServeHTTP(w, req)\n\t\treturn\n\t}\n\tdiscovery, ok := r.getDiscovery(schema.GroupVersion{Group: pathParts[1], Version: pathParts[2]})\n\tif !ok {\n\t\tr.delegate.ServeHTTP(w, req)\n\t\treturn\n\t}\n\n\tdiscovery.ServeHTTP(w, req)\n}","line":{"from":36,"to":50}} {"id":100014053,"name":"getDiscovery","signature":"func (r *versionDiscoveryHandler) getDiscovery(gv schema.GroupVersion) (*discovery.APIVersionHandler, bool)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_discovery.go","code":"func (r *versionDiscoveryHandler) getDiscovery(gv schema.GroupVersion) (*discovery.APIVersionHandler, bool) {\n\tr.discoveryLock.RLock()\n\tdefer r.discoveryLock.RUnlock()\n\n\tret, ok := r.discovery[gv]\n\treturn ret, ok\n}","line":{"from":52,"to":58}} {"id":100014054,"name":"setDiscovery","signature":"func (r *versionDiscoveryHandler) setDiscovery(gv schema.GroupVersion, discovery *discovery.APIVersionHandler)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_discovery.go","code":"func (r *versionDiscoveryHandler) setDiscovery(gv schema.GroupVersion, discovery *discovery.APIVersionHandler) {\n\tr.discoveryLock.Lock()\n\tdefer r.discoveryLock.Unlock()\n\n\tr.discovery[gv] = discovery\n}","line":{"from":60,"to":65}} {"id":100014055,"name":"unsetDiscovery","signature":"func (r *versionDiscoveryHandler) unsetDiscovery(gv schema.GroupVersion)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_discovery.go","code":"func (r *versionDiscoveryHandler) unsetDiscovery(gv schema.GroupVersion) {\n\tr.discoveryLock.Lock()\n\tdefer r.discoveryLock.Unlock()\n\n\tdelete(r.discovery, gv)\n}","line":{"from":67,"to":72}} {"id":100014056,"name":"ServeHTTP","signature":"func (r *groupDiscoveryHandler) ServeHTTP(w http.ResponseWriter, req *http.Request)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_discovery.go","code":"func (r *groupDiscoveryHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tpathParts := splitPath(req.URL.Path)\n\t// only match /apis/\u003cgroup\u003e\n\tif len(pathParts) != 2 || pathParts[0] != \"apis\" {\n\t\tr.delegate.ServeHTTP(w, req)\n\t\treturn\n\t}\n\tdiscovery, ok := r.getDiscovery(pathParts[1])\n\tif !ok {\n\t\tr.delegate.ServeHTTP(w, req)\n\t\treturn\n\t}\n\n\tdiscovery.ServeHTTP(w, req)\n}","line":{"from":82,"to":96}} {"id":100014057,"name":"getDiscovery","signature":"func (r *groupDiscoveryHandler) getDiscovery(group string) (*discovery.APIGroupHandler, bool)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_discovery.go","code":"func (r *groupDiscoveryHandler) getDiscovery(group string) (*discovery.APIGroupHandler, bool) {\n\tr.discoveryLock.RLock()\n\tdefer r.discoveryLock.RUnlock()\n\n\tret, ok := r.discovery[group]\n\treturn ret, ok\n}","line":{"from":98,"to":104}} {"id":100014058,"name":"setDiscovery","signature":"func (r *groupDiscoveryHandler) setDiscovery(group string, discovery *discovery.APIGroupHandler)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_discovery.go","code":"func (r *groupDiscoveryHandler) setDiscovery(group string, discovery *discovery.APIGroupHandler) {\n\tr.discoveryLock.Lock()\n\tdefer r.discoveryLock.Unlock()\n\n\tr.discovery[group] = discovery\n}","line":{"from":106,"to":111}} {"id":100014059,"name":"unsetDiscovery","signature":"func (r *groupDiscoveryHandler) unsetDiscovery(group string)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_discovery.go","code":"func (r *groupDiscoveryHandler) unsetDiscovery(group string) {\n\tr.discoveryLock.Lock()\n\tdefer r.discoveryLock.Unlock()\n\n\tdelete(r.discovery, group)\n}","line":{"from":113,"to":118}} {"id":100014060,"name":"splitPath","signature":"func splitPath(path string) []string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_discovery.go","code":"// splitPath returns the segments for a URL path.\nfunc splitPath(path string) []string {\n\tpath = strings.Trim(path, \"/\")\n\tif path == \"\" {\n\t\treturn []string{}\n\t}\n\treturn strings.Split(path, \"/\")\n}","line":{"from":120,"to":127}} {"id":100014061,"name":"NewDiscoveryController","signature":"func NewDiscoveryController(","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_discovery_controller.go","code":"func NewDiscoveryController(\n\tcrdInformer informers.CustomResourceDefinitionInformer,\n\tversionHandler *versionDiscoveryHandler,\n\tgroupHandler *groupDiscoveryHandler,\n\tresourceManager discoveryendpoint.ResourceManager,\n) *DiscoveryController {\n\tc := \u0026DiscoveryController{\n\t\tversionHandler: versionHandler,\n\t\tgroupHandler: groupHandler,\n\t\tresourceManager: resourceManager,\n\t\tcrdLister: crdInformer.Lister(),\n\t\tcrdsSynced: crdInformer.Informer().HasSynced,\n\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"DiscoveryController\"),\n\t}\n\n\tcrdInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: c.addCustomResourceDefinition,\n\t\tUpdateFunc: c.updateCustomResourceDefinition,\n\t\tDeleteFunc: c.deleteCustomResourceDefinition,\n\t})\n\n\tc.syncFn = c.sync\n\n\treturn c\n}","line":{"from":59,"to":84}} {"id":100014062,"name":"sync","signature":"func (c *DiscoveryController) sync(version schema.GroupVersion) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_discovery_controller.go","code":"func (c *DiscoveryController) sync(version schema.GroupVersion) error {\n\n\tapiVersionsForDiscovery := []metav1.GroupVersionForDiscovery{}\n\tapiResourcesForDiscovery := []metav1.APIResource{}\n\taggregatedApiResourcesForDiscovery := []apidiscoveryv2beta1.APIResourceDiscovery{}\n\tversionsForDiscoveryMap := map[metav1.GroupVersion]bool{}\n\n\tcrds, err := c.crdLister.List(labels.Everything())\n\tif err != nil {\n\t\treturn err\n\t}\n\tfoundVersion := false\n\tfoundGroup := false\n\tfor _, crd := range crds {\n\t\tif !apiextensionshelpers.IsCRDConditionTrue(crd, apiextensionsv1.Established) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif crd.Spec.Group != version.Group {\n\t\t\tcontinue\n\t\t}\n\n\t\tfoundThisVersion := false\n\t\tvar storageVersionHash string\n\t\tfor _, v := range crd.Spec.Versions {\n\t\t\tif !v.Served {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// If there is any Served version, that means the group should show up in discovery\n\t\t\tfoundGroup = true\n\n\t\t\tgv := metav1.GroupVersion{Group: crd.Spec.Group, Version: v.Name}\n\t\t\tif !versionsForDiscoveryMap[gv] {\n\t\t\t\tversionsForDiscoveryMap[gv] = true\n\t\t\t\tapiVersionsForDiscovery = append(apiVersionsForDiscovery, metav1.GroupVersionForDiscovery{\n\t\t\t\t\tGroupVersion: crd.Spec.Group + \"/\" + v.Name,\n\t\t\t\t\tVersion: v.Name,\n\t\t\t\t})\n\t\t\t}\n\t\t\tif v.Name == version.Version {\n\t\t\t\tfoundThisVersion = true\n\t\t\t}\n\t\t\tif v.Storage {\n\t\t\t\tstorageVersionHash = discovery.StorageVersionHash(gv.Group, gv.Version, crd.Spec.Names.Kind)\n\t\t\t}\n\t\t}\n\n\t\tif !foundThisVersion {\n\t\t\tcontinue\n\t\t}\n\t\tfoundVersion = true\n\n\t\tverbs := metav1.Verbs([]string{\"delete\", \"deletecollection\", \"get\", \"list\", \"patch\", \"create\", \"update\", \"watch\"})\n\t\t// if we're terminating we don't allow some verbs\n\t\tif apiextensionshelpers.IsCRDConditionTrue(crd, apiextensionsv1.Terminating) {\n\t\t\tverbs = metav1.Verbs([]string{\"delete\", \"deletecollection\", \"get\", \"list\", \"watch\"})\n\t\t}\n\n\t\tapiResourcesForDiscovery = append(apiResourcesForDiscovery, metav1.APIResource{\n\t\t\tName: crd.Status.AcceptedNames.Plural,\n\t\t\tSingularName: crd.Status.AcceptedNames.Singular,\n\t\t\tNamespaced: crd.Spec.Scope == apiextensionsv1.NamespaceScoped,\n\t\t\tKind: crd.Status.AcceptedNames.Kind,\n\t\t\tVerbs: verbs,\n\t\t\tShortNames: crd.Status.AcceptedNames.ShortNames,\n\t\t\tCategories: crd.Status.AcceptedNames.Categories,\n\t\t\tStorageVersionHash: storageVersionHash,\n\t\t})\n\n\t\tsubresources, err := apiextensionshelpers.GetSubresourcesForVersion(crd, version.Version)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif c.resourceManager != nil {\n\t\t\tvar scope apidiscoveryv2beta1.ResourceScope\n\t\t\tif crd.Spec.Scope == apiextensionsv1.NamespaceScoped {\n\t\t\t\tscope = apidiscoveryv2beta1.ScopeNamespace\n\t\t\t} else {\n\t\t\t\tscope = apidiscoveryv2beta1.ScopeCluster\n\t\t\t}\n\t\t\tapiResourceDiscovery := apidiscoveryv2beta1.APIResourceDiscovery{\n\t\t\t\tResource: crd.Status.AcceptedNames.Plural,\n\t\t\t\tSingularResource: crd.Status.AcceptedNames.Singular,\n\t\t\t\tScope: scope,\n\t\t\t\tResponseKind: \u0026metav1.GroupVersionKind{\n\t\t\t\t\tGroup: version.Group,\n\t\t\t\t\tVersion: version.Version,\n\t\t\t\t\tKind: crd.Status.AcceptedNames.Kind,\n\t\t\t\t},\n\t\t\t\tVerbs: verbs,\n\t\t\t\tShortNames: crd.Status.AcceptedNames.ShortNames,\n\t\t\t\tCategories: crd.Status.AcceptedNames.Categories,\n\t\t\t}\n\t\t\tif subresources != nil \u0026\u0026 subresources.Status != nil {\n\t\t\t\tapiResourceDiscovery.Subresources = append(apiResourceDiscovery.Subresources, apidiscoveryv2beta1.APISubresourceDiscovery{\n\t\t\t\t\tSubresource: \"status\",\n\t\t\t\t\tResponseKind: \u0026metav1.GroupVersionKind{\n\t\t\t\t\t\tGroup: version.Group,\n\t\t\t\t\t\tVersion: version.Version,\n\t\t\t\t\t\tKind: crd.Status.AcceptedNames.Kind,\n\t\t\t\t\t},\n\t\t\t\t\tVerbs: metav1.Verbs([]string{\"get\", \"patch\", \"update\"}),\n\t\t\t\t})\n\t\t\t}\n\t\t\tif subresources != nil \u0026\u0026 subresources.Scale != nil {\n\t\t\t\tapiResourceDiscovery.Subresources = append(apiResourceDiscovery.Subresources, apidiscoveryv2beta1.APISubresourceDiscovery{\n\t\t\t\t\tSubresource: \"scale\",\n\t\t\t\t\tResponseKind: \u0026metav1.GroupVersionKind{\n\t\t\t\t\t\tGroup: autoscaling.GroupName,\n\t\t\t\t\t\tVersion: \"v1\",\n\t\t\t\t\t\tKind: \"Scale\",\n\t\t\t\t\t},\n\t\t\t\t\tVerbs: metav1.Verbs([]string{\"get\", \"patch\", \"update\"}),\n\t\t\t\t})\n\n\t\t\t}\n\t\t\taggregatedApiResourcesForDiscovery = append(aggregatedApiResourcesForDiscovery, apiResourceDiscovery)\n\t\t}\n\n\t\tif subresources != nil \u0026\u0026 subresources.Status != nil {\n\t\t\tapiResourcesForDiscovery = append(apiResourcesForDiscovery, metav1.APIResource{\n\t\t\t\tName: crd.Status.AcceptedNames.Plural + \"/status\",\n\t\t\t\tNamespaced: crd.Spec.Scope == apiextensionsv1.NamespaceScoped,\n\t\t\t\tKind: crd.Status.AcceptedNames.Kind,\n\t\t\t\tVerbs: metav1.Verbs([]string{\"get\", \"patch\", \"update\"}),\n\t\t\t})\n\t\t}\n\n\t\tif subresources != nil \u0026\u0026 subresources.Scale != nil {\n\t\t\tapiResourcesForDiscovery = append(apiResourcesForDiscovery, metav1.APIResource{\n\t\t\t\tGroup: autoscaling.GroupName,\n\t\t\t\tVersion: \"v1\",\n\t\t\t\tKind: \"Scale\",\n\t\t\t\tName: crd.Status.AcceptedNames.Plural + \"/scale\",\n\t\t\t\tNamespaced: crd.Spec.Scope == apiextensionsv1.NamespaceScoped,\n\t\t\t\tVerbs: metav1.Verbs([]string{\"get\", \"patch\", \"update\"}),\n\t\t\t})\n\t\t}\n\t}\n\n\tif !foundGroup {\n\t\tc.groupHandler.unsetDiscovery(version.Group)\n\t\tc.versionHandler.unsetDiscovery(version)\n\n\t\tif c.resourceManager != nil {\n\t\t\tc.resourceManager.RemoveGroup(version.Group)\n\t\t}\n\t\treturn nil\n\t}\n\n\tsortGroupDiscoveryByKubeAwareVersion(apiVersionsForDiscovery)\n\n\tapiGroup := metav1.APIGroup{\n\t\tName: version.Group,\n\t\tVersions: apiVersionsForDiscovery,\n\t\t// the preferred versions for a group is the first item in\n\t\t// apiVersionsForDiscovery after it put in the right ordered\n\t\tPreferredVersion: apiVersionsForDiscovery[0],\n\t}\n\tc.groupHandler.setDiscovery(version.Group, discovery.NewAPIGroupHandler(Codecs, apiGroup))\n\n\tif !foundVersion {\n\t\tc.versionHandler.unsetDiscovery(version)\n\n\t\tif c.resourceManager != nil {\n\t\t\tc.resourceManager.RemoveGroupVersion(metav1.GroupVersion{\n\t\t\t\tGroup: version.Group,\n\t\t\t\tVersion: version.Version,\n\t\t\t})\n\t\t}\n\t\treturn nil\n\t}\n\tc.versionHandler.setDiscovery(version, discovery.NewAPIVersionHandler(Codecs, version, discovery.APIResourceListerFunc(func() []metav1.APIResource {\n\t\treturn apiResourcesForDiscovery\n\t})))\n\n\tsort.Slice(aggregatedApiResourcesForDiscovery[:], func(i, j int) bool {\n\t\treturn aggregatedApiResourcesForDiscovery[i].Resource \u003c aggregatedApiResourcesForDiscovery[j].Resource\n\t})\n\tif c.resourceManager != nil {\n\t\tc.resourceManager.AddGroupVersion(version.Group, apidiscoveryv2beta1.APIVersionDiscovery{\n\t\t\tFreshness: apidiscoveryv2beta1.DiscoveryFreshnessCurrent,\n\t\t\tVersion: version.Version,\n\t\t\tResources: aggregatedApiResourcesForDiscovery,\n\t\t})\n\t\t// Default priority for CRDs\n\t\tc.resourceManager.SetGroupVersionPriority(metav1.GroupVersion(version), 1000, 100)\n\t}\n\treturn nil\n}","line":{"from":86,"to":276}} {"id":100014063,"name":"sortGroupDiscoveryByKubeAwareVersion","signature":"func sortGroupDiscoveryByKubeAwareVersion(gd []metav1.GroupVersionForDiscovery)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_discovery_controller.go","code":"func sortGroupDiscoveryByKubeAwareVersion(gd []metav1.GroupVersionForDiscovery) {\n\tsort.Slice(gd, func(i, j int) bool {\n\t\treturn version.CompareKubeAwareVersionStrings(gd[i].Version, gd[j].Version) \u003e 0\n\t})\n}","line":{"from":278,"to":282}} {"id":100014064,"name":"Run","signature":"func (c *DiscoveryController) Run(stopCh \u003c-chan struct{}, synchedCh chan\u003c- struct{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_discovery_controller.go","code":"func (c *DiscoveryController) Run(stopCh \u003c-chan struct{}, synchedCh chan\u003c- struct{}) {\n\tdefer utilruntime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\tdefer klog.Info(\"Shutting down DiscoveryController\")\n\n\tklog.Info(\"Starting DiscoveryController\")\n\n\tif !cache.WaitForCacheSync(stopCh, c.crdsSynced) {\n\t\tutilruntime.HandleError(fmt.Errorf(\"timed out waiting for caches to sync\"))\n\t\treturn\n\t}\n\n\t// initially sync all group versions to make sure we serve complete discovery\n\tif err := wait.PollImmediateUntil(time.Second, func() (bool, error) {\n\t\tcrds, err := c.crdLister.List(labels.Everything())\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"failed to initially list CRDs: %v\", err))\n\t\t\treturn false, nil\n\t\t}\n\t\tfor _, crd := range crds {\n\t\t\tfor _, v := range crd.Spec.Versions {\n\t\t\t\tgv := schema.GroupVersion{Group: crd.Spec.Group, Version: v.Name}\n\t\t\t\tif err := c.sync(gv); err != nil {\n\t\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"failed to initially sync CRD version %v: %v\", gv, err))\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true, nil\n\t}, stopCh); err == wait.ErrWaitTimeout {\n\t\tutilruntime.HandleError(fmt.Errorf(\"timed out waiting for discovery endpoint to initialize\"))\n\t\treturn\n\t} else if err != nil {\n\t\tpanic(fmt.Errorf(\"unexpected error: %v\", err))\n\t}\n\tclose(synchedCh)\n\n\t// only start one worker thread since its a slow moving API\n\tgo wait.Until(c.runWorker, time.Second, stopCh)\n\n\t\u003c-stopCh\n}","line":{"from":284,"to":325}} {"id":100014065,"name":"runWorker","signature":"func (c *DiscoveryController) runWorker()","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_discovery_controller.go","code":"func (c *DiscoveryController) runWorker() {\n\tfor c.processNextWorkItem() {\n\t}\n}","line":{"from":327,"to":330}} {"id":100014066,"name":"processNextWorkItem","signature":"func (c *DiscoveryController) processNextWorkItem() bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_discovery_controller.go","code":"// processNextWorkItem deals with one key off the queue. It returns false when it's time to quit.\nfunc (c *DiscoveryController) processNextWorkItem() bool {\n\tkey, quit := c.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.queue.Done(key)\n\n\terr := c.syncFn(key.(schema.GroupVersion))\n\tif err == nil {\n\t\tc.queue.Forget(key)\n\t\treturn true\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"%v failed with: %v\", key, err))\n\tc.queue.AddRateLimited(key)\n\n\treturn true\n}","line":{"from":332,"to":350}} {"id":100014067,"name":"enqueue","signature":"func (c *DiscoveryController) enqueue(obj *apiextensionsv1.CustomResourceDefinition)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_discovery_controller.go","code":"func (c *DiscoveryController) enqueue(obj *apiextensionsv1.CustomResourceDefinition) {\n\tfor _, v := range obj.Spec.Versions {\n\t\tc.queue.Add(schema.GroupVersion{Group: obj.Spec.Group, Version: v.Name})\n\t}\n}","line":{"from":352,"to":356}} {"id":100014068,"name":"addCustomResourceDefinition","signature":"func (c *DiscoveryController) addCustomResourceDefinition(obj interface{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_discovery_controller.go","code":"func (c *DiscoveryController) addCustomResourceDefinition(obj interface{}) {\n\tcastObj := obj.(*apiextensionsv1.CustomResourceDefinition)\n\tklog.V(4).Infof(\"Adding customresourcedefinition %s\", castObj.Name)\n\tc.enqueue(castObj)\n}","line":{"from":358,"to":362}} {"id":100014069,"name":"updateCustomResourceDefinition","signature":"func (c *DiscoveryController) updateCustomResourceDefinition(oldObj, newObj interface{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_discovery_controller.go","code":"func (c *DiscoveryController) updateCustomResourceDefinition(oldObj, newObj interface{}) {\n\tcastNewObj := newObj.(*apiextensionsv1.CustomResourceDefinition)\n\tcastOldObj := oldObj.(*apiextensionsv1.CustomResourceDefinition)\n\tklog.V(4).Infof(\"Updating customresourcedefinition %s\", castOldObj.Name)\n\t// Enqueue both old and new object to make sure we remove and add appropriate Versions.\n\t// The working queue will resolve any duplicates and only changes will stay in the queue.\n\tc.enqueue(castNewObj)\n\tc.enqueue(castOldObj)\n}","line":{"from":364,"to":372}} {"id":100014070,"name":"deleteCustomResourceDefinition","signature":"func (c *DiscoveryController) deleteCustomResourceDefinition(obj interface{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_discovery_controller.go","code":"func (c *DiscoveryController) deleteCustomResourceDefinition(obj interface{}) {\n\tcastObj, ok := obj.(*apiextensionsv1.CustomResourceDefinition)\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"Couldn't get object from tombstone %#v\", obj)\n\t\t\treturn\n\t\t}\n\t\tcastObj, ok = tombstone.Obj.(*apiextensionsv1.CustomResourceDefinition)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"Tombstone contained object that is not expected %#v\", obj)\n\t\t\treturn\n\t\t}\n\t}\n\tklog.V(4).Infof(\"Deleting customresourcedefinition %q\", castObj.Name)\n\tc.enqueue(castObj)\n}","line":{"from":374,"to":390}} {"id":100014071,"name":"NewCustomResourceDefinitionHandler","signature":"func NewCustomResourceDefinitionHandler(","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"func NewCustomResourceDefinitionHandler(\n\tversionDiscoveryHandler *versionDiscoveryHandler,\n\tgroupDiscoveryHandler *groupDiscoveryHandler,\n\tcrdInformer informers.CustomResourceDefinitionInformer,\n\tdelegate http.Handler,\n\trestOptionsGetter generic.RESTOptionsGetter,\n\tadmission admission.Interface,\n\testablishingController *establish.EstablishingController,\n\tserviceResolver webhook.ServiceResolver,\n\tauthResolverWrapper webhook.AuthenticationInfoResolverWrapper,\n\tmasterCount int,\n\tauthorizer authorizer.Authorizer,\n\trequestTimeout time.Duration,\n\tminRequestTimeout time.Duration,\n\tstaticOpenAPISpec map[string]*spec.Schema,\n\tmaxRequestBodyBytes int64) (*crdHandler, error) {\n\tret := \u0026crdHandler{\n\t\tversionDiscoveryHandler: versionDiscoveryHandler,\n\t\tgroupDiscoveryHandler: groupDiscoveryHandler,\n\t\tcustomStorage: atomic.Value{},\n\t\tcrdLister: crdInformer.Lister(),\n\t\tdelegate: delegate,\n\t\trestOptionsGetter: restOptionsGetter,\n\t\tadmission: admission,\n\t\testablishingController: establishingController,\n\t\tmasterCount: masterCount,\n\t\tauthorizer: authorizer,\n\t\trequestTimeout: requestTimeout,\n\t\tminRequestTimeout: minRequestTimeout,\n\t\tstaticOpenAPISpec: staticOpenAPISpec,\n\t\tmaxRequestBodyBytes: maxRequestBodyBytes,\n\t}\n\tcrdInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: ret.createCustomResourceDefinition,\n\t\tUpdateFunc: ret.updateCustomResourceDefinition,\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tret.removeDeadStorage()\n\t\t},\n\t})\n\tcrConverterFactory, err := conversion.NewCRConverterFactory(serviceResolver, authResolverWrapper)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tret.converterFactory = crConverterFactory\n\n\tret.customStorage.Store(crdStorageMap{})\n\n\treturn ret, nil\n}","line":{"from":166,"to":214}} {"id":100014072,"name":"ServeHTTP","signature":"func (r *crdHandler) ServeHTTP(w http.ResponseWriter, req *http.Request)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"func (r *crdHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tctx := req.Context()\n\trequestInfo, ok := apirequest.RequestInfoFrom(ctx)\n\tif !ok {\n\t\tresponsewriters.ErrorNegotiated(\n\t\t\tapierrors.NewInternalError(fmt.Errorf(\"no RequestInfo found in the context\")),\n\t\t\tCodecs, schema.GroupVersion{}, w, req,\n\t\t)\n\t\treturn\n\t}\n\tif !requestInfo.IsResourceRequest {\n\t\tpathParts := splitPath(requestInfo.Path)\n\t\t// only match /apis/\u003cgroup\u003e/\u003cversion\u003e\n\t\t// only registered under /apis\n\t\tif len(pathParts) == 3 {\n\t\t\tr.versionDiscoveryHandler.ServeHTTP(w, req)\n\t\t\treturn\n\t\t}\n\t\t// only match /apis/\u003cgroup\u003e\n\t\tif len(pathParts) == 2 {\n\t\t\tr.groupDiscoveryHandler.ServeHTTP(w, req)\n\t\t\treturn\n\t\t}\n\n\t\tr.delegate.ServeHTTP(w, req)\n\t\treturn\n\t}\n\n\tcrdName := requestInfo.Resource + \".\" + requestInfo.APIGroup\n\tcrd, err := r.crdLister.Get(crdName)\n\tif apierrors.IsNotFound(err) {\n\t\tr.delegate.ServeHTTP(w, req)\n\t\treturn\n\t}\n\tif err != nil {\n\t\tutilruntime.HandleError(err)\n\t\tresponsewriters.ErrorNegotiated(\n\t\t\tapierrors.NewInternalError(fmt.Errorf(\"error resolving resource\")),\n\t\t\tCodecs, schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}, w, req,\n\t\t)\n\t\treturn\n\t}\n\n\t// if the scope in the CRD and the scope in request differ (with exception of the verbs in possiblyAcrossAllNamespacesVerbs\n\t// for namespaced resources), pass request to the delegate, which is supposed to lead to a 404.\n\tnamespacedCRD, namespacedReq := crd.Spec.Scope == apiextensionsv1.NamespaceScoped, len(requestInfo.Namespace) \u003e 0\n\tif !namespacedCRD \u0026\u0026 namespacedReq {\n\t\tr.delegate.ServeHTTP(w, req)\n\t\treturn\n\t}\n\tif namespacedCRD \u0026\u0026 !namespacedReq \u0026\u0026 !possiblyAcrossAllNamespacesVerbs.Has(requestInfo.Verb) {\n\t\tr.delegate.ServeHTTP(w, req)\n\t\treturn\n\t}\n\n\tif !apiextensionshelpers.HasServedCRDVersion(crd, requestInfo.APIVersion) {\n\t\tr.delegate.ServeHTTP(w, req)\n\t\treturn\n\t}\n\n\t// There is a small chance that a CRD is being served because NamesAccepted condition is true,\n\t// but it becomes \"unserved\" because another names update leads to a conflict\n\t// and EstablishingController wasn't fast enough to put the CRD into the Established condition.\n\t// We accept this as the problem is small and self-healing.\n\tif !apiextensionshelpers.IsCRDConditionTrue(crd, apiextensionsv1.NamesAccepted) \u0026\u0026\n\t\t!apiextensionshelpers.IsCRDConditionTrue(crd, apiextensionsv1.Established) {\n\t\tr.delegate.ServeHTTP(w, req)\n\t\treturn\n\t}\n\n\tterminating := apiextensionshelpers.IsCRDConditionTrue(crd, apiextensionsv1.Terminating)\n\n\tcrdInfo, err := r.getOrCreateServingInfoFor(crd.UID, crd.Name)\n\tif apierrors.IsNotFound(err) {\n\t\tr.delegate.ServeHTTP(w, req)\n\t\treturn\n\t}\n\tif err != nil {\n\t\tutilruntime.HandleError(err)\n\t\tresponsewriters.ErrorNegotiated(\n\t\t\tapierrors.NewInternalError(fmt.Errorf(\"error resolving resource\")),\n\t\t\tCodecs, schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}, w, req,\n\t\t)\n\t\treturn\n\t}\n\tif !hasServedCRDVersion(crdInfo.spec, requestInfo.APIVersion) {\n\t\tr.delegate.ServeHTTP(w, req)\n\t\treturn\n\t}\n\n\tdeprecated := crdInfo.deprecated[requestInfo.APIVersion]\n\tfor _, w := range crdInfo.warnings[requestInfo.APIVersion] {\n\t\twarning.AddWarning(req.Context(), \"\", w)\n\t}\n\n\tverb := strings.ToUpper(requestInfo.Verb)\n\tresource := requestInfo.Resource\n\tsubresource := requestInfo.Subresource\n\tscope := metrics.CleanScope(requestInfo)\n\tsupportedTypes := []string{\n\t\tstring(types.JSONPatchType),\n\t\tstring(types.MergePatchType),\n\t\tstring(types.ApplyPatchType),\n\t}\n\n\tvar handlerFunc http.HandlerFunc\n\tsubresources, err := apiextensionshelpers.GetSubresourcesForVersion(crd, requestInfo.APIVersion)\n\tif err != nil {\n\t\tutilruntime.HandleError(err)\n\t\tresponsewriters.ErrorNegotiated(\n\t\t\tapierrors.NewInternalError(fmt.Errorf(\"could not properly serve the subresource\")),\n\t\t\tCodecs, schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}, w, req,\n\t\t)\n\t\treturn\n\t}\n\tswitch {\n\tcase subresource == \"status\" \u0026\u0026 subresources != nil \u0026\u0026 subresources.Status != nil:\n\t\thandlerFunc = r.serveStatus(w, req, requestInfo, crdInfo, terminating, supportedTypes)\n\tcase subresource == \"scale\" \u0026\u0026 subresources != nil \u0026\u0026 subresources.Scale != nil:\n\t\thandlerFunc = r.serveScale(w, req, requestInfo, crdInfo, terminating, supportedTypes)\n\tcase len(subresource) == 0:\n\t\thandlerFunc = r.serveResource(w, req, requestInfo, crdInfo, crd, terminating, supportedTypes)\n\tdefault:\n\t\tresponsewriters.ErrorNegotiated(\n\t\t\tapierrors.NewNotFound(schema.GroupResource{Group: requestInfo.APIGroup, Resource: requestInfo.Resource}, requestInfo.Name),\n\t\t\tCodecs, schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}, w, req,\n\t\t)\n\t}\n\n\tif handlerFunc != nil {\n\t\thandlerFunc = metrics.InstrumentHandlerFunc(verb, requestInfo.APIGroup, requestInfo.APIVersion, resource, subresource, scope, metrics.APIServerComponent, deprecated, \"\", handlerFunc)\n\t\thandler := genericfilters.WithWaitGroup(handlerFunc, longRunningFilter, crdInfo.waitGroup)\n\t\thandler.ServeHTTP(w, req)\n\t\treturn\n\t}\n}","line":{"from":225,"to":360}} {"id":100014073,"name":"serveResource","signature":"func (r *crdHandler) serveResource(w http.ResponseWriter, req *http.Request, requestInfo *apirequest.RequestInfo, crdInfo *crdInfo, crd *apiextensionsv1.CustomResourceDefinition, terminating bool, supportedTypes []string) http.HandlerFunc","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"func (r *crdHandler) serveResource(w http.ResponseWriter, req *http.Request, requestInfo *apirequest.RequestInfo, crdInfo *crdInfo, crd *apiextensionsv1.CustomResourceDefinition, terminating bool, supportedTypes []string) http.HandlerFunc {\n\trequestScope := crdInfo.requestScopes[requestInfo.APIVersion]\n\tstorage := crdInfo.storages[requestInfo.APIVersion].CustomResource\n\n\tswitch requestInfo.Verb {\n\tcase \"get\":\n\t\treturn handlers.GetResource(storage, requestScope)\n\tcase \"list\":\n\t\tforceWatch := false\n\t\treturn handlers.ListResource(storage, storage, requestScope, forceWatch, r.minRequestTimeout)\n\tcase \"watch\":\n\t\tforceWatch := true\n\t\treturn handlers.ListResource(storage, storage, requestScope, forceWatch, r.minRequestTimeout)\n\tcase \"create\":\n\t\t// we want to track recently created CRDs so that in HA environments we don't have server A allow a create and server B\n\t\t// not have observed the established, so a followup get,update,delete results in a 404. We've observed about 800ms\n\t\t// delay in some CI environments. Two seconds looks long enough and reasonably short for hot retriers.\n\t\tjustCreated := time.Since(apiextensionshelpers.FindCRDCondition(crd, apiextensionsv1.Established).LastTransitionTime.Time) \u003c 2*time.Second\n\t\tif justCreated {\n\t\t\ttime.Sleep(2 * time.Second)\n\t\t}\n\t\tif terminating {\n\t\t\terr := apierrors.NewMethodNotSupported(schema.GroupResource{Group: requestInfo.APIGroup, Resource: requestInfo.Resource}, requestInfo.Verb)\n\t\t\terr.ErrStatus.Message = fmt.Sprintf(\"%v not allowed while custom resource definition is terminating\", requestInfo.Verb)\n\t\t\tresponsewriters.ErrorNegotiated(err, Codecs, schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}, w, req)\n\t\t\treturn nil\n\t\t}\n\t\treturn handlers.CreateResource(storage, requestScope, r.admission)\n\tcase \"update\":\n\t\treturn handlers.UpdateResource(storage, requestScope, r.admission)\n\tcase \"patch\":\n\t\treturn handlers.PatchResource(storage, requestScope, r.admission, supportedTypes)\n\tcase \"delete\":\n\t\tallowsOptions := true\n\t\treturn handlers.DeleteResource(storage, allowsOptions, requestScope, r.admission)\n\tcase \"deletecollection\":\n\t\tcheckBody := true\n\t\treturn handlers.DeleteCollection(storage, checkBody, requestScope, r.admission)\n\tdefault:\n\t\tresponsewriters.ErrorNegotiated(\n\t\t\tapierrors.NewMethodNotSupported(schema.GroupResource{Group: requestInfo.APIGroup, Resource: requestInfo.Resource}, requestInfo.Verb),\n\t\t\tCodecs, schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}, w, req,\n\t\t)\n\t\treturn nil\n\t}\n}","line":{"from":362,"to":407}} {"id":100014074,"name":"serveStatus","signature":"func (r *crdHandler) serveStatus(w http.ResponseWriter, req *http.Request, requestInfo *apirequest.RequestInfo, crdInfo *crdInfo, terminating bool, supportedTypes []string) http.HandlerFunc","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"func (r *crdHandler) serveStatus(w http.ResponseWriter, req *http.Request, requestInfo *apirequest.RequestInfo, crdInfo *crdInfo, terminating bool, supportedTypes []string) http.HandlerFunc {\n\trequestScope := crdInfo.statusRequestScopes[requestInfo.APIVersion]\n\tstorage := crdInfo.storages[requestInfo.APIVersion].Status\n\n\tswitch requestInfo.Verb {\n\tcase \"get\":\n\t\treturn handlers.GetResource(storage, requestScope)\n\tcase \"update\":\n\t\treturn handlers.UpdateResource(storage, requestScope, r.admission)\n\tcase \"patch\":\n\t\treturn handlers.PatchResource(storage, requestScope, r.admission, supportedTypes)\n\tdefault:\n\t\tresponsewriters.ErrorNegotiated(\n\t\t\tapierrors.NewMethodNotSupported(schema.GroupResource{Group: requestInfo.APIGroup, Resource: requestInfo.Resource}, requestInfo.Verb),\n\t\t\tCodecs, schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}, w, req,\n\t\t)\n\t\treturn nil\n\t}\n}","line":{"from":409,"to":427}} {"id":100014075,"name":"serveScale","signature":"func (r *crdHandler) serveScale(w http.ResponseWriter, req *http.Request, requestInfo *apirequest.RequestInfo, crdInfo *crdInfo, terminating bool, supportedTypes []string) http.HandlerFunc","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"func (r *crdHandler) serveScale(w http.ResponseWriter, req *http.Request, requestInfo *apirequest.RequestInfo, crdInfo *crdInfo, terminating bool, supportedTypes []string) http.HandlerFunc {\n\trequestScope := crdInfo.scaleRequestScopes[requestInfo.APIVersion]\n\tstorage := crdInfo.storages[requestInfo.APIVersion].Scale\n\n\tswitch requestInfo.Verb {\n\tcase \"get\":\n\t\treturn handlers.GetResource(storage, requestScope)\n\tcase \"update\":\n\t\treturn handlers.UpdateResource(storage, requestScope, r.admission)\n\tcase \"patch\":\n\t\treturn handlers.PatchResource(storage, requestScope, r.admission, supportedTypes)\n\tdefault:\n\t\tresponsewriters.ErrorNegotiated(\n\t\t\tapierrors.NewMethodNotSupported(schema.GroupResource{Group: requestInfo.APIGroup, Resource: requestInfo.Resource}, requestInfo.Verb),\n\t\t\tCodecs, schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}, w, req,\n\t\t)\n\t\treturn nil\n\t}\n}","line":{"from":429,"to":447}} {"id":100014076,"name":"createCustomResourceDefinition","signature":"func (r *crdHandler) createCustomResourceDefinition(obj interface{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"// createCustomResourceDefinition removes potentially stale storage so it gets re-created\nfunc (r *crdHandler) createCustomResourceDefinition(obj interface{}) {\n\tcrd := obj.(*apiextensionsv1.CustomResourceDefinition)\n\tr.customStorageLock.Lock()\n\tdefer r.customStorageLock.Unlock()\n\t// this could happen if the create event is merged from create-update events\n\tstorageMap := r.customStorage.Load().(crdStorageMap)\n\toldInfo, found := storageMap[crd.UID]\n\tif !found {\n\t\treturn\n\t}\n\tif apiequality.Semantic.DeepEqual(\u0026crd.Spec, oldInfo.spec) \u0026\u0026 apiequality.Semantic.DeepEqual(\u0026crd.Status.AcceptedNames, oldInfo.acceptedNames) {\n\t\tklog.V(6).Infof(\"Ignoring customresourcedefinition %s create event because a storage with the same spec and accepted names exists\",\n\t\t\tcrd.Name)\n\t\treturn\n\t}\n\tr.removeStorage_locked(crd.UID)\n}","line":{"from":449,"to":466}} {"id":100014077,"name":"updateCustomResourceDefinition","signature":"func (r *crdHandler) updateCustomResourceDefinition(oldObj, newObj interface{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"// updateCustomResourceDefinition removes potentially stale storage so it gets re-created\nfunc (r *crdHandler) updateCustomResourceDefinition(oldObj, newObj interface{}) {\n\toldCRD := oldObj.(*apiextensionsv1.CustomResourceDefinition)\n\tnewCRD := newObj.(*apiextensionsv1.CustomResourceDefinition)\n\n\tr.customStorageLock.Lock()\n\tdefer r.customStorageLock.Unlock()\n\n\t// Add CRD to the establishing controller queue.\n\t// For HA clusters, we want to prevent race conditions when changing status to Established,\n\t// so we want to be sure that CRD is Installing at least for 5 seconds before Establishing it.\n\t// TODO: find a real HA safe checkpointing mechanism instead of an arbitrary wait.\n\tif !apiextensionshelpers.IsCRDConditionTrue(newCRD, apiextensionsv1.Established) \u0026\u0026\n\t\tapiextensionshelpers.IsCRDConditionTrue(newCRD, apiextensionsv1.NamesAccepted) {\n\t\tif r.masterCount \u003e 1 {\n\t\t\tr.establishingController.QueueCRD(newCRD.Name, 5*time.Second)\n\t\t} else {\n\t\t\tr.establishingController.QueueCRD(newCRD.Name, 0)\n\t\t}\n\t}\n\n\tif oldCRD.UID != newCRD.UID {\n\t\tr.removeStorage_locked(oldCRD.UID)\n\t}\n\n\tstorageMap := r.customStorage.Load().(crdStorageMap)\n\toldInfo, found := storageMap[newCRD.UID]\n\tif !found {\n\t\treturn\n\t}\n\tif apiequality.Semantic.DeepEqual(\u0026newCRD.Spec, oldInfo.spec) \u0026\u0026 apiequality.Semantic.DeepEqual(\u0026newCRD.Status.AcceptedNames, oldInfo.acceptedNames) {\n\t\tklog.V(6).Infof(\"Ignoring customresourcedefinition %s update because neither spec, nor accepted names changed\", oldCRD.Name)\n\t\treturn\n\t}\n\n\tklog.V(4).Infof(\"Updating customresourcedefinition %s\", newCRD.Name)\n\tr.removeStorage_locked(newCRD.UID)\n}","line":{"from":468,"to":505}} {"id":100014078,"name":"removeStorage_locked","signature":"func (r *crdHandler) removeStorage_locked(uid types.UID)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"// removeStorage_locked removes the cached storage with the given uid as key from the storage map. This function\n// updates r.customStorage with the cleaned-up storageMap and tears down the old storage.\n// NOTE: Caller MUST hold r.customStorageLock to write r.customStorage thread-safely.\nfunc (r *crdHandler) removeStorage_locked(uid types.UID) {\n\tstorageMap := r.customStorage.Load().(crdStorageMap)\n\tif oldInfo, ok := storageMap[uid]; ok {\n\t\t// Copy because we cannot write to storageMap without a race\n\t\t// as it is used without locking elsewhere.\n\t\tstorageMap2 := storageMap.clone()\n\n\t\t// Remove from the CRD info map and store the map\n\t\tdelete(storageMap2, uid)\n\t\tr.customStorage.Store(storageMap2)\n\n\t\t// Tear down the old storage\n\t\tgo r.tearDown(oldInfo)\n\t}\n}","line":{"from":507,"to":524}} {"id":100014079,"name":"removeDeadStorage","signature":"func (r *crdHandler) removeDeadStorage()","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"// removeDeadStorage removes REST storage that isn't being used\nfunc (r *crdHandler) removeDeadStorage() {\n\tallCustomResourceDefinitions, err := r.crdLister.List(labels.Everything())\n\tif err != nil {\n\t\tutilruntime.HandleError(err)\n\t\treturn\n\t}\n\n\tr.customStorageLock.Lock()\n\tdefer r.customStorageLock.Unlock()\n\n\tstorageMap := r.customStorage.Load().(crdStorageMap)\n\t// Copy because we cannot write to storageMap without a race\n\tstorageMap2 := make(crdStorageMap)\n\tfor _, crd := range allCustomResourceDefinitions {\n\t\tif _, ok := storageMap[crd.UID]; ok {\n\t\t\tstorageMap2[crd.UID] = storageMap[crd.UID]\n\t\t}\n\t}\n\tr.customStorage.Store(storageMap2)\n\n\tfor uid, crdInfo := range storageMap {\n\t\tif _, ok := storageMap2[uid]; !ok {\n\t\t\tklog.V(4).Infof(\"Removing dead CRD storage for %s/%s\", crdInfo.spec.Group, crdInfo.spec.Names.Kind)\n\t\t\tgo r.tearDown(crdInfo)\n\t\t}\n\t}\n}","line":{"from":526,"to":553}} {"id":100014080,"name":"tearDown","signature":"func (r *crdHandler) tearDown(oldInfo *crdInfo)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"// Wait up to a minute for requests to drain, then tear down storage\nfunc (r *crdHandler) tearDown(oldInfo *crdInfo) {\n\trequestsDrained := make(chan struct{})\n\tgo func() {\n\t\tdefer close(requestsDrained)\n\t\t// Allow time for in-flight requests with a handle to the old info to register themselves\n\t\ttime.Sleep(time.Second)\n\t\t// Wait for in-flight requests to drain\n\t\toldInfo.waitGroup.Wait()\n\t}()\n\n\tselect {\n\tcase \u003c-time.After(r.requestTimeout * 2):\n\t\tklog.Warningf(\"timeout waiting for requests to drain for %s/%s, tearing down storage\", oldInfo.spec.Group, oldInfo.spec.Names.Kind)\n\tcase \u003c-requestsDrained:\n\t}\n\n\tfor _, storage := range oldInfo.storages {\n\t\t// destroy only the main storage. Those for the subresources share cacher and etcd clients.\n\t\tstorage.CustomResource.DestroyFunc()\n\t}\n}","line":{"from":555,"to":576}} {"id":100014081,"name":"destroy","signature":"func (r *crdHandler) destroy()","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"// Destroy shuts down storage layer for all registered CRDs.\n// It should be called as a last step of the shutdown sequence.\nfunc (r *crdHandler) destroy() {\n\tr.customStorageLock.Lock()\n\tdefer r.customStorageLock.Unlock()\n\n\tstorageMap := r.customStorage.Load().(crdStorageMap)\n\tfor _, crdInfo := range storageMap {\n\t\tfor _, storage := range crdInfo.storages {\n\t\t\t// DestroyFunc have to be implemented in idempotent way,\n\t\t\t// so the potential race with r.tearDown() (being called\n\t\t\t// from a goroutine) is safe.\n\t\t\tstorage.CustomResource.DestroyFunc()\n\t\t}\n\t}\n}","line":{"from":578,"to":593}} {"id":100014082,"name":"GetCustomResourceListerCollectionDeleter","signature":"func (r *crdHandler) GetCustomResourceListerCollectionDeleter(crd *apiextensionsv1.CustomResourceDefinition) (finalizer.ListerCollectionDeleter, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"// GetCustomResourceListerCollectionDeleter returns the ListerCollectionDeleter of\n// the given crd.\nfunc (r *crdHandler) GetCustomResourceListerCollectionDeleter(crd *apiextensionsv1.CustomResourceDefinition) (finalizer.ListerCollectionDeleter, error) {\n\tinfo, err := r.getOrCreateServingInfoFor(crd.UID, crd.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn info.storages[info.storageVersion].CustomResource, nil\n}","line":{"from":595,"to":603}} {"id":100014083,"name":"getOrCreateServingInfoFor","signature":"func (r *crdHandler) getOrCreateServingInfoFor(uid types.UID, name string) (*crdInfo, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"// getOrCreateServingInfoFor gets the CRD serving info for the given CRD UID if the key exists in the storage map.\n// Otherwise the function fetches the up-to-date CRD using the given CRD name and creates CRD serving info.\nfunc (r *crdHandler) getOrCreateServingInfoFor(uid types.UID, name string) (*crdInfo, error) {\n\tstorageMap := r.customStorage.Load().(crdStorageMap)\n\tif ret, ok := storageMap[uid]; ok {\n\t\treturn ret, nil\n\t}\n\n\tr.customStorageLock.Lock()\n\tdefer r.customStorageLock.Unlock()\n\n\t// Get the up-to-date CRD when we have the lock, to avoid racing with updateCustomResourceDefinition.\n\t// If updateCustomResourceDefinition sees an update and happens later, the storage will be deleted and\n\t// we will re-create the updated storage on demand. If updateCustomResourceDefinition happens before,\n\t// we make sure that we observe the same up-to-date CRD.\n\tcrd, err := r.crdLister.Get(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstorageMap = r.customStorage.Load().(crdStorageMap)\n\tif ret, ok := storageMap[crd.UID]; ok {\n\t\treturn ret, nil\n\t}\n\n\tstorageVersion, err := apiextensionshelpers.GetCRDStorageVersion(crd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Scope/Storages per version.\n\trequestScopes := map[string]*handlers.RequestScope{}\n\tstorages := map[string]customresource.CustomResourceStorage{}\n\tstatusScopes := map[string]*handlers.RequestScope{}\n\tscaleScopes := map[string]*handlers.RequestScope{}\n\tdeprecated := map[string]bool{}\n\twarnings := map[string][]string{}\n\n\tequivalentResourceRegistry := runtime.NewEquivalentResourceRegistry()\n\n\tstructuralSchemas := map[string]*structuralschema.Structural{}\n\tfor _, v := range crd.Spec.Versions {\n\t\tval, err := apiextensionshelpers.GetSchemaForVersion(crd, v.Name)\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(err)\n\t\t\treturn nil, fmt.Errorf(\"the server could not properly serve the CR schema\")\n\t\t}\n\t\tif val == nil {\n\t\t\tcontinue\n\t\t}\n\t\tinternalValidation := \u0026apiextensionsinternal.CustomResourceValidation{}\n\t\tif err := apiextensionsv1.Convert_v1_CustomResourceValidation_To_apiextensions_CustomResourceValidation(val, internalValidation, nil); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed converting CRD validation to internal version: %v\", err)\n\t\t}\n\t\ts, err := structuralschema.NewStructural(internalValidation.OpenAPIV3Schema)\n\t\tif crd.Spec.PreserveUnknownFields == false \u0026\u0026 err != nil {\n\t\t\t// This should never happen. If it does, it is a programming error.\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"failed to convert schema to structural: %v\", err))\n\t\t\treturn nil, fmt.Errorf(\"the server could not properly serve the CR schema\") // validation should avoid this\n\t\t}\n\n\t\tif crd.Spec.PreserveUnknownFields == false {\n\t\t\t// we don't own s completely, e.g. defaults are not deep-copied. So better make a copy here.\n\t\t\ts = s.DeepCopy()\n\n\t\t\tif err := structuraldefaulting.PruneDefaults(s); err != nil {\n\t\t\t\t// This should never happen. If it does, it is a programming error.\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"failed to prune defaults: %v\", err))\n\t\t\t\treturn nil, fmt.Errorf(\"the server could not properly serve the CR schema\") // validation should avoid this\n\t\t\t}\n\t\t}\n\t\tstructuralSchemas[v.Name] = s\n\t}\n\n\topenAPIModels, err := buildOpenAPIModelsForApply(r.staticOpenAPISpec, crd)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"error building openapi models for %s: %v\", crd.Name, err))\n\t\topenAPIModels = nil\n\t}\n\n\tvar typeConverter managedfields.TypeConverter = managedfields.NewDeducedTypeConverter()\n\tif len(openAPIModels) \u003e 0 {\n\t\ttypeConverter, err = managedfields.NewTypeConverter(openAPIModels, crd.Spec.PreserveUnknownFields)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tsafeConverter, unsafeConverter, err := r.converterFactory.NewConverter(crd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create replicasPathInCustomResource\n\treplicasPathInCustomResource := managedfields.ResourcePathMappings{}\n\tfor _, v := range crd.Spec.Versions {\n\t\tsubresources, err := apiextensionshelpers.GetSubresourcesForVersion(crd, v.Name)\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(err)\n\t\t\treturn nil, fmt.Errorf(\"the server could not properly serve the CR subresources\")\n\t\t}\n\t\tif subresources == nil || subresources.Scale == nil {\n\t\t\treplicasPathInCustomResource[schema.GroupVersion{Group: crd.Spec.Group, Version: v.Name}.String()] = nil\n\t\t\tcontinue\n\t\t}\n\t\tpath := fieldpath.Path{}\n\t\tsplitReplicasPath := strings.Split(strings.TrimPrefix(subresources.Scale.SpecReplicasPath, \".\"), \".\")\n\t\tfor _, element := range splitReplicasPath {\n\t\t\ts := element\n\t\t\tpath = append(path, fieldpath.PathElement{FieldName: \u0026s})\n\t\t}\n\t\treplicasPathInCustomResource[schema.GroupVersion{Group: crd.Spec.Group, Version: v.Name}.String()] = path\n\t}\n\n\tfor _, v := range crd.Spec.Versions {\n\t\t// In addition to Unstructured objects (Custom Resources), we also may sometimes need to\n\t\t// decode unversioned Options objects, so we delegate to parameterScheme for such types.\n\t\tparameterScheme := runtime.NewScheme()\n\t\tparameterScheme.AddUnversionedTypes(schema.GroupVersion{Group: crd.Spec.Group, Version: v.Name},\n\t\t\t\u0026metav1.ListOptions{},\n\t\t\t\u0026metav1.GetOptions{},\n\t\t\t\u0026metav1.DeleteOptions{},\n\t\t)\n\t\tparameterCodec := runtime.NewParameterCodec(parameterScheme)\n\n\t\tresource := schema.GroupVersionResource{Group: crd.Spec.Group, Version: v.Name, Resource: crd.Status.AcceptedNames.Plural}\n\t\tsingularResource := schema.GroupVersionResource{Group: crd.Spec.Group, Version: v.Name, Resource: crd.Status.AcceptedNames.Singular}\n\t\tkind := schema.GroupVersionKind{Group: crd.Spec.Group, Version: v.Name, Kind: crd.Status.AcceptedNames.Kind}\n\t\tequivalentResourceRegistry.RegisterKindFor(resource, \"\", kind)\n\n\t\ttyper := newUnstructuredObjectTyper(parameterScheme)\n\t\tcreator := unstructuredCreator{}\n\n\t\tvalidationSchema, err := apiextensionshelpers.GetSchemaForVersion(crd, v.Name)\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(err)\n\t\t\treturn nil, fmt.Errorf(\"the server could not properly serve the CR schema\")\n\t\t}\n\t\tvar internalValidationSchema *apiextensionsinternal.CustomResourceValidation\n\t\tif validationSchema != nil {\n\t\t\tinternalValidationSchema = \u0026apiextensionsinternal.CustomResourceValidation{}\n\t\t\tif err := apiextensionsv1.Convert_v1_CustomResourceValidation_To_apiextensions_CustomResourceValidation(validationSchema, internalValidationSchema, nil); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to convert CRD validation to internal version: %v\", err)\n\t\t\t}\n\t\t}\n\t\tvalidator, _, err := apiservervalidation.NewSchemaValidator(internalValidationSchema)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar statusSpec *apiextensionsinternal.CustomResourceSubresourceStatus\n\t\tvar statusValidator *validate.SchemaValidator\n\t\tsubresources, err := apiextensionshelpers.GetSubresourcesForVersion(crd, v.Name)\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(err)\n\t\t\treturn nil, fmt.Errorf(\"the server could not properly serve the CR subresources\")\n\t\t}\n\t\tif subresources != nil \u0026\u0026 subresources.Status != nil {\n\t\t\tequivalentResourceRegistry.RegisterKindFor(resource, \"status\", kind)\n\t\t\tstatusSpec = \u0026apiextensionsinternal.CustomResourceSubresourceStatus{}\n\t\t\tif err := apiextensionsv1.Convert_v1_CustomResourceSubresourceStatus_To_apiextensions_CustomResourceSubresourceStatus(subresources.Status, statusSpec, nil); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed converting CRD status subresource to internal version: %v\", err)\n\t\t\t}\n\t\t\t// for the status subresource, validate only against the status schema\n\t\t\tif internalValidationSchema != nil \u0026\u0026 internalValidationSchema.OpenAPIV3Schema != nil \u0026\u0026 internalValidationSchema.OpenAPIV3Schema.Properties != nil {\n\t\t\t\tif statusSchema, ok := internalValidationSchema.OpenAPIV3Schema.Properties[\"status\"]; ok {\n\t\t\t\t\topenapiSchema := \u0026spec.Schema{}\n\t\t\t\t\tif err := apiservervalidation.ConvertJSONSchemaPropsWithPostProcess(\u0026statusSchema, openapiSchema, apiservervalidation.StripUnsupportedFormatsPostProcess); err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tstatusValidator = validate.NewSchemaValidator(openapiSchema, nil, \"\", strfmt.Default)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvar scaleSpec *apiextensionsinternal.CustomResourceSubresourceScale\n\t\tif subresources != nil \u0026\u0026 subresources.Scale != nil {\n\t\t\tequivalentResourceRegistry.RegisterKindFor(resource, \"scale\", autoscalingv1.SchemeGroupVersion.WithKind(\"Scale\"))\n\t\t\tscaleSpec = \u0026apiextensionsinternal.CustomResourceSubresourceScale{}\n\t\t\tif err := apiextensionsv1.Convert_v1_CustomResourceSubresourceScale_To_apiextensions_CustomResourceSubresourceScale(subresources.Scale, scaleSpec, nil); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed converting CRD status subresource to internal version: %v\", err)\n\t\t\t}\n\t\t}\n\n\t\tcolumns, err := getColumnsForVersion(crd, v.Name)\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(err)\n\t\t\treturn nil, fmt.Errorf(\"the server could not properly serve the CR columns\")\n\t\t}\n\t\ttable, err := tableconvertor.New(columns)\n\t\tif err != nil {\n\t\t\tklog.V(2).Infof(\"The CRD for %v has an invalid printer specification, falling back to default printing: %v\", kind, err)\n\t\t}\n\n\t\tstorages[v.Name] = customresource.NewStorage(\n\t\t\tresource.GroupResource(),\n\t\t\tsingularResource.GroupResource(),\n\t\t\tkind,\n\t\t\tschema.GroupVersionKind{Group: crd.Spec.Group, Version: v.Name, Kind: crd.Status.AcceptedNames.ListKind},\n\t\t\tcustomresource.NewStrategy(\n\t\t\t\ttyper,\n\t\t\t\tcrd.Spec.Scope == apiextensionsv1.NamespaceScoped,\n\t\t\t\tkind,\n\t\t\t\tvalidator,\n\t\t\t\tstatusValidator,\n\t\t\t\tstructuralSchemas,\n\t\t\t\tstatusSpec,\n\t\t\t\tscaleSpec,\n\t\t\t),\n\t\t\tcrdConversionRESTOptionsGetter{\n\t\t\t\tRESTOptionsGetter: r.restOptionsGetter,\n\t\t\t\tconverter: safeConverter,\n\t\t\t\tdecoderVersion: schema.GroupVersion{Group: crd.Spec.Group, Version: v.Name},\n\t\t\t\tencoderVersion: schema.GroupVersion{Group: crd.Spec.Group, Version: storageVersion},\n\t\t\t\tstructuralSchemas: structuralSchemas,\n\t\t\t\tstructuralSchemaGK: kind.GroupKind(),\n\t\t\t\tpreserveUnknownFields: crd.Spec.PreserveUnknownFields,\n\t\t\t},\n\t\t\tcrd.Status.AcceptedNames.Categories,\n\t\t\ttable,\n\t\t\treplicasPathInCustomResource,\n\t\t)\n\n\t\tclusterScoped := crd.Spec.Scope == apiextensionsv1.ClusterScoped\n\n\t\t// CRDs explicitly do not support protobuf, but some objects returned by the API server do\n\t\tnegotiatedSerializer := unstructuredNegotiatedSerializer{\n\t\t\ttyper: typer,\n\t\t\tcreator: creator,\n\t\t\tconverter: safeConverter,\n\t\t\tstructuralSchemas: structuralSchemas,\n\t\t\tstructuralSchemaGK: kind.GroupKind(),\n\t\t\tpreserveUnknownFields: crd.Spec.PreserveUnknownFields,\n\t\t}\n\t\tvar standardSerializers []runtime.SerializerInfo\n\t\tfor _, s := range negotiatedSerializer.SupportedMediaTypes() {\n\t\t\tif s.MediaType == runtime.ContentTypeProtobuf {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstandardSerializers = append(standardSerializers, s)\n\t\t}\n\n\t\treqScope := handlers.RequestScope{\n\t\t\tNamer: handlers.ContextBasedNaming{\n\t\t\t\tNamer: meta.NewAccessor(),\n\t\t\t\tClusterScoped: clusterScoped,\n\t\t\t},\n\t\t\tSerializer: negotiatedSerializer,\n\t\t\tParameterCodec: parameterCodec,\n\t\t\tStandardSerializers: standardSerializers,\n\n\t\t\tCreater: creator,\n\t\t\tConvertor: safeConverter,\n\t\t\tDefaulter: unstructuredDefaulter{parameterScheme, structuralSchemas, kind.GroupKind()},\n\t\t\tTyper: typer,\n\t\t\tUnsafeConvertor: unsafeConverter,\n\n\t\t\tEquivalentResourceMapper: equivalentResourceRegistry,\n\n\t\t\tResource: schema.GroupVersionResource{Group: crd.Spec.Group, Version: v.Name, Resource: crd.Status.AcceptedNames.Plural},\n\t\t\tKind: kind,\n\n\t\t\t// a handler for a specific group-version of a custom resource uses that version as the in-memory representation\n\t\t\tHubGroupVersion: kind.GroupVersion(),\n\n\t\t\tMetaGroupVersion: metav1.SchemeGroupVersion,\n\n\t\t\tTableConvertor: storages[v.Name].CustomResource,\n\n\t\t\tAuthorizer: r.authorizer,\n\n\t\t\tMaxRequestBodyBytes: r.maxRequestBodyBytes,\n\t\t}\n\n\t\tresetFields := storages[v.Name].CustomResource.GetResetFields()\n\t\treqScope, err = scopeWithFieldManager(\n\t\t\ttypeConverter,\n\t\t\treqScope,\n\t\t\tresetFields,\n\t\t\t\"\",\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trequestScopes[v.Name] = \u0026reqScope\n\n\t\tscaleColumns, err := getScaleColumnsForVersion(crd, v.Name)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"the server could not properly serve the CR scale subresource columns %w\", err)\n\t\t}\n\t\tscaleTable, _ := tableconvertor.New(scaleColumns)\n\n\t\t// override scale subresource values\n\t\t// shallow copy\n\t\tscaleScope := *requestScopes[v.Name]\n\t\tscaleConverter := scale.NewScaleConverter()\n\t\tscaleScope.Subresource = \"scale\"\n\t\tscaleScope.Serializer = serializer.NewCodecFactory(scaleConverter.Scheme())\n\t\tscaleScope.Kind = autoscalingv1.SchemeGroupVersion.WithKind(\"Scale\")\n\t\tscaleScope.Namer = handlers.ContextBasedNaming{\n\t\t\tNamer: meta.NewAccessor(),\n\t\t\tClusterScoped: clusterScoped,\n\t\t}\n\t\tscaleScope.TableConvertor = scaleTable\n\n\t\tif subresources != nil \u0026\u0026 subresources.Scale != nil {\n\t\t\tscaleScope, err = scopeWithFieldManager(\n\t\t\t\ttypeConverter,\n\t\t\t\tscaleScope,\n\t\t\t\tnil,\n\t\t\t\t\"scale\",\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\tscaleScopes[v.Name] = \u0026scaleScope\n\n\t\t// override status subresource values\n\t\t// shallow copy\n\t\tstatusScope := *requestScopes[v.Name]\n\t\tstatusScope.Subresource = \"status\"\n\t\tstatusScope.Namer = handlers.ContextBasedNaming{\n\t\t\tNamer: meta.NewAccessor(),\n\t\t\tClusterScoped: clusterScoped,\n\t\t}\n\n\t\tif subresources != nil \u0026\u0026 subresources.Status != nil {\n\t\t\tresetFields := storages[v.Name].Status.GetResetFields()\n\t\t\tstatusScope, err = scopeWithFieldManager(\n\t\t\t\ttypeConverter,\n\t\t\t\tstatusScope,\n\t\t\t\tresetFields,\n\t\t\t\t\"status\",\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\tstatusScopes[v.Name] = \u0026statusScope\n\n\t\tif v.Deprecated {\n\t\t\tdeprecated[v.Name] = true\n\t\t\tif v.DeprecationWarning != nil {\n\t\t\t\twarnings[v.Name] = append(warnings[v.Name], *v.DeprecationWarning)\n\t\t\t} else {\n\t\t\t\twarnings[v.Name] = append(warnings[v.Name], defaultDeprecationWarning(v.Name, crd.Spec))\n\t\t\t}\n\t\t}\n\t}\n\n\tret := \u0026crdInfo{\n\t\tspec: \u0026crd.Spec,\n\t\tacceptedNames: \u0026crd.Status.AcceptedNames,\n\t\tstorages: storages,\n\t\trequestScopes: requestScopes,\n\t\tscaleRequestScopes: scaleScopes,\n\t\tstatusRequestScopes: statusScopes,\n\t\tdeprecated: deprecated,\n\t\twarnings: warnings,\n\t\tstorageVersion: storageVersion,\n\t\twaitGroup: \u0026utilwaitgroup.SafeWaitGroup{},\n\t}\n\n\t// Copy because we cannot write to storageMap without a race\n\t// as it is used without locking elsewhere.\n\tstorageMap2 := storageMap.clone()\n\n\tstorageMap2[crd.UID] = ret\n\tr.customStorage.Store(storageMap2)\n\n\treturn ret, nil\n}","line":{"from":605,"to":978}} {"id":100014084,"name":"scopeWithFieldManager","signature":"func scopeWithFieldManager(typeConverter managedfields.TypeConverter, reqScope handlers.RequestScope, resetFields map[fieldpath.APIVersion]*fieldpath.Set, subresource string) (handlers.RequestScope, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"func scopeWithFieldManager(typeConverter managedfields.TypeConverter, reqScope handlers.RequestScope, resetFields map[fieldpath.APIVersion]*fieldpath.Set, subresource string) (handlers.RequestScope, error) {\n\tfieldManager, err := managedfields.NewDefaultCRDFieldManager(\n\t\ttypeConverter,\n\t\treqScope.Convertor,\n\t\treqScope.Defaulter,\n\t\treqScope.Creater,\n\t\treqScope.Kind,\n\t\treqScope.HubGroupVersion,\n\t\tsubresource,\n\t\tresetFields,\n\t)\n\tif err != nil {\n\t\treturn handlers.RequestScope{}, err\n\t}\n\treqScope.FieldManager = fieldManager\n\treturn reqScope, nil\n}","line":{"from":980,"to":996}} {"id":100014085,"name":"defaultDeprecationWarning","signature":"func defaultDeprecationWarning(deprecatedVersion string, crd apiextensionsv1.CustomResourceDefinitionSpec) string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"func defaultDeprecationWarning(deprecatedVersion string, crd apiextensionsv1.CustomResourceDefinitionSpec) string {\n\tmsg := fmt.Sprintf(\"%s/%s %s is deprecated\", crd.Group, deprecatedVersion, crd.Names.Kind)\n\n\tvar servedNonDeprecatedVersions []string\n\tfor _, v := range crd.Versions {\n\t\tif v.Served \u0026\u0026 !v.Deprecated \u0026\u0026 version.CompareKubeAwareVersionStrings(deprecatedVersion, v.Name) \u003c 0 {\n\t\t\tservedNonDeprecatedVersions = append(servedNonDeprecatedVersions, v.Name)\n\t\t}\n\t}\n\tif len(servedNonDeprecatedVersions) == 0 {\n\t\treturn msg\n\t}\n\tsort.Slice(servedNonDeprecatedVersions, func(i, j int) bool {\n\t\treturn version.CompareKubeAwareVersionStrings(servedNonDeprecatedVersions[i], servedNonDeprecatedVersions[j]) \u003e 0\n\t})\n\tmsg += fmt.Sprintf(\"; use %s/%s %s\", crd.Group, servedNonDeprecatedVersions[0], crd.Names.Kind)\n\treturn msg\n}","line":{"from":998,"to":1015}} {"id":100014086,"name":"SupportedMediaTypes","signature":"func (s unstructuredNegotiatedSerializer) SupportedMediaTypes() []runtime.SerializerInfo","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"func (s unstructuredNegotiatedSerializer) SupportedMediaTypes() []runtime.SerializerInfo {\n\treturn []runtime.SerializerInfo{\n\t\t{\n\t\t\tMediaType: \"application/json\",\n\t\t\tMediaTypeType: \"application\",\n\t\t\tMediaTypeSubType: \"json\",\n\t\t\tEncodesAsText: true,\n\t\t\tSerializer: json.NewSerializer(json.DefaultMetaFactory, s.creator, s.typer, false),\n\t\t\tPrettySerializer: json.NewSerializer(json.DefaultMetaFactory, s.creator, s.typer, true),\n\t\t\tStrictSerializer: json.NewSerializerWithOptions(json.DefaultMetaFactory, s.creator, s.typer, json.SerializerOptions{\n\t\t\t\tStrict: true,\n\t\t\t}),\n\t\t\tStreamSerializer: \u0026runtime.StreamSerializerInfo{\n\t\t\t\tEncodesAsText: true,\n\t\t\t\tSerializer: json.NewSerializer(json.DefaultMetaFactory, s.creator, s.typer, false),\n\t\t\t\tFramer: json.Framer,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tMediaType: \"application/yaml\",\n\t\t\tMediaTypeType: \"application\",\n\t\t\tMediaTypeSubType: \"yaml\",\n\t\t\tEncodesAsText: true,\n\t\t\tSerializer: json.NewYAMLSerializer(json.DefaultMetaFactory, s.creator, s.typer),\n\t\t\tStrictSerializer: json.NewSerializerWithOptions(json.DefaultMetaFactory, s.creator, s.typer, json.SerializerOptions{\n\t\t\t\tYaml: true,\n\t\t\t\tStrict: true,\n\t\t\t}),\n\t\t},\n\t\t{\n\t\t\tMediaType: \"application/vnd.kubernetes.protobuf\",\n\t\t\tMediaTypeType: \"application\",\n\t\t\tMediaTypeSubType: \"vnd.kubernetes.protobuf\",\n\t\t\tSerializer: protobuf.NewSerializer(s.creator, s.typer),\n\t\t\tStreamSerializer: \u0026runtime.StreamSerializerInfo{\n\t\t\t\tSerializer: protobuf.NewRawSerializer(s.creator, s.typer),\n\t\t\t\tFramer: protobuf.LengthDelimitedFramer,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":1027,"to":1067}} {"id":100014087,"name":"EncoderForVersion","signature":"func (s unstructuredNegotiatedSerializer) EncoderForVersion(encoder runtime.Encoder, gv runtime.GroupVersioner) runtime.Encoder","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"func (s unstructuredNegotiatedSerializer) EncoderForVersion(encoder runtime.Encoder, gv runtime.GroupVersioner) runtime.Encoder {\n\treturn versioning.NewCodec(encoder, nil, s.converter, Scheme, Scheme, Scheme, gv, nil, \"crdNegotiatedSerializer\")\n}","line":{"from":1069,"to":1071}} {"id":100014088,"name":"DecoderToVersion","signature":"func (s unstructuredNegotiatedSerializer) DecoderToVersion(decoder runtime.Decoder, gv runtime.GroupVersioner) runtime.Decoder","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"func (s unstructuredNegotiatedSerializer) DecoderToVersion(decoder runtime.Decoder, gv runtime.GroupVersioner) runtime.Decoder {\n\treturnUnknownFieldPaths := false\n\tif serializer, ok := decoder.(*json.Serializer); ok {\n\t\treturnUnknownFieldPaths = serializer.IsStrict()\n\t}\n\td := schemaCoercingDecoder{delegate: decoder, validator: unstructuredSchemaCoercer{structuralSchemas: s.structuralSchemas, structuralSchemaGK: s.structuralSchemaGK, preserveUnknownFields: s.preserveUnknownFields, returnUnknownFieldPaths: returnUnknownFieldPaths}}\n\treturn versioning.NewCodec(nil, d, runtime.UnsafeObjectConvertor(Scheme), Scheme, Scheme, unstructuredDefaulter{\n\t\tdelegate: Scheme,\n\t\tstructuralSchemas: s.structuralSchemas,\n\t\tstructuralSchemaGK: s.structuralSchemaGK,\n\t}, nil, gv, \"unstructuredNegotiatedSerializer\")\n}","line":{"from":1073,"to":1084}} {"id":100014089,"name":"newUnstructuredObjectTyper","signature":"func newUnstructuredObjectTyper(Delegate runtime.ObjectTyper) UnstructuredObjectTyper","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"func newUnstructuredObjectTyper(Delegate runtime.ObjectTyper) UnstructuredObjectTyper {\n\treturn UnstructuredObjectTyper{\n\t\tDelegate: Delegate,\n\t\tUnstructuredTyper: crdserverscheme.NewUnstructuredObjectTyper(),\n\t}\n}","line":{"from":1091,"to":1096}} {"id":100014090,"name":"ObjectKinds","signature":"func (t UnstructuredObjectTyper) ObjectKinds(obj runtime.Object) ([]schema.GroupVersionKind, bool, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"func (t UnstructuredObjectTyper) ObjectKinds(obj runtime.Object) ([]schema.GroupVersionKind, bool, error) {\n\t// Delegate for things other than Unstructured.\n\tif _, ok := obj.(runtime.Unstructured); !ok {\n\t\treturn t.Delegate.ObjectKinds(obj)\n\t}\n\treturn t.UnstructuredTyper.ObjectKinds(obj)\n}","line":{"from":1098,"to":1104}} {"id":100014091,"name":"Recognizes","signature":"func (t UnstructuredObjectTyper) Recognizes(gvk schema.GroupVersionKind) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"func (t UnstructuredObjectTyper) Recognizes(gvk schema.GroupVersionKind) bool {\n\treturn t.Delegate.Recognizes(gvk) || t.UnstructuredTyper.Recognizes(gvk)\n}","line":{"from":1106,"to":1108}} {"id":100014092,"name":"New","signature":"func (c unstructuredCreator) New(kind schema.GroupVersionKind) (runtime.Object, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"func (c unstructuredCreator) New(kind schema.GroupVersionKind) (runtime.Object, error) {\n\tret := \u0026unstructured.Unstructured{}\n\tret.SetGroupVersionKind(kind)\n\treturn ret, nil\n}","line":{"from":1112,"to":1116}} {"id":100014093,"name":"Default","signature":"func (d unstructuredDefaulter) Default(in runtime.Object)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"func (d unstructuredDefaulter) Default(in runtime.Object) {\n\t// Delegate for things other than Unstructured, and other GKs\n\tu, ok := in.(runtime.Unstructured)\n\tif !ok || u.GetObjectKind().GroupVersionKind().GroupKind() != d.structuralSchemaGK {\n\t\td.delegate.Default(in)\n\t\treturn\n\t}\n\n\tstructuraldefaulting.Default(u.UnstructuredContent(), d.structuralSchemas[u.GetObjectKind().GroupVersionKind().Version])\n}","line":{"from":1124,"to":1133}} {"id":100014094,"name":"clone","signature":"func (in crdStorageMap) clone() crdStorageMap","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"// clone returns a clone of the provided crdStorageMap.\n// The clone is a shallow copy of the map.\nfunc (in crdStorageMap) clone() crdStorageMap {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := make(crdStorageMap, len(in))\n\tfor key, value := range in {\n\t\tout[key] = value\n\t}\n\treturn out\n}","line":{"from":1135,"to":1146}} {"id":100014095,"name":"GetRESTOptions","signature":"func (t crdConversionRESTOptionsGetter) GetRESTOptions(resource schema.GroupResource) (generic.RESTOptions, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"func (t crdConversionRESTOptionsGetter) GetRESTOptions(resource schema.GroupResource) (generic.RESTOptions, error) {\n\tret, err := t.RESTOptionsGetter.GetRESTOptions(resource)\n\tif err == nil {\n\t\td := schemaCoercingDecoder{delegate: ret.StorageConfig.Codec, validator: unstructuredSchemaCoercer{\n\t\t\t// drop invalid fields while decoding old CRs (before we haven't had any ObjectMeta validation)\n\t\t\tdropInvalidMetadata: true,\n\t\t\trepairGeneration: true,\n\t\t\tstructuralSchemas: t.structuralSchemas,\n\t\t\tstructuralSchemaGK: t.structuralSchemaGK,\n\t\t\tpreserveUnknownFields: t.preserveUnknownFields,\n\t\t}}\n\t\tc := schemaCoercingConverter{delegate: t.converter, validator: unstructuredSchemaCoercer{\n\t\t\tstructuralSchemas: t.structuralSchemas,\n\t\t\tstructuralSchemaGK: t.structuralSchemaGK,\n\t\t\tpreserveUnknownFields: t.preserveUnknownFields,\n\t\t}}\n\t\tret.StorageConfig.Codec = versioning.NewCodec(\n\t\t\tret.StorageConfig.Codec,\n\t\t\td,\n\t\t\tc,\n\t\t\t\u0026unstructuredCreator{},\n\t\t\tcrdserverscheme.NewUnstructuredObjectTyper(),\n\t\t\t\u0026unstructuredDefaulter{\n\t\t\t\tdelegate: Scheme,\n\t\t\t\tstructuralSchemaGK: t.structuralSchemaGK,\n\t\t\t\tstructuralSchemas: t.structuralSchemas,\n\t\t\t},\n\t\t\tt.encoderVersion,\n\t\t\tt.decoderVersion,\n\t\t\t\"crdRESTOptions\",\n\t\t)\n\t}\n\treturn ret, err\n}","line":{"from":1160,"to":1193}} {"id":100014096,"name":"Decode","signature":"func (d schemaCoercingDecoder) Decode(data []byte, defaults *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"func (d schemaCoercingDecoder) Decode(data []byte, defaults *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {\n\tvar decodingStrictErrs []error\n\tobj, gvk, err := d.delegate.Decode(data, defaults, into)\n\tif err != nil {\n\t\tdecodeStrictErr, ok := runtime.AsStrictDecodingError(err)\n\t\tif !ok || obj == nil {\n\t\t\treturn nil, gvk, err\n\t\t}\n\t\tdecodingStrictErrs = decodeStrictErr.Errors()\n\t}\n\tvar unknownFields []string\n\tif u, ok := obj.(*unstructured.Unstructured); ok {\n\t\tunknownFields, err = d.validator.apply(u)\n\t\tif err != nil {\n\t\t\treturn nil, gvk, err\n\t\t}\n\t}\n\tif d.validator.returnUnknownFieldPaths \u0026\u0026 (len(decodingStrictErrs) \u003e 0 || len(unknownFields) \u003e 0) {\n\t\tfor _, unknownField := range unknownFields {\n\t\t\tdecodingStrictErrs = append(decodingStrictErrs, fmt.Errorf(`unknown field \"%s\"`, unknownField))\n\t\t}\n\t\treturn obj, gvk, runtime.NewStrictDecodingError(decodingStrictErrs)\n\t}\n\n\treturn obj, gvk, nil\n}","line":{"from":1204,"to":1229}} {"id":100014097,"name":"Convert","signature":"func (v schemaCoercingConverter) Convert(in, out, context interface{}) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"func (v schemaCoercingConverter) Convert(in, out, context interface{}) error {\n\tif err := v.delegate.Convert(in, out, context); err != nil {\n\t\treturn err\n\t}\n\n\tif u, ok := out.(*unstructured.Unstructured); ok {\n\t\tif _, err := v.validator.apply(u); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":1240,"to":1252}} {"id":100014098,"name":"ConvertToVersion","signature":"func (v schemaCoercingConverter) ConvertToVersion(in runtime.Object, gv runtime.GroupVersioner) (runtime.Object, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"func (v schemaCoercingConverter) ConvertToVersion(in runtime.Object, gv runtime.GroupVersioner) (runtime.Object, error) {\n\tout, err := v.delegate.ConvertToVersion(in, gv)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif u, ok := out.(*unstructured.Unstructured); ok {\n\t\tif _, err := v.validator.apply(u); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn out, nil\n}","line":{"from":1254,"to":1267}} {"id":100014099,"name":"ConvertFieldLabel","signature":"func (v schemaCoercingConverter) ConvertFieldLabel(gvk schema.GroupVersionKind, label, value string) (string, string, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"func (v schemaCoercingConverter) ConvertFieldLabel(gvk schema.GroupVersionKind, label, value string) (string, string, error) {\n\treturn v.delegate.ConvertFieldLabel(gvk, label, value)\n}","line":{"from":1269,"to":1271}} {"id":100014100,"name":"apply","signature":"func (v *unstructuredSchemaCoercer) apply(u *unstructured.Unstructured) (unknownFieldPaths []string, err error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"func (v *unstructuredSchemaCoercer) apply(u *unstructured.Unstructured) (unknownFieldPaths []string, err error) {\n\t// save implicit meta fields that don't have to be specified in the validation spec\n\tkind, foundKind, err := unstructured.NestedString(u.UnstructuredContent(), \"kind\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tapiVersion, foundApiVersion, err := unstructured.NestedString(u.UnstructuredContent(), \"apiVersion\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tobjectMeta, foundObjectMeta, metaUnknownFields, err := schemaobjectmeta.GetObjectMetaWithOptions(u.Object, schemaobjectmeta.ObjectMetaOptions{\n\t\tDropMalformedFields: v.dropInvalidMetadata,\n\t\tReturnUnknownFieldPaths: v.returnUnknownFieldPaths,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tunknownFieldPaths = append(unknownFieldPaths, metaUnknownFields...)\n\n\t// compare group and kind because also other object like DeleteCollection options pass through here\n\tgv, err := schema.ParseGroupVersion(apiVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif gv.Group == v.structuralSchemaGK.Group \u0026\u0026 kind == v.structuralSchemaGK.Kind {\n\t\tif !v.preserveUnknownFields {\n\t\t\t// TODO: switch over pruning and coercing at the root to schemaobjectmeta.Coerce too\n\t\t\tpruneOpts := structuralschema.UnknownFieldPathOptions{}\n\t\t\tif v.returnUnknownFieldPaths {\n\t\t\t\tpruneOpts.TrackUnknownFieldPaths = true\n\t\t\t}\n\t\t\tunknownFieldPaths = append(unknownFieldPaths, structuralpruning.PruneWithOptions(u.Object, v.structuralSchemas[gv.Version], true, pruneOpts)...)\n\t\t\tstructuraldefaulting.PruneNonNullableNullsWithoutDefaults(u.Object, v.structuralSchemas[gv.Version])\n\t\t}\n\n\t\terr, paths := schemaobjectmeta.CoerceWithOptions(nil, u.Object, v.structuralSchemas[gv.Version], false, schemaobjectmeta.CoerceOptions{\n\t\t\tDropInvalidFields: v.dropInvalidMetadata,\n\t\t\tReturnUnknownFieldPaths: v.returnUnknownFieldPaths,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tunknownFieldPaths = append(unknownFieldPaths, paths...)\n\n\t\t// fixup missing generation in very old CRs\n\t\tif v.repairGeneration \u0026\u0026 objectMeta.Generation == 0 {\n\t\t\tobjectMeta.Generation = 1\n\t\t}\n\t}\n\n\t// restore meta fields, starting clean\n\tif foundKind {\n\t\tu.SetKind(kind)\n\t}\n\tif foundApiVersion {\n\t\tu.SetAPIVersion(apiVersion)\n\t}\n\tif foundObjectMeta {\n\t\tif err := schemaobjectmeta.SetObjectMeta(u.Object, objectMeta); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn unknownFieldPaths, nil\n}","line":{"from":1289,"to":1354}} {"id":100014101,"name":"hasServedCRDVersion","signature":"func hasServedCRDVersion(spec *apiextensionsv1.CustomResourceDefinitionSpec, version string) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"// hasServedCRDVersion returns true if the given version is in the list of CRD's versions and the Served flag is set.\nfunc hasServedCRDVersion(spec *apiextensionsv1.CustomResourceDefinitionSpec, version string) bool {\n\tfor _, v := range spec.Versions {\n\t\tif v.Name == version {\n\t\t\treturn v.Served\n\t\t}\n\t}\n\treturn false\n}","line":{"from":1356,"to":1364}} {"id":100014102,"name":"buildOpenAPIModelsForApply","signature":"func buildOpenAPIModelsForApply(staticOpenAPISpec map[string]*spec.Schema, crd *apiextensionsv1.CustomResourceDefinition) (map[string]*spec.Schema, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go","code":"// buildOpenAPIModelsForApply constructs openapi models from any validation schemas specified in the custom resource,\n// and merges it with the models defined in the static OpenAPI spec.\n// Returns nil models ifthe static spec is nil, or an error is encountered.\nfunc buildOpenAPIModelsForApply(staticOpenAPISpec map[string]*spec.Schema, crd *apiextensionsv1.CustomResourceDefinition) (map[string]*spec.Schema, error) {\n\tif staticOpenAPISpec == nil {\n\t\treturn nil, nil\n\t}\n\n\t// Convert static spec to V3 format to be able to merge\n\tstaticSpecV3 := \u0026spec3.OpenAPI{\n\t\tVersion: \"3.0.0\",\n\t\tInfo: \u0026spec.Info{\n\t\t\tInfoProps: spec.InfoProps{\n\t\t\t\tTitle: \"Kubernetes CRD Swagger\",\n\t\t\t\tVersion: \"v0.1.0\",\n\t\t\t},\n\t\t},\n\t\tComponents: \u0026spec3.Components{\n\t\t\tSchemas: staticOpenAPISpec,\n\t\t},\n\t}\n\n\tspecs := []*spec3.OpenAPI{staticSpecV3}\n\tfor _, v := range crd.Spec.Versions {\n\t\t// Defaults are not pruned here, but before being served.\n\t\t// See flag description in builder.go for flag usage\n\t\ts, err := builder.BuildOpenAPIV3(crd, v.Name, builder.Options{})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tspecs = append(specs, s)\n\t}\n\n\tmergedOpenAPI, err := builder.MergeSpecsV3(specs...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn mergedOpenAPI.Components.Schemas, nil\n}","line":{"from":1366,"to":1404}} {"id":100014103,"name":"getColumnsForVersion","signature":"func getColumnsForVersion(crd *apiextensionsv1.CustomResourceDefinition, version string) ([]apiextensionsv1.CustomResourceColumnDefinition, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/helpers.go","code":"// getColumnsForVersion returns the columns for given version or nil.\n// NOTE: the newly logically-defaulted columns is not pointing to the original CRD object.\n// One cannot mutate the original CRD columns using the logically-defaulted columns. Please iterate through\n// the original CRD object instead.\nfunc getColumnsForVersion(crd *apiextensionsv1.CustomResourceDefinition, version string) ([]apiextensionsv1.CustomResourceColumnDefinition, error) {\n\tfor _, v := range crd.Spec.Versions {\n\t\tif version == v.Name {\n\t\t\treturn serveDefaultColumnsIfEmpty(v.AdditionalPrinterColumns), nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"version %s not found in apiextensionsv1.CustomResourceDefinition: %v\", version, crd.Name)\n}","line":{"from":28,"to":39}} {"id":100014104,"name":"getScaleColumnsForVersion","signature":"func getScaleColumnsForVersion(crd *apiextensionsv1.CustomResourceDefinition, version string) ([]apiextensionsv1.CustomResourceColumnDefinition, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/helpers.go","code":"// getScaleColumnsForVersion returns 2 columns for the desired and actual number of replicas.\nfunc getScaleColumnsForVersion(crd *apiextensionsv1.CustomResourceDefinition, version string) ([]apiextensionsv1.CustomResourceColumnDefinition, error) {\n\tfor _, v := range crd.Spec.Versions {\n\t\tif version != v.Name {\n\t\t\tcontinue\n\t\t}\n\t\tvar cols []apiextensionsv1.CustomResourceColumnDefinition\n\t\tif v.Subresources != nil \u0026\u0026 v.Subresources.Scale != nil {\n\t\t\tif v.Subresources.Scale.SpecReplicasPath != \"\" {\n\t\t\t\tcols = append(cols, apiextensionsv1.CustomResourceColumnDefinition{\n\t\t\t\t\tName: \"Desired\",\n\t\t\t\t\tType: \"integer\",\n\t\t\t\t\tDescription: \"Number of desired replicas\",\n\t\t\t\t\tJSONPath: \".spec.replicas\",\n\t\t\t\t})\n\t\t\t}\n\t\t\tif v.Subresources.Scale.StatusReplicasPath != \"\" {\n\t\t\t\tcols = append(cols, apiextensionsv1.CustomResourceColumnDefinition{\n\t\t\t\t\tName: \"Available\",\n\t\t\t\t\tType: \"integer\",\n\t\t\t\t\tDescription: \"Number of actual replicas\",\n\t\t\t\t\tJSONPath: \".status.replicas\",\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\tcols = append(cols, apiextensionsv1.CustomResourceColumnDefinition{\n\t\t\tName: \"Age\",\n\t\t\tType: \"date\",\n\t\t\tDescription: swaggerMetadataDescriptions[\"creationTimestamp\"],\n\t\t\tJSONPath: \".metadata.creationTimestamp\",\n\t\t})\n\t\treturn cols, nil\n\t}\n\treturn nil, fmt.Errorf(\"version %s not found in apiextensionsv1.CustomResourceDefinition: %v\", version, crd.Name)\n}","line":{"from":41,"to":75}} {"id":100014105,"name":"serveDefaultColumnsIfEmpty","signature":"func serveDefaultColumnsIfEmpty(columns []apiextensionsv1.CustomResourceColumnDefinition) []apiextensionsv1.CustomResourceColumnDefinition","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/helpers.go","code":"// serveDefaultColumnsIfEmpty applies logically defaulting to columns, if the input columns is empty.\n// NOTE: in this way, the newly logically-defaulted columns is not pointing to the original CRD object.\n// One cannot mutate the original CRD columns using the logically-defaulted columns. Please iterate through\n// the original CRD object instead.\nfunc serveDefaultColumnsIfEmpty(columns []apiextensionsv1.CustomResourceColumnDefinition) []apiextensionsv1.CustomResourceColumnDefinition {\n\tif len(columns) \u003e 0 {\n\t\treturn columns\n\t}\n\treturn []apiextensionsv1.CustomResourceColumnDefinition{\n\t\t{Name: \"Age\", Type: \"date\", Description: swaggerMetadataDescriptions[\"creationTimestamp\"], JSONPath: \".metadata.creationTimestamp\"},\n\t}\n}","line":{"from":77,"to":88}} {"id":100014106,"name":"getBaseEnv","signature":"func getBaseEnv() (*cel.Env, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/compilation.go","code":"// This func is duplicated in k8s.io/apiserver/pkg/admission/plugin/cel/validator.go\n// If any changes are made here, consider to make the same changes there as well.\nfunc getBaseEnv() (*cel.Env, error) {\n\tinitEnvOnce.Do(func() {\n\t\tvar opts []cel.EnvOption\n\t\topts = append(opts, cel.HomogeneousAggregateLiterals())\n\t\t// Validate function declarations once during base env initialization,\n\t\t// so they don't need to be evaluated each time a CEL rule is compiled.\n\t\t// This is a relatively expensive operation.\n\t\topts = append(opts, cel.EagerlyValidateDeclarations(true), cel.DefaultUTCTimeZone(true))\n\t\topts = append(opts, library.ExtensionLibs...)\n\n\t\tinitEnv, initEnvErr = cel.NewEnv(opts...)\n\t})\n\treturn initEnv, initEnvErr\n}","line":{"from":75,"to":90}} {"id":100014107,"name":"Compile","signature":"func Compile(s *schema.Structural, declType *apiservercel.DeclType, perCallLimit uint64) ([]CompilationResult, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/compilation.go","code":"// Compile compiles all the XValidations rules (without recursing into the schema) and returns a slice containing a\n// CompilationResult for each ValidationRule, or an error. declType is expected to be a CEL DeclType corresponding\n// to the structural schema.\n// Each CompilationResult may contain:\n// - non-nil Program, nil Error: The program was compiled successfully\n// - nil Program, non-nil Error: Compilation resulted in an error\n// - nil Program, nil Error: The provided rule was empty so compilation was not attempted\n//\n// perCallLimit was added for testing purpose only. Callers should always use const PerCallLimit from k8s.io/apiserver/pkg/apis/cel/config.go as input.\nfunc Compile(s *schema.Structural, declType *apiservercel.DeclType, perCallLimit uint64) ([]CompilationResult, error) {\n\tt := time.Now()\n\tdefer func() {\n\t\tmetrics.Metrics.ObserveCompilation(time.Since(t))\n\t}()\n\n\tif len(s.Extensions.XValidations) == 0 {\n\t\treturn nil, nil\n\t}\n\tcelRules := s.Extensions.XValidations\n\n\tvar propDecls []cel.EnvOption\n\tvar root *apiservercel.DeclType\n\tvar ok bool\n\tbaseEnv, err := getBaseEnv()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treg := apiservercel.NewRegistry(baseEnv)\n\tscopedTypeName := generateUniqueSelfTypeName()\n\trt, err := apiservercel.NewRuleTypes(scopedTypeName, declType, reg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif rt == nil {\n\t\treturn nil, nil\n\t}\n\topts, err := rt.EnvOptions(baseEnv.TypeProvider())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\troot, ok = rt.FindDeclType(scopedTypeName)\n\tif !ok {\n\t\tif declType == nil {\n\t\t\treturn nil, fmt.Errorf(\"rule declared on schema that does not support validation rules type: '%s' x-kubernetes-preserve-unknown-fields: '%t'\", s.Type, s.XPreserveUnknownFields)\n\t\t}\n\t\troot = declType.MaybeAssignTypeName(scopedTypeName)\n\t}\n\tpropDecls = append(propDecls, cel.Variable(ScopedVarName, root.CelType()))\n\tpropDecls = append(propDecls, cel.Variable(OldScopedVarName, root.CelType()))\n\topts = append(opts, propDecls...)\n\tenv, err := baseEnv.Extend(opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\testimator := newCostEstimator(root)\n\t// compResults is the return value which saves a list of compilation results in the same order as x-kubernetes-validations rules.\n\tcompResults := make([]CompilationResult, len(celRules))\n\tmaxCardinality := maxCardinality(root.MinSerializedSize)\n\tfor i, rule := range celRules {\n\t\tcompResults[i] = compileRule(rule, env, perCallLimit, estimator, maxCardinality)\n\t}\n\n\treturn compResults, nil\n}","line":{"from":92,"to":155}} {"id":100014108,"name":"compileRule","signature":"func compileRule(rule apiextensions.ValidationRule, env *cel.Env, perCallLimit uint64, estimator *library.CostEstimator, maxCardinality uint64) (compilationResult CompilationResult)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/compilation.go","code":"func compileRule(rule apiextensions.ValidationRule, env *cel.Env, perCallLimit uint64, estimator *library.CostEstimator, maxCardinality uint64) (compilationResult CompilationResult) {\n\tif len(strings.TrimSpace(rule.Rule)) == 0 {\n\t\t// include a compilation result, but leave both program and error nil per documented return semantics of this\n\t\t// function\n\t\treturn\n\t}\n\tast, issues := env.Compile(rule.Rule)\n\tif issues != nil {\n\t\tcompilationResult.Error = \u0026apiservercel.Error{Type: apiservercel.ErrorTypeInvalid, Detail: \"compilation failed: \" + issues.String()}\n\t\treturn\n\t}\n\tif ast.OutputType() != cel.BoolType {\n\t\tcompilationResult.Error = \u0026apiservercel.Error{Type: apiservercel.ErrorTypeInvalid, Detail: \"cel expression must evaluate to a bool\"}\n\t\treturn\n\t}\n\n\tcheckedExpr, err := cel.AstToCheckedExpr(ast)\n\tif err != nil {\n\t\t// should be impossible since env.Compile returned no issues\n\t\tcompilationResult.Error = \u0026apiservercel.Error{Type: apiservercel.ErrorTypeInternal, Detail: \"unexpected compilation error: \" + err.Error()}\n\t\treturn\n\t}\n\tfor _, ref := range checkedExpr.ReferenceMap {\n\t\tif ref.Name == OldScopedVarName {\n\t\t\tcompilationResult.TransitionRule = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// TODO: Ideally we could configure the per expression limit at validation time and set it to the remaining overall budget, but we would either need a way to pass in a limit at evaluation time or move program creation to validation time\n\tprog, err := env.Program(ast,\n\t\tcel.EvalOptions(cel.OptOptimize, cel.OptTrackCost),\n\t\tcel.CostLimit(perCallLimit),\n\t\tcel.CostTracking(estimator),\n\t\tcel.OptimizeRegex(library.ExtensionLibRegexOptimizations...),\n\t\tcel.InterruptCheckFrequency(celconfig.CheckFrequency),\n\t)\n\tif err != nil {\n\t\tcompilationResult.Error = \u0026apiservercel.Error{Type: apiservercel.ErrorTypeInvalid, Detail: \"program instantiation failed: \" + err.Error()}\n\t\treturn\n\t}\n\tcostEst, err := env.EstimateCost(ast, estimator)\n\tif err != nil {\n\t\tcompilationResult.Error = \u0026apiservercel.Error{Type: apiservercel.ErrorTypeInternal, Detail: \"cost estimation failed: \" + err.Error()}\n\t\treturn\n\t}\n\tcompilationResult.MaxCost = costEst.Max\n\tcompilationResult.MaxCardinality = maxCardinality\n\tcompilationResult.Program = prog\n\tif rule.MessageExpression != \"\" {\n\t\tast, issues := env.Compile(rule.MessageExpression)\n\t\tif issues != nil {\n\t\t\tcompilationResult.MessageExpressionError = \u0026apiservercel.Error{Type: apiservercel.ErrorTypeInvalid, Detail: \"messageExpression compilation failed: \" + issues.String()}\n\t\t\treturn\n\t\t}\n\t\tif ast.OutputType() != cel.StringType {\n\t\t\tcompilationResult.MessageExpressionError = \u0026apiservercel.Error{Type: apiservercel.ErrorTypeInvalid, Detail: \"messageExpression must evaluate to a string\"}\n\t\t\treturn\n\t\t}\n\n\t\t_, err := cel.AstToCheckedExpr(ast)\n\t\tif err != nil {\n\t\t\tcompilationResult.MessageExpressionError = \u0026apiservercel.Error{Type: apiservercel.ErrorTypeInternal, Detail: \"unexpected messageExpression compilation error: \" + err.Error()}\n\t\t\treturn\n\t\t}\n\n\t\tmsgProg, err := env.Program(ast,\n\t\t\tcel.EvalOptions(cel.OptOptimize, cel.OptTrackCost),\n\t\t\tcel.CostLimit(perCallLimit),\n\t\t\tcel.CostTracking(estimator),\n\t\t\tcel.OptimizeRegex(library.ExtensionLibRegexOptimizations...),\n\t\t\tcel.InterruptCheckFrequency(celconfig.CheckFrequency),\n\t\t)\n\t\tif err != nil {\n\t\t\tcompilationResult.MessageExpressionError = \u0026apiservercel.Error{Type: apiservercel.ErrorTypeInvalid, Detail: \"messageExpression instantiation failed: \" + err.Error()}\n\t\t\treturn\n\t\t}\n\t\tcostEst, err := env.EstimateCost(ast, estimator)\n\t\tif err != nil {\n\t\t\tcompilationResult.MessageExpressionError = \u0026apiservercel.Error{Type: apiservercel.ErrorTypeInternal, Detail: \"cost estimation failed for messageExpression: \" + err.Error()}\n\t\t\treturn\n\t\t}\n\t\tcompilationResult.MessageExpression = msgProg\n\t\tcompilationResult.MessageExpressionMaxCost = costEst.Max\n\t}\n\treturn\n}","line":{"from":157,"to":243}} {"id":100014109,"name":"generateUniqueSelfTypeName","signature":"func generateUniqueSelfTypeName() string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/compilation.go","code":"// generateUniqueSelfTypeName creates a placeholder type name to use in a CEL programs for cases\n// where we do not wish to expose a stable type name to CEL validator rule authors. For this to effectively prevent\n// developers from depending on the generated name (i.e. using it in CEL programs), it must be changed each time a\n// CRD is created or updated.\nfunc generateUniqueSelfTypeName() string {\n\treturn fmt.Sprintf(\"selfType%d\", time.Now().Nanosecond())\n}","line":{"from":245,"to":251}} {"id":100014110,"name":"newCostEstimator","signature":"func newCostEstimator(root *apiservercel.DeclType) *library.CostEstimator","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/compilation.go","code":"func newCostEstimator(root *apiservercel.DeclType) *library.CostEstimator {\n\treturn \u0026library.CostEstimator{SizeEstimator: \u0026sizeEstimator{root: root}}\n}","line":{"from":253,"to":255}} {"id":100014111,"name":"EstimateSize","signature":"func (c *sizeEstimator) EstimateSize(element checker.AstNode) *checker.SizeEstimate","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/compilation.go","code":"func (c *sizeEstimator) EstimateSize(element checker.AstNode) *checker.SizeEstimate {\n\tif len(element.Path()) == 0 {\n\t\t// Path() can return an empty list, early exit if it does since we can't\n\t\t// provide size estimates when that happens\n\t\treturn nil\n\t}\n\tcurrentNode := c.root\n\t// cut off \"self\" from path, since we always start there\n\tfor _, name := range element.Path()[1:] {\n\t\tswitch name {\n\t\tcase \"@items\", \"@values\":\n\t\t\tif currentNode.ElemType == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tcurrentNode = currentNode.ElemType\n\t\tcase \"@keys\":\n\t\t\tif currentNode.KeyType == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tcurrentNode = currentNode.KeyType\n\t\tdefault:\n\t\t\tfield, ok := currentNode.Fields[name]\n\t\t\tif !ok {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif field.Type == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tcurrentNode = field.Type\n\t\t}\n\t}\n\treturn \u0026checker.SizeEstimate{Min: 0, Max: uint64(currentNode.MaxElements)}\n}","line":{"from":261,"to":293}} {"id":100014112,"name":"EstimateCallCost","signature":"func (c *sizeEstimator) EstimateCallCost(function, overloadID string, target *checker.AstNode, args []checker.AstNode) *checker.CallEstimate","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/compilation.go","code":"func (c *sizeEstimator) EstimateCallCost(function, overloadID string, target *checker.AstNode, args []checker.AstNode) *checker.CallEstimate {\n\treturn nil\n}","line":{"from":295,"to":297}} {"id":100014113,"name":"maxCardinality","signature":"func maxCardinality(minSize int64) uint64","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/compilation.go","code":"// maxCardinality returns the maximum number of times data conforming to the minimum size given could possibly exist in\n// an object serialized to JSON. For cases where a schema is contained under map or array schemas of unbounded\n// size, this can be used as an estimate as the worst case number of times data matching the schema could be repeated.\n// Note that this only assumes a single comma between data elements, so if the schema is contained under only maps,\n// this estimates a higher cardinality that would be possible. DeclType.MinSerializedSize is meant to be passed to\n// this function.\nfunc maxCardinality(minSize int64) uint64 {\n\tsz := minSize + 1 // assume at least one comma between elements\n\treturn uint64(celconfig.MaxRequestSizeBytes / sz)\n}","line":{"from":299,"to":308}} {"id":100014114,"name":"makeMapList","signature":"func makeMapList(sts *schema.Structural, items []interface{}) (rv common.MapList)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/maplist.go","code":"// makeMapList returns a queryable interface over the provided x-kubernetes-list-type=map\n// keyedItems. If the provided schema is _not_ an array with x-kubernetes-list-type=map, returns an\n// empty mapList.\nfunc makeMapList(sts *schema.Structural, items []interface{}) (rv common.MapList) {\n\treturn common.MakeMapList(\u0026model.Structural{Structural: sts}, items)\n}","line":{"from":25,"to":30}} {"id":100014115,"name":"Schema","signature":"func (sb *StructuralOrBool) Schema() common.Schema","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model/adaptor.go","code":"func (sb *StructuralOrBool) Schema() common.Schema {\n\tif sb.StructuralOrBool.Structural == nil {\n\t\treturn nil\n\t}\n\treturn \u0026Structural{Structural: sb.StructuralOrBool.Structural}\n}","line":{"from":35,"to":40}} {"id":100014116,"name":"Allows","signature":"func (sb *StructuralOrBool) Allows() bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model/adaptor.go","code":"func (sb *StructuralOrBool) Allows() bool {\n\treturn sb.StructuralOrBool.Bool\n}","line":{"from":42,"to":44}} {"id":100014117,"name":"Type","signature":"func (s *Structural) Type() string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model/adaptor.go","code":"func (s *Structural) Type() string {\n\treturn s.Structural.Type\n}","line":{"from":46,"to":48}} {"id":100014118,"name":"Format","signature":"func (s *Structural) Format() string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model/adaptor.go","code":"func (s *Structural) Format() string {\n\tif s.Structural.ValueValidation == nil {\n\t\treturn \"\"\n\t}\n\treturn s.Structural.ValueValidation.Format\n}","line":{"from":50,"to":55}} {"id":100014119,"name":"Items","signature":"func (s *Structural) Items() common.Schema","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model/adaptor.go","code":"func (s *Structural) Items() common.Schema {\n\treturn \u0026Structural{Structural: s.Structural.Items}\n}","line":{"from":57,"to":59}} {"id":100014120,"name":"Properties","signature":"func (s *Structural) Properties() map[string]common.Schema","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model/adaptor.go","code":"func (s *Structural) Properties() map[string]common.Schema {\n\tif s.Structural.Properties == nil {\n\t\treturn nil\n\t}\n\tres := make(map[string]common.Schema, len(s.Structural.Properties))\n\tfor n, prop := range s.Structural.Properties {\n\t\ts := prop\n\t\tres[n] = \u0026Structural{Structural: \u0026s}\n\t}\n\treturn res\n}","line":{"from":61,"to":71}} {"id":100014121,"name":"AdditionalProperties","signature":"func (s *Structural) AdditionalProperties() common.SchemaOrBool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model/adaptor.go","code":"func (s *Structural) AdditionalProperties() common.SchemaOrBool {\n\tif s.Structural.AdditionalProperties == nil {\n\t\treturn nil\n\t}\n\treturn \u0026StructuralOrBool{StructuralOrBool: s.Structural.AdditionalProperties}\n}","line":{"from":73,"to":78}} {"id":100014122,"name":"Default","signature":"func (s *Structural) Default() any","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model/adaptor.go","code":"func (s *Structural) Default() any {\n\treturn s.Structural.Default.Object\n}","line":{"from":80,"to":82}} {"id":100014123,"name":"MaxItems","signature":"func (s *Structural) MaxItems() *int64","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model/adaptor.go","code":"func (s *Structural) MaxItems() *int64 {\n\tif s.Structural.ValueValidation == nil {\n\t\treturn nil\n\t}\n\treturn s.Structural.ValueValidation.MaxItems\n}","line":{"from":84,"to":89}} {"id":100014124,"name":"MaxLength","signature":"func (s *Structural) MaxLength() *int64","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model/adaptor.go","code":"func (s *Structural) MaxLength() *int64 {\n\tif s.Structural.ValueValidation == nil {\n\t\treturn nil\n\t}\n\treturn s.Structural.ValueValidation.MaxLength\n}","line":{"from":91,"to":96}} {"id":100014125,"name":"MaxProperties","signature":"func (s *Structural) MaxProperties() *int64","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model/adaptor.go","code":"func (s *Structural) MaxProperties() *int64 {\n\tif s.Structural.ValueValidation == nil {\n\t\treturn nil\n\t}\n\treturn s.Structural.ValueValidation.MaxProperties\n}","line":{"from":98,"to":103}} {"id":100014126,"name":"Required","signature":"func (s *Structural) Required() []string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model/adaptor.go","code":"func (s *Structural) Required() []string {\n\tif s.Structural.ValueValidation == nil {\n\t\treturn nil\n\t}\n\treturn s.Structural.ValueValidation.Required\n}","line":{"from":105,"to":110}} {"id":100014127,"name":"Enum","signature":"func (s *Structural) Enum() []any","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model/adaptor.go","code":"func (s *Structural) Enum() []any {\n\tif s.Structural.ValueValidation == nil {\n\t\treturn nil\n\t}\n\tret := make([]any, 0, len(s.Structural.ValueValidation.Enum))\n\tfor _, e := range s.Structural.ValueValidation.Enum {\n\t\tret = append(ret, e.Object)\n\t}\n\treturn ret\n}","line":{"from":112,"to":121}} {"id":100014128,"name":"Nullable","signature":"func (s *Structural) Nullable() bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model/adaptor.go","code":"func (s *Structural) Nullable() bool {\n\treturn s.Structural.Nullable\n}","line":{"from":123,"to":125}} {"id":100014129,"name":"IsXIntOrString","signature":"func (s *Structural) IsXIntOrString() bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model/adaptor.go","code":"func (s *Structural) IsXIntOrString() bool {\n\treturn s.Structural.XIntOrString\n}","line":{"from":127,"to":129}} {"id":100014130,"name":"IsXEmbeddedResource","signature":"func (s *Structural) IsXEmbeddedResource() bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model/adaptor.go","code":"func (s *Structural) IsXEmbeddedResource() bool {\n\treturn s.Structural.XEmbeddedResource\n}","line":{"from":131,"to":133}} {"id":100014131,"name":"IsXPreserveUnknownFields","signature":"func (s *Structural) IsXPreserveUnknownFields() bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model/adaptor.go","code":"func (s *Structural) IsXPreserveUnknownFields() bool {\n\treturn s.Structural.XPreserveUnknownFields\n}","line":{"from":135,"to":137}} {"id":100014132,"name":"XListType","signature":"func (s *Structural) XListType() string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model/adaptor.go","code":"func (s *Structural) XListType() string {\n\tif s.Structural.XListType == nil {\n\t\treturn \"\"\n\t}\n\treturn *s.Structural.XListType\n}","line":{"from":139,"to":144}} {"id":100014133,"name":"XListMapKeys","signature":"func (s *Structural) XListMapKeys() []string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model/adaptor.go","code":"func (s *Structural) XListMapKeys() []string {\n\treturn s.Structural.XListMapKeys\n}","line":{"from":146,"to":148}} {"id":100014134,"name":"WithTypeAndObjectMeta","signature":"func (s *Structural) WithTypeAndObjectMeta() common.Schema","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model/adaptor.go","code":"func (s *Structural) WithTypeAndObjectMeta() common.Schema {\n\treturn \u0026Structural{Structural: WithTypeAndObjectMeta(s.Structural)}\n}","line":{"from":150,"to":152}} {"id":100014135,"name":"SchemaDeclType","signature":"func SchemaDeclType(s *schema.Structural, isResourceRoot bool) *apiservercel.DeclType","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model/schemas.go","code":"// SchemaDeclType converts the structural schema to a CEL declaration, or returns nil if the\n// structural schema should not be exposed in CEL expressions.\n// Set isResourceRoot to true for the root of a custom resource or embedded resource.\n//\n// Schemas with XPreserveUnknownFields not exposed unless they are objects. Array and \"maps\" schemas\n// are not exposed if their items or additionalProperties schemas are not exposed. Object Properties are not exposed\n// if their schema is not exposed.\n//\n// The CEL declaration for objects with XPreserveUnknownFields does not expose unknown fields.\nfunc SchemaDeclType(s *schema.Structural, isResourceRoot bool) *apiservercel.DeclType {\n\treturn common.SchemaDeclType(\u0026Structural{Structural: s}, isResourceRoot)\n}","line":{"from":26,"to":37}} {"id":100014136,"name":"WithTypeAndObjectMeta","signature":"func WithTypeAndObjectMeta(s *schema.Structural) *schema.Structural","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/model/schemas.go","code":"// WithTypeAndObjectMeta ensures the kind, apiVersion and\n// metadata.name and metadata.generateName properties are specified, making a shallow copy of the provided schema if needed.\nfunc WithTypeAndObjectMeta(s *schema.Structural) *schema.Structural {\n\tif s.Properties != nil \u0026\u0026\n\t\ts.Properties[\"kind\"].Type == \"string\" \u0026\u0026\n\t\ts.Properties[\"apiVersion\"].Type == \"string\" \u0026\u0026\n\t\ts.Properties[\"metadata\"].Type == \"object\" \u0026\u0026\n\t\ts.Properties[\"metadata\"].Properties != nil \u0026\u0026\n\t\ts.Properties[\"metadata\"].Properties[\"name\"].Type == \"string\" \u0026\u0026\n\t\ts.Properties[\"metadata\"].Properties[\"generateName\"].Type == \"string\" {\n\t\treturn s\n\t}\n\tresult := \u0026schema.Structural{\n\t\tGeneric: s.Generic,\n\t\tExtensions: s.Extensions,\n\t\tValueValidation: s.ValueValidation,\n\t}\n\tprops := make(map[string]schema.Structural, len(s.Properties))\n\tfor k, prop := range s.Properties {\n\t\tprops[k] = prop\n\t}\n\tstringType := schema.Structural{Generic: schema.Generic{Type: \"string\"}}\n\tprops[\"kind\"] = stringType\n\tprops[\"apiVersion\"] = stringType\n\tprops[\"metadata\"] = schema.Structural{\n\t\tGeneric: schema.Generic{Type: \"object\"},\n\t\tProperties: map[string]schema.Structural{\n\t\t\t\"name\": stringType,\n\t\t\t\"generateName\": stringType,\n\t\t},\n\t}\n\tresult.Properties = props\n\n\treturn result\n}","line":{"from":39,"to":73}} {"id":100014137,"name":"NewValidator","signature":"func NewValidator(s *schema.Structural, isResourceRoot bool, perCallLimit uint64) *Validator","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/validation.go","code":"// NewValidator returns compiles all the CEL programs defined in x-kubernetes-validations extensions\n// of the Structural schema and returns a custom resource validator that contains nested\n// validators for all items, properties and additionalProperties that transitively contain validator rules.\n// Returns nil if there are no validator rules in the Structural schema. May return a validator containing only errors.\n// Adding perCallLimit as input arg for testing purpose only. Callers should always use const PerCallLimit from k8s.io/apiserver/pkg/apis/cel/config.go as input\nfunc NewValidator(s *schema.Structural, isResourceRoot bool, perCallLimit uint64) *Validator {\n\tif !hasXValidations(s) {\n\t\treturn nil\n\t}\n\treturn validator(s, isResourceRoot, model.SchemaDeclType(s, isResourceRoot), perCallLimit)\n}","line":{"from":68,"to":78}} {"id":100014138,"name":"validator","signature":"func validator(s *schema.Structural, isResourceRoot bool, declType *cel.DeclType, perCallLimit uint64) *Validator","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/validation.go","code":"// validator creates a Validator for all x-kubernetes-validations at the level of the provided schema and lower and\n// returns the Validator if any x-kubernetes-validations exist in the schema, or nil if no x-kubernetes-validations\n// exist. declType is expected to be a CEL DeclType corresponding to the structural schema.\n// perCallLimit was added for testing purpose only. Callers should always use const PerCallLimit from k8s.io/apiserver/pkg/apis/cel/config.go as input.\nfunc validator(s *schema.Structural, isResourceRoot bool, declType *cel.DeclType, perCallLimit uint64) *Validator {\n\tcompiledRules, err := Compile(s, declType, perCallLimit)\n\tvar itemsValidator, additionalPropertiesValidator *Validator\n\tvar propertiesValidators map[string]Validator\n\tif s.Items != nil {\n\t\titemsValidator = validator(s.Items, s.Items.XEmbeddedResource, declType.ElemType, perCallLimit)\n\t}\n\tif len(s.Properties) \u003e 0 {\n\t\tpropertiesValidators = make(map[string]Validator, len(s.Properties))\n\t\tfor k, p := range s.Properties {\n\t\t\tprop := p\n\t\t\tvar fieldType *cel.DeclType\n\t\t\tif escapedPropName, ok := cel.Escape(k); ok {\n\t\t\t\tif f, ok := declType.Fields[escapedPropName]; ok {\n\t\t\t\t\tfieldType = f.Type\n\t\t\t\t} else {\n\t\t\t\t\t// fields with unknown types are omitted from CEL validation entirely\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// field may be absent from declType if the property name is unescapable, in which case we should convert\n\t\t\t\t// the field value type to a DeclType.\n\t\t\t\tfieldType = model.SchemaDeclType(\u0026prop, prop.XEmbeddedResource)\n\t\t\t\tif fieldType == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tif p := validator(\u0026prop, prop.XEmbeddedResource, fieldType, perCallLimit); p != nil {\n\t\t\t\tpropertiesValidators[k] = *p\n\t\t\t}\n\t\t}\n\t}\n\tif s.AdditionalProperties != nil \u0026\u0026 s.AdditionalProperties.Structural != nil {\n\t\tadditionalPropertiesValidator = validator(s.AdditionalProperties.Structural, s.AdditionalProperties.Structural.XEmbeddedResource, declType.ElemType, perCallLimit)\n\t}\n\tif len(compiledRules) \u003e 0 || err != nil || itemsValidator != nil || additionalPropertiesValidator != nil || len(propertiesValidators) \u003e 0 {\n\t\tvar activationFactory func(*schema.Structural, interface{}, interface{}) interpreter.Activation = validationActivationWithoutOldSelf\n\t\tfor _, rule := range compiledRules {\n\t\t\tif rule.TransitionRule {\n\t\t\t\tactivationFactory = validationActivationWithOldSelf\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\treturn \u0026Validator{\n\t\t\tcompiledRules: compiledRules,\n\t\t\tcompilationErr: err,\n\t\t\tisResourceRoot: isResourceRoot,\n\t\t\tItems: itemsValidator,\n\t\t\tAdditionalProperties: additionalPropertiesValidator,\n\t\t\tProperties: propertiesValidators,\n\t\t\tcelActivationFactory: activationFactory,\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":80,"to":140}} {"id":100014139,"name":"Validate","signature":"func (s *Validator) Validate(ctx context.Context, fldPath *field.Path, sts *schema.Structural, obj, oldObj interface{}, costBudget int64) (errs field.ErrorList, remainingBudget int64)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/validation.go","code":"// Validate validates all x-kubernetes-validations rules in Validator against obj and returns any errors.\n// If the validation rules exceed the costBudget, subsequent evaluations will be skipped, the list of errs returned will not be empty, and a negative remainingBudget will be returned.\n// Most callers can ignore the returned remainingBudget value unless another validate call is going to be made\n// context is passed for supporting context cancellation during cel validation\nfunc (s *Validator) Validate(ctx context.Context, fldPath *field.Path, sts *schema.Structural, obj, oldObj interface{}, costBudget int64) (errs field.ErrorList, remainingBudget int64) {\n\tt := time.Now()\n\tdefer func() {\n\t\tmetrics.Metrics.ObserveEvaluation(time.Since(t))\n\t}()\n\tremainingBudget = costBudget\n\tif s == nil || obj == nil {\n\t\treturn nil, remainingBudget\n\t}\n\n\terrs, remainingBudget = s.validateExpressions(ctx, fldPath, sts, obj, oldObj, remainingBudget)\n\tif remainingBudget \u003c 0 {\n\t\treturn errs, remainingBudget\n\t}\n\tswitch obj := obj.(type) {\n\tcase []interface{}:\n\t\toldArray, _ := oldObj.([]interface{})\n\t\tvar arrayErrs field.ErrorList\n\t\tarrayErrs, remainingBudget = s.validateArray(ctx, fldPath, sts, obj, oldArray, remainingBudget)\n\t\terrs = append(errs, arrayErrs...)\n\t\treturn errs, remainingBudget\n\tcase map[string]interface{}:\n\t\toldMap, _ := oldObj.(map[string]interface{})\n\t\tvar mapErrs field.ErrorList\n\t\tmapErrs, remainingBudget = s.validateMap(ctx, fldPath, sts, obj, oldMap, remainingBudget)\n\t\terrs = append(errs, mapErrs...)\n\t\treturn errs, remainingBudget\n\t}\n\treturn errs, remainingBudget\n}","line":{"from":142,"to":175}} {"id":100014140,"name":"validateExpressions","signature":"func (s *Validator) validateExpressions(ctx context.Context, fldPath *field.Path, sts *schema.Structural, obj, oldObj interface{}, costBudget int64) (errs field.ErrorList, remainingBudget int64)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/validation.go","code":"func (s *Validator) validateExpressions(ctx context.Context, fldPath *field.Path, sts *schema.Structural, obj, oldObj interface{}, costBudget int64) (errs field.ErrorList, remainingBudget int64) {\n\t// guard against oldObj being a non-nil interface with a nil value\n\tif oldObj != nil {\n\t\tv := reflect.ValueOf(oldObj)\n\t\tswitch v.Kind() {\n\t\tcase reflect.Map, reflect.Pointer, reflect.Interface, reflect.Slice:\n\t\t\tif v.IsNil() {\n\t\t\t\toldObj = nil // +k8s:verify-mutation:reason=clone\n\t\t\t}\n\t\t}\n\t}\n\n\tremainingBudget = costBudget\n\tif obj == nil {\n\t\t// We only validate non-null values. Rules that need to check for the state of a nullable value or the presence of an optional\n\t\t// field must do so from the surrounding schema. E.g. if an array has nullable string items, a rule on the array\n\t\t// schema can check if items are null, but a rule on the nullable string schema only validates the non-null strings.\n\t\treturn nil, remainingBudget\n\t}\n\tif s.compilationErr != nil {\n\t\terrs = append(errs, field.Invalid(fldPath, sts.Type, fmt.Sprintf(\"rule compiler initialization error: %v\", s.compilationErr)))\n\t\treturn errs, remainingBudget\n\t}\n\tif len(s.compiledRules) == 0 {\n\t\treturn nil, remainingBudget // nothing to do\n\t}\n\tif remainingBudget \u003c= 0 {\n\t\terrs = append(errs, field.Invalid(fldPath, sts.Type, fmt.Sprintf(\"validation failed due to running out of cost budget, no further validation rules will be run\")))\n\t\treturn errs, -1\n\t}\n\tif s.isResourceRoot {\n\t\tsts = model.WithTypeAndObjectMeta(sts)\n\t}\n\tactivation := s.celActivationFactory(sts, obj, oldObj)\n\tfor i, compiled := range s.compiledRules {\n\t\trule := sts.XValidations[i]\n\t\tif compiled.Error != nil {\n\t\t\terrs = append(errs, field.Invalid(fldPath, sts.Type, fmt.Sprintf(\"rule compile error: %v\", compiled.Error)))\n\t\t\tcontinue\n\t\t}\n\t\tif compiled.Program == nil {\n\t\t\t// rule is empty\n\t\t\tcontinue\n\t\t}\n\t\tif compiled.TransitionRule \u0026\u0026 oldObj == nil {\n\t\t\t// transition rules are evaluated only if there is a comparable existing value\n\t\t\tcontinue\n\t\t}\n\t\tevalResult, evalDetails, err := compiled.Program.ContextEval(ctx, activation)\n\t\tif evalDetails == nil {\n\t\t\terrs = append(errs, field.InternalError(fldPath, fmt.Errorf(\"runtime cost could not be calculated for validation rule: %v, no further validation rules will be run\", ruleErrorString(rule))))\n\t\t\treturn errs, -1\n\t\t} else {\n\t\t\trtCost := evalDetails.ActualCost()\n\t\t\tif rtCost == nil {\n\t\t\t\terrs = append(errs, field.Invalid(fldPath, sts.Type, fmt.Sprintf(\"runtime cost could not be calculated for validation rule: %v, no further validation rules will be run\", ruleErrorString(rule))))\n\t\t\t\treturn errs, -1\n\t\t\t} else {\n\t\t\t\tif *rtCost \u003e math.MaxInt64 || int64(*rtCost) \u003e remainingBudget {\n\t\t\t\t\terrs = append(errs, field.Invalid(fldPath, sts.Type, fmt.Sprintf(\"validation failed due to running out of cost budget, no further validation rules will be run\")))\n\t\t\t\t\treturn errs, -1\n\t\t\t\t}\n\t\t\t\tremainingBudget -= int64(*rtCost)\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\t// see types.Err for list of well defined error types\n\t\t\tif strings.HasPrefix(err.Error(), \"no such overload\") {\n\t\t\t\t// Most overload errors are caught by the compiler, which provides details on where exactly in the rule\n\t\t\t\t// error was found. Here, an overload error has occurred at runtime no details are provided, so we\n\t\t\t\t// append a more descriptive error message. This error can only occur when static type checking has\n\t\t\t\t// been bypassed. int-or-string is typed as dynamic and so bypasses compiler type checking.\n\t\t\t\terrs = append(errs, field.Invalid(fldPath, sts.Type, fmt.Sprintf(\"'%v': call arguments did not match a supported operator, function or macro signature for rule: %v\", err, ruleErrorString(rule))))\n\t\t\t} else if strings.HasPrefix(err.Error(), \"operation cancelled: actual cost limit exceeded\") {\n\t\t\t\terrs = append(errs, field.Invalid(fldPath, sts.Type, fmt.Sprintf(\"'%v': no further validation rules will be run due to call cost exceeds limit for rule: %v\", err, ruleErrorString(rule))))\n\t\t\t\treturn errs, -1\n\t\t\t} else {\n\t\t\t\t// no such key: {key}, index out of bounds: {index}, integer overflow, division by zero, ...\n\t\t\t\terrs = append(errs, field.Invalid(fldPath, sts.Type, fmt.Sprintf(\"%v evaluating rule: %v\", err, ruleErrorString(rule))))\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif evalResult != types.True {\n\t\t\tif compiled.MessageExpression != nil {\n\t\t\t\tmessageExpression, newRemainingBudget, msgErr := evalMessageExpression(ctx, compiled.MessageExpression, rule.MessageExpression, activation, remainingBudget)\n\t\t\t\tif msgErr != nil {\n\t\t\t\t\tif msgErr.Type == cel.ErrorTypeInternal {\n\t\t\t\t\t\terrs = append(errs, field.InternalError(fldPath, msgErr))\n\t\t\t\t\t\treturn errs, -1\n\t\t\t\t\t} else if msgErr.Type == cel.ErrorTypeInvalid {\n\t\t\t\t\t\terrs = append(errs, field.Invalid(fldPath, sts.Type, msgErr.Error()))\n\t\t\t\t\t\treturn errs, -1\n\t\t\t\t\t} else {\n\t\t\t\t\t\tklog.V(2).ErrorS(msgErr, \"messageExpression evaluation failed\")\n\t\t\t\t\t\terrs = append(errs, field.Invalid(fldPath, sts.Type, ruleMessageOrDefault(rule)))\n\t\t\t\t\t\tremainingBudget = newRemainingBudget\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\terrs = append(errs, field.Invalid(fldPath, sts.Type, messageExpression))\n\t\t\t\t\tremainingBudget = newRemainingBudget\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terrs = append(errs, field.Invalid(fldPath, sts.Type, ruleMessageOrDefault(rule)))\n\t\t\t}\n\t\t}\n\t}\n\treturn errs, remainingBudget\n}","line":{"from":177,"to":284}} {"id":100014141,"name":"evalMessageExpression","signature":"func evalMessageExpression(ctx context.Context, expr celgo.Program, exprSrc string, activation interpreter.Activation, remainingBudget int64) (string, int64, *cel.Error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/validation.go","code":"// evalMessageExpression evaluates the given message expression and returns the evaluated string form and the remaining budget, or an error if one\n// occurred during evaluation.\nfunc evalMessageExpression(ctx context.Context, expr celgo.Program, exprSrc string, activation interpreter.Activation, remainingBudget int64) (string, int64, *cel.Error) {\n\tevalResult, evalDetails, err := expr.ContextEval(ctx, activation)\n\tif evalDetails == nil {\n\t\treturn \"\", -1, \u0026cel.Error{\n\t\t\tType: cel.ErrorTypeInternal,\n\t\t\tDetail: fmt.Sprintf(\"runtime cost could not be calculated for messageExpression: %q\", exprSrc),\n\t\t}\n\t}\n\trtCost := evalDetails.ActualCost()\n\tif rtCost == nil {\n\t\treturn \"\", -1, \u0026cel.Error{\n\t\t\tType: cel.ErrorTypeInternal,\n\t\t\tDetail: fmt.Sprintf(\"runtime cost could not be calculated for messageExpression: %q\", exprSrc),\n\t\t}\n\t} else if *rtCost \u003e math.MaxInt64 || int64(*rtCost) \u003e remainingBudget {\n\t\treturn \"\", -1, \u0026cel.Error{\n\t\t\tType: cel.ErrorTypeInvalid,\n\t\t\tDetail: \"messageExpression evaluation failed due to running out of cost budget, no further validation rules will be run\",\n\t\t}\n\t}\n\tif err != nil {\n\t\tif strings.HasPrefix(err.Error(), \"operation cancelled: actual cost limit exceeded\") {\n\t\t\treturn \"\", -1, \u0026cel.Error{\n\t\t\t\tType: cel.ErrorTypeInvalid,\n\t\t\t\tDetail: fmt.Sprintf(\"no further validation rules will be run due to call cost exceeds limit for messageExpression: %q\", exprSrc),\n\t\t\t}\n\t\t}\n\t\treturn \"\", remainingBudget - int64(*rtCost), \u0026cel.Error{\n\t\t\tDetail: fmt.Sprintf(\"messageExpression evaluation failed due to: %v\", err.Error()),\n\t\t}\n\t}\n\tmessageStr, ok := evalResult.Value().(string)\n\tif !ok {\n\t\treturn \"\", remainingBudget - int64(*rtCost), \u0026cel.Error{\n\t\t\tDetail: \"messageExpression failed to convert to string\",\n\t\t}\n\t}\n\ttrimmedMsgStr := strings.TrimSpace(messageStr)\n\tif len(trimmedMsgStr) \u003e celconfig.MaxEvaluatedMessageExpressionSizeBytes {\n\t\treturn \"\", remainingBudget - int64(*rtCost), \u0026cel.Error{\n\t\t\tDetail: fmt.Sprintf(\"messageExpression beyond allowable length of %d\", celconfig.MaxEvaluatedMessageExpressionSizeBytes),\n\t\t}\n\t} else if hasNewlines(trimmedMsgStr) {\n\t\treturn \"\", remainingBudget - int64(*rtCost), \u0026cel.Error{\n\t\t\tDetail: \"messageExpression should not contain line breaks\",\n\t\t}\n\t} else if len(trimmedMsgStr) == 0 {\n\t\treturn \"\", remainingBudget - int64(*rtCost), \u0026cel.Error{\n\t\t\tDetail: \"messageExpression should evaluate to a non-empty string\",\n\t\t}\n\t}\n\treturn trimmedMsgStr, remainingBudget - int64(*rtCost), nil\n}","line":{"from":286,"to":340}} {"id":100014142,"name":"hasNewlines","signature":"func hasNewlines(s string) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/validation.go","code":"func hasNewlines(s string) bool {\n\treturn newlineMatcher.MatchString(s)\n}","line":{"from":344,"to":346}} {"id":100014143,"name":"ruleMessageOrDefault","signature":"func ruleMessageOrDefault(rule apiextensions.ValidationRule) string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/validation.go","code":"func ruleMessageOrDefault(rule apiextensions.ValidationRule) string {\n\tif len(rule.Message) == 0 {\n\t\treturn fmt.Sprintf(\"failed rule: %s\", ruleErrorString(rule))\n\t} else {\n\t\treturn strings.TrimSpace(rule.Message)\n\t}\n}","line":{"from":348,"to":354}} {"id":100014144,"name":"ruleErrorString","signature":"func ruleErrorString(rule apiextensions.ValidationRule) string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/validation.go","code":"func ruleErrorString(rule apiextensions.ValidationRule) string {\n\tif len(rule.Message) \u003e 0 {\n\t\treturn strings.TrimSpace(rule.Message)\n\t}\n\treturn strings.TrimSpace(rule.Rule)\n}","line":{"from":356,"to":361}} {"id":100014145,"name":"validationActivationWithOldSelf","signature":"func validationActivationWithOldSelf(sts *schema.Structural, obj, oldObj interface{}) interpreter.Activation","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/validation.go","code":"func validationActivationWithOldSelf(sts *schema.Structural, obj, oldObj interface{}) interpreter.Activation {\n\tva := \u0026validationActivation{\n\t\tself: UnstructuredToVal(obj, sts),\n\t}\n\tif oldObj != nil {\n\t\tva.oldSelf = UnstructuredToVal(oldObj, sts) // +k8s:verify-mutation:reason=clone\n\t\tva.hasOldSelf = true // +k8s:verify-mutation:reason=clone\n\t}\n\treturn va\n}","line":{"from":368,"to":377}} {"id":100014146,"name":"validationActivationWithoutOldSelf","signature":"func validationActivationWithoutOldSelf(sts *schema.Structural, obj, _ interface{}) interpreter.Activation","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/validation.go","code":"func validationActivationWithoutOldSelf(sts *schema.Structural, obj, _ interface{}) interpreter.Activation {\n\treturn \u0026validationActivation{\n\t\tself: UnstructuredToVal(obj, sts),\n\t}\n}","line":{"from":379,"to":383}} {"id":100014147,"name":"ResolveName","signature":"func (a *validationActivation) ResolveName(name string) (interface{}, bool)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/validation.go","code":"func (a *validationActivation) ResolveName(name string) (interface{}, bool) {\n\tswitch name {\n\tcase ScopedVarName:\n\t\treturn a.self, true\n\tcase OldScopedVarName:\n\t\treturn a.oldSelf, a.hasOldSelf\n\tdefault:\n\t\treturn nil, false\n\t}\n}","line":{"from":385,"to":394}} {"id":100014148,"name":"Parent","signature":"func (a *validationActivation) Parent() interpreter.Activation","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/validation.go","code":"func (a *validationActivation) Parent() interpreter.Activation {\n\treturn nil\n}","line":{"from":396,"to":398}} {"id":100014149,"name":"validateMap","signature":"func (s *Validator) validateMap(ctx context.Context, fldPath *field.Path, sts *schema.Structural, obj, oldObj map[string]interface{}, costBudget int64) (errs field.ErrorList, remainingBudget int64)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/validation.go","code":"func (s *Validator) validateMap(ctx context.Context, fldPath *field.Path, sts *schema.Structural, obj, oldObj map[string]interface{}, costBudget int64) (errs field.ErrorList, remainingBudget int64) {\n\tremainingBudget = costBudget\n\tif remainingBudget \u003c 0 {\n\t\treturn errs, remainingBudget\n\t}\n\tif s == nil || obj == nil {\n\t\treturn nil, remainingBudget\n\t}\n\n\tcorrelatable := MapIsCorrelatable(sts.XMapType)\n\n\tif s.AdditionalProperties != nil \u0026\u0026 sts.AdditionalProperties != nil \u0026\u0026 sts.AdditionalProperties.Structural != nil {\n\t\tfor k, v := range obj {\n\t\t\tvar oldV interface{}\n\t\t\tif correlatable {\n\t\t\t\toldV = oldObj[k] // +k8s:verify-mutation:reason=clone\n\t\t\t}\n\n\t\t\tvar err field.ErrorList\n\t\t\terr, remainingBudget = s.AdditionalProperties.Validate(ctx, fldPath.Key(k), sts.AdditionalProperties.Structural, v, oldV, remainingBudget)\n\t\t\terrs = append(errs, err...)\n\t\t\tif remainingBudget \u003c 0 {\n\t\t\t\treturn errs, remainingBudget\n\t\t\t}\n\t\t}\n\t}\n\tif s.Properties != nil \u0026\u0026 sts.Properties != nil {\n\t\tfor k, v := range obj {\n\t\t\tstsProp, stsOk := sts.Properties[k]\n\t\t\tsub, ok := s.Properties[k]\n\t\t\tif ok \u0026\u0026 stsOk {\n\t\t\t\tvar oldV interface{}\n\t\t\t\tif correlatable {\n\t\t\t\t\toldV = oldObj[k] // +k8s:verify-mutation:reason=clone\n\t\t\t\t}\n\n\t\t\t\tvar err field.ErrorList\n\t\t\t\terr, remainingBudget = sub.Validate(ctx, fldPath.Child(k), \u0026stsProp, v, oldV, remainingBudget)\n\t\t\t\terrs = append(errs, err...)\n\t\t\t\tif remainingBudget \u003c 0 {\n\t\t\t\t\treturn errs, remainingBudget\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn errs, remainingBudget\n}","line":{"from":400,"to":447}} {"id":100014150,"name":"validateArray","signature":"func (s *Validator) validateArray(ctx context.Context, fldPath *field.Path, sts *schema.Structural, obj, oldObj []interface{}, costBudget int64) (errs field.ErrorList, remainingBudget int64)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/validation.go","code":"func (s *Validator) validateArray(ctx context.Context, fldPath *field.Path, sts *schema.Structural, obj, oldObj []interface{}, costBudget int64) (errs field.ErrorList, remainingBudget int64) {\n\tremainingBudget = costBudget\n\tif remainingBudget \u003c 0 {\n\t\treturn errs, remainingBudget\n\t}\n\n\tif s.Items != nil \u0026\u0026 sts.Items != nil {\n\t\t// only map-type lists support self-oldSelf correlation for cel rules. if this isn't a\n\t\t// map-type list, then makeMapList returns an implementation that always returns nil\n\t\tcorrelatableOldItems := makeMapList(sts, oldObj)\n\t\tfor i := range obj {\n\t\t\tvar err field.ErrorList\n\t\t\terr, remainingBudget = s.Items.Validate(ctx, fldPath.Index(i), sts.Items, obj[i], correlatableOldItems.Get(obj[i]), remainingBudget)\n\t\t\terrs = append(errs, err...)\n\t\t\tif remainingBudget \u003c 0 {\n\t\t\t\treturn errs, remainingBudget\n\t\t\t}\n\t\t}\n\t}\n\n\treturn errs, remainingBudget\n}","line":{"from":449,"to":470}} {"id":100014151,"name":"MapIsCorrelatable","signature":"func MapIsCorrelatable(mapType *string) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/validation.go","code":"// MapIsCorrelatable returns true if the mapType can be used to correlate the data elements of a map after an update\n// with the data elements of the map from before the updated.\nfunc MapIsCorrelatable(mapType *string) bool {\n\t// if a third map type is introduced, assume it's not correlatable. granular is the default if unspecified.\n\treturn mapType == nil || *mapType == \"granular\" || *mapType == \"atomic\"\n}","line":{"from":472,"to":477}} {"id":100014152,"name":"hasXValidations","signature":"func hasXValidations(s *schema.Structural) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/validation.go","code":"func hasXValidations(s *schema.Structural) bool {\n\tif s == nil {\n\t\treturn false\n\t}\n\tif len(s.XValidations) \u003e 0 {\n\t\treturn true\n\t}\n\tif hasXValidations(s.Items) {\n\t\treturn true\n\t}\n\tif s.AdditionalProperties != nil \u0026\u0026 hasXValidations(s.AdditionalProperties.Structural) {\n\t\treturn true\n\t}\n\tif s.Properties != nil {\n\t\tfor _, prop := range s.Properties {\n\t\t\tif hasXValidations(\u0026prop) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":479,"to":500}} {"id":100014153,"name":"UnstructuredToVal","signature":"func UnstructuredToVal(unstructured interface{}, schema *structuralschema.Structural) ref.Val","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/values.go","code":"// UnstructuredToVal converts a Kubernetes unstructured data element to a CEL Val.\n// The root schema of custom resource schema is expected contain type meta and object meta schemas.\n// If Embedded resources do not contain type meta and object meta schemas, they will be added automatically.\nfunc UnstructuredToVal(unstructured interface{}, schema *structuralschema.Structural) ref.Val {\n\treturn celopenapi.UnstructuredToVal(unstructured, \u0026model.Structural{Structural: schema})\n}","line":{"from":27,"to":32}} {"id":100014154,"name":"validateStructuralCompleteness","signature":"func validateStructuralCompleteness(s *Structural, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/complete.go","code":"// validateStructuralCompleteness checks that every specified field or array in s is also specified\n// outside of value validation.\nfunc validateStructuralCompleteness(s *Structural, fldPath *field.Path) field.ErrorList {\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\treturn validateValueValidationCompleteness(s.ValueValidation, s, fldPath, fldPath)\n}","line":{"from":25,"to":33}} {"id":100014155,"name":"validateValueValidationCompleteness","signature":"func validateValueValidationCompleteness(v *ValueValidation, s *Structural, sPath, vPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/complete.go","code":"func validateValueValidationCompleteness(v *ValueValidation, s *Structural, sPath, vPath *field.Path) field.ErrorList {\n\tif v == nil {\n\t\treturn nil\n\t}\n\tif s == nil {\n\t\treturn field.ErrorList{field.Required(sPath, fmt.Sprintf(\"because it is defined in %s\", vPath.String()))}\n\t}\n\n\tallErrs := field.ErrorList{}\n\n\tallErrs = append(allErrs, validateNestedValueValidationCompleteness(v.Not, s, sPath, vPath.Child(\"not\"))...)\n\tfor i := range v.AllOf {\n\t\tallErrs = append(allErrs, validateNestedValueValidationCompleteness(\u0026v.AllOf[i], s, sPath, vPath.Child(\"allOf\").Index(i))...)\n\t}\n\tfor i := range v.AnyOf {\n\t\tallErrs = append(allErrs, validateNestedValueValidationCompleteness(\u0026v.AnyOf[i], s, sPath, vPath.Child(\"anyOf\").Index(i))...)\n\t}\n\tfor i := range v.OneOf {\n\t\tallErrs = append(allErrs, validateNestedValueValidationCompleteness(\u0026v.OneOf[i], s, sPath, vPath.Child(\"oneOf\").Index(i))...)\n\t}\n\n\treturn allErrs\n}","line":{"from":35,"to":57}} {"id":100014156,"name":"validateNestedValueValidationCompleteness","signature":"func validateNestedValueValidationCompleteness(v *NestedValueValidation, s *Structural, sPath, vPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/complete.go","code":"func validateNestedValueValidationCompleteness(v *NestedValueValidation, s *Structural, sPath, vPath *field.Path) field.ErrorList {\n\tif v == nil {\n\t\treturn nil\n\t}\n\tif s == nil {\n\t\treturn field.ErrorList{field.Required(sPath, fmt.Sprintf(\"because it is defined in %s\", vPath.String()))}\n\t}\n\n\tallErrs := field.ErrorList{}\n\n\tallErrs = append(allErrs, validateValueValidationCompleteness(\u0026v.ValueValidation, s, sPath, vPath)...)\n\tallErrs = append(allErrs, validateNestedValueValidationCompleteness(v.Items, s.Items, sPath.Child(\"items\"), vPath.Child(\"items\"))...)\n\tfor k, vFld := range v.Properties {\n\t\tif sFld, ok := s.Properties[k]; !ok {\n\t\t\tallErrs = append(allErrs, field.Required(sPath.Child(\"properties\").Key(k), fmt.Sprintf(\"because it is defined in %s\", vPath.Child(\"properties\").Key(k))))\n\t\t} else {\n\t\t\tallErrs = append(allErrs, validateNestedValueValidationCompleteness(\u0026vFld, \u0026sFld, sPath.Child(\"properties\").Key(k), vPath.Child(\"properties\").Key(k))...)\n\t\t}\n\t}\n\n\t// don't check additionalProperties as this is not allowed (and checked during validation)\n\n\treturn allErrs\n}","line":{"from":59,"to":82}} {"id":100014157,"name":"NewStructural","signature":"func NewStructural(s *apiextensions.JSONSchemaProps) (*Structural, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/convert.go","code":"// NewStructural converts an OpenAPI v3 schema into a structural schema. A pre-validated JSONSchemaProps will\n// not fail on NewStructural. This means that we require that:\n//\n// - items is not an array of schemas\n// - the following fields are not set:\n// - id\n// - schema\n// - $ref\n// - patternProperties\n// - dependencies\n// - additionalItems\n// - definitions.\n//\n// The follow fields are not preserved:\n// - externalDocs\n// - example.\nfunc NewStructural(s *apiextensions.JSONSchemaProps) (*Structural, error) {\n\tif s == nil {\n\t\treturn nil, nil\n\t}\n\n\tif err := validateUnsupportedFields(s); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvv, err := newValueValidation(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tg, err := newGenerics(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tx, err := newExtensions(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tss := \u0026Structural{\n\t\tGeneric: *g,\n\t\tExtensions: *x,\n\t\tValueValidation: vv,\n\t}\n\n\tif s.Items != nil {\n\t\tif len(s.Items.JSONSchemas) \u003e 0 {\n\t\t\t// we validate that it is not an array\n\t\t\treturn nil, fmt.Errorf(\"OpenAPIV3Schema 'items' must be a schema, but is an array\")\n\t\t}\n\t\titem, err := NewStructural(s.Items.Schema)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tss.Items = item\n\t}\n\n\tif len(s.Properties) \u003e 0 {\n\t\tss.Properties = make(map[string]Structural, len(s.Properties))\n\t\tfor k, x := range s.Properties {\n\t\t\tfld, err := NewStructural(\u0026x)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tss.Properties[k] = *fld\n\t\t}\n\t}\n\n\treturn ss, nil\n}","line":{"from":25,"to":95}} {"id":100014158,"name":"newGenerics","signature":"func newGenerics(s *apiextensions.JSONSchemaProps) (*Generic, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/convert.go","code":"func newGenerics(s *apiextensions.JSONSchemaProps) (*Generic, error) {\n\tif s == nil {\n\t\treturn nil, nil\n\t}\n\tg := \u0026Generic{\n\t\tType: s.Type,\n\t\tDescription: s.Description,\n\t\tTitle: s.Title,\n\t\tNullable: s.Nullable,\n\t}\n\tif s.Default != nil {\n\t\tg.Default = JSON{interface{}(*s.Default)}\n\t}\n\n\tif s.AdditionalProperties != nil {\n\t\tif s.AdditionalProperties.Schema != nil {\n\t\t\tss, err := NewStructural(s.AdditionalProperties.Schema)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tg.AdditionalProperties = \u0026StructuralOrBool{Structural: ss, Bool: true}\n\t\t} else {\n\t\t\tg.AdditionalProperties = \u0026StructuralOrBool{Bool: s.AdditionalProperties.Allows}\n\t\t}\n\t}\n\n\treturn g, nil\n}","line":{"from":97,"to":124}} {"id":100014159,"name":"newValueValidation","signature":"func newValueValidation(s *apiextensions.JSONSchemaProps) (*ValueValidation, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/convert.go","code":"func newValueValidation(s *apiextensions.JSONSchemaProps) (*ValueValidation, error) {\n\tif s == nil {\n\t\treturn nil, nil\n\t}\n\tnot, err := newNestedValueValidation(s.Not)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tv := \u0026ValueValidation{\n\t\tFormat: s.Format,\n\t\tMaximum: s.Maximum,\n\t\tExclusiveMaximum: s.ExclusiveMaximum,\n\t\tMinimum: s.Minimum,\n\t\tExclusiveMinimum: s.ExclusiveMinimum,\n\t\tMaxLength: s.MaxLength,\n\t\tMinLength: s.MinLength,\n\t\tPattern: s.Pattern,\n\t\tMaxItems: s.MaxItems,\n\t\tMinItems: s.MinItems,\n\t\tUniqueItems: s.UniqueItems,\n\t\tMultipleOf: s.MultipleOf,\n\t\tMaxProperties: s.MaxProperties,\n\t\tMinProperties: s.MinProperties,\n\t\tRequired: s.Required,\n\t\tNot: not,\n\t}\n\n\tfor _, e := range s.Enum {\n\t\tv.Enum = append(v.Enum, JSON{e})\n\t}\n\n\tfor _, x := range s.AllOf {\n\t\tclause, err := newNestedValueValidation(\u0026x)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tv.AllOf = append(v.AllOf, *clause)\n\t}\n\n\tfor _, x := range s.AnyOf {\n\t\tclause, err := newNestedValueValidation(\u0026x)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tv.AnyOf = append(v.AnyOf, *clause)\n\t}\n\n\tfor _, x := range s.OneOf {\n\t\tclause, err := newNestedValueValidation(\u0026x)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tv.OneOf = append(v.OneOf, *clause)\n\t}\n\n\treturn v, nil\n}","line":{"from":126,"to":182}} {"id":100014160,"name":"newNestedValueValidation","signature":"func newNestedValueValidation(s *apiextensions.JSONSchemaProps) (*NestedValueValidation, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/convert.go","code":"func newNestedValueValidation(s *apiextensions.JSONSchemaProps) (*NestedValueValidation, error) {\n\tif s == nil {\n\t\treturn nil, nil\n\t}\n\n\tif err := validateUnsupportedFields(s); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvv, err := newValueValidation(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tg, err := newGenerics(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tx, err := newExtensions(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tv := \u0026NestedValueValidation{\n\t\tValueValidation: *vv,\n\t\tForbiddenGenerics: *g,\n\t\tForbiddenExtensions: *x,\n\t}\n\n\tif s.Items != nil {\n\t\tif len(s.Items.JSONSchemas) \u003e 0 {\n\t\t\t// we validate that it is not an array\n\t\t\treturn nil, fmt.Errorf(\"OpenAPIV3Schema 'items' must be a schema, but is an array\")\n\t\t}\n\t\tnvv, err := newNestedValueValidation(s.Items.Schema)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tv.Items = nvv\n\t}\n\tif s.Properties != nil {\n\t\tv.Properties = make(map[string]NestedValueValidation, len(s.Properties))\n\t\tfor k, x := range s.Properties {\n\t\t\tnvv, err := newNestedValueValidation(\u0026x)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tv.Properties[k] = *nvv\n\t\t}\n\t}\n\n\treturn v, nil\n}","line":{"from":184,"to":237}} {"id":100014161,"name":"newExtensions","signature":"func newExtensions(s *apiextensions.JSONSchemaProps) (*Extensions, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/convert.go","code":"func newExtensions(s *apiextensions.JSONSchemaProps) (*Extensions, error) {\n\tif s == nil {\n\t\treturn nil, nil\n\t}\n\n\tret := \u0026Extensions{\n\t\tXEmbeddedResource: s.XEmbeddedResource,\n\t\tXIntOrString: s.XIntOrString,\n\t\tXListMapKeys: s.XListMapKeys,\n\t\tXListType: s.XListType,\n\t\tXMapType: s.XMapType,\n\t}\n\tif err := apiextensionsv1.Convert_apiextensions_ValidationRules_To_v1_ValidationRules(\u0026s.XValidations, \u0026ret.XValidations, nil); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif s.XPreserveUnknownFields != nil {\n\t\tif !*s.XPreserveUnknownFields {\n\t\t\treturn nil, fmt.Errorf(\"internal error: 'x-kubernetes-preserve-unknown-fields' must be true or undefined\")\n\t\t}\n\t\tret.XPreserveUnknownFields = true\n\t}\n\n\treturn ret, nil\n}","line":{"from":239,"to":263}} {"id":100014162,"name":"validateUnsupportedFields","signature":"func validateUnsupportedFields(s *apiextensions.JSONSchemaProps) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/convert.go","code":"// validateUnsupportedFields checks that those fields rejected by validation are actually unset.\nfunc validateUnsupportedFields(s *apiextensions.JSONSchemaProps) error {\n\tif len(s.ID) \u003e 0 {\n\t\treturn fmt.Errorf(\"OpenAPIV3Schema 'id' is not supported\")\n\t}\n\tif len(s.Schema) \u003e 0 {\n\t\treturn fmt.Errorf(\"OpenAPIV3Schema 'schema' is not supported\")\n\t}\n\tif s.Ref != nil \u0026\u0026 len(*s.Ref) \u003e 0 {\n\t\treturn fmt.Errorf(\"OpenAPIV3Schema '$ref' is not supported\")\n\t}\n\tif len(s.PatternProperties) \u003e 0 {\n\t\treturn fmt.Errorf(\"OpenAPIV3Schema 'patternProperties' is not supported\")\n\t}\n\tif len(s.Dependencies) \u003e 0 {\n\t\treturn fmt.Errorf(\"OpenAPIV3Schema 'dependencies' is not supported\")\n\t}\n\tif s.AdditionalItems != nil {\n\t\treturn fmt.Errorf(\"OpenAPIV3Schema 'additionalItems' is not supported\")\n\t}\n\tif len(s.Definitions) \u003e 0 {\n\t\treturn fmt.Errorf(\"OpenAPIV3Schema 'definitions' is not supported\")\n\t}\n\n\treturn nil\n}","line":{"from":265,"to":290}} {"id":100014163,"name":"isNonNullableNull","signature":"func isNonNullableNull(x interface{}, s *structuralschema.Structural) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/algorithm.go","code":"// isNonNullalbeNull returns true if the item is nil AND it's nullable\nfunc isNonNullableNull(x interface{}, s *structuralschema.Structural) bool {\n\treturn x == nil \u0026\u0026 s != nil \u0026\u0026 s.Generic.Nullable == false\n}","line":{"from":24,"to":27}} {"id":100014164,"name":"Default","signature":"func Default(x interface{}, s *structuralschema.Structural)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/algorithm.go","code":"// Default does defaulting of x depending on default values in s.\n// Default values from s are deep-copied.\n//\n// PruneNonNullableNullsWithoutDefaults has left the non-nullable nulls\n// that have a default here.\nfunc Default(x interface{}, s *structuralschema.Structural) {\n\tif s == nil {\n\t\treturn\n\t}\n\n\tswitch x := x.(type) {\n\tcase map[string]interface{}:\n\t\tfor k, prop := range s.Properties {\n\t\t\tif prop.Default.Object == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif _, found := x[k]; !found || isNonNullableNull(x[k], \u0026prop) {\n\t\t\t\tx[k] = runtime.DeepCopyJSONValue(prop.Default.Object)\n\t\t\t}\n\t\t}\n\t\tfor k := range x {\n\t\t\tif prop, found := s.Properties[k]; found {\n\t\t\t\tDefault(x[k], \u0026prop)\n\t\t\t} else if s.AdditionalProperties != nil {\n\t\t\t\tif isNonNullableNull(x[k], s.AdditionalProperties.Structural) {\n\t\t\t\t\tx[k] = runtime.DeepCopyJSONValue(s.AdditionalProperties.Structural.Default.Object)\n\t\t\t\t}\n\t\t\t\tDefault(x[k], s.AdditionalProperties.Structural)\n\t\t\t}\n\t\t}\n\tcase []interface{}:\n\t\tfor i := range x {\n\t\t\tif isNonNullableNull(x[i], s.Items) {\n\t\t\t\tx[i] = runtime.DeepCopyJSONValue(s.Items.Default.Object)\n\t\t\t}\n\t\t\tDefault(x[i], s.Items)\n\t\t}\n\tdefault:\n\t\t// scalars, do nothing\n\t}\n}","line":{"from":29,"to":69}} {"id":100014165,"name":"PruneDefaults","signature":"func PruneDefaults(s *structuralschema.Structural) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/prune.go","code":"// PruneDefaults prunes default values according to the schema and according to\n// the ObjectMeta definition of the running server. It mutates the passed schema.\nfunc PruneDefaults(s *structuralschema.Structural) error {\n\tp := pruner{s}\n\t_, err := p.pruneDefaults(s, NewRootObjectFunc())\n\treturn err\n}","line":{"from":29,"to":35}} {"id":100014166,"name":"pruneDefaults","signature":"func (p *pruner) pruneDefaults(s *structuralschema.Structural, f SurroundingObjectFunc) (changed bool, err error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/prune.go","code":"func (p *pruner) pruneDefaults(s *structuralschema.Structural, f SurroundingObjectFunc) (changed bool, err error) {\n\tif s == nil {\n\t\treturn false, nil\n\t}\n\n\tif s.Default.Object != nil {\n\t\torig := runtime.DeepCopyJSONValue(s.Default.Object)\n\n\t\tobj, acc, err := f(s.Default.Object)\n\t\tif err != nil {\n\t\t\treturn false, fmt.Errorf(\"failed to prune default value: %v\", err)\n\t\t}\n\t\tif err := structuralobjectmeta.Coerce(nil, obj, p.rootSchema, true, true); err != nil {\n\t\t\treturn false, fmt.Errorf(\"failed to prune default value: %v\", err)\n\t\t}\n\t\tpruning.Prune(obj, p.rootSchema, true)\n\t\ts.Default.Object, _, err = acc(obj)\n\t\tif err != nil {\n\t\t\treturn false, fmt.Errorf(\"failed to prune default value: %v\", err)\n\t\t}\n\n\t\tchanged = changed || !reflect.DeepEqual(orig, s.Default.Object)\n\t}\n\n\tif s.AdditionalProperties != nil \u0026\u0026 s.AdditionalProperties.Structural != nil {\n\t\tc, err := p.pruneDefaults(s.AdditionalProperties.Structural, f.Child(\"*\"))\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tchanged = changed || c\n\t}\n\tif s.Items != nil {\n\t\tc, err := p.pruneDefaults(s.Items, f.Index())\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tchanged = changed || c\n\t}\n\tfor k, subSchema := range s.Properties {\n\t\tc, err := p.pruneDefaults(\u0026subSchema, f.Child(k))\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif c {\n\t\t\ts.Properties[k] = subSchema\n\t\t\tchanged = true\n\t\t}\n\t}\n\n\treturn changed, nil\n}","line":{"from":41,"to":91}} {"id":100014167,"name":"isNonNullableNonDefaultableNull","signature":"func isNonNullableNonDefaultableNull(x interface{}, s *structuralschema.Structural) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/prunenulls.go","code":"func isNonNullableNonDefaultableNull(x interface{}, s *structuralschema.Structural) bool {\n\treturn x == nil \u0026\u0026 s != nil \u0026\u0026 s.Generic.Nullable == false \u0026\u0026 s.Default.Object == nil\n}","line":{"from":21,"to":23}} {"id":100014168,"name":"getSchemaForField","signature":"func getSchemaForField(field string, s *structuralschema.Structural) *structuralschema.Structural","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/prunenulls.go","code":"func getSchemaForField(field string, s *structuralschema.Structural) *structuralschema.Structural {\n\tif s == nil {\n\t\treturn nil\n\t}\n\tschema, ok := s.Properties[field]\n\tif ok {\n\t\treturn \u0026schema\n\t}\n\tif s.AdditionalProperties != nil {\n\t\treturn s.AdditionalProperties.Structural\n\t}\n\treturn nil\n}","line":{"from":25,"to":37}} {"id":100014169,"name":"PruneNonNullableNullsWithoutDefaults","signature":"func PruneNonNullableNullsWithoutDefaults(x interface{}, s *structuralschema.Structural)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/prunenulls.go","code":"// PruneNonNullableNullsWithoutDefaults removes non-nullable\n// non-defaultable null values from object.\n//\n// Non-nullable nulls that have a default are left alone here and will\n// be defaulted later.\nfunc PruneNonNullableNullsWithoutDefaults(x interface{}, s *structuralschema.Structural) {\n\tswitch x := x.(type) {\n\tcase map[string]interface{}:\n\t\tfor k, v := range x {\n\t\t\tschema := getSchemaForField(k, s)\n\t\t\tif isNonNullableNonDefaultableNull(v, schema) {\n\t\t\t\tdelete(x, k)\n\t\t\t} else {\n\t\t\t\tPruneNonNullableNullsWithoutDefaults(v, schema)\n\t\t\t}\n\t\t}\n\tcase []interface{}:\n\t\tvar schema *structuralschema.Structural\n\t\tif s != nil {\n\t\t\tschema = s.Items\n\t\t}\n\t\tfor i := range x {\n\t\t\tPruneNonNullableNullsWithoutDefaults(x[i], schema)\n\t\t}\n\tdefault:\n\t\t// scalars, do nothing\n\t}\n}","line":{"from":39,"to":66}} {"id":100014170,"name":"NewRootObjectFunc","signature":"func NewRootObjectFunc() SurroundingObjectFunc","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/surroundingobject.go","code":"// NewRootObjectFunc returns the identity function. The passed focus value\n// must be an object.\nfunc NewRootObjectFunc() SurroundingObjectFunc {\n\treturn func(x interface{}) (map[string]interface{}, AccessorFunc, error) {\n\t\tobj, ok := x.(map[string]interface{})\n\t\tif !ok {\n\t\t\treturn nil, nil, fmt.Errorf(\"object root default value must be of object type\")\n\t\t}\n\t\treturn obj, func(root map[string]interface{}) (interface{}, bool, error) {\n\t\t\treturn root, true, nil\n\t\t}, nil\n\t}\n}","line":{"from":62,"to":74}} {"id":100014171,"name":"WithTypeMeta","signature":"func (f SurroundingObjectFunc) WithTypeMeta(meta metav1.TypeMeta) SurroundingObjectFunc","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/surroundingobject.go","code":"// WithTypeMeta returns a closure with the TypeMeta fields set if they are defined.\n// This mutates f(x).\nfunc (f SurroundingObjectFunc) WithTypeMeta(meta metav1.TypeMeta) SurroundingObjectFunc {\n\treturn func(x interface{}) (map[string]interface{}, AccessorFunc, error) {\n\t\tobj, acc, err := f(x)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tif obj == nil {\n\t\t\tobj = map[string]interface{}{}\n\t\t}\n\t\tif _, found := obj[\"kind\"]; !found {\n\t\t\tobj[\"kind\"] = meta.Kind\n\t\t}\n\t\tif _, found := obj[\"apiVersion\"]; !found {\n\t\t\tobj[\"apiVersion\"] = meta.APIVersion\n\t\t}\n\t\treturn obj, acc, err\n\t}\n}","line":{"from":76,"to":95}} {"id":100014172,"name":"Child","signature":"func (f SurroundingObjectFunc) Child(k string) SurroundingObjectFunc","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/surroundingobject.go","code":"// Child returns a function x =\u003e f({k: x}) and the corresponding accessor.\nfunc (f SurroundingObjectFunc) Child(k string) SurroundingObjectFunc {\n\treturn func(x interface{}) (map[string]interface{}, AccessorFunc, error) {\n\t\tobj, acc, err := f(map[string]interface{}{k: x})\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\treturn obj, func(obj map[string]interface{}) (interface{}, bool, error) {\n\t\t\tx, found, err := acc(obj)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, false, fmt.Errorf(\".%s%v\", k, err)\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\treturn nil, false, nil\n\t\t\t}\n\t\t\tif x, ok := x.(map[string]interface{}); !ok {\n\t\t\t\treturn nil, false, fmt.Errorf(\".%s must be of object type\", k)\n\t\t\t} else if v, found := x[k]; !found {\n\t\t\t\treturn nil, false, nil\n\t\t\t} else {\n\t\t\t\treturn v, true, nil\n\t\t\t}\n\t\t}, err\n\t}\n}","line":{"from":97,"to":121}} {"id":100014173,"name":"Index","signature":"func (f SurroundingObjectFunc) Index() SurroundingObjectFunc","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/surroundingobject.go","code":"// Index returns a function x =\u003e f([x]) and the corresponding accessor.\nfunc (f SurroundingObjectFunc) Index() SurroundingObjectFunc {\n\treturn func(focus interface{}) (map[string]interface{}, AccessorFunc, error) {\n\t\tobj, acc, err := f([]interface{}{focus})\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\treturn obj, func(obj map[string]interface{}) (interface{}, bool, error) {\n\t\t\tx, found, err := acc(obj)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, false, fmt.Errorf(\"[]%v\", err)\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\treturn nil, false, nil\n\t\t\t}\n\t\t\tif x, ok := x.([]interface{}); !ok {\n\t\t\t\treturn nil, false, fmt.Errorf(\"[] must be of array type\")\n\t\t\t} else if len(x) == 0 {\n\t\t\t\treturn nil, false, nil\n\t\t\t} else {\n\t\t\t\treturn x[0], true, nil\n\t\t\t}\n\t\t}, err\n\t}\n}","line":{"from":123,"to":147}} {"id":100014174,"name":"ValidateDefaults","signature":"func ValidateDefaults(ctx context.Context, pth *field.Path, s *structuralschema.Structural, isResourceRoot, requirePrunedDefaults bool) (field.ErrorList, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/validation.go","code":"// ValidateDefaults checks that default values validate and are properly pruned.\n// context is passed for supporting context cancellation during cel validation\nfunc ValidateDefaults(ctx context.Context, pth *field.Path, s *structuralschema.Structural, isResourceRoot, requirePrunedDefaults bool) (field.ErrorList, error) {\n\tf := NewRootObjectFunc().WithTypeMeta(metav1.TypeMeta{APIVersion: \"validation/v1\", Kind: \"Validation\"})\n\n\tif isResourceRoot {\n\t\tif s == nil {\n\t\t\ts = \u0026structuralschema.Structural{}\n\t\t}\n\t\tif !s.XEmbeddedResource {\n\t\t\tclone := *s\n\t\t\tclone.XEmbeddedResource = true\n\t\t\ts = \u0026clone\n\t\t}\n\t}\n\n\tallErr, error, _ := validate(ctx, pth, s, s, f, false, requirePrunedDefaults, celconfig.RuntimeCELCostBudget)\n\treturn allErr, error\n}","line":{"from":38,"to":56}} {"id":100014175,"name":"validate","signature":"func validate(ctx context.Context, pth *field.Path, s *structuralschema.Structural, rootSchema *structuralschema.Structural, f SurroundingObjectFunc, insideMeta, requirePrunedDefaults bool, costBudget int64) (allErrs field.ErrorList, error error, remainingCost int64)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/validation.go","code":"// validate is the recursive step func for the validation. insideMeta is true if s specifies\n// TypeMeta or ObjectMeta. The SurroundingObjectFunc f is used to validate defaults of\n// TypeMeta or ObjectMeta fields.\n// context is passed for supporting context cancellation during cel validation\nfunc validate(ctx context.Context, pth *field.Path, s *structuralschema.Structural, rootSchema *structuralschema.Structural, f SurroundingObjectFunc, insideMeta, requirePrunedDefaults bool, costBudget int64) (allErrs field.ErrorList, error error, remainingCost int64) {\n\tremainingCost = costBudget\n\tif s == nil {\n\t\treturn nil, nil, remainingCost\n\t}\n\n\tif s.XEmbeddedResource {\n\t\tinsideMeta = false\n\t\tf = NewRootObjectFunc().WithTypeMeta(metav1.TypeMeta{APIVersion: \"validation/v1\", Kind: \"Validation\"})\n\t\trootSchema = s\n\t}\n\n\tisResourceRoot := s == rootSchema\n\n\tif s.Default.Object != nil {\n\t\tvalidator := kubeopenapivalidate.NewSchemaValidator(s.ToKubeOpenAPI(), nil, \"\", strfmt.Default)\n\n\t\tif insideMeta {\n\t\t\tobj, _, err := f(runtime.DeepCopyJSONValue(s.Default.Object))\n\t\t\tif err != nil {\n\t\t\t\t// this should never happen. f(s.Default.Object) only gives an error if f is the\n\t\t\t\t// root object func, but the default value is not a map. But then we wouldn't be\n\t\t\t\t// in this case.\n\t\t\t\treturn nil, fmt.Errorf(\"failed to validate default value inside metadata: %v\", err), remainingCost\n\t\t\t}\n\n\t\t\t// check ObjectMeta/TypeMeta and everything else\n\t\t\tif err := schemaobjectmeta.Coerce(nil, obj, rootSchema, true, false); err != nil {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(pth.Child(\"default\"), s.Default.Object, fmt.Sprintf(\"must result in valid metadata: %v\", err)))\n\t\t\t} else if errs := schemaobjectmeta.Validate(nil, obj, rootSchema, true); len(errs) \u003e 0 {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(pth.Child(\"default\"), s.Default.Object, fmt.Sprintf(\"must result in valid metadata: %v\", errs.ToAggregate())))\n\t\t\t} else if errs := apiservervalidation.ValidateCustomResource(pth.Child(\"default\"), s.Default.Object, validator); len(errs) \u003e 0 {\n\t\t\t\tallErrs = append(allErrs, errs...)\n\t\t\t} else if celValidator := cel.NewValidator(s, isResourceRoot, celconfig.PerCallLimit); celValidator != nil {\n\t\t\t\tcelErrs, rmCost := celValidator.Validate(ctx, pth.Child(\"default\"), s, s.Default.Object, s.Default.Object, remainingCost)\n\t\t\t\tremainingCost = rmCost\n\t\t\t\tallErrs = append(allErrs, celErrs...)\n\t\t\t\tif remainingCost \u003c 0 {\n\t\t\t\t\treturn allErrs, nil, remainingCost\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// check whether default is pruned\n\t\t\tif requirePrunedDefaults {\n\t\t\t\tpruned := runtime.DeepCopyJSONValue(s.Default.Object)\n\t\t\t\tpruning.Prune(pruned, s, s.XEmbeddedResource)\n\t\t\t\tif !reflect.DeepEqual(pruned, s.Default.Object) {\n\t\t\t\t\tallErrs = append(allErrs, field.Invalid(pth.Child(\"default\"), s.Default.Object, \"must not have unknown fields\"))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// check ObjectMeta/TypeMeta and everything else\n\t\t\tif err := schemaobjectmeta.Coerce(pth.Child(\"default\"), s.Default.Object, s, s.XEmbeddedResource, false); err != nil {\n\t\t\t\tallErrs = append(allErrs, err)\n\t\t\t} else if errs := schemaobjectmeta.Validate(pth.Child(\"default\"), s.Default.Object, s, s.XEmbeddedResource); len(errs) \u003e 0 {\n\t\t\t\tallErrs = append(allErrs, errs...)\n\t\t\t} else if errs := apiservervalidation.ValidateCustomResource(pth.Child(\"default\"), s.Default.Object, validator); len(errs) \u003e 0 {\n\t\t\t\tallErrs = append(allErrs, errs...)\n\t\t\t} else if celValidator := cel.NewValidator(s, isResourceRoot, celconfig.PerCallLimit); celValidator != nil {\n\t\t\t\tcelErrs, rmCost := celValidator.Validate(ctx, pth.Child(\"default\"), s, s.Default.Object, s.Default.Object, remainingCost)\n\t\t\t\tremainingCost = rmCost\n\t\t\t\tallErrs = append(allErrs, celErrs...)\n\t\t\t\tif remainingCost \u003c 0 {\n\t\t\t\t\treturn allErrs, nil, remainingCost\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// do not follow additionalProperties because defaults are forbidden there\n\n\tif s.Items != nil {\n\t\terrs, err, rCost := validate(ctx, pth.Child(\"items\"), s.Items, rootSchema, f.Index(), insideMeta, requirePrunedDefaults, remainingCost)\n\t\tremainingCost = rCost\n\t\tallErrs = append(allErrs, errs...)\n\t\tif err != nil {\n\t\t\treturn nil, err, remainingCost\n\t\t}\n\t\tif remainingCost \u003c 0 {\n\t\t\treturn allErrs, nil, remainingCost\n\t\t}\n\t}\n\n\tfor k, subSchema := range s.Properties {\n\t\tsubInsideMeta := insideMeta\n\t\tif s.XEmbeddedResource \u0026\u0026 (k == \"metadata\" || k == \"apiVersion\" || k == \"kind\") {\n\t\t\tsubInsideMeta = true\n\t\t}\n\t\terrs, err, rCost := validate(ctx, pth.Child(\"properties\").Key(k), \u0026subSchema, rootSchema, f.Child(k), subInsideMeta, requirePrunedDefaults, remainingCost)\n\t\tremainingCost = rCost\n\t\tallErrs = append(allErrs, errs...)\n\t\tif err != nil {\n\t\t\treturn nil, err, remainingCost\n\t\t}\n\t\tif remainingCost \u003c 0 {\n\t\t\treturn allErrs, nil, remainingCost\n\t\t}\n\t}\n\n\treturn allErrs, nil, remainingCost\n}","line":{"from":58,"to":162}} {"id":100014176,"name":"ToKubeOpenAPI","signature":"func (s *Structural) ToKubeOpenAPI() *spec.Schema","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/kubeopenapi.go","code":"// ToKubeOpenAPI converts a structural schema to go-openapi schema. It is faithful and roundtrippable.\nfunc (s *Structural) ToKubeOpenAPI() *spec.Schema {\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\tret := \u0026spec.Schema{}\n\n\tif s.Items != nil {\n\t\tret.Items = \u0026spec.SchemaOrArray{Schema: s.Items.ToKubeOpenAPI()}\n\t}\n\tif s.Properties != nil {\n\t\tret.Properties = make(map[string]spec.Schema, len(s.Properties))\n\t\tfor k, v := range s.Properties {\n\t\t\tret.Properties[k] = *v.ToKubeOpenAPI()\n\t\t}\n\t}\n\ts.Generic.toKubeOpenAPI(ret)\n\ts.Extensions.toKubeOpenAPI(ret)\n\ts.ValueValidation.toKubeOpenAPI(ret)\n\n\treturn ret\n}","line":{"from":23,"to":45}} {"id":100014177,"name":"toKubeOpenAPI","signature":"func (g *Generic) toKubeOpenAPI(ret *spec.Schema)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/kubeopenapi.go","code":"func (g *Generic) toKubeOpenAPI(ret *spec.Schema) {\n\tif g == nil {\n\t\treturn\n\t}\n\n\tif len(g.Type) != 0 {\n\t\tret.Type = spec.StringOrArray{g.Type}\n\t}\n\tret.Nullable = g.Nullable\n\tif g.AdditionalProperties != nil {\n\t\tret.AdditionalProperties = \u0026spec.SchemaOrBool{\n\t\t\tAllows: g.AdditionalProperties.Bool,\n\t\t\tSchema: g.AdditionalProperties.Structural.ToKubeOpenAPI(),\n\t\t}\n\t}\n\tret.Description = g.Description\n\tret.Title = g.Title\n\tret.Default = g.Default.Object\n}","line":{"from":47,"to":65}} {"id":100014178,"name":"toKubeOpenAPI","signature":"func (x *Extensions) toKubeOpenAPI(ret *spec.Schema)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/kubeopenapi.go","code":"func (x *Extensions) toKubeOpenAPI(ret *spec.Schema) {\n\tif x == nil {\n\t\treturn\n\t}\n\n\tif x.XPreserveUnknownFields {\n\t\tret.VendorExtensible.AddExtension(\"x-kubernetes-preserve-unknown-fields\", true)\n\t}\n\tif x.XEmbeddedResource {\n\t\tret.VendorExtensible.AddExtension(\"x-kubernetes-embedded-resource\", true)\n\t}\n\tif x.XIntOrString {\n\t\tret.VendorExtensible.AddExtension(\"x-kubernetes-int-or-string\", true)\n\t}\n\tif len(x.XListMapKeys) \u003e 0 {\n\t\tret.VendorExtensible.AddExtension(\"x-kubernetes-list-map-keys\", x.XListMapKeys)\n\t}\n\tif x.XListType != nil {\n\t\tret.VendorExtensible.AddExtension(\"x-kubernetes-list-type\", *x.XListType)\n\t}\n\tif x.XMapType != nil {\n\t\tret.VendorExtensible.AddExtension(\"x-kubernetes-map-type\", *x.XMapType)\n\t}\n\tif len(x.XValidations) \u003e 0 {\n\t\tret.VendorExtensible.AddExtension(\"x-kubernetes-validations\", x.XValidations)\n\t}\n}","line":{"from":67,"to":93}} {"id":100014179,"name":"toKubeOpenAPI","signature":"func (v *ValueValidation) toKubeOpenAPI(ret *spec.Schema)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/kubeopenapi.go","code":"func (v *ValueValidation) toKubeOpenAPI(ret *spec.Schema) {\n\tif v == nil {\n\t\treturn\n\t}\n\n\tret.Format = v.Format\n\tret.Maximum = v.Maximum\n\tret.ExclusiveMaximum = v.ExclusiveMaximum\n\tret.Minimum = v.Minimum\n\tret.ExclusiveMinimum = v.ExclusiveMinimum\n\tret.MaxLength = v.MaxLength\n\tret.MinLength = v.MinLength\n\tret.Pattern = v.Pattern\n\tret.MaxItems = v.MaxItems\n\tret.MinItems = v.MinItems\n\tret.UniqueItems = v.UniqueItems\n\tret.MultipleOf = v.MultipleOf\n\tif v.Enum != nil {\n\t\tret.Enum = make([]interface{}, 0, len(v.Enum))\n\t\tfor i := range v.Enum {\n\t\t\tret.Enum = append(ret.Enum, v.Enum[i].Object)\n\t\t}\n\t}\n\tret.MaxProperties = v.MaxProperties\n\tret.MinProperties = v.MinProperties\n\tret.Required = v.Required\n\tfor i := range v.AllOf {\n\t\tret.AllOf = append(ret.AllOf, *v.AllOf[i].toKubeOpenAPI())\n\t}\n\tfor i := range v.AnyOf {\n\t\tret.AnyOf = append(ret.AnyOf, *v.AnyOf[i].toKubeOpenAPI())\n\t}\n\tfor i := range v.OneOf {\n\t\tret.OneOf = append(ret.OneOf, *v.OneOf[i].toKubeOpenAPI())\n\t}\n\tret.Not = v.Not.toKubeOpenAPI()\n}","line":{"from":95,"to":131}} {"id":100014180,"name":"toKubeOpenAPI","signature":"func (vv *NestedValueValidation) toKubeOpenAPI() *spec.Schema","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/kubeopenapi.go","code":"func (vv *NestedValueValidation) toKubeOpenAPI() *spec.Schema {\n\tif vv == nil {\n\t\treturn nil\n\t}\n\n\tret := \u0026spec.Schema{}\n\n\tvv.ValueValidation.toKubeOpenAPI(ret)\n\tif vv.Items != nil {\n\t\tret.Items = \u0026spec.SchemaOrArray{Schema: vv.Items.toKubeOpenAPI()}\n\t}\n\tif vv.Properties != nil {\n\t\tret.Properties = make(map[string]spec.Schema, len(vv.Properties))\n\t\tfor k, v := range vv.Properties {\n\t\t\tret.Properties[k] = *v.toKubeOpenAPI()\n\t\t}\n\t}\n\tvv.ForbiddenGenerics.toKubeOpenAPI(ret) // normally empty. Exception: int-or-string\n\tvv.ForbiddenExtensions.toKubeOpenAPI(ret) // shouldn't do anything\n\n\treturn ret\n}","line":{"from":133,"to":154}} {"id":100014181,"name":"ValidateListSetsAndMaps","signature":"func ValidateListSetsAndMaps(fldPath *field.Path, s *schema.Structural, obj map[string]interface{}) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/listtype/validation.go","code":"// ValidateListSetsAndMaps validates that arrays with x-kubernetes-list-type \"map\" and \"set\" fulfill the uniqueness\n// invariants for the keys (maps) and whole elements (sets).\nfunc ValidateListSetsAndMaps(fldPath *field.Path, s *schema.Structural, obj map[string]interface{}) field.ErrorList {\n\tif s == nil || obj == nil {\n\t\treturn nil\n\t}\n\n\tvar errs field.ErrorList\n\n\tif s.AdditionalProperties != nil \u0026\u0026 s.AdditionalProperties.Structural != nil {\n\t\tfor k, v := range obj {\n\t\t\terrs = append(errs, validationListSetAndMaps(fldPath.Key(k), s.AdditionalProperties.Structural, v)...)\n\t\t}\n\t}\n\tif s.Properties != nil {\n\t\tfor k, v := range obj {\n\t\t\tif sub, ok := s.Properties[k]; ok {\n\t\t\t\terrs = append(errs, validationListSetAndMaps(fldPath.Child(k), \u0026sub, v)...)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn errs\n}","line":{"from":26,"to":49}} {"id":100014182,"name":"validationListSetAndMaps","signature":"func validationListSetAndMaps(fldPath *field.Path, s *schema.Structural, obj interface{}) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/listtype/validation.go","code":"func validationListSetAndMaps(fldPath *field.Path, s *schema.Structural, obj interface{}) field.ErrorList {\n\tswitch obj := obj.(type) {\n\tcase []interface{}:\n\t\treturn validateListSetsAndMapsArray(fldPath, s, obj)\n\tcase map[string]interface{}:\n\t\treturn ValidateListSetsAndMaps(fldPath, s, obj)\n\t}\n\treturn nil\n}","line":{"from":51,"to":59}} {"id":100014183,"name":"validateListSetsAndMapsArray","signature":"func validateListSetsAndMapsArray(fldPath *field.Path, s *schema.Structural, obj []interface{}) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/listtype/validation.go","code":"func validateListSetsAndMapsArray(fldPath *field.Path, s *schema.Structural, obj []interface{}) field.ErrorList {\n\tvar errs field.ErrorList\n\n\tif s.XListType != nil {\n\t\tswitch *s.XListType {\n\t\tcase \"set\":\n\t\t\tnonUnique, err := validateListSet(fldPath, obj)\n\t\t\tif err != nil {\n\t\t\t\terrs = append(errs, err)\n\t\t\t} else {\n\t\t\t\tfor _, i := range nonUnique {\n\t\t\t\t\terrs = append(errs, field.Duplicate(fldPath.Index(i), obj[i]))\n\t\t\t\t}\n\t\t\t}\n\t\tcase \"map\":\n\t\t\terrs = append(errs, validateListMap(fldPath, s, obj)...)\n\t\t}\n\t\t// if a case is ever added here then one should also be added to pkg/apiserver/schema/cel/values.go\n\t}\n\n\tif s.Items != nil {\n\t\tfor i := range obj {\n\t\t\terrs = append(errs, validationListSetAndMaps(fldPath.Index(i), s.Items, obj[i])...)\n\t\t}\n\t}\n\n\treturn errs\n}","line":{"from":61,"to":88}} {"id":100014184,"name":"validateListSet","signature":"func validateListSet(fldPath *field.Path, obj []interface{}) ([]int, *field.Error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/listtype/validation.go","code":"// validateListSet validated uniqueness of unstructured objects (scalar and compound) and\n// returns the first non-unique appearance of items.\n//\n// As a special case to distinguish undefined key and null values, we allow unspecifiedKeyValue and nullObjectValue\n// which are both handled like scalars with correct comparison by Golang.\nfunc validateListSet(fldPath *field.Path, obj []interface{}) ([]int, *field.Error) {\n\tif len(obj) \u003c= 1 {\n\t\treturn nil, nil\n\t}\n\n\tseenScalars := make(map[interface{}]int, len(obj))\n\tseenCompounds := make(map[string]int, len(obj))\n\tvar nonUniqueIndices []int\n\tfor i, x := range obj {\n\t\tswitch x.(type) {\n\t\tcase map[string]interface{}, []interface{}:\n\t\t\tbs, err := json.Marshal(x)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, field.Invalid(fldPath.Index(i), x, \"internal error\")\n\t\t\t}\n\t\t\ts := string(bs)\n\t\t\tif times, seen := seenCompounds[s]; !seen {\n\t\t\t\tseenCompounds[s] = 1\n\t\t\t} else {\n\t\t\t\tseenCompounds[s]++\n\t\t\t\tif times == 1 {\n\t\t\t\t\tnonUniqueIndices = append(nonUniqueIndices, i)\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\tif times, seen := seenScalars[x]; !seen {\n\t\t\t\tseenScalars[x] = 1\n\t\t\t} else {\n\t\t\t\tseenScalars[x]++\n\t\t\t\tif times == 1 {\n\t\t\t\t\tnonUniqueIndices = append(nonUniqueIndices, i)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nonUniqueIndices, nil\n}","line":{"from":90,"to":132}} {"id":100014185,"name":"validateListMap","signature":"func validateListMap(fldPath *field.Path, s *schema.Structural, obj []interface{}) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/listtype/validation.go","code":"func validateListMap(fldPath *field.Path, s *schema.Structural, obj []interface{}) field.ErrorList {\n\t// only allow nil and objects\n\tfor i, x := range obj {\n\t\tif _, ok := x.(map[string]interface{}); x != nil \u0026\u0026 !ok {\n\t\t\treturn field.ErrorList{field.Invalid(fldPath.Index(i), x, \"must be an object for an array of list-type map\")}\n\t\t}\n\t}\n\n\tif len(obj) \u003c= 1 {\n\t\treturn nil\n\t}\n\n\t// optimize simple case of one key\n\tif len(s.XListMapKeys) == 1 {\n\t\ttype unspecifiedKeyValue struct{}\n\n\t\tkeyField := s.XListMapKeys[0]\n\t\tkeys := make([]interface{}, 0, len(obj))\n\t\tfor _, x := range obj {\n\t\t\tif x == nil {\n\t\t\t\tkeys = append(keys, unspecifiedKeyValue{}) // nil object means unspecified key\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tx := x.(map[string]interface{})\n\n\t\t\t// undefined key?\n\t\t\tkey, ok := x[keyField]\n\t\t\tif !ok {\n\t\t\t\tkeys = append(keys, unspecifiedKeyValue{})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tkeys = append(keys, key)\n\t\t}\n\n\t\tnonUnique, err := validateListSet(fldPath, keys)\n\t\tif err != nil {\n\t\t\treturn field.ErrorList{err}\n\t\t}\n\n\t\tvar errs field.ErrorList\n\t\tfor _, i := range nonUnique {\n\t\t\tswitch keys[i] {\n\t\t\tcase unspecifiedKeyValue{}:\n\t\t\t\terrs = append(errs, field.Duplicate(fldPath.Index(i), map[string]interface{}{}))\n\t\t\tdefault:\n\t\t\t\terrs = append(errs, field.Duplicate(fldPath.Index(i), map[string]interface{}{keyField: keys[i]}))\n\t\t\t}\n\t\t}\n\n\t\treturn errs\n\t}\n\n\t// multiple key fields\n\tkeys := make([]interface{}, 0, len(obj))\n\tfor _, x := range obj {\n\t\tkey := map[string]interface{}{}\n\t\tif x == nil {\n\t\t\tkeys = append(keys, key)\n\t\t\tcontinue\n\t\t}\n\n\t\tx := x.(map[string]interface{})\n\n\t\tfor _, keyField := range s.XListMapKeys {\n\t\t\tif k, ok := x[keyField]; ok {\n\t\t\t\tkey[keyField] = k\n\t\t\t}\n\t\t}\n\n\t\tkeys = append(keys, key)\n\t}\n\n\tnonUnique, err := validateListSet(fldPath, keys)\n\tif err != nil {\n\t\treturn field.ErrorList{err}\n\t}\n\n\tvar errs field.ErrorList\n\tfor _, i := range nonUnique {\n\t\terrs = append(errs, field.Duplicate(fldPath.Index(i), keys[i]))\n\t}\n\n\treturn errs\n}","line":{"from":134,"to":219}} {"id":100014186,"name":"CoerceWithOptions","signature":"func CoerceWithOptions(pth *field.Path, obj interface{}, s *structuralschema.Structural, isResourceRoot bool, opts CoerceOptions) (*field.Error, []string)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/objectmeta/algorithm.go","code":"// Coerce checks types of embedded ObjectMeta and TypeMeta and prunes unknown fields inside the former.\n// It does coerce ObjectMeta and TypeMeta at the root if isResourceRoot is true.\n// If opts.ReturnUnknownFieldPaths is true, it will return the paths of any fields that are not a part of the\n// schema that are dropped when unmarshaling.\n// If opts.DropInvalidFields is true, fields of wrong type will be dropped.\nfunc CoerceWithOptions(pth *field.Path, obj interface{}, s *structuralschema.Structural, isResourceRoot bool, opts CoerceOptions) (*field.Error, []string) {\n\tif isResourceRoot {\n\t\tif s == nil {\n\t\t\ts = \u0026structuralschema.Structural{}\n\t\t}\n\t\tif !s.XEmbeddedResource {\n\t\t\tclone := *s\n\t\t\tclone.XEmbeddedResource = true\n\t\t\ts = \u0026clone\n\t\t}\n\t}\n\tc := coercer{DropInvalidFields: opts.DropInvalidFields, ReturnUnknownFieldPaths: opts.ReturnUnknownFieldPaths}\n\tschemaOpts := \u0026structuralschema.UnknownFieldPathOptions{\n\t\tTrackUnknownFieldPaths: opts.ReturnUnknownFieldPaths,\n\t}\n\tfieldErr := c.coerce(pth, obj, s, schemaOpts)\n\tsort.Strings(schemaOpts.UnknownFieldPaths)\n\treturn fieldErr, schemaOpts.UnknownFieldPaths\n}","line":{"from":42,"to":65}} {"id":100014187,"name":"Coerce","signature":"func Coerce(pth *field.Path, obj interface{}, s *structuralschema.Structural, isResourceRoot, dropInvalidFields bool) *field.Error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/objectmeta/algorithm.go","code":"// Coerce calls CoerceWithOptions without returning unknown field paths.\nfunc Coerce(pth *field.Path, obj interface{}, s *structuralschema.Structural, isResourceRoot, dropInvalidFields bool) *field.Error {\n\tfieldErr, _ := CoerceWithOptions(pth, obj, s, isResourceRoot, CoerceOptions{DropInvalidFields: dropInvalidFields})\n\treturn fieldErr\n}","line":{"from":67,"to":71}} {"id":100014188,"name":"coerce","signature":"func (c *coercer) coerce(pth *field.Path, x interface{}, s *structuralschema.Structural, opts *structuralschema.UnknownFieldPathOptions) *field.Error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/objectmeta/algorithm.go","code":"func (c *coercer) coerce(pth *field.Path, x interface{}, s *structuralschema.Structural, opts *structuralschema.UnknownFieldPathOptions) *field.Error {\n\tif s == nil {\n\t\treturn nil\n\t}\n\torigPathLen := len(opts.ParentPath)\n\tdefer func() {\n\t\topts.ParentPath = opts.ParentPath[:origPathLen]\n\t}()\n\tswitch x := x.(type) {\n\tcase map[string]interface{}:\n\t\tfor k, v := range x {\n\t\t\tif s.XEmbeddedResource {\n\t\t\t\tswitch k {\n\t\t\t\tcase \"apiVersion\", \"kind\":\n\t\t\t\t\tif _, ok := v.(string); !ok \u0026\u0026 c.DropInvalidFields {\n\t\t\t\t\t\tdelete(x, k)\n\t\t\t\t\t} else if !ok {\n\t\t\t\t\t\treturn field.Invalid(pth.Child(k), v, \"must be a string\")\n\t\t\t\t\t}\n\t\t\t\tcase \"metadata\":\n\t\t\t\t\tmeta, found, unknownFields, err := GetObjectMetaWithOptions(x, ObjectMetaOptions{\n\t\t\t\t\t\tDropMalformedFields: c.DropInvalidFields,\n\t\t\t\t\t\tReturnUnknownFieldPaths: c.ReturnUnknownFieldPaths,\n\t\t\t\t\t\tParentPath: pth,\n\t\t\t\t\t})\n\t\t\t\t\topts.UnknownFieldPaths = append(opts.UnknownFieldPaths, unknownFields...)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tif !c.DropInvalidFields {\n\t\t\t\t\t\t\treturn field.Invalid(pth.Child(\"metadata\"), v, err.Error())\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// pass through on error if DropInvalidFields is true\n\t\t\t\t\t} else if found {\n\t\t\t\t\t\tif err := SetObjectMeta(x, meta); err != nil {\n\t\t\t\t\t\t\treturn field.Invalid(pth.Child(\"metadata\"), v, err.Error())\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif meta.CreationTimestamp.IsZero() {\n\t\t\t\t\t\t\tunstructured.RemoveNestedField(x, \"metadata\", \"creationTimestamp\")\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tprop, ok := s.Properties[k]\n\t\t\tif ok {\n\t\t\t\topts.AppendKey(k)\n\t\t\t\tif err := c.coerce(pth.Child(k), v, \u0026prop, opts); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\topts.ParentPath = opts.ParentPath[:origPathLen]\n\t\t\t} else if s.AdditionalProperties != nil {\n\t\t\t\topts.AppendKey(k)\n\t\t\t\tif err := c.coerce(pth.Key(k), v, s.AdditionalProperties.Structural, opts); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\topts.ParentPath = opts.ParentPath[:origPathLen]\n\t\t\t}\n\t\t}\n\tcase []interface{}:\n\t\tfor i, v := range x {\n\t\t\topts.AppendIndex(i)\n\t\t\tif err := c.coerce(pth.Index(i), v, s.Items, opts); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\topts.ParentPath = opts.ParentPath[:origPathLen]\n\t\t}\n\tdefault:\n\t\t// scalars, do nothing\n\t}\n\n\treturn nil\n}","line":{"from":78,"to":147}} {"id":100014189,"name":"GetObjectMeta","signature":"func GetObjectMeta(obj map[string]interface{}, dropMalformedFields bool) (*metav1.ObjectMeta, bool, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/objectmeta/coerce.go","code":"// GetObjectMeta calls GetObjectMetaWithOptions without returning unknown field paths.\nfunc GetObjectMeta(obj map[string]interface{}, dropMalformedFields bool) (*metav1.ObjectMeta, bool, error) {\n\tmeta, found, _, err := GetObjectMetaWithOptions(obj, ObjectMetaOptions{\n\t\tDropMalformedFields: dropMalformedFields,\n\t})\n\treturn meta, found, err\n}","line":{"from":30,"to":36}} {"id":100014190,"name":"GetObjectMetaWithOptions","signature":"func GetObjectMetaWithOptions(obj map[string]interface{}, opts ObjectMetaOptions) (*metav1.ObjectMeta, bool, []string, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/objectmeta/coerce.go","code":"// GetObjectMetaWithOptions does conversion of JSON to ObjectMeta.\n// It first tries json.Unmarshal into a metav1.ObjectMeta\n// type. If that does not work and opts.DropMalformedFields is true, it does field-by-field best-effort conversion\n// throwing away fields which lead to errors.\n// If opts.ReturnedUnknownFields is true, it will UnmarshalStrict instead, returning the paths of any unknown fields\n// it encounters (i.e. paths returned as strict errs from UnmarshalStrict)\nfunc GetObjectMetaWithOptions(obj map[string]interface{}, opts ObjectMetaOptions) (*metav1.ObjectMeta, bool, []string, error) {\n\tmetadata, found := obj[\"metadata\"]\n\tif !found {\n\t\treturn nil, false, nil, nil\n\t}\n\n\t// round-trip through JSON first, hoping that unmarshalling just works\n\tobjectMeta := \u0026metav1.ObjectMeta{}\n\tmetadataBytes, err := utiljson.Marshal(metadata)\n\tif err != nil {\n\t\treturn nil, false, nil, err\n\t}\n\tvar unmarshalErr error\n\tif opts.ReturnUnknownFieldPaths {\n\t\tvar strictErrs []error\n\t\tstrictErrs, unmarshalErr = kjson.UnmarshalStrict(metadataBytes, objectMeta)\n\t\tif unmarshalErr == nil {\n\t\t\tif len(strictErrs) \u003e 0 {\n\t\t\t\tunknownPaths := []string{}\n\t\t\t\tprefix := opts.ParentPath.Child(\"metadata\").String()\n\t\t\t\tfor _, err := range strictErrs {\n\t\t\t\t\tif fieldPathErr, ok := err.(kjson.FieldError); ok {\n\t\t\t\t\t\tunknownPaths = append(unknownPaths, prefix+\".\"+fieldPathErr.FieldPath())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn objectMeta, true, unknownPaths, nil\n\t\t\t}\n\t\t\treturn objectMeta, true, nil, nil\n\t\t}\n\t} else {\n\t\tif unmarshalErr = utiljson.Unmarshal(metadataBytes, objectMeta); unmarshalErr == nil {\n\t\t\t// if successful, return\n\t\t\treturn objectMeta, true, nil, nil\n\t\t}\n\t}\n\tif !opts.DropMalformedFields {\n\t\t// if we're not trying to drop malformed fields, return the error\n\t\treturn nil, true, nil, unmarshalErr\n\t}\n\n\tmetadataMap, ok := metadata.(map[string]interface{})\n\tif !ok {\n\t\treturn nil, false, nil, fmt.Errorf(\"invalid metadata: expected object, got %T\", metadata)\n\t}\n\n\t// Go field by field accumulating into the metadata object.\n\t// This takes advantage of the fact that you can repeatedly unmarshal individual fields into a single struct,\n\t// each iteration preserving the old key-values.\n\taccumulatedObjectMeta := \u0026metav1.ObjectMeta{}\n\ttestObjectMeta := \u0026metav1.ObjectMeta{}\n\tvar unknownFields []string\n\tfor k, v := range metadataMap {\n\t\t// serialize a single field\n\t\tif singleFieldBytes, err := utiljson.Marshal(map[string]interface{}{k: v}); err == nil {\n\t\t\t// do a test unmarshal\n\t\t\tif utiljson.Unmarshal(singleFieldBytes, testObjectMeta) == nil {\n\t\t\t\t// if that succeeds, unmarshal for real\n\t\t\t\tif opts.ReturnUnknownFieldPaths {\n\t\t\t\t\tstrictErrs, _ := kjson.UnmarshalStrict(singleFieldBytes, accumulatedObjectMeta)\n\t\t\t\t\tif len(strictErrs) \u003e 0 {\n\t\t\t\t\t\tprefix := opts.ParentPath.Child(\"metadata\").String()\n\t\t\t\t\t\tfor _, err := range strictErrs {\n\t\t\t\t\t\t\tif fieldPathErr, ok := err.(kjson.FieldError); ok {\n\t\t\t\t\t\t\t\tunknownFields = append(unknownFields, prefix+\".\"+fieldPathErr.FieldPath())\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tutiljson.Unmarshal(singleFieldBytes, accumulatedObjectMeta)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn accumulatedObjectMeta, true, unknownFields, nil\n}","line":{"from":54,"to":135}} {"id":100014191,"name":"SetObjectMeta","signature":"func SetObjectMeta(obj map[string]interface{}, objectMeta *metav1.ObjectMeta) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/objectmeta/coerce.go","code":"// SetObjectMeta writes back ObjectMeta into a JSON data structure.\nfunc SetObjectMeta(obj map[string]interface{}, objectMeta *metav1.ObjectMeta) error {\n\tif objectMeta == nil {\n\t\tunstructured.RemoveNestedField(obj, \"metadata\")\n\t\treturn nil\n\t}\n\n\tmetadata, err := runtime.DefaultUnstructuredConverter.ToUnstructured(objectMeta)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tobj[\"metadata\"] = metadata\n\treturn nil\n}","line":{"from":137,"to":151}} {"id":100014192,"name":"Validate","signature":"func Validate(pth *field.Path, obj interface{}, s *structuralschema.Structural, isResourceRoot bool) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/objectmeta/validation.go","code":"// Validate validates embedded ObjectMeta and TypeMeta.\n// It also validate those at the root if isResourceRoot is true.\nfunc Validate(pth *field.Path, obj interface{}, s *structuralschema.Structural, isResourceRoot bool) field.ErrorList {\n\tif isResourceRoot {\n\t\tif s == nil {\n\t\t\ts = \u0026structuralschema.Structural{}\n\t\t}\n\t\tif !s.XEmbeddedResource {\n\t\t\tclone := *s\n\t\t\tclone.XEmbeddedResource = true\n\t\t\ts = \u0026clone\n\t\t}\n\t}\n\treturn validate(pth, obj, s)\n}","line":{"from":30,"to":44}} {"id":100014193,"name":"validate","signature":"func validate(pth *field.Path, x interface{}, s *structuralschema.Structural) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/objectmeta/validation.go","code":"func validate(pth *field.Path, x interface{}, s *structuralschema.Structural) field.ErrorList {\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\tvar allErrs field.ErrorList\n\n\tswitch x := x.(type) {\n\tcase map[string]interface{}:\n\t\tif s.XEmbeddedResource {\n\t\t\tallErrs = append(allErrs, validateEmbeddedResource(pth, x, s)...)\n\t\t}\n\n\t\tfor k, v := range x {\n\t\t\tprop, ok := s.Properties[k]\n\t\t\tif ok {\n\t\t\t\tallErrs = append(allErrs, validate(pth.Child(k), v, \u0026prop)...)\n\t\t\t} else if s.AdditionalProperties != nil {\n\t\t\t\tallErrs = append(allErrs, validate(pth.Key(k), v, s.AdditionalProperties.Structural)...)\n\t\t\t}\n\t\t}\n\tcase []interface{}:\n\t\tfor i, v := range x {\n\t\t\tallErrs = append(allErrs, validate(pth.Index(i), v, s.Items)...)\n\t\t}\n\tdefault:\n\t\t// scalars, do nothing\n\t}\n\n\treturn allErrs\n}","line":{"from":46,"to":76}} {"id":100014194,"name":"validateEmbeddedResource","signature":"func validateEmbeddedResource(pth *field.Path, x map[string]interface{}, s *structuralschema.Structural) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/objectmeta/validation.go","code":"func validateEmbeddedResource(pth *field.Path, x map[string]interface{}, s *structuralschema.Structural) field.ErrorList {\n\tvar allErrs field.ErrorList\n\n\t// require apiVersion and kind, but not metadata\n\tif _, found := x[\"apiVersion\"]; !found {\n\t\tallErrs = append(allErrs, field.Required(pth.Child(\"apiVersion\"), \"must not be empty\"))\n\t}\n\tif _, found := x[\"kind\"]; !found {\n\t\tallErrs = append(allErrs, field.Required(pth.Child(\"kind\"), \"must not be empty\"))\n\t}\n\n\tfor k, v := range x {\n\t\tswitch k {\n\t\tcase \"apiVersion\":\n\t\t\tif apiVersion, ok := v.(string); !ok {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(pth.Child(\"apiVersion\"), v, \"must be a string\"))\n\t\t\t} else if len(apiVersion) == 0 {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(pth.Child(\"apiVersion\"), apiVersion, \"must not be empty\"))\n\t\t\t} else if _, err := schema.ParseGroupVersion(apiVersion); err != nil {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(pth.Child(\"apiVersion\"), apiVersion, err.Error()))\n\t\t\t}\n\t\tcase \"kind\":\n\t\t\tif kind, ok := v.(string); !ok {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(pth.Child(\"kind\"), v, \"must be a string\"))\n\t\t\t} else if len(kind) == 0 {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(pth.Child(\"kind\"), kind, \"must not be empty\"))\n\t\t\t} else if errs := utilvalidation.IsDNS1035Label(strings.ToLower(kind)); len(errs) \u003e 0 {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(pth.Child(\"kind\"), kind, \"may have mixed case, but should otherwise match: \"+strings.Join(errs, \",\")))\n\t\t\t}\n\t\tcase \"metadata\":\n\t\t\tmeta, _, err := GetObjectMeta(x, false)\n\t\t\tif err != nil {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(pth.Child(\"metadata\"), v, err.Error()))\n\t\t\t} else {\n\t\t\t\tif len(meta.Name) == 0 {\n\t\t\t\t\tmeta.Name = \"fakename\" // we have to set something to avoid an error\n\t\t\t\t}\n\t\t\t\tallErrs = append(allErrs, metavalidation.ValidateObjectMeta(meta, len(meta.Namespace) \u003e 0, path.ValidatePathSegmentName, pth.Child(\"metadata\"))...)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":78,"to":121}} {"id":100014195,"name":"RecordUnknownField","signature":"func (o *UnknownFieldPathOptions) RecordUnknownField(field string)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/options.go","code":"// RecordUnknownFields adds a path to an unknown field to the\n// record of UnknownFieldPaths, if TrackUnknownFieldPaths is true\nfunc (o *UnknownFieldPathOptions) RecordUnknownField(field string) {\n\tif !o.TrackUnknownFieldPaths {\n\t\treturn\n\t}\n\tl := len(o.ParentPath)\n\to.AppendKey(field)\n\to.UnknownFieldPaths = append(o.UnknownFieldPaths, strings.Join(o.ParentPath, \"\"))\n\to.ParentPath = o.ParentPath[:l]\n}","line":{"from":36,"to":46}} {"id":100014196,"name":"AppendKey","signature":"func (o *UnknownFieldPathOptions) AppendKey(key string)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/options.go","code":"// AppendKey adds a key (i.e. field) to the current parent\n// path, if TrackUnknownFieldPaths is true.\nfunc (o *UnknownFieldPathOptions) AppendKey(key string) {\n\tif !o.TrackUnknownFieldPaths {\n\t\treturn\n\t}\n\tif len(o.ParentPath) \u003e 0 {\n\t\to.ParentPath = append(o.ParentPath, \".\")\n\t}\n\to.ParentPath = append(o.ParentPath, key)\n}","line":{"from":48,"to":58}} {"id":100014197,"name":"AppendIndex","signature":"func (o *UnknownFieldPathOptions) AppendIndex(index int)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/options.go","code":"// AppendIndex adds an index to the most recent field of\n// the current parent path, if TrackUnknownFieldPaths is true.\nfunc (o *UnknownFieldPathOptions) AppendIndex(index int) {\n\tif !o.TrackUnknownFieldPaths {\n\t\treturn\n\t}\n\to.ParentPath = append(o.ParentPath, \"[\", strconv.Itoa(index), \"]\")\n}","line":{"from":60,"to":67}} {"id":100014198,"name":"PruneWithOptions","signature":"func PruneWithOptions(obj interface{}, s *structuralschema.Structural, isResourceRoot bool, opts structuralschema.UnknownFieldPathOptions) []string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/pruning/algorithm.go","code":"// PruneWithOptions removes object fields in obj which are not specified in s. It skips TypeMeta\n// and ObjectMeta fields if XEmbeddedResource is set to true, or for the root if isResourceRoot=true,\n// i.e. it does not prune unknown metadata fields.\n// It returns the set of fields that it prunes if opts.TrackUnknownFieldPaths is true\nfunc PruneWithOptions(obj interface{}, s *structuralschema.Structural, isResourceRoot bool, opts structuralschema.UnknownFieldPathOptions) []string {\n\tif isResourceRoot {\n\t\tif s == nil {\n\t\t\ts = \u0026structuralschema.Structural{}\n\t\t}\n\t\tif !s.XEmbeddedResource {\n\t\t\tclone := *s\n\t\t\tclone.XEmbeddedResource = true\n\t\t\ts = \u0026clone\n\t\t}\n\t}\n\tprune(obj, s, \u0026opts)\n\tsort.Strings(opts.UnknownFieldPaths)\n\treturn opts.UnknownFieldPaths\n}","line":{"from":25,"to":43}} {"id":100014199,"name":"Prune","signature":"func Prune(obj interface{}, s *structuralschema.Structural, isResourceRoot bool)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/pruning/algorithm.go","code":"// Prune is equivalent to\n// PruneWithOptions(obj, s, isResourceRoot, structuralschema.UnknownFieldPathOptions{})\nfunc Prune(obj interface{}, s *structuralschema.Structural, isResourceRoot bool) {\n\tPruneWithOptions(obj, s, isResourceRoot, structuralschema.UnknownFieldPathOptions{})\n}","line":{"from":45,"to":49}} {"id":100014200,"name":"prune","signature":"func prune(x interface{}, s *structuralschema.Structural, opts *structuralschema.UnknownFieldPathOptions)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/pruning/algorithm.go","code":"func prune(x interface{}, s *structuralschema.Structural, opts *structuralschema.UnknownFieldPathOptions) {\n\tif s != nil \u0026\u0026 s.XPreserveUnknownFields {\n\t\tskipPrune(x, s, opts)\n\t\treturn\n\t}\n\n\torigPathLen := len(opts.ParentPath)\n\tdefer func() {\n\t\topts.ParentPath = opts.ParentPath[:origPathLen]\n\t}()\n\tswitch x := x.(type) {\n\tcase map[string]interface{}:\n\t\tif s == nil {\n\t\t\tfor k := range x {\n\t\t\t\topts.RecordUnknownField(k)\n\t\t\t\tdelete(x, k)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tfor k, v := range x {\n\t\t\tif s.XEmbeddedResource \u0026\u0026 metaFields[k] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tprop, ok := s.Properties[k]\n\t\t\tif ok {\n\t\t\t\topts.AppendKey(k)\n\t\t\t\tprune(v, \u0026prop, opts)\n\t\t\t\topts.ParentPath = opts.ParentPath[:origPathLen]\n\t\t\t} else if s.AdditionalProperties != nil {\n\t\t\t\topts.AppendKey(k)\n\t\t\t\tprune(v, s.AdditionalProperties.Structural, opts)\n\t\t\t\topts.ParentPath = opts.ParentPath[:origPathLen]\n\t\t\t} else {\n\t\t\t\tif !metaFields[k] || len(opts.ParentPath) \u003e 0 {\n\t\t\t\t\topts.RecordUnknownField(k)\n\t\t\t\t}\n\t\t\t\tdelete(x, k)\n\t\t\t}\n\t\t}\n\tcase []interface{}:\n\t\tif s == nil {\n\t\t\tfor i, v := range x {\n\t\t\t\topts.AppendIndex(i)\n\t\t\t\tprune(v, nil, opts)\n\t\t\t\topts.ParentPath = opts.ParentPath[:origPathLen]\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tfor i, v := range x {\n\t\t\topts.AppendIndex(i)\n\t\t\tprune(v, s.Items, opts)\n\t\t\topts.ParentPath = opts.ParentPath[:origPathLen]\n\t\t}\n\tdefault:\n\t\t// scalars, do nothing\n\t}\n}","line":{"from":57,"to":113}} {"id":100014201,"name":"skipPrune","signature":"func skipPrune(x interface{}, s *structuralschema.Structural, opts *structuralschema.UnknownFieldPathOptions)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/pruning/algorithm.go","code":"func skipPrune(x interface{}, s *structuralschema.Structural, opts *structuralschema.UnknownFieldPathOptions) {\n\tif s == nil {\n\t\treturn\n\t}\n\torigPathLen := len(opts.ParentPath)\n\tdefer func() {\n\t\topts.ParentPath = opts.ParentPath[:origPathLen]\n\t}()\n\n\tswitch x := x.(type) {\n\tcase map[string]interface{}:\n\t\tfor k, v := range x {\n\t\t\tif s.XEmbeddedResource \u0026\u0026 metaFields[k] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif prop, ok := s.Properties[k]; ok {\n\t\t\t\topts.AppendKey(k)\n\t\t\t\tprune(v, \u0026prop, opts)\n\t\t\t\topts.ParentPath = opts.ParentPath[:origPathLen]\n\t\t\t} else if s.AdditionalProperties != nil {\n\t\t\t\topts.AppendKey(k)\n\t\t\t\tprune(v, s.AdditionalProperties.Structural, opts)\n\t\t\t\topts.ParentPath = opts.ParentPath[:origPathLen]\n\t\t\t}\n\t\t}\n\tcase []interface{}:\n\t\tfor i, v := range x {\n\t\t\topts.AppendIndex(i)\n\t\t\tskipPrune(v, s.Items, opts)\n\t\t\topts.ParentPath = opts.ParentPath[:origPathLen]\n\t\t}\n\tdefault:\n\t\t// scalars, do nothing\n\t}\n}","line":{"from":115,"to":149}} {"id":100014202,"name":"StripValueValidations","signature":"func (s *Structural) StripValueValidations() *Structural","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/skeleton.go","code":"// StripValueValidations returns a copy without value validations.\nfunc (s *Structural) StripValueValidations() *Structural {\n\ts = s.DeepCopy()\n\tv := Visitor{\n\t\tStructural: func(s *Structural) bool {\n\t\t\tchanged := false\n\t\t\tif s.ValueValidation != nil {\n\t\t\t\ts.ValueValidation = nil\n\t\t\t\tchanged = true\n\t\t\t}\n\t\t\treturn changed\n\t\t},\n\t}\n\tv.Visit(s)\n\treturn s\n}","line":{"from":19,"to":34}} {"id":100014203,"name":"StripNullable","signature":"func (s *Structural) StripNullable() *Structural","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/skeleton.go","code":"// StripNullable returns a copy without nullable.\nfunc (s *Structural) StripNullable() *Structural {\n\ts = s.DeepCopy()\n\tv := Visitor{\n\t\tStructural: func(s *Structural) bool {\n\t\t\tchanged := s.Nullable\n\t\t\ts.Nullable = false\n\t\t\treturn changed\n\t\t},\n\t}\n\tv.Visit(s)\n\treturn s\n}","line":{"from":36,"to":48}} {"id":100014204,"name":"DeepCopy","signature":"func (j JSON) DeepCopy() JSON","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/structural.go","code":"// DeepCopy creates a deep copy of the wrapped JSON value.\nfunc (j JSON) DeepCopy() JSON {\n\treturn JSON{runtime.DeepCopyJSONValue(j.Object)}\n}","line":{"from":194,"to":197}} {"id":100014205,"name":"DeepCopyInto","signature":"func (j JSON) DeepCopyInto(into *JSON)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/structural.go","code":"// DeepCopyInto creates a deep copy of the wrapped JSON value and stores it in into.\nfunc (j JSON) DeepCopyInto(into *JSON) {\n\tinto.Object = runtime.DeepCopyJSONValue(j.Object)\n}","line":{"from":199,"to":202}} {"id":100014206,"name":"Unfold","signature":"func (s *Structural) Unfold() *Structural","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/unfold.go","code":"// Unfold expands vendor extensions of a structural schema.\n// It mutates the receiver.\nfunc (s *Structural) Unfold() *Structural {\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\tmapper := Visitor{\n\t\tStructural: func(s *Structural) bool {\n\t\t\tif !s.XIntOrString {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tskipAnyOf := isIntOrStringAnyOfPattern(s)\n\t\t\tskipFirstAllOfAnyOf := isIntOrStringAllOfPattern(s)\n\t\t\tif skipAnyOf || skipFirstAllOfAnyOf {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tif s.ValueValidation == nil {\n\t\t\t\ts.ValueValidation = \u0026ValueValidation{}\n\t\t\t}\n\t\t\tif s.ValueValidation.AnyOf == nil {\n\t\t\t\ts.ValueValidation.AnyOf = []NestedValueValidation{\n\t\t\t\t\t{ForbiddenGenerics: Generic{Type: \"integer\"}},\n\t\t\t\t\t{ForbiddenGenerics: Generic{Type: \"string\"}},\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ts.ValueValidation.AllOf = append([]NestedValueValidation{\n\t\t\t\t\t{\n\t\t\t\t\t\tValueValidation: ValueValidation{\n\t\t\t\t\t\t\tAnyOf: []NestedValueValidation{\n\t\t\t\t\t\t\t\t{ForbiddenGenerics: Generic{Type: \"integer\"}},\n\t\t\t\t\t\t\t\t{ForbiddenGenerics: Generic{Type: \"string\"}},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}, s.ValueValidation.AllOf...)\n\t\t\t}\n\n\t\t\treturn true\n\t\t},\n\t\tNestedValueValidation: nil, // x-kubernetes-int-or-string cannot be set in nested value validation\n\t}\n\tmapper.Visit(s)\n\n\treturn s\n}","line":{"from":19,"to":66}} {"id":100014207,"name":"ValidateStructural","signature":"func ValidateStructural(fldPath *field.Path, s *Structural) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/validation.go","code":"// ValidateStructural checks that s is a structural schema with the invariants:\n//\n// * structurality: both `ForbiddenGenerics` and `ForbiddenExtensions` only have zero values, with the two exceptions for IntOrString.\n// * RawExtension: for every schema with `x-kubernetes-embedded-resource: true`, `x-kubernetes-preserve-unknown-fields: true` and `type: object` are set\n// * IntOrString: for `x-kubernetes-int-or-string: true` either `type` is empty under `anyOf` and `allOf` or the schema structure is one of these:\n//\n// 1. anyOf:\n// - type: integer\n// - type: string\n// 2. allOf:\n// - anyOf:\n// - type: integer\n// - type: string\n// - ... zero or more\n//\n// * every specified field or array in s is also specified outside of value validation.\n// * metadata at the root can only restrict the name and generateName, and not be specified at all in nested contexts.\n// * additionalProperties at the root is not allowed.\nfunc ValidateStructural(fldPath *field.Path, s *Structural) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tallErrs = append(allErrs, validateStructuralInvariants(s, rootLevel, fldPath)...)\n\tallErrs = append(allErrs, validateStructuralCompleteness(s, fldPath)...)\n\n\t// sort error messages. Otherwise, the errors slice will change every time due to\n\t// maps in the types and randomized iteration.\n\tsort.Slice(allErrs, func(i, j int) bool {\n\t\treturn allErrs[i].Error() \u003c allErrs[j].Error()\n\t})\n\n\treturn allErrs\n}","line":{"from":45,"to":76}} {"id":100014208,"name":"validateStructuralInvariants","signature":"func validateStructuralInvariants(s *Structural, lvl level, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/validation.go","code":"// validateStructuralInvariants checks the invariants of a structural schema.\nfunc validateStructuralInvariants(s *Structural, lvl level, fldPath *field.Path) field.ErrorList {\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\tallErrs := field.ErrorList{}\n\n\tif s.Type == \"array\" \u0026\u0026 s.Items == nil {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"items\"), \"must be specified\"))\n\t}\n\tallErrs = append(allErrs, validateStructuralInvariants(s.Items, itemLevel, fldPath.Child(\"items\"))...)\n\n\tfor k, v := range s.Properties {\n\t\tallErrs = append(allErrs, validateStructuralInvariants(\u0026v, fieldLevel, fldPath.Child(\"properties\").Key(k))...)\n\t}\n\tallErrs = append(allErrs, validateGeneric(\u0026s.Generic, lvl, fldPath)...)\n\tallErrs = append(allErrs, validateExtensions(\u0026s.Extensions, fldPath)...)\n\n\t// detect the two IntOrString exceptions:\n\t// 1) anyOf:\n\t// - type: integer\n\t// - type: string\n\t// 2) allOf:\n\t// - anyOf:\n\t// - type: integer\n\t// - type: string\n\t// - ... zero or more\n\tskipAnyOf := isIntOrStringAnyOfPattern(s)\n\tskipFirstAllOfAnyOf := isIntOrStringAllOfPattern(s)\n\n\tallErrs = append(allErrs, validateValueValidation(s.ValueValidation, skipAnyOf, skipFirstAllOfAnyOf, lvl, fldPath)...)\n\n\tcheckMetadata := (lvl == rootLevel) || s.XEmbeddedResource\n\n\tif s.XEmbeddedResource \u0026\u0026 s.Type != \"object\" {\n\t\tif len(s.Type) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"type\"), \"must be object if x-kubernetes-embedded-resource is true\"))\n\t\t} else {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"type\"), s.Type, \"must be object if x-kubernetes-embedded-resource is true\"))\n\t\t}\n\t} else if len(s.Type) == 0 \u0026\u0026 !s.Extensions.XIntOrString \u0026\u0026 !s.Extensions.XPreserveUnknownFields {\n\t\tswitch lvl {\n\t\tcase rootLevel:\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"type\"), \"must not be empty at the root\"))\n\t\tcase itemLevel:\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"type\"), \"must not be empty for specified array items\"))\n\t\tcase fieldLevel:\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"type\"), \"must not be empty for specified object fields\"))\n\t\t}\n\t}\n\tif s.XEmbeddedResource \u0026\u0026 s.AdditionalProperties != nil {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"additionalProperties\"), \"must not be used if x-kubernetes-embedded-resource is set\"))\n\t}\n\n\tif lvl == rootLevel \u0026\u0026 len(s.Type) \u003e 0 \u0026\u0026 s.Type != \"object\" {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"type\"), s.Type, \"must be object at the root\"))\n\t}\n\n\t// restrict metadata schemas to name and generateName only\n\tif kind, found := s.Properties[\"kind\"]; found \u0026\u0026 checkMetadata {\n\t\tif kind.Type != \"string\" {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"properties\").Key(\"kind\").Child(\"type\"), kind.Type, \"must be string\"))\n\t\t}\n\t}\n\tif apiVersion, found := s.Properties[\"apiVersion\"]; found \u0026\u0026 checkMetadata {\n\t\tif apiVersion.Type != \"string\" {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"properties\").Key(\"apiVersion\").Child(\"type\"), apiVersion.Type, \"must be string\"))\n\t\t}\n\t}\n\n\tif metadata, found := s.Properties[\"metadata\"]; found {\n\t\tallErrs = append(allErrs, validateStructuralMetadataInvariants(\u0026metadata, checkMetadata, lvl, fldPath.Child(\"properties\").Key(\"metadata\"))...)\n\t}\n\n\tif s.XEmbeddedResource \u0026\u0026 !s.XPreserveUnknownFields \u0026\u0026 len(s.Properties) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"properties\"), \"must not be empty if x-kubernetes-embedded-resource is true without x-kubernetes-preserve-unknown-fields\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":78,"to":158}} {"id":100014209,"name":"validateStructuralMetadataInvariants","signature":"func validateStructuralMetadataInvariants(s *Structural, checkMetadata bool, lvl level, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/validation.go","code":"func validateStructuralMetadataInvariants(s *Structural, checkMetadata bool, lvl level, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif checkMetadata \u0026\u0026 s.Type != \"object\" {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"type\"), s.Type, \"must be object\"))\n\t}\n\n\tif lvl == rootLevel {\n\t\t// metadata is a shallow copy. We can mutate it.\n\t\t_, foundName := s.Properties[\"name\"]\n\t\t_, foundGenerateName := s.Properties[\"generateName\"]\n\t\tif foundName \u0026\u0026 foundGenerateName \u0026\u0026 len(s.Properties) == 2 {\n\t\t\ts.Properties = nil\n\t\t} else if (foundName || foundGenerateName) \u0026\u0026 len(s.Properties) == 1 {\n\t\t\ts.Properties = nil\n\t\t}\n\t\ts.Type = \"\"\n\t\ts.Default.Object = nil // this is checked in API validation (and also tested)\n\t\tif s.ValueValidation == nil {\n\t\t\ts.ValueValidation = \u0026ValueValidation{}\n\t\t}\n\t\tif !reflect.DeepEqual(*s, Structural{ValueValidation: \u0026ValueValidation{}}) {\n\t\t\t// TODO: this is actually a field.Invalid error, but we cannot do JSON serialization of metadata here to get a proper message\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath, \"must not specify anything other than name and generateName, but metadata is implicitly specified\"))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":160,"to":188}} {"id":100014210,"name":"isIntOrStringAnyOfPattern","signature":"func isIntOrStringAnyOfPattern(s *Structural) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/validation.go","code":"func isIntOrStringAnyOfPattern(s *Structural) bool {\n\tif s == nil || s.ValueValidation == nil {\n\t\treturn false\n\t}\n\treturn len(s.ValueValidation.AnyOf) == 2 \u0026\u0026 reflect.DeepEqual(s.ValueValidation.AnyOf, intOrStringAnyOf)\n}","line":{"from":190,"to":195}} {"id":100014211,"name":"isIntOrStringAllOfPattern","signature":"func isIntOrStringAllOfPattern(s *Structural) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/validation.go","code":"func isIntOrStringAllOfPattern(s *Structural) bool {\n\tif s == nil || s.ValueValidation == nil {\n\t\treturn false\n\t}\n\treturn len(s.ValueValidation.AllOf) \u003e= 1 \u0026\u0026 len(s.ValueValidation.AllOf[0].AnyOf) == 2 \u0026\u0026 reflect.DeepEqual(s.ValueValidation.AllOf[0].AnyOf, intOrStringAnyOf)\n}","line":{"from":197,"to":202}} {"id":100014212,"name":"validateGeneric","signature":"func validateGeneric(g *Generic, lvl level, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/validation.go","code":"// validateGeneric checks the generic fields of a structural schema.\nfunc validateGeneric(g *Generic, lvl level, fldPath *field.Path) field.ErrorList {\n\tif g == nil {\n\t\treturn nil\n\t}\n\n\tallErrs := field.ErrorList{}\n\n\tif g.AdditionalProperties != nil {\n\t\tif lvl == rootLevel {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"additionalProperties\"), \"must not be used at the root\"))\n\t\t}\n\t\tif g.AdditionalProperties.Structural != nil {\n\t\t\tallErrs = append(allErrs, validateStructuralInvariants(g.AdditionalProperties.Structural, fieldLevel, fldPath.Child(\"additionalProperties\"))...)\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":204,"to":222}} {"id":100014213,"name":"validateExtensions","signature":"func validateExtensions(x *Extensions, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/validation.go","code":"// validateExtensions checks Kubernetes vendor extensions of a structural schema.\nfunc validateExtensions(x *Extensions, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif x.XIntOrString \u0026\u0026 x.XPreserveUnknownFields {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"x-kubernetes-preserve-unknown-fields\"), x.XPreserveUnknownFields, \"must be false if x-kubernetes-int-or-string is true\"))\n\t}\n\tif x.XIntOrString \u0026\u0026 x.XEmbeddedResource {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"x-kubernetes-embedded-resource\"), x.XEmbeddedResource, \"must be false if x-kubernetes-int-or-string is true\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":224,"to":236}} {"id":100014214,"name":"validateValueValidation","signature":"func validateValueValidation(v *ValueValidation, skipAnyOf, skipFirstAllOfAnyOf bool, lvl level, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/validation.go","code":"// validateValueValidation checks the value validation in a structural schema.\nfunc validateValueValidation(v *ValueValidation, skipAnyOf, skipFirstAllOfAnyOf bool, lvl level, fldPath *field.Path) field.ErrorList {\n\tif v == nil {\n\t\treturn nil\n\t}\n\n\tallErrs := field.ErrorList{}\n\n\tif !skipAnyOf {\n\t\tfor i := range v.AnyOf {\n\t\t\tallErrs = append(allErrs, validateNestedValueValidation(\u0026v.AnyOf[i], false, false, lvl, fldPath.Child(\"anyOf\").Index(i))...)\n\t\t}\n\t}\n\n\tfor i := range v.AllOf {\n\t\tskipAnyOf := false\n\t\tif skipFirstAllOfAnyOf \u0026\u0026 i == 0 {\n\t\t\tskipAnyOf = true\n\t\t}\n\t\tallErrs = append(allErrs, validateNestedValueValidation(\u0026v.AllOf[i], skipAnyOf, false, lvl, fldPath.Child(\"allOf\").Index(i))...)\n\t}\n\n\tfor i := range v.OneOf {\n\t\tallErrs = append(allErrs, validateNestedValueValidation(\u0026v.OneOf[i], false, false, lvl, fldPath.Child(\"oneOf\").Index(i))...)\n\t}\n\n\tallErrs = append(allErrs, validateNestedValueValidation(v.Not, false, false, lvl, fldPath.Child(\"not\"))...)\n\n\tif len(v.Pattern) \u003e 0 {\n\t\tif _, err := regexp.Compile(v.Pattern); err != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"pattern\"), v.Pattern, fmt.Sprintf(\"must be a valid regular expression, but isn't: %v\", err)))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":238,"to":273}} {"id":100014215,"name":"validateNestedValueValidation","signature":"func validateNestedValueValidation(v *NestedValueValidation, skipAnyOf, skipAllOfAnyOf bool, lvl level, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/validation.go","code":"// validateNestedValueValidation checks the nested value validation under a logic junctor in a structural schema.\nfunc validateNestedValueValidation(v *NestedValueValidation, skipAnyOf, skipAllOfAnyOf bool, lvl level, fldPath *field.Path) field.ErrorList {\n\tif v == nil {\n\t\treturn nil\n\t}\n\n\tallErrs := field.ErrorList{}\n\n\tallErrs = append(allErrs, validateValueValidation(\u0026v.ValueValidation, skipAnyOf, skipAllOfAnyOf, lvl, fldPath)...)\n\tallErrs = append(allErrs, validateNestedValueValidation(v.Items, false, false, lvl, fldPath.Child(\"items\"))...)\n\n\tfor k, fld := range v.Properties {\n\t\tallErrs = append(allErrs, validateNestedValueValidation(\u0026fld, false, false, fieldLevel, fldPath.Child(\"properties\").Key(k))...)\n\t}\n\n\tif len(v.ForbiddenGenerics.Type) \u003e 0 {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"type\"), \"must be empty to be structural\"))\n\t}\n\tif v.ForbiddenGenerics.AdditionalProperties != nil {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"additionalProperties\"), \"must be undefined to be structural\"))\n\t}\n\tif v.ForbiddenGenerics.Default.Object != nil {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"default\"), \"must be undefined to be structural\"))\n\t}\n\tif len(v.ForbiddenGenerics.Title) \u003e 0 {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"title\"), \"must be empty to be structural\"))\n\t}\n\tif len(v.ForbiddenGenerics.Description) \u003e 0 {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"description\"), \"must be empty to be structural\"))\n\t}\n\tif v.ForbiddenGenerics.Nullable {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"nullable\"), \"must be false to be structural\"))\n\t}\n\n\tif v.ForbiddenExtensions.XPreserveUnknownFields {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"x-kubernetes-preserve-unknown-fields\"), \"must be false to be structural\"))\n\t}\n\tif v.ForbiddenExtensions.XEmbeddedResource {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"x-kubernetes-embedded-resource\"), \"must be false to be structural\"))\n\t}\n\tif v.ForbiddenExtensions.XIntOrString {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"x-kubernetes-int-or-string\"), \"must be false to be structural\"))\n\t}\n\tif len(v.ForbiddenExtensions.XListMapKeys) \u003e 0 {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"x-kubernetes-list-map-keys\"), \"must be empty to be structural\"))\n\t}\n\tif v.ForbiddenExtensions.XListType != nil {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"x-kubernetes-list-type\"), \"must be undefined to be structural\"))\n\t}\n\tif v.ForbiddenExtensions.XMapType != nil {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"x-kubernetes-map-type\"), \"must be undefined to be structural\"))\n\t}\n\tif len(v.ForbiddenExtensions.XValidations) \u003e 0 {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"x-kubernetes-validations\"), \"must be empty to be structural\"))\n\t}\n\n\t// forbid reasoning about metadata because it can lead to metadata restriction we don't want\n\tif _, found := v.Properties[\"metadata\"]; found {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"properties\").Key(\"metadata\"), \"must not be specified in a nested context\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":275,"to":337}} {"id":100014216,"name":"Visit","signature":"func (m *Visitor) Visit(s *Structural)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/visitor.go","code":"// Visit recursively walks through the structural schema and calls the given callbacks\n// at each node of those types.\nfunc (m *Visitor) Visit(s *Structural) {\n\tm.visitStructural(s)\n}","line":{"from":32,"to":36}} {"id":100014217,"name":"visitStructural","signature":"func (m *Visitor) visitStructural(s *Structural) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/visitor.go","code":"func (m *Visitor) visitStructural(s *Structural) bool {\n\tret := false\n\tif m.Structural != nil {\n\t\tret = m.Structural(s)\n\t}\n\n\tif s.Items != nil {\n\t\tm.visitStructural(s.Items)\n\t}\n\tfor k, v := range s.Properties {\n\t\tif changed := m.visitStructural(\u0026v); changed {\n\t\t\tret = true\n\t\t\ts.Properties[k] = v\n\t\t}\n\t}\n\tif s.Generic.AdditionalProperties != nil \u0026\u0026 s.Generic.AdditionalProperties.Structural != nil {\n\t\tm.visitStructural(s.Generic.AdditionalProperties.Structural)\n\t}\n\tif s.ValueValidation != nil {\n\t\tfor i := range s.ValueValidation.AllOf {\n\t\t\tm.visitNestedValueValidation(\u0026s.ValueValidation.AllOf[i])\n\t\t}\n\t\tfor i := range s.ValueValidation.AnyOf {\n\t\t\tm.visitNestedValueValidation(\u0026s.ValueValidation.AnyOf[i])\n\t\t}\n\t\tfor i := range s.ValueValidation.OneOf {\n\t\t\tm.visitNestedValueValidation(\u0026s.ValueValidation.OneOf[i])\n\t\t}\n\t\tif s.ValueValidation.Not != nil {\n\t\t\tm.visitNestedValueValidation(s.ValueValidation.Not)\n\t\t}\n\t}\n\n\treturn ret\n}","line":{"from":38,"to":72}} {"id":100014218,"name":"visitNestedValueValidation","signature":"func (m *Visitor) visitNestedValueValidation(vv *NestedValueValidation) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/visitor.go","code":"func (m *Visitor) visitNestedValueValidation(vv *NestedValueValidation) bool {\n\tret := false\n\tif m.NestedValueValidation != nil {\n\t\tret = m.NestedValueValidation(vv)\n\t}\n\n\tif vv.Items != nil {\n\t\tm.visitNestedValueValidation(vv.Items)\n\t}\n\tfor k, v := range vv.Properties {\n\t\tif changed := m.visitNestedValueValidation(\u0026v); changed {\n\t\t\tret = true\n\t\t\tvv.Properties[k] = v\n\t\t}\n\t}\n\tif vv.ForbiddenGenerics.AdditionalProperties != nil \u0026\u0026 vv.ForbiddenGenerics.AdditionalProperties.Structural != nil {\n\t\tm.visitStructural(vv.ForbiddenGenerics.AdditionalProperties.Structural)\n\t}\n\tfor i := range vv.ValueValidation.AllOf {\n\t\tm.visitNestedValueValidation(\u0026vv.ValueValidation.AllOf[i])\n\t}\n\tfor i := range vv.ValueValidation.AnyOf {\n\t\tm.visitNestedValueValidation(\u0026vv.ValueValidation.AnyOf[i])\n\t}\n\tfor i := range vv.ValueValidation.OneOf {\n\t\tm.visitNestedValueValidation(\u0026vv.ValueValidation.OneOf[i])\n\t}\n\tif vv.ValueValidation.Not != nil {\n\t\tm.visitNestedValueValidation(vv.ValueValidation.Not)\n\t}\n\n\treturn ret\n}","line":{"from":74,"to":106}} {"id":100014219,"name":"StripUnsupportedFormatsPostProcess","signature":"func StripUnsupportedFormatsPostProcess(s *spec.Schema) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/validation/formats.go","code":"// StripUnsupportedFormatsPostProcess sets unsupported formats to empty string.\nfunc StripUnsupportedFormatsPostProcess(s *spec.Schema) error {\n\tif len(s.Format) == 0 {\n\t\treturn nil\n\t}\n\n\tnormalized := strings.Replace(s.Format, \"-\", \"\", -1) // go-openapi default format name normalization\n\tif !supportedFormats.Has(normalized) {\n\t\ts.Format = \"\"\n\t}\n\n\treturn nil\n}","line":{"from":53,"to":65}} {"id":100014220,"name":"NewSchemaValidator","signature":"func NewSchemaValidator(customResourceValidation *apiextensions.CustomResourceValidation) (*validate.SchemaValidator, *spec.Schema, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/validation/validation.go","code":"// NewSchemaValidator creates an openapi schema validator for the given CRD validation.\nfunc NewSchemaValidator(customResourceValidation *apiextensions.CustomResourceValidation) (*validate.SchemaValidator, *spec.Schema, error) {\n\t// Convert CRD schema to openapi schema\n\topenapiSchema := \u0026spec.Schema{}\n\tif customResourceValidation != nil {\n\t\t// TODO: replace with NewStructural(...).ToGoOpenAPI\n\t\tif err := ConvertJSONSchemaPropsWithPostProcess(customResourceValidation.OpenAPIV3Schema, openapiSchema, StripUnsupportedFormatsPostProcess); err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\treturn validate.NewSchemaValidator(openapiSchema, nil, \"\", strfmt.Default), openapiSchema, nil\n}","line":{"from":32,"to":43}} {"id":100014221,"name":"ValidateCustomResource","signature":"func ValidateCustomResource(fldPath *field.Path, customResource interface{}, validator *validate.SchemaValidator) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/validation/validation.go","code":"// ValidateCustomResource validates the Custom Resource against the schema in the CustomResourceDefinition.\n// CustomResource is a JSON data structure.\nfunc ValidateCustomResource(fldPath *field.Path, customResource interface{}, validator *validate.SchemaValidator) field.ErrorList {\n\tif validator == nil {\n\t\treturn nil\n\t}\n\n\tresult := validator.Validate(customResource)\n\tif result.IsValid() {\n\t\treturn nil\n\t}\n\tvar allErrs field.ErrorList\n\tfor _, err := range result.Errors {\n\t\tswitch err := err.(type) {\n\n\t\tcase *openapierrors.Validation:\n\t\t\terrPath := fldPath\n\t\t\tif len(err.Name) \u003e 0 \u0026\u0026 err.Name != \".\" {\n\t\t\t\terrPath = errPath.Child(strings.TrimPrefix(err.Name, \".\"))\n\t\t\t}\n\n\t\t\tswitch err.Code() {\n\t\t\tcase openapierrors.RequiredFailCode:\n\t\t\t\tallErrs = append(allErrs, field.Required(errPath, \"\"))\n\n\t\t\tcase openapierrors.EnumFailCode:\n\t\t\t\tvalues := []string{}\n\t\t\t\tfor _, allowedValue := range err.Values {\n\t\t\t\t\tif s, ok := allowedValue.(string); ok {\n\t\t\t\t\t\tvalues = append(values, s)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tallowedJSON, _ := json.Marshal(allowedValue)\n\t\t\t\t\t\tvalues = append(values, string(allowedJSON))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tallErrs = append(allErrs, field.NotSupported(errPath, err.Value, values))\n\n\t\t\tcase openapierrors.TooLongFailCode:\n\t\t\t\tvalue := interface{}(\"\")\n\t\t\t\tif err.Value != nil {\n\t\t\t\t\tvalue = err.Value\n\t\t\t\t}\n\t\t\t\tmax := int64(-1)\n\t\t\t\tif i, ok := err.Valid.(int64); ok {\n\t\t\t\t\tmax = i\n\t\t\t\t}\n\t\t\t\tallErrs = append(allErrs, field.TooLongMaxLength(errPath, value, int(max)))\n\n\t\t\tcase openapierrors.MaxItemsFailCode:\n\t\t\t\tactual := int64(-1)\n\t\t\t\tif i, ok := err.Value.(int64); ok {\n\t\t\t\t\tactual = i\n\t\t\t\t}\n\t\t\t\tmax := int64(-1)\n\t\t\t\tif i, ok := err.Valid.(int64); ok {\n\t\t\t\t\tmax = i\n\t\t\t\t}\n\t\t\t\tallErrs = append(allErrs, field.TooMany(errPath, int(actual), int(max)))\n\n\t\t\tcase openapierrors.TooManyPropertiesCode:\n\t\t\t\tactual := int64(-1)\n\t\t\t\tif i, ok := err.Value.(int64); ok {\n\t\t\t\t\tactual = i\n\t\t\t\t}\n\t\t\t\tmax := int64(-1)\n\t\t\t\tif i, ok := err.Valid.(int64); ok {\n\t\t\t\t\tmax = i\n\t\t\t\t}\n\t\t\t\tallErrs = append(allErrs, field.TooMany(errPath, int(actual), int(max)))\n\n\t\t\tcase openapierrors.InvalidTypeCode:\n\t\t\t\tvalue := interface{}(\"\")\n\t\t\t\tif err.Value != nil {\n\t\t\t\t\tvalue = err.Value\n\t\t\t\t}\n\t\t\t\tallErrs = append(allErrs, field.TypeInvalid(errPath, value, err.Error()))\n\n\t\t\tdefault:\n\t\t\t\tvalue := interface{}(\"\")\n\t\t\t\tif err.Value != nil {\n\t\t\t\t\tvalue = err.Value\n\t\t\t\t}\n\t\t\t\tallErrs = append(allErrs, field.Invalid(errPath, value, err.Error()))\n\t\t\t}\n\n\t\tdefault:\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, \"\", err.Error()))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":45,"to":135}} {"id":100014222,"name":"ConvertJSONSchemaProps","signature":"func ConvertJSONSchemaProps(in *apiextensions.JSONSchemaProps, out *spec.Schema) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/validation/validation.go","code":"// ConvertJSONSchemaProps converts the schema from apiextensions.JSONSchemaPropos to go-openapi/spec.Schema.\nfunc ConvertJSONSchemaProps(in *apiextensions.JSONSchemaProps, out *spec.Schema) error {\n\treturn ConvertJSONSchemaPropsWithPostProcess(in, out, nil)\n}","line":{"from":137,"to":140}} {"id":100014223,"name":"ConvertJSONSchemaPropsWithPostProcess","signature":"func ConvertJSONSchemaPropsWithPostProcess(in *apiextensions.JSONSchemaProps, out *spec.Schema, postProcess PostProcessFunc) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/validation/validation.go","code":"// ConvertJSONSchemaPropsWithPostProcess converts the schema from apiextensions.JSONSchemaPropos to go-openapi/spec.Schema\n// and run a post process step on each JSONSchemaProps node. postProcess is never called for nil schemas.\nfunc ConvertJSONSchemaPropsWithPostProcess(in *apiextensions.JSONSchemaProps, out *spec.Schema, postProcess PostProcessFunc) error {\n\tif in == nil {\n\t\treturn nil\n\t}\n\n\tout.ID = in.ID\n\tout.Schema = spec.SchemaURL(in.Schema)\n\tout.Description = in.Description\n\tif in.Type != \"\" {\n\t\tout.Type = spec.StringOrArray([]string{in.Type})\n\t}\n\tif in.XIntOrString {\n\t\tout.VendorExtensible.AddExtension(\"x-kubernetes-int-or-string\", true)\n\t\tout.Type = spec.StringOrArray{\"integer\", \"string\"}\n\t}\n\tout.Nullable = in.Nullable\n\tout.Format = in.Format\n\tout.Title = in.Title\n\tout.Maximum = in.Maximum\n\tout.ExclusiveMaximum = in.ExclusiveMaximum\n\tout.Minimum = in.Minimum\n\tout.ExclusiveMinimum = in.ExclusiveMinimum\n\tout.MaxLength = in.MaxLength\n\tout.MinLength = in.MinLength\n\tout.Pattern = in.Pattern\n\tout.MaxItems = in.MaxItems\n\tout.MinItems = in.MinItems\n\tout.UniqueItems = in.UniqueItems\n\tout.MultipleOf = in.MultipleOf\n\tout.MaxProperties = in.MaxProperties\n\tout.MinProperties = in.MinProperties\n\tout.Required = in.Required\n\n\tif in.Default != nil {\n\t\tout.Default = *(in.Default)\n\t}\n\tif in.Example != nil {\n\t\tout.Example = *(in.Example)\n\t}\n\n\tif in.Enum != nil {\n\t\tout.Enum = make([]interface{}, len(in.Enum))\n\t\tfor k, v := range in.Enum {\n\t\t\tout.Enum[k] = v\n\t\t}\n\t}\n\n\tif err := convertSliceOfJSONSchemaProps(\u0026in.AllOf, \u0026out.AllOf, postProcess); err != nil {\n\t\treturn err\n\t}\n\tif err := convertSliceOfJSONSchemaProps(\u0026in.OneOf, \u0026out.OneOf, postProcess); err != nil {\n\t\treturn err\n\t}\n\tif err := convertSliceOfJSONSchemaProps(\u0026in.AnyOf, \u0026out.AnyOf, postProcess); err != nil {\n\t\treturn err\n\t}\n\n\tif in.Not != nil {\n\t\tin, out := \u0026in.Not, \u0026out.Not\n\t\t*out = new(spec.Schema)\n\t\tif err := ConvertJSONSchemaPropsWithPostProcess(*in, *out, postProcess); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tvar err error\n\tout.Properties, err = convertMapOfJSONSchemaProps(in.Properties, postProcess)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tout.PatternProperties, err = convertMapOfJSONSchemaProps(in.PatternProperties, postProcess)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tout.Definitions, err = convertMapOfJSONSchemaProps(in.Definitions, postProcess)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif in.Ref != nil {\n\t\tout.Ref, err = spec.NewRef(*in.Ref)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif in.AdditionalProperties != nil {\n\t\tin, out := \u0026in.AdditionalProperties, \u0026out.AdditionalProperties\n\t\t*out = new(spec.SchemaOrBool)\n\t\tif err := convertJSONSchemaPropsorBool(*in, *out, postProcess); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif in.AdditionalItems != nil {\n\t\tin, out := \u0026in.AdditionalItems, \u0026out.AdditionalItems\n\t\t*out = new(spec.SchemaOrBool)\n\t\tif err := convertJSONSchemaPropsorBool(*in, *out, postProcess); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif in.Items != nil {\n\t\tin, out := \u0026in.Items, \u0026out.Items\n\t\t*out = new(spec.SchemaOrArray)\n\t\tif err := convertJSONSchemaPropsOrArray(*in, *out, postProcess); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif in.Dependencies != nil {\n\t\tin, out := \u0026in.Dependencies, \u0026out.Dependencies\n\t\t*out = make(spec.Dependencies, len(*in))\n\t\tfor key, val := range *in {\n\t\t\tnewVal := new(spec.SchemaOrStringArray)\n\t\t\tif err := convertJSONSchemaPropsOrStringArray(\u0026val, newVal, postProcess); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t(*out)[key] = *newVal\n\t\t}\n\t}\n\n\tif in.ExternalDocs != nil {\n\t\tout.ExternalDocs = \u0026spec.ExternalDocumentation{}\n\t\tout.ExternalDocs.Description = in.ExternalDocs.Description\n\t\tout.ExternalDocs.URL = in.ExternalDocs.URL\n\t}\n\n\tif postProcess != nil {\n\t\tif err := postProcess(out); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif in.XPreserveUnknownFields != nil {\n\t\tout.VendorExtensible.AddExtension(\"x-kubernetes-preserve-unknown-fields\", *in.XPreserveUnknownFields)\n\t}\n\tif in.XEmbeddedResource {\n\t\tout.VendorExtensible.AddExtension(\"x-kubernetes-embedded-resource\", true)\n\t}\n\tif len(in.XListMapKeys) != 0 {\n\t\tout.VendorExtensible.AddExtension(\"x-kubernetes-list-map-keys\", in.XListMapKeys)\n\t}\n\tif in.XListType != nil {\n\t\tout.VendorExtensible.AddExtension(\"x-kubernetes-list-type\", *in.XListType)\n\t}\n\tif in.XMapType != nil {\n\t\tout.VendorExtensible.AddExtension(\"x-kubernetes-map-type\", *in.XMapType)\n\t}\n\tif len(in.XValidations) != 0 {\n\t\tvar serializationValidationRules apiextensionsv1.ValidationRules\n\t\tif err := apiextensionsv1.Convert_apiextensions_ValidationRules_To_v1_ValidationRules(\u0026in.XValidations, \u0026serializationValidationRules, nil); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tout.VendorExtensible.AddExtension(\"x-kubernetes-validations\", serializationValidationRules)\n\t}\n\treturn nil\n}","line":{"from":145,"to":306}} {"id":100014224,"name":"convertSliceOfJSONSchemaProps","signature":"func convertSliceOfJSONSchemaProps(in *[]apiextensions.JSONSchemaProps, out *[]spec.Schema, postProcess PostProcessFunc) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/validation/validation.go","code":"func convertSliceOfJSONSchemaProps(in *[]apiextensions.JSONSchemaProps, out *[]spec.Schema, postProcess PostProcessFunc) error {\n\tif in != nil {\n\t\tfor _, jsonSchemaProps := range *in {\n\t\t\tschema := spec.Schema{}\n\t\t\tif err := ConvertJSONSchemaPropsWithPostProcess(\u0026jsonSchemaProps, \u0026schema, postProcess); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t*out = append(*out, schema)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":308,"to":319}} {"id":100014225,"name":"convertMapOfJSONSchemaProps","signature":"func convertMapOfJSONSchemaProps(in map[string]apiextensions.JSONSchemaProps, postProcess PostProcessFunc) (map[string]spec.Schema, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/validation/validation.go","code":"func convertMapOfJSONSchemaProps(in map[string]apiextensions.JSONSchemaProps, postProcess PostProcessFunc) (map[string]spec.Schema, error) {\n\tif in == nil {\n\t\treturn nil, nil\n\t}\n\n\tout := make(map[string]spec.Schema)\n\tfor k, jsonSchemaProps := range in {\n\t\tschema := spec.Schema{}\n\t\tif err := ConvertJSONSchemaPropsWithPostProcess(\u0026jsonSchemaProps, \u0026schema, postProcess); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tout[k] = schema\n\t}\n\treturn out, nil\n}","line":{"from":321,"to":335}} {"id":100014226,"name":"convertJSONSchemaPropsOrArray","signature":"func convertJSONSchemaPropsOrArray(in *apiextensions.JSONSchemaPropsOrArray, out *spec.SchemaOrArray, postProcess PostProcessFunc) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/validation/validation.go","code":"func convertJSONSchemaPropsOrArray(in *apiextensions.JSONSchemaPropsOrArray, out *spec.SchemaOrArray, postProcess PostProcessFunc) error {\n\tif in.Schema != nil {\n\t\tin, out := \u0026in.Schema, \u0026out.Schema\n\t\t*out = new(spec.Schema)\n\t\tif err := ConvertJSONSchemaPropsWithPostProcess(*in, *out, postProcess); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif in.JSONSchemas != nil {\n\t\tin, out := \u0026in.JSONSchemas, \u0026out.Schemas\n\t\t*out = make([]spec.Schema, len(*in))\n\t\tfor i := range *in {\n\t\t\tif err := ConvertJSONSchemaPropsWithPostProcess(\u0026(*in)[i], \u0026(*out)[i], postProcess); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":337,"to":355}} {"id":100014227,"name":"convertJSONSchemaPropsorBool","signature":"func convertJSONSchemaPropsorBool(in *apiextensions.JSONSchemaPropsOrBool, out *spec.SchemaOrBool, postProcess PostProcessFunc) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/validation/validation.go","code":"func convertJSONSchemaPropsorBool(in *apiextensions.JSONSchemaPropsOrBool, out *spec.SchemaOrBool, postProcess PostProcessFunc) error {\n\tout.Allows = in.Allows\n\tif in.Schema != nil {\n\t\tin, out := \u0026in.Schema, \u0026out.Schema\n\t\t*out = new(spec.Schema)\n\t\tif err := ConvertJSONSchemaPropsWithPostProcess(*in, *out, postProcess); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":357,"to":367}} {"id":100014228,"name":"convertJSONSchemaPropsOrStringArray","signature":"func convertJSONSchemaPropsOrStringArray(in *apiextensions.JSONSchemaPropsOrStringArray, out *spec.SchemaOrStringArray, postProcess PostProcessFunc) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/validation/validation.go","code":"func convertJSONSchemaPropsOrStringArray(in *apiextensions.JSONSchemaPropsOrStringArray, out *spec.SchemaOrStringArray, postProcess PostProcessFunc) error {\n\tout.Property = in.Property\n\tif in.Schema != nil {\n\t\tin, out := \u0026in.Schema, \u0026out.Schema\n\t\t*out = new(spec.Schema)\n\t\tif err := ConvertJSONSchemaPropsWithPostProcess(*in, *out, postProcess); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":369,"to":379}} {"id":100014229,"name":"ApiextensionsV1beta1","signature":"func (c *Clientset) ApiextensionsV1beta1() apiextensionsv1beta1.ApiextensionsV1beta1Interface","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/clientset.go","code":"// ApiextensionsV1beta1 retrieves the ApiextensionsV1beta1Client\nfunc (c *Clientset) ApiextensionsV1beta1() apiextensionsv1beta1.ApiextensionsV1beta1Interface {\n\treturn c.apiextensionsV1beta1\n}","line":{"from":45,"to":48}} {"id":100014230,"name":"ApiextensionsV1","signature":"func (c *Clientset) ApiextensionsV1() apiextensionsv1.ApiextensionsV1Interface","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/clientset.go","code":"// ApiextensionsV1 retrieves the ApiextensionsV1Client\nfunc (c *Clientset) ApiextensionsV1() apiextensionsv1.ApiextensionsV1Interface {\n\treturn c.apiextensionsV1\n}","line":{"from":50,"to":53}} {"id":100014231,"name":"Discovery","signature":"func (c *Clientset) Discovery() discovery.DiscoveryInterface","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/clientset.go","code":"// Discovery retrieves the DiscoveryClient\nfunc (c *Clientset) Discovery() discovery.DiscoveryInterface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.DiscoveryClient\n}","line":{"from":55,"to":61}} {"id":100014232,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*Clientset, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/clientset.go","code":"// NewForConfig creates a new Clientset for the given config.\n// If config's RateLimiter is not set and QPS and Burst are acceptable,\n// NewForConfig will generate a rate-limiter in configShallowCopy.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*Clientset, error) {\n\tconfigShallowCopy := *c\n\n\tif configShallowCopy.UserAgent == \"\" {\n\t\tconfigShallowCopy.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\t// share the transport between all clients\n\thttpClient, err := rest.HTTPClientFor(\u0026configShallowCopy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n}","line":{"from":63,"to":82}} {"id":100014233,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, httpClient *http.Client) (*Clientset, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/clientset.go","code":"// NewForConfigAndClient creates a new Clientset for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\n// If config's RateLimiter is not set and QPS and Burst are acceptable,\n// NewForConfigAndClient will generate a rate-limiter in configShallowCopy.\nfunc NewForConfigAndClient(c *rest.Config, httpClient *http.Client) (*Clientset, error) {\n\tconfigShallowCopy := *c\n\tif configShallowCopy.RateLimiter == nil \u0026\u0026 configShallowCopy.QPS \u003e 0 {\n\t\tif configShallowCopy.Burst \u003c= 0 {\n\t\t\treturn nil, fmt.Errorf(\"burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0\")\n\t\t}\n\t\tconfigShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst)\n\t}\n\n\tvar cs Clientset\n\tvar err error\n\tcs.apiextensionsV1beta1, err = apiextensionsv1beta1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.apiextensionsV1, err = apiextensionsv1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026cs, nil\n}","line":{"from":84,"to":113}} {"id":100014234,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *Clientset","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/clientset.go","code":"// NewForConfigOrDie creates a new Clientset for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *Clientset {\n\tcs, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn cs\n}","line":{"from":115,"to":123}} {"id":100014235,"name":"New","signature":"func New(c rest.Interface) *Clientset","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/clientset.go","code":"// New creates a new Clientset for the given RESTClient.\nfunc New(c rest.Interface) *Clientset {\n\tvar cs Clientset\n\tcs.apiextensionsV1beta1 = apiextensionsv1beta1.New(c)\n\tcs.apiextensionsV1 = apiextensionsv1.New(c)\n\n\tcs.DiscoveryClient = discovery.NewDiscoveryClient(c)\n\treturn \u0026cs\n}","line":{"from":125,"to":133}} {"id":100014236,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/scheme/register.go","code":"func init() {\n\tv1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: \"v1\"})\n\tutilruntime.Must(AddToScheme(Scheme))\n}","line":{"from":55,"to":58}} {"id":100014237,"name":"CustomResourceDefinitions","signature":"func (c *ApiextensionsV1Client) CustomResourceDefinitions() CustomResourceDefinitionInterface","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1/apiextensions_client.go","code":"func (c *ApiextensionsV1Client) CustomResourceDefinitions() CustomResourceDefinitionInterface {\n\treturn newCustomResourceDefinitions(c)\n}","line":{"from":39,"to":41}} {"id":100014238,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*ApiextensionsV1Client, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1/apiextensions_client.go","code":"// NewForConfig creates a new ApiextensionsV1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*ApiextensionsV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":43,"to":56}} {"id":100014239,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*ApiextensionsV1Client, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1/apiextensions_client.go","code":"// NewForConfigAndClient creates a new ApiextensionsV1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*ApiextensionsV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026ApiextensionsV1Client{client}, nil\n}","line":{"from":58,"to":70}} {"id":100014240,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *ApiextensionsV1Client","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1/apiextensions_client.go","code":"// NewForConfigOrDie creates a new ApiextensionsV1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *ApiextensionsV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":72,"to":80}} {"id":100014241,"name":"New","signature":"func New(c rest.Interface) *ApiextensionsV1Client","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1/apiextensions_client.go","code":"// New creates a new ApiextensionsV1Client for the given RESTClient.\nfunc New(c rest.Interface) *ApiextensionsV1Client {\n\treturn \u0026ApiextensionsV1Client{c}\n}","line":{"from":82,"to":85}} {"id":100014242,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1/apiextensions_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":87,"to":98}} {"id":100014243,"name":"RESTClient","signature":"func (c *ApiextensionsV1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1/apiextensions_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *ApiextensionsV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":100,"to":107}} {"id":100014244,"name":"newCustomResourceDefinitions","signature":"func newCustomResourceDefinitions(c *ApiextensionsV1Client) *customResourceDefinitions","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1/customresourcedefinition.go","code":"// newCustomResourceDefinitions returns a CustomResourceDefinitions\nfunc newCustomResourceDefinitions(c *ApiextensionsV1Client) *customResourceDefinitions {\n\treturn \u0026customResourceDefinitions{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":58,"to":63}} {"id":100014245,"name":"Get","signature":"func (c *customResourceDefinitions) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.CustomResourceDefinition, err error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1/customresourcedefinition.go","code":"// Get takes name of the customResourceDefinition, and returns the corresponding customResourceDefinition object, and an error if there is any.\nfunc (c *customResourceDefinitions) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.CustomResourceDefinition, err error) {\n\tresult = \u0026v1.CustomResourceDefinition{}\n\terr = c.client.Get().\n\t\tResource(\"customresourcedefinitions\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":65,"to":75}} {"id":100014246,"name":"List","signature":"func (c *customResourceDefinitions) List(ctx context.Context, opts metav1.ListOptions) (result *v1.CustomResourceDefinitionList, err error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1/customresourcedefinition.go","code":"// List takes label and field selectors, and returns the list of CustomResourceDefinitions that match those selectors.\nfunc (c *customResourceDefinitions) List(ctx context.Context, opts metav1.ListOptions) (result *v1.CustomResourceDefinitionList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.CustomResourceDefinitionList{}\n\terr = c.client.Get().\n\t\tResource(\"customresourcedefinitions\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":77,"to":91}} {"id":100014247,"name":"Watch","signature":"func (c *customResourceDefinitions) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1/customresourcedefinition.go","code":"// Watch returns a watch.Interface that watches the requested customResourceDefinitions.\nfunc (c *customResourceDefinitions) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"customresourcedefinitions\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":93,"to":105}} {"id":100014248,"name":"Create","signature":"func (c *customResourceDefinitions) Create(ctx context.Context, customResourceDefinition *v1.CustomResourceDefinition, opts metav1.CreateOptions) (result *v1.CustomResourceDefinition, err error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1/customresourcedefinition.go","code":"// Create takes the representation of a customResourceDefinition and creates it. Returns the server's representation of the customResourceDefinition, and an error, if there is any.\nfunc (c *customResourceDefinitions) Create(ctx context.Context, customResourceDefinition *v1.CustomResourceDefinition, opts metav1.CreateOptions) (result *v1.CustomResourceDefinition, err error) {\n\tresult = \u0026v1.CustomResourceDefinition{}\n\terr = c.client.Post().\n\t\tResource(\"customresourcedefinitions\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(customResourceDefinition).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":107,"to":117}} {"id":100014249,"name":"Update","signature":"func (c *customResourceDefinitions) Update(ctx context.Context, customResourceDefinition *v1.CustomResourceDefinition, opts metav1.UpdateOptions) (result *v1.CustomResourceDefinition, err error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1/customresourcedefinition.go","code":"// Update takes the representation of a customResourceDefinition and updates it. Returns the server's representation of the customResourceDefinition, and an error, if there is any.\nfunc (c *customResourceDefinitions) Update(ctx context.Context, customResourceDefinition *v1.CustomResourceDefinition, opts metav1.UpdateOptions) (result *v1.CustomResourceDefinition, err error) {\n\tresult = \u0026v1.CustomResourceDefinition{}\n\terr = c.client.Put().\n\t\tResource(\"customresourcedefinitions\").\n\t\tName(customResourceDefinition.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(customResourceDefinition).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":119,"to":130}} {"id":100014250,"name":"UpdateStatus","signature":"func (c *customResourceDefinitions) UpdateStatus(ctx context.Context, customResourceDefinition *v1.CustomResourceDefinition, opts metav1.UpdateOptions) (result *v1.CustomResourceDefinition, err error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1/customresourcedefinition.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *customResourceDefinitions) UpdateStatus(ctx context.Context, customResourceDefinition *v1.CustomResourceDefinition, opts metav1.UpdateOptions) (result *v1.CustomResourceDefinition, err error) {\n\tresult = \u0026v1.CustomResourceDefinition{}\n\terr = c.client.Put().\n\t\tResource(\"customresourcedefinitions\").\n\t\tName(customResourceDefinition.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(customResourceDefinition).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":132,"to":145}} {"id":100014251,"name":"Delete","signature":"func (c *customResourceDefinitions) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1/customresourcedefinition.go","code":"// Delete takes name of the customResourceDefinition and deletes it. Returns an error if one occurs.\nfunc (c *customResourceDefinitions) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"customresourcedefinitions\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":147,"to":155}} {"id":100014252,"name":"DeleteCollection","signature":"func (c *customResourceDefinitions) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1/customresourcedefinition.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *customResourceDefinitions) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"customresourcedefinitions\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":157,"to":170}} {"id":100014253,"name":"Patch","signature":"func (c *customResourceDefinitions) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.CustomResourceDefinition, err error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1/customresourcedefinition.go","code":"// Patch applies the patch and returns the patched customResourceDefinition.\nfunc (c *customResourceDefinitions) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.CustomResourceDefinition, err error) {\n\tresult = \u0026v1.CustomResourceDefinition{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"customresourcedefinitions\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":172,"to":184}} {"id":100014254,"name":"CustomResourceDefinitions","signature":"func (c *ApiextensionsV1beta1Client) CustomResourceDefinitions() CustomResourceDefinitionInterface","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1/apiextensions_client.go","code":"func (c *ApiextensionsV1beta1Client) CustomResourceDefinitions() CustomResourceDefinitionInterface {\n\treturn newCustomResourceDefinitions(c)\n}","line":{"from":39,"to":41}} {"id":100014255,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*ApiextensionsV1beta1Client, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1/apiextensions_client.go","code":"// NewForConfig creates a new ApiextensionsV1beta1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*ApiextensionsV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":43,"to":56}} {"id":100014256,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*ApiextensionsV1beta1Client, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1/apiextensions_client.go","code":"// NewForConfigAndClient creates a new ApiextensionsV1beta1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*ApiextensionsV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026ApiextensionsV1beta1Client{client}, nil\n}","line":{"from":58,"to":70}} {"id":100014257,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *ApiextensionsV1beta1Client","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1/apiextensions_client.go","code":"// NewForConfigOrDie creates a new ApiextensionsV1beta1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *ApiextensionsV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":72,"to":80}} {"id":100014258,"name":"New","signature":"func New(c rest.Interface) *ApiextensionsV1beta1Client","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1/apiextensions_client.go","code":"// New creates a new ApiextensionsV1beta1Client for the given RESTClient.\nfunc New(c rest.Interface) *ApiextensionsV1beta1Client {\n\treturn \u0026ApiextensionsV1beta1Client{c}\n}","line":{"from":82,"to":85}} {"id":100014259,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1/apiextensions_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":87,"to":98}} {"id":100014260,"name":"RESTClient","signature":"func (c *ApiextensionsV1beta1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1/apiextensions_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *ApiextensionsV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":100,"to":107}} {"id":100014261,"name":"newCustomResourceDefinitions","signature":"func newCustomResourceDefinitions(c *ApiextensionsV1beta1Client) *customResourceDefinitions","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1/customresourcedefinition.go","code":"// newCustomResourceDefinitions returns a CustomResourceDefinitions\nfunc newCustomResourceDefinitions(c *ApiextensionsV1beta1Client) *customResourceDefinitions {\n\treturn \u0026customResourceDefinitions{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":58,"to":63}} {"id":100014262,"name":"Get","signature":"func (c *customResourceDefinitions) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.CustomResourceDefinition, err error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1/customresourcedefinition.go","code":"// Get takes name of the customResourceDefinition, and returns the corresponding customResourceDefinition object, and an error if there is any.\nfunc (c *customResourceDefinitions) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.CustomResourceDefinition, err error) {\n\tresult = \u0026v1beta1.CustomResourceDefinition{}\n\terr = c.client.Get().\n\t\tResource(\"customresourcedefinitions\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":65,"to":75}} {"id":100014263,"name":"List","signature":"func (c *customResourceDefinitions) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.CustomResourceDefinitionList, err error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1/customresourcedefinition.go","code":"// List takes label and field selectors, and returns the list of CustomResourceDefinitions that match those selectors.\nfunc (c *customResourceDefinitions) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.CustomResourceDefinitionList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.CustomResourceDefinitionList{}\n\terr = c.client.Get().\n\t\tResource(\"customresourcedefinitions\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":77,"to":91}} {"id":100014264,"name":"Watch","signature":"func (c *customResourceDefinitions) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1/customresourcedefinition.go","code":"// Watch returns a watch.Interface that watches the requested customResourceDefinitions.\nfunc (c *customResourceDefinitions) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"customresourcedefinitions\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":93,"to":105}} {"id":100014265,"name":"Create","signature":"func (c *customResourceDefinitions) Create(ctx context.Context, customResourceDefinition *v1beta1.CustomResourceDefinition, opts v1.CreateOptions) (result *v1beta1.CustomResourceDefinition, err error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1/customresourcedefinition.go","code":"// Create takes the representation of a customResourceDefinition and creates it. Returns the server's representation of the customResourceDefinition, and an error, if there is any.\nfunc (c *customResourceDefinitions) Create(ctx context.Context, customResourceDefinition *v1beta1.CustomResourceDefinition, opts v1.CreateOptions) (result *v1beta1.CustomResourceDefinition, err error) {\n\tresult = \u0026v1beta1.CustomResourceDefinition{}\n\terr = c.client.Post().\n\t\tResource(\"customresourcedefinitions\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(customResourceDefinition).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":107,"to":117}} {"id":100014266,"name":"Update","signature":"func (c *customResourceDefinitions) Update(ctx context.Context, customResourceDefinition *v1beta1.CustomResourceDefinition, opts v1.UpdateOptions) (result *v1beta1.CustomResourceDefinition, err error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1/customresourcedefinition.go","code":"// Update takes the representation of a customResourceDefinition and updates it. Returns the server's representation of the customResourceDefinition, and an error, if there is any.\nfunc (c *customResourceDefinitions) Update(ctx context.Context, customResourceDefinition *v1beta1.CustomResourceDefinition, opts v1.UpdateOptions) (result *v1beta1.CustomResourceDefinition, err error) {\n\tresult = \u0026v1beta1.CustomResourceDefinition{}\n\terr = c.client.Put().\n\t\tResource(\"customresourcedefinitions\").\n\t\tName(customResourceDefinition.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(customResourceDefinition).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":119,"to":130}} {"id":100014267,"name":"UpdateStatus","signature":"func (c *customResourceDefinitions) UpdateStatus(ctx context.Context, customResourceDefinition *v1beta1.CustomResourceDefinition, opts v1.UpdateOptions) (result *v1beta1.CustomResourceDefinition, err error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1/customresourcedefinition.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *customResourceDefinitions) UpdateStatus(ctx context.Context, customResourceDefinition *v1beta1.CustomResourceDefinition, opts v1.UpdateOptions) (result *v1beta1.CustomResourceDefinition, err error) {\n\tresult = \u0026v1beta1.CustomResourceDefinition{}\n\terr = c.client.Put().\n\t\tResource(\"customresourcedefinitions\").\n\t\tName(customResourceDefinition.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(customResourceDefinition).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":132,"to":145}} {"id":100014268,"name":"Delete","signature":"func (c *customResourceDefinitions) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1/customresourcedefinition.go","code":"// Delete takes name of the customResourceDefinition and deletes it. Returns an error if one occurs.\nfunc (c *customResourceDefinitions) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"customresourcedefinitions\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":147,"to":155}} {"id":100014269,"name":"DeleteCollection","signature":"func (c *customResourceDefinitions) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1/customresourcedefinition.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *customResourceDefinitions) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"customresourcedefinitions\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":157,"to":170}} {"id":100014270,"name":"Patch","signature":"func (c *customResourceDefinitions) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.CustomResourceDefinition, err error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1/customresourcedefinition.go","code":"// Patch applies the patch and returns the patched customResourceDefinition.\nfunc (c *customResourceDefinitions) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.CustomResourceDefinition, err error) {\n\tresult = \u0026v1beta1.CustomResourceDefinition{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"customresourcedefinitions\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":172,"to":184}} {"id":100014271,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/apiextensions/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":41,"to":44}} {"id":100014272,"name":"V1beta1","signature":"func (g *group) V1beta1() v1beta1.Interface","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/apiextensions/interface.go","code":"// V1beta1 returns a new v1beta1.Interface.\nfunc (g *group) V1beta1() v1beta1.Interface {\n\treturn v1beta1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":46,"to":49}} {"id":100014273,"name":"V1","signature":"func (g *group) V1() v1.Interface","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/apiextensions/interface.go","code":"// V1 returns a new v1.Interface.\nfunc (g *group) V1() v1.Interface {\n\treturn v1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":51,"to":54}} {"id":100014274,"name":"NewCustomResourceDefinitionInformer","signature":"func NewCustomResourceDefinitionInformer(client clientset.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/apiextensions/v1/customresourcedefinition.go","code":"// NewCustomResourceDefinitionInformer constructs a new informer for CustomResourceDefinition type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewCustomResourceDefinitionInformer(client clientset.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredCustomResourceDefinitionInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100014275,"name":"NewFilteredCustomResourceDefinitionInformer","signature":"func NewFilteredCustomResourceDefinitionInformer(client clientset.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/apiextensions/v1/customresourcedefinition.go","code":"// NewFilteredCustomResourceDefinitionInformer constructs a new informer for CustomResourceDefinition type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredCustomResourceDefinitionInformer(client clientset.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.ApiextensionsV1().CustomResourceDefinitions().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.ApiextensionsV1().CustomResourceDefinitions().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026apiextensionsv1.CustomResourceDefinition{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100014276,"name":"defaultInformer","signature":"func (f *customResourceDefinitionInformer) defaultInformer(client clientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/apiextensions/v1/customresourcedefinition.go","code":"func (f *customResourceDefinitionInformer) defaultInformer(client clientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredCustomResourceDefinitionInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100014277,"name":"Informer","signature":"func (f *customResourceDefinitionInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/apiextensions/v1/customresourcedefinition.go","code":"func (f *customResourceDefinitionInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026apiextensionsv1.CustomResourceDefinition{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100014278,"name":"Lister","signature":"func (f *customResourceDefinitionInformer) Lister() v1.CustomResourceDefinitionLister","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/apiextensions/v1/customresourcedefinition.go","code":"func (f *customResourceDefinitionInformer) Lister() v1.CustomResourceDefinitionLister {\n\treturn v1.NewCustomResourceDefinitionLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100014279,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/apiextensions/v1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":37,"to":40}} {"id":100014280,"name":"CustomResourceDefinitions","signature":"func (v *version) CustomResourceDefinitions() CustomResourceDefinitionInformer","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/apiextensions/v1/interface.go","code":"// CustomResourceDefinitions returns a CustomResourceDefinitionInformer.\nfunc (v *version) CustomResourceDefinitions() CustomResourceDefinitionInformer {\n\treturn \u0026customResourceDefinitionInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":42,"to":45}} {"id":100014281,"name":"NewCustomResourceDefinitionInformer","signature":"func NewCustomResourceDefinitionInformer(client clientset.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/apiextensions/v1beta1/customresourcedefinition.go","code":"// NewCustomResourceDefinitionInformer constructs a new informer for CustomResourceDefinition type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewCustomResourceDefinitionInformer(client clientset.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredCustomResourceDefinitionInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100014282,"name":"NewFilteredCustomResourceDefinitionInformer","signature":"func NewFilteredCustomResourceDefinitionInformer(client clientset.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/apiextensions/v1beta1/customresourcedefinition.go","code":"// NewFilteredCustomResourceDefinitionInformer constructs a new informer for CustomResourceDefinition type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredCustomResourceDefinitionInformer(client clientset.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.ApiextensionsV1beta1().CustomResourceDefinitions().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.ApiextensionsV1beta1().CustomResourceDefinitions().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026apiextensionsv1beta1.CustomResourceDefinition{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100014283,"name":"defaultInformer","signature":"func (f *customResourceDefinitionInformer) defaultInformer(client clientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/apiextensions/v1beta1/customresourcedefinition.go","code":"func (f *customResourceDefinitionInformer) defaultInformer(client clientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredCustomResourceDefinitionInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100014284,"name":"Informer","signature":"func (f *customResourceDefinitionInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/apiextensions/v1beta1/customresourcedefinition.go","code":"func (f *customResourceDefinitionInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026apiextensionsv1beta1.CustomResourceDefinition{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100014285,"name":"Lister","signature":"func (f *customResourceDefinitionInformer) Lister() v1beta1.CustomResourceDefinitionLister","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/apiextensions/v1beta1/customresourcedefinition.go","code":"func (f *customResourceDefinitionInformer) Lister() v1beta1.CustomResourceDefinitionLister {\n\treturn v1beta1.NewCustomResourceDefinitionLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100014286,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/apiextensions/v1beta1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":37,"to":40}} {"id":100014287,"name":"CustomResourceDefinitions","signature":"func (v *version) CustomResourceDefinitions() CustomResourceDefinitionInformer","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/apiextensions/v1beta1/interface.go","code":"// CustomResourceDefinitions returns a CustomResourceDefinitionInformer.\nfunc (v *version) CustomResourceDefinitions() CustomResourceDefinitionInformer {\n\treturn \u0026customResourceDefinitionInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":42,"to":45}} {"id":100014288,"name":"WithCustomResyncConfig","signature":"func WithCustomResyncConfig(resyncConfig map[v1.Object]time.Duration) SharedInformerOption","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/factory.go","code":"// WithCustomResyncConfig sets a custom resync period for the specified informer types.\nfunc WithCustomResyncConfig(resyncConfig map[v1.Object]time.Duration) SharedInformerOption {\n\treturn func(factory *sharedInformerFactory) *sharedInformerFactory {\n\t\tfor k, v := range resyncConfig {\n\t\t\tfactory.customResync[reflect.TypeOf(k)] = v\n\t\t}\n\t\treturn factory\n\t}\n}","line":{"from":57,"to":65}} {"id":100014289,"name":"WithTweakListOptions","signature":"func WithTweakListOptions(tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerOption","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/factory.go","code":"// WithTweakListOptions sets a custom filter on all listers of the configured SharedInformerFactory.\nfunc WithTweakListOptions(tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerOption {\n\treturn func(factory *sharedInformerFactory) *sharedInformerFactory {\n\t\tfactory.tweakListOptions = tweakListOptions\n\t\treturn factory\n\t}\n}","line":{"from":67,"to":73}} {"id":100014290,"name":"WithNamespace","signature":"func WithNamespace(namespace string) SharedInformerOption","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/factory.go","code":"// WithNamespace limits the SharedInformerFactory to the specified namespace.\nfunc WithNamespace(namespace string) SharedInformerOption {\n\treturn func(factory *sharedInformerFactory) *sharedInformerFactory {\n\t\tfactory.namespace = namespace\n\t\treturn factory\n\t}\n}","line":{"from":75,"to":81}} {"id":100014291,"name":"NewSharedInformerFactory","signature":"func NewSharedInformerFactory(client clientset.Interface, defaultResync time.Duration) SharedInformerFactory","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/factory.go","code":"// NewSharedInformerFactory constructs a new instance of sharedInformerFactory for all namespaces.\nfunc NewSharedInformerFactory(client clientset.Interface, defaultResync time.Duration) SharedInformerFactory {\n\treturn NewSharedInformerFactoryWithOptions(client, defaultResync)\n}","line":{"from":83,"to":86}} {"id":100014292,"name":"NewFilteredSharedInformerFactory","signature":"func NewFilteredSharedInformerFactory(client clientset.Interface, defaultResync time.Duration, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerFactory","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/factory.go","code":"// NewFilteredSharedInformerFactory constructs a new instance of sharedInformerFactory.\n// Listers obtained via this SharedInformerFactory will be subject to the same filters\n// as specified here.\n// Deprecated: Please use NewSharedInformerFactoryWithOptions instead\nfunc NewFilteredSharedInformerFactory(client clientset.Interface, defaultResync time.Duration, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerFactory {\n\treturn NewSharedInformerFactoryWithOptions(client, defaultResync, WithNamespace(namespace), WithTweakListOptions(tweakListOptions))\n}","line":{"from":88,"to":94}} {"id":100014293,"name":"NewSharedInformerFactoryWithOptions","signature":"func NewSharedInformerFactoryWithOptions(client clientset.Interface, defaultResync time.Duration, options ...SharedInformerOption) SharedInformerFactory","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/factory.go","code":"// NewSharedInformerFactoryWithOptions constructs a new instance of a SharedInformerFactory with additional options.\nfunc NewSharedInformerFactoryWithOptions(client clientset.Interface, defaultResync time.Duration, options ...SharedInformerOption) SharedInformerFactory {\n\tfactory := \u0026sharedInformerFactory{\n\t\tclient: client,\n\t\tnamespace: v1.NamespaceAll,\n\t\tdefaultResync: defaultResync,\n\t\tinformers: make(map[reflect.Type]cache.SharedIndexInformer),\n\t\tstartedInformers: make(map[reflect.Type]bool),\n\t\tcustomResync: make(map[reflect.Type]time.Duration),\n\t}\n\n\t// Apply all options\n\tfor _, opt := range options {\n\t\tfactory = opt(factory)\n\t}\n\n\treturn factory\n}","line":{"from":96,"to":113}} {"id":100014294,"name":"Start","signature":"func (f *sharedInformerFactory) Start(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/factory.go","code":"func (f *sharedInformerFactory) Start(stopCh \u003c-chan struct{}) {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\n\tif f.shuttingDown {\n\t\treturn\n\t}\n\n\tfor informerType, informer := range f.informers {\n\t\tif !f.startedInformers[informerType] {\n\t\t\tf.wg.Add(1)\n\t\t\t// We need a new variable in each loop iteration,\n\t\t\t// otherwise the goroutine would use the loop variable\n\t\t\t// and that keeps changing.\n\t\t\tinformer := informer\n\t\t\tgo func() {\n\t\t\t\tdefer f.wg.Done()\n\t\t\t\tinformer.Run(stopCh)\n\t\t\t}()\n\t\t\tf.startedInformers[informerType] = true\n\t\t}\n\t}\n}","line":{"from":115,"to":137}} {"id":100014295,"name":"Shutdown","signature":"func (f *sharedInformerFactory) Shutdown()","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/factory.go","code":"func (f *sharedInformerFactory) Shutdown() {\n\tf.lock.Lock()\n\tf.shuttingDown = true\n\tf.lock.Unlock()\n\n\t// Will return immediately if there is nothing to wait for.\n\tf.wg.Wait()\n}","line":{"from":139,"to":146}} {"id":100014296,"name":"WaitForCacheSync","signature":"func (f *sharedInformerFactory) WaitForCacheSync(stopCh \u003c-chan struct{}) map[reflect.Type]bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/factory.go","code":"func (f *sharedInformerFactory) WaitForCacheSync(stopCh \u003c-chan struct{}) map[reflect.Type]bool {\n\tinformers := func() map[reflect.Type]cache.SharedIndexInformer {\n\t\tf.lock.Lock()\n\t\tdefer f.lock.Unlock()\n\n\t\tinformers := map[reflect.Type]cache.SharedIndexInformer{}\n\t\tfor informerType, informer := range f.informers {\n\t\t\tif f.startedInformers[informerType] {\n\t\t\t\tinformers[informerType] = informer\n\t\t\t}\n\t\t}\n\t\treturn informers\n\t}()\n\n\tres := map[reflect.Type]bool{}\n\tfor informType, informer := range informers {\n\t\tres[informType] = cache.WaitForCacheSync(stopCh, informer.HasSynced)\n\t}\n\treturn res\n}","line":{"from":148,"to":167}} {"id":100014297,"name":"InformerFor","signature":"func (f *sharedInformerFactory) InformerFor(obj runtime.Object, newFunc internalinterfaces.NewInformerFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/factory.go","code":"// InternalInformerFor returns the SharedIndexInformer for obj using an internal\n// client.\nfunc (f *sharedInformerFactory) InformerFor(obj runtime.Object, newFunc internalinterfaces.NewInformerFunc) cache.SharedIndexInformer {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\n\tinformerType := reflect.TypeOf(obj)\n\tinformer, exists := f.informers[informerType]\n\tif exists {\n\t\treturn informer\n\t}\n\n\tresyncPeriod, exists := f.customResync[informerType]\n\tif !exists {\n\t\tresyncPeriod = f.defaultResync\n\t}\n\n\tinformer = newFunc(f.client, resyncPeriod)\n\tf.informers[informerType] = informer\n\n\treturn informer\n}","line":{"from":169,"to":190}} {"id":100014298,"name":"Apiextensions","signature":"func (f *sharedInformerFactory) Apiextensions() apiextensions.Interface","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/factory.go","code":"func (f *sharedInformerFactory) Apiextensions() apiextensions.Interface {\n\treturn apiextensions.New(f, f.namespace, f.tweakListOptions)\n}","line":{"from":249,"to":251}} {"id":100014299,"name":"Informer","signature":"func (f *genericInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/generic.go","code":"// Informer returns the SharedIndexInformer.\nfunc (f *genericInformer) Informer() cache.SharedIndexInformer {\n\treturn f.informer\n}","line":{"from":42,"to":45}} {"id":100014300,"name":"Lister","signature":"func (f *genericInformer) Lister() cache.GenericLister","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/generic.go","code":"// Lister returns the GenericLister.\nfunc (f *genericInformer) Lister() cache.GenericLister {\n\treturn cache.NewGenericLister(f.Informer().GetIndexer(), f.resource)\n}","line":{"from":47,"to":50}} {"id":100014301,"name":"ForResource","signature":"func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/generic.go","code":"// ForResource gives generic access to a shared informer of the matching type\n// TODO extend this to unknown resources with a client pool\nfunc (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) {\n\tswitch resource {\n\t// Group=apiextensions.k8s.io, Version=v1\n\tcase v1.SchemeGroupVersion.WithResource(\"customresourcedefinitions\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Apiextensions().V1().CustomResourceDefinitions().Informer()}, nil\n\n\t\t// Group=apiextensions.k8s.io, Version=v1beta1\n\tcase v1beta1.SchemeGroupVersion.WithResource(\"customresourcedefinitions\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Apiextensions().V1beta1().CustomResourceDefinitions().Informer()}, nil\n\n\t}\n\n\treturn nil, fmt.Errorf(\"no informer found for %v\", resource)\n}","line":{"from":52,"to":67}} {"id":100014302,"name":"NewCustomResourceDefinitionLister","signature":"func NewCustomResourceDefinitionLister(indexer cache.Indexer) CustomResourceDefinitionLister","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/listers/apiextensions/v1/customresourcedefinition.go","code":"// NewCustomResourceDefinitionLister returns a new CustomResourceDefinitionLister.\nfunc NewCustomResourceDefinitionLister(indexer cache.Indexer) CustomResourceDefinitionLister {\n\treturn \u0026customResourceDefinitionLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100014303,"name":"List","signature":"func (s *customResourceDefinitionLister) List(selector labels.Selector) (ret []*v1.CustomResourceDefinition, err error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/listers/apiextensions/v1/customresourcedefinition.go","code":"// List lists all CustomResourceDefinitions in the indexer.\nfunc (s *customResourceDefinitionLister) List(selector labels.Selector) (ret []*v1.CustomResourceDefinition, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.CustomResourceDefinition))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100014304,"name":"Get","signature":"func (s *customResourceDefinitionLister) Get(name string) (*v1.CustomResourceDefinition, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/listers/apiextensions/v1/customresourcedefinition.go","code":"// Get retrieves the CustomResourceDefinition from the index for a given name.\nfunc (s *customResourceDefinitionLister) Get(name string) (*v1.CustomResourceDefinition, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"customresourcedefinition\"), name)\n\t}\n\treturn obj.(*v1.CustomResourceDefinition), nil\n}","line":{"from":58,"to":68}} {"id":100014305,"name":"NewCustomResourceDefinitionLister","signature":"func NewCustomResourceDefinitionLister(indexer cache.Indexer) CustomResourceDefinitionLister","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/listers/apiextensions/v1beta1/customresourcedefinition.go","code":"// NewCustomResourceDefinitionLister returns a new CustomResourceDefinitionLister.\nfunc NewCustomResourceDefinitionLister(indexer cache.Indexer) CustomResourceDefinitionLister {\n\treturn \u0026customResourceDefinitionLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100014306,"name":"List","signature":"func (s *customResourceDefinitionLister) List(selector labels.Selector) (ret []*v1beta1.CustomResourceDefinition, err error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/listers/apiextensions/v1beta1/customresourcedefinition.go","code":"// List lists all CustomResourceDefinitions in the indexer.\nfunc (s *customResourceDefinitionLister) List(selector labels.Selector) (ret []*v1beta1.CustomResourceDefinition, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.CustomResourceDefinition))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100014307,"name":"Get","signature":"func (s *customResourceDefinitionLister) Get(name string) (*v1beta1.CustomResourceDefinition, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/client/listers/apiextensions/v1beta1/customresourcedefinition.go","code":"// Get retrieves the CustomResourceDefinition from the index for a given name.\nfunc (s *customResourceDefinitionLister) Get(name string) (*v1beta1.CustomResourceDefinition, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"customresourcedefinition\"), name)\n\t}\n\treturn obj.(*v1beta1.CustomResourceDefinition), nil\n}","line":{"from":58,"to":68}} {"id":100014308,"name":"NewCustomResourceDefinitionsServerOptions","signature":"func NewCustomResourceDefinitionsServerOptions(out, errOut io.Writer) *CustomResourceDefinitionsServerOptions","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/cmd/server/options/options.go","code":"// NewCustomResourceDefinitionsServerOptions creates default options of an apiextensions-apiserver.\nfunc NewCustomResourceDefinitionsServerOptions(out, errOut io.Writer) *CustomResourceDefinitionsServerOptions {\n\to := \u0026CustomResourceDefinitionsServerOptions{\n\t\tServerRunOptions: genericoptions.NewServerRunOptions(),\n\t\tRecommendedOptions: genericoptions.NewRecommendedOptions(\n\t\t\tdefaultEtcdPathPrefix,\n\t\t\tapiserver.Codecs.LegacyCodec(v1beta1.SchemeGroupVersion, v1.SchemeGroupVersion),\n\t\t),\n\t\tAPIEnablement: genericoptions.NewAPIEnablementOptions(),\n\n\t\tStdOut: out,\n\t\tStdErr: errOut,\n\t}\n\n\treturn o\n}","line":{"from":55,"to":70}} {"id":100014309,"name":"AddFlags","signature":"func (o CustomResourceDefinitionsServerOptions) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/cmd/server/options/options.go","code":"// AddFlags adds the apiextensions-apiserver flags to the flagset.\nfunc (o CustomResourceDefinitionsServerOptions) AddFlags(fs *pflag.FlagSet) {\n\to.ServerRunOptions.AddUniversalFlags(fs)\n\to.RecommendedOptions.AddFlags(fs)\n\to.APIEnablement.AddFlags(fs)\n}","line":{"from":72,"to":77}} {"id":100014310,"name":"Validate","signature":"func (o CustomResourceDefinitionsServerOptions) Validate() error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/cmd/server/options/options.go","code":"// Validate validates the apiextensions-apiserver options.\nfunc (o CustomResourceDefinitionsServerOptions) Validate() error {\n\terrors := []error{}\n\terrors = append(errors, o.ServerRunOptions.Validate()...)\n\terrors = append(errors, o.RecommendedOptions.Validate()...)\n\terrors = append(errors, o.APIEnablement.Validate(apiserver.Scheme)...)\n\treturn utilerrors.NewAggregate(errors)\n}","line":{"from":79,"to":86}} {"id":100014311,"name":"Complete","signature":"func (o *CustomResourceDefinitionsServerOptions) Complete() error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/cmd/server/options/options.go","code":"// Complete fills in missing options.\nfunc (o *CustomResourceDefinitionsServerOptions) Complete() error {\n\treturn nil\n}","line":{"from":88,"to":91}} {"id":100014312,"name":"Config","signature":"func (o CustomResourceDefinitionsServerOptions) Config() (*apiserver.Config, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/cmd/server/options/options.go","code":"// Config returns an apiextensions-apiserver configuration.\nfunc (o CustomResourceDefinitionsServerOptions) Config() (*apiserver.Config, error) {\n\t// TODO have a \"real\" external address\n\tif err := o.RecommendedOptions.SecureServing.MaybeDefaultWithSelfSignedCerts(\"localhost\", nil, []net.IP{netutils.ParseIPSloppy(\"127.0.0.1\")}); err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating self-signed certificates: %v\", err)\n\t}\n\n\tserverConfig := genericapiserver.NewRecommendedConfig(apiserver.Codecs)\n\tif err := o.ServerRunOptions.ApplyTo(\u0026serverConfig.Config); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := o.RecommendedOptions.ApplyTo(serverConfig); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := o.APIEnablement.ApplyTo(\u0026serverConfig.Config, apiserver.DefaultAPIResourceConfigSource(), apiserver.Scheme); err != nil {\n\t\treturn nil, err\n\t}\n\tcrdRESTOptionsGetter, err := NewCRDRESTOptionsGetter(*o.RecommendedOptions.Etcd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfig := \u0026apiserver.Config{\n\t\tGenericConfig: serverConfig,\n\t\tExtraConfig: apiserver.ExtraConfig{\n\t\t\tCRDRESTOptionsGetter: crdRESTOptionsGetter,\n\t\t\tServiceResolver: \u0026serviceResolver{serverConfig.SharedInformerFactory.Core().V1().Services().Lister()},\n\t\t\tAuthResolverWrapper: webhook.NewDefaultAuthenticationInfoResolverWrapper(nil, nil, serverConfig.LoopbackClientConfig, oteltrace.NewNoopTracerProvider()),\n\t\t},\n\t}\n\treturn config, nil\n}","line":{"from":93,"to":123}} {"id":100014313,"name":"NewCRDRESTOptionsGetter","signature":"func NewCRDRESTOptionsGetter(etcdOptions genericoptions.EtcdOptions) (genericregistry.RESTOptionsGetter, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/cmd/server/options/options.go","code":"// NewCRDRESTOptionsGetter create a RESTOptionsGetter for CustomResources.\n// This works on a copy of the etcd options so we don't mutate originals.\n// We assume that the input etcd options have been completed already.\n// Avoid messing with anything outside of changes to StorageConfig as that\n// may lead to unexpected behavior when the options are applied.\nfunc NewCRDRESTOptionsGetter(etcdOptions genericoptions.EtcdOptions) (genericregistry.RESTOptionsGetter, error) {\n\tetcdOptions.StorageConfig.Codec = unstructured.UnstructuredJSONScheme\n\tetcdOptions.WatchCacheSizes = nil // this control is not provided for custom resources\n\tetcdOptions.SkipHealthEndpoints = true // avoid double wiring of health checks\n\n\t// creates a generic apiserver config for etcdOptions to mutate\n\tc := genericapiserver.Config{}\n\tif err := etcdOptions.ApplyTo(\u0026c); err != nil {\n\t\treturn nil, err\n\t}\n\trestOptionsGetter := c.RESTOptionsGetter\n\tif restOptionsGetter == nil {\n\t\treturn nil, fmt.Errorf(\"server.Config RESTOptionsGetter should not be nil\")\n\t}\n\t// sanity check that no other fields are set\n\tc.RESTOptionsGetter = nil\n\tif !reflect.DeepEqual(c, genericapiserver.Config{}) {\n\t\treturn nil, fmt.Errorf(\"only RESTOptionsGetter should have been mutated in server.Config\")\n\t}\n\treturn restOptionsGetter, nil\n}","line":{"from":125,"to":150}} {"id":100014314,"name":"ResolveEndpoint","signature":"func (r *serviceResolver) ResolveEndpoint(namespace, name string, port int32) (*url.URL, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/cmd/server/options/options.go","code":"func (r *serviceResolver) ResolveEndpoint(namespace, name string, port int32) (*url.URL, error) {\n\treturn proxy.ResolveCluster(r.services, namespace, name, port)\n}","line":{"from":156,"to":158}} {"id":100014315,"name":"NewServerCommand","signature":"func NewServerCommand(out, errOut io.Writer, stopCh \u003c-chan struct{}) *cobra.Command","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/cmd/server/server.go","code":"func NewServerCommand(out, errOut io.Writer, stopCh \u003c-chan struct{}) *cobra.Command {\n\to := options.NewCustomResourceDefinitionsServerOptions(out, errOut)\n\n\tcmd := \u0026cobra.Command{\n\t\tShort: \"Launch an API extensions API server\",\n\t\tLong: \"Launch an API extensions API server\",\n\t\tRunE: func(c *cobra.Command, args []string) error {\n\t\t\tif err := o.Complete(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := o.Validate(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := Run(o, stopCh); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tfs := cmd.Flags()\n\to.AddFlags(fs)\n\treturn cmd\n}","line":{"from":28,"to":51}} {"id":100014316,"name":"Run","signature":"func Run(o *options.CustomResourceDefinitionsServerOptions, stopCh \u003c-chan struct{}) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/cmd/server/server.go","code":"func Run(o *options.CustomResourceDefinitionsServerOptions, stopCh \u003c-chan struct{}) error {\n\tconfig, err := o.Config()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tserver, err := config.Complete().New(genericapiserver.NewEmptyDelegate())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn server.GenericAPIServer.PrepareRun().Run(stopCh)\n}","line":{"from":53,"to":64}} {"id":100014317,"name":"NewKubernetesAPIApprovalPolicyConformantConditionController","signature":"func NewKubernetesAPIApprovalPolicyConformantConditionController(","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/apiapproval/apiapproval_controller.go","code":"// NewKubernetesAPIApprovalPolicyConformantConditionController constructs a KubernetesAPIApprovalPolicyConformant schema condition controller.\nfunc NewKubernetesAPIApprovalPolicyConformantConditionController(\n\tcrdInformer informers.CustomResourceDefinitionInformer,\n\tcrdClient client.CustomResourceDefinitionsGetter,\n) *KubernetesAPIApprovalPolicyConformantConditionController {\n\tc := \u0026KubernetesAPIApprovalPolicyConformantConditionController{\n\t\tcrdClient: crdClient,\n\t\tcrdLister: crdInformer.Lister(),\n\t\tcrdSynced: crdInformer.Informer().HasSynced,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"kubernetes_api_approval_conformant_condition_controller\"),\n\t\tlastSeenProtectedAnnotation: map[string]string{},\n\t}\n\n\tcrdInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: c.addCustomResourceDefinition,\n\t\tUpdateFunc: c.updateCustomResourceDefinition,\n\t\tDeleteFunc: c.deleteCustomResourceDefinition,\n\t})\n\n\tc.syncFn = c.sync\n\n\treturn c\n}","line":{"from":57,"to":79}} {"id":100014318,"name":"calculateCondition","signature":"func calculateCondition(crd *apiextensionsv1.CustomResourceDefinition) *apiextensionsv1.CustomResourceDefinitionCondition","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/apiapproval/apiapproval_controller.go","code":"// calculateCondition determines the new KubernetesAPIApprovalPolicyConformant condition\nfunc calculateCondition(crd *apiextensionsv1.CustomResourceDefinition) *apiextensionsv1.CustomResourceDefinitionCondition {\n\tif !apihelpers.IsProtectedCommunityGroup(crd.Spec.Group) {\n\t\treturn nil\n\t}\n\n\tapprovalState, reason := apihelpers.GetAPIApprovalState(crd.Annotations)\n\tswitch approvalState {\n\tcase apihelpers.APIApprovalInvalid:\n\t\treturn \u0026apiextensionsv1.CustomResourceDefinitionCondition{\n\t\t\tType: apiextensionsv1.KubernetesAPIApprovalPolicyConformant,\n\t\t\tStatus: apiextensionsv1.ConditionFalse,\n\t\t\tReason: \"InvalidAnnotation\",\n\t\t\tMessage: reason,\n\t\t}\n\tcase apihelpers.APIApprovalMissing:\n\t\treturn \u0026apiextensionsv1.CustomResourceDefinitionCondition{\n\t\t\tType: apiextensionsv1.KubernetesAPIApprovalPolicyConformant,\n\t\t\tStatus: apiextensionsv1.ConditionFalse,\n\t\t\tReason: \"MissingAnnotation\",\n\t\t\tMessage: reason,\n\t\t}\n\tcase apihelpers.APIApproved:\n\t\treturn \u0026apiextensionsv1.CustomResourceDefinitionCondition{\n\t\t\tType: apiextensionsv1.KubernetesAPIApprovalPolicyConformant,\n\t\t\tStatus: apiextensionsv1.ConditionTrue,\n\t\t\tReason: \"ApprovedAnnotation\",\n\t\t\tMessage: reason,\n\t\t}\n\tcase apihelpers.APIApprovalBypassed:\n\t\treturn \u0026apiextensionsv1.CustomResourceDefinitionCondition{\n\t\t\tType: apiextensionsv1.KubernetesAPIApprovalPolicyConformant,\n\t\t\tStatus: apiextensionsv1.ConditionFalse,\n\t\t\tReason: \"UnapprovedAnnotation\",\n\t\t\tMessage: reason,\n\t\t}\n\tdefault:\n\t\treturn \u0026apiextensionsv1.CustomResourceDefinitionCondition{\n\t\t\tType: apiextensionsv1.KubernetesAPIApprovalPolicyConformant,\n\t\t\tStatus: apiextensionsv1.ConditionUnknown,\n\t\t\tReason: \"UnknownAnnotation\",\n\t\t\tMessage: reason,\n\t\t}\n\t}\n}","line":{"from":81,"to":125}} {"id":100014319,"name":"sync","signature":"func (c *KubernetesAPIApprovalPolicyConformantConditionController) sync(key string) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/apiapproval/apiapproval_controller.go","code":"func (c *KubernetesAPIApprovalPolicyConformantConditionController) sync(key string) error {\n\tinCustomResourceDefinition, err := c.crdLister.Get(key)\n\tif apierrors.IsNotFound(err) {\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// avoid repeated calculation for the same annotation\n\tprotectionAnnotationValue := inCustomResourceDefinition.Annotations[apiextensionsv1.KubeAPIApprovedAnnotation]\n\tc.lastSeenProtectedAnnotationLock.Lock()\n\tlastSeen, seenBefore := c.lastSeenProtectedAnnotation[inCustomResourceDefinition.Name]\n\tc.lastSeenProtectedAnnotationLock.Unlock()\n\tif seenBefore \u0026\u0026 protectionAnnotationValue == lastSeen {\n\t\treturn nil\n\t}\n\n\t// check old condition\n\tcond := calculateCondition(inCustomResourceDefinition)\n\tif cond == nil {\n\t\t// because group is immutable, if we have no condition now, we have no need to remove a condition.\n\t\treturn nil\n\t}\n\told := apihelpers.FindCRDCondition(inCustomResourceDefinition, apiextensionsv1.KubernetesAPIApprovalPolicyConformant)\n\n\t// don't attempt a write if all the condition details are the same\n\tif old != nil \u0026\u0026 old.Status == cond.Status \u0026\u0026 old.Reason == cond.Reason \u0026\u0026 old.Message == cond.Message {\n\t\t// no need to update annotation because we took no action.\n\t\treturn nil\n\t}\n\n\t// update condition\n\tcrd := inCustomResourceDefinition.DeepCopy()\n\tapihelpers.SetCRDCondition(crd, *cond)\n\n\t_, err = c.crdClient.CustomResourceDefinitions().UpdateStatus(context.TODO(), crd, metav1.UpdateOptions{})\n\tif apierrors.IsNotFound(err) || apierrors.IsConflict(err) {\n\t\t// deleted or changed in the meantime, we'll get called again\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// store annotation in order to avoid repeated updates for the same annotation (and potential\n\t// fights of API server in HA environments).\n\tc.lastSeenProtectedAnnotationLock.Lock()\n\tdefer c.lastSeenProtectedAnnotationLock.Unlock()\n\tc.lastSeenProtectedAnnotation[crd.Name] = protectionAnnotationValue\n\n\treturn nil\n}","line":{"from":127,"to":179}} {"id":100014320,"name":"Run","signature":"func (c *KubernetesAPIApprovalPolicyConformantConditionController) Run(workers int, stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/apiapproval/apiapproval_controller.go","code":"// Run starts the controller.\nfunc (c *KubernetesAPIApprovalPolicyConformantConditionController) Run(workers int, stopCh \u003c-chan struct{}) {\n\tdefer utilruntime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\n\tklog.Infof(\"Starting KubernetesAPIApprovalPolicyConformantConditionController\")\n\tdefer klog.Infof(\"Shutting down KubernetesAPIApprovalPolicyConformantConditionController\")\n\n\tif !cache.WaitForCacheSync(stopCh, c.crdSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.Until(c.runWorker, time.Second, stopCh)\n\t}\n\n\t\u003c-stopCh\n}","line":{"from":181,"to":198}} {"id":100014321,"name":"runWorker","signature":"func (c *KubernetesAPIApprovalPolicyConformantConditionController) runWorker()","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/apiapproval/apiapproval_controller.go","code":"func (c *KubernetesAPIApprovalPolicyConformantConditionController) runWorker() {\n\tfor c.processNextWorkItem() {\n\t}\n}","line":{"from":200,"to":203}} {"id":100014322,"name":"processNextWorkItem","signature":"func (c *KubernetesAPIApprovalPolicyConformantConditionController) processNextWorkItem() bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/apiapproval/apiapproval_controller.go","code":"// processNextWorkItem deals with one key off the queue. It returns false when it's time to quit.\nfunc (c *KubernetesAPIApprovalPolicyConformantConditionController) processNextWorkItem() bool {\n\tkey, quit := c.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.queue.Done(key)\n\n\terr := c.syncFn(key.(string))\n\tif err == nil {\n\t\tc.queue.Forget(key)\n\t\treturn true\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"%v failed with: %v\", key, err))\n\tc.queue.AddRateLimited(key)\n\n\treturn true\n}","line":{"from":205,"to":223}} {"id":100014323,"name":"enqueue","signature":"func (c *KubernetesAPIApprovalPolicyConformantConditionController) enqueue(obj *apiextensionsv1.CustomResourceDefinition)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/apiapproval/apiapproval_controller.go","code":"func (c *KubernetesAPIApprovalPolicyConformantConditionController) enqueue(obj *apiextensionsv1.CustomResourceDefinition) {\n\tkey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Couldn't get key for object %#v: %v\", obj, err))\n\t\treturn\n\t}\n\n\tc.queue.Add(key)\n}","line":{"from":225,"to":233}} {"id":100014324,"name":"addCustomResourceDefinition","signature":"func (c *KubernetesAPIApprovalPolicyConformantConditionController) addCustomResourceDefinition(obj interface{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/apiapproval/apiapproval_controller.go","code":"func (c *KubernetesAPIApprovalPolicyConformantConditionController) addCustomResourceDefinition(obj interface{}) {\n\tcastObj := obj.(*apiextensionsv1.CustomResourceDefinition)\n\tklog.V(4).Infof(\"Adding %s\", castObj.Name)\n\tc.enqueue(castObj)\n}","line":{"from":235,"to":239}} {"id":100014325,"name":"updateCustomResourceDefinition","signature":"func (c *KubernetesAPIApprovalPolicyConformantConditionController) updateCustomResourceDefinition(obj, _ interface{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/apiapproval/apiapproval_controller.go","code":"func (c *KubernetesAPIApprovalPolicyConformantConditionController) updateCustomResourceDefinition(obj, _ interface{}) {\n\tcastObj := obj.(*apiextensionsv1.CustomResourceDefinition)\n\tklog.V(4).Infof(\"Updating %s\", castObj.Name)\n\tc.enqueue(castObj)\n}","line":{"from":241,"to":245}} {"id":100014326,"name":"deleteCustomResourceDefinition","signature":"func (c *KubernetesAPIApprovalPolicyConformantConditionController) deleteCustomResourceDefinition(obj interface{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/apiapproval/apiapproval_controller.go","code":"func (c *KubernetesAPIApprovalPolicyConformantConditionController) deleteCustomResourceDefinition(obj interface{}) {\n\tcastObj, ok := obj.(*apiextensionsv1.CustomResourceDefinition)\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"Couldn't get object from tombstone %#v\", obj)\n\t\t\treturn\n\t\t}\n\t\tcastObj, ok = tombstone.Obj.(*apiextensionsv1.CustomResourceDefinition)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"Tombstone contained object that is not expected %#v\", obj)\n\t\t\treturn\n\t\t}\n\t}\n\n\tc.lastSeenProtectedAnnotationLock.Lock()\n\tdefer c.lastSeenProtectedAnnotationLock.Unlock()\n\tdelete(c.lastSeenProtectedAnnotation, castObj.Name)\n}","line":{"from":247,"to":265}} {"id":100014327,"name":"NewEstablishingController","signature":"func NewEstablishingController(crdInformer informers.CustomResourceDefinitionInformer,","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/establish/establishing_controller.go","code":"// NewEstablishingController creates new EstablishingController.\nfunc NewEstablishingController(crdInformer informers.CustomResourceDefinitionInformer,\n\tcrdClient client.CustomResourceDefinitionsGetter) *EstablishingController {\n\tec := \u0026EstablishingController{\n\t\tcrdClient: crdClient,\n\t\tcrdLister: crdInformer.Lister(),\n\t\tcrdSynced: crdInformer.Informer().HasSynced,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"crdEstablishing\"),\n\t}\n\n\tec.syncFn = ec.sync\n\n\treturn ec\n}","line":{"from":51,"to":64}} {"id":100014328,"name":"QueueCRD","signature":"func (ec *EstablishingController) QueueCRD(key string, timeout time.Duration)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/establish/establishing_controller.go","code":"// QueueCRD adds CRD into the establishing queue.\nfunc (ec *EstablishingController) QueueCRD(key string, timeout time.Duration) {\n\tec.queue.AddAfter(key, timeout)\n}","line":{"from":66,"to":69}} {"id":100014329,"name":"Run","signature":"func (ec *EstablishingController) Run(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/establish/establishing_controller.go","code":"// Run starts the EstablishingController.\nfunc (ec *EstablishingController) Run(stopCh \u003c-chan struct{}) {\n\tdefer utilruntime.HandleCrash()\n\tdefer ec.queue.ShutDown()\n\n\tklog.Info(\"Starting EstablishingController\")\n\tdefer klog.Info(\"Shutting down EstablishingController\")\n\n\tif !cache.WaitForCacheSync(stopCh, ec.crdSynced) {\n\t\treturn\n\t}\n\n\t// only start one worker thread since its a slow moving API\n\tgo wait.Until(ec.runWorker, time.Second, stopCh)\n\n\t\u003c-stopCh\n}","line":{"from":71,"to":87}} {"id":100014330,"name":"runWorker","signature":"func (ec *EstablishingController) runWorker()","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/establish/establishing_controller.go","code":"func (ec *EstablishingController) runWorker() {\n\tfor ec.processNextWorkItem() {\n\t}\n}","line":{"from":89,"to":92}} {"id":100014331,"name":"processNextWorkItem","signature":"func (ec *EstablishingController) processNextWorkItem() bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/establish/establishing_controller.go","code":"// processNextWorkItem deals with one key off the queue.\n// It returns false when it's time to quit.\nfunc (ec *EstablishingController) processNextWorkItem() bool {\n\tkey, quit := ec.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer ec.queue.Done(key)\n\n\terr := ec.syncFn(key.(string))\n\tif err == nil {\n\t\tec.queue.Forget(key)\n\t\treturn true\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"%v failed with: %v\", key, err))\n\tec.queue.AddRateLimited(key)\n\n\treturn true\n}","line":{"from":94,"to":113}} {"id":100014332,"name":"sync","signature":"func (ec *EstablishingController) sync(key string) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/establish/establishing_controller.go","code":"// sync is used to turn CRDs into the Established state.\nfunc (ec *EstablishingController) sync(key string) error {\n\tcachedCRD, err := ec.crdLister.Get(key)\n\tif apierrors.IsNotFound(err) {\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !apiextensionshelpers.IsCRDConditionTrue(cachedCRD, apiextensionsv1.NamesAccepted) ||\n\t\tapiextensionshelpers.IsCRDConditionTrue(cachedCRD, apiextensionsv1.Established) {\n\t\treturn nil\n\t}\n\n\tcrd := cachedCRD.DeepCopy()\n\testablishedCondition := apiextensionsv1.CustomResourceDefinitionCondition{\n\t\tType: apiextensionsv1.Established,\n\t\tStatus: apiextensionsv1.ConditionTrue,\n\t\tReason: \"InitialNamesAccepted\",\n\t\tMessage: \"the initial names have been accepted\",\n\t}\n\tapiextensionshelpers.SetCRDCondition(crd, establishedCondition)\n\n\t// Update server with new CRD condition.\n\t_, err = ec.crdClient.CustomResourceDefinitions().UpdateStatus(context.TODO(), crd, metav1.UpdateOptions{})\n\tif apierrors.IsNotFound(err) || apierrors.IsConflict(err) {\n\t\t// deleted or changed in the meantime, we'll get called again\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":115,"to":150}} {"id":100014333,"name":"OverlappingBuiltInResources","signature":"func OverlappingBuiltInResources() map[schema.GroupResource]bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/finalizer/crd_finalizer.go","code":"// OverlappingBuiltInResources returns the set of built-in group/resources that are persisted\n// in storage paths that overlap with CRD storage paths, and should not be deleted\n// by this controller if an associated CRD is deleted.\nfunc OverlappingBuiltInResources() map[schema.GroupResource]bool {\n\treturn map[schema.GroupResource]bool{\n\t\t{Group: \"apiregistration.k8s.io\", Resource: \"apiservices\"}: true,\n\t\t{Group: \"apiextensions.k8s.io\", Resource: \"customresourcedefinitions\"}: true,\n\t}\n}","line":{"from":48,"to":56}} {"id":100014334,"name":"NewCRDFinalizer","signature":"func NewCRDFinalizer(","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/finalizer/crd_finalizer.go","code":"// NewCRDFinalizer creates a new CRDFinalizer.\nfunc NewCRDFinalizer(\n\tcrdInformer informers.CustomResourceDefinitionInformer,\n\tcrdClient client.CustomResourceDefinitionsGetter,\n\tcrClientGetter CRClientGetter,\n) *CRDFinalizer {\n\tc := \u0026CRDFinalizer{\n\t\tcrdClient: crdClient,\n\t\tcrdLister: crdInformer.Lister(),\n\t\tcrdSynced: crdInformer.Informer().HasSynced,\n\t\tcrClientGetter: crClientGetter,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"crd_finalizer\"),\n\t}\n\n\tcrdInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: c.addCustomResourceDefinition,\n\t\tUpdateFunc: c.updateCustomResourceDefinition,\n\t})\n\n\tc.syncFn = c.sync\n\n\treturn c\n}","line":{"from":85,"to":107}} {"id":100014335,"name":"sync","signature":"func (c *CRDFinalizer) sync(key string) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/finalizer/crd_finalizer.go","code":"func (c *CRDFinalizer) sync(key string) error {\n\tcachedCRD, err := c.crdLister.Get(key)\n\tif apierrors.IsNotFound(err) {\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// no work to do\n\tif cachedCRD.DeletionTimestamp.IsZero() || !apiextensionshelpers.CRDHasFinalizer(cachedCRD, apiextensionsv1.CustomResourceCleanupFinalizer) {\n\t\treturn nil\n\t}\n\n\tcrd := cachedCRD.DeepCopy()\n\n\t// update the status condition. This cleanup could take a while.\n\tapiextensionshelpers.SetCRDCondition(crd, apiextensionsv1.CustomResourceDefinitionCondition{\n\t\tType: apiextensionsv1.Terminating,\n\t\tStatus: apiextensionsv1.ConditionTrue,\n\t\tReason: \"InstanceDeletionInProgress\",\n\t\tMessage: \"CustomResource deletion is in progress\",\n\t})\n\tcrd, err = c.crdClient.CustomResourceDefinitions().UpdateStatus(context.TODO(), crd, metav1.UpdateOptions{})\n\tif apierrors.IsNotFound(err) || apierrors.IsConflict(err) {\n\t\t// deleted or changed in the meantime, we'll get called again\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Now we can start deleting items. We should use the REST API to ensure that all normal admission runs.\n\t// Since we control the endpoints, we know that delete collection works. No need to delete if not established.\n\tif OverlappingBuiltInResources()[schema.GroupResource{Group: crd.Spec.Group, Resource: crd.Spec.Names.Plural}] {\n\t\t// Skip deletion, explain why, and proceed to remove the finalizer and delete the CRD\n\t\tapiextensionshelpers.SetCRDCondition(crd, apiextensionsv1.CustomResourceDefinitionCondition{\n\t\t\tType: apiextensionsv1.Terminating,\n\t\t\tStatus: apiextensionsv1.ConditionFalse,\n\t\t\tReason: \"OverlappingBuiltInResource\",\n\t\t\tMessage: \"instances overlap with built-in resources in storage\",\n\t\t})\n\t} else if apiextensionshelpers.IsCRDConditionTrue(crd, apiextensionsv1.Established) {\n\t\tcond, deleteErr := c.deleteInstances(crd)\n\t\tapiextensionshelpers.SetCRDCondition(crd, cond)\n\t\tif deleteErr != nil {\n\t\t\tif _, err = c.crdClient.CustomResourceDefinitions().UpdateStatus(context.TODO(), crd, metav1.UpdateOptions{}); err != nil {\n\t\t\t\tutilruntime.HandleError(err)\n\t\t\t}\n\t\t\treturn deleteErr\n\t\t}\n\t} else {\n\t\tapiextensionshelpers.SetCRDCondition(crd, apiextensionsv1.CustomResourceDefinitionCondition{\n\t\t\tType: apiextensionsv1.Terminating,\n\t\t\tStatus: apiextensionsv1.ConditionFalse,\n\t\t\tReason: \"NeverEstablished\",\n\t\t\tMessage: \"resource was never established\",\n\t\t})\n\t}\n\n\tapiextensionshelpers.CRDRemoveFinalizer(crd, apiextensionsv1.CustomResourceCleanupFinalizer)\n\t_, err = c.crdClient.CustomResourceDefinitions().UpdateStatus(context.TODO(), crd, metav1.UpdateOptions{})\n\tif apierrors.IsNotFound(err) || apierrors.IsConflict(err) {\n\t\t// deleted or changed in the meantime, we'll get called again\n\t\treturn nil\n\t}\n\treturn err\n}","line":{"from":109,"to":176}} {"id":100014336,"name":"deleteInstances","signature":"func (c *CRDFinalizer) deleteInstances(crd *apiextensionsv1.CustomResourceDefinition) (apiextensionsv1.CustomResourceDefinitionCondition, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/finalizer/crd_finalizer.go","code":"func (c *CRDFinalizer) deleteInstances(crd *apiextensionsv1.CustomResourceDefinition) (apiextensionsv1.CustomResourceDefinitionCondition, error) {\n\t// Now we can start deleting items. While it would be ideal to use a REST API client, doing so\n\t// could incorrectly delete a ThirdPartyResource with the same URL as the CustomResource, so we go\n\t// directly to the storage instead. Since we control the storage, we know that delete collection works.\n\tcrClient, err := c.crClientGetter.GetCustomResourceListerCollectionDeleter(crd)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"unable to find a custom resource client for %s.%s: %v\", crd.Status.AcceptedNames.Plural, crd.Spec.Group, err)\n\t\treturn apiextensionsv1.CustomResourceDefinitionCondition{\n\t\t\tType: apiextensionsv1.Terminating,\n\t\t\tStatus: apiextensionsv1.ConditionTrue,\n\t\t\tReason: \"InstanceDeletionFailed\",\n\t\t\tMessage: fmt.Sprintf(\"could not list instances: %v\", err),\n\t\t}, err\n\t}\n\n\tctx := genericapirequest.NewContext()\n\tallResources, err := crClient.List(ctx, nil)\n\tif err != nil {\n\t\treturn apiextensionsv1.CustomResourceDefinitionCondition{\n\t\t\tType: apiextensionsv1.Terminating,\n\t\t\tStatus: apiextensionsv1.ConditionTrue,\n\t\t\tReason: \"InstanceDeletionFailed\",\n\t\t\tMessage: fmt.Sprintf(\"could not list instances: %v\", err),\n\t\t}, err\n\t}\n\n\tdeletedNamespaces := sets.String{}\n\tdeleteErrors := []error{}\n\tfor _, item := range allResources.(*unstructured.UnstructuredList).Items {\n\t\tmetadata, err := meta.Accessor(\u0026item)\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(err)\n\t\t\tcontinue\n\t\t}\n\t\tif deletedNamespaces.Has(metadata.GetNamespace()) {\n\t\t\tcontinue\n\t\t}\n\t\t// don't retry deleting the same namespace\n\t\tdeletedNamespaces.Insert(metadata.GetNamespace())\n\t\tnsCtx := genericapirequest.WithNamespace(ctx, metadata.GetNamespace())\n\t\tif _, err := crClient.DeleteCollection(nsCtx, rest.ValidateAllObjectFunc, nil, nil); err != nil {\n\t\t\tdeleteErrors = append(deleteErrors, err)\n\t\t\tcontinue\n\t\t}\n\t}\n\tif deleteError := utilerrors.NewAggregate(deleteErrors); deleteError != nil {\n\t\treturn apiextensionsv1.CustomResourceDefinitionCondition{\n\t\t\tType: apiextensionsv1.Terminating,\n\t\t\tStatus: apiextensionsv1.ConditionTrue,\n\t\t\tReason: \"InstanceDeletionFailed\",\n\t\t\tMessage: fmt.Sprintf(\"could not issue all deletes: %v\", deleteError),\n\t\t}, deleteError\n\t}\n\n\t// now we need to wait until all the resources are deleted. Start with a simple poll before we do anything fancy.\n\t// TODO not all servers are synchronized on caches. It is possible for a stale one to still be creating things.\n\t// Once we have a mechanism for servers to indicate their states, we should check that for concurrence.\n\terr = wait.PollImmediate(5*time.Second, 1*time.Minute, func() (bool, error) {\n\t\tlistObj, err := crClient.List(ctx, nil)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif len(listObj.(*unstructured.UnstructuredList).Items) == 0 {\n\t\t\treturn true, nil\n\t\t}\n\t\tklog.V(2).Infof(\"%s.%s waiting for %d items to be removed\", crd.Status.AcceptedNames.Plural, crd.Spec.Group, len(listObj.(*unstructured.UnstructuredList).Items))\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\treturn apiextensionsv1.CustomResourceDefinitionCondition{\n\t\t\tType: apiextensionsv1.Terminating,\n\t\t\tStatus: apiextensionsv1.ConditionTrue,\n\t\t\tReason: \"InstanceDeletionCheck\",\n\t\t\tMessage: fmt.Sprintf(\"could not confirm zero CustomResources remaining: %v\", err),\n\t\t}, err\n\t}\n\treturn apiextensionsv1.CustomResourceDefinitionCondition{\n\t\tType: apiextensionsv1.Terminating,\n\t\tStatus: apiextensionsv1.ConditionFalse,\n\t\tReason: \"InstanceDeletionCompleted\",\n\t\tMessage: \"removed all instances\",\n\t}, nil\n}","line":{"from":178,"to":260}} {"id":100014337,"name":"Run","signature":"func (c *CRDFinalizer) Run(workers int, stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/finalizer/crd_finalizer.go","code":"func (c *CRDFinalizer) Run(workers int, stopCh \u003c-chan struct{}) {\n\tdefer utilruntime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\n\tklog.Info(\"Starting CRDFinalizer\")\n\tdefer klog.Info(\"Shutting down CRDFinalizer\")\n\n\tif !cache.WaitForCacheSync(stopCh, c.crdSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.Until(c.runWorker, time.Second, stopCh)\n\t}\n\n\t\u003c-stopCh\n}","line":{"from":262,"to":278}} {"id":100014338,"name":"runWorker","signature":"func (c *CRDFinalizer) runWorker()","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/finalizer/crd_finalizer.go","code":"func (c *CRDFinalizer) runWorker() {\n\tfor c.processNextWorkItem() {\n\t}\n}","line":{"from":280,"to":283}} {"id":100014339,"name":"processNextWorkItem","signature":"func (c *CRDFinalizer) processNextWorkItem() bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/finalizer/crd_finalizer.go","code":"// processNextWorkItem deals with one key off the queue. It returns false when it's time to quit.\nfunc (c *CRDFinalizer) processNextWorkItem() bool {\n\tkey, quit := c.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.queue.Done(key)\n\n\terr := c.syncFn(key.(string))\n\tif err == nil {\n\t\tc.queue.Forget(key)\n\t\treturn true\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"%v failed with: %v\", key, err))\n\tc.queue.AddRateLimited(key)\n\n\treturn true\n}","line":{"from":285,"to":303}} {"id":100014340,"name":"enqueue","signature":"func (c *CRDFinalizer) enqueue(obj *apiextensionsv1.CustomResourceDefinition)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/finalizer/crd_finalizer.go","code":"func (c *CRDFinalizer) enqueue(obj *apiextensionsv1.CustomResourceDefinition) {\n\tkey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get key for object %#v: %v\", obj, err))\n\t\treturn\n\t}\n\n\tc.queue.Add(key)\n}","line":{"from":305,"to":313}} {"id":100014341,"name":"addCustomResourceDefinition","signature":"func (c *CRDFinalizer) addCustomResourceDefinition(obj interface{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/finalizer/crd_finalizer.go","code":"func (c *CRDFinalizer) addCustomResourceDefinition(obj interface{}) {\n\tcastObj := obj.(*apiextensionsv1.CustomResourceDefinition)\n\t// only queue deleted things\n\tif !castObj.DeletionTimestamp.IsZero() \u0026\u0026 apiextensionshelpers.CRDHasFinalizer(castObj, apiextensionsv1.CustomResourceCleanupFinalizer) {\n\t\tc.enqueue(castObj)\n\t}\n}","line":{"from":315,"to":321}} {"id":100014342,"name":"updateCustomResourceDefinition","signature":"func (c *CRDFinalizer) updateCustomResourceDefinition(oldObj, newObj interface{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/finalizer/crd_finalizer.go","code":"func (c *CRDFinalizer) updateCustomResourceDefinition(oldObj, newObj interface{}) {\n\toldCRD := oldObj.(*apiextensionsv1.CustomResourceDefinition)\n\tnewCRD := newObj.(*apiextensionsv1.CustomResourceDefinition)\n\t// only queue deleted things that haven't been finalized by us\n\tif newCRD.DeletionTimestamp.IsZero() || !apiextensionshelpers.CRDHasFinalizer(newCRD, apiextensionsv1.CustomResourceCleanupFinalizer) {\n\t\treturn\n\t}\n\n\t// always requeue resyncs just in case\n\tif oldCRD.ResourceVersion == newCRD.ResourceVersion {\n\t\tc.enqueue(newCRD)\n\t\treturn\n\t}\n\n\t// If the only difference is in the terminating condition, then there's no reason to requeue here. This controller\n\t// is likely to be the originator, so requeuing would hot-loop us. Failures are requeued by the workqueue directly.\n\t// This is a low traffic and scale resource, so the copy is terrible. It's not good, so better ideas\n\t// are welcome.\n\toldCopy := oldCRD.DeepCopy()\n\tnewCopy := newCRD.DeepCopy()\n\toldCopy.ResourceVersion = \"\"\n\tnewCopy.ResourceVersion = \"\"\n\tapiextensionshelpers.RemoveCRDCondition(oldCopy, apiextensionsv1.Terminating)\n\tapiextensionshelpers.RemoveCRDCondition(newCopy, apiextensionsv1.Terminating)\n\n\tif !reflect.DeepEqual(oldCopy, newCopy) {\n\t\tc.enqueue(newCRD)\n\t}\n}","line":{"from":323,"to":351}} {"id":100014343,"name":"NewConditionController","signature":"func NewConditionController(","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/nonstructuralschema/nonstructuralschema_controller.go","code":"// NewConditionController constructs a non-structural schema condition controller.\nfunc NewConditionController(\n\tcrdInformer informers.CustomResourceDefinitionInformer,\n\tcrdClient client.CustomResourceDefinitionsGetter,\n) *ConditionController {\n\tc := \u0026ConditionController{\n\t\tcrdClient: crdClient,\n\t\tcrdLister: crdInformer.Lister(),\n\t\tcrdSynced: crdInformer.Informer().HasSynced,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"non_structural_schema_condition_controller\"),\n\t\tlastSeenGeneration: map[string]int64{},\n\t}\n\n\tcrdInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: c.addCustomResourceDefinition,\n\t\tUpdateFunc: c.updateCustomResourceDefinition,\n\t\tDeleteFunc: c.deleteCustomResourceDefinition,\n\t})\n\n\tc.syncFn = c.sync\n\n\treturn c\n}","line":{"from":61,"to":83}} {"id":100014344,"name":"calculateCondition","signature":"func calculateCondition(in *apiextensionsv1.CustomResourceDefinition) *apiextensionsv1.CustomResourceDefinitionCondition","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/nonstructuralschema/nonstructuralschema_controller.go","code":"func calculateCondition(in *apiextensionsv1.CustomResourceDefinition) *apiextensionsv1.CustomResourceDefinitionCondition {\n\tcond := \u0026apiextensionsv1.CustomResourceDefinitionCondition{\n\t\tType: apiextensionsv1.NonStructuralSchema,\n\t\tStatus: apiextensionsv1.ConditionUnknown,\n\t}\n\n\tallErrs := field.ErrorList{}\n\n\tif in.Spec.PreserveUnknownFields {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"spec\", \"preserveUnknownFields\"),\n\t\t\tin.Spec.PreserveUnknownFields,\n\t\t\tfmt.Sprint(\"must be false\")))\n\t}\n\n\tfor i, v := range in.Spec.Versions {\n\t\tif v.Schema == nil || v.Schema.OpenAPIV3Schema == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tinternalSchema := \u0026apiextensionsinternal.CustomResourceValidation{}\n\t\tif err := apiextensionsv1.Convert_v1_CustomResourceValidation_To_apiextensions_CustomResourceValidation(v.Schema, internalSchema, nil); err != nil {\n\t\t\tklog.Errorf(\"failed to convert CRD validation to internal version: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\ts, err := schema.NewStructural(internalSchema.OpenAPIV3Schema)\n\t\tif err != nil {\n\t\t\tcond.Reason = \"StructuralError\"\n\t\t\tcond.Message = fmt.Sprintf(\"failed to check validation schema for version %s: %v\", v.Name, err)\n\t\t\treturn cond\n\t\t}\n\n\t\tpth := field.NewPath(\"spec\", \"versions\").Index(i).Child(\"schema\", \"openAPIV3Schema\")\n\n\t\tallErrs = append(allErrs, schema.ValidateStructural(pth, s)...)\n\t}\n\n\tif len(allErrs) == 0 {\n\t\treturn nil\n\t}\n\n\tcond.Status = apiextensionsv1.ConditionTrue\n\tcond.Reason = \"Violations\"\n\tcond.Message = allErrs.ToAggregate().Error()\n\n\treturn cond\n}","line":{"from":85,"to":130}} {"id":100014345,"name":"sync","signature":"func (c *ConditionController) sync(key string) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/nonstructuralschema/nonstructuralschema_controller.go","code":"func (c *ConditionController) sync(key string) error {\n\tinCustomResourceDefinition, err := c.crdLister.Get(key)\n\tif apierrors.IsNotFound(err) {\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// avoid repeated calculation for the same generation\n\tc.lastSeenGenerationLock.Lock()\n\tlastSeen, seenBefore := c.lastSeenGeneration[inCustomResourceDefinition.Name]\n\tc.lastSeenGenerationLock.Unlock()\n\tif seenBefore \u0026\u0026 inCustomResourceDefinition.Generation \u003c= lastSeen {\n\t\treturn nil\n\t}\n\n\t// check old condition\n\tcond := calculateCondition(inCustomResourceDefinition)\n\told := apiextensionshelpers.FindCRDCondition(inCustomResourceDefinition, apiextensionsv1.NonStructuralSchema)\n\n\tif cond == nil \u0026\u0026 old == nil {\n\t\treturn nil\n\t}\n\tif cond != nil \u0026\u0026 old != nil \u0026\u0026 old.Status == cond.Status \u0026\u0026 old.Reason == cond.Reason \u0026\u0026 old.Message == cond.Message {\n\t\treturn nil\n\t}\n\n\t// update condition\n\tcrd := inCustomResourceDefinition.DeepCopy()\n\tif cond == nil {\n\t\tapiextensionshelpers.RemoveCRDCondition(crd, apiextensionsv1.NonStructuralSchema)\n\t} else {\n\t\tcond.LastTransitionTime = metav1.NewTime(time.Now())\n\t\tapiextensionshelpers.SetCRDCondition(crd, *cond)\n\t}\n\n\t_, err = c.crdClient.CustomResourceDefinitions().UpdateStatus(context.TODO(), crd, metav1.UpdateOptions{})\n\tif apierrors.IsNotFound(err) || apierrors.IsConflict(err) {\n\t\t// deleted or changed in the meantime, we'll get called again\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// store generation in order to avoid repeated updates for the same generation (and potential\n\t// fights of API server in HA environments).\n\tc.lastSeenGenerationLock.Lock()\n\tdefer c.lastSeenGenerationLock.Unlock()\n\tc.lastSeenGeneration[crd.Name] = crd.Generation\n\n\treturn nil\n}","line":{"from":132,"to":185}} {"id":100014346,"name":"Run","signature":"func (c *ConditionController) Run(workers int, stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/nonstructuralschema/nonstructuralschema_controller.go","code":"// Run starts the controller.\nfunc (c *ConditionController) Run(workers int, stopCh \u003c-chan struct{}) {\n\tdefer utilruntime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\n\tklog.Infof(\"Starting NonStructuralSchemaConditionController\")\n\tdefer klog.Infof(\"Shutting down NonStructuralSchemaConditionController\")\n\n\tif !cache.WaitForCacheSync(stopCh, c.crdSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.Until(c.runWorker, time.Second, stopCh)\n\t}\n\n\t\u003c-stopCh\n}","line":{"from":187,"to":204}} {"id":100014347,"name":"runWorker","signature":"func (c *ConditionController) runWorker()","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/nonstructuralschema/nonstructuralschema_controller.go","code":"func (c *ConditionController) runWorker() {\n\tfor c.processNextWorkItem() {\n\t}\n}","line":{"from":206,"to":209}} {"id":100014348,"name":"processNextWorkItem","signature":"func (c *ConditionController) processNextWorkItem() bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/nonstructuralschema/nonstructuralschema_controller.go","code":"// processNextWorkItem deals with one key off the queue. It returns false when it's time to quit.\nfunc (c *ConditionController) processNextWorkItem() bool {\n\tkey, quit := c.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.queue.Done(key)\n\n\terr := c.syncFn(key.(string))\n\tif err == nil {\n\t\tc.queue.Forget(key)\n\t\treturn true\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"%v failed with: %v\", key, err))\n\tc.queue.AddRateLimited(key)\n\n\treturn true\n}","line":{"from":211,"to":229}} {"id":100014349,"name":"enqueue","signature":"func (c *ConditionController) enqueue(obj *apiextensionsv1.CustomResourceDefinition)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/nonstructuralschema/nonstructuralschema_controller.go","code":"func (c *ConditionController) enqueue(obj *apiextensionsv1.CustomResourceDefinition) {\n\tkey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get key for object %#v: %v\", obj, err))\n\t\treturn\n\t}\n\n\tc.queue.Add(key)\n}","line":{"from":231,"to":239}} {"id":100014350,"name":"addCustomResourceDefinition","signature":"func (c *ConditionController) addCustomResourceDefinition(obj interface{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/nonstructuralschema/nonstructuralschema_controller.go","code":"func (c *ConditionController) addCustomResourceDefinition(obj interface{}) {\n\tcastObj := obj.(*apiextensionsv1.CustomResourceDefinition)\n\tklog.V(4).Infof(\"Adding %s\", castObj.Name)\n\tc.enqueue(castObj)\n}","line":{"from":241,"to":245}} {"id":100014351,"name":"updateCustomResourceDefinition","signature":"func (c *ConditionController) updateCustomResourceDefinition(obj, _ interface{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/nonstructuralschema/nonstructuralschema_controller.go","code":"func (c *ConditionController) updateCustomResourceDefinition(obj, _ interface{}) {\n\tcastObj := obj.(*apiextensionsv1.CustomResourceDefinition)\n\tklog.V(4).Infof(\"Updating %s\", castObj.Name)\n\tc.enqueue(castObj)\n}","line":{"from":247,"to":251}} {"id":100014352,"name":"deleteCustomResourceDefinition","signature":"func (c *ConditionController) deleteCustomResourceDefinition(obj interface{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/nonstructuralschema/nonstructuralschema_controller.go","code":"func (c *ConditionController) deleteCustomResourceDefinition(obj interface{}) {\n\tcastObj, ok := obj.(*apiextensionsv1.CustomResourceDefinition)\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"Couldn't get object from tombstone %#v\", obj)\n\t\t\treturn\n\t\t}\n\t\tcastObj, ok = tombstone.Obj.(*apiextensionsv1.CustomResourceDefinition)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"Tombstone contained object that is not expected %#v\", obj)\n\t\t\treturn\n\t\t}\n\t}\n\n\tc.lastSeenGenerationLock.Lock()\n\tdefer c.lastSeenGenerationLock.Unlock()\n\tdelete(c.lastSeenGeneration, castObj.Name)\n}","line":{"from":253,"to":271}} {"id":100014353,"name":"refForOpenAPIVersion","signature":"func refForOpenAPIVersion(schemaRef string, v2 bool) string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/builder/builder.go","code":"// The path for definitions in OpenAPI v2 and v3 are different. Translate the path if necessary\n// The provided schemaRef uses a v2 prefix and is converted to v3 if the v2 bool is false\nfunc refForOpenAPIVersion(schemaRef string, v2 bool) string {\n\tif v2 {\n\t\treturn schemaRef\n\t}\n\treturn strings.Replace(schemaRef, definitionPrefix, v3DefinitionPrefix, 1)\n}","line":{"from":72,"to":79}} {"id":100014354,"name":"generateBuilder","signature":"func generateBuilder(crd *apiextensionsv1.CustomResourceDefinition, version string, opts Options) (*builder, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/builder/builder.go","code":"func generateBuilder(crd *apiextensionsv1.CustomResourceDefinition, version string, opts Options) (*builder, error) {\n\tvar schema *structuralschema.Structural\n\ts, err := apiextensionshelpers.GetSchemaForVersion(crd, version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif s != nil \u0026\u0026 s.OpenAPIV3Schema != nil {\n\t\tinternalCRDSchema := \u0026apiextensionsinternal.CustomResourceValidation{}\n\t\tif err := apiextensionsv1.Convert_v1_CustomResourceValidation_To_apiextensions_CustomResourceValidation(s, internalCRDSchema, nil); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed converting CRD validation to internal version: %v\", err)\n\t\t}\n\t\tif !validation.SchemaHasInvalidTypes(internalCRDSchema.OpenAPIV3Schema) {\n\t\t\tif ss, err := structuralschema.NewStructural(internalCRDSchema.OpenAPIV3Schema); err == nil {\n\t\t\t\t// skip non-structural schemas unless explicitly asked to produce swagger from them\n\t\t\t\tif opts.AllowNonStructural || len(structuralschema.ValidateStructural(nil, ss)) == 0 {\n\t\t\t\t\tschema = ss\n\n\t\t\t\t\t// This adds ValueValidation fields (anyOf, allOf) which may be stripped below if opts.StripValueValidation is true\n\t\t\t\t\tschema = schema.Unfold()\n\n\t\t\t\t\tif opts.StripValueValidation {\n\t\t\t\t\t\tschema = schema.StripValueValidations()\n\t\t\t\t\t}\n\t\t\t\t\tif opts.StripNullable {\n\t\t\t\t\t\tschema = schema.StripNullable()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// TODO(roycaihw): remove the WebService templating below. The following logic\n\t// comes from function registerResourceHandlers() in k8s.io/apiserver.\n\t// Alternatives are either (ideally) refactoring registerResourceHandlers() to\n\t// reuse the code, or faking an APIInstaller for CR to feed to registerResourceHandlers().\n\tb := newBuilder(crd, version, schema, opts)\n\n\t// Sample response types for building web service\n\tsample := \u0026CRDCanonicalTypeNamer{\n\t\tgroup: b.group,\n\t\tversion: b.version,\n\t\tkind: b.kind,\n\t}\n\tsampleList := \u0026CRDCanonicalTypeNamer{\n\t\tgroup: b.group,\n\t\tversion: b.version,\n\t\tkind: b.listKind,\n\t}\n\tstatus := \u0026metav1.Status{}\n\tpatch := \u0026metav1.Patch{}\n\tscale := \u0026v1.Scale{}\n\n\troutes := make([]*restful.RouteBuilder, 0)\n\troot := fmt.Sprintf(\"/apis/%s/%s/%s\", b.group, b.version, b.plural)\n\n\tif b.namespaced {\n\t\troutes = append(routes, b.buildRoute(root, \"\", \"GET\", \"list\", \"list\", sampleList).Operation(\"list\"+b.kind+\"ForAllNamespaces\"))\n\t\troot = fmt.Sprintf(\"/apis/%s/%s/namespaces/{namespace}/%s\", b.group, b.version, b.plural)\n\t}\n\troutes = append(routes, b.buildRoute(root, \"\", \"GET\", \"list\", \"list\", sampleList))\n\troutes = append(routes, b.buildRoute(root, \"\", \"POST\", \"post\", \"create\", sample).Reads(sample))\n\troutes = append(routes, b.buildRoute(root, \"\", \"DELETE\", \"deletecollection\", \"deletecollection\", status))\n\n\troutes = append(routes, b.buildRoute(root, \"/{name}\", \"GET\", \"get\", \"read\", sample))\n\troutes = append(routes, b.buildRoute(root, \"/{name}\", \"PUT\", \"put\", \"replace\", sample).Reads(sample))\n\troutes = append(routes, b.buildRoute(root, \"/{name}\", \"DELETE\", \"delete\", \"delete\", status))\n\troutes = append(routes, b.buildRoute(root, \"/{name}\", \"PATCH\", \"patch\", \"patch\", sample).Reads(patch))\n\n\tsubresources, err := apiextensionshelpers.GetSubresourcesForVersion(crd, version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif subresources != nil \u0026\u0026 subresources.Status != nil {\n\t\troutes = append(routes, b.buildRoute(root, \"/{name}/status\", \"GET\", \"get\", \"read\", sample))\n\t\troutes = append(routes, b.buildRoute(root, \"/{name}/status\", \"PUT\", \"put\", \"replace\", sample).Reads(sample))\n\t\troutes = append(routes, b.buildRoute(root, \"/{name}/status\", \"PATCH\", \"patch\", \"patch\", sample).Reads(patch))\n\t}\n\tif subresources != nil \u0026\u0026 subresources.Scale != nil {\n\t\troutes = append(routes, b.buildRoute(root, \"/{name}/scale\", \"GET\", \"get\", \"read\", scale))\n\t\troutes = append(routes, b.buildRoute(root, \"/{name}/scale\", \"PUT\", \"put\", \"replace\", scale).Reads(scale))\n\t\troutes = append(routes, b.buildRoute(root, \"/{name}/scale\", \"PATCH\", \"patch\", \"patch\", scale).Reads(patch))\n\t}\n\n\tfor _, route := range routes {\n\t\tb.ws.Route(route)\n\t}\n\treturn b, nil\n}","line":{"from":107,"to":195}} {"id":100014355,"name":"BuildOpenAPIV3","signature":"func BuildOpenAPIV3(crd *apiextensionsv1.CustomResourceDefinition, version string, opts Options) (*spec3.OpenAPI, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/builder/builder.go","code":"func BuildOpenAPIV3(crd *apiextensionsv1.CustomResourceDefinition, version string, opts Options) (*spec3.OpenAPI, error) {\n\tb, err := generateBuilder(crd, version, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn builder3.BuildOpenAPISpecFromRoutes(restfuladapter.AdaptWebServices([]*restful.WebService{b.ws}), b.getOpenAPIConfig(false))\n}","line":{"from":197,"to":204}} {"id":100014356,"name":"BuildOpenAPIV2","signature":"func BuildOpenAPIV2(crd *apiextensionsv1.CustomResourceDefinition, version string, opts Options) (*spec.Swagger, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/builder/builder.go","code":"// BuildOpenAPIV2 builds OpenAPI v2 for the given crd in the given version\nfunc BuildOpenAPIV2(crd *apiextensionsv1.CustomResourceDefinition, version string, opts Options) (*spec.Swagger, error) {\n\tb, err := generateBuilder(crd, version, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn openapibuilder.BuildOpenAPISpecFromRoutes(restfuladapter.AdaptWebServices([]*restful.WebService{b.ws}), b.getOpenAPIConfig(true))\n}","line":{"from":206,"to":214}} {"id":100014357,"name":"OpenAPICanonicalTypeName","signature":"func (c *CRDCanonicalTypeNamer) OpenAPICanonicalTypeName() string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/builder/builder.go","code":"// OpenAPICanonicalTypeName returns canonical type name for given CRD\nfunc (c *CRDCanonicalTypeNamer) OpenAPICanonicalTypeName() string {\n\treturn fmt.Sprintf(\"%s/%s.%s\", c.group, c.version, c.kind)\n}","line":{"from":227,"to":230}} {"id":100014358,"name":"subresource","signature":"func subresource(path string) string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/builder/builder.go","code":"// subresource is a handy method to get subresource name. Valid inputs are:\n//\n//\tinput output\n//\t\"\" \"\"\n//\t\"/\" \"\"\n//\t\"/{name}\" \"\"\n//\t\"/{name}/scale\" \"scale\"\n//\t\"/{name}/scale/foo\" invalid input\nfunc subresource(path string) string {\n\tparts := strings.Split(path, \"/\")\n\tif len(parts) \u003c= 2 {\n\t\treturn \"\"\n\t}\n\tif len(parts) == 3 {\n\t\treturn parts[2]\n\t}\n\t// panic to alert on programming error\n\tpanic(\"failed to parse subresource; invalid path\")\n}","line":{"from":249,"to":267}} {"id":100014359,"name":"descriptionFor","signature":"func (b *builder) descriptionFor(path, operationVerb string) string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/builder/builder.go","code":"func (b *builder) descriptionFor(path, operationVerb string) string {\n\tvar article string\n\tswitch operationVerb {\n\tcase \"list\":\n\t\tarticle = \" objects of kind \"\n\tcase \"read\", \"replace\":\n\t\tarticle = \" the specified \"\n\tcase \"patch\":\n\t\tarticle = \" the specified \"\n\tcase \"create\", \"delete\":\n\t\tarticle = endpoints.GetArticleForNoun(b.kind, \" \")\n\tdefault:\n\t\tarticle = \"\"\n\t}\n\n\tvar description string\n\tsub := subresource(path)\n\tif len(sub) \u003e 0 {\n\t\tsub = \" \" + sub + \" of\"\n\t}\n\tswitch operationVerb {\n\tcase \"patch\":\n\t\tdescription = \"partially update\" + sub + article + b.kind\n\tcase \"deletecollection\":\n\t\t// to match the text for built-in APIs\n\t\tif len(sub) \u003e 0 {\n\t\t\tsub = sub + \" a\"\n\t\t}\n\t\tdescription = \"delete collection of\" + sub + \" \" + b.kind\n\tdefault:\n\t\tdescription = operationVerb + sub + article + b.kind\n\t}\n\n\treturn description\n}","line":{"from":269,"to":303}} {"id":100014360,"name":"buildRoute","signature":"func (b *builder) buildRoute(root, path, httpMethod, actionVerb, operationVerb string, sample interface{}) *restful.RouteBuilder","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/builder/builder.go","code":"// buildRoute returns a RouteBuilder for WebService to consume and builds path in swagger\n//\n//\taction can be one of: GET, PUT, PATCH, POST, DELETE;\n//\tverb can be one of: list, read, replace, patch, create, delete, deletecollection;\n//\tsample is the sample Go type for response type.\nfunc (b *builder) buildRoute(root, path, httpMethod, actionVerb, operationVerb string, sample interface{}) *restful.RouteBuilder {\n\tvar namespaced string\n\tif b.namespaced {\n\t\tnamespaced = \"Namespaced\"\n\t}\n\troute := b.ws.Method(httpMethod).\n\t\tPath(root+path).\n\t\tTo(func(req *restful.Request, res *restful.Response) {}).\n\t\tDoc(b.descriptionFor(path, operationVerb)).\n\t\tParam(b.ws.QueryParameter(\"pretty\", \"If 'true', then the output is pretty printed.\")).\n\t\tOperation(operationVerb+namespaced+b.kind+strings.Title(subresource(path))).\n\t\tMetadata(endpoints.ROUTE_META_GVK, metav1.GroupVersionKind{\n\t\t\tGroup: b.group,\n\t\t\tVersion: b.version,\n\t\t\tKind: b.kind,\n\t\t}).\n\t\tMetadata(endpoints.ROUTE_META_ACTION, actionVerb).\n\t\tProduces(\"application/json\", \"application/yaml\").\n\t\tReturns(http.StatusOK, \"OK\", sample).\n\t\tWrites(sample)\n\tif strings.Contains(root, namespaceToken) || strings.Contains(path, namespaceToken) {\n\t\troute.Param(b.ws.PathParameter(\"namespace\", \"object name and auth scope, such as for teams and projects\").DataType(\"string\"))\n\t}\n\tif strings.Contains(root, nameToken) || strings.Contains(path, nameToken) {\n\t\troute.Param(b.ws.PathParameter(\"name\", \"name of the \"+b.kind).DataType(\"string\"))\n\t}\n\n\t// Build consume media types\n\tif httpMethod == \"PATCH\" {\n\t\tsupportedTypes := []string{\n\t\t\tstring(types.JSONPatchType),\n\t\t\tstring(types.MergePatchType),\n\t\t\tstring(types.ApplyPatchType),\n\t\t}\n\t\troute.Consumes(supportedTypes...)\n\t} else {\n\t\troute.Consumes(runtime.ContentTypeJSON, runtime.ContentTypeYAML)\n\t}\n\n\t// Build option parameters\n\tswitch actionVerb {\n\tcase \"get\":\n\t\tendpoints.AddObjectParams(b.ws, route, \u0026metav1.GetOptions{})\n\tcase \"list\", \"deletecollection\":\n\t\tendpoints.AddObjectParams(b.ws, route, \u0026metav1.ListOptions{})\n\tcase \"put\":\n\t\tendpoints.AddObjectParams(b.ws, route, \u0026metav1.UpdateOptions{})\n\tcase \"patch\":\n\t\tendpoints.AddObjectParams(b.ws, route, \u0026metav1.PatchOptions{})\n\tcase \"post\":\n\t\tendpoints.AddObjectParams(b.ws, route, \u0026metav1.CreateOptions{})\n\tcase \"delete\":\n\t\tendpoints.AddObjectParams(b.ws, route, \u0026metav1.DeleteOptions{})\n\t\troute.Reads(\u0026metav1.DeleteOptions{}).ParameterNamed(\"body\").Required(false)\n\t}\n\n\t// Build responses\n\tswitch actionVerb {\n\tcase \"post\":\n\t\troute.Returns(http.StatusAccepted, \"Accepted\", sample)\n\t\troute.Returns(http.StatusCreated, \"Created\", sample)\n\tcase \"delete\":\n\t\troute.Returns(http.StatusAccepted, \"Accepted\", sample)\n\tcase \"put\":\n\t\troute.Returns(http.StatusCreated, \"Created\", sample)\n\t}\n\n\treturn route\n}","line":{"from":305,"to":378}} {"id":100014361,"name":"buildKubeNative","signature":"func (b *builder) buildKubeNative(schema *structuralschema.Structural, opts Options, crdPreserveUnknownFields bool) (ret *spec.Schema)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/builder/builder.go","code":"// buildKubeNative builds input schema with Kubernetes' native object meta, type meta and\n// extensions\nfunc (b *builder) buildKubeNative(schema *structuralschema.Structural, opts Options, crdPreserveUnknownFields bool) (ret *spec.Schema) {\n\t// only add properties if we have a schema. Otherwise, kubectl would (wrongly) assume additionalProperties=false\n\t// and forbid anything outside of apiVersion, kind and metadata. We have to fix kubectl to stop doing this, e.g. by\n\t// adding additionalProperties=true support to explicitly allow additional fields.\n\t// TODO: fix kubectl to understand additionalProperties=true\n\tif schema == nil || ((opts.V2 \u0026\u0026 !opts.SkipFilterSchemaForKubectlOpenAPIV2Validation) \u0026\u0026 (schema.XPreserveUnknownFields || crdPreserveUnknownFields)) {\n\t\tret = \u0026spec.Schema{\n\t\t\tSchemaProps: spec.SchemaProps{Type: []string{\"object\"}},\n\t\t}\n\t\t// no, we cannot add more properties here, not even TypeMeta/ObjectMeta because kubectl will complain about\n\t\t// unknown fields for anything else.\n\t} else {\n\t\tif opts.V2 \u0026\u0026 !opts.SkipFilterSchemaForKubectlOpenAPIV2Validation {\n\t\t\tschema = openapiv2.ToStructuralOpenAPIV2(schema)\n\t\t}\n\n\t\tret = schema.ToKubeOpenAPI()\n\t\tret.SetProperty(\"metadata\", *spec.RefSchema(refForOpenAPIVersion(objectMetaSchemaRef, opts.V2)).WithDescription(swaggerPartialObjectMetadataDescriptions[\"metadata\"]))\n\t\taddTypeMetaProperties(ret, opts.V2)\n\t\taddEmbeddedProperties(ret, opts)\n\t}\n\tret.AddExtension(endpoints.ROUTE_META_GVK, []interface{}{\n\t\tmap[string]interface{}{\n\t\t\t\"group\": b.group,\n\t\t\t\"version\": b.version,\n\t\t\t\"kind\": b.kind,\n\t\t},\n\t})\n\n\treturn ret\n}","line":{"from":380,"to":412}} {"id":100014362,"name":"addEmbeddedProperties","signature":"func addEmbeddedProperties(s *spec.Schema, opts Options)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/builder/builder.go","code":"func addEmbeddedProperties(s *spec.Schema, opts Options) {\n\tif s == nil {\n\t\treturn\n\t}\n\n\tfor k := range s.Properties {\n\t\tv := s.Properties[k]\n\t\taddEmbeddedProperties(\u0026v, opts)\n\t\ts.Properties[k] = v\n\t}\n\tif s.Items != nil {\n\t\taddEmbeddedProperties(s.Items.Schema, opts)\n\t}\n\tif s.AdditionalProperties != nil {\n\t\taddEmbeddedProperties(s.AdditionalProperties.Schema, opts)\n\t}\n\n\tif isTrue, ok := s.VendorExtensible.Extensions.GetBool(\"x-kubernetes-preserve-unknown-fields\"); ok \u0026\u0026 isTrue \u0026\u0026 opts.V2 \u0026\u0026 !opts.SkipFilterSchemaForKubectlOpenAPIV2Validation {\n\t\t// don't add metadata properties if we're publishing to openapi v2 and are allowing unknown fields.\n\t\t// adding these metadata properties makes kubectl refuse to validate unknown fields.\n\t\treturn\n\t}\n\tif isTrue, ok := s.VendorExtensible.Extensions.GetBool(\"x-kubernetes-embedded-resource\"); ok \u0026\u0026 isTrue {\n\t\ts.SetProperty(\"apiVersion\", withDescription(getDefinition(typeMetaType, opts.V2).SchemaProps.Properties[\"apiVersion\"],\n\t\t\t\"apiVersion defines the versioned schema of this representation of an object. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources\",\n\t\t))\n\t\ts.SetProperty(\"kind\", withDescription(getDefinition(typeMetaType, opts.V2).SchemaProps.Properties[\"kind\"],\n\t\t\t\"kind is a string value representing the type of this object. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds\",\n\t\t))\n\t\ts.SetProperty(\"metadata\", *spec.RefSchema(refForOpenAPIVersion(objectMetaSchemaRef, opts.V2)).WithDescription(swaggerPartialObjectMetadataDescriptions[\"metadata\"]))\n\n\t\treq := sets.NewString(s.Required...)\n\t\tif !req.Has(\"kind\") {\n\t\t\ts.Required = append(s.Required, \"kind\")\n\t\t}\n\t\tif !req.Has(\"apiVersion\") {\n\t\t\ts.Required = append(s.Required, \"apiVersion\")\n\t\t}\n\t}\n}","line":{"from":414,"to":453}} {"id":100014363,"name":"getDefinition","signature":"func getDefinition(name string, v2 bool) spec.Schema","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/builder/builder.go","code":"// getDefinition gets definition for given Kubernetes type. This function is extracted from\n// kube-openapi builder logic\nfunc getDefinition(name string, v2 bool) spec.Schema {\n\tbuildDefinitions.Do(generateBuildDefinitionsFunc)\n\n\tif v2 {\n\t\treturn definitions[name].Schema\n\t}\n\treturn definitionsV3[name].Schema\n}","line":{"from":455,"to":464}} {"id":100014364,"name":"withDescription","signature":"func withDescription(s spec.Schema, desc string) spec.Schema","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/builder/builder.go","code":"func withDescription(s spec.Schema, desc string) spec.Schema {\n\treturn *s.WithDescription(desc)\n}","line":{"from":466,"to":468}} {"id":100014365,"name":"generateBuildDefinitionsFunc","signature":"func generateBuildDefinitionsFunc()","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/builder/builder.go","code":"func generateBuildDefinitionsFunc() {\n\tnamer = openapi.NewDefinitionNamer(runtime.NewScheme())\n\tdefinitionsV3 = utilopenapi.GetOpenAPIDefinitionsWithoutDisabledFeatures(generatedopenapi.GetOpenAPIDefinitions)(func(name string) spec.Ref {\n\t\tdefName, _ := namer.GetDefinitionName(name)\n\t\tprefix := v3DefinitionPrefix\n\t\treturn spec.MustCreateRef(prefix + common.EscapeJsonPointer(defName))\n\t})\n\n\tdefinitions = utilopenapi.GetOpenAPIDefinitionsWithoutDisabledFeatures(generatedopenapi.GetOpenAPIDefinitions)(func(name string) spec.Ref {\n\t\tdefName, _ := namer.GetDefinitionName(name)\n\t\tprefix := definitionPrefix\n\t\treturn spec.MustCreateRef(prefix + common.EscapeJsonPointer(defName))\n\t})\n}","line":{"from":470,"to":483}} {"id":100014366,"name":"addTypeMetaProperties","signature":"func addTypeMetaProperties(s *spec.Schema, v2 bool)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/builder/builder.go","code":"// addTypeMetaProperties adds Kubernetes-specific type meta properties to input schema:\n//\n//\tapiVersion and kind\nfunc addTypeMetaProperties(s *spec.Schema, v2 bool) {\n\ts.SetProperty(\"apiVersion\", getDefinition(typeMetaType, v2).SchemaProps.Properties[\"apiVersion\"])\n\ts.SetProperty(\"kind\", getDefinition(typeMetaType, v2).SchemaProps.Properties[\"kind\"])\n}","line":{"from":485,"to":491}} {"id":100014367,"name":"buildListSchema","signature":"func (b *builder) buildListSchema(v2 bool) *spec.Schema","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/builder/builder.go","code":"// buildListSchema builds the list kind schema for the CRD\nfunc (b *builder) buildListSchema(v2 bool) *spec.Schema {\n\tname := definitionPrefix + util.ToRESTFriendlyName(fmt.Sprintf(\"%s/%s/%s\", b.group, b.version, b.kind))\n\tdoc := fmt.Sprintf(\"List of %s. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md\", b.plural)\n\ts := new(spec.Schema).\n\t\tTyped(\"object\", \"\").\n\t\tWithDescription(fmt.Sprintf(\"%s is a list of %s\", b.listKind, b.kind)).\n\t\tWithRequired(\"items\").\n\t\tSetProperty(\"items\", *spec.ArrayProperty(spec.RefSchema(refForOpenAPIVersion(name, v2))).WithDescription(doc)).\n\t\tSetProperty(\"metadata\", *spec.RefSchema(refForOpenAPIVersion(listMetaSchemaRef, v2)).WithDescription(swaggerPartialObjectMetadataListDescriptions[\"metadata\"]))\n\n\taddTypeMetaProperties(s, v2)\n\ts.AddExtension(endpoints.ROUTE_META_GVK, []map[string]string{\n\t\t{\n\t\t\t\"group\": b.group,\n\t\t\t\"version\": b.version,\n\t\t\t\"kind\": b.listKind,\n\t\t},\n\t})\n\treturn s\n}","line":{"from":493,"to":513}} {"id":100014368,"name":"getOpenAPIConfig","signature":"func (b *builder) getOpenAPIConfig(v2 bool) *common.Config","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/builder/builder.go","code":"// getOpenAPIConfig builds config which wires up generated definitions for kube-openapi to consume\nfunc (b *builder) getOpenAPIConfig(v2 bool) *common.Config {\n\treturn \u0026common.Config{\n\t\tProtocolList: []string{\"https\"},\n\t\tInfo: \u0026spec.Info{\n\t\t\tInfoProps: spec.InfoProps{\n\t\t\t\tTitle: \"Kubernetes CRD Swagger\",\n\t\t\t\tVersion: \"v0.1.0\",\n\t\t\t},\n\t\t},\n\t\tCommonResponses: map[int]spec.Response{\n\t\t\t401: {\n\t\t\t\tResponseProps: spec.ResponseProps{\n\t\t\t\t\tDescription: \"Unauthorized\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tGetOperationIDAndTags: openapi.GetOperationIDAndTags,\n\t\tGetDefinitionName: func(name string) (string, spec.Extensions) {\n\t\t\tbuildDefinitions.Do(generateBuildDefinitionsFunc)\n\t\t\treturn namer.GetDefinitionName(name)\n\t\t},\n\t\tGetDefinitions: func(ref common.ReferenceCallback) map[string]common.OpenAPIDefinition {\n\t\t\tdef := utilopenapi.GetOpenAPIDefinitionsWithoutDisabledFeatures(generatedopenapi.GetOpenAPIDefinitions)(ref)\n\t\t\tdef[fmt.Sprintf(\"%s/%s.%s\", b.group, b.version, b.kind)] = common.OpenAPIDefinition{\n\t\t\t\tSchema: *b.schema,\n\t\t\t\tDependencies: []string{objectMetaType},\n\t\t\t}\n\t\t\tdef[fmt.Sprintf(\"%s/%s.%s\", b.group, b.version, b.listKind)] = common.OpenAPIDefinition{\n\t\t\t\tSchema: *b.listSchema,\n\t\t\t}\n\t\t\treturn def\n\t\t},\n\t}\n}","line":{"from":515,"to":549}} {"id":100014369,"name":"newBuilder","signature":"func newBuilder(crd *apiextensionsv1.CustomResourceDefinition, version string, schema *structuralschema.Structural, opts Options) *builder","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/builder/builder.go","code":"func newBuilder(crd *apiextensionsv1.CustomResourceDefinition, version string, schema *structuralschema.Structural, opts Options) *builder {\n\tb := \u0026builder{\n\t\tschema: \u0026spec.Schema{\n\t\t\tSchemaProps: spec.SchemaProps{Type: []string{\"object\"}},\n\t\t},\n\t\tlistSchema: \u0026spec.Schema{},\n\t\tws: \u0026restful.WebService{},\n\n\t\tgroup: crd.Spec.Group,\n\t\tversion: version,\n\t\tkind: crd.Spec.Names.Kind,\n\t\tlistKind: crd.Spec.Names.ListKind,\n\t\tplural: crd.Spec.Names.Plural,\n\t}\n\tif crd.Spec.Scope == apiextensionsv1.NamespaceScoped {\n\t\tb.namespaced = true\n\t}\n\n\t// Pre-build schema with Kubernetes native properties\n\tb.schema = b.buildKubeNative(schema, opts, crd.Spec.PreserveUnknownFields)\n\tb.listSchema = b.buildListSchema(opts.V2)\n\n\treturn b\n}","line":{"from":551,"to":574}} {"id":100014370,"name":"MergeSpecs","signature":"func MergeSpecs(staticSpec *spec.Swagger, crdSpecs ...*spec.Swagger) (*spec.Swagger, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/builder/merge.go","code":"// MergeSpecs aggregates all OpenAPI specs, reusing the metadata of the first, static spec as the basis.\n// The static spec has the highest priority, and its paths and definitions won't get overlapped by\n// user-defined CRDs. None of the input is mutated, but input and output share data structures.\nfunc MergeSpecs(staticSpec *spec.Swagger, crdSpecs ...*spec.Swagger) (*spec.Swagger, error) {\n\t// create shallow copy of staticSpec, but replace paths and definitions because we modify them.\n\tspecToReturn := *staticSpec\n\tif staticSpec.Definitions != nil {\n\t\tspecToReturn.Definitions = spec.Definitions{}\n\t\tfor k, s := range staticSpec.Definitions {\n\t\t\tspecToReturn.Definitions[k] = s\n\t\t}\n\t}\n\tif staticSpec.Paths != nil {\n\t\tspecToReturn.Paths = \u0026spec.Paths{\n\t\t\tPaths: map[string]spec.PathItem{},\n\t\t}\n\t\tfor k, p := range staticSpec.Paths.Paths {\n\t\t\tspecToReturn.Paths.Paths[k] = p\n\t\t}\n\t}\n\n\tcrdSpec := \u0026spec.Swagger{}\n\tfor _, s := range crdSpecs {\n\t\t// merge specs without checking conflicts, since the naming controller prevents\n\t\t// conflicts between user-defined CRDs\n\t\tmergeSpec(crdSpec, s)\n\t}\n\n\t// The static spec has the highest priority. Resolve conflicts to prevent user-defined\n\t// CRDs potentially overlapping the built-in apiextensions API\n\tif err := aggregator.MergeSpecsIgnorePathConflict(\u0026specToReturn, crdSpec); err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026specToReturn, nil\n}","line":{"from":31,"to":65}} {"id":100014371,"name":"mergeSpec","signature":"func mergeSpec(dest, source *spec.Swagger)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/builder/merge.go","code":"// mergeSpec copies paths and definitions from source to dest, mutating dest, but not source.\n// We assume that conflicts do not matter.\nfunc mergeSpec(dest, source *spec.Swagger) {\n\tif source == nil || source.Paths == nil {\n\t\treturn\n\t}\n\tif dest.Paths == nil {\n\t\tdest.Paths = \u0026spec.Paths{}\n\t}\n\tfor k, v := range source.Definitions {\n\t\tif dest.Definitions == nil {\n\t\t\tdest.Definitions = spec.Definitions{}\n\t\t}\n\t\tdest.Definitions[k] = v\n\t}\n\tfor k, v := range source.Paths.Paths {\n\t\tif dest.Paths.Paths == nil {\n\t\t\tdest.Paths.Paths = map[string]spec.PathItem{}\n\t\t}\n\t\tdest.Paths.Paths[k] = v\n\t}\n}","line":{"from":67,"to":88}} {"id":100014372,"name":"MergeSpecsV3","signature":"func MergeSpecsV3(crdSpecs ...*spec3.OpenAPI) (*spec3.OpenAPI, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/builder/merge.go","code":"// MergeSpecsV3 merges OpenAPI v3 specs for CRDs\n// Conflicts belonging to the meta.v1 or autoscaling.v1 group versions are skipped as all CRDs reference those types\n// Other conflicts will result in an error\nfunc MergeSpecsV3(crdSpecs ...*spec3.OpenAPI) (*spec3.OpenAPI, error) {\n\tcrdSpec := \u0026spec3.OpenAPI{}\n\tif len(crdSpecs) \u003e 0 {\n\t\tcrdSpec.Version = crdSpecs[0].Version\n\t\tcrdSpec.Info = crdSpecs[0].Info\n\t}\n\tfor _, s := range crdSpecs {\n\t\terr := mergeSpecV3(crdSpec, s)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn crdSpec, nil\n}","line":{"from":90,"to":106}} {"id":100014373,"name":"mergeSpecV3","signature":"func mergeSpecV3(dest, source *spec3.OpenAPI) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/builder/merge.go","code":"// mergeSpecV3 copies paths and definitions from source to dest, mutating dest, but not source.\n// Conflicts belonging to the meta.v1 or autoscaling.v1 group versions are skipped as all CRDs reference those types\n// Other conflicts will result in an error\nfunc mergeSpecV3(dest, source *spec3.OpenAPI) error {\n\tif source == nil || source.Paths == nil {\n\t\treturn nil\n\t}\n\tif dest.Paths == nil {\n\t\tdest.Paths = \u0026spec3.Paths{}\n\t}\n\n\tfor k, v := range source.Components.Schemas {\n\t\tif dest.Components == nil {\n\t\t\tdest.Components = \u0026spec3.Components{}\n\t\t}\n\t\tif dest.Components.Schemas == nil {\n\t\t\tdest.Components.Schemas = map[string]*spec.Schema{}\n\t\t}\n\t\tif _, exists := dest.Components.Schemas[k]; exists {\n\t\t\tif strings.HasPrefix(k, metadataGV) || strings.HasPrefix(k, autoscalingGV) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"OpenAPI V3 merge schema conflict on %s\", k)\n\t\t}\n\t\tdest.Components.Schemas[k] = v\n\t}\n\tfor k, v := range source.Paths.Paths {\n\t\tif dest.Paths.Paths == nil {\n\t\t\tdest.Paths.Paths = map[string]*spec3.Path{}\n\t\t}\n\t\tdest.Paths.Paths[k] = v\n\t}\n\treturn nil\n}","line":{"from":108,"to":141}} {"id":100014374,"name":"NewController","signature":"func NewController(crdInformer informers.CustomResourceDefinitionInformer) *Controller","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/controller.go","code":"// NewController creates a new Controller with input CustomResourceDefinition informer\nfunc NewController(crdInformer informers.CustomResourceDefinitionInformer) *Controller {\n\tc := \u0026Controller{\n\t\tcrdLister: crdInformer.Lister(),\n\t\tcrdsSynced: crdInformer.Informer().HasSynced,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"crd_openapi_controller\"),\n\t\tcrdSpecs: map[string]map[string]*spec.Swagger{},\n\t}\n\n\tcrdInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: c.addCustomResourceDefinition,\n\t\tUpdateFunc: c.updateCustomResourceDefinition,\n\t\tDeleteFunc: c.deleteCustomResourceDefinition,\n\t})\n\n\tc.syncFn = c.sync\n\treturn c\n}","line":{"from":60,"to":77}} {"id":100014375,"name":"Run","signature":"func (c *Controller) Run(staticSpec *spec.Swagger, openAPIService *handler.OpenAPIService, stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/controller.go","code":"// Run sets openAPIAggregationManager and starts workers\nfunc (c *Controller) Run(staticSpec *spec.Swagger, openAPIService *handler.OpenAPIService, stopCh \u003c-chan struct{}) {\n\tdefer utilruntime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\tdefer klog.Infof(\"Shutting down OpenAPI controller\")\n\n\tklog.Infof(\"Starting OpenAPI controller\")\n\n\tc.staticSpec = staticSpec\n\tc.openAPIService = openAPIService\n\n\tif !cache.WaitForCacheSync(stopCh, c.crdsSynced) {\n\t\tutilruntime.HandleError(fmt.Errorf(\"timed out waiting for caches to sync\"))\n\t\treturn\n\t}\n\n\t// create initial spec to avoid merging once per CRD on startup\n\tcrds, err := c.crdLister.List(labels.Everything())\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"failed to initially list all CRDs: %v\", err))\n\t\treturn\n\t}\n\tfor _, crd := range crds {\n\t\tif !apiextensionshelpers.IsCRDConditionTrue(crd, apiextensionsv1.Established) {\n\t\t\tcontinue\n\t\t}\n\t\tnewSpecs, changed, err := buildVersionSpecs(crd, nil)\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"failed to build OpenAPI spec of CRD %s: %v\", crd.Name, err))\n\t\t} else if !changed {\n\t\t\tcontinue\n\t\t}\n\t\tc.crdSpecs[crd.Name] = newSpecs\n\t}\n\tif err := c.updateSpecLocked(); err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"failed to initially create OpenAPI spec for CRDs: %v\", err))\n\t\treturn\n\t}\n\n\t// only start one worker thread since its a slow moving API\n\tgo wait.Until(c.runWorker, time.Second, stopCh)\n\n\t\u003c-stopCh\n}","line":{"from":79,"to":122}} {"id":100014376,"name":"runWorker","signature":"func (c *Controller) runWorker()","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/controller.go","code":"func (c *Controller) runWorker() {\n\tfor c.processNextWorkItem() {\n\t}\n}","line":{"from":124,"to":127}} {"id":100014377,"name":"processNextWorkItem","signature":"func (c *Controller) processNextWorkItem() bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/controller.go","code":"func (c *Controller) processNextWorkItem() bool {\n\tkey, quit := c.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.queue.Done(key)\n\n\t// log slow aggregations\n\tstart := time.Now()\n\tdefer func() {\n\t\telapsed := time.Since(start)\n\t\tif elapsed \u003e time.Second {\n\t\t\tklog.Warningf(\"slow openapi aggregation of %q: %s\", key.(string), elapsed)\n\t\t}\n\t}()\n\n\terr := c.syncFn(key.(string))\n\tif err == nil {\n\t\tc.queue.Forget(key)\n\t\treturn true\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"%v failed with: %v\", key, err))\n\tc.queue.AddRateLimited(key)\n\treturn true\n}","line":{"from":129,"to":154}} {"id":100014378,"name":"sync","signature":"func (c *Controller) sync(name string) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/controller.go","code":"func (c *Controller) sync(name string) error {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tcrd, err := c.crdLister.Get(name)\n\tif err != nil \u0026\u0026 !errors.IsNotFound(err) {\n\t\treturn err\n\t}\n\n\t// do we have to remove all specs of this CRD?\n\tif errors.IsNotFound(err) || !apiextensionshelpers.IsCRDConditionTrue(crd, apiextensionsv1.Established) {\n\t\tif _, found := c.crdSpecs[name]; !found {\n\t\t\treturn nil\n\t\t}\n\t\tdelete(c.crdSpecs, name)\n\t\tklog.V(2).Infof(\"Updating CRD OpenAPI spec because %s was removed\", name)\n\t\tregenerationCounter.With(map[string]string{\"crd\": name, \"reason\": \"remove\"})\n\t\treturn c.updateSpecLocked()\n\t}\n\n\t// compute CRD spec and see whether it changed\n\toldSpecs, updated := c.crdSpecs[crd.Name]\n\tnewSpecs, changed, err := buildVersionSpecs(crd, oldSpecs)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !changed {\n\t\treturn nil\n\t}\n\n\t// update specs of this CRD\n\tc.crdSpecs[crd.Name] = newSpecs\n\tklog.V(2).Infof(\"Updating CRD OpenAPI spec because %s changed\", name)\n\treason := \"add\"\n\tif updated {\n\t\treason = \"update\"\n\t}\n\tregenerationCounter.With(map[string]string{\"crd\": name, \"reason\": reason})\n\treturn c.updateSpecLocked()\n}","line":{"from":156,"to":195}} {"id":100014379,"name":"buildVersionSpecs","signature":"func buildVersionSpecs(crd *apiextensionsv1.CustomResourceDefinition, oldSpecs map[string]*spec.Swagger) (map[string]*spec.Swagger, bool, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/controller.go","code":"func buildVersionSpecs(crd *apiextensionsv1.CustomResourceDefinition, oldSpecs map[string]*spec.Swagger) (map[string]*spec.Swagger, bool, error) {\n\tnewSpecs := map[string]*spec.Swagger{}\n\tanyChanged := false\n\tfor _, v := range crd.Spec.Versions {\n\t\tif !v.Served {\n\t\t\tcontinue\n\t\t}\n\t\tspec, err := builder.BuildOpenAPIV2(crd, v.Name, builder.Options{V2: true})\n\t\t// Defaults must be pruned here for CRDs to cleanly merge with the static\n\t\t// spec that already has defaults pruned\n\t\tspec.Definitions = handler.PruneDefaults(spec.Definitions)\n\t\tif err != nil {\n\t\t\treturn nil, false, err\n\t\t}\n\t\tnewSpecs[v.Name] = spec\n\t\tif oldSpecs[v.Name] == nil || !reflect.DeepEqual(oldSpecs[v.Name], spec) {\n\t\t\tanyChanged = true\n\t\t}\n\t}\n\tif !anyChanged \u0026\u0026 len(oldSpecs) == len(newSpecs) {\n\t\treturn newSpecs, false, nil\n\t}\n\n\treturn newSpecs, true, nil\n}","line":{"from":197,"to":221}} {"id":100014380,"name":"updateSpecLocked","signature":"func (c *Controller) updateSpecLocked() error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/controller.go","code":"// updateSpecLocked aggregates all OpenAPI specs and updates openAPIService.\n// It is not thread-safe. The caller is responsible to hold proper lock (Controller.lock).\nfunc (c *Controller) updateSpecLocked() error {\n\tcrdSpecs := []*spec.Swagger{}\n\tfor _, versionSpecs := range c.crdSpecs {\n\t\tfor _, s := range versionSpecs {\n\t\t\tcrdSpecs = append(crdSpecs, s)\n\t\t}\n\t}\n\tmergedSpec, err := builder.MergeSpecs(c.staticSpec, crdSpecs...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to merge specs: %v\", err)\n\t}\n\treturn c.openAPIService.UpdateSpec(mergedSpec)\n}","line":{"from":223,"to":237}} {"id":100014381,"name":"addCustomResourceDefinition","signature":"func (c *Controller) addCustomResourceDefinition(obj interface{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/controller.go","code":"func (c *Controller) addCustomResourceDefinition(obj interface{}) {\n\tcastObj := obj.(*apiextensionsv1.CustomResourceDefinition)\n\tklog.V(4).Infof(\"Adding customresourcedefinition %s\", castObj.Name)\n\tc.enqueue(castObj)\n}","line":{"from":239,"to":243}} {"id":100014382,"name":"updateCustomResourceDefinition","signature":"func (c *Controller) updateCustomResourceDefinition(oldObj, newObj interface{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/controller.go","code":"func (c *Controller) updateCustomResourceDefinition(oldObj, newObj interface{}) {\n\tcastNewObj := newObj.(*apiextensionsv1.CustomResourceDefinition)\n\tklog.V(4).Infof(\"Updating customresourcedefinition %s\", castNewObj.Name)\n\tc.enqueue(castNewObj)\n}","line":{"from":245,"to":249}} {"id":100014383,"name":"deleteCustomResourceDefinition","signature":"func (c *Controller) deleteCustomResourceDefinition(obj interface{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/controller.go","code":"func (c *Controller) deleteCustomResourceDefinition(obj interface{}) {\n\tcastObj, ok := obj.(*apiextensionsv1.CustomResourceDefinition)\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"Couldn't get object from tombstone %#v\", obj)\n\t\t\treturn\n\t\t}\n\t\tcastObj, ok = tombstone.Obj.(*apiextensionsv1.CustomResourceDefinition)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"Tombstone contained object that is not expected %#v\", obj)\n\t\t\treturn\n\t\t}\n\t}\n\tklog.V(4).Infof(\"Deleting customresourcedefinition %q\", castObj.Name)\n\tc.enqueue(castObj)\n}","line":{"from":251,"to":267}} {"id":100014384,"name":"enqueue","signature":"func (c *Controller) enqueue(obj *apiextensionsv1.CustomResourceDefinition)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/controller.go","code":"func (c *Controller) enqueue(obj *apiextensionsv1.CustomResourceDefinition) {\n\tc.queue.Add(obj.Name)\n}","line":{"from":269,"to":271}} {"id":100014385,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/metrics.go","code":"func init() {\n\tlegacyregistry.MustRegister(regenerationCounter)\n}","line":{"from":35,"to":37}} {"id":100014386,"name":"ToStructuralOpenAPIV2","signature":"func ToStructuralOpenAPIV2(in *structuralschema.Structural) *structuralschema.Structural","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/v2/conversion.go","code":"// ToStructuralOpenAPIV2 converts our internal OpenAPI v3 structural schema to\n// to a v2 compatible schema.\nfunc ToStructuralOpenAPIV2(in *structuralschema.Structural) *structuralschema.Structural {\n\tif in == nil {\n\t\treturn nil\n\t}\n\n\tout := in.DeepCopy()\n\n\t// Remove unsupported fields in OpenAPI v2 recursively\n\tmapper := structuralschema.Visitor{\n\t\tStructural: func(s *structuralschema.Structural) bool {\n\t\t\tchanged := false\n\t\t\tif s.ValueValidation != nil {\n\t\t\t\tif s.ValueValidation.AllOf != nil {\n\t\t\t\t\ts.ValueValidation.AllOf = nil\n\t\t\t\t\tchanged = true\n\t\t\t\t}\n\t\t\t\tif s.ValueValidation.OneOf != nil {\n\t\t\t\t\ts.ValueValidation.OneOf = nil\n\t\t\t\t\tchanged = true\n\t\t\t\t}\n\t\t\t\tif s.ValueValidation.AnyOf != nil {\n\t\t\t\t\ts.ValueValidation.AnyOf = nil\n\t\t\t\t\tchanged = true\n\t\t\t\t}\n\t\t\t\tif s.ValueValidation.Not != nil {\n\t\t\t\t\ts.ValueValidation.Not = nil\n\t\t\t\t\tchanged = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// https://github.com/kubernetes/kube-openapi/pull/143/files#diff-ce77fea74b9dd098045004410023e0c3R219\n\t\t\tif s.Nullable {\n\t\t\t\ts.Type = \"\"\n\t\t\t\ts.Nullable = false\n\n\t\t\t\t// untyped values break if items or properties are set in kubectl\n\t\t\t\t// https://github.com/kubernetes/kube-openapi/pull/143/files#diff-62afddb578e9db18fb32ffb6b7802d92R183\n\t\t\t\ts.Items = nil\n\t\t\t\ts.Properties = nil\n\n\t\t\t\tchanged = true\n\t\t\t}\n\n\t\t\tif s.XPreserveUnknownFields {\n\t\t\t\t// unknown fields break if items or properties are set in kubectl\n\t\t\t\ts.Items = nil\n\t\t\t\ts.Properties = nil\n\n\t\t\t\tchanged = true\n\t\t\t}\n\n\t\t\tif s.Items == nil \u0026\u0026 s.Type == \"array\" {\n\t\t\t\t// kubectl cannot cope with array without item schema, e.g. due to XPreserveUnknownFields case above\n\t\t\t\t// https://github.com/kubernetes/kube-openapi/blob/64514a1d5d596b96e6f957e2be275ae14d6b0804/pkg/util/proto/document.go#L185\n\t\t\t\ts.Type = \"\"\n\n\t\t\t\tchanged = true\n\t\t\t}\n\n\t\t\tif s.XPreserveUnknownFields \u0026\u0026 s.Type == \"object\" {\n\t\t\t\t// similar as above, kubectl doesn't properly handle object fields with `x-kubernetes-preserve-unknown-fields: true`\n\t\t\t\ts.Type = \"\"\n\n\t\t\t\tchanged = true\n\t\t\t}\n\n\t\t\tfor f, fs := range s.Properties {\n\t\t\t\tif fs.Nullable {\n\t\t\t\t\ts.ValueValidation.Required, changed = filterOut(s.ValueValidation.Required, f)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif s.AdditionalProperties != nil \u0026\u0026 s.AdditionalProperties.Structural != nil \u0026\u0026 s.AdditionalProperties.Structural.Nullable {\n\t\t\t\ts.ValueValidation.Required, changed = nil, true\n\t\t\t}\n\n\t\t\treturn changed\n\t\t},\n\t\t// we drop all junctors above, and hence, never reach nested value validations\n\t\tNestedValueValidation: nil,\n\t}\n\tmapper.Visit(out)\n\n\treturn out\n}","line":{"from":23,"to":108}} {"id":100014387,"name":"filterOut","signature":"func filterOut(ss []string, x string) ([]string, bool)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapi/v2/conversion.go","code":"func filterOut(ss []string, x string) ([]string, bool) {\n\tvar filtered []string\n\tfor i, s := range ss {\n\t\tif s == x {\n\t\t\tif filtered == nil {\n\t\t\t\tfiltered = make([]string, i, len(ss))\n\t\t\t\tcopy(filtered, ss[:i])\n\t\t\t}\n\t\t} else if filtered != nil {\n\t\t\tfiltered = append(filtered, s)\n\t\t}\n\t}\n\tif filtered != nil {\n\t\tif len(filtered) == 0 {\n\t\t\treturn nil, true\n\t\t}\n\t\treturn filtered, true\n\t}\n\treturn ss, false\n}","line":{"from":110,"to":129}} {"id":100014388,"name":"NewController","signature":"func NewController(crdInformer informers.CustomResourceDefinitionInformer) *Controller","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapiv3/controller.go","code":"// NewController creates a new Controller with input CustomResourceDefinition informer\nfunc NewController(crdInformer informers.CustomResourceDefinitionInformer) *Controller {\n\tc := \u0026Controller{\n\t\tcrdLister: crdInformer.Lister(),\n\t\tcrdsSynced: crdInformer.Informer().HasSynced,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"crd_openapi_v3_controller\"),\n\t\tspecsByGVandName: map[schema.GroupVersion]map[string]*spec3.OpenAPI{},\n\t}\n\n\tcrdInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: c.addCustomResourceDefinition,\n\t\tUpdateFunc: c.updateCustomResourceDefinition,\n\t\tDeleteFunc: c.deleteCustomResourceDefinition,\n\t})\n\n\tc.syncFn = c.sync\n\treturn c\n}","line":{"from":60,"to":77}} {"id":100014389,"name":"Run","signature":"func (c *Controller) Run(openAPIV3Service *handler3.OpenAPIService, stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapiv3/controller.go","code":"// Run sets openAPIAggregationManager and starts workers\nfunc (c *Controller) Run(openAPIV3Service *handler3.OpenAPIService, stopCh \u003c-chan struct{}) {\n\tdefer utilruntime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\tdefer klog.Infof(\"Shutting down OpenAPI V3 controller\")\n\n\tklog.Infof(\"Starting OpenAPI V3 controller\")\n\n\tc.openAPIV3Service = openAPIV3Service\n\n\tif !cache.WaitForCacheSync(stopCh, c.crdsSynced) {\n\t\tutilruntime.HandleError(fmt.Errorf(\"timed out waiting for caches to sync\"))\n\t\treturn\n\t}\n\n\tcrds, err := c.crdLister.List(labels.Everything())\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"failed to initially list all CRDs: %v\", err))\n\t\treturn\n\t}\n\tfor _, crd := range crds {\n\t\tif !apiextensionshelpers.IsCRDConditionTrue(crd, apiextensionsv1.Established) {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, v := range crd.Spec.Versions {\n\t\t\tif !v.Served {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc.buildV3Spec(crd, crd.Name, v.Name)\n\t\t}\n\t}\n\n\t// only start one worker thread since its a slow moving API\n\tgo wait.Until(c.runWorker, time.Second, stopCh)\n\n\t\u003c-stopCh\n}","line":{"from":79,"to":115}} {"id":100014390,"name":"runWorker","signature":"func (c *Controller) runWorker()","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapiv3/controller.go","code":"func (c *Controller) runWorker() {\n\tfor c.processNextWorkItem() {\n\t}\n}","line":{"from":117,"to":120}} {"id":100014391,"name":"processNextWorkItem","signature":"func (c *Controller) processNextWorkItem() bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapiv3/controller.go","code":"func (c *Controller) processNextWorkItem() bool {\n\tkey, quit := c.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.queue.Done(key)\n\n\t// log slow aggregations\n\tstart := time.Now()\n\tdefer func() {\n\t\telapsed := time.Since(start)\n\t\tif elapsed \u003e time.Second {\n\t\t\tklog.Warningf(\"slow openapi aggregation of %q: %s\", key.(string), elapsed)\n\t\t}\n\t}()\n\n\terr := c.syncFn(key.(string))\n\tif err == nil {\n\t\tc.queue.Forget(key)\n\t\treturn true\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"%v failed with: %v\", key, err))\n\tc.queue.AddRateLimited(key)\n\treturn true\n}","line":{"from":122,"to":147}} {"id":100014392,"name":"sync","signature":"func (c *Controller) sync(name string) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapiv3/controller.go","code":"func (c *Controller) sync(name string) error {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tcrd, err := c.crdLister.Get(name)\n\tif err != nil \u0026\u0026 !errors.IsNotFound(err) {\n\t\treturn err\n\t}\n\n\tif errors.IsNotFound(err) || !apiextensionshelpers.IsCRDConditionTrue(crd, apiextensionsv1.Established) {\n\t\tc.deleteCRD(name)\n\t\treturn nil\n\t}\n\n\tfor _, v := range crd.Spec.Versions {\n\t\tif !v.Served {\n\t\t\tcontinue\n\t\t}\n\t\tc.buildV3Spec(crd, name, v.Name)\n\t}\n\n\treturn nil\n}","line":{"from":149,"to":171}} {"id":100014393,"name":"deleteCRD","signature":"func (c *Controller) deleteCRD(name string)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapiv3/controller.go","code":"func (c *Controller) deleteCRD(name string) {\n\tfor gv, crdListForGV := range c.specsByGVandName {\n\t\t_, needOpenAPIUpdate := crdListForGV[name]\n\t\tif needOpenAPIUpdate {\n\t\t\tdelete(crdListForGV, name)\n\t\t\tif len(crdListForGV) == 0 {\n\t\t\t\tdelete(c.specsByGVandName, gv)\n\t\t\t}\n\t\t\tregenerationCounter.With(map[string]string{\"group\": gv.Group, \"version\": gv.Version, \"crd\": name, \"reason\": \"remove\"})\n\t\t\tc.updateGroupVersion(gv)\n\t\t}\n\t}\n}","line":{"from":173,"to":185}} {"id":100014394,"name":"updateGroupVersion","signature":"func (c *Controller) updateGroupVersion(gv schema.GroupVersion) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapiv3/controller.go","code":"func (c *Controller) updateGroupVersion(gv schema.GroupVersion) error {\n\tif _, ok := c.specsByGVandName[gv]; !ok {\n\t\tc.openAPIV3Service.DeleteGroupVersion(groupVersionToOpenAPIV3Path(gv))\n\t\treturn nil\n\t}\n\n\tvar specs []*spec3.OpenAPI\n\tfor _, spec := range c.specsByGVandName[gv] {\n\t\tspecs = append(specs, spec)\n\t}\n\n\tmergedSpec, err := builder.MergeSpecsV3(specs...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to merge specs: %v\", err)\n\t}\n\n\tc.openAPIV3Service.UpdateGroupVersion(groupVersionToOpenAPIV3Path(gv), mergedSpec)\n\treturn nil\n}","line":{"from":187,"to":205}} {"id":100014395,"name":"updateCRDSpec","signature":"func (c *Controller) updateCRDSpec(crd *apiextensionsv1.CustomResourceDefinition, name, versionName string, v3 *spec3.OpenAPI) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapiv3/controller.go","code":"func (c *Controller) updateCRDSpec(crd *apiextensionsv1.CustomResourceDefinition, name, versionName string, v3 *spec3.OpenAPI) error {\n\tgv := schema.GroupVersion{\n\t\tGroup: crd.Spec.Group,\n\t\tVersion: versionName,\n\t}\n\n\t_, ok := c.specsByGVandName[gv]\n\treason := \"update\"\n\tif !ok {\n\t\treason = \"add\"\n\t\tc.specsByGVandName[gv] = map[string]*spec3.OpenAPI{}\n\t}\n\n\toldSpec, ok := c.specsByGVandName[gv][name]\n\tif ok {\n\t\tif reflect.DeepEqual(oldSpec, v3) {\n\t\t\t// no changes to CRD\n\t\t\treturn nil\n\t\t}\n\t}\n\tc.specsByGVandName[gv][name] = v3\n\tregenerationCounter.With(map[string]string{\"crd\": name, \"group\": gv.Group, \"version\": gv.Version, \"reason\": reason})\n\treturn c.updateGroupVersion(gv)\n}","line":{"from":207,"to":230}} {"id":100014396,"name":"buildV3Spec","signature":"func (c *Controller) buildV3Spec(crd *apiextensionsv1.CustomResourceDefinition, name, versionName string) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapiv3/controller.go","code":"func (c *Controller) buildV3Spec(crd *apiextensionsv1.CustomResourceDefinition, name, versionName string) error {\n\tv3, err := builder.BuildOpenAPIV3(crd, versionName, builder.Options{V2: false})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.updateCRDSpec(crd, name, versionName, v3)\n\treturn nil\n}","line":{"from":232,"to":241}} {"id":100014397,"name":"addCustomResourceDefinition","signature":"func (c *Controller) addCustomResourceDefinition(obj interface{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapiv3/controller.go","code":"func (c *Controller) addCustomResourceDefinition(obj interface{}) {\n\tcastObj := obj.(*apiextensionsv1.CustomResourceDefinition)\n\tklog.V(4).Infof(\"Adding customresourcedefinition %s\", castObj.Name)\n\tc.enqueue(castObj)\n}","line":{"from":243,"to":247}} {"id":100014398,"name":"updateCustomResourceDefinition","signature":"func (c *Controller) updateCustomResourceDefinition(oldObj, newObj interface{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapiv3/controller.go","code":"func (c *Controller) updateCustomResourceDefinition(oldObj, newObj interface{}) {\n\tcastNewObj := newObj.(*apiextensionsv1.CustomResourceDefinition)\n\tklog.V(4).Infof(\"Updating customresourcedefinition %s\", castNewObj.Name)\n\tc.enqueue(castNewObj)\n}","line":{"from":249,"to":253}} {"id":100014399,"name":"deleteCustomResourceDefinition","signature":"func (c *Controller) deleteCustomResourceDefinition(obj interface{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapiv3/controller.go","code":"func (c *Controller) deleteCustomResourceDefinition(obj interface{}) {\n\tcastObj, ok := obj.(*apiextensionsv1.CustomResourceDefinition)\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"Couldn't get object from tombstone %#v\", obj)\n\t\t\treturn\n\t\t}\n\t\tcastObj, ok = tombstone.Obj.(*apiextensionsv1.CustomResourceDefinition)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"Tombstone contained object that is not expected %#v\", obj)\n\t\t\treturn\n\t\t}\n\t}\n\tklog.V(4).Infof(\"Deleting customresourcedefinition %q\", castObj.Name)\n\tc.enqueue(castObj)\n}","line":{"from":255,"to":271}} {"id":100014400,"name":"enqueue","signature":"func (c *Controller) enqueue(obj *apiextensionsv1.CustomResourceDefinition)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapiv3/controller.go","code":"func (c *Controller) enqueue(obj *apiextensionsv1.CustomResourceDefinition) {\n\tc.queue.Add(obj.Name)\n}","line":{"from":273,"to":275}} {"id":100014401,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapiv3/metrics.go","code":"func init() {\n\tlegacyregistry.MustRegister(regenerationCounter)\n}","line":{"from":35,"to":37}} {"id":100014402,"name":"groupVersionToOpenAPIV3Path","signature":"func groupVersionToOpenAPIV3Path(gv schema.GroupVersion) string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/openapiv3/util.go","code":"func groupVersionToOpenAPIV3Path(gv schema.GroupVersion) string {\n\treturn \"apis/\" + gv.Group + \"/\" + gv.Version\n}","line":{"from":23,"to":25}} {"id":100014403,"name":"NewNamingConditionController","signature":"func NewNamingConditionController(","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/status/naming_controller.go","code":"func NewNamingConditionController(\n\tcrdInformer informers.CustomResourceDefinitionInformer,\n\tcrdClient client.CustomResourceDefinitionsGetter,\n) *NamingConditionController {\n\tc := \u0026NamingConditionController{\n\t\tcrdClient: crdClient,\n\t\tcrdLister: crdInformer.Lister(),\n\t\tcrdSynced: crdInformer.Informer().HasSynced,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"crd_naming_condition_controller\"),\n\t}\n\n\tinformerIndexer := crdInformer.Informer().GetIndexer()\n\tc.crdMutationCache = cache.NewIntegerResourceVersionMutationCache(informerIndexer, informerIndexer, 60*time.Second, false)\n\n\tcrdInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: c.addCustomResourceDefinition,\n\t\tUpdateFunc: c.updateCustomResourceDefinition,\n\t\tDeleteFunc: c.deleteCustomResourceDefinition,\n\t})\n\n\tc.syncFn = c.sync\n\n\treturn c\n}","line":{"from":64,"to":87}} {"id":100014404,"name":"getAcceptedNamesForGroup","signature":"func (c *NamingConditionController) getAcceptedNamesForGroup(group string) (allResources sets.String, allKinds sets.String)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/status/naming_controller.go","code":"func (c *NamingConditionController) getAcceptedNamesForGroup(group string) (allResources sets.String, allKinds sets.String) {\n\tallResources = sets.String{}\n\tallKinds = sets.String{}\n\n\tlist, err := c.crdLister.List(labels.Everything())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor _, curr := range list {\n\t\tif curr.Spec.Group != group {\n\t\t\tcontinue\n\t\t}\n\n\t\t// for each item here, see if we have a mutation cache entry that is more recent\n\t\t// this makes sure that if we tight loop on update and run, our mutation cache will show\n\t\t// us the version of the objects we just updated to.\n\t\titem := curr\n\t\tobj, exists, err := c.crdMutationCache.GetByKey(curr.Name)\n\t\tif exists \u0026\u0026 err == nil {\n\t\t\titem = obj.(*apiextensionsv1.CustomResourceDefinition)\n\t\t}\n\n\t\tallResources.Insert(item.Status.AcceptedNames.Plural)\n\t\tallResources.Insert(item.Status.AcceptedNames.Singular)\n\t\tallResources.Insert(item.Status.AcceptedNames.ShortNames...)\n\n\t\tallKinds.Insert(item.Status.AcceptedNames.Kind)\n\t\tallKinds.Insert(item.Status.AcceptedNames.ListKind)\n\t}\n\n\treturn allResources, allKinds\n}","line":{"from":89,"to":121}} {"id":100014405,"name":"calculateNamesAndConditions","signature":"func (c *NamingConditionController) calculateNamesAndConditions(in *apiextensionsv1.CustomResourceDefinition) (apiextensionsv1.CustomResourceDefinitionNames, apiextensionsv1.CustomResourceDefinitionCondition, apiextensionsv1.CustomResourceDefinitionCondition)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/status/naming_controller.go","code":"func (c *NamingConditionController) calculateNamesAndConditions(in *apiextensionsv1.CustomResourceDefinition) (apiextensionsv1.CustomResourceDefinitionNames, apiextensionsv1.CustomResourceDefinitionCondition, apiextensionsv1.CustomResourceDefinitionCondition) {\n\t// Get the names that have already been claimed\n\tallResources, allKinds := c.getAcceptedNamesForGroup(in.Spec.Group)\n\n\tnamesAcceptedCondition := apiextensionsv1.CustomResourceDefinitionCondition{\n\t\tType: apiextensionsv1.NamesAccepted,\n\t\tStatus: apiextensionsv1.ConditionUnknown,\n\t}\n\n\trequestedNames := in.Spec.Names\n\tacceptedNames := in.Status.AcceptedNames\n\tnewNames := in.Status.AcceptedNames\n\n\t// Check each name for mismatches. If there's a mismatch between spec and status, then try to deconflict.\n\t// Continue on errors so that the status is the best match possible\n\tif err := equalToAcceptedOrFresh(requestedNames.Plural, acceptedNames.Plural, allResources); err != nil {\n\t\tnamesAcceptedCondition.Status = apiextensionsv1.ConditionFalse\n\t\tnamesAcceptedCondition.Reason = \"PluralConflict\"\n\t\tnamesAcceptedCondition.Message = err.Error()\n\t} else {\n\t\tnewNames.Plural = requestedNames.Plural\n\t}\n\tif err := equalToAcceptedOrFresh(requestedNames.Singular, acceptedNames.Singular, allResources); err != nil {\n\t\tnamesAcceptedCondition.Status = apiextensionsv1.ConditionFalse\n\t\tnamesAcceptedCondition.Reason = \"SingularConflict\"\n\t\tnamesAcceptedCondition.Message = err.Error()\n\t} else {\n\t\tnewNames.Singular = requestedNames.Singular\n\t}\n\tif !reflect.DeepEqual(requestedNames.ShortNames, acceptedNames.ShortNames) {\n\t\terrs := []error{}\n\t\texistingShortNames := sets.NewString(acceptedNames.ShortNames...)\n\t\tfor _, shortName := range requestedNames.ShortNames {\n\t\t\t// if the shortname is already ours, then we're fine\n\t\t\tif existingShortNames.Has(shortName) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := equalToAcceptedOrFresh(shortName, \"\", allResources); err != nil {\n\t\t\t\terrs = append(errs, err)\n\t\t\t}\n\n\t\t}\n\t\tif err := utilerrors.NewAggregate(errs); err != nil {\n\t\t\tnamesAcceptedCondition.Status = apiextensionsv1.ConditionFalse\n\t\t\tnamesAcceptedCondition.Reason = \"ShortNamesConflict\"\n\t\t\tnamesAcceptedCondition.Message = err.Error()\n\t\t} else {\n\t\t\tnewNames.ShortNames = requestedNames.ShortNames\n\t\t}\n\t}\n\n\tif err := equalToAcceptedOrFresh(requestedNames.Kind, acceptedNames.Kind, allKinds); err != nil {\n\t\tnamesAcceptedCondition.Status = apiextensionsv1.ConditionFalse\n\t\tnamesAcceptedCondition.Reason = \"KindConflict\"\n\t\tnamesAcceptedCondition.Message = err.Error()\n\t} else {\n\t\tnewNames.Kind = requestedNames.Kind\n\t}\n\tif err := equalToAcceptedOrFresh(requestedNames.ListKind, acceptedNames.ListKind, allKinds); err != nil {\n\t\tnamesAcceptedCondition.Status = apiextensionsv1.ConditionFalse\n\t\tnamesAcceptedCondition.Reason = \"ListKindConflict\"\n\t\tnamesAcceptedCondition.Message = err.Error()\n\t} else {\n\t\tnewNames.ListKind = requestedNames.ListKind\n\t}\n\n\tnewNames.Categories = requestedNames.Categories\n\n\t// if we haven't changed the condition, then our names must be good.\n\tif namesAcceptedCondition.Status == apiextensionsv1.ConditionUnknown {\n\t\tnamesAcceptedCondition.Status = apiextensionsv1.ConditionTrue\n\t\tnamesAcceptedCondition.Reason = \"NoConflicts\"\n\t\tnamesAcceptedCondition.Message = \"no conflicts found\"\n\t}\n\n\t// set EstablishedCondition initially to false, then set it to true in establishing controller.\n\t// The Establishing Controller will see the NamesAccepted condition when it arrives through the shared informer.\n\t// At that time the API endpoint handler will serve the endpoint, avoiding a race\n\t// which we had if we set Established to true here.\n\testablishedCondition := apiextensionsv1.CustomResourceDefinitionCondition{\n\t\tType: apiextensionsv1.Established,\n\t\tStatus: apiextensionsv1.ConditionFalse,\n\t\tReason: \"NotAccepted\",\n\t\tMessage: \"not all names are accepted\",\n\t}\n\tif old := apiextensionshelpers.FindCRDCondition(in, apiextensionsv1.Established); old != nil {\n\t\testablishedCondition = *old\n\t}\n\tif establishedCondition.Status != apiextensionsv1.ConditionTrue \u0026\u0026 namesAcceptedCondition.Status == apiextensionsv1.ConditionTrue {\n\t\testablishedCondition = apiextensionsv1.CustomResourceDefinitionCondition{\n\t\t\tType: apiextensionsv1.Established,\n\t\t\tStatus: apiextensionsv1.ConditionFalse,\n\t\t\tReason: \"Installing\",\n\t\t\tMessage: \"the initial names have been accepted\",\n\t\t}\n\t}\n\n\treturn newNames, namesAcceptedCondition, establishedCondition\n}","line":{"from":123,"to":221}} {"id":100014406,"name":"equalToAcceptedOrFresh","signature":"func equalToAcceptedOrFresh(requestedName, acceptedName string, usedNames sets.String) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/status/naming_controller.go","code":"func equalToAcceptedOrFresh(requestedName, acceptedName string, usedNames sets.String) error {\n\tif requestedName == acceptedName {\n\t\treturn nil\n\t}\n\tif !usedNames.Has(requestedName) {\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"%q is already in use\", requestedName)\n}","line":{"from":223,"to":232}} {"id":100014407,"name":"sync","signature":"func (c *NamingConditionController) sync(key string) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/status/naming_controller.go","code":"func (c *NamingConditionController) sync(key string) error {\n\tinCustomResourceDefinition, err := c.crdLister.Get(key)\n\tif apierrors.IsNotFound(err) {\n\t\t// CRD was deleted and has freed its names.\n\t\t// Reconsider all other CRDs in the same group.\n\t\tif err := c.requeueAllOtherGroupCRDs(key); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Skip checking names if Spec and Status names are same.\n\tif equality.Semantic.DeepEqual(inCustomResourceDefinition.Spec.Names, inCustomResourceDefinition.Status.AcceptedNames) {\n\t\treturn nil\n\t}\n\n\tacceptedNames, namingCondition, establishedCondition := c.calculateNamesAndConditions(inCustomResourceDefinition)\n\n\t// nothing to do if accepted names and NamesAccepted condition didn't change\n\tif reflect.DeepEqual(inCustomResourceDefinition.Status.AcceptedNames, acceptedNames) \u0026\u0026\n\t\tapiextensionshelpers.IsCRDConditionEquivalent(\u0026namingCondition, apiextensionshelpers.FindCRDCondition(inCustomResourceDefinition, apiextensionsv1.NamesAccepted)) {\n\t\treturn nil\n\t}\n\n\tcrd := inCustomResourceDefinition.DeepCopy()\n\tcrd.Status.AcceptedNames = acceptedNames\n\tapiextensionshelpers.SetCRDCondition(crd, namingCondition)\n\tapiextensionshelpers.SetCRDCondition(crd, establishedCondition)\n\n\tupdatedObj, err := c.crdClient.CustomResourceDefinitions().UpdateStatus(context.TODO(), crd, metav1.UpdateOptions{})\n\tif apierrors.IsNotFound(err) || apierrors.IsConflict(err) {\n\t\t// deleted or changed in the meantime, we'll get called again\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// if the update was successful, go ahead and add the entry to the mutation cache\n\tc.crdMutationCache.Mutation(updatedObj)\n\n\t// we updated our status, so we may be releasing a name. When this happens, we need to rekick everything in our group\n\t// if we fail to rekick, just return as normal. We'll get everything on a resync\n\tif err := c.requeueAllOtherGroupCRDs(key); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":234,"to":285}} {"id":100014408,"name":"Run","signature":"func (c *NamingConditionController) Run(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/status/naming_controller.go","code":"func (c *NamingConditionController) Run(stopCh \u003c-chan struct{}) {\n\tdefer utilruntime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\n\tklog.Info(\"Starting NamingConditionController\")\n\tdefer klog.Info(\"Shutting down NamingConditionController\")\n\n\tif !cache.WaitForCacheSync(stopCh, c.crdSynced) {\n\t\treturn\n\t}\n\n\t// only start one worker thread since its a slow moving API and the naming conflict resolution bits aren't thread-safe\n\tgo wait.Until(c.runWorker, time.Second, stopCh)\n\n\t\u003c-stopCh\n}","line":{"from":287,"to":302}} {"id":100014409,"name":"runWorker","signature":"func (c *NamingConditionController) runWorker()","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/status/naming_controller.go","code":"func (c *NamingConditionController) runWorker() {\n\tfor c.processNextWorkItem() {\n\t}\n}","line":{"from":304,"to":307}} {"id":100014410,"name":"processNextWorkItem","signature":"func (c *NamingConditionController) processNextWorkItem() bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/status/naming_controller.go","code":"// processNextWorkItem deals with one key off the queue. It returns false when it's time to quit.\nfunc (c *NamingConditionController) processNextWorkItem() bool {\n\tkey, quit := c.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.queue.Done(key)\n\n\terr := c.syncFn(key.(string))\n\tif err == nil {\n\t\tc.queue.Forget(key)\n\t\treturn true\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"%v failed with: %v\", key, err))\n\tc.queue.AddRateLimited(key)\n\n\treturn true\n}","line":{"from":309,"to":327}} {"id":100014411,"name":"enqueue","signature":"func (c *NamingConditionController) enqueue(obj *apiextensionsv1.CustomResourceDefinition)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/status/naming_controller.go","code":"func (c *NamingConditionController) enqueue(obj *apiextensionsv1.CustomResourceDefinition) {\n\tkey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get key for object %#v: %v\", obj, err))\n\t\treturn\n\t}\n\n\tc.queue.Add(key)\n}","line":{"from":329,"to":337}} {"id":100014412,"name":"addCustomResourceDefinition","signature":"func (c *NamingConditionController) addCustomResourceDefinition(obj interface{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/status/naming_controller.go","code":"func (c *NamingConditionController) addCustomResourceDefinition(obj interface{}) {\n\tcastObj := obj.(*apiextensionsv1.CustomResourceDefinition)\n\tklog.V(4).Infof(\"Adding %s\", castObj.Name)\n\tc.enqueue(castObj)\n}","line":{"from":339,"to":343}} {"id":100014413,"name":"updateCustomResourceDefinition","signature":"func (c *NamingConditionController) updateCustomResourceDefinition(obj, _ interface{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/status/naming_controller.go","code":"func (c *NamingConditionController) updateCustomResourceDefinition(obj, _ interface{}) {\n\tcastObj := obj.(*apiextensionsv1.CustomResourceDefinition)\n\tklog.V(4).Infof(\"Updating %s\", castObj.Name)\n\tc.enqueue(castObj)\n}","line":{"from":345,"to":349}} {"id":100014414,"name":"deleteCustomResourceDefinition","signature":"func (c *NamingConditionController) deleteCustomResourceDefinition(obj interface{})","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/status/naming_controller.go","code":"func (c *NamingConditionController) deleteCustomResourceDefinition(obj interface{}) {\n\tcastObj, ok := obj.(*apiextensionsv1.CustomResourceDefinition)\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"Couldn't get object from tombstone %#v\", obj)\n\t\t\treturn\n\t\t}\n\t\tcastObj, ok = tombstone.Obj.(*apiextensionsv1.CustomResourceDefinition)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"Tombstone contained object that is not expected %#v\", obj)\n\t\t\treturn\n\t\t}\n\t}\n\tklog.V(4).Infof(\"Deleting %q\", castObj.Name)\n\tc.enqueue(castObj)\n}","line":{"from":351,"to":367}} {"id":100014415,"name":"requeueAllOtherGroupCRDs","signature":"func (c *NamingConditionController) requeueAllOtherGroupCRDs(name string) error","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/controller/status/naming_controller.go","code":"func (c *NamingConditionController) requeueAllOtherGroupCRDs(name string) error {\n\tpluralGroup := strings.SplitN(name, \".\", 2)\n\tlist, err := c.crdLister.List(labels.Everything())\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, curr := range list {\n\t\tif curr.Spec.Group == pluralGroup[1] \u0026\u0026 curr.Name != name {\n\t\t\tc.queue.Add(curr.Name)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":369,"to":381}} {"id":100014416,"name":"NewUnstructuredObjectTyper","signature":"func NewUnstructuredObjectTyper() *UnstructuredObjectTyper","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/crdserverscheme/unstructured.go","code":"// NewUnstructuredObjectTyper returns a runtime.ObjectTyper for\n// unstructured objects based on discovery information. It accepts a list of fallback typers\n// for handling objects that are not runtime.Unstructured. It does not delegate the Recognizes\n// check, only ObjectKinds.\n// TODO this only works for the apiextensions server and doesn't recognize any types. Move to point of use.\nfunc NewUnstructuredObjectTyper() *UnstructuredObjectTyper {\n\tdot := \u0026UnstructuredObjectTyper{}\n\treturn dot\n}","line":{"from":31,"to":39}} {"id":100014417,"name":"ObjectKinds","signature":"func (d *UnstructuredObjectTyper) ObjectKinds(obj runtime.Object) (gvks []schema.GroupVersionKind, unversionedType bool, err error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/crdserverscheme/unstructured.go","code":"// ObjectKinds returns a slice of one element with the group,version,kind of the\n// provided object, or an error if the object is not runtime.Unstructured or\n// has no group,version,kind information. unversionedType will always be false\n// because runtime.Unstructured object should always have group,version,kind\n// information set.\nfunc (d *UnstructuredObjectTyper) ObjectKinds(obj runtime.Object) (gvks []schema.GroupVersionKind, unversionedType bool, err error) {\n\tif _, ok := obj.(runtime.Unstructured); ok {\n\t\tgvk := obj.GetObjectKind().GroupVersionKind()\n\t\tif len(gvk.Kind) == 0 {\n\t\t\treturn nil, false, runtime.NewMissingKindErr(\"object has no kind field \")\n\t\t}\n\t\tif len(gvk.Version) == 0 {\n\t\t\treturn nil, false, runtime.NewMissingVersionErr(\"object has no apiVersion field\")\n\t\t}\n\t\treturn []schema.GroupVersionKind{gvk}, false, nil\n\t}\n\n\treturn nil, false, runtime.NewNotRegisteredErrForType(\"crdserverscheme.UnstructuredObjectTyper\", reflect.TypeOf(obj))\n}","line":{"from":41,"to":59}} {"id":100014418,"name":"Recognizes","signature":"func (d *UnstructuredObjectTyper) Recognizes(gvk schema.GroupVersionKind) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/crdserverscheme/unstructured.go","code":"// Recognizes returns true if the provided group,version,kind was in the\n// discovery information.\nfunc (d *UnstructuredObjectTyper) Recognizes(gvk schema.GroupVersionKind) bool {\n\treturn false\n}","line":{"from":61,"to":65}} {"id":100014419,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/features/kube_features.go","code":"func init() {\n\tutilfeature.DefaultMutableFeatureGate.Add(defaultKubernetesFeatureGates)\n}","line":{"from":32,"to":34}} {"id":100014420,"name":"NewStorage","signature":"func NewStorage(resource schema.GroupResource, singularResource schema.GroupResource, kind, listKind schema.GroupVersionKind, strategy customResourceStrategy, optsGetter generic.RESTOptionsGetter, categories []string, tableConvertor rest.TableConvertor, replicasPathMapping managedfields.ResourcePathMappings) CustomResourceStorage","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/etcd.go","code":"func NewStorage(resource schema.GroupResource, singularResource schema.GroupResource, kind, listKind schema.GroupVersionKind, strategy customResourceStrategy, optsGetter generic.RESTOptionsGetter, categories []string, tableConvertor rest.TableConvertor, replicasPathMapping managedfields.ResourcePathMappings) CustomResourceStorage {\n\tvar storage CustomResourceStorage\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object {\n\t\t\t// set the expected group/version/kind in the new object as a signal to the versioning decoder\n\t\t\tret := \u0026unstructured.Unstructured{}\n\t\t\tret.SetGroupVersionKind(kind)\n\t\t\treturn ret\n\t\t},\n\t\tNewListFunc: func() runtime.Object {\n\t\t\t// lists are never stored, only manufactured, so stomp in the right kind\n\t\t\tret := \u0026unstructured.UnstructuredList{}\n\t\t\tret.SetGroupVersionKind(listKind)\n\t\t\treturn ret\n\t\t},\n\t\tPredicateFunc: strategy.MatchCustomResourceDefinitionStorage,\n\t\tDefaultQualifiedResource: resource,\n\t\tSingularQualifiedResource: singularResource,\n\n\t\tCreateStrategy: strategy,\n\t\tUpdateStrategy: strategy,\n\t\tDeleteStrategy: strategy,\n\t\tResetFieldsStrategy: strategy,\n\n\t\tTableConvertor: tableConvertor,\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: strategy.GetAttrs}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\tpanic(err) // TODO: Propagate error up\n\t}\n\tstorage.CustomResource = \u0026REST{store, categories}\n\n\tif strategy.status != nil {\n\t\tstatusStore := *store\n\t\tstatusStrategy := NewStatusStrategy(strategy)\n\t\tstatusStore.UpdateStrategy = statusStrategy\n\t\tstatusStore.ResetFieldsStrategy = statusStrategy\n\t\tstorage.Status = \u0026StatusREST{store: \u0026statusStore}\n\t}\n\n\tif scale := strategy.scale; scale != nil {\n\t\tvar labelSelectorPath string\n\t\tif scale.LabelSelectorPath != nil {\n\t\t\tlabelSelectorPath = *scale.LabelSelectorPath\n\t\t}\n\n\t\tstorage.Scale = \u0026ScaleREST{\n\t\t\tstore: store,\n\t\t\tspecReplicasPath: scale.SpecReplicasPath,\n\t\t\tstatusReplicasPath: scale.StatusReplicasPath,\n\t\t\tlabelSelectorPath: labelSelectorPath,\n\t\t\tparentGV: kind.GroupVersion(),\n\t\t\treplicasPathMapping: replicasPathMapping,\n\t\t}\n\t}\n\n\treturn storage\n}","line":{"from":44,"to":101}} {"id":100014421,"name":"Categories","signature":"func (r *REST) Categories() []string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/etcd.go","code":"// Categories implements the CategoriesProvider interface. Returns a list of categories a resource is part of.\nfunc (r *REST) Categories() []string {\n\treturn r.categories\n}","line":{"from":112,"to":115}} {"id":100014422,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/etcd.go","code":"func (r *StatusREST) New() runtime.Object {\n\treturn r.store.New()\n}","line":{"from":124,"to":126}} {"id":100014423,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/etcd.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\to, err := r.store.Get(ctx, name, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn o, nil\n}","line":{"from":128,"to":135}} {"id":100014424,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/etcd.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":137,"to":142}} {"id":100014425,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/etcd.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":144,"to":147}} {"id":100014426,"name":"GroupVersionKind","signature":"func (r *ScaleREST) GroupVersionKind(containingGV schema.GroupVersion) schema.GroupVersionKind","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/etcd.go","code":"func (r *ScaleREST) GroupVersionKind(containingGV schema.GroupVersion) schema.GroupVersionKind {\n\treturn autoscalingv1.SchemeGroupVersion.WithKind(\"Scale\")\n}","line":{"from":162,"to":164}} {"id":100014427,"name":"New","signature":"func (r *ScaleREST) New() runtime.Object","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/etcd.go","code":"// New creates a new Scale object\nfunc (r *ScaleREST) New() runtime.Object {\n\treturn \u0026autoscalingv1.Scale{}\n}","line":{"from":166,"to":169}} {"id":100014428,"name":"Get","signature":"func (r *ScaleREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/etcd.go","code":"func (r *ScaleREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\tobj, err := r.store.Get(ctx, name, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcr := obj.(*unstructured.Unstructured)\n\n\tscaleObject, replicasFound, err := scaleFromCustomResource(cr, r.specReplicasPath, r.statusReplicasPath, r.labelSelectorPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !replicasFound {\n\t\treturn nil, apierrors.NewInternalError(fmt.Errorf(\"the spec replicas field %q does not exist\", r.specReplicasPath))\n\t}\n\treturn scaleObject, err\n}","line":{"from":171,"to":186}} {"id":100014429,"name":"Update","signature":"func (r *ScaleREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/etcd.go","code":"func (r *ScaleREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\tscaleObjInfo := \u0026scaleUpdatedObjectInfo{\n\t\treqObjInfo: objInfo,\n\t\tspecReplicasPath: r.specReplicasPath,\n\t\tlabelSelectorPath: r.labelSelectorPath,\n\t\tstatusReplicasPath: r.statusReplicasPath,\n\t\tparentGV: r.parentGV,\n\t\treplicasPathMapping: r.replicasPathMapping,\n\t}\n\n\tobj, _, err := r.store.Update(\n\t\tctx,\n\t\tname,\n\t\tscaleObjInfo,\n\t\ttoScaleCreateValidation(createValidation, r.specReplicasPath, r.statusReplicasPath, r.labelSelectorPath),\n\t\ttoScaleUpdateValidation(updateValidation, r.specReplicasPath, r.statusReplicasPath, r.labelSelectorPath),\n\t\tfalse,\n\t\toptions,\n\t)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\tcr := obj.(*unstructured.Unstructured)\n\n\tnewScale, _, err := scaleFromCustomResource(cr, r.specReplicasPath, r.statusReplicasPath, r.labelSelectorPath)\n\tif err != nil {\n\t\treturn nil, false, apierrors.NewBadRequest(err.Error())\n\t}\n\n\treturn newScale, false, err\n}","line":{"from":188,"to":218}} {"id":100014430,"name":"toScaleCreateValidation","signature":"func toScaleCreateValidation(f rest.ValidateObjectFunc, specReplicasPath, statusReplicasPath, labelSelectorPath string) rest.ValidateObjectFunc","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/etcd.go","code":"func toScaleCreateValidation(f rest.ValidateObjectFunc, specReplicasPath, statusReplicasPath, labelSelectorPath string) rest.ValidateObjectFunc {\n\treturn func(ctx context.Context, obj runtime.Object) error {\n\t\tscale, _, err := scaleFromCustomResource(obj.(*unstructured.Unstructured), specReplicasPath, statusReplicasPath, labelSelectorPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn f(ctx, scale)\n\t}\n}","line":{"from":220,"to":228}} {"id":100014431,"name":"toScaleUpdateValidation","signature":"func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc, specReplicasPath, statusReplicasPath, labelSelectorPath string) rest.ValidateObjectUpdateFunc","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/etcd.go","code":"func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc, specReplicasPath, statusReplicasPath, labelSelectorPath string) rest.ValidateObjectUpdateFunc {\n\treturn func(ctx context.Context, obj, old runtime.Object) error {\n\t\tnewScale, _, err := scaleFromCustomResource(obj.(*unstructured.Unstructured), specReplicasPath, statusReplicasPath, labelSelectorPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\toldScale, _, err := scaleFromCustomResource(old.(*unstructured.Unstructured), specReplicasPath, statusReplicasPath, labelSelectorPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn f(ctx, newScale, oldScale)\n\t}\n}","line":{"from":230,"to":242}} {"id":100014432,"name":"splitReplicasPath","signature":"func splitReplicasPath(replicasPath string) []string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/etcd.go","code":"// Split the path per period, ignoring the leading period.\nfunc splitReplicasPath(replicasPath string) []string {\n\treturn strings.Split(strings.TrimPrefix(replicasPath, \".\"), \".\")\n}","line":{"from":244,"to":247}} {"id":100014433,"name":"scaleFromCustomResource","signature":"func scaleFromCustomResource(cr *unstructured.Unstructured, specReplicasPath, statusReplicasPath, labelSelectorPath string) (*autoscalingv1.Scale, bool, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/etcd.go","code":"// scaleFromCustomResource returns a scale subresource for a customresource and a bool signalling wether\n// the specReplicas value was found.\nfunc scaleFromCustomResource(cr *unstructured.Unstructured, specReplicasPath, statusReplicasPath, labelSelectorPath string) (*autoscalingv1.Scale, bool, error) {\n\tspecReplicas, foundSpecReplicas, err := unstructured.NestedInt64(cr.UnstructuredContent(), splitReplicasPath(specReplicasPath)...)\n\tif err != nil {\n\t\treturn nil, false, err\n\t} else if !foundSpecReplicas {\n\t\tspecReplicas = 0\n\t}\n\n\tstatusReplicas, found, err := unstructured.NestedInt64(cr.UnstructuredContent(), splitReplicasPath(statusReplicasPath)...)\n\tif err != nil {\n\t\treturn nil, false, err\n\t} else if !found {\n\t\tstatusReplicas = 0\n\t}\n\n\tvar labelSelector string\n\tif len(labelSelectorPath) \u003e 0 {\n\t\tlabelSelector, _, err = unstructured.NestedString(cr.UnstructuredContent(), splitReplicasPath(labelSelectorPath)...)\n\t\tif err != nil {\n\t\t\treturn nil, false, err\n\t\t}\n\t}\n\n\tscale := \u0026autoscalingv1.Scale{\n\t\t// Populate apiVersion and kind so conversion recognizes we are already in the desired GVK and doesn't try to convert\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"autoscaling/v1\",\n\t\t\tKind: \"Scale\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cr.GetName(),\n\t\t\tNamespace: cr.GetNamespace(),\n\t\t\tUID: cr.GetUID(),\n\t\t\tResourceVersion: cr.GetResourceVersion(),\n\t\t\tCreationTimestamp: cr.GetCreationTimestamp(),\n\t\t},\n\t\tSpec: autoscalingv1.ScaleSpec{\n\t\t\tReplicas: int32(specReplicas),\n\t\t},\n\t\tStatus: autoscalingv1.ScaleStatus{\n\t\t\tReplicas: int32(statusReplicas),\n\t\t\tSelector: labelSelector,\n\t\t},\n\t}\n\n\treturn scale, foundSpecReplicas, nil\n}","line":{"from":249,"to":297}} {"id":100014434,"name":"Preconditions","signature":"func (i *scaleUpdatedObjectInfo) Preconditions() *metav1.Preconditions","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/etcd.go","code":"func (i *scaleUpdatedObjectInfo) Preconditions() *metav1.Preconditions {\n\treturn i.reqObjInfo.Preconditions()\n}","line":{"from":308,"to":310}} {"id":100014435,"name":"UpdatedObject","signature":"func (i *scaleUpdatedObjectInfo) UpdatedObject(ctx context.Context, oldObj runtime.Object) (runtime.Object, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/etcd.go","code":"func (i *scaleUpdatedObjectInfo) UpdatedObject(ctx context.Context, oldObj runtime.Object) (runtime.Object, error) {\n\tcr := oldObj.DeepCopyObject().(*unstructured.Unstructured)\n\tconst invalidSpecReplicas = -2147483648 // smallest int32\n\n\tmanagedFieldsHandler := managedfields.NewScaleHandler(\n\t\tcr.GetManagedFields(),\n\t\ti.parentGV,\n\t\ti.replicasPathMapping,\n\t)\n\n\toldScale, replicasFound, err := scaleFromCustomResource(cr, i.specReplicasPath, i.statusReplicasPath, i.labelSelectorPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !replicasFound {\n\t\toldScale.Spec.Replicas = invalidSpecReplicas // signal that this was not set before\n\t}\n\n\tscaleManagedFields, err := managedFieldsHandler.ToSubresource()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\toldScale.ManagedFields = scaleManagedFields\n\n\tobj, err := i.reqObjInfo.UpdatedObject(ctx, oldScale)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif obj == nil {\n\t\treturn nil, apierrors.NewBadRequest(fmt.Sprintf(\"nil update passed to Scale\"))\n\t}\n\n\tscale, ok := obj.(*autoscalingv1.Scale)\n\tif !ok {\n\t\treturn nil, apierrors.NewBadRequest(fmt.Sprintf(\"wrong object passed to Scale update: %v\", obj))\n\t}\n\n\tif scale.Spec.Replicas == invalidSpecReplicas {\n\t\treturn nil, apierrors.NewBadRequest(fmt.Sprintf(\"the spec replicas field %q cannot be empty\", i.specReplicasPath))\n\t}\n\n\tif err := unstructured.SetNestedField(cr.Object, int64(scale.Spec.Replicas), splitReplicasPath(i.specReplicasPath)...); err != nil {\n\t\treturn nil, err\n\t}\n\tif len(scale.ResourceVersion) != 0 {\n\t\t// The client provided a resourceVersion precondition.\n\t\t// Set that precondition and return any conflict errors to the client.\n\t\tcr.SetResourceVersion(scale.ResourceVersion)\n\t}\n\n\tupdatedEntries, err := managedFieldsHandler.ToParent(scale.ManagedFields)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcr.SetManagedFields(updatedEntries)\n\n\treturn cr, nil\n}","line":{"from":312,"to":369}} {"id":100014436,"name":"NewStatusStrategy","signature":"func NewStatusStrategy(strategy customResourceStrategy) statusStrategy","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/status_strategy.go","code":"func NewStatusStrategy(strategy customResourceStrategy) statusStrategy {\n\treturn statusStrategy{strategy}\n}","line":{"from":35,"to":37}} {"id":100014437,"name":"GetResetFields","signature":"func (a statusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/status_strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (a statusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\tfieldpath.APIVersion(a.customResourceStrategy.kind.GroupVersion().String()): fieldpath.NewSet(\n\t\t\t// Note that if there are other top level fields unique to CRDs,\n\t\t\t// those will also get removed by the apiserver prior to persisting,\n\t\t\t// but won't be added to the resetFields set.\n\n\t\t\t// This isn't an issue now, but if it becomes an issue in the future\n\t\t\t// we might need a mechanism that is the inverse of resetFields where\n\t\t\t// you specify only the fields to be kept rather than the fields to be wiped\n\t\t\t// that way you could wipe everything but the status in this case.\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":39,"to":57}} {"id":100014438,"name":"PrepareForUpdate","signature":"func (a statusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/status_strategy.go","code":"func (a statusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\t// update is only allowed to set status\n\tnewCustomResourceObject := obj.(*unstructured.Unstructured)\n\tnewCustomResource := newCustomResourceObject.UnstructuredContent()\n\tstatus, ok := newCustomResource[\"status\"]\n\n\t// managedFields must be preserved since it's been modified to\n\t// track changed fields in the status update.\n\tmanagedFields := newCustomResourceObject.GetManagedFields()\n\n\t// copy old object into new object\n\toldCustomResourceObject := old.(*unstructured.Unstructured)\n\t// overridding the resourceVersion in metadata is safe here, we have already checked that\n\t// new object and old object have the same resourceVersion.\n\t*newCustomResourceObject = *oldCustomResourceObject.DeepCopy()\n\n\t// set status\n\tnewCustomResourceObject.SetManagedFields(managedFields)\n\tnewCustomResource = newCustomResourceObject.UnstructuredContent()\n\tif ok {\n\t\tnewCustomResource[\"status\"] = status\n\t} else {\n\t\tdelete(newCustomResource, \"status\")\n\t}\n}","line":{"from":59,"to":83}} {"id":100014439,"name":"ValidateUpdate","signature":"func (a statusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/status_strategy.go","code":"// ValidateUpdate is the default update validation for an end user updating status.\nfunc (a statusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tvar errs field.ErrorList\n\terrs = append(errs, a.customResourceStrategy.validator.ValidateStatusUpdate(ctx, obj, old, a.scale)...)\n\n\tuNew, ok := obj.(*unstructured.Unstructured)\n\tif !ok {\n\t\treturn errs\n\t}\n\tuOld, ok := old.(*unstructured.Unstructured)\n\tvar oldObject map[string]interface{}\n\tif !ok {\n\t\toldObject = nil\n\t} else {\n\t\toldObject = uOld.Object\n\t}\n\n\tv := obj.GetObjectKind().GroupVersionKind().Version\n\n\t// ratcheting validation of x-kubernetes-list-type value map and set\n\tif newErrs := structurallisttype.ValidateListSetsAndMaps(nil, a.structuralSchemas[v], uNew.Object); len(newErrs) \u003e 0 {\n\t\tif oldErrs := structurallisttype.ValidateListSetsAndMaps(nil, a.structuralSchemas[v], oldObject); len(oldErrs) == 0 {\n\t\t\terrs = append(errs, newErrs...)\n\t\t}\n\t}\n\n\t// validate x-kubernetes-validations rules\n\tif celValidator, ok := a.customResourceStrategy.celValidators[v]; ok {\n\t\tif has, err := hasBlockingErr(errs); has {\n\t\t\terrs = append(errs, err)\n\t\t} else {\n\t\t\terr, _ := celValidator.Validate(ctx, nil, a.customResourceStrategy.structuralSchemas[v], uNew.Object, oldObject, celconfig.RuntimeCELCostBudget)\n\t\t\terrs = append(errs, err...)\n\t\t}\n\t}\n\treturn errs\n}","line":{"from":85,"to":121}} {"id":100014440,"name":"WarningsOnUpdate","signature":"func (statusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/status_strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (statusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":123,"to":126}} {"id":100014441,"name":"NewStrategy","signature":"func NewStrategy(typer runtime.ObjectTyper, namespaceScoped bool, kind schema.GroupVersionKind, schemaValidator, statusSchemaValidator *validate.SchemaValidator, structuralSchemas map[string]*structuralschema.Structural, status *apiextensions.CustomResourceSubresourceStatus, scale *apiextensions.CustomResourceSubresourceScale) customResourceStrategy","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/strategy.go","code":"func NewStrategy(typer runtime.ObjectTyper, namespaceScoped bool, kind schema.GroupVersionKind, schemaValidator, statusSchemaValidator *validate.SchemaValidator, structuralSchemas map[string]*structuralschema.Structural, status *apiextensions.CustomResourceSubresourceStatus, scale *apiextensions.CustomResourceSubresourceScale) customResourceStrategy {\n\tcelValidators := map[string]*cel.Validator{}\n\tif utilfeature.DefaultFeatureGate.Enabled(features.CustomResourceValidationExpressions) {\n\t\tfor name, s := range structuralSchemas {\n\t\t\tv := cel.NewValidator(s, true, celconfig.PerCallLimit) // CEL programs are compiled and cached here\n\t\t\tif v != nil {\n\t\t\t\tcelValidators[name] = v\n\t\t\t}\n\t\t}\n\t}\n\n\treturn customResourceStrategy{\n\t\tObjectTyper: typer,\n\t\tNameGenerator: names.SimpleNameGenerator,\n\t\tnamespaceScoped: namespaceScoped,\n\t\tstatus: status,\n\t\tscale: scale,\n\t\tvalidator: customResourceValidator{\n\t\t\tnamespaceScoped: namespaceScoped,\n\t\t\tkind: kind,\n\t\t\tschemaValidator: schemaValidator,\n\t\t\tstatusSchemaValidator: statusSchemaValidator,\n\t\t},\n\t\tstructuralSchemas: structuralSchemas,\n\t\tcelValidators: celValidators,\n\t\tkind: kind,\n\t}\n}","line":{"from":61,"to":88}} {"id":100014442,"name":"NamespaceScoped","signature":"func (a customResourceStrategy) NamespaceScoped() bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/strategy.go","code":"func (a customResourceStrategy) NamespaceScoped() bool {\n\treturn a.namespaceScoped\n}","line":{"from":90,"to":92}} {"id":100014443,"name":"GetResetFields","signature":"func (a customResourceStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (a customResourceStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{}\n\n\tif a.status != nil {\n\t\tfields[fieldpath.APIVersion(a.kind.GroupVersion().String())] = fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t)\n\t}\n\n\treturn fields\n}","line":{"from":94,"to":106}} {"id":100014444,"name":"PrepareForCreate","signature":"func (a customResourceStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/strategy.go","code":"// PrepareForCreate clears the status of a CustomResource before creation.\nfunc (a customResourceStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tif a.status != nil {\n\t\tcustomResourceObject := obj.(*unstructured.Unstructured)\n\t\tcustomResource := customResourceObject.UnstructuredContent()\n\n\t\t// create cannot set status\n\t\tdelete(customResource, \"status\")\n\t}\n\n\taccessor, _ := meta.Accessor(obj)\n\taccessor.SetGeneration(1)\n}","line":{"from":108,"to":120}} {"id":100014445,"name":"PrepareForUpdate","signature":"func (a customResourceStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (a customResourceStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewCustomResourceObject := obj.(*unstructured.Unstructured)\n\toldCustomResourceObject := old.(*unstructured.Unstructured)\n\n\tnewCustomResource := newCustomResourceObject.UnstructuredContent()\n\toldCustomResource := oldCustomResourceObject.UnstructuredContent()\n\n\t// If the /status subresource endpoint is installed, update is not allowed to set status.\n\tif a.status != nil {\n\t\t_, ok1 := newCustomResource[\"status\"]\n\t\t_, ok2 := oldCustomResource[\"status\"]\n\t\tswitch {\n\t\tcase ok2:\n\t\t\tnewCustomResource[\"status\"] = oldCustomResource[\"status\"]\n\t\tcase ok1:\n\t\t\tdelete(newCustomResource, \"status\")\n\t\t}\n\t}\n\n\t// except for the changes to `metadata`, any other changes\n\t// cause the generation to increment.\n\tnewCopyContent := copyNonMetadata(newCustomResource)\n\toldCopyContent := copyNonMetadata(oldCustomResource)\n\tif !apiequality.Semantic.DeepEqual(newCopyContent, oldCopyContent) {\n\t\toldAccessor, _ := meta.Accessor(oldCustomResourceObject)\n\t\tnewAccessor, _ := meta.Accessor(newCustomResourceObject)\n\t\tnewAccessor.SetGeneration(oldAccessor.GetGeneration() + 1)\n\t}\n}","line":{"from":122,"to":151}} {"id":100014446,"name":"copyNonMetadata","signature":"func copyNonMetadata(original map[string]interface{}) map[string]interface{}","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/strategy.go","code":"func copyNonMetadata(original map[string]interface{}) map[string]interface{} {\n\tret := make(map[string]interface{})\n\tfor key, val := range original {\n\t\tif key == \"metadata\" {\n\t\t\tcontinue\n\t\t}\n\t\tret[key] = val\n\t}\n\treturn ret\n}","line":{"from":153,"to":162}} {"id":100014447,"name":"Validate","signature":"func (a customResourceStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/strategy.go","code":"// Validate validates a new CustomResource.\nfunc (a customResourceStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\tvar errs field.ErrorList\n\terrs = append(errs, a.validator.Validate(ctx, obj, a.scale)...)\n\n\t// validate embedded resources\n\tif u, ok := obj.(*unstructured.Unstructured); ok {\n\t\tv := obj.GetObjectKind().GroupVersionKind().Version\n\t\terrs = append(errs, schemaobjectmeta.Validate(nil, u.Object, a.structuralSchemas[v], false)...)\n\n\t\t// validate x-kubernetes-list-type \"map\" and \"set\" invariant\n\t\terrs = append(errs, structurallisttype.ValidateListSetsAndMaps(nil, a.structuralSchemas[v], u.Object)...)\n\n\t\t// validate x-kubernetes-validations rules\n\t\tif celValidator, ok := a.celValidators[v]; ok {\n\t\t\tif has, err := hasBlockingErr(errs); has {\n\t\t\t\terrs = append(errs, err)\n\t\t\t} else {\n\t\t\t\terr, _ := celValidator.Validate(ctx, nil, a.structuralSchemas[v], u.Object, nil, celconfig.RuntimeCELCostBudget)\n\t\t\t\terrs = append(errs, err...)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn errs\n}","line":{"from":164,"to":189}} {"id":100014448,"name":"WarningsOnCreate","signature":"func (customResourceStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (customResourceStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":191,"to":194}} {"id":100014449,"name":"Canonicalize","signature":"func (customResourceStrategy) Canonicalize(obj runtime.Object)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (customResourceStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":196,"to":198}} {"id":100014450,"name":"AllowCreateOnUpdate","signature":"func (customResourceStrategy) AllowCreateOnUpdate() bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/strategy.go","code":"// AllowCreateOnUpdate is false for CustomResources; this means a POST is\n// needed to create one.\nfunc (customResourceStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":200,"to":204}} {"id":100014451,"name":"AllowUnconditionalUpdate","signature":"func (customResourceStrategy) AllowUnconditionalUpdate() bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/strategy.go","code":"// AllowUnconditionalUpdate is the default update policy for CustomResource objects.\nfunc (customResourceStrategy) AllowUnconditionalUpdate() bool {\n\treturn false\n}","line":{"from":206,"to":209}} {"id":100014452,"name":"ValidateUpdate","signature":"func (a customResourceStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/strategy.go","code":"// ValidateUpdate is the default update validation for an end user updating status.\nfunc (a customResourceStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tvar errs field.ErrorList\n\terrs = append(errs, a.validator.ValidateUpdate(ctx, obj, old, a.scale)...)\n\n\tuNew, ok := obj.(*unstructured.Unstructured)\n\tif !ok {\n\t\treturn errs\n\t}\n\tuOld, ok := old.(*unstructured.Unstructured)\n\tif !ok {\n\t\treturn errs\n\t}\n\n\t// Checks the embedded objects. We don't make a difference between update and create for those.\n\tv := obj.GetObjectKind().GroupVersionKind().Version\n\terrs = append(errs, schemaobjectmeta.Validate(nil, uNew.Object, a.structuralSchemas[v], false)...)\n\n\t// ratcheting validation of x-kubernetes-list-type value map and set\n\tif oldErrs := structurallisttype.ValidateListSetsAndMaps(nil, a.structuralSchemas[v], uOld.Object); len(oldErrs) == 0 {\n\t\terrs = append(errs, structurallisttype.ValidateListSetsAndMaps(nil, a.structuralSchemas[v], uNew.Object)...)\n\t}\n\n\t// validate x-kubernetes-validations rules\n\tif celValidator, ok := a.celValidators[v]; ok {\n\t\tif has, err := hasBlockingErr(errs); has {\n\t\t\terrs = append(errs, err)\n\t\t} else {\n\t\t\terr, _ := celValidator.Validate(ctx, nil, a.structuralSchemas[v], uNew.Object, uOld.Object, celconfig.RuntimeCELCostBudget)\n\t\t\terrs = append(errs, err...)\n\t\t}\n\t}\n\n\treturn errs\n}","line":{"from":211,"to":245}} {"id":100014453,"name":"WarningsOnUpdate","signature":"func (customResourceStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (customResourceStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":247,"to":250}} {"id":100014454,"name":"GetAttrs","signature":"func (a customResourceStrategy) GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/strategy.go","code":"// GetAttrs returns labels and fields of a given object for filtering purposes.\nfunc (a customResourceStrategy) GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn labels.Set(accessor.GetLabels()), objectMetaFieldsSet(accessor, a.namespaceScoped), nil\n}","line":{"from":252,"to":259}} {"id":100014455,"name":"objectMetaFieldsSet","signature":"func objectMetaFieldsSet(objectMeta metav1.Object, namespaceScoped bool) fields.Set","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/strategy.go","code":"// objectMetaFieldsSet returns a fields that represent the ObjectMeta.\nfunc objectMetaFieldsSet(objectMeta metav1.Object, namespaceScoped bool) fields.Set {\n\tif namespaceScoped {\n\t\treturn fields.Set{\n\t\t\t\"metadata.name\": objectMeta.GetName(),\n\t\t\t\"metadata.namespace\": objectMeta.GetNamespace(),\n\t\t}\n\t}\n\treturn fields.Set{\n\t\t\"metadata.name\": objectMeta.GetName(),\n\t}\n}","line":{"from":261,"to":272}} {"id":100014456,"name":"MatchCustomResourceDefinitionStorage","signature":"func (a customResourceStrategy) MatchCustomResourceDefinitionStorage(label labels.Selector, field fields.Selector) apiserverstorage.SelectionPredicate","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/strategy.go","code":"// MatchCustomResourceDefinitionStorage is the filter used by the generic etcd backend to route\n// watch events from etcd to clients of the apiserver only interested in specific\n// labels/fields.\nfunc (a customResourceStrategy) MatchCustomResourceDefinitionStorage(label labels.Selector, field fields.Selector) apiserverstorage.SelectionPredicate {\n\treturn apiserverstorage.SelectionPredicate{\n\t\tLabel: label,\n\t\tField: field,\n\t\tGetAttrs: a.GetAttrs,\n\t}\n}","line":{"from":274,"to":283}} {"id":100014457,"name":"hasBlockingErr","signature":"func hasBlockingErr(errs field.ErrorList) (bool, *field.Error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/strategy.go","code":"// OpenAPIv3 type/maxLength/maxItems/MaxProperties/required/wrong type field validation failures are viewed as blocking err for CEL validation\nfunc hasBlockingErr(errs field.ErrorList) (bool, *field.Error) {\n\tfor _, err := range errs {\n\t\tif err.Type == field.ErrorTypeRequired || err.Type == field.ErrorTypeTooLong || err.Type == field.ErrorTypeTooMany || err.Type == field.ErrorTypeTypeInvalid {\n\t\t\treturn true, field.Invalid(nil, nil, \"some validation rules were not checked because the object was invalid; correct the existing errors to complete validation\")\n\t\t}\n\t}\n\treturn false, nil\n}","line":{"from":285,"to":293}} {"id":100014458,"name":"New","signature":"func New(crdColumns []apiextensionsv1.CustomResourceColumnDefinition) (rest.TableConvertor, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/tableconvertor/tableconvertor.go","code":"// New creates a new table convertor for the provided CRD column definition. If the printer definition cannot be parsed,\n// error will be returned along with a default table convertor.\nfunc New(crdColumns []apiextensionsv1.CustomResourceColumnDefinition) (rest.TableConvertor, error) {\n\theaders := []metav1.TableColumnDefinition{\n\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: swaggerMetadataDescriptions[\"name\"]},\n\t}\n\tc := \u0026convertor{\n\t\theaders: headers,\n\t}\n\n\tfor _, col := range crdColumns {\n\t\tpath := jsonpath.New(col.Name)\n\t\tif err := path.Parse(fmt.Sprintf(\"{%s}\", col.JSONPath)); err != nil {\n\t\t\treturn c, fmt.Errorf(\"unrecognized column definition %q\", col.JSONPath)\n\t\t}\n\t\tpath.AllowMissingKeys(true)\n\n\t\tdesc := fmt.Sprintf(\"Custom resource definition column (in JSONPath format): %s\", col.JSONPath)\n\t\tif len(col.Description) \u003e 0 {\n\t\t\tdesc = col.Description\n\t\t}\n\n\t\tc.additionalColumns = append(c.additionalColumns, path)\n\t\tc.headers = append(c.headers, metav1.TableColumnDefinition{\n\t\t\tName: col.Name,\n\t\t\tType: col.Type,\n\t\t\tFormat: col.Format,\n\t\t\tDescription: desc,\n\t\t\tPriority: col.Priority,\n\t\t})\n\t}\n\n\treturn c, nil\n}","line":{"from":39,"to":72}} {"id":100014459,"name":"ConvertToTable","signature":"func (c *convertor) ConvertToTable(ctx context.Context, obj runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/tableconvertor/tableconvertor.go","code":"func (c *convertor) ConvertToTable(ctx context.Context, obj runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\ttable := \u0026metav1.Table{}\n\topt, ok := tableOptions.(*metav1.TableOptions)\n\tnoHeaders := ok \u0026\u0026 opt != nil \u0026\u0026 opt.NoHeaders\n\tif !noHeaders {\n\t\ttable.ColumnDefinitions = c.headers\n\t}\n\n\tif m, err := meta.ListAccessor(obj); err == nil {\n\t\ttable.ResourceVersion = m.GetResourceVersion()\n\t\ttable.Continue = m.GetContinue()\n\t\ttable.RemainingItemCount = m.GetRemainingItemCount()\n\t} else {\n\t\tif m, err := meta.CommonAccessor(obj); err == nil {\n\t\t\ttable.ResourceVersion = m.GetResourceVersion()\n\t\t}\n\t}\n\n\tvar err error\n\tbuf := \u0026bytes.Buffer{}\n\ttable.Rows, err = metatable.MetaToTableRow(obj, func(obj runtime.Object, m metav1.Object, name, age string) ([]interface{}, error) {\n\t\tcells := make([]interface{}, 1, 1+len(c.additionalColumns))\n\t\tcells[0] = name\n\t\tcustomHeaders := c.headers[1:]\n\t\tus, ok := obj.(runtime.Unstructured)\n\t\tif !ok {\n\t\t\tm, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tus = \u0026unstructured.Unstructured{Object: m}\n\t\t}\n\t\tfor i, column := range c.additionalColumns {\n\t\t\tresults, err := column.FindResults(us.UnstructuredContent())\n\t\t\tif err != nil || len(results) == 0 || len(results[0]) == 0 {\n\t\t\t\tcells = append(cells, nil)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// as we only support simple JSON path, we can assume to have only one result (or none, filtered out above)\n\t\t\tvalue := results[0][0].Interface()\n\t\t\tif customHeaders[i].Type == \"string\" {\n\t\t\t\tif err := column.PrintResults(buf, []reflect.Value{reflect.ValueOf(value)}); err == nil {\n\t\t\t\t\tcells = append(cells, buf.String())\n\t\t\t\t\tbuf.Reset()\n\t\t\t\t} else {\n\t\t\t\t\tcells = append(cells, nil)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcells = append(cells, cellForJSONValue(customHeaders[i].Type, value))\n\t\t\t}\n\t\t}\n\t\treturn cells, nil\n\t})\n\treturn table, err\n}","line":{"from":84,"to":139}} {"id":100014460,"name":"cellForJSONValue","signature":"func cellForJSONValue(headerType string, value interface{}) interface{}","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/tableconvertor/tableconvertor.go","code":"func cellForJSONValue(headerType string, value interface{}) interface{} {\n\tif value == nil {\n\t\treturn nil\n\t}\n\n\tswitch headerType {\n\tcase \"integer\":\n\t\tswitch typed := value.(type) {\n\t\tcase int64:\n\t\t\treturn typed\n\t\tcase float64:\n\t\t\treturn int64(typed)\n\t\tcase json.Number:\n\t\t\tif i64, err := typed.Int64(); err == nil {\n\t\t\t\treturn i64\n\t\t\t}\n\t\t}\n\tcase \"number\":\n\t\tswitch typed := value.(type) {\n\t\tcase int64:\n\t\t\treturn float64(typed)\n\t\tcase float64:\n\t\t\treturn typed\n\t\tcase json.Number:\n\t\t\tif f, err := typed.Float64(); err == nil {\n\t\t\t\treturn f\n\t\t\t}\n\t\t}\n\tcase \"boolean\":\n\t\tif b, ok := value.(bool); ok {\n\t\t\treturn b\n\t\t}\n\tcase \"string\":\n\t\tif s, ok := value.(string); ok {\n\t\t\treturn s\n\t\t}\n\tcase \"date\":\n\t\tif typed, ok := value.(string); ok {\n\t\t\tvar timestamp metav1.Time\n\t\t\terr := timestamp.UnmarshalQueryParameter(typed)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\u003cinvalid\u003e\"\n\t\t\t}\n\t\t\treturn metatable.ConvertToHumanReadableDateType(timestamp)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":141,"to":189}} {"id":100014461,"name":"Validate","signature":"func (a customResourceValidator) Validate(ctx context.Context, obj runtime.Object, scale *apiextensions.CustomResourceSubresourceScale) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/validator.go","code":"func (a customResourceValidator) Validate(ctx context.Context, obj runtime.Object, scale *apiextensions.CustomResourceSubresourceScale) field.ErrorList {\n\tu, ok := obj.(*unstructured.Unstructured)\n\tif !ok {\n\t\treturn field.ErrorList{field.Invalid(field.NewPath(\"\"), u, fmt.Sprintf(\"has type %T. Must be a pointer to an Unstructured type\", u))}\n\t}\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn field.ErrorList{field.Invalid(field.NewPath(\"metadata\"), nil, err.Error())}\n\t}\n\n\tif errs := a.ValidateTypeMeta(ctx, u); len(errs) \u003e 0 {\n\t\treturn errs\n\t}\n\n\tvar allErrs field.ErrorList\n\n\tallErrs = append(allErrs, validation.ValidateObjectMetaAccessor(accessor, a.namespaceScoped, validation.NameIsDNSSubdomain, field.NewPath(\"metadata\"))...)\n\tallErrs = append(allErrs, apiservervalidation.ValidateCustomResource(nil, u.UnstructuredContent(), a.schemaValidator)...)\n\tallErrs = append(allErrs, a.ValidateScaleSpec(ctx, u, scale)...)\n\tallErrs = append(allErrs, a.ValidateScaleStatus(ctx, u, scale)...)\n\n\treturn allErrs\n}","line":{"from":44,"to":66}} {"id":100014462,"name":"ValidateUpdate","signature":"func (a customResourceValidator) ValidateUpdate(ctx context.Context, obj, old runtime.Object, scale *apiextensions.CustomResourceSubresourceScale) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/validator.go","code":"func (a customResourceValidator) ValidateUpdate(ctx context.Context, obj, old runtime.Object, scale *apiextensions.CustomResourceSubresourceScale) field.ErrorList {\n\tu, ok := obj.(*unstructured.Unstructured)\n\tif !ok {\n\t\treturn field.ErrorList{field.Invalid(field.NewPath(\"\"), u, fmt.Sprintf(\"has type %T. Must be a pointer to an Unstructured type\", u))}\n\t}\n\tobjAccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn field.ErrorList{field.Invalid(field.NewPath(\"metadata\"), nil, err.Error())}\n\t}\n\toldAccessor, err := meta.Accessor(old)\n\tif err != nil {\n\t\treturn field.ErrorList{field.Invalid(field.NewPath(\"metadata\"), nil, err.Error())}\n\t}\n\n\tif errs := a.ValidateTypeMeta(ctx, u); len(errs) \u003e 0 {\n\t\treturn errs\n\t}\n\n\tvar allErrs field.ErrorList\n\n\tallErrs = append(allErrs, validation.ValidateObjectMetaAccessorUpdate(objAccessor, oldAccessor, field.NewPath(\"metadata\"))...)\n\tallErrs = append(allErrs, apiservervalidation.ValidateCustomResource(nil, u.UnstructuredContent(), a.schemaValidator)...)\n\tallErrs = append(allErrs, a.ValidateScaleSpec(ctx, u, scale)...)\n\tallErrs = append(allErrs, a.ValidateScaleStatus(ctx, u, scale)...)\n\n\treturn allErrs\n}","line":{"from":68,"to":94}} {"id":100014463,"name":"WarningsOnUpdate","signature":"func (customResourceValidator) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/validator.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (customResourceValidator) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":96,"to":99}} {"id":100014464,"name":"ValidateStatusUpdate","signature":"func (a customResourceValidator) ValidateStatusUpdate(ctx context.Context, obj, old runtime.Object, scale *apiextensions.CustomResourceSubresourceScale) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/validator.go","code":"func (a customResourceValidator) ValidateStatusUpdate(ctx context.Context, obj, old runtime.Object, scale *apiextensions.CustomResourceSubresourceScale) field.ErrorList {\n\tu, ok := obj.(*unstructured.Unstructured)\n\tif !ok {\n\t\treturn field.ErrorList{field.Invalid(field.NewPath(\"\"), u, fmt.Sprintf(\"has type %T. Must be a pointer to an Unstructured type\", u))}\n\t}\n\tobjAccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn field.ErrorList{field.Invalid(field.NewPath(\"metadata\"), nil, err.Error())}\n\t}\n\toldAccessor, err := meta.Accessor(old)\n\tif err != nil {\n\t\treturn field.ErrorList{field.Invalid(field.NewPath(\"metadata\"), nil, err.Error())}\n\t}\n\n\tif errs := a.ValidateTypeMeta(ctx, u); len(errs) \u003e 0 {\n\t\treturn errs\n\t}\n\n\tvar allErrs field.ErrorList\n\n\tallErrs = append(allErrs, validation.ValidateObjectMetaAccessorUpdate(objAccessor, oldAccessor, field.NewPath(\"metadata\"))...)\n\tallErrs = append(allErrs, apiservervalidation.ValidateCustomResource(nil, u.UnstructuredContent(), a.schemaValidator)...)\n\tallErrs = append(allErrs, a.ValidateScaleStatus(ctx, u, scale)...)\n\n\treturn allErrs\n}","line":{"from":101,"to":126}} {"id":100014465,"name":"ValidateTypeMeta","signature":"func (a customResourceValidator) ValidateTypeMeta(ctx context.Context, obj *unstructured.Unstructured) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/validator.go","code":"func (a customResourceValidator) ValidateTypeMeta(ctx context.Context, obj *unstructured.Unstructured) field.ErrorList {\n\ttypeAccessor, err := meta.TypeAccessor(obj)\n\tif err != nil {\n\t\treturn field.ErrorList{field.Invalid(field.NewPath(\"kind\"), nil, err.Error())}\n\t}\n\n\tvar allErrs field.ErrorList\n\tif typeAccessor.GetKind() != a.kind.Kind {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"kind\"), typeAccessor.GetKind(), fmt.Sprintf(\"must be %v\", a.kind.Kind)))\n\t}\n\tif typeAccessor.GetAPIVersion() != a.kind.Group+\"/\"+a.kind.Version {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"apiVersion\"), typeAccessor.GetAPIVersion(), fmt.Sprintf(\"must be %v\", a.kind.Group+\"/\"+a.kind.Version)))\n\t}\n\treturn allErrs\n}","line":{"from":128,"to":142}} {"id":100014466,"name":"ValidateScaleSpec","signature":"func (a customResourceValidator) ValidateScaleSpec(ctx context.Context, obj *unstructured.Unstructured, scale *apiextensions.CustomResourceSubresourceScale) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/validator.go","code":"func (a customResourceValidator) ValidateScaleSpec(ctx context.Context, obj *unstructured.Unstructured, scale *apiextensions.CustomResourceSubresourceScale) field.ErrorList {\n\tif scale == nil {\n\t\treturn nil\n\t}\n\n\tvar allErrs field.ErrorList\n\n\t// validate specReplicas\n\tspecReplicasPath := strings.TrimPrefix(scale.SpecReplicasPath, \".\") // ignore leading period\n\tspecReplicas, _, err := unstructured.NestedInt64(obj.UnstructuredContent(), strings.Split(specReplicasPath, \".\")...)\n\tif err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(scale.SpecReplicasPath), specReplicas, err.Error()))\n\t} else if specReplicas \u003c 0 {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(scale.SpecReplicasPath), specReplicas, \"should be a non-negative integer\"))\n\t} else if specReplicas \u003e math.MaxInt32 {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(scale.SpecReplicasPath), specReplicas, fmt.Sprintf(\"should be less than or equal to %v\", math.MaxInt32)))\n\t}\n\n\treturn allErrs\n}","line":{"from":144,"to":163}} {"id":100014467,"name":"ValidateScaleStatus","signature":"func (a customResourceValidator) ValidateScaleStatus(ctx context.Context, obj *unstructured.Unstructured, scale *apiextensions.CustomResourceSubresourceScale) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/validator.go","code":"func (a customResourceValidator) ValidateScaleStatus(ctx context.Context, obj *unstructured.Unstructured, scale *apiextensions.CustomResourceSubresourceScale) field.ErrorList {\n\tif scale == nil {\n\t\treturn nil\n\t}\n\n\tvar allErrs field.ErrorList\n\n\t// validate statusReplicas\n\tstatusReplicasPath := strings.TrimPrefix(scale.StatusReplicasPath, \".\") // ignore leading period\n\tstatusReplicas, _, err := unstructured.NestedInt64(obj.UnstructuredContent(), strings.Split(statusReplicasPath, \".\")...)\n\tif err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(scale.StatusReplicasPath), statusReplicas, err.Error()))\n\t} else if statusReplicas \u003c 0 {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(scale.StatusReplicasPath), statusReplicas, \"should be a non-negative integer\"))\n\t} else if statusReplicas \u003e math.MaxInt32 {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(scale.StatusReplicasPath), statusReplicas, fmt.Sprintf(\"should be less than or equal to %v\", math.MaxInt32)))\n\t}\n\n\t// validate labelSelector\n\tif scale.LabelSelectorPath != nil {\n\t\tlabelSelectorPath := strings.TrimPrefix(*scale.LabelSelectorPath, \".\") // ignore leading period\n\t\tlabelSelector, _, err := unstructured.NestedString(obj.UnstructuredContent(), strings.Split(labelSelectorPath, \".\")...)\n\t\tif err != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(*scale.LabelSelectorPath), labelSelector, err.Error()))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":165,"to":193}} {"id":100014468,"name":"NewREST","signature":"func NewREST(scheme *runtime.Scheme, optsGetter generic.RESTOptionsGetter) (*REST, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/etcd.go","code":"// NewREST returns a RESTStorage object that will work against API services.\nfunc NewREST(scheme *runtime.Scheme, optsGetter generic.RESTOptionsGetter) (*REST, error) {\n\tstrategy := NewStrategy(scheme)\n\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026apiextensions.CustomResourceDefinition{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026apiextensions.CustomResourceDefinitionList{} },\n\t\tPredicateFunc: MatchCustomResourceDefinition,\n\t\tDefaultQualifiedResource: apiextensions.Resource(\"customresourcedefinitions\"),\n\t\tSingularQualifiedResource: apiextensions.Resource(\"customresourcedefinition\"),\n\n\t\tCreateStrategy: strategy,\n\t\tUpdateStrategy: strategy,\n\t\tDeleteStrategy: strategy,\n\t\tResetFieldsStrategy: strategy,\n\n\t\t// TODO: define table converter that exposes more than name/creation timestamp\n\t\tTableConvertor: rest.NewDefaultTableConvertor(apiextensions.Resource(\"customresourcedefinitions\")),\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: GetAttrs}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026REST{store}, nil\n}","line":{"from":41,"to":65}} {"id":100014469,"name":"ShortNames","signature":"func (r *REST) ShortNames() []string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/etcd.go","code":"// ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"crd\", \"crds\"}\n}","line":{"from":70,"to":73}} {"id":100014470,"name":"Categories","signature":"func (r *REST) Categories() []string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/etcd.go","code":"// Categories implements the CategoriesProvider interface. Returns a list of categories a resource is part of.\nfunc (r *REST) Categories() []string {\n\treturn []string{\"api-extensions\"}\n}","line":{"from":78,"to":81}} {"id":100014471,"name":"Delete","signature":"func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions) (runtime.Object, bool, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/etcd.go","code":"// Delete adds the CRD finalizer to the list\nfunc (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions) (runtime.Object, bool, error) {\n\tobj, err := r.Get(ctx, name, \u0026metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\tcrd := obj.(*apiextensions.CustomResourceDefinition)\n\n\t// Ensure we have a UID precondition\n\tif options == nil {\n\t\toptions = metav1.NewDeleteOptions(0)\n\t}\n\tif options.Preconditions == nil {\n\t\toptions.Preconditions = \u0026metav1.Preconditions{}\n\t}\n\tif options.Preconditions.UID == nil {\n\t\toptions.Preconditions.UID = \u0026crd.UID\n\t} else if *options.Preconditions.UID != crd.UID {\n\t\terr = apierrors.NewConflict(\n\t\t\tapiextensions.Resource(\"customresourcedefinitions\"),\n\t\t\tname,\n\t\t\tfmt.Errorf(\"Precondition failed: UID in precondition: %v, UID in object meta: %v\", *options.Preconditions.UID, crd.UID),\n\t\t)\n\t\treturn nil, false, err\n\t}\n\tif options.Preconditions.ResourceVersion != nil \u0026\u0026 *options.Preconditions.ResourceVersion != crd.ResourceVersion {\n\t\terr = apierrors.NewConflict(\n\t\t\tapiextensions.Resource(\"customresourcedefinitions\"),\n\t\t\tname,\n\t\t\tfmt.Errorf(\"Precondition failed: ResourceVersion in precondition: %v, ResourceVersion in object meta: %v\", *options.Preconditions.ResourceVersion, crd.ResourceVersion),\n\t\t)\n\t\treturn nil, false, err\n\t}\n\n\t// upon first request to delete, add our finalizer and then delegate\n\tif crd.DeletionTimestamp.IsZero() {\n\t\tkey, err := r.Store.KeyFunc(ctx, name)\n\t\tif err != nil {\n\t\t\treturn nil, false, err\n\t\t}\n\n\t\tpreconditions := storage.Preconditions{UID: options.Preconditions.UID, ResourceVersion: options.Preconditions.ResourceVersion}\n\n\t\tout := r.Store.NewFunc()\n\t\terr = r.Store.Storage.GuaranteedUpdate(\n\t\t\tctx, key, out, false, \u0026preconditions,\n\t\t\tstorage.SimpleUpdate(func(existing runtime.Object) (runtime.Object, error) {\n\t\t\t\texistingCRD, ok := existing.(*apiextensions.CustomResourceDefinition)\n\t\t\t\tif !ok {\n\t\t\t\t\t// wrong type\n\t\t\t\t\treturn nil, fmt.Errorf(\"expected *apiextensions.CustomResourceDefinition, got %v\", existing)\n\t\t\t\t}\n\t\t\t\tif err := deleteValidation(ctx, existingCRD); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\t// Set the deletion timestamp if needed\n\t\t\t\tif existingCRD.DeletionTimestamp.IsZero() {\n\t\t\t\t\tnow := metav1.Now()\n\t\t\t\t\texistingCRD.DeletionTimestamp = \u0026now\n\t\t\t\t}\n\n\t\t\t\tif !apiextensions.CRDHasFinalizer(existingCRD, apiextensions.CustomResourceCleanupFinalizer) {\n\t\t\t\t\texistingCRD.Finalizers = append(existingCRD.Finalizers, apiextensions.CustomResourceCleanupFinalizer)\n\t\t\t\t}\n\t\t\t\t// update the status condition too\n\t\t\t\tapiextensions.SetCRDCondition(existingCRD, apiextensions.CustomResourceDefinitionCondition{\n\t\t\t\t\tType: apiextensions.Terminating,\n\t\t\t\t\tStatus: apiextensions.ConditionTrue,\n\t\t\t\t\tReason: \"InstanceDeletionPending\",\n\t\t\t\t\tMessage: \"CustomResourceDefinition marked for deletion; CustomResource deletion will begin soon\",\n\t\t\t\t})\n\t\t\t\treturn existingCRD, nil\n\t\t\t}),\n\t\t\tdryrun.IsDryRun(options.DryRun),\n\t\t\tnil,\n\t\t)\n\n\t\tif err != nil {\n\t\t\terr = storageerr.InterpretGetError(err, apiextensions.Resource(\"customresourcedefinitions\"), name)\n\t\t\terr = storageerr.InterpretUpdateError(err, apiextensions.Resource(\"customresourcedefinitions\"), name)\n\t\t\tif _, ok := err.(*apierrors.StatusError); !ok {\n\t\t\t\terr = apierrors.NewInternalError(err)\n\t\t\t}\n\t\t\treturn nil, false, err\n\t\t}\n\n\t\treturn out, false, nil\n\t}\n\n\treturn r.Store.Delete(ctx, name, deleteValidation, options)\n}","line":{"from":83,"to":175}} {"id":100014472,"name":"NewStatusREST","signature":"func NewStatusREST(scheme *runtime.Scheme, rest *REST) *StatusREST","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/etcd.go","code":"// NewStatusREST makes a RESTStorage for status that has more limited options.\n// It is based on the original REST so that we can share the same underlying store\nfunc NewStatusREST(scheme *runtime.Scheme, rest *REST) *StatusREST {\n\tstatusStore := *rest.Store\n\tstatusStore.CreateStrategy = nil\n\tstatusStore.DeleteStrategy = nil\n\tstatusStrategy := NewStatusStrategy(scheme)\n\tstatusStore.UpdateStrategy = statusStrategy\n\tstatusStore.ResetFieldsStrategy = statusStrategy\n\treturn \u0026StatusREST{store: \u0026statusStore}\n}","line":{"from":177,"to":187}} {"id":100014473,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/etcd.go","code":"func (r *StatusREST) New() runtime.Object {\n\treturn \u0026apiextensions.CustomResourceDefinition{}\n}","line":{"from":195,"to":197}} {"id":100014474,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/etcd.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":199,"to":203}} {"id":100014475,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/etcd.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":205,"to":208}} {"id":100014476,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/etcd.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":210,"to":215}} {"id":100014477,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/etcd.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":217,"to":220}} {"id":100014478,"name":"NewStrategy","signature":"func NewStrategy(typer runtime.ObjectTyper) strategy","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"func NewStrategy(typer runtime.ObjectTyper) strategy {\n\treturn strategy{typer, names.SimpleNameGenerator}\n}","line":{"from":45,"to":47}} {"id":100014479,"name":"NamespaceScoped","signature":"func (strategy) NamespaceScoped() bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"func (strategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":49,"to":51}} {"id":100014480,"name":"GetResetFields","signature":"func (strategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (strategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"apiextensions.k8s.io/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t\t\"apiextensions.k8s.io/v1beta1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":53,"to":66}} {"id":100014481,"name":"PrepareForCreate","signature":"func (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"// PrepareForCreate clears the status of a CustomResourceDefinition before creation.\nfunc (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tcrd := obj.(*apiextensions.CustomResourceDefinition)\n\tcrd.Status = apiextensions.CustomResourceDefinitionStatus{}\n\tcrd.Generation = 1\n\n\tfor _, v := range crd.Spec.Versions {\n\t\tif v.Storage {\n\t\t\tif !apiextensions.IsStoredVersion(crd, v.Name) {\n\t\t\t\tcrd.Status.StoredVersions = append(crd.Status.StoredVersions, v.Name)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\tdropDisabledFields(crd, nil)\n}","line":{"from":68,"to":84}} {"id":100014482,"name":"PrepareForUpdate","signature":"func (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"// PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewCRD := obj.(*apiextensions.CustomResourceDefinition)\n\toldCRD := old.(*apiextensions.CustomResourceDefinition)\n\tnewCRD.Status = oldCRD.Status\n\n\t// Any changes to the spec increment the generation number, any changes to the\n\t// status should reflect the generation number of the corresponding object. We push\n\t// the burden of managing the status onto the clients because we can't (in general)\n\t// know here what version of spec the writer of the status has seen. It may seem like\n\t// we can at first -- since obj contains spec -- but in the future we will probably make\n\t// status its own object, and even if we don't, writes may be the result of a\n\t// read-update-write loop, so the contents of spec may not actually be the spec that\n\t// the controller has *seen*.\n\tif !apiequality.Semantic.DeepEqual(oldCRD.Spec, newCRD.Spec) {\n\t\tnewCRD.Generation = oldCRD.Generation + 1\n\t}\n\n\tfor _, v := range newCRD.Spec.Versions {\n\t\tif v.Storage {\n\t\t\tif !apiextensions.IsStoredVersion(newCRD, v.Name) {\n\t\t\t\tnewCRD.Status.StoredVersions = append(newCRD.Status.StoredVersions, v.Name)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\tdropDisabledFields(newCRD, oldCRD)\n}","line":{"from":86,"to":114}} {"id":100014483,"name":"Validate","signature":"func (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"// Validate validates a new CustomResourceDefinition.\nfunc (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\treturn validation.ValidateCustomResourceDefinition(ctx, obj.(*apiextensions.CustomResourceDefinition))\n}","line":{"from":116,"to":119}} {"id":100014484,"name":"WarningsOnCreate","signature":"func (strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return nil }","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (strategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return nil }","line":{"from":121,"to":122}} {"id":100014485,"name":"AllowCreateOnUpdate","signature":"func (strategy) AllowCreateOnUpdate() bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"// AllowCreateOnUpdate is false for CustomResourceDefinition; this means a POST is\n// needed to create one.\nfunc (strategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":124,"to":128}} {"id":100014486,"name":"AllowUnconditionalUpdate","signature":"func (strategy) AllowUnconditionalUpdate() bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"// AllowUnconditionalUpdate is the default update policy for CustomResourceDefinition objects.\nfunc (strategy) AllowUnconditionalUpdate() bool {\n\treturn false\n}","line":{"from":130,"to":133}} {"id":100014487,"name":"Canonicalize","signature":"func (strategy) Canonicalize(obj runtime.Object)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (strategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":135,"to":137}} {"id":100014488,"name":"ValidateUpdate","signature":"func (strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"// ValidateUpdate is the default update validation for an end user updating status.\nfunc (strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateCustomResourceDefinitionUpdate(ctx, obj.(*apiextensions.CustomResourceDefinition), old.(*apiextensions.CustomResourceDefinition))\n}","line":{"from":139,"to":142}} {"id":100014489,"name":"WarningsOnUpdate","signature":"func (strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (strategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":144,"to":147}} {"id":100014490,"name":"NewStatusStrategy","signature":"func NewStatusStrategy(typer runtime.ObjectTyper) statusStrategy","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"func NewStatusStrategy(typer runtime.ObjectTyper) statusStrategy {\n\treturn statusStrategy{typer, names.SimpleNameGenerator}\n}","line":{"from":154,"to":156}} {"id":100014491,"name":"NamespaceScoped","signature":"func (statusStrategy) NamespaceScoped() bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"func (statusStrategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":158,"to":160}} {"id":100014492,"name":"GetResetFields","signature":"func (statusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"// GetResetFields returns the set of fields that get reset by the strategy\n// and should not be modified by the user.\nfunc (statusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"apiextensions.k8s.io/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"metadata\"),\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t\t\"apiextensions.k8s.io/v1beta1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"metadata\"),\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":162,"to":177}} {"id":100014493,"name":"PrepareForUpdate","signature":"func (statusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"func (statusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewObj := obj.(*apiextensions.CustomResourceDefinition)\n\toldObj := old.(*apiextensions.CustomResourceDefinition)\n\tnewObj.Spec = oldObj.Spec\n\n\t// Status updates are for only for updating status, not objectmeta.\n\tmetav1.ResetObjectMetaForStatus(\u0026newObj.ObjectMeta, \u0026newObj.ObjectMeta)\n}","line":{"from":179,"to":186}} {"id":100014494,"name":"AllowCreateOnUpdate","signature":"func (statusStrategy) AllowCreateOnUpdate() bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"func (statusStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":188,"to":190}} {"id":100014495,"name":"AllowUnconditionalUpdate","signature":"func (statusStrategy) AllowUnconditionalUpdate() bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"func (statusStrategy) AllowUnconditionalUpdate() bool {\n\treturn false\n}","line":{"from":192,"to":194}} {"id":100014496,"name":"Canonicalize","signature":"func (statusStrategy) Canonicalize(obj runtime.Object)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"func (statusStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":196,"to":197}} {"id":100014497,"name":"ValidateUpdate","signature":"func (statusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"func (statusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateUpdateCustomResourceDefinitionStatus(obj.(*apiextensions.CustomResourceDefinition), old.(*apiextensions.CustomResourceDefinition))\n}","line":{"from":199,"to":201}} {"id":100014498,"name":"WarningsOnUpdate","signature":"func (statusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (statusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":203,"to":206}} {"id":100014499,"name":"GetAttrs","signature":"func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"// GetAttrs returns labels and fields of a given object for filtering purposes.\nfunc GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {\n\tapiserver, ok := obj.(*apiextensions.CustomResourceDefinition)\n\tif !ok {\n\t\treturn nil, nil, fmt.Errorf(\"given object is not a CustomResourceDefinition\")\n\t}\n\treturn labels.Set(apiserver.ObjectMeta.Labels), CustomResourceDefinitionToSelectableFields(apiserver), nil\n}","line":{"from":208,"to":215}} {"id":100014500,"name":"MatchCustomResourceDefinition","signature":"func MatchCustomResourceDefinition(label labels.Selector, field fields.Selector) storage.SelectionPredicate","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"// MatchCustomResourceDefinition is the filter used by the generic etcd backend to watch events\n// from etcd to clients of the apiserver only interested in specific labels/fields.\nfunc MatchCustomResourceDefinition(label labels.Selector, field fields.Selector) storage.SelectionPredicate {\n\treturn storage.SelectionPredicate{\n\t\tLabel: label,\n\t\tField: field,\n\t\tGetAttrs: GetAttrs,\n\t}\n}","line":{"from":217,"to":225}} {"id":100014501,"name":"CustomResourceDefinitionToSelectableFields","signature":"func CustomResourceDefinitionToSelectableFields(obj *apiextensions.CustomResourceDefinition) fields.Set","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"// CustomResourceDefinitionToSelectableFields returns a field set that represents the object.\nfunc CustomResourceDefinitionToSelectableFields(obj *apiextensions.CustomResourceDefinition) fields.Set {\n\treturn generic.ObjectMetaFieldsSet(\u0026obj.ObjectMeta, true)\n}","line":{"from":227,"to":230}} {"id":100014502,"name":"dropDisabledFields","signature":"func dropDisabledFields(newCRD *apiextensions.CustomResourceDefinition, oldCRD *apiextensions.CustomResourceDefinition)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"// dropDisabledFields drops disabled fields that are not used if their associated feature gates\n// are not enabled.\nfunc dropDisabledFields(newCRD *apiextensions.CustomResourceDefinition, oldCRD *apiextensions.CustomResourceDefinition) {\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.CustomResourceValidationExpressions) \u0026\u0026 (oldCRD == nil || (oldCRD != nil \u0026\u0026 !specHasXValidations(\u0026oldCRD.Spec))) {\n\t\tif newCRD.Spec.Validation != nil {\n\t\t\tdropXValidationsField(newCRD.Spec.Validation.OpenAPIV3Schema)\n\t\t}\n\t\tfor _, v := range newCRD.Spec.Versions {\n\t\t\tif v.Schema != nil {\n\t\t\t\tdropXValidationsField(v.Schema.OpenAPIV3Schema)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":232,"to":245}} {"id":100014503,"name":"dropXValidationsField","signature":"func dropXValidationsField(schema *apiextensions.JSONSchemaProps)","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"// dropXValidationsField drops field XValidations from CRD schema\nfunc dropXValidationsField(schema *apiextensions.JSONSchemaProps) {\n\tif schema == nil {\n\t\treturn\n\t}\n\tschema.XValidations = nil\n\tif schema.AdditionalProperties != nil {\n\t\tdropXValidationsField(schema.AdditionalProperties.Schema)\n\t}\n\tfor def, jsonSchema := range schema.Properties {\n\t\tdropXValidationsField(\u0026jsonSchema)\n\t\tschema.Properties[def] = jsonSchema\n\t}\n\tif schema.Items != nil {\n\t\tdropXValidationsField(schema.Items.Schema)\n\t\tfor i, jsonSchema := range schema.Items.JSONSchemas {\n\t\t\tdropXValidationsField(\u0026jsonSchema)\n\t\t\tschema.Items.JSONSchemas[i] = jsonSchema\n\t\t}\n\t}\n\tfor def, jsonSchemaPropsOrStringArray := range schema.Dependencies {\n\t\tdropXValidationsField(jsonSchemaPropsOrStringArray.Schema)\n\t\tschema.Dependencies[def] = jsonSchemaPropsOrStringArray\n\t}\n}","line":{"from":247,"to":271}} {"id":100014504,"name":"specHasXValidations","signature":"func specHasXValidations(spec *apiextensions.CustomResourceDefinitionSpec) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"func specHasXValidations(spec *apiextensions.CustomResourceDefinitionSpec) bool {\n\treturn validation.HasSchemaWith(spec, schemaHasXValidations)\n}","line":{"from":273,"to":275}} {"id":100014505,"name":"schemaHasXValidations","signature":"func schemaHasXValidations(s *apiextensions.JSONSchemaProps) bool","file":"staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/strategy.go","code":"func schemaHasXValidations(s *apiextensions.JSONSchemaProps) bool {\n\treturn validation.SchemaHas(s, func(s *apiextensions.JSONSchemaProps) bool {\n\t\treturn s.XValidations != nil\n\t})\n}","line":{"from":277,"to":281}} {"id":100014506,"name":"Error","signature":"func (e *StatusError) Error() string","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// Error implements the Error interface.\nfunc (e *StatusError) Error() string {\n\treturn e.ErrStatus.Message\n}","line":{"from":69,"to":72}} {"id":100014507,"name":"Status","signature":"func (e *StatusError) Status() metav1.Status","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// Status allows access to e's status without having to know the detailed workings\n// of StatusError.\nfunc (e *StatusError) Status() metav1.Status {\n\treturn e.ErrStatus\n}","line":{"from":74,"to":78}} {"id":100014508,"name":"DebugError","signature":"func (e *StatusError) DebugError() (string, []interface{})","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// DebugError reports extended info about the error to debug output.\nfunc (e *StatusError) DebugError() (string, []interface{}) {\n\tif out, err := json.MarshalIndent(e.ErrStatus, \"\", \" \"); err == nil {\n\t\treturn \"server response object: %s\", []interface{}{string(out)}\n\t}\n\treturn \"server response object: %#v\", []interface{}{e.ErrStatus}\n}","line":{"from":80,"to":86}} {"id":100014509,"name":"HasStatusCause","signature":"func HasStatusCause(err error, name metav1.CauseType) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// HasStatusCause returns true if the provided error has a details cause\n// with the provided type name.\n// It supports wrapped errors and returns false when the error is nil.\nfunc HasStatusCause(err error, name metav1.CauseType) bool {\n\t_, ok := StatusCause(err, name)\n\treturn ok\n}","line":{"from":88,"to":94}} {"id":100014510,"name":"StatusCause","signature":"func StatusCause(err error, name metav1.CauseType) (metav1.StatusCause, bool)","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// StatusCause returns the named cause from the provided error if it exists and\n// the error unwraps to the type APIStatus. Otherwise it returns false.\nfunc StatusCause(err error, name metav1.CauseType) (metav1.StatusCause, bool) {\n\tstatus, ok := err.(APIStatus)\n\tif (ok || errors.As(err, \u0026status)) \u0026\u0026 status.Status().Details != nil {\n\t\tfor _, cause := range status.Status().Details.Causes {\n\t\t\tif cause.Type == name {\n\t\t\t\treturn cause, true\n\t\t\t}\n\t\t}\n\t}\n\treturn metav1.StatusCause{}, false\n}","line":{"from":96,"to":108}} {"id":100014511,"name":"Error","signature":"func (u *UnexpectedObjectError) Error() string","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// Error returns an error message describing 'u'.\nfunc (u *UnexpectedObjectError) Error() string {\n\treturn fmt.Sprintf(\"unexpected object: %v\", u.Object)\n}","line":{"from":115,"to":118}} {"id":100014512,"name":"FromObject","signature":"func FromObject(obj runtime.Object) error","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// FromObject generates an StatusError from an metav1.Status, if that is the type of obj; otherwise,\n// returns an UnexpecteObjectError.\nfunc FromObject(obj runtime.Object) error {\n\tswitch t := obj.(type) {\n\tcase *metav1.Status:\n\t\treturn \u0026StatusError{ErrStatus: *t}\n\tcase runtime.Unstructured:\n\t\tvar status metav1.Status\n\t\tobj := t.UnstructuredContent()\n\t\tif !reflect.DeepEqual(obj[\"kind\"], \"Status\") {\n\t\t\tbreak\n\t\t}\n\t\tif err := runtime.DefaultUnstructuredConverter.FromUnstructured(t.UnstructuredContent(), \u0026status); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif status.APIVersion != \"v1\" \u0026\u0026 status.APIVersion != \"meta.k8s.io/v1\" {\n\t\t\tbreak\n\t\t}\n\t\treturn \u0026StatusError{ErrStatus: status}\n\t}\n\treturn \u0026UnexpectedObjectError{obj}\n}","line":{"from":120,"to":141}} {"id":100014513,"name":"NewNotFound","signature":"func NewNotFound(qualifiedResource schema.GroupResource, name string) *StatusError","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// NewNotFound returns a new error which indicates that the resource of the kind and the name was not found.\nfunc NewNotFound(qualifiedResource schema.GroupResource, name string) *StatusError {\n\treturn \u0026StatusError{metav1.Status{\n\t\tStatus: metav1.StatusFailure,\n\t\tCode: http.StatusNotFound,\n\t\tReason: metav1.StatusReasonNotFound,\n\t\tDetails: \u0026metav1.StatusDetails{\n\t\t\tGroup: qualifiedResource.Group,\n\t\t\tKind: qualifiedResource.Resource,\n\t\t\tName: name,\n\t\t},\n\t\tMessage: fmt.Sprintf(\"%s %q not found\", qualifiedResource.String(), name),\n\t}}\n}","line":{"from":143,"to":156}} {"id":100014514,"name":"NewAlreadyExists","signature":"func NewAlreadyExists(qualifiedResource schema.GroupResource, name string) *StatusError","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// NewAlreadyExists returns an error indicating the item requested exists by that identifier.\nfunc NewAlreadyExists(qualifiedResource schema.GroupResource, name string) *StatusError {\n\treturn \u0026StatusError{metav1.Status{\n\t\tStatus: metav1.StatusFailure,\n\t\tCode: http.StatusConflict,\n\t\tReason: metav1.StatusReasonAlreadyExists,\n\t\tDetails: \u0026metav1.StatusDetails{\n\t\t\tGroup: qualifiedResource.Group,\n\t\t\tKind: qualifiedResource.Resource,\n\t\t\tName: name,\n\t\t},\n\t\tMessage: fmt.Sprintf(\"%s %q already exists\", qualifiedResource.String(), name),\n\t}}\n}","line":{"from":158,"to":171}} {"id":100014515,"name":"NewGenerateNameConflict","signature":"func NewGenerateNameConflict(qualifiedResource schema.GroupResource, name string, retryAfterSeconds int) *StatusError","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// NewGenerateNameConflict returns an error indicating the server\n// was not able to generate a valid name for a resource.\nfunc NewGenerateNameConflict(qualifiedResource schema.GroupResource, name string, retryAfterSeconds int) *StatusError {\n\treturn \u0026StatusError{metav1.Status{\n\t\tStatus: metav1.StatusFailure,\n\t\tCode: http.StatusConflict,\n\t\tReason: metav1.StatusReasonAlreadyExists,\n\t\tDetails: \u0026metav1.StatusDetails{\n\t\t\tGroup: qualifiedResource.Group,\n\t\t\tKind: qualifiedResource.Resource,\n\t\t\tName: name,\n\t\t\tRetryAfterSeconds: int32(retryAfterSeconds),\n\t\t},\n\t\tMessage: fmt.Sprintf(\n\t\t\t\"%s %q already exists, the server was not able to generate a unique name for the object\",\n\t\t\tqualifiedResource.String(), name),\n\t}}\n}","line":{"from":173,"to":190}} {"id":100014516,"name":"NewUnauthorized","signature":"func NewUnauthorized(reason string) *StatusError","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// NewUnauthorized returns an error indicating the client is not authorized to perform the requested\n// action.\nfunc NewUnauthorized(reason string) *StatusError {\n\tmessage := reason\n\tif len(message) == 0 {\n\t\tmessage = \"not authorized\"\n\t}\n\treturn \u0026StatusError{metav1.Status{\n\t\tStatus: metav1.StatusFailure,\n\t\tCode: http.StatusUnauthorized,\n\t\tReason: metav1.StatusReasonUnauthorized,\n\t\tMessage: message,\n\t}}\n}","line":{"from":192,"to":205}} {"id":100014517,"name":"NewForbidden","signature":"func NewForbidden(qualifiedResource schema.GroupResource, name string, err error) *StatusError","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// NewForbidden returns an error indicating the requested action was forbidden\nfunc NewForbidden(qualifiedResource schema.GroupResource, name string, err error) *StatusError {\n\tvar message string\n\tif qualifiedResource.Empty() {\n\t\tmessage = fmt.Sprintf(\"forbidden: %v\", err)\n\t} else if name == \"\" {\n\t\tmessage = fmt.Sprintf(\"%s is forbidden: %v\", qualifiedResource.String(), err)\n\t} else {\n\t\tmessage = fmt.Sprintf(\"%s %q is forbidden: %v\", qualifiedResource.String(), name, err)\n\t}\n\treturn \u0026StatusError{metav1.Status{\n\t\tStatus: metav1.StatusFailure,\n\t\tCode: http.StatusForbidden,\n\t\tReason: metav1.StatusReasonForbidden,\n\t\tDetails: \u0026metav1.StatusDetails{\n\t\t\tGroup: qualifiedResource.Group,\n\t\t\tKind: qualifiedResource.Resource,\n\t\t\tName: name,\n\t\t},\n\t\tMessage: message,\n\t}}\n}","line":{"from":207,"to":228}} {"id":100014518,"name":"NewConflict","signature":"func NewConflict(qualifiedResource schema.GroupResource, name string, err error) *StatusError","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// NewConflict returns an error indicating the item can't be updated as provided.\nfunc NewConflict(qualifiedResource schema.GroupResource, name string, err error) *StatusError {\n\treturn \u0026StatusError{metav1.Status{\n\t\tStatus: metav1.StatusFailure,\n\t\tCode: http.StatusConflict,\n\t\tReason: metav1.StatusReasonConflict,\n\t\tDetails: \u0026metav1.StatusDetails{\n\t\t\tGroup: qualifiedResource.Group,\n\t\t\tKind: qualifiedResource.Resource,\n\t\t\tName: name,\n\t\t},\n\t\tMessage: fmt.Sprintf(\"Operation cannot be fulfilled on %s %q: %v\", qualifiedResource.String(), name, err),\n\t}}\n}","line":{"from":230,"to":243}} {"id":100014519,"name":"NewApplyConflict","signature":"func NewApplyConflict(causes []metav1.StatusCause, message string) *StatusError","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// NewApplyConflict returns an error including details on the requests apply conflicts\nfunc NewApplyConflict(causes []metav1.StatusCause, message string) *StatusError {\n\treturn \u0026StatusError{ErrStatus: metav1.Status{\n\t\tStatus: metav1.StatusFailure,\n\t\tCode: http.StatusConflict,\n\t\tReason: metav1.StatusReasonConflict,\n\t\tDetails: \u0026metav1.StatusDetails{\n\t\t\t// TODO: Get obj details here?\n\t\t\tCauses: causes,\n\t\t},\n\t\tMessage: message,\n\t}}\n}","line":{"from":245,"to":257}} {"id":100014520,"name":"NewGone","signature":"func NewGone(message string) *StatusError","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// NewGone returns an error indicating the item no longer available at the server and no forwarding address is known.\n// DEPRECATED: Please use NewResourceExpired instead.\nfunc NewGone(message string) *StatusError {\n\treturn \u0026StatusError{metav1.Status{\n\t\tStatus: metav1.StatusFailure,\n\t\tCode: http.StatusGone,\n\t\tReason: metav1.StatusReasonGone,\n\t\tMessage: message,\n\t}}\n}","line":{"from":259,"to":268}} {"id":100014521,"name":"NewResourceExpired","signature":"func NewResourceExpired(message string) *StatusError","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// NewResourceExpired creates an error that indicates that the requested resource content has expired from\n// the server (usually due to a resourceVersion that is too old).\nfunc NewResourceExpired(message string) *StatusError {\n\treturn \u0026StatusError{metav1.Status{\n\t\tStatus: metav1.StatusFailure,\n\t\tCode: http.StatusGone,\n\t\tReason: metav1.StatusReasonExpired,\n\t\tMessage: message,\n\t}}\n}","line":{"from":270,"to":279}} {"id":100014522,"name":"NewInvalid","signature":"func NewInvalid(qualifiedKind schema.GroupKind, name string, errs field.ErrorList) *StatusError","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// NewInvalid returns an error indicating the item is invalid and cannot be processed.\nfunc NewInvalid(qualifiedKind schema.GroupKind, name string, errs field.ErrorList) *StatusError {\n\tcauses := make([]metav1.StatusCause, 0, len(errs))\n\tfor i := range errs {\n\t\terr := errs[i]\n\t\tcauses = append(causes, metav1.StatusCause{\n\t\t\tType: metav1.CauseType(err.Type),\n\t\t\tMessage: err.ErrorBody(),\n\t\t\tField: err.Field,\n\t\t})\n\t}\n\terr := \u0026StatusError{metav1.Status{\n\t\tStatus: metav1.StatusFailure,\n\t\tCode: http.StatusUnprocessableEntity,\n\t\tReason: metav1.StatusReasonInvalid,\n\t\tDetails: \u0026metav1.StatusDetails{\n\t\t\tGroup: qualifiedKind.Group,\n\t\t\tKind: qualifiedKind.Kind,\n\t\t\tName: name,\n\t\t\tCauses: causes,\n\t\t},\n\t}}\n\taggregatedErrs := errs.ToAggregate()\n\tif aggregatedErrs == nil {\n\t\terr.ErrStatus.Message = fmt.Sprintf(\"%s %q is invalid\", qualifiedKind.String(), name)\n\t} else {\n\t\terr.ErrStatus.Message = fmt.Sprintf(\"%s %q is invalid: %v\", qualifiedKind.String(), name, aggregatedErrs)\n\t}\n\treturn err\n}","line":{"from":281,"to":310}} {"id":100014523,"name":"NewBadRequest","signature":"func NewBadRequest(reason string) *StatusError","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// NewBadRequest creates an error that indicates that the request is invalid and can not be processed.\nfunc NewBadRequest(reason string) *StatusError {\n\treturn \u0026StatusError{metav1.Status{\n\t\tStatus: metav1.StatusFailure,\n\t\tCode: http.StatusBadRequest,\n\t\tReason: metav1.StatusReasonBadRequest,\n\t\tMessage: reason,\n\t}}\n}","line":{"from":312,"to":320}} {"id":100014524,"name":"NewTooManyRequests","signature":"func NewTooManyRequests(message string, retryAfterSeconds int) *StatusError","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// NewTooManyRequests creates an error that indicates that the client must try again later because\n// the specified endpoint is not accepting requests. More specific details should be provided\n// if client should know why the failure was limited.\nfunc NewTooManyRequests(message string, retryAfterSeconds int) *StatusError {\n\treturn \u0026StatusError{metav1.Status{\n\t\tStatus: metav1.StatusFailure,\n\t\tCode: http.StatusTooManyRequests,\n\t\tReason: metav1.StatusReasonTooManyRequests,\n\t\tMessage: message,\n\t\tDetails: \u0026metav1.StatusDetails{\n\t\t\tRetryAfterSeconds: int32(retryAfterSeconds),\n\t\t},\n\t}}\n}","line":{"from":322,"to":335}} {"id":100014525,"name":"NewServiceUnavailable","signature":"func NewServiceUnavailable(reason string) *StatusError","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// NewServiceUnavailable creates an error that indicates that the requested service is unavailable.\nfunc NewServiceUnavailable(reason string) *StatusError {\n\treturn \u0026StatusError{metav1.Status{\n\t\tStatus: metav1.StatusFailure,\n\t\tCode: http.StatusServiceUnavailable,\n\t\tReason: metav1.StatusReasonServiceUnavailable,\n\t\tMessage: reason,\n\t}}\n}","line":{"from":337,"to":345}} {"id":100014526,"name":"NewMethodNotSupported","signature":"func NewMethodNotSupported(qualifiedResource schema.GroupResource, action string) *StatusError","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// NewMethodNotSupported returns an error indicating the requested action is not supported on this kind.\nfunc NewMethodNotSupported(qualifiedResource schema.GroupResource, action string) *StatusError {\n\treturn \u0026StatusError{metav1.Status{\n\t\tStatus: metav1.StatusFailure,\n\t\tCode: http.StatusMethodNotAllowed,\n\t\tReason: metav1.StatusReasonMethodNotAllowed,\n\t\tDetails: \u0026metav1.StatusDetails{\n\t\t\tGroup: qualifiedResource.Group,\n\t\t\tKind: qualifiedResource.Resource,\n\t\t},\n\t\tMessage: fmt.Sprintf(\"%s is not supported on resources of kind %q\", action, qualifiedResource.String()),\n\t}}\n}","line":{"from":347,"to":359}} {"id":100014527,"name":"NewServerTimeout","signature":"func NewServerTimeout(qualifiedResource schema.GroupResource, operation string, retryAfterSeconds int) *StatusError","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// NewServerTimeout returns an error indicating the requested action could not be completed due to a\n// transient error, and the client should try again.\nfunc NewServerTimeout(qualifiedResource schema.GroupResource, operation string, retryAfterSeconds int) *StatusError {\n\treturn \u0026StatusError{metav1.Status{\n\t\tStatus: metav1.StatusFailure,\n\t\tCode: http.StatusInternalServerError,\n\t\tReason: metav1.StatusReasonServerTimeout,\n\t\tDetails: \u0026metav1.StatusDetails{\n\t\t\tGroup: qualifiedResource.Group,\n\t\t\tKind: qualifiedResource.Resource,\n\t\t\tName: operation,\n\t\t\tRetryAfterSeconds: int32(retryAfterSeconds),\n\t\t},\n\t\tMessage: fmt.Sprintf(\"The %s operation against %s could not be completed at this time, please try again.\", operation, qualifiedResource.String()),\n\t}}\n}","line":{"from":361,"to":376}} {"id":100014528,"name":"NewServerTimeoutForKind","signature":"func NewServerTimeoutForKind(qualifiedKind schema.GroupKind, operation string, retryAfterSeconds int) *StatusError","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// NewServerTimeoutForKind should not exist. Server timeouts happen when accessing resources, the Kind is just what we\n// happened to be looking at when the request failed. This delegates to keep code sane, but we should work towards removing this.\nfunc NewServerTimeoutForKind(qualifiedKind schema.GroupKind, operation string, retryAfterSeconds int) *StatusError {\n\treturn NewServerTimeout(schema.GroupResource{Group: qualifiedKind.Group, Resource: qualifiedKind.Kind}, operation, retryAfterSeconds)\n}","line":{"from":378,"to":382}} {"id":100014529,"name":"NewInternalError","signature":"func NewInternalError(err error) *StatusError","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// NewInternalError returns an error indicating the item is invalid and cannot be processed.\nfunc NewInternalError(err error) *StatusError {\n\treturn \u0026StatusError{metav1.Status{\n\t\tStatus: metav1.StatusFailure,\n\t\tCode: http.StatusInternalServerError,\n\t\tReason: metav1.StatusReasonInternalError,\n\t\tDetails: \u0026metav1.StatusDetails{\n\t\t\tCauses: []metav1.StatusCause{{Message: err.Error()}},\n\t\t},\n\t\tMessage: fmt.Sprintf(\"Internal error occurred: %v\", err),\n\t}}\n}","line":{"from":384,"to":395}} {"id":100014530,"name":"NewTimeoutError","signature":"func NewTimeoutError(message string, retryAfterSeconds int) *StatusError","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// NewTimeoutError returns an error indicating that a timeout occurred before the request\n// could be completed. Clients may retry, but the operation may still complete.\nfunc NewTimeoutError(message string, retryAfterSeconds int) *StatusError {\n\treturn \u0026StatusError{metav1.Status{\n\t\tStatus: metav1.StatusFailure,\n\t\tCode: http.StatusGatewayTimeout,\n\t\tReason: metav1.StatusReasonTimeout,\n\t\tMessage: fmt.Sprintf(\"Timeout: %s\", message),\n\t\tDetails: \u0026metav1.StatusDetails{\n\t\t\tRetryAfterSeconds: int32(retryAfterSeconds),\n\t\t},\n\t}}\n}","line":{"from":397,"to":409}} {"id":100014531,"name":"NewTooManyRequestsError","signature":"func NewTooManyRequestsError(message string) *StatusError","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// NewTooManyRequestsError returns an error indicating that the request was rejected because\n// the server has received too many requests. Client should wait and retry. But if the request\n// is perishable, then the client should not retry the request.\nfunc NewTooManyRequestsError(message string) *StatusError {\n\treturn \u0026StatusError{metav1.Status{\n\t\tStatus: metav1.StatusFailure,\n\t\tCode: http.StatusTooManyRequests,\n\t\tReason: metav1.StatusReasonTooManyRequests,\n\t\tMessage: fmt.Sprintf(\"Too many requests: %s\", message),\n\t}}\n}","line":{"from":411,"to":421}} {"id":100014532,"name":"NewRequestEntityTooLargeError","signature":"func NewRequestEntityTooLargeError(message string) *StatusError","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// NewRequestEntityTooLargeError returns an error indicating that the request\n// entity was too large.\nfunc NewRequestEntityTooLargeError(message string) *StatusError {\n\treturn \u0026StatusError{metav1.Status{\n\t\tStatus: metav1.StatusFailure,\n\t\tCode: http.StatusRequestEntityTooLarge,\n\t\tReason: metav1.StatusReasonRequestEntityTooLarge,\n\t\tMessage: fmt.Sprintf(\"Request entity too large: %s\", message),\n\t}}\n}","line":{"from":423,"to":432}} {"id":100014533,"name":"NewGenericServerResponse","signature":"func NewGenericServerResponse(code int, verb string, qualifiedResource schema.GroupResource, name, serverMessage string, retryAfterSeconds int, isUnexpectedResponse bool) *StatusError","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// NewGenericServerResponse returns a new error for server responses that are not in a recognizable form.\nfunc NewGenericServerResponse(code int, verb string, qualifiedResource schema.GroupResource, name, serverMessage string, retryAfterSeconds int, isUnexpectedResponse bool) *StatusError {\n\treason := metav1.StatusReasonUnknown\n\tmessage := fmt.Sprintf(\"the server responded with the status code %d but did not return more information\", code)\n\tswitch code {\n\tcase http.StatusConflict:\n\t\tif verb == \"POST\" {\n\t\t\treason = metav1.StatusReasonAlreadyExists\n\t\t} else {\n\t\t\treason = metav1.StatusReasonConflict\n\t\t}\n\t\tmessage = \"the server reported a conflict\"\n\tcase http.StatusNotFound:\n\t\treason = metav1.StatusReasonNotFound\n\t\tmessage = \"the server could not find the requested resource\"\n\tcase http.StatusBadRequest:\n\t\treason = metav1.StatusReasonBadRequest\n\t\tmessage = \"the server rejected our request for an unknown reason\"\n\tcase http.StatusUnauthorized:\n\t\treason = metav1.StatusReasonUnauthorized\n\t\tmessage = \"the server has asked for the client to provide credentials\"\n\tcase http.StatusForbidden:\n\t\treason = metav1.StatusReasonForbidden\n\t\t// the server message has details about who is trying to perform what action. Keep its message.\n\t\tmessage = serverMessage\n\tcase http.StatusNotAcceptable:\n\t\treason = metav1.StatusReasonNotAcceptable\n\t\t// the server message has details about what types are acceptable\n\t\tif len(serverMessage) == 0 || serverMessage == \"unknown\" {\n\t\t\tmessage = \"the server was unable to respond with a content type that the client supports\"\n\t\t} else {\n\t\t\tmessage = serverMessage\n\t\t}\n\tcase http.StatusUnsupportedMediaType:\n\t\treason = metav1.StatusReasonUnsupportedMediaType\n\t\t// the server message has details about what types are acceptable\n\t\tmessage = serverMessage\n\tcase http.StatusMethodNotAllowed:\n\t\treason = metav1.StatusReasonMethodNotAllowed\n\t\tmessage = \"the server does not allow this method on the requested resource\"\n\tcase http.StatusUnprocessableEntity:\n\t\treason = metav1.StatusReasonInvalid\n\t\tmessage = \"the server rejected our request due to an error in our request\"\n\tcase http.StatusServiceUnavailable:\n\t\treason = metav1.StatusReasonServiceUnavailable\n\t\tmessage = \"the server is currently unable to handle the request\"\n\tcase http.StatusGatewayTimeout:\n\t\treason = metav1.StatusReasonTimeout\n\t\tmessage = \"the server was unable to return a response in the time allotted, but may still be processing the request\"\n\tcase http.StatusTooManyRequests:\n\t\treason = metav1.StatusReasonTooManyRequests\n\t\tmessage = \"the server has received too many requests and has asked us to try again later\"\n\tdefault:\n\t\tif code \u003e= 500 {\n\t\t\treason = metav1.StatusReasonInternalError\n\t\t\tmessage = fmt.Sprintf(\"an error on the server (%q) has prevented the request from succeeding\", serverMessage)\n\t\t}\n\t}\n\tswitch {\n\tcase !qualifiedResource.Empty() \u0026\u0026 len(name) \u003e 0:\n\t\tmessage = fmt.Sprintf(\"%s (%s %s %s)\", message, strings.ToLower(verb), qualifiedResource.String(), name)\n\tcase !qualifiedResource.Empty():\n\t\tmessage = fmt.Sprintf(\"%s (%s %s)\", message, strings.ToLower(verb), qualifiedResource.String())\n\t}\n\tvar causes []metav1.StatusCause\n\tif isUnexpectedResponse {\n\t\tcauses = []metav1.StatusCause{\n\t\t\t{\n\t\t\t\tType: metav1.CauseTypeUnexpectedServerResponse,\n\t\t\t\tMessage: serverMessage,\n\t\t\t},\n\t\t}\n\t} else {\n\t\tcauses = nil\n\t}\n\treturn \u0026StatusError{metav1.Status{\n\t\tStatus: metav1.StatusFailure,\n\t\tCode: int32(code),\n\t\tReason: reason,\n\t\tDetails: \u0026metav1.StatusDetails{\n\t\t\tGroup: qualifiedResource.Group,\n\t\t\tKind: qualifiedResource.Resource,\n\t\t\tName: name,\n\n\t\t\tCauses: causes,\n\t\t\tRetryAfterSeconds: int32(retryAfterSeconds),\n\t\t},\n\t\tMessage: message,\n\t}}\n}","line":{"from":434,"to":523}} {"id":100014534,"name":"IsNotFound","signature":"func IsNotFound(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// IsNotFound returns true if the specified error was created by NewNotFound.\n// It supports wrapped errors and returns false when the error is nil.\nfunc IsNotFound(err error) bool {\n\treason, code := reasonAndCodeForError(err)\n\tif reason == metav1.StatusReasonNotFound {\n\t\treturn true\n\t}\n\tif _, ok := knownReasons[reason]; !ok \u0026\u0026 code == http.StatusNotFound {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":525,"to":536}} {"id":100014535,"name":"IsAlreadyExists","signature":"func IsAlreadyExists(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// IsAlreadyExists determines if the err is an error which indicates that a specified resource already exists.\n// It supports wrapped errors and returns false when the error is nil.\nfunc IsAlreadyExists(err error) bool {\n\treturn ReasonForError(err) == metav1.StatusReasonAlreadyExists\n}","line":{"from":538,"to":542}} {"id":100014536,"name":"IsConflict","signature":"func IsConflict(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// IsConflict determines if the err is an error which indicates the provided update conflicts.\n// It supports wrapped errors and returns false when the error is nil.\nfunc IsConflict(err error) bool {\n\treason, code := reasonAndCodeForError(err)\n\tif reason == metav1.StatusReasonConflict {\n\t\treturn true\n\t}\n\tif _, ok := knownReasons[reason]; !ok \u0026\u0026 code == http.StatusConflict {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":544,"to":555}} {"id":100014537,"name":"IsInvalid","signature":"func IsInvalid(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// IsInvalid determines if the err is an error which indicates the provided resource is not valid.\n// It supports wrapped errors and returns false when the error is nil.\nfunc IsInvalid(err error) bool {\n\treason, code := reasonAndCodeForError(err)\n\tif reason == metav1.StatusReasonInvalid {\n\t\treturn true\n\t}\n\tif _, ok := knownReasons[reason]; !ok \u0026\u0026 code == http.StatusUnprocessableEntity {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":557,"to":568}} {"id":100014538,"name":"IsGone","signature":"func IsGone(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// IsGone is true if the error indicates the requested resource is no longer available.\n// It supports wrapped errors and returns false when the error is nil.\nfunc IsGone(err error) bool {\n\treason, code := reasonAndCodeForError(err)\n\tif reason == metav1.StatusReasonGone {\n\t\treturn true\n\t}\n\tif _, ok := knownReasons[reason]; !ok \u0026\u0026 code == http.StatusGone {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":570,"to":581}} {"id":100014539,"name":"IsResourceExpired","signature":"func IsResourceExpired(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// IsResourceExpired is true if the error indicates the resource has expired and the current action is\n// no longer possible.\n// It supports wrapped errors and returns false when the error is nil.\nfunc IsResourceExpired(err error) bool {\n\treturn ReasonForError(err) == metav1.StatusReasonExpired\n}","line":{"from":583,"to":588}} {"id":100014540,"name":"IsNotAcceptable","signature":"func IsNotAcceptable(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// IsNotAcceptable determines if err is an error which indicates that the request failed due to an invalid Accept header\n// It supports wrapped errors and returns false when the error is nil.\nfunc IsNotAcceptable(err error) bool {\n\treason, code := reasonAndCodeForError(err)\n\tif reason == metav1.StatusReasonNotAcceptable {\n\t\treturn true\n\t}\n\tif _, ok := knownReasons[reason]; !ok \u0026\u0026 code == http.StatusNotAcceptable {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":590,"to":601}} {"id":100014541,"name":"IsUnsupportedMediaType","signature":"func IsUnsupportedMediaType(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// IsUnsupportedMediaType determines if err is an error which indicates that the request failed due to an invalid Content-Type header\n// It supports wrapped errors and returns false when the error is nil.\nfunc IsUnsupportedMediaType(err error) bool {\n\treason, code := reasonAndCodeForError(err)\n\tif reason == metav1.StatusReasonUnsupportedMediaType {\n\t\treturn true\n\t}\n\tif _, ok := knownReasons[reason]; !ok \u0026\u0026 code == http.StatusUnsupportedMediaType {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":603,"to":614}} {"id":100014542,"name":"IsMethodNotSupported","signature":"func IsMethodNotSupported(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// IsMethodNotSupported determines if the err is an error which indicates the provided action could not\n// be performed because it is not supported by the server.\n// It supports wrapped errors and returns false when the error is nil.\nfunc IsMethodNotSupported(err error) bool {\n\treason, code := reasonAndCodeForError(err)\n\tif reason == metav1.StatusReasonMethodNotAllowed {\n\t\treturn true\n\t}\n\tif _, ok := knownReasons[reason]; !ok \u0026\u0026 code == http.StatusMethodNotAllowed {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":616,"to":628}} {"id":100014543,"name":"IsServiceUnavailable","signature":"func IsServiceUnavailable(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// IsServiceUnavailable is true if the error indicates the underlying service is no longer available.\n// It supports wrapped errors and returns false when the error is nil.\nfunc IsServiceUnavailable(err error) bool {\n\treason, code := reasonAndCodeForError(err)\n\tif reason == metav1.StatusReasonServiceUnavailable {\n\t\treturn true\n\t}\n\tif _, ok := knownReasons[reason]; !ok \u0026\u0026 code == http.StatusServiceUnavailable {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":630,"to":641}} {"id":100014544,"name":"IsBadRequest","signature":"func IsBadRequest(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// IsBadRequest determines if err is an error which indicates that the request is invalid.\n// It supports wrapped errors and returns false when the error is nil.\nfunc IsBadRequest(err error) bool {\n\treason, code := reasonAndCodeForError(err)\n\tif reason == metav1.StatusReasonBadRequest {\n\t\treturn true\n\t}\n\tif _, ok := knownReasons[reason]; !ok \u0026\u0026 code == http.StatusBadRequest {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":643,"to":654}} {"id":100014545,"name":"IsUnauthorized","signature":"func IsUnauthorized(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// IsUnauthorized determines if err is an error which indicates that the request is unauthorized and\n// requires authentication by the user.\n// It supports wrapped errors and returns false when the error is nil.\nfunc IsUnauthorized(err error) bool {\n\treason, code := reasonAndCodeForError(err)\n\tif reason == metav1.StatusReasonUnauthorized {\n\t\treturn true\n\t}\n\tif _, ok := knownReasons[reason]; !ok \u0026\u0026 code == http.StatusUnauthorized {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":656,"to":668}} {"id":100014546,"name":"IsForbidden","signature":"func IsForbidden(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// IsForbidden determines if err is an error which indicates that the request is forbidden and cannot\n// be completed as requested.\n// It supports wrapped errors and returns false when the error is nil.\nfunc IsForbidden(err error) bool {\n\treason, code := reasonAndCodeForError(err)\n\tif reason == metav1.StatusReasonForbidden {\n\t\treturn true\n\t}\n\tif _, ok := knownReasons[reason]; !ok \u0026\u0026 code == http.StatusForbidden {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":670,"to":682}} {"id":100014547,"name":"IsTimeout","signature":"func IsTimeout(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// IsTimeout determines if err is an error which indicates that request times out due to long\n// processing.\n// It supports wrapped errors and returns false when the error is nil.\nfunc IsTimeout(err error) bool {\n\treason, code := reasonAndCodeForError(err)\n\tif reason == metav1.StatusReasonTimeout {\n\t\treturn true\n\t}\n\tif _, ok := knownReasons[reason]; !ok \u0026\u0026 code == http.StatusGatewayTimeout {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":684,"to":696}} {"id":100014548,"name":"IsServerTimeout","signature":"func IsServerTimeout(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// IsServerTimeout determines if err is an error which indicates that the request needs to be retried\n// by the client.\n// It supports wrapped errors and returns false when the error is nil.\nfunc IsServerTimeout(err error) bool {\n\t// do not check the status code, because no https status code exists that can\n\t// be scoped to retryable timeouts.\n\treturn ReasonForError(err) == metav1.StatusReasonServerTimeout\n}","line":{"from":698,"to":705}} {"id":100014549,"name":"IsInternalError","signature":"func IsInternalError(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// IsInternalError determines if err is an error which indicates an internal server error.\n// It supports wrapped errors and returns false when the error is nil.\nfunc IsInternalError(err error) bool {\n\treason, code := reasonAndCodeForError(err)\n\tif reason == metav1.StatusReasonInternalError {\n\t\treturn true\n\t}\n\tif _, ok := knownReasons[reason]; !ok \u0026\u0026 code == http.StatusInternalServerError {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":707,"to":718}} {"id":100014550,"name":"IsTooManyRequests","signature":"func IsTooManyRequests(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// IsTooManyRequests determines if err is an error which indicates that there are too many requests\n// that the server cannot handle.\n// It supports wrapped errors and returns false when the error is nil.\nfunc IsTooManyRequests(err error) bool {\n\treason, code := reasonAndCodeForError(err)\n\tif reason == metav1.StatusReasonTooManyRequests {\n\t\treturn true\n\t}\n\n\t// IsTooManyRequests' checking of code predates the checking of the code in\n\t// the other Is* functions. In order to maintain backward compatibility, this\n\t// does not check that the reason is unknown.\n\tif code == http.StatusTooManyRequests {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":720,"to":736}} {"id":100014551,"name":"IsRequestEntityTooLargeError","signature":"func IsRequestEntityTooLargeError(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// IsRequestEntityTooLargeError determines if err is an error which indicates\n// the request entity is too large.\n// It supports wrapped errors and returns false when the error is nil.\nfunc IsRequestEntityTooLargeError(err error) bool {\n\treason, code := reasonAndCodeForError(err)\n\tif reason == metav1.StatusReasonRequestEntityTooLarge {\n\t\treturn true\n\t}\n\n\t// IsRequestEntityTooLargeError's checking of code predates the checking of\n\t// the code in the other Is* functions. In order to maintain backward\n\t// compatibility, this does not check that the reason is unknown.\n\tif code == http.StatusRequestEntityTooLarge {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":738,"to":754}} {"id":100014552,"name":"IsUnexpectedServerError","signature":"func IsUnexpectedServerError(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// IsUnexpectedServerError returns true if the server response was not in the expected API format,\n// and may be the result of another HTTP actor.\n// It supports wrapped errors and returns false when the error is nil.\nfunc IsUnexpectedServerError(err error) bool {\n\tstatus, ok := err.(APIStatus)\n\tif (ok || errors.As(err, \u0026status)) \u0026\u0026 status.Status().Details != nil {\n\t\tfor _, cause := range status.Status().Details.Causes {\n\t\t\tif cause.Type == metav1.CauseTypeUnexpectedServerResponse {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":756,"to":769}} {"id":100014553,"name":"IsUnexpectedObjectError","signature":"func IsUnexpectedObjectError(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// IsUnexpectedObjectError determines if err is due to an unexpected object from the master.\n// It supports wrapped errors and returns false when the error is nil.\nfunc IsUnexpectedObjectError(err error) bool {\n\tuoe, ok := err.(*UnexpectedObjectError)\n\treturn err != nil \u0026\u0026 (ok || errors.As(err, \u0026uoe))\n}","line":{"from":771,"to":776}} {"id":100014554,"name":"SuggestsClientDelay","signature":"func SuggestsClientDelay(err error) (int, bool)","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// SuggestsClientDelay returns true if this error suggests a client delay as well as the\n// suggested seconds to wait, or false if the error does not imply a wait. It does not\n// address whether the error *should* be retried, since some errors (like a 3xx) may\n// request delay without retry.\n// It supports wrapped errors and returns false when the error is nil.\nfunc SuggestsClientDelay(err error) (int, bool) {\n\tt, ok := err.(APIStatus)\n\tif (ok || errors.As(err, \u0026t)) \u0026\u0026 t.Status().Details != nil {\n\t\tswitch t.Status().Reason {\n\t\t// this StatusReason explicitly requests the caller to delay the action\n\t\tcase metav1.StatusReasonServerTimeout:\n\t\t\treturn int(t.Status().Details.RetryAfterSeconds), true\n\t\t}\n\t\t// If the client requests that we retry after a certain number of seconds\n\t\tif t.Status().Details.RetryAfterSeconds \u003e 0 {\n\t\t\treturn int(t.Status().Details.RetryAfterSeconds), true\n\t\t}\n\t}\n\treturn 0, false\n}","line":{"from":778,"to":797}} {"id":100014555,"name":"ReasonForError","signature":"func ReasonForError(err error) metav1.StatusReason","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// ReasonForError returns the HTTP status for a particular error.\n// It supports wrapped errors and returns StatusReasonUnknown when\n// the error is nil or doesn't have a status.\nfunc ReasonForError(err error) metav1.StatusReason {\n\tif status, ok := err.(APIStatus); ok || errors.As(err, \u0026status) {\n\t\treturn status.Status().Reason\n\t}\n\treturn metav1.StatusReasonUnknown\n}","line":{"from":799,"to":807}} {"id":100014556,"name":"reasonAndCodeForError","signature":"func reasonAndCodeForError(err error) (metav1.StatusReason, int32)","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"func reasonAndCodeForError(err error) (metav1.StatusReason, int32) {\n\tif status, ok := err.(APIStatus); ok || errors.As(err, \u0026status) {\n\t\treturn status.Status().Reason, status.Status().Code\n\t}\n\treturn metav1.StatusReasonUnknown, 0\n}","line":{"from":809,"to":814}} {"id":100014557,"name":"NewClientErrorReporter","signature":"func NewClientErrorReporter(code int, verb string, reason string) *ErrorReporter","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// NewClientErrorReporter will respond with valid v1.Status objects that report\n// unexpected server responses. Primarily used by watch to report errors when\n// we attempt to decode a response from the server and it is not in the form\n// we expect. Because watch is a dependency of the core api, we can't return\n// meta/v1.Status in that package and so much inject this interface to convert a\n// generic error as appropriate. The reason is passed as a unique status cause\n// on the returned status, otherwise the generic \"ClientError\" is returned.\nfunc NewClientErrorReporter(code int, verb string, reason string) *ErrorReporter {\n\treturn \u0026ErrorReporter{\n\t\tcode: code,\n\t\tverb: verb,\n\t\treason: reason,\n\t}\n}","line":{"from":825,"to":838}} {"id":100014558,"name":"AsObject","signature":"func (r *ErrorReporter) AsObject(err error) runtime.Object","file":"staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go","code":"// AsObject returns a valid error runtime.Object (a v1.Status) for the given\n// error, using the code and verb of the reporter type. The error is set to\n// indicate that this was an unexpected server response.\nfunc (r *ErrorReporter) AsObject(err error) runtime.Object {\n\tstatus := NewGenericServerResponse(r.code, r.verb, schema.GroupResource{}, \"\", err.Error(), 0, true)\n\tif status.ErrStatus.Details == nil {\n\t\tstatus.ErrStatus.Details = \u0026metav1.StatusDetails{}\n\t}\n\treason := r.reason\n\tif len(reason) == 0 {\n\t\treason = \"ClientError\"\n\t}\n\tstatus.ErrStatus.Details.Causes = append(status.ErrStatus.Details.Causes, metav1.StatusCause{\n\t\tType: metav1.CauseType(reason),\n\t\tMessage: err.Error(),\n\t})\n\treturn \u0026status.ErrStatus\n}","line":{"from":840,"to":857}} {"id":100014559,"name":"SetStatusCondition","signature":"func SetStatusCondition(conditions *[]metav1.Condition, newCondition metav1.Condition)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/conditions.go","code":"// SetStatusCondition sets the corresponding condition in conditions to newCondition.\n// conditions must be non-nil.\n// 1. if the condition of the specified type already exists (all fields of the existing condition are updated to\n// newCondition, LastTransitionTime is set to now if the new status differs from the old status)\n// 2. if a condition of the specified type does not exist (LastTransitionTime is set to now() if unset, and newCondition is appended)\nfunc SetStatusCondition(conditions *[]metav1.Condition, newCondition metav1.Condition) {\n\tif conditions == nil {\n\t\treturn\n\t}\n\texistingCondition := FindStatusCondition(*conditions, newCondition.Type)\n\tif existingCondition == nil {\n\t\tif newCondition.LastTransitionTime.IsZero() {\n\t\t\tnewCondition.LastTransitionTime = metav1.NewTime(time.Now())\n\t\t}\n\t\t*conditions = append(*conditions, newCondition)\n\t\treturn\n\t}\n\n\tif existingCondition.Status != newCondition.Status {\n\t\texistingCondition.Status = newCondition.Status\n\t\tif !newCondition.LastTransitionTime.IsZero() {\n\t\t\texistingCondition.LastTransitionTime = newCondition.LastTransitionTime\n\t\t} else {\n\t\t\texistingCondition.LastTransitionTime = metav1.NewTime(time.Now())\n\t\t}\n\t}\n\n\texistingCondition.Reason = newCondition.Reason\n\texistingCondition.Message = newCondition.Message\n\texistingCondition.ObservedGeneration = newCondition.ObservedGeneration\n}","line":{"from":25,"to":55}} {"id":100014560,"name":"RemoveStatusCondition","signature":"func RemoveStatusCondition(conditions *[]metav1.Condition, conditionType string)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/conditions.go","code":"// RemoveStatusCondition removes the corresponding conditionType from conditions.\n// conditions must be non-nil.\nfunc RemoveStatusCondition(conditions *[]metav1.Condition, conditionType string) {\n\tif conditions == nil || len(*conditions) == 0 {\n\t\treturn\n\t}\n\tnewConditions := make([]metav1.Condition, 0, len(*conditions)-1)\n\tfor _, condition := range *conditions {\n\t\tif condition.Type != conditionType {\n\t\t\tnewConditions = append(newConditions, condition)\n\t\t}\n\t}\n\n\t*conditions = newConditions\n}","line":{"from":57,"to":71}} {"id":100014561,"name":"FindStatusCondition","signature":"func FindStatusCondition(conditions []metav1.Condition, conditionType string) *metav1.Condition","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/conditions.go","code":"// FindStatusCondition finds the conditionType in conditions.\nfunc FindStatusCondition(conditions []metav1.Condition, conditionType string) *metav1.Condition {\n\tfor i := range conditions {\n\t\tif conditions[i].Type == conditionType {\n\t\t\treturn \u0026conditions[i]\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":73,"to":82}} {"id":100014562,"name":"IsStatusConditionTrue","signature":"func IsStatusConditionTrue(conditions []metav1.Condition, conditionType string) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/conditions.go","code":"// IsStatusConditionTrue returns true when the conditionType is present and set to `metav1.ConditionTrue`\nfunc IsStatusConditionTrue(conditions []metav1.Condition, conditionType string) bool {\n\treturn IsStatusConditionPresentAndEqual(conditions, conditionType, metav1.ConditionTrue)\n}","line":{"from":84,"to":87}} {"id":100014563,"name":"IsStatusConditionFalse","signature":"func IsStatusConditionFalse(conditions []metav1.Condition, conditionType string) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/conditions.go","code":"// IsStatusConditionFalse returns true when the conditionType is present and set to `metav1.ConditionFalse`\nfunc IsStatusConditionFalse(conditions []metav1.Condition, conditionType string) bool {\n\treturn IsStatusConditionPresentAndEqual(conditions, conditionType, metav1.ConditionFalse)\n}","line":{"from":89,"to":92}} {"id":100014564,"name":"IsStatusConditionPresentAndEqual","signature":"func IsStatusConditionPresentAndEqual(conditions []metav1.Condition, conditionType string, status metav1.ConditionStatus) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/conditions.go","code":"// IsStatusConditionPresentAndEqual returns true when conditionType is present and equal to status.\nfunc IsStatusConditionPresentAndEqual(conditions []metav1.Condition, conditionType string, status metav1.ConditionStatus) bool {\n\tfor _, condition := range conditions {\n\t\tif condition.Type == conditionType {\n\t\t\treturn condition.Status == status\n\t\t}\n\t}\n\treturn false\n}","line":{"from":94,"to":102}} {"id":100014565,"name":"Error","signature":"func (e *AmbiguousResourceError) Error() string","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/errors.go","code":"func (e *AmbiguousResourceError) Error() string {\n\tswitch {\n\tcase len(e.MatchingKinds) \u003e 0 \u0026\u0026 len(e.MatchingResources) \u003e 0:\n\t\treturn fmt.Sprintf(\"%v matches multiple resources %v and kinds %v\", e.PartialResource, e.MatchingResources, e.MatchingKinds)\n\tcase len(e.MatchingKinds) \u003e 0:\n\t\treturn fmt.Sprintf(\"%v matches multiple kinds %v\", e.PartialResource, e.MatchingKinds)\n\tcase len(e.MatchingResources) \u003e 0:\n\t\treturn fmt.Sprintf(\"%v matches multiple resources %v\", e.PartialResource, e.MatchingResources)\n\t}\n\treturn fmt.Sprintf(\"%v matches multiple resources or kinds\", e.PartialResource)\n}","line":{"from":35,"to":45}} {"id":100014566,"name":"Is","signature":"func (*AmbiguousResourceError) Is(target error) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/errors.go","code":"func (*AmbiguousResourceError) Is(target error) bool {\n\t_, ok := target.(*AmbiguousResourceError)\n\treturn ok\n}","line":{"from":47,"to":50}} {"id":100014567,"name":"Error","signature":"func (e *AmbiguousKindError) Error() string","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/errors.go","code":"func (e *AmbiguousKindError) Error() string {\n\tswitch {\n\tcase len(e.MatchingKinds) \u003e 0 \u0026\u0026 len(e.MatchingResources) \u003e 0:\n\t\treturn fmt.Sprintf(\"%v matches multiple resources %v and kinds %v\", e.PartialKind, e.MatchingResources, e.MatchingKinds)\n\tcase len(e.MatchingKinds) \u003e 0:\n\t\treturn fmt.Sprintf(\"%v matches multiple kinds %v\", e.PartialKind, e.MatchingKinds)\n\tcase len(e.MatchingResources) \u003e 0:\n\t\treturn fmt.Sprintf(\"%v matches multiple resources %v\", e.PartialKind, e.MatchingResources)\n\t}\n\treturn fmt.Sprintf(\"%v matches multiple resources or kinds\", e.PartialKind)\n}","line":{"from":60,"to":70}} {"id":100014568,"name":"Is","signature":"func (*AmbiguousKindError) Is(target error) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/errors.go","code":"func (*AmbiguousKindError) Is(target error) bool {\n\t_, ok := target.(*AmbiguousKindError)\n\treturn ok\n}","line":{"from":72,"to":75}} {"id":100014569,"name":"IsAmbiguousError","signature":"func IsAmbiguousError(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/errors.go","code":"func IsAmbiguousError(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\treturn errors.Is(err, \u0026AmbiguousResourceError{}) || errors.Is(err, \u0026AmbiguousKindError{})\n}","line":{"from":77,"to":82}} {"id":100014570,"name":"Error","signature":"func (e *NoResourceMatchError) Error() string","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/errors.go","code":"func (e *NoResourceMatchError) Error() string {\n\treturn fmt.Sprintf(\"no matches for %v\", e.PartialResource)\n}","line":{"from":89,"to":91}} {"id":100014571,"name":"Is","signature":"func (*NoResourceMatchError) Is(target error) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/errors.go","code":"func (*NoResourceMatchError) Is(target error) bool {\n\t_, ok := target.(*NoResourceMatchError)\n\treturn ok\n}","line":{"from":93,"to":96}} {"id":100014572,"name":"Error","signature":"func (e *NoKindMatchError) Error() string","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/errors.go","code":"func (e *NoKindMatchError) Error() string {\n\tsearchedVersions := sets.NewString()\n\tfor _, v := range e.SearchedVersions {\n\t\tsearchedVersions.Insert(schema.GroupVersion{Group: e.GroupKind.Group, Version: v}.String())\n\t}\n\n\tswitch len(searchedVersions) {\n\tcase 0:\n\t\treturn fmt.Sprintf(\"no matches for kind %q in group %q\", e.GroupKind.Kind, e.GroupKind.Group)\n\tcase 1:\n\t\treturn fmt.Sprintf(\"no matches for kind %q in version %q\", e.GroupKind.Kind, searchedVersions.List()[0])\n\tdefault:\n\t\treturn fmt.Sprintf(\"no matches for kind %q in versions %q\", e.GroupKind.Kind, searchedVersions.List())\n\t}\n}","line":{"from":106,"to":120}} {"id":100014573,"name":"Is","signature":"func (*NoKindMatchError) Is(target error) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/errors.go","code":"func (*NoKindMatchError) Is(target error) bool {\n\t_, ok := target.(*NoKindMatchError)\n\treturn ok\n}","line":{"from":122,"to":125}} {"id":100014574,"name":"IsNoMatchError","signature":"func IsNoMatchError(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/errors.go","code":"func IsNoMatchError(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\treturn errors.Is(err, \u0026NoResourceMatchError{}) || errors.Is(err, \u0026NoKindMatchError{})\n}","line":{"from":127,"to":132}} {"id":100014575,"name":"String","signature":"func (m FirstHitRESTMapper) String() string","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/firsthit_restmapper.go","code":"func (m FirstHitRESTMapper) String() string {\n\treturn fmt.Sprintf(\"FirstHitRESTMapper{\\n\\t%v\\n}\", m.MultiRESTMapper)\n}","line":{"from":36,"to":38}} {"id":100014576,"name":"ResourceFor","signature":"func (m FirstHitRESTMapper) ResourceFor(resource schema.GroupVersionResource) (schema.GroupVersionResource, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/firsthit_restmapper.go","code":"func (m FirstHitRESTMapper) ResourceFor(resource schema.GroupVersionResource) (schema.GroupVersionResource, error) {\n\terrors := []error{}\n\tfor _, t := range m.MultiRESTMapper {\n\t\tret, err := t.ResourceFor(resource)\n\t\tif err == nil {\n\t\t\treturn ret, nil\n\t\t}\n\t\terrors = append(errors, err)\n\t}\n\n\treturn schema.GroupVersionResource{}, collapseAggregateErrors(errors)\n}","line":{"from":40,"to":51}} {"id":100014577,"name":"KindFor","signature":"func (m FirstHitRESTMapper) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/firsthit_restmapper.go","code":"func (m FirstHitRESTMapper) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) {\n\terrors := []error{}\n\tfor _, t := range m.MultiRESTMapper {\n\t\tret, err := t.KindFor(resource)\n\t\tif err == nil {\n\t\t\treturn ret, nil\n\t\t}\n\t\terrors = append(errors, err)\n\t}\n\n\treturn schema.GroupVersionKind{}, collapseAggregateErrors(errors)\n}","line":{"from":53,"to":64}} {"id":100014578,"name":"RESTMapping","signature":"func (m FirstHitRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (*RESTMapping, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/firsthit_restmapper.go","code":"// RESTMapping provides the REST mapping for the resource based on the\n// kind and version. This implementation supports multiple REST schemas and\n// return the first match.\nfunc (m FirstHitRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (*RESTMapping, error) {\n\terrors := []error{}\n\tfor _, t := range m.MultiRESTMapper {\n\t\tret, err := t.RESTMapping(gk, versions...)\n\t\tif err == nil {\n\t\t\treturn ret, nil\n\t\t}\n\t\terrors = append(errors, err)\n\t}\n\n\treturn nil, collapseAggregateErrors(errors)\n}","line":{"from":66,"to":80}} {"id":100014579,"name":"Reset","signature":"func (m FirstHitRESTMapper) Reset()","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/firsthit_restmapper.go","code":"func (m FirstHitRESTMapper) Reset() {\n\tm.MultiRESTMapper.Reset()\n}","line":{"from":82,"to":84}} {"id":100014580,"name":"collapseAggregateErrors","signature":"func collapseAggregateErrors(errors []error) error","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/firsthit_restmapper.go","code":"// collapseAggregateErrors returns the minimal errors. it handles empty as nil, handles one item in a list\n// by returning the item, and collapses all NoMatchErrors to a single one (since they should all be the same)\nfunc collapseAggregateErrors(errors []error) error {\n\tif len(errors) == 0 {\n\t\treturn nil\n\t}\n\tif len(errors) == 1 {\n\t\treturn errors[0]\n\t}\n\n\tallNoMatchErrors := true\n\tfor _, err := range errors {\n\t\tallNoMatchErrors = allNoMatchErrors \u0026\u0026 IsNoMatchError(err)\n\t}\n\tif allNoMatchErrors {\n\t\treturn errors[0]\n\t}\n\n\treturn utilerrors.NewAggregate(errors)\n}","line":{"from":86,"to":105}} {"id":100014581,"name":"IsListType","signature":"func IsListType(obj runtime.Object) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/help.go","code":"// IsListType returns true if the provided Object has a slice called Items.\n// TODO: Replace the code in this check with an interface comparison by\n// creating and enforcing that lists implement a list accessor.\nfunc IsListType(obj runtime.Object) bool {\n\tswitch t := obj.(type) {\n\tcase runtime.Unstructured:\n\t\treturn t.IsList()\n\t}\n\tt := reflect.TypeOf(obj)\n\n\tisListCache.lock.RLock()\n\tok, exists := isListCache.byType[t]\n\tisListCache.lock.RUnlock()\n\n\tif !exists {\n\t\t_, err := getItemsPtr(obj)\n\t\tok = err == nil\n\n\t\t// cache only the first 1024 types\n\t\tisListCache.lock.Lock()\n\t\tif len(isListCache.byType) \u003c 1024 {\n\t\t\tisListCache.byType[t] = ok\n\t\t}\n\t\tisListCache.lock.Unlock()\n\t}\n\n\treturn ok\n}","line":{"from":41,"to":68}} {"id":100014582,"name":"GetItemsPtr","signature":"func GetItemsPtr(list runtime.Object) (interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/help.go","code":"// GetItemsPtr returns a pointer to the list object's Items member.\n// If 'list' doesn't have an Items member, it's not really a list type\n// and an error will be returned.\n// This function will either return a pointer to a slice, or an error, but not both.\n// TODO: this will be replaced with an interface in the future\nfunc GetItemsPtr(list runtime.Object) (interface{}, error) {\n\tobj, err := getItemsPtr(list)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%T is not a list: %v\", list, err)\n\t}\n\treturn obj, nil\n}","line":{"from":75,"to":86}} {"id":100014583,"name":"getItemsPtr","signature":"func getItemsPtr(list runtime.Object) (interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/help.go","code":"// getItemsPtr returns a pointer to the list object's Items member or an error.\nfunc getItemsPtr(list runtime.Object) (interface{}, error) {\n\tv, err := conversion.EnforcePtr(list)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\titems := v.FieldByName(\"Items\")\n\tif !items.IsValid() {\n\t\treturn nil, errExpectFieldItems\n\t}\n\tswitch items.Kind() {\n\tcase reflect.Interface, reflect.Pointer:\n\t\ttarget := reflect.TypeOf(items.Interface()).Elem()\n\t\tif target.Kind() != reflect.Slice {\n\t\t\treturn nil, errExpectSliceItems\n\t\t}\n\t\treturn items.Interface(), nil\n\tcase reflect.Slice:\n\t\treturn items.Addr().Interface(), nil\n\tdefault:\n\t\treturn nil, errExpectSliceItems\n\t}\n}","line":{"from":88,"to":111}} {"id":100014584,"name":"EachListItem","signature":"func EachListItem(obj runtime.Object, fn func(runtime.Object) error) error","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/help.go","code":"// EachListItem invokes fn on each runtime.Object in the list. Any error immediately terminates\n// the loop.\nfunc EachListItem(obj runtime.Object, fn func(runtime.Object) error) error {\n\tif unstructured, ok := obj.(runtime.Unstructured); ok {\n\t\treturn unstructured.EachListItem(fn)\n\t}\n\t// TODO: Change to an interface call?\n\titemsPtr, err := GetItemsPtr(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\titems, err := conversion.EnforcePtr(itemsPtr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlen := items.Len()\n\tif len == 0 {\n\t\treturn nil\n\t}\n\ttakeAddr := false\n\tif elemType := items.Type().Elem(); elemType.Kind() != reflect.Pointer \u0026\u0026 elemType.Kind() != reflect.Interface {\n\t\tif !items.Index(0).CanAddr() {\n\t\t\treturn fmt.Errorf(\"unable to take address of items in %T for EachListItem\", obj)\n\t\t}\n\t\ttakeAddr = true\n\t}\n\n\tfor i := 0; i \u003c len; i++ {\n\t\traw := items.Index(i)\n\t\tif takeAddr {\n\t\t\traw = raw.Addr()\n\t\t}\n\t\tswitch item := raw.Interface().(type) {\n\t\tcase *runtime.RawExtension:\n\t\t\tif err := fn(item.Object); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase runtime.Object:\n\t\t\tif err := fn(item); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tobj, ok := item.(runtime.Object)\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"%v: item[%v]: Expected object, got %#v(%s)\", obj, i, raw.Interface(), raw.Kind())\n\t\t\t}\n\t\t\tif err := fn(obj); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":113,"to":165}} {"id":100014585,"name":"ExtractList","signature":"func ExtractList(obj runtime.Object) ([]runtime.Object, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/help.go","code":"// ExtractList returns obj's Items element as an array of runtime.Objects.\n// Returns an error if obj is not a List type (does not have an Items member).\nfunc ExtractList(obj runtime.Object) ([]runtime.Object, error) {\n\titemsPtr, err := GetItemsPtr(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\titems, err := conversion.EnforcePtr(itemsPtr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlist := make([]runtime.Object, items.Len())\n\tfor i := range list {\n\t\traw := items.Index(i)\n\t\tswitch item := raw.Interface().(type) {\n\t\tcase runtime.RawExtension:\n\t\t\tswitch {\n\t\t\tcase item.Object != nil:\n\t\t\t\tlist[i] = item.Object\n\t\t\tcase item.Raw != nil:\n\t\t\t\t// TODO: Set ContentEncoding and ContentType correctly.\n\t\t\t\tlist[i] = \u0026runtime.Unknown{Raw: item.Raw}\n\t\t\tdefault:\n\t\t\t\tlist[i] = nil\n\t\t\t}\n\t\tcase runtime.Object:\n\t\t\tlist[i] = item\n\t\tdefault:\n\t\t\tvar found bool\n\t\t\tif list[i], found = raw.Addr().Interface().(runtime.Object); !found {\n\t\t\t\treturn nil, fmt.Errorf(\"%v: item[%v]: Expected object, got %#v(%s)\", obj, i, raw.Interface(), raw.Kind())\n\t\t\t}\n\t\t}\n\t}\n\treturn list, nil\n}","line":{"from":167,"to":202}} {"id":100014586,"name":"LenList","signature":"func LenList(list runtime.Object) int","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/help.go","code":"// LenList returns the length of this list or 0 if it is not a list.\nfunc LenList(list runtime.Object) int {\n\titemsPtr, err := GetItemsPtr(list)\n\tif err != nil {\n\t\treturn 0\n\t}\n\titems, err := conversion.EnforcePtr(itemsPtr)\n\tif err != nil {\n\t\treturn 0\n\t}\n\treturn items.Len()\n}","line":{"from":207,"to":218}} {"id":100014587,"name":"SetList","signature":"func SetList(list runtime.Object, objects []runtime.Object) error","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/help.go","code":"// SetList sets the given list object's Items member have the elements given in\n// objects.\n// Returns an error if list is not a List type (does not have an Items member),\n// or if any of the objects are not of the right type.\nfunc SetList(list runtime.Object, objects []runtime.Object) error {\n\titemsPtr, err := GetItemsPtr(list)\n\tif err != nil {\n\t\treturn err\n\t}\n\titems, err := conversion.EnforcePtr(itemsPtr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif items.Type() == objectSliceType {\n\t\titems.Set(reflect.ValueOf(objects))\n\t\treturn nil\n\t}\n\tslice := reflect.MakeSlice(items.Type(), len(objects), len(objects))\n\tfor i := range objects {\n\t\tdest := slice.Index(i)\n\t\tif dest.Type() == reflect.TypeOf(runtime.RawExtension{}) {\n\t\t\tdest = dest.FieldByName(\"Object\")\n\t\t}\n\n\t\t// check to see if you're directly assignable\n\t\tif reflect.TypeOf(objects[i]).AssignableTo(dest.Type()) {\n\t\t\tdest.Set(reflect.ValueOf(objects[i]))\n\t\t\tcontinue\n\t\t}\n\n\t\tsrc, err := conversion.EnforcePtr(objects[i])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif src.Type().AssignableTo(dest.Type()) {\n\t\t\tdest.Set(src)\n\t\t} else if src.Type().ConvertibleTo(dest.Type()) {\n\t\t\tdest.Set(src.Convert(dest.Type()))\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"item[%d]: can't assign or convert %v into %v\", i, src.Type(), dest.Type())\n\t\t}\n\t}\n\titems.Set(slice)\n\treturn nil\n}","line":{"from":220,"to":264}} {"id":100014588,"name":"NewLazyRESTMapperLoader","signature":"func NewLazyRESTMapperLoader(fn func() (RESTMapper, error)) RESTMapper","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/lazy.go","code":"// NewLazyRESTMapperLoader handles unrecoverable errors when creating a RESTMapper / ObjectTyper by\n// returning those initialization errors when the interface methods are invoked. This defers the\n// initialization and any server calls until a client actually needs to perform the action.\nfunc NewLazyRESTMapperLoader(fn func() (RESTMapper, error)) RESTMapper {\n\tobj := \u0026lazyObject{loader: fn}\n\treturn obj\n}","line":{"from":35,"to":41}} {"id":100014589,"name":"init","signature":"func (o *lazyObject) init() error","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/lazy.go","code":"// init lazily loads the mapper and typer, returning an error if initialization has failed.\nfunc (o *lazyObject) init() error {\n\to.lock.Lock()\n\tdefer o.lock.Unlock()\n\tif o.loaded {\n\t\treturn o.err\n\t}\n\to.mapper, o.err = o.loader()\n\to.loaded = true\n\treturn o.err\n}","line":{"from":43,"to":53}} {"id":100014590,"name":"KindFor","signature":"func (o *lazyObject) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/lazy.go","code":"func (o *lazyObject) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) {\n\tif err := o.init(); err != nil {\n\t\treturn schema.GroupVersionKind{}, err\n\t}\n\treturn o.mapper.KindFor(resource)\n}","line":{"from":57,"to":62}} {"id":100014591,"name":"KindsFor","signature":"func (o *lazyObject) KindsFor(resource schema.GroupVersionResource) ([]schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/lazy.go","code":"func (o *lazyObject) KindsFor(resource schema.GroupVersionResource) ([]schema.GroupVersionKind, error) {\n\tif err := o.init(); err != nil {\n\t\treturn []schema.GroupVersionKind{}, err\n\t}\n\treturn o.mapper.KindsFor(resource)\n}","line":{"from":64,"to":69}} {"id":100014592,"name":"ResourceFor","signature":"func (o *lazyObject) ResourceFor(input schema.GroupVersionResource) (schema.GroupVersionResource, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/lazy.go","code":"func (o *lazyObject) ResourceFor(input schema.GroupVersionResource) (schema.GroupVersionResource, error) {\n\tif err := o.init(); err != nil {\n\t\treturn schema.GroupVersionResource{}, err\n\t}\n\treturn o.mapper.ResourceFor(input)\n}","line":{"from":71,"to":76}} {"id":100014593,"name":"ResourcesFor","signature":"func (o *lazyObject) ResourcesFor(input schema.GroupVersionResource) ([]schema.GroupVersionResource, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/lazy.go","code":"func (o *lazyObject) ResourcesFor(input schema.GroupVersionResource) ([]schema.GroupVersionResource, error) {\n\tif err := o.init(); err != nil {\n\t\treturn []schema.GroupVersionResource{}, err\n\t}\n\treturn o.mapper.ResourcesFor(input)\n}","line":{"from":78,"to":83}} {"id":100014594,"name":"RESTMapping","signature":"func (o *lazyObject) RESTMapping(gk schema.GroupKind, versions ...string) (*RESTMapping, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/lazy.go","code":"func (o *lazyObject) RESTMapping(gk schema.GroupKind, versions ...string) (*RESTMapping, error) {\n\tif err := o.init(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn o.mapper.RESTMapping(gk, versions...)\n}","line":{"from":85,"to":90}} {"id":100014595,"name":"RESTMappings","signature":"func (o *lazyObject) RESTMappings(gk schema.GroupKind, versions ...string) ([]*RESTMapping, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/lazy.go","code":"func (o *lazyObject) RESTMappings(gk schema.GroupKind, versions ...string) ([]*RESTMapping, error) {\n\tif err := o.init(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn o.mapper.RESTMappings(gk, versions...)\n}","line":{"from":92,"to":97}} {"id":100014596,"name":"ResourceSingularizer","signature":"func (o *lazyObject) ResourceSingularizer(resource string) (singular string, err error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/lazy.go","code":"func (o *lazyObject) ResourceSingularizer(resource string) (singular string, err error) {\n\tif err := o.init(); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn o.mapper.ResourceSingularizer(resource)\n}","line":{"from":99,"to":104}} {"id":100014597,"name":"Reset","signature":"func (o *lazyObject) Reset()","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/lazy.go","code":"func (o *lazyObject) Reset() {\n\to.lock.Lock()\n\tdefer o.lock.Unlock()\n\tif o.loaded \u0026\u0026 o.err == nil {\n\t\tMaybeResetRESTMapper(o.mapper)\n\t}\n}","line":{"from":106,"to":112}} {"id":100014598,"name":"CommonAccessor","signature":"func CommonAccessor(obj interface{}) (metav1.Common, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"// CommonAccessor returns a Common interface for the provided object or an error if the object does\n// not provide List.\nfunc CommonAccessor(obj interface{}) (metav1.Common, error) {\n\tswitch t := obj.(type) {\n\tcase List:\n\t\treturn t, nil\n\tcase ListMetaAccessor:\n\t\tif m := t.GetListMeta(); m != nil {\n\t\t\treturn m, nil\n\t\t}\n\t\treturn nil, errNotCommon\n\tcase metav1.ListMetaAccessor:\n\t\tif m := t.GetListMeta(); m != nil {\n\t\t\treturn m, nil\n\t\t}\n\t\treturn nil, errNotCommon\n\tcase metav1.Object:\n\t\treturn t, nil\n\tcase metav1.ObjectMetaAccessor:\n\t\tif m := t.GetObjectMeta(); m != nil {\n\t\t\treturn m, nil\n\t\t}\n\t\treturn nil, errNotCommon\n\tdefault:\n\t\treturn nil, errNotCommon\n\t}\n}","line":{"from":37,"to":63}} {"id":100014599,"name":"ListAccessor","signature":"func ListAccessor(obj interface{}) (List, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"// ListAccessor returns a List interface for the provided object or an error if the object does\n// not provide List.\n// IMPORTANT: Objects are NOT a superset of lists. Do not use this check to determine whether an\n// object *is* a List.\nfunc ListAccessor(obj interface{}) (List, error) {\n\tswitch t := obj.(type) {\n\tcase List:\n\t\treturn t, nil\n\tcase ListMetaAccessor:\n\t\tif m := t.GetListMeta(); m != nil {\n\t\t\treturn m, nil\n\t\t}\n\t\treturn nil, errNotList\n\tcase metav1.ListMetaAccessor:\n\t\tif m := t.GetListMeta(); m != nil {\n\t\t\treturn m, nil\n\t\t}\n\t\treturn nil, errNotList\n\tdefault:\n\t\treturn nil, errNotList\n\t}\n}","line":{"from":65,"to":86}} {"id":100014600,"name":"Accessor","signature":"func Accessor(obj interface{}) (metav1.Object, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"// Accessor takes an arbitrary object pointer and returns meta.Interface.\n// obj must be a pointer to an API type. An error is returned if the minimum\n// required fields are missing. Fields that are not required return the default\n// value and are a no-op if set.\nfunc Accessor(obj interface{}) (metav1.Object, error) {\n\tswitch t := obj.(type) {\n\tcase metav1.Object:\n\t\treturn t, nil\n\tcase metav1.ObjectMetaAccessor:\n\t\tif m := t.GetObjectMeta(); m != nil {\n\t\t\treturn m, nil\n\t\t}\n\t\treturn nil, errNotObject\n\tdefault:\n\t\treturn nil, errNotObject\n\t}\n}","line":{"from":92,"to":108}} {"id":100014601,"name":"AsPartialObjectMetadata","signature":"func AsPartialObjectMetadata(m metav1.Object) *metav1.PartialObjectMetadata","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"// AsPartialObjectMetadata takes the metav1 interface and returns a partial object.\n// TODO: consider making this solely a conversion action.\nfunc AsPartialObjectMetadata(m metav1.Object) *metav1.PartialObjectMetadata {\n\tswitch t := m.(type) {\n\tcase *metav1.ObjectMeta:\n\t\treturn \u0026metav1.PartialObjectMetadata{ObjectMeta: *t}\n\tdefault:\n\t\treturn \u0026metav1.PartialObjectMetadata{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: m.GetName(),\n\t\t\t\tGenerateName: m.GetGenerateName(),\n\t\t\t\tNamespace: m.GetNamespace(),\n\t\t\t\tSelfLink: m.GetSelfLink(),\n\t\t\t\tUID: m.GetUID(),\n\t\t\t\tResourceVersion: m.GetResourceVersion(),\n\t\t\t\tGeneration: m.GetGeneration(),\n\t\t\t\tCreationTimestamp: m.GetCreationTimestamp(),\n\t\t\t\tDeletionTimestamp: m.GetDeletionTimestamp(),\n\t\t\t\tDeletionGracePeriodSeconds: m.GetDeletionGracePeriodSeconds(),\n\t\t\t\tLabels: m.GetLabels(),\n\t\t\t\tAnnotations: m.GetAnnotations(),\n\t\t\t\tOwnerReferences: m.GetOwnerReferences(),\n\t\t\t\tFinalizers: m.GetFinalizers(),\n\t\t\t\tManagedFields: m.GetManagedFields(),\n\t\t\t},\n\t\t}\n\t}\n}","line":{"from":110,"to":137}} {"id":100014602,"name":"TypeAccessor","signature":"func TypeAccessor(obj interface{}) (Type, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"// TypeAccessor returns an interface that allows retrieving and modifying the APIVersion\n// and Kind of an in-memory internal object.\n// TODO: this interface is used to test code that does not have ObjectMeta or ListMeta\n// in round tripping (objects which can use apiVersion/kind, but do not fit the Kube\n// api conventions).\nfunc TypeAccessor(obj interface{}) (Type, error) {\n\tif typed, ok := obj.(runtime.Object); ok {\n\t\treturn objectAccessor{typed}, nil\n\t}\n\tv, err := conversion.EnforcePtr(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt := v.Type()\n\tif v.Kind() != reflect.Struct {\n\t\treturn nil, fmt.Errorf(\"expected struct, but got %v: %v (%#v)\", v.Kind(), t, v.Interface())\n\t}\n\n\ttypeMeta := v.FieldByName(\"TypeMeta\")\n\tif !typeMeta.IsValid() {\n\t\treturn nil, fmt.Errorf(\"struct %v lacks embedded TypeMeta type\", t)\n\t}\n\ta := \u0026genericAccessor{}\n\tif err := extractFromTypeMeta(typeMeta, a); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to find type fields on %#v: %v\", typeMeta, err)\n\t}\n\treturn a, nil\n}","line":{"from":139,"to":166}} {"id":100014603,"name":"GetKind","signature":"func (obj objectAccessor) GetKind() string","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (obj objectAccessor) GetKind() string {\n\treturn obj.GetObjectKind().GroupVersionKind().Kind\n}","line":{"from":172,"to":174}} {"id":100014604,"name":"SetKind","signature":"func (obj objectAccessor) SetKind(kind string)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (obj objectAccessor) SetKind(kind string) {\n\tgvk := obj.GetObjectKind().GroupVersionKind()\n\tgvk.Kind = kind\n\tobj.GetObjectKind().SetGroupVersionKind(gvk)\n}","line":{"from":176,"to":180}} {"id":100014605,"name":"GetAPIVersion","signature":"func (obj objectAccessor) GetAPIVersion() string","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (obj objectAccessor) GetAPIVersion() string {\n\treturn obj.GetObjectKind().GroupVersionKind().GroupVersion().String()\n}","line":{"from":182,"to":184}} {"id":100014606,"name":"SetAPIVersion","signature":"func (obj objectAccessor) SetAPIVersion(version string)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (obj objectAccessor) SetAPIVersion(version string) {\n\tgvk := obj.GetObjectKind().GroupVersionKind()\n\tgv, err := schema.ParseGroupVersion(version)\n\tif err != nil {\n\t\tgv = schema.GroupVersion{Version: version}\n\t}\n\tgvk.Group, gvk.Version = gv.Group, gv.Version\n\tobj.GetObjectKind().SetGroupVersionKind(gvk)\n}","line":{"from":186,"to":194}} {"id":100014607,"name":"NewAccessor","signature":"func NewAccessor() MetadataAccessor","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"// NewAccessor returns a MetadataAccessor that can retrieve\n// or manipulate resource version on objects derived from core API\n// metadata concepts.\nfunc NewAccessor() MetadataAccessor {\n\treturn resourceAccessor{}\n}","line":{"from":196,"to":201}} {"id":100014608,"name":"Kind","signature":"func (resourceAccessor) Kind(obj runtime.Object) (string, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (resourceAccessor) Kind(obj runtime.Object) (string, error) {\n\treturn objectAccessor{obj}.GetKind(), nil\n}","line":{"from":206,"to":208}} {"id":100014609,"name":"SetKind","signature":"func (resourceAccessor) SetKind(obj runtime.Object, kind string) error","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (resourceAccessor) SetKind(obj runtime.Object, kind string) error {\n\tobjectAccessor{obj}.SetKind(kind)\n\treturn nil\n}","line":{"from":210,"to":213}} {"id":100014610,"name":"APIVersion","signature":"func (resourceAccessor) APIVersion(obj runtime.Object) (string, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (resourceAccessor) APIVersion(obj runtime.Object) (string, error) {\n\treturn objectAccessor{obj}.GetAPIVersion(), nil\n}","line":{"from":215,"to":217}} {"id":100014611,"name":"SetAPIVersion","signature":"func (resourceAccessor) SetAPIVersion(obj runtime.Object, version string) error","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (resourceAccessor) SetAPIVersion(obj runtime.Object, version string) error {\n\tobjectAccessor{obj}.SetAPIVersion(version)\n\treturn nil\n}","line":{"from":219,"to":222}} {"id":100014612,"name":"Namespace","signature":"func (resourceAccessor) Namespace(obj runtime.Object) (string, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (resourceAccessor) Namespace(obj runtime.Object) (string, error) {\n\taccessor, err := Accessor(obj)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn accessor.GetNamespace(), nil\n}","line":{"from":224,"to":230}} {"id":100014613,"name":"SetNamespace","signature":"func (resourceAccessor) SetNamespace(obj runtime.Object, namespace string) error","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (resourceAccessor) SetNamespace(obj runtime.Object, namespace string) error {\n\taccessor, err := Accessor(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\taccessor.SetNamespace(namespace)\n\treturn nil\n}","line":{"from":232,"to":239}} {"id":100014614,"name":"Name","signature":"func (resourceAccessor) Name(obj runtime.Object) (string, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (resourceAccessor) Name(obj runtime.Object) (string, error) {\n\taccessor, err := Accessor(obj)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn accessor.GetName(), nil\n}","line":{"from":241,"to":247}} {"id":100014615,"name":"SetName","signature":"func (resourceAccessor) SetName(obj runtime.Object, name string) error","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (resourceAccessor) SetName(obj runtime.Object, name string) error {\n\taccessor, err := Accessor(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\taccessor.SetName(name)\n\treturn nil\n}","line":{"from":249,"to":256}} {"id":100014616,"name":"GenerateName","signature":"func (resourceAccessor) GenerateName(obj runtime.Object) (string, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (resourceAccessor) GenerateName(obj runtime.Object) (string, error) {\n\taccessor, err := Accessor(obj)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn accessor.GetGenerateName(), nil\n}","line":{"from":258,"to":264}} {"id":100014617,"name":"SetGenerateName","signature":"func (resourceAccessor) SetGenerateName(obj runtime.Object, name string) error","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (resourceAccessor) SetGenerateName(obj runtime.Object, name string) error {\n\taccessor, err := Accessor(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\taccessor.SetGenerateName(name)\n\treturn nil\n}","line":{"from":266,"to":273}} {"id":100014618,"name":"UID","signature":"func (resourceAccessor) UID(obj runtime.Object) (types.UID, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (resourceAccessor) UID(obj runtime.Object) (types.UID, error) {\n\taccessor, err := Accessor(obj)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn accessor.GetUID(), nil\n}","line":{"from":275,"to":281}} {"id":100014619,"name":"SetUID","signature":"func (resourceAccessor) SetUID(obj runtime.Object, uid types.UID) error","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (resourceAccessor) SetUID(obj runtime.Object, uid types.UID) error {\n\taccessor, err := Accessor(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\taccessor.SetUID(uid)\n\treturn nil\n}","line":{"from":283,"to":290}} {"id":100014620,"name":"SelfLink","signature":"func (resourceAccessor) SelfLink(obj runtime.Object) (string, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (resourceAccessor) SelfLink(obj runtime.Object) (string, error) {\n\taccessor, err := CommonAccessor(obj)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn accessor.GetSelfLink(), nil\n}","line":{"from":292,"to":298}} {"id":100014621,"name":"SetSelfLink","signature":"func (resourceAccessor) SetSelfLink(obj runtime.Object, selfLink string) error","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (resourceAccessor) SetSelfLink(obj runtime.Object, selfLink string) error {\n\taccessor, err := CommonAccessor(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\taccessor.SetSelfLink(selfLink)\n\treturn nil\n}","line":{"from":300,"to":307}} {"id":100014622,"name":"Labels","signature":"func (resourceAccessor) Labels(obj runtime.Object) (map[string]string, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (resourceAccessor) Labels(obj runtime.Object) (map[string]string, error) {\n\taccessor, err := Accessor(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn accessor.GetLabels(), nil\n}","line":{"from":309,"to":315}} {"id":100014623,"name":"SetLabels","signature":"func (resourceAccessor) SetLabels(obj runtime.Object, labels map[string]string) error","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (resourceAccessor) SetLabels(obj runtime.Object, labels map[string]string) error {\n\taccessor, err := Accessor(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\taccessor.SetLabels(labels)\n\treturn nil\n}","line":{"from":317,"to":324}} {"id":100014624,"name":"Annotations","signature":"func (resourceAccessor) Annotations(obj runtime.Object) (map[string]string, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (resourceAccessor) Annotations(obj runtime.Object) (map[string]string, error) {\n\taccessor, err := Accessor(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn accessor.GetAnnotations(), nil\n}","line":{"from":326,"to":332}} {"id":100014625,"name":"SetAnnotations","signature":"func (resourceAccessor) SetAnnotations(obj runtime.Object, annotations map[string]string) error","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (resourceAccessor) SetAnnotations(obj runtime.Object, annotations map[string]string) error {\n\taccessor, err := Accessor(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\taccessor.SetAnnotations(annotations)\n\treturn nil\n}","line":{"from":334,"to":341}} {"id":100014626,"name":"ResourceVersion","signature":"func (resourceAccessor) ResourceVersion(obj runtime.Object) (string, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (resourceAccessor) ResourceVersion(obj runtime.Object) (string, error) {\n\taccessor, err := CommonAccessor(obj)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn accessor.GetResourceVersion(), nil\n}","line":{"from":343,"to":349}} {"id":100014627,"name":"SetResourceVersion","signature":"func (resourceAccessor) SetResourceVersion(obj runtime.Object, version string) error","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (resourceAccessor) SetResourceVersion(obj runtime.Object, version string) error {\n\taccessor, err := CommonAccessor(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\taccessor.SetResourceVersion(version)\n\treturn nil\n}","line":{"from":351,"to":358}} {"id":100014628,"name":"Continue","signature":"func (resourceAccessor) Continue(obj runtime.Object) (string, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (resourceAccessor) Continue(obj runtime.Object) (string, error) {\n\taccessor, err := ListAccessor(obj)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn accessor.GetContinue(), nil\n}","line":{"from":360,"to":366}} {"id":100014629,"name":"SetContinue","signature":"func (resourceAccessor) SetContinue(obj runtime.Object, version string) error","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (resourceAccessor) SetContinue(obj runtime.Object, version string) error {\n\taccessor, err := ListAccessor(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\taccessor.SetContinue(version)\n\treturn nil\n}","line":{"from":368,"to":375}} {"id":100014630,"name":"extractFromOwnerReference","signature":"func extractFromOwnerReference(v reflect.Value, o *metav1.OwnerReference) error","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"// extractFromOwnerReference extracts v to o. v is the OwnerReferences field of an object.\nfunc extractFromOwnerReference(v reflect.Value, o *metav1.OwnerReference) error {\n\tif err := runtime.Field(v, \"APIVersion\", \u0026o.APIVersion); err != nil {\n\t\treturn err\n\t}\n\tif err := runtime.Field(v, \"Kind\", \u0026o.Kind); err != nil {\n\t\treturn err\n\t}\n\tif err := runtime.Field(v, \"Name\", \u0026o.Name); err != nil {\n\t\treturn err\n\t}\n\tif err := runtime.Field(v, \"UID\", \u0026o.UID); err != nil {\n\t\treturn err\n\t}\n\tvar controllerPtr *bool\n\tif err := runtime.Field(v, \"Controller\", \u0026controllerPtr); err != nil {\n\t\treturn err\n\t}\n\tif controllerPtr != nil {\n\t\tcontroller := *controllerPtr\n\t\to.Controller = \u0026controller\n\t}\n\tvar blockOwnerDeletionPtr *bool\n\tif err := runtime.Field(v, \"BlockOwnerDeletion\", \u0026blockOwnerDeletionPtr); err != nil {\n\t\treturn err\n\t}\n\tif blockOwnerDeletionPtr != nil {\n\t\tblock := *blockOwnerDeletionPtr\n\t\to.BlockOwnerDeletion = \u0026block\n\t}\n\treturn nil\n}","line":{"from":377,"to":408}} {"id":100014631,"name":"setOwnerReference","signature":"func setOwnerReference(v reflect.Value, o *metav1.OwnerReference) error","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"// setOwnerReference sets v to o. v is the OwnerReferences field of an object.\nfunc setOwnerReference(v reflect.Value, o *metav1.OwnerReference) error {\n\tif err := runtime.SetField(o.APIVersion, v, \"APIVersion\"); err != nil {\n\t\treturn err\n\t}\n\tif err := runtime.SetField(o.Kind, v, \"Kind\"); err != nil {\n\t\treturn err\n\t}\n\tif err := runtime.SetField(o.Name, v, \"Name\"); err != nil {\n\t\treturn err\n\t}\n\tif err := runtime.SetField(o.UID, v, \"UID\"); err != nil {\n\t\treturn err\n\t}\n\tif o.Controller != nil {\n\t\tcontroller := *(o.Controller)\n\t\tif err := runtime.SetField(\u0026controller, v, \"Controller\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif o.BlockOwnerDeletion != nil {\n\t\tblock := *(o.BlockOwnerDeletion)\n\t\tif err := runtime.SetField(\u0026block, v, \"BlockOwnerDeletion\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":410,"to":437}} {"id":100014632,"name":"GetNamespace","signature":"func (a genericAccessor) GetNamespace() string","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) GetNamespace() string {\n\tif a.namespace == nil {\n\t\treturn \"\"\n\t}\n\treturn *a.namespace\n}","line":{"from":458,"to":463}} {"id":100014633,"name":"SetNamespace","signature":"func (a genericAccessor) SetNamespace(namespace string)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) SetNamespace(namespace string) {\n\tif a.namespace == nil {\n\t\treturn\n\t}\n\t*a.namespace = namespace\n}","line":{"from":465,"to":470}} {"id":100014634,"name":"GetName","signature":"func (a genericAccessor) GetName() string","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) GetName() string {\n\tif a.name == nil {\n\t\treturn \"\"\n\t}\n\treturn *a.name\n}","line":{"from":472,"to":477}} {"id":100014635,"name":"SetName","signature":"func (a genericAccessor) SetName(name string)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) SetName(name string) {\n\tif a.name == nil {\n\t\treturn\n\t}\n\t*a.name = name\n}","line":{"from":479,"to":484}} {"id":100014636,"name":"GetGenerateName","signature":"func (a genericAccessor) GetGenerateName() string","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) GetGenerateName() string {\n\tif a.generateName == nil {\n\t\treturn \"\"\n\t}\n\treturn *a.generateName\n}","line":{"from":486,"to":491}} {"id":100014637,"name":"SetGenerateName","signature":"func (a genericAccessor) SetGenerateName(generateName string)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) SetGenerateName(generateName string) {\n\tif a.generateName == nil {\n\t\treturn\n\t}\n\t*a.generateName = generateName\n}","line":{"from":493,"to":498}} {"id":100014638,"name":"GetUID","signature":"func (a genericAccessor) GetUID() types.UID","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) GetUID() types.UID {\n\tif a.uid == nil {\n\t\treturn \"\"\n\t}\n\treturn *a.uid\n}","line":{"from":500,"to":505}} {"id":100014639,"name":"SetUID","signature":"func (a genericAccessor) SetUID(uid types.UID)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) SetUID(uid types.UID) {\n\tif a.uid == nil {\n\t\treturn\n\t}\n\t*a.uid = uid\n}","line":{"from":507,"to":512}} {"id":100014640,"name":"GetAPIVersion","signature":"func (a genericAccessor) GetAPIVersion() string","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) GetAPIVersion() string {\n\treturn *a.apiVersion\n}","line":{"from":514,"to":516}} {"id":100014641,"name":"SetAPIVersion","signature":"func (a genericAccessor) SetAPIVersion(version string)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) SetAPIVersion(version string) {\n\t*a.apiVersion = version\n}","line":{"from":518,"to":520}} {"id":100014642,"name":"GetKind","signature":"func (a genericAccessor) GetKind() string","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) GetKind() string {\n\treturn *a.kind\n}","line":{"from":522,"to":524}} {"id":100014643,"name":"SetKind","signature":"func (a genericAccessor) SetKind(kind string)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) SetKind(kind string) {\n\t*a.kind = kind\n}","line":{"from":526,"to":528}} {"id":100014644,"name":"GetResourceVersion","signature":"func (a genericAccessor) GetResourceVersion() string","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) GetResourceVersion() string {\n\treturn *a.resourceVersion\n}","line":{"from":530,"to":532}} {"id":100014645,"name":"SetResourceVersion","signature":"func (a genericAccessor) SetResourceVersion(version string)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) SetResourceVersion(version string) {\n\t*a.resourceVersion = version\n}","line":{"from":534,"to":536}} {"id":100014646,"name":"GetSelfLink","signature":"func (a genericAccessor) GetSelfLink() string","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) GetSelfLink() string {\n\treturn *a.selfLink\n}","line":{"from":538,"to":540}} {"id":100014647,"name":"SetSelfLink","signature":"func (a genericAccessor) SetSelfLink(selfLink string)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) SetSelfLink(selfLink string) {\n\t*a.selfLink = selfLink\n}","line":{"from":542,"to":544}} {"id":100014648,"name":"GetCreationTimestamp","signature":"func (a genericAccessor) GetCreationTimestamp() metav1.Time","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) GetCreationTimestamp() metav1.Time {\n\treturn *a.creationTimestamp\n}","line":{"from":546,"to":548}} {"id":100014649,"name":"SetCreationTimestamp","signature":"func (a genericAccessor) SetCreationTimestamp(timestamp metav1.Time)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) SetCreationTimestamp(timestamp metav1.Time) {\n\t*a.creationTimestamp = timestamp\n}","line":{"from":550,"to":552}} {"id":100014650,"name":"GetDeletionTimestamp","signature":"func (a genericAccessor) GetDeletionTimestamp() *metav1.Time","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) GetDeletionTimestamp() *metav1.Time {\n\treturn *a.deletionTimestamp\n}","line":{"from":554,"to":556}} {"id":100014651,"name":"SetDeletionTimestamp","signature":"func (a genericAccessor) SetDeletionTimestamp(timestamp *metav1.Time)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) SetDeletionTimestamp(timestamp *metav1.Time) {\n\t*a.deletionTimestamp = timestamp\n}","line":{"from":558,"to":560}} {"id":100014652,"name":"GetLabels","signature":"func (a genericAccessor) GetLabels() map[string]string","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) GetLabels() map[string]string {\n\tif a.labels == nil {\n\t\treturn nil\n\t}\n\treturn *a.labels\n}","line":{"from":562,"to":567}} {"id":100014653,"name":"SetLabels","signature":"func (a genericAccessor) SetLabels(labels map[string]string)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) SetLabels(labels map[string]string) {\n\t*a.labels = labels\n}","line":{"from":569,"to":571}} {"id":100014654,"name":"GetAnnotations","signature":"func (a genericAccessor) GetAnnotations() map[string]string","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) GetAnnotations() map[string]string {\n\tif a.annotations == nil {\n\t\treturn nil\n\t}\n\treturn *a.annotations\n}","line":{"from":573,"to":578}} {"id":100014655,"name":"SetAnnotations","signature":"func (a genericAccessor) SetAnnotations(annotations map[string]string)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) SetAnnotations(annotations map[string]string) {\n\tif a.annotations == nil {\n\t\temptyAnnotations := make(map[string]string)\n\t\ta.annotations = \u0026emptyAnnotations\n\t}\n\t*a.annotations = annotations\n}","line":{"from":580,"to":586}} {"id":100014656,"name":"GetFinalizers","signature":"func (a genericAccessor) GetFinalizers() []string","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) GetFinalizers() []string {\n\tif a.finalizers == nil {\n\t\treturn nil\n\t}\n\treturn *a.finalizers\n}","line":{"from":588,"to":593}} {"id":100014657,"name":"SetFinalizers","signature":"func (a genericAccessor) SetFinalizers(finalizers []string)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) SetFinalizers(finalizers []string) {\n\t*a.finalizers = finalizers\n}","line":{"from":595,"to":597}} {"id":100014658,"name":"GetOwnerReferences","signature":"func (a genericAccessor) GetOwnerReferences() []metav1.OwnerReference","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) GetOwnerReferences() []metav1.OwnerReference {\n\tvar ret []metav1.OwnerReference\n\ts := a.ownerReferences\n\tif s.Kind() != reflect.Pointer || s.Elem().Kind() != reflect.Slice {\n\t\tklog.Errorf(\"expect %v to be a pointer to slice\", s)\n\t\treturn ret\n\t}\n\ts = s.Elem()\n\t// Set the capacity to one element greater to avoid copy if the caller later append an element.\n\tret = make([]metav1.OwnerReference, s.Len(), s.Len()+1)\n\tfor i := 0; i \u003c s.Len(); i++ {\n\t\tif err := extractFromOwnerReference(s.Index(i), \u0026ret[i]); err != nil {\n\t\t\tklog.Errorf(\"extractFromOwnerReference failed: %v\", err)\n\t\t\treturn ret\n\t\t}\n\t}\n\treturn ret\n}","line":{"from":599,"to":616}} {"id":100014659,"name":"SetOwnerReferences","signature":"func (a genericAccessor) SetOwnerReferences(references []metav1.OwnerReference)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"func (a genericAccessor) SetOwnerReferences(references []metav1.OwnerReference) {\n\ts := a.ownerReferences\n\tif s.Kind() != reflect.Pointer || s.Elem().Kind() != reflect.Slice {\n\t\tklog.Errorf(\"expect %v to be a pointer to slice\", s)\n\t}\n\ts = s.Elem()\n\tnewReferences := reflect.MakeSlice(s.Type(), len(references), len(references))\n\tfor i := 0; i \u003c len(references); i++ {\n\t\tif err := setOwnerReference(newReferences.Index(i), \u0026references[i]); err != nil {\n\t\t\tklog.Errorf(\"setOwnerReference failed: %v\", err)\n\t\t\treturn\n\t\t}\n\t}\n\ts.Set(newReferences)\n}","line":{"from":618,"to":632}} {"id":100014660,"name":"extractFromTypeMeta","signature":"func extractFromTypeMeta(v reflect.Value, a *genericAccessor) error","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/meta.go","code":"// extractFromTypeMeta extracts pointers to version and kind fields from an object\nfunc extractFromTypeMeta(v reflect.Value, a *genericAccessor) error {\n\tif err := runtime.FieldPtr(v, \"APIVersion\", \u0026a.apiVersion); err != nil {\n\t\treturn err\n\t}\n\tif err := runtime.FieldPtr(v, \"Kind\", \u0026a.kind); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":634,"to":643}} {"id":100014661,"name":"String","signature":"func (m MultiRESTMapper) String() string","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/multirestmapper.go","code":"func (m MultiRESTMapper) String() string {\n\tnested := make([]string, 0, len(m))\n\tfor _, t := range m {\n\t\tcurrString := fmt.Sprintf(\"%v\", t)\n\t\tsplitStrings := strings.Split(currString, \"\\n\")\n\t\tnested = append(nested, strings.Join(splitStrings, \"\\n\\t\"))\n\t}\n\n\treturn fmt.Sprintf(\"MultiRESTMapper{\\n\\t%s\\n}\", strings.Join(nested, \"\\n\\t\"))\n}","line":{"from":34,"to":43}} {"id":100014662,"name":"ResourceSingularizer","signature":"func (m MultiRESTMapper) ResourceSingularizer(resource string) (singular string, err error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/multirestmapper.go","code":"// ResourceSingularizer converts a REST resource name from plural to singular (e.g., from pods to pod)\n// This implementation supports multiple REST schemas and return the first match.\nfunc (m MultiRESTMapper) ResourceSingularizer(resource string) (singular string, err error) {\n\tfor _, t := range m {\n\t\tsingular, err = t.ResourceSingularizer(resource)\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}","line":{"from":45,"to":55}} {"id":100014663,"name":"ResourcesFor","signature":"func (m MultiRESTMapper) ResourcesFor(resource schema.GroupVersionResource) ([]schema.GroupVersionResource, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/multirestmapper.go","code":"func (m MultiRESTMapper) ResourcesFor(resource schema.GroupVersionResource) ([]schema.GroupVersionResource, error) {\n\tallGVRs := []schema.GroupVersionResource{}\n\tfor _, t := range m {\n\t\tgvrs, err := t.ResourcesFor(resource)\n\t\t// ignore \"no match\" errors, but any other error percolates back up\n\t\tif IsNoMatchError(err) {\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// walk the existing values to de-dup\n\t\tfor _, curr := range gvrs {\n\t\t\tfound := false\n\t\t\tfor _, existing := range allGVRs {\n\t\t\t\tif curr == existing {\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !found {\n\t\t\t\tallGVRs = append(allGVRs, curr)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(allGVRs) == 0 {\n\t\treturn nil, \u0026NoResourceMatchError{PartialResource: resource}\n\t}\n\n\treturn allGVRs, nil\n}","line":{"from":57,"to":90}} {"id":100014664,"name":"KindsFor","signature":"func (m MultiRESTMapper) KindsFor(resource schema.GroupVersionResource) (gvk []schema.GroupVersionKind, err error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/multirestmapper.go","code":"func (m MultiRESTMapper) KindsFor(resource schema.GroupVersionResource) (gvk []schema.GroupVersionKind, err error) {\n\tallGVKs := []schema.GroupVersionKind{}\n\tfor _, t := range m {\n\t\tgvks, err := t.KindsFor(resource)\n\t\t// ignore \"no match\" errors, but any other error percolates back up\n\t\tif IsNoMatchError(err) {\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// walk the existing values to de-dup\n\t\tfor _, curr := range gvks {\n\t\t\tfound := false\n\t\t\tfor _, existing := range allGVKs {\n\t\t\t\tif curr == existing {\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !found {\n\t\t\t\tallGVKs = append(allGVKs, curr)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(allGVKs) == 0 {\n\t\treturn nil, \u0026NoResourceMatchError{PartialResource: resource}\n\t}\n\n\treturn allGVKs, nil\n}","line":{"from":92,"to":125}} {"id":100014665,"name":"ResourceFor","signature":"func (m MultiRESTMapper) ResourceFor(resource schema.GroupVersionResource) (schema.GroupVersionResource, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/multirestmapper.go","code":"func (m MultiRESTMapper) ResourceFor(resource schema.GroupVersionResource) (schema.GroupVersionResource, error) {\n\tresources, err := m.ResourcesFor(resource)\n\tif err != nil {\n\t\treturn schema.GroupVersionResource{}, err\n\t}\n\tif len(resources) == 1 {\n\t\treturn resources[0], nil\n\t}\n\n\treturn schema.GroupVersionResource{}, \u0026AmbiguousResourceError{PartialResource: resource, MatchingResources: resources}\n}","line":{"from":127,"to":137}} {"id":100014666,"name":"KindFor","signature":"func (m MultiRESTMapper) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/multirestmapper.go","code":"func (m MultiRESTMapper) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) {\n\tkinds, err := m.KindsFor(resource)\n\tif err != nil {\n\t\treturn schema.GroupVersionKind{}, err\n\t}\n\tif len(kinds) == 1 {\n\t\treturn kinds[0], nil\n\t}\n\n\treturn schema.GroupVersionKind{}, \u0026AmbiguousResourceError{PartialResource: resource, MatchingKinds: kinds}\n}","line":{"from":139,"to":149}} {"id":100014667,"name":"RESTMapping","signature":"func (m MultiRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (*RESTMapping, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/multirestmapper.go","code":"// RESTMapping provides the REST mapping for the resource based on the\n// kind and version. This implementation supports multiple REST schemas and\n// return the first match.\nfunc (m MultiRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (*RESTMapping, error) {\n\tallMappings := []*RESTMapping{}\n\terrors := []error{}\n\n\tfor _, t := range m {\n\t\tcurrMapping, err := t.RESTMapping(gk, versions...)\n\t\t// ignore \"no match\" errors, but any other error percolates back up\n\t\tif IsNoMatchError(err) {\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\terrors = append(errors, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tallMappings = append(allMappings, currMapping)\n\t}\n\n\t// if we got exactly one mapping, then use it even if other requested failed\n\tif len(allMappings) == 1 {\n\t\treturn allMappings[0], nil\n\t}\n\tif len(allMappings) \u003e 1 {\n\t\tvar kinds []schema.GroupVersionKind\n\t\tfor _, m := range allMappings {\n\t\t\tkinds = append(kinds, m.GroupVersionKind)\n\t\t}\n\t\treturn nil, \u0026AmbiguousKindError{PartialKind: gk.WithVersion(\"\"), MatchingKinds: kinds}\n\t}\n\tif len(errors) \u003e 0 {\n\t\treturn nil, utilerrors.NewAggregate(errors)\n\t}\n\treturn nil, \u0026NoKindMatchError{GroupKind: gk, SearchedVersions: versions}\n}","line":{"from":151,"to":187}} {"id":100014668,"name":"RESTMappings","signature":"func (m MultiRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) ([]*RESTMapping, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/multirestmapper.go","code":"// RESTMappings returns all possible RESTMappings for the provided group kind, or an error\n// if the type is not recognized.\nfunc (m MultiRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) ([]*RESTMapping, error) {\n\tvar allMappings []*RESTMapping\n\tvar errors []error\n\n\tfor _, t := range m {\n\t\tcurrMappings, err := t.RESTMappings(gk, versions...)\n\t\t// ignore \"no match\" errors, but any other error percolates back up\n\t\tif IsNoMatchError(err) {\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\terrors = append(errors, err)\n\t\t\tcontinue\n\t\t}\n\t\tallMappings = append(allMappings, currMappings...)\n\t}\n\tif len(errors) \u003e 0 {\n\t\treturn nil, utilerrors.NewAggregate(errors)\n\t}\n\tif len(allMappings) == 0 {\n\t\treturn nil, \u0026NoKindMatchError{GroupKind: gk, SearchedVersions: versions}\n\t}\n\treturn allMappings, nil\n}","line":{"from":189,"to":214}} {"id":100014669,"name":"Reset","signature":"func (m MultiRESTMapper) Reset()","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/multirestmapper.go","code":"func (m MultiRESTMapper) Reset() {\n\tfor _, t := range m {\n\t\tMaybeResetRESTMapper(t)\n\t}\n}","line":{"from":216,"to":220}} {"id":100014670,"name":"String","signature":"func (m PriorityRESTMapper) String() string","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/priority.go","code":"func (m PriorityRESTMapper) String() string {\n\treturn fmt.Sprintf(\"PriorityRESTMapper{\\n\\t%v\\n\\t%v\\n\\t%v\\n}\", m.ResourcePriority, m.KindPriority, m.Delegate)\n}","line":{"from":55,"to":57}} {"id":100014671,"name":"ResourceFor","signature":"func (m PriorityRESTMapper) ResourceFor(partiallySpecifiedResource schema.GroupVersionResource) (schema.GroupVersionResource, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/priority.go","code":"// ResourceFor finds all resources, then passes them through the ResourcePriority patterns to find a single matching hit.\nfunc (m PriorityRESTMapper) ResourceFor(partiallySpecifiedResource schema.GroupVersionResource) (schema.GroupVersionResource, error) {\n\toriginalGVRs, originalErr := m.Delegate.ResourcesFor(partiallySpecifiedResource)\n\tif originalErr != nil \u0026\u0026 len(originalGVRs) == 0 {\n\t\treturn schema.GroupVersionResource{}, originalErr\n\t}\n\tif len(originalGVRs) == 1 {\n\t\treturn originalGVRs[0], originalErr\n\t}\n\n\tremainingGVRs := append([]schema.GroupVersionResource{}, originalGVRs...)\n\tfor _, pattern := range m.ResourcePriority {\n\t\tmatchedGVRs := []schema.GroupVersionResource{}\n\t\tfor _, gvr := range remainingGVRs {\n\t\t\tif resourceMatches(pattern, gvr) {\n\t\t\t\tmatchedGVRs = append(matchedGVRs, gvr)\n\t\t\t}\n\t\t}\n\n\t\tswitch len(matchedGVRs) {\n\t\tcase 0:\n\t\t\t// if you have no matches, then nothing matched this pattern just move to the next\n\t\t\tcontinue\n\t\tcase 1:\n\t\t\t// one match, return\n\t\t\treturn matchedGVRs[0], originalErr\n\t\tdefault:\n\t\t\t// more than one match, use the matched hits as the list moving to the next pattern.\n\t\t\t// this way you can have a series of selection criteria\n\t\t\tremainingGVRs = matchedGVRs\n\t\t}\n\t}\n\n\treturn schema.GroupVersionResource{}, \u0026AmbiguousResourceError{PartialResource: partiallySpecifiedResource, MatchingResources: originalGVRs}\n}","line":{"from":59,"to":93}} {"id":100014672,"name":"KindFor","signature":"func (m PriorityRESTMapper) KindFor(partiallySpecifiedResource schema.GroupVersionResource) (schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/priority.go","code":"// KindFor finds all kinds, then passes them through the KindPriority patterns to find a single matching hit.\nfunc (m PriorityRESTMapper) KindFor(partiallySpecifiedResource schema.GroupVersionResource) (schema.GroupVersionKind, error) {\n\toriginalGVKs, originalErr := m.Delegate.KindsFor(partiallySpecifiedResource)\n\tif originalErr != nil \u0026\u0026 len(originalGVKs) == 0 {\n\t\treturn schema.GroupVersionKind{}, originalErr\n\t}\n\tif len(originalGVKs) == 1 {\n\t\treturn originalGVKs[0], originalErr\n\t}\n\n\tremainingGVKs := append([]schema.GroupVersionKind{}, originalGVKs...)\n\tfor _, pattern := range m.KindPriority {\n\t\tmatchedGVKs := []schema.GroupVersionKind{}\n\t\tfor _, gvr := range remainingGVKs {\n\t\t\tif kindMatches(pattern, gvr) {\n\t\t\t\tmatchedGVKs = append(matchedGVKs, gvr)\n\t\t\t}\n\t\t}\n\n\t\tswitch len(matchedGVKs) {\n\t\tcase 0:\n\t\t\t// if you have no matches, then nothing matched this pattern just move to the next\n\t\t\tcontinue\n\t\tcase 1:\n\t\t\t// one match, return\n\t\t\treturn matchedGVKs[0], originalErr\n\t\tdefault:\n\t\t\t// more than one match, use the matched hits as the list moving to the next pattern.\n\t\t\t// this way you can have a series of selection criteria\n\t\t\tremainingGVKs = matchedGVKs\n\t\t}\n\t}\n\n\treturn schema.GroupVersionKind{}, \u0026AmbiguousResourceError{PartialResource: partiallySpecifiedResource, MatchingKinds: originalGVKs}\n}","line":{"from":95,"to":129}} {"id":100014673,"name":"resourceMatches","signature":"func resourceMatches(pattern schema.GroupVersionResource, resource schema.GroupVersionResource) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/priority.go","code":"func resourceMatches(pattern schema.GroupVersionResource, resource schema.GroupVersionResource) bool {\n\tif pattern.Group != AnyGroup \u0026\u0026 pattern.Group != resource.Group {\n\t\treturn false\n\t}\n\tif pattern.Version != AnyVersion \u0026\u0026 pattern.Version != resource.Version {\n\t\treturn false\n\t}\n\tif pattern.Resource != AnyResource \u0026\u0026 pattern.Resource != resource.Resource {\n\t\treturn false\n\t}\n\n\treturn true\n}","line":{"from":131,"to":143}} {"id":100014674,"name":"kindMatches","signature":"func kindMatches(pattern schema.GroupVersionKind, kind schema.GroupVersionKind) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/priority.go","code":"func kindMatches(pattern schema.GroupVersionKind, kind schema.GroupVersionKind) bool {\n\tif pattern.Group != AnyGroup \u0026\u0026 pattern.Group != kind.Group {\n\t\treturn false\n\t}\n\tif pattern.Version != AnyVersion \u0026\u0026 pattern.Version != kind.Version {\n\t\treturn false\n\t}\n\tif pattern.Kind != AnyKind \u0026\u0026 pattern.Kind != kind.Kind {\n\t\treturn false\n\t}\n\n\treturn true\n}","line":{"from":145,"to":157}} {"id":100014675,"name":"RESTMapping","signature":"func (m PriorityRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (mapping *RESTMapping, err error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/priority.go","code":"func (m PriorityRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (mapping *RESTMapping, err error) {\n\tmappings, originalErr := m.Delegate.RESTMappings(gk, versions...)\n\tif originalErr != nil \u0026\u0026 len(mappings) == 0 {\n\t\treturn nil, originalErr\n\t}\n\n\t// any versions the user provides take priority\n\tpriorities := m.KindPriority\n\tif len(versions) \u003e 0 {\n\t\tpriorities = make([]schema.GroupVersionKind, 0, len(m.KindPriority)+len(versions))\n\t\tfor _, version := range versions {\n\t\t\tgv := schema.GroupVersion{\n\t\t\t\tVersion: version,\n\t\t\t\tGroup: gk.Group,\n\t\t\t}\n\t\t\tpriorities = append(priorities, gv.WithKind(AnyKind))\n\t\t}\n\t\tpriorities = append(priorities, m.KindPriority...)\n\t}\n\n\tremaining := append([]*RESTMapping{}, mappings...)\n\tfor _, pattern := range priorities {\n\t\tvar matching []*RESTMapping\n\t\tfor _, m := range remaining {\n\t\t\tif kindMatches(pattern, m.GroupVersionKind) {\n\t\t\t\tmatching = append(matching, m)\n\t\t\t}\n\t\t}\n\n\t\tswitch len(matching) {\n\t\tcase 0:\n\t\t\t// if you have no matches, then nothing matched this pattern just move to the next\n\t\t\tcontinue\n\t\tcase 1:\n\t\t\t// one match, return\n\t\t\treturn matching[0], originalErr\n\t\tdefault:\n\t\t\t// more than one match, use the matched hits as the list moving to the next pattern.\n\t\t\t// this way you can have a series of selection criteria\n\t\t\tremaining = matching\n\t\t}\n\t}\n\tif len(remaining) == 1 {\n\t\treturn remaining[0], originalErr\n\t}\n\n\tvar kinds []schema.GroupVersionKind\n\tfor _, m := range mappings {\n\t\tkinds = append(kinds, m.GroupVersionKind)\n\t}\n\treturn nil, \u0026AmbiguousKindError{PartialKind: gk.WithVersion(\"\"), MatchingKinds: kinds}\n}","line":{"from":159,"to":210}} {"id":100014676,"name":"RESTMappings","signature":"func (m PriorityRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) ([]*RESTMapping, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/priority.go","code":"func (m PriorityRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) ([]*RESTMapping, error) {\n\treturn m.Delegate.RESTMappings(gk, versions...)\n}","line":{"from":212,"to":214}} {"id":100014677,"name":"ResourceSingularizer","signature":"func (m PriorityRESTMapper) ResourceSingularizer(resource string) (singular string, err error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/priority.go","code":"func (m PriorityRESTMapper) ResourceSingularizer(resource string) (singular string, err error) {\n\treturn m.Delegate.ResourceSingularizer(resource)\n}","line":{"from":216,"to":218}} {"id":100014678,"name":"ResourcesFor","signature":"func (m PriorityRESTMapper) ResourcesFor(partiallySpecifiedResource schema.GroupVersionResource) ([]schema.GroupVersionResource, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/priority.go","code":"func (m PriorityRESTMapper) ResourcesFor(partiallySpecifiedResource schema.GroupVersionResource) ([]schema.GroupVersionResource, error) {\n\treturn m.Delegate.ResourcesFor(partiallySpecifiedResource)\n}","line":{"from":220,"to":222}} {"id":100014679,"name":"KindsFor","signature":"func (m PriorityRESTMapper) KindsFor(partiallySpecifiedResource schema.GroupVersionResource) (gvk []schema.GroupVersionKind, err error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/priority.go","code":"func (m PriorityRESTMapper) KindsFor(partiallySpecifiedResource schema.GroupVersionResource) (gvk []schema.GroupVersionKind, err error) {\n\treturn m.Delegate.KindsFor(partiallySpecifiedResource)\n}","line":{"from":224,"to":226}} {"id":100014680,"name":"Reset","signature":"func (m PriorityRESTMapper) Reset()","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/priority.go","code":"func (m PriorityRESTMapper) Reset() {\n\tMaybeResetRESTMapper(m.Delegate)\n}","line":{"from":228,"to":230}} {"id":100014681,"name":"Name","signature":"func (r *restScope) Name() RESTScopeName","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/restmapper.go","code":"func (r *restScope) Name() RESTScopeName {\n\treturn r.name\n}","line":{"from":34,"to":36}} {"id":100014682,"name":"String","signature":"func (m *DefaultRESTMapper) String() string","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/restmapper.go","code":"func (m *DefaultRESTMapper) String() string {\n\tif m == nil {\n\t\treturn \"\u003cnil\u003e\"\n\t}\n\treturn fmt.Sprintf(\"DefaultRESTMapper{kindToPluralResource=%v}\", m.kindToPluralResource)\n}","line":{"from":67,"to":72}} {"id":100014683,"name":"NewDefaultRESTMapper","signature":"func NewDefaultRESTMapper(defaultGroupVersions []schema.GroupVersion) *DefaultRESTMapper","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/restmapper.go","code":"// NewDefaultRESTMapper initializes a mapping between Kind and APIVersion\n// to a resource name and back based on the objects in a runtime.Scheme\n// and the Kubernetes API conventions. Takes a group name, a priority list of the versions\n// to search when an object has no default version (set empty to return an error),\n// and a function that retrieves the correct metadata for a given version.\nfunc NewDefaultRESTMapper(defaultGroupVersions []schema.GroupVersion) *DefaultRESTMapper {\n\tresourceToKind := make(map[schema.GroupVersionResource]schema.GroupVersionKind)\n\tkindToPluralResource := make(map[schema.GroupVersionKind]schema.GroupVersionResource)\n\tkindToScope := make(map[schema.GroupVersionKind]RESTScope)\n\tsingularToPlural := make(map[schema.GroupVersionResource]schema.GroupVersionResource)\n\tpluralToSingular := make(map[schema.GroupVersionResource]schema.GroupVersionResource)\n\t// TODO: verify name mappings work correctly when versions differ\n\n\treturn \u0026DefaultRESTMapper{\n\t\tresourceToKind: resourceToKind,\n\t\tkindToPluralResource: kindToPluralResource,\n\t\tkindToScope: kindToScope,\n\t\tdefaultGroupVersions: defaultGroupVersions,\n\t\tsingularToPlural: singularToPlural,\n\t\tpluralToSingular: pluralToSingular,\n\t}\n}","line":{"from":76,"to":97}} {"id":100014684,"name":"Add","signature":"func (m *DefaultRESTMapper) Add(kind schema.GroupVersionKind, scope RESTScope)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/restmapper.go","code":"func (m *DefaultRESTMapper) Add(kind schema.GroupVersionKind, scope RESTScope) {\n\tplural, singular := UnsafeGuessKindToResource(kind)\n\tm.AddSpecific(kind, plural, singular, scope)\n}","line":{"from":99,"to":102}} {"id":100014685,"name":"AddSpecific","signature":"func (m *DefaultRESTMapper) AddSpecific(kind schema.GroupVersionKind, plural, singular schema.GroupVersionResource, scope RESTScope)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/restmapper.go","code":"func (m *DefaultRESTMapper) AddSpecific(kind schema.GroupVersionKind, plural, singular schema.GroupVersionResource, scope RESTScope) {\n\tm.singularToPlural[singular] = plural\n\tm.pluralToSingular[plural] = singular\n\n\tm.resourceToKind[singular] = kind\n\tm.resourceToKind[plural] = kind\n\n\tm.kindToPluralResource[kind] = plural\n\tm.kindToScope[kind] = scope\n}","line":{"from":104,"to":113}} {"id":100014686,"name":"UnsafeGuessKindToResource","signature":"func UnsafeGuessKindToResource(kind schema.GroupVersionKind) ( /*plural*/ schema.GroupVersionResource /*singular*/, schema.GroupVersionResource)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/restmapper.go","code":"// UnsafeGuessKindToResource converts Kind to a resource name.\n// Broken. This method only \"sort of\" works when used outside of this package. It assumes that Kinds and Resources match\n// and they aren't guaranteed to do so.\nfunc UnsafeGuessKindToResource(kind schema.GroupVersionKind) ( /*plural*/ schema.GroupVersionResource /*singular*/, schema.GroupVersionResource) {\n\tkindName := kind.Kind\n\tif len(kindName) == 0 {\n\t\treturn schema.GroupVersionResource{}, schema.GroupVersionResource{}\n\t}\n\tsingularName := strings.ToLower(kindName)\n\tsingular := kind.GroupVersion().WithResource(singularName)\n\n\tfor _, skip := range unpluralizedSuffixes {\n\t\tif strings.HasSuffix(singularName, skip) {\n\t\t\treturn singular, singular\n\t\t}\n\t}\n\n\tswitch string(singularName[len(singularName)-1]) {\n\tcase \"s\":\n\t\treturn kind.GroupVersion().WithResource(singularName + \"es\"), singular\n\tcase \"y\":\n\t\treturn kind.GroupVersion().WithResource(strings.TrimSuffix(singularName, \"y\") + \"ies\"), singular\n\t}\n\n\treturn kind.GroupVersion().WithResource(singularName + \"s\"), singular\n}","line":{"from":123,"to":148}} {"id":100014687,"name":"ResourceSingularizer","signature":"func (m *DefaultRESTMapper) ResourceSingularizer(resourceType string) (string, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/restmapper.go","code":"// ResourceSingularizer implements RESTMapper\n// It converts a resource name from plural to singular (e.g., from pods to pod)\nfunc (m *DefaultRESTMapper) ResourceSingularizer(resourceType string) (string, error) {\n\tpartialResource := schema.GroupVersionResource{Resource: resourceType}\n\tresources, err := m.ResourcesFor(partialResource)\n\tif err != nil {\n\t\treturn resourceType, err\n\t}\n\n\tsingular := schema.GroupVersionResource{}\n\tfor _, curr := range resources {\n\t\tcurrSingular, ok := m.pluralToSingular[curr]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tif singular.Empty() {\n\t\t\tsingular = currSingular\n\t\t\tcontinue\n\t\t}\n\n\t\tif currSingular.Resource != singular.Resource {\n\t\t\treturn resourceType, fmt.Errorf(\"multiple possible singular resources (%v) found for %v\", resources, resourceType)\n\t\t}\n\t}\n\n\tif singular.Empty() {\n\t\treturn resourceType, fmt.Errorf(\"no singular of resource %v has been defined\", resourceType)\n\t}\n\n\treturn singular.Resource, nil\n}","line":{"from":150,"to":180}} {"id":100014688,"name":"coerceResourceForMatching","signature":"func coerceResourceForMatching(resource schema.GroupVersionResource) schema.GroupVersionResource","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/restmapper.go","code":"// coerceResourceForMatching makes the resource lower case and converts internal versions to unspecified (legacy behavior)\nfunc coerceResourceForMatching(resource schema.GroupVersionResource) schema.GroupVersionResource {\n\tresource.Resource = strings.ToLower(resource.Resource)\n\tif resource.Version == runtime.APIVersionInternal {\n\t\tresource.Version = \"\"\n\t}\n\n\treturn resource\n}","line":{"from":182,"to":190}} {"id":100014689,"name":"ResourcesFor","signature":"func (m *DefaultRESTMapper) ResourcesFor(input schema.GroupVersionResource) ([]schema.GroupVersionResource, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/restmapper.go","code":"func (m *DefaultRESTMapper) ResourcesFor(input schema.GroupVersionResource) ([]schema.GroupVersionResource, error) {\n\tresource := coerceResourceForMatching(input)\n\n\thasResource := len(resource.Resource) \u003e 0\n\thasGroup := len(resource.Group) \u003e 0\n\thasVersion := len(resource.Version) \u003e 0\n\n\tif !hasResource {\n\t\treturn nil, fmt.Errorf(\"a resource must be present, got: %v\", resource)\n\t}\n\n\tret := []schema.GroupVersionResource{}\n\tswitch {\n\tcase hasGroup \u0026\u0026 hasVersion:\n\t\t// fully qualified. Find the exact match\n\t\tfor plural, singular := range m.pluralToSingular {\n\t\t\tif singular == resource {\n\t\t\t\tret = append(ret, plural)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif plural == resource {\n\t\t\t\tret = append(ret, plural)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\tcase hasGroup:\n\t\t// given a group, prefer an exact match. If you don't find one, resort to a prefix match on group\n\t\tfoundExactMatch := false\n\t\trequestedGroupResource := resource.GroupResource()\n\t\tfor plural, singular := range m.pluralToSingular {\n\t\t\tif singular.GroupResource() == requestedGroupResource {\n\t\t\t\tfoundExactMatch = true\n\t\t\t\tret = append(ret, plural)\n\t\t\t}\n\t\t\tif plural.GroupResource() == requestedGroupResource {\n\t\t\t\tfoundExactMatch = true\n\t\t\t\tret = append(ret, plural)\n\t\t\t}\n\t\t}\n\n\t\t// if you didn't find an exact match, match on group prefixing. This allows storageclass.storage to match\n\t\t// storageclass.storage.k8s.io\n\t\tif !foundExactMatch {\n\t\t\tfor plural, singular := range m.pluralToSingular {\n\t\t\t\tif !strings.HasPrefix(plural.Group, requestedGroupResource.Group) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif singular.Resource == requestedGroupResource.Resource {\n\t\t\t\t\tret = append(ret, plural)\n\t\t\t\t}\n\t\t\t\tif plural.Resource == requestedGroupResource.Resource {\n\t\t\t\t\tret = append(ret, plural)\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\tcase hasVersion:\n\t\tfor plural, singular := range m.pluralToSingular {\n\t\t\tif singular.Version == resource.Version \u0026\u0026 singular.Resource == resource.Resource {\n\t\t\t\tret = append(ret, plural)\n\t\t\t}\n\t\t\tif plural.Version == resource.Version \u0026\u0026 plural.Resource == resource.Resource {\n\t\t\t\tret = append(ret, plural)\n\t\t\t}\n\t\t}\n\n\tdefault:\n\t\tfor plural, singular := range m.pluralToSingular {\n\t\t\tif singular.Resource == resource.Resource {\n\t\t\t\tret = append(ret, plural)\n\t\t\t}\n\t\t\tif plural.Resource == resource.Resource {\n\t\t\t\tret = append(ret, plural)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(ret) == 0 {\n\t\treturn nil, \u0026NoResourceMatchError{PartialResource: resource}\n\t}\n\n\tsort.Sort(resourceByPreferredGroupVersion{ret, m.defaultGroupVersions})\n\treturn ret, nil\n}","line":{"from":192,"to":277}} {"id":100014690,"name":"ResourceFor","signature":"func (m *DefaultRESTMapper) ResourceFor(resource schema.GroupVersionResource) (schema.GroupVersionResource, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/restmapper.go","code":"func (m *DefaultRESTMapper) ResourceFor(resource schema.GroupVersionResource) (schema.GroupVersionResource, error) {\n\tresources, err := m.ResourcesFor(resource)\n\tif err != nil {\n\t\treturn schema.GroupVersionResource{}, err\n\t}\n\tif len(resources) == 1 {\n\t\treturn resources[0], nil\n\t}\n\n\treturn schema.GroupVersionResource{}, \u0026AmbiguousResourceError{PartialResource: resource, MatchingResources: resources}\n}","line":{"from":279,"to":289}} {"id":100014691,"name":"KindsFor","signature":"func (m *DefaultRESTMapper) KindsFor(input schema.GroupVersionResource) ([]schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/restmapper.go","code":"func (m *DefaultRESTMapper) KindsFor(input schema.GroupVersionResource) ([]schema.GroupVersionKind, error) {\n\tresource := coerceResourceForMatching(input)\n\n\thasResource := len(resource.Resource) \u003e 0\n\thasGroup := len(resource.Group) \u003e 0\n\thasVersion := len(resource.Version) \u003e 0\n\n\tif !hasResource {\n\t\treturn nil, fmt.Errorf(\"a resource must be present, got: %v\", resource)\n\t}\n\n\tret := []schema.GroupVersionKind{}\n\tswitch {\n\t// fully qualified. Find the exact match\n\tcase hasGroup \u0026\u0026 hasVersion:\n\t\tkind, exists := m.resourceToKind[resource]\n\t\tif exists {\n\t\t\tret = append(ret, kind)\n\t\t}\n\n\tcase hasGroup:\n\t\tfoundExactMatch := false\n\t\trequestedGroupResource := resource.GroupResource()\n\t\tfor currResource, currKind := range m.resourceToKind {\n\t\t\tif currResource.GroupResource() == requestedGroupResource {\n\t\t\t\tfoundExactMatch = true\n\t\t\t\tret = append(ret, currKind)\n\t\t\t}\n\t\t}\n\n\t\t// if you didn't find an exact match, match on group prefixing. This allows storageclass.storage to match\n\t\t// storageclass.storage.k8s.io\n\t\tif !foundExactMatch {\n\t\t\tfor currResource, currKind := range m.resourceToKind {\n\t\t\t\tif !strings.HasPrefix(currResource.Group, requestedGroupResource.Group) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif currResource.Resource == requestedGroupResource.Resource {\n\t\t\t\t\tret = append(ret, currKind)\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\tcase hasVersion:\n\t\tfor currResource, currKind := range m.resourceToKind {\n\t\t\tif currResource.Version == resource.Version \u0026\u0026 currResource.Resource == resource.Resource {\n\t\t\t\tret = append(ret, currKind)\n\t\t\t}\n\t\t}\n\n\tdefault:\n\t\tfor currResource, currKind := range m.resourceToKind {\n\t\t\tif currResource.Resource == resource.Resource {\n\t\t\t\tret = append(ret, currKind)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(ret) == 0 {\n\t\treturn nil, \u0026NoResourceMatchError{PartialResource: input}\n\t}\n\n\tsort.Sort(kindByPreferredGroupVersion{ret, m.defaultGroupVersions})\n\treturn ret, nil\n}","line":{"from":291,"to":356}} {"id":100014692,"name":"KindFor","signature":"func (m *DefaultRESTMapper) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/restmapper.go","code":"func (m *DefaultRESTMapper) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) {\n\tkinds, err := m.KindsFor(resource)\n\tif err != nil {\n\t\treturn schema.GroupVersionKind{}, err\n\t}\n\tif len(kinds) == 1 {\n\t\treturn kinds[0], nil\n\t}\n\n\treturn schema.GroupVersionKind{}, \u0026AmbiguousResourceError{PartialResource: resource, MatchingKinds: kinds}\n}","line":{"from":358,"to":368}} {"id":100014693,"name":"Len","signature":"func (o kindByPreferredGroupVersion) Len() int { return len(o.list) }","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/restmapper.go","code":"func (o kindByPreferredGroupVersion) Len() int { return len(o.list) }","line":{"from":375,"to":375}} {"id":100014694,"name":"Swap","signature":"func (o kindByPreferredGroupVersion) Swap(i, j int) { o.list[i], o.list[j] = o.list[j], o.list[i] }","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/restmapper.go","code":"func (o kindByPreferredGroupVersion) Swap(i, j int) { o.list[i], o.list[j] = o.list[j], o.list[i] }","line":{"from":376,"to":376}} {"id":100014695,"name":"Less","signature":"func (o kindByPreferredGroupVersion) Less(i, j int) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/restmapper.go","code":"func (o kindByPreferredGroupVersion) Less(i, j int) bool {\n\tlhs := o.list[i]\n\trhs := o.list[j]\n\tif lhs == rhs {\n\t\treturn false\n\t}\n\n\tif lhs.GroupVersion() == rhs.GroupVersion() {\n\t\treturn lhs.Kind \u003c rhs.Kind\n\t}\n\n\t// otherwise, the difference is in the GroupVersion, so we need to sort with respect to the preferred order\n\tlhsIndex := -1\n\trhsIndex := -1\n\n\tfor i := range o.sortOrder {\n\t\tif o.sortOrder[i] == lhs.GroupVersion() {\n\t\t\tlhsIndex = i\n\t\t}\n\t\tif o.sortOrder[i] == rhs.GroupVersion() {\n\t\t\trhsIndex = i\n\t\t}\n\t}\n\n\tif rhsIndex == -1 {\n\t\treturn true\n\t}\n\n\treturn lhsIndex \u003c rhsIndex\n}","line":{"from":377,"to":406}} {"id":100014696,"name":"Len","signature":"func (o resourceByPreferredGroupVersion) Len() int { return len(o.list) }","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/restmapper.go","code":"func (o resourceByPreferredGroupVersion) Len() int { return len(o.list) }","line":{"from":413,"to":413}} {"id":100014697,"name":"Swap","signature":"func (o resourceByPreferredGroupVersion) Swap(i, j int) { o.list[i], o.list[j] = o.list[j], o.list[i] }","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/restmapper.go","code":"func (o resourceByPreferredGroupVersion) Swap(i, j int) { o.list[i], o.list[j] = o.list[j], o.list[i] }","line":{"from":414,"to":414}} {"id":100014698,"name":"Less","signature":"func (o resourceByPreferredGroupVersion) Less(i, j int) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/restmapper.go","code":"func (o resourceByPreferredGroupVersion) Less(i, j int) bool {\n\tlhs := o.list[i]\n\trhs := o.list[j]\n\tif lhs == rhs {\n\t\treturn false\n\t}\n\n\tif lhs.GroupVersion() == rhs.GroupVersion() {\n\t\treturn lhs.Resource \u003c rhs.Resource\n\t}\n\n\t// otherwise, the difference is in the GroupVersion, so we need to sort with respect to the preferred order\n\tlhsIndex := -1\n\trhsIndex := -1\n\n\tfor i := range o.sortOrder {\n\t\tif o.sortOrder[i] == lhs.GroupVersion() {\n\t\t\tlhsIndex = i\n\t\t}\n\t\tif o.sortOrder[i] == rhs.GroupVersion() {\n\t\t\trhsIndex = i\n\t\t}\n\t}\n\n\tif rhsIndex == -1 {\n\t\treturn true\n\t}\n\n\treturn lhsIndex \u003c rhsIndex\n}","line":{"from":415,"to":444}} {"id":100014699,"name":"RESTMapping","signature":"func (m *DefaultRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (*RESTMapping, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/restmapper.go","code":"// RESTMapping returns a struct representing the resource path and conversion interfaces a\n// RESTClient should use to operate on the provided group/kind in order of versions. If a version search\n// order is not provided, the search order provided to DefaultRESTMapper will be used to resolve which\n// version should be used to access the named group/kind.\nfunc (m *DefaultRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (*RESTMapping, error) {\n\tmappings, err := m.RESTMappings(gk, versions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(mappings) == 0 {\n\t\treturn nil, \u0026NoKindMatchError{GroupKind: gk, SearchedVersions: versions}\n\t}\n\t// since we rely on RESTMappings method\n\t// take the first match and return to the caller\n\t// as this was the existing behavior.\n\treturn mappings[0], nil\n}","line":{"from":446,"to":462}} {"id":100014700,"name":"RESTMappings","signature":"func (m *DefaultRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) ([]*RESTMapping, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/restmapper.go","code":"// RESTMappings returns the RESTMappings for the provided group kind. If a version search order\n// is not provided, the search order provided to DefaultRESTMapper will be used.\nfunc (m *DefaultRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) ([]*RESTMapping, error) {\n\tmappings := make([]*RESTMapping, 0)\n\tpotentialGVK := make([]schema.GroupVersionKind, 0)\n\thadVersion := false\n\n\t// Pick an appropriate version\n\tfor _, version := range versions {\n\t\tif len(version) == 0 || version == runtime.APIVersionInternal {\n\t\t\tcontinue\n\t\t}\n\t\tcurrGVK := gk.WithVersion(version)\n\t\thadVersion = true\n\t\tif _, ok := m.kindToPluralResource[currGVK]; ok {\n\t\t\tpotentialGVK = append(potentialGVK, currGVK)\n\t\t\tbreak\n\t\t}\n\t}\n\t// Use the default preferred versions\n\tif !hadVersion \u0026\u0026 len(potentialGVK) == 0 {\n\t\tfor _, gv := range m.defaultGroupVersions {\n\t\t\tif gv.Group != gk.Group {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpotentialGVK = append(potentialGVK, gk.WithVersion(gv.Version))\n\t\t}\n\t}\n\n\tif len(potentialGVK) == 0 {\n\t\treturn nil, \u0026NoKindMatchError{GroupKind: gk, SearchedVersions: versions}\n\t}\n\n\tfor _, gvk := range potentialGVK {\n\t\t//Ensure we have a REST mapping\n\t\tres, ok := m.kindToPluralResource[gvk]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Ensure we have a REST scope\n\t\tscope, ok := m.kindToScope[gvk]\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"the provided version %q and kind %q cannot be mapped to a supported scope\", gvk.GroupVersion(), gvk.Kind)\n\t\t}\n\n\t\tmappings = append(mappings, \u0026RESTMapping{\n\t\t\tResource: res,\n\t\t\tGroupVersionKind: gvk,\n\t\t\tScope: scope,\n\t\t})\n\t}\n\n\tif len(mappings) == 0 {\n\t\treturn nil, \u0026NoResourceMatchError{PartialResource: schema.GroupVersionResource{Group: gk.Group, Resource: gk.Kind}}\n\t}\n\treturn mappings, nil\n}","line":{"from":464,"to":521}} {"id":100014701,"name":"MaybeResetRESTMapper","signature":"func MaybeResetRESTMapper(mapper RESTMapper)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/restmapper.go","code":"// MaybeResetRESTMapper calls Reset() on the mapper if it is a ResettableRESTMapper.\nfunc MaybeResetRESTMapper(mapper RESTMapper) {\n\tm, ok := mapper.(ResettableRESTMapper)\n\tif ok {\n\t\tm.Reset()\n\t}\n}","line":{"from":523,"to":529}} {"id":100014702,"name":"MetaToTableRow","signature":"func MetaToTableRow(obj runtime.Object, rowFn func(obj runtime.Object, m metav1.Object, name, age string) ([]interface{}, error)) ([]metav1.TableRow, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/table/table.go","code":"// MetaToTableRow converts a list or object into one or more table rows. The provided rowFn is invoked for\n// each accessed item, with name and age being passed to each.\nfunc MetaToTableRow(obj runtime.Object, rowFn func(obj runtime.Object, m metav1.Object, name, age string) ([]interface{}, error)) ([]metav1.TableRow, error) {\n\tif meta.IsListType(obj) {\n\t\trows := make([]metav1.TableRow, 0, 16)\n\t\terr := meta.EachListItem(obj, func(obj runtime.Object) error {\n\t\t\tnestedRows, err := MetaToTableRow(obj, rowFn)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\trows = append(rows, nestedRows...)\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn rows, nil\n\t}\n\n\trows := make([]metav1.TableRow, 0, 1)\n\tm, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\trow.Cells, err = rowFn(obj, m, m.GetName(), ConvertToHumanReadableDateType(m.GetCreationTimestamp()))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trows = append(rows, row)\n\treturn rows, nil\n}","line":{"from":28,"to":61}} {"id":100014703,"name":"ConvertToHumanReadableDateType","signature":"func ConvertToHumanReadableDateType(timestamp metav1.Time) string","file":"staging/src/k8s.io/apimachinery/pkg/api/meta/table/table.go","code":"// ConvertToHumanReadableDateType returns the elapsed time since timestamp in\n// human-readable approximation.\nfunc ConvertToHumanReadableDateType(timestamp metav1.Time) string {\n\tif timestamp.IsZero() {\n\t\treturn \"\u003cunknown\u003e\"\n\t}\n\treturn duration.HumanDuration(time.Since(timestamp.Time))\n}","line":{"from":63,"to":70}} {"id":100014704,"name":"infScale","signature":"func (s Scale) infScale() inf.Scale","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/amount.go","code":"// infScale adapts a Scale value to an inf.Scale value.\nfunc (s Scale) infScale() inf.Scale {\n\treturn inf.Scale(-s) // inf.Scale is upside-down\n}","line":{"from":31,"to":34}} {"id":100014705,"name":"Sign","signature":"func (a int64Amount) Sign() int","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/amount.go","code":"// Sign returns 0 if the value is zero, -1 if it is less than 0, or 1 if it is greater than 0.\nfunc (a int64Amount) Sign() int {\n\tswitch {\n\tcase a.value == 0:\n\t\treturn 0\n\tcase a.value \u003e 0:\n\t\treturn 1\n\tdefault:\n\t\treturn -1\n\t}\n}","line":{"from":63,"to":73}} {"id":100014706,"name":"AsInt64","signature":"func (a int64Amount) AsInt64() (int64, bool)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/amount.go","code":"// AsInt64 returns the current amount as an int64 at scale 0, or false if the value cannot be\n// represented in an int64 OR would result in a loss of precision. This method is intended as\n// an optimization to avoid calling AsDec.\nfunc (a int64Amount) AsInt64() (int64, bool) {\n\tif a.scale == 0 {\n\t\treturn a.value, true\n\t}\n\tif a.scale \u003c 0 {\n\t\t// TODO: attempt to reduce factors, although it is assumed that factors are reduced prior\n\t\t// to the int64Amount being created.\n\t\treturn 0, false\n\t}\n\treturn positiveScaleInt64(a.value, a.scale)\n}","line":{"from":75,"to":88}} {"id":100014707,"name":"AsScaledInt64","signature":"func (a int64Amount) AsScaledInt64(scale Scale) (result int64, ok bool)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/amount.go","code":"// AsScaledInt64 returns an int64 representing the value of this amount at the specified scale,\n// rounding up, or false if that would result in overflow. (1e20).AsScaledInt64(1) would result\n// in overflow because 1e19 is not representable as an int64. Note that setting a scale larger\n// than the current value may result in loss of precision - i.e. (1e-6).AsScaledInt64(0) would\n// return 1, because 0.000001 is rounded up to 1.\nfunc (a int64Amount) AsScaledInt64(scale Scale) (result int64, ok bool) {\n\tif a.scale \u003c scale {\n\t\tresult, _ = negativeScaleInt64(a.value, scale-a.scale)\n\t\treturn result, true\n\t}\n\treturn positiveScaleInt64(a.value, a.scale-scale)\n}","line":{"from":90,"to":101}} {"id":100014708,"name":"AsDec","signature":"func (a int64Amount) AsDec() *inf.Dec","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/amount.go","code":"// AsDec returns an inf.Dec representation of this value.\nfunc (a int64Amount) AsDec() *inf.Dec {\n\tvar base inf.Dec\n\tbase.SetUnscaled(a.value)\n\tbase.SetScale(inf.Scale(-a.scale))\n\treturn \u0026base\n}","line":{"from":103,"to":109}} {"id":100014709,"name":"Cmp","signature":"func (a int64Amount) Cmp(b int64Amount) int","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/amount.go","code":"// Cmp returns 0 if a and b are equal, 1 if a is greater than b, or -1 if a is less than b.\nfunc (a int64Amount) Cmp(b int64Amount) int {\n\tswitch {\n\tcase a.scale == b.scale:\n\t\t// compare only the unscaled portion\n\tcase a.scale \u003e b.scale:\n\t\tresult, remainder, exact := divideByScaleInt64(b.value, a.scale-b.scale)\n\t\tif !exact {\n\t\t\treturn a.AsDec().Cmp(b.AsDec())\n\t\t}\n\t\tif result == a.value {\n\t\t\tswitch {\n\t\t\tcase remainder == 0:\n\t\t\t\treturn 0\n\t\t\tcase remainder \u003e 0:\n\t\t\t\treturn -1\n\t\t\tdefault:\n\t\t\t\treturn 1\n\t\t\t}\n\t\t}\n\t\tb.value = result\n\tdefault:\n\t\tresult, remainder, exact := divideByScaleInt64(a.value, b.scale-a.scale)\n\t\tif !exact {\n\t\t\treturn a.AsDec().Cmp(b.AsDec())\n\t\t}\n\t\tif result == b.value {\n\t\t\tswitch {\n\t\t\tcase remainder == 0:\n\t\t\t\treturn 0\n\t\t\tcase remainder \u003e 0:\n\t\t\t\treturn 1\n\t\t\tdefault:\n\t\t\t\treturn -1\n\t\t\t}\n\t\t}\n\t\ta.value = result\n\t}\n\n\tswitch {\n\tcase a.value == b.value:\n\t\treturn 0\n\tcase a.value \u003c b.value:\n\t\treturn -1\n\tdefault:\n\t\treturn 1\n\t}\n}","line":{"from":111,"to":158}} {"id":100014710,"name":"Add","signature":"func (a *int64Amount) Add(b int64Amount) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/amount.go","code":"// Add adds two int64Amounts together, matching scales. It will return false and not mutate\n// a if overflow or underflow would result.\nfunc (a *int64Amount) Add(b int64Amount) bool {\n\tswitch {\n\tcase b.value == 0:\n\t\treturn true\n\tcase a.value == 0:\n\t\ta.value = b.value\n\t\ta.scale = b.scale\n\t\treturn true\n\tcase a.scale == b.scale:\n\t\tc, ok := int64Add(a.value, b.value)\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\ta.value = c\n\tcase a.scale \u003e b.scale:\n\t\tc, ok := positiveScaleInt64(a.value, a.scale-b.scale)\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\tc, ok = int64Add(c, b.value)\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\ta.scale = b.scale\n\t\ta.value = c\n\tdefault:\n\t\tc, ok := positiveScaleInt64(b.value, b.scale-a.scale)\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\tc, ok = int64Add(a.value, c)\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\ta.value = c\n\t}\n\treturn true\n}","line":{"from":160,"to":199}} {"id":100014711,"name":"Sub","signature":"func (a *int64Amount) Sub(b int64Amount) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/amount.go","code":"// Sub removes the value of b from the current amount, or returns false if underflow would result.\nfunc (a *int64Amount) Sub(b int64Amount) bool {\n\treturn a.Add(int64Amount{value: -b.value, scale: b.scale})\n}","line":{"from":201,"to":204}} {"id":100014712,"name":"AsScale","signature":"func (a int64Amount) AsScale(scale Scale) (int64Amount, bool)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/amount.go","code":"// AsScale adjusts this amount to set a minimum scale, rounding up, and returns true iff no precision\n// was lost. (1.1e5).AsScale(5) would return 1.1e5, but (1.1e5).AsScale(6) would return 1e6.\nfunc (a int64Amount) AsScale(scale Scale) (int64Amount, bool) {\n\tif a.scale \u003e= scale {\n\t\treturn a, true\n\t}\n\tresult, exact := negativeScaleInt64(a.value, scale-a.scale)\n\treturn int64Amount{value: result, scale: scale}, exact\n}","line":{"from":206,"to":214}} {"id":100014713,"name":"AsCanonicalBytes","signature":"func (a int64Amount) AsCanonicalBytes(out []byte) (result []byte, exponent int32)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/amount.go","code":"// AsCanonicalBytes accepts a buffer to write the base-10 string value of this field to, and returns\n// either that buffer or a larger buffer and the current exponent of the value. The value is adjusted\n// until the exponent is a multiple of 3 - i.e. 1.1e5 would return \"110\", 3.\nfunc (a int64Amount) AsCanonicalBytes(out []byte) (result []byte, exponent int32) {\n\tmantissa := a.value\n\texponent = int32(a.scale)\n\n\tamount, times := removeInt64Factors(mantissa, 10)\n\texponent += int32(times)\n\n\t// make sure exponent is a multiple of 3\n\tvar ok bool\n\tswitch exponent % 3 {\n\tcase 1, -2:\n\t\tamount, ok = int64MultiplyScale10(amount)\n\t\tif !ok {\n\t\t\treturn infDecAmount{a.AsDec()}.AsCanonicalBytes(out)\n\t\t}\n\t\texponent = exponent - 1\n\tcase 2, -1:\n\t\tamount, ok = int64MultiplyScale100(amount)\n\t\tif !ok {\n\t\t\treturn infDecAmount{a.AsDec()}.AsCanonicalBytes(out)\n\t\t}\n\t\texponent = exponent - 2\n\t}\n\treturn strconv.AppendInt(out, amount, 10), exponent\n}","line":{"from":216,"to":243}} {"id":100014714,"name":"AsCanonicalBase1024Bytes","signature":"func (a int64Amount) AsCanonicalBase1024Bytes(out []byte) (result []byte, exponent int32)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/amount.go","code":"// AsCanonicalBase1024Bytes accepts a buffer to write the base-1024 string value of this field to, and returns\n// either that buffer or a larger buffer and the current exponent of the value. 2048 is 2 * 1024 ^ 1 and would\n// return []byte(\"2048\"), 1.\nfunc (a int64Amount) AsCanonicalBase1024Bytes(out []byte) (result []byte, exponent int32) {\n\tvalue, ok := a.AsScaledInt64(0)\n\tif !ok {\n\t\treturn infDecAmount{a.AsDec()}.AsCanonicalBase1024Bytes(out)\n\t}\n\tamount, exponent := removeInt64Factors(value, 1024)\n\treturn strconv.AppendInt(out, amount, 10), exponent\n}","line":{"from":245,"to":255}} {"id":100014715,"name":"AsScale","signature":"func (a infDecAmount) AsScale(scale Scale) (infDecAmount, bool)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/amount.go","code":"// AsScale adjusts this amount to set a minimum scale, rounding up, and returns true iff no precision\n// was lost. (1.1e5).AsScale(5) would return 1.1e5, but (1.1e5).AsScale(6) would return 1e6.\nfunc (a infDecAmount) AsScale(scale Scale) (infDecAmount, bool) {\n\ttmp := \u0026inf.Dec{}\n\ttmp.Round(a.Dec, scale.infScale(), inf.RoundUp)\n\treturn infDecAmount{tmp}, tmp.Cmp(a.Dec) == 0\n}","line":{"from":263,"to":269}} {"id":100014716,"name":"AsCanonicalBytes","signature":"func (a infDecAmount) AsCanonicalBytes(out []byte) (result []byte, exponent int32)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/amount.go","code":"// AsCanonicalBytes accepts a buffer to write the base-10 string value of this field to, and returns\n// either that buffer or a larger buffer and the current exponent of the value. The value is adjusted\n// until the exponent is a multiple of 3 - i.e. 1.1e5 would return \"110\", 3.\nfunc (a infDecAmount) AsCanonicalBytes(out []byte) (result []byte, exponent int32) {\n\tmantissa := a.Dec.UnscaledBig()\n\texponent = int32(-a.Dec.Scale())\n\tamount := big.NewInt(0).Set(mantissa)\n\t// move all factors of 10 into the exponent for easy reasoning\n\tamount, times := removeBigIntFactors(amount, bigTen)\n\texponent += times\n\n\t// make sure exponent is a multiple of 3\n\tfor exponent%3 != 0 {\n\t\tamount.Mul(amount, bigTen)\n\t\texponent--\n\t}\n\n\treturn append(out, amount.String()...), exponent\n}","line":{"from":271,"to":289}} {"id":100014717,"name":"AsCanonicalBase1024Bytes","signature":"func (a infDecAmount) AsCanonicalBase1024Bytes(out []byte) (result []byte, exponent int32)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/amount.go","code":"// AsCanonicalBase1024Bytes accepts a buffer to write the base-1024 string value of this field to, and returns\n// either that buffer or a larger buffer and the current exponent of the value. 2048 is 2 * 1024 ^ 1 and would\n// return []byte(\"2048\"), 1.\nfunc (a infDecAmount) AsCanonicalBase1024Bytes(out []byte) (result []byte, exponent int32) {\n\ttmp := \u0026inf.Dec{}\n\ttmp.Round(a.Dec, 0, inf.RoundUp)\n\tamount, exponent := removeBigIntFactors(tmp.UnscaledBig(), big1024)\n\treturn append(out, amount.String()...), exponent\n}","line":{"from":291,"to":299}} {"id":100014718,"name":"int64Add","signature":"func int64Add(a, b int64) (int64, bool)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/math.go","code":"// int64Add returns a+b, or false if that would overflow int64.\nfunc int64Add(a, b int64) (int64, bool) {\n\tc := a + b\n\tswitch {\n\tcase a \u003e 0 \u0026\u0026 b \u003e 0:\n\t\tif c \u003c 0 {\n\t\t\treturn 0, false\n\t\t}\n\tcase a \u003c 0 \u0026\u0026 b \u003c 0:\n\t\tif c \u003e 0 {\n\t\t\treturn 0, false\n\t\t}\n\t\tif a == mostNegative \u0026\u0026 b == mostNegative {\n\t\t\treturn 0, false\n\t\t}\n\t}\n\treturn c, true\n}","line":{"from":55,"to":72}} {"id":100014719,"name":"int64Multiply","signature":"func int64Multiply(a, b int64) (int64, bool)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/math.go","code":"// int64Multiply returns a*b, or false if that would overflow or underflow int64.\nfunc int64Multiply(a, b int64) (int64, bool) {\n\tif a == 0 || b == 0 || a == 1 || b == 1 {\n\t\treturn a * b, true\n\t}\n\tif a == mostNegative || b == mostNegative {\n\t\treturn 0, false\n\t}\n\tc := a * b\n\treturn c, c/b == a\n}","line":{"from":74,"to":84}} {"id":100014720,"name":"int64MultiplyScale","signature":"func int64MultiplyScale(a int64, b int64) (int64, bool)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/math.go","code":"// int64MultiplyScale returns a*b, assuming b is greater than one, or false if that would overflow or underflow int64.\n// Use when b is known to be greater than one.\nfunc int64MultiplyScale(a int64, b int64) (int64, bool) {\n\tif a == 0 || a == 1 {\n\t\treturn a * b, true\n\t}\n\tif a == mostNegative \u0026\u0026 b != 1 {\n\t\treturn 0, false\n\t}\n\tc := a * b\n\treturn c, c/b == a\n}","line":{"from":86,"to":97}} {"id":100014721,"name":"int64MultiplyScale10","signature":"func int64MultiplyScale10(a int64) (int64, bool)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/math.go","code":"// int64MultiplyScale10 multiplies a by 10, or returns false if that would overflow. This method is faster than\n// int64Multiply(a, 10) because the compiler can optimize constant factor multiplication.\nfunc int64MultiplyScale10(a int64) (int64, bool) {\n\tif a == 0 || a == 1 {\n\t\treturn a * 10, true\n\t}\n\tif a == mostNegative {\n\t\treturn 0, false\n\t}\n\tc := a * 10\n\treturn c, c/10 == a\n}","line":{"from":99,"to":110}} {"id":100014722,"name":"int64MultiplyScale100","signature":"func int64MultiplyScale100(a int64) (int64, bool)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/math.go","code":"// int64MultiplyScale100 multiplies a by 100, or returns false if that would overflow. This method is faster than\n// int64Multiply(a, 100) because the compiler can optimize constant factor multiplication.\nfunc int64MultiplyScale100(a int64) (int64, bool) {\n\tif a == 0 || a == 1 {\n\t\treturn a * 100, true\n\t}\n\tif a == mostNegative {\n\t\treturn 0, false\n\t}\n\tc := a * 100\n\treturn c, c/100 == a\n}","line":{"from":112,"to":123}} {"id":100014723,"name":"int64MultiplyScale1000","signature":"func int64MultiplyScale1000(a int64) (int64, bool)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/math.go","code":"// int64MultiplyScale1000 multiplies a by 1000, or returns false if that would overflow. This method is faster than\n// int64Multiply(a, 1000) because the compiler can optimize constant factor multiplication.\nfunc int64MultiplyScale1000(a int64) (int64, bool) {\n\tif a == 0 || a == 1 {\n\t\treturn a * 1000, true\n\t}\n\tif a == mostNegative {\n\t\treturn 0, false\n\t}\n\tc := a * 1000\n\treturn c, c/1000 == a\n}","line":{"from":125,"to":136}} {"id":100014724,"name":"positiveScaleInt64","signature":"func positiveScaleInt64(base int64, scale Scale) (int64, bool)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/math.go","code":"// positiveScaleInt64 multiplies base by 10^scale, returning false if the\n// value overflows. Passing a negative scale is undefined.\nfunc positiveScaleInt64(base int64, scale Scale) (int64, bool) {\n\tswitch scale {\n\tcase 0:\n\t\treturn base, true\n\tcase 1:\n\t\treturn int64MultiplyScale10(base)\n\tcase 2:\n\t\treturn int64MultiplyScale100(base)\n\tcase 3:\n\t\treturn int64MultiplyScale1000(base)\n\tcase 6:\n\t\treturn int64MultiplyScale(base, 1000000)\n\tcase 9:\n\t\treturn int64MultiplyScale(base, 1000000000)\n\tdefault:\n\t\tvalue := base\n\t\tvar ok bool\n\t\tfor i := Scale(0); i \u003c scale; i++ {\n\t\t\tif value, ok = int64MultiplyScale(value, 10); !ok {\n\t\t\t\treturn 0, false\n\t\t\t}\n\t\t}\n\t\treturn value, true\n\t}\n}","line":{"from":138,"to":164}} {"id":100014725,"name":"negativeScaleInt64","signature":"func negativeScaleInt64(base int64, scale Scale) (result int64, exact bool)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/math.go","code":"// negativeScaleInt64 reduces base by the provided scale, rounding up, until the\n// value is zero or the scale is reached. Passing a negative scale is undefined.\n// The value returned, if not exact, is rounded away from zero.\nfunc negativeScaleInt64(base int64, scale Scale) (result int64, exact bool) {\n\tif scale == 0 {\n\t\treturn base, true\n\t}\n\n\tvalue := base\n\tvar fraction bool\n\tfor i := Scale(0); i \u003c scale; i++ {\n\t\tif !fraction \u0026\u0026 value%10 != 0 {\n\t\t\tfraction = true\n\t\t}\n\t\tvalue = value / 10\n\t\tif value == 0 {\n\t\t\tif fraction {\n\t\t\t\tif base \u003e 0 {\n\t\t\t\t\treturn 1, false\n\t\t\t\t}\n\t\t\t\treturn -1, false\n\t\t\t}\n\t\t\treturn 0, true\n\t\t}\n\t}\n\tif fraction {\n\t\tif base \u003e 0 {\n\t\t\tvalue++\n\t\t} else {\n\t\t\tvalue--\n\t\t}\n\t}\n\treturn value, !fraction\n}","line":{"from":166,"to":199}} {"id":100014726,"name":"pow10Int64","signature":"func pow10Int64(b int64) int64","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/math.go","code":"func pow10Int64(b int64) int64 {\n\tswitch b {\n\tcase 0:\n\t\treturn 1\n\tcase 1:\n\t\treturn 10\n\tcase 2:\n\t\treturn 100\n\tcase 3:\n\t\treturn 1000\n\tcase 4:\n\t\treturn 10000\n\tcase 5:\n\t\treturn 100000\n\tcase 6:\n\t\treturn 1000000\n\tcase 7:\n\t\treturn 10000000\n\tcase 8:\n\t\treturn 100000000\n\tcase 9:\n\t\treturn 1000000000\n\tcase 10:\n\t\treturn 10000000000\n\tcase 11:\n\t\treturn 100000000000\n\tcase 12:\n\t\treturn 1000000000000\n\tcase 13:\n\t\treturn 10000000000000\n\tcase 14:\n\t\treturn 100000000000000\n\tcase 15:\n\t\treturn 1000000000000000\n\tcase 16:\n\t\treturn 10000000000000000\n\tcase 17:\n\t\treturn 100000000000000000\n\tcase 18:\n\t\treturn 1000000000000000000\n\tdefault:\n\t\treturn 0\n\t}\n}","line":{"from":201,"to":244}} {"id":100014727,"name":"divideByScaleInt64","signature":"func divideByScaleInt64(base int64, scale Scale) (result, remainder int64, exact bool)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/math.go","code":"// negativeScaleInt64 returns the result of dividing base by scale * 10 and the remainder, or\n// false if no such division is possible. Dividing by negative scales is undefined.\nfunc divideByScaleInt64(base int64, scale Scale) (result, remainder int64, exact bool) {\n\tif scale == 0 {\n\t\treturn base, 0, true\n\t}\n\t// the max scale representable in base 10 in an int64 is 18 decimal places\n\tif scale \u003e= 18 {\n\t\treturn 0, base, false\n\t}\n\tdivisor := pow10Int64(int64(scale))\n\treturn base / divisor, base % divisor, true\n}","line":{"from":246,"to":258}} {"id":100014728,"name":"removeInt64Factors","signature":"func removeInt64Factors(value int64, base int64) (result int64, times int32)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/math.go","code":"// removeInt64Factors divides in a loop; the return values have the property that\n// value == result * base ^ scale\nfunc removeInt64Factors(value int64, base int64) (result int64, times int32) {\n\ttimes = 0\n\tresult = value\n\tnegative := result \u003c 0\n\tif negative {\n\t\tresult = -result\n\t}\n\tswitch base {\n\t// allow the compiler to optimize the common cases\n\tcase 10:\n\t\tfor result \u003e= 10 \u0026\u0026 result%10 == 0 {\n\t\t\ttimes++\n\t\t\tresult = result / 10\n\t\t}\n\t// allow the compiler to optimize the common cases\n\tcase 1024:\n\t\tfor result \u003e= 1024 \u0026\u0026 result%1024 == 0 {\n\t\t\ttimes++\n\t\t\tresult = result / 1024\n\t\t}\n\tdefault:\n\t\tfor result \u003e= base \u0026\u0026 result%base == 0 {\n\t\t\ttimes++\n\t\t\tresult = result / base\n\t\t}\n\t}\n\tif negative {\n\t\tresult = -result\n\t}\n\treturn result, times\n}","line":{"from":260,"to":292}} {"id":100014729,"name":"removeBigIntFactors","signature":"func removeBigIntFactors(d, factor *big.Int) (result *big.Int, times int32)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/math.go","code":"// removeBigIntFactors divides in a loop; the return values have the property that\n// d == result * factor ^ times\n// d may be modified in place.\n// If d == 0, then the return values will be (0, 0)\nfunc removeBigIntFactors(d, factor *big.Int) (result *big.Int, times int32) {\n\tq := big.NewInt(0)\n\tm := big.NewInt(0)\n\tfor d.Cmp(bigZero) != 0 {\n\t\tq.DivMod(d, factor, m)\n\t\tif m.Cmp(bigZero) != 0 {\n\t\t\tbreak\n\t\t}\n\t\ttimes++\n\t\td, q = q, d\n\t}\n\treturn d, times\n}","line":{"from":294,"to":310}} {"id":100014730,"name":"MustParse","signature":"func MustParse(str string) Quantity","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// MustParse turns the given string into a quantity or panics; for tests\n// or other cases where you know the string is valid.\nfunc MustParse(str string) Quantity {\n\tq, err := ParseQuantity(str)\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"cannot parse '%v': %v\", str, err))\n\t}\n\treturn q\n}","line":{"from":134,"to":142}} {"id":100014731,"name":"parseQuantityString","signature":"func parseQuantityString(str string) (positive bool, value, num, denom, suffix string, err error)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// parseQuantityString is a fast scanner for quantity values.\nfunc parseQuantityString(str string) (positive bool, value, num, denom, suffix string, err error) {\n\tpositive = true\n\tpos := 0\n\tend := len(str)\n\n\t// handle leading sign\n\tif pos \u003c end {\n\t\tswitch str[0] {\n\t\tcase '-':\n\t\t\tpositive = false\n\t\t\tpos++\n\t\tcase '+':\n\t\t\tpos++\n\t\t}\n\t}\n\n\t// strip leading zeros\nZeroes:\n\tfor i := pos; ; i++ {\n\t\tif i \u003e= end {\n\t\t\tnum = \"0\"\n\t\t\tvalue = num\n\t\t\treturn\n\t\t}\n\t\tswitch str[i] {\n\t\tcase '0':\n\t\t\tpos++\n\t\tdefault:\n\t\t\tbreak Zeroes\n\t\t}\n\t}\n\n\t// extract the numerator\nNum:\n\tfor i := pos; ; i++ {\n\t\tif i \u003e= end {\n\t\t\tnum = str[pos:end]\n\t\t\tvalue = str[0:end]\n\t\t\treturn\n\t\t}\n\t\tswitch str[i] {\n\t\tcase '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':\n\t\tdefault:\n\t\t\tnum = str[pos:i]\n\t\t\tpos = i\n\t\t\tbreak Num\n\t\t}\n\t}\n\n\t// if we stripped all numerator positions, always return 0\n\tif len(num) == 0 {\n\t\tnum = \"0\"\n\t}\n\n\t// handle a denominator\n\tif pos \u003c end \u0026\u0026 str[pos] == '.' {\n\t\tpos++\n\tDenom:\n\t\tfor i := pos; ; i++ {\n\t\t\tif i \u003e= end {\n\t\t\t\tdenom = str[pos:end]\n\t\t\t\tvalue = str[0:end]\n\t\t\t\treturn\n\t\t\t}\n\t\t\tswitch str[i] {\n\t\t\tcase '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':\n\t\t\tdefault:\n\t\t\t\tdenom = str[pos:i]\n\t\t\t\tpos = i\n\t\t\t\tbreak Denom\n\t\t\t}\n\t\t}\n\t\t// TODO: we currently allow 1.G, but we may not want to in the future.\n\t\t// if len(denom) == 0 {\n\t\t// \terr = ErrFormatWrong\n\t\t// \treturn\n\t\t// }\n\t}\n\tvalue = str[0:pos]\n\n\t// grab the elements of the suffix\n\tsuffixStart := pos\n\tfor i := pos; ; i++ {\n\t\tif i \u003e= end {\n\t\t\tsuffix = str[suffixStart:end]\n\t\t\treturn\n\t\t}\n\t\tif !strings.ContainsAny(str[i:i+1], \"eEinumkKMGTP\") {\n\t\t\tpos = i\n\t\t\tbreak\n\t\t}\n\t}\n\tif pos \u003c end {\n\t\tswitch str[pos] {\n\t\tcase '-', '+':\n\t\t\tpos++\n\t\t}\n\t}\nSuffix:\n\tfor i := pos; ; i++ {\n\t\tif i \u003e= end {\n\t\t\tsuffix = str[suffixStart:end]\n\t\t\treturn\n\t\t}\n\t\tswitch str[i] {\n\t\tcase '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':\n\t\tdefault:\n\t\t\tbreak Suffix\n\t\t}\n\t}\n\t// we encountered a non decimal in the Suffix loop, but the last character\n\t// was not a valid exponent\n\terr = ErrFormatWrong\n\treturn\n}","line":{"from":157,"to":272}} {"id":100014732,"name":"ParseQuantity","signature":"func ParseQuantity(str string) (Quantity, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// ParseQuantity turns str into a Quantity, or returns an error.\nfunc ParseQuantity(str string) (Quantity, error) {\n\tif len(str) == 0 {\n\t\treturn Quantity{}, ErrFormatWrong\n\t}\n\tif str == \"0\" {\n\t\treturn Quantity{Format: DecimalSI, s: str}, nil\n\t}\n\n\tpositive, value, num, denom, suf, err := parseQuantityString(str)\n\tif err != nil {\n\t\treturn Quantity{}, err\n\t}\n\n\tbase, exponent, format, ok := quantitySuffixer.interpret(suffix(suf))\n\tif !ok {\n\t\treturn Quantity{}, ErrSuffix\n\t}\n\n\tprecision := int32(0)\n\tscale := int32(0)\n\tmantissa := int64(1)\n\tswitch format {\n\tcase DecimalExponent, DecimalSI:\n\t\tscale = exponent\n\t\tprecision = maxInt64Factors - int32(len(num)+len(denom))\n\tcase BinarySI:\n\t\tscale = 0\n\t\tswitch {\n\t\tcase exponent \u003e= 0 \u0026\u0026 len(denom) == 0:\n\t\t\t// only handle positive binary numbers with the fast path\n\t\t\tmantissa = int64(int64(mantissa) \u003c\u003c uint64(exponent))\n\t\t\t// 1Mi (2^20) has ~6 digits of decimal precision, so exponent*3/10 -1 is roughly the precision\n\t\t\tprecision = 15 - int32(len(num)) - int32(float32(exponent)*3/10) - 1\n\t\tdefault:\n\t\t\tprecision = -1\n\t\t}\n\t}\n\n\tif precision \u003e= 0 {\n\t\t// if we have a denominator, shift the entire value to the left by the number of places in the\n\t\t// denominator\n\t\tscale -= int32(len(denom))\n\t\tif scale \u003e= int32(Nano) {\n\t\t\tshifted := num + denom\n\n\t\t\tvar value int64\n\t\t\tvalue, err := strconv.ParseInt(shifted, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn Quantity{}, ErrNumeric\n\t\t\t}\n\t\t\tif result, ok := int64Multiply(value, int64(mantissa)); ok {\n\t\t\t\tif !positive {\n\t\t\t\t\tresult = -result\n\t\t\t\t}\n\t\t\t\t// if the number is in canonical form, reuse the string\n\t\t\t\tswitch format {\n\t\t\t\tcase BinarySI:\n\t\t\t\t\tif exponent%10 == 0 \u0026\u0026 (value\u00260x07 != 0) {\n\t\t\t\t\t\treturn Quantity{i: int64Amount{value: result, scale: Scale(scale)}, Format: format, s: str}, nil\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\tif scale%3 == 0 \u0026\u0026 !strings.HasSuffix(shifted, \"000\") \u0026\u0026 shifted[0] != '0' {\n\t\t\t\t\t\treturn Quantity{i: int64Amount{value: result, scale: Scale(scale)}, Format: format, s: str}, nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn Quantity{i: int64Amount{value: result, scale: Scale(scale)}, Format: format}, nil\n\t\t\t}\n\t\t}\n\t}\n\n\tamount := new(inf.Dec)\n\tif _, ok := amount.SetString(value); !ok {\n\t\treturn Quantity{}, ErrNumeric\n\t}\n\n\t// So that no one but us has to think about suffixes, remove it.\n\tif base == 10 {\n\t\tamount.SetScale(amount.Scale() + Scale(exponent).infScale())\n\t} else if base == 2 {\n\t\t// numericSuffix = 2 ** exponent\n\t\tnumericSuffix := big.NewInt(1).Lsh(bigOne, uint(exponent))\n\t\tub := amount.UnscaledBig()\n\t\tamount.SetUnscaledBig(ub.Mul(ub, numericSuffix))\n\t}\n\n\t// Cap at min/max bounds.\n\tsign := amount.Sign()\n\tif sign == -1 {\n\t\tamount.Neg(amount)\n\t}\n\n\t// This rounds non-zero values up to the minimum representable value, under the theory that\n\t// if you want some resources, you should get some resources, even if you asked for way too small\n\t// of an amount. Arguably, this should be inf.RoundHalfUp (normal rounding), but that would have\n\t// the side effect of rounding values \u003c .5n to zero.\n\tif v, ok := amount.Unscaled(); v != int64(0) || !ok {\n\t\tamount.Round(amount, Nano.infScale(), inf.RoundUp)\n\t}\n\n\t// The max is just a simple cap.\n\t// TODO: this prevents accumulating quantities greater than int64, for instance quota across a cluster\n\tif format == BinarySI \u0026\u0026 amount.Cmp(maxAllowed.Dec) \u003e 0 {\n\t\tamount.Set(maxAllowed.Dec)\n\t}\n\n\tif format == BinarySI \u0026\u0026 amount.Cmp(decOne) \u003c 0 \u0026\u0026 amount.Cmp(decZero) \u003e 0 {\n\t\t// This avoids rounding and hopefully confusion, too.\n\t\tformat = DecimalSI\n\t}\n\tif sign == -1 {\n\t\tamount.Neg(amount)\n\t}\n\n\treturn Quantity{d: infDecAmount{amount}, Format: format}, nil\n}","line":{"from":274,"to":389}} {"id":100014733,"name":"DeepCopy","signature":"func (q Quantity) DeepCopy() Quantity","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// DeepCopy returns a deep-copy of the Quantity value. Note that the method\n// receiver is a value, so we can mutate it in-place and return it.\nfunc (q Quantity) DeepCopy() Quantity {\n\tif q.d.Dec != nil {\n\t\ttmp := \u0026inf.Dec{}\n\t\tq.d.Dec = tmp.Set(q.d.Dec)\n\t}\n\treturn q\n}","line":{"from":391,"to":399}} {"id":100014734,"name":"OpenAPISchemaType","signature":"func (_ Quantity) OpenAPISchemaType() []string { return []string{\"string\"} }","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// OpenAPISchemaType is used by the kube-openapi generator when constructing\n// the OpenAPI spec of this type.\n//\n// See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators\nfunc (_ Quantity) OpenAPISchemaType() []string { return []string{\"string\"} }","line":{"from":401,"to":405}} {"id":100014735,"name":"OpenAPISchemaFormat","signature":"func (_ Quantity) OpenAPISchemaFormat() string { return \"\" }","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// OpenAPISchemaFormat is used by the kube-openapi generator when constructing\n// the OpenAPI spec of this type.\nfunc (_ Quantity) OpenAPISchemaFormat() string { return \"\" }","line":{"from":407,"to":409}} {"id":100014736,"name":"OpenAPIV3OneOfTypes","signature":"func (Quantity) OpenAPIV3OneOfTypes() []string { return []string{\"string\", \"number\"} }","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// OpenAPIV3OneOfTypes is used by the kube-openapi generator when constructing\n// the OpenAPI v3 spec of this type.\nfunc (Quantity) OpenAPIV3OneOfTypes() []string { return []string{\"string\", \"number\"} }","line":{"from":411,"to":413}} {"id":100014737,"name":"CanonicalizeBytes","signature":"func (q *Quantity) CanonicalizeBytes(out []byte) (result, suffix []byte)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// CanonicalizeBytes returns the canonical form of q and its suffix (see comment on Quantity).\n//\n// Note about BinarySI:\n// - If q.Format is set to BinarySI and q.Amount represents a non-zero value between\n// -1 and +1, it will be emitted as if q.Format were DecimalSI.\n// - Otherwise, if q.Format is set to BinarySI, fractional parts of q.Amount will be\n// rounded up. (1.1i becomes 2i.)\nfunc (q *Quantity) CanonicalizeBytes(out []byte) (result, suffix []byte) {\n\tif q.IsZero() {\n\t\treturn zeroBytes, nil\n\t}\n\n\tvar rounded CanonicalValue\n\tformat := q.Format\n\tswitch format {\n\tcase DecimalExponent, DecimalSI:\n\tcase BinarySI:\n\t\tif q.CmpInt64(-1024) \u003e 0 \u0026\u0026 q.CmpInt64(1024) \u003c 0 {\n\t\t\t// This avoids rounding and hopefully confusion, too.\n\t\t\tformat = DecimalSI\n\t\t} else {\n\t\t\tvar exact bool\n\t\t\tif rounded, exact = q.AsScale(0); !exact {\n\t\t\t\t// Don't lose precision-- show as DecimalSI\n\t\t\t\tformat = DecimalSI\n\t\t\t}\n\t\t}\n\tdefault:\n\t\tformat = DecimalExponent\n\t}\n\n\t// TODO: If BinarySI formatting is requested but would cause rounding, upgrade to\n\t// one of the other formats.\n\tswitch format {\n\tcase DecimalExponent, DecimalSI:\n\t\tnumber, exponent := q.AsCanonicalBytes(out)\n\t\tsuffix, _ := quantitySuffixer.constructBytes(10, exponent, format)\n\t\treturn number, suffix\n\tdefault:\n\t\t// format must be BinarySI\n\t\tnumber, exponent := rounded.AsCanonicalBase1024Bytes(out)\n\t\tsuffix, _ := quantitySuffixer.constructBytes(2, exponent*10, format)\n\t\treturn number, suffix\n\t}\n}","line":{"from":415,"to":459}} {"id":100014738,"name":"AsApproximateFloat64","signature":"func (q *Quantity) AsApproximateFloat64() float64","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// AsApproximateFloat64 returns a float64 representation of the quantity which may\n// lose precision. If the value of the quantity is outside the range of a float64\n// +Inf/-Inf will be returned.\nfunc (q *Quantity) AsApproximateFloat64() float64 {\n\tvar base float64\n\tvar exponent int\n\tif q.d.Dec != nil {\n\t\tbase, _ = big.NewFloat(0).SetInt(q.d.Dec.UnscaledBig()).Float64()\n\t\texponent = int(-q.d.Dec.Scale())\n\t} else {\n\t\tbase = float64(q.i.value)\n\t\texponent = int(q.i.scale)\n\t}\n\tif exponent == 0 {\n\t\treturn base\n\t}\n\n\treturn base * math.Pow10(exponent)\n}","line":{"from":461,"to":479}} {"id":100014739,"name":"AsInt64","signature":"func (q *Quantity) AsInt64() (int64, bool)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// AsInt64 returns a representation of the current value as an int64 if a fast conversion\n// is possible. If false is returned, callers must use the inf.Dec form of this quantity.\nfunc (q *Quantity) AsInt64() (int64, bool) {\n\tif q.d.Dec != nil {\n\t\treturn 0, false\n\t}\n\treturn q.i.AsInt64()\n}","line":{"from":481,"to":488}} {"id":100014740,"name":"ToDec","signature":"func (q *Quantity) ToDec() *Quantity","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// ToDec promotes the quantity in place to use an inf.Dec representation and returns itself.\nfunc (q *Quantity) ToDec() *Quantity {\n\tif q.d.Dec == nil {\n\t\tq.d.Dec = q.i.AsDec()\n\t\tq.i = int64Amount{}\n\t}\n\treturn q\n}","line":{"from":490,"to":497}} {"id":100014741,"name":"AsDec","signature":"func (q *Quantity) AsDec() *inf.Dec","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// AsDec returns the quantity as represented by a scaled inf.Dec.\nfunc (q *Quantity) AsDec() *inf.Dec {\n\tif q.d.Dec != nil {\n\t\treturn q.d.Dec\n\t}\n\tq.d.Dec = q.i.AsDec()\n\tq.i = int64Amount{}\n\treturn q.d.Dec\n}","line":{"from":499,"to":507}} {"id":100014742,"name":"AsCanonicalBytes","signature":"func (q *Quantity) AsCanonicalBytes(out []byte) (result []byte, exponent int32)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// AsCanonicalBytes returns the canonical byte representation of this quantity as a mantissa\n// and base 10 exponent. The out byte slice may be passed to the method to avoid an extra\n// allocation.\nfunc (q *Quantity) AsCanonicalBytes(out []byte) (result []byte, exponent int32) {\n\tif q.d.Dec != nil {\n\t\treturn q.d.AsCanonicalBytes(out)\n\t}\n\treturn q.i.AsCanonicalBytes(out)\n}","line":{"from":509,"to":517}} {"id":100014743,"name":"IsZero","signature":"func (q *Quantity) IsZero() bool","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// IsZero returns true if the quantity is equal to zero.\nfunc (q *Quantity) IsZero() bool {\n\tif q.d.Dec != nil {\n\t\treturn q.d.Dec.Sign() == 0\n\t}\n\treturn q.i.value == 0\n}","line":{"from":519,"to":525}} {"id":100014744,"name":"Sign","signature":"func (q *Quantity) Sign() int","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// Sign returns 0 if the quantity is zero, -1 if the quantity is less than zero, or 1 if the\n// quantity is greater than zero.\nfunc (q *Quantity) Sign() int {\n\tif q.d.Dec != nil {\n\t\treturn q.d.Dec.Sign()\n\t}\n\treturn q.i.Sign()\n}","line":{"from":527,"to":534}} {"id":100014745,"name":"AsScale","signature":"func (q *Quantity) AsScale(scale Scale) (CanonicalValue, bool)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// AsScale returns the current value, rounded up to the provided scale, and returns\n// false if the scale resulted in a loss of precision.\nfunc (q *Quantity) AsScale(scale Scale) (CanonicalValue, bool) {\n\tif q.d.Dec != nil {\n\t\treturn q.d.AsScale(scale)\n\t}\n\treturn q.i.AsScale(scale)\n}","line":{"from":536,"to":543}} {"id":100014746,"name":"RoundUp","signature":"func (q *Quantity) RoundUp(scale Scale) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// RoundUp updates the quantity to the provided scale, ensuring that the value is at\n// least 1. False is returned if the rounding operation resulted in a loss of precision.\n// Negative numbers are rounded away from zero (-9 scale 1 rounds to -10).\nfunc (q *Quantity) RoundUp(scale Scale) bool {\n\tif q.d.Dec != nil {\n\t\tq.s = \"\"\n\t\td, exact := q.d.AsScale(scale)\n\t\tq.d = d\n\t\treturn exact\n\t}\n\t// avoid clearing the string value if we have already calculated it\n\tif q.i.scale \u003e= scale {\n\t\treturn true\n\t}\n\tq.s = \"\"\n\ti, exact := q.i.AsScale(scale)\n\tq.i = i\n\treturn exact\n}","line":{"from":545,"to":563}} {"id":100014747,"name":"Add","signature":"func (q *Quantity) Add(y Quantity)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// Add adds the provide y quantity to the current value. If the current value is zero,\n// the format of the quantity will be updated to the format of y.\nfunc (q *Quantity) Add(y Quantity) {\n\tq.s = \"\"\n\tif q.d.Dec == nil \u0026\u0026 y.d.Dec == nil {\n\t\tif q.i.value == 0 {\n\t\t\tq.Format = y.Format\n\t\t}\n\t\tif q.i.Add(y.i) {\n\t\t\treturn\n\t\t}\n\t} else if q.IsZero() {\n\t\tq.Format = y.Format\n\t}\n\tq.ToDec().d.Dec.Add(q.d.Dec, y.AsDec())\n}","line":{"from":565,"to":580}} {"id":100014748,"name":"Sub","signature":"func (q *Quantity) Sub(y Quantity)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// Sub subtracts the provided quantity from the current value in place. If the current\n// value is zero, the format of the quantity will be updated to the format of y.\nfunc (q *Quantity) Sub(y Quantity) {\n\tq.s = \"\"\n\tif q.IsZero() {\n\t\tq.Format = y.Format\n\t}\n\tif q.d.Dec == nil \u0026\u0026 y.d.Dec == nil \u0026\u0026 q.i.Sub(y.i) {\n\t\treturn\n\t}\n\tq.ToDec().d.Dec.Sub(q.d.Dec, y.AsDec())\n}","line":{"from":582,"to":593}} {"id":100014749,"name":"Cmp","signature":"func (q *Quantity) Cmp(y Quantity) int","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// Cmp returns 0 if the quantity is equal to y, -1 if the quantity is less than y, or 1 if the\n// quantity is greater than y.\nfunc (q *Quantity) Cmp(y Quantity) int {\n\tif q.d.Dec == nil \u0026\u0026 y.d.Dec == nil {\n\t\treturn q.i.Cmp(y.i)\n\t}\n\treturn q.AsDec().Cmp(y.AsDec())\n}","line":{"from":595,"to":602}} {"id":100014750,"name":"CmpInt64","signature":"func (q *Quantity) CmpInt64(y int64) int","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// CmpInt64 returns 0 if the quantity is equal to y, -1 if the quantity is less than y, or 1 if the\n// quantity is greater than y.\nfunc (q *Quantity) CmpInt64(y int64) int {\n\tif q.d.Dec != nil {\n\t\treturn q.d.Dec.Cmp(inf.NewDec(y, inf.Scale(0)))\n\t}\n\treturn q.i.Cmp(int64Amount{value: y})\n}","line":{"from":604,"to":611}} {"id":100014751,"name":"Neg","signature":"func (q *Quantity) Neg()","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// Neg sets quantity to be the negative value of itself.\nfunc (q *Quantity) Neg() {\n\tq.s = \"\"\n\tif q.d.Dec == nil {\n\t\tq.i.value = -q.i.value\n\t\treturn\n\t}\n\tq.d.Dec.Neg(q.d.Dec)\n}","line":{"from":613,"to":621}} {"id":100014752,"name":"Equal","signature":"func (q Quantity) Equal(v Quantity) bool","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// Equal checks equality of two Quantities. This is useful for testing with\n// cmp.Equal.\nfunc (q Quantity) Equal(v Quantity) bool {\n\treturn q.Cmp(v) == 0\n}","line":{"from":623,"to":627}} {"id":100014753,"name":"String","signature":"func (q *Quantity) String() string","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// String formats the Quantity as a string, caching the result if not calculated.\n// String is an expensive operation and caching this result significantly reduces the cost of\n// normal parse / marshal operations on Quantity.\nfunc (q *Quantity) String() string {\n\tif q == nil {\n\t\treturn \"\u003cnil\u003e\"\n\t}\n\tif len(q.s) == 0 {\n\t\tresult := make([]byte, 0, int64QuantityExpectedBytes)\n\t\tnumber, suffix := q.CanonicalizeBytes(result)\n\t\tnumber = append(number, suffix...)\n\t\tq.s = string(number)\n\t}\n\treturn q.s\n}","line":{"from":633,"to":647}} {"id":100014754,"name":"MarshalJSON","signature":"func (q Quantity) MarshalJSON() ([]byte, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// MarshalJSON implements the json.Marshaller interface.\nfunc (q Quantity) MarshalJSON() ([]byte, error) {\n\tif len(q.s) \u003e 0 {\n\t\tout := make([]byte, len(q.s)+2)\n\t\tout[0], out[len(out)-1] = '\"', '\"'\n\t\tcopy(out[1:], q.s)\n\t\treturn out, nil\n\t}\n\tresult := make([]byte, int64QuantityExpectedBytes)\n\tresult[0] = '\"'\n\tnumber, suffix := q.CanonicalizeBytes(result[1:1])\n\t// if the same slice was returned to us that we passed in, avoid another allocation by copying number into\n\t// the source slice and returning that\n\tif len(number) \u003e 0 \u0026\u0026 \u0026number[0] == \u0026result[1] \u0026\u0026 (len(number)+len(suffix)+2) \u003c= int64QuantityExpectedBytes {\n\t\tnumber = append(number, suffix...)\n\t\tnumber = append(number, '\"')\n\t\treturn result[:1+len(number)], nil\n\t}\n\t// if CanonicalizeBytes needed more space than our slice provided, we may need to allocate again so use\n\t// append\n\tresult = result[:1]\n\tresult = append(result, number...)\n\tresult = append(result, suffix...)\n\tresult = append(result, '\"')\n\treturn result, nil\n}","line":{"from":649,"to":674}} {"id":100014755,"name":"ToUnstructured","signature":"func (q Quantity) ToUnstructured() interface{}","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// ToUnstructured implements the value.UnstructuredConverter interface.\nfunc (q Quantity) ToUnstructured() interface{} {\n\treturn q.String()\n}","line":{"from":676,"to":679}} {"id":100014756,"name":"UnmarshalJSON","signature":"func (q *Quantity) UnmarshalJSON(value []byte) error","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// UnmarshalJSON implements the json.Unmarshaller interface.\n// TODO: Remove support for leading/trailing whitespace\nfunc (q *Quantity) UnmarshalJSON(value []byte) error {\n\tl := len(value)\n\tif l == 4 \u0026\u0026 bytes.Equal(value, []byte(\"null\")) {\n\t\tq.d.Dec = nil\n\t\tq.i = int64Amount{}\n\t\treturn nil\n\t}\n\tif l \u003e= 2 \u0026\u0026 value[0] == '\"' \u0026\u0026 value[l-1] == '\"' {\n\t\tvalue = value[1 : l-1]\n\t}\n\n\tparsed, err := ParseQuantity(strings.TrimSpace(string(value)))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// This copy is safe because parsed will not be referred to again.\n\t*q = parsed\n\treturn nil\n}","line":{"from":681,"to":702}} {"id":100014757,"name":"NewDecimalQuantity","signature":"func NewDecimalQuantity(b inf.Dec, format Format) *Quantity","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// NewDecimalQuantity returns a new Quantity representing the given\n// value in the given format.\nfunc NewDecimalQuantity(b inf.Dec, format Format) *Quantity {\n\treturn \u0026Quantity{\n\t\td: infDecAmount{\u0026b},\n\t\tFormat: format,\n\t}\n}","line":{"from":704,"to":711}} {"id":100014758,"name":"NewQuantity","signature":"func NewQuantity(value int64, format Format) *Quantity","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// NewQuantity returns a new Quantity representing the given\n// value in the given format.\nfunc NewQuantity(value int64, format Format) *Quantity {\n\treturn \u0026Quantity{\n\t\ti: int64Amount{value: value},\n\t\tFormat: format,\n\t}\n}","line":{"from":713,"to":720}} {"id":100014759,"name":"NewMilliQuantity","signature":"func NewMilliQuantity(value int64, format Format) *Quantity","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// NewMilliQuantity returns a new Quantity representing the given\n// value * 1/1000 in the given format. Note that BinarySI formatting\n// will round fractional values, and will be changed to DecimalSI for\n// values x where (-1 \u003c x \u003c 1) \u0026\u0026 (x != 0).\nfunc NewMilliQuantity(value int64, format Format) *Quantity {\n\treturn \u0026Quantity{\n\t\ti: int64Amount{value: value, scale: -3},\n\t\tFormat: format,\n\t}\n}","line":{"from":722,"to":731}} {"id":100014760,"name":"NewScaledQuantity","signature":"func NewScaledQuantity(value int64, scale Scale) *Quantity","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// NewScaledQuantity returns a new Quantity representing the given\n// value * 10^scale in DecimalSI format.\nfunc NewScaledQuantity(value int64, scale Scale) *Quantity {\n\treturn \u0026Quantity{\n\t\ti: int64Amount{value: value, scale: scale},\n\t\tFormat: DecimalSI,\n\t}\n}","line":{"from":733,"to":740}} {"id":100014761,"name":"Value","signature":"func (q *Quantity) Value() int64","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// Value returns the unscaled value of q rounded up to the nearest integer away from 0.\nfunc (q *Quantity) Value() int64 {\n\treturn q.ScaledValue(0)\n}","line":{"from":742,"to":745}} {"id":100014762,"name":"MilliValue","signature":"func (q *Quantity) MilliValue() int64","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// MilliValue returns the value of ceil(q * 1000); this could overflow an int64;\n// if that's a concern, call Value() first to verify the number is small enough.\nfunc (q *Quantity) MilliValue() int64 {\n\treturn q.ScaledValue(Milli)\n}","line":{"from":747,"to":751}} {"id":100014763,"name":"ScaledValue","signature":"func (q *Quantity) ScaledValue(scale Scale) int64","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// ScaledValue returns the value of ceil(q / 10^scale).\n// For example, NewQuantity(1, DecimalSI).ScaledValue(Milli) returns 1000.\n// This could overflow an int64.\n// To detect overflow, call Value() first and verify the expected magnitude.\nfunc (q *Quantity) ScaledValue(scale Scale) int64 {\n\tif q.d.Dec == nil {\n\t\ti, _ := q.i.AsScaledInt64(scale)\n\t\treturn i\n\t}\n\tdec := q.d.Dec\n\treturn scaledValue(dec.UnscaledBig(), int(dec.Scale()), int(scale.infScale()))\n}","line":{"from":753,"to":764}} {"id":100014764,"name":"Set","signature":"func (q *Quantity) Set(value int64)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// Set sets q's value to be value.\nfunc (q *Quantity) Set(value int64) {\n\tq.SetScaled(value, 0)\n}","line":{"from":766,"to":769}} {"id":100014765,"name":"SetMilli","signature":"func (q *Quantity) SetMilli(value int64)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// SetMilli sets q's value to be value * 1/1000.\nfunc (q *Quantity) SetMilli(value int64) {\n\tq.SetScaled(value, Milli)\n}","line":{"from":771,"to":774}} {"id":100014766,"name":"SetScaled","signature":"func (q *Quantity) SetScaled(value int64, scale Scale)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// SetScaled sets q's value to be value * 10^scale\nfunc (q *Quantity) SetScaled(value int64, scale Scale) {\n\tq.s = \"\"\n\tq.d.Dec = nil\n\tq.i = int64Amount{value: value, scale: scale}\n}","line":{"from":776,"to":781}} {"id":100014767,"name":"Set","signature":"func (q *QuantityValue) Set(s string) error","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// Set implements pflag.Value.Set and Go flag.Value.Set.\nfunc (q *QuantityValue) Set(s string) error {\n\tquantity, err := ParseQuantity(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\tq.Quantity = quantity\n\treturn nil\n}","line":{"from":795,"to":803}} {"id":100014768,"name":"Type","signature":"func (q QuantityValue) Type() string","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go","code":"// Type implements pflag.Value.Type.\nfunc (q QuantityValue) Type() string {\n\treturn \"quantity\"\n}","line":{"from":805,"to":808}} {"id":100014769,"name":"Marshal","signature":"func (m *Quantity) Marshal() (data []byte, err error)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity_proto.go","code":"func (m *Quantity) Marshal() (data []byte, err error) {\n\tsize := m.Size()\n\tdata = make([]byte, size)\n\tn, err := m.MarshalToSizedBuffer(data[:size])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn data[:n], nil\n}","line":{"from":29,"to":37}} {"id":100014770,"name":"MarshalTo","signature":"func (m *Quantity) MarshalTo(data []byte) (int, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity_proto.go","code":"// MarshalTo is a customized version of the generated Protobuf unmarshaler for a struct\n// with a single string field.\nfunc (m *Quantity) MarshalTo(data []byte) (int, error) {\n\tsize := m.Size()\n\treturn m.MarshalToSizedBuffer(data[:size])\n}","line":{"from":39,"to":44}} {"id":100014771,"name":"MarshalToSizedBuffer","signature":"func (m *Quantity) MarshalToSizedBuffer(data []byte) (int, error)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity_proto.go","code":"// MarshalToSizedBuffer is a customized version of the generated\n// Protobuf unmarshaler for a struct with a single string field.\nfunc (m *Quantity) MarshalToSizedBuffer(data []byte) (int, error) {\n\ti := len(data)\n\t_ = i\n\tvar l int\n\t_ = l\n\n\t// BEGIN CUSTOM MARSHAL\n\tout := m.String()\n\ti -= len(out)\n\tcopy(data[i:], out)\n\ti = encodeVarintGenerated(data, i, uint64(len(out)))\n\t// END CUSTOM MARSHAL\n\ti--\n\tdata[i] = 0xa\n\n\treturn len(data) - i, nil\n}","line":{"from":46,"to":64}} {"id":100014772,"name":"encodeVarintGenerated","signature":"func encodeVarintGenerated(data []byte, offset int, v uint64) int","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity_proto.go","code":"func encodeVarintGenerated(data []byte, offset int, v uint64) int {\n\toffset -= sovGenerated(v)\n\tbase := offset\n\tfor v \u003e= 1\u003c\u003c7 {\n\t\tdata[offset] = uint8(v\u00260x7f | 0x80)\n\t\tv \u003e\u003e= 7\n\t\toffset++\n\t}\n\tdata[offset] = uint8(v)\n\treturn base\n}","line":{"from":66,"to":76}} {"id":100014773,"name":"Size","signature":"func (m *Quantity) Size() (n int)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity_proto.go","code":"func (m *Quantity) Size() (n int) {\n\tvar l int\n\t_ = l\n\n\t// BEGIN CUSTOM SIZE\n\tl = len(m.String())\n\t// END CUSTOM SIZE\n\n\tn += 1 + l + sovGenerated(uint64(l))\n\treturn n\n}","line":{"from":78,"to":88}} {"id":100014774,"name":"sovGenerated","signature":"func sovGenerated(x uint64) (n int)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity_proto.go","code":"func sovGenerated(x uint64) (n int) {\n\treturn (bits.Len64(x|1) + 6) / 7\n}","line":{"from":90,"to":92}} {"id":100014775,"name":"Unmarshal","signature":"func (m *Quantity) Unmarshal(data []byte) error","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity_proto.go","code":"// Unmarshal is a customized version of the generated Protobuf unmarshaler for a struct\n// with a single string field.\nfunc (m *Quantity) Unmarshal(data []byte) error {\n\tl := len(data)\n\tiNdEx := 0\n\tfor iNdEx \u003c l {\n\t\tpreIndex := iNdEx\n\t\tvar wire uint64\n\t\tfor shift := uint(0); ; shift += 7 {\n\t\t\tif shift \u003e= 64 {\n\t\t\t\treturn ErrIntOverflowGenerated\n\t\t\t}\n\t\t\tif iNdEx \u003e= l {\n\t\t\t\treturn io.ErrUnexpectedEOF\n\t\t\t}\n\t\t\tb := data[iNdEx]\n\t\t\tiNdEx++\n\t\t\twire |= (uint64(b) \u0026 0x7F) \u003c\u003c shift\n\t\t\tif b \u003c 0x80 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tfieldNum := int32(wire \u003e\u003e 3)\n\t\twireType := int(wire \u0026 0x7)\n\t\tif wireType == 4 {\n\t\t\treturn fmt.Errorf(\"proto: Quantity: wiretype end group for non-group\")\n\t\t}\n\t\tif fieldNum \u003c= 0 {\n\t\t\treturn fmt.Errorf(\"proto: Quantity: illegal tag %d (wire type %d)\", fieldNum, wire)\n\t\t}\n\t\tswitch fieldNum {\n\t\tcase 1:\n\t\t\tif wireType != 2 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field String_\", wireType)\n\t\t\t}\n\t\t\tvar stringLen uint64\n\t\t\tfor shift := uint(0); ; shift += 7 {\n\t\t\t\tif shift \u003e= 64 {\n\t\t\t\t\treturn ErrIntOverflowGenerated\n\t\t\t\t}\n\t\t\t\tif iNdEx \u003e= l {\n\t\t\t\t\treturn io.ErrUnexpectedEOF\n\t\t\t\t}\n\t\t\t\tb := data[iNdEx]\n\t\t\t\tiNdEx++\n\t\t\t\tstringLen |= (uint64(b) \u0026 0x7F) \u003c\u003c shift\n\t\t\t\tif b \u003c 0x80 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tintStringLen := int(stringLen)\n\t\t\tif intStringLen \u003c 0 {\n\t\t\t\treturn ErrInvalidLengthGenerated\n\t\t\t}\n\t\t\tpostIndex := iNdEx + intStringLen\n\t\t\tif postIndex \u003e l {\n\t\t\t\treturn io.ErrUnexpectedEOF\n\t\t\t}\n\t\t\ts := string(data[iNdEx:postIndex])\n\n\t\t\t// BEGIN CUSTOM DECODE\n\t\t\tp, err := ParseQuantity(s)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t*m = p\n\t\t\t// END CUSTOM DECODE\n\n\t\t\tiNdEx = postIndex\n\t\tdefault:\n\t\t\tiNdEx = preIndex\n\t\t\tskippy, err := skipGenerated(data[iNdEx:])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif (skippy \u003c 0) || (iNdEx+skippy) \u003c 0 {\n\t\t\t\treturn ErrInvalidLengthGenerated\n\t\t\t}\n\t\t\tif (iNdEx + skippy) \u003e l {\n\t\t\t\treturn io.ErrUnexpectedEOF\n\t\t\t}\n\t\t\tiNdEx += skippy\n\t\t}\n\t}\n\n\tif iNdEx \u003e l {\n\t\treturn io.ErrUnexpectedEOF\n\t}\n\treturn nil\n}","line":{"from":94,"to":183}} {"id":100014776,"name":"skipGenerated","signature":"func skipGenerated(data []byte) (n int, err error)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/quantity_proto.go","code":"func skipGenerated(data []byte) (n int, err error) {\n\tl := len(data)\n\tiNdEx := 0\n\tfor iNdEx \u003c l {\n\t\tvar wire uint64\n\t\tfor shift := uint(0); ; shift += 7 {\n\t\t\tif shift \u003e= 64 {\n\t\t\t\treturn 0, ErrIntOverflowGenerated\n\t\t\t}\n\t\t\tif iNdEx \u003e= l {\n\t\t\t\treturn 0, io.ErrUnexpectedEOF\n\t\t\t}\n\t\t\tb := data[iNdEx]\n\t\t\tiNdEx++\n\t\t\twire |= (uint64(b) \u0026 0x7F) \u003c\u003c shift\n\t\t\tif b \u003c 0x80 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\twireType := int(wire \u0026 0x7)\n\t\tswitch wireType {\n\t\tcase 0:\n\t\t\tfor shift := uint(0); ; shift += 7 {\n\t\t\t\tif shift \u003e= 64 {\n\t\t\t\t\treturn 0, ErrIntOverflowGenerated\n\t\t\t\t}\n\t\t\t\tif iNdEx \u003e= l {\n\t\t\t\t\treturn 0, io.ErrUnexpectedEOF\n\t\t\t\t}\n\t\t\t\tiNdEx++\n\t\t\t\tif data[iNdEx-1] \u003c 0x80 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn iNdEx, nil\n\t\tcase 1:\n\t\t\tiNdEx += 8\n\t\t\treturn iNdEx, nil\n\t\tcase 2:\n\t\t\tvar length int\n\t\t\tfor shift := uint(0); ; shift += 7 {\n\t\t\t\tif shift \u003e= 64 {\n\t\t\t\t\treturn 0, ErrIntOverflowGenerated\n\t\t\t\t}\n\t\t\t\tif iNdEx \u003e= l {\n\t\t\t\t\treturn 0, io.ErrUnexpectedEOF\n\t\t\t\t}\n\t\t\t\tb := data[iNdEx]\n\t\t\t\tiNdEx++\n\t\t\t\tlength |= (int(b) \u0026 0x7F) \u003c\u003c shift\n\t\t\t\tif b \u003c 0x80 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tiNdEx += length\n\t\t\tif length \u003c 0 {\n\t\t\t\treturn 0, ErrInvalidLengthGenerated\n\t\t\t}\n\t\t\treturn iNdEx, nil\n\t\tcase 3:\n\t\t\tfor {\n\t\t\t\tvar innerWire uint64\n\t\t\t\tvar start int = iNdEx\n\t\t\t\tfor shift := uint(0); ; shift += 7 {\n\t\t\t\t\tif shift \u003e= 64 {\n\t\t\t\t\t\treturn 0, ErrIntOverflowGenerated\n\t\t\t\t\t}\n\t\t\t\t\tif iNdEx \u003e= l {\n\t\t\t\t\t\treturn 0, io.ErrUnexpectedEOF\n\t\t\t\t\t}\n\t\t\t\t\tb := data[iNdEx]\n\t\t\t\t\tiNdEx++\n\t\t\t\t\tinnerWire |= (uint64(b) \u0026 0x7F) \u003c\u003c shift\n\t\t\t\t\tif b \u003c 0x80 {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tinnerWireType := int(innerWire \u0026 0x7)\n\t\t\t\tif innerWireType == 4 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tnext, err := skipGenerated(data[start:])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn 0, err\n\t\t\t\t}\n\t\t\t\tiNdEx = start + next\n\t\t\t}\n\t\t\treturn iNdEx, nil\n\t\tcase 4:\n\t\t\treturn iNdEx, nil\n\t\tcase 5:\n\t\t\tiNdEx += 4\n\t\t\treturn iNdEx, nil\n\t\tdefault:\n\t\t\treturn 0, fmt.Errorf(\"proto: illegal wireType %d\", wireType)\n\t\t}\n\t}\n\tpanic(\"unreachable\")\n}","line":{"from":185,"to":283}} {"id":100014777,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/scale_int.go","code":"func init() {\n\tintPool.New = func() interface{} {\n\t\treturn \u0026big.Int{}\n\t}\n}","line":{"from":31,"to":35}} {"id":100014778,"name":"scaledValue","signature":"func scaledValue(unscaled *big.Int, scale, newScale int) int64","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/scale_int.go","code":"// scaledValue scales given unscaled value from scale to new Scale and returns\n// an int64. It ALWAYS rounds up the result when scale down. The final result might\n// overflow.\n//\n// scale, newScale represents the scale of the unscaled decimal.\n// The mathematical value of the decimal is unscaled * 10**(-scale).\nfunc scaledValue(unscaled *big.Int, scale, newScale int) int64 {\n\tdif := scale - newScale\n\tif dif == 0 {\n\t\treturn unscaled.Int64()\n\t}\n\n\t// Handle scale up\n\t// This is an easy case, we do not need to care about rounding and overflow.\n\t// If any intermediate operation causes overflow, the result will overflow.\n\tif dif \u003c 0 {\n\t\treturn unscaled.Int64() * int64(math.Pow10(-dif))\n\t}\n\n\t// Handle scale down\n\t// We have to be careful about the intermediate operations.\n\n\t// fast path when unscaled \u003c max.Int64 and exp(10,dif) \u003c max.Int64\n\tconst log10MaxInt64 = 19\n\tif unscaled.Cmp(maxInt64) \u003c 0 \u0026\u0026 dif \u003c log10MaxInt64 {\n\t\tdivide := int64(math.Pow10(dif))\n\t\tresult := unscaled.Int64() / divide\n\t\tmod := unscaled.Int64() % divide\n\t\tif mod != 0 {\n\t\t\treturn result + 1\n\t\t}\n\t\treturn result\n\t}\n\n\t// We should only convert back to int64 when getting the result.\n\tdivisor := intPool.Get().(*big.Int)\n\texp := intPool.Get().(*big.Int)\n\tresult := intPool.Get().(*big.Int)\n\tdefer func() {\n\t\tintPool.Put(divisor)\n\t\tintPool.Put(exp)\n\t\tintPool.Put(result)\n\t}()\n\n\t// divisor = 10^(dif)\n\t// TODO: create loop up table if exp costs too much.\n\tdivisor.Exp(bigTen, exp.SetInt64(int64(dif)), nil)\n\t// reuse exp\n\tremainder := exp\n\n\t// result = unscaled / divisor\n\t// remainder = unscaled % divisor\n\tresult.DivMod(unscaled, divisor, remainder)\n\tif remainder.Sign() != 0 {\n\t\treturn result.Int64() + 1\n\t}\n\n\treturn result.Int64()\n}","line":{"from":37,"to":95}} {"id":100014779,"name":"addSuffix","signature":"func (ls *listSuffixer) addSuffix(s suffix, pair bePair)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/suffix.go","code":"func (ls *listSuffixer) addSuffix(s suffix, pair bePair) {\n\tif ls.suffixToBE == nil {\n\t\tls.suffixToBE = map[suffix]bePair{}\n\t}\n\tif ls.beToSuffix == nil {\n\t\tls.beToSuffix = map[bePair]suffix{}\n\t}\n\tif ls.beToSuffixBytes == nil {\n\t\tls.beToSuffixBytes = map[bePair][]byte{}\n\t}\n\tls.suffixToBE[s] = pair\n\tls.beToSuffix[pair] = s\n\tls.beToSuffixBytes[pair] = []byte(s)\n}","line":{"from":46,"to":59}} {"id":100014780,"name":"lookup","signature":"func (ls *listSuffixer) lookup(s suffix) (base, exponent int32, ok bool)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/suffix.go","code":"func (ls *listSuffixer) lookup(s suffix) (base, exponent int32, ok bool) {\n\tpair, ok := ls.suffixToBE[s]\n\tif !ok {\n\t\treturn 0, 0, false\n\t}\n\treturn pair.base, pair.exponent, true\n}","line":{"from":61,"to":67}} {"id":100014781,"name":"construct","signature":"func (ls *listSuffixer) construct(base, exponent int32) (s suffix, ok bool)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/suffix.go","code":"func (ls *listSuffixer) construct(base, exponent int32) (s suffix, ok bool) {\n\ts, ok = ls.beToSuffix[bePair{base, exponent}]\n\treturn\n}","line":{"from":69,"to":72}} {"id":100014782,"name":"constructBytes","signature":"func (ls *listSuffixer) constructBytes(base, exponent int32) (s []byte, ok bool)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/suffix.go","code":"func (ls *listSuffixer) constructBytes(base, exponent int32) (s []byte, ok bool) {\n\ts, ok = ls.beToSuffixBytes[bePair{base, exponent}]\n\treturn\n}","line":{"from":74,"to":77}} {"id":100014783,"name":"interpret","signature":"func (l fastLookup) interpret(s suffix) (base, exponent int32, format Format, ok bool)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/suffix.go","code":"func (l fastLookup) interpret(s suffix) (base, exponent int32, format Format, ok bool) {\n\tswitch s {\n\tcase \"\":\n\t\treturn 10, 0, DecimalSI, true\n\tcase \"n\":\n\t\treturn 10, -9, DecimalSI, true\n\tcase \"u\":\n\t\treturn 10, -6, DecimalSI, true\n\tcase \"m\":\n\t\treturn 10, -3, DecimalSI, true\n\tcase \"k\":\n\t\treturn 10, 3, DecimalSI, true\n\tcase \"M\":\n\t\treturn 10, 6, DecimalSI, true\n\tcase \"G\":\n\t\treturn 10, 9, DecimalSI, true\n\t}\n\treturn l.suffixHandler.interpret(s)\n}","line":{"from":88,"to":106}} {"id":100014784,"name":"newSuffixer","signature":"func newSuffixer() suffixer","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/suffix.go","code":"func newSuffixer() suffixer {\n\tsh := \u0026suffixHandler{}\n\n\t// IMPORTANT: if you change this section you must change fastLookup\n\n\tsh.binSuffixes.addSuffix(\"Ki\", bePair{2, 10})\n\tsh.binSuffixes.addSuffix(\"Mi\", bePair{2, 20})\n\tsh.binSuffixes.addSuffix(\"Gi\", bePair{2, 30})\n\tsh.binSuffixes.addSuffix(\"Ti\", bePair{2, 40})\n\tsh.binSuffixes.addSuffix(\"Pi\", bePair{2, 50})\n\tsh.binSuffixes.addSuffix(\"Ei\", bePair{2, 60})\n\t// Don't emit an error when trying to produce\n\t// a suffix for 2^0.\n\tsh.decSuffixes.addSuffix(\"\", bePair{2, 0})\n\n\tsh.decSuffixes.addSuffix(\"n\", bePair{10, -9})\n\tsh.decSuffixes.addSuffix(\"u\", bePair{10, -6})\n\tsh.decSuffixes.addSuffix(\"m\", bePair{10, -3})\n\tsh.decSuffixes.addSuffix(\"\", bePair{10, 0})\n\tsh.decSuffixes.addSuffix(\"k\", bePair{10, 3})\n\tsh.decSuffixes.addSuffix(\"M\", bePair{10, 6})\n\tsh.decSuffixes.addSuffix(\"G\", bePair{10, 9})\n\tsh.decSuffixes.addSuffix(\"T\", bePair{10, 12})\n\tsh.decSuffixes.addSuffix(\"P\", bePair{10, 15})\n\tsh.decSuffixes.addSuffix(\"E\", bePair{10, 18})\n\n\treturn fastLookup{sh}\n}","line":{"from":108,"to":135}} {"id":100014785,"name":"construct","signature":"func (sh *suffixHandler) construct(base, exponent int32, fmt Format) (s suffix, ok bool)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/suffix.go","code":"func (sh *suffixHandler) construct(base, exponent int32, fmt Format) (s suffix, ok bool) {\n\tswitch fmt {\n\tcase DecimalSI:\n\t\treturn sh.decSuffixes.construct(base, exponent)\n\tcase BinarySI:\n\t\treturn sh.binSuffixes.construct(base, exponent)\n\tcase DecimalExponent:\n\t\tif base != 10 {\n\t\t\treturn \"\", false\n\t\t}\n\t\tif exponent == 0 {\n\t\t\treturn \"\", true\n\t\t}\n\t\treturn suffix(\"e\" + strconv.FormatInt(int64(exponent), 10)), true\n\t}\n\treturn \"\", false\n}","line":{"from":137,"to":153}} {"id":100014786,"name":"constructBytes","signature":"func (sh *suffixHandler) constructBytes(base, exponent int32, format Format) (s []byte, ok bool)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/suffix.go","code":"func (sh *suffixHandler) constructBytes(base, exponent int32, format Format) (s []byte, ok bool) {\n\tswitch format {\n\tcase DecimalSI:\n\t\treturn sh.decSuffixes.constructBytes(base, exponent)\n\tcase BinarySI:\n\t\treturn sh.binSuffixes.constructBytes(base, exponent)\n\tcase DecimalExponent:\n\t\tif base != 10 {\n\t\t\treturn nil, false\n\t\t}\n\t\tif exponent == 0 {\n\t\t\treturn nil, true\n\t\t}\n\t\tresult := make([]byte, 8)\n\t\tresult[0] = 'e'\n\t\tnumber := strconv.AppendInt(result[1:1], int64(exponent), 10)\n\t\tif \u0026result[1] == \u0026number[0] {\n\t\t\treturn result[:1+len(number)], true\n\t\t}\n\t\tresult = append(result[:1], number...)\n\t\treturn result, true\n\t}\n\treturn nil, false\n}","line":{"from":155,"to":178}} {"id":100014787,"name":"interpret","signature":"func (sh *suffixHandler) interpret(suffix suffix) (base, exponent int32, fmt Format, ok bool)","file":"staging/src/k8s.io/apimachinery/pkg/api/resource/suffix.go","code":"func (sh *suffixHandler) interpret(suffix suffix) (base, exponent int32, fmt Format, ok bool) {\n\t// Try lookup tables first\n\tif b, e, ok := sh.decSuffixes.lookup(suffix); ok {\n\t\treturn b, e, DecimalSI, true\n\t}\n\tif b, e, ok := sh.binSuffixes.lookup(suffix); ok {\n\t\treturn b, e, BinarySI, true\n\t}\n\n\tif len(suffix) \u003e 1 \u0026\u0026 (suffix[0] == 'E' || suffix[0] == 'e') {\n\t\tparsed, err := strconv.ParseInt(string(suffix[1:]), 10, 64)\n\t\tif err != nil {\n\t\t\treturn 0, 0, DecimalExponent, false\n\t\t}\n\t\treturn 10, int32(parsed), DecimalExponent, true\n\t}\n\n\treturn 0, 0, DecimalExponent, false\n}","line":{"from":180,"to":198}} {"id":100014788,"name":"NameIsDNSSubdomain","signature":"func NameIsDNSSubdomain(name string, prefix bool) []string","file":"staging/src/k8s.io/apimachinery/pkg/api/validation/generic.go","code":"// NameIsDNSSubdomain is a ValidateNameFunc for names that must be a DNS subdomain.\nfunc NameIsDNSSubdomain(name string, prefix bool) []string {\n\tif prefix {\n\t\tname = maskTrailingDash(name)\n\t}\n\treturn validation.IsDNS1123Subdomain(name)\n}","line":{"from":36,"to":42}} {"id":100014789,"name":"NameIsDNSLabel","signature":"func NameIsDNSLabel(name string, prefix bool) []string","file":"staging/src/k8s.io/apimachinery/pkg/api/validation/generic.go","code":"// NameIsDNSLabel is a ValidateNameFunc for names that must be a DNS 1123 label.\nfunc NameIsDNSLabel(name string, prefix bool) []string {\n\tif prefix {\n\t\tname = maskTrailingDash(name)\n\t}\n\treturn validation.IsDNS1123Label(name)\n}","line":{"from":44,"to":50}} {"id":100014790,"name":"NameIsDNS1035Label","signature":"func NameIsDNS1035Label(name string, prefix bool) []string","file":"staging/src/k8s.io/apimachinery/pkg/api/validation/generic.go","code":"// NameIsDNS1035Label is a ValidateNameFunc for names that must be a DNS 952 label.\nfunc NameIsDNS1035Label(name string, prefix bool) []string {\n\tif prefix {\n\t\tname = maskTrailingDash(name)\n\t}\n\treturn validation.IsDNS1035Label(name)\n}","line":{"from":52,"to":58}} {"id":100014791,"name":"maskTrailingDash","signature":"func maskTrailingDash(name string) string","file":"staging/src/k8s.io/apimachinery/pkg/api/validation/generic.go","code":"// maskTrailingDash replaces the final character of a string with a subdomain safe\n// value if it is a dash and if the length of this string is greater than 1. Note that\n// this is used when a value could be appended to the string, see ValidateNameFunc\n// for more info.\nfunc maskTrailingDash(name string) string {\n\tif len(name) \u003e 1 \u0026\u0026 strings.HasSuffix(name, \"-\") {\n\t\treturn name[:len(name)-2] + \"a\"\n\t}\n\treturn name\n}","line":{"from":70,"to":79}} {"id":100014792,"name":"ValidateNonnegativeField","signature":"func ValidateNonnegativeField(value int64, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/api/validation/generic.go","code":"// ValidateNonnegativeField validates that given value is not negative.\nfunc ValidateNonnegativeField(value int64, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif value \u003c 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, value, IsNegativeErrorMsg))\n\t}\n\treturn allErrs\n}","line":{"from":81,"to":88}} {"id":100014793,"name":"ValidateAnnotations","signature":"func ValidateAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/api/validation/objectmeta.go","code":"// ValidateAnnotations validates that a set of annotations are correctly defined.\nfunc ValidateAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor k := range annotations {\n\t\t// The rule is QualifiedName except that case doesn't matter, so convert to lowercase before checking.\n\t\tfor _, msg := range validation.IsQualifiedName(strings.ToLower(k)) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, k, msg))\n\t\t}\n\t}\n\tif err := ValidateAnnotationsSize(annotations); err != nil {\n\t\tallErrs = append(allErrs, field.TooLong(fldPath, \"\", TotalAnnotationSizeLimitB))\n\t}\n\treturn allErrs\n}","line":{"from":43,"to":56}} {"id":100014794,"name":"ValidateAnnotationsSize","signature":"func ValidateAnnotationsSize(annotations map[string]string) error","file":"staging/src/k8s.io/apimachinery/pkg/api/validation/objectmeta.go","code":"func ValidateAnnotationsSize(annotations map[string]string) error {\n\tvar totalSize int64\n\tfor k, v := range annotations {\n\t\ttotalSize += (int64)(len(k)) + (int64)(len(v))\n\t}\n\tif totalSize \u003e (int64)(TotalAnnotationSizeLimitB) {\n\t\treturn fmt.Errorf(\"annotations size %d is larger than limit %d\", totalSize, TotalAnnotationSizeLimitB)\n\t}\n\treturn nil\n}","line":{"from":58,"to":67}} {"id":100014795,"name":"validateOwnerReference","signature":"func validateOwnerReference(ownerReference metav1.OwnerReference, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/api/validation/objectmeta.go","code":"func validateOwnerReference(ownerReference metav1.OwnerReference, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tgvk := schema.FromAPIVersionAndKind(ownerReference.APIVersion, ownerReference.Kind)\n\t// gvk.Group is empty for the legacy group.\n\tif len(gvk.Version) == 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"apiVersion\"), ownerReference.APIVersion, \"version must not be empty\"))\n\t}\n\tif len(gvk.Kind) == 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"kind\"), ownerReference.Kind, \"kind must not be empty\"))\n\t}\n\tif len(ownerReference.Name) == 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"name\"), ownerReference.Name, \"name must not be empty\"))\n\t}\n\tif len(ownerReference.UID) == 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"uid\"), ownerReference.UID, \"uid must not be empty\"))\n\t}\n\tif _, ok := BannedOwners[gvk]; ok {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, ownerReference, fmt.Sprintf(\"%s is disallowed from being an owner\", gvk)))\n\t}\n\treturn allErrs\n}","line":{"from":69,"to":89}} {"id":100014796,"name":"ValidateOwnerReferences","signature":"func ValidateOwnerReferences(ownerReferences []metav1.OwnerReference, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/api/validation/objectmeta.go","code":"// ValidateOwnerReferences validates that a set of owner references are correctly defined.\nfunc ValidateOwnerReferences(ownerReferences []metav1.OwnerReference, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfirstControllerName := \"\"\n\tfor _, ref := range ownerReferences {\n\t\tallErrs = append(allErrs, validateOwnerReference(ref, fldPath)...)\n\t\tif ref.Controller != nil \u0026\u0026 *ref.Controller {\n\t\t\tcurControllerName := ref.Kind + \"/\" + ref.Name\n\t\t\tif firstControllerName != \"\" {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, ownerReferences,\n\t\t\t\t\tfmt.Sprintf(\"Only one reference can have Controller set to true. Found \\\"true\\\" in references for %v and %v\", firstControllerName, curControllerName)))\n\t\t\t} else {\n\t\t\t\tfirstControllerName = curControllerName\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":91,"to":108}} {"id":100014797,"name":"ValidateFinalizerName","signature":"func ValidateFinalizerName(stringValue string, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/api/validation/objectmeta.go","code":"// ValidateFinalizerName validates finalizer names.\nfunc ValidateFinalizerName(stringValue string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor _, msg := range validation.IsQualifiedName(stringValue) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, stringValue, msg))\n\t}\n\n\treturn allErrs\n}","line":{"from":110,"to":118}} {"id":100014798,"name":"ValidateNoNewFinalizers","signature":"func ValidateNoNewFinalizers(newFinalizers []string, oldFinalizers []string, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/api/validation/objectmeta.go","code":"// ValidateNoNewFinalizers validates the new finalizers has no new finalizers compare to old finalizers.\nfunc ValidateNoNewFinalizers(newFinalizers []string, oldFinalizers []string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\textra := sets.NewString(newFinalizers...).Difference(sets.NewString(oldFinalizers...))\n\tif len(extra) != 0 {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath, fmt.Sprintf(\"no new finalizers can be added if the object is being deleted, found new finalizers %#v\", extra.List())))\n\t}\n\treturn allErrs\n}","line":{"from":120,"to":128}} {"id":100014799,"name":"ValidateImmutableField","signature":"func ValidateImmutableField(newVal, oldVal interface{}, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/api/validation/objectmeta.go","code":"// ValidateImmutableField validates the new value and the old value are deeply equal.\nfunc ValidateImmutableField(newVal, oldVal interface{}, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif !apiequality.Semantic.DeepEqual(oldVal, newVal) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, newVal, FieldImmutableErrorMsg))\n\t}\n\treturn allErrs\n}","line":{"from":130,"to":137}} {"id":100014800,"name":"ValidateObjectMeta","signature":"func ValidateObjectMeta(objMeta *metav1.ObjectMeta, requiresNamespace bool, nameFn ValidateNameFunc, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/api/validation/objectmeta.go","code":"// ValidateObjectMeta validates an object's metadata on creation. It expects that name generation has already\n// been performed.\n// It doesn't return an error for rootscoped resources with namespace, because namespace should already be cleared before.\nfunc ValidateObjectMeta(objMeta *metav1.ObjectMeta, requiresNamespace bool, nameFn ValidateNameFunc, fldPath *field.Path) field.ErrorList {\n\tmetadata, err := meta.Accessor(objMeta)\n\tif err != nil {\n\t\tvar allErrs field.ErrorList\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, objMeta, err.Error()))\n\t\treturn allErrs\n\t}\n\treturn ValidateObjectMetaAccessor(metadata, requiresNamespace, nameFn, fldPath)\n}","line":{"from":139,"to":150}} {"id":100014801,"name":"ValidateObjectMetaAccessor","signature":"func ValidateObjectMetaAccessor(meta metav1.Object, requiresNamespace bool, nameFn ValidateNameFunc, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/api/validation/objectmeta.go","code":"// ValidateObjectMetaAccessor validates an object's metadata on creation. It expects that name generation has already\n// been performed.\n// It doesn't return an error for rootscoped resources with namespace, because namespace should already be cleared before.\nfunc ValidateObjectMetaAccessor(meta metav1.Object, requiresNamespace bool, nameFn ValidateNameFunc, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\n\tif len(meta.GetGenerateName()) != 0 {\n\t\tfor _, msg := range nameFn(meta.GetGenerateName(), true) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"generateName\"), meta.GetGenerateName(), msg))\n\t\t}\n\t}\n\t// If the generated name validates, but the calculated value does not, it's a problem with generation, and we\n\t// report it here. This may confuse users, but indicates a programming bug and still must be validated.\n\t// If there are multiple fields out of which one is required then add an or as a separator\n\tif len(meta.GetName()) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"name\"), \"name or generateName is required\"))\n\t} else {\n\t\tfor _, msg := range nameFn(meta.GetName(), false) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"name\"), meta.GetName(), msg))\n\t\t}\n\t}\n\tif requiresNamespace {\n\t\tif len(meta.GetNamespace()) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"namespace\"), \"\"))\n\t\t} else {\n\t\t\tfor _, msg := range ValidateNamespaceName(meta.GetNamespace(), false) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"namespace\"), meta.GetNamespace(), msg))\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif len(meta.GetNamespace()) != 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"namespace\"), \"not allowed on this type\"))\n\t\t}\n\t}\n\n\tallErrs = append(allErrs, ValidateNonnegativeField(meta.GetGeneration(), fldPath.Child(\"generation\"))...)\n\tallErrs = append(allErrs, v1validation.ValidateLabels(meta.GetLabels(), fldPath.Child(\"labels\"))...)\n\tallErrs = append(allErrs, ValidateAnnotations(meta.GetAnnotations(), fldPath.Child(\"annotations\"))...)\n\tallErrs = append(allErrs, ValidateOwnerReferences(meta.GetOwnerReferences(), fldPath.Child(\"ownerReferences\"))...)\n\tallErrs = append(allErrs, ValidateFinalizers(meta.GetFinalizers(), fldPath.Child(\"finalizers\"))...)\n\tallErrs = append(allErrs, v1validation.ValidateManagedFields(meta.GetManagedFields(), fldPath.Child(\"managedFields\"))...)\n\treturn allErrs\n}","line":{"from":152,"to":194}} {"id":100014802,"name":"ValidateFinalizers","signature":"func ValidateFinalizers(finalizers []string, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/api/validation/objectmeta.go","code":"// ValidateFinalizers tests if the finalizers name are valid, and if there are conflicting finalizers.\nfunc ValidateFinalizers(finalizers []string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\thasFinalizerOrphanDependents := false\n\thasFinalizerDeleteDependents := false\n\tfor _, finalizer := range finalizers {\n\t\tallErrs = append(allErrs, ValidateFinalizerName(finalizer, fldPath)...)\n\t\tif finalizer == metav1.FinalizerOrphanDependents {\n\t\t\thasFinalizerOrphanDependents = true\n\t\t}\n\t\tif finalizer == metav1.FinalizerDeleteDependents {\n\t\t\thasFinalizerDeleteDependents = true\n\t\t}\n\t}\n\tif hasFinalizerDeleteDependents \u0026\u0026 hasFinalizerOrphanDependents {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, finalizers, fmt.Sprintf(\"finalizer %s and %s cannot be both set\", metav1.FinalizerOrphanDependents, metav1.FinalizerDeleteDependents)))\n\t}\n\treturn allErrs\n}","line":{"from":196,"to":214}} {"id":100014803,"name":"ValidateObjectMetaUpdate","signature":"func ValidateObjectMetaUpdate(newMeta, oldMeta *metav1.ObjectMeta, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/api/validation/objectmeta.go","code":"// ValidateObjectMetaUpdate validates an object's metadata when updated.\nfunc ValidateObjectMetaUpdate(newMeta, oldMeta *metav1.ObjectMeta, fldPath *field.Path) field.ErrorList {\n\tnewMetadata, err := meta.Accessor(newMeta)\n\tif err != nil {\n\t\tallErrs := field.ErrorList{}\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, newMeta, err.Error()))\n\t\treturn allErrs\n\t}\n\toldMetadata, err := meta.Accessor(oldMeta)\n\tif err != nil {\n\t\tallErrs := field.ErrorList{}\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, oldMeta, err.Error()))\n\t\treturn allErrs\n\t}\n\treturn ValidateObjectMetaAccessorUpdate(newMetadata, oldMetadata, fldPath)\n}","line":{"from":216,"to":231}} {"id":100014804,"name":"ValidateObjectMetaAccessorUpdate","signature":"func ValidateObjectMetaAccessorUpdate(newMeta, oldMeta metav1.Object, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/api/validation/objectmeta.go","code":"// ValidateObjectMetaAccessorUpdate validates an object's metadata when updated.\nfunc ValidateObjectMetaAccessorUpdate(newMeta, oldMeta metav1.Object, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\n\t// Finalizers cannot be added if the object is already being deleted.\n\tif oldMeta.GetDeletionTimestamp() != nil {\n\t\tallErrs = append(allErrs, ValidateNoNewFinalizers(newMeta.GetFinalizers(), oldMeta.GetFinalizers(), fldPath.Child(\"finalizers\"))...)\n\t}\n\n\t// Reject updates that don't specify a resource version\n\tif len(newMeta.GetResourceVersion()) == 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"resourceVersion\"), newMeta.GetResourceVersion(), \"must be specified for an update\"))\n\t}\n\n\t// Generation shouldn't be decremented\n\tif newMeta.GetGeneration() \u003c oldMeta.GetGeneration() {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"generation\"), newMeta.GetGeneration(), \"must not be decremented\"))\n\t}\n\n\tallErrs = append(allErrs, ValidateImmutableField(newMeta.GetName(), oldMeta.GetName(), fldPath.Child(\"name\"))...)\n\tallErrs = append(allErrs, ValidateImmutableField(newMeta.GetNamespace(), oldMeta.GetNamespace(), fldPath.Child(\"namespace\"))...)\n\tallErrs = append(allErrs, ValidateImmutableField(newMeta.GetUID(), oldMeta.GetUID(), fldPath.Child(\"uid\"))...)\n\tallErrs = append(allErrs, ValidateImmutableField(newMeta.GetCreationTimestamp(), oldMeta.GetCreationTimestamp(), fldPath.Child(\"creationTimestamp\"))...)\n\tallErrs = append(allErrs, ValidateImmutableField(newMeta.GetDeletionTimestamp(), oldMeta.GetDeletionTimestamp(), fldPath.Child(\"deletionTimestamp\"))...)\n\tallErrs = append(allErrs, ValidateImmutableField(newMeta.GetDeletionGracePeriodSeconds(), oldMeta.GetDeletionGracePeriodSeconds(), fldPath.Child(\"deletionGracePeriodSeconds\"))...)\n\n\tallErrs = append(allErrs, v1validation.ValidateLabels(newMeta.GetLabels(), fldPath.Child(\"labels\"))...)\n\tallErrs = append(allErrs, ValidateAnnotations(newMeta.GetAnnotations(), fldPath.Child(\"annotations\"))...)\n\tallErrs = append(allErrs, ValidateOwnerReferences(newMeta.GetOwnerReferences(), fldPath.Child(\"ownerReferences\"))...)\n\tallErrs = append(allErrs, v1validation.ValidateManagedFields(newMeta.GetManagedFields(), fldPath.Child(\"managedFields\"))...)\n\n\treturn allErrs\n}","line":{"from":233,"to":265}} {"id":100014805,"name":"IsValidPathSegmentName","signature":"func IsValidPathSegmentName(name string) []string","file":"staging/src/k8s.io/apimachinery/pkg/api/validation/path/name.go","code":"// IsValidPathSegmentName validates the name can be safely encoded as a path segment\nfunc IsValidPathSegmentName(name string) []string {\n\tfor _, illegalName := range NameMayNotBe {\n\t\tif name == illegalName {\n\t\t\treturn []string{fmt.Sprintf(`may not be '%s'`, illegalName)}\n\t\t}\n\t}\n\n\tvar errors []string\n\tfor _, illegalContent := range NameMayNotContain {\n\t\tif strings.Contains(name, illegalContent) {\n\t\t\terrors = append(errors, fmt.Sprintf(`may not contain '%s'`, illegalContent))\n\t\t}\n\t}\n\n\treturn errors\n}","line":{"from":30,"to":46}} {"id":100014806,"name":"IsValidPathSegmentPrefix","signature":"func IsValidPathSegmentPrefix(name string) []string","file":"staging/src/k8s.io/apimachinery/pkg/api/validation/path/name.go","code":"// IsValidPathSegmentPrefix validates the name can be used as a prefix for a name which will be encoded as a path segment\n// It does not check for exact matches with disallowed names, since an arbitrary suffix might make the name valid\nfunc IsValidPathSegmentPrefix(name string) []string {\n\tvar errors []string\n\tfor _, illegalContent := range NameMayNotContain {\n\t\tif strings.Contains(name, illegalContent) {\n\t\t\terrors = append(errors, fmt.Sprintf(`may not contain '%s'`, illegalContent))\n\t\t}\n\t}\n\n\treturn errors\n}","line":{"from":48,"to":59}} {"id":100014807,"name":"ValidatePathSegmentName","signature":"func ValidatePathSegmentName(name string, prefix bool) []string","file":"staging/src/k8s.io/apimachinery/pkg/api/validation/path/name.go","code":"// ValidatePathSegmentName validates the name can be safely encoded as a path segment\nfunc ValidatePathSegmentName(name string, prefix bool) []string {\n\tif prefix {\n\t\treturn IsValidPathSegmentPrefix(name)\n\t}\n\n\treturn IsValidPathSegmentName(name)\n}","line":{"from":61,"to":68}} {"id":100014808,"name":"genericFuzzerFuncs","signature":"func genericFuzzerFuncs(codecs runtimeserializer.CodecFactory) []interface{}","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/fuzzer/fuzzer.go","code":"func genericFuzzerFuncs(codecs runtimeserializer.CodecFactory) []interface{} {\n\treturn []interface{}{\n\t\tfunc(q *resource.Quantity, c fuzz.Continue) {\n\t\t\t*q = *resource.NewQuantity(c.Int63n(1000), resource.DecimalExponent)\n\t\t},\n\t\tfunc(j *int, c fuzz.Continue) {\n\t\t\t*j = int(c.Int31())\n\t\t},\n\t\tfunc(j **int, c fuzz.Continue) {\n\t\t\tif c.RandBool() {\n\t\t\t\ti := int(c.Int31())\n\t\t\t\t*j = \u0026i\n\t\t\t} else {\n\t\t\t\t*j = nil\n\t\t\t}\n\t\t},\n\t\tfunc(j *runtime.TypeMeta, c fuzz.Continue) {\n\t\t\t// We have to customize the randomization of TypeMetas because their\n\t\t\t// APIVersion and Kind must remain blank in memory.\n\t\t\tj.APIVersion = \"\"\n\t\t\tj.Kind = \"\"\n\t\t},\n\t\tfunc(j *runtime.Object, c fuzz.Continue) {\n\t\t\t// TODO: uncomment when round trip starts from a versioned object\n\t\t\tif true { //c.RandBool() {\n\t\t\t\t*j = \u0026runtime.Unknown{\n\t\t\t\t\t// We do not set TypeMeta here because it is not carried through a round trip\n\t\t\t\t\tRaw: []byte(`{\"apiVersion\":\"unknown.group/unknown\",\"kind\":\"Something\",\"someKey\":\"someValue\"}`),\n\t\t\t\t\tContentType: runtime.ContentTypeJSON,\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttypes := []runtime.Object{\u0026metav1.Status{}, \u0026metav1.APIGroup{}}\n\t\t\t\tt := types[c.Rand.Intn(len(types))]\n\t\t\t\tc.Fuzz(t)\n\t\t\t\t*j = t\n\t\t\t}\n\t\t},\n\t\tfunc(r *runtime.RawExtension, c fuzz.Continue) {\n\t\t\t// Pick an arbitrary type and fuzz it\n\t\t\ttypes := []runtime.Object{\u0026metav1.Status{}, \u0026metav1.APIGroup{}}\n\t\t\tobj := types[c.Rand.Intn(len(types))]\n\t\t\tc.Fuzz(obj)\n\n\t\t\t// Find a codec for converting the object to raw bytes. This is necessary for the\n\t\t\t// api version and kind to be correctly set be serialization.\n\t\t\tvar codec = apitesting.TestCodec(codecs, metav1.SchemeGroupVersion)\n\n\t\t\t// Convert the object to raw bytes\n\t\t\tbytes, err := runtime.Encode(codec, obj)\n\t\t\tif err != nil {\n\t\t\t\tpanic(fmt.Sprintf(\"Failed to encode object: %v\", err))\n\t\t\t}\n\n\t\t\t// strip trailing newlines which do not survive roundtrips\n\t\t\tfor len(bytes) \u003e= 1 \u0026\u0026 bytes[len(bytes)-1] == 10 {\n\t\t\t\tbytes = bytes[:len(bytes)-1]\n\t\t\t}\n\n\t\t\t// Set the bytes field on the RawExtension\n\t\t\tr.Raw = bytes\n\t\t},\n\t}\n}","line":{"from":38,"to":100}} {"id":100014809,"name":"choose","signature":"func (c *charRange) choose(r *rand.Rand) rune","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/fuzzer/fuzzer.go","code":"func (c *charRange) choose(r *rand.Rand) rune {\n\tcount := int64(c.last - c.first + 1)\n\tch := c.first + rune(r.Int63n(count))\n\n\treturn ch\n}","line":{"from":107,"to":112}} {"id":100014810,"name":"randomLabelPart","signature":"func randomLabelPart(c fuzz.Continue, canBeEmpty bool) string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/fuzzer/fuzzer.go","code":"// randomLabelPart produces a valid random label value or name-part\n// of a label key.\nfunc randomLabelPart(c fuzz.Continue, canBeEmpty bool) string {\n\tvalidStartEnd := []charRange{{'0', '9'}, {'a', 'z'}, {'A', 'Z'}}\n\tvalidMiddle := []charRange{{'0', '9'}, {'a', 'z'}, {'A', 'Z'},\n\t\t{'.', '.'}, {'-', '-'}, {'_', '_'}}\n\n\tpartLen := c.Rand.Intn(64) // len is [0, 63]\n\tif !canBeEmpty {\n\t\tpartLen = c.Rand.Intn(63) + 1 // len is [1, 63]\n\t}\n\n\trunes := make([]rune, partLen)\n\tif partLen == 0 {\n\t\treturn string(runes)\n\t}\n\n\trunes[0] = validStartEnd[c.Rand.Intn(len(validStartEnd))].choose(c.Rand)\n\tfor i := range runes[1:] {\n\t\trunes[i+1] = validMiddle[c.Rand.Intn(len(validMiddle))].choose(c.Rand)\n\t}\n\trunes[len(runes)-1] = validStartEnd[c.Rand.Intn(len(validStartEnd))].choose(c.Rand)\n\n\treturn string(runes)\n}","line":{"from":114,"to":138}} {"id":100014811,"name":"randomDNSLabel","signature":"func randomDNSLabel(c fuzz.Continue) string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/fuzzer/fuzzer.go","code":"func randomDNSLabel(c fuzz.Continue) string {\n\tvalidStartEnd := []charRange{{'0', '9'}, {'a', 'z'}}\n\tvalidMiddle := []charRange{{'0', '9'}, {'a', 'z'}, {'-', '-'}}\n\n\tpartLen := c.Rand.Intn(63) + 1 // len is [1, 63]\n\trunes := make([]rune, partLen)\n\n\trunes[0] = validStartEnd[c.Rand.Intn(len(validStartEnd))].choose(c.Rand)\n\tfor i := range runes[1:] {\n\t\trunes[i+1] = validMiddle[c.Rand.Intn(len(validMiddle))].choose(c.Rand)\n\t}\n\trunes[len(runes)-1] = validStartEnd[c.Rand.Intn(len(validStartEnd))].choose(c.Rand)\n\n\treturn string(runes)\n}","line":{"from":140,"to":154}} {"id":100014812,"name":"randomLabelKey","signature":"func randomLabelKey(c fuzz.Continue) string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/fuzzer/fuzzer.go","code":"func randomLabelKey(c fuzz.Continue) string {\n\tnamePart := randomLabelPart(c, false)\n\tprefixPart := \"\"\n\n\tusePrefix := c.RandBool()\n\tif usePrefix {\n\t\t// we can fit, with dots, at most 3 labels in the 253 allotted characters\n\t\tprefixPartsLen := c.Rand.Intn(2) + 1\n\t\tprefixParts := make([]string, prefixPartsLen)\n\t\tfor i := range prefixParts {\n\t\t\tprefixParts[i] = randomDNSLabel(c)\n\t\t}\n\t\tprefixPart = strings.Join(prefixParts, \".\") + \"/\"\n\t}\n\n\treturn prefixPart + namePart\n}","line":{"from":156,"to":172}} {"id":100014813,"name":"v1FuzzerFuncs","signature":"func v1FuzzerFuncs(codecs runtimeserializer.CodecFactory) []interface{}","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/fuzzer/fuzzer.go","code":"func v1FuzzerFuncs(codecs runtimeserializer.CodecFactory) []interface{} {\n\n\treturn []interface{}{\n\t\tfunc(j *metav1.TypeMeta, c fuzz.Continue) {\n\t\t\t// We have to customize the randomization of TypeMetas because their\n\t\t\t// APIVersion and Kind must remain blank in memory.\n\t\t\tj.APIVersion = \"\"\n\t\t\tj.Kind = \"\"\n\t\t},\n\t\tfunc(j *metav1.ObjectMeta, c fuzz.Continue) {\n\t\t\tc.FuzzNoCustom(j)\n\n\t\t\tj.ResourceVersion = strconv.FormatUint(c.RandUint64(), 10)\n\t\t\tj.UID = types.UID(c.RandString())\n\n\t\t\t// Fuzzing sec and nsec in a smaller range (uint32 instead of int64),\n\t\t\t// so that the result Unix time is a valid date and can be parsed into RFC3339 format.\n\t\t\tvar sec, nsec uint32\n\t\t\tc.Fuzz(\u0026sec)\n\t\t\tc.Fuzz(\u0026nsec)\n\t\t\tj.CreationTimestamp = metav1.Unix(int64(sec), int64(nsec)).Rfc3339Copy()\n\n\t\t\tif j.DeletionTimestamp != nil {\n\t\t\t\tc.Fuzz(\u0026sec)\n\t\t\t\tc.Fuzz(\u0026nsec)\n\t\t\t\tt := metav1.Unix(int64(sec), int64(nsec)).Rfc3339Copy()\n\t\t\t\tj.DeletionTimestamp = \u0026t\n\t\t\t}\n\n\t\t\tif len(j.Labels) == 0 {\n\t\t\t\tj.Labels = nil\n\t\t\t} else {\n\t\t\t\tdelete(j.Labels, \"\")\n\t\t\t}\n\t\t\tif len(j.Annotations) == 0 {\n\t\t\t\tj.Annotations = nil\n\t\t\t} else {\n\t\t\t\tdelete(j.Annotations, \"\")\n\t\t\t}\n\t\t\tif len(j.OwnerReferences) == 0 {\n\t\t\t\tj.OwnerReferences = nil\n\t\t\t}\n\t\t\tif len(j.Finalizers) == 0 {\n\t\t\t\tj.Finalizers = nil\n\t\t\t}\n\t\t},\n\t\tfunc(j *metav1.ResourceVersionMatch, c fuzz.Continue) {\n\t\t\tmatches := []metav1.ResourceVersionMatch{\"\", metav1.ResourceVersionMatchExact, metav1.ResourceVersionMatchNotOlderThan}\n\t\t\t*j = matches[c.Rand.Intn(len(matches))]\n\t\t},\n\t\tfunc(j *metav1.ListMeta, c fuzz.Continue) {\n\t\t\tj.ResourceVersion = strconv.FormatUint(c.RandUint64(), 10)\n\t\t\tj.SelfLink = c.RandString()\n\t\t},\n\t\tfunc(j *metav1.LabelSelector, c fuzz.Continue) {\n\t\t\tc.FuzzNoCustom(j)\n\t\t\t// we can't have an entirely empty selector, so force\n\t\t\t// use of MatchExpression if necessary\n\t\t\tif len(j.MatchLabels) == 0 \u0026\u0026 len(j.MatchExpressions) == 0 {\n\t\t\t\tj.MatchExpressions = make([]metav1.LabelSelectorRequirement, c.Rand.Intn(2)+1)\n\t\t\t}\n\n\t\t\tif j.MatchLabels != nil {\n\t\t\t\tfuzzedMatchLabels := make(map[string]string, len(j.MatchLabels))\n\t\t\t\tfor i := 0; i \u003c len(j.MatchLabels); i++ {\n\t\t\t\t\tfuzzedMatchLabels[randomLabelKey(c)] = randomLabelPart(c, true)\n\t\t\t\t}\n\t\t\t\tj.MatchLabels = fuzzedMatchLabels\n\t\t\t}\n\n\t\t\tvalidOperators := []metav1.LabelSelectorOperator{\n\t\t\t\tmetav1.LabelSelectorOpIn,\n\t\t\t\tmetav1.LabelSelectorOpNotIn,\n\t\t\t\tmetav1.LabelSelectorOpExists,\n\t\t\t\tmetav1.LabelSelectorOpDoesNotExist,\n\t\t\t}\n\n\t\t\tif j.MatchExpressions != nil {\n\t\t\t\t// NB: the label selector parser code sorts match expressions by key, and sorts the values,\n\t\t\t\t// so we need to make sure ours are sorted as well here to preserve round-trip comparison.\n\t\t\t\t// In practice, not sorting doesn't hurt anything...\n\n\t\t\t\tfor i := range j.MatchExpressions {\n\t\t\t\t\treq := metav1.LabelSelectorRequirement{}\n\t\t\t\t\tc.Fuzz(\u0026req)\n\t\t\t\t\treq.Key = randomLabelKey(c)\n\t\t\t\t\treq.Operator = validOperators[c.Rand.Intn(len(validOperators))]\n\t\t\t\t\tif req.Operator == metav1.LabelSelectorOpIn || req.Operator == metav1.LabelSelectorOpNotIn {\n\t\t\t\t\t\tif len(req.Values) == 0 {\n\t\t\t\t\t\t\t// we must have some values here, so randomly choose a short length\n\t\t\t\t\t\t\treq.Values = make([]string, c.Rand.Intn(2)+1)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor i := range req.Values {\n\t\t\t\t\t\t\treq.Values[i] = randomLabelPart(c, true)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsort.Strings(req.Values)\n\t\t\t\t\t} else {\n\t\t\t\t\t\treq.Values = nil\n\t\t\t\t\t}\n\t\t\t\t\tj.MatchExpressions[i] = req\n\t\t\t\t}\n\n\t\t\t\tsort.Slice(j.MatchExpressions, func(a, b int) bool { return j.MatchExpressions[a].Key \u003c j.MatchExpressions[b].Key })\n\t\t\t}\n\t\t},\n\t\tfunc(j *metav1.ManagedFieldsEntry, c fuzz.Continue) {\n\t\t\tc.FuzzNoCustom(j)\n\t\t\tj.FieldsV1 = nil\n\t\t},\n\t}\n}","line":{"from":174,"to":284}} {"id":100014814,"name":"v1beta1FuzzerFuncs","signature":"func v1beta1FuzzerFuncs(codecs runtimeserializer.CodecFactory) []interface{}","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/fuzzer/fuzzer.go","code":"func v1beta1FuzzerFuncs(codecs runtimeserializer.CodecFactory) []interface{} {\n\treturn []interface{}{\n\t\tfunc(r *metav1beta1.TableOptions, c fuzz.Continue) {\n\t\t\tc.FuzzNoCustom(r)\n\t\t\t// NoHeaders is not serialized to the wire but is allowed within the versioned\n\t\t\t// type because we don't use meta internal types in the client and API server.\n\t\t\tr.NoHeaders = false\n\t\t},\n\t\tfunc(r *metav1beta1.TableRow, c fuzz.Continue) {\n\t\t\tc.Fuzz(\u0026r.Object)\n\t\t\tc.Fuzz(\u0026r.Conditions)\n\t\t\tif len(r.Conditions) == 0 {\n\t\t\t\tr.Conditions = nil\n\t\t\t}\n\t\t\tn := c.Intn(10)\n\t\t\tif n \u003e 0 {\n\t\t\t\tr.Cells = make([]interface{}, n)\n\t\t\t}\n\t\t\tfor i := range r.Cells {\n\t\t\t\tt := c.Intn(6)\n\t\t\t\tswitch t {\n\t\t\t\tcase 0:\n\t\t\t\t\tr.Cells[i] = c.RandString()\n\t\t\t\tcase 1:\n\t\t\t\t\tr.Cells[i] = c.Int63()\n\t\t\t\tcase 2:\n\t\t\t\t\tr.Cells[i] = c.RandBool()\n\t\t\t\tcase 3:\n\t\t\t\t\tx := map[string]interface{}{}\n\t\t\t\t\tfor j := c.Intn(10) + 1; j \u003e= 0; j-- {\n\t\t\t\t\t\tx[c.RandString()] = c.RandString()\n\t\t\t\t\t}\n\t\t\t\t\tr.Cells[i] = x\n\t\t\t\tcase 4:\n\t\t\t\t\tx := make([]interface{}, c.Intn(10))\n\t\t\t\t\tfor i := range x {\n\t\t\t\t\t\tx[i] = c.Int63()\n\t\t\t\t\t}\n\t\t\t\t\tr.Cells[i] = x\n\t\t\t\tdefault:\n\t\t\t\t\tr.Cells[i] = nil\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t}\n}","line":{"from":286,"to":331}} {"id":100014815,"name":"SetListOptionsDefaults","signature":"func SetListOptionsDefaults(obj *ListOptions, isWatchListFeatureEnabled bool)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/internalversion/defaults.go","code":"// SetListOptionsDefaults sets defaults on the provided ListOptions if applicable.\n//\n// TODO(#115478): once the watch-list fg is always on we register this function in the scheme (via AddTypeDefaultingFunc).\n// TODO(#115478): when the function is registered in the scheme remove all callers of this method.\nfunc SetListOptionsDefaults(obj *ListOptions, isWatchListFeatureEnabled bool) {\n\tif !isWatchListFeatureEnabled {\n\t\treturn\n\t}\n\tif obj.SendInitialEvents != nil || len(obj.ResourceVersionMatch) != 0 {\n\t\treturn\n\t}\n\tlegacy := obj.ResourceVersion == \"\" || obj.ResourceVersion == \"0\"\n\tif obj.Watch \u0026\u0026 legacy {\n\t\tturnOnInitialEvents := true\n\t\tobj.SendInitialEvents = \u0026turnOnInitialEvents\n\t\tobj.ResourceVersionMatch = metav1.ResourceVersionMatchNotOlderThan\n\t}\n}","line":{"from":21,"to":38}} {"id":100014816,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/internalversion/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":40,"to":43}} {"id":100014817,"name":"addToGroupVersion","signature":"func addToGroupVersion(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/internalversion/register.go","code":"// addToGroupVersion registers common meta types into schemas.\nfunc addToGroupVersion(scheme *runtime.Scheme) error {\n\tif err := scheme.AddIgnoredConversionType(\u0026metav1.TypeMeta{}, \u0026metav1.TypeMeta{}); err != nil {\n\t\treturn err\n\t}\n\t// ListOptions is the only options struct which needs conversion (it exposes labels and fields\n\t// as selectors for convenience). The other types have only a single representation today.\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026ListOptions{},\n\t\t\u0026metav1.GetOptions{},\n\t\t\u0026metav1.DeleteOptions{},\n\t\t\u0026metav1.CreateOptions{},\n\t\t\u0026metav1.UpdateOptions{},\n\t)\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026metav1.Table{},\n\t\t\u0026metav1.TableOptions{},\n\t\t\u0026metav1beta1.PartialObjectMetadata{},\n\t\t\u0026metav1beta1.PartialObjectMetadataList{},\n\t)\n\tif err := metav1beta1.AddMetaToScheme(scheme); err != nil {\n\t\treturn err\n\t}\n\tif err := metav1.AddMetaToScheme(scheme); err != nil {\n\t\treturn err\n\t}\n\t// Allow delete options to be decoded across all version in this scheme (we may want to be more clever than this)\n\tscheme.AddUnversionedTypes(SchemeGroupVersion,\n\t\t\u0026metav1.DeleteOptions{},\n\t\t\u0026metav1.CreateOptions{},\n\t\t\u0026metav1.UpdateOptions{})\n\n\tmetav1.AddToGroupVersion(scheme, metav1.SchemeGroupVersion)\n\tif err := metav1beta1.RegisterConversions(scheme); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":45,"to":82}} {"id":100014818,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/internalversion/register.go","code":"// Unlike other API groups, meta internal knows about all meta external versions, but keeps\n// the logic for conversion private.\nfunc init() {\n\tlocalSchemeBuilder.Register(addToGroupVersion)\n}","line":{"from":84,"to":88}} {"id":100014819,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/internalversion/scheme/register.go","code":"// Unlike other API groups, meta internal knows about all meta external versions, but keeps\n// the logic for conversion private.\nfunc init() {\n\tutilruntime.Must(internalversion.AddToScheme(scheme))\n}","line":{"from":35,"to":39}} {"id":100014820,"name":"ValidateListOptions","signature":"func ValidateListOptions(options *internalversion.ListOptions, isWatchListFeatureEnabled bool) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/internalversion/validation/validation.go","code":"// ValidateListOptions returns all validation errors found while validating the ListOptions.\nfunc ValidateListOptions(options *internalversion.ListOptions, isWatchListFeatureEnabled bool) field.ErrorList {\n\tif options.Watch {\n\t\treturn validateWatchOptions(options, isWatchListFeatureEnabled)\n\t}\n\tallErrs := field.ErrorList{}\n\tif match := options.ResourceVersionMatch; len(match) \u003e 0 {\n\t\tif len(options.ResourceVersion) == 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"resourceVersionMatch\"), \"resourceVersionMatch is forbidden unless resourceVersion is provided\"))\n\t\t}\n\t\tif len(options.Continue) \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"resourceVersionMatch\"), \"resourceVersionMatch is forbidden when continue is provided\"))\n\t\t}\n\t\tif match != metav1.ResourceVersionMatchExact \u0026\u0026 match != metav1.ResourceVersionMatchNotOlderThan {\n\t\t\tallErrs = append(allErrs, field.NotSupported(field.NewPath(\"resourceVersionMatch\"), match, []string{string(metav1.ResourceVersionMatchExact), string(metav1.ResourceVersionMatchNotOlderThan), \"\"}))\n\t\t}\n\t\tif match == metav1.ResourceVersionMatchExact \u0026\u0026 options.ResourceVersion == \"0\" {\n\t\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"resourceVersionMatch\"), \"resourceVersionMatch \\\"exact\\\" is forbidden for resourceVersion \\\"0\\\"\"))\n\t\t}\n\t}\n\tif options.SendInitialEvents != nil {\n\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"sendInitialEvents\"), \"sendInitialEvents is forbidden for list\"))\n\t}\n\treturn allErrs\n}","line":{"from":27,"to":51}} {"id":100014821,"name":"validateWatchOptions","signature":"func validateWatchOptions(options *internalversion.ListOptions, isWatchListFeatureEnabled bool) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/internalversion/validation/validation.go","code":"func validateWatchOptions(options *internalversion.ListOptions, isWatchListFeatureEnabled bool) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tmatch := options.ResourceVersionMatch\n\tif options.SendInitialEvents != nil {\n\t\tif match != metav1.ResourceVersionMatchNotOlderThan {\n\t\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"resourceVersionMatch\"), fmt.Sprintf(\"sendInitialEvents requires setting resourceVersionMatch to %s\", metav1.ResourceVersionMatchNotOlderThan)))\n\t\t}\n\t\tif !isWatchListFeatureEnabled {\n\t\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"sendInitialEvents\"), \"sendInitialEvents is forbidden for watch unless the WatchList feature gate is enabled\"))\n\t\t}\n\t}\n\tif len(match) \u003e 0 {\n\t\tif options.SendInitialEvents == nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"resourceVersionMatch\"), \"resourceVersionMatch is forbidden for watch unless sendInitialEvents is provided\"))\n\t\t}\n\t\tif match != metav1.ResourceVersionMatchNotOlderThan {\n\t\t\tallErrs = append(allErrs, field.NotSupported(field.NewPath(\"resourceVersionMatch\"), match, []string{string(metav1.ResourceVersionMatchNotOlderThan)}))\n\t\t}\n\t\tif len(options.Continue) \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"resourceVersionMatch\"), \"resourceVersionMatch is forbidden when continue is provided\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":53,"to":76}} {"id":100014822,"name":"IsControlledBy","signature":"func IsControlledBy(obj Object, owner Object) bool","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/controller_ref.go","code":"// IsControlledBy checks if the object has a controllerRef set to the given owner\nfunc IsControlledBy(obj Object, owner Object) bool {\n\tref := GetControllerOfNoCopy(obj)\n\tif ref == nil {\n\t\treturn false\n\t}\n\treturn ref.UID == owner.GetUID()\n}","line":{"from":23,"to":30}} {"id":100014823,"name":"GetControllerOf","signature":"func GetControllerOf(controllee Object) *OwnerReference","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/controller_ref.go","code":"// GetControllerOf returns a pointer to a copy of the controllerRef if controllee has a controller\nfunc GetControllerOf(controllee Object) *OwnerReference {\n\tref := GetControllerOfNoCopy(controllee)\n\tif ref == nil {\n\t\treturn nil\n\t}\n\tcp := *ref\n\treturn \u0026cp\n}","line":{"from":32,"to":40}} {"id":100014824,"name":"GetControllerOfNoCopy","signature":"func GetControllerOfNoCopy(controllee Object) *OwnerReference","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/controller_ref.go","code":"// GetControllerOf returns a pointer to the controllerRef if controllee has a controller\nfunc GetControllerOfNoCopy(controllee Object) *OwnerReference {\n\trefs := controllee.GetOwnerReferences()\n\tfor i := range refs {\n\t\tif refs[i].Controller != nil \u0026\u0026 *refs[i].Controller {\n\t\t\treturn \u0026refs[i]\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":42,"to":51}} {"id":100014825,"name":"NewControllerRef","signature":"func NewControllerRef(owner Object, gvk schema.GroupVersionKind) *OwnerReference","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/controller_ref.go","code":"// NewControllerRef creates an OwnerReference pointing to the given owner.\nfunc NewControllerRef(owner Object, gvk schema.GroupVersionKind) *OwnerReference {\n\tblockOwnerDeletion := true\n\tisController := true\n\treturn \u0026OwnerReference{\n\t\tAPIVersion: gvk.GroupVersion().String(),\n\t\tKind: gvk.Kind,\n\t\tName: owner.GetName(),\n\t\tUID: owner.GetUID(),\n\t\tBlockOwnerDeletion: \u0026blockOwnerDeletion,\n\t\tController: \u0026isController,\n\t}\n}","line":{"from":53,"to":65}} {"id":100014826,"name":"Convert_Pointer_float64_To_float64","signature":"func Convert_Pointer_float64_To_float64(in **float64, out *float64, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"func Convert_Pointer_float64_To_float64(in **float64, out *float64, s conversion.Scope) error {\n\tif *in == nil {\n\t\t*out = 0\n\t\treturn nil\n\t}\n\t*out = float64(**in)\n\treturn nil\n}","line":{"from":33,"to":40}} {"id":100014827,"name":"Convert_float64_To_Pointer_float64","signature":"func Convert_float64_To_Pointer_float64(in *float64, out **float64, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"func Convert_float64_To_Pointer_float64(in *float64, out **float64, s conversion.Scope) error {\n\ttemp := float64(*in)\n\t*out = \u0026temp\n\treturn nil\n}","line":{"from":42,"to":46}} {"id":100014828,"name":"Convert_Pointer_int32_To_int32","signature":"func Convert_Pointer_int32_To_int32(in **int32, out *int32, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"func Convert_Pointer_int32_To_int32(in **int32, out *int32, s conversion.Scope) error {\n\tif *in == nil {\n\t\t*out = 0\n\t\treturn nil\n\t}\n\t*out = int32(**in)\n\treturn nil\n}","line":{"from":48,"to":55}} {"id":100014829,"name":"Convert_int32_To_Pointer_int32","signature":"func Convert_int32_To_Pointer_int32(in *int32, out **int32, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"func Convert_int32_To_Pointer_int32(in *int32, out **int32, s conversion.Scope) error {\n\ttemp := int32(*in)\n\t*out = \u0026temp\n\treturn nil\n}","line":{"from":57,"to":61}} {"id":100014830,"name":"Convert_Pointer_int64_To_int64","signature":"func Convert_Pointer_int64_To_int64(in **int64, out *int64, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"func Convert_Pointer_int64_To_int64(in **int64, out *int64, s conversion.Scope) error {\n\tif *in == nil {\n\t\t*out = 0\n\t\treturn nil\n\t}\n\t*out = int64(**in)\n\treturn nil\n}","line":{"from":63,"to":70}} {"id":100014831,"name":"Convert_int64_To_Pointer_int64","signature":"func Convert_int64_To_Pointer_int64(in *int64, out **int64, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"func Convert_int64_To_Pointer_int64(in *int64, out **int64, s conversion.Scope) error {\n\ttemp := int64(*in)\n\t*out = \u0026temp\n\treturn nil\n}","line":{"from":72,"to":76}} {"id":100014832,"name":"Convert_Pointer_int64_To_int","signature":"func Convert_Pointer_int64_To_int(in **int64, out *int, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"func Convert_Pointer_int64_To_int(in **int64, out *int, s conversion.Scope) error {\n\tif *in == nil {\n\t\t*out = 0\n\t\treturn nil\n\t}\n\t*out = int(**in)\n\treturn nil\n}","line":{"from":78,"to":85}} {"id":100014833,"name":"Convert_int_To_Pointer_int64","signature":"func Convert_int_To_Pointer_int64(in *int, out **int64, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"func Convert_int_To_Pointer_int64(in *int, out **int64, s conversion.Scope) error {\n\ttemp := int64(*in)\n\t*out = \u0026temp\n\treturn nil\n}","line":{"from":87,"to":91}} {"id":100014834,"name":"Convert_Pointer_string_To_string","signature":"func Convert_Pointer_string_To_string(in **string, out *string, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"func Convert_Pointer_string_To_string(in **string, out *string, s conversion.Scope) error {\n\tif *in == nil {\n\t\t*out = \"\"\n\t\treturn nil\n\t}\n\t*out = **in\n\treturn nil\n}","line":{"from":93,"to":100}} {"id":100014835,"name":"Convert_string_To_Pointer_string","signature":"func Convert_string_To_Pointer_string(in *string, out **string, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"func Convert_string_To_Pointer_string(in *string, out **string, s conversion.Scope) error {\n\tif in == nil {\n\t\tstringVar := \"\"\n\t\t*out = \u0026stringVar\n\t\treturn nil\n\t}\n\t*out = in\n\treturn nil\n}","line":{"from":102,"to":110}} {"id":100014836,"name":"Convert_Pointer_bool_To_bool","signature":"func Convert_Pointer_bool_To_bool(in **bool, out *bool, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"func Convert_Pointer_bool_To_bool(in **bool, out *bool, s conversion.Scope) error {\n\tif *in == nil {\n\t\t*out = false\n\t\treturn nil\n\t}\n\t*out = **in\n\treturn nil\n}","line":{"from":112,"to":119}} {"id":100014837,"name":"Convert_bool_To_Pointer_bool","signature":"func Convert_bool_To_Pointer_bool(in *bool, out **bool, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"func Convert_bool_To_Pointer_bool(in *bool, out **bool, s conversion.Scope) error {\n\tif in == nil {\n\t\tboolVar := false\n\t\t*out = \u0026boolVar\n\t\treturn nil\n\t}\n\t*out = in\n\treturn nil\n}","line":{"from":121,"to":129}} {"id":100014838,"name":"Convert_v1_TypeMeta_To_v1_TypeMeta","signature":"func Convert_v1_TypeMeta_To_v1_TypeMeta(in, out *TypeMeta, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"// +k8s:conversion-fn=drop\nfunc Convert_v1_TypeMeta_To_v1_TypeMeta(in, out *TypeMeta, s conversion.Scope) error {\n\t// These values are explicitly not copied\n\t//out.APIVersion = in.APIVersion\n\t//out.Kind = in.Kind\n\treturn nil\n}","line":{"from":131,"to":137}} {"id":100014839,"name":"Convert_v1_ListMeta_To_v1_ListMeta","signature":"func Convert_v1_ListMeta_To_v1_ListMeta(in, out *ListMeta, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"// +k8s:conversion-fn=copy-only\nfunc Convert_v1_ListMeta_To_v1_ListMeta(in, out *ListMeta, s conversion.Scope) error {\n\t*out = *in\n\treturn nil\n}","line":{"from":139,"to":143}} {"id":100014840,"name":"Convert_v1_DeleteOptions_To_v1_DeleteOptions","signature":"func Convert_v1_DeleteOptions_To_v1_DeleteOptions(in, out *DeleteOptions, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"// +k8s:conversion-fn=copy-only\nfunc Convert_v1_DeleteOptions_To_v1_DeleteOptions(in, out *DeleteOptions, s conversion.Scope) error {\n\t*out = *in\n\treturn nil\n}","line":{"from":145,"to":149}} {"id":100014841,"name":"Convert_intstr_IntOrString_To_intstr_IntOrString","signature":"func Convert_intstr_IntOrString_To_intstr_IntOrString(in, out *intstr.IntOrString, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"// +k8s:conversion-fn=copy-only\nfunc Convert_intstr_IntOrString_To_intstr_IntOrString(in, out *intstr.IntOrString, s conversion.Scope) error {\n\t*out = *in\n\treturn nil\n}","line":{"from":151,"to":155}} {"id":100014842,"name":"Convert_Pointer_intstr_IntOrString_To_intstr_IntOrString","signature":"func Convert_Pointer_intstr_IntOrString_To_intstr_IntOrString(in **intstr.IntOrString, out *intstr.IntOrString, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"func Convert_Pointer_intstr_IntOrString_To_intstr_IntOrString(in **intstr.IntOrString, out *intstr.IntOrString, s conversion.Scope) error {\n\tif *in == nil {\n\t\t*out = intstr.IntOrString{} // zero value\n\t\treturn nil\n\t}\n\t*out = **in // copy\n\treturn nil\n}","line":{"from":157,"to":164}} {"id":100014843,"name":"Convert_intstr_IntOrString_To_Pointer_intstr_IntOrString","signature":"func Convert_intstr_IntOrString_To_Pointer_intstr_IntOrString(in *intstr.IntOrString, out **intstr.IntOrString, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"func Convert_intstr_IntOrString_To_Pointer_intstr_IntOrString(in *intstr.IntOrString, out **intstr.IntOrString, s conversion.Scope) error {\n\ttemp := *in // copy\n\t*out = \u0026temp\n\treturn nil\n}","line":{"from":166,"to":170}} {"id":100014844,"name":"Convert_v1_Time_To_v1_Time","signature":"func Convert_v1_Time_To_v1_Time(in *Time, out *Time, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"// +k8s:conversion-fn=copy-only\nfunc Convert_v1_Time_To_v1_Time(in *Time, out *Time, s conversion.Scope) error {\n\t// Cannot deep copy these, because time.Time has unexported fields.\n\t*out = *in\n\treturn nil\n}","line":{"from":172,"to":177}} {"id":100014845,"name":"Convert_v1_MicroTime_To_v1_MicroTime","signature":"func Convert_v1_MicroTime_To_v1_MicroTime(in *MicroTime, out *MicroTime, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"// +k8s:conversion-fn=copy-only\nfunc Convert_v1_MicroTime_To_v1_MicroTime(in *MicroTime, out *MicroTime, s conversion.Scope) error {\n\t// Cannot deep copy these, because time.Time has unexported fields.\n\t*out = *in\n\treturn nil\n}","line":{"from":179,"to":184}} {"id":100014846,"name":"Convert_Pointer_v1_Duration_To_v1_Duration","signature":"func Convert_Pointer_v1_Duration_To_v1_Duration(in **Duration, out *Duration, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"func Convert_Pointer_v1_Duration_To_v1_Duration(in **Duration, out *Duration, s conversion.Scope) error {\n\tif *in == nil {\n\t\t*out = Duration{} // zero duration\n\t\treturn nil\n\t}\n\t*out = **in // copy\n\treturn nil\n}","line":{"from":186,"to":193}} {"id":100014847,"name":"Convert_v1_Duration_To_Pointer_v1_Duration","signature":"func Convert_v1_Duration_To_Pointer_v1_Duration(in *Duration, out **Duration, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"func Convert_v1_Duration_To_Pointer_v1_Duration(in *Duration, out **Duration, s conversion.Scope) error {\n\ttemp := *in //copy\n\t*out = \u0026temp\n\treturn nil\n}","line":{"from":195,"to":199}} {"id":100014848,"name":"Convert_Slice_string_To_v1_Time","signature":"func Convert_Slice_string_To_v1_Time(in *[]string, out *Time, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"// Convert_Slice_string_To_v1_Time allows converting a URL query parameter value\nfunc Convert_Slice_string_To_v1_Time(in *[]string, out *Time, s conversion.Scope) error {\n\tstr := \"\"\n\tif len(*in) \u003e 0 {\n\t\tstr = (*in)[0]\n\t}\n\treturn out.UnmarshalQueryParameter(str)\n}","line":{"from":201,"to":208}} {"id":100014849,"name":"Convert_Slice_string_To_Pointer_v1_Time","signature":"func Convert_Slice_string_To_Pointer_v1_Time(in *[]string, out **Time, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"func Convert_Slice_string_To_Pointer_v1_Time(in *[]string, out **Time, s conversion.Scope) error {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tstr := \"\"\n\tif len(*in) \u003e 0 {\n\t\tstr = (*in)[0]\n\t}\n\ttemp := Time{}\n\tif err := temp.UnmarshalQueryParameter(str); err != nil {\n\t\treturn err\n\t}\n\t*out = \u0026temp\n\treturn nil\n}","line":{"from":210,"to":224}} {"id":100014850,"name":"Convert_string_To_labels_Selector","signature":"func Convert_string_To_labels_Selector(in *string, out *labels.Selector, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"func Convert_string_To_labels_Selector(in *string, out *labels.Selector, s conversion.Scope) error {\n\tselector, err := labels.Parse(*in)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*out = selector\n\treturn nil\n}","line":{"from":226,"to":233}} {"id":100014851,"name":"Convert_string_To_fields_Selector","signature":"func Convert_string_To_fields_Selector(in *string, out *fields.Selector, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"func Convert_string_To_fields_Selector(in *string, out *fields.Selector, s conversion.Scope) error {\n\tselector, err := fields.ParseSelector(*in)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*out = selector\n\treturn nil\n}","line":{"from":235,"to":242}} {"id":100014852,"name":"Convert_labels_Selector_To_string","signature":"func Convert_labels_Selector_To_string(in *labels.Selector, out *string, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"func Convert_labels_Selector_To_string(in *labels.Selector, out *string, s conversion.Scope) error {\n\tif *in == nil {\n\t\treturn nil\n\t}\n\t*out = (*in).String()\n\treturn nil\n}","line":{"from":244,"to":250}} {"id":100014853,"name":"Convert_fields_Selector_To_string","signature":"func Convert_fields_Selector_To_string(in *fields.Selector, out *string, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"func Convert_fields_Selector_To_string(in *fields.Selector, out *string, s conversion.Scope) error {\n\tif *in == nil {\n\t\treturn nil\n\t}\n\t*out = (*in).String()\n\treturn nil\n}","line":{"from":252,"to":258}} {"id":100014854,"name":"Convert_resource_Quantity_To_resource_Quantity","signature":"func Convert_resource_Quantity_To_resource_Quantity(in *resource.Quantity, out *resource.Quantity, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"// +k8s:conversion-fn=copy-only\nfunc Convert_resource_Quantity_To_resource_Quantity(in *resource.Quantity, out *resource.Quantity, s conversion.Scope) error {\n\t*out = *in\n\treturn nil\n}","line":{"from":260,"to":264}} {"id":100014855,"name":"Convert_Map_string_To_string_To_v1_LabelSelector","signature":"func Convert_Map_string_To_string_To_v1_LabelSelector(in *map[string]string, out *LabelSelector, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"func Convert_Map_string_To_string_To_v1_LabelSelector(in *map[string]string, out *LabelSelector, s conversion.Scope) error {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tfor labelKey, labelValue := range *in {\n\t\tAddLabelToSelector(out, labelKey, labelValue)\n\t}\n\treturn nil\n}","line":{"from":266,"to":274}} {"id":100014856,"name":"Convert_v1_LabelSelector_To_Map_string_To_string","signature":"func Convert_v1_LabelSelector_To_Map_string_To_string(in *LabelSelector, out *map[string]string, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"func Convert_v1_LabelSelector_To_Map_string_To_string(in *LabelSelector, out *map[string]string, s conversion.Scope) error {\n\tvar err error\n\t*out, err = LabelSelectorAsMap(in)\n\treturn err\n}","line":{"from":276,"to":280}} {"id":100014857,"name":"Convert_Slice_string_To_Slice_int32","signature":"func Convert_Slice_string_To_Slice_int32(in *[]string, out *[]int32, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"// Convert_Slice_string_To_Slice_int32 converts multiple query parameters or\n// a single query parameter with a comma delimited value to multiple int32.\n// This is used for port forwarding which needs the ports as int32.\nfunc Convert_Slice_string_To_Slice_int32(in *[]string, out *[]int32, s conversion.Scope) error {\n\tfor _, s := range *in {\n\t\tfor _, v := range strings.Split(s, \",\") {\n\t\t\tx, err := strconv.ParseUint(v, 10, 16)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"cannot convert to []int32: %v\", err)\n\t\t\t}\n\t\t\t*out = append(*out, int32(x))\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":282,"to":296}} {"id":100014858,"name":"Convert_Slice_string_To_Pointer_v1_DeletionPropagation","signature":"func Convert_Slice_string_To_Pointer_v1_DeletionPropagation(in *[]string, out **DeletionPropagation, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"// Convert_Slice_string_To_Pointer_v1_DeletionPropagation allows converting a URL query parameter propagationPolicy\nfunc Convert_Slice_string_To_Pointer_v1_DeletionPropagation(in *[]string, out **DeletionPropagation, s conversion.Scope) error {\n\tvar str string\n\tif len(*in) \u003e 0 {\n\t\tstr = (*in)[0]\n\t} else {\n\t\tstr = \"\"\n\t}\n\ttemp := DeletionPropagation(str)\n\t*out = \u0026temp\n\treturn nil\n}","line":{"from":298,"to":309}} {"id":100014859,"name":"Convert_Slice_string_To_v1_IncludeObjectPolicy","signature":"func Convert_Slice_string_To_v1_IncludeObjectPolicy(in *[]string, out *IncludeObjectPolicy, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"// Convert_Slice_string_To_v1_IncludeObjectPolicy allows converting a URL query parameter value\nfunc Convert_Slice_string_To_v1_IncludeObjectPolicy(in *[]string, out *IncludeObjectPolicy, s conversion.Scope) error {\n\tif len(*in) \u003e 0 {\n\t\t*out = IncludeObjectPolicy((*in)[0])\n\t}\n\treturn nil\n}","line":{"from":311,"to":317}} {"id":100014860,"name":"Convert_url_Values_To_v1_DeleteOptions","signature":"func Convert_url_Values_To_v1_DeleteOptions(in *url.Values, out *DeleteOptions, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"// Convert_url_Values_To_v1_DeleteOptions allows converting a URL to DeleteOptions.\nfunc Convert_url_Values_To_v1_DeleteOptions(in *url.Values, out *DeleteOptions, s conversion.Scope) error {\n\tif err := autoConvert_url_Values_To_v1_DeleteOptions(in, out, s); err != nil {\n\t\treturn err\n\t}\n\n\tuid := types.UID(\"\")\n\tif values, ok := (*in)[\"uid\"]; ok \u0026\u0026 len(values) \u003e 0 {\n\t\tuid = types.UID(values[0])\n\t}\n\n\tresourceVersion := \"\"\n\tif values, ok := (*in)[\"resourceVersion\"]; ok \u0026\u0026 len(values) \u003e 0 {\n\t\tresourceVersion = values[0]\n\t}\n\n\tif len(uid) \u003e 0 || len(resourceVersion) \u003e 0 {\n\t\tif out.Preconditions == nil {\n\t\t\tout.Preconditions = \u0026Preconditions{}\n\t\t}\n\t\tif len(uid) \u003e 0 {\n\t\t\tout.Preconditions.UID = \u0026uid\n\t\t}\n\t\tif len(resourceVersion) \u003e 0 {\n\t\t\tout.Preconditions.ResourceVersion = \u0026resourceVersion\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":319,"to":347}} {"id":100014861,"name":"Convert_Slice_string_To_v1_ResourceVersionMatch","signature":"func Convert_Slice_string_To_v1_ResourceVersionMatch(in *[]string, out *ResourceVersionMatch, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go","code":"// Convert_Slice_string_To_v1_ResourceVersionMatch allows converting a URL query parameter to ResourceVersionMatch\nfunc Convert_Slice_string_To_v1_ResourceVersionMatch(in *[]string, out *ResourceVersionMatch, s conversion.Scope) error {\n\tif len(*in) \u003e 0 {\n\t\t*out = ResourceVersionMatch((*in)[0])\n\t}\n\treturn nil\n}","line":{"from":349,"to":355}} {"id":100014862,"name":"DeepCopy","signature":"func (in *TableRow) DeepCopy() *TableRow","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/deepcopy.go","code":"func (in *TableRow) DeepCopy() *TableRow {\n\tif in == nil {\n\t\treturn nil\n\t}\n\n\tout := new(TableRow)\n\n\tif in.Cells != nil {\n\t\tout.Cells = make([]interface{}, len(in.Cells))\n\t\tfor i := range in.Cells {\n\t\t\tout.Cells[i] = runtime.DeepCopyJSONValue(in.Cells[i])\n\t\t}\n\t}\n\n\tif in.Conditions != nil {\n\t\tout.Conditions = make([]TableRowCondition, len(in.Conditions))\n\t\tfor i := range in.Conditions {\n\t\t\tin.Conditions[i].DeepCopyInto(\u0026out.Conditions[i])\n\t\t}\n\t}\n\n\tin.Object.DeepCopyInto(\u0026out.Object)\n\treturn out\n}","line":{"from":23,"to":46}} {"id":100014863,"name":"UnmarshalJSON","signature":"func (d *Duration) UnmarshalJSON(b []byte) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/duration.go","code":"// UnmarshalJSON implements the json.Unmarshaller interface.\nfunc (d *Duration) UnmarshalJSON(b []byte) error {\n\tvar str string\n\terr := json.Unmarshal(b, \u0026str)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpd, err := time.ParseDuration(str)\n\tif err != nil {\n\t\treturn err\n\t}\n\td.Duration = pd\n\treturn nil\n}","line":{"from":31,"to":45}} {"id":100014864,"name":"MarshalJSON","signature":"func (d Duration) MarshalJSON() ([]byte, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/duration.go","code":"// MarshalJSON implements the json.Marshaler interface.\nfunc (d Duration) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(d.Duration.String())\n}","line":{"from":47,"to":50}} {"id":100014865,"name":"ToUnstructured","signature":"func (d Duration) ToUnstructured() interface{}","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/duration.go","code":"// ToUnstructured implements the value.UnstructuredConverter interface.\nfunc (d Duration) ToUnstructured() interface{} {\n\treturn d.Duration.String()\n}","line":{"from":52,"to":55}} {"id":100014866,"name":"OpenAPISchemaType","signature":"func (_ Duration) OpenAPISchemaType() []string { return []string{\"string\"} }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/duration.go","code":"// OpenAPISchemaType is used by the kube-openapi generator when constructing\n// the OpenAPI spec of this type.\n//\n// See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators\nfunc (_ Duration) OpenAPISchemaType() []string { return []string{\"string\"} }","line":{"from":57,"to":61}} {"id":100014867,"name":"OpenAPISchemaFormat","signature":"func (_ Duration) OpenAPISchemaFormat() string { return \"\" }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/duration.go","code":"// OpenAPISchemaFormat is used by the kube-openapi generator when constructing\n// the OpenAPI spec of this type.\nfunc (_ Duration) OpenAPISchemaFormat() string { return \"\" }","line":{"from":63,"to":65}} {"id":100014868,"name":"String","signature":"func (gr *GroupResource) String() string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/group_version.go","code":"func (gr *GroupResource) String() string {\n\tif gr == nil {\n\t\treturn \"\u003cnil\u003e\"\n\t}\n\tif len(gr.Group) == 0 {\n\t\treturn gr.Resource\n\t}\n\treturn gr.Resource + \".\" + gr.Group\n}","line":{"from":36,"to":44}} {"id":100014869,"name":"String","signature":"func (gvr *GroupVersionResource) String() string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/group_version.go","code":"func (gvr *GroupVersionResource) String() string {\n\tif gvr == nil {\n\t\treturn \"\u003cnil\u003e\"\n\t}\n\treturn strings.Join([]string{gvr.Group, \"/\", gvr.Version, \", Resource=\", gvr.Resource}, \"\")\n}","line":{"from":56,"to":61}} {"id":100014870,"name":"String","signature":"func (gk *GroupKind) String() string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/group_version.go","code":"func (gk *GroupKind) String() string {\n\tif gk == nil {\n\t\treturn \"\u003cnil\u003e\"\n\t}\n\tif len(gk.Group) == 0 {\n\t\treturn gk.Kind\n\t}\n\treturn gk.Kind + \".\" + gk.Group\n}","line":{"from":72,"to":80}} {"id":100014871,"name":"String","signature":"func (gvk GroupVersionKind) String() string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/group_version.go","code":"func (gvk GroupVersionKind) String() string {\n\treturn gvk.Group + \"/\" + gvk.Version + \", Kind=\" + gvk.Kind\n}","line":{"from":92,"to":94}} {"id":100014872,"name":"Empty","signature":"func (gv GroupVersion) Empty() bool","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/group_version.go","code":"// Empty returns true if group and version are empty\nfunc (gv GroupVersion) Empty() bool {\n\treturn len(gv.Group) == 0 \u0026\u0026 len(gv.Version) == 0\n}","line":{"from":104,"to":107}} {"id":100014873,"name":"String","signature":"func (gv GroupVersion) String() string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/group_version.go","code":"// String puts \"group\" and \"version\" into a single \"group/version\" string. For the legacy v1\n// it returns \"v1\".\nfunc (gv GroupVersion) String() string {\n\t// special case the internal apiVersion for the legacy kube types\n\tif gv.Empty() {\n\t\treturn \"\"\n\t}\n\n\t// special case of \"v1\" for backward compatibility\n\tif len(gv.Group) == 0 \u0026\u0026 gv.Version == \"v1\" {\n\t\treturn gv.Version\n\t}\n\tif len(gv.Group) \u003e 0 {\n\t\treturn gv.Group + \"/\" + gv.Version\n\t}\n\treturn gv.Version\n}","line":{"from":109,"to":125}} {"id":100014874,"name":"MarshalJSON","signature":"func (gv GroupVersion) MarshalJSON() ([]byte, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/group_version.go","code":"// MarshalJSON implements the json.Marshaller interface.\nfunc (gv GroupVersion) MarshalJSON() ([]byte, error) {\n\ts := gv.String()\n\tif strings.Count(s, \"/\") \u003e 1 {\n\t\treturn []byte{}, fmt.Errorf(\"illegal GroupVersion %v: contains more than one /\", s)\n\t}\n\treturn json.Marshal(s)\n}","line":{"from":127,"to":134}} {"id":100014875,"name":"unmarshal","signature":"func (gv *GroupVersion) unmarshal(value []byte) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/group_version.go","code":"func (gv *GroupVersion) unmarshal(value []byte) error {\n\tvar s string\n\tif err := json.Unmarshal(value, \u0026s); err != nil {\n\t\treturn err\n\t}\n\tparsed, err := schema.ParseGroupVersion(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgv.Group, gv.Version = parsed.Group, parsed.Version\n\treturn nil\n}","line":{"from":136,"to":147}} {"id":100014876,"name":"UnmarshalJSON","signature":"func (gv *GroupVersion) UnmarshalJSON(value []byte) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/group_version.go","code":"// UnmarshalJSON implements the json.Unmarshaller interface.\nfunc (gv *GroupVersion) UnmarshalJSON(value []byte) error {\n\treturn gv.unmarshal(value)\n}","line":{"from":149,"to":152}} {"id":100014877,"name":"UnmarshalText","signature":"func (gv *GroupVersion) UnmarshalText(value []byte) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/group_version.go","code":"// UnmarshalTEXT implements the Ugorji's encoding.TextUnmarshaler interface.\nfunc (gv *GroupVersion) UnmarshalText(value []byte) error {\n\treturn gv.unmarshal(value)\n}","line":{"from":154,"to":157}} {"id":100014878,"name":"LabelSelectorAsSelector","signature":"func LabelSelectorAsSelector(ps *LabelSelector) (labels.Selector, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/helpers.go","code":"// LabelSelectorAsSelector converts the LabelSelector api type into a struct that implements\n// labels.Selector\n// Note: This function should be kept in sync with the selector methods in pkg/labels/selector.go\nfunc LabelSelectorAsSelector(ps *LabelSelector) (labels.Selector, error) {\n\tif ps == nil {\n\t\treturn labels.Nothing(), nil\n\t}\n\tif len(ps.MatchLabels)+len(ps.MatchExpressions) == 0 {\n\t\treturn labels.Everything(), nil\n\t}\n\trequirements := make([]labels.Requirement, 0, len(ps.MatchLabels)+len(ps.MatchExpressions))\n\tfor k, v := range ps.MatchLabels {\n\t\tr, err := labels.NewRequirement(k, selection.Equals, []string{v})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trequirements = append(requirements, *r)\n\t}\n\tfor _, expr := range ps.MatchExpressions {\n\t\tvar op selection.Operator\n\t\tswitch expr.Operator {\n\t\tcase LabelSelectorOpIn:\n\t\t\top = selection.In\n\t\tcase LabelSelectorOpNotIn:\n\t\t\top = selection.NotIn\n\t\tcase LabelSelectorOpExists:\n\t\t\top = selection.Exists\n\t\tcase LabelSelectorOpDoesNotExist:\n\t\t\top = selection.DoesNotExist\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"%q is not a valid label selector operator\", expr.Operator)\n\t\t}\n\t\tr, err := labels.NewRequirement(expr.Key, op, append([]string(nil), expr.Values...))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trequirements = append(requirements, *r)\n\t}\n\tselector := labels.NewSelector()\n\tselector = selector.Add(requirements...)\n\treturn selector, nil\n}","line":{"from":31,"to":72}} {"id":100014879,"name":"LabelSelectorAsMap","signature":"func LabelSelectorAsMap(ps *LabelSelector) (map[string]string, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/helpers.go","code":"// LabelSelectorAsMap converts the LabelSelector api type into a map of strings, ie. the\n// original structure of a label selector. Operators that cannot be converted into plain\n// labels (Exists, DoesNotExist, NotIn, and In with more than one value) will result in\n// an error.\nfunc LabelSelectorAsMap(ps *LabelSelector) (map[string]string, error) {\n\tif ps == nil {\n\t\treturn nil, nil\n\t}\n\tselector := map[string]string{}\n\tfor k, v := range ps.MatchLabels {\n\t\tselector[k] = v\n\t}\n\tfor _, expr := range ps.MatchExpressions {\n\t\tswitch expr.Operator {\n\t\tcase LabelSelectorOpIn:\n\t\t\tif len(expr.Values) != 1 {\n\t\t\t\treturn selector, fmt.Errorf(\"operator %q without a single value cannot be converted into the old label selector format\", expr.Operator)\n\t\t\t}\n\t\t\t// Should we do anything in case this will override a previous key-value pair?\n\t\t\tselector[expr.Key] = expr.Values[0]\n\t\tcase LabelSelectorOpNotIn, LabelSelectorOpExists, LabelSelectorOpDoesNotExist:\n\t\t\treturn selector, fmt.Errorf(\"operator %q cannot be converted into the old label selector format\", expr.Operator)\n\t\tdefault:\n\t\t\treturn selector, fmt.Errorf(\"%q is not a valid selector operator\", expr.Operator)\n\t\t}\n\t}\n\treturn selector, nil\n}","line":{"from":74,"to":101}} {"id":100014880,"name":"ParseToLabelSelector","signature":"func ParseToLabelSelector(selector string) (*LabelSelector, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/helpers.go","code":"// ParseToLabelSelector parses a string representing a selector into a LabelSelector object.\n// Note: This function should be kept in sync with the parser in pkg/labels/selector.go\nfunc ParseToLabelSelector(selector string) (*LabelSelector, error) {\n\treqs, err := labels.ParseToRequirements(selector)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"couldn't parse the selector string \\\"%s\\\": %v\", selector, err)\n\t}\n\n\tlabelSelector := \u0026LabelSelector{\n\t\tMatchLabels: map[string]string{},\n\t\tMatchExpressions: []LabelSelectorRequirement{},\n\t}\n\tfor _, req := range reqs {\n\t\tvar op LabelSelectorOperator\n\t\tswitch req.Operator() {\n\t\tcase selection.Equals, selection.DoubleEquals:\n\t\t\tvals := req.Values()\n\t\t\tif vals.Len() != 1 {\n\t\t\t\treturn nil, fmt.Errorf(\"equals operator must have exactly one value\")\n\t\t\t}\n\t\t\tval, ok := vals.PopAny()\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"equals operator has exactly one value but it cannot be retrieved\")\n\t\t\t}\n\t\t\tlabelSelector.MatchLabels[req.Key()] = val\n\t\t\tcontinue\n\t\tcase selection.In:\n\t\t\top = LabelSelectorOpIn\n\t\tcase selection.NotIn:\n\t\t\top = LabelSelectorOpNotIn\n\t\tcase selection.Exists:\n\t\t\top = LabelSelectorOpExists\n\t\tcase selection.DoesNotExist:\n\t\t\top = LabelSelectorOpDoesNotExist\n\t\tcase selection.GreaterThan, selection.LessThan:\n\t\t\t// Adding a separate case for these operators to indicate that this is deliberate\n\t\t\treturn nil, fmt.Errorf(\"%q isn't supported in label selectors\", req.Operator())\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"%q is not a valid label selector operator\", req.Operator())\n\t\t}\n\t\tlabelSelector.MatchExpressions = append(labelSelector.MatchExpressions, LabelSelectorRequirement{\n\t\t\tKey: req.Key(),\n\t\t\tOperator: op,\n\t\t\tValues: req.Values().List(),\n\t\t})\n\t}\n\treturn labelSelector, nil\n}","line":{"from":103,"to":150}} {"id":100014881,"name":"SetAsLabelSelector","signature":"func SetAsLabelSelector(ls labels.Set) *LabelSelector","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/helpers.go","code":"// SetAsLabelSelector converts the labels.Set object into a LabelSelector api object.\nfunc SetAsLabelSelector(ls labels.Set) *LabelSelector {\n\tif ls == nil {\n\t\treturn nil\n\t}\n\n\tselector := \u0026LabelSelector{\n\t\tMatchLabels: make(map[string]string, len(ls)),\n\t}\n\tfor label, value := range ls {\n\t\tselector.MatchLabels[label] = value\n\t}\n\n\treturn selector\n}","line":{"from":152,"to":166}} {"id":100014882,"name":"FormatLabelSelector","signature":"func FormatLabelSelector(labelSelector *LabelSelector) string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/helpers.go","code":"// FormatLabelSelector convert labelSelector into plain string\nfunc FormatLabelSelector(labelSelector *LabelSelector) string {\n\tselector, err := LabelSelectorAsSelector(labelSelector)\n\tif err != nil {\n\t\treturn \"\u003cerror\u003e\"\n\t}\n\n\tl := selector.String()\n\tif len(l) == 0 {\n\t\tl = \"\u003cnone\u003e\"\n\t}\n\treturn l\n}","line":{"from":168,"to":180}} {"id":100014883,"name":"ExtractGroupVersions","signature":"func ExtractGroupVersions(l *APIGroupList) []string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/helpers.go","code":"func ExtractGroupVersions(l *APIGroupList) []string {\n\tvar groupVersions []string\n\tfor _, g := range l.Groups {\n\t\tfor _, gv := range g.Versions {\n\t\t\tgroupVersions = append(groupVersions, gv.GroupVersion)\n\t\t}\n\t}\n\treturn groupVersions\n}","line":{"from":182,"to":190}} {"id":100014884,"name":"HasAnnotation","signature":"func HasAnnotation(obj ObjectMeta, ann string) bool","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/helpers.go","code":"// HasAnnotation returns a bool if passed in annotation exists\nfunc HasAnnotation(obj ObjectMeta, ann string) bool {\n\t_, found := obj.Annotations[ann]\n\treturn found\n}","line":{"from":192,"to":196}} {"id":100014885,"name":"SetMetaDataAnnotation","signature":"func SetMetaDataAnnotation(obj *ObjectMeta, ann string, value string)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/helpers.go","code":"// SetMetaDataAnnotation sets the annotation and value\nfunc SetMetaDataAnnotation(obj *ObjectMeta, ann string, value string) {\n\tif obj.Annotations == nil {\n\t\tobj.Annotations = make(map[string]string)\n\t}\n\tobj.Annotations[ann] = value\n}","line":{"from":198,"to":204}} {"id":100014886,"name":"HasLabel","signature":"func HasLabel(obj ObjectMeta, label string) bool","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/helpers.go","code":"// HasLabel returns a bool if passed in label exists\nfunc HasLabel(obj ObjectMeta, label string) bool {\n\t_, found := obj.Labels[label]\n\treturn found\n}","line":{"from":206,"to":210}} {"id":100014887,"name":"SetMetaDataLabel","signature":"func SetMetaDataLabel(obj *ObjectMeta, label string, value string)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/helpers.go","code":"// SetMetaDataLabel sets the label and value\nfunc SetMetaDataLabel(obj *ObjectMeta, label string, value string) {\n\tif obj.Labels == nil {\n\t\tobj.Labels = make(map[string]string)\n\t}\n\tobj.Labels[label] = value\n}","line":{"from":212,"to":218}} {"id":100014888,"name":"SingleObject","signature":"func SingleObject(meta ObjectMeta) ListOptions","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/helpers.go","code":"// SingleObject returns a ListOptions for watching a single object.\nfunc SingleObject(meta ObjectMeta) ListOptions {\n\treturn ListOptions{\n\t\tFieldSelector: fields.OneTermEqualSelector(\"metadata.name\", meta.Name).String(),\n\t\tResourceVersion: meta.ResourceVersion,\n\t}\n}","line":{"from":220,"to":226}} {"id":100014889,"name":"NewDeleteOptions","signature":"func NewDeleteOptions(grace int64) *DeleteOptions","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/helpers.go","code":"// NewDeleteOptions returns a DeleteOptions indicating the resource should\n// be deleted within the specified grace period. Use zero to indicate\n// immediate deletion. If you would prefer to use the default grace period,\n// use \u0026metav1.DeleteOptions{} directly.\nfunc NewDeleteOptions(grace int64) *DeleteOptions {\n\treturn \u0026DeleteOptions{GracePeriodSeconds: \u0026grace}\n}","line":{"from":228,"to":234}} {"id":100014890,"name":"NewPreconditionDeleteOptions","signature":"func NewPreconditionDeleteOptions(uid string) *DeleteOptions","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/helpers.go","code":"// NewPreconditionDeleteOptions returns a DeleteOptions with a UID precondition set.\nfunc NewPreconditionDeleteOptions(uid string) *DeleteOptions {\n\tu := types.UID(uid)\n\tp := Preconditions{UID: \u0026u}\n\treturn \u0026DeleteOptions{Preconditions: \u0026p}\n}","line":{"from":236,"to":241}} {"id":100014891,"name":"NewUIDPreconditions","signature":"func NewUIDPreconditions(uid string) *Preconditions","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/helpers.go","code":"// NewUIDPreconditions returns a Preconditions with UID set.\nfunc NewUIDPreconditions(uid string) *Preconditions {\n\tu := types.UID(uid)\n\treturn \u0026Preconditions{UID: \u0026u}\n}","line":{"from":243,"to":247}} {"id":100014892,"name":"NewRVDeletionPrecondition","signature":"func NewRVDeletionPrecondition(rv string) *DeleteOptions","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/helpers.go","code":"// NewRVDeletionPrecondition returns a DeleteOptions with a ResourceVersion precondition set.\nfunc NewRVDeletionPrecondition(rv string) *DeleteOptions {\n\tp := Preconditions{ResourceVersion: \u0026rv}\n\treturn \u0026DeleteOptions{Preconditions: \u0026p}\n}","line":{"from":249,"to":253}} {"id":100014893,"name":"HasObjectMetaSystemFieldValues","signature":"func HasObjectMetaSystemFieldValues(meta Object) bool","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/helpers.go","code":"// HasObjectMetaSystemFieldValues returns true if fields that are managed by the system on ObjectMeta have values.\nfunc HasObjectMetaSystemFieldValues(meta Object) bool {\n\treturn !meta.GetCreationTimestamp().Time.IsZero() ||\n\t\tlen(meta.GetUID()) != 0\n}","line":{"from":255,"to":259}} {"id":100014894,"name":"ResetObjectMetaForStatus","signature":"func ResetObjectMetaForStatus(meta, existingMeta Object)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/helpers.go","code":"// ResetObjectMetaForStatus forces the meta fields for a status update to match the meta fields\n// for a pre-existing object. This is opt-in for new objects with Status subresource.\nfunc ResetObjectMetaForStatus(meta, existingMeta Object) {\n\tmeta.SetDeletionTimestamp(existingMeta.GetDeletionTimestamp())\n\tmeta.SetGeneration(existingMeta.GetGeneration())\n\tmeta.SetSelfLink(existingMeta.GetSelfLink())\n\tmeta.SetLabels(existingMeta.GetLabels())\n\tmeta.SetAnnotations(existingMeta.GetAnnotations())\n\tmeta.SetFinalizers(existingMeta.GetFinalizers())\n\tmeta.SetOwnerReferences(existingMeta.GetOwnerReferences())\n\t// managedFields must be preserved since it's been modified to\n\t// track changed fields in the status update.\n\t//meta.SetManagedFields(existingMeta.GetManagedFields())\n}","line":{"from":261,"to":274}} {"id":100014895,"name":"MarshalJSON","signature":"func (f FieldsV1) MarshalJSON() ([]byte, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/helpers.go","code":"// MarshalJSON implements json.Marshaler\n// MarshalJSON may get called on pointers or values, so implement MarshalJSON on value.\n// http://stackoverflow.com/questions/21390979/custom-marshaljson-never-gets-called-in-go\nfunc (f FieldsV1) MarshalJSON() ([]byte, error) {\n\tif f.Raw == nil {\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn f.Raw, nil\n}","line":{"from":276,"to":284}} {"id":100014896,"name":"UnmarshalJSON","signature":"func (f *FieldsV1) UnmarshalJSON(b []byte) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/helpers.go","code":"// UnmarshalJSON implements json.Unmarshaler\nfunc (f *FieldsV1) UnmarshalJSON(b []byte) error {\n\tif f == nil {\n\t\treturn errors.New(\"metav1.Fields: UnmarshalJSON on nil pointer\")\n\t}\n\tif !bytes.Equal(b, []byte(\"null\")) {\n\t\tf.Raw = append(f.Raw[0:0], b...)\n\t}\n\treturn nil\n}","line":{"from":286,"to":295}} {"id":100014897,"name":"CloneSelectorAndAddLabel","signature":"func CloneSelectorAndAddLabel(selector *LabelSelector, labelKey, labelValue string) *LabelSelector","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/labels.go","code":"// Clones the given selector and returns a new selector with the given key and value added.\n// Returns the given selector, if labelKey is empty.\nfunc CloneSelectorAndAddLabel(selector *LabelSelector, labelKey, labelValue string) *LabelSelector {\n\tif labelKey == \"\" {\n\t\t// Don't need to add a label.\n\t\treturn selector\n\t}\n\n\t// Clone.\n\tnewSelector := selector.DeepCopy()\n\n\tif newSelector.MatchLabels == nil {\n\t\tnewSelector.MatchLabels = make(map[string]string)\n\t}\n\n\tnewSelector.MatchLabels[labelKey] = labelValue\n\n\treturn newSelector\n}","line":{"from":19,"to":37}} {"id":100014898,"name":"AddLabelToSelector","signature":"func AddLabelToSelector(selector *LabelSelector, labelKey, labelValue string) *LabelSelector","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/labels.go","code":"// AddLabelToSelector returns a selector with the given key and value added to the given selector's MatchLabels.\nfunc AddLabelToSelector(selector *LabelSelector, labelKey, labelValue string) *LabelSelector {\n\tif labelKey == \"\" {\n\t\t// Don't need to add a label.\n\t\treturn selector\n\t}\n\tif selector.MatchLabels == nil {\n\t\tselector.MatchLabels = make(map[string]string)\n\t}\n\tselector.MatchLabels[labelKey] = labelValue\n\treturn selector\n}","line":{"from":39,"to":50}} {"id":100014899,"name":"SelectorHasLabel","signature":"func SelectorHasLabel(selector *LabelSelector, labelKey string) bool","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/labels.go","code":"// SelectorHasLabel checks if the given selector contains the given label key in its MatchLabels\nfunc SelectorHasLabel(selector *LabelSelector, labelKey string) bool {\n\treturn len(selector.MatchLabels[labelKey]) \u003e 0\n}","line":{"from":52,"to":55}} {"id":100014900,"name":"GetResourceVersion","signature":"func (meta *ListMeta) GetResourceVersion() string { return meta.ResourceVersion }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ListMeta) GetResourceVersion() string { return meta.ResourceVersion }","line":{"from":108,"to":108}} {"id":100014901,"name":"SetResourceVersion","signature":"func (meta *ListMeta) SetResourceVersion(version string) { meta.ResourceVersion = version }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ListMeta) SetResourceVersion(version string) { meta.ResourceVersion = version }","line":{"from":109,"to":109}} {"id":100014902,"name":"GetSelfLink","signature":"func (meta *ListMeta) GetSelfLink() string { return meta.SelfLink }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ListMeta) GetSelfLink() string { return meta.SelfLink }","line":{"from":110,"to":110}} {"id":100014903,"name":"SetSelfLink","signature":"func (meta *ListMeta) SetSelfLink(selfLink string) { meta.SelfLink = selfLink }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ListMeta) SetSelfLink(selfLink string) { meta.SelfLink = selfLink }","line":{"from":111,"to":111}} {"id":100014904,"name":"GetContinue","signature":"func (meta *ListMeta) GetContinue() string { return meta.Continue }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ListMeta) GetContinue() string { return meta.Continue }","line":{"from":112,"to":112}} {"id":100014905,"name":"SetContinue","signature":"func (meta *ListMeta) SetContinue(c string) { meta.Continue = c }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ListMeta) SetContinue(c string) { meta.Continue = c }","line":{"from":113,"to":113}} {"id":100014906,"name":"GetRemainingItemCount","signature":"func (meta *ListMeta) GetRemainingItemCount() *int64 { return meta.RemainingItemCount }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ListMeta) GetRemainingItemCount() *int64 { return meta.RemainingItemCount }","line":{"from":114,"to":114}} {"id":100014907,"name":"SetRemainingItemCount","signature":"func (meta *ListMeta) SetRemainingItemCount(c *int64) { meta.RemainingItemCount = c }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ListMeta) SetRemainingItemCount(c *int64) { meta.RemainingItemCount = c }","line":{"from":115,"to":115}} {"id":100014908,"name":"GetObjectKind","signature":"func (obj *TypeMeta) GetObjectKind() schema.ObjectKind { return obj }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (obj *TypeMeta) GetObjectKind() schema.ObjectKind { return obj }","line":{"from":117,"to":117}} {"id":100014909,"name":"SetGroupVersionKind","signature":"func (obj *TypeMeta) SetGroupVersionKind(gvk schema.GroupVersionKind)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"// SetGroupVersionKind satisfies the ObjectKind interface for all objects that embed TypeMeta\nfunc (obj *TypeMeta) SetGroupVersionKind(gvk schema.GroupVersionKind) {\n\tobj.APIVersion, obj.Kind = gvk.ToAPIVersionAndKind()\n}","line":{"from":119,"to":122}} {"id":100014910,"name":"GroupVersionKind","signature":"func (obj *TypeMeta) GroupVersionKind() schema.GroupVersionKind","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"// GroupVersionKind satisfies the ObjectKind interface for all objects that embed TypeMeta\nfunc (obj *TypeMeta) GroupVersionKind() schema.GroupVersionKind {\n\treturn schema.FromAPIVersionAndKind(obj.APIVersion, obj.Kind)\n}","line":{"from":124,"to":127}} {"id":100014911,"name":"GetListMeta","signature":"func (obj *ListMeta) GetListMeta() ListInterface { return obj }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (obj *ListMeta) GetListMeta() ListInterface { return obj }","line":{"from":129,"to":129}} {"id":100014912,"name":"GetObjectMeta","signature":"func (obj *ObjectMeta) GetObjectMeta() Object { return obj }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (obj *ObjectMeta) GetObjectMeta() Object { return obj }","line":{"from":131,"to":131}} {"id":100014913,"name":"GetNamespace","signature":"func (meta *ObjectMeta) GetNamespace() string { return meta.Namespace }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"// Namespace implements metav1.Object for any object with an ObjectMeta typed field. Allows\n// fast, direct access to metadata fields for API objects.\nfunc (meta *ObjectMeta) GetNamespace() string { return meta.Namespace }","line":{"from":133,"to":135}} {"id":100014914,"name":"SetNamespace","signature":"func (meta *ObjectMeta) SetNamespace(namespace string) { meta.Namespace = namespace }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) SetNamespace(namespace string) { meta.Namespace = namespace }","line":{"from":136,"to":136}} {"id":100014915,"name":"GetName","signature":"func (meta *ObjectMeta) GetName() string { return meta.Name }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) GetName() string { return meta.Name }","line":{"from":137,"to":137}} {"id":100014916,"name":"SetName","signature":"func (meta *ObjectMeta) SetName(name string) { meta.Name = name }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) SetName(name string) { meta.Name = name }","line":{"from":138,"to":138}} {"id":100014917,"name":"GetGenerateName","signature":"func (meta *ObjectMeta) GetGenerateName() string { return meta.GenerateName }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) GetGenerateName() string { return meta.GenerateName }","line":{"from":139,"to":139}} {"id":100014918,"name":"SetGenerateName","signature":"func (meta *ObjectMeta) SetGenerateName(generateName string) { meta.GenerateName = generateName }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) SetGenerateName(generateName string) { meta.GenerateName = generateName }","line":{"from":140,"to":140}} {"id":100014919,"name":"GetUID","signature":"func (meta *ObjectMeta) GetUID() types.UID { return meta.UID }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) GetUID() types.UID { return meta.UID }","line":{"from":141,"to":141}} {"id":100014920,"name":"SetUID","signature":"func (meta *ObjectMeta) SetUID(uid types.UID) { meta.UID = uid }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) SetUID(uid types.UID) { meta.UID = uid }","line":{"from":142,"to":142}} {"id":100014921,"name":"GetResourceVersion","signature":"func (meta *ObjectMeta) GetResourceVersion() string { return meta.ResourceVersion }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) GetResourceVersion() string { return meta.ResourceVersion }","line":{"from":143,"to":143}} {"id":100014922,"name":"SetResourceVersion","signature":"func (meta *ObjectMeta) SetResourceVersion(version string) { meta.ResourceVersion = version }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) SetResourceVersion(version string) { meta.ResourceVersion = version }","line":{"from":144,"to":144}} {"id":100014923,"name":"GetGeneration","signature":"func (meta *ObjectMeta) GetGeneration() int64 { return meta.Generation }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) GetGeneration() int64 { return meta.Generation }","line":{"from":145,"to":145}} {"id":100014924,"name":"SetGeneration","signature":"func (meta *ObjectMeta) SetGeneration(generation int64) { meta.Generation = generation }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) SetGeneration(generation int64) { meta.Generation = generation }","line":{"from":146,"to":146}} {"id":100014925,"name":"GetSelfLink","signature":"func (meta *ObjectMeta) GetSelfLink() string { return meta.SelfLink }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) GetSelfLink() string { return meta.SelfLink }","line":{"from":147,"to":147}} {"id":100014926,"name":"SetSelfLink","signature":"func (meta *ObjectMeta) SetSelfLink(selfLink string) { meta.SelfLink = selfLink }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) SetSelfLink(selfLink string) { meta.SelfLink = selfLink }","line":{"from":148,"to":148}} {"id":100014927,"name":"GetCreationTimestamp","signature":"func (meta *ObjectMeta) GetCreationTimestamp() Time { return meta.CreationTimestamp }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) GetCreationTimestamp() Time { return meta.CreationTimestamp }","line":{"from":149,"to":149}} {"id":100014928,"name":"SetCreationTimestamp","signature":"func (meta *ObjectMeta) SetCreationTimestamp(creationTimestamp Time)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) SetCreationTimestamp(creationTimestamp Time) {\n\tmeta.CreationTimestamp = creationTimestamp\n}","line":{"from":150,"to":152}} {"id":100014929,"name":"GetDeletionTimestamp","signature":"func (meta *ObjectMeta) GetDeletionTimestamp() *Time { return meta.DeletionTimestamp }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) GetDeletionTimestamp() *Time { return meta.DeletionTimestamp }","line":{"from":153,"to":153}} {"id":100014930,"name":"SetDeletionTimestamp","signature":"func (meta *ObjectMeta) SetDeletionTimestamp(deletionTimestamp *Time)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) SetDeletionTimestamp(deletionTimestamp *Time) {\n\tmeta.DeletionTimestamp = deletionTimestamp\n}","line":{"from":154,"to":156}} {"id":100014931,"name":"GetDeletionGracePeriodSeconds","signature":"func (meta *ObjectMeta) GetDeletionGracePeriodSeconds() *int64","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) GetDeletionGracePeriodSeconds() *int64 {\n\treturn meta.DeletionGracePeriodSeconds\n}","line":{"from":157,"to":159}} {"id":100014932,"name":"SetDeletionGracePeriodSeconds","signature":"func (meta *ObjectMeta) SetDeletionGracePeriodSeconds(deletionGracePeriodSeconds *int64)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) SetDeletionGracePeriodSeconds(deletionGracePeriodSeconds *int64) {\n\tmeta.DeletionGracePeriodSeconds = deletionGracePeriodSeconds\n}","line":{"from":160,"to":162}} {"id":100014933,"name":"GetLabels","signature":"func (meta *ObjectMeta) GetLabels() map[string]string { return meta.Labels }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) GetLabels() map[string]string { return meta.Labels }","line":{"from":163,"to":163}} {"id":100014934,"name":"SetLabels","signature":"func (meta *ObjectMeta) SetLabels(labels map[string]string) { meta.Labels = labels }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) SetLabels(labels map[string]string) { meta.Labels = labels }","line":{"from":164,"to":164}} {"id":100014935,"name":"GetAnnotations","signature":"func (meta *ObjectMeta) GetAnnotations() map[string]string { return meta.Annotations }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) GetAnnotations() map[string]string { return meta.Annotations }","line":{"from":165,"to":165}} {"id":100014936,"name":"SetAnnotations","signature":"func (meta *ObjectMeta) SetAnnotations(annotations map[string]string) { meta.Annotations = annotations }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) SetAnnotations(annotations map[string]string) { meta.Annotations = annotations }","line":{"from":166,"to":166}} {"id":100014937,"name":"GetFinalizers","signature":"func (meta *ObjectMeta) GetFinalizers() []string { return meta.Finalizers }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) GetFinalizers() []string { return meta.Finalizers }","line":{"from":167,"to":167}} {"id":100014938,"name":"SetFinalizers","signature":"func (meta *ObjectMeta) SetFinalizers(finalizers []string) { meta.Finalizers = finalizers }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) SetFinalizers(finalizers []string) { meta.Finalizers = finalizers }","line":{"from":168,"to":168}} {"id":100014939,"name":"GetOwnerReferences","signature":"func (meta *ObjectMeta) GetOwnerReferences() []OwnerReference { return meta.OwnerReferences }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) GetOwnerReferences() []OwnerReference { return meta.OwnerReferences }","line":{"from":169,"to":169}} {"id":100014940,"name":"SetOwnerReferences","signature":"func (meta *ObjectMeta) SetOwnerReferences(references []OwnerReference)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) SetOwnerReferences(references []OwnerReference) {\n\tmeta.OwnerReferences = references\n}","line":{"from":170,"to":172}} {"id":100014941,"name":"GetManagedFields","signature":"func (meta *ObjectMeta) GetManagedFields() []ManagedFieldsEntry { return meta.ManagedFields }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) GetManagedFields() []ManagedFieldsEntry { return meta.ManagedFields }","line":{"from":173,"to":173}} {"id":100014942,"name":"SetManagedFields","signature":"func (meta *ObjectMeta) SetManagedFields(managedFields []ManagedFieldsEntry)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go","code":"func (meta *ObjectMeta) SetManagedFields(managedFields []ManagedFieldsEntry) {\n\tmeta.ManagedFields = managedFields\n}","line":{"from":174,"to":176}} {"id":100014943,"name":"DeepCopyInto","signature":"func (t *MicroTime) DeepCopyInto(out *MicroTime)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time.go","code":"// DeepCopy returns a deep-copy of the MicroTime value. The underlying time.Time\n// type is effectively immutable in the time API, so it is safe to\n// copy-by-assign, despite the presence of (unexported) Pointer fields.\nfunc (t *MicroTime) DeepCopyInto(out *MicroTime) {\n\t*out = *t\n}","line":{"from":35,"to":40}} {"id":100014944,"name":"NewMicroTime","signature":"func NewMicroTime(time time.Time) MicroTime","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time.go","code":"// NewMicroTime returns a wrapped instance of the provided time\nfunc NewMicroTime(time time.Time) MicroTime {\n\treturn MicroTime{time}\n}","line":{"from":42,"to":45}} {"id":100014945,"name":"DateMicro","signature":"func DateMicro(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) MicroTime","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time.go","code":"// DateMicro returns the MicroTime corresponding to the supplied parameters\n// by wrapping time.Date.\nfunc DateMicro(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) MicroTime {\n\treturn MicroTime{time.Date(year, month, day, hour, min, sec, nsec, loc)}\n}","line":{"from":47,"to":51}} {"id":100014946,"name":"NowMicro","signature":"func NowMicro() MicroTime","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time.go","code":"// NowMicro returns the current local time.\nfunc NowMicro() MicroTime {\n\treturn MicroTime{time.Now()}\n}","line":{"from":53,"to":56}} {"id":100014947,"name":"IsZero","signature":"func (t *MicroTime) IsZero() bool","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time.go","code":"// IsZero returns true if the value is nil or time is zero.\nfunc (t *MicroTime) IsZero() bool {\n\tif t == nil {\n\t\treturn true\n\t}\n\treturn t.Time.IsZero()\n}","line":{"from":58,"to":64}} {"id":100014948,"name":"Before","signature":"func (t *MicroTime) Before(u *MicroTime) bool","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time.go","code":"// Before reports whether the time instant t is before u.\nfunc (t *MicroTime) Before(u *MicroTime) bool {\n\tif t != nil \u0026\u0026 u != nil {\n\t\treturn t.Time.Before(u.Time)\n\t}\n\treturn false\n}","line":{"from":66,"to":72}} {"id":100014949,"name":"Equal","signature":"func (t *MicroTime) Equal(u *MicroTime) bool","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time.go","code":"// Equal reports whether the time instant t is equal to u.\nfunc (t *MicroTime) Equal(u *MicroTime) bool {\n\tif t == nil \u0026\u0026 u == nil {\n\t\treturn true\n\t}\n\tif t != nil \u0026\u0026 u != nil {\n\t\treturn t.Time.Equal(u.Time)\n\t}\n\treturn false\n}","line":{"from":74,"to":83}} {"id":100014950,"name":"BeforeTime","signature":"func (t *MicroTime) BeforeTime(u *Time) bool","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time.go","code":"// BeforeTime reports whether the time instant t is before second-lever precision u.\nfunc (t *MicroTime) BeforeTime(u *Time) bool {\n\tif t != nil \u0026\u0026 u != nil {\n\t\treturn t.Time.Before(u.Time)\n\t}\n\treturn false\n}","line":{"from":85,"to":91}} {"id":100014951,"name":"EqualTime","signature":"func (t *MicroTime) EqualTime(u *Time) bool","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time.go","code":"// EqualTime reports whether the time instant t is equal to second-lever precision u.\nfunc (t *MicroTime) EqualTime(u *Time) bool {\n\tif t == nil \u0026\u0026 u == nil {\n\t\treturn true\n\t}\n\tif t != nil \u0026\u0026 u != nil {\n\t\treturn t.Time.Equal(u.Time)\n\t}\n\treturn false\n}","line":{"from":93,"to":102}} {"id":100014952,"name":"UnixMicro","signature":"func UnixMicro(sec int64, nsec int64) MicroTime","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time.go","code":"// UnixMicro returns the local time corresponding to the given Unix time\n// by wrapping time.Unix.\nfunc UnixMicro(sec int64, nsec int64) MicroTime {\n\treturn MicroTime{time.Unix(sec, nsec)}\n}","line":{"from":104,"to":108}} {"id":100014953,"name":"UnmarshalJSON","signature":"func (t *MicroTime) UnmarshalJSON(b []byte) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time.go","code":"// UnmarshalJSON implements the json.Unmarshaller interface.\nfunc (t *MicroTime) UnmarshalJSON(b []byte) error {\n\tif len(b) == 4 \u0026\u0026 string(b) == \"null\" {\n\t\tt.Time = time.Time{}\n\t\treturn nil\n\t}\n\n\tvar str string\n\terr := json.Unmarshal(b, \u0026str)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpt, err := time.Parse(RFC3339Micro, str)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tt.Time = pt.Local()\n\treturn nil\n}","line":{"from":110,"to":130}} {"id":100014954,"name":"UnmarshalQueryParameter","signature":"func (t *MicroTime) UnmarshalQueryParameter(str string) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time.go","code":"// UnmarshalQueryParameter converts from a URL query parameter value to an object\nfunc (t *MicroTime) UnmarshalQueryParameter(str string) error {\n\tif len(str) == 0 {\n\t\tt.Time = time.Time{}\n\t\treturn nil\n\t}\n\t// Tolerate requests from older clients that used JSON serialization to build query params\n\tif len(str) == 4 \u0026\u0026 str == \"null\" {\n\t\tt.Time = time.Time{}\n\t\treturn nil\n\t}\n\n\tpt, err := time.Parse(RFC3339Micro, str)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tt.Time = pt.Local()\n\treturn nil\n}","line":{"from":132,"to":151}} {"id":100014955,"name":"MarshalJSON","signature":"func (t MicroTime) MarshalJSON() ([]byte, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time.go","code":"// MarshalJSON implements the json.Marshaler interface.\nfunc (t MicroTime) MarshalJSON() ([]byte, error) {\n\tif t.IsZero() {\n\t\t// Encode unset/nil objects as JSON's \"null\".\n\t\treturn []byte(\"null\"), nil\n\t}\n\n\treturn json.Marshal(t.UTC().Format(RFC3339Micro))\n}","line":{"from":153,"to":161}} {"id":100014956,"name":"OpenAPISchemaType","signature":"func (_ MicroTime) OpenAPISchemaType() []string { return []string{\"string\"} }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time.go","code":"// OpenAPISchemaType is used by the kube-openapi generator when constructing\n// the OpenAPI spec of this type.\n//\n// See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators\nfunc (_ MicroTime) OpenAPISchemaType() []string { return []string{\"string\"} }","line":{"from":163,"to":167}} {"id":100014957,"name":"OpenAPISchemaFormat","signature":"func (_ MicroTime) OpenAPISchemaFormat() string { return \"date-time\" }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time.go","code":"// OpenAPISchemaFormat is used by the kube-openapi generator when constructing\n// the OpenAPI spec of this type.\nfunc (_ MicroTime) OpenAPISchemaFormat() string { return \"date-time\" }","line":{"from":169,"to":171}} {"id":100014958,"name":"MarshalQueryParameter","signature":"func (t MicroTime) MarshalQueryParameter() (string, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time.go","code":"// MarshalQueryParameter converts to a URL query parameter value\nfunc (t MicroTime) MarshalQueryParameter() (string, error) {\n\tif t.IsZero() {\n\t\t// Encode unset/nil objects as an empty string\n\t\treturn \"\", nil\n\t}\n\n\treturn t.UTC().Format(RFC3339Micro), nil\n}","line":{"from":173,"to":181}} {"id":100014959,"name":"Fuzz","signature":"func (t *MicroTime) Fuzz(c fuzz.Continue)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time_fuzz.go","code":"// Fuzz satisfies fuzz.Interface.\nfunc (t *MicroTime) Fuzz(c fuzz.Continue) {\n\tif t == nil {\n\t\treturn\n\t}\n\t// Allow for about 1000 years of randomness. Accurate to a tenth of\n\t// micro second. Leave off nanoseconds because JSON doesn't\n\t// represent them so they can't round-trip properly.\n\tt.Time = time.Unix(c.Rand.Int63n(1000*365*24*60*60), 1000*c.Rand.Int63n(1000000))\n}","line":{"from":28,"to":37}} {"id":100014960,"name":"ProtoMicroTime","signature":"func (m *MicroTime) ProtoMicroTime() *Timestamp","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time_proto.go","code":"// Timestamp returns the Time as a new Timestamp value.\nfunc (m *MicroTime) ProtoMicroTime() *Timestamp {\n\tif m == nil {\n\t\treturn \u0026Timestamp{}\n\t}\n\n\t// truncate precision to microseconds to match JSON marshaling/unmarshaling\n\ttruncatedNanoseconds := time.Duration(m.Time.Nanosecond()).Truncate(time.Microsecond)\n\treturn \u0026Timestamp{\n\t\tSeconds: m.Time.Unix(),\n\t\tNanos: int32(truncatedNanoseconds),\n\t}\n}","line":{"from":25,"to":37}} {"id":100014961,"name":"Size","signature":"func (m *MicroTime) Size() (n int)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time_proto.go","code":"// Size implements the protobuf marshalling interface.\nfunc (m *MicroTime) Size() (n int) {\n\tif m == nil || m.Time.IsZero() {\n\t\treturn 0\n\t}\n\treturn m.ProtoMicroTime().Size()\n}","line":{"from":39,"to":45}} {"id":100014962,"name":"Unmarshal","signature":"func (m *MicroTime) Unmarshal(data []byte) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time_proto.go","code":"// Reset implements the protobuf marshalling interface.\nfunc (m *MicroTime) Unmarshal(data []byte) error {\n\tif len(data) == 0 {\n\t\tm.Time = time.Time{}\n\t\treturn nil\n\t}\n\tp := Timestamp{}\n\tif err := p.Unmarshal(data); err != nil {\n\t\treturn err\n\t}\n\n\t// truncate precision to microseconds to match JSON marshaling/unmarshaling\n\ttruncatedNanoseconds := time.Duration(p.Nanos).Truncate(time.Microsecond)\n\tm.Time = time.Unix(p.Seconds, int64(truncatedNanoseconds)).Local()\n\treturn nil\n}","line":{"from":47,"to":62}} {"id":100014963,"name":"Marshal","signature":"func (m *MicroTime) Marshal() (data []byte, err error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time_proto.go","code":"// Marshal implements the protobuf marshalling interface.\nfunc (m *MicroTime) Marshal() (data []byte, err error) {\n\tif m == nil || m.Time.IsZero() {\n\t\treturn nil, nil\n\t}\n\treturn m.ProtoMicroTime().Marshal()\n}","line":{"from":64,"to":70}} {"id":100014964,"name":"MarshalTo","signature":"func (m *MicroTime) MarshalTo(data []byte) (int, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time_proto.go","code":"// MarshalTo implements the protobuf marshalling interface.\nfunc (m *MicroTime) MarshalTo(data []byte) (int, error) {\n\tif m == nil || m.Time.IsZero() {\n\t\treturn 0, nil\n\t}\n\treturn m.ProtoMicroTime().MarshalTo(data)\n}","line":{"from":72,"to":78}} {"id":100014965,"name":"MarshalToSizedBuffer","signature":"func (m *MicroTime) MarshalToSizedBuffer(data []byte) (int, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time_proto.go","code":"// MarshalToSizedBuffer implements the protobuf marshalling interface.\nfunc (m *MicroTime) MarshalToSizedBuffer(data []byte) (int, error) {\n\tif m == nil || m.Time.IsZero() {\n\t\treturn 0, nil\n\t}\n\treturn m.ProtoMicroTime().MarshalToSizedBuffer(data)\n}","line":{"from":80,"to":86}} {"id":100014966,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":45,"to":48}} {"id":100014967,"name":"AddToGroupVersion","signature":"func AddToGroupVersion(scheme *runtime.Scheme, groupVersion schema.GroupVersion)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/register.go","code":"// AddToGroupVersion registers common meta types into schemas.\nfunc AddToGroupVersion(scheme *runtime.Scheme, groupVersion schema.GroupVersion) {\n\tscheme.AddKnownTypeWithName(groupVersion.WithKind(WatchEventKind), \u0026WatchEvent{})\n\tscheme.AddKnownTypeWithName(\n\t\tschema.GroupVersion{Group: groupVersion.Group, Version: runtime.APIVersionInternal}.WithKind(WatchEventKind),\n\t\t\u0026InternalEvent{},\n\t)\n\t// Supports legacy code paths, most callers should use metav1.ParameterCodec for now\n\tscheme.AddKnownTypes(groupVersion, optionsTypes...)\n\t// Register Unversioned types under their own special group\n\tscheme.AddUnversionedTypes(Unversioned,\n\t\t\u0026Status{},\n\t\t\u0026APIVersions{},\n\t\t\u0026APIGroupList{},\n\t\t\u0026APIGroup{},\n\t\t\u0026APIResourceList{},\n\t)\n\n\t// register manually. This usually goes through the SchemeBuilder, which we cannot use here.\n\tutilruntime.Must(RegisterConversions(scheme))\n\tutilruntime.Must(RegisterDefaults(scheme))\n}","line":{"from":65,"to":86}} {"id":100014968,"name":"AddMetaToScheme","signature":"func AddMetaToScheme(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/register.go","code":"// AddMetaToScheme registers base meta types into schemas.\nfunc AddMetaToScheme(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Table{},\n\t\t\u0026TableOptions{},\n\t\t\u0026PartialObjectMetadata{},\n\t\t\u0026PartialObjectMetadataList{},\n\t)\n\n\treturn nil\n}","line":{"from":88,"to":98}} {"id":100014969,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/register.go","code":"func init() {\n\tscheme.AddUnversionedTypes(SchemeGroupVersion, optionsTypes...)\n\n\tutilruntime.Must(AddMetaToScheme(scheme))\n\n\t// register manually. This usually goes through the SchemeBuilder, which we cannot use here.\n\tutilruntime.Must(RegisterDefaults(scheme))\n}","line":{"from":100,"to":107}} {"id":100014970,"name":"DeepCopyInto","signature":"func (t *Time) DeepCopyInto(out *Time)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time.go","code":"// DeepCopyInto creates a deep-copy of the Time value. The underlying time.Time\n// type is effectively immutable in the time API, so it is safe to\n// copy-by-assign, despite the presence of (unexported) Pointer fields.\nfunc (t *Time) DeepCopyInto(out *Time) {\n\t*out = *t\n}","line":{"from":35,"to":40}} {"id":100014971,"name":"NewTime","signature":"func NewTime(time time.Time) Time","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time.go","code":"// NewTime returns a wrapped instance of the provided time\nfunc NewTime(time time.Time) Time {\n\treturn Time{time}\n}","line":{"from":42,"to":45}} {"id":100014972,"name":"Date","signature":"func Date(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) Time","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time.go","code":"// Date returns the Time corresponding to the supplied parameters\n// by wrapping time.Date.\nfunc Date(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) Time {\n\treturn Time{time.Date(year, month, day, hour, min, sec, nsec, loc)}\n}","line":{"from":47,"to":51}} {"id":100014973,"name":"Now","signature":"func Now() Time","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time.go","code":"// Now returns the current local time.\nfunc Now() Time {\n\treturn Time{time.Now()}\n}","line":{"from":53,"to":56}} {"id":100014974,"name":"IsZero","signature":"func (t *Time) IsZero() bool","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time.go","code":"// IsZero returns true if the value is nil or time is zero.\nfunc (t *Time) IsZero() bool {\n\tif t == nil {\n\t\treturn true\n\t}\n\treturn t.Time.IsZero()\n}","line":{"from":58,"to":64}} {"id":100014975,"name":"Before","signature":"func (t *Time) Before(u *Time) bool","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time.go","code":"// Before reports whether the time instant t is before u.\nfunc (t *Time) Before(u *Time) bool {\n\tif t != nil \u0026\u0026 u != nil {\n\t\treturn t.Time.Before(u.Time)\n\t}\n\treturn false\n}","line":{"from":66,"to":72}} {"id":100014976,"name":"Equal","signature":"func (t *Time) Equal(u *Time) bool","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time.go","code":"// Equal reports whether the time instant t is equal to u.\nfunc (t *Time) Equal(u *Time) bool {\n\tif t == nil \u0026\u0026 u == nil {\n\t\treturn true\n\t}\n\tif t != nil \u0026\u0026 u != nil {\n\t\treturn t.Time.Equal(u.Time)\n\t}\n\treturn false\n}","line":{"from":74,"to":83}} {"id":100014977,"name":"Unix","signature":"func Unix(sec int64, nsec int64) Time","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time.go","code":"// Unix returns the local time corresponding to the given Unix time\n// by wrapping time.Unix.\nfunc Unix(sec int64, nsec int64) Time {\n\treturn Time{time.Unix(sec, nsec)}\n}","line":{"from":85,"to":89}} {"id":100014978,"name":"Rfc3339Copy","signature":"func (t Time) Rfc3339Copy() Time","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time.go","code":"// Rfc3339Copy returns a copy of the Time at second-level precision.\nfunc (t Time) Rfc3339Copy() Time {\n\tcopied, _ := time.Parse(time.RFC3339, t.Format(time.RFC3339))\n\treturn Time{copied}\n}","line":{"from":91,"to":95}} {"id":100014979,"name":"UnmarshalJSON","signature":"func (t *Time) UnmarshalJSON(b []byte) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time.go","code":"// UnmarshalJSON implements the json.Unmarshaller interface.\nfunc (t *Time) UnmarshalJSON(b []byte) error {\n\tif len(b) == 4 \u0026\u0026 string(b) == \"null\" {\n\t\tt.Time = time.Time{}\n\t\treturn nil\n\t}\n\n\tvar str string\n\terr := json.Unmarshal(b, \u0026str)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpt, err := time.Parse(time.RFC3339, str)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tt.Time = pt.Local()\n\treturn nil\n}","line":{"from":97,"to":117}} {"id":100014980,"name":"UnmarshalQueryParameter","signature":"func (t *Time) UnmarshalQueryParameter(str string) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time.go","code":"// UnmarshalQueryParameter converts from a URL query parameter value to an object\nfunc (t *Time) UnmarshalQueryParameter(str string) error {\n\tif len(str) == 0 {\n\t\tt.Time = time.Time{}\n\t\treturn nil\n\t}\n\t// Tolerate requests from older clients that used JSON serialization to build query params\n\tif len(str) == 4 \u0026\u0026 str == \"null\" {\n\t\tt.Time = time.Time{}\n\t\treturn nil\n\t}\n\n\tpt, err := time.Parse(time.RFC3339, str)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tt.Time = pt.Local()\n\treturn nil\n}","line":{"from":119,"to":138}} {"id":100014981,"name":"MarshalJSON","signature":"func (t Time) MarshalJSON() ([]byte, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time.go","code":"// MarshalJSON implements the json.Marshaler interface.\nfunc (t Time) MarshalJSON() ([]byte, error) {\n\tif t.IsZero() {\n\t\t// Encode unset/nil objects as JSON's \"null\".\n\t\treturn []byte(\"null\"), nil\n\t}\n\tbuf := make([]byte, 0, len(time.RFC3339)+2)\n\tbuf = append(buf, '\"')\n\t// time cannot contain non escapable JSON characters\n\tbuf = t.UTC().AppendFormat(buf, time.RFC3339)\n\tbuf = append(buf, '\"')\n\treturn buf, nil\n}","line":{"from":140,"to":152}} {"id":100014982,"name":"ToUnstructured","signature":"func (t Time) ToUnstructured() interface{}","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time.go","code":"// ToUnstructured implements the value.UnstructuredConverter interface.\nfunc (t Time) ToUnstructured() interface{} {\n\tif t.IsZero() {\n\t\treturn nil\n\t}\n\tbuf := make([]byte, 0, len(time.RFC3339))\n\tbuf = t.UTC().AppendFormat(buf, time.RFC3339)\n\treturn string(buf)\n}","line":{"from":154,"to":162}} {"id":100014983,"name":"OpenAPISchemaType","signature":"func (_ Time) OpenAPISchemaType() []string { return []string{\"string\"} }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time.go","code":"// OpenAPISchemaType is used by the kube-openapi generator when constructing\n// the OpenAPI spec of this type.\n//\n// See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators\nfunc (_ Time) OpenAPISchemaType() []string { return []string{\"string\"} }","line":{"from":164,"to":168}} {"id":100014984,"name":"OpenAPISchemaFormat","signature":"func (_ Time) OpenAPISchemaFormat() string { return \"date-time\" }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time.go","code":"// OpenAPISchemaFormat is used by the kube-openapi generator when constructing\n// the OpenAPI spec of this type.\nfunc (_ Time) OpenAPISchemaFormat() string { return \"date-time\" }","line":{"from":170,"to":172}} {"id":100014985,"name":"MarshalQueryParameter","signature":"func (t Time) MarshalQueryParameter() (string, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time.go","code":"// MarshalQueryParameter converts to a URL query parameter value\nfunc (t Time) MarshalQueryParameter() (string, error) {\n\tif t.IsZero() {\n\t\t// Encode unset/nil objects as an empty string\n\t\treturn \"\", nil\n\t}\n\n\treturn t.UTC().Format(time.RFC3339), nil\n}","line":{"from":174,"to":182}} {"id":100014986,"name":"Fuzz","signature":"func (t *Time) Fuzz(c fuzz.Continue)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time_fuzz.go","code":"// Fuzz satisfies fuzz.Interface.\nfunc (t *Time) Fuzz(c fuzz.Continue) {\n\tif t == nil {\n\t\treturn\n\t}\n\t// Allow for about 1000 years of randomness. Leave off nanoseconds\n\t// because JSON doesn't represent them so they can't round-trip\n\t// properly.\n\tt.Time = time.Unix(c.Rand.Int63n(1000*365*24*60*60), 0)\n}","line":{"from":28,"to":37}} {"id":100014987,"name":"ProtoTime","signature":"func (m *Time) ProtoTime() *Timestamp","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time_proto.go","code":"// Timestamp returns the Time as a new Timestamp value.\nfunc (m *Time) ProtoTime() *Timestamp {\n\tif m == nil {\n\t\treturn \u0026Timestamp{}\n\t}\n\treturn \u0026Timestamp{\n\t\tSeconds: m.Time.Unix(),\n\t\t// leaving this here for the record. our JSON only handled seconds, so this results in writes by\n\t\t// protobuf clients storing values that aren't read by json clients, which results in unexpected\n\t\t// field mutation, which fails various validation and equality code.\n\t\t// Nanos: int32(m.Time.Nanosecond()),\n\t}\n}","line":{"from":38,"to":50}} {"id":100014988,"name":"Size","signature":"func (m *Time) Size() (n int)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time_proto.go","code":"// Size implements the protobuf marshalling interface.\nfunc (m *Time) Size() (n int) {\n\tif m == nil || m.Time.IsZero() {\n\t\treturn 0\n\t}\n\treturn m.ProtoTime().Size()\n}","line":{"from":52,"to":58}} {"id":100014989,"name":"Unmarshal","signature":"func (m *Time) Unmarshal(data []byte) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time_proto.go","code":"// Reset implements the protobuf marshalling interface.\nfunc (m *Time) Unmarshal(data []byte) error {\n\tif len(data) == 0 {\n\t\tm.Time = time.Time{}\n\t\treturn nil\n\t}\n\tp := Timestamp{}\n\tif err := p.Unmarshal(data); err != nil {\n\t\treturn err\n\t}\n\t// leaving this here for the record. our JSON only handled seconds, so this results in writes by\n\t// protobuf clients storing values that aren't read by json clients, which results in unexpected\n\t// field mutation, which fails various validation and equality code.\n\t// m.Time = time.Unix(p.Seconds, int64(p.Nanos)).Local()\n\tm.Time = time.Unix(p.Seconds, int64(0)).Local()\n\treturn nil\n}","line":{"from":60,"to":76}} {"id":100014990,"name":"Marshal","signature":"func (m *Time) Marshal() (data []byte, err error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time_proto.go","code":"// Marshal implements the protobuf marshaling interface.\nfunc (m *Time) Marshal() (data []byte, err error) {\n\tif m == nil || m.Time.IsZero() {\n\t\treturn nil, nil\n\t}\n\treturn m.ProtoTime().Marshal()\n}","line":{"from":78,"to":84}} {"id":100014991,"name":"MarshalTo","signature":"func (m *Time) MarshalTo(data []byte) (int, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time_proto.go","code":"// MarshalTo implements the protobuf marshaling interface.\nfunc (m *Time) MarshalTo(data []byte) (int, error) {\n\tif m == nil || m.Time.IsZero() {\n\t\treturn 0, nil\n\t}\n\treturn m.ProtoTime().MarshalTo(data)\n}","line":{"from":86,"to":92}} {"id":100014992,"name":"MarshalToSizedBuffer","signature":"func (m *Time) MarshalToSizedBuffer(data []byte) (int, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time_proto.go","code":"// MarshalToSizedBuffer implements the protobuf reverse marshaling interface.\nfunc (m *Time) MarshalToSizedBuffer(data []byte) (int, error) {\n\tif m == nil || m.Time.IsZero() {\n\t\treturn 0, nil\n\t}\n\treturn m.ProtoTime().MarshalToSizedBuffer(data)\n}","line":{"from":94,"to":100}} {"id":100014993,"name":"ToPatchOptions","signature":"func (o ApplyOptions) ToPatchOptions() PatchOptions","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/types.go","code":"func (o ApplyOptions) ToPatchOptions() PatchOptions {\n\treturn PatchOptions{DryRun: o.DryRun, Force: \u0026o.Force, FieldManager: o.FieldManager}\n}","line":{"from":668,"to":670}} {"id":100014994,"name":"String","signature":"func (vs Verbs) String() string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/types.go","code":"func (vs Verbs) String() string {\n\treturn fmt.Sprintf(\"%v\", []string(vs))\n}","line":{"from":1139,"to":1141}} {"id":100014995,"name":"LabelSelectorQueryParam","signature":"func LabelSelectorQueryParam(version string) string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/types.go","code":"// TODO: remove me when watch is refactored\nfunc LabelSelectorQueryParam(version string) string {\n\treturn \"labelSelector\"\n}","line":{"from":1163,"to":1166}} {"id":100014996,"name":"FieldSelectorQueryParam","signature":"func FieldSelectorQueryParam(version string) string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/types.go","code":"// TODO: remove me when watch is refactored\nfunc FieldSelectorQueryParam(version string) string {\n\treturn \"fieldSelector\"\n}","line":{"from":1168,"to":1171}} {"id":100014997,"name":"String","signature":"func (apiVersions APIVersions) String() string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/types.go","code":"// String returns available api versions as a human-friendly version string.\nfunc (apiVersions APIVersions) String() string {\n\treturn strings.Join(apiVersions.Versions, \",\")\n}","line":{"from":1173,"to":1176}} {"id":100014998,"name":"GoString","signature":"func (apiVersions APIVersions) GoString() string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/types.go","code":"func (apiVersions APIVersions) GoString() string {\n\treturn apiVersions.String()\n}","line":{"from":1178,"to":1180}} {"id":100014999,"name":"String","signature":"func (f FieldsV1) String() string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/types.go","code":"func (f FieldsV1) String() string {\n\treturn string(f.Raw)\n}","line":{"from":1300,"to":1302}} {"id":100015000,"name":"NestedFieldCopy","signature":"func NestedFieldCopy(obj map[string]interface{}, fields ...string) (interface{}, bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"// NestedFieldCopy returns a deep copy of the value of a nested field.\n// Returns false if the value is missing.\n// No error is returned for a nil field.\n//\n// Note: fields passed to this function are treated as keys within the passed\n// object; no array/slice syntax is supported.\nfunc NestedFieldCopy(obj map[string]interface{}, fields ...string) (interface{}, bool, error) {\n\tval, found, err := NestedFieldNoCopy(obj, fields...)\n\tif !found || err != nil {\n\t\treturn nil, found, err\n\t}\n\treturn runtime.DeepCopyJSONValue(val), true, nil\n}","line":{"from":33,"to":45}} {"id":100015001,"name":"NestedFieldNoCopy","signature":"func NestedFieldNoCopy(obj map[string]interface{}, fields ...string) (interface{}, bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"// NestedFieldNoCopy returns a reference to a nested field.\n// Returns false if value is not found and an error if unable\n// to traverse obj.\n//\n// Note: fields passed to this function are treated as keys within the passed\n// object; no array/slice syntax is supported.\nfunc NestedFieldNoCopy(obj map[string]interface{}, fields ...string) (interface{}, bool, error) {\n\tvar val interface{} = obj\n\n\tfor i, field := range fields {\n\t\tif val == nil {\n\t\t\treturn nil, false, nil\n\t\t}\n\t\tif m, ok := val.(map[string]interface{}); ok {\n\t\t\tval, ok = m[field]\n\t\t\tif !ok {\n\t\t\t\treturn nil, false, nil\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, false, fmt.Errorf(\"%v accessor error: %v is of the type %T, expected map[string]interface{}\", jsonPath(fields[:i+1]), val, val)\n\t\t}\n\t}\n\treturn val, true, nil\n}","line":{"from":47,"to":70}} {"id":100015002,"name":"NestedString","signature":"func NestedString(obj map[string]interface{}, fields ...string) (string, bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"// NestedString returns the string value of a nested field.\n// Returns false if value is not found and an error if not a string.\nfunc NestedString(obj map[string]interface{}, fields ...string) (string, bool, error) {\n\tval, found, err := NestedFieldNoCopy(obj, fields...)\n\tif !found || err != nil {\n\t\treturn \"\", found, err\n\t}\n\ts, ok := val.(string)\n\tif !ok {\n\t\treturn \"\", false, fmt.Errorf(\"%v accessor error: %v is of the type %T, expected string\", jsonPath(fields), val, val)\n\t}\n\treturn s, true, nil\n}","line":{"from":72,"to":84}} {"id":100015003,"name":"NestedBool","signature":"func NestedBool(obj map[string]interface{}, fields ...string) (bool, bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"// NestedBool returns the bool value of a nested field.\n// Returns false if value is not found and an error if not a bool.\nfunc NestedBool(obj map[string]interface{}, fields ...string) (bool, bool, error) {\n\tval, found, err := NestedFieldNoCopy(obj, fields...)\n\tif !found || err != nil {\n\t\treturn false, found, err\n\t}\n\tb, ok := val.(bool)\n\tif !ok {\n\t\treturn false, false, fmt.Errorf(\"%v accessor error: %v is of the type %T, expected bool\", jsonPath(fields), val, val)\n\t}\n\treturn b, true, nil\n}","line":{"from":86,"to":98}} {"id":100015004,"name":"NestedFloat64","signature":"func NestedFloat64(obj map[string]interface{}, fields ...string) (float64, bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"// NestedFloat64 returns the float64 value of a nested field.\n// Returns false if value is not found and an error if not a float64.\nfunc NestedFloat64(obj map[string]interface{}, fields ...string) (float64, bool, error) {\n\tval, found, err := NestedFieldNoCopy(obj, fields...)\n\tif !found || err != nil {\n\t\treturn 0, found, err\n\t}\n\tf, ok := val.(float64)\n\tif !ok {\n\t\treturn 0, false, fmt.Errorf(\"%v accessor error: %v is of the type %T, expected float64\", jsonPath(fields), val, val)\n\t}\n\treturn f, true, nil\n}","line":{"from":100,"to":112}} {"id":100015005,"name":"NestedInt64","signature":"func NestedInt64(obj map[string]interface{}, fields ...string) (int64, bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"// NestedInt64 returns the int64 value of a nested field.\n// Returns false if value is not found and an error if not an int64.\nfunc NestedInt64(obj map[string]interface{}, fields ...string) (int64, bool, error) {\n\tval, found, err := NestedFieldNoCopy(obj, fields...)\n\tif !found || err != nil {\n\t\treturn 0, found, err\n\t}\n\ti, ok := val.(int64)\n\tif !ok {\n\t\treturn 0, false, fmt.Errorf(\"%v accessor error: %v is of the type %T, expected int64\", jsonPath(fields), val, val)\n\t}\n\treturn i, true, nil\n}","line":{"from":114,"to":126}} {"id":100015006,"name":"NestedStringSlice","signature":"func NestedStringSlice(obj map[string]interface{}, fields ...string) ([]string, bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"// NestedStringSlice returns a copy of []string value of a nested field.\n// Returns false if value is not found and an error if not a []interface{} or contains non-string items in the slice.\nfunc NestedStringSlice(obj map[string]interface{}, fields ...string) ([]string, bool, error) {\n\tval, found, err := NestedFieldNoCopy(obj, fields...)\n\tif !found || err != nil {\n\t\treturn nil, found, err\n\t}\n\tm, ok := val.([]interface{})\n\tif !ok {\n\t\treturn nil, false, fmt.Errorf(\"%v accessor error: %v is of the type %T, expected []interface{}\", jsonPath(fields), val, val)\n\t}\n\tstrSlice := make([]string, 0, len(m))\n\tfor _, v := range m {\n\t\tif str, ok := v.(string); ok {\n\t\t\tstrSlice = append(strSlice, str)\n\t\t} else {\n\t\t\treturn nil, false, fmt.Errorf(\"%v accessor error: contains non-string key in the slice: %v is of the type %T, expected string\", jsonPath(fields), v, v)\n\t\t}\n\t}\n\treturn strSlice, true, nil\n}","line":{"from":128,"to":148}} {"id":100015007,"name":"NestedSlice","signature":"func NestedSlice(obj map[string]interface{}, fields ...string) ([]interface{}, bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"// NestedSlice returns a deep copy of []interface{} value of a nested field.\n// Returns false if value is not found and an error if not a []interface{}.\nfunc NestedSlice(obj map[string]interface{}, fields ...string) ([]interface{}, bool, error) {\n\tval, found, err := NestedFieldNoCopy(obj, fields...)\n\tif !found || err != nil {\n\t\treturn nil, found, err\n\t}\n\t_, ok := val.([]interface{})\n\tif !ok {\n\t\treturn nil, false, fmt.Errorf(\"%v accessor error: %v is of the type %T, expected []interface{}\", jsonPath(fields), val, val)\n\t}\n\treturn runtime.DeepCopyJSONValue(val).([]interface{}), true, nil\n}","line":{"from":150,"to":162}} {"id":100015008,"name":"NestedStringMap","signature":"func NestedStringMap(obj map[string]interface{}, fields ...string) (map[string]string, bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"// NestedStringMap returns a copy of map[string]string value of a nested field.\n// Returns false if value is not found and an error if not a map[string]interface{} or contains non-string values in the map.\nfunc NestedStringMap(obj map[string]interface{}, fields ...string) (map[string]string, bool, error) {\n\tm, found, err := nestedMapNoCopy(obj, fields...)\n\tif !found || err != nil {\n\t\treturn nil, found, err\n\t}\n\tstrMap := make(map[string]string, len(m))\n\tfor k, v := range m {\n\t\tif str, ok := v.(string); ok {\n\t\t\tstrMap[k] = str\n\t\t} else {\n\t\t\treturn nil, false, fmt.Errorf(\"%v accessor error: contains non-string key in the map: %v is of the type %T, expected string\", jsonPath(fields), v, v)\n\t\t}\n\t}\n\treturn strMap, true, nil\n}","line":{"from":164,"to":180}} {"id":100015009,"name":"NestedMap","signature":"func NestedMap(obj map[string]interface{}, fields ...string) (map[string]interface{}, bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"// NestedMap returns a deep copy of map[string]interface{} value of a nested field.\n// Returns false if value is not found and an error if not a map[string]interface{}.\nfunc NestedMap(obj map[string]interface{}, fields ...string) (map[string]interface{}, bool, error) {\n\tm, found, err := nestedMapNoCopy(obj, fields...)\n\tif !found || err != nil {\n\t\treturn nil, found, err\n\t}\n\treturn runtime.DeepCopyJSON(m), true, nil\n}","line":{"from":182,"to":190}} {"id":100015010,"name":"nestedMapNoCopy","signature":"func nestedMapNoCopy(obj map[string]interface{}, fields ...string) (map[string]interface{}, bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"// nestedMapNoCopy returns a map[string]interface{} value of a nested field.\n// Returns false if value is not found and an error if not a map[string]interface{}.\nfunc nestedMapNoCopy(obj map[string]interface{}, fields ...string) (map[string]interface{}, bool, error) {\n\tval, found, err := NestedFieldNoCopy(obj, fields...)\n\tif !found || err != nil {\n\t\treturn nil, found, err\n\t}\n\tm, ok := val.(map[string]interface{})\n\tif !ok {\n\t\treturn nil, false, fmt.Errorf(\"%v accessor error: %v is of the type %T, expected map[string]interface{}\", jsonPath(fields), val, val)\n\t}\n\treturn m, true, nil\n}","line":{"from":192,"to":204}} {"id":100015011,"name":"SetNestedField","signature":"func SetNestedField(obj map[string]interface{}, value interface{}, fields ...string) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"// SetNestedField sets the value of a nested field to a deep copy of the value provided.\n// Returns an error if value cannot be set because one of the nesting levels is not a map[string]interface{}.\nfunc SetNestedField(obj map[string]interface{}, value interface{}, fields ...string) error {\n\treturn setNestedFieldNoCopy(obj, runtime.DeepCopyJSONValue(value), fields...)\n}","line":{"from":206,"to":210}} {"id":100015012,"name":"setNestedFieldNoCopy","signature":"func setNestedFieldNoCopy(obj map[string]interface{}, value interface{}, fields ...string) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"func setNestedFieldNoCopy(obj map[string]interface{}, value interface{}, fields ...string) error {\n\tm := obj\n\n\tfor i, field := range fields[:len(fields)-1] {\n\t\tif val, ok := m[field]; ok {\n\t\t\tif valMap, ok := val.(map[string]interface{}); ok {\n\t\t\t\tm = valMap\n\t\t\t} else {\n\t\t\t\treturn fmt.Errorf(\"value cannot be set because %v is not a map[string]interface{}\", jsonPath(fields[:i+1]))\n\t\t\t}\n\t\t} else {\n\t\t\tnewVal := make(map[string]interface{})\n\t\t\tm[field] = newVal\n\t\t\tm = newVal\n\t\t}\n\t}\n\tm[fields[len(fields)-1]] = value\n\treturn nil\n}","line":{"from":212,"to":230}} {"id":100015013,"name":"SetNestedStringSlice","signature":"func SetNestedStringSlice(obj map[string]interface{}, value []string, fields ...string) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"// SetNestedStringSlice sets the string slice value of a nested field.\n// Returns an error if value cannot be set because one of the nesting levels is not a map[string]interface{}.\nfunc SetNestedStringSlice(obj map[string]interface{}, value []string, fields ...string) error {\n\tm := make([]interface{}, 0, len(value)) // convert []string into []interface{}\n\tfor _, v := range value {\n\t\tm = append(m, v)\n\t}\n\treturn setNestedFieldNoCopy(obj, m, fields...)\n}","line":{"from":232,"to":240}} {"id":100015014,"name":"SetNestedSlice","signature":"func SetNestedSlice(obj map[string]interface{}, value []interface{}, fields ...string) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"// SetNestedSlice sets the slice value of a nested field.\n// Returns an error if value cannot be set because one of the nesting levels is not a map[string]interface{}.\nfunc SetNestedSlice(obj map[string]interface{}, value []interface{}, fields ...string) error {\n\treturn SetNestedField(obj, value, fields...)\n}","line":{"from":242,"to":246}} {"id":100015015,"name":"SetNestedStringMap","signature":"func SetNestedStringMap(obj map[string]interface{}, value map[string]string, fields ...string) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"// SetNestedStringMap sets the map[string]string value of a nested field.\n// Returns an error if value cannot be set because one of the nesting levels is not a map[string]interface{}.\nfunc SetNestedStringMap(obj map[string]interface{}, value map[string]string, fields ...string) error {\n\tm := make(map[string]interface{}, len(value)) // convert map[string]string into map[string]interface{}\n\tfor k, v := range value {\n\t\tm[k] = v\n\t}\n\treturn setNestedFieldNoCopy(obj, m, fields...)\n}","line":{"from":248,"to":256}} {"id":100015016,"name":"SetNestedMap","signature":"func SetNestedMap(obj map[string]interface{}, value map[string]interface{}, fields ...string) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"// SetNestedMap sets the map[string]interface{} value of a nested field.\n// Returns an error if value cannot be set because one of the nesting levels is not a map[string]interface{}.\nfunc SetNestedMap(obj map[string]interface{}, value map[string]interface{}, fields ...string) error {\n\treturn SetNestedField(obj, value, fields...)\n}","line":{"from":258,"to":262}} {"id":100015017,"name":"RemoveNestedField","signature":"func RemoveNestedField(obj map[string]interface{}, fields ...string)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"// RemoveNestedField removes the nested field from the obj.\nfunc RemoveNestedField(obj map[string]interface{}, fields ...string) {\n\tm := obj\n\tfor _, field := range fields[:len(fields)-1] {\n\t\tif x, ok := m[field].(map[string]interface{}); ok {\n\t\t\tm = x\n\t\t} else {\n\t\t\treturn\n\t\t}\n\t}\n\tdelete(m, fields[len(fields)-1])\n}","line":{"from":264,"to":275}} {"id":100015018,"name":"getNestedString","signature":"func getNestedString(obj map[string]interface{}, fields ...string) string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"func getNestedString(obj map[string]interface{}, fields ...string) string {\n\tval, found, err := NestedString(obj, fields...)\n\tif !found || err != nil {\n\t\treturn \"\"\n\t}\n\treturn val\n}","line":{"from":277,"to":283}} {"id":100015019,"name":"getNestedInt64Pointer","signature":"func getNestedInt64Pointer(obj map[string]interface{}, fields ...string) *int64","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"func getNestedInt64Pointer(obj map[string]interface{}, fields ...string) *int64 {\n\tval, found, err := NestedInt64(obj, fields...)\n\tif !found || err != nil {\n\t\treturn nil\n\t}\n\treturn \u0026val\n}","line":{"from":285,"to":291}} {"id":100015020,"name":"jsonPath","signature":"func jsonPath(fields []string) string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"func jsonPath(fields []string) string {\n\treturn \".\" + strings.Join(fields, \".\")\n}","line":{"from":293,"to":295}} {"id":100015021,"name":"extractOwnerReference","signature":"func extractOwnerReference(v map[string]interface{}) metav1.OwnerReference","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"func extractOwnerReference(v map[string]interface{}) metav1.OwnerReference {\n\t// though this field is a *bool, but when decoded from JSON, it's\n\t// unmarshalled as bool.\n\tvar controllerPtr *bool\n\tif controller, found, err := NestedBool(v, \"controller\"); err == nil \u0026\u0026 found {\n\t\tcontrollerPtr = \u0026controller\n\t}\n\tvar blockOwnerDeletionPtr *bool\n\tif blockOwnerDeletion, found, err := NestedBool(v, \"blockOwnerDeletion\"); err == nil \u0026\u0026 found {\n\t\tblockOwnerDeletionPtr = \u0026blockOwnerDeletion\n\t}\n\treturn metav1.OwnerReference{\n\t\tKind: getNestedString(v, \"kind\"),\n\t\tName: getNestedString(v, \"name\"),\n\t\tAPIVersion: getNestedString(v, \"apiVersion\"),\n\t\tUID: types.UID(getNestedString(v, \"uid\")),\n\t\tController: controllerPtr,\n\t\tBlockOwnerDeletion: blockOwnerDeletionPtr,\n\t}\n}","line":{"from":297,"to":316}} {"id":100015022,"name":"Decode","signature":"func (s unstructuredJSONScheme) Decode(data []byte, _ *schema.GroupVersionKind, obj runtime.Object) (runtime.Object, *schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"func (s unstructuredJSONScheme) Decode(data []byte, _ *schema.GroupVersionKind, obj runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {\n\tvar err error\n\tif obj != nil {\n\t\terr = s.decodeInto(data, obj)\n\t} else {\n\t\tobj, err = s.decode(data)\n\t}\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tgvk := obj.GetObjectKind().GroupVersionKind()\n\tif len(gvk.Kind) == 0 {\n\t\treturn nil, \u0026gvk, runtime.NewMissingKindErr(string(data))\n\t}\n\t// TODO(109023): require apiVersion here as well\n\n\treturn obj, \u0026gvk, nil\n}","line":{"from":327,"to":346}} {"id":100015023,"name":"Encode","signature":"func (s unstructuredJSONScheme) Encode(obj runtime.Object, w io.Writer) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"func (s unstructuredJSONScheme) Encode(obj runtime.Object, w io.Writer) error {\n\tif co, ok := obj.(runtime.CacheableObject); ok {\n\t\treturn co.CacheEncode(s.Identifier(), s.doEncode, w)\n\t}\n\treturn s.doEncode(obj, w)\n}","line":{"from":348,"to":353}} {"id":100015024,"name":"doEncode","signature":"func (unstructuredJSONScheme) doEncode(obj runtime.Object, w io.Writer) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"func (unstructuredJSONScheme) doEncode(obj runtime.Object, w io.Writer) error {\n\tswitch t := obj.(type) {\n\tcase *Unstructured:\n\t\treturn json.NewEncoder(w).Encode(t.Object)\n\tcase *UnstructuredList:\n\t\titems := make([]interface{}, 0, len(t.Items))\n\t\tfor _, i := range t.Items {\n\t\t\titems = append(items, i.Object)\n\t\t}\n\t\tlistObj := make(map[string]interface{}, len(t.Object)+1)\n\t\tfor k, v := range t.Object { // Make a shallow copy\n\t\t\tlistObj[k] = v\n\t\t}\n\t\tlistObj[\"items\"] = items\n\t\treturn json.NewEncoder(w).Encode(listObj)\n\tcase *runtime.Unknown:\n\t\t// TODO: Unstructured needs to deal with ContentType.\n\t\t_, err := w.Write(t.Raw)\n\t\treturn err\n\tdefault:\n\t\treturn json.NewEncoder(w).Encode(t)\n\t}\n}","line":{"from":355,"to":377}} {"id":100015025,"name":"Identifier","signature":"func (unstructuredJSONScheme) Identifier() runtime.Identifier","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"// Identifier implements runtime.Encoder interface.\nfunc (unstructuredJSONScheme) Identifier() runtime.Identifier {\n\treturn unstructuredJSONSchemeIdentifier\n}","line":{"from":379,"to":382}} {"id":100015026,"name":"decode","signature":"func (s unstructuredJSONScheme) decode(data []byte) (runtime.Object, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"func (s unstructuredJSONScheme) decode(data []byte) (runtime.Object, error) {\n\ttype detector struct {\n\t\tItems gojson.RawMessage `json:\"items\"`\n\t}\n\tvar det detector\n\tif err := json.Unmarshal(data, \u0026det); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif det.Items != nil {\n\t\tlist := \u0026UnstructuredList{}\n\t\terr := s.decodeToList(data, list)\n\t\treturn list, err\n\t}\n\n\t// No Items field, so it wasn't a list.\n\tunstruct := \u0026Unstructured{}\n\terr := s.decodeToUnstructured(data, unstruct)\n\treturn unstruct, err\n}","line":{"from":384,"to":403}} {"id":100015027,"name":"decodeInto","signature":"func (s unstructuredJSONScheme) decodeInto(data []byte, obj runtime.Object) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"func (s unstructuredJSONScheme) decodeInto(data []byte, obj runtime.Object) error {\n\tswitch x := obj.(type) {\n\tcase *Unstructured:\n\t\treturn s.decodeToUnstructured(data, x)\n\tcase *UnstructuredList:\n\t\treturn s.decodeToList(data, x)\n\tdefault:\n\t\treturn json.Unmarshal(data, x)\n\t}\n}","line":{"from":405,"to":414}} {"id":100015028,"name":"decodeToUnstructured","signature":"func (unstructuredJSONScheme) decodeToUnstructured(data []byte, unstruct *Unstructured) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"func (unstructuredJSONScheme) decodeToUnstructured(data []byte, unstruct *Unstructured) error {\n\tm := make(map[string]interface{})\n\tif err := json.Unmarshal(data, \u0026m); err != nil {\n\t\treturn err\n\t}\n\n\tunstruct.Object = m\n\n\treturn nil\n}","line":{"from":416,"to":425}} {"id":100015029,"name":"decodeToList","signature":"func (s unstructuredJSONScheme) decodeToList(data []byte, list *UnstructuredList) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"func (s unstructuredJSONScheme) decodeToList(data []byte, list *UnstructuredList) error {\n\ttype decodeList struct {\n\t\tItems []gojson.RawMessage `json:\"items\"`\n\t}\n\n\tvar dList decodeList\n\tif err := json.Unmarshal(data, \u0026dList); err != nil {\n\t\treturn err\n\t}\n\n\tif err := json.Unmarshal(data, \u0026list.Object); err != nil {\n\t\treturn err\n\t}\n\n\t// For typed lists, e.g., a PodList, API server doesn't set each item's\n\t// APIVersion and Kind. We need to set it.\n\tlistAPIVersion := list.GetAPIVersion()\n\tlistKind := list.GetKind()\n\titemKind := strings.TrimSuffix(listKind, \"List\")\n\n\tdelete(list.Object, \"items\")\n\tlist.Items = make([]Unstructured, 0, len(dList.Items))\n\tfor _, i := range dList.Items {\n\t\tunstruct := \u0026Unstructured{}\n\t\tif err := s.decodeToUnstructured([]byte(i), unstruct); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// This is hacky. Set the item's Kind and APIVersion to those inferred\n\t\t// from the List.\n\t\tif len(unstruct.GetKind()) == 0 \u0026\u0026 len(unstruct.GetAPIVersion()) == 0 {\n\t\t\tunstruct.SetKind(itemKind)\n\t\t\tunstruct.SetAPIVersion(listAPIVersion)\n\t\t}\n\t\tlist.Items = append(list.Items, *unstruct)\n\t}\n\treturn nil\n}","line":{"from":427,"to":463}} {"id":100015030,"name":"NewJSONFallbackEncoder","signature":"func NewJSONFallbackEncoder(encoder runtime.Encoder) runtime.Encoder","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"func NewJSONFallbackEncoder(encoder runtime.Encoder) runtime.Encoder {\n\tresult := map[string]string{\n\t\t\"name\": \"fallback\",\n\t\t\"base\": string(encoder.Identifier()),\n\t}\n\tidentifier, err := gojson.Marshal(result)\n\tif err != nil {\n\t\tklog.Fatalf(\"Failed marshaling identifier for jsonFallbackEncoder: %v\", err)\n\t}\n\treturn \u0026jsonFallbackEncoder{\n\t\tencoder: encoder,\n\t\tidentifier: runtime.Identifier(identifier),\n\t}\n}","line":{"from":470,"to":483}} {"id":100015031,"name":"Encode","signature":"func (c *jsonFallbackEncoder) Encode(obj runtime.Object, w io.Writer) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"func (c *jsonFallbackEncoder) Encode(obj runtime.Object, w io.Writer) error {\n\t// There is no need to handle runtime.CacheableObject, as we only\n\t// fallback to other encoders here.\n\terr := c.encoder.Encode(obj, w)\n\tif runtime.IsNotRegisteredError(err) {\n\t\tswitch obj.(type) {\n\t\tcase *Unstructured, *UnstructuredList:\n\t\t\treturn UnstructuredJSONScheme.Encode(obj, w)\n\t\t}\n\t}\n\treturn err\n}","line":{"from":485,"to":496}} {"id":100015032,"name":"Identifier","signature":"func (c *jsonFallbackEncoder) Identifier() runtime.Identifier","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers.go","code":"// Identifier implements runtime.Encoder interface.\nfunc (c *jsonFallbackEncoder) Identifier() runtime.Identifier {\n\treturn c.identifier\n}","line":{"from":498,"to":501}} {"id":100015033,"name":"GetObjectKind","signature":"func (obj *Unstructured) GetObjectKind() schema.ObjectKind { return obj }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (obj *Unstructured) GetObjectKind() schema.ObjectKind { return obj }","line":{"from":52,"to":52}} {"id":100015034,"name":"IsList","signature":"func (obj *Unstructured) IsList() bool","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (obj *Unstructured) IsList() bool {\n\tfield, ok := obj.Object[\"items\"]\n\tif !ok {\n\t\treturn false\n\t}\n\t_, ok = field.([]interface{})\n\treturn ok\n}","line":{"from":54,"to":61}} {"id":100015035,"name":"ToList","signature":"func (obj *Unstructured) ToList() (*UnstructuredList, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (obj *Unstructured) ToList() (*UnstructuredList, error) {\n\tif !obj.IsList() {\n\t\t// return an empty list back\n\t\treturn \u0026UnstructuredList{Object: obj.Object}, nil\n\t}\n\n\tret := \u0026UnstructuredList{}\n\tret.Object = obj.Object\n\n\terr := obj.EachListItem(func(item runtime.Object) error {\n\t\tcastItem := item.(*Unstructured)\n\t\tret.Items = append(ret.Items, *castItem)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ret, nil\n}","line":{"from":62,"to":81}} {"id":100015036,"name":"EachListItem","signature":"func (obj *Unstructured) EachListItem(fn func(runtime.Object) error) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (obj *Unstructured) EachListItem(fn func(runtime.Object) error) error {\n\tfield, ok := obj.Object[\"items\"]\n\tif !ok {\n\t\treturn errors.New(\"content is not a list\")\n\t}\n\titems, ok := field.([]interface{})\n\tif !ok {\n\t\treturn fmt.Errorf(\"content is not a list: %T\", field)\n\t}\n\tfor _, item := range items {\n\t\tchild, ok := item.(map[string]interface{})\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"items member is not an object: %T\", child)\n\t\t}\n\t\tif err := fn(\u0026Unstructured{Object: child}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":83,"to":102}} {"id":100015037,"name":"UnstructuredContent","signature":"func (obj *Unstructured) UnstructuredContent() map[string]interface{}","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (obj *Unstructured) UnstructuredContent() map[string]interface{} {\n\tif obj.Object == nil {\n\t\treturn make(map[string]interface{})\n\t}\n\treturn obj.Object\n}","line":{"from":104,"to":109}} {"id":100015038,"name":"SetUnstructuredContent","signature":"func (obj *Unstructured) SetUnstructuredContent(content map[string]interface{})","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (obj *Unstructured) SetUnstructuredContent(content map[string]interface{}) {\n\tobj.Object = content\n}","line":{"from":111,"to":113}} {"id":100015039,"name":"MarshalJSON","signature":"func (u *Unstructured) MarshalJSON() ([]byte, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"// MarshalJSON ensures that the unstructured object produces proper\n// JSON when passed to Go's standard JSON library.\nfunc (u *Unstructured) MarshalJSON() ([]byte, error) {\n\tvar buf bytes.Buffer\n\terr := UnstructuredJSONScheme.Encode(u, \u0026buf)\n\treturn buf.Bytes(), err\n}","line":{"from":115,"to":121}} {"id":100015040,"name":"UnmarshalJSON","signature":"func (u *Unstructured) UnmarshalJSON(b []byte) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"// UnmarshalJSON ensures that the unstructured object properly decodes\n// JSON when passed to Go's standard JSON library.\nfunc (u *Unstructured) UnmarshalJSON(b []byte) error {\n\t_, _, err := UnstructuredJSONScheme.Decode(b, nil, u)\n\treturn err\n}","line":{"from":123,"to":128}} {"id":100015041,"name":"NewEmptyInstance","signature":"func (in *Unstructured) NewEmptyInstance() runtime.Unstructured","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"// NewEmptyInstance returns a new instance of the concrete type containing only kind/apiVersion and no other data.\n// This should be called instead of reflect.New() for unstructured types because the go type alone does not preserve kind/apiVersion info.\nfunc (in *Unstructured) NewEmptyInstance() runtime.Unstructured {\n\tout := new(Unstructured)\n\tif in != nil {\n\t\tout.GetObjectKind().SetGroupVersionKind(in.GetObjectKind().GroupVersionKind())\n\t}\n\treturn out\n}","line":{"from":130,"to":138}} {"id":100015042,"name":"DeepCopy","signature":"func (in *Unstructured) DeepCopy() *Unstructured","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (in *Unstructured) DeepCopy() *Unstructured {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Unstructured)\n\t*out = *in\n\tout.Object = runtime.DeepCopyJSON(in.Object)\n\treturn out\n}","line":{"from":140,"to":148}} {"id":100015043,"name":"setNestedField","signature":"func (u *Unstructured) setNestedField(value interface{}, fields ...string)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) setNestedField(value interface{}, fields ...string) {\n\tif u.Object == nil {\n\t\tu.Object = make(map[string]interface{})\n\t}\n\tSetNestedField(u.Object, value, fields...)\n}","line":{"from":150,"to":155}} {"id":100015044,"name":"setNestedStringSlice","signature":"func (u *Unstructured) setNestedStringSlice(value []string, fields ...string)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) setNestedStringSlice(value []string, fields ...string) {\n\tif u.Object == nil {\n\t\tu.Object = make(map[string]interface{})\n\t}\n\tSetNestedStringSlice(u.Object, value, fields...)\n}","line":{"from":157,"to":162}} {"id":100015045,"name":"setNestedSlice","signature":"func (u *Unstructured) setNestedSlice(value []interface{}, fields ...string)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) setNestedSlice(value []interface{}, fields ...string) {\n\tif u.Object == nil {\n\t\tu.Object = make(map[string]interface{})\n\t}\n\tSetNestedSlice(u.Object, value, fields...)\n}","line":{"from":164,"to":169}} {"id":100015046,"name":"setNestedMap","signature":"func (u *Unstructured) setNestedMap(value map[string]string, fields ...string)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) setNestedMap(value map[string]string, fields ...string) {\n\tif u.Object == nil {\n\t\tu.Object = make(map[string]interface{})\n\t}\n\tSetNestedStringMap(u.Object, value, fields...)\n}","line":{"from":171,"to":176}} {"id":100015047,"name":"GetOwnerReferences","signature":"func (u *Unstructured) GetOwnerReferences() []metav1.OwnerReference","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) GetOwnerReferences() []metav1.OwnerReference {\n\tfield, found, err := NestedFieldNoCopy(u.Object, \"metadata\", \"ownerReferences\")\n\tif !found || err != nil {\n\t\treturn nil\n\t}\n\toriginal, ok := field.([]interface{})\n\tif !ok {\n\t\treturn nil\n\t}\n\tret := make([]metav1.OwnerReference, 0, len(original))\n\tfor _, obj := range original {\n\t\to, ok := obj.(map[string]interface{})\n\t\tif !ok {\n\t\t\t// expected map[string]interface{}, got something else\n\t\t\treturn nil\n\t\t}\n\t\tret = append(ret, extractOwnerReference(o))\n\t}\n\treturn ret\n}","line":{"from":178,"to":197}} {"id":100015048,"name":"SetOwnerReferences","signature":"func (u *Unstructured) SetOwnerReferences(references []metav1.OwnerReference)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) SetOwnerReferences(references []metav1.OwnerReference) {\n\tif references == nil {\n\t\tRemoveNestedField(u.Object, \"metadata\", \"ownerReferences\")\n\t\treturn\n\t}\n\n\tnewReferences := make([]interface{}, 0, len(references))\n\tfor _, reference := range references {\n\t\tout, err := runtime.DefaultUnstructuredConverter.ToUnstructured(\u0026reference)\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"unable to convert Owner Reference: %v\", err))\n\t\t\tcontinue\n\t\t}\n\t\tnewReferences = append(newReferences, out)\n\t}\n\tu.setNestedField(newReferences, \"metadata\", \"ownerReferences\")\n}","line":{"from":199,"to":215}} {"id":100015049,"name":"GetAPIVersion","signature":"func (u *Unstructured) GetAPIVersion() string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) GetAPIVersion() string {\n\treturn getNestedString(u.Object, \"apiVersion\")\n}","line":{"from":217,"to":219}} {"id":100015050,"name":"SetAPIVersion","signature":"func (u *Unstructured) SetAPIVersion(version string)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) SetAPIVersion(version string) {\n\tu.setNestedField(version, \"apiVersion\")\n}","line":{"from":221,"to":223}} {"id":100015051,"name":"GetKind","signature":"func (u *Unstructured) GetKind() string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) GetKind() string {\n\treturn getNestedString(u.Object, \"kind\")\n}","line":{"from":225,"to":227}} {"id":100015052,"name":"SetKind","signature":"func (u *Unstructured) SetKind(kind string)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) SetKind(kind string) {\n\tu.setNestedField(kind, \"kind\")\n}","line":{"from":229,"to":231}} {"id":100015053,"name":"GetNamespace","signature":"func (u *Unstructured) GetNamespace() string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) GetNamespace() string {\n\treturn getNestedString(u.Object, \"metadata\", \"namespace\")\n}","line":{"from":233,"to":235}} {"id":100015054,"name":"SetNamespace","signature":"func (u *Unstructured) SetNamespace(namespace string)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) SetNamespace(namespace string) {\n\tif len(namespace) == 0 {\n\t\tRemoveNestedField(u.Object, \"metadata\", \"namespace\")\n\t\treturn\n\t}\n\tu.setNestedField(namespace, \"metadata\", \"namespace\")\n}","line":{"from":237,"to":243}} {"id":100015055,"name":"GetName","signature":"func (u *Unstructured) GetName() string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) GetName() string {\n\treturn getNestedString(u.Object, \"metadata\", \"name\")\n}","line":{"from":245,"to":247}} {"id":100015056,"name":"SetName","signature":"func (u *Unstructured) SetName(name string)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) SetName(name string) {\n\tif len(name) == 0 {\n\t\tRemoveNestedField(u.Object, \"metadata\", \"name\")\n\t\treturn\n\t}\n\tu.setNestedField(name, \"metadata\", \"name\")\n}","line":{"from":249,"to":255}} {"id":100015057,"name":"GetGenerateName","signature":"func (u *Unstructured) GetGenerateName() string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) GetGenerateName() string {\n\treturn getNestedString(u.Object, \"metadata\", \"generateName\")\n}","line":{"from":257,"to":259}} {"id":100015058,"name":"SetGenerateName","signature":"func (u *Unstructured) SetGenerateName(generateName string)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) SetGenerateName(generateName string) {\n\tif len(generateName) == 0 {\n\t\tRemoveNestedField(u.Object, \"metadata\", \"generateName\")\n\t\treturn\n\t}\n\tu.setNestedField(generateName, \"metadata\", \"generateName\")\n}","line":{"from":261,"to":267}} {"id":100015059,"name":"GetUID","signature":"func (u *Unstructured) GetUID() types.UID","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) GetUID() types.UID {\n\treturn types.UID(getNestedString(u.Object, \"metadata\", \"uid\"))\n}","line":{"from":269,"to":271}} {"id":100015060,"name":"SetUID","signature":"func (u *Unstructured) SetUID(uid types.UID)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) SetUID(uid types.UID) {\n\tif len(string(uid)) == 0 {\n\t\tRemoveNestedField(u.Object, \"metadata\", \"uid\")\n\t\treturn\n\t}\n\tu.setNestedField(string(uid), \"metadata\", \"uid\")\n}","line":{"from":273,"to":279}} {"id":100015061,"name":"GetResourceVersion","signature":"func (u *Unstructured) GetResourceVersion() string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) GetResourceVersion() string {\n\treturn getNestedString(u.Object, \"metadata\", \"resourceVersion\")\n}","line":{"from":281,"to":283}} {"id":100015062,"name":"SetResourceVersion","signature":"func (u *Unstructured) SetResourceVersion(resourceVersion string)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) SetResourceVersion(resourceVersion string) {\n\tif len(resourceVersion) == 0 {\n\t\tRemoveNestedField(u.Object, \"metadata\", \"resourceVersion\")\n\t\treturn\n\t}\n\tu.setNestedField(resourceVersion, \"metadata\", \"resourceVersion\")\n}","line":{"from":285,"to":291}} {"id":100015063,"name":"GetGeneration","signature":"func (u *Unstructured) GetGeneration() int64","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) GetGeneration() int64 {\n\tval, found, err := NestedInt64(u.Object, \"metadata\", \"generation\")\n\tif !found || err != nil {\n\t\treturn 0\n\t}\n\treturn val\n}","line":{"from":293,"to":299}} {"id":100015064,"name":"SetGeneration","signature":"func (u *Unstructured) SetGeneration(generation int64)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) SetGeneration(generation int64) {\n\tif generation == 0 {\n\t\tRemoveNestedField(u.Object, \"metadata\", \"generation\")\n\t\treturn\n\t}\n\tu.setNestedField(generation, \"metadata\", \"generation\")\n}","line":{"from":301,"to":307}} {"id":100015065,"name":"GetSelfLink","signature":"func (u *Unstructured) GetSelfLink() string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) GetSelfLink() string {\n\treturn getNestedString(u.Object, \"metadata\", \"selfLink\")\n}","line":{"from":309,"to":311}} {"id":100015066,"name":"SetSelfLink","signature":"func (u *Unstructured) SetSelfLink(selfLink string)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) SetSelfLink(selfLink string) {\n\tif len(selfLink) == 0 {\n\t\tRemoveNestedField(u.Object, \"metadata\", \"selfLink\")\n\t\treturn\n\t}\n\tu.setNestedField(selfLink, \"metadata\", \"selfLink\")\n}","line":{"from":313,"to":319}} {"id":100015067,"name":"GetContinue","signature":"func (u *Unstructured) GetContinue() string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) GetContinue() string {\n\treturn getNestedString(u.Object, \"metadata\", \"continue\")\n}","line":{"from":321,"to":323}} {"id":100015068,"name":"SetContinue","signature":"func (u *Unstructured) SetContinue(c string)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) SetContinue(c string) {\n\tif len(c) == 0 {\n\t\tRemoveNestedField(u.Object, \"metadata\", \"continue\")\n\t\treturn\n\t}\n\tu.setNestedField(c, \"metadata\", \"continue\")\n}","line":{"from":325,"to":331}} {"id":100015069,"name":"GetRemainingItemCount","signature":"func (u *Unstructured) GetRemainingItemCount() *int64","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) GetRemainingItemCount() *int64 {\n\treturn getNestedInt64Pointer(u.Object, \"metadata\", \"remainingItemCount\")\n}","line":{"from":333,"to":335}} {"id":100015070,"name":"SetRemainingItemCount","signature":"func (u *Unstructured) SetRemainingItemCount(c *int64)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) SetRemainingItemCount(c *int64) {\n\tif c == nil {\n\t\tRemoveNestedField(u.Object, \"metadata\", \"remainingItemCount\")\n\t} else {\n\t\tu.setNestedField(*c, \"metadata\", \"remainingItemCount\")\n\t}\n}","line":{"from":337,"to":343}} {"id":100015071,"name":"GetCreationTimestamp","signature":"func (u *Unstructured) GetCreationTimestamp() metav1.Time","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) GetCreationTimestamp() metav1.Time {\n\tvar timestamp metav1.Time\n\ttimestamp.UnmarshalQueryParameter(getNestedString(u.Object, \"metadata\", \"creationTimestamp\"))\n\treturn timestamp\n}","line":{"from":345,"to":349}} {"id":100015072,"name":"SetCreationTimestamp","signature":"func (u *Unstructured) SetCreationTimestamp(timestamp metav1.Time)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) SetCreationTimestamp(timestamp metav1.Time) {\n\tts, _ := timestamp.MarshalQueryParameter()\n\tif len(ts) == 0 || timestamp.Time.IsZero() {\n\t\tRemoveNestedField(u.Object, \"metadata\", \"creationTimestamp\")\n\t\treturn\n\t}\n\tu.setNestedField(ts, \"metadata\", \"creationTimestamp\")\n}","line":{"from":351,"to":358}} {"id":100015073,"name":"GetDeletionTimestamp","signature":"func (u *Unstructured) GetDeletionTimestamp() *metav1.Time","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) GetDeletionTimestamp() *metav1.Time {\n\tvar timestamp metav1.Time\n\ttimestamp.UnmarshalQueryParameter(getNestedString(u.Object, \"metadata\", \"deletionTimestamp\"))\n\tif timestamp.IsZero() {\n\t\treturn nil\n\t}\n\treturn \u0026timestamp\n}","line":{"from":360,"to":367}} {"id":100015074,"name":"SetDeletionTimestamp","signature":"func (u *Unstructured) SetDeletionTimestamp(timestamp *metav1.Time)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) SetDeletionTimestamp(timestamp *metav1.Time) {\n\tif timestamp == nil {\n\t\tRemoveNestedField(u.Object, \"metadata\", \"deletionTimestamp\")\n\t\treturn\n\t}\n\tts, _ := timestamp.MarshalQueryParameter()\n\tu.setNestedField(ts, \"metadata\", \"deletionTimestamp\")\n}","line":{"from":369,"to":376}} {"id":100015075,"name":"GetDeletionGracePeriodSeconds","signature":"func (u *Unstructured) GetDeletionGracePeriodSeconds() *int64","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) GetDeletionGracePeriodSeconds() *int64 {\n\tval, found, err := NestedInt64(u.Object, \"metadata\", \"deletionGracePeriodSeconds\")\n\tif !found || err != nil {\n\t\treturn nil\n\t}\n\treturn \u0026val\n}","line":{"from":378,"to":384}} {"id":100015076,"name":"SetDeletionGracePeriodSeconds","signature":"func (u *Unstructured) SetDeletionGracePeriodSeconds(deletionGracePeriodSeconds *int64)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) SetDeletionGracePeriodSeconds(deletionGracePeriodSeconds *int64) {\n\tif deletionGracePeriodSeconds == nil {\n\t\tRemoveNestedField(u.Object, \"metadata\", \"deletionGracePeriodSeconds\")\n\t\treturn\n\t}\n\tu.setNestedField(*deletionGracePeriodSeconds, \"metadata\", \"deletionGracePeriodSeconds\")\n}","line":{"from":386,"to":392}} {"id":100015077,"name":"GetLabels","signature":"func (u *Unstructured) GetLabels() map[string]string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) GetLabels() map[string]string {\n\tm, _, _ := NestedStringMap(u.Object, \"metadata\", \"labels\")\n\treturn m\n}","line":{"from":394,"to":397}} {"id":100015078,"name":"SetLabels","signature":"func (u *Unstructured) SetLabels(labels map[string]string)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) SetLabels(labels map[string]string) {\n\tif labels == nil {\n\t\tRemoveNestedField(u.Object, \"metadata\", \"labels\")\n\t\treturn\n\t}\n\tu.setNestedMap(labels, \"metadata\", \"labels\")\n}","line":{"from":399,"to":405}} {"id":100015079,"name":"GetAnnotations","signature":"func (u *Unstructured) GetAnnotations() map[string]string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) GetAnnotations() map[string]string {\n\tm, _, _ := NestedStringMap(u.Object, \"metadata\", \"annotations\")\n\treturn m\n}","line":{"from":407,"to":410}} {"id":100015080,"name":"SetAnnotations","signature":"func (u *Unstructured) SetAnnotations(annotations map[string]string)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) SetAnnotations(annotations map[string]string) {\n\tif annotations == nil {\n\t\tRemoveNestedField(u.Object, \"metadata\", \"annotations\")\n\t\treturn\n\t}\n\tu.setNestedMap(annotations, \"metadata\", \"annotations\")\n}","line":{"from":412,"to":418}} {"id":100015081,"name":"SetGroupVersionKind","signature":"func (u *Unstructured) SetGroupVersionKind(gvk schema.GroupVersionKind)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) SetGroupVersionKind(gvk schema.GroupVersionKind) {\n\tu.SetAPIVersion(gvk.GroupVersion().String())\n\tu.SetKind(gvk.Kind)\n}","line":{"from":420,"to":423}} {"id":100015082,"name":"GroupVersionKind","signature":"func (u *Unstructured) GroupVersionKind() schema.GroupVersionKind","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) GroupVersionKind() schema.GroupVersionKind {\n\tgv, err := schema.ParseGroupVersion(u.GetAPIVersion())\n\tif err != nil {\n\t\treturn schema.GroupVersionKind{}\n\t}\n\tgvk := gv.WithKind(u.GetKind())\n\treturn gvk\n}","line":{"from":425,"to":432}} {"id":100015083,"name":"GetFinalizers","signature":"func (u *Unstructured) GetFinalizers() []string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) GetFinalizers() []string {\n\tval, _, _ := NestedStringSlice(u.Object, \"metadata\", \"finalizers\")\n\treturn val\n}","line":{"from":434,"to":437}} {"id":100015084,"name":"SetFinalizers","signature":"func (u *Unstructured) SetFinalizers(finalizers []string)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) SetFinalizers(finalizers []string) {\n\tif finalizers == nil {\n\t\tRemoveNestedField(u.Object, \"metadata\", \"finalizers\")\n\t\treturn\n\t}\n\tu.setNestedStringSlice(finalizers, \"metadata\", \"finalizers\")\n}","line":{"from":439,"to":445}} {"id":100015085,"name":"GetManagedFields","signature":"func (u *Unstructured) GetManagedFields() []metav1.ManagedFieldsEntry","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) GetManagedFields() []metav1.ManagedFieldsEntry {\n\titems, found, err := NestedSlice(u.Object, \"metadata\", \"managedFields\")\n\tif !found || err != nil {\n\t\treturn nil\n\t}\n\tmanagedFields := []metav1.ManagedFieldsEntry{}\n\tfor _, item := range items {\n\t\tm, ok := item.(map[string]interface{})\n\t\tif !ok {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"unable to retrieve managedFields for object, item %v is not a map\", item))\n\t\t\treturn nil\n\t\t}\n\t\tout := metav1.ManagedFieldsEntry{}\n\t\tif err := runtime.DefaultUnstructuredConverter.FromUnstructured(m, \u0026out); err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"unable to retrieve managedFields for object: %v\", err))\n\t\t\treturn nil\n\t\t}\n\t\tmanagedFields = append(managedFields, out)\n\t}\n\treturn managedFields\n}","line":{"from":447,"to":467}} {"id":100015086,"name":"SetManagedFields","signature":"func (u *Unstructured) SetManagedFields(managedFields []metav1.ManagedFieldsEntry)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured.go","code":"func (u *Unstructured) SetManagedFields(managedFields []metav1.ManagedFieldsEntry) {\n\tif managedFields == nil {\n\t\tRemoveNestedField(u.Object, \"metadata\", \"managedFields\")\n\t\treturn\n\t}\n\titems := []interface{}{}\n\tfor _, managedFieldsEntry := range managedFields {\n\t\tout, err := runtime.DefaultUnstructuredConverter.ToUnstructured(\u0026managedFieldsEntry)\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"unable to set managedFields for object: %v\", err))\n\t\t\treturn\n\t\t}\n\t\titems = append(items, out)\n\t}\n\tu.setNestedSlice(items, \"metadata\", \"managedFields\")\n}","line":{"from":469,"to":484}} {"id":100015087,"name":"GetObjectKind","signature":"func (u *UnstructuredList) GetObjectKind() schema.ObjectKind { return u }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go","code":"func (u *UnstructuredList) GetObjectKind() schema.ObjectKind { return u }","line":{"from":42,"to":42}} {"id":100015088,"name":"IsList","signature":"func (u *UnstructuredList) IsList() bool { return true }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go","code":"func (u *UnstructuredList) IsList() bool { return true }","line":{"from":44,"to":44}} {"id":100015089,"name":"EachListItem","signature":"func (u *UnstructuredList) EachListItem(fn func(runtime.Object) error) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go","code":"func (u *UnstructuredList) EachListItem(fn func(runtime.Object) error) error {\n\tfor i := range u.Items {\n\t\tif err := fn(\u0026u.Items[i]); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":46,"to":53}} {"id":100015090,"name":"NewEmptyInstance","signature":"func (u *UnstructuredList) NewEmptyInstance() runtime.Unstructured","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go","code":"// NewEmptyInstance returns a new instance of the concrete type containing only kind/apiVersion and no other data.\n// This should be called instead of reflect.New() for unstructured types because the go type alone does not preserve kind/apiVersion info.\nfunc (u *UnstructuredList) NewEmptyInstance() runtime.Unstructured {\n\tout := new(UnstructuredList)\n\tif u != nil {\n\t\tout.SetGroupVersionKind(u.GroupVersionKind())\n\t}\n\treturn out\n}","line":{"from":55,"to":63}} {"id":100015091,"name":"UnstructuredContent","signature":"func (u *UnstructuredList) UnstructuredContent() map[string]interface{}","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go","code":"// UnstructuredContent returns a map contain an overlay of the Items field onto\n// the Object field. Items always overwrites overlay.\nfunc (u *UnstructuredList) UnstructuredContent() map[string]interface{} {\n\tout := make(map[string]interface{}, len(u.Object)+1)\n\n\t// shallow copy every property\n\tfor k, v := range u.Object {\n\t\tout[k] = v\n\t}\n\n\titems := make([]interface{}, len(u.Items))\n\tfor i, item := range u.Items {\n\t\titems[i] = item.UnstructuredContent()\n\t}\n\tout[\"items\"] = items\n\treturn out\n}","line":{"from":65,"to":81}} {"id":100015092,"name":"SetUnstructuredContent","signature":"func (obj *UnstructuredList) SetUnstructuredContent(content map[string]interface{})","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go","code":"// SetUnstructuredContent obeys the conventions of List and keeps Items and the items\n// array in sync. If items is not an array of objects in the incoming map, then any\n// mismatched item will be removed.\nfunc (obj *UnstructuredList) SetUnstructuredContent(content map[string]interface{}) {\n\tobj.Object = content\n\tif content == nil {\n\t\tobj.Items = nil\n\t\treturn\n\t}\n\titems, ok := obj.Object[\"items\"].([]interface{})\n\tif !ok || items == nil {\n\t\titems = []interface{}{}\n\t}\n\tunstructuredItems := make([]Unstructured, 0, len(items))\n\tnewItems := make([]interface{}, 0, len(items))\n\tfor _, item := range items {\n\t\to, ok := item.(map[string]interface{})\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tunstructuredItems = append(unstructuredItems, Unstructured{Object: o})\n\t\tnewItems = append(newItems, o)\n\t}\n\tobj.Items = unstructuredItems\n\tobj.Object[\"items\"] = newItems\n}","line":{"from":83,"to":108}} {"id":100015093,"name":"DeepCopy","signature":"func (u *UnstructuredList) DeepCopy() *UnstructuredList","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go","code":"func (u *UnstructuredList) DeepCopy() *UnstructuredList {\n\tif u == nil {\n\t\treturn nil\n\t}\n\tout := new(UnstructuredList)\n\t*out = *u\n\tout.Object = runtime.DeepCopyJSON(u.Object)\n\tout.Items = make([]Unstructured, len(u.Items))\n\tfor i := range u.Items {\n\t\tu.Items[i].DeepCopyInto(\u0026out.Items[i])\n\t}\n\treturn out\n}","line":{"from":110,"to":122}} {"id":100015094,"name":"MarshalJSON","signature":"func (u *UnstructuredList) MarshalJSON() ([]byte, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go","code":"// MarshalJSON ensures that the unstructured list object produces proper\n// JSON when passed to Go's standard JSON library.\nfunc (u *UnstructuredList) MarshalJSON() ([]byte, error) {\n\tvar buf bytes.Buffer\n\terr := UnstructuredJSONScheme.Encode(u, \u0026buf)\n\treturn buf.Bytes(), err\n}","line":{"from":124,"to":130}} {"id":100015095,"name":"UnmarshalJSON","signature":"func (u *UnstructuredList) UnmarshalJSON(b []byte) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go","code":"// UnmarshalJSON ensures that the unstructured list object properly\n// decodes JSON when passed to Go's standard JSON library.\nfunc (u *UnstructuredList) UnmarshalJSON(b []byte) error {\n\t_, _, err := UnstructuredJSONScheme.Decode(b, nil, u)\n\treturn err\n}","line":{"from":132,"to":137}} {"id":100015096,"name":"GetAPIVersion","signature":"func (u *UnstructuredList) GetAPIVersion() string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go","code":"func (u *UnstructuredList) GetAPIVersion() string {\n\treturn getNestedString(u.Object, \"apiVersion\")\n}","line":{"from":139,"to":141}} {"id":100015097,"name":"SetAPIVersion","signature":"func (u *UnstructuredList) SetAPIVersion(version string)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go","code":"func (u *UnstructuredList) SetAPIVersion(version string) {\n\tu.setNestedField(version, \"apiVersion\")\n}","line":{"from":143,"to":145}} {"id":100015098,"name":"GetKind","signature":"func (u *UnstructuredList) GetKind() string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go","code":"func (u *UnstructuredList) GetKind() string {\n\treturn getNestedString(u.Object, \"kind\")\n}","line":{"from":147,"to":149}} {"id":100015099,"name":"SetKind","signature":"func (u *UnstructuredList) SetKind(kind string)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go","code":"func (u *UnstructuredList) SetKind(kind string) {\n\tu.setNestedField(kind, \"kind\")\n}","line":{"from":151,"to":153}} {"id":100015100,"name":"GetResourceVersion","signature":"func (u *UnstructuredList) GetResourceVersion() string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go","code":"func (u *UnstructuredList) GetResourceVersion() string {\n\treturn getNestedString(u.Object, \"metadata\", \"resourceVersion\")\n}","line":{"from":155,"to":157}} {"id":100015101,"name":"SetResourceVersion","signature":"func (u *UnstructuredList) SetResourceVersion(version string)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go","code":"func (u *UnstructuredList) SetResourceVersion(version string) {\n\tu.setNestedField(version, \"metadata\", \"resourceVersion\")\n}","line":{"from":159,"to":161}} {"id":100015102,"name":"GetSelfLink","signature":"func (u *UnstructuredList) GetSelfLink() string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go","code":"func (u *UnstructuredList) GetSelfLink() string {\n\treturn getNestedString(u.Object, \"metadata\", \"selfLink\")\n}","line":{"from":163,"to":165}} {"id":100015103,"name":"SetSelfLink","signature":"func (u *UnstructuredList) SetSelfLink(selfLink string)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go","code":"func (u *UnstructuredList) SetSelfLink(selfLink string) {\n\tu.setNestedField(selfLink, \"metadata\", \"selfLink\")\n}","line":{"from":167,"to":169}} {"id":100015104,"name":"GetContinue","signature":"func (u *UnstructuredList) GetContinue() string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go","code":"func (u *UnstructuredList) GetContinue() string {\n\treturn getNestedString(u.Object, \"metadata\", \"continue\")\n}","line":{"from":171,"to":173}} {"id":100015105,"name":"SetContinue","signature":"func (u *UnstructuredList) SetContinue(c string)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go","code":"func (u *UnstructuredList) SetContinue(c string) {\n\tu.setNestedField(c, \"metadata\", \"continue\")\n}","line":{"from":175,"to":177}} {"id":100015106,"name":"GetRemainingItemCount","signature":"func (u *UnstructuredList) GetRemainingItemCount() *int64","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go","code":"func (u *UnstructuredList) GetRemainingItemCount() *int64 {\n\treturn getNestedInt64Pointer(u.Object, \"metadata\", \"remainingItemCount\")\n}","line":{"from":179,"to":181}} {"id":100015107,"name":"SetRemainingItemCount","signature":"func (u *UnstructuredList) SetRemainingItemCount(c *int64)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go","code":"func (u *UnstructuredList) SetRemainingItemCount(c *int64) {\n\tif c == nil {\n\t\tRemoveNestedField(u.Object, \"metadata\", \"remainingItemCount\")\n\t} else {\n\t\tu.setNestedField(*c, \"metadata\", \"remainingItemCount\")\n\t}\n}","line":{"from":183,"to":189}} {"id":100015108,"name":"SetGroupVersionKind","signature":"func (u *UnstructuredList) SetGroupVersionKind(gvk schema.GroupVersionKind)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go","code":"func (u *UnstructuredList) SetGroupVersionKind(gvk schema.GroupVersionKind) {\n\tu.SetAPIVersion(gvk.GroupVersion().String())\n\tu.SetKind(gvk.Kind)\n}","line":{"from":191,"to":194}} {"id":100015109,"name":"GroupVersionKind","signature":"func (u *UnstructuredList) GroupVersionKind() schema.GroupVersionKind","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go","code":"func (u *UnstructuredList) GroupVersionKind() schema.GroupVersionKind {\n\tgv, err := schema.ParseGroupVersion(u.GetAPIVersion())\n\tif err != nil {\n\t\treturn schema.GroupVersionKind{}\n\t}\n\tgvk := gv.WithKind(u.GetKind())\n\treturn gvk\n}","line":{"from":196,"to":203}} {"id":100015110,"name":"setNestedField","signature":"func (u *UnstructuredList) setNestedField(value interface{}, fields ...string)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list.go","code":"func (u *UnstructuredList) setNestedField(value interface{}, fields ...string) {\n\tif u.Object == nil {\n\t\tu.Object = make(map[string]interface{})\n\t}\n\tSetNestedField(u.Object, value, fields...)\n}","line":{"from":205,"to":210}} {"id":100015111,"name":"NewUnstructuredNegotiatedSerializer","signature":"func NewUnstructuredNegotiatedSerializer() runtime.NegotiatedSerializer","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructuredscheme/scheme.go","code":"// NewUnstructuredNegotiatedSerializer returns a simple, negotiated serializer\nfunc NewUnstructuredNegotiatedSerializer() runtime.NegotiatedSerializer {\n\treturn unstructuredNegotiatedSerializer{\n\t\tscheme: scheme,\n\t\ttyper: NewUnstructuredObjectTyper(),\n\t\tcreator: NewUnstructuredCreator(),\n\t}\n}","line":{"from":31,"to":38}} {"id":100015112,"name":"SupportedMediaTypes","signature":"func (s unstructuredNegotiatedSerializer) SupportedMediaTypes() []runtime.SerializerInfo","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructuredscheme/scheme.go","code":"func (s unstructuredNegotiatedSerializer) SupportedMediaTypes() []runtime.SerializerInfo {\n\treturn []runtime.SerializerInfo{\n\t\t{\n\t\t\tMediaType: \"application/json\",\n\t\t\tMediaTypeType: \"application\",\n\t\t\tMediaTypeSubType: \"json\",\n\t\t\tEncodesAsText: true,\n\t\t\tSerializer: json.NewSerializer(json.DefaultMetaFactory, s.creator, s.typer, false),\n\t\t\tPrettySerializer: json.NewSerializer(json.DefaultMetaFactory, s.creator, s.typer, true),\n\t\t\tStreamSerializer: \u0026runtime.StreamSerializerInfo{\n\t\t\t\tEncodesAsText: true,\n\t\t\t\tSerializer: json.NewSerializer(json.DefaultMetaFactory, s.creator, s.typer, false),\n\t\t\t\tFramer: json.Framer,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tMediaType: \"application/yaml\",\n\t\t\tMediaTypeType: \"application\",\n\t\t\tMediaTypeSubType: \"yaml\",\n\t\t\tEncodesAsText: true,\n\t\t\tSerializer: json.NewYAMLSerializer(json.DefaultMetaFactory, s.creator, s.typer),\n\t\t},\n\t}\n}","line":{"from":46,"to":69}} {"id":100015113,"name":"EncoderForVersion","signature":"func (s unstructuredNegotiatedSerializer) EncoderForVersion(encoder runtime.Encoder, gv runtime.GroupVersioner) runtime.Encoder","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructuredscheme/scheme.go","code":"func (s unstructuredNegotiatedSerializer) EncoderForVersion(encoder runtime.Encoder, gv runtime.GroupVersioner) runtime.Encoder {\n\treturn versioning.NewDefaultingCodecForScheme(s.scheme, encoder, nil, gv, nil)\n}","line":{"from":71,"to":73}} {"id":100015114,"name":"DecoderToVersion","signature":"func (s unstructuredNegotiatedSerializer) DecoderToVersion(decoder runtime.Decoder, gv runtime.GroupVersioner) runtime.Decoder","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructuredscheme/scheme.go","code":"func (s unstructuredNegotiatedSerializer) DecoderToVersion(decoder runtime.Decoder, gv runtime.GroupVersioner) runtime.Decoder {\n\treturn versioning.NewDefaultingCodecForScheme(s.scheme, nil, decoder, nil, gv)\n}","line":{"from":75,"to":77}} {"id":100015115,"name":"NewUnstructuredObjectTyper","signature":"func NewUnstructuredObjectTyper() runtime.ObjectTyper","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructuredscheme/scheme.go","code":"// NewUnstructuredObjectTyper returns an object typer that can deal with unstructured things\nfunc NewUnstructuredObjectTyper() runtime.ObjectTyper {\n\treturn unstructuredObjectTyper{}\n}","line":{"from":82,"to":85}} {"id":100015116,"name":"ObjectKinds","signature":"func (t unstructuredObjectTyper) ObjectKinds(obj runtime.Object) ([]schema.GroupVersionKind, bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructuredscheme/scheme.go","code":"func (t unstructuredObjectTyper) ObjectKinds(obj runtime.Object) ([]schema.GroupVersionKind, bool, error) {\n\t// Delegate for things other than Unstructured.\n\tif _, ok := obj.(runtime.Unstructured); !ok {\n\t\treturn nil, false, fmt.Errorf(\"cannot type %T\", obj)\n\t}\n\tgvk := obj.GetObjectKind().GroupVersionKind()\n\tif len(gvk.Kind) == 0 {\n\t\treturn nil, false, runtime.NewMissingKindErr(\"object has no kind field \")\n\t}\n\tif len(gvk.Version) == 0 {\n\t\treturn nil, false, runtime.NewMissingVersionErr(\"object has no apiVersion field\")\n\t}\n\n\treturn []schema.GroupVersionKind{obj.GetObjectKind().GroupVersionKind()}, false, nil\n}","line":{"from":87,"to":101}} {"id":100015117,"name":"Recognizes","signature":"func (t unstructuredObjectTyper) Recognizes(gvk schema.GroupVersionKind) bool","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructuredscheme/scheme.go","code":"func (t unstructuredObjectTyper) Recognizes(gvk schema.GroupVersionKind) bool {\n\treturn true\n}","line":{"from":103,"to":105}} {"id":100015118,"name":"NewUnstructuredCreator","signature":"func NewUnstructuredCreator() runtime.ObjectCreater","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructuredscheme/scheme.go","code":"// NewUnstructuredCreator returns a simple object creator that always returns an unstructured\nfunc NewUnstructuredCreator() runtime.ObjectCreater {\n\treturn unstructuredCreator{}\n}","line":{"from":109,"to":112}} {"id":100015119,"name":"New","signature":"func (c unstructuredCreator) New(kind schema.GroupVersionKind) (runtime.Object, error)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructuredscheme/scheme.go","code":"func (c unstructuredCreator) New(kind schema.GroupVersionKind) (runtime.Object, error) {\n\tret := \u0026unstructured.Unstructured{}\n\tret.SetGroupVersionKind(kind)\n\treturn ret, nil\n}","line":{"from":114,"to":118}} {"id":100015120,"name":"NewUnstructuredDefaulter","signature":"func NewUnstructuredDefaulter() runtime.ObjectDefaulter","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructuredscheme/scheme.go","code":"// NewUnstructuredDefaulter returns defaulter suitable for unstructured types that doesn't default anything\nfunc NewUnstructuredDefaulter() runtime.ObjectDefaulter {\n\treturn unstructuredDefaulter{}\n}","line":{"from":123,"to":126}} {"id":100015121,"name":"Default","signature":"func (d unstructuredDefaulter) Default(in runtime.Object)","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructuredscheme/scheme.go","code":"func (d unstructuredDefaulter) Default(in runtime.Object) {\n}","line":{"from":128,"to":129}} {"id":100015122,"name":"LabelSelectorHasInvalidLabelValue","signature":"func LabelSelectorHasInvalidLabelValue(ps *metav1.LabelSelector) bool","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go","code":"// LabelSelectorHasInvalidLabelValue returns true if the given selector contains an invalid label value in a match expression.\n// This is useful for determining whether AllowInvalidLabelValueInSelector should be set to true when validating an update\n// based on existing persisted invalid values.\nfunc LabelSelectorHasInvalidLabelValue(ps *metav1.LabelSelector) bool {\n\tif ps == nil {\n\t\treturn false\n\t}\n\tfor _, e := range ps.MatchExpressions {\n\t\tfor _, v := range e.Values {\n\t\t\tif len(validation.IsValidLabelValue(v)) \u003e 0 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":37,"to":52}} {"id":100015123,"name":"ValidateLabelSelector","signature":"func ValidateLabelSelector(ps *metav1.LabelSelector, opts LabelSelectorValidationOptions, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go","code":"// ValidateLabelSelector validate the LabelSelector according to the opts and returns any validation errors.\n// opts.AllowInvalidLabelValueInSelector is only expected to be set to true when required for backwards compatibility with existing invalid data.\nfunc ValidateLabelSelector(ps *metav1.LabelSelector, opts LabelSelectorValidationOptions, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif ps == nil {\n\t\treturn allErrs\n\t}\n\tallErrs = append(allErrs, ValidateLabels(ps.MatchLabels, fldPath.Child(\"matchLabels\"))...)\n\tfor i, expr := range ps.MatchExpressions {\n\t\tallErrs = append(allErrs, ValidateLabelSelectorRequirement(expr, opts, fldPath.Child(\"matchExpressions\").Index(i))...)\n\t}\n\treturn allErrs\n}","line":{"from":54,"to":66}} {"id":100015124,"name":"ValidateLabelSelectorRequirement","signature":"func ValidateLabelSelectorRequirement(sr metav1.LabelSelectorRequirement, opts LabelSelectorValidationOptions, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go","code":"// ValidateLabelSelectorRequirement validate the requirement according to the opts and returns any validation errors.\n// opts.AllowInvalidLabelValueInSelector is only expected to be set to true when required for backwards compatibility with existing invalid data.\nfunc ValidateLabelSelectorRequirement(sr metav1.LabelSelectorRequirement, opts LabelSelectorValidationOptions, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tswitch sr.Operator {\n\tcase metav1.LabelSelectorOpIn, metav1.LabelSelectorOpNotIn:\n\t\tif len(sr.Values) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"values\"), \"must be specified when `operator` is 'In' or 'NotIn'\"))\n\t\t}\n\tcase metav1.LabelSelectorOpExists, metav1.LabelSelectorOpDoesNotExist:\n\t\tif len(sr.Values) \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"values\"), \"may not be specified when `operator` is 'Exists' or 'DoesNotExist'\"))\n\t\t}\n\tdefault:\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"operator\"), sr.Operator, \"not a valid selector operator\"))\n\t}\n\tallErrs = append(allErrs, ValidateLabelName(sr.Key, fldPath.Child(\"key\"))...)\n\tif !opts.AllowInvalidLabelValueInSelector {\n\t\tfor valueIndex, value := range sr.Values {\n\t\t\tfor _, msg := range validation.IsValidLabelValue(value) {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"values\").Index(valueIndex), value, msg))\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":68,"to":93}} {"id":100015125,"name":"ValidateLabelName","signature":"func ValidateLabelName(labelName string, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go","code":"// ValidateLabelName validates that the label name is correctly defined.\nfunc ValidateLabelName(labelName string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor _, msg := range validation.IsQualifiedName(labelName) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, labelName, msg))\n\t}\n\treturn allErrs\n}","line":{"from":95,"to":102}} {"id":100015126,"name":"ValidateLabels","signature":"func ValidateLabels(labels map[string]string, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go","code":"// ValidateLabels validates that a set of labels are correctly defined.\nfunc ValidateLabels(labels map[string]string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor k, v := range labels {\n\t\tallErrs = append(allErrs, ValidateLabelName(k, fldPath)...)\n\t\tfor _, msg := range validation.IsValidLabelValue(v) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, v, msg))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":104,"to":114}} {"id":100015127,"name":"ValidateDeleteOptions","signature":"func ValidateDeleteOptions(options *metav1.DeleteOptions) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go","code":"func ValidateDeleteOptions(options *metav1.DeleteOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\t//lint:file-ignore SA1019 Keep validation for deprecated OrphanDependents option until it's being removed\n\tif options.OrphanDependents != nil \u0026\u0026 options.PropagationPolicy != nil {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"propagationPolicy\"), options.PropagationPolicy, \"orphanDependents and deletionPropagation cannot be both set\"))\n\t}\n\tif options.PropagationPolicy != nil \u0026\u0026\n\t\t*options.PropagationPolicy != metav1.DeletePropagationForeground \u0026\u0026\n\t\t*options.PropagationPolicy != metav1.DeletePropagationBackground \u0026\u0026\n\t\t*options.PropagationPolicy != metav1.DeletePropagationOrphan {\n\t\tallErrs = append(allErrs, field.NotSupported(field.NewPath(\"propagationPolicy\"), options.PropagationPolicy, []string{string(metav1.DeletePropagationForeground), string(metav1.DeletePropagationBackground), string(metav1.DeletePropagationOrphan), \"nil\"}))\n\t}\n\tallErrs = append(allErrs, ValidateDryRun(field.NewPath(\"dryRun\"), options.DryRun)...)\n\treturn allErrs\n}","line":{"from":116,"to":130}} {"id":100015128,"name":"ValidateCreateOptions","signature":"func ValidateCreateOptions(options *metav1.CreateOptions) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go","code":"func ValidateCreateOptions(options *metav1.CreateOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, ValidateFieldManager(options.FieldManager, field.NewPath(\"fieldManager\"))...)\n\tallErrs = append(allErrs, ValidateDryRun(field.NewPath(\"dryRun\"), options.DryRun)...)\n\tallErrs = append(allErrs, ValidateFieldValidation(field.NewPath(\"fieldValidation\"), options.FieldValidation)...)\n\treturn allErrs\n}","line":{"from":132,"to":138}} {"id":100015129,"name":"ValidateUpdateOptions","signature":"func ValidateUpdateOptions(options *metav1.UpdateOptions) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go","code":"func ValidateUpdateOptions(options *metav1.UpdateOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tallErrs = append(allErrs, ValidateFieldManager(options.FieldManager, field.NewPath(\"fieldManager\"))...)\n\tallErrs = append(allErrs, ValidateDryRun(field.NewPath(\"dryRun\"), options.DryRun)...)\n\tallErrs = append(allErrs, ValidateFieldValidation(field.NewPath(\"fieldValidation\"), options.FieldValidation)...)\n\treturn allErrs\n}","line":{"from":140,"to":146}} {"id":100015130,"name":"ValidatePatchOptions","signature":"func ValidatePatchOptions(options *metav1.PatchOptions, patchType types.PatchType) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go","code":"func ValidatePatchOptions(options *metav1.PatchOptions, patchType types.PatchType) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif patchType != types.ApplyPatchType {\n\t\tif options.Force != nil {\n\t\t\tallErrs = append(allErrs, field.Forbidden(field.NewPath(\"force\"), \"may not be specified for non-apply patch\"))\n\t\t}\n\t} else {\n\t\tif options.FieldManager == \"\" {\n\t\t\t// This field is defaulted to \"kubectl\" by kubectl, but HAS TO be explicitly set by controllers.\n\t\t\tallErrs = append(allErrs, field.Required(field.NewPath(\"fieldManager\"), \"is required for apply patch\"))\n\t\t}\n\t}\n\tallErrs = append(allErrs, ValidateFieldManager(options.FieldManager, field.NewPath(\"fieldManager\"))...)\n\tallErrs = append(allErrs, ValidateDryRun(field.NewPath(\"dryRun\"), options.DryRun)...)\n\tallErrs = append(allErrs, ValidateFieldValidation(field.NewPath(\"fieldValidation\"), options.FieldValidation)...)\n\treturn allErrs\n}","line":{"from":148,"to":164}} {"id":100015131,"name":"ValidateFieldManager","signature":"func ValidateFieldManager(fieldManager string, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go","code":"// ValidateFieldManager valides that the fieldManager is the proper length and\n// only has printable characters.\nfunc ValidateFieldManager(fieldManager string, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\t// the field can not be set as a `*string`, so a empty string (\"\") is\n\t// considered as not set and is defaulted by the rest of the process\n\t// (unless apply is used, in which case it is required).\n\tif len(fieldManager) \u003e FieldManagerMaxLength {\n\t\tallErrs = append(allErrs, field.TooLong(fldPath, fieldManager, FieldManagerMaxLength))\n\t}\n\t// Verify that all characters are printable.\n\tfor i, r := range fieldManager {\n\t\tif !unicode.IsPrint(r) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, fieldManager, fmt.Sprintf(\"invalid character %#U (at position %d)\", r, i)))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":168,"to":186}} {"id":100015132,"name":"ValidateDryRun","signature":"func ValidateDryRun(fldPath *field.Path, dryRun []string) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go","code":"// ValidateDryRun validates that a dryRun query param only contains allowed values.\nfunc ValidateDryRun(fldPath *field.Path, dryRun []string) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif !allowedDryRunValues.HasAll(dryRun...) {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath, dryRun, allowedDryRunValues.List()))\n\t}\n\treturn allErrs\n}","line":{"from":190,"to":197}} {"id":100015133,"name":"ValidateFieldValidation","signature":"func ValidateFieldValidation(fldPath *field.Path, fieldValidation string) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go","code":"// ValidateFieldValidation validates that a fieldValidation query param only contains allowed values.\nfunc ValidateFieldValidation(fldPath *field.Path, fieldValidation string) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif !allowedFieldValidationValues.Has(fieldValidation) {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath, fieldValidation, allowedFieldValidationValues.List()))\n\t}\n\treturn allErrs\n\n}","line":{"from":201,"to":209}} {"id":100015134,"name":"ValidateTableOptions","signature":"func ValidateTableOptions(opts *metav1.TableOptions) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go","code":"// ValidateTableOptions returns any invalid flags on TableOptions.\nfunc ValidateTableOptions(opts *metav1.TableOptions) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tswitch opts.IncludeObject {\n\tcase metav1.IncludeMetadata, metav1.IncludeNone, metav1.IncludeObject, \"\":\n\tdefault:\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"includeObject\"), opts.IncludeObject, \"must be 'Metadata', 'Object', 'None', or empty\"))\n\t}\n\treturn allErrs\n}","line":{"from":213,"to":222}} {"id":100015135,"name":"ValidateManagedFields","signature":"func ValidateManagedFields(fieldsList []metav1.ManagedFieldsEntry, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go","code":"func ValidateManagedFields(fieldsList []metav1.ManagedFieldsEntry, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tfor i, fields := range fieldsList {\n\t\tfldPath := fldPath.Index(i)\n\t\tswitch fields.Operation {\n\t\tcase metav1.ManagedFieldsOperationApply, metav1.ManagedFieldsOperationUpdate:\n\t\tdefault:\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"operation\"), fields.Operation, \"must be `Apply` or `Update`\"))\n\t\t}\n\t\tif len(fields.FieldsType) \u003e 0 \u0026\u0026 fields.FieldsType != \"FieldsV1\" {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"fieldsType\"), fields.FieldsType, \"must be `FieldsV1`\"))\n\t\t}\n\t\tallErrs = append(allErrs, ValidateFieldManager(fields.Manager, fldPath.Child(\"manager\"))...)\n\n\t\tif len(fields.Subresource) \u003e MaxSubresourceNameLength {\n\t\t\tallErrs = append(allErrs, field.TooLong(fldPath.Child(\"subresource\"), fields.Subresource, MaxSubresourceNameLength))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":226,"to":245}} {"id":100015136,"name":"ValidateConditions","signature":"func ValidateConditions(conditions []metav1.Condition, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go","code":"func ValidateConditions(conditions []metav1.Condition, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\n\tconditionTypeToFirstIndex := map[string]int{}\n\tfor i, condition := range conditions {\n\t\tif _, ok := conditionTypeToFirstIndex[condition.Type]; ok {\n\t\t\tallErrs = append(allErrs, field.Duplicate(fldPath.Index(i).Child(\"type\"), condition.Type))\n\t\t} else {\n\t\t\tconditionTypeToFirstIndex[condition.Type] = i\n\t\t}\n\n\t\tallErrs = append(allErrs, ValidateCondition(condition, fldPath.Index(i))...)\n\t}\n\n\treturn allErrs\n}","line":{"from":247,"to":262}} {"id":100015137,"name":"ValidateCondition","signature":"func ValidateCondition(condition metav1.Condition, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go","code":"func ValidateCondition(condition metav1.Condition, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\n\t// type is set and is a valid format\n\tallErrs = append(allErrs, ValidateLabelName(condition.Type, fldPath.Child(\"type\"))...)\n\n\t// status is set and is an accepted value\n\tif !validConditionStatuses.Has(string(condition.Status)) {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"status\"), condition.Status, validConditionStatuses.List()))\n\t}\n\n\tif condition.ObservedGeneration \u003c 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"observedGeneration\"), condition.ObservedGeneration, \"must be greater than or equal to zero\"))\n\t}\n\n\tif condition.LastTransitionTime.IsZero() {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"lastTransitionTime\"), \"must be set\"))\n\t}\n\n\tif len(condition.Reason) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"reason\"), \"must be set\"))\n\t} else {\n\t\tfor _, currErr := range isValidConditionReason(condition.Reason) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"reason\"), condition.Reason, currErr))\n\t\t}\n\t\tif len(condition.Reason) \u003e maxReasonLen {\n\t\t\tallErrs = append(allErrs, field.TooLong(fldPath.Child(\"reason\"), condition.Reason, maxReasonLen))\n\t\t}\n\t}\n\n\tif len(condition.Message) \u003e maxMessageLen {\n\t\tallErrs = append(allErrs, field.TooLong(fldPath.Child(\"message\"), condition.Message, maxMessageLen))\n\t}\n\n\treturn allErrs\n}","line":{"from":272,"to":307}} {"id":100015138,"name":"isValidConditionReason","signature":"func isValidConditionReason(value string) []string","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation.go","code":"// isValidConditionReason tests for a string that conforms to rules for condition reasons. This checks the format, but not the length.\nfunc isValidConditionReason(value string) []string {\n\tif !conditionReasonRegexp.MatchString(value) {\n\t\treturn []string{validation.RegexError(conditionReasonErrMsg, conditionReasonFmt, \"my_name\", \"MY_NAME\", \"MyName\", \"ReasonA,ReasonB\", \"ReasonA:ReasonB\")}\n\t}\n\treturn nil\n}","line":{"from":314,"to":320}} {"id":100015139,"name":"Convert_watch_Event_To_v1_WatchEvent","signature":"func Convert_watch_Event_To_v1_WatchEvent(in *watch.Event, out *WatchEvent, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/watch.go","code":"func Convert_watch_Event_To_v1_WatchEvent(in *watch.Event, out *WatchEvent, s conversion.Scope) error {\n\tout.Type = string(in.Type)\n\tswitch t := in.Object.(type) {\n\tcase *runtime.Unknown:\n\t\t// TODO: handle other fields on Unknown and detect type\n\t\tout.Object.Raw = t.Raw\n\tcase nil:\n\tdefault:\n\t\tout.Object.Object = in.Object\n\t}\n\treturn nil\n}","line":{"from":42,"to":53}} {"id":100015140,"name":"Convert_v1_InternalEvent_To_v1_WatchEvent","signature":"func Convert_v1_InternalEvent_To_v1_WatchEvent(in *InternalEvent, out *WatchEvent, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/watch.go","code":"func Convert_v1_InternalEvent_To_v1_WatchEvent(in *InternalEvent, out *WatchEvent, s conversion.Scope) error {\n\treturn Convert_watch_Event_To_v1_WatchEvent((*watch.Event)(in), out, s)\n}","line":{"from":55,"to":57}} {"id":100015141,"name":"Convert_v1_WatchEvent_To_watch_Event","signature":"func Convert_v1_WatchEvent_To_watch_Event(in *WatchEvent, out *watch.Event, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/watch.go","code":"func Convert_v1_WatchEvent_To_watch_Event(in *WatchEvent, out *watch.Event, s conversion.Scope) error {\n\tout.Type = watch.EventType(in.Type)\n\tif in.Object.Object != nil {\n\t\tout.Object = in.Object.Object\n\t} else if in.Object.Raw != nil {\n\t\t// TODO: handle other fields on Unknown and detect type\n\t\tout.Object = \u0026runtime.Unknown{\n\t\t\tRaw: in.Object.Raw,\n\t\t\tContentType: runtime.ContentTypeJSON,\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":59,"to":71}} {"id":100015142,"name":"Convert_v1_WatchEvent_To_v1_InternalEvent","signature":"func Convert_v1_WatchEvent_To_v1_InternalEvent(in *WatchEvent, out *InternalEvent, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/watch.go","code":"func Convert_v1_WatchEvent_To_v1_InternalEvent(in *WatchEvent, out *InternalEvent, s conversion.Scope) error {\n\treturn Convert_v1_WatchEvent_To_watch_Event(in, (*watch.Event)(out), s)\n}","line":{"from":73,"to":75}} {"id":100015143,"name":"GetObjectKind","signature":"func (e *InternalEvent) GetObjectKind() schema.ObjectKind { return schema.EmptyObjectKind }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/watch.go","code":"func (e *InternalEvent) GetObjectKind() schema.ObjectKind { return schema.EmptyObjectKind }","line":{"from":81,"to":81}} {"id":100015144,"name":"GetObjectKind","signature":"func (e *WatchEvent) GetObjectKind() schema.ObjectKind { return schema.EmptyObjectKind }","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/watch.go","code":"func (e *WatchEvent) GetObjectKind() schema.ObjectKind { return schema.EmptyObjectKind }","line":{"from":82,"to":82}} {"id":100015145,"name":"DeepCopyObject","signature":"func (e *InternalEvent) DeepCopyObject() runtime.Object","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/watch.go","code":"func (e *InternalEvent) DeepCopyObject() runtime.Object {\n\tif c := e.DeepCopy(); c != nil {\n\t\treturn c\n\t} else {\n\t\treturn nil\n\t}\n}","line":{"from":83,"to":89}} {"id":100015146,"name":"Convert_Slice_string_To_v1beta1_IncludeObjectPolicy","signature":"func Convert_Slice_string_To_v1beta1_IncludeObjectPolicy(in *[]string, out *IncludeObjectPolicy, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1beta1/conversion.go","code":"// Convert_Slice_string_To_v1beta1_IncludeObjectPolicy allows converting a URL query parameter value\nfunc Convert_Slice_string_To_v1beta1_IncludeObjectPolicy(in *[]string, out *IncludeObjectPolicy, s conversion.Scope) error {\n\tif len(*in) \u003e 0 {\n\t\t*out = IncludeObjectPolicy((*in)[0])\n\t}\n\treturn nil\n}","line":{"from":26,"to":32}} {"id":100015147,"name":"Convert_v1beta1_PartialObjectMetadataList_To_v1_PartialObjectMetadataList","signature":"func Convert_v1beta1_PartialObjectMetadataList_To_v1_PartialObjectMetadataList(in *PartialObjectMetadataList, out *v1.PartialObjectMetadataList, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1beta1/conversion.go","code":"// Convert_v1beta1_PartialObjectMetadataList_To_v1_PartialObjectMetadataList allows converting PartialObjectMetadataList between versions\nfunc Convert_v1beta1_PartialObjectMetadataList_To_v1_PartialObjectMetadataList(in *PartialObjectMetadataList, out *v1.PartialObjectMetadataList, s conversion.Scope) error {\n\tout.ListMeta = in.ListMeta\n\tout.Items = *(*[]v1.PartialObjectMetadata)(unsafe.Pointer(\u0026in.Items))\n\treturn nil\n}","line":{"from":34,"to":39}} {"id":100015148,"name":"Convert_v1_PartialObjectMetadataList_To_v1beta1_PartialObjectMetadataList","signature":"func Convert_v1_PartialObjectMetadataList_To_v1beta1_PartialObjectMetadataList(in *v1.PartialObjectMetadataList, out *PartialObjectMetadataList, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1beta1/conversion.go","code":"// Convert_v1_PartialObjectMetadataList_To_v1beta1_PartialObjectMetadataList allows converting PartialObjectMetadataList between versions\nfunc Convert_v1_PartialObjectMetadataList_To_v1beta1_PartialObjectMetadataList(in *v1.PartialObjectMetadataList, out *PartialObjectMetadataList, s conversion.Scope) error {\n\tout.ListMeta = in.ListMeta\n\tout.Items = *(*[]v1.PartialObjectMetadata)(unsafe.Pointer(\u0026in.Items))\n\treturn nil\n}","line":{"from":41,"to":46}} {"id":100015149,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1beta1/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":32,"to":35}} {"id":100015150,"name":"AddMetaToScheme","signature":"func AddMetaToScheme(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1beta1/register.go","code":"// AddMetaToScheme registers base meta types into schemas.\nfunc AddMetaToScheme(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Table{},\n\t\t\u0026TableOptions{},\n\t\t\u0026PartialObjectMetadata{},\n\t\t\u0026PartialObjectMetadataList{},\n\t)\n\n\treturn nil\n}","line":{"from":37,"to":47}} {"id":100015151,"name":"RegisterConversions","signature":"func RegisterConversions(s *runtime.Scheme) error","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1beta1/register.go","code":"// RegisterConversions adds conversion functions to the given scheme.\nfunc RegisterConversions(s *runtime.Scheme) error {\n\tif err := s.AddGeneratedConversionFunc((*PartialObjectMetadataList)(nil), (*v1.PartialObjectMetadataList)(nil), func(a, b interface{}, scope conversion.Scope) error {\n\t\treturn Convert_v1beta1_PartialObjectMetadataList_To_v1_PartialObjectMetadataList(a.(*PartialObjectMetadataList), b.(*v1.PartialObjectMetadataList), scope)\n\t}); err != nil {\n\t\treturn err\n\t}\n\tif err := s.AddGeneratedConversionFunc((*v1.PartialObjectMetadataList)(nil), (*PartialObjectMetadataList)(nil), func(a, b interface{}, scope conversion.Scope) error {\n\t\treturn Convert_v1_PartialObjectMetadataList_To_v1beta1_PartialObjectMetadataList(a.(*v1.PartialObjectMetadataList), b.(*PartialObjectMetadataList), scope)\n\t}); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":49,"to":62}} {"id":100015152,"name":"ValidateTableOptions","signature":"func ValidateTableOptions(opts *metav1.TableOptions) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1beta1/validation/validation.go","code":"// ValidateTableOptions returns any invalid flags on TableOptions.\nfunc ValidateTableOptions(opts *metav1.TableOptions) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tswitch opts.IncludeObject {\n\tcase metav1.IncludeMetadata, metav1.IncludeNone, metav1.IncludeObject, \"\":\n\tdefault:\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"includeObject\"), opts.IncludeObject, \"must be 'Metadata', 'Object', 'None', or empty\"))\n\t}\n\treturn allErrs\n}","line":{"from":24,"to":33}} {"id":100015153,"name":"NewConverter","signature":"func NewConverter(NameFunc) *Converter","file":"staging/src/k8s.io/apimachinery/pkg/conversion/converter.go","code":"// NewConverter creates a new Converter object.\n// Arg NameFunc is just for backward compatibility.\nfunc NewConverter(NameFunc) *Converter {\n\tc := \u0026Converter{\n\t\tconversionFuncs: NewConversionFuncs(),\n\t\tgeneratedConversionFuncs: NewConversionFuncs(),\n\t\tignoredUntypedConversions: make(map[typePair]struct{}),\n\t}\n\tc.RegisterUntypedConversionFunc(\n\t\t(*[]byte)(nil), (*[]byte)(nil),\n\t\tfunc(a, b interface{}, s Scope) error {\n\t\t\treturn Convert_Slice_byte_To_Slice_byte(a.(*[]byte), b.(*[]byte), s)\n\t\t},\n\t)\n\treturn c\n}","line":{"from":50,"to":65}} {"id":100015154,"name":"WithConversions","signature":"func (c *Converter) WithConversions(fns ConversionFuncs) *Converter","file":"staging/src/k8s.io/apimachinery/pkg/conversion/converter.go","code":"// WithConversions returns a Converter that is a copy of c but with the additional\n// fns merged on top.\nfunc (c *Converter) WithConversions(fns ConversionFuncs) *Converter {\n\tcopied := *c\n\tcopied.conversionFuncs = c.conversionFuncs.Merge(fns)\n\treturn \u0026copied\n}","line":{"from":67,"to":73}} {"id":100015155,"name":"DefaultMeta","signature":"func (c *Converter) DefaultMeta(t reflect.Type) *Meta","file":"staging/src/k8s.io/apimachinery/pkg/conversion/converter.go","code":"// DefaultMeta returns meta for a given type.\nfunc (c *Converter) DefaultMeta(t reflect.Type) *Meta {\n\treturn \u0026Meta{}\n}","line":{"from":75,"to":78}} {"id":100015156,"name":"Convert_Slice_byte_To_Slice_byte","signature":"func Convert_Slice_byte_To_Slice_byte(in *[]byte, out *[]byte, s Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/conversion/converter.go","code":"// Convert_Slice_byte_To_Slice_byte prevents recursing into every byte\nfunc Convert_Slice_byte_To_Slice_byte(in *[]byte, out *[]byte, s Scope) error {\n\tif *in == nil {\n\t\t*out = nil\n\t\treturn nil\n\t}\n\t*out = make([]byte, len(*in))\n\tcopy(*out, *in)\n\treturn nil\n}","line":{"from":80,"to":89}} {"id":100015157,"name":"NewConversionFuncs","signature":"func NewConversionFuncs() ConversionFuncs","file":"staging/src/k8s.io/apimachinery/pkg/conversion/converter.go","code":"func NewConversionFuncs() ConversionFuncs {\n\treturn ConversionFuncs{\n\t\tuntyped: make(map[typePair]ConversionFunc),\n\t}\n}","line":{"from":103,"to":107}} {"id":100015158,"name":"AddUntyped","signature":"func (c ConversionFuncs) AddUntyped(a, b interface{}, fn ConversionFunc) error","file":"staging/src/k8s.io/apimachinery/pkg/conversion/converter.go","code":"// AddUntyped adds the provided conversion function to the lookup table for the types that are\n// supplied as a and b. a and b must be pointers or an error is returned. This method overwrites\n// previously defined functions.\nfunc (c ConversionFuncs) AddUntyped(a, b interface{}, fn ConversionFunc) error {\n\ttA, tB := reflect.TypeOf(a), reflect.TypeOf(b)\n\tif tA.Kind() != reflect.Pointer {\n\t\treturn fmt.Errorf(\"the type %T must be a pointer to register as an untyped conversion\", a)\n\t}\n\tif tB.Kind() != reflect.Pointer {\n\t\treturn fmt.Errorf(\"the type %T must be a pointer to register as an untyped conversion\", b)\n\t}\n\tc.untyped[typePair{tA, tB}] = fn\n\treturn nil\n}","line":{"from":113,"to":126}} {"id":100015159,"name":"Merge","signature":"func (c ConversionFuncs) Merge(other ConversionFuncs) ConversionFuncs","file":"staging/src/k8s.io/apimachinery/pkg/conversion/converter.go","code":"// Merge returns a new ConversionFuncs that contains all conversions from\n// both other and c, with other conversions taking precedence.\nfunc (c ConversionFuncs) Merge(other ConversionFuncs) ConversionFuncs {\n\tmerged := NewConversionFuncs()\n\tfor k, v := range c.untyped {\n\t\tmerged.untyped[k] = v\n\t}\n\tfor k, v := range other.untyped {\n\t\tmerged.untyped[k] = v\n\t}\n\treturn merged\n}","line":{"from":128,"to":139}} {"id":100015160,"name":"Convert","signature":"func (s *scope) Convert(src, dest interface{}) error","file":"staging/src/k8s.io/apimachinery/pkg/conversion/converter.go","code":"// Convert continues a conversion.\nfunc (s *scope) Convert(src, dest interface{}) error {\n\treturn s.converter.Convert(src, dest, s.meta)\n}","line":{"from":153,"to":156}} {"id":100015161,"name":"Meta","signature":"func (s *scope) Meta() *Meta","file":"staging/src/k8s.io/apimachinery/pkg/conversion/converter.go","code":"// Meta returns the meta object that was originally passed to Convert.\nfunc (s *scope) Meta() *Meta {\n\treturn s.meta\n}","line":{"from":158,"to":161}} {"id":100015162,"name":"RegisterUntypedConversionFunc","signature":"func (c *Converter) RegisterUntypedConversionFunc(a, b interface{}, fn ConversionFunc) error","file":"staging/src/k8s.io/apimachinery/pkg/conversion/converter.go","code":"// RegisterUntypedConversionFunc registers a function that converts between a and b by passing objects of those\n// types to the provided function. The function *must* accept objects of a and b - this machinery will not enforce\n// any other guarantee.\nfunc (c *Converter) RegisterUntypedConversionFunc(a, b interface{}, fn ConversionFunc) error {\n\treturn c.conversionFuncs.AddUntyped(a, b, fn)\n}","line":{"from":163,"to":168}} {"id":100015163,"name":"RegisterGeneratedUntypedConversionFunc","signature":"func (c *Converter) RegisterGeneratedUntypedConversionFunc(a, b interface{}, fn ConversionFunc) error","file":"staging/src/k8s.io/apimachinery/pkg/conversion/converter.go","code":"// RegisterGeneratedUntypedConversionFunc registers a function that converts between a and b by passing objects of those\n// types to the provided function. The function *must* accept objects of a and b - this machinery will not enforce\n// any other guarantee.\nfunc (c *Converter) RegisterGeneratedUntypedConversionFunc(a, b interface{}, fn ConversionFunc) error {\n\treturn c.generatedConversionFuncs.AddUntyped(a, b, fn)\n}","line":{"from":170,"to":175}} {"id":100015164,"name":"RegisterIgnoredConversion","signature":"func (c *Converter) RegisterIgnoredConversion(from, to interface{}) error","file":"staging/src/k8s.io/apimachinery/pkg/conversion/converter.go","code":"// RegisterIgnoredConversion registers a \"no-op\" for conversion, where any requested\n// conversion between from and to is ignored.\nfunc (c *Converter) RegisterIgnoredConversion(from, to interface{}) error {\n\ttypeFrom := reflect.TypeOf(from)\n\ttypeTo := reflect.TypeOf(to)\n\tif typeFrom.Kind() != reflect.Pointer {\n\t\treturn fmt.Errorf(\"expected pointer arg for 'from' param 0, got: %v\", typeFrom)\n\t}\n\tif typeTo.Kind() != reflect.Pointer {\n\t\treturn fmt.Errorf(\"expected pointer arg for 'to' param 1, got: %v\", typeTo)\n\t}\n\tc.ignoredUntypedConversions[typePair{typeFrom, typeTo}] = struct{}{}\n\treturn nil\n}","line":{"from":177,"to":190}} {"id":100015165,"name":"Convert","signature":"func (c *Converter) Convert(src, dest interface{}, meta *Meta) error","file":"staging/src/k8s.io/apimachinery/pkg/conversion/converter.go","code":"// Convert will translate src to dest if it knows how. Both must be pointers.\n// If no conversion func is registered and the default copying mechanism\n// doesn't work on this type pair, an error will be returned.\n// 'meta' is given to allow you to pass information to conversion functions,\n// it is not used by Convert() other than storing it in the scope.\n// Not safe for objects with cyclic references!\nfunc (c *Converter) Convert(src, dest interface{}, meta *Meta) error {\n\tpair := typePair{reflect.TypeOf(src), reflect.TypeOf(dest)}\n\tscope := \u0026scope{\n\t\tconverter: c,\n\t\tmeta: meta,\n\t}\n\n\t// ignore conversions of this type\n\tif _, ok := c.ignoredUntypedConversions[pair]; ok {\n\t\treturn nil\n\t}\n\tif fn, ok := c.conversionFuncs.untyped[pair]; ok {\n\t\treturn fn(src, dest, scope)\n\t}\n\tif fn, ok := c.generatedConversionFuncs.untyped[pair]; ok {\n\t\treturn fn(src, dest, scope)\n\t}\n\n\tdv, err := EnforcePtr(dest)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsv, err := EnforcePtr(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn fmt.Errorf(\"converting (%s) to (%s): unknown conversion\", sv.Type(), dv.Type())\n}","line":{"from":192,"to":225}} {"id":100015166,"name":"EqualitiesOrDie","signature":"func EqualitiesOrDie(funcs ...interface{}) Equalities","file":"staging/src/k8s.io/apimachinery/pkg/conversion/deep_equal.go","code":"// For convenience, panics on errors\nfunc EqualitiesOrDie(funcs ...interface{}) Equalities {\n\te := Equalities{reflect.Equalities{}}\n\tif err := e.AddFuncs(funcs...); err != nil {\n\t\tpanic(err)\n\t}\n\treturn e\n}","line":{"from":29,"to":36}} {"id":100015167,"name":"Copy","signature":"func (e Equalities) Copy() Equalities","file":"staging/src/k8s.io/apimachinery/pkg/conversion/deep_equal.go","code":"// Performs a shallow copy of the equalities map\nfunc (e Equalities) Copy() Equalities {\n\tresult := Equalities{reflect.Equalities{}}\n\n\tfor key, value := range e.Equalities {\n\t\tresult.Equalities[key] = value\n\t}\n\n\treturn result\n}","line":{"from":38,"to":47}} {"id":100015168,"name":"EnforcePtr","signature":"func EnforcePtr(obj interface{}) (reflect.Value, error)","file":"staging/src/k8s.io/apimachinery/pkg/conversion/helper.go","code":"// EnforcePtr ensures that obj is a pointer of some sort. Returns a reflect.Value\n// of the dereferenced pointer, ensuring that it is settable/addressable.\n// Returns an error if this is not possible.\nfunc EnforcePtr(obj interface{}) (reflect.Value, error) {\n\tv := reflect.ValueOf(obj)\n\tif v.Kind() != reflect.Pointer {\n\t\tif v.Kind() == reflect.Invalid {\n\t\t\treturn reflect.Value{}, fmt.Errorf(\"expected pointer, but got invalid kind\")\n\t\t}\n\t\treturn reflect.Value{}, fmt.Errorf(\"expected pointer, but got %v type\", v.Type())\n\t}\n\tif v.IsNil() {\n\t\treturn reflect.Value{}, fmt.Errorf(\"expected pointer, but got nil\")\n\t}\n\treturn v.Elem(), nil\n}","line":{"from":24,"to":39}} {"id":100015169,"name":"jsonTag","signature":"func jsonTag(field reflect.StructField) (string, bool)","file":"staging/src/k8s.io/apimachinery/pkg/conversion/queryparams/convert.go","code":"func jsonTag(field reflect.StructField) (string, bool) {\n\tstructTag := field.Tag.Get(\"json\")\n\tif len(structTag) == 0 {\n\t\treturn \"\", false\n\t}\n\tparts := strings.Split(structTag, \",\")\n\ttag := parts[0]\n\tif tag == \"-\" {\n\t\ttag = \"\"\n\t}\n\tomitempty := false\n\tparts = parts[1:]\n\tfor _, part := range parts {\n\t\tif part == \"omitempty\" {\n\t\t\tomitempty = true\n\t\t\tbreak\n\t\t}\n\t}\n\treturn tag, omitempty\n}","line":{"from":36,"to":55}} {"id":100015170,"name":"isPointerKind","signature":"func isPointerKind(kind reflect.Kind) bool","file":"staging/src/k8s.io/apimachinery/pkg/conversion/queryparams/convert.go","code":"func isPointerKind(kind reflect.Kind) bool {\n\treturn kind == reflect.Pointer\n}","line":{"from":57,"to":59}} {"id":100015171,"name":"isStructKind","signature":"func isStructKind(kind reflect.Kind) bool","file":"staging/src/k8s.io/apimachinery/pkg/conversion/queryparams/convert.go","code":"func isStructKind(kind reflect.Kind) bool {\n\treturn kind == reflect.Struct\n}","line":{"from":61,"to":63}} {"id":100015172,"name":"isValueKind","signature":"func isValueKind(kind reflect.Kind) bool","file":"staging/src/k8s.io/apimachinery/pkg/conversion/queryparams/convert.go","code":"func isValueKind(kind reflect.Kind) bool {\n\tswitch kind {\n\tcase reflect.String, reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16,\n\t\treflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8,\n\t\treflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32,\n\t\treflect.Float64, reflect.Complex64, reflect.Complex128:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":65,"to":75}} {"id":100015173,"name":"zeroValue","signature":"func zeroValue(value reflect.Value) bool","file":"staging/src/k8s.io/apimachinery/pkg/conversion/queryparams/convert.go","code":"func zeroValue(value reflect.Value) bool {\n\treturn reflect.DeepEqual(reflect.Zero(value.Type()).Interface(), value.Interface())\n}","line":{"from":77,"to":79}} {"id":100015174,"name":"customMarshalValue","signature":"func customMarshalValue(value reflect.Value) (reflect.Value, bool)","file":"staging/src/k8s.io/apimachinery/pkg/conversion/queryparams/convert.go","code":"func customMarshalValue(value reflect.Value) (reflect.Value, bool) {\n\t// Return unless we implement a custom query marshaler\n\tif !value.CanInterface() {\n\t\treturn reflect.Value{}, false\n\t}\n\n\tmarshaler, ok := value.Interface().(Marshaler)\n\tif !ok {\n\t\tif !isPointerKind(value.Kind()) \u0026\u0026 value.CanAddr() {\n\t\t\tmarshaler, ok = value.Addr().Interface().(Marshaler)\n\t\t\tif !ok {\n\t\t\t\treturn reflect.Value{}, false\n\t\t\t}\n\t\t} else {\n\t\t\treturn reflect.Value{}, false\n\t\t}\n\t}\n\n\t// Don't invoke functions on nil pointers\n\t// If the type implements MarshalQueryParameter, AND the tag is not omitempty, AND the value is a nil pointer, \"\" seems like a reasonable response\n\tif isPointerKind(value.Kind()) \u0026\u0026 zeroValue(value) {\n\t\treturn reflect.ValueOf(\"\"), true\n\t}\n\n\t// Get the custom marshalled value\n\tv, err := marshaler.MarshalQueryParameter()\n\tif err != nil {\n\t\treturn reflect.Value{}, false\n\t}\n\treturn reflect.ValueOf(v), true\n}","line":{"from":81,"to":111}} {"id":100015175,"name":"addParam","signature":"func addParam(values url.Values, tag string, omitempty bool, value reflect.Value)","file":"staging/src/k8s.io/apimachinery/pkg/conversion/queryparams/convert.go","code":"func addParam(values url.Values, tag string, omitempty bool, value reflect.Value) {\n\tif omitempty \u0026\u0026 zeroValue(value) {\n\t\treturn\n\t}\n\tval := \"\"\n\tiValue := fmt.Sprintf(\"%v\", value.Interface())\n\n\tif iValue != \"\u003cnil\u003e\" {\n\t\tval = iValue\n\t}\n\tvalues.Add(tag, val)\n}","line":{"from":113,"to":124}} {"id":100015176,"name":"addListOfParams","signature":"func addListOfParams(values url.Values, tag string, omitempty bool, list reflect.Value)","file":"staging/src/k8s.io/apimachinery/pkg/conversion/queryparams/convert.go","code":"func addListOfParams(values url.Values, tag string, omitempty bool, list reflect.Value) {\n\tfor i := 0; i \u003c list.Len(); i++ {\n\t\taddParam(values, tag, omitempty, list.Index(i))\n\t}\n}","line":{"from":126,"to":130}} {"id":100015177,"name":"Convert","signature":"func Convert(obj interface{}) (url.Values, error)","file":"staging/src/k8s.io/apimachinery/pkg/conversion/queryparams/convert.go","code":"// Convert takes an object and converts it to a url.Values object using JSON tags as\n// parameter names. Only top-level simple values, arrays, and slices are serialized.\n// Embedded structs, maps, etc. will not be serialized.\nfunc Convert(obj interface{}) (url.Values, error) {\n\tresult := url.Values{}\n\tif obj == nil {\n\t\treturn result, nil\n\t}\n\tvar sv reflect.Value\n\tswitch reflect.TypeOf(obj).Kind() {\n\tcase reflect.Pointer, reflect.Interface:\n\t\tsv = reflect.ValueOf(obj).Elem()\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"expecting a pointer or interface\")\n\t}\n\tst := sv.Type()\n\tif !isStructKind(st.Kind()) {\n\t\treturn nil, fmt.Errorf(\"expecting a pointer to a struct\")\n\t}\n\n\t// Check all object fields\n\tconvertStruct(result, st, sv)\n\n\treturn result, nil\n}","line":{"from":132,"to":156}} {"id":100015178,"name":"convertStruct","signature":"func convertStruct(result url.Values, st reflect.Type, sv reflect.Value)","file":"staging/src/k8s.io/apimachinery/pkg/conversion/queryparams/convert.go","code":"func convertStruct(result url.Values, st reflect.Type, sv reflect.Value) {\n\tfor i := 0; i \u003c st.NumField(); i++ {\n\t\tfield := sv.Field(i)\n\t\ttag, omitempty := jsonTag(st.Field(i))\n\t\tif len(tag) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tft := field.Type()\n\n\t\tkind := ft.Kind()\n\t\tif isPointerKind(kind) {\n\t\t\tft = ft.Elem()\n\t\t\tkind = ft.Kind()\n\t\t\tif !field.IsNil() {\n\t\t\t\tfield = reflect.Indirect(field)\n\t\t\t\t// If the field is non-nil, it should be added to params\n\t\t\t\t// and the omitempty should be overwite to false\n\t\t\t\tomitempty = false\n\t\t\t}\n\t\t}\n\n\t\tswitch {\n\t\tcase isValueKind(kind):\n\t\t\taddParam(result, tag, omitempty, field)\n\t\tcase kind == reflect.Array || kind == reflect.Slice:\n\t\t\tif isValueKind(ft.Elem().Kind()) {\n\t\t\t\taddListOfParams(result, tag, omitempty, field)\n\t\t\t}\n\t\tcase isStructKind(kind) \u0026\u0026 !(zeroValue(field) \u0026\u0026 omitempty):\n\t\t\tif marshalValue, ok := customMarshalValue(field); ok {\n\t\t\t\taddParam(result, tag, omitempty, marshalValue)\n\t\t\t} else {\n\t\t\t\tconvertStruct(result, ft, field)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":158,"to":194}} {"id":100015179,"name":"String","signature":"func (ls Set) String() string","file":"staging/src/k8s.io/apimachinery/pkg/fields/fields.go","code":"// String returns all fields listed as a human readable string.\n// Conveniently, exactly the format that ParseSelector takes.\nfunc (ls Set) String() string {\n\tselector := make([]string, 0, len(ls))\n\tfor key, value := range ls {\n\t\tselector = append(selector, key+\"=\"+value)\n\t}\n\t// Sort for determinism.\n\tsort.StringSlice(selector).Sort()\n\treturn strings.Join(selector, \",\")\n}","line":{"from":36,"to":46}} {"id":100015180,"name":"Has","signature":"func (ls Set) Has(field string) bool","file":"staging/src/k8s.io/apimachinery/pkg/fields/fields.go","code":"// Has returns whether the provided field exists in the map.\nfunc (ls Set) Has(field string) bool {\n\t_, exists := ls[field]\n\treturn exists\n}","line":{"from":48,"to":52}} {"id":100015181,"name":"Get","signature":"func (ls Set) Get(field string) string","file":"staging/src/k8s.io/apimachinery/pkg/fields/fields.go","code":"// Get returns the value in the map for the provided field.\nfunc (ls Set) Get(field string) string {\n\treturn ls[field]\n}","line":{"from":54,"to":57}} {"id":100015182,"name":"AsSelector","signature":"func (ls Set) AsSelector() Selector","file":"staging/src/k8s.io/apimachinery/pkg/fields/fields.go","code":"// AsSelector converts fields into a selectors.\nfunc (ls Set) AsSelector() Selector {\n\treturn SelectorFromSet(ls)\n}","line":{"from":59,"to":62}} {"id":100015183,"name":"Matches","signature":"func (n nothingSelector) Matches(_ Fields) bool { return false }","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (n nothingSelector) Matches(_ Fields) bool { return false }","line":{"from":60,"to":60}} {"id":100015184,"name":"Empty","signature":"func (n nothingSelector) Empty() bool { return false }","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (n nothingSelector) Empty() bool { return false }","line":{"from":61,"to":61}} {"id":100015185,"name":"String","signature":"func (n nothingSelector) String() string { return \"\" }","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (n nothingSelector) String() string { return \"\" }","line":{"from":62,"to":62}} {"id":100015186,"name":"Requirements","signature":"func (n nothingSelector) Requirements() Requirements { return nil }","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (n nothingSelector) Requirements() Requirements { return nil }","line":{"from":63,"to":63}} {"id":100015187,"name":"DeepCopySelector","signature":"func (n nothingSelector) DeepCopySelector() Selector { return n }","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (n nothingSelector) DeepCopySelector() Selector { return n }","line":{"from":64,"to":64}} {"id":100015188,"name":"RequiresExactMatch","signature":"func (n nothingSelector) RequiresExactMatch(field string) (value string, found bool)","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (n nothingSelector) RequiresExactMatch(field string) (value string, found bool) {\n\treturn \"\", false\n}","line":{"from":65,"to":67}} {"id":100015189,"name":"Transform","signature":"func (n nothingSelector) Transform(fn TransformFunc) (Selector, error) { return n, nil }","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (n nothingSelector) Transform(fn TransformFunc) (Selector, error) { return n, nil }","line":{"from":68,"to":68}} {"id":100015190,"name":"Nothing","signature":"func Nothing() Selector","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"// Nothing returns a selector that matches no fields\nfunc Nothing() Selector {\n\treturn nothingSelector{}\n}","line":{"from":70,"to":73}} {"id":100015191,"name":"Everything","signature":"func Everything() Selector","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"// Everything returns a selector that matches all fields.\nfunc Everything() Selector {\n\treturn andTerm{}\n}","line":{"from":75,"to":78}} {"id":100015192,"name":"Matches","signature":"func (t *hasTerm) Matches(ls Fields) bool","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (t *hasTerm) Matches(ls Fields) bool {\n\treturn ls.Get(t.field) == t.value\n}","line":{"from":84,"to":86}} {"id":100015193,"name":"Empty","signature":"func (t *hasTerm) Empty() bool","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (t *hasTerm) Empty() bool {\n\treturn false\n}","line":{"from":88,"to":90}} {"id":100015194,"name":"RequiresExactMatch","signature":"func (t *hasTerm) RequiresExactMatch(field string) (value string, found bool)","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (t *hasTerm) RequiresExactMatch(field string) (value string, found bool) {\n\tif t.field == field {\n\t\treturn t.value, true\n\t}\n\treturn \"\", false\n}","line":{"from":92,"to":97}} {"id":100015195,"name":"Transform","signature":"func (t *hasTerm) Transform(fn TransformFunc) (Selector, error)","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (t *hasTerm) Transform(fn TransformFunc) (Selector, error) {\n\tfield, value, err := fn(t.field, t.value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(field) == 0 \u0026\u0026 len(value) == 0 {\n\t\treturn Everything(), nil\n\t}\n\treturn \u0026hasTerm{field, value}, nil\n}","line":{"from":99,"to":108}} {"id":100015196,"name":"Requirements","signature":"func (t *hasTerm) Requirements() Requirements","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (t *hasTerm) Requirements() Requirements {\n\treturn []Requirement{{\n\t\tField: t.field,\n\t\tOperator: selection.Equals,\n\t\tValue: t.value,\n\t}}\n}","line":{"from":110,"to":116}} {"id":100015197,"name":"String","signature":"func (t *hasTerm) String() string","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (t *hasTerm) String() string {\n\treturn fmt.Sprintf(\"%v=%v\", t.field, EscapeValue(t.value))\n}","line":{"from":118,"to":120}} {"id":100015198,"name":"DeepCopySelector","signature":"func (t *hasTerm) DeepCopySelector() Selector","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (t *hasTerm) DeepCopySelector() Selector {\n\tif t == nil {\n\t\treturn nil\n\t}\n\tout := new(hasTerm)\n\t*out = *t\n\treturn out\n}","line":{"from":122,"to":129}} {"id":100015199,"name":"Matches","signature":"func (t *notHasTerm) Matches(ls Fields) bool","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (t *notHasTerm) Matches(ls Fields) bool {\n\treturn ls.Get(t.field) != t.value\n}","line":{"from":135,"to":137}} {"id":100015200,"name":"Empty","signature":"func (t *notHasTerm) Empty() bool","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (t *notHasTerm) Empty() bool {\n\treturn false\n}","line":{"from":139,"to":141}} {"id":100015201,"name":"RequiresExactMatch","signature":"func (t *notHasTerm) RequiresExactMatch(field string) (value string, found bool)","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (t *notHasTerm) RequiresExactMatch(field string) (value string, found bool) {\n\treturn \"\", false\n}","line":{"from":143,"to":145}} {"id":100015202,"name":"Transform","signature":"func (t *notHasTerm) Transform(fn TransformFunc) (Selector, error)","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (t *notHasTerm) Transform(fn TransformFunc) (Selector, error) {\n\tfield, value, err := fn(t.field, t.value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(field) == 0 \u0026\u0026 len(value) == 0 {\n\t\treturn Everything(), nil\n\t}\n\treturn \u0026notHasTerm{field, value}, nil\n}","line":{"from":147,"to":156}} {"id":100015203,"name":"Requirements","signature":"func (t *notHasTerm) Requirements() Requirements","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (t *notHasTerm) Requirements() Requirements {\n\treturn []Requirement{{\n\t\tField: t.field,\n\t\tOperator: selection.NotEquals,\n\t\tValue: t.value,\n\t}}\n}","line":{"from":158,"to":164}} {"id":100015204,"name":"String","signature":"func (t *notHasTerm) String() string","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (t *notHasTerm) String() string {\n\treturn fmt.Sprintf(\"%v!=%v\", t.field, EscapeValue(t.value))\n}","line":{"from":166,"to":168}} {"id":100015205,"name":"DeepCopySelector","signature":"func (t *notHasTerm) DeepCopySelector() Selector","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (t *notHasTerm) DeepCopySelector() Selector {\n\tif t == nil {\n\t\treturn nil\n\t}\n\tout := new(notHasTerm)\n\t*out = *t\n\treturn out\n}","line":{"from":170,"to":177}} {"id":100015206,"name":"Matches","signature":"func (t andTerm) Matches(ls Fields) bool","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (t andTerm) Matches(ls Fields) bool {\n\tfor _, q := range t {\n\t\tif !q.Matches(ls) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":181,"to":188}} {"id":100015207,"name":"Empty","signature":"func (t andTerm) Empty() bool","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (t andTerm) Empty() bool {\n\tif t == nil {\n\t\treturn true\n\t}\n\tif len([]Selector(t)) == 0 {\n\t\treturn true\n\t}\n\tfor i := range t {\n\t\tif !t[i].Empty() {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":190,"to":203}} {"id":100015208,"name":"RequiresExactMatch","signature":"func (t andTerm) RequiresExactMatch(field string) (string, bool)","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (t andTerm) RequiresExactMatch(field string) (string, bool) {\n\tif t == nil || len([]Selector(t)) == 0 {\n\t\treturn \"\", false\n\t}\n\tfor i := range t {\n\t\tif value, found := t[i].RequiresExactMatch(field); found {\n\t\t\treturn value, found\n\t\t}\n\t}\n\treturn \"\", false\n}","line":{"from":205,"to":215}} {"id":100015209,"name":"Transform","signature":"func (t andTerm) Transform(fn TransformFunc) (Selector, error)","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (t andTerm) Transform(fn TransformFunc) (Selector, error) {\n\tnext := make([]Selector, 0, len([]Selector(t)))\n\tfor _, s := range []Selector(t) {\n\t\tn, err := s.Transform(fn)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !n.Empty() {\n\t\t\tnext = append(next, n)\n\t\t}\n\t}\n\treturn andTerm(next), nil\n}","line":{"from":217,"to":229}} {"id":100015210,"name":"Requirements","signature":"func (t andTerm) Requirements() Requirements","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (t andTerm) Requirements() Requirements {\n\treqs := make([]Requirement, 0, len(t))\n\tfor _, s := range []Selector(t) {\n\t\trs := s.Requirements()\n\t\treqs = append(reqs, rs...)\n\t}\n\treturn reqs\n}","line":{"from":231,"to":238}} {"id":100015211,"name":"String","signature":"func (t andTerm) String() string","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (t andTerm) String() string {\n\tvar terms []string\n\tfor _, q := range t {\n\t\tterms = append(terms, q.String())\n\t}\n\treturn strings.Join(terms, \",\")\n}","line":{"from":240,"to":246}} {"id":100015212,"name":"DeepCopySelector","signature":"func (t andTerm) DeepCopySelector() Selector","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (t andTerm) DeepCopySelector() Selector {\n\tif t == nil {\n\t\treturn nil\n\t}\n\tout := make([]Selector, len(t))\n\tfor i := range t {\n\t\tout[i] = t[i].DeepCopySelector()\n\t}\n\treturn andTerm(out)\n}","line":{"from":248,"to":257}} {"id":100015213,"name":"SelectorFromSet","signature":"func SelectorFromSet(ls Set) Selector","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"// SelectorFromSet returns a Selector which will match exactly the given Set. A\n// nil Set is considered equivalent to Everything().\nfunc SelectorFromSet(ls Set) Selector {\n\tif ls == nil {\n\t\treturn Everything()\n\t}\n\titems := make([]Selector, 0, len(ls))\n\tfor field, value := range ls {\n\t\titems = append(items, \u0026hasTerm{field: field, value: value})\n\t}\n\tif len(items) == 1 {\n\t\treturn items[0]\n\t}\n\treturn andTerm(items)\n}","line":{"from":259,"to":273}} {"id":100015214,"name":"EscapeValue","signature":"func EscapeValue(s string) string","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"// EscapeValue escapes an arbitrary literal string for use as a fieldSelector value\nfunc EscapeValue(s string) string {\n\treturn valueEscaper.Replace(s)\n}","line":{"from":284,"to":287}} {"id":100015215,"name":"Error","signature":"func (i InvalidEscapeSequence) Error() string","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (i InvalidEscapeSequence) Error() string {\n\treturn fmt.Sprintf(\"invalid field selector: invalid escape sequence: %s\", i.sequence)\n}","line":{"from":294,"to":296}} {"id":100015216,"name":"Error","signature":"func (i UnescapedRune) Error() string","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func (i UnescapedRune) Error() string {\n\treturn fmt.Sprintf(\"invalid field selector: unescaped character in value: %v\", i.r)\n}","line":{"from":303,"to":305}} {"id":100015217,"name":"UnescapeValue","signature":"func UnescapeValue(s string) (string, error)","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"// UnescapeValue unescapes a fieldSelector value and returns the original literal value.\n// May return the original string if it contains no escaped or special characters.\nfunc UnescapeValue(s string) (string, error) {\n\t// if there's no escaping or special characters, just return to avoid allocation\n\tif !strings.ContainsAny(s, `\\,=`) {\n\t\treturn s, nil\n\t}\n\n\tv := bytes.NewBuffer(make([]byte, 0, len(s)))\n\tinSlash := false\n\tfor _, c := range s {\n\t\tif inSlash {\n\t\t\tswitch c {\n\t\t\tcase '\\\\', ',', '=':\n\t\t\t\t// omit the \\ for recognized escape sequences\n\t\t\t\tv.WriteRune(c)\n\t\t\tdefault:\n\t\t\t\t// error on unrecognized escape sequences\n\t\t\t\treturn \"\", InvalidEscapeSequence{sequence: string([]rune{'\\\\', c})}\n\t\t\t}\n\t\t\tinSlash = false\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch c {\n\t\tcase '\\\\':\n\t\t\tinSlash = true\n\t\tcase ',', '=':\n\t\t\t// unescaped , and = characters are not allowed in field selector values\n\t\t\treturn \"\", UnescapedRune{r: c}\n\t\tdefault:\n\t\t\tv.WriteRune(c)\n\t\t}\n\t}\n\n\t// Ending with a single backslash is an invalid sequence\n\tif inSlash {\n\t\treturn \"\", InvalidEscapeSequence{sequence: \"\\\\\"}\n\t}\n\n\treturn v.String(), nil\n}","line":{"from":307,"to":348}} {"id":100015218,"name":"ParseSelectorOrDie","signature":"func ParseSelectorOrDie(s string) Selector","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"// ParseSelectorOrDie takes a string representing a selector and returns an\n// object suitable for matching, or panic when an error occur.\nfunc ParseSelectorOrDie(s string) Selector {\n\tselector, err := ParseSelector(s)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn selector\n}","line":{"from":350,"to":358}} {"id":100015219,"name":"ParseSelector","signature":"func ParseSelector(selector string) (Selector, error)","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"// ParseSelector takes a string representing a selector and returns an\n// object suitable for matching, or an error.\nfunc ParseSelector(selector string) (Selector, error) {\n\treturn parseSelector(selector,\n\t\tfunc(lhs, rhs string) (newLhs, newRhs string, err error) {\n\t\t\treturn lhs, rhs, nil\n\t\t})\n}","line":{"from":360,"to":367}} {"id":100015220,"name":"ParseAndTransformSelector","signature":"func ParseAndTransformSelector(selector string, fn TransformFunc) (Selector, error)","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"// ParseAndTransformSelector parses the selector and runs them through the given TransformFunc.\nfunc ParseAndTransformSelector(selector string, fn TransformFunc) (Selector, error) {\n\treturn parseSelector(selector, fn)\n}","line":{"from":369,"to":372}} {"id":100015221,"name":"splitTerms","signature":"func splitTerms(fieldSelector string) []string","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"// splitTerms returns the comma-separated terms contained in the given fieldSelector.\n// Backslash-escaped commas are treated as data instead of delimiters, and are included in the returned terms, with the leading backslash preserved.\nfunc splitTerms(fieldSelector string) []string {\n\tif len(fieldSelector) == 0 {\n\t\treturn nil\n\t}\n\n\tterms := make([]string, 0, 1)\n\tstartIndex := 0\n\tinSlash := false\n\tfor i, c := range fieldSelector {\n\t\tswitch {\n\t\tcase inSlash:\n\t\t\tinSlash = false\n\t\tcase c == '\\\\':\n\t\t\tinSlash = true\n\t\tcase c == ',':\n\t\t\tterms = append(terms, fieldSelector[startIndex:i])\n\t\t\tstartIndex = i + 1\n\t\t}\n\t}\n\n\tterms = append(terms, fieldSelector[startIndex:])\n\n\treturn terms\n}","line":{"from":377,"to":402}} {"id":100015222,"name":"splitTerm","signature":"func splitTerm(term string) (lhs, op, rhs string, ok bool)","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"// splitTerm returns the lhs, operator, and rhs parsed from the given term, along with an indicator of whether the parse was successful.\n// no escaping of special characters is supported in the lhs value, so the first occurrence of a recognized operator is used as the split point.\n// the literal rhs is returned, and the caller is responsible for applying any desired unescaping.\nfunc splitTerm(term string) (lhs, op, rhs string, ok bool) {\n\tfor i := range term {\n\t\tremaining := term[i:]\n\t\tfor _, op := range termOperators {\n\t\t\tif strings.HasPrefix(remaining, op) {\n\t\t\t\treturn term[0:i], op, term[i+len(op):], true\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", \"\", \"\", false\n}","line":{"from":415,"to":428}} {"id":100015223,"name":"parseSelector","signature":"func parseSelector(selector string, fn TransformFunc) (Selector, error)","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"func parseSelector(selector string, fn TransformFunc) (Selector, error) {\n\tparts := splitTerms(selector)\n\tsort.StringSlice(parts).Sort()\n\tvar items []Selector\n\tfor _, part := range parts {\n\t\tif part == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tlhs, op, rhs, ok := splitTerm(part)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"invalid selector: '%s'; can't understand '%s'\", selector, part)\n\t\t}\n\t\tunescapedRHS, err := UnescapeValue(rhs)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tswitch op {\n\t\tcase notEqualOperator:\n\t\t\titems = append(items, \u0026notHasTerm{field: lhs, value: unescapedRHS})\n\t\tcase doubleEqualOperator:\n\t\t\titems = append(items, \u0026hasTerm{field: lhs, value: unescapedRHS})\n\t\tcase equalOperator:\n\t\t\titems = append(items, \u0026hasTerm{field: lhs, value: unescapedRHS})\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"invalid selector: '%s'; can't understand '%s'\", selector, part)\n\t\t}\n\t}\n\tif len(items) == 1 {\n\t\treturn items[0].Transform(fn)\n\t}\n\treturn andTerm(items).Transform(fn)\n}","line":{"from":430,"to":461}} {"id":100015224,"name":"OneTermEqualSelector","signature":"func OneTermEqualSelector(k, v string) Selector","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"// OneTermEqualSelector returns an object that matches objects where one field/field equals one value.\n// Cannot return an error.\nfunc OneTermEqualSelector(k, v string) Selector {\n\treturn \u0026hasTerm{field: k, value: v}\n}","line":{"from":463,"to":467}} {"id":100015225,"name":"OneTermNotEqualSelector","signature":"func OneTermNotEqualSelector(k, v string) Selector","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"// OneTermNotEqualSelector returns an object that matches objects where one field/field does not equal one value.\n// Cannot return an error.\nfunc OneTermNotEqualSelector(k, v string) Selector {\n\treturn \u0026notHasTerm{field: k, value: v}\n}","line":{"from":469,"to":473}} {"id":100015226,"name":"AndSelectors","signature":"func AndSelectors(selectors ...Selector) Selector","file":"staging/src/k8s.io/apimachinery/pkg/fields/selector.go","code":"// AndSelectors creates a selector that is the logical AND of all the given selectors\nfunc AndSelectors(selectors ...Selector) Selector {\n\treturn andTerm(selectors)\n}","line":{"from":475,"to":478}} {"id":100015227,"name":"String","signature":"func (ls Set) String() string","file":"staging/src/k8s.io/apimachinery/pkg/labels/labels.go","code":"// String returns all labels listed as a human readable string.\n// Conveniently, exactly the format that ParseSelector takes.\nfunc (ls Set) String() string {\n\tselector := make([]string, 0, len(ls))\n\tfor key, value := range ls {\n\t\tselector = append(selector, key+\"=\"+value)\n\t}\n\t// Sort for determinism.\n\tsort.StringSlice(selector).Sort()\n\treturn strings.Join(selector, \",\")\n}","line":{"from":39,"to":49}} {"id":100015228,"name":"Has","signature":"func (ls Set) Has(label string) bool","file":"staging/src/k8s.io/apimachinery/pkg/labels/labels.go","code":"// Has returns whether the provided label exists in the map.\nfunc (ls Set) Has(label string) bool {\n\t_, exists := ls[label]\n\treturn exists\n}","line":{"from":51,"to":55}} {"id":100015229,"name":"Get","signature":"func (ls Set) Get(label string) string","file":"staging/src/k8s.io/apimachinery/pkg/labels/labels.go","code":"// Get returns the value in the map for the provided label.\nfunc (ls Set) Get(label string) string {\n\treturn ls[label]\n}","line":{"from":57,"to":60}} {"id":100015230,"name":"AsSelector","signature":"func (ls Set) AsSelector() Selector","file":"staging/src/k8s.io/apimachinery/pkg/labels/labels.go","code":"// AsSelector converts labels into a selectors. It does not\n// perform any validation, which means the server will reject\n// the request if the Set contains invalid values.\nfunc (ls Set) AsSelector() Selector {\n\treturn SelectorFromSet(ls)\n}","line":{"from":62,"to":67}} {"id":100015231,"name":"AsValidatedSelector","signature":"func (ls Set) AsValidatedSelector() (Selector, error)","file":"staging/src/k8s.io/apimachinery/pkg/labels/labels.go","code":"// AsValidatedSelector converts labels into a selectors.\n// The Set is validated client-side, which allows to catch errors early.\nfunc (ls Set) AsValidatedSelector() (Selector, error) {\n\treturn ValidatedSelectorFromSet(ls)\n}","line":{"from":69,"to":73}} {"id":100015232,"name":"AsSelectorPreValidated","signature":"func (ls Set) AsSelectorPreValidated() Selector","file":"staging/src/k8s.io/apimachinery/pkg/labels/labels.go","code":"// AsSelectorPreValidated converts labels into a selector, but\n// assumes that labels are already validated and thus doesn't\n// perform any validation.\n// According to our measurements this is significantly faster\n// in codepaths that matter at high scale.\n// Note: this method copies the Set; if the Set is immutable, consider wrapping it with ValidatedSetSelector\n// instead, which does not copy.\nfunc (ls Set) AsSelectorPreValidated() Selector {\n\treturn SelectorFromValidatedSet(ls)\n}","line":{"from":75,"to":84}} {"id":100015233,"name":"FormatLabels","signature":"func FormatLabels(labelMap map[string]string) string","file":"staging/src/k8s.io/apimachinery/pkg/labels/labels.go","code":"// FormatLabels converts label map into plain string\nfunc FormatLabels(labelMap map[string]string) string {\n\tl := Set(labelMap).String()\n\tif l == \"\" {\n\t\tl = \"\u003cnone\u003e\"\n\t}\n\treturn l\n}","line":{"from":86,"to":93}} {"id":100015234,"name":"Conflicts","signature":"func Conflicts(labels1, labels2 Set) bool","file":"staging/src/k8s.io/apimachinery/pkg/labels/labels.go","code":"// Conflicts takes 2 maps and returns true if there a key match between\n// the maps but the value doesn't match, and returns false in other cases\nfunc Conflicts(labels1, labels2 Set) bool {\n\tsmall := labels1\n\tbig := labels2\n\tif len(labels2) \u003c len(labels1) {\n\t\tsmall = labels2\n\t\tbig = labels1\n\t}\n\n\tfor k, v := range small {\n\t\tif val, match := big[k]; match {\n\t\t\tif val != v {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":95,"to":114}} {"id":100015235,"name":"Merge","signature":"func Merge(labels1, labels2 Set) Set","file":"staging/src/k8s.io/apimachinery/pkg/labels/labels.go","code":"// Merge combines given maps, and does not check for any conflicts\n// between the maps. In case of conflicts, second map (labels2) wins\nfunc Merge(labels1, labels2 Set) Set {\n\tmergedMap := Set{}\n\n\tfor k, v := range labels1 {\n\t\tmergedMap[k] = v\n\t}\n\tfor k, v := range labels2 {\n\t\tmergedMap[k] = v\n\t}\n\treturn mergedMap\n}","line":{"from":116,"to":128}} {"id":100015236,"name":"Equals","signature":"func Equals(labels1, labels2 Set) bool","file":"staging/src/k8s.io/apimachinery/pkg/labels/labels.go","code":"// Equals returns true if the given maps are equal\nfunc Equals(labels1, labels2 Set) bool {\n\tif len(labels1) != len(labels2) {\n\t\treturn false\n\t}\n\n\tfor k, v := range labels1 {\n\t\tvalue, ok := labels2[k]\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\tif value != v {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":130,"to":146}} {"id":100015237,"name":"ConvertSelectorToLabelsMap","signature":"func ConvertSelectorToLabelsMap(selector string, opts ...field.PathOption) (Set, error)","file":"staging/src/k8s.io/apimachinery/pkg/labels/labels.go","code":"// ConvertSelectorToLabelsMap converts selector string to labels map\n// and validates keys and values\nfunc ConvertSelectorToLabelsMap(selector string, opts ...field.PathOption) (Set, error) {\n\tlabelsMap := Set{}\n\n\tif len(selector) == 0 {\n\t\treturn labelsMap, nil\n\t}\n\n\tlabels := strings.Split(selector, \",\")\n\tfor _, label := range labels {\n\t\tl := strings.Split(label, \"=\")\n\t\tif len(l) != 2 {\n\t\t\treturn labelsMap, fmt.Errorf(\"invalid selector: %s\", l)\n\t\t}\n\t\tkey := strings.TrimSpace(l[0])\n\t\tif err := validateLabelKey(key, field.ToPath(opts...)); err != nil {\n\t\t\treturn labelsMap, err\n\t\t}\n\t\tvalue := strings.TrimSpace(l[1])\n\t\tif err := validateLabelValue(key, value, field.ToPath(opts...)); err != nil {\n\t\t\treturn labelsMap, err\n\t\t}\n\t\tlabelsMap[key] = value\n\t}\n\treturn labelsMap, nil\n}","line":{"from":148,"to":174}} {"id":100015238,"name":"Everything","signature":"func Everything() Selector","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// Everything returns a selector that matches all labels.\nfunc Everything() Selector {\n\treturn sharedEverythingSelector\n}","line":{"from":80,"to":83}} {"id":100015239,"name":"Matches","signature":"func (n nothingSelector) Matches(_ Labels) bool { return false }","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"func (n nothingSelector) Matches(_ Labels) bool { return false }","line":{"from":87,"to":87}} {"id":100015240,"name":"Empty","signature":"func (n nothingSelector) Empty() bool { return false }","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"func (n nothingSelector) Empty() bool { return false }","line":{"from":88,"to":88}} {"id":100015241,"name":"String","signature":"func (n nothingSelector) String() string { return \"\" }","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"func (n nothingSelector) String() string { return \"\" }","line":{"from":89,"to":89}} {"id":100015242,"name":"Add","signature":"func (n nothingSelector) Add(_ ...Requirement) Selector { return n }","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"func (n nothingSelector) Add(_ ...Requirement) Selector { return n }","line":{"from":90,"to":90}} {"id":100015243,"name":"Requirements","signature":"func (n nothingSelector) Requirements() (Requirements, bool) { return nil, false }","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"func (n nothingSelector) Requirements() (Requirements, bool) { return nil, false }","line":{"from":91,"to":91}} {"id":100015244,"name":"DeepCopySelector","signature":"func (n nothingSelector) DeepCopySelector() Selector { return n }","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"func (n nothingSelector) DeepCopySelector() Selector { return n }","line":{"from":92,"to":92}} {"id":100015245,"name":"RequiresExactMatch","signature":"func (n nothingSelector) RequiresExactMatch(label string) (value string, found bool)","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"func (n nothingSelector) RequiresExactMatch(label string) (value string, found bool) {\n\treturn \"\", false\n}","line":{"from":93,"to":95}} {"id":100015246,"name":"Nothing","signature":"func Nothing() Selector","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// Nothing returns a selector that matches no labels\nfunc Nothing() Selector {\n\treturn sharedNothingSelector\n}","line":{"from":100,"to":103}} {"id":100015247,"name":"NewSelector","signature":"func NewSelector() Selector","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// NewSelector returns a nil selector\nfunc NewSelector() Selector {\n\treturn internalSelector(nil)\n}","line":{"from":105,"to":108}} {"id":100015248,"name":"DeepCopy","signature":"func (s internalSelector) DeepCopy() internalSelector","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"func (s internalSelector) DeepCopy() internalSelector {\n\tif s == nil {\n\t\treturn nil\n\t}\n\tresult := make([]Requirement, len(s))\n\tfor i := range s {\n\t\ts[i].DeepCopyInto(\u0026result[i])\n\t}\n\treturn result\n}","line":{"from":112,"to":121}} {"id":100015249,"name":"DeepCopySelector","signature":"func (s internalSelector) DeepCopySelector() Selector","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"func (s internalSelector) DeepCopySelector() Selector {\n\treturn s.DeepCopy()\n}","line":{"from":123,"to":125}} {"id":100015250,"name":"Len","signature":"func (a ByKey) Len() int { return len(a) }","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"func (a ByKey) Len() int { return len(a) }","line":{"from":130,"to":130}} {"id":100015251,"name":"Swap","signature":"func (a ByKey) Swap(i, j int) { a[i], a[j] = a[j], a[i] }","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"func (a ByKey) Swap(i, j int) { a[i], a[j] = a[j], a[i] }","line":{"from":132,"to":132}} {"id":100015252,"name":"Less","signature":"func (a ByKey) Less(i, j int) bool { return a[i].key \u003c a[j].key }","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"func (a ByKey) Less(i, j int) bool { return a[i].key \u003c a[j].key }","line":{"from":134,"to":134}} {"id":100015253,"name":"NewRequirement","signature":"func NewRequirement(key string, op selection.Operator, vals []string, opts ...field.PathOption) (*Requirement, error)","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// NewRequirement is the constructor for a Requirement.\n// If any of these rules is violated, an error is returned:\n// 1. The operator can only be In, NotIn, Equals, DoubleEquals, Gt, Lt, NotEquals, Exists, or DoesNotExist.\n// 2. If the operator is In or NotIn, the values set must be non-empty.\n// 3. If the operator is Equals, DoubleEquals, or NotEquals, the values set must contain one value.\n// 4. If the operator is Exists or DoesNotExist, the value set must be empty.\n// 5. If the operator is Gt or Lt, the values set must contain only one value, which will be interpreted as an integer.\n// 6. The key is invalid due to its length, or sequence of characters. See validateLabelKey for more details.\n//\n// The empty string is a valid value in the input values set.\n// Returned error, if not nil, is guaranteed to be an aggregated field.ErrorList\nfunc NewRequirement(key string, op selection.Operator, vals []string, opts ...field.PathOption) (*Requirement, error) {\n\tvar allErrs field.ErrorList\n\tpath := field.ToPath(opts...)\n\tif err := validateLabelKey(key, path.Child(\"key\")); err != nil {\n\t\tallErrs = append(allErrs, err)\n\t}\n\n\tvaluePath := path.Child(\"values\")\n\tswitch op {\n\tcase selection.In, selection.NotIn:\n\t\tif len(vals) == 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(valuePath, vals, \"for 'in', 'notin' operators, values set can't be empty\"))\n\t\t}\n\tcase selection.Equals, selection.DoubleEquals, selection.NotEquals:\n\t\tif len(vals) != 1 {\n\t\t\tallErrs = append(allErrs, field.Invalid(valuePath, vals, \"exact-match compatibility requires one single value\"))\n\t\t}\n\tcase selection.Exists, selection.DoesNotExist:\n\t\tif len(vals) != 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(valuePath, vals, \"values set must be empty for exists and does not exist\"))\n\t\t}\n\tcase selection.GreaterThan, selection.LessThan:\n\t\tif len(vals) != 1 {\n\t\t\tallErrs = append(allErrs, field.Invalid(valuePath, vals, \"for 'Gt', 'Lt' operators, exactly one value is required\"))\n\t\t}\n\t\tfor i := range vals {\n\t\t\tif _, err := strconv.ParseInt(vals[i], 10, 64); err != nil {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(valuePath.Index(i), vals[i], \"for 'Gt', 'Lt' operators, the value must be an integer\"))\n\t\t\t}\n\t\t}\n\tdefault:\n\t\tallErrs = append(allErrs, field.NotSupported(path.Child(\"operator\"), op, validRequirementOperators))\n\t}\n\n\tfor i := range vals {\n\t\tif err := validateLabelValue(key, vals[i], valuePath.Index(i)); err != nil {\n\t\t\tallErrs = append(allErrs, err)\n\t\t}\n\t}\n\treturn \u0026Requirement{key: key, operator: op, strValues: vals}, allErrs.ToAggregate()\n}","line":{"from":150,"to":201}} {"id":100015254,"name":"hasValue","signature":"func (r *Requirement) hasValue(value string) bool","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"func (r *Requirement) hasValue(value string) bool {\n\tfor i := range r.strValues {\n\t\tif r.strValues[i] == value {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":203,"to":210}} {"id":100015255,"name":"Matches","signature":"func (r *Requirement) Matches(ls Labels) bool","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// Matches returns true if the Requirement matches the input Labels.\n// There is a match in the following cases:\n// 1. The operator is Exists and Labels has the Requirement's key.\n// 2. The operator is In, Labels has the Requirement's key and Labels'\n// value for that key is in Requirement's value set.\n// 3. The operator is NotIn, Labels has the Requirement's key and\n// Labels' value for that key is not in Requirement's value set.\n// 4. The operator is DoesNotExist or NotIn and Labels does not have the\n// Requirement's key.\n// 5. The operator is GreaterThanOperator or LessThanOperator, and Labels has\n// the Requirement's key and the corresponding value satisfies mathematical inequality.\nfunc (r *Requirement) Matches(ls Labels) bool {\n\tswitch r.operator {\n\tcase selection.In, selection.Equals, selection.DoubleEquals:\n\t\tif !ls.Has(r.key) {\n\t\t\treturn false\n\t\t}\n\t\treturn r.hasValue(ls.Get(r.key))\n\tcase selection.NotIn, selection.NotEquals:\n\t\tif !ls.Has(r.key) {\n\t\t\treturn true\n\t\t}\n\t\treturn !r.hasValue(ls.Get(r.key))\n\tcase selection.Exists:\n\t\treturn ls.Has(r.key)\n\tcase selection.DoesNotExist:\n\t\treturn !ls.Has(r.key)\n\tcase selection.GreaterThan, selection.LessThan:\n\t\tif !ls.Has(r.key) {\n\t\t\treturn false\n\t\t}\n\t\tlsValue, err := strconv.ParseInt(ls.Get(r.key), 10, 64)\n\t\tif err != nil {\n\t\t\tklog.V(10).Infof(\"ParseInt failed for value %+v in label %+v, %+v\", ls.Get(r.key), ls, err)\n\t\t\treturn false\n\t\t}\n\n\t\t// There should be only one strValue in r.strValues, and can be converted to an integer.\n\t\tif len(r.strValues) != 1 {\n\t\t\tklog.V(10).Infof(\"Invalid values count %+v of requirement %#v, for 'Gt', 'Lt' operators, exactly one value is required\", len(r.strValues), r)\n\t\t\treturn false\n\t\t}\n\n\t\tvar rValue int64\n\t\tfor i := range r.strValues {\n\t\t\trValue, err = strconv.ParseInt(r.strValues[i], 10, 64)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(10).Infof(\"ParseInt failed for value %+v in requirement %#v, for 'Gt', 'Lt' operators, the value must be an integer\", r.strValues[i], r)\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn (r.operator == selection.GreaterThan \u0026\u0026 lsValue \u003e rValue) || (r.operator == selection.LessThan \u0026\u0026 lsValue \u003c rValue)\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":212,"to":267}} {"id":100015256,"name":"Key","signature":"func (r *Requirement) Key() string","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// Key returns requirement key\nfunc (r *Requirement) Key() string {\n\treturn r.key\n}","line":{"from":269,"to":272}} {"id":100015257,"name":"Operator","signature":"func (r *Requirement) Operator() selection.Operator","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// Operator returns requirement operator\nfunc (r *Requirement) Operator() selection.Operator {\n\treturn r.operator\n}","line":{"from":274,"to":277}} {"id":100015258,"name":"Values","signature":"func (r *Requirement) Values() sets.String","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// Values returns requirement values\nfunc (r *Requirement) Values() sets.String {\n\tret := sets.String{}\n\tfor i := range r.strValues {\n\t\tret.Insert(r.strValues[i])\n\t}\n\treturn ret\n}","line":{"from":279,"to":286}} {"id":100015259,"name":"Equal","signature":"func (r Requirement) Equal(x Requirement) bool","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// Equal checks the equality of requirement.\nfunc (r Requirement) Equal(x Requirement) bool {\n\tif r.key != x.key {\n\t\treturn false\n\t}\n\tif r.operator != x.operator {\n\t\treturn false\n\t}\n\treturn stringslices.Equal(r.strValues, x.strValues)\n}","line":{"from":288,"to":297}} {"id":100015260,"name":"Empty","signature":"func (s internalSelector) Empty() bool","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// Empty returns true if the internalSelector doesn't restrict selection space\nfunc (s internalSelector) Empty() bool {\n\tif s == nil {\n\t\treturn true\n\t}\n\treturn len(s) == 0\n}","line":{"from":299,"to":305}} {"id":100015261,"name":"String","signature":"func (r *Requirement) String() string","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// String returns a human-readable string that represents this\n// Requirement. If called on an invalid Requirement, an error is\n// returned. See NewRequirement for creating a valid Requirement.\nfunc (r *Requirement) String() string {\n\tvar sb strings.Builder\n\tsb.Grow(\n\t\t// length of r.key\n\t\tlen(r.key) +\n\t\t\t// length of 'r.operator' + 2 spaces for the worst case ('in' and 'notin')\n\t\t\tlen(r.operator) + 2 +\n\t\t\t// length of 'r.strValues' slice times. Heuristically 5 chars per word\n\t\t\t+5*len(r.strValues))\n\tif r.operator == selection.DoesNotExist {\n\t\tsb.WriteString(\"!\")\n\t}\n\tsb.WriteString(r.key)\n\n\tswitch r.operator {\n\tcase selection.Equals:\n\t\tsb.WriteString(\"=\")\n\tcase selection.DoubleEquals:\n\t\tsb.WriteString(\"==\")\n\tcase selection.NotEquals:\n\t\tsb.WriteString(\"!=\")\n\tcase selection.In:\n\t\tsb.WriteString(\" in \")\n\tcase selection.NotIn:\n\t\tsb.WriteString(\" notin \")\n\tcase selection.GreaterThan:\n\t\tsb.WriteString(\"\u003e\")\n\tcase selection.LessThan:\n\t\tsb.WriteString(\"\u003c\")\n\tcase selection.Exists, selection.DoesNotExist:\n\t\treturn sb.String()\n\t}\n\n\tswitch r.operator {\n\tcase selection.In, selection.NotIn:\n\t\tsb.WriteString(\"(\")\n\t}\n\tif len(r.strValues) == 1 {\n\t\tsb.WriteString(r.strValues[0])\n\t} else { // only \u003e 1 since == 0 prohibited by NewRequirement\n\t\t// normalizes value order on output, without mutating the in-memory selector representation\n\t\t// also avoids normalization when it is not required, and ensures we do not mutate shared data\n\t\tsb.WriteString(strings.Join(safeSort(r.strValues), \",\"))\n\t}\n\n\tswitch r.operator {\n\tcase selection.In, selection.NotIn:\n\t\tsb.WriteString(\")\")\n\t}\n\treturn sb.String()\n}","line":{"from":307,"to":360}} {"id":100015262,"name":"safeSort","signature":"func safeSort(in []string) []string","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// safeSort sorts input strings without modification\nfunc safeSort(in []string) []string {\n\tif sort.StringsAreSorted(in) {\n\t\treturn in\n\t}\n\tout := make([]string, len(in))\n\tcopy(out, in)\n\tsort.Strings(out)\n\treturn out\n}","line":{"from":362,"to":371}} {"id":100015263,"name":"Add","signature":"func (s internalSelector) Add(reqs ...Requirement) Selector","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// Add adds requirements to the selector. It copies the current selector returning a new one\nfunc (s internalSelector) Add(reqs ...Requirement) Selector {\n\tret := make(internalSelector, 0, len(s)+len(reqs))\n\tret = append(ret, s...)\n\tret = append(ret, reqs...)\n\tsort.Sort(ByKey(ret))\n\treturn ret\n}","line":{"from":373,"to":380}} {"id":100015264,"name":"Matches","signature":"func (s internalSelector) Matches(l Labels) bool","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// Matches for a internalSelector returns true if all\n// its Requirements match the input Labels. If any\n// Requirement does not match, false is returned.\nfunc (s internalSelector) Matches(l Labels) bool {\n\tfor ix := range s {\n\t\tif matches := s[ix].Matches(l); !matches {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":382,"to":392}} {"id":100015265,"name":"Requirements","signature":"func (s internalSelector) Requirements() (Requirements, bool) { return Requirements(s), true }","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"func (s internalSelector) Requirements() (Requirements, bool) { return Requirements(s), true }","line":{"from":394,"to":394}} {"id":100015266,"name":"String","signature":"func (s internalSelector) String() string","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// String returns a comma-separated string of all\n// the internalSelector Requirements' human-readable strings.\nfunc (s internalSelector) String() string {\n\tvar reqs []string\n\tfor ix := range s {\n\t\treqs = append(reqs, s[ix].String())\n\t}\n\treturn strings.Join(reqs, \",\")\n}","line":{"from":396,"to":404}} {"id":100015267,"name":"RequiresExactMatch","signature":"func (s internalSelector) RequiresExactMatch(label string) (value string, found bool)","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// RequiresExactMatch introspects whether a given selector requires a single specific field\n// to be set, and if so returns the value it requires.\nfunc (s internalSelector) RequiresExactMatch(label string) (value string, found bool) {\n\tfor ix := range s {\n\t\tif s[ix].key == label {\n\t\t\tswitch s[ix].operator {\n\t\t\tcase selection.Equals, selection.DoubleEquals, selection.In:\n\t\t\t\tif len(s[ix].strValues) == 1 {\n\t\t\t\t\treturn s[ix].strValues[0], true\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn \"\", false\n\t\t}\n\t}\n\treturn \"\", false\n}","line":{"from":406,"to":421}} {"id":100015268,"name":"isWhitespace","signature":"func isWhitespace(ch byte) bool","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// isWhitespace returns true if the rune is a space, tab, or newline.\nfunc isWhitespace(ch byte) bool {\n\treturn ch == ' ' || ch == '\\t' || ch == '\\r' || ch == '\\n'\n}","line":{"from":479,"to":482}} {"id":100015269,"name":"isSpecialSymbol","signature":"func isSpecialSymbol(ch byte) bool","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// isSpecialSymbol detects if the character ch can be an operator\nfunc isSpecialSymbol(ch byte) bool {\n\tswitch ch {\n\tcase '=', '!', '(', ')', ',', '\u003e', '\u003c':\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":484,"to":491}} {"id":100015270,"name":"read","signature":"func (l *Lexer) read() (b byte)","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// read returns the character currently lexed\n// increment the position and check the buffer overflow\nfunc (l *Lexer) read() (b byte) {\n\tb = 0\n\tif l.pos \u003c len(l.s) {\n\t\tb = l.s[l.pos]\n\t\tl.pos++\n\t}\n\treturn b\n}","line":{"from":502,"to":511}} {"id":100015271,"name":"unread","signature":"func (l *Lexer) unread()","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// unread 'undoes' the last read character\nfunc (l *Lexer) unread() {\n\tl.pos--\n}","line":{"from":513,"to":516}} {"id":100015272,"name":"scanIDOrKeyword","signature":"func (l *Lexer) scanIDOrKeyword() (tok Token, lit string)","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// scanIDOrKeyword scans string to recognize literal token (for example 'in') or an identifier.\nfunc (l *Lexer) scanIDOrKeyword() (tok Token, lit string) {\n\tvar buffer []byte\nIdentifierLoop:\n\tfor {\n\t\tswitch ch := l.read(); {\n\t\tcase ch == 0:\n\t\t\tbreak IdentifierLoop\n\t\tcase isSpecialSymbol(ch) || isWhitespace(ch):\n\t\t\tl.unread()\n\t\t\tbreak IdentifierLoop\n\t\tdefault:\n\t\t\tbuffer = append(buffer, ch)\n\t\t}\n\t}\n\ts := string(buffer)\n\tif val, ok := string2token[s]; ok { // is a literal token?\n\t\treturn val, s\n\t}\n\treturn IdentifierToken, s // otherwise is an identifier\n}","line":{"from":518,"to":538}} {"id":100015273,"name":"scanSpecialSymbol","signature":"func (l *Lexer) scanSpecialSymbol() (Token, string)","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// scanSpecialSymbol scans string starting with special symbol.\n// special symbol identify non literal operators. \"!=\", \"==\", \"=\"\nfunc (l *Lexer) scanSpecialSymbol() (Token, string) {\n\tlastScannedItem := ScannedItem{}\n\tvar buffer []byte\nSpecialSymbolLoop:\n\tfor {\n\t\tswitch ch := l.read(); {\n\t\tcase ch == 0:\n\t\t\tbreak SpecialSymbolLoop\n\t\tcase isSpecialSymbol(ch):\n\t\t\tbuffer = append(buffer, ch)\n\t\t\tif token, ok := string2token[string(buffer)]; ok {\n\t\t\t\tlastScannedItem = ScannedItem{tok: token, literal: string(buffer)}\n\t\t\t} else if lastScannedItem.tok != 0 {\n\t\t\t\tl.unread()\n\t\t\t\tbreak SpecialSymbolLoop\n\t\t\t}\n\t\tdefault:\n\t\t\tl.unread()\n\t\t\tbreak SpecialSymbolLoop\n\t\t}\n\t}\n\tif lastScannedItem.tok == 0 {\n\t\treturn ErrorToken, fmt.Sprintf(\"error expected: keyword found '%s'\", buffer)\n\t}\n\treturn lastScannedItem.tok, lastScannedItem.literal\n}","line":{"from":540,"to":567}} {"id":100015274,"name":"skipWhiteSpaces","signature":"func (l *Lexer) skipWhiteSpaces(ch byte) byte","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// skipWhiteSpaces consumes all blank characters\n// returning the first non blank character\nfunc (l *Lexer) skipWhiteSpaces(ch byte) byte {\n\tfor {\n\t\tif !isWhitespace(ch) {\n\t\t\treturn ch\n\t\t}\n\t\tch = l.read()\n\t}\n}","line":{"from":569,"to":578}} {"id":100015275,"name":"Lex","signature":"func (l *Lexer) Lex() (tok Token, lit string)","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// Lex returns a pair of Token and the literal\n// literal is meaningfull only for IdentifierToken token\nfunc (l *Lexer) Lex() (tok Token, lit string) {\n\tswitch ch := l.skipWhiteSpaces(l.read()); {\n\tcase ch == 0:\n\t\treturn EndOfStringToken, \"\"\n\tcase isSpecialSymbol(ch):\n\t\tl.unread()\n\t\treturn l.scanSpecialSymbol()\n\tdefault:\n\t\tl.unread()\n\t\treturn l.scanIDOrKeyword()\n\t}\n}","line":{"from":580,"to":593}} {"id":100015276,"name":"lookahead","signature":"func (p *Parser) lookahead(context ParserContext) (Token, string)","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// lookahead func returns the current token and string. No increment of current position\nfunc (p *Parser) lookahead(context ParserContext) (Token, string) {\n\ttok, lit := p.scannedItems[p.position].tok, p.scannedItems[p.position].literal\n\tif context == Values {\n\t\tswitch tok {\n\t\tcase InToken, NotInToken:\n\t\t\ttok = IdentifierToken\n\t\t}\n\t}\n\treturn tok, lit\n}","line":{"from":616,"to":626}} {"id":100015277,"name":"consume","signature":"func (p *Parser) consume(context ParserContext) (Token, string)","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// consume returns current token and string. Increments the position\nfunc (p *Parser) consume(context ParserContext) (Token, string) {\n\tp.position++\n\ttok, lit := p.scannedItems[p.position-1].tok, p.scannedItems[p.position-1].literal\n\tif context == Values {\n\t\tswitch tok {\n\t\tcase InToken, NotInToken:\n\t\t\ttok = IdentifierToken\n\t\t}\n\t}\n\treturn tok, lit\n}","line":{"from":628,"to":639}} {"id":100015278,"name":"scan","signature":"func (p *Parser) scan()","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// scan runs through the input string and stores the ScannedItem in an array\n// Parser can now lookahead and consume the tokens\nfunc (p *Parser) scan() {\n\tfor {\n\t\ttoken, literal := p.l.Lex()\n\t\tp.scannedItems = append(p.scannedItems, ScannedItem{token, literal})\n\t\tif token == EndOfStringToken {\n\t\t\tbreak\n\t\t}\n\t}\n}","line":{"from":641,"to":651}} {"id":100015279,"name":"parse","signature":"func (p *Parser) parse() (internalSelector, error)","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// parse runs the left recursive descending algorithm\n// on input string. It returns a list of Requirement objects.\nfunc (p *Parser) parse() (internalSelector, error) {\n\tp.scan() // init scannedItems\n\n\tvar requirements internalSelector\n\tfor {\n\t\ttok, lit := p.lookahead(Values)\n\t\tswitch tok {\n\t\tcase IdentifierToken, DoesNotExistToken:\n\t\t\tr, err := p.parseRequirement()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"unable to parse requirement: %v\", err)\n\t\t\t}\n\t\t\trequirements = append(requirements, *r)\n\t\t\tt, l := p.consume(Values)\n\t\t\tswitch t {\n\t\t\tcase EndOfStringToken:\n\t\t\t\treturn requirements, nil\n\t\t\tcase CommaToken:\n\t\t\t\tt2, l2 := p.lookahead(Values)\n\t\t\t\tif t2 != IdentifierToken \u0026\u0026 t2 != DoesNotExistToken {\n\t\t\t\t\treturn nil, fmt.Errorf(\"found '%s', expected: identifier after ','\", l2)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn nil, fmt.Errorf(\"found '%s', expected: ',' or 'end of string'\", l)\n\t\t\t}\n\t\tcase EndOfStringToken:\n\t\t\treturn requirements, nil\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"found '%s', expected: !, identifier, or 'end of string'\", lit)\n\t\t}\n\t}\n}","line":{"from":653,"to":686}} {"id":100015280,"name":"parseRequirement","signature":"func (p *Parser) parseRequirement() (*Requirement, error)","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"func (p *Parser) parseRequirement() (*Requirement, error) {\n\tkey, operator, err := p.parseKeyAndInferOperator()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif operator == selection.Exists || operator == selection.DoesNotExist { // operator found lookahead set checked\n\t\treturn NewRequirement(key, operator, []string{}, field.WithPath(p.path))\n\t}\n\toperator, err = p.parseOperator()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar values sets.String\n\tswitch operator {\n\tcase selection.In, selection.NotIn:\n\t\tvalues, err = p.parseValues()\n\tcase selection.Equals, selection.DoubleEquals, selection.NotEquals, selection.GreaterThan, selection.LessThan:\n\t\tvalues, err = p.parseExactValue()\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewRequirement(key, operator, values.List(), field.WithPath(p.path))\n\n}","line":{"from":688,"to":712}} {"id":100015281,"name":"parseKeyAndInferOperator","signature":"func (p *Parser) parseKeyAndInferOperator() (string, selection.Operator, error)","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// parseKeyAndInferOperator parses literals.\n// in case of no operator '!, in, notin, ==, =, !=' are found\n// the 'exists' operator is inferred\nfunc (p *Parser) parseKeyAndInferOperator() (string, selection.Operator, error) {\n\tvar operator selection.Operator\n\ttok, literal := p.consume(Values)\n\tif tok == DoesNotExistToken {\n\t\toperator = selection.DoesNotExist\n\t\ttok, literal = p.consume(Values)\n\t}\n\tif tok != IdentifierToken {\n\t\terr := fmt.Errorf(\"found '%s', expected: identifier\", literal)\n\t\treturn \"\", \"\", err\n\t}\n\tif err := validateLabelKey(literal, p.path); err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tif t, _ := p.lookahead(Values); t == EndOfStringToken || t == CommaToken {\n\t\tif operator != selection.DoesNotExist {\n\t\t\toperator = selection.Exists\n\t\t}\n\t}\n\treturn literal, operator, nil\n}","line":{"from":714,"to":737}} {"id":100015282,"name":"parseOperator","signature":"func (p *Parser) parseOperator() (op selection.Operator, err error)","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// parseOperator returns operator and eventually matchType\n// matchType can be exact\nfunc (p *Parser) parseOperator() (op selection.Operator, err error) {\n\ttok, lit := p.consume(KeyAndOperator)\n\tswitch tok {\n\t// DoesNotExistToken shouldn't be here because it's a unary operator, not a binary operator\n\tcase InToken:\n\t\top = selection.In\n\tcase EqualsToken:\n\t\top = selection.Equals\n\tcase DoubleEqualsToken:\n\t\top = selection.DoubleEquals\n\tcase GreaterThanToken:\n\t\top = selection.GreaterThan\n\tcase LessThanToken:\n\t\top = selection.LessThan\n\tcase NotInToken:\n\t\top = selection.NotIn\n\tcase NotEqualsToken:\n\t\top = selection.NotEquals\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"found '%s', expected: %v\", lit, strings.Join(binaryOperators, \", \"))\n\t}\n\treturn op, nil\n}","line":{"from":739,"to":763}} {"id":100015283,"name":"parseValues","signature":"func (p *Parser) parseValues() (sets.String, error)","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// parseValues parses the values for set based matching (x,y,z)\nfunc (p *Parser) parseValues() (sets.String, error) {\n\ttok, lit := p.consume(Values)\n\tif tok != OpenParToken {\n\t\treturn nil, fmt.Errorf(\"found '%s' expected: '('\", lit)\n\t}\n\ttok, lit = p.lookahead(Values)\n\tswitch tok {\n\tcase IdentifierToken, CommaToken:\n\t\ts, err := p.parseIdentifiersList() // handles general cases\n\t\tif err != nil {\n\t\t\treturn s, err\n\t\t}\n\t\tif tok, _ = p.consume(Values); tok != ClosedParToken {\n\t\t\treturn nil, fmt.Errorf(\"found '%s', expected: ')'\", lit)\n\t\t}\n\t\treturn s, nil\n\tcase ClosedParToken: // handles \"()\"\n\t\tp.consume(Values)\n\t\treturn sets.NewString(\"\"), nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"found '%s', expected: ',', ')' or identifier\", lit)\n\t}\n}","line":{"from":765,"to":788}} {"id":100015284,"name":"parseIdentifiersList","signature":"func (p *Parser) parseIdentifiersList() (sets.String, error)","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// parseIdentifiersList parses a (possibly empty) list of\n// of comma separated (possibly empty) identifiers\nfunc (p *Parser) parseIdentifiersList() (sets.String, error) {\n\ts := sets.NewString()\n\tfor {\n\t\ttok, lit := p.consume(Values)\n\t\tswitch tok {\n\t\tcase IdentifierToken:\n\t\t\ts.Insert(lit)\n\t\t\ttok2, lit2 := p.lookahead(Values)\n\t\t\tswitch tok2 {\n\t\t\tcase CommaToken:\n\t\t\t\tcontinue\n\t\t\tcase ClosedParToken:\n\t\t\t\treturn s, nil\n\t\t\tdefault:\n\t\t\t\treturn nil, fmt.Errorf(\"found '%s', expected: ',' or ')'\", lit2)\n\t\t\t}\n\t\tcase CommaToken: // handled here since we can have \"(,\"\n\t\t\tif s.Len() == 0 {\n\t\t\t\ts.Insert(\"\") // to handle (,\n\t\t\t}\n\t\t\ttok2, _ := p.lookahead(Values)\n\t\t\tif tok2 == ClosedParToken {\n\t\t\t\ts.Insert(\"\") // to handle ,) Double \"\" removed by StringSet\n\t\t\t\treturn s, nil\n\t\t\t}\n\t\t\tif tok2 == CommaToken {\n\t\t\t\tp.consume(Values)\n\t\t\t\ts.Insert(\"\") // to handle ,, Double \"\" removed by StringSet\n\t\t\t}\n\t\tdefault: // it can be operator\n\t\t\treturn s, fmt.Errorf(\"found '%s', expected: ',', or identifier\", lit)\n\t\t}\n\t}\n}","line":{"from":790,"to":825}} {"id":100015285,"name":"parseExactValue","signature":"func (p *Parser) parseExactValue() (sets.String, error)","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// parseExactValue parses the only value for exact match style\nfunc (p *Parser) parseExactValue() (sets.String, error) {\n\ts := sets.NewString()\n\ttok, _ := p.lookahead(Values)\n\tif tok == EndOfStringToken || tok == CommaToken {\n\t\ts.Insert(\"\")\n\t\treturn s, nil\n\t}\n\ttok, lit := p.consume(Values)\n\tif tok == IdentifierToken {\n\t\ts.Insert(lit)\n\t\treturn s, nil\n\t}\n\treturn nil, fmt.Errorf(\"found '%s', expected: identifier\", lit)\n}","line":{"from":827,"to":841}} {"id":100015286,"name":"Parse","signature":"func Parse(selector string, opts ...field.PathOption) (Selector, error)","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// Parse takes a string representing a selector and returns a selector\n// object, or an error. This parsing function differs from ParseSelector\n// as they parse different selectors with different syntaxes.\n// The input will cause an error if it does not follow this form:\n//\n//\t\u003cselector-syntax\u003e ::= \u003crequirement\u003e | \u003crequirement\u003e \",\" \u003cselector-syntax\u003e\n//\t\u003crequirement\u003e ::= [!] KEY [ \u003cset-based-restriction\u003e | \u003cexact-match-restriction\u003e ]\n//\t\u003cset-based-restriction\u003e ::= \"\" | \u003cinclusion-exclusion\u003e \u003cvalue-set\u003e\n//\t\u003cinclusion-exclusion\u003e ::= \u003cinclusion\u003e | \u003cexclusion\u003e\n//\t\u003cexclusion\u003e ::= \"notin\"\n//\t\u003cinclusion\u003e ::= \"in\"\n//\t\u003cvalue-set\u003e ::= \"(\" \u003cvalues\u003e \")\"\n//\t\u003cvalues\u003e ::= VALUE | VALUE \",\" \u003cvalues\u003e\n//\t\u003cexact-match-restriction\u003e ::= [\"=\"|\"==\"|\"!=\"] VALUE\n//\n// KEY is a sequence of one or more characters following [ DNS_SUBDOMAIN \"/\" ] DNS_LABEL. Max length is 63 characters.\n// VALUE is a sequence of zero or more characters \"([A-Za-z0-9_-\\.])\". Max length is 63 characters.\n// Delimiter is white space: (' ', '\\t')\n// Example of valid syntax:\n//\n//\t\"x in (foo,,baz),y,z notin ()\"\n//\n// Note:\n// 1. Inclusion - \" in \" - denotes that the KEY exists and is equal to any of the\n// VALUEs in its requirement\n// 2. Exclusion - \" notin \" - denotes that the KEY is not equal to any\n// of the VALUEs in its requirement or does not exist\n// 3. The empty string is a valid VALUE\n// 4. A requirement with just a KEY - as in \"y\" above - denotes that\n// the KEY exists and can be any VALUE.\n// 5. A requirement with just !KEY requires that the KEY not exist.\nfunc Parse(selector string, opts ...field.PathOption) (Selector, error) {\n\tparsedSelector, err := parse(selector, field.ToPath(opts...))\n\tif err == nil {\n\t\treturn parsedSelector, nil\n\t}\n\treturn nil, err\n}","line":{"from":843,"to":880}} {"id":100015287,"name":"parse","signature":"func parse(selector string, path *field.Path) (internalSelector, error)","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// parse parses the string representation of the selector and returns the internalSelector struct.\n// The callers of this method can then decide how to return the internalSelector struct to their\n// callers. This function has two callers now, one returns a Selector interface and the other\n// returns a list of requirements.\nfunc parse(selector string, path *field.Path) (internalSelector, error) {\n\tp := \u0026Parser{l: \u0026Lexer{s: selector, pos: 0}, path: path}\n\titems, err := p.parse()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsort.Sort(ByKey(items)) // sort to grant determistic parsing\n\treturn internalSelector(items), err\n}","line":{"from":882,"to":894}} {"id":100015288,"name":"validateLabelKey","signature":"func validateLabelKey(k string, path *field.Path) *field.Error","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"func validateLabelKey(k string, path *field.Path) *field.Error {\n\tif errs := validation.IsQualifiedName(k); len(errs) != 0 {\n\t\treturn field.Invalid(path, k, strings.Join(errs, \"; \"))\n\t}\n\treturn nil\n}","line":{"from":896,"to":901}} {"id":100015289,"name":"validateLabelValue","signature":"func validateLabelValue(k, v string, path *field.Path) *field.Error","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"func validateLabelValue(k, v string, path *field.Path) *field.Error {\n\tif errs := validation.IsValidLabelValue(v); len(errs) != 0 {\n\t\treturn field.Invalid(path.Key(k), v, strings.Join(errs, \"; \"))\n\t}\n\treturn nil\n}","line":{"from":903,"to":908}} {"id":100015290,"name":"SelectorFromSet","signature":"func SelectorFromSet(ls Set) Selector","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// SelectorFromSet returns a Selector which will match exactly the given Set. A\n// nil and empty Sets are considered equivalent to Everything().\n// It does not perform any validation, which means the server will reject\n// the request if the Set contains invalid values.\nfunc SelectorFromSet(ls Set) Selector {\n\treturn SelectorFromValidatedSet(ls)\n}","line":{"from":910,"to":916}} {"id":100015291,"name":"ValidatedSelectorFromSet","signature":"func ValidatedSelectorFromSet(ls Set) (Selector, error)","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// ValidatedSelectorFromSet returns a Selector which will match exactly the given Set. A\n// nil and empty Sets are considered equivalent to Everything().\n// The Set is validated client-side, which allows to catch errors early.\nfunc ValidatedSelectorFromSet(ls Set) (Selector, error) {\n\tif ls == nil || len(ls) == 0 {\n\t\treturn internalSelector{}, nil\n\t}\n\trequirements := make([]Requirement, 0, len(ls))\n\tfor label, value := range ls {\n\t\tr, err := NewRequirement(label, selection.Equals, []string{value})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trequirements = append(requirements, *r)\n\t}\n\t// sort to have deterministic string representation\n\tsort.Sort(ByKey(requirements))\n\treturn internalSelector(requirements), nil\n}","line":{"from":918,"to":936}} {"id":100015292,"name":"SelectorFromValidatedSet","signature":"func SelectorFromValidatedSet(ls Set) Selector","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// SelectorFromValidatedSet returns a Selector which will match exactly the given Set.\n// A nil and empty Sets are considered equivalent to Everything().\n// It assumes that Set is already validated and doesn't do any validation.\n// Note: this method copies the Set; if the Set is immutable, consider wrapping it with ValidatedSetSelector\n// instead, which does not copy.\nfunc SelectorFromValidatedSet(ls Set) Selector {\n\tif ls == nil || len(ls) == 0 {\n\t\treturn internalSelector{}\n\t}\n\trequirements := make([]Requirement, 0, len(ls))\n\tfor label, value := range ls {\n\t\trequirements = append(requirements, Requirement{key: label, operator: selection.Equals, strValues: []string{value}})\n\t}\n\t// sort to have deterministic string representation\n\tsort.Sort(ByKey(requirements))\n\treturn internalSelector(requirements)\n}","line":{"from":938,"to":954}} {"id":100015293,"name":"ParseToRequirements","signature":"func ParseToRequirements(selector string, opts ...field.PathOption) ([]Requirement, error)","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"// ParseToRequirements takes a string representing a selector and returns a list of\n// requirements. This function is suitable for those callers that perform additional\n// processing on selector requirements.\n// See the documentation for Parse() function for more details.\n// TODO: Consider exporting the internalSelector type instead.\nfunc ParseToRequirements(selector string, opts ...field.PathOption) ([]Requirement, error) {\n\treturn parse(selector, field.ToPath(opts...))\n}","line":{"from":956,"to":963}} {"id":100015294,"name":"Matches","signature":"func (s ValidatedSetSelector) Matches(labels Labels) bool","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"func (s ValidatedSetSelector) Matches(labels Labels) bool {\n\tfor k, v := range s {\n\t\tif !labels.Has(k) || v != labels.Get(k) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":977,"to":984}} {"id":100015295,"name":"Empty","signature":"func (s ValidatedSetSelector) Empty() bool","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"func (s ValidatedSetSelector) Empty() bool {\n\treturn len(s) == 0\n}","line":{"from":986,"to":988}} {"id":100015296,"name":"String","signature":"func (s ValidatedSetSelector) String() string","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"func (s ValidatedSetSelector) String() string {\n\tkeys := make([]string, 0, len(s))\n\tfor k := range s {\n\t\tkeys = append(keys, k)\n\t}\n\t// Ensure deterministic output\n\tsort.Strings(keys)\n\tb := strings.Builder{}\n\tfor i, key := range keys {\n\t\tv := s[key]\n\t\tb.Grow(len(key) + 2 + len(v))\n\t\tif i != 0 {\n\t\t\tb.WriteString(\",\")\n\t\t}\n\t\tb.WriteString(key)\n\t\tb.WriteString(\"=\")\n\t\tb.WriteString(v)\n\t}\n\treturn b.String()\n}","line":{"from":990,"to":1009}} {"id":100015297,"name":"Add","signature":"func (s ValidatedSetSelector) Add(r ...Requirement) Selector","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"func (s ValidatedSetSelector) Add(r ...Requirement) Selector {\n\treturn s.toFullSelector().Add(r...)\n}","line":{"from":1011,"to":1013}} {"id":100015298,"name":"Requirements","signature":"func (s ValidatedSetSelector) Requirements() (requirements Requirements, selectable bool)","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"func (s ValidatedSetSelector) Requirements() (requirements Requirements, selectable bool) {\n\treturn s.toFullSelector().Requirements()\n}","line":{"from":1015,"to":1017}} {"id":100015299,"name":"DeepCopySelector","signature":"func (s ValidatedSetSelector) DeepCopySelector() Selector","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"func (s ValidatedSetSelector) DeepCopySelector() Selector {\n\tres := make(ValidatedSetSelector, len(s))\n\tfor k, v := range s {\n\t\tres[k] = v\n\t}\n\treturn res\n}","line":{"from":1019,"to":1025}} {"id":100015300,"name":"RequiresExactMatch","signature":"func (s ValidatedSetSelector) RequiresExactMatch(label string) (value string, found bool)","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"func (s ValidatedSetSelector) RequiresExactMatch(label string) (value string, found bool) {\n\tv, f := s[label]\n\treturn v, f\n}","line":{"from":1027,"to":1030}} {"id":100015301,"name":"toFullSelector","signature":"func (s ValidatedSetSelector) toFullSelector() Selector","file":"staging/src/k8s.io/apimachinery/pkg/labels/selector.go","code":"func (s ValidatedSetSelector) toFullSelector() Selector {\n\treturn SelectorFromValidatedSet(Set(s))\n}","line":{"from":1032,"to":1034}} {"id":100015302,"name":"Allocate","signature":"func (a *Allocator) Allocate(n uint64) []byte","file":"staging/src/k8s.io/apimachinery/pkg/runtime/allocator.go","code":"// Allocate reserves memory for n bytes only if the underlying array doesn't have enough capacity\n// otherwise it returns previously allocated block of memory.\n//\n// Note that the returned array is not zeroed, it is the caller's\n// responsibility to clean the memory if needed.\nfunc (a *Allocator) Allocate(n uint64) []byte {\n\tif uint64(cap(a.buf)) \u003e= n {\n\t\ta.buf = a.buf[:n]\n\t\treturn a.buf\n\t}\n\t// grow the buffer\n\tsize := uint64(2*cap(a.buf)) + n\n\ta.buf = make([]byte, size)\n\ta.buf = a.buf[:n]\n\treturn a.buf\n}","line":{"from":51,"to":66}} {"id":100015303,"name":"Allocate","signature":"func (sa *SimpleAllocator) Allocate(n uint64) []byte","file":"staging/src/k8s.io/apimachinery/pkg/runtime/allocator.go","code":"func (sa *SimpleAllocator) Allocate(n uint64) []byte {\n\treturn make([]byte, n)\n}","line":{"from":74,"to":76}} {"id":100015304,"name":"NewCodec","signature":"func NewCodec(e Encoder, d Decoder) Codec","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"// NewCodec creates a Codec from an Encoder and Decoder.\nfunc NewCodec(e Encoder, d Decoder) Codec {\n\treturn codec{e, d}\n}","line":{"from":41,"to":44}} {"id":100015305,"name":"Encode","signature":"func Encode(e Encoder, obj Object) ([]byte, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"// Encode is a convenience wrapper for encoding to a []byte from an Encoder\nfunc Encode(e Encoder, obj Object) ([]byte, error) {\n\t// TODO: reuse buffer\n\tbuf := \u0026bytes.Buffer{}\n\tif err := e.Encode(obj, buf); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}","line":{"from":46,"to":54}} {"id":100015306,"name":"Decode","signature":"func Decode(d Decoder, data []byte) (Object, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"// Decode is a convenience wrapper for decoding data into an Object.\nfunc Decode(d Decoder, data []byte) (Object, error) {\n\tobj, _, err := d.Decode(data, nil, nil)\n\treturn obj, err\n}","line":{"from":56,"to":60}} {"id":100015307,"name":"DecodeInto","signature":"func DecodeInto(d Decoder, data []byte, into Object) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"// DecodeInto performs a Decode into the provided object.\nfunc DecodeInto(d Decoder, data []byte, into Object) error {\n\tout, gvk, err := d.Decode(data, nil, into)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif out != into {\n\t\treturn fmt.Errorf(\"unable to decode %s into %v\", gvk, reflect.TypeOf(into))\n\t}\n\treturn nil\n}","line":{"from":62,"to":72}} {"id":100015308,"name":"EncodeOrDie","signature":"func EncodeOrDie(e Encoder, obj Object) string","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"// EncodeOrDie is a version of Encode which will panic instead of returning an error. For tests.\nfunc EncodeOrDie(e Encoder, obj Object) string {\n\tbytes, err := Encode(e, obj)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn string(bytes)\n}","line":{"from":74,"to":81}} {"id":100015309,"name":"UseOrCreateObject","signature":"func UseOrCreateObject(t ObjectTyper, c ObjectCreater, gvk schema.GroupVersionKind, obj Object) (Object, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"// UseOrCreateObject returns obj if the canonical ObjectKind returned by the provided typer matches gvk, or\n// invokes the ObjectCreator to instantiate a new gvk. Returns an error if the typer cannot find the object.\nfunc UseOrCreateObject(t ObjectTyper, c ObjectCreater, gvk schema.GroupVersionKind, obj Object) (Object, error) {\n\tif obj != nil {\n\t\tkinds, _, err := t.ObjectKinds(obj)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, kind := range kinds {\n\t\t\tif gvk == kind {\n\t\t\t\treturn obj, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn c.New(gvk)\n}","line":{"from":83,"to":98}} {"id":100015310,"name":"Encode","signature":"func (n NoopEncoder) Encode(obj Object, w io.Writer) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"func (n NoopEncoder) Encode(obj Object, w io.Writer) error {\n\t// There is no need to handle runtime.CacheableObject, as we don't\n\t// process the obj at all.\n\treturn fmt.Errorf(\"encoding is not allowed for this codec: %v\", reflect.TypeOf(n.Decoder))\n}","line":{"from":109,"to":113}} {"id":100015311,"name":"Identifier","signature":"func (n NoopEncoder) Identifier() Identifier","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"// Identifier implements runtime.Encoder interface.\nfunc (n NoopEncoder) Identifier() Identifier {\n\treturn noopEncoderIdentifier\n}","line":{"from":115,"to":118}} {"id":100015312,"name":"Decode","signature":"func (n NoopDecoder) Decode(data []byte, gvk *schema.GroupVersionKind, into Object) (Object, *schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"func (n NoopDecoder) Decode(data []byte, gvk *schema.GroupVersionKind, into Object) (Object, *schema.GroupVersionKind, error) {\n\treturn nil, nil, fmt.Errorf(\"decoding is not allowed for this codec: %v\", reflect.TypeOf(n.Encoder))\n}","line":{"from":127,"to":129}} {"id":100015313,"name":"NewParameterCodec","signature":"func NewParameterCodec(scheme *Scheme) ParameterCodec","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"// NewParameterCodec creates a ParameterCodec capable of transforming url values into versioned objects and back.\nfunc NewParameterCodec(scheme *Scheme) ParameterCodec {\n\treturn \u0026parameterCodec{\n\t\ttyper: scheme,\n\t\tconvertor: scheme,\n\t\tcreator: scheme,\n\t\tdefaulter: scheme,\n\t}\n}","line":{"from":131,"to":139}} {"id":100015314,"name":"DecodeParameters","signature":"func (c *parameterCodec) DecodeParameters(parameters url.Values, from schema.GroupVersion, into Object) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"// DecodeParameters converts the provided url.Values into an object of type From with the kind of into, and then\n// converts that object to into (if necessary). Returns an error if the operation cannot be completed.\nfunc (c *parameterCodec) DecodeParameters(parameters url.Values, from schema.GroupVersion, into Object) error {\n\tif len(parameters) == 0 {\n\t\treturn nil\n\t}\n\ttargetGVKs, _, err := c.typer.ObjectKinds(into)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor i := range targetGVKs {\n\t\tif targetGVKs[i].GroupVersion() == from {\n\t\t\tif err := c.convertor.Convert(\u0026parameters, into, nil); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// in the case where we going into the same object we're receiving, default on the outbound object\n\t\t\tif c.defaulter != nil {\n\t\t\t\tc.defaulter.Default(into)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tinput, err := c.creator.New(from.WithKind(targetGVKs[0].Kind))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := c.convertor.Convert(\u0026parameters, input, nil); err != nil {\n\t\treturn err\n\t}\n\t// if we have defaulter, default the input before converting to output\n\tif c.defaulter != nil {\n\t\tc.defaulter.Default(input)\n\t}\n\treturn c.convertor.Convert(input, into, nil)\n}","line":{"from":151,"to":186}} {"id":100015315,"name":"EncodeParameters","signature":"func (c *parameterCodec) EncodeParameters(obj Object, to schema.GroupVersion) (url.Values, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"// EncodeParameters converts the provided object into the to version, then converts that object to url.Values.\n// Returns an error if conversion is not possible.\nfunc (c *parameterCodec) EncodeParameters(obj Object, to schema.GroupVersion) (url.Values, error) {\n\tgvks, _, err := c.typer.ObjectKinds(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgvk := gvks[0]\n\tif to != gvk.GroupVersion() {\n\t\tout, err := c.convertor.ConvertToVersion(obj, to)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tobj = out\n\t}\n\treturn queryparams.Convert(obj)\n}","line":{"from":188,"to":204}} {"id":100015316,"name":"NewBase64Serializer","signature":"func NewBase64Serializer(e Encoder, d Decoder) Serializer","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"func NewBase64Serializer(e Encoder, d Decoder) Serializer {\n\treturn \u0026base64Serializer{\n\t\tEncoder: e,\n\t\tDecoder: d,\n\t\tidentifier: identifier(e),\n\t}\n}","line":{"from":213,"to":219}} {"id":100015317,"name":"identifier","signature":"func identifier(e Encoder) Identifier","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"func identifier(e Encoder) Identifier {\n\tresult := map[string]string{\n\t\t\"name\": \"base64\",\n\t}\n\tif e != nil {\n\t\tresult[\"encoder\"] = string(e.Identifier())\n\t}\n\tidentifier, err := json.Marshal(result)\n\tif err != nil {\n\t\tklog.Fatalf(\"Failed marshaling identifier for base64Serializer: %v\", err)\n\t}\n\treturn Identifier(identifier)\n}","line":{"from":221,"to":233}} {"id":100015318,"name":"Encode","signature":"func (s base64Serializer) Encode(obj Object, stream io.Writer) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"func (s base64Serializer) Encode(obj Object, stream io.Writer) error {\n\tif co, ok := obj.(CacheableObject); ok {\n\t\treturn co.CacheEncode(s.Identifier(), s.doEncode, stream)\n\t}\n\treturn s.doEncode(obj, stream)\n}","line":{"from":235,"to":240}} {"id":100015319,"name":"doEncode","signature":"func (s base64Serializer) doEncode(obj Object, stream io.Writer) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"func (s base64Serializer) doEncode(obj Object, stream io.Writer) error {\n\te := base64.NewEncoder(base64.StdEncoding, stream)\n\terr := s.Encoder.Encode(obj, e)\n\te.Close()\n\treturn err\n}","line":{"from":242,"to":247}} {"id":100015320,"name":"Identifier","signature":"func (s base64Serializer) Identifier() Identifier","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"// Identifier implements runtime.Encoder interface.\nfunc (s base64Serializer) Identifier() Identifier {\n\treturn s.identifier\n}","line":{"from":249,"to":252}} {"id":100015321,"name":"Decode","signature":"func (s base64Serializer) Decode(data []byte, defaults *schema.GroupVersionKind, into Object) (Object, *schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"func (s base64Serializer) Decode(data []byte, defaults *schema.GroupVersionKind, into Object) (Object, *schema.GroupVersionKind, error) {\n\tout := make([]byte, base64.StdEncoding.DecodedLen(len(data)))\n\tn, err := base64.StdEncoding.Decode(out, data)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn s.Decoder.Decode(out[:n], defaults, into)\n}","line":{"from":254,"to":261}} {"id":100015322,"name":"SerializerInfoForMediaType","signature":"func SerializerInfoForMediaType(types []SerializerInfo, mediaType string) (SerializerInfo, bool)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"// SerializerInfoForMediaType returns the first info in types that has a matching media type (which cannot\n// include media-type parameters), or the first info with an empty media type, or false if no type matches.\nfunc SerializerInfoForMediaType(types []SerializerInfo, mediaType string) (SerializerInfo, bool) {\n\tfor _, info := range types {\n\t\tif info.MediaType == mediaType {\n\t\t\treturn info, true\n\t\t}\n\t}\n\tfor _, info := range types {\n\t\tif len(info.MediaType) == 0 {\n\t\t\treturn info, true\n\t\t}\n\t}\n\treturn SerializerInfo{}, false\n}","line":{"from":263,"to":277}} {"id":100015323,"name":"KindForGroupVersionKinds","signature":"func (internalGroupVersioner) KindForGroupVersionKinds(kinds []schema.GroupVersionKind) (schema.GroupVersionKind, bool)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"// KindForGroupVersionKinds returns an internal Kind if one is found, or converts the first provided kind to the internal version.\nfunc (internalGroupVersioner) KindForGroupVersionKinds(kinds []schema.GroupVersionKind) (schema.GroupVersionKind, bool) {\n\tfor _, kind := range kinds {\n\t\tif kind.Version == APIVersionInternal {\n\t\t\treturn kind, true\n\t\t}\n\t}\n\tfor _, kind := range kinds {\n\t\treturn schema.GroupVersionKind{Group: kind.Group, Version: APIVersionInternal, Kind: kind.Kind}, true\n\t}\n\treturn schema.GroupVersionKind{}, false\n}","line":{"from":293,"to":304}} {"id":100015324,"name":"Identifier","signature":"func (internalGroupVersioner) Identifier() string","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"// Identifier implements GroupVersioner interface.\nfunc (internalGroupVersioner) Identifier() string {\n\treturn internalGroupVersionerIdentifier\n}","line":{"from":306,"to":309}} {"id":100015325,"name":"KindForGroupVersionKinds","signature":"func (disabledGroupVersioner) KindForGroupVersionKinds(kinds []schema.GroupVersionKind) (schema.GroupVersionKind, bool)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"// KindForGroupVersionKinds returns false for any input.\nfunc (disabledGroupVersioner) KindForGroupVersionKinds(kinds []schema.GroupVersionKind) (schema.GroupVersionKind, bool) {\n\treturn schema.GroupVersionKind{}, false\n}","line":{"from":313,"to":316}} {"id":100015326,"name":"Identifier","signature":"func (disabledGroupVersioner) Identifier() string","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"// Identifier implements GroupVersioner interface.\nfunc (disabledGroupVersioner) Identifier() string {\n\treturn disabledGroupVersionerIdentifier\n}","line":{"from":318,"to":321}} {"id":100015327,"name":"NewMultiGroupVersioner","signature":"func NewMultiGroupVersioner(gv schema.GroupVersion, groupKinds ...schema.GroupKind) GroupVersioner","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"// NewMultiGroupVersioner returns the provided group version for any kind that matches one of the provided group kinds.\n// Kind may be empty in the provided group kind, in which case any kind will match.\nfunc NewMultiGroupVersioner(gv schema.GroupVersion, groupKinds ...schema.GroupKind) GroupVersioner {\n\tif len(groupKinds) == 0 || (len(groupKinds) == 1 \u0026\u0026 groupKinds[0].Group == gv.Group) {\n\t\treturn gv\n\t}\n\treturn multiGroupVersioner{target: gv, acceptedGroupKinds: groupKinds}\n}","line":{"from":334,"to":341}} {"id":100015328,"name":"NewCoercingMultiGroupVersioner","signature":"func NewCoercingMultiGroupVersioner(gv schema.GroupVersion, groupKinds ...schema.GroupKind) GroupVersioner","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"// NewCoercingMultiGroupVersioner returns the provided group version for any incoming kind.\n// Incoming kinds that match the provided groupKinds are preferred.\n// Kind may be empty in the provided group kind, in which case any kind will match.\n// Examples:\n//\n//\tgv=mygroup/__internal, groupKinds=mygroup/Foo, anothergroup/Bar\n//\tKindForGroupVersionKinds(yetanother/v1/Baz, anothergroup/v1/Bar) -\u003e mygroup/__internal/Bar (matched preferred group/kind)\n//\n//\tgv=mygroup/__internal, groupKinds=mygroup, anothergroup\n//\tKindForGroupVersionKinds(yetanother/v1/Baz, anothergroup/v1/Bar) -\u003e mygroup/__internal/Bar (matched preferred group)\n//\n//\tgv=mygroup/__internal, groupKinds=mygroup, anothergroup\n//\tKindForGroupVersionKinds(yetanother/v1/Baz, yetanother/v1/Bar) -\u003e mygroup/__internal/Baz (no preferred group/kind match, uses first kind in list)\nfunc NewCoercingMultiGroupVersioner(gv schema.GroupVersion, groupKinds ...schema.GroupKind) GroupVersioner {\n\treturn multiGroupVersioner{target: gv, acceptedGroupKinds: groupKinds, coerce: true}\n}","line":{"from":343,"to":358}} {"id":100015329,"name":"KindForGroupVersionKinds","signature":"func (v multiGroupVersioner) KindForGroupVersionKinds(kinds []schema.GroupVersionKind) (schema.GroupVersionKind, bool)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"// KindForGroupVersionKinds returns the target group version if any kind matches any of the original group kinds. It will\n// use the originating kind where possible.\nfunc (v multiGroupVersioner) KindForGroupVersionKinds(kinds []schema.GroupVersionKind) (schema.GroupVersionKind, bool) {\n\tfor _, src := range kinds {\n\t\tfor _, kind := range v.acceptedGroupKinds {\n\t\t\tif kind.Group != src.Group {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(kind.Kind) \u003e 0 \u0026\u0026 kind.Kind != src.Kind {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn v.target.WithKind(src.Kind), true\n\t\t}\n\t}\n\tif v.coerce \u0026\u0026 len(kinds) \u003e 0 {\n\t\treturn v.target.WithKind(kinds[0].Kind), true\n\t}\n\treturn schema.GroupVersionKind{}, false\n}","line":{"from":360,"to":378}} {"id":100015330,"name":"Identifier","signature":"func (v multiGroupVersioner) Identifier() string","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec.go","code":"// Identifier implements GroupVersioner interface.\nfunc (v multiGroupVersioner) Identifier() string {\n\tgroupKinds := make([]string, 0, len(v.acceptedGroupKinds))\n\tfor _, gk := range v.acceptedGroupKinds {\n\t\tgroupKinds = append(groupKinds, gk.String())\n\t}\n\tresult := map[string]string{\n\t\t\"name\": \"multi\",\n\t\t\"target\": v.target.String(),\n\t\t\"accepted\": strings.Join(groupKinds, \",\"),\n\t\t\"coerce\": strconv.FormatBool(v.coerce),\n\t}\n\tidentifier, err := json.Marshal(result)\n\tif err != nil {\n\t\tklog.Fatalf(\"Failed marshaling Identifier for %#v: %v\", v, err)\n\t}\n\treturn string(identifier)\n}","line":{"from":380,"to":397}} {"id":100015331,"name":"CheckCodec","signature":"func CheckCodec(c Codec, internalType Object, externalTypes ...schema.GroupVersionKind) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/codec_check.go","code":"// CheckCodec makes sure that the codec can encode objects like internalType,\n// decode all of the external types listed, and also decode them into the given\n// object. (Will modify internalObject.) (Assumes JSON serialization.)\n// TODO: verify that the correct external version is chosen on encode...\nfunc CheckCodec(c Codec, internalType Object, externalTypes ...schema.GroupVersionKind) error {\n\tif _, err := Encode(c, internalType); err != nil {\n\t\treturn fmt.Errorf(\"internal type not encodable: %v\", err)\n\t}\n\tfor _, et := range externalTypes {\n\t\ttypeMeta := TypeMeta{\n\t\t\tKind: et.Kind,\n\t\t\tAPIVersion: et.GroupVersion().String(),\n\t\t}\n\t\texBytes, err := json.Marshal(\u0026typeMeta)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tobj, err := Decode(c, exBytes)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"external type %s not interpretable: %v\", et, err)\n\t\t}\n\t\tif reflect.TypeOf(obj) != reflect.TypeOf(internalType) {\n\t\t\treturn fmt.Errorf(\"decode of external type %s produced: %#v\", et, obj)\n\t\t}\n\t\tif err = DecodeInto(c, exBytes, internalType); err != nil {\n\t\t\treturn fmt.Errorf(\"external type %s not convertible to internal type: %v\", et, err)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":27,"to":56}} {"id":100015332,"name":"DefaultMetaV1FieldSelectorConversion","signature":"func DefaultMetaV1FieldSelectorConversion(label, value string) (string, string, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/conversion.go","code":"// DefaultMetaV1FieldSelectorConversion auto-accepts metav1 values for name and namespace.\n// A cluster scoped resource specifying namespace empty works fine and specifying a particular\n// namespace will return no results, as expected.\nfunc DefaultMetaV1FieldSelectorConversion(label, value string) (string, string, error) {\n\tswitch label {\n\tcase \"metadata.name\":\n\t\treturn label, value, nil\n\tcase \"metadata.namespace\":\n\t\treturn label, value, nil\n\tdefault:\n\t\treturn \"\", \"\", fmt.Errorf(\"%q is not a known field selector: only %q, %q\", label, \"metadata.name\", \"metadata.namespace\")\n\t}\n}","line":{"from":30,"to":42}} {"id":100015333,"name":"JSONKeyMapper","signature":"func JSONKeyMapper(key string, sourceTag, destTag reflect.StructTag) (string, string)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/conversion.go","code":"// JSONKeyMapper uses the struct tags on a conversion to determine the key value for\n// the other side. Use when mapping from a map[string]* to a struct or vice versa.\nfunc JSONKeyMapper(key string, sourceTag, destTag reflect.StructTag) (string, string) {\n\tif s := destTag.Get(\"json\"); len(s) \u003e 0 {\n\t\treturn strings.SplitN(s, \",\", 2)[0], key\n\t}\n\tif s := sourceTag.Get(\"json\"); len(s) \u003e 0 {\n\t\treturn key, strings.SplitN(s, \",\", 2)[0]\n\t}\n\treturn key, key\n}","line":{"from":44,"to":54}} {"id":100015334,"name":"Convert_Slice_string_To_string","signature":"func Convert_Slice_string_To_string(in *[]string, out *string, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/conversion.go","code":"func Convert_Slice_string_To_string(in *[]string, out *string, s conversion.Scope) error {\n\tif len(*in) == 0 {\n\t\t*out = \"\"\n\t\treturn nil\n\t}\n\t*out = (*in)[0]\n\treturn nil\n}","line":{"from":56,"to":63}} {"id":100015335,"name":"Convert_Slice_string_To_int","signature":"func Convert_Slice_string_To_int(in *[]string, out *int, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/conversion.go","code":"func Convert_Slice_string_To_int(in *[]string, out *int, s conversion.Scope) error {\n\tif len(*in) == 0 {\n\t\t*out = 0\n\t\treturn nil\n\t}\n\tstr := (*in)[0]\n\ti, err := strconv.Atoi(str)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*out = i\n\treturn nil\n}","line":{"from":65,"to":77}} {"id":100015336,"name":"Convert_Slice_string_To_bool","signature":"func Convert_Slice_string_To_bool(in *[]string, out *bool, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/conversion.go","code":"// Convert_Slice_string_To_bool will convert a string parameter to boolean.\n// Only the absence of a value (i.e. zero-length slice), a value of \"false\", or a\n// value of \"0\" resolve to false.\n// Any other value (including empty string) resolves to true.\nfunc Convert_Slice_string_To_bool(in *[]string, out *bool, s conversion.Scope) error {\n\tif len(*in) == 0 {\n\t\t*out = false\n\t\treturn nil\n\t}\n\tswitch {\n\tcase (*in)[0] == \"0\", strings.EqualFold((*in)[0], \"false\"):\n\t\t*out = false\n\tdefault:\n\t\t*out = true\n\t}\n\treturn nil\n}","line":{"from":79,"to":95}} {"id":100015337,"name":"Convert_Slice_string_To_Pointer_bool","signature":"func Convert_Slice_string_To_Pointer_bool(in *[]string, out **bool, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/conversion.go","code":"// Convert_Slice_string_To_bool will convert a string parameter to boolean.\n// Only the absence of a value (i.e. zero-length slice), a value of \"false\", or a\n// value of \"0\" resolve to false.\n// Any other value (including empty string) resolves to true.\nfunc Convert_Slice_string_To_Pointer_bool(in *[]string, out **bool, s conversion.Scope) error {\n\tif len(*in) == 0 {\n\t\tboolVar := false\n\t\t*out = \u0026boolVar\n\t\treturn nil\n\t}\n\tswitch {\n\tcase (*in)[0] == \"0\", strings.EqualFold((*in)[0], \"false\"):\n\t\tboolVar := false\n\t\t*out = \u0026boolVar\n\tdefault:\n\t\tboolVar := true\n\t\t*out = \u0026boolVar\n\t}\n\treturn nil\n}","line":{"from":97,"to":116}} {"id":100015338,"name":"string_to_int64","signature":"func string_to_int64(in string) (int64, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/conversion.go","code":"func string_to_int64(in string) (int64, error) {\n\treturn strconv.ParseInt(in, 10, 64)\n}","line":{"from":118,"to":120}} {"id":100015339,"name":"Convert_string_To_int64","signature":"func Convert_string_To_int64(in *string, out *int64, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/conversion.go","code":"func Convert_string_To_int64(in *string, out *int64, s conversion.Scope) error {\n\tif in == nil {\n\t\t*out = 0\n\t\treturn nil\n\t}\n\ti, err := string_to_int64(*in)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*out = i\n\treturn nil\n}","line":{"from":122,"to":133}} {"id":100015340,"name":"Convert_Slice_string_To_int64","signature":"func Convert_Slice_string_To_int64(in *[]string, out *int64, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/conversion.go","code":"func Convert_Slice_string_To_int64(in *[]string, out *int64, s conversion.Scope) error {\n\tif len(*in) == 0 {\n\t\t*out = 0\n\t\treturn nil\n\t}\n\ti, err := string_to_int64((*in)[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\t*out = i\n\treturn nil\n}","line":{"from":135,"to":146}} {"id":100015341,"name":"Convert_string_To_Pointer_int64","signature":"func Convert_string_To_Pointer_int64(in *string, out **int64, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/conversion.go","code":"func Convert_string_To_Pointer_int64(in *string, out **int64, s conversion.Scope) error {\n\tif in == nil {\n\t\t*out = nil\n\t\treturn nil\n\t}\n\ti, err := string_to_int64(*in)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*out = \u0026i\n\treturn nil\n}","line":{"from":148,"to":159}} {"id":100015342,"name":"Convert_Slice_string_To_Pointer_int64","signature":"func Convert_Slice_string_To_Pointer_int64(in *[]string, out **int64, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/conversion.go","code":"func Convert_Slice_string_To_Pointer_int64(in *[]string, out **int64, s conversion.Scope) error {\n\tif len(*in) == 0 {\n\t\t*out = nil\n\t\treturn nil\n\t}\n\ti, err := string_to_int64((*in)[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\t*out = \u0026i\n\treturn nil\n}","line":{"from":161,"to":172}} {"id":100015343,"name":"RegisterStringConversions","signature":"func RegisterStringConversions(s *Scheme) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/conversion.go","code":"func RegisterStringConversions(s *Scheme) error {\n\tif err := s.AddConversionFunc((*[]string)(nil), (*string)(nil), func(a, b interface{}, scope conversion.Scope) error {\n\t\treturn Convert_Slice_string_To_string(a.(*[]string), b.(*string), scope)\n\t}); err != nil {\n\t\treturn err\n\t}\n\tif err := s.AddConversionFunc((*[]string)(nil), (*int)(nil), func(a, b interface{}, scope conversion.Scope) error {\n\t\treturn Convert_Slice_string_To_int(a.(*[]string), b.(*int), scope)\n\t}); err != nil {\n\t\treturn err\n\t}\n\tif err := s.AddConversionFunc((*[]string)(nil), (*bool)(nil), func(a, b interface{}, scope conversion.Scope) error {\n\t\treturn Convert_Slice_string_To_bool(a.(*[]string), b.(*bool), scope)\n\t}); err != nil {\n\t\treturn err\n\t}\n\tif err := s.AddConversionFunc((*[]string)(nil), (*int64)(nil), func(a, b interface{}, scope conversion.Scope) error {\n\t\treturn Convert_Slice_string_To_int64(a.(*[]string), b.(*int64), scope)\n\t}); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":174,"to":196}} {"id":100015344,"name":"newFieldsCache","signature":"func newFieldsCache() *fieldsCache","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"func newFieldsCache() *fieldsCache {\n\tcache := \u0026fieldsCache{}\n\tcache.value.Store(make(fieldsCacheMap))\n\treturn cache\n}","line":{"from":65,"to":69}} {"id":100015345,"name":"parseBool","signature":"func parseBool(key string) bool","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"func parseBool(key string) bool {\n\tif len(key) == 0 {\n\t\treturn false\n\t}\n\tvalue, err := strconv.ParseBool(key)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't parse '%s' as bool for unstructured mismatch detection\", key))\n\t}\n\treturn value\n}","line":{"from":87,"to":96}} {"id":100015346,"name":"NewTestUnstructuredConverter","signature":"func NewTestUnstructuredConverter(comparison conversion.Equalities) UnstructuredConverter","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"// NewTestUnstructuredConverter creates an UnstructuredConverter that accepts JSON typed maps and translates them\n// to Go types via reflection. It performs mismatch detection automatically and is intended for use by external\n// test tools. Use DefaultUnstructuredConverter if you do not explicitly need mismatch detection.\nfunc NewTestUnstructuredConverter(comparison conversion.Equalities) UnstructuredConverter {\n\treturn NewTestUnstructuredConverterWithValidation(comparison)\n}","line":{"from":109,"to":114}} {"id":100015347,"name":"NewTestUnstructuredConverterWithValidation","signature":"func NewTestUnstructuredConverterWithValidation(comparison conversion.Equalities) *unstructuredConverter","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"// NewTestUnstrucutredConverterWithValidation allows for access to\n// FromUnstructuredWithValidation from within tests.\nfunc NewTestUnstructuredConverterWithValidation(comparison conversion.Equalities) *unstructuredConverter {\n\treturn \u0026unstructuredConverter{\n\t\tmismatchDetection: true,\n\t\tcomparison: comparison,\n\t}\n}","line":{"from":116,"to":123}} {"id":100015348,"name":"pushMatchedKeyTracker","signature":"func (c *fromUnstructuredContext) pushMatchedKeyTracker()","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"// pushMatchedKeyTracker adds a placeholder set for tracking\n// matched keys for the given level. This should only be\n// called from `structFromUnstructured`.\nfunc (c *fromUnstructuredContext) pushMatchedKeyTracker() {\n\tif !c.returnUnknownFields {\n\t\treturn\n\t}\n\n\tc.matchedKeys = append(c.matchedKeys, nil)\n}","line":{"from":153,"to":162}} {"id":100015349,"name":"recordMatchedKey","signature":"func (c *fromUnstructuredContext) recordMatchedKey(key string)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"// recordMatchedKey initializes the last element of matchedKeys\n// (if needed) and sets 'key'. This should only be called from\n// `structFromUnstructured`.\nfunc (c *fromUnstructuredContext) recordMatchedKey(key string) {\n\tif !c.returnUnknownFields {\n\t\treturn\n\t}\n\n\tlast := len(c.matchedKeys) - 1\n\tif c.matchedKeys[last] == nil {\n\t\tc.matchedKeys[last] = map[string]struct{}{}\n\t}\n\tc.matchedKeys[last][key] = struct{}{}\n}","line":{"from":164,"to":177}} {"id":100015350,"name":"popAndVerifyMatchedKeys","signature":"func (c *fromUnstructuredContext) popAndVerifyMatchedKeys(mapValue reflect.Value)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"// popAndVerifyMatchedKeys pops the last element of matchedKeys,\n// checks the matched keys against the data, and adds unknown\n// field errors for any matched keys.\n// `mapValue` is the value of sv containing all of the keys that exist at this level\n// (ie. sv.MapKeys) in the source data.\n// `matchedKeys` are all the keys found for that level in the destination object.\n// This should only be called from `structFromUnstructured`.\nfunc (c *fromUnstructuredContext) popAndVerifyMatchedKeys(mapValue reflect.Value) {\n\tif !c.returnUnknownFields {\n\t\treturn\n\t}\n\n\tlast := len(c.matchedKeys) - 1\n\tcurMatchedKeys := c.matchedKeys[last]\n\tc.matchedKeys[last] = nil\n\tc.matchedKeys = c.matchedKeys[:last]\n\tfor _, key := range mapValue.MapKeys() {\n\t\tif _, ok := curMatchedKeys[key.String()]; !ok {\n\t\t\tc.recordUnknownField(key.String())\n\t\t}\n\t}\n}","line":{"from":179,"to":200}} {"id":100015351,"name":"recordUnknownField","signature":"func (c *fromUnstructuredContext) recordUnknownField(field string)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"func (c *fromUnstructuredContext) recordUnknownField(field string) {\n\tif !c.returnUnknownFields {\n\t\treturn\n\t}\n\n\tpathLen := len(c.parentPath)\n\tc.pushKey(field)\n\terrPath := strings.Join(c.parentPath, \"\")\n\tc.parentPath = c.parentPath[:pathLen]\n\tc.unknownFieldErrors = append(c.unknownFieldErrors, fmt.Errorf(`unknown field \"%s\"`, errPath))\n}","line":{"from":202,"to":212}} {"id":100015352,"name":"pushIndex","signature":"func (c *fromUnstructuredContext) pushIndex(index int)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"func (c *fromUnstructuredContext) pushIndex(index int) {\n\tif !c.returnUnknownFields {\n\t\treturn\n\t}\n\n\tc.parentPath = append(c.parentPath, \"[\", strconv.Itoa(index), \"]\")\n}","line":{"from":214,"to":220}} {"id":100015353,"name":"pushKey","signature":"func (c *fromUnstructuredContext) pushKey(key string)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"func (c *fromUnstructuredContext) pushKey(key string) {\n\tif !c.returnUnknownFields {\n\t\treturn\n\t}\n\n\tif len(c.parentPath) \u003e 0 {\n\t\tc.parentPath = append(c.parentPath, \".\")\n\t}\n\tc.parentPath = append(c.parentPath, key)\n\n}","line":{"from":222,"to":232}} {"id":100015354,"name":"FromUnstructuredWithValidation","signature":"func (c *unstructuredConverter) FromUnstructuredWithValidation(u map[string]interface{}, obj interface{}, returnUnknownFields bool) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"// FromUnstructuredWithValidation converts an object from map[string]interface{} representation into a concrete type.\n// It uses encoding/json/Unmarshaler if object implements it or reflection if not.\n// It takes a validationDirective that indicates how to behave when it encounters unknown fields.\nfunc (c *unstructuredConverter) FromUnstructuredWithValidation(u map[string]interface{}, obj interface{}, returnUnknownFields bool) error {\n\tt := reflect.TypeOf(obj)\n\tvalue := reflect.ValueOf(obj)\n\tif t.Kind() != reflect.Pointer || value.IsNil() {\n\t\treturn fmt.Errorf(\"FromUnstructured requires a non-nil pointer to an object, got %v\", t)\n\t}\n\n\tfromUnstructuredContext := \u0026fromUnstructuredContext{\n\t\treturnUnknownFields: returnUnknownFields,\n\t}\n\terr := fromUnstructured(reflect.ValueOf(u), value.Elem(), fromUnstructuredContext)\n\tif c.mismatchDetection {\n\t\tnewObj := reflect.New(t.Elem()).Interface()\n\t\tnewErr := fromUnstructuredViaJSON(u, newObj)\n\t\tif (err != nil) != (newErr != nil) {\n\t\t\tklog.Fatalf(\"FromUnstructured unexpected error for %v: error: %v\", u, err)\n\t\t}\n\t\tif err == nil \u0026\u0026 !c.comparison.DeepEqual(obj, newObj) {\n\t\t\tklog.Fatalf(\"FromUnstructured mismatch\\nobj1: %#v\\nobj2: %#v\", obj, newObj)\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tif returnUnknownFields \u0026\u0026 len(fromUnstructuredContext.unknownFieldErrors) \u003e 0 {\n\t\tsort.Slice(fromUnstructuredContext.unknownFieldErrors, func(i, j int) bool {\n\t\t\treturn fromUnstructuredContext.unknownFieldErrors[i].Error() \u003c\n\t\t\t\tfromUnstructuredContext.unknownFieldErrors[j].Error()\n\t\t})\n\t\treturn NewStrictDecodingError(fromUnstructuredContext.unknownFieldErrors)\n\t}\n\treturn nil\n}","line":{"from":234,"to":269}} {"id":100015355,"name":"FromUnstructured","signature":"func (c *unstructuredConverter) FromUnstructured(u map[string]interface{}, obj interface{}) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"// FromUnstructured converts an object from map[string]interface{} representation into a concrete type.\n// It uses encoding/json/Unmarshaler if object implements it or reflection if not.\nfunc (c *unstructuredConverter) FromUnstructured(u map[string]interface{}, obj interface{}) error {\n\treturn c.FromUnstructuredWithValidation(u, obj, false)\n}","line":{"from":271,"to":275}} {"id":100015356,"name":"fromUnstructuredViaJSON","signature":"func fromUnstructuredViaJSON(u map[string]interface{}, obj interface{}) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"func fromUnstructuredViaJSON(u map[string]interface{}, obj interface{}) error {\n\tdata, err := json.Marshal(u)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn json.Unmarshal(data, obj)\n}","line":{"from":277,"to":283}} {"id":100015357,"name":"fromUnstructured","signature":"func fromUnstructured(sv, dv reflect.Value, ctx *fromUnstructuredContext) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"func fromUnstructured(sv, dv reflect.Value, ctx *fromUnstructuredContext) error {\n\tsv = unwrapInterface(sv)\n\tif !sv.IsValid() {\n\t\tdv.Set(reflect.Zero(dv.Type()))\n\t\treturn nil\n\t}\n\tst, dt := sv.Type(), dv.Type()\n\n\tswitch dt.Kind() {\n\tcase reflect.Map, reflect.Slice, reflect.Pointer, reflect.Struct, reflect.Interface:\n\t\t// Those require non-trivial conversion.\n\tdefault:\n\t\t// This should handle all simple types.\n\t\tif st.AssignableTo(dt) {\n\t\t\tdv.Set(sv)\n\t\t\treturn nil\n\t\t}\n\t\t// We cannot simply use \"ConvertibleTo\", as JSON doesn't support conversions\n\t\t// between those four groups: bools, integers, floats and string. We need to\n\t\t// do the same.\n\t\tif st.ConvertibleTo(dt) {\n\t\t\tswitch st.Kind() {\n\t\t\tcase reflect.String:\n\t\t\t\tswitch dt.Kind() {\n\t\t\t\tcase reflect.String:\n\t\t\t\t\tdv.Set(sv.Convert(dt))\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\tcase reflect.Bool:\n\t\t\t\tswitch dt.Kind() {\n\t\t\t\tcase reflect.Bool:\n\t\t\t\t\tdv.Set(sv.Convert(dt))\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,\n\t\t\t\treflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\t\t\tswitch dt.Kind() {\n\t\t\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,\n\t\t\t\t\treflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\t\t\t\tdv.Set(sv.Convert(dt))\n\t\t\t\t\treturn nil\n\t\t\t\tcase reflect.Float32, reflect.Float64:\n\t\t\t\t\tdv.Set(sv.Convert(dt))\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\tcase reflect.Float32, reflect.Float64:\n\t\t\t\tswitch dt.Kind() {\n\t\t\t\tcase reflect.Float32, reflect.Float64:\n\t\t\t\t\tdv.Set(sv.Convert(dt))\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\tif sv.Float() == math.Trunc(sv.Float()) {\n\t\t\t\t\tdv.Set(sv.Convert(dt))\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"cannot convert %s to %s\", st.String(), dt.String())\n\t\t}\n\t}\n\n\t// Check if the object has a custom JSON marshaller/unmarshaller.\n\tentry := value.TypeReflectEntryOf(dv.Type())\n\tif entry.CanConvertFromUnstructured() {\n\t\treturn entry.FromUnstructured(sv, dv)\n\t}\n\n\tswitch dt.Kind() {\n\tcase reflect.Map:\n\t\treturn mapFromUnstructured(sv, dv, ctx)\n\tcase reflect.Slice:\n\t\treturn sliceFromUnstructured(sv, dv, ctx)\n\tcase reflect.Pointer:\n\t\treturn pointerFromUnstructured(sv, dv, ctx)\n\tcase reflect.Struct:\n\t\treturn structFromUnstructured(sv, dv, ctx)\n\tcase reflect.Interface:\n\t\treturn interfaceFromUnstructured(sv, dv)\n\tdefault:\n\t\treturn fmt.Errorf(\"unrecognized type: %v\", dt.Kind())\n\t}\n\n}","line":{"from":285,"to":366}} {"id":100015358,"name":"fieldInfoFromField","signature":"func fieldInfoFromField(structType reflect.Type, field int) *fieldInfo","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"func fieldInfoFromField(structType reflect.Type, field int) *fieldInfo {\n\tfieldCacheMap := fieldCache.value.Load().(fieldsCacheMap)\n\tif info, ok := fieldCacheMap[structField{structType, field}]; ok {\n\t\treturn info\n\t}\n\n\t// Cache miss - we need to compute the field name.\n\tinfo := \u0026fieldInfo{}\n\ttypeField := structType.Field(field)\n\tjsonTag := typeField.Tag.Get(\"json\")\n\tif len(jsonTag) == 0 {\n\t\t// Make the first character lowercase.\n\t\tif typeField.Name == \"\" {\n\t\t\tinfo.name = typeField.Name\n\t\t} else {\n\t\t\tinfo.name = strings.ToLower(typeField.Name[:1]) + typeField.Name[1:]\n\t\t}\n\t} else {\n\t\titems := strings.Split(jsonTag, \",\")\n\t\tinfo.name = items[0]\n\t\tfor i := range items {\n\t\t\tif items[i] == \"omitempty\" {\n\t\t\t\tinfo.omitempty = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tinfo.nameValue = reflect.ValueOf(info.name)\n\n\tfieldCache.Lock()\n\tdefer fieldCache.Unlock()\n\tfieldCacheMap = fieldCache.value.Load().(fieldsCacheMap)\n\tnewFieldCacheMap := make(fieldsCacheMap)\n\tfor k, v := range fieldCacheMap {\n\t\tnewFieldCacheMap[k] = v\n\t}\n\tnewFieldCacheMap[structField{structType, field}] = info\n\tfieldCache.value.Store(newFieldCacheMap)\n\treturn info\n}","line":{"from":368,"to":407}} {"id":100015359,"name":"unwrapInterface","signature":"func unwrapInterface(v reflect.Value) reflect.Value","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"func unwrapInterface(v reflect.Value) reflect.Value {\n\tfor v.Kind() == reflect.Interface {\n\t\tv = v.Elem()\n\t}\n\treturn v\n}","line":{"from":409,"to":414}} {"id":100015360,"name":"mapFromUnstructured","signature":"func mapFromUnstructured(sv, dv reflect.Value, ctx *fromUnstructuredContext) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"func mapFromUnstructured(sv, dv reflect.Value, ctx *fromUnstructuredContext) error {\n\tst, dt := sv.Type(), dv.Type()\n\tif st.Kind() != reflect.Map {\n\t\treturn fmt.Errorf(\"cannot restore map from %v\", st.Kind())\n\t}\n\n\tif !st.Key().AssignableTo(dt.Key()) \u0026\u0026 !st.Key().ConvertibleTo(dt.Key()) {\n\t\treturn fmt.Errorf(\"cannot copy map with non-assignable keys: %v %v\", st.Key(), dt.Key())\n\t}\n\n\tif sv.IsNil() {\n\t\tdv.Set(reflect.Zero(dt))\n\t\treturn nil\n\t}\n\tdv.Set(reflect.MakeMap(dt))\n\tfor _, key := range sv.MapKeys() {\n\t\tvalue := reflect.New(dt.Elem()).Elem()\n\t\tif val := unwrapInterface(sv.MapIndex(key)); val.IsValid() {\n\t\t\tif err := fromUnstructured(val, value, ctx); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tvalue.Set(reflect.Zero(dt.Elem()))\n\t\t}\n\t\tif st.Key().AssignableTo(dt.Key()) {\n\t\t\tdv.SetMapIndex(key, value)\n\t\t} else {\n\t\t\tdv.SetMapIndex(key.Convert(dt.Key()), value)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":416,"to":447}} {"id":100015361,"name":"sliceFromUnstructured","signature":"func sliceFromUnstructured(sv, dv reflect.Value, ctx *fromUnstructuredContext) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"func sliceFromUnstructured(sv, dv reflect.Value, ctx *fromUnstructuredContext) error {\n\tst, dt := sv.Type(), dv.Type()\n\tif st.Kind() == reflect.String \u0026\u0026 dt.Elem().Kind() == reflect.Uint8 {\n\t\t// We store original []byte representation as string.\n\t\t// This conversion is allowed, but we need to be careful about\n\t\t// marshaling data appropriately.\n\t\tif len(sv.Interface().(string)) \u003e 0 {\n\t\t\tmarshalled, err := json.Marshal(sv.Interface())\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error encoding %s to json: %v\", st, err)\n\t\t\t}\n\t\t\t// TODO: Is this Unmarshal needed?\n\t\t\tvar data []byte\n\t\t\terr = json.Unmarshal(marshalled, \u0026data)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error decoding from json: %v\", err)\n\t\t\t}\n\t\t\tdv.SetBytes(data)\n\t\t} else {\n\t\t\tdv.Set(reflect.MakeSlice(dt, 0, 0))\n\t\t}\n\t\treturn nil\n\t}\n\tif st.Kind() != reflect.Slice {\n\t\treturn fmt.Errorf(\"cannot restore slice from %v\", st.Kind())\n\t}\n\n\tif sv.IsNil() {\n\t\tdv.Set(reflect.Zero(dt))\n\t\treturn nil\n\t}\n\tdv.Set(reflect.MakeSlice(dt, sv.Len(), sv.Cap()))\n\n\tpathLen := len(ctx.parentPath)\n\tdefer func() {\n\t\tctx.parentPath = ctx.parentPath[:pathLen]\n\t}()\n\tfor i := 0; i \u003c sv.Len(); i++ {\n\t\tctx.pushIndex(i)\n\t\tif err := fromUnstructured(sv.Index(i), dv.Index(i), ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tctx.parentPath = ctx.parentPath[:pathLen]\n\t}\n\treturn nil\n}","line":{"from":449,"to":494}} {"id":100015362,"name":"pointerFromUnstructured","signature":"func pointerFromUnstructured(sv, dv reflect.Value, ctx *fromUnstructuredContext) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"func pointerFromUnstructured(sv, dv reflect.Value, ctx *fromUnstructuredContext) error {\n\tst, dt := sv.Type(), dv.Type()\n\n\tif st.Kind() == reflect.Pointer \u0026\u0026 sv.IsNil() {\n\t\tdv.Set(reflect.Zero(dt))\n\t\treturn nil\n\t}\n\tdv.Set(reflect.New(dt.Elem()))\n\tswitch st.Kind() {\n\tcase reflect.Pointer, reflect.Interface:\n\t\treturn fromUnstructured(sv.Elem(), dv.Elem(), ctx)\n\tdefault:\n\t\treturn fromUnstructured(sv, dv.Elem(), ctx)\n\t}\n}","line":{"from":496,"to":510}} {"id":100015363,"name":"structFromUnstructured","signature":"func structFromUnstructured(sv, dv reflect.Value, ctx *fromUnstructuredContext) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"func structFromUnstructured(sv, dv reflect.Value, ctx *fromUnstructuredContext) error {\n\tst, dt := sv.Type(), dv.Type()\n\tif st.Kind() != reflect.Map {\n\t\treturn fmt.Errorf(\"cannot restore struct from: %v\", st.Kind())\n\t}\n\n\tpathLen := len(ctx.parentPath)\n\tsvInlined := ctx.isInlined\n\tdefer func() {\n\t\tctx.parentPath = ctx.parentPath[:pathLen]\n\t\tctx.isInlined = svInlined\n\t}()\n\tif !svInlined {\n\t\tctx.pushMatchedKeyTracker()\n\t}\n\tfor i := 0; i \u003c dt.NumField(); i++ {\n\t\tfieldInfo := fieldInfoFromField(dt, i)\n\t\tfv := dv.Field(i)\n\n\t\tif len(fieldInfo.name) == 0 {\n\t\t\t// This field is inlined, recurse into fromUnstructured again\n\t\t\t// with the same set of matched keys.\n\t\t\tctx.isInlined = true\n\t\t\tif err := fromUnstructured(sv, fv, ctx); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tctx.isInlined = svInlined\n\t\t} else {\n\t\t\t// This field is not inlined so we recurse into\n\t\t\t// child field of sv corresponding to field i of\n\t\t\t// dv, with a new set of matchedKeys and updating\n\t\t\t// the parentPath to indicate that we are one level\n\t\t\t// deeper.\n\t\t\tctx.recordMatchedKey(fieldInfo.name)\n\t\t\tvalue := unwrapInterface(sv.MapIndex(fieldInfo.nameValue))\n\t\t\tif value.IsValid() {\n\t\t\t\tctx.isInlined = false\n\t\t\t\tctx.pushKey(fieldInfo.name)\n\t\t\t\tif err := fromUnstructured(value, fv, ctx); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tctx.parentPath = ctx.parentPath[:pathLen]\n\t\t\t\tctx.isInlined = svInlined\n\t\t\t} else {\n\t\t\t\tfv.Set(reflect.Zero(fv.Type()))\n\t\t\t}\n\t\t}\n\t}\n\tif !svInlined {\n\t\tctx.popAndVerifyMatchedKeys(sv)\n\t}\n\treturn nil\n}","line":{"from":512,"to":564}} {"id":100015364,"name":"interfaceFromUnstructured","signature":"func interfaceFromUnstructured(sv, dv reflect.Value) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"func interfaceFromUnstructured(sv, dv reflect.Value) error {\n\t// TODO: Is this conversion safe?\n\tdv.Set(sv)\n\treturn nil\n}","line":{"from":566,"to":570}} {"id":100015365,"name":"ToUnstructured","signature":"func (c *unstructuredConverter) ToUnstructured(obj interface{}) (map[string]interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"// ToUnstructured converts an object into map[string]interface{} representation.\n// It uses encoding/json/Marshaler if object implements it or reflection if not.\nfunc (c *unstructuredConverter) ToUnstructured(obj interface{}) (map[string]interface{}, error) {\n\tvar u map[string]interface{}\n\tvar err error\n\tif unstr, ok := obj.(Unstructured); ok {\n\t\tu = unstr.UnstructuredContent()\n\t} else {\n\t\tt := reflect.TypeOf(obj)\n\t\tvalue := reflect.ValueOf(obj)\n\t\tif t.Kind() != reflect.Pointer || value.IsNil() {\n\t\t\treturn nil, fmt.Errorf(\"ToUnstructured requires a non-nil pointer to an object, got %v\", t)\n\t\t}\n\t\tu = map[string]interface{}{}\n\t\terr = toUnstructured(value.Elem(), reflect.ValueOf(\u0026u).Elem())\n\t}\n\tif c.mismatchDetection {\n\t\tnewUnstr := map[string]interface{}{}\n\t\tnewErr := toUnstructuredViaJSON(obj, \u0026newUnstr)\n\t\tif (err != nil) != (newErr != nil) {\n\t\t\tklog.Fatalf(\"ToUnstructured unexpected error for %v: error: %v; newErr: %v\", obj, err, newErr)\n\t\t}\n\t\tif err == nil \u0026\u0026 !c.comparison.DeepEqual(u, newUnstr) {\n\t\t\tklog.Fatalf(\"ToUnstructured mismatch\\nobj1: %#v\\nobj2: %#v\", u, newUnstr)\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn u, nil\n}","line":{"from":572,"to":602}} {"id":100015366,"name":"DeepCopyJSON","signature":"func DeepCopyJSON(x map[string]interface{}) map[string]interface{}","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"// DeepCopyJSON deep copies the passed value, assuming it is a valid JSON representation i.e. only contains\n// types produced by json.Unmarshal() and also int64.\n// bool, int64, float64, string, []interface{}, map[string]interface{}, json.Number and nil\nfunc DeepCopyJSON(x map[string]interface{}) map[string]interface{} {\n\treturn DeepCopyJSONValue(x).(map[string]interface{})\n}","line":{"from":604,"to":609}} {"id":100015367,"name":"DeepCopyJSONValue","signature":"func DeepCopyJSONValue(x interface{}) interface{}","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"// DeepCopyJSONValue deep copies the passed value, assuming it is a valid JSON representation i.e. only contains\n// types produced by json.Unmarshal() and also int64.\n// bool, int64, float64, string, []interface{}, map[string]interface{}, json.Number and nil\nfunc DeepCopyJSONValue(x interface{}) interface{} {\n\tswitch x := x.(type) {\n\tcase map[string]interface{}:\n\t\tif x == nil {\n\t\t\t// Typed nil - an interface{} that contains a type map[string]interface{} with a value of nil\n\t\t\treturn x\n\t\t}\n\t\tclone := make(map[string]interface{}, len(x))\n\t\tfor k, v := range x {\n\t\t\tclone[k] = DeepCopyJSONValue(v)\n\t\t}\n\t\treturn clone\n\tcase []interface{}:\n\t\tif x == nil {\n\t\t\t// Typed nil - an interface{} that contains a type []interface{} with a value of nil\n\t\t\treturn x\n\t\t}\n\t\tclone := make([]interface{}, len(x))\n\t\tfor i, v := range x {\n\t\t\tclone[i] = DeepCopyJSONValue(v)\n\t\t}\n\t\treturn clone\n\tcase string, int64, bool, float64, nil, encodingjson.Number:\n\t\treturn x\n\tdefault:\n\t\tpanic(fmt.Errorf(\"cannot deep copy %T\", x))\n\t}\n}","line":{"from":611,"to":641}} {"id":100015368,"name":"toUnstructuredViaJSON","signature":"func toUnstructuredViaJSON(obj interface{}, u *map[string]interface{}) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"func toUnstructuredViaJSON(obj interface{}, u *map[string]interface{}) error {\n\tdata, err := json.Marshal(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn json.Unmarshal(data, u)\n}","line":{"from":643,"to":649}} {"id":100015369,"name":"toUnstructured","signature":"func toUnstructured(sv, dv reflect.Value) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"func toUnstructured(sv, dv reflect.Value) error {\n\t// Check if the object has a custom string converter.\n\tentry := value.TypeReflectEntryOf(sv.Type())\n\tif entry.CanConvertToUnstructured() {\n\t\tv, err := entry.ToUnstructured(sv)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif v != nil {\n\t\t\tdv.Set(reflect.ValueOf(v))\n\t\t}\n\t\treturn nil\n\t}\n\tst := sv.Type()\n\tswitch st.Kind() {\n\tcase reflect.String:\n\t\tdv.Set(reflect.ValueOf(sv.String()))\n\t\treturn nil\n\tcase reflect.Bool:\n\t\tdv.Set(reflect.ValueOf(sv.Bool()))\n\t\treturn nil\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\tdv.Set(reflect.ValueOf(sv.Int()))\n\t\treturn nil\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\tuVal := sv.Uint()\n\t\tif uVal \u003e math.MaxInt64 {\n\t\t\treturn fmt.Errorf(\"unsigned value %d does not fit into int64 (overflow)\", uVal)\n\t\t}\n\t\tdv.Set(reflect.ValueOf(int64(uVal)))\n\t\treturn nil\n\tcase reflect.Float32, reflect.Float64:\n\t\tdv.Set(reflect.ValueOf(sv.Float()))\n\t\treturn nil\n\tcase reflect.Map:\n\t\treturn mapToUnstructured(sv, dv)\n\tcase reflect.Slice:\n\t\treturn sliceToUnstructured(sv, dv)\n\tcase reflect.Pointer:\n\t\treturn pointerToUnstructured(sv, dv)\n\tcase reflect.Struct:\n\t\treturn structToUnstructured(sv, dv)\n\tcase reflect.Interface:\n\t\treturn interfaceToUnstructured(sv, dv)\n\tdefault:\n\t\treturn fmt.Errorf(\"unrecognized type: %v\", st.Kind())\n\t}\n}","line":{"from":651,"to":698}} {"id":100015370,"name":"mapToUnstructured","signature":"func mapToUnstructured(sv, dv reflect.Value) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"func mapToUnstructured(sv, dv reflect.Value) error {\n\tst, dt := sv.Type(), dv.Type()\n\tif sv.IsNil() {\n\t\tdv.Set(reflect.Zero(dt))\n\t\treturn nil\n\t}\n\tif dt.Kind() == reflect.Interface \u0026\u0026 dv.NumMethod() == 0 {\n\t\tif st.Key().Kind() == reflect.String {\n\t\t\tdv.Set(reflect.MakeMap(mapStringInterfaceType))\n\t\t\tdv = dv.Elem()\n\t\t\tdt = dv.Type()\n\t\t}\n\t}\n\tif dt.Kind() != reflect.Map {\n\t\treturn fmt.Errorf(\"cannot convert map to: %v\", dt.Kind())\n\t}\n\n\tif !st.Key().AssignableTo(dt.Key()) \u0026\u0026 !st.Key().ConvertibleTo(dt.Key()) {\n\t\treturn fmt.Errorf(\"cannot copy map with non-assignable keys: %v %v\", st.Key(), dt.Key())\n\t}\n\n\tfor _, key := range sv.MapKeys() {\n\t\tvalue := reflect.New(dt.Elem()).Elem()\n\t\tif err := toUnstructured(sv.MapIndex(key), value); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif st.Key().AssignableTo(dt.Key()) {\n\t\t\tdv.SetMapIndex(key, value)\n\t\t} else {\n\t\t\tdv.SetMapIndex(key.Convert(dt.Key()), value)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":700,"to":733}} {"id":100015371,"name":"sliceToUnstructured","signature":"func sliceToUnstructured(sv, dv reflect.Value) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"func sliceToUnstructured(sv, dv reflect.Value) error {\n\tst, dt := sv.Type(), dv.Type()\n\tif sv.IsNil() {\n\t\tdv.Set(reflect.Zero(dt))\n\t\treturn nil\n\t}\n\tif st.Elem().Kind() == reflect.Uint8 {\n\t\tdv.Set(reflect.New(stringType))\n\t\tdata, err := json.Marshal(sv.Bytes())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar result string\n\t\tif err = json.Unmarshal(data, \u0026result); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdv.Set(reflect.ValueOf(result))\n\t\treturn nil\n\t}\n\tif dt.Kind() == reflect.Interface \u0026\u0026 dv.NumMethod() == 0 {\n\t\tdv.Set(reflect.MakeSlice(reflect.SliceOf(dt), sv.Len(), sv.Cap()))\n\t\tdv = dv.Elem()\n\t\tdt = dv.Type()\n\t}\n\tif dt.Kind() != reflect.Slice {\n\t\treturn fmt.Errorf(\"cannot convert slice to: %v\", dt.Kind())\n\t}\n\tfor i := 0; i \u003c sv.Len(); i++ {\n\t\tif err := toUnstructured(sv.Index(i), dv.Index(i)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":735,"to":768}} {"id":100015372,"name":"pointerToUnstructured","signature":"func pointerToUnstructured(sv, dv reflect.Value) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"func pointerToUnstructured(sv, dv reflect.Value) error {\n\tif sv.IsNil() {\n\t\t// We're done - we don't need to store anything.\n\t\treturn nil\n\t}\n\treturn toUnstructured(sv.Elem(), dv)\n}","line":{"from":770,"to":776}} {"id":100015373,"name":"isZero","signature":"func isZero(v reflect.Value) bool","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"func isZero(v reflect.Value) bool {\n\tswitch v.Kind() {\n\tcase reflect.Array, reflect.String:\n\t\treturn v.Len() == 0\n\tcase reflect.Bool:\n\t\treturn !v.Bool()\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\treturn v.Int() == 0\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\treturn v.Uint() == 0\n\tcase reflect.Float32, reflect.Float64:\n\t\treturn v.Float() == 0\n\tcase reflect.Map, reflect.Slice:\n\t\t// TODO: It seems that 0-len maps are ignored in it.\n\t\treturn v.IsNil() || v.Len() == 0\n\tcase reflect.Pointer, reflect.Interface:\n\t\treturn v.IsNil()\n\t}\n\treturn false\n}","line":{"from":778,"to":797}} {"id":100015374,"name":"structToUnstructured","signature":"func structToUnstructured(sv, dv reflect.Value) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"func structToUnstructured(sv, dv reflect.Value) error {\n\tst, dt := sv.Type(), dv.Type()\n\tif dt.Kind() == reflect.Interface \u0026\u0026 dv.NumMethod() == 0 {\n\t\tdv.Set(reflect.MakeMapWithSize(mapStringInterfaceType, st.NumField()))\n\t\tdv = dv.Elem()\n\t\tdt = dv.Type()\n\t}\n\tif dt.Kind() != reflect.Map {\n\t\treturn fmt.Errorf(\"cannot convert struct to: %v\", dt.Kind())\n\t}\n\trealMap := dv.Interface().(map[string]interface{})\n\n\tfor i := 0; i \u003c st.NumField(); i++ {\n\t\tfieldInfo := fieldInfoFromField(st, i)\n\t\tfv := sv.Field(i)\n\n\t\tif fieldInfo.name == \"-\" {\n\t\t\t// This field should be skipped.\n\t\t\tcontinue\n\t\t}\n\t\tif fieldInfo.omitempty \u0026\u0026 isZero(fv) {\n\t\t\t// omitempty fields should be ignored.\n\t\t\tcontinue\n\t\t}\n\t\tif len(fieldInfo.name) == 0 {\n\t\t\t// This field is inlined.\n\t\t\tif err := toUnstructured(fv, dv); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tswitch fv.Type().Kind() {\n\t\tcase reflect.String:\n\t\t\trealMap[fieldInfo.name] = fv.String()\n\t\tcase reflect.Bool:\n\t\t\trealMap[fieldInfo.name] = fv.Bool()\n\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\t\trealMap[fieldInfo.name] = fv.Int()\n\t\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\t\trealMap[fieldInfo.name] = fv.Uint()\n\t\tcase reflect.Float32, reflect.Float64:\n\t\t\trealMap[fieldInfo.name] = fv.Float()\n\t\tdefault:\n\t\t\tsubv := reflect.New(dt.Elem()).Elem()\n\t\t\tif err := toUnstructured(fv, subv); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdv.SetMapIndex(fieldInfo.nameValue, subv)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":799,"to":850}} {"id":100015375,"name":"interfaceToUnstructured","signature":"func interfaceToUnstructured(sv, dv reflect.Value) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/converter.go","code":"func interfaceToUnstructured(sv, dv reflect.Value) error {\n\tif !sv.IsValid() || sv.IsNil() {\n\t\tdv.Set(reflect.Zero(dv.Type()))\n\t\treturn nil\n\t}\n\treturn toUnstructured(sv.Elem(), dv)\n}","line":{"from":852,"to":858}} {"id":100015376,"name":"GetObjectKind","signature":"func (e encodable) GetObjectKind() schema.ObjectKind { return e.obj.GetObjectKind() }","file":"staging/src/k8s.io/apimachinery/pkg/runtime/embedded.go","code":"func (e encodable) GetObjectKind() schema.ObjectKind { return e.obj.GetObjectKind() }","line":{"from":32,"to":32}} {"id":100015377,"name":"DeepCopyObject","signature":"func (e encodable) DeepCopyObject() Object","file":"staging/src/k8s.io/apimachinery/pkg/runtime/embedded.go","code":"func (e encodable) DeepCopyObject() Object {\n\tout := e\n\tout.obj = e.obj.DeepCopyObject()\n\tcopy(out.versions, e.versions)\n\treturn out\n}","line":{"from":33,"to":38}} {"id":100015378,"name":"NewEncodable","signature":"func NewEncodable(e Encoder, obj Object, versions ...schema.GroupVersion) Object","file":"staging/src/k8s.io/apimachinery/pkg/runtime/embedded.go","code":"// NewEncodable creates an object that will be encoded with the provided codec on demand.\n// Provided as a convenience for test cases dealing with internal objects.\nfunc NewEncodable(e Encoder, obj Object, versions ...schema.GroupVersion) Object {\n\tif _, ok := obj.(*Unknown); ok {\n\t\treturn obj\n\t}\n\treturn encodable{e, obj, versions}\n}","line":{"from":40,"to":47}} {"id":100015379,"name":"UnmarshalJSON","signature":"func (e encodable) UnmarshalJSON(in []byte) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/embedded.go","code":"func (e encodable) UnmarshalJSON(in []byte) error {\n\treturn errors.New(\"runtime.encodable cannot be unmarshalled from JSON\")\n}","line":{"from":49,"to":51}} {"id":100015380,"name":"MarshalJSON","signature":"func (e encodable) MarshalJSON() ([]byte, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/embedded.go","code":"// Marshal may get called on pointers or values, so implement MarshalJSON on value.\n// http://stackoverflow.com/questions/21390979/custom-marshaljson-never-gets-called-in-go\nfunc (e encodable) MarshalJSON() ([]byte, error) {\n\treturn Encode(e.E, e.obj)\n}","line":{"from":53,"to":57}} {"id":100015381,"name":"NewEncodableList","signature":"func NewEncodableList(e Encoder, objects []Object, versions ...schema.GroupVersion) []Object","file":"staging/src/k8s.io/apimachinery/pkg/runtime/embedded.go","code":"// NewEncodableList creates an object that will be encoded with the provided codec on demand.\n// Provided as a convenience for test cases dealing with internal objects.\nfunc NewEncodableList(e Encoder, objects []Object, versions ...schema.GroupVersion) []Object {\n\tout := make([]Object, len(objects))\n\tfor i := range objects {\n\t\tif _, ok := objects[i].(*Unknown); ok {\n\t\t\tout[i] = objects[i]\n\t\t\tcontinue\n\t\t}\n\t\tout[i] = NewEncodable(e, objects[i], versions...)\n\t}\n\treturn out\n}","line":{"from":59,"to":71}} {"id":100015382,"name":"UnmarshalJSON","signature":"func (e *Unknown) UnmarshalJSON(in []byte) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/embedded.go","code":"func (e *Unknown) UnmarshalJSON(in []byte) error {\n\tif e == nil {\n\t\treturn errors.New(\"runtime.Unknown: UnmarshalJSON on nil pointer\")\n\t}\n\te.TypeMeta = TypeMeta{}\n\te.Raw = append(e.Raw[0:0], in...)\n\te.ContentEncoding = \"\"\n\te.ContentType = ContentTypeJSON\n\treturn nil\n}","line":{"from":73,"to":82}} {"id":100015383,"name":"MarshalJSON","signature":"func (e Unknown) MarshalJSON() ([]byte, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/embedded.go","code":"// Marshal may get called on pointers or values, so implement MarshalJSON on value.\n// http://stackoverflow.com/questions/21390979/custom-marshaljson-never-gets-called-in-go\nfunc (e Unknown) MarshalJSON() ([]byte, error) {\n\t// If ContentType is unset, we assume this is JSON.\n\tif e.ContentType != \"\" \u0026\u0026 e.ContentType != ContentTypeJSON {\n\t\treturn nil, errors.New(\"runtime.Unknown: MarshalJSON on non-json data\")\n\t}\n\tif e.Raw == nil {\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn e.Raw, nil\n}","line":{"from":84,"to":95}} {"id":100015384,"name":"Convert_runtime_Object_To_runtime_RawExtension","signature":"func Convert_runtime_Object_To_runtime_RawExtension(in *Object, out *RawExtension, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/embedded.go","code":"func Convert_runtime_Object_To_runtime_RawExtension(in *Object, out *RawExtension, s conversion.Scope) error {\n\tif in == nil {\n\t\tout.Raw = []byte(\"null\")\n\t\treturn nil\n\t}\n\tobj := *in\n\tif unk, ok := obj.(*Unknown); ok {\n\t\tif unk.Raw != nil {\n\t\t\tout.Raw = unk.Raw\n\t\t\treturn nil\n\t\t}\n\t\tobj = out.Object\n\t}\n\tif obj == nil {\n\t\tout.Raw = nil\n\t\treturn nil\n\t}\n\tout.Object = obj\n\treturn nil\n}","line":{"from":97,"to":116}} {"id":100015385,"name":"Convert_runtime_RawExtension_To_runtime_Object","signature":"func Convert_runtime_RawExtension_To_runtime_Object(in *RawExtension, out *Object, s conversion.Scope) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/embedded.go","code":"func Convert_runtime_RawExtension_To_runtime_Object(in *RawExtension, out *Object, s conversion.Scope) error {\n\tif in.Object != nil {\n\t\t*out = in.Object\n\t\treturn nil\n\t}\n\tdata := in.Raw\n\tif len(data) == 0 || (len(data) == 4 \u0026\u0026 string(data) == \"null\") {\n\t\t*out = nil\n\t\treturn nil\n\t}\n\t*out = \u0026Unknown{\n\t\tRaw: data,\n\t\t// TODO: Set ContentEncoding and ContentType appropriately.\n\t\t// Currently we set ContentTypeJSON to make tests passing.\n\t\tContentType: ContentTypeJSON,\n\t}\n\treturn nil\n}","line":{"from":118,"to":135}} {"id":100015386,"name":"RegisterEmbeddedConversions","signature":"func RegisterEmbeddedConversions(s *Scheme) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/embedded.go","code":"func RegisterEmbeddedConversions(s *Scheme) error {\n\tif err := s.AddConversionFunc((*Object)(nil), (*RawExtension)(nil), func(a, b interface{}, scope conversion.Scope) error {\n\t\treturn Convert_runtime_Object_To_runtime_RawExtension(a.(*Object), b.(*RawExtension), scope)\n\t}); err != nil {\n\t\treturn err\n\t}\n\tif err := s.AddConversionFunc((*RawExtension)(nil), (*Object)(nil), func(a, b interface{}, scope conversion.Scope) error {\n\t\treturn Convert_runtime_RawExtension_To_runtime_Object(a.(*RawExtension), b.(*Object), scope)\n\t}); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":137,"to":149}} {"id":100015387,"name":"NewNotRegisteredErrForKind","signature":"func NewNotRegisteredErrForKind(schemeName string, gvk schema.GroupVersionKind) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/error.go","code":"func NewNotRegisteredErrForKind(schemeName string, gvk schema.GroupVersionKind) error {\n\treturn \u0026notRegisteredErr{schemeName: schemeName, gvk: gvk}\n}","line":{"from":34,"to":36}} {"id":100015388,"name":"NewNotRegisteredErrForType","signature":"func NewNotRegisteredErrForType(schemeName string, t reflect.Type) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/error.go","code":"func NewNotRegisteredErrForType(schemeName string, t reflect.Type) error {\n\treturn \u0026notRegisteredErr{schemeName: schemeName, t: t}\n}","line":{"from":38,"to":40}} {"id":100015389,"name":"NewNotRegisteredErrForTarget","signature":"func NewNotRegisteredErrForTarget(schemeName string, t reflect.Type, target GroupVersioner) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/error.go","code":"func NewNotRegisteredErrForTarget(schemeName string, t reflect.Type, target GroupVersioner) error {\n\treturn \u0026notRegisteredErr{schemeName: schemeName, t: t, target: target}\n}","line":{"from":42,"to":44}} {"id":100015390,"name":"NewNotRegisteredGVKErrForTarget","signature":"func NewNotRegisteredGVKErrForTarget(schemeName string, gvk schema.GroupVersionKind, target GroupVersioner) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/error.go","code":"func NewNotRegisteredGVKErrForTarget(schemeName string, gvk schema.GroupVersionKind, target GroupVersioner) error {\n\treturn \u0026notRegisteredErr{schemeName: schemeName, gvk: gvk, target: target}\n}","line":{"from":46,"to":48}} {"id":100015391,"name":"Error","signature":"func (k *notRegisteredErr) Error() string","file":"staging/src/k8s.io/apimachinery/pkg/runtime/error.go","code":"func (k *notRegisteredErr) Error() string {\n\tif k.t != nil \u0026\u0026 k.target != nil {\n\t\treturn fmt.Sprintf(\"%v is not suitable for converting to %q in scheme %q\", k.t, k.target, k.schemeName)\n\t}\n\tnullGVK := schema.GroupVersionKind{}\n\tif k.gvk != nullGVK \u0026\u0026 k.target != nil {\n\t\treturn fmt.Sprintf(\"%q is not suitable for converting to %q in scheme %q\", k.gvk.GroupVersion(), k.target, k.schemeName)\n\t}\n\tif k.t != nil {\n\t\treturn fmt.Sprintf(\"no kind is registered for the type %v in scheme %q\", k.t, k.schemeName)\n\t}\n\tif len(k.gvk.Kind) == 0 {\n\t\treturn fmt.Sprintf(\"no version %q has been registered in scheme %q\", k.gvk.GroupVersion(), k.schemeName)\n\t}\n\tif k.gvk.Version == APIVersionInternal {\n\t\treturn fmt.Sprintf(\"no kind %q is registered for the internal version of group %q in scheme %q\", k.gvk.Kind, k.gvk.Group, k.schemeName)\n\t}\n\n\treturn fmt.Sprintf(\"no kind %q is registered for version %q in scheme %q\", k.gvk.Kind, k.gvk.GroupVersion(), k.schemeName)\n}","line":{"from":50,"to":69}} {"id":100015392,"name":"IsNotRegisteredError","signature":"func IsNotRegisteredError(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/runtime/error.go","code":"// IsNotRegisteredError returns true if the error indicates the provided\n// object or input data is not registered.\nfunc IsNotRegisteredError(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\t_, ok := err.(*notRegisteredErr)\n\treturn ok\n}","line":{"from":71,"to":79}} {"id":100015393,"name":"NewMissingKindErr","signature":"func NewMissingKindErr(data string) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/error.go","code":"func NewMissingKindErr(data string) error {\n\treturn \u0026missingKindErr{data}\n}","line":{"from":85,"to":87}} {"id":100015394,"name":"Error","signature":"func (k *missingKindErr) Error() string","file":"staging/src/k8s.io/apimachinery/pkg/runtime/error.go","code":"func (k *missingKindErr) Error() string {\n\treturn fmt.Sprintf(\"Object 'Kind' is missing in '%s'\", k.data)\n}","line":{"from":89,"to":91}} {"id":100015395,"name":"IsMissingKind","signature":"func IsMissingKind(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/runtime/error.go","code":"// IsMissingKind returns true if the error indicates that the provided object\n// is missing a 'Kind' field.\nfunc IsMissingKind(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\t_, ok := err.(*missingKindErr)\n\treturn ok\n}","line":{"from":93,"to":101}} {"id":100015396,"name":"NewMissingVersionErr","signature":"func NewMissingVersionErr(data string) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/error.go","code":"func NewMissingVersionErr(data string) error {\n\treturn \u0026missingVersionErr{data}\n}","line":{"from":107,"to":109}} {"id":100015397,"name":"Error","signature":"func (k *missingVersionErr) Error() string","file":"staging/src/k8s.io/apimachinery/pkg/runtime/error.go","code":"func (k *missingVersionErr) Error() string {\n\treturn fmt.Sprintf(\"Object 'apiVersion' is missing in '%s'\", k.data)\n}","line":{"from":111,"to":113}} {"id":100015398,"name":"IsMissingVersion","signature":"func IsMissingVersion(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/runtime/error.go","code":"// IsMissingVersion returns true if the error indicates that the provided object\n// is missing a 'Version' field.\nfunc IsMissingVersion(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\t_, ok := err.(*missingVersionErr)\n\treturn ok\n}","line":{"from":115,"to":123}} {"id":100015399,"name":"NewStrictDecodingError","signature":"func NewStrictDecodingError(errors []error) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/error.go","code":"// NewStrictDecodingError creates a new strictDecodingError object.\nfunc NewStrictDecodingError(errors []error) error {\n\treturn \u0026strictDecodingError{\n\t\terrors: errors,\n\t}\n}","line":{"from":131,"to":136}} {"id":100015400,"name":"Error","signature":"func (e *strictDecodingError) Error() string","file":"staging/src/k8s.io/apimachinery/pkg/runtime/error.go","code":"func (e *strictDecodingError) Error() string {\n\tvar s strings.Builder\n\ts.WriteString(\"strict decoding error: \")\n\tfor i, err := range e.errors {\n\t\tif i != 0 {\n\t\t\ts.WriteString(\", \")\n\t\t}\n\t\ts.WriteString(err.Error())\n\t}\n\treturn s.String()\n}","line":{"from":138,"to":148}} {"id":100015401,"name":"Errors","signature":"func (e *strictDecodingError) Errors() []error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/error.go","code":"func (e *strictDecodingError) Errors() []error {\n\treturn e.errors\n}","line":{"from":150,"to":152}} {"id":100015402,"name":"IsStrictDecodingError","signature":"func IsStrictDecodingError(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/runtime/error.go","code":"// IsStrictDecodingError returns true if the error indicates that the provided object\n// strictness violations.\nfunc IsStrictDecodingError(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\t_, ok := err.(*strictDecodingError)\n\treturn ok\n}","line":{"from":154,"to":162}} {"id":100015403,"name":"AsStrictDecodingError","signature":"func AsStrictDecodingError(err error) (*strictDecodingError, bool)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/error.go","code":"// AsStrictDecodingError returns a strict decoding error\n// containing all the strictness violations.\nfunc AsStrictDecodingError(err error) (*strictDecodingError, bool) {\n\tif err == nil {\n\t\treturn nil, false\n\t}\n\tstrictErr, ok := err.(*strictDecodingError)\n\treturn strictErr, ok\n}","line":{"from":164,"to":172}} {"id":100015404,"name":"UnmarshalJSON","signature":"func (re *RawExtension) UnmarshalJSON(in []byte) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/extension.go","code":"func (re *RawExtension) UnmarshalJSON(in []byte) error {\n\tif re == nil {\n\t\treturn errors.New(\"runtime.RawExtension: UnmarshalJSON on nil pointer\")\n\t}\n\tif !bytes.Equal(in, []byte(\"null\")) {\n\t\tre.Raw = append(re.Raw[0:0], in...)\n\t}\n\treturn nil\n}","line":{"from":25,"to":33}} {"id":100015405,"name":"MarshalJSON","signature":"func (re RawExtension) MarshalJSON() ([]byte, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/extension.go","code":"// MarshalJSON may get called on pointers or values, so implement MarshalJSON on value.\n// http://stackoverflow.com/questions/21390979/custom-marshaljson-never-gets-called-in-go\nfunc (re RawExtension) MarshalJSON() ([]byte, error) {\n\tif re.Raw == nil {\n\t\t// TODO: this is to support legacy behavior of JSONPrinter and YAMLPrinter, which\n\t\t// expect to call json.Marshal on arbitrary versioned objects (even those not in\n\t\t// the scheme). pkg/kubectl/resource#AsVersionedObjects and its interaction with\n\t\t// kubectl get on objects not in the scheme needs to be updated to ensure that the\n\t\t// objects that are not part of the scheme are correctly put into the right form.\n\t\tif re.Object != nil {\n\t\t\treturn json.Marshal(re.Object)\n\t\t}\n\t\treturn []byte(\"null\"), nil\n\t}\n\t// TODO: Check whether ContentType is actually JSON before returning it.\n\treturn re.Raw, nil\n}","line":{"from":35,"to":51}} {"id":100015406,"name":"ConvertToVersion","signature":"func (c unsafeObjectConvertor) ConvertToVersion(in Object, outVersion GroupVersioner) (Object, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/helper.go","code":"// ConvertToVersion converts in to the provided outVersion without copying the input first, which\n// is only safe if the output object is not mutated or reused.\nfunc (c unsafeObjectConvertor) ConvertToVersion(in Object, outVersion GroupVersioner) (Object, error) {\n\treturn c.Scheme.UnsafeConvertToVersion(in, outVersion)\n}","line":{"from":36,"to":40}} {"id":100015407,"name":"UnsafeObjectConvertor","signature":"func UnsafeObjectConvertor(scheme *Scheme) ObjectConvertor","file":"staging/src/k8s.io/apimachinery/pkg/runtime/helper.go","code":"// UnsafeObjectConvertor performs object conversion without copying the object structure,\n// for use when the converted object will not be reused or mutated. Primarily for use within\n// versioned codecs, which use the external object for serialization but do not return it.\nfunc UnsafeObjectConvertor(scheme *Scheme) ObjectConvertor {\n\treturn unsafeObjectConvertor{scheme}\n}","line":{"from":42,"to":47}} {"id":100015408,"name":"SetField","signature":"func SetField(src interface{}, v reflect.Value, fieldName string) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/helper.go","code":"// SetField puts the value of src, into fieldName, which must be a member of v.\n// The value of src must be assignable to the field.\nfunc SetField(src interface{}, v reflect.Value, fieldName string) error {\n\tfield := v.FieldByName(fieldName)\n\tif !field.IsValid() {\n\t\treturn fmt.Errorf(\"couldn't find %v field in %T\", fieldName, v.Interface())\n\t}\n\tsrcValue := reflect.ValueOf(src)\n\tif srcValue.Type().AssignableTo(field.Type()) {\n\t\tfield.Set(srcValue)\n\t\treturn nil\n\t}\n\tif srcValue.Type().ConvertibleTo(field.Type()) {\n\t\tfield.Set(srcValue.Convert(field.Type()))\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"couldn't assign/convert %v to %v\", srcValue.Type(), field.Type())\n}","line":{"from":49,"to":66}} {"id":100015409,"name":"Field","signature":"func Field(v reflect.Value, fieldName string, dest interface{}) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/helper.go","code":"// Field puts the value of fieldName, which must be a member of v, into dest,\n// which must be a variable to which this field's value can be assigned.\nfunc Field(v reflect.Value, fieldName string, dest interface{}) error {\n\tfield := v.FieldByName(fieldName)\n\tif !field.IsValid() {\n\t\treturn fmt.Errorf(\"couldn't find %v field in %T\", fieldName, v.Interface())\n\t}\n\tdestValue, err := conversion.EnforcePtr(dest)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif field.Type().AssignableTo(destValue.Type()) {\n\t\tdestValue.Set(field)\n\t\treturn nil\n\t}\n\tif field.Type().ConvertibleTo(destValue.Type()) {\n\t\tdestValue.Set(field.Convert(destValue.Type()))\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"couldn't assign/convert %v to %v\", field.Type(), destValue.Type())\n}","line":{"from":68,"to":88}} {"id":100015410,"name":"FieldPtr","signature":"func FieldPtr(v reflect.Value, fieldName string, dest interface{}) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/helper.go","code":"// FieldPtr puts the address of fieldName, which must be a member of v,\n// into dest, which must be an address of a variable to which this field's\n// address can be assigned.\nfunc FieldPtr(v reflect.Value, fieldName string, dest interface{}) error {\n\tfield := v.FieldByName(fieldName)\n\tif !field.IsValid() {\n\t\treturn fmt.Errorf(\"couldn't find %v field in %T\", fieldName, v.Interface())\n\t}\n\tv, err := conversion.EnforcePtr(dest)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfield = field.Addr()\n\tif field.Type().AssignableTo(v.Type()) {\n\t\tv.Set(field)\n\t\treturn nil\n\t}\n\tif field.Type().ConvertibleTo(v.Type()) {\n\t\tv.Set(field.Convert(v.Type()))\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"couldn't assign/convert %v to %v\", field.Type(), v.Type())\n}","line":{"from":90,"to":112}} {"id":100015411,"name":"EncodeList","signature":"func EncodeList(e Encoder, objects []Object) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/helper.go","code":"// EncodeList ensures that each object in an array is converted to a Unknown{} in serialized form.\n// TODO: accept a content type.\nfunc EncodeList(e Encoder, objects []Object) error {\n\tvar errs []error\n\tfor i := range objects {\n\t\tdata, err := Encode(e, objects[i])\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t\tcontinue\n\t\t}\n\t\t// TODO: Set ContentEncoding and ContentType.\n\t\tobjects[i] = \u0026Unknown{Raw: data}\n\t}\n\treturn errors.NewAggregate(errs)\n}","line":{"from":114,"to":128}} {"id":100015412,"name":"decodeListItem","signature":"func decodeListItem(obj *Unknown, decoders []Decoder) (Object, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/helper.go","code":"func decodeListItem(obj *Unknown, decoders []Decoder) (Object, error) {\n\tfor _, decoder := range decoders {\n\t\t// TODO: Decode based on ContentType.\n\t\tobj, err := Decode(decoder, obj.Raw)\n\t\tif err != nil {\n\t\t\tif IsNotRegisteredError(err) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\treturn obj, nil\n\t}\n\t// could not decode, so leave the object as Unknown, but give the decoders the\n\t// chance to set Unknown.TypeMeta if it is available.\n\tfor _, decoder := range decoders {\n\t\tif err := DecodeInto(decoder, obj.Raw, obj); err == nil {\n\t\t\treturn obj, nil\n\t\t}\n\t}\n\treturn obj, nil\n}","line":{"from":130,"to":150}} {"id":100015413,"name":"DecodeList","signature":"func DecodeList(objects []Object, decoders ...Decoder) []error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/helper.go","code":"// DecodeList alters the list in place, attempting to decode any objects found in\n// the list that have the Unknown type. Any errors that occur are returned\n// after the entire list is processed. Decoders are tried in order.\nfunc DecodeList(objects []Object, decoders ...Decoder) []error {\n\terrs := []error(nil)\n\tfor i, obj := range objects {\n\t\tswitch t := obj.(type) {\n\t\tcase *Unknown:\n\t\t\tdecoded, err := decodeListItem(t, decoders)\n\t\t\tif err != nil {\n\t\t\t\terrs = append(errs, err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tobjects[i] = decoded\n\t\t}\n\t}\n\treturn errs\n}","line":{"from":152,"to":169}} {"id":100015414,"name":"ObjectKinds","signature":"func (m MultiObjectTyper) ObjectKinds(obj Object) (gvks []schema.GroupVersionKind, unversionedType bool, err error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/helper.go","code":"func (m MultiObjectTyper) ObjectKinds(obj Object) (gvks []schema.GroupVersionKind, unversionedType bool, err error) {\n\tfor _, t := range m {\n\t\tgvks, unversionedType, err = t.ObjectKinds(obj)\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}","line":{"from":176,"to":184}} {"id":100015415,"name":"Recognizes","signature":"func (m MultiObjectTyper) Recognizes(gvk schema.GroupVersionKind) bool","file":"staging/src/k8s.io/apimachinery/pkg/runtime/helper.go","code":"func (m MultiObjectTyper) Recognizes(gvk schema.GroupVersionKind) bool {\n\tfor _, t := range m {\n\t\tif t.Recognizes(gvk) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":186,"to":193}} {"id":100015416,"name":"SetZeroValue","signature":"func SetZeroValue(objPtr Object) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/helper.go","code":"// SetZeroValue would set the object of objPtr to zero value of its type.\nfunc SetZeroValue(objPtr Object) error {\n\tv, err := conversion.EnforcePtr(objPtr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.Set(reflect.Zero(v.Type()))\n\treturn nil\n}","line":{"from":195,"to":203}} {"id":100015417,"name":"NewFrameReader","signature":"func (defaultFramer) NewFrameReader(r io.ReadCloser) io.ReadCloser { return r }","file":"staging/src/k8s.io/apimachinery/pkg/runtime/helper.go","code":"func (defaultFramer) NewFrameReader(r io.ReadCloser) io.ReadCloser { return r }","line":{"from":211,"to":211}} {"id":100015418,"name":"NewFrameWriter","signature":"func (defaultFramer) NewFrameWriter(w io.Writer) io.Writer { return w }","file":"staging/src/k8s.io/apimachinery/pkg/runtime/helper.go","code":"func (defaultFramer) NewFrameWriter(w io.Writer) io.Writer { return w }","line":{"from":212,"to":212}} {"id":100015419,"name":"Encode","signature":"func (e WithVersionEncoder) Encode(obj Object, stream io.Writer) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/helper.go","code":"// Encode does not do conversion. It sets the gvk during serialization.\nfunc (e WithVersionEncoder) Encode(obj Object, stream io.Writer) error {\n\tgvks, _, err := e.ObjectTyper.ObjectKinds(obj)\n\tif err != nil {\n\t\tif IsNotRegisteredError(err) {\n\t\t\treturn e.Encoder.Encode(obj, stream)\n\t\t}\n\t\treturn err\n\t}\n\tkind := obj.GetObjectKind()\n\toldGVK := kind.GroupVersionKind()\n\tgvk := gvks[0]\n\tif e.Version != nil {\n\t\tpreferredGVK, ok := e.Version.KindForGroupVersionKinds(gvks)\n\t\tif ok {\n\t\t\tgvk = preferredGVK\n\t\t}\n\t}\n\tkind.SetGroupVersionKind(gvk)\n\terr = e.Encoder.Encode(obj, stream)\n\tkind.SetGroupVersionKind(oldGVK)\n\treturn err\n}","line":{"from":221,"to":243}} {"id":100015420,"name":"Decode","signature":"func (d WithoutVersionDecoder) Decode(data []byte, defaults *schema.GroupVersionKind, into Object) (Object, *schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/helper.go","code":"// Decode does not do conversion. It removes the gvk during deserialization.\nfunc (d WithoutVersionDecoder) Decode(data []byte, defaults *schema.GroupVersionKind, into Object) (Object, *schema.GroupVersionKind, error) {\n\tobj, gvk, err := d.Decoder.Decode(data, defaults, into)\n\tif obj != nil {\n\t\tkind := obj.GetObjectKind()\n\t\t// clearing the gvk is just a convention of a codec\n\t\tkind.SetGroupVersionKind(schema.GroupVersionKind{})\n\t}\n\treturn obj, gvk, err\n}","line":{"from":250,"to":259}} {"id":100015421,"name":"NewEquivalentResourceRegistry","signature":"func NewEquivalentResourceRegistry() EquivalentResourceRegistry","file":"staging/src/k8s.io/apimachinery/pkg/runtime/mapper.go","code":"// NewEquivalentResourceRegistry creates a resource registry that considers all versions of a GroupResource to be equivalent.\nfunc NewEquivalentResourceRegistry() EquivalentResourceRegistry {\n\treturn \u0026equivalentResourceRegistry{}\n}","line":{"from":43,"to":46}} {"id":100015422,"name":"NewEquivalentResourceRegistryWithIdentity","signature":"func NewEquivalentResourceRegistryWithIdentity(keyFunc func(schema.GroupResource) string) EquivalentResourceRegistry","file":"staging/src/k8s.io/apimachinery/pkg/runtime/mapper.go","code":"// NewEquivalentResourceRegistryWithIdentity creates a resource mapper with a custom identity function.\n// If \"\" is returned by the function, GroupResource#String is used as the identity.\n// GroupResources with the same identity string are considered equivalent.\nfunc NewEquivalentResourceRegistryWithIdentity(keyFunc func(schema.GroupResource) string) EquivalentResourceRegistry {\n\treturn \u0026equivalentResourceRegistry{keyFunc: keyFunc}\n}","line":{"from":48,"to":53}} {"id":100015423,"name":"EquivalentResourcesFor","signature":"func (r *equivalentResourceRegistry) EquivalentResourcesFor(resource schema.GroupVersionResource, subresource string) []schema.GroupVersionResource","file":"staging/src/k8s.io/apimachinery/pkg/runtime/mapper.go","code":"func (r *equivalentResourceRegistry) EquivalentResourcesFor(resource schema.GroupVersionResource, subresource string) []schema.GroupVersionResource {\n\tr.mutex.RLock()\n\tdefer r.mutex.RUnlock()\n\treturn r.resources[r.keys[resource.GroupResource()]][subresource]\n}","line":{"from":55,"to":59}} {"id":100015424,"name":"KindFor","signature":"func (r *equivalentResourceRegistry) KindFor(resource schema.GroupVersionResource, subresource string) schema.GroupVersionKind","file":"staging/src/k8s.io/apimachinery/pkg/runtime/mapper.go","code":"func (r *equivalentResourceRegistry) KindFor(resource schema.GroupVersionResource, subresource string) schema.GroupVersionKind {\n\tr.mutex.RLock()\n\tdefer r.mutex.RUnlock()\n\treturn r.kinds[resource][subresource]\n}","line":{"from":60,"to":64}} {"id":100015425,"name":"RegisterKindFor","signature":"func (r *equivalentResourceRegistry) RegisterKindFor(resource schema.GroupVersionResource, subresource string, kind schema.GroupVersionKind)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/mapper.go","code":"func (r *equivalentResourceRegistry) RegisterKindFor(resource schema.GroupVersionResource, subresource string, kind schema.GroupVersionKind) {\n\tr.mutex.Lock()\n\tdefer r.mutex.Unlock()\n\tif r.kinds == nil {\n\t\tr.kinds = map[schema.GroupVersionResource]map[string]schema.GroupVersionKind{}\n\t}\n\tif r.kinds[resource] == nil {\n\t\tr.kinds[resource] = map[string]schema.GroupVersionKind{}\n\t}\n\tr.kinds[resource][subresource] = kind\n\n\t// get the shared key of the parent resource\n\tkey := \"\"\n\tgr := resource.GroupResource()\n\tif r.keyFunc != nil {\n\t\tkey = r.keyFunc(gr)\n\t}\n\tif key == \"\" {\n\t\tkey = gr.String()\n\t}\n\n\tif r.keys == nil {\n\t\tr.keys = map[schema.GroupResource]string{}\n\t}\n\tr.keys[gr] = key\n\n\tif r.resources == nil {\n\t\tr.resources = map[string]map[string][]schema.GroupVersionResource{}\n\t}\n\tif r.resources[key] == nil {\n\t\tr.resources[key] = map[string][]schema.GroupVersionResource{}\n\t}\n\tr.resources[key][subresource] = append(r.resources[key][subresource], resource)\n}","line":{"from":65,"to":98}} {"id":100015426,"name":"Error","signature":"func (e NegotiateError) Error() string","file":"staging/src/k8s.io/apimachinery/pkg/runtime/negotiate.go","code":"func (e NegotiateError) Error() string {\n\tif e.Stream {\n\t\treturn fmt.Sprintf(\"no stream serializers registered for %s\", e.ContentType)\n\t}\n\treturn fmt.Sprintf(\"no serializers registered for %s\", e.ContentType)\n}","line":{"from":32,"to":37}} {"id":100015427,"name":"Encoder","signature":"func (n *clientNegotiator) Encoder(contentType string, params map[string]string) (Encoder, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/negotiate.go","code":"func (n *clientNegotiator) Encoder(contentType string, params map[string]string) (Encoder, error) {\n\t// TODO: `pretty=1` is handled in NegotiateOutputMediaType, consider moving it to this method\n\t// if client negotiators truly need to use it\n\tmediaTypes := n.serializer.SupportedMediaTypes()\n\tinfo, ok := SerializerInfoForMediaType(mediaTypes, contentType)\n\tif !ok {\n\t\tif len(contentType) != 0 || len(mediaTypes) == 0 {\n\t\t\treturn nil, NegotiateError{ContentType: contentType}\n\t\t}\n\t\tinfo = mediaTypes[0]\n\t}\n\treturn n.serializer.EncoderForVersion(info.Serializer, n.encode), nil\n}","line":{"from":44,"to":56}} {"id":100015428,"name":"Decoder","signature":"func (n *clientNegotiator) Decoder(contentType string, params map[string]string) (Decoder, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/negotiate.go","code":"func (n *clientNegotiator) Decoder(contentType string, params map[string]string) (Decoder, error) {\n\tmediaTypes := n.serializer.SupportedMediaTypes()\n\tinfo, ok := SerializerInfoForMediaType(mediaTypes, contentType)\n\tif !ok {\n\t\tif len(contentType) != 0 || len(mediaTypes) == 0 {\n\t\t\treturn nil, NegotiateError{ContentType: contentType}\n\t\t}\n\t\tinfo = mediaTypes[0]\n\t}\n\treturn n.serializer.DecoderToVersion(info.Serializer, n.decode), nil\n}","line":{"from":58,"to":68}} {"id":100015429,"name":"StreamDecoder","signature":"func (n *clientNegotiator) StreamDecoder(contentType string, params map[string]string) (Decoder, Serializer, Framer, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/negotiate.go","code":"func (n *clientNegotiator) StreamDecoder(contentType string, params map[string]string) (Decoder, Serializer, Framer, error) {\n\tmediaTypes := n.serializer.SupportedMediaTypes()\n\tinfo, ok := SerializerInfoForMediaType(mediaTypes, contentType)\n\tif !ok {\n\t\tif len(contentType) != 0 || len(mediaTypes) == 0 {\n\t\t\treturn nil, nil, nil, NegotiateError{ContentType: contentType, Stream: true}\n\t\t}\n\t\tinfo = mediaTypes[0]\n\t}\n\tif info.StreamSerializer == nil {\n\t\treturn nil, nil, nil, NegotiateError{ContentType: info.MediaType, Stream: true}\n\t}\n\treturn n.serializer.DecoderToVersion(info.Serializer, n.decode), info.StreamSerializer.Serializer, info.StreamSerializer.Framer, nil\n}","line":{"from":70,"to":83}} {"id":100015430,"name":"NewClientNegotiator","signature":"func NewClientNegotiator(serializer NegotiatedSerializer, gv schema.GroupVersion) ClientNegotiator","file":"staging/src/k8s.io/apimachinery/pkg/runtime/negotiate.go","code":"// NewClientNegotiator will attempt to retrieve the appropriate encoder, decoder, or\n// stream decoder for a given content type. Does not perform any conversion, but will\n// encode the object to the desired group, version, and kind. Use when creating a client.\nfunc NewClientNegotiator(serializer NegotiatedSerializer, gv schema.GroupVersion) ClientNegotiator {\n\treturn \u0026clientNegotiator{\n\t\tserializer: serializer,\n\t\tencode: gv,\n\t}\n}","line":{"from":85,"to":93}} {"id":100015431,"name":"NewSimpleNegotiatedSerializer","signature":"func NewSimpleNegotiatedSerializer(info SerializerInfo) NegotiatedSerializer","file":"staging/src/k8s.io/apimachinery/pkg/runtime/negotiate.go","code":"func NewSimpleNegotiatedSerializer(info SerializerInfo) NegotiatedSerializer {\n\treturn \u0026simpleNegotiatedSerializer{info: info}\n}","line":{"from":99,"to":101}} {"id":100015432,"name":"SupportedMediaTypes","signature":"func (n *simpleNegotiatedSerializer) SupportedMediaTypes() []SerializerInfo","file":"staging/src/k8s.io/apimachinery/pkg/runtime/negotiate.go","code":"func (n *simpleNegotiatedSerializer) SupportedMediaTypes() []SerializerInfo {\n\treturn []SerializerInfo{n.info}\n}","line":{"from":103,"to":105}} {"id":100015433,"name":"EncoderForVersion","signature":"func (n *simpleNegotiatedSerializer) EncoderForVersion(e Encoder, _ GroupVersioner) Encoder","file":"staging/src/k8s.io/apimachinery/pkg/runtime/negotiate.go","code":"func (n *simpleNegotiatedSerializer) EncoderForVersion(e Encoder, _ GroupVersioner) Encoder {\n\treturn e\n}","line":{"from":107,"to":109}} {"id":100015434,"name":"DecoderToVersion","signature":"func (n *simpleNegotiatedSerializer) DecoderToVersion(d Decoder, _gv GroupVersioner) Decoder","file":"staging/src/k8s.io/apimachinery/pkg/runtime/negotiate.go","code":"func (n *simpleNegotiatedSerializer) DecoderToVersion(d Decoder, _gv GroupVersioner) Decoder {\n\treturn d\n}","line":{"from":111,"to":113}} {"id":100015435,"name":"SetGroupVersionKind","signature":"func (obj *TypeMeta) SetGroupVersionKind(gvk schema.GroupVersionKind)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/register.go","code":"// SetGroupVersionKind satisfies the ObjectKind interface for all objects that embed TypeMeta\nfunc (obj *TypeMeta) SetGroupVersionKind(gvk schema.GroupVersionKind) {\n\tobj.APIVersion, obj.Kind = gvk.ToAPIVersionAndKind()\n}","line":{"from":21,"to":24}} {"id":100015436,"name":"GroupVersionKind","signature":"func (obj *TypeMeta) GroupVersionKind() schema.GroupVersionKind","file":"staging/src/k8s.io/apimachinery/pkg/runtime/register.go","code":"// GroupVersionKind satisfies the ObjectKind interface for all objects that embed TypeMeta\nfunc (obj *TypeMeta) GroupVersionKind() schema.GroupVersionKind {\n\treturn schema.FromAPIVersionAndKind(obj.APIVersion, obj.Kind)\n}","line":{"from":26,"to":29}} {"id":100015437,"name":"GetObjectKind","signature":"func (obj *TypeMeta) GetObjectKind() schema.ObjectKind { return obj }","file":"staging/src/k8s.io/apimachinery/pkg/runtime/register.go","code":"func (obj *TypeMeta) GetObjectKind() schema.ObjectKind { return obj }","line":{"from":31,"to":31}} {"id":100015438,"name":"ParseResourceArg","signature":"func ParseResourceArg(arg string) (*GroupVersionResource, GroupResource)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"// ParseResourceArg takes the common style of string which may be either `resource.group.com` or `resource.version.group.com`\n// and parses it out into both possibilities. This code takes no responsibility for knowing which representation was intended\n// but with a knowledge of all GroupVersions, calling code can take a very good guess. If there are only two segments, then\n// `*GroupVersionResource` is nil.\n// `resource.group.com` -\u003e `group=com, version=group, resource=resource` and `group=group.com, resource=resource`\nfunc ParseResourceArg(arg string) (*GroupVersionResource, GroupResource) {\n\tvar gvr *GroupVersionResource\n\tif strings.Count(arg, \".\") \u003e= 2 {\n\t\ts := strings.SplitN(arg, \".\", 3)\n\t\tgvr = \u0026GroupVersionResource{Group: s[2], Version: s[1], Resource: s[0]}\n\t}\n\n\treturn gvr, ParseGroupResource(arg)\n}","line":{"from":24,"to":37}} {"id":100015439,"name":"ParseKindArg","signature":"func ParseKindArg(arg string) (*GroupVersionKind, GroupKind)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"// ParseKindArg takes the common style of string which may be either `Kind.group.com` or `Kind.version.group.com`\n// and parses it out into both possibilities. This code takes no responsibility for knowing which representation was intended\n// but with a knowledge of all GroupKinds, calling code can take a very good guess. If there are only two segments, then\n// `*GroupVersionResource` is nil.\n// `Kind.group.com` -\u003e `group=com, version=group, kind=Kind` and `group=group.com, kind=Kind`\nfunc ParseKindArg(arg string) (*GroupVersionKind, GroupKind) {\n\tvar gvk *GroupVersionKind\n\tif strings.Count(arg, \".\") \u003e= 2 {\n\t\ts := strings.SplitN(arg, \".\", 3)\n\t\tgvk = \u0026GroupVersionKind{Group: s[2], Version: s[1], Kind: s[0]}\n\t}\n\n\treturn gvk, ParseGroupKind(arg)\n}","line":{"from":39,"to":52}} {"id":100015440,"name":"WithVersion","signature":"func (gr GroupResource) WithVersion(version string) GroupVersionResource","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"func (gr GroupResource) WithVersion(version string) GroupVersionResource {\n\treturn GroupVersionResource{Group: gr.Group, Version: version, Resource: gr.Resource}\n}","line":{"from":61,"to":63}} {"id":100015441,"name":"Empty","signature":"func (gr GroupResource) Empty() bool","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"func (gr GroupResource) Empty() bool {\n\treturn len(gr.Group) == 0 \u0026\u0026 len(gr.Resource) == 0\n}","line":{"from":65,"to":67}} {"id":100015442,"name":"String","signature":"func (gr GroupResource) String() string","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"func (gr GroupResource) String() string {\n\tif len(gr.Group) == 0 {\n\t\treturn gr.Resource\n\t}\n\treturn gr.Resource + \".\" + gr.Group\n}","line":{"from":69,"to":74}} {"id":100015443,"name":"ParseGroupKind","signature":"func ParseGroupKind(gk string) GroupKind","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"func ParseGroupKind(gk string) GroupKind {\n\ti := strings.Index(gk, \".\")\n\tif i == -1 {\n\t\treturn GroupKind{Kind: gk}\n\t}\n\n\treturn GroupKind{Group: gk[i+1:], Kind: gk[:i]}\n}","line":{"from":76,"to":83}} {"id":100015444,"name":"ParseGroupResource","signature":"func ParseGroupResource(gr string) GroupResource","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"// ParseGroupResource turns \"resource.group\" string into a GroupResource struct. Empty strings are allowed\n// for each field.\nfunc ParseGroupResource(gr string) GroupResource {\n\tif i := strings.Index(gr, \".\"); i \u003e= 0 {\n\t\treturn GroupResource{Group: gr[i+1:], Resource: gr[:i]}\n\t}\n\treturn GroupResource{Resource: gr}\n}","line":{"from":85,"to":92}} {"id":100015445,"name":"Empty","signature":"func (gvr GroupVersionResource) Empty() bool","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"func (gvr GroupVersionResource) Empty() bool {\n\treturn len(gvr.Group) == 0 \u0026\u0026 len(gvr.Version) == 0 \u0026\u0026 len(gvr.Resource) == 0\n}","line":{"from":102,"to":104}} {"id":100015446,"name":"GroupResource","signature":"func (gvr GroupVersionResource) GroupResource() GroupResource","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"func (gvr GroupVersionResource) GroupResource() GroupResource {\n\treturn GroupResource{Group: gvr.Group, Resource: gvr.Resource}\n}","line":{"from":106,"to":108}} {"id":100015447,"name":"GroupVersion","signature":"func (gvr GroupVersionResource) GroupVersion() GroupVersion","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"func (gvr GroupVersionResource) GroupVersion() GroupVersion {\n\treturn GroupVersion{Group: gvr.Group, Version: gvr.Version}\n}","line":{"from":110,"to":112}} {"id":100015448,"name":"String","signature":"func (gvr GroupVersionResource) String() string","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"func (gvr GroupVersionResource) String() string {\n\treturn strings.Join([]string{gvr.Group, \"/\", gvr.Version, \", Resource=\", gvr.Resource}, \"\")\n}","line":{"from":114,"to":116}} {"id":100015449,"name":"Empty","signature":"func (gk GroupKind) Empty() bool","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"func (gk GroupKind) Empty() bool {\n\treturn len(gk.Group) == 0 \u0026\u0026 len(gk.Kind) == 0\n}","line":{"from":125,"to":127}} {"id":100015450,"name":"WithVersion","signature":"func (gk GroupKind) WithVersion(version string) GroupVersionKind","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"func (gk GroupKind) WithVersion(version string) GroupVersionKind {\n\treturn GroupVersionKind{Group: gk.Group, Version: version, Kind: gk.Kind}\n}","line":{"from":129,"to":131}} {"id":100015451,"name":"String","signature":"func (gk GroupKind) String() string","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"func (gk GroupKind) String() string {\n\tif len(gk.Group) == 0 {\n\t\treturn gk.Kind\n\t}\n\treturn gk.Kind + \".\" + gk.Group\n}","line":{"from":133,"to":138}} {"id":100015452,"name":"Empty","signature":"func (gvk GroupVersionKind) Empty() bool","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"// Empty returns true if group, version, and kind are empty\nfunc (gvk GroupVersionKind) Empty() bool {\n\treturn len(gvk.Group) == 0 \u0026\u0026 len(gvk.Version) == 0 \u0026\u0026 len(gvk.Kind) == 0\n}","line":{"from":148,"to":151}} {"id":100015453,"name":"GroupKind","signature":"func (gvk GroupVersionKind) GroupKind() GroupKind","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"func (gvk GroupVersionKind) GroupKind() GroupKind {\n\treturn GroupKind{Group: gvk.Group, Kind: gvk.Kind}\n}","line":{"from":153,"to":155}} {"id":100015454,"name":"GroupVersion","signature":"func (gvk GroupVersionKind) GroupVersion() GroupVersion","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"func (gvk GroupVersionKind) GroupVersion() GroupVersion {\n\treturn GroupVersion{Group: gvk.Group, Version: gvk.Version}\n}","line":{"from":157,"to":159}} {"id":100015455,"name":"String","signature":"func (gvk GroupVersionKind) String() string","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"func (gvk GroupVersionKind) String() string {\n\treturn gvk.Group + \"/\" + gvk.Version + \", Kind=\" + gvk.Kind\n}","line":{"from":161,"to":163}} {"id":100015456,"name":"Empty","signature":"func (gv GroupVersion) Empty() bool","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"// Empty returns true if group and version are empty\nfunc (gv GroupVersion) Empty() bool {\n\treturn len(gv.Group) == 0 \u0026\u0026 len(gv.Version) == 0\n}","line":{"from":171,"to":174}} {"id":100015457,"name":"String","signature":"func (gv GroupVersion) String() string","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"// String puts \"group\" and \"version\" into a single \"group/version\" string. For the legacy v1\n// it returns \"v1\".\nfunc (gv GroupVersion) String() string {\n\tif len(gv.Group) \u003e 0 {\n\t\treturn gv.Group + \"/\" + gv.Version\n\t}\n\treturn gv.Version\n}","line":{"from":176,"to":183}} {"id":100015458,"name":"Identifier","signature":"func (gv GroupVersion) Identifier() string","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"// Identifier implements runtime.GroupVersioner interface.\nfunc (gv GroupVersion) Identifier() string {\n\treturn gv.String()\n}","line":{"from":185,"to":188}} {"id":100015459,"name":"KindForGroupVersionKinds","signature":"func (gv GroupVersion) KindForGroupVersionKinds(kinds []GroupVersionKind) (target GroupVersionKind, ok bool)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"// KindForGroupVersionKinds identifies the preferred GroupVersionKind out of a list. It returns ok false\n// if none of the options match the group. It prefers a match to group and version over just group.\n// TODO: Move GroupVersion to a package under pkg/runtime, since it's used by scheme.\n// TODO: Introduce an adapter type between GroupVersion and runtime.GroupVersioner, and use LegacyCodec(GroupVersion)\n// in fewer places.\nfunc (gv GroupVersion) KindForGroupVersionKinds(kinds []GroupVersionKind) (target GroupVersionKind, ok bool) {\n\tfor _, gvk := range kinds {\n\t\tif gvk.Group == gv.Group \u0026\u0026 gvk.Version == gv.Version {\n\t\t\treturn gvk, true\n\t\t}\n\t}\n\tfor _, gvk := range kinds {\n\t\tif gvk.Group == gv.Group {\n\t\t\treturn gv.WithKind(gvk.Kind), true\n\t\t}\n\t}\n\treturn GroupVersionKind{}, false\n}","line":{"from":190,"to":207}} {"id":100015460,"name":"ParseGroupVersion","signature":"func ParseGroupVersion(gv string) (GroupVersion, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"// ParseGroupVersion turns \"group/version\" string into a GroupVersion struct. It reports error\n// if it cannot parse the string.\nfunc ParseGroupVersion(gv string) (GroupVersion, error) {\n\t// this can be the internal version for the legacy kube types\n\t// TODO once we've cleared the last uses as strings, this special case should be removed.\n\tif (len(gv) == 0) || (gv == \"/\") {\n\t\treturn GroupVersion{}, nil\n\t}\n\n\tswitch strings.Count(gv, \"/\") {\n\tcase 0:\n\t\treturn GroupVersion{\"\", gv}, nil\n\tcase 1:\n\t\ti := strings.Index(gv, \"/\")\n\t\treturn GroupVersion{gv[:i], gv[i+1:]}, nil\n\tdefault:\n\t\treturn GroupVersion{}, fmt.Errorf(\"unexpected GroupVersion string: %v\", gv)\n\t}\n}","line":{"from":209,"to":227}} {"id":100015461,"name":"WithKind","signature":"func (gv GroupVersion) WithKind(kind string) GroupVersionKind","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"// WithKind creates a GroupVersionKind based on the method receiver's GroupVersion and the passed Kind.\nfunc (gv GroupVersion) WithKind(kind string) GroupVersionKind {\n\treturn GroupVersionKind{Group: gv.Group, Version: gv.Version, Kind: kind}\n}","line":{"from":229,"to":232}} {"id":100015462,"name":"WithResource","signature":"func (gv GroupVersion) WithResource(resource string) GroupVersionResource","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"// WithResource creates a GroupVersionResource based on the method receiver's GroupVersion and the passed Resource.\nfunc (gv GroupVersion) WithResource(resource string) GroupVersionResource {\n\treturn GroupVersionResource{Group: gv.Group, Version: gv.Version, Resource: resource}\n}","line":{"from":234,"to":237}} {"id":100015463,"name":"Identifier","signature":"func (gvs GroupVersions) Identifier() string","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"// Identifier implements runtime.GroupVersioner interface.\nfunc (gvs GroupVersions) Identifier() string {\n\tgroupVersions := make([]string, 0, len(gvs))\n\tfor i := range gvs {\n\t\tgroupVersions = append(groupVersions, gvs[i].String())\n\t}\n\treturn fmt.Sprintf(\"[%s]\", strings.Join(groupVersions, \",\"))\n}","line":{"from":245,"to":252}} {"id":100015464,"name":"KindForGroupVersionKinds","signature":"func (gvs GroupVersions) KindForGroupVersionKinds(kinds []GroupVersionKind) (GroupVersionKind, bool)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"// KindForGroupVersionKinds identifies the preferred GroupVersionKind out of a list. It returns ok false\n// if none of the options match the group.\nfunc (gvs GroupVersions) KindForGroupVersionKinds(kinds []GroupVersionKind) (GroupVersionKind, bool) {\n\tvar targets []GroupVersionKind\n\tfor _, gv := range gvs {\n\t\ttarget, ok := gv.KindForGroupVersionKinds(kinds)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\ttargets = append(targets, target)\n\t}\n\tif len(targets) == 1 {\n\t\treturn targets[0], true\n\t}\n\tif len(targets) \u003e 1 {\n\t\treturn bestMatch(kinds, targets), true\n\t}\n\treturn GroupVersionKind{}, false\n}","line":{"from":254,"to":272}} {"id":100015465,"name":"bestMatch","signature":"func bestMatch(kinds []GroupVersionKind, targets []GroupVersionKind) GroupVersionKind","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"// bestMatch tries to pick best matching GroupVersionKind and falls back to the first\n// found if no exact match exists.\nfunc bestMatch(kinds []GroupVersionKind, targets []GroupVersionKind) GroupVersionKind {\n\tfor _, gvk := range targets {\n\t\tfor _, k := range kinds {\n\t\t\tif k == gvk {\n\t\t\t\treturn k\n\t\t\t}\n\t\t}\n\t}\n\treturn targets[0]\n}","line":{"from":274,"to":285}} {"id":100015466,"name":"ToAPIVersionAndKind","signature":"func (gvk GroupVersionKind) ToAPIVersionAndKind() (string, string)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"// ToAPIVersionAndKind is a convenience method for satisfying runtime.Object on types that\n// do not use TypeMeta.\nfunc (gvk GroupVersionKind) ToAPIVersionAndKind() (string, string) {\n\tif gvk.Empty() {\n\t\treturn \"\", \"\"\n\t}\n\treturn gvk.GroupVersion().String(), gvk.Kind\n}","line":{"from":287,"to":294}} {"id":100015467,"name":"FromAPIVersionAndKind","signature":"func FromAPIVersionAndKind(apiVersion, kind string) GroupVersionKind","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/group_version.go","code":"// FromAPIVersionAndKind returns a GVK representing the provided fields for types that\n// do not use TypeMeta. This method exists to support test types and legacy serializations\n// that have a distinct group and kind.\n// TODO: further reduce usage of this method.\nfunc FromAPIVersionAndKind(apiVersion, kind string) GroupVersionKind {\n\tif gv, err := ParseGroupVersion(apiVersion); err == nil {\n\t\treturn GroupVersionKind{Group: gv.Group, Version: gv.Version, Kind: kind}\n\t}\n\treturn GroupVersionKind{Kind: kind}\n}","line":{"from":296,"to":305}} {"id":100015468,"name":"SetGroupVersionKind","signature":"func (emptyObjectKind) SetGroupVersionKind(gvk GroupVersionKind) {}","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/interfaces.go","code":"// SetGroupVersionKind implements the ObjectKind interface\nfunc (emptyObjectKind) SetGroupVersionKind(gvk GroupVersionKind) {}","line":{"from":36,"to":37}} {"id":100015469,"name":"GroupVersionKind","signature":"func (emptyObjectKind) GroupVersionKind() GroupVersionKind { return GroupVersionKind{} }","file":"staging/src/k8s.io/apimachinery/pkg/runtime/schema/interfaces.go","code":"// GroupVersionKind implements the ObjectKind interface\nfunc (emptyObjectKind) GroupVersionKind() GroupVersionKind { return GroupVersionKind{} }","line":{"from":39,"to":40}} {"id":100015470,"name":"NewScheme","signature":"func NewScheme() *Scheme","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// NewScheme creates a new Scheme. This scheme is pluggable by default.\nfunc NewScheme() *Scheme {\n\ts := \u0026Scheme{\n\t\tgvkToType: map[schema.GroupVersionKind]reflect.Type{},\n\t\ttypeToGVK: map[reflect.Type][]schema.GroupVersionKind{},\n\t\tunversionedTypes: map[reflect.Type]schema.GroupVersionKind{},\n\t\tunversionedKinds: map[string]reflect.Type{},\n\t\tfieldLabelConversionFuncs: map[schema.GroupVersionKind]FieldLabelConversionFunc{},\n\t\tdefaulterFuncs: map[reflect.Type]func(interface{}){},\n\t\tversionPriority: map[string][]string{},\n\t\tschemeName: naming.GetNameFromCallsite(internalPackages...),\n\t}\n\ts.converter = conversion.NewConverter(nil)\n\n\t// Enable couple default conversions by default.\n\tutilruntime.Must(RegisterEmbeddedConversions(s))\n\tutilruntime.Must(RegisterStringConversions(s))\n\treturn s\n}","line":{"from":90,"to":108}} {"id":100015471,"name":"Converter","signature":"func (s *Scheme) Converter() *conversion.Converter","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// Converter allows access to the converter for the scheme\nfunc (s *Scheme) Converter() *conversion.Converter {\n\treturn s.converter\n}","line":{"from":110,"to":113}} {"id":100015472,"name":"AddUnversionedTypes","signature":"func (s *Scheme) AddUnversionedTypes(version schema.GroupVersion, types ...Object)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// AddUnversionedTypes registers the provided types as \"unversioned\", which means that they follow special rules.\n// Whenever an object of this type is serialized, it is serialized with the provided group version and is not\n// converted. Thus unversioned objects are expected to remain backwards compatible forever, as if they were in an\n// API group and version that would never be updated.\n//\n// TODO: there is discussion about removing unversioned and replacing it with objects that are manifest into\n// every version with particular schemas. Resolve this method at that point.\nfunc (s *Scheme) AddUnversionedTypes(version schema.GroupVersion, types ...Object) {\n\ts.addObservedVersion(version)\n\ts.AddKnownTypes(version, types...)\n\tfor _, obj := range types {\n\t\tt := reflect.TypeOf(obj).Elem()\n\t\tgvk := version.WithKind(t.Name())\n\t\ts.unversionedTypes[t] = gvk\n\t\tif old, ok := s.unversionedKinds[gvk.Kind]; ok \u0026\u0026 t != old {\n\t\t\tpanic(fmt.Sprintf(\"%v.%v has already been registered as unversioned kind %q - kind name must be unique in scheme %q\", old.PkgPath(), old.Name(), gvk, s.schemeName))\n\t\t}\n\t\ts.unversionedKinds[gvk.Kind] = t\n\t}\n}","line":{"from":115,"to":134}} {"id":100015473,"name":"AddKnownTypes","signature":"func (s *Scheme) AddKnownTypes(gv schema.GroupVersion, types ...Object)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// AddKnownTypes registers all types passed in 'types' as being members of version 'version'.\n// All objects passed to types should be pointers to structs. The name that go reports for\n// the struct becomes the \"kind\" field when encoding. Version may not be empty - use the\n// APIVersionInternal constant if you have a type that does not have a formal version.\nfunc (s *Scheme) AddKnownTypes(gv schema.GroupVersion, types ...Object) {\n\ts.addObservedVersion(gv)\n\tfor _, obj := range types {\n\t\tt := reflect.TypeOf(obj)\n\t\tif t.Kind() != reflect.Pointer {\n\t\t\tpanic(\"All types must be pointers to structs.\")\n\t\t}\n\t\tt = t.Elem()\n\t\ts.AddKnownTypeWithName(gv.WithKind(t.Name()), obj)\n\t}\n}","line":{"from":136,"to":150}} {"id":100015474,"name":"AddKnownTypeWithName","signature":"func (s *Scheme) AddKnownTypeWithName(gvk schema.GroupVersionKind, obj Object)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// AddKnownTypeWithName is like AddKnownTypes, but it lets you specify what this type should\n// be encoded as. Useful for testing when you don't want to make multiple packages to define\n// your structs. Version may not be empty - use the APIVersionInternal constant if you have a\n// type that does not have a formal version.\nfunc (s *Scheme) AddKnownTypeWithName(gvk schema.GroupVersionKind, obj Object) {\n\ts.addObservedVersion(gvk.GroupVersion())\n\tt := reflect.TypeOf(obj)\n\tif len(gvk.Version) == 0 {\n\t\tpanic(fmt.Sprintf(\"version is required on all types: %s %v\", gvk, t))\n\t}\n\tif t.Kind() != reflect.Pointer {\n\t\tpanic(\"All types must be pointers to structs.\")\n\t}\n\tt = t.Elem()\n\tif t.Kind() != reflect.Struct {\n\t\tpanic(\"All types must be pointers to structs.\")\n\t}\n\n\tif oldT, found := s.gvkToType[gvk]; found \u0026\u0026 oldT != t {\n\t\tpanic(fmt.Sprintf(\"Double registration of different types for %v: old=%v.%v, new=%v.%v in scheme %q\", gvk, oldT.PkgPath(), oldT.Name(), t.PkgPath(), t.Name(), s.schemeName))\n\t}\n\n\ts.gvkToType[gvk] = t\n\n\tfor _, existingGvk := range s.typeToGVK[t] {\n\t\tif existingGvk == gvk {\n\t\t\treturn\n\t\t}\n\t}\n\ts.typeToGVK[t] = append(s.typeToGVK[t], gvk)\n\n\t// if the type implements DeepCopyInto(\u003cobj\u003e), register a self-conversion\n\tif m := reflect.ValueOf(obj).MethodByName(\"DeepCopyInto\"); m.IsValid() \u0026\u0026 m.Type().NumIn() == 1 \u0026\u0026 m.Type().NumOut() == 0 \u0026\u0026 m.Type().In(0) == reflect.TypeOf(obj) {\n\t\tif err := s.AddGeneratedConversionFunc(obj, obj, func(a, b interface{}, scope conversion.Scope) error {\n\t\t\t// copy a to b\n\t\t\treflect.ValueOf(a).MethodByName(\"DeepCopyInto\").Call([]reflect.Value{reflect.ValueOf(b)})\n\t\t\t// clear TypeMeta to match legacy reflective conversion\n\t\t\tb.(Object).GetObjectKind().SetGroupVersionKind(schema.GroupVersionKind{})\n\t\t\treturn nil\n\t\t}); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}","line":{"from":152,"to":195}} {"id":100015475,"name":"KnownTypes","signature":"func (s *Scheme) KnownTypes(gv schema.GroupVersion) map[string]reflect.Type","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// KnownTypes returns the types known for the given version.\nfunc (s *Scheme) KnownTypes(gv schema.GroupVersion) map[string]reflect.Type {\n\ttypes := make(map[string]reflect.Type)\n\tfor gvk, t := range s.gvkToType {\n\t\tif gv != gvk.GroupVersion() {\n\t\t\tcontinue\n\t\t}\n\n\t\ttypes[gvk.Kind] = t\n\t}\n\treturn types\n}","line":{"from":197,"to":208}} {"id":100015476,"name":"VersionsForGroupKind","signature":"func (s *Scheme) VersionsForGroupKind(gk schema.GroupKind) []schema.GroupVersion","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// VersionsForGroupKind returns the versions that a particular GroupKind can be converted to within the given group.\n// A GroupKind might be converted to a different group. That information is available in EquivalentResourceMapper.\nfunc (s *Scheme) VersionsForGroupKind(gk schema.GroupKind) []schema.GroupVersion {\n\tavailableVersions := []schema.GroupVersion{}\n\tfor gvk := range s.gvkToType {\n\t\tif gk != gvk.GroupKind() {\n\t\t\tcontinue\n\t\t}\n\n\t\tavailableVersions = append(availableVersions, gvk.GroupVersion())\n\t}\n\n\t// order the return for stability\n\tret := []schema.GroupVersion{}\n\tfor _, version := range s.PrioritizedVersionsForGroup(gk.Group) {\n\t\tfor _, availableVersion := range availableVersions {\n\t\t\tif version != availableVersion {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tret = append(ret, availableVersion)\n\t\t}\n\t}\n\n\treturn ret\n}","line":{"from":210,"to":234}} {"id":100015477,"name":"AllKnownTypes","signature":"func (s *Scheme) AllKnownTypes() map[schema.GroupVersionKind]reflect.Type","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// AllKnownTypes returns the all known types.\nfunc (s *Scheme) AllKnownTypes() map[schema.GroupVersionKind]reflect.Type {\n\treturn s.gvkToType\n}","line":{"from":236,"to":239}} {"id":100015478,"name":"ObjectKinds","signature":"func (s *Scheme) ObjectKinds(obj Object) ([]schema.GroupVersionKind, bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// ObjectKinds returns all possible group,version,kind of the go object, true if the\n// object is considered unversioned, or an error if it's not a pointer or is unregistered.\nfunc (s *Scheme) ObjectKinds(obj Object) ([]schema.GroupVersionKind, bool, error) {\n\t// Unstructured objects are always considered to have their declared GVK\n\tif _, ok := obj.(Unstructured); ok {\n\t\t// we require that the GVK be populated in order to recognize the object\n\t\tgvk := obj.GetObjectKind().GroupVersionKind()\n\t\tif len(gvk.Kind) == 0 {\n\t\t\treturn nil, false, NewMissingKindErr(\"unstructured object has no kind\")\n\t\t}\n\t\tif len(gvk.Version) == 0 {\n\t\t\treturn nil, false, NewMissingVersionErr(\"unstructured object has no version\")\n\t\t}\n\t\treturn []schema.GroupVersionKind{gvk}, false, nil\n\t}\n\n\tv, err := conversion.EnforcePtr(obj)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\tt := v.Type()\n\n\tgvks, ok := s.typeToGVK[t]\n\tif !ok {\n\t\treturn nil, false, NewNotRegisteredErrForType(s.schemeName, t)\n\t}\n\t_, unversionedType := s.unversionedTypes[t]\n\n\treturn gvks, unversionedType, nil\n}","line":{"from":241,"to":270}} {"id":100015479,"name":"Recognizes","signature":"func (s *Scheme) Recognizes(gvk schema.GroupVersionKind) bool","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// Recognizes returns true if the scheme is able to handle the provided group,version,kind\n// of an object.\nfunc (s *Scheme) Recognizes(gvk schema.GroupVersionKind) bool {\n\t_, exists := s.gvkToType[gvk]\n\treturn exists\n}","line":{"from":272,"to":277}} {"id":100015480,"name":"IsUnversioned","signature":"func (s *Scheme) IsUnversioned(obj Object) (bool, bool)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"func (s *Scheme) IsUnversioned(obj Object) (bool, bool) {\n\tv, err := conversion.EnforcePtr(obj)\n\tif err != nil {\n\t\treturn false, false\n\t}\n\tt := v.Type()\n\n\tif _, ok := s.typeToGVK[t]; !ok {\n\t\treturn false, false\n\t}\n\t_, ok := s.unversionedTypes[t]\n\treturn ok, true\n}","line":{"from":279,"to":291}} {"id":100015481,"name":"New","signature":"func (s *Scheme) New(kind schema.GroupVersionKind) (Object, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// New returns a new API object of the given version and name, or an error if it hasn't\n// been registered. The version and kind fields must be specified.\nfunc (s *Scheme) New(kind schema.GroupVersionKind) (Object, error) {\n\tif t, exists := s.gvkToType[kind]; exists {\n\t\treturn reflect.New(t).Interface().(Object), nil\n\t}\n\n\tif t, exists := s.unversionedKinds[kind.Kind]; exists {\n\t\treturn reflect.New(t).Interface().(Object), nil\n\t}\n\treturn nil, NewNotRegisteredErrForKind(s.schemeName, kind)\n}","line":{"from":293,"to":304}} {"id":100015482,"name":"AddIgnoredConversionType","signature":"func (s *Scheme) AddIgnoredConversionType(from, to interface{}) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// AddIgnoredConversionType identifies a pair of types that should be skipped by\n// conversion (because the data inside them is explicitly dropped during\n// conversion).\nfunc (s *Scheme) AddIgnoredConversionType(from, to interface{}) error {\n\treturn s.converter.RegisterIgnoredConversion(from, to)\n}","line":{"from":306,"to":311}} {"id":100015483,"name":"AddConversionFunc","signature":"func (s *Scheme) AddConversionFunc(a, b interface{}, fn conversion.ConversionFunc) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// AddConversionFunc registers a function that converts between a and b by passing objects of those\n// types to the provided function. The function *must* accept objects of a and b - this machinery will not enforce\n// any other guarantee.\nfunc (s *Scheme) AddConversionFunc(a, b interface{}, fn conversion.ConversionFunc) error {\n\treturn s.converter.RegisterUntypedConversionFunc(a, b, fn)\n}","line":{"from":313,"to":318}} {"id":100015484,"name":"AddGeneratedConversionFunc","signature":"func (s *Scheme) AddGeneratedConversionFunc(a, b interface{}, fn conversion.ConversionFunc) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// AddGeneratedConversionFunc registers a function that converts between a and b by passing objects of those\n// types to the provided function. The function *must* accept objects of a and b - this machinery will not enforce\n// any other guarantee.\nfunc (s *Scheme) AddGeneratedConversionFunc(a, b interface{}, fn conversion.ConversionFunc) error {\n\treturn s.converter.RegisterGeneratedUntypedConversionFunc(a, b, fn)\n}","line":{"from":320,"to":325}} {"id":100015485,"name":"AddFieldLabelConversionFunc","signature":"func (s *Scheme) AddFieldLabelConversionFunc(gvk schema.GroupVersionKind, conversionFunc FieldLabelConversionFunc) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// AddFieldLabelConversionFunc adds a conversion function to convert field selectors\n// of the given kind from the given version to internal version representation.\nfunc (s *Scheme) AddFieldLabelConversionFunc(gvk schema.GroupVersionKind, conversionFunc FieldLabelConversionFunc) error {\n\ts.fieldLabelConversionFuncs[gvk] = conversionFunc\n\treturn nil\n}","line":{"from":327,"to":332}} {"id":100015486,"name":"AddTypeDefaultingFunc","signature":"func (s *Scheme) AddTypeDefaultingFunc(srcType Object, fn func(interface{}))","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// AddTypeDefaultingFunc registers a function that is passed a pointer to an\n// object and can default fields on the object. These functions will be invoked\n// when Default() is called. The function will never be called unless the\n// defaulted object matches srcType. If this function is invoked twice with the\n// same srcType, the fn passed to the later call will be used instead.\nfunc (s *Scheme) AddTypeDefaultingFunc(srcType Object, fn func(interface{})) {\n\ts.defaulterFuncs[reflect.TypeOf(srcType)] = fn\n}","line":{"from":334,"to":341}} {"id":100015487,"name":"Default","signature":"func (s *Scheme) Default(src Object)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// Default sets defaults on the provided Object.\nfunc (s *Scheme) Default(src Object) {\n\tif fn, ok := s.defaulterFuncs[reflect.TypeOf(src)]; ok {\n\t\tfn(src)\n\t}\n}","line":{"from":343,"to":348}} {"id":100015488,"name":"Convert","signature":"func (s *Scheme) Convert(in, out interface{}, context interface{}) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// Convert will attempt to convert in into out. Both must be pointers. For easy\n// testing of conversion functions. Returns an error if the conversion isn't\n// possible. You can call this with types that haven't been registered (for example,\n// a to test conversion of types that are nested within registered types). The\n// context interface is passed to the convertor. Convert also supports Unstructured\n// types and will convert them intelligently.\nfunc (s *Scheme) Convert(in, out interface{}, context interface{}) error {\n\tunstructuredIn, okIn := in.(Unstructured)\n\tunstructuredOut, okOut := out.(Unstructured)\n\tswitch {\n\tcase okIn \u0026\u0026 okOut:\n\t\t// converting unstructured input to an unstructured output is a straight copy - unstructured\n\t\t// is a \"smart holder\" and the contents are passed by reference between the two objects\n\t\tunstructuredOut.SetUnstructuredContent(unstructuredIn.UnstructuredContent())\n\t\treturn nil\n\n\tcase okOut:\n\t\t// if the output is an unstructured object, use the standard Go type to unstructured\n\t\t// conversion. The object must not be internal.\n\t\tobj, ok := in.(Object)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unable to convert object type %T to Unstructured, must be a runtime.Object\", in)\n\t\t}\n\t\tgvks, unversioned, err := s.ObjectKinds(obj)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgvk := gvks[0]\n\n\t\t// if no conversion is necessary, convert immediately\n\t\tif unversioned || gvk.Version != APIVersionInternal {\n\t\t\tcontent, err := DefaultUnstructuredConverter.ToUnstructured(in)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tunstructuredOut.SetUnstructuredContent(content)\n\t\t\tunstructuredOut.GetObjectKind().SetGroupVersionKind(gvk)\n\t\t\treturn nil\n\t\t}\n\n\t\t// attempt to convert the object to an external version first.\n\t\ttarget, ok := context.(GroupVersioner)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unable to convert the internal object type %T to Unstructured without providing a preferred version to convert to\", in)\n\t\t}\n\t\t// Convert is implicitly unsafe, so we don't need to perform a safe conversion\n\t\tversioned, err := s.UnsafeConvertToVersion(obj, target)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcontent, err := DefaultUnstructuredConverter.ToUnstructured(versioned)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tunstructuredOut.SetUnstructuredContent(content)\n\t\treturn nil\n\n\tcase okIn:\n\t\t// converting an unstructured object to any type is modeled by first converting\n\t\t// the input to a versioned type, then running standard conversions\n\t\ttyped, err := s.unstructuredToTyped(unstructuredIn)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tin = typed\n\t}\n\n\tmeta := s.generateConvertMeta(in)\n\tmeta.Context = context\n\treturn s.converter.Convert(in, out, meta)\n}","line":{"from":350,"to":420}} {"id":100015489,"name":"ConvertFieldLabel","signature":"func (s *Scheme) ConvertFieldLabel(gvk schema.GroupVersionKind, label, value string) (string, string, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// ConvertFieldLabel alters the given field label and value for an kind field selector from\n// versioned representation to an unversioned one or returns an error.\nfunc (s *Scheme) ConvertFieldLabel(gvk schema.GroupVersionKind, label, value string) (string, string, error) {\n\tconversionFunc, ok := s.fieldLabelConversionFuncs[gvk]\n\tif !ok {\n\t\treturn DefaultMetaV1FieldSelectorConversion(label, value)\n\t}\n\treturn conversionFunc(label, value)\n}","line":{"from":422,"to":430}} {"id":100015490,"name":"ConvertToVersion","signature":"func (s *Scheme) ConvertToVersion(in Object, target GroupVersioner) (Object, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// ConvertToVersion attempts to convert an input object to its matching Kind in another\n// version within this scheme. Will return an error if the provided version does not\n// contain the inKind (or a mapping by name defined with AddKnownTypeWithName). Will also\n// return an error if the conversion does not result in a valid Object being\n// returned. Passes target down to the conversion methods as the Context on the scope.\nfunc (s *Scheme) ConvertToVersion(in Object, target GroupVersioner) (Object, error) {\n\treturn s.convertToVersion(true, in, target)\n}","line":{"from":432,"to":439}} {"id":100015491,"name":"UnsafeConvertToVersion","signature":"func (s *Scheme) UnsafeConvertToVersion(in Object, target GroupVersioner) (Object, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// UnsafeConvertToVersion will convert in to the provided target if such a conversion is possible,\n// but does not guarantee the output object does not share fields with the input object. It attempts to be as\n// efficient as possible when doing conversion.\nfunc (s *Scheme) UnsafeConvertToVersion(in Object, target GroupVersioner) (Object, error) {\n\treturn s.convertToVersion(false, in, target)\n}","line":{"from":441,"to":446}} {"id":100015492,"name":"convertToVersion","signature":"func (s *Scheme) convertToVersion(copy bool, in Object, target GroupVersioner) (Object, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// convertToVersion handles conversion with an optional copy.\nfunc (s *Scheme) convertToVersion(copy bool, in Object, target GroupVersioner) (Object, error) {\n\tvar t reflect.Type\n\n\tif u, ok := in.(Unstructured); ok {\n\t\ttyped, err := s.unstructuredToTyped(u)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tin = typed\n\t\t// unstructuredToTyped returns an Object, which must be a pointer to a struct.\n\t\tt = reflect.TypeOf(in).Elem()\n\n\t} else {\n\t\t// determine the incoming kinds with as few allocations as possible.\n\t\tt = reflect.TypeOf(in)\n\t\tif t.Kind() != reflect.Pointer {\n\t\t\treturn nil, fmt.Errorf(\"only pointer types may be converted: %v\", t)\n\t\t}\n\t\tt = t.Elem()\n\t\tif t.Kind() != reflect.Struct {\n\t\t\treturn nil, fmt.Errorf(\"only pointers to struct types may be converted: %v\", t)\n\t\t}\n\t}\n\n\tkinds, ok := s.typeToGVK[t]\n\tif !ok || len(kinds) == 0 {\n\t\treturn nil, NewNotRegisteredErrForType(s.schemeName, t)\n\t}\n\n\tgvk, ok := target.KindForGroupVersionKinds(kinds)\n\tif !ok {\n\t\t// try to see if this type is listed as unversioned (for legacy support)\n\t\t// TODO: when we move to server API versions, we should completely remove the unversioned concept\n\t\tif unversionedKind, ok := s.unversionedTypes[t]; ok {\n\t\t\tif gvk, ok := target.KindForGroupVersionKinds([]schema.GroupVersionKind{unversionedKind}); ok {\n\t\t\t\treturn copyAndSetTargetKind(copy, in, gvk)\n\t\t\t}\n\t\t\treturn copyAndSetTargetKind(copy, in, unversionedKind)\n\t\t}\n\t\treturn nil, NewNotRegisteredErrForTarget(s.schemeName, t, target)\n\t}\n\n\t// target wants to use the existing type, set kind and return (no conversion necessary)\n\tfor _, kind := range kinds {\n\t\tif gvk == kind {\n\t\t\treturn copyAndSetTargetKind(copy, in, gvk)\n\t\t}\n\t}\n\n\t// type is unversioned, no conversion necessary\n\tif unversionedKind, ok := s.unversionedTypes[t]; ok {\n\t\tif gvk, ok := target.KindForGroupVersionKinds([]schema.GroupVersionKind{unversionedKind}); ok {\n\t\t\treturn copyAndSetTargetKind(copy, in, gvk)\n\t\t}\n\t\treturn copyAndSetTargetKind(copy, in, unversionedKind)\n\t}\n\n\tout, err := s.New(gvk)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif copy {\n\t\tin = in.DeepCopyObject()\n\t}\n\n\tmeta := s.generateConvertMeta(in)\n\tmeta.Context = target\n\tif err := s.converter.Convert(in, out, meta); err != nil {\n\t\treturn nil, err\n\t}\n\n\tsetTargetKind(out, gvk)\n\treturn out, nil\n}","line":{"from":448,"to":524}} {"id":100015493,"name":"unstructuredToTyped","signature":"func (s *Scheme) unstructuredToTyped(in Unstructured) (Object, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// unstructuredToTyped attempts to transform an unstructured object to a typed\n// object if possible. It will return an error if conversion is not possible, or the versioned\n// Go form of the object. Note that this conversion will lose fields.\nfunc (s *Scheme) unstructuredToTyped(in Unstructured) (Object, error) {\n\t// the type must be something we recognize\n\tgvks, _, err := s.ObjectKinds(in)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttyped, err := s.New(gvks[0])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := DefaultUnstructuredConverter.FromUnstructured(in.UnstructuredContent(), typed); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to convert unstructured object to %v: %v\", gvks[0], err)\n\t}\n\treturn typed, nil\n}","line":{"from":526,"to":543}} {"id":100015494,"name":"generateConvertMeta","signature":"func (s *Scheme) generateConvertMeta(in interface{}) *conversion.Meta","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// generateConvertMeta constructs the meta value we pass to Convert.\nfunc (s *Scheme) generateConvertMeta(in interface{}) *conversion.Meta {\n\treturn s.converter.DefaultMeta(reflect.TypeOf(in))\n}","line":{"from":545,"to":548}} {"id":100015495,"name":"copyAndSetTargetKind","signature":"func copyAndSetTargetKind(copy bool, obj Object, kind schema.GroupVersionKind) (Object, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// copyAndSetTargetKind performs a conditional copy before returning the object, or an error if copy was not successful.\nfunc copyAndSetTargetKind(copy bool, obj Object, kind schema.GroupVersionKind) (Object, error) {\n\tif copy {\n\t\tobj = obj.DeepCopyObject()\n\t}\n\tsetTargetKind(obj, kind)\n\treturn obj, nil\n}","line":{"from":550,"to":557}} {"id":100015496,"name":"setTargetKind","signature":"func setTargetKind(obj Object, kind schema.GroupVersionKind)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// setTargetKind sets the kind on an object, taking into account whether the target kind is the internal version.\nfunc setTargetKind(obj Object, kind schema.GroupVersionKind) {\n\tif kind.Version == APIVersionInternal {\n\t\t// internal is a special case\n\t\t// TODO: look at removing the need to special case this\n\t\tobj.GetObjectKind().SetGroupVersionKind(schema.GroupVersionKind{})\n\t\treturn\n\t}\n\tobj.GetObjectKind().SetGroupVersionKind(kind)\n}","line":{"from":559,"to":568}} {"id":100015497,"name":"SetVersionPriority","signature":"func (s *Scheme) SetVersionPriority(versions ...schema.GroupVersion) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// SetVersionPriority allows specifying a precise order of priority. All specified versions must be in the same group,\n// and the specified order overwrites any previously specified order for this group\nfunc (s *Scheme) SetVersionPriority(versions ...schema.GroupVersion) error {\n\tgroups := sets.String{}\n\torder := []string{}\n\tfor _, version := range versions {\n\t\tif len(version.Version) == 0 || version.Version == APIVersionInternal {\n\t\t\treturn fmt.Errorf(\"internal versions cannot be prioritized: %v\", version)\n\t\t}\n\n\t\tgroups.Insert(version.Group)\n\t\torder = append(order, version.Version)\n\t}\n\tif len(groups) != 1 {\n\t\treturn fmt.Errorf(\"must register versions for exactly one group: %v\", strings.Join(groups.List(), \", \"))\n\t}\n\n\ts.versionPriority[groups.List()[0]] = order\n\treturn nil\n}","line":{"from":570,"to":589}} {"id":100015498,"name":"PrioritizedVersionsForGroup","signature":"func (s *Scheme) PrioritizedVersionsForGroup(group string) []schema.GroupVersion","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// PrioritizedVersionsForGroup returns versions for a single group in priority order\nfunc (s *Scheme) PrioritizedVersionsForGroup(group string) []schema.GroupVersion {\n\tret := []schema.GroupVersion{}\n\tfor _, version := range s.versionPriority[group] {\n\t\tret = append(ret, schema.GroupVersion{Group: group, Version: version})\n\t}\n\tfor _, observedVersion := range s.observedVersions {\n\t\tif observedVersion.Group != group {\n\t\t\tcontinue\n\t\t}\n\t\tfound := false\n\t\tfor _, existing := range ret {\n\t\t\tif existing == observedVersion {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tret = append(ret, observedVersion)\n\t\t}\n\t}\n\n\treturn ret\n}","line":{"from":591,"to":614}} {"id":100015499,"name":"PrioritizedVersionsAllGroups","signature":"func (s *Scheme) PrioritizedVersionsAllGroups() []schema.GroupVersion","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// PrioritizedVersionsAllGroups returns all known versions in their priority order. Groups are random, but\n// versions for a single group are prioritized\nfunc (s *Scheme) PrioritizedVersionsAllGroups() []schema.GroupVersion {\n\tret := []schema.GroupVersion{}\n\tfor group, versions := range s.versionPriority {\n\t\tfor _, version := range versions {\n\t\t\tret = append(ret, schema.GroupVersion{Group: group, Version: version})\n\t\t}\n\t}\n\tfor _, observedVersion := range s.observedVersions {\n\t\tfound := false\n\t\tfor _, existing := range ret {\n\t\t\tif existing == observedVersion {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tret = append(ret, observedVersion)\n\t\t}\n\t}\n\treturn ret\n}","line":{"from":616,"to":638}} {"id":100015500,"name":"PreferredVersionAllGroups","signature":"func (s *Scheme) PreferredVersionAllGroups() []schema.GroupVersion","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// PreferredVersionAllGroups returns the most preferred version for every group.\n// group ordering is random.\nfunc (s *Scheme) PreferredVersionAllGroups() []schema.GroupVersion {\n\tret := []schema.GroupVersion{}\n\tfor group, versions := range s.versionPriority {\n\t\tfor _, version := range versions {\n\t\t\tret = append(ret, schema.GroupVersion{Group: group, Version: version})\n\t\t\tbreak\n\t\t}\n\t}\n\tfor _, observedVersion := range s.observedVersions {\n\t\tfound := false\n\t\tfor _, existing := range ret {\n\t\t\tif existing.Group == observedVersion.Group {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tret = append(ret, observedVersion)\n\t\t}\n\t}\n\n\treturn ret\n}","line":{"from":640,"to":664}} {"id":100015501,"name":"IsGroupRegistered","signature":"func (s *Scheme) IsGroupRegistered(group string) bool","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// IsGroupRegistered returns true if types for the group have been registered with the scheme\nfunc (s *Scheme) IsGroupRegistered(group string) bool {\n\tfor _, observedVersion := range s.observedVersions {\n\t\tif observedVersion.Group == group {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":666,"to":674}} {"id":100015502,"name":"IsVersionRegistered","signature":"func (s *Scheme) IsVersionRegistered(version schema.GroupVersion) bool","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"// IsVersionRegistered returns true if types for the version have been registered with the scheme\nfunc (s *Scheme) IsVersionRegistered(version schema.GroupVersion) bool {\n\tfor _, observedVersion := range s.observedVersions {\n\t\tif observedVersion == version {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":676,"to":685}} {"id":100015503,"name":"addObservedVersion","signature":"func (s *Scheme) addObservedVersion(version schema.GroupVersion)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"func (s *Scheme) addObservedVersion(version schema.GroupVersion) {\n\tif len(version.Version) == 0 || version.Version == APIVersionInternal {\n\t\treturn\n\t}\n\tfor _, observedVersion := range s.observedVersions {\n\t\tif observedVersion == version {\n\t\t\treturn\n\t\t}\n\t}\n\n\ts.observedVersions = append(s.observedVersions, version)\n}","line":{"from":687,"to":698}} {"id":100015504,"name":"Name","signature":"func (s *Scheme) Name() string","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme.go","code":"func (s *Scheme) Name() string {\n\treturn s.schemeName\n}","line":{"from":700,"to":702}} {"id":100015505,"name":"AddToScheme","signature":"func (sb *SchemeBuilder) AddToScheme(s *Scheme) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme_builder.go","code":"// AddToScheme applies all the stored functions to the scheme. A non-nil error\n// indicates that one function failed and the attempt was abandoned.\nfunc (sb *SchemeBuilder) AddToScheme(s *Scheme) error {\n\tfor _, f := range *sb {\n\t\tif err := f(s); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":25,"to":34}} {"id":100015506,"name":"Register","signature":"func (sb *SchemeBuilder) Register(funcs ...func(*Scheme) error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme_builder.go","code":"// Register adds a scheme setup function to the list.\nfunc (sb *SchemeBuilder) Register(funcs ...func(*Scheme) error) {\n\tfor _, f := range funcs {\n\t\t*sb = append(*sb, f)\n\t}\n}","line":{"from":36,"to":41}} {"id":100015507,"name":"NewSchemeBuilder","signature":"func NewSchemeBuilder(funcs ...func(*Scheme) error) SchemeBuilder","file":"staging/src/k8s.io/apimachinery/pkg/runtime/scheme_builder.go","code":"// NewSchemeBuilder calls Register for you.\nfunc NewSchemeBuilder(funcs ...func(*Scheme) error) SchemeBuilder {\n\tvar sb SchemeBuilder\n\tsb.Register(funcs...)\n\treturn sb\n}","line":{"from":43,"to":48}} {"id":100015508,"name":"newSerializersForScheme","signature":"func newSerializersForScheme(scheme *runtime.Scheme, mf json.MetaFactory, options CodecFactoryOptions) []serializerType","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/codec_factory.go","code":"func newSerializersForScheme(scheme *runtime.Scheme, mf json.MetaFactory, options CodecFactoryOptions) []serializerType {\n\tjsonSerializer := json.NewSerializerWithOptions(\n\t\tmf, scheme, scheme,\n\t\tjson.SerializerOptions{Yaml: false, Pretty: false, Strict: options.Strict},\n\t)\n\tjsonSerializerType := serializerType{\n\t\tAcceptContentTypes: []string{runtime.ContentTypeJSON},\n\t\tContentType: runtime.ContentTypeJSON,\n\t\tFileExtensions: []string{\"json\"},\n\t\tEncodesAsText: true,\n\t\tSerializer: jsonSerializer,\n\n\t\tFramer: json.Framer,\n\t\tStreamSerializer: jsonSerializer,\n\t}\n\tif options.Pretty {\n\t\tjsonSerializerType.PrettySerializer = json.NewSerializerWithOptions(\n\t\t\tmf, scheme, scheme,\n\t\t\tjson.SerializerOptions{Yaml: false, Pretty: true, Strict: options.Strict},\n\t\t)\n\t}\n\n\tstrictJSONSerializer := json.NewSerializerWithOptions(\n\t\tmf, scheme, scheme,\n\t\tjson.SerializerOptions{Yaml: false, Pretty: false, Strict: true},\n\t)\n\tjsonSerializerType.StrictSerializer = strictJSONSerializer\n\n\tyamlSerializer := json.NewSerializerWithOptions(\n\t\tmf, scheme, scheme,\n\t\tjson.SerializerOptions{Yaml: true, Pretty: false, Strict: options.Strict},\n\t)\n\tstrictYAMLSerializer := json.NewSerializerWithOptions(\n\t\tmf, scheme, scheme,\n\t\tjson.SerializerOptions{Yaml: true, Pretty: false, Strict: true},\n\t)\n\tprotoSerializer := protobuf.NewSerializer(scheme, scheme)\n\tprotoRawSerializer := protobuf.NewRawSerializer(scheme, scheme)\n\n\tserializers := []serializerType{\n\t\tjsonSerializerType,\n\t\t{\n\t\t\tAcceptContentTypes: []string{runtime.ContentTypeYAML},\n\t\t\tContentType: runtime.ContentTypeYAML,\n\t\t\tFileExtensions: []string{\"yaml\"},\n\t\t\tEncodesAsText: true,\n\t\t\tSerializer: yamlSerializer,\n\t\t\tStrictSerializer: strictYAMLSerializer,\n\t\t},\n\t\t{\n\t\t\tAcceptContentTypes: []string{runtime.ContentTypeProtobuf},\n\t\t\tContentType: runtime.ContentTypeProtobuf,\n\t\t\tFileExtensions: []string{\"pb\"},\n\t\t\tSerializer: protoSerializer,\n\t\t\t// note, strict decoding is unsupported for protobuf,\n\t\t\t// fall back to regular serializing\n\t\t\tStrictSerializer: protoSerializer,\n\n\t\t\tFramer: protobuf.LengthDelimitedFramer,\n\t\t\tStreamSerializer: protoRawSerializer,\n\t\t},\n\t}\n\n\tfor _, fn := range serializerExtensions {\n\t\tif serializer, ok := fn(scheme); ok {\n\t\t\tserializers = append(serializers, serializer)\n\t\t}\n\t}\n\treturn serializers\n}","line":{"from":52,"to":121}} {"id":100015509,"name":"EnablePretty","signature":"func EnablePretty(options *CodecFactoryOptions)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/codec_factory.go","code":"// EnablePretty enables including a pretty serializer along with the non-pretty one\nfunc EnablePretty(options *CodecFactoryOptions) {\n\toptions.Pretty = true\n}","line":{"from":145,"to":148}} {"id":100015510,"name":"DisablePretty","signature":"func DisablePretty(options *CodecFactoryOptions)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/codec_factory.go","code":"// DisablePretty disables including a pretty serializer along with the non-pretty one\nfunc DisablePretty(options *CodecFactoryOptions) {\n\toptions.Pretty = false\n}","line":{"from":150,"to":153}} {"id":100015511,"name":"EnableStrict","signature":"func EnableStrict(options *CodecFactoryOptions)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/codec_factory.go","code":"// EnableStrict enables configuring all serializers in strict mode\nfunc EnableStrict(options *CodecFactoryOptions) {\n\toptions.Strict = true\n}","line":{"from":155,"to":158}} {"id":100015512,"name":"DisableStrict","signature":"func DisableStrict(options *CodecFactoryOptions)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/codec_factory.go","code":"// DisableStrict disables configuring all serializers in strict mode\nfunc DisableStrict(options *CodecFactoryOptions) {\n\toptions.Strict = false\n}","line":{"from":160,"to":163}} {"id":100015513,"name":"NewCodecFactory","signature":"func NewCodecFactory(scheme *runtime.Scheme, mutators ...CodecFactoryOptionsMutator) CodecFactory","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/codec_factory.go","code":"// NewCodecFactory provides methods for retrieving serializers for the supported wire formats\n// and conversion wrappers to define preferred internal and external versions. In the future,\n// as the internal version is used less, callers may instead use a defaulting serializer and\n// only convert objects which are shared internally (Status, common API machinery).\n//\n// Mutators can be passed to change the CodecFactoryOptions before construction of the factory.\n// It is recommended to explicitly pass mutators instead of relying on defaults.\n// By default, Pretty is enabled -- this is conformant with previously supported behavior.\n//\n// TODO: allow other codecs to be compiled in?\n// TODO: accept a scheme interface\nfunc NewCodecFactory(scheme *runtime.Scheme, mutators ...CodecFactoryOptionsMutator) CodecFactory {\n\toptions := CodecFactoryOptions{Pretty: true}\n\tfor _, fn := range mutators {\n\t\tfn(\u0026options)\n\t}\n\n\tserializers := newSerializersForScheme(scheme, json.DefaultMetaFactory, options)\n\treturn newCodecFactory(scheme, serializers)\n}","line":{"from":165,"to":184}} {"id":100015514,"name":"newCodecFactory","signature":"func newCodecFactory(scheme *runtime.Scheme, serializers []serializerType) CodecFactory","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/codec_factory.go","code":"// newCodecFactory is a helper for testing that allows a different metafactory to be specified.\nfunc newCodecFactory(scheme *runtime.Scheme, serializers []serializerType) CodecFactory {\n\tdecoders := make([]runtime.Decoder, 0, len(serializers))\n\tvar accepts []runtime.SerializerInfo\n\talreadyAccepted := make(map[string]struct{})\n\n\tvar legacySerializer runtime.Serializer\n\tfor _, d := range serializers {\n\t\tdecoders = append(decoders, d.Serializer)\n\t\tfor _, mediaType := range d.AcceptContentTypes {\n\t\t\tif _, ok := alreadyAccepted[mediaType]; ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\talreadyAccepted[mediaType] = struct{}{}\n\t\t\tinfo := runtime.SerializerInfo{\n\t\t\t\tMediaType: d.ContentType,\n\t\t\t\tEncodesAsText: d.EncodesAsText,\n\t\t\t\tSerializer: d.Serializer,\n\t\t\t\tPrettySerializer: d.PrettySerializer,\n\t\t\t\tStrictSerializer: d.StrictSerializer,\n\t\t\t}\n\n\t\t\tmediaType, _, err := mime.ParseMediaType(info.MediaType)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tparts := strings.SplitN(mediaType, \"/\", 2)\n\t\t\tinfo.MediaTypeType = parts[0]\n\t\t\tinfo.MediaTypeSubType = parts[1]\n\n\t\t\tif d.StreamSerializer != nil {\n\t\t\t\tinfo.StreamSerializer = \u0026runtime.StreamSerializerInfo{\n\t\t\t\t\tSerializer: d.StreamSerializer,\n\t\t\t\t\tEncodesAsText: d.EncodesAsText,\n\t\t\t\t\tFramer: d.Framer,\n\t\t\t\t}\n\t\t\t}\n\t\t\taccepts = append(accepts, info)\n\t\t\tif mediaType == runtime.ContentTypeJSON {\n\t\t\t\tlegacySerializer = d.Serializer\n\t\t\t}\n\t\t}\n\t}\n\tif legacySerializer == nil {\n\t\tlegacySerializer = serializers[0].Serializer\n\t}\n\n\treturn CodecFactory{\n\t\tscheme: scheme,\n\t\tuniversal: recognizer.NewDecoder(decoders...),\n\n\t\taccepts: accepts,\n\n\t\tlegacySerializer: legacySerializer,\n\t}\n}","line":{"from":186,"to":241}} {"id":100015515,"name":"WithoutConversion","signature":"func (f CodecFactory) WithoutConversion() runtime.NegotiatedSerializer","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/codec_factory.go","code":"// WithoutConversion returns a NegotiatedSerializer that performs no conversion, even if the\n// caller requests it.\nfunc (f CodecFactory) WithoutConversion() runtime.NegotiatedSerializer {\n\treturn WithoutConversionCodecFactory{f}\n}","line":{"from":243,"to":247}} {"id":100015516,"name":"SupportedMediaTypes","signature":"func (f CodecFactory) SupportedMediaTypes() []runtime.SerializerInfo","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/codec_factory.go","code":"// SupportedMediaTypes returns the RFC2046 media types that this factory has serializers for.\nfunc (f CodecFactory) SupportedMediaTypes() []runtime.SerializerInfo {\n\treturn f.accepts\n}","line":{"from":249,"to":252}} {"id":100015517,"name":"LegacyCodec","signature":"func (f CodecFactory) LegacyCodec(version ...schema.GroupVersion) runtime.Codec","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/codec_factory.go","code":"// LegacyCodec encodes output to a given API versions, and decodes output into the internal form from\n// any recognized source. The returned codec will always encode output to JSON. If a type is not\n// found in the list of versions an error will be returned.\n//\n// This method is deprecated - clients and servers should negotiate a serializer by mime-type and\n// invoke CodecForVersions. Callers that need only to read data should use UniversalDecoder().\n//\n// TODO: make this call exist only in pkg/api, and initialize it with the set of default versions.\n// All other callers will be forced to request a Codec directly.\nfunc (f CodecFactory) LegacyCodec(version ...schema.GroupVersion) runtime.Codec {\n\treturn versioning.NewDefaultingCodecForScheme(f.scheme, f.legacySerializer, f.universal, schema.GroupVersions(version), runtime.InternalGroupVersioner)\n}","line":{"from":254,"to":265}} {"id":100015518,"name":"UniversalDeserializer","signature":"func (f CodecFactory) UniversalDeserializer() runtime.Decoder","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/codec_factory.go","code":"// UniversalDeserializer can convert any stored data recognized by this factory into a Go object that satisfies\n// runtime.Object. It does not perform conversion. It does not perform defaulting.\nfunc (f CodecFactory) UniversalDeserializer() runtime.Decoder {\n\treturn f.universal\n}","line":{"from":267,"to":271}} {"id":100015519,"name":"UniversalDecoder","signature":"func (f CodecFactory) UniversalDecoder(versions ...schema.GroupVersion) runtime.Decoder","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/codec_factory.go","code":"// UniversalDecoder returns a runtime.Decoder capable of decoding all known API objects in all known formats. Used\n// by clients that do not need to encode objects but want to deserialize API objects stored on disk. Only decodes\n// objects in groups registered with the scheme. The GroupVersions passed may be used to select alternate\n// versions of objects to return - by default, runtime.APIVersionInternal is used. If any versions are specified,\n// unrecognized groups will be returned in the version they are encoded as (no conversion). This decoder performs\n// defaulting.\n//\n// TODO: the decoder will eventually be removed in favor of dealing with objects in their versioned form\n// TODO: only accept a group versioner\nfunc (f CodecFactory) UniversalDecoder(versions ...schema.GroupVersion) runtime.Decoder {\n\tvar versioner runtime.GroupVersioner\n\tif len(versions) == 0 {\n\t\tversioner = runtime.InternalGroupVersioner\n\t} else {\n\t\tversioner = schema.GroupVersions(versions)\n\t}\n\treturn f.CodecForVersions(nil, f.universal, nil, versioner)\n}","line":{"from":273,"to":290}} {"id":100015520,"name":"CodecForVersions","signature":"func (f CodecFactory) CodecForVersions(encoder runtime.Encoder, decoder runtime.Decoder, encode runtime.GroupVersioner, decode runtime.GroupVersioner) runtime.Codec","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/codec_factory.go","code":"// CodecForVersions creates a codec with the provided serializer. If an object is decoded and its group is not in the list,\n// it will default to runtime.APIVersionInternal. If encode is not specified for an object's group, the object is not\n// converted. If encode or decode are nil, no conversion is performed.\nfunc (f CodecFactory) CodecForVersions(encoder runtime.Encoder, decoder runtime.Decoder, encode runtime.GroupVersioner, decode runtime.GroupVersioner) runtime.Codec {\n\t// TODO: these are for backcompat, remove them in the future\n\tif encode == nil {\n\t\tencode = runtime.DisabledGroupVersioner\n\t}\n\tif decode == nil {\n\t\tdecode = runtime.InternalGroupVersioner\n\t}\n\treturn versioning.NewDefaultingCodecForScheme(f.scheme, encoder, decoder, encode, decode)\n}","line":{"from":292,"to":304}} {"id":100015521,"name":"DecoderToVersion","signature":"func (f CodecFactory) DecoderToVersion(decoder runtime.Decoder, gv runtime.GroupVersioner) runtime.Decoder","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/codec_factory.go","code":"// DecoderToVersion returns a decoder that targets the provided group version.\nfunc (f CodecFactory) DecoderToVersion(decoder runtime.Decoder, gv runtime.GroupVersioner) runtime.Decoder {\n\treturn f.CodecForVersions(nil, decoder, nil, gv)\n}","line":{"from":306,"to":309}} {"id":100015522,"name":"EncoderForVersion","signature":"func (f CodecFactory) EncoderForVersion(encoder runtime.Encoder, gv runtime.GroupVersioner) runtime.Encoder","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/codec_factory.go","code":"// EncoderForVersion returns an encoder that targets the provided group version.\nfunc (f CodecFactory) EncoderForVersion(encoder runtime.Encoder, gv runtime.GroupVersioner) runtime.Encoder {\n\treturn f.CodecForVersions(encoder, nil, gv, nil)\n}","line":{"from":311,"to":314}} {"id":100015523,"name":"EncoderForVersion","signature":"func (f WithoutConversionCodecFactory) EncoderForVersion(serializer runtime.Encoder, version runtime.GroupVersioner) runtime.Encoder","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/codec_factory.go","code":"// EncoderForVersion returns an encoder that does not do conversion, but does set the group version kind of the object\n// when serialized.\nfunc (f WithoutConversionCodecFactory) EncoderForVersion(serializer runtime.Encoder, version runtime.GroupVersioner) runtime.Encoder {\n\treturn runtime.WithVersionEncoder{\n\t\tVersion: version,\n\t\tEncoder: serializer,\n\t\tObjectTyper: f.CodecFactory.scheme,\n\t}\n}","line":{"from":323,"to":331}} {"id":100015524,"name":"DecoderToVersion","signature":"func (f WithoutConversionCodecFactory) DecoderToVersion(serializer runtime.Decoder, _ runtime.GroupVersioner) runtime.Decoder","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/codec_factory.go","code":"// DecoderToVersion returns an decoder that does not do conversion.\nfunc (f WithoutConversionCodecFactory) DecoderToVersion(serializer runtime.Decoder, _ runtime.GroupVersioner) runtime.Decoder {\n\treturn runtime.WithoutVersionDecoder{\n\t\tDecoder: serializer,\n\t}\n}","line":{"from":333,"to":338}} {"id":100015525,"name":"NewSerializer","signature":"func NewSerializer(meta MetaFactory, creater runtime.ObjectCreater, typer runtime.ObjectTyper, pretty bool) *Serializer","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go","code":"// NewSerializer creates a JSON serializer that handles encoding versioned objects into the proper JSON form. If typer\n// is not nil, the object has the group, version, and kind fields set.\n// Deprecated: use NewSerializerWithOptions instead.\nfunc NewSerializer(meta MetaFactory, creater runtime.ObjectCreater, typer runtime.ObjectTyper, pretty bool) *Serializer {\n\treturn NewSerializerWithOptions(meta, creater, typer, SerializerOptions{false, pretty, false})\n}","line":{"from":35,"to":40}} {"id":100015526,"name":"NewYAMLSerializer","signature":"func NewYAMLSerializer(meta MetaFactory, creater runtime.ObjectCreater, typer runtime.ObjectTyper) *Serializer","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go","code":"// NewYAMLSerializer creates a YAML serializer that handles encoding versioned objects into the proper YAML form. If typer\n// is not nil, the object has the group, version, and kind fields set. This serializer supports only the subset of YAML that\n// matches JSON, and will error if constructs are used that do not serialize to JSON.\n// Deprecated: use NewSerializerWithOptions instead.\nfunc NewYAMLSerializer(meta MetaFactory, creater runtime.ObjectCreater, typer runtime.ObjectTyper) *Serializer {\n\treturn NewSerializerWithOptions(meta, creater, typer, SerializerOptions{true, false, false})\n}","line":{"from":42,"to":48}} {"id":100015527,"name":"NewSerializerWithOptions","signature":"func NewSerializerWithOptions(meta MetaFactory, creater runtime.ObjectCreater, typer runtime.ObjectTyper, options SerializerOptions) *Serializer","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go","code":"// NewSerializerWithOptions creates a JSON/YAML serializer that handles encoding versioned objects into the proper JSON/YAML\n// form. If typer is not nil, the object has the group, version, and kind fields set. Options are copied into the Serializer\n// and are immutable.\nfunc NewSerializerWithOptions(meta MetaFactory, creater runtime.ObjectCreater, typer runtime.ObjectTyper, options SerializerOptions) *Serializer {\n\treturn \u0026Serializer{\n\t\tmeta: meta,\n\t\tcreater: creater,\n\t\ttyper: typer,\n\t\toptions: options,\n\t\tidentifier: identifier(options),\n\t}\n}","line":{"from":50,"to":61}} {"id":100015528,"name":"identifier","signature":"func identifier(options SerializerOptions) runtime.Identifier","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go","code":"// identifier computes Identifier of Encoder based on the given options.\nfunc identifier(options SerializerOptions) runtime.Identifier {\n\tresult := map[string]string{\n\t\t\"name\": \"json\",\n\t\t\"yaml\": strconv.FormatBool(options.Yaml),\n\t\t\"pretty\": strconv.FormatBool(options.Pretty),\n\t\t\"strict\": strconv.FormatBool(options.Strict),\n\t}\n\tidentifier, err := json.Marshal(result)\n\tif err != nil {\n\t\tklog.Fatalf(\"Failed marshaling identifier for json Serializer: %v\", err)\n\t}\n\treturn runtime.Identifier(identifier)\n}","line":{"from":63,"to":76}} {"id":100015529,"name":"gvkWithDefaults","signature":"func gvkWithDefaults(actual, defaultGVK schema.GroupVersionKind) schema.GroupVersionKind","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go","code":"// gvkWithDefaults returns group kind and version defaulting from provided default\nfunc gvkWithDefaults(actual, defaultGVK schema.GroupVersionKind) schema.GroupVersionKind {\n\tif len(actual.Kind) == 0 {\n\t\tactual.Kind = defaultGVK.Kind\n\t}\n\tif len(actual.Version) == 0 \u0026\u0026 len(actual.Group) == 0 {\n\t\tactual.Group = defaultGVK.Group\n\t\tactual.Version = defaultGVK.Version\n\t}\n\tif len(actual.Version) == 0 \u0026\u0026 actual.Group == defaultGVK.Group {\n\t\tactual.Version = defaultGVK.Version\n\t}\n\treturn actual\n}","line":{"from":112,"to":125}} {"id":100015530,"name":"Decode","signature":"func (s *Serializer) Decode(originalData []byte, gvk *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go","code":"// Decode attempts to convert the provided data into YAML or JSON, extract the stored schema kind, apply the provided default gvk, and then\n// load that data into an object matching the desired schema kind or the provided into.\n// If into is *runtime.Unknown, the raw data will be extracted and no decoding will be performed.\n// If into is not registered with the typer, then the object will be straight decoded using normal JSON/YAML unmarshalling.\n// If into is provided and the original data is not fully qualified with kind/version/group, the type of the into will be used to alter the returned gvk.\n// If into is nil or data's gvk different from into's gvk, it will generate a new Object with ObjectCreater.New(gvk)\n// On success or most errors, the method will return the calculated schema kind.\n// The gvk calculate priority will be originalData \u003e default gvk \u003e into\nfunc (s *Serializer) Decode(originalData []byte, gvk *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {\n\tdata := originalData\n\tif s.options.Yaml {\n\t\taltered, err := yaml.YAMLToJSON(data)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tdata = altered\n\t}\n\n\tactual, err := s.meta.Interpret(data)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif gvk != nil {\n\t\t*actual = gvkWithDefaults(*actual, *gvk)\n\t}\n\n\tif unk, ok := into.(*runtime.Unknown); ok \u0026\u0026 unk != nil {\n\t\tunk.Raw = originalData\n\t\tunk.ContentType = runtime.ContentTypeJSON\n\t\tunk.GetObjectKind().SetGroupVersionKind(*actual)\n\t\treturn unk, actual, nil\n\t}\n\n\tif into != nil {\n\t\t_, isUnstructured := into.(runtime.Unstructured)\n\t\ttypes, _, err := s.typer.ObjectKinds(into)\n\t\tswitch {\n\t\tcase runtime.IsNotRegisteredError(err), isUnstructured:\n\t\t\tstrictErrs, err := s.unmarshal(into, data, originalData)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, actual, err\n\t\t\t}\n\n\t\t\t// when decoding directly into a provided unstructured object,\n\t\t\t// extract the actual gvk decoded from the provided data,\n\t\t\t// and ensure it is non-empty.\n\t\t\tif isUnstructured {\n\t\t\t\t*actual = into.GetObjectKind().GroupVersionKind()\n\t\t\t\tif len(actual.Kind) == 0 {\n\t\t\t\t\treturn nil, actual, runtime.NewMissingKindErr(string(originalData))\n\t\t\t\t}\n\t\t\t\t// TODO(109023): require apiVersion here as well once unstructuredJSONScheme#Decode does\n\t\t\t}\n\n\t\t\tif len(strictErrs) \u003e 0 {\n\t\t\t\treturn into, actual, runtime.NewStrictDecodingError(strictErrs)\n\t\t\t}\n\t\t\treturn into, actual, nil\n\t\tcase err != nil:\n\t\t\treturn nil, actual, err\n\t\tdefault:\n\t\t\t*actual = gvkWithDefaults(*actual, types[0])\n\t\t}\n\t}\n\n\tif len(actual.Kind) == 0 {\n\t\treturn nil, actual, runtime.NewMissingKindErr(string(originalData))\n\t}\n\tif len(actual.Version) == 0 {\n\t\treturn nil, actual, runtime.NewMissingVersionErr(string(originalData))\n\t}\n\n\t// use the target if necessary\n\tobj, err := runtime.UseOrCreateObject(s.typer, s.creater, *actual, into)\n\tif err != nil {\n\t\treturn nil, actual, err\n\t}\n\n\tstrictErrs, err := s.unmarshal(obj, data, originalData)\n\tif err != nil {\n\t\treturn nil, actual, err\n\t} else if len(strictErrs) \u003e 0 {\n\t\treturn obj, actual, runtime.NewStrictDecodingError(strictErrs)\n\t}\n\treturn obj, actual, nil\n}","line":{"from":127,"to":213}} {"id":100015531,"name":"Encode","signature":"func (s *Serializer) Encode(obj runtime.Object, w io.Writer) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go","code":"// Encode serializes the provided object to the given writer.\nfunc (s *Serializer) Encode(obj runtime.Object, w io.Writer) error {\n\tif co, ok := obj.(runtime.CacheableObject); ok {\n\t\treturn co.CacheEncode(s.Identifier(), s.doEncode, w)\n\t}\n\treturn s.doEncode(obj, w)\n}","line":{"from":215,"to":221}} {"id":100015532,"name":"doEncode","signature":"func (s *Serializer) doEncode(obj runtime.Object, w io.Writer) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go","code":"func (s *Serializer) doEncode(obj runtime.Object, w io.Writer) error {\n\tif s.options.Yaml {\n\t\tjson, err := json.Marshal(obj)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdata, err := yaml.JSONToYAML(json)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = w.Write(data)\n\t\treturn err\n\t}\n\n\tif s.options.Pretty {\n\t\tdata, err := json.MarshalIndent(obj, \"\", \" \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = w.Write(data)\n\t\treturn err\n\t}\n\tencoder := json.NewEncoder(w)\n\treturn encoder.Encode(obj)\n}","line":{"from":223,"to":247}} {"id":100015533,"name":"IsStrict","signature":"func (s *Serializer) IsStrict() bool","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go","code":"// IsStrict indicates whether the serializer\n// uses strict decoding or not\nfunc (s *Serializer) IsStrict() bool {\n\treturn s.options.Strict\n}","line":{"from":249,"to":253}} {"id":100015534,"name":"unmarshal","signature":"func (s *Serializer) unmarshal(into runtime.Object, data, originalData []byte) (strictErrs []error, err error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go","code":"func (s *Serializer) unmarshal(into runtime.Object, data, originalData []byte) (strictErrs []error, err error) {\n\t// If the deserializer is non-strict, return here.\n\tif !s.options.Strict {\n\t\tif err := kjson.UnmarshalCaseSensitivePreserveInts(data, into); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, nil\n\t}\n\n\tif s.options.Yaml {\n\t\t// In strict mode pass the original data through the YAMLToJSONStrict converter.\n\t\t// This is done to catch duplicate fields in YAML that would have been dropped in the original YAMLToJSON conversion.\n\t\t// TODO: rework YAMLToJSONStrict to return warnings about duplicate fields without terminating so we don't have to do this twice.\n\t\t_, err := yaml.YAMLToJSONStrict(originalData)\n\t\tif err != nil {\n\t\t\tstrictErrs = append(strictErrs, err)\n\t\t}\n\t}\n\n\tvar strictJSONErrs []error\n\tif u, isUnstructured := into.(runtime.Unstructured); isUnstructured {\n\t\t// Unstructured is a custom unmarshaler that gets delegated\n\t\t// to, so in order to detect strict JSON errors we need\n\t\t// to unmarshal directly into the object.\n\t\tm := map[string]interface{}{}\n\t\tstrictJSONErrs, err = kjson.UnmarshalStrict(data, \u0026m)\n\t\tu.SetUnstructuredContent(m)\n\t} else {\n\t\tstrictJSONErrs, err = kjson.UnmarshalStrict(data, into)\n\t}\n\tif err != nil {\n\t\t// fatal decoding error, not due to strictness\n\t\treturn nil, err\n\t}\n\tstrictErrs = append(strictErrs, strictJSONErrs...)\n\treturn strictErrs, nil\n}","line":{"from":255,"to":291}} {"id":100015535,"name":"Identifier","signature":"func (s *Serializer) Identifier() runtime.Identifier","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go","code":"// Identifier implements runtime.Encoder interface.\nfunc (s *Serializer) Identifier() runtime.Identifier {\n\treturn s.identifier\n}","line":{"from":293,"to":296}} {"id":100015536,"name":"RecognizesData","signature":"func (s *Serializer) RecognizesData(data []byte) (ok, unknown bool, err error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go","code":"// RecognizesData implements the RecognizingDecoder interface.\nfunc (s *Serializer) RecognizesData(data []byte) (ok, unknown bool, err error) {\n\tif s.options.Yaml {\n\t\t// we could potentially look for '---'\n\t\treturn false, true, nil\n\t}\n\treturn utilyaml.IsJSONBuffer(data), false, nil\n}","line":{"from":298,"to":305}} {"id":100015537,"name":"NewFrameWriter","signature":"func (jsonFramer) NewFrameWriter(w io.Writer) io.Writer","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go","code":"// NewFrameWriter implements stream framing for this serializer\nfunc (jsonFramer) NewFrameWriter(w io.Writer) io.Writer {\n\t// we can write JSON objects directly to the writer, because they are self-framing\n\treturn w\n}","line":{"from":312,"to":316}} {"id":100015538,"name":"NewFrameReader","signature":"func (jsonFramer) NewFrameReader(r io.ReadCloser) io.ReadCloser","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go","code":"// NewFrameReader implements stream framing for this serializer\nfunc (jsonFramer) NewFrameReader(r io.ReadCloser) io.ReadCloser {\n\t// we need to extract the JSON chunks of data to pass to Decode()\n\treturn framer.NewJSONFramedReader(r)\n}","line":{"from":318,"to":322}} {"id":100015539,"name":"NewFrameWriter","signature":"func (yamlFramer) NewFrameWriter(w io.Writer) io.Writer","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go","code":"// NewFrameWriter implements stream framing for this serializer\nfunc (yamlFramer) NewFrameWriter(w io.Writer) io.Writer {\n\treturn yamlFrameWriter{w}\n}","line":{"from":329,"to":332}} {"id":100015540,"name":"NewFrameReader","signature":"func (yamlFramer) NewFrameReader(r io.ReadCloser) io.ReadCloser","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go","code":"// NewFrameReader implements stream framing for this serializer\nfunc (yamlFramer) NewFrameReader(r io.ReadCloser) io.ReadCloser {\n\t// extract the YAML document chunks directly\n\treturn utilyaml.NewDocumentDecoder(r)\n}","line":{"from":334,"to":338}} {"id":100015541,"name":"Write","signature":"func (w yamlFrameWriter) Write(data []byte) (n int, err error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/json/json.go","code":"// Write separates each document with the YAML document separator (`---` followed by line\n// break). Writers must write well formed YAML documents (include a final line break).\nfunc (w yamlFrameWriter) Write(data []byte) (n int, err error) {\n\tif _, err := w.w.Write([]byte(\"---\\n\")); err != nil {\n\t\treturn 0, err\n\t}\n\treturn w.w.Write(data)\n}","line":{"from":344,"to":351}} {"id":100015542,"name":"Interpret","signature":"func (SimpleMetaFactory) Interpret(data []byte) (*schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/json/meta.go","code":"// Interpret will return the APIVersion and Kind of the JSON wire-format\n// encoding of an object, or an error.\nfunc (SimpleMetaFactory) Interpret(data []byte) (*schema.GroupVersionKind, error) {\n\tfindKind := struct {\n\t\t// +optional\n\t\tAPIVersion string `json:\"apiVersion,omitempty\"`\n\t\t// +optional\n\t\tKind string `json:\"kind,omitempty\"`\n\t}{}\n\tif err := json.Unmarshal(data, \u0026findKind); err != nil {\n\t\treturn nil, fmt.Errorf(\"couldn't get version/kind; json parse error: %v\", err)\n\t}\n\tgv, err := schema.ParseGroupVersion(findKind.APIVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026schema.GroupVersionKind{Group: gv.Group, Version: gv.Version, Kind: findKind.Kind}, nil\n}","line":{"from":46,"to":63}} {"id":100015543,"name":"NegotiatedSerializerWrapper","signature":"func NegotiatedSerializerWrapper(info runtime.SerializerInfo) runtime.NegotiatedSerializer","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/negotiated_codec.go","code":"func NegotiatedSerializerWrapper(info runtime.SerializerInfo) runtime.NegotiatedSerializer {\n\treturn \u0026negotiatedSerializerWrapper{info}\n}","line":{"from":29,"to":31}} {"id":100015544,"name":"SupportedMediaTypes","signature":"func (n *negotiatedSerializerWrapper) SupportedMediaTypes() []runtime.SerializerInfo","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/negotiated_codec.go","code":"func (n *negotiatedSerializerWrapper) SupportedMediaTypes() []runtime.SerializerInfo {\n\treturn []runtime.SerializerInfo{n.info}\n}","line":{"from":33,"to":35}} {"id":100015545,"name":"EncoderForVersion","signature":"func (n *negotiatedSerializerWrapper) EncoderForVersion(e runtime.Encoder, _ runtime.GroupVersioner) runtime.Encoder","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/negotiated_codec.go","code":"func (n *negotiatedSerializerWrapper) EncoderForVersion(e runtime.Encoder, _ runtime.GroupVersioner) runtime.Encoder {\n\treturn e\n}","line":{"from":37,"to":39}} {"id":100015546,"name":"DecoderToVersion","signature":"func (n *negotiatedSerializerWrapper) DecoderToVersion(d runtime.Decoder, _gv runtime.GroupVersioner) runtime.Decoder","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/negotiated_codec.go","code":"func (n *negotiatedSerializerWrapper) DecoderToVersion(d runtime.Decoder, _gv runtime.GroupVersioner) runtime.Decoder {\n\treturn d\n}","line":{"from":41,"to":43}} {"id":100015547,"name":"Error","signature":"func (e errNotMarshalable) Error() string","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go","code":"func (e errNotMarshalable) Error() string {\n\treturn fmt.Sprintf(\"object %v does not implement the protobuf marshalling interface and cannot be encoded to a protobuf message\", e.t)\n}","line":{"from":52,"to":54}} {"id":100015548,"name":"Status","signature":"func (e errNotMarshalable) Status() metav1.Status","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go","code":"func (e errNotMarshalable) Status() metav1.Status {\n\treturn metav1.Status{\n\t\tStatus: metav1.StatusFailure,\n\t\tCode: http.StatusNotAcceptable,\n\t\tReason: metav1.StatusReason(\"NotAcceptable\"),\n\t\tMessage: e.Error(),\n\t}\n}","line":{"from":56,"to":63}} {"id":100015549,"name":"IsNotMarshalable","signature":"func IsNotMarshalable(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go","code":"// IsNotMarshalable checks the type of error, returns a boolean true if error is not nil and not marshalable false otherwise\nfunc IsNotMarshalable(err error) bool {\n\t_, ok := err.(errNotMarshalable)\n\treturn err != nil \u0026\u0026 ok\n}","line":{"from":65,"to":69}} {"id":100015550,"name":"NewSerializer","signature":"func NewSerializer(creater runtime.ObjectCreater, typer runtime.ObjectTyper) *Serializer","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go","code":"// NewSerializer creates a Protobuf serializer that handles encoding versioned objects into the proper wire form. If a typer\n// is passed, the encoded object will have group, version, and kind fields set. If typer is nil, the objects will be written\n// as-is (any type info passed with the object will be used).\nfunc NewSerializer(creater runtime.ObjectCreater, typer runtime.ObjectTyper) *Serializer {\n\treturn \u0026Serializer{\n\t\tprefix: protoEncodingPrefix,\n\t\tcreater: creater,\n\t\ttyper: typer,\n\t}\n}","line":{"from":71,"to":80}} {"id":100015551,"name":"Decode","signature":"func (s *Serializer) Decode(originalData []byte, gvk *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go","code":"// Decode attempts to convert the provided data into a protobuf message, extract the stored schema kind, apply the provided default\n// gvk, and then load that data into an object matching the desired schema kind or the provided into. If into is *runtime.Unknown,\n// the raw data will be extracted and no decoding will be performed. If into is not registered with the typer, then the object will\n// be straight decoded using normal protobuf unmarshalling (the MarshalTo interface). If into is provided and the original data is\n// not fully qualified with kind/version/group, the type of the into will be used to alter the returned gvk. On success or most\n// errors, the method will return the calculated schema kind.\nfunc (s *Serializer) Decode(originalData []byte, gvk *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {\n\tprefixLen := len(s.prefix)\n\tswitch {\n\tcase len(originalData) == 0:\n\t\t// TODO: treat like decoding {} from JSON with defaulting\n\t\treturn nil, nil, fmt.Errorf(\"empty data\")\n\tcase len(originalData) \u003c prefixLen || !bytes.Equal(s.prefix, originalData[:prefixLen]):\n\t\treturn nil, nil, fmt.Errorf(\"provided data does not appear to be a protobuf message, expected prefix %v\", s.prefix)\n\tcase len(originalData) == prefixLen:\n\t\t// TODO: treat like decoding {} from JSON with defaulting\n\t\treturn nil, nil, fmt.Errorf(\"empty body\")\n\t}\n\n\tdata := originalData[prefixLen:]\n\tunk := runtime.Unknown{}\n\tif err := unk.Unmarshal(data); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tactual := unk.GroupVersionKind()\n\tcopyKindDefaults(\u0026actual, gvk)\n\n\tif intoUnknown, ok := into.(*runtime.Unknown); ok \u0026\u0026 intoUnknown != nil {\n\t\t*intoUnknown = unk\n\t\tif ok, _, _ := s.RecognizesData(unk.Raw); ok {\n\t\t\tintoUnknown.ContentType = runtime.ContentTypeProtobuf\n\t\t}\n\t\treturn intoUnknown, \u0026actual, nil\n\t}\n\n\tif into != nil {\n\t\ttypes, _, err := s.typer.ObjectKinds(into)\n\t\tswitch {\n\t\tcase runtime.IsNotRegisteredError(err):\n\t\t\tpb, ok := into.(proto.Message)\n\t\t\tif !ok {\n\t\t\t\treturn nil, \u0026actual, errNotMarshalable{reflect.TypeOf(into)}\n\t\t\t}\n\t\t\tif err := proto.Unmarshal(unk.Raw, pb); err != nil {\n\t\t\t\treturn nil, \u0026actual, err\n\t\t\t}\n\t\t\treturn into, \u0026actual, nil\n\t\tcase err != nil:\n\t\t\treturn nil, \u0026actual, err\n\t\tdefault:\n\t\t\tcopyKindDefaults(\u0026actual, \u0026types[0])\n\t\t\t// if the result of defaulting did not set a version or group, ensure that at least group is set\n\t\t\t// (copyKindDefaults will not assign Group if version is already set). This guarantees that the group\n\t\t\t// of into is set if there is no better information from the caller or object.\n\t\t\tif len(actual.Version) == 0 \u0026\u0026 len(actual.Group) == 0 {\n\t\t\t\tactual.Group = types[0].Group\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(actual.Kind) == 0 {\n\t\treturn nil, \u0026actual, runtime.NewMissingKindErr(fmt.Sprintf(\"%#v\", unk.TypeMeta))\n\t}\n\tif len(actual.Version) == 0 {\n\t\treturn nil, \u0026actual, runtime.NewMissingVersionErr(fmt.Sprintf(\"%#v\", unk.TypeMeta))\n\t}\n\n\treturn unmarshalToObject(s.typer, s.creater, \u0026actual, into, unk.Raw)\n}","line":{"from":95,"to":164}} {"id":100015552,"name":"EncodeWithAllocator","signature":"func (s *Serializer) EncodeWithAllocator(obj runtime.Object, w io.Writer, memAlloc runtime.MemoryAllocator) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go","code":"// EncodeWithAllocator writes an object to the provided writer.\n// In addition, it allows for providing a memory allocator for efficient memory usage during object serialization.\nfunc (s *Serializer) EncodeWithAllocator(obj runtime.Object, w io.Writer, memAlloc runtime.MemoryAllocator) error {\n\treturn s.encode(obj, w, memAlloc)\n}","line":{"from":166,"to":170}} {"id":100015553,"name":"Encode","signature":"func (s *Serializer) Encode(obj runtime.Object, w io.Writer) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go","code":"// Encode serializes the provided object to the given writer.\nfunc (s *Serializer) Encode(obj runtime.Object, w io.Writer) error {\n\treturn s.encode(obj, w, \u0026runtime.SimpleAllocator{})\n}","line":{"from":172,"to":175}} {"id":100015554,"name":"encode","signature":"func (s *Serializer) encode(obj runtime.Object, w io.Writer, memAlloc runtime.MemoryAllocator) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go","code":"func (s *Serializer) encode(obj runtime.Object, w io.Writer, memAlloc runtime.MemoryAllocator) error {\n\tif co, ok := obj.(runtime.CacheableObject); ok {\n\t\treturn co.CacheEncode(s.Identifier(), func(obj runtime.Object, w io.Writer) error { return s.doEncode(obj, w, memAlloc) }, w)\n\t}\n\treturn s.doEncode(obj, w, memAlloc)\n}","line":{"from":177,"to":182}} {"id":100015555,"name":"doEncode","signature":"func (s *Serializer) doEncode(obj runtime.Object, w io.Writer, memAlloc runtime.MemoryAllocator) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go","code":"func (s *Serializer) doEncode(obj runtime.Object, w io.Writer, memAlloc runtime.MemoryAllocator) error {\n\tif memAlloc == nil {\n\t\tklog.Error(\"a mandatory memory allocator wasn't provided, this might have a negative impact on performance, check invocations of EncodeWithAllocator method, falling back on runtime.SimpleAllocator\")\n\t\tmemAlloc = \u0026runtime.SimpleAllocator{}\n\t}\n\tprefixSize := uint64(len(s.prefix))\n\n\tvar unk runtime.Unknown\n\tswitch t := obj.(type) {\n\tcase *runtime.Unknown:\n\t\testimatedSize := prefixSize + uint64(t.Size())\n\t\tdata := memAlloc.Allocate(estimatedSize)\n\t\ti, err := t.MarshalTo(data[prefixSize:])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcopy(data, s.prefix)\n\t\t_, err = w.Write(data[:prefixSize+uint64(i)])\n\t\treturn err\n\tdefault:\n\t\tkind := obj.GetObjectKind().GroupVersionKind()\n\t\tunk = runtime.Unknown{\n\t\t\tTypeMeta: runtime.TypeMeta{\n\t\t\t\tKind: kind.Kind,\n\t\t\t\tAPIVersion: kind.GroupVersion().String(),\n\t\t\t},\n\t\t}\n\t}\n\n\tswitch t := obj.(type) {\n\tcase bufferedMarshaller:\n\t\t// this path performs a single allocation during write only when the Allocator wasn't provided\n\t\t// it also requires the caller to implement the more efficient Size and MarshalToSizedBuffer methods\n\t\tencodedSize := uint64(t.Size())\n\t\testimatedSize := prefixSize + estimateUnknownSize(\u0026unk, encodedSize)\n\t\tdata := memAlloc.Allocate(estimatedSize)\n\n\t\ti, err := unk.NestedMarshalTo(data[prefixSize:], t, encodedSize)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcopy(data, s.prefix)\n\n\t\t_, err = w.Write(data[:prefixSize+uint64(i)])\n\t\treturn err\n\n\tcase proto.Marshaler:\n\t\t// this path performs extra allocations\n\t\tdata, err := t.Marshal()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tunk.Raw = data\n\n\t\testimatedSize := prefixSize + uint64(unk.Size())\n\t\tdata = memAlloc.Allocate(estimatedSize)\n\n\t\ti, err := unk.MarshalTo(data[prefixSize:])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcopy(data, s.prefix)\n\n\t\t_, err = w.Write(data[:prefixSize+uint64(i)])\n\t\treturn err\n\n\tdefault:\n\t\t// TODO: marshal with a different content type and serializer (JSON for third party objects)\n\t\treturn errNotMarshalable{reflect.TypeOf(obj)}\n\t}\n}","line":{"from":184,"to":256}} {"id":100015556,"name":"Identifier","signature":"func (s *Serializer) Identifier() runtime.Identifier","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go","code":"// Identifier implements runtime.Encoder interface.\nfunc (s *Serializer) Identifier() runtime.Identifier {\n\treturn serializerIdentifier\n}","line":{"from":258,"to":261}} {"id":100015557,"name":"RecognizesData","signature":"func (s *Serializer) RecognizesData(data []byte) (bool, bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go","code":"// RecognizesData implements the RecognizingDecoder interface.\nfunc (s *Serializer) RecognizesData(data []byte) (bool, bool, error) {\n\treturn bytes.HasPrefix(data, s.prefix), false, nil\n}","line":{"from":263,"to":266}} {"id":100015558,"name":"copyKindDefaults","signature":"func copyKindDefaults(dst, src *schema.GroupVersionKind)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go","code":"// copyKindDefaults defaults dst to the value in src if dst does not have a value set.\nfunc copyKindDefaults(dst, src *schema.GroupVersionKind) {\n\tif src == nil {\n\t\treturn\n\t}\n\t// apply kind and version defaulting from provided default\n\tif len(dst.Kind) == 0 {\n\t\tdst.Kind = src.Kind\n\t}\n\tif len(dst.Version) == 0 \u0026\u0026 len(src.Version) \u003e 0 {\n\t\tdst.Group = src.Group\n\t\tdst.Version = src.Version\n\t}\n}","line":{"from":268,"to":281}} {"id":100015559,"name":"estimateUnknownSize","signature":"func estimateUnknownSize(unk *runtime.Unknown, byteSize uint64) uint64","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go","code":"// estimateUnknownSize returns the expected bytes consumed by a given runtime.Unknown\n// object with a nil RawJSON struct and the expected size of the provided buffer. The\n// returned size will not be correct if RawJSOn is set on unk.\nfunc estimateUnknownSize(unk *runtime.Unknown, byteSize uint64) uint64 {\n\tsize := uint64(unk.Size())\n\t// protobuf uses 1 byte for the tag, a varint for the length of the array (at most 8 bytes - uint64 - here),\n\t// and the size of the array.\n\tsize += 1 + 8 + byteSize\n\treturn size\n}","line":{"from":296,"to":305}} {"id":100015560,"name":"NewRawSerializer","signature":"func NewRawSerializer(creater runtime.ObjectCreater, typer runtime.ObjectTyper) *RawSerializer","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go","code":"// NewRawSerializer creates a Protobuf serializer that handles encoding versioned objects into the proper wire form. If typer\n// is not nil, the object has the group, version, and kind fields set. This serializer does not provide type information for the\n// encoded object, and thus is not self describing (callers must know what type is being described in order to decode).\n//\n// This encoding scheme is experimental, and is subject to change at any time.\nfunc NewRawSerializer(creater runtime.ObjectCreater, typer runtime.ObjectTyper) *RawSerializer {\n\treturn \u0026RawSerializer{\n\t\tcreater: creater,\n\t\ttyper: typer,\n\t}\n}","line":{"from":307,"to":317}} {"id":100015561,"name":"Decode","signature":"func (s *RawSerializer) Decode(originalData []byte, gvk *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go","code":"// Decode attempts to convert the provided data into a protobuf message, extract the stored schema kind, apply the provided default\n// gvk, and then load that data into an object matching the desired schema kind or the provided into. If into is *runtime.Unknown,\n// the raw data will be extracted and no decoding will be performed. If into is not registered with the typer, then the object will\n// be straight decoded using normal protobuf unmarshalling (the MarshalTo interface). If into is provided and the original data is\n// not fully qualified with kind/version/group, the type of the into will be used to alter the returned gvk. On success or most\n// errors, the method will return the calculated schema kind.\nfunc (s *RawSerializer) Decode(originalData []byte, gvk *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {\n\tif into == nil {\n\t\treturn nil, nil, fmt.Errorf(\"this serializer requires an object to decode into: %#v\", s)\n\t}\n\n\tif len(originalData) == 0 {\n\t\t// TODO: treat like decoding {} from JSON with defaulting\n\t\treturn nil, nil, fmt.Errorf(\"empty data\")\n\t}\n\tdata := originalData\n\n\tactual := \u0026schema.GroupVersionKind{}\n\tcopyKindDefaults(actual, gvk)\n\n\tif intoUnknown, ok := into.(*runtime.Unknown); ok \u0026\u0026 intoUnknown != nil {\n\t\tintoUnknown.Raw = data\n\t\tintoUnknown.ContentEncoding = \"\"\n\t\tintoUnknown.ContentType = runtime.ContentTypeProtobuf\n\t\tintoUnknown.SetGroupVersionKind(*actual)\n\t\treturn intoUnknown, actual, nil\n\t}\n\n\ttypes, _, err := s.typer.ObjectKinds(into)\n\tswitch {\n\tcase runtime.IsNotRegisteredError(err):\n\t\tpb, ok := into.(proto.Message)\n\t\tif !ok {\n\t\t\treturn nil, actual, errNotMarshalable{reflect.TypeOf(into)}\n\t\t}\n\t\tif err := proto.Unmarshal(data, pb); err != nil {\n\t\t\treturn nil, actual, err\n\t\t}\n\t\treturn into, actual, nil\n\tcase err != nil:\n\t\treturn nil, actual, err\n\tdefault:\n\t\tcopyKindDefaults(actual, \u0026types[0])\n\t\t// if the result of defaulting did not set a version or group, ensure that at least group is set\n\t\t// (copyKindDefaults will not assign Group if version is already set). This guarantees that the group\n\t\t// of into is set if there is no better information from the caller or object.\n\t\tif len(actual.Version) == 0 \u0026\u0026 len(actual.Group) == 0 {\n\t\t\tactual.Group = types[0].Group\n\t\t}\n\t}\n\n\tif len(actual.Kind) == 0 {\n\t\treturn nil, actual, runtime.NewMissingKindErr(\"\u003cprotobuf encoded body - must provide default type\u003e\")\n\t}\n\tif len(actual.Version) == 0 {\n\t\treturn nil, actual, runtime.NewMissingVersionErr(\"\u003cprotobuf encoded body - must provide default type\u003e\")\n\t}\n\n\treturn unmarshalToObject(s.typer, s.creater, actual, into, data)\n}","line":{"from":330,"to":389}} {"id":100015562,"name":"unmarshalToObject","signature":"func unmarshalToObject(typer runtime.ObjectTyper, creater runtime.ObjectCreater, actual *schema.GroupVersionKind, into runtime.Object, data []byte) (runtime.Object, *schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go","code":"// unmarshalToObject is the common code between decode in the raw and normal serializer.\nfunc unmarshalToObject(typer runtime.ObjectTyper, creater runtime.ObjectCreater, actual *schema.GroupVersionKind, into runtime.Object, data []byte) (runtime.Object, *schema.GroupVersionKind, error) {\n\t// use the target if necessary\n\tobj, err := runtime.UseOrCreateObject(typer, creater, *actual, into)\n\tif err != nil {\n\t\treturn nil, actual, err\n\t}\n\n\tpb, ok := obj.(proto.Message)\n\tif !ok {\n\t\treturn nil, actual, errNotMarshalable{reflect.TypeOf(obj)}\n\t}\n\tif err := proto.Unmarshal(data, pb); err != nil {\n\t\treturn nil, actual, err\n\t}\n\tif actual != nil {\n\t\tobj.GetObjectKind().SetGroupVersionKind(*actual)\n\t}\n\treturn obj, actual, nil\n}","line":{"from":391,"to":410}} {"id":100015563,"name":"Encode","signature":"func (s *RawSerializer) Encode(obj runtime.Object, w io.Writer) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go","code":"// Encode serializes the provided object to the given writer. Overrides is ignored.\nfunc (s *RawSerializer) Encode(obj runtime.Object, w io.Writer) error {\n\treturn s.encode(obj, w, \u0026runtime.SimpleAllocator{})\n}","line":{"from":412,"to":415}} {"id":100015564,"name":"EncodeWithAllocator","signature":"func (s *RawSerializer) EncodeWithAllocator(obj runtime.Object, w io.Writer, memAlloc runtime.MemoryAllocator) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go","code":"// EncodeWithAllocator writes an object to the provided writer.\n// In addition, it allows for providing a memory allocator for efficient memory usage during object serialization.\nfunc (s *RawSerializer) EncodeWithAllocator(obj runtime.Object, w io.Writer, memAlloc runtime.MemoryAllocator) error {\n\treturn s.encode(obj, w, memAlloc)\n}","line":{"from":417,"to":421}} {"id":100015565,"name":"encode","signature":"func (s *RawSerializer) encode(obj runtime.Object, w io.Writer, memAlloc runtime.MemoryAllocator) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go","code":"func (s *RawSerializer) encode(obj runtime.Object, w io.Writer, memAlloc runtime.MemoryAllocator) error {\n\tif co, ok := obj.(runtime.CacheableObject); ok {\n\t\treturn co.CacheEncode(s.Identifier(), func(obj runtime.Object, w io.Writer) error { return s.doEncode(obj, w, memAlloc) }, w)\n\t}\n\treturn s.doEncode(obj, w, memAlloc)\n}","line":{"from":423,"to":428}} {"id":100015566,"name":"doEncode","signature":"func (s *RawSerializer) doEncode(obj runtime.Object, w io.Writer, memAlloc runtime.MemoryAllocator) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go","code":"func (s *RawSerializer) doEncode(obj runtime.Object, w io.Writer, memAlloc runtime.MemoryAllocator) error {\n\tif memAlloc == nil {\n\t\tklog.Error(\"a mandatory memory allocator wasn't provided, this might have a negative impact on performance, check invocations of EncodeWithAllocator method, falling back on runtime.SimpleAllocator\")\n\t\tmemAlloc = \u0026runtime.SimpleAllocator{}\n\t}\n\tswitch t := obj.(type) {\n\tcase bufferedReverseMarshaller:\n\t\t// this path performs a single allocation during write only when the Allocator wasn't provided\n\t\t// it also requires the caller to implement the more efficient Size and MarshalToSizedBuffer methods\n\t\tencodedSize := uint64(t.Size())\n\t\tdata := memAlloc.Allocate(encodedSize)\n\n\t\tn, err := t.MarshalToSizedBuffer(data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = w.Write(data[:n])\n\t\treturn err\n\n\tcase bufferedMarshaller:\n\t\t// this path performs a single allocation during write only when the Allocator wasn't provided\n\t\t// it also requires the caller to implement the more efficient Size and MarshalTo methods\n\t\tencodedSize := uint64(t.Size())\n\t\tdata := memAlloc.Allocate(encodedSize)\n\n\t\tn, err := t.MarshalTo(data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = w.Write(data[:n])\n\t\treturn err\n\n\tcase proto.Marshaler:\n\t\t// this path performs extra allocations\n\t\tdata, err := t.Marshal()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = w.Write(data)\n\t\treturn err\n\n\tdefault:\n\t\treturn errNotMarshalable{reflect.TypeOf(obj)}\n\t}\n}","line":{"from":430,"to":474}} {"id":100015567,"name":"Identifier","signature":"func (s *RawSerializer) Identifier() runtime.Identifier","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go","code":"// Identifier implements runtime.Encoder interface.\nfunc (s *RawSerializer) Identifier() runtime.Identifier {\n\treturn rawSerializerIdentifier\n}","line":{"from":476,"to":479}} {"id":100015568,"name":"NewFrameWriter","signature":"func (lengthDelimitedFramer) NewFrameWriter(w io.Writer) io.Writer","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go","code":"// NewFrameWriter implements stream framing for this serializer\nfunc (lengthDelimitedFramer) NewFrameWriter(w io.Writer) io.Writer {\n\treturn framer.NewLengthDelimitedFrameWriter(w)\n}","line":{"from":487,"to":490}} {"id":100015569,"name":"NewFrameReader","signature":"func (lengthDelimitedFramer) NewFrameReader(r io.ReadCloser) io.ReadCloser","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/protobuf.go","code":"// NewFrameReader implements stream framing for this serializer\nfunc (lengthDelimitedFramer) NewFrameReader(r io.ReadCloser) io.ReadCloser {\n\treturn framer.NewLengthDelimitedFrameReader(r)\n}","line":{"from":492,"to":495}} {"id":100015570,"name":"NewDecoder","signature":"func NewDecoder(decoders ...runtime.Decoder) runtime.Decoder","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/recognizer/recognizer.go","code":"// NewDecoder creates a decoder that will attempt multiple decoders in an order defined\n// by:\n//\n// 1. The decoder implements RecognizingDecoder and identifies the data\n// 2. All other decoders, and any decoder that returned true for unknown.\n//\n// The order passed to the constructor is preserved within those priorities.\nfunc NewDecoder(decoders ...runtime.Decoder) runtime.Decoder {\n\treturn \u0026decoder{\n\t\tdecoders: decoders,\n\t}\n}","line":{"from":38,"to":49}} {"id":100015571,"name":"RecognizesData","signature":"func (d *decoder) RecognizesData(data []byte) (bool, bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/recognizer/recognizer.go","code":"func (d *decoder) RecognizesData(data []byte) (bool, bool, error) {\n\tvar (\n\t\tlastErr error\n\t\tanyUnknown bool\n\t)\n\tfor _, r := range d.decoders {\n\t\tswitch t := r.(type) {\n\t\tcase RecognizingDecoder:\n\t\t\tok, unknown, err := t.RecognizesData(data)\n\t\t\tif err != nil {\n\t\t\t\tlastErr = err\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tanyUnknown = anyUnknown || unknown\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn true, false, nil\n\t\t}\n\t}\n\treturn false, anyUnknown, lastErr\n}","line":{"from":57,"to":78}} {"id":100015572,"name":"Decode","signature":"func (d *decoder) Decode(data []byte, gvk *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/recognizer/recognizer.go","code":"func (d *decoder) Decode(data []byte, gvk *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {\n\tvar (\n\t\tlastErr error\n\t\tskipped []runtime.Decoder\n\t)\n\n\t// try recognizers, record any decoders we need to give a chance later\n\tfor _, r := range d.decoders {\n\t\tswitch t := r.(type) {\n\t\tcase RecognizingDecoder:\n\t\t\tok, unknown, err := t.RecognizesData(data)\n\t\t\tif err != nil {\n\t\t\t\tlastErr = err\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif unknown {\n\t\t\t\tskipped = append(skipped, t)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn r.Decode(data, gvk, into)\n\t\tdefault:\n\t\t\tskipped = append(skipped, t)\n\t\t}\n\t}\n\n\t// try recognizers that returned unknown or didn't recognize their data\n\tfor _, r := range skipped {\n\t\tout, actual, err := r.Decode(data, gvk, into)\n\t\tif err != nil {\n\t\t\t// if we got an object back from the decoder, and the\n\t\t\t// error was a strict decoding error (e.g. unknown or\n\t\t\t// duplicate fields), we still consider the recognizer\n\t\t\t// to have understood the object\n\t\t\tif out == nil || !runtime.IsStrictDecodingError(err) {\n\t\t\t\tlastErr = err\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\treturn out, actual, err\n\t}\n\n\tif lastErr == nil {\n\t\tlastErr = fmt.Errorf(\"no serialization format matched the provided data\")\n\t}\n\treturn nil, nil, lastErr\n}","line":{"from":80,"to":128}} {"id":100015573,"name":"NewDecoder","signature":"func NewDecoder(r io.ReadCloser, d runtime.Decoder) Decoder","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/streaming/streaming.go","code":"// NewDecoder creates a streaming decoder that reads object chunks from r and decodes them with d.\n// The reader is expected to return ErrShortRead if the provided buffer is not large enough to read\n// an entire object.\nfunc NewDecoder(r io.ReadCloser, d runtime.Decoder) Decoder {\n\treturn \u0026decoder{\n\t\treader: r,\n\t\tdecoder: d,\n\t\tbuf: make([]byte, 1024),\n\t\tmaxBytes: 16 * 1024 * 1024,\n\t}\n}","line":{"from":59,"to":69}} {"id":100015574,"name":"Decode","signature":"func (d *decoder) Decode(defaults *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/streaming/streaming.go","code":"// Decode reads the next object from the stream and decodes it.\nfunc (d *decoder) Decode(defaults *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {\n\tbase := 0\n\tfor {\n\t\tn, err := d.reader.Read(d.buf[base:])\n\t\tif err == io.ErrShortBuffer {\n\t\t\tif n == 0 {\n\t\t\t\treturn nil, nil, fmt.Errorf(\"got short buffer with n=0, base=%d, cap=%d\", base, cap(d.buf))\n\t\t\t}\n\t\t\tif d.resetRead {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// double the buffer size up to maxBytes\n\t\t\tif len(d.buf) \u003c d.maxBytes {\n\t\t\t\tbase += n\n\t\t\t\td.buf = append(d.buf, make([]byte, len(d.buf))...)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// must read the rest of the frame (until we stop getting ErrShortBuffer)\n\t\t\td.resetRead = true\n\t\t\treturn nil, nil, ErrObjectTooLarge\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tif d.resetRead {\n\t\t\t// now that we have drained the large read, continue\n\t\t\td.resetRead = false\n\t\t\tcontinue\n\t\t}\n\t\tbase += n\n\t\tbreak\n\t}\n\treturn d.decoder.Decode(d.buf[:base], defaults, into)\n}","line":{"from":73,"to":107}} {"id":100015575,"name":"Close","signature":"func (d *decoder) Close() error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/streaming/streaming.go","code":"func (d *decoder) Close() error {\n\treturn d.reader.Close()\n}","line":{"from":109,"to":111}} {"id":100015576,"name":"NewEncoder","signature":"func NewEncoder(w io.Writer, e runtime.Encoder) Encoder","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/streaming/streaming.go","code":"// NewEncoder returns a new streaming encoder.\nfunc NewEncoder(w io.Writer, e runtime.Encoder) Encoder {\n\treturn \u0026encoder{\n\t\twriter: w,\n\t\tencoder: e,\n\t\tbuf: \u0026bytes.Buffer{},\n\t}\n}","line":{"from":119,"to":126}} {"id":100015577,"name":"Encode","signature":"func (e *encoder) Encode(obj runtime.Object) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/streaming/streaming.go","code":"// Encode writes the provided object to the nested writer.\nfunc (e *encoder) Encode(obj runtime.Object) error {\n\tif err := e.encoder.Encode(obj, e.buf); err != nil {\n\t\treturn err\n\t}\n\t_, err := e.writer.Write(e.buf.Bytes())\n\te.buf.Reset()\n\treturn err\n}","line":{"from":128,"to":136}} {"id":100015578,"name":"NewEncoderWithAllocator","signature":"func NewEncoderWithAllocator(w io.Writer, e runtime.EncoderWithAllocator, a runtime.MemoryAllocator) Encoder","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/streaming/streaming.go","code":"// NewEncoderWithAllocator returns a new streaming encoder\nfunc NewEncoderWithAllocator(w io.Writer, e runtime.EncoderWithAllocator, a runtime.MemoryAllocator) Encoder {\n\treturn \u0026encoderWithAllocator{\n\t\twriter: w,\n\t\tencoder: e,\n\t\tmemAllocator: a,\n\t}\n}","line":{"from":144,"to":151}} {"id":100015579,"name":"Encode","signature":"func (e *encoderWithAllocator) Encode(obj runtime.Object) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/streaming/streaming.go","code":"// Encode writes the provided object to the nested writer\nfunc (e *encoderWithAllocator) Encode(obj runtime.Object) error {\n\treturn e.encoder.EncodeWithAllocator(obj, e.writer, e.memAllocator)\n}","line":{"from":153,"to":156}} {"id":100015580,"name":"NewDefaultingCodecForScheme","signature":"func NewDefaultingCodecForScheme(","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/versioning/versioning.go","code":"// NewDefaultingCodecForScheme is a convenience method for callers that are using a scheme.\nfunc NewDefaultingCodecForScheme(\n\t// TODO: I should be a scheme interface?\n\tscheme *runtime.Scheme,\n\tencoder runtime.Encoder,\n\tdecoder runtime.Decoder,\n\tencodeVersion runtime.GroupVersioner,\n\tdecodeVersion runtime.GroupVersioner,\n) runtime.Codec {\n\treturn NewCodec(encoder, decoder, runtime.UnsafeObjectConvertor(scheme), scheme, scheme, scheme, encodeVersion, decodeVersion, scheme.Name())\n}","line":{"from":31,"to":41}} {"id":100015581,"name":"NewCodec","signature":"func NewCodec(","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/versioning/versioning.go","code":"// NewCodec takes objects in their internal versions and converts them to external versions before\n// serializing them. It assumes the serializer provided to it only deals with external versions.\n// This class is also a serializer, but is generally used with a specific version.\nfunc NewCodec(\n\tencoder runtime.Encoder,\n\tdecoder runtime.Decoder,\n\tconvertor runtime.ObjectConvertor,\n\tcreater runtime.ObjectCreater,\n\ttyper runtime.ObjectTyper,\n\tdefaulter runtime.ObjectDefaulter,\n\tencodeVersion runtime.GroupVersioner,\n\tdecodeVersion runtime.GroupVersioner,\n\toriginalSchemeName string,\n) runtime.Codec {\n\tinternal := \u0026codec{\n\t\tencoder: encoder,\n\t\tdecoder: decoder,\n\t\tconvertor: convertor,\n\t\tcreater: creater,\n\t\ttyper: typer,\n\t\tdefaulter: defaulter,\n\n\t\tencodeVersion: encodeVersion,\n\t\tdecodeVersion: decodeVersion,\n\n\t\tidentifier: identifier(encodeVersion, encoder),\n\n\t\toriginalSchemeName: originalSchemeName,\n\t}\n\treturn internal\n}","line":{"from":43,"to":73}} {"id":100015582,"name":"identifier","signature":"func identifier(encodeGV runtime.GroupVersioner, encoder runtime.Encoder) runtime.Identifier","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/versioning/versioning.go","code":"// identifier computes Identifier of Encoder based on codec parameters.\nfunc identifier(encodeGV runtime.GroupVersioner, encoder runtime.Encoder) runtime.Identifier {\n\tresult := codecIdentifier{\n\t\tName: \"versioning\",\n\t}\n\n\tif encodeGV != nil {\n\t\tresult.EncodeGV = encodeGV.Identifier()\n\t}\n\tif encoder != nil {\n\t\tresult.Encoder = string(encoder.Identifier())\n\t}\n\tif id, ok := identifiersMap.Load(result); ok {\n\t\treturn id.(runtime.Identifier)\n\t}\n\tidentifier, err := json.Marshal(result)\n\tif err != nil {\n\t\tklog.Fatalf(\"Failed marshaling identifier for codec: %v\", err)\n\t}\n\tidentifiersMap.Store(result, runtime.Identifier(identifier))\n\treturn runtime.Identifier(identifier)\n}","line":{"from":102,"to":123}} {"id":100015583,"name":"Decode","signature":"func (c *codec) Decode(data []byte, defaultGVK *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/versioning/versioning.go","code":"// Decode attempts a decode of the object, then tries to convert it to the internal version. If into is provided and the decoding is\n// successful, the returned runtime.Object will be the value passed as into. Note that this may bypass conversion if you pass an\n// into that matches the serialized version.\nfunc (c *codec) Decode(data []byte, defaultGVK *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {\n\t// If the into object is unstructured and expresses an opinion about its group/version,\n\t// create a new instance of the type so we always exercise the conversion path (skips short-circuiting on `into == obj`)\n\tdecodeInto := into\n\tif into != nil {\n\t\tif _, ok := into.(runtime.Unstructured); ok \u0026\u0026 !into.GetObjectKind().GroupVersionKind().GroupVersion().Empty() {\n\t\t\tdecodeInto = reflect.New(reflect.TypeOf(into).Elem()).Interface().(runtime.Object)\n\t\t}\n\t}\n\n\tvar strictDecodingErrs []error\n\tobj, gvk, err := c.decoder.Decode(data, defaultGVK, decodeInto)\n\tif err != nil {\n\t\tif strictErr, ok := runtime.AsStrictDecodingError(err); obj != nil \u0026\u0026 ok {\n\t\t\t// save the strictDecodingError and let the caller decide what to do with it\n\t\t\tstrictDecodingErrs = append(strictDecodingErrs, strictErr.Errors()...)\n\t\t} else {\n\t\t\treturn nil, gvk, err\n\t\t}\n\t}\n\n\tif d, ok := obj.(runtime.NestedObjectDecoder); ok {\n\t\tif err := d.DecodeNestedObjects(runtime.WithoutVersionDecoder{Decoder: c.decoder}); err != nil {\n\t\t\tif strictErr, ok := runtime.AsStrictDecodingError(err); ok {\n\t\t\t\t// save the strictDecodingError let and the caller decide what to do with it\n\t\t\t\tstrictDecodingErrs = append(strictDecodingErrs, strictErr.Errors()...)\n\t\t\t} else {\n\t\t\t\treturn nil, gvk, err\n\n\t\t\t}\n\t\t}\n\t}\n\n\t// aggregate the strict decoding errors into one\n\tvar strictDecodingErr error\n\tif len(strictDecodingErrs) \u003e 0 {\n\t\tstrictDecodingErr = runtime.NewStrictDecodingError(strictDecodingErrs)\n\t}\n\t// if we specify a target, use generic conversion.\n\tif into != nil {\n\t\t// perform defaulting if requested\n\t\tif c.defaulter != nil {\n\t\t\tc.defaulter.Default(obj)\n\t\t}\n\n\t\t// Short-circuit conversion if the into object is same object\n\t\tif into == obj {\n\t\t\treturn into, gvk, strictDecodingErr\n\t\t}\n\n\t\tif err := c.convertor.Convert(obj, into, c.decodeVersion); err != nil {\n\t\t\treturn nil, gvk, err\n\t\t}\n\n\t\treturn into, gvk, strictDecodingErr\n\t}\n\n\t// perform defaulting if requested\n\tif c.defaulter != nil {\n\t\tc.defaulter.Default(obj)\n\t}\n\n\tout, err := c.convertor.ConvertToVersion(obj, c.decodeVersion)\n\tif err != nil {\n\t\treturn nil, gvk, err\n\t}\n\treturn out, gvk, strictDecodingErr\n}","line":{"from":125,"to":195}} {"id":100015584,"name":"EncodeWithAllocator","signature":"func (c *codec) EncodeWithAllocator(obj runtime.Object, w io.Writer, memAlloc runtime.MemoryAllocator) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/versioning/versioning.go","code":"// EncodeWithAllocator ensures the provided object is output in the appropriate group and version, invoking\n// conversion if necessary. Unversioned objects (according to the ObjectTyper) are output as is.\n// In addition, it allows for providing a memory allocator for efficient memory usage during object serialization.\nfunc (c *codec) EncodeWithAllocator(obj runtime.Object, w io.Writer, memAlloc runtime.MemoryAllocator) error {\n\treturn c.encode(obj, w, memAlloc)\n}","line":{"from":197,"to":202}} {"id":100015585,"name":"Encode","signature":"func (c *codec) Encode(obj runtime.Object, w io.Writer) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/versioning/versioning.go","code":"// Encode ensures the provided object is output in the appropriate group and version, invoking\n// conversion if necessary. Unversioned objects (according to the ObjectTyper) are output as is.\nfunc (c *codec) Encode(obj runtime.Object, w io.Writer) error {\n\treturn c.encode(obj, w, nil)\n}","line":{"from":204,"to":208}} {"id":100015586,"name":"encode","signature":"func (c *codec) encode(obj runtime.Object, w io.Writer, memAlloc runtime.MemoryAllocator) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/versioning/versioning.go","code":"func (c *codec) encode(obj runtime.Object, w io.Writer, memAlloc runtime.MemoryAllocator) error {\n\tif co, ok := obj.(runtime.CacheableObject); ok {\n\t\treturn co.CacheEncode(c.Identifier(), func(obj runtime.Object, w io.Writer) error { return c.doEncode(obj, w, memAlloc) }, w)\n\t}\n\treturn c.doEncode(obj, w, memAlloc)\n}","line":{"from":210,"to":215}} {"id":100015587,"name":"doEncode","signature":"func (c *codec) doEncode(obj runtime.Object, w io.Writer, memAlloc runtime.MemoryAllocator) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/versioning/versioning.go","code":"func (c *codec) doEncode(obj runtime.Object, w io.Writer, memAlloc runtime.MemoryAllocator) error {\n\tencodeFn := c.encoder.Encode\n\tif memAlloc != nil {\n\t\tif encoder, supportsAllocator := c.encoder.(runtime.EncoderWithAllocator); supportsAllocator {\n\t\t\tencodeFn = func(obj runtime.Object, w io.Writer) error {\n\t\t\t\treturn encoder.EncodeWithAllocator(obj, w, memAlloc)\n\t\t\t}\n\t\t} else {\n\t\t\tklog.V(6).Infof(\"a memory allocator was provided but the encoder %s doesn't implement the runtime.EncoderWithAllocator, using regular encoder.Encode method\", c.encoder.Identifier())\n\t\t}\n\t}\n\tswitch obj := obj.(type) {\n\tcase *runtime.Unknown:\n\t\treturn encodeFn(obj, w)\n\tcase runtime.Unstructured:\n\t\t// An unstructured list can contain objects of multiple group version kinds. don't short-circuit just\n\t\t// because the top-level type matches our desired destination type. actually send the object to the converter\n\t\t// to give it a chance to convert the list items if needed.\n\t\tif _, ok := obj.(*unstructured.UnstructuredList); !ok {\n\t\t\t// avoid conversion roundtrip if GVK is the right one already or is empty (yes, this is a hack, but the old behaviour we rely on in kubectl)\n\t\t\tobjGVK := obj.GetObjectKind().GroupVersionKind()\n\t\t\tif len(objGVK.Version) == 0 {\n\t\t\t\treturn encodeFn(obj, w)\n\t\t\t}\n\t\t\ttargetGVK, ok := c.encodeVersion.KindForGroupVersionKinds([]schema.GroupVersionKind{objGVK})\n\t\t\tif !ok {\n\t\t\t\treturn runtime.NewNotRegisteredGVKErrForTarget(c.originalSchemeName, objGVK, c.encodeVersion)\n\t\t\t}\n\t\t\tif targetGVK == objGVK {\n\t\t\t\treturn encodeFn(obj, w)\n\t\t\t}\n\t\t}\n\t}\n\n\tgvks, isUnversioned, err := c.typer.ObjectKinds(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tobjectKind := obj.GetObjectKind()\n\told := objectKind.GroupVersionKind()\n\t// restore the old GVK after encoding\n\tdefer objectKind.SetGroupVersionKind(old)\n\n\tif c.encodeVersion == nil || isUnversioned {\n\t\tif e, ok := obj.(runtime.NestedObjectEncoder); ok {\n\t\t\tif err := e.EncodeNestedObjects(runtime.WithVersionEncoder{Encoder: c.encoder, ObjectTyper: c.typer}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tobjectKind.SetGroupVersionKind(gvks[0])\n\t\treturn encodeFn(obj, w)\n\t}\n\n\t// Perform a conversion if necessary\n\tout, err := c.convertor.ConvertToVersion(obj, c.encodeVersion)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif e, ok := out.(runtime.NestedObjectEncoder); ok {\n\t\tif err := e.EncodeNestedObjects(runtime.WithVersionEncoder{Version: c.encodeVersion, Encoder: c.encoder, ObjectTyper: c.typer}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Conversion is responsible for setting the proper group, version, and kind onto the outgoing object\n\treturn encodeFn(out, w)\n}","line":{"from":217,"to":285}} {"id":100015588,"name":"Identifier","signature":"func (c *codec) Identifier() runtime.Identifier","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/versioning/versioning.go","code":"// Identifier implements runtime.Encoder interface.\nfunc (c *codec) Identifier() runtime.Identifier {\n\treturn c.identifier\n}","line":{"from":287,"to":290}} {"id":100015589,"name":"Interpret","signature":"func (SimpleMetaFactory) Interpret(data []byte) (*schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/yaml/meta.go","code":"// Interpret will return the APIVersion and Kind of the JSON wire-format\n// encoding of an object, or an error.\nfunc (SimpleMetaFactory) Interpret(data []byte) (*schema.GroupVersionKind, error) {\n\tgvk := runtime.TypeMeta{}\n\tif err := yaml.Unmarshal(data, \u0026gvk); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not interpret GroupVersionKind; unmarshal error: %v\", err)\n\t}\n\tgv, err := schema.ParseGroupVersion(gvk.APIVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026schema.GroupVersionKind{Group: gv.Group, Version: gv.Version, Kind: gvk.Kind}, nil\n}","line":{"from":38,"to":50}} {"id":100015590,"name":"NewDecodingSerializer","signature":"func NewDecodingSerializer(jsonSerializer runtime.Serializer) runtime.Serializer","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/yaml/yaml.go","code":"// NewDecodingSerializer adds YAML decoding support to a serializer that supports JSON.\nfunc NewDecodingSerializer(jsonSerializer runtime.Serializer) runtime.Serializer {\n\treturn \u0026yamlSerializer{jsonSerializer}\n}","line":{"from":34,"to":37}} {"id":100015591,"name":"Decode","signature":"func (c yamlSerializer) Decode(data []byte, gvk *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/serializer/yaml/yaml.go","code":"func (c yamlSerializer) Decode(data []byte, gvk *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {\n\tout, err := yaml.ToJSON(data)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdata = out\n\treturn c.Serializer.Decode(data, gvk, into)\n}","line":{"from":39,"to":46}} {"id":100015592,"name":"astFrom","signature":"func astFrom(filePath string) *doc.Package","file":"staging/src/k8s.io/apimachinery/pkg/runtime/swagger_doc_generator.go","code":"func astFrom(filePath string) *doc.Package {\n\tfset := token.NewFileSet()\n\tm := make(map[string]*ast.File)\n\n\tf, err := parser.ParseFile(fset, filePath, nil, parser.ParseComments)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn nil\n\t}\n\n\tm[filePath] = f\n\tapkg, _ := ast.NewPackage(fset, m, nil, nil)\n\n\treturn doc.New(apkg, \"\", 0)\n}","line":{"from":39,"to":53}} {"id":100015593,"name":"fmtRawDoc","signature":"func fmtRawDoc(rawDoc string) string","file":"staging/src/k8s.io/apimachinery/pkg/runtime/swagger_doc_generator.go","code":"func fmtRawDoc(rawDoc string) string {\n\tvar buffer bytes.Buffer\n\tdelPrevChar := func() {\n\t\tif buffer.Len() \u003e 0 {\n\t\t\tbuffer.Truncate(buffer.Len() - 1) // Delete the last \" \" or \"\\n\"\n\t\t}\n\t}\n\n\t// Ignore all lines after ---\n\trawDoc = strings.Split(rawDoc, \"---\")[0]\n\n\tfor _, line := range strings.Split(rawDoc, \"\\n\") {\n\t\tline = strings.TrimRight(line, \" \")\n\t\tleading := strings.TrimLeft(line, \" \")\n\t\tswitch {\n\t\tcase len(line) == 0: // Keep paragraphs\n\t\t\tdelPrevChar()\n\t\t\tbuffer.WriteString(\"\\n\\n\")\n\t\tcase strings.HasPrefix(leading, \"TODO\"): // Ignore one line TODOs\n\t\tcase strings.HasPrefix(leading, \"+\"): // Ignore instructions to the generators\n\t\tdefault:\n\t\t\tif strings.HasPrefix(line, \" \") || strings.HasPrefix(line, \"\\t\") {\n\t\t\t\tdelPrevChar()\n\t\t\t\tline = \"\\n\" + line + \"\\n\" // Replace it with newline. This is useful when we have a line with: \"Example:\\n\\tJSON-someting...\"\n\t\t\t} else {\n\t\t\t\tline += \" \"\n\t\t\t}\n\t\t\tbuffer.WriteString(line)\n\t\t}\n\t}\n\n\tpostDoc := strings.TrimRight(buffer.String(), \"\\n\")\n\tpostDoc = strings.Replace(postDoc, \"\\\\\\\"\", \"\\\"\", -1) // replace user's \\\" to \"\n\tpostDoc = strings.Replace(postDoc, \"\\\"\", \"\\\\\\\"\", -1) // Escape \"\n\tpostDoc = strings.Replace(postDoc, \"\\n\", \"\\\\n\", -1)\n\tpostDoc = strings.Replace(postDoc, \"\\t\", \"\\\\t\", -1)\n\n\treturn postDoc\n}","line":{"from":55,"to":93}} {"id":100015594,"name":"fieldName","signature":"func fieldName(field *ast.Field) string","file":"staging/src/k8s.io/apimachinery/pkg/runtime/swagger_doc_generator.go","code":"// fieldName returns the name of the field as it should appear in JSON format\n// \"-\" indicates that this field is not part of the JSON representation\nfunc fieldName(field *ast.Field) string {\n\tjsonTag := \"\"\n\tif field.Tag != nil {\n\t\tjsonTag = reflect.StructTag(field.Tag.Value[1 : len(field.Tag.Value)-1]).Get(\"json\") // Delete first and last quotation\n\t\tif strings.Contains(jsonTag, \"inline\") {\n\t\t\treturn \"-\"\n\t\t}\n\t}\n\n\tjsonTag = strings.Split(jsonTag, \",\")[0] // This can return \"-\"\n\tif jsonTag == \"\" {\n\t\tif field.Names != nil {\n\t\t\treturn field.Names[0].Name\n\t\t}\n\t\treturn field.Type.(*ast.Ident).Name\n\t}\n\treturn jsonTag\n}","line":{"from":95,"to":114}} {"id":100015595,"name":"newBuffer","signature":"func newBuffer() *buffer","file":"staging/src/k8s.io/apimachinery/pkg/runtime/swagger_doc_generator.go","code":"func newBuffer() *buffer {\n\treturn \u0026buffer{\n\t\tlines: make([]bufferedLine, 0),\n\t}\n}","line":{"from":126,"to":130}} {"id":100015596,"name":"addLine","signature":"func (b *buffer) addLine(line string, indent int)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/swagger_doc_generator.go","code":"func (b *buffer) addLine(line string, indent int) {\n\tb.lines = append(b.lines, bufferedLine{line, indent})\n}","line":{"from":132,"to":134}} {"id":100015597,"name":"flushLines","signature":"func (b *buffer) flushLines(w io.Writer) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/swagger_doc_generator.go","code":"func (b *buffer) flushLines(w io.Writer) error {\n\tfor _, line := range b.lines {\n\t\tindentation := strings.Repeat(\"\\t\", line.indentation)\n\t\tfullLine := fmt.Sprintf(\"%s%s\", indentation, line.line)\n\t\tif _, err := io.WriteString(w, fullLine); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":136,"to":145}} {"id":100015598,"name":"writeFuncHeader","signature":"func writeFuncHeader(b *buffer, structName string, indent int)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/swagger_doc_generator.go","code":"func writeFuncHeader(b *buffer, structName string, indent int) {\n\ts := fmt.Sprintf(\"var map_%s = map[string]string {\\n\", structName)\n\tb.addLine(s, indent)\n}","line":{"from":147,"to":150}} {"id":100015599,"name":"writeFuncFooter","signature":"func writeFuncFooter(b *buffer, structName string, indent int)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/swagger_doc_generator.go","code":"func writeFuncFooter(b *buffer, structName string, indent int) {\n\tb.addLine(\"}\\n\", indent) // Closes the map definition\n\n\ts := fmt.Sprintf(\"func (%s) SwaggerDoc() map[string]string {\\n\", structName)\n\tb.addLine(s, indent)\n\ts = fmt.Sprintf(\"return map_%s\\n\", structName)\n\tb.addLine(s, indent+1)\n\tb.addLine(\"}\\n\", indent) // Closes the function definition\n}","line":{"from":152,"to":160}} {"id":100015600,"name":"writeMapBody","signature":"func writeMapBody(b *buffer, kubeType []Pair, indent int)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/swagger_doc_generator.go","code":"func writeMapBody(b *buffer, kubeType []Pair, indent int) {\n\tformat := \"\\\"%s\\\": \\\"%s\\\",\\n\"\n\tfor _, pair := range kubeType {\n\t\ts := fmt.Sprintf(format, pair.Name, pair.Doc)\n\t\tb.addLine(s, indent+2)\n\t}\n}","line":{"from":162,"to":168}} {"id":100015601,"name":"ParseDocumentationFrom","signature":"func ParseDocumentationFrom(src string) []KubeTypes","file":"staging/src/k8s.io/apimachinery/pkg/runtime/swagger_doc_generator.go","code":"// ParseDocumentationFrom gets all types' documentation and returns them as an\n// array. Each type is again represented as an array (we have to use arrays as we\n// need to be sure for the order of the fields). This function returns fields and\n// struct definitions that have no documentation as {name, \"\"}.\nfunc ParseDocumentationFrom(src string) []KubeTypes {\n\tvar docForTypes []KubeTypes\n\n\tpkg := astFrom(src)\n\n\tfor _, kubType := range pkg.Types {\n\t\tif structType, ok := kubType.Decl.Specs[0].(*ast.TypeSpec).Type.(*ast.StructType); ok {\n\t\t\tvar ks KubeTypes\n\t\t\tks = append(ks, Pair{kubType.Name, fmtRawDoc(kubType.Doc)})\n\n\t\t\tfor _, field := range structType.Fields.List {\n\t\t\t\tif n := fieldName(field); n != \"-\" {\n\t\t\t\t\tfieldDoc := fmtRawDoc(field.Doc.Text())\n\t\t\t\t\tks = append(ks, Pair{n, fieldDoc})\n\t\t\t\t}\n\t\t\t}\n\t\t\tdocForTypes = append(docForTypes, ks)\n\t\t}\n\t}\n\n\treturn docForTypes\n}","line":{"from":170,"to":195}} {"id":100015602,"name":"WriteSwaggerDocFunc","signature":"func WriteSwaggerDocFunc(kubeTypes []KubeTypes, w io.Writer) error","file":"staging/src/k8s.io/apimachinery/pkg/runtime/swagger_doc_generator.go","code":"// WriteSwaggerDocFunc writes a declaration of a function as a string. This function is used in\n// Swagger as a documentation source for structs and theirs fields\nfunc WriteSwaggerDocFunc(kubeTypes []KubeTypes, w io.Writer) error {\n\tfor _, kubeType := range kubeTypes {\n\t\tstructName := kubeType[0].Name\n\t\tkubeType[0].Name = \"\"\n\n\t\t// Ignore empty documentation\n\t\tdocfulTypes := make(KubeTypes, 0, len(kubeType))\n\t\tfor _, pair := range kubeType {\n\t\t\tif pair.Doc != \"\" {\n\t\t\t\tdocfulTypes = append(docfulTypes, pair)\n\t\t\t}\n\t\t}\n\n\t\tif len(docfulTypes) == 0 {\n\t\t\tcontinue // If no fields and the struct have documentation, skip the function definition\n\t\t}\n\n\t\tindent := 0\n\t\tbuffer := newBuffer()\n\n\t\twriteFuncHeader(buffer, structName, indent)\n\t\twriteMapBody(buffer, docfulTypes, indent)\n\t\twriteFuncFooter(buffer, structName, indent)\n\t\tbuffer.addLine(\"\\n\", 0)\n\n\t\tif err := buffer.flushLines(w); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":197,"to":230}} {"id":100015603,"name":"VerifySwaggerDocsExist","signature":"func VerifySwaggerDocsExist(kubeTypes []KubeTypes, w io.Writer) (int, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/swagger_doc_generator.go","code":"// VerifySwaggerDocsExist writes in a io.Writer a list of structs and fields that\n// are missing of documentation.\nfunc VerifySwaggerDocsExist(kubeTypes []KubeTypes, w io.Writer) (int, error) {\n\tmissingDocs := 0\n\tbuffer := newBuffer()\n\n\tfor _, kubeType := range kubeTypes {\n\t\tstructName := kubeType[0].Name\n\t\tif kubeType[0].Doc == \"\" {\n\t\t\tformat := \"Missing documentation for the struct itself: %s\\n\"\n\t\t\ts := fmt.Sprintf(format, structName)\n\t\t\tbuffer.addLine(s, 0)\n\t\t\tmissingDocs++\n\t\t}\n\t\tkubeType = kubeType[1:] // Skip struct definition\n\n\t\tfor _, pair := range kubeType { // Iterate only the fields\n\t\t\tif pair.Doc == \"\" {\n\t\t\t\tformat := \"In struct: %s, field documentation is missing: %s\\n\"\n\t\t\t\ts := fmt.Sprintf(format, structName, pair.Name)\n\t\t\t\tbuffer.addLine(s, 0)\n\t\t\t\tmissingDocs++\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := buffer.flushLines(w); err != nil {\n\t\treturn -1, err\n\t}\n\treturn missingDocs, nil\n}","line":{"from":232,"to":262}} {"id":100015604,"name":"NestedMarshalTo","signature":"func (m *Unknown) NestedMarshalTo(data []byte, b ProtobufMarshaller, size uint64) (int, error)","file":"staging/src/k8s.io/apimachinery/pkg/runtime/types_proto.go","code":"// NestedMarshalTo allows a caller to avoid extra allocations during serialization of an Unknown\n// that will contain an object that implements ProtobufMarshaller or ProtobufReverseMarshaller.\nfunc (m *Unknown) NestedMarshalTo(data []byte, b ProtobufMarshaller, size uint64) (int, error) {\n\t// Calculate the full size of the message.\n\tmsgSize := m.Size()\n\tif b != nil {\n\t\tmsgSize += int(size) + sovGenerated(size) + 1\n\t}\n\n\t// Reverse marshal the fields of m.\n\ti := msgSize\n\ti -= len(m.ContentType)\n\tcopy(data[i:], m.ContentType)\n\ti = encodeVarintGenerated(data, i, uint64(len(m.ContentType)))\n\ti--\n\tdata[i] = 0x22\n\ti -= len(m.ContentEncoding)\n\tcopy(data[i:], m.ContentEncoding)\n\ti = encodeVarintGenerated(data, i, uint64(len(m.ContentEncoding)))\n\ti--\n\tdata[i] = 0x1a\n\tif b != nil {\n\t\tif r, ok := b.(ProtobufReverseMarshaller); ok {\n\t\t\tn1, err := r.MarshalToSizedBuffer(data[:i])\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t\ti -= int(size)\n\t\t\tif uint64(n1) != size {\n\t\t\t\t// programmer error: the Size() method for protobuf does not match the results of LashramOt, which means the proto\n\t\t\t\t// struct returned would be wrong.\n\t\t\t\treturn 0, fmt.Errorf(\"the Size() value of %T was %d, but NestedMarshalTo wrote %d bytes to data\", b, size, n1)\n\t\t\t}\n\t\t} else {\n\t\t\ti -= int(size)\n\t\t\tn1, err := b.MarshalTo(data[i:])\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t\tif uint64(n1) != size {\n\t\t\t\t// programmer error: the Size() method for protobuf does not match the results of MarshalTo, which means the proto\n\t\t\t\t// struct returned would be wrong.\n\t\t\t\treturn 0, fmt.Errorf(\"the Size() value of %T was %d, but NestedMarshalTo wrote %d bytes to data\", b, size, n1)\n\t\t\t}\n\t\t}\n\t\ti = encodeVarintGenerated(data, i, size)\n\t\ti--\n\t\tdata[i] = 0x12\n\t}\n\tn2, err := m.TypeMeta.MarshalToSizedBuffer(data[:i])\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ti -= n2\n\ti = encodeVarintGenerated(data, i, uint64(n2))\n\ti--\n\tdata[i] = 0xa\n\treturn msgSize - i, nil\n}","line":{"from":31,"to":89}} {"id":100015605,"name":"String","signature":"func (n NamespacedName) String() string","file":"staging/src/k8s.io/apimachinery/pkg/types/namespacedname.go","code":"// String returns the general purpose string representation\nfunc (n NamespacedName) String() string {\n\treturn n.Namespace + string(Separator) + n.Name\n}","line":{"from":36,"to":39}} {"id":100015606,"name":"MarshalLog","signature":"func (n NamespacedName) MarshalLog() interface{}","file":"staging/src/k8s.io/apimachinery/pkg/types/namespacedname.go","code":"// MarshalLog emits a struct containing required key/value pair\nfunc (n NamespacedName) MarshalLog() interface{} {\n\treturn struct {\n\t\tName string `json:\"name\"`\n\t\tNamespace string `json:\"namespace,omitempty\"`\n\t}{\n\t\tName: n.Name,\n\t\tNamespace: n.Namespace,\n\t}\n}","line":{"from":41,"to":50}} {"id":100015607,"name":"NewExpiring","signature":"func NewExpiring() *Expiring","file":"staging/src/k8s.io/apimachinery/pkg/util/cache/expiring.go","code":"// NewExpiring returns an initialized expiring cache.\nfunc NewExpiring() *Expiring {\n\treturn NewExpiringWithClock(clock.RealClock{})\n}","line":{"from":27,"to":30}} {"id":100015608,"name":"NewExpiringWithClock","signature":"func NewExpiringWithClock(clock clock.Clock) *Expiring","file":"staging/src/k8s.io/apimachinery/pkg/util/cache/expiring.go","code":"// NewExpiringWithClock is like NewExpiring but allows passing in a custom\n// clock for testing.\nfunc NewExpiringWithClock(clock clock.Clock) *Expiring {\n\treturn \u0026Expiring{\n\t\tclock: clock,\n\t\tcache: make(map[interface{}]entry),\n\t}\n}","line":{"from":32,"to":39}} {"id":100015609,"name":"Get","signature":"func (c *Expiring) Get(key interface{}) (val interface{}, ok bool)","file":"staging/src/k8s.io/apimachinery/pkg/util/cache/expiring.go","code":"// Get looks up an entry in the cache.\nfunc (c *Expiring) Get(key interface{}) (val interface{}, ok bool) {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\te, ok := c.cache[key]\n\tif !ok || !c.clock.Now().Before(e.expiry) {\n\t\treturn nil, false\n\t}\n\treturn e.val, true\n}","line":{"from":68,"to":77}} {"id":100015610,"name":"Set","signature":"func (c *Expiring) Set(key interface{}, val interface{}, ttl time.Duration)","file":"staging/src/k8s.io/apimachinery/pkg/util/cache/expiring.go","code":"// Set sets a key/value/expiry entry in the map, overwriting any previous entry\n// with the same key. The entry expires at the given expiry time, but its TTL\n// may be lengthened or shortened by additional calls to Set(). Garbage\n// collection of expired entries occurs during calls to Set(), however calls to\n// Get() will not return expired entries that have not yet been garbage\n// collected.\nfunc (c *Expiring) Set(key interface{}, val interface{}, ttl time.Duration) {\n\tnow := c.clock.Now()\n\texpiry := now.Add(ttl)\n\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tc.generation++\n\n\tc.cache[key] = entry{\n\t\tval: val,\n\t\texpiry: expiry,\n\t\tgeneration: c.generation,\n\t}\n\n\t// Run GC inline before pushing the new entry.\n\tc.gc(now)\n\n\theap.Push(\u0026c.heap, \u0026expiringHeapEntry{\n\t\tkey: key,\n\t\texpiry: expiry,\n\t\tgeneration: c.generation,\n\t})\n}","line":{"from":79,"to":108}} {"id":100015611,"name":"Delete","signature":"func (c *Expiring) Delete(key interface{})","file":"staging/src/k8s.io/apimachinery/pkg/util/cache/expiring.go","code":"// Delete deletes an entry in the map.\nfunc (c *Expiring) Delete(key interface{}) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tc.del(key, 0)\n}","line":{"from":110,"to":115}} {"id":100015612,"name":"del","signature":"func (c *Expiring) del(key interface{}, generation uint64)","file":"staging/src/k8s.io/apimachinery/pkg/util/cache/expiring.go","code":"// del deletes the entry for the given key. The generation argument is the\n// generation of the entry that should be deleted. If the generation has been\n// changed (e.g. if a set has occurred on an existing element but the old\n// cleanup still runs), this is a noop. If the generation argument is 0, the\n// entry's generation is ignored and the entry is deleted.\n//\n// del must be called under the write lock.\nfunc (c *Expiring) del(key interface{}, generation uint64) {\n\te, ok := c.cache[key]\n\tif !ok {\n\t\treturn\n\t}\n\tif generation != 0 \u0026\u0026 generation != e.generation {\n\t\treturn\n\t}\n\tdelete(c.cache, key)\n}","line":{"from":117,"to":133}} {"id":100015613,"name":"Len","signature":"func (c *Expiring) Len() int","file":"staging/src/k8s.io/apimachinery/pkg/util/cache/expiring.go","code":"// Len returns the number of items in the cache.\nfunc (c *Expiring) Len() int {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\treturn len(c.cache)\n}","line":{"from":135,"to":140}} {"id":100015614,"name":"gc","signature":"func (c *Expiring) gc(now time.Time)","file":"staging/src/k8s.io/apimachinery/pkg/util/cache/expiring.go","code":"func (c *Expiring) gc(now time.Time) {\n\tfor {\n\t\t// Return from gc if the heap is empty or the next element is not yet\n\t\t// expired.\n\t\t//\n\t\t// heap[0] is a peek at the next element in the heap, which is not obvious\n\t\t// from looking at the (*expiringHeap).Pop() implementation below.\n\t\t// heap.Pop() swaps the first entry with the last entry of the heap, then\n\t\t// calls (*expiringHeap).Pop() which returns the last element.\n\t\tif len(c.heap) == 0 || now.Before(c.heap[0].expiry) {\n\t\t\treturn\n\t\t}\n\t\tcleanup := heap.Pop(\u0026c.heap).(*expiringHeapEntry)\n\t\tc.del(cleanup.key, cleanup.generation)\n\t}\n}","line":{"from":142,"to":157}} {"id":100015615,"name":"Len","signature":"func (cq expiringHeap) Len() int","file":"staging/src/k8s.io/apimachinery/pkg/util/cache/expiring.go","code":"func (cq expiringHeap) Len() int {\n\treturn len(cq)\n}","line":{"from":172,"to":174}} {"id":100015616,"name":"Less","signature":"func (cq expiringHeap) Less(i, j int) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/cache/expiring.go","code":"func (cq expiringHeap) Less(i, j int) bool {\n\treturn cq[i].expiry.Before(cq[j].expiry)\n}","line":{"from":176,"to":178}} {"id":100015617,"name":"Swap","signature":"func (cq expiringHeap) Swap(i, j int)","file":"staging/src/k8s.io/apimachinery/pkg/util/cache/expiring.go","code":"func (cq expiringHeap) Swap(i, j int) {\n\tcq[i], cq[j] = cq[j], cq[i]\n}","line":{"from":180,"to":182}} {"id":100015618,"name":"Push","signature":"func (cq *expiringHeap) Push(c interface{})","file":"staging/src/k8s.io/apimachinery/pkg/util/cache/expiring.go","code":"func (cq *expiringHeap) Push(c interface{}) {\n\t*cq = append(*cq, c.(*expiringHeapEntry))\n}","line":{"from":184,"to":186}} {"id":100015619,"name":"Pop","signature":"func (cq *expiringHeap) Pop() interface{}","file":"staging/src/k8s.io/apimachinery/pkg/util/cache/expiring.go","code":"func (cq *expiringHeap) Pop() interface{} {\n\tc := (*cq)[cq.Len()-1]\n\t*cq = (*cq)[:cq.Len()-1]\n\treturn c\n}","line":{"from":188,"to":192}} {"id":100015620,"name":"Now","signature":"func (realClock) Now() time.Time { return time.Now() }","file":"staging/src/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.go","code":"func (realClock) Now() time.Time { return time.Now() }","line":{"from":33,"to":33}} {"id":100015621,"name":"NewLRUExpireCache","signature":"func NewLRUExpireCache(maxSize int) *LRUExpireCache","file":"staging/src/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.go","code":"// NewLRUExpireCache creates an expiring cache with the given size\nfunc NewLRUExpireCache(maxSize int) *LRUExpireCache {\n\treturn NewLRUExpireCacheWithClock(maxSize, realClock{})\n}","line":{"from":48,"to":51}} {"id":100015622,"name":"NewLRUExpireCacheWithClock","signature":"func NewLRUExpireCacheWithClock(maxSize int, clock Clock) *LRUExpireCache","file":"staging/src/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.go","code":"// NewLRUExpireCacheWithClock creates an expiring cache with the given size, using the specified clock to obtain the current time.\nfunc NewLRUExpireCacheWithClock(maxSize int, clock Clock) *LRUExpireCache {\n\tif maxSize \u003c= 0 {\n\t\tpanic(\"maxSize must be \u003e 0\")\n\t}\n\n\treturn \u0026LRUExpireCache{\n\t\tclock: clock,\n\t\tmaxSize: maxSize,\n\t\tentries: map[interface{}]*list.Element{},\n\t}\n}","line":{"from":53,"to":64}} {"id":100015623,"name":"Add","signature":"func (c *LRUExpireCache) Add(key interface{}, value interface{}, ttl time.Duration)","file":"staging/src/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.go","code":"// Add adds the value to the cache at key with the specified maximum duration.\nfunc (c *LRUExpireCache) Add(key interface{}, value interface{}, ttl time.Duration) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\t// Key already exists\n\toldElement, ok := c.entries[key]\n\tif ok {\n\t\tc.evictionList.MoveToFront(oldElement)\n\t\toldElement.Value.(*cacheEntry).value = value\n\t\toldElement.Value.(*cacheEntry).expireTime = c.clock.Now().Add(ttl)\n\t\treturn\n\t}\n\n\t// Make space if necessary\n\tif c.evictionList.Len() \u003e= c.maxSize {\n\t\ttoEvict := c.evictionList.Back()\n\t\tc.evictionList.Remove(toEvict)\n\t\tdelete(c.entries, toEvict.Value.(*cacheEntry).key)\n\t}\n\n\t// Add new entry\n\tentry := \u0026cacheEntry{\n\t\tkey: key,\n\t\tvalue: value,\n\t\texpireTime: c.clock.Now().Add(ttl),\n\t}\n\telement := c.evictionList.PushFront(entry)\n\tc.entries[key] = element\n}","line":{"from":72,"to":101}} {"id":100015624,"name":"Get","signature":"func (c *LRUExpireCache) Get(key interface{}) (interface{}, bool)","file":"staging/src/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.go","code":"// Get returns the value at the specified key from the cache if it exists and is not\n// expired, or returns false.\nfunc (c *LRUExpireCache) Get(key interface{}) (interface{}, bool) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\telement, ok := c.entries[key]\n\tif !ok {\n\t\treturn nil, false\n\t}\n\n\tif c.clock.Now().After(element.Value.(*cacheEntry).expireTime) {\n\t\tc.evictionList.Remove(element)\n\t\tdelete(c.entries, key)\n\t\treturn nil, false\n\t}\n\n\tc.evictionList.MoveToFront(element)\n\n\treturn element.Value.(*cacheEntry).value, true\n}","line":{"from":103,"to":123}} {"id":100015625,"name":"Remove","signature":"func (c *LRUExpireCache) Remove(key interface{})","file":"staging/src/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.go","code":"// Remove removes the specified key from the cache if it exists\nfunc (c *LRUExpireCache) Remove(key interface{}) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\telement, ok := c.entries[key]\n\tif !ok {\n\t\treturn\n\t}\n\n\tc.evictionList.Remove(element)\n\tdelete(c.entries, key)\n}","line":{"from":125,"to":137}} {"id":100015626,"name":"Keys","signature":"func (c *LRUExpireCache) Keys() []interface{}","file":"staging/src/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.go","code":"// Keys returns all unexpired keys in the cache.\n//\n// Keep in mind that subsequent calls to Get() for any of the returned keys\n// might return \"not found\".\n//\n// Keys are returned ordered from least recently used to most recently used.\nfunc (c *LRUExpireCache) Keys() []interface{} {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tnow := c.clock.Now()\n\n\tval := make([]interface{}, 0, c.evictionList.Len())\n\tfor element := c.evictionList.Back(); element != nil; element = element.Prev() {\n\t\t// Only return unexpired keys\n\t\tif !now.After(element.Value.(*cacheEntry).expireTime) {\n\t\t\tval = append(val, element.Value.(*cacheEntry).key)\n\t\t}\n\t}\n\n\treturn val\n}","line":{"from":139,"to":160}} {"id":100015627,"name":"StringDiff","signature":"func StringDiff(a, b string) string","file":"staging/src/k8s.io/apimachinery/pkg/util/diff/diff.go","code":"// StringDiff diffs a and b and returns a human readable diff.\nfunc StringDiff(a, b string) string {\n\tba := []byte(a)\n\tbb := []byte(b)\n\tout := []byte{}\n\ti := 0\n\tfor ; i \u003c len(ba) \u0026\u0026 i \u003c len(bb); i++ {\n\t\tif ba[i] != bb[i] {\n\t\t\tbreak\n\t\t}\n\t\tout = append(out, ba[i])\n\t}\n\tout = append(out, []byte(\"\\n\\nA: \")...)\n\tout = append(out, ba[i:]...)\n\tout = append(out, []byte(\"\\n\\nB: \")...)\n\tout = append(out, bb[i:]...)\n\tout = append(out, []byte(\"\\n\\n\")...)\n\treturn string(out)\n}","line":{"from":30,"to":48}} {"id":100015628,"name":"legacyDiff","signature":"func legacyDiff(a, b interface{}) string","file":"staging/src/k8s.io/apimachinery/pkg/util/diff/diff.go","code":"func legacyDiff(a, b interface{}) string {\n\treturn cmp.Diff(a, b)\n}","line":{"from":50,"to":52}} {"id":100015629,"name":"ObjectDiff","signature":"func ObjectDiff(a, b interface{}) string","file":"staging/src/k8s.io/apimachinery/pkg/util/diff/diff.go","code":"// ObjectDiff prints the diff of two go objects and fails if the objects\n// contain unhandled unexported fields.\n// DEPRECATED: use github.com/google/go-cmp/cmp.Diff\nfunc ObjectDiff(a, b interface{}) string {\n\treturn legacyDiff(a, b)\n}","line":{"from":54,"to":59}} {"id":100015630,"name":"ObjectGoPrintDiff","signature":"func ObjectGoPrintDiff(a, b interface{}) string","file":"staging/src/k8s.io/apimachinery/pkg/util/diff/diff.go","code":"// ObjectGoPrintDiff prints the diff of two go objects and fails if the objects\n// contain unhandled unexported fields.\n// DEPRECATED: use github.com/google/go-cmp/cmp.Diff\nfunc ObjectGoPrintDiff(a, b interface{}) string {\n\treturn legacyDiff(a, b)\n}","line":{"from":61,"to":66}} {"id":100015631,"name":"ObjectReflectDiff","signature":"func ObjectReflectDiff(a, b interface{}) string","file":"staging/src/k8s.io/apimachinery/pkg/util/diff/diff.go","code":"// ObjectReflectDiff prints the diff of two go objects and fails if the objects\n// contain unhandled unexported fields.\n// DEPRECATED: use github.com/google/go-cmp/cmp.Diff\nfunc ObjectReflectDiff(a, b interface{}) string {\n\treturn legacyDiff(a, b)\n}","line":{"from":68,"to":73}} {"id":100015632,"name":"ObjectGoPrintSideBySide","signature":"func ObjectGoPrintSideBySide(a, b interface{}) string","file":"staging/src/k8s.io/apimachinery/pkg/util/diff/diff.go","code":"// ObjectGoPrintSideBySide prints a and b as textual dumps side by side,\n// enabling easy visual scanning for mismatches.\nfunc ObjectGoPrintSideBySide(a, b interface{}) string {\n\ts := spew.ConfigState{\n\t\tIndent: \" \",\n\t\t// Extra deep spew.\n\t\tDisableMethods: true,\n\t}\n\tsA := s.Sdump(a)\n\tsB := s.Sdump(b)\n\n\tlinesA := strings.Split(sA, \"\\n\")\n\tlinesB := strings.Split(sB, \"\\n\")\n\twidth := 0\n\tfor _, s := range linesA {\n\t\tl := len(s)\n\t\tif l \u003e width {\n\t\t\twidth = l\n\t\t}\n\t}\n\tfor _, s := range linesB {\n\t\tl := len(s)\n\t\tif l \u003e width {\n\t\t\twidth = l\n\t\t}\n\t}\n\tbuf := \u0026bytes.Buffer{}\n\tw := tabwriter.NewWriter(buf, width, 0, 1, ' ', 0)\n\tmax := len(linesA)\n\tif len(linesB) \u003e max {\n\t\tmax = len(linesB)\n\t}\n\tfor i := 0; i \u003c max; i++ {\n\t\tvar a, b string\n\t\tif i \u003c len(linesA) {\n\t\t\ta = linesA[i]\n\t\t}\n\t\tif i \u003c len(linesB) {\n\t\t\tb = linesB[i]\n\t\t}\n\t\tfmt.Fprintf(w, \"%s\\t%s\\n\", a, b)\n\t}\n\tw.Flush()\n\treturn buf.String()\n}","line":{"from":75,"to":119}} {"id":100015633,"name":"IgnoreUnset","signature":"func IgnoreUnset() cmp.Option","file":"staging/src/k8s.io/apimachinery/pkg/util/diff/diff.go","code":"// IgnoreUnset is an option that ignores fields that are unset on the right\n// hand side of a comparison. This is useful in testing to assert that an\n// object is a derivative.\nfunc IgnoreUnset() cmp.Option {\n\treturn cmp.Options{\n\t\t// ignore unset fields in v2\n\t\tcmp.FilterPath(func(path cmp.Path) bool {\n\t\t\t_, v2 := path.Last().Values()\n\t\t\tswitch v2.Kind() {\n\t\t\tcase reflect.Slice, reflect.Map:\n\t\t\t\tif v2.IsNil() || v2.Len() == 0 {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\tcase reflect.String:\n\t\t\t\tif v2.Len() == 0 {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\tcase reflect.Interface, reflect.Pointer:\n\t\t\t\tif v2.IsNil() {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false\n\t\t}, cmp.Ignore()),\n\t\t// ignore map entries that aren't set in v2\n\t\tcmp.FilterPath(func(path cmp.Path) bool {\n\t\t\tswitch i := path.Last().(type) {\n\t\t\tcase cmp.MapIndex:\n\t\t\t\tif _, v2 := i.Values(); !v2.IsValid() {\n\t\t\t\t\tfmt.Println(\"E\")\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false\n\t\t}, cmp.Ignore()),\n\t}\n}","line":{"from":121,"to":157}} {"id":100015634,"name":"ShortHumanDuration","signature":"func ShortHumanDuration(d time.Duration) string","file":"staging/src/k8s.io/apimachinery/pkg/util/duration/duration.go","code":"// ShortHumanDuration returns a succinct representation of the provided duration\n// with limited precision for consumption by humans.\nfunc ShortHumanDuration(d time.Duration) string {\n\t// Allow deviation no more than 2 seconds(excluded) to tolerate machine time\n\t// inconsistence, it can be considered as almost now.\n\tif seconds := int(d.Seconds()); seconds \u003c -1 {\n\t\treturn \"\u003cinvalid\u003e\"\n\t} else if seconds \u003c 0 {\n\t\treturn \"0s\"\n\t} else if seconds \u003c 60 {\n\t\treturn fmt.Sprintf(\"%ds\", seconds)\n\t} else if minutes := int(d.Minutes()); minutes \u003c 60 {\n\t\treturn fmt.Sprintf(\"%dm\", minutes)\n\t} else if hours := int(d.Hours()); hours \u003c 24 {\n\t\treturn fmt.Sprintf(\"%dh\", hours)\n\t} else if hours \u003c 24*365 {\n\t\treturn fmt.Sprintf(\"%dd\", hours/24)\n\t}\n\treturn fmt.Sprintf(\"%dy\", int(d.Hours()/24/365))\n}","line":{"from":24,"to":43}} {"id":100015635,"name":"HumanDuration","signature":"func HumanDuration(d time.Duration) string","file":"staging/src/k8s.io/apimachinery/pkg/util/duration/duration.go","code":"// HumanDuration returns a succinct representation of the provided duration\n// with limited precision for consumption by humans. It provides ~2-3 significant\n// figures of duration.\nfunc HumanDuration(d time.Duration) string {\n\t// Allow deviation no more than 2 seconds(excluded) to tolerate machine time\n\t// inconsistence, it can be considered as almost now.\n\tif seconds := int(d.Seconds()); seconds \u003c -1 {\n\t\treturn \"\u003cinvalid\u003e\"\n\t} else if seconds \u003c 0 {\n\t\treturn \"0s\"\n\t} else if seconds \u003c 60*2 {\n\t\treturn fmt.Sprintf(\"%ds\", seconds)\n\t}\n\tminutes := int(d / time.Minute)\n\tif minutes \u003c 10 {\n\t\ts := int(d/time.Second) % 60\n\t\tif s == 0 {\n\t\t\treturn fmt.Sprintf(\"%dm\", minutes)\n\t\t}\n\t\treturn fmt.Sprintf(\"%dm%ds\", minutes, s)\n\t} else if minutes \u003c 60*3 {\n\t\treturn fmt.Sprintf(\"%dm\", minutes)\n\t}\n\thours := int(d / time.Hour)\n\tif hours \u003c 8 {\n\t\tm := int(d/time.Minute) % 60\n\t\tif m == 0 {\n\t\t\treturn fmt.Sprintf(\"%dh\", hours)\n\t\t}\n\t\treturn fmt.Sprintf(\"%dh%dm\", hours, m)\n\t} else if hours \u003c 48 {\n\t\treturn fmt.Sprintf(\"%dh\", hours)\n\t} else if hours \u003c 24*8 {\n\t\th := hours % 24\n\t\tif h == 0 {\n\t\t\treturn fmt.Sprintf(\"%dd\", hours/24)\n\t\t}\n\t\treturn fmt.Sprintf(\"%dd%dh\", hours/24, h)\n\t} else if hours \u003c 24*365*2 {\n\t\treturn fmt.Sprintf(\"%dd\", hours/24)\n\t} else if hours \u003c 24*365*8 {\n\t\tdy := int(hours/24) % 365\n\t\tif dy == 0 {\n\t\t\treturn fmt.Sprintf(\"%dy\", hours/24/365)\n\t\t}\n\t\treturn fmt.Sprintf(\"%dy%dd\", hours/24/365, dy)\n\t}\n\treturn fmt.Sprintf(\"%dy\", int(hours/24/365))\n}","line":{"from":45,"to":93}} {"id":100015636,"name":"NewAggregate","signature":"func NewAggregate(errlist []error) Aggregate","file":"staging/src/k8s.io/apimachinery/pkg/util/errors/errors.go","code":"// NewAggregate converts a slice of errors into an Aggregate interface, which\n// is itself an implementation of the error interface. If the slice is empty,\n// this returns nil.\n// It will check if any of the element of input error list is nil, to avoid\n// nil pointer panic when call Error().\nfunc NewAggregate(errlist []error) Aggregate {\n\tif len(errlist) == 0 {\n\t\treturn nil\n\t}\n\t// In case of input error list contains nil\n\tvar errs []error\n\tfor _, e := range errlist {\n\t\tif e != nil {\n\t\t\terrs = append(errs, e)\n\t\t}\n\t}\n\tif len(errs) == 0 {\n\t\treturn nil\n\t}\n\treturn aggregate(errs)\n}","line":{"from":41,"to":61}} {"id":100015637,"name":"Error","signature":"func (agg aggregate) Error() string","file":"staging/src/k8s.io/apimachinery/pkg/util/errors/errors.go","code":"// Error is part of the error interface.\nfunc (agg aggregate) Error() string {\n\tif len(agg) == 0 {\n\t\t// This should never happen, really.\n\t\treturn \"\"\n\t}\n\tif len(agg) == 1 {\n\t\treturn agg[0].Error()\n\t}\n\tseenerrs := sets.NewString()\n\tresult := \"\"\n\tagg.visit(func(err error) bool {\n\t\tmsg := err.Error()\n\t\tif seenerrs.Has(msg) {\n\t\t\treturn false\n\t\t}\n\t\tseenerrs.Insert(msg)\n\t\tif len(seenerrs) \u003e 1 {\n\t\t\tresult += \", \"\n\t\t}\n\t\tresult += msg\n\t\treturn false\n\t})\n\tif len(seenerrs) == 1 {\n\t\treturn result\n\t}\n\treturn \"[\" + result + \"]\"\n}","line":{"from":68,"to":95}} {"id":100015638,"name":"Is","signature":"func (agg aggregate) Is(target error) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/errors/errors.go","code":"func (agg aggregate) Is(target error) bool {\n\treturn agg.visit(func(err error) bool {\n\t\treturn errors.Is(err, target)\n\t})\n}","line":{"from":97,"to":101}} {"id":100015639,"name":"visit","signature":"func (agg aggregate) visit(f func(err error) bool) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/errors/errors.go","code":"func (agg aggregate) visit(f func(err error) bool) bool {\n\tfor _, err := range agg {\n\t\tswitch err := err.(type) {\n\t\tcase aggregate:\n\t\t\tif match := err.visit(f); match {\n\t\t\t\treturn match\n\t\t\t}\n\t\tcase Aggregate:\n\t\t\tfor _, nestedErr := range err.Errors() {\n\t\t\t\tif match := f(nestedErr); match {\n\t\t\t\t\treturn match\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\tif match := f(err); match {\n\t\t\t\treturn match\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":103,"to":124}} {"id":100015640,"name":"Errors","signature":"func (agg aggregate) Errors() []error","file":"staging/src/k8s.io/apimachinery/pkg/util/errors/errors.go","code":"// Errors is part of the Aggregate interface.\nfunc (agg aggregate) Errors() []error {\n\treturn []error(agg)\n}","line":{"from":126,"to":129}} {"id":100015641,"name":"FilterOut","signature":"func FilterOut(err error, fns ...Matcher) error","file":"staging/src/k8s.io/apimachinery/pkg/util/errors/errors.go","code":"// FilterOut removes all errors that match any of the matchers from the input\n// error. If the input is a singular error, only that error is tested. If the\n// input implements the Aggregate interface, the list of errors will be\n// processed recursively.\n//\n// This can be used, for example, to remove known-OK errors (such as io.EOF or\n// os.PathNotFound) from a list of errors.\nfunc FilterOut(err error, fns ...Matcher) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\tif agg, ok := err.(Aggregate); ok {\n\t\treturn NewAggregate(filterErrors(agg.Errors(), fns...))\n\t}\n\tif !matchesError(err, fns...) {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":134,"to":152}} {"id":100015642,"name":"matchesError","signature":"func matchesError(err error, fns ...Matcher) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/errors/errors.go","code":"// matchesError returns true if any Matcher returns true\nfunc matchesError(err error, fns ...Matcher) bool {\n\tfor _, fn := range fns {\n\t\tif fn(err) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":154,"to":162}} {"id":100015643,"name":"filterErrors","signature":"func filterErrors(list []error, fns ...Matcher) []error","file":"staging/src/k8s.io/apimachinery/pkg/util/errors/errors.go","code":"// filterErrors returns any errors (or nested errors, if the list contains\n// nested Errors) for which all fns return false. If no errors\n// remain a nil list is returned. The resulting slice will have all\n// nested slices flattened as a side effect.\nfunc filterErrors(list []error, fns ...Matcher) []error {\n\tresult := []error{}\n\tfor _, err := range list {\n\t\tr := FilterOut(err, fns...)\n\t\tif r != nil {\n\t\t\tresult = append(result, r)\n\t\t}\n\t}\n\treturn result\n}","line":{"from":164,"to":177}} {"id":100015644,"name":"Flatten","signature":"func Flatten(agg Aggregate) Aggregate","file":"staging/src/k8s.io/apimachinery/pkg/util/errors/errors.go","code":"// Flatten takes an Aggregate, which may hold other Aggregates in arbitrary\n// nesting, and flattens them all into a single Aggregate, recursively.\nfunc Flatten(agg Aggregate) Aggregate {\n\tresult := []error{}\n\tif agg == nil {\n\t\treturn nil\n\t}\n\tfor _, err := range agg.Errors() {\n\t\tif a, ok := err.(Aggregate); ok {\n\t\t\tr := Flatten(a)\n\t\t\tif r != nil {\n\t\t\t\tresult = append(result, r.Errors()...)\n\t\t\t}\n\t\t} else {\n\t\t\tif err != nil {\n\t\t\t\tresult = append(result, err)\n\t\t\t}\n\t\t}\n\t}\n\treturn NewAggregate(result)\n}","line":{"from":179,"to":199}} {"id":100015645,"name":"CreateAggregateFromMessageCountMap","signature":"func CreateAggregateFromMessageCountMap(m MessageCountMap) Aggregate","file":"staging/src/k8s.io/apimachinery/pkg/util/errors/errors.go","code":"// CreateAggregateFromMessageCountMap converts MessageCountMap Aggregate\nfunc CreateAggregateFromMessageCountMap(m MessageCountMap) Aggregate {\n\tif m == nil {\n\t\treturn nil\n\t}\n\tresult := make([]error, 0, len(m))\n\tfor errStr, count := range m {\n\t\tvar countStr string\n\t\tif count \u003e 1 {\n\t\t\tcountStr = fmt.Sprintf(\" (repeated %v times)\", count)\n\t\t}\n\t\tresult = append(result, fmt.Errorf(\"%v%v\", errStr, countStr))\n\t}\n\treturn NewAggregate(result)\n}","line":{"from":201,"to":215}} {"id":100015646,"name":"Reduce","signature":"func Reduce(err error) error","file":"staging/src/k8s.io/apimachinery/pkg/util/errors/errors.go","code":"// Reduce will return err or nil, if err is an Aggregate and only has one item,\n// the first item in the aggregate.\nfunc Reduce(err error) error {\n\tif agg, ok := err.(Aggregate); ok \u0026\u0026 err != nil {\n\t\tswitch len(agg.Errors()) {\n\t\tcase 1:\n\t\t\treturn agg.Errors()[0]\n\t\tcase 0:\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn err\n}","line":{"from":217,"to":229}} {"id":100015647,"name":"AggregateGoroutines","signature":"func AggregateGoroutines(funcs ...func() error) Aggregate","file":"staging/src/k8s.io/apimachinery/pkg/util/errors/errors.go","code":"// AggregateGoroutines runs the provided functions in parallel, stuffing all\n// non-nil errors into the returned Aggregate.\n// Returns nil if all the functions complete successfully.\nfunc AggregateGoroutines(funcs ...func() error) Aggregate {\n\terrChan := make(chan error, len(funcs))\n\tfor _, f := range funcs {\n\t\tgo func(f func() error) { errChan \u003c- f() }(f)\n\t}\n\terrs := make([]error, 0)\n\tfor i := 0; i \u003c cap(errChan); i++ {\n\t\tif err := \u003c-errChan; err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\treturn NewAggregate(errs)\n}","line":{"from":231,"to":246}} {"id":100015648,"name":"NewLengthDelimitedFrameWriter","signature":"func NewLengthDelimitedFrameWriter(w io.Writer) io.Writer","file":"staging/src/k8s.io/apimachinery/pkg/util/framer/framer.go","code":"func NewLengthDelimitedFrameWriter(w io.Writer) io.Writer {\n\treturn \u0026lengthDelimitedFrameWriter{w: w}\n}","line":{"from":31,"to":33}} {"id":100015649,"name":"Write","signature":"func (w *lengthDelimitedFrameWriter) Write(data []byte) (int, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/framer/framer.go","code":"// Write writes a single frame to the nested writer, prepending it with the length\n// in bytes of data (as a 4 byte, bigendian uint32).\nfunc (w *lengthDelimitedFrameWriter) Write(data []byte) (int, error) {\n\tbinary.BigEndian.PutUint32(w.h[:], uint32(len(data)))\n\tn, err := w.w.Write(w.h[:])\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif n != len(w.h) {\n\t\treturn 0, io.ErrShortWrite\n\t}\n\treturn w.w.Write(data)\n}","line":{"from":35,"to":47}} {"id":100015650,"name":"NewLengthDelimitedFrameReader","signature":"func NewLengthDelimitedFrameReader(r io.ReadCloser) io.ReadCloser","file":"staging/src/k8s.io/apimachinery/pkg/util/framer/framer.go","code":"// NewLengthDelimitedFrameReader returns an io.Reader that will decode length-prefixed\n// frames off of a stream.\n//\n// The protocol is:\n//\n//\tstream: message ...\n//\tmessage: prefix body\n//\tprefix: 4 byte uint32 in BigEndian order, denotes length of body\n//\tbody: bytes (0..prefix)\n//\n// If the buffer passed to Read is not long enough to contain an entire frame, io.ErrShortRead\n// will be returned along with the number of bytes read.\nfunc NewLengthDelimitedFrameReader(r io.ReadCloser) io.ReadCloser {\n\treturn \u0026lengthDelimitedFrameReader{r: r}\n}","line":{"from":54,"to":68}} {"id":100015651,"name":"Read","signature":"func (r *lengthDelimitedFrameReader) Read(data []byte) (int, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/framer/framer.go","code":"// Read attempts to read an entire frame into data. If that is not possible, io.ErrShortBuffer\n// is returned and subsequent calls will attempt to read the last frame. A frame is complete when\n// err is nil.\nfunc (r *lengthDelimitedFrameReader) Read(data []byte) (int, error) {\n\tif r.remaining \u003c= 0 {\n\t\theader := [4]byte{}\n\t\tn, err := io.ReadAtLeast(r.r, header[:4], 4)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tif n != 4 {\n\t\t\treturn 0, io.ErrUnexpectedEOF\n\t\t}\n\t\tframeLength := int(binary.BigEndian.Uint32(header[:]))\n\t\tr.remaining = frameLength\n\t}\n\n\texpect := r.remaining\n\tmax := expect\n\tif max \u003e len(data) {\n\t\tmax = len(data)\n\t}\n\tn, err := io.ReadAtLeast(r.r, data[:max], int(max))\n\tr.remaining -= n\n\tif err == io.ErrShortBuffer || r.remaining \u003e 0 {\n\t\treturn n, io.ErrShortBuffer\n\t}\n\tif err != nil {\n\t\treturn n, err\n\t}\n\tif n != expect {\n\t\treturn n, io.ErrUnexpectedEOF\n\t}\n\n\treturn n, nil\n}","line":{"from":70,"to":105}} {"id":100015652,"name":"Close","signature":"func (r *lengthDelimitedFrameReader) Close() error","file":"staging/src/k8s.io/apimachinery/pkg/util/framer/framer.go","code":"func (r *lengthDelimitedFrameReader) Close() error {\n\treturn r.r.Close()\n}","line":{"from":107,"to":109}} {"id":100015653,"name":"NewJSONFramedReader","signature":"func NewJSONFramedReader(r io.ReadCloser) io.ReadCloser","file":"staging/src/k8s.io/apimachinery/pkg/util/framer/framer.go","code":"// NewJSONFramedReader returns an io.Reader that will decode individual JSON objects off\n// of a wire.\n//\n// The boundaries between each frame are valid JSON objects. A JSON parsing error will terminate\n// the read.\nfunc NewJSONFramedReader(r io.ReadCloser) io.ReadCloser {\n\treturn \u0026jsonFrameReader{\n\t\tr: r,\n\t\tdecoder: json.NewDecoder(r),\n\t}\n}","line":{"from":117,"to":127}} {"id":100015654,"name":"Read","signature":"func (r *jsonFrameReader) Read(data []byte) (int, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/framer/framer.go","code":"// ReadFrame decodes the next JSON object in the stream, or returns an error. The returned\n// byte slice will be modified the next time ReadFrame is invoked and should not be altered.\nfunc (r *jsonFrameReader) Read(data []byte) (int, error) {\n\t// Return whatever remaining data exists from an in progress frame\n\tif n := len(r.remaining); n \u003e 0 {\n\t\tif n \u003c= len(data) {\n\t\t\t//nolint:staticcheck // SA4006,SA4010 underlying array of data is modified here.\n\t\t\tdata = append(data[0:0], r.remaining...)\n\t\t\tr.remaining = nil\n\t\t\treturn n, nil\n\t\t}\n\n\t\tn = len(data)\n\t\t//nolint:staticcheck // SA4006,SA4010 underlying array of data is modified here.\n\t\tdata = append(data[0:0], r.remaining[:n]...)\n\t\tr.remaining = r.remaining[n:]\n\t\treturn n, io.ErrShortBuffer\n\t}\n\n\t// RawMessage#Unmarshal appends to data - we reset the slice down to 0 and will either see\n\t// data written to data, or be larger than data and a different array.\n\tn := len(data)\n\tm := json.RawMessage(data[:0])\n\tif err := r.decoder.Decode(\u0026m); err != nil {\n\t\treturn 0, err\n\t}\n\n\t// If capacity of data is less than length of the message, decoder will allocate a new slice\n\t// and set m to it, which means we need to copy the partial result back into data and preserve\n\t// the remaining result for subsequent reads.\n\tif len(m) \u003e n {\n\t\t//nolint:staticcheck // SA4006,SA4010 underlying array of data is modified here.\n\t\tdata = append(data[0:0], m[:n]...)\n\t\tr.remaining = m[n:]\n\t\treturn n, io.ErrShortBuffer\n\t}\n\treturn len(m), nil\n}","line":{"from":129,"to":166}} {"id":100015655,"name":"Close","signature":"func (r *jsonFrameReader) Close() error","file":"staging/src/k8s.io/apimachinery/pkg/util/framer/framer.go","code":"func (r *jsonFrameReader) Close() error {\n\treturn r.r.Close()\n}","line":{"from":168,"to":170}} {"id":100015656,"name":"NoOpNewStreamHandler","signature":"func NoOpNewStreamHandler(stream Stream, replySent \u003c-chan struct{}) error { return nil }","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/httpstream.go","code":"// NoOpNewStreamHandler is a stream handler that accepts a new stream and\n// performs no other logic.\nfunc NoOpNewStreamHandler(stream Stream, replySent \u003c-chan struct{}) error { return nil }","line":{"from":39,"to":41}} {"id":100015657,"name":"IsUpgradeRequest","signature":"func IsUpgradeRequest(req *http.Request) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/httpstream.go","code":"// IsUpgradeRequest returns true if the given request is a connection upgrade request\nfunc IsUpgradeRequest(req *http.Request) bool {\n\tfor _, h := range req.Header[http.CanonicalHeaderKey(HeaderConnection)] {\n\t\tif strings.Contains(strings.ToLower(h), strings.ToLower(HeaderUpgrade)) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":98,"to":106}} {"id":100015658,"name":"negotiateProtocol","signature":"func negotiateProtocol(clientProtocols, serverProtocols []string) string","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/httpstream.go","code":"func negotiateProtocol(clientProtocols, serverProtocols []string) string {\n\tfor i := range clientProtocols {\n\t\tfor j := range serverProtocols {\n\t\t\tif clientProtocols[i] == serverProtocols[j] {\n\t\t\t\treturn clientProtocols[i]\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\"\n}","line":{"from":108,"to":117}} {"id":100015659,"name":"commaSeparatedHeaderValues","signature":"func commaSeparatedHeaderValues(header []string) []string","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/httpstream.go","code":"func commaSeparatedHeaderValues(header []string) []string {\n\tvar parsedClientProtocols []string\n\tfor i := range header {\n\t\tfor _, clientProtocol := range strings.Split(header[i], \",\") {\n\t\t\tif proto := strings.Trim(clientProtocol, \" \"); len(proto) \u003e 0 {\n\t\t\t\tparsedClientProtocols = append(parsedClientProtocols, proto)\n\t\t\t}\n\t\t}\n\t}\n\treturn parsedClientProtocols\n}","line":{"from":119,"to":129}} {"id":100015660,"name":"Handshake","signature":"func Handshake(req *http.Request, w http.ResponseWriter, serverProtocols []string) (string, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/httpstream.go","code":"// Handshake performs a subprotocol negotiation. If the client did request a\n// subprotocol, Handshake will select the first common value found in\n// serverProtocols. If a match is found, Handshake adds a response header\n// indicating the chosen subprotocol. If no match is found, HTTP forbidden is\n// returned, along with a response header containing the list of protocols the\n// server can accept.\nfunc Handshake(req *http.Request, w http.ResponseWriter, serverProtocols []string) (string, error) {\n\tclientProtocols := commaSeparatedHeaderValues(req.Header[http.CanonicalHeaderKey(HeaderProtocolVersion)])\n\tif len(clientProtocols) == 0 {\n\t\treturn \"\", fmt.Errorf(\"unable to upgrade: %s is required\", HeaderProtocolVersion)\n\t}\n\n\tif len(serverProtocols) == 0 {\n\t\tpanic(fmt.Errorf(\"unable to upgrade: serverProtocols is required\"))\n\t}\n\n\tnegotiatedProtocol := negotiateProtocol(clientProtocols, serverProtocols)\n\tif len(negotiatedProtocol) == 0 {\n\t\tfor i := range serverProtocols {\n\t\t\tw.Header().Add(HeaderAcceptedProtocolVersions, serverProtocols[i])\n\t\t}\n\t\terr := fmt.Errorf(\"unable to upgrade: unable to negotiate protocol: client supports %v, server accepts %v\", clientProtocols, serverProtocols)\n\t\thttp.Error(w, err.Error(), http.StatusForbidden)\n\t\treturn \"\", err\n\t}\n\n\tw.Header().Add(HeaderProtocolVersion, negotiatedProtocol)\n\treturn negotiatedProtocol, nil\n}","line":{"from":131,"to":159}} {"id":100015661,"name":"NewClientConnection","signature":"func NewClientConnection(conn net.Conn) (httpstream.Connection, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/connection.go","code":"// NewClientConnection creates a new SPDY client connection.\nfunc NewClientConnection(conn net.Conn) (httpstream.Connection, error) {\n\treturn NewClientConnectionWithPings(conn, 0)\n}","line":{"from":40,"to":43}} {"id":100015662,"name":"NewClientConnectionWithPings","signature":"func NewClientConnectionWithPings(conn net.Conn, pingPeriod time.Duration) (httpstream.Connection, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/connection.go","code":"// NewClientConnectionWithPings creates a new SPDY client connection.\n//\n// If pingPeriod is non-zero, a background goroutine will send periodic Ping\n// frames to the server. Use this to keep idle connections through certain load\n// balancers alive longer.\nfunc NewClientConnectionWithPings(conn net.Conn, pingPeriod time.Duration) (httpstream.Connection, error) {\n\tspdyConn, err := spdystream.NewConnection(conn, false)\n\tif err != nil {\n\t\tdefer conn.Close()\n\t\treturn nil, err\n\t}\n\n\treturn newConnection(spdyConn, httpstream.NoOpNewStreamHandler, pingPeriod, spdyConn.Ping), nil\n}","line":{"from":45,"to":58}} {"id":100015663,"name":"NewServerConnection","signature":"func NewServerConnection(conn net.Conn, newStreamHandler httpstream.NewStreamHandler) (httpstream.Connection, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/connection.go","code":"// NewServerConnection creates a new SPDY server connection. newStreamHandler\n// will be invoked when the server receives a newly created stream from the\n// client.\nfunc NewServerConnection(conn net.Conn, newStreamHandler httpstream.NewStreamHandler) (httpstream.Connection, error) {\n\treturn NewServerConnectionWithPings(conn, newStreamHandler, 0)\n}","line":{"from":60,"to":65}} {"id":100015664,"name":"NewServerConnectionWithPings","signature":"func NewServerConnectionWithPings(conn net.Conn, newStreamHandler httpstream.NewStreamHandler, pingPeriod time.Duration) (httpstream.Connection, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/connection.go","code":"// NewServerConnectionWithPings creates a new SPDY server connection.\n// newStreamHandler will be invoked when the server receives a newly created\n// stream from the client.\n//\n// If pingPeriod is non-zero, a background goroutine will send periodic Ping\n// frames to the server. Use this to keep idle connections through certain load\n// balancers alive longer.\nfunc NewServerConnectionWithPings(conn net.Conn, newStreamHandler httpstream.NewStreamHandler, pingPeriod time.Duration) (httpstream.Connection, error) {\n\tspdyConn, err := spdystream.NewConnection(conn, true)\n\tif err != nil {\n\t\tdefer conn.Close()\n\t\treturn nil, err\n\t}\n\n\treturn newConnection(spdyConn, newStreamHandler, pingPeriod, spdyConn.Ping), nil\n}","line":{"from":67,"to":82}} {"id":100015665,"name":"newConnection","signature":"func newConnection(conn *spdystream.Connection, newStreamHandler httpstream.NewStreamHandler, pingPeriod time.Duration, pingFn func() (time.Duration, error)) httpstream.Connection","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/connection.go","code":"// newConnection returns a new connection wrapping conn. newStreamHandler\n// will be invoked when the server receives a newly created stream from the\n// client.\nfunc newConnection(conn *spdystream.Connection, newStreamHandler httpstream.NewStreamHandler, pingPeriod time.Duration, pingFn func() (time.Duration, error)) httpstream.Connection {\n\tc := \u0026connection{\n\t\tconn: conn,\n\t\tnewStreamHandler: newStreamHandler,\n\t\tping: pingFn,\n\t\tstreams: make(map[uint32]httpstream.Stream),\n\t}\n\tgo conn.Serve(c.newSpdyStream)\n\tif pingPeriod \u003e 0 \u0026\u0026 pingFn != nil {\n\t\tgo c.sendPings(pingPeriod)\n\t}\n\treturn c\n}","line":{"from":84,"to":99}} {"id":100015666,"name":"Close","signature":"func (c *connection) Close() error","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/connection.go","code":"// Close first sends a reset for all of the connection's streams, and then\n// closes the underlying spdystream.Connection.\nfunc (c *connection) Close() error {\n\tc.streamLock.Lock()\n\tfor _, s := range c.streams {\n\t\t// calling Reset instead of Close ensures that all streams are fully torn down\n\t\ts.Reset()\n\t}\n\tc.streams = make(map[uint32]httpstream.Stream, 0)\n\tc.streamLock.Unlock()\n\n\t// now that all streams are fully torn down, it's safe to call close on the underlying connection,\n\t// which should be able to terminate immediately at this point, instead of waiting for any\n\t// remaining graceful stream termination.\n\treturn c.conn.Close()\n}","line":{"from":105,"to":120}} {"id":100015667,"name":"RemoveStreams","signature":"func (c *connection) RemoveStreams(streams ...httpstream.Stream)","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/connection.go","code":"// RemoveStreams can be used to removes a set of streams from the Connection.\nfunc (c *connection) RemoveStreams(streams ...httpstream.Stream) {\n\tc.streamLock.Lock()\n\tfor _, stream := range streams {\n\t\t// It may be possible that the provided stream is nil if timed out.\n\t\tif stream != nil {\n\t\t\tdelete(c.streams, stream.Identifier())\n\t\t}\n\t}\n\tc.streamLock.Unlock()\n}","line":{"from":122,"to":132}} {"id":100015668,"name":"CreateStream","signature":"func (c *connection) CreateStream(headers http.Header) (httpstream.Stream, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/connection.go","code":"// CreateStream creates a new stream with the specified headers and registers\n// it with the connection.\nfunc (c *connection) CreateStream(headers http.Header) (httpstream.Stream, error) {\n\tstream, err := c.conn.CreateStream(headers, nil, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err = stream.WaitTimeout(createStreamResponseTimeout); err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.registerStream(stream)\n\treturn stream, nil\n}","line":{"from":134,"to":147}} {"id":100015669,"name":"registerStream","signature":"func (c *connection) registerStream(s httpstream.Stream)","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/connection.go","code":"// registerStream adds the stream s to the connection's list of streams that\n// it owns.\nfunc (c *connection) registerStream(s httpstream.Stream) {\n\tc.streamLock.Lock()\n\tc.streams[s.Identifier()] = s\n\tc.streamLock.Unlock()\n}","line":{"from":149,"to":155}} {"id":100015670,"name":"CloseChan","signature":"func (c *connection) CloseChan() \u003c-chan bool","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/connection.go","code":"// CloseChan returns a channel that, when closed, indicates that the underlying\n// spdystream.Connection has been closed.\nfunc (c *connection) CloseChan() \u003c-chan bool {\n\treturn c.conn.CloseChan()\n}","line":{"from":157,"to":161}} {"id":100015671,"name":"newSpdyStream","signature":"func (c *connection) newSpdyStream(stream *spdystream.Stream)","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/connection.go","code":"// newSpdyStream is the internal new stream handler used by spdystream.Connection.Serve.\n// It calls connection's newStreamHandler, giving it the opportunity to accept or reject\n// the stream. If newStreamHandler returns an error, the stream is rejected. If not, the\n// stream is accepted and registered with the connection.\nfunc (c *connection) newSpdyStream(stream *spdystream.Stream) {\n\treplySent := make(chan struct{})\n\terr := c.newStreamHandler(stream, replySent)\n\trejectStream := (err != nil)\n\tif rejectStream {\n\t\tklog.Warningf(\"Stream rejected: %v\", err)\n\t\tstream.Reset()\n\t\treturn\n\t}\n\n\tc.registerStream(stream)\n\tstream.SendReply(http.Header{}, rejectStream)\n\tclose(replySent)\n}","line":{"from":163,"to":180}} {"id":100015672,"name":"SetIdleTimeout","signature":"func (c *connection) SetIdleTimeout(timeout time.Duration)","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/connection.go","code":"// SetIdleTimeout sets the amount of time the connection may remain idle before\n// it is automatically closed.\nfunc (c *connection) SetIdleTimeout(timeout time.Duration) {\n\tc.conn.SetIdleTimeout(timeout)\n}","line":{"from":182,"to":186}} {"id":100015673,"name":"sendPings","signature":"func (c *connection) sendPings(period time.Duration)","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/connection.go","code":"func (c *connection) sendPings(period time.Duration) {\n\tt := time.NewTicker(period)\n\tdefer t.Stop()\n\tfor {\n\t\tselect {\n\t\tcase \u003c-c.conn.CloseChan():\n\t\t\treturn\n\t\tcase \u003c-t.C:\n\t\t}\n\t\tif _, err := c.ping(); err != nil {\n\t\t\tklog.V(3).Infof(\"SPDY Ping failed: %v\", err)\n\t\t\t// Continue, in case this is a transient failure.\n\t\t\t// c.conn.CloseChan above will tell us when the connection is\n\t\t\t// actually closed.\n\t\t}\n\t}\n}","line":{"from":188,"to":204}} {"id":100015674,"name":"NewRoundTripper","signature":"func NewRoundTripper(tlsConfig *tls.Config) *SpdyRoundTripper","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper.go","code":"// NewRoundTripper creates a new SpdyRoundTripper that will use the specified\n// tlsConfig.\nfunc NewRoundTripper(tlsConfig *tls.Config) *SpdyRoundTripper {\n\treturn NewRoundTripperWithConfig(RoundTripperConfig{\n\t\tTLS: tlsConfig,\n\t})\n}","line":{"from":77,"to":83}} {"id":100015675,"name":"NewRoundTripperWithProxy","signature":"func NewRoundTripperWithProxy(tlsConfig *tls.Config, proxier func(*http.Request) (*url.URL, error)) *SpdyRoundTripper","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper.go","code":"// NewRoundTripperWithProxy creates a new SpdyRoundTripper that will use the\n// specified tlsConfig and proxy func.\nfunc NewRoundTripperWithProxy(tlsConfig *tls.Config, proxier func(*http.Request) (*url.URL, error)) *SpdyRoundTripper {\n\treturn NewRoundTripperWithConfig(RoundTripperConfig{\n\t\tTLS: tlsConfig,\n\t\tProxier: proxier,\n\t})\n}","line":{"from":85,"to":92}} {"id":100015676,"name":"NewRoundTripperWithConfig","signature":"func NewRoundTripperWithConfig(cfg RoundTripperConfig) *SpdyRoundTripper","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper.go","code":"// NewRoundTripperWithConfig creates a new SpdyRoundTripper with the specified\n// configuration.\nfunc NewRoundTripperWithConfig(cfg RoundTripperConfig) *SpdyRoundTripper {\n\tif cfg.Proxier == nil {\n\t\tcfg.Proxier = utilnet.NewProxierWithNoProxyCIDR(http.ProxyFromEnvironment)\n\t}\n\treturn \u0026SpdyRoundTripper{\n\t\ttlsConfig: cfg.TLS,\n\t\tproxier: cfg.Proxier,\n\t\tpingPeriod: cfg.PingPeriod,\n\t}\n}","line":{"from":94,"to":105}} {"id":100015677,"name":"TLSClientConfig","signature":"func (s *SpdyRoundTripper) TLSClientConfig() *tls.Config","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper.go","code":"// TLSClientConfig implements pkg/util/net.TLSClientConfigHolder for proper TLS checking during\n// proxying with a spdy roundtripper.\nfunc (s *SpdyRoundTripper) TLSClientConfig() *tls.Config {\n\treturn s.tlsConfig\n}","line":{"from":118,"to":122}} {"id":100015678,"name":"Dial","signature":"func (s *SpdyRoundTripper) Dial(req *http.Request) (net.Conn, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper.go","code":"// Dial implements k8s.io/apimachinery/pkg/util/net.Dialer.\nfunc (s *SpdyRoundTripper) Dial(req *http.Request) (net.Conn, error) {\n\tconn, err := s.dial(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := req.Write(conn); err != nil {\n\t\tconn.Close()\n\t\treturn nil, err\n\t}\n\n\treturn conn, nil\n}","line":{"from":124,"to":137}} {"id":100015679,"name":"dial","signature":"func (s *SpdyRoundTripper) dial(req *http.Request) (net.Conn, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper.go","code":"// dial dials the host specified by req, using TLS if appropriate, optionally\n// using a proxy server if one is configured via environment variables.\nfunc (s *SpdyRoundTripper) dial(req *http.Request) (net.Conn, error) {\n\tproxyURL, err := s.proxier(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif proxyURL == nil {\n\t\treturn s.dialWithoutProxy(req.Context(), req.URL)\n\t}\n\n\tswitch proxyURL.Scheme {\n\tcase \"socks5\":\n\t\treturn s.dialWithSocks5Proxy(req, proxyURL)\n\tcase \"https\", \"http\", \"\":\n\t\treturn s.dialWithHttpProxy(req, proxyURL)\n\t}\n\n\treturn nil, fmt.Errorf(\"proxy URL scheme not supported: %s\", proxyURL.Scheme)\n}","line":{"from":139,"to":159}} {"id":100015680,"name":"dialWithHttpProxy","signature":"func (s *SpdyRoundTripper) dialWithHttpProxy(req *http.Request, proxyURL *url.URL) (net.Conn, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper.go","code":"// dialWithHttpProxy dials the host specified by url through an http or an https proxy.\nfunc (s *SpdyRoundTripper) dialWithHttpProxy(req *http.Request, proxyURL *url.URL) (net.Conn, error) {\n\t// ensure we use a canonical host with proxyReq\n\ttargetHost := netutil.CanonicalAddr(req.URL)\n\n\t// proxying logic adapted from http://blog.h6t.eu/post/74098062923/golang-websocket-with-http-proxy-support\n\tproxyReq := http.Request{\n\t\tMethod: \"CONNECT\",\n\t\tURL: \u0026url.URL{},\n\t\tHost: targetHost,\n\t}\n\n\tproxyReq = *proxyReq.WithContext(req.Context())\n\n\tif pa := s.proxyAuth(proxyURL); pa != \"\" {\n\t\tproxyReq.Header = http.Header{}\n\t\tproxyReq.Header.Set(\"Proxy-Authorization\", pa)\n\t}\n\n\tproxyDialConn, err := s.dialWithoutProxy(proxyReq.Context(), proxyURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//nolint:staticcheck // SA1019 ignore deprecated httputil.NewProxyClientConn\n\tproxyClientConn := httputil.NewProxyClientConn(proxyDialConn, nil)\n\tresponse, err := proxyClientConn.Do(\u0026proxyReq)\n\t//nolint:staticcheck // SA1019 ignore deprecated httputil.ErrPersistEOF: it might be\n\t// returned from the invocation of proxyClientConn.Do\n\tif err != nil \u0026\u0026 err != httputil.ErrPersistEOF {\n\t\treturn nil, err\n\t}\n\tif response != nil \u0026\u0026 response.StatusCode \u003e= 300 || response.StatusCode \u003c 200 {\n\t\treturn nil, fmt.Errorf(\"CONNECT request to %s returned response: %s\", proxyURL.Redacted(), response.Status)\n\t}\n\n\trwc, _ := proxyClientConn.Hijack()\n\n\tif req.URL.Scheme == \"https\" {\n\t\treturn s.tlsConn(proxyReq.Context(), rwc, targetHost)\n\t}\n\treturn rwc, nil\n}","line":{"from":161,"to":203}} {"id":100015681,"name":"dialWithSocks5Proxy","signature":"func (s *SpdyRoundTripper) dialWithSocks5Proxy(req *http.Request, proxyURL *url.URL) (net.Conn, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper.go","code":"// dialWithSocks5Proxy dials the host specified by url through a socks5 proxy.\nfunc (s *SpdyRoundTripper) dialWithSocks5Proxy(req *http.Request, proxyURL *url.URL) (net.Conn, error) {\n\t// ensure we use a canonical host with proxyReq\n\ttargetHost := netutil.CanonicalAddr(req.URL)\n\tproxyDialAddr := netutil.CanonicalAddr(proxyURL)\n\n\tvar auth *proxy.Auth\n\tif proxyURL.User != nil {\n\t\tpass, _ := proxyURL.User.Password()\n\t\tauth = \u0026proxy.Auth{\n\t\t\tUser: proxyURL.User.Username(),\n\t\t\tPassword: pass,\n\t\t}\n\t}\n\n\tdialer := s.Dialer\n\tif dialer == nil {\n\t\tdialer = \u0026net.Dialer{\n\t\t\tTimeout: 30 * time.Second,\n\t\t}\n\t}\n\n\tproxyDialer, err := proxy.SOCKS5(\"tcp\", proxyDialAddr, auth, dialer)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// According to the implementation of proxy.SOCKS5, the type assertion will always succeed\n\tcontextDialer, ok := proxyDialer.(proxy.ContextDialer)\n\tif !ok {\n\t\treturn nil, errors.New(\"SOCKS5 Dialer must implement ContextDialer\")\n\t}\n\n\tproxyDialConn, err := contextDialer.DialContext(req.Context(), \"tcp\", targetHost)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif req.URL.Scheme == \"https\" {\n\t\treturn s.tlsConn(req.Context(), proxyDialConn, targetHost)\n\t}\n\treturn proxyDialConn, nil\n}","line":{"from":205,"to":247}} {"id":100015682,"name":"tlsConn","signature":"func (s *SpdyRoundTripper) tlsConn(ctx context.Context, rwc net.Conn, targetHost string) (net.Conn, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper.go","code":"// tlsConn returns a TLS client side connection using rwc as the underlying transport.\nfunc (s *SpdyRoundTripper) tlsConn(ctx context.Context, rwc net.Conn, targetHost string) (net.Conn, error) {\n\n\thost, _, err := net.SplitHostPort(targetHost)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttlsConfig := s.tlsConfig\n\tswitch {\n\tcase tlsConfig == nil:\n\t\ttlsConfig = \u0026tls.Config{ServerName: host}\n\tcase len(tlsConfig.ServerName) == 0:\n\t\ttlsConfig = tlsConfig.Clone()\n\t\ttlsConfig.ServerName = host\n\t}\n\n\ttlsConn := tls.Client(rwc, tlsConfig)\n\n\tif err := tlsConn.HandshakeContext(ctx); err != nil {\n\t\ttlsConn.Close()\n\t\treturn nil, err\n\t}\n\n\treturn tlsConn, nil\n}","line":{"from":249,"to":274}} {"id":100015683,"name":"dialWithoutProxy","signature":"func (s *SpdyRoundTripper) dialWithoutProxy(ctx context.Context, url *url.URL) (net.Conn, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper.go","code":"// dialWithoutProxy dials the host specified by url, using TLS if appropriate.\nfunc (s *SpdyRoundTripper) dialWithoutProxy(ctx context.Context, url *url.URL) (net.Conn, error) {\n\tdialAddr := netutil.CanonicalAddr(url)\n\tdialer := s.Dialer\n\tif dialer == nil {\n\t\tdialer = \u0026net.Dialer{}\n\t}\n\n\tif url.Scheme == \"http\" {\n\t\treturn dialer.DialContext(ctx, \"tcp\", dialAddr)\n\t}\n\n\ttlsDialer := tls.Dialer{\n\t\tNetDialer: dialer,\n\t\tConfig: s.tlsConfig,\n\t}\n\treturn tlsDialer.DialContext(ctx, \"tcp\", dialAddr)\n}","line":{"from":276,"to":293}} {"id":100015684,"name":"proxyAuth","signature":"func (s *SpdyRoundTripper) proxyAuth(proxyURL *url.URL) string","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper.go","code":"// proxyAuth returns, for a given proxy URL, the value to be used for the Proxy-Authorization header\nfunc (s *SpdyRoundTripper) proxyAuth(proxyURL *url.URL) string {\n\tif proxyURL == nil || proxyURL.User == nil {\n\t\treturn \"\"\n\t}\n\tusername := proxyURL.User.Username()\n\tpassword, _ := proxyURL.User.Password()\n\tauth := username + \":\" + password\n\treturn \"Basic \" + base64.StdEncoding.EncodeToString([]byte(auth))\n}","line":{"from":295,"to":304}} {"id":100015685,"name":"RoundTrip","signature":"func (s *SpdyRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper.go","code":"// RoundTrip executes the Request and upgrades it. After a successful upgrade,\n// clients may call SpdyRoundTripper.Connection() to retrieve the upgraded\n// connection.\nfunc (s *SpdyRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {\n\treq = utilnet.CloneRequest(req)\n\treq.Header.Add(httpstream.HeaderConnection, httpstream.HeaderUpgrade)\n\treq.Header.Add(httpstream.HeaderUpgrade, HeaderSpdy31)\n\n\tconn, err := s.Dial(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponseReader := bufio.NewReader(conn)\n\n\tresp, err := http.ReadResponse(responseReader, nil)\n\tif err != nil {\n\t\tconn.Close()\n\t\treturn nil, err\n\t}\n\n\ts.conn = conn\n\n\treturn resp, nil\n}","line":{"from":306,"to":330}} {"id":100015686,"name":"NewConnection","signature":"func (s *SpdyRoundTripper) NewConnection(resp *http.Response) (httpstream.Connection, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper.go","code":"// NewConnection validates the upgrade response, creating and returning a new\n// httpstream.Connection if there were no errors.\nfunc (s *SpdyRoundTripper) NewConnection(resp *http.Response) (httpstream.Connection, error) {\n\tconnectionHeader := strings.ToLower(resp.Header.Get(httpstream.HeaderConnection))\n\tupgradeHeader := strings.ToLower(resp.Header.Get(httpstream.HeaderUpgrade))\n\tif (resp.StatusCode != http.StatusSwitchingProtocols) || !strings.Contains(connectionHeader, strings.ToLower(httpstream.HeaderUpgrade)) || !strings.Contains(upgradeHeader, strings.ToLower(HeaderSpdy31)) {\n\t\tdefer resp.Body.Close()\n\t\tresponseError := \"\"\n\t\tresponseErrorBytes, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\tresponseError = \"unable to read error from server response\"\n\t\t} else {\n\t\t\t// TODO: I don't belong here, I should be abstracted from this class\n\t\t\tif obj, _, err := statusCodecs.UniversalDecoder().Decode(responseErrorBytes, nil, \u0026metav1.Status{}); err == nil {\n\t\t\t\tif status, ok := obj.(*metav1.Status); ok {\n\t\t\t\t\treturn nil, \u0026apierrors.StatusError{ErrStatus: *status}\n\t\t\t\t}\n\t\t\t}\n\t\t\tresponseError = string(responseErrorBytes)\n\t\t\tresponseError = strings.TrimSpace(responseError)\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"unable to upgrade connection: %s\", responseError)\n\t}\n\n\treturn NewClientConnectionWithPings(s.conn, s.pingPeriod)\n}","line":{"from":332,"to":358}} {"id":100015687,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper.go","code":"func init() {\n\tstatusScheme.AddUnversionedTypes(metav1.SchemeGroupVersion,\n\t\t\u0026metav1.Status{},\n\t)\n}","line":{"from":366,"to":370}} {"id":100015688,"name":"Read","signature":"func (w *connWrapper) Read(b []byte) (n int, err error)","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/upgrade.go","code":"func (w *connWrapper) Read(b []byte) (n int, err error) {\n\tif atomic.LoadInt32(\u0026w.closed) == 1 {\n\t\treturn 0, io.EOF\n\t}\n\treturn w.bufReader.Read(b)\n}","line":{"from":52,"to":57}} {"id":100015689,"name":"Close","signature":"func (w *connWrapper) Close() error","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/upgrade.go","code":"func (w *connWrapper) Close() error {\n\terr := w.Conn.Close()\n\tatomic.StoreInt32(\u0026w.closed, 1)\n\treturn err\n}","line":{"from":59,"to":63}} {"id":100015690,"name":"NewResponseUpgrader","signature":"func NewResponseUpgrader() httpstream.ResponseUpgrader","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/upgrade.go","code":"// NewResponseUpgrader returns a new httpstream.ResponseUpgrader that is\n// capable of upgrading HTTP responses using SPDY/3.1 via the\n// spdystream package.\nfunc NewResponseUpgrader() httpstream.ResponseUpgrader {\n\treturn NewResponseUpgraderWithPings(0)\n}","line":{"from":65,"to":70}} {"id":100015691,"name":"NewResponseUpgraderWithPings","signature":"func NewResponseUpgraderWithPings(pingPeriod time.Duration) httpstream.ResponseUpgrader","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/upgrade.go","code":"// NewResponseUpgraderWithPings returns a new httpstream.ResponseUpgrader that\n// is capable of upgrading HTTP responses using SPDY/3.1 via the spdystream\n// package.\n//\n// If pingPeriod is non-zero, for each incoming connection a background\n// goroutine will send periodic Ping frames to the server. Use this to keep\n// idle connections through certain load balancers alive longer.\nfunc NewResponseUpgraderWithPings(pingPeriod time.Duration) httpstream.ResponseUpgrader {\n\treturn responseUpgrader{pingPeriod: pingPeriod}\n}","line":{"from":72,"to":81}} {"id":100015692,"name":"UpgradeResponse","signature":"func (u responseUpgrader) UpgradeResponse(w http.ResponseWriter, req *http.Request, newStreamHandler httpstream.NewStreamHandler) httpstream.Connection","file":"staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy/upgrade.go","code":"// UpgradeResponse upgrades an HTTP response to one that supports multiplexed\n// streams. newStreamHandler will be called synchronously whenever the\n// other end of the upgraded connection creates a new stream.\nfunc (u responseUpgrader) UpgradeResponse(w http.ResponseWriter, req *http.Request, newStreamHandler httpstream.NewStreamHandler) httpstream.Connection {\n\tconnectionHeader := strings.ToLower(req.Header.Get(httpstream.HeaderConnection))\n\tupgradeHeader := strings.ToLower(req.Header.Get(httpstream.HeaderUpgrade))\n\tif !strings.Contains(connectionHeader, strings.ToLower(httpstream.HeaderUpgrade)) || !strings.Contains(upgradeHeader, strings.ToLower(HeaderSpdy31)) {\n\t\terrorMsg := fmt.Sprintf(\"unable to upgrade: missing upgrade headers in request: %#v\", req.Header)\n\t\thttp.Error(w, errorMsg, http.StatusBadRequest)\n\t\treturn nil\n\t}\n\n\thijacker, ok := w.(http.Hijacker)\n\tif !ok {\n\t\terrorMsg := \"unable to upgrade: unable to hijack response\"\n\t\thttp.Error(w, errorMsg, http.StatusInternalServerError)\n\t\treturn nil\n\t}\n\n\tw.Header().Add(httpstream.HeaderConnection, httpstream.HeaderUpgrade)\n\tw.Header().Add(httpstream.HeaderUpgrade, HeaderSpdy31)\n\tw.WriteHeader(http.StatusSwitchingProtocols)\n\n\tconn, bufrw, err := hijacker.Hijack()\n\tif err != nil {\n\t\truntime.HandleError(fmt.Errorf(\"unable to upgrade: error hijacking response: %v\", err))\n\t\treturn nil\n\t}\n\n\tconnWithBuf := \u0026connWrapper{Conn: conn, bufReader: bufrw.Reader}\n\tspdyConn, err := NewServerConnectionWithPings(connWithBuf, newStreamHandler, u.pingPeriod)\n\tif err != nil {\n\t\truntime.HandleError(fmt.Errorf(\"unable to upgrade: error creating SPDY server connection: %v\", err))\n\t\treturn nil\n\t}\n\n\treturn spdyConn\n}","line":{"from":83,"to":120}} {"id":100015693,"name":"Fuzz","signature":"func (intstr *IntOrString) Fuzz(c fuzz.Continue)","file":"staging/src/k8s.io/apimachinery/pkg/util/intstr/instr_fuzz.go","code":"// Fuzz satisfies fuzz.Interface\nfunc (intstr *IntOrString) Fuzz(c fuzz.Continue) {\n\tif intstr == nil {\n\t\treturn\n\t}\n\tif c.RandBool() {\n\t\tintstr.Type = Int\n\t\tc.Fuzz(\u0026intstr.IntVal)\n\t\tintstr.StrVal = \"\"\n\t} else {\n\t\tintstr.Type = String\n\t\tintstr.IntVal = 0\n\t\tc.Fuzz(\u0026intstr.StrVal)\n\t}\n}","line":{"from":26,"to":40}} {"id":100015694,"name":"FromInt","signature":"func FromInt(val int) IntOrString","file":"staging/src/k8s.io/apimachinery/pkg/util/intstr/intstr.go","code":"// FromInt creates an IntOrString object with an int32 value. It is\n// your responsibility not to call this method with a value greater\n// than int32.\n// TODO: convert to (val int32)\nfunc FromInt(val int) IntOrString {\n\tif val \u003e math.MaxInt32 || val \u003c math.MinInt32 {\n\t\tklog.Errorf(\"value: %d overflows int32\\n%s\\n\", val, debug.Stack())\n\t}\n\treturn IntOrString{Type: Int, IntVal: int32(val)}\n}","line":{"from":54,"to":63}} {"id":100015695,"name":"FromString","signature":"func FromString(val string) IntOrString","file":"staging/src/k8s.io/apimachinery/pkg/util/intstr/intstr.go","code":"// FromString creates an IntOrString object with a string value.\nfunc FromString(val string) IntOrString {\n\treturn IntOrString{Type: String, StrVal: val}\n}","line":{"from":65,"to":68}} {"id":100015696,"name":"Parse","signature":"func Parse(val string) IntOrString","file":"staging/src/k8s.io/apimachinery/pkg/util/intstr/intstr.go","code":"// Parse the given string and try to convert it to an integer before\n// setting it as a string value.\nfunc Parse(val string) IntOrString {\n\ti, err := strconv.Atoi(val)\n\tif err != nil {\n\t\treturn FromString(val)\n\t}\n\treturn FromInt(i)\n}","line":{"from":70,"to":78}} {"id":100015697,"name":"UnmarshalJSON","signature":"func (intstr *IntOrString) UnmarshalJSON(value []byte) error","file":"staging/src/k8s.io/apimachinery/pkg/util/intstr/intstr.go","code":"// UnmarshalJSON implements the json.Unmarshaller interface.\nfunc (intstr *IntOrString) UnmarshalJSON(value []byte) error {\n\tif value[0] == '\"' {\n\t\tintstr.Type = String\n\t\treturn json.Unmarshal(value, \u0026intstr.StrVal)\n\t}\n\tintstr.Type = Int\n\treturn json.Unmarshal(value, \u0026intstr.IntVal)\n}","line":{"from":80,"to":88}} {"id":100015698,"name":"String","signature":"func (intstr *IntOrString) String() string","file":"staging/src/k8s.io/apimachinery/pkg/util/intstr/intstr.go","code":"// String returns the string value, or the Itoa of the int value.\nfunc (intstr *IntOrString) String() string {\n\tif intstr == nil {\n\t\treturn \"\u003cnil\u003e\"\n\t}\n\tif intstr.Type == String {\n\t\treturn intstr.StrVal\n\t}\n\treturn strconv.Itoa(intstr.IntValue())\n}","line":{"from":90,"to":99}} {"id":100015699,"name":"IntValue","signature":"func (intstr *IntOrString) IntValue() int","file":"staging/src/k8s.io/apimachinery/pkg/util/intstr/intstr.go","code":"// IntValue returns the IntVal if type Int, or if\n// it is a String, will attempt a conversion to int,\n// returning 0 if a parsing error occurs.\nfunc (intstr *IntOrString) IntValue() int {\n\tif intstr.Type == String {\n\t\ti, _ := strconv.Atoi(intstr.StrVal)\n\t\treturn i\n\t}\n\treturn int(intstr.IntVal)\n}","line":{"from":101,"to":110}} {"id":100015700,"name":"MarshalJSON","signature":"func (intstr IntOrString) MarshalJSON() ([]byte, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/intstr/intstr.go","code":"// MarshalJSON implements the json.Marshaller interface.\nfunc (intstr IntOrString) MarshalJSON() ([]byte, error) {\n\tswitch intstr.Type {\n\tcase Int:\n\t\treturn json.Marshal(intstr.IntVal)\n\tcase String:\n\t\treturn json.Marshal(intstr.StrVal)\n\tdefault:\n\t\treturn []byte{}, fmt.Errorf(\"impossible IntOrString.Type\")\n\t}\n}","line":{"from":112,"to":122}} {"id":100015701,"name":"OpenAPISchemaType","signature":"func (IntOrString) OpenAPISchemaType() []string { return []string{\"string\"} }","file":"staging/src/k8s.io/apimachinery/pkg/util/intstr/intstr.go","code":"// OpenAPISchemaType is used by the kube-openapi generator when constructing\n// the OpenAPI spec of this type.\n//\n// See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators\nfunc (IntOrString) OpenAPISchemaType() []string { return []string{\"string\"} }","line":{"from":124,"to":128}} {"id":100015702,"name":"OpenAPISchemaFormat","signature":"func (IntOrString) OpenAPISchemaFormat() string { return \"int-or-string\" }","file":"staging/src/k8s.io/apimachinery/pkg/util/intstr/intstr.go","code":"// OpenAPISchemaFormat is used by the kube-openapi generator when constructing\n// the OpenAPI spec of this type.\nfunc (IntOrString) OpenAPISchemaFormat() string { return \"int-or-string\" }","line":{"from":130,"to":132}} {"id":100015703,"name":"OpenAPIV3OneOfTypes","signature":"func (IntOrString) OpenAPIV3OneOfTypes() []string { return []string{\"integer\", \"string\"} }","file":"staging/src/k8s.io/apimachinery/pkg/util/intstr/intstr.go","code":"// OpenAPIV3OneOfTypes is used by the kube-openapi generator when constructing\n// the OpenAPI v3 spec of this type.\nfunc (IntOrString) OpenAPIV3OneOfTypes() []string { return []string{\"integer\", \"string\"} }","line":{"from":134,"to":136}} {"id":100015704,"name":"ValueOrDefault","signature":"func ValueOrDefault(intOrPercent *IntOrString, defaultValue IntOrString) *IntOrString","file":"staging/src/k8s.io/apimachinery/pkg/util/intstr/intstr.go","code":"func ValueOrDefault(intOrPercent *IntOrString, defaultValue IntOrString) *IntOrString {\n\tif intOrPercent == nil {\n\t\treturn \u0026defaultValue\n\t}\n\treturn intOrPercent\n}","line":{"from":138,"to":143}} {"id":100015705,"name":"GetScaledValueFromIntOrPercent","signature":"func GetScaledValueFromIntOrPercent(intOrPercent *IntOrString, total int, roundUp bool) (int, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/intstr/intstr.go","code":"// GetScaledValueFromIntOrPercent is meant to replace GetValueFromIntOrPercent.\n// This method returns a scaled value from an IntOrString type. If the IntOrString\n// is a percentage string value it's treated as a percentage and scaled appropriately\n// in accordance to the total, if it's an int value it's treated as a simple value and\n// if it is a string value which is either non-numeric or numeric but lacking a trailing '%' it returns an error.\nfunc GetScaledValueFromIntOrPercent(intOrPercent *IntOrString, total int, roundUp bool) (int, error) {\n\tif intOrPercent == nil {\n\t\treturn 0, errors.New(\"nil value for IntOrString\")\n\t}\n\tvalue, isPercent, err := getIntOrPercentValueSafely(intOrPercent)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"invalid value for IntOrString: %v\", err)\n\t}\n\tif isPercent {\n\t\tif roundUp {\n\t\t\tvalue = int(math.Ceil(float64(value) * (float64(total)) / 100))\n\t\t} else {\n\t\t\tvalue = int(math.Floor(float64(value) * (float64(total)) / 100))\n\t\t}\n\t}\n\treturn value, nil\n}","line":{"from":145,"to":166}} {"id":100015706,"name":"GetValueFromIntOrPercent","signature":"func GetValueFromIntOrPercent(intOrPercent *IntOrString, total int, roundUp bool) (int, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/intstr/intstr.go","code":"// GetValueFromIntOrPercent was deprecated in favor of\n// GetScaledValueFromIntOrPercent. This method was treating all int as a numeric value and all\n// strings with or without a percent symbol as a percentage value.\n// Deprecated\nfunc GetValueFromIntOrPercent(intOrPercent *IntOrString, total int, roundUp bool) (int, error) {\n\tif intOrPercent == nil {\n\t\treturn 0, errors.New(\"nil value for IntOrString\")\n\t}\n\tvalue, isPercent, err := getIntOrPercentValue(intOrPercent)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"invalid value for IntOrString: %v\", err)\n\t}\n\tif isPercent {\n\t\tif roundUp {\n\t\t\tvalue = int(math.Ceil(float64(value) * (float64(total)) / 100))\n\t\t} else {\n\t\t\tvalue = int(math.Floor(float64(value) * (float64(total)) / 100))\n\t\t}\n\t}\n\treturn value, nil\n}","line":{"from":168,"to":188}} {"id":100015707,"name":"getIntOrPercentValue","signature":"func getIntOrPercentValue(intOrStr *IntOrString) (int, bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/intstr/intstr.go","code":"// getIntOrPercentValue is a legacy function and only meant to be called by GetValueFromIntOrPercent\n// For a more correct implementation call getIntOrPercentSafely\nfunc getIntOrPercentValue(intOrStr *IntOrString) (int, bool, error) {\n\tswitch intOrStr.Type {\n\tcase Int:\n\t\treturn intOrStr.IntValue(), false, nil\n\tcase String:\n\t\ts := strings.Replace(intOrStr.StrVal, \"%\", \"\", -1)\n\t\tv, err := strconv.Atoi(s)\n\t\tif err != nil {\n\t\t\treturn 0, false, fmt.Errorf(\"invalid value %q: %v\", intOrStr.StrVal, err)\n\t\t}\n\t\treturn int(v), true, nil\n\t}\n\treturn 0, false, fmt.Errorf(\"invalid type: neither int nor percentage\")\n}","line":{"from":190,"to":205}} {"id":100015708,"name":"getIntOrPercentValueSafely","signature":"func getIntOrPercentValueSafely(intOrStr *IntOrString) (int, bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/intstr/intstr.go","code":"func getIntOrPercentValueSafely(intOrStr *IntOrString) (int, bool, error) {\n\tswitch intOrStr.Type {\n\tcase Int:\n\t\treturn intOrStr.IntValue(), false, nil\n\tcase String:\n\t\tisPercent := false\n\t\ts := intOrStr.StrVal\n\t\tif strings.HasSuffix(s, \"%\") {\n\t\t\tisPercent = true\n\t\t\ts = strings.TrimSuffix(intOrStr.StrVal, \"%\")\n\t\t} else {\n\t\t\treturn 0, false, fmt.Errorf(\"invalid type: string is not a percentage\")\n\t\t}\n\t\tv, err := strconv.Atoi(s)\n\t\tif err != nil {\n\t\t\treturn 0, false, fmt.Errorf(\"invalid value %q: %v\", intOrStr.StrVal, err)\n\t\t}\n\t\treturn int(v), isPercent, nil\n\t}\n\treturn 0, false, fmt.Errorf(\"invalid type: neither int nor percentage\")\n}","line":{"from":207,"to":227}} {"id":100015709,"name":"NewEncoder","signature":"func NewEncoder(w io.Writer) *json.Encoder","file":"staging/src/k8s.io/apimachinery/pkg/util/json/json.go","code":"// NewEncoder delegates to json.NewEncoder\n// It is only here so this package can be a drop-in for common encoding/json uses\nfunc NewEncoder(w io.Writer) *json.Encoder {\n\treturn json.NewEncoder(w)\n}","line":{"from":27,"to":31}} {"id":100015710,"name":"Marshal","signature":"func Marshal(v interface{}) ([]byte, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/json/json.go","code":"// Marshal delegates to json.Marshal\n// It is only here so this package can be a drop-in for common encoding/json uses\nfunc Marshal(v interface{}) ([]byte, error) {\n\treturn json.Marshal(v)\n}","line":{"from":33,"to":37}} {"id":100015711,"name":"Unmarshal","signature":"func Unmarshal(data []byte, v interface{}) error","file":"staging/src/k8s.io/apimachinery/pkg/util/json/json.go","code":"// Unmarshal unmarshals the given data.\n// Object keys are case-sensitive.\n// Numbers decoded into interface{} fields are converted to int64 or float64.\nfunc Unmarshal(data []byte, v interface{}) error {\n\treturn kjson.UnmarshalCaseSensitivePreserveInts(data, v)\n}","line":{"from":42,"to":47}} {"id":100015712,"name":"ConvertInterfaceNumbers","signature":"func ConvertInterfaceNumbers(v *interface{}, depth int) error","file":"staging/src/k8s.io/apimachinery/pkg/util/json/json.go","code":"// ConvertInterfaceNumbers converts any json.Number values to int64 or float64.\n// Values which are map[string]interface{} or []interface{} are recursively visited\nfunc ConvertInterfaceNumbers(v *interface{}, depth int) error {\n\tvar err error\n\tswitch v2 := (*v).(type) {\n\tcase json.Number:\n\t\t*v, err = convertNumber(v2)\n\tcase map[string]interface{}:\n\t\terr = ConvertMapNumbers(v2, depth+1)\n\tcase []interface{}:\n\t\terr = ConvertSliceNumbers(v2, depth+1)\n\t}\n\treturn err\n}","line":{"from":49,"to":62}} {"id":100015713,"name":"ConvertMapNumbers","signature":"func ConvertMapNumbers(m map[string]interface{}, depth int) error","file":"staging/src/k8s.io/apimachinery/pkg/util/json/json.go","code":"// ConvertMapNumbers traverses the map, converting any json.Number values to int64 or float64.\n// values which are map[string]interface{} or []interface{} are recursively visited\nfunc ConvertMapNumbers(m map[string]interface{}, depth int) error {\n\tif depth \u003e maxDepth {\n\t\treturn fmt.Errorf(\"exceeded max depth of %d\", maxDepth)\n\t}\n\n\tvar err error\n\tfor k, v := range m {\n\t\tswitch v := v.(type) {\n\t\tcase json.Number:\n\t\t\tm[k], err = convertNumber(v)\n\t\tcase map[string]interface{}:\n\t\t\terr = ConvertMapNumbers(v, depth+1)\n\t\tcase []interface{}:\n\t\t\terr = ConvertSliceNumbers(v, depth+1)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":64,"to":86}} {"id":100015714,"name":"ConvertSliceNumbers","signature":"func ConvertSliceNumbers(s []interface{}, depth int) error","file":"staging/src/k8s.io/apimachinery/pkg/util/json/json.go","code":"// ConvertSliceNumbers traverses the slice, converting any json.Number values to int64 or float64.\n// values which are map[string]interface{} or []interface{} are recursively visited\nfunc ConvertSliceNumbers(s []interface{}, depth int) error {\n\tif depth \u003e maxDepth {\n\t\treturn fmt.Errorf(\"exceeded max depth of %d\", maxDepth)\n\t}\n\n\tvar err error\n\tfor i, v := range s {\n\t\tswitch v := v.(type) {\n\t\tcase json.Number:\n\t\t\ts[i], err = convertNumber(v)\n\t\tcase map[string]interface{}:\n\t\t\terr = ConvertMapNumbers(v, depth+1)\n\t\tcase []interface{}:\n\t\t\terr = ConvertSliceNumbers(v, depth+1)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":88,"to":110}} {"id":100015715,"name":"convertNumber","signature":"func convertNumber(n json.Number) (interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/json/json.go","code":"// convertNumber converts a json.Number to an int64 or float64, or returns an error\nfunc convertNumber(n json.Number) (interface{}, error) {\n\t// Attempt to convert to an int64 first\n\tif i, err := n.Int64(); err == nil {\n\t\treturn i, nil\n\t}\n\t// Return a float64 (default json.Decode() behavior)\n\t// An overflow will return an error\n\treturn n.Float64()\n}","line":{"from":112,"to":121}} {"id":100015716,"name":"CreateThreeWayJSONMergePatch","signature":"func CreateThreeWayJSONMergePatch(original, modified, current []byte, fns ...mergepatch.PreconditionFunc) ([]byte, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/jsonmergepatch/patch.go","code":"// Create a 3-way merge patch based-on JSON merge patch.\n// Calculate addition-and-change patch between current and modified.\n// Calculate deletion patch between original and modified.\nfunc CreateThreeWayJSONMergePatch(original, modified, current []byte, fns ...mergepatch.PreconditionFunc) ([]byte, error) {\n\tif len(original) == 0 {\n\t\toriginal = []byte(`{}`)\n\t}\n\tif len(modified) == 0 {\n\t\tmodified = []byte(`{}`)\n\t}\n\tif len(current) == 0 {\n\t\tcurrent = []byte(`{}`)\n\t}\n\n\taddAndChangePatch, err := jsonpatch.CreateMergePatch(current, modified)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Only keep addition and changes\n\taddAndChangePatch, addAndChangePatchObj, err := keepOrDeleteNullInJsonPatch(addAndChangePatch, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdeletePatch, err := jsonpatch.CreateMergePatch(original, modified)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Only keep deletion\n\tdeletePatch, deletePatchObj, err := keepOrDeleteNullInJsonPatch(deletePatch, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thasConflicts, err := mergepatch.HasConflicts(addAndChangePatchObj, deletePatchObj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif hasConflicts {\n\t\treturn nil, mergepatch.NewErrConflict(mergepatch.ToYAMLOrError(addAndChangePatchObj), mergepatch.ToYAMLOrError(deletePatchObj))\n\t}\n\tpatch, err := jsonpatch.MergePatch(deletePatch, addAndChangePatch)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar patchMap map[string]interface{}\n\terr = json.Unmarshal(patch, \u0026patchMap)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal patch for precondition check: %s\", patch)\n\t}\n\tmeetPreconditions, err := meetPreconditions(patchMap, fns...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !meetPreconditions {\n\t\treturn nil, mergepatch.NewErrPreconditionFailed(patchMap)\n\t}\n\n\treturn patch, nil\n}","line":{"from":28,"to":88}} {"id":100015717,"name":"keepOrDeleteNullInJsonPatch","signature":"func keepOrDeleteNullInJsonPatch(patch []byte, keepNull bool) ([]byte, map[string]interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/jsonmergepatch/patch.go","code":"// keepOrDeleteNullInJsonPatch takes a json-encoded byte array and a boolean.\n// It returns a filtered object and its corresponding json-encoded byte array.\n// It is a wrapper of func keepOrDeleteNullInObj\nfunc keepOrDeleteNullInJsonPatch(patch []byte, keepNull bool) ([]byte, map[string]interface{}, error) {\n\tvar patchMap map[string]interface{}\n\terr := json.Unmarshal(patch, \u0026patchMap)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tfilteredMap, err := keepOrDeleteNullInObj(patchMap, keepNull)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\to, err := json.Marshal(filteredMap)\n\treturn o, filteredMap, err\n}","line":{"from":90,"to":105}} {"id":100015718,"name":"keepOrDeleteNullInObj","signature":"func keepOrDeleteNullInObj(m map[string]interface{}, keepNull bool) (map[string]interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/jsonmergepatch/patch.go","code":"// keepOrDeleteNullInObj will keep only the null value and delete all the others,\n// if keepNull is true. Otherwise, it will delete all the null value and keep the others.\nfunc keepOrDeleteNullInObj(m map[string]interface{}, keepNull bool) (map[string]interface{}, error) {\n\tfilteredMap := make(map[string]interface{})\n\tvar err error\n\tfor key, val := range m {\n\t\tswitch {\n\t\tcase keepNull \u0026\u0026 val == nil:\n\t\t\tfilteredMap[key] = nil\n\t\tcase val != nil:\n\t\t\tswitch typedVal := val.(type) {\n\t\t\tcase map[string]interface{}:\n\t\t\t\t// Explicitly-set empty maps are treated as values instead of empty patches\n\t\t\t\tif len(typedVal) == 0 {\n\t\t\t\t\tif !keepNull {\n\t\t\t\t\t\tfilteredMap[key] = typedVal\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tvar filteredSubMap map[string]interface{}\n\t\t\t\tfilteredSubMap, err = keepOrDeleteNullInObj(typedVal, keepNull)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\t// If the returned filtered submap was empty, this is an empty patch for the entire subdict, so the key\n\t\t\t\t// should not be set\n\t\t\t\tif len(filteredSubMap) != 0 {\n\t\t\t\t\tfilteredMap[key] = filteredSubMap\n\t\t\t\t}\n\n\t\t\tcase []interface{}, string, float64, bool, int64, nil:\n\t\t\t\t// Lists are always replaced in Json, no need to check each entry in the list.\n\t\t\t\tif !keepNull {\n\t\t\t\t\tfilteredMap[key] = val\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn nil, fmt.Errorf(\"unknown type: %v\", reflect.TypeOf(typedVal))\n\t\t\t}\n\t\t}\n\t}\n\treturn filteredMap, nil\n}","line":{"from":107,"to":150}} {"id":100015719,"name":"meetPreconditions","signature":"func meetPreconditions(patchObj map[string]interface{}, fns ...mergepatch.PreconditionFunc) (bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/jsonmergepatch/patch.go","code":"func meetPreconditions(patchObj map[string]interface{}, fns ...mergepatch.PreconditionFunc) (bool, error) {\n\t// Apply the preconditions to the patch, and return an error if any of them fail.\n\tfor _, fn := range fns {\n\t\tif !fn(patchObj) {\n\t\t\treturn false, fmt.Errorf(\"precondition failed for: %v\", patchObj)\n\t\t}\n\t}\n\treturn true, nil\n}","line":{"from":152,"to":160}} {"id":100015720,"name":"ExtractInto","signature":"func ExtractInto(object runtime.Object, objectType typed.ParseableType, fieldManager string, applyConfiguration interface{}, subresource string) error","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/extract.go","code":"// ExtractInto extracts the applied configuration state from object for fieldManager\n// into applyConfiguration. If no managed fields are found for the given fieldManager,\n// no error is returned, but applyConfiguration is left unpopulated. It is possible\n// that no managed fields were found for the fieldManager because other field managers\n// have taken ownership of all the fields previously owned by the fieldManager. It is\n// also possible the fieldManager never owned fields.\n//\n// The provided object MUST bo a root resource object since subresource objects\n// do not contain their own managed fields. For example, an autoscaling.Scale\n// object read from a \"scale\" subresource does not have any managed fields and so\n// cannot be used as the object.\n//\n// If the fields of a subresource are a subset of the fields of the root object,\n// and their field paths and types are exactly the same, then ExtractInto can be\n// called with the root resource as the object and the subresource as the\n// applyConfiguration. This works for \"status\", obviously, because status is\n// represented by the exact same object as the root resource. This does NOT\n// work, for example, with the \"scale\" subresources of Deployment, ReplicaSet and\n// StatefulSet. While the spec.replicas, status.replicas fields are in the same\n// exact field path locations as they are in autoscaling.Scale, the selector\n// fields are in different locations, and are a different type.\nfunc ExtractInto(object runtime.Object, objectType typed.ParseableType, fieldManager string, applyConfiguration interface{}, subresource string) error {\n\ttypedObj, err := toTyped(object, objectType)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error converting obj to typed: %w\", err)\n\t}\n\n\taccessor, err := meta.Accessor(object)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error accessing metadata: %w\", err)\n\t}\n\tfieldsEntry, ok := findManagedFields(accessor, fieldManager, subresource)\n\tif !ok {\n\t\treturn nil\n\t}\n\tfieldset := \u0026fieldpath.Set{}\n\terr = fieldset.FromJSON(bytes.NewReader(fieldsEntry.FieldsV1.Raw))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error marshalling FieldsV1 to JSON: %w\", err)\n\t}\n\n\tu := typedObj.ExtractItems(fieldset.Leaves()).AsValue().Unstructured()\n\tm, ok := u.(map[string]interface{})\n\tif !ok {\n\t\treturn fmt.Errorf(\"unable to convert managed fields for %s to unstructured, expected map, got %T\", fieldManager, u)\n\t}\n\n\t// set the type meta manually if it doesn't exist to avoid missing kind errors\n\t// when decoding from unstructured JSON\n\tif _, ok := m[\"kind\"]; !ok \u0026\u0026 object.GetObjectKind().GroupVersionKind().Kind != \"\" {\n\t\tm[\"kind\"] = object.GetObjectKind().GroupVersionKind().Kind\n\t\tm[\"apiVersion\"] = object.GetObjectKind().GroupVersionKind().GroupVersion().String()\n\t}\n\tif err := runtime.DefaultUnstructuredConverter.FromUnstructured(m, applyConfiguration); err != nil {\n\t\treturn fmt.Errorf(\"error extracting into obj from unstructured: %w\", err)\n\t}\n\treturn nil\n}","line":{"from":32,"to":89}} {"id":100015721,"name":"findManagedFields","signature":"func findManagedFields(accessor metav1.Object, fieldManager string, subresource string) (metav1.ManagedFieldsEntry, bool)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/extract.go","code":"func findManagedFields(accessor metav1.Object, fieldManager string, subresource string) (metav1.ManagedFieldsEntry, bool) {\n\tobjManagedFields := accessor.GetManagedFields()\n\tfor _, mf := range objManagedFields {\n\t\tif mf.Manager == fieldManager \u0026\u0026 mf.Operation == metav1.ManagedFieldsOperationApply \u0026\u0026 mf.Subresource == subresource {\n\t\t\treturn mf, true\n\t\t}\n\t}\n\treturn metav1.ManagedFieldsEntry{}, false\n}","line":{"from":91,"to":99}} {"id":100015722,"name":"toTyped","signature":"func toTyped(obj runtime.Object, objectType typed.ParseableType) (*typed.TypedValue, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/extract.go","code":"func toTyped(obj runtime.Object, objectType typed.ParseableType) (*typed.TypedValue, error) {\n\tswitch o := obj.(type) {\n\tcase *unstructured.Unstructured:\n\t\treturn objectType.FromUnstructured(o.Object)\n\tdefault:\n\t\treturn objectType.FromStructured(o)\n\t}\n}","line":{"from":101,"to":108}} {"id":100015723,"name":"NewDefaultFieldManager","signature":"func NewDefaultFieldManager(typeConverter TypeConverter, objectConverter runtime.ObjectConvertor, objectDefaulter runtime.ObjectDefaulter, objectCreater runtime.ObjectCreater, kind schema.GroupVersionKind, hub schema.GroupVersion, subresource string, resetFields map[fieldpath.APIVersion]*fieldpath.Set) (*FieldManager, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/fieldmanager.go","code":"// NewDefaultFieldManager creates a new FieldManager that merges apply requests\n// and update managed fields for other types of requests.\nfunc NewDefaultFieldManager(typeConverter TypeConverter, objectConverter runtime.ObjectConvertor, objectDefaulter runtime.ObjectDefaulter, objectCreater runtime.ObjectCreater, kind schema.GroupVersionKind, hub schema.GroupVersion, subresource string, resetFields map[fieldpath.APIVersion]*fieldpath.Set) (*FieldManager, error) {\n\tf, err := internal.NewStructuredMergeManager(typeConverter, objectConverter, objectDefaulter, kind.GroupVersion(), hub, resetFields)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create field manager: %v\", err)\n\t}\n\treturn internal.NewDefaultFieldManager(f, typeConverter, objectConverter, objectCreater, kind, subresource), nil\n}","line":{"from":33,"to":41}} {"id":100015724,"name":"NewDefaultCRDFieldManager","signature":"func NewDefaultCRDFieldManager(typeConverter TypeConverter, objectConverter runtime.ObjectConvertor, objectDefaulter runtime.ObjectDefaulter, objectCreater runtime.ObjectCreater, kind schema.GroupVersionKind, hub schema.GroupVersion, subresource string, resetFields map[fieldpath.APIVersion]*fieldpath.Set) (_ *FieldManager, err error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/fieldmanager.go","code":"// NewDefaultCRDFieldManager creates a new FieldManager specifically for\n// CRDs. This allows for the possibility of fields which are not defined\n// in models, as well as having no models defined at all.\nfunc NewDefaultCRDFieldManager(typeConverter TypeConverter, objectConverter runtime.ObjectConvertor, objectDefaulter runtime.ObjectDefaulter, objectCreater runtime.ObjectCreater, kind schema.GroupVersionKind, hub schema.GroupVersion, subresource string, resetFields map[fieldpath.APIVersion]*fieldpath.Set) (_ *FieldManager, err error) {\n\tf, err := internal.NewCRDStructuredMergeManager(typeConverter, objectConverter, objectDefaulter, kind.GroupVersion(), hub, resetFields)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create field manager: %v\", err)\n\t}\n\treturn internal.NewDefaultFieldManager(f, typeConverter, objectConverter, objectCreater, kind, subresource), nil\n}","line":{"from":43,"to":52}} {"id":100015725,"name":"ValidateManagedFields","signature":"func ValidateManagedFields(encodedManagedFields []metav1.ManagedFieldsEntry) error","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/fieldmanager.go","code":"func ValidateManagedFields(encodedManagedFields []metav1.ManagedFieldsEntry) error {\n\t_, err := internal.DecodeManagedFields(encodedManagedFields)\n\treturn err\n}","line":{"from":54,"to":57}} {"id":100015726,"name":"Type","signature":"func (p *GvkParser) Type(gvk schema.GroupVersionKind) *typed.ParseableType","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/gvkparser.go","code":"// Type returns a helper which can produce objects of the given type. Any\n// errors are deferred until a further function is called.\nfunc (p *GvkParser) Type(gvk schema.GroupVersionKind) *typed.ParseableType {\n\ttypeName, ok := p.gvks[gvk]\n\tif !ok {\n\t\treturn nil\n\t}\n\tt := p.parser.Type(typeName)\n\treturn \u0026t\n}","line":{"from":40,"to":49}} {"id":100015727,"name":"NewGVKParser","signature":"func NewGVKParser(models proto.Models, preserveUnknownFields bool) (*GvkParser, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/gvkparser.go","code":"// NewGVKParser builds a GVKParser from a proto.Models. This\n// will automatically find the proper version of the object, and the\n// corresponding schema information.\nfunc NewGVKParser(models proto.Models, preserveUnknownFields bool) (*GvkParser, error) {\n\ttypeSchema, err := schemaconv.ToSchemaWithPreserveUnknownFields(models, preserveUnknownFields)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to convert models to schema: %v\", err)\n\t}\n\tparser := GvkParser{\n\t\tgvks: map[schema.GroupVersionKind]string{},\n\t}\n\tparser.parser = typed.Parser{Schema: smdschema.Schema{Types: typeSchema.Types}}\n\tfor _, modelName := range models.ListModels() {\n\t\tmodel := models.LookupModel(modelName)\n\t\tif model == nil {\n\t\t\tpanic(fmt.Sprintf(\"ListModels returns a model that can't be looked-up for: %v\", modelName))\n\t\t}\n\t\tgvkList := parseGroupVersionKind(model)\n\t\tfor _, gvk := range gvkList {\n\t\t\tif len(gvk.Kind) \u003e 0 {\n\t\t\t\t_, ok := parser.gvks[gvk]\n\t\t\t\tif ok {\n\t\t\t\t\treturn nil, fmt.Errorf(\"duplicate entry for %v\", gvk)\n\t\t\t\t}\n\t\t\t\tparser.gvks[gvk] = modelName\n\t\t\t}\n\t\t}\n\t}\n\treturn \u0026parser, nil\n}","line":{"from":51,"to":80}} {"id":100015728,"name":"parseGroupVersionKind","signature":"func parseGroupVersionKind(s proto.Schema) []schema.GroupVersionKind","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/gvkparser.go","code":"// Get and parse GroupVersionKind from the extension. Returns empty if it doesn't have one.\nfunc parseGroupVersionKind(s proto.Schema) []schema.GroupVersionKind {\n\textensions := s.GetExtensions()\n\n\tgvkListResult := []schema.GroupVersionKind{}\n\n\t// Get the extensions\n\tgvkExtension, ok := extensions[groupVersionKindExtensionKey]\n\tif !ok {\n\t\treturn []schema.GroupVersionKind{}\n\t}\n\n\t// gvk extension must be a list of at least 1 element.\n\tgvkList, ok := gvkExtension.([]interface{})\n\tif !ok {\n\t\treturn []schema.GroupVersionKind{}\n\t}\n\n\tfor _, gvk := range gvkList {\n\t\t// gvk extension list must be a map with group, version, and\n\t\t// kind fields\n\t\tgvkMap, ok := gvk.(map[interface{}]interface{})\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tgroup, ok := gvkMap[\"group\"].(string)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tversion, ok := gvkMap[\"version\"].(string)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tkind, ok := gvkMap[\"kind\"].(string)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tgvkListResult = append(gvkListResult, schema.GroupVersionKind{\n\t\t\tGroup: group,\n\t\t\tVersion: version,\n\t\t\tKind: kind,\n\t\t})\n\t}\n\n\treturn gvkListResult\n}","line":{"from":82,"to":128}} {"id":100015729,"name":"NewAtMostEvery","signature":"func NewAtMostEvery(delay time.Duration) *AtMostEvery","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/atmostevery.go","code":"// NewAtMostEvery creates a new AtMostEvery, that will run the method at\n// most every given duration.\nfunc NewAtMostEvery(delay time.Duration) *AtMostEvery {\n\treturn \u0026AtMostEvery{\n\t\tdelay: delay,\n\t}\n}","line":{"from":32,"to":38}} {"id":100015730,"name":"updateLastCall","signature":"func (s *AtMostEvery) updateLastCall() bool","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/atmostevery.go","code":"// updateLastCall returns true if the lastCall time has been updated,\n// false if it was too early.\nfunc (s *AtMostEvery) updateLastCall() bool {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\tif time.Since(s.lastCall) \u003c s.delay {\n\t\treturn false\n\t}\n\ts.lastCall = time.Now()\n\treturn true\n}","line":{"from":40,"to":50}} {"id":100015731,"name":"Do","signature":"func (s *AtMostEvery) Do(fn func()) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/atmostevery.go","code":"// Do will run the method if enough time has passed, and return true.\n// Otherwise, it does nothing and returns false.\nfunc (s *AtMostEvery) Do(fn func()) bool {\n\tif !s.updateLastCall() {\n\t\treturn false\n\t}\n\tfn()\n\treturn true\n}","line":{"from":52,"to":60}} {"id":100015732,"name":"NewBuildManagerInfoManager","signature":"func NewBuildManagerInfoManager(f Manager, gv schema.GroupVersion, subresource string) Manager","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/buildmanagerinfo.go","code":"// NewBuildManagerInfoManager creates a new Manager that converts the manager name into a unique identifier\n// combining operation and version for update requests, and just operation for apply requests.\nfunc NewBuildManagerInfoManager(f Manager, gv schema.GroupVersion, subresource string) Manager {\n\treturn \u0026buildManagerInfoManager{\n\t\tfieldManager: f,\n\t\tgroupVersion: gv,\n\t\tsubresource: subresource,\n\t}\n}","line":{"from":35,"to":43}} {"id":100015733,"name":"Update","signature":"func (f *buildManagerInfoManager) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/buildmanagerinfo.go","code":"// Update implements Manager.\nfunc (f *buildManagerInfoManager) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) {\n\tmanager, err := f.buildManagerInfo(manager, metav1.ManagedFieldsOperationUpdate)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to build manager identifier: %v\", err)\n\t}\n\treturn f.fieldManager.Update(liveObj, newObj, managed, manager)\n}","line":{"from":45,"to":52}} {"id":100015734,"name":"Apply","signature":"func (f *buildManagerInfoManager) Apply(liveObj, appliedObj runtime.Object, managed Managed, manager string, force bool) (runtime.Object, Managed, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/buildmanagerinfo.go","code":"// Apply implements Manager.\nfunc (f *buildManagerInfoManager) Apply(liveObj, appliedObj runtime.Object, managed Managed, manager string, force bool) (runtime.Object, Managed, error) {\n\tmanager, err := f.buildManagerInfo(manager, metav1.ManagedFieldsOperationApply)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to build manager identifier: %v\", err)\n\t}\n\treturn f.fieldManager.Apply(liveObj, appliedObj, managed, manager, force)\n}","line":{"from":54,"to":61}} {"id":100015735,"name":"buildManagerInfo","signature":"func (f *buildManagerInfoManager) buildManagerInfo(prefix string, operation metav1.ManagedFieldsOperationType) (string, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/buildmanagerinfo.go","code":"func (f *buildManagerInfoManager) buildManagerInfo(prefix string, operation metav1.ManagedFieldsOperationType) (string, error) {\n\tmanagerInfo := metav1.ManagedFieldsEntry{\n\t\tManager: prefix,\n\t\tOperation: operation,\n\t\tAPIVersion: f.groupVersion.String(),\n\t\tSubresource: f.subresource,\n\t}\n\tif managerInfo.Manager == \"\" {\n\t\tmanagerInfo.Manager = \"unknown\"\n\t}\n\treturn BuildManagerIdentifier(\u0026managerInfo)\n}","line":{"from":63,"to":74}} {"id":100015736,"name":"NewCapManagersManager","signature":"func NewCapManagersManager(fieldManager Manager, maxUpdateManagers int) Manager","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/capmanagers.go","code":"// NewCapManagersManager creates a new wrapped FieldManager which ensures that the number of managers from updates\n// does not exceed maxUpdateManagers, by merging some of the oldest entries on each update.\nfunc NewCapManagersManager(fieldManager Manager, maxUpdateManagers int) Manager {\n\treturn \u0026capManagersManager{\n\t\tfieldManager: fieldManager,\n\t\tmaxUpdateManagers: maxUpdateManagers,\n\t\toldUpdatesManagerName: \"ancient-changes\",\n\t}\n}","line":{"from":36,"to":44}} {"id":100015737,"name":"Update","signature":"func (f *capManagersManager) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/capmanagers.go","code":"// Update implements Manager.\nfunc (f *capManagersManager) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) {\n\tobject, managed, err := f.fieldManager.Update(liveObj, newObj, managed, manager)\n\tif err != nil {\n\t\treturn object, managed, err\n\t}\n\tif managed, err = f.capUpdateManagers(managed); err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to cap update managers: %v\", err)\n\t}\n\treturn object, managed, nil\n}","line":{"from":46,"to":56}} {"id":100015738,"name":"Apply","signature":"func (f *capManagersManager) Apply(liveObj, appliedObj runtime.Object, managed Managed, fieldManager string, force bool) (runtime.Object, Managed, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/capmanagers.go","code":"// Apply implements Manager.\nfunc (f *capManagersManager) Apply(liveObj, appliedObj runtime.Object, managed Managed, fieldManager string, force bool) (runtime.Object, Managed, error) {\n\treturn f.fieldManager.Apply(liveObj, appliedObj, managed, fieldManager, force)\n}","line":{"from":58,"to":61}} {"id":100015739,"name":"capUpdateManagers","signature":"func (f *capManagersManager) capUpdateManagers(managed Managed) (newManaged Managed, err error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/capmanagers.go","code":"// capUpdateManagers merges a number of the oldest update entries into versioned buckets,\n// such that the number of entries from updates does not exceed f.maxUpdateManagers.\nfunc (f *capManagersManager) capUpdateManagers(managed Managed) (newManaged Managed, err error) {\n\t// Gather all entries from updates\n\tupdaters := []string{}\n\tfor manager, fields := range managed.Fields() {\n\t\tif !fields.Applied() {\n\t\t\tupdaters = append(updaters, manager)\n\t\t}\n\t}\n\tif len(updaters) \u003c= f.maxUpdateManagers {\n\t\treturn managed, nil\n\t}\n\n\t// If we have more than the maximum, sort the update entries by time, oldest first.\n\tsort.Slice(updaters, func(i, j int) bool {\n\t\tiTime, jTime, iSeconds, jSeconds := managed.Times()[updaters[i]], managed.Times()[updaters[j]], int64(0), int64(0)\n\t\tif iTime != nil {\n\t\t\tiSeconds = iTime.Unix()\n\t\t}\n\t\tif jTime != nil {\n\t\t\tjSeconds = jTime.Unix()\n\t\t}\n\t\tif iSeconds != jSeconds {\n\t\t\treturn iSeconds \u003c jSeconds\n\t\t}\n\t\treturn updaters[i] \u003c updaters[j]\n\t})\n\n\t// Merge the oldest updaters with versioned bucket managers until the number of updaters is under the cap\n\tversionToFirstManager := map[string]string{}\n\tfor i, length := 0, len(updaters); i \u003c len(updaters) \u0026\u0026 length \u003e f.maxUpdateManagers; i++ {\n\t\tmanager := updaters[i]\n\t\tvs := managed.Fields()[manager]\n\t\ttime := managed.Times()[manager]\n\t\tversion := string(vs.APIVersion())\n\n\t\t// Create a new manager identifier for the versioned bucket entry.\n\t\t// The version for this manager comes from the version of the update being merged into the bucket.\n\t\tbucket, err := BuildManagerIdentifier(\u0026metav1.ManagedFieldsEntry{\n\t\t\tManager: f.oldUpdatesManagerName,\n\t\t\tOperation: metav1.ManagedFieldsOperationUpdate,\n\t\t\tAPIVersion: version,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn managed, fmt.Errorf(\"failed to create bucket manager for version %v: %v\", version, err)\n\t\t}\n\n\t\t// Merge the fieldets if this is not the first time the version was seen.\n\t\t// Otherwise just record the manager name in versionToFirstManager\n\t\tif first, ok := versionToFirstManager[version]; ok {\n\t\t\t// If the bucket doesn't exists yet, create one.\n\t\t\tif _, ok := managed.Fields()[bucket]; !ok {\n\t\t\t\ts := managed.Fields()[first]\n\t\t\t\tdelete(managed.Fields(), first)\n\t\t\t\tmanaged.Fields()[bucket] = s\n\t\t\t}\n\n\t\t\tmanaged.Fields()[bucket] = fieldpath.NewVersionedSet(vs.Set().Union(managed.Fields()[bucket].Set()), vs.APIVersion(), vs.Applied())\n\t\t\tdelete(managed.Fields(), manager)\n\t\t\tlength--\n\n\t\t\t// Use the time from the update being merged into the bucket, since it is more recent.\n\t\t\tmanaged.Times()[bucket] = time\n\t\t} else {\n\t\t\tversionToFirstManager[version] = manager\n\t\t}\n\t}\n\n\treturn managed, nil\n}","line":{"from":63,"to":133}} {"id":100015740,"name":"NewConflictError","signature":"func NewConflictError(conflicts merge.Conflicts) *errors.StatusError","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/conflict.go","code":"// NewConflictError returns an error including details on the requests apply conflicts\nfunc NewConflictError(conflicts merge.Conflicts) *errors.StatusError {\n\tcauses := []metav1.StatusCause{}\n\tfor _, conflict := range conflicts {\n\t\tcauses = append(causes, metav1.StatusCause{\n\t\t\tType: metav1.CauseTypeFieldManagerConflict,\n\t\t\tMessage: fmt.Sprintf(\"conflict with %v\", printManager(conflict.Manager)),\n\t\t\tField: conflict.Path.String(),\n\t\t})\n\t}\n\treturn errors.NewApplyConflict(causes, getConflictMessage(conflicts))\n}","line":{"from":32,"to":43}} {"id":100015741,"name":"getConflictMessage","signature":"func getConflictMessage(conflicts merge.Conflicts) string","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/conflict.go","code":"func getConflictMessage(conflicts merge.Conflicts) string {\n\tif len(conflicts) == 1 {\n\t\treturn fmt.Sprintf(\"Apply failed with 1 conflict: conflict with %v: %v\", printManager(conflicts[0].Manager), conflicts[0].Path)\n\t}\n\n\tm := map[string][]fieldpath.Path{}\n\tfor _, conflict := range conflicts {\n\t\tm[conflict.Manager] = append(m[conflict.Manager], conflict.Path)\n\t}\n\n\tuniqueManagers := []string{}\n\tfor manager := range m {\n\t\tuniqueManagers = append(uniqueManagers, manager)\n\t}\n\n\t// Print conflicts by sorted managers.\n\tsort.Strings(uniqueManagers)\n\n\tmessages := []string{}\n\tfor _, manager := range uniqueManagers {\n\t\tmessages = append(messages, fmt.Sprintf(\"conflicts with %v:\", printManager(manager)))\n\t\tfor _, path := range m[manager] {\n\t\t\tmessages = append(messages, fmt.Sprintf(\"- %v\", path))\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"Apply failed with %d conflicts: %s\", len(conflicts), strings.Join(messages, \"\\n\"))\n}","line":{"from":45,"to":71}} {"id":100015742,"name":"printManager","signature":"func printManager(manager string) string","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/conflict.go","code":"func printManager(manager string) string {\n\tencodedManager := \u0026metav1.ManagedFieldsEntry{}\n\tif err := json.Unmarshal([]byte(manager), encodedManager); err != nil {\n\t\treturn fmt.Sprintf(\"%q\", manager)\n\t}\n\tmanagerStr := fmt.Sprintf(\"%q\", encodedManager.Manager)\n\tif encodedManager.Subresource != \"\" {\n\t\tmanagerStr = fmt.Sprintf(\"%s with subresource %q\", managerStr, encodedManager.Subresource)\n\t}\n\tif encodedManager.Operation == metav1.ManagedFieldsOperationUpdate {\n\t\tif encodedManager.Time == nil {\n\t\t\treturn fmt.Sprintf(\"%s using %v\", managerStr, encodedManager.APIVersion)\n\t\t}\n\t\treturn fmt.Sprintf(\"%s using %v at %v\", managerStr, encodedManager.APIVersion, encodedManager.Time.UTC().Format(time.RFC3339))\n\t}\n\treturn managerStr\n}","line":{"from":73,"to":89}} {"id":100015743,"name":"NewFieldManager","signature":"func NewFieldManager(f Manager, subresource string) *FieldManager","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/fieldmanager.go","code":"// NewFieldManager creates a new FieldManager that decodes, manages, then re-encodes managedFields\n// on update and apply requests.\nfunc NewFieldManager(f Manager, subresource string) *FieldManager {\n\treturn \u0026FieldManager{fieldManager: f, subresource: subresource}\n}","line":{"from":50,"to":54}} {"id":100015744,"name":"NewDefaultFieldManager","signature":"func NewDefaultFieldManager(f Manager, typeConverter TypeConverter, objectConverter runtime.ObjectConvertor, objectCreater runtime.ObjectCreater, kind schema.GroupVersionKind, subresource string) *FieldManager","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/fieldmanager.go","code":"// newDefaultFieldManager is a helper function which wraps a Manager with certain default logic.\nfunc NewDefaultFieldManager(f Manager, typeConverter TypeConverter, objectConverter runtime.ObjectConvertor, objectCreater runtime.ObjectCreater, kind schema.GroupVersionKind, subresource string) *FieldManager {\n\treturn NewFieldManager(\n\t\tNewLastAppliedUpdater(\n\t\t\tNewLastAppliedManager(\n\t\t\t\tNewProbabilisticSkipNonAppliedManager(\n\t\t\t\t\tNewCapManagersManager(\n\t\t\t\t\t\tNewBuildManagerInfoManager(\n\t\t\t\t\t\t\tNewManagedFieldsUpdater(\n\t\t\t\t\t\t\t\tNewStripMetaManager(f),\n\t\t\t\t\t\t\t), kind.GroupVersion(), subresource,\n\t\t\t\t\t\t), DefaultMaxUpdateManagers,\n\t\t\t\t\t), objectCreater, kind, DefaultTrackOnCreateProbability,\n\t\t\t\t), typeConverter, objectConverter, kind.GroupVersion()),\n\t\t), subresource,\n\t)\n}","line":{"from":56,"to":72}} {"id":100015745,"name":"decodeLiveOrNew","signature":"func decodeLiveOrNew(liveObj, newObj runtime.Object, ignoreManagedFieldsFromRequestObject bool) (Managed, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/fieldmanager.go","code":"func decodeLiveOrNew(liveObj, newObj runtime.Object, ignoreManagedFieldsFromRequestObject bool) (Managed, error) {\n\tliveAccessor, err := meta.Accessor(liveObj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// We take the managedFields of the live object in case the request tries to\n\t// manually set managedFields via a subresource.\n\tif ignoreManagedFieldsFromRequestObject {\n\t\treturn emptyManagedFieldsOnErr(DecodeManagedFields(liveAccessor.GetManagedFields()))\n\t}\n\n\t// If the object doesn't have metadata, we should just return without trying to\n\t// set the managedFields at all, so creates/updates/patches will work normally.\n\tnewAccessor, err := meta.Accessor(newObj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif isResetManagedFields(newAccessor.GetManagedFields()) {\n\t\treturn NewEmptyManaged(), nil\n\t}\n\n\t// If the managed field is empty or we failed to decode it,\n\t// let's try the live object. This is to prevent clients who\n\t// don't understand managedFields from deleting it accidentally.\n\tmanaged, err := DecodeManagedFields(newAccessor.GetManagedFields())\n\tif err != nil || len(managed.Fields()) == 0 {\n\t\treturn emptyManagedFieldsOnErr(DecodeManagedFields(liveAccessor.GetManagedFields()))\n\t}\n\treturn managed, nil\n}","line":{"from":74,"to":105}} {"id":100015746,"name":"emptyManagedFieldsOnErr","signature":"func emptyManagedFieldsOnErr(managed Managed, err error) (Managed, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/fieldmanager.go","code":"func emptyManagedFieldsOnErr(managed Managed, err error) (Managed, error) {\n\tif err != nil {\n\t\treturn NewEmptyManaged(), nil\n\t}\n\treturn managed, nil\n}","line":{"from":107,"to":112}} {"id":100015747,"name":"Update","signature":"func (f *FieldManager) Update(liveObj, newObj runtime.Object, manager string) (object runtime.Object, err error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/fieldmanager.go","code":"// Update is used when the object has already been merged (non-apply\n// use-case), and simply updates the managed fields in the output\n// object.\nfunc (f *FieldManager) Update(liveObj, newObj runtime.Object, manager string) (object runtime.Object, err error) {\n\t// First try to decode the managed fields provided in the update,\n\t// This is necessary to allow directly updating managed fields.\n\tisSubresource := f.subresource != \"\"\n\tmanaged, err := decodeLiveOrNew(liveObj, newObj, isSubresource)\n\tif err != nil {\n\t\treturn newObj, nil\n\t}\n\n\tRemoveObjectManagedFields(newObj)\n\n\tif object, managed, err = f.fieldManager.Update(liveObj, newObj, managed, manager); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = EncodeObjectManagedFields(object, managed); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to encode managed fields: %v\", err)\n\t}\n\n\treturn object, nil\n}","line":{"from":114,"to":137}} {"id":100015748,"name":"UpdateNoErrors","signature":"func (f *FieldManager) UpdateNoErrors(liveObj, newObj runtime.Object, manager string) runtime.Object","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/fieldmanager.go","code":"// UpdateNoErrors is the same as Update, but it will not return\n// errors. If an error happens, the object is returned with\n// managedFields cleared.\nfunc (f *FieldManager) UpdateNoErrors(liveObj, newObj runtime.Object, manager string) runtime.Object {\n\tobj, err := f.Update(liveObj, newObj, manager)\n\tif err != nil {\n\t\tatMostEverySecond.Do(func() {\n\t\t\tns, name := \"unknown\", \"unknown\"\n\t\t\tif accessor, err := meta.Accessor(newObj); err == nil {\n\t\t\t\tns = accessor.GetNamespace()\n\t\t\t\tname = accessor.GetName()\n\t\t\t}\n\n\t\t\tklog.ErrorS(err, \"[SHOULD NOT HAPPEN] failed to update managedFields\", \"versionKind\",\n\t\t\t\tnewObj.GetObjectKind().GroupVersionKind(), \"namespace\", ns, \"name\", name)\n\t\t})\n\t\t// Explicitly remove managedFields on failure, so that\n\t\t// we can't have garbage in it.\n\t\tRemoveObjectManagedFields(newObj)\n\t\treturn newObj\n\t}\n\treturn obj\n}","line":{"from":139,"to":161}} {"id":100015749,"name":"isResetManagedFields","signature":"func isResetManagedFields(managedFields []metav1.ManagedFieldsEntry) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/fieldmanager.go","code":"// Returns true if the managedFields indicate that the user is trying to\n// reset the managedFields, i.e. if the list is non-nil but empty, or if\n// the list has one empty item.\nfunc isResetManagedFields(managedFields []metav1.ManagedFieldsEntry) bool {\n\tif len(managedFields) == 0 {\n\t\treturn managedFields != nil\n\t}\n\n\tif len(managedFields) == 1 {\n\t\treturn reflect.DeepEqual(managedFields[0], metav1.ManagedFieldsEntry{})\n\t}\n\n\treturn false\n}","line":{"from":163,"to":176}} {"id":100015750,"name":"Apply","signature":"func (f *FieldManager) Apply(liveObj, appliedObj runtime.Object, manager string, force bool) (object runtime.Object, err error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/fieldmanager.go","code":"// Apply is used when server-side apply is called, as it merges the\n// object and updates the managed fields.\nfunc (f *FieldManager) Apply(liveObj, appliedObj runtime.Object, manager string, force bool) (object runtime.Object, err error) {\n\t// If the object doesn't have metadata, apply isn't allowed.\n\taccessor, err := meta.Accessor(liveObj)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"couldn't get accessor: %v\", err)\n\t}\n\n\t// Decode the managed fields in the live object, since it isn't allowed in the patch.\n\tmanaged, err := DecodeManagedFields(accessor.GetManagedFields())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to decode managed fields: %v\", err)\n\t}\n\n\tobject, managed, err = f.fieldManager.Apply(liveObj, appliedObj, managed, manager, force)\n\tif err != nil {\n\t\tif conflicts, ok := err.(merge.Conflicts); ok {\n\t\t\treturn nil, NewConflictError(conflicts)\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tif err = EncodeObjectManagedFields(object, managed); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to encode managed fields: %v\", err)\n\t}\n\n\treturn object, nil\n}","line":{"from":178,"to":206}} {"id":100015751,"name":"FieldsToSet","signature":"func FieldsToSet(f metav1.FieldsV1) (s fieldpath.Set, err error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/fields.go","code":"// FieldsToSet creates a set paths from an input trie of fields\nfunc FieldsToSet(f metav1.FieldsV1) (s fieldpath.Set, err error) {\n\terr = s.FromJSON(bytes.NewReader(f.Raw))\n\treturn s, err\n}","line":{"from":37,"to":41}} {"id":100015752,"name":"SetToFields","signature":"func SetToFields(s fieldpath.Set) (f metav1.FieldsV1, err error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/fields.go","code":"// SetToFields creates a trie of fields from an input set of paths\nfunc SetToFields(s fieldpath.Set) (f metav1.FieldsV1, err error) {\n\tf.Raw, err = s.ToJSON()\n\treturn f, err\n}","line":{"from":43,"to":47}} {"id":100015753,"name":"SetLastApplied","signature":"func SetLastApplied(obj runtime.Object, value string) error","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/lastapplied.go","code":"// SetLastApplied sets the last-applied annotation the given value in\n// the object.\nfunc SetLastApplied(obj runtime.Object, value string) error {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"couldn't get accessor: %v\", err))\n\t}\n\tvar annotations = accessor.GetAnnotations()\n\tif annotations == nil {\n\t\tannotations = map[string]string{}\n\t}\n\tannotations[LastAppliedConfigAnnotation] = value\n\tif err := apimachineryvalidation.ValidateAnnotationsSize(annotations); err != nil {\n\t\tdelete(annotations, LastAppliedConfigAnnotation)\n\t}\n\taccessor.SetAnnotations(annotations)\n\treturn nil\n}","line":{"from":33,"to":50}} {"id":100015754,"name":"NewLastAppliedManager","signature":"func NewLastAppliedManager(fieldManager Manager, typeConverter TypeConverter, objectConverter runtime.ObjectConvertor, groupVersion schema.GroupVersion) Manager","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/lastappliedmanager.go","code":"// NewLastAppliedManager converts the client-side apply annotation to\n// server-side apply managed fields\nfunc NewLastAppliedManager(fieldManager Manager, typeConverter TypeConverter, objectConverter runtime.ObjectConvertor, groupVersion schema.GroupVersion) Manager {\n\treturn \u0026lastAppliedManager{\n\t\tfieldManager: fieldManager,\n\t\ttypeConverter: typeConverter,\n\t\tobjectConverter: objectConverter,\n\t\tgroupVersion: groupVersion,\n\t}\n}","line":{"from":40,"to":49}} {"id":100015755,"name":"Update","signature":"func (f *lastAppliedManager) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/lastappliedmanager.go","code":"// Update implements Manager.\nfunc (f *lastAppliedManager) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) {\n\treturn f.fieldManager.Update(liveObj, newObj, managed, manager)\n}","line":{"from":51,"to":54}} {"id":100015756,"name":"Apply","signature":"func (f *lastAppliedManager) Apply(liveObj, newObj runtime.Object, managed Managed, manager string, force bool) (runtime.Object, Managed, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/lastappliedmanager.go","code":"// Apply will consider the last-applied annotation\n// for upgrading an object managed by client-side apply to server-side apply\n// without conflicts.\nfunc (f *lastAppliedManager) Apply(liveObj, newObj runtime.Object, managed Managed, manager string, force bool) (runtime.Object, Managed, error) {\n\tnewLiveObj, newManaged, newErr := f.fieldManager.Apply(liveObj, newObj, managed, manager, force)\n\t// Upgrade the client-side apply annotation only from kubectl server-side-apply.\n\t// To opt-out of this behavior, users may specify a different field manager.\n\tif manager != \"kubectl\" {\n\t\treturn newLiveObj, newManaged, newErr\n\t}\n\n\t// Check if we have conflicts\n\tif newErr == nil {\n\t\treturn newLiveObj, newManaged, newErr\n\t}\n\tconflicts, ok := newErr.(merge.Conflicts)\n\tif !ok {\n\t\treturn newLiveObj, newManaged, newErr\n\t}\n\tconflictSet := conflictsToSet(conflicts)\n\n\t// Check if conflicts are allowed due to client-side apply,\n\t// and if so, then force apply\n\tallowedConflictSet, err := f.allowedConflictsFromLastApplied(liveObj)\n\tif err != nil {\n\t\treturn newLiveObj, newManaged, newErr\n\t}\n\tif !conflictSet.Difference(allowedConflictSet).Empty() {\n\t\tnewConflicts := conflictsDifference(conflicts, allowedConflictSet)\n\t\treturn newLiveObj, newManaged, newConflicts\n\t}\n\n\treturn f.fieldManager.Apply(liveObj, newObj, managed, manager, true)\n}","line":{"from":56,"to":89}} {"id":100015757,"name":"allowedConflictsFromLastApplied","signature":"func (f *lastAppliedManager) allowedConflictsFromLastApplied(liveObj runtime.Object) (*fieldpath.Set, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/lastappliedmanager.go","code":"func (f *lastAppliedManager) allowedConflictsFromLastApplied(liveObj runtime.Object) (*fieldpath.Set, error) {\n\tvar accessor, err = meta.Accessor(liveObj)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"couldn't get accessor: %v\", err))\n\t}\n\n\t// If there is no client-side apply annotation, then there is nothing to do\n\tvar annotations = accessor.GetAnnotations()\n\tif annotations == nil {\n\t\treturn nil, fmt.Errorf(\"no last applied annotation\")\n\t}\n\tvar lastApplied, ok = annotations[LastAppliedConfigAnnotation]\n\tif !ok || lastApplied == \"\" {\n\t\treturn nil, fmt.Errorf(\"no last applied annotation\")\n\t}\n\n\tliveObjVersioned, err := f.objectConverter.ConvertToVersion(liveObj, f.groupVersion)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to convert live obj to versioned: %v\", err)\n\t}\n\n\tliveObjTyped, err := f.typeConverter.ObjectToTyped(liveObjVersioned)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to convert live obj to typed: %v\", err)\n\t}\n\n\tvar lastAppliedObj = \u0026unstructured.Unstructured{Object: map[string]interface{}{}}\n\terr = json.Unmarshal([]byte(lastApplied), lastAppliedObj)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to decode last applied obj: %v in '%s'\", err, lastApplied)\n\t}\n\n\tif lastAppliedObj.GetAPIVersion() != f.groupVersion.String() {\n\t\treturn nil, fmt.Errorf(\"expected version of last applied to match live object '%s', but got '%s': %v\", f.groupVersion.String(), lastAppliedObj.GetAPIVersion(), err)\n\t}\n\n\tlastAppliedObjTyped, err := f.typeConverter.ObjectToTyped(lastAppliedObj)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to convert last applied to typed: %v\", err)\n\t}\n\n\tlastAppliedObjFieldSet, err := lastAppliedObjTyped.ToFieldSet()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create fieldset for last applied object: %v\", err)\n\t}\n\n\tcomparison, err := lastAppliedObjTyped.Compare(liveObjTyped)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to compare last applied object and live object: %v\", err)\n\t}\n\n\t// Remove fields in last applied that are different, added, or missing in\n\t// the live object.\n\t// Because last-applied fields don't match the live object fields,\n\t// then we don't own these fields.\n\tlastAppliedObjFieldSet = lastAppliedObjFieldSet.\n\t\tDifference(comparison.Modified).\n\t\tDifference(comparison.Added).\n\t\tDifference(comparison.Removed)\n\n\treturn lastAppliedObjFieldSet, nil\n}","line":{"from":91,"to":152}} {"id":100015758,"name":"conflictsToSet","signature":"func conflictsToSet(conflicts merge.Conflicts) *fieldpath.Set","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/lastappliedmanager.go","code":"// TODO: replace with merge.Conflicts.ToSet()\nfunc conflictsToSet(conflicts merge.Conflicts) *fieldpath.Set {\n\tconflictSet := fieldpath.NewSet()\n\tfor _, conflict := range []merge.Conflict(conflicts) {\n\t\tconflictSet.Insert(conflict.Path)\n\t}\n\treturn conflictSet\n}","line":{"from":154,"to":161}} {"id":100015759,"name":"conflictsDifference","signature":"func conflictsDifference(conflicts merge.Conflicts, s *fieldpath.Set) merge.Conflicts","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/lastappliedmanager.go","code":"func conflictsDifference(conflicts merge.Conflicts, s *fieldpath.Set) merge.Conflicts {\n\tnewConflicts := []merge.Conflict{}\n\tfor _, conflict := range []merge.Conflict(conflicts) {\n\t\tif !s.Has(conflict.Path) {\n\t\t\tnewConflicts = append(newConflicts, conflict)\n\t\t}\n\t}\n\treturn newConflicts\n}","line":{"from":163,"to":171}} {"id":100015760,"name":"NewLastAppliedUpdater","signature":"func NewLastAppliedUpdater(fieldManager Manager) Manager","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/lastappliedupdater.go","code":"// NewLastAppliedUpdater sets the client-side apply annotation up to date with\n// server-side apply managed fields\nfunc NewLastAppliedUpdater(fieldManager Manager) Manager {\n\treturn \u0026lastAppliedUpdater{\n\t\tfieldManager: fieldManager,\n\t}\n}","line":{"from":33,"to":39}} {"id":100015761,"name":"Update","signature":"func (f *lastAppliedUpdater) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/lastappliedupdater.go","code":"// Update implements Manager.\nfunc (f *lastAppliedUpdater) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) {\n\treturn f.fieldManager.Update(liveObj, newObj, managed, manager)\n}","line":{"from":41,"to":44}} {"id":100015762,"name":"Apply","signature":"func (f *lastAppliedUpdater) Apply(liveObj, newObj runtime.Object, managed Managed, manager string, force bool) (runtime.Object, Managed, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/lastappliedupdater.go","code":"// server-side apply managed fields\nfunc (f *lastAppliedUpdater) Apply(liveObj, newObj runtime.Object, managed Managed, manager string, force bool) (runtime.Object, Managed, error) {\n\tliveObj, managed, err := f.fieldManager.Apply(liveObj, newObj, managed, manager, force)\n\tif err != nil {\n\t\treturn liveObj, managed, err\n\t}\n\n\t// Sync the client-side apply annotation only from kubectl server-side apply.\n\t// To opt-out of this behavior, users may specify a different field manager.\n\t//\n\t// If the client-side apply annotation doesn't exist,\n\t// then continue because we have no annotation to update\n\tif manager == \"kubectl\" \u0026\u0026 hasLastApplied(liveObj) {\n\t\tlastAppliedValue, err := buildLastApplied(newObj)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"failed to build last-applied annotation: %v\", err)\n\t\t}\n\t\terr = SetLastApplied(liveObj, lastAppliedValue)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"failed to set last-applied annotation: %v\", err)\n\t\t}\n\t}\n\treturn liveObj, managed, err\n}","line":{"from":46,"to":69}} {"id":100015763,"name":"hasLastApplied","signature":"func hasLastApplied(obj runtime.Object) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/lastappliedupdater.go","code":"func hasLastApplied(obj runtime.Object) bool {\n\tvar accessor, err = meta.Accessor(obj)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"couldn't get accessor: %v\", err))\n\t}\n\tvar annotations = accessor.GetAnnotations()\n\tif annotations == nil {\n\t\treturn false\n\t}\n\tlastApplied, ok := annotations[LastAppliedConfigAnnotation]\n\treturn ok \u0026\u0026 len(lastApplied) \u003e 0\n}","line":{"from":71,"to":82}} {"id":100015764,"name":"buildLastApplied","signature":"func buildLastApplied(obj runtime.Object) (string, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/lastappliedupdater.go","code":"func buildLastApplied(obj runtime.Object) (string, error) {\n\tobj = obj.DeepCopyObject()\n\n\tvar accessor, err = meta.Accessor(obj)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"couldn't get accessor: %v\", err))\n\t}\n\n\t// Remove the annotation from the object before encoding the object\n\tvar annotations = accessor.GetAnnotations()\n\tdelete(annotations, LastAppliedConfigAnnotation)\n\taccessor.SetAnnotations(annotations)\n\n\tlastApplied, err := runtime.Encode(unstructured.UnstructuredJSONScheme, obj)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"couldn't encode object into last applied annotation: %v\", err)\n\t}\n\treturn string(lastApplied), nil\n}","line":{"from":84,"to":102}} {"id":100015765,"name":"Fields","signature":"func (m *managedStruct) Fields() fieldpath.ManagedFields","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/managedfields.go","code":"// Fields implements ManagedInterface.\nfunc (m *managedStruct) Fields() fieldpath.ManagedFields {\n\treturn m.fields\n}","line":{"from":46,"to":49}} {"id":100015766,"name":"Times","signature":"func (m *managedStruct) Times() map[string]*metav1.Time","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/managedfields.go","code":"// Times implements ManagedInterface.\nfunc (m *managedStruct) Times() map[string]*metav1.Time {\n\treturn m.times\n}","line":{"from":51,"to":54}} {"id":100015767,"name":"NewEmptyManaged","signature":"func NewEmptyManaged() ManagedInterface","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/managedfields.go","code":"// NewEmptyManaged creates an empty ManagedInterface.\nfunc NewEmptyManaged() ManagedInterface {\n\treturn NewManaged(fieldpath.ManagedFields{}, map[string]*metav1.Time{})\n}","line":{"from":56,"to":59}} {"id":100015768,"name":"NewManaged","signature":"func NewManaged(f fieldpath.ManagedFields, t map[string]*metav1.Time) ManagedInterface","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/managedfields.go","code":"// NewManaged creates a ManagedInterface from a fieldpath.ManagedFields and the timestamps associated with each operation.\nfunc NewManaged(f fieldpath.ManagedFields, t map[string]*metav1.Time) ManagedInterface {\n\treturn \u0026managedStruct{\n\t\tfields: f,\n\t\ttimes: t,\n\t}\n}","line":{"from":61,"to":67}} {"id":100015769,"name":"RemoveObjectManagedFields","signature":"func RemoveObjectManagedFields(obj runtime.Object)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/managedfields.go","code":"// RemoveObjectManagedFields removes the ManagedFields from the object\n// before we merge so that it doesn't appear in the ManagedFields\n// recursively.\nfunc RemoveObjectManagedFields(obj runtime.Object) {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"couldn't get accessor: %v\", err))\n\t}\n\taccessor.SetManagedFields(nil)\n}","line":{"from":69,"to":78}} {"id":100015770,"name":"EncodeObjectManagedFields","signature":"func EncodeObjectManagedFields(obj runtime.Object, managed ManagedInterface) error","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/managedfields.go","code":"// EncodeObjectManagedFields converts and stores the fieldpathManagedFields into the objects ManagedFields\nfunc EncodeObjectManagedFields(obj runtime.Object, managed ManagedInterface) error {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"couldn't get accessor: %v\", err))\n\t}\n\n\tencodedManagedFields, err := encodeManagedFields(managed)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to convert back managed fields to API: %v\", err)\n\t}\n\taccessor.SetManagedFields(encodedManagedFields)\n\n\treturn nil\n}","line":{"from":80,"to":94}} {"id":100015771,"name":"DecodeManagedFields","signature":"func DecodeManagedFields(encodedManagedFields []metav1.ManagedFieldsEntry) (ManagedInterface, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/managedfields.go","code":"// DecodeManagedFields converts ManagedFields from the wire format (api format)\n// to the format used by sigs.k8s.io/structured-merge-diff\nfunc DecodeManagedFields(encodedManagedFields []metav1.ManagedFieldsEntry) (ManagedInterface, error) {\n\tmanaged := managedStruct{}\n\tmanaged.fields = make(fieldpath.ManagedFields, len(encodedManagedFields))\n\tmanaged.times = make(map[string]*metav1.Time, len(encodedManagedFields))\n\n\tfor i, encodedVersionedSet := range encodedManagedFields {\n\t\tswitch encodedVersionedSet.Operation {\n\t\tcase metav1.ManagedFieldsOperationApply, metav1.ManagedFieldsOperationUpdate:\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"operation must be `Apply` or `Update`\")\n\t\t}\n\t\tif len(encodedVersionedSet.APIVersion) \u003c 1 {\n\t\t\treturn nil, fmt.Errorf(\"apiVersion must not be empty\")\n\t\t}\n\t\tswitch encodedVersionedSet.FieldsType {\n\t\tcase \"FieldsV1\":\n\t\t\t// Valid case.\n\t\tcase \"\":\n\t\t\treturn nil, fmt.Errorf(\"missing fieldsType in managed fields entry %d\", i)\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"invalid fieldsType %q in managed fields entry %d\", encodedVersionedSet.FieldsType, i)\n\t\t}\n\t\tmanager, err := BuildManagerIdentifier(\u0026encodedVersionedSet)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding manager from %v: %v\", encodedVersionedSet, err)\n\t\t}\n\t\tmanaged.fields[manager], err = decodeVersionedSet(\u0026encodedVersionedSet)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding versioned set from %v: %v\", encodedVersionedSet, err)\n\t\t}\n\t\tmanaged.times[manager] = encodedVersionedSet.Time\n\t}\n\treturn \u0026managed, nil\n}","line":{"from":96,"to":131}} {"id":100015772,"name":"BuildManagerIdentifier","signature":"func BuildManagerIdentifier(encodedManager *metav1.ManagedFieldsEntry) (manager string, err error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/managedfields.go","code":"// BuildManagerIdentifier creates a manager identifier string from a ManagedFieldsEntry\nfunc BuildManagerIdentifier(encodedManager *metav1.ManagedFieldsEntry) (manager string, err error) {\n\tencodedManagerCopy := *encodedManager\n\n\t// Never include fields type in the manager identifier\n\tencodedManagerCopy.FieldsType = \"\"\n\n\t// Never include the fields in the manager identifier\n\tencodedManagerCopy.FieldsV1 = nil\n\n\t// Never include the time in the manager identifier\n\tencodedManagerCopy.Time = nil\n\n\t// For appliers, don't include the APIVersion in the manager identifier,\n\t// so it will always have the same manager identifier each time it applied.\n\tif encodedManager.Operation == metav1.ManagedFieldsOperationApply {\n\t\tencodedManagerCopy.APIVersion = \"\"\n\t}\n\n\t// Use the remaining fields to build the manager identifier\n\tb, err := json.Marshal(\u0026encodedManagerCopy)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error marshalling manager identifier: %v\", err)\n\t}\n\n\treturn string(b), nil\n}","line":{"from":133,"to":159}} {"id":100015773,"name":"decodeVersionedSet","signature":"func decodeVersionedSet(encodedVersionedSet *metav1.ManagedFieldsEntry) (versionedSet fieldpath.VersionedSet, err error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/managedfields.go","code":"func decodeVersionedSet(encodedVersionedSet *metav1.ManagedFieldsEntry) (versionedSet fieldpath.VersionedSet, err error) {\n\tfields := EmptyFields\n\tif encodedVersionedSet.FieldsV1 != nil {\n\t\tfields = *encodedVersionedSet.FieldsV1\n\t}\n\tset, err := FieldsToSet(fields)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error decoding set: %v\", err)\n\t}\n\treturn fieldpath.NewVersionedSet(\u0026set, fieldpath.APIVersion(encodedVersionedSet.APIVersion), encodedVersionedSet.Operation == metav1.ManagedFieldsOperationApply), nil\n}","line":{"from":161,"to":171}} {"id":100015774,"name":"encodeManagedFields","signature":"func encodeManagedFields(managed ManagedInterface) (encodedManagedFields []metav1.ManagedFieldsEntry, err error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/managedfields.go","code":"// encodeManagedFields converts ManagedFields from the format used by\n// sigs.k8s.io/structured-merge-diff to the wire format (api format)\nfunc encodeManagedFields(managed ManagedInterface) (encodedManagedFields []metav1.ManagedFieldsEntry, err error) {\n\tif len(managed.Fields()) == 0 {\n\t\treturn nil, nil\n\t}\n\tencodedManagedFields = []metav1.ManagedFieldsEntry{}\n\tfor manager := range managed.Fields() {\n\t\tversionedSet := managed.Fields()[manager]\n\t\tv, err := encodeManagerVersionedSet(manager, versionedSet)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error encoding versioned set for %v: %v\", manager, err)\n\t\t}\n\t\tif t, ok := managed.Times()[manager]; ok {\n\t\t\tv.Time = t\n\t\t}\n\t\tencodedManagedFields = append(encodedManagedFields, *v)\n\t}\n\treturn sortEncodedManagedFields(encodedManagedFields)\n}","line":{"from":173,"to":192}} {"id":100015775,"name":"sortEncodedManagedFields","signature":"func sortEncodedManagedFields(encodedManagedFields []metav1.ManagedFieldsEntry) (sortedManagedFields []metav1.ManagedFieldsEntry, err error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/managedfields.go","code":"func sortEncodedManagedFields(encodedManagedFields []metav1.ManagedFieldsEntry) (sortedManagedFields []metav1.ManagedFieldsEntry, err error) {\n\tsort.Slice(encodedManagedFields, func(i, j int) bool {\n\t\tp, q := encodedManagedFields[i], encodedManagedFields[j]\n\n\t\tif p.Operation != q.Operation {\n\t\t\treturn p.Operation \u003c q.Operation\n\t\t}\n\n\t\tpSeconds, qSeconds := int64(0), int64(0)\n\t\tif p.Time != nil {\n\t\t\tpSeconds = p.Time.Unix()\n\t\t}\n\t\tif q.Time != nil {\n\t\t\tqSeconds = q.Time.Unix()\n\t\t}\n\t\tif pSeconds != qSeconds {\n\t\t\treturn pSeconds \u003c qSeconds\n\t\t}\n\n\t\tif p.Manager != q.Manager {\n\t\t\treturn p.Manager \u003c q.Manager\n\t\t}\n\n\t\tif p.APIVersion != q.APIVersion {\n\t\t\treturn p.APIVersion \u003c q.APIVersion\n\t\t}\n\t\treturn p.Subresource \u003c q.Subresource\n\t})\n\n\treturn encodedManagedFields, nil\n}","line":{"from":194,"to":224}} {"id":100015776,"name":"encodeManagerVersionedSet","signature":"func encodeManagerVersionedSet(manager string, versionedSet fieldpath.VersionedSet) (encodedVersionedSet *metav1.ManagedFieldsEntry, err error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/managedfields.go","code":"func encodeManagerVersionedSet(manager string, versionedSet fieldpath.VersionedSet) (encodedVersionedSet *metav1.ManagedFieldsEntry, err error) {\n\tencodedVersionedSet = \u0026metav1.ManagedFieldsEntry{}\n\n\t// Get as many fields as we can from the manager identifier\n\terr = json.Unmarshal([]byte(manager), encodedVersionedSet)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error unmarshalling manager identifier %v: %v\", manager, err)\n\t}\n\n\t// Get the APIVersion, Operation, and Fields from the VersionedSet\n\tencodedVersionedSet.APIVersion = string(versionedSet.APIVersion())\n\tif versionedSet.Applied() {\n\t\tencodedVersionedSet.Operation = metav1.ManagedFieldsOperationApply\n\t}\n\tencodedVersionedSet.FieldsType = \"FieldsV1\"\n\tfields, err := SetToFields(*versionedSet.Set())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error encoding set: %v\", err)\n\t}\n\tencodedVersionedSet.FieldsV1 = \u0026fields\n\n\treturn encodedVersionedSet, nil\n}","line":{"from":226,"to":248}} {"id":100015777,"name":"NewManagedFieldsUpdater","signature":"func NewManagedFieldsUpdater(fieldManager Manager) Manager","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/managedfieldsupdater.go","code":"// NewManagedFieldsUpdater is responsible for updating the managedfields\n// in the object, updating the time of the operation as necessary. For\n// updates, it uses a hard-coded manager to detect if things have\n// changed, and swaps back the correct manager after the operation is\n// done.\nfunc NewManagedFieldsUpdater(fieldManager Manager) Manager {\n\treturn \u0026managedFieldsUpdater{\n\t\tfieldManager: fieldManager,\n\t}\n}","line":{"from":33,"to":42}} {"id":100015778,"name":"Update","signature":"func (f *managedFieldsUpdater) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/managedfieldsupdater.go","code":"// Update implements Manager.\nfunc (f *managedFieldsUpdater) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) {\n\tself := \"current-operation\"\n\tobject, managed, err := f.fieldManager.Update(liveObj, newObj, managed, self)\n\tif err != nil {\n\t\treturn object, managed, err\n\t}\n\n\t// If the current operation took any fields from anything, it means the object changed,\n\t// so update the timestamp of the managedFieldsEntry and merge with any previous updates from the same manager\n\tif vs, ok := managed.Fields()[self]; ok {\n\t\tdelete(managed.Fields(), self)\n\n\t\tif previous, ok := managed.Fields()[manager]; ok {\n\t\t\tmanaged.Fields()[manager] = fieldpath.NewVersionedSet(vs.Set().Union(previous.Set()), vs.APIVersion(), vs.Applied())\n\t\t} else {\n\t\t\tmanaged.Fields()[manager] = vs\n\t\t}\n\n\t\tmanaged.Times()[manager] = \u0026metav1.Time{Time: time.Now().UTC()}\n\t}\n\n\treturn object, managed, nil\n}","line":{"from":44,"to":67}} {"id":100015779,"name":"Apply","signature":"func (f *managedFieldsUpdater) Apply(liveObj, appliedObj runtime.Object, managed Managed, fieldManager string, force bool) (runtime.Object, Managed, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/managedfieldsupdater.go","code":"// Apply implements Manager.\nfunc (f *managedFieldsUpdater) Apply(liveObj, appliedObj runtime.Object, managed Managed, fieldManager string, force bool) (runtime.Object, Managed, error) {\n\tobject, managed, err := f.fieldManager.Apply(liveObj, appliedObj, managed, fieldManager, force)\n\tif err != nil {\n\t\treturn object, managed, err\n\t}\n\tif object != nil {\n\t\tmanaged.Times()[fieldManager] = \u0026metav1.Time{Time: time.Now().UTC()}\n\t} else {\n\t\tobject = liveObj.DeepCopyObject()\n\t\tRemoveObjectManagedFields(object)\n\t}\n\treturn object, managed, nil\n}","line":{"from":69,"to":82}} {"id":100015780,"name":"NewPathElement","signature":"func NewPathElement(s string) (fieldpath.PathElement, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/pathelement.go","code":"// NewPathElement parses a serialized path element\nfunc NewPathElement(s string) (fieldpath.PathElement, error) {\n\tsplit := strings.SplitN(s, Separator, 2)\n\tif len(split) \u003c 2 {\n\t\treturn fieldpath.PathElement{}, fmt.Errorf(\"missing colon: %v\", s)\n\t}\n\tswitch split[0] {\n\tcase Field:\n\t\treturn fieldpath.PathElement{\n\t\t\tFieldName: \u0026split[1],\n\t\t}, nil\n\tcase Value:\n\t\tval, err := value.FromJSON([]byte(split[1]))\n\t\tif err != nil {\n\t\t\treturn fieldpath.PathElement{}, err\n\t\t}\n\t\treturn fieldpath.PathElement{\n\t\t\tValue: \u0026val,\n\t\t}, nil\n\tcase Index:\n\t\ti, err := strconv.Atoi(split[1])\n\t\tif err != nil {\n\t\t\treturn fieldpath.PathElement{}, err\n\t\t}\n\t\treturn fieldpath.PathElement{\n\t\t\tIndex: \u0026i,\n\t\t}, nil\n\tcase Key:\n\t\tkv := map[string]json.RawMessage{}\n\t\terr := json.Unmarshal([]byte(split[1]), \u0026kv)\n\t\tif err != nil {\n\t\t\treturn fieldpath.PathElement{}, err\n\t\t}\n\t\tfields := value.FieldList{}\n\t\tfor k, v := range kv {\n\t\t\tb, err := json.Marshal(v)\n\t\t\tif err != nil {\n\t\t\t\treturn fieldpath.PathElement{}, err\n\t\t\t}\n\t\t\tval, err := value.FromJSON(b)\n\t\t\tif err != nil {\n\t\t\t\treturn fieldpath.PathElement{}, err\n\t\t\t}\n\n\t\t\tfields = append(fields, value.Field{\n\t\t\t\tName: k,\n\t\t\t\tValue: val,\n\t\t\t})\n\t\t}\n\t\treturn fieldpath.PathElement{\n\t\t\tKey: \u0026fields,\n\t\t}, nil\n\tdefault:\n\t\t// Ignore unknown key types\n\t\treturn fieldpath.PathElement{}, nil\n\t}\n}","line":{"from":47,"to":103}} {"id":100015781,"name":"PathElementString","signature":"func PathElementString(pe fieldpath.PathElement) (string, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/pathelement.go","code":"// PathElementString serializes a path element\nfunc PathElementString(pe fieldpath.PathElement) (string, error) {\n\tswitch {\n\tcase pe.FieldName != nil:\n\t\treturn Field + Separator + *pe.FieldName, nil\n\tcase pe.Key != nil:\n\t\tkv := map[string]json.RawMessage{}\n\t\tfor _, k := range *pe.Key {\n\t\t\tb, err := value.ToJSON(k.Value)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\tm := json.RawMessage{}\n\t\t\terr = json.Unmarshal(b, \u0026m)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\tkv[k.Name] = m\n\t\t}\n\t\tb, err := json.Marshal(kv)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn Key + \":\" + string(b), nil\n\tcase pe.Value != nil:\n\t\tb, err := value.ToJSON(*pe.Value)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn Value + \":\" + string(b), nil\n\tcase pe.Index != nil:\n\t\treturn Index + \":\" + strconv.Itoa(*pe.Index), nil\n\tdefault:\n\t\treturn \"\", errors.New(\"Invalid type of path element\")\n\t}\n}","line":{"from":105,"to":140}} {"id":100015782,"name":"NewSkipNonAppliedManager","signature":"func NewSkipNonAppliedManager(fieldManager Manager, objectCreater runtime.ObjectCreater, gvk schema.GroupVersionKind) Manager","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/skipnonapplied.go","code":"// NewSkipNonAppliedManager creates a new wrapped FieldManager that only starts tracking managers after the first apply.\nfunc NewSkipNonAppliedManager(fieldManager Manager, objectCreater runtime.ObjectCreater, gvk schema.GroupVersionKind) Manager {\n\treturn NewProbabilisticSkipNonAppliedManager(fieldManager, objectCreater, gvk, 0.0)\n}","line":{"from":38,"to":41}} {"id":100015783,"name":"NewProbabilisticSkipNonAppliedManager","signature":"func NewProbabilisticSkipNonAppliedManager(fieldManager Manager, objectCreater runtime.ObjectCreater, gvk schema.GroupVersionKind, p float32) Manager","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/skipnonapplied.go","code":"// NewProbabilisticSkipNonAppliedManager creates a new wrapped FieldManager that starts tracking managers after the first apply,\n// or starts tracking on create with p probability.\nfunc NewProbabilisticSkipNonAppliedManager(fieldManager Manager, objectCreater runtime.ObjectCreater, gvk schema.GroupVersionKind, p float32) Manager {\n\treturn \u0026skipNonAppliedManager{\n\t\tfieldManager: fieldManager,\n\t\tobjectCreater: objectCreater,\n\t\tgvk: gvk,\n\t\tbeforeApplyManagerName: \"before-first-apply\",\n\t\tprobability: p,\n\t}\n}","line":{"from":43,"to":53}} {"id":100015784,"name":"Update","signature":"func (f *skipNonAppliedManager) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/skipnonapplied.go","code":"// Update implements Manager.\nfunc (f *skipNonAppliedManager) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) {\n\taccessor, err := meta.Accessor(liveObj)\n\tif err != nil {\n\t\treturn newObj, managed, nil\n\t}\n\n\t// If managed fields is empty, we need to determine whether to skip tracking managed fields.\n\tif len(managed.Fields()) == 0 {\n\t\t// Check if the operation is a create, by checking whether lastObj's UID is empty.\n\t\t// If the operation is create, P(tracking managed fields) = f.probability\n\t\t// If the operation is update, skip tracking managed fields, since we already know managed fields is empty.\n\t\tif len(accessor.GetUID()) == 0 {\n\t\t\tif f.probability \u003c= rand.Float32() {\n\t\t\t\treturn newObj, managed, nil\n\t\t\t}\n\t\t} else {\n\t\t\treturn newObj, managed, nil\n\t\t}\n\t}\n\treturn f.fieldManager.Update(liveObj, newObj, managed, manager)\n}","line":{"from":55,"to":76}} {"id":100015785,"name":"Apply","signature":"func (f *skipNonAppliedManager) Apply(liveObj, appliedObj runtime.Object, managed Managed, fieldManager string, force bool) (runtime.Object, Managed, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/skipnonapplied.go","code":"// Apply implements Manager.\nfunc (f *skipNonAppliedManager) Apply(liveObj, appliedObj runtime.Object, managed Managed, fieldManager string, force bool) (runtime.Object, Managed, error) {\n\tif len(managed.Fields()) == 0 {\n\t\temptyObj, err := f.objectCreater.New(f.gvk)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"failed to create empty object of type %v: %v\", f.gvk, err)\n\t\t}\n\t\tliveObj, managed, err = f.fieldManager.Update(emptyObj, liveObj, managed, f.beforeApplyManagerName)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"failed to create manager for existing fields: %v\", err)\n\t\t}\n\t}\n\treturn f.fieldManager.Apply(liveObj, appliedObj, managed, fieldManager, force)\n}","line":{"from":78,"to":91}} {"id":100015786,"name":"NewStripMetaManager","signature":"func NewStripMetaManager(fieldManager Manager) Manager","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/stripmeta.go","code":"// NewStripMetaManager creates a new Manager that strips metadata and typemeta fields from the manager's fieldset.\nfunc NewStripMetaManager(fieldManager Manager) Manager {\n\treturn \u0026stripMetaManager{\n\t\tfieldManager: fieldManager,\n\t\tstripSet: fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"apiVersion\"),\n\t\t\tfieldpath.MakePathOrDie(\"kind\"),\n\t\t\tfieldpath.MakePathOrDie(\"metadata\"),\n\t\t\tfieldpath.MakePathOrDie(\"metadata\", \"name\"),\n\t\t\tfieldpath.MakePathOrDie(\"metadata\", \"namespace\"),\n\t\t\tfieldpath.MakePathOrDie(\"metadata\", \"creationTimestamp\"),\n\t\t\tfieldpath.MakePathOrDie(\"metadata\", \"selfLink\"),\n\t\t\tfieldpath.MakePathOrDie(\"metadata\", \"uid\"),\n\t\t\tfieldpath.MakePathOrDie(\"metadata\", \"clusterName\"),\n\t\t\tfieldpath.MakePathOrDie(\"metadata\", \"generation\"),\n\t\t\tfieldpath.MakePathOrDie(\"metadata\", \"managedFields\"),\n\t\t\tfieldpath.MakePathOrDie(\"metadata\", \"resourceVersion\"),\n\t\t),\n\t}\n}","line":{"from":35,"to":54}} {"id":100015787,"name":"Update","signature":"func (f *stripMetaManager) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/stripmeta.go","code":"// Update implements Manager.\nfunc (f *stripMetaManager) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) {\n\tnewObj, managed, err := f.fieldManager.Update(liveObj, newObj, managed, manager)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tf.stripFields(managed.Fields(), manager)\n\treturn newObj, managed, nil\n}","line":{"from":56,"to":64}} {"id":100015788,"name":"Apply","signature":"func (f *stripMetaManager) Apply(liveObj, appliedObj runtime.Object, managed Managed, manager string, force bool) (runtime.Object, Managed, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/stripmeta.go","code":"// Apply implements Manager.\nfunc (f *stripMetaManager) Apply(liveObj, appliedObj runtime.Object, managed Managed, manager string, force bool) (runtime.Object, Managed, error) {\n\tnewObj, managed, err := f.fieldManager.Apply(liveObj, appliedObj, managed, manager, force)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tf.stripFields(managed.Fields(), manager)\n\treturn newObj, managed, nil\n}","line":{"from":66,"to":74}} {"id":100015789,"name":"stripFields","signature":"func (f *stripMetaManager) stripFields(managed fieldpath.ManagedFields, manager string)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/stripmeta.go","code":"// stripFields removes a predefined set of paths found in typed from managed\nfunc (f *stripMetaManager) stripFields(managed fieldpath.ManagedFields, manager string) {\n\tvs, ok := managed[manager]\n\tif ok {\n\t\tif vs == nil {\n\t\t\tpanic(fmt.Sprintf(\"Found unexpected nil manager which should never happen: %s\", manager))\n\t\t}\n\t\tnewSet := vs.Set().Difference(f.stripSet)\n\t\tif newSet.Empty() {\n\t\t\tdelete(managed, manager)\n\t\t} else {\n\t\t\tmanaged[manager] = fieldpath.NewVersionedSet(newSet, vs.APIVersion(), vs.Applied())\n\t\t}\n\t}\n}","line":{"from":76,"to":90}} {"id":100015790,"name":"NewStructuredMergeManager","signature":"func NewStructuredMergeManager(typeConverter TypeConverter, objectConverter runtime.ObjectConvertor, objectDefaulter runtime.ObjectDefaulter, gv schema.GroupVersion, hub schema.GroupVersion, resetFields map[fieldpath.APIVersion]*fieldpath.Set) (Manager, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/structuredmerge.go","code":"// NewStructuredMergeManager creates a new Manager that merges apply requests\n// and update managed fields for other types of requests.\nfunc NewStructuredMergeManager(typeConverter TypeConverter, objectConverter runtime.ObjectConvertor, objectDefaulter runtime.ObjectDefaulter, gv schema.GroupVersion, hub schema.GroupVersion, resetFields map[fieldpath.APIVersion]*fieldpath.Set) (Manager, error) {\n\treturn \u0026structuredMergeManager{\n\t\ttypeConverter: typeConverter,\n\t\tobjectConverter: objectConverter,\n\t\tobjectDefaulter: objectDefaulter,\n\t\tgroupVersion: gv,\n\t\thubVersion: hub,\n\t\tupdater: merge.Updater{\n\t\t\tConverter: newVersionConverter(typeConverter, objectConverter, hub), // This is the converter provided to SMD from k8s\n\t\t\tIgnoredFields: resetFields,\n\t\t},\n\t}, nil\n}","line":{"from":41,"to":55}} {"id":100015791,"name":"NewCRDStructuredMergeManager","signature":"func NewCRDStructuredMergeManager(typeConverter TypeConverter, objectConverter runtime.ObjectConvertor, objectDefaulter runtime.ObjectDefaulter, gv schema.GroupVersion, hub schema.GroupVersion, resetFields map[fieldpath.APIVersion]*fieldpath.Set) (_ Manager, err error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/structuredmerge.go","code":"// NewCRDStructuredMergeManager creates a new Manager specifically for\n// CRDs. This allows for the possibility of fields which are not defined\n// in models, as well as having no models defined at all.\nfunc NewCRDStructuredMergeManager(typeConverter TypeConverter, objectConverter runtime.ObjectConvertor, objectDefaulter runtime.ObjectDefaulter, gv schema.GroupVersion, hub schema.GroupVersion, resetFields map[fieldpath.APIVersion]*fieldpath.Set) (_ Manager, err error) {\n\treturn \u0026structuredMergeManager{\n\t\ttypeConverter: typeConverter,\n\t\tobjectConverter: objectConverter,\n\t\tobjectDefaulter: objectDefaulter,\n\t\tgroupVersion: gv,\n\t\thubVersion: hub,\n\t\tupdater: merge.Updater{\n\t\t\tConverter: newCRDVersionConverter(typeConverter, objectConverter, hub),\n\t\t\tIgnoredFields: resetFields,\n\t\t},\n\t}, nil\n}","line":{"from":57,"to":72}} {"id":100015792,"name":"objectGVKNN","signature":"func objectGVKNN(obj runtime.Object) string","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/structuredmerge.go","code":"func objectGVKNN(obj runtime.Object) string {\n\tname := \"\u003cunknown\u003e\"\n\tnamespace := \"\u003cunknown\u003e\"\n\tif accessor, err := meta.Accessor(obj); err == nil {\n\t\tname = accessor.GetName()\n\t\tnamespace = accessor.GetNamespace()\n\t}\n\n\treturn fmt.Sprintf(\"%v/%v; %v\", namespace, name, obj.GetObjectKind().GroupVersionKind())\n}","line":{"from":74,"to":83}} {"id":100015793,"name":"Update","signature":"func (f *structuredMergeManager) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/structuredmerge.go","code":"// Update implements Manager.\nfunc (f *structuredMergeManager) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) {\n\tnewObjVersioned, err := f.toVersioned(newObj)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to convert new object (%v) to proper version (%v): %v\", objectGVKNN(newObj), f.groupVersion, err)\n\t}\n\tliveObjVersioned, err := f.toVersioned(liveObj)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to convert live object (%v) to proper version: %v\", objectGVKNN(liveObj), err)\n\t}\n\tnewObjTyped, err := f.typeConverter.ObjectToTyped(newObjVersioned)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to convert new object (%v) to smd typed: %v\", objectGVKNN(newObjVersioned), err)\n\t}\n\tliveObjTyped, err := f.typeConverter.ObjectToTyped(liveObjVersioned)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to convert live object (%v) to smd typed: %v\", objectGVKNN(liveObjVersioned), err)\n\t}\n\tapiVersion := fieldpath.APIVersion(f.groupVersion.String())\n\n\t// TODO(apelisse) use the first return value when unions are implemented\n\t_, managedFields, err := f.updater.Update(liveObjTyped, newObjTyped, apiVersion, managed.Fields(), manager)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to update ManagedFields (%v): %v\", objectGVKNN(newObjVersioned), err)\n\t}\n\tmanaged = NewManaged(managedFields, managed.Times())\n\n\treturn newObj, managed, nil\n}","line":{"from":85,"to":113}} {"id":100015794,"name":"Apply","signature":"func (f *structuredMergeManager) Apply(liveObj, patchObj runtime.Object, managed Managed, manager string, force bool) (runtime.Object, Managed, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/structuredmerge.go","code":"// Apply implements Manager.\nfunc (f *structuredMergeManager) Apply(liveObj, patchObj runtime.Object, managed Managed, manager string, force bool) (runtime.Object, Managed, error) {\n\t// Check that the patch object has the same version as the live object\n\tif patchVersion := patchObj.GetObjectKind().GroupVersionKind().GroupVersion(); patchVersion != f.groupVersion {\n\t\treturn nil, nil,\n\t\t\terrors.NewBadRequest(\n\t\t\t\tfmt.Sprintf(\"Incorrect version specified in apply patch. \"+\n\t\t\t\t\t\"Specified patch version: %s, expected: %s\",\n\t\t\t\t\tpatchVersion, f.groupVersion))\n\t}\n\n\tpatchObjMeta, err := meta.Accessor(patchObj)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"couldn't get accessor: %v\", err)\n\t}\n\tif patchObjMeta.GetManagedFields() != nil {\n\t\treturn nil, nil, errors.NewBadRequest(\"metadata.managedFields must be nil\")\n\t}\n\n\tliveObjVersioned, err := f.toVersioned(liveObj)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to convert live object (%v) to proper version: %v\", objectGVKNN(liveObj), err)\n\t}\n\n\tpatchObjTyped, err := f.typeConverter.ObjectToTyped(patchObj)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to create typed patch object (%v): %v\", objectGVKNN(patchObj), err)\n\t}\n\tliveObjTyped, err := f.typeConverter.ObjectToTyped(liveObjVersioned)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to create typed live object (%v): %v\", objectGVKNN(liveObjVersioned), err)\n\t}\n\n\tapiVersion := fieldpath.APIVersion(f.groupVersion.String())\n\tnewObjTyped, managedFields, err := f.updater.Apply(liveObjTyped, patchObjTyped, apiVersion, managed.Fields(), manager, force)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tmanaged = NewManaged(managedFields, managed.Times())\n\n\tif newObjTyped == nil {\n\t\treturn nil, managed, nil\n\t}\n\n\tnewObj, err := f.typeConverter.TypedToObject(newObjTyped)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to convert new typed object (%v) to object: %v\", objectGVKNN(patchObj), err)\n\t}\n\n\tnewObjVersioned, err := f.toVersioned(newObj)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to convert new object (%v) to proper version: %v\", objectGVKNN(patchObj), err)\n\t}\n\tf.objectDefaulter.Default(newObjVersioned)\n\n\tnewObjUnversioned, err := f.toUnversioned(newObjVersioned)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to convert to unversioned (%v): %v\", objectGVKNN(patchObj), err)\n\t}\n\treturn newObjUnversioned, managed, nil\n}","line":{"from":115,"to":175}} {"id":100015795,"name":"toVersioned","signature":"func (f *structuredMergeManager) toVersioned(obj runtime.Object) (runtime.Object, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/structuredmerge.go","code":"func (f *structuredMergeManager) toVersioned(obj runtime.Object) (runtime.Object, error) {\n\treturn f.objectConverter.ConvertToVersion(obj, f.groupVersion)\n}","line":{"from":177,"to":179}} {"id":100015796,"name":"toUnversioned","signature":"func (f *structuredMergeManager) toUnversioned(obj runtime.Object) (runtime.Object, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/structuredmerge.go","code":"func (f *structuredMergeManager) toUnversioned(obj runtime.Object) (runtime.Object, error) {\n\treturn f.objectConverter.ConvertToVersion(obj, f.hubVersion)\n}","line":{"from":181,"to":183}} {"id":100015797,"name":"NewTypeConverter","signature":"func NewTypeConverter(openapiSpec map[string]*spec.Schema, preserveUnknownFields bool) (TypeConverter, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/typeconverter.go","code":"func NewTypeConverter(openapiSpec map[string]*spec.Schema, preserveUnknownFields bool) (TypeConverter, error) {\n\ttypeSchema, err := schemaconv.ToSchemaFromOpenAPI(openapiSpec, preserveUnknownFields)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to convert models to schema: %v\", err)\n\t}\n\n\ttypeParser := typed.Parser{Schema: smdschema.Schema{Types: typeSchema.Types}}\n\ttr := indexModels(\u0026typeParser, openapiSpec)\n\n\treturn \u0026typeConverter{parser: tr}, nil\n}","line":{"from":45,"to":55}} {"id":100015798,"name":"ObjectToTyped","signature":"func (c *typeConverter) ObjectToTyped(obj runtime.Object) (*typed.TypedValue, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/typeconverter.go","code":"func (c *typeConverter) ObjectToTyped(obj runtime.Object) (*typed.TypedValue, error) {\n\tgvk := obj.GetObjectKind().GroupVersionKind()\n\tt := c.parser[gvk]\n\tif t == nil {\n\t\treturn nil, NewNoCorrespondingTypeError(gvk)\n\t}\n\tswitch o := obj.(type) {\n\tcase *unstructured.Unstructured:\n\t\treturn t.FromUnstructured(o.UnstructuredContent())\n\tdefault:\n\t\treturn t.FromStructured(obj)\n\t}\n}","line":{"from":57,"to":69}} {"id":100015799,"name":"TypedToObject","signature":"func (c *typeConverter) TypedToObject(value *typed.TypedValue) (runtime.Object, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/typeconverter.go","code":"func (c *typeConverter) TypedToObject(value *typed.TypedValue) (runtime.Object, error) {\n\treturn valueToObject(value.AsValue())\n}","line":{"from":71,"to":73}} {"id":100015800,"name":"NewDeducedTypeConverter","signature":"func NewDeducedTypeConverter() TypeConverter","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/typeconverter.go","code":"// DeducedTypeConverter is a TypeConverter for CRDs that don't have a\n// schema. It does implement the same interface though (and create the\n// same types of objects), so that everything can still work the same.\n// CRDs are merged with all their fields being \"atomic\" (lists\n// included).\nfunc NewDeducedTypeConverter() TypeConverter {\n\treturn deducedTypeConverter{}\n}","line":{"from":77,"to":84}} {"id":100015801,"name":"ObjectToTyped","signature":"func (deducedTypeConverter) ObjectToTyped(obj runtime.Object) (*typed.TypedValue, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/typeconverter.go","code":"// ObjectToTyped converts an object into a TypedValue with a \"deduced type\".\nfunc (deducedTypeConverter) ObjectToTyped(obj runtime.Object) (*typed.TypedValue, error) {\n\tswitch o := obj.(type) {\n\tcase *unstructured.Unstructured:\n\t\treturn typed.DeducedParseableType.FromUnstructured(o.UnstructuredContent())\n\tdefault:\n\t\treturn typed.DeducedParseableType.FromStructured(obj)\n\t}\n}","line":{"from":86,"to":94}} {"id":100015802,"name":"TypedToObject","signature":"func (deducedTypeConverter) TypedToObject(value *typed.TypedValue) (runtime.Object, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/typeconverter.go","code":"// TypedToObject transforms the typed value into a runtime.Object. That\n// is not specific to deduced type.\nfunc (deducedTypeConverter) TypedToObject(value *typed.TypedValue) (runtime.Object, error) {\n\treturn valueToObject(value.AsValue())\n}","line":{"from":96,"to":100}} {"id":100015803,"name":"valueToObject","signature":"func valueToObject(val value.Value) (runtime.Object, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/typeconverter.go","code":"func valueToObject(val value.Value) (runtime.Object, error) {\n\tvu := val.Unstructured()\n\tswitch o := vu.(type) {\n\tcase map[string]interface{}:\n\t\treturn \u0026unstructured.Unstructured{Object: o}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"failed to convert value to unstructured for type %T\", vu)\n\t}\n}","line":{"from":102,"to":110}} {"id":100015804,"name":"indexModels","signature":"func indexModels(","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/typeconverter.go","code":"func indexModels(\n\ttypeParser *typed.Parser,\n\topenAPISchemas map[string]*spec.Schema,\n) map[schema.GroupVersionKind]*typed.ParseableType {\n\ttr := map[schema.GroupVersionKind]*typed.ParseableType{}\n\tfor modelName, model := range openAPISchemas {\n\t\tgvkList := parseGroupVersionKind(model.Extensions)\n\t\tif len(gvkList) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tparsedType := typeParser.Type(modelName)\n\t\tfor _, gvk := range gvkList {\n\t\t\tif len(gvk.Kind) \u003e 0 {\n\t\t\t\ttr[schema.GroupVersionKind(gvk)] = \u0026parsedType\n\t\t\t}\n\t\t}\n\t}\n\treturn tr\n}","line":{"from":112,"to":131}} {"id":100015805,"name":"parseGroupVersionKind","signature":"func parseGroupVersionKind(extensions map[string]interface{}) []schema.GroupVersionKind","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/typeconverter.go","code":"// Get and parse GroupVersionKind from the extension. Returns empty if it doesn't have one.\nfunc parseGroupVersionKind(extensions map[string]interface{}) []schema.GroupVersionKind {\n\tgvkListResult := []schema.GroupVersionKind{}\n\n\t// Get the extensions\n\tgvkExtension, ok := extensions[\"x-kubernetes-group-version-kind\"]\n\tif !ok {\n\t\treturn []schema.GroupVersionKind{}\n\t}\n\n\t// gvk extension must be a list of at least 1 element.\n\tgvkList, ok := gvkExtension.([]interface{})\n\tif !ok {\n\t\treturn []schema.GroupVersionKind{}\n\t}\n\n\tfor _, gvk := range gvkList {\n\t\tvar group, version, kind string\n\n\t\t// gvk extension list must be a map with group, version, and\n\t\t// kind fields\n\t\tif gvkMap, ok := gvk.(map[interface{}]interface{}); ok {\n\t\t\tgroup, ok = gvkMap[\"group\"].(string)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tversion, ok = gvkMap[\"version\"].(string)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tkind, ok = gvkMap[\"kind\"].(string)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t} else if gvkMap, ok := gvk.(map[string]interface{}); ok {\n\t\t\tgroup, ok = gvkMap[\"group\"].(string)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tversion, ok = gvkMap[\"version\"].(string)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tkind, ok = gvkMap[\"kind\"].(string)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else {\n\t\t\tcontinue\n\t\t}\n\n\t\tgvkListResult = append(gvkListResult, schema.GroupVersionKind{\n\t\t\tGroup: group,\n\t\t\tVersion: version,\n\t\t\tKind: kind,\n\t\t})\n\t}\n\n\treturn gvkListResult\n}","line":{"from":133,"to":193}} {"id":100015806,"name":"newVersionConverter","signature":"func newVersionConverter(t TypeConverter, o runtime.ObjectConvertor, h schema.GroupVersion) merge.Converter","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/versionconverter.go","code":"// NewVersionConverter builds a VersionConverter from a TypeConverter and an ObjectConvertor.\nfunc newVersionConverter(t TypeConverter, o runtime.ObjectConvertor, h schema.GroupVersion) merge.Converter {\n\treturn \u0026versionConverter{\n\t\ttypeConverter: t,\n\t\tobjectConvertor: o,\n\t\thubGetter: func(from schema.GroupVersion) schema.GroupVersion {\n\t\t\treturn schema.GroupVersion{\n\t\t\t\tGroup: from.Group,\n\t\t\t\tVersion: h.Version,\n\t\t\t}\n\t\t},\n\t}\n}","line":{"from":39,"to":51}} {"id":100015807,"name":"newCRDVersionConverter","signature":"func newCRDVersionConverter(t TypeConverter, o runtime.ObjectConvertor, h schema.GroupVersion) merge.Converter","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/versionconverter.go","code":"// NewCRDVersionConverter builds a VersionConverter for CRDs from a TypeConverter and an ObjectConvertor.\nfunc newCRDVersionConverter(t TypeConverter, o runtime.ObjectConvertor, h schema.GroupVersion) merge.Converter {\n\treturn \u0026versionConverter{\n\t\ttypeConverter: t,\n\t\tobjectConvertor: o,\n\t\thubGetter: func(from schema.GroupVersion) schema.GroupVersion {\n\t\t\treturn h\n\t\t},\n\t}\n}","line":{"from":53,"to":62}} {"id":100015808,"name":"Convert","signature":"func (v *versionConverter) Convert(object *typed.TypedValue, version fieldpath.APIVersion) (*typed.TypedValue, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/versionconverter.go","code":"// Convert implements sigs.k8s.io/structured-merge-diff/merge.Converter\nfunc (v *versionConverter) Convert(object *typed.TypedValue, version fieldpath.APIVersion) (*typed.TypedValue, error) {\n\t// Convert the smd typed value to a kubernetes object.\n\tobjectToConvert, err := v.typeConverter.TypedToObject(object)\n\tif err != nil {\n\t\treturn object, err\n\t}\n\n\t// Parse the target groupVersion.\n\tgroupVersion, err := schema.ParseGroupVersion(string(version))\n\tif err != nil {\n\t\treturn object, err\n\t}\n\n\t// If attempting to convert to the same version as we already have, just return it.\n\tfromVersion := objectToConvert.GetObjectKind().GroupVersionKind().GroupVersion()\n\tif fromVersion == groupVersion {\n\t\treturn object, nil\n\t}\n\n\t// Convert to internal\n\tinternalObject, err := v.objectConvertor.ConvertToVersion(objectToConvert, v.hubGetter(fromVersion))\n\tif err != nil {\n\t\treturn object, err\n\t}\n\n\t// Convert the object into the target version\n\tconvertedObject, err := v.objectConvertor.ConvertToVersion(internalObject, groupVersion)\n\tif err != nil {\n\t\treturn object, err\n\t}\n\n\t// Convert the object back to a smd typed value and return it.\n\treturn v.typeConverter.ObjectToTyped(convertedObject)\n}","line":{"from":64,"to":98}} {"id":100015809,"name":"IsMissingVersionError","signature":"func (v *versionConverter) IsMissingVersionError(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/versionconverter.go","code":"// IsMissingVersionError\nfunc (v *versionConverter) IsMissingVersionError(err error) bool {\n\treturn runtime.IsNotRegisteredError(err) || isNoCorrespondingTypeError(err)\n}","line":{"from":100,"to":103}} {"id":100015810,"name":"NewNoCorrespondingTypeError","signature":"func NewNoCorrespondingTypeError(gvk schema.GroupVersionKind) error","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/versionconverter.go","code":"func NewNoCorrespondingTypeError(gvk schema.GroupVersionKind) error {\n\treturn \u0026noCorrespondingTypeErr{gvk: gvk}\n}","line":{"from":109,"to":111}} {"id":100015811,"name":"Error","signature":"func (k *noCorrespondingTypeErr) Error() string","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/versionconverter.go","code":"func (k *noCorrespondingTypeErr) Error() string {\n\treturn fmt.Sprintf(\"no corresponding type for %v\", k.gvk)\n}","line":{"from":113,"to":115}} {"id":100015812,"name":"isNoCorrespondingTypeError","signature":"func isNoCorrespondingTypeError(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/internal/versionconverter.go","code":"func isNoCorrespondingTypeError(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\t_, ok := err.(*noCorrespondingTypeErr)\n\treturn ok\n}","line":{"from":117,"to":123}} {"id":100015813,"name":"NewScaleHandler","signature":"func NewScaleHandler(parentEntries []metav1.ManagedFieldsEntry, groupVersion schema.GroupVersion, mappings ResourcePathMappings) *ScaleHandler","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/scalehandler.go","code":"// NewScaleHandler creates a new ScaleHandler\nfunc NewScaleHandler(parentEntries []metav1.ManagedFieldsEntry, groupVersion schema.GroupVersion, mappings ResourcePathMappings) *ScaleHandler {\n\treturn \u0026ScaleHandler{\n\t\tparentEntries: parentEntries,\n\t\tgroupVersion: groupVersion,\n\t\tmappings: mappings,\n\t}\n}","line":{"from":47,"to":54}} {"id":100015814,"name":"ToSubresource","signature":"func (h *ScaleHandler) ToSubresource() ([]metav1.ManagedFieldsEntry, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/scalehandler.go","code":"// ToSubresource filter the managed fields of the main resource and convert\n// them so that they can be handled by scale.\n// For the managed fields that have a replicas path it performs two changes:\n// 1. APIVersion is changed to the APIVersion of the scale subresource\n// 2. Replicas path of the main resource is transformed to the replicas path of\n// the scale subresource\nfunc (h *ScaleHandler) ToSubresource() ([]metav1.ManagedFieldsEntry, error) {\n\tmanaged, err := internal.DecodeManagedFields(h.parentEntries)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tf := fieldpath.ManagedFields{}\n\tt := map[string]*metav1.Time{}\n\tfor manager, versionedSet := range managed.Fields() {\n\t\tpath, ok := h.mappings[string(versionedSet.APIVersion())]\n\t\t// Skip the entry if the APIVersion is unknown\n\t\tif !ok || path == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif versionedSet.Set().Has(path) {\n\t\t\tnewVersionedSet := fieldpath.NewVersionedSet(\n\t\t\t\tfieldpath.NewSet(replicasPathInScale),\n\t\t\t\tfieldpath.APIVersion(scaleGroupVersion.String()),\n\t\t\t\tversionedSet.Applied(),\n\t\t\t)\n\n\t\t\tf[manager] = newVersionedSet\n\t\t\tt[manager] = managed.Times()[manager]\n\t\t}\n\t}\n\n\treturn managedFieldsEntries(internal.NewManaged(f, t))\n}","line":{"from":56,"to":90}} {"id":100015815,"name":"ToParent","signature":"func (h *ScaleHandler) ToParent(scaleEntries []metav1.ManagedFieldsEntry) ([]metav1.ManagedFieldsEntry, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/scalehandler.go","code":"// ToParent merges `scaleEntries` with the entries of the main resource and\n// transforms them accordingly\nfunc (h *ScaleHandler) ToParent(scaleEntries []metav1.ManagedFieldsEntry) ([]metav1.ManagedFieldsEntry, error) {\n\tdecodedParentEntries, err := internal.DecodeManagedFields(h.parentEntries)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tparentFields := decodedParentEntries.Fields()\n\n\tdecodedScaleEntries, err := internal.DecodeManagedFields(scaleEntries)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tscaleFields := decodedScaleEntries.Fields()\n\n\tf := fieldpath.ManagedFields{}\n\tt := map[string]*metav1.Time{}\n\n\tfor manager, versionedSet := range parentFields {\n\t\t// Get the main resource \"replicas\" path\n\t\tpath, ok := h.mappings[string(versionedSet.APIVersion())]\n\t\t// Drop the entry if the APIVersion is unknown.\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\t// If the parent entry does not have the replicas path or it is nil, just\n\t\t// keep it as it is. The path is nil for Custom Resources without scale\n\t\t// subresource.\n\t\tif path == nil || !versionedSet.Set().Has(path) {\n\t\t\tf[manager] = versionedSet\n\t\t\tt[manager] = decodedParentEntries.Times()[manager]\n\t\t\tcontinue\n\t\t}\n\n\t\tif _, ok := scaleFields[manager]; !ok {\n\t\t\t// \"Steal\" the replicas path from the main resource entry\n\t\t\tnewSet := versionedSet.Set().Difference(fieldpath.NewSet(path))\n\n\t\t\tif !newSet.Empty() {\n\t\t\t\tnewVersionedSet := fieldpath.NewVersionedSet(\n\t\t\t\t\tnewSet,\n\t\t\t\t\tversionedSet.APIVersion(),\n\t\t\t\t\tversionedSet.Applied(),\n\t\t\t\t)\n\t\t\t\tf[manager] = newVersionedSet\n\t\t\t\tt[manager] = decodedParentEntries.Times()[manager]\n\t\t\t}\n\t\t} else {\n\t\t\t// Field wasn't stolen, let's keep the entry as it is.\n\t\t\tf[manager] = versionedSet\n\t\t\tt[manager] = decodedParentEntries.Times()[manager]\n\t\t\tdelete(scaleFields, manager)\n\t\t}\n\t}\n\n\tfor manager, versionedSet := range scaleFields {\n\t\tif !versionedSet.Set().Has(replicasPathInScale) {\n\t\t\tcontinue\n\t\t}\n\t\tnewVersionedSet := fieldpath.NewVersionedSet(\n\t\t\tfieldpath.NewSet(h.mappings[h.groupVersion.String()]),\n\t\t\tfieldpath.APIVersion(h.groupVersion.String()),\n\t\t\tversionedSet.Applied(),\n\t\t)\n\t\tf[manager] = newVersionedSet\n\t\tt[manager] = decodedParentEntries.Times()[manager]\n\t}\n\n\treturn managedFieldsEntries(internal.NewManaged(f, t))\n}","line":{"from":92,"to":162}} {"id":100015816,"name":"managedFieldsEntries","signature":"func managedFieldsEntries(entries internal.ManagedInterface) ([]metav1.ManagedFieldsEntry, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/scalehandler.go","code":"func managedFieldsEntries(entries internal.ManagedInterface) ([]metav1.ManagedFieldsEntry, error) {\n\tobj := \u0026unstructured.Unstructured{Object: map[string]interface{}{}}\n\tif err := internal.EncodeObjectManagedFields(obj, entries); err != nil {\n\t\treturn nil, err\n\t}\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"couldn't get accessor: %v\", err))\n\t}\n\treturn accessor.GetManagedFields(), nil\n}","line":{"from":164,"to":174}} {"id":100015817,"name":"NewDeducedTypeConverter","signature":"func NewDeducedTypeConverter() TypeConverter","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/typeconverter.go","code":"// NewDeducedTypeConverter creates a TypeConverter for CRDs that don't\n// have a schema. It does implement the same interface though (and\n// create the same types of objects), so that everything can still work\n// the same. CRDs are merged with all their fields being \"atomic\" (lists\n// included).\nfunc NewDeducedTypeConverter() TypeConverter {\n\treturn internal.NewDeducedTypeConverter()\n}","line":{"from":28,"to":35}} {"id":100015818,"name":"NewTypeConverter","signature":"func NewTypeConverter(openapiSpec map[string]*spec.Schema, preserveUnknownFields bool) (TypeConverter, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/managedfields/typeconverter.go","code":"// NewTypeConverter builds a TypeConverter from a map of OpenAPIV3 schemas.\n// This will automatically find the proper version of the object, and the\n// corresponding schema information.\n// The keys to the map must be consistent with the names\n// used by Refs within the schemas.\n// The schemas should conform to the Kubernetes Structural Schema OpenAPI\n// restrictions found in docs:\n// https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#specifying-a-structural-schema\nfunc NewTypeConverter(openapiSpec map[string]*spec.Schema, preserveUnknownFields bool) (TypeConverter, error) {\n\treturn internal.NewTypeConverter(openapiSpec, preserveUnknownFields)\n}","line":{"from":37,"to":47}} {"id":100015819,"name":"ErrNoMergeKey","signature":"func ErrNoMergeKey(m map[string]interface{}, k string) error","file":"staging/src/k8s.io/apimachinery/pkg/util/mergepatch/errors.go","code":"func ErrNoMergeKey(m map[string]interface{}, k string) error {\n\treturn fmt.Errorf(\"map: %v does not contain declared merge key: %s\", m, k)\n}","line":{"from":35,"to":37}} {"id":100015820,"name":"ErrBadArgType","signature":"func ErrBadArgType(expected, actual interface{}) error","file":"staging/src/k8s.io/apimachinery/pkg/util/mergepatch/errors.go","code":"func ErrBadArgType(expected, actual interface{}) error {\n\treturn fmt.Errorf(\"expected a %s, but received a %s\",\n\t\treflect.TypeOf(expected),\n\t\treflect.TypeOf(actual))\n}","line":{"from":39,"to":43}} {"id":100015821,"name":"ErrBadArgKind","signature":"func ErrBadArgKind(expected, actual interface{}) error","file":"staging/src/k8s.io/apimachinery/pkg/util/mergepatch/errors.go","code":"func ErrBadArgKind(expected, actual interface{}) error {\n\tvar expectedKindString, actualKindString string\n\tif expected == nil {\n\t\texpectedKindString = \"nil\"\n\t} else {\n\t\texpectedKindString = reflect.TypeOf(expected).Kind().String()\n\t}\n\tif actual == nil {\n\t\tactualKindString = \"nil\"\n\t} else {\n\t\tactualKindString = reflect.TypeOf(actual).Kind().String()\n\t}\n\treturn fmt.Errorf(\"expected a %s, but received a %s\", expectedKindString, actualKindString)\n}","line":{"from":45,"to":58}} {"id":100015822,"name":"ErrBadPatchType","signature":"func ErrBadPatchType(t interface{}, m map[string]interface{}) error","file":"staging/src/k8s.io/apimachinery/pkg/util/mergepatch/errors.go","code":"func ErrBadPatchType(t interface{}, m map[string]interface{}) error {\n\treturn fmt.Errorf(\"unknown patch type: %s in map: %v\", t, m)\n}","line":{"from":60,"to":62}} {"id":100015823,"name":"IsPreconditionFailed","signature":"func IsPreconditionFailed(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/mergepatch/errors.go","code":"// IsPreconditionFailed returns true if the provided error indicates\n// a precondition failed.\nfunc IsPreconditionFailed(err error) bool {\n\t_, ok := err.(ErrPreconditionFailed)\n\treturn ok\n}","line":{"from":64,"to":69}} {"id":100015824,"name":"NewErrPreconditionFailed","signature":"func NewErrPreconditionFailed(target map[string]interface{}) ErrPreconditionFailed","file":"staging/src/k8s.io/apimachinery/pkg/util/mergepatch/errors.go","code":"func NewErrPreconditionFailed(target map[string]interface{}) ErrPreconditionFailed {\n\ts := fmt.Sprintf(\"precondition failed for: %v\", target)\n\treturn ErrPreconditionFailed{s}\n}","line":{"from":75,"to":78}} {"id":100015825,"name":"Error","signature":"func (err ErrPreconditionFailed) Error() string","file":"staging/src/k8s.io/apimachinery/pkg/util/mergepatch/errors.go","code":"func (err ErrPreconditionFailed) Error() string {\n\treturn err.message\n}","line":{"from":80,"to":82}} {"id":100015826,"name":"NewErrConflict","signature":"func NewErrConflict(patch, current string) ErrConflict","file":"staging/src/k8s.io/apimachinery/pkg/util/mergepatch/errors.go","code":"func NewErrConflict(patch, current string) ErrConflict {\n\ts := fmt.Sprintf(\"patch:\\n%s\\nconflicts with changes made from original to current:\\n%s\\n\", patch, current)\n\treturn ErrConflict{s}\n}","line":{"from":88,"to":91}} {"id":100015827,"name":"Error","signature":"func (err ErrConflict) Error() string","file":"staging/src/k8s.io/apimachinery/pkg/util/mergepatch/errors.go","code":"func (err ErrConflict) Error() string {\n\treturn err.message\n}","line":{"from":93,"to":95}} {"id":100015828,"name":"IsConflict","signature":"func IsConflict(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/mergepatch/errors.go","code":"// IsConflict returns true if the provided error indicates\n// a conflict between the patch and the current configuration.\nfunc IsConflict(err error) bool {\n\t_, ok := err.(ErrConflict)\n\treturn ok\n}","line":{"from":97,"to":102}} {"id":100015829,"name":"RequireKeyUnchanged","signature":"func RequireKeyUnchanged(key string) PreconditionFunc","file":"staging/src/k8s.io/apimachinery/pkg/util/mergepatch/util.go","code":"// RequireKeyUnchanged returns a precondition function that fails if the provided key\n// is present in the patch (indicating that its value has changed).\nfunc RequireKeyUnchanged(key string) PreconditionFunc {\n\treturn func(patch interface{}) bool {\n\t\tpatchMap, ok := patch.(map[string]interface{})\n\t\tif !ok {\n\t\t\treturn true\n\t\t}\n\n\t\t// The presence of key means that its value has been changed, so the test fails.\n\t\t_, ok = patchMap[key]\n\t\treturn !ok\n\t}\n}","line":{"from":30,"to":43}} {"id":100015830,"name":"RequireMetadataKeyUnchanged","signature":"func RequireMetadataKeyUnchanged(key string) PreconditionFunc","file":"staging/src/k8s.io/apimachinery/pkg/util/mergepatch/util.go","code":"// RequireMetadataKeyUnchanged creates a precondition function that fails\n// if the metadata.key is present in the patch (indicating its value\n// has changed).\nfunc RequireMetadataKeyUnchanged(key string) PreconditionFunc {\n\treturn func(patch interface{}) bool {\n\t\tpatchMap, ok := patch.(map[string]interface{})\n\t\tif !ok {\n\t\t\treturn true\n\t\t}\n\t\tpatchMap1, ok := patchMap[\"metadata\"]\n\t\tif !ok {\n\t\t\treturn true\n\t\t}\n\t\tpatchMap2, ok := patchMap1.(map[string]interface{})\n\t\tif !ok {\n\t\t\treturn true\n\t\t}\n\t\t_, ok = patchMap2[key]\n\t\treturn !ok\n\t}\n}","line":{"from":45,"to":65}} {"id":100015831,"name":"ToYAMLOrError","signature":"func ToYAMLOrError(v interface{}) string","file":"staging/src/k8s.io/apimachinery/pkg/util/mergepatch/util.go","code":"func ToYAMLOrError(v interface{}) string {\n\ty, err := toYAML(v)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\treturn y\n}","line":{"from":67,"to":74}} {"id":100015832,"name":"toYAML","signature":"func toYAML(v interface{}) (string, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/mergepatch/util.go","code":"func toYAML(v interface{}) (string, error) {\n\ty, err := yaml.Marshal(v)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"yaml marshal failed:%v\\n%v\\n\", err, spew.Sdump(v))\n\t}\n\n\treturn string(y), nil\n}","line":{"from":76,"to":83}} {"id":100015833,"name":"HasConflicts","signature":"func HasConflicts(left, right interface{}) (bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/mergepatch/util.go","code":"// HasConflicts returns true if the left and right JSON interface objects overlap with\n// different values in any key. All keys are required to be strings. Since patches of the\n// same Type have congruent keys, this is valid for multiple patch types. This method\n// supports JSON merge patch semantics.\n//\n// NOTE: Numbers with different types (e.g. int(0) vs int64(0)) will be detected as conflicts.\n// Make sure the unmarshaling of left and right are consistent (e.g. use the same library).\nfunc HasConflicts(left, right interface{}) (bool, error) {\n\tswitch typedLeft := left.(type) {\n\tcase map[string]interface{}:\n\t\tswitch typedRight := right.(type) {\n\t\tcase map[string]interface{}:\n\t\t\tfor key, leftValue := range typedLeft {\n\t\t\t\trightValue, ok := typedRight[key]\n\t\t\t\tif !ok {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif conflict, err := HasConflicts(leftValue, rightValue); err != nil || conflict {\n\t\t\t\t\treturn conflict, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn false, nil\n\t\tdefault:\n\t\t\treturn true, nil\n\t\t}\n\tcase []interface{}:\n\t\tswitch typedRight := right.(type) {\n\t\tcase []interface{}:\n\t\t\tif len(typedLeft) != len(typedRight) {\n\t\t\t\treturn true, nil\n\t\t\t}\n\n\t\t\tfor i := range typedLeft {\n\t\t\t\tif conflict, err := HasConflicts(typedLeft[i], typedRight[i]); err != nil || conflict {\n\t\t\t\t\treturn conflict, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn false, nil\n\t\tdefault:\n\t\t\treturn true, nil\n\t\t}\n\tcase string, float64, bool, int64, nil:\n\t\treturn !reflect.DeepEqual(left, right), nil\n\tdefault:\n\t\treturn true, fmt.Errorf(\"unknown type: %v\", reflect.TypeOf(left))\n\t}\n}","line":{"from":85,"to":133}} {"id":100015834,"name":"GetNameFromCallsite","signature":"func GetNameFromCallsite(ignoredPackages ...string) string","file":"staging/src/k8s.io/apimachinery/pkg/util/naming/from_stack.go","code":"// GetNameFromCallsite walks back through the call stack until we find a caller from outside of the ignoredPackages\n// it returns back a shortpath/filename:line to aid in identification of this reflector when it starts logging\nfunc GetNameFromCallsite(ignoredPackages ...string) string {\n\tname := \"????\"\n\tconst maxStack = 10\n\tfor i := 1; i \u003c maxStack; i++ {\n\t\t_, file, line, ok := goruntime.Caller(i)\n\t\tif !ok {\n\t\t\tfile, line, ok = extractStackCreator()\n\t\t\tif !ok {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ti += maxStack\n\t\t}\n\t\tif hasPackage(file, append(ignoredPackages, \"/runtime/asm_\")) {\n\t\t\tcontinue\n\t\t}\n\n\t\tfile = trimPackagePrefix(file)\n\t\tname = fmt.Sprintf(\"%s:%d\", file, line)\n\t\tbreak\n\t}\n\treturn name\n}","line":{"from":28,"to":51}} {"id":100015835,"name":"hasPackage","signature":"func hasPackage(file string, ignoredPackages []string) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/naming/from_stack.go","code":"// hasPackage returns true if the file is in one of the ignored packages.\nfunc hasPackage(file string, ignoredPackages []string) bool {\n\tfor _, ignoredPackage := range ignoredPackages {\n\t\tif strings.Contains(file, ignoredPackage) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":53,"to":61}} {"id":100015836,"name":"trimPackagePrefix","signature":"func trimPackagePrefix(file string) string","file":"staging/src/k8s.io/apimachinery/pkg/util/naming/from_stack.go","code":"// trimPackagePrefix reduces duplicate values off the front of a package name.\nfunc trimPackagePrefix(file string) string {\n\tif l := strings.LastIndex(file, \"/vendor/\"); l \u003e= 0 {\n\t\treturn file[l+len(\"/vendor/\"):]\n\t}\n\tif l := strings.LastIndex(file, \"/src/\"); l \u003e= 0 {\n\t\treturn file[l+5:]\n\t}\n\tif l := strings.LastIndex(file, \"/pkg/\"); l \u003e= 0 {\n\t\treturn file[l+1:]\n\t}\n\treturn file\n}","line":{"from":63,"to":75}} {"id":100015837,"name":"extractStackCreator","signature":"func extractStackCreator() (string, int, bool)","file":"staging/src/k8s.io/apimachinery/pkg/util/naming/from_stack.go","code":"// extractStackCreator retrieves the goroutine file and line that launched this stack. Returns false\n// if the creator cannot be located.\n// TODO: Go does not expose this via runtime https://github.com/golang/go/issues/11440\nfunc extractStackCreator() (string, int, bool) {\n\tstack := debug.Stack()\n\tmatches := stackCreator.FindStringSubmatch(string(stack))\n\tif len(matches) != 4 {\n\t\treturn \"\", 0, false\n\t}\n\tline, err := strconv.Atoi(matches[3])\n\tif err != nil {\n\t\treturn \"\", 0, false\n\t}\n\treturn matches[2], line, true\n}","line":{"from":79,"to":93}} {"id":100015838,"name":"JoinPreservingTrailingSlash","signature":"func JoinPreservingTrailingSlash(elem ...string) string","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"// JoinPreservingTrailingSlash does a path.Join of the specified elements,\n// preserving any trailing slash on the last non-empty segment\nfunc JoinPreservingTrailingSlash(elem ...string) string {\n\t// do the basic path join\n\tresult := path.Join(elem...)\n\n\t// find the last non-empty segment\n\tfor i := len(elem) - 1; i \u003e= 0; i-- {\n\t\tif len(elem[i]) \u003e 0 {\n\t\t\t// if the last segment ended in a slash, ensure our result does as well\n\t\t\tif strings.HasSuffix(elem[i], \"/\") \u0026\u0026 !strings.HasSuffix(result, \"/\") {\n\t\t\t\tresult += \"/\"\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn result\n}","line":{"from":44,"to":62}} {"id":100015839,"name":"IsTimeout","signature":"func IsTimeout(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"// IsTimeout returns true if the given error is a network timeout error\nfunc IsTimeout(err error) bool {\n\tvar neterr net.Error\n\tif errors.As(err, \u0026neterr) {\n\t\treturn neterr != nil \u0026\u0026 neterr.Timeout()\n\t}\n\treturn false\n}","line":{"from":64,"to":71}} {"id":100015840,"name":"IsProbableEOF","signature":"func IsProbableEOF(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"// IsProbableEOF returns true if the given error resembles a connection termination\n// scenario that would justify assuming that the watch is empty.\n// These errors are what the Go http stack returns back to us which are general\n// connection closure errors (strongly correlated) and callers that need to\n// differentiate probable errors in connection behavior between normal \"this is\n// disconnected\" should use the method.\nfunc IsProbableEOF(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\tvar uerr *url.Error\n\tif errors.As(err, \u0026uerr) {\n\t\terr = uerr.Err\n\t}\n\tmsg := err.Error()\n\tswitch {\n\tcase err == io.EOF:\n\t\treturn true\n\tcase err == io.ErrUnexpectedEOF:\n\t\treturn true\n\tcase msg == \"http: can't write HTTP request on broken connection\":\n\t\treturn true\n\tcase strings.Contains(msg, \"http2: server sent GOAWAY and closed the connection\"):\n\t\treturn true\n\tcase strings.Contains(msg, \"connection reset by peer\"):\n\t\treturn true\n\tcase strings.Contains(strings.ToLower(msg), \"use of closed network connection\"):\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":73,"to":103}} {"id":100015841,"name":"SetOldTransportDefaults","signature":"func SetOldTransportDefaults(t *http.Transport) *http.Transport","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"// SetOldTransportDefaults applies the defaults from http.DefaultTransport\n// for the Proxy, Dial, and TLSHandshakeTimeout fields if unset\nfunc SetOldTransportDefaults(t *http.Transport) *http.Transport {\n\tif t.Proxy == nil || isDefault(t.Proxy) {\n\t\t// http.ProxyFromEnvironment doesn't respect CIDRs and that makes it impossible to exclude things like pod and service IPs from proxy settings\n\t\t// ProxierWithNoProxyCIDR allows CIDR rules in NO_PROXY\n\t\tt.Proxy = NewProxierWithNoProxyCIDR(http.ProxyFromEnvironment)\n\t}\n\t// If no custom dialer is set, use the default context dialer\n\t//lint:file-ignore SA1019 Keep supporting deprecated Dial method of custom transports\n\tif t.DialContext == nil \u0026\u0026 t.Dial == nil {\n\t\tt.DialContext = defaultTransport.DialContext\n\t}\n\tif t.TLSHandshakeTimeout == 0 {\n\t\tt.TLSHandshakeTimeout = defaultTransport.TLSHandshakeTimeout\n\t}\n\tif t.IdleConnTimeout == 0 {\n\t\tt.IdleConnTimeout = defaultTransport.IdleConnTimeout\n\t}\n\treturn t\n}","line":{"from":107,"to":127}} {"id":100015842,"name":"SetTransportDefaults","signature":"func SetTransportDefaults(t *http.Transport) *http.Transport","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"// SetTransportDefaults applies the defaults from http.DefaultTransport\n// for the Proxy, Dial, and TLSHandshakeTimeout fields if unset\nfunc SetTransportDefaults(t *http.Transport) *http.Transport {\n\tt = SetOldTransportDefaults(t)\n\t// Allow clients to disable http2 if needed.\n\tif s := os.Getenv(\"DISABLE_HTTP2\"); len(s) \u003e 0 {\n\t\tklog.Info(\"HTTP2 has been explicitly disabled\")\n\t} else if allowsHTTP2(t) {\n\t\tif err := configureHTTP2Transport(t); err != nil {\n\t\t\tklog.Warningf(\"Transport failed http2 configuration: %v\", err)\n\t\t}\n\t}\n\treturn t\n}","line":{"from":129,"to":142}} {"id":100015843,"name":"readIdleTimeoutSeconds","signature":"func readIdleTimeoutSeconds() int","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"func readIdleTimeoutSeconds() int {\n\tret := 30\n\t// User can set the readIdleTimeout to 0 to disable the HTTP/2\n\t// connection health check.\n\tif s := os.Getenv(\"HTTP2_READ_IDLE_TIMEOUT_SECONDS\"); len(s) \u003e 0 {\n\t\ti, err := strconv.Atoi(s)\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"Illegal HTTP2_READ_IDLE_TIMEOUT_SECONDS(%q): %v.\"+\n\t\t\t\t\" Default value %d is used\", s, err, ret)\n\t\t\treturn ret\n\t\t}\n\t\tret = i\n\t}\n\treturn ret\n}","line":{"from":144,"to":158}} {"id":100015844,"name":"pingTimeoutSeconds","signature":"func pingTimeoutSeconds() int","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"func pingTimeoutSeconds() int {\n\tret := 15\n\tif s := os.Getenv(\"HTTP2_PING_TIMEOUT_SECONDS\"); len(s) \u003e 0 {\n\t\ti, err := strconv.Atoi(s)\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"Illegal HTTP2_PING_TIMEOUT_SECONDS(%q): %v.\"+\n\t\t\t\t\" Default value %d is used\", s, err, ret)\n\t\t\treturn ret\n\t\t}\n\t\tret = i\n\t}\n\treturn ret\n}","line":{"from":160,"to":172}} {"id":100015845,"name":"configureHTTP2Transport","signature":"func configureHTTP2Transport(t *http.Transport) error","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"func configureHTTP2Transport(t *http.Transport) error {\n\tt2, err := http2.ConfigureTransports(t)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// The following enables the HTTP/2 connection health check added in\n\t// https://github.com/golang/net/pull/55. The health check detects and\n\t// closes broken transport layer connections. Without the health check,\n\t// a broken connection can linger too long, e.g., a broken TCP\n\t// connection will be closed by the Linux kernel after 13 to 30 minutes\n\t// by default, which caused\n\t// https://github.com/kubernetes/client-go/issues/374 and\n\t// https://github.com/kubernetes/kubernetes/issues/87615.\n\tt2.ReadIdleTimeout = time.Duration(readIdleTimeoutSeconds()) * time.Second\n\tt2.PingTimeout = time.Duration(pingTimeoutSeconds()) * time.Second\n\treturn nil\n}","line":{"from":174,"to":190}} {"id":100015846,"name":"allowsHTTP2","signature":"func allowsHTTP2(t *http.Transport) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"func allowsHTTP2(t *http.Transport) bool {\n\tif t.TLSClientConfig == nil || len(t.TLSClientConfig.NextProtos) == 0 {\n\t\t// the transport expressed no NextProto preference, allow\n\t\treturn true\n\t}\n\tfor _, p := range t.TLSClientConfig.NextProtos {\n\t\tif p == http2.NextProtoTLS {\n\t\t\t// the transport explicitly allowed http/2\n\t\t\treturn true\n\t\t}\n\t}\n\t// the transport explicitly set NextProtos and excluded http/2\n\treturn false\n}","line":{"from":192,"to":205}} {"id":100015847,"name":"DialerFor","signature":"func DialerFor(transport http.RoundTripper) (DialFunc, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"func DialerFor(transport http.RoundTripper) (DialFunc, error) {\n\tif transport == nil {\n\t\treturn nil, nil\n\t}\n\n\tswitch transport := transport.(type) {\n\tcase *http.Transport:\n\t\t// transport.DialContext takes precedence over transport.Dial\n\t\tif transport.DialContext != nil {\n\t\t\treturn transport.DialContext, nil\n\t\t}\n\t\t// adapt transport.Dial to the DialWithContext signature\n\t\tif transport.Dial != nil {\n\t\t\treturn func(ctx context.Context, net, addr string) (net.Conn, error) {\n\t\t\t\treturn transport.Dial(net, addr)\n\t\t\t}, nil\n\t\t}\n\t\t// otherwise return nil\n\t\treturn nil, nil\n\tcase RoundTripperWrapper:\n\t\treturn DialerFor(transport.WrappedRoundTripper())\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown transport type: %T\", transport)\n\t}\n}","line":{"from":214,"to":238}} {"id":100015848,"name":"CloseIdleConnectionsFor","signature":"func CloseIdleConnectionsFor(transport http.RoundTripper)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"// CloseIdleConnectionsFor close idles connections for the Transport.\n// If the Transport is wrapped it iterates over the wrapped round trippers\n// until it finds one that implements the CloseIdleConnections method.\n// If the Transport does not have a CloseIdleConnections method\n// then this function does nothing.\nfunc CloseIdleConnectionsFor(transport http.RoundTripper) {\n\tif transport == nil {\n\t\treturn\n\t}\n\ttype closeIdler interface {\n\t\tCloseIdleConnections()\n\t}\n\n\tswitch transport := transport.(type) {\n\tcase closeIdler:\n\t\ttransport.CloseIdleConnections()\n\tcase RoundTripperWrapper:\n\t\tCloseIdleConnectionsFor(transport.WrappedRoundTripper())\n\tdefault:\n\t\tklog.Warningf(\"unknown transport type: %T\", transport)\n\t}\n}","line":{"from":240,"to":261}} {"id":100015849,"name":"TLSClientConfig","signature":"func TLSClientConfig(transport http.RoundTripper) (*tls.Config, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"func TLSClientConfig(transport http.RoundTripper) (*tls.Config, error) {\n\tif transport == nil {\n\t\treturn nil, nil\n\t}\n\n\tswitch transport := transport.(type) {\n\tcase *http.Transport:\n\t\treturn transport.TLSClientConfig, nil\n\tcase TLSClientConfigHolder:\n\t\treturn transport.TLSClientConfig(), nil\n\tcase RoundTripperWrapper:\n\t\treturn TLSClientConfig(transport.WrappedRoundTripper())\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown transport type: %T\", transport)\n\t}\n}","line":{"from":267,"to":282}} {"id":100015850,"name":"FormatURL","signature":"func FormatURL(scheme string, host string, port int, path string) *url.URL","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"func FormatURL(scheme string, host string, port int, path string) *url.URL {\n\treturn \u0026url.URL{\n\t\tScheme: scheme,\n\t\tHost: net.JoinHostPort(host, strconv.Itoa(port)),\n\t\tPath: path,\n\t}\n}","line":{"from":284,"to":290}} {"id":100015851,"name":"GetHTTPClient","signature":"func GetHTTPClient(req *http.Request) string","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"func GetHTTPClient(req *http.Request) string {\n\tif ua := req.UserAgent(); len(ua) != 0 {\n\t\treturn ua\n\t}\n\treturn \"unknown\"\n}","line":{"from":292,"to":297}} {"id":100015852,"name":"SourceIPs","signature":"func SourceIPs(req *http.Request) []net.IP","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"// SourceIPs splits the comma separated X-Forwarded-For header and joins it with\n// the X-Real-Ip header and/or req.RemoteAddr, ignoring invalid IPs.\n// The X-Real-Ip is omitted if it's already present in the X-Forwarded-For chain.\n// The req.RemoteAddr is always the last IP in the returned list.\n// It returns nil if all of these are empty or invalid.\nfunc SourceIPs(req *http.Request) []net.IP {\n\tvar srcIPs []net.IP\n\n\thdr := req.Header\n\t// First check the X-Forwarded-For header for requests via proxy.\n\thdrForwardedFor := hdr.Get(\"X-Forwarded-For\")\n\tif hdrForwardedFor != \"\" {\n\t\t// X-Forwarded-For can be a csv of IPs in case of multiple proxies.\n\t\t// Use the first valid one.\n\t\tparts := strings.Split(hdrForwardedFor, \",\")\n\t\tfor _, part := range parts {\n\t\t\tip := netutils.ParseIPSloppy(strings.TrimSpace(part))\n\t\t\tif ip != nil {\n\t\t\t\tsrcIPs = append(srcIPs, ip)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Try the X-Real-Ip header.\n\thdrRealIp := hdr.Get(\"X-Real-Ip\")\n\tif hdrRealIp != \"\" {\n\t\tip := netutils.ParseIPSloppy(hdrRealIp)\n\t\t// Only append the X-Real-Ip if it's not already contained in the X-Forwarded-For chain.\n\t\tif ip != nil \u0026\u0026 !containsIP(srcIPs, ip) {\n\t\t\tsrcIPs = append(srcIPs, ip)\n\t\t}\n\t}\n\n\t// Always include the request Remote Address as it cannot be easily spoofed.\n\tvar remoteIP net.IP\n\t// Remote Address in Go's HTTP server is in the form host:port so we need to split that first.\n\thost, _, err := net.SplitHostPort(req.RemoteAddr)\n\tif err == nil {\n\t\tremoteIP = netutils.ParseIPSloppy(host)\n\t}\n\t// Fallback if Remote Address was just IP.\n\tif remoteIP == nil {\n\t\tremoteIP = netutils.ParseIPSloppy(req.RemoteAddr)\n\t}\n\n\t// Don't duplicate remote IP if it's already the last address in the chain.\n\tif remoteIP != nil \u0026\u0026 (len(srcIPs) == 0 || !remoteIP.Equal(srcIPs[len(srcIPs)-1])) {\n\t\tsrcIPs = append(srcIPs, remoteIP)\n\t}\n\n\treturn srcIPs\n}","line":{"from":299,"to":350}} {"id":100015853,"name":"containsIP","signature":"func containsIP(ips []net.IP, ip net.IP) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"// Checks whether the given IP address is contained in the list of IPs.\nfunc containsIP(ips []net.IP, ip net.IP) bool {\n\tfor _, v := range ips {\n\t\tif v.Equal(ip) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":352,"to":360}} {"id":100015854,"name":"GetClientIP","signature":"func GetClientIP(req *http.Request) net.IP","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"// Extracts and returns the clients IP from the given request.\n// Looks at X-Forwarded-For header, X-Real-Ip header and request.RemoteAddr in that order.\n// Returns nil if none of them are set or is set to an invalid value.\nfunc GetClientIP(req *http.Request) net.IP {\n\tips := SourceIPs(req)\n\tif len(ips) == 0 {\n\t\treturn nil\n\t}\n\treturn ips[0]\n}","line":{"from":362,"to":371}} {"id":100015855,"name":"AppendForwardedForHeader","signature":"func AppendForwardedForHeader(req *http.Request)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"// Prepares the X-Forwarded-For header for another forwarding hop by appending the previous sender's\n// IP address to the X-Forwarded-For chain.\nfunc AppendForwardedForHeader(req *http.Request) {\n\t// Copied from net/http/httputil/reverseproxy.go:\n\tif clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {\n\t\t// If we aren't the first proxy retain prior\n\t\t// X-Forwarded-For information as a comma+space\n\t\t// separated list and fold multiple headers into one.\n\t\tif prior, ok := req.Header[\"X-Forwarded-For\"]; ok {\n\t\t\tclientIP = strings.Join(prior, \", \") + \", \" + clientIP\n\t\t}\n\t\treq.Header.Set(\"X-Forwarded-For\", clientIP)\n\t}\n}","line":{"from":373,"to":386}} {"id":100015856,"name":"isDefault","signature":"func isDefault(transportProxier func(*http.Request) (*url.URL, error)) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"// isDefault checks to see if the transportProxierFunc is pointing to the default one\nfunc isDefault(transportProxier func(*http.Request) (*url.URL, error)) bool {\n\ttransportProxierPointer := fmt.Sprintf(\"%p\", transportProxier)\n\treturn transportProxierPointer == defaultProxyFuncPointer\n}","line":{"from":390,"to":394}} {"id":100015857,"name":"NewProxierWithNoProxyCIDR","signature":"func NewProxierWithNoProxyCIDR(delegate func(req *http.Request) (*url.URL, error)) func(req *http.Request) (*url.URL, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"// NewProxierWithNoProxyCIDR constructs a Proxier function that respects CIDRs in NO_PROXY and delegates if\n// no matching CIDRs are found\nfunc NewProxierWithNoProxyCIDR(delegate func(req *http.Request) (*url.URL, error)) func(req *http.Request) (*url.URL, error) {\n\t// we wrap the default method, so we only need to perform our check if the NO_PROXY (or no_proxy) envvar has a CIDR in it\n\tnoProxyEnv := os.Getenv(\"NO_PROXY\")\n\tif noProxyEnv == \"\" {\n\t\tnoProxyEnv = os.Getenv(\"no_proxy\")\n\t}\n\tnoProxyRules := strings.Split(noProxyEnv, \",\")\n\n\tcidrs := []*net.IPNet{}\n\tfor _, noProxyRule := range noProxyRules {\n\t\t_, cidr, _ := netutils.ParseCIDRSloppy(noProxyRule)\n\t\tif cidr != nil {\n\t\t\tcidrs = append(cidrs, cidr)\n\t\t}\n\t}\n\n\tif len(cidrs) == 0 {\n\t\treturn delegate\n\t}\n\n\treturn func(req *http.Request) (*url.URL, error) {\n\t\tip := netutils.ParseIPSloppy(req.URL.Hostname())\n\t\tif ip == nil {\n\t\t\treturn delegate(req)\n\t\t}\n\n\t\tfor _, cidr := range cidrs {\n\t\t\tif cidr.Contains(ip) {\n\t\t\t\treturn nil, nil\n\t\t\t}\n\t\t}\n\n\t\treturn delegate(req)\n\t}\n}","line":{"from":396,"to":432}} {"id":100015858,"name":"Dial","signature":"func (fn DialerFunc) Dial(req *http.Request) (net.Conn, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"func (fn DialerFunc) Dial(req *http.Request) (net.Conn, error) {\n\treturn fn(req)\n}","line":{"from":437,"to":439}} {"id":100015859,"name":"CloneRequest","signature":"func CloneRequest(req *http.Request) *http.Request","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"// CloneRequest creates a shallow copy of the request along with a deep copy of the Headers.\nfunc CloneRequest(req *http.Request) *http.Request {\n\tr := new(http.Request)\n\n\t// shallow clone\n\t*r = *req\n\n\t// deep copy headers\n\tr.Header = CloneHeader(req.Header)\n\n\treturn r\n}","line":{"from":448,"to":459}} {"id":100015860,"name":"CloneHeader","signature":"func CloneHeader(in http.Header) http.Header","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"// CloneHeader creates a deep copy of an http.Header.\nfunc CloneHeader(in http.Header) http.Header {\n\tout := make(http.Header, len(in))\n\tfor key, values := range in {\n\t\tnewValues := make([]string, len(values))\n\t\tcopy(newValues, values)\n\t\tout[key] = newValues\n\t}\n\treturn out\n}","line":{"from":461,"to":470}} {"id":100015861,"name":"ParseWarningHeaders","signature":"func ParseWarningHeaders(headers []string) ([]WarningHeader, []error)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"// ParseWarningHeaders extract RFC2616 14.46 warnings headers from the specified set of header values.\n// Multiple comma-separated warnings per header are supported.\n// If errors are encountered on a header, the remainder of that header are skipped and subsequent headers are parsed.\n// Returns successfully parsed warnings and any errors encountered.\nfunc ParseWarningHeaders(headers []string) ([]WarningHeader, []error) {\n\tvar (\n\t\tresults []WarningHeader\n\t\terrs []error\n\t)\n\tfor _, header := range headers {\n\t\tfor len(header) \u003e 0 {\n\t\t\tresult, remainder, err := ParseWarningHeader(header)\n\t\t\tif err != nil {\n\t\t\t\terrs = append(errs, err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tresults = append(results, result)\n\t\t\theader = remainder\n\t\t}\n\t}\n\treturn results, errs\n}","line":{"from":483,"to":504}} {"id":100015862,"name":"ParseWarningHeader","signature":"func ParseWarningHeader(header string) (result WarningHeader, remainder string, err error)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"// ParseWarningHeader extracts one RFC2616 14.46 warning from the specified header,\n// returning an error if the header does not contain a correctly formatted warning.\n// Any remaining content in the header is returned.\nfunc ParseWarningHeader(header string) (result WarningHeader, remainder string, err error) {\n\t// https://tools.ietf.org/html/rfc2616#section-14.46\n\t// updated by\n\t// https://tools.ietf.org/html/rfc7234#section-5.5\n\t// https://tools.ietf.org/html/rfc7234#appendix-A\n\t// Some requirements regarding production and processing of the Warning\n\t// header fields have been relaxed, as it is not widely implemented.\n\t// Furthermore, the Warning header field no longer uses RFC 2047\n\t// encoding, nor does it allow multiple languages, as these aspects were\n\t// not implemented.\n\t//\n\t// Format is one of:\n\t// warn-code warn-agent \"warn-text\"\n\t// warn-code warn-agent \"warn-text\" \"warn-date\"\n\t//\n\t// warn-code is a three digit number\n\t// warn-agent is unquoted and contains no spaces\n\t// warn-text is quoted with backslash escaping (RFC2047-encoded according to RFC2616, not encoded according to RFC7234)\n\t// warn-date is optional, quoted, and in HTTP-date format (no embedded or escaped quotes)\n\t//\n\t// additional warnings can optionally be included in the same header by comma-separating them:\n\t// warn-code warn-agent \"warn-text\" \"warn-date\"[, warn-code warn-agent \"warn-text\" \"warn-date\", ...]\n\n\t// tolerate leading whitespace\n\theader = strings.TrimSpace(header)\n\n\tparts := strings.SplitN(header, \" \", 3)\n\tif len(parts) != 3 {\n\t\treturn WarningHeader{}, \"\", errors.New(\"invalid warning header: fewer than 3 segments\")\n\t}\n\tcode, agent, textDateRemainder := parts[0], parts[1], parts[2]\n\n\t// verify code format\n\tif !codeMatcher.Match([]byte(code)) {\n\t\treturn WarningHeader{}, \"\", errors.New(\"invalid warning header: code segment is not 3 digits between 100-299\")\n\t}\n\tcodeInt, _ := strconv.ParseInt(code, 10, 64)\n\n\t// verify agent presence\n\tif len(agent) == 0 {\n\t\treturn WarningHeader{}, \"\", errors.New(\"invalid warning header: empty agent segment\")\n\t}\n\tif !utf8.ValidString(agent) || hasAnyRunes(agent, unicode.IsControl) {\n\t\treturn WarningHeader{}, \"\", errors.New(\"invalid warning header: invalid agent\")\n\t}\n\n\t// verify textDateRemainder presence\n\tif len(textDateRemainder) == 0 {\n\t\treturn WarningHeader{}, \"\", errors.New(\"invalid warning header: empty text segment\")\n\t}\n\n\t// extract text\n\ttext, dateAndRemainder, err := parseQuotedString(textDateRemainder)\n\tif err != nil {\n\t\treturn WarningHeader{}, \"\", fmt.Errorf(\"invalid warning header: %v\", err)\n\t}\n\t// tolerate RFC2047-encoded text from warnings produced according to RFC2616\n\tif decodedText, err := wordDecoder.DecodeHeader(text); err == nil {\n\t\ttext = decodedText\n\t}\n\tif !utf8.ValidString(text) || hasAnyRunes(text, unicode.IsControl) {\n\t\treturn WarningHeader{}, \"\", errors.New(\"invalid warning header: invalid text\")\n\t}\n\tresult = WarningHeader{Code: int(codeInt), Agent: agent, Text: text}\n\n\tif len(dateAndRemainder) \u003e 0 {\n\t\tif dateAndRemainder[0] == '\"' {\n\t\t\t// consume date\n\t\t\tfoundEndQuote := false\n\t\t\tfor i := 1; i \u003c len(dateAndRemainder); i++ {\n\t\t\t\tif dateAndRemainder[i] == '\"' {\n\t\t\t\t\tfoundEndQuote = true\n\t\t\t\t\tremainder = strings.TrimSpace(dateAndRemainder[i+1:])\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !foundEndQuote {\n\t\t\t\treturn WarningHeader{}, \"\", errors.New(\"invalid warning header: unterminated date segment\")\n\t\t\t}\n\t\t} else {\n\t\t\tremainder = dateAndRemainder\n\t\t}\n\t}\n\tif len(remainder) \u003e 0 {\n\t\tif remainder[0] == ',' {\n\t\t\t// consume comma if present\n\t\t\tremainder = strings.TrimSpace(remainder[1:])\n\t\t} else {\n\t\t\treturn WarningHeader{}, \"\", errors.New(\"invalid warning header: unexpected token after warn-date\")\n\t\t}\n\t}\n\n\treturn result, remainder, nil\n}","line":{"from":511,"to":607}} {"id":100015863,"name":"parseQuotedString","signature":"func parseQuotedString(quotedString string) (string, string, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"func parseQuotedString(quotedString string) (string, string, error) {\n\tif len(quotedString) == 0 {\n\t\treturn \"\", \"\", errors.New(\"invalid quoted string: 0-length\")\n\t}\n\n\tif quotedString[0] != '\"' {\n\t\treturn \"\", \"\", errors.New(\"invalid quoted string: missing initial quote\")\n\t}\n\n\tquotedString = quotedString[1:]\n\tvar remainder string\n\tescaping := false\n\tclosedQuote := false\n\tresult := \u0026strings.Builder{}\nloop:\n\tfor i := 0; i \u003c len(quotedString); i++ {\n\t\tb := quotedString[i]\n\t\tswitch b {\n\t\tcase '\"':\n\t\t\tif escaping {\n\t\t\t\tresult.WriteByte(b)\n\t\t\t\tescaping = false\n\t\t\t} else {\n\t\t\t\tclosedQuote = true\n\t\t\t\tremainder = strings.TrimSpace(quotedString[i+1:])\n\t\t\t\tbreak loop\n\t\t\t}\n\t\tcase '\\\\':\n\t\t\tif escaping {\n\t\t\t\tresult.WriteByte(b)\n\t\t\t\tescaping = false\n\t\t\t} else {\n\t\t\t\tescaping = true\n\t\t\t}\n\t\tdefault:\n\t\t\tresult.WriteByte(b)\n\t\t\tescaping = false\n\t\t}\n\t}\n\n\tif !closedQuote {\n\t\treturn \"\", \"\", errors.New(\"invalid quoted string: missing closing quote\")\n\t}\n\treturn result.String(), remainder, nil\n}","line":{"from":609,"to":653}} {"id":100015864,"name":"NewWarningHeader","signature":"func NewWarningHeader(code int, agent, text string) (string, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"func NewWarningHeader(code int, agent, text string) (string, error) {\n\tif code \u003c 0 || code \u003e 999 {\n\t\treturn \"\", errors.New(\"code must be between 0 and 999\")\n\t}\n\tif len(agent) == 0 {\n\t\tagent = \"-\"\n\t} else if !utf8.ValidString(agent) || strings.ContainsAny(agent, `\\\"`) || hasAnyRunes(agent, unicode.IsSpace, unicode.IsControl) {\n\t\treturn \"\", errors.New(\"agent must be valid UTF-8 and must not contain spaces, quotes, backslashes, or control characters\")\n\t}\n\tif !utf8.ValidString(text) || hasAnyRunes(text, unicode.IsControl) {\n\t\treturn \"\", errors.New(\"text must be valid UTF-8 and must not contain control characters\")\n\t}\n\treturn fmt.Sprintf(\"%03d %s %s\", code, agent, makeQuotedString(text)), nil\n}","line":{"from":655,"to":668}} {"id":100015865,"name":"hasAnyRunes","signature":"func hasAnyRunes(s string, runeCheckers ...func(rune) bool) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"func hasAnyRunes(s string, runeCheckers ...func(rune) bool) bool {\n\tfor _, r := range s {\n\t\tfor _, checker := range runeCheckers {\n\t\t\tif checker(r) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":670,"to":679}} {"id":100015866,"name":"makeQuotedString","signature":"func makeQuotedString(s string) string","file":"staging/src/k8s.io/apimachinery/pkg/util/net/http.go","code":"func makeQuotedString(s string) string {\n\tresult := \u0026bytes.Buffer{}\n\t// opening quote\n\tresult.WriteRune('\"')\n\tfor _, c := range s {\n\t\tswitch c {\n\t\tcase '\"', '\\\\':\n\t\t\t// escape \" and \\\n\t\t\tresult.WriteRune('\\\\')\n\t\t\tresult.WriteRune(c)\n\t\tdefault:\n\t\t\t// write everything else as-is\n\t\t\tresult.WriteRune(c)\n\t\t}\n\t}\n\t// closing quote\n\tresult.WriteRune('\"')\n\treturn result.String()\n}","line":{"from":681,"to":699}} {"id":100015867,"name":"Error","signature":"func (e noRoutesError) Error() string","file":"staging/src/k8s.io/apimachinery/pkg/util/net/interface.go","code":"func (e noRoutesError) Error() string {\n\treturn e.message\n}","line":{"from":74,"to":76}} {"id":100015868,"name":"IsNoRoutesError","signature":"func IsNoRoutesError(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/net/interface.go","code":"// IsNoRoutesError checks if an error is of type noRoutesError\nfunc IsNoRoutesError(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\tswitch err.(type) {\n\tcase noRoutesError:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":78,"to":89}} {"id":100015869,"name":"extract","signature":"func (rf RouteFile) extract() ([]Route, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/interface.go","code":"func (rf RouteFile) extract() ([]Route, error) {\n\tfile, err := os.Open(rf.name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\treturn rf.parse(file)\n}","line":{"from":96,"to":103}} {"id":100015870,"name":"getIPv4DefaultRoutes","signature":"func getIPv4DefaultRoutes(input io.Reader) ([]Route, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/interface.go","code":"// getIPv4DefaultRoutes obtains the IPv4 routes, and filters out non-default routes.\nfunc getIPv4DefaultRoutes(input io.Reader) ([]Route, error) {\n\troutes := []Route{}\n\tscanner := bufio.NewReader(input)\n\tfor {\n\t\tline, err := scanner.ReadString('\\n')\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\t//ignore the headers in the route info\n\t\tif strings.HasPrefix(line, \"Iface\") {\n\t\t\tcontinue\n\t\t}\n\t\tfields := strings.Fields(line)\n\t\t// Interested in fields:\n\t\t// 0 - interface name\n\t\t// 1 - destination address\n\t\t// 2 - gateway\n\t\tdest, err := parseIP(fields[1], familyIPv4)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tgw, err := parseIP(fields[2], familyIPv4)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !dest.Equal(net.IPv4zero) {\n\t\t\tcontinue\n\t\t}\n\t\troutes = append(routes, Route{\n\t\t\tInterface: fields[0],\n\t\t\tDestination: dest,\n\t\t\tGateway: gw,\n\t\t\tFamily: familyIPv4,\n\t\t})\n\t}\n\treturn routes, nil\n}","line":{"from":105,"to":142}} {"id":100015871,"name":"getIPv6DefaultRoutes","signature":"func getIPv6DefaultRoutes(input io.Reader) ([]Route, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/interface.go","code":"func getIPv6DefaultRoutes(input io.Reader) ([]Route, error) {\n\troutes := []Route{}\n\tscanner := bufio.NewReader(input)\n\tfor {\n\t\tline, err := scanner.ReadString('\\n')\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tfields := strings.Fields(line)\n\t\t// Interested in fields:\n\t\t// 0 - destination address\n\t\t// 4 - gateway\n\t\t// 9 - interface name\n\t\tdest, err := parseIP(fields[0], familyIPv6)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tgw, err := parseIP(fields[4], familyIPv6)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !dest.Equal(net.IPv6zero) {\n\t\t\tcontinue\n\t\t}\n\t\tif gw.Equal(net.IPv6zero) {\n\t\t\tcontinue // loopback\n\t\t}\n\t\troutes = append(routes, Route{\n\t\t\tInterface: fields[9],\n\t\t\tDestination: dest,\n\t\t\tGateway: gw,\n\t\t\tFamily: familyIPv6,\n\t\t})\n\t}\n\treturn routes, nil\n}","line":{"from":144,"to":179}} {"id":100015872,"name":"parseIP","signature":"func parseIP(str string, family AddressFamily) (net.IP, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/interface.go","code":"// parseIP takes the hex IP address string from route file and converts it\n// to a net.IP address. For IPv4, the value must be converted to big endian.\nfunc parseIP(str string, family AddressFamily) (net.IP, error) {\n\tif str == \"\" {\n\t\treturn nil, fmt.Errorf(\"input is nil\")\n\t}\n\tbytes, err := hex.DecodeString(str)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif family == familyIPv4 {\n\t\tif len(bytes) != net.IPv4len {\n\t\t\treturn nil, fmt.Errorf(\"invalid IPv4 address in route\")\n\t\t}\n\t\treturn net.IP([]byte{bytes[3], bytes[2], bytes[1], bytes[0]}), nil\n\t}\n\t// Must be IPv6\n\tif len(bytes) != net.IPv6len {\n\t\treturn nil, fmt.Errorf(\"invalid IPv6 address in route\")\n\t}\n\treturn net.IP(bytes), nil\n}","line":{"from":181,"to":202}} {"id":100015873,"name":"isInterfaceUp","signature":"func isInterfaceUp(intf *net.Interface) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/net/interface.go","code":"func isInterfaceUp(intf *net.Interface) bool {\n\tif intf == nil {\n\t\treturn false\n\t}\n\tif intf.Flags\u0026net.FlagUp != 0 {\n\t\tklog.V(4).Infof(\"Interface %v is up\", intf.Name)\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":204,"to":213}} {"id":100015874,"name":"isLoopbackOrPointToPoint","signature":"func isLoopbackOrPointToPoint(intf *net.Interface) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/net/interface.go","code":"func isLoopbackOrPointToPoint(intf *net.Interface) bool {\n\treturn intf.Flags\u0026(net.FlagLoopback|net.FlagPointToPoint) != 0\n}","line":{"from":215,"to":217}} {"id":100015875,"name":"getMatchingGlobalIP","signature":"func getMatchingGlobalIP(addrs []net.Addr, family AddressFamily) (net.IP, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/interface.go","code":"// getMatchingGlobalIP returns the first valid global unicast address of the given\n// 'family' from the list of 'addrs'.\nfunc getMatchingGlobalIP(addrs []net.Addr, family AddressFamily) (net.IP, error) {\n\tif len(addrs) \u003e 0 {\n\t\tfor i := range addrs {\n\t\t\tklog.V(4).Infof(\"Checking addr %s.\", addrs[i].String())\n\t\t\tip, _, err := netutils.ParseCIDRSloppy(addrs[i].String())\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif memberOf(ip, family) {\n\t\t\t\tif ip.IsGlobalUnicast() {\n\t\t\t\t\tklog.V(4).Infof(\"IP found %v\", ip)\n\t\t\t\t\treturn ip, nil\n\t\t\t\t} else {\n\t\t\t\t\tklog.V(4).Infof(\"Non-global unicast address found %v\", ip)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tklog.V(4).Infof(\"%v is not an IPv%d address\", ip, int(family))\n\t\t\t}\n\n\t\t}\n\t}\n\treturn nil, nil\n}","line":{"from":219,"to":243}} {"id":100015876,"name":"getIPFromInterface","signature":"func getIPFromInterface(intfName string, forFamily AddressFamily, nw networkInterfacer) (net.IP, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/interface.go","code":"// getIPFromInterface gets the IPs on an interface and returns a global unicast address, if any. The\n// interface must be up, the IP must in the family requested, and the IP must be a global unicast address.\nfunc getIPFromInterface(intfName string, forFamily AddressFamily, nw networkInterfacer) (net.IP, error) {\n\tintf, err := nw.InterfaceByName(intfName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif isInterfaceUp(intf) {\n\t\taddrs, err := nw.Addrs(intf)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tklog.V(4).Infof(\"Interface %q has %d addresses :%v.\", intfName, len(addrs), addrs)\n\t\tmatchingIP, err := getMatchingGlobalIP(addrs, forFamily)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif matchingIP != nil {\n\t\t\tklog.V(4).Infof(\"Found valid IPv%d address %v for interface %q.\", int(forFamily), matchingIP, intfName)\n\t\t\treturn matchingIP, nil\n\t\t}\n\t}\n\treturn nil, nil\n}","line":{"from":245,"to":268}} {"id":100015877,"name":"getIPFromLoopbackInterface","signature":"func getIPFromLoopbackInterface(forFamily AddressFamily, nw networkInterfacer) (net.IP, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/interface.go","code":"// getIPFromLoopbackInterface gets the IPs on a loopback interface and returns a global unicast address, if any.\n// The loopback interface must be up, the IP must in the family requested, and the IP must be a global unicast address.\nfunc getIPFromLoopbackInterface(forFamily AddressFamily, nw networkInterfacer) (net.IP, error) {\n\tintfs, err := nw.Interfaces()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, intf := range intfs {\n\t\tif !isInterfaceUp(\u0026intf) {\n\t\t\tcontinue\n\t\t}\n\t\tif intf.Flags\u0026(net.FlagLoopback) != 0 {\n\t\t\taddrs, err := nw.Addrs(\u0026intf)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tklog.V(4).Infof(\"Interface %q has %d addresses :%v.\", intf.Name, len(addrs), addrs)\n\t\t\tmatchingIP, err := getMatchingGlobalIP(addrs, forFamily)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif matchingIP != nil {\n\t\t\t\tklog.V(4).Infof(\"Found valid IPv%d address %v for interface %q.\", int(forFamily), matchingIP, intf.Name)\n\t\t\t\treturn matchingIP, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, nil\n}","line":{"from":270,"to":298}} {"id":100015878,"name":"memberOf","signature":"func memberOf(ip net.IP, family AddressFamily) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/net/interface.go","code":"// memberOf tells if the IP is of the desired family. Used for checking interface addresses.\nfunc memberOf(ip net.IP, family AddressFamily) bool {\n\tif ip.To4() != nil {\n\t\treturn family == familyIPv4\n\t} else {\n\t\treturn family == familyIPv6\n\t}\n}","line":{"from":300,"to":307}} {"id":100015879,"name":"chooseIPFromHostInterfaces","signature":"func chooseIPFromHostInterfaces(nw networkInterfacer, addressFamilies AddressFamilyPreference) (net.IP, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/interface.go","code":"// chooseIPFromHostInterfaces looks at all system interfaces, trying to find one that is up that\n// has a global unicast address (non-loopback, non-link local, non-point2point), and returns the IP.\n// addressFamilies determines whether it prefers IPv4 or IPv6\nfunc chooseIPFromHostInterfaces(nw networkInterfacer, addressFamilies AddressFamilyPreference) (net.IP, error) {\n\tintfs, err := nw.Interfaces()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(intfs) == 0 {\n\t\treturn nil, fmt.Errorf(\"no interfaces found on host.\")\n\t}\n\tfor _, family := range addressFamilies {\n\t\tklog.V(4).Infof(\"Looking for system interface with a global IPv%d address\", uint(family))\n\t\tfor _, intf := range intfs {\n\t\t\tif !isInterfaceUp(\u0026intf) {\n\t\t\t\tklog.V(4).Infof(\"Skipping: down interface %q\", intf.Name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif isLoopbackOrPointToPoint(\u0026intf) {\n\t\t\t\tklog.V(4).Infof(\"Skipping: LB or P2P interface %q\", intf.Name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\taddrs, err := nw.Addrs(\u0026intf)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif len(addrs) == 0 {\n\t\t\t\tklog.V(4).Infof(\"Skipping: no addresses on interface %q\", intf.Name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor _, addr := range addrs {\n\t\t\t\tip, _, err := netutils.ParseCIDRSloppy(addr.String())\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"unable to parse CIDR for interface %q: %s\", intf.Name, err)\n\t\t\t\t}\n\t\t\t\tif !memberOf(ip, family) {\n\t\t\t\t\tklog.V(4).Infof(\"Skipping: no address family match for %q on interface %q.\", ip, intf.Name)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// TODO: Decide if should open up to allow IPv6 LLAs in future.\n\t\t\t\tif !ip.IsGlobalUnicast() {\n\t\t\t\t\tklog.V(4).Infof(\"Skipping: non-global address %q on interface %q.\", ip, intf.Name)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tklog.V(4).Infof(\"Found global unicast address %q on interface %q.\", ip, intf.Name)\n\t\t\t\treturn ip, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"no acceptable interface with global unicast address found on host\")\n}","line":{"from":309,"to":359}} {"id":100015880,"name":"ChooseHostInterface","signature":"func ChooseHostInterface() (net.IP, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/interface.go","code":"// ChooseHostInterface is a method used fetch an IP for a daemon.\n// If there is no routing info file, it will choose a global IP from the system\n// interfaces. Otherwise, it will use IPv4 and IPv6 route information to return the\n// IP of the interface with a gateway on it (with priority given to IPv4). For a node\n// with no internet connection, it returns error.\nfunc ChooseHostInterface() (net.IP, error) {\n\treturn chooseHostInterface(preferIPv4)\n}","line":{"from":361,"to":368}} {"id":100015881,"name":"chooseHostInterface","signature":"func chooseHostInterface(addressFamilies AddressFamilyPreference) (net.IP, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/interface.go","code":"func chooseHostInterface(addressFamilies AddressFamilyPreference) (net.IP, error) {\n\tvar nw networkInterfacer = networkInterface{}\n\tif _, err := os.Stat(ipv4RouteFile); os.IsNotExist(err) {\n\t\treturn chooseIPFromHostInterfaces(nw, addressFamilies)\n\t}\n\troutes, err := getAllDefaultRoutes()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn chooseHostInterfaceFromRoute(routes, nw, addressFamilies)\n}","line":{"from":370,"to":380}} {"id":100015882,"name":"InterfaceByName","signature":"func (_ networkInterface) InterfaceByName(intfName string) (*net.Interface, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/interface.go","code":"func (_ networkInterface) InterfaceByName(intfName string) (*net.Interface, error) {\n\treturn net.InterfaceByName(intfName)\n}","line":{"from":395,"to":397}} {"id":100015883,"name":"Addrs","signature":"func (_ networkInterface) Addrs(intf *net.Interface) ([]net.Addr, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/interface.go","code":"func (_ networkInterface) Addrs(intf *net.Interface) ([]net.Addr, error) {\n\treturn intf.Addrs()\n}","line":{"from":399,"to":401}} {"id":100015884,"name":"Interfaces","signature":"func (_ networkInterface) Interfaces() ([]net.Interface, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/interface.go","code":"func (_ networkInterface) Interfaces() ([]net.Interface, error) {\n\treturn net.Interfaces()\n}","line":{"from":403,"to":405}} {"id":100015885,"name":"getAllDefaultRoutes","signature":"func getAllDefaultRoutes() ([]Route, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/interface.go","code":"// getAllDefaultRoutes obtains IPv4 and IPv6 default routes on the node. If unable\n// to read the IPv4 routing info file, we return an error. If unable to read the IPv6\n// routing info file (which is optional), we'll just use the IPv4 route information.\n// Using all the routing info, if no default routes are found, an error is returned.\nfunc getAllDefaultRoutes() ([]Route, error) {\n\troutes, err := v4File.extract()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tv6Routes, _ := v6File.extract()\n\troutes = append(routes, v6Routes...)\n\tif len(routes) == 0 {\n\t\treturn nil, noRoutesError{\n\t\t\tmessage: fmt.Sprintf(\"no default routes found in %q or %q\", v4File.name, v6File.name),\n\t\t}\n\t}\n\treturn routes, nil\n}","line":{"from":407,"to":424}} {"id":100015886,"name":"chooseHostInterfaceFromRoute","signature":"func chooseHostInterfaceFromRoute(routes []Route, nw networkInterfacer, addressFamilies AddressFamilyPreference) (net.IP, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/interface.go","code":"// chooseHostInterfaceFromRoute cycles through each default route provided, looking for a\n// global IP address from the interface for the route. If there are routes but no global\n// address is obtained from the interfaces, it checks if the loopback interface has a global address.\n// addressFamilies determines whether it prefers IPv4 or IPv6\nfunc chooseHostInterfaceFromRoute(routes []Route, nw networkInterfacer, addressFamilies AddressFamilyPreference) (net.IP, error) {\n\tfor _, family := range addressFamilies {\n\t\tklog.V(4).Infof(\"Looking for default routes with IPv%d addresses\", uint(family))\n\t\tfor _, route := range routes {\n\t\t\tif route.Family != family {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tklog.V(4).Infof(\"Default route transits interface %q\", route.Interface)\n\t\t\tfinalIP, err := getIPFromInterface(route.Interface, family, nw)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif finalIP != nil {\n\t\t\t\tklog.V(4).Infof(\"Found active IP %v \", finalIP)\n\t\t\t\treturn finalIP, nil\n\t\t\t}\n\t\t\t// In case of network setups where default routes are present, but network\n\t\t\t// interfaces use only link-local addresses (e.g. as described in RFC5549).\n\t\t\t// the global IP is assigned to the loopback interface, and we should use it\n\t\t\tloopbackIP, err := getIPFromLoopbackInterface(family, nw)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif loopbackIP != nil {\n\t\t\t\tklog.V(4).Infof(\"Found active IP %v on Loopback interface\", loopbackIP)\n\t\t\t\treturn loopbackIP, nil\n\t\t\t}\n\t\t}\n\t}\n\tklog.V(4).Infof(\"No active IP found by looking at default routes\")\n\treturn nil, fmt.Errorf(\"unable to select an IP from default routes.\")\n}","line":{"from":426,"to":461}} {"id":100015887,"name":"ResolveBindAddress","signature":"func ResolveBindAddress(bindAddress net.IP) (net.IP, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/interface.go","code":"// ResolveBindAddress returns the IP address of a daemon, based on the given bindAddress:\n// If bindAddress is unset, it returns the host's default IP, as with ChooseHostInterface().\n// If bindAddress is unspecified or loopback, it returns the default IP of the same\n// address family as bindAddress.\n// Otherwise, it just returns bindAddress.\nfunc ResolveBindAddress(bindAddress net.IP) (net.IP, error) {\n\taddressFamilies := preferIPv4\n\tif bindAddress != nil \u0026\u0026 memberOf(bindAddress, familyIPv6) {\n\t\taddressFamilies = preferIPv6\n\t}\n\n\tif bindAddress == nil || bindAddress.IsUnspecified() || bindAddress.IsLoopback() {\n\t\thostIP, err := chooseHostInterface(addressFamilies)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbindAddress = hostIP\n\t}\n\treturn bindAddress, nil\n}","line":{"from":463,"to":482}} {"id":100015888,"name":"ChooseBindAddressForInterface","signature":"func ChooseBindAddressForInterface(intfName string) (net.IP, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/interface.go","code":"// ChooseBindAddressForInterface choose a global IP for a specific interface, with priority given to IPv4.\n// This is required in case of network setups where default routes are present, but network\n// interfaces use only link-local addresses (e.g. as described in RFC5549).\n// e.g when using BGP to announce a host IP over link-local ip addresses and this ip address is attached to the lo interface.\nfunc ChooseBindAddressForInterface(intfName string) (net.IP, error) {\n\tvar nw networkInterfacer = networkInterface{}\n\tfor _, family := range preferIPv4 {\n\t\tip, err := getIPFromInterface(intfName, family, nw)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif ip != nil {\n\t\t\treturn ip, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"unable to select an IP from %s network interface\", intfName)\n}","line":{"from":484,"to":500}} {"id":100015889,"name":"Contains","signature":"func (pr *PortRange) Contains(p int) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/net/port_range.go","code":"// Contains tests whether a given port falls within the PortRange.\nfunc (pr *PortRange) Contains(p int) bool {\n\treturn (p \u003e= pr.Base) \u0026\u0026 ((p - pr.Base) \u003c pr.Size)\n}","line":{"from":32,"to":35}} {"id":100015890,"name":"String","signature":"func (pr PortRange) String() string","file":"staging/src/k8s.io/apimachinery/pkg/util/net/port_range.go","code":"// String converts the PortRange to a string representation, which can be\n// parsed by PortRange.Set or ParsePortRange.\nfunc (pr PortRange) String() string {\n\tif pr.Size == 0 {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(\"%d-%d\", pr.Base, pr.Base+pr.Size-1)\n}","line":{"from":37,"to":44}} {"id":100015891,"name":"Set","signature":"func (pr *PortRange) Set(value string) error","file":"staging/src/k8s.io/apimachinery/pkg/util/net/port_range.go","code":"// Set parses a string of the form \"value\", \"min-max\", or \"min+offset\", inclusive at both ends, and\n// sets the PortRange from it. This is part of the flag.Value and pflag.Value\n// interfaces.\nfunc (pr *PortRange) Set(value string) error {\n\tconst (\n\t\tSinglePortNotation = 1 \u003c\u003c iota\n\t\tHyphenNotation\n\t\tPlusNotation\n\t)\n\n\tvalue = strings.TrimSpace(value)\n\thyphenIndex := strings.Index(value, \"-\")\n\tplusIndex := strings.Index(value, \"+\")\n\n\tif value == \"\" {\n\t\tpr.Base = 0\n\t\tpr.Size = 0\n\t\treturn nil\n\t}\n\n\tvar err error\n\tvar low, high int\n\tvar notation int\n\n\tif plusIndex == -1 \u0026\u0026 hyphenIndex == -1 {\n\t\tnotation |= SinglePortNotation\n\t}\n\tif hyphenIndex != -1 {\n\t\tnotation |= HyphenNotation\n\t}\n\tif plusIndex != -1 {\n\t\tnotation |= PlusNotation\n\t}\n\n\tswitch notation {\n\tcase SinglePortNotation:\n\t\tvar port int\n\t\tport, err = strconv.Atoi(value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlow = port\n\t\thigh = port\n\tcase HyphenNotation:\n\t\tlow, err = strconv.Atoi(value[:hyphenIndex])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thigh, err = strconv.Atoi(value[hyphenIndex+1:])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase PlusNotation:\n\t\tvar offset int\n\t\tlow, err = strconv.Atoi(value[:plusIndex])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\toffset, err = strconv.Atoi(value[plusIndex+1:])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thigh = low + offset\n\tdefault:\n\t\treturn fmt.Errorf(\"unable to parse port range: %s\", value)\n\t}\n\n\tif low \u003e 65535 || high \u003e 65535 {\n\t\treturn fmt.Errorf(\"the port range cannot be greater than 65535: %s\", value)\n\t}\n\n\tif high \u003c low {\n\t\treturn fmt.Errorf(\"end port cannot be less than start port: %s\", value)\n\t}\n\n\tpr.Base = low\n\tpr.Size = 1 + high - low\n\treturn nil\n}","line":{"from":46,"to":124}} {"id":100015892,"name":"Type","signature":"func (*PortRange) Type() string","file":"staging/src/k8s.io/apimachinery/pkg/util/net/port_range.go","code":"// Type returns a descriptive string about this type. This is part of the\n// pflag.Value interface.\nfunc (*PortRange) Type() string {\n\treturn \"portRange\"\n}","line":{"from":126,"to":130}} {"id":100015893,"name":"ParsePortRange","signature":"func ParsePortRange(value string) (*PortRange, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/port_range.go","code":"// ParsePortRange parses a string of the form \"min-max\", inclusive at both\n// ends, and initializes a new PortRange from it.\nfunc ParsePortRange(value string) (*PortRange, error) {\n\tpr := \u0026PortRange{}\n\terr := pr.Set(value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn pr, nil\n}","line":{"from":132,"to":141}} {"id":100015894,"name":"ParsePortRangeOrDie","signature":"func ParsePortRangeOrDie(value string) *PortRange","file":"staging/src/k8s.io/apimachinery/pkg/util/net/port_range.go","code":"func ParsePortRangeOrDie(value string) *PortRange {\n\tpr, err := ParsePortRange(value)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"couldn't parse port range %q: %v\", value, err))\n\t}\n\treturn pr\n}","line":{"from":143,"to":149}} {"id":100015895,"name":"SplitSchemeNamePort","signature":"func SplitSchemeNamePort(id string) (scheme, name, port string, valid bool)","file":"staging/src/k8s.io/apimachinery/pkg/util/net/port_split.go","code":"// SplitSchemeNamePort takes a string of the following forms:\n// - \"\u003cname\u003e\", returns \"\", \"\u003cname\u003e\",\"\", true\n// - \"\u003cname\u003e:\u003cport\u003e\", returns \"\", \"\u003cname\u003e\",\"\u003cport\u003e\",true\n// - \"\u003cscheme\u003e:\u003cname\u003e:\u003cport\u003e\", returns \"\u003cscheme\u003e\",\"\u003cname\u003e\",\"\u003cport\u003e\",true\n//\n// Name must be non-empty or valid will be returned false.\n// Scheme must be \"http\" or \"https\" if specified\n// Port is returned as a string, and it is not required to be numeric (could be\n// used for a named port, for example).\nfunc SplitSchemeNamePort(id string) (scheme, name, port string, valid bool) {\n\tparts := strings.Split(id, \":\")\n\tswitch len(parts) {\n\tcase 1:\n\t\tname = parts[0]\n\tcase 2:\n\t\tname = parts[0]\n\t\tport = parts[1]\n\tcase 3:\n\t\tscheme = parts[0]\n\t\tname = parts[1]\n\t\tport = parts[2]\n\tdefault:\n\t\treturn \"\", \"\", \"\", false\n\t}\n\n\tif len(name) \u003e 0 \u0026\u0026 validSchemes.Has(scheme) {\n\t\treturn scheme, name, port, true\n\t} else {\n\t\treturn \"\", \"\", \"\", false\n\t}\n}","line":{"from":27,"to":57}} {"id":100015896,"name":"JoinSchemeNamePort","signature":"func JoinSchemeNamePort(scheme, name, port string) string","file":"staging/src/k8s.io/apimachinery/pkg/util/net/port_split.go","code":"// JoinSchemeNamePort returns a string that specifies the scheme, name, and port:\n// - \"\u003cname\u003e\"\n// - \"\u003cname\u003e:\u003cport\u003e\"\n// - \"\u003cscheme\u003e:\u003cname\u003e:\u003cport\u003e\"\n//\n// None of the parameters may contain a ':' character\n// Name is required\n// Scheme must be \"\", \"http\", or \"https\"\nfunc JoinSchemeNamePort(scheme, name, port string) string {\n\tif len(scheme) \u003e 0 {\n\t\t// Must include three segments to specify scheme\n\t\treturn scheme + \":\" + name + \":\" + port\n\t}\n\tif len(port) \u003e 0 {\n\t\t// Must include two segments to specify port\n\t\treturn name + \":\" + port\n\t}\n\t// Return name alone\n\treturn name\n}","line":{"from":59,"to":78}} {"id":100015897,"name":"IPNetEqual","signature":"func IPNetEqual(ipnet1, ipnet2 *net.IPNet) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/net/util.go","code":"// IPNetEqual checks if the two input IPNets are representing the same subnet.\n// For example,\n//\n//\t10.0.0.1/24 and 10.0.0.0/24 are the same subnet.\n//\t10.0.0.1/24 and 10.0.0.0/25 are not the same subnet.\nfunc IPNetEqual(ipnet1, ipnet2 *net.IPNet) bool {\n\tif ipnet1 == nil || ipnet2 == nil {\n\t\treturn false\n\t}\n\tif reflect.DeepEqual(ipnet1.Mask, ipnet2.Mask) \u0026\u0026 ipnet1.Contains(ipnet2.IP) \u0026\u0026 ipnet2.Contains(ipnet1.IP) {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":26,"to":39}} {"id":100015898,"name":"IsConnectionReset","signature":"func IsConnectionReset(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/net/util.go","code":"// Returns if the given err is \"connection reset by peer\" error.\nfunc IsConnectionReset(err error) bool {\n\tvar errno syscall.Errno\n\tif errors.As(err, \u0026errno) {\n\t\treturn errno == syscall.ECONNRESET\n\t}\n\treturn false\n}","line":{"from":41,"to":48}} {"id":100015899,"name":"IsConnectionRefused","signature":"func IsConnectionRefused(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/net/util.go","code":"// Returns if the given err is \"connection refused\" error\nfunc IsConnectionRefused(err error) bool {\n\tvar errno syscall.Errno\n\tif errors.As(err, \u0026errno) {\n\t\treturn errno == syscall.ECONNREFUSED\n\t}\n\treturn false\n}","line":{"from":50,"to":57}} {"id":100015900,"name":"dialURL","signature":"func dialURL(ctx context.Context, url *url.URL, transport http.RoundTripper) (net.Conn, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/dial.go","code":"// dialURL will dial the specified URL using the underlying dialer held by the passed\n// RoundTripper. The primary use of this method is to support proxying upgradable connections.\n// For this reason this method will prefer to negotiate http/1.1 if the URL scheme is https.\n// If you wish to ensure ALPN negotiates http2 then set NextProto=[]string{\"http2\"} in the\n// TLSConfig of the http.Transport\nfunc dialURL(ctx context.Context, url *url.URL, transport http.RoundTripper) (net.Conn, error) {\n\tdialAddr := netutil.CanonicalAddr(url)\n\n\tdialer, err := utilnet.DialerFor(transport)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Unable to unwrap transport %T to get dialer: %v\", transport, err)\n\t}\n\n\tswitch url.Scheme {\n\tcase \"http\":\n\t\tif dialer != nil {\n\t\t\treturn dialer(ctx, \"tcp\", dialAddr)\n\t\t}\n\t\tvar d net.Dialer\n\t\treturn d.DialContext(ctx, \"tcp\", dialAddr)\n\tcase \"https\":\n\t\t// Get the tls config from the transport if we recognize it\n\t\ttlsConfig, err := utilnet.TLSClientConfig(transport)\n\t\tif err != nil {\n\t\t\tklog.V(5).Infof(\"Unable to unwrap transport %T to get at TLS config: %v\", transport, err)\n\t\t}\n\n\t\tif dialer != nil {\n\t\t\t// We have a dialer; use it to open the connection, then\n\t\t\t// create a tls client using the connection.\n\t\t\tnetConn, err := dialer(ctx, \"tcp\", dialAddr)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif tlsConfig == nil {\n\t\t\t\t// tls.Client requires non-nil config\n\t\t\t\tklog.Warning(\"using custom dialer with no TLSClientConfig. Defaulting to InsecureSkipVerify\")\n\t\t\t\t// tls.Handshake() requires ServerName or InsecureSkipVerify\n\t\t\t\ttlsConfig = \u0026tls.Config{\n\t\t\t\t\tInsecureSkipVerify: true,\n\t\t\t\t}\n\t\t\t} else if len(tlsConfig.ServerName) == 0 \u0026\u0026 !tlsConfig.InsecureSkipVerify {\n\t\t\t\t// tls.HandshakeContext() requires ServerName or InsecureSkipVerify\n\t\t\t\t// infer the ServerName from the hostname we're connecting to.\n\t\t\t\tinferredHost := dialAddr\n\t\t\t\tif host, _, err := net.SplitHostPort(dialAddr); err == nil {\n\t\t\t\t\tinferredHost = host\n\t\t\t\t}\n\t\t\t\t// Make a copy to avoid polluting the provided config\n\t\t\t\ttlsConfigCopy := tlsConfig.Clone()\n\t\t\t\ttlsConfigCopy.ServerName = inferredHost\n\t\t\t\ttlsConfig = tlsConfigCopy\n\t\t\t}\n\n\t\t\t// Since this method is primarily used within a \"Connection: Upgrade\" call we assume the caller is\n\t\t\t// going to write HTTP/1.1 request to the wire. http2 should not be allowed in the TLSConfig.NextProtos,\n\t\t\t// so we explicitly set that here. We only do this check if the TLSConfig support http/1.1.\n\t\t\tif supportsHTTP11(tlsConfig.NextProtos) {\n\t\t\t\ttlsConfig = tlsConfig.Clone()\n\t\t\t\ttlsConfig.NextProtos = []string{\"http/1.1\"}\n\t\t\t}\n\n\t\t\ttlsConn := tls.Client(netConn, tlsConfig)\n\t\t\tif err := tlsConn.HandshakeContext(ctx); err != nil {\n\t\t\t\tnetConn.Close()\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn tlsConn, nil\n\t\t} else {\n\t\t\t// Dial.\n\t\t\ttlsDialer := tls.Dialer{\n\t\t\t\tConfig: tlsConfig,\n\t\t\t}\n\t\t\treturn tlsDialer.DialContext(ctx, \"tcp\", dialAddr)\n\t\t}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown scheme: %s\", url.Scheme)\n\t}\n}","line":{"from":32,"to":110}} {"id":100015901,"name":"supportsHTTP11","signature":"func supportsHTTP11(nextProtos []string) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/dial.go","code":"func supportsHTTP11(nextProtos []string) bool {\n\tif len(nextProtos) == 0 {\n\t\treturn true\n\t}\n\tfor _, proto := range nextProtos {\n\t\tif proto == \"http/1.1\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":112,"to":122}} {"id":100015902,"name":"RoundTrip","signature":"func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/transport.go","code":"// RoundTrip implements the http.RoundTripper interface\nfunc (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {\n\t// Add reverse proxy headers.\n\tforwardedURI := path.Join(t.PathPrepend, req.URL.EscapedPath())\n\tif strings.HasSuffix(req.URL.Path, \"/\") {\n\t\tforwardedURI = forwardedURI + \"/\"\n\t}\n\treq.Header.Set(\"X-Forwarded-Uri\", forwardedURI)\n\tif len(t.Host) \u003e 0 {\n\t\treq.Header.Set(\"X-Forwarded-Host\", t.Host)\n\t}\n\tif len(t.Scheme) \u003e 0 {\n\t\treq.Header.Set(\"X-Forwarded-Proto\", t.Scheme)\n\t}\n\n\trt := t.RoundTripper\n\tif rt == nil {\n\t\trt = http.DefaultTransport\n\t}\n\tresp, err := rt.RoundTrip(req)\n\n\tif err != nil {\n\t\treturn nil, errors.NewServiceUnavailable(fmt.Sprintf(\"error trying to reach service: %v\", err))\n\t}\n\n\tif redirect := resp.Header.Get(\"Location\"); redirect != \"\" {\n\t\ttargetURL, err := url.Parse(redirect)\n\t\tif err != nil {\n\t\t\treturn nil, errors.NewInternalError(fmt.Errorf(\"error trying to parse Location header: %v\", err))\n\t\t}\n\t\tresp.Header.Set(\"Location\", t.rewriteURL(targetURL, req.URL, req.Host))\n\t\treturn resp, nil\n\t}\n\n\tcType := resp.Header.Get(\"Content-Type\")\n\tcType = strings.TrimSpace(strings.SplitN(cType, \";\", 2)[0])\n\tif cType != \"text/html\" {\n\t\t// Do nothing, simply pass through\n\t\treturn resp, nil\n\t}\n\n\treturn t.rewriteResponse(req, resp)\n}","line":{"from":84,"to":126}} {"id":100015903,"name":"WrappedRoundTripper","signature":"func (rt *Transport) WrappedRoundTripper() http.RoundTripper","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/transport.go","code":"func (rt *Transport) WrappedRoundTripper() http.RoundTripper {\n\treturn rt.RoundTripper\n}","line":{"from":130,"to":132}} {"id":100015904,"name":"rewriteURL","signature":"func (t *Transport) rewriteURL(url *url.URL, sourceURL *url.URL, sourceRequestHost string) string","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/transport.go","code":"// rewriteURL rewrites a single URL to go through the proxy, if the URL refers\n// to the same host as sourceURL, which is the page on which the target URL\n// occurred, or if the URL matches the sourceRequestHost.\nfunc (t *Transport) rewriteURL(url *url.URL, sourceURL *url.URL, sourceRequestHost string) string {\n\t// Example:\n\t// When API server processes a proxy request to a service (e.g. /api/v1/namespace/foo/service/bar/proxy/),\n\t// the sourceURL.Host (i.e. req.URL.Host) is the endpoint IP address of the service. The\n\t// sourceRequestHost (i.e. req.Host) is the Host header that specifies the host on which the\n\t// URL is sought, which can be different from sourceURL.Host. For example, if user sends the\n\t// request through \"kubectl proxy\" locally (i.e. localhost:8001/api/v1/namespace/foo/service/bar/proxy/),\n\t// sourceRequestHost is \"localhost:8001\".\n\t//\n\t// If the service's response URL contains non-empty host, and url.Host is equal to either sourceURL.Host\n\t// or sourceRequestHost, we should not consider the returned URL to be a completely different host.\n\t// It's the API server's responsibility to rewrite a same-host-and-absolute-path URL and append the\n\t// necessary URL prefix (i.e. /api/v1/namespace/foo/service/bar/proxy/).\n\tisDifferentHost := url.Host != \"\" \u0026\u0026 url.Host != sourceURL.Host \u0026\u0026 url.Host != sourceRequestHost\n\tisRelative := !strings.HasPrefix(url.Path, \"/\")\n\tif isDifferentHost || isRelative {\n\t\treturn url.String()\n\t}\n\n\t// Do not rewrite scheme and host if the Transport has empty scheme and host\n\t// when targetURL already contains the sourceRequestHost\n\tif !(url.Host == sourceRequestHost \u0026\u0026 t.Scheme == \"\" \u0026\u0026 t.Host == \"\") {\n\t\turl.Scheme = t.Scheme\n\t\turl.Host = t.Host\n\t}\n\n\torigPath := url.Path\n\t// Do not rewrite URL if the sourceURL already contains the necessary prefix.\n\tif strings.HasPrefix(url.Path, t.PathPrepend) {\n\t\treturn url.String()\n\t}\n\turl.Path = path.Join(t.PathPrepend, url.Path)\n\tif strings.HasSuffix(origPath, \"/\") {\n\t\t// Add back the trailing slash, which was stripped by path.Join().\n\t\turl.Path += \"/\"\n\t}\n\n\treturn url.String()\n}","line":{"from":134,"to":175}} {"id":100015905,"name":"rewriteHTML","signature":"func rewriteHTML(reader io.Reader, writer io.Writer, urlRewriter func(*url.URL) string) error","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/transport.go","code":"// rewriteHTML scans the HTML for tags with url-valued attributes, and updates\n// those values with the urlRewriter function. The updated HTML is output to the\n// writer.\nfunc rewriteHTML(reader io.Reader, writer io.Writer, urlRewriter func(*url.URL) string) error {\n\t// Note: This assumes the content is UTF-8.\n\ttokenizer := html.NewTokenizer(reader)\n\n\tvar err error\n\tfor err == nil {\n\t\ttokenType := tokenizer.Next()\n\t\tswitch tokenType {\n\t\tcase html.ErrorToken:\n\t\t\terr = tokenizer.Err()\n\t\tcase html.StartTagToken, html.SelfClosingTagToken:\n\t\t\ttoken := tokenizer.Token()\n\t\t\tif urlAttrs, ok := atomsToAttrs[token.DataAtom]; ok {\n\t\t\t\tfor i, attr := range token.Attr {\n\t\t\t\t\tif urlAttrs.Has(attr.Key) {\n\t\t\t\t\t\turl, err := url.Parse(attr.Val)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t// Do not rewrite the URL if it isn't valid. It is intended not\n\t\t\t\t\t\t\t// to error here to prevent the inability to understand the\n\t\t\t\t\t\t\t// content of the body to cause a fatal error.\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttoken.Attr[i].Val = urlRewriter(url)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t_, err = writer.Write([]byte(token.String()))\n\t\tdefault:\n\t\t\t_, err = writer.Write(tokenizer.Raw())\n\t\t}\n\t}\n\tif err != io.EOF {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":177,"to":215}} {"id":100015906,"name":"rewriteResponse","signature":"func (t *Transport) rewriteResponse(req *http.Request, resp *http.Response) (*http.Response, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/transport.go","code":"// rewriteResponse modifies an HTML response by updating absolute links referring\n// to the original host to instead refer to the proxy transport.\nfunc (t *Transport) rewriteResponse(req *http.Request, resp *http.Response) (*http.Response, error) {\n\torigBody := resp.Body\n\tdefer origBody.Close()\n\n\tnewContent := \u0026bytes.Buffer{}\n\tvar reader io.Reader = origBody\n\tvar writer io.Writer = newContent\n\tencoding := resp.Header.Get(\"Content-Encoding\")\n\tswitch encoding {\n\tcase \"gzip\":\n\t\tvar err error\n\t\treader, err = gzip.NewReader(reader)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"errorf making gzip reader: %v\", err)\n\t\t}\n\t\tgzw := gzip.NewWriter(writer)\n\t\tdefer gzw.Close()\n\t\twriter = gzw\n\tcase \"deflate\":\n\t\tvar err error\n\t\treader = flate.NewReader(reader)\n\t\tflw, err := flate.NewWriter(writer, flate.BestCompression)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"errorf making flate writer: %v\", err)\n\t\t}\n\t\tdefer func() {\n\t\t\tflw.Close()\n\t\t\tflw.Flush()\n\t\t}()\n\t\twriter = flw\n\tcase \"\":\n\t\t// This is fine\n\tdefault:\n\t\t// Some encoding we don't understand-- don't try to parse this\n\t\tklog.Errorf(\"Proxy encountered encoding %v for text/html; can't understand this so not fixing links.\", encoding)\n\t\treturn resp, nil\n\t}\n\n\turlRewriter := func(targetUrl *url.URL) string {\n\t\treturn t.rewriteURL(targetUrl, req.URL, req.Host)\n\t}\n\terr := rewriteHTML(reader, writer, urlRewriter)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to rewrite URLs: %v\", err)\n\t\treturn resp, err\n\t}\n\n\tresp.Body = ioutil.NopCloser(newContent)\n\t// Update header node with new content-length\n\t// TODO: Remove any hash/signature headers here?\n\tresp.Header.Del(\"Content-Length\")\n\tresp.ContentLength = int64(newContent.Len())\n\n\treturn resp, err\n}","line":{"from":217,"to":273}} {"id":100015907,"name":"NewErrorResponder","signature":"func NewErrorResponder(r SimpleErrorResponder) ErrorResponder","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.go","code":"func NewErrorResponder(r SimpleErrorResponder) ErrorResponder {\n\treturn simpleResponder{r}\n}","line":{"from":104,"to":106}} {"id":100015908,"name":"Error","signature":"func (r simpleResponder) Error(w http.ResponseWriter, req *http.Request, err error)","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.go","code":"func (r simpleResponder) Error(w http.ResponseWriter, req *http.Request, err error) {\n\tr.responder.Error(err)\n}","line":{"from":112,"to":114}} {"id":100015909,"name":"WrappedRoundTripper","signature":"func (rt *upgradeRequestRoundTripper) WrappedRoundTripper() http.RoundTripper","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.go","code":"// WrappedRoundTripper returns the round tripper that a caller would use.\nfunc (rt *upgradeRequestRoundTripper) WrappedRoundTripper() http.RoundTripper {\n\treturn rt.RoundTripper\n}","line":{"from":127,"to":130}} {"id":100015910,"name":"WrapRequest","signature":"func (rt *upgradeRequestRoundTripper) WrapRequest(req *http.Request) (*http.Request, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.go","code":"// WriteToRequest calls the nested upgrader and then copies the returned request\n// fields onto the passed request.\nfunc (rt *upgradeRequestRoundTripper) WrapRequest(req *http.Request) (*http.Request, error) {\n\tresp, err := rt.upgrader.RoundTrip(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp.Request, nil\n}","line":{"from":132,"to":140}} {"id":100015911,"name":"RoundTrip","signature":"func (onewayRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.go","code":"// RoundTrip returns a simple 200 OK response that captures the provided request.\nfunc (onewayRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {\n\treturn \u0026http.Response{\n\t\tStatus: \"200 OK\",\n\t\tStatusCode: http.StatusOK,\n\t\tBody: ioutil.NopCloser(\u0026bytes.Buffer{}),\n\t\tRequest: req,\n\t}, nil\n}","line":{"from":146,"to":154}} {"id":100015912,"name":"NewUpgradeRequestRoundTripper","signature":"func NewUpgradeRequestRoundTripper(connection, request http.RoundTripper) UpgradeRequestRoundTripper","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.go","code":"// NewUpgradeRequestRoundTripper takes two round trippers - one for the underlying TCP connection, and\n// one that is able to write headers to an HTTP request. The request rt is used to set the request headers\n// and that is written to the underlying connection rt.\nfunc NewUpgradeRequestRoundTripper(connection, request http.RoundTripper) UpgradeRequestRoundTripper {\n\treturn \u0026upgradeRequestRoundTripper{\n\t\tRoundTripper: connection,\n\t\tupgrader: request,\n\t}\n}","line":{"from":160,"to":168}} {"id":100015913,"name":"normalizeLocation","signature":"func normalizeLocation(location *url.URL) *url.URL","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.go","code":"// normalizeLocation returns the result of parsing the full URL, with scheme set to http if missing\nfunc normalizeLocation(location *url.URL) *url.URL {\n\tnormalized, _ := url.Parse(location.String())\n\tif len(normalized.Scheme) == 0 {\n\t\tnormalized.Scheme = \"http\"\n\t}\n\treturn normalized\n}","line":{"from":170,"to":177}} {"id":100015914,"name":"NewUpgradeAwareHandler","signature":"func NewUpgradeAwareHandler(location *url.URL, transport http.RoundTripper, wrapTransport, upgradeRequired bool, responder ErrorResponder) *UpgradeAwareHandler","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.go","code":"// NewUpgradeAwareHandler creates a new proxy handler with a default flush interval. Responder is required for returning\n// errors to the caller.\nfunc NewUpgradeAwareHandler(location *url.URL, transport http.RoundTripper, wrapTransport, upgradeRequired bool, responder ErrorResponder) *UpgradeAwareHandler {\n\treturn \u0026UpgradeAwareHandler{\n\t\tLocation: normalizeLocation(location),\n\t\tTransport: transport,\n\t\tWrapTransport: wrapTransport,\n\t\tUpgradeRequired: upgradeRequired,\n\t\tFlushInterval: defaultFlushInterval,\n\t\tResponder: responder,\n\t}\n}","line":{"from":179,"to":190}} {"id":100015915,"name":"proxyRedirectsforRootPath","signature":"func proxyRedirectsforRootPath(path string, w http.ResponseWriter, req *http.Request) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.go","code":"func proxyRedirectsforRootPath(path string, w http.ResponseWriter, req *http.Request) bool {\n\tredirect := false\n\tmethod := req.Method\n\n\t// From pkg/genericapiserver/endpoints/handlers/proxy.go#ServeHTTP:\n\t// Redirect requests with an empty path to a location that ends with a '/'\n\t// This is essentially a hack for https://issue.k8s.io/4958.\n\t// Note: Keep this code after tryUpgrade to not break that flow.\n\tif len(path) == 0 \u0026\u0026 (method == http.MethodGet || method == http.MethodHead) {\n\t\tvar queryPart string\n\t\tif len(req.URL.RawQuery) \u003e 0 {\n\t\t\tqueryPart = \"?\" + req.URL.RawQuery\n\t\t}\n\t\tw.Header().Set(\"Location\", req.URL.Path+\"/\"+queryPart)\n\t\tw.WriteHeader(http.StatusMovedPermanently)\n\t\tredirect = true\n\t}\n\treturn redirect\n}","line":{"from":192,"to":210}} {"id":100015916,"name":"ServeHTTP","signature":"func (h *UpgradeAwareHandler) ServeHTTP(w http.ResponseWriter, req *http.Request)","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.go","code":"// ServeHTTP handles the proxy request\nfunc (h *UpgradeAwareHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tif h.tryUpgrade(w, req) {\n\t\treturn\n\t}\n\tif h.UpgradeRequired {\n\t\th.Responder.Error(w, req, errors.NewBadRequest(\"Upgrade request required\"))\n\t\treturn\n\t}\n\n\tloc := *h.Location\n\tloc.RawQuery = req.URL.RawQuery\n\n\t// If original request URL ended in '/', append a '/' at the end of the\n\t// of the proxy URL\n\tif !strings.HasSuffix(loc.Path, \"/\") \u0026\u0026 strings.HasSuffix(req.URL.Path, \"/\") {\n\t\tloc.Path += \"/\"\n\t}\n\n\tproxyRedirect := proxyRedirectsforRootPath(loc.Path, w, req)\n\tif proxyRedirect {\n\t\treturn\n\t}\n\n\tif h.Transport == nil || h.WrapTransport {\n\t\th.Transport = h.defaultProxyTransport(req.URL, h.Transport)\n\t}\n\n\t// WithContext creates a shallow clone of the request with the same context.\n\tnewReq := req.WithContext(req.Context())\n\tnewReq.Header = utilnet.CloneHeader(req.Header)\n\tif !h.UseRequestLocation {\n\t\tnewReq.URL = \u0026loc\n\t}\n\tif h.UseLocationHost {\n\t\t// exchanging req.Host with the backend location is necessary for backends that act on the HTTP host header (e.g. API gateways),\n\t\t// because req.Host has preference over req.URL.Host in filling this header field\n\t\tnewReq.Host = h.Location.Host\n\t}\n\n\t// create the target location to use for the reverse proxy\n\treverseProxyLocation := \u0026url.URL{Scheme: h.Location.Scheme, Host: h.Location.Host}\n\tif h.AppendLocationPath {\n\t\treverseProxyLocation.Path = h.Location.Path\n\t}\n\n\tproxy := httputil.NewSingleHostReverseProxy(reverseProxyLocation)\n\tproxy.Transport = h.Transport\n\tproxy.FlushInterval = h.FlushInterval\n\tproxy.ErrorLog = log.New(noSuppressPanicError{}, \"\", log.LstdFlags)\n\tif h.RejectForwardingRedirects {\n\t\toldModifyResponse := proxy.ModifyResponse\n\t\tproxy.ModifyResponse = func(response *http.Response) error {\n\t\t\tcode := response.StatusCode\n\t\t\tif code \u003e= 300 \u0026\u0026 code \u003c= 399 \u0026\u0026 len(response.Header.Get(\"Location\")) \u003e 0 {\n\t\t\t\t// close the original response\n\t\t\t\tresponse.Body.Close()\n\t\t\t\tmsg := \"the backend attempted to redirect this request, which is not permitted\"\n\t\t\t\t// replace the response\n\t\t\t\t*response = http.Response{\n\t\t\t\t\tStatusCode: http.StatusBadGateway,\n\t\t\t\t\tStatus: fmt.Sprintf(\"%d %s\", response.StatusCode, http.StatusText(response.StatusCode)),\n\t\t\t\t\tBody: io.NopCloser(strings.NewReader(msg)),\n\t\t\t\t\tContentLength: int64(len(msg)),\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif oldModifyResponse != nil {\n\t\t\t\t\tif err := oldModifyResponse(response); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\tif h.Responder != nil {\n\t\t// if an optional error interceptor/responder was provided wire it\n\t\t// the custom responder might be used for providing a unified error reporting\n\t\t// or supporting retry mechanisms by not sending non-fatal errors to the clients\n\t\tproxy.ErrorHandler = h.Responder.Error\n\t}\n\tproxy.ServeHTTP(w, newReq)\n}","line":{"from":212,"to":294}} {"id":100015917,"name":"Write","signature":"func (noSuppressPanicError) Write(p []byte) (n int, err error)","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.go","code":"func (noSuppressPanicError) Write(p []byte) (n int, err error) {\n\t// skip \"suppressing panic for copyResponse error in test; copy error\" error message\n\t// that ends up in CI tests on each kube-apiserver termination as noise and\n\t// everybody thinks this is fatal.\n\tif strings.Contains(string(p), \"suppressing panic\") {\n\t\treturn len(p), nil\n\t}\n\treturn os.Stderr.Write(p)\n}","line":{"from":298,"to":306}} {"id":100015918,"name":"tryUpgrade","signature":"func (h *UpgradeAwareHandler) tryUpgrade(w http.ResponseWriter, req *http.Request) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.go","code":"// tryUpgrade returns true if the request was handled.\nfunc (h *UpgradeAwareHandler) tryUpgrade(w http.ResponseWriter, req *http.Request) bool {\n\tif !httpstream.IsUpgradeRequest(req) {\n\t\tklog.V(6).Infof(\"Request was not an upgrade\")\n\t\treturn false\n\t}\n\n\tvar (\n\t\tbackendConn net.Conn\n\t\trawResponse []byte\n\t\terr error\n\t)\n\n\tlocation := *h.Location\n\tif h.UseRequestLocation {\n\t\tlocation = *req.URL\n\t\tlocation.Scheme = h.Location.Scheme\n\t\tlocation.Host = h.Location.Host\n\t\tif h.AppendLocationPath {\n\t\t\tlocation.Path = singleJoiningSlash(h.Location.Path, location.Path)\n\t\t}\n\t}\n\n\tclone := utilnet.CloneRequest(req)\n\t// Only append X-Forwarded-For in the upgrade path, since httputil.NewSingleHostReverseProxy\n\t// handles this in the non-upgrade path.\n\tutilnet.AppendForwardedForHeader(clone)\n\tklog.V(6).Infof(\"Connecting to backend proxy (direct dial) %s\\n Headers: %v\", \u0026location, clone.Header)\n\tif h.UseLocationHost {\n\t\tclone.Host = h.Location.Host\n\t}\n\tclone.URL = \u0026location\n\tbackendConn, err = h.DialForUpgrade(clone)\n\tif err != nil {\n\t\tklog.V(6).Infof(\"Proxy connection error: %v\", err)\n\t\th.Responder.Error(w, req, err)\n\t\treturn true\n\t}\n\tdefer backendConn.Close()\n\n\t// determine the http response code from the backend by reading from rawResponse+backendConn\n\tbackendHTTPResponse, headerBytes, err := getResponse(io.MultiReader(bytes.NewReader(rawResponse), backendConn))\n\tif err != nil {\n\t\tklog.V(6).Infof(\"Proxy connection error: %v\", err)\n\t\th.Responder.Error(w, req, err)\n\t\treturn true\n\t}\n\tif len(headerBytes) \u003e len(rawResponse) {\n\t\t// we read beyond the bytes stored in rawResponse, update rawResponse to the full set of bytes read from the backend\n\t\trawResponse = headerBytes\n\t}\n\n\t// If the backend did not upgrade the request, return an error to the client. If the response was\n\t// an error, the error is forwarded directly after the connection is hijacked. Otherwise, just\n\t// return a generic error here.\n\tif backendHTTPResponse.StatusCode != http.StatusSwitchingProtocols \u0026\u0026 backendHTTPResponse.StatusCode \u003c 400 {\n\t\terr := fmt.Errorf(\"invalid upgrade response: status code %d\", backendHTTPResponse.StatusCode)\n\t\tklog.Errorf(\"Proxy upgrade error: %v\", err)\n\t\th.Responder.Error(w, req, err)\n\t\treturn true\n\t}\n\n\t// Once the connection is hijacked, the ErrorResponder will no longer work, so\n\t// hijacking should be the last step in the upgrade.\n\trequestHijacker, ok := w.(http.Hijacker)\n\tif !ok {\n\t\tklog.V(6).Infof(\"Unable to hijack response writer: %T\", w)\n\t\th.Responder.Error(w, req, fmt.Errorf(\"request connection cannot be hijacked: %T\", w))\n\t\treturn true\n\t}\n\trequestHijackedConn, _, err := requestHijacker.Hijack()\n\tif err != nil {\n\t\tklog.V(6).Infof(\"Unable to hijack response: %v\", err)\n\t\th.Responder.Error(w, req, fmt.Errorf(\"error hijacking connection: %v\", err))\n\t\treturn true\n\t}\n\tdefer requestHijackedConn.Close()\n\n\tif backendHTTPResponse.StatusCode != http.StatusSwitchingProtocols {\n\t\t// If the backend did not upgrade the request, echo the response from the backend to the client and return, closing the connection.\n\t\tklog.V(6).Infof(\"Proxy upgrade error, status code %d\", backendHTTPResponse.StatusCode)\n\t\t// set read/write deadlines\n\t\tdeadline := time.Now().Add(10 * time.Second)\n\t\tbackendConn.SetReadDeadline(deadline)\n\t\trequestHijackedConn.SetWriteDeadline(deadline)\n\t\t// write the response to the client\n\t\terr := backendHTTPResponse.Write(requestHijackedConn)\n\t\tif err != nil \u0026\u0026 !strings.Contains(err.Error(), \"use of closed network connection\") {\n\t\t\tklog.Errorf(\"Error proxying data from backend to client: %v\", err)\n\t\t}\n\t\t// Indicate we handled the request\n\t\treturn true\n\t}\n\n\t// Forward raw response bytes back to client.\n\tif len(rawResponse) \u003e 0 {\n\t\tklog.V(6).Infof(\"Writing %d bytes to hijacked connection\", len(rawResponse))\n\t\tif _, err = requestHijackedConn.Write(rawResponse); err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"Error proxying response from backend to client: %v\", err))\n\t\t}\n\t}\n\n\t// Proxy the connection. This is bidirectional, so we need a goroutine\n\t// to copy in each direction. Once one side of the connection exits, we\n\t// exit the function which performs cleanup and in the process closes\n\t// the other half of the connection in the defer.\n\twriterComplete := make(chan struct{})\n\treaderComplete := make(chan struct{})\n\n\tgo func() {\n\t\tvar writer io.WriteCloser\n\t\tif h.MaxBytesPerSec \u003e 0 {\n\t\t\twriter = flowrate.NewWriter(backendConn, h.MaxBytesPerSec)\n\t\t} else {\n\t\t\twriter = backendConn\n\t\t}\n\t\t_, err := io.Copy(writer, requestHijackedConn)\n\t\tif err != nil \u0026\u0026 !strings.Contains(err.Error(), \"use of closed network connection\") {\n\t\t\tklog.Errorf(\"Error proxying data from client to backend: %v\", err)\n\t\t}\n\t\tclose(writerComplete)\n\t}()\n\n\tgo func() {\n\t\tvar reader io.ReadCloser\n\t\tif h.MaxBytesPerSec \u003e 0 {\n\t\t\treader = flowrate.NewReader(backendConn, h.MaxBytesPerSec)\n\t\t} else {\n\t\t\treader = backendConn\n\t\t}\n\t\t_, err := io.Copy(requestHijackedConn, reader)\n\t\tif err != nil \u0026\u0026 !strings.Contains(err.Error(), \"use of closed network connection\") {\n\t\t\tklog.Errorf(\"Error proxying data from backend to client: %v\", err)\n\t\t}\n\t\tclose(readerComplete)\n\t}()\n\n\t// Wait for one half the connection to exit. Once it does the defer will\n\t// clean up the other half of the connection.\n\tselect {\n\tcase \u003c-writerComplete:\n\tcase \u003c-readerComplete:\n\t}\n\tklog.V(6).Infof(\"Disconnecting from backend proxy %s\\n Headers: %v\", \u0026location, clone.Header)\n\n\treturn true\n}","line":{"from":308,"to":454}} {"id":100015919,"name":"singleJoiningSlash","signature":"func singleJoiningSlash(a, b string) string","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.go","code":"// FIXME: Taken from net/http/httputil/reverseproxy.go as singleJoiningSlash is not exported to be re-used.\n// See-also: https://github.com/golang/go/issues/44290\nfunc singleJoiningSlash(a, b string) string {\n\taslash := strings.HasSuffix(a, \"/\")\n\tbslash := strings.HasPrefix(b, \"/\")\n\tswitch {\n\tcase aslash \u0026\u0026 bslash:\n\t\treturn a + b[1:]\n\tcase !aslash \u0026\u0026 !bslash:\n\t\treturn a + \"/\" + b\n\t}\n\treturn a + b\n}","line":{"from":456,"to":468}} {"id":100015920,"name":"DialForUpgrade","signature":"func (h *UpgradeAwareHandler) DialForUpgrade(req *http.Request) (net.Conn, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.go","code":"func (h *UpgradeAwareHandler) DialForUpgrade(req *http.Request) (net.Conn, error) {\n\tif h.UpgradeTransport == nil {\n\t\treturn dial(req, h.Transport)\n\t}\n\tupdatedReq, err := h.UpgradeTransport.WrapRequest(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn dial(updatedReq, h.UpgradeTransport)\n}","line":{"from":470,"to":479}} {"id":100015921,"name":"getResponse","signature":"func getResponse(r io.Reader) (*http.Response, []byte, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.go","code":"// getResponseCode reads a http response from the given reader, returns the response,\n// the bytes read from the reader, and any error encountered\nfunc getResponse(r io.Reader) (*http.Response, []byte, error) {\n\trawResponse := bytes.NewBuffer(make([]byte, 0, 256))\n\t// Save the bytes read while reading the response headers into the rawResponse buffer\n\tresp, err := http.ReadResponse(bufio.NewReader(io.TeeReader(r, rawResponse)), nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\t// return the http response and the raw bytes consumed from the reader in the process\n\treturn resp, rawResponse.Bytes(), nil\n}","line":{"from":481,"to":492}} {"id":100015922,"name":"dial","signature":"func dial(req *http.Request, transport http.RoundTripper) (net.Conn, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.go","code":"// dial dials the backend at req.URL and writes req to it.\nfunc dial(req *http.Request, transport http.RoundTripper) (net.Conn, error) {\n\tconn, err := dialURL(req.Context(), req.URL, transport)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error dialing backend: %v\", err)\n\t}\n\n\tif err = req.Write(conn); err != nil {\n\t\tconn.Close()\n\t\treturn nil, fmt.Errorf(\"error sending request: %v\", err)\n\t}\n\n\treturn conn, err\n}","line":{"from":494,"to":507}} {"id":100015923,"name":"defaultProxyTransport","signature":"func (h *UpgradeAwareHandler) defaultProxyTransport(url *url.URL, internalTransport http.RoundTripper) http.RoundTripper","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.go","code":"func (h *UpgradeAwareHandler) defaultProxyTransport(url *url.URL, internalTransport http.RoundTripper) http.RoundTripper {\n\tscheme := url.Scheme\n\thost := url.Host\n\tsuffix := h.Location.Path\n\tif strings.HasSuffix(url.Path, \"/\") \u0026\u0026 !strings.HasSuffix(suffix, \"/\") {\n\t\tsuffix += \"/\"\n\t}\n\tpathPrepend := strings.TrimSuffix(url.Path, suffix)\n\trewritingTransport := \u0026Transport{\n\t\tScheme: scheme,\n\t\tHost: host,\n\t\tPathPrepend: pathPrepend,\n\t\tRoundTripper: internalTransport,\n\t}\n\treturn \u0026corsRemovingTransport{\n\t\tRoundTripper: rewritingTransport,\n\t}\n}","line":{"from":509,"to":526}} {"id":100015924,"name":"RoundTrip","signature":"func (rt *corsRemovingTransport) RoundTrip(req *http.Request) (*http.Response, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.go","code":"func (rt *corsRemovingTransport) RoundTrip(req *http.Request) (*http.Response, error) {\n\tresp, err := rt.RoundTripper.RoundTrip(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tremoveCORSHeaders(resp)\n\treturn resp, nil\n}","line":{"from":537,"to":544}} {"id":100015925,"name":"WrappedRoundTripper","signature":"func (rt *corsRemovingTransport) WrappedRoundTripper() http.RoundTripper","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.go","code":"func (rt *corsRemovingTransport) WrappedRoundTripper() http.RoundTripper {\n\treturn rt.RoundTripper\n}","line":{"from":546,"to":548}} {"id":100015926,"name":"removeCORSHeaders","signature":"func removeCORSHeaders(resp *http.Response)","file":"staging/src/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.go","code":"// removeCORSHeaders strip CORS headers sent from the backend\n// This should be called on all responses before returning\nfunc removeCORSHeaders(resp *http.Response) {\n\tresp.Header.Del(\"Access-Control-Allow-Credentials\")\n\tresp.Header.Del(\"Access-Control-Allow-Headers\")\n\tresp.Header.Del(\"Access-Control-Allow-Methods\")\n\tresp.Header.Del(\"Access-Control-Allow-Origin\")\n}","line":{"from":550,"to":557}} {"id":100015927,"name":"Int","signature":"func Int() int","file":"staging/src/k8s.io/apimachinery/pkg/util/rand/rand.go","code":"// Int returns a non-negative pseudo-random int.\nfunc Int() int {\n\trng.Lock()\n\tdefer rng.Unlock()\n\treturn rng.rand.Int()\n}","line":{"from":33,"to":38}} {"id":100015928,"name":"Intn","signature":"func Intn(max int) int","file":"staging/src/k8s.io/apimachinery/pkg/util/rand/rand.go","code":"// Intn generates an integer in range [0,max).\n// By design this should panic if input is invalid, \u003c= 0.\nfunc Intn(max int) int {\n\trng.Lock()\n\tdefer rng.Unlock()\n\treturn rng.rand.Intn(max)\n}","line":{"from":40,"to":46}} {"id":100015929,"name":"IntnRange","signature":"func IntnRange(min, max int) int","file":"staging/src/k8s.io/apimachinery/pkg/util/rand/rand.go","code":"// IntnRange generates an integer in range [min,max).\n// By design this should panic if input is invalid, \u003c= 0.\nfunc IntnRange(min, max int) int {\n\trng.Lock()\n\tdefer rng.Unlock()\n\treturn rng.rand.Intn(max-min) + min\n}","line":{"from":48,"to":54}} {"id":100015930,"name":"Int63nRange","signature":"func Int63nRange(min, max int64) int64","file":"staging/src/k8s.io/apimachinery/pkg/util/rand/rand.go","code":"// IntnRange generates an int64 integer in range [min,max).\n// By design this should panic if input is invalid, \u003c= 0.\nfunc Int63nRange(min, max int64) int64 {\n\trng.Lock()\n\tdefer rng.Unlock()\n\treturn rng.rand.Int63n(max-min) + min\n}","line":{"from":56,"to":62}} {"id":100015931,"name":"Seed","signature":"func Seed(seed int64)","file":"staging/src/k8s.io/apimachinery/pkg/util/rand/rand.go","code":"// Seed seeds the rng with the provided seed.\nfunc Seed(seed int64) {\n\trng.Lock()\n\tdefer rng.Unlock()\n\n\trng.rand = rand.New(rand.NewSource(seed))\n}","line":{"from":64,"to":70}} {"id":100015932,"name":"Perm","signature":"func Perm(n int) []int","file":"staging/src/k8s.io/apimachinery/pkg/util/rand/rand.go","code":"// Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n)\n// from the default Source.\nfunc Perm(n int) []int {\n\trng.Lock()\n\tdefer rng.Unlock()\n\treturn rng.rand.Perm(n)\n}","line":{"from":72,"to":78}} {"id":100015933,"name":"String","signature":"func String(n int) string","file":"staging/src/k8s.io/apimachinery/pkg/util/rand/rand.go","code":"// String generates a random alphanumeric string, without vowels, which is n\n// characters long. This will panic if n is less than zero.\n// How the random string is created:\n// - we generate random int63's\n// - from each int63, we are extracting multiple random letters by bit-shifting and masking\n// - if some index is out of range of alphanums we neglect it (unlikely to happen multiple times in a row)\nfunc String(n int) string {\n\tb := make([]byte, n)\n\trng.Lock()\n\tdefer rng.Unlock()\n\n\trandomInt63 := rng.rand.Int63()\n\tremaining := maxAlphanumsPerInt\n\tfor i := 0; i \u003c n; {\n\t\tif remaining == 0 {\n\t\t\trandomInt63, remaining = rng.rand.Int63(), maxAlphanumsPerInt\n\t\t}\n\t\tif idx := int(randomInt63 \u0026 alphanumsIdxMask); idx \u003c len(alphanums) {\n\t\t\tb[i] = alphanums[idx]\n\t\t\ti++\n\t\t}\n\t\trandomInt63 \u003e\u003e= alphanumsIdxBits\n\t\tremaining--\n\t}\n\treturn string(b)\n}","line":{"from":92,"to":117}} {"id":100015934,"name":"SafeEncodeString","signature":"func SafeEncodeString(s string) string","file":"staging/src/k8s.io/apimachinery/pkg/util/rand/rand.go","code":"// SafeEncodeString encodes s using the same characters as rand.String. This reduces the chances of bad words and\n// ensures that strings generated from hash functions appear consistent throughout the API.\nfunc SafeEncodeString(s string) string {\n\tr := make([]byte, len(s))\n\tfor i, b := range []rune(s) {\n\t\tr[i] = alphanums[(int(b) % len(alphanums))]\n\t}\n\treturn string(r)\n}","line":{"from":119,"to":127}} {"id":100015935,"name":"HandleCrash","signature":"func HandleCrash(additionalHandlers ...func(interface{}))","file":"staging/src/k8s.io/apimachinery/pkg/util/runtime/runtime.go","code":"// HandleCrash simply catches a crash and logs an error. Meant to be called via\n// defer. Additional context-specific handlers can be provided, and will be\n// called in case of panic. HandleCrash actually crashes, after calling the\n// handlers and logging the panic message.\n//\n// E.g., you can provide one or more additional handlers for something like shutting down go routines gracefully.\nfunc HandleCrash(additionalHandlers ...func(interface{})) {\n\tif r := recover(); r != nil {\n\t\tfor _, fn := range PanicHandlers {\n\t\t\tfn(r)\n\t\t}\n\t\tfor _, fn := range additionalHandlers {\n\t\t\tfn(r)\n\t\t}\n\t\tif ReallyCrash {\n\t\t\t// Actually proceed to panic.\n\t\t\tpanic(r)\n\t\t}\n\t}\n}","line":{"from":40,"to":59}} {"id":100015936,"name":"logPanic","signature":"func logPanic(r interface{})","file":"staging/src/k8s.io/apimachinery/pkg/util/runtime/runtime.go","code":"// logPanic logs the caller tree when a panic occurs (except in the special case of http.ErrAbortHandler).\nfunc logPanic(r interface{}) {\n\tif r == http.ErrAbortHandler {\n\t\t// honor the http.ErrAbortHandler sentinel panic value:\n\t\t// ErrAbortHandler is a sentinel panic value to abort a handler.\n\t\t// While any panic from ServeHTTP aborts the response to the client,\n\t\t// panicking with ErrAbortHandler also suppresses logging of a stack trace to the server's error log.\n\t\treturn\n\t}\n\n\t// Same as stdlib http server code. Manually allocate stack trace buffer size\n\t// to prevent excessively large logs\n\tconst size = 64 \u003c\u003c 10\n\tstacktrace := make([]byte, size)\n\tstacktrace = stacktrace[:runtime.Stack(stacktrace, false)]\n\tif _, ok := r.(string); ok {\n\t\tklog.Errorf(\"Observed a panic: %s\\n%s\", r, stacktrace)\n\t} else {\n\t\tklog.Errorf(\"Observed a panic: %#v (%v)\\n%s\", r, r, stacktrace)\n\t}\n}","line":{"from":61,"to":81}} {"id":100015937,"name":"HandleError","signature":"func HandleError(err error)","file":"staging/src/k8s.io/apimachinery/pkg/util/runtime/runtime.go","code":"// HandlerError is a method to invoke when a non-user facing piece of code cannot\n// return an error and needs to indicate it has been ignored. Invoking this method\n// is preferable to logging the error - the default behavior is to log but the\n// errors may be sent to a remote server for analysis.\nfunc HandleError(err error) {\n\t// this is sometimes called with a nil error. We probably shouldn't fail and should do nothing instead\n\tif err == nil {\n\t\treturn\n\t}\n\n\tfor _, fn := range ErrorHandlers {\n\t\tfn(err)\n\t}\n}","line":{"from":98,"to":111}} {"id":100015938,"name":"logError","signature":"func logError(err error)","file":"staging/src/k8s.io/apimachinery/pkg/util/runtime/runtime.go","code":"// logError prints an error with the call stack of the location it was reported\nfunc logError(err error) {\n\tklog.ErrorDepth(2, err)\n}","line":{"from":113,"to":116}} {"id":100015939,"name":"OnError","signature":"func (r *rudimentaryErrorBackoff) OnError(error)","file":"staging/src/k8s.io/apimachinery/pkg/util/runtime/runtime.go","code":"// OnError will block if it is called more often than the embedded period time.\n// This will prevent overly tight hot error loops.\nfunc (r *rudimentaryErrorBackoff) OnError(error) {\n\tr.lastErrorTimeLock.Lock()\n\tdefer r.lastErrorTimeLock.Unlock()\n\td := time.Since(r.lastErrorTime)\n\tif d \u003c r.minPeriod {\n\t\t// If the time moves backwards for any reason, do nothing\n\t\ttime.Sleep(r.minPeriod - d)\n\t}\n\tr.lastErrorTime = time.Now()\n}","line":{"from":126,"to":137}} {"id":100015940,"name":"GetCaller","signature":"func GetCaller() string","file":"staging/src/k8s.io/apimachinery/pkg/util/runtime/runtime.go","code":"// GetCaller returns the caller of the function that calls it.\nfunc GetCaller() string {\n\tvar pc [1]uintptr\n\truntime.Callers(3, pc[:])\n\tf := runtime.FuncForPC(pc[0])\n\tif f == nil {\n\t\treturn \"Unable to find caller\"\n\t}\n\treturn f.Name()\n}","line":{"from":139,"to":148}} {"id":100015941,"name":"RecoverFromPanic","signature":"func RecoverFromPanic(err *error)","file":"staging/src/k8s.io/apimachinery/pkg/util/runtime/runtime.go","code":"// RecoverFromPanic replaces the specified error with an error containing the\n// original error, and the call tree when a panic occurs. This enables error\n// handlers to handle errors and panics the same way.\nfunc RecoverFromPanic(err *error) {\n\tif r := recover(); r != nil {\n\t\t// Same as stdlib http server code. Manually allocate stack trace buffer size\n\t\t// to prevent excessively large logs\n\t\tconst size = 64 \u003c\u003c 10\n\t\tstacktrace := make([]byte, size)\n\t\tstacktrace = stacktrace[:runtime.Stack(stacktrace, false)]\n\n\t\t*err = fmt.Errorf(\n\t\t\t\"recovered from panic %q. (err=%v) Call stack:\\n%s\",\n\t\t\tr,\n\t\t\t*err,\n\t\t\tstacktrace)\n\t}\n}","line":{"from":150,"to":167}} {"id":100015942,"name":"Must","signature":"func Must(err error)","file":"staging/src/k8s.io/apimachinery/pkg/util/runtime/runtime.go","code":"// Must panics on non-nil errors. Useful to handling programmer level errors.\nfunc Must(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}","line":{"from":169,"to":174}} {"id":100015943,"name":"NewByte","signature":"func NewByte(items ...byte) Byte","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/byte.go","code":"// NewByte creates a Byte from a list of values.\nfunc NewByte(items ...byte) Byte {\n\treturn Byte(New[byte](items...))\n}","line":{"from":27,"to":30}} {"id":100015944,"name":"ByteKeySet","signature":"func ByteKeySet[T any](theMap map[byte]T) Byte","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/byte.go","code":"// ByteKeySet creates a Byte from a keys of a map[byte](? extends interface{}).\n// If the value passed in is not actually a map, this will panic.\nfunc ByteKeySet[T any](theMap map[byte]T) Byte {\n\treturn Byte(KeySet(theMap))\n}","line":{"from":32,"to":36}} {"id":100015945,"name":"Insert","signature":"func (s Byte) Insert(items ...byte) Byte","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/byte.go","code":"// Insert adds items to the set.\nfunc (s Byte) Insert(items ...byte) Byte {\n\treturn Byte(cast(s).Insert(items...))\n}","line":{"from":38,"to":41}} {"id":100015946,"name":"Delete","signature":"func (s Byte) Delete(items ...byte) Byte","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/byte.go","code":"// Delete removes all items from the set.\nfunc (s Byte) Delete(items ...byte) Byte {\n\treturn Byte(cast(s).Delete(items...))\n}","line":{"from":43,"to":46}} {"id":100015947,"name":"Has","signature":"func (s Byte) Has(item byte) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/byte.go","code":"// Has returns true if and only if item is contained in the set.\nfunc (s Byte) Has(item byte) bool {\n\treturn cast(s).Has(item)\n}","line":{"from":48,"to":51}} {"id":100015948,"name":"HasAll","signature":"func (s Byte) HasAll(items ...byte) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/byte.go","code":"// HasAll returns true if and only if all items are contained in the set.\nfunc (s Byte) HasAll(items ...byte) bool {\n\treturn cast(s).HasAll(items...)\n}","line":{"from":53,"to":56}} {"id":100015949,"name":"HasAny","signature":"func (s Byte) HasAny(items ...byte) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/byte.go","code":"// HasAny returns true if any items are contained in the set.\nfunc (s Byte) HasAny(items ...byte) bool {\n\treturn cast(s).HasAny(items...)\n}","line":{"from":58,"to":61}} {"id":100015950,"name":"Clone","signature":"func (s Byte) Clone() Byte","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/byte.go","code":"// Clone returns a new set which is a copy of the current set.\nfunc (s Byte) Clone() Byte {\n\treturn Byte(cast(s).Clone())\n}","line":{"from":63,"to":66}} {"id":100015951,"name":"Difference","signature":"func (s1 Byte) Difference(s2 Byte) Byte","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/byte.go","code":"// Difference returns a set of objects that are not in s2.\n// For example:\n// s1 = {a1, a2, a3}\n// s2 = {a1, a2, a4, a5}\n// s1.Difference(s2) = {a3}\n// s2.Difference(s1) = {a4, a5}\nfunc (s1 Byte) Difference(s2 Byte) Byte {\n\treturn Byte(cast(s1).Difference(cast(s2)))\n}","line":{"from":68,"to":76}} {"id":100015952,"name":"SymmetricDifference","signature":"func (s1 Byte) SymmetricDifference(s2 Byte) Byte","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/byte.go","code":"// SymmetricDifference returns a set of elements which are in either of the sets, but not in their intersection.\n// For example:\n// s1 = {a1, a2, a3}\n// s2 = {a1, a2, a4, a5}\n// s1.SymmetricDifference(s2) = {a3, a4, a5}\n// s2.SymmetricDifference(s1) = {a3, a4, a5}\nfunc (s1 Byte) SymmetricDifference(s2 Byte) Byte {\n\treturn Byte(cast(s1).SymmetricDifference(cast(s2)))\n}","line":{"from":78,"to":86}} {"id":100015953,"name":"Union","signature":"func (s1 Byte) Union(s2 Byte) Byte","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/byte.go","code":"// Union returns a new set which includes items in either s1 or s2.\n// For example:\n// s1 = {a1, a2}\n// s2 = {a3, a4}\n// s1.Union(s2) = {a1, a2, a3, a4}\n// s2.Union(s1) = {a1, a2, a3, a4}\nfunc (s1 Byte) Union(s2 Byte) Byte {\n\treturn Byte(cast(s1).Union(cast(s2)))\n}","line":{"from":88,"to":96}} {"id":100015954,"name":"Intersection","signature":"func (s1 Byte) Intersection(s2 Byte) Byte","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/byte.go","code":"// Intersection returns a new set which includes the item in BOTH s1 and s2\n// For example:\n// s1 = {a1, a2}\n// s2 = {a2, a3}\n// s1.Intersection(s2) = {a2}\nfunc (s1 Byte) Intersection(s2 Byte) Byte {\n\treturn Byte(cast(s1).Intersection(cast(s2)))\n}","line":{"from":98,"to":105}} {"id":100015955,"name":"IsSuperset","signature":"func (s1 Byte) IsSuperset(s2 Byte) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/byte.go","code":"// IsSuperset returns true if and only if s1 is a superset of s2.\nfunc (s1 Byte) IsSuperset(s2 Byte) bool {\n\treturn cast(s1).IsSuperset(cast(s2))\n}","line":{"from":107,"to":110}} {"id":100015956,"name":"Equal","signature":"func (s1 Byte) Equal(s2 Byte) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/byte.go","code":"// Equal returns true if and only if s1 is equal (as a set) to s2.\n// Two sets are equal if their membership is identical.\n// (In practice, this means same elements, order doesn't matter)\nfunc (s1 Byte) Equal(s2 Byte) bool {\n\treturn cast(s1).Equal(cast(s2))\n}","line":{"from":112,"to":117}} {"id":100015957,"name":"List","signature":"func (s Byte) List() []byte","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/byte.go","code":"// List returns the contents as a sorted byte slice.\nfunc (s Byte) List() []byte {\n\treturn List(cast(s))\n}","line":{"from":119,"to":122}} {"id":100015958,"name":"UnsortedList","signature":"func (s Byte) UnsortedList() []byte","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/byte.go","code":"// UnsortedList returns the slice with contents in random order.\nfunc (s Byte) UnsortedList() []byte {\n\treturn cast(s).UnsortedList()\n}","line":{"from":124,"to":127}} {"id":100015959,"name":"PopAny","signature":"func (s Byte) PopAny() (byte, bool)","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/byte.go","code":"// PopAny returns a single element from the set.\nfunc (s Byte) PopAny() (byte, bool) {\n\treturn cast(s).PopAny()\n}","line":{"from":129,"to":132}} {"id":100015960,"name":"Len","signature":"func (s Byte) Len() int","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/byte.go","code":"// Len returns the size of the set.\nfunc (s Byte) Len() int {\n\treturn len(s)\n}","line":{"from":134,"to":137}} {"id":100015961,"name":"NewInt","signature":"func NewInt(items ...int) Int","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int.go","code":"// NewInt creates a Int from a list of values.\nfunc NewInt(items ...int) Int {\n\treturn Int(New[int](items...))\n}","line":{"from":27,"to":30}} {"id":100015962,"name":"IntKeySet","signature":"func IntKeySet[T any](theMap map[int]T) Int","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int.go","code":"// IntKeySet creates a Int from a keys of a map[int](? extends interface{}).\n// If the value passed in is not actually a map, this will panic.\nfunc IntKeySet[T any](theMap map[int]T) Int {\n\treturn Int(KeySet(theMap))\n}","line":{"from":32,"to":36}} {"id":100015963,"name":"Insert","signature":"func (s Int) Insert(items ...int) Int","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int.go","code":"// Insert adds items to the set.\nfunc (s Int) Insert(items ...int) Int {\n\treturn Int(cast(s).Insert(items...))\n}","line":{"from":38,"to":41}} {"id":100015964,"name":"Delete","signature":"func (s Int) Delete(items ...int) Int","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int.go","code":"// Delete removes all items from the set.\nfunc (s Int) Delete(items ...int) Int {\n\treturn Int(cast(s).Delete(items...))\n}","line":{"from":43,"to":46}} {"id":100015965,"name":"Has","signature":"func (s Int) Has(item int) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int.go","code":"// Has returns true if and only if item is contained in the set.\nfunc (s Int) Has(item int) bool {\n\treturn cast(s).Has(item)\n}","line":{"from":48,"to":51}} {"id":100015966,"name":"HasAll","signature":"func (s Int) HasAll(items ...int) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int.go","code":"// HasAll returns true if and only if all items are contained in the set.\nfunc (s Int) HasAll(items ...int) bool {\n\treturn cast(s).HasAll(items...)\n}","line":{"from":53,"to":56}} {"id":100015967,"name":"HasAny","signature":"func (s Int) HasAny(items ...int) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int.go","code":"// HasAny returns true if any items are contained in the set.\nfunc (s Int) HasAny(items ...int) bool {\n\treturn cast(s).HasAny(items...)\n}","line":{"from":58,"to":61}} {"id":100015968,"name":"Clone","signature":"func (s Int) Clone() Int","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int.go","code":"// Clone returns a new set which is a copy of the current set.\nfunc (s Int) Clone() Int {\n\treturn Int(cast(s).Clone())\n}","line":{"from":63,"to":66}} {"id":100015969,"name":"Difference","signature":"func (s1 Int) Difference(s2 Int) Int","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int.go","code":"// Difference returns a set of objects that are not in s2.\n// For example:\n// s1 = {a1, a2, a3}\n// s2 = {a1, a2, a4, a5}\n// s1.Difference(s2) = {a3}\n// s2.Difference(s1) = {a4, a5}\nfunc (s1 Int) Difference(s2 Int) Int {\n\treturn Int(cast(s1).Difference(cast(s2)))\n}","line":{"from":68,"to":76}} {"id":100015970,"name":"SymmetricDifference","signature":"func (s1 Int) SymmetricDifference(s2 Int) Int","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int.go","code":"// SymmetricDifference returns a set of elements which are in either of the sets, but not in their intersection.\n// For example:\n// s1 = {a1, a2, a3}\n// s2 = {a1, a2, a4, a5}\n// s1.SymmetricDifference(s2) = {a3, a4, a5}\n// s2.SymmetricDifference(s1) = {a3, a4, a5}\nfunc (s1 Int) SymmetricDifference(s2 Int) Int {\n\treturn Int(cast(s1).SymmetricDifference(cast(s2)))\n}","line":{"from":78,"to":86}} {"id":100015971,"name":"Union","signature":"func (s1 Int) Union(s2 Int) Int","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int.go","code":"// Union returns a new set which includes items in either s1 or s2.\n// For example:\n// s1 = {a1, a2}\n// s2 = {a3, a4}\n// s1.Union(s2) = {a1, a2, a3, a4}\n// s2.Union(s1) = {a1, a2, a3, a4}\nfunc (s1 Int) Union(s2 Int) Int {\n\treturn Int(cast(s1).Union(cast(s2)))\n}","line":{"from":88,"to":96}} {"id":100015972,"name":"Intersection","signature":"func (s1 Int) Intersection(s2 Int) Int","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int.go","code":"// Intersection returns a new set which includes the item in BOTH s1 and s2\n// For example:\n// s1 = {a1, a2}\n// s2 = {a2, a3}\n// s1.Intersection(s2) = {a2}\nfunc (s1 Int) Intersection(s2 Int) Int {\n\treturn Int(cast(s1).Intersection(cast(s2)))\n}","line":{"from":98,"to":105}} {"id":100015973,"name":"IsSuperset","signature":"func (s1 Int) IsSuperset(s2 Int) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int.go","code":"// IsSuperset returns true if and only if s1 is a superset of s2.\nfunc (s1 Int) IsSuperset(s2 Int) bool {\n\treturn cast(s1).IsSuperset(cast(s2))\n}","line":{"from":107,"to":110}} {"id":100015974,"name":"Equal","signature":"func (s1 Int) Equal(s2 Int) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int.go","code":"// Equal returns true if and only if s1 is equal (as a set) to s2.\n// Two sets are equal if their membership is identical.\n// (In practice, this means same elements, order doesn't matter)\nfunc (s1 Int) Equal(s2 Int) bool {\n\treturn cast(s1).Equal(cast(s2))\n}","line":{"from":112,"to":117}} {"id":100015975,"name":"List","signature":"func (s Int) List() []int","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int.go","code":"// List returns the contents as a sorted int slice.\nfunc (s Int) List() []int {\n\treturn List(cast(s))\n}","line":{"from":119,"to":122}} {"id":100015976,"name":"UnsortedList","signature":"func (s Int) UnsortedList() []int","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int.go","code":"// UnsortedList returns the slice with contents in random order.\nfunc (s Int) UnsortedList() []int {\n\treturn cast(s).UnsortedList()\n}","line":{"from":124,"to":127}} {"id":100015977,"name":"PopAny","signature":"func (s Int) PopAny() (int, bool)","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int.go","code":"// PopAny returns a single element from the set.\nfunc (s Int) PopAny() (int, bool) {\n\treturn cast(s).PopAny()\n}","line":{"from":129,"to":132}} {"id":100015978,"name":"Len","signature":"func (s Int) Len() int","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int.go","code":"// Len returns the size of the set.\nfunc (s Int) Len() int {\n\treturn len(s)\n}","line":{"from":134,"to":137}} {"id":100015979,"name":"NewInt32","signature":"func NewInt32(items ...int32) Int32","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int32.go","code":"// NewInt32 creates a Int32 from a list of values.\nfunc NewInt32(items ...int32) Int32 {\n\treturn Int32(New[int32](items...))\n}","line":{"from":27,"to":30}} {"id":100015980,"name":"Int32KeySet","signature":"func Int32KeySet[T any](theMap map[int32]T) Int32","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int32.go","code":"// Int32KeySet creates a Int32 from a keys of a map[int32](? extends interface{}).\n// If the value passed in is not actually a map, this will panic.\nfunc Int32KeySet[T any](theMap map[int32]T) Int32 {\n\treturn Int32(KeySet(theMap))\n}","line":{"from":32,"to":36}} {"id":100015981,"name":"Insert","signature":"func (s Int32) Insert(items ...int32) Int32","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int32.go","code":"// Insert adds items to the set.\nfunc (s Int32) Insert(items ...int32) Int32 {\n\treturn Int32(cast(s).Insert(items...))\n}","line":{"from":38,"to":41}} {"id":100015982,"name":"Delete","signature":"func (s Int32) Delete(items ...int32) Int32","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int32.go","code":"// Delete removes all items from the set.\nfunc (s Int32) Delete(items ...int32) Int32 {\n\treturn Int32(cast(s).Delete(items...))\n}","line":{"from":43,"to":46}} {"id":100015983,"name":"Has","signature":"func (s Int32) Has(item int32) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int32.go","code":"// Has returns true if and only if item is contained in the set.\nfunc (s Int32) Has(item int32) bool {\n\treturn cast(s).Has(item)\n}","line":{"from":48,"to":51}} {"id":100015984,"name":"HasAll","signature":"func (s Int32) HasAll(items ...int32) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int32.go","code":"// HasAll returns true if and only if all items are contained in the set.\nfunc (s Int32) HasAll(items ...int32) bool {\n\treturn cast(s).HasAll(items...)\n}","line":{"from":53,"to":56}} {"id":100015985,"name":"HasAny","signature":"func (s Int32) HasAny(items ...int32) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int32.go","code":"// HasAny returns true if any items are contained in the set.\nfunc (s Int32) HasAny(items ...int32) bool {\n\treturn cast(s).HasAny(items...)\n}","line":{"from":58,"to":61}} {"id":100015986,"name":"Clone","signature":"func (s Int32) Clone() Int32","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int32.go","code":"// Clone returns a new set which is a copy of the current set.\nfunc (s Int32) Clone() Int32 {\n\treturn Int32(cast(s).Clone())\n}","line":{"from":63,"to":66}} {"id":100015987,"name":"Difference","signature":"func (s1 Int32) Difference(s2 Int32) Int32","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int32.go","code":"// Difference returns a set of objects that are not in s2.\n// For example:\n// s1 = {a1, a2, a3}\n// s2 = {a1, a2, a4, a5}\n// s1.Difference(s2) = {a3}\n// s2.Difference(s1) = {a4, a5}\nfunc (s1 Int32) Difference(s2 Int32) Int32 {\n\treturn Int32(cast(s1).Difference(cast(s2)))\n}","line":{"from":68,"to":76}} {"id":100015988,"name":"SymmetricDifference","signature":"func (s1 Int32) SymmetricDifference(s2 Int32) Int32","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int32.go","code":"// SymmetricDifference returns a set of elements which are in either of the sets, but not in their intersection.\n// For example:\n// s1 = {a1, a2, a3}\n// s2 = {a1, a2, a4, a5}\n// s1.SymmetricDifference(s2) = {a3, a4, a5}\n// s2.SymmetricDifference(s1) = {a3, a4, a5}\nfunc (s1 Int32) SymmetricDifference(s2 Int32) Int32 {\n\treturn Int32(cast(s1).SymmetricDifference(cast(s2)))\n}","line":{"from":78,"to":86}} {"id":100015989,"name":"Union","signature":"func (s1 Int32) Union(s2 Int32) Int32","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int32.go","code":"// Union returns a new set which includes items in either s1 or s2.\n// For example:\n// s1 = {a1, a2}\n// s2 = {a3, a4}\n// s1.Union(s2) = {a1, a2, a3, a4}\n// s2.Union(s1) = {a1, a2, a3, a4}\nfunc (s1 Int32) Union(s2 Int32) Int32 {\n\treturn Int32(cast(s1).Union(cast(s2)))\n}","line":{"from":88,"to":96}} {"id":100015990,"name":"Intersection","signature":"func (s1 Int32) Intersection(s2 Int32) Int32","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int32.go","code":"// Intersection returns a new set which includes the item in BOTH s1 and s2\n// For example:\n// s1 = {a1, a2}\n// s2 = {a2, a3}\n// s1.Intersection(s2) = {a2}\nfunc (s1 Int32) Intersection(s2 Int32) Int32 {\n\treturn Int32(cast(s1).Intersection(cast(s2)))\n}","line":{"from":98,"to":105}} {"id":100015991,"name":"IsSuperset","signature":"func (s1 Int32) IsSuperset(s2 Int32) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int32.go","code":"// IsSuperset returns true if and only if s1 is a superset of s2.\nfunc (s1 Int32) IsSuperset(s2 Int32) bool {\n\treturn cast(s1).IsSuperset(cast(s2))\n}","line":{"from":107,"to":110}} {"id":100015992,"name":"Equal","signature":"func (s1 Int32) Equal(s2 Int32) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int32.go","code":"// Equal returns true if and only if s1 is equal (as a set) to s2.\n// Two sets are equal if their membership is identical.\n// (In practice, this means same elements, order doesn't matter)\nfunc (s1 Int32) Equal(s2 Int32) bool {\n\treturn cast(s1).Equal(cast(s2))\n}","line":{"from":112,"to":117}} {"id":100015993,"name":"List","signature":"func (s Int32) List() []int32","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int32.go","code":"// List returns the contents as a sorted int32 slice.\nfunc (s Int32) List() []int32 {\n\treturn List(cast(s))\n}","line":{"from":119,"to":122}} {"id":100015994,"name":"UnsortedList","signature":"func (s Int32) UnsortedList() []int32","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int32.go","code":"// UnsortedList returns the slice with contents in random order.\nfunc (s Int32) UnsortedList() []int32 {\n\treturn cast(s).UnsortedList()\n}","line":{"from":124,"to":127}} {"id":100015995,"name":"PopAny","signature":"func (s Int32) PopAny() (int32, bool)","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int32.go","code":"// PopAny returns a single element from the set.\nfunc (s Int32) PopAny() (int32, bool) {\n\treturn cast(s).PopAny()\n}","line":{"from":129,"to":132}} {"id":100015996,"name":"Len","signature":"func (s Int32) Len() int","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int32.go","code":"// Len returns the size of the set.\nfunc (s Int32) Len() int {\n\treturn len(s)\n}","line":{"from":134,"to":137}} {"id":100015997,"name":"NewInt64","signature":"func NewInt64(items ...int64) Int64","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int64.go","code":"// NewInt64 creates a Int64 from a list of values.\nfunc NewInt64(items ...int64) Int64 {\n\treturn Int64(New[int64](items...))\n}","line":{"from":27,"to":30}} {"id":100015998,"name":"Int64KeySet","signature":"func Int64KeySet[T any](theMap map[int64]T) Int64","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int64.go","code":"// Int64KeySet creates a Int64 from a keys of a map[int64](? extends interface{}).\n// If the value passed in is not actually a map, this will panic.\nfunc Int64KeySet[T any](theMap map[int64]T) Int64 {\n\treturn Int64(KeySet(theMap))\n}","line":{"from":32,"to":36}} {"id":100015999,"name":"Insert","signature":"func (s Int64) Insert(items ...int64) Int64","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int64.go","code":"// Insert adds items to the set.\nfunc (s Int64) Insert(items ...int64) Int64 {\n\treturn Int64(cast(s).Insert(items...))\n}","line":{"from":38,"to":41}} {"id":100016000,"name":"Delete","signature":"func (s Int64) Delete(items ...int64) Int64","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int64.go","code":"// Delete removes all items from the set.\nfunc (s Int64) Delete(items ...int64) Int64 {\n\treturn Int64(cast(s).Delete(items...))\n}","line":{"from":43,"to":46}} {"id":100016001,"name":"Has","signature":"func (s Int64) Has(item int64) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int64.go","code":"// Has returns true if and only if item is contained in the set.\nfunc (s Int64) Has(item int64) bool {\n\treturn cast(s).Has(item)\n}","line":{"from":48,"to":51}} {"id":100016002,"name":"HasAll","signature":"func (s Int64) HasAll(items ...int64) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int64.go","code":"// HasAll returns true if and only if all items are contained in the set.\nfunc (s Int64) HasAll(items ...int64) bool {\n\treturn cast(s).HasAll(items...)\n}","line":{"from":53,"to":56}} {"id":100016003,"name":"HasAny","signature":"func (s Int64) HasAny(items ...int64) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int64.go","code":"// HasAny returns true if any items are contained in the set.\nfunc (s Int64) HasAny(items ...int64) bool {\n\treturn cast(s).HasAny(items...)\n}","line":{"from":58,"to":61}} {"id":100016004,"name":"Clone","signature":"func (s Int64) Clone() Int64","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int64.go","code":"// Clone returns a new set which is a copy of the current set.\nfunc (s Int64) Clone() Int64 {\n\treturn Int64(cast(s).Clone())\n}","line":{"from":63,"to":66}} {"id":100016005,"name":"Difference","signature":"func (s1 Int64) Difference(s2 Int64) Int64","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int64.go","code":"// Difference returns a set of objects that are not in s2.\n// For example:\n// s1 = {a1, a2, a3}\n// s2 = {a1, a2, a4, a5}\n// s1.Difference(s2) = {a3}\n// s2.Difference(s1) = {a4, a5}\nfunc (s1 Int64) Difference(s2 Int64) Int64 {\n\treturn Int64(cast(s1).Difference(cast(s2)))\n}","line":{"from":68,"to":76}} {"id":100016006,"name":"SymmetricDifference","signature":"func (s1 Int64) SymmetricDifference(s2 Int64) Int64","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int64.go","code":"// SymmetricDifference returns a set of elements which are in either of the sets, but not in their intersection.\n// For example:\n// s1 = {a1, a2, a3}\n// s2 = {a1, a2, a4, a5}\n// s1.SymmetricDifference(s2) = {a3, a4, a5}\n// s2.SymmetricDifference(s1) = {a3, a4, a5}\nfunc (s1 Int64) SymmetricDifference(s2 Int64) Int64 {\n\treturn Int64(cast(s1).SymmetricDifference(cast(s2)))\n}","line":{"from":78,"to":86}} {"id":100016007,"name":"Union","signature":"func (s1 Int64) Union(s2 Int64) Int64","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int64.go","code":"// Union returns a new set which includes items in either s1 or s2.\n// For example:\n// s1 = {a1, a2}\n// s2 = {a3, a4}\n// s1.Union(s2) = {a1, a2, a3, a4}\n// s2.Union(s1) = {a1, a2, a3, a4}\nfunc (s1 Int64) Union(s2 Int64) Int64 {\n\treturn Int64(cast(s1).Union(cast(s2)))\n}","line":{"from":88,"to":96}} {"id":100016008,"name":"Intersection","signature":"func (s1 Int64) Intersection(s2 Int64) Int64","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int64.go","code":"// Intersection returns a new set which includes the item in BOTH s1 and s2\n// For example:\n// s1 = {a1, a2}\n// s2 = {a2, a3}\n// s1.Intersection(s2) = {a2}\nfunc (s1 Int64) Intersection(s2 Int64) Int64 {\n\treturn Int64(cast(s1).Intersection(cast(s2)))\n}","line":{"from":98,"to":105}} {"id":100016009,"name":"IsSuperset","signature":"func (s1 Int64) IsSuperset(s2 Int64) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int64.go","code":"// IsSuperset returns true if and only if s1 is a superset of s2.\nfunc (s1 Int64) IsSuperset(s2 Int64) bool {\n\treturn cast(s1).IsSuperset(cast(s2))\n}","line":{"from":107,"to":110}} {"id":100016010,"name":"Equal","signature":"func (s1 Int64) Equal(s2 Int64) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int64.go","code":"// Equal returns true if and only if s1 is equal (as a set) to s2.\n// Two sets are equal if their membership is identical.\n// (In practice, this means same elements, order doesn't matter)\nfunc (s1 Int64) Equal(s2 Int64) bool {\n\treturn cast(s1).Equal(cast(s2))\n}","line":{"from":112,"to":117}} {"id":100016011,"name":"List","signature":"func (s Int64) List() []int64","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int64.go","code":"// List returns the contents as a sorted int64 slice.\nfunc (s Int64) List() []int64 {\n\treturn List(cast(s))\n}","line":{"from":119,"to":122}} {"id":100016012,"name":"UnsortedList","signature":"func (s Int64) UnsortedList() []int64","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int64.go","code":"// UnsortedList returns the slice with contents in random order.\nfunc (s Int64) UnsortedList() []int64 {\n\treturn cast(s).UnsortedList()\n}","line":{"from":124,"to":127}} {"id":100016013,"name":"PopAny","signature":"func (s Int64) PopAny() (int64, bool)","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int64.go","code":"// PopAny returns a single element from the set.\nfunc (s Int64) PopAny() (int64, bool) {\n\treturn cast(s).PopAny()\n}","line":{"from":129,"to":132}} {"id":100016014,"name":"Len","signature":"func (s Int64) Len() int","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/int64.go","code":"// Len returns the size of the set.\nfunc (s Int64) Len() int {\n\treturn len(s)\n}","line":{"from":134,"to":137}} {"id":100016015,"name":"cast","signature":"func cast[T comparable](s map[T]Empty) Set[T] { return s }","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/set.go","code":"// cast transforms specified set to generic Set[T].\nfunc cast[T comparable](s map[T]Empty) Set[T] { return s }","line":{"from":26,"to":27}} {"id":100016016,"name":"New","signature":"func New[T comparable](items ...T) Set[T]","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/set.go","code":"// New creates a Set from a list of values.\n// NOTE: type param must be explicitly instantiated if given items are empty.\nfunc New[T comparable](items ...T) Set[T] {\n\tss := make(Set[T], len(items))\n\tss.Insert(items...)\n\treturn ss\n}","line":{"from":29,"to":35}} {"id":100016017,"name":"KeySet","signature":"func KeySet[T comparable, V any](theMap map[T]V) Set[T]","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/set.go","code":"// KeySet creates a Set from a keys of a map[comparable](? extends interface{}).\n// If the value passed in is not actually a map, this will panic.\nfunc KeySet[T comparable, V any](theMap map[T]V) Set[T] {\n\tret := Set[T]{}\n\tfor keyValue := range theMap {\n\t\tret.Insert(keyValue)\n\t}\n\treturn ret\n}","line":{"from":37,"to":45}} {"id":100016018,"name":"Insert","signature":"func (s Set[T]) Insert(items ...T) Set[T]","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/set.go","code":"// Insert adds items to the set.\nfunc (s Set[T]) Insert(items ...T) Set[T] {\n\tfor _, item := range items {\n\t\ts[item] = Empty{}\n\t}\n\treturn s\n}","line":{"from":47,"to":53}} {"id":100016019,"name":"Insert","signature":"func Insert[T comparable](set Set[T], items ...T) Set[T]","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/set.go","code":"func Insert[T comparable](set Set[T], items ...T) Set[T] {\n\treturn set.Insert(items...)\n}","line":{"from":55,"to":57}} {"id":100016020,"name":"Delete","signature":"func (s Set[T]) Delete(items ...T) Set[T]","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/set.go","code":"// Delete removes all items from the set.\nfunc (s Set[T]) Delete(items ...T) Set[T] {\n\tfor _, item := range items {\n\t\tdelete(s, item)\n\t}\n\treturn s\n}","line":{"from":59,"to":65}} {"id":100016021,"name":"Clear","signature":"func (s Set[T]) Clear() Set[T]","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/set.go","code":"// Clear empties the set.\n// It is preferable to replace the set with a newly constructed set,\n// but not all callers can do that (when there are other references to the map).\n// In some cases the set *won't* be fully cleared, e.g. a Set[float32] containing NaN\n// can't be cleared because NaN can't be removed.\n// For sets containing items of a type that is reflexive for ==,\n// this is optimized to a single call to runtime.mapclear().\nfunc (s Set[T]) Clear() Set[T] {\n\tfor key := range s {\n\t\tdelete(s, key)\n\t}\n\treturn s\n}","line":{"from":67,"to":79}} {"id":100016022,"name":"Has","signature":"func (s Set[T]) Has(item T) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/set.go","code":"// Has returns true if and only if item is contained in the set.\nfunc (s Set[T]) Has(item T) bool {\n\t_, contained := s[item]\n\treturn contained\n}","line":{"from":81,"to":85}} {"id":100016023,"name":"HasAll","signature":"func (s Set[T]) HasAll(items ...T) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/set.go","code":"// HasAll returns true if and only if all items are contained in the set.\nfunc (s Set[T]) HasAll(items ...T) bool {\n\tfor _, item := range items {\n\t\tif !s.Has(item) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":87,"to":95}} {"id":100016024,"name":"HasAny","signature":"func (s Set[T]) HasAny(items ...T) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/set.go","code":"// HasAny returns true if any items are contained in the set.\nfunc (s Set[T]) HasAny(items ...T) bool {\n\tfor _, item := range items {\n\t\tif s.Has(item) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":97,"to":105}} {"id":100016025,"name":"Clone","signature":"func (s Set[T]) Clone() Set[T]","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/set.go","code":"// Clone returns a new set which is a copy of the current set.\nfunc (s Set[T]) Clone() Set[T] {\n\tresult := make(Set[T], len(s))\n\tfor key := range s {\n\t\tresult.Insert(key)\n\t}\n\treturn result\n}","line":{"from":107,"to":114}} {"id":100016026,"name":"Difference","signature":"func (s1 Set[T]) Difference(s2 Set[T]) Set[T]","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/set.go","code":"// Difference returns a set of objects that are not in s2.\n// For example:\n// s1 = {a1, a2, a3}\n// s2 = {a1, a2, a4, a5}\n// s1.Difference(s2) = {a3}\n// s2.Difference(s1) = {a4, a5}\nfunc (s1 Set[T]) Difference(s2 Set[T]) Set[T] {\n\tresult := New[T]()\n\tfor key := range s1 {\n\t\tif !s2.Has(key) {\n\t\t\tresult.Insert(key)\n\t\t}\n\t}\n\treturn result\n}","line":{"from":116,"to":130}} {"id":100016027,"name":"SymmetricDifference","signature":"func (s1 Set[T]) SymmetricDifference(s2 Set[T]) Set[T]","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/set.go","code":"// SymmetricDifference returns a set of elements which are in either of the sets, but not in their intersection.\n// For example:\n// s1 = {a1, a2, a3}\n// s2 = {a1, a2, a4, a5}\n// s1.SymmetricDifference(s2) = {a3, a4, a5}\n// s2.SymmetricDifference(s1) = {a3, a4, a5}\nfunc (s1 Set[T]) SymmetricDifference(s2 Set[T]) Set[T] {\n\treturn s1.Difference(s2).Union(s2.Difference(s1))\n}","line":{"from":132,"to":140}} {"id":100016028,"name":"Union","signature":"func (s1 Set[T]) Union(s2 Set[T]) Set[T]","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/set.go","code":"// Union returns a new set which includes items in either s1 or s2.\n// For example:\n// s1 = {a1, a2}\n// s2 = {a3, a4}\n// s1.Union(s2) = {a1, a2, a3, a4}\n// s2.Union(s1) = {a1, a2, a3, a4}\nfunc (s1 Set[T]) Union(s2 Set[T]) Set[T] {\n\tresult := s1.Clone()\n\tfor key := range s2 {\n\t\tresult.Insert(key)\n\t}\n\treturn result\n}","line":{"from":142,"to":154}} {"id":100016029,"name":"Intersection","signature":"func (s1 Set[T]) Intersection(s2 Set[T]) Set[T]","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/set.go","code":"// Intersection returns a new set which includes the item in BOTH s1 and s2\n// For example:\n// s1 = {a1, a2}\n// s2 = {a2, a3}\n// s1.Intersection(s2) = {a2}\nfunc (s1 Set[T]) Intersection(s2 Set[T]) Set[T] {\n\tvar walk, other Set[T]\n\tresult := New[T]()\n\tif s1.Len() \u003c s2.Len() {\n\t\twalk = s1\n\t\tother = s2\n\t} else {\n\t\twalk = s2\n\t\tother = s1\n\t}\n\tfor key := range walk {\n\t\tif other.Has(key) {\n\t\t\tresult.Insert(key)\n\t\t}\n\t}\n\treturn result\n}","line":{"from":156,"to":177}} {"id":100016030,"name":"IsSuperset","signature":"func (s1 Set[T]) IsSuperset(s2 Set[T]) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/set.go","code":"// IsSuperset returns true if and only if s1 is a superset of s2.\nfunc (s1 Set[T]) IsSuperset(s2 Set[T]) bool {\n\tfor item := range s2 {\n\t\tif !s1.Has(item) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":179,"to":187}} {"id":100016031,"name":"Equal","signature":"func (s1 Set[T]) Equal(s2 Set[T]) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/set.go","code":"// Equal returns true if and only if s1 is equal (as a set) to s2.\n// Two sets are equal if their membership is identical.\n// (In practice, this means same elements, order doesn't matter)\nfunc (s1 Set[T]) Equal(s2 Set[T]) bool {\n\treturn len(s1) == len(s2) \u0026\u0026 s1.IsSuperset(s2)\n}","line":{"from":189,"to":194}} {"id":100016032,"name":"Len","signature":"func (g sortableSliceOfGeneric[T]) Len() int { return len(g) }","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/set.go","code":"func (g sortableSliceOfGeneric[T]) Len() int { return len(g) }","line":{"from":198,"to":198}} {"id":100016033,"name":"Less","signature":"func (g sortableSliceOfGeneric[T]) Less(i, j int) bool { return less[T](g[i], g[j]) }","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/set.go","code":"func (g sortableSliceOfGeneric[T]) Less(i, j int) bool { return less[T](g[i], g[j]) }","line":{"from":199,"to":199}} {"id":100016034,"name":"Swap","signature":"func (g sortableSliceOfGeneric[T]) Swap(i, j int) { g[i], g[j] = g[j], g[i] }","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/set.go","code":"func (g sortableSliceOfGeneric[T]) Swap(i, j int) { g[i], g[j] = g[j], g[i] }","line":{"from":200,"to":200}} {"id":100016035,"name":"List","signature":"func List[T ordered](s Set[T]) []T","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/set.go","code":"// List returns the contents as a sorted T slice.\n//\n// This is a separate function and not a method because not all types supported\n// by Generic are ordered and only those can be sorted.\nfunc List[T ordered](s Set[T]) []T {\n\tres := make(sortableSliceOfGeneric[T], 0, len(s))\n\tfor key := range s {\n\t\tres = append(res, key)\n\t}\n\tsort.Sort(res)\n\treturn res\n}","line":{"from":202,"to":213}} {"id":100016036,"name":"UnsortedList","signature":"func (s Set[T]) UnsortedList() []T","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/set.go","code":"// UnsortedList returns the slice with contents in random order.\nfunc (s Set[T]) UnsortedList() []T {\n\tres := make([]T, 0, len(s))\n\tfor key := range s {\n\t\tres = append(res, key)\n\t}\n\treturn res\n}","line":{"from":215,"to":222}} {"id":100016037,"name":"PopAny","signature":"func (s Set[T]) PopAny() (T, bool)","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/set.go","code":"// PopAny returns a single element from the set.\nfunc (s Set[T]) PopAny() (T, bool) {\n\tfor key := range s {\n\t\ts.Delete(key)\n\t\treturn key, true\n\t}\n\tvar zeroValue T\n\treturn zeroValue, false\n}","line":{"from":224,"to":232}} {"id":100016038,"name":"Len","signature":"func (s Set[T]) Len() int","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/set.go","code":"// Len returns the size of the set.\nfunc (s Set[T]) Len() int {\n\treturn len(s)\n}","line":{"from":234,"to":237}} {"id":100016039,"name":"less","signature":"func less[T ordered](lhs, rhs T) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/set.go","code":"func less[T ordered](lhs, rhs T) bool {\n\treturn lhs \u003c rhs\n}","line":{"from":239,"to":241}} {"id":100016040,"name":"NewString","signature":"func NewString(items ...string) String","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/string.go","code":"// NewString creates a String from a list of values.\nfunc NewString(items ...string) String {\n\treturn String(New[string](items...))\n}","line":{"from":27,"to":30}} {"id":100016041,"name":"StringKeySet","signature":"func StringKeySet[T any](theMap map[string]T) String","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/string.go","code":"// StringKeySet creates a String from a keys of a map[string](? extends interface{}).\n// If the value passed in is not actually a map, this will panic.\nfunc StringKeySet[T any](theMap map[string]T) String {\n\treturn String(KeySet(theMap))\n}","line":{"from":32,"to":36}} {"id":100016042,"name":"Insert","signature":"func (s String) Insert(items ...string) String","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/string.go","code":"// Insert adds items to the set.\nfunc (s String) Insert(items ...string) String {\n\treturn String(cast(s).Insert(items...))\n}","line":{"from":38,"to":41}} {"id":100016043,"name":"Delete","signature":"func (s String) Delete(items ...string) String","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/string.go","code":"// Delete removes all items from the set.\nfunc (s String) Delete(items ...string) String {\n\treturn String(cast(s).Delete(items...))\n}","line":{"from":43,"to":46}} {"id":100016044,"name":"Has","signature":"func (s String) Has(item string) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/string.go","code":"// Has returns true if and only if item is contained in the set.\nfunc (s String) Has(item string) bool {\n\treturn cast(s).Has(item)\n}","line":{"from":48,"to":51}} {"id":100016045,"name":"HasAll","signature":"func (s String) HasAll(items ...string) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/string.go","code":"// HasAll returns true if and only if all items are contained in the set.\nfunc (s String) HasAll(items ...string) bool {\n\treturn cast(s).HasAll(items...)\n}","line":{"from":53,"to":56}} {"id":100016046,"name":"HasAny","signature":"func (s String) HasAny(items ...string) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/string.go","code":"// HasAny returns true if any items are contained in the set.\nfunc (s String) HasAny(items ...string) bool {\n\treturn cast(s).HasAny(items...)\n}","line":{"from":58,"to":61}} {"id":100016047,"name":"Clone","signature":"func (s String) Clone() String","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/string.go","code":"// Clone returns a new set which is a copy of the current set.\nfunc (s String) Clone() String {\n\treturn String(cast(s).Clone())\n}","line":{"from":63,"to":66}} {"id":100016048,"name":"Difference","signature":"func (s1 String) Difference(s2 String) String","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/string.go","code":"// Difference returns a set of objects that are not in s2.\n// For example:\n// s1 = {a1, a2, a3}\n// s2 = {a1, a2, a4, a5}\n// s1.Difference(s2) = {a3}\n// s2.Difference(s1) = {a4, a5}\nfunc (s1 String) Difference(s2 String) String {\n\treturn String(cast(s1).Difference(cast(s2)))\n}","line":{"from":68,"to":76}} {"id":100016049,"name":"SymmetricDifference","signature":"func (s1 String) SymmetricDifference(s2 String) String","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/string.go","code":"// SymmetricDifference returns a set of elements which are in either of the sets, but not in their intersection.\n// For example:\n// s1 = {a1, a2, a3}\n// s2 = {a1, a2, a4, a5}\n// s1.SymmetricDifference(s2) = {a3, a4, a5}\n// s2.SymmetricDifference(s1) = {a3, a4, a5}\nfunc (s1 String) SymmetricDifference(s2 String) String {\n\treturn String(cast(s1).SymmetricDifference(cast(s2)))\n}","line":{"from":78,"to":86}} {"id":100016050,"name":"Union","signature":"func (s1 String) Union(s2 String) String","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/string.go","code":"// Union returns a new set which includes items in either s1 or s2.\n// For example:\n// s1 = {a1, a2}\n// s2 = {a3, a4}\n// s1.Union(s2) = {a1, a2, a3, a4}\n// s2.Union(s1) = {a1, a2, a3, a4}\nfunc (s1 String) Union(s2 String) String {\n\treturn String(cast(s1).Union(cast(s2)))\n}","line":{"from":88,"to":96}} {"id":100016051,"name":"Intersection","signature":"func (s1 String) Intersection(s2 String) String","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/string.go","code":"// Intersection returns a new set which includes the item in BOTH s1 and s2\n// For example:\n// s1 = {a1, a2}\n// s2 = {a2, a3}\n// s1.Intersection(s2) = {a2}\nfunc (s1 String) Intersection(s2 String) String {\n\treturn String(cast(s1).Intersection(cast(s2)))\n}","line":{"from":98,"to":105}} {"id":100016052,"name":"IsSuperset","signature":"func (s1 String) IsSuperset(s2 String) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/string.go","code":"// IsSuperset returns true if and only if s1 is a superset of s2.\nfunc (s1 String) IsSuperset(s2 String) bool {\n\treturn cast(s1).IsSuperset(cast(s2))\n}","line":{"from":107,"to":110}} {"id":100016053,"name":"Equal","signature":"func (s1 String) Equal(s2 String) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/string.go","code":"// Equal returns true if and only if s1 is equal (as a set) to s2.\n// Two sets are equal if their membership is identical.\n// (In practice, this means same elements, order doesn't matter)\nfunc (s1 String) Equal(s2 String) bool {\n\treturn cast(s1).Equal(cast(s2))\n}","line":{"from":112,"to":117}} {"id":100016054,"name":"List","signature":"func (s String) List() []string","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/string.go","code":"// List returns the contents as a sorted string slice.\nfunc (s String) List() []string {\n\treturn List(cast(s))\n}","line":{"from":119,"to":122}} {"id":100016055,"name":"UnsortedList","signature":"func (s String) UnsortedList() []string","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/string.go","code":"// UnsortedList returns the slice with contents in random order.\nfunc (s String) UnsortedList() []string {\n\treturn cast(s).UnsortedList()\n}","line":{"from":124,"to":127}} {"id":100016056,"name":"PopAny","signature":"func (s String) PopAny() (string, bool)","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/string.go","code":"// PopAny returns a single element from the set.\nfunc (s String) PopAny() (string, bool) {\n\treturn cast(s).PopAny()\n}","line":{"from":129,"to":132}} {"id":100016057,"name":"Len","signature":"func (s String) Len() int","file":"staging/src/k8s.io/apimachinery/pkg/util/sets/string.go","code":"// Len returns the size of the set.\nfunc (s String) Len() int {\n\treturn len(s)\n}","line":{"from":134,"to":137}} {"id":100016058,"name":"Error","signature":"func (e LookupPatchMetaError) Error() string","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/errors.go","code":"func (e LookupPatchMetaError) Error() string {\n\treturn fmt.Sprintf(\"LookupPatchMetaError(%s): %v\", e.Path, e.Err)\n}","line":{"from":28,"to":30}} {"id":100016059,"name":"Error","signature":"func (e FieldNotFoundError) Error() string","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/errors.go","code":"func (e FieldNotFoundError) Error() string {\n\treturn fmt.Sprintf(\"unable to find api field %q in %s\", e.Field, e.Path)\n}","line":{"from":37,"to":39}} {"id":100016060,"name":"Error","signature":"func (e InvalidTypeError) Error() string","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/errors.go","code":"func (e InvalidTypeError) Error() string {\n\treturn fmt.Sprintf(\"invalid type for %s: got %q, expected %q\", e.Path, e.Actual, e.Expected)\n}","line":{"from":47,"to":49}} {"id":100016061,"name":"GetPatchStrategies","signature":"func (pm *PatchMeta) GetPatchStrategies() []string","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/meta.go","code":"func (pm *PatchMeta) GetPatchStrategies() []string {\n\tif pm.patchStrategies == nil {\n\t\treturn []string{}\n\t}\n\treturn pm.patchStrategies\n}","line":{"from":34,"to":39}} {"id":100016062,"name":"SetPatchStrategies","signature":"func (pm *PatchMeta) SetPatchStrategies(ps []string)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/meta.go","code":"func (pm *PatchMeta) SetPatchStrategies(ps []string) {\n\tpm.patchStrategies = ps\n}","line":{"from":41,"to":43}} {"id":100016063,"name":"GetPatchMergeKey","signature":"func (pm *PatchMeta) GetPatchMergeKey() string","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/meta.go","code":"func (pm *PatchMeta) GetPatchMergeKey() string {\n\treturn pm.patchMergeKey\n}","line":{"from":45,"to":47}} {"id":100016064,"name":"SetPatchMergeKey","signature":"func (pm *PatchMeta) SetPatchMergeKey(pmk string)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/meta.go","code":"func (pm *PatchMeta) SetPatchMergeKey(pmk string) {\n\tpm.patchMergeKey = pmk\n}","line":{"from":49,"to":51}} {"id":100016065,"name":"NewPatchMetaFromStruct","signature":"func NewPatchMetaFromStruct(dataStruct interface{}) (PatchMetaFromStruct, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/meta.go","code":"func NewPatchMetaFromStruct(dataStruct interface{}) (PatchMetaFromStruct, error) {\n\tt, err := getTagStructType(dataStruct)\n\treturn PatchMetaFromStruct{T: t}, err\n}","line":{"from":66,"to":69}} {"id":100016066,"name":"LookupPatchMetadataForStruct","signature":"func (s PatchMetaFromStruct) LookupPatchMetadataForStruct(key string) (LookupPatchMeta, PatchMeta, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/meta.go","code":"func (s PatchMetaFromStruct) LookupPatchMetadataForStruct(key string) (LookupPatchMeta, PatchMeta, error) {\n\tfieldType, fieldPatchStrategies, fieldPatchMergeKey, err := forkedjson.LookupPatchMetadataForStruct(s.T, key)\n\tif err != nil {\n\t\treturn nil, PatchMeta{}, err\n\t}\n\n\treturn PatchMetaFromStruct{T: fieldType},\n\t\tPatchMeta{\n\t\t\tpatchStrategies: fieldPatchStrategies,\n\t\t\tpatchMergeKey: fieldPatchMergeKey,\n\t\t}, nil\n}","line":{"from":73,"to":84}} {"id":100016067,"name":"LookupPatchMetadataForSlice","signature":"func (s PatchMetaFromStruct) LookupPatchMetadataForSlice(key string) (LookupPatchMeta, PatchMeta, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/meta.go","code":"func (s PatchMetaFromStruct) LookupPatchMetadataForSlice(key string) (LookupPatchMeta, PatchMeta, error) {\n\tsubschema, patchMeta, err := s.LookupPatchMetadataForStruct(key)\n\tif err != nil {\n\t\treturn nil, PatchMeta{}, err\n\t}\n\telemPatchMetaFromStruct := subschema.(PatchMetaFromStruct)\n\tt := elemPatchMetaFromStruct.T\n\n\tvar elemType reflect.Type\n\tswitch t.Kind() {\n\t// If t is an array or a slice, get the element type.\n\t// If element is still an array or a slice, return an error.\n\t// Otherwise, return element type.\n\tcase reflect.Array, reflect.Slice:\n\t\telemType = t.Elem()\n\t\tif elemType.Kind() == reflect.Array || elemType.Kind() == reflect.Slice {\n\t\t\treturn nil, PatchMeta{}, errors.New(\"unexpected slice of slice\")\n\t\t}\n\t// If t is an pointer, get the underlying element.\n\t// If the underlying element is neither an array nor a slice, the pointer is pointing to a slice,\n\t// e.g. https://github.com/kubernetes/kubernetes/blob/bc22e206c79282487ea0bf5696d5ccec7e839a76/staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch_test.go#L2782-L2822\n\t// If the underlying element is either an array or a slice, return its element type.\n\tcase reflect.Pointer:\n\t\tt = t.Elem()\n\t\tif t.Kind() == reflect.Array || t.Kind() == reflect.Slice {\n\t\t\tt = t.Elem()\n\t\t}\n\t\telemType = t\n\tdefault:\n\t\treturn nil, PatchMeta{}, fmt.Errorf(\"expected slice or array type, but got: %s\", s.T.Kind().String())\n\t}\n\n\treturn PatchMetaFromStruct{T: elemType}, patchMeta, nil\n}","line":{"from":86,"to":119}} {"id":100016068,"name":"Name","signature":"func (s PatchMetaFromStruct) Name() string","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/meta.go","code":"func (s PatchMetaFromStruct) Name() string {\n\treturn s.T.Kind().String()\n}","line":{"from":121,"to":123}} {"id":100016069,"name":"getTagStructType","signature":"func getTagStructType(dataStruct interface{}) (reflect.Type, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/meta.go","code":"func getTagStructType(dataStruct interface{}) (reflect.Type, error) {\n\tif dataStruct == nil {\n\t\treturn nil, mergepatch.ErrBadArgKind(struct{}{}, nil)\n\t}\n\n\tt := reflect.TypeOf(dataStruct)\n\t// Get the underlying type for pointers\n\tif t.Kind() == reflect.Pointer {\n\t\tt = t.Elem()\n\t}\n\n\tif t.Kind() != reflect.Struct {\n\t\treturn nil, mergepatch.ErrBadArgKind(struct{}{}, dataStruct)\n\t}\n\n\treturn t, nil\n}","line":{"from":125,"to":141}} {"id":100016070,"name":"GetTagStructTypeOrDie","signature":"func GetTagStructTypeOrDie(dataStruct interface{}) reflect.Type","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/meta.go","code":"func GetTagStructTypeOrDie(dataStruct interface{}) reflect.Type {\n\tt, err := getTagStructType(dataStruct)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn t\n}","line":{"from":143,"to":149}} {"id":100016071,"name":"NewPatchMetaFromOpenAPI","signature":"func NewPatchMetaFromOpenAPI(s openapi.Schema) PatchMetaFromOpenAPI","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/meta.go","code":"func NewPatchMetaFromOpenAPI(s openapi.Schema) PatchMetaFromOpenAPI {\n\treturn PatchMetaFromOpenAPI{Schema: s}\n}","line":{"from":155,"to":157}} {"id":100016072,"name":"LookupPatchMetadataForStruct","signature":"func (s PatchMetaFromOpenAPI) LookupPatchMetadataForStruct(key string) (LookupPatchMeta, PatchMeta, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/meta.go","code":"func (s PatchMetaFromOpenAPI) LookupPatchMetadataForStruct(key string) (LookupPatchMeta, PatchMeta, error) {\n\tif s.Schema == nil {\n\t\treturn nil, PatchMeta{}, nil\n\t}\n\tkindItem := NewKindItem(key, s.Schema.GetPath())\n\ts.Schema.Accept(kindItem)\n\n\terr := kindItem.Error()\n\tif err != nil {\n\t\treturn nil, PatchMeta{}, err\n\t}\n\treturn PatchMetaFromOpenAPI{Schema: kindItem.subschema},\n\t\tkindItem.patchmeta, nil\n}","line":{"from":161,"to":174}} {"id":100016073,"name":"LookupPatchMetadataForSlice","signature":"func (s PatchMetaFromOpenAPI) LookupPatchMetadataForSlice(key string) (LookupPatchMeta, PatchMeta, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/meta.go","code":"func (s PatchMetaFromOpenAPI) LookupPatchMetadataForSlice(key string) (LookupPatchMeta, PatchMeta, error) {\n\tif s.Schema == nil {\n\t\treturn nil, PatchMeta{}, nil\n\t}\n\tsliceItem := NewSliceItem(key, s.Schema.GetPath())\n\ts.Schema.Accept(sliceItem)\n\n\terr := sliceItem.Error()\n\tif err != nil {\n\t\treturn nil, PatchMeta{}, err\n\t}\n\treturn PatchMetaFromOpenAPI{Schema: sliceItem.subschema},\n\t\tsliceItem.patchmeta, nil\n}","line":{"from":176,"to":189}} {"id":100016074,"name":"Name","signature":"func (s PatchMetaFromOpenAPI) Name() string","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/meta.go","code":"func (s PatchMetaFromOpenAPI) Name() string {\n\tschema := s.Schema\n\treturn schema.GetName()\n}","line":{"from":191,"to":194}} {"id":100016075,"name":"CreateTwoWayMergePatch","signature":"func CreateTwoWayMergePatch(original, modified []byte, dataStruct interface{}, fns ...mergepatch.PreconditionFunc) ([]byte, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// CreateTwoWayMergePatch creates a patch that can be passed to StrategicMergePatch from an original\n// document and a modified document, which are passed to the method as json encoded content. It will\n// return a patch that yields the modified document when applied to the original document, or an error\n// if either of the two documents is invalid.\nfunc CreateTwoWayMergePatch(original, modified []byte, dataStruct interface{}, fns ...mergepatch.PreconditionFunc) ([]byte, error) {\n\tschema, err := NewPatchMetaFromStruct(dataStruct)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn CreateTwoWayMergePatchUsingLookupPatchMeta(original, modified, schema, fns...)\n}","line":{"from":90,"to":101}} {"id":100016076,"name":"CreateTwoWayMergePatchUsingLookupPatchMeta","signature":"func CreateTwoWayMergePatchUsingLookupPatchMeta(","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func CreateTwoWayMergePatchUsingLookupPatchMeta(\n\toriginal, modified []byte, schema LookupPatchMeta, fns ...mergepatch.PreconditionFunc) ([]byte, error) {\n\toriginalMap := map[string]interface{}{}\n\tif len(original) \u003e 0 {\n\t\tif err := json.Unmarshal(original, \u0026originalMap); err != nil {\n\t\t\treturn nil, mergepatch.ErrBadJSONDoc\n\t\t}\n\t}\n\n\tmodifiedMap := map[string]interface{}{}\n\tif len(modified) \u003e 0 {\n\t\tif err := json.Unmarshal(modified, \u0026modifiedMap); err != nil {\n\t\t\treturn nil, mergepatch.ErrBadJSONDoc\n\t\t}\n\t}\n\n\tpatchMap, err := CreateTwoWayMergeMapPatchUsingLookupPatchMeta(originalMap, modifiedMap, schema, fns...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn json.Marshal(patchMap)\n}","line":{"from":103,"to":125}} {"id":100016077,"name":"CreateTwoWayMergeMapPatch","signature":"func CreateTwoWayMergeMapPatch(original, modified JSONMap, dataStruct interface{}, fns ...mergepatch.PreconditionFunc) (JSONMap, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// CreateTwoWayMergeMapPatch creates a patch from an original and modified JSON objects,\n// encoded JSONMap.\n// The serialized version of the map can then be passed to StrategicMergeMapPatch.\nfunc CreateTwoWayMergeMapPatch(original, modified JSONMap, dataStruct interface{}, fns ...mergepatch.PreconditionFunc) (JSONMap, error) {\n\tschema, err := NewPatchMetaFromStruct(dataStruct)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn CreateTwoWayMergeMapPatchUsingLookupPatchMeta(original, modified, schema, fns...)\n}","line":{"from":127,"to":137}} {"id":100016078,"name":"CreateTwoWayMergeMapPatchUsingLookupPatchMeta","signature":"func CreateTwoWayMergeMapPatchUsingLookupPatchMeta(original, modified JSONMap, schema LookupPatchMeta, fns ...mergepatch.PreconditionFunc) (JSONMap, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func CreateTwoWayMergeMapPatchUsingLookupPatchMeta(original, modified JSONMap, schema LookupPatchMeta, fns ...mergepatch.PreconditionFunc) (JSONMap, error) {\n\tdiffOptions := DiffOptions{\n\t\tSetElementOrder: true,\n\t}\n\tpatchMap, err := diffMaps(original, modified, schema, diffOptions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Apply the preconditions to the patch, and return an error if any of them fail.\n\tfor _, fn := range fns {\n\t\tif !fn(patchMap) {\n\t\t\treturn nil, mergepatch.NewErrPreconditionFailed(patchMap)\n\t\t}\n\t}\n\n\treturn patchMap, nil\n}","line":{"from":139,"to":156}} {"id":100016079,"name":"diffMaps","signature":"func diffMaps(original, modified map[string]interface{}, schema LookupPatchMeta, diffOptions DiffOptions) (map[string]interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// Returns a (recursive) strategic merge patch that yields modified when applied to original.\n// Including:\n// - Adding fields to the patch present in modified, missing from original\n// - Setting fields to the patch present in modified and original with different values\n// - Delete fields present in original, missing from modified through\n// - IFF map field - set to nil in patch\n// - IFF list of maps \u0026\u0026 merge strategy - use deleteDirective for the elements\n// - IFF list of primitives \u0026\u0026 merge strategy - use parallel deletion list\n// - IFF list of maps or primitives with replace strategy (default) - set patch value to the value in modified\n// - Build $retainKeys directive for fields with retainKeys patch strategy\nfunc diffMaps(original, modified map[string]interface{}, schema LookupPatchMeta, diffOptions DiffOptions) (map[string]interface{}, error) {\n\tpatch := map[string]interface{}{}\n\n\t// This will be used to build the $retainKeys directive sent in the patch\n\tretainKeysList := make([]interface{}, 0, len(modified))\n\n\t// Compare each value in the modified map against the value in the original map\n\tfor key, modifiedValue := range modified {\n\t\t// Get the underlying type for pointers\n\t\tif diffOptions.BuildRetainKeysDirective \u0026\u0026 modifiedValue != nil {\n\t\t\tretainKeysList = append(retainKeysList, key)\n\t\t}\n\n\t\toriginalValue, ok := original[key]\n\t\tif !ok {\n\t\t\t// Key was added, so add to patch\n\t\t\tif !diffOptions.IgnoreChangesAndAdditions {\n\t\t\t\tpatch[key] = modifiedValue\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// The patch may have a patch directive\n\t\t// TODO: figure out if we need this. This shouldn't be needed by apply. When would the original map have patch directives in it?\n\t\tfoundDirectiveMarker, err := handleDirectiveMarker(key, originalValue, modifiedValue, patch)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif foundDirectiveMarker {\n\t\t\tcontinue\n\t\t}\n\n\t\tif reflect.TypeOf(originalValue) != reflect.TypeOf(modifiedValue) {\n\t\t\t// Types have changed, so add to patch\n\t\t\tif !diffOptions.IgnoreChangesAndAdditions {\n\t\t\t\tpatch[key] = modifiedValue\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// Types are the same, so compare values\n\t\tswitch originalValueTyped := originalValue.(type) {\n\t\tcase map[string]interface{}:\n\t\t\tmodifiedValueTyped := modifiedValue.(map[string]interface{})\n\t\t\terr = handleMapDiff(key, originalValueTyped, modifiedValueTyped, patch, schema, diffOptions)\n\t\tcase []interface{}:\n\t\t\tmodifiedValueTyped := modifiedValue.([]interface{})\n\t\t\terr = handleSliceDiff(key, originalValueTyped, modifiedValueTyped, patch, schema, diffOptions)\n\t\tdefault:\n\t\t\treplacePatchFieldIfNotEqual(key, originalValue, modifiedValue, patch, diffOptions)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tupdatePatchIfMissing(original, modified, patch, diffOptions)\n\t// Insert the retainKeysList iff there are values present in the retainKeysList and\n\t// either of the following is true:\n\t// - the patch is not empty\n\t// - there are additional field in original that need to be cleared\n\tif len(retainKeysList) \u003e 0 \u0026\u0026\n\t\t(len(patch) \u003e 0 || hasAdditionalNewField(original, modified)) {\n\t\tpatch[retainKeysDirective] = sortScalars(retainKeysList)\n\t}\n\treturn patch, nil\n}","line":{"from":158,"to":234}} {"id":100016080,"name":"handleDirectiveMarker","signature":"func handleDirectiveMarker(key string, originalValue, modifiedValue interface{}, patch map[string]interface{}) (bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// handleDirectiveMarker handles how to diff directive marker between 2 objects\nfunc handleDirectiveMarker(key string, originalValue, modifiedValue interface{}, patch map[string]interface{}) (bool, error) {\n\tif key == directiveMarker {\n\t\toriginalString, ok := originalValue.(string)\n\t\tif !ok {\n\t\t\treturn false, fmt.Errorf(\"invalid value for special key: %s\", directiveMarker)\n\t\t}\n\t\tmodifiedString, ok := modifiedValue.(string)\n\t\tif !ok {\n\t\t\treturn false, fmt.Errorf(\"invalid value for special key: %s\", directiveMarker)\n\t\t}\n\t\tif modifiedString != originalString {\n\t\t\tpatch[directiveMarker] = modifiedValue\n\t\t}\n\t\treturn true, nil\n\t}\n\treturn false, nil\n}","line":{"from":236,"to":253}} {"id":100016081,"name":"handleMapDiff","signature":"func handleMapDiff(key string, originalValue, modifiedValue, patch map[string]interface{},","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// handleMapDiff diff between 2 maps `originalValueTyped` and `modifiedValue`,\n// puts the diff in the `patch` associated with `key`\n// key is the key associated with originalValue and modifiedValue.\n// originalValue, modifiedValue are the old and new value respectively.They are both maps\n// patch is the patch map that contains key and the updated value, and it is the parent of originalValue, modifiedValue\n// diffOptions contains multiple options to control how we do the diff.\nfunc handleMapDiff(key string, originalValue, modifiedValue, patch map[string]interface{},\n\tschema LookupPatchMeta, diffOptions DiffOptions) error {\n\tsubschema, patchMeta, err := schema.LookupPatchMetadataForStruct(key)\n\n\tif err != nil {\n\t\t// We couldn't look up metadata for the field\n\t\t// If the values are identical, this doesn't matter, no patch is needed\n\t\tif reflect.DeepEqual(originalValue, modifiedValue) {\n\t\t\treturn nil\n\t\t}\n\t\t// Otherwise, return the error\n\t\treturn err\n\t}\n\tretainKeys, patchStrategy, err := extractRetainKeysPatchStrategy(patchMeta.GetPatchStrategies())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdiffOptions.BuildRetainKeysDirective = retainKeys\n\tswitch patchStrategy {\n\t// The patch strategic from metadata tells us to replace the entire object instead of diffing it\n\tcase replaceDirective:\n\t\tif !diffOptions.IgnoreChangesAndAdditions {\n\t\t\tpatch[key] = modifiedValue\n\t\t}\n\tdefault:\n\t\tpatchValue, err := diffMaps(originalValue, modifiedValue, subschema, diffOptions)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Maps were not identical, use provided patch value\n\t\tif len(patchValue) \u003e 0 {\n\t\t\tpatch[key] = patchValue\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":255,"to":296}} {"id":100016082,"name":"handleSliceDiff","signature":"func handleSliceDiff(key string, originalValue, modifiedValue []interface{}, patch map[string]interface{},","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// handleSliceDiff diff between 2 slices `originalValueTyped` and `modifiedValue`,\n// puts the diff in the `patch` associated with `key`\n// key is the key associated with originalValue and modifiedValue.\n// originalValue, modifiedValue are the old and new value respectively.They are both slices\n// patch is the patch map that contains key and the updated value, and it is the parent of originalValue, modifiedValue\n// diffOptions contains multiple options to control how we do the diff.\nfunc handleSliceDiff(key string, originalValue, modifiedValue []interface{}, patch map[string]interface{},\n\tschema LookupPatchMeta, diffOptions DiffOptions) error {\n\tsubschema, patchMeta, err := schema.LookupPatchMetadataForSlice(key)\n\tif err != nil {\n\t\t// We couldn't look up metadata for the field\n\t\t// If the values are identical, this doesn't matter, no patch is needed\n\t\tif reflect.DeepEqual(originalValue, modifiedValue) {\n\t\t\treturn nil\n\t\t}\n\t\t// Otherwise, return the error\n\t\treturn err\n\t}\n\tretainKeys, patchStrategy, err := extractRetainKeysPatchStrategy(patchMeta.GetPatchStrategies())\n\tif err != nil {\n\t\treturn err\n\t}\n\tswitch patchStrategy {\n\t// Merge the 2 slices using mergePatchKey\n\tcase mergeDirective:\n\t\tdiffOptions.BuildRetainKeysDirective = retainKeys\n\t\taddList, deletionList, setOrderList, err := diffLists(originalValue, modifiedValue, subschema, patchMeta.GetPatchMergeKey(), diffOptions)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(addList) \u003e 0 {\n\t\t\tpatch[key] = addList\n\t\t}\n\t\t// generate a parallel list for deletion\n\t\tif len(deletionList) \u003e 0 {\n\t\t\tparallelDeletionListKey := fmt.Sprintf(\"%s/%s\", deleteFromPrimitiveListDirectivePrefix, key)\n\t\t\tpatch[parallelDeletionListKey] = deletionList\n\t\t}\n\t\tif len(setOrderList) \u003e 0 {\n\t\t\tparallelSetOrderListKey := fmt.Sprintf(\"%s/%s\", setElementOrderDirectivePrefix, key)\n\t\t\tpatch[parallelSetOrderListKey] = setOrderList\n\t\t}\n\tdefault:\n\t\treplacePatchFieldIfNotEqual(key, originalValue, modifiedValue, patch, diffOptions)\n\t}\n\treturn nil\n}","line":{"from":298,"to":344}} {"id":100016083,"name":"replacePatchFieldIfNotEqual","signature":"func replacePatchFieldIfNotEqual(key string, original, modified interface{},","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// replacePatchFieldIfNotEqual updates the patch if original and modified are not deep equal\n// if diffOptions.IgnoreChangesAndAdditions is false.\n// original is the old value, maybe either the live cluster object or the last applied configuration\n// modified is the new value, is always the users new config\nfunc replacePatchFieldIfNotEqual(key string, original, modified interface{},\n\tpatch map[string]interface{}, diffOptions DiffOptions) {\n\tif diffOptions.IgnoreChangesAndAdditions {\n\t\t// Ignoring changes - do nothing\n\t\treturn\n\t}\n\tif reflect.DeepEqual(original, modified) {\n\t\t// Contents are identical - do nothing\n\t\treturn\n\t}\n\t// Create a patch to replace the old value with the new one\n\tpatch[key] = modified\n}","line":{"from":346,"to":362}} {"id":100016084,"name":"updatePatchIfMissing","signature":"func updatePatchIfMissing(original, modified, patch map[string]interface{}, diffOptions DiffOptions)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// updatePatchIfMissing iterates over `original` when ignoreDeletions is false.\n// Clear the field whose key is not present in `modified`.\n// original is the old value, maybe either the live cluster object or the last applied configuration\n// modified is the new value, is always the users new config\nfunc updatePatchIfMissing(original, modified, patch map[string]interface{}, diffOptions DiffOptions) {\n\tif diffOptions.IgnoreDeletions {\n\t\t// Ignoring deletion - do nothing\n\t\treturn\n\t}\n\t// Add nils for deleted values\n\tfor key := range original {\n\t\tif _, found := modified[key]; !found {\n\t\t\tpatch[key] = nil\n\t\t}\n\t}\n}","line":{"from":364,"to":379}} {"id":100016085,"name":"validateMergeKeyInLists","signature":"func validateMergeKeyInLists(mergeKey string, lists ...[]interface{}) error","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// validateMergeKeyInLists checks if each map in the list has the mentryerge key.\nfunc validateMergeKeyInLists(mergeKey string, lists ...[]interface{}) error {\n\tfor _, list := range lists {\n\t\tfor _, item := range list {\n\t\t\tm, ok := item.(map[string]interface{})\n\t\t\tif !ok {\n\t\t\t\treturn mergepatch.ErrBadArgType(m, item)\n\t\t\t}\n\t\t\tif _, ok = m[mergeKey]; !ok {\n\t\t\t\treturn mergepatch.ErrNoMergeKey(m, mergeKey)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":381,"to":395}} {"id":100016086,"name":"normalizeElementOrder","signature":"func normalizeElementOrder(patch, serverOnly, patchOrder, serverOrder []interface{}, mergeKey string, kind reflect.Kind) ([]interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// normalizeElementOrder sort `patch` list by `patchOrder` and sort `serverOnly` list by `serverOrder`.\n// Then it merges the 2 sorted lists.\n// It guarantee the relative order in the patch list and in the serverOnly list is kept.\n// `patch` is a list of items in the patch, and `serverOnly` is a list of items in the live object.\n// `patchOrder` is the order we want `patch` list to have and\n// `serverOrder` is the order we want `serverOnly` list to have.\n// kind is the kind of each item in the lists `patch` and `serverOnly`.\nfunc normalizeElementOrder(patch, serverOnly, patchOrder, serverOrder []interface{}, mergeKey string, kind reflect.Kind) ([]interface{}, error) {\n\tpatch, err := normalizeSliceOrder(patch, patchOrder, mergeKey, kind)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tserverOnly, err = normalizeSliceOrder(serverOnly, serverOrder, mergeKey, kind)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tall := mergeSortedSlice(serverOnly, patch, serverOrder, mergeKey, kind)\n\n\treturn all, nil\n}","line":{"from":397,"to":416}} {"id":100016087,"name":"mergeSortedSlice","signature":"func mergeSortedSlice(left, right, serverOrder []interface{}, mergeKey string, kind reflect.Kind) []interface{}","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// mergeSortedSlice merges the 2 sorted lists by serverOrder with best effort.\n// It will insert each item in `left` list to `right` list. In most cases, the 2 lists will be interleaved.\n// The relative order of left and right are guaranteed to be kept.\n// They have higher precedence than the order in the live list.\n// The place for a item in `left` is found by:\n// scan from the place of last insertion in `right` to the end of `right`,\n// the place is before the first item that is greater than the item we want to insert.\n// example usage: using server-only items as left and patch items as right. We insert server-only items\n// to patch list. We use the order of live object as record for comparison.\nfunc mergeSortedSlice(left, right, serverOrder []interface{}, mergeKey string, kind reflect.Kind) []interface{} {\n\t// Returns if l is less than r, and if both have been found.\n\t// If l and r both present and l is in front of r, l is less than r.\n\tless := func(l, r interface{}) (bool, bool) {\n\t\tli := index(serverOrder, l, mergeKey, kind)\n\t\tri := index(serverOrder, r, mergeKey, kind)\n\t\tif li \u003e= 0 \u0026\u0026 ri \u003e= 0 {\n\t\t\treturn li \u003c ri, true\n\t\t} else {\n\t\t\treturn false, false\n\t\t}\n\t}\n\n\t// left and right should be non-overlapping.\n\tsize := len(left) + len(right)\n\ti, j := 0, 0\n\ts := make([]interface{}, size, size)\n\n\tfor k := 0; k \u003c size; k++ {\n\t\tif i \u003e= len(left) \u0026\u0026 j \u003c len(right) {\n\t\t\t// have items left in `right` list\n\t\t\ts[k] = right[j]\n\t\t\tj++\n\t\t} else if j \u003e= len(right) \u0026\u0026 i \u003c len(left) {\n\t\t\t// have items left in `left` list\n\t\t\ts[k] = left[i]\n\t\t\ti++\n\t\t} else {\n\t\t\t// compare them if i and j are both in bound\n\t\t\tless, foundBoth := less(left[i], right[j])\n\t\t\tif foundBoth \u0026\u0026 less {\n\t\t\t\ts[k] = left[i]\n\t\t\t\ti++\n\t\t\t} else {\n\t\t\t\ts[k] = right[j]\n\t\t\t\tj++\n\t\t\t}\n\t\t}\n\t}\n\treturn s\n}","line":{"from":418,"to":467}} {"id":100016088,"name":"index","signature":"func index(l []interface{}, valToLookUp interface{}, mergeKey string, kind reflect.Kind) int","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// index returns the index of the item in the given items, or -1 if it doesn't exist\n// l must NOT be a slice of slices, this should be checked before calling.\nfunc index(l []interface{}, valToLookUp interface{}, mergeKey string, kind reflect.Kind) int {\n\tvar getValFn func(interface{}) interface{}\n\t// Get the correct `getValFn` based on item `kind`.\n\t// It should return the value of merge key for maps and\n\t// return the item for other kinds.\n\tswitch kind {\n\tcase reflect.Map:\n\t\tgetValFn = func(item interface{}) interface{} {\n\t\t\ttypedItem, ok := item.(map[string]interface{})\n\t\t\tif !ok {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tval := typedItem[mergeKey]\n\t\t\treturn val\n\t\t}\n\tdefault:\n\t\tgetValFn = func(item interface{}) interface{} {\n\t\t\treturn item\n\t\t}\n\t}\n\n\tfor i, v := range l {\n\t\tif getValFn(valToLookUp) == getValFn(v) {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}","line":{"from":469,"to":498}} {"id":100016089,"name":"extractToDeleteItems","signature":"func extractToDeleteItems(l []interface{}) ([]interface{}, []interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// extractToDeleteItems takes a list and\n// returns 2 lists: one contains items that should be kept and the other contains items to be deleted.\nfunc extractToDeleteItems(l []interface{}) ([]interface{}, []interface{}, error) {\n\tvar nonDelete, toDelete []interface{}\n\tfor _, v := range l {\n\t\tm, ok := v.(map[string]interface{})\n\t\tif !ok {\n\t\t\treturn nil, nil, mergepatch.ErrBadArgType(m, v)\n\t\t}\n\n\t\tdirective, foundDirective := m[directiveMarker]\n\t\tif foundDirective \u0026\u0026 directive == deleteDirective {\n\t\t\ttoDelete = append(toDelete, v)\n\t\t} else {\n\t\t\tnonDelete = append(nonDelete, v)\n\t\t}\n\t}\n\treturn nonDelete, toDelete, nil\n}","line":{"from":500,"to":518}} {"id":100016090,"name":"normalizeSliceOrder","signature":"func normalizeSliceOrder(toSort, order []interface{}, mergeKey string, kind reflect.Kind) ([]interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// normalizeSliceOrder sort `toSort` list by `order`\nfunc normalizeSliceOrder(toSort, order []interface{}, mergeKey string, kind reflect.Kind) ([]interface{}, error) {\n\tvar toDelete []interface{}\n\tif kind == reflect.Map {\n\t\t// make sure each item in toSort, order has merge key\n\t\terr := validateMergeKeyInLists(mergeKey, toSort, order)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttoSort, toDelete, err = extractToDeleteItems(toSort)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tsort.SliceStable(toSort, func(i, j int) bool {\n\t\tif ii := index(order, toSort[i], mergeKey, kind); ii \u003e= 0 {\n\t\t\tif ij := index(order, toSort[j], mergeKey, kind); ij \u003e= 0 {\n\t\t\t\treturn ii \u003c ij\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n\ttoSort = append(toSort, toDelete...)\n\treturn toSort, nil\n}","line":{"from":520,"to":545}} {"id":100016091,"name":"diffLists","signature":"func diffLists(original, modified []interface{}, schema LookupPatchMeta, mergeKey string, diffOptions DiffOptions) ([]interface{}, []interface{}, []interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// Returns a (recursive) strategic merge patch, a parallel deletion list if necessary and\n// another list to set the order of the list\n// Only list of primitives with merge strategy will generate a parallel deletion list.\n// These two lists should yield modified when applied to original, for lists with merge semantics.\nfunc diffLists(original, modified []interface{}, schema LookupPatchMeta, mergeKey string, diffOptions DiffOptions) ([]interface{}, []interface{}, []interface{}, error) {\n\tif len(original) == 0 {\n\t\t// Both slices are empty - do nothing\n\t\tif len(modified) == 0 || diffOptions.IgnoreChangesAndAdditions {\n\t\t\treturn nil, nil, nil, nil\n\t\t}\n\n\t\t// Old slice was empty - add all elements from the new slice\n\t\treturn modified, nil, nil, nil\n\t}\n\n\telementType, err := sliceElementType(original, modified)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tvar patchList, deleteList, setOrderList []interface{}\n\tkind := elementType.Kind()\n\tswitch kind {\n\tcase reflect.Map:\n\t\tpatchList, deleteList, err = diffListsOfMaps(original, modified, schema, mergeKey, diffOptions)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t\tpatchList, err = normalizeSliceOrder(patchList, modified, mergeKey, kind)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t\torderSame, err := isOrderSame(original, modified, mergeKey)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t\t// append the deletions to the end of the patch list.\n\t\tpatchList = append(patchList, deleteList...)\n\t\tdeleteList = nil\n\t\t// generate the setElementOrder list when there are content changes or order changes\n\t\tif diffOptions.SetElementOrder \u0026\u0026\n\t\t\t((!diffOptions.IgnoreChangesAndAdditions \u0026\u0026 (len(patchList) \u003e 0 || !orderSame)) ||\n\t\t\t\t(!diffOptions.IgnoreDeletions \u0026\u0026 len(patchList) \u003e 0)) {\n\t\t\t// Generate a list of maps that each item contains only the merge key.\n\t\t\tsetOrderList = make([]interface{}, len(modified))\n\t\t\tfor i, v := range modified {\n\t\t\t\ttypedV := v.(map[string]interface{})\n\t\t\t\tsetOrderList[i] = map[string]interface{}{\n\t\t\t\t\tmergeKey: typedV[mergeKey],\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase reflect.Slice:\n\t\t// Lists of Lists are not permitted by the api\n\t\treturn nil, nil, nil, mergepatch.ErrNoListOfLists\n\tdefault:\n\t\tpatchList, deleteList, err = diffListsOfScalars(original, modified, diffOptions)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t\tpatchList, err = normalizeSliceOrder(patchList, modified, mergeKey, kind)\n\t\t// generate the setElementOrder list when there are content changes or order changes\n\t\tif diffOptions.SetElementOrder \u0026\u0026 ((!diffOptions.IgnoreDeletions \u0026\u0026 len(deleteList) \u003e 0) ||\n\t\t\t(!diffOptions.IgnoreChangesAndAdditions \u0026\u0026 !reflect.DeepEqual(original, modified))) {\n\t\t\tsetOrderList = modified\n\t\t}\n\t}\n\treturn patchList, deleteList, setOrderList, err\n}","line":{"from":547,"to":615}} {"id":100016092,"name":"isOrderSame","signature":"func isOrderSame(original, modified []interface{}, mergeKey string) (bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// isOrderSame checks if the order in a list has changed\nfunc isOrderSame(original, modified []interface{}, mergeKey string) (bool, error) {\n\tif len(original) != len(modified) {\n\t\treturn false, nil\n\t}\n\tfor i, modifiedItem := range modified {\n\t\tequal, err := mergeKeyValueEqual(original[i], modifiedItem, mergeKey)\n\t\tif err != nil || !equal {\n\t\t\treturn equal, err\n\t\t}\n\t}\n\treturn true, nil\n}","line":{"from":617,"to":629}} {"id":100016093,"name":"diffListsOfScalars","signature":"func diffListsOfScalars(original, modified []interface{}, diffOptions DiffOptions) ([]interface{}, []interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// diffListsOfScalars returns 2 lists, the first one is addList and the second one is deletionList.\n// Argument diffOptions.IgnoreChangesAndAdditions controls if calculate addList. true means not calculate.\n// Argument diffOptions.IgnoreDeletions controls if calculate deletionList. true means not calculate.\n// original may be changed, but modified is guaranteed to not be changed\nfunc diffListsOfScalars(original, modified []interface{}, diffOptions DiffOptions) ([]interface{}, []interface{}, error) {\n\tmodifiedCopy := make([]interface{}, len(modified))\n\tcopy(modifiedCopy, modified)\n\t// Sort the scalars for easier calculating the diff\n\toriginalScalars := sortScalars(original)\n\tmodifiedScalars := sortScalars(modifiedCopy)\n\n\toriginalIndex, modifiedIndex := 0, 0\n\taddList := []interface{}{}\n\tdeletionList := []interface{}{}\n\n\tfor {\n\t\toriginalInBounds := originalIndex \u003c len(originalScalars)\n\t\tmodifiedInBounds := modifiedIndex \u003c len(modifiedScalars)\n\t\tif !originalInBounds \u0026\u0026 !modifiedInBounds {\n\t\t\tbreak\n\t\t}\n\t\t// we need to compare the string representation of the scalar,\n\t\t// because the scalar is an interface which doesn't support either \u003c or \u003e\n\t\t// And that's how func sortScalars compare scalars.\n\t\tvar originalString, modifiedString string\n\t\tvar originalValue, modifiedValue interface{}\n\t\tif originalInBounds {\n\t\t\toriginalValue = originalScalars[originalIndex]\n\t\t\toriginalString = fmt.Sprintf(\"%v\", originalValue)\n\t\t}\n\t\tif modifiedInBounds {\n\t\t\tmodifiedValue = modifiedScalars[modifiedIndex]\n\t\t\tmodifiedString = fmt.Sprintf(\"%v\", modifiedValue)\n\t\t}\n\n\t\toriginalV, modifiedV := compareListValuesAtIndex(originalInBounds, modifiedInBounds, originalString, modifiedString)\n\t\tswitch {\n\t\tcase originalV == nil \u0026\u0026 modifiedV == nil:\n\t\t\toriginalIndex++\n\t\t\tmodifiedIndex++\n\t\tcase originalV != nil \u0026\u0026 modifiedV == nil:\n\t\t\tif !diffOptions.IgnoreDeletions {\n\t\t\t\tdeletionList = append(deletionList, originalValue)\n\t\t\t}\n\t\t\toriginalIndex++\n\t\tcase originalV == nil \u0026\u0026 modifiedV != nil:\n\t\t\tif !diffOptions.IgnoreChangesAndAdditions {\n\t\t\t\taddList = append(addList, modifiedValue)\n\t\t\t}\n\t\t\tmodifiedIndex++\n\t\tdefault:\n\t\t\treturn nil, nil, fmt.Errorf(\"Unexpected returned value from compareListValuesAtIndex: %v and %v\", originalV, modifiedV)\n\t\t}\n\t}\n\n\treturn addList, deduplicateScalars(deletionList), nil\n}","line":{"from":631,"to":687}} {"id":100016094,"name":"compareListValuesAtIndex","signature":"func compareListValuesAtIndex(list1Inbounds, list2Inbounds bool, list1Value, list2Value string) (interface{}, interface{})","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// If first return value is non-nil, list1 contains an element not present in list2\n// If second return value is non-nil, list2 contains an element not present in list1\nfunc compareListValuesAtIndex(list1Inbounds, list2Inbounds bool, list1Value, list2Value string) (interface{}, interface{}) {\n\tbothInBounds := list1Inbounds \u0026\u0026 list2Inbounds\n\tswitch {\n\t// scalars are identical\n\tcase bothInBounds \u0026\u0026 list1Value == list2Value:\n\t\treturn nil, nil\n\t// only list2 is in bound\n\tcase !list1Inbounds:\n\t\tfallthrough\n\t// list2 has additional scalar\n\tcase bothInBounds \u0026\u0026 list1Value \u003e list2Value:\n\t\treturn nil, list2Value\n\t// only original is in bound\n\tcase !list2Inbounds:\n\t\tfallthrough\n\t// original has additional scalar\n\tcase bothInBounds \u0026\u0026 list1Value \u003c list2Value:\n\t\treturn list1Value, nil\n\tdefault:\n\t\treturn nil, nil\n\t}\n}","line":{"from":689,"to":712}} {"id":100016095,"name":"diffListsOfMaps","signature":"func diffListsOfMaps(original, modified []interface{}, schema LookupPatchMeta, mergeKey string, diffOptions DiffOptions) ([]interface{}, []interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// diffListsOfMaps takes a pair of lists and\n// returns a (recursive) strategic merge patch list contains additions and changes and\n// a deletion list contains deletions\nfunc diffListsOfMaps(original, modified []interface{}, schema LookupPatchMeta, mergeKey string, diffOptions DiffOptions) ([]interface{}, []interface{}, error) {\n\tpatch := make([]interface{}, 0, len(modified))\n\tdeletionList := make([]interface{}, 0, len(original))\n\n\toriginalSorted, err := sortMergeListsByNameArray(original, schema, mergeKey, false)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tmodifiedSorted, err := sortMergeListsByNameArray(modified, schema, mergeKey, false)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\toriginalIndex, modifiedIndex := 0, 0\n\tfor {\n\t\toriginalInBounds := originalIndex \u003c len(originalSorted)\n\t\tmodifiedInBounds := modifiedIndex \u003c len(modifiedSorted)\n\t\tbothInBounds := originalInBounds \u0026\u0026 modifiedInBounds\n\t\tif !originalInBounds \u0026\u0026 !modifiedInBounds {\n\t\t\tbreak\n\t\t}\n\n\t\tvar originalElementMergeKeyValueString, modifiedElementMergeKeyValueString string\n\t\tvar originalElementMergeKeyValue, modifiedElementMergeKeyValue interface{}\n\t\tvar originalElement, modifiedElement map[string]interface{}\n\t\tif originalInBounds {\n\t\t\toriginalElement, originalElementMergeKeyValue, err = getMapAndMergeKeyValueByIndex(originalIndex, mergeKey, originalSorted)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\toriginalElementMergeKeyValueString = fmt.Sprintf(\"%v\", originalElementMergeKeyValue)\n\t\t}\n\t\tif modifiedInBounds {\n\t\t\tmodifiedElement, modifiedElementMergeKeyValue, err = getMapAndMergeKeyValueByIndex(modifiedIndex, mergeKey, modifiedSorted)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\tmodifiedElementMergeKeyValueString = fmt.Sprintf(\"%v\", modifiedElementMergeKeyValue)\n\t\t}\n\n\t\tswitch {\n\t\tcase bothInBounds \u0026\u0026 ItemMatchesOriginalAndModifiedSlice(originalElementMergeKeyValueString, modifiedElementMergeKeyValueString):\n\t\t\t// Merge key values are equal, so recurse\n\t\t\tpatchValue, err := diffMaps(originalElement, modifiedElement, schema, diffOptions)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\tif len(patchValue) \u003e 0 {\n\t\t\t\tpatchValue[mergeKey] = modifiedElementMergeKeyValue\n\t\t\t\tpatch = append(patch, patchValue)\n\t\t\t}\n\t\t\toriginalIndex++\n\t\t\tmodifiedIndex++\n\t\t// only modified is in bound\n\t\tcase !originalInBounds:\n\t\t\tfallthrough\n\t\t// modified has additional map\n\t\tcase bothInBounds \u0026\u0026 ItemAddedToModifiedSlice(originalElementMergeKeyValueString, modifiedElementMergeKeyValueString):\n\t\t\tif !diffOptions.IgnoreChangesAndAdditions {\n\t\t\t\tpatch = append(patch, modifiedElement)\n\t\t\t}\n\t\t\tmodifiedIndex++\n\t\t// only original is in bound\n\t\tcase !modifiedInBounds:\n\t\t\tfallthrough\n\t\t// original has additional map\n\t\tcase bothInBounds \u0026\u0026 ItemRemovedFromModifiedSlice(originalElementMergeKeyValueString, modifiedElementMergeKeyValueString):\n\t\t\tif !diffOptions.IgnoreDeletions {\n\t\t\t\t// Item was deleted, so add delete directive\n\t\t\t\tdeletionList = append(deletionList, CreateDeleteDirective(mergeKey, originalElementMergeKeyValue))\n\t\t\t}\n\t\t\toriginalIndex++\n\t\t}\n\t}\n\n\treturn patch, deletionList, nil\n}","line":{"from":714,"to":793}} {"id":100016096,"name":"getMapAndMergeKeyValueByIndex","signature":"func getMapAndMergeKeyValueByIndex(index int, mergeKey string, listOfMaps []interface{}) (map[string]interface{}, interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// getMapAndMergeKeyValueByIndex return a map in the list and its merge key value given the index of the map.\nfunc getMapAndMergeKeyValueByIndex(index int, mergeKey string, listOfMaps []interface{}) (map[string]interface{}, interface{}, error) {\n\tm, ok := listOfMaps[index].(map[string]interface{})\n\tif !ok {\n\t\treturn nil, nil, mergepatch.ErrBadArgType(m, listOfMaps[index])\n\t}\n\n\tval, ok := m[mergeKey]\n\tif !ok {\n\t\treturn nil, nil, mergepatch.ErrNoMergeKey(m, mergeKey)\n\t}\n\treturn m, val, nil\n}","line":{"from":795,"to":807}} {"id":100016097,"name":"StrategicMergePatch","signature":"func StrategicMergePatch(original, patch []byte, dataStruct interface{}) ([]byte, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// StrategicMergePatch applies a strategic merge patch. The patch and the original document\n// must be json encoded content. A patch can be created from an original and a modified document\n// by calling CreateStrategicMergePatch.\nfunc StrategicMergePatch(original, patch []byte, dataStruct interface{}) ([]byte, error) {\n\tschema, err := NewPatchMetaFromStruct(dataStruct)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn StrategicMergePatchUsingLookupPatchMeta(original, patch, schema)\n}","line":{"from":809,"to":819}} {"id":100016098,"name":"StrategicMergePatchUsingLookupPatchMeta","signature":"func StrategicMergePatchUsingLookupPatchMeta(original, patch []byte, schema LookupPatchMeta) ([]byte, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func StrategicMergePatchUsingLookupPatchMeta(original, patch []byte, schema LookupPatchMeta) ([]byte, error) {\n\toriginalMap, err := handleUnmarshal(original)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpatchMap, err := handleUnmarshal(patch)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult, err := StrategicMergeMapPatchUsingLookupPatchMeta(originalMap, patchMap, schema)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn json.Marshal(result)\n}","line":{"from":821,"to":837}} {"id":100016099,"name":"handleUnmarshal","signature":"func handleUnmarshal(j []byte) (map[string]interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func handleUnmarshal(j []byte) (map[string]interface{}, error) {\n\tif j == nil {\n\t\tj = []byte(\"{}\")\n\t}\n\n\tm := map[string]interface{}{}\n\terr := json.Unmarshal(j, \u0026m)\n\tif err != nil {\n\t\treturn nil, mergepatch.ErrBadJSONDoc\n\t}\n\treturn m, nil\n}","line":{"from":839,"to":850}} {"id":100016100,"name":"StrategicMergeMapPatch","signature":"func StrategicMergeMapPatch(original, patch JSONMap, dataStruct interface{}) (JSONMap, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// StrategicMergeMapPatch applies a strategic merge patch. The original and patch documents\n// must be JSONMap. A patch can be created from an original and modified document by\n// calling CreateTwoWayMergeMapPatch.\n// Warning: the original and patch JSONMap objects are mutated by this function and should not be reused.\nfunc StrategicMergeMapPatch(original, patch JSONMap, dataStruct interface{}) (JSONMap, error) {\n\tschema, err := NewPatchMetaFromStruct(dataStruct)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// We need the go struct tags `patchMergeKey` and `patchStrategy` for fields that support a strategic merge patch.\n\t// For native resources, we can easily figure out these tags since we know the fields.\n\n\t// Because custom resources are decoded as Unstructured and because we're missing the metadata about how to handle\n\t// each field in a strategic merge patch, we can't find the go struct tags. Hence, we can't easily do a strategic merge\n\t// for custom resources. So we should fail fast and return an error.\n\tif _, ok := dataStruct.(*unstructured.Unstructured); ok {\n\t\treturn nil, mergepatch.ErrUnsupportedStrategicMergePatchFormat\n\t}\n\n\treturn StrategicMergeMapPatchUsingLookupPatchMeta(original, patch, schema)\n}","line":{"from":852,"to":873}} {"id":100016101,"name":"StrategicMergeMapPatchUsingLookupPatchMeta","signature":"func StrategicMergeMapPatchUsingLookupPatchMeta(original, patch JSONMap, schema LookupPatchMeta) (JSONMap, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func StrategicMergeMapPatchUsingLookupPatchMeta(original, patch JSONMap, schema LookupPatchMeta) (JSONMap, error) {\n\tmergeOptions := MergeOptions{\n\t\tMergeParallelList: true,\n\t\tIgnoreUnmatchedNulls: true,\n\t}\n\treturn mergeMap(original, patch, schema, mergeOptions)\n}","line":{"from":875,"to":881}} {"id":100016102,"name":"MergeStrategicMergeMapPatchUsingLookupPatchMeta","signature":"func MergeStrategicMergeMapPatchUsingLookupPatchMeta(schema LookupPatchMeta, patches ...JSONMap) (JSONMap, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// MergeStrategicMergeMapPatchUsingLookupPatchMeta merges strategic merge\n// patches retaining `null` fields and parallel lists. If 2 patches change the\n// same fields and the latter one will override the former one. If you don't\n// want that happen, you need to run func MergingMapsHaveConflicts before\n// merging these patches. Applying the resulting merged merge patch to a JSONMap\n// yields the same as merging each strategic merge patch to the JSONMap in\n// succession.\nfunc MergeStrategicMergeMapPatchUsingLookupPatchMeta(schema LookupPatchMeta, patches ...JSONMap) (JSONMap, error) {\n\tmergeOptions := MergeOptions{\n\t\tMergeParallelList: false,\n\t\tIgnoreUnmatchedNulls: false,\n\t}\n\tmerged := JSONMap{}\n\tvar err error\n\tfor _, patch := range patches {\n\t\tmerged, err = mergeMap(merged, patch, schema, mergeOptions)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn merged, nil\n}","line":{"from":883,"to":904}} {"id":100016103,"name":"handleDirectiveInMergeMap","signature":"func handleDirectiveInMergeMap(directive interface{}, patch map[string]interface{}) (map[string]interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// handleDirectiveInMergeMap handles the patch directive when merging 2 maps.\nfunc handleDirectiveInMergeMap(directive interface{}, patch map[string]interface{}) (map[string]interface{}, error) {\n\tif directive == replaceDirective {\n\t\t// If the patch contains \"$patch: replace\", don't merge it, just use the\n\t\t// patch directly. Later on, we can add a single level replace that only\n\t\t// affects the map that the $patch is in.\n\t\tdelete(patch, directiveMarker)\n\t\treturn patch, nil\n\t}\n\n\tif directive == deleteDirective {\n\t\t// If the patch contains \"$patch: delete\", don't merge it, just return\n\t\t// an empty map.\n\t\treturn map[string]interface{}{}, nil\n\t}\n\n\treturn nil, mergepatch.ErrBadPatchType(directive, patch)\n}","line":{"from":906,"to":923}} {"id":100016104,"name":"containsDirectiveMarker","signature":"func containsDirectiveMarker(item interface{}) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func containsDirectiveMarker(item interface{}) bool {\n\tm, ok := item.(map[string]interface{})\n\tif ok {\n\t\tif _, foundDirectiveMarker := m[directiveMarker]; foundDirectiveMarker {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":925,"to":933}} {"id":100016105,"name":"mergeKeyValueEqual","signature":"func mergeKeyValueEqual(left, right interface{}, mergeKey string) (bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func mergeKeyValueEqual(left, right interface{}, mergeKey string) (bool, error) {\n\tif len(mergeKey) == 0 {\n\t\treturn left == right, nil\n\t}\n\ttypedLeft, ok := left.(map[string]interface{})\n\tif !ok {\n\t\treturn false, mergepatch.ErrBadArgType(typedLeft, left)\n\t}\n\ttypedRight, ok := right.(map[string]interface{})\n\tif !ok {\n\t\treturn false, mergepatch.ErrBadArgType(typedRight, right)\n\t}\n\tmergeKeyLeft, ok := typedLeft[mergeKey]\n\tif !ok {\n\t\treturn false, mergepatch.ErrNoMergeKey(typedLeft, mergeKey)\n\t}\n\tmergeKeyRight, ok := typedRight[mergeKey]\n\tif !ok {\n\t\treturn false, mergepatch.ErrNoMergeKey(typedRight, mergeKey)\n\t}\n\treturn mergeKeyLeft == mergeKeyRight, nil\n}","line":{"from":935,"to":956}} {"id":100016106,"name":"extractKey","signature":"func extractKey(s, prefix string) (string, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// extractKey trims the prefix and return the original key\nfunc extractKey(s, prefix string) (string, error) {\n\tsubstrings := strings.SplitN(s, \"/\", 2)\n\tif len(substrings) \u003c= 1 || substrings[0] != prefix {\n\t\tswitch prefix {\n\t\tcase deleteFromPrimitiveListDirectivePrefix:\n\t\t\treturn \"\", mergepatch.ErrBadPatchFormatForPrimitiveList\n\t\tcase setElementOrderDirectivePrefix:\n\t\t\treturn \"\", mergepatch.ErrBadPatchFormatForSetElementOrderList\n\t\tdefault:\n\t\t\treturn \"\", fmt.Errorf(\"fail to find unknown prefix %q in %s\\n\", prefix, s)\n\t\t}\n\t}\n\treturn substrings[1], nil\n}","line":{"from":958,"to":972}} {"id":100016107,"name":"validatePatchWithSetOrderList","signature":"func validatePatchWithSetOrderList(patchList, setOrderList interface{}, mergeKey string) error","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// validatePatchUsingSetOrderList verifies:\n// the relative order of any two items in the setOrderList list matches that in the patch list.\n// the items in the patch list must be a subset or the same as the $setElementOrder list (deletions are ignored).\nfunc validatePatchWithSetOrderList(patchList, setOrderList interface{}, mergeKey string) error {\n\ttypedSetOrderList, ok := setOrderList.([]interface{})\n\tif !ok {\n\t\treturn mergepatch.ErrBadPatchFormatForSetElementOrderList\n\t}\n\ttypedPatchList, ok := patchList.([]interface{})\n\tif !ok {\n\t\treturn mergepatch.ErrBadPatchFormatForSetElementOrderList\n\t}\n\tif len(typedSetOrderList) == 0 || len(typedPatchList) == 0 {\n\t\treturn nil\n\t}\n\n\tvar nonDeleteList []interface{}\n\tvar err error\n\tif len(mergeKey) \u003e 0 {\n\t\tnonDeleteList, _, err = extractToDeleteItems(typedPatchList)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tnonDeleteList = typedPatchList\n\t}\n\n\tpatchIndex, setOrderIndex := 0, 0\n\tfor patchIndex \u003c len(nonDeleteList) \u0026\u0026 setOrderIndex \u003c len(typedSetOrderList) {\n\t\tif containsDirectiveMarker(nonDeleteList[patchIndex]) {\n\t\t\tpatchIndex++\n\t\t\tcontinue\n\t\t}\n\t\tmergeKeyEqual, err := mergeKeyValueEqual(nonDeleteList[patchIndex], typedSetOrderList[setOrderIndex], mergeKey)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif mergeKeyEqual {\n\t\t\tpatchIndex++\n\t\t}\n\t\tsetOrderIndex++\n\t}\n\t// If patchIndex is inbound but setOrderIndex if out of bound mean there are items mismatching between the patch list and setElementOrder list.\n\t// the second check is a sanity check, and should always be true if the first is true.\n\tif patchIndex \u003c len(nonDeleteList) \u0026\u0026 setOrderIndex \u003e= len(typedSetOrderList) {\n\t\treturn fmt.Errorf(\"The order in patch list:\\n%v\\n doesn't match %s list:\\n%v\\n\", typedPatchList, setElementOrderDirectivePrefix, setOrderList)\n\t}\n\treturn nil\n}","line":{"from":974,"to":1022}} {"id":100016108,"name":"preprocessDeletionListForMerging","signature":"func preprocessDeletionListForMerging(key string, original map[string]interface{},","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// preprocessDeletionListForMerging preprocesses the deletion list.\n// it returns shouldContinue, isDeletionList, noPrefixKey\nfunc preprocessDeletionListForMerging(key string, original map[string]interface{},\n\tpatchVal interface{}, mergeDeletionList bool) (bool, bool, string, error) {\n\t// If found a parallel list for deletion and we are going to merge the list,\n\t// overwrite the key to the original key and set flag isDeleteList\n\tfoundParallelListPrefix := strings.HasPrefix(key, deleteFromPrimitiveListDirectivePrefix)\n\tif foundParallelListPrefix {\n\t\tif !mergeDeletionList {\n\t\t\toriginal[key] = patchVal\n\t\t\treturn true, false, \"\", nil\n\t\t}\n\t\toriginalKey, err := extractKey(key, deleteFromPrimitiveListDirectivePrefix)\n\t\treturn false, true, originalKey, err\n\t}\n\treturn false, false, \"\", nil\n}","line":{"from":1024,"to":1040}} {"id":100016109,"name":"applyRetainKeysDirective","signature":"func applyRetainKeysDirective(original, patch map[string]interface{}, options MergeOptions) error","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// applyRetainKeysDirective looks for a retainKeys directive and applies to original\n// - if no directive exists do nothing\n// - if directive is found, clear keys in original missing from the directive list\n// - validate that all keys present in the patch are present in the retainKeys directive\n// note: original may be another patch request, e.g. applying the add+modified patch to the deletions patch. In this case it may have directives\nfunc applyRetainKeysDirective(original, patch map[string]interface{}, options MergeOptions) error {\n\tretainKeysInPatch, foundInPatch := patch[retainKeysDirective]\n\tif !foundInPatch {\n\t\treturn nil\n\t}\n\t// cleanup the directive\n\tdelete(patch, retainKeysDirective)\n\n\tif !options.MergeParallelList {\n\t\t// If original is actually a patch, make sure the retainKeys directives are the same in both patches if present in both.\n\t\t// If not present in the original patch, copy from the modified patch.\n\t\tretainKeysInOriginal, foundInOriginal := original[retainKeysDirective]\n\t\tif foundInOriginal {\n\t\t\tif !reflect.DeepEqual(retainKeysInOriginal, retainKeysInPatch) {\n\t\t\t\t// This error actually should never happen.\n\t\t\t\treturn fmt.Errorf(\"%v and %v are not deep equal: this may happen when calculating the 3-way diff patch\", retainKeysInOriginal, retainKeysInPatch)\n\t\t\t}\n\t\t} else {\n\t\t\toriginal[retainKeysDirective] = retainKeysInPatch\n\t\t}\n\t\treturn nil\n\t}\n\n\tretainKeysList, ok := retainKeysInPatch.([]interface{})\n\tif !ok {\n\t\treturn mergepatch.ErrBadPatchFormatForRetainKeys\n\t}\n\n\t// validate patch to make sure all fields in the patch are present in the retainKeysList.\n\t// The map is used only as a set, the value is never referenced\n\tm := map[interface{}]struct{}{}\n\tfor _, v := range retainKeysList {\n\t\tm[v] = struct{}{}\n\t}\n\tfor k, v := range patch {\n\t\tif v == nil || strings.HasPrefix(k, deleteFromPrimitiveListDirectivePrefix) ||\n\t\t\tstrings.HasPrefix(k, setElementOrderDirectivePrefix) {\n\t\t\tcontinue\n\t\t}\n\t\t// If there is an item present in the patch but not in the retainKeys list,\n\t\t// the patch is invalid.\n\t\tif _, found := m[k]; !found {\n\t\t\treturn mergepatch.ErrBadPatchFormatForRetainKeys\n\t\t}\n\t}\n\n\t// clear not present fields\n\tfor k := range original {\n\t\tif _, found := m[k]; !found {\n\t\t\tdelete(original, k)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":1042,"to":1100}} {"id":100016110,"name":"mergePatchIntoOriginal","signature":"func mergePatchIntoOriginal(original, patch map[string]interface{}, schema LookupPatchMeta, mergeOptions MergeOptions) error","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// mergePatchIntoOriginal processes $setElementOrder list.\n// When not merging the directive, it will make sure $setElementOrder list exist only in original.\n// When merging the directive, it will try to find the $setElementOrder list and\n// its corresponding patch list, validate it and merge it.\n// Then, sort them by the relative order in setElementOrder, patch list and live list.\n// The precedence is $setElementOrder \u003e order in patch list \u003e order in live list.\n// This function will delete the item after merging it to prevent process it again in the future.\n// Ref: https://git.k8s.io/design-proposals-archive/cli/preserve-order-in-strategic-merge-patch.md\nfunc mergePatchIntoOriginal(original, patch map[string]interface{}, schema LookupPatchMeta, mergeOptions MergeOptions) error {\n\tfor key, patchV := range patch {\n\t\t// Do nothing if there is no ordering directive\n\t\tif !strings.HasPrefix(key, setElementOrderDirectivePrefix) {\n\t\t\tcontinue\n\t\t}\n\n\t\tsetElementOrderInPatch := patchV\n\t\t// Copies directive from the second patch (`patch`) to the first patch (`original`)\n\t\t// and checks they are equal and delete the directive in the second patch\n\t\tif !mergeOptions.MergeParallelList {\n\t\t\tsetElementOrderListInOriginal, ok := original[key]\n\t\t\tif ok {\n\t\t\t\t// check if the setElementOrder list in original and the one in patch matches\n\t\t\t\tif !reflect.DeepEqual(setElementOrderListInOriginal, setElementOrderInPatch) {\n\t\t\t\t\treturn mergepatch.ErrBadPatchFormatForSetElementOrderList\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// move the setElementOrder list from patch to original\n\t\t\t\toriginal[key] = setElementOrderInPatch\n\t\t\t}\n\t\t}\n\t\tdelete(patch, key)\n\n\t\tvar (\n\t\t\tok bool\n\t\t\toriginalFieldValue, patchFieldValue, merged []interface{}\n\t\t\tpatchStrategy string\n\t\t\tpatchMeta PatchMeta\n\t\t\tsubschema LookupPatchMeta\n\t\t)\n\t\ttypedSetElementOrderList, ok := setElementOrderInPatch.([]interface{})\n\t\tif !ok {\n\t\t\treturn mergepatch.ErrBadArgType(typedSetElementOrderList, setElementOrderInPatch)\n\t\t}\n\t\t// Trim the setElementOrderDirectivePrefix to get the key of the list field in original.\n\t\toriginalKey, err := extractKey(key, setElementOrderDirectivePrefix)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// try to find the list with `originalKey` in `original` and `modified` and merge them.\n\t\toriginalList, foundOriginal := original[originalKey]\n\t\tpatchList, foundPatch := patch[originalKey]\n\t\tif foundOriginal {\n\t\t\toriginalFieldValue, ok = originalList.([]interface{})\n\t\t\tif !ok {\n\t\t\t\treturn mergepatch.ErrBadArgType(originalFieldValue, originalList)\n\t\t\t}\n\t\t}\n\t\tif foundPatch {\n\t\t\tpatchFieldValue, ok = patchList.([]interface{})\n\t\t\tif !ok {\n\t\t\t\treturn mergepatch.ErrBadArgType(patchFieldValue, patchList)\n\t\t\t}\n\t\t}\n\t\tsubschema, patchMeta, err = schema.LookupPatchMetadataForSlice(originalKey)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, patchStrategy, err = extractRetainKeysPatchStrategy(patchMeta.GetPatchStrategies())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Check for consistency between the element order list and the field it applies to\n\t\terr = validatePatchWithSetOrderList(patchFieldValue, typedSetElementOrderList, patchMeta.GetPatchMergeKey())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tswitch {\n\t\tcase foundOriginal \u0026\u0026 !foundPatch:\n\t\t\t// no change to list contents\n\t\t\tmerged = originalFieldValue\n\t\tcase !foundOriginal \u0026\u0026 foundPatch:\n\t\t\t// list was added\n\t\t\tmerged = patchFieldValue\n\t\tcase foundOriginal \u0026\u0026 foundPatch:\n\t\t\tmerged, err = mergeSliceHandler(originalList, patchList, subschema,\n\t\t\t\tpatchStrategy, patchMeta.GetPatchMergeKey(), false, mergeOptions)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase !foundOriginal \u0026\u0026 !foundPatch:\n\t\t\tcontinue\n\t\t}\n\n\t\t// Split all items into patch items and server-only items and then enforce the order.\n\t\tvar patchItems, serverOnlyItems []interface{}\n\t\tif len(patchMeta.GetPatchMergeKey()) == 0 {\n\t\t\t// Primitives doesn't need merge key to do partitioning.\n\t\t\tpatchItems, serverOnlyItems = partitionPrimitivesByPresentInList(merged, typedSetElementOrderList)\n\n\t\t} else {\n\t\t\t// Maps need merge key to do partitioning.\n\t\t\tpatchItems, serverOnlyItems, err = partitionMapsByPresentInList(merged, typedSetElementOrderList, patchMeta.GetPatchMergeKey())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\telementType, err := sliceElementType(originalFieldValue, patchFieldValue)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tkind := elementType.Kind()\n\t\t// normalize merged list\n\t\t// typedSetElementOrderList contains all the relative order in typedPatchList,\n\t\t// so don't need to use typedPatchList\n\t\tboth, err := normalizeElementOrder(patchItems, serverOnlyItems, typedSetElementOrderList, originalFieldValue, patchMeta.GetPatchMergeKey(), kind)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\toriginal[originalKey] = both\n\t\t// delete patch list from patch to prevent process again in the future\n\t\tdelete(patch, originalKey)\n\t}\n\treturn nil\n}","line":{"from":1102,"to":1227}} {"id":100016111,"name":"partitionPrimitivesByPresentInList","signature":"func partitionPrimitivesByPresentInList(original, partitionBy []interface{}) ([]interface{}, []interface{})","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// partitionPrimitivesByPresentInList partitions elements into 2 slices, the first containing items present in partitionBy, the other not.\nfunc partitionPrimitivesByPresentInList(original, partitionBy []interface{}) ([]interface{}, []interface{}) {\n\tpatch := make([]interface{}, 0, len(original))\n\tserverOnly := make([]interface{}, 0, len(original))\n\tinPatch := map[interface{}]bool{}\n\tfor _, v := range partitionBy {\n\t\tinPatch[v] = true\n\t}\n\tfor _, v := range original {\n\t\tif !inPatch[v] {\n\t\t\tserverOnly = append(serverOnly, v)\n\t\t} else {\n\t\t\tpatch = append(patch, v)\n\t\t}\n\t}\n\treturn patch, serverOnly\n}","line":{"from":1229,"to":1245}} {"id":100016112,"name":"partitionMapsByPresentInList","signature":"func partitionMapsByPresentInList(original, partitionBy []interface{}, mergeKey string) ([]interface{}, []interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// partitionMapsByPresentInList partitions elements into 2 slices, the first containing items present in partitionBy, the other not.\nfunc partitionMapsByPresentInList(original, partitionBy []interface{}, mergeKey string) ([]interface{}, []interface{}, error) {\n\tpatch := make([]interface{}, 0, len(original))\n\tserverOnly := make([]interface{}, 0, len(original))\n\tfor _, v := range original {\n\t\ttypedV, ok := v.(map[string]interface{})\n\t\tif !ok {\n\t\t\treturn nil, nil, mergepatch.ErrBadArgType(typedV, v)\n\t\t}\n\t\tmergeKeyValue, foundMergeKey := typedV[mergeKey]\n\t\tif !foundMergeKey {\n\t\t\treturn nil, nil, mergepatch.ErrNoMergeKey(typedV, mergeKey)\n\t\t}\n\t\t_, _, found, err := findMapInSliceBasedOnKeyValue(partitionBy, mergeKey, mergeKeyValue)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tif !found {\n\t\t\tserverOnly = append(serverOnly, v)\n\t\t} else {\n\t\t\tpatch = append(patch, v)\n\t\t}\n\t}\n\treturn patch, serverOnly, nil\n}","line":{"from":1247,"to":1271}} {"id":100016113,"name":"mergeMap","signature":"func mergeMap(original, patch map[string]interface{}, schema LookupPatchMeta, mergeOptions MergeOptions) (map[string]interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// Merge fields from a patch map into the original map. Note: This may modify\n// both the original map and the patch because getting a deep copy of a map in\n// golang is highly non-trivial.\n// flag mergeOptions.MergeParallelList controls if using the parallel list to delete or keeping the list.\n// If patch contains any null field (e.g. field_1: null) that is not\n// present in original, then to propagate it to the end result use\n// mergeOptions.IgnoreUnmatchedNulls == false.\nfunc mergeMap(original, patch map[string]interface{}, schema LookupPatchMeta, mergeOptions MergeOptions) (map[string]interface{}, error) {\n\tif v, ok := patch[directiveMarker]; ok {\n\t\treturn handleDirectiveInMergeMap(v, patch)\n\t}\n\n\t// nil is an accepted value for original to simplify logic in other places.\n\t// If original is nil, replace it with an empty map and then apply the patch.\n\tif original == nil {\n\t\toriginal = map[string]interface{}{}\n\t}\n\n\terr := applyRetainKeysDirective(original, patch, mergeOptions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Process $setElementOrder list and other lists sharing the same key.\n\t// When not merging the directive, it will make sure $setElementOrder list exist only in original.\n\t// When merging the directive, it will process $setElementOrder and its patch list together.\n\t// This function will delete the merged elements from patch so they will not be reprocessed\n\terr = mergePatchIntoOriginal(original, patch, schema, mergeOptions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Start merging the patch into the original.\n\tfor k, patchV := range patch {\n\t\tskipProcessing, isDeleteList, noPrefixKey, err := preprocessDeletionListForMerging(k, original, patchV, mergeOptions.MergeParallelList)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif skipProcessing {\n\t\t\tcontinue\n\t\t}\n\t\tif len(noPrefixKey) \u003e 0 {\n\t\t\tk = noPrefixKey\n\t\t}\n\n\t\t// If the value of this key is null, delete the key if it exists in the\n\t\t// original. Otherwise, check if we want to preserve it or skip it.\n\t\t// Preserving the null value is useful when we want to send an explicit\n\t\t// delete to the API server.\n\t\tif patchV == nil {\n\t\t\tdelete(original, k)\n\t\t\tif mergeOptions.IgnoreUnmatchedNulls {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\t_, ok := original[k]\n\t\tif !ok {\n\t\t\tif !isDeleteList {\n\t\t\t\t// If it's not in the original document, just take the patch value.\n\t\t\t\tif mergeOptions.IgnoreUnmatchedNulls {\n\t\t\t\t\tdiscardNullValuesFromPatch(patchV)\n\t\t\t\t}\n\t\t\t\toriginal[k] = patchV\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\toriginalType := reflect.TypeOf(original[k])\n\t\tpatchType := reflect.TypeOf(patchV)\n\t\tif originalType != patchType {\n\t\t\tif !isDeleteList {\n\t\t\t\tif mergeOptions.IgnoreUnmatchedNulls {\n\t\t\t\t\tdiscardNullValuesFromPatch(patchV)\n\t\t\t\t}\n\t\t\t\toriginal[k] = patchV\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\t// If they're both maps or lists, recurse into the value.\n\t\tswitch originalType.Kind() {\n\t\tcase reflect.Map:\n\t\t\tsubschema, patchMeta, err2 := schema.LookupPatchMetadataForStruct(k)\n\t\t\tif err2 != nil {\n\t\t\t\treturn nil, err2\n\t\t\t}\n\t\t\t_, patchStrategy, err2 := extractRetainKeysPatchStrategy(patchMeta.GetPatchStrategies())\n\t\t\tif err2 != nil {\n\t\t\t\treturn nil, err2\n\t\t\t}\n\t\t\toriginal[k], err = mergeMapHandler(original[k], patchV, subschema, patchStrategy, mergeOptions)\n\t\tcase reflect.Slice:\n\t\t\tsubschema, patchMeta, err2 := schema.LookupPatchMetadataForSlice(k)\n\t\t\tif err2 != nil {\n\t\t\t\treturn nil, err2\n\t\t\t}\n\t\t\t_, patchStrategy, err2 := extractRetainKeysPatchStrategy(patchMeta.GetPatchStrategies())\n\t\t\tif err2 != nil {\n\t\t\t\treturn nil, err2\n\t\t\t}\n\t\t\toriginal[k], err = mergeSliceHandler(original[k], patchV, subschema, patchStrategy, patchMeta.GetPatchMergeKey(), isDeleteList, mergeOptions)\n\t\tdefault:\n\t\t\toriginal[k] = patchV\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn original, nil\n}","line":{"from":1273,"to":1382}} {"id":100016114,"name":"discardNullValuesFromPatch","signature":"func discardNullValuesFromPatch(patchV interface{})","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// discardNullValuesFromPatch discards all null property values from patch.\n// It traverses all slices and map types.\nfunc discardNullValuesFromPatch(patchV interface{}) {\n\tswitch patchV := patchV.(type) {\n\tcase map[string]interface{}:\n\t\tfor k, v := range patchV {\n\t\t\tif v == nil {\n\t\t\t\tdelete(patchV, k)\n\t\t\t} else {\n\t\t\t\tdiscardNullValuesFromPatch(v)\n\t\t\t}\n\t\t}\n\tcase []interface{}:\n\t\tfor _, v := range patchV {\n\t\t\tdiscardNullValuesFromPatch(v)\n\t\t}\n\t}\n}","line":{"from":1384,"to":1401}} {"id":100016115,"name":"mergeMapHandler","signature":"func mergeMapHandler(original, patch interface{}, schema LookupPatchMeta,","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// mergeMapHandler handles how to merge `patchV` whose key is `key` with `original` respecting\n// fieldPatchStrategy and mergeOptions.\nfunc mergeMapHandler(original, patch interface{}, schema LookupPatchMeta,\n\tfieldPatchStrategy string, mergeOptions MergeOptions) (map[string]interface{}, error) {\n\ttypedOriginal, typedPatch, err := mapTypeAssertion(original, patch)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif fieldPatchStrategy != replaceDirective {\n\t\treturn mergeMap(typedOriginal, typedPatch, schema, mergeOptions)\n\t} else {\n\t\treturn typedPatch, nil\n\t}\n}","line":{"from":1403,"to":1417}} {"id":100016116,"name":"mergeSliceHandler","signature":"func mergeSliceHandler(original, patch interface{}, schema LookupPatchMeta,","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// mergeSliceHandler handles how to merge `patchV` whose key is `key` with `original` respecting\n// fieldPatchStrategy, fieldPatchMergeKey, isDeleteList and mergeOptions.\nfunc mergeSliceHandler(original, patch interface{}, schema LookupPatchMeta,\n\tfieldPatchStrategy, fieldPatchMergeKey string, isDeleteList bool, mergeOptions MergeOptions) ([]interface{}, error) {\n\ttypedOriginal, typedPatch, err := sliceTypeAssertion(original, patch)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif fieldPatchStrategy == mergeDirective {\n\t\treturn mergeSlice(typedOriginal, typedPatch, schema, fieldPatchMergeKey, mergeOptions, isDeleteList)\n\t} else {\n\t\treturn typedPatch, nil\n\t}\n}","line":{"from":1419,"to":1433}} {"id":100016117,"name":"mergeSlice","signature":"func mergeSlice(original, patch []interface{}, schema LookupPatchMeta, mergeKey string, mergeOptions MergeOptions, isDeleteList bool) ([]interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// Merge two slices together. Note: This may modify both the original slice and\n// the patch because getting a deep copy of a slice in golang is highly\n// non-trivial.\nfunc mergeSlice(original, patch []interface{}, schema LookupPatchMeta, mergeKey string, mergeOptions MergeOptions, isDeleteList bool) ([]interface{}, error) {\n\tif len(original) == 0 \u0026\u0026 len(patch) == 0 {\n\t\treturn original, nil\n\t}\n\n\t// All the values must be of the same type, but not a list.\n\tt, err := sliceElementType(original, patch)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar merged []interface{}\n\tkind := t.Kind()\n\t// If the elements are not maps, merge the slices of scalars.\n\tif kind != reflect.Map {\n\t\tif mergeOptions.MergeParallelList \u0026\u0026 isDeleteList {\n\t\t\treturn deleteFromSlice(original, patch), nil\n\t\t}\n\t\t// Maybe in the future add a \"concat\" mode that doesn't\n\t\t// deduplicate.\n\t\tboth := append(original, patch...)\n\t\tmerged = deduplicateScalars(both)\n\n\t} else {\n\t\tif mergeKey == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"cannot merge lists without merge key for %s\", schema.Name())\n\t\t}\n\n\t\toriginal, patch, err = mergeSliceWithSpecialElements(original, patch, mergeKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tmerged, err = mergeSliceWithoutSpecialElements(original, patch, mergeKey, schema, mergeOptions)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// enforce the order\n\tvar patchItems, serverOnlyItems []interface{}\n\tif len(mergeKey) == 0 {\n\t\tpatchItems, serverOnlyItems = partitionPrimitivesByPresentInList(merged, patch)\n\t} else {\n\t\tpatchItems, serverOnlyItems, err = partitionMapsByPresentInList(merged, patch, mergeKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn normalizeElementOrder(patchItems, serverOnlyItems, patch, original, mergeKey, kind)\n}","line":{"from":1435,"to":1488}} {"id":100016118,"name":"mergeSliceWithSpecialElements","signature":"func mergeSliceWithSpecialElements(original, patch []interface{}, mergeKey string) ([]interface{}, []interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// mergeSliceWithSpecialElements handles special elements with directiveMarker\n// before merging the slices. It returns a updated `original` and a patch without special elements.\n// original and patch must be slices of maps, they should be checked before calling this function.\nfunc mergeSliceWithSpecialElements(original, patch []interface{}, mergeKey string) ([]interface{}, []interface{}, error) {\n\tpatchWithoutSpecialElements := []interface{}{}\n\treplace := false\n\tfor _, v := range patch {\n\t\ttypedV := v.(map[string]interface{})\n\t\tpatchType, ok := typedV[directiveMarker]\n\t\tif !ok {\n\t\t\tpatchWithoutSpecialElements = append(patchWithoutSpecialElements, v)\n\t\t} else {\n\t\t\tswitch patchType {\n\t\t\tcase deleteDirective:\n\t\t\t\tmergeValue, ok := typedV[mergeKey]\n\t\t\t\tif ok {\n\t\t\t\t\tvar err error\n\t\t\t\t\toriginal, err = deleteMatchingEntries(original, mergeKey, mergeValue)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, nil, err\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, nil, mergepatch.ErrNoMergeKey(typedV, mergeKey)\n\t\t\t\t}\n\t\t\tcase replaceDirective:\n\t\t\t\treplace = true\n\t\t\t\t// Continue iterating through the array to prune any other $patch elements.\n\t\t\tcase mergeDirective:\n\t\t\t\treturn nil, nil, fmt.Errorf(\"merging lists cannot yet be specified in the patch\")\n\t\t\tdefault:\n\t\t\t\treturn nil, nil, mergepatch.ErrBadPatchType(patchType, typedV)\n\t\t\t}\n\t\t}\n\t}\n\tif replace {\n\t\treturn patchWithoutSpecialElements, nil, nil\n\t}\n\treturn original, patchWithoutSpecialElements, nil\n}","line":{"from":1490,"to":1528}} {"id":100016119,"name":"deleteMatchingEntries","signature":"func deleteMatchingEntries(original []interface{}, mergeKey string, mergeValue interface{}) ([]interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// delete all matching entries (based on merge key) from a merging list\nfunc deleteMatchingEntries(original []interface{}, mergeKey string, mergeValue interface{}) ([]interface{}, error) {\n\tfor {\n\t\t_, originalKey, found, err := findMapInSliceBasedOnKeyValue(original, mergeKey, mergeValue)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif !found {\n\t\t\tbreak\n\t\t}\n\t\t// Delete the element at originalKey.\n\t\toriginal = append(original[:originalKey], original[originalKey+1:]...)\n\t}\n\treturn original, nil\n}","line":{"from":1530,"to":1545}} {"id":100016120,"name":"mergeSliceWithoutSpecialElements","signature":"func mergeSliceWithoutSpecialElements(original, patch []interface{}, mergeKey string, schema LookupPatchMeta, mergeOptions MergeOptions) ([]interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// mergeSliceWithoutSpecialElements merges slices with non-special elements.\n// original and patch must be slices of maps, they should be checked before calling this function.\nfunc mergeSliceWithoutSpecialElements(original, patch []interface{}, mergeKey string, schema LookupPatchMeta, mergeOptions MergeOptions) ([]interface{}, error) {\n\tfor _, v := range patch {\n\t\ttypedV := v.(map[string]interface{})\n\t\tmergeValue, ok := typedV[mergeKey]\n\t\tif !ok {\n\t\t\treturn nil, mergepatch.ErrNoMergeKey(typedV, mergeKey)\n\t\t}\n\n\t\t// If we find a value with this merge key value in original, merge the\n\t\t// maps. Otherwise append onto original.\n\t\toriginalMap, originalKey, found, err := findMapInSliceBasedOnKeyValue(original, mergeKey, mergeValue)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif found {\n\t\t\tvar mergedMaps interface{}\n\t\t\tvar err error\n\t\t\t// Merge into original.\n\t\t\tmergedMaps, err = mergeMap(originalMap, typedV, schema, mergeOptions)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\toriginal[originalKey] = mergedMaps\n\t\t} else {\n\t\t\toriginal = append(original, v)\n\t\t}\n\t}\n\treturn original, nil\n}","line":{"from":1547,"to":1579}} {"id":100016121,"name":"deleteFromSlice","signature":"func deleteFromSlice(current, toDelete []interface{}) []interface{}","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// deleteFromSlice uses the parallel list to delete the items in a list of scalars\nfunc deleteFromSlice(current, toDelete []interface{}) []interface{} {\n\ttoDeleteMap := map[interface{}]interface{}{}\n\tprocessed := make([]interface{}, 0, len(current))\n\tfor _, v := range toDelete {\n\t\ttoDeleteMap[v] = true\n\t}\n\tfor _, v := range current {\n\t\tif _, found := toDeleteMap[v]; !found {\n\t\t\tprocessed = append(processed, v)\n\t\t}\n\t}\n\treturn processed\n}","line":{"from":1581,"to":1594}} {"id":100016122,"name":"findMapInSliceBasedOnKeyValue","signature":"func findMapInSliceBasedOnKeyValue(m []interface{}, key string, value interface{}) (map[string]interface{}, int, bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// This method no longer panics if any element of the slice is not a map.\nfunc findMapInSliceBasedOnKeyValue(m []interface{}, key string, value interface{}) (map[string]interface{}, int, bool, error) {\n\tfor k, v := range m {\n\t\ttypedV, ok := v.(map[string]interface{})\n\t\tif !ok {\n\t\t\treturn nil, 0, false, fmt.Errorf(\"value for key %v is not a map\", k)\n\t\t}\n\n\t\tvalueToMatch, ok := typedV[key]\n\t\tif ok \u0026\u0026 valueToMatch == value {\n\t\t\treturn typedV, k, true, nil\n\t\t}\n\t}\n\n\treturn nil, 0, false, nil\n}","line":{"from":1596,"to":1611}} {"id":100016123,"name":"sortMergeListsByName","signature":"func sortMergeListsByName(mapJSON []byte, schema LookupPatchMeta) ([]byte, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// This function takes a JSON map and sorts all the lists that should be merged\n// by key. This is needed by tests because in JSON, list order is significant,\n// but in Strategic Merge Patch, merge lists do not have significant order.\n// Sorting the lists allows for order-insensitive comparison of patched maps.\nfunc sortMergeListsByName(mapJSON []byte, schema LookupPatchMeta) ([]byte, error) {\n\tvar m map[string]interface{}\n\terr := json.Unmarshal(mapJSON, \u0026m)\n\tif err != nil {\n\t\treturn nil, mergepatch.ErrBadJSONDoc\n\t}\n\n\tnewM, err := sortMergeListsByNameMap(m, schema)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn json.Marshal(newM)\n}","line":{"from":1613,"to":1630}} {"id":100016124,"name":"sortMergeListsByNameMap","signature":"func sortMergeListsByNameMap(s map[string]interface{}, schema LookupPatchMeta) (map[string]interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// Function sortMergeListsByNameMap recursively sorts the merge lists by its mergeKey in a map.\nfunc sortMergeListsByNameMap(s map[string]interface{}, schema LookupPatchMeta) (map[string]interface{}, error) {\n\tnewS := map[string]interface{}{}\n\tfor k, v := range s {\n\t\tif k == retainKeysDirective {\n\t\t\ttypedV, ok := v.([]interface{})\n\t\t\tif !ok {\n\t\t\t\treturn nil, mergepatch.ErrBadPatchFormatForRetainKeys\n\t\t\t}\n\t\t\tv = sortScalars(typedV)\n\t\t} else if strings.HasPrefix(k, deleteFromPrimitiveListDirectivePrefix) {\n\t\t\ttypedV, ok := v.([]interface{})\n\t\t\tif !ok {\n\t\t\t\treturn nil, mergepatch.ErrBadPatchFormatForPrimitiveList\n\t\t\t}\n\t\t\tv = sortScalars(typedV)\n\t\t} else if strings.HasPrefix(k, setElementOrderDirectivePrefix) {\n\t\t\t_, ok := v.([]interface{})\n\t\t\tif !ok {\n\t\t\t\treturn nil, mergepatch.ErrBadPatchFormatForSetElementOrderList\n\t\t\t}\n\t\t} else if k != directiveMarker {\n\t\t\t// recurse for map and slice.\n\t\t\tswitch typedV := v.(type) {\n\t\t\tcase map[string]interface{}:\n\t\t\t\tsubschema, _, err := schema.LookupPatchMetadataForStruct(k)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tv, err = sortMergeListsByNameMap(typedV, subschema)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\tcase []interface{}:\n\t\t\t\tsubschema, patchMeta, err := schema.LookupPatchMetadataForSlice(k)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\t_, patchStrategy, err := extractRetainKeysPatchStrategy(patchMeta.GetPatchStrategies())\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif patchStrategy == mergeDirective {\n\t\t\t\t\tvar err error\n\t\t\t\t\tv, err = sortMergeListsByNameArray(typedV, subschema, patchMeta.GetPatchMergeKey(), true)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tnewS[k] = v\n\t}\n\n\treturn newS, nil\n}","line":{"from":1632,"to":1688}} {"id":100016125,"name":"sortMergeListsByNameArray","signature":"func sortMergeListsByNameArray(s []interface{}, schema LookupPatchMeta, mergeKey string, recurse bool) ([]interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// Function sortMergeListsByNameMap recursively sorts the merge lists by its mergeKey in an array.\nfunc sortMergeListsByNameArray(s []interface{}, schema LookupPatchMeta, mergeKey string, recurse bool) ([]interface{}, error) {\n\tif len(s) == 0 {\n\t\treturn s, nil\n\t}\n\n\t// We don't support lists of lists yet.\n\tt, err := sliceElementType(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// If the elements are not maps...\n\tif t.Kind() != reflect.Map {\n\t\t// Sort the elements, because they may have been merged out of order.\n\t\treturn deduplicateAndSortScalars(s), nil\n\t}\n\n\t// Elements are maps - if one of the keys of the map is a map or a\n\t// list, we may need to recurse into it.\n\tnewS := []interface{}{}\n\tfor _, elem := range s {\n\t\tif recurse {\n\t\t\ttypedElem := elem.(map[string]interface{})\n\t\t\tnewElem, err := sortMergeListsByNameMap(typedElem, schema)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tnewS = append(newS, newElem)\n\t\t} else {\n\t\t\tnewS = append(newS, elem)\n\t\t}\n\t}\n\n\t// Sort the maps.\n\tnewS = sortMapsBasedOnField(newS, mergeKey)\n\treturn newS, nil\n}","line":{"from":1690,"to":1728}} {"id":100016126,"name":"sortMapsBasedOnField","signature":"func sortMapsBasedOnField(m []interface{}, fieldName string) []interface{}","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func sortMapsBasedOnField(m []interface{}, fieldName string) []interface{} {\n\tmapM := mapSliceFromSlice(m)\n\tss := SortableSliceOfMaps{mapM, fieldName}\n\tsort.Sort(ss)\n\tnewS := sliceFromMapSlice(ss.s)\n\treturn newS\n}","line":{"from":1730,"to":1736}} {"id":100016127,"name":"mapSliceFromSlice","signature":"func mapSliceFromSlice(m []interface{}) []map[string]interface{}","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func mapSliceFromSlice(m []interface{}) []map[string]interface{} {\n\tnewM := []map[string]interface{}{}\n\tfor _, v := range m {\n\t\tvt := v.(map[string]interface{})\n\t\tnewM = append(newM, vt)\n\t}\n\n\treturn newM\n}","line":{"from":1738,"to":1746}} {"id":100016128,"name":"sliceFromMapSlice","signature":"func sliceFromMapSlice(s []map[string]interface{}) []interface{}","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func sliceFromMapSlice(s []map[string]interface{}) []interface{} {\n\tnewS := []interface{}{}\n\tfor _, v := range s {\n\t\tnewS = append(newS, v)\n\t}\n\n\treturn newS\n}","line":{"from":1748,"to":1755}} {"id":100016129,"name":"Len","signature":"func (ss SortableSliceOfMaps) Len() int","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func (ss SortableSliceOfMaps) Len() int {\n\treturn len(ss.s)\n}","line":{"from":1762,"to":1764}} {"id":100016130,"name":"Less","signature":"func (ss SortableSliceOfMaps) Less(i, j int) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func (ss SortableSliceOfMaps) Less(i, j int) bool {\n\tiStr := fmt.Sprintf(\"%v\", ss.s[i][ss.k])\n\tjStr := fmt.Sprintf(\"%v\", ss.s[j][ss.k])\n\treturn sort.StringsAreSorted([]string{iStr, jStr})\n}","line":{"from":1766,"to":1770}} {"id":100016131,"name":"Swap","signature":"func (ss SortableSliceOfMaps) Swap(i, j int)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func (ss SortableSliceOfMaps) Swap(i, j int) {\n\ttmp := ss.s[i]\n\tss.s[i] = ss.s[j]\n\tss.s[j] = tmp\n}","line":{"from":1772,"to":1776}} {"id":100016132,"name":"deduplicateAndSortScalars","signature":"func deduplicateAndSortScalars(s []interface{}) []interface{}","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func deduplicateAndSortScalars(s []interface{}) []interface{} {\n\ts = deduplicateScalars(s)\n\treturn sortScalars(s)\n}","line":{"from":1778,"to":1781}} {"id":100016133,"name":"sortScalars","signature":"func sortScalars(s []interface{}) []interface{}","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func sortScalars(s []interface{}) []interface{} {\n\tss := SortableSliceOfScalars{s}\n\tsort.Sort(ss)\n\treturn ss.s\n}","line":{"from":1783,"to":1787}} {"id":100016134,"name":"deduplicateScalars","signature":"func deduplicateScalars(s []interface{}) []interface{}","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func deduplicateScalars(s []interface{}) []interface{} {\n\t// Clever algorithm to deduplicate.\n\tlength := len(s) - 1\n\tfor i := 0; i \u003c length; i++ {\n\t\tfor j := i + 1; j \u003c= length; j++ {\n\t\t\tif s[i] == s[j] {\n\t\t\t\ts[j] = s[length]\n\t\t\t\ts = s[0:length]\n\t\t\t\tlength--\n\t\t\t\tj--\n\t\t\t}\n\t\t}\n\t}\n\n\treturn s\n}","line":{"from":1789,"to":1804}} {"id":100016135,"name":"Len","signature":"func (ss SortableSliceOfScalars) Len() int","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func (ss SortableSliceOfScalars) Len() int {\n\treturn len(ss.s)\n}","line":{"from":1810,"to":1812}} {"id":100016136,"name":"Less","signature":"func (ss SortableSliceOfScalars) Less(i, j int) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func (ss SortableSliceOfScalars) Less(i, j int) bool {\n\tiStr := fmt.Sprintf(\"%v\", ss.s[i])\n\tjStr := fmt.Sprintf(\"%v\", ss.s[j])\n\treturn sort.StringsAreSorted([]string{iStr, jStr})\n}","line":{"from":1814,"to":1818}} {"id":100016137,"name":"Swap","signature":"func (ss SortableSliceOfScalars) Swap(i, j int)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func (ss SortableSliceOfScalars) Swap(i, j int) {\n\ttmp := ss.s[i]\n\tss.s[i] = ss.s[j]\n\tss.s[j] = tmp\n}","line":{"from":1820,"to":1824}} {"id":100016138,"name":"sliceElementType","signature":"func sliceElementType(slices ...[]interface{}) (reflect.Type, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// Returns the type of the elements of N slice(s). If the type is different,\n// another slice or undefined, returns an error.\nfunc sliceElementType(slices ...[]interface{}) (reflect.Type, error) {\n\tvar prevType reflect.Type\n\tfor _, s := range slices {\n\t\t// Go through elements of all given slices and make sure they are all the same type.\n\t\tfor _, v := range s {\n\t\t\tcurrentType := reflect.TypeOf(v)\n\t\t\tif prevType == nil {\n\t\t\t\tprevType = currentType\n\t\t\t\t// We don't support lists of lists yet.\n\t\t\t\tif prevType.Kind() == reflect.Slice {\n\t\t\t\t\treturn nil, mergepatch.ErrNoListOfLists\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif prevType != currentType {\n\t\t\t\t\treturn nil, fmt.Errorf(\"list element types are not identical: %v\", fmt.Sprint(slices))\n\t\t\t\t}\n\t\t\t\tprevType = currentType\n\t\t\t}\n\t\t}\n\t}\n\n\tif prevType == nil {\n\t\treturn nil, fmt.Errorf(\"no elements in any of the given slices\")\n\t}\n\n\treturn prevType, nil\n}","line":{"from":1826,"to":1854}} {"id":100016139,"name":"MergingMapsHaveConflicts","signature":"func MergingMapsHaveConflicts(left, right map[string]interface{}, schema LookupPatchMeta) (bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// MergingMapsHaveConflicts returns true if the left and right JSON interface\n// objects overlap with different values in any key. All keys are required to be\n// strings. Since patches of the same Type have congruent keys, this is valid\n// for multiple patch types. This method supports strategic merge patch semantics.\nfunc MergingMapsHaveConflicts(left, right map[string]interface{}, schema LookupPatchMeta) (bool, error) {\n\treturn mergingMapFieldsHaveConflicts(left, right, schema, \"\", \"\")\n}","line":{"from":1856,"to":1862}} {"id":100016140,"name":"mergingMapFieldsHaveConflicts","signature":"func mergingMapFieldsHaveConflicts(","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func mergingMapFieldsHaveConflicts(\n\tleft, right interface{},\n\tschema LookupPatchMeta,\n\tfieldPatchStrategy, fieldPatchMergeKey string,\n) (bool, error) {\n\tswitch leftType := left.(type) {\n\tcase map[string]interface{}:\n\t\trightType, ok := right.(map[string]interface{})\n\t\tif !ok {\n\t\t\treturn true, nil\n\t\t}\n\t\tleftMarker, okLeft := leftType[directiveMarker]\n\t\trightMarker, okRight := rightType[directiveMarker]\n\t\t// if one or the other has a directive marker,\n\t\t// then we need to consider that before looking at the individual keys,\n\t\t// since a directive operates on the whole map.\n\t\tif okLeft || okRight {\n\t\t\t// if one has a directive marker and the other doesn't,\n\t\t\t// then we have a conflict, since one is deleting or replacing the whole map,\n\t\t\t// and the other is doing things to individual keys.\n\t\t\tif okLeft != okRight {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\t// if they both have markers, but they are not the same directive,\n\t\t\t// then we have a conflict because they're doing different things to the map.\n\t\t\tif leftMarker != rightMarker {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\t\tif fieldPatchStrategy == replaceDirective {\n\t\t\treturn false, nil\n\t\t}\n\t\t// Check the individual keys.\n\t\treturn mapsHaveConflicts(leftType, rightType, schema)\n\n\tcase []interface{}:\n\t\trightType, ok := right.([]interface{})\n\t\tif !ok {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn slicesHaveConflicts(leftType, rightType, schema, fieldPatchStrategy, fieldPatchMergeKey)\n\tcase string, float64, bool, int64, nil:\n\t\treturn !reflect.DeepEqual(left, right), nil\n\tdefault:\n\t\treturn true, fmt.Errorf(\"unknown type: %v\", reflect.TypeOf(left))\n\t}\n}","line":{"from":1864,"to":1910}} {"id":100016141,"name":"mapsHaveConflicts","signature":"func mapsHaveConflicts(typedLeft, typedRight map[string]interface{}, schema LookupPatchMeta) (bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func mapsHaveConflicts(typedLeft, typedRight map[string]interface{}, schema LookupPatchMeta) (bool, error) {\n\tfor key, leftValue := range typedLeft {\n\t\tif key != directiveMarker \u0026\u0026 key != retainKeysDirective {\n\t\t\tif rightValue, ok := typedRight[key]; ok {\n\t\t\t\tvar subschema LookupPatchMeta\n\t\t\t\tvar patchMeta PatchMeta\n\t\t\t\tvar patchStrategy string\n\t\t\t\tvar err error\n\t\t\t\tswitch leftValue.(type) {\n\t\t\t\tcase []interface{}:\n\t\t\t\t\tsubschema, patchMeta, err = schema.LookupPatchMetadataForSlice(key)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn true, err\n\t\t\t\t\t}\n\t\t\t\t\t_, patchStrategy, err = extractRetainKeysPatchStrategy(patchMeta.patchStrategies)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn true, err\n\t\t\t\t\t}\n\t\t\t\tcase map[string]interface{}:\n\t\t\t\t\tsubschema, patchMeta, err = schema.LookupPatchMetadataForStruct(key)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn true, err\n\t\t\t\t\t}\n\t\t\t\t\t_, patchStrategy, err = extractRetainKeysPatchStrategy(patchMeta.patchStrategies)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn true, err\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif hasConflicts, err := mergingMapFieldsHaveConflicts(leftValue, rightValue,\n\t\t\t\t\tsubschema, patchStrategy, patchMeta.GetPatchMergeKey()); hasConflicts {\n\t\t\t\t\treturn true, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false, nil\n}","line":{"from":1912,"to":1950}} {"id":100016142,"name":"slicesHaveConflicts","signature":"func slicesHaveConflicts(","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func slicesHaveConflicts(\n\ttypedLeft, typedRight []interface{},\n\tschema LookupPatchMeta,\n\tfieldPatchStrategy, fieldPatchMergeKey string,\n) (bool, error) {\n\telementType, err := sliceElementType(typedLeft, typedRight)\n\tif err != nil {\n\t\treturn true, err\n\t}\n\n\tif fieldPatchStrategy == mergeDirective {\n\t\t// Merging lists of scalars have no conflicts by definition\n\t\t// So we only need to check further if the elements are maps\n\t\tif elementType.Kind() != reflect.Map {\n\t\t\treturn false, nil\n\t\t}\n\n\t\t// Build a map for each slice and then compare the two maps\n\t\tleftMap, err := sliceOfMapsToMapOfMaps(typedLeft, fieldPatchMergeKey)\n\t\tif err != nil {\n\t\t\treturn true, err\n\t\t}\n\n\t\trightMap, err := sliceOfMapsToMapOfMaps(typedRight, fieldPatchMergeKey)\n\t\tif err != nil {\n\t\t\treturn true, err\n\t\t}\n\n\t\treturn mapsOfMapsHaveConflicts(leftMap, rightMap, schema)\n\t}\n\n\t// Either we don't have type information, or these are non-merging lists\n\tif len(typedLeft) != len(typedRight) {\n\t\treturn true, nil\n\t}\n\n\t// Sort scalar slices to prevent ordering issues\n\t// We have no way to sort non-merging lists of maps\n\tif elementType.Kind() != reflect.Map {\n\t\ttypedLeft = deduplicateAndSortScalars(typedLeft)\n\t\ttypedRight = deduplicateAndSortScalars(typedRight)\n\t}\n\n\t// Compare the slices element by element in order\n\t// This test will fail if the slices are not sorted\n\tfor i := range typedLeft {\n\t\tif hasConflicts, err := mergingMapFieldsHaveConflicts(typedLeft[i], typedRight[i], schema, \"\", \"\"); hasConflicts {\n\t\t\treturn true, err\n\t\t}\n\t}\n\n\treturn false, nil\n}","line":{"from":1952,"to":2004}} {"id":100016143,"name":"sliceOfMapsToMapOfMaps","signature":"func sliceOfMapsToMapOfMaps(slice []interface{}, mergeKey string) (map[string]interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func sliceOfMapsToMapOfMaps(slice []interface{}, mergeKey string) (map[string]interface{}, error) {\n\tresult := make(map[string]interface{}, len(slice))\n\tfor _, value := range slice {\n\t\ttypedValue, ok := value.(map[string]interface{})\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"invalid element type in merging list:%v\", slice)\n\t\t}\n\n\t\tmergeValue, ok := typedValue[mergeKey]\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"cannot find merge key `%s` in merging list element:%v\", mergeKey, typedValue)\n\t\t}\n\n\t\tresult[fmt.Sprintf(\"%s\", mergeValue)] = typedValue\n\t}\n\n\treturn result, nil\n}","line":{"from":2006,"to":2023}} {"id":100016144,"name":"mapsOfMapsHaveConflicts","signature":"func mapsOfMapsHaveConflicts(typedLeft, typedRight map[string]interface{}, schema LookupPatchMeta) (bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func mapsOfMapsHaveConflicts(typedLeft, typedRight map[string]interface{}, schema LookupPatchMeta) (bool, error) {\n\tfor key, leftValue := range typedLeft {\n\t\tif rightValue, ok := typedRight[key]; ok {\n\t\t\tif hasConflicts, err := mergingMapFieldsHaveConflicts(leftValue, rightValue, schema, \"\", \"\"); hasConflicts {\n\t\t\t\treturn true, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false, nil\n}","line":{"from":2025,"to":2035}} {"id":100016145,"name":"CreateThreeWayMergePatch","signature":"func CreateThreeWayMergePatch(original, modified, current []byte, schema LookupPatchMeta, overwrite bool, fns ...mergepatch.PreconditionFunc) ([]byte, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// CreateThreeWayMergePatch reconciles a modified configuration with an original configuration,\n// while preserving any changes or deletions made to the original configuration in the interim,\n// and not overridden by the current configuration. All three documents must be passed to the\n// method as json encoded content. It will return a strategic merge patch, or an error if any\n// of the documents is invalid, or if there are any preconditions that fail against the modified\n// configuration, or, if overwrite is false and there are conflicts between the modified and current\n// configurations. Conflicts are defined as keys changed differently from original to modified\n// than from original to current. In other words, a conflict occurs if modified changes any key\n// in a way that is different from how it is changed in current (e.g., deleting it, changing its\n// value). We also propagate values fields that do not exist in original but are explicitly\n// defined in modified.\nfunc CreateThreeWayMergePatch(original, modified, current []byte, schema LookupPatchMeta, overwrite bool, fns ...mergepatch.PreconditionFunc) ([]byte, error) {\n\toriginalMap := map[string]interface{}{}\n\tif len(original) \u003e 0 {\n\t\tif err := json.Unmarshal(original, \u0026originalMap); err != nil {\n\t\t\treturn nil, mergepatch.ErrBadJSONDoc\n\t\t}\n\t}\n\n\tmodifiedMap := map[string]interface{}{}\n\tif len(modified) \u003e 0 {\n\t\tif err := json.Unmarshal(modified, \u0026modifiedMap); err != nil {\n\t\t\treturn nil, mergepatch.ErrBadJSONDoc\n\t\t}\n\t}\n\n\tcurrentMap := map[string]interface{}{}\n\tif len(current) \u003e 0 {\n\t\tif err := json.Unmarshal(current, \u0026currentMap); err != nil {\n\t\t\treturn nil, mergepatch.ErrBadJSONDoc\n\t\t}\n\t}\n\n\t// The patch is the difference from current to modified without deletions, plus deletions\n\t// from original to modified. To find it, we compute deletions, which are the deletions from\n\t// original to modified, and delta, which is the difference from current to modified without\n\t// deletions, and then apply delta to deletions as a patch, which should be strictly additive.\n\tdeltaMapDiffOptions := DiffOptions{\n\t\tIgnoreDeletions: true,\n\t\tSetElementOrder: true,\n\t}\n\tdeltaMap, err := diffMaps(currentMap, modifiedMap, schema, deltaMapDiffOptions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdeletionsMapDiffOptions := DiffOptions{\n\t\tSetElementOrder: true,\n\t\tIgnoreChangesAndAdditions: true,\n\t}\n\tdeletionsMap, err := diffMaps(originalMap, modifiedMap, schema, deletionsMapDiffOptions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmergeOptions := MergeOptions{}\n\tpatchMap, err := mergeMap(deletionsMap, deltaMap, schema, mergeOptions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Apply the preconditions to the patch, and return an error if any of them fail.\n\tfor _, fn := range fns {\n\t\tif !fn(patchMap) {\n\t\t\treturn nil, mergepatch.NewErrPreconditionFailed(patchMap)\n\t\t}\n\t}\n\n\t// If overwrite is false, and the patch contains any keys that were changed differently,\n\t// then return a conflict error.\n\tif !overwrite {\n\t\tchangeMapDiffOptions := DiffOptions{}\n\t\tchangedMap, err := diffMaps(originalMap, currentMap, schema, changeMapDiffOptions)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\thasConflicts, err := MergingMapsHaveConflicts(patchMap, changedMap, schema)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif hasConflicts {\n\t\t\treturn nil, mergepatch.NewErrConflict(mergepatch.ToYAMLOrError(patchMap), mergepatch.ToYAMLOrError(changedMap))\n\t\t}\n\t}\n\n\treturn json.Marshal(patchMap)\n}","line":{"from":2037,"to":2124}} {"id":100016146,"name":"ItemAddedToModifiedSlice","signature":"func ItemAddedToModifiedSlice(original, modified string) bool { return original \u003e modified }","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func ItemAddedToModifiedSlice(original, modified string) bool { return original \u003e modified }","line":{"from":2126,"to":2126}} {"id":100016147,"name":"ItemRemovedFromModifiedSlice","signature":"func ItemRemovedFromModifiedSlice(original, modified string) bool { return original \u003c modified }","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func ItemRemovedFromModifiedSlice(original, modified string) bool { return original \u003c modified }","line":{"from":2128,"to":2128}} {"id":100016148,"name":"ItemMatchesOriginalAndModifiedSlice","signature":"func ItemMatchesOriginalAndModifiedSlice(original, modified string) bool { return original == modified }","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func ItemMatchesOriginalAndModifiedSlice(original, modified string) bool { return original == modified }","line":{"from":2130,"to":2130}} {"id":100016149,"name":"CreateDeleteDirective","signature":"func CreateDeleteDirective(mergeKey string, mergeKeyValue interface{}) map[string]interface{}","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func CreateDeleteDirective(mergeKey string, mergeKeyValue interface{}) map[string]interface{} {\n\treturn map[string]interface{}{mergeKey: mergeKeyValue, directiveMarker: deleteDirective}\n}","line":{"from":2132,"to":2134}} {"id":100016150,"name":"mapTypeAssertion","signature":"func mapTypeAssertion(original, patch interface{}) (map[string]interface{}, map[string]interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func mapTypeAssertion(original, patch interface{}) (map[string]interface{}, map[string]interface{}, error) {\n\ttypedOriginal, ok := original.(map[string]interface{})\n\tif !ok {\n\t\treturn nil, nil, mergepatch.ErrBadArgType(typedOriginal, original)\n\t}\n\ttypedPatch, ok := patch.(map[string]interface{})\n\tif !ok {\n\t\treturn nil, nil, mergepatch.ErrBadArgType(typedPatch, patch)\n\t}\n\treturn typedOriginal, typedPatch, nil\n}","line":{"from":2136,"to":2146}} {"id":100016151,"name":"sliceTypeAssertion","signature":"func sliceTypeAssertion(original, patch interface{}) ([]interface{}, []interface{}, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"func sliceTypeAssertion(original, patch interface{}) ([]interface{}, []interface{}, error) {\n\ttypedOriginal, ok := original.([]interface{})\n\tif !ok {\n\t\treturn nil, nil, mergepatch.ErrBadArgType(typedOriginal, original)\n\t}\n\ttypedPatch, ok := patch.([]interface{})\n\tif !ok {\n\t\treturn nil, nil, mergepatch.ErrBadArgType(typedPatch, patch)\n\t}\n\treturn typedOriginal, typedPatch, nil\n}","line":{"from":2148,"to":2158}} {"id":100016152,"name":"extractRetainKeysPatchStrategy","signature":"func extractRetainKeysPatchStrategy(strategies []string) (bool, string, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// extractRetainKeysPatchStrategy process patch strategy, which is a string may contains multiple\n// patch strategies separated by \",\". It returns a boolean var indicating if it has\n// retainKeys strategies and a string for the other strategy.\nfunc extractRetainKeysPatchStrategy(strategies []string) (bool, string, error) {\n\tswitch len(strategies) {\n\tcase 0:\n\t\treturn false, \"\", nil\n\tcase 1:\n\t\tsingleStrategy := strategies[0]\n\t\tswitch singleStrategy {\n\t\tcase retainKeysStrategy:\n\t\t\treturn true, \"\", nil\n\t\tdefault:\n\t\t\treturn false, singleStrategy, nil\n\t\t}\n\tcase 2:\n\t\tswitch {\n\t\tcase strategies[0] == retainKeysStrategy:\n\t\t\treturn true, strategies[1], nil\n\t\tcase strategies[1] == retainKeysStrategy:\n\t\t\treturn true, strategies[0], nil\n\t\tdefault:\n\t\t\treturn false, \"\", fmt.Errorf(\"unexpected patch strategy: %v\", strategies)\n\t\t}\n\tdefault:\n\t\treturn false, \"\", fmt.Errorf(\"unexpected patch strategy: %v\", strategies)\n\t}\n}","line":{"from":2160,"to":2187}} {"id":100016153,"name":"hasAdditionalNewField","signature":"func hasAdditionalNewField(original, modified map[string]interface{}) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go","code":"// hasAdditionalNewField returns if original map has additional key with non-nil value than modified.\nfunc hasAdditionalNewField(original, modified map[string]interface{}) bool {\n\tfor k, v := range original {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif _, found := modified[k]; !found {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":2189,"to":2200}} {"id":100016154,"name":"NewKindItem","signature":"func NewKindItem(key string, path *openapi.Path) *kindItem","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/types.go","code":"func NewKindItem(key string, path *openapi.Path) *kindItem {\n\treturn \u0026kindItem{\n\t\tkey: key,\n\t\tpath: path,\n\t}\n}","line":{"from":48,"to":53}} {"id":100016155,"name":"Error","signature":"func (item *kindItem) Error() error","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/types.go","code":"func (item *kindItem) Error() error {\n\treturn item.err\n}","line":{"from":57,"to":59}} {"id":100016156,"name":"Path","signature":"func (item *kindItem) Path() *openapi.Path","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/types.go","code":"func (item *kindItem) Path() *openapi.Path {\n\treturn item.path\n}","line":{"from":61,"to":63}} {"id":100016157,"name":"VisitPrimitive","signature":"func (item *kindItem) VisitPrimitive(schema *openapi.Primitive)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/types.go","code":"func (item *kindItem) VisitPrimitive(schema *openapi.Primitive) {\n\titem.err = errors.New(\"expected kind, but got primitive\")\n}","line":{"from":65,"to":67}} {"id":100016158,"name":"VisitArray","signature":"func (item *kindItem) VisitArray(schema *openapi.Array)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/types.go","code":"func (item *kindItem) VisitArray(schema *openapi.Array) {\n\titem.err = errors.New(\"expected kind, but got slice\")\n}","line":{"from":69,"to":71}} {"id":100016159,"name":"VisitMap","signature":"func (item *kindItem) VisitMap(schema *openapi.Map)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/types.go","code":"func (item *kindItem) VisitMap(schema *openapi.Map) {\n\titem.err = errors.New(\"expected kind, but got map\")\n}","line":{"from":73,"to":75}} {"id":100016160,"name":"VisitReference","signature":"func (item *kindItem) VisitReference(schema openapi.Reference)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/types.go","code":"func (item *kindItem) VisitReference(schema openapi.Reference) {\n\tif !item.hasVisitKind {\n\t\tschema.SubSchema().Accept(item)\n\t}\n}","line":{"from":77,"to":81}} {"id":100016161,"name":"VisitKind","signature":"func (item *kindItem) VisitKind(schema *openapi.Kind)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/types.go","code":"func (item *kindItem) VisitKind(schema *openapi.Kind) {\n\tsubschema, ok := schema.Fields[item.key]\n\tif !ok {\n\t\titem.err = FieldNotFoundError{Path: schema.GetPath().String(), Field: item.key}\n\t\treturn\n\t}\n\n\tmergeKey, patchStrategies, err := parsePatchMetadata(subschema.GetExtensions())\n\tif err != nil {\n\t\titem.err = err\n\t\treturn\n\t}\n\titem.patchmeta = PatchMeta{\n\t\tpatchStrategies: patchStrategies,\n\t\tpatchMergeKey: mergeKey,\n\t}\n\titem.subschema = subschema\n}","line":{"from":83,"to":100}} {"id":100016162,"name":"NewSliceItem","signature":"func NewSliceItem(key string, path *openapi.Path) *sliceItem","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/types.go","code":"func NewSliceItem(key string, path *openapi.Path) *sliceItem {\n\treturn \u0026sliceItem{\n\t\tkey: key,\n\t\tpath: path,\n\t}\n}","line":{"from":111,"to":116}} {"id":100016163,"name":"Error","signature":"func (item *sliceItem) Error() error","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/types.go","code":"func (item *sliceItem) Error() error {\n\treturn item.err\n}","line":{"from":120,"to":122}} {"id":100016164,"name":"Path","signature":"func (item *sliceItem) Path() *openapi.Path","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/types.go","code":"func (item *sliceItem) Path() *openapi.Path {\n\treturn item.path\n}","line":{"from":124,"to":126}} {"id":100016165,"name":"VisitPrimitive","signature":"func (item *sliceItem) VisitPrimitive(schema *openapi.Primitive)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/types.go","code":"func (item *sliceItem) VisitPrimitive(schema *openapi.Primitive) {\n\titem.err = errors.New(\"expected slice, but got primitive\")\n}","line":{"from":128,"to":130}} {"id":100016166,"name":"VisitArray","signature":"func (item *sliceItem) VisitArray(schema *openapi.Array)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/types.go","code":"func (item *sliceItem) VisitArray(schema *openapi.Array) {\n\tif !item.hasVisitKind {\n\t\titem.err = errors.New(\"expected visit kind first, then visit array\")\n\t}\n\tsubschema := schema.SubType\n\titem.subschema = subschema\n}","line":{"from":132,"to":138}} {"id":100016167,"name":"VisitMap","signature":"func (item *sliceItem) VisitMap(schema *openapi.Map)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/types.go","code":"func (item *sliceItem) VisitMap(schema *openapi.Map) {\n\titem.err = errors.New(\"expected slice, but got map\")\n}","line":{"from":140,"to":142}} {"id":100016168,"name":"VisitReference","signature":"func (item *sliceItem) VisitReference(schema openapi.Reference)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/types.go","code":"func (item *sliceItem) VisitReference(schema openapi.Reference) {\n\tif !item.hasVisitKind {\n\t\tschema.SubSchema().Accept(item)\n\t} else {\n\t\titem.subschema = schema.SubSchema()\n\t}\n}","line":{"from":144,"to":150}} {"id":100016169,"name":"VisitKind","signature":"func (item *sliceItem) VisitKind(schema *openapi.Kind)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/types.go","code":"func (item *sliceItem) VisitKind(schema *openapi.Kind) {\n\tsubschema, ok := schema.Fields[item.key]\n\tif !ok {\n\t\titem.err = FieldNotFoundError{Path: schema.GetPath().String(), Field: item.key}\n\t\treturn\n\t}\n\n\tmergeKey, patchStrategies, err := parsePatchMetadata(subschema.GetExtensions())\n\tif err != nil {\n\t\titem.err = err\n\t\treturn\n\t}\n\titem.patchmeta = PatchMeta{\n\t\tpatchStrategies: patchStrategies,\n\t\tpatchMergeKey: mergeKey,\n\t}\n\titem.hasVisitKind = true\n\tsubschema.Accept(item)\n}","line":{"from":152,"to":170}} {"id":100016170,"name":"parsePatchMetadata","signature":"func parsePatchMetadata(extensions map[string]interface{}) (string, []string, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/types.go","code":"func parsePatchMetadata(extensions map[string]interface{}) (string, []string, error) {\n\tps, foundPS := extensions[patchStrategyOpenapiextensionKey]\n\tvar patchStrategies []string\n\tvar mergeKey, patchStrategy string\n\tvar ok bool\n\tif foundPS {\n\t\tpatchStrategy, ok = ps.(string)\n\t\tif ok {\n\t\t\tpatchStrategies = strings.Split(patchStrategy, \",\")\n\t\t} else {\n\t\t\treturn \"\", nil, mergepatch.ErrBadArgType(patchStrategy, ps)\n\t\t}\n\t}\n\tmk, foundMK := extensions[patchMergeKeyOpenapiextensionKey]\n\tif foundMK {\n\t\tmergeKey, ok = mk.(string)\n\t\tif !ok {\n\t\t\treturn \"\", nil, mergepatch.ErrBadArgType(mergeKey, mk)\n\t\t}\n\t}\n\treturn mergeKey, patchStrategies, nil\n}","line":{"from":172,"to":193}} {"id":100016171,"name":"NewUUID","signature":"func NewUUID() types.UID","file":"staging/src/k8s.io/apimachinery/pkg/util/uuid/uuid.go","code":"func NewUUID() types.UID {\n\treturn types.UID(uuid.New().String())\n}","line":{"from":25,"to":27}} {"id":100016172,"name":"Error","signature":"func (v *Error) Error() string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/field/errors.go","code":"// Error implements the error interface.\nfunc (v *Error) Error() string {\n\treturn fmt.Sprintf(\"%s: %s\", v.Field, v.ErrorBody())\n}","line":{"from":40,"to":43}} {"id":100016173,"name":"ErrorBody","signature":"func (v *Error) ErrorBody() string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/field/errors.go","code":"// ErrorBody returns the error message without the field name. This is useful\n// for building nice-looking higher-level error reporting.\nfunc (v *Error) ErrorBody() string {\n\tvar s string\n\tswitch {\n\tcase v.Type == ErrorTypeRequired:\n\t\ts = v.Type.String()\n\tcase v.Type == ErrorTypeForbidden:\n\t\ts = v.Type.String()\n\tcase v.Type == ErrorTypeTooLong:\n\t\ts = v.Type.String()\n\tcase v.Type == ErrorTypeInternal:\n\t\ts = v.Type.String()\n\tcase v.BadValue == omitValue:\n\t\ts = v.Type.String()\n\tdefault:\n\t\tvalue := v.BadValue\n\t\tvalueType := reflect.TypeOf(value)\n\t\tif value == nil || valueType == nil {\n\t\t\tvalue = \"null\"\n\t\t} else if valueType.Kind() == reflect.Pointer {\n\t\t\tif reflectValue := reflect.ValueOf(value); reflectValue.IsNil() {\n\t\t\t\tvalue = \"null\"\n\t\t\t} else {\n\t\t\t\tvalue = reflectValue.Elem().Interface()\n\t\t\t}\n\t\t}\n\t\tswitch t := value.(type) {\n\t\tcase int64, int32, float64, float32, bool:\n\t\t\t// use simple printer for simple types\n\t\t\ts = fmt.Sprintf(\"%s: %v\", v.Type, value)\n\t\tcase string:\n\t\t\ts = fmt.Sprintf(\"%s: %q\", v.Type, t)\n\t\tcase fmt.Stringer:\n\t\t\t// anything that defines String() is better than raw struct\n\t\t\ts = fmt.Sprintf(\"%s: %s\", v.Type, t.String())\n\t\tdefault:\n\t\t\t// fallback to raw struct\n\t\t\t// TODO: internal types have panic guards against json.Marshalling to prevent\n\t\t\t// accidental use of internal types in external serialized form. For now, use\n\t\t\t// %#v, although it would be better to show a more expressive output in the future\n\t\t\ts = fmt.Sprintf(\"%s: %#v\", v.Type, value)\n\t\t}\n\t}\n\tif len(v.Detail) != 0 {\n\t\ts += fmt.Sprintf(\": %s\", v.Detail)\n\t}\n\treturn s\n}","line":{"from":49,"to":97}} {"id":100016174,"name":"String","signature":"func (t ErrorType) String() string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/field/errors.go","code":"// String converts a ErrorType into its corresponding canonical error message.\nfunc (t ErrorType) String() string {\n\tswitch t {\n\tcase ErrorTypeNotFound:\n\t\treturn \"Not found\"\n\tcase ErrorTypeRequired:\n\t\treturn \"Required value\"\n\tcase ErrorTypeDuplicate:\n\t\treturn \"Duplicate value\"\n\tcase ErrorTypeInvalid:\n\t\treturn \"Invalid value\"\n\tcase ErrorTypeNotSupported:\n\t\treturn \"Unsupported value\"\n\tcase ErrorTypeForbidden:\n\t\treturn \"Forbidden\"\n\tcase ErrorTypeTooLong:\n\t\treturn \"Too long\"\n\tcase ErrorTypeTooMany:\n\t\treturn \"Too many\"\n\tcase ErrorTypeInternal:\n\t\treturn \"Internal error\"\n\tcase ErrorTypeTypeInvalid:\n\t\treturn \"Invalid value\"\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unrecognized validation error: %q\", string(t)))\n\t}\n}","line":{"from":142,"to":168}} {"id":100016175,"name":"TypeInvalid","signature":"func TypeInvalid(field *Path, value interface{}, detail string) *Error","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/field/errors.go","code":"// TypeInvalid returns a *Error indicating \"type is invalid\"\nfunc TypeInvalid(field *Path, value interface{}, detail string) *Error {\n\treturn \u0026Error{ErrorTypeTypeInvalid, field.String(), value, detail}\n}","line":{"from":170,"to":173}} {"id":100016176,"name":"NotFound","signature":"func NotFound(field *Path, value interface{}) *Error","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/field/errors.go","code":"// NotFound returns a *Error indicating \"value not found\". This is\n// used to report failure to find a requested value (e.g. looking up an ID).\nfunc NotFound(field *Path, value interface{}) *Error {\n\treturn \u0026Error{ErrorTypeNotFound, field.String(), value, \"\"}\n}","line":{"from":175,"to":179}} {"id":100016177,"name":"Required","signature":"func Required(field *Path, detail string) *Error","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/field/errors.go","code":"// Required returns a *Error indicating \"value required\". This is used\n// to report required values that are not provided (e.g. empty strings, null\n// values, or empty arrays).\nfunc Required(field *Path, detail string) *Error {\n\treturn \u0026Error{ErrorTypeRequired, field.String(), \"\", detail}\n}","line":{"from":181,"to":186}} {"id":100016178,"name":"Duplicate","signature":"func Duplicate(field *Path, value interface{}) *Error","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/field/errors.go","code":"// Duplicate returns a *Error indicating \"duplicate value\". This is\n// used to report collisions of values that must be unique (e.g. names or IDs).\nfunc Duplicate(field *Path, value interface{}) *Error {\n\treturn \u0026Error{ErrorTypeDuplicate, field.String(), value, \"\"}\n}","line":{"from":188,"to":192}} {"id":100016179,"name":"Invalid","signature":"func Invalid(field *Path, value interface{}, detail string) *Error","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/field/errors.go","code":"// Invalid returns a *Error indicating \"invalid value\". This is used\n// to report malformed values (e.g. failed regex match, too long, out of bounds).\nfunc Invalid(field *Path, value interface{}, detail string) *Error {\n\treturn \u0026Error{ErrorTypeInvalid, field.String(), value, detail}\n}","line":{"from":194,"to":198}} {"id":100016180,"name":"NotSupported","signature":"func NotSupported(field *Path, value interface{}, validValues []string) *Error","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/field/errors.go","code":"// NotSupported returns a *Error indicating \"unsupported value\".\n// This is used to report unknown values for enumerated fields (e.g. a list of\n// valid values).\nfunc NotSupported(field *Path, value interface{}, validValues []string) *Error {\n\tdetail := \"\"\n\tif len(validValues) \u003e 0 {\n\t\tquotedValues := make([]string, len(validValues))\n\t\tfor i, v := range validValues {\n\t\t\tquotedValues[i] = strconv.Quote(v)\n\t\t}\n\t\tdetail = \"supported values: \" + strings.Join(quotedValues, \", \")\n\t}\n\treturn \u0026Error{ErrorTypeNotSupported, field.String(), value, detail}\n}","line":{"from":200,"to":213}} {"id":100016181,"name":"Forbidden","signature":"func Forbidden(field *Path, detail string) *Error","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/field/errors.go","code":"// Forbidden returns a *Error indicating \"forbidden\". This is used to\n// report valid (as per formatting rules) values which would be accepted under\n// some conditions, but which are not permitted by current conditions (e.g.\n// security policy).\nfunc Forbidden(field *Path, detail string) *Error {\n\treturn \u0026Error{ErrorTypeForbidden, field.String(), \"\", detail}\n}","line":{"from":215,"to":221}} {"id":100016182,"name":"TooLong","signature":"func TooLong(field *Path, value interface{}, maxLength int) *Error","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/field/errors.go","code":"// TooLong returns a *Error indicating \"too long\". This is used to\n// report that the given value is too long. This is similar to\n// Invalid, but the returned error will not include the too-long\n// value.\nfunc TooLong(field *Path, value interface{}, maxLength int) *Error {\n\treturn \u0026Error{ErrorTypeTooLong, field.String(), value, fmt.Sprintf(\"must have at most %d bytes\", maxLength)}\n}","line":{"from":223,"to":229}} {"id":100016183,"name":"TooLongMaxLength","signature":"func TooLongMaxLength(field *Path, value interface{}, maxLength int) *Error","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/field/errors.go","code":"// TooLongMaxLength returns a *Error indicating \"too long\". This is used to\n// report that the given value is too long. This is similar to\n// Invalid, but the returned error will not include the too-long\n// value. If maxLength is negative, no max length will be included in the message.\nfunc TooLongMaxLength(field *Path, value interface{}, maxLength int) *Error {\n\tvar msg string\n\tif maxLength \u003e= 0 {\n\t\tmsg = fmt.Sprintf(\"may not be longer than %d\", maxLength)\n\t} else {\n\t\tmsg = \"value is too long\"\n\t}\n\treturn \u0026Error{ErrorTypeTooLong, field.String(), value, msg}\n}","line":{"from":231,"to":243}} {"id":100016184,"name":"TooMany","signature":"func TooMany(field *Path, actualQuantity, maxQuantity int) *Error","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/field/errors.go","code":"// TooMany returns a *Error indicating \"too many\". This is used to\n// report that a given list has too many items. This is similar to TooLong,\n// but the returned error indicates quantity instead of length.\nfunc TooMany(field *Path, actualQuantity, maxQuantity int) *Error {\n\tvar msg string\n\n\tif maxQuantity \u003e= 0 {\n\t\tmsg = fmt.Sprintf(\"must have at most %d items\", maxQuantity)\n\t} else {\n\t\tmsg = \"has too many items\"\n\t}\n\n\tvar actual interface{}\n\tif actualQuantity \u003e= 0 {\n\t\tactual = actualQuantity\n\t} else {\n\t\tactual = omitValue\n\t}\n\n\treturn \u0026Error{ErrorTypeTooMany, field.String(), actual, msg}\n}","line":{"from":245,"to":265}} {"id":100016185,"name":"InternalError","signature":"func InternalError(field *Path, err error) *Error","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/field/errors.go","code":"// InternalError returns a *Error indicating \"internal error\". This is used\n// to signal that an error was found that was not directly related to user\n// input. The err argument must be non-nil.\nfunc InternalError(field *Path, err error) *Error {\n\treturn \u0026Error{ErrorTypeInternal, field.String(), nil, err.Error()}\n}","line":{"from":267,"to":272}} {"id":100016186,"name":"NewErrorTypeMatcher","signature":"func NewErrorTypeMatcher(t ErrorType) utilerrors.Matcher","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/field/errors.go","code":"// NewErrorTypeMatcher returns an errors.Matcher that returns true\n// if the provided error is a Error and has the provided ErrorType.\nfunc NewErrorTypeMatcher(t ErrorType) utilerrors.Matcher {\n\treturn func(err error) bool {\n\t\tif e, ok := err.(*Error); ok {\n\t\t\treturn e.Type == t\n\t\t}\n\t\treturn false\n\t}\n}","line":{"from":279,"to":288}} {"id":100016187,"name":"ToAggregate","signature":"func (list ErrorList) ToAggregate() utilerrors.Aggregate","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/field/errors.go","code":"// ToAggregate converts the ErrorList into an errors.Aggregate.\nfunc (list ErrorList) ToAggregate() utilerrors.Aggregate {\n\tif len(list) == 0 {\n\t\treturn nil\n\t}\n\terrs := make([]error, 0, len(list))\n\terrorMsgs := sets.NewString()\n\tfor _, err := range list {\n\t\tmsg := fmt.Sprintf(\"%v\", err)\n\t\tif errorMsgs.Has(msg) {\n\t\t\tcontinue\n\t\t}\n\t\terrorMsgs.Insert(msg)\n\t\terrs = append(errs, err)\n\t}\n\treturn utilerrors.NewAggregate(errs)\n}","line":{"from":290,"to":306}} {"id":100016188,"name":"fromAggregate","signature":"func fromAggregate(agg utilerrors.Aggregate) ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/field/errors.go","code":"func fromAggregate(agg utilerrors.Aggregate) ErrorList {\n\terrs := agg.Errors()\n\tlist := make(ErrorList, len(errs))\n\tfor i := range errs {\n\t\tlist[i] = errs[i].(*Error)\n\t}\n\treturn list\n}","line":{"from":308,"to":315}} {"id":100016189,"name":"Filter","signature":"func (list ErrorList) Filter(fns ...utilerrors.Matcher) ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/field/errors.go","code":"// Filter removes items from the ErrorList that match the provided fns.\nfunc (list ErrorList) Filter(fns ...utilerrors.Matcher) ErrorList {\n\terr := utilerrors.FilterOut(list.ToAggregate(), fns...)\n\tif err == nil {\n\t\treturn nil\n\t}\n\t// FilterOut takes an Aggregate and returns an Aggregate\n\treturn fromAggregate(err.(utilerrors.Aggregate))\n}","line":{"from":317,"to":325}} {"id":100016190,"name":"WithPath","signature":"func WithPath(p *Path) PathOption","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/field/path.go","code":"// WithPath generates a PathOption\nfunc WithPath(p *Path) PathOption {\n\treturn func(o *pathOptions) {\n\t\to.path = p\n\t}\n}","line":{"from":32,"to":37}} {"id":100016191,"name":"ToPath","signature":"func ToPath(opts ...PathOption) *Path","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/field/path.go","code":"// ToPath produces *Path from a set of PathOption\nfunc ToPath(opts ...PathOption) *Path {\n\tc := \u0026pathOptions{}\n\tfor _, opt := range opts {\n\t\topt(c)\n\t}\n\treturn c.path\n}","line":{"from":39,"to":46}} {"id":100016192,"name":"NewPath","signature":"func NewPath(name string, moreNames ...string) *Path","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/field/path.go","code":"// NewPath creates a root Path object.\nfunc NewPath(name string, moreNames ...string) *Path {\n\tr := \u0026Path{name: name, parent: nil}\n\tfor _, anotherName := range moreNames {\n\t\tr = \u0026Path{name: anotherName, parent: r}\n\t}\n\treturn r\n}","line":{"from":55,"to":62}} {"id":100016193,"name":"Root","signature":"func (p *Path) Root() *Path","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/field/path.go","code":"// Root returns the root element of this Path.\nfunc (p *Path) Root() *Path {\n\tfor ; p.parent != nil; p = p.parent {\n\t\t// Do nothing.\n\t}\n\treturn p\n}","line":{"from":64,"to":70}} {"id":100016194,"name":"Child","signature":"func (p *Path) Child(name string, moreNames ...string) *Path","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/field/path.go","code":"// Child creates a new Path that is a child of the method receiver.\nfunc (p *Path) Child(name string, moreNames ...string) *Path {\n\tr := NewPath(name, moreNames...)\n\tr.Root().parent = p\n\treturn r\n}","line":{"from":72,"to":77}} {"id":100016195,"name":"Index","signature":"func (p *Path) Index(index int) *Path","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/field/path.go","code":"// Index indicates that the previous Path is to be subscripted by an int.\n// This sets the same underlying value as Key.\nfunc (p *Path) Index(index int) *Path {\n\treturn \u0026Path{index: strconv.Itoa(index), parent: p}\n}","line":{"from":79,"to":83}} {"id":100016196,"name":"Key","signature":"func (p *Path) Key(key string) *Path","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/field/path.go","code":"// Key indicates that the previous Path is to be subscripted by a string.\n// This sets the same underlying value as Index.\nfunc (p *Path) Key(key string) *Path {\n\treturn \u0026Path{index: key, parent: p}\n}","line":{"from":85,"to":89}} {"id":100016197,"name":"String","signature":"func (p *Path) String() string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/field/path.go","code":"// String produces a string representation of the Path.\nfunc (p *Path) String() string {\n\tif p == nil {\n\t\treturn \"\u003cnil\u003e\"\n\t}\n\t// make a slice to iterate\n\telems := []*Path{}\n\tfor ; p != nil; p = p.parent {\n\t\telems = append(elems, p)\n\t}\n\n\t// iterate, but it has to be backwards\n\tbuf := bytes.NewBuffer(nil)\n\tfor i := range elems {\n\t\tp := elems[len(elems)-1-i]\n\t\tif p.parent != nil \u0026\u0026 len(p.name) \u003e 0 {\n\t\t\t// This is either the root or it is a subscript.\n\t\t\tbuf.WriteString(\".\")\n\t\t}\n\t\tif len(p.name) \u003e 0 {\n\t\t\tbuf.WriteString(p.name)\n\t\t} else {\n\t\t\tfmt.Fprintf(buf, \"[%s]\", p.index)\n\t\t}\n\t}\n\treturn buf.String()\n}","line":{"from":91,"to":117}} {"id":100016198,"name":"IsQualifiedName","signature":"func IsQualifiedName(value string) []string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// IsQualifiedName tests whether the value passed is what Kubernetes calls a\n// \"qualified name\". This is a format used in various places throughout the\n// system. If the value is not valid, a list of error strings is returned.\n// Otherwise an empty list (or nil) is returned.\nfunc IsQualifiedName(value string) []string {\n\tvar errs []string\n\tparts := strings.Split(value, \"/\")\n\tvar name string\n\tswitch len(parts) {\n\tcase 1:\n\t\tname = parts[0]\n\tcase 2:\n\t\tvar prefix string\n\t\tprefix, name = parts[0], parts[1]\n\t\tif len(prefix) == 0 {\n\t\t\terrs = append(errs, \"prefix part \"+EmptyError())\n\t\t} else if msgs := IsDNS1123Subdomain(prefix); len(msgs) != 0 {\n\t\t\terrs = append(errs, prefixEach(msgs, \"prefix part \")...)\n\t\t}\n\tdefault:\n\t\treturn append(errs, \"a qualified name \"+RegexError(qualifiedNameErrMsg, qualifiedNameFmt, \"MyName\", \"my.name\", \"123-abc\")+\n\t\t\t\" with an optional DNS subdomain prefix and '/' (e.g. 'example.com/MyName')\")\n\t}\n\n\tif len(name) == 0 {\n\t\terrs = append(errs, \"name part \"+EmptyError())\n\t} else if len(name) \u003e qualifiedNameMaxLength {\n\t\terrs = append(errs, \"name part \"+MaxLenError(qualifiedNameMaxLength))\n\t}\n\tif !qualifiedNameRegexp.MatchString(name) {\n\t\terrs = append(errs, \"name part \"+RegexError(qualifiedNameErrMsg, qualifiedNameFmt, \"MyName\", \"my.name\", \"123-abc\"))\n\t}\n\treturn errs\n}","line":{"from":39,"to":72}} {"id":100016199,"name":"IsFullyQualifiedName","signature":"func IsFullyQualifiedName(fldPath *field.Path, name string) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// IsFullyQualifiedName checks if the name is fully qualified. This is similar\n// to IsFullyQualifiedDomainName but requires a minimum of 3 segments instead of\n// 2 and does not accept a trailing . as valid.\n// TODO: This function is deprecated and preserved until all callers migrate to\n// IsFullyQualifiedDomainName; please don't add new callers.\nfunc IsFullyQualifiedName(fldPath *field.Path, name string) field.ErrorList {\n\tvar allErrors field.ErrorList\n\tif len(name) == 0 {\n\t\treturn append(allErrors, field.Required(fldPath, \"\"))\n\t}\n\tif errs := IsDNS1123Subdomain(name); len(errs) \u003e 0 {\n\t\treturn append(allErrors, field.Invalid(fldPath, name, strings.Join(errs, \",\")))\n\t}\n\tif len(strings.Split(name, \".\")) \u003c 3 {\n\t\treturn append(allErrors, field.Invalid(fldPath, name, \"should be a domain with at least three segments separated by dots\"))\n\t}\n\treturn allErrors\n}","line":{"from":74,"to":91}} {"id":100016200,"name":"IsFullyQualifiedDomainName","signature":"func IsFullyQualifiedDomainName(fldPath *field.Path, name string) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// IsFullyQualifiedDomainName checks if the domain name is fully qualified. This\n// is similar to IsFullyQualifiedName but only requires a minimum of 2 segments\n// instead of 3 and accepts a trailing . as valid.\nfunc IsFullyQualifiedDomainName(fldPath *field.Path, name string) field.ErrorList {\n\tvar allErrors field.ErrorList\n\tif len(name) == 0 {\n\t\treturn append(allErrors, field.Required(fldPath, \"\"))\n\t}\n\tif strings.HasSuffix(name, \".\") {\n\t\tname = name[:len(name)-1]\n\t}\n\tif errs := IsDNS1123Subdomain(name); len(errs) \u003e 0 {\n\t\treturn append(allErrors, field.Invalid(fldPath, name, strings.Join(errs, \",\")))\n\t}\n\tif len(strings.Split(name, \".\")) \u003c 2 {\n\t\treturn append(allErrors, field.Invalid(fldPath, name, \"should be a domain with at least two segments separated by dots\"))\n\t}\n\tfor _, label := range strings.Split(name, \".\") {\n\t\tif errs := IsDNS1123Label(label); len(errs) \u003e 0 {\n\t\t\treturn append(allErrors, field.Invalid(fldPath, label, strings.Join(errs, \",\")))\n\t\t}\n\t}\n\treturn allErrors\n}","line":{"from":93,"to":116}} {"id":100016201,"name":"IsDomainPrefixedPath","signature":"func IsDomainPrefixedPath(fldPath *field.Path, dpPath string) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// IsDomainPrefixedPath checks if the given string is a domain-prefixed path\n// (e.g. acme.io/foo). All characters before the first \"/\" must be a valid\n// subdomain as defined by RFC 1123. All characters trailing the first \"/\" must\n// be valid HTTP Path characters as defined by RFC 3986.\nfunc IsDomainPrefixedPath(fldPath *field.Path, dpPath string) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tif len(dpPath) == 0 {\n\t\treturn append(allErrs, field.Required(fldPath, \"\"))\n\t}\n\n\tsegments := strings.SplitN(dpPath, \"/\", 2)\n\tif len(segments) != 2 || len(segments[0]) == 0 || len(segments[1]) == 0 {\n\t\treturn append(allErrs, field.Invalid(fldPath, dpPath, \"must be a domain-prefixed path (such as \\\"acme.io/foo\\\")\"))\n\t}\n\n\thost := segments[0]\n\tfor _, err := range IsDNS1123Subdomain(host) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath, host, err))\n\t}\n\n\tpath := segments[1]\n\tif !httpPathRegexp.MatchString(path) {\n\t\treturn append(allErrs, field.Invalid(fldPath, path, RegexError(\"Invalid path\", httpPathFmt)))\n\t}\n\n\treturn allErrs\n}","line":{"from":128,"to":154}} {"id":100016202,"name":"IsValidLabelValue","signature":"func IsValidLabelValue(value string) []string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// IsValidLabelValue tests whether the value passed is a valid label value. If\n// the value is not valid, a list of error strings is returned. Otherwise an\n// empty list (or nil) is returned.\nfunc IsValidLabelValue(value string) []string {\n\tvar errs []string\n\tif len(value) \u003e LabelValueMaxLength {\n\t\terrs = append(errs, MaxLenError(LabelValueMaxLength))\n\t}\n\tif !labelValueRegexp.MatchString(value) {\n\t\terrs = append(errs, RegexError(labelValueErrMsg, labelValueFmt, \"MyValue\", \"my_value\", \"12345\"))\n\t}\n\treturn errs\n}","line":{"from":164,"to":176}} {"id":100016203,"name":"IsDNS1123Label","signature":"func IsDNS1123Label(value string) []string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// IsDNS1123Label tests for a string that conforms to the definition of a label in\n// DNS (RFC 1123).\nfunc IsDNS1123Label(value string) []string {\n\tvar errs []string\n\tif len(value) \u003e DNS1123LabelMaxLength {\n\t\terrs = append(errs, MaxLenError(DNS1123LabelMaxLength))\n\t}\n\tif !dns1123LabelRegexp.MatchString(value) {\n\t\tif dns1123SubdomainRegexp.MatchString(value) {\n\t\t\t// It was a valid subdomain and not a valid label. Since we\n\t\t\t// already checked length, it must be dots.\n\t\t\terrs = append(errs, \"must not contain dots\")\n\t\t} else {\n\t\t\terrs = append(errs, RegexError(dns1123LabelErrMsg, dns1123LabelFmt, \"my-name\", \"123-abc\"))\n\t\t}\n\t}\n\treturn errs\n}","line":{"from":186,"to":203}} {"id":100016204,"name":"IsDNS1123Subdomain","signature":"func IsDNS1123Subdomain(value string) []string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// IsDNS1123Subdomain tests for a string that conforms to the definition of a\n// subdomain in DNS (RFC 1123).\nfunc IsDNS1123Subdomain(value string) []string {\n\tvar errs []string\n\tif len(value) \u003e DNS1123SubdomainMaxLength {\n\t\terrs = append(errs, MaxLenError(DNS1123SubdomainMaxLength))\n\t}\n\tif !dns1123SubdomainRegexp.MatchString(value) {\n\t\terrs = append(errs, RegexError(dns1123SubdomainErrorMsg, dns1123SubdomainFmt, \"example.com\"))\n\t}\n\treturn errs\n}","line":{"from":213,"to":224}} {"id":100016205,"name":"IsDNS1035Label","signature":"func IsDNS1035Label(value string) []string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// IsDNS1035Label tests for a string that conforms to the definition of a label in\n// DNS (RFC 1035).\nfunc IsDNS1035Label(value string) []string {\n\tvar errs []string\n\tif len(value) \u003e DNS1035LabelMaxLength {\n\t\terrs = append(errs, MaxLenError(DNS1035LabelMaxLength))\n\t}\n\tif !dns1035LabelRegexp.MatchString(value) {\n\t\terrs = append(errs, RegexError(dns1035LabelErrMsg, dns1035LabelFmt, \"my-name\", \"abc-123\"))\n\t}\n\treturn errs\n}","line":{"from":234,"to":245}} {"id":100016206,"name":"IsWildcardDNS1123Subdomain","signature":"func IsWildcardDNS1123Subdomain(value string) []string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// IsWildcardDNS1123Subdomain tests for a string that conforms to the definition of a\n// wildcard subdomain in DNS (RFC 1034 section 4.3.3).\nfunc IsWildcardDNS1123Subdomain(value string) []string {\n\twildcardDNS1123SubdomainRegexp := regexp.MustCompile(\"^\" + wildcardDNS1123SubdomainFmt + \"$\")\n\n\tvar errs []string\n\tif len(value) \u003e DNS1123SubdomainMaxLength {\n\t\terrs = append(errs, MaxLenError(DNS1123SubdomainMaxLength))\n\t}\n\tif !wildcardDNS1123SubdomainRegexp.MatchString(value) {\n\t\terrs = append(errs, RegexError(wildcardDNS1123SubdomainErrMsg, wildcardDNS1123SubdomainFmt, \"*.example.com\"))\n\t}\n\treturn errs\n}","line":{"from":254,"to":267}} {"id":100016207,"name":"IsCIdentifier","signature":"func IsCIdentifier(value string) []string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// IsCIdentifier tests for a string that conforms the definition of an identifier\n// in C. This checks the format, but not the length.\nfunc IsCIdentifier(value string) []string {\n\tif !cIdentifierRegexp.MatchString(value) {\n\t\treturn []string{RegexError(identifierErrMsg, cIdentifierFmt, \"my_name\", \"MY_NAME\", \"MyName\")}\n\t}\n\treturn nil\n}","line":{"from":274,"to":281}} {"id":100016208,"name":"IsValidPortNum","signature":"func IsValidPortNum(port int) []string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// IsValidPortNum tests that the argument is a valid, non-zero port number.\nfunc IsValidPortNum(port int) []string {\n\tif 1 \u003c= port \u0026\u0026 port \u003c= 65535 {\n\t\treturn nil\n\t}\n\treturn []string{InclusiveRangeError(1, 65535)}\n}","line":{"from":283,"to":289}} {"id":100016209,"name":"IsInRange","signature":"func IsInRange(value int, min int, max int) []string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// IsInRange tests that the argument is in an inclusive range.\nfunc IsInRange(value int, min int, max int) []string {\n\tif value \u003e= min \u0026\u0026 value \u003c= max {\n\t\treturn nil\n\t}\n\treturn []string{InclusiveRangeError(min, max)}\n}","line":{"from":291,"to":297}} {"id":100016210,"name":"IsValidGroupID","signature":"func IsValidGroupID(gid int64) []string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// IsValidGroupID tests that the argument is a valid Unix GID.\nfunc IsValidGroupID(gid int64) []string {\n\tif minGroupID \u003c= gid \u0026\u0026 gid \u003c= maxGroupID {\n\t\treturn nil\n\t}\n\treturn []string{InclusiveRangeError(minGroupID, maxGroupID)}\n}","line":{"from":308,"to":314}} {"id":100016211,"name":"IsValidUserID","signature":"func IsValidUserID(uid int64) []string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// IsValidUserID tests that the argument is a valid Unix UID.\nfunc IsValidUserID(uid int64) []string {\n\tif minUserID \u003c= uid \u0026\u0026 uid \u003c= maxUserID {\n\t\treturn nil\n\t}\n\treturn []string{InclusiveRangeError(minUserID, maxUserID)}\n}","line":{"from":316,"to":322}} {"id":100016212,"name":"IsValidPortName","signature":"func IsValidPortName(port string) []string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// IsValidPortName check that the argument is valid syntax. It must be\n// non-empty and no more than 15 characters long. It may contain only [-a-z0-9]\n// and must contain at least one letter [a-z]. It must not start or end with a\n// hyphen, nor contain adjacent hyphens.\n//\n// Note: We only allow lower-case characters, even though RFC 6335 is case\n// insensitive.\nfunc IsValidPortName(port string) []string {\n\tvar errs []string\n\tif len(port) \u003e 15 {\n\t\terrs = append(errs, MaxLenError(15))\n\t}\n\tif !portNameCharsetRegex.MatchString(port) {\n\t\terrs = append(errs, \"must contain only alpha-numeric characters (a-z, 0-9), and hyphens (-)\")\n\t}\n\tif !portNameOneLetterRegexp.MatchString(port) {\n\t\terrs = append(errs, \"must contain at least one letter (a-z)\")\n\t}\n\tif strings.Contains(port, \"--\") {\n\t\terrs = append(errs, \"must not contain consecutive hyphens\")\n\t}\n\tif len(port) \u003e 0 \u0026\u0026 (port[0] == '-' || port[len(port)-1] == '-') {\n\t\terrs = append(errs, \"must not begin or end with a hyphen\")\n\t}\n\treturn errs\n}","line":{"from":327,"to":352}} {"id":100016213,"name":"IsValidIP","signature":"func IsValidIP(value string) []string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// IsValidIP tests that the argument is a valid IP address.\nfunc IsValidIP(value string) []string {\n\tif netutils.ParseIPSloppy(value) == nil {\n\t\treturn []string{\"must be a valid IP address, (e.g. 10.9.8.7 or 2001:db8::ffff)\"}\n\t}\n\treturn nil\n}","line":{"from":354,"to":360}} {"id":100016214,"name":"IsValidIPv4Address","signature":"func IsValidIPv4Address(fldPath *field.Path, value string) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// IsValidIPv4Address tests that the argument is a valid IPv4 address.\nfunc IsValidIPv4Address(fldPath *field.Path, value string) field.ErrorList {\n\tvar allErrors field.ErrorList\n\tip := netutils.ParseIPSloppy(value)\n\tif ip == nil || ip.To4() == nil {\n\t\tallErrors = append(allErrors, field.Invalid(fldPath, value, \"must be a valid IPv4 address\"))\n\t}\n\treturn allErrors\n}","line":{"from":362,"to":370}} {"id":100016215,"name":"IsValidIPv6Address","signature":"func IsValidIPv6Address(fldPath *field.Path, value string) field.ErrorList","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// IsValidIPv6Address tests that the argument is a valid IPv6 address.\nfunc IsValidIPv6Address(fldPath *field.Path, value string) field.ErrorList {\n\tvar allErrors field.ErrorList\n\tip := netutils.ParseIPSloppy(value)\n\tif ip == nil || ip.To4() != nil {\n\t\tallErrors = append(allErrors, field.Invalid(fldPath, value, \"must be a valid IPv6 address\"))\n\t}\n\treturn allErrors\n}","line":{"from":372,"to":380}} {"id":100016216,"name":"IsValidPercent","signature":"func IsValidPercent(percent string) []string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// IsValidPercent checks that string is in the form of a percentage\nfunc IsValidPercent(percent string) []string {\n\tif !percentRegexp.MatchString(percent) {\n\t\treturn []string{RegexError(percentErrMsg, percentFmt, \"1%\", \"93%\")}\n\t}\n\treturn nil\n}","line":{"from":387,"to":393}} {"id":100016217,"name":"IsHTTPHeaderName","signature":"func IsHTTPHeaderName(value string) []string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// IsHTTPHeaderName checks that a string conforms to the Go HTTP library's\n// definition of a valid header field name (a stricter subset than RFC7230).\nfunc IsHTTPHeaderName(value string) []string {\n\tif !httpHeaderNameRegexp.MatchString(value) {\n\t\treturn []string{RegexError(httpHeaderNameErrMsg, httpHeaderNameFmt, \"X-Header-Name\")}\n\t}\n\treturn nil\n}","line":{"from":400,"to":407}} {"id":100016218,"name":"IsEnvVarName","signature":"func IsEnvVarName(value string) []string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// IsEnvVarName tests if a string is a valid environment variable name.\nfunc IsEnvVarName(value string) []string {\n\tvar errs []string\n\tif !envVarNameRegexp.MatchString(value) {\n\t\terrs = append(errs, RegexError(envVarNameFmtErrMsg, envVarNameFmt, \"my.env-name\", \"MY_ENV.NAME\", \"MyEnvName1\"))\n\t}\n\n\terrs = append(errs, hasChDirPrefix(value)...)\n\treturn errs\n}","line":{"from":414,"to":423}} {"id":100016219,"name":"IsConfigMapKey","signature":"func IsConfigMapKey(value string) []string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// IsConfigMapKey tests for a string that is a valid key for a ConfigMap or Secret\nfunc IsConfigMapKey(value string) []string {\n\tvar errs []string\n\tif len(value) \u003e DNS1123SubdomainMaxLength {\n\t\terrs = append(errs, MaxLenError(DNS1123SubdomainMaxLength))\n\t}\n\tif !configMapKeyRegexp.MatchString(value) {\n\t\terrs = append(errs, RegexError(configMapKeyErrMsg, configMapKeyFmt, \"key.name\", \"KEY_NAME\", \"key-name\"))\n\t}\n\terrs = append(errs, hasChDirPrefix(value)...)\n\treturn errs\n}","line":{"from":430,"to":441}} {"id":100016220,"name":"MaxLenError","signature":"func MaxLenError(length int) string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// MaxLenError returns a string explanation of a \"string too long\" validation\n// failure.\nfunc MaxLenError(length int) string {\n\treturn fmt.Sprintf(\"must be no more than %d characters\", length)\n}","line":{"from":443,"to":447}} {"id":100016221,"name":"RegexError","signature":"func RegexError(msg string, fmt string, examples ...string) string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// RegexError returns a string explanation of a regex validation failure.\nfunc RegexError(msg string, fmt string, examples ...string) string {\n\tif len(examples) == 0 {\n\t\treturn msg + \" (regex used for validation is '\" + fmt + \"')\"\n\t}\n\tmsg += \" (e.g. \"\n\tfor i := range examples {\n\t\tif i \u003e 0 {\n\t\t\tmsg += \" or \"\n\t\t}\n\t\tmsg += \"'\" + examples[i] + \"', \"\n\t}\n\tmsg += \"regex used for validation is '\" + fmt + \"')\"\n\treturn msg\n}","line":{"from":449,"to":463}} {"id":100016222,"name":"EmptyError","signature":"func EmptyError() string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// EmptyError returns a string explanation of a \"must not be empty\" validation\n// failure.\nfunc EmptyError() string {\n\treturn \"must be non-empty\"\n}","line":{"from":465,"to":469}} {"id":100016223,"name":"prefixEach","signature":"func prefixEach(msgs []string, prefix string) []string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"func prefixEach(msgs []string, prefix string) []string {\n\tfor i := range msgs {\n\t\tmsgs[i] = prefix + msgs[i]\n\t}\n\treturn msgs\n}","line":{"from":471,"to":476}} {"id":100016224,"name":"InclusiveRangeError","signature":"func InclusiveRangeError(lo, hi int) string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// InclusiveRangeError returns a string explanation of a numeric \"must be\n// between\" validation failure.\nfunc InclusiveRangeError(lo, hi int) string {\n\treturn fmt.Sprintf(`must be between %d and %d, inclusive`, lo, hi)\n}","line":{"from":478,"to":482}} {"id":100016225,"name":"hasChDirPrefix","signature":"func hasChDirPrefix(value string) []string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"func hasChDirPrefix(value string) []string {\n\tvar errs []string\n\tswitch {\n\tcase value == \".\":\n\t\terrs = append(errs, `must not be '.'`)\n\tcase value == \"..\":\n\t\terrs = append(errs, `must not be '..'`)\n\tcase strings.HasPrefix(value, \"..\"):\n\t\terrs = append(errs, `must not start with '..'`)\n\t}\n\treturn errs\n}","line":{"from":484,"to":495}} {"id":100016226,"name":"IsValidSocketAddr","signature":"func IsValidSocketAddr(value string) []string","file":"staging/src/k8s.io/apimachinery/pkg/util/validation/validation.go","code":"// IsValidSocketAddr checks that string represents a valid socket address\n// as defined in RFC 789. (e.g 0.0.0.0:10254 or [::]:10254))\nfunc IsValidSocketAddr(value string) []string {\n\tvar errs []string\n\tip, port, err := net.SplitHostPort(value)\n\tif err != nil {\n\t\terrs = append(errs, \"must be a valid socket address format, (e.g. 0.0.0.0:10254 or [::]:10254)\")\n\t\treturn errs\n\t}\n\tportInt, _ := strconv.Atoi(port)\n\terrs = append(errs, IsValidPortNum(portInt)...)\n\terrs = append(errs, IsValidIP(ip)...)\n\treturn errs\n}","line":{"from":497,"to":510}} {"id":100016227,"name":"parse","signature":"func parse(str string, semver bool) (*Version, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/version/version.go","code":"func parse(str string, semver bool) (*Version, error) {\n\tparts := versionMatchRE.FindStringSubmatch(str)\n\tif parts == nil {\n\t\treturn nil, fmt.Errorf(\"could not parse %q as version\", str)\n\t}\n\tnumbers, extra := parts[1], parts[2]\n\n\tcomponents := strings.Split(numbers, \".\")\n\tif (semver \u0026\u0026 len(components) != 3) || (!semver \u0026\u0026 len(components) \u003c 2) {\n\t\treturn nil, fmt.Errorf(\"illegal version string %q\", str)\n\t}\n\n\tv := \u0026Version{\n\t\tcomponents: make([]uint, len(components)),\n\t\tsemver: semver,\n\t}\n\tfor i, comp := range components {\n\t\tif (i == 0 || semver) \u0026\u0026 strings.HasPrefix(comp, \"0\") \u0026\u0026 comp != \"0\" {\n\t\t\treturn nil, fmt.Errorf(\"illegal zero-prefixed version component %q in %q\", comp, str)\n\t\t}\n\t\tnum, err := strconv.ParseUint(comp, 10, 0)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"illegal non-numeric version component %q in %q: %v\", comp, str, err)\n\t\t}\n\t\tv.components[i] = uint(num)\n\t}\n\n\tif semver \u0026\u0026 extra != \"\" {\n\t\textraParts := extraMatchRE.FindStringSubmatch(extra)\n\t\tif extraParts == nil {\n\t\t\treturn nil, fmt.Errorf(\"could not parse pre-release/metadata (%s) in version %q\", extra, str)\n\t\t}\n\t\tv.preRelease, v.buildMetadata = extraParts[1], extraParts[2]\n\n\t\tfor _, comp := range strings.Split(v.preRelease, \".\") {\n\t\t\tif _, err := strconv.ParseUint(comp, 10, 0); err == nil {\n\t\t\t\tif strings.HasPrefix(comp, \"0\") \u0026\u0026 comp != \"0\" {\n\t\t\t\t\treturn nil, fmt.Errorf(\"illegal zero-prefixed version component %q in %q\", comp, str)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn v, nil\n}","line":{"from":42,"to":86}} {"id":100016228,"name":"ParseGeneric","signature":"func ParseGeneric(str string) (*Version, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/version/version.go","code":"// ParseGeneric parses a \"generic\" version string. The version string must consist of two\n// or more dot-separated numeric fields (the first of which can't have leading zeroes),\n// followed by arbitrary uninterpreted data (which need not be separated from the final\n// numeric field by punctuation). For convenience, leading and trailing whitespace is\n// ignored, and the version can be preceded by the letter \"v\". See also ParseSemantic.\nfunc ParseGeneric(str string) (*Version, error) {\n\treturn parse(str, false)\n}","line":{"from":88,"to":95}} {"id":100016229,"name":"MustParseGeneric","signature":"func MustParseGeneric(str string) *Version","file":"staging/src/k8s.io/apimachinery/pkg/util/version/version.go","code":"// MustParseGeneric is like ParseGeneric except that it panics on error\nfunc MustParseGeneric(str string) *Version {\n\tv, err := ParseGeneric(str)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}","line":{"from":97,"to":104}} {"id":100016230,"name":"ParseSemantic","signature":"func ParseSemantic(str string) (*Version, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/version/version.go","code":"// ParseSemantic parses a version string that exactly obeys the syntax and semantics of\n// the \"Semantic Versioning\" specification (http://semver.org/) (although it ignores\n// leading and trailing whitespace, and allows the version to be preceded by \"v\"). For\n// version strings that are not guaranteed to obey the Semantic Versioning syntax, use\n// ParseGeneric.\nfunc ParseSemantic(str string) (*Version, error) {\n\treturn parse(str, true)\n}","line":{"from":106,"to":113}} {"id":100016231,"name":"MustParseSemantic","signature":"func MustParseSemantic(str string) *Version","file":"staging/src/k8s.io/apimachinery/pkg/util/version/version.go","code":"// MustParseSemantic is like ParseSemantic except that it panics on error\nfunc MustParseSemantic(str string) *Version {\n\tv, err := ParseSemantic(str)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}","line":{"from":115,"to":122}} {"id":100016232,"name":"Major","signature":"func (v *Version) Major() uint","file":"staging/src/k8s.io/apimachinery/pkg/util/version/version.go","code":"// Major returns the major release number\nfunc (v *Version) Major() uint {\n\treturn v.components[0]\n}","line":{"from":124,"to":127}} {"id":100016233,"name":"Minor","signature":"func (v *Version) Minor() uint","file":"staging/src/k8s.io/apimachinery/pkg/util/version/version.go","code":"// Minor returns the minor release number\nfunc (v *Version) Minor() uint {\n\treturn v.components[1]\n}","line":{"from":129,"to":132}} {"id":100016234,"name":"Patch","signature":"func (v *Version) Patch() uint","file":"staging/src/k8s.io/apimachinery/pkg/util/version/version.go","code":"// Patch returns the patch release number if v is a Semantic Version, or 0\nfunc (v *Version) Patch() uint {\n\tif len(v.components) \u003c 3 {\n\t\treturn 0\n\t}\n\treturn v.components[2]\n}","line":{"from":134,"to":140}} {"id":100016235,"name":"BuildMetadata","signature":"func (v *Version) BuildMetadata() string","file":"staging/src/k8s.io/apimachinery/pkg/util/version/version.go","code":"// BuildMetadata returns the build metadata, if v is a Semantic Version, or \"\"\nfunc (v *Version) BuildMetadata() string {\n\treturn v.buildMetadata\n}","line":{"from":142,"to":145}} {"id":100016236,"name":"PreRelease","signature":"func (v *Version) PreRelease() string","file":"staging/src/k8s.io/apimachinery/pkg/util/version/version.go","code":"// PreRelease returns the prerelease metadata, if v is a Semantic Version, or \"\"\nfunc (v *Version) PreRelease() string {\n\treturn v.preRelease\n}","line":{"from":147,"to":150}} {"id":100016237,"name":"Components","signature":"func (v *Version) Components() []uint","file":"staging/src/k8s.io/apimachinery/pkg/util/version/version.go","code":"// Components returns the version number components\nfunc (v *Version) Components() []uint {\n\treturn v.components\n}","line":{"from":152,"to":155}} {"id":100016238,"name":"WithMajor","signature":"func (v *Version) WithMajor(major uint) *Version","file":"staging/src/k8s.io/apimachinery/pkg/util/version/version.go","code":"// WithMajor returns copy of the version object with requested major number\nfunc (v *Version) WithMajor(major uint) *Version {\n\tresult := *v\n\tresult.components = []uint{major, v.Minor(), v.Patch()}\n\treturn \u0026result\n}","line":{"from":157,"to":162}} {"id":100016239,"name":"WithMinor","signature":"func (v *Version) WithMinor(minor uint) *Version","file":"staging/src/k8s.io/apimachinery/pkg/util/version/version.go","code":"// WithMinor returns copy of the version object with requested minor number\nfunc (v *Version) WithMinor(minor uint) *Version {\n\tresult := *v\n\tresult.components = []uint{v.Major(), minor, v.Patch()}\n\treturn \u0026result\n}","line":{"from":164,"to":169}} {"id":100016240,"name":"WithPatch","signature":"func (v *Version) WithPatch(patch uint) *Version","file":"staging/src/k8s.io/apimachinery/pkg/util/version/version.go","code":"// WithPatch returns copy of the version object with requested patch number\nfunc (v *Version) WithPatch(patch uint) *Version {\n\tresult := *v\n\tresult.components = []uint{v.Major(), v.Minor(), patch}\n\treturn \u0026result\n}","line":{"from":171,"to":176}} {"id":100016241,"name":"WithPreRelease","signature":"func (v *Version) WithPreRelease(preRelease string) *Version","file":"staging/src/k8s.io/apimachinery/pkg/util/version/version.go","code":"// WithPreRelease returns copy of the version object with requested prerelease\nfunc (v *Version) WithPreRelease(preRelease string) *Version {\n\tresult := *v\n\tresult.components = []uint{v.Major(), v.Minor(), v.Patch()}\n\tresult.preRelease = preRelease\n\treturn \u0026result\n}","line":{"from":178,"to":184}} {"id":100016242,"name":"WithBuildMetadata","signature":"func (v *Version) WithBuildMetadata(buildMetadata string) *Version","file":"staging/src/k8s.io/apimachinery/pkg/util/version/version.go","code":"// WithBuildMetadata returns copy of the version object with requested buildMetadata\nfunc (v *Version) WithBuildMetadata(buildMetadata string) *Version {\n\tresult := *v\n\tresult.components = []uint{v.Major(), v.Minor(), v.Patch()}\n\tresult.buildMetadata = buildMetadata\n\treturn \u0026result\n}","line":{"from":186,"to":192}} {"id":100016243,"name":"String","signature":"func (v *Version) String() string","file":"staging/src/k8s.io/apimachinery/pkg/util/version/version.go","code":"// String converts a Version back to a string; note that for versions parsed with\n// ParseGeneric, this will not include the trailing uninterpreted portion of the version\n// number.\nfunc (v *Version) String() string {\n\tif v == nil {\n\t\treturn \"\u003cnil\u003e\"\n\t}\n\tvar buffer bytes.Buffer\n\n\tfor i, comp := range v.components {\n\t\tif i \u003e 0 {\n\t\t\tbuffer.WriteString(\".\")\n\t\t}\n\t\tbuffer.WriteString(fmt.Sprintf(\"%d\", comp))\n\t}\n\tif v.preRelease != \"\" {\n\t\tbuffer.WriteString(\"-\")\n\t\tbuffer.WriteString(v.preRelease)\n\t}\n\tif v.buildMetadata != \"\" {\n\t\tbuffer.WriteString(\"+\")\n\t\tbuffer.WriteString(v.buildMetadata)\n\t}\n\n\treturn buffer.String()\n}","line":{"from":194,"to":219}} {"id":100016244,"name":"compareInternal","signature":"func (v *Version) compareInternal(other *Version) int","file":"staging/src/k8s.io/apimachinery/pkg/util/version/version.go","code":"// compareInternal returns -1 if v is less than other, 1 if it is greater than other, or 0\n// if they are equal\nfunc (v *Version) compareInternal(other *Version) int {\n\n\tvLen := len(v.components)\n\toLen := len(other.components)\n\tfor i := 0; i \u003c vLen \u0026\u0026 i \u003c oLen; i++ {\n\t\tswitch {\n\t\tcase other.components[i] \u003c v.components[i]:\n\t\t\treturn 1\n\t\tcase other.components[i] \u003e v.components[i]:\n\t\t\treturn -1\n\t\t}\n\t}\n\n\t// If components are common but one has more items and they are not zeros, it is bigger\n\tswitch {\n\tcase oLen \u003c vLen \u0026\u0026 !onlyZeros(v.components[oLen:]):\n\t\treturn 1\n\tcase oLen \u003e vLen \u0026\u0026 !onlyZeros(other.components[vLen:]):\n\t\treturn -1\n\t}\n\n\tif !v.semver || !other.semver {\n\t\treturn 0\n\t}\n\n\tswitch {\n\tcase v.preRelease == \"\" \u0026\u0026 other.preRelease != \"\":\n\t\treturn 1\n\tcase v.preRelease != \"\" \u0026\u0026 other.preRelease == \"\":\n\t\treturn -1\n\tcase v.preRelease == other.preRelease: // includes case where both are \"\"\n\t\treturn 0\n\t}\n\n\tvPR := strings.Split(v.preRelease, \".\")\n\toPR := strings.Split(other.preRelease, \".\")\n\tfor i := 0; i \u003c len(vPR) \u0026\u0026 i \u003c len(oPR); i++ {\n\t\tvNum, err := strconv.ParseUint(vPR[i], 10, 0)\n\t\tif err == nil {\n\t\t\toNum, err := strconv.ParseUint(oPR[i], 10, 0)\n\t\t\tif err == nil {\n\t\t\t\tswitch {\n\t\t\t\tcase oNum \u003c vNum:\n\t\t\t\t\treturn 1\n\t\t\t\tcase oNum \u003e vNum:\n\t\t\t\t\treturn -1\n\t\t\t\tdefault:\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif oPR[i] \u003c vPR[i] {\n\t\t\treturn 1\n\t\t} else if oPR[i] \u003e vPR[i] {\n\t\t\treturn -1\n\t\t}\n\t}\n\n\tswitch {\n\tcase len(oPR) \u003c len(vPR):\n\t\treturn 1\n\tcase len(oPR) \u003e len(vPR):\n\t\treturn -1\n\t}\n\n\treturn 0\n}","line":{"from":221,"to":289}} {"id":100016245,"name":"onlyZeros","signature":"func onlyZeros(array []uint) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/version/version.go","code":"// returns false if array contain any non-zero element\nfunc onlyZeros(array []uint) bool {\n\tfor _, num := range array {\n\t\tif num != 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":291,"to":299}} {"id":100016246,"name":"AtLeast","signature":"func (v *Version) AtLeast(min *Version) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/version/version.go","code":"// AtLeast tests if a version is at least equal to a given minimum version. If both\n// Versions are Semantic Versions, this will use the Semantic Version comparison\n// algorithm. Otherwise, it will compare only the numeric components, with non-present\n// components being considered \"0\" (ie, \"1.4\" is equal to \"1.4.0\").\nfunc (v *Version) AtLeast(min *Version) bool {\n\treturn v.compareInternal(min) != -1\n}","line":{"from":301,"to":307}} {"id":100016247,"name":"LessThan","signature":"func (v *Version) LessThan(other *Version) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/version/version.go","code":"// LessThan tests if a version is less than a given version. (It is exactly the opposite\n// of AtLeast, for situations where asking \"is v too old?\" makes more sense than asking\n// \"is v new enough?\".)\nfunc (v *Version) LessThan(other *Version) bool {\n\treturn v.compareInternal(other) == -1\n}","line":{"from":309,"to":314}} {"id":100016248,"name":"Compare","signature":"func (v *Version) Compare(other string) (int, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/version/version.go","code":"// Compare compares v against a version string (which will be parsed as either Semantic\n// or non-Semantic depending on v). On success it returns -1 if v is less than other, 1 if\n// it is greater than other, or 0 if they are equal.\nfunc (v *Version) Compare(other string) (int, error) {\n\tov, err := parse(other, v.semver)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn v.compareInternal(ov), nil\n}","line":{"from":316,"to":325}} {"id":100016249,"name":"Step","signature":"func (b *Backoff) Step() time.Duration","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/backoff.go","code":"// Step returns an amount of time to sleep determined by the original\n// Duration and Jitter. The backoff is mutated to update its Steps and\n// Duration. A nil Backoff always has a zero-duration step.\nfunc (b *Backoff) Step() time.Duration {\n\tif b == nil {\n\t\treturn 0\n\t}\n\tvar nextDuration time.Duration\n\tnextDuration, b.Duration, b.Steps = delay(b.Steps, b.Duration, b.Cap, b.Factor, b.Jitter)\n\treturn nextDuration\n}","line":{"from":55,"to":65}} {"id":100016250,"name":"DelayFunc","signature":"func (b Backoff) DelayFunc() DelayFunc","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/backoff.go","code":"// DelayFunc returns a function that will compute the next interval to\n// wait given the arguments in b. It does not mutate the original backoff\n// but the function is safe to use only from a single goroutine.\nfunc (b Backoff) DelayFunc() DelayFunc {\n\tsteps := b.Steps\n\tduration := b.Duration\n\tcap := b.Cap\n\tfactor := b.Factor\n\tjitter := b.Jitter\n\n\treturn func() time.Duration {\n\t\tvar nextDuration time.Duration\n\t\t// jitter is applied per step and is not cumulative over multiple steps\n\t\tnextDuration, duration, steps = delay(steps, duration, cap, factor, jitter)\n\t\treturn nextDuration\n\t}\n}","line":{"from":67,"to":83}} {"id":100016251,"name":"Timer","signature":"func (b Backoff) Timer() Timer","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/backoff.go","code":"// Timer returns a timer implementation appropriate to this backoff's parameters\n// for use with wait functions.\nfunc (b Backoff) Timer() Timer {\n\tif b.Steps \u003e 1 || b.Jitter != 0 {\n\t\treturn \u0026variableTimer{new: internalClock.NewTimer, fn: b.DelayFunc()}\n\t}\n\tif b.Duration \u003e 0 {\n\t\treturn \u0026fixedTimer{new: internalClock.NewTicker, interval: b.Duration}\n\t}\n\treturn newNoopTimer()\n}","line":{"from":85,"to":95}} {"id":100016252,"name":"delay","signature":"func delay(steps int, duration, cap time.Duration, factor, jitter float64) (_ time.Duration, next time.Duration, nextSteps int)","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/backoff.go","code":"// delay implements the core delay algorithm used in this package.\nfunc delay(steps int, duration, cap time.Duration, factor, jitter float64) (_ time.Duration, next time.Duration, nextSteps int) {\n\t// when steps is non-positive, do not alter the base duration\n\tif steps \u003c 1 {\n\t\tif jitter \u003e 0 {\n\t\t\treturn Jitter(duration, jitter), duration, 0\n\t\t}\n\t\treturn duration, duration, 0\n\t}\n\tsteps--\n\n\t// calculate the next step's interval\n\tif factor != 0 {\n\t\tnext = time.Duration(float64(duration) * factor)\n\t\tif cap \u003e 0 \u0026\u0026 next \u003e cap {\n\t\t\tnext = cap\n\t\t\tsteps = 0\n\t\t}\n\t} else {\n\t\tnext = duration\n\t}\n\n\t// add jitter for this step\n\tif jitter \u003e 0 {\n\t\tduration = Jitter(duration, jitter)\n\t}\n\n\treturn duration, next, steps\n\n}","line":{"from":97,"to":126}} {"id":100016253,"name":"DelayWithReset","signature":"func (b Backoff) DelayWithReset(c clock.Clock, resetInterval time.Duration) DelayFunc","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/backoff.go","code":"// DelayWithReset returns a DelayFunc that will return the appropriate next interval to\n// wait. Every resetInterval the backoff parameters are reset to their initial state.\n// This method is safe to invoke from multiple goroutines, but all calls will advance\n// the backoff state when Factor is set. If Factor is zero, this method is the same as\n// invoking b.DelayFunc() since Steps has no impact without Factor. If resetInterval is\n// zero no backoff will be performed as the same calling DelayFunc with a zero factor\n// and steps.\nfunc (b Backoff) DelayWithReset(c clock.Clock, resetInterval time.Duration) DelayFunc {\n\tif b.Factor \u003c= 0 {\n\t\treturn b.DelayFunc()\n\t}\n\tif resetInterval \u003c= 0 {\n\t\tb.Steps = 0\n\t\tb.Factor = 0\n\t\treturn b.DelayFunc()\n\t}\n\treturn (\u0026backoffManager{\n\t\tbackoff: b,\n\t\tinitialBackoff: b,\n\t\tresetInterval: resetInterval,\n\n\t\tclock: c,\n\t\tlastStart: c.Now(),\n\t\ttimer: nil,\n\t}).Step\n}","line":{"from":128,"to":153}} {"id":100016254,"name":"Until","signature":"func Until(f func(), period time.Duration, stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/backoff.go","code":"// Until loops until stop channel is closed, running f every period.\n//\n// Until is syntactic sugar on top of JitterUntil with zero jitter factor and\n// with sliding = true (which means the timer for period starts after the f\n// completes).\nfunc Until(f func(), period time.Duration, stopCh \u003c-chan struct{}) {\n\tJitterUntil(f, period, 0.0, true, stopCh)\n}","line":{"from":155,"to":162}} {"id":100016255,"name":"UntilWithContext","signature":"func UntilWithContext(ctx context.Context, f func(context.Context), period time.Duration)","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/backoff.go","code":"// UntilWithContext loops until context is done, running f every period.\n//\n// UntilWithContext is syntactic sugar on top of JitterUntilWithContext\n// with zero jitter factor and with sliding = true (which means the timer\n// for period starts after the f completes).\nfunc UntilWithContext(ctx context.Context, f func(context.Context), period time.Duration) {\n\tJitterUntilWithContext(ctx, f, period, 0.0, true)\n}","line":{"from":164,"to":171}} {"id":100016256,"name":"NonSlidingUntil","signature":"func NonSlidingUntil(f func(), period time.Duration, stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/backoff.go","code":"// NonSlidingUntil loops until stop channel is closed, running f every\n// period.\n//\n// NonSlidingUntil is syntactic sugar on top of JitterUntil with zero jitter\n// factor, with sliding = false (meaning the timer for period starts at the same\n// time as the function starts).\nfunc NonSlidingUntil(f func(), period time.Duration, stopCh \u003c-chan struct{}) {\n\tJitterUntil(f, period, 0.0, false, stopCh)\n}","line":{"from":173,"to":181}} {"id":100016257,"name":"NonSlidingUntilWithContext","signature":"func NonSlidingUntilWithContext(ctx context.Context, f func(context.Context), period time.Duration)","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/backoff.go","code":"// NonSlidingUntilWithContext loops until context is done, running f every\n// period.\n//\n// NonSlidingUntilWithContext is syntactic sugar on top of JitterUntilWithContext\n// with zero jitter factor, with sliding = false (meaning the timer for period\n// starts at the same time as the function starts).\nfunc NonSlidingUntilWithContext(ctx context.Context, f func(context.Context), period time.Duration) {\n\tJitterUntilWithContext(ctx, f, period, 0.0, false)\n}","line":{"from":183,"to":191}} {"id":100016258,"name":"JitterUntil","signature":"func JitterUntil(f func(), period time.Duration, jitterFactor float64, sliding bool, stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/backoff.go","code":"// JitterUntil loops until stop channel is closed, running f every period.\n//\n// If jitterFactor is positive, the period is jittered before every run of f.\n// If jitterFactor is not positive, the period is unchanged and not jittered.\n//\n// If sliding is true, the period is computed after f runs. If it is false then\n// period includes the runtime for f.\n//\n// Close stopCh to stop. f may not be invoked if stop channel is already\n// closed. Pass NeverStop to if you don't want it stop.\nfunc JitterUntil(f func(), period time.Duration, jitterFactor float64, sliding bool, stopCh \u003c-chan struct{}) {\n\tBackoffUntil(f, NewJitteredBackoffManager(period, jitterFactor, \u0026clock.RealClock{}), sliding, stopCh)\n}","line":{"from":193,"to":205}} {"id":100016259,"name":"BackoffUntil","signature":"func BackoffUntil(f func(), backoff BackoffManager, sliding bool, stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/backoff.go","code":"// BackoffUntil loops until stop channel is closed, run f every duration given by BackoffManager.\n//\n// If sliding is true, the period is computed after f runs. If it is false then\n// period includes the runtime for f.\nfunc BackoffUntil(f func(), backoff BackoffManager, sliding bool, stopCh \u003c-chan struct{}) {\n\tvar t clock.Timer\n\tfor {\n\t\tselect {\n\t\tcase \u003c-stopCh:\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\n\t\tif !sliding {\n\t\t\tt = backoff.Backoff()\n\t\t}\n\n\t\tfunc() {\n\t\t\tdefer runtime.HandleCrash()\n\t\t\tf()\n\t\t}()\n\n\t\tif sliding {\n\t\t\tt = backoff.Backoff()\n\t\t}\n\n\t\t// NOTE: b/c there is no priority selection in golang\n\t\t// it is possible for this to race, meaning we could\n\t\t// trigger t.C and stopCh, and t.C select falls through.\n\t\t// In order to mitigate we re-check stopCh at the beginning\n\t\t// of every loop to prevent extra executions of f().\n\t\tselect {\n\t\tcase \u003c-stopCh:\n\t\t\tif !t.Stop() {\n\t\t\t\t\u003c-t.C()\n\t\t\t}\n\t\t\treturn\n\t\tcase \u003c-t.C():\n\t\t}\n\t}\n}","line":{"from":207,"to":247}} {"id":100016260,"name":"JitterUntilWithContext","signature":"func JitterUntilWithContext(ctx context.Context, f func(context.Context), period time.Duration, jitterFactor float64, sliding bool)","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/backoff.go","code":"// JitterUntilWithContext loops until context is done, running f every period.\n//\n// If jitterFactor is positive, the period is jittered before every run of f.\n// If jitterFactor is not positive, the period is unchanged and not jittered.\n//\n// If sliding is true, the period is computed after f runs. If it is false then\n// period includes the runtime for f.\n//\n// Cancel context to stop. f may not be invoked if context is already expired.\nfunc JitterUntilWithContext(ctx context.Context, f func(context.Context), period time.Duration, jitterFactor float64, sliding bool) {\n\tJitterUntil(func() { f(ctx) }, period, jitterFactor, sliding, ctx.Done())\n}","line":{"from":249,"to":260}} {"id":100016261,"name":"Step","signature":"func (b *backoffManager) Step() time.Duration","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/backoff.go","code":"// Step returns the expected next duration to wait.\nfunc (b *backoffManager) Step() time.Duration {\n\tb.lock.Lock()\n\tdefer b.lock.Unlock()\n\n\tswitch {\n\tcase b.resetInterval == 0:\n\t\tb.backoff = b.initialBackoff\n\tcase b.clock.Now().Sub(b.lastStart) \u003e b.resetInterval:\n\t\tb.backoff = b.initialBackoff\n\t\tb.lastStart = b.clock.Now()\n\t}\n\treturn b.backoff.Step()\n}","line":{"from":275,"to":288}} {"id":100016262,"name":"Backoff","signature":"func (b *backoffManager) Backoff() clock.Timer","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/backoff.go","code":"// Backoff implements BackoffManager.Backoff, it returns a timer so caller can block on the timer\n// for exponential backoff. The returned timer must be drained before calling Backoff() the second\n// time.\nfunc (b *backoffManager) Backoff() clock.Timer {\n\tb.lock.Lock()\n\tdefer b.lock.Unlock()\n\tif b.timer == nil {\n\t\tb.timer = b.clock.NewTimer(b.Step())\n\t} else {\n\t\tb.timer.Reset(b.Step())\n\t}\n\treturn b.timer\n}","line":{"from":290,"to":302}} {"id":100016263,"name":"Timer","signature":"func (b *backoffManager) Timer() Timer","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/backoff.go","code":"// Timer returns a new Timer instance that shares the clock and the reset behavior with all other\n// timers.\nfunc (b *backoffManager) Timer() Timer {\n\treturn DelayFunc(b.Step).Timer(b.clock)\n}","line":{"from":304,"to":308}} {"id":100016264,"name":"NewExponentialBackoffManager","signature":"func NewExponentialBackoffManager(initBackoff, maxBackoff, resetDuration time.Duration, backoffFactor, jitter float64, c clock.Clock) BackoffManager","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/backoff.go","code":"// NewExponentialBackoffManager returns a manager for managing exponential backoff. Each backoff is jittered and\n// backoff will not exceed the given max. If the backoff is not called within resetDuration, the backoff is reset.\n// This backoff manager is used to reduce load during upstream unhealthiness.\n//\n// Deprecated: Will be removed when the legacy Poll methods are removed. Callers should construct a\n// Backoff struct, use DelayWithReset() to get a DelayFunc that periodically resets itself, and then\n// invoke Timer() when calling wait.BackoffUntil.\n//\n// Instead of:\n//\n//\tbm := wait.NewExponentialBackoffManager(init, max, reset, factor, jitter, clock)\n//\t...\n//\twait.BackoffUntil(..., bm.Backoff, ...)\n//\n// Use:\n//\n//\tdelayFn := wait.Backoff{\n//\t Duration: init,\n//\t Cap: max,\n//\t Steps: int(math.Ceil(float64(max) / float64(init))), // now a required argument\n//\t Factor: factor,\n//\t Jitter: jitter,\n//\t}.DelayWithReset(reset, clock)\n//\twait.BackoffUntil(..., delayFn.Timer(), ...)\nfunc NewExponentialBackoffManager(initBackoff, maxBackoff, resetDuration time.Duration, backoffFactor, jitter float64, c clock.Clock) BackoffManager {\n\treturn \u0026exponentialBackoffManagerImpl{\n\t\tbackoff: \u0026Backoff{\n\t\t\tDuration: initBackoff,\n\t\t\tFactor: backoffFactor,\n\t\t\tJitter: jitter,\n\n\t\t\t// the current impl of wait.Backoff returns Backoff.Duration once steps are used up, which is not\n\t\t\t// what we ideally need here, we set it to max int and assume we will never use up the steps\n\t\t\tSteps: math.MaxInt32,\n\t\t\tCap: maxBackoff,\n\t\t},\n\t\tbackoffTimer: nil,\n\t\tinitialBackoff: initBackoff,\n\t\tlastBackoffStart: c.Now(),\n\t\tbackoffResetDuration: resetDuration,\n\t\tclock: c,\n\t}\n}","line":{"from":330,"to":372}} {"id":100016265,"name":"getNextBackoff","signature":"func (b *exponentialBackoffManagerImpl) getNextBackoff() time.Duration","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/backoff.go","code":"func (b *exponentialBackoffManagerImpl) getNextBackoff() time.Duration {\n\tif b.clock.Now().Sub(b.lastBackoffStart) \u003e b.backoffResetDuration {\n\t\tb.backoff.Steps = math.MaxInt32\n\t\tb.backoff.Duration = b.initialBackoff\n\t}\n\tb.lastBackoffStart = b.clock.Now()\n\treturn b.backoff.Step()\n}","line":{"from":374,"to":381}} {"id":100016266,"name":"Backoff","signature":"func (b *exponentialBackoffManagerImpl) Backoff() clock.Timer","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/backoff.go","code":"// Backoff implements BackoffManager.Backoff, it returns a timer so caller can block on the timer for exponential backoff.\n// The returned timer must be drained before calling Backoff() the second time\nfunc (b *exponentialBackoffManagerImpl) Backoff() clock.Timer {\n\tif b.backoffTimer == nil {\n\t\tb.backoffTimer = b.clock.NewTimer(b.getNextBackoff())\n\t} else {\n\t\tb.backoffTimer.Reset(b.getNextBackoff())\n\t}\n\treturn b.backoffTimer\n}","line":{"from":383,"to":392}} {"id":100016267,"name":"NewJitteredBackoffManager","signature":"func NewJitteredBackoffManager(duration time.Duration, jitter float64, c clock.Clock) BackoffManager","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/backoff.go","code":"// NewJitteredBackoffManager returns a BackoffManager that backoffs with given duration plus given jitter. If the jitter\n// is negative, backoff will not be jittered.\n//\n// Deprecated: Will be removed when the legacy Poll methods are removed. Callers should construct a\n// Backoff struct and invoke Timer() when calling wait.BackoffUntil.\n//\n// Instead of:\n//\n//\tbm := wait.NewJitteredBackoffManager(duration, jitter, clock)\n//\t...\n//\twait.BackoffUntil(..., bm.Backoff, ...)\n//\n// Use:\n//\n//\twait.BackoffUntil(..., wait.Backoff{Duration: duration, Jitter: jitter}.Timer(), ...)\nfunc NewJitteredBackoffManager(duration time.Duration, jitter float64, c clock.Clock) BackoffManager {\n\treturn \u0026jitteredBackoffManagerImpl{\n\t\tclock: c,\n\t\tduration: duration,\n\t\tjitter: jitter,\n\t\tbackoffTimer: nil,\n\t}\n}","line":{"from":402,"to":424}} {"id":100016268,"name":"getNextBackoff","signature":"func (j *jitteredBackoffManagerImpl) getNextBackoff() time.Duration","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/backoff.go","code":"func (j *jitteredBackoffManagerImpl) getNextBackoff() time.Duration {\n\tjitteredPeriod := j.duration\n\tif j.jitter \u003e 0.0 {\n\t\tjitteredPeriod = Jitter(j.duration, j.jitter)\n\t}\n\treturn jitteredPeriod\n}","line":{"from":426,"to":432}} {"id":100016269,"name":"Backoff","signature":"func (j *jitteredBackoffManagerImpl) Backoff() clock.Timer","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/backoff.go","code":"// Backoff implements BackoffManager.Backoff, it returns a timer so caller can block on the timer for jittered backoff.\n// The returned timer must be drained before calling Backoff() the second time\nfunc (j *jitteredBackoffManagerImpl) Backoff() clock.Timer {\n\tbackoff := j.getNextBackoff()\n\tif j.backoffTimer == nil {\n\t\tj.backoffTimer = j.clock.NewTimer(backoff)\n\t} else {\n\t\tj.backoffTimer.Reset(backoff)\n\t}\n\treturn j.backoffTimer\n}","line":{"from":434,"to":444}} {"id":100016270,"name":"ExponentialBackoff","signature":"func ExponentialBackoff(backoff Backoff, condition ConditionFunc) error","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/backoff.go","code":"// ExponentialBackoff repeats a condition check with exponential backoff.\n//\n// It repeatedly checks the condition and then sleeps, using `backoff.Step()`\n// to determine the length of the sleep and adjust Duration and Steps.\n// Stops and returns as soon as:\n// 1. the condition check returns true or an error,\n// 2. `backoff.Steps` checks of the condition have been done, or\n// 3. a sleep truncated by the cap on duration has been completed.\n// In case (1) the returned error is what the condition function returned.\n// In all other cases, ErrWaitTimeout is returned.\n//\n// Since backoffs are often subject to cancellation, we recommend using\n// ExponentialBackoffWithContext and passing a context to the method.\nfunc ExponentialBackoff(backoff Backoff, condition ConditionFunc) error {\n\tfor backoff.Steps \u003e 0 {\n\t\tif ok, err := runConditionWithCrashProtection(condition); err != nil || ok {\n\t\t\treturn err\n\t\t}\n\t\tif backoff.Steps == 1 {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(backoff.Step())\n\t}\n\treturn ErrWaitTimeout\n}","line":{"from":446,"to":470}} {"id":100016271,"name":"ExponentialBackoffWithContext","signature":"func ExponentialBackoffWithContext(ctx context.Context, backoff Backoff, condition ConditionWithContextFunc) error","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/backoff.go","code":"// ExponentialBackoffWithContext repeats a condition check with exponential backoff.\n// It immediately returns an error if the condition returns an error, the context is cancelled\n// or hits the deadline, or if the maximum attempts defined in backoff is exceeded (ErrWaitTimeout).\n// If an error is returned by the condition the backoff stops immediately. The condition will\n// never be invoked more than backoff.Steps times.\nfunc ExponentialBackoffWithContext(ctx context.Context, backoff Backoff, condition ConditionWithContextFunc) error {\n\tfor backoff.Steps \u003e 0 {\n\t\tselect {\n\t\tcase \u003c-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tdefault:\n\t\t}\n\n\t\tif ok, err := runConditionWithCrashProtectionWithContext(ctx, condition); err != nil || ok {\n\t\t\treturn err\n\t\t}\n\n\t\tif backoff.Steps == 1 {\n\t\t\tbreak\n\t\t}\n\n\t\twaitBeforeRetry := backoff.Step()\n\t\tselect {\n\t\tcase \u003c-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tcase \u003c-time.After(waitBeforeRetry):\n\t\t}\n\t}\n\n\treturn ErrWaitTimeout\n}","line":{"from":472,"to":502}} {"id":100016272,"name":"Timer","signature":"func (fn DelayFunc) Timer(c clock.Clock) Timer","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/delay.go","code":"// Timer takes an arbitrary delay function and returns a timer that can handle arbitrary interval changes.\n// Use Backoff{...}.Timer() for simple delays and more efficient timers.\nfunc (fn DelayFunc) Timer(c clock.Clock) Timer {\n\treturn \u0026variableTimer{fn: fn, new: c.NewTimer}\n}","line":{"from":30,"to":34}} {"id":100016273,"name":"Until","signature":"func (fn DelayFunc) Until(ctx context.Context, immediate, sliding bool, condition ConditionWithContextFunc) error","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/delay.go","code":"// Until takes an arbitrary delay function and runs until cancelled or the condition indicates exit. This\n// offers all of the functionality of the methods in this package.\nfunc (fn DelayFunc) Until(ctx context.Context, immediate, sliding bool, condition ConditionWithContextFunc) error {\n\treturn loopConditionUntilContext(ctx, \u0026variableTimer{fn: fn, new: internalClock.NewTimer}, immediate, sliding, condition)\n}","line":{"from":36,"to":40}} {"id":100016274,"name":"Concurrent","signature":"func (fn DelayFunc) Concurrent() DelayFunc","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/delay.go","code":"// Concurrent returns a version of this DelayFunc that is safe for use by multiple goroutines that\n// wish to share a single delay timer.\nfunc (fn DelayFunc) Concurrent() DelayFunc {\n\tvar lock sync.Mutex\n\treturn func() time.Duration {\n\t\tlock.Lock()\n\t\tdefer lock.Unlock()\n\t\treturn fn()\n\t}\n}","line":{"from":42,"to":51}} {"id":100016275,"name":"Interrupted","signature":"func Interrupted(err error) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/error.go","code":"// Interrupted returns true if the error indicates a Poll, ExponentialBackoff, or\n// Until loop exited for any reason besides the condition returning true or an\n// error. A loop is considered interrupted if the calling context is cancelled,\n// the context reaches its deadline, or a backoff reaches its maximum allowed\n// steps.\n//\n// Callers should use this method instead of comparing the error value directly to\n// ErrWaitTimeout, as methods that cancel a context may not return that error.\n//\n// Instead of:\n//\n//\terr := wait.Poll(...)\n//\tif err == wait.ErrWaitTimeout {\n//\t log.Infof(\"Wait for operation exceeded\")\n//\t} else ...\n//\n// Use:\n//\n//\terr := wait.Poll(...)\n//\tif wait.Interrupted(err) {\n//\t log.Infof(\"Wait for operation exceeded\")\n//\t} else ...\nfunc Interrupted(err error) bool {\n\tswitch {\n\tcase errors.Is(err, errWaitTimeout),\n\t\terrors.Is(err, context.Canceled),\n\t\terrors.Is(err, context.DeadlineExceeded):\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":30,"to":61}} {"id":100016276,"name":"ErrorInterrupted","signature":"func ErrorInterrupted(cause error) error","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/error.go","code":"// ErrorInterrupted returns an error that indicates the wait was ended\n// early for a given reason. If no cause is provided a generic error\n// will be used but callers are encouraged to provide a real cause for\n// clarity in debugging.\nfunc ErrorInterrupted(cause error) error {\n\tswitch cause.(type) {\n\tcase errInterrupted:\n\t\t// no need to wrap twice since errInterrupted is only needed\n\t\t// once in a chain\n\t\treturn cause\n\tdefault:\n\t\treturn errInterrupted{cause}\n\t}\n}","line":{"from":68,"to":81}} {"id":100016277,"name":"Unwrap","signature":"func (e errInterrupted) Unwrap() error { return e.cause }","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/error.go","code":"func (e errInterrupted) Unwrap() error { return e.cause }","line":{"from":88,"to":88}} {"id":100016278,"name":"Is","signature":"func (e errInterrupted) Is(target error) bool { return target == errWaitTimeout }","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/error.go","code":"func (e errInterrupted) Is(target error) bool { return target == errWaitTimeout }","line":{"from":89,"to":89}} {"id":100016279,"name":"Error","signature":"func (e errInterrupted) Error() string","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/error.go","code":"func (e errInterrupted) Error() string {\n\tif e.cause == nil {\n\t\t// returns the same error message as historical behavior\n\t\treturn \"timed out waiting for the condition\"\n\t}\n\treturn e.cause.Error()\n}","line":{"from":90,"to":96}} {"id":100016280,"name":"loopConditionUntilContext","signature":"func loopConditionUntilContext(ctx context.Context, t Timer, immediate, sliding bool, condition ConditionWithContextFunc) error","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/loop.go","code":"// loopConditionUntilContext executes the provided condition at intervals defined by\n// the provided timer until the provided context is cancelled, the condition returns\n// true, or the condition returns an error. If sliding is true, the period is computed\n// after condition runs. If it is false then period includes the runtime for condition.\n// If immediate is false the first delay happens before any call to condition, if\n// immediate is true the condition will be invoked before waiting and guarantees that\n// the condition is invoked at least once, regardless of whether the context has been\n// cancelled. The returned error is the error returned by the last condition or the\n// context error if the context was terminated.\n//\n// This is the common loop construct for all polling in the wait package.\nfunc loopConditionUntilContext(ctx context.Context, t Timer, immediate, sliding bool, condition ConditionWithContextFunc) error {\n\tdefer t.Stop()\n\n\tvar timeCh \u003c-chan time.Time\n\tdoneCh := ctx.Done()\n\n\t// if immediate is true the condition is\n\t// guaranteed to be executed at least once,\n\t// if we haven't requested immediate execution, delay once\n\tif immediate {\n\t\tif ok, err := func() (bool, error) {\n\t\t\tdefer runtime.HandleCrash()\n\t\t\treturn condition(ctx)\n\t\t}(); err != nil || ok {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\ttimeCh = t.C()\n\t\tselect {\n\t\tcase \u003c-doneCh:\n\t\t\treturn ctx.Err()\n\t\tcase \u003c-timeCh:\n\t\t}\n\t}\n\n\tfor {\n\t\t// checking ctx.Err() is slightly faster than checking a select\n\t\tif err := ctx.Err(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif !sliding {\n\t\t\tt.Next()\n\t\t}\n\t\tif ok, err := func() (bool, error) {\n\t\t\tdefer runtime.HandleCrash()\n\t\t\treturn condition(ctx)\n\t\t}(); err != nil || ok {\n\t\t\treturn err\n\t\t}\n\t\tif sliding {\n\t\t\tt.Next()\n\t\t}\n\n\t\tif timeCh == nil {\n\t\t\ttimeCh = t.C()\n\t\t}\n\n\t\t// NOTE: b/c there is no priority selection in golang\n\t\t// it is possible for this to race, meaning we could\n\t\t// trigger t.C and doneCh, and t.C select falls through.\n\t\t// In order to mitigate we re-check doneCh at the beginning\n\t\t// of every loop to guarantee at-most one extra execution\n\t\t// of condition.\n\t\tselect {\n\t\tcase \u003c-doneCh:\n\t\t\treturn ctx.Err()\n\t\tcase \u003c-timeCh:\n\t\t}\n\t}\n}","line":{"from":26,"to":97}} {"id":100016281,"name":"PollUntilContextCancel","signature":"func PollUntilContextCancel(ctx context.Context, interval time.Duration, immediate bool, condition ConditionWithContextFunc) error","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/poll.go","code":"// PollUntilContextCancel tries a condition func until it returns true, an error, or the context\n// is cancelled or hits a deadline. condition will be invoked after the first interval if the\n// context is not cancelled first. The returned error will be from ctx.Err(), the condition's\n// err return value, or nil. If invoking condition takes longer than interval the next condition\n// will be invoked immediately. When using very short intervals, condition may be invoked multiple\n// times before a context cancellation is detected. If immediate is true, condition will be\n// invoked before waiting and guarantees that condition is invoked at least once, regardless of\n// whether the context has been cancelled.\nfunc PollUntilContextCancel(ctx context.Context, interval time.Duration, immediate bool, condition ConditionWithContextFunc) error {\n\treturn loopConditionUntilContext(ctx, Backoff{Duration: interval}.Timer(), immediate, false, condition)\n}","line":{"from":24,"to":34}} {"id":100016282,"name":"PollUntilContextTimeout","signature":"func PollUntilContextTimeout(ctx context.Context, interval, timeout time.Duration, immediate bool, condition ConditionWithContextFunc) error","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/poll.go","code":"// PollUntilContextTimeout will terminate polling after timeout duration by setting a context\n// timeout. This is provided as a convenience function for callers not currently executing under\n// a deadline and is equivalent to:\n//\n//\tdeadlineCtx, deadlineCancel := context.WithTimeout(ctx, timeout)\n//\terr := PollUntilContextCancel(ctx, interval, immediate, condition)\n//\n// The deadline context will be cancelled if the Poll succeeds before the timeout, simplifying\n// inline usage. All other behavior is identical to PollWithContextTimeout.\nfunc PollUntilContextTimeout(ctx context.Context, interval, timeout time.Duration, immediate bool, condition ConditionWithContextFunc) error {\n\tdeadlineCtx, deadlineCancel := context.WithTimeout(ctx, timeout)\n\tdefer deadlineCancel()\n\treturn loopConditionUntilContext(deadlineCtx, Backoff{Duration: interval}.Timer(), immediate, false, condition)\n}","line":{"from":36,"to":49}} {"id":100016283,"name":"Poll","signature":"func Poll(interval, timeout time.Duration, condition ConditionFunc) error","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/poll.go","code":"// Poll tries a condition func until it returns true, an error, or the timeout\n// is reached.\n//\n// Poll always waits the interval before the run of 'condition'.\n// 'condition' will always be invoked at least once.\n//\n// Some intervals may be missed if the condition takes too long or the time\n// window is too short.\n//\n// If you want to Poll something forever, see PollInfinite.\n//\n// Deprecated: This method does not return errors from context, use PollWithContextTimeout.\n// Note that the new method will no longer return ErrWaitTimeout and instead return errors\n// defined by the context package. Will be removed in a future release.\nfunc Poll(interval, timeout time.Duration, condition ConditionFunc) error {\n\treturn PollWithContext(context.Background(), interval, timeout, condition.WithContext())\n}","line":{"from":51,"to":67}} {"id":100016284,"name":"PollWithContext","signature":"func PollWithContext(ctx context.Context, interval, timeout time.Duration, condition ConditionWithContextFunc) error","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/poll.go","code":"// PollWithContext tries a condition func until it returns true, an error,\n// or when the context expires or the timeout is reached, whichever\n// happens first.\n//\n// PollWithContext always waits the interval before the run of 'condition'.\n// 'condition' will always be invoked at least once.\n//\n// Some intervals may be missed if the condition takes too long or the time\n// window is too short.\n//\n// If you want to Poll something forever, see PollInfinite.\n//\n// Deprecated: This method does not return errors from context, use PollWithContextTimeout.\n// Note that the new method will no longer return ErrWaitTimeout and instead return errors\n// defined by the context package. Will be removed in a future release.\nfunc PollWithContext(ctx context.Context, interval, timeout time.Duration, condition ConditionWithContextFunc) error {\n\treturn poll(ctx, false, poller(interval, timeout), condition)\n}","line":{"from":69,"to":86}} {"id":100016285,"name":"PollUntil","signature":"func PollUntil(interval time.Duration, condition ConditionFunc, stopCh \u003c-chan struct{}) error","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/poll.go","code":"// PollUntil tries a condition func until it returns true, an error or stopCh is\n// closed.\n//\n// PollUntil always waits interval before the first run of 'condition'.\n// 'condition' will always be invoked at least once.\n//\n// Deprecated: This method does not return errors from context, use PollWithContextCancel.\n// Note that the new method will no longer return ErrWaitTimeout and instead return errors\n// defined by the context package. Will be removed in a future release.\nfunc PollUntil(interval time.Duration, condition ConditionFunc, stopCh \u003c-chan struct{}) error {\n\treturn PollUntilWithContext(ContextForChannel(stopCh), interval, condition.WithContext())\n}","line":{"from":88,"to":99}} {"id":100016286,"name":"PollUntilWithContext","signature":"func PollUntilWithContext(ctx context.Context, interval time.Duration, condition ConditionWithContextFunc) error","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/poll.go","code":"// PollUntilWithContext tries a condition func until it returns true,\n// an error or the specified context is cancelled or expired.\n//\n// PollUntilWithContext always waits interval before the first run of 'condition'.\n// 'condition' will always be invoked at least once.\n//\n// Deprecated: This method does not return errors from context, use PollWithContextCancel.\n// Note that the new method will no longer return ErrWaitTimeout and instead return errors\n// defined by the context package. Will be removed in a future release.\nfunc PollUntilWithContext(ctx context.Context, interval time.Duration, condition ConditionWithContextFunc) error {\n\treturn poll(ctx, false, poller(interval, 0), condition)\n}","line":{"from":101,"to":112}} {"id":100016287,"name":"PollInfinite","signature":"func PollInfinite(interval time.Duration, condition ConditionFunc) error","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/poll.go","code":"// PollInfinite tries a condition func until it returns true or an error\n//\n// PollInfinite always waits the interval before the run of 'condition'.\n//\n// Some intervals may be missed if the condition takes too long or the time\n// window is too short.\n//\n// Deprecated: This method does not return errors from context, use PollWithContextCancel.\n// Note that the new method will no longer return ErrWaitTimeout and instead return errors\n// defined by the context package. Will be removed in a future release.\nfunc PollInfinite(interval time.Duration, condition ConditionFunc) error {\n\treturn PollInfiniteWithContext(context.Background(), interval, condition.WithContext())\n}","line":{"from":114,"to":126}} {"id":100016288,"name":"PollInfiniteWithContext","signature":"func PollInfiniteWithContext(ctx context.Context, interval time.Duration, condition ConditionWithContextFunc) error","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/poll.go","code":"// PollInfiniteWithContext tries a condition func until it returns true or an error\n//\n// PollInfiniteWithContext always waits the interval before the run of 'condition'.\n//\n// Some intervals may be missed if the condition takes too long or the time\n// window is too short.\n//\n// Deprecated: This method does not return errors from context, use PollWithContextCancel.\n// Note that the new method will no longer return ErrWaitTimeout and instead return errors\n// defined by the context package. Will be removed in a future release.\nfunc PollInfiniteWithContext(ctx context.Context, interval time.Duration, condition ConditionWithContextFunc) error {\n\treturn poll(ctx, false, poller(interval, 0), condition)\n}","line":{"from":128,"to":140}} {"id":100016289,"name":"PollImmediate","signature":"func PollImmediate(interval, timeout time.Duration, condition ConditionFunc) error","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/poll.go","code":"// PollImmediate tries a condition func until it returns true, an error, or the timeout\n// is reached.\n//\n// PollImmediate always checks 'condition' before waiting for the interval. 'condition'\n// will always be invoked at least once.\n//\n// Some intervals may be missed if the condition takes too long or the time\n// window is too short.\n//\n// If you want to immediately Poll something forever, see PollImmediateInfinite.\n//\n// Deprecated: This method does not return errors from context, use PollWithContextTimeout.\n// Note that the new method will no longer return ErrWaitTimeout and instead return errors\n// defined by the context package. Will be removed in a future release.\nfunc PollImmediate(interval, timeout time.Duration, condition ConditionFunc) error {\n\treturn PollImmediateWithContext(context.Background(), interval, timeout, condition.WithContext())\n}","line":{"from":142,"to":158}} {"id":100016290,"name":"PollImmediateWithContext","signature":"func PollImmediateWithContext(ctx context.Context, interval, timeout time.Duration, condition ConditionWithContextFunc) error","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/poll.go","code":"// PollImmediateWithContext tries a condition func until it returns true, an error,\n// or the timeout is reached or the specified context expires, whichever happens first.\n//\n// PollImmediateWithContext always checks 'condition' before waiting for the interval.\n// 'condition' will always be invoked at least once.\n//\n// Some intervals may be missed if the condition takes too long or the time\n// window is too short.\n//\n// If you want to immediately Poll something forever, see PollImmediateInfinite.\n//\n// Deprecated: This method does not return errors from context, use PollWithContextTimeout.\n// Note that the new method will no longer return ErrWaitTimeout and instead return errors\n// defined by the context package. Will be removed in a future release.\nfunc PollImmediateWithContext(ctx context.Context, interval, timeout time.Duration, condition ConditionWithContextFunc) error {\n\treturn poll(ctx, true, poller(interval, timeout), condition)\n}","line":{"from":160,"to":176}} {"id":100016291,"name":"PollImmediateUntil","signature":"func PollImmediateUntil(interval time.Duration, condition ConditionFunc, stopCh \u003c-chan struct{}) error","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/poll.go","code":"// PollImmediateUntil tries a condition func until it returns true, an error or stopCh is closed.\n//\n// PollImmediateUntil runs the 'condition' before waiting for the interval.\n// 'condition' will always be invoked at least once.\n//\n// Deprecated: This method does not return errors from context, use PollWithContextCancel.\n// Note that the new method will no longer return ErrWaitTimeout and instead return errors\n// defined by the context package. Will be removed in a future release.\nfunc PollImmediateUntil(interval time.Duration, condition ConditionFunc, stopCh \u003c-chan struct{}) error {\n\treturn PollImmediateUntilWithContext(ContextForChannel(stopCh), interval, condition.WithContext())\n}","line":{"from":178,"to":188}} {"id":100016292,"name":"PollImmediateUntilWithContext","signature":"func PollImmediateUntilWithContext(ctx context.Context, interval time.Duration, condition ConditionWithContextFunc) error","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/poll.go","code":"// PollImmediateUntilWithContext tries a condition func until it returns true,\n// an error or the specified context is cancelled or expired.\n//\n// PollImmediateUntilWithContext runs the 'condition' before waiting for the interval.\n// 'condition' will always be invoked at least once.\n//\n// Deprecated: This method does not return errors from context, use PollWithContextCancel.\n// Note that the new method will no longer return ErrWaitTimeout and instead return errors\n// defined by the context package. Will be removed in a future release.\nfunc PollImmediateUntilWithContext(ctx context.Context, interval time.Duration, condition ConditionWithContextFunc) error {\n\treturn poll(ctx, true, poller(interval, 0), condition)\n}","line":{"from":190,"to":201}} {"id":100016293,"name":"PollImmediateInfinite","signature":"func PollImmediateInfinite(interval time.Duration, condition ConditionFunc) error","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/poll.go","code":"// PollImmediateInfinite tries a condition func until it returns true or an error\n//\n// PollImmediateInfinite runs the 'condition' before waiting for the interval.\n//\n// Some intervals may be missed if the condition takes too long or the time\n// window is too short.\n//\n// Deprecated: This method does not return errors from context, use PollWithContextCancel.\n// Note that the new method will no longer return ErrWaitTimeout and instead return errors\n// defined by the context package. Will be removed in a future release.\nfunc PollImmediateInfinite(interval time.Duration, condition ConditionFunc) error {\n\treturn PollImmediateInfiniteWithContext(context.Background(), interval, condition.WithContext())\n}","line":{"from":203,"to":215}} {"id":100016294,"name":"PollImmediateInfiniteWithContext","signature":"func PollImmediateInfiniteWithContext(ctx context.Context, interval time.Duration, condition ConditionWithContextFunc) error","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/poll.go","code":"// PollImmediateInfiniteWithContext tries a condition func until it returns true\n// or an error or the specified context gets cancelled or expired.\n//\n// PollImmediateInfiniteWithContext runs the 'condition' before waiting for the interval.\n//\n// Some intervals may be missed if the condition takes too long or the time\n// window is too short.\n//\n// Deprecated: This method does not return errors from context, use PollWithContextCancel.\n// Note that the new method will no longer return ErrWaitTimeout and instead return errors\n// defined by the context package. Will be removed in a future release.\nfunc PollImmediateInfiniteWithContext(ctx context.Context, interval time.Duration, condition ConditionWithContextFunc) error {\n\treturn poll(ctx, true, poller(interval, 0), condition)\n}","line":{"from":217,"to":230}} {"id":100016295,"name":"poll","signature":"func poll(ctx context.Context, immediate bool, wait waitWithContextFunc, condition ConditionWithContextFunc) error","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/poll.go","code":"// Internally used, each of the public 'Poll*' function defined in this\n// package should invoke this internal function with appropriate parameters.\n// ctx: the context specified by the caller, for infinite polling pass\n// a context that never gets cancelled or expired.\n// immediate: if true, the 'condition' will be invoked before waiting for the interval,\n// in this case 'condition' will always be invoked at least once.\n// wait: user specified WaitFunc function that controls at what interval the condition\n// function should be invoked periodically and whether it is bound by a timeout.\n// condition: user specified ConditionWithContextFunc function.\n//\n// Deprecated: will be removed in favor of loopConditionUntilContext.\nfunc poll(ctx context.Context, immediate bool, wait waitWithContextFunc, condition ConditionWithContextFunc) error {\n\tif immediate {\n\t\tdone, err := runConditionWithCrashProtectionWithContext(ctx, condition)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif done {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tselect {\n\tcase \u003c-ctx.Done():\n\t\t// returning ctx.Err() will break backward compatibility, use new PollUntilContext*\n\t\t// methods instead\n\t\treturn ErrWaitTimeout\n\tdefault:\n\t\treturn waitForWithContext(ctx, wait, condition)\n\t}\n}","line":{"from":232,"to":262}} {"id":100016296,"name":"poller","signature":"func poller(interval, timeout time.Duration) waitWithContextFunc","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/poll.go","code":"// poller returns a WaitFunc that will send to the channel every interval until\n// timeout has elapsed and then closes the channel.\n//\n// Over very short intervals you may receive no ticks before the channel is\n// closed. A timeout of 0 is interpreted as an infinity, and in such a case\n// it would be the caller's responsibility to close the done channel.\n// Failure to do so would result in a leaked goroutine.\n//\n// Output ticks are not buffered. If the channel is not ready to receive an\n// item, the tick is skipped.\n//\n// Deprecated: Will be removed in a future release.\nfunc poller(interval, timeout time.Duration) waitWithContextFunc {\n\treturn waitWithContextFunc(func(ctx context.Context) \u003c-chan struct{} {\n\t\tch := make(chan struct{})\n\n\t\tgo func() {\n\t\t\tdefer close(ch)\n\n\t\t\ttick := time.NewTicker(interval)\n\t\t\tdefer tick.Stop()\n\n\t\t\tvar after \u003c-chan time.Time\n\t\t\tif timeout != 0 {\n\t\t\t\t// time.After is more convenient, but it\n\t\t\t\t// potentially leaves timers around much longer\n\t\t\t\t// than necessary if we exit early.\n\t\t\t\ttimer := time.NewTimer(timeout)\n\t\t\t\tafter = timer.C\n\t\t\t\tdefer timer.Stop()\n\t\t\t}\n\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase \u003c-tick.C:\n\t\t\t\t\t// If the consumer isn't ready for this signal drop it and\n\t\t\t\t\t// check the other channels.\n\t\t\t\t\tselect {\n\t\t\t\t\tcase ch \u003c- struct{}{}:\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\tcase \u003c-after:\n\t\t\t\t\treturn\n\t\t\t\tcase \u003c-ctx.Done():\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\treturn ch\n\t})\n}","line":{"from":264,"to":315}} {"id":100016297,"name":"newNoopTimer","signature":"func newNoopTimer() noopTimer","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/timer.go","code":"// newNoopTimer creates a timer with a unique channel to avoid contention\n// for the channel's lock across multiple unrelated timers.\nfunc newNoopTimer() noopTimer {\n\tch := make(chan time.Time)\n\tclose(ch)\n\treturn noopTimer{closedCh: ch}\n}","line":{"from":48,"to":54}} {"id":100016298,"name":"C","signature":"func (t noopTimer) C() \u003c-chan time.Time","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/timer.go","code":"func (t noopTimer) C() \u003c-chan time.Time {\n\treturn t.closedCh\n}","line":{"from":56,"to":58}} {"id":100016299,"name":"Next","signature":"func (noopTimer) Next() {}","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/timer.go","code":"func (noopTimer) Next() {}","line":{"from":59,"to":59}} {"id":100016300,"name":"Stop","signature":"func (noopTimer) Stop() {}","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/timer.go","code":"func (noopTimer) Stop() {}","line":{"from":60,"to":60}} {"id":100016301,"name":"C","signature":"func (t *variableTimer) C() \u003c-chan time.Time","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/timer.go","code":"func (t *variableTimer) C() \u003c-chan time.Time {\n\tif t.t == nil {\n\t\td := t.fn()\n\t\tt.t = t.new(d)\n\t}\n\treturn t.t.C()\n}","line":{"from":68,"to":74}} {"id":100016302,"name":"Next","signature":"func (t *variableTimer) Next()","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/timer.go","code":"func (t *variableTimer) Next() {\n\tif t.t == nil {\n\t\treturn\n\t}\n\td := t.fn()\n\tt.t.Reset(d)\n}","line":{"from":75,"to":81}} {"id":100016303,"name":"Stop","signature":"func (t *variableTimer) Stop()","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/timer.go","code":"func (t *variableTimer) Stop() {\n\tif t.t == nil {\n\t\treturn\n\t}\n\tt.t.Stop()\n\tt.t = nil\n}","line":{"from":82,"to":88}} {"id":100016304,"name":"C","signature":"func (t *fixedTimer) C() \u003c-chan time.Time","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/timer.go","code":"func (t *fixedTimer) C() \u003c-chan time.Time {\n\tif t.t == nil {\n\t\tt.t = t.new(t.interval)\n\t}\n\treturn t.t.C()\n}","line":{"from":96,"to":101}} {"id":100016305,"name":"Next","signature":"func (t *fixedTimer) Next()","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/timer.go","code":"func (t *fixedTimer) Next() {\n\t// no-op for fixed timers\n}","line":{"from":102,"to":104}} {"id":100016306,"name":"Stop","signature":"func (t *fixedTimer) Stop()","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/timer.go","code":"func (t *fixedTimer) Stop() {\n\tif t.t == nil {\n\t\treturn\n\t}\n\tt.t.Stop()\n\tt.t = nil\n}","line":{"from":105,"to":111}} {"id":100016307,"name":"Wait","signature":"func (g *Group) Wait()","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/wait.go","code":"func (g *Group) Wait() {\n\tg.wg.Wait()\n}","line":{"from":47,"to":49}} {"id":100016308,"name":"StartWithChannel","signature":"func (g *Group) StartWithChannel(stopCh \u003c-chan struct{}, f func(stopCh \u003c-chan struct{}))","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/wait.go","code":"// StartWithChannel starts f in a new goroutine in the group.\n// stopCh is passed to f as an argument. f should stop when stopCh is available.\nfunc (g *Group) StartWithChannel(stopCh \u003c-chan struct{}, f func(stopCh \u003c-chan struct{})) {\n\tg.Start(func() {\n\t\tf(stopCh)\n\t})\n}","line":{"from":51,"to":57}} {"id":100016309,"name":"StartWithContext","signature":"func (g *Group) StartWithContext(ctx context.Context, f func(context.Context))","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/wait.go","code":"// StartWithContext starts f in a new goroutine in the group.\n// ctx is passed to f as an argument. f should stop when ctx.Done() is available.\nfunc (g *Group) StartWithContext(ctx context.Context, f func(context.Context)) {\n\tg.Start(func() {\n\t\tf(ctx)\n\t})\n}","line":{"from":59,"to":65}} {"id":100016310,"name":"Start","signature":"func (g *Group) Start(f func())","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/wait.go","code":"// Start starts f in a new goroutine in the group.\nfunc (g *Group) Start(f func()) {\n\tg.wg.Add(1)\n\tgo func() {\n\t\tdefer g.wg.Done()\n\t\tf()\n\t}()\n}","line":{"from":67,"to":74}} {"id":100016311,"name":"Forever","signature":"func Forever(f func(), period time.Duration)","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/wait.go","code":"// Forever calls f every period for ever.\n//\n// Forever is syntactic sugar on top of Until.\nfunc Forever(f func(), period time.Duration) {\n\tUntil(f, period, NeverStop)\n}","line":{"from":76,"to":81}} {"id":100016312,"name":"Jitter","signature":"func Jitter(duration time.Duration, maxFactor float64) time.Duration","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/wait.go","code":"// Jitter returns a time.Duration between duration and duration + maxFactor *\n// duration.\n//\n// This allows clients to avoid converging on periodic behavior. If maxFactor\n// is 0.0, a suggested default value will be chosen.\nfunc Jitter(duration time.Duration, maxFactor float64) time.Duration {\n\tif maxFactor \u003c= 0.0 {\n\t\tmaxFactor = 1.0\n\t}\n\twait := duration + time.Duration(rand.Float64()*maxFactor*float64(duration))\n\treturn wait\n}","line":{"from":83,"to":94}} {"id":100016313,"name":"WithContext","signature":"func (cf ConditionFunc) WithContext() ConditionWithContextFunc","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/wait.go","code":"// WithContext converts a ConditionFunc into a ConditionWithContextFunc\nfunc (cf ConditionFunc) WithContext() ConditionWithContextFunc {\n\treturn func(context.Context) (done bool, err error) {\n\t\treturn cf()\n\t}\n}","line":{"from":106,"to":111}} {"id":100016314,"name":"ContextForChannel","signature":"func ContextForChannel(parentCh \u003c-chan struct{}) context.Context","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/wait.go","code":"// ContextForChannel provides a context that will be treated as cancelled\n// when the provided parentCh is closed. The implementation returns\n// context.Canceled for Err() if and only if the parentCh is closed.\nfunc ContextForChannel(parentCh \u003c-chan struct{}) context.Context {\n\treturn channelContext{stopCh: parentCh}\n}","line":{"from":113,"to":118}} {"id":100016315,"name":"Done","signature":"func (c channelContext) Done() \u003c-chan struct{} { return c.stopCh }","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/wait.go","code":"func (c channelContext) Done() \u003c-chan struct{} { return c.stopCh }","line":{"from":128,"to":128}} {"id":100016316,"name":"Err","signature":"func (c channelContext) Err() error","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/wait.go","code":"func (c channelContext) Err() error {\n\tselect {\n\tcase \u003c-c.stopCh:\n\t\treturn context.Canceled\n\tdefault:\n\t\treturn nil\n\t}\n}","line":{"from":129,"to":136}} {"id":100016317,"name":"Deadline","signature":"func (c channelContext) Deadline() (time.Time, bool) { return time.Time{}, false }","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/wait.go","code":"func (c channelContext) Deadline() (time.Time, bool) { return time.Time{}, false }","line":{"from":137,"to":137}} {"id":100016318,"name":"Value","signature":"func (c channelContext) Value(key any) any { return nil }","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/wait.go","code":"func (c channelContext) Value(key any) any { return nil }","line":{"from":138,"to":138}} {"id":100016319,"name":"runConditionWithCrashProtection","signature":"func runConditionWithCrashProtection(condition ConditionFunc) (bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/wait.go","code":"// runConditionWithCrashProtection runs a ConditionFunc with crash protection.\n//\n// Deprecated: Will be removed when the legacy polling methods are removed.\nfunc runConditionWithCrashProtection(condition ConditionFunc) (bool, error) {\n\tdefer runtime.HandleCrash()\n\treturn condition()\n}","line":{"from":140,"to":146}} {"id":100016320,"name":"runConditionWithCrashProtectionWithContext","signature":"func runConditionWithCrashProtectionWithContext(ctx context.Context, condition ConditionWithContextFunc) (bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/wait.go","code":"// runConditionWithCrashProtectionWithContext runs a ConditionWithContextFunc\n// with crash protection.\n//\n// Deprecated: Will be removed when the legacy polling methods are removed.\nfunc runConditionWithCrashProtectionWithContext(ctx context.Context, condition ConditionWithContextFunc) (bool, error) {\n\tdefer runtime.HandleCrash()\n\treturn condition(ctx)\n}","line":{"from":148,"to":155}} {"id":100016321,"name":"WithContext","signature":"func (w waitFunc) WithContext() waitWithContextFunc","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/wait.go","code":"// WithContext converts the WaitFunc to an equivalent WaitWithContextFunc\nfunc (w waitFunc) WithContext() waitWithContextFunc {\n\treturn func(ctx context.Context) \u003c-chan struct{} {\n\t\treturn w(ctx.Done())\n\t}\n}","line":{"from":164,"to":169}} {"id":100016322,"name":"waitForWithContext","signature":"func waitForWithContext(ctx context.Context, wait waitWithContextFunc, fn ConditionWithContextFunc) error","file":"staging/src/k8s.io/apimachinery/pkg/util/wait/wait.go","code":"// waitForWithContext continually checks 'fn' as driven by 'wait'.\n//\n// waitForWithContext gets a channel from 'wait()”, and then invokes 'fn'\n// once for every value placed on the channel and once more when the\n// channel is closed. If the channel is closed and 'fn'\n// returns false without error, waitForWithContext returns ErrWaitTimeout.\n//\n// If 'fn' returns an error the loop ends and that error is returned. If\n// 'fn' returns true the loop ends and nil is returned.\n//\n// context.Canceled will be returned if the ctx.Done() channel is closed\n// without fn ever returning true.\n//\n// When the ctx.Done() channel is closed, because the golang `select` statement is\n// \"uniform pseudo-random\", the `fn` might still run one or multiple times,\n// though eventually `waitForWithContext` will return.\n//\n// Deprecated: Will be removed in a future release in favor of\n// loopConditionUntilContext.\nfunc waitForWithContext(ctx context.Context, wait waitWithContextFunc, fn ConditionWithContextFunc) error {\n\twaitCtx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tc := wait(waitCtx)\n\tfor {\n\t\tselect {\n\t\tcase _, open := \u003c-c:\n\t\t\tok, err := runConditionWithCrashProtectionWithContext(ctx, fn)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif ok {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif !open {\n\t\t\t\treturn ErrWaitTimeout\n\t\t\t}\n\t\tcase \u003c-ctx.Done():\n\t\t\t// returning ctx.Err() will break backward compatibility, use new PollUntilContext*\n\t\t\t// methods instead\n\t\t\treturn ErrWaitTimeout\n\t\t}\n\t}\n}","line":{"from":181,"to":223}} {"id":100016323,"name":"Add","signature":"func (wg *RateLimitedSafeWaitGroup) Add(delta int) error","file":"staging/src/k8s.io/apimachinery/pkg/util/waitgroup/ratelimited_waitgroup.go","code":"// Add adds delta, which may be negative, similar to sync.WaitGroup.\n// If Add with a positive delta happens after Wait, it will return error,\n// which prevent unsafe Add.\nfunc (wg *RateLimitedSafeWaitGroup) Add(delta int) error {\n\twg.mu.Lock()\n\tdefer wg.mu.Unlock()\n\n\tif wg.wait \u0026\u0026 delta \u003e 0 {\n\t\treturn fmt.Errorf(\"add with positive delta after Wait is forbidden\")\n\t}\n\twg.wg.Add(delta)\n\twg.count += delta\n\treturn nil\n}","line":{"from":53,"to":66}} {"id":100016324,"name":"Done","signature":"func (wg *RateLimitedSafeWaitGroup) Done()","file":"staging/src/k8s.io/apimachinery/pkg/util/waitgroup/ratelimited_waitgroup.go","code":"// Done decrements the WaitGroup counter, rate limiting is applied only\n// when the wait group is in waiting mode.\nfunc (wg *RateLimitedSafeWaitGroup) Done() {\n\tvar limiter RateLimiter\n\tfunc() {\n\t\twg.mu.Lock()\n\t\tdefer wg.mu.Unlock()\n\n\t\twg.count -= 1\n\t\tif wg.wait {\n\t\t\t// we are using the limiter outside the scope of the lock\n\t\t\tlimiter = wg.limiter\n\t\t}\n\t}()\n\n\tdefer wg.wg.Done()\n\tif limiter != nil {\n\t\tlimiter.Wait(wg.stopCtx)\n\t}\n}","line":{"from":68,"to":87}} {"id":100016325,"name":"Wait","signature":"func (wg *RateLimitedSafeWaitGroup) Wait(limiterFactory RateLimiterFactoryFunc) (int, int, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/waitgroup/ratelimited_waitgroup.go","code":"// Wait blocks until the WaitGroup counter is zero or a hard limit has elapsed.\n// It returns the number of active request(s) accounted for at the time Wait\n// has been invoked, number of request(s) that have drianed (done using the\n// wait group immediately before Wait returns).\n// Ideally, the both numbers returned should be equal, to indicate that all\n// request(s) using the wait group have released their lock.\nfunc (wg *RateLimitedSafeWaitGroup) Wait(limiterFactory RateLimiterFactoryFunc) (int, int, error) {\n\tif limiterFactory == nil {\n\t\treturn 0, 0, fmt.Errorf(\"rate limiter factory must be specified\")\n\t}\n\n\tvar cancel context.CancelFunc\n\tvar countNow, countAfter int\n\tfunc() {\n\t\twg.mu.Lock()\n\t\tdefer wg.mu.Unlock()\n\n\t\twg.limiter, wg.stopCtx, cancel = limiterFactory(wg.count)\n\t\tcountNow = wg.count\n\t\twg.wait = true\n\t}()\n\n\tdefer cancel()\n\t// there should be a hard stop, in case request(s) are not responsive\n\t// enough to invoke Done before the grace period is over.\n\twaitDoneCh := make(chan struct{})\n\tgo func() {\n\t\tdefer close(waitDoneCh)\n\t\twg.wg.Wait()\n\t}()\n\n\tvar err error\n\tselect {\n\tcase \u003c-wg.stopCtx.Done():\n\t\terr = wg.stopCtx.Err()\n\tcase \u003c-waitDoneCh:\n\t}\n\n\tfunc() {\n\t\twg.mu.Lock()\n\t\tdefer wg.mu.Unlock()\n\n\t\tcountAfter = wg.count\n\t}()\n\treturn countNow, countAfter, err\n}","line":{"from":89,"to":134}} {"id":100016326,"name":"Add","signature":"func (wg *SafeWaitGroup) Add(delta int) error","file":"staging/src/k8s.io/apimachinery/pkg/util/waitgroup/waitgroup.go","code":"// Add adds delta, which may be negative, similar to sync.WaitGroup.\n// If Add with a positive delta happens after Wait, it will return error,\n// which prevent unsafe Add.\nfunc (wg *SafeWaitGroup) Add(delta int) error {\n\twg.mu.RLock()\n\tdefer wg.mu.RUnlock()\n\tif wg.wait \u0026\u0026 delta \u003e 0 {\n\t\treturn fmt.Errorf(\"add with positive delta after Wait is forbidden\")\n\t}\n\twg.wg.Add(delta)\n\treturn nil\n}","line":{"from":33,"to":44}} {"id":100016327,"name":"Done","signature":"func (wg *SafeWaitGroup) Done()","file":"staging/src/k8s.io/apimachinery/pkg/util/waitgroup/waitgroup.go","code":"// Done decrements the WaitGroup counter.\nfunc (wg *SafeWaitGroup) Done() {\n\twg.wg.Done()\n}","line":{"from":46,"to":49}} {"id":100016328,"name":"Wait","signature":"func (wg *SafeWaitGroup) Wait()","file":"staging/src/k8s.io/apimachinery/pkg/util/waitgroup/waitgroup.go","code":"// Wait blocks until the WaitGroup counter is zero.\nfunc (wg *SafeWaitGroup) Wait() {\n\twg.mu.Lock()\n\twg.wait = true\n\twg.mu.Unlock()\n\twg.wg.Wait()\n}","line":{"from":51,"to":57}} {"id":100016329,"name":"Unmarshal","signature":"func Unmarshal(data []byte, v interface{}) error","file":"staging/src/k8s.io/apimachinery/pkg/util/yaml/decoder.go","code":"// Unmarshal unmarshals the given data\n// If v is a *map[string]interface{}, *[]interface{}, or *interface{} numbers\n// are converted to int64 or float64\nfunc Unmarshal(data []byte, v interface{}) error {\n\tpreserveIntFloat := func(d *json.Decoder) *json.Decoder {\n\t\td.UseNumber()\n\t\treturn d\n\t}\n\tswitch v := v.(type) {\n\tcase *map[string]interface{}:\n\t\tif err := yaml.Unmarshal(data, v, preserveIntFloat); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn jsonutil.ConvertMapNumbers(*v, 0)\n\tcase *[]interface{}:\n\t\tif err := yaml.Unmarshal(data, v, preserveIntFloat); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn jsonutil.ConvertSliceNumbers(*v, 0)\n\tcase *interface{}:\n\t\tif err := yaml.Unmarshal(data, v, preserveIntFloat); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn jsonutil.ConvertInterfaceNumbers(v, 0)\n\tdefault:\n\t\treturn yaml.Unmarshal(data, v)\n\t}\n}","line":{"from":33,"to":60}} {"id":100016330,"name":"UnmarshalStrict","signature":"func UnmarshalStrict(data []byte, v interface{}) error","file":"staging/src/k8s.io/apimachinery/pkg/util/yaml/decoder.go","code":"// UnmarshalStrict unmarshals the given data\n// strictly (erroring when there are duplicate fields).\nfunc UnmarshalStrict(data []byte, v interface{}) error {\n\tpreserveIntFloat := func(d *json.Decoder) *json.Decoder {\n\t\td.UseNumber()\n\t\treturn d\n\t}\n\tswitch v := v.(type) {\n\tcase *map[string]interface{}:\n\t\tif err := yaml.UnmarshalStrict(data, v, preserveIntFloat); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn jsonutil.ConvertMapNumbers(*v, 0)\n\tcase *[]interface{}:\n\t\tif err := yaml.UnmarshalStrict(data, v, preserveIntFloat); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn jsonutil.ConvertSliceNumbers(*v, 0)\n\tcase *interface{}:\n\t\tif err := yaml.UnmarshalStrict(data, v, preserveIntFloat); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn jsonutil.ConvertInterfaceNumbers(v, 0)\n\tdefault:\n\t\treturn yaml.UnmarshalStrict(data, v)\n\t}\n}","line":{"from":62,"to":88}} {"id":100016331,"name":"ToJSON","signature":"func ToJSON(data []byte) ([]byte, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/yaml/decoder.go","code":"// ToJSON converts a single YAML document into a JSON document\n// or returns an error. If the document appears to be JSON the\n// YAML decoding path is not used (so that error messages are\n// JSON specific).\nfunc ToJSON(data []byte) ([]byte, error) {\n\tif hasJSONPrefix(data) {\n\t\treturn data, nil\n\t}\n\treturn yaml.YAMLToJSON(data)\n}","line":{"from":90,"to":99}} {"id":100016332,"name":"NewYAMLToJSONDecoder","signature":"func NewYAMLToJSONDecoder(r io.Reader) *YAMLToJSONDecoder","file":"staging/src/k8s.io/apimachinery/pkg/util/yaml/decoder.go","code":"// NewYAMLToJSONDecoder decodes YAML documents from the provided\n// stream in chunks by converting each document (as defined by\n// the YAML spec) into its own chunk, converting it to JSON via\n// yaml.YAMLToJSON, and then passing it to json.Decoder.\nfunc NewYAMLToJSONDecoder(r io.Reader) *YAMLToJSONDecoder {\n\treader := bufio.NewReader(r)\n\treturn \u0026YAMLToJSONDecoder{\n\t\treader: NewYAMLReader(reader),\n\t}\n}","line":{"from":108,"to":117}} {"id":100016333,"name":"Decode","signature":"func (d *YAMLToJSONDecoder) Decode(into interface{}) error","file":"staging/src/k8s.io/apimachinery/pkg/util/yaml/decoder.go","code":"// Decode reads a YAML document as JSON from the stream or returns\n// an error. The decoding rules match json.Unmarshal, not\n// yaml.Unmarshal.\nfunc (d *YAMLToJSONDecoder) Decode(into interface{}) error {\n\tbytes, err := d.reader.Read()\n\tif err != nil \u0026\u0026 err != io.EOF {\n\t\treturn err\n\t}\n\n\tif len(bytes) != 0 {\n\t\terr := yaml.Unmarshal(bytes, into)\n\t\tif err != nil {\n\t\t\treturn YAMLSyntaxError{err}\n\t\t}\n\t}\n\treturn err\n}","line":{"from":119,"to":135}} {"id":100016334,"name":"NewDocumentDecoder","signature":"func NewDocumentDecoder(r io.ReadCloser) io.ReadCloser","file":"staging/src/k8s.io/apimachinery/pkg/util/yaml/decoder.go","code":"// NewDocumentDecoder decodes YAML documents from the provided\n// stream in chunks by converting each document (as defined by\n// the YAML spec) into its own chunk. io.ErrShortBuffer will be\n// returned if the entire buffer could not be read to assist\n// the caller in framing the chunk.\nfunc NewDocumentDecoder(r io.ReadCloser) io.ReadCloser {\n\tscanner := bufio.NewScanner(r)\n\t// the size of initial allocation for buffer 4k\n\tbuf := make([]byte, 4*1024)\n\t// the maximum size used to buffer a token 5M\n\tscanner.Buffer(buf, 5*1024*1024)\n\tscanner.Split(splitYAMLDocument)\n\treturn \u0026YAMLDecoder{\n\t\tr: r,\n\t\tscanner: scanner,\n\t}\n}","line":{"from":145,"to":161}} {"id":100016335,"name":"Read","signature":"func (d *YAMLDecoder) Read(data []byte) (n int, err error)","file":"staging/src/k8s.io/apimachinery/pkg/util/yaml/decoder.go","code":"// Read reads the previous slice into the buffer, or attempts to read\n// the next chunk.\n// TODO: switch to readline approach.\nfunc (d *YAMLDecoder) Read(data []byte) (n int, err error) {\n\tleft := len(d.remaining)\n\tif left == 0 {\n\t\t// return the next chunk from the stream\n\t\tif !d.scanner.Scan() {\n\t\t\terr := d.scanner.Err()\n\t\t\tif err == nil {\n\t\t\t\terr = io.EOF\n\t\t\t}\n\t\t\treturn 0, err\n\t\t}\n\t\tout := d.scanner.Bytes()\n\t\td.remaining = out\n\t\tleft = len(out)\n\t}\n\n\t// fits within data\n\tif left \u003c= len(data) {\n\t\tcopy(data, d.remaining)\n\t\td.remaining = nil\n\t\treturn left, nil\n\t}\n\n\t// caller will need to reread\n\tcopy(data, d.remaining[:len(data)])\n\td.remaining = d.remaining[len(data):]\n\treturn len(data), io.ErrShortBuffer\n}","line":{"from":163,"to":193}} {"id":100016336,"name":"Close","signature":"func (d *YAMLDecoder) Close() error","file":"staging/src/k8s.io/apimachinery/pkg/util/yaml/decoder.go","code":"func (d *YAMLDecoder) Close() error {\n\treturn d.r.Close()\n}","line":{"from":195,"to":197}} {"id":100016337,"name":"splitYAMLDocument","signature":"func splitYAMLDocument(data []byte, atEOF bool) (advance int, token []byte, err error)","file":"staging/src/k8s.io/apimachinery/pkg/util/yaml/decoder.go","code":"// splitYAMLDocument is a bufio.SplitFunc for splitting YAML streams into individual documents.\nfunc splitYAMLDocument(data []byte, atEOF bool) (advance int, token []byte, err error) {\n\tif atEOF \u0026\u0026 len(data) == 0 {\n\t\treturn 0, nil, nil\n\t}\n\tsep := len([]byte(yamlSeparator))\n\tif i := bytes.Index(data, []byte(yamlSeparator)); i \u003e= 0 {\n\t\t// We have a potential document terminator\n\t\ti += sep\n\t\tafter := data[i:]\n\t\tif len(after) == 0 {\n\t\t\t// we can't read any more characters\n\t\t\tif atEOF {\n\t\t\t\treturn len(data), data[:len(data)-sep], nil\n\t\t\t}\n\t\t\treturn 0, nil, nil\n\t\t}\n\t\tif j := bytes.IndexByte(after, '\\n'); j \u003e= 0 {\n\t\t\treturn i + j + 1, data[0 : i-sep], nil\n\t\t}\n\t\treturn 0, nil, nil\n\t}\n\t// If we're at EOF, we have a final, non-terminated line. Return it.\n\tif atEOF {\n\t\treturn len(data), data, nil\n\t}\n\t// Request more data.\n\treturn 0, nil, nil\n}","line":{"from":202,"to":230}} {"id":100016338,"name":"Error","signature":"func (e JSONSyntaxError) Error() string","file":"staging/src/k8s.io/apimachinery/pkg/util/yaml/decoder.go","code":"func (e JSONSyntaxError) Error() string {\n\treturn fmt.Sprintf(\"json: offset %d: %s\", e.Offset, e.Err.Error())\n}","line":{"from":251,"to":253}} {"id":100016339,"name":"Error","signature":"func (e YAMLSyntaxError) Error() string","file":"staging/src/k8s.io/apimachinery/pkg/util/yaml/decoder.go","code":"func (e YAMLSyntaxError) Error() string {\n\treturn e.err.Error()\n}","line":{"from":259,"to":261}} {"id":100016340,"name":"NewYAMLOrJSONDecoder","signature":"func NewYAMLOrJSONDecoder(r io.Reader, bufferSize int) *YAMLOrJSONDecoder","file":"staging/src/k8s.io/apimachinery/pkg/util/yaml/decoder.go","code":"// NewYAMLOrJSONDecoder returns a decoder that will process YAML documents\n// or JSON documents from the given reader as a stream. bufferSize determines\n// how far into the stream the decoder will look to figure out whether this\n// is a JSON stream (has whitespace followed by an open brace).\nfunc NewYAMLOrJSONDecoder(r io.Reader, bufferSize int) *YAMLOrJSONDecoder {\n\treturn \u0026YAMLOrJSONDecoder{\n\t\tr: r,\n\t\tbufferSize: bufferSize,\n\t}\n}","line":{"from":263,"to":272}} {"id":100016341,"name":"Decode","signature":"func (d *YAMLOrJSONDecoder) Decode(into interface{}) error","file":"staging/src/k8s.io/apimachinery/pkg/util/yaml/decoder.go","code":"// Decode unmarshals the next object from the underlying stream into the\n// provide object, or returns an error.\nfunc (d *YAMLOrJSONDecoder) Decode(into interface{}) error {\n\tif d.decoder == nil {\n\t\tbuffer, _, isJSON := GuessJSONStream(d.r, d.bufferSize)\n\t\tif isJSON {\n\t\t\td.decoder = json.NewDecoder(buffer)\n\t\t} else {\n\t\t\td.decoder = NewYAMLToJSONDecoder(buffer)\n\t\t}\n\t}\n\terr := d.decoder.Decode(into)\n\tif syntax, ok := err.(*json.SyntaxError); ok {\n\t\treturn JSONSyntaxError{\n\t\t\tOffset: syntax.Offset,\n\t\t\tErr: syntax,\n\t\t}\n\t}\n\treturn err\n}","line":{"from":274,"to":293}} {"id":100016342,"name":"NewYAMLReader","signature":"func NewYAMLReader(r *bufio.Reader) *YAMLReader","file":"staging/src/k8s.io/apimachinery/pkg/util/yaml/decoder.go","code":"func NewYAMLReader(r *bufio.Reader) *YAMLReader {\n\treturn \u0026YAMLReader{\n\t\treader: \u0026LineReader{reader: r},\n\t}\n}","line":{"from":303,"to":307}} {"id":100016343,"name":"Read","signature":"func (r *YAMLReader) Read() ([]byte, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/yaml/decoder.go","code":"// Read returns a full YAML document.\nfunc (r *YAMLReader) Read() ([]byte, error) {\n\tvar buffer bytes.Buffer\n\tfor {\n\t\tline, err := r.reader.Read()\n\t\tif err != nil \u0026\u0026 err != io.EOF {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tsep := len([]byte(separator))\n\t\tif i := bytes.Index(line, []byte(separator)); i == 0 {\n\t\t\t// We have a potential document terminator\n\t\t\ti += sep\n\t\t\ttrimmed := strings.TrimSpace(string(line[i:]))\n\t\t\t// We only allow comments and spaces following the yaml doc separator, otherwise we'll return an error\n\t\t\tif len(trimmed) \u003e 0 \u0026\u0026 string(trimmed[0]) != \"#\" {\n\t\t\t\treturn nil, YAMLSyntaxError{\n\t\t\t\t\terr: fmt.Errorf(\"invalid Yaml document separator: %s\", trimmed),\n\t\t\t\t}\n\t\t\t}\n\t\t\tif buffer.Len() != 0 {\n\t\t\t\treturn buffer.Bytes(), nil\n\t\t\t}\n\t\t\tif err == io.EOF {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\tif err == io.EOF {\n\t\t\tif buffer.Len() != 0 {\n\t\t\t\t// If we're at EOF, we have a final, non-terminated line. Return it.\n\t\t\t\treturn buffer.Bytes(), nil\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\tbuffer.Write(line)\n\t}\n}","line":{"from":309,"to":345}} {"id":100016344,"name":"Read","signature":"func (r *LineReader) Read() ([]byte, error)","file":"staging/src/k8s.io/apimachinery/pkg/util/yaml/decoder.go","code":"// Read returns a single line (with '\\n' ended) from the underlying reader.\n// An error is returned iff there is an error with the underlying reader.\nfunc (r *LineReader) Read() ([]byte, error) {\n\tvar (\n\t\tisPrefix bool = true\n\t\terr error = nil\n\t\tline []byte\n\t\tbuffer bytes.Buffer\n\t)\n\n\tfor isPrefix \u0026\u0026 err == nil {\n\t\tline, isPrefix, err = r.reader.ReadLine()\n\t\tbuffer.Write(line)\n\t}\n\tbuffer.WriteByte('\\n')\n\treturn buffer.Bytes(), err\n}","line":{"from":351,"to":367}} {"id":100016345,"name":"GuessJSONStream","signature":"func GuessJSONStream(r io.Reader, size int) (io.Reader, []byte, bool)","file":"staging/src/k8s.io/apimachinery/pkg/util/yaml/decoder.go","code":"// GuessJSONStream scans the provided reader up to size, looking\n// for an open brace indicating this is JSON. It will return the\n// bufio.Reader it creates for the consumer.\nfunc GuessJSONStream(r io.Reader, size int) (io.Reader, []byte, bool) {\n\tbuffer := bufio.NewReaderSize(r, size)\n\tb, _ := buffer.Peek(size)\n\treturn buffer, b, hasJSONPrefix(b)\n}","line":{"from":369,"to":376}} {"id":100016346,"name":"IsJSONBuffer","signature":"func IsJSONBuffer(buf []byte) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/yaml/decoder.go","code":"// IsJSONBuffer scans the provided buffer, looking\n// for an open brace indicating this is JSON.\nfunc IsJSONBuffer(buf []byte) bool {\n\treturn hasJSONPrefix(buf)\n}","line":{"from":378,"to":382}} {"id":100016347,"name":"hasJSONPrefix","signature":"func hasJSONPrefix(buf []byte) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/yaml/decoder.go","code":"// hasJSONPrefix returns true if the provided buffer appears to start with\n// a JSON open brace.\nfunc hasJSONPrefix(buf []byte) bool {\n\treturn hasPrefix(buf, jsonPrefix)\n}","line":{"from":386,"to":390}} {"id":100016348,"name":"hasPrefix","signature":"func hasPrefix(buf []byte, prefix []byte) bool","file":"staging/src/k8s.io/apimachinery/pkg/util/yaml/decoder.go","code":"// Return true if the first non-whitespace bytes in buf is\n// prefix.\nfunc hasPrefix(buf []byte, prefix []byte) bool {\n\ttrim := bytes.TrimLeftFunc(buf, unicode.IsSpace)\n\treturn bytes.HasPrefix(trim, prefix)\n}","line":{"from":392,"to":397}} {"id":100016349,"name":"parseKubeVersion","signature":"func parseKubeVersion(v string) (majorVersion int, vType versionType, minorVersion int, ok bool)","file":"staging/src/k8s.io/apimachinery/pkg/version/helpers.go","code":"func parseKubeVersion(v string) (majorVersion int, vType versionType, minorVersion int, ok bool) {\n\tvar err error\n\tsubmatches := kubeVersionRegex.FindStringSubmatch(v)\n\tif len(submatches) != 4 {\n\t\treturn 0, 0, 0, false\n\t}\n\tswitch submatches[2] {\n\tcase \"alpha\":\n\t\tvType = versionTypeAlpha\n\tcase \"beta\":\n\t\tvType = versionTypeBeta\n\tcase \"\":\n\t\tvType = versionTypeGA\n\tdefault:\n\t\treturn 0, 0, 0, false\n\t}\n\tif majorVersion, err = strconv.Atoi(submatches[1]); err != nil {\n\t\treturn 0, 0, 0, false\n\t}\n\tif vType != versionTypeGA {\n\t\tif minorVersion, err = strconv.Atoi(submatches[3]); err != nil {\n\t\t\treturn 0, 0, 0, false\n\t\t}\n\t}\n\treturn majorVersion, vType, minorVersion, true\n}","line":{"from":36,"to":61}} {"id":100016350,"name":"CompareKubeAwareVersionStrings","signature":"func CompareKubeAwareVersionStrings(v1, v2 string) int","file":"staging/src/k8s.io/apimachinery/pkg/version/helpers.go","code":"// CompareKubeAwareVersionStrings compares two kube-like version strings.\n// Kube-like version strings are starting with a v, followed by a major version, optional \"alpha\" or \"beta\" strings\n// followed by a minor version (e.g. v1, v2beta1). Versions will be sorted based on GA/alpha/beta first and then major\n// and minor versions. e.g. v2, v1, v1beta2, v1beta1, v1alpha1.\nfunc CompareKubeAwareVersionStrings(v1, v2 string) int {\n\tif v1 == v2 {\n\t\treturn 0\n\t}\n\tv1major, v1type, v1minor, ok1 := parseKubeVersion(v1)\n\tv2major, v2type, v2minor, ok2 := parseKubeVersion(v2)\n\tswitch {\n\tcase !ok1 \u0026\u0026 !ok2:\n\t\treturn strings.Compare(v2, v1)\n\tcase !ok1 \u0026\u0026 ok2:\n\t\treturn -1\n\tcase ok1 \u0026\u0026 !ok2:\n\t\treturn 1\n\t}\n\tif v1type != v2type {\n\t\treturn int(v1type) - int(v2type)\n\t}\n\tif v1major != v2major {\n\t\treturn v1major - v2major\n\t}\n\treturn v1minor - v2minor\n}","line":{"from":63,"to":88}} {"id":100016351,"name":"String","signature":"func (info Info) String() string","file":"staging/src/k8s.io/apimachinery/pkg/version/types.go","code":"// String returns info as a human-friendly version string.\nfunc (info Info) String() string {\n\treturn info.GitVersion\n}","line":{"from":34,"to":37}} {"id":100016352,"name":"Filter","signature":"func Filter(w Interface, f FilterFunc) Interface","file":"staging/src/k8s.io/apimachinery/pkg/watch/filter.go","code":"// Filter passes all events through f before allowing them to pass on.\n// Putting a filter on a watch, as an unavoidable side-effect due to the way\n// go channels work, effectively causes the watch's event channel to have its\n// queue length increased by one.\n//\n// WARNING: filter has a fatal flaw, in that it can't properly update the\n// Type field (Add/Modified/Deleted) to reflect items beginning to pass the\n// filter when they previously didn't.\nfunc Filter(w Interface, f FilterFunc) Interface {\n\tfw := \u0026filteredWatch{\n\t\tincoming: w,\n\t\tresult: make(chan Event),\n\t\tf: f,\n\t}\n\tgo fw.loop()\n\treturn fw\n}","line":{"from":27,"to":43}} {"id":100016353,"name":"ResultChan","signature":"func (fw *filteredWatch) ResultChan() \u003c-chan Event","file":"staging/src/k8s.io/apimachinery/pkg/watch/filter.go","code":"// ResultChan returns a channel which will receive filtered events.\nfunc (fw *filteredWatch) ResultChan() \u003c-chan Event {\n\treturn fw.result\n}","line":{"from":51,"to":54}} {"id":100016354,"name":"Stop","signature":"func (fw *filteredWatch) Stop()","file":"staging/src/k8s.io/apimachinery/pkg/watch/filter.go","code":"// Stop stops the upstream watch, which will eventually stop this watch.\nfunc (fw *filteredWatch) Stop() {\n\tfw.incoming.Stop()\n}","line":{"from":56,"to":59}} {"id":100016355,"name":"loop","signature":"func (fw *filteredWatch) loop()","file":"staging/src/k8s.io/apimachinery/pkg/watch/filter.go","code":"// loop waits for new values, filters them, and resends them.\nfunc (fw *filteredWatch) loop() {\n\tdefer close(fw.result)\n\tfor event := range fw.incoming.ResultChan() {\n\t\tfiltered, keep := fw.f(event)\n\t\tif keep {\n\t\t\tfw.result \u003c- filtered\n\t\t}\n\t}\n}","line":{"from":61,"to":70}} {"id":100016356,"name":"NewRecorder","signature":"func NewRecorder(w Interface) *Recorder","file":"staging/src/k8s.io/apimachinery/pkg/watch/filter.go","code":"// NewRecorder wraps an Interface and records any changes sent across it.\nfunc NewRecorder(w Interface) *Recorder {\n\tr := \u0026Recorder{}\n\tr.Interface = Filter(w, r.record)\n\treturn r\n}","line":{"from":82,"to":87}} {"id":100016357,"name":"record","signature":"func (r *Recorder) record(in Event) (Event, bool)","file":"staging/src/k8s.io/apimachinery/pkg/watch/filter.go","code":"// record is a FilterFunc and tracks each received event.\nfunc (r *Recorder) record(in Event) (Event, bool) {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\tr.events = append(r.events, in)\n\treturn in, true\n}","line":{"from":89,"to":95}} {"id":100016358,"name":"Events","signature":"func (r *Recorder) Events() []Event","file":"staging/src/k8s.io/apimachinery/pkg/watch/filter.go","code":"// Events returns a copy of the events sent across this recorder.\nfunc (r *Recorder) Events() []Event {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\tcopied := make([]Event, len(r.events))\n\tcopy(copied, r.events)\n\treturn copied\n}","line":{"from":97,"to":104}} {"id":100016359,"name":"NewBroadcaster","signature":"func NewBroadcaster(queueLength int, fullChannelBehavior FullChannelBehavior) *Broadcaster","file":"staging/src/k8s.io/apimachinery/pkg/watch/mux.go","code":"// NewBroadcaster creates a new Broadcaster. queueLength is the maximum number of events to queue per watcher.\n// It is guaranteed that events will be distributed in the order in which they occur,\n// but the order in which a single event is distributed among all of the watchers is unspecified.\nfunc NewBroadcaster(queueLength int, fullChannelBehavior FullChannelBehavior) *Broadcaster {\n\tm := \u0026Broadcaster{\n\t\twatchers: map[int64]*broadcasterWatcher{},\n\t\tincoming: make(chan Event, incomingQueueLength),\n\t\tstopped: make(chan struct{}),\n\t\twatchQueueLength: queueLength,\n\t\tfullChannelBehavior: fullChannelBehavior,\n\t}\n\tm.distributing.Add(1)\n\tgo m.loop()\n\treturn m\n}","line":{"from":65,"to":79}} {"id":100016360,"name":"NewLongQueueBroadcaster","signature":"func NewLongQueueBroadcaster(queueLength int, fullChannelBehavior FullChannelBehavior) *Broadcaster","file":"staging/src/k8s.io/apimachinery/pkg/watch/mux.go","code":"// NewLongQueueBroadcaster functions nearly identically to NewBroadcaster,\n// except that the incoming queue is the same size as the outgoing queues\n// (specified by queueLength).\nfunc NewLongQueueBroadcaster(queueLength int, fullChannelBehavior FullChannelBehavior) *Broadcaster {\n\tm := \u0026Broadcaster{\n\t\twatchers: map[int64]*broadcasterWatcher{},\n\t\tincoming: make(chan Event, queueLength),\n\t\tstopped: make(chan struct{}),\n\t\twatchQueueLength: queueLength,\n\t\tfullChannelBehavior: fullChannelBehavior,\n\t}\n\tm.distributing.Add(1)\n\tgo m.loop()\n\treturn m\n}","line":{"from":81,"to":95}} {"id":100016361,"name":"GetObjectKind","signature":"func (obj functionFakeRuntimeObject) GetObjectKind() schema.ObjectKind","file":"staging/src/k8s.io/apimachinery/pkg/watch/mux.go","code":"func (obj functionFakeRuntimeObject) GetObjectKind() schema.ObjectKind {\n\treturn schema.EmptyObjectKind\n}","line":{"from":102,"to":104}} {"id":100016362,"name":"DeepCopyObject","signature":"func (obj functionFakeRuntimeObject) DeepCopyObject() runtime.Object","file":"staging/src/k8s.io/apimachinery/pkg/watch/mux.go","code":"func (obj functionFakeRuntimeObject) DeepCopyObject() runtime.Object {\n\tif obj == nil {\n\t\treturn nil\n\t}\n\t// funcs are immutable. Hence, just return the original func.\n\treturn obj\n}","line":{"from":105,"to":111}} {"id":100016363,"name":"blockQueue","signature":"func (m *Broadcaster) blockQueue(f func())","file":"staging/src/k8s.io/apimachinery/pkg/watch/mux.go","code":"// Execute f, blocking the incoming queue (and waiting for it to drain first).\n// The purpose of this terrible hack is so that watchers added after an event\n// won't ever see that event, and will always see any event after they are\n// added.\nfunc (m *Broadcaster) blockQueue(f func()) {\n\tm.incomingBlock.Lock()\n\tdefer m.incomingBlock.Unlock()\n\tselect {\n\tcase \u003c-m.stopped:\n\t\treturn\n\tdefault:\n\t}\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tm.incoming \u003c- Event{\n\t\tType: internalRunFunctionMarker,\n\t\tObject: functionFakeRuntimeObject(func() {\n\t\t\tdefer wg.Done()\n\t\t\tf()\n\t\t}),\n\t}\n\twg.Wait()\n}","line":{"from":113,"to":135}} {"id":100016364,"name":"Watch","signature":"func (m *Broadcaster) Watch() (Interface, error)","file":"staging/src/k8s.io/apimachinery/pkg/watch/mux.go","code":"// Watch adds a new watcher to the list and returns an Interface for it.\n// Note: new watchers will only receive new events. They won't get an entire history\n// of previous events. It will block until the watcher is actually added to the\n// broadcaster.\nfunc (m *Broadcaster) Watch() (Interface, error) {\n\tvar w *broadcasterWatcher\n\tm.blockQueue(func() {\n\t\tid := m.nextWatcher\n\t\tm.nextWatcher++\n\t\tw = \u0026broadcasterWatcher{\n\t\t\tresult: make(chan Event, m.watchQueueLength),\n\t\t\tstopped: make(chan struct{}),\n\t\t\tid: id,\n\t\t\tm: m,\n\t\t}\n\t\tm.watchers[id] = w\n\t})\n\tif w == nil {\n\t\treturn nil, fmt.Errorf(\"broadcaster already stopped\")\n\t}\n\treturn w, nil\n}","line":{"from":137,"to":158}} {"id":100016365,"name":"WatchWithPrefix","signature":"func (m *Broadcaster) WatchWithPrefix(queuedEvents []Event) (Interface, error)","file":"staging/src/k8s.io/apimachinery/pkg/watch/mux.go","code":"// WatchWithPrefix adds a new watcher to the list and returns an Interface for it. It sends\n// queuedEvents down the new watch before beginning to send ordinary events from Broadcaster.\n// The returned watch will have a queue length that is at least large enough to accommodate\n// all of the items in queuedEvents. It will block until the watcher is actually added to\n// the broadcaster.\nfunc (m *Broadcaster) WatchWithPrefix(queuedEvents []Event) (Interface, error) {\n\tvar w *broadcasterWatcher\n\tm.blockQueue(func() {\n\t\tid := m.nextWatcher\n\t\tm.nextWatcher++\n\t\tlength := m.watchQueueLength\n\t\tif n := len(queuedEvents) + 1; n \u003e length {\n\t\t\tlength = n\n\t\t}\n\t\tw = \u0026broadcasterWatcher{\n\t\t\tresult: make(chan Event, length),\n\t\t\tstopped: make(chan struct{}),\n\t\t\tid: id,\n\t\t\tm: m,\n\t\t}\n\t\tm.watchers[id] = w\n\t\tfor _, e := range queuedEvents {\n\t\t\tw.result \u003c- e\n\t\t}\n\t})\n\tif w == nil {\n\t\treturn nil, fmt.Errorf(\"broadcaster already stopped\")\n\t}\n\treturn w, nil\n}","line":{"from":160,"to":189}} {"id":100016366,"name":"stopWatching","signature":"func (m *Broadcaster) stopWatching(id int64)","file":"staging/src/k8s.io/apimachinery/pkg/watch/mux.go","code":"// stopWatching stops the given watcher and removes it from the list.\nfunc (m *Broadcaster) stopWatching(id int64) {\n\tm.blockQueue(func() {\n\t\tw, ok := m.watchers[id]\n\t\tif !ok {\n\t\t\t// No need to do anything, it's already been removed from the list.\n\t\t\treturn\n\t\t}\n\t\tdelete(m.watchers, id)\n\t\tclose(w.result)\n\t})\n}","line":{"from":191,"to":202}} {"id":100016367,"name":"closeAll","signature":"func (m *Broadcaster) closeAll()","file":"staging/src/k8s.io/apimachinery/pkg/watch/mux.go","code":"// closeAll disconnects all watchers (presumably in response to a Shutdown call).\nfunc (m *Broadcaster) closeAll() {\n\tfor _, w := range m.watchers {\n\t\tclose(w.result)\n\t}\n\t// Delete everything from the map, since presence/absence in the map is used\n\t// by stopWatching to avoid double-closing the channel.\n\tm.watchers = map[int64]*broadcasterWatcher{}\n}","line":{"from":204,"to":212}} {"id":100016368,"name":"Action","signature":"func (m *Broadcaster) Action(action EventType, obj runtime.Object) error","file":"staging/src/k8s.io/apimachinery/pkg/watch/mux.go","code":"// Action distributes the given event among all watchers.\nfunc (m *Broadcaster) Action(action EventType, obj runtime.Object) error {\n\tm.incomingBlock.Lock()\n\tdefer m.incomingBlock.Unlock()\n\tselect {\n\tcase \u003c-m.stopped:\n\t\treturn fmt.Errorf(\"broadcaster already stopped\")\n\tdefault:\n\t}\n\n\tm.incoming \u003c- Event{action, obj}\n\treturn nil\n}","line":{"from":214,"to":226}} {"id":100016369,"name":"ActionOrDrop","signature":"func (m *Broadcaster) ActionOrDrop(action EventType, obj runtime.Object) (bool, error)","file":"staging/src/k8s.io/apimachinery/pkg/watch/mux.go","code":"// Action distributes the given event among all watchers, or drops it on the floor\n// if too many incoming actions are queued up. Returns true if the action was sent,\n// false if dropped.\nfunc (m *Broadcaster) ActionOrDrop(action EventType, obj runtime.Object) (bool, error) {\n\tm.incomingBlock.Lock()\n\tdefer m.incomingBlock.Unlock()\n\n\t// Ensure that if the broadcaster is stopped we do not send events to it.\n\tselect {\n\tcase \u003c-m.stopped:\n\t\treturn false, fmt.Errorf(\"broadcaster already stopped\")\n\tdefault:\n\t}\n\n\tselect {\n\tcase m.incoming \u003c- Event{action, obj}:\n\t\treturn true, nil\n\tdefault:\n\t\treturn false, nil\n\t}\n}","line":{"from":228,"to":248}} {"id":100016370,"name":"Shutdown","signature":"func (m *Broadcaster) Shutdown()","file":"staging/src/k8s.io/apimachinery/pkg/watch/mux.go","code":"// Shutdown disconnects all watchers (but any queued events will still be distributed).\n// You must not call Action or Watch* after calling Shutdown. This call blocks\n// until all events have been distributed through the outbound channels. Note\n// that since they can be buffered, this means that the watchers might not\n// have received the data yet as it can remain sitting in the buffered\n// channel. It will block until the broadcaster stop request is actually executed\nfunc (m *Broadcaster) Shutdown() {\n\tm.blockQueue(func() {\n\t\tclose(m.stopped)\n\t\tclose(m.incoming)\n\t})\n\tm.distributing.Wait()\n}","line":{"from":250,"to":262}} {"id":100016371,"name":"loop","signature":"func (m *Broadcaster) loop()","file":"staging/src/k8s.io/apimachinery/pkg/watch/mux.go","code":"// loop receives from m.incoming and distributes to all watchers.\nfunc (m *Broadcaster) loop() {\n\t// Deliberately not catching crashes here. Yes, bring down the process if there's a\n\t// bug in watch.Broadcaster.\n\tfor event := range m.incoming {\n\t\tif event.Type == internalRunFunctionMarker {\n\t\t\tevent.Object.(functionFakeRuntimeObject)()\n\t\t\tcontinue\n\t\t}\n\t\tm.distribute(event)\n\t}\n\tm.closeAll()\n\tm.distributing.Done()\n}","line":{"from":264,"to":277}} {"id":100016372,"name":"distribute","signature":"func (m *Broadcaster) distribute(event Event)","file":"staging/src/k8s.io/apimachinery/pkg/watch/mux.go","code":"// distribute sends event to all watchers. Blocking.\nfunc (m *Broadcaster) distribute(event Event) {\n\tif m.fullChannelBehavior == DropIfChannelFull {\n\t\tfor _, w := range m.watchers {\n\t\t\tselect {\n\t\t\tcase w.result \u003c- event:\n\t\t\tcase \u003c-w.stopped:\n\t\t\tdefault: // Don't block if the event can't be queued.\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor _, w := range m.watchers {\n\t\t\tselect {\n\t\t\tcase w.result \u003c- event:\n\t\t\tcase \u003c-w.stopped:\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":279,"to":297}} {"id":100016373,"name":"ResultChan","signature":"func (mw *broadcasterWatcher) ResultChan() \u003c-chan Event","file":"staging/src/k8s.io/apimachinery/pkg/watch/mux.go","code":"// ResultChan returns a channel to use for waiting on events.\nfunc (mw *broadcasterWatcher) ResultChan() \u003c-chan Event {\n\treturn mw.result\n}","line":{"from":308,"to":311}} {"id":100016374,"name":"Stop","signature":"func (mw *broadcasterWatcher) Stop()","file":"staging/src/k8s.io/apimachinery/pkg/watch/mux.go","code":"// Stop stops watching and removes mw from its list.\n// It will block until the watcher stop request is actually executed\nfunc (mw *broadcasterWatcher) Stop() {\n\tmw.stop.Do(func() {\n\t\tclose(mw.stopped)\n\t\tmw.m.stopWatching(mw.id)\n\t})\n}","line":{"from":313,"to":320}} {"id":100016375,"name":"NewStreamWatcher","signature":"func NewStreamWatcher(d Decoder, r Reporter) *StreamWatcher","file":"staging/src/k8s.io/apimachinery/pkg/watch/streamwatcher.go","code":"// NewStreamWatcher creates a StreamWatcher from the given decoder.\nfunc NewStreamWatcher(d Decoder, r Reporter) *StreamWatcher {\n\tsw := \u0026StreamWatcher{\n\t\tsource: d,\n\t\treporter: r,\n\t\t// It's easy for a consumer to add buffering via an extra\n\t\t// goroutine/channel, but impossible for them to remove it,\n\t\t// so nonbuffered is better.\n\t\tresult: make(chan Event),\n\t\t// If the watcher is externally stopped there is no receiver anymore\n\t\t// and the send operations on the result channel, especially the\n\t\t// error reporting might block forever.\n\t\t// Therefore a dedicated stop channel is used to resolve this blocking.\n\t\tdone: make(chan struct{}),\n\t}\n\tgo sw.receive()\n\treturn sw\n}","line":{"from":61,"to":78}} {"id":100016376,"name":"ResultChan","signature":"func (sw *StreamWatcher) ResultChan() \u003c-chan Event","file":"staging/src/k8s.io/apimachinery/pkg/watch/streamwatcher.go","code":"// ResultChan implements Interface.\nfunc (sw *StreamWatcher) ResultChan() \u003c-chan Event {\n\treturn sw.result\n}","line":{"from":80,"to":83}} {"id":100016377,"name":"Stop","signature":"func (sw *StreamWatcher) Stop()","file":"staging/src/k8s.io/apimachinery/pkg/watch/streamwatcher.go","code":"// Stop implements Interface.\nfunc (sw *StreamWatcher) Stop() {\n\t// Call Close() exactly once by locking and setting a flag.\n\tsw.Lock()\n\tdefer sw.Unlock()\n\t// closing a closed channel always panics, therefore check before closing\n\tselect {\n\tcase \u003c-sw.done:\n\tdefault:\n\t\tclose(sw.done)\n\t\tsw.source.Close()\n\t}\n}","line":{"from":85,"to":97}} {"id":100016378,"name":"receive","signature":"func (sw *StreamWatcher) receive()","file":"staging/src/k8s.io/apimachinery/pkg/watch/streamwatcher.go","code":"// receive reads result from the decoder in a loop and sends down the result channel.\nfunc (sw *StreamWatcher) receive() {\n\tdefer utilruntime.HandleCrash()\n\tdefer close(sw.result)\n\tdefer sw.Stop()\n\tfor {\n\t\taction, obj, err := sw.source.Decode()\n\t\tif err != nil {\n\t\t\tswitch err {\n\t\t\tcase io.EOF:\n\t\t\t\t// watch closed normally\n\t\t\tcase io.ErrUnexpectedEOF:\n\t\t\t\tklog.V(1).Infof(\"Unexpected EOF during watch stream event decoding: %v\", err)\n\t\t\tdefault:\n\t\t\t\tif net.IsProbableEOF(err) || net.IsTimeout(err) {\n\t\t\t\t\tklog.V(5).Infof(\"Unable to decode an event from the watch stream: %v\", err)\n\t\t\t\t} else {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase \u003c-sw.done:\n\t\t\t\t\tcase sw.result \u003c- Event{\n\t\t\t\t\t\tType: Error,\n\t\t\t\t\t\tObject: sw.reporter.AsObject(fmt.Errorf(\"unable to decode an event from the watch stream: %v\", err)),\n\t\t\t\t\t}:\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tselect {\n\t\tcase \u003c-sw.done:\n\t\t\treturn\n\t\tcase sw.result \u003c- Event{\n\t\t\tType: action,\n\t\t\tObject: obj,\n\t\t}:\n\t\t}\n\t}\n}","line":{"from":99,"to":136}} {"id":100016379,"name":"NewEmptyWatch","signature":"func NewEmptyWatch() Interface","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"// NewEmptyWatch returns a watch interface that returns no results and is closed.\n// May be used in certain error conditions where no information is available but\n// an error is not warranted.\nfunc NewEmptyWatch() Interface {\n\tch := make(chan Event)\n\tclose(ch)\n\treturn emptyWatch(ch)\n}","line":{"from":74,"to":81}} {"id":100016380,"name":"Stop","signature":"func (w emptyWatch) Stop()","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"// Stop implements Interface\nfunc (w emptyWatch) Stop() {\n}","line":{"from":83,"to":85}} {"id":100016381,"name":"ResultChan","signature":"func (w emptyWatch) ResultChan() \u003c-chan Event","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"// ResultChan implements Interface\nfunc (w emptyWatch) ResultChan() \u003c-chan Event {\n\treturn chan Event(w)\n}","line":{"from":87,"to":90}} {"id":100016382,"name":"NewFake","signature":"func NewFake() *FakeWatcher","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"func NewFake() *FakeWatcher {\n\treturn \u0026FakeWatcher{\n\t\tresult: make(chan Event),\n\t}\n}","line":{"from":99,"to":103}} {"id":100016383,"name":"NewFakeWithChanSize","signature":"func NewFakeWithChanSize(size int, blocking bool) *FakeWatcher","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"func NewFakeWithChanSize(size int, blocking bool) *FakeWatcher {\n\treturn \u0026FakeWatcher{\n\t\tresult: make(chan Event, size),\n\t}\n}","line":{"from":105,"to":109}} {"id":100016384,"name":"Stop","signature":"func (f *FakeWatcher) Stop()","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"// Stop implements Interface.Stop().\nfunc (f *FakeWatcher) Stop() {\n\tf.Lock()\n\tdefer f.Unlock()\n\tif !f.stopped {\n\t\tklog.V(4).Infof(\"Stopping fake watcher.\")\n\t\tclose(f.result)\n\t\tf.stopped = true\n\t}\n}","line":{"from":111,"to":120}} {"id":100016385,"name":"IsStopped","signature":"func (f *FakeWatcher) IsStopped() bool","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"func (f *FakeWatcher) IsStopped() bool {\n\tf.Lock()\n\tdefer f.Unlock()\n\treturn f.stopped\n}","line":{"from":122,"to":126}} {"id":100016386,"name":"Reset","signature":"func (f *FakeWatcher) Reset()","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"// Reset prepares the watcher to be reused.\nfunc (f *FakeWatcher) Reset() {\n\tf.Lock()\n\tdefer f.Unlock()\n\tf.stopped = false\n\tf.result = make(chan Event)\n}","line":{"from":128,"to":134}} {"id":100016387,"name":"ResultChan","signature":"func (f *FakeWatcher) ResultChan() \u003c-chan Event","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"func (f *FakeWatcher) ResultChan() \u003c-chan Event {\n\treturn f.result\n}","line":{"from":136,"to":138}} {"id":100016388,"name":"Add","signature":"func (f *FakeWatcher) Add(obj runtime.Object)","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"// Add sends an add event.\nfunc (f *FakeWatcher) Add(obj runtime.Object) {\n\tf.result \u003c- Event{Added, obj}\n}","line":{"from":140,"to":143}} {"id":100016389,"name":"Modify","signature":"func (f *FakeWatcher) Modify(obj runtime.Object)","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"// Modify sends a modify event.\nfunc (f *FakeWatcher) Modify(obj runtime.Object) {\n\tf.result \u003c- Event{Modified, obj}\n}","line":{"from":145,"to":148}} {"id":100016390,"name":"Delete","signature":"func (f *FakeWatcher) Delete(lastValue runtime.Object)","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"// Delete sends a delete event.\nfunc (f *FakeWatcher) Delete(lastValue runtime.Object) {\n\tf.result \u003c- Event{Deleted, lastValue}\n}","line":{"from":150,"to":153}} {"id":100016391,"name":"Error","signature":"func (f *FakeWatcher) Error(errValue runtime.Object)","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"// Error sends an Error event.\nfunc (f *FakeWatcher) Error(errValue runtime.Object) {\n\tf.result \u003c- Event{Error, errValue}\n}","line":{"from":155,"to":158}} {"id":100016392,"name":"Action","signature":"func (f *FakeWatcher) Action(action EventType, obj runtime.Object)","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"// Action sends an event of the requested type, for table-based testing.\nfunc (f *FakeWatcher) Action(action EventType, obj runtime.Object) {\n\tf.result \u003c- Event{action, obj}\n}","line":{"from":160,"to":163}} {"id":100016393,"name":"NewRaceFreeFake","signature":"func NewRaceFreeFake() *RaceFreeFakeWatcher","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"func NewRaceFreeFake() *RaceFreeFakeWatcher {\n\treturn \u0026RaceFreeFakeWatcher{\n\t\tresult: make(chan Event, DefaultChanSize),\n\t}\n}","line":{"from":172,"to":176}} {"id":100016394,"name":"Stop","signature":"func (f *RaceFreeFakeWatcher) Stop()","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"// Stop implements Interface.Stop().\nfunc (f *RaceFreeFakeWatcher) Stop() {\n\tf.Lock()\n\tdefer f.Unlock()\n\tif !f.Stopped {\n\t\tklog.V(4).Infof(\"Stopping fake watcher.\")\n\t\tclose(f.result)\n\t\tf.Stopped = true\n\t}\n}","line":{"from":178,"to":187}} {"id":100016395,"name":"IsStopped","signature":"func (f *RaceFreeFakeWatcher) IsStopped() bool","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"func (f *RaceFreeFakeWatcher) IsStopped() bool {\n\tf.Lock()\n\tdefer f.Unlock()\n\treturn f.Stopped\n}","line":{"from":189,"to":193}} {"id":100016396,"name":"Reset","signature":"func (f *RaceFreeFakeWatcher) Reset()","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"// Reset prepares the watcher to be reused.\nfunc (f *RaceFreeFakeWatcher) Reset() {\n\tf.Lock()\n\tdefer f.Unlock()\n\tf.Stopped = false\n\tf.result = make(chan Event, DefaultChanSize)\n}","line":{"from":195,"to":201}} {"id":100016397,"name":"ResultChan","signature":"func (f *RaceFreeFakeWatcher) ResultChan() \u003c-chan Event","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"func (f *RaceFreeFakeWatcher) ResultChan() \u003c-chan Event {\n\tf.Lock()\n\tdefer f.Unlock()\n\treturn f.result\n}","line":{"from":203,"to":207}} {"id":100016398,"name":"Add","signature":"func (f *RaceFreeFakeWatcher) Add(obj runtime.Object)","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"// Add sends an add event.\nfunc (f *RaceFreeFakeWatcher) Add(obj runtime.Object) {\n\tf.Lock()\n\tdefer f.Unlock()\n\tif !f.Stopped {\n\t\tselect {\n\t\tcase f.result \u003c- Event{Added, obj}:\n\t\t\treturn\n\t\tdefault:\n\t\t\tpanic(fmt.Errorf(\"channel full\"))\n\t\t}\n\t}\n}","line":{"from":209,"to":221}} {"id":100016399,"name":"Modify","signature":"func (f *RaceFreeFakeWatcher) Modify(obj runtime.Object)","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"// Modify sends a modify event.\nfunc (f *RaceFreeFakeWatcher) Modify(obj runtime.Object) {\n\tf.Lock()\n\tdefer f.Unlock()\n\tif !f.Stopped {\n\t\tselect {\n\t\tcase f.result \u003c- Event{Modified, obj}:\n\t\t\treturn\n\t\tdefault:\n\t\t\tpanic(fmt.Errorf(\"channel full\"))\n\t\t}\n\t}\n}","line":{"from":223,"to":235}} {"id":100016400,"name":"Delete","signature":"func (f *RaceFreeFakeWatcher) Delete(lastValue runtime.Object)","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"// Delete sends a delete event.\nfunc (f *RaceFreeFakeWatcher) Delete(lastValue runtime.Object) {\n\tf.Lock()\n\tdefer f.Unlock()\n\tif !f.Stopped {\n\t\tselect {\n\t\tcase f.result \u003c- Event{Deleted, lastValue}:\n\t\t\treturn\n\t\tdefault:\n\t\t\tpanic(fmt.Errorf(\"channel full\"))\n\t\t}\n\t}\n}","line":{"from":237,"to":249}} {"id":100016401,"name":"Error","signature":"func (f *RaceFreeFakeWatcher) Error(errValue runtime.Object)","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"// Error sends an Error event.\nfunc (f *RaceFreeFakeWatcher) Error(errValue runtime.Object) {\n\tf.Lock()\n\tdefer f.Unlock()\n\tif !f.Stopped {\n\t\tselect {\n\t\tcase f.result \u003c- Event{Error, errValue}:\n\t\t\treturn\n\t\tdefault:\n\t\t\tpanic(fmt.Errorf(\"channel full\"))\n\t\t}\n\t}\n}","line":{"from":251,"to":263}} {"id":100016402,"name":"Action","signature":"func (f *RaceFreeFakeWatcher) Action(action EventType, obj runtime.Object)","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"// Action sends an event of the requested type, for table-based testing.\nfunc (f *RaceFreeFakeWatcher) Action(action EventType, obj runtime.Object) {\n\tf.Lock()\n\tdefer f.Unlock()\n\tif !f.Stopped {\n\t\tselect {\n\t\tcase f.result \u003c- Event{action, obj}:\n\t\t\treturn\n\t\tdefault:\n\t\t\tpanic(fmt.Errorf(\"channel full\"))\n\t\t}\n\t}\n}","line":{"from":265,"to":277}} {"id":100016403,"name":"NewProxyWatcher","signature":"func NewProxyWatcher(ch chan Event) *ProxyWatcher","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"// NewProxyWatcher creates new ProxyWatcher by wrapping a channel\nfunc NewProxyWatcher(ch chan Event) *ProxyWatcher {\n\treturn \u0026ProxyWatcher{\n\t\tresult: ch,\n\t\tstopCh: make(chan struct{}),\n\t\tstopped: false,\n\t}\n}","line":{"from":290,"to":297}} {"id":100016404,"name":"Stop","signature":"func (pw *ProxyWatcher) Stop()","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"// Stop implements Interface\nfunc (pw *ProxyWatcher) Stop() {\n\tpw.mutex.Lock()\n\tdefer pw.mutex.Unlock()\n\tif !pw.stopped {\n\t\tpw.stopped = true\n\t\tclose(pw.stopCh)\n\t}\n}","line":{"from":299,"to":307}} {"id":100016405,"name":"Stopping","signature":"func (pw *ProxyWatcher) Stopping() bool","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"// Stopping returns true if Stop() has been called\nfunc (pw *ProxyWatcher) Stopping() bool {\n\tpw.mutex.Lock()\n\tdefer pw.mutex.Unlock()\n\treturn pw.stopped\n}","line":{"from":309,"to":314}} {"id":100016406,"name":"ResultChan","signature":"func (pw *ProxyWatcher) ResultChan() \u003c-chan Event","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"// ResultChan implements Interface\nfunc (pw *ProxyWatcher) ResultChan() \u003c-chan Event {\n\treturn pw.result\n}","line":{"from":316,"to":319}} {"id":100016407,"name":"StopChan","signature":"func (pw *ProxyWatcher) StopChan() \u003c-chan struct{}","file":"staging/src/k8s.io/apimachinery/pkg/watch/watch.go","code":"// StopChan returns stop channel\nfunc (pw *ProxyWatcher) StopChan() \u003c-chan struct{} {\n\treturn pw.stopCh\n}","line":{"from":321,"to":324}} {"id":100016408,"name":"NewAttributesRecord","signature":"func NewAttributesRecord(object runtime.Object, oldObject runtime.Object, kind schema.GroupVersionKind, namespace, name string, resource schema.GroupVersionResource, subresource string, operation Operation, operationOptions runtime.Object, dryRun bool, userInfo user.Info) Attributes","file":"staging/src/k8s.io/apiserver/pkg/admission/attributes.go","code":"func NewAttributesRecord(object runtime.Object, oldObject runtime.Object, kind schema.GroupVersionKind, namespace, name string, resource schema.GroupVersionResource, subresource string, operation Operation, operationOptions runtime.Object, dryRun bool, userInfo user.Info) Attributes {\n\treturn \u0026attributesRecord{\n\t\tkind: kind,\n\t\tnamespace: namespace,\n\t\tname: name,\n\t\tresource: resource,\n\t\tsubresource: subresource,\n\t\toperation: operation,\n\t\toptions: operationOptions,\n\t\tdryRun: dryRun,\n\t\tobject: object,\n\t\toldObject: oldObject,\n\t\tuserInfo: userInfo,\n\t\treinvocationContext: \u0026reinvocationContext{},\n\t}\n}","line":{"from":57,"to":72}} {"id":100016409,"name":"GetKind","signature":"func (record *attributesRecord) GetKind() schema.GroupVersionKind","file":"staging/src/k8s.io/apiserver/pkg/admission/attributes.go","code":"func (record *attributesRecord) GetKind() schema.GroupVersionKind {\n\treturn record.kind\n}","line":{"from":74,"to":76}} {"id":100016410,"name":"GetNamespace","signature":"func (record *attributesRecord) GetNamespace() string","file":"staging/src/k8s.io/apiserver/pkg/admission/attributes.go","code":"func (record *attributesRecord) GetNamespace() string {\n\treturn record.namespace\n}","line":{"from":78,"to":80}} {"id":100016411,"name":"GetName","signature":"func (record *attributesRecord) GetName() string","file":"staging/src/k8s.io/apiserver/pkg/admission/attributes.go","code":"func (record *attributesRecord) GetName() string {\n\treturn record.name\n}","line":{"from":82,"to":84}} {"id":100016412,"name":"GetResource","signature":"func (record *attributesRecord) GetResource() schema.GroupVersionResource","file":"staging/src/k8s.io/apiserver/pkg/admission/attributes.go","code":"func (record *attributesRecord) GetResource() schema.GroupVersionResource {\n\treturn record.resource\n}","line":{"from":86,"to":88}} {"id":100016413,"name":"GetSubresource","signature":"func (record *attributesRecord) GetSubresource() string","file":"staging/src/k8s.io/apiserver/pkg/admission/attributes.go","code":"func (record *attributesRecord) GetSubresource() string {\n\treturn record.subresource\n}","line":{"from":90,"to":92}} {"id":100016414,"name":"GetOperation","signature":"func (record *attributesRecord) GetOperation() Operation","file":"staging/src/k8s.io/apiserver/pkg/admission/attributes.go","code":"func (record *attributesRecord) GetOperation() Operation {\n\treturn record.operation\n}","line":{"from":94,"to":96}} {"id":100016415,"name":"GetOperationOptions","signature":"func (record *attributesRecord) GetOperationOptions() runtime.Object","file":"staging/src/k8s.io/apiserver/pkg/admission/attributes.go","code":"func (record *attributesRecord) GetOperationOptions() runtime.Object {\n\treturn record.options\n}","line":{"from":98,"to":100}} {"id":100016416,"name":"IsDryRun","signature":"func (record *attributesRecord) IsDryRun() bool","file":"staging/src/k8s.io/apiserver/pkg/admission/attributes.go","code":"func (record *attributesRecord) IsDryRun() bool {\n\treturn record.dryRun\n}","line":{"from":102,"to":104}} {"id":100016417,"name":"GetObject","signature":"func (record *attributesRecord) GetObject() runtime.Object","file":"staging/src/k8s.io/apiserver/pkg/admission/attributes.go","code":"func (record *attributesRecord) GetObject() runtime.Object {\n\treturn record.object\n}","line":{"from":106,"to":108}} {"id":100016418,"name":"GetOldObject","signature":"func (record *attributesRecord) GetOldObject() runtime.Object","file":"staging/src/k8s.io/apiserver/pkg/admission/attributes.go","code":"func (record *attributesRecord) GetOldObject() runtime.Object {\n\treturn record.oldObject\n}","line":{"from":110,"to":112}} {"id":100016419,"name":"GetUserInfo","signature":"func (record *attributesRecord) GetUserInfo() user.Info","file":"staging/src/k8s.io/apiserver/pkg/admission/attributes.go","code":"func (record *attributesRecord) GetUserInfo() user.Info {\n\treturn record.userInfo\n}","line":{"from":114,"to":116}} {"id":100016420,"name":"getAnnotations","signature":"func (record *attributesRecord) getAnnotations(maxLevel auditinternal.Level) map[string]string","file":"staging/src/k8s.io/apiserver/pkg/admission/attributes.go","code":"// getAnnotations implements privateAnnotationsGetter.It's a private method used\n// by WithAudit decorator.\nfunc (record *attributesRecord) getAnnotations(maxLevel auditinternal.Level) map[string]string {\n\trecord.annotationsLock.RLock()\n\tdefer record.annotationsLock.RUnlock()\n\n\tif record.annotations == nil {\n\t\treturn nil\n\t}\n\tcp := make(map[string]string, len(record.annotations))\n\tfor key, value := range record.annotations {\n\t\tif value.level.Less(maxLevel) || value.level == maxLevel {\n\t\t\tcp[key] = value.value\n\t\t}\n\t}\n\treturn cp\n}","line":{"from":118,"to":134}} {"id":100016421,"name":"AddAnnotation","signature":"func (record *attributesRecord) AddAnnotation(key, value string) error","file":"staging/src/k8s.io/apiserver/pkg/admission/attributes.go","code":"// AddAnnotation adds an annotation to attributesRecord with Metadata audit level\nfunc (record *attributesRecord) AddAnnotation(key, value string) error {\n\treturn record.AddAnnotationWithLevel(key, value, auditinternal.LevelMetadata)\n}","line":{"from":136,"to":139}} {"id":100016422,"name":"AddAnnotationWithLevel","signature":"func (record *attributesRecord) AddAnnotationWithLevel(key, value string, level auditinternal.Level) error","file":"staging/src/k8s.io/apiserver/pkg/admission/attributes.go","code":"func (record *attributesRecord) AddAnnotationWithLevel(key, value string, level auditinternal.Level) error {\n\tif err := checkKeyFormat(key); err != nil {\n\t\treturn err\n\t}\n\tif level.Less(auditinternal.LevelMetadata) {\n\t\treturn fmt.Errorf(\"admission annotations are not allowed to be set at audit level lower than Metadata, key: %q, level: %s\", key, level)\n\t}\n\trecord.annotationsLock.Lock()\n\tdefer record.annotationsLock.Unlock()\n\n\tif record.annotations == nil {\n\t\trecord.annotations = make(map[string]annotation)\n\t}\n\tannotation := annotation{level: level, value: value}\n\tif v, ok := record.annotations[key]; ok \u0026\u0026 v != annotation {\n\t\treturn fmt.Errorf(\"admission annotations are not allowd to be overwritten, key:%q, old value: %v, new value: %v\", key, record.annotations[key], annotation)\n\t}\n\trecord.annotations[key] = annotation\n\treturn nil\n}","line":{"from":141,"to":160}} {"id":100016423,"name":"GetReinvocationContext","signature":"func (record *attributesRecord) GetReinvocationContext() ReinvocationContext","file":"staging/src/k8s.io/apiserver/pkg/admission/attributes.go","code":"func (record *attributesRecord) GetReinvocationContext() ReinvocationContext {\n\treturn record.reinvocationContext\n}","line":{"from":162,"to":164}} {"id":100016424,"name":"IsReinvoke","signature":"func (rc *reinvocationContext) IsReinvoke() bool","file":"staging/src/k8s.io/apiserver/pkg/admission/attributes.go","code":"func (rc *reinvocationContext) IsReinvoke() bool {\n\treturn rc.isReinvoke\n}","line":{"from":175,"to":177}} {"id":100016425,"name":"SetIsReinvoke","signature":"func (rc *reinvocationContext) SetIsReinvoke()","file":"staging/src/k8s.io/apiserver/pkg/admission/attributes.go","code":"func (rc *reinvocationContext) SetIsReinvoke() {\n\trc.isReinvoke = true\n}","line":{"from":179,"to":181}} {"id":100016426,"name":"ShouldReinvoke","signature":"func (rc *reinvocationContext) ShouldReinvoke() bool","file":"staging/src/k8s.io/apiserver/pkg/admission/attributes.go","code":"func (rc *reinvocationContext) ShouldReinvoke() bool {\n\treturn rc.reinvokeRequested\n}","line":{"from":183,"to":185}} {"id":100016427,"name":"SetShouldReinvoke","signature":"func (rc *reinvocationContext) SetShouldReinvoke()","file":"staging/src/k8s.io/apiserver/pkg/admission/attributes.go","code":"func (rc *reinvocationContext) SetShouldReinvoke() {\n\trc.reinvokeRequested = true\n}","line":{"from":187,"to":189}} {"id":100016428,"name":"SetValue","signature":"func (rc *reinvocationContext) SetValue(plugin string, v interface{})","file":"staging/src/k8s.io/apiserver/pkg/admission/attributes.go","code":"func (rc *reinvocationContext) SetValue(plugin string, v interface{}) {\n\tif rc.values == nil {\n\t\trc.values = map[string]interface{}{}\n\t}\n\trc.values[plugin] = v\n}","line":{"from":191,"to":196}} {"id":100016429,"name":"Value","signature":"func (rc *reinvocationContext) Value(plugin string) interface{}","file":"staging/src/k8s.io/apiserver/pkg/admission/attributes.go","code":"func (rc *reinvocationContext) Value(plugin string) interface{} {\n\treturn rc.values[plugin]\n}","line":{"from":198,"to":200}} {"id":100016430,"name":"checkKeyFormat","signature":"func checkKeyFormat(key string) error","file":"staging/src/k8s.io/apiserver/pkg/admission/attributes.go","code":"func checkKeyFormat(key string) error {\n\tparts := strings.Split(key, \"/\")\n\tif len(parts) != 2 {\n\t\treturn fmt.Errorf(\"annotation key has invalid format, the right format is a DNS subdomain prefix and '/' and key name. (e.g. 'podsecuritypolicy.admission.k8s.io/admit-policy')\")\n\t}\n\tif msgs := validation.IsQualifiedName(key); len(msgs) != 0 {\n\t\treturn fmt.Errorf(\"annotation key has invalid format %s. A qualified name like 'podsecuritypolicy.admission.k8s.io/admit-policy' is required.\", strings.Join(msgs, \",\"))\n\t}\n\treturn nil\n}","line":{"from":202,"to":211}} {"id":100016431,"name":"WithAudit","signature":"func WithAudit(i Interface) Interface","file":"staging/src/k8s.io/apiserver/pkg/admission/audit.go","code":"// WithAudit is a decorator for a admission phase. It saves annotations\n// of attribute into the audit event. Attributes passed to the Admit and\n// Validate function must be instance of privateAnnotationsGetter or\n// AnnotationsGetter, otherwise an error is returned.\nfunc WithAudit(i Interface) Interface {\n\tif i == nil {\n\t\treturn i\n\t}\n\treturn \u0026auditHandler{Interface: i}\n}","line":{"from":35,"to":44}} {"id":100016432,"name":"Admit","signature":"func (handler *auditHandler) Admit(ctx context.Context, a Attributes, o ObjectInterfaces) error","file":"staging/src/k8s.io/apiserver/pkg/admission/audit.go","code":"func (handler *auditHandler) Admit(ctx context.Context, a Attributes, o ObjectInterfaces) error {\n\tif !handler.Interface.Handles(a.GetOperation()) {\n\t\treturn nil\n\t}\n\tif err := ensureAnnotationGetter(a); err != nil {\n\t\treturn err\n\t}\n\tvar err error\n\tif mutator, ok := handler.Interface.(MutationInterface); ok {\n\t\terr = mutator.Admit(ctx, a, o)\n\t\thandler.logAnnotations(ctx, a)\n\t}\n\treturn err\n}","line":{"from":46,"to":59}} {"id":100016433,"name":"Validate","signature":"func (handler *auditHandler) Validate(ctx context.Context, a Attributes, o ObjectInterfaces) error","file":"staging/src/k8s.io/apiserver/pkg/admission/audit.go","code":"func (handler *auditHandler) Validate(ctx context.Context, a Attributes, o ObjectInterfaces) error {\n\tif !handler.Interface.Handles(a.GetOperation()) {\n\t\treturn nil\n\t}\n\tif err := ensureAnnotationGetter(a); err != nil {\n\t\treturn err\n\t}\n\tvar err error\n\tif validator, ok := handler.Interface.(ValidationInterface); ok {\n\t\terr = validator.Validate(ctx, a, o)\n\t\thandler.logAnnotations(ctx, a)\n\t}\n\treturn err\n}","line":{"from":61,"to":74}} {"id":100016434,"name":"ensureAnnotationGetter","signature":"func ensureAnnotationGetter(a Attributes) error","file":"staging/src/k8s.io/apiserver/pkg/admission/audit.go","code":"func ensureAnnotationGetter(a Attributes) error {\n\t_, okPrivate := a.(privateAnnotationsGetter)\n\t_, okPublic := a.(AnnotationsGetter)\n\tif okPrivate || okPublic {\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"attributes must be an instance of privateAnnotationsGetter or AnnotationsGetter\")\n}","line":{"from":76,"to":83}} {"id":100016435,"name":"logAnnotations","signature":"func (handler *auditHandler) logAnnotations(ctx context.Context, a Attributes)","file":"staging/src/k8s.io/apiserver/pkg/admission/audit.go","code":"func (handler *auditHandler) logAnnotations(ctx context.Context, a Attributes) {\n\tae := audit.AuditEventFrom(ctx)\n\tif ae == nil {\n\t\treturn\n\t}\n\n\tvar annotations map[string]string\n\tswitch a := a.(type) {\n\tcase privateAnnotationsGetter:\n\t\tannotations = a.getAnnotations(ae.Level)\n\tcase AnnotationsGetter:\n\t\tannotations = a.GetAnnotations(ae.Level)\n\tdefault:\n\t\t// this will never happen, because we have already checked it in ensureAnnotationGetter\n\t}\n\n\taudit.AddAuditAnnotationsMap(ctx, annotations)\n}","line":{"from":85,"to":102}} {"id":100016436,"name":"newValidationAdmissionMetrics","signature":"func newValidationAdmissionMetrics() *ValidatingAdmissionPolicyMetrics","file":"staging/src/k8s.io/apiserver/pkg/admission/cel/metrics.go","code":"func newValidationAdmissionMetrics() *ValidatingAdmissionPolicyMetrics {\n\tcheck := metrics.NewCounterVec(\n\t\t\u0026metrics.CounterOpts{\n\t\t\tNamespace: metricsNamespace,\n\t\t\tSubsystem: metricsSubsystem,\n\t\t\tName: \"check_total\",\n\t\t\tHelp: \"Validation admission policy check total, labeled by policy and further identified by binding, enforcement action taken, and state.\",\n\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t},\n\t\t[]string{\"policy\", \"policy_binding\", \"enforcement_action\", \"state\"},\n\t)\n\tdefinition := metrics.NewCounterVec(\u0026metrics.CounterOpts{\n\t\tNamespace: metricsNamespace,\n\t\tSubsystem: metricsSubsystem,\n\t\tName: \"definition_total\",\n\t\tHelp: \"Validation admission policy count total, labeled by state and enforcement action.\",\n\t\tStabilityLevel: metrics.ALPHA,\n\t},\n\t\t[]string{\"state\", \"enforcement_action\"},\n\t)\n\tlatency := metrics.NewHistogramVec(\u0026metrics.HistogramOpts{\n\t\tNamespace: metricsNamespace,\n\t\tSubsystem: metricsSubsystem,\n\t\tName: \"check_duration_seconds\",\n\t\tHelp: \"Validation admission latency for individual validation expressions in seconds, labeled by policy and further including binding, state and enforcement action taken.\",\n\t\t// the bucket distribution here is based oo the benchmark suite at\n\t\t// github.com/DangerOnTheRanger/cel-benchmark performed on 16-core Intel Xeon\n\t\t// the lowest bucket was based around the 180ns/op figure for BenchmarkAccess,\n\t\t// plus some additional leeway to account for the apiserver doing other things\n\t\t// the largest bucket was chosen based on the fact that benchmarks indicate the\n\t\t// same Xeon running a CEL expression close to the estimated cost limit takes\n\t\t// around 760ms, so that bucket should only ever have the slowest CEL expressions\n\t\t// in it\n\t\tBuckets: []float64{0.0000005, 0.001, 0.01, 0.1, 1.0},\n\t\tStabilityLevel: metrics.ALPHA,\n\t},\n\t\t[]string{\"policy\", \"policy_binding\", \"enforcement_action\", \"state\"},\n\t)\n\n\tlegacyregistry.MustRegister(check)\n\tlegacyregistry.MustRegister(definition)\n\tlegacyregistry.MustRegister(latency)\n\treturn \u0026ValidatingAdmissionPolicyMetrics{policyCheck: check, policyDefinition: definition, policyLatency: latency}\n}","line":{"from":44,"to":87}} {"id":100016437,"name":"Reset","signature":"func (m *ValidatingAdmissionPolicyMetrics) Reset()","file":"staging/src/k8s.io/apiserver/pkg/admission/cel/metrics.go","code":"// Reset resets all validation admission-related Prometheus metrics.\nfunc (m *ValidatingAdmissionPolicyMetrics) Reset() {\n\tm.policyCheck.Reset()\n\tm.policyDefinition.Reset()\n\tm.policyLatency.Reset()\n}","line":{"from":89,"to":94}} {"id":100016438,"name":"ObserveDefinition","signature":"func (m *ValidatingAdmissionPolicyMetrics) ObserveDefinition(ctx context.Context, state, enforcementAction string)","file":"staging/src/k8s.io/apiserver/pkg/admission/cel/metrics.go","code":"// ObserveDefinition observes a policy definition.\nfunc (m *ValidatingAdmissionPolicyMetrics) ObserveDefinition(ctx context.Context, state, enforcementAction string) {\n\tm.policyDefinition.WithContext(ctx).WithLabelValues(state, enforcementAction).Inc()\n}","line":{"from":96,"to":99}} {"id":100016439,"name":"ObserveAdmissionWithError","signature":"func (m *ValidatingAdmissionPolicyMetrics) ObserveAdmissionWithError(ctx context.Context, elapsed time.Duration, policy, binding, state string)","file":"staging/src/k8s.io/apiserver/pkg/admission/cel/metrics.go","code":"// ObserveAdmissionWithError observes a policy validation error that was ignored due to failure policy.\nfunc (m *ValidatingAdmissionPolicyMetrics) ObserveAdmissionWithError(ctx context.Context, elapsed time.Duration, policy, binding, state string) {\n\tm.policyCheck.WithContext(ctx).WithLabelValues(policy, binding, \"allow\", state).Inc()\n\tm.policyLatency.WithContext(ctx).WithLabelValues(policy, binding, \"allow\", state).Observe(elapsed.Seconds())\n}","line":{"from":101,"to":105}} {"id":100016440,"name":"ObserveRejection","signature":"func (m *ValidatingAdmissionPolicyMetrics) ObserveRejection(ctx context.Context, elapsed time.Duration, policy, binding, state string)","file":"staging/src/k8s.io/apiserver/pkg/admission/cel/metrics.go","code":"// ObserveRejection observes a policy validation error that was at least one of the reasons for a deny.\nfunc (m *ValidatingAdmissionPolicyMetrics) ObserveRejection(ctx context.Context, elapsed time.Duration, policy, binding, state string) {\n\tm.policyCheck.WithContext(ctx).WithLabelValues(policy, binding, \"deny\", state).Inc()\n\tm.policyLatency.WithContext(ctx).WithLabelValues(policy, binding, \"deny\", state).Observe(elapsed.Seconds())\n}","line":{"from":107,"to":111}} {"id":100016441,"name":"ObserveAudit","signature":"func (m *ValidatingAdmissionPolicyMetrics) ObserveAudit(ctx context.Context, elapsed time.Duration, policy, binding, state string)","file":"staging/src/k8s.io/apiserver/pkg/admission/cel/metrics.go","code":"// ObserveAudit observes a policy validation audit annotation was published for a validation failure.\nfunc (m *ValidatingAdmissionPolicyMetrics) ObserveAudit(ctx context.Context, elapsed time.Duration, policy, binding, state string) {\n\tm.policyCheck.WithContext(ctx).WithLabelValues(policy, binding, \"audit\", state).Inc()\n\tm.policyLatency.WithContext(ctx).WithLabelValues(policy, binding, \"audit\", state).Observe(elapsed.Seconds())\n}","line":{"from":113,"to":117}} {"id":100016442,"name":"ObserveWarn","signature":"func (m *ValidatingAdmissionPolicyMetrics) ObserveWarn(ctx context.Context, elapsed time.Duration, policy, binding, state string)","file":"staging/src/k8s.io/apiserver/pkg/admission/cel/metrics.go","code":"// ObserveWarn observes a policy validation warning was published for a validation failure.\nfunc (m *ValidatingAdmissionPolicyMetrics) ObserveWarn(ctx context.Context, elapsed time.Duration, policy, binding, state string) {\n\tm.policyCheck.WithContext(ctx).WithLabelValues(policy, binding, \"warn\", state).Inc()\n\tm.policyLatency.WithContext(ctx).WithLabelValues(policy, binding, \"warn\", state).Observe(elapsed.Seconds())\n}","line":{"from":119,"to":123}} {"id":100016443,"name":"NewChainHandler","signature":"func NewChainHandler(handlers ...Interface) chainAdmissionHandler","file":"staging/src/k8s.io/apiserver/pkg/admission/chain.go","code":"// NewChainHandler creates a new chain handler from an array of handlers. Used for testing.\nfunc NewChainHandler(handlers ...Interface) chainAdmissionHandler {\n\treturn chainAdmissionHandler(handlers)\n}","line":{"from":25,"to":28}} {"id":100016444,"name":"Admit","signature":"func (admissionHandler chainAdmissionHandler) Admit(ctx context.Context, a Attributes, o ObjectInterfaces) error","file":"staging/src/k8s.io/apiserver/pkg/admission/chain.go","code":"// Admit performs an admission control check using a chain of handlers, and returns immediately on first error\nfunc (admissionHandler chainAdmissionHandler) Admit(ctx context.Context, a Attributes, o ObjectInterfaces) error {\n\tfor _, handler := range admissionHandler {\n\t\tif !handler.Handles(a.GetOperation()) {\n\t\t\tcontinue\n\t\t}\n\t\tif mutator, ok := handler.(MutationInterface); ok {\n\t\t\terr := mutator.Admit(ctx, a, o)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":30,"to":44}} {"id":100016445,"name":"Validate","signature":"func (admissionHandler chainAdmissionHandler) Validate(ctx context.Context, a Attributes, o ObjectInterfaces) error","file":"staging/src/k8s.io/apiserver/pkg/admission/chain.go","code":"// Validate performs an admission control check using a chain of handlers, and returns immediately on first error\nfunc (admissionHandler chainAdmissionHandler) Validate(ctx context.Context, a Attributes, o ObjectInterfaces) error {\n\tfor _, handler := range admissionHandler {\n\t\tif !handler.Handles(a.GetOperation()) {\n\t\t\tcontinue\n\t\t}\n\t\tif validator, ok := handler.(ValidationInterface); ok {\n\t\t\terr := validator.Validate(ctx, a, o)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":46,"to":60}} {"id":100016446,"name":"Handles","signature":"func (admissionHandler chainAdmissionHandler) Handles(operation Operation) bool","file":"staging/src/k8s.io/apiserver/pkg/admission/chain.go","code":"// Handles will return true if any of the handlers handles the given operation\nfunc (admissionHandler chainAdmissionHandler) Handles(operation Operation) bool {\n\tfor _, handler := range admissionHandler {\n\t\tif handler.Handles(operation) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":62,"to":70}} {"id":100016447,"name":"makeAbs","signature":"func makeAbs(path, base string) (string, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/config.go","code":"func makeAbs(path, base string) (string, error) {\n\tif filepath.IsAbs(path) {\n\t\treturn path, nil\n\t}\n\tif len(base) == 0 || base == \".\" {\n\t\tcwd, err := os.Getwd()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tbase = cwd\n\t}\n\treturn filepath.Join(base, path), nil\n}","line":{"from":38,"to":50}} {"id":100016448,"name":"ReadAdmissionConfiguration","signature":"func ReadAdmissionConfiguration(pluginNames []string, configFilePath string, configScheme *runtime.Scheme) (ConfigProvider, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/config.go","code":"// ReadAdmissionConfiguration reads the admission configuration at the specified path.\n// It returns the loaded admission configuration if the input file aligns with the required syntax.\n// If it does not align with the provided syntax, it returns a default configuration for the enumerated\n// set of pluginNames whose config location references the specified configFilePath.\n// It does this to preserve backward compatibility when admission control files were opaque.\n// It returns an error if the file did not exist.\nfunc ReadAdmissionConfiguration(pluginNames []string, configFilePath string, configScheme *runtime.Scheme) (ConfigProvider, error) {\n\tif configFilePath == \"\" {\n\t\treturn configProvider{config: \u0026apiserver.AdmissionConfiguration{}}, nil\n\t}\n\t// a file was provided, so we just read it.\n\tdata, err := ioutil.ReadFile(configFilePath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to read admission control configuration from %q [%v]\", configFilePath, err)\n\t}\n\tcodecs := serializer.NewCodecFactory(configScheme)\n\tdecoder := codecs.UniversalDecoder()\n\tdecodedObj, err := runtime.Decode(decoder, data)\n\t// we were able to decode the file successfully\n\tif err == nil {\n\t\tdecodedConfig, ok := decodedObj.(*apiserver.AdmissionConfiguration)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"unexpected type: %T\", decodedObj)\n\t\t}\n\t\tbaseDir := path.Dir(configFilePath)\n\t\tfor i := range decodedConfig.Plugins {\n\t\t\tif decodedConfig.Plugins[i].Path == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// we update relative file paths to absolute paths\n\t\t\tabsPath, err := makeAbs(decodedConfig.Plugins[i].Path, baseDir)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdecodedConfig.Plugins[i].Path = absPath\n\t\t}\n\t\treturn configProvider{\n\t\t\tconfig: decodedConfig,\n\t\t}, nil\n\t}\n\t// we got an error where the decode wasn't related to a missing type\n\tif !(runtime.IsMissingVersion(err) || runtime.IsMissingKind(err) || runtime.IsNotRegisteredError(err)) {\n\t\treturn nil, err\n\t}\n\n\t// Only tolerate load errors if the file appears to be one of the two legacy plugin configs\n\tunstructuredData := map[string]interface{}{}\n\tif err2 := yaml.Unmarshal(data, \u0026unstructuredData); err2 != nil {\n\t\treturn nil, err\n\t}\n\t_, isLegacyImagePolicy := unstructuredData[\"imagePolicy\"]\n\t_, isLegacyPodNodeSelector := unstructuredData[\"podNodeSelectorPluginConfig\"]\n\tif !isLegacyImagePolicy \u0026\u0026 !isLegacyPodNodeSelector {\n\t\treturn nil, err\n\t}\n\n\t// convert the legacy format to the new admission control format\n\t// in order to preserve backwards compatibility, we set plugins that\n\t// previously read input from a non-versioned file configuration to the\n\t// current input file.\n\tlegacyPluginsWithUnversionedConfig := sets.NewString(\"ImagePolicyWebhook\", \"PodNodeSelector\")\n\texternalConfig := \u0026apiserverv1.AdmissionConfiguration{}\n\tfor _, pluginName := range pluginNames {\n\t\tif legacyPluginsWithUnversionedConfig.Has(pluginName) {\n\t\t\texternalConfig.Plugins = append(externalConfig.Plugins,\n\t\t\t\tapiserverv1.AdmissionPluginConfiguration{\n\t\t\t\t\tName: pluginName,\n\t\t\t\t\tPath: configFilePath})\n\t\t}\n\t}\n\tconfigScheme.Default(externalConfig)\n\tinternalConfig := \u0026apiserver.AdmissionConfiguration{}\n\tif err := configScheme.Convert(externalConfig, internalConfig, nil); err != nil {\n\t\treturn nil, err\n\t}\n\treturn configProvider{\n\t\tconfig: internalConfig,\n\t}, nil\n}","line":{"from":52,"to":130}} {"id":100016449,"name":"GetAdmissionPluginConfigurationFor","signature":"func GetAdmissionPluginConfigurationFor(pluginCfg apiserver.AdmissionPluginConfiguration) (io.Reader, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/config.go","code":"// GetAdmissionPluginConfigurationFor returns a reader that holds the admission plugin configuration.\nfunc GetAdmissionPluginConfigurationFor(pluginCfg apiserver.AdmissionPluginConfiguration) (io.Reader, error) {\n\t// if there is a nest object, return it directly\n\tif pluginCfg.Configuration != nil {\n\t\treturn bytes.NewBuffer(pluginCfg.Configuration.Raw), nil\n\t}\n\t// there is nothing nested, so we delegate to path\n\tif pluginCfg.Path != \"\" {\n\t\tcontent, err := ioutil.ReadFile(pluginCfg.Path)\n\t\tif err != nil {\n\t\t\tklog.Fatalf(\"Couldn't open admission plugin configuration %s: %#v\", pluginCfg.Path, err)\n\t\t\treturn nil, err\n\t\t}\n\t\treturn bytes.NewBuffer(content), nil\n\t}\n\t// there is no special config at all\n\treturn nil, nil\n}","line":{"from":136,"to":153}} {"id":100016450,"name":"ConfigFor","signature":"func (p configProvider) ConfigFor(pluginName string) (io.Reader, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/config.go","code":"// ConfigFor returns a reader for the specified plugin.\n// If no specific configuration is present, we return a nil reader.\nfunc (p configProvider) ConfigFor(pluginName string) (io.Reader, error) {\n\t// there is no config, so there is no potential config\n\tif p.config == nil {\n\t\treturn nil, nil\n\t}\n\t// look for matching plugin and get configuration\n\tfor _, pluginCfg := range p.config.Plugins {\n\t\tif pluginName != pluginCfg.Name {\n\t\t\tcontinue\n\t\t}\n\t\tpluginConfig, err := GetAdmissionPluginConfigurationFor(pluginCfg)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn pluginConfig, nil\n\t}\n\t// there is no registered config that matches on plugin name.\n\treturn nil, nil\n}","line":{"from":155,"to":175}} {"id":100016451,"name":"newPoller","signature":"func newPoller(get getFunc) *poller","file":"staging/src/k8s.io/apiserver/pkg/admission/configuration/configuration_manager.go","code":"func newPoller(get getFunc) *poller {\n\tp := poller{\n\t\tget: get,\n\t\tinterval: defaultInterval,\n\t\tfailureThreshold: defaultFailureThreshold,\n\t\tbootstrapRetries: defaultBootstrapRetries,\n\t\tbootstrapGracePeriod: defaultBootstrapGraceperiod,\n\t}\n\treturn \u0026p\n}","line":{"from":80,"to":89}} {"id":100016452,"name":"lastError","signature":"func (a *poller) lastError(err error)","file":"staging/src/k8s.io/apiserver/pkg/admission/configuration/configuration_manager.go","code":"func (a *poller) lastError(err error) {\n\ta.lock.Lock()\n\tdefer a.lock.Unlock()\n\ta.lastErr = err\n}","line":{"from":91,"to":95}} {"id":100016453,"name":"notReady","signature":"func (a *poller) notReady()","file":"staging/src/k8s.io/apiserver/pkg/admission/configuration/configuration_manager.go","code":"func (a *poller) notReady() {\n\ta.lock.Lock()\n\tdefer a.lock.Unlock()\n\ta.ready = false\n}","line":{"from":97,"to":101}} {"id":100016454,"name":"bootstrapping","signature":"func (a *poller) bootstrapping()","file":"staging/src/k8s.io/apiserver/pkg/admission/configuration/configuration_manager.go","code":"func (a *poller) bootstrapping() {\n\t// bootstrapGracePeriod is read-only, so no lock is required\n\ttimer := time.NewTimer(a.bootstrapGracePeriod)\n\tgo func() {\n\t\tdefer timer.Stop()\n\t\t\u003c-timer.C\n\t\ta.lock.Lock()\n\t\tdefer a.lock.Unlock()\n\t\ta.bootstrapped = true\n\t}()\n}","line":{"from":103,"to":113}} {"id":100016455,"name":"configuration","signature":"func (a *poller) configuration() (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/configuration/configuration_manager.go","code":"// If the poller is not bootstrapped yet, the configuration() gets a few chances\n// to retry. This hides transient failures during system startup.\nfunc (a *poller) configuration() (runtime.Object, error) {\n\ta.once.Do(a.bootstrapping)\n\ta.lock.RLock()\n\tdefer a.lock.RUnlock()\n\tretries := 1\n\tif !a.bootstrapped {\n\t\tretries = a.bootstrapRetries\n\t}\n\tfor count := 0; count \u003c retries; count++ {\n\t\tif count \u003e 0 {\n\t\t\ta.lock.RUnlock()\n\t\t\ttime.Sleep(a.interval)\n\t\t\ta.lock.RLock()\n\t\t}\n\t\tif a.ready {\n\t\t\treturn a.mergedConfiguration, nil\n\t\t}\n\t}\n\tif a.lastErr != nil {\n\t\treturn nil, a.lastErr\n\t}\n\treturn nil, ErrNotReady\n}","line":{"from":115,"to":139}} {"id":100016456,"name":"setConfigurationAndReady","signature":"func (a *poller) setConfigurationAndReady(value runtime.Object)","file":"staging/src/k8s.io/apiserver/pkg/admission/configuration/configuration_manager.go","code":"func (a *poller) setConfigurationAndReady(value runtime.Object) {\n\ta.lock.Lock()\n\tdefer a.lock.Unlock()\n\ta.bootstrapped = true\n\ta.mergedConfiguration = value\n\ta.ready = true\n\ta.lastErr = nil\n}","line":{"from":141,"to":148}} {"id":100016457,"name":"Run","signature":"func (a *poller) Run(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/apiserver/pkg/admission/configuration/configuration_manager.go","code":"func (a *poller) Run(stopCh \u003c-chan struct{}) {\n\tgo wait.Until(a.sync, a.interval, stopCh)\n}","line":{"from":150,"to":152}} {"id":100016458,"name":"sync","signature":"func (a *poller) sync()","file":"staging/src/k8s.io/apiserver/pkg/admission/configuration/configuration_manager.go","code":"func (a *poller) sync() {\n\tconfiguration, err := a.get()\n\tif err != nil {\n\t\ta.failures++\n\t\ta.lastError(err)\n\t\tif a.failures \u003e= a.failureThreshold {\n\t\t\ta.notReady()\n\t\t}\n\t\treturn\n\t}\n\ta.failures = 0\n\ta.setConfigurationAndReady(configuration)\n}","line":{"from":154,"to":166}} {"id":100016459,"name":"NewMutatingWebhookConfigurationManager","signature":"func NewMutatingWebhookConfigurationManager(f informers.SharedInformerFactory) generic.Source","file":"staging/src/k8s.io/apiserver/pkg/admission/configuration/mutating_webhook_manager.go","code":"func NewMutatingWebhookConfigurationManager(f informers.SharedInformerFactory) generic.Source {\n\tinformer := f.Admissionregistration().V1().MutatingWebhookConfigurations()\n\tmanager := \u0026mutatingWebhookConfigurationManager{\n\t\tlister: informer.Lister(),\n\t}\n\tmanager.lazy.Evaluate = manager.getConfiguration\n\n\thandle, _ := informer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(_ interface{}) { manager.lazy.Notify() },\n\t\tUpdateFunc: func(_, _ interface{}) { manager.lazy.Notify() },\n\t\tDeleteFunc: func(_ interface{}) { manager.lazy.Notify() },\n\t})\n\tmanager.hasSynced = handle.HasSynced\n\n\treturn manager\n}","line":{"from":43,"to":58}} {"id":100016460,"name":"Webhooks","signature":"func (m *mutatingWebhookConfigurationManager) Webhooks() []webhook.WebhookAccessor","file":"staging/src/k8s.io/apiserver/pkg/admission/configuration/mutating_webhook_manager.go","code":"// Webhooks returns the merged MutatingWebhookConfiguration.\nfunc (m *mutatingWebhookConfigurationManager) Webhooks() []webhook.WebhookAccessor {\n\tout, err := m.lazy.Get()\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"error getting webhook configuration: %v\", err))\n\t}\n\treturn out\n}","line":{"from":60,"to":67}} {"id":100016461,"name":"HasSynced","signature":"func (m *mutatingWebhookConfigurationManager) HasSynced() bool { return m.hasSynced() }","file":"staging/src/k8s.io/apiserver/pkg/admission/configuration/mutating_webhook_manager.go","code":"// HasSynced returns true if the initial set of mutating webhook configurations\n// has been loaded.\nfunc (m *mutatingWebhookConfigurationManager) HasSynced() bool { return m.hasSynced() }","line":{"from":69,"to":71}} {"id":100016462,"name":"getConfiguration","signature":"func (m *mutatingWebhookConfigurationManager) getConfiguration() ([]webhook.WebhookAccessor, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/configuration/mutating_webhook_manager.go","code":"func (m *mutatingWebhookConfigurationManager) getConfiguration() ([]webhook.WebhookAccessor, error) {\n\tconfigurations, err := m.lister.List(labels.Everything())\n\tif err != nil {\n\t\treturn []webhook.WebhookAccessor{}, err\n\t}\n\treturn mergeMutatingWebhookConfigurations(configurations), nil\n}","line":{"from":73,"to":79}} {"id":100016463,"name":"mergeMutatingWebhookConfigurations","signature":"func mergeMutatingWebhookConfigurations(configurations []*v1.MutatingWebhookConfiguration) []webhook.WebhookAccessor","file":"staging/src/k8s.io/apiserver/pkg/admission/configuration/mutating_webhook_manager.go","code":"func mergeMutatingWebhookConfigurations(configurations []*v1.MutatingWebhookConfiguration) []webhook.WebhookAccessor {\n\t// The internal order of webhooks for each configuration is provided by the user\n\t// but configurations themselves can be in any order. As we are going to run these\n\t// webhooks in serial, they are sorted here to have a deterministic order.\n\tsort.SliceStable(configurations, MutatingWebhookConfigurationSorter(configurations).ByName)\n\taccessors := []webhook.WebhookAccessor{}\n\tfor _, c := range configurations {\n\t\t// webhook names are not validated for uniqueness, so we check for duplicates and\n\t\t// add a int suffix to distinguish between them\n\t\tnames := map[string]int{}\n\t\tfor i := range c.Webhooks {\n\t\t\tn := c.Webhooks[i].Name\n\t\t\tuid := fmt.Sprintf(\"%s/%s/%d\", c.Name, n, names[n])\n\t\t\tnames[n]++\n\t\t\taccessors = append(accessors, webhook.NewMutatingWebhookAccessor(uid, c.Name, \u0026c.Webhooks[i]))\n\t\t}\n\t}\n\treturn accessors\n}","line":{"from":81,"to":99}} {"id":100016464,"name":"ByName","signature":"func (a MutatingWebhookConfigurationSorter) ByName(i, j int) bool","file":"staging/src/k8s.io/apiserver/pkg/admission/configuration/mutating_webhook_manager.go","code":"func (a MutatingWebhookConfigurationSorter) ByName(i, j int) bool {\n\treturn a[i].Name \u003c a[j].Name\n}","line":{"from":103,"to":105}} {"id":100016465,"name":"NewValidatingWebhookConfigurationManager","signature":"func NewValidatingWebhookConfigurationManager(f informers.SharedInformerFactory) generic.Source","file":"staging/src/k8s.io/apiserver/pkg/admission/configuration/validating_webhook_manager.go","code":"func NewValidatingWebhookConfigurationManager(f informers.SharedInformerFactory) generic.Source {\n\tinformer := f.Admissionregistration().V1().ValidatingWebhookConfigurations()\n\tmanager := \u0026validatingWebhookConfigurationManager{\n\t\tlister: informer.Lister(),\n\t}\n\tmanager.lazy.Evaluate = manager.getConfiguration\n\n\thandle, _ := informer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(_ interface{}) { manager.lazy.Notify() },\n\t\tUpdateFunc: func(_, _ interface{}) { manager.lazy.Notify() },\n\t\tDeleteFunc: func(_ interface{}) { manager.lazy.Notify() },\n\t})\n\tmanager.hasSynced = handle.HasSynced\n\n\treturn manager\n}","line":{"from":43,"to":58}} {"id":100016466,"name":"Webhooks","signature":"func (v *validatingWebhookConfigurationManager) Webhooks() []webhook.WebhookAccessor","file":"staging/src/k8s.io/apiserver/pkg/admission/configuration/validating_webhook_manager.go","code":"// Webhooks returns the merged ValidatingWebhookConfiguration.\nfunc (v *validatingWebhookConfigurationManager) Webhooks() []webhook.WebhookAccessor {\n\tout, err := v.lazy.Get()\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"error getting webhook configuration: %v\", err))\n\t}\n\treturn out\n}","line":{"from":60,"to":67}} {"id":100016467,"name":"HasSynced","signature":"func (v *validatingWebhookConfigurationManager) HasSynced() bool { return v.hasSynced() }","file":"staging/src/k8s.io/apiserver/pkg/admission/configuration/validating_webhook_manager.go","code":"// HasSynced returns true if the initial set of mutating webhook configurations\n// has been loaded.\nfunc (v *validatingWebhookConfigurationManager) HasSynced() bool { return v.hasSynced() }","line":{"from":69,"to":71}} {"id":100016468,"name":"getConfiguration","signature":"func (v *validatingWebhookConfigurationManager) getConfiguration() ([]webhook.WebhookAccessor, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/configuration/validating_webhook_manager.go","code":"func (v *validatingWebhookConfigurationManager) getConfiguration() ([]webhook.WebhookAccessor, error) {\n\tconfigurations, err := v.lister.List(labels.Everything())\n\tif err != nil {\n\t\treturn []webhook.WebhookAccessor{}, err\n\t}\n\treturn mergeValidatingWebhookConfigurations(configurations), nil\n}","line":{"from":73,"to":79}} {"id":100016469,"name":"mergeValidatingWebhookConfigurations","signature":"func mergeValidatingWebhookConfigurations(configurations []*v1.ValidatingWebhookConfiguration) []webhook.WebhookAccessor","file":"staging/src/k8s.io/apiserver/pkg/admission/configuration/validating_webhook_manager.go","code":"func mergeValidatingWebhookConfigurations(configurations []*v1.ValidatingWebhookConfiguration) []webhook.WebhookAccessor {\n\tsort.SliceStable(configurations, ValidatingWebhookConfigurationSorter(configurations).ByName)\n\taccessors := []webhook.WebhookAccessor{}\n\tfor _, c := range configurations {\n\t\t// webhook names are not validated for uniqueness, so we check for duplicates and\n\t\t// add a int suffix to distinguish between them\n\t\tnames := map[string]int{}\n\t\tfor i := range c.Webhooks {\n\t\t\tn := c.Webhooks[i].Name\n\t\t\tuid := fmt.Sprintf(\"%s/%s/%d\", c.Name, n, names[n])\n\t\t\tnames[n]++\n\t\t\taccessors = append(accessors, webhook.NewValidatingWebhookAccessor(uid, c.Name, \u0026c.Webhooks[i]))\n\t\t}\n\t}\n\treturn accessors\n}","line":{"from":81,"to":96}} {"id":100016470,"name":"ByName","signature":"func (a ValidatingWebhookConfigurationSorter) ByName(i, j int) bool","file":"staging/src/k8s.io/apiserver/pkg/admission/configuration/validating_webhook_manager.go","code":"func (a ValidatingWebhookConfigurationSorter) ByName(i, j int) bool {\n\treturn a[i].Name \u003c a[j].Name\n}","line":{"from":100,"to":102}} {"id":100016471,"name":"GetObject","signature":"func (v *VersionedAttributes) GetObject() runtime.Object","file":"staging/src/k8s.io/apiserver/pkg/admission/conversion.go","code":"// GetObject overrides the Attributes.GetObject()\nfunc (v *VersionedAttributes) GetObject() runtime.Object {\n\tif v.VersionedObject != nil {\n\t\treturn v.VersionedObject\n\t}\n\treturn v.Attributes.GetObject()\n}","line":{"from":41,"to":47}} {"id":100016472,"name":"ConvertToGVK","signature":"func ConvertToGVK(obj runtime.Object, gvk schema.GroupVersionKind, o ObjectInterfaces) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/conversion.go","code":"// ConvertToGVK converts object to the desired gvk.\nfunc ConvertToGVK(obj runtime.Object, gvk schema.GroupVersionKind, o ObjectInterfaces) (runtime.Object, error) {\n\t// Unlike other resources, custom resources do not have internal version, so\n\t// if obj is a custom resource, it should not need conversion.\n\tif obj.GetObjectKind().GroupVersionKind() == gvk {\n\t\treturn obj, nil\n\t}\n\tout, err := o.GetObjectCreater().New(gvk)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = o.GetObjectConvertor().Convert(obj, out, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Explicitly set the GVK\n\tout.GetObjectKind().SetGroupVersionKind(gvk)\n\treturn out, nil\n}","line":{"from":49,"to":67}} {"id":100016473,"name":"NewVersionedAttributes","signature":"func NewVersionedAttributes(attr Attributes, gvk schema.GroupVersionKind, o ObjectInterfaces) (*VersionedAttributes, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/conversion.go","code":"// NewVersionedAttributes returns versioned attributes with the old and new object (if non-nil) converted to the requested kind\nfunc NewVersionedAttributes(attr Attributes, gvk schema.GroupVersionKind, o ObjectInterfaces) (*VersionedAttributes, error) {\n\t// convert the old and new objects to the requested version\n\tversionedAttr := \u0026VersionedAttributes{\n\t\tAttributes: attr,\n\t\tVersionedKind: gvk,\n\t}\n\tif oldObj := attr.GetOldObject(); oldObj != nil {\n\t\tout, err := ConvertToGVK(oldObj, gvk, o)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tversionedAttr.VersionedOldObject = out\n\t}\n\tif obj := attr.GetObject(); obj != nil {\n\t\tout, err := ConvertToGVK(obj, gvk, o)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tversionedAttr.VersionedObject = out\n\t}\n\treturn versionedAttr, nil\n}","line":{"from":69,"to":91}} {"id":100016474,"name":"ConvertVersionedAttributes","signature":"func ConvertVersionedAttributes(attr *VersionedAttributes, gvk schema.GroupVersionKind, o ObjectInterfaces) error","file":"staging/src/k8s.io/apiserver/pkg/admission/conversion.go","code":"// ConvertVersionedAttributes converts VersionedObject and VersionedOldObject to the specified kind, if needed.\n// If attr.VersionedKind already matches the requested kind, no conversion is performed.\n// If conversion is required:\n// * attr.VersionedObject is used as the source for the new object if Dirty=true (and is round-tripped through attr.Attributes.Object, clearing Dirty in the process)\n// * attr.Attributes.Object is used as the source for the new object if Dirty=false\n// * attr.Attributes.OldObject is used as the source for the old object\nfunc ConvertVersionedAttributes(attr *VersionedAttributes, gvk schema.GroupVersionKind, o ObjectInterfaces) error {\n\t// we already have the desired kind, we're done\n\tif attr.VersionedKind == gvk {\n\t\treturn nil\n\t}\n\n\t// convert the original old object to the desired GVK\n\tif oldObj := attr.Attributes.GetOldObject(); oldObj != nil {\n\t\tout, err := ConvertToGVK(oldObj, gvk, o)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tattr.VersionedOldObject = out\n\t}\n\n\tif attr.VersionedObject != nil {\n\t\t// convert the existing versioned object to internal\n\t\tif attr.Dirty {\n\t\t\terr := o.GetObjectConvertor().Convert(attr.VersionedObject, attr.Attributes.GetObject(), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// and back to external\n\t\tout, err := ConvertToGVK(attr.Attributes.GetObject(), gvk, o)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tattr.VersionedObject = out\n\t}\n\n\t// Remember we converted to this version\n\tattr.VersionedKind = gvk\n\tattr.Dirty = false\n\n\treturn nil\n}","line":{"from":93,"to":136}} {"id":100016475,"name":"Decorate","signature":"func (d DecoratorFunc) Decorate(handler Interface, name string) Interface","file":"staging/src/k8s.io/apiserver/pkg/admission/decorator.go","code":"func (d DecoratorFunc) Decorate(handler Interface, name string) Interface {\n\treturn d(handler, name)\n}","line":{"from":25,"to":27}} {"id":100016476,"name":"Decorate","signature":"func (d Decorators) Decorate(handler Interface, name string) Interface","file":"staging/src/k8s.io/apiserver/pkg/admission/decorator.go","code":"// Decorate applies the decorator in inside-out order, i.e. the first decorator in the slice is first applied to the given handler.\nfunc (d Decorators) Decorate(handler Interface, name string) Interface {\n\tresult := handler\n\tfor _, d := range d {\n\t\tresult = d.Decorate(result, name)\n\t}\n\n\treturn result\n}","line":{"from":31,"to":39}} {"id":100016477,"name":"extractResourceName","signature":"func extractResourceName(a Attributes) (name string, resource schema.GroupResource, err error)","file":"staging/src/k8s.io/apiserver/pkg/admission/errors.go","code":"func extractResourceName(a Attributes) (name string, resource schema.GroupResource, err error) {\n\tresource = a.GetResource().GroupResource()\n\n\tif len(a.GetName()) \u003e 0 {\n\t\treturn a.GetName(), resource, nil\n\t}\n\n\tname = \"Unknown\"\n\tobj := a.GetObject()\n\tif obj != nil {\n\t\taccessor, err := meta.Accessor(obj)\n\t\tif err != nil {\n\t\t\t// not all object have ObjectMeta. If we don't, return a name with a slash (always illegal)\n\t\t\treturn \"Unknown/errorGettingName\", resource, nil\n\t\t}\n\n\t\t// this is necessary because name object name generation has not occurred yet\n\t\tif len(accessor.GetName()) \u003e 0 {\n\t\t\tname = accessor.GetName()\n\t\t} else if len(accessor.GetGenerateName()) \u003e 0 {\n\t\t\tname = accessor.GetGenerateName()\n\t\t}\n\t}\n\treturn name, resource, nil\n}","line":{"from":26,"to":50}} {"id":100016478,"name":"NewForbidden","signature":"func NewForbidden(a Attributes, internalError error) error","file":"staging/src/k8s.io/apiserver/pkg/admission/errors.go","code":"// NewForbidden is a utility function to return a well-formatted admission control error response\nfunc NewForbidden(a Attributes, internalError error) error {\n\t// do not double wrap an error of same type\n\tif apierrors.IsForbidden(internalError) {\n\t\treturn internalError\n\t}\n\tname, resource, err := extractResourceName(a)\n\tif err != nil {\n\t\treturn apierrors.NewInternalError(utilerrors.NewAggregate([]error{internalError, err}))\n\t}\n\treturn apierrors.NewForbidden(resource, name, internalError)\n}","line":{"from":52,"to":63}} {"id":100016479,"name":"NewNotFound","signature":"func NewNotFound(a Attributes) error","file":"staging/src/k8s.io/apiserver/pkg/admission/errors.go","code":"// NewNotFound is a utility function to return a well-formatted admission control error response\nfunc NewNotFound(a Attributes) error {\n\tname, resource, err := extractResourceName(a)\n\tif err != nil {\n\t\treturn apierrors.NewInternalError(err)\n\t}\n\treturn apierrors.NewNotFound(resource, name)\n}","line":{"from":65,"to":72}} {"id":100016480,"name":"Handles","signature":"func (h *Handler) Handles(operation Operation) bool","file":"staging/src/k8s.io/apiserver/pkg/admission/handler.go","code":"// Handles returns true for methods that this handler supports\nfunc (h *Handler) Handles(operation Operation) bool {\n\treturn h.operations.Has(string(operation))\n}","line":{"from":41,"to":44}} {"id":100016481,"name":"NewHandler","signature":"func NewHandler(ops ...Operation) *Handler","file":"staging/src/k8s.io/apiserver/pkg/admission/handler.go","code":"// NewHandler creates a new base handler that handles the passed\n// in operations\nfunc NewHandler(ops ...Operation) *Handler {\n\toperations := sets.NewString()\n\tfor _, op := range ops {\n\t\toperations.Insert(string(op))\n\t}\n\treturn \u0026Handler{\n\t\toperations: operations,\n\t}\n}","line":{"from":46,"to":56}} {"id":100016482,"name":"SetReadyFunc","signature":"func (h *Handler) SetReadyFunc(readyFunc ReadyFunc)","file":"staging/src/k8s.io/apiserver/pkg/admission/handler.go","code":"// SetReadyFunc allows late registration of a ReadyFunc to know if the handler is ready to process requests.\nfunc (h *Handler) SetReadyFunc(readyFunc ReadyFunc) {\n\th.readyFunc = readyFunc\n}","line":{"from":58,"to":61}} {"id":100016483,"name":"WaitForReady","signature":"func (h *Handler) WaitForReady() bool","file":"staging/src/k8s.io/apiserver/pkg/admission/handler.go","code":"// WaitForReady will wait for the readyFunc (if registered) to return ready, and in case of timeout, will return false.\nfunc (h *Handler) WaitForReady() bool {\n\t// there is no ready func configured, so we return immediately\n\tif h.readyFunc == nil {\n\t\treturn true\n\t}\n\n\ttimeout := time.After(timeToWaitForReady)\n\tfor !h.readyFunc() {\n\t\tselect {\n\t\tcase \u003c-time.After(100 * time.Millisecond):\n\t\tcase \u003c-timeout:\n\t\t\treturn h.readyFunc()\n\t\t}\n\t}\n\treturn true\n}","line":{"from":63,"to":79}} {"id":100016484,"name":"New","signature":"func New(","file":"staging/src/k8s.io/apiserver/pkg/admission/initializer/initializer.go","code":"// New creates an instance of admission plugins initializer.\n// This constructor is public with a long param list so that callers immediately know that new information can be expected\n// during compilation when they update a level.\nfunc New(\n\textClientset kubernetes.Interface,\n\tdynamicClient dynamic.Interface,\n\textInformers informers.SharedInformerFactory,\n\tauthz authorizer.Authorizer,\n\tfeatureGates featuregate.FeatureGate,\n\tstopCh \u003c-chan struct{},\n) pluginInitializer {\n\treturn pluginInitializer{\n\t\texternalClient: extClientset,\n\t\tdynamicClient: dynamicClient,\n\t\texternalInformers: extInformers,\n\t\tauthorizer: authz,\n\t\tfeatureGates: featureGates,\n\t\tstopCh: stopCh,\n\t}\n}","line":{"from":37,"to":56}} {"id":100016485,"name":"Initialize","signature":"func (i pluginInitializer) Initialize(plugin admission.Interface)","file":"staging/src/k8s.io/apiserver/pkg/admission/initializer/initializer.go","code":"// Initialize checks the initialization interfaces implemented by a plugin\n// and provide the appropriate initialization data\nfunc (i pluginInitializer) Initialize(plugin admission.Interface) {\n\t// First tell the plugin about drained notification, so it can pass it to further initializations.\n\tif wants, ok := plugin.(WantsDrainedNotification); ok {\n\t\twants.SetDrainedNotification(i.stopCh)\n\t}\n\n\t// Second tell the plugin about enabled features, so it can decide whether to start informers or not\n\tif wants, ok := plugin.(WantsFeatures); ok {\n\t\twants.InspectFeatureGates(i.featureGates)\n\t}\n\n\tif wants, ok := plugin.(WantsExternalKubeClientSet); ok {\n\t\twants.SetExternalKubeClientSet(i.externalClient)\n\t}\n\n\tif wants, ok := plugin.(WantsDynamicClient); ok {\n\t\twants.SetDynamicClient(i.dynamicClient)\n\t}\n\n\tif wants, ok := plugin.(WantsExternalKubeInformerFactory); ok {\n\t\twants.SetExternalKubeInformerFactory(i.externalInformers)\n\t}\n\n\tif wants, ok := plugin.(WantsAuthorizer); ok {\n\t\twants.SetAuthorizer(i.authorizer)\n\t}\n}","line":{"from":58,"to":86}} {"id":100016486,"name":"WithControllerMetrics","signature":"func WithControllerMetrics(i admission.Interface, name string) admission.Interface","file":"staging/src/k8s.io/apiserver/pkg/admission/metrics/metrics.go","code":"// WithControllerMetrics is a decorator for named admission handlers.\nfunc WithControllerMetrics(i admission.Interface, name string) admission.Interface {\n\treturn WithMetrics(i, Metrics.ObserveAdmissionController, name)\n}","line":{"from":61,"to":64}} {"id":100016487,"name":"WithStepMetrics","signature":"func WithStepMetrics(i admission.Interface) admission.Interface","file":"staging/src/k8s.io/apiserver/pkg/admission/metrics/metrics.go","code":"// WithStepMetrics is a decorator for a whole admission phase, i.e. admit or validation.admission step.\nfunc WithStepMetrics(i admission.Interface) admission.Interface {\n\treturn WithMetrics(i, Metrics.ObserveAdmissionStep)\n}","line":{"from":66,"to":69}} {"id":100016488,"name":"WithMetrics","signature":"func WithMetrics(i admission.Interface, observer ObserverFunc, extraLabels ...string) admission.Interface","file":"staging/src/k8s.io/apiserver/pkg/admission/metrics/metrics.go","code":"// WithMetrics is a decorator for admission handlers with a generic observer func.\nfunc WithMetrics(i admission.Interface, observer ObserverFunc, extraLabels ...string) admission.Interface {\n\treturn \u0026pluginHandlerWithMetrics{\n\t\tInterface: i,\n\t\tobserver: observer,\n\t\textraLabels: extraLabels,\n\t}\n}","line":{"from":71,"to":78}} {"id":100016489,"name":"Admit","signature":"func (p pluginHandlerWithMetrics) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error","file":"staging/src/k8s.io/apiserver/pkg/admission/metrics/metrics.go","code":"// Admit performs a mutating admission control check and emit metrics.\nfunc (p pluginHandlerWithMetrics) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {\n\tmutatingHandler, ok := p.Interface.(admission.MutationInterface)\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tstart := time.Now()\n\terr := mutatingHandler.Admit(ctx, a, o)\n\tp.observer(ctx, time.Since(start), err != nil, a, stepAdmit, p.extraLabels...)\n\treturn err\n}","line":{"from":87,"to":98}} {"id":100016490,"name":"Validate","signature":"func (p pluginHandlerWithMetrics) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error","file":"staging/src/k8s.io/apiserver/pkg/admission/metrics/metrics.go","code":"// Validate performs a non-mutating admission control check and emits metrics.\nfunc (p pluginHandlerWithMetrics) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {\n\tvalidatingHandler, ok := p.Interface.(admission.ValidationInterface)\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tstart := time.Now()\n\terr := validatingHandler.Validate(ctx, a, o)\n\tp.observer(ctx, time.Since(start), err != nil, a, stepValidate, p.extraLabels...)\n\treturn err\n}","line":{"from":100,"to":111}} {"id":100016491,"name":"newAdmissionMetrics","signature":"func newAdmissionMetrics() *AdmissionMetrics","file":"staging/src/k8s.io/apiserver/pkg/admission/metrics/metrics.go","code":"// newAdmissionMetrics create a new AdmissionMetrics, configured with default metric names.\nfunc newAdmissionMetrics() *AdmissionMetrics {\n\t// Admission metrics for a step of the admission flow. The entire admission flow is broken down into a series of steps\n\t// Each step is identified by a distinct type label value.\n\t// Use buckets ranging from 5 ms to 2.5 seconds.\n\tstep := \u0026metricSet{\n\t\tlatencies: metrics.NewHistogramVec(\n\t\t\t\u0026metrics.HistogramOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tSubsystem: subsystem,\n\t\t\t\tName: \"step_admission_duration_seconds\",\n\t\t\t\tHelp: \"Admission sub-step latency histogram in seconds, broken out for each operation and API resource and step type (validate or admit).\",\n\t\t\t\tBuckets: []float64{0.005, 0.025, 0.1, 0.5, 1.0, 2.5},\n\t\t\t\tStabilityLevel: metrics.STABLE,\n\t\t\t},\n\t\t\t[]string{\"type\", \"operation\", \"rejected\"},\n\t\t),\n\n\t\tlatenciesSummary: metrics.NewSummaryVec(\n\t\t\t\u0026metrics.SummaryOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tSubsystem: subsystem,\n\t\t\t\tName: \"step_admission_duration_seconds_summary\",\n\t\t\t\tHelp: \"Admission sub-step latency summary in seconds, broken out for each operation and API resource and step type (validate or admit).\",\n\t\t\t\tMaxAge: latencySummaryMaxAge,\n\t\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t\t},\n\t\t\t[]string{\"type\", \"operation\", \"rejected\"},\n\t\t),\n\t}\n\n\t// Built-in admission controller metrics. Each admission controller is identified by name.\n\t// Use buckets ranging from 5 ms to 2.5 seconds.\n\tcontroller := \u0026metricSet{\n\t\tlatencies: metrics.NewHistogramVec(\n\t\t\t\u0026metrics.HistogramOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tSubsystem: subsystem,\n\t\t\t\tName: \"controller_admission_duration_seconds\",\n\t\t\t\tHelp: \"Admission controller latency histogram in seconds, identified by name and broken out for each operation and API resource and type (validate or admit).\",\n\t\t\t\tBuckets: []float64{0.005, 0.025, 0.1, 0.5, 1.0, 2.5},\n\t\t\t\tStabilityLevel: metrics.STABLE,\n\t\t\t},\n\t\t\t[]string{\"name\", \"type\", \"operation\", \"rejected\"},\n\t\t),\n\n\t\tlatenciesSummary: nil,\n\t}\n\n\t// Admission webhook metrics. Each webhook is identified by name.\n\t// Use buckets ranging from 5 ms to 2.5 seconds (admission webhooks timeout at 30 seconds by default).\n\twebhook := \u0026metricSet{\n\t\tlatencies: metrics.NewHistogramVec(\n\t\t\t\u0026metrics.HistogramOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tSubsystem: subsystem,\n\t\t\t\tName: \"webhook_admission_duration_seconds\",\n\t\t\t\tHelp: \"Admission webhook latency histogram in seconds, identified by name and broken out for each operation and API resource and type (validate or admit).\",\n\t\t\t\tBuckets: []float64{0.005, 0.025, 0.1, 0.5, 1.0, 2.5, 10, 25},\n\t\t\t\tStabilityLevel: metrics.STABLE,\n\t\t\t},\n\t\t\t[]string{\"name\", \"type\", \"operation\", \"rejected\"},\n\t\t),\n\n\t\tlatenciesSummary: nil,\n\t}\n\n\twebhookRejection := metrics.NewCounterVec(\n\t\t\u0026metrics.CounterOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: \"webhook_rejection_count\",\n\t\t\tHelp: \"Admission webhook rejection count, identified by name and broken out for each admission type (validating or admit) and operation. Additional labels specify an error type (calling_webhook_error or apiserver_internal_error if an error occurred; no_error otherwise) and optionally a non-zero rejection code if the webhook rejects the request with an HTTP status code (honored by the apiserver when the code is greater or equal to 400). Codes greater than 600 are truncated to 600, to keep the metrics cardinality bounded.\",\n\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t},\n\t\t[]string{\"name\", \"type\", \"operation\", \"error_type\", \"rejection_code\"})\n\n\twebhookFailOpen := metrics.NewCounterVec(\n\t\t\u0026metrics.CounterOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: \"webhook_fail_open_count\",\n\t\t\tHelp: \"Admission webhook fail open count, identified by name and broken out for each admission type (validating or mutating).\",\n\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t},\n\t\t[]string{\"name\", \"type\"})\n\n\twebhookRequest := metrics.NewCounterVec(\n\t\t\u0026metrics.CounterOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: \"webhook_request_total\",\n\t\t\tHelp: \"Admission webhook request total, identified by name and broken out for each admission type (validating or mutating) and operation. Additional labels specify whether the request was rejected or not and an HTTP status code. Codes greater than 600 are truncated to 600, to keep the metrics cardinality bounded.\",\n\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t},\n\t\t[]string{\"name\", \"type\", \"operation\", \"code\", \"rejected\"})\n\n\tmatchConditionEvalError := metrics.NewCounterVec(\n\t\t\u0026metrics.CounterOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: \"admission_match_condition_evaluation_errors_total\",\n\t\t\tHelp: \"Admission match condition evaluation errors count, identified by name of resource containing the match condition and broken out for each admission type (validating or mutating).\",\n\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t},\n\t\t[]string{\"name\", \"type\"})\n\n\tstep.mustRegister()\n\tcontroller.mustRegister()\n\twebhook.mustRegister()\n\tlegacyregistry.MustRegister(webhookRejection)\n\tlegacyregistry.MustRegister(webhookFailOpen)\n\tlegacyregistry.MustRegister(webhookRequest)\n\tlegacyregistry.MustRegister(matchConditionEvalError)\n\treturn \u0026AdmissionMetrics{step: step, controller: controller, webhook: webhook, webhookRejection: webhookRejection, webhookFailOpen: webhookFailOpen, webhookRequest: webhookRequest, matchConditionEvalErrors: matchConditionEvalError}\n}","line":{"from":124,"to":239}} {"id":100016492,"name":"reset","signature":"func (m *AdmissionMetrics) reset()","file":"staging/src/k8s.io/apiserver/pkg/admission/metrics/metrics.go","code":"func (m *AdmissionMetrics) reset() {\n\tm.step.reset()\n\tm.controller.reset()\n\tm.webhook.reset()\n}","line":{"from":241,"to":245}} {"id":100016493,"name":"ObserveAdmissionStep","signature":"func (m *AdmissionMetrics) ObserveAdmissionStep(ctx context.Context, elapsed time.Duration, rejected bool, attr admission.Attributes, stepType string, extraLabels ...string)","file":"staging/src/k8s.io/apiserver/pkg/admission/metrics/metrics.go","code":"// ObserveAdmissionStep records admission related metrics for a admission step, identified by step type.\nfunc (m *AdmissionMetrics) ObserveAdmissionStep(ctx context.Context, elapsed time.Duration, rejected bool, attr admission.Attributes, stepType string, extraLabels ...string) {\n\tm.step.observe(ctx, elapsed, append(extraLabels, stepType, string(attr.GetOperation()), strconv.FormatBool(rejected))...)\n}","line":{"from":247,"to":250}} {"id":100016494,"name":"ObserveAdmissionController","signature":"func (m *AdmissionMetrics) ObserveAdmissionController(ctx context.Context, elapsed time.Duration, rejected bool, attr admission.Attributes, stepType string, extraLabels ...string)","file":"staging/src/k8s.io/apiserver/pkg/admission/metrics/metrics.go","code":"// ObserveAdmissionController records admission related metrics for a built-in admission controller, identified by it's plugin handler name.\nfunc (m *AdmissionMetrics) ObserveAdmissionController(ctx context.Context, elapsed time.Duration, rejected bool, attr admission.Attributes, stepType string, extraLabels ...string) {\n\tm.controller.observe(ctx, elapsed, append(extraLabels, stepType, string(attr.GetOperation()), strconv.FormatBool(rejected))...)\n}","line":{"from":252,"to":255}} {"id":100016495,"name":"ObserveWebhook","signature":"func (m *AdmissionMetrics) ObserveWebhook(ctx context.Context, name string, elapsed time.Duration, rejected bool, attr admission.Attributes, stepType string, code int)","file":"staging/src/k8s.io/apiserver/pkg/admission/metrics/metrics.go","code":"// ObserveWebhook records admission related metrics for a admission webhook.\nfunc (m *AdmissionMetrics) ObserveWebhook(ctx context.Context, name string, elapsed time.Duration, rejected bool, attr admission.Attributes, stepType string, code int) {\n\t// We truncate codes greater than 600 to keep the cardinality bounded.\n\tif code \u003e 600 {\n\t\tcode = 600\n\t}\n\tm.webhookRequest.WithContext(ctx).WithLabelValues(name, stepType, string(attr.GetOperation()), strconv.Itoa(code), strconv.FormatBool(rejected)).Inc()\n\tm.webhook.observe(ctx, elapsed, name, stepType, string(attr.GetOperation()), strconv.FormatBool(rejected))\n}","line":{"from":257,"to":265}} {"id":100016496,"name":"ObserveWebhookRejection","signature":"func (m *AdmissionMetrics) ObserveWebhookRejection(ctx context.Context, name, stepType, operation string, errorType WebhookRejectionErrorType, rejectionCode int)","file":"staging/src/k8s.io/apiserver/pkg/admission/metrics/metrics.go","code":"// ObserveWebhookRejection records admission related metrics for an admission webhook rejection.\nfunc (m *AdmissionMetrics) ObserveWebhookRejection(ctx context.Context, name, stepType, operation string, errorType WebhookRejectionErrorType, rejectionCode int) {\n\t// We truncate codes greater than 600 to keep the cardinality bounded.\n\t// This should be rarely done by a malfunctioning webhook server.\n\tif rejectionCode \u003e 600 {\n\t\trejectionCode = 600\n\t}\n\tm.webhookRejection.WithContext(ctx).WithLabelValues(name, stepType, operation, string(errorType), strconv.Itoa(rejectionCode)).Inc()\n}","line":{"from":267,"to":275}} {"id":100016497,"name":"ObserveWebhookFailOpen","signature":"func (m *AdmissionMetrics) ObserveWebhookFailOpen(ctx context.Context, name, stepType string)","file":"staging/src/k8s.io/apiserver/pkg/admission/metrics/metrics.go","code":"// ObserveWebhookFailOpen records validating or mutating webhook that fail open.\nfunc (m *AdmissionMetrics) ObserveWebhookFailOpen(ctx context.Context, name, stepType string) {\n\tm.webhookFailOpen.WithContext(ctx).WithLabelValues(name, stepType).Inc()\n}","line":{"from":277,"to":280}} {"id":100016498,"name":"ObserveMatchConditionEvalError","signature":"func (m *AdmissionMetrics) ObserveMatchConditionEvalError(ctx context.Context, name, stepType string)","file":"staging/src/k8s.io/apiserver/pkg/admission/metrics/metrics.go","code":"// ObserveMatchConditionEvalError records validating or mutating webhook that are not called due to match conditions\nfunc (m *AdmissionMetrics) ObserveMatchConditionEvalError(ctx context.Context, name, stepType string) {\n\tm.matchConditionEvalErrors.WithContext(ctx).WithLabelValues(name, stepType).Inc()\n}","line":{"from":282,"to":285}} {"id":100016499,"name":"mustRegister","signature":"func (m *metricSet) mustRegister()","file":"staging/src/k8s.io/apiserver/pkg/admission/metrics/metrics.go","code":"// MustRegister registers all the prometheus metrics in the metricSet.\nfunc (m *metricSet) mustRegister() {\n\tlegacyregistry.MustRegister(m.latencies)\n\tif m.latenciesSummary != nil {\n\t\tlegacyregistry.MustRegister(m.latenciesSummary)\n\t}\n}","line":{"from":292,"to":298}} {"id":100016500,"name":"reset","signature":"func (m *metricSet) reset()","file":"staging/src/k8s.io/apiserver/pkg/admission/metrics/metrics.go","code":"// Reset resets all the prometheus metrics in the metricSet.\nfunc (m *metricSet) reset() {\n\tm.latencies.Reset()\n\tif m.latenciesSummary != nil {\n\t\tm.latenciesSummary.Reset()\n\t}\n}","line":{"from":300,"to":306}} {"id":100016501,"name":"observe","signature":"func (m *metricSet) observe(ctx context.Context, elapsed time.Duration, labels ...string)","file":"staging/src/k8s.io/apiserver/pkg/admission/metrics/metrics.go","code":"// Observe records an observed admission event to all metrics in the metricSet.\nfunc (m *metricSet) observe(ctx context.Context, elapsed time.Duration, labels ...string) {\n\telapsedSeconds := elapsed.Seconds()\n\tm.latencies.WithContext(ctx).WithLabelValues(labels...).Observe(elapsedSeconds)\n\tif m.latenciesSummary != nil {\n\t\tm.latenciesSummary.WithContext(ctx).WithLabelValues(labels...).Observe(elapsedSeconds)\n\t}\n}","line":{"from":308,"to":315}} {"id":100016502,"name":"getEnvs","signature":"func getEnvs() (envs, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/cel/compile.go","code":"func getEnvs() (envs, error) {\n\tinitEnvsOnce.Do(func() {\n\t\trequiredVarsEnv, err := buildRequiredVarsEnv()\n\t\tif err != nil {\n\t\t\tinitEnvsErr = err\n\t\t\treturn\n\t\t}\n\n\t\tinitEnvs, err = buildWithOptionalVarsEnvs(requiredVarsEnv)\n\t\tif err != nil {\n\t\t\tinitEnvsErr = err\n\t\t\treturn\n\t\t}\n\t})\n\treturn initEnvs, initEnvsErr\n}","line":{"from":45,"to":60}} {"id":100016503,"name":"buildBaseEnv","signature":"func buildBaseEnv() (*cel.Env, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/cel/compile.go","code":"// This is a similar code as in k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/compilation.go\n// If any changes are made here, consider to make the same changes there as well.\nfunc buildBaseEnv() (*cel.Env, error) {\n\tvar opts []cel.EnvOption\n\topts = append(opts, cel.HomogeneousAggregateLiterals())\n\t// Validate function declarations once during base env initialization,\n\t// so they don't need to be evaluated each time a CEL rule is compiled.\n\t// This is a relatively expensive operation.\n\topts = append(opts, cel.EagerlyValidateDeclarations(true), cel.DefaultUTCTimeZone(true))\n\topts = append(opts, library.ExtensionLibs...)\n\n\treturn cel.NewEnv(opts...)\n}","line":{"from":62,"to":74}} {"id":100016504,"name":"buildRequiredVarsEnv","signature":"func buildRequiredVarsEnv() (*cel.Env, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/cel/compile.go","code":"func buildRequiredVarsEnv() (*cel.Env, error) {\n\tbaseEnv, err := buildBaseEnv()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar propDecls []cel.EnvOption\n\treg := apiservercel.NewRegistry(baseEnv)\n\n\trequestType := BuildRequestType()\n\trt, err := apiservercel.NewRuleTypes(requestType.TypeName(), requestType, reg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif rt == nil {\n\t\treturn nil, nil\n\t}\n\topts, err := rt.EnvOptions(baseEnv.TypeProvider())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpropDecls = append(propDecls, cel.Variable(ObjectVarName, cel.DynType))\n\tpropDecls = append(propDecls, cel.Variable(OldObjectVarName, cel.DynType))\n\tpropDecls = append(propDecls, cel.Variable(RequestVarName, requestType.CelType()))\n\n\topts = append(opts, propDecls...)\n\tenv, err := baseEnv.Extend(opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn env, nil\n}","line":{"from":76,"to":106}} {"id":100016505,"name":"buildEnvWithVars","signature":"func buildEnvWithVars(baseVarsEnv *cel.Env, options OptionalVariableDeclarations) (*cel.Env, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/cel/compile.go","code":"func buildEnvWithVars(baseVarsEnv *cel.Env, options OptionalVariableDeclarations) (*cel.Env, error) {\n\tvar opts []cel.EnvOption\n\tif options.HasParams {\n\t\topts = append(opts, cel.Variable(ParamsVarName, cel.DynType))\n\t}\n\tif options.HasAuthorizer {\n\t\topts = append(opts, cel.Variable(AuthorizerVarName, library.AuthorizerType))\n\t\topts = append(opts, cel.Variable(RequestResourceAuthorizerVarName, library.ResourceCheckType))\n\t}\n\treturn baseVarsEnv.Extend(opts...)\n}","line":{"from":110,"to":120}} {"id":100016506,"name":"buildWithOptionalVarsEnvs","signature":"func buildWithOptionalVarsEnvs(requiredVarsEnv *cel.Env) (envs, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/cel/compile.go","code":"func buildWithOptionalVarsEnvs(requiredVarsEnv *cel.Env) (envs, error) {\n\tenvs := make(envs, 4) // since the number of variable combinations is small, pre-build a environment for each\n\tfor _, hasParams := range []bool{false, true} {\n\t\tfor _, hasAuthorizer := range []bool{false, true} {\n\t\t\topts := OptionalVariableDeclarations{HasParams: hasParams, HasAuthorizer: hasAuthorizer}\n\t\t\tenv, err := buildEnvWithVars(requiredVarsEnv, opts)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tenvs[opts] = env\n\t\t}\n\t}\n\treturn envs, nil\n}","line":{"from":122,"to":135}} {"id":100016507,"name":"BuildRequestType","signature":"func BuildRequestType() *apiservercel.DeclType","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/cel/compile.go","code":"// BuildRequestType generates a DeclType for AdmissionRequest. This may be replaced with a utility that\n// converts the native type definition to apiservercel.DeclType once such a utility becomes available.\n// The 'uid' field is omitted since it is not needed for in-process admission review.\n// The 'object' and 'oldObject' fields are omitted since they are exposed as root level CEL variables.\nfunc BuildRequestType() *apiservercel.DeclType {\n\tfield := func(name string, declType *apiservercel.DeclType, required bool) *apiservercel.DeclField {\n\t\treturn apiservercel.NewDeclField(name, declType, required, nil, nil)\n\t}\n\tfields := func(fields ...*apiservercel.DeclField) map[string]*apiservercel.DeclField {\n\t\tresult := make(map[string]*apiservercel.DeclField, len(fields))\n\t\tfor _, f := range fields {\n\t\t\tresult[f.Name] = f\n\t\t}\n\t\treturn result\n\t}\n\tgvkType := apiservercel.NewObjectType(\"kubernetes.GroupVersionKind\", fields(\n\t\tfield(\"group\", apiservercel.StringType, true),\n\t\tfield(\"version\", apiservercel.StringType, true),\n\t\tfield(\"kind\", apiservercel.StringType, true),\n\t))\n\tgvrType := apiservercel.NewObjectType(\"kubernetes.GroupVersionResource\", fields(\n\t\tfield(\"group\", apiservercel.StringType, true),\n\t\tfield(\"version\", apiservercel.StringType, true),\n\t\tfield(\"resource\", apiservercel.StringType, true),\n\t))\n\tuserInfoType := apiservercel.NewObjectType(\"kubernetes.UserInfo\", fields(\n\t\tfield(\"username\", apiservercel.StringType, false),\n\t\tfield(\"uid\", apiservercel.StringType, false),\n\t\tfield(\"groups\", apiservercel.NewListType(apiservercel.StringType, -1), false),\n\t\tfield(\"extra\", apiservercel.NewMapType(apiservercel.StringType, apiservercel.NewListType(apiservercel.StringType, -1), -1), false),\n\t))\n\treturn apiservercel.NewObjectType(\"kubernetes.AdmissionRequest\", fields(\n\t\tfield(\"kind\", gvkType, true),\n\t\tfield(\"resource\", gvrType, true),\n\t\tfield(\"subResource\", apiservercel.StringType, false),\n\t\tfield(\"requestKind\", gvkType, true),\n\t\tfield(\"requestResource\", gvrType, true),\n\t\tfield(\"requestSubResource\", apiservercel.StringType, false),\n\t\tfield(\"name\", apiservercel.StringType, true),\n\t\tfield(\"namespace\", apiservercel.StringType, false),\n\t\tfield(\"operation\", apiservercel.StringType, true),\n\t\tfield(\"userInfo\", userInfoType, true),\n\t\tfield(\"dryRun\", apiservercel.BoolType, false),\n\t\tfield(\"options\", apiservercel.DynType, false),\n\t))\n}","line":{"from":137,"to":182}} {"id":100016508,"name":"CompileCELExpression","signature":"func CompileCELExpression(expressionAccessor ExpressionAccessor, optionalVars OptionalVariableDeclarations, perCallLimit uint64) CompilationResult","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/cel/compile.go","code":"// CompileCELExpression returns a compiled CEL expression.\n// perCallLimit was added for testing purpose only. Callers should always use const PerCallLimit from k8s.io/apiserver/pkg/apis/cel/config.go as input.\nfunc CompileCELExpression(expressionAccessor ExpressionAccessor, optionalVars OptionalVariableDeclarations, perCallLimit uint64) CompilationResult {\n\tvar env *cel.Env\n\tenvs, err := getEnvs()\n\tif err != nil {\n\t\treturn CompilationResult{\n\t\t\tError: \u0026apiservercel.Error{\n\t\t\t\tType: apiservercel.ErrorTypeInternal,\n\t\t\t\tDetail: \"compiler initialization failed: \" + err.Error(),\n\t\t\t},\n\t\t\tExpressionAccessor: expressionAccessor,\n\t\t}\n\t}\n\tenv, ok := envs[optionalVars]\n\tif !ok {\n\t\treturn CompilationResult{\n\t\t\tError: \u0026apiservercel.Error{\n\t\t\t\tType: apiservercel.ErrorTypeInvalid,\n\t\t\t\tDetail: fmt.Sprintf(\"compiler initialization failed: failed to load environment for %v\", optionalVars),\n\t\t\t},\n\t\t\tExpressionAccessor: expressionAccessor,\n\t\t}\n\t}\n\n\tast, issues := env.Compile(expressionAccessor.GetExpression())\n\tif issues != nil {\n\t\treturn CompilationResult{\n\t\t\tError: \u0026apiservercel.Error{\n\t\t\t\tType: apiservercel.ErrorTypeInvalid,\n\t\t\t\tDetail: \"compilation failed: \" + issues.String(),\n\t\t\t},\n\t\t\tExpressionAccessor: expressionAccessor,\n\t\t}\n\t}\n\tfound := false\n\treturnTypes := expressionAccessor.ReturnTypes()\n\tfor _, returnType := range returnTypes {\n\t\tif ast.OutputType() == returnType {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\tvar reason string\n\t\tif len(returnTypes) == 1 {\n\t\t\treason = fmt.Sprintf(\"must evaluate to %v\", returnTypes[0].String())\n\t\t} else {\n\t\t\treason = fmt.Sprintf(\"must evaluate to one of %v\", returnTypes)\n\t\t}\n\n\t\treturn CompilationResult{\n\t\t\tError: \u0026apiservercel.Error{\n\t\t\t\tType: apiservercel.ErrorTypeInvalid,\n\t\t\t\tDetail: reason,\n\t\t\t},\n\t\t\tExpressionAccessor: expressionAccessor,\n\t\t}\n\t}\n\n\t_, err = cel.AstToCheckedExpr(ast)\n\tif err != nil {\n\t\t// should be impossible since env.Compile returned no issues\n\t\treturn CompilationResult{\n\t\t\tError: \u0026apiservercel.Error{\n\t\t\t\tType: apiservercel.ErrorTypeInternal,\n\t\t\t\tDetail: \"unexpected compilation error: \" + err.Error(),\n\t\t\t},\n\t\t\tExpressionAccessor: expressionAccessor,\n\t\t}\n\t}\n\tprog, err := env.Program(ast,\n\t\tcel.EvalOptions(cel.OptOptimize, cel.OptTrackCost),\n\t\tcel.OptimizeRegex(library.ExtensionLibRegexOptimizations...),\n\t\tcel.InterruptCheckFrequency(celconfig.CheckFrequency),\n\t\tcel.CostLimit(perCallLimit),\n\t)\n\tif err != nil {\n\t\treturn CompilationResult{\n\t\t\tError: \u0026apiservercel.Error{\n\t\t\t\tType: apiservercel.ErrorTypeInvalid,\n\t\t\t\tDetail: \"program instantiation failed: \" + err.Error(),\n\t\t\t},\n\t\t\tExpressionAccessor: expressionAccessor,\n\t\t}\n\t}\n\treturn CompilationResult{\n\t\tProgram: prog,\n\t\tExpressionAccessor: expressionAccessor,\n\t}\n}","line":{"from":191,"to":281}} {"id":100016509,"name":"NewFilterCompiler","signature":"func NewFilterCompiler() FilterCompiler","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/cel/filter.go","code":"func NewFilterCompiler() FilterCompiler {\n\treturn \u0026filterCompiler{}\n}","line":{"from":42,"to":44}} {"id":100016510,"name":"ResolveName","signature":"func (a *evaluationActivation) ResolveName(name string) (interface{}, bool)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/cel/filter.go","code":"// ResolveName returns a value from the activation by qualified name, or false if the name\n// could not be found.\nfunc (a *evaluationActivation) ResolveName(name string) (interface{}, bool) {\n\tswitch name {\n\tcase ObjectVarName:\n\t\treturn a.object, true\n\tcase OldObjectVarName:\n\t\treturn a.oldObject, true\n\tcase ParamsVarName:\n\t\treturn a.params, true // params may be null\n\tcase RequestVarName:\n\t\treturn a.request, true\n\tcase AuthorizerVarName:\n\t\treturn a.authorizer, a.authorizer != nil\n\tcase RequestResourceAuthorizerVarName:\n\t\treturn a.requestResourceAuthorizer, a.requestResourceAuthorizer != nil\n\tdefault:\n\t\treturn nil, false\n\t}\n}","line":{"from":50,"to":69}} {"id":100016511,"name":"Parent","signature":"func (a *evaluationActivation) Parent() interpreter.Activation","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/cel/filter.go","code":"// Parent returns the parent of the current activation, may be nil.\n// If non-nil, the parent will be searched during resolve calls.\nfunc (a *evaluationActivation) Parent() interpreter.Activation {\n\treturn nil\n}","line":{"from":71,"to":75}} {"id":100016512,"name":"Compile","signature":"func (c *filterCompiler) Compile(expressionAccessors []ExpressionAccessor, options OptionalVariableDeclarations, perCallLimit uint64) Filter","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/cel/filter.go","code":"// Compile compiles the cel expressions defined in the ExpressionAccessors into a Filter\nfunc (c *filterCompiler) Compile(expressionAccessors []ExpressionAccessor, options OptionalVariableDeclarations, perCallLimit uint64) Filter {\n\tcompilationResults := make([]CompilationResult, len(expressionAccessors))\n\tfor i, expressionAccessor := range expressionAccessors {\n\t\tif expressionAccessor == nil {\n\t\t\tcontinue\n\t\t}\n\t\tcompilationResults[i] = CompileCELExpression(expressionAccessor, options, perCallLimit)\n\t}\n\treturn NewFilter(compilationResults)\n}","line":{"from":77,"to":87}} {"id":100016513,"name":"NewFilter","signature":"func NewFilter(compilationResults []CompilationResult) Filter","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/cel/filter.go","code":"func NewFilter(compilationResults []CompilationResult) Filter {\n\treturn \u0026filter{\n\t\tcompilationResults,\n\t}\n}","line":{"from":94,"to":98}} {"id":100016514,"name":"convertObjectToUnstructured","signature":"func convertObjectToUnstructured(obj interface{}) (*unstructured.Unstructured, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/cel/filter.go","code":"func convertObjectToUnstructured(obj interface{}) (*unstructured.Unstructured, error) {\n\tif obj == nil || reflect.ValueOf(obj).IsNil() {\n\t\treturn \u0026unstructured.Unstructured{Object: nil}, nil\n\t}\n\tret, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026unstructured.Unstructured{Object: ret}, nil\n}","line":{"from":100,"to":109}} {"id":100016515,"name":"objectToResolveVal","signature":"func objectToResolveVal(r runtime.Object) (interface{}, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/cel/filter.go","code":"func objectToResolveVal(r runtime.Object) (interface{}, error) {\n\tif r == nil || reflect.ValueOf(r).IsNil() {\n\t\treturn nil, nil\n\t}\n\tv, err := convertObjectToUnstructured(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn v.Object, nil\n}","line":{"from":111,"to":120}} {"id":100016516,"name":"ForInput","signature":"func (f *filter) ForInput(ctx context.Context, versionedAttr *admission.VersionedAttributes, request *admissionv1.AdmissionRequest, inputs OptionalVariableBindings, runtimeCELCostBudget int64) ([]EvaluationResult, int64, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/cel/filter.go","code":"// ForInput evaluates the compiled CEL expressions converting them into CELEvaluations\n// errors per evaluation are returned on the Evaluation object\n// runtimeCELCostBudget was added for testing purpose only. Callers should always use const RuntimeCELCostBudget from k8s.io/apiserver/pkg/apis/cel/config.go as input.\nfunc (f *filter) ForInput(ctx context.Context, versionedAttr *admission.VersionedAttributes, request *admissionv1.AdmissionRequest, inputs OptionalVariableBindings, runtimeCELCostBudget int64) ([]EvaluationResult, int64, error) {\n\t// TODO: replace unstructured with ref.Val for CEL variables when native type support is available\n\tevaluations := make([]EvaluationResult, len(f.compilationResults))\n\tvar err error\n\n\toldObjectVal, err := objectToResolveVal(versionedAttr.VersionedOldObject)\n\tif err != nil {\n\t\treturn nil, -1, err\n\t}\n\tobjectVal, err := objectToResolveVal(versionedAttr.VersionedObject)\n\tif err != nil {\n\t\treturn nil, -1, err\n\t}\n\tvar paramsVal, authorizerVal, requestResourceAuthorizerVal any\n\tif inputs.VersionedParams != nil {\n\t\tparamsVal, err = objectToResolveVal(inputs.VersionedParams)\n\t\tif err != nil {\n\t\t\treturn nil, -1, err\n\t\t}\n\t}\n\n\tif inputs.Authorizer != nil {\n\t\tauthorizerVal = library.NewAuthorizerVal(versionedAttr.GetUserInfo(), inputs.Authorizer)\n\t\trequestResourceAuthorizerVal = library.NewResourceAuthorizerVal(versionedAttr.GetUserInfo(), inputs.Authorizer, versionedAttr)\n\t}\n\n\trequestVal, err := convertObjectToUnstructured(request)\n\tif err != nil {\n\t\treturn nil, -1, err\n\t}\n\tva := \u0026evaluationActivation{\n\t\tobject: objectVal,\n\t\toldObject: oldObjectVal,\n\t\tparams: paramsVal,\n\t\trequest: requestVal.Object,\n\t\tauthorizer: authorizerVal,\n\t\trequestResourceAuthorizer: requestResourceAuthorizerVal,\n\t}\n\n\tremainingBudget := runtimeCELCostBudget\n\tfor i, compilationResult := range f.compilationResults {\n\t\tvar evaluation = \u0026evaluations[i]\n\t\tif compilationResult.ExpressionAccessor == nil { // in case of placeholder\n\t\t\tcontinue\n\t\t}\n\t\tevaluation.ExpressionAccessor = compilationResult.ExpressionAccessor\n\t\tif compilationResult.Error != nil {\n\t\t\tevaluation.Error = \u0026cel.Error{\n\t\t\t\tType: cel.ErrorTypeInvalid,\n\t\t\t\tDetail: fmt.Sprintf(\"compilation error: %v\", compilationResult.Error),\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif compilationResult.Program == nil {\n\t\t\tevaluation.Error = \u0026cel.Error{\n\t\t\t\tType: cel.ErrorTypeInternal,\n\t\t\t\tDetail: fmt.Sprintf(\"unexpected internal error compiling expression\"),\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tt1 := time.Now()\n\t\tevalResult, evalDetails, err := compilationResult.Program.ContextEval(ctx, va)\n\t\telapsed := time.Since(t1)\n\t\tevaluation.Elapsed = elapsed\n\t\tif evalDetails == nil {\n\t\t\treturn nil, -1, \u0026cel.Error{\n\t\t\t\tType: cel.ErrorTypeInternal,\n\t\t\t\tDetail: fmt.Sprintf(\"runtime cost could not be calculated for expression: %v, no further expression will be run\", compilationResult.ExpressionAccessor.GetExpression()),\n\t\t\t}\n\t\t} else {\n\t\t\trtCost := evalDetails.ActualCost()\n\t\t\tif rtCost == nil {\n\t\t\t\treturn nil, -1, \u0026cel.Error{\n\t\t\t\t\tType: cel.ErrorTypeInvalid,\n\t\t\t\t\tDetail: fmt.Sprintf(\"runtime cost could not be calculated for expression: %v, no further expression will be run\", compilationResult.ExpressionAccessor.GetExpression()),\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif *rtCost \u003e math.MaxInt64 || int64(*rtCost) \u003e remainingBudget {\n\t\t\t\t\treturn nil, -1, \u0026cel.Error{\n\t\t\t\t\t\tType: cel.ErrorTypeInvalid,\n\t\t\t\t\t\tDetail: fmt.Sprintf(\"validation failed due to running out of cost budget, no further validation rules will be run\"),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tremainingBudget -= int64(*rtCost)\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\tevaluation.Error = \u0026cel.Error{\n\t\t\t\tType: cel.ErrorTypeInvalid,\n\t\t\t\tDetail: fmt.Sprintf(\"expression '%v' resulted in error: %v\", compilationResult.ExpressionAccessor.GetExpression(), err),\n\t\t\t}\n\t\t} else {\n\t\t\tevaluation.EvalResult = evalResult\n\t\t}\n\t}\n\n\treturn evaluations, remainingBudget, nil\n}","line":{"from":122,"to":222}} {"id":100016517,"name":"CreateAdmissionRequest","signature":"func CreateAdmissionRequest(attr admission.Attributes) *admissionv1.AdmissionRequest","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/cel/filter.go","code":"// TODO: to reuse https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/request/admissionreview.go#L154\nfunc CreateAdmissionRequest(attr admission.Attributes) *admissionv1.AdmissionRequest {\n\t// FIXME: how to get resource GVK, GVR and subresource?\n\tgvk := attr.GetKind()\n\tgvr := attr.GetResource()\n\tsubresource := attr.GetSubresource()\n\n\trequestGVK := attr.GetKind()\n\trequestGVR := attr.GetResource()\n\trequestSubResource := attr.GetSubresource()\n\n\taUserInfo := attr.GetUserInfo()\n\tvar userInfo authenticationv1.UserInfo\n\tif aUserInfo != nil {\n\t\tuserInfo = authenticationv1.UserInfo{\n\t\t\tExtra: make(map[string]authenticationv1.ExtraValue),\n\t\t\tGroups: aUserInfo.GetGroups(),\n\t\t\tUID: aUserInfo.GetUID(),\n\t\t\tUsername: aUserInfo.GetName(),\n\t\t}\n\t\t// Convert the extra information in the user object\n\t\tfor key, val := range aUserInfo.GetExtra() {\n\t\t\tuserInfo.Extra[key] = authenticationv1.ExtraValue(val)\n\t\t}\n\t}\n\n\tdryRun := attr.IsDryRun()\n\n\treturn \u0026admissionv1.AdmissionRequest{\n\t\tKind: metav1.GroupVersionKind{\n\t\t\tGroup: gvk.Group,\n\t\t\tKind: gvk.Kind,\n\t\t\tVersion: gvk.Version,\n\t\t},\n\t\tResource: metav1.GroupVersionResource{\n\t\t\tGroup: gvr.Group,\n\t\t\tResource: gvr.Resource,\n\t\t\tVersion: gvr.Version,\n\t\t},\n\t\tSubResource: subresource,\n\t\tRequestKind: \u0026metav1.GroupVersionKind{\n\t\t\tGroup: requestGVK.Group,\n\t\t\tKind: requestGVK.Kind,\n\t\t\tVersion: requestGVK.Version,\n\t\t},\n\t\tRequestResource: \u0026metav1.GroupVersionResource{\n\t\t\tGroup: requestGVR.Group,\n\t\t\tResource: requestGVR.Resource,\n\t\t\tVersion: requestGVR.Version,\n\t\t},\n\t\tRequestSubResource: requestSubResource,\n\t\tName: attr.GetName(),\n\t\tNamespace: attr.GetNamespace(),\n\t\tOperation: admissionv1.Operation(attr.GetOperation()),\n\t\tUserInfo: userInfo,\n\t\t// Leave Object and OldObject unset since we don't provide access to them via request\n\t\tDryRun: \u0026dryRun,\n\t\tOptions: runtime.RawExtension{\n\t\t\tObject: attr.GetOperationOptions(),\n\t\t},\n\t}\n}","line":{"from":224,"to":285}} {"id":100016518,"name":"CompilationErrors","signature":"func (e *filter) CompilationErrors() []error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/cel/filter.go","code":"// CompilationErrors returns a list of all the errors from the compilation of the evaluator\nfunc (e *filter) CompilationErrors() []error {\n\tcompilationErrors := []error{}\n\tfor _, result := range e.compilationResults {\n\t\tif result.Error != nil {\n\t\t\tcompilationErrors = append(compilationErrors, result.Error)\n\t\t}\n\t}\n\treturn compilationErrors\n}","line":{"from":287,"to":296}} {"id":100016519,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/namespace/lifecycle/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\treturn NewLifecycle(sets.NewString(metav1.NamespaceDefault, metav1.NamespaceSystem, metav1.NamespacePublic))\n\t})\n}","line":{"from":54,"to":59}} {"id":100016520,"name":"Admit","signature":"func (l *Lifecycle) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/namespace/lifecycle/admission.go","code":"// Admit makes an admission decision based on the request attributes\nfunc (l *Lifecycle) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {\n\t// prevent deletion of immortal namespaces\n\tif a.GetOperation() == admission.Delete \u0026\u0026 a.GetKind().GroupKind() == v1.SchemeGroupVersion.WithKind(\"Namespace\").GroupKind() \u0026\u0026 l.immortalNamespaces.Has(a.GetName()) {\n\t\treturn errors.NewForbidden(a.GetResource().GroupResource(), a.GetName(), fmt.Errorf(\"this namespace may not be deleted\"))\n\t}\n\n\t// always allow non-namespaced resources\n\tif len(a.GetNamespace()) == 0 \u0026\u0026 a.GetKind().GroupKind() != v1.SchemeGroupVersion.WithKind(\"Namespace\").GroupKind() {\n\t\treturn nil\n\t}\n\n\tif a.GetKind().GroupKind() == v1.SchemeGroupVersion.WithKind(\"Namespace\").GroupKind() {\n\t\t// if a namespace is deleted, we want to prevent all further creates into it\n\t\t// while it is undergoing termination. to reduce incidences where the cache\n\t\t// is slow to update, we add the namespace into a force live lookup list to ensure\n\t\t// we are not looking at stale state.\n\t\tif a.GetOperation() == admission.Delete {\n\t\t\tl.forceLiveLookupCache.Add(a.GetName(), true, forceLiveLookupTTL)\n\t\t}\n\t\t// allow all operations to namespaces\n\t\treturn nil\n\t}\n\n\t// always allow deletion of other resources\n\tif a.GetOperation() == admission.Delete {\n\t\treturn nil\n\t}\n\n\t// always allow access review checks. Returning status about the namespace would be leaking information\n\tif isAccessReview(a) {\n\t\treturn nil\n\t}\n\n\t// we need to wait for our caches to warm\n\tif !l.WaitForReady() {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"not yet ready to handle request\"))\n\t}\n\n\tvar (\n\t\texists bool\n\t\terr error\n\t)\n\n\tnamespace, err := l.namespaceLister.Get(a.GetNamespace())\n\tif err != nil {\n\t\tif !errors.IsNotFound(err) {\n\t\t\treturn errors.NewInternalError(err)\n\t\t}\n\t} else {\n\t\texists = true\n\t}\n\n\tif !exists \u0026\u0026 a.GetOperation() == admission.Create {\n\t\t// give the cache time to observe the namespace before rejecting a create.\n\t\t// this helps when creating a namespace and immediately creating objects within it.\n\t\ttime.Sleep(missingNamespaceWait)\n\t\tnamespace, err = l.namespaceLister.Get(a.GetNamespace())\n\t\tswitch {\n\t\tcase errors.IsNotFound(err):\n\t\t\t// no-op\n\t\tcase err != nil:\n\t\t\treturn errors.NewInternalError(err)\n\t\tdefault:\n\t\t\texists = true\n\t\t}\n\t\tif exists {\n\t\t\tklog.V(4).InfoS(\"Namespace existed in cache after waiting\", \"namespace\", klog.KRef(\"\", a.GetNamespace()))\n\t\t}\n\t}\n\n\t// forceLiveLookup if true will skip looking at local cache state and instead always make a live call to server.\n\tforceLiveLookup := false\n\tif _, ok := l.forceLiveLookupCache.Get(a.GetNamespace()); ok {\n\t\t// we think the namespace was marked for deletion, but our current local cache says otherwise, we will force a live lookup.\n\t\tforceLiveLookup = exists \u0026\u0026 namespace.Status.Phase == v1.NamespaceActive\n\t}\n\n\t// refuse to operate on non-existent namespaces\n\tif !exists || forceLiveLookup {\n\t\t// as a last resort, make a call directly to storage\n\t\tnamespace, err = l.client.CoreV1().Namespaces().Get(context.TODO(), a.GetNamespace(), metav1.GetOptions{})\n\t\tswitch {\n\t\tcase errors.IsNotFound(err):\n\t\t\treturn err\n\t\tcase err != nil:\n\t\t\treturn errors.NewInternalError(err)\n\t\t}\n\n\t\tklog.V(4).InfoS(\"Found namespace via storage lookup\", \"namespace\", klog.KRef(\"\", a.GetNamespace()))\n\t}\n\n\t// ensure that we're not trying to create objects in terminating namespaces\n\tif a.GetOperation() == admission.Create {\n\t\tif namespace.Status.Phase != v1.NamespaceTerminating {\n\t\t\treturn nil\n\t\t}\n\n\t\terr := admission.NewForbidden(a, fmt.Errorf(\"unable to create new content in namespace %s because it is being terminated\", a.GetNamespace()))\n\t\tif apierr, ok := err.(*errors.StatusError); ok {\n\t\t\tapierr.ErrStatus.Details.Causes = append(apierr.ErrStatus.Details.Causes, metav1.StatusCause{\n\t\t\t\tType: v1.NamespaceTerminatingCause,\n\t\t\t\tMessage: fmt.Sprintf(\"namespace %s is being terminated\", a.GetNamespace()),\n\t\t\t\tField: \"metadata.namespace\",\n\t\t\t})\n\t\t}\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":76,"to":186}} {"id":100016521,"name":"NewLifecycle","signature":"func NewLifecycle(immortalNamespaces sets.String) (*Lifecycle, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/namespace/lifecycle/admission.go","code":"// NewLifecycle creates a new namespace Lifecycle admission control handler\nfunc NewLifecycle(immortalNamespaces sets.String) (*Lifecycle, error) {\n\treturn newLifecycleWithClock(immortalNamespaces, clock.RealClock{})\n}","line":{"from":188,"to":191}} {"id":100016522,"name":"newLifecycleWithClock","signature":"func newLifecycleWithClock(immortalNamespaces sets.String, clock utilcache.Clock) (*Lifecycle, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/namespace/lifecycle/admission.go","code":"func newLifecycleWithClock(immortalNamespaces sets.String, clock utilcache.Clock) (*Lifecycle, error) {\n\tforceLiveLookupCache := utilcache.NewLRUExpireCacheWithClock(100, clock)\n\treturn \u0026Lifecycle{\n\t\tHandler: admission.NewHandler(admission.Create, admission.Update, admission.Delete),\n\t\timmortalNamespaces: immortalNamespaces,\n\t\tforceLiveLookupCache: forceLiveLookupCache,\n\t}, nil\n}","line":{"from":193,"to":200}} {"id":100016523,"name":"SetExternalKubeInformerFactory","signature":"func (l *Lifecycle) SetExternalKubeInformerFactory(f informers.SharedInformerFactory)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/namespace/lifecycle/admission.go","code":"// SetExternalKubeInformerFactory implements the WantsExternalKubeInformerFactory interface.\nfunc (l *Lifecycle) SetExternalKubeInformerFactory(f informers.SharedInformerFactory) {\n\tnamespaceInformer := f.Core().V1().Namespaces()\n\tl.namespaceLister = namespaceInformer.Lister()\n\tl.SetReadyFunc(namespaceInformer.Informer().HasSynced)\n}","line":{"from":202,"to":207}} {"id":100016524,"name":"SetExternalKubeClientSet","signature":"func (l *Lifecycle) SetExternalKubeClientSet(client kubernetes.Interface)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/namespace/lifecycle/admission.go","code":"// SetExternalKubeClientSet implements the WantsExternalKubeClientSet interface.\nfunc (l *Lifecycle) SetExternalKubeClientSet(client kubernetes.Interface) {\n\tl.client = client\n}","line":{"from":209,"to":212}} {"id":100016525,"name":"ValidateInitialization","signature":"func (l *Lifecycle) ValidateInitialization() error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/namespace/lifecycle/admission.go","code":"// ValidateInitialization implements the InitializationValidator interface.\nfunc (l *Lifecycle) ValidateInitialization() error {\n\tif l.namespaceLister == nil {\n\t\treturn fmt.Errorf(\"missing namespaceLister\")\n\t}\n\tif l.client == nil {\n\t\treturn fmt.Errorf(\"missing client\")\n\t}\n\treturn nil\n}","line":{"from":214,"to":223}} {"id":100016526,"name":"isAccessReview","signature":"func isAccessReview(a admission.Attributes) bool","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/namespace/lifecycle/admission.go","code":"func isAccessReview(a admission.Attributes) bool {\n\treturn accessReviewResources[a.GetResource().GroupResource()]\n}","line":{"from":231,"to":233}} {"id":100016527,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName,\n\t\tfunc(config io.Reader) (admission.Interface, error) {\n\t\t\t// load the configuration provided (if any)\n\t\t\tconfiguration, err := LoadConfiguration(config)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\t// validate the configuration (if any)\n\t\t\tif configuration != nil {\n\t\t\t\tif errs := validation.ValidateConfiguration(configuration); len(errs) != 0 {\n\t\t\t\t\treturn nil, errs.ToAggregate()\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn NewResourceQuota(configuration, 5)\n\t\t})\n}","line":{"from":45,"to":62}} {"id":100016528,"name":"NewResourceQuota","signature":"func NewResourceQuota(config *resourcequotaapi.Configuration, numEvaluators int) (*QuotaAdmission, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/admission.go","code":"// NewResourceQuota configures an admission controller that can enforce quota constraints\n// using the provided registry. The registry must have the capability to handle group/kinds that\n// are persisted by the server this admission controller is intercepting\nfunc NewResourceQuota(config *resourcequotaapi.Configuration, numEvaluators int) (*QuotaAdmission, error) {\n\tquotaAccessor, err := newQuotaAccessor()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026QuotaAdmission{\n\t\tHandler: admission.NewHandler(admission.Create, admission.Update),\n\t\tstopCh: nil,\n\t\tnumEvaluators: numEvaluators,\n\t\tconfig: config,\n\t\tquotaAccessor: quotaAccessor,\n\t}, nil\n}","line":{"from":87,"to":103}} {"id":100016529,"name":"SetDrainedNotification","signature":"func (a *QuotaAdmission) SetDrainedNotification(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/admission.go","code":"// SetDrainedNotification sets the stop channel into QuotaAdmission.\nfunc (a *QuotaAdmission) SetDrainedNotification(stopCh \u003c-chan struct{}) {\n\ta.stopCh = stopCh\n}","line":{"from":105,"to":108}} {"id":100016530,"name":"SetExternalKubeClientSet","signature":"func (a *QuotaAdmission) SetExternalKubeClientSet(client kubernetes.Interface)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/admission.go","code":"// SetExternalKubeClientSet registers the client into QuotaAdmission\nfunc (a *QuotaAdmission) SetExternalKubeClientSet(client kubernetes.Interface) {\n\ta.quotaAccessor.client = client\n}","line":{"from":110,"to":113}} {"id":100016531,"name":"SetExternalKubeInformerFactory","signature":"func (a *QuotaAdmission) SetExternalKubeInformerFactory(f informers.SharedInformerFactory)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/admission.go","code":"// SetExternalKubeInformerFactory registers an informer factory into QuotaAdmission\nfunc (a *QuotaAdmission) SetExternalKubeInformerFactory(f informers.SharedInformerFactory) {\n\ta.quotaAccessor.lister = f.Core().V1().ResourceQuotas().Lister()\n}","line":{"from":115,"to":118}} {"id":100016532,"name":"SetQuotaConfiguration","signature":"func (a *QuotaAdmission) SetQuotaConfiguration(c quota.Configuration)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/admission.go","code":"// SetQuotaConfiguration assigns and initializes configuration and evaluator for QuotaAdmission\nfunc (a *QuotaAdmission) SetQuotaConfiguration(c quota.Configuration) {\n\ta.quotaConfiguration = c\n\tif a.stopCh == nil {\n\t\ta.initializationErr = stopChUnconfiguredErr\n\t\treturn\n\t}\n\ta.evaluator = NewQuotaEvaluator(a.quotaAccessor, a.quotaConfiguration.IgnoredResources(), generic.NewRegistry(a.quotaConfiguration.Evaluators()), nil, a.config, a.numEvaluators, a.stopCh)\n}","line":{"from":120,"to":128}} {"id":100016533,"name":"ValidateInitialization","signature":"func (a *QuotaAdmission) ValidateInitialization() error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/admission.go","code":"// ValidateInitialization ensures an authorizer is set.\nfunc (a *QuotaAdmission) ValidateInitialization() error {\n\tif a.initializationErr != nil {\n\t\treturn a.initializationErr\n\t}\n\tif a.stopCh == nil {\n\t\treturn fmt.Errorf(\"missing stopCh\")\n\t}\n\tif a.quotaAccessor == nil {\n\t\treturn fmt.Errorf(\"missing quotaAccessor\")\n\t}\n\tif a.quotaAccessor.client == nil {\n\t\treturn fmt.Errorf(\"missing quotaAccessor.client\")\n\t}\n\tif a.quotaAccessor.lister == nil {\n\t\treturn fmt.Errorf(\"missing quotaAccessor.lister\")\n\t}\n\tif a.quotaConfiguration == nil {\n\t\treturn fmt.Errorf(\"missing quotaConfiguration\")\n\t}\n\tif a.evaluator == nil {\n\t\treturn fmt.Errorf(\"missing evaluator\")\n\t}\n\treturn nil\n}","line":{"from":130,"to":154}} {"id":100016534,"name":"Validate","signature":"func (a *QuotaAdmission) Validate(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) (err error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/admission.go","code":"// Validate makes admission decisions while enforcing quota\nfunc (a *QuotaAdmission) Validate(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) (err error) {\n\t// ignore all operations that correspond to sub-resource actions\n\tif attr.GetSubresource() != \"\" {\n\t\treturn nil\n\t}\n\t// ignore all operations that are not namespaced or creation of namespaces\n\tif attr.GetNamespace() == \"\" || isNamespaceCreation(attr) {\n\t\treturn nil\n\t}\n\treturn a.evaluator.Evaluate(attr)\n}","line":{"from":156,"to":167}} {"id":100016535,"name":"isNamespaceCreation","signature":"func isNamespaceCreation(attr admission.Attributes) bool","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/admission.go","code":"func isNamespaceCreation(attr admission.Attributes) bool {\n\treturn attr.GetOperation() == admission.Create \u0026\u0026 attr.GetKind().GroupKind() == namespaceGVK\n}","line":{"from":169,"to":171}} {"id":100016536,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/apis/resourcequota/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(resourcequotaapi.AddToScheme(scheme))\n\n\t// v1beta1 and v1alpha1 are in the k8s.io-suffixed group\n\tutilruntime.Must(resourcequotav1beta1.AddToScheme(scheme))\n\tutilruntime.Must(resourcequotav1alpha1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(resourcequotav1beta1.SchemeGroupVersion, resourcequotav1alpha1.SchemeGroupVersion))\n\n\t// v1 is in the config.k8s.io-suffixed group\n\tutilruntime.Must(resourcequotav1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(resourcequotav1.SchemeGroupVersion))\n}","line":{"from":30,"to":42}} {"id":100016537,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/apis/resourcequota/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(LegacySchemeGroupVersion,\n\t\t\u0026Configuration{},\n\t)\n\tscheme.AddKnownTypeWithName(SchemeGroupVersion.WithKind(\"ResourceQuotaConfiguration\"),\n\t\t\u0026Configuration{},\n\t)\n\treturn nil\n}","line":{"from":43,"to":51}} {"id":100016538,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *kruntime.Scheme) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/apis/resourcequota/v1/defaults.go","code":"func addDefaultingFuncs(scheme *kruntime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":21,"to":23}} {"id":100016539,"name":"SetDefaults_Configuration","signature":"func SetDefaults_Configuration(obj *Configuration) {}","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/apis/resourcequota/v1/defaults.go","code":"func SetDefaults_Configuration(obj *Configuration) {}","line":{"from":25,"to":25}} {"id":100016540,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/apis/resourcequota/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addKnownTypes, addDefaultingFuncs)\n}","line":{"from":41,"to":46}} {"id":100016541,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/apis/resourcequota/v1/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypeWithName(SchemeGroupVersion.WithKind(\"ResourceQuotaConfiguration\"), \u0026Configuration{})\n\treturn nil\n}","line":{"from":48,"to":51}} {"id":100016542,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *kruntime.Scheme) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/apis/resourcequota/v1alpha1/defaults.go","code":"func addDefaultingFuncs(scheme *kruntime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":21,"to":23}} {"id":100016543,"name":"SetDefaults_Configuration","signature":"func SetDefaults_Configuration(obj *Configuration) {}","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/apis/resourcequota/v1alpha1/defaults.go","code":"func SetDefaults_Configuration(obj *Configuration) {}","line":{"from":25,"to":25}} {"id":100016544,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/apis/resourcequota/v1alpha1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addKnownTypes, addDefaultingFuncs)\n}","line":{"from":41,"to":46}} {"id":100016545,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/apis/resourcequota/v1alpha1/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Configuration{},\n\t)\n\treturn nil\n}","line":{"from":48,"to":53}} {"id":100016546,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *kruntime.Scheme) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/apis/resourcequota/v1beta1/defaults.go","code":"func addDefaultingFuncs(scheme *kruntime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":21,"to":23}} {"id":100016547,"name":"SetDefaults_Configuration","signature":"func SetDefaults_Configuration(obj *Configuration) {}","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/apis/resourcequota/v1beta1/defaults.go","code":"func SetDefaults_Configuration(obj *Configuration) {}","line":{"from":25,"to":25}} {"id":100016548,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/apis/resourcequota/v1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addKnownTypes, addDefaultingFuncs)\n}","line":{"from":41,"to":46}} {"id":100016549,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/apis/resourcequota/v1beta1/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Configuration{},\n\t)\n\treturn nil\n}","line":{"from":48,"to":53}} {"id":100016550,"name":"ValidateConfiguration","signature":"func ValidateConfiguration(config *resourcequotaapi.Configuration) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/apis/resourcequota/validation/validation.go","code":"// ValidateConfiguration validates the configuration.\nfunc ValidateConfiguration(config *resourcequotaapi.Configuration) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfldPath := field.NewPath(\"limitedResources\")\n\tfor i, limitedResource := range config.LimitedResources {\n\t\tidxPath := fldPath.Index(i)\n\t\tif len(limitedResource.Resource) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(idxPath.Child(\"resource\"), \"\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":25,"to":36}} {"id":100016551,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/config.go","code":"func init() {\n\tinstall.Install(scheme)\n}","line":{"from":36,"to":38}} {"id":100016552,"name":"LoadConfiguration","signature":"func LoadConfiguration(config io.Reader) (*resourcequotaapi.Configuration, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/config.go","code":"// LoadConfiguration loads the provided configuration.\nfunc LoadConfiguration(config io.Reader) (*resourcequotaapi.Configuration, error) {\n\t// if no config is provided, return a default configuration\n\tif config == nil {\n\t\texternalConfig := \u0026resourcequotav1.Configuration{}\n\t\tscheme.Default(externalConfig)\n\t\tinternalConfig := \u0026resourcequotaapi.Configuration{}\n\t\tif err := scheme.Convert(externalConfig, internalConfig, nil); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn internalConfig, nil\n\t}\n\t// we have a config so parse it.\n\tdata, err := ioutil.ReadAll(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdecoder := codecs.UniversalDecoder()\n\tdecodedObj, err := runtime.Decode(decoder, data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresourceQuotaConfiguration, ok := decodedObj.(*resourcequotaapi.Configuration)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unexpected type: %T\", decodedObj)\n\t}\n\treturn resourceQuotaConfiguration, nil\n}","line":{"from":40,"to":67}} {"id":100016553,"name":"Error","signature":"func (defaultDeny) Error() string","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/controller.go","code":"func (defaultDeny) Error() string {\n\treturn \"DEFAULT DENY\"\n}","line":{"from":89,"to":91}} {"id":100016554,"name":"IsDefaultDeny","signature":"func IsDefaultDeny(err error) bool","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/controller.go","code":"// IsDefaultDeny returns true if the error is defaultDeny\nfunc IsDefaultDeny(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\n\t_, ok := err.(defaultDeny)\n\treturn ok\n}","line":{"from":93,"to":101}} {"id":100016555,"name":"newAdmissionWaiter","signature":"func newAdmissionWaiter(a admission.Attributes) *admissionWaiter","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/controller.go","code":"func newAdmissionWaiter(a admission.Attributes) *admissionWaiter {\n\treturn \u0026admissionWaiter{\n\t\tattributes: a,\n\t\tfinished: make(chan struct{}),\n\t\tresult: defaultDeny{},\n\t}\n}","line":{"from":103,"to":109}} {"id":100016556,"name":"NewQuotaEvaluator","signature":"func NewQuotaEvaluator(quotaAccessor QuotaAccessor, ignoredResources map[schema.GroupResource]struct{}, quotaRegistry quota.Registry, lockAcquisitionFunc func([]corev1.ResourceQuota) func(), config *resourcequotaapi.Configuration, workers int, stopCh \u003c-chan struct{}) Evaluator","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/controller.go","code":"// NewQuotaEvaluator configures an admission controller that can enforce quota constraints\n// using the provided registry. The registry must have the capability to handle group/kinds that\n// are persisted by the server this admission controller is intercepting\nfunc NewQuotaEvaluator(quotaAccessor QuotaAccessor, ignoredResources map[schema.GroupResource]struct{}, quotaRegistry quota.Registry, lockAcquisitionFunc func([]corev1.ResourceQuota) func(), config *resourcequotaapi.Configuration, workers int, stopCh \u003c-chan struct{}) Evaluator {\n\t// if we get a nil config, just create an empty default.\n\tif config == nil {\n\t\tconfig = \u0026resourcequotaapi.Configuration{}\n\t}\n\n\tevaluator := \u0026quotaEvaluator{\n\t\tquotaAccessor: quotaAccessor,\n\t\tlockAcquisitionFunc: lockAcquisitionFunc,\n\n\t\tignoredResources: ignoredResources,\n\t\tregistry: quotaRegistry,\n\n\t\tqueue: workqueue.NewNamed(\"admission_quota_controller\"),\n\t\twork: map[string][]*admissionWaiter{},\n\t\tdirtyWork: map[string][]*admissionWaiter{},\n\t\tinProgress: sets.String{},\n\n\t\tworkers: workers,\n\t\tstopCh: stopCh,\n\t\tconfig: config,\n\t}\n\n\t// The queue underneath is starting a goroutine for metrics\n\t// exportint that is only stopped on calling ShutDown.\n\t// Given that QuotaEvaluator is created for each layer of apiserver\n\t// and often not started for some of those (e.g. aggregated apiserver)\n\t// we explicitly shut it down on stopCh signal even if it wasn't\n\t// effectively started.\n\tgo evaluator.shutdownOnStop()\n\n\treturn evaluator\n}","line":{"from":111,"to":146}} {"id":100016557,"name":"start","signature":"func (e *quotaEvaluator) start()","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/controller.go","code":"// start begins watching and syncing.\nfunc (e *quotaEvaluator) start() {\n\tdefer utilruntime.HandleCrash()\n\n\tfor i := 0; i \u003c e.workers; i++ {\n\t\tgo wait.Until(e.doWork, time.Second, e.stopCh)\n\t}\n}","line":{"from":148,"to":155}} {"id":100016558,"name":"shutdownOnStop","signature":"func (e *quotaEvaluator) shutdownOnStop()","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/controller.go","code":"func (e *quotaEvaluator) shutdownOnStop() {\n\t\u003c-e.stopCh\n\tklog.Infof(\"Shutting down quota evaluator\")\n\te.queue.ShutDown()\n}","line":{"from":157,"to":161}} {"id":100016559,"name":"doWork","signature":"func (e *quotaEvaluator) doWork()","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/controller.go","code":"func (e *quotaEvaluator) doWork() {\n\tworkFunc := func() bool {\n\t\tns, admissionAttributes, quit := e.getWork()\n\t\tif quit {\n\t\t\treturn true\n\t\t}\n\t\tdefer e.completeWork(ns)\n\t\tif len(admissionAttributes) == 0 {\n\t\t\treturn false\n\t\t}\n\t\te.checkAttributes(ns, admissionAttributes)\n\t\treturn false\n\t}\n\tfor {\n\t\tif quit := workFunc(); quit {\n\t\t\tklog.Infof(\"quota evaluator worker shutdown\")\n\t\t\treturn\n\t\t}\n\t}\n}","line":{"from":163,"to":182}} {"id":100016560,"name":"checkAttributes","signature":"func (e *quotaEvaluator) checkAttributes(ns string, admissionAttributes []*admissionWaiter)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/controller.go","code":"// checkAttributes iterates evaluates all the waiting admissionAttributes. It will always notify all waiters\n// before returning. The default is to deny.\nfunc (e *quotaEvaluator) checkAttributes(ns string, admissionAttributes []*admissionWaiter) {\n\t// notify all on exit\n\tdefer func() {\n\t\tfor _, admissionAttribute := range admissionAttributes {\n\t\t\tclose(admissionAttribute.finished)\n\t\t}\n\t}()\n\n\tquotas, err := e.quotaAccessor.GetQuotas(ns)\n\tif err != nil {\n\t\tfor _, admissionAttribute := range admissionAttributes {\n\t\t\tadmissionAttribute.result = err\n\t\t}\n\t\treturn\n\t}\n\t// if limited resources are disabled, we can just return safely when there are no quotas.\n\tlimitedResourcesDisabled := len(e.config.LimitedResources) == 0\n\tif len(quotas) == 0 \u0026\u0026 limitedResourcesDisabled {\n\t\tfor _, admissionAttribute := range admissionAttributes {\n\t\t\tadmissionAttribute.result = nil\n\t\t}\n\t\treturn\n\t}\n\n\tif e.lockAcquisitionFunc != nil {\n\t\treleaseLocks := e.lockAcquisitionFunc(quotas)\n\t\tdefer releaseLocks()\n\t}\n\n\te.checkQuotas(quotas, admissionAttributes, 3)\n}","line":{"from":184,"to":216}} {"id":100016561,"name":"checkQuotas","signature":"func (e *quotaEvaluator) checkQuotas(quotas []corev1.ResourceQuota, admissionAttributes []*admissionWaiter, remainingRetries int)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/controller.go","code":"// checkQuotas checks the admission attributes against the passed quotas. If a quota applies, it will attempt to update it\n// AFTER it has checked all the admissionAttributes. The method breaks down into phase like this:\n// 0. make a copy of the quotas to act as a \"running\" quota so we know what we need to update and can still compare against the\n// originals\n// 1. check each admission attribute to see if it fits within *all* the quotas. If it doesn't fit, mark the waiter as failed\n// and the running quota don't change. If it did fit, check to see if any quota was changed. It there was no quota change\n// mark the waiter as succeeded. If some quota did change, update the running quotas\n// 2. If no running quota was changed, return now since no updates are needed.\n// 3. for each quota that has changed, attempt an update. If all updates succeeded, update all unset waiters to success status and return. If the some\n// updates failed on conflict errors and we have retries left, re-get the failed quota from our cache for the latest version\n// and recurse into this method with the subset. It's safe for us to evaluate ONLY the subset, because the other quota\n// documents for these waiters have already been evaluated. Step 1, will mark all the ones that should already have succeeded.\nfunc (e *quotaEvaluator) checkQuotas(quotas []corev1.ResourceQuota, admissionAttributes []*admissionWaiter, remainingRetries int) {\n\t// yet another copy to compare against originals to see if we actually have deltas\n\toriginalQuotas, err := copyQuotas(quotas)\n\tif err != nil {\n\t\tutilruntime.HandleError(err)\n\t\treturn\n\t}\n\n\tatLeastOneChanged := false\n\tfor i := range admissionAttributes {\n\t\tadmissionAttribute := admissionAttributes[i]\n\t\tnewQuotas, err := e.checkRequest(quotas, admissionAttribute.attributes)\n\t\tif err != nil {\n\t\t\tadmissionAttribute.result = err\n\t\t\tcontinue\n\t\t}\n\n\t\t// Don't update quota for admissionAttributes that correspond to dry-run requests\n\t\tif admissionAttribute.attributes.IsDryRun() {\n\t\t\tadmissionAttribute.result = nil\n\t\t\tcontinue\n\t\t}\n\n\t\t// if the new quotas are the same as the old quotas, then this particular one doesn't issue any updates\n\t\t// that means that no quota docs applied, so it can get a pass\n\t\tatLeastOneChangeForThisWaiter := false\n\t\tfor j := range newQuotas {\n\t\t\tif !quota.Equals(quotas[j].Status.Used, newQuotas[j].Status.Used) {\n\t\t\t\tatLeastOneChanged = true\n\t\t\t\tatLeastOneChangeForThisWaiter = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !atLeastOneChangeForThisWaiter {\n\t\t\tadmissionAttribute.result = nil\n\t\t}\n\n\t\tquotas = newQuotas\n\t}\n\n\t// if none of the requests changed anything, there's no reason to issue an update, just fail them all now\n\tif !atLeastOneChanged {\n\t\treturn\n\t}\n\n\t// now go through and try to issue updates. Things get a little weird here:\n\t// 1. check to see if the quota changed. If not, skip.\n\t// 2. if the quota changed and the update passes, be happy\n\t// 3. if the quota changed and the update fails, add the original to a retry list\n\tvar updatedFailedQuotas []corev1.ResourceQuota\n\tvar lastErr error\n\tfor i := range quotas {\n\t\tnewQuota := quotas[i]\n\n\t\t// if this quota didn't have its status changed, skip it\n\t\tif quota.Equals(originalQuotas[i].Status.Used, newQuota.Status.Used) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := e.quotaAccessor.UpdateQuotaStatus(\u0026newQuota); err != nil {\n\t\t\tupdatedFailedQuotas = append(updatedFailedQuotas, newQuota)\n\t\t\tlastErr = err\n\t\t}\n\t}\n\n\tif len(updatedFailedQuotas) == 0 {\n\t\t// all the updates succeeded. At this point, anything with the default deny error was just waiting to\n\t\t// get a successful update, so we can mark and notify\n\t\tfor _, admissionAttribute := range admissionAttributes {\n\t\t\tif IsDefaultDeny(admissionAttribute.result) {\n\t\t\t\tadmissionAttribute.result = nil\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\n\t// at this point, errors are fatal. Update all waiters without status to failed and return\n\tif remainingRetries \u003c= 0 {\n\t\tfor _, admissionAttribute := range admissionAttributes {\n\t\t\tif IsDefaultDeny(admissionAttribute.result) {\n\t\t\t\tadmissionAttribute.result = lastErr\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\n\t// this retry logic has the same bug that its possible to be checking against quota in a state that never actually exists where\n\t// you've added a new documented, then updated an old one, your resource matches both and you're only checking one\n\t// updates for these quota names failed. Get the current quotas in the namespace, compare by name, check to see if the\n\t// resource versions have changed. If not, we're going to fall through an fail everything. If they all have, then we can try again\n\tnewQuotas, err := e.quotaAccessor.GetQuotas(quotas[0].Namespace)\n\tif err != nil {\n\t\t// this means that updates failed. Anything with a default deny error has failed and we need to let them know\n\t\tfor _, admissionAttribute := range admissionAttributes {\n\t\t\tif IsDefaultDeny(admissionAttribute.result) {\n\t\t\t\tadmissionAttribute.result = lastErr\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\n\t// this logic goes through our cache to find the new version of all quotas that failed update. If something has been removed\n\t// it is skipped on this retry. After all, you removed it.\n\tquotasToCheck := []corev1.ResourceQuota{}\n\tfor _, newQuota := range newQuotas {\n\t\tfor _, oldQuota := range updatedFailedQuotas {\n\t\t\tif newQuota.Name == oldQuota.Name {\n\t\t\t\tquotasToCheck = append(quotasToCheck, newQuota)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\te.checkQuotas(quotasToCheck, admissionAttributes, remainingRetries-1)\n}","line":{"from":218,"to":344}} {"id":100016562,"name":"copyQuotas","signature":"func copyQuotas(in []corev1.ResourceQuota) ([]corev1.ResourceQuota, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/controller.go","code":"func copyQuotas(in []corev1.ResourceQuota) ([]corev1.ResourceQuota, error) {\n\tout := make([]corev1.ResourceQuota, 0, len(in))\n\tfor _, quota := range in {\n\t\tout = append(out, *quota.DeepCopy())\n\t}\n\n\treturn out, nil\n}","line":{"from":346,"to":353}} {"id":100016563,"name":"filterLimitedResourcesByGroupResource","signature":"func filterLimitedResourcesByGroupResource(input []resourcequotaapi.LimitedResource, groupResource schema.GroupResource) []resourcequotaapi.LimitedResource","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/controller.go","code":"// filterLimitedResourcesByGroupResource filters the input that match the specified groupResource\nfunc filterLimitedResourcesByGroupResource(input []resourcequotaapi.LimitedResource, groupResource schema.GroupResource) []resourcequotaapi.LimitedResource {\n\tresult := []resourcequotaapi.LimitedResource{}\n\tfor i := range input {\n\t\tlimitedResource := input[i]\n\t\tlimitedGroupResource := schema.GroupResource{Group: limitedResource.APIGroup, Resource: limitedResource.Resource}\n\t\tif limitedGroupResource == groupResource {\n\t\t\tresult = append(result, limitedResource)\n\t\t}\n\t}\n\treturn result\n}","line":{"from":355,"to":366}} {"id":100016564,"name":"limitedByDefault","signature":"func limitedByDefault(usage corev1.ResourceList, limitedResources []resourcequotaapi.LimitedResource) []corev1.ResourceName","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/controller.go","code":"// limitedByDefault determines from the specified usage and limitedResources the set of resources names\n// that must be present in a covering quota. It returns empty set if it was unable to determine if\n// a resource was not limited by default.\nfunc limitedByDefault(usage corev1.ResourceList, limitedResources []resourcequotaapi.LimitedResource) []corev1.ResourceName {\n\tresult := []corev1.ResourceName{}\n\tfor _, limitedResource := range limitedResources {\n\t\tfor k, v := range usage {\n\t\t\t// if a resource is consumed, we need to check if it matches on the limited resource list.\n\t\t\tif v.Sign() == 1 {\n\t\t\t\t// if we get a match, we add it to limited set\n\t\t\t\tfor _, matchContain := range limitedResource.MatchContains {\n\t\t\t\t\tif strings.Contains(string(k), matchContain) {\n\t\t\t\t\t\tresult = append(result, k)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}","line":{"from":368,"to":388}} {"id":100016565,"name":"getMatchedLimitedScopes","signature":"func getMatchedLimitedScopes(evaluator quota.Evaluator, inputObject runtime.Object, limitedResources []resourcequotaapi.LimitedResource) ([]corev1.ScopedResourceSelectorRequirement, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/controller.go","code":"func getMatchedLimitedScopes(evaluator quota.Evaluator, inputObject runtime.Object, limitedResources []resourcequotaapi.LimitedResource) ([]corev1.ScopedResourceSelectorRequirement, error) {\n\tscopes := []corev1.ScopedResourceSelectorRequirement{}\n\tfor _, limitedResource := range limitedResources {\n\t\tmatched, err := evaluator.MatchingScopes(inputObject, limitedResource.MatchScopes)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Error while matching limited Scopes\")\n\t\t\treturn []corev1.ScopedResourceSelectorRequirement{}, err\n\t\t}\n\t\tscopes = append(scopes, matched...)\n\t}\n\treturn scopes, nil\n}","line":{"from":390,"to":401}} {"id":100016566,"name":"checkRequest","signature":"func (e *quotaEvaluator) checkRequest(quotas []corev1.ResourceQuota, a admission.Attributes) ([]corev1.ResourceQuota, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/controller.go","code":"// checkRequest verifies that the request does not exceed any quota constraint. it returns a copy of quotas not yet persisted\n// that capture what the usage would be if the request succeeded. It return an error if there is insufficient quota to satisfy the request\nfunc (e *quotaEvaluator) checkRequest(quotas []corev1.ResourceQuota, a admission.Attributes) ([]corev1.ResourceQuota, error) {\n\tevaluator := e.registry.Get(a.GetResource().GroupResource())\n\tif evaluator == nil {\n\t\treturn quotas, nil\n\t}\n\treturn CheckRequest(quotas, a, evaluator, e.config.LimitedResources)\n}","line":{"from":403,"to":411}} {"id":100016567,"name":"CheckRequest","signature":"func CheckRequest(quotas []corev1.ResourceQuota, a admission.Attributes, evaluator quota.Evaluator,","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/controller.go","code":"// CheckRequest is a static version of quotaEvaluator.checkRequest, possible to be called from outside.\nfunc CheckRequest(quotas []corev1.ResourceQuota, a admission.Attributes, evaluator quota.Evaluator,\n\tlimited []resourcequotaapi.LimitedResource) ([]corev1.ResourceQuota, error) {\n\tif !evaluator.Handles(a) {\n\t\treturn quotas, nil\n\t}\n\n\t// if we have limited resources enabled for this resource, always calculate usage\n\tinputObject := a.GetObject()\n\n\t// Check if object matches AdmissionConfiguration matchScopes\n\tlimitedScopes, err := getMatchedLimitedScopes(evaluator, inputObject, limited)\n\tif err != nil {\n\t\treturn quotas, nil\n\t}\n\n\t// determine the set of resource names that must exist in a covering quota\n\tlimitedResourceNames := []corev1.ResourceName{}\n\tlimitedResources := filterLimitedResourcesByGroupResource(limited, a.GetResource().GroupResource())\n\tif len(limitedResources) \u003e 0 {\n\t\tdeltaUsage, err := evaluator.Usage(inputObject)\n\t\tif err != nil {\n\t\t\treturn quotas, err\n\t\t}\n\t\tlimitedResourceNames = limitedByDefault(deltaUsage, limitedResources)\n\t}\n\tlimitedResourceNamesSet := quota.ToSet(limitedResourceNames)\n\n\t// find the set of quotas that are pertinent to this request\n\t// reject if we match the quota, but usage is not calculated yet\n\t// reject if the input object does not satisfy quota constraints\n\t// if there are no pertinent quotas, we can just return\n\tinterestingQuotaIndexes := []int{}\n\t// track the cumulative set of resources that were required across all quotas\n\t// this is needed to know if we have satisfied any constraints where consumption\n\t// was limited by default.\n\trestrictedResourcesSet := sets.String{}\n\trestrictedScopes := []corev1.ScopedResourceSelectorRequirement{}\n\tfor i := range quotas {\n\t\tresourceQuota := quotas[i]\n\t\tscopeSelectors := getScopeSelectorsFromQuota(resourceQuota)\n\t\tlocalRestrictedScopes, err := evaluator.MatchingScopes(inputObject, scopeSelectors)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error matching scopes of quota %s, err: %v\", resourceQuota.Name, err)\n\t\t}\n\t\trestrictedScopes = append(restrictedScopes, localRestrictedScopes...)\n\n\t\tmatch, err := evaluator.Matches(\u0026resourceQuota, inputObject)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Error occurred while matching resource quota against input object\",\n\t\t\t\t\"resourceQuota\", resourceQuota)\n\t\t\treturn quotas, err\n\t\t}\n\t\tif !match {\n\t\t\tcontinue\n\t\t}\n\n\t\thardResources := quota.ResourceNames(resourceQuota.Status.Hard)\n\t\trestrictedResources := evaluator.MatchingResources(hardResources)\n\t\tif err := evaluator.Constraints(restrictedResources, inputObject); err != nil {\n\t\t\treturn nil, admission.NewForbidden(a, fmt.Errorf(\"failed quota: %s: %v\", resourceQuota.Name, err))\n\t\t}\n\t\tif !hasUsageStats(\u0026resourceQuota, restrictedResources) {\n\t\t\treturn nil, admission.NewForbidden(a, fmt.Errorf(\"status unknown for quota: %s, resources: %s\", resourceQuota.Name, prettyPrintResourceNames(restrictedResources)))\n\t\t}\n\t\tinterestingQuotaIndexes = append(interestingQuotaIndexes, i)\n\t\tlocalRestrictedResourcesSet := quota.ToSet(restrictedResources)\n\t\trestrictedResourcesSet.Insert(localRestrictedResourcesSet.List()...)\n\t}\n\n\t// Usage of some resources cannot be counted in isolation. For example, when\n\t// the resource represents a number of unique references to external\n\t// resource. In such a case an evaluator needs to process other objects in\n\t// the same namespace which needs to be known.\n\tnamespace := a.GetNamespace()\n\tif accessor, err := meta.Accessor(inputObject); namespace != \"\" \u0026\u0026 err == nil {\n\t\tif accessor.GetNamespace() == \"\" {\n\t\t\taccessor.SetNamespace(namespace)\n\t\t}\n\t}\n\t// there is at least one quota that definitely matches our object\n\t// as a result, we need to measure the usage of this object for quota\n\t// on updates, we need to subtract the previous measured usage\n\t// if usage shows no change, just return since it has no impact on quota\n\tdeltaUsage, err := evaluator.Usage(inputObject)\n\tif err != nil {\n\t\treturn quotas, err\n\t}\n\n\t// ensure that usage for input object is never negative (this would mean a resource made a negative resource requirement)\n\tif negativeUsage := quota.IsNegative(deltaUsage); len(negativeUsage) \u003e 0 {\n\t\treturn nil, admission.NewForbidden(a, fmt.Errorf(\"quota usage is negative for resource(s): %s\", prettyPrintResourceNames(negativeUsage)))\n\t}\n\n\tif admission.Update == a.GetOperation() {\n\t\tprevItem := a.GetOldObject()\n\t\tif prevItem == nil {\n\t\t\treturn nil, admission.NewForbidden(a, fmt.Errorf(\"unable to get previous usage since prior version of object was not found\"))\n\t\t}\n\n\t\t// if we can definitively determine that this is not a case of \"create on update\",\n\t\t// then charge based on the delta. Otherwise, bill the maximum\n\t\tmetadata, err := meta.Accessor(prevItem)\n\t\tif err == nil \u0026\u0026 len(metadata.GetResourceVersion()) \u003e 0 {\n\t\t\tprevUsage, innerErr := evaluator.Usage(prevItem)\n\t\t\tif innerErr != nil {\n\t\t\t\treturn quotas, innerErr\n\t\t\t}\n\t\t\tif feature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) {\n\t\t\t\t// allow negative usage for pods as pod resources can increase or decrease\n\t\t\t\tif a.GetResource().GroupResource() == corev1.Resource(\"pods\") {\n\t\t\t\t\tdeltaUsage = quota.Subtract(deltaUsage, prevUsage)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdeltaUsage = quota.SubtractWithNonNegativeResult(deltaUsage, prevUsage)\n\t\t\t}\n\t\t}\n\t}\n\n\t// ignore items in deltaUsage with zero usage\n\tdeltaUsage = quota.RemoveZeros(deltaUsage)\n\t// if there is no remaining non-zero usage, short-circuit and return\n\tif len(deltaUsage) == 0 {\n\t\treturn quotas, nil\n\t}\n\n\t// verify that for every resource that had limited by default consumption\n\t// enabled that there was a corresponding quota that covered its use.\n\t// if not, we reject the request.\n\thasNoCoveringQuota := limitedResourceNamesSet.Difference(restrictedResourcesSet)\n\tif len(hasNoCoveringQuota) \u003e 0 {\n\t\treturn quotas, admission.NewForbidden(a, fmt.Errorf(\"insufficient quota to consume: %v\", strings.Join(hasNoCoveringQuota.List(), \",\")))\n\t}\n\n\t// verify that for every scope that had limited access enabled\n\t// that there was a corresponding quota that covered it.\n\t// if not, we reject the request.\n\tscopesHasNoCoveringQuota, err := evaluator.UncoveredQuotaScopes(limitedScopes, restrictedScopes)\n\tif err != nil {\n\t\treturn quotas, err\n\t}\n\tif len(scopesHasNoCoveringQuota) \u003e 0 {\n\t\treturn quotas, fmt.Errorf(\"insufficient quota to match these scopes: %v\", scopesHasNoCoveringQuota)\n\t}\n\n\tif len(interestingQuotaIndexes) == 0 {\n\t\treturn quotas, nil\n\t}\n\n\toutQuotas, err := copyQuotas(quotas)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, index := range interestingQuotaIndexes {\n\t\tresourceQuota := outQuotas[index]\n\n\t\thardResources := quota.ResourceNames(resourceQuota.Status.Hard)\n\t\trequestedUsage := quota.Mask(deltaUsage, hardResources)\n\t\tnewUsage := quota.Add(resourceQuota.Status.Used, requestedUsage)\n\t\tmaskedNewUsage := quota.Mask(newUsage, quota.ResourceNames(requestedUsage))\n\n\t\tif allowed, exceeded := quota.LessThanOrEqual(maskedNewUsage, resourceQuota.Status.Hard); !allowed {\n\t\t\tfailedRequestedUsage := quota.Mask(requestedUsage, exceeded)\n\t\t\tfailedUsed := quota.Mask(resourceQuota.Status.Used, exceeded)\n\t\t\tfailedHard := quota.Mask(resourceQuota.Status.Hard, exceeded)\n\t\t\treturn nil, admission.NewForbidden(a,\n\t\t\t\tfmt.Errorf(\"exceeded quota: %s, requested: %s, used: %s, limited: %s\",\n\t\t\t\t\tresourceQuota.Name,\n\t\t\t\t\tprettyPrint(failedRequestedUsage),\n\t\t\t\t\tprettyPrint(failedUsed),\n\t\t\t\t\tprettyPrint(failedHard)))\n\t\t}\n\n\t\t// update to the new usage number\n\t\toutQuotas[index].Status.Used = newUsage\n\t}\n\n\treturn outQuotas, nil\n}","line":{"from":413,"to":592}} {"id":100016568,"name":"getScopeSelectorsFromQuota","signature":"func getScopeSelectorsFromQuota(quota corev1.ResourceQuota) []corev1.ScopedResourceSelectorRequirement","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/controller.go","code":"func getScopeSelectorsFromQuota(quota corev1.ResourceQuota) []corev1.ScopedResourceSelectorRequirement {\n\tselectors := []corev1.ScopedResourceSelectorRequirement{}\n\tfor _, scope := range quota.Spec.Scopes {\n\t\tselectors = append(selectors, corev1.ScopedResourceSelectorRequirement{\n\t\t\tScopeName: scope,\n\t\t\tOperator: corev1.ScopeSelectorOpExists})\n\t}\n\tif quota.Spec.ScopeSelector != nil {\n\t\tselectors = append(selectors, quota.Spec.ScopeSelector.MatchExpressions...)\n\t}\n\treturn selectors\n}","line":{"from":594,"to":605}} {"id":100016569,"name":"Evaluate","signature":"func (e *quotaEvaluator) Evaluate(a admission.Attributes) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/controller.go","code":"func (e *quotaEvaluator) Evaluate(a admission.Attributes) error {\n\te.init.Do(e.start)\n\n\t// is this resource ignored?\n\tgvr := a.GetResource()\n\tgr := gvr.GroupResource()\n\tif _, ok := e.ignoredResources[gr]; ok {\n\t\treturn nil\n\t}\n\n\t// if we do not know how to evaluate use for this resource, create an evaluator\n\tevaluator := e.registry.Get(gr)\n\tif evaluator == nil {\n\t\t// create an object count evaluator if no evaluator previously registered\n\t\t// note, we do not need aggregate usage here, so we pass a nil informer func\n\t\tevaluator = generic.NewObjectCountEvaluator(gr, nil, \"\")\n\t\te.registry.Add(evaluator)\n\t\tklog.Infof(\"quota admission added evaluator for: %s\", gr)\n\t}\n\t// for this kind, check if the operation could mutate any quota resources\n\t// if no resources tracked by quota are impacted, then just return\n\tif !evaluator.Handles(a) {\n\t\treturn nil\n\t}\n\twaiter := newAdmissionWaiter(a)\n\n\te.addWork(waiter)\n\n\t// wait for completion or timeout\n\tselect {\n\tcase \u003c-waiter.finished:\n\tcase \u003c-time.After(10 * time.Second):\n\t\treturn apierrors.NewInternalError(fmt.Errorf(\"resource quota evaluation timed out\"))\n\t}\n\n\treturn waiter.result\n}","line":{"from":607,"to":643}} {"id":100016570,"name":"addWork","signature":"func (e *quotaEvaluator) addWork(a *admissionWaiter)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/controller.go","code":"func (e *quotaEvaluator) addWork(a *admissionWaiter) {\n\te.workLock.Lock()\n\tdefer e.workLock.Unlock()\n\n\tns := a.attributes.GetNamespace()\n\t// this Add can trigger a Get BEFORE the work is added to a list, but this is ok because the getWork routine\n\t// waits the worklock before retrieving the work to do, so the writes in this method will be observed\n\te.queue.Add(ns)\n\n\tif e.inProgress.Has(ns) {\n\t\te.dirtyWork[ns] = append(e.dirtyWork[ns], a)\n\t\treturn\n\t}\n\n\te.work[ns] = append(e.work[ns], a)\n}","line":{"from":645,"to":660}} {"id":100016571,"name":"completeWork","signature":"func (e *quotaEvaluator) completeWork(ns string)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/controller.go","code":"func (e *quotaEvaluator) completeWork(ns string) {\n\te.workLock.Lock()\n\tdefer e.workLock.Unlock()\n\n\te.queue.Done(ns)\n\te.work[ns] = e.dirtyWork[ns]\n\tdelete(e.dirtyWork, ns)\n\te.inProgress.Delete(ns)\n}","line":{"from":662,"to":670}} {"id":100016572,"name":"getWork","signature":"func (e *quotaEvaluator) getWork() (string, []*admissionWaiter, bool)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/controller.go","code":"// getWork returns a namespace, a list of work items in that\n// namespace, and a shutdown boolean. If not shutdown then the return\n// must eventually be followed by a call on completeWork for the\n// returned namespace (regardless of whether the work item list is\n// empty).\nfunc (e *quotaEvaluator) getWork() (string, []*admissionWaiter, bool) {\n\tuncastNS, shutdown := e.queue.Get()\n\tif shutdown {\n\t\treturn \"\", []*admissionWaiter{}, shutdown\n\t}\n\tns := uncastNS.(string)\n\n\te.workLock.Lock()\n\tdefer e.workLock.Unlock()\n\t// at this point, we know we have a coherent view of e.work. It is entirely possible\n\t// that our workqueue has another item requeued to it, but we'll pick it up early. This ok\n\t// because the next time will go into our dirty list\n\n\twork := e.work[ns]\n\tdelete(e.work, ns)\n\tdelete(e.dirtyWork, ns)\n\te.inProgress.Insert(ns)\n\treturn ns, work, false\n}","line":{"from":672,"to":695}} {"id":100016573,"name":"prettyPrint","signature":"func prettyPrint(item corev1.ResourceList) string","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/controller.go","code":"// prettyPrint formats a resource list for usage in errors\n// it outputs resources sorted in increasing order\nfunc prettyPrint(item corev1.ResourceList) string {\n\tparts := []string{}\n\tkeys := []string{}\n\tfor key := range item {\n\t\tkeys = append(keys, string(key))\n\t}\n\tsort.Strings(keys)\n\tfor _, key := range keys {\n\t\tvalue := item[corev1.ResourceName(key)]\n\t\tconstraint := key + \"=\" + value.String()\n\t\tparts = append(parts, constraint)\n\t}\n\treturn strings.Join(parts, \",\")\n}","line":{"from":697,"to":712}} {"id":100016574,"name":"prettyPrintResourceNames","signature":"func prettyPrintResourceNames(a []corev1.ResourceName) string","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/controller.go","code":"func prettyPrintResourceNames(a []corev1.ResourceName) string {\n\tvalues := []string{}\n\tfor _, value := range a {\n\t\tvalues = append(values, string(value))\n\t}\n\tsort.Strings(values)\n\treturn strings.Join(values, \",\")\n}","line":{"from":714,"to":721}} {"id":100016575,"name":"hasUsageStats","signature":"func hasUsageStats(resourceQuota *corev1.ResourceQuota, interestingResources []corev1.ResourceName) bool","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/controller.go","code":"// hasUsageStats returns true if for each hard constraint in interestingResources there is a value for its current usage\nfunc hasUsageStats(resourceQuota *corev1.ResourceQuota, interestingResources []corev1.ResourceName) bool {\n\tinterestingSet := quota.ToSet(interestingResources)\n\tfor resourceName := range resourceQuota.Status.Hard {\n\t\tif !interestingSet.Has(string(resourceName)) {\n\t\t\tcontinue\n\t\t}\n\t\tif _, found := resourceQuota.Status.Used[resourceName]; !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":723,"to":735}} {"id":100016576,"name":"newQuotaAccessor","signature":"func newQuotaAccessor() (*quotaAccessor, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/resource_access.go","code":"// newQuotaAccessor creates an object that conforms to the QuotaAccessor interface to be used to retrieve quota objects.\nfunc newQuotaAccessor() (*quotaAccessor, error) {\n\tliveLookupCache := lru.New(100)\n\tupdatedCache := lru.New(100)\n\n\t// client and lister will be set when SetInternalKubeClientSet and SetInternalKubeInformerFactory are invoked\n\treturn \u0026quotaAccessor{\n\t\tliveLookupCache: liveLookupCache,\n\t\tliveTTL: time.Duration(30 * time.Second),\n\t\tupdatedQuotas: updatedCache,\n\t}, nil\n}","line":{"from":61,"to":72}} {"id":100016577,"name":"UpdateQuotaStatus","signature":"func (e *quotaAccessor) UpdateQuotaStatus(newQuota *corev1.ResourceQuota) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/resource_access.go","code":"func (e *quotaAccessor) UpdateQuotaStatus(newQuota *corev1.ResourceQuota) error {\n\tupdatedQuota, err := e.client.CoreV1().ResourceQuotas(newQuota.Namespace).UpdateStatus(context.TODO(), newQuota, metav1.UpdateOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tkey := newQuota.Namespace + \"/\" + newQuota.Name\n\te.updatedQuotas.Add(key, updatedQuota)\n\treturn nil\n}","line":{"from":74,"to":83}} {"id":100016578,"name":"checkCache","signature":"func (e *quotaAccessor) checkCache(quota *corev1.ResourceQuota) *corev1.ResourceQuota","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/resource_access.go","code":"// checkCache compares the passed quota against the value in the look-aside cache and returns the newer\n// if the cache is out of date, it deletes the stale entry. This only works because of etcd resourceVersions\n// being monotonically increasing integers\nfunc (e *quotaAccessor) checkCache(quota *corev1.ResourceQuota) *corev1.ResourceQuota {\n\tkey := quota.Namespace + \"/\" + quota.Name\n\tuncastCachedQuota, ok := e.updatedQuotas.Get(key)\n\tif !ok {\n\t\treturn quota\n\t}\n\tcachedQuota := uncastCachedQuota.(*corev1.ResourceQuota)\n\n\tif etcdVersioner.CompareResourceVersion(quota, cachedQuota) \u003e= 0 {\n\t\te.updatedQuotas.Remove(key)\n\t\treturn quota\n\t}\n\treturn cachedQuota\n}","line":{"from":87,"to":103}} {"id":100016579,"name":"GetQuotas","signature":"func (e *quotaAccessor) GetQuotas(namespace string) ([]corev1.ResourceQuota, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/resourcequota/resource_access.go","code":"func (e *quotaAccessor) GetQuotas(namespace string) ([]corev1.ResourceQuota, error) {\n\t// determine if there are any quotas in this namespace\n\t// if there are no quotas, we don't need to do anything\n\titems, err := e.lister.ResourceQuotas(namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error resolving quota: %v\", err)\n\t}\n\n\t// if there are no items held in our indexer, check our live-lookup LRU, if that misses, do the live lookup to prime it.\n\tif len(items) == 0 {\n\t\tlruItemObj, ok := e.liveLookupCache.Get(namespace)\n\t\tif !ok || lruItemObj.(liveLookupEntry).expiry.Before(time.Now()) {\n\t\t\t// TODO: If there are multiple operations at the same time and cache has just expired,\n\t\t\t// this may cause multiple List operations being issued at the same time.\n\t\t\t// If there is already in-flight List() for a given namespace, we should wait until\n\t\t\t// it is finished and cache is updated instead of doing the same, also to avoid\n\t\t\t// throttling - see #22422 for details.\n\t\t\tliveList, err := e.client.CoreV1().ResourceQuotas(namespace).List(context.TODO(), metav1.ListOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tnewEntry := liveLookupEntry{expiry: time.Now().Add(e.liveTTL)}\n\t\t\tfor i := range liveList.Items {\n\t\t\t\tnewEntry.items = append(newEntry.items, \u0026liveList.Items[i])\n\t\t\t}\n\t\t\te.liveLookupCache.Add(namespace, newEntry)\n\t\t\tlruItemObj = newEntry\n\t\t}\n\t\tlruEntry := lruItemObj.(liveLookupEntry)\n\t\tfor i := range lruEntry.items {\n\t\t\titems = append(items, lruEntry.items[i])\n\t\t}\n\t}\n\n\tresourceQuotas := []corev1.ResourceQuota{}\n\tfor i := range items {\n\t\tquota := items[i]\n\t\tquota = e.checkCache(quota)\n\t\t// always make a copy. We're going to muck around with this and we should never mutate the originals\n\t\tresourceQuotas = append(resourceQuotas, *quota)\n\t}\n\n\treturn resourceQuotas, nil\n}","line":{"from":105,"to":148}} {"id":100016580,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/admission.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {\n\t\treturn NewPlugin()\n\t})\n}","line":{"from":52,"to":57}} {"id":100016581,"name":"NewPlugin","signature":"func NewPlugin() (admission.Interface, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/admission.go","code":"func NewPlugin() (admission.Interface, error) {\n\treturn \u0026celAdmissionPlugin{\n\t\tHandler: admission.NewHandler(admission.Connect, admission.Create, admission.Delete, admission.Update),\n\t}, nil\n}","line":{"from":90,"to":94}} {"id":100016582,"name":"SetExternalKubeInformerFactory","signature":"func (c *celAdmissionPlugin) SetExternalKubeInformerFactory(f informers.SharedInformerFactory)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/admission.go","code":"func (c *celAdmissionPlugin) SetExternalKubeInformerFactory(f informers.SharedInformerFactory) {\n\tc.informerFactory = f\n}","line":{"from":96,"to":98}} {"id":100016583,"name":"SetExternalKubeClientSet","signature":"func (c *celAdmissionPlugin) SetExternalKubeClientSet(client kubernetes.Interface)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/admission.go","code":"func (c *celAdmissionPlugin) SetExternalKubeClientSet(client kubernetes.Interface) {\n\tc.client = client\n}","line":{"from":100,"to":102}} {"id":100016584,"name":"SetRESTMapper","signature":"func (c *celAdmissionPlugin) SetRESTMapper(mapper meta.RESTMapper)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/admission.go","code":"func (c *celAdmissionPlugin) SetRESTMapper(mapper meta.RESTMapper) {\n\tc.restMapper = mapper\n}","line":{"from":104,"to":106}} {"id":100016585,"name":"SetDynamicClient","signature":"func (c *celAdmissionPlugin) SetDynamicClient(client dynamic.Interface)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/admission.go","code":"func (c *celAdmissionPlugin) SetDynamicClient(client dynamic.Interface) {\n\tc.dynamicClient = client\n}","line":{"from":108,"to":110}} {"id":100016586,"name":"SetDrainedNotification","signature":"func (c *celAdmissionPlugin) SetDrainedNotification(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/admission.go","code":"func (c *celAdmissionPlugin) SetDrainedNotification(stopCh \u003c-chan struct{}) {\n\tc.stopCh = stopCh\n}","line":{"from":112,"to":114}} {"id":100016587,"name":"SetAuthorizer","signature":"func (c *celAdmissionPlugin) SetAuthorizer(authorizer authorizer.Authorizer)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/admission.go","code":"func (c *celAdmissionPlugin) SetAuthorizer(authorizer authorizer.Authorizer) {\n\tc.authorizer = authorizer\n}","line":{"from":116,"to":118}} {"id":100016588,"name":"SetSchemaResolver","signature":"func (c *celAdmissionPlugin) SetSchemaResolver(resolver resolver.SchemaResolver)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/admission.go","code":"func (c *celAdmissionPlugin) SetSchemaResolver(resolver resolver.SchemaResolver) {\n\tc.schemaResolver = resolver\n}","line":{"from":120,"to":122}} {"id":100016589,"name":"InspectFeatureGates","signature":"func (c *celAdmissionPlugin) InspectFeatureGates(featureGates featuregate.FeatureGate)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/admission.go","code":"func (c *celAdmissionPlugin) InspectFeatureGates(featureGates featuregate.FeatureGate) {\n\tif featureGates.Enabled(features.ValidatingAdmissionPolicy) {\n\t\tc.enabled = true\n\t}\n\tc.inspectedFeatureGates = true\n}","line":{"from":124,"to":129}} {"id":100016590,"name":"ValidateInitialization","signature":"func (c *celAdmissionPlugin) ValidateInitialization() error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/admission.go","code":"// ValidateInitialization - once clientset and informer factory are provided, creates and starts the admission controller\nfunc (c *celAdmissionPlugin) ValidateInitialization() error {\n\tif !c.inspectedFeatureGates {\n\t\treturn fmt.Errorf(\"%s did not see feature gates\", PluginName)\n\t}\n\tif !c.enabled {\n\t\treturn nil\n\t}\n\tif c.informerFactory == nil {\n\t\treturn errors.New(\"missing informer factory\")\n\t}\n\tif c.client == nil {\n\t\treturn errors.New(\"missing kubernetes client\")\n\t}\n\tif c.restMapper == nil {\n\t\treturn errors.New(\"missing rest mapper\")\n\t}\n\tif c.dynamicClient == nil {\n\t\treturn errors.New(\"missing dynamic client\")\n\t}\n\tif c.stopCh == nil {\n\t\treturn errors.New(\"missing stop channel\")\n\t}\n\tif c.authorizer == nil {\n\t\treturn errors.New(\"missing authorizer\")\n\t}\n\tc.evaluator = NewAdmissionController(c.informerFactory, c.client, c.restMapper, c.schemaResolver /* (optional) */, c.dynamicClient, c.authorizer)\n\tif err := c.evaluator.ValidateInitialization(); err != nil {\n\t\treturn err\n\t}\n\n\tc.SetReadyFunc(c.evaluator.HasSynced)\n\tgo c.evaluator.Run(c.stopCh)\n\treturn nil\n}","line":{"from":131,"to":165}} {"id":100016591,"name":"Handles","signature":"func (c *celAdmissionPlugin) Handles(operation admission.Operation) bool","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/admission.go","code":"func (c *celAdmissionPlugin) Handles(operation admission.Operation) bool {\n\treturn true\n}","line":{"from":171,"to":173}} {"id":100016592,"name":"Validate","signature":"func (c *celAdmissionPlugin) Validate(","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/admission.go","code":"func (c *celAdmissionPlugin) Validate(\n\tctx context.Context,\n\ta admission.Attributes,\n\to admission.ObjectInterfaces,\n) (err error) {\n\tif !c.enabled {\n\t\treturn nil\n\t}\n\n\t// isPolicyResource determines if an admission.Attributes object is describing\n\t// the admission of a ValidatingAdmissionPolicy or a ValidatingAdmissionPolicyBinding\n\tif isPolicyResource(a) {\n\t\treturn\n\t}\n\n\tif !c.WaitForReady() {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"not yet ready to handle request\"))\n\t}\n\n\treturn c.evaluator.Validate(ctx, a, o)\n}","line":{"from":175,"to":195}} {"id":100016593,"name":"isPolicyResource","signature":"func isPolicyResource(attr admission.Attributes) bool","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/admission.go","code":"func isPolicyResource(attr admission.Attributes) bool {\n\tgvk := attr.GetResource()\n\tif gvk.Group == \"admissionregistration.k8s.io\" {\n\t\tif gvk.Resource == \"validatingadmissionpolicies\" || gvk.Resource == \"validatingadmissionpolicybindings\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":197,"to":205}} {"id":100016594,"name":"NewAdmissionController","signature":"func NewAdmissionController(","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/controller.go","code":"func NewAdmissionController(\n\t// Injected Dependencies\n\tinformerFactory informers.SharedInformerFactory,\n\tclient kubernetes.Interface,\n\trestMapper meta.RESTMapper,\n\tschemaResolver resolver.SchemaResolver,\n\tdynamicClient dynamic.Interface,\n\tauthz authorizer.Authorizer,\n) CELPolicyEvaluator {\n\tvar typeChecker *TypeChecker\n\tif schemaResolver != nil {\n\t\ttypeChecker = \u0026TypeChecker{schemaResolver: schemaResolver, restMapper: restMapper}\n\t}\n\treturn \u0026celAdmissionController{\n\t\tdefinitions: atomic.Value{},\n\t\tpolicyController: newPolicyController(\n\t\t\trestMapper,\n\t\t\tclient,\n\t\t\tdynamicClient,\n\t\t\ttypeChecker,\n\t\t\tcel.NewFilterCompiler(),\n\t\t\tNewMatcher(matching.NewMatcher(informerFactory.Core().V1().Namespaces().Lister(), client)),\n\t\t\tgeneric.NewInformer[*v1alpha1.ValidatingAdmissionPolicy](\n\t\t\t\tinformerFactory.Admissionregistration().V1alpha1().ValidatingAdmissionPolicies().Informer()),\n\t\t\tgeneric.NewInformer[*v1alpha1.ValidatingAdmissionPolicyBinding](\n\t\t\t\tinformerFactory.Admissionregistration().V1alpha1().ValidatingAdmissionPolicyBindings().Informer()),\n\t\t\tauthz,\n\t\t),\n\t}\n}","line":{"from":123,"to":152}} {"id":100016595,"name":"Run","signature":"func (c *celAdmissionController) Run(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/controller.go","code":"func (c *celAdmissionController) Run(stopCh \u003c-chan struct{}) {\n\tctx, cancel := context.WithCancel(context.Background())\n\twg := sync.WaitGroup{}\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tc.policyController.Run(ctx)\n\t}()\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\n\t\t// Wait indefinitely until policies/bindings are listed \u0026 handled before\n\t\t// allowing policies to be refreshed\n\t\tif !cache.WaitForNamedCacheSync(\"cel-admission-controller\", ctx.Done(), c.policyController.HasSynced) {\n\t\t\treturn\n\t\t}\n\n\t\t// Loop every 1 second until context is cancelled, refreshing policies\n\t\twait.Until(c.refreshPolicies, 1*time.Second, ctx.Done())\n\t}()\n\n\t\u003c-stopCh\n\tcancel()\n\twg.Wait()\n}","line":{"from":154,"to":181}} {"id":100016596,"name":"Validate","signature":"func (c *celAdmissionController) Validate(","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/controller.go","code":"func (c *celAdmissionController) Validate(\n\tctx context.Context,\n\ta admission.Attributes,\n\to admission.ObjectInterfaces,\n) (err error) {\n\tif !c.HasSynced() {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"not yet ready to handle request\"))\n\t}\n\n\tvar deniedDecisions []policyDecisionWithMetadata\n\n\taddConfigError := func(err error, definition *v1alpha1.ValidatingAdmissionPolicy, binding *v1alpha1.ValidatingAdmissionPolicyBinding) {\n\t\t// we always default the FailurePolicy if it is unset and validate it in API level\n\t\tvar policy v1alpha1.FailurePolicyType\n\t\tif definition.Spec.FailurePolicy == nil {\n\t\t\tpolicy = v1alpha1.Fail\n\t\t} else {\n\t\t\tpolicy = *definition.Spec.FailurePolicy\n\t\t}\n\n\t\t// apply FailurePolicy specified in ValidatingAdmissionPolicy, the default would be Fail\n\t\tswitch policy {\n\t\tcase v1alpha1.Ignore:\n\t\t\t// TODO: add metrics for ignored error here\n\t\t\treturn\n\t\tcase v1alpha1.Fail:\n\t\t\tvar message string\n\t\t\tif binding == nil {\n\t\t\t\tmessage = fmt.Errorf(\"failed to configure policy: %w\", err).Error()\n\t\t\t} else {\n\t\t\t\tmessage = fmt.Errorf(\"failed to configure binding: %w\", err).Error()\n\t\t\t}\n\t\t\tdeniedDecisions = append(deniedDecisions, policyDecisionWithMetadata{\n\t\t\t\tPolicyDecision: PolicyDecision{\n\t\t\t\t\tAction: ActionDeny,\n\t\t\t\t\tMessage: message,\n\t\t\t\t},\n\t\t\t\tDefinition: definition,\n\t\t\t\tBinding: binding,\n\t\t\t})\n\t\tdefault:\n\t\t\tdeniedDecisions = append(deniedDecisions, policyDecisionWithMetadata{\n\t\t\t\tPolicyDecision: PolicyDecision{\n\t\t\t\t\tAction: ActionDeny,\n\t\t\t\t\tMessage: fmt.Errorf(\"unrecognized failure policy: '%v'\", policy).Error(),\n\t\t\t\t},\n\t\t\t\tDefinition: definition,\n\t\t\t\tBinding: binding,\n\t\t\t})\n\t\t}\n\t}\n\tpolicyDatas := c.definitions.Load().([]policyData)\n\n\tfor _, definitionInfo := range policyDatas {\n\t\tdefinition := definitionInfo.lastReconciledValue\n\t\tmatches, matchKind, err := c.policyController.matcher.DefinitionMatches(a, o, definition)\n\t\tif err != nil {\n\t\t\t// Configuration error.\n\t\t\taddConfigError(err, definition, nil)\n\t\t\tcontinue\n\t\t}\n\t\tif !matches {\n\t\t\t// Policy definition does not match request\n\t\t\tcontinue\n\t\t} else if definitionInfo.configurationError != nil {\n\t\t\t// Configuration error.\n\t\t\taddConfigError(definitionInfo.configurationError, definition, nil)\n\t\t\tcontinue\n\t\t}\n\n\t\tauditAnnotationCollector := newAuditAnnotationCollector()\n\t\tfor _, bindingInfo := range definitionInfo.bindings {\n\t\t\t// If the key is inside dependentBindings, there is guaranteed to\n\t\t\t// be a bindingInfo for it\n\t\t\tbinding := bindingInfo.lastReconciledValue\n\t\t\tmatches, err := c.policyController.matcher.BindingMatches(a, o, binding)\n\t\t\tif err != nil {\n\t\t\t\t// Configuration error.\n\t\t\t\taddConfigError(err, definition, binding)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !matches {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar param runtime.Object\n\n\t\t\t// versionedAttributes will be set to non-nil inside of the loop, but\n\t\t\t// is scoped outside of the param loop so we only convert once. We defer\n\t\t\t// conversion so that it is only performed when we know a policy matches,\n\t\t\t// saving the cost of converting non-matching requests.\n\t\t\tvar versionedAttr *admission.VersionedAttributes\n\n\t\t\t// If definition has paramKind, paramRef is required in binding.\n\t\t\t// If definition has no paramKind, paramRef set in binding will be ignored.\n\t\t\tparamKind := definition.Spec.ParamKind\n\t\t\tparamRef := binding.Spec.ParamRef\n\t\t\tif paramKind != nil \u0026\u0026 paramRef != nil {\n\t\t\t\tparamController := definitionInfo.paramController\n\t\t\t\tif paramController == nil {\n\t\t\t\t\taddConfigError(fmt.Errorf(\"paramKind kind `%v` not known\",\n\t\t\t\t\t\tparamKind.String()), definition, binding)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// If the param informer for this admission policy has not yet\n\t\t\t\t// had time to perform an initial listing, don't attempt to use\n\t\t\t\t// it.\n\t\t\t\ttimeoutCtx, cancel := context.WithTimeout(c.policyController.context, 1*time.Second)\n\t\t\t\tdefer cancel()\n\n\t\t\t\tif !cache.WaitForCacheSync(timeoutCtx.Done(), paramController.HasSynced) {\n\t\t\t\t\taddConfigError(fmt.Errorf(\"paramKind kind `%v` not yet synced to use for admission\",\n\t\t\t\t\t\tparamKind.String()), definition, binding)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif len(paramRef.Namespace) == 0 {\n\t\t\t\t\tparam, err = paramController.Informer().Get(paramRef.Name)\n\t\t\t\t} else {\n\t\t\t\t\tparam, err = paramController.Informer().Namespaced(paramRef.Namespace).Get(paramRef.Name)\n\t\t\t\t}\n\n\t\t\t\tif err != nil {\n\t\t\t\t\t// Apply failure policy\n\t\t\t\t\taddConfigError(err, definition, binding)\n\n\t\t\t\t\tif k8serrors.IsInvalid(err) {\n\t\t\t\t\t\t// Param mis-configured\n\t\t\t\t\t\t// require to set paramRef.namespace for namespaced resource and unset paramRef.namespace for cluster scoped resource\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if k8serrors.IsNotFound(err) {\n\t\t\t\t\t\t// Param not yet available. User may need to wait a bit\n\t\t\t\t\t\t// before being able to use it for validation.\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\t// There was a bad internal error\n\t\t\t\t\tutilruntime.HandleError(err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif versionedAttr == nil {\n\t\t\t\tva, err := admission.NewVersionedAttributes(a, matchKind, o)\n\t\t\t\tif err != nil {\n\t\t\t\t\twrappedErr := fmt.Errorf(\"failed to convert object version: %w\", err)\n\t\t\t\t\taddConfigError(wrappedErr, definition, binding)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tversionedAttr = va\n\t\t\t}\n\n\t\t\tvalidationResult := bindingInfo.validator.Validate(ctx, versionedAttr, param, celconfig.RuntimeCELCostBudget)\n\t\t\tif err != nil {\n\t\t\t\t// runtime error. Apply failure policy\n\t\t\t\twrappedError := fmt.Errorf(\"failed to evaluate CEL expression: %w\", err)\n\t\t\t\taddConfigError(wrappedError, definition, binding)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor i, decision := range validationResult.Decisions {\n\t\t\t\tswitch decision.Action {\n\t\t\t\tcase ActionAdmit:\n\t\t\t\t\tif decision.Evaluation == EvalError {\n\t\t\t\t\t\tcelmetrics.Metrics.ObserveAdmissionWithError(ctx, decision.Elapsed, definition.Name, binding.Name, \"active\")\n\t\t\t\t\t}\n\t\t\t\tcase ActionDeny:\n\t\t\t\t\tfor _, action := range binding.Spec.ValidationActions {\n\t\t\t\t\t\tswitch action {\n\t\t\t\t\t\tcase v1alpha1.Deny:\n\t\t\t\t\t\t\tdeniedDecisions = append(deniedDecisions, policyDecisionWithMetadata{\n\t\t\t\t\t\t\t\tDefinition: definition,\n\t\t\t\t\t\t\t\tBinding: binding,\n\t\t\t\t\t\t\t\tPolicyDecision: decision,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\tcelmetrics.Metrics.ObserveRejection(ctx, decision.Elapsed, definition.Name, binding.Name, \"active\")\n\t\t\t\t\t\tcase v1alpha1.Audit:\n\t\t\t\t\t\t\tc.publishValidationFailureAnnotation(binding, i, decision, versionedAttr)\n\t\t\t\t\t\t\tcelmetrics.Metrics.ObserveAudit(ctx, decision.Elapsed, definition.Name, binding.Name, \"active\")\n\t\t\t\t\t\tcase v1alpha1.Warn:\n\t\t\t\t\t\t\twarning.AddWarning(ctx, \"\", fmt.Sprintf(\"Validation failed for ValidatingAdmissionPolicy '%s' with binding '%s': %s\", definition.Name, binding.Name, decision.Message))\n\t\t\t\t\t\t\tcelmetrics.Metrics.ObserveWarn(ctx, decision.Elapsed, definition.Name, binding.Name, \"active\")\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\treturn fmt.Errorf(\"unrecognized evaluation decision '%s' for ValidatingAdmissionPolicyBinding '%s' with ValidatingAdmissionPolicy '%s'\",\n\t\t\t\t\t\tdecision.Action, binding.Name, definition.Name)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor _, auditAnnotation := range validationResult.AuditAnnotations {\n\t\t\t\tswitch auditAnnotation.Action {\n\t\t\t\tcase AuditAnnotationActionPublish:\n\t\t\t\t\tvalue := auditAnnotation.Value\n\t\t\t\t\tif len(auditAnnotation.Value) \u003e maxAuditAnnotationValueLength {\n\t\t\t\t\t\tvalue = value[:maxAuditAnnotationValueLength]\n\t\t\t\t\t}\n\t\t\t\t\tauditAnnotationCollector.add(auditAnnotation.Key, value)\n\t\t\t\tcase AuditAnnotationActionError:\n\t\t\t\t\t// When failurePolicy=fail, audit annotation errors result in deny\n\t\t\t\t\tdeniedDecisions = append(deniedDecisions, policyDecisionWithMetadata{\n\t\t\t\t\t\tDefinition: definition,\n\t\t\t\t\t\tBinding: binding,\n\t\t\t\t\t\tPolicyDecision: PolicyDecision{\n\t\t\t\t\t\t\tAction: ActionDeny,\n\t\t\t\t\t\t\tEvaluation: EvalError,\n\t\t\t\t\t\t\tMessage: auditAnnotation.Error,\n\t\t\t\t\t\t\tElapsed: auditAnnotation.Elapsed,\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t\tcelmetrics.Metrics.ObserveRejection(ctx, auditAnnotation.Elapsed, definition.Name, binding.Name, \"active\")\n\t\t\t\tcase AuditAnnotationActionExclude: // skip it\n\t\t\t\tdefault:\n\t\t\t\t\treturn fmt.Errorf(\"unsupported AuditAnnotation Action: %s\", auditAnnotation.Action)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tauditAnnotationCollector.publish(definition.Name, a)\n\t}\n\n\tif len(deniedDecisions) \u003e 0 {\n\t\t// TODO: refactor admission.NewForbidden so the name extraction is reusable but the code/reason is customizable\n\t\tvar message string\n\t\tdeniedDecision := deniedDecisions[0]\n\t\tif deniedDecision.Binding != nil {\n\t\t\tmessage = fmt.Sprintf(\"ValidatingAdmissionPolicy '%s' with binding '%s' denied request: %s\", deniedDecision.Definition.Name, deniedDecision.Binding.Name, deniedDecision.Message)\n\t\t} else {\n\t\t\tmessage = fmt.Sprintf(\"ValidatingAdmissionPolicy '%s' denied request: %s\", deniedDecision.Definition.Name, deniedDecision.Message)\n\t\t}\n\t\terr := admission.NewForbidden(a, errors.New(message)).(*k8serrors.StatusError)\n\t\treason := deniedDecision.Reason\n\t\tif len(reason) == 0 {\n\t\t\treason = metav1.StatusReasonInvalid\n\t\t}\n\t\terr.ErrStatus.Reason = reason\n\t\terr.ErrStatus.Code = reasonToCode(reason)\n\t\terr.ErrStatus.Details.Causes = append(err.ErrStatus.Details.Causes, metav1.StatusCause{Message: message})\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":185,"to":426}} {"id":100016597,"name":"publishValidationFailureAnnotation","signature":"func (c *celAdmissionController) publishValidationFailureAnnotation(binding *v1alpha1.ValidatingAdmissionPolicyBinding, expressionIndex int, decision PolicyDecision, attributes admission.Attributes)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/controller.go","code":"func (c *celAdmissionController) publishValidationFailureAnnotation(binding *v1alpha1.ValidatingAdmissionPolicyBinding, expressionIndex int, decision PolicyDecision, attributes admission.Attributes) {\n\tkey := \"validation.policy.admission.k8s.io/validation_failure\"\n\t// Marshal to a list of failures since, in the future, we may need to support multiple failures\n\tvalueJson, err := utiljson.Marshal([]validationFailureValue{{\n\t\tExpressionIndex: expressionIndex,\n\t\tMessage: decision.Message,\n\t\tValidationActions: binding.Spec.ValidationActions,\n\t\tBinding: binding.Name,\n\t\tPolicy: binding.Spec.PolicyName,\n\t}})\n\tif err != nil {\n\t\tklog.Warningf(\"Failed to set admission audit annotation %s for ValidatingAdmissionPolicy %s and ValidatingAdmissionPolicyBinding %s: %v\", key, binding.Spec.PolicyName, binding.Name, err)\n\t}\n\tvalue := string(valueJson)\n\tif err := attributes.AddAnnotation(key, value); err != nil {\n\t\tklog.Warningf(\"Failed to set admission audit annotation %s to %s for ValidatingAdmissionPolicy %s and ValidatingAdmissionPolicyBinding %s: %v\", key, value, binding.Spec.PolicyName, binding.Name, err)\n\t}\n}","line":{"from":428,"to":445}} {"id":100016598,"name":"HasSynced","signature":"func (c *celAdmissionController) HasSynced() bool","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/controller.go","code":"func (c *celAdmissionController) HasSynced() bool {\n\treturn c.policyController.HasSynced() \u0026\u0026 c.definitions.Load() != nil\n}","line":{"from":447,"to":449}} {"id":100016599,"name":"ValidateInitialization","signature":"func (c *celAdmissionController) ValidateInitialization() error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/controller.go","code":"func (c *celAdmissionController) ValidateInitialization() error {\n\treturn c.policyController.matcher.ValidateInitialization()\n}","line":{"from":451,"to":453}} {"id":100016600,"name":"refreshPolicies","signature":"func (c *celAdmissionController) refreshPolicies()","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/controller.go","code":"func (c *celAdmissionController) refreshPolicies() {\n\tc.definitions.Store(c.policyController.latestPolicyData())\n}","line":{"from":455,"to":457}} {"id":100016601,"name":"newAuditAnnotationCollector","signature":"func newAuditAnnotationCollector() auditAnnotationCollector","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/controller.go","code":"func newAuditAnnotationCollector() auditAnnotationCollector {\n\treturn auditAnnotationCollector{annotations: map[string][]string{}}\n}","line":{"from":473,"to":475}} {"id":100016602,"name":"add","signature":"func (a auditAnnotationCollector) add(key, value string)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/controller.go","code":"func (a auditAnnotationCollector) add(key, value string) {\n\t// If multiple bindings produces the exact same key and value for an audit annotation,\n\t// ignore the duplicates.\n\tfor _, v := range a.annotations[key] {\n\t\tif v == value {\n\t\t\treturn\n\t\t}\n\t}\n\ta.annotations[key] = append(a.annotations[key], value)\n}","line":{"from":477,"to":486}} {"id":100016603,"name":"publish","signature":"func (a auditAnnotationCollector) publish(policyName string, attributes admission.Attributes)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/controller.go","code":"func (a auditAnnotationCollector) publish(policyName string, attributes admission.Attributes) {\n\tfor key, bindingAnnotations := range a.annotations {\n\t\tvar value string\n\t\tif len(bindingAnnotations) == 1 {\n\t\t\tvalue = bindingAnnotations[0]\n\t\t} else {\n\t\t\t// Multiple distinct values can exist when binding params are used in the valueExpression of an auditAnnotation.\n\t\t\t// When this happens, the values are concatenated into a comma-separated list.\n\t\t\tvalue = strings.Join(bindingAnnotations, \", \")\n\t\t}\n\t\tif err := attributes.AddAnnotation(policyName+\"/\"+key, value); err != nil {\n\t\t\tklog.Warningf(\"Failed to set admission audit annotation %s to %s for ValidatingAdmissionPolicy %s: %v\", key, value, policyName, err)\n\t\t}\n\t}\n}","line":{"from":488,"to":502}} {"id":100016604,"name":"newPolicyController","signature":"func newPolicyController(","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/controller_reconcile.go","code":"func newPolicyController(\n\trestMapper meta.RESTMapper,\n\tclient kubernetes.Interface,\n\tdynamicClient dynamic.Interface,\n\ttypeChecker *TypeChecker,\n\tfilterCompiler cel.FilterCompiler,\n\tmatcher Matcher,\n\tpoliciesInformer generic.Informer[*v1alpha1.ValidatingAdmissionPolicy],\n\tbindingsInformer generic.Informer[*v1alpha1.ValidatingAdmissionPolicyBinding],\n\tauthz authorizer.Authorizer,\n) *policyController {\n\tres := \u0026policyController{}\n\t*res = policyController{\n\t\tfilterCompiler: filterCompiler,\n\t\ttypeChecker: typeChecker,\n\t\tdefinitionInfo: make(map[namespacedName]*definitionInfo),\n\t\tbindingInfos: make(map[namespacedName]*bindingInfo),\n\t\tparamsCRDControllers: make(map[v1alpha1.ParamKind]*paramInfo),\n\t\tdefinitionsToBindings: make(map[namespacedName]sets.Set[namespacedName]),\n\t\tmatcher: matcher,\n\t\tnewValidator: NewValidator,\n\t\tpolicyDefinitionsController: generic.NewController(\n\t\t\tpoliciesInformer,\n\t\t\tres.reconcilePolicyDefinition,\n\t\t\tgeneric.ControllerOptions{\n\t\t\t\tWorkers: 1,\n\t\t\t\tName: \"cel-policy-definitions\",\n\t\t\t},\n\t\t),\n\t\tpolicyBindingController: generic.NewController(\n\t\t\tbindingsInformer,\n\t\t\tres.reconcilePolicyBinding,\n\t\t\tgeneric.ControllerOptions{\n\t\t\t\tWorkers: 1,\n\t\t\t\tName: \"cel-policy-bindings\",\n\t\t\t},\n\t\t),\n\t\trestMapper: restMapper,\n\t\tdynamicClient: dynamicClient,\n\t\tclient: client,\n\t\tauthz: authz,\n\t}\n\treturn res\n}","line":{"from":105,"to":148}} {"id":100016605,"name":"Run","signature":"func (c *policyController) Run(ctx context.Context)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/controller_reconcile.go","code":"func (c *policyController) Run(ctx context.Context) {\n\t// Only support being run once\n\tc.once.Do(func() {\n\t\tc.context = ctx\n\n\t\twg := sync.WaitGroup{}\n\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tc.policyDefinitionsController.Run(ctx)\n\t\t}()\n\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tc.policyBindingController.Run(ctx)\n\t\t}()\n\n\t\t\u003c-ctx.Done()\n\t\twg.Wait()\n\t})\n}","line":{"from":150,"to":172}} {"id":100016606,"name":"HasSynced","signature":"func (c *policyController) HasSynced() bool","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/controller_reconcile.go","code":"func (c *policyController) HasSynced() bool {\n\treturn c.policyDefinitionsController.HasSynced() \u0026\u0026 c.policyBindingController.HasSynced()\n}","line":{"from":174,"to":176}} {"id":100016607,"name":"reconcilePolicyDefinition","signature":"func (c *policyController) reconcilePolicyDefinition(namespace, name string, definition *v1alpha1.ValidatingAdmissionPolicy) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/controller_reconcile.go","code":"func (c *policyController) reconcilePolicyDefinition(namespace, name string, definition *v1alpha1.ValidatingAdmissionPolicy) error {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\terr := c.reconcilePolicyDefinitionSpec(namespace, name, definition)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif c.typeChecker != nil {\n\t\terr = c.reconcilePolicyStatus(namespace, name, definition)\n\t}\n\treturn err\n}","line":{"from":178,"to":189}} {"id":100016608,"name":"reconcilePolicyDefinitionSpec","signature":"func (c *policyController) reconcilePolicyDefinitionSpec(namespace, name string, definition *v1alpha1.ValidatingAdmissionPolicy) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/controller_reconcile.go","code":"func (c *policyController) reconcilePolicyDefinitionSpec(namespace, name string, definition *v1alpha1.ValidatingAdmissionPolicy) error {\n\tc.cachedPolicies = nil // invalidate cachedPolicies\n\n\t// Namespace for policydefinition is empty.\n\tnn := getNamespaceName(namespace, name)\n\tinfo, ok := c.definitionInfo[nn]\n\tif !ok {\n\t\tinfo = \u0026definitionInfo{}\n\t\tc.definitionInfo[nn] = info\n\t\t// TODO(DangerOnTheRanger): add support for \"warn\" being a valid enforcementAction\n\t\tcelmetrics.Metrics.ObserveDefinition(context.TODO(), \"active\", \"deny\")\n\t}\n\n\t// Skip reconcile if the spec of the definition is unchanged\n\tif info.lastReconciledValue != nil \u0026\u0026 definition != nil \u0026\u0026\n\t\tapiequality.Semantic.DeepEqual(info.lastReconciledValue.Spec, definition.Spec) {\n\t\treturn nil\n\t}\n\n\tvar paramSource *v1alpha1.ParamKind\n\tif definition != nil {\n\t\tparamSource = definition.Spec.ParamKind\n\t}\n\n\t// If param source has changed, remove definition as dependent of old params\n\t// If there are no more dependents of old param, stop and clean up controller\n\tif info.lastReconciledValue != nil \u0026\u0026 info.lastReconciledValue.Spec.ParamKind != nil {\n\t\toldParamSource := *info.lastReconciledValue.Spec.ParamKind\n\n\t\t// If we are:\n\t\t//\t- switching from having a param to not having a param (includes deletion)\n\t\t//\t- or from having a param to a different one\n\t\t// we remove dependency on the controller.\n\t\tif paramSource == nil || *paramSource != oldParamSource {\n\t\t\tif oldParamInfo, ok := c.paramsCRDControllers[oldParamSource]; ok {\n\t\t\t\toldParamInfo.dependentDefinitions.Delete(nn)\n\t\t\t\tif len(oldParamInfo.dependentDefinitions) == 0 {\n\t\t\t\t\toldParamInfo.stop()\n\t\t\t\t\tdelete(c.paramsCRDControllers, oldParamSource)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Reset all previously compiled evaluators in case something relevant in\n\t// definition has changed.\n\tfor key := range c.definitionsToBindings[nn] {\n\t\tbindingInfo := c.bindingInfos[key]\n\t\tbindingInfo.validator = nil\n\t\tc.bindingInfos[key] = bindingInfo\n\t}\n\n\tif definition == nil {\n\t\tdelete(c.definitionInfo, nn)\n\t\treturn nil\n\t}\n\n\t// Update definition info\n\tinfo.lastReconciledValue = definition\n\tinfo.configurationError = nil\n\n\tif paramSource == nil {\n\t\t// Skip setting up controller for empty param type\n\t\treturn nil\n\t}\n\n\t// find GVR for params\n\t// Parse param source into a GVK\n\n\tparamSourceGV, err := schema.ParseGroupVersion(paramSource.APIVersion)\n\tif err != nil {\n\t\t// Failed to resolve. Return error so we retry again (rate limited)\n\t\t// Save a record of this definition with an evaluator that unconditionally\n\t\tinfo.configurationError = fmt.Errorf(\"failed to parse apiVersion of paramKind '%v' with error: %w\", paramSource.String(), err)\n\n\t\t// Return nil, since this error cannot be resolved by waiting more time\n\t\treturn nil\n\t}\n\n\tparamsGVR, err := c.restMapper.RESTMapping(schema.GroupKind{\n\t\tGroup: paramSourceGV.Group,\n\t\tKind: paramSource.Kind,\n\t}, paramSourceGV.Version)\n\n\tif err != nil {\n\t\t// Failed to resolve. Return error so we retry again (rate limited)\n\t\t// Save a record of this definition with an evaluator that unconditionally\n\t\t//\n\t\tinfo.configurationError = fmt.Errorf(\"failed to find resource referenced by paramKind: '%v'\", paramSourceGV.WithKind(paramSource.Kind))\n\t\treturn info.configurationError\n\t}\n\n\tif info, ok := c.paramsCRDControllers[*paramSource]; ok {\n\t\t// If a param controller is already active for this paramsource, make\n\t\t// sure it is tracking this policy's dependency upon it\n\t\tinfo.dependentDefinitions.Insert(nn)\n\n\t} else {\n\t\tinstanceContext, instanceCancel := context.WithCancel(c.context)\n\n\t\tvar informer cache.SharedIndexInformer\n\n\t\t// Informer Factory is optional\n\t\tif c.client != nil {\n\t\t\t// Create temporary informer factory\n\t\t\t// Cannot use the k8s shared informer factory for dynamic params informer.\n\t\t\t// Would leak unnecessary informers when we are done since we would have to\n\t\t\t// call informerFactory.Start() with a longer-lived stopCh than necessary.\n\t\t\t// SharedInformerFactory does not support temporary usage.\n\t\t\tdynamicFactory := informers.NewSharedInformerFactory(c.client, 10*time.Minute)\n\n\t\t\t// Look for a typed informer. If it does not exist\n\t\t\tgenericInformer, err := dynamicFactory.ForResource(paramsGVR.Resource)\n\n\t\t\t// Ignore error. We fallback to dynamic informer if there is no\n\t\t\t// typed informer\n\t\t\tif err != nil {\n\t\t\t\tinformer = nil\n\t\t\t} else {\n\t\t\t\tinformer = genericInformer.Informer()\n\n\t\t\t\t// Set transformer on the informer to workaround inconsistency\n\t\t\t\t// where typed objects have TypeMeta wiped out but dynamic\n\t\t\t\t// objects keep kind/apiVersion fields\n\t\t\t\tinformer.SetTransform(func(i interface{}) (interface{}, error) {\n\t\t\t\t\t// Ensure param is populated with its GVK for consistency\n\t\t\t\t\t// (CRD dynamic informer always returns objects with kind/apiversion,\n\t\t\t\t\t// but native types do not include populated TypeMeta.\n\t\t\t\t\tif param := i.(runtime.Object); param != nil {\n\t\t\t\t\t\tif param.GetObjectKind().GroupVersionKind().Empty() {\n\t\t\t\t\t\t\t// https://github.com/kubernetes/client-go/issues/413#issue-324586398\n\t\t\t\t\t\t\tgvks, _, _ := k8sscheme.Scheme.ObjectKinds(param)\n\t\t\t\t\t\t\tfor _, gvk := range gvks {\n\t\t\t\t\t\t\t\tif len(gvk.Kind) == 0 {\n\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif len(gvk.Version) == 0 || gvk.Version == runtime.APIVersionInternal {\n\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tparam.GetObjectKind().SetGroupVersionKind(gvk)\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn i, nil\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\tif informer == nil {\n\t\t\t// Dynamic JSON informer fallback.\n\t\t\t// Cannot use shared dynamic informer since it would be impossible\n\t\t\t// to clean CRD informers properly with multiple dependents\n\t\t\t// (cannot start ahead of time, and cannot track dependencies via stopCh)\n\t\t\tinformer = dynamicinformer.NewFilteredDynamicInformer(\n\t\t\t\tc.dynamicClient,\n\t\t\t\tparamsGVR.Resource,\n\t\t\t\tcorev1.NamespaceAll,\n\t\t\t\t// Use same interval as is used for k8s typed sharedInformerFactory\n\t\t\t\t// https://github.com/kubernetes/kubernetes/blob/7e0923899fed622efbc8679cca6b000d43633e38/cmd/kube-apiserver/app/server.go#L430\n\t\t\t\t10*time.Minute,\n\t\t\t\tcache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},\n\t\t\t\tnil,\n\t\t\t).Informer()\n\t\t}\n\n\t\tcontroller := generic.NewController(\n\t\t\tgeneric.NewInformer[runtime.Object](informer),\n\t\t\tc.reconcileParams,\n\t\t\tgeneric.ControllerOptions{\n\t\t\t\tWorkers: 1,\n\t\t\t\tName: paramSource.String() + \"-controller\",\n\t\t\t},\n\t\t)\n\n\t\tc.paramsCRDControllers[*paramSource] = \u0026paramInfo{\n\t\t\tcontroller: controller,\n\t\t\tstop: instanceCancel,\n\t\t\tdependentDefinitions: sets.New(nn),\n\t\t}\n\n\t\tgo controller.Run(instanceContext)\n\t\tgo informer.Run(instanceContext.Done())\n\t}\n\n\treturn nil\n}","line":{"from":191,"to":378}} {"id":100016609,"name":"reconcilePolicyBinding","signature":"func (c *policyController) reconcilePolicyBinding(namespace, name string, binding *v1alpha1.ValidatingAdmissionPolicyBinding) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/controller_reconcile.go","code":"func (c *policyController) reconcilePolicyBinding(namespace, name string, binding *v1alpha1.ValidatingAdmissionPolicyBinding) error {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\n\tc.cachedPolicies = nil // invalidate cachedPolicies\n\n\t// Namespace for PolicyBinding is empty. In the future a namespaced binding\n\t// may be added\n\t// https://github.com/kubernetes/enhancements/blob/bf5c3c81ea2081d60c1dc7c832faa98479e06209/keps/sig-api-machinery/3488-cel-admission-control/README.md?plain=1#L1042\n\tnn := getNamespaceName(namespace, name)\n\tinfo, ok := c.bindingInfos[nn]\n\tif !ok {\n\t\tinfo = \u0026bindingInfo{}\n\t\tc.bindingInfos[nn] = info\n\t}\n\n\t// Skip if the spec of the binding is unchanged.\n\tif info.lastReconciledValue != nil \u0026\u0026 binding != nil \u0026\u0026\n\t\tapiequality.Semantic.DeepEqual(info.lastReconciledValue.Spec, binding.Spec) {\n\t\treturn nil\n\t}\n\n\tvar oldNamespacedDefinitionName namespacedName\n\tif info.lastReconciledValue != nil {\n\t\t// All validating policies are cluster-scoped so have empty namespace\n\t\toldNamespacedDefinitionName = getNamespaceName(\"\", info.lastReconciledValue.Spec.PolicyName)\n\t}\n\n\tvar namespacedDefinitionName namespacedName\n\tif binding != nil {\n\t\t// All validating policies are cluster-scoped so have empty namespace\n\t\tnamespacedDefinitionName = getNamespaceName(\"\", binding.Spec.PolicyName)\n\t}\n\n\t// Remove record of binding from old definition if the referred policy\n\t// has changed\n\tif oldNamespacedDefinitionName != namespacedDefinitionName {\n\t\tif dependentBindings, ok := c.definitionsToBindings[oldNamespacedDefinitionName]; ok {\n\t\t\tdependentBindings.Delete(nn)\n\n\t\t\t// if there are no more dependent bindings, remove knowledge of the\n\t\t\t// definition altogether\n\t\t\tif len(dependentBindings) == 0 {\n\t\t\t\tdelete(c.definitionsToBindings, oldNamespacedDefinitionName)\n\t\t\t}\n\t\t}\n\t}\n\n\tif binding == nil {\n\t\tdelete(c.bindingInfos, nn)\n\t\treturn nil\n\t}\n\n\t// Add record of binding to new definition\n\tif dependentBindings, ok := c.definitionsToBindings[namespacedDefinitionName]; ok {\n\t\tdependentBindings.Insert(nn)\n\t} else {\n\t\tc.definitionsToBindings[namespacedDefinitionName] = sets.New(nn)\n\t}\n\n\t// Remove compiled template for old binding\n\tinfo.validator = nil\n\tinfo.lastReconciledValue = binding\n\treturn nil\n}","line":{"from":380,"to":444}} {"id":100016610,"name":"reconcilePolicyStatus","signature":"func (c *policyController) reconcilePolicyStatus(namespace, name string, definition *v1alpha1.ValidatingAdmissionPolicy) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/controller_reconcile.go","code":"func (c *policyController) reconcilePolicyStatus(namespace, name string, definition *v1alpha1.ValidatingAdmissionPolicy) error {\n\tif definition != nil \u0026\u0026 definition.Status.ObservedGeneration \u003c definition.Generation {\n\t\tst := c.calculatePolicyStatus(definition)\n\t\tnewDefinition := definition.DeepCopy()\n\t\tnewDefinition.Status = *st\n\t\t_, err := c.client.AdmissionregistrationV1alpha1().ValidatingAdmissionPolicies().UpdateStatus(c.context, newDefinition, metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\t// ignore error when the controller is not able to\n\t\t\t// mutate the definition, and to avoid infinite requeue.\n\t\t\tutilruntime.HandleError(err)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":446,"to":459}} {"id":100016611,"name":"calculatePolicyStatus","signature":"func (c *policyController) calculatePolicyStatus(definition *v1alpha1.ValidatingAdmissionPolicy) *v1alpha1.ValidatingAdmissionPolicyStatus","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/controller_reconcile.go","code":"func (c *policyController) calculatePolicyStatus(definition *v1alpha1.ValidatingAdmissionPolicy) *v1alpha1.ValidatingAdmissionPolicyStatus {\n\texpressionWarnings := c.typeChecker.Check(definition)\n\t// modifying a deepcopy of the original status, preserving unrelated existing data\n\tstatus := definition.Status.DeepCopy()\n\tstatus.ObservedGeneration = definition.Generation\n\tstatus.TypeChecking = \u0026v1alpha1.TypeChecking{ExpressionWarnings: expressionWarnings}\n\treturn status\n}","line":{"from":461,"to":468}} {"id":100016612,"name":"reconcileParams","signature":"func (c *policyController) reconcileParams(namespace, name string, params runtime.Object) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/controller_reconcile.go","code":"func (c *policyController) reconcileParams(namespace, name string, params runtime.Object) error {\n\t// Do nothing.\n\t// When we add informational type checking we will need to compile in the\n\t// reconcile loops instead of lazily so we can add compiler errors / type\n\t// checker errors to the status of the resources.\n\treturn nil\n}","line":{"from":470,"to":476}} {"id":100016613,"name":"latestPolicyData","signature":"func (c *policyController) latestPolicyData() []policyData","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/controller_reconcile.go","code":"// Fetches the latest set of policy data or recalculates it if it has changed\n// since it was last fetched\nfunc (c *policyController) latestPolicyData() []policyData {\n\texisting := func() []policyData {\n\t\tc.mutex.RLock()\n\t\tdefer c.mutex.RUnlock()\n\n\t\treturn c.cachedPolicies\n\t}()\n\n\tif existing != nil {\n\t\treturn existing\n\t}\n\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\n\tvar res []policyData\n\tfor definitionNN, definitionInfo := range c.definitionInfo {\n\t\tvar bindingInfos []bindingInfo\n\t\tfor bindingNN := range c.definitionsToBindings[definitionNN] {\n\t\t\tbindingInfo := c.bindingInfos[bindingNN]\n\t\t\tif bindingInfo.validator == nil \u0026\u0026 definitionInfo.configurationError == nil {\n\t\t\t\thasParam := false\n\t\t\t\tif definitionInfo.lastReconciledValue.Spec.ParamKind != nil {\n\t\t\t\t\thasParam = true\n\t\t\t\t}\n\t\t\t\toptionalVars := cel.OptionalVariableDeclarations{HasParams: hasParam, HasAuthorizer: true}\n\t\t\t\texpressionOptionalVars := cel.OptionalVariableDeclarations{HasParams: hasParam, HasAuthorizer: false}\n\t\t\t\tfailurePolicy := convertv1alpha1FailurePolicyTypeTov1FailurePolicyType(definitionInfo.lastReconciledValue.Spec.FailurePolicy)\n\t\t\t\tvar matcher matchconditions.Matcher = nil\n\t\t\t\tmatchConditions := definitionInfo.lastReconciledValue.Spec.MatchConditions\n\t\t\t\tif len(matchConditions) \u003e 0 {\n\t\t\t\t\tmatchExpressionAccessors := make([]cel.ExpressionAccessor, len(matchConditions))\n\t\t\t\t\tfor i := range matchConditions {\n\t\t\t\t\t\tmatchExpressionAccessors[i] = (*matchconditions.MatchCondition)(\u0026matchConditions[i])\n\t\t\t\t\t}\n\t\t\t\t\tmatcher = matchconditions.NewMatcher(c.filterCompiler.Compile(matchExpressionAccessors, optionalVars, celconfig.PerCallLimit), c.authz, failurePolicy, \"validatingadmissionpolicy\", definitionInfo.lastReconciledValue.Name)\n\t\t\t\t}\n\t\t\t\tbindingInfo.validator = c.newValidator(\n\t\t\t\t\tc.filterCompiler.Compile(convertv1alpha1Validations(definitionInfo.lastReconciledValue.Spec.Validations), optionalVars, celconfig.PerCallLimit),\n\t\t\t\t\tmatcher,\n\t\t\t\t\tc.filterCompiler.Compile(convertv1alpha1AuditAnnotations(definitionInfo.lastReconciledValue.Spec.AuditAnnotations), optionalVars, celconfig.PerCallLimit),\n\t\t\t\t\tc.filterCompiler.Compile(convertV1Alpha1MessageExpressions(definitionInfo.lastReconciledValue.Spec.Validations), expressionOptionalVars, celconfig.PerCallLimit),\n\t\t\t\t\tfailurePolicy,\n\t\t\t\t\tc.authz,\n\t\t\t\t)\n\t\t\t}\n\t\t\tbindingInfos = append(bindingInfos, *bindingInfo)\n\t\t}\n\n\t\tvar paramController generic.Controller[runtime.Object]\n\t\tif paramKind := definitionInfo.lastReconciledValue.Spec.ParamKind; paramKind != nil {\n\t\t\tif info, ok := c.paramsCRDControllers[*paramKind]; ok {\n\t\t\t\tparamController = info.controller\n\t\t\t}\n\t\t}\n\n\t\tres = append(res, policyData{\n\t\t\tdefinitionInfo: *definitionInfo,\n\t\t\tparamController: paramController,\n\t\t\tbindings: bindingInfos,\n\t\t})\n\t}\n\n\tc.cachedPolicies = res\n\treturn res\n}","line":{"from":478,"to":545}} {"id":100016614,"name":"convertv1alpha1FailurePolicyTypeTov1FailurePolicyType","signature":"func convertv1alpha1FailurePolicyTypeTov1FailurePolicyType(policyType *v1alpha1.FailurePolicyType) *v1.FailurePolicyType","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/controller_reconcile.go","code":"func convertv1alpha1FailurePolicyTypeTov1FailurePolicyType(policyType *v1alpha1.FailurePolicyType) *v1.FailurePolicyType {\n\tif policyType == nil {\n\t\treturn nil\n\t}\n\n\tvar v1FailPolicy v1.FailurePolicyType\n\tif *policyType == v1alpha1.Fail {\n\t\tv1FailPolicy = v1.Fail\n\t} else if *policyType == v1alpha1.Ignore {\n\t\tv1FailPolicy = v1.Ignore\n\t}\n\treturn \u0026v1FailPolicy\n}","line":{"from":547,"to":559}} {"id":100016615,"name":"convertv1alpha1Validations","signature":"func convertv1alpha1Validations(inputValidations []v1alpha1.Validation) []cel.ExpressionAccessor","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/controller_reconcile.go","code":"func convertv1alpha1Validations(inputValidations []v1alpha1.Validation) []cel.ExpressionAccessor {\n\tcelExpressionAccessor := make([]cel.ExpressionAccessor, len(inputValidations))\n\tfor i, validation := range inputValidations {\n\t\tvalidation := ValidationCondition{\n\t\t\tExpression: validation.Expression,\n\t\t\tMessage: validation.Message,\n\t\t\tReason: validation.Reason,\n\t\t}\n\t\tcelExpressionAccessor[i] = \u0026validation\n\t}\n\treturn celExpressionAccessor\n}","line":{"from":561,"to":572}} {"id":100016616,"name":"convertV1Alpha1MessageExpressions","signature":"func convertV1Alpha1MessageExpressions(inputValidations []v1alpha1.Validation) []cel.ExpressionAccessor","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/controller_reconcile.go","code":"func convertV1Alpha1MessageExpressions(inputValidations []v1alpha1.Validation) []cel.ExpressionAccessor {\n\tcelExpressionAccessor := make([]cel.ExpressionAccessor, len(inputValidations))\n\tfor i, validation := range inputValidations {\n\t\tif validation.MessageExpression != \"\" {\n\t\t\tcondition := MessageExpressionCondition{\n\t\t\t\tMessageExpression: validation.MessageExpression,\n\t\t\t}\n\t\t\tcelExpressionAccessor[i] = \u0026condition\n\t\t}\n\t}\n\treturn celExpressionAccessor\n}","line":{"from":574,"to":585}} {"id":100016617,"name":"convertv1alpha1AuditAnnotations","signature":"func convertv1alpha1AuditAnnotations(inputValidations []v1alpha1.AuditAnnotation) []cel.ExpressionAccessor","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/controller_reconcile.go","code":"func convertv1alpha1AuditAnnotations(inputValidations []v1alpha1.AuditAnnotation) []cel.ExpressionAccessor {\n\tcelExpressionAccessor := make([]cel.ExpressionAccessor, len(inputValidations))\n\tfor i, validation := range inputValidations {\n\t\tvalidation := AuditAnnotationCondition{\n\t\t\tKey: validation.Key,\n\t\t\tValueExpression: validation.ValueExpression,\n\t\t}\n\t\tcelExpressionAccessor[i] = \u0026validation\n\t}\n\treturn celExpressionAccessor\n}","line":{"from":587,"to":597}} {"id":100016618,"name":"getNamespaceName","signature":"func getNamespaceName(namespace, name string) namespacedName","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/controller_reconcile.go","code":"func getNamespaceName(namespace, name string) namespacedName {\n\treturn namespacedName{\n\t\tnamespace: namespace,\n\t\tname: name,\n\t}\n}","line":{"from":599,"to":604}} {"id":100016619,"name":"GetExpression","signature":"func (v *ValidationCondition) GetExpression() string","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/interface.go","code":"func (v *ValidationCondition) GetExpression() string {\n\treturn v.Expression\n}","line":{"from":41,"to":43}} {"id":100016620,"name":"ReturnTypes","signature":"func (v *ValidationCondition) ReturnTypes() []*celgo.Type","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/interface.go","code":"func (v *ValidationCondition) ReturnTypes() []*celgo.Type {\n\treturn []*celgo.Type{celgo.BoolType}\n}","line":{"from":45,"to":47}} {"id":100016621,"name":"GetExpression","signature":"func (v *AuditAnnotationCondition) GetExpression() string","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/interface.go","code":"func (v *AuditAnnotationCondition) GetExpression() string {\n\treturn v.ValueExpression\n}","line":{"from":55,"to":57}} {"id":100016622,"name":"ReturnTypes","signature":"func (v *AuditAnnotationCondition) ReturnTypes() []*celgo.Type","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/interface.go","code":"func (v *AuditAnnotationCondition) ReturnTypes() []*celgo.Type {\n\treturn []*celgo.Type{celgo.StringType, celgo.NullType}\n}","line":{"from":59,"to":61}} {"id":100016623,"name":"Informer","signature":"func (c *controller[T]) Informer() Informer[T]","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/internal/generic/controller.go","code":"func (c *controller[T]) Informer() Informer[T] {\n\treturn c.informer\n}","line":{"from":62,"to":64}} {"id":100016624,"name":"NewController","signature":"func NewController[T runtime.Object](","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/internal/generic/controller.go","code":"func NewController[T runtime.Object](\n\tinformer Informer[T],\n\treconciler func(namepace, name string, newObj T) error,\n\toptions ControllerOptions,\n) Controller[T] {\n\tif options.Workers == 0 {\n\t\toptions.Workers = 2\n\t}\n\n\tif len(options.Name) == 0 {\n\t\toptions.Name = fmt.Sprintf(\"%T-controller\", *new(T))\n\t}\n\n\tc := \u0026controller[T]{\n\t\toptions: options,\n\t\tinformer: informer,\n\t\treconciler: reconciler,\n\t\tqueue: nil,\n\t}\n\tc.hasProcessed.UpstreamHasSynced = func() bool {\n\t\tf := c.notificationsDelivered.Load()\n\t\tif f == nil {\n\t\t\treturn false\n\t\t}\n\t\treturn f.(func() bool)()\n\t}\n\treturn c\n}","line":{"from":66,"to":93}} {"id":100016625,"name":"Run","signature":"func (c *controller[T]) Run(ctx context.Context) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/internal/generic/controller.go","code":"// Runs the controller and returns an error explaining why running was stopped.\n// Reconciliation ends as soon as the context completes. If there are events\n// waiting to be processed at that itme, they will be dropped.\nfunc (c *controller[T]) Run(ctx context.Context) error {\n\tklog.Infof(\"starting %s\", c.options.Name)\n\tdefer klog.Infof(\"stopping %s\", c.options.Name)\n\n\tc.queue = workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), c.options.Name)\n\n\t// Forcefully shutdown workqueue. Drop any enqueued items.\n\t// Important to do this in a `defer` at the start of `Run`.\n\t// Otherwise, if there are any early returns without calling this, we\n\t// would never shut down the workqueue\n\tdefer c.queue.ShutDown()\n\n\tenqueue := func(obj interface{}, isInInitialList bool) {\n\t\tvar key string\n\t\tvar err error\n\t\tif key, err = cache.DeletionHandlingMetaNamespaceKeyFunc(obj); err != nil {\n\t\t\tutilruntime.HandleError(err)\n\t\t\treturn\n\t\t}\n\t\tif isInInitialList {\n\t\t\tc.hasProcessed.Start(key)\n\t\t}\n\n\t\tc.queue.Add(key)\n\t}\n\n\tregistration, err := c.informer.AddEventHandler(cache.ResourceEventHandlerDetailedFuncs{\n\t\tAddFunc: enqueue,\n\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\toldMeta, err1 := meta.Accessor(oldObj)\n\t\t\tnewMeta, err2 := meta.Accessor(newObj)\n\n\t\t\tif err1 != nil || err2 != nil {\n\t\t\t\tif err1 != nil {\n\t\t\t\t\tutilruntime.HandleError(err1)\n\t\t\t\t}\n\n\t\t\t\tif err2 != nil {\n\t\t\t\t\tutilruntime.HandleError(err2)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t} else if oldMeta.GetResourceVersion() == newMeta.GetResourceVersion() {\n\t\t\t\tif len(oldMeta.GetResourceVersion()) == 0 {\n\t\t\t\t\tklog.Warningf(\"%v throwing out update with empty RV. this is likely to happen if a test did not supply a resource version on an updated object\", c.options.Name)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tenqueue(newObj, false)\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\t// Enqueue\n\t\t\tenqueue(obj, false)\n\t\t},\n\t})\n\n\t// Error might be raised if informer was started and stopped already\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.notificationsDelivered.Store(registration.HasSynced)\n\n\t// Make sure event handler is removed from informer in case return early from\n\t// an error\n\tdefer func() {\n\t\tc.notificationsDelivered.Store(func() bool { return false })\n\t\t// Remove event handler and Handle Error here. Error should only be raised\n\t\t// for improper usage of event handler API.\n\t\tif err := c.informer.RemoveEventHandler(registration); err != nil {\n\t\t\tutilruntime.HandleError(err)\n\t\t}\n\t}()\n\n\t// Wait for initial cache list to complete before beginning to reconcile\n\t// objects.\n\tif !cache.WaitForNamedCacheSync(c.options.Name, ctx.Done(), c.informer.HasSynced) {\n\t\t// ctx cancelled during cache sync. return early\n\t\terr := ctx.Err()\n\t\tif err == nil {\n\t\t\t// if context wasnt cancelled then the sync failed for another reason\n\t\t\terr = errors.New(\"cache sync failed\")\n\t\t}\n\t\treturn err\n\t}\n\n\twaitGroup := sync.WaitGroup{}\n\n\tfor i := uint(0); i \u003c c.options.Workers; i++ {\n\t\twaitGroup.Add(1)\n\t\tgo func() {\n\t\t\tdefer waitGroup.Done()\n\t\t\twait.Until(c.runWorker, time.Second, ctx.Done())\n\t\t}()\n\t}\n\n\tklog.Infof(\"Started %v workers for %v\", c.options.Workers, c.options.Name)\n\n\t// Wait for context cancel.\n\t\u003c-ctx.Done()\n\n\t// Forcefully shutdown workqueue. Drop any enqueued items.\n\tc.queue.ShutDown()\n\n\t// Workqueue shutdown signals for workers to stop. Wait for all workers to\n\t// clean up\n\twaitGroup.Wait()\n\n\t// Only way for workers to ever stop is for caller to cancel the context\n\treturn ctx.Err()\n}","line":{"from":95,"to":208}} {"id":100016626,"name":"HasSynced","signature":"func (c *controller[T]) HasSynced() bool","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/internal/generic/controller.go","code":"func (c *controller[T]) HasSynced() bool {\n\treturn c.hasProcessed.HasSynced()\n}","line":{"from":210,"to":212}} {"id":100016627,"name":"runWorker","signature":"func (c *controller[T]) runWorker()","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/internal/generic/controller.go","code":"func (c *controller[T]) runWorker() {\n\tfor {\n\t\tkey, shutdown := c.queue.Get()\n\t\tif shutdown {\n\t\t\treturn\n\t\t}\n\n\t\t// We wrap this block in a func so we can defer c.workqueue.Done.\n\t\terr := func(obj interface{}) error {\n\t\t\t// We call Done here so the workqueue knows we have finished\n\t\t\t// processing this item. We also must remember to call Forget if we\n\t\t\t// do not want this work item being re-queued. For example, we do\n\t\t\t// not call Forget if a transient error occurs, instead the item is\n\t\t\t// put back on the workqueue and attempted again after a back-off\n\t\t\t// period.\n\t\t\tdefer c.queue.Done(obj)\n\t\t\tvar key string\n\t\t\tvar ok bool\n\t\t\t// We expect strings to come off the workqueue. These are of the\n\t\t\t// form namespace/name. We do this as the delayed nature of the\n\t\t\t// workqueue means the items in the informer cache may actually be\n\t\t\t// more up to date that when the item was initially put onto the\n\t\t\t// workqueue.\n\t\t\tif key, ok = obj.(string); !ok {\n\t\t\t\t// How did an incorrectly formatted key get in the workqueue?\n\t\t\t\t// Done is sufficient. (Forget resets rate limiter for the key,\n\t\t\t\t// but the key is invalid so there is no point in doing that)\n\t\t\t\treturn fmt.Errorf(\"expected string in workqueue but got %#v\", obj)\n\t\t\t}\n\t\t\tdefer c.hasProcessed.Finished(key)\n\n\t\t\tif err := c.reconcile(key); err != nil {\n\t\t\t\t// Put the item back on the workqueue to handle any transient errors.\n\t\t\t\tc.queue.AddRateLimited(key)\n\t\t\t\treturn fmt.Errorf(\"error syncing '%s': %s, requeuing\", key, err.Error())\n\t\t\t}\n\t\t\t// Finally, if no error occurs we Forget this item so it is allowed\n\t\t\t// to be re-enqueued without a long rate limit\n\t\t\tc.queue.Forget(obj)\n\t\t\tklog.V(4).Infof(\"syncAdmissionPolicy(%q)\", key)\n\t\t\treturn nil\n\t\t}(key)\n\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(err)\n\t\t}\n\t}\n}","line":{"from":214,"to":261}} {"id":100016628,"name":"reconcile","signature":"func (c *controller[T]) reconcile(key string) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/internal/generic/controller.go","code":"func (c *controller[T]) reconcile(key string) error {\n\tvar newObj T\n\tvar err error\n\tvar namespace string\n\tvar name string\n\tvar lister NamespacedLister[T]\n\n\t// Convert the namespace/name string into a distinct namespace and name\n\tnamespace, name, err = cache.SplitMetaNamespaceKey(key)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"invalid resource key: %s\", key))\n\t\treturn nil\n\t}\n\n\tif len(namespace) \u003e 0 {\n\t\tlister = c.informer.Namespaced(namespace)\n\t} else {\n\t\tlister = c.informer\n\t}\n\n\tnewObj, err = lister.Get(name)\n\tif err != nil {\n\t\tif !kerrors.IsNotFound(err) {\n\t\t\treturn err\n\t\t}\n\n\t\t// Deleted object. Inform reconciler with empty\n\t}\n\n\treturn c.reconciler(namespace, name, newObj)\n}","line":{"from":263,"to":293}} {"id":100016629,"name":"NewInformer","signature":"func NewInformer[T runtime.Object](informe cache.SharedIndexInformer) Informer[T]","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/internal/generic/informer.go","code":"func NewInformer[T runtime.Object](informe cache.SharedIndexInformer) Informer[T] {\n\treturn informer[T]{\n\t\tSharedIndexInformer: informe,\n\t\tlister: NewLister[T](informe.GetIndexer()),\n\t}\n}","line":{"from":31,"to":36}} {"id":100016630,"name":"List","signature":"func (w namespacedLister[T]) List(selector labels.Selector) (ret []T, err error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/internal/generic/lister.go","code":"func (w namespacedLister[T]) List(selector labels.Selector) (ret []T, err error) {\n\terr = cache.ListAllByNamespace(w.indexer, w.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(T))\n\t})\n\treturn ret, err\n}","line":{"from":37,"to":42}} {"id":100016631,"name":"Get","signature":"func (w namespacedLister[T]) Get(name string) (T, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/internal/generic/lister.go","code":"func (w namespacedLister[T]) Get(name string) (T, error) {\n\tvar result T\n\n\tobj, exists, err := w.indexer.GetByKey(w.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tif !exists {\n\t\treturn result, \u0026kerrors.StatusError{ErrStatus: metav1.Status{\n\t\t\tStatus: metav1.StatusFailure,\n\t\t\tCode: http.StatusNotFound,\n\t\t\tReason: metav1.StatusReasonNotFound,\n\t\t\tMessage: fmt.Sprintf(\"%s not found\", name),\n\t\t}}\n\t}\n\tresult = obj.(T)\n\treturn result, nil\n}","line":{"from":44,"to":61}} {"id":100016632,"name":"List","signature":"func (w lister[T]) List(selector labels.Selector) (ret []T, err error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/internal/generic/lister.go","code":"func (w lister[T]) List(selector labels.Selector) (ret []T, err error) {\n\terr = cache.ListAll(w.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(T))\n\t})\n\treturn ret, err\n}","line":{"from":67,"to":72}} {"id":100016633,"name":"Get","signature":"func (w lister[T]) Get(name string) (T, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/internal/generic/lister.go","code":"func (w lister[T]) Get(name string) (T, error) {\n\tvar result T\n\n\tobj, exists, err := w.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tif !exists {\n\t\t// kerrors.StatusNotFound requires a GroupResource we cannot provide\n\t\treturn result, \u0026kerrors.StatusError{ErrStatus: metav1.Status{\n\t\t\tStatus: metav1.StatusFailure,\n\t\t\tCode: http.StatusNotFound,\n\t\t\tReason: metav1.StatusReasonNotFound,\n\t\t\tMessage: fmt.Sprintf(\"%s not found\", name),\n\t\t}}\n\t}\n\tresult = obj.(T)\n\treturn result, nil\n}","line":{"from":74,"to":92}} {"id":100016634,"name":"Namespaced","signature":"func (w lister[T]) Namespaced(namespace string) NamespacedLister[T]","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/internal/generic/lister.go","code":"func (w lister[T]) Namespaced(namespace string) NamespacedLister[T] {\n\treturn namespacedLister[T]{namespace: namespace, indexer: w.indexer}\n}","line":{"from":94,"to":96}} {"id":100016635,"name":"NewLister","signature":"func NewLister[T runtime.Object](indexer cache.Indexer) lister[T]","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/internal/generic/lister.go","code":"func NewLister[T runtime.Object](indexer cache.Indexer) lister[T] {\n\treturn lister[T]{indexer: indexer}\n}","line":{"from":98,"to":100}} {"id":100016636,"name":"GetParsedNamespaceSelector","signature":"func (m *matchCriteria) GetParsedNamespaceSelector() (labels.Selector, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matcher.go","code":"// GetParsedNamespaceSelector returns the converted LabelSelector which implements labels.Selector\nfunc (m *matchCriteria) GetParsedNamespaceSelector() (labels.Selector, error) {\n\treturn metav1.LabelSelectorAsSelector(m.constraints.NamespaceSelector)\n}","line":{"from":34,"to":37}} {"id":100016637,"name":"GetParsedObjectSelector","signature":"func (m *matchCriteria) GetParsedObjectSelector() (labels.Selector, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matcher.go","code":"// GetParsedObjectSelector returns the converted LabelSelector which implements labels.Selector\nfunc (m *matchCriteria) GetParsedObjectSelector() (labels.Selector, error) {\n\treturn metav1.LabelSelectorAsSelector(m.constraints.ObjectSelector)\n}","line":{"from":39,"to":42}} {"id":100016638,"name":"GetMatchResources","signature":"func (m *matchCriteria) GetMatchResources() v1alpha1.MatchResources","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matcher.go","code":"// GetMatchResources returns the matchConstraints\nfunc (m *matchCriteria) GetMatchResources() v1alpha1.MatchResources {\n\treturn *m.constraints\n}","line":{"from":44,"to":47}} {"id":100016639,"name":"NewMatcher","signature":"func NewMatcher(m *matching.Matcher) Matcher","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matcher.go","code":"func NewMatcher(m *matching.Matcher) Matcher {\n\treturn \u0026matcher{\n\t\tMatcher: m,\n\t}\n}","line":{"from":53,"to":57}} {"id":100016640,"name":"ValidateInitialization","signature":"func (c *matcher) ValidateInitialization() error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matcher.go","code":"// ValidateInitialization checks if Matcher is initialized.\nfunc (c *matcher) ValidateInitialization() error {\n\treturn c.Matcher.ValidateInitialization()\n}","line":{"from":59,"to":62}} {"id":100016641,"name":"DefinitionMatches","signature":"func (c *matcher) DefinitionMatches(a admission.Attributes, o admission.ObjectInterfaces, definition *v1alpha1.ValidatingAdmissionPolicy) (bool, schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matcher.go","code":"// DefinitionMatches returns whether this ValidatingAdmissionPolicy matches the provided admission resource request\nfunc (c *matcher) DefinitionMatches(a admission.Attributes, o admission.ObjectInterfaces, definition *v1alpha1.ValidatingAdmissionPolicy) (bool, schema.GroupVersionKind, error) {\n\tcriteria := matchCriteria{constraints: definition.Spec.MatchConstraints}\n\treturn c.Matcher.Matches(a, o, \u0026criteria)\n}","line":{"from":64,"to":68}} {"id":100016642,"name":"BindingMatches","signature":"func (c *matcher) BindingMatches(a admission.Attributes, o admission.ObjectInterfaces, binding *v1alpha1.ValidatingAdmissionPolicyBinding) (bool, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matcher.go","code":"// BindingMatches returns whether this ValidatingAdmissionPolicyBinding matches the provided admission resource request\nfunc (c *matcher) BindingMatches(a admission.Attributes, o admission.ObjectInterfaces, binding *v1alpha1.ValidatingAdmissionPolicyBinding) (bool, error) {\n\tif binding.Spec.MatchResources == nil {\n\t\treturn true, nil\n\t}\n\tcriteria := matchCriteria{constraints: binding.Spec.MatchResources}\n\tisMatch, _, err := c.Matcher.Matches(a, o, \u0026criteria)\n\treturn isMatch, err\n}","line":{"from":70,"to":78}} {"id":100016643,"name":"NewMatcher","signature":"func NewMatcher(","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching.go","code":"// NewMatcher initialize the matcher with dependencies requires\nfunc NewMatcher(\n\tnamespaceLister listersv1.NamespaceLister,\n\tclient kubernetes.Interface,\n) *Matcher {\n\treturn \u0026Matcher{\n\t\tnamespaceMatcher: \u0026namespace.Matcher{\n\t\t\tNamespaceLister: namespaceLister,\n\t\t\tClient: client,\n\t\t},\n\t\tobjectMatcher: \u0026object.Matcher{},\n\t}\n}","line":{"from":47,"to":59}} {"id":100016644,"name":"ValidateInitialization","signature":"func (m *Matcher) ValidateInitialization() error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching.go","code":"// ValidateInitialization verify if the matcher is ready before use\nfunc (m *Matcher) ValidateInitialization() error {\n\tif err := m.namespaceMatcher.Validate(); err != nil {\n\t\treturn fmt.Errorf(\"namespaceMatcher is not properly setup: %v\", err)\n\t}\n\treturn nil\n}","line":{"from":61,"to":67}} {"id":100016645,"name":"Matches","signature":"func (m *Matcher) Matches(attr admission.Attributes, o admission.ObjectInterfaces, criteria MatchCriteria) (bool, schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching.go","code":"func (m *Matcher) Matches(attr admission.Attributes, o admission.ObjectInterfaces, criteria MatchCriteria) (bool, schema.GroupVersionKind, error) {\n\tmatches, matchNsErr := m.namespaceMatcher.MatchNamespaceSelector(criteria, attr)\n\t// Should not return an error here for policy which do not apply to the request, even if err is an unexpected scenario.\n\tif !matches \u0026\u0026 matchNsErr == nil {\n\t\treturn false, schema.GroupVersionKind{}, nil\n\t}\n\n\tmatches, matchObjErr := m.objectMatcher.MatchObjectSelector(criteria, attr)\n\t// Should not return an error here for policy which do not apply to the request, even if err is an unexpected scenario.\n\tif !matches \u0026\u0026 matchObjErr == nil {\n\t\treturn false, schema.GroupVersionKind{}, nil\n\t}\n\n\tmatchResources := criteria.GetMatchResources()\n\tmatchPolicy := matchResources.MatchPolicy\n\tif isExcluded, _, err := matchesResourceRules(matchResources.ExcludeResourceRules, matchPolicy, attr, o); isExcluded || err != nil {\n\t\treturn false, schema.GroupVersionKind{}, err\n\t}\n\n\tvar (\n\t\tisMatch bool\n\t\tmatchKind schema.GroupVersionKind\n\t\tmatchErr error\n\t)\n\tif len(matchResources.ResourceRules) == 0 {\n\t\tisMatch = true\n\t\tmatchKind = attr.GetKind()\n\t} else {\n\t\tisMatch, matchKind, matchErr = matchesResourceRules(matchResources.ResourceRules, matchPolicy, attr, o)\n\t}\n\tif matchErr != nil {\n\t\treturn false, schema.GroupVersionKind{}, matchErr\n\t}\n\tif !isMatch {\n\t\treturn false, schema.GroupVersionKind{}, nil\n\t}\n\n\t// now that we know this applies to this request otherwise, if there were selector errors, return them\n\tif matchNsErr != nil {\n\t\treturn false, schema.GroupVersionKind{}, matchNsErr\n\t}\n\tif matchObjErr != nil {\n\t\treturn false, schema.GroupVersionKind{}, matchObjErr\n\t}\n\n\treturn true, matchKind, nil\n}","line":{"from":69,"to":115}} {"id":100016646,"name":"matchesResourceRules","signature":"func matchesResourceRules(namedRules []v1alpha1.NamedRuleWithOperations, matchPolicy *v1alpha1.MatchPolicyType, attr admission.Attributes, o admission.ObjectInterfaces) (bool, schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching.go","code":"func matchesResourceRules(namedRules []v1alpha1.NamedRuleWithOperations, matchPolicy *v1alpha1.MatchPolicyType, attr admission.Attributes, o admission.ObjectInterfaces) (bool, schema.GroupVersionKind, error) {\n\tmatchKind := attr.GetKind()\n\tfor _, namedRule := range namedRules {\n\t\trule := v1.RuleWithOperations(namedRule.RuleWithOperations)\n\t\truleMatcher := rules.Matcher{\n\t\t\tRule: rule,\n\t\t\tAttr: attr,\n\t\t}\n\t\tif !ruleMatcher.Matches() {\n\t\t\tcontinue\n\t\t}\n\t\t// an empty name list always matches\n\t\tif len(namedRule.ResourceNames) == 0 {\n\t\t\treturn true, matchKind, nil\n\t\t}\n\t\t// TODO: GetName() can return an empty string if the user is relying on\n\t\t// the API server to generate the name... figure out what to do for this edge case\n\t\tname := attr.GetName()\n\t\tfor _, matchedName := range namedRule.ResourceNames {\n\t\t\tif name == matchedName {\n\t\t\t\treturn true, matchKind, nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// if match policy is undefined or exact, don't perform fuzzy matching\n\t// note that defaulting to fuzzy matching is set by the API\n\tif matchPolicy == nil || *matchPolicy == v1alpha1.Exact {\n\t\treturn false, schema.GroupVersionKind{}, nil\n\t}\n\n\tattrWithOverride := \u0026attrWithResourceOverride{Attributes: attr}\n\tequivalents := o.GetEquivalentResourceMapper().EquivalentResourcesFor(attr.GetResource(), attr.GetSubresource())\n\tfor _, namedRule := range namedRules {\n\t\tfor _, equivalent := range equivalents {\n\t\t\tif equivalent == attr.GetResource() {\n\t\t\t\t// we have already checked the original resource\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tattrWithOverride.resource = equivalent\n\t\t\trule := v1.RuleWithOperations(namedRule.RuleWithOperations)\n\t\t\tm := rules.Matcher{\n\t\t\t\tRule: rule,\n\t\t\t\tAttr: attrWithOverride,\n\t\t\t}\n\t\t\tif !m.Matches() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmatchKind = o.GetEquivalentResourceMapper().KindFor(equivalent, attr.GetSubresource())\n\t\t\tif matchKind.Empty() {\n\t\t\t\treturn false, schema.GroupVersionKind{}, fmt.Errorf(\"unable to convert to %v: unknown kind\", equivalent)\n\t\t\t}\n\t\t\t// an empty name list always matches\n\t\t\tif len(namedRule.ResourceNames) == 0 {\n\t\t\t\treturn true, matchKind, nil\n\t\t\t}\n\n\t\t\t// TODO: GetName() can return an empty string if the user is relying on\n\t\t\t// the API server to generate the name... figure out what to do for this edge case\n\t\t\tname := attr.GetName()\n\t\t\tfor _, matchedName := range namedRule.ResourceNames {\n\t\t\t\tif name == matchedName {\n\t\t\t\t\treturn true, matchKind, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false, schema.GroupVersionKind{}, nil\n}","line":{"from":117,"to":185}} {"id":100016647,"name":"GetResource","signature":"func (a *attrWithResourceOverride) GetResource() schema.GroupVersionResource { return a.resource }","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching.go","code":"func (a *attrWithResourceOverride) GetResource() schema.GroupVersionResource { return a.resource }","line":{"from":192,"to":192}} {"id":100016648,"name":"GetExpression","signature":"func (m *MessageExpressionCondition) GetExpression() string","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/message.go","code":"func (m *MessageExpressionCondition) GetExpression() string {\n\treturn m.MessageExpression\n}","line":{"from":30,"to":32}} {"id":100016649,"name":"ReturnTypes","signature":"func (m *MessageExpressionCondition) ReturnTypes() []*celgo.Type","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/message.go","code":"func (m *MessageExpressionCondition) ReturnTypes() []*celgo.Type {\n\treturn []*celgo.Type{celgo.StringType}\n}","line":{"from":34,"to":36}} {"id":100016650,"name":"reasonToCode","signature":"func reasonToCode(r metav1.StatusReason) int32","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/policy_decision.go","code":"func reasonToCode(r metav1.StatusReason) int32 {\n\tswitch r {\n\tcase metav1.StatusReasonForbidden:\n\t\treturn http.StatusForbidden\n\tcase metav1.StatusReasonUnauthorized:\n\t\treturn http.StatusUnauthorized\n\tcase metav1.StatusReasonRequestEntityTooLarge:\n\t\treturn http.StatusRequestEntityTooLarge\n\tcase metav1.StatusReasonInvalid:\n\t\treturn http.StatusUnprocessableEntity\n\tdefault:\n\t\t// It should not reach here since we only allow above reason to be set from API level\n\t\treturn http.StatusUnprocessableEntity\n\t}\n}","line":{"from":73,"to":87}} {"id":100016651,"name":"Check","signature":"func (c *TypeChecker) Check(policy *v1alpha1.ValidatingAdmissionPolicy) []v1alpha1.ExpressionWarning","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/typechecking.go","code":"// Check preforms the type check against the given policy, and format the result\n// as []ExpressionWarning that is ready to be set in policy.Status\n// The result is nil if type checking returns no warning.\n// The policy object is NOT mutated. The caller should update Status accordingly\nfunc (c *TypeChecker) Check(policy *v1alpha1.ValidatingAdmissionPolicy) []v1alpha1.ExpressionWarning {\n\texps := make([]string, 0, len(policy.Spec.Validations))\n\t// check main validation expressions, located in spec.validations[*]\n\tfieldRef := field.NewPath(\"spec\", \"validations\")\n\tfor _, v := range policy.Spec.Validations {\n\t\texps = append(exps, v.Expression)\n\t}\n\tmsgs := c.CheckExpressions(exps, policy.Spec.ParamKind != nil, policy)\n\tvar results []v1alpha1.ExpressionWarning // intentionally not setting capacity\n\tfor i, msg := range msgs {\n\t\tif msg != \"\" {\n\t\t\tresults = append(results, v1alpha1.ExpressionWarning{\n\t\t\t\tFieldRef: fieldRef.Index(i).Child(\"expression\").String(),\n\t\t\t\tWarning: msg,\n\t\t\t})\n\t\t}\n\t}\n\treturn results\n}","line":{"from":64,"to":86}} {"id":100016652,"name":"CheckExpressions","signature":"func (c *TypeChecker) CheckExpressions(expressions []string, hasParams bool, policy *v1alpha1.ValidatingAdmissionPolicy) []string","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/typechecking.go","code":"// CheckExpressions checks a set of compiled CEL programs against the GVKs defined in\n// policy.Spec.MatchConstraints\n// The result is a human-readable form that describe which expressions\n// violate what types at what place. The indexes of the return []string\n// matches these of the input expressions.\n// TODO: It is much more useful to have machine-readable output and let the\n// client format it. That requires an update to the KEP, probably in coming\n// releases.\nfunc (c *TypeChecker) CheckExpressions(expressions []string, hasParams bool, policy *v1alpha1.ValidatingAdmissionPolicy) []string {\n\tvar allWarnings []string\n\tallGvks := c.typesToCheck(policy)\n\tgvks := make([]schema.GroupVersionKind, 0, len(allGvks))\n\tschemas := make([]common.Schema, 0, len(allGvks))\n\tfor _, gvk := range allGvks {\n\t\ts, err := c.schemaResolver.ResolveSchema(gvk)\n\t\tif err != nil {\n\t\t\t// type checking errors MUST NOT alter the behavior of the policy\n\t\t\t// even if an error occurs.\n\t\t\tif !errors.Is(err, resolver.ErrSchemaNotFound) {\n\t\t\t\t// Anything except ErrSchemaNotFound is an internal error\n\t\t\t\tklog.ErrorS(err, \"internal error: schema resolution failure\", \"gvk\", gvk)\n\t\t\t}\n\t\t\t// skip if an unrecoverable error occurs.\n\t\t\tcontinue\n\t\t}\n\t\tgvks = append(gvks, gvk)\n\t\tschemas = append(schemas, \u0026openapi.Schema{Schema: s})\n\t}\n\n\tparamsType := c.paramsType(policy)\n\tparamsDeclType, err := c.declType(paramsType)\n\tif err != nil {\n\t\tif !errors.Is(err, resolver.ErrSchemaNotFound) {\n\t\t\tklog.V(2).ErrorS(err, \"cannot resolve schema for params\", \"gvk\", paramsType)\n\t\t}\n\t\tparamsDeclType = nil\n\t}\n\n\tfor _, exp := range expressions {\n\t\tvar results []typeCheckingResult\n\t\tfor i, gvk := range gvks {\n\t\t\ts := schemas[i]\n\t\t\tissues, err := c.checkExpression(exp, hasParams, typeOverwrite{\n\t\t\t\tobject: common.SchemaDeclType(s, true),\n\t\t\t\tparams: paramsDeclType,\n\t\t\t})\n\t\t\t// save even if no issues are found, for the sake of formatting.\n\t\t\tresults = append(results, typeCheckingResult{\n\t\t\t\tgvk: gvk,\n\t\t\t\tissues: issues,\n\t\t\t\terr: err,\n\t\t\t})\n\t\t}\n\t\tallWarnings = append(allWarnings, c.formatWarning(results))\n\t}\n\n\treturn allWarnings\n}","line":{"from":88,"to":145}} {"id":100016653,"name":"formatWarning","signature":"func (c *TypeChecker) formatWarning(results []typeCheckingResult) string","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/typechecking.go","code":"// formatWarning converts the resulting issues and possible error during\n// type checking into a human-readable string\nfunc (c *TypeChecker) formatWarning(results []typeCheckingResult) string {\n\tvar sb strings.Builder\n\tfor _, result := range results {\n\t\tif result.issues == nil \u0026\u0026 result.err == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif result.err != nil {\n\t\t\tsb.WriteString(fmt.Sprintf(\"%v: type checking error: %v\\n\", result.gvk, result.err))\n\t\t} else {\n\t\t\tsb.WriteString(fmt.Sprintf(\"%v: %s\\n\", result.gvk, result.issues))\n\t\t}\n\t}\n\treturn strings.TrimSuffix(sb.String(), \"\\n\")\n}","line":{"from":147,"to":162}} {"id":100016654,"name":"declType","signature":"func (c *TypeChecker) declType(gvk schema.GroupVersionKind) (*apiservercel.DeclType, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/typechecking.go","code":"func (c *TypeChecker) declType(gvk schema.GroupVersionKind) (*apiservercel.DeclType, error) {\n\tif gvk.Empty() {\n\t\treturn nil, nil\n\t}\n\ts, err := c.schemaResolver.ResolveSchema(gvk)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn common.SchemaDeclType(\u0026openapi.Schema{Schema: s}, true), nil\n}","line":{"from":164,"to":173}} {"id":100016655,"name":"paramsType","signature":"func (c *TypeChecker) paramsType(policy *v1alpha1.ValidatingAdmissionPolicy) schema.GroupVersionKind","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/typechecking.go","code":"func (c *TypeChecker) paramsType(policy *v1alpha1.ValidatingAdmissionPolicy) schema.GroupVersionKind {\n\tif policy.Spec.ParamKind == nil {\n\t\treturn schema.GroupVersionKind{}\n\t}\n\tgv, err := schema.ParseGroupVersion(policy.Spec.ParamKind.APIVersion)\n\tif err != nil {\n\t\treturn schema.GroupVersionKind{}\n\t}\n\treturn gv.WithKind(policy.Spec.ParamKind.Kind)\n}","line":{"from":175,"to":184}} {"id":100016656,"name":"checkExpression","signature":"func (c *TypeChecker) checkExpression(expression string, hasParams bool, types typeOverwrite) (*cel.Issues, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/typechecking.go","code":"func (c *TypeChecker) checkExpression(expression string, hasParams bool, types typeOverwrite) (*cel.Issues, error) {\n\tenv, err := buildEnv(hasParams, types)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// We cannot reuse an AST that is parsed by another env, so reparse it here.\n\t// Compile = Parse + Check, we especially want the results of Check.\n\t//\n\t// Paradoxically, we discard the type-checked result and let the admission\n\t// controller use the dynamic typed program.\n\t// This is a compromise that is defined in the KEP. We can revisit this\n\t// decision and expect a change with limited size.\n\t_, issues := env.Compile(expression)\n\treturn issues, nil\n}","line":{"from":186,"to":201}} {"id":100016657,"name":"typesToCheck","signature":"func (c *TypeChecker) typesToCheck(p *v1alpha1.ValidatingAdmissionPolicy) []schema.GroupVersionKind","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/typechecking.go","code":"// typesToCheck extracts a list of GVKs that needs type checking from the policy\n// the result is sorted in the order of Group, Version, and Kind\nfunc (c *TypeChecker) typesToCheck(p *v1alpha1.ValidatingAdmissionPolicy) []schema.GroupVersionKind {\n\tgvks := sets.New[schema.GroupVersionKind]()\n\tif p.Spec.MatchConstraints == nil || len(p.Spec.MatchConstraints.ResourceRules) == 0 {\n\t\treturn nil\n\t}\n\n\tfor _, rule := range p.Spec.MatchConstraints.ResourceRules {\n\t\tgroups := extractGroups(\u0026rule.Rule)\n\t\tif len(groups) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tversions := extractVersions(\u0026rule.Rule)\n\t\tif len(versions) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tresources := extractResources(\u0026rule.Rule)\n\t\tif len(resources) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\t// sort GVRs so that the loop below provides\n\t\t// consistent results.\n\t\tsort.Strings(groups)\n\t\tsort.Strings(versions)\n\t\tsort.Strings(resources)\n\t\tcount := 0\n\t\tfor _, group := range groups {\n\t\t\tfor _, version := range versions {\n\t\t\t\tfor _, resource := range resources {\n\t\t\t\t\tgvr := schema.GroupVersionResource{\n\t\t\t\t\t\tGroup: group,\n\t\t\t\t\t\tVersion: version,\n\t\t\t\t\t\tResource: resource,\n\t\t\t\t\t}\n\t\t\t\t\tresolved, err := c.restMapper.KindsFor(gvr)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tfor _, r := range resolved {\n\t\t\t\t\t\tif !r.Empty() {\n\t\t\t\t\t\t\tgvks.Insert(r)\n\t\t\t\t\t\t\tcount++\n\t\t\t\t\t\t\t// early return if maximum number of types are already\n\t\t\t\t\t\t\t// collected\n\t\t\t\t\t\t\tif count == maxTypesToCheck {\n\t\t\t\t\t\t\t\tif gvks.Len() == 0 {\n\t\t\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn sortGVKList(gvks.UnsortedList())\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif gvks.Len() == 0 {\n\t\treturn nil\n\t}\n\treturn sortGVKList(gvks.UnsortedList())\n}","line":{"from":203,"to":264}} {"id":100016658,"name":"extractGroups","signature":"func extractGroups(rule *v1alpha1.Rule) []string","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/typechecking.go","code":"func extractGroups(rule *v1alpha1.Rule) []string {\n\tgroups := make([]string, 0, len(rule.APIGroups))\n\tfor _, group := range rule.APIGroups {\n\t\t// give up if wildcard\n\t\tif strings.ContainsAny(group, \"*\") {\n\t\t\treturn nil\n\t\t}\n\t\tgroups = append(groups, group)\n\t}\n\treturn groups\n}","line":{"from":266,"to":276}} {"id":100016659,"name":"extractVersions","signature":"func extractVersions(rule *v1alpha1.Rule) []string","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/typechecking.go","code":"func extractVersions(rule *v1alpha1.Rule) []string {\n\tversions := make([]string, 0, len(rule.APIVersions))\n\tfor _, version := range rule.APIVersions {\n\t\tif strings.ContainsAny(version, \"*\") {\n\t\t\treturn nil\n\t\t}\n\t\tversions = append(versions, version)\n\t}\n\treturn versions\n}","line":{"from":278,"to":287}} {"id":100016660,"name":"extractResources","signature":"func extractResources(rule *v1alpha1.Rule) []string","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/typechecking.go","code":"func extractResources(rule *v1alpha1.Rule) []string {\n\tresources := make([]string, 0, len(rule.Resources))\n\tfor _, resource := range rule.Resources {\n\t\t// skip wildcard and subresources\n\t\tif strings.ContainsAny(resource, \"*/\") {\n\t\t\tcontinue\n\t\t}\n\t\tresources = append(resources, resource)\n\t}\n\treturn resources\n}","line":{"from":289,"to":299}} {"id":100016661,"name":"sortGVKList","signature":"func sortGVKList(list []schema.GroupVersionKind) []schema.GroupVersionKind","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/typechecking.go","code":"// sortGVKList sorts the list by Group, Version, and Kind\n// returns the list itself.\nfunc sortGVKList(list []schema.GroupVersionKind) []schema.GroupVersionKind {\n\tsort.Slice(list, func(i, j int) bool {\n\t\tif g := strings.Compare(list[i].Group, list[j].Group); g != 0 {\n\t\t\treturn g \u003c 0\n\t\t}\n\t\tif v := strings.Compare(list[i].Version, list[j].Version); v != 0 {\n\t\t\treturn v \u003c 0\n\t\t}\n\t\treturn strings.Compare(list[i].Kind, list[j].Kind) \u003c 0\n\t})\n\treturn list\n}","line":{"from":301,"to":314}} {"id":100016662,"name":"buildEnv","signature":"func buildEnv(hasParams bool, types typeOverwrite) (*cel.Env, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/typechecking.go","code":"func buildEnv(hasParams bool, types typeOverwrite) (*cel.Env, error) {\n\tbaseEnv, err := getBaseEnv()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treg := apiservercel.NewRegistry(baseEnv)\n\trequestType := plugincel.BuildRequestType()\n\n\tvar varOpts []cel.EnvOption\n\tvar rts []*apiservercel.RuleTypes\n\n\t// request, hand-crafted type\n\trt, opts, err := createRuleTypesAndOptions(reg, requestType, plugincel.RequestVarName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trts = append(rts, rt)\n\tvarOpts = append(varOpts, opts...)\n\n\t// object and oldObject, same type, type(s) resolved from constraints\n\trt, opts, err = createRuleTypesAndOptions(reg, types.object, plugincel.ObjectVarName, plugincel.OldObjectVarName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trts = append(rts, rt)\n\tvarOpts = append(varOpts, opts...)\n\n\t// params, defined by ParamKind\n\tif hasParams {\n\t\trt, opts, err := createRuleTypesAndOptions(reg, types.params, plugincel.ParamsVarName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trts = append(rts, rt)\n\t\tvarOpts = append(varOpts, opts...)\n\t}\n\n\topts, err = ruleTypesOpts(rts, baseEnv.TypeProvider())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\topts = append(opts, varOpts...) // add variables after ruleTypes.\n\tenv, err := baseEnv.Extend(opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn env, nil\n}","line":{"from":316,"to":363}} {"id":100016663,"name":"createRuleTypesAndOptions","signature":"func createRuleTypesAndOptions(registry *apiservercel.Registry, declType *apiservercel.DeclType, variables ...string) (*apiservercel.RuleTypes, []cel.EnvOption, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/typechecking.go","code":"// createRuleTypeAndOptions creates the cel RuleTypes and a slice of EnvOption\n// that can be used for creating a CEL env containing variables of declType.\n// declType can be nil, in which case the variables will be of DynType.\nfunc createRuleTypesAndOptions(registry *apiservercel.Registry, declType *apiservercel.DeclType, variables ...string) (*apiservercel.RuleTypes, []cel.EnvOption, error) {\n\topts := make([]cel.EnvOption, 0, len(variables))\n\t// untyped, use DynType\n\tif declType == nil {\n\t\tfor _, v := range variables {\n\t\t\topts = append(opts, cel.Variable(v, cel.DynType))\n\t\t}\n\t\treturn nil, opts, nil\n\t}\n\t// create a RuleType for the given type\n\trt, err := apiservercel.NewRuleTypes(declType.TypeName(), declType, registry)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif rt == nil {\n\t\treturn nil, nil, nil\n\t}\n\tfor _, v := range variables {\n\t\topts = append(opts, cel.Variable(v, declType.CelType()))\n\t}\n\treturn rt, opts, nil\n}","line":{"from":365,"to":389}} {"id":100016664,"name":"ruleTypesOpts","signature":"func ruleTypesOpts(ruleTypes []*apiservercel.RuleTypes, underlyingTypeProvider ref.TypeProvider) ([]cel.EnvOption, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/typechecking.go","code":"func ruleTypesOpts(ruleTypes []*apiservercel.RuleTypes, underlyingTypeProvider ref.TypeProvider) ([]cel.EnvOption, error) {\n\tvar providers []ref.TypeProvider // may be unused, too small to matter\n\tvar adapters []ref.TypeAdapter\n\tfor _, rt := range ruleTypes {\n\t\tif rt != nil {\n\t\t\twithTP, err := rt.WithTypeProvider(underlyingTypeProvider)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tproviders = append(providers, withTP)\n\t\t\tadapters = append(adapters, withTP)\n\t\t}\n\t}\n\tvar tp ref.TypeProvider\n\tvar ta ref.TypeAdapter\n\tswitch len(providers) {\n\tcase 0:\n\t\treturn nil, nil\n\tcase 1:\n\t\ttp = providers[0]\n\t\tta = adapters[0]\n\tdefault:\n\t\ttp = \u0026apiservercel.CompositedTypeProvider{Providers: providers}\n\t\tta = \u0026apiservercel.CompositedTypeAdapter{Adapters: adapters}\n\t}\n\treturn []cel.EnvOption{cel.CustomTypeProvider(tp), cel.CustomTypeAdapter(ta)}, nil\n}","line":{"from":391,"to":417}} {"id":100016665,"name":"getBaseEnv","signature":"func getBaseEnv() (*cel.Env, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/typechecking.go","code":"func getBaseEnv() (*cel.Env, error) {\n\ttypeCheckingBaseEnvInit.Do(func() {\n\t\tvar opts []cel.EnvOption\n\t\topts = append(opts, cel.HomogeneousAggregateLiterals())\n\t\t// Validate function declarations once during base env initialization,\n\t\t// so they don't need to be evaluated each time a CEL rule is compiled.\n\t\t// This is a relatively expensive operation.\n\t\topts = append(opts, cel.EagerlyValidateDeclarations(true), cel.DefaultUTCTimeZone(true))\n\t\topts = append(opts, library.ExtensionLibs...)\n\t\ttypeCheckingBaseEnv, typeCheckingBaseEnvError = cel.NewEnv(opts...)\n\t})\n\treturn typeCheckingBaseEnv, typeCheckingBaseEnvError\n}","line":{"from":419,"to":431}} {"id":100016666,"name":"NewValidator","signature":"func NewValidator(validationFilter cel.Filter, celMatcher matchconditions.Matcher, auditAnnotationFilter, messageFilter cel.Filter, failPolicy *v1.FailurePolicyType, authorizer authorizer.Authorizer) Validator","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/validator.go","code":"func NewValidator(validationFilter cel.Filter, celMatcher matchconditions.Matcher, auditAnnotationFilter, messageFilter cel.Filter, failPolicy *v1.FailurePolicyType, authorizer authorizer.Authorizer) Validator {\n\treturn \u0026validator{\n\t\tcelMatcher: celMatcher,\n\t\tvalidationFilter: validationFilter,\n\t\tauditAnnotationFilter: auditAnnotationFilter,\n\t\tmessageFilter: messageFilter,\n\t\tfailPolicy: failPolicy,\n\t\tauthorizer: authorizer,\n\t}\n}","line":{"from":48,"to":57}} {"id":100016667,"name":"policyDecisionActionForError","signature":"func policyDecisionActionForError(f v1.FailurePolicyType) PolicyDecisionAction","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/validator.go","code":"func policyDecisionActionForError(f v1.FailurePolicyType) PolicyDecisionAction {\n\tif f == v1.Ignore {\n\t\treturn ActionAdmit\n\t}\n\treturn ActionDeny\n}","line":{"from":59,"to":64}} {"id":100016668,"name":"auditAnnotationEvaluationForError","signature":"func auditAnnotationEvaluationForError(f v1.FailurePolicyType) PolicyAuditAnnotationAction","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/validator.go","code":"func auditAnnotationEvaluationForError(f v1.FailurePolicyType) PolicyAuditAnnotationAction {\n\tif f == v1.Ignore {\n\t\treturn AuditAnnotationActionExclude\n\t}\n\treturn AuditAnnotationActionError\n}","line":{"from":66,"to":71}} {"id":100016669,"name":"Validate","signature":"func (v *validator) Validate(ctx context.Context, versionedAttr *admission.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) ValidateResult","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/validator.go","code":"// Validate takes a list of Evaluation and a failure policy and converts them into actionable PolicyDecisions\n// runtimeCELCostBudget was added for testing purpose only. Callers should always use const RuntimeCELCostBudget from k8s.io/apiserver/pkg/apis/cel/config.go as input.\nfunc (v *validator) Validate(ctx context.Context, versionedAttr *admission.VersionedAttributes, versionedParams runtime.Object, runtimeCELCostBudget int64) ValidateResult {\n\tvar f v1.FailurePolicyType\n\tif v.failPolicy == nil {\n\t\tf = v1.Fail\n\t} else {\n\t\tf = *v.failPolicy\n\t}\n\n\tif v.celMatcher != nil {\n\t\tmatchResults := v.celMatcher.Match(ctx, versionedAttr, versionedParams)\n\t\tif matchResults.Error != nil {\n\t\t\treturn ValidateResult{\n\t\t\t\tDecisions: []PolicyDecision{\n\t\t\t\t\t{\n\t\t\t\t\t\tAction: policyDecisionActionForError(f),\n\t\t\t\t\t\tEvaluation: EvalError,\n\t\t\t\t\t\tMessage: matchResults.Error.Error(),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\n\t\t// if preconditions are not met, then do not return any validations\n\t\tif !matchResults.Matches {\n\t\t\treturn ValidateResult{}\n\t\t}\n\t}\n\n\toptionalVars := cel.OptionalVariableBindings{VersionedParams: versionedParams, Authorizer: v.authorizer}\n\texpressionOptionalVars := cel.OptionalVariableBindings{VersionedParams: versionedParams}\n\tadmissionRequest := cel.CreateAdmissionRequest(versionedAttr.Attributes)\n\tevalResults, remainingBudget, err := v.validationFilter.ForInput(ctx, versionedAttr, admissionRequest, optionalVars, runtimeCELCostBudget)\n\tif err != nil {\n\t\treturn ValidateResult{\n\t\t\tDecisions: []PolicyDecision{\n\t\t\t\t{\n\t\t\t\t\tAction: policyDecisionActionForError(f),\n\t\t\t\t\tEvaluation: EvalError,\n\t\t\t\t\tMessage: err.Error(),\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\tdecisions := make([]PolicyDecision, len(evalResults))\n\tmessageResults, _, err := v.messageFilter.ForInput(ctx, versionedAttr, admissionRequest, expressionOptionalVars, remainingBudget)\n\tfor i, evalResult := range evalResults {\n\t\tvar decision = \u0026decisions[i]\n\t\t// TODO: move this to generics\n\t\tvalidation, ok := evalResult.ExpressionAccessor.(*ValidationCondition)\n\t\tif !ok {\n\t\t\tklog.Error(\"Invalid type conversion to ValidationCondition\")\n\t\t\tdecision.Action = policyDecisionActionForError(f)\n\t\t\tdecision.Evaluation = EvalError\n\t\t\tdecision.Message = \"Invalid type sent to validator, expected ValidationCondition\"\n\t\t\tcontinue\n\t\t}\n\n\t\tvar messageResult *cel.EvaluationResult\n\t\tvar messageError *apiservercel.Error\n\t\tif len(messageResults) \u003e i {\n\t\t\tmessageResult = \u0026messageResults[i]\n\t\t}\n\t\tmessageError, _ = err.(*apiservercel.Error)\n\t\tif evalResult.Error != nil {\n\t\t\tdecision.Action = policyDecisionActionForError(f)\n\t\t\tdecision.Evaluation = EvalError\n\t\t\tdecision.Message = evalResult.Error.Error()\n\t\t} else if messageError != nil \u0026\u0026\n\t\t\t(messageError.Type == apiservercel.ErrorTypeInternal ||\n\t\t\t\t(messageError.Type == apiservercel.ErrorTypeInvalid \u0026\u0026\n\t\t\t\t\tstrings.HasPrefix(messageError.Detail, \"validation failed due to running out of cost budget\"))) {\n\t\t\tdecision.Action = policyDecisionActionForError(f)\n\t\t\tdecision.Evaluation = EvalError\n\t\t\tdecision.Message = fmt.Sprintf(\"failed messageExpression: %s\", err)\n\t\t} else if evalResult.EvalResult != celtypes.True {\n\t\t\tdecision.Action = ActionDeny\n\t\t\tif validation.Reason == nil {\n\t\t\t\tdecision.Reason = metav1.StatusReasonInvalid\n\t\t\t} else {\n\t\t\t\tdecision.Reason = *validation.Reason\n\t\t\t}\n\t\t\t// decide the failure message\n\t\t\tvar message string\n\t\t\t// attempt to set message with messageExpression result\n\t\t\tif messageResult != nil \u0026\u0026 messageResult.Error == nil \u0026\u0026 messageResult.EvalResult != nil {\n\t\t\t\t// also fallback if the eval result is non-string (including null) or\n\t\t\t\t// whitespaces.\n\t\t\t\tif message, ok = messageResult.EvalResult.Value().(string); ok {\n\t\t\t\t\tmessage = strings.TrimSpace(message)\n\t\t\t\t\t// deny excessively long message from EvalResult\n\t\t\t\t\tif len(message) \u003e celconfig.MaxEvaluatedMessageExpressionSizeBytes {\n\t\t\t\t\t\tklog.V(2).InfoS(\"excessively long message denied\", \"message\", message)\n\t\t\t\t\t\tmessage = \"\"\n\t\t\t\t\t}\n\t\t\t\t\t// deny message that contains newlines\n\t\t\t\t\tif strings.ContainsAny(message, \"\\n\") {\n\t\t\t\t\t\tklog.V(2).InfoS(\"multi-line message denied\", \"message\", message)\n\t\t\t\t\t\tmessage = \"\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif messageResult != nil \u0026\u0026 messageResult.Error != nil {\n\t\t\t\t// log any error with messageExpression\n\t\t\t\tklog.V(2).ErrorS(messageResult.Error, \"error while evaluating messageExpression\")\n\t\t\t}\n\t\t\t// fallback to set message to the custom message\n\t\t\tif message == \"\" \u0026\u0026 len(validation.Message) \u003e 0 {\n\t\t\t\tmessage = strings.TrimSpace(validation.Message)\n\t\t\t}\n\t\t\t// fallback to use the expression to compose a message\n\t\t\tif message == \"\" {\n\t\t\t\tmessage = fmt.Sprintf(\"failed expression: %v\", strings.TrimSpace(validation.Expression))\n\t\t\t}\n\t\t\tdecision.Message = message\n\t\t} else {\n\t\t\tdecision.Action = ActionAdmit\n\t\t\tdecision.Evaluation = EvalAdmit\n\t\t}\n\t}\n\n\toptions := cel.OptionalVariableBindings{VersionedParams: versionedParams}\n\tauditAnnotationEvalResults, _, err := v.auditAnnotationFilter.ForInput(ctx, versionedAttr, cel.CreateAdmissionRequest(versionedAttr.Attributes), options, runtimeCELCostBudget)\n\tif err != nil {\n\t\treturn ValidateResult{\n\t\t\tDecisions: []PolicyDecision{\n\t\t\t\t{\n\t\t\t\t\tAction: policyDecisionActionForError(f),\n\t\t\t\t\tEvaluation: EvalError,\n\t\t\t\t\tMessage: err.Error(),\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\tauditAnnotationResults := make([]PolicyAuditAnnotation, len(auditAnnotationEvalResults))\n\tfor i, evalResult := range auditAnnotationEvalResults {\n\t\tif evalResult.ExpressionAccessor == nil {\n\t\t\tcontinue\n\t\t}\n\t\tvar auditAnnotationResult = \u0026auditAnnotationResults[i]\n\t\t// TODO: move this to generics\n\t\tvalidation, ok := evalResult.ExpressionAccessor.(*AuditAnnotationCondition)\n\t\tif !ok {\n\t\t\tklog.Error(\"Invalid type conversion to AuditAnnotationCondition\")\n\t\t\tauditAnnotationResult.Action = auditAnnotationEvaluationForError(f)\n\t\t\tauditAnnotationResult.Error = fmt.Sprintf(\"Invalid type sent to validator, expected AuditAnnotationCondition but got %T\", evalResult.ExpressionAccessor)\n\t\t\tcontinue\n\t\t}\n\t\tauditAnnotationResult.Key = validation.Key\n\n\t\tif evalResult.Error != nil {\n\t\t\tauditAnnotationResult.Action = auditAnnotationEvaluationForError(f)\n\t\t\tauditAnnotationResult.Error = evalResult.Error.Error()\n\t\t} else {\n\t\t\tswitch evalResult.EvalResult.Type() {\n\t\t\tcase celtypes.StringType:\n\t\t\t\tvalue := strings.TrimSpace(evalResult.EvalResult.Value().(string))\n\t\t\t\tif len(value) == 0 {\n\t\t\t\t\tauditAnnotationResult.Action = AuditAnnotationActionExclude\n\t\t\t\t} else {\n\t\t\t\t\tauditAnnotationResult.Action = AuditAnnotationActionPublish\n\t\t\t\t\tauditAnnotationResult.Value = value\n\t\t\t\t}\n\t\t\tcase celtypes.NullType:\n\t\t\t\tauditAnnotationResult.Action = AuditAnnotationActionExclude\n\t\t\tdefault:\n\t\t\t\tauditAnnotationResult.Action = AuditAnnotationActionError\n\t\t\t\tauditAnnotationResult.Error = fmt.Sprintf(\"valueExpression '%v' resulted in unsupported return type: %v. \"+\n\t\t\t\t\t\"Return type must be either string or null.\", validation.ValueExpression, evalResult.EvalResult.Type())\n\t\t\t}\n\t\t}\n\t}\n\treturn ValidateResult{Decisions: decisions, AuditAnnotations: auditAnnotationResults}\n}","line":{"from":73,"to":248}} {"id":100016670,"name":"NewMutatingWebhookAccessor","signature":"func NewMutatingWebhookAccessor(uid, configurationName string, h *v1.MutatingWebhook) WebhookAccessor","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"// NewMutatingWebhookAccessor creates an accessor for a MutatingWebhook.\nfunc NewMutatingWebhookAccessor(uid, configurationName string, h *v1.MutatingWebhook) WebhookAccessor {\n\treturn \u0026mutatingWebhookAccessor{uid: uid, configurationName: configurationName, MutatingWebhook: h}\n}","line":{"from":86,"to":89}} {"id":100016671,"name":"GetUID","signature":"func (m *mutatingWebhookAccessor) GetUID() string","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (m *mutatingWebhookAccessor) GetUID() string {\n\treturn m.uid\n}","line":{"from":112,"to":114}} {"id":100016672,"name":"GetConfigurationName","signature":"func (m *mutatingWebhookAccessor) GetConfigurationName() string","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (m *mutatingWebhookAccessor) GetConfigurationName() string {\n\treturn m.configurationName\n}","line":{"from":116,"to":118}} {"id":100016673,"name":"GetRESTClient","signature":"func (m *mutatingWebhookAccessor) GetRESTClient(clientManager *webhookutil.ClientManager) (*rest.RESTClient, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (m *mutatingWebhookAccessor) GetRESTClient(clientManager *webhookutil.ClientManager) (*rest.RESTClient, error) {\n\tm.initClient.Do(func() {\n\t\tm.client, m.clientErr = clientManager.HookClient(hookClientConfigForWebhook(m))\n\t})\n\treturn m.client, m.clientErr\n}","line":{"from":120,"to":125}} {"id":100016674,"name":"GetCompiledMatcher","signature":"func (m *mutatingWebhookAccessor) GetCompiledMatcher(compiler cel.FilterCompiler, authorizer authorizer.Authorizer) matchconditions.Matcher","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"// TODO: graduation to beta: resolve the fact that we rebuild ALL items whenever ANY config changes in NewMutatingWebhookConfigurationManager and NewValidatingWebhookConfigurationManager ... now that we're doing CEL compilation, we probably want to avoid that\nfunc (m *mutatingWebhookAccessor) GetCompiledMatcher(compiler cel.FilterCompiler, authorizer authorizer.Authorizer) matchconditions.Matcher {\n\tm.compileMatcher.Do(func() {\n\t\texpressions := make([]cel.ExpressionAccessor, len(m.MutatingWebhook.MatchConditions))\n\t\tfor i, matchCondition := range m.MutatingWebhook.MatchConditions {\n\t\t\texpressions[i] = \u0026matchconditions.MatchCondition{\n\t\t\t\tName: matchCondition.Name,\n\t\t\t\tExpression: matchCondition.Expression,\n\t\t\t}\n\t\t}\n\t\tm.compiledMatcher = matchconditions.NewMatcher(compiler.Compile(\n\t\t\texpressions,\n\t\t\tcel.OptionalVariableDeclarations{\n\t\t\t\tHasParams: false,\n\t\t\t\tHasAuthorizer: true,\n\t\t\t},\n\t\t\tcelconfig.PerCallLimit,\n\t\t), authorizer, m.FailurePolicy, \"validating\", m.Name)\n\t})\n\treturn m.compiledMatcher\n}","line":{"from":127,"to":147}} {"id":100016675,"name":"GetParsedNamespaceSelector","signature":"func (m *mutatingWebhookAccessor) GetParsedNamespaceSelector() (labels.Selector, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (m *mutatingWebhookAccessor) GetParsedNamespaceSelector() (labels.Selector, error) {\n\tm.initNamespaceSelector.Do(func() {\n\t\tm.namespaceSelector, m.namespaceSelectorErr = metav1.LabelSelectorAsSelector(m.NamespaceSelector)\n\t})\n\treturn m.namespaceSelector, m.namespaceSelectorErr\n}","line":{"from":149,"to":154}} {"id":100016676,"name":"GetParsedObjectSelector","signature":"func (m *mutatingWebhookAccessor) GetParsedObjectSelector() (labels.Selector, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (m *mutatingWebhookAccessor) GetParsedObjectSelector() (labels.Selector, error) {\n\tm.initObjectSelector.Do(func() {\n\t\tm.objectSelector, m.objectSelectorErr = metav1.LabelSelectorAsSelector(m.ObjectSelector)\n\t})\n\treturn m.objectSelector, m.objectSelectorErr\n}","line":{"from":156,"to":161}} {"id":100016677,"name":"GetName","signature":"func (m *mutatingWebhookAccessor) GetName() string","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (m *mutatingWebhookAccessor) GetName() string {\n\treturn m.Name\n}","line":{"from":163,"to":165}} {"id":100016678,"name":"GetClientConfig","signature":"func (m *mutatingWebhookAccessor) GetClientConfig() v1.WebhookClientConfig","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (m *mutatingWebhookAccessor) GetClientConfig() v1.WebhookClientConfig {\n\treturn m.ClientConfig\n}","line":{"from":167,"to":169}} {"id":100016679,"name":"GetRules","signature":"func (m *mutatingWebhookAccessor) GetRules() []v1.RuleWithOperations","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (m *mutatingWebhookAccessor) GetRules() []v1.RuleWithOperations {\n\treturn m.Rules\n}","line":{"from":171,"to":173}} {"id":100016680,"name":"GetFailurePolicy","signature":"func (m *mutatingWebhookAccessor) GetFailurePolicy() *v1.FailurePolicyType","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (m *mutatingWebhookAccessor) GetFailurePolicy() *v1.FailurePolicyType {\n\treturn m.FailurePolicy\n}","line":{"from":175,"to":177}} {"id":100016681,"name":"GetMatchPolicy","signature":"func (m *mutatingWebhookAccessor) GetMatchPolicy() *v1.MatchPolicyType","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (m *mutatingWebhookAccessor) GetMatchPolicy() *v1.MatchPolicyType {\n\treturn m.MatchPolicy\n}","line":{"from":179,"to":181}} {"id":100016682,"name":"GetNamespaceSelector","signature":"func (m *mutatingWebhookAccessor) GetNamespaceSelector() *metav1.LabelSelector","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (m *mutatingWebhookAccessor) GetNamespaceSelector() *metav1.LabelSelector {\n\treturn m.NamespaceSelector\n}","line":{"from":183,"to":185}} {"id":100016683,"name":"GetObjectSelector","signature":"func (m *mutatingWebhookAccessor) GetObjectSelector() *metav1.LabelSelector","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (m *mutatingWebhookAccessor) GetObjectSelector() *metav1.LabelSelector {\n\treturn m.ObjectSelector\n}","line":{"from":187,"to":189}} {"id":100016684,"name":"GetSideEffects","signature":"func (m *mutatingWebhookAccessor) GetSideEffects() *v1.SideEffectClass","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (m *mutatingWebhookAccessor) GetSideEffects() *v1.SideEffectClass {\n\treturn m.SideEffects\n}","line":{"from":191,"to":193}} {"id":100016685,"name":"GetTimeoutSeconds","signature":"func (m *mutatingWebhookAccessor) GetTimeoutSeconds() *int32","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (m *mutatingWebhookAccessor) GetTimeoutSeconds() *int32 {\n\treturn m.TimeoutSeconds\n}","line":{"from":195,"to":197}} {"id":100016686,"name":"GetAdmissionReviewVersions","signature":"func (m *mutatingWebhookAccessor) GetAdmissionReviewVersions() []string","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (m *mutatingWebhookAccessor) GetAdmissionReviewVersions() []string {\n\treturn m.AdmissionReviewVersions\n}","line":{"from":199,"to":201}} {"id":100016687,"name":"GetMatchConditions","signature":"func (m *mutatingWebhookAccessor) GetMatchConditions() []v1.MatchCondition","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (m *mutatingWebhookAccessor) GetMatchConditions() []v1.MatchCondition {\n\treturn m.MatchConditions\n}","line":{"from":203,"to":205}} {"id":100016688,"name":"GetMutatingWebhook","signature":"func (m *mutatingWebhookAccessor) GetMutatingWebhook() (*v1.MutatingWebhook, bool)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (m *mutatingWebhookAccessor) GetMutatingWebhook() (*v1.MutatingWebhook, bool) {\n\treturn m.MutatingWebhook, true\n}","line":{"from":207,"to":209}} {"id":100016689,"name":"GetValidatingWebhook","signature":"func (m *mutatingWebhookAccessor) GetValidatingWebhook() (*v1.ValidatingWebhook, bool)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (m *mutatingWebhookAccessor) GetValidatingWebhook() (*v1.ValidatingWebhook, bool) {\n\treturn nil, false\n}","line":{"from":211,"to":213}} {"id":100016690,"name":"NewValidatingWebhookAccessor","signature":"func NewValidatingWebhookAccessor(uid, configurationName string, h *v1.ValidatingWebhook) WebhookAccessor","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"// NewValidatingWebhookAccessor creates an accessor for a ValidatingWebhook.\nfunc NewValidatingWebhookAccessor(uid, configurationName string, h *v1.ValidatingWebhook) WebhookAccessor {\n\treturn \u0026validatingWebhookAccessor{uid: uid, configurationName: configurationName, ValidatingWebhook: h}\n}","line":{"from":215,"to":218}} {"id":100016691,"name":"GetUID","signature":"func (v *validatingWebhookAccessor) GetUID() string","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (v *validatingWebhookAccessor) GetUID() string {\n\treturn v.uid\n}","line":{"from":241,"to":243}} {"id":100016692,"name":"GetConfigurationName","signature":"func (v *validatingWebhookAccessor) GetConfigurationName() string","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (v *validatingWebhookAccessor) GetConfigurationName() string {\n\treturn v.configurationName\n}","line":{"from":245,"to":247}} {"id":100016693,"name":"GetRESTClient","signature":"func (v *validatingWebhookAccessor) GetRESTClient(clientManager *webhookutil.ClientManager) (*rest.RESTClient, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (v *validatingWebhookAccessor) GetRESTClient(clientManager *webhookutil.ClientManager) (*rest.RESTClient, error) {\n\tv.initClient.Do(func() {\n\t\tv.client, v.clientErr = clientManager.HookClient(hookClientConfigForWebhook(v))\n\t})\n\treturn v.client, v.clientErr\n}","line":{"from":249,"to":254}} {"id":100016694,"name":"GetCompiledMatcher","signature":"func (v *validatingWebhookAccessor) GetCompiledMatcher(compiler cel.FilterCompiler, authorizer authorizer.Authorizer) matchconditions.Matcher","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (v *validatingWebhookAccessor) GetCompiledMatcher(compiler cel.FilterCompiler, authorizer authorizer.Authorizer) matchconditions.Matcher {\n\tv.compileMatcher.Do(func() {\n\t\texpressions := make([]cel.ExpressionAccessor, len(v.ValidatingWebhook.MatchConditions))\n\t\tfor i, matchCondition := range v.ValidatingWebhook.MatchConditions {\n\t\t\texpressions[i] = \u0026matchconditions.MatchCondition{\n\t\t\t\tName: matchCondition.Name,\n\t\t\t\tExpression: matchCondition.Expression,\n\t\t\t}\n\t\t}\n\t\tv.compiledMatcher = matchconditions.NewMatcher(compiler.Compile(\n\t\t\texpressions,\n\t\t\tcel.OptionalVariableDeclarations{\n\t\t\t\tHasParams: false,\n\t\t\t\tHasAuthorizer: true,\n\t\t\t},\n\t\t\tcelconfig.PerCallLimit,\n\t\t), authorizer, v.FailurePolicy, \"validating\", v.Name)\n\t})\n\treturn v.compiledMatcher\n}","line":{"from":256,"to":275}} {"id":100016695,"name":"GetParsedNamespaceSelector","signature":"func (v *validatingWebhookAccessor) GetParsedNamespaceSelector() (labels.Selector, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (v *validatingWebhookAccessor) GetParsedNamespaceSelector() (labels.Selector, error) {\n\tv.initNamespaceSelector.Do(func() {\n\t\tv.namespaceSelector, v.namespaceSelectorErr = metav1.LabelSelectorAsSelector(v.NamespaceSelector)\n\t})\n\treturn v.namespaceSelector, v.namespaceSelectorErr\n}","line":{"from":277,"to":282}} {"id":100016696,"name":"GetParsedObjectSelector","signature":"func (v *validatingWebhookAccessor) GetParsedObjectSelector() (labels.Selector, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (v *validatingWebhookAccessor) GetParsedObjectSelector() (labels.Selector, error) {\n\tv.initObjectSelector.Do(func() {\n\t\tv.objectSelector, v.objectSelectorErr = metav1.LabelSelectorAsSelector(v.ObjectSelector)\n\t})\n\treturn v.objectSelector, v.objectSelectorErr\n}","line":{"from":284,"to":289}} {"id":100016697,"name":"GetName","signature":"func (v *validatingWebhookAccessor) GetName() string","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (v *validatingWebhookAccessor) GetName() string {\n\treturn v.Name\n}","line":{"from":291,"to":293}} {"id":100016698,"name":"GetClientConfig","signature":"func (v *validatingWebhookAccessor) GetClientConfig() v1.WebhookClientConfig","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (v *validatingWebhookAccessor) GetClientConfig() v1.WebhookClientConfig {\n\treturn v.ClientConfig\n}","line":{"from":295,"to":297}} {"id":100016699,"name":"GetRules","signature":"func (v *validatingWebhookAccessor) GetRules() []v1.RuleWithOperations","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (v *validatingWebhookAccessor) GetRules() []v1.RuleWithOperations {\n\treturn v.Rules\n}","line":{"from":299,"to":301}} {"id":100016700,"name":"GetFailurePolicy","signature":"func (v *validatingWebhookAccessor) GetFailurePolicy() *v1.FailurePolicyType","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (v *validatingWebhookAccessor) GetFailurePolicy() *v1.FailurePolicyType {\n\treturn v.FailurePolicy\n}","line":{"from":303,"to":305}} {"id":100016701,"name":"GetMatchPolicy","signature":"func (v *validatingWebhookAccessor) GetMatchPolicy() *v1.MatchPolicyType","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (v *validatingWebhookAccessor) GetMatchPolicy() *v1.MatchPolicyType {\n\treturn v.MatchPolicy\n}","line":{"from":307,"to":309}} {"id":100016702,"name":"GetNamespaceSelector","signature":"func (v *validatingWebhookAccessor) GetNamespaceSelector() *metav1.LabelSelector","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (v *validatingWebhookAccessor) GetNamespaceSelector() *metav1.LabelSelector {\n\treturn v.NamespaceSelector\n}","line":{"from":311,"to":313}} {"id":100016703,"name":"GetObjectSelector","signature":"func (v *validatingWebhookAccessor) GetObjectSelector() *metav1.LabelSelector","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (v *validatingWebhookAccessor) GetObjectSelector() *metav1.LabelSelector {\n\treturn v.ObjectSelector\n}","line":{"from":315,"to":317}} {"id":100016704,"name":"GetSideEffects","signature":"func (v *validatingWebhookAccessor) GetSideEffects() *v1.SideEffectClass","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (v *validatingWebhookAccessor) GetSideEffects() *v1.SideEffectClass {\n\treturn v.SideEffects\n}","line":{"from":319,"to":321}} {"id":100016705,"name":"GetTimeoutSeconds","signature":"func (v *validatingWebhookAccessor) GetTimeoutSeconds() *int32","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (v *validatingWebhookAccessor) GetTimeoutSeconds() *int32 {\n\treturn v.TimeoutSeconds\n}","line":{"from":323,"to":325}} {"id":100016706,"name":"GetAdmissionReviewVersions","signature":"func (v *validatingWebhookAccessor) GetAdmissionReviewVersions() []string","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (v *validatingWebhookAccessor) GetAdmissionReviewVersions() []string {\n\treturn v.AdmissionReviewVersions\n}","line":{"from":327,"to":329}} {"id":100016707,"name":"GetMatchConditions","signature":"func (v *validatingWebhookAccessor) GetMatchConditions() []v1.MatchCondition","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (v *validatingWebhookAccessor) GetMatchConditions() []v1.MatchCondition {\n\treturn v.MatchConditions\n}","line":{"from":331,"to":333}} {"id":100016708,"name":"GetMutatingWebhook","signature":"func (v *validatingWebhookAccessor) GetMutatingWebhook() (*v1.MutatingWebhook, bool)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (v *validatingWebhookAccessor) GetMutatingWebhook() (*v1.MutatingWebhook, bool) {\n\treturn nil, false\n}","line":{"from":335,"to":337}} {"id":100016709,"name":"GetValidatingWebhook","signature":"func (v *validatingWebhookAccessor) GetValidatingWebhook() (*v1.ValidatingWebhook, bool)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"func (v *validatingWebhookAccessor) GetValidatingWebhook() (*v1.ValidatingWebhook, bool) {\n\treturn v.ValidatingWebhook, true\n}","line":{"from":339,"to":341}} {"id":100016710,"name":"hookClientConfigForWebhook","signature":"func hookClientConfigForWebhook(w WebhookAccessor) webhookutil.ClientConfig","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/accessors.go","code":"// hookClientConfigForWebhook construct a webhookutil.ClientConfig using a WebhookAccessor to access\n// v1beta1.MutatingWebhook and v1beta1.ValidatingWebhook API objects. webhookutil.ClientConfig is used\n// to create a HookClient and the purpose of the config struct is to share that with other packages\n// that need to create a HookClient.\nfunc hookClientConfigForWebhook(w WebhookAccessor) webhookutil.ClientConfig {\n\tret := webhookutil.ClientConfig{Name: w.GetName(), CABundle: w.GetClientConfig().CABundle}\n\tif w.GetClientConfig().URL != nil {\n\t\tret.URL = *w.GetClientConfig().URL\n\t}\n\tif w.GetClientConfig().Service != nil {\n\t\tret.Service = \u0026webhookutil.ClientConfigService{\n\t\t\tName: w.GetClientConfig().Service.Name,\n\t\t\tNamespace: w.GetClientConfig().Service.Namespace,\n\t\t}\n\t\tif w.GetClientConfig().Service.Port != nil {\n\t\t\tret.Service.Port = *w.GetClientConfig().Service.Port\n\t\t} else {\n\t\t\tret.Service.Port = 443\n\t\t}\n\t\tif w.GetClientConfig().Service.Path != nil {\n\t\t\tret.Service.Path = *w.GetClientConfig().Service.Path\n\t\t}\n\t}\n\treturn ret\n}","line":{"from":343,"to":367}} {"id":100016711,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/config/apis/webhookadmission/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(webhookadmission.AddToScheme(scheme))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(v1alpha1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1.SchemeGroupVersion, v1alpha1.SchemeGroupVersion))\n}","line":{"from":29,"to":35}} {"id":100016712,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/config/apis/webhookadmission/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":35,"to":38}} {"id":100016713,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/config/apis/webhookadmission/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":40,"to":43}} {"id":100016714,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/config/apis/webhookadmission/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026WebhookAdmission{},\n\t)\n\tscheme.AddKnownTypeWithName(SchemeGroupVersion.WithKind(\"WebhookAdmissionConfiguration\"),\n\t\t\u0026WebhookAdmission{},\n\t)\n\treturn nil\n}","line":{"from":45,"to":53}} {"id":100016715,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/config/apis/webhookadmission/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addKnownTypes)\n}","line":{"from":38,"to":43}} {"id":100016716,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/config/apis/webhookadmission/v1/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypeWithName(SchemeGroupVersion.WithKind(\"WebhookAdmissionConfiguration\"),\n\t\t\u0026WebhookAdmission{},\n\t)\n\treturn nil\n}","line":{"from":45,"to":50}} {"id":100016717,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/config/apis/webhookadmission/v1alpha1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addKnownTypes)\n}","line":{"from":38,"to":43}} {"id":100016718,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/config/apis/webhookadmission/v1alpha1/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026WebhookAdmission{},\n\t)\n\treturn nil\n}","line":{"from":45,"to":50}} {"id":100016719,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/config/kubeconfig.go","code":"func init() {\n\tutilruntime.Must(webhookadmission.AddToScheme(scheme))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(v1alpha1.AddToScheme(scheme))\n}","line":{"from":39,"to":43}} {"id":100016720,"name":"LoadConfig","signature":"func LoadConfig(configFile io.Reader) (string, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/config/kubeconfig.go","code":"// LoadConfig extract the KubeConfigFile from configFile\nfunc LoadConfig(configFile io.Reader) (string, error) {\n\tvar kubeconfigFile string\n\tif configFile != nil {\n\t\t// we have a config so parse it.\n\t\tdata, err := ioutil.ReadAll(configFile)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tdecoder := codecs.UniversalDecoder()\n\t\tdecodedObj, err := runtime.Decode(decoder, data)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tconfig, ok := decodedObj.(*webhookadmission.WebhookAdmission)\n\t\tif !ok {\n\t\t\treturn \"\", fmt.Errorf(\"unexpected type: %T\", decodedObj)\n\t\t}\n\n\t\tif !path.IsAbs(config.KubeConfigFile) {\n\t\t\treturn \"\", field.Invalid(field.NewPath(\"kubeConfigFile\"), config.KubeConfigFile, \"must be an absolute file path\")\n\t\t}\n\n\t\tkubeconfigFile = config.KubeConfigFile\n\t}\n\treturn kubeconfigFile, nil\n}","line":{"from":45,"to":71}} {"id":100016721,"name":"ToStatusErr","signature":"func ToStatusErr(webhookName string, result *metav1.Status) *apierrors.StatusError","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/errors/statuserror.go","code":"// ToStatusErr returns a StatusError with information about the webhook plugin\nfunc ToStatusErr(webhookName string, result *metav1.Status) *apierrors.StatusError {\n\tdeniedBy := fmt.Sprintf(\"admission webhook %q denied the request\", webhookName)\n\tconst noExp = \"without explanation\"\n\n\tif result == nil {\n\t\tresult = \u0026metav1.Status{Status: metav1.StatusFailure}\n\t}\n\n\t// Make sure we don't return \u003c 400 status codes along with a rejection\n\tif result.Code \u003c http.StatusBadRequest {\n\t\tresult.Code = http.StatusBadRequest\n\t}\n\t// Make sure we don't return \"\" or \"Success\" status along with a rejection\n\tif result.Status == \"\" || result.Status == metav1.StatusSuccess {\n\t\tresult.Status = metav1.StatusFailure\n\t}\n\n\tswitch {\n\tcase len(result.Message) \u003e 0:\n\t\tresult.Message = fmt.Sprintf(\"%s: %s\", deniedBy, result.Message)\n\tcase len(result.Reason) \u003e 0:\n\t\tresult.Message = fmt.Sprintf(\"%s: %s\", deniedBy, result.Reason)\n\tdefault:\n\t\tresult.Message = fmt.Sprintf(\"%s %s\", deniedBy, noExp)\n\t}\n\n\treturn \u0026apierrors.StatusError{\n\t\tErrStatus: *result,\n\t}\n}","line":{"from":27,"to":57}} {"id":100016722,"name":"NewDryRunUnsupportedErr","signature":"func NewDryRunUnsupportedErr(webhookName string) *apierrors.StatusError","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/errors/statuserror.go","code":"// NewDryRunUnsupportedErr returns a StatusError with information about the webhook plugin\nfunc NewDryRunUnsupportedErr(webhookName string) *apierrors.StatusError {\n\treason := fmt.Sprintf(\"admission webhook %q does not support dry run\", webhookName)\n\treturn apierrors.NewBadRequest(reason)\n}","line":{"from":59,"to":63}} {"id":100016723,"name":"NewWebhook","signature":"func NewWebhook(handler *admission.Handler, configFile io.Reader, sourceFactory sourceFactory, dispatcherFactory dispatcherFactory) (*Webhook, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/generic/webhook.go","code":"// NewWebhook creates a new generic admission webhook.\nfunc NewWebhook(handler *admission.Handler, configFile io.Reader, sourceFactory sourceFactory, dispatcherFactory dispatcherFactory) (*Webhook, error) {\n\tkubeconfigFile, err := config.LoadConfig(configFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcm, err := webhookutil.NewClientManager(\n\t\t[]schema.GroupVersion{\n\t\t\tadmissionv1beta1.SchemeGroupVersion,\n\t\t\tadmissionv1.SchemeGroupVersion,\n\t\t},\n\t\tadmissionv1beta1.AddToScheme,\n\t\tadmissionv1.AddToScheme,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tauthInfoResolver, err := webhookutil.NewDefaultAuthenticationInfoResolver(kubeconfigFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Set defaults which may be overridden later.\n\tcm.SetAuthenticationInfoResolver(authInfoResolver)\n\tcm.SetServiceResolver(webhookutil.NewDefaultServiceResolver())\n\n\treturn \u0026Webhook{\n\t\tHandler: handler,\n\t\tsourceFactory: sourceFactory,\n\t\tclientManager: \u0026cm,\n\t\tnamespaceMatcher: \u0026namespace.Matcher{},\n\t\tobjectMatcher: \u0026object.Matcher{},\n\t\tdispatcher: dispatcherFactory(\u0026cm),\n\t\tfilterCompiler: cel.NewFilterCompiler(),\n\t}, nil\n}","line":{"from":67,"to":102}} {"id":100016724,"name":"SetAuthenticationInfoResolverWrapper","signature":"func (a *Webhook) SetAuthenticationInfoResolverWrapper(wrapper webhookutil.AuthenticationInfoResolverWrapper)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/generic/webhook.go","code":"// SetAuthenticationInfoResolverWrapper sets the\n// AuthenticationInfoResolverWrapper.\n// TODO find a better way wire this, but keep this pull small for now.\nfunc (a *Webhook) SetAuthenticationInfoResolverWrapper(wrapper webhookutil.AuthenticationInfoResolverWrapper) {\n\ta.clientManager.SetAuthenticationInfoResolverWrapper(wrapper)\n}","line":{"from":104,"to":109}} {"id":100016725,"name":"SetServiceResolver","signature":"func (a *Webhook) SetServiceResolver(sr webhookutil.ServiceResolver)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/generic/webhook.go","code":"// SetServiceResolver sets a service resolver for the webhook admission plugin.\n// Passing a nil resolver does not have an effect, instead a default one will be used.\nfunc (a *Webhook) SetServiceResolver(sr webhookutil.ServiceResolver) {\n\ta.clientManager.SetServiceResolver(sr)\n}","line":{"from":111,"to":115}} {"id":100016726,"name":"SetExternalKubeClientSet","signature":"func (a *Webhook) SetExternalKubeClientSet(client clientset.Interface)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/generic/webhook.go","code":"// SetExternalKubeClientSet implements the WantsExternalKubeInformerFactory interface.\n// It sets external ClientSet for admission plugins that need it\nfunc (a *Webhook) SetExternalKubeClientSet(client clientset.Interface) {\n\ta.namespaceMatcher.Client = client\n}","line":{"from":117,"to":121}} {"id":100016727,"name":"SetExternalKubeInformerFactory","signature":"func (a *Webhook) SetExternalKubeInformerFactory(f informers.SharedInformerFactory)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/generic/webhook.go","code":"// SetExternalKubeInformerFactory implements the WantsExternalKubeInformerFactory interface.\nfunc (a *Webhook) SetExternalKubeInformerFactory(f informers.SharedInformerFactory) {\n\tnamespaceInformer := f.Core().V1().Namespaces()\n\ta.namespaceMatcher.NamespaceLister = namespaceInformer.Lister()\n\ta.hookSource = a.sourceFactory(f)\n\ta.SetReadyFunc(func() bool {\n\t\treturn namespaceInformer.Informer().HasSynced() \u0026\u0026 a.hookSource.HasSynced()\n\t})\n}","line":{"from":123,"to":131}} {"id":100016728,"name":"SetAuthorizer","signature":"func (a *Webhook) SetAuthorizer(authorizer authorizer.Authorizer)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/generic/webhook.go","code":"func (a *Webhook) SetAuthorizer(authorizer authorizer.Authorizer) {\n\ta.authorizer = authorizer\n}","line":{"from":133,"to":135}} {"id":100016729,"name":"ValidateInitialization","signature":"func (a *Webhook) ValidateInitialization() error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/generic/webhook.go","code":"// ValidateInitialization implements the InitializationValidator interface.\nfunc (a *Webhook) ValidateInitialization() error {\n\tif a.hookSource == nil {\n\t\treturn fmt.Errorf(\"kubernetes client is not properly setup\")\n\t}\n\tif err := a.namespaceMatcher.Validate(); err != nil {\n\t\treturn fmt.Errorf(\"namespaceMatcher is not properly setup: %v\", err)\n\t}\n\tif err := a.clientManager.Validate(); err != nil {\n\t\treturn fmt.Errorf(\"clientManager is not properly setup: %v\", err)\n\t}\n\treturn nil\n}","line":{"from":137,"to":149}} {"id":100016730,"name":"ShouldCallHook","signature":"func (a *Webhook) ShouldCallHook(ctx context.Context, h webhook.WebhookAccessor, attr admission.Attributes, o admission.ObjectInterfaces, v VersionedAttributeAccessor) (*WebhookInvocation, *apierrors.StatusError)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/generic/webhook.go","code":"// ShouldCallHook returns invocation details if the webhook should be called, nil if the webhook should not be called,\n// or an error if an error was encountered during evaluation.\nfunc (a *Webhook) ShouldCallHook(ctx context.Context, h webhook.WebhookAccessor, attr admission.Attributes, o admission.ObjectInterfaces, v VersionedAttributeAccessor) (*WebhookInvocation, *apierrors.StatusError) {\n\tmatches, matchNsErr := a.namespaceMatcher.MatchNamespaceSelector(h, attr)\n\t// Should not return an error here for webhooks which do not apply to the request, even if err is an unexpected scenario.\n\tif !matches \u0026\u0026 matchNsErr == nil {\n\t\treturn nil, nil\n\t}\n\n\t// Should not return an error here for webhooks which do not apply to the request, even if err is an unexpected scenario.\n\tmatches, matchObjErr := a.objectMatcher.MatchObjectSelector(h, attr)\n\tif !matches \u0026\u0026 matchObjErr == nil {\n\t\treturn nil, nil\n\t}\n\n\tvar invocation *WebhookInvocation\n\tfor _, r := range h.GetRules() {\n\t\tm := rules.Matcher{Rule: r, Attr: attr}\n\t\tif m.Matches() {\n\t\t\tinvocation = \u0026WebhookInvocation{\n\t\t\t\tWebhook: h,\n\t\t\t\tResource: attr.GetResource(),\n\t\t\t\tSubresource: attr.GetSubresource(),\n\t\t\t\tKind: attr.GetKind(),\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\tif invocation == nil \u0026\u0026 h.GetMatchPolicy() != nil \u0026\u0026 *h.GetMatchPolicy() == v1.Equivalent {\n\t\tattrWithOverride := \u0026attrWithResourceOverride{Attributes: attr}\n\t\tequivalents := o.GetEquivalentResourceMapper().EquivalentResourcesFor(attr.GetResource(), attr.GetSubresource())\n\t\t// honor earlier rules first\n\tOuterLoop:\n\t\tfor _, r := range h.GetRules() {\n\t\t\t// see if the rule matches any of the equivalent resources\n\t\t\tfor _, equivalent := range equivalents {\n\t\t\t\tif equivalent == attr.GetResource() {\n\t\t\t\t\t// exclude attr.GetResource(), which we already checked\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tattrWithOverride.resource = equivalent\n\t\t\t\tm := rules.Matcher{Rule: r, Attr: attrWithOverride}\n\t\t\t\tif m.Matches() {\n\t\t\t\t\tkind := o.GetEquivalentResourceMapper().KindFor(equivalent, attr.GetSubresource())\n\t\t\t\t\tif kind.Empty() {\n\t\t\t\t\t\treturn nil, apierrors.NewInternalError(fmt.Errorf(\"unable to convert to %v: unknown kind\", equivalent))\n\t\t\t\t\t}\n\t\t\t\t\tinvocation = \u0026WebhookInvocation{\n\t\t\t\t\t\tWebhook: h,\n\t\t\t\t\t\tResource: equivalent,\n\t\t\t\t\t\tSubresource: attr.GetSubresource(),\n\t\t\t\t\t\tKind: kind,\n\t\t\t\t\t}\n\t\t\t\t\tbreak OuterLoop\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif invocation == nil {\n\t\treturn nil, nil\n\t}\n\tif matchNsErr != nil {\n\t\treturn nil, matchNsErr\n\t}\n\tif matchObjErr != nil {\n\t\treturn nil, matchObjErr\n\t}\n\n\tmatchConditions := h.GetMatchConditions()\n\tif len(matchConditions) \u003e 0 {\n\t\tversionedAttr, err := v.VersionedAttribute(invocation.Kind)\n\t\tif err != nil {\n\t\t\treturn nil, apierrors.NewInternalError(err)\n\t\t}\n\n\t\tmatcher := h.GetCompiledMatcher(a.filterCompiler, a.authorizer)\n\t\tmatchResult := matcher.Match(ctx, versionedAttr, nil)\n\n\t\tif matchResult.Error != nil {\n\t\t\tklog.Warningf(\"Failed evaluating match conditions, failing closed %v: %v\", h.GetName(), matchResult.Error)\n\t\t\treturn nil, apierrors.NewForbidden(attr.GetResource().GroupResource(), attr.GetName(), matchResult.Error)\n\t\t} else if !matchResult.Matches {\n\t\t\t// if no match, always skip webhook\n\t\t\treturn nil, nil\n\t\t}\n\t}\n\n\treturn invocation, nil\n}","line":{"from":151,"to":240}} {"id":100016731,"name":"GetResource","signature":"func (a *attrWithResourceOverride) GetResource() schema.GroupVersionResource { return a.resource }","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/generic/webhook.go","code":"func (a *attrWithResourceOverride) GetResource() schema.GroupVersionResource { return a.resource }","line":{"from":247,"to":247}} {"id":100016732,"name":"Dispatch","signature":"func (a *Webhook) Dispatch(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/generic/webhook.go","code":"// Dispatch is called by the downstream Validate or Admit methods.\nfunc (a *Webhook) Dispatch(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) error {\n\tif rules.IsExemptAdmissionConfigurationResource(attr) {\n\t\treturn nil\n\t}\n\tif !a.WaitForReady() {\n\t\treturn admission.NewForbidden(attr, fmt.Errorf(\"not yet ready to handle request\"))\n\t}\n\thooks := a.hookSource.Webhooks()\n\treturn a.dispatcher.Dispatch(ctx, attr, o, hooks)\n}","line":{"from":249,"to":259}} {"id":100016733,"name":"NewPluginInitializer","signature":"func NewPluginInitializer(","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/initializer/initializer.go","code":"// NewPluginInitializer constructs new instance of PluginInitializer\nfunc NewPluginInitializer(\n\tauthenticationInfoResolverWrapper webhook.AuthenticationInfoResolverWrapper,\n\tserviceResolver webhook.ServiceResolver,\n) *PluginInitializer {\n\treturn \u0026PluginInitializer{\n\t\tauthenticationInfoResolverWrapper: authenticationInfoResolverWrapper,\n\t\tserviceResolver: serviceResolver,\n\t}\n}","line":{"from":53,"to":62}} {"id":100016734,"name":"Initialize","signature":"func (i *PluginInitializer) Initialize(plugin admission.Interface)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/initializer/initializer.go","code":"// Initialize checks the initialization interfaces implemented by each plugin\n// and provide the appropriate initialization data\nfunc (i *PluginInitializer) Initialize(plugin admission.Interface) {\n\tif wants, ok := plugin.(WantsServiceResolver); ok {\n\t\twants.SetServiceResolver(i.serviceResolver)\n\t}\n\n\tif wants, ok := plugin.(WantsAuthenticationInfoResolverWrapper); ok {\n\t\tif i.authenticationInfoResolverWrapper != nil {\n\t\t\twants.SetAuthenticationInfoResolverWrapper(i.authenticationInfoResolverWrapper)\n\t\t}\n\t}\n}","line":{"from":64,"to":76}} {"id":100016735,"name":"GetExpression","signature":"func (v *MatchCondition) GetExpression() string","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/matchconditions/matcher.go","code":"func (v *MatchCondition) GetExpression() string {\n\treturn v.Expression\n}","line":{"from":43,"to":45}} {"id":100016736,"name":"ReturnTypes","signature":"func (v *MatchCondition) ReturnTypes() []*cel.Type","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/matchconditions/matcher.go","code":"func (v *MatchCondition) ReturnTypes() []*cel.Type {\n\treturn []*cel.Type{cel.BoolType}\n}","line":{"from":47,"to":49}} {"id":100016737,"name":"NewMatcher","signature":"func NewMatcher(filter celplugin.Filter, authorizer authorizer.Authorizer, failPolicy *v1.FailurePolicyType, matcherType, objectName string) Matcher","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/matchconditions/matcher.go","code":"func NewMatcher(filter celplugin.Filter, authorizer authorizer.Authorizer, failPolicy *v1.FailurePolicyType, matcherType, objectName string) Matcher {\n\tvar f v1.FailurePolicyType\n\tif failPolicy == nil {\n\t\tf = v1.Fail\n\t} else {\n\t\tf = *failPolicy\n\t}\n\treturn \u0026matcher{\n\t\tfilter: filter,\n\t\tauthorizer: authorizer,\n\t\tfailPolicy: f,\n\t\tmatcherType: matcherType,\n\t\tobjectName: objectName,\n\t}\n}","line":{"from":62,"to":76}} {"id":100016738,"name":"Match","signature":"func (m *matcher) Match(ctx context.Context, versionedAttr *admission.VersionedAttributes, versionedParams runtime.Object) MatchResult","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/matchconditions/matcher.go","code":"func (m *matcher) Match(ctx context.Context, versionedAttr *admission.VersionedAttributes, versionedParams runtime.Object) MatchResult {\n\tevalResults, _, err := m.filter.ForInput(ctx, versionedAttr, celplugin.CreateAdmissionRequest(versionedAttr.Attributes), celplugin.OptionalVariableBindings{\n\t\tVersionedParams: versionedParams,\n\t\tAuthorizer: m.authorizer,\n\t}, celconfig.RuntimeCELCostBudgetMatchConditions)\n\n\tif err != nil {\n\t\t// filter returning error is unexpected and not an evaluation error so not incrementing metric here\n\t\tif m.failPolicy == v1.Fail {\n\t\t\treturn MatchResult{\n\t\t\t\tError: err,\n\t\t\t}\n\t\t} else if m.failPolicy == v1.Ignore {\n\t\t\treturn MatchResult{\n\t\t\t\tMatches: false,\n\t\t\t}\n\t\t}\n\t\t//TODO: add default so that if in future we add different failure types it doesn't fall through\n\t}\n\n\terrorList := []error{}\n\tfor _, evalResult := range evalResults {\n\t\tmatchCondition, ok := evalResult.ExpressionAccessor.(*MatchCondition)\n\t\tif !ok {\n\t\t\t// This shouldnt happen, but if it does treat same as eval error\n\t\t\tklog.Error(\"Invalid type conversion to MatchCondition\")\n\t\t\terrorList = append(errorList, errors.New(fmt.Sprintf(\"internal error converting ExpressionAccessor to MatchCondition\")))\n\t\t\tcontinue\n\t\t}\n\t\tif evalResult.Error != nil {\n\t\t\terrorList = append(errorList, evalResult.Error)\n\t\t\t//TODO: what's the best way to handle this metric since its reused by VAP for match conditions\n\t\t\tadmissionmetrics.Metrics.ObserveMatchConditionEvalError(ctx, m.objectName, m.matcherType)\n\t\t}\n\t\tif evalResult.EvalResult == celtypes.False {\n\t\t\t// If any condition false, skip calling webhook always\n\t\t\treturn MatchResult{\n\t\t\t\tMatches: false,\n\t\t\t\tFailedConditionName: matchCondition.Name,\n\t\t\t}\n\t\t}\n\t}\n\tif len(errorList) \u003e 0 {\n\t\t// If mix of true and eval errors then resort to fail policy\n\t\tif m.failPolicy == v1.Fail {\n\t\t\t// mix of true and errors with fail policy fail should fail request without calling webhook\n\t\t\terr = utilerrors.NewAggregate(errorList)\n\t\t\treturn MatchResult{\n\t\t\t\tError: err,\n\t\t\t}\n\t\t} else if m.failPolicy == v1.Ignore {\n\t\t\t// if fail policy ignore then skip call to webhook\n\t\t\treturn MatchResult{\n\t\t\t\tMatches: false,\n\t\t\t}\n\t\t}\n\t}\n\t// if no results eval to false, return matches true with list of any errors encountered\n\treturn MatchResult{\n\t\tMatches: true,\n\t}\n}","line":{"from":78,"to":139}} {"id":100016739,"name":"newMutatingDispatcher","signature":"func newMutatingDispatcher(p *Plugin) func(cm *webhookutil.ClientManager) generic.Dispatcher","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/dispatcher.go","code":"func newMutatingDispatcher(p *Plugin) func(cm *webhookutil.ClientManager) generic.Dispatcher {\n\treturn func(cm *webhookutil.ClientManager) generic.Dispatcher {\n\t\treturn \u0026mutatingDispatcher{cm, p}\n\t}\n}","line":{"from":72,"to":76}} {"id":100016740,"name":"VersionedAttribute","signature":"func (v *versionedAttributeAccessor) VersionedAttribute(gvk schema.GroupVersionKind) (*admission.VersionedAttributes, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/dispatcher.go","code":"func (v *versionedAttributeAccessor) VersionedAttribute(gvk schema.GroupVersionKind) (*admission.VersionedAttributes, error) {\n\tif v.versionedAttr == nil {\n\t\t// First call, create versioned attributes\n\t\tvar err error\n\t\tif v.versionedAttr, err = admission.NewVersionedAttributes(v.attr, gvk, v.objectInterfaces); err != nil {\n\t\t\treturn nil, apierrors.NewInternalError(err)\n\t\t}\n\t} else {\n\t\t// Subsequent call, convert existing versioned attributes to the requested version\n\t\tif err := admission.ConvertVersionedAttributes(v.versionedAttr, gvk, v.objectInterfaces); err != nil {\n\t\t\treturn nil, apierrors.NewInternalError(err)\n\t\t}\n\t}\n\treturn v.versionedAttr, nil\n}","line":{"from":86,"to":100}} {"id":100016741,"name":"Dispatch","signature":"func (a *mutatingDispatcher) Dispatch(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces, hooks []webhook.WebhookAccessor) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/dispatcher.go","code":"func (a *mutatingDispatcher) Dispatch(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces, hooks []webhook.WebhookAccessor) error {\n\treinvokeCtx := attr.GetReinvocationContext()\n\tvar webhookReinvokeCtx *webhookReinvokeContext\n\tif v := reinvokeCtx.Value(PluginName); v != nil {\n\t\twebhookReinvokeCtx = v.(*webhookReinvokeContext)\n\t} else {\n\t\twebhookReinvokeCtx = \u0026webhookReinvokeContext{}\n\t\treinvokeCtx.SetValue(PluginName, webhookReinvokeCtx)\n\t}\n\n\tif reinvokeCtx.IsReinvoke() \u0026\u0026 webhookReinvokeCtx.IsOutputChangedSinceLastWebhookInvocation(attr.GetObject()) {\n\t\t// If the object has changed, we know the in-tree plugin re-invocations have mutated the object,\n\t\t// and we need to reinvoke all eligible webhooks.\n\t\twebhookReinvokeCtx.RequireReinvokingPreviouslyInvokedPlugins()\n\t}\n\tdefer func() {\n\t\twebhookReinvokeCtx.SetLastWebhookInvocationOutput(attr.GetObject())\n\t}()\n\tv := \u0026versionedAttributeAccessor{\n\t\tattr: attr,\n\t\tobjectInterfaces: o,\n\t}\n\tfor i, hook := range hooks {\n\t\tattrForCheck := attr\n\t\tif v.versionedAttr != nil {\n\t\t\tattrForCheck = v.versionedAttr\n\t\t}\n\n\t\tinvocation, statusErr := a.plugin.ShouldCallHook(ctx, hook, attrForCheck, o, v)\n\t\tif statusErr != nil {\n\t\t\treturn statusErr\n\t\t}\n\t\tif invocation == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\thook, ok := invocation.Webhook.GetMutatingWebhook()\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"mutating webhook dispatch requires v1.MutatingWebhook, but got %T\", hook)\n\t\t}\n\t\t// This means that during reinvocation, a webhook will not be\n\t\t// called for the first time. For example, if the webhook is\n\t\t// skipped in the first round because of mismatching labels,\n\t\t// even if the labels become matching, the webhook does not\n\t\t// get called during reinvocation.\n\t\tif reinvokeCtx.IsReinvoke() \u0026\u0026 !webhookReinvokeCtx.ShouldReinvokeWebhook(invocation.Webhook.GetUID()) {\n\t\t\tcontinue\n\t\t}\n\n\t\tversionedAttr, err := v.VersionedAttribute(invocation.Kind)\n\t\tif err != nil {\n\t\t\treturn apierrors.NewInternalError(err)\n\t\t}\n\n\t\tt := time.Now()\n\t\tround := 0\n\t\tif reinvokeCtx.IsReinvoke() {\n\t\t\tround = 1\n\t\t}\n\n\t\tannotator := newWebhookAnnotator(versionedAttr, round, i, hook.Name, invocation.Webhook.GetConfigurationName())\n\t\tchanged, err := a.callAttrMutatingHook(ctx, hook, invocation, versionedAttr, annotator, o, round, i)\n\t\tignoreClientCallFailures := hook.FailurePolicy != nil \u0026\u0026 *hook.FailurePolicy == admissionregistrationv1.Ignore\n\t\trejected := false\n\t\tif err != nil {\n\t\t\tswitch err := err.(type) {\n\t\t\tcase *webhookutil.ErrCallingWebhook:\n\t\t\t\tif !ignoreClientCallFailures {\n\t\t\t\t\trejected = true\n\t\t\t\t\tadmissionmetrics.Metrics.ObserveWebhookRejection(ctx, hook.Name, \"admit\", string(versionedAttr.Attributes.GetOperation()), admissionmetrics.WebhookRejectionCallingWebhookError, int(err.Status.ErrStatus.Code))\n\t\t\t\t}\n\t\t\t\tadmissionmetrics.Metrics.ObserveWebhook(ctx, hook.Name, time.Since(t), rejected, versionedAttr.Attributes, \"admit\", int(err.Status.ErrStatus.Code))\n\t\t\tcase *webhookutil.ErrWebhookRejection:\n\t\t\t\trejected = true\n\t\t\t\tadmissionmetrics.Metrics.ObserveWebhookRejection(ctx, hook.Name, \"admit\", string(versionedAttr.Attributes.GetOperation()), admissionmetrics.WebhookRejectionNoError, int(err.Status.ErrStatus.Code))\n\t\t\t\tadmissionmetrics.Metrics.ObserveWebhook(ctx, hook.Name, time.Since(t), rejected, versionedAttr.Attributes, \"admit\", int(err.Status.ErrStatus.Code))\n\t\t\tdefault:\n\t\t\t\trejected = true\n\t\t\t\tadmissionmetrics.Metrics.ObserveWebhookRejection(ctx, hook.Name, \"admit\", string(versionedAttr.Attributes.GetOperation()), admissionmetrics.WebhookRejectionAPIServerInternalError, 0)\n\t\t\t\tadmissionmetrics.Metrics.ObserveWebhook(ctx, hook.Name, time.Since(t), rejected, versionedAttr.Attributes, \"admit\", 0)\n\t\t\t}\n\t\t} else {\n\t\t\tadmissionmetrics.Metrics.ObserveWebhook(ctx, hook.Name, time.Since(t), rejected, versionedAttr.Attributes, \"admit\", 200)\n\t\t}\n\t\tif changed {\n\t\t\t// Patch had changed the object. Prepare to reinvoke all previous webhooks that are eligible for re-invocation.\n\t\t\twebhookReinvokeCtx.RequireReinvokingPreviouslyInvokedPlugins()\n\t\t\treinvokeCtx.SetShouldReinvoke()\n\t\t}\n\t\tif hook.ReinvocationPolicy != nil \u0026\u0026 *hook.ReinvocationPolicy == admissionregistrationv1.IfNeededReinvocationPolicy {\n\t\t\twebhookReinvokeCtx.AddReinvocableWebhookToPreviouslyInvoked(invocation.Webhook.GetUID())\n\t\t}\n\t\tif err == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif callErr, ok := err.(*webhookutil.ErrCallingWebhook); ok {\n\t\t\tif ignoreClientCallFailures {\n\t\t\t\tklog.Warningf(\"Failed calling webhook, failing open %v: %v\", hook.Name, callErr)\n\t\t\t\tadmissionmetrics.Metrics.ObserveWebhookFailOpen(ctx, hook.Name, \"admit\")\n\t\t\t\tannotator.addFailedOpenAnnotation()\n\n\t\t\t\tutilruntime.HandleError(callErr)\n\n\t\t\t\tselect {\n\t\t\t\tcase \u003c-ctx.Done():\n\t\t\t\t\t// parent context is canceled or timed out, no point in continuing\n\t\t\t\t\treturn apierrors.NewTimeoutError(\"request did not complete within requested timeout\", 0)\n\t\t\t\tdefault:\n\t\t\t\t\t// individual webhook timed out, but parent context did not, continue\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tklog.Warningf(\"Failed calling webhook, failing closed %v: %v\", hook.Name, err)\n\t\t\treturn apierrors.NewInternalError(err)\n\t\t}\n\t\tif rejectionErr, ok := err.(*webhookutil.ErrWebhookRejection); ok {\n\t\t\treturn rejectionErr.Status\n\t\t}\n\t\treturn err\n\t}\n\n\t// convert versionedAttr.VersionedObject to the internal version in the underlying admission.Attributes\n\tif v.versionedAttr != nil \u0026\u0026 v.versionedAttr.VersionedObject != nil \u0026\u0026 v.versionedAttr.Dirty {\n\t\treturn o.GetObjectConvertor().Convert(v.versionedAttr.VersionedObject, v.versionedAttr.Attributes.GetObject(), nil)\n\t}\n\n\treturn nil\n}","line":{"from":104,"to":232}} {"id":100016742,"name":"callAttrMutatingHook","signature":"func (a *mutatingDispatcher) callAttrMutatingHook(ctx context.Context, h *admissionregistrationv1.MutatingWebhook, invocation *generic.WebhookInvocation, attr *admission.VersionedAttributes, annotator *webhookAnnotator, o admission.ObjectInterfaces, round, idx int) (bool, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/dispatcher.go","code":"func (a *mutatingDispatcher) callAttrMutatingHook(ctx context.Context, h *admissionregistrationv1.MutatingWebhook, invocation *generic.WebhookInvocation, attr *admission.VersionedAttributes, annotator *webhookAnnotator, o admission.ObjectInterfaces, round, idx int) (bool, error) {\n\tconfigurationName := invocation.Webhook.GetConfigurationName()\n\tchanged := false\n\tdefer func() { annotator.addMutationAnnotation(changed) }()\n\tif attr.Attributes.IsDryRun() {\n\t\tif h.SideEffects == nil {\n\t\t\treturn false, \u0026webhookutil.ErrCallingWebhook{WebhookName: h.Name, Reason: fmt.Errorf(\"Webhook SideEffects is nil\"), Status: apierrors.NewBadRequest(\"Webhook SideEffects is nil\")}\n\t\t}\n\t\tif !(*h.SideEffects == admissionregistrationv1.SideEffectClassNone || *h.SideEffects == admissionregistrationv1.SideEffectClassNoneOnDryRun) {\n\t\t\treturn false, webhookerrors.NewDryRunUnsupportedErr(h.Name)\n\t\t}\n\t}\n\n\tuid, request, response, err := webhookrequest.CreateAdmissionObjects(attr, invocation)\n\tif err != nil {\n\t\treturn false, \u0026webhookutil.ErrCallingWebhook{WebhookName: h.Name, Reason: fmt.Errorf(\"could not create admission objects: %w\", err), Status: apierrors.NewBadRequest(\"error creating admission objects\")}\n\t}\n\t// Make the webhook request\n\tclient, err := invocation.Webhook.GetRESTClient(a.cm)\n\tif err != nil {\n\t\treturn false, \u0026webhookutil.ErrCallingWebhook{WebhookName: h.Name, Reason: fmt.Errorf(\"could not get REST client: %w\", err), Status: apierrors.NewBadRequest(\"error getting REST client\")}\n\t}\n\tctx, span := tracing.Start(ctx, \"Call mutating webhook\",\n\t\tattribute.String(\"configuration\", configurationName),\n\t\tattribute.String(\"webhook\", h.Name),\n\t\tattribute.Stringer(\"resource\", attr.GetResource()),\n\t\tattribute.String(\"subresource\", attr.GetSubresource()),\n\t\tattribute.String(\"operation\", string(attr.GetOperation())),\n\t\tattribute.String(\"UID\", string(uid)))\n\tdefer span.End(500 * time.Millisecond)\n\n\t// if the webhook has a specific timeout, wrap the context to apply it\n\tif h.TimeoutSeconds != nil {\n\t\tvar cancel context.CancelFunc\n\t\tctx, cancel = context.WithTimeout(ctx, time.Duration(*h.TimeoutSeconds)*time.Second)\n\t\tdefer cancel()\n\t}\n\n\tr := client.Post().Body(request)\n\n\t// if the context has a deadline, set it as a parameter to inform the backend\n\tif deadline, hasDeadline := ctx.Deadline(); hasDeadline {\n\t\t// compute the timeout\n\t\tif timeout := time.Until(deadline); timeout \u003e 0 {\n\t\t\t// if it's not an even number of seconds, round up to the nearest second\n\t\t\tif truncated := timeout.Truncate(time.Second); truncated != timeout {\n\t\t\t\ttimeout = truncated + time.Second\n\t\t\t}\n\t\t\t// set the timeout\n\t\t\tr.Timeout(timeout)\n\t\t}\n\t}\n\n\tdo := func() { err = r.Do(ctx).Into(response) }\n\tif wd, ok := endpointsrequest.LatencyTrackersFrom(ctx); ok {\n\t\ttmp := do\n\t\tdo = func() { wd.MutatingWebhookTracker.Track(tmp) }\n\t}\n\tdo()\n\tif err != nil {\n\t\tvar status *apierrors.StatusError\n\t\tif se, ok := err.(*apierrors.StatusError); ok {\n\t\t\tstatus = se\n\t\t} else {\n\t\t\tstatus = apierrors.NewBadRequest(\"error calling webhook\")\n\t\t}\n\t\treturn false, \u0026webhookutil.ErrCallingWebhook{WebhookName: h.Name, Reason: fmt.Errorf(\"failed to call webhook: %w\", err), Status: status}\n\t}\n\tspan.AddEvent(\"Request completed\")\n\n\tresult, err := webhookrequest.VerifyAdmissionResponse(uid, true, response)\n\tif err != nil {\n\t\treturn false, \u0026webhookutil.ErrCallingWebhook{WebhookName: h.Name, Reason: fmt.Errorf(\"received invalid webhook response: %w\", err), Status: apierrors.NewServiceUnavailable(\"error validating webhook response\")}\n\t}\n\n\tfor k, v := range result.AuditAnnotations {\n\t\tkey := h.Name + \"/\" + k\n\t\tif err := attr.Attributes.AddAnnotation(key, v); err != nil {\n\t\t\tklog.Warningf(\"Failed to set admission audit annotation %s to %s for mutating webhook %s: %v\", key, v, h.Name, err)\n\t\t}\n\t}\n\tfor _, w := range result.Warnings {\n\t\twarning.AddWarning(ctx, \"\", w)\n\t}\n\n\tif !result.Allowed {\n\t\treturn false, \u0026webhookutil.ErrWebhookRejection{Status: webhookerrors.ToStatusErr(h.Name, result.Result)}\n\t}\n\n\tif len(result.Patch) == 0 {\n\t\treturn false, nil\n\t}\n\tpatchObj, err := jsonpatch.DecodePatch(result.Patch)\n\tif err != nil {\n\t\treturn false, apierrors.NewInternalError(err)\n\t}\n\n\tif len(patchObj) == 0 {\n\t\treturn false, nil\n\t}\n\n\t// if a non-empty patch was provided, and we have no object we can apply it to (e.g. a DELETE admission operation), error\n\tif attr.VersionedObject == nil {\n\t\treturn false, apierrors.NewInternalError(fmt.Errorf(\"admission webhook %q attempted to modify the object, which is not supported for this operation\", h.Name))\n\t}\n\n\tvar patchedJS []byte\n\tjsonSerializer := json.NewSerializer(json.DefaultMetaFactory, o.GetObjectCreater(), o.GetObjectTyper(), false)\n\tswitch result.PatchType {\n\t// VerifyAdmissionResponse normalizes to v1 patch types, regardless of the AdmissionReview version used\n\tcase admissionv1.PatchTypeJSONPatch:\n\t\tobjJS, err := runtime.Encode(jsonSerializer, attr.VersionedObject)\n\t\tif err != nil {\n\t\t\treturn false, apierrors.NewInternalError(err)\n\t\t}\n\t\tpatchedJS, err = patchObj.Apply(objJS)\n\t\tif err != nil {\n\t\t\treturn false, apierrors.NewInternalError(err)\n\t\t}\n\tdefault:\n\t\treturn false, \u0026webhookutil.ErrCallingWebhook{WebhookName: h.Name, Reason: fmt.Errorf(\"unsupported patch type %q\", result.PatchType), Status: webhookerrors.ToStatusErr(h.Name, result.Result)}\n\t}\n\n\tvar newVersionedObject runtime.Object\n\tif _, ok := attr.VersionedObject.(*unstructured.Unstructured); ok {\n\t\t// Custom Resources don't have corresponding Go struct's.\n\t\t// They are represented as Unstructured.\n\t\tnewVersionedObject = \u0026unstructured.Unstructured{}\n\t} else {\n\t\tnewVersionedObject, err = o.GetObjectCreater().New(attr.VersionedKind)\n\t\tif err != nil {\n\t\t\treturn false, apierrors.NewInternalError(err)\n\t\t}\n\t}\n\n\t// TODO: if we have multiple mutating webhooks, we can remember the json\n\t// instead of encoding and decoding for each one.\n\tif newVersionedObject, _, err = jsonSerializer.Decode(patchedJS, nil, newVersionedObject); err != nil {\n\t\treturn false, apierrors.NewInternalError(err)\n\t}\n\n\tchanged = !apiequality.Semantic.DeepEqual(attr.VersionedObject, newVersionedObject)\n\tspan.AddEvent(\"Patch applied\")\n\tannotator.addPatchAnnotation(patchObj, result.PatchType)\n\tattr.Dirty = true\n\tattr.VersionedObject = newVersionedObject\n\to.GetObjectDefaulter().Default(attr.VersionedObject)\n\treturn changed, nil\n}","line":{"from":236,"to":384}} {"id":100016743,"name":"newWebhookAnnotator","signature":"func newWebhookAnnotator(attr *admission.VersionedAttributes, round, idx int, webhook, configuration string) *webhookAnnotator","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/dispatcher.go","code":"func newWebhookAnnotator(attr *admission.VersionedAttributes, round, idx int, webhook, configuration string) *webhookAnnotator {\n\treturn \u0026webhookAnnotator{\n\t\tattr: attr,\n\t\tfailedOpenAnnotationKey: fmt.Sprintf(\"%sround_%d_index_%d\", MutationAuditAnnotationFailedOpenKeyPrefix, round, idx),\n\t\tpatchAnnotationKey: fmt.Sprintf(\"%sround_%d_index_%d\", PatchAuditAnnotationPrefix, round, idx),\n\t\tmutationAnnotationKey: fmt.Sprintf(\"%sround_%d_index_%d\", MutationAuditAnnotationPrefix, round, idx),\n\t\twebhook: webhook,\n\t\tconfiguration: configuration,\n\t}\n}","line":{"from":395,"to":404}} {"id":100016744,"name":"addFailedOpenAnnotation","signature":"func (w *webhookAnnotator) addFailedOpenAnnotation()","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/dispatcher.go","code":"func (w *webhookAnnotator) addFailedOpenAnnotation() {\n\tif w.attr == nil || w.attr.Attributes == nil {\n\t\treturn\n\t}\n\tvalue := w.webhook\n\tif err := w.attr.Attributes.AddAnnotation(w.failedOpenAnnotationKey, value); err != nil {\n\t\tklog.Warningf(\"failed to set failed open annotation for mutating webhook key %s to %s: %v\", w.failedOpenAnnotationKey, value, err)\n\t}\n}","line":{"from":406,"to":414}} {"id":100016745,"name":"addMutationAnnotation","signature":"func (w *webhookAnnotator) addMutationAnnotation(mutated bool)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/dispatcher.go","code":"func (w *webhookAnnotator) addMutationAnnotation(mutated bool) {\n\tif w.attr == nil || w.attr.Attributes == nil {\n\t\treturn\n\t}\n\tvalue, err := mutationAnnotationValue(w.configuration, w.webhook, mutated)\n\tif err != nil {\n\t\tklog.Warningf(\"unexpected error composing mutating webhook annotation: %v\", err)\n\t\treturn\n\t}\n\tif err := w.attr.Attributes.AddAnnotation(w.mutationAnnotationKey, value); err != nil {\n\t\tklog.Warningf(\"failed to set mutation annotation for mutating webhook key %s to %s: %v\", w.mutationAnnotationKey, value, err)\n\t}\n}","line":{"from":416,"to":428}} {"id":100016746,"name":"addPatchAnnotation","signature":"func (w *webhookAnnotator) addPatchAnnotation(patch interface{}, patchType admissionv1.PatchType)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/dispatcher.go","code":"func (w *webhookAnnotator) addPatchAnnotation(patch interface{}, patchType admissionv1.PatchType) {\n\tif w.attr == nil || w.attr.Attributes == nil {\n\t\treturn\n\t}\n\tvar value string\n\tvar err error\n\tswitch patchType {\n\tcase admissionv1.PatchTypeJSONPatch:\n\t\tvalue, err = jsonPatchAnnotationValue(w.configuration, w.webhook, patch)\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"unexpected error composing mutating webhook JSON patch annotation: %v\", err)\n\t\t\treturn\n\t\t}\n\tdefault:\n\t\tklog.Warningf(\"unsupported patch type for mutating webhook annotation: %v\", patchType)\n\t\treturn\n\t}\n\tif err := w.attr.Attributes.AddAnnotationWithLevel(w.patchAnnotationKey, value, auditinternal.LevelRequest); err != nil {\n\t\t// NOTE: we don't log actual patch in kube-apiserver log to avoid potentially\n\t\t// leaking information\n\t\tklog.Warningf(\"failed to set patch annotation for mutating webhook key %s; confugiration name: %s, webhook name: %s\", w.patchAnnotationKey, w.configuration, w.webhook)\n\t}\n}","line":{"from":430,"to":452}} {"id":100016747,"name":"mutationAnnotationValue","signature":"func mutationAnnotationValue(configuration, webhook string, mutated bool) (string, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/dispatcher.go","code":"func mutationAnnotationValue(configuration, webhook string, mutated bool) (string, error) {\n\tm := MutationAuditAnnotation{\n\t\tConfiguration: configuration,\n\t\tWebhook: webhook,\n\t\tMutated: mutated,\n\t}\n\tbytes, err := utiljson.Marshal(m)\n\treturn string(bytes), err\n}","line":{"from":469,"to":477}} {"id":100016748,"name":"jsonPatchAnnotationValue","signature":"func jsonPatchAnnotationValue(configuration, webhook string, patch interface{}) (string, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/dispatcher.go","code":"func jsonPatchAnnotationValue(configuration, webhook string, patch interface{}) (string, error) {\n\tp := PatchAuditAnnotation{\n\t\tConfiguration: configuration,\n\t\tWebhook: webhook,\n\t\tPatch: patch,\n\t\tPatchType: string(admissionv1.PatchTypeJSONPatch),\n\t}\n\tbytes, err := utiljson.Marshal(p)\n\treturn string(bytes), err\n}","line":{"from":479,"to":488}} {"id":100016749,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/plugin.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(configFile io.Reader) (admission.Interface, error) {\n\t\tplugin, err := NewMutatingWebhook(configFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn plugin, nil\n\t})\n}","line":{"from":33,"to":43}} {"id":100016750,"name":"NewMutatingWebhook","signature":"func NewMutatingWebhook(configFile io.Reader) (*Plugin, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/plugin.go","code":"// NewMutatingWebhook returns a generic admission webhook plugin.\nfunc NewMutatingWebhook(configFile io.Reader) (*Plugin, error) {\n\thandler := admission.NewHandler(admission.Connect, admission.Create, admission.Delete, admission.Update)\n\tp := \u0026Plugin{}\n\tvar err error\n\tp.Webhook, err = generic.NewWebhook(handler, configFile, configuration.NewMutatingWebhookConfigurationManager, newMutatingDispatcher(p))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn p, nil\n}","line":{"from":52,"to":63}} {"id":100016751,"name":"ValidateInitialization","signature":"func (a *Plugin) ValidateInitialization() error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/plugin.go","code":"// ValidateInitialization implements the InitializationValidator interface.\nfunc (a *Plugin) ValidateInitialization() error {\n\tif err := a.Webhook.ValidateInitialization(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":65,"to":71}} {"id":100016752,"name":"Admit","signature":"func (a *Plugin) Admit(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/plugin.go","code":"// Admit makes an admission decision based on the request attributes.\nfunc (a *Plugin) Admit(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) error {\n\treturn a.Webhook.Dispatch(ctx, attr, o)\n}","line":{"from":73,"to":76}} {"id":100016753,"name":"ShouldReinvokeWebhook","signature":"func (rc *webhookReinvokeContext) ShouldReinvokeWebhook(webhook string) bool","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/reinvocationcontext.go","code":"func (rc *webhookReinvokeContext) ShouldReinvokeWebhook(webhook string) bool {\n\treturn rc.reinvokeWebhooks.Has(webhook)\n}","line":{"from":35,"to":37}} {"id":100016754,"name":"IsOutputChangedSinceLastWebhookInvocation","signature":"func (rc *webhookReinvokeContext) IsOutputChangedSinceLastWebhookInvocation(object runtime.Object) bool","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/reinvocationcontext.go","code":"func (rc *webhookReinvokeContext) IsOutputChangedSinceLastWebhookInvocation(object runtime.Object) bool {\n\treturn !apiequality.Semantic.DeepEqual(rc.lastWebhookOutput, object)\n}","line":{"from":39,"to":41}} {"id":100016755,"name":"SetLastWebhookInvocationOutput","signature":"func (rc *webhookReinvokeContext) SetLastWebhookInvocationOutput(object runtime.Object)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/reinvocationcontext.go","code":"func (rc *webhookReinvokeContext) SetLastWebhookInvocationOutput(object runtime.Object) {\n\tif object == nil {\n\t\trc.lastWebhookOutput = nil\n\t\treturn\n\t}\n\trc.lastWebhookOutput = object.DeepCopyObject()\n}","line":{"from":43,"to":49}} {"id":100016756,"name":"AddReinvocableWebhookToPreviouslyInvoked","signature":"func (rc *webhookReinvokeContext) AddReinvocableWebhookToPreviouslyInvoked(webhook string)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/reinvocationcontext.go","code":"func (rc *webhookReinvokeContext) AddReinvocableWebhookToPreviouslyInvoked(webhook string) {\n\tif rc.previouslyInvokedReinvocableWebhooks == nil {\n\t\trc.previouslyInvokedReinvocableWebhooks = sets.NewString()\n\t}\n\trc.previouslyInvokedReinvocableWebhooks.Insert(webhook)\n}","line":{"from":51,"to":56}} {"id":100016757,"name":"RequireReinvokingPreviouslyInvokedPlugins","signature":"func (rc *webhookReinvokeContext) RequireReinvokingPreviouslyInvokedPlugins()","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/reinvocationcontext.go","code":"func (rc *webhookReinvokeContext) RequireReinvokingPreviouslyInvokedPlugins() {\n\tif len(rc.previouslyInvokedReinvocableWebhooks) \u003e 0 {\n\t\tif rc.reinvokeWebhooks == nil {\n\t\t\trc.reinvokeWebhooks = sets.NewString()\n\t\t}\n\t\tfor s := range rc.previouslyInvokedReinvocableWebhooks {\n\t\t\trc.reinvokeWebhooks.Insert(s)\n\t\t}\n\t\trc.previouslyInvokedReinvocableWebhooks = sets.NewString()\n\t}\n}","line":{"from":58,"to":68}} {"id":100016758,"name":"Validate","signature":"func (m *Matcher) Validate() error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/namespace/matcher.go","code":"// Validate checks if the Matcher has a NamespaceLister and Client.\nfunc (m *Matcher) Validate() error {\n\tvar errs []error\n\tif m.NamespaceLister == nil {\n\t\terrs = append(errs, fmt.Errorf(\"the namespace matcher requires a namespaceLister\"))\n\t}\n\tif m.Client == nil {\n\t\terrs = append(errs, fmt.Errorf(\"the namespace matcher requires a client\"))\n\t}\n\treturn utilerrors.NewAggregate(errs)\n}","line":{"from":45,"to":55}} {"id":100016759,"name":"GetNamespaceLabels","signature":"func (m *Matcher) GetNamespaceLabels(attr admission.Attributes) (map[string]string, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/namespace/matcher.go","code":"// GetNamespaceLabels gets the labels of the namespace related to the attr.\nfunc (m *Matcher) GetNamespaceLabels(attr admission.Attributes) (map[string]string, error) {\n\t// If the request itself is creating or updating a namespace, then get the\n\t// labels from attr.Object, because namespaceLister doesn't have the latest\n\t// namespace yet.\n\t//\n\t// However, if the request is deleting a namespace, then get the label from\n\t// the namespace in the namespaceLister, because a delete request is not\n\t// going to change the object, and attr.Object will be a DeleteOptions\n\t// rather than a namespace object.\n\tif attr.GetResource().Resource == \"namespaces\" \u0026\u0026\n\t\tlen(attr.GetSubresource()) == 0 \u0026\u0026\n\t\t(attr.GetOperation() == admission.Create || attr.GetOperation() == admission.Update) {\n\t\taccessor, err := meta.Accessor(attr.GetObject())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn accessor.GetLabels(), nil\n\t}\n\n\tnamespaceName := attr.GetNamespace()\n\tnamespace, err := m.NamespaceLister.Get(namespaceName)\n\tif err != nil \u0026\u0026 !apierrors.IsNotFound(err) {\n\t\treturn nil, err\n\t}\n\tif apierrors.IsNotFound(err) {\n\t\t// in case of latency in our caches, make a call direct to storage to verify that it truly exists or not\n\t\tnamespace, err = m.Client.CoreV1().Namespaces().Get(context.TODO(), namespaceName, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn namespace.Labels, nil\n}","line":{"from":57,"to":90}} {"id":100016760,"name":"MatchNamespaceSelector","signature":"func (m *Matcher) MatchNamespaceSelector(p NamespaceSelectorProvider, attr admission.Attributes) (bool, *apierrors.StatusError)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/namespace/matcher.go","code":"// MatchNamespaceSelector decideds whether the request matches the\n// namespaceSelctor of the webhook. Only when they match, the webhook is called.\nfunc (m *Matcher) MatchNamespaceSelector(p NamespaceSelectorProvider, attr admission.Attributes) (bool, *apierrors.StatusError) {\n\tnamespaceName := attr.GetNamespace()\n\tif len(namespaceName) == 0 \u0026\u0026 attr.GetResource().Resource != \"namespaces\" {\n\t\t// If the request is about a cluster scoped resource, and it is not a\n\t\t// namespace, it is never exempted.\n\t\t// TODO: figure out a way selective exempt cluster scoped resources.\n\t\t// Also update the comment in types.go\n\t\treturn true, nil\n\t}\n\tselector, err := p.GetParsedNamespaceSelector()\n\tif err != nil {\n\t\treturn false, apierrors.NewInternalError(err)\n\t}\n\tif selector.Empty() {\n\t\treturn true, nil\n\t}\n\n\tnamespaceLabels, err := m.GetNamespaceLabels(attr)\n\t// this means the namespace is not found, for backwards compatibility,\n\t// return a 404\n\tif apierrors.IsNotFound(err) {\n\t\tstatus, ok := err.(apierrors.APIStatus)\n\t\tif !ok {\n\t\t\treturn false, apierrors.NewInternalError(err)\n\t\t}\n\t\treturn false, \u0026apierrors.StatusError{ErrStatus: status.Status()}\n\t}\n\tif err != nil {\n\t\treturn false, apierrors.NewInternalError(err)\n\t}\n\treturn selector.Matches(labels.Set(namespaceLabels)), nil\n}","line":{"from":92,"to":125}} {"id":100016761,"name":"matchObject","signature":"func matchObject(obj runtime.Object, selector labels.Selector) bool","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/object/matcher.go","code":"func matchObject(obj runtime.Object, selector labels.Selector) bool {\n\tif obj == nil {\n\t\treturn false\n\t}\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\tklog.V(5).InfoS(\"Accessing metadata failed\", \"object\", obj, \"err\", err)\n\t\treturn false\n\t}\n\treturn selector.Matches(labels.Set(accessor.GetLabels()))\n\n}","line":{"from":37,"to":48}} {"id":100016762,"name":"MatchObjectSelector","signature":"func (m *Matcher) MatchObjectSelector(p ObjectSelectorProvider, attr admission.Attributes) (bool, *apierrors.StatusError)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/object/matcher.go","code":"// MatchObjectSelector decideds whether the request matches the ObjectSelector\n// of the webhook. Only when they match, the webhook is called.\nfunc (m *Matcher) MatchObjectSelector(p ObjectSelectorProvider, attr admission.Attributes) (bool, *apierrors.StatusError) {\n\tselector, err := p.GetParsedObjectSelector()\n\tif err != nil {\n\t\treturn false, apierrors.NewInternalError(err)\n\t}\n\tif selector.Empty() {\n\t\treturn true, nil\n\t}\n\treturn matchObject(attr.GetObject(), selector) || matchObject(attr.GetOldObject(), selector), nil\n}","line":{"from":50,"to":61}} {"id":100016763,"name":"Matches","signature":"func (r *Matcher) Matches() bool","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/rules/rules.go","code":"// Matches returns if the Attr matches the Rule.\nfunc (r *Matcher) Matches() bool {\n\treturn r.scope() \u0026\u0026\n\t\tr.operation() \u0026\u0026\n\t\tr.group() \u0026\u0026\n\t\tr.version() \u0026\u0026\n\t\tr.resource()\n}","line":{"from":34,"to":41}} {"id":100016764,"name":"exactOrWildcard","signature":"func exactOrWildcard(items []string, requested string) bool","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/rules/rules.go","code":"func exactOrWildcard(items []string, requested string) bool {\n\tfor _, item := range items {\n\t\tif item == \"*\" {\n\t\t\treturn true\n\t\t}\n\t\tif item == requested {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":43,"to":54}} {"id":100016765,"name":"scope","signature":"func (r *Matcher) scope() bool","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/rules/rules.go","code":"func (r *Matcher) scope() bool {\n\tif r.Rule.Scope == nil || *r.Rule.Scope == v1.AllScopes {\n\t\treturn true\n\t}\n\t// attr.GetNamespace() is set to the name of the namespace for requests of the namespace object itself.\n\tswitch *r.Rule.Scope {\n\tcase v1.NamespacedScope:\n\t\t// first make sure that we are not requesting a namespace object (namespace objects are cluster-scoped)\n\t\treturn r.Attr.GetResource() != namespaceResource \u0026\u0026 r.Attr.GetNamespace() != metav1.NamespaceNone\n\tcase v1.ClusterScope:\n\t\t// also return true if the request is for a namespace object (namespace objects are cluster-scoped)\n\t\treturn r.Attr.GetResource() == namespaceResource || r.Attr.GetNamespace() == metav1.NamespaceNone\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":58,"to":73}} {"id":100016766,"name":"group","signature":"func (r *Matcher) group() bool","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/rules/rules.go","code":"func (r *Matcher) group() bool {\n\treturn exactOrWildcard(r.Rule.APIGroups, r.Attr.GetResource().Group)\n}","line":{"from":75,"to":77}} {"id":100016767,"name":"version","signature":"func (r *Matcher) version() bool","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/rules/rules.go","code":"func (r *Matcher) version() bool {\n\treturn exactOrWildcard(r.Rule.APIVersions, r.Attr.GetResource().Version)\n}","line":{"from":79,"to":81}} {"id":100016768,"name":"operation","signature":"func (r *Matcher) operation() bool","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/rules/rules.go","code":"func (r *Matcher) operation() bool {\n\tattrOp := r.Attr.GetOperation()\n\tfor _, op := range r.Rule.Operations {\n\t\tif op == v1.OperationAll {\n\t\t\treturn true\n\t\t}\n\t\t// The constants are the same such that this is a valid cast (and this\n\t\t// is tested).\n\t\tif op == v1.OperationType(attrOp) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":83,"to":96}} {"id":100016769,"name":"splitResource","signature":"func splitResource(resSub string) (res, sub string)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/rules/rules.go","code":"func splitResource(resSub string) (res, sub string) {\n\tparts := strings.SplitN(resSub, \"/\", 2)\n\tif len(parts) == 2 {\n\t\treturn parts[0], parts[1]\n\t}\n\treturn parts[0], \"\"\n}","line":{"from":98,"to":104}} {"id":100016770,"name":"resource","signature":"func (r *Matcher) resource() bool","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/rules/rules.go","code":"func (r *Matcher) resource() bool {\n\topRes, opSub := r.Attr.GetResource().Resource, r.Attr.GetSubresource()\n\tfor _, res := range r.Rule.Resources {\n\t\tres, sub := splitResource(res)\n\t\tresMatch := res == \"*\" || res == opRes\n\t\tsubMatch := sub == \"*\" || sub == opSub\n\t\tif resMatch \u0026\u0026 subMatch {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":106,"to":117}} {"id":100016771,"name":"IsExemptAdmissionConfigurationResource","signature":"func IsExemptAdmissionConfigurationResource(attr admission.Attributes) bool","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/rules/rules.go","code":"// IsExemptAdmissionConfigurationResource determines if an admission.Attributes object is describing\n// the admission of a ValidatingWebhookConfiguration or a MutatingWebhookConfiguration or a ValidatingAdmissionPolicy or a ValidatingAdmissionPolicyBinding\nfunc IsExemptAdmissionConfigurationResource(attr admission.Attributes) bool {\n\tgvk := attr.GetKind()\n\tif gvk.Group == \"admissionregistration.k8s.io\" {\n\t\tif gvk.Kind == \"ValidatingWebhookConfiguration\" || gvk.Kind == \"MutatingWebhookConfiguration\" || gvk.Kind == \"ValidatingAdmissionPolicy\" || gvk.Kind == \"ValidatingAdmissionPolicyBinding\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":119,"to":129}} {"id":100016772,"name":"VerifyAdmissionResponse","signature":"func VerifyAdmissionResponse(uid types.UID, mutating bool, review runtime.Object) (*AdmissionResponse, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/request/admissionreview.go","code":"// VerifyAdmissionResponse checks the validity of the provided admission review object, and returns the\n// audit annotations, whether the response allowed the request, any provided patch/patchType/status,\n// or an error if the provided admission review was not valid.\nfunc VerifyAdmissionResponse(uid types.UID, mutating bool, review runtime.Object) (*AdmissionResponse, error) {\n\tswitch r := review.(type) {\n\tcase *admissionv1.AdmissionReview:\n\t\tif r.Response == nil {\n\t\t\treturn nil, fmt.Errorf(\"webhook response was absent\")\n\t\t}\n\n\t\t// Verify UID matches\n\t\tif r.Response.UID != uid {\n\t\t\treturn nil, fmt.Errorf(\"expected response.uid=%q, got %q\", uid, r.Response.UID)\n\t\t}\n\n\t\t// Verify GVK\n\t\tv1GVK := admissionv1.SchemeGroupVersion.WithKind(\"AdmissionReview\")\n\t\tif r.GroupVersionKind() != v1GVK {\n\t\t\treturn nil, fmt.Errorf(\"expected webhook response of %v, got %v\", v1GVK.String(), r.GroupVersionKind().String())\n\t\t}\n\n\t\tpatch := []byte(nil)\n\t\tpatchType := admissionv1.PatchType(\"\")\n\n\t\tif mutating {\n\t\t\t// Ensure a mutating webhook provides both patch and patchType together\n\t\t\tif len(r.Response.Patch) \u003e 0 \u0026\u0026 r.Response.PatchType == nil {\n\t\t\t\treturn nil, fmt.Errorf(\"webhook returned response.patch but not response.patchType\")\n\t\t\t}\n\t\t\tif len(r.Response.Patch) == 0 \u0026\u0026 r.Response.PatchType != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"webhook returned response.patchType but not response.patch\")\n\t\t\t}\n\t\t\tpatch = r.Response.Patch\n\t\t\tif r.Response.PatchType != nil {\n\t\t\t\tpatchType = *r.Response.PatchType\n\t\t\t\tif len(patchType) == 0 {\n\t\t\t\t\treturn nil, fmt.Errorf(\"webhook returned invalid response.patchType of %q\", patchType)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// Ensure a validating webhook doesn't return patch or patchType\n\t\t\tif len(r.Response.Patch) \u003e 0 {\n\t\t\t\treturn nil, fmt.Errorf(\"validating webhook may not return response.patch\")\n\t\t\t}\n\t\t\tif r.Response.PatchType != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"validating webhook may not return response.patchType\")\n\t\t\t}\n\t\t}\n\n\t\treturn \u0026AdmissionResponse{\n\t\t\tAuditAnnotations: r.Response.AuditAnnotations,\n\t\t\tAllowed: r.Response.Allowed,\n\t\t\tPatch: patch,\n\t\t\tPatchType: patchType,\n\t\t\tResult: r.Response.Result,\n\t\t\tWarnings: r.Response.Warnings,\n\t\t}, nil\n\n\tcase *admissionv1beta1.AdmissionReview:\n\t\tif r.Response == nil {\n\t\t\treturn nil, fmt.Errorf(\"webhook response was absent\")\n\t\t}\n\n\t\t// Response GVK and response.uid were not verified in v1beta1 handling, allow any\n\n\t\tpatch := []byte(nil)\n\t\tpatchType := admissionv1.PatchType(\"\")\n\t\tif mutating {\n\t\t\tpatch = r.Response.Patch\n\t\t\tif len(r.Response.Patch) \u003e 0 {\n\t\t\t\t// patch type was not verified in v1beta1 admissionreview handling. pin to only supported version if a patch is provided.\n\t\t\t\tpatchType = admissionv1.PatchTypeJSONPatch\n\t\t\t}\n\t\t}\n\n\t\treturn \u0026AdmissionResponse{\n\t\t\tAuditAnnotations: r.Response.AuditAnnotations,\n\t\t\tAllowed: r.Response.Allowed,\n\t\t\tPatch: patch,\n\t\t\tPatchType: patchType,\n\t\t\tResult: r.Response.Result,\n\t\t\tWarnings: r.Response.Warnings,\n\t\t}, nil\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unexpected response type %T\", review)\n\t}\n}","line":{"from":43,"to":130}} {"id":100016773,"name":"CreateAdmissionObjects","signature":"func CreateAdmissionObjects(versionedAttributes *admission.VersionedAttributes, invocation *generic.WebhookInvocation) (uid types.UID, request, response runtime.Object, err error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/request/admissionreview.go","code":"// CreateAdmissionObjects returns the unique request uid, the AdmissionReview object to send the webhook and to decode the response into,\n// or an error if the webhook does not support receiving any of the admission review versions we know to send\nfunc CreateAdmissionObjects(versionedAttributes *admission.VersionedAttributes, invocation *generic.WebhookInvocation) (uid types.UID, request, response runtime.Object, err error) {\n\tfor _, version := range invocation.Webhook.GetAdmissionReviewVersions() {\n\t\tswitch version {\n\t\tcase admissionv1.SchemeGroupVersion.Version:\n\t\t\tuid := types.UID(uuid.NewUUID())\n\t\t\trequest := CreateV1AdmissionReview(uid, versionedAttributes, invocation)\n\t\t\tresponse := \u0026admissionv1.AdmissionReview{}\n\t\t\treturn uid, request, response, nil\n\n\t\tcase admissionv1beta1.SchemeGroupVersion.Version:\n\t\t\tuid := types.UID(uuid.NewUUID())\n\t\t\trequest := CreateV1beta1AdmissionReview(uid, versionedAttributes, invocation)\n\t\t\tresponse := \u0026admissionv1beta1.AdmissionReview{}\n\t\t\treturn uid, request, response, nil\n\n\t\t}\n\t}\n\treturn \"\", nil, nil, fmt.Errorf(\"webhook does not accept known AdmissionReview versions (v1, v1beta1)\")\n}","line":{"from":132,"to":152}} {"id":100016774,"name":"CreateV1AdmissionReview","signature":"func CreateV1AdmissionReview(uid types.UID, versionedAttributes *admission.VersionedAttributes, invocation *generic.WebhookInvocation) *admissionv1.AdmissionReview","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/request/admissionreview.go","code":"// CreateV1AdmissionReview creates an AdmissionReview for the provided admission.Attributes\nfunc CreateV1AdmissionReview(uid types.UID, versionedAttributes *admission.VersionedAttributes, invocation *generic.WebhookInvocation) *admissionv1.AdmissionReview {\n\tattr := versionedAttributes.Attributes\n\tgvk := invocation.Kind\n\tgvr := invocation.Resource\n\tsubresource := invocation.Subresource\n\trequestGVK := attr.GetKind()\n\trequestGVR := attr.GetResource()\n\trequestSubResource := attr.GetSubresource()\n\taUserInfo := attr.GetUserInfo()\n\tuserInfo := authenticationv1.UserInfo{\n\t\tExtra: make(map[string]authenticationv1.ExtraValue),\n\t\tGroups: aUserInfo.GetGroups(),\n\t\tUID: aUserInfo.GetUID(),\n\t\tUsername: aUserInfo.GetName(),\n\t}\n\tdryRun := attr.IsDryRun()\n\n\t// Convert the extra information in the user object\n\tfor key, val := range aUserInfo.GetExtra() {\n\t\tuserInfo.Extra[key] = authenticationv1.ExtraValue(val)\n\t}\n\n\treturn \u0026admissionv1.AdmissionReview{\n\t\tRequest: \u0026admissionv1.AdmissionRequest{\n\t\t\tUID: uid,\n\t\t\tKind: metav1.GroupVersionKind{\n\t\t\t\tGroup: gvk.Group,\n\t\t\t\tKind: gvk.Kind,\n\t\t\t\tVersion: gvk.Version,\n\t\t\t},\n\t\t\tResource: metav1.GroupVersionResource{\n\t\t\t\tGroup: gvr.Group,\n\t\t\t\tResource: gvr.Resource,\n\t\t\t\tVersion: gvr.Version,\n\t\t\t},\n\t\t\tSubResource: subresource,\n\t\t\tRequestKind: \u0026metav1.GroupVersionKind{\n\t\t\t\tGroup: requestGVK.Group,\n\t\t\t\tKind: requestGVK.Kind,\n\t\t\t\tVersion: requestGVK.Version,\n\t\t\t},\n\t\t\tRequestResource: \u0026metav1.GroupVersionResource{\n\t\t\t\tGroup: requestGVR.Group,\n\t\t\t\tResource: requestGVR.Resource,\n\t\t\t\tVersion: requestGVR.Version,\n\t\t\t},\n\t\t\tRequestSubResource: requestSubResource,\n\t\t\tName: attr.GetName(),\n\t\t\tNamespace: attr.GetNamespace(),\n\t\t\tOperation: admissionv1.Operation(attr.GetOperation()),\n\t\t\tUserInfo: userInfo,\n\t\t\tObject: runtime.RawExtension{\n\t\t\t\tObject: versionedAttributes.VersionedObject,\n\t\t\t},\n\t\t\tOldObject: runtime.RawExtension{\n\t\t\t\tObject: versionedAttributes.VersionedOldObject,\n\t\t\t},\n\t\t\tDryRun: \u0026dryRun,\n\t\t\tOptions: runtime.RawExtension{\n\t\t\t\tObject: attr.GetOperationOptions(),\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":154,"to":218}} {"id":100016775,"name":"CreateV1beta1AdmissionReview","signature":"func CreateV1beta1AdmissionReview(uid types.UID, versionedAttributes *admission.VersionedAttributes, invocation *generic.WebhookInvocation) *admissionv1beta1.AdmissionReview","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/request/admissionreview.go","code":"// CreateV1beta1AdmissionReview creates an AdmissionReview for the provided admission.Attributes\nfunc CreateV1beta1AdmissionReview(uid types.UID, versionedAttributes *admission.VersionedAttributes, invocation *generic.WebhookInvocation) *admissionv1beta1.AdmissionReview {\n\tattr := versionedAttributes.Attributes\n\tgvk := invocation.Kind\n\tgvr := invocation.Resource\n\tsubresource := invocation.Subresource\n\trequestGVK := attr.GetKind()\n\trequestGVR := attr.GetResource()\n\trequestSubResource := attr.GetSubresource()\n\taUserInfo := attr.GetUserInfo()\n\tuserInfo := authenticationv1.UserInfo{\n\t\tExtra: make(map[string]authenticationv1.ExtraValue),\n\t\tGroups: aUserInfo.GetGroups(),\n\t\tUID: aUserInfo.GetUID(),\n\t\tUsername: aUserInfo.GetName(),\n\t}\n\tdryRun := attr.IsDryRun()\n\n\t// Convert the extra information in the user object\n\tfor key, val := range aUserInfo.GetExtra() {\n\t\tuserInfo.Extra[key] = authenticationv1.ExtraValue(val)\n\t}\n\n\treturn \u0026admissionv1beta1.AdmissionReview{\n\t\tRequest: \u0026admissionv1beta1.AdmissionRequest{\n\t\t\tUID: uid,\n\t\t\tKind: metav1.GroupVersionKind{\n\t\t\t\tGroup: gvk.Group,\n\t\t\t\tKind: gvk.Kind,\n\t\t\t\tVersion: gvk.Version,\n\t\t\t},\n\t\t\tResource: metav1.GroupVersionResource{\n\t\t\t\tGroup: gvr.Group,\n\t\t\t\tResource: gvr.Resource,\n\t\t\t\tVersion: gvr.Version,\n\t\t\t},\n\t\t\tSubResource: subresource,\n\t\t\tRequestKind: \u0026metav1.GroupVersionKind{\n\t\t\t\tGroup: requestGVK.Group,\n\t\t\t\tKind: requestGVK.Kind,\n\t\t\t\tVersion: requestGVK.Version,\n\t\t\t},\n\t\t\tRequestResource: \u0026metav1.GroupVersionResource{\n\t\t\t\tGroup: requestGVR.Group,\n\t\t\t\tResource: requestGVR.Resource,\n\t\t\t\tVersion: requestGVR.Version,\n\t\t\t},\n\t\t\tRequestSubResource: requestSubResource,\n\t\t\tName: attr.GetName(),\n\t\t\tNamespace: attr.GetNamespace(),\n\t\t\tOperation: admissionv1beta1.Operation(attr.GetOperation()),\n\t\t\tUserInfo: userInfo,\n\t\t\tObject: runtime.RawExtension{\n\t\t\t\tObject: versionedAttributes.VersionedObject,\n\t\t\t},\n\t\t\tOldObject: runtime.RawExtension{\n\t\t\t\tObject: versionedAttributes.VersionedOldObject,\n\t\t\t},\n\t\t\tDryRun: \u0026dryRun,\n\t\t\tOptions: runtime.RawExtension{\n\t\t\t\tObject: attr.GetOperationOptions(),\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":220,"to":284}} {"id":100016776,"name":"HasAdmissionReviewVersion","signature":"func HasAdmissionReviewVersion(a string, w webhook.WebhookAccessor) bool","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/util/client_config.go","code":"// HasAdmissionReviewVersion check whether a version is accepted by a given webhook.\nfunc HasAdmissionReviewVersion(a string, w webhook.WebhookAccessor) bool {\n\tfor _, b := range w.GetAdmissionReviewVersions() {\n\t\tif b == a {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":23,"to":31}} {"id":100016777,"name":"newValidatingDispatcher","signature":"func newValidatingDispatcher(p *Plugin) func(cm *webhookutil.ClientManager) generic.Dispatcher","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/validating/dispatcher.go","code":"func newValidatingDispatcher(p *Plugin) func(cm *webhookutil.ClientManager) generic.Dispatcher {\n\treturn func(cm *webhookutil.ClientManager) generic.Dispatcher {\n\t\treturn \u0026validatingDispatcher{cm, p}\n\t}\n}","line":{"from":59,"to":63}} {"id":100016778,"name":"VersionedAttribute","signature":"func (v *versionedAttributeAccessor) VersionedAttribute(gvk schema.GroupVersionKind) (*admission.VersionedAttributes, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/validating/dispatcher.go","code":"func (v *versionedAttributeAccessor) VersionedAttribute(gvk schema.GroupVersionKind) (*admission.VersionedAttributes, error) {\n\tif val, ok := v.versionedAttrs[gvk]; ok {\n\t\treturn val, nil\n\t}\n\tversionedAttr, err := admission.NewVersionedAttributes(v.attr, gvk, v.objectInterfaces)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tv.versionedAttrs[gvk] = versionedAttr\n\treturn versionedAttr, nil\n}","line":{"from":73,"to":83}} {"id":100016779,"name":"Dispatch","signature":"func (d *validatingDispatcher) Dispatch(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces, hooks []webhook.WebhookAccessor) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/validating/dispatcher.go","code":"func (d *validatingDispatcher) Dispatch(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces, hooks []webhook.WebhookAccessor) error {\n\tvar relevantHooks []*generic.WebhookInvocation\n\t// Construct all the versions we need to call our webhooks\n\tversionedAttrAccessor := \u0026versionedAttributeAccessor{\n\t\tversionedAttrs: map[schema.GroupVersionKind]*admission.VersionedAttributes{},\n\t\tattr: attr,\n\t\tobjectInterfaces: o,\n\t}\n\tfor _, hook := range hooks {\n\t\tinvocation, statusError := d.plugin.ShouldCallHook(ctx, hook, attr, o, versionedAttrAccessor)\n\t\tif statusError != nil {\n\t\t\treturn statusError\n\t\t}\n\t\tif invocation == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\trelevantHooks = append(relevantHooks, invocation)\n\t\t// VersionedAttr result will be cached and reused later during parallel webhook calls\n\t\t_, err := versionedAttrAccessor.VersionedAttribute(invocation.Kind)\n\t\tif err != nil {\n\t\t\treturn apierrors.NewInternalError(err)\n\t\t}\n\t}\n\n\tif len(relevantHooks) == 0 {\n\t\t// no matching hooks\n\t\treturn nil\n\t}\n\n\t// Check if the request has already timed out before spawning remote calls\n\tselect {\n\tcase \u003c-ctx.Done():\n\t\t// parent context is canceled or timed out, no point in continuing\n\t\treturn apierrors.NewTimeoutError(\"request did not complete within requested timeout\", 0)\n\tdefault:\n\t}\n\n\twg := sync.WaitGroup{}\n\terrCh := make(chan error, 2*len(relevantHooks)) // double the length to handle extra errors for panics in the gofunc\n\twg.Add(len(relevantHooks))\n\tfor i := range relevantHooks {\n\t\tgo func(invocation *generic.WebhookInvocation, idx int) {\n\t\t\tignoreClientCallFailures := false\n\t\t\thookName := \"unknown\"\n\t\t\tversionedAttr := versionedAttrAccessor.versionedAttrs[invocation.Kind]\n\t\t\t// The ordering of these two defers is critical. The wg.Done will release the parent go func to close the errCh\n\t\t\t// that is used by the second defer to report errors. The recovery and error reporting must be done first.\n\t\t\tdefer wg.Done()\n\t\t\tdefer func() {\n\t\t\t\t// HandleCrash has already called the crash handlers and it has been configured to utilruntime.ReallyCrash\n\t\t\t\t// This block prevents the second panic from failing our process.\n\t\t\t\t// This failure mode for the handler functions properly using the channel below.\n\t\t\t\trecover()\n\t\t\t}()\n\t\t\tdefer utilruntime.HandleCrash(\n\t\t\t\tfunc(r interface{}) {\n\t\t\t\t\tif r == nil {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tif ignoreClientCallFailures {\n\t\t\t\t\t\t// if failures are supposed to ignored, ignore it\n\t\t\t\t\t\tklog.Warningf(\"Panic calling webhook, failing open %v: %v\", hookName, r)\n\t\t\t\t\t\tadmissionmetrics.Metrics.ObserveWebhookFailOpen(ctx, hookName, \"validating\")\n\t\t\t\t\t\tkey := fmt.Sprintf(\"%sround_0_index_%d\", ValidatingAuditAnnotationFailedOpenKeyPrefix, idx)\n\t\t\t\t\t\tvalue := hookName\n\t\t\t\t\t\tif err := versionedAttr.Attributes.AddAnnotation(key, value); err != nil {\n\t\t\t\t\t\t\tklog.Warningf(\"Failed to set admission audit annotation %s to %s for validating webhook %s: %v\", key, value, hookName, err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\t// this ensures that the admission request fails and a message is provided.\n\t\t\t\t\terrCh \u003c- apierrors.NewInternalError(fmt.Errorf(\"ValidatingAdmissionWebhook/%v has panicked: %v\", hookName, r))\n\t\t\t\t},\n\t\t\t)\n\n\t\t\thook, ok := invocation.Webhook.GetValidatingWebhook()\n\t\t\tif !ok {\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"validating webhook dispatch requires v1.ValidatingWebhook, but got %T\", hook))\n\t\t\t\treturn\n\t\t\t}\n\t\t\thookName = hook.Name\n\t\t\tignoreClientCallFailures = hook.FailurePolicy != nil \u0026\u0026 *hook.FailurePolicy == v1.Ignore\n\t\t\tt := time.Now()\n\t\t\terr := d.callHook(ctx, hook, invocation, versionedAttr)\n\t\t\trejected := false\n\t\t\tif err != nil {\n\t\t\t\tswitch err := err.(type) {\n\t\t\t\tcase *webhookutil.ErrCallingWebhook:\n\t\t\t\t\tif !ignoreClientCallFailures {\n\t\t\t\t\t\trejected = true\n\t\t\t\t\t\tadmissionmetrics.Metrics.ObserveWebhookRejection(ctx, hook.Name, \"validating\", string(versionedAttr.Attributes.GetOperation()), admissionmetrics.WebhookRejectionCallingWebhookError, int(err.Status.ErrStatus.Code))\n\t\t\t\t\t}\n\t\t\t\t\tadmissionmetrics.Metrics.ObserveWebhook(ctx, hook.Name, time.Since(t), rejected, versionedAttr.Attributes, \"validating\", int(err.Status.ErrStatus.Code))\n\t\t\t\tcase *webhookutil.ErrWebhookRejection:\n\t\t\t\t\trejected = true\n\t\t\t\t\tadmissionmetrics.Metrics.ObserveWebhookRejection(ctx, hook.Name, \"validating\", string(versionedAttr.Attributes.GetOperation()), admissionmetrics.WebhookRejectionNoError, int(err.Status.ErrStatus.Code))\n\t\t\t\t\tadmissionmetrics.Metrics.ObserveWebhook(ctx, hook.Name, time.Since(t), rejected, versionedAttr.Attributes, \"validating\", int(err.Status.ErrStatus.Code))\n\t\t\t\tdefault:\n\t\t\t\t\trejected = true\n\t\t\t\t\tadmissionmetrics.Metrics.ObserveWebhookRejection(ctx, hook.Name, \"validating\", string(versionedAttr.Attributes.GetOperation()), admissionmetrics.WebhookRejectionAPIServerInternalError, 0)\n\t\t\t\t\tadmissionmetrics.Metrics.ObserveWebhook(ctx, hook.Name, time.Since(t), rejected, versionedAttr.Attributes, \"validating\", 0)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tadmissionmetrics.Metrics.ObserveWebhook(ctx, hook.Name, time.Since(t), rejected, versionedAttr.Attributes, \"validating\", 200)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif callErr, ok := err.(*webhookutil.ErrCallingWebhook); ok {\n\t\t\t\tif ignoreClientCallFailures {\n\t\t\t\t\tklog.Warningf(\"Failed calling webhook, failing open %v: %v\", hook.Name, callErr)\n\t\t\t\t\tadmissionmetrics.Metrics.ObserveWebhookFailOpen(ctx, hook.Name, \"validating\")\n\t\t\t\t\tkey := fmt.Sprintf(\"%sround_0_index_%d\", ValidatingAuditAnnotationFailedOpenKeyPrefix, idx)\n\t\t\t\t\tvalue := hook.Name\n\t\t\t\t\tif err := versionedAttr.Attributes.AddAnnotation(key, value); err != nil {\n\t\t\t\t\t\tklog.Warningf(\"Failed to set admission audit annotation %s to %s for validating webhook %s: %v\", key, value, hook.Name, err)\n\t\t\t\t\t}\n\t\t\t\t\tutilruntime.HandleError(callErr)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tklog.Warningf(\"Failed calling webhook, failing closed %v: %v\", hook.Name, err)\n\t\t\t\terrCh \u003c- apierrors.NewInternalError(err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif rejectionErr, ok := err.(*webhookutil.ErrWebhookRejection); ok {\n\t\t\t\terr = rejectionErr.Status\n\t\t\t}\n\t\t\tklog.Warningf(\"rejected by webhook %q: %#v\", hook.Name, err)\n\t\t\terrCh \u003c- err\n\t\t}(relevantHooks[i], i)\n\t}\n\twg.Wait()\n\tclose(errCh)\n\n\tvar errs []error\n\tfor e := range errCh {\n\t\terrs = append(errs, e)\n\t}\n\tif len(errs) == 0 {\n\t\treturn nil\n\t}\n\tif len(errs) \u003e 1 {\n\t\tfor i := 1; i \u003c len(errs); i++ {\n\t\t\t// TODO: merge status errors; until then, just return the first one.\n\t\t\tutilruntime.HandleError(errs[i])\n\t\t}\n\t}\n\treturn errs[0]\n}","line":{"from":87,"to":237}} {"id":100016780,"name":"callHook","signature":"func (d *validatingDispatcher) callHook(ctx context.Context, h *v1.ValidatingWebhook, invocation *generic.WebhookInvocation, attr *admission.VersionedAttributes) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/validating/dispatcher.go","code":"func (d *validatingDispatcher) callHook(ctx context.Context, h *v1.ValidatingWebhook, invocation *generic.WebhookInvocation, attr *admission.VersionedAttributes) error {\n\tif attr.Attributes.IsDryRun() {\n\t\tif h.SideEffects == nil {\n\t\t\treturn \u0026webhookutil.ErrCallingWebhook{WebhookName: h.Name, Reason: fmt.Errorf(\"Webhook SideEffects is nil\"), Status: apierrors.NewBadRequest(\"Webhook SideEffects is nil\")}\n\t\t}\n\t\tif !(*h.SideEffects == v1.SideEffectClassNone || *h.SideEffects == v1.SideEffectClassNoneOnDryRun) {\n\t\t\treturn webhookerrors.NewDryRunUnsupportedErr(h.Name)\n\t\t}\n\t}\n\n\tuid, request, response, err := webhookrequest.CreateAdmissionObjects(attr, invocation)\n\tif err != nil {\n\t\treturn \u0026webhookutil.ErrCallingWebhook{WebhookName: h.Name, Reason: fmt.Errorf(\"could not create admission objects: %w\", err), Status: apierrors.NewBadRequest(\"error creating admission objects\")}\n\t}\n\t// Make the webhook request\n\tclient, err := invocation.Webhook.GetRESTClient(d.cm)\n\tif err != nil {\n\t\treturn \u0026webhookutil.ErrCallingWebhook{WebhookName: h.Name, Reason: fmt.Errorf(\"could not get REST client: %w\", err), Status: apierrors.NewBadRequest(\"error getting REST client\")}\n\t}\n\tctx, span := tracing.Start(ctx, \"Call validating webhook\",\n\t\tattribute.String(\"configuration\", invocation.Webhook.GetConfigurationName()),\n\t\tattribute.String(\"webhook\", h.Name),\n\t\tattribute.Stringer(\"resource\", attr.GetResource()),\n\t\tattribute.String(\"subresource\", attr.GetSubresource()),\n\t\tattribute.String(\"operation\", string(attr.GetOperation())),\n\t\tattribute.String(\"UID\", string(uid)))\n\tdefer span.End(500 * time.Millisecond)\n\n\t// if the webhook has a specific timeout, wrap the context to apply it\n\tif h.TimeoutSeconds != nil {\n\t\tvar cancel context.CancelFunc\n\t\tctx, cancel = context.WithTimeout(ctx, time.Duration(*h.TimeoutSeconds)*time.Second)\n\t\tdefer cancel()\n\t}\n\n\tr := client.Post().Body(request)\n\n\t// if the context has a deadline, set it as a parameter to inform the backend\n\tif deadline, hasDeadline := ctx.Deadline(); hasDeadline {\n\t\t// compute the timeout\n\t\tif timeout := time.Until(deadline); timeout \u003e 0 {\n\t\t\t// if it's not an even number of seconds, round up to the nearest second\n\t\t\tif truncated := timeout.Truncate(time.Second); truncated != timeout {\n\t\t\t\ttimeout = truncated + time.Second\n\t\t\t}\n\t\t\t// set the timeout\n\t\t\tr.Timeout(timeout)\n\t\t}\n\t}\n\n\tdo := func() { err = r.Do(ctx).Into(response) }\n\tif wd, ok := endpointsrequest.LatencyTrackersFrom(ctx); ok {\n\t\ttmp := do\n\t\tdo = func() { wd.ValidatingWebhookTracker.Track(tmp) }\n\t}\n\tdo()\n\tif err != nil {\n\t\tvar status *apierrors.StatusError\n\t\tif se, ok := err.(*apierrors.StatusError); ok {\n\t\t\tstatus = se\n\t\t} else {\n\t\t\tstatus = apierrors.NewBadRequest(\"error calling webhook\")\n\t\t}\n\t\treturn \u0026webhookutil.ErrCallingWebhook{WebhookName: h.Name, Reason: fmt.Errorf(\"failed to call webhook: %w\", err), Status: status}\n\t}\n\tspan.AddEvent(\"Request completed\")\n\n\tresult, err := webhookrequest.VerifyAdmissionResponse(uid, false, response)\n\tif err != nil {\n\t\treturn \u0026webhookutil.ErrCallingWebhook{WebhookName: h.Name, Reason: fmt.Errorf(\"received invalid webhook response: %w\", err), Status: apierrors.NewServiceUnavailable(\"error validating webhook response\")}\n\t}\n\n\tfor k, v := range result.AuditAnnotations {\n\t\tkey := h.Name + \"/\" + k\n\t\tif err := attr.Attributes.AddAnnotation(key, v); err != nil {\n\t\t\tklog.Warningf(\"Failed to set admission audit annotation %s to %s for validating webhook %s: %v\", key, v, h.Name, err)\n\t\t}\n\t}\n\tfor _, w := range result.Warnings {\n\t\twarning.AddWarning(ctx, \"\", w)\n\t}\n\tif result.Allowed {\n\t\treturn nil\n\t}\n\treturn \u0026webhookutil.ErrWebhookRejection{Status: webhookerrors.ToStatusErr(h.Name, result.Result)}\n}","line":{"from":239,"to":324}} {"id":100016781,"name":"Register","signature":"func Register(plugins *admission.Plugins)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/validating/plugin.go","code":"// Register registers a plugin\nfunc Register(plugins *admission.Plugins) {\n\tplugins.Register(PluginName, func(configFile io.Reader) (admission.Interface, error) {\n\t\tplugin, err := NewValidatingAdmissionWebhook(configFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn plugin, nil\n\t})\n}","line":{"from":33,"to":43}} {"id":100016782,"name":"NewValidatingAdmissionWebhook","signature":"func NewValidatingAdmissionWebhook(configFile io.Reader) (*Plugin, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/validating/plugin.go","code":"// NewValidatingAdmissionWebhook returns a generic admission webhook plugin.\nfunc NewValidatingAdmissionWebhook(configFile io.Reader) (*Plugin, error) {\n\thandler := admission.NewHandler(admission.Connect, admission.Create, admission.Delete, admission.Update)\n\tp := \u0026Plugin{}\n\tvar err error\n\tp.Webhook, err = generic.NewWebhook(handler, configFile, configuration.NewValidatingWebhookConfigurationManager, newValidatingDispatcher(p))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn p, nil\n}","line":{"from":52,"to":62}} {"id":100016783,"name":"Validate","signature":"func (a *Plugin) Validate(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/validating/plugin.go","code":"// Validate makes an admission decision based on the request attributes.\nfunc (a *Plugin) Validate(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) error {\n\treturn a.Webhook.Dispatch(ctx, attr, o)\n}","line":{"from":64,"to":67}} {"id":100016784,"name":"NewPlugins","signature":"func NewPlugins() *Plugins","file":"staging/src/k8s.io/apiserver/pkg/admission/plugins.go","code":"func NewPlugins() *Plugins {\n\treturn \u0026Plugins{}\n}","line":{"from":43,"to":45}} {"id":100016785,"name":"Registered","signature":"func (ps *Plugins) Registered() []string","file":"staging/src/k8s.io/apiserver/pkg/admission/plugins.go","code":"// Registered enumerates the names of all registered plugins.\nfunc (ps *Plugins) Registered() []string {\n\tps.lock.Lock()\n\tdefer ps.lock.Unlock()\n\tkeys := []string{}\n\tfor k := range ps.registry {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\treturn keys\n}","line":{"from":58,"to":68}} {"id":100016786,"name":"Register","signature":"func (ps *Plugins) Register(name string, plugin Factory)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugins.go","code":"// Register registers a plugin Factory by name. This\n// is expected to happen during app startup.\nfunc (ps *Plugins) Register(name string, plugin Factory) {\n\tps.lock.Lock()\n\tdefer ps.lock.Unlock()\n\tif ps.registry != nil {\n\t\t_, found := ps.registry[name]\n\t\tif found {\n\t\t\tklog.Fatalf(\"Admission plugin %q was registered twice\", name)\n\t\t}\n\t} else {\n\t\tps.registry = map[string]Factory{}\n\t}\n\n\tklog.V(1).InfoS(\"Registered admission plugin\", \"plugin\", name)\n\tps.registry[name] = plugin\n}","line":{"from":70,"to":86}} {"id":100016787,"name":"getPlugin","signature":"func (ps *Plugins) getPlugin(name string, config io.Reader) (Interface, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugins.go","code":"// getPlugin creates an instance of the named plugin. It returns `false` if\n// the name is not known. The error is returned only when the named provider was\n// known but failed to initialize. The config parameter specifies the io.Reader\n// handler of the configuration file for the cloud provider, or nil for no configuration.\nfunc (ps *Plugins) getPlugin(name string, config io.Reader) (Interface, bool, error) {\n\tps.lock.Lock()\n\tdefer ps.lock.Unlock()\n\tf, found := ps.registry[name]\n\tif !found {\n\t\treturn nil, false, nil\n\t}\n\n\tconfig1, config2, err := splitStream(config)\n\tif err != nil {\n\t\treturn nil, true, err\n\t}\n\tif !PluginEnabledFn(name, config1) {\n\t\treturn nil, true, nil\n\t}\n\n\tret, err := f(config2)\n\treturn ret, true, err\n}","line":{"from":88,"to":110}} {"id":100016788,"name":"splitStream","signature":"func splitStream(config io.Reader) (io.Reader, io.Reader, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugins.go","code":"// splitStream reads the stream bytes and constructs two copies of it.\nfunc splitStream(config io.Reader) (io.Reader, io.Reader, error) {\n\tif config == nil || reflect.ValueOf(config).IsNil() {\n\t\treturn nil, nil, nil\n\t}\n\n\tconfigBytes, err := ioutil.ReadAll(config)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn bytes.NewBuffer(configBytes), bytes.NewBuffer(configBytes), nil\n}","line":{"from":112,"to":124}} {"id":100016789,"name":"NewFromPlugins","signature":"func (ps *Plugins) NewFromPlugins(pluginNames []string, configProvider ConfigProvider, pluginInitializer PluginInitializer, decorator Decorator) (Interface, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugins.go","code":"// NewFromPlugins returns an admission.Interface that will enforce admission control decisions of all\n// the given plugins.\nfunc (ps *Plugins) NewFromPlugins(pluginNames []string, configProvider ConfigProvider, pluginInitializer PluginInitializer, decorator Decorator) (Interface, error) {\n\thandlers := []Interface{}\n\tmutationPlugins := []string{}\n\tvalidationPlugins := []string{}\n\tfor _, pluginName := range pluginNames {\n\t\tpluginConfig, err := configProvider.ConfigFor(pluginName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tplugin, err := ps.InitPlugin(pluginName, pluginConfig, pluginInitializer)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif plugin != nil {\n\t\t\tif decorator != nil {\n\t\t\t\thandlers = append(handlers, decorator.Decorate(plugin, pluginName))\n\t\t\t} else {\n\t\t\t\thandlers = append(handlers, plugin)\n\t\t\t}\n\n\t\t\tif _, ok := plugin.(MutationInterface); ok {\n\t\t\t\tmutationPlugins = append(mutationPlugins, pluginName)\n\t\t\t}\n\t\t\tif _, ok := plugin.(ValidationInterface); ok {\n\t\t\t\tvalidationPlugins = append(validationPlugins, pluginName)\n\t\t\t}\n\t\t}\n\t}\n\tif len(mutationPlugins) != 0 {\n\t\tklog.Infof(\"Loaded %d mutating admission controller(s) successfully in the following order: %s.\", len(mutationPlugins), strings.Join(mutationPlugins, \",\"))\n\t}\n\tif len(validationPlugins) != 0 {\n\t\tklog.Infof(\"Loaded %d validating admission controller(s) successfully in the following order: %s.\", len(validationPlugins), strings.Join(validationPlugins, \",\"))\n\t}\n\treturn newReinvocationHandler(chainAdmissionHandler(handlers)), nil\n}","line":{"from":126,"to":164}} {"id":100016790,"name":"InitPlugin","signature":"func (ps *Plugins) InitPlugin(name string, config io.Reader, pluginInitializer PluginInitializer) (Interface, error)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugins.go","code":"// InitPlugin creates an instance of the named interface.\nfunc (ps *Plugins) InitPlugin(name string, config io.Reader, pluginInitializer PluginInitializer) (Interface, error) {\n\tif name == \"\" {\n\t\tklog.Info(\"No admission plugin specified.\")\n\t\treturn nil, nil\n\t}\n\n\tplugin, found, err := ps.getPlugin(name, config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"couldn't init admission plugin %q: %v\", name, err)\n\t}\n\tif !found {\n\t\treturn nil, fmt.Errorf(\"unknown admission plugin: %s\", name)\n\t}\n\n\tpluginInitializer.Initialize(plugin)\n\t// ensure that plugins have been properly initialized\n\tif err := ValidateInitialization(plugin); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize admission plugin %q: %v\", name, err)\n\t}\n\n\treturn plugin, nil\n}","line":{"from":166,"to":188}} {"id":100016791,"name":"ValidateInitialization","signature":"func ValidateInitialization(plugin Interface) error","file":"staging/src/k8s.io/apiserver/pkg/admission/plugins.go","code":"// ValidateInitialization will call the InitializationValidate function in each plugin if they implement\n// the InitializationValidator interface.\nfunc ValidateInitialization(plugin Interface) error {\n\tif validater, ok := plugin.(InitializationValidator); ok {\n\t\terr := validater.ValidateInitialization()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":190,"to":200}} {"id":100016792,"name":"Initialize","signature":"func (pp PluginInitializers) Initialize(plugin Interface)","file":"staging/src/k8s.io/apiserver/pkg/admission/plugins.go","code":"func (pp PluginInitializers) Initialize(plugin Interface) {\n\tfor _, p := range pp {\n\t\tp.Initialize(plugin)\n\t}\n}","line":{"from":204,"to":208}} {"id":100016793,"name":"newReinvocationHandler","signature":"func newReinvocationHandler(admissionChain Interface) Interface","file":"staging/src/k8s.io/apiserver/pkg/admission/reinvocation.go","code":"// newReinvocationHandler creates a handler that wraps the provided admission chain and reinvokes it\n// if needed according to re-invocation policy of the webhooks.\nfunc newReinvocationHandler(admissionChain Interface) Interface {\n\treturn \u0026reinvoker{admissionChain}\n}","line":{"from":21,"to":25}} {"id":100016794,"name":"Admit","signature":"func (r *reinvoker) Admit(ctx context.Context, a Attributes, o ObjectInterfaces) error","file":"staging/src/k8s.io/apiserver/pkg/admission/reinvocation.go","code":"// Admit performs an admission control check using the wrapped admission chain, reinvoking the\n// admission chain if needed according to the reinvocation policy. Plugins are expected to check\n// the admission attributes' reinvocation context against their reinvocation policy to decide if\n// they should re-run, and to update the reinvocation context if they perform any mutations.\nfunc (r *reinvoker) Admit(ctx context.Context, a Attributes, o ObjectInterfaces) error {\n\tif mutator, ok := r.admissionChain.(MutationInterface); ok {\n\t\terr := mutator.Admit(ctx, a, o)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ts := a.GetReinvocationContext()\n\t\tif s.ShouldReinvoke() {\n\t\t\ts.SetIsReinvoke()\n\t\t\t// Calling admit a second time will reinvoke all in-tree plugins\n\t\t\t// as well as any webhook plugins that need to be reinvoked based on the\n\t\t\t// reinvocation policy.\n\t\t\treturn mutator.Admit(ctx, a, o)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":31,"to":51}} {"id":100016795,"name":"Validate","signature":"func (r *reinvoker) Validate(ctx context.Context, a Attributes, o ObjectInterfaces) error","file":"staging/src/k8s.io/apiserver/pkg/admission/reinvocation.go","code":"// Validate performs an admission control check using the wrapped admission chain, and returns immediately on first error.\nfunc (r *reinvoker) Validate(ctx context.Context, a Attributes, o ObjectInterfaces) error {\n\tif validator, ok := r.admissionChain.(ValidationInterface); ok {\n\t\treturn validator.Validate(ctx, a, o)\n\t}\n\treturn nil\n}","line":{"from":53,"to":59}} {"id":100016796,"name":"Handles","signature":"func (r *reinvoker) Handles(operation Operation) bool","file":"staging/src/k8s.io/apiserver/pkg/admission/reinvocation.go","code":"// Handles will return true if any of the admission chain handlers handle the given operation.\nfunc (r *reinvoker) Handles(operation Operation) bool {\n\treturn r.admissionChain.Handles(operation)\n}","line":{"from":61,"to":64}} {"id":100016797,"name":"NewObjectInterfacesFromScheme","signature":"func NewObjectInterfacesFromScheme(scheme *runtime.Scheme) ObjectInterfaces","file":"staging/src/k8s.io/apiserver/pkg/admission/util.go","code":"func NewObjectInterfacesFromScheme(scheme *runtime.Scheme) ObjectInterfaces {\n\treturn \u0026RuntimeObjectInterfaces{scheme, scheme, scheme, scheme, runtime.NewEquivalentResourceRegistry()}\n}","line":{"from":29,"to":31}} {"id":100016798,"name":"GetObjectCreater","signature":"func (r *RuntimeObjectInterfaces) GetObjectCreater() runtime.ObjectCreater","file":"staging/src/k8s.io/apiserver/pkg/admission/util.go","code":"func (r *RuntimeObjectInterfaces) GetObjectCreater() runtime.ObjectCreater {\n\treturn r.ObjectCreater\n}","line":{"from":33,"to":35}} {"id":100016799,"name":"GetObjectTyper","signature":"func (r *RuntimeObjectInterfaces) GetObjectTyper() runtime.ObjectTyper","file":"staging/src/k8s.io/apiserver/pkg/admission/util.go","code":"func (r *RuntimeObjectInterfaces) GetObjectTyper() runtime.ObjectTyper {\n\treturn r.ObjectTyper\n}","line":{"from":36,"to":38}} {"id":100016800,"name":"GetObjectDefaulter","signature":"func (r *RuntimeObjectInterfaces) GetObjectDefaulter() runtime.ObjectDefaulter","file":"staging/src/k8s.io/apiserver/pkg/admission/util.go","code":"func (r *RuntimeObjectInterfaces) GetObjectDefaulter() runtime.ObjectDefaulter {\n\treturn r.ObjectDefaulter\n}","line":{"from":39,"to":41}} {"id":100016801,"name":"GetObjectConvertor","signature":"func (r *RuntimeObjectInterfaces) GetObjectConvertor() runtime.ObjectConvertor","file":"staging/src/k8s.io/apiserver/pkg/admission/util.go","code":"func (r *RuntimeObjectInterfaces) GetObjectConvertor() runtime.ObjectConvertor {\n\treturn r.ObjectConvertor\n}","line":{"from":42,"to":44}} {"id":100016802,"name":"GetEquivalentResourceMapper","signature":"func (r *RuntimeObjectInterfaces) GetEquivalentResourceMapper() runtime.EquivalentResourceMapper","file":"staging/src/k8s.io/apiserver/pkg/admission/util.go","code":"func (r *RuntimeObjectInterfaces) GetEquivalentResourceMapper() runtime.EquivalentResourceMapper {\n\treturn r.EquivalentResourceMapper\n}","line":{"from":45,"to":47}} {"id":100016803,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"staging/src/k8s.io/apiserver/pkg/apis/apiserver/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(apiserver.AddToScheme(scheme))\n\n\t// v1alpha is in the k8s.io-suffixed API group\n\tutilruntime.Must(v1alpha1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1alpha1.SchemeGroupVersion))\n\n\t// v1alpha is in the k8s.io-suffixed API group\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1beta1.SchemeGroupVersion))\n\n\t// v1 is in the config.k8s.io-suffixed API group\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1.SchemeGroupVersion))\n}","line":{"from":28,"to":43}} {"id":100016804,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/apiserver/pkg/apis/apiserver/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(LegacySchemeGroupVersion,\n\t\t\u0026AdmissionConfiguration{},\n\t\t\u0026EgressSelectorConfiguration{},\n\t)\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026AdmissionConfiguration{},\n\t\t\u0026EgressSelectorConfiguration{},\n\t\t\u0026TracingConfiguration{},\n\t)\n\treturn nil\n}","line":{"from":38,"to":50}} {"id":100016805,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/apis/apiserver/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addKnownTypes)\n}","line":{"from":38,"to":43}} {"id":100016806,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/apiserver/pkg/apis/apiserver/v1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026AdmissionConfiguration{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":45,"to":52}} {"id":100016807,"name":"Convert_v1alpha1_EgressSelection_To_apiserver_EgressSelection","signature":"func Convert_v1alpha1_EgressSelection_To_apiserver_EgressSelection(in *EgressSelection, out *apiserver.EgressSelection, s conversion.Scope) error","file":"staging/src/k8s.io/apiserver/pkg/apis/apiserver/v1alpha1/conversion.go","code":"func Convert_v1alpha1_EgressSelection_To_apiserver_EgressSelection(in *EgressSelection, out *apiserver.EgressSelection, s conversion.Scope) error {\n\tif err := autoConvert_v1alpha1_EgressSelection_To_apiserver_EgressSelection(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tif out.Name == \"master\" {\n\t\tout.Name = \"controlplane\"\n\t}\n\treturn nil\n}","line":{"from":24,"to":32}} {"id":100016808,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/apis/apiserver/v1alpha1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addKnownTypes)\n}","line":{"from":42,"to":47}} {"id":100016809,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/apiserver/pkg/apis/apiserver/v1alpha1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026AdmissionConfiguration{},\n\t\t\u0026EgressSelectorConfiguration{},\n\t)\n\tscheme.AddKnownTypes(ConfigSchemeGroupVersion,\n\t\t\u0026TracingConfiguration{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\tmetav1.AddToGroupVersion(scheme, ConfigSchemeGroupVersion)\n\treturn nil\n}","line":{"from":49,"to":61}} {"id":100016810,"name":"Convert_v1beta1_EgressSelection_To_apiserver_EgressSelection","signature":"func Convert_v1beta1_EgressSelection_To_apiserver_EgressSelection(in *EgressSelection, out *apiserver.EgressSelection, s conversion.Scope) error","file":"staging/src/k8s.io/apiserver/pkg/apis/apiserver/v1beta1/conversion.go","code":"func Convert_v1beta1_EgressSelection_To_apiserver_EgressSelection(in *EgressSelection, out *apiserver.EgressSelection, s conversion.Scope) error {\n\tif err := autoConvert_v1beta1_EgressSelection_To_apiserver_EgressSelection(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tif out.Name == \"master\" {\n\t\tout.Name = \"controlplane\"\n\t}\n\treturn nil\n}","line":{"from":24,"to":32}} {"id":100016811,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/apis/apiserver/v1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addKnownTypes)\n}","line":{"from":42,"to":47}} {"id":100016812,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/apiserver/pkg/apis/apiserver/v1beta1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026EgressSelectorConfiguration{},\n\t)\n\tscheme.AddKnownTypes(ConfigSchemeGroupVersion,\n\t\t\u0026TracingConfiguration{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":49,"to":59}} {"id":100016813,"name":"Funcs","signature":"func Funcs(codecs runtimeserializer.CodecFactory) []interface{}","file":"staging/src/k8s.io/apiserver/pkg/apis/audit/fuzzer/fuzzer.go","code":"// Funcs returns the fuzzer functions for the audit api group.\nfunc Funcs(codecs runtimeserializer.CodecFactory) []interface{} {\n\treturn []interface{}{\n\t\tfunc(e *audit.Event, c fuzz.Continue) {\n\t\t\tc.FuzzNoCustom(e)\n\t\t\tswitch c.RandBool() {\n\t\t\tcase true:\n\t\t\t\te.RequestObject = nil\n\t\t\tcase false:\n\t\t\t\te.RequestObject = \u0026runtime.Unknown{\n\t\t\t\t\tTypeMeta: runtime.TypeMeta{APIVersion: \"\", Kind: \"\"},\n\t\t\t\t\tRaw: []byte(`{\"apiVersion\":\"\",\"kind\":\"Pod\",\"someKey\":\"someValue\"}`),\n\t\t\t\t\tContentType: runtime.ContentTypeJSON,\n\t\t\t\t}\n\t\t\t}\n\t\t\tswitch c.RandBool() {\n\t\t\tcase true:\n\t\t\t\te.ResponseObject = nil\n\t\t\tcase false:\n\t\t\t\te.ResponseObject = \u0026runtime.Unknown{\n\t\t\t\t\tTypeMeta: runtime.TypeMeta{APIVersion: \"\", Kind: \"\"},\n\t\t\t\t\tRaw: []byte(`{\"apiVersion\":\"\",\"kind\":\"Pod\",\"someKey\":\"someValue\"}`),\n\t\t\t\t\tContentType: runtime.ContentTypeJSON,\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tfunc(o *audit.ObjectReference, c fuzz.Continue) {\n\t\t\tc.FuzzNoCustom(o)\n\t\t\tswitch c.Intn(3) {\n\t\t\tcase 0:\n\t\t\t\t// core api group\n\t\t\t\to.APIGroup = \"\"\n\t\t\t\to.APIVersion = \"v1\"\n\t\t\tcase 1:\n\t\t\t\t// other group\n\t\t\t\to.APIGroup = \"rbac.authorization.k8s.io\"\n\t\t\t\to.APIVersion = \"v1beta1\"\n\t\t\tdefault:\n\t\t\t\t// use random value, but without / as it is used as separator\n\t\t\t\to.APIGroup = strings.Replace(o.APIGroup, \"/\", \"-\", -1)\n\t\t\t\to.APIVersion = strings.Replace(o.APIVersion, \"/\", \"-\", -1)\n\t\t\t}\n\t\t},\n\t}\n}","line":{"from":29,"to":73}} {"id":100016814,"name":"ordLevel","signature":"func ordLevel(l Level) int","file":"staging/src/k8s.io/apiserver/pkg/apis/audit/helpers.go","code":"func ordLevel(l Level) int {\n\tswitch l {\n\tcase LevelMetadata:\n\t\treturn 1\n\tcase LevelRequest:\n\t\treturn 2\n\tcase LevelRequestResponse:\n\t\treturn 3\n\tdefault:\n\t\treturn 0\n\t}\n}","line":{"from":19,"to":30}} {"id":100016815,"name":"Less","signature":"func (a Level) Less(b Level) bool","file":"staging/src/k8s.io/apiserver/pkg/apis/audit/helpers.go","code":"func (a Level) Less(b Level) bool {\n\treturn ordLevel(a) \u003c ordLevel(b)\n}","line":{"from":32,"to":34}} {"id":100016816,"name":"GreaterOrEqual","signature":"func (a Level) GreaterOrEqual(b Level) bool","file":"staging/src/k8s.io/apiserver/pkg/apis/audit/helpers.go","code":"func (a Level) GreaterOrEqual(b Level) bool {\n\treturn ordLevel(a) \u003e= ordLevel(b)\n}","line":{"from":36,"to":38}} {"id":100016817,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"staging/src/k8s.io/apiserver/pkg/apis/audit/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(audit.AddToScheme(scheme))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1.SchemeGroupVersion))\n}","line":{"from":28,"to":33}} {"id":100016818,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/apiserver/pkg/apis/audit/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100016819,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/apiserver/pkg/apis/audit/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100016820,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/apiserver/pkg/apis/audit/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Event{},\n\t\t\u0026EventList{},\n\t\t\u0026Policy{},\n\t\t\u0026PolicyList{},\n\t)\n\treturn nil\n}","line":{"from":45,"to":53}} {"id":100016821,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/apiserver/pkg/apis/audit/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100016822,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/apis/audit/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addKnownTypes)\n}","line":{"from":42,"to":47}} {"id":100016823,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/apiserver/pkg/apis/audit/v1/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Event{},\n\t\t\u0026EventList{},\n\t\t\u0026Policy{},\n\t\t\u0026PolicyList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":49,"to":58}} {"id":100016824,"name":"ValidatePolicy","signature":"func ValidatePolicy(policy *audit.Policy) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/apis/audit/validation/validation.go","code":"// ValidatePolicy validates the audit policy\nfunc ValidatePolicy(policy *audit.Policy) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tallErrs = append(allErrs, validateOmitStages(policy.OmitStages, field.NewPath(\"omitStages\"))...)\n\trulePath := field.NewPath(\"rules\")\n\tfor i, rule := range policy.Rules {\n\t\tallErrs = append(allErrs, validatePolicyRule(rule, rulePath.Index(i))...)\n\t}\n\treturn allErrs\n}","line":{"from":27,"to":36}} {"id":100016825,"name":"validatePolicyRule","signature":"func validatePolicyRule(rule audit.PolicyRule, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/apis/audit/validation/validation.go","code":"func validatePolicyRule(rule audit.PolicyRule, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tallErrs = append(allErrs, validateLevel(rule.Level, fldPath.Child(\"level\"))...)\n\tallErrs = append(allErrs, validateNonResourceURLs(rule.NonResourceURLs, fldPath.Child(\"nonResourceURLs\"))...)\n\tallErrs = append(allErrs, validateResources(rule.Resources, fldPath.Child(\"resources\"))...)\n\tallErrs = append(allErrs, validateOmitStages(rule.OmitStages, fldPath.Child(\"omitStages\"))...)\n\n\tif len(rule.NonResourceURLs) \u003e 0 {\n\t\tif len(rule.Resources) \u003e 0 || len(rule.Namespaces) \u003e 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"nonResourceURLs\"), rule.NonResourceURLs, \"rules cannot apply to both regular resources and non-resource URLs\"))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":38,"to":52}} {"id":100016826,"name":"validateLevel","signature":"func validateLevel(level audit.Level, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/apis/audit/validation/validation.go","code":"func validateLevel(level audit.Level, fldPath *field.Path) field.ErrorList {\n\tswitch level {\n\tcase audit.LevelNone, audit.LevelMetadata, audit.LevelRequest, audit.LevelRequestResponse:\n\t\treturn nil\n\tcase \"\":\n\t\treturn field.ErrorList{field.Required(fldPath, \"\")}\n\tdefault:\n\t\treturn field.ErrorList{field.NotSupported(fldPath, level, validLevels)}\n\t}\n}","line":{"from":68,"to":77}} {"id":100016827,"name":"validateNonResourceURLs","signature":"func validateNonResourceURLs(urls []string, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/apis/audit/validation/validation.go","code":"func validateNonResourceURLs(urls []string, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tfor i, url := range urls {\n\t\tif url == \"*\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tif !strings.HasPrefix(url, \"/\") {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Index(i), url, \"non-resource URL rules must begin with a '/' character\"))\n\t\t}\n\n\t\tif url != \"\" \u0026\u0026 strings.ContainsRune(url[:len(url)-1], '*') {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Index(i), url, \"non-resource URL wildcards '*' must be the final character of the rule\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":79,"to":95}} {"id":100016828,"name":"validateResources","signature":"func validateResources(groupResources []audit.GroupResources, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/apis/audit/validation/validation.go","code":"func validateResources(groupResources []audit.GroupResources, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tfor _, groupResource := range groupResources {\n\t\t// The empty string represents the core API group.\n\t\tif len(groupResource.Group) != 0 {\n\t\t\t// Group names must be lower case and be valid DNS subdomains.\n\t\t\t// reference: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md\n\t\t\t// an error is returned for group name like rbac.authorization.k8s.io/v1beta1\n\t\t\t// rbac.authorization.k8s.io is the valid one\n\t\t\tif msgs := validation.NameIsDNSSubdomain(groupResource.Group, false); len(msgs) != 0 {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"group\"), groupResource.Group, strings.Join(msgs, \",\")))\n\t\t\t}\n\t\t}\n\n\t\tif len(groupResource.ResourceNames) \u003e 0 \u0026\u0026 len(groupResource.Resources) == 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"resourceNames\"), groupResource.ResourceNames, \"using resourceNames requires at least one resource\"))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":97,"to":116}} {"id":100016829,"name":"validateOmitStages","signature":"func validateOmitStages(omitStages []audit.Stage, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/apis/audit/validation/validation.go","code":"func validateOmitStages(omitStages []audit.Stage, fldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\tfor i, stage := range omitStages {\n\t\tvalid := false\n\t\tfor _, validOmitStage := range validOmitStages {\n\t\t\tif string(stage) == validOmitStage {\n\t\t\t\tvalid = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !valid {\n\t\t\tallErrs = append(allErrs, field.Invalid(fldPath.Index(i), string(stage), \"allowed stages are \"+strings.Join(validOmitStages, \",\")))\n\t\t}\n\t}\n\treturn allErrs\n}","line":{"from":118,"to":133}} {"id":100016830,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/apiserver/pkg/apis/config/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind.\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":37,"to":40}} {"id":100016831,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/apiserver/pkg/apis/config/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource.\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":42,"to":45}} {"id":100016832,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/apiserver/pkg/apis/config/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\t// TODO this will get cleaned up with the scheme types are fixed\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026EncryptionConfiguration{},\n\t)\n\treturn nil\n}","line":{"from":47,"to":53}} {"id":100016833,"name":"String","signature":"func (k Key) String() string","file":"staging/src/k8s.io/apiserver/pkg/apis/config/types.go","code":"// String implements Stringer interface in a log safe way.\nfunc (k Key) String() string {\n\treturn fmt.Sprintf(\"Name: %s, Secret: [REDACTED]\", k.Name)\n}","line":{"from":125,"to":128}} {"id":100016834,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/apiserver/pkg/apis/config/v1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":32,"to":34}} {"id":100016835,"name":"SetDefaults_KMSConfiguration","signature":"func SetDefaults_KMSConfiguration(obj *KMSConfiguration)","file":"staging/src/k8s.io/apiserver/pkg/apis/config/v1/defaults.go","code":"// SetDefaults_KMSConfiguration applies defaults to KMSConfiguration.\nfunc SetDefaults_KMSConfiguration(obj *KMSConfiguration) {\n\tif obj.Timeout == nil {\n\t\tobj.Timeout = defaultTimeout\n\t}\n\n\tif obj.APIVersion == \"\" {\n\t\tobj.APIVersion = defaultAPIVersion\n\t}\n\n\t// cacheSize is relevant only for kms v1\n\tif obj.CacheSize == nil \u0026\u0026 obj.APIVersion == \"v1\" {\n\t\tobj.CacheSize = \u0026defaultCacheSize\n\t}\n}","line":{"from":36,"to":50}} {"id":100016836,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/apis/config/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addKnownTypes)\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":38,"to":44}} {"id":100016837,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/apiserver/pkg/apis/config/v1/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026EncryptionConfiguration{},\n\t)\n\t// also register into the v1 group as EncryptionConfig (due to a docs bug)\n\tscheme.AddKnownTypeWithName(schema.GroupVersionKind{Group: \"\", Version: \"v1\", Kind: \"EncryptionConfig\"}, \u0026EncryptionConfiguration{})\n\treturn nil\n}","line":{"from":46,"to":53}} {"id":100016838,"name":"String","signature":"func (k Key) String() string","file":"staging/src/k8s.io/apiserver/pkg/apis/config/v1/types.go","code":"// String implements Stringer interface in a log safe way.\nfunc (k Key) String() string {\n\treturn fmt.Sprintf(\"Name: %s, Secret: [REDACTED]\", k.Name)\n}","line":{"from":125,"to":128}} {"id":100016839,"name":"ValidateEncryptionConfiguration","signature":"func ValidateEncryptionConfiguration(c *config.EncryptionConfiguration, reload bool) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/apis/config/validation/validation.go","code":"// ValidateEncryptionConfiguration validates a v1.EncryptionConfiguration.\nfunc ValidateEncryptionConfiguration(c *config.EncryptionConfiguration, reload bool) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif c == nil {\n\t\tallErrs = append(allErrs, field.Required(root, encryptionConfigNilErr))\n\t\treturn allErrs\n\t}\n\n\tif len(c.Resources) == 0 {\n\t\tallErrs = append(allErrs, field.Required(root, fmt.Sprintf(atLeastOneRequiredErrFmt, root)))\n\t\treturn allErrs\n\t}\n\n\t// kmsProviderNames is used to track config names to ensure they are unique.\n\tkmsProviderNames := sets.NewString()\n\tfor i, conf := range c.Resources {\n\t\tr := root.Index(i).Child(\"resources\")\n\t\tp := root.Index(i).Child(\"providers\")\n\n\t\tif len(conf.Resources) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(r, fmt.Sprintf(atLeastOneRequiredErrFmt, r)))\n\t\t}\n\n\t\tallErrs = append(allErrs, validateResourceOverlap(conf.Resources, r)...)\n\t\tallErrs = append(allErrs, validateResourceNames(conf.Resources, r)...)\n\n\t\tif len(conf.Providers) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(p, fmt.Sprintf(atLeastOneRequiredErrFmt, p)))\n\t\t}\n\n\t\tfor j, provider := range conf.Providers {\n\t\t\tpath := p.Index(j)\n\t\t\tallErrs = append(allErrs, validateSingleProvider(provider, path)...)\n\n\t\t\tswitch {\n\t\t\tcase provider.KMS != nil:\n\t\t\t\tallErrs = append(allErrs, validateKMSConfiguration(provider.KMS, path.Child(\"kms\"), kmsProviderNames, reload)...)\n\t\t\t\tkmsProviderNames.Insert(provider.KMS.Name)\n\t\t\tcase provider.AESGCM != nil:\n\t\t\t\tallErrs = append(allErrs, validateKeys(provider.AESGCM.Keys, path.Child(\"aesgcm\").Child(\"keys\"), aesKeySizes)...)\n\t\t\tcase provider.AESCBC != nil:\n\t\t\t\tallErrs = append(allErrs, validateKeys(provider.AESCBC.Keys, path.Child(\"aescbc\").Child(\"keys\"), aesKeySizes)...)\n\t\t\tcase provider.Secretbox != nil:\n\t\t\t\tallErrs = append(allErrs, validateKeys(provider.Secretbox.Keys, path.Child(\"secretbox\").Child(\"keys\"), secretBoxKeySizes)...)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":66,"to":116}} {"id":100016840,"name":"validateResourceOverlap","signature":"func validateResourceOverlap(resources []string, fieldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/apis/config/validation/validation.go","code":"func validateResourceOverlap(resources []string, fieldPath *field.Path) field.ErrorList {\n\tif len(resources) \u003c 2 { // cannot have overlap with a single resource\n\t\treturn nil\n\t}\n\n\tvar allErrs field.ErrorList\n\n\tr := make([]schema.GroupResource, 0, len(resources))\n\tfor _, resource := range resources {\n\t\tr = append(r, schema.ParseGroupResource(resource))\n\t}\n\n\tvar hasOverlap, hasDuplicate bool\n\n\tfor i, r1 := range r {\n\t\tfor j, r2 := range r {\n\t\t\tif i == j {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif r1 == r2 \u0026\u0026 !hasDuplicate {\n\t\t\t\thasDuplicate = true\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif hasOverlap {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif r1 == anyGroupAnyResource {\n\t\t\t\thasOverlap = true\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif r1.Group != r2.Group {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif r1.Resource == \"*\" || r2.Resource == \"*\" {\n\t\t\t\thasOverlap = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\n\tif hasDuplicate {\n\t\tallErrs = append(\n\t\t\tallErrs,\n\t\t\tfield.Invalid(\n\t\t\t\tfieldPath,\n\t\t\t\tresources,\n\t\t\t\tduplicateResourceErr,\n\t\t\t),\n\t\t)\n\t}\n\n\tif hasOverlap {\n\t\tallErrs = append(\n\t\t\tallErrs,\n\t\t\tfield.Invalid(\n\t\t\t\tfieldPath,\n\t\t\t\tresources,\n\t\t\t\toverlapErr,\n\t\t\t),\n\t\t)\n\t}\n\n\treturn allErrs\n}","line":{"from":123,"to":191}} {"id":100016841,"name":"validateResourceNames","signature":"func validateResourceNames(resources []string, fieldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/apis/config/validation/validation.go","code":"func validateResourceNames(resources []string, fieldPath *field.Path) field.ErrorList {\n\tvar allErrs field.ErrorList\n\n\tfor j, res := range resources {\n\t\tjj := fieldPath.Index(j)\n\n\t\t// check if resource name has capital letters\n\t\tif hasCapital(res) {\n\t\t\tallErrs = append(\n\t\t\t\tallErrs,\n\t\t\t\tfield.Invalid(\n\t\t\t\t\tjj,\n\t\t\t\t\tresources[j],\n\t\t\t\t\tresourceNameErr,\n\t\t\t\t),\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\n\t\t// check if resource is '*'\n\t\tif res == \"*\" {\n\t\t\tallErrs = append(\n\t\t\t\tallErrs,\n\t\t\t\tfield.Invalid(\n\t\t\t\t\tjj,\n\t\t\t\t\tresources[j],\n\t\t\t\t\tstarResourceErr,\n\t\t\t\t),\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\n\t\t// check if resource is:\n\t\t// 'apiserveripinfo' OR\n\t\t// 'serviceipallocations' OR\n\t\t// 'servicenodeportallocations' OR\n\t\tif res == \"apiserveripinfo\" ||\n\t\t\tres == \"serviceipallocations\" ||\n\t\t\tres == \"servicenodeportallocations\" {\n\t\t\tallErrs = append(\n\t\t\t\tallErrs,\n\t\t\t\tfield.Invalid(\n\t\t\t\t\tjj,\n\t\t\t\t\tresources[j],\n\t\t\t\t\tnonRESTAPIResourceErr,\n\t\t\t\t),\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\n\t\t// check if group is 'events.k8s.io'\n\t\tgr := schema.ParseGroupResource(res)\n\t\tif gr.Group == \"events.k8s.io\" {\n\t\t\tallErrs = append(\n\t\t\t\tallErrs,\n\t\t\t\tfield.Invalid(\n\t\t\t\t\tjj,\n\t\t\t\t\tresources[j],\n\t\t\t\t\teventsGroupErr,\n\t\t\t\t),\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\n\t\t// check if group is 'extensions'\n\t\tif gr.Group == \"extensions\" {\n\t\t\tallErrs = append(\n\t\t\t\tallErrs,\n\t\t\t\tfield.Invalid(\n\t\t\t\t\tjj,\n\t\t\t\t\tresources[j],\n\t\t\t\t\textensionsGroupErr,\n\t\t\t\t),\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\n\t\t// disallow resource.* as encrypting the same resource across groups does not make sense\n\t\tif gr.Group == \"*\" \u0026\u0026 gr.Resource != \"*\" {\n\t\t\tallErrs = append(\n\t\t\t\tallErrs,\n\t\t\t\tfield.Invalid(\n\t\t\t\t\tjj,\n\t\t\t\t\tresources[j],\n\t\t\t\t\tresourceAcrossGroupErr,\n\t\t\t\t),\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":193,"to":285}} {"id":100016842,"name":"validateSingleProvider","signature":"func validateSingleProvider(provider config.ProviderConfiguration, fieldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/apis/config/validation/validation.go","code":"func validateSingleProvider(provider config.ProviderConfiguration, fieldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfound := 0\n\n\tif provider.KMS != nil {\n\t\tfound++\n\t}\n\tif provider.AESGCM != nil {\n\t\tfound++\n\t}\n\tif provider.AESCBC != nil {\n\t\tfound++\n\t}\n\tif provider.Secretbox != nil {\n\t\tfound++\n\t}\n\tif provider.Identity != nil {\n\t\tfound++\n\t}\n\n\tif found == 0 {\n\t\treturn append(allErrs, field.Invalid(fieldPath, provider, \"provider does not contain any of the expected providers: KMS, AESGCM, AESCBC, Secretbox, Identity\"))\n\t}\n\n\tif found \u003e 1 {\n\t\treturn append(allErrs, field.Invalid(fieldPath, provider, moreThanOneElementErr))\n\t}\n\n\treturn allErrs\n}","line":{"from":287,"to":316}} {"id":100016843,"name":"validateKeys","signature":"func validateKeys(keys []config.Key, fieldPath *field.Path, expectedLen []int) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/apis/config/validation/validation.go","code":"func validateKeys(keys []config.Key, fieldPath *field.Path, expectedLen []int) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(keys) == 0 {\n\t\tallErrs = append(allErrs, field.Required(fieldPath, fmt.Sprintf(atLeastOneRequiredErrFmt, \"keys\")))\n\t\treturn allErrs\n\t}\n\n\tfor i, key := range keys {\n\t\tallErrs = append(allErrs, validateKey(key, fieldPath.Index(i), expectedLen)...)\n\t}\n\n\treturn allErrs\n}","line":{"from":318,"to":331}} {"id":100016844,"name":"validateKey","signature":"func validateKey(key config.Key, fieldPath *field.Path, expectedLen []int) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/apis/config/validation/validation.go","code":"func validateKey(key config.Key, fieldPath *field.Path, expectedLen []int) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif key.Name == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fieldPath.Child(\"name\"), fmt.Sprintf(mandatoryFieldErrFmt, \"name\", \"key\")))\n\t}\n\n\tif key.Secret == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fieldPath.Child(\"secret\"), fmt.Sprintf(mandatoryFieldErrFmt, \"secret\", \"key\")))\n\t\treturn allErrs\n\t}\n\n\tsecret, err := base64.StdEncoding.DecodeString(key.Secret)\n\tif err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fieldPath.Child(\"secret\"), \"REDACTED\", base64EncodingErr))\n\t\treturn allErrs\n\t}\n\n\tlenMatched := false\n\tfor _, l := range expectedLen {\n\t\tif len(secret) == l {\n\t\t\tlenMatched = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !lenMatched {\n\t\tallErrs = append(allErrs, field.Invalid(fieldPath.Child(\"secret\"), \"REDACTED\", fmt.Sprintf(keyLenErrFmt, len(secret), expectedLen)))\n\t}\n\n\treturn allErrs\n}","line":{"from":333,"to":364}} {"id":100016845,"name":"validateKMSConfiguration","signature":"func validateKMSConfiguration(c *config.KMSConfiguration, fieldPath *field.Path, kmsProviderNames sets.String, reload bool) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/apis/config/validation/validation.go","code":"func validateKMSConfiguration(c *config.KMSConfiguration, fieldPath *field.Path, kmsProviderNames sets.String, reload bool) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tallErrs = append(allErrs, validateKMSConfigName(c, fieldPath.Child(\"name\"), kmsProviderNames, reload)...)\n\tallErrs = append(allErrs, validateKMSTimeout(c, fieldPath.Child(\"timeout\"))...)\n\tallErrs = append(allErrs, validateKMSEndpoint(c, fieldPath.Child(\"endpoint\"))...)\n\tallErrs = append(allErrs, validateKMSCacheSize(c, fieldPath.Child(\"cachesize\"))...)\n\tallErrs = append(allErrs, validateKMSAPIVersion(c, fieldPath.Child(\"apiVersion\"))...)\n\treturn allErrs\n}","line":{"from":366,"to":375}} {"id":100016846,"name":"validateKMSCacheSize","signature":"func validateKMSCacheSize(c *config.KMSConfiguration, fieldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/apis/config/validation/validation.go","code":"func validateKMSCacheSize(c *config.KMSConfiguration, fieldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\t// In defaulting, we set the cache size to the default value only when API version is v1.\n\t// So, for v2 API version, we expect the cache size field to be nil.\n\tif c.APIVersion != \"v1\" \u0026\u0026 c.CacheSize != nil {\n\t\tallErrs = append(allErrs, field.Invalid(fieldPath, *c.CacheSize, \"cachesize is not supported in v2\"))\n\t}\n\tif c.APIVersion == \"v1\" \u0026\u0026 *c.CacheSize == 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fieldPath, *c.CacheSize, fmt.Sprintf(nonZeroErrFmt, \"cachesize\")))\n\t}\n\n\treturn allErrs\n}","line":{"from":377,"to":390}} {"id":100016847,"name":"validateKMSTimeout","signature":"func validateKMSTimeout(c *config.KMSConfiguration, fieldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/apis/config/validation/validation.go","code":"func validateKMSTimeout(c *config.KMSConfiguration, fieldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif c.Timeout.Duration \u003c= 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fieldPath, c.Timeout, fmt.Sprintf(zeroOrNegativeErrFmt, \"timeout\")))\n\t}\n\n\treturn allErrs\n}","line":{"from":392,"to":399}} {"id":100016848,"name":"validateKMSEndpoint","signature":"func validateKMSEndpoint(c *config.KMSConfiguration, fieldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/apis/config/validation/validation.go","code":"func validateKMSEndpoint(c *config.KMSConfiguration, fieldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif len(c.Endpoint) == 0 {\n\t\treturn append(allErrs, field.Invalid(fieldPath, \"\", fmt.Sprintf(mandatoryFieldErrFmt, \"endpoint\", \"kms\")))\n\t}\n\n\tu, err := url.Parse(c.Endpoint)\n\tif err != nil {\n\t\treturn append(allErrs, field.Invalid(fieldPath, c.Endpoint, fmt.Sprintf(invalidURLErrFmt, err)))\n\t}\n\n\tif u.Scheme != \"unix\" {\n\t\treturn append(allErrs, field.Invalid(fieldPath, c.Endpoint, fmt.Sprintf(unsupportedSchemeErrFmt, u.Scheme)))\n\t}\n\n\treturn allErrs\n}","line":{"from":401,"to":417}} {"id":100016849,"name":"validateKMSAPIVersion","signature":"func validateKMSAPIVersion(c *config.KMSConfiguration, fieldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/apis/config/validation/validation.go","code":"func validateKMSAPIVersion(c *config.KMSConfiguration, fieldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif c.APIVersion != \"v1\" \u0026\u0026 c.APIVersion != \"v2\" {\n\t\tallErrs = append(allErrs, field.Invalid(fieldPath, c.APIVersion, fmt.Sprintf(unsupportedKMSAPIVersionErrFmt, \"apiVersion\")))\n\t}\n\n\treturn allErrs\n}","line":{"from":419,"to":426}} {"id":100016850,"name":"validateKMSConfigName","signature":"func validateKMSConfigName(c *config.KMSConfiguration, fieldPath *field.Path, kmsProviderNames sets.String, reload bool) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/apis/config/validation/validation.go","code":"func validateKMSConfigName(c *config.KMSConfiguration, fieldPath *field.Path, kmsProviderNames sets.String, reload bool) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif c.Name == \"\" {\n\t\tallErrs = append(allErrs, field.Required(fieldPath, fmt.Sprintf(mandatoryFieldErrFmt, \"name\", \"provider\")))\n\t}\n\n\t// kms v2 providers are not allowed to have a \":\" in their name\n\tif c.APIVersion != \"v1\" \u0026\u0026 strings.Contains(c.Name, \":\") {\n\t\tallErrs = append(allErrs, field.Invalid(fieldPath, c.Name, fmt.Sprintf(invalidKMSConfigNameErrFmt, c.Name)))\n\t}\n\n\t// kms v2 providers name must always be unique across all kms providers (v1 and v2)\n\t// kms v1 provider names must be unique across all kms providers (v1 and v2) when hot reloading of encryption configuration is enabled (reload=true)\n\tif reload || c.APIVersion != \"v1\" {\n\t\tif kmsProviderNames.Has(c.Name) {\n\t\t\tallErrs = append(allErrs, field.Invalid(fieldPath, c.Name, fmt.Sprintf(duplicateKMSConfigNameErrFmt, c.Name)))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":428,"to":448}} {"id":100016851,"name":"hasCapital","signature":"func hasCapital(input string) bool","file":"staging/src/k8s.io/apiserver/pkg/apis/config/validation/validation.go","code":"func hasCapital(input string) bool {\n\treturn strings.ToLower(input) != input\n}","line":{"from":450,"to":452}} {"id":100016852,"name":"newPriorityLevelConfiguration","signature":"func newPriorityLevelConfiguration(name string, spec flowcontrol.PriorityLevelConfigurationSpec) *flowcontrol.PriorityLevelConfiguration","file":"staging/src/k8s.io/apiserver/pkg/apis/flowcontrol/bootstrap/default.go","code":"func newPriorityLevelConfiguration(name string, spec flowcontrol.PriorityLevelConfigurationSpec) *flowcontrol.PriorityLevelConfiguration {\n\treturn \u0026flowcontrol.PriorityLevelConfiguration{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tAnnotations: map[string]string{\n\t\t\t\tflowcontrol.AutoUpdateAnnotationKey: \"true\",\n\t\t\t},\n\t\t},\n\t\tSpec: spec,\n\t}\n}","line":{"from":486,"to":496}} {"id":100016853,"name":"newFlowSchema","signature":"func newFlowSchema(name, plName string, matchingPrecedence int32, dmType flowcontrol.FlowDistinguisherMethodType, rules ...flowcontrol.PolicyRulesWithSubjects) *flowcontrol.FlowSchema","file":"staging/src/k8s.io/apiserver/pkg/apis/flowcontrol/bootstrap/default.go","code":"func newFlowSchema(name, plName string, matchingPrecedence int32, dmType flowcontrol.FlowDistinguisherMethodType, rules ...flowcontrol.PolicyRulesWithSubjects) *flowcontrol.FlowSchema {\n\tvar dm *flowcontrol.FlowDistinguisherMethod\n\tif dmType != \"\" {\n\t\tdm = \u0026flowcontrol.FlowDistinguisherMethod{Type: dmType}\n\t}\n\treturn \u0026flowcontrol.FlowSchema{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tAnnotations: map[string]string{\n\t\t\t\tflowcontrol.AutoUpdateAnnotationKey: \"true\",\n\t\t\t},\n\t\t},\n\t\tSpec: flowcontrol.FlowSchemaSpec{\n\t\t\tPriorityLevelConfiguration: flowcontrol.PriorityLevelConfigurationReference{\n\t\t\t\tName: plName,\n\t\t\t},\n\t\t\tMatchingPrecedence: matchingPrecedence,\n\t\t\tDistinguisherMethod: dm,\n\t\t\tRules: rules},\n\t}\n\n}","line":{"from":498,"to":519}} {"id":100016854,"name":"groups","signature":"func groups(names ...string) []flowcontrol.Subject","file":"staging/src/k8s.io/apiserver/pkg/apis/flowcontrol/bootstrap/default.go","code":"func groups(names ...string) []flowcontrol.Subject {\n\tans := make([]flowcontrol.Subject, len(names))\n\tfor idx, name := range names {\n\t\tans[idx] = flowcontrol.Subject{\n\t\t\tKind: flowcontrol.SubjectKindGroup,\n\t\t\tGroup: \u0026flowcontrol.GroupSubject{\n\t\t\t\tName: name,\n\t\t\t},\n\t\t}\n\t}\n\treturn ans\n}","line":{"from":521,"to":532}} {"id":100016855,"name":"users","signature":"func users(names ...string) []flowcontrol.Subject","file":"staging/src/k8s.io/apiserver/pkg/apis/flowcontrol/bootstrap/default.go","code":"func users(names ...string) []flowcontrol.Subject {\n\tans := make([]flowcontrol.Subject, len(names))\n\tfor idx, name := range names {\n\t\tans[idx] = flowcontrol.Subject{\n\t\t\tKind: flowcontrol.SubjectKindUser,\n\t\t\tUser: \u0026flowcontrol.UserSubject{\n\t\t\t\tName: name,\n\t\t\t},\n\t\t}\n\t}\n\treturn ans\n}","line":{"from":534,"to":545}} {"id":100016856,"name":"kubeSystemServiceAccount","signature":"func kubeSystemServiceAccount(names ...string) []flowcontrol.Subject","file":"staging/src/k8s.io/apiserver/pkg/apis/flowcontrol/bootstrap/default.go","code":"func kubeSystemServiceAccount(names ...string) []flowcontrol.Subject {\n\tsubjects := []flowcontrol.Subject{}\n\tfor _, name := range names {\n\t\tsubjects = append(subjects, flowcontrol.Subject{\n\t\t\tKind: flowcontrol.SubjectKindServiceAccount,\n\t\t\tServiceAccount: \u0026flowcontrol.ServiceAccountSubject{\n\t\t\t\tName: name,\n\t\t\t\tNamespace: metav1.NamespaceSystem,\n\t\t\t},\n\t\t})\n\t}\n\treturn subjects\n}","line":{"from":547,"to":559}} {"id":100016857,"name":"resourceRule","signature":"func resourceRule(verbs []string, groups []string, resources []string, namespaces []string, clusterScoped bool) flowcontrol.ResourcePolicyRule","file":"staging/src/k8s.io/apiserver/pkg/apis/flowcontrol/bootstrap/default.go","code":"func resourceRule(verbs []string, groups []string, resources []string, namespaces []string, clusterScoped bool) flowcontrol.ResourcePolicyRule {\n\treturn flowcontrol.ResourcePolicyRule{\n\t\tVerbs: verbs,\n\t\tAPIGroups: groups,\n\t\tResources: resources,\n\t\tNamespaces: namespaces,\n\t\tClusterScope: clusterScoped,\n\t}\n}","line":{"from":561,"to":569}} {"id":100016858,"name":"nonResourceRule","signature":"func nonResourceRule(verbs []string, nonResourceURLs []string) flowcontrol.NonResourcePolicyRule","file":"staging/src/k8s.io/apiserver/pkg/apis/flowcontrol/bootstrap/default.go","code":"func nonResourceRule(verbs []string, nonResourceURLs []string) flowcontrol.NonResourcePolicyRule {\n\treturn flowcontrol.NonResourcePolicyRule{Verbs: verbs, NonResourceURLs: nonResourceURLs}\n}","line":{"from":571,"to":573}} {"id":100016859,"name":"AddAuditAnnotation","signature":"func AddAuditAnnotation(ctx context.Context, key, value string)","file":"staging/src/k8s.io/apiserver/pkg/audit/context.go","code":"// AddAuditAnnotation sets the audit annotation for the given key, value pair.\n// It is safe to call at most parts of request flow that come after WithAuditAnnotations.\n// The notable exception being that this function must not be called via a\n// defer statement (i.e. after ServeHTTP) in a handler that runs before WithAudit\n// as at that point the audit event has already been sent to the audit sink.\n// Handlers that are unaware of their position in the overall request flow should\n// prefer AddAuditAnnotation over LogAnnotation to avoid dropping annotations.\nfunc AddAuditAnnotation(ctx context.Context, key, value string) {\n\tac := AuditContextFrom(ctx)\n\tif ac == nil {\n\t\t// auditing is not enabled\n\t\treturn\n\t}\n\n\tac.annotationMutex.Lock()\n\tdefer ac.annotationMutex.Unlock()\n\n\taddAuditAnnotationLocked(ac, key, value)\n}","line":{"from":59,"to":77}} {"id":100016860,"name":"AddAuditAnnotations","signature":"func AddAuditAnnotations(ctx context.Context, keysAndValues ...string)","file":"staging/src/k8s.io/apiserver/pkg/audit/context.go","code":"// AddAuditAnnotations is a bulk version of AddAuditAnnotation. Refer to AddAuditAnnotation for\n// restrictions on when this can be called.\n// keysAndValues are the key-value pairs to add, and must have an even number of items.\nfunc AddAuditAnnotations(ctx context.Context, keysAndValues ...string) {\n\tac := AuditContextFrom(ctx)\n\tif ac == nil {\n\t\t// auditing is not enabled\n\t\treturn\n\t}\n\n\tac.annotationMutex.Lock()\n\tdefer ac.annotationMutex.Unlock()\n\n\tif len(keysAndValues)%2 != 0 {\n\t\tklog.Errorf(\"Dropping mismatched audit annotation %q\", keysAndValues[len(keysAndValues)-1])\n\t}\n\tfor i := 0; i \u003c len(keysAndValues); i += 2 {\n\t\taddAuditAnnotationLocked(ac, keysAndValues[i], keysAndValues[i+1])\n\t}\n}","line":{"from":79,"to":98}} {"id":100016861,"name":"AddAuditAnnotationsMap","signature":"func AddAuditAnnotationsMap(ctx context.Context, annotations map[string]string)","file":"staging/src/k8s.io/apiserver/pkg/audit/context.go","code":"// AddAuditAnnotationsMap is a bulk version of AddAuditAnnotation. Refer to AddAuditAnnotation for\n// restrictions on when this can be called.\nfunc AddAuditAnnotationsMap(ctx context.Context, annotations map[string]string) {\n\tac := AuditContextFrom(ctx)\n\tif ac == nil {\n\t\t// auditing is not enabled\n\t\treturn\n\t}\n\n\tac.annotationMutex.Lock()\n\tdefer ac.annotationMutex.Unlock()\n\n\tfor k, v := range annotations {\n\t\taddAuditAnnotationLocked(ac, k, v)\n\t}\n}","line":{"from":100,"to":115}} {"id":100016862,"name":"addAuditAnnotationLocked","signature":"func addAuditAnnotationLocked(ac *AuditContext, key, value string)","file":"staging/src/k8s.io/apiserver/pkg/audit/context.go","code":"// addAuditAnnotationLocked is the shared code for recording an audit annotation. This method should\n// only be called while the auditAnnotationsMutex is locked.\nfunc addAuditAnnotationLocked(ac *AuditContext, key, value string) {\n\tif ac.Event != nil {\n\t\tlogAnnotation(ac.Event, key, value)\n\t} else {\n\t\tac.annotations = append(ac.annotations, annotation{key: key, value: value})\n\t}\n}","line":{"from":117,"to":125}} {"id":100016863,"name":"addAuditAnnotationsFrom","signature":"func addAuditAnnotationsFrom(ctx context.Context, ev *auditinternal.Event)","file":"staging/src/k8s.io/apiserver/pkg/audit/context.go","code":"// This is private to prevent reads/write to the slice from outside of this package.\n// The audit event should be directly read to get access to the annotations.\nfunc addAuditAnnotationsFrom(ctx context.Context, ev *auditinternal.Event) {\n\tac := AuditContextFrom(ctx)\n\tif ac == nil {\n\t\t// auditing is not enabled\n\t\treturn\n\t}\n\n\tac.annotationMutex.Lock()\n\tdefer ac.annotationMutex.Unlock()\n\n\tfor _, kv := range ac.annotations {\n\t\tlogAnnotation(ev, kv.key, kv.value)\n\t}\n}","line":{"from":127,"to":142}} {"id":100016864,"name":"logAnnotation","signature":"func logAnnotation(ae *auditinternal.Event, key, value string)","file":"staging/src/k8s.io/apiserver/pkg/audit/context.go","code":"// LogAnnotation fills in the Annotations according to the key value pair.\nfunc logAnnotation(ae *auditinternal.Event, key, value string) {\n\tif ae == nil || ae.Level.Less(auditinternal.LevelMetadata) {\n\t\treturn\n\t}\n\tif ae.Annotations == nil {\n\t\tae.Annotations = make(map[string]string)\n\t}\n\tif v, ok := ae.Annotations[key]; ok \u0026\u0026 v != value {\n\t\tklog.Warningf(\"Failed to set annotations[%q] to %q for audit:%q, it has already been set to %q\", key, value, ae.AuditID, ae.Annotations[key])\n\t\treturn\n\t}\n\tae.Annotations[key] = value\n}","line":{"from":144,"to":157}} {"id":100016865,"name":"WithAuditContext","signature":"func WithAuditContext(parent context.Context) context.Context","file":"staging/src/k8s.io/apiserver/pkg/audit/context.go","code":"// WithAuditContext returns a new context that stores the AuditContext.\nfunc WithAuditContext(parent context.Context) context.Context {\n\tif AuditContextFrom(parent) != nil {\n\t\treturn parent // Avoid double registering.\n\t}\n\n\treturn genericapirequest.WithValue(parent, auditKey, \u0026AuditContext{})\n}","line":{"from":159,"to":166}} {"id":100016866,"name":"AuditEventFrom","signature":"func AuditEventFrom(ctx context.Context) *auditinternal.Event","file":"staging/src/k8s.io/apiserver/pkg/audit/context.go","code":"// AuditEventFrom returns the audit event struct on the ctx\nfunc AuditEventFrom(ctx context.Context) *auditinternal.Event {\n\tif o := AuditContextFrom(ctx); o != nil {\n\t\treturn o.Event\n\t}\n\treturn nil\n}","line":{"from":168,"to":174}} {"id":100016867,"name":"AuditContextFrom","signature":"func AuditContextFrom(ctx context.Context) *AuditContext","file":"staging/src/k8s.io/apiserver/pkg/audit/context.go","code":"// AuditContextFrom returns the pair of the audit configuration object\n// that applies to the given request and the audit event that is going to\n// be written to the API audit log.\nfunc AuditContextFrom(ctx context.Context) *AuditContext {\n\tev, _ := ctx.Value(auditKey).(*AuditContext)\n\treturn ev\n}","line":{"from":176,"to":182}} {"id":100016868,"name":"WithAuditID","signature":"func WithAuditID(ctx context.Context, auditID types.UID)","file":"staging/src/k8s.io/apiserver/pkg/audit/context.go","code":"// WithAuditID sets the AuditID on the AuditContext. The AuditContext must already be present in the\n// request context. If the specified auditID is empty, no value is set.\nfunc WithAuditID(ctx context.Context, auditID types.UID) {\n\tif auditID == \"\" {\n\t\treturn\n\t}\n\tac := AuditContextFrom(ctx)\n\tif ac == nil {\n\t\treturn\n\t}\n\tac.auditID = auditID\n\tif ac.Event != nil {\n\t\tac.Event.AuditID = auditID\n\t}\n}","line":{"from":184,"to":198}} {"id":100016869,"name":"AuditIDFrom","signature":"func AuditIDFrom(ctx context.Context) (types.UID, bool)","file":"staging/src/k8s.io/apiserver/pkg/audit/context.go","code":"// AuditIDFrom returns the value of the audit ID from the request context.\nfunc AuditIDFrom(ctx context.Context) (types.UID, bool) {\n\tif ac := AuditContextFrom(ctx); ac != nil {\n\t\treturn ac.auditID, ac.auditID != \"\"\n\t}\n\treturn \"\", false\n}","line":{"from":200,"to":206}} {"id":100016870,"name":"GetAuditIDTruncated","signature":"func GetAuditIDTruncated(ctx context.Context) string","file":"staging/src/k8s.io/apiserver/pkg/audit/context.go","code":"// GetAuditIDTruncated returns the audit ID (truncated) from the request context.\n// If the length of the Audit-ID value exceeds the limit, we truncate it to keep\n// the first N (maxAuditIDLength) characters.\n// This is intended to be used in logging only.\nfunc GetAuditIDTruncated(ctx context.Context) string {\n\tauditID, ok := AuditIDFrom(ctx)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\n\t// if the user has specified a very long audit ID then we will use the first N characters\n\t// Note: assuming Audit-ID header is in ASCII\n\tconst maxAuditIDLength = 64\n\tif len(auditID) \u003e maxAuditIDLength {\n\t\tauditID = auditID[:maxAuditIDLength]\n\t}\n\n\treturn string(auditID)\n}","line":{"from":208,"to":226}} {"id":100016871,"name":"EventString","signature":"func EventString(ev *auditinternal.Event) string","file":"staging/src/k8s.io/apiserver/pkg/audit/format.go","code":"// EventString creates a 1-line text representation of an audit event, using a subset of the\n// information in the event struct.\nfunc EventString(ev *auditinternal.Event) string {\n\tusername := \"\u003cnone\u003e\"\n\tgroups := \"\u003cnone\u003e\"\n\tif len(ev.User.Username) \u003e 0 {\n\t\tusername = ev.User.Username\n\t\tif len(ev.User.Groups) \u003e 0 {\n\t\t\tgroups = auditStringSlice(ev.User.Groups)\n\t\t}\n\t}\n\tasuser := \"\u003cself\u003e\"\n\tasgroups := \"\u003clookup\u003e\"\n\tif ev.ImpersonatedUser != nil {\n\t\tasuser = ev.ImpersonatedUser.Username\n\t\tif ev.ImpersonatedUser.Groups != nil {\n\t\t\tasgroups = auditStringSlice(ev.ImpersonatedUser.Groups)\n\t\t}\n\t}\n\n\tnamespace := \"\u003cnone\u003e\"\n\tif ev.ObjectRef != nil \u0026\u0026 len(ev.ObjectRef.Namespace) != 0 {\n\t\tnamespace = ev.ObjectRef.Namespace\n\t}\n\n\tresponse := \"\u003cdeferred\u003e\"\n\tif ev.ResponseStatus != nil {\n\t\tresponse = strconv.Itoa(int(ev.ResponseStatus.Code))\n\t}\n\n\tip := \"\u003cunknown\u003e\"\n\tif len(ev.SourceIPs) \u003e 0 {\n\t\tip = ev.SourceIPs[0]\n\t}\n\n\treturn fmt.Sprintf(\"%s AUDIT: id=%q stage=%q ip=%q method=%q user=%q groups=%q as=%q asgroups=%q user-agent=%q namespace=%q uri=%q response=\\\"%s\\\"\",\n\t\tev.RequestReceivedTimestamp.Format(time.RFC3339Nano), ev.AuditID, ev.Stage, ip, ev.Verb, username, groups, asuser, asgroups, ev.UserAgent, namespace, ev.RequestURI, response)\n}","line":{"from":28,"to":65}} {"id":100016872,"name":"auditStringSlice","signature":"func auditStringSlice(inList []string) string","file":"staging/src/k8s.io/apiserver/pkg/audit/format.go","code":"func auditStringSlice(inList []string) string {\n\tquotedElements := make([]string, len(inList))\n\tfor i, in := range inList {\n\t\tquotedElements[i] = fmt.Sprintf(\"%q\", in)\n\t}\n\treturn strings.Join(quotedElements, \",\")\n}","line":{"from":67,"to":73}} {"id":100016873,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/audit/metrics.go","code":"func init() {\n\tlegacyregistry.MustRegister(eventCounter)\n\tlegacyregistry.MustRegister(errorCounter)\n\tlegacyregistry.MustRegister(levelCounter)\n\tlegacyregistry.MustRegister(ApiserverAuditDroppedCounter)\n}","line":{"from":80,"to":85}} {"id":100016874,"name":"ObserveEvent","signature":"func ObserveEvent(ctx context.Context)","file":"staging/src/k8s.io/apiserver/pkg/audit/metrics.go","code":"// ObserveEvent updates the relevant prometheus metrics for the generated audit event.\nfunc ObserveEvent(ctx context.Context) {\n\teventCounter.WithContext(ctx).Inc()\n}","line":{"from":87,"to":90}} {"id":100016875,"name":"ObservePolicyLevel","signature":"func ObservePolicyLevel(ctx context.Context, level auditinternal.Level)","file":"staging/src/k8s.io/apiserver/pkg/audit/metrics.go","code":"// ObservePolicyLevel updates the relevant prometheus metrics with the audit level for a request.\nfunc ObservePolicyLevel(ctx context.Context, level auditinternal.Level) {\n\tlevelCounter.WithContext(ctx).WithLabelValues(string(level)).Inc()\n}","line":{"from":92,"to":95}} {"id":100016876,"name":"HandlePluginError","signature":"func HandlePluginError(plugin string, err error, impacted ...*auditinternal.Event)","file":"staging/src/k8s.io/apiserver/pkg/audit/metrics.go","code":"// HandlePluginError handles an error that occurred in an audit plugin. This method should only be\n// used if the error may have prevented the audit event from being properly recorded. The events are\n// logged to the debug log.\nfunc HandlePluginError(plugin string, err error, impacted ...*auditinternal.Event) {\n\t// Count the error.\n\terrorCounter.WithLabelValues(plugin).Add(float64(len(impacted)))\n\n\t// Log the audit events to the debug log.\n\tmsg := fmt.Sprintf(\"Error in audit plugin '%s' affecting %d audit events: %v\\nImpacted events:\\n\",\n\t\tplugin, len(impacted), err)\n\tfor _, ev := range impacted {\n\t\tmsg = msg + EventString(ev) + \"\\n\"\n\t}\n\tklog.Error(msg)\n}","line":{"from":97,"to":111}} {"id":100016877,"name":"NewPolicyRuleEvaluator","signature":"func NewPolicyRuleEvaluator(policy *audit.Policy) auditinternal.PolicyRuleEvaluator","file":"staging/src/k8s.io/apiserver/pkg/audit/policy/checker.go","code":"// NewPolicyRuleEvaluator creates a new policy rule evaluator.\nfunc NewPolicyRuleEvaluator(policy *audit.Policy) auditinternal.PolicyRuleEvaluator {\n\tfor i, rule := range policy.Rules {\n\t\tpolicy.Rules[i].OmitStages = unionStages(policy.OmitStages, rule.OmitStages)\n\t}\n\treturn \u0026policyRuleEvaluator{*policy}\n}","line":{"from":32,"to":38}} {"id":100016878,"name":"unionStages","signature":"func unionStages(stageLists ...[]audit.Stage) []audit.Stage","file":"staging/src/k8s.io/apiserver/pkg/audit/policy/checker.go","code":"func unionStages(stageLists ...[]audit.Stage) []audit.Stage {\n\tm := make(map[audit.Stage]bool)\n\tfor _, sl := range stageLists {\n\t\tfor _, s := range sl {\n\t\t\tm[s] = true\n\t\t}\n\t}\n\tresult := make([]audit.Stage, 0, len(m))\n\tfor key := range m {\n\t\tresult = append(result, key)\n\t}\n\treturn result\n}","line":{"from":40,"to":52}} {"id":100016879,"name":"NewFakePolicyRuleEvaluator","signature":"func NewFakePolicyRuleEvaluator(level audit.Level, stage []audit.Stage) auditinternal.PolicyRuleEvaluator","file":"staging/src/k8s.io/apiserver/pkg/audit/policy/checker.go","code":"// NewFakePolicyRuleEvaluator creates a fake policy rule evaluator that returns\n// a constant level for all requests (for testing).\nfunc NewFakePolicyRuleEvaluator(level audit.Level, stage []audit.Stage) auditinternal.PolicyRuleEvaluator {\n\treturn \u0026fakePolicyRuleEvaluator{level, stage}\n}","line":{"from":54,"to":58}} {"id":100016880,"name":"EvaluatePolicyRule","signature":"func (p *policyRuleEvaluator) EvaluatePolicyRule(attrs authorizer.Attributes) auditinternal.RequestAuditConfig","file":"staging/src/k8s.io/apiserver/pkg/audit/policy/checker.go","code":"func (p *policyRuleEvaluator) EvaluatePolicyRule(attrs authorizer.Attributes) auditinternal.RequestAuditConfig {\n\tfor _, rule := range p.Rules {\n\t\tif ruleMatches(\u0026rule, attrs) {\n\t\t\treturn auditinternal.RequestAuditConfig{\n\t\t\t\tLevel: rule.Level,\n\t\t\t\tOmitStages: rule.OmitStages,\n\t\t\t\tOmitManagedFields: isOmitManagedFields(\u0026rule, p.OmitManagedFields),\n\t\t\t}\n\t\t}\n\t}\n\n\treturn auditinternal.RequestAuditConfig{\n\t\tLevel: DefaultAuditLevel,\n\t\tOmitStages: p.OmitStages,\n\t\tOmitManagedFields: p.OmitManagedFields,\n\t}\n}","line":{"from":64,"to":80}} {"id":100016881,"name":"isOmitManagedFields","signature":"func isOmitManagedFields(policyRule *audit.PolicyRule, policyDefault bool) bool","file":"staging/src/k8s.io/apiserver/pkg/audit/policy/checker.go","code":"// isOmitManagedFields returns whether to omit managed fields from the request\n// and response bodies from being written to the API audit log.\n// If a user specifies OmitManagedFields inside a policy rule, that overrides\n// the global policy default in Policy.OmitManagedFields.\nfunc isOmitManagedFields(policyRule *audit.PolicyRule, policyDefault bool) bool {\n\tif policyRule.OmitManagedFields == nil {\n\t\treturn policyDefault\n\t}\n\n\treturn *policyRule.OmitManagedFields\n}","line":{"from":82,"to":92}} {"id":100016882,"name":"ruleMatches","signature":"func ruleMatches(r *audit.PolicyRule, attrs authorizer.Attributes) bool","file":"staging/src/k8s.io/apiserver/pkg/audit/policy/checker.go","code":"// Check whether the rule matches the request attrs.\nfunc ruleMatches(r *audit.PolicyRule, attrs authorizer.Attributes) bool {\n\tuser := attrs.GetUser()\n\tif len(r.Users) \u003e 0 {\n\t\tif user == nil || !hasString(r.Users, user.GetName()) {\n\t\t\treturn false\n\t\t}\n\t}\n\tif len(r.UserGroups) \u003e 0 {\n\t\tif user == nil {\n\t\t\treturn false\n\t\t}\n\t\tmatched := false\n\t\tfor _, group := range user.GetGroups() {\n\t\t\tif hasString(r.UserGroups, group) {\n\t\t\t\tmatched = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !matched {\n\t\t\treturn false\n\t\t}\n\t}\n\tif len(r.Verbs) \u003e 0 {\n\t\tif !hasString(r.Verbs, attrs.GetVerb()) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif len(r.Namespaces) \u003e 0 || len(r.Resources) \u003e 0 {\n\t\treturn ruleMatchesResource(r, attrs)\n\t}\n\n\tif len(r.NonResourceURLs) \u003e 0 {\n\t\treturn ruleMatchesNonResource(r, attrs)\n\t}\n\n\treturn true\n}","line":{"from":94,"to":132}} {"id":100016883,"name":"ruleMatchesNonResource","signature":"func ruleMatchesNonResource(r *audit.PolicyRule, attrs authorizer.Attributes) bool","file":"staging/src/k8s.io/apiserver/pkg/audit/policy/checker.go","code":"// Check whether the rule's non-resource URLs match the request attrs.\nfunc ruleMatchesNonResource(r *audit.PolicyRule, attrs authorizer.Attributes) bool {\n\tif attrs.IsResourceRequest() {\n\t\treturn false\n\t}\n\n\tpath := attrs.GetPath()\n\tfor _, spec := range r.NonResourceURLs {\n\t\tif pathMatches(path, spec) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":134,"to":148}} {"id":100016884,"name":"pathMatches","signature":"func pathMatches(path, spec string) bool","file":"staging/src/k8s.io/apiserver/pkg/audit/policy/checker.go","code":"// Check whether the path matches the path specification.\nfunc pathMatches(path, spec string) bool {\n\t// Allow wildcard match\n\tif spec == \"*\" {\n\t\treturn true\n\t}\n\t// Allow exact match\n\tif spec == path {\n\t\treturn true\n\t}\n\t// Allow a trailing * subpath match\n\tif strings.HasSuffix(spec, \"*\") \u0026\u0026 strings.HasPrefix(path, strings.TrimRight(spec, \"*\")) {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":150,"to":165}} {"id":100016885,"name":"ruleMatchesResource","signature":"func ruleMatchesResource(r *audit.PolicyRule, attrs authorizer.Attributes) bool","file":"staging/src/k8s.io/apiserver/pkg/audit/policy/checker.go","code":"// Check whether the rule's resource fields match the request attrs.\nfunc ruleMatchesResource(r *audit.PolicyRule, attrs authorizer.Attributes) bool {\n\tif !attrs.IsResourceRequest() {\n\t\treturn false\n\t}\n\n\tif len(r.Namespaces) \u003e 0 {\n\t\tif !hasString(r.Namespaces, attrs.GetNamespace()) { // Non-namespaced resources use the empty string.\n\t\t\treturn false\n\t\t}\n\t}\n\tif len(r.Resources) == 0 {\n\t\treturn true\n\t}\n\n\tapiGroup := attrs.GetAPIGroup()\n\tresource := attrs.GetResource()\n\tsubresource := attrs.GetSubresource()\n\tcombinedResource := resource\n\t// If subresource, the resource in the policy must match \"(resource)/(subresource)\"\n\tif subresource != \"\" {\n\t\tcombinedResource = resource + \"/\" + subresource\n\t}\n\n\tname := attrs.GetName()\n\n\tfor _, gr := range r.Resources {\n\t\tif gr.Group == apiGroup {\n\t\t\tif len(gr.Resources) == 0 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tfor _, res := range gr.Resources {\n\t\t\t\tif len(gr.ResourceNames) == 0 || hasString(gr.ResourceNames, name) {\n\t\t\t\t\t// match \"*\"\n\t\t\t\t\tif res == combinedResource || res == \"*\" {\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t\t// match \"*/subresource\"\n\t\t\t\t\tif len(subresource) \u003e 0 \u0026\u0026 strings.HasPrefix(res, \"*/\") \u0026\u0026 subresource == strings.TrimPrefix(res, \"*/\") {\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t\t// match \"resource/*\"\n\t\t\t\t\tif strings.HasSuffix(res, \"/*\") \u0026\u0026 resource == strings.TrimSuffix(res, \"/*\") {\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":167,"to":217}} {"id":100016886,"name":"hasString","signature":"func hasString(slice []string, value string) bool","file":"staging/src/k8s.io/apiserver/pkg/audit/policy/checker.go","code":"// Utility function to check whether a string slice contains a string.\nfunc hasString(slice []string, value string) bool {\n\tfor _, s := range slice {\n\t\tif s == value {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":219,"to":227}} {"id":100016887,"name":"EvaluatePolicyRule","signature":"func (f *fakePolicyRuleEvaluator) EvaluatePolicyRule(_ authorizer.Attributes) auditinternal.RequestAuditConfig","file":"staging/src/k8s.io/apiserver/pkg/audit/policy/checker.go","code":"func (f *fakePolicyRuleEvaluator) EvaluatePolicyRule(_ authorizer.Attributes) auditinternal.RequestAuditConfig {\n\treturn auditinternal.RequestAuditConfig{\n\t\tLevel: f.level,\n\t\tOmitStages: f.stage,\n\t}\n}","line":{"from":234,"to":239}} {"id":100016888,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/audit/policy/reader.go","code":"func init() {\n\tfor _, gv := range apiGroupVersions {\n\t\tapiGroupVersionSet[gv] = true\n\t}\n}","line":{"from":40,"to":44}} {"id":100016889,"name":"LoadPolicyFromFile","signature":"func LoadPolicyFromFile(filePath string) (*auditinternal.Policy, error)","file":"staging/src/k8s.io/apiserver/pkg/audit/policy/reader.go","code":"func LoadPolicyFromFile(filePath string) (*auditinternal.Policy, error) {\n\tif filePath == \"\" {\n\t\treturn nil, fmt.Errorf(\"file path not specified\")\n\t}\n\tpolicyDef, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read file path %q: %+v\", filePath, err)\n\t}\n\n\tret, err := LoadPolicyFromBytes(policyDef)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%v: from file %v\", err.Error(), filePath)\n\t}\n\n\treturn ret, nil\n}","line":{"from":46,"to":61}} {"id":100016890,"name":"LoadPolicyFromBytes","signature":"func LoadPolicyFromBytes(policyDef []byte) (*auditinternal.Policy, error)","file":"staging/src/k8s.io/apiserver/pkg/audit/policy/reader.go","code":"func LoadPolicyFromBytes(policyDef []byte) (*auditinternal.Policy, error) {\n\tpolicy := \u0026auditinternal.Policy{}\n\tstrictDecoder := serializer.NewCodecFactory(audit.Scheme, serializer.EnableStrict).UniversalDecoder()\n\n\t// Try strict decoding first.\n\t_, gvk, err := strictDecoder.Decode(policyDef, nil, policy)\n\tif err != nil {\n\t\tif !runtime.IsStrictDecodingError(err) {\n\t\t\treturn nil, fmt.Errorf(\"failed decoding: %w\", err)\n\t\t}\n\t\tvar (\n\t\t\tlenientDecoder = audit.Codecs.UniversalDecoder(apiGroupVersions...)\n\t\t\tlenientErr error\n\t\t)\n\t\t_, gvk, lenientErr = lenientDecoder.Decode(policyDef, nil, policy)\n\t\tif lenientErr != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed lenient decoding: %w\", lenientErr)\n\t\t}\n\t\tklog.Warningf(\"Audit policy contains errors, falling back to lenient decoding: %v\", err)\n\t}\n\n\t// Ensure the policy file contained an apiVersion and kind.\n\tgv := schema.GroupVersion{Group: gvk.Group, Version: gvk.Version}\n\tif !apiGroupVersionSet[gv] {\n\t\treturn nil, fmt.Errorf(\"unknown group version field %v in policy\", gvk)\n\t}\n\n\tif err := validation.ValidatePolicy(policy); err != nil {\n\t\treturn nil, err.ToAggregate()\n\t}\n\n\tpolicyCnt := len(policy.Rules)\n\tif policyCnt == 0 {\n\t\treturn nil, fmt.Errorf(\"loaded illegal policy with 0 rules\")\n\t}\n\n\tklog.V(4).InfoS(\"Load audit policy rules success\", \"policyCnt\", policyCnt)\n\treturn policy, nil\n}","line":{"from":63,"to":101}} {"id":100016891,"name":"AllStages","signature":"func AllStages() sets.String","file":"staging/src/k8s.io/apiserver/pkg/audit/policy/util.go","code":"// AllStages returns all possible stages\nfunc AllStages() sets.String {\n\treturn sets.NewString(\n\t\tstring(audit.StageRequestReceived),\n\t\tstring(audit.StageResponseStarted),\n\t\tstring(audit.StageResponseComplete),\n\t\tstring(audit.StagePanic),\n\t)\n}","line":{"from":24,"to":32}} {"id":100016892,"name":"AllLevels","signature":"func AllLevels() sets.String","file":"staging/src/k8s.io/apiserver/pkg/audit/policy/util.go","code":"// AllLevels returns all possible levels\nfunc AllLevels() sets.String {\n\treturn sets.NewString(\n\t\tstring(audit.LevelNone),\n\t\tstring(audit.LevelMetadata),\n\t\tstring(audit.LevelRequest),\n\t\tstring(audit.LevelRequestResponse),\n\t)\n}","line":{"from":34,"to":42}} {"id":100016893,"name":"InvertStages","signature":"func InvertStages(stages []audit.Stage) []audit.Stage","file":"staging/src/k8s.io/apiserver/pkg/audit/policy/util.go","code":"// InvertStages subtracts the given array of stages from all stages\nfunc InvertStages(stages []audit.Stage) []audit.Stage {\n\ts := ConvertStagesToStrings(stages)\n\ta := AllStages()\n\ta.Delete(s...)\n\treturn ConvertStringSetToStages(a)\n}","line":{"from":44,"to":50}} {"id":100016894,"name":"ConvertStagesToStrings","signature":"func ConvertStagesToStrings(stages []audit.Stage) []string","file":"staging/src/k8s.io/apiserver/pkg/audit/policy/util.go","code":"// ConvertStagesToStrings converts an array of stages to a string array\nfunc ConvertStagesToStrings(stages []audit.Stage) []string {\n\ts := make([]string, len(stages))\n\tfor i, stage := range stages {\n\t\ts[i] = string(stage)\n\t}\n\treturn s\n}","line":{"from":52,"to":59}} {"id":100016895,"name":"ConvertStringSetToStages","signature":"func ConvertStringSetToStages(set sets.String) []audit.Stage","file":"staging/src/k8s.io/apiserver/pkg/audit/policy/util.go","code":"// ConvertStringSetToStages converts a string set to an array of stages\nfunc ConvertStringSetToStages(set sets.String) []audit.Stage {\n\tstages := make([]audit.Stage, len(set))\n\tfor i, stage := range set.List() {\n\t\tstages[i] = audit.Stage(stage)\n\t}\n\treturn stages\n}","line":{"from":61,"to":68}} {"id":100016896,"name":"NewEventFromRequest","signature":"func NewEventFromRequest(req *http.Request, requestReceivedTimestamp time.Time, level auditinternal.Level, attribs authorizer.Attributes) (*auditinternal.Event, error)","file":"staging/src/k8s.io/apiserver/pkg/audit/request.go","code":"func NewEventFromRequest(req *http.Request, requestReceivedTimestamp time.Time, level auditinternal.Level, attribs authorizer.Attributes) (*auditinternal.Event, error) {\n\tev := \u0026auditinternal.Event{\n\t\tRequestReceivedTimestamp: metav1.NewMicroTime(requestReceivedTimestamp),\n\t\tVerb: attribs.GetVerb(),\n\t\tRequestURI: req.URL.RequestURI(),\n\t\tUserAgent: maybeTruncateUserAgent(req),\n\t\tLevel: level,\n\t}\n\n\tauditID, found := AuditIDFrom(req.Context())\n\tif !found {\n\t\tauditID = types.UID(uuid.New().String())\n\t}\n\tev.AuditID = auditID\n\n\tips := utilnet.SourceIPs(req)\n\tev.SourceIPs = make([]string, len(ips))\n\tfor i := range ips {\n\t\tev.SourceIPs[i] = ips[i].String()\n\t}\n\n\tif user := attribs.GetUser(); user != nil {\n\t\tev.User.Username = user.GetName()\n\t\tev.User.Extra = map[string]authnv1.ExtraValue{}\n\t\tfor k, v := range user.GetExtra() {\n\t\t\tev.User.Extra[k] = authnv1.ExtraValue(v)\n\t\t}\n\t\tev.User.Groups = user.GetGroups()\n\t\tev.User.UID = user.GetUID()\n\t}\n\n\tif attribs.IsResourceRequest() {\n\t\tev.ObjectRef = \u0026auditinternal.ObjectReference{\n\t\t\tNamespace: attribs.GetNamespace(),\n\t\t\tName: attribs.GetName(),\n\t\t\tResource: attribs.GetResource(),\n\t\t\tSubresource: attribs.GetSubresource(),\n\t\t\tAPIGroup: attribs.GetAPIGroup(),\n\t\t\tAPIVersion: attribs.GetAPIVersion(),\n\t\t}\n\t}\n\n\taddAuditAnnotationsFrom(req.Context(), ev)\n\n\treturn ev, nil\n}","line":{"from":46,"to":91}} {"id":100016897,"name":"LogImpersonatedUser","signature":"func LogImpersonatedUser(ae *auditinternal.Event, user user.Info)","file":"staging/src/k8s.io/apiserver/pkg/audit/request.go","code":"// LogImpersonatedUser fills in the impersonated user attributes into an audit event.\nfunc LogImpersonatedUser(ae *auditinternal.Event, user user.Info) {\n\tif ae == nil || ae.Level.Less(auditinternal.LevelMetadata) {\n\t\treturn\n\t}\n\tae.ImpersonatedUser = \u0026authnv1.UserInfo{\n\t\tUsername: user.GetName(),\n\t}\n\tae.ImpersonatedUser.Groups = user.GetGroups()\n\tae.ImpersonatedUser.UID = user.GetUID()\n\tae.ImpersonatedUser.Extra = map[string]authnv1.ExtraValue{}\n\tfor k, v := range user.GetExtra() {\n\t\tae.ImpersonatedUser.Extra[k] = authnv1.ExtraValue(v)\n\t}\n}","line":{"from":93,"to":107}} {"id":100016898,"name":"LogRequestObject","signature":"func LogRequestObject(ctx context.Context, obj runtime.Object, objGV schema.GroupVersion, gvr schema.GroupVersionResource, subresource string, s runtime.NegotiatedSerializer)","file":"staging/src/k8s.io/apiserver/pkg/audit/request.go","code":"// LogRequestObject fills in the request object into an audit event. The passed runtime.Object\n// will be converted to the given gv.\nfunc LogRequestObject(ctx context.Context, obj runtime.Object, objGV schema.GroupVersion, gvr schema.GroupVersionResource, subresource string, s runtime.NegotiatedSerializer) {\n\tae := AuditEventFrom(ctx)\n\tif ae == nil || ae.Level.Less(auditinternal.LevelMetadata) {\n\t\treturn\n\t}\n\n\t// complete ObjectRef\n\tif ae.ObjectRef == nil {\n\t\tae.ObjectRef = \u0026auditinternal.ObjectReference{}\n\t}\n\n\t// meta.Accessor is more general than ObjectMetaAccessor, but if it fails, we can just skip setting these bits\n\tif meta, err := meta.Accessor(obj); err == nil {\n\t\tif len(ae.ObjectRef.Namespace) == 0 {\n\t\t\tae.ObjectRef.Namespace = meta.GetNamespace()\n\t\t}\n\t\tif len(ae.ObjectRef.Name) == 0 {\n\t\t\tae.ObjectRef.Name = meta.GetName()\n\t\t}\n\t\tif len(ae.ObjectRef.UID) == 0 {\n\t\t\tae.ObjectRef.UID = meta.GetUID()\n\t\t}\n\t\tif len(ae.ObjectRef.ResourceVersion) == 0 {\n\t\t\tae.ObjectRef.ResourceVersion = meta.GetResourceVersion()\n\t\t}\n\t}\n\tif len(ae.ObjectRef.APIVersion) == 0 {\n\t\tae.ObjectRef.APIGroup = gvr.Group\n\t\tae.ObjectRef.APIVersion = gvr.Version\n\t}\n\tif len(ae.ObjectRef.Resource) == 0 {\n\t\tae.ObjectRef.Resource = gvr.Resource\n\t}\n\tif len(ae.ObjectRef.Subresource) == 0 {\n\t\tae.ObjectRef.Subresource = subresource\n\t}\n\n\tif ae.Level.Less(auditinternal.LevelRequest) {\n\t\treturn\n\t}\n\n\tif shouldOmitManagedFields(ctx) {\n\t\tcopy, ok, err := copyWithoutManagedFields(obj)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Error while dropping managed fields from the request\", \"auditID\", ae.AuditID)\n\t\t}\n\t\tif ok {\n\t\t\tobj = copy\n\t\t}\n\t}\n\n\t// TODO(audit): hook into the serializer to avoid double conversion\n\tvar err error\n\tae.RequestObject, err = encodeObject(obj, objGV, s)\n\tif err != nil {\n\t\t// TODO(audit): add error slice to audit event struct\n\t\tklog.ErrorS(err, \"Encoding failed of request object\", \"auditID\", ae.AuditID, \"gvr\", gvr.String(), \"obj\", obj)\n\t\treturn\n\t}\n}","line":{"from":109,"to":170}} {"id":100016899,"name":"LogRequestPatch","signature":"func LogRequestPatch(ctx context.Context, patch []byte)","file":"staging/src/k8s.io/apiserver/pkg/audit/request.go","code":"// LogRequestPatch fills in the given patch as the request object into an audit event.\nfunc LogRequestPatch(ctx context.Context, patch []byte) {\n\tae := AuditEventFrom(ctx)\n\tif ae == nil || ae.Level.Less(auditinternal.LevelRequest) {\n\t\treturn\n\t}\n\n\tae.RequestObject = \u0026runtime.Unknown{\n\t\tRaw: patch,\n\t\tContentType: runtime.ContentTypeJSON,\n\t}\n}","line":{"from":172,"to":183}} {"id":100016900,"name":"LogResponseObject","signature":"func LogResponseObject(ctx context.Context, obj runtime.Object, gv schema.GroupVersion, s runtime.NegotiatedSerializer)","file":"staging/src/k8s.io/apiserver/pkg/audit/request.go","code":"// LogResponseObject fills in the response object into an audit event. The passed runtime.Object\n// will be converted to the given gv.\nfunc LogResponseObject(ctx context.Context, obj runtime.Object, gv schema.GroupVersion, s runtime.NegotiatedSerializer) {\n\tae := AuditEventFrom(ctx)\n\tif ae == nil || ae.Level.Less(auditinternal.LevelMetadata) {\n\t\treturn\n\t}\n\tif status, ok := obj.(*metav1.Status); ok {\n\t\t// selectively copy the bounded fields.\n\t\tae.ResponseStatus = \u0026metav1.Status{\n\t\t\tStatus: status.Status,\n\t\t\tMessage: status.Message,\n\t\t\tReason: status.Reason,\n\t\t\tDetails: status.Details,\n\t\t\tCode: status.Code,\n\t\t}\n\t}\n\n\tif ae.Level.Less(auditinternal.LevelRequestResponse) {\n\t\treturn\n\t}\n\n\tif shouldOmitManagedFields(ctx) {\n\t\tcopy, ok, err := copyWithoutManagedFields(obj)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Error while dropping managed fields from the response\", \"auditID\", ae.AuditID)\n\t\t}\n\t\tif ok {\n\t\t\tobj = copy\n\t\t}\n\t}\n\n\t// TODO(audit): hook into the serializer to avoid double conversion\n\tvar err error\n\tae.ResponseObject, err = encodeObject(obj, gv, s)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Encoding failed of response object\", \"auditID\", ae.AuditID, \"obj\", obj)\n\t}\n}","line":{"from":185,"to":223}} {"id":100016901,"name":"encodeObject","signature":"func encodeObject(obj runtime.Object, gv schema.GroupVersion, serializer runtime.NegotiatedSerializer) (*runtime.Unknown, error)","file":"staging/src/k8s.io/apiserver/pkg/audit/request.go","code":"func encodeObject(obj runtime.Object, gv schema.GroupVersion, serializer runtime.NegotiatedSerializer) (*runtime.Unknown, error) {\n\tconst mediaType = runtime.ContentTypeJSON\n\tinfo, ok := runtime.SerializerInfoForMediaType(serializer.SupportedMediaTypes(), mediaType)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unable to locate encoder -- %q is not a supported media type\", mediaType)\n\t}\n\n\tenc := serializer.EncoderForVersion(info.Serializer, gv)\n\tvar buf bytes.Buffer\n\tif err := enc.Encode(obj, \u0026buf); err != nil {\n\t\treturn nil, fmt.Errorf(\"encoding failed: %v\", err)\n\t}\n\n\treturn \u0026runtime.Unknown{\n\t\tRaw: buf.Bytes(),\n\t\tContentType: mediaType,\n\t}, nil\n}","line":{"from":225,"to":242}} {"id":100016902,"name":"maybeTruncateUserAgent","signature":"func maybeTruncateUserAgent(req *http.Request) string","file":"staging/src/k8s.io/apiserver/pkg/audit/request.go","code":"// truncate User-Agent if too long, otherwise return it directly.\nfunc maybeTruncateUserAgent(req *http.Request) string {\n\tua := req.UserAgent()\n\tif len(ua) \u003e maxUserAgentLength {\n\t\tua = ua[:maxUserAgentLength] + userAgentTruncateSuffix\n\t}\n\n\treturn ua\n}","line":{"from":244,"to":252}} {"id":100016903,"name":"copyWithoutManagedFields","signature":"func copyWithoutManagedFields(obj runtime.Object) (runtime.Object, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/audit/request.go","code":"// copyWithoutManagedFields will make a deep copy of the specified object and\n// will discard the managed fields from the copy.\n// The specified object is expected to be a meta.Object or a \"list\".\n// The specified object obj is treated as readonly and hence not mutated.\n// On return, an error is set if the function runs into any error while\n// removing the managed fields, the boolean value is true if the copy has\n// been made successfully, otherwise false.\nfunc copyWithoutManagedFields(obj runtime.Object) (runtime.Object, bool, error) {\n\tisAccessor := true\n\tif _, err := meta.Accessor(obj); err != nil {\n\t\tisAccessor = false\n\t}\n\tisList := meta.IsListType(obj)\n\t_, isTable := obj.(*metav1.Table)\n\tif !isAccessor \u0026\u0026 !isList \u0026\u0026 !isTable {\n\t\treturn nil, false, nil\n\t}\n\n\t// TODO a deep copy isn't really needed here, figure out how we can reliably\n\t// use shallow copy here to omit the manageFields.\n\tcopy := obj.DeepCopyObject()\n\n\tif isAccessor {\n\t\tif err := removeManagedFields(copy); err != nil {\n\t\t\treturn nil, false, err\n\t\t}\n\t}\n\n\tif isList {\n\t\tif err := meta.EachListItem(copy, removeManagedFields); err != nil {\n\t\t\treturn nil, false, err\n\t\t}\n\t}\n\n\tif isTable {\n\t\ttable := copy.(*metav1.Table)\n\t\tfor i := range table.Rows {\n\t\t\trowObj := table.Rows[i].Object\n\t\t\tif err := removeManagedFields(rowObj.Object); err != nil {\n\t\t\t\treturn nil, false, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn copy, true, nil\n}","line":{"from":254,"to":299}} {"id":100016904,"name":"removeManagedFields","signature":"func removeManagedFields(obj runtime.Object) error","file":"staging/src/k8s.io/apiserver/pkg/audit/request.go","code":"func removeManagedFields(obj runtime.Object) error {\n\tif obj == nil {\n\t\treturn nil\n\t}\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\taccessor.SetManagedFields(nil)\n\treturn nil\n}","line":{"from":301,"to":311}} {"id":100016905,"name":"shouldOmitManagedFields","signature":"func shouldOmitManagedFields(ctx context.Context) bool","file":"staging/src/k8s.io/apiserver/pkg/audit/request.go","code":"func shouldOmitManagedFields(ctx context.Context) bool {\n\tif auditContext := AuditContextFrom(ctx); auditContext != nil {\n\t\treturn auditContext.RequestAuditConfig.OmitManagedFields\n\t}\n\n\t// If we can't decide, return false to maintain current behavior which is\n\t// to retain the manage fields in the audit.\n\treturn false\n}","line":{"from":313,"to":321}} {"id":100016906,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/audit/scheme.go","code":"func init() {\n\tmetav1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: \"v1\"})\n\tutilruntime.Must(v1.AddToScheme(Scheme))\n\tutilruntime.Must(auditinternal.AddToScheme(Scheme))\n\tutilruntime.Must(Scheme.SetVersionPriority(v1.SchemeGroupVersion))\n}","line":{"from":33,"to":38}} {"id":100016907,"name":"Union","signature":"func Union(backends ...Backend) Backend","file":"staging/src/k8s.io/apiserver/pkg/audit/union.go","code":"// Union returns an audit Backend which logs events to a set of backends. The returned\n// Sink implementation blocks in turn for each call to ProcessEvents.\nfunc Union(backends ...Backend) Backend {\n\tif len(backends) == 1 {\n\t\treturn backends[0]\n\t}\n\treturn union{backends}\n}","line":{"from":27,"to":34}} {"id":100016908,"name":"ProcessEvents","signature":"func (u union) ProcessEvents(events ...*auditinternal.Event) bool","file":"staging/src/k8s.io/apiserver/pkg/audit/union.go","code":"func (u union) ProcessEvents(events ...*auditinternal.Event) bool {\n\tsuccess := true\n\tfor _, backend := range u.backends {\n\t\tsuccess = backend.ProcessEvents(events...) \u0026\u0026 success\n\t}\n\treturn success\n}","line":{"from":40,"to":46}} {"id":100016909,"name":"Run","signature":"func (u union) Run(stopCh \u003c-chan struct{}) error","file":"staging/src/k8s.io/apiserver/pkg/audit/union.go","code":"func (u union) Run(stopCh \u003c-chan struct{}) error {\n\tvar funcs []func() error\n\tfor _, backend := range u.backends {\n\t\tbackend := backend\n\t\tfuncs = append(funcs, func() error {\n\t\t\treturn backend.Run(stopCh)\n\t\t})\n\t}\n\treturn errors.AggregateGoroutines(funcs...)\n}","line":{"from":48,"to":57}} {"id":100016910,"name":"Shutdown","signature":"func (u union) Shutdown()","file":"staging/src/k8s.io/apiserver/pkg/audit/union.go","code":"func (u union) Shutdown() {\n\tfor _, backend := range u.backends {\n\t\tbackend.Shutdown()\n\t}\n}","line":{"from":59,"to":63}} {"id":100016911,"name":"String","signature":"func (u union) String() string","file":"staging/src/k8s.io/apiserver/pkg/audit/union.go","code":"func (u union) String() string {\n\tvar backendStrings []string\n\tfor _, backend := range u.backends {\n\t\tbackendStrings = append(backendStrings, fmt.Sprintf(\"%s\", backend))\n\t}\n\treturn fmt.Sprintf(\"union[%s]\", strings.Join(backendStrings, \",\"))\n}","line":{"from":65,"to":71}} {"id":100016912,"name":"authenticate","signature":"func authenticate(ctx context.Context, implicitAuds Audiences, authenticate func() (*Response, bool, error)) (*Response, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/authenticator/audagnostic.go","code":"func authenticate(ctx context.Context, implicitAuds Audiences, authenticate func() (*Response, bool, error)) (*Response, bool, error) {\n\ttargetAuds, ok := AudiencesFrom(ctx)\n\t// We can remove this once api audiences is never empty. That will probably\n\t// be N releases after TokenRequest is GA.\n\tif !ok {\n\t\treturn authenticate()\n\t}\n\tauds := implicitAuds.Intersect(targetAuds)\n\tif len(auds) == 0 {\n\t\treturn nil, false, nil\n\t}\n\tresp, ok, err := authenticate()\n\tif err != nil || !ok {\n\t\treturn nil, false, err\n\t}\n\tif len(resp.Audiences) \u003e 0 {\n\t\t// maybe the authenticator was audience aware after all.\n\t\treturn nil, false, fmt.Errorf(\"audience agnostic authenticator wrapped an authenticator that returned audiences: %q\", resp.Audiences)\n\t}\n\tresp.Audiences = auds\n\treturn resp, true, nil\n}","line":{"from":25,"to":46}} {"id":100016913,"name":"AuthenticateRequest","signature":"func (a *audAgnosticRequestAuthenticator) AuthenticateRequest(req *http.Request) (*Response, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/authenticator/audagnostic.go","code":"func (a *audAgnosticRequestAuthenticator) AuthenticateRequest(req *http.Request) (*Response, bool, error) {\n\treturn authenticate(req.Context(), a.implicit, func() (*Response, bool, error) {\n\t\treturn a.delegate.AuthenticateRequest(req)\n\t})\n}","line":{"from":55,"to":59}} {"id":100016914,"name":"WrapAudienceAgnosticRequest","signature":"func WrapAudienceAgnosticRequest(implicit Audiences, delegate Request) Request","file":"staging/src/k8s.io/apiserver/pkg/authentication/authenticator/audagnostic.go","code":"// WrapAudienceAgnosticRequest wraps an audience agnostic request authenticator\n// to restrict its accepted audiences to a set of implicit audiences.\nfunc WrapAudienceAgnosticRequest(implicit Audiences, delegate Request) Request {\n\treturn \u0026audAgnosticRequestAuthenticator{\n\t\timplicit: implicit,\n\t\tdelegate: delegate,\n\t}\n}","line":{"from":61,"to":68}} {"id":100016915,"name":"AuthenticateToken","signature":"func (a *audAgnosticTokenAuthenticator) AuthenticateToken(ctx context.Context, tok string) (*Response, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/authenticator/audagnostic.go","code":"func (a *audAgnosticTokenAuthenticator) AuthenticateToken(ctx context.Context, tok string) (*Response, bool, error) {\n\treturn authenticate(ctx, a.implicit, func() (*Response, bool, error) {\n\t\treturn a.delegate.AuthenticateToken(ctx, tok)\n\t})\n}","line":{"from":77,"to":81}} {"id":100016916,"name":"WrapAudienceAgnosticToken","signature":"func WrapAudienceAgnosticToken(implicit Audiences, delegate Token) Token","file":"staging/src/k8s.io/apiserver/pkg/authentication/authenticator/audagnostic.go","code":"// WrapAudienceAgnosticToken wraps an audience agnostic token authenticator to\n// restrict its accepted audiences to a set of implicit audiences.\nfunc WrapAudienceAgnosticToken(implicit Audiences, delegate Token) Token {\n\treturn \u0026audAgnosticTokenAuthenticator{\n\t\timplicit: implicit,\n\t\tdelegate: delegate,\n\t}\n}","line":{"from":83,"to":90}} {"id":100016917,"name":"WithAudiences","signature":"func WithAudiences(ctx context.Context, auds Audiences) context.Context","file":"staging/src/k8s.io/apiserver/pkg/authentication/authenticator/audiences.go","code":"// WithAudiences returns a context that stores a request's expected audiences.\nfunc WithAudiences(ctx context.Context, auds Audiences) context.Context {\n\treturn context.WithValue(ctx, audiencesKey, auds)\n}","line":{"from":32,"to":35}} {"id":100016918,"name":"AudiencesFrom","signature":"func AudiencesFrom(ctx context.Context) (Audiences, bool)","file":"staging/src/k8s.io/apiserver/pkg/authentication/authenticator/audiences.go","code":"// AudiencesFrom returns a request's expected audiences stored in the request context.\nfunc AudiencesFrom(ctx context.Context) (Audiences, bool) {\n\tauds, ok := ctx.Value(audiencesKey).(Audiences)\n\treturn auds, ok\n}","line":{"from":37,"to":41}} {"id":100016919,"name":"Has","signature":"func (a Audiences) Has(taud string) bool","file":"staging/src/k8s.io/apiserver/pkg/authentication/authenticator/audiences.go","code":"// Has checks if Audiences contains a specific audiences.\nfunc (a Audiences) Has(taud string) bool {\n\tfor _, aud := range a {\n\t\tif aud == taud {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":43,"to":51}} {"id":100016920,"name":"Intersect","signature":"func (a Audiences) Intersect(tauds Audiences) Audiences","file":"staging/src/k8s.io/apiserver/pkg/authentication/authenticator/audiences.go","code":"// Intersect intersects Audiences with a target Audiences and returns all\n// elements in both.\nfunc (a Audiences) Intersect(tauds Audiences) Audiences {\n\tselected := Audiences{}\n\tfor _, taud := range tauds {\n\t\tif a.Has(taud) {\n\t\t\tselected = append(selected, taud)\n\t\t}\n\t}\n\treturn selected\n}","line":{"from":53,"to":63}} {"id":100016921,"name":"AuthenticateToken","signature":"func (f TokenFunc) AuthenticateToken(ctx context.Context, token string) (*Response, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/authenticator/interfaces.go","code":"// AuthenticateToken implements authenticator.Token.\nfunc (f TokenFunc) AuthenticateToken(ctx context.Context, token string) (*Response, bool, error) {\n\treturn f(ctx, token)\n}","line":{"from":41,"to":44}} {"id":100016922,"name":"AuthenticateRequest","signature":"func (f RequestFunc) AuthenticateRequest(req *http.Request) (*Response, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/authenticator/interfaces.go","code":"// AuthenticateRequest implements authenticator.Request.\nfunc (f RequestFunc) AuthenticateRequest(req *http.Request) (*Response, bool, error) {\n\treturn f(req)\n}","line":{"from":49,"to":52}} {"id":100016923,"name":"New","signature":"func (c DelegatingAuthenticatorConfig) New() (authenticator.Request, *spec.SecurityDefinitions, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/authenticatorfactory/delegating.go","code":"func (c DelegatingAuthenticatorConfig) New() (authenticator.Request, *spec.SecurityDefinitions, error) {\n\tauthenticators := []authenticator.Request{}\n\tsecurityDefinitions := spec.SecurityDefinitions{}\n\n\t// front-proxy first, then remote\n\t// Add the front proxy authenticator if requested\n\tif c.RequestHeaderConfig != nil {\n\t\trequestHeaderAuthenticator := headerrequest.NewDynamicVerifyOptionsSecure(\n\t\t\tc.RequestHeaderConfig.CAContentProvider.VerifyOptions,\n\t\t\tc.RequestHeaderConfig.AllowedClientNames,\n\t\t\tc.RequestHeaderConfig.UsernameHeaders,\n\t\t\tc.RequestHeaderConfig.GroupHeaders,\n\t\t\tc.RequestHeaderConfig.ExtraHeaderPrefixes,\n\t\t)\n\t\tauthenticators = append(authenticators, requestHeaderAuthenticator)\n\t}\n\n\t// x509 client cert auth\n\tif c.ClientCertificateCAContentProvider != nil {\n\t\tauthenticators = append(authenticators, x509.NewDynamic(c.ClientCertificateCAContentProvider.VerifyOptions, x509.CommonNameUserConversion))\n\t}\n\n\tif c.TokenAccessReviewClient != nil {\n\t\tif c.WebhookRetryBackoff == nil {\n\t\t\treturn nil, nil, errors.New(\"retry backoff parameters for delegating authentication webhook has not been specified\")\n\t\t}\n\t\ttokenAuth, err := webhooktoken.NewFromInterface(c.TokenAccessReviewClient, c.APIAudiences, *c.WebhookRetryBackoff, c.TokenAccessReviewTimeout, webhooktoken.AuthenticatorMetrics{\n\t\t\tRecordRequestTotal: RecordRequestTotal,\n\t\t\tRecordRequestLatency: RecordRequestLatency,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tcachingTokenAuth := cache.New(tokenAuth, false, c.CacheTTL, c.CacheTTL)\n\t\tauthenticators = append(authenticators, bearertoken.New(cachingTokenAuth), websocket.NewProtocolAuthenticator(cachingTokenAuth))\n\n\t\tsecurityDefinitions[\"BearerToken\"] = \u0026spec.SecurityScheme{\n\t\t\tSecuritySchemeProps: spec.SecuritySchemeProps{\n\t\t\t\tType: \"apiKey\",\n\t\t\t\tName: \"authorization\",\n\t\t\t\tIn: \"header\",\n\t\t\t\tDescription: \"Bearer Token authentication\",\n\t\t\t},\n\t\t}\n\t}\n\n\tif len(authenticators) == 0 {\n\t\tif c.Anonymous {\n\t\t\treturn anonymous.NewAuthenticator(), \u0026securityDefinitions, nil\n\t\t}\n\t\treturn nil, nil, errors.New(\"No authentication method configured\")\n\t}\n\n\tauthenticator := group.NewAuthenticatedGroupAdder(unionauth.New(authenticators...))\n\tif c.Anonymous {\n\t\tauthenticator = unionauth.NewFailOnError(authenticator, anonymous.NewAuthenticator())\n\t}\n\treturn authenticator, \u0026securityDefinitions, nil\n}","line":{"from":68,"to":126}} {"id":100016924,"name":"NewFromTokens","signature":"func NewFromTokens(tokens map[string]*user.DefaultInfo, audiences authenticator.Audiences) authenticator.Request","file":"staging/src/k8s.io/apiserver/pkg/authentication/authenticatorfactory/loopback.go","code":"// NewFromTokens returns an authenticator.Request or an error\nfunc NewFromTokens(tokens map[string]*user.DefaultInfo, audiences authenticator.Audiences) authenticator.Request {\n\treturn bearertoken.New(authenticator.WrapAudienceAgnosticToken(audiences, tokenfile.New(tokens)))\n}","line":{"from":26,"to":29}} {"id":100016925,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/authentication/authenticatorfactory/metrics.go","code":"// init registers all metrics.\nfunc init() {\n\tfor _, metric := range metrics {\n\t\tlegacyregistry.MustRegister(metric)\n\t}\n}","line":{"from":28,"to":33}} {"id":100016926,"name":"RecordRequestTotal","signature":"func RecordRequestTotal(ctx context.Context, code string)","file":"staging/src/k8s.io/apiserver/pkg/authentication/authenticatorfactory/metrics.go","code":"// RecordRequestTotal increments the total number of requests for the delegated authentication.\nfunc RecordRequestTotal(ctx context.Context, code string) {\n\trequestTotal.WithContext(ctx).WithLabelValues(code).Inc()\n}","line":{"from":61,"to":64}} {"id":100016927,"name":"RecordRequestLatency","signature":"func RecordRequestLatency(ctx context.Context, code string, latency float64)","file":"staging/src/k8s.io/apiserver/pkg/authentication/authenticatorfactory/metrics.go","code":"// RecordRequestLatency measures request latency in seconds for the delegated authentication. Broken down by status code.\nfunc RecordRequestLatency(ctx context.Context, code string, latency float64) {\n\trequestLatency.WithContext(ctx).WithLabelValues(code).Observe(latency)\n}","line":{"from":66,"to":69}} {"id":100016928,"name":"NewAuthenticatedGroupAdder","signature":"func NewAuthenticatedGroupAdder(auth authenticator.Request) authenticator.Request","file":"staging/src/k8s.io/apiserver/pkg/authentication/group/authenticated_group_adder.go","code":"// NewAuthenticatedGroupAdder wraps a request authenticator, and adds the system:authenticated group when appropriate.\n// Authentication must succeed, the user must not be system:anonymous, the groups system:authenticated or system:unauthenticated must\n// not be present\nfunc NewAuthenticatedGroupAdder(auth authenticator.Request) authenticator.Request {\n\treturn \u0026AuthenticatedGroupAdder{auth}\n}","line":{"from":32,"to":37}} {"id":100016929,"name":"AuthenticateRequest","signature":"func (g *AuthenticatedGroupAdder) AuthenticateRequest(req *http.Request) (*authenticator.Response, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/group/authenticated_group_adder.go","code":"func (g *AuthenticatedGroupAdder) AuthenticateRequest(req *http.Request) (*authenticator.Response, bool, error) {\n\tr, ok, err := g.Authenticator.AuthenticateRequest(req)\n\tif err != nil || !ok {\n\t\treturn nil, ok, err\n\t}\n\n\tif r.User.GetName() == user.Anonymous {\n\t\treturn r, true, nil\n\t}\n\tfor _, group := range r.User.GetGroups() {\n\t\tif group == user.AllAuthenticated || group == user.AllUnauthenticated {\n\t\t\treturn r, true, nil\n\t\t}\n\t}\n\n\tnewGroups := make([]string, 0, len(r.User.GetGroups())+1)\n\tnewGroups = append(newGroups, r.User.GetGroups()...)\n\tnewGroups = append(newGroups, user.AllAuthenticated)\n\n\tret := *r // shallow copy\n\tret.User = \u0026user.DefaultInfo{\n\t\tName: r.User.GetName(),\n\t\tUID: r.User.GetUID(),\n\t\tGroups: newGroups,\n\t\tExtra: r.User.GetExtra(),\n\t}\n\treturn \u0026ret, true, nil\n}","line":{"from":39,"to":66}} {"id":100016930,"name":"NewGroupAdder","signature":"func NewGroupAdder(auth authenticator.Request, groups []string) authenticator.Request","file":"staging/src/k8s.io/apiserver/pkg/authentication/group/group_adder.go","code":"// NewGroupAdder wraps a request authenticator, and adds the specified groups to the returned user when authentication succeeds\nfunc NewGroupAdder(auth authenticator.Request, groups []string) authenticator.Request {\n\treturn \u0026GroupAdder{auth, groups}\n}","line":{"from":34,"to":37}} {"id":100016931,"name":"AuthenticateRequest","signature":"func (g *GroupAdder) AuthenticateRequest(req *http.Request) (*authenticator.Response, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/group/group_adder.go","code":"func (g *GroupAdder) AuthenticateRequest(req *http.Request) (*authenticator.Response, bool, error) {\n\tr, ok, err := g.Authenticator.AuthenticateRequest(req)\n\tif err != nil || !ok {\n\t\treturn nil, ok, err\n\t}\n\n\tnewGroups := make([]string, 0, len(r.User.GetGroups())+len(g.Groups))\n\tnewGroups = append(newGroups, r.User.GetGroups()...)\n\tnewGroups = append(newGroups, g.Groups...)\n\n\tret := *r // shallow copy\n\tret.User = \u0026user.DefaultInfo{\n\t\tName: r.User.GetName(),\n\t\tUID: r.User.GetUID(),\n\t\tGroups: newGroups,\n\t\tExtra: r.User.GetExtra(),\n\t}\n\treturn \u0026ret, true, nil\n}","line":{"from":39,"to":57}} {"id":100016932,"name":"NewTokenGroupAdder","signature":"func NewTokenGroupAdder(auth authenticator.Token, groups []string) authenticator.Token","file":"staging/src/k8s.io/apiserver/pkg/authentication/group/token_group_adder.go","code":"// NewTokenGroupAdder wraps a token authenticator, and adds the specified groups to the returned user when authentication succeeds\nfunc NewTokenGroupAdder(auth authenticator.Token, groups []string) authenticator.Token {\n\treturn \u0026TokenGroupAdder{auth, groups}\n}","line":{"from":34,"to":37}} {"id":100016933,"name":"AuthenticateToken","signature":"func (g *TokenGroupAdder) AuthenticateToken(ctx context.Context, token string) (*authenticator.Response, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/group/token_group_adder.go","code":"func (g *TokenGroupAdder) AuthenticateToken(ctx context.Context, token string) (*authenticator.Response, bool, error) {\n\tr, ok, err := g.Authenticator.AuthenticateToken(ctx, token)\n\tif err != nil || !ok {\n\t\treturn nil, ok, err\n\t}\n\n\tnewGroups := make([]string, 0, len(r.User.GetGroups())+len(g.Groups))\n\tnewGroups = append(newGroups, r.User.GetGroups()...)\n\tnewGroups = append(newGroups, g.Groups...)\n\n\tret := *r // shallow copy\n\tret.User = \u0026user.DefaultInfo{\n\t\tName: r.User.GetName(),\n\t\tUID: r.User.GetUID(),\n\t\tGroups: newGroups,\n\t\tExtra: r.User.GetExtra(),\n\t}\n\treturn \u0026ret, true, nil\n}","line":{"from":39,"to":57}} {"id":100016934,"name":"NewAuthenticator","signature":"func NewAuthenticator() authenticator.Request","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/anonymous/anonymous.go","code":"func NewAuthenticator() authenticator.Request {\n\treturn authenticator.RequestFunc(func(req *http.Request) (*authenticator.Response, bool, error) {\n\t\tauds, _ := authenticator.AudiencesFrom(req.Context())\n\t\treturn \u0026authenticator.Response{\n\t\t\tUser: \u0026user.DefaultInfo{\n\t\t\t\tName: anonymousUser,\n\t\t\t\tGroups: []string{unauthenticatedGroup},\n\t\t\t},\n\t\t\tAudiences: auds,\n\t\t}, true, nil\n\t})\n}","line":{"from":32,"to":43}} {"id":100016935,"name":"New","signature":"func New(auth authenticator.Token) *Authenticator","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/bearertoken/bearertoken.go","code":"func New(auth authenticator.Token) *Authenticator {\n\treturn \u0026Authenticator{auth}\n}","line":{"from":36,"to":38}} {"id":100016936,"name":"AuthenticateRequest","signature":"func (a *Authenticator) AuthenticateRequest(req *http.Request) (*authenticator.Response, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/bearertoken/bearertoken.go","code":"func (a *Authenticator) AuthenticateRequest(req *http.Request) (*authenticator.Response, bool, error) {\n\tauth := strings.TrimSpace(req.Header.Get(\"Authorization\"))\n\tif auth == \"\" {\n\t\treturn nil, false, nil\n\t}\n\tparts := strings.SplitN(auth, \" \", 3)\n\tif len(parts) \u003c 2 || strings.ToLower(parts[0]) != \"bearer\" {\n\t\treturn nil, false, nil\n\t}\n\n\ttoken := parts[1]\n\n\t// Empty bearer tokens aren't valid\n\tif len(token) == 0 {\n\t\t// The space before the token case\n\t\tif len(parts) == 3 {\n\t\t\twarning.AddWarning(req.Context(), \"\", invalidTokenWithSpaceWarning)\n\t\t}\n\t\treturn nil, false, nil\n\t}\n\n\tresp, ok, err := a.auth.AuthenticateToken(req.Context(), token)\n\t// if we authenticated successfully, go ahead and remove the bearer token so that no one\n\t// is ever tempted to use it inside of the API server\n\tif ok {\n\t\treq.Header.Del(\"Authorization\")\n\t}\n\n\t// If the token authenticator didn't error, provide a default error\n\tif !ok \u0026\u0026 err == nil {\n\t\terr = invalidToken\n\t}\n\n\treturn resp, ok, err\n}","line":{"from":42,"to":76}} {"id":100016937,"name":"Value","signature":"func (d StringSliceProviderFunc) Value() []string","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader.go","code":"// Value returns the current string slice. Callers should never mutate the returned value.\nfunc (d StringSliceProviderFunc) Value() []string {\n\treturn d()\n}","line":{"from":42,"to":45}} {"id":100016938,"name":"Value","signature":"func (s StaticStringSlice) Value() []string","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader.go","code":"// Value returns the current string slice. Callers should never mutate the returned value.\nfunc (s StaticStringSlice) Value() []string {\n\treturn s\n}","line":{"from":50,"to":53}} {"id":100016939,"name":"New","signature":"func New(nameHeaders, groupHeaders, extraHeaderPrefixes []string) (authenticator.Request, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader.go","code":"func New(nameHeaders, groupHeaders, extraHeaderPrefixes []string) (authenticator.Request, error) {\n\ttrimmedNameHeaders, err := trimHeaders(nameHeaders...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttrimmedGroupHeaders, err := trimHeaders(groupHeaders...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttrimmedExtraHeaderPrefixes, err := trimHeaders(extraHeaderPrefixes...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewDynamic(\n\t\tStaticStringSlice(trimmedNameHeaders),\n\t\tStaticStringSlice(trimmedGroupHeaders),\n\t\tStaticStringSlice(trimmedExtraHeaderPrefixes),\n\t), nil\n}","line":{"from":67,"to":86}} {"id":100016940,"name":"NewDynamic","signature":"func NewDynamic(nameHeaders, groupHeaders, extraHeaderPrefixes StringSliceProvider) authenticator.Request","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader.go","code":"func NewDynamic(nameHeaders, groupHeaders, extraHeaderPrefixes StringSliceProvider) authenticator.Request {\n\treturn \u0026requestHeaderAuthRequestHandler{\n\t\tnameHeaders: nameHeaders,\n\t\tgroupHeaders: groupHeaders,\n\t\textraHeaderPrefixes: extraHeaderPrefixes,\n\t}\n}","line":{"from":88,"to":94}} {"id":100016941,"name":"trimHeaders","signature":"func trimHeaders(headerNames ...string) ([]string, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader.go","code":"func trimHeaders(headerNames ...string) ([]string, error) {\n\tret := []string{}\n\tfor _, headerName := range headerNames {\n\t\ttrimmedHeader := strings.TrimSpace(headerName)\n\t\tif len(trimmedHeader) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"empty header %q\", headerName)\n\t\t}\n\t\tret = append(ret, trimmedHeader)\n\t}\n\n\treturn ret, nil\n}","line":{"from":96,"to":107}} {"id":100016942,"name":"NewSecure","signature":"func NewSecure(clientCA string, proxyClientNames []string, nameHeaders []string, groupHeaders []string, extraHeaderPrefixes []string) (authenticator.Request, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader.go","code":"func NewSecure(clientCA string, proxyClientNames []string, nameHeaders []string, groupHeaders []string, extraHeaderPrefixes []string) (authenticator.Request, error) {\n\tif len(clientCA) == 0 {\n\t\treturn nil, fmt.Errorf(\"missing clientCA file\")\n\t}\n\n\t// Wrap with an x509 verifier\n\tcaData, err := ioutil.ReadFile(clientCA)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading %s: %v\", clientCA, err)\n\t}\n\topts := x509request.DefaultVerifyOptions()\n\topts.Roots = x509.NewCertPool()\n\tcerts, err := utilcert.ParseCertsPEM(caData)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error loading certs from %s: %v\", clientCA, err)\n\t}\n\tfor _, cert := range certs {\n\t\topts.Roots.AddCert(cert)\n\t}\n\n\ttrimmedNameHeaders, err := trimHeaders(nameHeaders...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttrimmedGroupHeaders, err := trimHeaders(groupHeaders...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttrimmedExtraHeaderPrefixes, err := trimHeaders(extraHeaderPrefixes...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewDynamicVerifyOptionsSecure(\n\t\tx509request.StaticVerifierFn(opts),\n\t\tStaticStringSlice(proxyClientNames),\n\t\tStaticStringSlice(trimmedNameHeaders),\n\t\tStaticStringSlice(trimmedGroupHeaders),\n\t\tStaticStringSlice(trimmedExtraHeaderPrefixes),\n\t), nil\n}","line":{"from":109,"to":149}} {"id":100016943,"name":"NewDynamicVerifyOptionsSecure","signature":"func NewDynamicVerifyOptionsSecure(verifyOptionFn x509request.VerifyOptionFunc, proxyClientNames, nameHeaders, groupHeaders, extraHeaderPrefixes StringSliceProvider) authenticator.Request","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader.go","code":"func NewDynamicVerifyOptionsSecure(verifyOptionFn x509request.VerifyOptionFunc, proxyClientNames, nameHeaders, groupHeaders, extraHeaderPrefixes StringSliceProvider) authenticator.Request {\n\theaderAuthenticator := NewDynamic(nameHeaders, groupHeaders, extraHeaderPrefixes)\n\n\treturn x509request.NewDynamicCAVerifier(verifyOptionFn, headerAuthenticator, proxyClientNames)\n}","line":{"from":151,"to":155}} {"id":100016944,"name":"AuthenticateRequest","signature":"func (a *requestHeaderAuthRequestHandler) AuthenticateRequest(req *http.Request) (*authenticator.Response, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader.go","code":"func (a *requestHeaderAuthRequestHandler) AuthenticateRequest(req *http.Request) (*authenticator.Response, bool, error) {\n\tname := headerValue(req.Header, a.nameHeaders.Value())\n\tif len(name) == 0 {\n\t\treturn nil, false, nil\n\t}\n\tgroups := allHeaderValues(req.Header, a.groupHeaders.Value())\n\textra := newExtra(req.Header, a.extraHeaderPrefixes.Value())\n\n\t// clear headers used for authentication\n\tClearAuthenticationHeaders(req.Header, a.nameHeaders, a.groupHeaders, a.extraHeaderPrefixes)\n\n\treturn \u0026authenticator.Response{\n\t\tUser: \u0026user.DefaultInfo{\n\t\t\tName: name,\n\t\t\tGroups: groups,\n\t\t\tExtra: extra,\n\t\t},\n\t}, true, nil\n}","line":{"from":157,"to":175}} {"id":100016945,"name":"ClearAuthenticationHeaders","signature":"func ClearAuthenticationHeaders(h http.Header, nameHeaders, groupHeaders, extraHeaderPrefixes StringSliceProvider)","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader.go","code":"func ClearAuthenticationHeaders(h http.Header, nameHeaders, groupHeaders, extraHeaderPrefixes StringSliceProvider) {\n\tfor _, headerName := range nameHeaders.Value() {\n\t\th.Del(headerName)\n\t}\n\tfor _, headerName := range groupHeaders.Value() {\n\t\th.Del(headerName)\n\t}\n\tfor _, prefix := range extraHeaderPrefixes.Value() {\n\t\tfor k := range h {\n\t\t\tif hasPrefixIgnoreCase(k, prefix) {\n\t\t\t\tdelete(h, k) // we have the raw key so avoid relying on canonicalization\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":177,"to":191}} {"id":100016946,"name":"hasPrefixIgnoreCase","signature":"func hasPrefixIgnoreCase(s, prefix string) bool","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader.go","code":"func hasPrefixIgnoreCase(s, prefix string) bool {\n\treturn len(s) \u003e= len(prefix) \u0026\u0026 strings.EqualFold(s[:len(prefix)], prefix)\n}","line":{"from":193,"to":195}} {"id":100016947,"name":"headerValue","signature":"func headerValue(h http.Header, headerNames []string) string","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader.go","code":"func headerValue(h http.Header, headerNames []string) string {\n\tfor _, headerName := range headerNames {\n\t\theaderValue := h.Get(headerName)\n\t\tif len(headerValue) \u003e 0 {\n\t\t\treturn headerValue\n\t\t}\n\t}\n\treturn \"\"\n}","line":{"from":197,"to":205}} {"id":100016948,"name":"allHeaderValues","signature":"func allHeaderValues(h http.Header, headerNames []string) []string","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader.go","code":"func allHeaderValues(h http.Header, headerNames []string) []string {\n\tret := []string{}\n\tfor _, headerName := range headerNames {\n\t\theaderKey := http.CanonicalHeaderKey(headerName)\n\t\tvalues, ok := h[headerKey]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, headerValue := range values {\n\t\t\tif len(headerValue) \u003e 0 {\n\t\t\t\tret = append(ret, headerValue)\n\t\t\t}\n\t\t}\n\t}\n\treturn ret\n}","line":{"from":207,"to":223}} {"id":100016949,"name":"unescapeExtraKey","signature":"func unescapeExtraKey(encodedKey string) string","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader.go","code":"func unescapeExtraKey(encodedKey string) string {\n\tkey, err := url.PathUnescape(encodedKey) // Decode %-encoded bytes.\n\tif err != nil {\n\t\treturn encodedKey // Always record extra strings, even if malformed/unencoded.\n\t}\n\treturn key\n}","line":{"from":225,"to":231}} {"id":100016950,"name":"newExtra","signature":"func newExtra(h http.Header, headerPrefixes []string) map[string][]string","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader.go","code":"func newExtra(h http.Header, headerPrefixes []string) map[string][]string {\n\tret := map[string][]string{}\n\n\t// we have to iterate over prefixes first in order to have proper ordering inside the value slices\n\tfor _, prefix := range headerPrefixes {\n\t\tfor headerName, vv := range h {\n\t\t\tif !hasPrefixIgnoreCase(headerName, prefix) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\textraKey := unescapeExtraKey(strings.ToLower(headerName[len(prefix):]))\n\t\t\tret[extraKey] = append(ret[extraKey], vv...)\n\t\t}\n\t}\n\n\treturn ret\n}","line":{"from":233,"to":249}} {"id":100016951,"name":"NewRequestHeaderAuthRequestController","signature":"func NewRequestHeaderAuthRequestController(","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader_controller.go","code":"// NewRequestHeaderAuthRequestController creates a new controller that implements RequestHeaderAuthRequestController\nfunc NewRequestHeaderAuthRequestController(\n\tcmName string,\n\tcmNamespace string,\n\tclient kubernetes.Interface,\n\tusernameHeadersKey, groupHeadersKey, extraHeaderPrefixesKey, allowedClientNamesKey string) *RequestHeaderAuthRequestController {\n\tc := \u0026RequestHeaderAuthRequestController{\n\t\tname: \"RequestHeaderAuthRequestController\",\n\n\t\tclient: client,\n\n\t\tconfigmapName: cmName,\n\t\tconfigmapNamespace: cmNamespace,\n\n\t\tusernameHeadersKey: usernameHeadersKey,\n\t\tgroupHeadersKey: groupHeadersKey,\n\t\textraHeaderPrefixesKey: extraHeaderPrefixesKey,\n\t\tallowedClientNamesKey: allowedClientNamesKey,\n\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"RequestHeaderAuthRequestController\"),\n\t}\n\n\t// we construct our own informer because we need such a small subset of the information available. Just one namespace.\n\tc.configmapInformer = coreinformers.NewFilteredConfigMapInformer(client, c.configmapNamespace, 12*time.Hour, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, func(listOptions *metav1.ListOptions) {\n\t\tlistOptions.FieldSelector = fields.OneTermEqualSelector(\"metadata.name\", c.configmapName).String()\n\t})\n\n\tc.configmapInformer.AddEventHandler(cache.FilteringResourceEventHandler{\n\t\tFilterFunc: func(obj interface{}) bool {\n\t\t\tif cast, ok := obj.(*corev1.ConfigMap); ok {\n\t\t\t\treturn cast.Name == c.configmapName \u0026\u0026 cast.Namespace == c.configmapNamespace\n\t\t\t}\n\t\t\tif tombstone, ok := obj.(cache.DeletedFinalStateUnknown); ok {\n\t\t\t\tif cast, ok := tombstone.Obj.(*corev1.ConfigMap); ok {\n\t\t\t\t\treturn cast.Name == c.configmapName \u0026\u0026 cast.Namespace == c.configmapNamespace\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true // always return true just in case. The checks are fairly cheap\n\t\t},\n\t\tHandler: cache.ResourceEventHandlerFuncs{\n\t\t\t// we have a filter, so any time we're called, we may as well queue. We only ever check one configmap\n\t\t\t// so we don't have to be choosy about our key.\n\t\t\tAddFunc: func(obj interface{}) {\n\t\t\t\tc.queue.Add(c.keyFn())\n\t\t\t},\n\t\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\t\tc.queue.Add(c.keyFn())\n\t\t\t},\n\t\t\tDeleteFunc: func(obj interface{}) {\n\t\t\t\tc.queue.Add(c.keyFn())\n\t\t\t},\n\t\t},\n\t})\n\n\tc.configmapLister = corev1listers.NewConfigMapLister(c.configmapInformer.GetIndexer()).ConfigMaps(c.configmapNamespace)\n\tc.configmapInformerSynced = c.configmapInformer.HasSynced\n\n\treturn c\n}","line":{"from":88,"to":146}} {"id":100016952,"name":"UsernameHeaders","signature":"func (c *RequestHeaderAuthRequestController) UsernameHeaders() []string","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader_controller.go","code":"func (c *RequestHeaderAuthRequestController) UsernameHeaders() []string {\n\treturn c.loadRequestHeaderFor(c.usernameHeadersKey)\n}","line":{"from":148,"to":150}} {"id":100016953,"name":"GroupHeaders","signature":"func (c *RequestHeaderAuthRequestController) GroupHeaders() []string","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader_controller.go","code":"func (c *RequestHeaderAuthRequestController) GroupHeaders() []string {\n\treturn c.loadRequestHeaderFor(c.groupHeadersKey)\n}","line":{"from":152,"to":154}} {"id":100016954,"name":"ExtraHeaderPrefixes","signature":"func (c *RequestHeaderAuthRequestController) ExtraHeaderPrefixes() []string","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader_controller.go","code":"func (c *RequestHeaderAuthRequestController) ExtraHeaderPrefixes() []string {\n\treturn c.loadRequestHeaderFor(c.extraHeaderPrefixesKey)\n}","line":{"from":156,"to":158}} {"id":100016955,"name":"AllowedClientNames","signature":"func (c *RequestHeaderAuthRequestController) AllowedClientNames() []string","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader_controller.go","code":"func (c *RequestHeaderAuthRequestController) AllowedClientNames() []string {\n\treturn c.loadRequestHeaderFor(c.allowedClientNamesKey)\n}","line":{"from":160,"to":162}} {"id":100016956,"name":"Run","signature":"func (c *RequestHeaderAuthRequestController) Run(ctx context.Context, workers int)","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader_controller.go","code":"// Run starts RequestHeaderAuthRequestController controller and blocks until stopCh is closed.\nfunc (c *RequestHeaderAuthRequestController) Run(ctx context.Context, workers int) {\n\tdefer utilruntime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\n\tklog.Infof(\"Starting %s\", c.name)\n\tdefer klog.Infof(\"Shutting down %s\", c.name)\n\n\tgo c.configmapInformer.Run(ctx.Done())\n\n\t// wait for caches to fill before starting your work\n\tif !cache.WaitForNamedCacheSync(c.name, ctx.Done(), c.configmapInformerSynced) {\n\t\treturn\n\t}\n\n\t// doesn't matter what workers say, only start one.\n\tgo wait.Until(c.runWorker, time.Second, ctx.Done())\n\n\t\u003c-ctx.Done()\n}","line":{"from":164,"to":183}} {"id":100016957,"name":"RunOnce","signature":"func (c *RequestHeaderAuthRequestController) RunOnce(ctx context.Context) error","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader_controller.go","code":"// // RunOnce runs a single sync loop\nfunc (c *RequestHeaderAuthRequestController) RunOnce(ctx context.Context) error {\n\tconfigMap, err := c.client.CoreV1().ConfigMaps(c.configmapNamespace).Get(ctx, c.configmapName, metav1.GetOptions{})\n\tswitch {\n\tcase errors.IsNotFound(err):\n\t\t// ignore, authConfigMap is nil now\n\t\treturn nil\n\tcase errors.IsForbidden(err):\n\t\tklog.Warningf(\"Unable to get configmap/%s in %s. Usually fixed by \"+\n\t\t\t\"'kubectl create rolebinding -n %s ROLEBINDING_NAME --role=%s --serviceaccount=YOUR_NS:YOUR_SA'\",\n\t\t\tc.configmapName, c.configmapNamespace, c.configmapNamespace, authenticationRoleName)\n\t\treturn err\n\tcase err != nil:\n\t\treturn err\n\t}\n\treturn c.syncConfigMap(configMap)\n}","line":{"from":185,"to":201}} {"id":100016958,"name":"runWorker","signature":"func (c *RequestHeaderAuthRequestController) runWorker()","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader_controller.go","code":"func (c *RequestHeaderAuthRequestController) runWorker() {\n\tfor c.processNextWorkItem() {\n\t}\n}","line":{"from":203,"to":206}} {"id":100016959,"name":"processNextWorkItem","signature":"func (c *RequestHeaderAuthRequestController) processNextWorkItem() bool","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader_controller.go","code":"func (c *RequestHeaderAuthRequestController) processNextWorkItem() bool {\n\tdsKey, quit := c.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.queue.Done(dsKey)\n\n\terr := c.sync()\n\tif err == nil {\n\t\tc.queue.Forget(dsKey)\n\t\treturn true\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"%v failed with : %v\", dsKey, err))\n\tc.queue.AddRateLimited(dsKey)\n\n\treturn true\n}","line":{"from":208,"to":225}} {"id":100016960,"name":"sync","signature":"func (c *RequestHeaderAuthRequestController) sync() error","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader_controller.go","code":"// sync reads the config and propagates the changes to exportedRequestHeaderBundle\n// which is exposed by the set of methods that are used to fill RequestHeaderConfig struct\nfunc (c *RequestHeaderAuthRequestController) sync() error {\n\tconfigMap, err := c.configmapLister.Get(c.configmapName)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.syncConfigMap(configMap)\n}","line":{"from":227,"to":235}} {"id":100016961,"name":"syncConfigMap","signature":"func (c *RequestHeaderAuthRequestController) syncConfigMap(configMap *corev1.ConfigMap) error","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader_controller.go","code":"func (c *RequestHeaderAuthRequestController) syncConfigMap(configMap *corev1.ConfigMap) error {\n\thasChanged, newRequestHeaderBundle, err := c.hasRequestHeaderBundleChanged(configMap)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif hasChanged {\n\t\tc.exportedRequestHeaderBundle.Store(newRequestHeaderBundle)\n\t\tklog.V(2).Infof(\"Loaded a new request header values for %v\", c.name)\n\t}\n\treturn nil\n}","line":{"from":237,"to":247}} {"id":100016962,"name":"hasRequestHeaderBundleChanged","signature":"func (c *RequestHeaderAuthRequestController) hasRequestHeaderBundleChanged(cm *corev1.ConfigMap) (bool, *requestHeaderBundle, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader_controller.go","code":"func (c *RequestHeaderAuthRequestController) hasRequestHeaderBundleChanged(cm *corev1.ConfigMap) (bool, *requestHeaderBundle, error) {\n\tcurrentHeadersBundle, err := c.getRequestHeaderBundleFromConfigMap(cm)\n\tif err != nil {\n\t\treturn false, nil, err\n\t}\n\n\trawHeaderBundle := c.exportedRequestHeaderBundle.Load()\n\tif rawHeaderBundle == nil {\n\t\treturn true, currentHeadersBundle, nil\n\t}\n\n\t// check to see if we have a change. If the values are the same, do nothing.\n\tloadedHeadersBundle, ok := rawHeaderBundle.(*requestHeaderBundle)\n\tif !ok {\n\t\treturn true, currentHeadersBundle, nil\n\t}\n\n\tif !equality.Semantic.DeepEqual(loadedHeadersBundle, currentHeadersBundle) {\n\t\treturn true, currentHeadersBundle, nil\n\t}\n\treturn false, nil, nil\n}","line":{"from":249,"to":270}} {"id":100016963,"name":"getRequestHeaderBundleFromConfigMap","signature":"func (c *RequestHeaderAuthRequestController) getRequestHeaderBundleFromConfigMap(cm *corev1.ConfigMap) (*requestHeaderBundle, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader_controller.go","code":"func (c *RequestHeaderAuthRequestController) getRequestHeaderBundleFromConfigMap(cm *corev1.ConfigMap) (*requestHeaderBundle, error) {\n\tusernameHeaderCurrentValue, err := deserializeStrings(cm.Data[c.usernameHeadersKey])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgroupHeadersCurrentValue, err := deserializeStrings(cm.Data[c.groupHeadersKey])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\textraHeaderPrefixesCurrentValue, err := deserializeStrings(cm.Data[c.extraHeaderPrefixesKey])\n\tif err != nil {\n\t\treturn nil, err\n\n\t}\n\n\tallowedClientNamesCurrentValue, err := deserializeStrings(cm.Data[c.allowedClientNamesKey])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026requestHeaderBundle{\n\t\tUsernameHeaders: usernameHeaderCurrentValue,\n\t\tGroupHeaders: groupHeadersCurrentValue,\n\t\tExtraHeaderPrefixes: extraHeaderPrefixesCurrentValue,\n\t\tAllowedClientNames: allowedClientNamesCurrentValue,\n\t}, nil\n}","line":{"from":272,"to":300}} {"id":100016964,"name":"loadRequestHeaderFor","signature":"func (c *RequestHeaderAuthRequestController) loadRequestHeaderFor(key string) []string","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader_controller.go","code":"func (c *RequestHeaderAuthRequestController) loadRequestHeaderFor(key string) []string {\n\trawHeaderBundle := c.exportedRequestHeaderBundle.Load()\n\tif rawHeaderBundle == nil {\n\t\treturn nil // this can happen if we've been unable load data from the apiserver for some reason\n\t}\n\theaderBundle := rawHeaderBundle.(*requestHeaderBundle)\n\n\tswitch key {\n\tcase c.usernameHeadersKey:\n\t\treturn headerBundle.UsernameHeaders\n\tcase c.groupHeadersKey:\n\t\treturn headerBundle.GroupHeaders\n\tcase c.extraHeaderPrefixesKey:\n\t\treturn headerBundle.ExtraHeaderPrefixes\n\tcase c.allowedClientNamesKey:\n\t\treturn headerBundle.AllowedClientNames\n\tdefault:\n\t\treturn nil\n\t}\n}","line":{"from":302,"to":321}} {"id":100016965,"name":"keyFn","signature":"func (c *RequestHeaderAuthRequestController) keyFn() string","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader_controller.go","code":"func (c *RequestHeaderAuthRequestController) keyFn() string {\n\t// this format matches DeletionHandlingMetaNamespaceKeyFunc for our single key\n\treturn c.configmapNamespace + \"/\" + c.configmapName\n}","line":{"from":323,"to":326}} {"id":100016966,"name":"deserializeStrings","signature":"func deserializeStrings(in string) ([]string, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/headerrequest/requestheader_controller.go","code":"func deserializeStrings(in string) ([]string, error) {\n\tif len(in) == 0 {\n\t\treturn nil, nil\n\t}\n\tvar ret []string\n\tif err := json.Unmarshal([]byte(in), \u0026ret); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ret, nil\n}","line":{"from":328,"to":337}} {"id":100016967,"name":"New","signature":"func New(authRequestHandlers ...authenticator.Request) authenticator.Request","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/union/union.go","code":"// New returns a request authenticator that validates credentials using a chain of authenticator.Request objects.\n// The entire chain is tried until one succeeds. If all fail, an aggregate error is returned.\nfunc New(authRequestHandlers ...authenticator.Request) authenticator.Request {\n\tif len(authRequestHandlers) == 1 {\n\t\treturn authRequestHandlers[0]\n\t}\n\treturn \u0026unionAuthRequestHandler{Handlers: authRequestHandlers, FailOnError: false}\n}","line":{"from":34,"to":41}} {"id":100016968,"name":"NewFailOnError","signature":"func NewFailOnError(authRequestHandlers ...authenticator.Request) authenticator.Request","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/union/union.go","code":"// NewFailOnError returns a request authenticator that validates credentials using a chain of authenticator.Request objects.\n// The first error short-circuits the chain.\nfunc NewFailOnError(authRequestHandlers ...authenticator.Request) authenticator.Request {\n\tif len(authRequestHandlers) == 1 {\n\t\treturn authRequestHandlers[0]\n\t}\n\treturn \u0026unionAuthRequestHandler{Handlers: authRequestHandlers, FailOnError: true}\n}","line":{"from":43,"to":50}} {"id":100016969,"name":"AuthenticateRequest","signature":"func (authHandler *unionAuthRequestHandler) AuthenticateRequest(req *http.Request) (*authenticator.Response, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/union/union.go","code":"// AuthenticateRequest authenticates the request using a chain of authenticator.Request objects.\nfunc (authHandler *unionAuthRequestHandler) AuthenticateRequest(req *http.Request) (*authenticator.Response, bool, error) {\n\tvar errlist []error\n\tfor _, currAuthRequestHandler := range authHandler.Handlers {\n\t\tresp, ok, err := currAuthRequestHandler.AuthenticateRequest(req)\n\t\tif err != nil {\n\t\t\tif authHandler.FailOnError {\n\t\t\t\treturn resp, ok, err\n\t\t\t}\n\t\t\terrlist = append(errlist, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif ok {\n\t\t\treturn resp, ok, err\n\t\t}\n\t}\n\n\treturn nil, false, utilerrors.NewAggregate(errlist)\n}","line":{"from":52,"to":71}} {"id":100016970,"name":"NewProtocolAuthenticator","signature":"func NewProtocolAuthenticator(auth authenticator.Token) *ProtocolAuthenticator","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/websocket/protocol.go","code":"func NewProtocolAuthenticator(auth authenticator.Token) *ProtocolAuthenticator {\n\treturn \u0026ProtocolAuthenticator{auth}\n}","line":{"from":44,"to":46}} {"id":100016971,"name":"AuthenticateRequest","signature":"func (a *ProtocolAuthenticator) AuthenticateRequest(req *http.Request) (*authenticator.Response, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/websocket/protocol.go","code":"func (a *ProtocolAuthenticator) AuthenticateRequest(req *http.Request) (*authenticator.Response, bool, error) {\n\t// Only accept websocket connections\n\tif !wsstream.IsWebSocketRequest(req) {\n\t\treturn nil, false, nil\n\t}\n\n\ttoken := \"\"\n\tsawTokenProtocol := false\n\tfilteredProtocols := []string{}\n\tfor _, protocolHeader := range req.Header[protocolHeader] {\n\t\tfor _, protocol := range strings.Split(protocolHeader, \",\") {\n\t\t\tprotocol = strings.TrimSpace(protocol)\n\n\t\t\tif !strings.HasPrefix(protocol, bearerProtocolPrefix) {\n\t\t\t\tfilteredProtocols = append(filteredProtocols, protocol)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif sawTokenProtocol {\n\t\t\t\treturn nil, false, errors.New(\"multiple base64.bearer.authorization tokens specified\")\n\t\t\t}\n\t\t\tsawTokenProtocol = true\n\n\t\t\tencodedToken := strings.TrimPrefix(protocol, bearerProtocolPrefix)\n\t\t\tdecodedToken, err := base64.RawURLEncoding.DecodeString(encodedToken)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, false, errors.New(\"invalid base64.bearer.authorization token encoding\")\n\t\t\t}\n\t\t\tif !utf8.Valid(decodedToken) {\n\t\t\t\treturn nil, false, errors.New(\"invalid base64.bearer.authorization token\")\n\t\t\t}\n\t\t\ttoken = string(decodedToken)\n\t\t}\n\t}\n\n\t// Must pass at least one other subprotocol so that we can remove the one containing the bearer token,\n\t// and there is at least one to echo back to the client\n\tif len(token) \u003e 0 \u0026\u0026 len(filteredProtocols) == 0 {\n\t\treturn nil, false, errors.New(\"missing additional subprotocol\")\n\t}\n\n\tif len(token) == 0 {\n\t\treturn nil, false, nil\n\t}\n\n\tresp, ok, err := a.auth.AuthenticateToken(req.Context(), token)\n\n\t// on success, remove the protocol with the token\n\tif ok {\n\t\t// https://tools.ietf.org/html/rfc6455#section-11.3.4 indicates the Sec-WebSocket-Protocol header may appear multiple times\n\t\t// in a request, and is logically the same as a single Sec-WebSocket-Protocol header field that contains all values\n\t\treq.Header.Set(protocolHeader, strings.Join(filteredProtocols, \",\"))\n\t}\n\n\t// If the token authenticator didn't error, provide a default error\n\tif !ok \u0026\u0026 err == nil {\n\t\terr = errInvalidToken\n\t}\n\n\treturn resp, ok, err\n}","line":{"from":48,"to":108}} {"id":100016972,"name":"StaticVerifierFn","signature":"func StaticVerifierFn(opts x509.VerifyOptions) VerifyOptionFunc","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/x509/verify_options.go","code":"// StaticVerifierFn is a VerifyOptionFunc that always returns the same value. This allows verify options that cannot change.\nfunc StaticVerifierFn(opts x509.VerifyOptions) VerifyOptionFunc {\n\treturn func() (x509.VerifyOptions, bool) {\n\t\treturn opts, true\n\t}\n}","line":{"from":26,"to":31}} {"id":100016973,"name":"NewStaticVerifierFromFile","signature":"func NewStaticVerifierFromFile(clientCA string) (VerifyOptionFunc, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/x509/verify_options.go","code":"// NewStaticVerifierFromFile creates a new verification func from a file. It reads the content and then fails.\n// It will return a nil function if you pass an empty CA file.\nfunc NewStaticVerifierFromFile(clientCA string) (VerifyOptionFunc, error) {\n\tif len(clientCA) == 0 {\n\t\treturn nil, nil\n\t}\n\n\t// Wrap with an x509 verifier\n\tvar err error\n\topts := DefaultVerifyOptions()\n\topts.Roots, err = cert.NewPool(clientCA)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error loading certs from %s: %v\", clientCA, err)\n\t}\n\n\treturn StaticVerifierFn(opts), nil\n}","line":{"from":33,"to":49}} {"id":100016974,"name":"Value","signature":"func (d StringSliceProviderFunc) Value() []string","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/x509/verify_options.go","code":"// Value returns the current string slice. Callers should never mutate the returned value.\nfunc (d StringSliceProviderFunc) Value() []string {\n\treturn d()\n}","line":{"from":60,"to":63}} {"id":100016975,"name":"Value","signature":"func (s StaticStringSlice) Value() []string","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/x509/verify_options.go","code":"// Value returns the current string slice. Callers should never mutate the returned value.\nfunc (s StaticStringSlice) Value() []string {\n\treturn s\n}","line":{"from":68,"to":71}} {"id":100016976,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/x509/x509.go","code":"func init() {\n\tlegacyregistry.MustRegister(clientCertificateExpirationHistogram)\n}","line":{"from":70,"to":72}} {"id":100016977,"name":"User","signature":"func (f UserConversionFunc) User(chain []*x509.Certificate) (*authenticator.Response, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/x509/x509.go","code":"// User implements x509.UserConversion\nfunc (f UserConversionFunc) User(chain []*x509.Certificate) (*authenticator.Response, bool, error) {\n\treturn f(chain)\n}","line":{"from":82,"to":85}} {"id":100016978,"name":"columnSeparatedHex","signature":"func columnSeparatedHex(d []byte) string","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/x509/x509.go","code":"func columnSeparatedHex(d []byte) string {\n\th := strings.ToUpper(hex.EncodeToString(d))\n\tvar sb strings.Builder\n\tfor i, r := range h {\n\t\tsb.WriteRune(r)\n\t\tif i%2 == 1 \u0026\u0026 i != len(h)-1 {\n\t\t\tsb.WriteRune(':')\n\t\t}\n\t}\n\treturn sb.String()\n}","line":{"from":87,"to":97}} {"id":100016979,"name":"certificateIdentifier","signature":"func certificateIdentifier(c *x509.Certificate) string","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/x509/x509.go","code":"func certificateIdentifier(c *x509.Certificate) string {\n\treturn fmt.Sprintf(\n\t\t\"SN=%d, SKID=%s, AKID=%s\",\n\t\tc.SerialNumber,\n\t\tcolumnSeparatedHex(c.SubjectKeyId),\n\t\tcolumnSeparatedHex(c.AuthorityKeyId),\n\t)\n}","line":{"from":99,"to":106}} {"id":100016980,"name":"New","signature":"func New(opts x509.VerifyOptions, user UserConversion) *Authenticator","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/x509/x509.go","code":"// New returns a request.Authenticator that verifies client certificates using the provided\n// VerifyOptions, and converts valid certificate chains into user.Info using the provided UserConversion\nfunc New(opts x509.VerifyOptions, user UserConversion) *Authenticator {\n\treturn NewDynamic(StaticVerifierFn(opts), user)\n}","line":{"from":120,"to":124}} {"id":100016981,"name":"NewDynamic","signature":"func NewDynamic(verifyOptionsFn VerifyOptionFunc, user UserConversion) *Authenticator","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/x509/x509.go","code":"// NewDynamic returns a request.Authenticator that verifies client certificates using the provided\n// VerifyOptionFunc (which may be dynamic), and converts valid certificate chains into user.Info using the provided UserConversion\nfunc NewDynamic(verifyOptionsFn VerifyOptionFunc, user UserConversion) *Authenticator {\n\treturn \u0026Authenticator{verifyOptionsFn, user}\n}","line":{"from":126,"to":130}} {"id":100016982,"name":"AuthenticateRequest","signature":"func (a *Authenticator) AuthenticateRequest(req *http.Request) (*authenticator.Response, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/x509/x509.go","code":"// AuthenticateRequest authenticates the request using presented client certificates\nfunc (a *Authenticator) AuthenticateRequest(req *http.Request) (*authenticator.Response, bool, error) {\n\tif req.TLS == nil || len(req.TLS.PeerCertificates) == 0 {\n\t\treturn nil, false, nil\n\t}\n\n\t// Use intermediates, if provided\n\toptsCopy, ok := a.verifyOptionsFn()\n\t// if there are intentionally no verify options, then we cannot authenticate this request\n\tif !ok {\n\t\treturn nil, false, nil\n\t}\n\tif optsCopy.Intermediates == nil \u0026\u0026 len(req.TLS.PeerCertificates) \u003e 1 {\n\t\toptsCopy.Intermediates = x509.NewCertPool()\n\t\tfor _, intermediate := range req.TLS.PeerCertificates[1:] {\n\t\t\toptsCopy.Intermediates.AddCert(intermediate)\n\t\t}\n\t}\n\n\tremaining := req.TLS.PeerCertificates[0].NotAfter.Sub(time.Now())\n\tclientCertificateExpirationHistogram.WithContext(req.Context()).Observe(remaining.Seconds())\n\tchains, err := req.TLS.PeerCertificates[0].Verify(optsCopy)\n\tif err != nil {\n\t\treturn nil, false, fmt.Errorf(\n\t\t\t\"verifying certificate %s failed: %w\",\n\t\t\tcertificateIdentifier(req.TLS.PeerCertificates[0]),\n\t\t\terr,\n\t\t)\n\t}\n\n\tvar errlist []error\n\tfor _, chain := range chains {\n\t\tuser, ok, err := a.user.User(chain)\n\t\tif err != nil {\n\t\t\terrlist = append(errlist, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif ok {\n\t\t\treturn user, ok, err\n\t\t}\n\t}\n\treturn nil, false, utilerrors.NewAggregate(errlist)\n}","line":{"from":132,"to":175}} {"id":100016983,"name":"NewVerifier","signature":"func NewVerifier(opts x509.VerifyOptions, auth authenticator.Request, allowedCommonNames sets.String) authenticator.Request","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/x509/x509.go","code":"// NewVerifier create a request.Authenticator by verifying a client cert on the request, then delegating to the wrapped auth\nfunc NewVerifier(opts x509.VerifyOptions, auth authenticator.Request, allowedCommonNames sets.String) authenticator.Request {\n\treturn NewDynamicCAVerifier(StaticVerifierFn(opts), auth, StaticStringSlice(allowedCommonNames.List()))\n}","line":{"from":187,"to":190}} {"id":100016984,"name":"NewDynamicCAVerifier","signature":"func NewDynamicCAVerifier(verifyOptionsFn VerifyOptionFunc, auth authenticator.Request, allowedCommonNames StringSliceProvider) authenticator.Request","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/x509/x509.go","code":"// NewDynamicCAVerifier create a request.Authenticator by verifying a client cert on the request, then delegating to the wrapped auth\nfunc NewDynamicCAVerifier(verifyOptionsFn VerifyOptionFunc, auth authenticator.Request, allowedCommonNames StringSliceProvider) authenticator.Request {\n\treturn \u0026Verifier{verifyOptionsFn, auth, allowedCommonNames}\n}","line":{"from":192,"to":195}} {"id":100016985,"name":"AuthenticateRequest","signature":"func (a *Verifier) AuthenticateRequest(req *http.Request) (*authenticator.Response, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/x509/x509.go","code":"// AuthenticateRequest verifies the presented client certificate, then delegates to the wrapped auth\nfunc (a *Verifier) AuthenticateRequest(req *http.Request) (*authenticator.Response, bool, error) {\n\tif req.TLS == nil || len(req.TLS.PeerCertificates) == 0 {\n\t\treturn nil, false, nil\n\t}\n\n\t// Use intermediates, if provided\n\toptsCopy, ok := a.verifyOptionsFn()\n\t// if there are intentionally no verify options, then we cannot authenticate this request\n\tif !ok {\n\t\treturn nil, false, nil\n\t}\n\tif optsCopy.Intermediates == nil \u0026\u0026 len(req.TLS.PeerCertificates) \u003e 1 {\n\t\toptsCopy.Intermediates = x509.NewCertPool()\n\t\tfor _, intermediate := range req.TLS.PeerCertificates[1:] {\n\t\t\toptsCopy.Intermediates.AddCert(intermediate)\n\t\t}\n\t}\n\n\tif _, err := req.TLS.PeerCertificates[0].Verify(optsCopy); err != nil {\n\t\treturn nil, false, err\n\t}\n\tif err := a.verifySubject(req.TLS.PeerCertificates[0].Subject); err != nil {\n\t\treturn nil, false, err\n\t}\n\treturn a.auth.AuthenticateRequest(req)\n}","line":{"from":197,"to":223}} {"id":100016986,"name":"verifySubject","signature":"func (a *Verifier) verifySubject(subject pkix.Name) error","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/x509/x509.go","code":"func (a *Verifier) verifySubject(subject pkix.Name) error {\n\t// No CN restrictions\n\tif len(a.allowedCommonNames.Value()) == 0 {\n\t\treturn nil\n\t}\n\t// Enforce CN restrictions\n\tfor _, allowedCommonName := range a.allowedCommonNames.Value() {\n\t\tif allowedCommonName == subject.CommonName {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"x509: subject with cn=%s is not in the allowed list\", subject.CommonName)\n}","line":{"from":225,"to":237}} {"id":100016987,"name":"DefaultVerifyOptions","signature":"func DefaultVerifyOptions() x509.VerifyOptions","file":"staging/src/k8s.io/apiserver/pkg/authentication/request/x509/x509.go","code":"// DefaultVerifyOptions returns VerifyOptions that use the system root certificates, current time,\n// and requires certificates to be valid for client auth (x509.ExtKeyUsageClientAuth)\nfunc DefaultVerifyOptions() x509.VerifyOptions {\n\treturn x509.VerifyOptions{\n\t\tKeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},\n\t}\n}","line":{"from":239,"to":245}} {"id":100016988,"name":"MakeUsername","signature":"func MakeUsername(namespace, name string) string","file":"staging/src/k8s.io/apiserver/pkg/authentication/serviceaccount/util.go","code":"// MakeUsername generates a username from the given namespace and ServiceAccount name.\n// The resulting username can be passed to SplitUsername to extract the original namespace and ServiceAccount name.\nfunc MakeUsername(namespace, name string) string {\n\treturn ServiceAccountUsernamePrefix + namespace + ServiceAccountUsernameSeparator + name\n}","line":{"from":47,"to":51}} {"id":100016989,"name":"MatchesUsername","signature":"func MatchesUsername(namespace, name string, username string) bool","file":"staging/src/k8s.io/apiserver/pkg/authentication/serviceaccount/util.go","code":"// MatchesUsername checks whether the provided username matches the namespace and name without\n// allocating. Use this when checking a service account namespace and name against a known string.\nfunc MatchesUsername(namespace, name string, username string) bool {\n\tif !strings.HasPrefix(username, ServiceAccountUsernamePrefix) {\n\t\treturn false\n\t}\n\tusername = username[len(ServiceAccountUsernamePrefix):]\n\n\tif !strings.HasPrefix(username, namespace) {\n\t\treturn false\n\t}\n\tusername = username[len(namespace):]\n\n\tif !strings.HasPrefix(username, ServiceAccountUsernameSeparator) {\n\t\treturn false\n\t}\n\tusername = username[len(ServiceAccountUsernameSeparator):]\n\n\treturn username == name\n}","line":{"from":53,"to":72}} {"id":100016990,"name":"SplitUsername","signature":"func SplitUsername(username string) (string, string, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/serviceaccount/util.go","code":"// SplitUsername returns the namespace and ServiceAccount name embedded in the given username,\n// or an error if the username is not a valid name produced by MakeUsername\nfunc SplitUsername(username string) (string, string, error) {\n\tif !strings.HasPrefix(username, ServiceAccountUsernamePrefix) {\n\t\treturn \"\", \"\", invalidUsernameErr\n\t}\n\ttrimmed := strings.TrimPrefix(username, ServiceAccountUsernamePrefix)\n\tparts := strings.Split(trimmed, ServiceAccountUsernameSeparator)\n\tif len(parts) != 2 {\n\t\treturn \"\", \"\", invalidUsernameErr\n\t}\n\tnamespace, name := parts[0], parts[1]\n\tif len(apimachineryvalidation.ValidateNamespaceName(namespace, false)) != 0 {\n\t\treturn \"\", \"\", invalidUsernameErr\n\t}\n\tif len(apimachineryvalidation.ValidateServiceAccountName(name, false)) != 0 {\n\t\treturn \"\", \"\", invalidUsernameErr\n\t}\n\treturn namespace, name, nil\n}","line":{"from":76,"to":95}} {"id":100016991,"name":"MakeGroupNames","signature":"func MakeGroupNames(namespace string) []string","file":"staging/src/k8s.io/apiserver/pkg/authentication/serviceaccount/util.go","code":"// MakeGroupNames generates service account group names for the given namespace\nfunc MakeGroupNames(namespace string) []string {\n\treturn []string{\n\t\tAllServiceAccountsGroup,\n\t\tMakeNamespaceGroupName(namespace),\n\t}\n}","line":{"from":97,"to":103}} {"id":100016992,"name":"MakeNamespaceGroupName","signature":"func MakeNamespaceGroupName(namespace string) string","file":"staging/src/k8s.io/apiserver/pkg/authentication/serviceaccount/util.go","code":"// MakeNamespaceGroupName returns the name of the group all service accounts in the namespace are included in\nfunc MakeNamespaceGroupName(namespace string) string {\n\treturn ServiceAccountGroupPrefix + namespace\n}","line":{"from":105,"to":108}} {"id":100016993,"name":"UserInfo","signature":"func UserInfo(namespace, name, uid string) user.Info","file":"staging/src/k8s.io/apiserver/pkg/authentication/serviceaccount/util.go","code":"// UserInfo returns a user.Info interface for the given namespace, service account name and UID\nfunc UserInfo(namespace, name, uid string) user.Info {\n\treturn (\u0026ServiceAccountInfo{\n\t\tName: name,\n\t\tNamespace: namespace,\n\t\tUID: uid,\n\t}).UserInfo()\n}","line":{"from":110,"to":117}} {"id":100016994,"name":"UserInfo","signature":"func (sa *ServiceAccountInfo) UserInfo() user.Info","file":"staging/src/k8s.io/apiserver/pkg/authentication/serviceaccount/util.go","code":"func (sa *ServiceAccountInfo) UserInfo() user.Info {\n\tinfo := \u0026user.DefaultInfo{\n\t\tName: MakeUsername(sa.Namespace, sa.Name),\n\t\tUID: sa.UID,\n\t\tGroups: MakeGroupNames(sa.Namespace),\n\t}\n\tif sa.PodName != \"\" \u0026\u0026 sa.PodUID != \"\" {\n\t\tinfo.Extra = map[string][]string{\n\t\t\tPodNameKey: {sa.PodName},\n\t\t\tPodUIDKey: {sa.PodUID},\n\t\t}\n\t}\n\treturn info\n}","line":{"from":124,"to":137}} {"id":100016995,"name":"IsServiceAccountToken","signature":"func IsServiceAccountToken(secret *v1.Secret, sa *v1.ServiceAccount) bool","file":"staging/src/k8s.io/apiserver/pkg/authentication/serviceaccount/util.go","code":"// IsServiceAccountToken returns true if the secret is a valid api token for the service account\nfunc IsServiceAccountToken(secret *v1.Secret, sa *v1.ServiceAccount) bool {\n\tif secret.Type != v1.SecretTypeServiceAccountToken {\n\t\treturn false\n\t}\n\n\tname := secret.Annotations[v1.ServiceAccountNameKey]\n\tuid := secret.Annotations[v1.ServiceAccountUIDKey]\n\tif name != sa.Name {\n\t\t// Name must match\n\t\treturn false\n\t}\n\tif len(uid) \u003e 0 \u0026\u0026 uid != string(sa.UID) {\n\t\t// If UID is specified, it must match\n\t\treturn false\n\t}\n\n\treturn true\n}","line":{"from":139,"to":157}} {"id":100016996,"name":"GetOrCreateServiceAccount","signature":"func GetOrCreateServiceAccount(coreClient v1core.CoreV1Interface, namespace, name string) (*v1.ServiceAccount, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/serviceaccount/util.go","code":"func GetOrCreateServiceAccount(coreClient v1core.CoreV1Interface, namespace, name string) (*v1.ServiceAccount, error) {\n\tsa, err := coreClient.ServiceAccounts(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\tif err == nil {\n\t\treturn sa, nil\n\t}\n\tif !apierrors.IsNotFound(err) {\n\t\treturn nil, err\n\t}\n\n\t// Create the namespace if we can't verify it exists.\n\t// Tolerate errors, since we don't know whether this component has namespace creation permissions.\n\tif _, err := coreClient.Namespaces().Get(context.TODO(), namespace, metav1.GetOptions{}); apierrors.IsNotFound(err) {\n\t\tif _, err = coreClient.Namespaces().Create(context.TODO(), \u0026v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace}}, metav1.CreateOptions{}); err != nil \u0026\u0026 !apierrors.IsAlreadyExists(err) {\n\t\t\tklog.Warningf(\"create non-exist namespace %s failed:%v\", namespace, err)\n\t\t}\n\t}\n\n\t// Create the service account\n\tsa, err = coreClient.ServiceAccounts(namespace).Create(context.TODO(), \u0026v1.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Namespace: namespace, Name: name}}, metav1.CreateOptions{})\n\tif apierrors.IsAlreadyExists(err) {\n\t\t// If we're racing to init and someone else already created it, re-fetch\n\t\treturn coreClient.ServiceAccounts(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\t}\n\treturn sa, err\n}","line":{"from":159,"to":183}} {"id":100016997,"name":"newSimpleCache","signature":"func newSimpleCache(clock clock.Clock) cache","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/cache/cache_simple.go","code":"func newSimpleCache(clock clock.Clock) cache {\n\treturn \u0026simpleCache{cache: utilcache.NewExpiringWithClock(clock)}\n}","line":{"from":30,"to":32}} {"id":100016998,"name":"get","signature":"func (c *simpleCache) get(key string) (*cacheRecord, bool)","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/cache/cache_simple.go","code":"func (c *simpleCache) get(key string) (*cacheRecord, bool) {\n\trecord, ok := c.cache.Get(key)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\tvalue, ok := record.(*cacheRecord)\n\treturn value, ok\n}","line":{"from":34,"to":41}} {"id":100016999,"name":"set","signature":"func (c *simpleCache) set(key string, value *cacheRecord, ttl time.Duration)","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/cache/cache_simple.go","code":"func (c *simpleCache) set(key string, value *cacheRecord, ttl time.Duration) {\n\tc.cache.Set(key, value, ttl)\n}","line":{"from":43,"to":45}} {"id":100017000,"name":"remove","signature":"func (c *simpleCache) remove(key string)","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/cache/cache_simple.go","code":"func (c *simpleCache) remove(key string) {\n\tc.cache.Delete(key)\n}","line":{"from":47,"to":49}} {"id":100017001,"name":"newStripedCache","signature":"func newStripedCache(stripeCount int, hash hashFunc, newCacheFunc newCacheFunc) cache","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/cache/cache_striped.go","code":"func newStripedCache(stripeCount int, hash hashFunc, newCacheFunc newCacheFunc) cache {\n\tcaches := []cache{}\n\tfor i := 0; i \u003c stripeCount; i++ {\n\t\tcaches = append(caches, newCacheFunc())\n\t}\n\treturn \u0026stripedCache{\n\t\tstripeCount: uint32(stripeCount),\n\t\thashFunc: hash,\n\t\tcaches: caches,\n\t}\n}","line":{"from":34,"to":44}} {"id":100017002,"name":"get","signature":"func (c *stripedCache) get(key string) (*cacheRecord, bool)","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/cache/cache_striped.go","code":"func (c *stripedCache) get(key string) (*cacheRecord, bool) {\n\treturn c.caches[c.hashFunc(key)%c.stripeCount].get(key)\n}","line":{"from":46,"to":48}} {"id":100017003,"name":"set","signature":"func (c *stripedCache) set(key string, value *cacheRecord, ttl time.Duration)","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/cache/cache_striped.go","code":"func (c *stripedCache) set(key string, value *cacheRecord, ttl time.Duration) {\n\tc.caches[c.hashFunc(key)%c.stripeCount].set(key, value, ttl)\n}","line":{"from":49,"to":51}} {"id":100017004,"name":"remove","signature":"func (c *stripedCache) remove(key string)","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/cache/cache_striped.go","code":"func (c *stripedCache) remove(key string) {\n\tc.caches[c.hashFunc(key)%c.stripeCount].remove(key)\n}","line":{"from":52,"to":54}} {"id":100017005,"name":"fnvHashFunc","signature":"func fnvHashFunc(key string) uint32","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/cache/cache_striped.go","code":"func fnvHashFunc(key string) uint32 {\n\tf := fnv.New32()\n\tf.Write([]byte(key))\n\treturn f.Sum32()\n}","line":{"from":56,"to":60}} {"id":100017006,"name":"New","signature":"func New(authenticator authenticator.Token, cacheErrs bool, successTTL, failureTTL time.Duration) authenticator.Token","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/cache/cached_token_authenticator.go","code":"// New returns a token authenticator that caches the results of the specified authenticator. A ttl of 0 bypasses the cache.\nfunc New(authenticator authenticator.Token, cacheErrs bool, successTTL, failureTTL time.Duration) authenticator.Token {\n\treturn newWithClock(authenticator, cacheErrs, successTTL, failureTTL, clock.RealClock{})\n}","line":{"from":96,"to":99}} {"id":100017007,"name":"newWithClock","signature":"func newWithClock(authenticator authenticator.Token, cacheErrs bool, successTTL, failureTTL time.Duration, clock clock.Clock) authenticator.Token","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/cache/cached_token_authenticator.go","code":"func newWithClock(authenticator authenticator.Token, cacheErrs bool, successTTL, failureTTL time.Duration, clock clock.Clock) authenticator.Token {\n\trandomCacheKey := make([]byte, 32)\n\tif _, err := rand.Read(randomCacheKey); err != nil {\n\t\tpanic(err) // rand should never fail\n\t}\n\n\treturn \u0026cachedTokenAuthenticator{\n\t\tauthenticator: authenticator,\n\t\tcacheErrs: cacheErrs,\n\t\tsuccessTTL: successTTL,\n\t\tfailureTTL: failureTTL,\n\t\t// Cache performance degrades noticeably when the number of\n\t\t// tokens in operation exceeds the size of the cache. It is\n\t\t// cheap to make the cache big in the second dimension below,\n\t\t// the memory is only consumed when that many tokens are being\n\t\t// used. Currently we advertise support 5k nodes and 10k\n\t\t// namespaces; a 32k entry cache is therefore a 2x safety\n\t\t// margin.\n\t\tcache: newStripedCache(32, fnvHashFunc, func() cache { return newSimpleCache(clock) }),\n\n\t\thashPool: \u0026sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn hmac.New(sha256.New, randomCacheKey)\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":101,"to":127}} {"id":100017008,"name":"AuthenticateToken","signature":"func (a *cachedTokenAuthenticator) AuthenticateToken(ctx context.Context, token string) (*authenticator.Response, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/cache/cached_token_authenticator.go","code":"// AuthenticateToken implements authenticator.Token\nfunc (a *cachedTokenAuthenticator) AuthenticateToken(ctx context.Context, token string) (*authenticator.Response, bool, error) {\n\trecord := a.doAuthenticateToken(ctx, token)\n\tif !record.ok || record.err != nil {\n\t\treturn nil, false, record.err\n\t}\n\tfor key, value := range record.annotations {\n\t\taudit.AddAuditAnnotation(ctx, key, value)\n\t}\n\tfor _, w := range record.warnings {\n\t\twarning.AddWarning(ctx, w.agent, w.text)\n\t}\n\treturn record.resp, true, nil\n}","line":{"from":129,"to":142}} {"id":100017009,"name":"doAuthenticateToken","signature":"func (a *cachedTokenAuthenticator) doAuthenticateToken(ctx context.Context, token string) *cacheRecord","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/cache/cached_token_authenticator.go","code":"func (a *cachedTokenAuthenticator) doAuthenticateToken(ctx context.Context, token string) *cacheRecord {\n\tdoneAuthenticating := stats.authenticating(ctx)\n\n\tauds, audsOk := authenticator.AudiencesFrom(ctx)\n\n\tkey := keyFunc(a.hashPool, auds, token)\n\tif record, ok := a.cache.get(key); ok {\n\t\t// Record cache hit\n\t\tdoneAuthenticating(true)\n\t\treturn record\n\t}\n\n\t// Record cache miss\n\tdoneBlocking := stats.blocking(ctx)\n\tdefer doneBlocking()\n\tdefer doneAuthenticating(false)\n\n\tc := a.group.DoChan(key, func() (val interface{}, _ error) {\n\t\t// always use one place to read and write the output of AuthenticateToken\n\t\trecord := \u0026cacheRecord{}\n\n\t\tdoneFetching := stats.fetching(ctx)\n\t\t// We're leaving the request handling stack so we need to handle crashes\n\t\t// ourselves. Log a stack trace and return a 500 if something panics.\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\t// make sure to always return a record\n\t\t\t\trecord.err = errAuthnCrash\n\t\t\t\tval = record\n\n\t\t\t\t// Same as stdlib http server code. Manually allocate stack\n\t\t\t\t// trace buffer size to prevent excessively large logs\n\t\t\t\tconst size = 64 \u003c\u003c 10\n\t\t\t\tbuf := make([]byte, size)\n\t\t\t\tbuf = buf[:runtime.Stack(buf, false)]\n\t\t\t\tklog.Errorf(\"%v\\n%s\", r, buf)\n\t\t\t}\n\t\t\tdoneFetching(record.err == nil)\n\t\t}()\n\n\t\t// Check again for a cached record. We may have raced with a fetch.\n\t\tif record, ok := a.cache.get(key); ok {\n\t\t\treturn record, nil\n\t\t}\n\n\t\t// Detach the context because the lookup may be shared by multiple callers,\n\t\t// however propagate the audience.\n\t\tctx, cancel := context.WithTimeout(context.Background(), sharedLookupTimeout)\n\t\tdefer cancel()\n\n\t\tif audsOk {\n\t\t\tctx = authenticator.WithAudiences(ctx, auds)\n\t\t}\n\t\trecorder := \u0026recorder{}\n\t\tctx = warning.WithWarningRecorder(ctx, recorder)\n\n\t\t// since this is shared work between multiple requests, we have no way of knowing if any\n\t\t// particular request supports audit annotations. thus we always attempt to record them.\n\t\tev := \u0026auditinternal.Event{Level: auditinternal.LevelMetadata}\n\t\tctx = audit.WithAuditContext(ctx)\n\t\tac := audit.AuditContextFrom(ctx)\n\t\tac.Event = ev\n\n\t\trecord.resp, record.ok, record.err = a.authenticator.AuthenticateToken(ctx, token)\n\t\trecord.annotations = ev.Annotations\n\t\trecord.warnings = recorder.extractWarnings()\n\n\t\tif !a.cacheErrs \u0026\u0026 record.err != nil {\n\t\t\treturn record, nil\n\t\t}\n\n\t\tswitch {\n\t\tcase record.ok \u0026\u0026 a.successTTL \u003e 0:\n\t\t\ta.cache.set(key, record, a.successTTL)\n\t\tcase !record.ok \u0026\u0026 a.failureTTL \u003e 0:\n\t\t\ta.cache.set(key, record, a.failureTTL)\n\t\t}\n\n\t\treturn record, nil\n\t})\n\n\tselect {\n\tcase result := \u003c-c:\n\t\t// we always set Val and never set Err\n\t\treturn result.Val.(*cacheRecord)\n\tcase \u003c-ctx.Done():\n\t\t// fake a record on context cancel\n\t\treturn \u0026cacheRecord{err: ctx.Err()}\n\t}\n}","line":{"from":144,"to":233}} {"id":100017010,"name":"keyFunc","signature":"func keyFunc(hashPool *sync.Pool, auds []string, token string) string","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/cache/cached_token_authenticator.go","code":"// keyFunc generates a string key by hashing the inputs.\n// This lowers the memory requirement of the cache and keeps tokens out of memory.\nfunc keyFunc(hashPool *sync.Pool, auds []string, token string) string {\n\th := hashPool.Get().(hash.Hash)\n\n\th.Reset()\n\n\t// try to force stack allocation\n\tvar a [4]byte\n\tb := a[:]\n\n\twriteLengthPrefixedString(h, b, token)\n\t// encode the length of audiences to avoid ambiguities\n\twriteLength(h, b, len(auds))\n\tfor _, aud := range auds {\n\t\twriteLengthPrefixedString(h, b, aud)\n\t}\n\n\tkey := toString(h.Sum(nil)) // skip base64 encoding to save an allocation\n\n\thashPool.Put(h)\n\n\treturn key\n}","line":{"from":235,"to":258}} {"id":100017011,"name":"writeLengthPrefixedString","signature":"func writeLengthPrefixedString(w io.Writer, b []byte, s string)","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/cache/cached_token_authenticator.go","code":"// writeLengthPrefixedString writes s with a length prefix to prevent ambiguities, i.e. \"xy\" + \"z\" == \"x\" + \"yz\"\n// the length of b is assumed to be 4 (b is mutated by this function to store the length of s)\nfunc writeLengthPrefixedString(w io.Writer, b []byte, s string) {\n\twriteLength(w, b, len(s))\n\tif _, err := w.Write(toBytes(s)); err != nil {\n\t\tpanic(err) // Write() on hash never fails\n\t}\n}","line":{"from":260,"to":267}} {"id":100017012,"name":"writeLength","signature":"func writeLength(w io.Writer, b []byte, length int)","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/cache/cached_token_authenticator.go","code":"// writeLength encodes length into b and then writes it via the given writer\n// the length of b is assumed to be 4\nfunc writeLength(w io.Writer, b []byte, length int) {\n\tbinary.BigEndian.PutUint32(b, uint32(length))\n\tif _, err := w.Write(b); err != nil {\n\t\tpanic(err) // Write() on hash never fails\n\t}\n}","line":{"from":269,"to":276}} {"id":100017013,"name":"toBytes","signature":"func toBytes(s string) []byte","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/cache/cached_token_authenticator.go","code":"// toBytes performs unholy acts to avoid allocations\nfunc toBytes(s string) []byte {\n\t// unsafe.StringData is unspecified for the empty string, so we provide a strict interpretation\n\tif len(s) == 0 {\n\t\treturn nil\n\t}\n\t// Copied from go 1.20.1 os.File.WriteString\n\t// https://github.com/golang/go/blob/202a1a57064127c3f19d96df57b9f9586145e21c/src/os/file.go#L246\n\treturn unsafe.Slice(unsafe.StringData(s), len(s))\n}","line":{"from":278,"to":287}} {"id":100017014,"name":"toString","signature":"func toString(b []byte) string","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/cache/cached_token_authenticator.go","code":"// toString performs unholy acts to avoid allocations\nfunc toString(b []byte) string {\n\t// unsafe.SliceData relies on cap whereas we want to rely on len\n\tif len(b) == 0 {\n\t\treturn \"\"\n\t}\n\t// Copied from go 1.20.1 strings.Builder.String\n\t// https://github.com/golang/go/blob/202a1a57064127c3f19d96df57b9f9586145e21c/src/strings/builder.go#L48\n\treturn unsafe.String(unsafe.SliceData(b), len(b))\n}","line":{"from":289,"to":298}} {"id":100017015,"name":"AddWarning","signature":"func (r *recorder) AddWarning(agent, text string)","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/cache/cached_token_authenticator.go","code":"// AddWarning adds a warning to recorder.\nfunc (r *recorder) AddWarning(agent, text string) {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\tr.warnings = append(r.warnings, \u0026cacheWarning{agent: agent, text: text})\n}","line":{"from":306,"to":311}} {"id":100017016,"name":"extractWarnings","signature":"func (r *recorder) extractWarnings() []*cacheWarning","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/cache/cached_token_authenticator.go","code":"func (r *recorder) extractWarnings() []*cacheWarning {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\twarnings := r.warnings\n\tr.warnings = nil\n\treturn warnings\n}","line":{"from":313,"to":319}} {"id":100017017,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/cache/stats.go","code":"func init() {\n\tlegacyregistry.MustRegister(\n\t\trequestLatency,\n\t\trequestCount,\n\t\tfetchCount,\n\t\tactiveFetchCount,\n\t)\n}","line":{"from":66,"to":73}} {"id":100017018,"name":"authenticating","signature":"func (statsCollector) authenticating(ctx context.Context) func(hit bool)","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/cache/stats.go","code":"func (statsCollector) authenticating(ctx context.Context) func(hit bool) {\n\tstart := time.Now()\n\treturn func(hit bool) {\n\t\tvar tag string\n\t\tif hit {\n\t\t\ttag = hitTag\n\t\t} else {\n\t\t\ttag = missTag\n\t\t}\n\n\t\tlatency := time.Since(start)\n\n\t\trequestCount.WithContext(ctx).WithLabelValues(tag).Inc()\n\t\trequestLatency.WithContext(ctx).WithLabelValues(tag).Observe(float64(latency.Milliseconds()) / 1000)\n\t}\n}","line":{"from":90,"to":105}} {"id":100017019,"name":"blocking","signature":"func (statsCollector) blocking(ctx context.Context) func()","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/cache/stats.go","code":"func (statsCollector) blocking(ctx context.Context) func() {\n\tactiveFetchCount.WithContext(ctx).WithLabelValues(fetchBlockedTag).Inc()\n\treturn activeFetchCount.WithContext(ctx).WithLabelValues(fetchBlockedTag).Dec\n}","line":{"from":107,"to":110}} {"id":100017020,"name":"fetching","signature":"func (statsCollector) fetching(ctx context.Context) func(ok bool)","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/cache/stats.go","code":"func (statsCollector) fetching(ctx context.Context) func(ok bool) {\n\tactiveFetchCount.WithContext(ctx).WithLabelValues(fetchInFlightTag).Inc()\n\treturn func(ok bool) {\n\t\tvar tag string\n\t\tif ok {\n\t\t\ttag = fetchOkTag\n\t\t} else {\n\t\t\ttag = fetchFailedTag\n\t\t}\n\n\t\tfetchCount.WithContext(ctx).WithLabelValues(tag).Inc()\n\n\t\tactiveFetchCount.WithContext(ctx).WithLabelValues(fetchInFlightTag).Dec()\n\t}\n}","line":{"from":112,"to":126}} {"id":100017021,"name":"New","signature":"func New(tokens map[string]*user.DefaultInfo) *TokenAuthenticator","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/tokenfile/tokenfile.go","code":"// New returns a TokenAuthenticator for a single token\nfunc New(tokens map[string]*user.DefaultInfo) *TokenAuthenticator {\n\treturn \u0026TokenAuthenticator{\n\t\ttokens: tokens,\n\t}\n}","line":{"from":36,"to":41}} {"id":100017022,"name":"NewCSV","signature":"func NewCSV(path string) (*TokenAuthenticator, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/tokenfile/tokenfile.go","code":"// NewCSV returns a TokenAuthenticator, populated from a CSV file.\n// The CSV file must contain records in the format \"token,username,useruid\"\nfunc NewCSV(path string) (*TokenAuthenticator, error) {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\n\trecordNum := 0\n\ttokens := make(map[string]*user.DefaultInfo)\n\treader := csv.NewReader(file)\n\treader.FieldsPerRecord = -1\n\tfor {\n\t\trecord, err := reader.Read()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(record) \u003c 3 {\n\t\t\treturn nil, fmt.Errorf(\"token file '%s' must have at least 3 columns (token, user name, user uid), found %d\", path, len(record))\n\t\t}\n\n\t\trecordNum++\n\t\tif record[0] == \"\" {\n\t\t\tklog.Warningf(\"empty token has been found in token file '%s', record number '%d'\", path, recordNum)\n\t\t\tcontinue\n\t\t}\n\n\t\tobj := \u0026user.DefaultInfo{\n\t\t\tName: record[1],\n\t\t\tUID: record[2],\n\t\t}\n\t\tif _, exist := tokens[record[0]]; exist {\n\t\t\tklog.Warningf(\"duplicate token has been found in token file '%s', record number '%d'\", path, recordNum)\n\t\t}\n\t\ttokens[record[0]] = obj\n\n\t\tif len(record) \u003e= 4 {\n\t\t\tobj.Groups = strings.Split(record[3], \",\")\n\t\t}\n\t}\n\n\treturn \u0026TokenAuthenticator{\n\t\ttokens: tokens,\n\t}, nil\n}","line":{"from":43,"to":91}} {"id":100017023,"name":"AuthenticateToken","signature":"func (a *TokenAuthenticator) AuthenticateToken(ctx context.Context, value string) (*authenticator.Response, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/tokenfile/tokenfile.go","code":"func (a *TokenAuthenticator) AuthenticateToken(ctx context.Context, value string) (*authenticator.Response, bool, error) {\n\tuser, ok := a.tokens[value]\n\tif !ok {\n\t\treturn nil, false, nil\n\t}\n\treturn \u0026authenticator.Response{User: user}, true, nil\n}","line":{"from":93,"to":99}} {"id":100017024,"name":"New","signature":"func New(authTokenHandlers ...authenticator.Token) authenticator.Token","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/union/union.go","code":"// New returns a token authenticator that validates credentials using a chain of authenticator.Token objects.\n// The entire chain is tried until one succeeds. If all fail, an aggregate error is returned.\nfunc New(authTokenHandlers ...authenticator.Token) authenticator.Token {\n\tif len(authTokenHandlers) == 1 {\n\t\treturn authTokenHandlers[0]\n\t}\n\treturn \u0026unionAuthTokenHandler{Handlers: authTokenHandlers, FailOnError: false}\n}","line":{"from":34,"to":41}} {"id":100017025,"name":"NewFailOnError","signature":"func NewFailOnError(authTokenHandlers ...authenticator.Token) authenticator.Token","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/union/union.go","code":"// NewFailOnError returns a token authenticator that validates credentials using a chain of authenticator.Token objects.\n// The first error short-circuits the chain.\nfunc NewFailOnError(authTokenHandlers ...authenticator.Token) authenticator.Token {\n\tif len(authTokenHandlers) == 1 {\n\t\treturn authTokenHandlers[0]\n\t}\n\treturn \u0026unionAuthTokenHandler{Handlers: authTokenHandlers, FailOnError: true}\n}","line":{"from":43,"to":50}} {"id":100017026,"name":"AuthenticateToken","signature":"func (authHandler *unionAuthTokenHandler) AuthenticateToken(ctx context.Context, token string) (*authenticator.Response, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/authentication/token/union/union.go","code":"// AuthenticateToken authenticates the token using a chain of authenticator.Token objects.\nfunc (authHandler *unionAuthTokenHandler) AuthenticateToken(ctx context.Context, token string) (*authenticator.Response, bool, error) {\n\tvar errlist []error\n\tfor _, currAuthRequestHandler := range authHandler.Handlers {\n\t\tinfo, ok, err := currAuthRequestHandler.AuthenticateToken(ctx, token)\n\t\tif err != nil {\n\t\t\tif authHandler.FailOnError {\n\t\t\t\treturn info, ok, err\n\t\t\t}\n\t\t\terrlist = append(errlist, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif ok {\n\t\t\treturn info, ok, err\n\t\t}\n\t}\n\n\treturn nil, false, utilerrors.NewAggregate(errlist)\n}","line":{"from":52,"to":71}} {"id":100017027,"name":"GetName","signature":"func (i *DefaultInfo) GetName() string","file":"staging/src/k8s.io/apiserver/pkg/authentication/user/user.go","code":"func (i *DefaultInfo) GetName() string {\n\treturn i.Name\n}","line":{"from":53,"to":55}} {"id":100017028,"name":"GetUID","signature":"func (i *DefaultInfo) GetUID() string","file":"staging/src/k8s.io/apiserver/pkg/authentication/user/user.go","code":"func (i *DefaultInfo) GetUID() string {\n\treturn i.UID\n}","line":{"from":57,"to":59}} {"id":100017029,"name":"GetGroups","signature":"func (i *DefaultInfo) GetGroups() []string","file":"staging/src/k8s.io/apiserver/pkg/authentication/user/user.go","code":"func (i *DefaultInfo) GetGroups() []string {\n\treturn i.Groups\n}","line":{"from":61,"to":63}} {"id":100017030,"name":"GetExtra","signature":"func (i *DefaultInfo) GetExtra() map[string][]string","file":"staging/src/k8s.io/apiserver/pkg/authentication/user/user.go","code":"func (i *DefaultInfo) GetExtra() map[string][]string {\n\treturn i.Extra\n}","line":{"from":65,"to":67}} {"id":100017031,"name":"Authorize","signature":"func (f AuthorizerFunc) Authorize(ctx context.Context, a Attributes) (Decision, string, error)","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizer/interfaces.go","code":"func (f AuthorizerFunc) Authorize(ctx context.Context, a Attributes) (Decision, string, error) {\n\treturn f(ctx, a)\n}","line":{"from":76,"to":78}} {"id":100017032,"name":"GetUser","signature":"func (a AttributesRecord) GetUser() user.Info","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizer/interfaces.go","code":"func (a AttributesRecord) GetUser() user.Info {\n\treturn a.User\n}","line":{"from":105,"to":107}} {"id":100017033,"name":"GetVerb","signature":"func (a AttributesRecord) GetVerb() string","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizer/interfaces.go","code":"func (a AttributesRecord) GetVerb() string {\n\treturn a.Verb\n}","line":{"from":109,"to":111}} {"id":100017034,"name":"IsReadOnly","signature":"func (a AttributesRecord) IsReadOnly() bool","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizer/interfaces.go","code":"func (a AttributesRecord) IsReadOnly() bool {\n\treturn a.Verb == \"get\" || a.Verb == \"list\" || a.Verb == \"watch\"\n}","line":{"from":113,"to":115}} {"id":100017035,"name":"GetNamespace","signature":"func (a AttributesRecord) GetNamespace() string","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizer/interfaces.go","code":"func (a AttributesRecord) GetNamespace() string {\n\treturn a.Namespace\n}","line":{"from":117,"to":119}} {"id":100017036,"name":"GetResource","signature":"func (a AttributesRecord) GetResource() string","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizer/interfaces.go","code":"func (a AttributesRecord) GetResource() string {\n\treturn a.Resource\n}","line":{"from":121,"to":123}} {"id":100017037,"name":"GetSubresource","signature":"func (a AttributesRecord) GetSubresource() string","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizer/interfaces.go","code":"func (a AttributesRecord) GetSubresource() string {\n\treturn a.Subresource\n}","line":{"from":125,"to":127}} {"id":100017038,"name":"GetName","signature":"func (a AttributesRecord) GetName() string","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizer/interfaces.go","code":"func (a AttributesRecord) GetName() string {\n\treturn a.Name\n}","line":{"from":129,"to":131}} {"id":100017039,"name":"GetAPIGroup","signature":"func (a AttributesRecord) GetAPIGroup() string","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizer/interfaces.go","code":"func (a AttributesRecord) GetAPIGroup() string {\n\treturn a.APIGroup\n}","line":{"from":133,"to":135}} {"id":100017040,"name":"GetAPIVersion","signature":"func (a AttributesRecord) GetAPIVersion() string","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizer/interfaces.go","code":"func (a AttributesRecord) GetAPIVersion() string {\n\treturn a.APIVersion\n}","line":{"from":137,"to":139}} {"id":100017041,"name":"IsResourceRequest","signature":"func (a AttributesRecord) IsResourceRequest() bool","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizer/interfaces.go","code":"func (a AttributesRecord) IsResourceRequest() bool {\n\treturn a.ResourceRequest\n}","line":{"from":141,"to":143}} {"id":100017042,"name":"GetPath","signature":"func (a AttributesRecord) GetPath() string","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizer/interfaces.go","code":"func (a AttributesRecord) GetPath() string {\n\treturn a.Path\n}","line":{"from":145,"to":147}} {"id":100017043,"name":"GetVerbs","signature":"func (i *DefaultResourceRuleInfo) GetVerbs() []string","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizer/rule.go","code":"func (i *DefaultResourceRuleInfo) GetVerbs() []string {\n\treturn i.Verbs\n}","line":{"from":38,"to":40}} {"id":100017044,"name":"GetAPIGroups","signature":"func (i *DefaultResourceRuleInfo) GetAPIGroups() []string","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizer/rule.go","code":"func (i *DefaultResourceRuleInfo) GetAPIGroups() []string {\n\treturn i.APIGroups\n}","line":{"from":42,"to":44}} {"id":100017045,"name":"GetResources","signature":"func (i *DefaultResourceRuleInfo) GetResources() []string","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizer/rule.go","code":"func (i *DefaultResourceRuleInfo) GetResources() []string {\n\treturn i.Resources\n}","line":{"from":46,"to":48}} {"id":100017046,"name":"GetResourceNames","signature":"func (i *DefaultResourceRuleInfo) GetResourceNames() []string","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizer/rule.go","code":"func (i *DefaultResourceRuleInfo) GetResourceNames() []string {\n\treturn i.ResourceNames\n}","line":{"from":50,"to":52}} {"id":100017047,"name":"GetVerbs","signature":"func (i *DefaultNonResourceRuleInfo) GetVerbs() []string","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizer/rule.go","code":"func (i *DefaultNonResourceRuleInfo) GetVerbs() []string {\n\treturn i.Verbs\n}","line":{"from":67,"to":69}} {"id":100017048,"name":"GetNonResourceURLs","signature":"func (i *DefaultNonResourceRuleInfo) GetNonResourceURLs() []string","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizer/rule.go","code":"func (i *DefaultNonResourceRuleInfo) GetNonResourceURLs() []string {\n\treturn i.NonResourceURLs\n}","line":{"from":71,"to":73}} {"id":100017049,"name":"Authorize","signature":"func (alwaysAllowAuthorizer) Authorize(ctx context.Context, a authorizer.Attributes) (authorized authorizer.Decision, reason string, err error)","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizerfactory/builtin.go","code":"func (alwaysAllowAuthorizer) Authorize(ctx context.Context, a authorizer.Attributes) (authorized authorizer.Decision, reason string, err error) {\n\treturn authorizer.DecisionAllow, \"\", nil\n}","line":{"from":32,"to":34}} {"id":100017050,"name":"RulesFor","signature":"func (alwaysAllowAuthorizer) RulesFor(user user.Info, namespace string) ([]authorizer.ResourceRuleInfo, []authorizer.NonResourceRuleInfo, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizerfactory/builtin.go","code":"func (alwaysAllowAuthorizer) RulesFor(user user.Info, namespace string) ([]authorizer.ResourceRuleInfo, []authorizer.NonResourceRuleInfo, bool, error) {\n\treturn []authorizer.ResourceRuleInfo{\n\t\t\t\u0026authorizer.DefaultResourceRuleInfo{\n\t\t\t\tVerbs: []string{\"*\"},\n\t\t\t\tAPIGroups: []string{\"*\"},\n\t\t\t\tResources: []string{\"*\"},\n\t\t\t},\n\t\t}, []authorizer.NonResourceRuleInfo{\n\t\t\t\u0026authorizer.DefaultNonResourceRuleInfo{\n\t\t\t\tVerbs: []string{\"*\"},\n\t\t\t\tNonResourceURLs: []string{\"*\"},\n\t\t\t},\n\t\t}, false, nil\n}","line":{"from":36,"to":49}} {"id":100017051,"name":"NewAlwaysAllowAuthorizer","signature":"func NewAlwaysAllowAuthorizer() *alwaysAllowAuthorizer","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizerfactory/builtin.go","code":"func NewAlwaysAllowAuthorizer() *alwaysAllowAuthorizer {\n\treturn new(alwaysAllowAuthorizer)\n}","line":{"from":51,"to":53}} {"id":100017052,"name":"Authorize","signature":"func (alwaysDenyAuthorizer) Authorize(ctx context.Context, a authorizer.Attributes) (decision authorizer.Decision, reason string, err error)","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizerfactory/builtin.go","code":"func (alwaysDenyAuthorizer) Authorize(ctx context.Context, a authorizer.Attributes) (decision authorizer.Decision, reason string, err error) {\n\treturn authorizer.DecisionNoOpinion, \"Everything is forbidden.\", nil\n}","line":{"from":60,"to":62}} {"id":100017053,"name":"RulesFor","signature":"func (alwaysDenyAuthorizer) RulesFor(user user.Info, namespace string) ([]authorizer.ResourceRuleInfo, []authorizer.NonResourceRuleInfo, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizerfactory/builtin.go","code":"func (alwaysDenyAuthorizer) RulesFor(user user.Info, namespace string) ([]authorizer.ResourceRuleInfo, []authorizer.NonResourceRuleInfo, bool, error) {\n\treturn []authorizer.ResourceRuleInfo{}, []authorizer.NonResourceRuleInfo{}, false, nil\n}","line":{"from":64,"to":66}} {"id":100017054,"name":"NewAlwaysDenyAuthorizer","signature":"func NewAlwaysDenyAuthorizer() *alwaysDenyAuthorizer","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizerfactory/builtin.go","code":"func NewAlwaysDenyAuthorizer() *alwaysDenyAuthorizer {\n\treturn new(alwaysDenyAuthorizer)\n}","line":{"from":68,"to":70}} {"id":100017055,"name":"Authorize","signature":"func (r *privilegedGroupAuthorizer) Authorize(ctx context.Context, attr authorizer.Attributes) (authorizer.Decision, string, error)","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizerfactory/builtin.go","code":"func (r *privilegedGroupAuthorizer) Authorize(ctx context.Context, attr authorizer.Attributes) (authorizer.Decision, string, error) {\n\tif attr.GetUser() == nil {\n\t\treturn authorizer.DecisionNoOpinion, \"Error\", errors.New(\"no user on request.\")\n\t}\n\tfor _, attr_group := range attr.GetUser().GetGroups() {\n\t\tfor _, priv_group := range r.groups {\n\t\t\tif priv_group == attr_group {\n\t\t\t\treturn authorizer.DecisionAllow, \"\", nil\n\t\t\t}\n\t\t}\n\t}\n\treturn authorizer.DecisionNoOpinion, \"\", nil\n}","line":{"from":76,"to":88}} {"id":100017056,"name":"NewPrivilegedGroups","signature":"func NewPrivilegedGroups(groups ...string) *privilegedGroupAuthorizer","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizerfactory/builtin.go","code":"// NewPrivilegedGroups is for use in loopback scenarios\nfunc NewPrivilegedGroups(groups ...string) *privilegedGroupAuthorizer {\n\treturn \u0026privilegedGroupAuthorizer{\n\t\tgroups: groups,\n\t}\n}","line":{"from":90,"to":95}} {"id":100017057,"name":"New","signature":"func (c DelegatingAuthorizerConfig) New() (authorizer.Authorizer, error)","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizerfactory/delegating.go","code":"func (c DelegatingAuthorizerConfig) New() (authorizer.Authorizer, error) {\n\tif c.WebhookRetryBackoff == nil {\n\t\treturn nil, errors.New(\"retry backoff parameters for delegating authorization webhook has not been specified\")\n\t}\n\n\treturn webhook.NewFromInterface(\n\t\tc.SubjectAccessReviewClient,\n\t\tc.AllowCacheTTL,\n\t\tc.DenyCacheTTL,\n\t\t*c.WebhookRetryBackoff,\n\t\twebhook.AuthorizerMetrics{\n\t\t\tRecordRequestTotal: RecordRequestTotal,\n\t\t\tRecordRequestLatency: RecordRequestLatency,\n\t\t},\n\t)\n}","line":{"from":47,"to":62}} {"id":100017058,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizerfactory/metrics.go","code":"// init registers all metrics\nfunc init() {\n\tfor _, metric := range metrics {\n\t\tlegacyregistry.MustRegister(metric)\n\t}\n}","line":{"from":28,"to":33}} {"id":100017059,"name":"RecordRequestTotal","signature":"func RecordRequestTotal(ctx context.Context, code string)","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizerfactory/metrics.go","code":"// RecordRequestTotal increments the total number of requests for the delegated authorization.\nfunc RecordRequestTotal(ctx context.Context, code string) {\n\trequestTotal.WithContext(ctx).WithLabelValues(code).Add(1)\n}","line":{"from":61,"to":64}} {"id":100017060,"name":"RecordRequestLatency","signature":"func RecordRequestLatency(ctx context.Context, code string, latency float64)","file":"staging/src/k8s.io/apiserver/pkg/authorization/authorizerfactory/metrics.go","code":"// RecordRequestLatency measures request latency in seconds for the delegated authorization. Broken down by status code.\nfunc RecordRequestLatency(ctx context.Context, code string, latency float64) {\n\trequestLatency.WithContext(ctx).WithLabelValues(code).Observe(latency)\n}","line":{"from":66,"to":69}} {"id":100017061,"name":"NewAuthorizer","signature":"func NewAuthorizer(alwaysAllowPaths []string) (authorizer.Authorizer, error)","file":"staging/src/k8s.io/apiserver/pkg/authorization/path/path.go","code":"// NewAuthorizer returns an authorizer which accepts a given set of paths.\n// Each path is either a fully matching path or it ends in * in case a prefix match is done. A leading / is optional.\nfunc NewAuthorizer(alwaysAllowPaths []string) (authorizer.Authorizer, error) {\n\tvar prefixes []string\n\tpaths := sets.NewString()\n\tfor _, p := range alwaysAllowPaths {\n\t\tp = strings.TrimPrefix(p, \"/\")\n\t\tif len(p) == 0 {\n\t\t\t// matches \"/\"\n\t\t\tpaths.Insert(p)\n\t\t\tcontinue\n\t\t}\n\t\tif strings.ContainsRune(p[:len(p)-1], '*') {\n\t\t\treturn nil, fmt.Errorf(\"only trailing * allowed in %q\", p)\n\t\t}\n\t\tif strings.HasSuffix(p, \"*\") {\n\t\t\tprefixes = append(prefixes, p[:len(p)-1])\n\t\t} else {\n\t\t\tpaths.Insert(p)\n\t\t}\n\t}\n\n\treturn authorizer.AuthorizerFunc(func(ctx context.Context, a authorizer.Attributes) (authorizer.Decision, string, error) {\n\t\tif a.IsResourceRequest() {\n\t\t\treturn authorizer.DecisionNoOpinion, \"\", nil\n\t\t}\n\n\t\tpth := strings.TrimPrefix(a.GetPath(), \"/\")\n\t\tif paths.Has(pth) {\n\t\t\treturn authorizer.DecisionAllow, \"\", nil\n\t\t}\n\n\t\tfor _, prefix := range prefixes {\n\t\t\tif strings.HasPrefix(pth, prefix) {\n\t\t\t\treturn authorizer.DecisionAllow, \"\", nil\n\t\t\t}\n\t\t}\n\n\t\treturn authorizer.DecisionNoOpinion, \"\", nil\n\t}), nil\n}","line":{"from":28,"to":68}} {"id":100017062,"name":"New","signature":"func New(authorizationHandlers ...authorizer.Authorizer) authorizer.Authorizer","file":"staging/src/k8s.io/apiserver/pkg/authorization/union/union.go","code":"// New returns an authorizer that authorizes against a chain of authorizer.Authorizer objects\nfunc New(authorizationHandlers ...authorizer.Authorizer) authorizer.Authorizer {\n\treturn unionAuthzHandler(authorizationHandlers)\n}","line":{"from":39,"to":42}} {"id":100017063,"name":"Authorize","signature":"func (authzHandler unionAuthzHandler) Authorize(ctx context.Context, a authorizer.Attributes) (authorizer.Decision, string, error)","file":"staging/src/k8s.io/apiserver/pkg/authorization/union/union.go","code":"// Authorizes against a chain of authorizer.Authorizer objects and returns nil if successful and returns error if unsuccessful\nfunc (authzHandler unionAuthzHandler) Authorize(ctx context.Context, a authorizer.Attributes) (authorizer.Decision, string, error) {\n\tvar (\n\t\terrlist []error\n\t\treasonlist []string\n\t)\n\n\tfor _, currAuthzHandler := range authzHandler {\n\t\tdecision, reason, err := currAuthzHandler.Authorize(ctx, a)\n\n\t\tif err != nil {\n\t\t\terrlist = append(errlist, err)\n\t\t}\n\t\tif len(reason) != 0 {\n\t\t\treasonlist = append(reasonlist, reason)\n\t\t}\n\t\tswitch decision {\n\t\tcase authorizer.DecisionAllow, authorizer.DecisionDeny:\n\t\t\treturn decision, reason, err\n\t\tcase authorizer.DecisionNoOpinion:\n\t\t\t// continue to the next authorizer\n\t\t}\n\t}\n\n\treturn authorizer.DecisionNoOpinion, strings.Join(reasonlist, \"\\n\"), utilerrors.NewAggregate(errlist)\n}","line":{"from":44,"to":69}} {"id":100017064,"name":"NewRuleResolvers","signature":"func NewRuleResolvers(authorizationHandlers ...authorizer.RuleResolver) authorizer.RuleResolver","file":"staging/src/k8s.io/apiserver/pkg/authorization/union/union.go","code":"// NewRuleResolvers returns an authorizer that authorizes against a chain of authorizer.Authorizer objects\nfunc NewRuleResolvers(authorizationHandlers ...authorizer.RuleResolver) authorizer.RuleResolver {\n\treturn unionAuthzRulesHandler(authorizationHandlers)\n}","line":{"from":74,"to":77}} {"id":100017065,"name":"RulesFor","signature":"func (authzHandler unionAuthzRulesHandler) RulesFor(user user.Info, namespace string) ([]authorizer.ResourceRuleInfo, []authorizer.NonResourceRuleInfo, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/authorization/union/union.go","code":"// RulesFor against a chain of authorizer.RuleResolver objects and returns nil if successful and returns error if unsuccessful\nfunc (authzHandler unionAuthzRulesHandler) RulesFor(user user.Info, namespace string) ([]authorizer.ResourceRuleInfo, []authorizer.NonResourceRuleInfo, bool, error) {\n\tvar (\n\t\terrList []error\n\t\tresourceRulesList []authorizer.ResourceRuleInfo\n\t\tnonResourceRulesList []authorizer.NonResourceRuleInfo\n\t)\n\tincompleteStatus := false\n\n\tfor _, currAuthzHandler := range authzHandler {\n\t\tresourceRules, nonResourceRules, incomplete, err := currAuthzHandler.RulesFor(user, namespace)\n\n\t\tif incomplete {\n\t\t\tincompleteStatus = true\n\t\t}\n\t\tif err != nil {\n\t\t\terrList = append(errList, err)\n\t\t}\n\t\tif len(resourceRules) \u003e 0 {\n\t\t\tresourceRulesList = append(resourceRulesList, resourceRules...)\n\t\t}\n\t\tif len(nonResourceRules) \u003e 0 {\n\t\t\tnonResourceRulesList = append(nonResourceRulesList, nonResourceRules...)\n\t\t}\n\t}\n\n\treturn resourceRulesList, nonResourceRulesList, incompleteStatus, utilerrors.NewAggregate(errList)\n}","line":{"from":79,"to":106}} {"id":100017066,"name":"CompositeKeyFor","signature":"func (ks *singleKeyStrategy) CompositeKeyFor(obj map[string]interface{}) (interface{}, bool)","file":"staging/src/k8s.io/apiserver/pkg/cel/common/maplist.go","code":"// CompositeKeyFor directly returns the value of the single key to\n// use as a composite key.\nfunc (ks *singleKeyStrategy) CompositeKeyFor(obj map[string]interface{}) (interface{}, bool) {\n\tv, ok := obj[ks.key]\n\tif !ok {\n\t\treturn nil, false\n\t}\n\n\tswitch v.(type) {\n\tcase bool, float64, int64, string:\n\t\treturn v, true\n\tdefault:\n\t\treturn nil, false // non-scalar\n\t}\n}","line":{"from":43,"to":57}} {"id":100017067,"name":"CompositeKeyFor","signature":"func (ks *multiKeyStrategy) CompositeKeyFor(obj map[string]interface{}) (interface{}, bool)","file":"staging/src/k8s.io/apiserver/pkg/cel/common/maplist.go","code":"// CompositeKeyFor returns a composite key computed from the values of all\n// keys.\nfunc (ks *multiKeyStrategy) CompositeKeyFor(obj map[string]interface{}) (interface{}, bool) {\n\tconst keyDelimiter = \"\\x00\" // 0 byte should never appear in the composite key except as delimiter\n\n\tvar delimited strings.Builder\n\tfor _, key := range ks.sts.XListMapKeys() {\n\t\tv, ok := obj[key]\n\t\tif !ok {\n\t\t\treturn nil, false\n\t\t}\n\n\t\tswitch v.(type) {\n\t\tcase bool:\n\t\t\tfmt.Fprintf(\u0026delimited, keyDelimiter+\"%t\", v)\n\t\tcase float64:\n\t\t\tfmt.Fprintf(\u0026delimited, keyDelimiter+\"%f\", v)\n\t\tcase int64:\n\t\t\tfmt.Fprintf(\u0026delimited, keyDelimiter+\"%d\", v)\n\t\tcase string:\n\t\t\tfmt.Fprintf(\u0026delimited, keyDelimiter+\"%q\", v)\n\t\tdefault:\n\t\t\treturn nil, false // values must be scalars\n\t\t}\n\t}\n\treturn delimited.String(), true\n}","line":{"from":64,"to":90}} {"id":100017068,"name":"Get","signature":"func (emptyMapList) Get(interface{}) interface{}","file":"staging/src/k8s.io/apiserver/pkg/cel/common/maplist.go","code":"func (emptyMapList) Get(interface{}) interface{} {\n\treturn nil\n}","line":{"from":95,"to":97}} {"id":100017069,"name":"Get","signature":"func (a *mapListImpl) Get(obj interface{}) interface{}","file":"staging/src/k8s.io/apiserver/pkg/cel/common/maplist.go","code":"func (a *mapListImpl) Get(obj interface{}) interface{} {\n\tmobj, ok := obj.(map[string]interface{})\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tkey, ok := a.ks.CompositeKeyFor(mobj)\n\tif !ok {\n\t\treturn nil\n\t}\n\tif match, ok := a.keyedItems[key]; ok {\n\t\treturn match\n\t}\n\t// keep keying items until we either find a match or run out of unkeyed items\n\tfor len(a.unkeyedItems) \u003e 0 {\n\t\t// dequeue an unkeyed item\n\t\titem := a.unkeyedItems[0]\n\t\ta.unkeyedItems = a.unkeyedItems[1:]\n\n\t\t// key the item\n\t\tmitem, ok := item.(map[string]interface{})\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\titemKey, ok := a.ks.CompositeKeyFor(mitem)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tif _, exists := a.keyedItems[itemKey]; !exists {\n\t\t\ta.keyedItems[itemKey] = mitem\n\t\t}\n\n\t\t// if it matches, short-circuit\n\t\tif itemKey == key {\n\t\t\treturn mitem\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":108,"to":147}} {"id":100017070,"name":"makeKeyStrategy","signature":"func makeKeyStrategy(sts Schema) keyStrategy","file":"staging/src/k8s.io/apiserver/pkg/cel/common/maplist.go","code":"func makeKeyStrategy(sts Schema) keyStrategy {\n\tlistMapKeys := sts.XListMapKeys()\n\tif len(listMapKeys) == 1 {\n\t\tkey := listMapKeys[0]\n\t\treturn \u0026singleKeyStrategy{\n\t\t\tkey: key,\n\t\t}\n\t}\n\n\treturn \u0026multiKeyStrategy{\n\t\tsts: sts,\n\t}\n}","line":{"from":149,"to":161}} {"id":100017071,"name":"MakeMapList","signature":"func MakeMapList(sts Schema, items []interface{}) (rv MapList)","file":"staging/src/k8s.io/apiserver/pkg/cel/common/maplist.go","code":"// MakeMapList returns a queryable interface over the provided x-kubernetes-list-type=map\n// keyedItems. If the provided schema is _not_ an array with x-kubernetes-list-type=map, returns an\n// empty mapList.\nfunc MakeMapList(sts Schema, items []interface{}) (rv MapList) {\n\tif sts.Type() != \"array\" || sts.XListType() != \"map\" || len(sts.XListMapKeys()) == 0 || len(items) == 0 {\n\t\treturn emptyMapList{}\n\t}\n\tks := makeKeyStrategy(sts)\n\treturn \u0026mapListImpl{\n\t\tsts: sts,\n\t\tks: ks,\n\t\tkeyedItems: map[interface{}]interface{}{},\n\t\tunkeyedItems: items,\n\t}\n}","line":{"from":163,"to":177}} {"id":100017072,"name":"SchemaDeclType","signature":"func SchemaDeclType(s Schema, isResourceRoot bool) *apiservercel.DeclType","file":"staging/src/k8s.io/apiserver/pkg/cel/common/schemas.go","code":"// SchemaDeclType converts the structural schema to a CEL declaration, or returns nil if the\n// structural schema should not be exposed in CEL expressions.\n// Set isResourceRoot to true for the root of a custom resource or embedded resource.\n//\n// Schemas with XPreserveUnknownFields not exposed unless they are objects. Array and \"maps\" schemas\n// are not exposed if their items or additionalProperties schemas are not exposed. Object Properties are not exposed\n// if their schema is not exposed.\n//\n// The CEL declaration for objects with XPreserveUnknownFields does not expose unknown fields.\nfunc SchemaDeclType(s Schema, isResourceRoot bool) *apiservercel.DeclType {\n\tif s == nil {\n\t\treturn nil\n\t}\n\tif s.IsXIntOrString() {\n\t\t// schemas using XIntOrString are not required to have a type.\n\n\t\t// intOrStringType represents the x-kubernetes-int-or-string union type in CEL expressions.\n\t\t// In CEL, the type is represented as dynamic value, which can be thought of as a union type of all types.\n\t\t// All type checking for XIntOrString is deferred to runtime, so all access to values of this type must\n\t\t// be guarded with a type check, e.g.:\n\t\t//\n\t\t// To require that the string representation be a percentage:\n\t\t// `type(intOrStringField) == string \u0026\u0026 intOrStringField.matches(r'(\\d+(\\.\\d+)?%)')`\n\t\t// To validate requirements on both the int and string representation:\n\t\t// `type(intOrStringField) == int ? intOrStringField \u003c 5 : double(intOrStringField.replace('%', '')) \u003c 0.5\n\t\t//\n\t\tdyn := apiservercel.NewSimpleTypeWithMinSize(\"dyn\", cel.DynType, nil, 1) // smallest value for a serialized x-kubernetes-int-or-string is 0\n\t\t// handle x-kubernetes-int-or-string by returning the max length/min serialized size of the largest possible string\n\t\tdyn.MaxElements = maxRequestSizeBytes - 2\n\t\treturn dyn\n\t}\n\n\t// We ignore XPreserveUnknownFields since we don't support validation rules on\n\t// data that we don't have schema information for.\n\n\tif isResourceRoot {\n\t\t// 'apiVersion', 'kind', 'metadata.name' and 'metadata.generateName' are always accessible to validator rules\n\t\t// at the root of resources, even if not specified in the schema.\n\t\t// This includes the root of a custom resource and the root of XEmbeddedResource objects.\n\t\ts = s.WithTypeAndObjectMeta()\n\t}\n\n\tswitch s.Type() {\n\tcase \"array\":\n\t\tif s.Items() != nil {\n\t\t\titemsType := SchemaDeclType(s.Items(), s.Items().IsXEmbeddedResource())\n\t\t\tif itemsType == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tvar maxItems int64\n\t\t\tif s.MaxItems() != nil {\n\t\t\t\tmaxItems = zeroIfNegative(*s.MaxItems())\n\t\t\t} else {\n\t\t\t\tmaxItems = estimateMaxArrayItemsFromMinSize(itemsType.MinSerializedSize)\n\t\t\t}\n\t\t\treturn apiservercel.NewListType(itemsType, maxItems)\n\t\t}\n\t\treturn nil\n\tcase \"object\":\n\t\tif s.AdditionalProperties() != nil \u0026\u0026 s.AdditionalProperties().Schema() != nil {\n\t\t\tpropsType := SchemaDeclType(s.AdditionalProperties().Schema(), s.AdditionalProperties().Schema().IsXEmbeddedResource())\n\t\t\tif propsType != nil {\n\t\t\t\tvar maxProperties int64\n\t\t\t\tif s.MaxProperties() != nil {\n\t\t\t\t\tmaxProperties = zeroIfNegative(*s.MaxProperties())\n\t\t\t\t} else {\n\t\t\t\t\tmaxProperties = estimateMaxAdditionalPropertiesFromMinSize(propsType.MinSerializedSize)\n\t\t\t\t}\n\t\t\t\treturn apiservercel.NewMapType(apiservercel.StringType, propsType, maxProperties)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\tfields := make(map[string]*apiservercel.DeclField, len(s.Properties()))\n\n\t\trequired := map[string]bool{}\n\t\tif s.Required() != nil {\n\t\t\tfor _, f := range s.Required() {\n\t\t\t\trequired[f] = true\n\t\t\t}\n\t\t}\n\t\t// an object will always be serialized at least as {}, so account for that\n\t\tminSerializedSize := int64(2)\n\t\tfor name, prop := range s.Properties() {\n\t\t\tvar enumValues []interface{}\n\t\t\tif prop.Enum() != nil {\n\t\t\t\tfor _, e := range prop.Enum() {\n\t\t\t\t\tenumValues = append(enumValues, e)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif fieldType := SchemaDeclType(prop, prop.IsXEmbeddedResource()); fieldType != nil {\n\t\t\t\tif propName, ok := apiservercel.Escape(name); ok {\n\t\t\t\t\tfields[propName] = apiservercel.NewDeclField(propName, fieldType, required[name], enumValues, prop.Default())\n\t\t\t\t}\n\t\t\t\t// the min serialized size for an object is 2 (for {}) plus the min size of all its required\n\t\t\t\t// properties\n\t\t\t\t// only include required properties without a default value; default values are filled in\n\t\t\t\t// server-side\n\t\t\t\tif required[name] \u0026\u0026 prop.Default() == nil {\n\t\t\t\t\tminSerializedSize += int64(len(name)) + fieldType.MinSerializedSize + 4\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tobjType := apiservercel.NewObjectType(\"object\", fields)\n\t\tobjType.MinSerializedSize = minSerializedSize\n\t\treturn objType\n\tcase \"string\":\n\t\tswitch s.Format() {\n\t\tcase \"byte\":\n\t\t\tbyteWithMaxLength := apiservercel.NewSimpleTypeWithMinSize(\"bytes\", cel.BytesType, types.Bytes([]byte{}), apiservercel.MinStringSize)\n\t\t\tif s.MaxLength() != nil {\n\t\t\t\tbyteWithMaxLength.MaxElements = zeroIfNegative(*s.MaxLength())\n\t\t\t} else {\n\t\t\t\tbyteWithMaxLength.MaxElements = estimateMaxStringLengthPerRequest(s)\n\t\t\t}\n\t\t\treturn byteWithMaxLength\n\t\tcase \"duration\":\n\t\t\tdurationWithMaxLength := apiservercel.NewSimpleTypeWithMinSize(\"duration\", cel.DurationType, types.Duration{Duration: time.Duration(0)}, int64(apiservercel.MinDurationSizeJSON))\n\t\t\tdurationWithMaxLength.MaxElements = estimateMaxStringLengthPerRequest(s)\n\t\t\treturn durationWithMaxLength\n\t\tcase \"date\":\n\t\t\ttimestampWithMaxLength := apiservercel.NewSimpleTypeWithMinSize(\"timestamp\", cel.TimestampType, types.Timestamp{Time: time.Time{}}, int64(apiservercel.JSONDateSize))\n\t\t\ttimestampWithMaxLength.MaxElements = estimateMaxStringLengthPerRequest(s)\n\t\t\treturn timestampWithMaxLength\n\t\tcase \"date-time\":\n\t\t\ttimestampWithMaxLength := apiservercel.NewSimpleTypeWithMinSize(\"timestamp\", cel.TimestampType, types.Timestamp{Time: time.Time{}}, int64(apiservercel.MinDatetimeSizeJSON))\n\t\t\ttimestampWithMaxLength.MaxElements = estimateMaxStringLengthPerRequest(s)\n\t\t\treturn timestampWithMaxLength\n\t\t}\n\n\t\tstrWithMaxLength := apiservercel.NewSimpleTypeWithMinSize(\"string\", cel.StringType, types.String(\"\"), apiservercel.MinStringSize)\n\t\tif s.MaxLength() != nil {\n\t\t\t// multiply the user-provided max length by 4 in the case of an otherwise-untyped string\n\t\t\t// we do this because the OpenAPIv3 spec indicates that maxLength is specified in runes/code points,\n\t\t\t// but we need to reason about length for things like request size, so we use bytes in this code (and an individual\n\t\t\t// unicode code point can be up to 4 bytes long)\n\t\t\tstrWithMaxLength.MaxElements = zeroIfNegative(*s.MaxLength()) * 4\n\t\t} else {\n\t\t\tstrWithMaxLength.MaxElements = estimateMaxStringLengthPerRequest(s)\n\t\t}\n\t\treturn strWithMaxLength\n\tcase \"boolean\":\n\t\treturn apiservercel.BoolType\n\tcase \"number\":\n\t\treturn apiservercel.DoubleType\n\tcase \"integer\":\n\t\treturn apiservercel.IntType\n\t}\n\treturn nil\n}","line":{"from":31,"to":179}} {"id":100017073,"name":"zeroIfNegative","signature":"func zeroIfNegative(v int64) int64","file":"staging/src/k8s.io/apiserver/pkg/cel/common/schemas.go","code":"func zeroIfNegative(v int64) int64 {\n\tif v \u003c 0 {\n\t\treturn 0\n\t}\n\treturn v\n}","line":{"from":181,"to":186}} {"id":100017074,"name":"WithTypeAndObjectMeta","signature":"func WithTypeAndObjectMeta(s *spec.Schema) *spec.Schema","file":"staging/src/k8s.io/apiserver/pkg/cel/common/schemas.go","code":"// WithTypeAndObjectMeta ensures the kind, apiVersion and\n// metadata.name and metadata.generateName properties are specified, making a shallow copy of the provided schema if needed.\nfunc WithTypeAndObjectMeta(s *spec.Schema) *spec.Schema {\n\tif s.Properties != nil \u0026\u0026\n\t\ts.Properties[\"kind\"].Type.Contains(\"string\") \u0026\u0026\n\t\ts.Properties[\"apiVersion\"].Type.Contains(\"string\") \u0026\u0026\n\t\ts.Properties[\"metadata\"].Type.Contains(\"object\") \u0026\u0026\n\t\ts.Properties[\"metadata\"].Properties != nil \u0026\u0026\n\t\ts.Properties[\"metadata\"].Properties[\"name\"].Type.Contains(\"string\") \u0026\u0026\n\t\ts.Properties[\"metadata\"].Properties[\"generateName\"].Type.Contains(\"string\") {\n\t\treturn s\n\t}\n\tresult := *s\n\tprops := make(map[string]spec.Schema, len(s.Properties))\n\tfor k, prop := range s.Properties {\n\t\tprops[k] = prop\n\t}\n\tstringType := spec.StringProperty()\n\tprops[\"kind\"] = *stringType\n\tprops[\"apiVersion\"] = *stringType\n\tprops[\"metadata\"] = spec.Schema{\n\t\tSchemaProps: spec.SchemaProps{\n\t\t\tType: []string{\"object\"},\n\t\t\tProperties: map[string]spec.Schema{\n\t\t\t\t\"name\": *stringType,\n\t\t\t\t\"generateName\": *stringType,\n\t\t\t},\n\t\t},\n\t}\n\tresult.Properties = props\n\n\treturn \u0026result\n}","line":{"from":188,"to":220}} {"id":100017075,"name":"estimateMaxStringLengthPerRequest","signature":"func estimateMaxStringLengthPerRequest(s Schema) int64","file":"staging/src/k8s.io/apiserver/pkg/cel/common/schemas.go","code":"// estimateMaxStringLengthPerRequest estimates the maximum string length (in characters)\n// of a string compatible with the format requirements in the provided schema.\n// must only be called on schemas of type \"string\" or x-kubernetes-int-or-string: true\nfunc estimateMaxStringLengthPerRequest(s Schema) int64 {\n\tif s.IsXIntOrString() {\n\t\treturn maxRequestSizeBytes - 2\n\t}\n\tswitch s.Format() {\n\tcase \"duration\":\n\t\treturn apiservercel.MaxDurationSizeJSON\n\tcase \"date\":\n\t\treturn apiservercel.JSONDateSize\n\tcase \"date-time\":\n\t\treturn apiservercel.MaxDatetimeSizeJSON\n\tdefault:\n\t\t// subtract 2 to account for \"\"\n\t\treturn maxRequestSizeBytes - 2\n\t}\n}","line":{"from":222,"to":240}} {"id":100017076,"name":"estimateMaxArrayItemsFromMinSize","signature":"func estimateMaxArrayItemsFromMinSize(minSize int64) int64","file":"staging/src/k8s.io/apiserver/pkg/cel/common/schemas.go","code":"// estimateMaxArrayItemsPerRequest estimates the maximum number of array items with\n// the provided minimum serialized size that can fit into a single request.\nfunc estimateMaxArrayItemsFromMinSize(minSize int64) int64 {\n\t// subtract 2 to account for [ and ]\n\treturn (maxRequestSizeBytes - 2) / (minSize + 1)\n}","line":{"from":242,"to":247}} {"id":100017077,"name":"estimateMaxAdditionalPropertiesFromMinSize","signature":"func estimateMaxAdditionalPropertiesFromMinSize(minSize int64) int64","file":"staging/src/k8s.io/apiserver/pkg/cel/common/schemas.go","code":"// estimateMaxAdditionalPropertiesPerRequest estimates the maximum number of additional properties\n// with the provided minimum serialized size that can fit into a single request.\nfunc estimateMaxAdditionalPropertiesFromMinSize(minSize int64) int64 {\n\t// 2 bytes for key + \"\" + colon + comma + smallest possible value, realistically the actual keys\n\t// will all vary in length\n\tkeyValuePairSize := minSize + 6\n\t// subtract 2 to account for { and }\n\treturn (maxRequestSizeBytes - 2) / keyValuePairSize\n}","line":{"from":249,"to":257}} {"id":100017078,"name":"UnstructuredToVal","signature":"func UnstructuredToVal(unstructured interface{}, schema Schema) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"// UnstructuredToVal converts a Kubernetes unstructured data element to a CEL Val.\n// The root schema of custom resource schema is expected contain type meta and object meta schemas.\n// If Embedded resources do not contain type meta and object meta schemas, they will be added automatically.\nfunc UnstructuredToVal(unstructured interface{}, schema Schema) ref.Val {\n\tif unstructured == nil {\n\t\tif schema.Nullable() {\n\t\t\treturn types.NullValue\n\t\t}\n\t\treturn types.NewErr(\"invalid data, got null for schema with nullable=false\")\n\t}\n\tif schema.IsXIntOrString() {\n\t\tswitch v := unstructured.(type) {\n\t\tcase string:\n\t\t\treturn types.String(v)\n\t\tcase int:\n\t\t\treturn types.Int(v)\n\t\tcase int32:\n\t\t\treturn types.Int(v)\n\t\tcase int64:\n\t\t\treturn types.Int(v)\n\t\t}\n\t\treturn types.NewErr(\"invalid data, expected XIntOrString value to be either a string or integer\")\n\t}\n\tif schema.Type() == \"object\" {\n\t\tm, ok := unstructured.(map[string]interface{})\n\t\tif !ok {\n\t\t\treturn types.NewErr(\"invalid data, expected a map for the provided schema with type=object\")\n\t\t}\n\t\tif schema.IsXEmbeddedResource() || schema.Properties() != nil {\n\t\t\tif schema.IsXEmbeddedResource() {\n\t\t\t\tschema = schema.WithTypeAndObjectMeta()\n\t\t\t}\n\t\t\treturn \u0026unstructuredMap{\n\t\t\t\tvalue: m,\n\t\t\t\tschema: schema,\n\t\t\t\tpropSchema: func(key string) (Schema, bool) {\n\t\t\t\t\tif schema, ok := schema.Properties()[key]; ok {\n\t\t\t\t\t\treturn schema, true\n\t\t\t\t\t}\n\t\t\t\t\treturn nil, false\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t\tif schema.AdditionalProperties() != nil \u0026\u0026 schema.AdditionalProperties().Schema() != nil {\n\t\t\treturn \u0026unstructuredMap{\n\t\t\t\tvalue: m,\n\t\t\t\tschema: schema,\n\t\t\t\tpropSchema: func(key string) (Schema, bool) {\n\t\t\t\t\treturn schema.AdditionalProperties().Schema(), true\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t\t// A object with x-kubernetes-preserve-unknown-fields but no properties or additionalProperties is treated\n\t\t// as an empty object.\n\t\tif schema.IsXPreserveUnknownFields() {\n\t\t\treturn \u0026unstructuredMap{\n\t\t\t\tvalue: m,\n\t\t\t\tschema: schema,\n\t\t\t\tpropSchema: func(key string) (Schema, bool) {\n\t\t\t\t\treturn nil, false\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t\treturn types.NewErr(\"invalid object type, expected either Properties or AdditionalProperties with Allows=true and non-empty Schema\")\n\t}\n\n\tif schema.Type() == \"array\" {\n\t\tl, ok := unstructured.([]interface{})\n\t\tif !ok {\n\t\t\treturn types.NewErr(\"invalid data, expected an array for the provided schema with type=array\")\n\t\t}\n\t\tif schema.Items() == nil {\n\t\t\treturn types.NewErr(\"invalid array type, expected Items with a non-empty Schema\")\n\t\t}\n\t\ttypedList := unstructuredList{elements: l, itemsSchema: schema.Items()}\n\t\tlistType := schema.XListType()\n\t\tif listType != \"\" {\n\t\t\tswitch listType {\n\t\t\tcase \"map\":\n\t\t\t\tmapKeys := schema.XListMapKeys()\n\t\t\t\treturn \u0026unstructuredMapList{unstructuredList: typedList, escapedKeyProps: escapeKeyProps(mapKeys)}\n\t\t\tcase \"set\":\n\t\t\t\treturn \u0026unstructuredSetList{unstructuredList: typedList}\n\t\t\tcase \"atomic\":\n\t\t\t\treturn \u0026typedList\n\t\t\tdefault:\n\t\t\t\treturn types.NewErr(\"invalid x-kubernetes-list-type, expected 'map', 'set' or 'atomic' but got %s\", listType)\n\t\t\t}\n\t\t}\n\t\treturn \u0026typedList\n\t}\n\n\tif schema.Type() == \"string\" {\n\t\tstr, ok := unstructured.(string)\n\t\tif !ok {\n\t\t\treturn types.NewErr(\"invalid data, expected string, got %T\", unstructured)\n\t\t}\n\t\tswitch schema.Format() {\n\t\tcase \"duration\":\n\t\t\td, err := strfmt.ParseDuration(str)\n\t\t\tif err != nil {\n\t\t\t\treturn types.NewErr(\"Invalid duration %s: %v\", str, err)\n\t\t\t}\n\t\t\treturn types.Duration{Duration: d}\n\t\tcase \"date\":\n\t\t\td, err := time.Parse(strfmt.RFC3339FullDate, str) // strfmt uses this format for OpenAPIv3 value validation\n\t\t\tif err != nil {\n\t\t\t\treturn types.NewErr(\"Invalid date formatted string %s: %v\", str, err)\n\t\t\t}\n\t\t\treturn types.Timestamp{Time: d}\n\t\tcase \"date-time\":\n\t\t\td, err := strfmt.ParseDateTime(str)\n\t\t\tif err != nil {\n\t\t\t\treturn types.NewErr(\"Invalid date-time formatted string %s: %v\", str, err)\n\t\t\t}\n\t\t\treturn types.Timestamp{Time: time.Time(d)}\n\t\tcase \"byte\":\n\t\t\tbase64 := strfmt.Base64{}\n\t\t\terr := base64.UnmarshalText([]byte(str))\n\t\t\tif err != nil {\n\t\t\t\treturn types.NewErr(\"Invalid byte formatted string %s: %v\", str, err)\n\t\t\t}\n\t\t\treturn types.Bytes(base64)\n\t\t}\n\n\t\treturn types.String(str)\n\t}\n\tif schema.Type() == \"number\" {\n\t\tswitch v := unstructured.(type) {\n\t\t// float representations of whole numbers (e.g. 1.0, 0.0) can convert to int representations (e.g. 1, 0) in yaml\n\t\t// to json translation, and then get parsed as int64s\n\t\tcase int:\n\t\t\treturn types.Double(v)\n\t\tcase int32:\n\t\t\treturn types.Double(v)\n\t\tcase int64:\n\t\t\treturn types.Double(v)\n\n\t\tcase float32:\n\t\t\treturn types.Double(v)\n\t\tcase float64:\n\t\t\treturn types.Double(v)\n\t\tdefault:\n\t\t\treturn types.NewErr(\"invalid data, expected float, got %T\", unstructured)\n\t\t}\n\t}\n\tif schema.Type() == \"integer\" {\n\t\tswitch v := unstructured.(type) {\n\t\tcase int:\n\t\t\treturn types.Int(v)\n\t\tcase int32:\n\t\t\treturn types.Int(v)\n\t\tcase int64:\n\t\t\treturn types.Int(v)\n\t\tdefault:\n\t\t\treturn types.NewErr(\"invalid data, expected int, got %T\", unstructured)\n\t\t}\n\t}\n\tif schema.Type() == \"boolean\" {\n\t\tb, ok := unstructured.(bool)\n\t\tif !ok {\n\t\t\treturn types.NewErr(\"invalid data, expected bool, got %T\", unstructured)\n\t\t}\n\t\treturn types.Bool(b)\n\t}\n\n\tif schema.IsXPreserveUnknownFields() {\n\t\treturn \u0026unknownPreserved{u: unstructured}\n\t}\n\n\treturn types.NewErr(\"invalid type, expected object, array, number, integer, boolean or string, or no type with x-kubernetes-int-or-string or x-kubernetes-preserve-unknown-fields is true, got %s\", schema.Type())\n}","line":{"from":35,"to":206}} {"id":100017079,"name":"ConvertToNative","signature":"func (t *unknownPreserved) ConvertToNative(refType reflect.Type) (interface{}, error)","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unknownPreserved) ConvertToNative(refType reflect.Type) (interface{}, error) {\n\treturn nil, fmt.Errorf(\"type conversion to '%s' not supported for values preserved by x-kubernetes-preserve-unknown-fields\", refType)\n}","line":{"from":216,"to":218}} {"id":100017080,"name":"ConvertToType","signature":"func (t *unknownPreserved) ConvertToType(typeValue ref.Type) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unknownPreserved) ConvertToType(typeValue ref.Type) ref.Val {\n\treturn types.NewErr(\"type conversion to '%s' not supported for values preserved by x-kubernetes-preserve-unknown-fields\", typeValue.TypeName())\n}","line":{"from":220,"to":222}} {"id":100017081,"name":"Equal","signature":"func (t *unknownPreserved) Equal(other ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unknownPreserved) Equal(other ref.Val) ref.Val {\n\treturn types.Bool(equality.Semantic.DeepEqual(t.u, other.Value()))\n}","line":{"from":224,"to":226}} {"id":100017082,"name":"Type","signature":"func (t *unknownPreserved) Type() ref.Type","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unknownPreserved) Type() ref.Type {\n\treturn types.UnknownType\n}","line":{"from":228,"to":230}} {"id":100017083,"name":"Value","signature":"func (t *unknownPreserved) Value() interface{}","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unknownPreserved) Value() interface{} {\n\treturn t.u // used by Equal checks\n}","line":{"from":232,"to":234}} {"id":100017084,"name":"getMap","signature":"func (t *unstructuredMapList) getMap() map[interface{}]interface{}","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unstructuredMapList) getMap() map[interface{}]interface{} {\n\tt.Do(func() {\n\t\tt.mapOfList = make(map[interface{}]interface{}, len(t.elements))\n\t\tfor _, e := range t.elements {\n\t\t\tt.mapOfList[t.toMapKey(e)] = e\n\t\t}\n\t})\n\treturn t.mapOfList\n}","line":{"from":245,"to":253}} {"id":100017085,"name":"toMapKey","signature":"func (t *unstructuredMapList) toMapKey(element interface{}) interface{}","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"// toMapKey returns a valid golang map key for the given element of the map list.\n// element must be a valid map list entry where all map key props are scalar types (which are comparable in go\n// and valid for use in a golang map key).\nfunc (t *unstructuredMapList) toMapKey(element interface{}) interface{} {\n\teObj, ok := element.(map[string]interface{})\n\tif !ok {\n\t\treturn types.NewErr(\"unexpected data format for element of array with x-kubernetes-list-type=map: %T\", element)\n\t}\n\t// Arrays are comparable in go and may be used as map keys, but maps and slices are not.\n\t// So we can special case small numbers of key props as arrays and fall back to serialization\n\t// for larger numbers of key props\n\tif len(t.escapedKeyProps) == 1 {\n\t\treturn eObj[t.escapedKeyProps[0]]\n\t}\n\tif len(t.escapedKeyProps) == 2 {\n\t\treturn [2]interface{}{eObj[t.escapedKeyProps[0]], eObj[t.escapedKeyProps[1]]}\n\t}\n\tif len(t.escapedKeyProps) == 3 {\n\t\treturn [3]interface{}{eObj[t.escapedKeyProps[0]], eObj[t.escapedKeyProps[1]], eObj[t.escapedKeyProps[2]]}\n\t}\n\n\tkey := make([]interface{}, len(t.escapedKeyProps))\n\tfor i, kf := range t.escapedKeyProps {\n\t\tkey[i] = eObj[kf]\n\t}\n\treturn fmt.Sprintf(\"%v\", key)\n}","line":{"from":255,"to":281}} {"id":100017086,"name":"Equal","signature":"func (t *unstructuredMapList) Equal(other ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"// Equal on a map list ignores list element order.\nfunc (t *unstructuredMapList) Equal(other ref.Val) ref.Val {\n\toMapList, ok := other.(traits.Lister)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(other)\n\t}\n\tsz := types.Int(len(t.elements))\n\tif sz != oMapList.Size() {\n\t\treturn types.False\n\t}\n\ttMap := t.getMap()\n\tfor it := oMapList.Iterator(); it.HasNext() == types.True; {\n\t\tv := it.Next()\n\t\tk := t.toMapKey(v.Value())\n\t\ttVal, ok := tMap[k]\n\t\tif !ok {\n\t\t\treturn types.False\n\t\t}\n\t\teq := UnstructuredToVal(tVal, t.itemsSchema).Equal(v)\n\t\tif eq != types.True {\n\t\t\treturn eq // either false or error\n\t\t}\n\t}\n\treturn types.True\n}","line":{"from":283,"to":307}} {"id":100017087,"name":"Add","signature":"func (t *unstructuredMapList) Add(other ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"// Add for a map list `X + Y` performs a merge where the array positions of all keys in `X` are preserved but the values\n// are overwritten by values in `Y` when the key sets of `X` and `Y` intersect. Elements in `Y` with\n// non-intersecting keys are appended, retaining their partial order.\nfunc (t *unstructuredMapList) Add(other ref.Val) ref.Val {\n\toMapList, ok := other.(traits.Lister)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(other)\n\t}\n\telements := make([]interface{}, len(t.elements))\n\tkeyToIdx := map[interface{}]int{}\n\tfor i, e := range t.elements {\n\t\tk := t.toMapKey(e)\n\t\tkeyToIdx[k] = i\n\t\telements[i] = e\n\t}\n\tfor it := oMapList.Iterator(); it.HasNext() == types.True; {\n\t\tv := it.Next().Value()\n\t\tk := t.toMapKey(v)\n\t\tif overwritePosition, ok := keyToIdx[k]; ok {\n\t\t\telements[overwritePosition] = v\n\t\t} else {\n\t\t\telements = append(elements, v)\n\t\t}\n\t}\n\treturn \u0026unstructuredMapList{\n\t\tunstructuredList: unstructuredList{elements: elements, itemsSchema: t.itemsSchema},\n\t\tescapedKeyProps: t.escapedKeyProps,\n\t}\n}","line":{"from":309,"to":337}} {"id":100017088,"name":"escapeKeyProps","signature":"func escapeKeyProps(idents []string) []string","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"// escapeKeyProps returns identifiers with Escape applied to each.\n// Identifiers that cannot be escaped are left as-is. They are inaccessible to CEL programs but are\n// are still needed internally to perform equality checks.\nfunc escapeKeyProps(idents []string) []string {\n\tresult := make([]string, len(idents))\n\tfor i, prop := range idents {\n\t\tif escaped, ok := cel.Escape(prop); ok {\n\t\t\tresult[i] = escaped\n\t\t} else {\n\t\t\tresult[i] = prop\n\t\t}\n\t}\n\treturn result\n}","line":{"from":339,"to":352}} {"id":100017089,"name":"getSet","signature":"func (t *unstructuredSetList) getSet() map[interface{}]struct{}","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unstructuredSetList) getSet() map[interface{}]struct{} {\n\t// sets are only allowed to contain scalar elements, which are comparable in go, and can safely be used as\n\t// golang map keys\n\tt.Do(func() {\n\t\tt.set = make(map[interface{}]struct{}, len(t.elements))\n\t\tfor _, e := range t.elements {\n\t\t\tt.set[e] = struct{}{}\n\t\t}\n\t})\n\treturn t.set\n}","line":{"from":363,"to":373}} {"id":100017090,"name":"Equal","signature":"func (t *unstructuredSetList) Equal(other ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"// Equal on a map list ignores list element order.\nfunc (t *unstructuredSetList) Equal(other ref.Val) ref.Val {\n\toSetList, ok := other.(traits.Lister)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(other)\n\t}\n\tsz := types.Int(len(t.elements))\n\tif sz != oSetList.Size() {\n\t\treturn types.False\n\t}\n\ttSet := t.getSet()\n\tfor it := oSetList.Iterator(); it.HasNext() == types.True; {\n\t\tnext := it.Next().Value()\n\t\t_, ok := tSet[next]\n\t\tif !ok {\n\t\t\treturn types.False\n\t\t}\n\t}\n\treturn types.True\n}","line":{"from":375,"to":394}} {"id":100017091,"name":"Add","signature":"func (t *unstructuredSetList) Add(other ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"// Add for a set list `X + Y` performs a union where the array positions of all elements in `X` are preserved and\n// non-intersecting elements in `Y` are appended, retaining their partial order.\nfunc (t *unstructuredSetList) Add(other ref.Val) ref.Val {\n\toSetList, ok := other.(traits.Lister)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(other)\n\t}\n\telements := t.elements\n\tset := t.getSet()\n\tfor it := oSetList.Iterator(); it.HasNext() == types.True; {\n\t\tnext := it.Next().Value()\n\t\tif _, ok := set[next]; !ok {\n\t\t\tset[next] = struct{}{}\n\t\t\telements = append(elements, next)\n\t\t}\n\t}\n\treturn \u0026unstructuredSetList{\n\t\tunstructuredList: unstructuredList{elements: elements, itemsSchema: t.itemsSchema},\n\t\tescapedKeyProps: t.escapedKeyProps,\n\t}\n}","line":{"from":396,"to":416}} {"id":100017092,"name":"ConvertToNative","signature":"func (t *unstructuredList) ConvertToNative(typeDesc reflect.Type) (interface{}, error)","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unstructuredList) ConvertToNative(typeDesc reflect.Type) (interface{}, error) {\n\tswitch typeDesc.Kind() {\n\tcase reflect.Slice:\n\t\tswitch t.itemsSchema.Type() {\n\t\t// Workaround for https://github.com/kubernetes/kubernetes/issues/117590 until we\n\t\t// resolve the desired behavior in cel-go via https://github.com/google/cel-go/issues/688\n\t\tcase \"string\":\n\t\t\tvar result []string\n\t\t\tfor _, e := range t.elements {\n\t\t\t\ts, ok := e.(string)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, fmt.Errorf(\"expected all elements to be of type string, but got %T\", e)\n\t\t\t\t}\n\t\t\t\tresult = append(result, s)\n\t\t\t}\n\t\t\treturn result, nil\n\t\tdefault:\n\t\t\treturn t.elements, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"type conversion error from '%s' to '%s'\", t.Type(), typeDesc)\n}","line":{"from":426,"to":447}} {"id":100017093,"name":"ConvertToType","signature":"func (t *unstructuredList) ConvertToType(typeValue ref.Type) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unstructuredList) ConvertToType(typeValue ref.Type) ref.Val {\n\tswitch typeValue {\n\tcase types.ListType:\n\t\treturn t\n\tcase types.TypeType:\n\t\treturn types.ListType\n\t}\n\treturn types.NewErr(\"type conversion error from '%s' to '%s'\", t.Type(), typeValue.TypeName())\n}","line":{"from":449,"to":457}} {"id":100017094,"name":"Equal","signature":"func (t *unstructuredList) Equal(other ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unstructuredList) Equal(other ref.Val) ref.Val {\n\toList, ok := other.(traits.Lister)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(other)\n\t}\n\tsz := types.Int(len(t.elements))\n\tif sz != oList.Size() {\n\t\treturn types.False\n\t}\n\tfor i := types.Int(0); i \u003c sz; i++ {\n\t\teq := t.Get(i).Equal(oList.Get(i))\n\t\tif eq != types.True {\n\t\t\treturn eq // either false or error\n\t\t}\n\t}\n\treturn types.True\n}","line":{"from":459,"to":475}} {"id":100017095,"name":"Type","signature":"func (t *unstructuredList) Type() ref.Type","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unstructuredList) Type() ref.Type {\n\treturn types.ListType\n}","line":{"from":477,"to":479}} {"id":100017096,"name":"Value","signature":"func (t *unstructuredList) Value() interface{}","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unstructuredList) Value() interface{} {\n\treturn t.elements\n}","line":{"from":481,"to":483}} {"id":100017097,"name":"Add","signature":"func (t *unstructuredList) Add(other ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unstructuredList) Add(other ref.Val) ref.Val {\n\toList, ok := other.(traits.Lister)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(other)\n\t}\n\telements := t.elements\n\tfor it := oList.Iterator(); it.HasNext() == types.True; {\n\t\tnext := it.Next().Value()\n\t\telements = append(elements, next)\n\t}\n\n\treturn \u0026unstructuredList{elements: elements, itemsSchema: t.itemsSchema}\n}","line":{"from":485,"to":497}} {"id":100017098,"name":"Contains","signature":"func (t *unstructuredList) Contains(val ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unstructuredList) Contains(val ref.Val) ref.Val {\n\tif types.IsUnknownOrError(val) {\n\t\treturn val\n\t}\n\tvar err ref.Val\n\tsz := len(t.elements)\n\tfor i := 0; i \u003c sz; i++ {\n\t\telem := UnstructuredToVal(t.elements[i], t.itemsSchema)\n\t\tcmp := elem.Equal(val)\n\t\tb, ok := cmp.(types.Bool)\n\t\tif !ok \u0026\u0026 err == nil {\n\t\t\terr = types.MaybeNoSuchOverloadErr(cmp)\n\t\t}\n\t\tif b == types.True {\n\t\t\treturn types.True\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn types.False\n}","line":{"from":499,"to":520}} {"id":100017099,"name":"Get","signature":"func (t *unstructuredList) Get(idx ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unstructuredList) Get(idx ref.Val) ref.Val {\n\tiv, isInt := idx.(types.Int)\n\tif !isInt {\n\t\treturn types.ValOrErr(idx, \"unsupported index: %v\", idx)\n\t}\n\ti := int(iv)\n\tif i \u003c 0 || i \u003e= len(t.elements) {\n\t\treturn types.NewErr(\"index out of bounds: %v\", idx)\n\t}\n\treturn UnstructuredToVal(t.elements[i], t.itemsSchema)\n}","line":{"from":522,"to":532}} {"id":100017100,"name":"Iterator","signature":"func (t *unstructuredList) Iterator() traits.Iterator","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unstructuredList) Iterator() traits.Iterator {\n\titems := make([]ref.Val, len(t.elements))\n\tfor i, item := range t.elements {\n\t\titemCopy := item\n\t\titems[i] = UnstructuredToVal(itemCopy, t.itemsSchema)\n\t}\n\treturn \u0026listIterator{unstructuredList: t, items: items}\n}","line":{"from":534,"to":541}} {"id":100017101,"name":"HasNext","signature":"func (it *listIterator) HasNext() ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (it *listIterator) HasNext() ref.Val {\n\treturn types.Bool(it.idx \u003c len(it.items))\n}","line":{"from":549,"to":551}} {"id":100017102,"name":"Next","signature":"func (it *listIterator) Next() ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (it *listIterator) Next() ref.Val {\n\titem := it.items[it.idx]\n\tit.idx++\n\treturn item\n}","line":{"from":553,"to":557}} {"id":100017103,"name":"Size","signature":"func (t *unstructuredList) Size() ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unstructuredList) Size() ref.Val {\n\treturn types.Int(len(t.elements))\n}","line":{"from":559,"to":561}} {"id":100017104,"name":"ConvertToNative","signature":"func (t *unstructuredMap) ConvertToNative(typeDesc reflect.Type) (interface{}, error)","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unstructuredMap) ConvertToNative(typeDesc reflect.Type) (interface{}, error) {\n\tswitch typeDesc.Kind() {\n\tcase reflect.Map:\n\t\treturn t.value, nil\n\t}\n\treturn nil, fmt.Errorf(\"type conversion error from '%s' to '%s'\", t.Type(), typeDesc)\n}","line":{"from":573,"to":579}} {"id":100017105,"name":"ConvertToType","signature":"func (t *unstructuredMap) ConvertToType(typeValue ref.Type) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unstructuredMap) ConvertToType(typeValue ref.Type) ref.Val {\n\tswitch typeValue {\n\tcase types.MapType:\n\t\treturn t\n\tcase types.TypeType:\n\t\treturn types.MapType\n\t}\n\treturn types.NewErr(\"type conversion error from '%s' to '%s'\", t.Type(), typeValue.TypeName())\n}","line":{"from":581,"to":589}} {"id":100017106,"name":"Equal","signature":"func (t *unstructuredMap) Equal(other ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unstructuredMap) Equal(other ref.Val) ref.Val {\n\toMap, isMap := other.(traits.Mapper)\n\tif !isMap {\n\t\treturn types.MaybeNoSuchOverloadErr(other)\n\t}\n\tif t.Size() != oMap.Size() {\n\t\treturn types.False\n\t}\n\tfor key, value := range t.value {\n\t\tif propSchema, ok := t.propSchema(key); ok {\n\t\t\tov, found := oMap.Find(types.String(key))\n\t\t\tif !found {\n\t\t\t\treturn types.False\n\t\t\t}\n\t\t\tv := UnstructuredToVal(value, propSchema)\n\t\t\tvEq := v.Equal(ov)\n\t\t\tif vEq != types.True {\n\t\t\t\treturn vEq // either false or error\n\t\t\t}\n\t\t} else {\n\t\t\t// Must be an object with properties.\n\t\t\t// Since we've encountered an unknown field, fallback to unstructured equality checking.\n\t\t\touMap, ok := other.(*unstructuredMap)\n\t\t\tif !ok {\n\t\t\t\t// The compiler ensures equality is against the same type of object, so this should be unreachable\n\t\t\t\treturn types.MaybeNoSuchOverloadErr(other)\n\t\t\t}\n\t\t\tif oValue, ok := ouMap.value[key]; ok {\n\t\t\t\tif !equality.Semantic.DeepEqual(value, oValue) {\n\t\t\t\t\treturn types.False\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn types.True\n}","line":{"from":591,"to":626}} {"id":100017107,"name":"Type","signature":"func (t *unstructuredMap) Type() ref.Type","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unstructuredMap) Type() ref.Type {\n\treturn types.MapType\n}","line":{"from":628,"to":630}} {"id":100017108,"name":"Value","signature":"func (t *unstructuredMap) Value() interface{}","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unstructuredMap) Value() interface{} {\n\treturn t.value\n}","line":{"from":632,"to":634}} {"id":100017109,"name":"Contains","signature":"func (t *unstructuredMap) Contains(key ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unstructuredMap) Contains(key ref.Val) ref.Val {\n\tv, found := t.Find(key)\n\tif v != nil \u0026\u0026 types.IsUnknownOrError(v) {\n\t\treturn v\n\t}\n\n\treturn types.Bool(found)\n}","line":{"from":636,"to":643}} {"id":100017110,"name":"Get","signature":"func (t *unstructuredMap) Get(key ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unstructuredMap) Get(key ref.Val) ref.Val {\n\tv, found := t.Find(key)\n\tif found {\n\t\treturn v\n\t}\n\treturn types.ValOrErr(key, \"no such key: %v\", key)\n}","line":{"from":645,"to":651}} {"id":100017111,"name":"Iterator","signature":"func (t *unstructuredMap) Iterator() traits.Iterator","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unstructuredMap) Iterator() traits.Iterator {\n\tisObject := t.schema.Properties() != nil\n\tkeys := make([]ref.Val, len(t.value))\n\ti := 0\n\tfor k := range t.value {\n\t\tif _, ok := t.propSchema(k); ok {\n\t\t\tmapKey := k\n\t\t\tif isObject {\n\t\t\t\tif escaped, ok := cel.Escape(k); ok {\n\t\t\t\t\tmapKey = escaped\n\t\t\t\t}\n\t\t\t}\n\t\t\tkeys[i] = types.String(mapKey)\n\t\t\ti++\n\t\t}\n\t}\n\treturn \u0026mapIterator{unstructuredMap: t, keys: keys}\n}","line":{"from":653,"to":670}} {"id":100017112,"name":"HasNext","signature":"func (it *mapIterator) HasNext() ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (it *mapIterator) HasNext() ref.Val {\n\treturn types.Bool(it.idx \u003c len(it.keys))\n}","line":{"from":678,"to":680}} {"id":100017113,"name":"Next","signature":"func (it *mapIterator) Next() ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (it *mapIterator) Next() ref.Val {\n\tkey := it.keys[it.idx]\n\tit.idx++\n\treturn key\n}","line":{"from":682,"to":686}} {"id":100017114,"name":"Size","signature":"func (t *unstructuredMap) Size() ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unstructuredMap) Size() ref.Val {\n\treturn types.Int(len(t.value))\n}","line":{"from":688,"to":690}} {"id":100017115,"name":"Find","signature":"func (t *unstructuredMap) Find(key ref.Val) (ref.Val, bool)","file":"staging/src/k8s.io/apiserver/pkg/cel/common/values.go","code":"func (t *unstructuredMap) Find(key ref.Val) (ref.Val, bool) {\n\tisObject := t.schema.Properties() != nil\n\tkeyStr, ok := key.(types.String)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(key), true\n\t}\n\tk := keyStr.Value().(string)\n\tif isObject {\n\t\tk, ok = cel.Unescape(k)\n\t\tif !ok {\n\t\t\treturn nil, false\n\t\t}\n\t}\n\tif v, ok := t.value[k]; ok {\n\t\t// If this is an object with properties, not an object with additionalProperties,\n\t\t// then null valued nullable fields are treated the same as absent optional fields.\n\t\tif isObject \u0026\u0026 v == nil {\n\t\t\treturn nil, false\n\t\t}\n\t\tif propSchema, ok := t.propSchema(k); ok {\n\t\t\treturn UnstructuredToVal(v, propSchema), true\n\t\t}\n\t}\n\n\treturn nil, false\n}","line":{"from":692,"to":717}} {"id":100017116,"name":"EnumValue","signature":"func (c *CompositedTypeProvider) EnumValue(enumName string) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/composited.go","code":"// EnumValue finds out the numeric value of the given enum name.\n// The result comes from first provider that returns non-nil.\nfunc (c *CompositedTypeProvider) EnumValue(enumName string) ref.Val {\n\tfor _, p := range c.Providers {\n\t\tval := p.EnumValue(enumName)\n\t\tif val != nil {\n\t\t\treturn val\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":35,"to":45}} {"id":100017117,"name":"FindIdent","signature":"func (c *CompositedTypeProvider) FindIdent(identName string) (ref.Val, bool)","file":"staging/src/k8s.io/apiserver/pkg/cel/composited.go","code":"// FindIdent takes a qualified identifier name and returns a Value if one\n// exists. The result comes from first provider that returns non-nil.\nfunc (c *CompositedTypeProvider) FindIdent(identName string) (ref.Val, bool) {\n\tfor _, p := range c.Providers {\n\t\tval, ok := p.FindIdent(identName)\n\t\tif ok {\n\t\t\treturn val, ok\n\t\t}\n\t}\n\treturn nil, false\n}","line":{"from":47,"to":57}} {"id":100017118,"name":"FindType","signature":"func (c *CompositedTypeProvider) FindType(typeName string) (*exprpb.Type, bool)","file":"staging/src/k8s.io/apiserver/pkg/cel/composited.go","code":"// FindType finds the Type given a qualified type name, or return false\n// if none of the providers finds the type.\n// If any of the providers find the type, the first provider that returns true\n// will be the result.\nfunc (c *CompositedTypeProvider) FindType(typeName string) (*exprpb.Type, bool) {\n\tfor _, p := range c.Providers {\n\t\ttyp, ok := p.FindType(typeName)\n\t\tif ok {\n\t\t\treturn typ, ok\n\t\t}\n\t}\n\treturn nil, false\n}","line":{"from":59,"to":71}} {"id":100017119,"name":"FindFieldType","signature":"func (c *CompositedTypeProvider) FindFieldType(messageType string, fieldName string) (*ref.FieldType, bool)","file":"staging/src/k8s.io/apiserver/pkg/cel/composited.go","code":"// FindFieldType returns the field type for a checked type value. Returns\n// false if none of the providers can find the type.\n// If multiple providers can find the field, the result is taken from\n// the first that does.\nfunc (c *CompositedTypeProvider) FindFieldType(messageType string, fieldName string) (*ref.FieldType, bool) {\n\tfor _, p := range c.Providers {\n\t\tft, ok := p.FindFieldType(messageType, fieldName)\n\t\tif ok {\n\t\t\treturn ft, ok\n\t\t}\n\t}\n\treturn nil, false\n}","line":{"from":73,"to":85}} {"id":100017120,"name":"NewValue","signature":"func (c *CompositedTypeProvider) NewValue(typeName string, fields map[string]ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/composited.go","code":"// NewValue creates a new type value from a qualified name and map of field\n// name to value.\n// If multiple providers can create the new type, the first that returns\n// non-nil will decide the result.\nfunc (c *CompositedTypeProvider) NewValue(typeName string, fields map[string]ref.Val) ref.Val {\n\tfor _, p := range c.Providers {\n\t\tv := p.NewValue(typeName, fields)\n\t\tif v != nil {\n\t\t\treturn v\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":87,"to":99}} {"id":100017121,"name":"NativeToValue","signature":"func (c *CompositedTypeAdapter) NativeToValue(value interface{}) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/composited.go","code":"// NativeToValue takes the value and convert it into a ref.Val\n// The result comes from the first TypeAdapter that returns non-nil.\nfunc (c *CompositedTypeAdapter) NativeToValue(value interface{}) ref.Val {\n\tfor _, a := range c.Adapters {\n\t\tv := a.NativeToValue(value)\n\t\tif v != nil {\n\t\t\treturn v\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":109,"to":119}} {"id":100017122,"name":"Error","signature":"func (v *Error) Error() string","file":"staging/src/k8s.io/apiserver/pkg/cel/errors.go","code":"// Error implements the error interface.\nfunc (v *Error) Error() string {\n\treturn v.Detail\n}","line":{"from":28,"to":31}} {"id":100017123,"name":"newCharacterFilter","signature":"func newCharacterFilter(characters string) []bool","file":"staging/src/k8s.io/apiserver/pkg/cel/escaping.go","code":"// newCharacterFilter returns a boolean array to indicate the allowed characters\nfunc newCharacterFilter(characters string) []bool {\n\tmaxChar := 0\n\tfor _, c := range characters {\n\t\tif maxChar \u003c int(c) {\n\t\t\tmaxChar = int(c)\n\t\t}\n\t}\n\tfilter := make([]bool, maxChar+1)\n\n\tfor _, c := range characters {\n\t\tfilter[int(c)] = true\n\t}\n\n\treturn filter\n}","line":{"from":39,"to":54}} {"id":100017124,"name":"skipRegexCheck","signature":"func skipRegexCheck(ident string) escapeCheck","file":"staging/src/k8s.io/apiserver/pkg/cel/escaping.go","code":"// skipRegexCheck checks if escape would be skipped.\n// if invalidCharFound is true, it must have invalid character; if invalidCharFound is false, not sure if it has invalid character or not\nfunc skipRegexCheck(ident string) escapeCheck {\n\tescapeCheck := escapeCheck{canSkipRegex: true, invalidCharFound: false}\n\t// skip escape if possible\n\tprevious_underscore := false\n\tfor _, c := range ident {\n\t\tif c == '/' || c == '-' || c == '.' {\n\t\t\tescapeCheck.canSkipRegex = false\n\t\t\treturn escapeCheck\n\t\t}\n\t\tintc := int(c)\n\t\tif intc \u003c 0 || intc \u003e= len(validCharacterFilter) || !validCharacterFilter[intc] {\n\t\t\tescapeCheck.invalidCharFound = true\n\t\t\treturn escapeCheck\n\t\t}\n\t\tif c == '_' \u0026\u0026 previous_underscore {\n\t\t\tescapeCheck.canSkipRegex = false\n\t\t\treturn escapeCheck\n\t\t}\n\n\t\tprevious_underscore = c == '_'\n\t}\n\treturn escapeCheck\n}","line":{"from":61,"to":85}} {"id":100017125,"name":"Escape","signature":"func Escape(ident string) (string, bool)","file":"staging/src/k8s.io/apiserver/pkg/cel/escaping.go","code":"// Escape escapes ident and returns a CEL identifier (of the form '[a-zA-Z_][a-zA-Z0-9_]*'), or returns\n// false if the ident does not match the supported input format of `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*`.\n// Escaping Rules:\n// - '__' escapes to '__underscores__'\n// - '.' escapes to '__dot__'\n// - '-' escapes to '__dash__'\n// - '/' escapes to '__slash__'\n// - Identifiers that exactly match a CEL RESERVED keyword escape to '__{keyword}__'. The keywords are: \"true\", \"false\",\n// \"null\", \"in\", \"as\", \"break\", \"const\", \"continue\", \"else\", \"for\", \"function\", \"if\", \"import\", \"let\", loop\", \"package\",\n// \"namespace\", \"return\".\nfunc Escape(ident string) (string, bool) {\n\tif len(ident) == 0 || ('0' \u003c= ident[0] \u0026\u0026 ident[0] \u003c= '9') {\n\t\treturn \"\", false\n\t}\n\tif celReservedSymbols.Has(ident) {\n\t\treturn \"__\" + ident + \"__\", true\n\t}\n\n\tescapeCheck := skipRegexCheck(ident)\n\tif escapeCheck.invalidCharFound {\n\t\treturn \"\", false\n\t}\n\tif escapeCheck.canSkipRegex {\n\t\treturn ident, true\n\t}\n\n\tok := true\n\tident = expandMatcher.ReplaceAllStringFunc(ident, func(s string) string {\n\t\tswitch s {\n\t\tcase \"__\":\n\t\t\treturn \"__underscores__\"\n\t\tcase \".\":\n\t\t\treturn \"__dot__\"\n\t\tcase \"-\":\n\t\t\treturn \"__dash__\"\n\t\tcase \"/\":\n\t\t\treturn \"__slash__\"\n\t\tdefault: // matched a unsupported supported\n\t\t\tok = false\n\t\t\treturn \"\"\n\t\t}\n\t})\n\tif !ok {\n\t\treturn \"\", false\n\t}\n\treturn ident, true\n}","line":{"from":90,"to":136}} {"id":100017126,"name":"Unescape","signature":"func Unescape(escaped string) (string, bool)","file":"staging/src/k8s.io/apiserver/pkg/cel/escaping.go","code":"// Unescape unescapes an CEL identifier containing the escape sequences described in Escape, or return false if the\n// string contains invalid escape sequences. The escaped input is expected to be a valid CEL identifier, but is\n// not checked.\nfunc Unescape(escaped string) (string, bool) {\n\tok := true\n\tescaped = unexpandMatcher.ReplaceAllStringFunc(escaped, func(s string) string {\n\t\tcontents := s[2 : len(s)-2]\n\t\tswitch contents {\n\t\tcase \"underscores\":\n\t\t\treturn \"__\"\n\t\tcase \"dot\":\n\t\t\treturn \".\"\n\t\tcase \"dash\":\n\t\t\treturn \"-\"\n\t\tcase \"slash\":\n\t\t\treturn \"/\"\n\t\t}\n\t\tif celReservedSymbols.Has(contents) {\n\t\t\tif len(s) != len(escaped) {\n\t\t\t\tok = false\n\t\t\t}\n\t\t\treturn contents\n\t\t}\n\t\tok = false\n\t\treturn \"\"\n\t})\n\tif !ok {\n\t\treturn \"\", false\n\t}\n\treturn escaped, true\n}","line":{"from":140,"to":170}} {"id":100017127,"name":"Authz","signature":"func Authz() cel.EnvOption","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"// Authz provides a CEL function library extension for performing authorization checks.\n// Note that authorization checks are only supported for CEL expression fields in the API\n// where an 'authorizer' variable is provided to the CEL expression. See the\n// documentation of API fields where CEL expressions are used to learn if the 'authorizer'\n// variable is provided.\n//\n// path\n//\n// Returns a PathCheck configured to check authorization for a non-resource request\n// path (e.g. /healthz). If path is an empty string, an error is returned.\n// Note that the leading '/' is not required.\n//\n//\t\u003cAuthorizer\u003e.path(\u003cstring\u003e) \u003cPathCheck\u003e\n//\n// Examples:\n//\n//\tauthorizer.path('/healthz') // returns a PathCheck for the '/healthz' API path\n//\tauthorizer.path('') // results in \"path must not be empty\" error\n//\tauthorizer.path(' ') // results in \"path must not be empty\" error\n//\n// group\n//\n// Returns a GroupCheck configured to check authorization for the API resources for\n// a particular API group.\n// Note that authorization checks are only supported for CEL expression fields in the API\n// where an 'authorizer' variable is provided to the CEL expression. Check the\n// documentation of API fields where CEL expressions are used to learn if the 'authorizer'\n// variable is provided.\n//\n//\t\u003cAuthorizer\u003e.group(\u003cstring\u003e) \u003cGroupCheck\u003e\n//\n// Examples:\n//\n//\tauthorizer.group('apps') // returns a GroupCheck for the 'apps' API group\n//\tauthorizer.group('') // returns a GroupCheck for the core API group\n//\tauthorizer.group('example.com') // returns a GroupCheck for the custom resources in the 'example.com' API group\n//\n// serviceAccount\n//\n// Returns an Authorizer configured to check authorization for the provided service account namespace and name.\n// If the name is not a valid DNS subdomain string (as defined by RFC 1123), an error is returned.\n// If the namespace is not a valid DNS label (as defined by RFC 1123), an error is returned.\n//\n//\t\u003cAuthorizer\u003e.serviceAccount(\u003cstring\u003e, \u003cstring\u003e) \u003cAuthorizer\u003e\n//\n// Examples:\n//\n//\tauthorizer.serviceAccount('default', 'myserviceaccount') // returns an Authorizer for the service account with namespace 'default' and name 'myserviceaccount'\n//\tauthorizer.serviceAccount('not@a#valid!namespace', 'validname') // returns an error\n//\tauthorizer.serviceAccount('valid.example.com', 'invalid@*name') // returns an error\n//\n// resource\n//\n// Returns a ResourceCheck configured to check authorization for a particular API resource.\n// Note that the provided resource string should be a lower case plural name of a Kubernetes API resource.\n//\n//\t\u003cGroupCheck\u003e.resource(\u003cstring\u003e) \u003cResourceCheck\u003e\n//\n// Examples:\n//\n//\tauthorizer.group('apps').resource('deployments') // returns a ResourceCheck for the 'deployments' resources in the 'apps' group.\n//\tauthorizer.group('').resource('pods') // returns a ResourceCheck for the 'pods' resources in the core group.\n//\tauthorizer.group('apps').resource('') // results in \"resource must not be empty\" error\n//\tauthorizer.group('apps').resource(' ') // results in \"resource must not be empty\" error\n//\n// subresource\n//\n// Returns a ResourceCheck configured to check authorization for a particular subresource of an API resource.\n// If subresource is set to \"\", the subresource field of this ResourceCheck is considered unset.\n//\n//\t\u003cResourceCheck\u003e.subresource(\u003cstring\u003e) \u003cResourceCheck\u003e\n//\n// Examples:\n//\n//\tauthorizer.group('').resource('pods').subresource('status') // returns a ResourceCheck the 'status' subresource of 'pods'\n//\tauthorizer.group('apps').resource('deployments').subresource('scale') // returns a ResourceCheck the 'scale' subresource of 'deployments'\n//\tauthorizer.group('example.com').resource('widgets').subresource('scale') // returns a ResourceCheck for the 'scale' subresource of the 'widgets' custom resource\n//\tauthorizer.group('example.com').resource('widgets').subresource('') // returns a ResourceCheck for the 'widgets' resource.\n//\n// namespace\n//\n// Returns a ResourceCheck configured to check authorization for a particular namespace.\n// For cluster scoped resources, namespace() does not need to be called; namespace defaults\n// to \"\", which is the correct namespace value to use to check cluster scoped resources.\n// If namespace is set to \"\", the ResourceCheck will check authorization for the cluster scope.\n//\n//\t\u003cResourceCheck\u003e.namespace(\u003cstring\u003e) \u003cResourceCheck\u003e\n//\n// Examples:\n//\n//\tauthorizer.group('apps').resource('deployments').namespace('test') // returns a ResourceCheck for 'deployments' in the 'test' namespace\n//\tauthorizer.group('').resource('pods').namespace('default') // returns a ResourceCheck for 'pods' in the 'default' namespace\n//\tauthorizer.group('').resource('widgets').namespace('') // returns a ResourceCheck for 'widgets' in the cluster scope\n//\n// name\n//\n// Returns a ResourceCheck configured to check authorization for a particular resource name.\n// If name is set to \"\", the name field of this ResourceCheck is considered unset.\n//\n//\t\u003cResourceCheck\u003e.name(\u003cname\u003e) \u003cResourceCheck\u003e\n//\n// Examples:\n//\n//\tauthorizer.group('apps').resource('deployments').namespace('test').name('backend') // returns a ResourceCheck for the 'backend' 'deployments' resource in the 'test' namespace\n//\tauthorizer.group('apps').resource('deployments').namespace('test').name('') // returns a ResourceCheck for the 'deployments' resource in the 'test' namespace\n//\n// check\n//\n// For PathCheck, checks if the principal (user or service account) that sent the request is authorized for the HTTP request verb of the path.\n// For ResourceCheck, checks if the principal (user or service account) that sent the request is authorized for the API verb and the configured authorization checks of the ResourceCheck.\n// The check operation can be expensive, particularly in clusters using the webhook authorization mode.\n//\n//\t\u003cPathCheck\u003e.check(\u003ccheck\u003e) \u003cDecision\u003e\n//\t\u003cResourceCheck\u003e.check(\u003ccheck\u003e) \u003cDecision\u003e\n//\n// Examples:\n//\n//\tauthorizer.group('').resource('pods').namespace('default').check('create') // Checks if the principal (user or service account) is authorized create pods in the 'default' namespace.\n//\tauthorizer.path('/healthz').check('get') // Checks if the principal (user or service account) is authorized to make HTTP GET requests to the /healthz API path.\n//\n// allowed\n//\n// Returns true if the authorizer's decision for the check is \"allow\". Note that if the authorizer's decision is\n// \"no opinion\", that the 'allowed' function will return false.\n//\n//\t\u003cDecision\u003e.allowed() \u003cbool\u003e\n//\n// Examples:\n//\n//\tauthorizer.group('').resource('pods').namespace('default').check('create').allowed() // Returns true if the principal (user or service account) is allowed create pods in the 'default' namespace.\n//\tauthorizer.path('/healthz').check('get').allowed() // Returns true if the principal (user or service account) is allowed to make HTTP GET requests to the /healthz API path.\n//\n// reason\n//\n// Returns a string reason for the authorization decision\n//\n//\t\u003cDecision\u003e.reason() \u003cstring\u003e\n//\n// Examples:\n//\n//\tauthorizer.path('/healthz').check('GET').reason()\nfunc Authz() cel.EnvOption {\n\treturn cel.Lib(authzLib)\n}","line":{"from":36,"to":179}} {"id":100017128,"name":"CompileOptions","signature":"func (*authz) CompileOptions() []cel.EnvOption","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"func (*authz) CompileOptions() []cel.EnvOption {\n\toptions := make([]cel.EnvOption, 0, len(authzLibraryDecls))\n\tfor name, overloads := range authzLibraryDecls {\n\t\toptions = append(options, cel.Function(name, overloads...))\n\t}\n\treturn options\n}","line":{"from":220,"to":226}} {"id":100017129,"name":"ProgramOptions","signature":"func (*authz) ProgramOptions() []cel.ProgramOption","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"func (*authz) ProgramOptions() []cel.ProgramOption {\n\treturn []cel.ProgramOption{}\n}","line":{"from":228,"to":230}} {"id":100017130,"name":"authorizerPath","signature":"func authorizerPath(arg1, arg2 ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"func authorizerPath(arg1, arg2 ref.Val) ref.Val {\n\tauthz, ok := arg1.(authorizerVal)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(arg1)\n\t}\n\n\tpath, ok := arg2.Value().(string)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(arg1)\n\t}\n\n\tif len(strings.TrimSpace(path)) == 0 {\n\t\treturn types.NewErr(\"path must not be empty\")\n\t}\n\n\treturn authz.pathCheck(path)\n}","line":{"from":232,"to":248}} {"id":100017131,"name":"authorizerGroup","signature":"func authorizerGroup(arg1, arg2 ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"func authorizerGroup(arg1, arg2 ref.Val) ref.Val {\n\tauthz, ok := arg1.(authorizerVal)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(arg1)\n\t}\n\n\tgroup, ok := arg2.Value().(string)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(arg1)\n\t}\n\n\treturn authz.groupCheck(group)\n}","line":{"from":250,"to":262}} {"id":100017132,"name":"authorizerServiceAccount","signature":"func authorizerServiceAccount(args ...ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"func authorizerServiceAccount(args ...ref.Val) ref.Val {\n\targn := len(args)\n\tif argn != 3 {\n\t\treturn types.NoSuchOverloadErr()\n\t}\n\n\tauthz, ok := args[0].(authorizerVal)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(args[0])\n\t}\n\n\tnamespace, ok := args[1].Value().(string)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(args[1])\n\t}\n\n\tname, ok := args[2].Value().(string)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(args[2])\n\t}\n\n\tif errors := apimachineryvalidation.ValidateServiceAccountName(name, false); len(errors) \u003e 0 {\n\t\treturn types.NewErr(\"Invalid service account name\")\n\t}\n\tif errors := apimachineryvalidation.ValidateNamespaceName(namespace, false); len(errors) \u003e 0 {\n\t\treturn types.NewErr(\"Invalid service account namespace\")\n\t}\n\treturn authz.serviceAccount(namespace, name)\n}","line":{"from":264,"to":292}} {"id":100017133,"name":"groupCheckResource","signature":"func groupCheckResource(arg1, arg2 ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"func groupCheckResource(arg1, arg2 ref.Val) ref.Val {\n\tgroupCheck, ok := arg1.(groupCheckVal)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(arg1)\n\t}\n\n\tresource, ok := arg2.Value().(string)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(arg1)\n\t}\n\n\tif len(strings.TrimSpace(resource)) == 0 {\n\t\treturn types.NewErr(\"resource must not be empty\")\n\t}\n\treturn groupCheck.resourceCheck(resource)\n}","line":{"from":294,"to":309}} {"id":100017134,"name":"resourceCheckSubresource","signature":"func resourceCheckSubresource(arg1, arg2 ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"func resourceCheckSubresource(arg1, arg2 ref.Val) ref.Val {\n\tresourceCheck, ok := arg1.(resourceCheckVal)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(arg1)\n\t}\n\n\tsubresource, ok := arg2.Value().(string)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(arg1)\n\t}\n\n\tresult := resourceCheck\n\tresult.subresource = subresource\n\treturn result\n}","line":{"from":311,"to":325}} {"id":100017135,"name":"resourceCheckNamespace","signature":"func resourceCheckNamespace(arg1, arg2 ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"func resourceCheckNamespace(arg1, arg2 ref.Val) ref.Val {\n\tresourceCheck, ok := arg1.(resourceCheckVal)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(arg1)\n\t}\n\n\tnamespace, ok := arg2.Value().(string)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(arg1)\n\t}\n\n\tresult := resourceCheck\n\tresult.namespace = namespace\n\treturn result\n}","line":{"from":327,"to":341}} {"id":100017136,"name":"resourceCheckName","signature":"func resourceCheckName(arg1, arg2 ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"func resourceCheckName(arg1, arg2 ref.Val) ref.Val {\n\tresourceCheck, ok := arg1.(resourceCheckVal)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(arg1)\n\t}\n\n\tname, ok := arg2.Value().(string)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(arg1)\n\t}\n\n\tresult := resourceCheck\n\tresult.name = name\n\treturn result\n}","line":{"from":343,"to":357}} {"id":100017137,"name":"pathCheckCheck","signature":"func pathCheckCheck(arg1, arg2 ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"func pathCheckCheck(arg1, arg2 ref.Val) ref.Val {\n\tpathCheck, ok := arg1.(pathCheckVal)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(arg1)\n\t}\n\n\thttpRequestVerb, ok := arg2.Value().(string)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(arg1)\n\t}\n\n\treturn pathCheck.Authorize(context.TODO(), httpRequestVerb)\n}","line":{"from":359,"to":371}} {"id":100017138,"name":"resourceCheckCheck","signature":"func resourceCheckCheck(arg1, arg2 ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"func resourceCheckCheck(arg1, arg2 ref.Val) ref.Val {\n\tresourceCheck, ok := arg1.(resourceCheckVal)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(arg1)\n\t}\n\n\tapiVerb, ok := arg2.Value().(string)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(arg1)\n\t}\n\n\treturn resourceCheck.Authorize(context.TODO(), apiVerb)\n}","line":{"from":373,"to":385}} {"id":100017139,"name":"decisionAllowed","signature":"func decisionAllowed(arg ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"func decisionAllowed(arg ref.Val) ref.Val {\n\tdecision, ok := arg.(decisionVal)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(arg)\n\t}\n\n\treturn types.Bool(decision.authDecision == authorizer.DecisionAllow)\n}","line":{"from":387,"to":394}} {"id":100017140,"name":"decisionReason","signature":"func decisionReason(arg ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"func decisionReason(arg ref.Val) ref.Val {\n\tdecision, ok := arg.(decisionVal)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(arg)\n\t}\n\n\treturn types.String(decision.reason)\n}","line":{"from":396,"to":403}} {"id":100017141,"name":"NewAuthorizerVal","signature":"func NewAuthorizerVal(userInfo user.Info, authorizer authorizer.Authorizer) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"func NewAuthorizerVal(userInfo user.Info, authorizer authorizer.Authorizer) ref.Val {\n\treturn authorizerVal{receiverOnlyObjectVal: receiverOnlyVal(AuthorizerType), userInfo: userInfo, authAuthorizer: authorizer}\n}","line":{"from":429,"to":431}} {"id":100017142,"name":"NewResourceAuthorizerVal","signature":"func NewResourceAuthorizerVal(userInfo user.Info, authorizer authorizer.Authorizer, requestResource Resource) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"func NewResourceAuthorizerVal(userInfo user.Info, authorizer authorizer.Authorizer, requestResource Resource) ref.Val {\n\ta := authorizerVal{receiverOnlyObjectVal: receiverOnlyVal(AuthorizerType), userInfo: userInfo, authAuthorizer: authorizer}\n\tresource := requestResource.GetResource()\n\tg := a.groupCheck(resource.Group)\n\tr := g.resourceCheck(resource.Resource)\n\tr.subresource = requestResource.GetSubresource()\n\tr.namespace = requestResource.GetNamespace()\n\tr.name = requestResource.GetName()\n\treturn r\n}","line":{"from":433,"to":442}} {"id":100017143,"name":"pathCheck","signature":"func (a authorizerVal) pathCheck(path string) pathCheckVal","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"func (a authorizerVal) pathCheck(path string) pathCheckVal {\n\treturn pathCheckVal{receiverOnlyObjectVal: receiverOnlyVal(PathCheckType), authorizer: a, path: path}\n}","line":{"from":450,"to":452}} {"id":100017144,"name":"groupCheck","signature":"func (a authorizerVal) groupCheck(group string) groupCheckVal","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"func (a authorizerVal) groupCheck(group string) groupCheckVal {\n\treturn groupCheckVal{receiverOnlyObjectVal: receiverOnlyVal(GroupCheckType), authorizer: a, group: group}\n}","line":{"from":454,"to":456}} {"id":100017145,"name":"serviceAccount","signature":"func (a authorizerVal) serviceAccount(namespace, name string) authorizerVal","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"func (a authorizerVal) serviceAccount(namespace, name string) authorizerVal {\n\tsa := \u0026serviceaccount.ServiceAccountInfo{Name: name, Namespace: namespace}\n\treturn authorizerVal{\n\t\treceiverOnlyObjectVal: receiverOnlyVal(AuthorizerType),\n\t\tuserInfo: sa.UserInfo(),\n\t\tauthAuthorizer: a.authAuthorizer,\n\t}\n}","line":{"from":458,"to":465}} {"id":100017146,"name":"Authorize","signature":"func (a pathCheckVal) Authorize(ctx context.Context, verb string) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"func (a pathCheckVal) Authorize(ctx context.Context, verb string) ref.Val {\n\tattr := \u0026authorizer.AttributesRecord{\n\t\tPath: a.path,\n\t\tVerb: verb,\n\t\tUser: a.authorizer.userInfo,\n\t}\n\n\tdecision, reason, err := a.authorizer.authAuthorizer.Authorize(ctx, attr)\n\tif err != nil {\n\t\treturn types.NewErr(\"error in authorization check: %v\", err)\n\t}\n\treturn newDecision(decision, reason)\n}","line":{"from":473,"to":485}} {"id":100017147,"name":"resourceCheck","signature":"func (g groupCheckVal) resourceCheck(resource string) resourceCheckVal","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"func (g groupCheckVal) resourceCheck(resource string) resourceCheckVal {\n\treturn resourceCheckVal{receiverOnlyObjectVal: receiverOnlyVal(ResourceCheckType), groupCheck: g, resource: resource}\n}","line":{"from":493,"to":495}} {"id":100017148,"name":"Authorize","signature":"func (a resourceCheckVal) Authorize(ctx context.Context, verb string) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"func (a resourceCheckVal) Authorize(ctx context.Context, verb string) ref.Val {\n\tattr := \u0026authorizer.AttributesRecord{\n\t\tResourceRequest: true,\n\t\tAPIGroup: a.groupCheck.group,\n\t\tAPIVersion: \"*\",\n\t\tResource: a.resource,\n\t\tSubresource: a.subresource,\n\t\tNamespace: a.namespace,\n\t\tName: a.name,\n\t\tVerb: verb,\n\t\tUser: a.groupCheck.authorizer.userInfo,\n\t}\n\tdecision, reason, err := a.groupCheck.authorizer.authAuthorizer.Authorize(ctx, attr)\n\tif err != nil {\n\t\treturn types.NewErr(\"error in authorization check: %v\", err)\n\t}\n\treturn newDecision(decision, reason)\n}","line":{"from":506,"to":523}} {"id":100017149,"name":"newDecision","signature":"func newDecision(authDecision authorizer.Decision, reason string) decisionVal","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"func newDecision(authDecision authorizer.Decision, reason string) decisionVal {\n\treturn decisionVal{receiverOnlyObjectVal: receiverOnlyVal(DecisionType), authDecision: authDecision, reason: reason}\n}","line":{"from":525,"to":527}} {"id":100017150,"name":"receiverOnlyVal","signature":"func receiverOnlyVal(objectType *cel.Type) receiverOnlyObjectVal","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"// receiverOnlyVal returns a receiverOnlyObjectVal for the given type.\nfunc receiverOnlyVal(objectType *cel.Type) receiverOnlyObjectVal {\n\treturn receiverOnlyObjectVal{typeValue: types.NewTypeValue(objectType.String())}\n}","line":{"from":542,"to":545}} {"id":100017151,"name":"ConvertToNative","signature":"func (a receiverOnlyObjectVal) ConvertToNative(typeDesc reflect.Type) (any, error)","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"// ConvertToNative implements ref.Val.ConvertToNative.\nfunc (a receiverOnlyObjectVal) ConvertToNative(typeDesc reflect.Type) (any, error) {\n\treturn nil, fmt.Errorf(\"type conversion error from '%s' to '%v'\", a.typeValue.String(), typeDesc)\n}","line":{"from":547,"to":550}} {"id":100017152,"name":"ConvertToType","signature":"func (a receiverOnlyObjectVal) ConvertToType(typeVal ref.Type) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"// ConvertToType implements ref.Val.ConvertToType.\nfunc (a receiverOnlyObjectVal) ConvertToType(typeVal ref.Type) ref.Val {\n\tswitch typeVal {\n\tcase a.typeValue:\n\t\treturn a\n\tcase types.TypeType:\n\t\treturn a.typeValue\n\t}\n\treturn types.NewErr(\"type conversion error from '%s' to '%s'\", a.typeValue, typeVal)\n}","line":{"from":552,"to":561}} {"id":100017153,"name":"Equal","signature":"func (a receiverOnlyObjectVal) Equal(other ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"// Equal implements ref.Val.Equal.\nfunc (a receiverOnlyObjectVal) Equal(other ref.Val) ref.Val {\n\to, ok := other.(receiverOnlyObjectVal)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(other)\n\t}\n\treturn types.Bool(a == o)\n}","line":{"from":563,"to":570}} {"id":100017154,"name":"Type","signature":"func (a receiverOnlyObjectVal) Type() ref.Type","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"// Type implements ref.Val.Type.\nfunc (a receiverOnlyObjectVal) Type() ref.Type {\n\treturn a.typeValue\n}","line":{"from":572,"to":575}} {"id":100017155,"name":"Value","signature":"func (a receiverOnlyObjectVal) Value() any","file":"staging/src/k8s.io/apiserver/pkg/cel/library/authz.go","code":"// Value implements ref.Val.Value.\nfunc (a receiverOnlyObjectVal) Value() any {\n\treturn types.NoSuchOverloadErr()\n}","line":{"from":577,"to":580}} {"id":100017156,"name":"CallCost","signature":"func (l *CostEstimator) CallCost(function, overloadId string, args []ref.Val, result ref.Val) *uint64","file":"staging/src/k8s.io/apiserver/pkg/cel/library/cost.go","code":"func (l *CostEstimator) CallCost(function, overloadId string, args []ref.Val, result ref.Val) *uint64 {\n\tswitch function {\n\tcase \"check\":\n\t\t// An authorization check has a fixed cost\n\t\t// This cost is set to allow for only two authorization checks per expression\n\t\tcost := uint64(350000)\n\t\treturn \u0026cost\n\tcase \"serviceAccount\", \"path\", \"group\", \"resource\", \"subresource\", \"namespace\", \"name\", \"allowed\", \"denied\", \"reason\":\n\t\t// All authorization builder and accessor functions have a nominal cost\n\t\tcost := uint64(1)\n\t\treturn \u0026cost\n\tcase \"isSorted\", \"sum\", \"max\", \"min\", \"indexOf\", \"lastIndexOf\":\n\t\tvar cost uint64\n\t\tif len(args) \u003e 0 {\n\t\t\tcost += traversalCost(args[0]) // these O(n) operations all cost roughly the cost of a single traversal\n\t\t}\n\t\treturn \u0026cost\n\tcase \"url\", \"lowerAscii\", \"upperAscii\", \"substring\", \"trim\":\n\t\tif len(args) \u003e= 1 {\n\t\t\tcost := uint64(math.Ceil(float64(actualSize(args[0])) * common.StringTraversalCostFactor))\n\t\t\treturn \u0026cost\n\t\t}\n\tcase \"replace\", \"split\":\n\t\tif len(args) \u003e= 1 {\n\t\t\t// cost is the traversal plus the construction of the result\n\t\t\tcost := uint64(math.Ceil(float64(actualSize(args[0])) * 2 * common.StringTraversalCostFactor))\n\t\t\treturn \u0026cost\n\t\t}\n\tcase \"join\":\n\t\tif len(args) \u003e= 1 {\n\t\t\tcost := uint64(math.Ceil(float64(actualSize(result)) * 2 * common.StringTraversalCostFactor))\n\t\t\treturn \u0026cost\n\t\t}\n\tcase \"find\", \"findAll\":\n\t\tif len(args) \u003e= 2 {\n\t\t\tstrCost := uint64(math.Ceil((1.0 + float64(actualSize(args[0]))) * common.StringTraversalCostFactor))\n\t\t\t// We don't know how many expressions are in the regex, just the string length (a huge\n\t\t\t// improvement here would be to somehow get a count the number of expressions in the regex or\n\t\t\t// how many states are in the regex state machine and use that to measure regex cost).\n\t\t\t// For now, we're making a guess that each expression in a regex is typically at least 4 chars\n\t\t\t// in length.\n\t\t\tregexCost := uint64(math.Ceil(float64(actualSize(args[1])) * common.RegexStringLengthCostFactor))\n\t\t\tcost := strCost * regexCost\n\t\t\treturn \u0026cost\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":37,"to":84}} {"id":100017157,"name":"EstimateCallCost","signature":"func (l *CostEstimator) EstimateCallCost(function, overloadId string, target *checker.AstNode, args []checker.AstNode) *checker.CallEstimate","file":"staging/src/k8s.io/apiserver/pkg/cel/library/cost.go","code":"func (l *CostEstimator) EstimateCallCost(function, overloadId string, target *checker.AstNode, args []checker.AstNode) *checker.CallEstimate {\n\t// WARNING: Any changes to this code impact API compatibility! The estimated cost is used to determine which CEL rules may be written to a\n\t// CRD and any change (cost increases and cost decreases) are breaking.\n\tswitch function {\n\tcase \"check\":\n\t\t// An authorization check has a fixed cost\n\t\t// This cost is set to allow for only two authorization checks per expression\n\t\treturn \u0026checker.CallEstimate{CostEstimate: checker.CostEstimate{Min: 350000, Max: 350000}}\n\tcase \"serviceAccount\", \"path\", \"group\", \"resource\", \"subresource\", \"namespace\", \"name\", \"allowed\", \"denied\", \"reason\":\n\t\t// All authorization builder and accessor functions have a nominal cost\n\t\treturn \u0026checker.CallEstimate{CostEstimate: checker.CostEstimate{Min: 1, Max: 1}}\n\tcase \"isSorted\", \"sum\", \"max\", \"min\", \"indexOf\", \"lastIndexOf\":\n\t\tif target != nil {\n\t\t\t// Charge 1 cost for comparing each element in the list\n\t\t\telCost := checker.CostEstimate{Min: 1, Max: 1}\n\t\t\t// If the list contains strings or bytes, add the cost of traversing all the strings/bytes as a way\n\t\t\t// of estimating the additional comparison cost.\n\t\t\tif elNode := l.listElementNode(*target); elNode != nil {\n\t\t\t\tt := elNode.Type().GetPrimitive()\n\t\t\t\tif t == exprpb.Type_STRING || t == exprpb.Type_BYTES {\n\t\t\t\t\tsz := l.sizeEstimate(elNode)\n\t\t\t\t\telCost = elCost.Add(sz.MultiplyByCostFactor(common.StringTraversalCostFactor))\n\t\t\t\t}\n\t\t\t\treturn \u0026checker.CallEstimate{CostEstimate: l.sizeEstimate(*target).MultiplyByCost(elCost)}\n\t\t\t} else { // the target is a string, which is supported by indexOf and lastIndexOf\n\t\t\t\treturn \u0026checker.CallEstimate{CostEstimate: l.sizeEstimate(*target).MultiplyByCostFactor(common.StringTraversalCostFactor)}\n\t\t\t}\n\t\t}\n\tcase \"url\":\n\t\tif len(args) == 1 {\n\t\t\tsz := l.sizeEstimate(args[0])\n\t\t\treturn \u0026checker.CallEstimate{CostEstimate: sz.MultiplyByCostFactor(common.StringTraversalCostFactor)}\n\t\t}\n\tcase \"lowerAscii\", \"upperAscii\", \"substring\", \"trim\":\n\t\tif target != nil {\n\t\t\tsz := l.sizeEstimate(*target)\n\t\t\treturn \u0026checker.CallEstimate{CostEstimate: sz.MultiplyByCostFactor(common.StringTraversalCostFactor), ResultSize: \u0026sz}\n\t\t}\n\tcase \"replace\":\n\t\tif target != nil \u0026\u0026 len(args) \u003e= 2 {\n\t\t\tsz := l.sizeEstimate(*target)\n\t\t\ttoReplaceSz := l.sizeEstimate(args[0])\n\t\t\treplaceWithSz := l.sizeEstimate(args[1])\n\t\t\t// smallest possible result: smallest input size composed of the largest possible substrings being replaced by smallest possible replacement\n\t\t\tminSz := uint64(math.Ceil(float64(sz.Min)/float64(toReplaceSz.Max))) * replaceWithSz.Min\n\t\t\t// largest possible result: largest input size composed of the smallest possible substrings being replaced by largest possible replacement\n\t\t\tmaxSz := uint64(math.Ceil(float64(sz.Max)/float64(toReplaceSz.Min))) * replaceWithSz.Max\n\n\t\t\t// cost is the traversal plus the construction of the result\n\t\t\treturn \u0026checker.CallEstimate{CostEstimate: sz.MultiplyByCostFactor(2 * common.StringTraversalCostFactor), ResultSize: \u0026checker.SizeEstimate{Min: minSz, Max: maxSz}}\n\t\t}\n\tcase \"split\":\n\t\tif target != nil {\n\t\t\tsz := l.sizeEstimate(*target)\n\n\t\t\t// Worst case size is where is that a separator of \"\" is used, and each char is returned as a list element.\n\t\t\tmax := sz.Max\n\t\t\tif len(args) \u003e 1 {\n\t\t\t\tif c := args[1].Expr().GetConstExpr(); c != nil {\n\t\t\t\t\tmax = uint64(c.GetInt64Value())\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Cost is the traversal plus the construction of the result.\n\t\t\treturn \u0026checker.CallEstimate{CostEstimate: sz.MultiplyByCostFactor(2 * common.StringTraversalCostFactor), ResultSize: \u0026checker.SizeEstimate{Min: 0, Max: max}}\n\t\t}\n\tcase \"join\":\n\t\tif target != nil {\n\t\t\tvar sz checker.SizeEstimate\n\t\t\tlistSize := l.sizeEstimate(*target)\n\t\t\tif elNode := l.listElementNode(*target); elNode != nil {\n\t\t\t\telemSize := l.sizeEstimate(elNode)\n\t\t\t\tsz = listSize.Multiply(elemSize)\n\t\t\t}\n\n\t\t\tif len(args) \u003e 0 {\n\t\t\t\tsepSize := l.sizeEstimate(args[0])\n\t\t\t\tminSeparators := uint64(0)\n\t\t\t\tmaxSeparators := uint64(0)\n\t\t\t\tif listSize.Min \u003e 0 {\n\t\t\t\t\tminSeparators = listSize.Min - 1\n\t\t\t\t}\n\t\t\t\tif listSize.Max \u003e 0 {\n\t\t\t\t\tmaxSeparators = listSize.Max - 1\n\t\t\t\t}\n\t\t\t\tsz = sz.Add(sepSize.Multiply(checker.SizeEstimate{Min: minSeparators, Max: maxSeparators}))\n\t\t\t}\n\n\t\t\treturn \u0026checker.CallEstimate{CostEstimate: sz.MultiplyByCostFactor(common.StringTraversalCostFactor), ResultSize: \u0026sz}\n\t\t}\n\tcase \"find\", \"findAll\":\n\t\tif target != nil \u0026\u0026 len(args) \u003e= 1 {\n\t\t\tsz := l.sizeEstimate(*target)\n\t\t\t// Add one to string length for purposes of cost calculation to prevent product of string and regex to be 0\n\t\t\t// in case where string is empty but regex is still expensive.\n\t\t\tstrCost := sz.Add(checker.SizeEstimate{Min: 1, Max: 1}).MultiplyByCostFactor(common.StringTraversalCostFactor)\n\t\t\t// We don't know how many expressions are in the regex, just the string length (a huge\n\t\t\t// improvement here would be to somehow get a count the number of expressions in the regex or\n\t\t\t// how many states are in the regex state machine and use that to measure regex cost).\n\t\t\t// For now, we're making a guess that each expression in a regex is typically at least 4 chars\n\t\t\t// in length.\n\t\t\tregexCost := l.sizeEstimate(args[0]).MultiplyByCostFactor(common.RegexStringLengthCostFactor)\n\t\t\t// worst case size of result is that every char is returned as separate find result.\n\t\t\treturn \u0026checker.CallEstimate{CostEstimate: strCost.Multiply(regexCost), ResultSize: \u0026checker.SizeEstimate{Min: 0, Max: sz.Max}}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":86,"to":192}} {"id":100017158,"name":"actualSize","signature":"func actualSize(value ref.Val) uint64","file":"staging/src/k8s.io/apiserver/pkg/cel/library/cost.go","code":"func actualSize(value ref.Val) uint64 {\n\tif sz, ok := value.(traits.Sizer); ok {\n\t\treturn uint64(sz.Size().(types.Int))\n\t}\n\treturn 1\n}","line":{"from":194,"to":199}} {"id":100017159,"name":"sizeEstimate","signature":"func (l *CostEstimator) sizeEstimate(t checker.AstNode) checker.SizeEstimate","file":"staging/src/k8s.io/apiserver/pkg/cel/library/cost.go","code":"func (l *CostEstimator) sizeEstimate(t checker.AstNode) checker.SizeEstimate {\n\tif sz := t.ComputedSize(); sz != nil {\n\t\treturn *sz\n\t}\n\tif sz := l.EstimateSize(t); sz != nil {\n\t\treturn *sz\n\t}\n\treturn checker.SizeEstimate{Min: 0, Max: math.MaxUint64}\n}","line":{"from":201,"to":209}} {"id":100017160,"name":"listElementNode","signature":"func (l *CostEstimator) listElementNode(list checker.AstNode) checker.AstNode","file":"staging/src/k8s.io/apiserver/pkg/cel/library/cost.go","code":"func (l *CostEstimator) listElementNode(list checker.AstNode) checker.AstNode {\n\tif lt := list.Type().GetListType(); lt != nil {\n\t\tnodePath := list.Path()\n\t\tif nodePath != nil {\n\t\t\t// Provide path if we have it so that a OpenAPIv3 maxLength validation can be looked up, if it exists\n\t\t\t// for this node.\n\t\t\tpath := make([]string, len(nodePath)+1)\n\t\t\tcopy(path, nodePath)\n\t\t\tpath[len(nodePath)] = \"@items\"\n\t\t\treturn \u0026itemsNode{path: path, t: lt.GetElemType(), expr: nil}\n\t\t} else {\n\t\t\t// Provide just the type if no path is available so that worst case size can be looked up based on type.\n\t\t\treturn \u0026itemsNode{t: lt.GetElemType(), expr: nil}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":211,"to":227}} {"id":100017161,"name":"EstimateSize","signature":"func (l *CostEstimator) EstimateSize(element checker.AstNode) *checker.SizeEstimate","file":"staging/src/k8s.io/apiserver/pkg/cel/library/cost.go","code":"func (l *CostEstimator) EstimateSize(element checker.AstNode) *checker.SizeEstimate {\n\tif l.SizeEstimator != nil {\n\t\treturn l.SizeEstimator.EstimateSize(element)\n\t}\n\treturn nil\n}","line":{"from":229,"to":234}} {"id":100017162,"name":"Path","signature":"func (i *itemsNode) Path() []string","file":"staging/src/k8s.io/apiserver/pkg/cel/library/cost.go","code":"func (i *itemsNode) Path() []string {\n\treturn i.path\n}","line":{"from":242,"to":244}} {"id":100017163,"name":"Type","signature":"func (i *itemsNode) Type() *exprpb.Type","file":"staging/src/k8s.io/apiserver/pkg/cel/library/cost.go","code":"func (i *itemsNode) Type() *exprpb.Type {\n\treturn i.t\n}","line":{"from":246,"to":248}} {"id":100017164,"name":"Expr","signature":"func (i *itemsNode) Expr() *exprpb.Expr","file":"staging/src/k8s.io/apiserver/pkg/cel/library/cost.go","code":"func (i *itemsNode) Expr() *exprpb.Expr {\n\treturn i.expr\n}","line":{"from":250,"to":252}} {"id":100017165,"name":"ComputedSize","signature":"func (i *itemsNode) ComputedSize() *checker.SizeEstimate","file":"staging/src/k8s.io/apiserver/pkg/cel/library/cost.go","code":"func (i *itemsNode) ComputedSize() *checker.SizeEstimate {\n\treturn nil\n}","line":{"from":254,"to":256}} {"id":100017166,"name":"traversalCost","signature":"func traversalCost(v ref.Val) uint64","file":"staging/src/k8s.io/apiserver/pkg/cel/library/cost.go","code":"// traversalCost computes the cost of traversing a ref.Val as a data tree.\nfunc traversalCost(v ref.Val) uint64 {\n\t// TODO: This could potentially be optimized by sampling maps and lists instead of traversing.\n\tswitch vt := v.(type) {\n\tcase types.String:\n\t\treturn uint64(float64(len(string(vt))) * common.StringTraversalCostFactor)\n\tcase types.Bytes:\n\t\treturn uint64(float64(len([]byte(vt))) * common.StringTraversalCostFactor)\n\tcase traits.Lister:\n\t\tcost := uint64(0)\n\t\tfor it := vt.Iterator(); it.HasNext() == types.True; {\n\t\t\ti := it.Next()\n\t\t\tcost += traversalCost(i)\n\t\t}\n\t\treturn cost\n\tcase traits.Mapper: // maps and objects\n\t\tcost := uint64(0)\n\t\tfor it := vt.Iterator(); it.HasNext() == types.True; {\n\t\t\tk := it.Next()\n\t\t\tcost += traversalCost(k) + traversalCost(vt.Get(k))\n\t\t}\n\t\treturn cost\n\tdefault:\n\t\treturn 1\n\t}\n}","line":{"from":258,"to":283}} {"id":100017167,"name":"Lists","signature":"func Lists() cel.EnvOption","file":"staging/src/k8s.io/apiserver/pkg/cel/library/lists.go","code":"// Lists provides a CEL function library extension of list utility functions.\n//\n// isSorted\n//\n// Returns true if the provided list of comparable elements is sorted, else returns false.\n//\n//\t\u003clist\u003cT\u003e\u003e.isSorted() \u003cbool\u003e, T must be a comparable type\n//\n// Examples:\n//\n//\t[1, 2, 3].isSorted() // return true\n//\t['a', 'b', 'b', 'c'].isSorted() // return true\n//\t[2.0, 1.0].isSorted() // return false\n//\t[1].isSorted() // return true\n//\t[].isSorted() // return true\n//\n// sum\n//\n// Returns the sum of the elements of the provided list. Supports CEL number (int, uint, double) and duration types.\n//\n//\t\u003clist\u003cT\u003e\u003e.sum() \u003cT\u003e, T must be a numeric type or a duration\n//\n// Examples:\n//\n//\t[1, 3].sum() // returns 4\n//\t[1.0, 3.0].sum() // returns 4.0\n//\t['1m', '1s'].sum() // returns '1m1s'\n//\temptyIntList.sum() // returns 0\n//\temptyDoubleList.sum() // returns 0.0\n//\t[].sum() // returns 0\n//\n// min / max\n//\n// Returns the minimum/maximum valued element of the provided list. Supports all comparable types.\n// If the list is empty, an error is returned.\n//\n//\t\u003clist\u003cT\u003e\u003e.min() \u003cT\u003e, T must be a comparable type\n//\t\u003clist\u003cT\u003e\u003e.max() \u003cT\u003e, T must be a comparable type\n//\n// Examples:\n//\n//\t[1, 3].min() // returns 1\n//\t[1, 3].max() // returns 3\n//\t[].min() // error\n//\t[1].min() // returns 1\n//\t([0] + emptyList).min() // returns 0\n//\n// indexOf / lastIndexOf\n//\n// Returns either the first or last positional index of the provided element in the list.\n// If the element is not found, -1 is returned. Supports all equatable types.\n//\n//\t\u003clist\u003cT\u003e\u003e.indexOf(\u003cT\u003e) \u003cint\u003e, T must be an equatable type\n//\t\u003clist\u003cT\u003e\u003e.lastIndexOf(\u003cT\u003e) \u003cint\u003e, T must be an equatable type\n//\n// Examples:\n//\n//\t[1, 2, 2, 3].indexOf(2) // returns 1\n//\t['a', 'b', 'b', 'c'].lastIndexOf('b') // returns 2\n//\t[1.0].indexOf(1.1) // returns -1\n//\t[].indexOf('string') // returns -1\nfunc Lists() cel.EnvOption {\n\treturn cel.Lib(listsLib)\n}","line":{"from":29,"to":92}} {"id":100017168,"name":"CompileOptions","signature":"func (*lists) CompileOptions() []cel.EnvOption","file":"staging/src/k8s.io/apiserver/pkg/cel/library/lists.go","code":"func (*lists) CompileOptions() []cel.EnvOption {\n\toptions := []cel.EnvOption{}\n\tfor name, overloads := range listsLibraryDecls {\n\t\toptions = append(options, cel.Function(name, overloads...))\n\t}\n\treturn options\n}","line":{"from":166,"to":172}} {"id":100017169,"name":"ProgramOptions","signature":"func (*lists) ProgramOptions() []cel.ProgramOption","file":"staging/src/k8s.io/apiserver/pkg/cel/library/lists.go","code":"func (*lists) ProgramOptions() []cel.ProgramOption {\n\treturn []cel.ProgramOption{}\n}","line":{"from":174,"to":176}} {"id":100017170,"name":"isSorted","signature":"func isSorted(val ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/lists.go","code":"func isSorted(val ref.Val) ref.Val {\n\tvar prev traits.Comparer\n\titerable, ok := val.(traits.Iterable)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(val)\n\t}\n\tfor it := iterable.Iterator(); it.HasNext() == types.True; {\n\t\tnext := it.Next()\n\t\tnextCmp, ok := next.(traits.Comparer)\n\t\tif !ok {\n\t\t\treturn types.MaybeNoSuchOverloadErr(next)\n\t\t}\n\t\tif prev != nil {\n\t\t\tcmp := prev.Compare(next)\n\t\t\tif cmp == types.IntOne {\n\t\t\t\treturn types.False\n\t\t\t}\n\t\t}\n\t\tprev = nextCmp\n\t}\n\treturn types.True\n}","line":{"from":178,"to":199}} {"id":100017171,"name":"sum","signature":"func sum(init func() ref.Val) functions.UnaryOp","file":"staging/src/k8s.io/apiserver/pkg/cel/library/lists.go","code":"func sum(init func() ref.Val) functions.UnaryOp {\n\treturn func(val ref.Val) ref.Val {\n\t\ti := init()\n\t\tacc, ok := i.(traits.Adder)\n\t\tif !ok {\n\t\t\t// Should never happen since all passed in init values are valid\n\t\t\treturn types.MaybeNoSuchOverloadErr(i)\n\t\t}\n\t\titerable, ok := val.(traits.Iterable)\n\t\tif !ok {\n\t\t\treturn types.MaybeNoSuchOverloadErr(val)\n\t\t}\n\t\tfor it := iterable.Iterator(); it.HasNext() == types.True; {\n\t\t\tnext := it.Next()\n\t\t\tnextAdder, ok := next.(traits.Adder)\n\t\t\tif !ok {\n\t\t\t\t// Should never happen for type checked CEL programs\n\t\t\t\treturn types.MaybeNoSuchOverloadErr(next)\n\t\t\t}\n\t\t\tif acc != nil {\n\t\t\t\ts := acc.Add(next)\n\t\t\t\tsum, ok := s.(traits.Adder)\n\t\t\t\tif !ok {\n\t\t\t\t\t// Should never happen for type checked CEL programs\n\t\t\t\t\treturn types.MaybeNoSuchOverloadErr(s)\n\t\t\t\t}\n\t\t\t\tacc = sum\n\t\t\t} else {\n\t\t\t\tacc = nextAdder\n\t\t\t}\n\t\t}\n\t\treturn acc.(ref.Val)\n\t}\n}","line":{"from":201,"to":234}} {"id":100017172,"name":"min","signature":"func min() functions.UnaryOp","file":"staging/src/k8s.io/apiserver/pkg/cel/library/lists.go","code":"func min() functions.UnaryOp {\n\treturn cmp(\"min\", types.IntOne)\n}","line":{"from":236,"to":238}} {"id":100017173,"name":"max","signature":"func max() functions.UnaryOp","file":"staging/src/k8s.io/apiserver/pkg/cel/library/lists.go","code":"func max() functions.UnaryOp {\n\treturn cmp(\"max\", types.IntNegOne)\n}","line":{"from":240,"to":242}} {"id":100017174,"name":"cmp","signature":"func cmp(opName string, opPreferCmpResult ref.Val) functions.UnaryOp","file":"staging/src/k8s.io/apiserver/pkg/cel/library/lists.go","code":"func cmp(opName string, opPreferCmpResult ref.Val) functions.UnaryOp {\n\treturn func(val ref.Val) ref.Val {\n\t\tvar result traits.Comparer\n\t\titerable, ok := val.(traits.Iterable)\n\t\tif !ok {\n\t\t\treturn types.MaybeNoSuchOverloadErr(val)\n\t\t}\n\t\tfor it := iterable.Iterator(); it.HasNext() == types.True; {\n\t\t\tnext := it.Next()\n\t\t\tnextCmp, ok := next.(traits.Comparer)\n\t\t\tif !ok {\n\t\t\t\t// Should never happen for type checked CEL programs\n\t\t\t\treturn types.MaybeNoSuchOverloadErr(next)\n\t\t\t}\n\t\t\tif result == nil {\n\t\t\t\tresult = nextCmp\n\t\t\t} else {\n\t\t\t\tcmp := result.Compare(next)\n\t\t\t\tif cmp == opPreferCmpResult {\n\t\t\t\t\tresult = nextCmp\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif result == nil {\n\t\t\treturn types.NewErr(\"%s called on empty list\", opName)\n\t\t}\n\t\treturn result.(ref.Val)\n\t}\n}","line":{"from":244,"to":272}} {"id":100017175,"name":"indexOf","signature":"func indexOf(list ref.Val, item ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/lists.go","code":"func indexOf(list ref.Val, item ref.Val) ref.Val {\n\tlister, ok := list.(traits.Lister)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(list)\n\t}\n\tsz := lister.Size().(types.Int)\n\tfor i := types.Int(0); i \u003c sz; i++ {\n\t\tif lister.Get(types.Int(i)).Equal(item) == types.True {\n\t\t\treturn types.Int(i)\n\t\t}\n\t}\n\treturn types.Int(-1)\n}","line":{"from":274,"to":286}} {"id":100017176,"name":"lastIndexOf","signature":"func lastIndexOf(list ref.Val, item ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/lists.go","code":"func lastIndexOf(list ref.Val, item ref.Val) ref.Val {\n\tlister, ok := list.(traits.Lister)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(list)\n\t}\n\tsz := lister.Size().(types.Int)\n\tfor i := sz - 1; i \u003e= 0; i-- {\n\t\tif lister.Get(types.Int(i)).Equal(item) == types.True {\n\t\t\treturn types.Int(i)\n\t\t}\n\t}\n\treturn types.Int(-1)\n}","line":{"from":288,"to":300}} {"id":100017177,"name":"templatedOverloads","signature":"func templatedOverloads(types []namedCELType, template func(name string, t *cel.Type) cel.FunctionOpt) []cel.FunctionOpt","file":"staging/src/k8s.io/apiserver/pkg/cel/library/lists.go","code":"// templatedOverloads returns overloads for each of the provided types. The template function is called with each type\n// name (map key) and type to construct the overloads.\nfunc templatedOverloads(types []namedCELType, template func(name string, t *cel.Type) cel.FunctionOpt) []cel.FunctionOpt {\n\toverloads := make([]cel.FunctionOpt, len(types))\n\ti := 0\n\tfor _, t := range types {\n\t\toverloads[i] = template(t.typeName, t.celType)\n\t\ti++\n\t}\n\treturn overloads\n}","line":{"from":302,"to":312}} {"id":100017178,"name":"Regex","signature":"func Regex() cel.EnvOption","file":"staging/src/k8s.io/apiserver/pkg/cel/library/regex.go","code":"// Regex provides a CEL function library extension of regex utility functions.\n//\n// find / findAll\n//\n// Returns substrings that match the provided regular expression. find returns the first match. findAll may optionally\n// be provided a limit. If the limit is set and \u003e= 0, no more than the limit number of matches are returned.\n//\n//\t\u003cstring\u003e.find(\u003cstring\u003e) \u003cstring\u003e\n//\t\u003cstring\u003e.findAll(\u003cstring\u003e) \u003clist \u003cstring\u003e\u003e\n//\t\u003cstring\u003e.findAll(\u003cstring\u003e, \u003cint\u003e) \u003clist \u003cstring\u003e\u003e\n//\n// Examples:\n//\n//\t\"abc 123\".find('[0-9]*') // returns '123'\n//\t\"abc 123\".find('xyz') // returns ''\n//\t\"123 abc 456\".findAll('[0-9]*') // returns ['123', '456']\n//\t\"123 abc 456\".findAll('[0-9]*', 1) // returns ['123']\n//\t\"123 abc 456\".findAll('xyz') // returns []\nfunc Regex() cel.EnvOption {\n\treturn cel.Lib(regexLib)\n}","line":{"from":28,"to":48}} {"id":100017179,"name":"CompileOptions","signature":"func (*regex) CompileOptions() []cel.EnvOption","file":"staging/src/k8s.io/apiserver/pkg/cel/library/regex.go","code":"func (*regex) CompileOptions() []cel.EnvOption {\n\toptions := []cel.EnvOption{}\n\tfor name, overloads := range regexLibraryDecls {\n\t\toptions = append(options, cel.Function(name, overloads...))\n\t}\n\treturn options\n}","line":{"from":71,"to":77}} {"id":100017180,"name":"ProgramOptions","signature":"func (*regex) ProgramOptions() []cel.ProgramOption","file":"staging/src/k8s.io/apiserver/pkg/cel/library/regex.go","code":"func (*regex) ProgramOptions() []cel.ProgramOption {\n\treturn []cel.ProgramOption{}\n}","line":{"from":79,"to":81}} {"id":100017181,"name":"find","signature":"func find(strVal ref.Val, regexVal ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/regex.go","code":"func find(strVal ref.Val, regexVal ref.Val) ref.Val {\n\tstr, ok := strVal.Value().(string)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(strVal)\n\t}\n\tregex, ok := regexVal.Value().(string)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(regexVal)\n\t}\n\tre, err := regexp.Compile(regex)\n\tif err != nil {\n\t\treturn types.NewErr(\"Illegal regex: %v\", err.Error())\n\t}\n\tresult := re.FindString(str)\n\treturn types.String(result)\n}","line":{"from":83,"to":98}} {"id":100017182,"name":"findAll","signature":"func findAll(args ...ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/regex.go","code":"func findAll(args ...ref.Val) ref.Val {\n\targn := len(args)\n\tif argn \u003c 2 || argn \u003e 3 {\n\t\treturn types.NoSuchOverloadErr()\n\t}\n\tstr, ok := args[0].Value().(string)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(args[0])\n\t}\n\tregex, ok := args[1].Value().(string)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(args[1])\n\t}\n\tn := int64(-1)\n\tif argn == 3 {\n\t\tn, ok = args[2].Value().(int64)\n\t\tif !ok {\n\t\t\treturn types.MaybeNoSuchOverloadErr(args[2])\n\t\t}\n\t}\n\n\tre, err := regexp.Compile(regex)\n\tif err != nil {\n\t\treturn types.NewErr(\"Illegal regex: %v\", err.Error())\n\t}\n\n\tresult := re.FindAllString(str, int(n))\n\n\treturn types.NewStringList(types.DefaultTypeAdapter, result)\n}","line":{"from":100,"to":129}} {"id":100017183,"name":"URLs","signature":"func URLs() cel.EnvOption","file":"staging/src/k8s.io/apiserver/pkg/cel/library/urls.go","code":"// URLs provides a CEL function library extension of URL parsing functions.\n//\n// url\n//\n// Converts a string to a URL or results in an error if the string is not a valid URL. The URL must be an absolute URI\n// or an absolute path.\n//\n//\turl(\u003cstring\u003e) \u003cURL\u003e\n//\n// Examples:\n//\n//\turl('https://user:pass@example.com:80/path?query=val#fragment') // returns a URL\n//\turl('/absolute-path') // returns a URL\n//\turl('https://a:b:c/') // error\n//\turl('../relative-path') // error\n//\n// isURL\n//\n// Returns true if a string is a valid URL. The URL must be an absolute URI or an absolute path.\n//\n//\tisURL( \u003cstring\u003e) \u003cbool\u003e\n//\n// Examples:\n//\n//\tisURL('https://user:pass@example.com:80/path?query=val#fragment') // returns true\n//\tisURL('/absolute-path') // returns true\n//\tisURL('https://a:b:c/') // returns false\n//\tisURL('../relative-path') // returns false\n//\n// getScheme / getHost / getHostname / getPort / getEscapedPath / getQuery\n//\n// Return the parsed components of a URL.\n//\n// - getScheme: If absent in the URL, returns an empty string.\n//\n// - getHostname: IPv6 addresses are returned without braces, e.g. \"::1\". If absent in the URL, returns an empty string.\n//\n// - getHost: IPv6 addresses are returned with braces, e.g. \"[::1]\". If absent in the URL, returns an empty string.\n//\n// - getEscapedPath: The string returned by getEscapedPath is URL escaped, e.g. \"with space\" becomes \"with%20space\".\n// If absent in the URL, returns an empty string.\n//\n// - getPort: If absent in the URL, returns an empty string.\n//\n// - getQuery: Returns the query parameters in \"matrix\" form where a repeated query key is interpreted to\n// mean that there are multiple values for that key. The keys and values are returned unescaped.\n// If absent in the URL, returns an empty map.\n//\n// \u003cURL\u003e.getScheme() \u003cstring\u003e\n// \u003cURL\u003e.getHost() \u003cstring\u003e\n// \u003cURL\u003e.getHostname() \u003cstring\u003e\n// \u003cURL\u003e.getPort() \u003cstring\u003e\n// \u003cURL\u003e.getEscapedPath() \u003cstring\u003e\n// \u003cURL\u003e.getQuery() \u003cmap \u003cstring\u003e, \u003clist \u003cstring\u003e\u003e\n//\n// Examples:\n//\n//\turl('/path').getScheme() // returns ''\n//\turl('https://example.com/').getScheme() // returns 'https'\n//\turl('https://example.com:80/').getHost() // returns 'example.com:80'\n//\turl('https://example.com/').getHost() // returns 'example.com'\n//\turl('https://[::1]:80/').getHost() // returns '[::1]:80'\n//\turl('https://[::1]/').getHost() // returns '[::1]'\n//\turl('/path').getHost() // returns ''\n//\turl('https://example.com:80/').getHostname() // returns 'example.com'\n//\turl('https://127.0.0.1:80/').getHostname() // returns '127.0.0.1'\n//\turl('https://[::1]:80/').getHostname() // returns '::1'\n//\turl('/path').getHostname() // returns ''\n//\turl('https://example.com:80/').getPort() // returns '80'\n//\turl('https://example.com/').getPort() // returns ''\n//\turl('/path').getPort() // returns ''\n//\turl('https://example.com/path').getEscapedPath() // returns '/path'\n//\turl('https://example.com/path with spaces/').getEscapedPath() // returns '/path%20with%20spaces/'\n//\turl('https://example.com').getEscapedPath() // returns ''\n//\turl('https://example.com/path?k1=a\u0026k2=b\u0026k2=c').getQuery() // returns { 'k1': ['a'], 'k2': ['b', 'c']}\n//\turl('https://example.com/path?key with spaces=value with spaces').getQuery() // returns { 'key with spaces': ['value with spaces']}\n//\turl('https://example.com/path?').getQuery() // returns {}\n//\turl('https://example.com/path').getQuery() // returns {}\nfunc URLs() cel.EnvOption {\n\treturn cel.Lib(urlsLib)\n}","line":{"from":29,"to":109}} {"id":100017184,"name":"CompileOptions","signature":"func (*urls) CompileOptions() []cel.EnvOption","file":"staging/src/k8s.io/apiserver/pkg/cel/library/urls.go","code":"func (*urls) CompileOptions() []cel.EnvOption {\n\toptions := []cel.EnvOption{}\n\tfor name, overloads := range urlLibraryDecls {\n\t\toptions = append(options, cel.Function(name, overloads...))\n\t}\n\treturn options\n}","line":{"from":143,"to":149}} {"id":100017185,"name":"ProgramOptions","signature":"func (*urls) ProgramOptions() []cel.ProgramOption","file":"staging/src/k8s.io/apiserver/pkg/cel/library/urls.go","code":"func (*urls) ProgramOptions() []cel.ProgramOption {\n\treturn []cel.ProgramOption{}\n}","line":{"from":151,"to":153}} {"id":100017186,"name":"stringToUrl","signature":"func stringToUrl(arg ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/urls.go","code":"func stringToUrl(arg ref.Val) ref.Val {\n\ts, ok := arg.Value().(string)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(arg)\n\t}\n\t// Use ParseRequestURI to check the URL before conversion.\n\t// ParseRequestURI requires absolute URLs and is used by the OpenAPIv3 'uri' format.\n\t_, err := url.ParseRequestURI(s)\n\tif err != nil {\n\t\treturn types.NewErr(\"URL parse error during conversion from string: %v\", err)\n\t}\n\t// We must parse again with Parse since ParseRequestURI incorrectly parses URLs that contain a fragment\n\t// part and will incorrectly append the fragment to either the path or the query, depending on which it was adjacent to.\n\tu, err := url.Parse(s)\n\tif err != nil {\n\t\t// Errors are not expected here since Parse is a more lenient parser than ParseRequestURI.\n\t\treturn types.NewErr(\"URL parse error during conversion from string: %v\", err)\n\t}\n\treturn apiservercel.URL{URL: u}\n}","line":{"from":155,"to":174}} {"id":100017187,"name":"getScheme","signature":"func getScheme(arg ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/urls.go","code":"func getScheme(arg ref.Val) ref.Val {\n\tu, ok := arg.Value().(*url.URL)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(arg)\n\t}\n\treturn types.String(u.Scheme)\n}","line":{"from":176,"to":182}} {"id":100017188,"name":"getHost","signature":"func getHost(arg ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/urls.go","code":"func getHost(arg ref.Val) ref.Val {\n\tu, ok := arg.Value().(*url.URL)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(arg)\n\t}\n\treturn types.String(u.Host)\n}","line":{"from":184,"to":190}} {"id":100017189,"name":"getHostname","signature":"func getHostname(arg ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/urls.go","code":"func getHostname(arg ref.Val) ref.Val {\n\tu, ok := arg.Value().(*url.URL)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(arg)\n\t}\n\treturn types.String(u.Hostname())\n}","line":{"from":192,"to":198}} {"id":100017190,"name":"getPort","signature":"func getPort(arg ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/urls.go","code":"func getPort(arg ref.Val) ref.Val {\n\tu, ok := arg.Value().(*url.URL)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(arg)\n\t}\n\treturn types.String(u.Port())\n}","line":{"from":200,"to":206}} {"id":100017191,"name":"getEscapedPath","signature":"func getEscapedPath(arg ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/urls.go","code":"func getEscapedPath(arg ref.Val) ref.Val {\n\tu, ok := arg.Value().(*url.URL)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(arg)\n\t}\n\treturn types.String(u.EscapedPath())\n}","line":{"from":208,"to":214}} {"id":100017192,"name":"getQuery","signature":"func getQuery(arg ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/urls.go","code":"func getQuery(arg ref.Val) ref.Val {\n\tu, ok := arg.Value().(*url.URL)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(arg)\n\t}\n\n\tresult := map[ref.Val]ref.Val{}\n\tfor k, v := range u.Query() {\n\t\tresult[types.String(k)] = types.NewStringList(types.DefaultTypeAdapter, v)\n\t}\n\treturn types.NewRefValMap(types.DefaultTypeAdapter, result)\n}","line":{"from":216,"to":227}} {"id":100017193,"name":"isURL","signature":"func isURL(arg ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/library/urls.go","code":"func isURL(arg ref.Val) ref.Val {\n\ts, ok := arg.Value().(string)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(arg)\n\t}\n\t_, err := url.ParseRequestURI(s)\n\treturn types.Bool(err == nil)\n}","line":{"from":229,"to":236}} {"id":100017194,"name":"newCelMetrics","signature":"func newCelMetrics() *CelMetrics","file":"staging/src/k8s.io/apiserver/pkg/cel/metrics/metrics.go","code":"func newCelMetrics() *CelMetrics {\n\tm := \u0026CelMetrics{\n\t\tcompilationTime: metrics.NewHistogram(\u0026metrics.HistogramOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: \"compilation_duration_seconds\",\n\t\t\tHelp: \"CEL compilation time in seconds.\",\n\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t}),\n\t\tevaluationTime: metrics.NewHistogram(\u0026metrics.HistogramOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: \"evaluation_duration_seconds\",\n\t\t\tHelp: \"CEL evaluation time in seconds.\",\n\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t}),\n\t}\n\n\tlegacyregistry.MustRegister(m.compilationTime)\n\tlegacyregistry.MustRegister(m.evaluationTime)\n\n\treturn m\n}","line":{"from":40,"to":62}} {"id":100017195,"name":"ObserveCompilation","signature":"func (m *CelMetrics) ObserveCompilation(elapsed time.Duration)","file":"staging/src/k8s.io/apiserver/pkg/cel/metrics/metrics.go","code":"// ObserveCompilation records a CEL compilation with the time the compilation took.\nfunc (m *CelMetrics) ObserveCompilation(elapsed time.Duration) {\n\tseconds := elapsed.Seconds()\n\tm.compilationTime.Observe(seconds)\n}","line":{"from":64,"to":68}} {"id":100017196,"name":"ObserveEvaluation","signature":"func (m *CelMetrics) ObserveEvaluation(elapsed time.Duration)","file":"staging/src/k8s.io/apiserver/pkg/cel/metrics/metrics.go","code":"// ObserveEvaluation records a CEL evaluation with the time the evaluation took.\nfunc (m *CelMetrics) ObserveEvaluation(elapsed time.Duration) {\n\tseconds := elapsed.Seconds()\n\tm.evaluationTime.Observe(seconds)\n}","line":{"from":70,"to":74}} {"id":100017197,"name":"Schema","signature":"func (sb *SchemaOrBool) Schema() common.Schema","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/adaptor.go","code":"func (sb *SchemaOrBool) Schema() common.Schema {\n\treturn \u0026Schema{Schema: sb.SchemaOrBool.Schema}\n}","line":{"from":38,"to":40}} {"id":100017198,"name":"Allows","signature":"func (sb *SchemaOrBool) Allows() bool","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/adaptor.go","code":"func (sb *SchemaOrBool) Allows() bool {\n\treturn sb.SchemaOrBool.Allows\n}","line":{"from":42,"to":44}} {"id":100017199,"name":"Type","signature":"func (s *Schema) Type() string","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/adaptor.go","code":"func (s *Schema) Type() string {\n\tif len(s.Schema.Type) == 0 {\n\t\treturn \"\"\n\t}\n\treturn s.Schema.Type[0]\n}","line":{"from":46,"to":51}} {"id":100017200,"name":"Format","signature":"func (s *Schema) Format() string","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/adaptor.go","code":"func (s *Schema) Format() string {\n\treturn s.Schema.Format\n}","line":{"from":53,"to":55}} {"id":100017201,"name":"Items","signature":"func (s *Schema) Items() common.Schema","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/adaptor.go","code":"func (s *Schema) Items() common.Schema {\n\tif s.Schema.Items == nil || s.Schema.Items.Schema == nil {\n\t\treturn nil\n\t}\n\treturn \u0026Schema{Schema: s.Schema.Items.Schema}\n}","line":{"from":57,"to":62}} {"id":100017202,"name":"Properties","signature":"func (s *Schema) Properties() map[string]common.Schema","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/adaptor.go","code":"func (s *Schema) Properties() map[string]common.Schema {\n\tif s.Schema.Properties == nil {\n\t\treturn nil\n\t}\n\tres := make(map[string]common.Schema, len(s.Schema.Properties))\n\tfor n, prop := range s.Schema.Properties {\n\t\t// map value is unaddressable, create a shallow copy\n\t\t// this is a shallow non-recursive copy\n\t\ts := prop\n\t\tres[n] = \u0026Schema{Schema: \u0026s}\n\t}\n\treturn res\n}","line":{"from":64,"to":76}} {"id":100017203,"name":"AdditionalProperties","signature":"func (s *Schema) AdditionalProperties() common.SchemaOrBool","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/adaptor.go","code":"func (s *Schema) AdditionalProperties() common.SchemaOrBool {\n\tif s.Schema.AdditionalProperties == nil {\n\t\treturn nil\n\t}\n\treturn \u0026SchemaOrBool{SchemaOrBool: s.Schema.AdditionalProperties}\n}","line":{"from":78,"to":83}} {"id":100017204,"name":"Default","signature":"func (s *Schema) Default() any","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/adaptor.go","code":"func (s *Schema) Default() any {\n\treturn s.Schema.Default\n}","line":{"from":85,"to":87}} {"id":100017205,"name":"MaxItems","signature":"func (s *Schema) MaxItems() *int64","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/adaptor.go","code":"func (s *Schema) MaxItems() *int64 {\n\treturn s.Schema.MaxItems\n}","line":{"from":89,"to":91}} {"id":100017206,"name":"MaxLength","signature":"func (s *Schema) MaxLength() *int64","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/adaptor.go","code":"func (s *Schema) MaxLength() *int64 {\n\treturn s.Schema.MaxLength\n}","line":{"from":93,"to":95}} {"id":100017207,"name":"MaxProperties","signature":"func (s *Schema) MaxProperties() *int64","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/adaptor.go","code":"func (s *Schema) MaxProperties() *int64 {\n\treturn s.Schema.MaxProperties\n}","line":{"from":97,"to":99}} {"id":100017208,"name":"Required","signature":"func (s *Schema) Required() []string","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/adaptor.go","code":"func (s *Schema) Required() []string {\n\treturn s.Schema.Required\n}","line":{"from":101,"to":103}} {"id":100017209,"name":"Enum","signature":"func (s *Schema) Enum() []any","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/adaptor.go","code":"func (s *Schema) Enum() []any {\n\treturn s.Schema.Enum\n}","line":{"from":105,"to":107}} {"id":100017210,"name":"Nullable","signature":"func (s *Schema) Nullable() bool","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/adaptor.go","code":"func (s *Schema) Nullable() bool {\n\treturn s.Schema.Nullable\n}","line":{"from":109,"to":111}} {"id":100017211,"name":"IsXIntOrString","signature":"func (s *Schema) IsXIntOrString() bool","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/adaptor.go","code":"func (s *Schema) IsXIntOrString() bool {\n\treturn isXIntOrString(s.Schema)\n}","line":{"from":113,"to":115}} {"id":100017212,"name":"IsXEmbeddedResource","signature":"func (s *Schema) IsXEmbeddedResource() bool","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/adaptor.go","code":"func (s *Schema) IsXEmbeddedResource() bool {\n\treturn isXEmbeddedResource(s.Schema)\n}","line":{"from":117,"to":119}} {"id":100017213,"name":"IsXPreserveUnknownFields","signature":"func (s *Schema) IsXPreserveUnknownFields() bool","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/adaptor.go","code":"func (s *Schema) IsXPreserveUnknownFields() bool {\n\treturn isXPreserveUnknownFields(s.Schema)\n}","line":{"from":121,"to":123}} {"id":100017214,"name":"XListType","signature":"func (s *Schema) XListType() string","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/adaptor.go","code":"func (s *Schema) XListType() string {\n\treturn getXListType(s.Schema)\n}","line":{"from":125,"to":127}} {"id":100017215,"name":"XListMapKeys","signature":"func (s *Schema) XListMapKeys() []string","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/adaptor.go","code":"func (s *Schema) XListMapKeys() []string {\n\treturn getXListMapKeys(s.Schema)\n}","line":{"from":129,"to":131}} {"id":100017216,"name":"WithTypeAndObjectMeta","signature":"func (s *Schema) WithTypeAndObjectMeta() common.Schema","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/adaptor.go","code":"func (s *Schema) WithTypeAndObjectMeta() common.Schema {\n\treturn \u0026Schema{common.WithTypeAndObjectMeta(s.Schema)}\n}","line":{"from":133,"to":135}} {"id":100017217,"name":"UnstructuredToVal","signature":"func UnstructuredToVal(unstructured any, schema *spec.Schema) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/adaptor.go","code":"func UnstructuredToVal(unstructured any, schema *spec.Schema) ref.Val {\n\treturn common.UnstructuredToVal(unstructured, \u0026Schema{schema})\n}","line":{"from":137,"to":139}} {"id":100017218,"name":"SchemaDeclType","signature":"func SchemaDeclType(s *spec.Schema, isResourceRoot bool) *apiservercel.DeclType","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/adaptor.go","code":"func SchemaDeclType(s *spec.Schema, isResourceRoot bool) *apiservercel.DeclType {\n\treturn common.SchemaDeclType(\u0026Schema{Schema: s}, isResourceRoot)\n}","line":{"from":141,"to":143}} {"id":100017219,"name":"MakeMapList","signature":"func MakeMapList(sts *spec.Schema, items []interface{}) (rv common.MapList)","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/adaptor.go","code":"func MakeMapList(sts *spec.Schema, items []interface{}) (rv common.MapList) {\n\treturn common.MakeMapList(\u0026Schema{Schema: sts}, items)\n}","line":{"from":145,"to":147}} {"id":100017220,"name":"isExtension","signature":"func isExtension(schema *spec.Schema, key string) bool","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/extensions.go","code":"func isExtension(schema *spec.Schema, key string) bool {\n\tv, ok := schema.Extensions.GetBool(key)\n\treturn v \u0026\u0026 ok\n}","line":{"from":26,"to":29}} {"id":100017221,"name":"isXIntOrString","signature":"func isXIntOrString(schema *spec.Schema) bool","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/extensions.go","code":"func isXIntOrString(schema *spec.Schema) bool {\n\t// built-in types have the Format while CRDs use extension\n\t// both are valid, checking both\n\treturn schema.Format == intOrStringFormat || isExtension(schema, extIntOrString)\n}","line":{"from":31,"to":35}} {"id":100017222,"name":"isXEmbeddedResource","signature":"func isXEmbeddedResource(schema *spec.Schema) bool","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/extensions.go","code":"func isXEmbeddedResource(schema *spec.Schema) bool {\n\treturn isExtension(schema, extEmbeddedResource)\n}","line":{"from":37,"to":39}} {"id":100017223,"name":"isXPreserveUnknownFields","signature":"func isXPreserveUnknownFields(schema *spec.Schema) bool","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/extensions.go","code":"func isXPreserveUnknownFields(schema *spec.Schema) bool {\n\treturn isExtension(schema, extPreserveUnknownFields)\n}","line":{"from":41,"to":43}} {"id":100017224,"name":"getXListType","signature":"func getXListType(schema *spec.Schema) string","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/extensions.go","code":"func getXListType(schema *spec.Schema) string {\n\ts, _ := schema.Extensions.GetString(extListType)\n\treturn s\n}","line":{"from":45,"to":48}} {"id":100017225,"name":"getXListMapKeys","signature":"func getXListMapKeys(schema *spec.Schema) []string","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/extensions.go","code":"func getXListMapKeys(schema *spec.Schema) []string {\n\tmapKeys, ok := schema.Extensions.GetStringSlice(extListMapKeys)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn mapKeys\n}","line":{"from":50,"to":56}} {"id":100017226,"name":"NewDefinitionsSchemaResolver","signature":"func NewDefinitionsSchemaResolver(scheme *runtime.Scheme, getDefinitions common.GetOpenAPIDefinitions) *DefinitionsSchemaResolver","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/resolver/definitions.go","code":"// NewDefinitionsSchemaResolver creates a new DefinitionsSchemaResolver.\n// An example working setup:\n// scheme = \"k8s.io/client-go/kubernetes/scheme\".Scheme\n// getDefinitions = \"k8s.io/kubernetes/pkg/generated/openapi\".GetOpenAPIDefinitions\nfunc NewDefinitionsSchemaResolver(scheme *runtime.Scheme, getDefinitions common.GetOpenAPIDefinitions) *DefinitionsSchemaResolver {\n\tgvkToSchema := make(map[schema.GroupVersionKind]*spec.Schema)\n\tnamer := openapi.NewDefinitionNamer(scheme)\n\tdefs := getDefinitions(func(path string) spec.Ref {\n\t\treturn spec.MustCreateRef(path)\n\t})\n\tfor name, def := range defs {\n\t\t_, e := namer.GetDefinitionName(name)\n\t\tgvks := extensionsToGVKs(e)\n\t\ts := def.Schema // map value not addressable, make copy\n\t\tfor _, gvk := range gvks {\n\t\t\tgvkToSchema[gvk] = \u0026s\n\t\t}\n\t}\n\treturn \u0026DefinitionsSchemaResolver{\n\t\tgvkToSchema: gvkToSchema,\n\t\tdefs: defs,\n\t}\n}","line":{"from":36,"to":58}} {"id":100017227,"name":"ResolveSchema","signature":"func (d *DefinitionsSchemaResolver) ResolveSchema(gvk schema.GroupVersionKind) (*spec.Schema, error)","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/resolver/definitions.go","code":"func (d *DefinitionsSchemaResolver) ResolveSchema(gvk schema.GroupVersionKind) (*spec.Schema, error) {\n\ts, ok := d.gvkToSchema[gvk]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"cannot resolve %v: %w\", gvk, ErrSchemaNotFound)\n\t}\n\ts, err := populateRefs(func(ref string) (*spec.Schema, bool) {\n\t\t// find the schema by the ref string, and return a deep copy\n\t\tdef, ok := d.defs[ref]\n\t\tif !ok {\n\t\t\treturn nil, false\n\t\t}\n\t\ts := def.Schema\n\t\treturn \u0026s, true\n\t}, s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s, nil\n}","line":{"from":60,"to":78}} {"id":100017228,"name":"extensionsToGVKs","signature":"func extensionsToGVKs(extensions spec.Extensions) []schema.GroupVersionKind","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/resolver/definitions.go","code":"func extensionsToGVKs(extensions spec.Extensions) []schema.GroupVersionKind {\n\tgvksAny, ok := extensions[extGVK]\n\tif !ok {\n\t\treturn nil\n\t}\n\tgvks, ok := gvksAny.([]any)\n\tif !ok {\n\t\treturn nil\n\t}\n\tresult := make([]schema.GroupVersionKind, 0, len(gvks))\n\tfor _, gvkAny := range gvks {\n\t\t// type check the map and all fields\n\t\tgvkMap, ok := gvkAny.(map[string]any)\n\t\tif !ok {\n\t\t\treturn nil\n\t\t}\n\t\tg, ok := gvkMap[\"group\"].(string)\n\t\tif !ok {\n\t\t\treturn nil\n\t\t}\n\t\tv, ok := gvkMap[\"version\"].(string)\n\t\tif !ok {\n\t\t\treturn nil\n\t\t}\n\t\tk, ok := gvkMap[\"kind\"].(string)\n\t\tif !ok {\n\t\t\treturn nil\n\t\t}\n\t\tresult = append(result, schema.GroupVersionKind{\n\t\t\tGroup: g,\n\t\t\tVersion: v,\n\t\t\tKind: k,\n\t\t})\n\t}\n\treturn result\n}","line":{"from":80,"to":115}} {"id":100017229,"name":"ResolveSchema","signature":"func (r *ClientDiscoveryResolver) ResolveSchema(gvk schema.GroupVersionKind) (*spec.Schema, error)","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/resolver/discovery.go","code":"func (r *ClientDiscoveryResolver) ResolveSchema(gvk schema.GroupVersionKind) (*spec.Schema, error) {\n\tp, err := r.Discovery.OpenAPIV3().Paths()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresourcePath := resourcePathFromGV(gvk.GroupVersion())\n\tc, ok := p[resourcePath]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"cannot resolve group version %q: %w\", gvk.GroupVersion(), ErrSchemaNotFound)\n\t}\n\tb, err := c.Schema(runtime.ContentTypeJSON)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp := new(schemaResponse)\n\terr = json.Unmarshal(b, resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts, err := resolveType(resp, gvk)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts, err = populateRefs(func(ref string) (*spec.Schema, bool) {\n\t\ts, ok := resp.Components.Schemas[strings.TrimPrefix(ref, refPrefix)]\n\t\treturn s, ok\n\t}, s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s, nil\n}","line":{"from":37,"to":68}} {"id":100017230,"name":"resolveType","signature":"func resolveType(resp *schemaResponse, gvk schema.GroupVersionKind) (*spec.Schema, error)","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/resolver/discovery.go","code":"func resolveType(resp *schemaResponse, gvk schema.GroupVersionKind) (*spec.Schema, error) {\n\tfor _, s := range resp.Components.Schemas {\n\t\tvar gvks []schema.GroupVersionKind\n\t\terr := s.Extensions.GetObject(extGVK, \u0026gvks)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, g := range gvks {\n\t\t\tif g == gvk {\n\t\t\t\treturn s, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"cannot resolve group version kind %q: %w\", gvk, ErrSchemaNotFound)\n}","line":{"from":70,"to":84}} {"id":100017231,"name":"resourcePathFromGV","signature":"func resourcePathFromGV(gv schema.GroupVersion) string","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/resolver/discovery.go","code":"func resourcePathFromGV(gv schema.GroupVersion) string {\n\tvar resourcePath string\n\tif len(gv.Group) == 0 {\n\t\tresourcePath = fmt.Sprintf(\"api/%s\", gv.Version)\n\t} else {\n\t\tresourcePath = fmt.Sprintf(\"apis/%s/%s\", gv.Group, gv.Version)\n\t}\n\treturn resourcePath\n}","line":{"from":86,"to":94}} {"id":100017232,"name":"populateRefs","signature":"func populateRefs(schemaOf func(ref string) (*spec.Schema, bool), schema *spec.Schema) (*spec.Schema, error)","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/resolver/refs.go","code":"// populateRefs recursively replaces Refs in the schema with the referred one.\n// schemaOf is the callback to find the corresponding schema by the ref.\n// This function will not mutate the original schema. If the schema needs to be\n// mutated, a copy will be returned, otherwise it returns the original schema.\nfunc populateRefs(schemaOf func(ref string) (*spec.Schema, bool), schema *spec.Schema) (*spec.Schema, error) {\n\tresult := *schema\n\tchanged := false\n\n\tref, isRef := refOf(schema)\n\tif isRef {\n\t\t// replace the whole schema with the referred one.\n\t\tresolved, ok := schemaOf(ref)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"internal error: cannot resolve Ref %q: %w\", ref, ErrSchemaNotFound)\n\t\t}\n\t\tresult = *resolved\n\t\tchanged = true\n\t}\n\t// schema is an object, populate its properties and additionalProperties\n\tprops := make(map[string]spec.Schema, len(schema.Properties))\n\tpropsChanged := false\n\tfor name, prop := range result.Properties {\n\t\tpopulated, err := populateRefs(schemaOf, \u0026prop)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif populated != \u0026prop {\n\t\t\tpropsChanged = true\n\t\t}\n\t\tprops[name] = *populated\n\t}\n\tif propsChanged {\n\t\tchanged = true\n\t\tresult.Properties = props\n\t}\n\tif result.AdditionalProperties != nil \u0026\u0026 result.AdditionalProperties.Schema != nil {\n\t\tpopulated, err := populateRefs(schemaOf, result.AdditionalProperties.Schema)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif populated != result.AdditionalProperties.Schema {\n\t\t\tchanged = true\n\t\t\tresult.AdditionalProperties.Schema = populated\n\t\t}\n\t}\n\t// schema is a list, populate its items\n\tif result.Items != nil \u0026\u0026 result.Items.Schema != nil {\n\t\tpopulated, err := populateRefs(schemaOf, result.Items.Schema)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif populated != result.Items.Schema {\n\t\t\tchanged = true\n\t\t\tresult.Items.Schema = populated\n\t\t}\n\t}\n\tif changed {\n\t\treturn \u0026result, nil\n\t}\n\treturn schema, nil\n}","line":{"from":25,"to":85}} {"id":100017233,"name":"refOf","signature":"func refOf(schema *spec.Schema) (string, bool)","file":"staging/src/k8s.io/apiserver/pkg/cel/openapi/resolver/refs.go","code":"func refOf(schema *spec.Schema) (string, bool) {\n\tif schema.Ref.GetURL() != nil {\n\t\treturn schema.Ref.String(), true\n\t}\n\t// A Ref may be wrapped in allOf to preserve its description\n\t// see https://github.com/kubernetes/kubernetes/issues/106387\n\t// For kube-openapi, allOf is only used for wrapping a Ref.\n\tfor _, allOf := range schema.AllOf {\n\t\tif ref, isRef := refOf(\u0026allOf); isRef {\n\t\t\treturn ref, isRef\n\t\t}\n\t}\n\treturn \"\", false\n}","line":{"from":87,"to":100}} {"id":100017234,"name":"NewRegistry","signature":"func NewRegistry(stdExprEnv *cel.Env) *Registry","file":"staging/src/k8s.io/apiserver/pkg/cel/registry.go","code":"// NewRegistry create a registry for keeping track of environments and types\n// from a base cel.Env expression environment.\nfunc NewRegistry(stdExprEnv *cel.Env) *Registry {\n\treturn \u0026Registry{\n\t\texprEnvs: map[string]*cel.Env{\"\": stdExprEnv},\n\t\ttypes: map[string]*DeclType{\n\t\t\tBoolType.TypeName(): BoolType,\n\t\t\tBytesType.TypeName(): BytesType,\n\t\t\tDoubleType.TypeName(): DoubleType,\n\t\t\tDurationType.TypeName(): DurationType,\n\t\t\tIntType.TypeName(): IntType,\n\t\t\tNullType.TypeName(): NullType,\n\t\t\tStringType.TypeName(): StringType,\n\t\t\tTimestampType.TypeName(): TimestampType,\n\t\t\tUintType.TypeName(): UintType,\n\t\t\tListType.TypeName(): ListType,\n\t\t\tMapType.TypeName(): MapType,\n\t\t},\n\t}\n}","line":{"from":32,"to":51}} {"id":100017235,"name":"FindType","signature":"func (r *Registry) FindType(name string) (*DeclType, bool)","file":"staging/src/k8s.io/apiserver/pkg/cel/registry.go","code":"// FindType implements the Resolver interface method.\nfunc (r *Registry) FindType(name string) (*DeclType, bool) {\n\tr.rwMux.RLock()\n\tdefer r.rwMux.RUnlock()\n\ttyp, found := r.types[name]\n\tif found {\n\t\treturn typ, true\n\t}\n\treturn typ, found\n}","line":{"from":62,"to":71}} {"id":100017236,"name":"SetType","signature":"func (r *Registry) SetType(name string, declType *DeclType) error","file":"staging/src/k8s.io/apiserver/pkg/cel/registry.go","code":"// SetType registers a DeclType descriptor by its fully qualified name.\nfunc (r *Registry) SetType(name string, declType *DeclType) error {\n\tr.rwMux.Lock()\n\tdefer r.rwMux.Unlock()\n\tr.types[name] = declType\n\treturn nil\n}","line":{"from":73,"to":79}} {"id":100017237,"name":"NewListType","signature":"func NewListType(elem *DeclType, maxItems int64) *DeclType","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"// NewListType returns a parameterized list type with a specified element type.\nfunc NewListType(elem *DeclType, maxItems int64) *DeclType {\n\treturn \u0026DeclType{\n\t\tname: \"list\",\n\t\tElemType: elem,\n\t\tMaxElements: maxItems,\n\t\tcelType: cel.ListType(elem.CelType()),\n\t\tdefaultValue: NewListValue(),\n\t\t// a list can always be represented as [] in JSON, so hardcode the min size\n\t\t// to 2\n\t\tMinSerializedSize: 2,\n\t}\n}","line":{"from":37,"to":49}} {"id":100017238,"name":"NewMapType","signature":"func NewMapType(key, elem *DeclType, maxProperties int64) *DeclType","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"// NewMapType returns a parameterized map type with the given key and element types.\nfunc NewMapType(key, elem *DeclType, maxProperties int64) *DeclType {\n\treturn \u0026DeclType{\n\t\tname: \"map\",\n\t\tKeyType: key,\n\t\tElemType: elem,\n\t\tMaxElements: maxProperties,\n\t\tcelType: cel.MapType(key.CelType(), elem.CelType()),\n\t\tdefaultValue: NewMapValue(),\n\t\t// a map can always be represented as {} in JSON, so hardcode the min size\n\t\t// to 2\n\t\tMinSerializedSize: 2,\n\t}\n}","line":{"from":51,"to":64}} {"id":100017239,"name":"NewObjectType","signature":"func NewObjectType(name string, fields map[string]*DeclField) *DeclType","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"// NewObjectType creates an object type with a qualified name and a set of field declarations.\nfunc NewObjectType(name string, fields map[string]*DeclField) *DeclType {\n\tt := \u0026DeclType{\n\t\tname: name,\n\t\tFields: fields,\n\t\tcelType: cel.ObjectType(name),\n\t\ttraitMask: traits.FieldTesterType | traits.IndexerType,\n\t\t// an object could potentially be larger than the min size we default to here ({}),\n\t\t// but we rely upon the caller to change MinSerializedSize accordingly if they add\n\t\t// properties to the object\n\t\tMinSerializedSize: 2,\n\t}\n\tt.defaultValue = NewObjectValue(t)\n\treturn t\n}","line":{"from":66,"to":80}} {"id":100017240,"name":"NewSimpleTypeWithMinSize","signature":"func NewSimpleTypeWithMinSize(name string, celType *cel.Type, zeroVal ref.Val, minSize int64) *DeclType","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"func NewSimpleTypeWithMinSize(name string, celType *cel.Type, zeroVal ref.Val, minSize int64) *DeclType {\n\treturn \u0026DeclType{\n\t\tname: name,\n\t\tcelType: celType,\n\t\tdefaultValue: zeroVal,\n\t\tMinSerializedSize: minSize,\n\t}\n}","line":{"from":82,"to":89}} {"id":100017241,"name":"MaybeAssignTypeName","signature":"func (t *DeclType) MaybeAssignTypeName(name string) *DeclType","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"// MaybeAssignTypeName attempts to set the DeclType name to a fully qualified name, if the type\n// is of `object` type.\n//\n// The DeclType must return true for `IsObject` or this assignment will error.\nfunc (t *DeclType) MaybeAssignTypeName(name string) *DeclType {\n\tif t.IsObject() {\n\t\tobjUpdated := false\n\t\tif t.name != \"object\" {\n\t\t\tname = t.name\n\t\t} else {\n\t\t\tobjUpdated = true\n\t\t}\n\t\tfieldMap := make(map[string]*DeclField, len(t.Fields))\n\t\tfor fieldName, field := range t.Fields {\n\t\t\tfieldType := field.Type\n\t\t\tfieldTypeName := fmt.Sprintf(\"%s.%s\", name, fieldName)\n\t\t\tupdated := fieldType.MaybeAssignTypeName(fieldTypeName)\n\t\t\tif updated == fieldType {\n\t\t\t\tfieldMap[fieldName] = field\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tobjUpdated = true\n\t\t\tfieldMap[fieldName] = \u0026DeclField{\n\t\t\t\tName: fieldName,\n\t\t\t\tType: updated,\n\t\t\t\tRequired: field.Required,\n\t\t\t\tenumValues: field.enumValues,\n\t\t\t\tdefaultValue: field.defaultValue,\n\t\t\t}\n\t\t}\n\t\tif !objUpdated {\n\t\t\treturn t\n\t\t}\n\t\treturn \u0026DeclType{\n\t\t\tname: name,\n\t\t\tFields: fieldMap,\n\t\t\tKeyType: t.KeyType,\n\t\t\tElemType: t.ElemType,\n\t\t\tTypeParam: t.TypeParam,\n\t\t\tMetadata: t.Metadata,\n\t\t\tcelType: cel.ObjectType(name),\n\t\t\ttraitMask: t.traitMask,\n\t\t\tdefaultValue: t.defaultValue,\n\t\t\tMinSerializedSize: t.MinSerializedSize,\n\t\t}\n\t}\n\tif t.IsMap() {\n\t\telemTypeName := fmt.Sprintf(\"%s.@elem\", name)\n\t\tupdated := t.ElemType.MaybeAssignTypeName(elemTypeName)\n\t\tif updated == t.ElemType {\n\t\t\treturn t\n\t\t}\n\t\treturn NewMapType(t.KeyType, updated, t.MaxElements)\n\t}\n\tif t.IsList() {\n\t\telemTypeName := fmt.Sprintf(\"%s.@idx\", name)\n\t\tupdated := t.ElemType.MaybeAssignTypeName(elemTypeName)\n\t\tif updated == t.ElemType {\n\t\t\treturn t\n\t\t}\n\t\treturn NewListType(updated, t.MaxElements)\n\t}\n\treturn t\n}","line":{"from":112,"to":175}} {"id":100017242,"name":"ExprType","signature":"func (t *DeclType) ExprType() (*exprpb.Type, error)","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"// ExprType returns the CEL expression type of this declaration.\nfunc (t *DeclType) ExprType() (*exprpb.Type, error) {\n\treturn cel.TypeToExprType(t.celType)\n}","line":{"from":177,"to":180}} {"id":100017243,"name":"CelType","signature":"func (t *DeclType) CelType() *cel.Type","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"// CelType returns the CEL type of this declaration.\nfunc (t *DeclType) CelType() *cel.Type {\n\treturn t.celType\n}","line":{"from":182,"to":185}} {"id":100017244,"name":"FindField","signature":"func (t *DeclType) FindField(name string) (*DeclField, bool)","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"// FindField returns the DeclField with the given name if present.\nfunc (t *DeclType) FindField(name string) (*DeclField, bool) {\n\tf, found := t.Fields[name]\n\treturn f, found\n}","line":{"from":187,"to":191}} {"id":100017245,"name":"HasTrait","signature":"func (t *DeclType) HasTrait(trait int) bool","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"// HasTrait implements the CEL ref.Type interface making this type declaration suitable for use\n// within the CEL evaluator.\nfunc (t *DeclType) HasTrait(trait int) bool {\n\tif t.traitMask\u0026trait == trait {\n\t\treturn true\n\t}\n\tif t.defaultValue == nil {\n\t\treturn false\n\t}\n\t_, isDecl := t.defaultValue.Type().(*DeclType)\n\tif isDecl {\n\t\treturn false\n\t}\n\treturn t.defaultValue.Type().HasTrait(trait)\n}","line":{"from":193,"to":207}} {"id":100017246,"name":"IsList","signature":"func (t *DeclType) IsList() bool","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"// IsList returns whether the declaration is a `list` type which defines a parameterized element\n// type, but not a parameterized key type or fields.\nfunc (t *DeclType) IsList() bool {\n\treturn t.KeyType == nil \u0026\u0026 t.ElemType != nil \u0026\u0026 t.Fields == nil\n}","line":{"from":209,"to":213}} {"id":100017247,"name":"IsMap","signature":"func (t *DeclType) IsMap() bool","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"// IsMap returns whether the declaration is a 'map' type which defines parameterized key and\n// element types, but not fields.\nfunc (t *DeclType) IsMap() bool {\n\treturn t.KeyType != nil \u0026\u0026 t.ElemType != nil \u0026\u0026 t.Fields == nil\n}","line":{"from":215,"to":219}} {"id":100017248,"name":"IsObject","signature":"func (t *DeclType) IsObject() bool","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"// IsObject returns whether the declartion is an 'object' type which defined a set of typed fields.\nfunc (t *DeclType) IsObject() bool {\n\treturn t.KeyType == nil \u0026\u0026 t.ElemType == nil \u0026\u0026 t.Fields != nil\n}","line":{"from":221,"to":224}} {"id":100017249,"name":"String","signature":"func (t *DeclType) String() string","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"// String implements the fmt.Stringer interface method.\nfunc (t *DeclType) String() string {\n\treturn t.name\n}","line":{"from":226,"to":229}} {"id":100017250,"name":"TypeName","signature":"func (t *DeclType) TypeName() string","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"// TypeName returns the fully qualified type name for the DeclType.\nfunc (t *DeclType) TypeName() string {\n\treturn t.name\n}","line":{"from":231,"to":234}} {"id":100017251,"name":"DefaultValue","signature":"func (t *DeclType) DefaultValue() ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"// DefaultValue returns the CEL ref.Val representing the default value for this object type,\n// if one exists.\nfunc (t *DeclType) DefaultValue() ref.Val {\n\treturn t.defaultValue\n}","line":{"from":236,"to":240}} {"id":100017252,"name":"FieldTypeMap","signature":"func FieldTypeMap(path string, t *DeclType) map[string]*DeclType","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"// FieldTypeMap constructs a map of the field and object types nested within a given type.\nfunc FieldTypeMap(path string, t *DeclType) map[string]*DeclType {\n\tif t.IsObject() \u0026\u0026 t.TypeName() != \"object\" {\n\t\tpath = t.TypeName()\n\t}\n\ttypes := make(map[string]*DeclType)\n\tbuildDeclTypes(path, t, types)\n\treturn types\n}","line":{"from":242,"to":250}} {"id":100017253,"name":"buildDeclTypes","signature":"func buildDeclTypes(path string, t *DeclType, types map[string]*DeclType)","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"func buildDeclTypes(path string, t *DeclType, types map[string]*DeclType) {\n\t// Ensure object types are properly named according to where they appear in the schema.\n\tif t.IsObject() {\n\t\t// Hack to ensure that names are uniquely qualified and work well with the type\n\t\t// resolution steps which require fully qualified type names for field resolution\n\t\t// to function properly.\n\t\ttypes[t.TypeName()] = t\n\t\tfor name, field := range t.Fields {\n\t\t\tfieldPath := fmt.Sprintf(\"%s.%s\", path, name)\n\t\t\tbuildDeclTypes(fieldPath, field.Type, types)\n\t\t}\n\t}\n\t// Map element properties to type names if needed.\n\tif t.IsMap() {\n\t\tmapElemPath := fmt.Sprintf(\"%s.@elem\", path)\n\t\tbuildDeclTypes(mapElemPath, t.ElemType, types)\n\t\ttypes[path] = t\n\t}\n\t// List element properties.\n\tif t.IsList() {\n\t\tlistIdxPath := fmt.Sprintf(\"%s.@idx\", path)\n\t\tbuildDeclTypes(listIdxPath, t.ElemType, types)\n\t\ttypes[path] = t\n\t}\n}","line":{"from":252,"to":276}} {"id":100017254,"name":"NewDeclField","signature":"func NewDeclField(name string, declType *DeclType, required bool, enumValues []interface{}, defaultValue interface{}) *DeclField","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"func NewDeclField(name string, declType *DeclType, required bool, enumValues []interface{}, defaultValue interface{}) *DeclField {\n\treturn \u0026DeclField{\n\t\tName: name,\n\t\tType: declType,\n\t\tRequired: required,\n\t\tenumValues: enumValues,\n\t\tdefaultValue: defaultValue,\n\t}\n}","line":{"from":287,"to":295}} {"id":100017255,"name":"TypeName","signature":"func (f *DeclField) TypeName() string","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"// TypeName returns the string type name of the field.\nfunc (f *DeclField) TypeName() string {\n\treturn f.Type.TypeName()\n}","line":{"from":297,"to":300}} {"id":100017256,"name":"DefaultValue","signature":"func (f *DeclField) DefaultValue() ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"// DefaultValue returns the zero value associated with the field.\nfunc (f *DeclField) DefaultValue() ref.Val {\n\tif f.defaultValue != nil {\n\t\treturn types.DefaultTypeAdapter.NativeToValue(f.defaultValue)\n\t}\n\treturn f.Type.DefaultValue()\n}","line":{"from":302,"to":308}} {"id":100017257,"name":"EnumValues","signature":"func (f *DeclField) EnumValues() []ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"// EnumValues returns the set of values that this field may take.\nfunc (f *DeclField) EnumValues() []ref.Val {\n\tif f.enumValues == nil || len(f.enumValues) == 0 {\n\t\treturn []ref.Val{}\n\t}\n\tev := make([]ref.Val, len(f.enumValues))\n\tfor i, e := range f.enumValues {\n\t\tev[i] = types.DefaultTypeAdapter.NativeToValue(e)\n\t}\n\treturn ev\n}","line":{"from":310,"to":320}} {"id":100017258,"name":"NewRuleTypes","signature":"func NewRuleTypes(kind string,","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"// NewRuleTypes returns an Open API Schema-based type-system which is CEL compatible.\nfunc NewRuleTypes(kind string,\n\tdeclType *DeclType,\n\tres Resolver) (*RuleTypes, error) {\n\t// Note, if the schema indicates that it's actually based on another proto\n\t// then prefer the proto definition. For expressions in the proto, a new field\n\t// annotation will be needed to indicate the expected environment and type of\n\t// the expression.\n\tschemaTypes, err := newSchemaTypeProvider(kind, declType)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif schemaTypes == nil {\n\t\treturn nil, nil\n\t}\n\treturn \u0026RuleTypes{\n\t\truleSchemaDeclTypes: schemaTypes,\n\t\tresolver: res,\n\t}, nil\n}","line":{"from":322,"to":341}} {"id":100017259,"name":"EnvOptions","signature":"func (rt *RuleTypes) EnvOptions(tp ref.TypeProvider) ([]cel.EnvOption, error)","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"// EnvOptions returns a set of cel.EnvOption values which includes the declaration set\n// as well as a custom ref.TypeProvider.\n//\n// Note, the standard declaration set includes 'rule' which is defined as the top-level rule-schema\n// type if one is configured.\n//\n// If the RuleTypes value is nil, an empty []cel.EnvOption set is returned.\nfunc (rt *RuleTypes) EnvOptions(tp ref.TypeProvider) ([]cel.EnvOption, error) {\n\tif rt == nil {\n\t\treturn []cel.EnvOption{}, nil\n\t}\n\trtWithTypes, err := rt.WithTypeProvider(tp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn []cel.EnvOption{\n\t\tcel.CustomTypeProvider(rtWithTypes),\n\t\tcel.CustomTypeAdapter(rtWithTypes),\n\t\tcel.Variable(\"rule\", rt.ruleSchemaDeclTypes.root.CelType()),\n\t}, nil\n}","line":{"from":352,"to":372}} {"id":100017260,"name":"WithTypeProvider","signature":"func (rt *RuleTypes) WithTypeProvider(tp ref.TypeProvider) (*RuleTypes, error)","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"// WithTypeProvider returns a new RuleTypes that sets the given TypeProvider\n// If the original RuleTypes is nil, the returned RuleTypes is still nil.\nfunc (rt *RuleTypes) WithTypeProvider(tp ref.TypeProvider) (*RuleTypes, error) {\n\tif rt == nil {\n\t\treturn nil, nil\n\t}\n\tvar ta ref.TypeAdapter = types.DefaultTypeAdapter\n\ttpa, ok := tp.(ref.TypeAdapter)\n\tif ok {\n\t\tta = tpa\n\t}\n\trtWithTypes := \u0026RuleTypes{\n\t\tTypeProvider: tp,\n\t\ttypeAdapter: ta,\n\t\truleSchemaDeclTypes: rt.ruleSchemaDeclTypes,\n\t\tresolver: rt.resolver,\n\t}\n\tfor name, declType := range rt.ruleSchemaDeclTypes.types {\n\t\ttpType, found := tp.FindType(name)\n\t\texpT, err := declType.ExprType()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"fail to get cel type: %s\", err)\n\t\t}\n\t\tif found \u0026\u0026 !proto.Equal(tpType, expT) {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"type %s definition differs between CEL environment and rule\", name)\n\t\t}\n\t}\n\treturn rtWithTypes, nil\n}","line":{"from":374,"to":403}} {"id":100017261,"name":"FindType","signature":"func (rt *RuleTypes) FindType(typeName string) (*exprpb.Type, bool)","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"// FindType attempts to resolve the typeName provided from the rule's rule-schema, or if not\n// from the embedded ref.TypeProvider.\n//\n// FindType overrides the default type-finding behavior of the embedded TypeProvider.\n//\n// Note, when the type name is based on the Open API Schema, the name will reflect the object path\n// where the type definition appears.\nfunc (rt *RuleTypes) FindType(typeName string) (*exprpb.Type, bool) {\n\tif rt == nil {\n\t\treturn nil, false\n\t}\n\tdeclType, found := rt.findDeclType(typeName)\n\tif found {\n\t\texpT, err := declType.ExprType()\n\t\tif err != nil {\n\t\t\treturn expT, false\n\t\t}\n\t\treturn expT, found\n\t}\n\treturn rt.TypeProvider.FindType(typeName)\n}","line":{"from":405,"to":425}} {"id":100017262,"name":"FindDeclType","signature":"func (rt *RuleTypes) FindDeclType(typeName string) (*DeclType, bool)","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"// FindDeclType returns the CPT type description which can be mapped to a CEL type.\nfunc (rt *RuleTypes) FindDeclType(typeName string) (*DeclType, bool) {\n\tif rt == nil {\n\t\treturn nil, false\n\t}\n\treturn rt.findDeclType(typeName)\n}","line":{"from":427,"to":433}} {"id":100017263,"name":"FindFieldType","signature":"func (rt *RuleTypes) FindFieldType(typeName, fieldName string) (*ref.FieldType, bool)","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"// FindFieldType returns a field type given a type name and field name, if found.\n//\n// Note, the type name for an Open API Schema type is likely to be its qualified object path.\n// If, in the future an object instance rather than a type name were provided, the field\n// resolution might more accurately reflect the expected type model. However, in this case\n// concessions were made to align with the existing CEL interfaces.\nfunc (rt *RuleTypes) FindFieldType(typeName, fieldName string) (*ref.FieldType, bool) {\n\tst, found := rt.findDeclType(typeName)\n\tif !found {\n\t\treturn rt.TypeProvider.FindFieldType(typeName, fieldName)\n\t}\n\n\tf, found := st.Fields[fieldName]\n\tif found {\n\t\tft := f.Type\n\t\texpT, err := ft.ExprType()\n\t\tif err != nil {\n\t\t\treturn nil, false\n\t\t}\n\t\treturn \u0026ref.FieldType{\n\t\t\tType: expT,\n\t\t}, true\n\t}\n\t// This could be a dynamic map.\n\tif st.IsMap() {\n\t\tet := st.ElemType\n\t\texpT, err := et.ExprType()\n\t\tif err != nil {\n\t\t\treturn nil, false\n\t\t}\n\t\treturn \u0026ref.FieldType{\n\t\t\tType: expT,\n\t\t}, true\n\t}\n\treturn nil, false\n}","line":{"from":435,"to":470}} {"id":100017264,"name":"NativeToValue","signature":"func (rt *RuleTypes) NativeToValue(val interface{}) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"// NativeToValue is an implementation of the ref.TypeAdapater interface which supports conversion\n// of rule values to CEL ref.Val instances.\nfunc (rt *RuleTypes) NativeToValue(val interface{}) ref.Val {\n\treturn rt.typeAdapter.NativeToValue(val)\n}","line":{"from":472,"to":476}} {"id":100017265,"name":"TypeNames","signature":"func (rt *RuleTypes) TypeNames() []string","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"// TypeNames returns the list of type names declared within the RuleTypes object.\nfunc (rt *RuleTypes) TypeNames() []string {\n\ttypeNames := make([]string, len(rt.ruleSchemaDeclTypes.types))\n\ti := 0\n\tfor name := range rt.ruleSchemaDeclTypes.types {\n\t\ttypeNames[i] = name\n\t\ti++\n\t}\n\treturn typeNames\n}","line":{"from":478,"to":487}} {"id":100017266,"name":"findDeclType","signature":"func (rt *RuleTypes) findDeclType(typeName string) (*DeclType, bool)","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"func (rt *RuleTypes) findDeclType(typeName string) (*DeclType, bool) {\n\tdeclType, found := rt.ruleSchemaDeclTypes.types[typeName]\n\tif found {\n\t\treturn declType, true\n\t}\n\tdeclType, found = rt.resolver.FindType(typeName)\n\tif found {\n\t\treturn declType, true\n\t}\n\treturn nil, false\n}","line":{"from":489,"to":499}} {"id":100017267,"name":"newSchemaTypeProvider","signature":"func newSchemaTypeProvider(kind string, declType *DeclType) (*schemaTypeProvider, error)","file":"staging/src/k8s.io/apiserver/pkg/cel/types.go","code":"func newSchemaTypeProvider(kind string, declType *DeclType) (*schemaTypeProvider, error) {\n\tif declType == nil {\n\t\treturn nil, nil\n\t}\n\troot := declType.MaybeAssignTypeName(kind)\n\ttypes := FieldTypeMap(kind, root)\n\treturn \u0026schemaTypeProvider{\n\t\troot: root,\n\t\ttypes: types,\n\t}, nil\n}","line":{"from":501,"to":511}} {"id":100017268,"name":"ConvertToNative","signature":"func (d URL) ConvertToNative(typeDesc reflect.Type) (interface{}, error)","file":"staging/src/k8s.io/apiserver/pkg/cel/url.go","code":"// ConvertToNative implements ref.Val.ConvertToNative.\nfunc (d URL) ConvertToNative(typeDesc reflect.Type) (interface{}, error) {\n\tif reflect.TypeOf(d.URL).AssignableTo(typeDesc) {\n\t\treturn d.URL, nil\n\t}\n\tif reflect.TypeOf(\"\").AssignableTo(typeDesc) {\n\t\treturn d.URL.String(), nil\n\t}\n\treturn nil, fmt.Errorf(\"type conversion error from 'URL' to '%v'\", typeDesc)\n}","line":{"from":41,"to":50}} {"id":100017269,"name":"ConvertToType","signature":"func (d URL) ConvertToType(typeVal ref.Type) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/url.go","code":"// ConvertToType implements ref.Val.ConvertToType.\nfunc (d URL) ConvertToType(typeVal ref.Type) ref.Val {\n\tswitch typeVal {\n\tcase typeValue:\n\t\treturn d\n\tcase types.TypeType:\n\t\treturn typeValue\n\t}\n\treturn types.NewErr(\"type conversion error from '%s' to '%s'\", typeValue, typeVal)\n}","line":{"from":52,"to":61}} {"id":100017270,"name":"Equal","signature":"func (d URL) Equal(other ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/url.go","code":"// Equal implements ref.Val.Equal.\nfunc (d URL) Equal(other ref.Val) ref.Val {\n\totherDur, ok := other.(URL)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(other)\n\t}\n\treturn types.Bool(d.URL.String() == otherDur.URL.String())\n}","line":{"from":63,"to":70}} {"id":100017271,"name":"Type","signature":"func (d URL) Type() ref.Type","file":"staging/src/k8s.io/apiserver/pkg/cel/url.go","code":"// Type implements ref.Val.Type.\nfunc (d URL) Type() ref.Type {\n\treturn typeValue\n}","line":{"from":72,"to":75}} {"id":100017272,"name":"Value","signature":"func (d URL) Value() interface{}","file":"staging/src/k8s.io/apiserver/pkg/cel/url.go","code":"// Value implements ref.Val.Value.\nfunc (d URL) Value() interface{} {\n\treturn d.URL\n}","line":{"from":77,"to":80}} {"id":100017273,"name":"NewEmptyDynValue","signature":"func NewEmptyDynValue() *DynValue","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// NewEmptyDynValue returns the zero-valued DynValue.\nfunc NewEmptyDynValue() *DynValue {\n\t// note: 0 is not a valid parse node identifier.\n\tdv, _ := NewDynValue(0, nil)\n\treturn dv\n}","line":{"from":50,"to":55}} {"id":100017274,"name":"NewDynValue","signature":"func NewDynValue(id int64, val interface{}) (*DynValue, error)","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// NewDynValue returns a DynValue that corresponds to a parse node id and value.\nfunc NewDynValue(id int64, val interface{}) (*DynValue, error) {\n\tdv := \u0026DynValue{ID: id}\n\terr := dv.SetValue(val)\n\treturn dv, err\n}","line":{"from":57,"to":62}} {"id":100017275,"name":"DeclType","signature":"func (dv *DynValue) DeclType() *DeclType","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// DeclType returns the policy model type of the dyn value.\nfunc (dv *DynValue) DeclType() *DeclType {\n\treturn dv.declType\n}","line":{"from":75,"to":78}} {"id":100017276,"name":"ConvertToNative","signature":"func (dv *DynValue) ConvertToNative(typeDesc reflect.Type) (interface{}, error)","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// ConvertToNative is an implementation of the CEL ref.Val method used to adapt between CEL types\n// and Go-native types.\n//\n// The default behavior of this method is to first convert to a CEL type which has a well-defined\n// set of conversion behaviors and proxy to the CEL ConvertToNative method for the type.\nfunc (dv *DynValue) ConvertToNative(typeDesc reflect.Type) (interface{}, error) {\n\tev := dv.ExprValue()\n\tif types.IsError(ev) {\n\t\treturn nil, ev.(*types.Err)\n\t}\n\treturn ev.ConvertToNative(typeDesc)\n}","line":{"from":80,"to":91}} {"id":100017277,"name":"Equal","signature":"func (dv *DynValue) Equal(other ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// Equal returns whether the dyn value is equal to a given CEL value.\nfunc (dv *DynValue) Equal(other ref.Val) ref.Val {\n\tdvType := dv.Type()\n\totherType := other.Type()\n\t// Preserve CEL's homogeneous equality constraint.\n\tif dvType.TypeName() != otherType.TypeName() {\n\t\treturn types.MaybeNoSuchOverloadErr(other)\n\t}\n\tswitch v := dv.value.(type) {\n\tcase ref.Val:\n\t\treturn v.Equal(other)\n\tcase PlainTextValue:\n\t\treturn celBool(string(v) == other.Value().(string))\n\tcase *MultilineStringValue:\n\t\treturn celBool(v.Value == other.Value().(string))\n\tcase time.Duration:\n\t\totherDuration := other.Value().(time.Duration)\n\t\treturn celBool(v == otherDuration)\n\tcase time.Time:\n\t\totherTimestamp := other.Value().(time.Time)\n\t\treturn celBool(v.Equal(otherTimestamp))\n\tdefault:\n\t\treturn celBool(reflect.DeepEqual(v, other.Value()))\n\t}\n}","line":{"from":93,"to":117}} {"id":100017278,"name":"ExprValue","signature":"func (dv *DynValue) ExprValue() ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// ExprValue converts the DynValue into a CEL value.\nfunc (dv *DynValue) ExprValue() ref.Val {\n\treturn dv.exprValue\n}","line":{"from":119,"to":122}} {"id":100017279,"name":"Value","signature":"func (dv *DynValue) Value() interface{}","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// Value returns the underlying value held by this reference.\nfunc (dv *DynValue) Value() interface{} {\n\treturn dv.value\n}","line":{"from":124,"to":127}} {"id":100017280,"name":"SetValue","signature":"func (dv *DynValue) SetValue(value interface{}) error","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// SetValue updates the underlying value held by this reference.\nfunc (dv *DynValue) SetValue(value interface{}) error {\n\tdv.value = value\n\tvar err error\n\tdv.exprValue, dv.declType, err = exprValue(value)\n\treturn err\n}","line":{"from":129,"to":135}} {"id":100017281,"name":"Type","signature":"func (dv *DynValue) Type() ref.Type","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// Type returns the CEL type for the given value.\nfunc (dv *DynValue) Type() ref.Type {\n\treturn dv.ExprValue().Type()\n}","line":{"from":137,"to":140}} {"id":100017282,"name":"exprValue","signature":"func exprValue(value interface{}) (ref.Val, *DeclType, error)","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"func exprValue(value interface{}) (ref.Val, *DeclType, error) {\n\tswitch v := value.(type) {\n\tcase bool:\n\t\treturn types.Bool(v), BoolType, nil\n\tcase []byte:\n\t\treturn types.Bytes(v), BytesType, nil\n\tcase float64:\n\t\treturn types.Double(v), DoubleType, nil\n\tcase int64:\n\t\treturn types.Int(v), IntType, nil\n\tcase string:\n\t\treturn types.String(v), StringType, nil\n\tcase uint64:\n\t\treturn types.Uint(v), UintType, nil\n\tcase time.Duration:\n\t\treturn types.Duration{Duration: v}, DurationType, nil\n\tcase time.Time:\n\t\treturn types.Timestamp{Time: v}, TimestampType, nil\n\tcase types.Null:\n\t\treturn v, NullType, nil\n\tcase *ListValue:\n\t\treturn v, ListType, nil\n\tcase *MapValue:\n\t\treturn v, MapType, nil\n\tcase *ObjectValue:\n\t\treturn v, v.objectType, nil\n\tdefault:\n\t\treturn nil, unknownType, fmt.Errorf(\"unsupported type: (%T)%v\", v, v)\n\t}\n}","line":{"from":142,"to":171}} {"id":100017283,"name":"newStructValue","signature":"func newStructValue() *structValue","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"func newStructValue() *structValue {\n\treturn \u0026structValue{\n\t\tFields: []*Field{},\n\t\tfieldMap: map[string]*Field{},\n\t}\n}","line":{"from":183,"to":188}} {"id":100017284,"name":"AddField","signature":"func (sv *structValue) AddField(field *Field)","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// AddField appends a MapField to the MapValue and indexes the field by name.\nfunc (sv *structValue) AddField(field *Field) {\n\tsv.Fields = append(sv.Fields, field)\n\tsv.fieldMap[field.Name] = field\n}","line":{"from":195,"to":199}} {"id":100017285,"name":"ConvertToNative","signature":"func (sv *structValue) ConvertToNative(typeDesc reflect.Type) (interface{}, error)","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// ConvertToNative converts the MapValue type to a native go types.\nfunc (sv *structValue) ConvertToNative(typeDesc reflect.Type) (interface{}, error) {\n\tif typeDesc.Kind() != reflect.Map \u0026\u0026\n\t\ttypeDesc.Kind() != reflect.Struct \u0026\u0026\n\t\ttypeDesc.Kind() != reflect.Pointer \u0026\u0026\n\t\ttypeDesc.Kind() != reflect.Interface {\n\t\treturn nil, fmt.Errorf(\"type conversion error from object to '%v'\", typeDesc)\n\t}\n\n\t// Unwrap pointers, but track their use.\n\tisPtr := false\n\tif typeDesc.Kind() == reflect.Pointer {\n\t\ttk := typeDesc\n\t\ttypeDesc = typeDesc.Elem()\n\t\tif typeDesc.Kind() == reflect.Pointer {\n\t\t\treturn nil, fmt.Errorf(\"unsupported type conversion to '%v'\", tk)\n\t\t}\n\t\tisPtr = true\n\t}\n\n\tif typeDesc.Kind() == reflect.Map {\n\t\tkeyType := typeDesc.Key()\n\t\tif keyType.Kind() != reflect.String \u0026\u0026 keyType.Kind() != reflect.Interface {\n\t\t\treturn nil, fmt.Errorf(\"object fields cannot be converted to type '%v'\", keyType)\n\t\t}\n\t\telemType := typeDesc.Elem()\n\t\tsz := len(sv.fieldMap)\n\t\tntvMap := reflect.MakeMapWithSize(typeDesc, sz)\n\t\tfor name, val := range sv.fieldMap {\n\t\t\trefVal, err := val.Ref.ConvertToNative(elemType)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tntvMap.SetMapIndex(reflect.ValueOf(name), reflect.ValueOf(refVal))\n\t\t}\n\t\treturn ntvMap.Interface(), nil\n\t}\n\n\tif typeDesc.Kind() == reflect.Struct {\n\t\tntvObjPtr := reflect.New(typeDesc)\n\t\tntvObj := ntvObjPtr.Elem()\n\t\tfor name, val := range sv.fieldMap {\n\t\t\tf := ntvObj.FieldByName(name)\n\t\t\tif !f.IsValid() {\n\t\t\t\treturn nil, fmt.Errorf(\"type conversion error, no such field %s in type %v\",\n\t\t\t\t\tname, typeDesc)\n\t\t\t}\n\t\t\tfv, err := val.Ref.ConvertToNative(f.Type())\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tf.Set(reflect.ValueOf(fv))\n\t\t}\n\t\tif isPtr {\n\t\t\treturn ntvObjPtr.Interface(), nil\n\t\t}\n\t\treturn ntvObj.Interface(), nil\n\t}\n\treturn nil, fmt.Errorf(\"type conversion error from object to '%v'\", typeDesc)\n}","line":{"from":201,"to":260}} {"id":100017286,"name":"GetField","signature":"func (sv *structValue) GetField(name string) (*Field, bool)","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// GetField returns a MapField by name if one exists.\nfunc (sv *structValue) GetField(name string) (*Field, bool) {\n\tfield, found := sv.fieldMap[name]\n\treturn field, found\n}","line":{"from":262,"to":266}} {"id":100017287,"name":"IsSet","signature":"func (sv *structValue) IsSet(key ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// IsSet returns whether the given field, which is defined, has also been set.\nfunc (sv *structValue) IsSet(key ref.Val) ref.Val {\n\tk, ok := key.(types.String)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(key)\n\t}\n\tname := string(k)\n\t_, found := sv.fieldMap[name]\n\treturn celBool(found)\n}","line":{"from":268,"to":277}} {"id":100017288,"name":"NewObjectValue","signature":"func NewObjectValue(sType *DeclType) *ObjectValue","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// NewObjectValue creates a struct value with a schema type and returns the empty ObjectValue.\nfunc NewObjectValue(sType *DeclType) *ObjectValue {\n\treturn \u0026ObjectValue{\n\t\tstructValue: newStructValue(),\n\t\tobjectType: sType,\n\t}\n}","line":{"from":279,"to":285}} {"id":100017289,"name":"ConvertToType","signature":"func (o *ObjectValue) ConvertToType(t ref.Type) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// ConvertToType is an implementation of the CEL ref.Val interface method.\nfunc (o *ObjectValue) ConvertToType(t ref.Type) ref.Val {\n\tif t == types.TypeType {\n\t\treturn types.NewObjectTypeValue(o.objectType.TypeName())\n\t}\n\tif t.TypeName() == o.objectType.TypeName() {\n\t\treturn o\n\t}\n\treturn types.NewErr(\"type conversion error from '%s' to '%s'\", o.Type(), t)\n}","line":{"from":294,"to":303}} {"id":100017290,"name":"Equal","signature":"func (o *ObjectValue) Equal(other ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// Equal returns true if the two object types are equal and their field values are equal.\nfunc (o *ObjectValue) Equal(other ref.Val) ref.Val {\n\t// Preserve CEL's homogeneous equality semantics.\n\tif o.objectType.TypeName() != other.Type().TypeName() {\n\t\treturn types.MaybeNoSuchOverloadErr(other)\n\t}\n\to2 := other.(traits.Indexer)\n\tfor name := range o.objectType.Fields {\n\t\tk := types.String(name)\n\t\tv := o.Get(k)\n\t\tov := o2.Get(k)\n\t\tvEq := v.Equal(ov)\n\t\tif vEq != types.True {\n\t\t\treturn vEq\n\t\t}\n\t}\n\treturn types.True\n}","line":{"from":305,"to":322}} {"id":100017291,"name":"Get","signature":"func (o *ObjectValue) Get(name ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// Get returns the value of the specified field.\n//\n// If the field is set, its value is returned. If the field is not set, the default value for the\n// field is returned thus allowing for safe-traversal and preserving proto-like field traversal\n// semantics for Open API Schema backed types.\nfunc (o *ObjectValue) Get(name ref.Val) ref.Val {\n\tn, ok := name.(types.String)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(n)\n\t}\n\tnameStr := string(n)\n\tfield, found := o.fieldMap[nameStr]\n\tif found {\n\t\treturn field.Ref.ExprValue()\n\t}\n\tfieldDef, found := o.objectType.Fields[nameStr]\n\tif !found {\n\t\treturn types.NewErr(\"no such field: %s\", nameStr)\n\t}\n\tdefValue := fieldDef.DefaultValue()\n\tif defValue != nil {\n\t\treturn defValue\n\t}\n\treturn types.NewErr(\"no default for type: %s\", fieldDef.TypeName())\n}","line":{"from":324,"to":348}} {"id":100017292,"name":"Type","signature":"func (o *ObjectValue) Type() ref.Type","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// Type returns the CEL type value of the object.\nfunc (o *ObjectValue) Type() ref.Type {\n\treturn o.objectType\n}","line":{"from":350,"to":353}} {"id":100017293,"name":"Value","signature":"func (o *ObjectValue) Value() interface{}","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// Value returns the Go-native representation of the object.\nfunc (o *ObjectValue) Value() interface{} {\n\treturn o\n}","line":{"from":355,"to":358}} {"id":100017294,"name":"NewMapValue","signature":"func NewMapValue() *MapValue","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// NewMapValue returns an empty MapValue.\nfunc NewMapValue() *MapValue {\n\treturn \u0026MapValue{\n\t\tstructValue: newStructValue(),\n\t}\n}","line":{"from":360,"to":365}} {"id":100017295,"name":"ConvertToObject","signature":"func (m *MapValue) ConvertToObject(declType *DeclType) *ObjectValue","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// ConvertToObject produces an ObjectValue from the MapValue with the associated schema type.\n//\n// The conversion is shallow and the memory shared between the Object and Map as all references\n// to the map are expected to be replaced with the Object reference.\nfunc (m *MapValue) ConvertToObject(declType *DeclType) *ObjectValue {\n\treturn \u0026ObjectValue{\n\t\tstructValue: m.structValue,\n\t\tobjectType: declType,\n\t}\n}","line":{"from":372,"to":381}} {"id":100017296,"name":"Contains","signature":"func (m *MapValue) Contains(key ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// Contains returns whether the given key is contained in the MapValue.\nfunc (m *MapValue) Contains(key ref.Val) ref.Val {\n\tv, found := m.Find(key)\n\tif v != nil \u0026\u0026 types.IsUnknownOrError(v) {\n\t\treturn v\n\t}\n\treturn celBool(found)\n}","line":{"from":383,"to":390}} {"id":100017297,"name":"ConvertToType","signature":"func (m *MapValue) ConvertToType(t ref.Type) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// ConvertToType converts the MapValue to another CEL type, if possible.\nfunc (m *MapValue) ConvertToType(t ref.Type) ref.Val {\n\tswitch t {\n\tcase types.MapType:\n\t\treturn m\n\tcase types.TypeType:\n\t\treturn types.MapType\n\t}\n\treturn types.NewErr(\"type conversion error from '%s' to '%s'\", m.Type(), t)\n}","line":{"from":392,"to":401}} {"id":100017298,"name":"Equal","signature":"func (m *MapValue) Equal(other ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// Equal returns true if the maps are of the same size, have the same keys, and the key-values\n// from each map are equal.\nfunc (m *MapValue) Equal(other ref.Val) ref.Val {\n\toMap, isMap := other.(traits.Mapper)\n\tif !isMap {\n\t\treturn types.MaybeNoSuchOverloadErr(other)\n\t}\n\tif m.Size() != oMap.Size() {\n\t\treturn types.False\n\t}\n\tfor name, field := range m.fieldMap {\n\t\tk := types.String(name)\n\t\tov, found := oMap.Find(k)\n\t\tif !found {\n\t\t\treturn types.False\n\t\t}\n\t\tv := field.Ref.ExprValue()\n\t\tvEq := v.Equal(ov)\n\t\tif vEq != types.True {\n\t\t\treturn vEq\n\t\t}\n\t}\n\treturn types.True\n}","line":{"from":403,"to":426}} {"id":100017299,"name":"Find","signature":"func (m *MapValue) Find(name ref.Val) (ref.Val, bool)","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// Find returns the value for the key in the map, if found.\nfunc (m *MapValue) Find(name ref.Val) (ref.Val, bool) {\n\t// Currently only maps with string keys are supported as this is best aligned with JSON,\n\t// and also much simpler to support.\n\tn, ok := name.(types.String)\n\tif !ok {\n\t\treturn types.MaybeNoSuchOverloadErr(n), true\n\t}\n\tnameStr := string(n)\n\tfield, found := m.fieldMap[nameStr]\n\tif found {\n\t\treturn field.Ref.ExprValue(), true\n\t}\n\treturn nil, false\n}","line":{"from":428,"to":442}} {"id":100017300,"name":"Get","signature":"func (m *MapValue) Get(key ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// Get returns the value for the key in the map, or error if not found.\nfunc (m *MapValue) Get(key ref.Val) ref.Val {\n\tv, found := m.Find(key)\n\tif found {\n\t\treturn v\n\t}\n\treturn types.ValOrErr(key, \"no such key: %v\", key)\n}","line":{"from":444,"to":451}} {"id":100017301,"name":"Iterator","signature":"func (m *MapValue) Iterator() traits.Iterator","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// Iterator produces a traits.Iterator which walks over the map keys.\n//\n// The Iterator is frequently used within comprehensions.\nfunc (m *MapValue) Iterator() traits.Iterator {\n\tkeys := make([]ref.Val, len(m.fieldMap))\n\ti := 0\n\tfor k := range m.fieldMap {\n\t\tkeys[i] = types.String(k)\n\t\ti++\n\t}\n\treturn \u0026baseMapIterator{\n\t\tbaseVal: \u0026baseVal{},\n\t\tkeys: keys,\n\t}\n}","line":{"from":453,"to":467}} {"id":100017302,"name":"Size","signature":"func (m *MapValue) Size() ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// Size returns the number of keys in the map.\nfunc (m *MapValue) Size() ref.Val {\n\treturn types.Int(len(m.Fields))\n}","line":{"from":469,"to":472}} {"id":100017303,"name":"Type","signature":"func (m *MapValue) Type() ref.Type","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// Type returns the CEL ref.Type for the map.\nfunc (m *MapValue) Type() ref.Type {\n\treturn types.MapType\n}","line":{"from":474,"to":477}} {"id":100017304,"name":"Value","signature":"func (m *MapValue) Value() interface{}","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// Value returns the Go-native representation of the MapValue.\nfunc (m *MapValue) Value() interface{} {\n\treturn m\n}","line":{"from":479,"to":482}} {"id":100017305,"name":"HasNext","signature":"func (it *baseMapIterator) HasNext() ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// HasNext implements the traits.Iterator interface method.\nfunc (it *baseMapIterator) HasNext() ref.Val {\n\tif it.idx \u003c len(it.keys) {\n\t\treturn types.True\n\t}\n\treturn types.False\n}","line":{"from":490,"to":496}} {"id":100017306,"name":"Next","signature":"func (it *baseMapIterator) Next() ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// Next implements the traits.Iterator interface method.\nfunc (it *baseMapIterator) Next() ref.Val {\n\tkey := it.keys[it.idx]\n\tit.idx++\n\treturn key\n}","line":{"from":498,"to":503}} {"id":100017307,"name":"Type","signature":"func (it *baseMapIterator) Type() ref.Type","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// Type implements the CEL ref.Val interface metohd.\nfunc (it *baseMapIterator) Type() ref.Type {\n\treturn types.IteratorType\n}","line":{"from":505,"to":508}} {"id":100017308,"name":"NewField","signature":"func NewField(id int64, name string) *Field","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// NewField returns a MapField instance with an empty DynValue that refers to the\n// specified parse node id and field name.\nfunc NewField(id int64, name string) *Field {\n\treturn \u0026Field{\n\t\tID: id,\n\t\tName: name,\n\t\tRef: NewEmptyDynValue(),\n\t}\n}","line":{"from":510,"to":518}} {"id":100017309,"name":"NewListValue","signature":"func NewListValue() *ListValue","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// NewListValue returns an empty ListValue instance.\nfunc NewListValue() *ListValue {\n\treturn \u0026ListValue{\n\t\tEntries: []*DynValue{},\n\t}\n}","line":{"from":527,"to":532}} {"id":100017310,"name":"Add","signature":"func (lv *ListValue) Add(other ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// Add concatenates two lists together to produce a new CEL list value.\nfunc (lv *ListValue) Add(other ref.Val) ref.Val {\n\toArr, isArr := other.(traits.Lister)\n\tif !isArr {\n\t\treturn types.MaybeNoSuchOverloadErr(other)\n\t}\n\tszRight := len(lv.Entries)\n\tszLeft := int(oArr.Size().(types.Int))\n\tsz := szRight + szLeft\n\tcombo := make([]ref.Val, sz)\n\tfor i := 0; i \u003c szRight; i++ {\n\t\tcombo[i] = lv.Entries[i].ExprValue()\n\t}\n\tfor i := 0; i \u003c szLeft; i++ {\n\t\tcombo[i+szRight] = oArr.Get(types.Int(i))\n\t}\n\treturn types.DefaultTypeAdapter.NativeToValue(combo)\n}","line":{"from":541,"to":558}} {"id":100017311,"name":"Append","signature":"func (lv *ListValue) Append(entry *DynValue)","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// Append adds another entry into the ListValue.\nfunc (lv *ListValue) Append(entry *DynValue) {\n\tlv.Entries = append(lv.Entries, entry)\n\t// The append resets all previously built indices.\n\tlv.initValueSet = sync.Once{}\n}","line":{"from":560,"to":565}} {"id":100017312,"name":"Contains","signature":"func (lv *ListValue) Contains(val ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// Contains returns whether the input `val` is equal to an element in the list.\n//\n// If any pair-wise comparison between the input value and the list element is an error, the\n// operation will return an error.\nfunc (lv *ListValue) Contains(val ref.Val) ref.Val {\n\tif types.IsUnknownOrError(val) {\n\t\treturn val\n\t}\n\tlv.initValueSet.Do(lv.finalizeValueSet)\n\tif lv.valueSet != nil {\n\t\t_, found := lv.valueSet[val]\n\t\tif found {\n\t\t\treturn types.True\n\t\t}\n\t\t// Instead of returning false, ensure that CEL's heterogeneous equality constraint\n\t\t// is satisfied by allowing pair-wise equality behavior to determine the outcome.\n\t}\n\tvar err ref.Val\n\tsz := len(lv.Entries)\n\tfor i := 0; i \u003c sz; i++ {\n\t\telem := lv.Entries[i]\n\t\tcmp := elem.Equal(val)\n\t\tb, ok := cmp.(types.Bool)\n\t\tif !ok \u0026\u0026 err == nil {\n\t\t\terr = types.MaybeNoSuchOverloadErr(cmp)\n\t\t}\n\t\tif b == types.True {\n\t\t\treturn types.True\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn types.False\n}","line":{"from":567,"to":601}} {"id":100017313,"name":"ConvertToNative","signature":"func (lv *ListValue) ConvertToNative(typeDesc reflect.Type) (interface{}, error)","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// ConvertToNative is an implementation of the CEL ref.Val method used to adapt between CEL types\n// and Go-native array-like types.\nfunc (lv *ListValue) ConvertToNative(typeDesc reflect.Type) (interface{}, error) {\n\t// Non-list conversion.\n\tif typeDesc.Kind() != reflect.Slice \u0026\u0026\n\t\ttypeDesc.Kind() != reflect.Array \u0026\u0026\n\t\ttypeDesc.Kind() != reflect.Interface {\n\t\treturn nil, fmt.Errorf(\"type conversion error from list to '%v'\", typeDesc)\n\t}\n\n\t// If the list is already assignable to the desired type return it.\n\tif reflect.TypeOf(lv).AssignableTo(typeDesc) {\n\t\treturn lv, nil\n\t}\n\n\t// List conversion.\n\totherElem := typeDesc.Elem()\n\n\t// Allow the element ConvertToNative() function to determine whether conversion is possible.\n\tsz := len(lv.Entries)\n\tnativeList := reflect.MakeSlice(typeDesc, int(sz), int(sz))\n\tfor i := 0; i \u003c sz; i++ {\n\t\telem := lv.Entries[i]\n\t\tnativeElemVal, err := elem.ConvertToNative(otherElem)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tnativeList.Index(int(i)).Set(reflect.ValueOf(nativeElemVal))\n\t}\n\treturn nativeList.Interface(), nil\n}","line":{"from":603,"to":633}} {"id":100017314,"name":"ConvertToType","signature":"func (lv *ListValue) ConvertToType(t ref.Type) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// ConvertToType converts the ListValue to another CEL type.\nfunc (lv *ListValue) ConvertToType(t ref.Type) ref.Val {\n\tswitch t {\n\tcase types.ListType:\n\t\treturn lv\n\tcase types.TypeType:\n\t\treturn types.ListType\n\t}\n\treturn types.NewErr(\"type conversion error from '%s' to '%s'\", ListType, t)\n}","line":{"from":635,"to":644}} {"id":100017315,"name":"Equal","signature":"func (lv *ListValue) Equal(other ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// Equal returns true if two lists are of the same size, and the values at each index are also\n// equal.\nfunc (lv *ListValue) Equal(other ref.Val) ref.Val {\n\toArr, isArr := other.(traits.Lister)\n\tif !isArr {\n\t\treturn types.MaybeNoSuchOverloadErr(other)\n\t}\n\tsz := types.Int(len(lv.Entries))\n\tif sz != oArr.Size() {\n\t\treturn types.False\n\t}\n\tfor i := types.Int(0); i \u003c sz; i++ {\n\t\tcmp := lv.Get(i).Equal(oArr.Get(i))\n\t\tif cmp != types.True {\n\t\t\treturn cmp\n\t\t}\n\t}\n\treturn types.True\n}","line":{"from":646,"to":664}} {"id":100017316,"name":"Get","signature":"func (lv *ListValue) Get(idx ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// Get returns the value at the given index.\n//\n// If the index is negative or greater than the size of the list, an error is returned.\nfunc (lv *ListValue) Get(idx ref.Val) ref.Val {\n\tiv, isInt := idx.(types.Int)\n\tif !isInt {\n\t\treturn types.ValOrErr(idx, \"unsupported index: %v\", idx)\n\t}\n\ti := int(iv)\n\tif i \u003c 0 || i \u003e= len(lv.Entries) {\n\t\treturn types.NewErr(\"index out of bounds: %v\", idx)\n\t}\n\treturn lv.Entries[i].ExprValue()\n}","line":{"from":666,"to":679}} {"id":100017317,"name":"Iterator","signature":"func (lv *ListValue) Iterator() traits.Iterator","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// Iterator produces a traits.Iterator suitable for use in CEL comprehension macros.\nfunc (lv *ListValue) Iterator() traits.Iterator {\n\treturn \u0026baseListIterator{\n\t\tgetter: lv.Get,\n\t\tsz: len(lv.Entries),\n\t}\n}","line":{"from":681,"to":687}} {"id":100017318,"name":"Size","signature":"func (lv *ListValue) Size() ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// Size returns the number of elements in the list.\nfunc (lv *ListValue) Size() ref.Val {\n\treturn types.Int(len(lv.Entries))\n}","line":{"from":689,"to":692}} {"id":100017319,"name":"Type","signature":"func (lv *ListValue) Type() ref.Type","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// Type returns the CEL ref.Type for the list.\nfunc (lv *ListValue) Type() ref.Type {\n\treturn types.ListType\n}","line":{"from":694,"to":697}} {"id":100017320,"name":"Value","signature":"func (lv *ListValue) Value() interface{}","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// Value returns the Go-native value.\nfunc (lv *ListValue) Value() interface{} {\n\treturn lv\n}","line":{"from":699,"to":702}} {"id":100017321,"name":"finalizeValueSet","signature":"func (lv *ListValue) finalizeValueSet()","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"// finalizeValueSet inspects the ListValue entries in order to make internal optimizations once all list\n// entries are known.\nfunc (lv *ListValue) finalizeValueSet() {\n\tvalueSet := make(map[ref.Val]struct{})\n\tfor _, e := range lv.Entries {\n\t\tswitch e.value.(type) {\n\t\tcase bool, float64, int64, string, uint64, types.Null, PlainTextValue:\n\t\t\tvalueSet[e.ExprValue()] = struct{}{}\n\t\tdefault:\n\t\t\tlv.valueSet = nil\n\t\t\treturn\n\t\t}\n\t}\n\tlv.valueSet = valueSet\n}","line":{"from":704,"to":718}} {"id":100017322,"name":"ConvertToNative","signature":"func (*baseVal) ConvertToNative(typeDesc reflect.Type) (interface{}, error)","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"func (*baseVal) ConvertToNative(typeDesc reflect.Type) (interface{}, error) {\n\treturn nil, fmt.Errorf(\"unsupported native conversion to: %v\", typeDesc)\n}","line":{"from":722,"to":724}} {"id":100017323,"name":"ConvertToType","signature":"func (*baseVal) ConvertToType(t ref.Type) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"func (*baseVal) ConvertToType(t ref.Type) ref.Val {\n\treturn types.NewErr(\"unsupported type conversion to: %v\", t)\n}","line":{"from":726,"to":728}} {"id":100017324,"name":"Equal","signature":"func (*baseVal) Equal(other ref.Val) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"func (*baseVal) Equal(other ref.Val) ref.Val {\n\treturn types.NewErr(\"unsupported equality test between instances\")\n}","line":{"from":730,"to":732}} {"id":100017325,"name":"Value","signature":"func (v *baseVal) Value() interface{}","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"func (v *baseVal) Value() interface{} {\n\treturn nil\n}","line":{"from":734,"to":736}} {"id":100017326,"name":"HasNext","signature":"func (it *baseListIterator) HasNext() ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"func (it *baseListIterator) HasNext() ref.Val {\n\tif it.idx \u003c it.sz {\n\t\treturn types.True\n\t}\n\treturn types.False\n}","line":{"from":745,"to":750}} {"id":100017327,"name":"Next","signature":"func (it *baseListIterator) Next() ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"func (it *baseListIterator) Next() ref.Val {\n\tv := it.getter(types.Int(it.idx))\n\tit.idx++\n\treturn v\n}","line":{"from":752,"to":756}} {"id":100017328,"name":"Type","signature":"func (it *baseListIterator) Type() ref.Type","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"func (it *baseListIterator) Type() ref.Type {\n\treturn types.IteratorType\n}","line":{"from":758,"to":760}} {"id":100017329,"name":"celBool","signature":"func celBool(pred bool) ref.Val","file":"staging/src/k8s.io/apiserver/pkg/cel/value.go","code":"func celBool(pred bool) ref.Val {\n\tif pred {\n\t\treturn types.True\n\t}\n\treturn types.False\n}","line":{"from":762,"to":767}} {"id":100017330,"name":"MajorMinor","signature":"func MajorMinor(v version.Info) (int, int, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/deprecation/deprecation.go","code":"// MajorMinor parses a numeric major/minor version from the provided version info.\n// The minor version drops all characters after the first non-digit character:\n//\n//\tversion.Info{Major:\"1\", Minor:\"2+\"} -\u003e 1,2\n//\tversion.Info{Major:\"1\", Minor:\"2.3-build4\"} -\u003e 1,2\nfunc MajorMinor(v version.Info) (int, int, error) {\n\tmajor, err := strconv.Atoi(v.Major)\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\tminor, err := strconv.Atoi(leadingDigits.FindString(v.Minor))\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\treturn major, minor, nil\n}","line":{"from":44,"to":59}} {"id":100017331,"name":"IsDeprecated","signature":"func IsDeprecated(obj runtime.Object, currentMajor, currentMinor int) bool","file":"staging/src/k8s.io/apiserver/pkg/endpoints/deprecation/deprecation.go","code":"// IsDeprecated returns true if obj implements APILifecycleDeprecated() and returns\n// a major/minor version that is non-zero and is \u003c= the specified current major/minor version.\nfunc IsDeprecated(obj runtime.Object, currentMajor, currentMinor int) bool {\n\tdeprecated, isDeprecated := obj.(apiLifecycleDeprecated)\n\tif !isDeprecated {\n\t\treturn false\n\t}\n\n\tdeprecatedMajor, deprecatedMinor := deprecated.APILifecycleDeprecated()\n\t// no deprecation version expressed\n\tif deprecatedMajor == 0 \u0026\u0026 deprecatedMinor == 0 {\n\t\treturn false\n\t}\n\t// no current version info available\n\tif currentMajor == 0 \u0026\u0026 currentMinor == 0 {\n\t\treturn true\n\t}\n\t// compare deprecation version to current version\n\tif deprecatedMajor \u003e currentMajor {\n\t\treturn false\n\t}\n\tif deprecatedMajor == currentMajor \u0026\u0026 deprecatedMinor \u003e currentMinor {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":61,"to":86}} {"id":100017332,"name":"RemovedRelease","signature":"func RemovedRelease(obj runtime.Object) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/deprecation/deprecation.go","code":"// RemovedRelease returns the major/minor version in which the given object is unavailable (in the form \"\u003cmajor\u003e.\u003cminor\u003e\")\n// if the object implements APILifecycleRemoved() to indicate a non-zero removal version, and returns an empty string otherwise.\nfunc RemovedRelease(obj runtime.Object) string {\n\tif removed, hasRemovalInfo := obj.(apiLifecycleRemoved); hasRemovalInfo {\n\t\tremovedMajor, removedMinor := removed.APILifecycleRemoved()\n\t\tif removedMajor != 0 || removedMinor != 0 {\n\t\t\treturn fmt.Sprintf(\"%d.%d\", removedMajor, removedMinor)\n\t\t}\n\t}\n\treturn \"\"\n}","line":{"from":88,"to":98}} {"id":100017333,"name":"WarningMessage","signature":"func WarningMessage(obj runtime.Object) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/deprecation/deprecation.go","code":"// WarningMessage returns a human-readable deprecation warning if the object implements APILifecycleDeprecated()\n// to indicate a non-zero deprecated major/minor version and has a populated GetObjectKind().GroupVersionKind().\nfunc WarningMessage(obj runtime.Object) string {\n\tdeprecated, isDeprecated := obj.(apiLifecycleDeprecated)\n\tif !isDeprecated {\n\t\treturn \"\"\n\t}\n\n\tdeprecatedMajor, deprecatedMinor := deprecated.APILifecycleDeprecated()\n\tif deprecatedMajor == 0 \u0026\u0026 deprecatedMinor == 0 {\n\t\treturn \"\"\n\t}\n\n\tgvk := obj.GetObjectKind().GroupVersionKind()\n\tif gvk.Empty() {\n\t\treturn \"\"\n\t}\n\tdeprecationWarning := fmt.Sprintf(\"%s %s is deprecated in v%d.%d+\", gvk.GroupVersion().String(), gvk.Kind, deprecatedMajor, deprecatedMinor)\n\n\tif removed, hasRemovalInfo := obj.(apiLifecycleRemoved); hasRemovalInfo {\n\t\tremovedMajor, removedMinor := removed.APILifecycleRemoved()\n\t\tif removedMajor != 0 || removedMinor != 0 {\n\t\t\tdeprecationWarning = deprecationWarning + fmt.Sprintf(\", unavailable in v%d.%d+\", removedMajor, removedMinor)\n\t\t}\n\t}\n\n\tif replaced, hasReplacement := obj.(apiLifecycleReplacement); hasReplacement {\n\t\treplacement := replaced.APILifecycleReplacement()\n\t\tif !replacement.Empty() {\n\t\t\tdeprecationWarning = deprecationWarning + fmt.Sprintf(\"; use %s %s\", replacement.GroupVersion().String(), replacement.Kind)\n\t\t}\n\t}\n\n\treturn deprecationWarning\n}","line":{"from":100,"to":134}} {"id":100017334,"name":"ServerAddressByClientCIDRs","signature":"func (d DefaultAddresses) ServerAddressByClientCIDRs(clientIP net.IP) []metav1.ServerAddressByClientCIDR","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/addresses.go","code":"func (d DefaultAddresses) ServerAddressByClientCIDRs(clientIP net.IP) []metav1.ServerAddressByClientCIDR {\n\taddressCIDRMap := []metav1.ServerAddressByClientCIDR{\n\t\t{\n\t\t\tClientCIDR: \"0.0.0.0/0\",\n\t\t\tServerAddress: d.DefaultAddress,\n\t\t},\n\t}\n\n\tfor _, rule := range d.CIDRRules {\n\t\taddressCIDRMap = append(addressCIDRMap, rule.ServerAddressByClientCIDRs(clientIP)...)\n\t}\n\treturn addressCIDRMap\n}","line":{"from":48,"to":60}} {"id":100017335,"name":"ServerAddressByClientCIDRs","signature":"func (d CIDRRule) ServerAddressByClientCIDRs(clientIP net.IP) []metav1.ServerAddressByClientCIDR","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/addresses.go","code":"func (d CIDRRule) ServerAddressByClientCIDRs(clientIP net.IP) []metav1.ServerAddressByClientCIDR {\n\taddressCIDRMap := []metav1.ServerAddressByClientCIDR{}\n\n\tif d.IPRange.Contains(clientIP) {\n\t\taddressCIDRMap = append(addressCIDRMap, metav1.ServerAddressByClientCIDR{\n\t\t\tClientCIDR: d.IPRange.String(),\n\t\t\tServerAddress: d.Address,\n\t\t})\n\t}\n\treturn addressCIDRMap\n}","line":{"from":62,"to":72}} {"id":100017336,"name":"ServeHTTPWithETag","signature":"func ServeHTTPWithETag(","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/etag.go","code":"// Attaches Cache-Busting functionality to an endpoint\n// - Sets ETag header to provided hash\n// - Replies with 304 Not Modified, if If-None-Match header matches hash\n//\n// hash should be the value of calculateETag on object. If hash is empty, then\n// the object is simply serialized without E-Tag functionality\nfunc ServeHTTPWithETag(\n\tobject runtime.Object,\n\thash string,\n\tserializer runtime.NegotiatedSerializer,\n\tw http.ResponseWriter,\n\treq *http.Request,\n) {\n\t// ETag must be enclosed in double quotes:\n\t// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag\n\tquotedHash := strconv.Quote(hash)\n\tw.Header().Set(\"ETag\", quotedHash)\n\tw.Header().Set(\"Vary\", \"Accept\")\n\tw.Header().Set(\"Cache-Control\", \"public\")\n\n\t// If Request includes If-None-Match and matches hash, reply with 304\n\t// Otherwise, we delegate to the handler for actual content\n\t//\n\t// According to documentation, An Etag within an If-None-Match\n\t// header will be enclosed within double quotes:\n\t// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-None-Match#directives\n\tif clientCachedHash := req.Header.Get(\"If-None-Match\"); quotedHash == clientCachedHash {\n\t\tw.WriteHeader(http.StatusNotModified)\n\t\treturn\n\t}\n\n\tresponsewriters.WriteObjectNegotiated(\n\t\tserializer,\n\t\tDiscoveryEndpointRestrictions,\n\t\tAggregatedDiscoveryGV,\n\t\tw,\n\t\treq,\n\t\thttp.StatusOK,\n\t\tobject,\n\t\ttrue,\n\t)\n}","line":{"from":33,"to":74}} {"id":100017337,"name":"calculateETag","signature":"func calculateETag(resources interface{}) (string, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/etag.go","code":"func calculateETag(resources interface{}) (string, error) {\n\tserialized, err := json.Marshal(resources)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn fmt.Sprintf(\"%X\", sha512.Sum512(serialized)), nil\n}","line":{"from":76,"to":83}} {"id":100017338,"name":"AddGroupVersion","signature":"func (rm resourceManager) AddGroupVersion(groupName string, value apidiscoveryv2beta1.APIVersionDiscovery)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/handler.go","code":"func (rm resourceManager) AddGroupVersion(groupName string, value apidiscoveryv2beta1.APIVersionDiscovery) {\n\trm.resourceDiscoveryManager.AddGroupVersion(rm.source, groupName, value)\n}","line":{"from":90,"to":92}} {"id":100017339,"name":"SetGroupVersionPriority","signature":"func (rm resourceManager) SetGroupVersionPriority(gv metav1.GroupVersion, grouppriority, versionpriority int)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/handler.go","code":"func (rm resourceManager) SetGroupVersionPriority(gv metav1.GroupVersion, grouppriority, versionpriority int) {\n\trm.resourceDiscoveryManager.SetGroupVersionPriority(rm.source, gv, grouppriority, versionpriority)\n}","line":{"from":93,"to":95}} {"id":100017340,"name":"RemoveGroup","signature":"func (rm resourceManager) RemoveGroup(groupName string)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/handler.go","code":"func (rm resourceManager) RemoveGroup(groupName string) {\n\trm.resourceDiscoveryManager.RemoveGroup(rm.source, groupName)\n}","line":{"from":96,"to":98}} {"id":100017341,"name":"RemoveGroupVersion","signature":"func (rm resourceManager) RemoveGroupVersion(gv metav1.GroupVersion)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/handler.go","code":"func (rm resourceManager) RemoveGroupVersion(gv metav1.GroupVersion) {\n\trm.resourceDiscoveryManager.RemoveGroupVersion(rm.source, gv)\n}","line":{"from":99,"to":101}} {"id":100017342,"name":"SetGroups","signature":"func (rm resourceManager) SetGroups(groups []apidiscoveryv2beta1.APIGroupDiscovery)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/handler.go","code":"func (rm resourceManager) SetGroups(groups []apidiscoveryv2beta1.APIGroupDiscovery) {\n\trm.resourceDiscoveryManager.SetGroups(rm.source, groups)\n}","line":{"from":102,"to":104}} {"id":100017343,"name":"WithSource","signature":"func (rm resourceManager) WithSource(source Source) ResourceManager","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/handler.go","code":"func (rm resourceManager) WithSource(source Source) ResourceManager {\n\treturn resourceManager{\n\t\tsource: source,\n\t\tresourceDiscoveryManager: rm.resourceDiscoveryManager,\n\t}\n}","line":{"from":106,"to":111}} {"id":100017344,"name":"NewResourceManager","signature":"func NewResourceManager(path string) ResourceManager","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/handler.go","code":"func NewResourceManager(path string) ResourceManager {\n\tscheme := runtime.NewScheme()\n\tcodecs := serializer.NewCodecFactory(scheme)\n\tutilruntime.Must(apidiscoveryv2beta1.AddToScheme(scheme))\n\trdm := \u0026resourceDiscoveryManager{\n\t\tserializer: codecs,\n\t\tversionPriorities: make(map[groupVersionKey]priorityInfo),\n\t}\n\trdm.serveHTTPFunc = metrics.InstrumentHandlerFunc(\"GET\",\n\t\t/* group = */ \"\",\n\t\t/* version = */ \"\",\n\t\t/* resource = */ \"\",\n\t\t/* subresource = */ path,\n\t\t/* scope = */ \"\",\n\t\t/* component = */ metrics.APIServerComponent,\n\t\t/* deprecated */ false,\n\t\t/* removedRelease */ \"\",\n\t\trdm.serveHTTP)\n\treturn resourceManager{\n\t\tsource: BuiltinSource,\n\t\tresourceDiscoveryManager: rdm,\n\t}\n}","line":{"from":145,"to":167}} {"id":100017345,"name":"SetGroupVersionPriority","signature":"func (rdm *resourceDiscoveryManager) SetGroupVersionPriority(source Source, gv metav1.GroupVersion, groupPriorityMinimum, versionPriority int)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/handler.go","code":"func (rdm *resourceDiscoveryManager) SetGroupVersionPriority(source Source, gv metav1.GroupVersion, groupPriorityMinimum, versionPriority int) {\n\trdm.lock.Lock()\n\tdefer rdm.lock.Unlock()\n\n\tkey := groupVersionKey{\n\t\tGroupVersion: gv,\n\t\tsource: source,\n\t}\n\trdm.versionPriorities[key] = priorityInfo{\n\t\tGroupPriorityMinimum: groupPriorityMinimum,\n\t\tVersionPriority: versionPriority,\n\t}\n\trdm.cache.Store(nil)\n}","line":{"from":169,"to":182}} {"id":100017346,"name":"SetGroups","signature":"func (rdm *resourceDiscoveryManager) SetGroups(source Source, groups []apidiscoveryv2beta1.APIGroupDiscovery)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/handler.go","code":"func (rdm *resourceDiscoveryManager) SetGroups(source Source, groups []apidiscoveryv2beta1.APIGroupDiscovery) {\n\trdm.lock.Lock()\n\tdefer rdm.lock.Unlock()\n\n\trdm.apiGroups = nil\n\trdm.cache.Store(nil)\n\n\tfor _, group := range groups {\n\t\tfor _, version := range group.Versions {\n\t\t\trdm.addGroupVersionLocked(source, group.Name, version)\n\t\t}\n\t}\n\n\t// Filter unused out priority entries\n\tfor gv := range rdm.versionPriorities {\n\t\tkey := groupKey{\n\t\t\tsource: source,\n\t\t\tname: gv.Group,\n\t\t}\n\t\tentry, exists := rdm.apiGroups[key]\n\t\tif !exists {\n\t\t\tdelete(rdm.versionPriorities, gv)\n\t\t\tcontinue\n\t\t}\n\n\t\tcontainsVersion := false\n\n\t\tfor _, v := range entry.Versions {\n\t\t\tif v.Version == gv.Version {\n\t\t\t\tcontainsVersion = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !containsVersion {\n\t\t\tdelete(rdm.versionPriorities, gv)\n\t\t}\n\t}\n}","line":{"from":184,"to":222}} {"id":100017347,"name":"AddGroupVersion","signature":"func (rdm *resourceDiscoveryManager) AddGroupVersion(source Source, groupName string, value apidiscoveryv2beta1.APIVersionDiscovery)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/handler.go","code":"func (rdm *resourceDiscoveryManager) AddGroupVersion(source Source, groupName string, value apidiscoveryv2beta1.APIVersionDiscovery) {\n\trdm.lock.Lock()\n\tdefer rdm.lock.Unlock()\n\n\trdm.addGroupVersionLocked(source, groupName, value)\n}","line":{"from":224,"to":229}} {"id":100017348,"name":"addGroupVersionLocked","signature":"func (rdm *resourceDiscoveryManager) addGroupVersionLocked(source Source, groupName string, value apidiscoveryv2beta1.APIVersionDiscovery)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/handler.go","code":"func (rdm *resourceDiscoveryManager) addGroupVersionLocked(source Source, groupName string, value apidiscoveryv2beta1.APIVersionDiscovery) {\n\tklog.Infof(\"Adding GroupVersion %s %s to ResourceManager\", groupName, value.Version)\n\n\tif rdm.apiGroups == nil {\n\t\trdm.apiGroups = make(map[groupKey]*apidiscoveryv2beta1.APIGroupDiscovery)\n\t}\n\n\tkey := groupKey{\n\t\tsource: source,\n\t\tname: groupName,\n\t}\n\n\tif existing, groupExists := rdm.apiGroups[key]; groupExists {\n\t\t// If this version already exists, replace it\n\t\tversionExists := false\n\n\t\t// Not very efficient, but in practice there are generally not many versions\n\t\tfor i := range existing.Versions {\n\t\t\tif existing.Versions[i].Version == value.Version {\n\t\t\t\t// The new gv is the exact same as what is already in\n\t\t\t\t// the map. This is a noop and cache should not be\n\t\t\t\t// invalidated.\n\t\t\t\tif reflect.DeepEqual(existing.Versions[i], value) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\texisting.Versions[i] = value\n\t\t\t\tversionExists = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !versionExists {\n\t\t\texisting.Versions = append(existing.Versions, value)\n\t\t}\n\n\t} else {\n\t\tgroup := \u0026apidiscoveryv2beta1.APIGroupDiscovery{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: groupName,\n\t\t\t},\n\t\t\tVersions: []apidiscoveryv2beta1.APIVersionDiscovery{value},\n\t\t}\n\t\trdm.apiGroups[key] = group\n\t}\n\n\tgv := metav1.GroupVersion{Group: groupName, Version: value.Version}\n\tgvKey := groupVersionKey{\n\t\tGroupVersion: gv,\n\t\tsource: source,\n\t}\n\tif _, ok := rdm.versionPriorities[gvKey]; !ok {\n\t\trdm.versionPriorities[gvKey] = priorityInfo{\n\t\t\tGroupPriorityMinimum: 1000,\n\t\t\tVersionPriority: 15,\n\t\t}\n\t}\n\n\t// Reset response document so it is recreated lazily\n\trdm.cache.Store(nil)\n}","line":{"from":231,"to":291}} {"id":100017349,"name":"RemoveGroupVersion","signature":"func (rdm *resourceDiscoveryManager) RemoveGroupVersion(source Source, apiGroup metav1.GroupVersion)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/handler.go","code":"func (rdm *resourceDiscoveryManager) RemoveGroupVersion(source Source, apiGroup metav1.GroupVersion) {\n\trdm.lock.Lock()\n\tdefer rdm.lock.Unlock()\n\n\tkey := groupKey{\n\t\tsource: source,\n\t\tname: apiGroup.Group,\n\t}\n\n\tgroup, exists := rdm.apiGroups[key]\n\tif !exists {\n\t\treturn\n\t}\n\n\tmodified := false\n\tfor i := range group.Versions {\n\t\tif group.Versions[i].Version == apiGroup.Version {\n\t\t\tgroup.Versions = append(group.Versions[:i], group.Versions[i+1:]...)\n\t\t\tmodified = true\n\t\t\tbreak\n\t\t}\n\t}\n\t// If no modification was done, cache does not need to be cleared\n\tif !modified {\n\t\treturn\n\t}\n\n\tgvKey := groupVersionKey{\n\t\tGroupVersion: apiGroup,\n\t\tsource: source,\n\t}\n\n\tdelete(rdm.versionPriorities, gvKey)\n\tif len(group.Versions) == 0 {\n\t\tdelete(rdm.apiGroups, key)\n\t}\n\n\t// Reset response document so it is recreated lazily\n\trdm.cache.Store(nil)\n}","line":{"from":293,"to":332}} {"id":100017350,"name":"RemoveGroup","signature":"func (rdm *resourceDiscoveryManager) RemoveGroup(source Source, groupName string)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/handler.go","code":"func (rdm *resourceDiscoveryManager) RemoveGroup(source Source, groupName string) {\n\trdm.lock.Lock()\n\tdefer rdm.lock.Unlock()\n\n\tkey := groupKey{\n\t\tsource: source,\n\t\tname: groupName,\n\t}\n\n\tdelete(rdm.apiGroups, key)\n\n\tfor k := range rdm.versionPriorities {\n\t\tif k.Group == groupName \u0026\u0026 k.source == source {\n\t\t\tdelete(rdm.versionPriorities, k)\n\t\t}\n\t}\n\n\t// Reset response document so it is recreated lazily\n\trdm.cache.Store(nil)\n}","line":{"from":334,"to":353}} {"id":100017351,"name":"calculateAPIGroupsLocked","signature":"func (rdm *resourceDiscoveryManager) calculateAPIGroupsLocked() []apidiscoveryv2beta1.APIGroupDiscovery","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/handler.go","code":"// Prepares the api group list for serving by converting them from map into\n// list and sorting them according to insertion order\nfunc (rdm *resourceDiscoveryManager) calculateAPIGroupsLocked() []apidiscoveryv2beta1.APIGroupDiscovery {\n\tregenerationCounter.Inc()\n\t// Re-order the apiGroups by their priority.\n\tgroups := []apidiscoveryv2beta1.APIGroupDiscovery{}\n\n\tgroupsToUse := map[string]apidiscoveryv2beta1.APIGroupDiscovery{}\n\tsourcesUsed := map[metav1.GroupVersion]Source{}\n\n\tfor key, group := range rdm.apiGroups {\n\t\tif existing, ok := groupsToUse[key.name]; ok {\n\t\t\tfor _, v := range group.Versions {\n\t\t\t\tgv := metav1.GroupVersion{Group: key.name, Version: v.Version}\n\n\t\t\t\t// Skip groupversions we've already seen before. Only DefaultSource\n\t\t\t\t// takes precedence\n\t\t\t\tif usedSource, seen := sourcesUsed[gv]; seen \u0026\u0026 key.source \u003e= usedSource {\n\t\t\t\t\tcontinue\n\t\t\t\t} else if seen {\n\t\t\t\t\t// Find the index of the duplicate version and replace\n\t\t\t\t\tfor i := 0; i \u003c len(existing.Versions); i++ {\n\t\t\t\t\t\tif existing.Versions[i].Version == v.Version {\n\t\t\t\t\t\t\texisting.Versions[i] = v\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\t// New group-version, just append\n\t\t\t\t\texisting.Versions = append(existing.Versions, v)\n\t\t\t\t}\n\n\t\t\t\tsourcesUsed[gv] = key.source\n\t\t\t\tgroupsToUse[key.name] = existing\n\t\t\t}\n\t\t\t// Check to see if we have overlapping versions. If we do, take the one\n\t\t\t// with highest source precedence\n\t\t} else {\n\t\t\tgroupsToUse[key.name] = *group.DeepCopy()\n\t\t\tfor _, v := range group.Versions {\n\t\t\t\tgv := metav1.GroupVersion{Group: key.name, Version: v.Version}\n\t\t\t\tsourcesUsed[gv] = key.source\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, group := range groupsToUse {\n\n\t\t// Re-order versions based on their priority. Use kube-aware string\n\t\t// comparison as a tie breaker\n\t\tsort.SliceStable(group.Versions, func(i, j int) bool {\n\t\t\tiVersion := group.Versions[i].Version\n\t\t\tjVersion := group.Versions[j].Version\n\n\t\t\tiGV := metav1.GroupVersion{Group: group.Name, Version: iVersion}\n\t\t\tjGV := metav1.GroupVersion{Group: group.Name, Version: jVersion}\n\n\t\t\tiSource := sourcesUsed[iGV]\n\t\t\tjSource := sourcesUsed[jGV]\n\n\t\t\tiPriority := rdm.versionPriorities[groupVersionKey{iGV, iSource}].VersionPriority\n\t\t\tjPriority := rdm.versionPriorities[groupVersionKey{jGV, jSource}].VersionPriority\n\n\t\t\t// Sort by version string comparator if priority is equal\n\t\t\tif iPriority == jPriority {\n\t\t\t\treturn version.CompareKubeAwareVersionStrings(iVersion, jVersion) \u003e 0\n\t\t\t}\n\n\t\t\t// i sorts before j if it has a higher priority\n\t\t\treturn iPriority \u003e jPriority\n\t\t})\n\n\t\tgroups = append(groups, group)\n\t}\n\n\t// For each group, determine the highest minimum group priority and use that\n\tpriorities := map[string]int{}\n\tfor gv, info := range rdm.versionPriorities {\n\t\tif source := sourcesUsed[gv.GroupVersion]; source != gv.source {\n\t\t\tcontinue\n\t\t}\n\n\t\tif existing, exists := priorities[gv.Group]; exists {\n\t\t\tif existing \u003c info.GroupPriorityMinimum {\n\t\t\t\tpriorities[gv.Group] = info.GroupPriorityMinimum\n\t\t\t}\n\t\t} else {\n\t\t\tpriorities[gv.Group] = info.GroupPriorityMinimum\n\t\t}\n\t}\n\n\tsort.SliceStable(groups, func(i, j int) bool {\n\t\tiName := groups[i].Name\n\t\tjName := groups[j].Name\n\n\t\t// Default to 0 priority by default\n\t\tiPriority := priorities[iName]\n\t\tjPriority := priorities[jName]\n\n\t\t// Sort discovery based on apiservice priority.\n\t\t// Duplicated from staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/v1/helpers.go\n\t\tif iPriority == jPriority {\n\t\t\t// Equal priority uses name to break ties\n\t\t\treturn iName \u003c jName\n\t\t}\n\n\t\t// i sorts before j if it has a higher priority\n\t\treturn iPriority \u003e jPriority\n\t})\n\n\treturn groups\n}","line":{"from":355,"to":467}} {"id":100017352,"name":"fetchFromCache","signature":"func (rdm *resourceDiscoveryManager) fetchFromCache() *cachedGroupList","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/handler.go","code":"// Fetches from cache if it exists. If cache is empty, create it.\nfunc (rdm *resourceDiscoveryManager) fetchFromCache() *cachedGroupList {\n\trdm.lock.RLock()\n\tdefer rdm.lock.RUnlock()\n\n\tcacheLoad := rdm.cache.Load()\n\tif cacheLoad != nil {\n\t\treturn cacheLoad\n\t}\n\tresponse := apidiscoveryv2beta1.APIGroupDiscoveryList{\n\t\tItems: rdm.calculateAPIGroupsLocked(),\n\t}\n\tetag, err := calculateETag(response)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to calculate etag for discovery document: %s\", etag)\n\t\tetag = \"\"\n\t}\n\tcached := \u0026cachedGroupList{\n\t\tcachedResponse: response,\n\t\tcachedResponseETag: etag,\n\t}\n\trdm.cache.Store(cached)\n\treturn cached\n}","line":{"from":469,"to":492}} {"id":100017353,"name":"ServeHTTP","signature":"func (rdm *resourceDiscoveryManager) ServeHTTP(resp http.ResponseWriter, req *http.Request)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/handler.go","code":"func (rdm *resourceDiscoveryManager) ServeHTTP(resp http.ResponseWriter, req *http.Request) {\n\trdm.serveHTTPFunc(resp, req)\n}","line":{"from":499,"to":501}} {"id":100017354,"name":"serveHTTP","signature":"func (rdm *resourceDiscoveryManager) serveHTTP(resp http.ResponseWriter, req *http.Request)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/handler.go","code":"func (rdm *resourceDiscoveryManager) serveHTTP(resp http.ResponseWriter, req *http.Request) {\n\tcache := rdm.fetchFromCache()\n\tresponse := cache.cachedResponse\n\tetag := cache.cachedResponseETag\n\n\tif len(etag) \u003e 0 {\n\t\t// Use proper e-tag headers if one is available\n\t\tServeHTTPWithETag(\n\t\t\t\u0026response,\n\t\t\tetag,\n\t\t\trdm.serializer,\n\t\t\tresp,\n\t\t\treq,\n\t\t)\n\t} else {\n\t\t// Default to normal response in rare case etag is\n\t\t// not cached with the object for some reason.\n\t\tresponsewriters.WriteObjectNegotiated(\n\t\t\trdm.serializer,\n\t\t\tDiscoveryEndpointRestrictions,\n\t\t\tAggregatedDiscoveryGV,\n\t\t\tresp,\n\t\t\treq,\n\t\t\thttp.StatusOK,\n\t\t\t\u0026response,\n\t\t\ttrue,\n\t\t)\n\t}\n}","line":{"from":503,"to":531}} {"id":100017355,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/metrics.go","code":"func init() {\n\tlegacyregistry.MustRegister(regenerationCounter)\n}","line":{"from":34,"to":36}} {"id":100017356,"name":"AllowsMediaTypeTransform","signature":"func (discoveryEndpointRestrictions) AllowsMediaTypeTransform(mimeType string, mimeSubType string, gvk *schema.GroupVersionKind) bool","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/negotiation.go","code":"func (discoveryEndpointRestrictions) AllowsMediaTypeTransform(mimeType string, mimeSubType string, gvk *schema.GroupVersionKind) bool {\n\treturn IsAggregatedDiscoveryGVK(gvk)\n}","line":{"from":32,"to":34}} {"id":100017357,"name":"AllowsServerVersion","signature":"func (discoveryEndpointRestrictions) AllowsServerVersion(string) bool { return false }","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/negotiation.go","code":"func (discoveryEndpointRestrictions) AllowsServerVersion(string) bool { return false }","line":{"from":36,"to":36}} {"id":100017358,"name":"AllowsStreamSchema","signature":"func (discoveryEndpointRestrictions) AllowsStreamSchema(s string) bool { return s == \"watch\" }","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/negotiation.go","code":"func (discoveryEndpointRestrictions) AllowsStreamSchema(s string) bool { return s == \"watch\" }","line":{"from":37,"to":37}} {"id":100017359,"name":"IsAggregatedDiscoveryGVK","signature":"func IsAggregatedDiscoveryGVK(gvk *schema.GroupVersionKind) bool","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/negotiation.go","code":"// IsAggregatedDiscoveryGVK checks if a provided GVK is the GVK for serving aggregated discovery.\nfunc IsAggregatedDiscoveryGVK(gvk *schema.GroupVersionKind) bool {\n\tif gvk != nil {\n\t\treturn gvk.Group == \"apidiscovery.k8s.io\" \u0026\u0026 gvk.Version == \"v2beta1\" \u0026\u0026 gvk.Kind == \"APIGroupDiscoveryList\"\n\t}\n\treturn false\n}","line":{"from":39,"to":45}} {"id":100017360,"name":"ServeHTTP","signature":"func (wrapped *WrappedHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/wrapper.go","code":"func (wrapped *WrappedHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {\n\tif utilfeature.DefaultFeatureGate.Enabled(genericfeatures.AggregatedDiscoveryEndpoint) {\n\t\tmediaType, _ := negotiation.NegotiateMediaTypeOptions(req.Header.Get(\"Accept\"), wrapped.s.SupportedMediaTypes(), DiscoveryEndpointRestrictions)\n\t\t// mediaType.Convert looks at the request accept headers and is used to control whether the discovery document will be aggregated.\n\t\tif IsAggregatedDiscoveryGVK(mediaType.Convert) {\n\t\t\twrapped.aggHandler.ServeHTTP(resp, req)\n\t\t\treturn\n\t\t}\n\t}\n\twrapped.handler.ServeHTTP(resp, req)\n}","line":{"from":39,"to":49}} {"id":100017361,"name":"restfulHandle","signature":"func (wrapped *WrappedHandler) restfulHandle(req *restful.Request, resp *restful.Response)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/wrapper.go","code":"func (wrapped *WrappedHandler) restfulHandle(req *restful.Request, resp *restful.Response) {\n\twrapped.ServeHTTP(resp.ResponseWriter, req.Request)\n}","line":{"from":51,"to":53}} {"id":100017362,"name":"GenerateWebService","signature":"func (wrapped *WrappedHandler) GenerateWebService(prefix string, returnType interface{}) *restful.WebService","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/wrapper.go","code":"func (wrapped *WrappedHandler) GenerateWebService(prefix string, returnType interface{}) *restful.WebService {\n\tmediaTypes, _ := negotiation.MediaTypesForSerializer(wrapped.s)\n\tws := new(restful.WebService)\n\tws.Path(prefix)\n\tws.Doc(\"get available API versions\")\n\tws.Route(ws.GET(\"/\").To(wrapped.restfulHandle).\n\t\tDoc(\"get available API versions\").\n\t\tOperation(\"getAPIVersions\").\n\t\tProduces(mediaTypes...).\n\t\tConsumes(mediaTypes...).\n\t\tWrites(returnType))\n\treturn ws\n}","line":{"from":55,"to":67}} {"id":100017363,"name":"WrapAggregatedDiscoveryToHandler","signature":"func WrapAggregatedDiscoveryToHandler(handler http.Handler, aggHandler http.Handler) *WrappedHandler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/aggregated/wrapper.go","code":"// WrapAggregatedDiscoveryToHandler wraps a handler with an option to\n// emit the aggregated discovery by passing in the aggregated\n// discovery type in content negotiation headers: eg: (Accept:\n// application/json;v=v2beta1;g=apidiscovery.k8s.io;as=APIGroupDiscoveryList)\nfunc WrapAggregatedDiscoveryToHandler(handler http.Handler, aggHandler http.Handler) *WrappedHandler {\n\tscheme := runtime.NewScheme()\n\tapidiscoveryv2beta1.AddToScheme(scheme)\n\tcodecs := serializer.NewCodecFactory(scheme)\n\treturn \u0026WrappedHandler{codecs, handler, aggHandler}\n}","line":{"from":69,"to":78}} {"id":100017364,"name":"NewAPIGroupHandler","signature":"func NewAPIGroupHandler(serializer runtime.NegotiatedSerializer, group metav1.APIGroup) *APIGroupHandler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/group.go","code":"func NewAPIGroupHandler(serializer runtime.NegotiatedSerializer, group metav1.APIGroup) *APIGroupHandler {\n\tif keepUnversioned(group.Name) {\n\t\t// Because in release 1.1, /apis/extensions returns response with empty\n\t\t// APIVersion, we use stripVersionNegotiatedSerializer to keep the\n\t\t// response backwards compatible.\n\t\tserializer = stripVersionNegotiatedSerializer{serializer}\n\t}\n\n\treturn \u0026APIGroupHandler{\n\t\tserializer: serializer,\n\t\tgroup: group,\n\t}\n}","line":{"from":38,"to":50}} {"id":100017365,"name":"WebService","signature":"func (s *APIGroupHandler) WebService() *restful.WebService","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/group.go","code":"func (s *APIGroupHandler) WebService() *restful.WebService {\n\tmediaTypes, _ := negotiation.MediaTypesForSerializer(s.serializer)\n\tws := new(restful.WebService)\n\tws.Path(APIGroupPrefix + \"/\" + s.group.Name)\n\tws.Doc(\"get information of a group\")\n\tws.Route(ws.GET(\"/\").To(s.handle).\n\t\tDoc(\"get information of a group\").\n\t\tOperation(\"getAPIGroup\").\n\t\tProduces(mediaTypes...).\n\t\tConsumes(mediaTypes...).\n\t\tWrites(metav1.APIGroup{}))\n\treturn ws\n}","line":{"from":52,"to":64}} {"id":100017366,"name":"handle","signature":"func (s *APIGroupHandler) handle(req *restful.Request, resp *restful.Response)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/group.go","code":"// handle returns a handler which will return the api.GroupAndVersion of the group.\nfunc (s *APIGroupHandler) handle(req *restful.Request, resp *restful.Response) {\n\ts.ServeHTTP(resp.ResponseWriter, req.Request)\n}","line":{"from":66,"to":69}} {"id":100017367,"name":"ServeHTTP","signature":"func (s *APIGroupHandler) ServeHTTP(w http.ResponseWriter, req *http.Request)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/group.go","code":"func (s *APIGroupHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tresponsewriters.WriteObjectNegotiated(s.serializer, negotiation.DefaultEndpointRestrictions, schema.GroupVersion{}, w, req, http.StatusOK, \u0026s.group, false)\n}","line":{"from":71,"to":73}} {"id":100017368,"name":"NewLegacyRootAPIHandler","signature":"func NewLegacyRootAPIHandler(addresses Addresses, serializer runtime.NegotiatedSerializer, apiPrefix string) *legacyRootAPIHandler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/legacy.go","code":"func NewLegacyRootAPIHandler(addresses Addresses, serializer runtime.NegotiatedSerializer, apiPrefix string) *legacyRootAPIHandler {\n\t// Because in release 1.1, /apis returns response with empty APIVersion, we\n\t// use stripVersionNegotiatedSerializer to keep the response backwards\n\t// compatible.\n\tserializer = stripVersionNegotiatedSerializer{serializer}\n\n\treturn \u0026legacyRootAPIHandler{\n\t\taddresses: addresses,\n\t\tapiPrefix: apiPrefix,\n\t\tserializer: serializer,\n\t}\n}","line":{"from":40,"to":51}} {"id":100017369,"name":"WebService","signature":"func (s *legacyRootAPIHandler) WebService() *restful.WebService","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/legacy.go","code":"// AddApiWebService adds a service to return the supported api versions at the legacy /api.\nfunc (s *legacyRootAPIHandler) WebService() *restful.WebService {\n\tmediaTypes, _ := negotiation.MediaTypesForSerializer(s.serializer)\n\tws := new(restful.WebService)\n\tws.Path(s.apiPrefix)\n\tws.Doc(\"get available API versions\")\n\tws.Route(ws.GET(\"/\").To(s.restfulHandle).\n\t\tDoc(\"get available API versions\").\n\t\tOperation(\"getAPIVersions\").\n\t\tProduces(mediaTypes...).\n\t\tConsumes(mediaTypes...).\n\t\tWrites(metav1.APIVersions{}))\n\treturn ws\n}","line":{"from":53,"to":66}} {"id":100017370,"name":"restfulHandle","signature":"func (s *legacyRootAPIHandler) restfulHandle(req *restful.Request, resp *restful.Response)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/legacy.go","code":"func (s *legacyRootAPIHandler) restfulHandle(req *restful.Request, resp *restful.Response) {\n\ts.ServeHTTP(resp.ResponseWriter, req.Request)\n}","line":{"from":68,"to":70}} {"id":100017371,"name":"ServeHTTP","signature":"func (s *legacyRootAPIHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/legacy.go","code":"func (s *legacyRootAPIHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {\n\tclientIP := utilnet.GetClientIP(req)\n\tapiVersions := \u0026metav1.APIVersions{\n\t\tServerAddressByClientCIDRs: s.addresses.ServerAddressByClientCIDRs(clientIP),\n\t\tVersions: []string{\"v1\"},\n\t}\n\n\tresponsewriters.WriteObjectNegotiated(s.serializer, negotiation.DefaultEndpointRestrictions, schema.GroupVersion{}, resp, req, http.StatusOK, apiVersions, false)\n}","line":{"from":72,"to":80}} {"id":100017372,"name":"NewRootAPIsHandler","signature":"func NewRootAPIsHandler(addresses Addresses, serializer runtime.NegotiatedSerializer) *rootAPIsHandler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/root.go","code":"func NewRootAPIsHandler(addresses Addresses, serializer runtime.NegotiatedSerializer) *rootAPIsHandler {\n\t// Because in release 1.1, /apis returns response with empty APIVersion, we\n\t// use stripVersionNegotiatedSerializer to keep the response backwards\n\t// compatible.\n\tserializer = stripVersionNegotiatedSerializer{serializer}\n\n\treturn \u0026rootAPIsHandler{\n\t\taddresses: addresses,\n\t\tserializer: serializer,\n\t\tapiGroups: map[string]metav1.APIGroup{},\n\t}\n}","line":{"from":59,"to":70}} {"id":100017373,"name":"AddGroup","signature":"func (s *rootAPIsHandler) AddGroup(apiGroup metav1.APIGroup)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/root.go","code":"func (s *rootAPIsHandler) AddGroup(apiGroup metav1.APIGroup) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\t_, alreadyExists := s.apiGroups[apiGroup.Name]\n\n\ts.apiGroups[apiGroup.Name] = apiGroup\n\tif !alreadyExists {\n\t\ts.apiGroupNames = append(s.apiGroupNames, apiGroup.Name)\n\t}\n}","line":{"from":72,"to":82}} {"id":100017374,"name":"RemoveGroup","signature":"func (s *rootAPIsHandler) RemoveGroup(groupName string)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/root.go","code":"func (s *rootAPIsHandler) RemoveGroup(groupName string) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\tdelete(s.apiGroups, groupName)\n\tfor i := range s.apiGroupNames {\n\t\tif s.apiGroupNames[i] == groupName {\n\t\t\ts.apiGroupNames = append(s.apiGroupNames[:i], s.apiGroupNames[i+1:]...)\n\t\t\tbreak\n\t\t}\n\t}\n}","line":{"from":84,"to":95}} {"id":100017375,"name":"ServeHTTP","signature":"func (s *rootAPIsHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/root.go","code":"func (s *rootAPIsHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {\n\ts.lock.RLock()\n\tdefer s.lock.RUnlock()\n\n\torderedGroups := []metav1.APIGroup{}\n\tfor _, groupName := range s.apiGroupNames {\n\t\torderedGroups = append(orderedGroups, s.apiGroups[groupName])\n\t}\n\n\tclientIP := utilnet.GetClientIP(req)\n\tserverCIDR := s.addresses.ServerAddressByClientCIDRs(clientIP)\n\tgroups := make([]metav1.APIGroup, len(orderedGroups))\n\tfor i := range orderedGroups {\n\t\tgroups[i] = orderedGroups[i]\n\t\tgroups[i].ServerAddressByClientCIDRs = serverCIDR\n\t}\n\n\tresponsewriters.WriteObjectNegotiated(s.serializer, negotiation.DefaultEndpointRestrictions, schema.GroupVersion{}, resp, req, http.StatusOK, \u0026metav1.APIGroupList{Groups: groups}, false)\n}","line":{"from":97,"to":115}} {"id":100017376,"name":"restfulHandle","signature":"func (s *rootAPIsHandler) restfulHandle(req *restful.Request, resp *restful.Response)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/root.go","code":"func (s *rootAPIsHandler) restfulHandle(req *restful.Request, resp *restful.Response) {\n\ts.ServeHTTP(resp.ResponseWriter, req.Request)\n}","line":{"from":117,"to":119}} {"id":100017377,"name":"WebService","signature":"func (s *rootAPIsHandler) WebService() *restful.WebService","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/root.go","code":"// WebService returns a webservice serving api group discovery.\n// Note: during the server runtime apiGroups might change.\nfunc (s *rootAPIsHandler) WebService() *restful.WebService {\n\tmediaTypes, _ := negotiation.MediaTypesForSerializer(s.serializer)\n\tws := new(restful.WebService)\n\tws.Path(APIGroupPrefix)\n\tws.Doc(\"get available API versions\")\n\tws.Route(ws.GET(\"/\").To(s.restfulHandle).\n\t\tDoc(\"get available API versions\").\n\t\tOperation(\"getAPIVersions\").\n\t\tProduces(mediaTypes...).\n\t\tConsumes(mediaTypes...).\n\t\tWrites(metav1.APIGroupList{}))\n\treturn ws\n}","line":{"from":121,"to":135}} {"id":100017378,"name":"StorageVersionHash","signature":"func StorageVersionHash(group, version, kind string) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/storageversionhash.go","code":"// StorageVersionHash calculates the storage version hash for a\n// \u003cgroup/version/kind\u003e tuple.\n// WARNING: this function is subject to change. Clients shouldn't depend on\n// this function.\nfunc StorageVersionHash(group, version, kind string) string {\n\tgvk := group + \"/\" + version + \"/\" + kind\n\tbytes := sha256.Sum256([]byte(gvk))\n\t// Assuming there are N kinds in the cluster, and the hash is X-byte long,\n\t// the chance of colliding hash P(N,X) approximates to 1-e^(-(N^2)/2^(8X+1)).\n\t// P(10,000, 8) ~= 2.7*10^(-12), which is low enough.\n\t// See https://en.wikipedia.org/wiki/Birthday_problem#Approximations.\n\treturn base64.StdEncoding.EncodeToString(bytes[:8])\n}","line":{"from":24,"to":36}} {"id":100017379,"name":"keepUnversioned","signature":"func keepUnversioned(group string) bool","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/util.go","code":"func keepUnversioned(group string) bool {\n\treturn group == \"\" || group == \"extensions\"\n}","line":{"from":31,"to":33}} {"id":100017380,"name":"newStripVersionEncoder","signature":"func newStripVersionEncoder(e runtime.Encoder, s runtime.Serializer) runtime.Encoder","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/util.go","code":"func newStripVersionEncoder(e runtime.Encoder, s runtime.Serializer) runtime.Encoder {\n\treturn stripVersionEncoder{\n\t\tencoder: e,\n\t\tserializer: s,\n\t\tidentifier: identifier(e),\n\t}\n}","line":{"from":44,"to":50}} {"id":100017381,"name":"identifier","signature":"func identifier(e runtime.Encoder) runtime.Identifier","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/util.go","code":"func identifier(e runtime.Encoder) runtime.Identifier {\n\tresult := map[string]string{\n\t\t\"name\": \"stripVersion\",\n\t}\n\tif e != nil {\n\t\tresult[\"encoder\"] = string(e.Identifier())\n\t}\n\tidentifier, err := json.Marshal(result)\n\tif err != nil {\n\t\tklog.Fatalf(\"Failed marshaling identifier for stripVersionEncoder: %v\", err)\n\t}\n\treturn runtime.Identifier(identifier)\n}","line":{"from":52,"to":64}} {"id":100017382,"name":"Encode","signature":"func (c stripVersionEncoder) Encode(obj runtime.Object, w io.Writer) error","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/util.go","code":"func (c stripVersionEncoder) Encode(obj runtime.Object, w io.Writer) error {\n\tif co, ok := obj.(runtime.CacheableObject); ok {\n\t\treturn co.CacheEncode(c.Identifier(), c.doEncode, w)\n\t}\n\treturn c.doEncode(obj, w)\n}","line":{"from":66,"to":71}} {"id":100017383,"name":"doEncode","signature":"func (c stripVersionEncoder) doEncode(obj runtime.Object, w io.Writer) error","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/util.go","code":"func (c stripVersionEncoder) doEncode(obj runtime.Object, w io.Writer) error {\n\tbuf := bytes.NewBuffer([]byte{})\n\terr := c.encoder.Encode(obj, buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\troundTrippedObj, gvk, err := c.serializer.Decode(buf.Bytes(), nil, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgvk.Group = \"\"\n\tgvk.Version = \"\"\n\troundTrippedObj.GetObjectKind().SetGroupVersionKind(*gvk)\n\treturn c.serializer.Encode(roundTrippedObj, w)\n}","line":{"from":73,"to":87}} {"id":100017384,"name":"Identifier","signature":"func (c stripVersionEncoder) Identifier() runtime.Identifier","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/util.go","code":"// Identifier implements runtime.Encoder interface.\nfunc (c stripVersionEncoder) Identifier() runtime.Identifier {\n\treturn c.identifier\n}","line":{"from":89,"to":92}} {"id":100017385,"name":"EncoderForVersion","signature":"func (n stripVersionNegotiatedSerializer) EncoderForVersion(encoder runtime.Encoder, gv runtime.GroupVersioner) runtime.Encoder","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/util.go","code":"func (n stripVersionNegotiatedSerializer) EncoderForVersion(encoder runtime.Encoder, gv runtime.GroupVersioner) runtime.Encoder {\n\tserializer, ok := encoder.(runtime.Serializer)\n\tif !ok {\n\t\t// The stripVersionEncoder needs both an encoder and decoder, but is called from a context that doesn't have access to the\n\t\t// decoder. We do a best effort cast here (since this code path is only for backwards compatibility) to get access to the caller's\n\t\t// decoder.\n\t\tpanic(fmt.Sprintf(\"Unable to extract serializer from %#v\", encoder))\n\t}\n\tversioned := n.NegotiatedSerializer.EncoderForVersion(encoder, gv)\n\treturn newStripVersionEncoder(versioned, serializer)\n}","line":{"from":100,"to":110}} {"id":100017386,"name":"ListAPIResources","signature":"func (f APIResourceListerFunc) ListAPIResources() []metav1.APIResource","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/version.go","code":"func (f APIResourceListerFunc) ListAPIResources() []metav1.APIResource {\n\treturn f()\n}","line":{"from":37,"to":39}} {"id":100017387,"name":"NewAPIVersionHandler","signature":"func NewAPIVersionHandler(serializer runtime.NegotiatedSerializer, groupVersion schema.GroupVersion, apiResourceLister APIResourceLister) *APIVersionHandler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/version.go","code":"func NewAPIVersionHandler(serializer runtime.NegotiatedSerializer, groupVersion schema.GroupVersion, apiResourceLister APIResourceLister) *APIVersionHandler {\n\tif keepUnversioned(groupVersion.Group) {\n\t\t// Because in release 1.1, /apis/extensions returns response with empty\n\t\t// APIVersion, we use stripVersionNegotiatedSerializer to keep the\n\t\t// response backwards compatible.\n\t\tserializer = stripVersionNegotiatedSerializer{serializer}\n\t}\n\n\treturn \u0026APIVersionHandler{\n\t\tserializer: serializer,\n\t\tgroupVersion: groupVersion,\n\t\tapiResourceLister: apiResourceLister,\n\t}\n}","line":{"from":50,"to":63}} {"id":100017388,"name":"AddToWebService","signature":"func (s *APIVersionHandler) AddToWebService(ws *restful.WebService)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/version.go","code":"func (s *APIVersionHandler) AddToWebService(ws *restful.WebService) {\n\tmediaTypes, _ := negotiation.MediaTypesForSerializer(s.serializer)\n\tws.Route(ws.GET(\"/\").To(s.handle).\n\t\tDoc(\"get available resources\").\n\t\tOperation(\"getAPIResources\").\n\t\tProduces(mediaTypes...).\n\t\tConsumes(mediaTypes...).\n\t\tWrites(metav1.APIResourceList{}))\n}","line":{"from":65,"to":73}} {"id":100017389,"name":"handle","signature":"func (s *APIVersionHandler) handle(req *restful.Request, resp *restful.Response)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/version.go","code":"// handle returns a handler which will return the api.VersionAndVersion of the group.\nfunc (s *APIVersionHandler) handle(req *restful.Request, resp *restful.Response) {\n\ts.ServeHTTP(resp.ResponseWriter, req.Request)\n}","line":{"from":75,"to":78}} {"id":100017390,"name":"ServeHTTP","signature":"func (s *APIVersionHandler) ServeHTTP(w http.ResponseWriter, req *http.Request)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/discovery/version.go","code":"func (s *APIVersionHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tresponsewriters.WriteObjectNegotiated(s.serializer, negotiation.DefaultEndpointRestrictions, schema.GroupVersion{}, w, req, http.StatusOK,\n\t\t\u0026metav1.APIResourceList{GroupVersion: s.groupVersion.String(), APIResources: s.apiResourceLister.ListAPIResources()}, false)\n}","line":{"from":80,"to":83}} {"id":100017391,"name":"withRequestFilterRecord","signature":"func withRequestFilterRecord(parent context.Context, fr *requestFilterRecord) context.Context","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filterlatency/filterlatency.go","code":"// withRequestFilterRecord attaches the given request filter record to the parent context.\nfunc withRequestFilterRecord(parent context.Context, fr *requestFilterRecord) context.Context {\n\treturn apirequest.WithValue(parent, requestFilterRecordKey, fr)\n}","line":{"from":46,"to":49}} {"id":100017392,"name":"requestFilterRecordFrom","signature":"func requestFilterRecordFrom(ctx context.Context) *requestFilterRecord","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filterlatency/filterlatency.go","code":"// requestFilterRecordFrom returns the request filter record from the given context.\nfunc requestFilterRecordFrom(ctx context.Context) *requestFilterRecord {\n\tfr, _ := ctx.Value(requestFilterRecordKey).(*requestFilterRecord)\n\treturn fr\n}","line":{"from":51,"to":55}} {"id":100017393,"name":"TrackStarted","signature":"func TrackStarted(handler http.Handler, tp trace.TracerProvider, name string) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filterlatency/filterlatency.go","code":"// TrackStarted measures the timestamp the given handler has started execution\n// by attaching a handler to the chain.\nfunc TrackStarted(handler http.Handler, tp trace.TracerProvider, name string) http.Handler {\n\treturn trackStarted(handler, tp, name, clock.RealClock{})\n}","line":{"from":57,"to":61}} {"id":100017394,"name":"TrackCompleted","signature":"func TrackCompleted(handler http.Handler) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filterlatency/filterlatency.go","code":"// TrackCompleted measures the timestamp the given handler has completed execution and then\n// it updates the corresponding metric with the filter latency duration.\nfunc TrackCompleted(handler http.Handler) http.Handler {\n\treturn trackCompleted(handler, clock.RealClock{}, func(ctx context.Context, fr *requestFilterRecord, completedAt time.Time) {\n\t\tlatency := completedAt.Sub(fr.startedTimestamp)\n\t\tmetrics.RecordFilterLatency(ctx, fr.name, latency)\n\t\tif klog.V(3).Enabled() \u0026\u0026 latency \u003e minFilterLatencyToLog {\n\t\t\thttplog.AddKeyValue(ctx, fmt.Sprintf(\"fl_%s\", fr.name), latency.String())\n\t\t}\n\t})\n}","line":{"from":63,"to":73}} {"id":100017395,"name":"trackStarted","signature":"func trackStarted(handler http.Handler, tp trace.TracerProvider, name string, clock clock.PassiveClock) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filterlatency/filterlatency.go","code":"func trackStarted(handler http.Handler, tp trace.TracerProvider, name string, clock clock.PassiveClock) http.Handler {\n\t// This is a noop if the tracing is disabled, since tp will be a NoopTracerProvider\n\ttracer := tp.Tracer(\"k8s.op/apiserver/pkg/endpoints/filterlatency\")\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tctx := r.Context()\n\t\tif fr := requestFilterRecordFrom(ctx); fr != nil {\n\t\t\tfr.name = name\n\t\t\tfr.startedTimestamp = clock.Now()\n\n\t\t\thandler.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\tfr := \u0026requestFilterRecord{\n\t\t\tname: name,\n\t\t\tstartedTimestamp: clock.Now(),\n\t\t}\n\t\tctx, _ = tracer.Start(ctx, name)\n\t\tr = r.WithContext(withRequestFilterRecord(ctx, fr))\n\t\thandler.ServeHTTP(w, r)\n\t})\n}","line":{"from":75,"to":96}} {"id":100017396,"name":"trackCompleted","signature":"func trackCompleted(handler http.Handler, clock clock.PassiveClock, action func(context.Context, *requestFilterRecord, time.Time)) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filterlatency/filterlatency.go","code":"func trackCompleted(handler http.Handler, clock clock.PassiveClock, action func(context.Context, *requestFilterRecord, time.Time)) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t// The previous filter has just completed.\n\t\tcompletedAt := clock.Now()\n\n\t\tdefer handler.ServeHTTP(w, r)\n\n\t\tctx := r.Context()\n\t\tif fr := requestFilterRecordFrom(ctx); fr != nil {\n\t\t\taction(ctx, fr, completedAt)\n\t\t}\n\t\ttrace.SpanFromContext(ctx).End()\n\t})\n}","line":{"from":98,"to":111}} {"id":100017397,"name":"WithAudit","signature":"func WithAudit(handler http.Handler, sink audit.Sink, policy audit.PolicyRuleEvaluator, longRunningCheck request.LongRunningRequestCheck) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/audit.go","code":"// WithAudit decorates a http.Handler with audit logging information for all the\n// requests coming to the server. Audit level is decided according to requests'\n// attributes and audit policy. Logs are emitted to the audit sink to\n// process events. If sink or audit policy is nil, no decoration takes place.\nfunc WithAudit(handler http.Handler, sink audit.Sink, policy audit.PolicyRuleEvaluator, longRunningCheck request.LongRunningRequestCheck) http.Handler {\n\tif sink == nil || policy == nil {\n\t\treturn handler\n\t}\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tac, err := evaluatePolicyAndCreateAuditEvent(req, policy)\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"failed to create audit event: %v\", err))\n\t\t\tresponsewriters.InternalError(w, req, errors.New(\"failed to create audit event\"))\n\t\t\treturn\n\t\t}\n\n\t\tif ac == nil || ac.Event == nil {\n\t\t\thandler.ServeHTTP(w, req)\n\t\t\treturn\n\t\t}\n\t\tev := ac.Event\n\n\t\tctx := req.Context()\n\t\tomitStages := ac.RequestAuditConfig.OmitStages\n\n\t\tev.Stage = auditinternal.StageRequestReceived\n\t\tif processed := processAuditEvent(ctx, sink, ev, omitStages); !processed {\n\t\t\taudit.ApiserverAuditDroppedCounter.WithContext(ctx).Inc()\n\t\t\tresponsewriters.InternalError(w, req, errors.New(\"failed to store audit event\"))\n\t\t\treturn\n\t\t}\n\n\t\t// intercept the status code\n\t\tvar longRunningSink audit.Sink\n\t\tif longRunningCheck != nil {\n\t\t\tri, _ := request.RequestInfoFrom(ctx)\n\t\t\tif longRunningCheck(req, ri) {\n\t\t\t\tlongRunningSink = sink\n\t\t\t}\n\t\t}\n\t\trespWriter := decorateResponseWriter(ctx, w, ev, longRunningSink, omitStages)\n\n\t\t// send audit event when we leave this func, either via a panic or cleanly. In the case of long\n\t\t// running requests, this will be the second audit event.\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\tdefer panic(r)\n\t\t\t\tev.Stage = auditinternal.StagePanic\n\t\t\t\tev.ResponseStatus = \u0026metav1.Status{\n\t\t\t\t\tCode: http.StatusInternalServerError,\n\t\t\t\t\tStatus: metav1.StatusFailure,\n\t\t\t\t\tReason: metav1.StatusReasonInternalError,\n\t\t\t\t\tMessage: fmt.Sprintf(\"APIServer panic'd: %v\", r),\n\t\t\t\t}\n\t\t\t\tprocessAuditEvent(ctx, sink, ev, omitStages)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// if no StageResponseStarted event was sent b/c neither a status code nor a body was sent, fake it here\n\t\t\t// But Audit-Id http header will only be sent when http.ResponseWriter.WriteHeader is called.\n\t\t\tfakedSuccessStatus := \u0026metav1.Status{\n\t\t\t\tCode: http.StatusOK,\n\t\t\t\tStatus: metav1.StatusSuccess,\n\t\t\t\tMessage: \"Connection closed early\",\n\t\t\t}\n\t\t\tif ev.ResponseStatus == nil \u0026\u0026 longRunningSink != nil {\n\t\t\t\tev.ResponseStatus = fakedSuccessStatus\n\t\t\t\tev.Stage = auditinternal.StageResponseStarted\n\t\t\t\tprocessAuditEvent(ctx, longRunningSink, ev, omitStages)\n\t\t\t}\n\n\t\t\tev.Stage = auditinternal.StageResponseComplete\n\t\t\tif ev.ResponseStatus == nil {\n\t\t\t\tev.ResponseStatus = fakedSuccessStatus\n\t\t\t}\n\t\t\tprocessAuditEvent(ctx, sink, ev, omitStages)\n\t\t}()\n\t\thandler.ServeHTTP(respWriter, req)\n\t})\n}","line":{"from":38,"to":117}} {"id":100017398,"name":"evaluatePolicyAndCreateAuditEvent","signature":"func evaluatePolicyAndCreateAuditEvent(req *http.Request, policy audit.PolicyRuleEvaluator) (*audit.AuditContext, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/audit.go","code":"// evaluatePolicyAndCreateAuditEvent is responsible for evaluating the audit\n// policy configuration applicable to the request and create a new audit\n// event that will be written to the API audit log.\n// - error if anything bad happened\nfunc evaluatePolicyAndCreateAuditEvent(req *http.Request, policy audit.PolicyRuleEvaluator) (*audit.AuditContext, error) {\n\tctx := req.Context()\n\tac := audit.AuditContextFrom(ctx)\n\tif ac == nil {\n\t\t// Auditing not enabled.\n\t\treturn nil, nil\n\t}\n\n\tattribs, err := GetAuthorizerAttributes(ctx)\n\tif err != nil {\n\t\treturn ac, fmt.Errorf(\"failed to GetAuthorizerAttributes: %v\", err)\n\t}\n\n\trac := policy.EvaluatePolicyRule(attribs)\n\taudit.ObservePolicyLevel(ctx, rac.Level)\n\tac.RequestAuditConfig = rac\n\tif rac.Level == auditinternal.LevelNone {\n\t\t// Don't audit.\n\t\treturn ac, nil\n\t}\n\n\trequestReceivedTimestamp, ok := request.ReceivedTimestampFrom(ctx)\n\tif !ok {\n\t\trequestReceivedTimestamp = time.Now()\n\t}\n\tev, err := audit.NewEventFromRequest(req, requestReceivedTimestamp, rac.Level, attribs)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to complete audit event from request: %v\", err)\n\t}\n\n\tac.Event = ev\n\n\treturn ac, nil\n}","line":{"from":119,"to":156}} {"id":100017399,"name":"writeLatencyToAnnotation","signature":"func writeLatencyToAnnotation(ctx context.Context, ev *auditinternal.Event)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/audit.go","code":"// writeLatencyToAnnotation writes the latency incurred in different\n// layers of the apiserver to the annotations of the audit object.\n// it should be invoked after ev.StageTimestamp has been set appropriately.\nfunc writeLatencyToAnnotation(ctx context.Context, ev *auditinternal.Event) {\n\t// we will track latency in annotation only when the total latency\n\t// of the given request exceeds 500ms, this is in keeping with the\n\t// traces in rest/handlers for create, delete, update,\n\t// get, list, and deletecollection.\n\tconst threshold = 500 * time.Millisecond\n\tlatency := ev.StageTimestamp.Time.Sub(ev.RequestReceivedTimestamp.Time)\n\tif latency \u003c= threshold {\n\t\treturn\n\t}\n\n\t// if we are tracking latency incurred inside different layers within\n\t// the apiserver, add these as annotation to the audit event object.\n\tlayerLatencies := request.AuditAnnotationsFromLatencyTrackers(ctx)\n\tif len(layerLatencies) == 0 {\n\t\t// latency tracking is not enabled for this request\n\t\treturn\n\t}\n\n\t// record the total latency for this request, for convenience.\n\tlayerLatencies[\"apiserver.latency.k8s.io/total\"] = latency.String()\n\taudit.AddAuditAnnotationsMap(ctx, layerLatencies)\n}","line":{"from":158,"to":183}} {"id":100017400,"name":"processAuditEvent","signature":"func processAuditEvent(ctx context.Context, sink audit.Sink, ev *auditinternal.Event, omitStages []auditinternal.Stage) bool","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/audit.go","code":"func processAuditEvent(ctx context.Context, sink audit.Sink, ev *auditinternal.Event, omitStages []auditinternal.Stage) bool {\n\tfor _, stage := range omitStages {\n\t\tif ev.Stage == stage {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tswitch {\n\tcase ev.Stage == auditinternal.StageRequestReceived:\n\t\tev.StageTimestamp = metav1.NewMicroTime(ev.RequestReceivedTimestamp.Time)\n\tcase ev.Stage == auditinternal.StageResponseComplete:\n\t\tev.StageTimestamp = metav1.NewMicroTime(time.Now())\n\t\twriteLatencyToAnnotation(ctx, ev)\n\tdefault:\n\t\tev.StageTimestamp = metav1.NewMicroTime(time.Now())\n\t}\n\n\taudit.ObserveEvent(ctx)\n\treturn sink.ProcessEvents(ev)\n}","line":{"from":185,"to":204}} {"id":100017401,"name":"decorateResponseWriter","signature":"func decorateResponseWriter(ctx context.Context, responseWriter http.ResponseWriter, ev *auditinternal.Event, sink audit.Sink, omitStages []auditinternal.Stage) http.ResponseWriter","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/audit.go","code":"func decorateResponseWriter(ctx context.Context, responseWriter http.ResponseWriter, ev *auditinternal.Event, sink audit.Sink, omitStages []auditinternal.Stage) http.ResponseWriter {\n\tdelegate := \u0026auditResponseWriter{\n\t\tctx: ctx,\n\t\tResponseWriter: responseWriter,\n\t\tevent: ev,\n\t\tsink: sink,\n\t\tomitStages: omitStages,\n\t}\n\n\treturn responsewriter.WrapForHTTP1Or2(delegate)\n}","line":{"from":206,"to":216}} {"id":100017402,"name":"Unwrap","signature":"func (a *auditResponseWriter) Unwrap() http.ResponseWriter","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/audit.go","code":"func (a *auditResponseWriter) Unwrap() http.ResponseWriter {\n\treturn a.ResponseWriter\n}","line":{"from":232,"to":234}} {"id":100017403,"name":"processCode","signature":"func (a *auditResponseWriter) processCode(code int)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/audit.go","code":"func (a *auditResponseWriter) processCode(code int) {\n\ta.once.Do(func() {\n\t\tif a.event.ResponseStatus == nil {\n\t\t\ta.event.ResponseStatus = \u0026metav1.Status{}\n\t\t}\n\t\ta.event.ResponseStatus.Code = int32(code)\n\t\ta.event.Stage = auditinternal.StageResponseStarted\n\n\t\tif a.sink != nil {\n\t\t\tprocessAuditEvent(a.ctx, a.sink, a.event, a.omitStages)\n\t\t}\n\t})\n}","line":{"from":236,"to":248}} {"id":100017404,"name":"Write","signature":"func (a *auditResponseWriter) Write(bs []byte) (int, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/audit.go","code":"func (a *auditResponseWriter) Write(bs []byte) (int, error) {\n\t// the Go library calls WriteHeader internally if no code was written yet. But this will go unnoticed for us\n\ta.processCode(http.StatusOK)\n\treturn a.ResponseWriter.Write(bs)\n}","line":{"from":250,"to":254}} {"id":100017405,"name":"WriteHeader","signature":"func (a *auditResponseWriter) WriteHeader(code int)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/audit.go","code":"func (a *auditResponseWriter) WriteHeader(code int) {\n\ta.processCode(code)\n\ta.ResponseWriter.WriteHeader(code)\n}","line":{"from":256,"to":259}} {"id":100017406,"name":"Hijack","signature":"func (a *auditResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/audit.go","code":"func (a *auditResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\t// fake a response status before protocol switch happens\n\ta.processCode(http.StatusSwitchingProtocols)\n\n\t// the outer ResponseWriter object returned by WrapForHTTP1Or2 implements\n\t// http.Hijacker if the inner object (a.ResponseWriter) implements http.Hijacker.\n\treturn a.ResponseWriter.(http.Hijacker).Hijack()\n}","line":{"from":261,"to":268}} {"id":100017407,"name":"WithAuditInit","signature":"func WithAuditInit(handler http.Handler) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/audit_init.go","code":"// WithAuditInit initializes the audit context and attaches the Audit-ID associated with a request.\n//\n// a. If the caller does not specify a value for Audit-ID in the request header, we generate a new audit ID\n// b. We echo the Audit-ID value to the caller via the response Header 'Audit-ID'.\nfunc WithAuditInit(handler http.Handler) http.Handler {\n\treturn withAuditInit(handler, func() string {\n\t\treturn uuid.New().String()\n\t})\n}","line":{"from":29,"to":37}} {"id":100017408,"name":"withAuditInit","signature":"func withAuditInit(handler http.Handler, newAuditIDFunc func() string) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/audit_init.go","code":"func withAuditInit(handler http.Handler, newAuditIDFunc func() string) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tctx := audit.WithAuditContext(r.Context())\n\t\tr = r.WithContext(ctx)\n\n\t\tauditID := r.Header.Get(auditinternal.HeaderAuditID)\n\t\tif len(auditID) == 0 {\n\t\t\tauditID = newAuditIDFunc()\n\t\t}\n\n\t\t// Note: we save the user specified value of the Audit-ID header as is, no truncation is performed.\n\t\taudit.WithAuditID(ctx, types.UID(auditID))\n\n\t\t// We echo the Audit-ID in to the response header.\n\t\t// It's not guaranteed Audit-ID http header is sent for all requests.\n\t\t// For example, when user run \"kubectl exec\", apiserver uses a proxy handler\n\t\t// to deal with the request, users can only get http headers returned by kubelet node.\n\t\t//\n\t\t// This filter will also be used by other aggregated api server(s). For an aggregated API\n\t\t// we don't want to see the same audit ID appearing more than once.\n\t\tif value := w.Header().Get(auditinternal.HeaderAuditID); len(value) == 0 {\n\t\t\tw.Header().Set(auditinternal.HeaderAuditID, auditID)\n\t\t}\n\n\t\thandler.ServeHTTP(w, r)\n\t})\n}","line":{"from":39,"to":65}} {"id":100017409,"name":"WithAuthentication","signature":"func WithAuthentication(handler http.Handler, auth authenticator.Request, failed http.Handler, apiAuds authenticator.Audiences, requestHeaderConfig *authenticatorfactory.RequestHeaderConfig) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/authentication.go","code":"// WithAuthentication creates an http handler that tries to authenticate the given request as a user, and then\n// stores any such user found onto the provided context for the request. If authentication fails or returns an error\n// the failed handler is used. On success, \"Authorization\" header is removed from the request and handler\n// is invoked to serve the request.\nfunc WithAuthentication(handler http.Handler, auth authenticator.Request, failed http.Handler, apiAuds authenticator.Audiences, requestHeaderConfig *authenticatorfactory.RequestHeaderConfig) http.Handler {\n\treturn withAuthentication(handler, auth, failed, apiAuds, requestHeaderConfig, recordAuthMetrics)\n}","line":{"from":39,"to":45}} {"id":100017410,"name":"withAuthentication","signature":"func withAuthentication(handler http.Handler, auth authenticator.Request, failed http.Handler, apiAuds authenticator.Audiences, requestHeaderConfig *authenticatorfactory.RequestHeaderConfig, metrics recordMetrics) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/authentication.go","code":"func withAuthentication(handler http.Handler, auth authenticator.Request, failed http.Handler, apiAuds authenticator.Audiences, requestHeaderConfig *authenticatorfactory.RequestHeaderConfig, metrics recordMetrics) http.Handler {\n\tif auth == nil {\n\t\tklog.Warning(\"Authentication is disabled\")\n\t\treturn handler\n\t}\n\tstandardRequestHeaderConfig := \u0026authenticatorfactory.RequestHeaderConfig{\n\t\tUsernameHeaders: headerrequest.StaticStringSlice{\"X-Remote-User\"},\n\t\tGroupHeaders: headerrequest.StaticStringSlice{\"X-Remote-Group\"},\n\t\tExtraHeaderPrefixes: headerrequest.StaticStringSlice{\"X-Remote-Extra-\"},\n\t}\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tauthenticationStart := time.Now()\n\n\t\tif len(apiAuds) \u003e 0 {\n\t\t\treq = req.WithContext(authenticator.WithAudiences(req.Context(), apiAuds))\n\t\t}\n\t\tresp, ok, err := auth.AuthenticateRequest(req)\n\t\tauthenticationFinish := time.Now()\n\t\tdefer func() {\n\t\t\tmetrics(req.Context(), resp, ok, err, apiAuds, authenticationStart, authenticationFinish)\n\t\t}()\n\t\tif err != nil || !ok {\n\t\t\tif err != nil {\n\t\t\t\tklog.ErrorS(err, \"Unable to authenticate the request\")\n\t\t\t}\n\t\t\tfailed.ServeHTTP(w, req)\n\t\t\treturn\n\t\t}\n\n\t\tif !audiencesAreAcceptable(apiAuds, resp.Audiences) {\n\t\t\terr = fmt.Errorf(\"unable to match the audience: %v , accepted: %v\", resp.Audiences, apiAuds)\n\t\t\tklog.Error(err)\n\t\t\tfailed.ServeHTTP(w, req)\n\t\t\treturn\n\t\t}\n\n\t\t// authorization header is not required anymore in case of a successful authentication.\n\t\treq.Header.Del(\"Authorization\")\n\n\t\t// delete standard front proxy headers\n\t\theaderrequest.ClearAuthenticationHeaders(\n\t\t\treq.Header,\n\t\t\tstandardRequestHeaderConfig.UsernameHeaders,\n\t\t\tstandardRequestHeaderConfig.GroupHeaders,\n\t\t\tstandardRequestHeaderConfig.ExtraHeaderPrefixes,\n\t\t)\n\n\t\t// also delete any custom front proxy headers\n\t\tif requestHeaderConfig != nil {\n\t\t\theaderrequest.ClearAuthenticationHeaders(\n\t\t\t\treq.Header,\n\t\t\t\trequestHeaderConfig.UsernameHeaders,\n\t\t\t\trequestHeaderConfig.GroupHeaders,\n\t\t\t\trequestHeaderConfig.ExtraHeaderPrefixes,\n\t\t\t)\n\t\t}\n\n\t\treq = req.WithContext(genericapirequest.WithUser(req.Context(), resp.User))\n\t\thandler.ServeHTTP(w, req)\n\t})\n}","line":{"from":47,"to":107}} {"id":100017411,"name":"Unauthorized","signature":"func Unauthorized(s runtime.NegotiatedSerializer) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/authentication.go","code":"func Unauthorized(s runtime.NegotiatedSerializer) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tctx := req.Context()\n\t\trequestInfo, found := genericapirequest.RequestInfoFrom(ctx)\n\t\tif !found {\n\t\t\tresponsewriters.InternalError(w, req, errors.New(\"no RequestInfo found in the context\"))\n\t\t\treturn\n\t\t}\n\n\t\tgv := schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}\n\t\tresponsewriters.ErrorNegotiated(apierrors.NewUnauthorized(\"Unauthorized\"), s, gv, w, req)\n\t})\n}","line":{"from":109,"to":121}} {"id":100017412,"name":"audiencesAreAcceptable","signature":"func audiencesAreAcceptable(apiAuds, responseAudiences authenticator.Audiences) bool","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/authentication.go","code":"func audiencesAreAcceptable(apiAuds, responseAudiences authenticator.Audiences) bool {\n\tif len(apiAuds) == 0 || len(responseAudiences) == 0 {\n\t\treturn true\n\t}\n\n\treturn len(apiAuds.Intersect(responseAudiences)) \u003e 0\n}","line":{"from":123,"to":129}} {"id":100017413,"name":"WithFailedAuthenticationAudit","signature":"func WithFailedAuthenticationAudit(failedHandler http.Handler, sink audit.Sink, policy audit.PolicyRuleEvaluator) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/authn_audit.go","code":"// WithFailedAuthenticationAudit decorates a failed http.Handler used in WithAuthentication handler.\n// It is meant to log only failed authentication requests.\nfunc WithFailedAuthenticationAudit(failedHandler http.Handler, sink audit.Sink, policy audit.PolicyRuleEvaluator) http.Handler {\n\tif sink == nil || policy == nil {\n\t\treturn failedHandler\n\t}\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tac, err := evaluatePolicyAndCreateAuditEvent(req, policy)\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"failed to create audit event: %v\", err))\n\t\t\tresponsewriters.InternalError(w, req, errors.New(\"failed to create audit event\"))\n\t\t\treturn\n\t\t}\n\n\t\tif ac == nil || ac.Event == nil {\n\t\t\tfailedHandler.ServeHTTP(w, req)\n\t\t\treturn\n\t\t}\n\t\tev := ac.Event\n\n\t\tev.ResponseStatus = \u0026metav1.Status{}\n\t\tev.ResponseStatus.Message = getAuthMethods(req)\n\t\tev.Stage = auditinternal.StageResponseStarted\n\n\t\trw := decorateResponseWriter(req.Context(), w, ev, sink, ac.RequestAuditConfig.OmitStages)\n\t\tfailedHandler.ServeHTTP(rw, req)\n\t})\n}","line":{"from":32,"to":59}} {"id":100017414,"name":"getAuthMethods","signature":"func getAuthMethods(req *http.Request) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/authn_audit.go","code":"func getAuthMethods(req *http.Request) string {\n\tauthMethods := []string{}\n\n\tif _, _, ok := req.BasicAuth(); ok {\n\t\tauthMethods = append(authMethods, \"basic\")\n\t}\n\n\tauth := strings.TrimSpace(req.Header.Get(\"Authorization\"))\n\tparts := strings.Split(auth, \" \")\n\tif len(parts) \u003e 1 \u0026\u0026 strings.ToLower(parts[0]) == \"bearer\" {\n\t\tauthMethods = append(authMethods, \"bearer\")\n\t}\n\n\ttoken := strings.TrimSpace(req.URL.Query().Get(\"access_token\"))\n\tif len(token) \u003e 0 {\n\t\tauthMethods = append(authMethods, \"access_token\")\n\t}\n\n\tif req.TLS != nil \u0026\u0026 len(req.TLS.PeerCertificates) \u003e 0 {\n\t\tauthMethods = append(authMethods, \"x509\")\n\t}\n\n\tif len(authMethods) \u003e 0 {\n\t\treturn fmt.Sprintf(\"Authentication failed, attempted: %s\", strings.Join(authMethods, \", \"))\n\t}\n\treturn \"Authentication failed, no credentials provided\"\n}","line":{"from":61,"to":87}} {"id":100017415,"name":"WithAuthorization","signature":"func WithAuthorization(handler http.Handler, a authorizer.Authorizer, s runtime.NegotiatedSerializer) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/authorization.go","code":"// WithAuthorizationCheck passes all authorized requests on to handler, and returns a forbidden error otherwise.\nfunc WithAuthorization(handler http.Handler, a authorizer.Authorizer, s runtime.NegotiatedSerializer) http.Handler {\n\tif a == nil {\n\t\tklog.Warning(\"Authorization is disabled\")\n\t\treturn handler\n\t}\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tctx := req.Context()\n\n\t\tattributes, err := GetAuthorizerAttributes(ctx)\n\t\tif err != nil {\n\t\t\tresponsewriters.InternalError(w, req, err)\n\t\t\treturn\n\t\t}\n\t\tauthorized, reason, err := a.Authorize(ctx, attributes)\n\t\t// an authorizer like RBAC could encounter evaluation errors and still allow the request, so authorizer decision is checked before error here.\n\t\tif authorized == authorizer.DecisionAllow {\n\t\t\taudit.AddAuditAnnotations(ctx,\n\t\t\t\tdecisionAnnotationKey, decisionAllow,\n\t\t\t\treasonAnnotationKey, reason)\n\t\t\thandler.ServeHTTP(w, req)\n\t\t\treturn\n\t\t}\n\t\tif err != nil {\n\t\t\taudit.AddAuditAnnotation(ctx, reasonAnnotationKey, reasonError)\n\t\t\tresponsewriters.InternalError(w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tklog.V(4).InfoS(\"Forbidden\", \"URI\", req.RequestURI, \"reason\", reason)\n\t\taudit.AddAuditAnnotations(ctx,\n\t\t\tdecisionAnnotationKey, decisionForbid,\n\t\t\treasonAnnotationKey, reason)\n\t\tresponsewriters.Forbidden(ctx, attributes, w, req, reason, s)\n\t})\n}","line":{"from":44,"to":79}} {"id":100017416,"name":"GetAuthorizerAttributes","signature":"func GetAuthorizerAttributes(ctx context.Context) (authorizer.Attributes, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/authorization.go","code":"func GetAuthorizerAttributes(ctx context.Context) (authorizer.Attributes, error) {\n\tattribs := authorizer.AttributesRecord{}\n\n\tuser, ok := request.UserFrom(ctx)\n\tif ok {\n\t\tattribs.User = user\n\t}\n\n\trequestInfo, found := request.RequestInfoFrom(ctx)\n\tif !found {\n\t\treturn nil, errors.New(\"no RequestInfo found in the context\")\n\t}\n\n\t// Start with common attributes that apply to resource and non-resource requests\n\tattribs.ResourceRequest = requestInfo.IsResourceRequest\n\tattribs.Path = requestInfo.Path\n\tattribs.Verb = requestInfo.Verb\n\n\tattribs.APIGroup = requestInfo.APIGroup\n\tattribs.APIVersion = requestInfo.APIVersion\n\tattribs.Resource = requestInfo.Resource\n\tattribs.Subresource = requestInfo.Subresource\n\tattribs.Namespace = requestInfo.Namespace\n\tattribs.Name = requestInfo.Name\n\n\treturn \u0026attribs, nil\n}","line":{"from":81,"to":107}} {"id":100017417,"name":"WithCacheControl","signature":"func WithCacheControl(handler http.Handler) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/cachecontrol.go","code":"// WithCacheControl sets the Cache-Control header to \"no-cache, private\" because all servers are protected by authn/authz.\n// see https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching#defining_optimal_cache-control_policy\nfunc WithCacheControl(handler http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\t// Set the cache-control header if it is not already set\n\t\tif _, ok := w.Header()[\"Cache-Control\"]; !ok {\n\t\t\tw.Header().Set(\"Cache-Control\", \"no-cache, private\")\n\t\t}\n\t\thandler.ServeHTTP(w, req)\n\t})\n}","line":{"from":23,"to":33}} {"id":100017418,"name":"WithImpersonation","signature":"func WithImpersonation(handler http.Handler, a authorizer.Authorizer, s runtime.NegotiatedSerializer) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/impersonation.go","code":"// WithImpersonation is a filter that will inspect and check requests that attempt to change the user.Info for their requests\nfunc WithImpersonation(handler http.Handler, a authorizer.Authorizer, s runtime.NegotiatedSerializer) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\timpersonationRequests, err := buildImpersonationRequests(req.Header)\n\t\tif err != nil {\n\t\t\tklog.V(4).Infof(\"%v\", err)\n\t\t\tresponsewriters.InternalError(w, req, err)\n\t\t\treturn\n\t\t}\n\t\tif len(impersonationRequests) == 0 {\n\t\t\thandler.ServeHTTP(w, req)\n\t\t\treturn\n\t\t}\n\n\t\tctx := req.Context()\n\t\trequestor, exists := request.UserFrom(ctx)\n\t\tif !exists {\n\t\t\tresponsewriters.InternalError(w, req, errors.New(\"no user found for request\"))\n\t\t\treturn\n\t\t}\n\n\t\t// if groups are not specified, then we need to look them up differently depending on the type of user\n\t\t// if they are specified, then they are the authority (including the inclusion of system:authenticated/system:unauthenticated groups)\n\t\tgroupsSpecified := len(req.Header[authenticationv1.ImpersonateGroupHeader]) \u003e 0\n\n\t\t// make sure we're allowed to impersonate each thing we're requesting. While we're iterating through, start building username\n\t\t// and group information\n\t\tusername := \"\"\n\t\tgroups := []string{}\n\t\tuserExtra := map[string][]string{}\n\t\tuid := \"\"\n\t\tfor _, impersonationRequest := range impersonationRequests {\n\t\t\tgvk := impersonationRequest.GetObjectKind().GroupVersionKind()\n\t\t\tactingAsAttributes := \u0026authorizer.AttributesRecord{\n\t\t\t\tUser: requestor,\n\t\t\t\tVerb: \"impersonate\",\n\t\t\t\tAPIGroup: gvk.Group,\n\t\t\t\tAPIVersion: gvk.Version,\n\t\t\t\tNamespace: impersonationRequest.Namespace,\n\t\t\t\tName: impersonationRequest.Name,\n\t\t\t\tResourceRequest: true,\n\t\t\t}\n\n\t\t\tswitch gvk.GroupKind() {\n\t\t\tcase v1.SchemeGroupVersion.WithKind(\"ServiceAccount\").GroupKind():\n\t\t\t\tactingAsAttributes.Resource = \"serviceaccounts\"\n\t\t\t\tusername = serviceaccount.MakeUsername(impersonationRequest.Namespace, impersonationRequest.Name)\n\t\t\t\tif !groupsSpecified {\n\t\t\t\t\t// if groups aren't specified for a service account, we know the groups because its a fixed mapping. Add them\n\t\t\t\t\tgroups = serviceaccount.MakeGroupNames(impersonationRequest.Namespace)\n\t\t\t\t}\n\n\t\t\tcase v1.SchemeGroupVersion.WithKind(\"User\").GroupKind():\n\t\t\t\tactingAsAttributes.Resource = \"users\"\n\t\t\t\tusername = impersonationRequest.Name\n\n\t\t\tcase v1.SchemeGroupVersion.WithKind(\"Group\").GroupKind():\n\t\t\t\tactingAsAttributes.Resource = \"groups\"\n\t\t\t\tgroups = append(groups, impersonationRequest.Name)\n\n\t\t\tcase authenticationv1.SchemeGroupVersion.WithKind(\"UserExtra\").GroupKind():\n\t\t\t\textraKey := impersonationRequest.FieldPath\n\t\t\t\textraValue := impersonationRequest.Name\n\t\t\t\tactingAsAttributes.Resource = \"userextras\"\n\t\t\t\tactingAsAttributes.Subresource = extraKey\n\t\t\t\tuserExtra[extraKey] = append(userExtra[extraKey], extraValue)\n\n\t\t\tcase authenticationv1.SchemeGroupVersion.WithKind(\"UID\").GroupKind():\n\t\t\t\tuid = string(impersonationRequest.Name)\n\t\t\t\tactingAsAttributes.Resource = \"uids\"\n\n\t\t\tdefault:\n\t\t\t\tklog.V(4).InfoS(\"unknown impersonation request type\", \"request\", impersonationRequest)\n\t\t\t\tresponsewriters.Forbidden(ctx, actingAsAttributes, w, req, fmt.Sprintf(\"unknown impersonation request type: %v\", impersonationRequest), s)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tdecision, reason, err := a.Authorize(ctx, actingAsAttributes)\n\t\t\tif err != nil || decision != authorizer.DecisionAllow {\n\t\t\t\tklog.V(4).InfoS(\"Forbidden\", \"URI\", req.RequestURI, \"reason\", reason, \"err\", err)\n\t\t\t\tresponsewriters.Forbidden(ctx, actingAsAttributes, w, req, reason, s)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tif username != user.Anonymous {\n\t\t\t// When impersonating a non-anonymous user, include the 'system:authenticated' group\n\t\t\t// in the impersonated user info:\n\t\t\t// - if no groups were specified\n\t\t\t// - if a group has been specified other than 'system:authenticated'\n\t\t\t//\n\t\t\t// If 'system:unauthenticated' group has been specified we should not include\n\t\t\t// the 'system:authenticated' group.\n\t\t\taddAuthenticated := true\n\t\t\tfor _, group := range groups {\n\t\t\t\tif group == user.AllAuthenticated || group == user.AllUnauthenticated {\n\t\t\t\t\taddAuthenticated = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif addAuthenticated {\n\t\t\t\tgroups = append(groups, user.AllAuthenticated)\n\t\t\t}\n\t\t} else {\n\t\t\taddUnauthenticated := true\n\t\t\tfor _, group := range groups {\n\t\t\t\tif group == user.AllUnauthenticated {\n\t\t\t\t\taddUnauthenticated = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif addUnauthenticated {\n\t\t\t\tgroups = append(groups, user.AllUnauthenticated)\n\t\t\t}\n\t\t}\n\n\t\tnewUser := \u0026user.DefaultInfo{\n\t\t\tName: username,\n\t\t\tGroups: groups,\n\t\t\tExtra: userExtra,\n\t\t\tUID: uid,\n\t\t}\n\t\treq = req.WithContext(request.WithUser(ctx, newUser))\n\n\t\toldUser, _ := request.UserFrom(ctx)\n\t\thttplog.LogOf(req, w).Addf(\"%v is acting as %v\", oldUser, newUser)\n\n\t\tae := audit.AuditEventFrom(ctx)\n\t\taudit.LogImpersonatedUser(ae, newUser)\n\n\t\t// clear all the impersonation headers from the request\n\t\treq.Header.Del(authenticationv1.ImpersonateUserHeader)\n\t\treq.Header.Del(authenticationv1.ImpersonateGroupHeader)\n\t\treq.Header.Del(authenticationv1.ImpersonateUIDHeader)\n\t\tfor headerName := range req.Header {\n\t\t\tif strings.HasPrefix(headerName, authenticationv1.ImpersonateUserExtraHeaderPrefix) {\n\t\t\t\treq.Header.Del(headerName)\n\t\t\t}\n\t\t}\n\n\t\thandler.ServeHTTP(w, req)\n\t})\n}","line":{"from":40,"to":184}} {"id":100017419,"name":"unescapeExtraKey","signature":"func unescapeExtraKey(encodedKey string) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/impersonation.go","code":"func unescapeExtraKey(encodedKey string) string {\n\tkey, err := url.PathUnescape(encodedKey) // Decode %-encoded bytes.\n\tif err != nil {\n\t\treturn encodedKey // Always record extra strings, even if malformed/unencoded.\n\t}\n\treturn key\n}","line":{"from":186,"to":192}} {"id":100017420,"name":"buildImpersonationRequests","signature":"func buildImpersonationRequests(headers http.Header) ([]v1.ObjectReference, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/impersonation.go","code":"// buildImpersonationRequests returns a list of objectreferences that represent the different things we're requesting to impersonate.\n// Also includes a map[string][]string representing user.Info.Extra\n// Each request must be authorized against the current user before switching contexts.\nfunc buildImpersonationRequests(headers http.Header) ([]v1.ObjectReference, error) {\n\timpersonationRequests := []v1.ObjectReference{}\n\n\trequestedUser := headers.Get(authenticationv1.ImpersonateUserHeader)\n\thasUser := len(requestedUser) \u003e 0\n\tif hasUser {\n\t\tif namespace, name, err := serviceaccount.SplitUsername(requestedUser); err == nil {\n\t\t\timpersonationRequests = append(impersonationRequests, v1.ObjectReference{Kind: \"ServiceAccount\", Namespace: namespace, Name: name})\n\t\t} else {\n\t\t\timpersonationRequests = append(impersonationRequests, v1.ObjectReference{Kind: \"User\", Name: requestedUser})\n\t\t}\n\t}\n\n\thasGroups := false\n\tfor _, group := range headers[authenticationv1.ImpersonateGroupHeader] {\n\t\thasGroups = true\n\t\timpersonationRequests = append(impersonationRequests, v1.ObjectReference{Kind: \"Group\", Name: group})\n\t}\n\n\thasUserExtra := false\n\tfor headerName, values := range headers {\n\t\tif !strings.HasPrefix(headerName, authenticationv1.ImpersonateUserExtraHeaderPrefix) {\n\t\t\tcontinue\n\t\t}\n\n\t\thasUserExtra = true\n\t\textraKey := unescapeExtraKey(strings.ToLower(headerName[len(authenticationv1.ImpersonateUserExtraHeaderPrefix):]))\n\n\t\t// make a separate request for each extra value they're trying to set\n\t\tfor _, value := range values {\n\t\t\timpersonationRequests = append(impersonationRequests,\n\t\t\t\tv1.ObjectReference{\n\t\t\t\t\tKind: \"UserExtra\",\n\t\t\t\t\t// we only parse out a group above, but the parsing will fail if there isn't SOME version\n\t\t\t\t\t// using the internal version will help us fail if anyone starts using it\n\t\t\t\t\tAPIVersion: authenticationv1.SchemeGroupVersion.String(),\n\t\t\t\t\tName: value,\n\t\t\t\t\t// ObjectReference doesn't have a subresource field. FieldPath is close and available, so we'll use that\n\t\t\t\t\t// TODO fight the good fight for ObjectReference to refer to resources and subresources\n\t\t\t\t\tFieldPath: extraKey,\n\t\t\t\t})\n\t\t}\n\t}\n\n\trequestedUID := headers.Get(authenticationv1.ImpersonateUIDHeader)\n\thasUID := len(requestedUID) \u003e 0\n\tif hasUID {\n\t\timpersonationRequests = append(impersonationRequests, v1.ObjectReference{\n\t\t\tKind: \"UID\",\n\t\t\tName: requestedUID,\n\t\t\tAPIVersion: authenticationv1.SchemeGroupVersion.String(),\n\t\t})\n\t}\n\n\tif (hasGroups || hasUserExtra || hasUID) \u0026\u0026 !hasUser {\n\t\treturn nil, fmt.Errorf(\"requested %v without impersonating a user\", impersonationRequests)\n\t}\n\n\treturn impersonationRequests, nil\n}","line":{"from":194,"to":256}} {"id":100017421,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/metrics.go","code":"func init() {\n\tlegacyregistry.MustRegister(authenticatedUserCounter)\n\tlegacyregistry.MustRegister(authenticatedAttemptsCounter)\n\tlegacyregistry.MustRegister(authenticationLatency)\n}","line":{"from":73,"to":77}} {"id":100017422,"name":"recordAuthMetrics","signature":"func recordAuthMetrics(ctx context.Context, resp *authenticator.Response, ok bool, err error, apiAudiences authenticator.Audiences, authStart time.Time, authFinish time.Time)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/metrics.go","code":"func recordAuthMetrics(ctx context.Context, resp *authenticator.Response, ok bool, err error, apiAudiences authenticator.Audiences, authStart time.Time, authFinish time.Time) {\n\tvar resultLabel string\n\n\tswitch {\n\tcase err != nil || (resp != nil \u0026\u0026 !audiencesAreAcceptable(apiAudiences, resp.Audiences)):\n\t\tresultLabel = errorLabel\n\tcase !ok:\n\t\tresultLabel = failureLabel\n\tdefault:\n\t\tresultLabel = successLabel\n\t\tauthenticatedUserCounter.WithContext(ctx).WithLabelValues(compressUsername(resp.User.GetName())).Inc()\n\t}\n\n\tauthenticatedAttemptsCounter.WithContext(ctx).WithLabelValues(resultLabel).Inc()\n\tauthenticationLatency.WithContext(ctx).WithLabelValues(resultLabel).Observe(authFinish.Sub(authStart).Seconds())\n}","line":{"from":79,"to":94}} {"id":100017423,"name":"compressUsername","signature":"func compressUsername(username string) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/metrics.go","code":"// compressUsername maps all possible usernames onto a small set of categories\n// of usernames. This is done both to limit the cardinality of the\n// authorized_user_requests metric, and to avoid pushing actual usernames in the\n// metric.\nfunc compressUsername(username string) string {\n\tswitch {\n\t// Known internal identities.\n\tcase username == \"admin\" ||\n\t\tusername == \"client\" ||\n\t\tusername == \"kube_proxy\" ||\n\t\tusername == \"kubelet\" ||\n\t\tusername == \"system:serviceaccount:kube-system:default\":\n\t\treturn username\n\t// Probably an email address.\n\tcase strings.Contains(username, \"@\"):\n\t\treturn \"email_id\"\n\t// Anything else (custom service accounts, custom external identities, etc.)\n\tdefault:\n\t\treturn \"other\"\n\t}\n}","line":{"from":96,"to":116}} {"id":100017424,"name":"NoMuxAndDiscoveryIncompleteKey","signature":"func NoMuxAndDiscoveryIncompleteKey(ctx context.Context) bool","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/mux_discovery_complete.go","code":"// NoMuxAndDiscoveryIncompleteKey checks if the context contains muxAndDiscoveryIncompleteKey.\n// The presence of the key indicates the request has been made when the HTTP paths weren't installed.\nfunc NoMuxAndDiscoveryIncompleteKey(ctx context.Context) bool {\n\tmuxAndDiscoveryCompleteProtectionKeyValue, _ := ctx.Value(muxAndDiscoveryIncompleteKey).(string)\n\treturn len(muxAndDiscoveryCompleteProtectionKeyValue) == 0\n}","line":{"from":31,"to":36}} {"id":100017425,"name":"WithMuxAndDiscoveryComplete","signature":"func WithMuxAndDiscoveryComplete(handler http.Handler, muxAndDiscoveryCompleteSignal \u003c-chan struct{}) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/mux_discovery_complete.go","code":"// WithMuxAndDiscoveryComplete puts the muxAndDiscoveryIncompleteKey in the context if a request has been made before muxAndDiscoveryCompleteSignal has been ready.\n// Putting the key protect us from returning a 404 response instead of a 503.\n// It is especially important for controllers like GC and NS since they act on 404s.\n//\n// The presence of the key is checked in the NotFoundHandler (staging/src/k8s.io/apiserver/pkg/util/notfoundhandler/not_found_handler.go)\n//\n// The primary reason this filter exists is to protect from a potential race between the client's requests reaching the NotFoundHandler and the server becoming ready.\n// Without the protection key a request could still get a 404 response when the registered signals changed their status just slightly before reaching the new handler.\n// In that case, the presence of the key will make the handler return a 503 instead of a 404.\nfunc WithMuxAndDiscoveryComplete(handler http.Handler, muxAndDiscoveryCompleteSignal \u003c-chan struct{}) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tif muxAndDiscoveryCompleteSignal != nil \u0026\u0026 !isClosed(muxAndDiscoveryCompleteSignal) {\n\t\t\treq = req.WithContext(context.WithValue(req.Context(), muxAndDiscoveryIncompleteKey, \"MuxAndDiscoveryInstallationNotComplete\"))\n\t\t}\n\t\thandler.ServeHTTP(w, req)\n\t})\n}","line":{"from":38,"to":54}} {"id":100017426,"name":"isClosed","signature":"func isClosed(ch \u003c-chan struct{}) bool","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/mux_discovery_complete.go","code":"// isClosed is a convenience function that simply check if the given chan has been closed\nfunc isClosed(ch \u003c-chan struct{}) bool {\n\tselect {\n\tcase \u003c-ch:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":56,"to":64}} {"id":100017427,"name":"WithRequestDeadline","signature":"func WithRequestDeadline(handler http.Handler, sink audit.Sink, policy audit.PolicyRuleEvaluator, longRunning request.LongRunningRequestCheck,","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/request_deadline.go","code":"// WithRequestDeadline determines the timeout duration applicable to the given request and sets a new context\n// with the appropriate deadline.\n// auditWrapper provides an http.Handler that audits a failed request.\n// longRunning returns true if he given request is a long running request.\n// requestTimeoutMaximum specifies the default request timeout value.\nfunc WithRequestDeadline(handler http.Handler, sink audit.Sink, policy audit.PolicyRuleEvaluator, longRunning request.LongRunningRequestCheck,\n\tnegotiatedSerializer runtime.NegotiatedSerializer, requestTimeoutMaximum time.Duration) http.Handler {\n\treturn withRequestDeadline(handler, sink, policy, longRunning, negotiatedSerializer, requestTimeoutMaximum, clock.RealClock{})\n}","line":{"from":44,"to":52}} {"id":100017428,"name":"withRequestDeadline","signature":"func withRequestDeadline(handler http.Handler, sink audit.Sink, policy audit.PolicyRuleEvaluator, longRunning request.LongRunningRequestCheck,","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/request_deadline.go","code":"func withRequestDeadline(handler http.Handler, sink audit.Sink, policy audit.PolicyRuleEvaluator, longRunning request.LongRunningRequestCheck,\n\tnegotiatedSerializer runtime.NegotiatedSerializer, requestTimeoutMaximum time.Duration, clock clock.PassiveClock) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tctx := req.Context()\n\n\t\trequestInfo, ok := request.RequestInfoFrom(ctx)\n\t\tif !ok {\n\t\t\thandleError(w, req, http.StatusInternalServerError, fmt.Errorf(\"no RequestInfo found in context, handler chain must be wrong\"))\n\t\t\treturn\n\t\t}\n\t\tif longRunning(req, requestInfo) {\n\t\t\thandler.ServeHTTP(w, req)\n\t\t\treturn\n\t\t}\n\n\t\tuserSpecifiedTimeout, ok, err := parseTimeout(req)\n\t\tif err != nil {\n\t\t\tstatusErr := apierrors.NewBadRequest(err.Error())\n\n\t\t\tklog.Errorf(\"Error - %s: %#v\", err.Error(), req.RequestURI)\n\n\t\t\tfailed := failedErrorHandler(negotiatedSerializer, statusErr)\n\t\t\tfailWithAudit := withFailedRequestAudit(failed, statusErr, sink, policy)\n\t\t\tfailWithAudit.ServeHTTP(w, req)\n\t\t\treturn\n\t\t}\n\n\t\ttimeout := requestTimeoutMaximum\n\t\tif ok {\n\t\t\t// we use the default timeout enforced by the apiserver:\n\t\t\t// - if the user has specified a timeout of 0s, this implies no timeout on the user's part.\n\t\t\t// - if the user has specified a timeout that exceeds the maximum deadline allowed by the apiserver.\n\t\t\tif userSpecifiedTimeout \u003e 0 \u0026\u0026 userSpecifiedTimeout \u003c requestTimeoutMaximum {\n\t\t\t\ttimeout = userSpecifiedTimeout\n\t\t\t}\n\t\t}\n\n\t\tstarted := clock.Now()\n\t\tif requestStartedTimestamp, ok := request.ReceivedTimestampFrom(ctx); ok {\n\t\t\tstarted = requestStartedTimestamp\n\t\t}\n\n\t\tctx, cancel := context.WithDeadline(ctx, started.Add(timeout))\n\t\tdefer cancel()\n\n\t\treq = req.WithContext(ctx)\n\t\thandler.ServeHTTP(w, req)\n\t})\n}","line":{"from":54,"to":102}} {"id":100017429,"name":"withFailedRequestAudit","signature":"func withFailedRequestAudit(failedHandler http.Handler, statusErr *apierrors.StatusError, sink audit.Sink, policy audit.PolicyRuleEvaluator) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/request_deadline.go","code":"// withFailedRequestAudit decorates a failed http.Handler and is used to audit a failed request.\n// statusErr is used to populate the Message property of ResponseStatus.\nfunc withFailedRequestAudit(failedHandler http.Handler, statusErr *apierrors.StatusError, sink audit.Sink, policy audit.PolicyRuleEvaluator) http.Handler {\n\tif sink == nil || policy == nil {\n\t\treturn failedHandler\n\t}\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tac, err := evaluatePolicyAndCreateAuditEvent(req, policy)\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"failed to create audit event: %v\", err))\n\t\t\tresponsewriters.InternalError(w, req, errors.New(\"failed to create audit event\"))\n\t\t\treturn\n\t\t}\n\n\t\tif ac == nil || ac.Event == nil {\n\t\t\tfailedHandler.ServeHTTP(w, req)\n\t\t\treturn\n\t\t}\n\t\tev := ac.Event\n\n\t\tev.ResponseStatus = \u0026metav1.Status{}\n\t\tev.Stage = auditinternal.StageResponseStarted\n\t\tif statusErr != nil {\n\t\t\tev.ResponseStatus.Message = statusErr.Error()\n\t\t}\n\n\t\trw := decorateResponseWriter(req.Context(), w, ev, sink, ac.RequestAuditConfig.OmitStages)\n\t\tfailedHandler.ServeHTTP(rw, req)\n\t})\n}","line":{"from":104,"to":133}} {"id":100017430,"name":"failedErrorHandler","signature":"func failedErrorHandler(s runtime.NegotiatedSerializer, statusError *apierrors.StatusError) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/request_deadline.go","code":"// failedErrorHandler returns an http.Handler that uses the specified StatusError object\n// to render an error response to the request.\nfunc failedErrorHandler(s runtime.NegotiatedSerializer, statusError *apierrors.StatusError) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tctx := req.Context()\n\t\trequestInfo, found := request.RequestInfoFrom(ctx)\n\t\tif !found {\n\t\t\tresponsewriters.InternalError(w, req, errors.New(\"no RequestInfo found in the context\"))\n\t\t\treturn\n\t\t}\n\n\t\tgv := schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}\n\t\tresponsewriters.ErrorNegotiated(statusError, s, gv, w, req)\n\t})\n}","line":{"from":135,"to":149}} {"id":100017431,"name":"parseTimeout","signature":"func parseTimeout(req *http.Request) (time.Duration, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/request_deadline.go","code":"// parseTimeout parses the given HTTP request URL and extracts the timeout query parameter\n// value if specified by the user.\n// If a timeout is not specified the function returns false and err is set to nil\n// If the value specified is malformed then the function returns false and err is set\nfunc parseTimeout(req *http.Request) (time.Duration, bool, error) {\n\tvalue := req.URL.Query().Get(\"timeout\")\n\tif value == \"\" {\n\t\treturn 0, false, nil\n\t}\n\n\ttimeout, err := time.ParseDuration(value)\n\tif err != nil {\n\t\treturn 0, false, fmt.Errorf(\"%s - %s\", invalidTimeoutInURL, err.Error())\n\t}\n\n\treturn timeout, true, nil\n}","line":{"from":151,"to":167}} {"id":100017432,"name":"handleError","signature":"func handleError(w http.ResponseWriter, r *http.Request, code int, err error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/request_deadline.go","code":"func handleError(w http.ResponseWriter, r *http.Request, code int, err error) {\n\terrorMsg := fmt.Sprintf(\"Error - %s: %#v\", err.Error(), r.RequestURI)\n\thttp.Error(w, errorMsg, code)\n\tklog.Errorf(errorMsg)\n}","line":{"from":169,"to":173}} {"id":100017433,"name":"WithRequestReceivedTimestamp","signature":"func WithRequestReceivedTimestamp(handler http.Handler) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/request_received_time.go","code":"// WithRequestReceivedTimestamp attaches the ReceivedTimestamp (the time the request reached\n// the apiserver) to the context.\nfunc WithRequestReceivedTimestamp(handler http.Handler) http.Handler {\n\treturn withRequestReceivedTimestampWithClock(handler, clock.RealClock{})\n}","line":{"from":26,"to":30}} {"id":100017434,"name":"withRequestReceivedTimestampWithClock","signature":"func withRequestReceivedTimestampWithClock(handler http.Handler, clock clock.PassiveClock) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/request_received_time.go","code":"// The clock is passed as a parameter, handy for unit testing.\nfunc withRequestReceivedTimestampWithClock(handler http.Handler, clock clock.PassiveClock) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tctx := req.Context()\n\t\treq = req.WithContext(request.WithReceivedTimestamp(ctx, clock.Now()))\n\n\t\thandler.ServeHTTP(w, req)\n\t})\n}","line":{"from":32,"to":40}} {"id":100017435,"name":"WithRequestInfo","signature":"func WithRequestInfo(handler http.Handler, resolver request.RequestInfoResolver) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/requestinfo.go","code":"// WithRequestInfo attaches a RequestInfo to the context.\nfunc WithRequestInfo(handler http.Handler, resolver request.RequestInfoResolver) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tctx := req.Context()\n\t\tinfo, err := resolver.NewRequestInfo(req)\n\t\tif err != nil {\n\t\t\tresponsewriters.InternalError(w, req, fmt.Errorf(\"failed to create RequestInfo: %v\", err))\n\t\t\treturn\n\t\t}\n\n\t\treq = req.WithContext(request.WithRequestInfo(ctx, info))\n\n\t\thandler.ServeHTTP(w, req)\n\t})\n}","line":{"from":27,"to":41}} {"id":100017436,"name":"WithStorageVersionPrecondition","signature":"func WithStorageVersionPrecondition(handler http.Handler, svm storageversion.Manager, s runtime.NegotiatedSerializer) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/storageversion.go","code":"// WithStorageVersionPrecondition checks if the storage version barrier has\n// completed, if not, it only passes the following API requests:\n// 1. non-resource requests,\n// 2. read requests,\n// 3. write requests to the storageversion API,\n// 4. create requests to the namespace API sent by apiserver itself,\n// 5. write requests to the lease API in kube-system namespace,\n// 6. resources whose StorageVersion is not pending update, including non-persisted resources.\nfunc WithStorageVersionPrecondition(handler http.Handler, svm storageversion.Manager, s runtime.NegotiatedSerializer) http.Handler {\n\tif svm == nil {\n\t\t// TODO(roycaihw): switch to warning after the feature graduate to beta/GA\n\t\tklog.V(2).Infof(\"Storage Version barrier is disabled\")\n\t\treturn handler\n\t}\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tif svm.Completed() {\n\t\t\thandler.ServeHTTP(w, req)\n\t\t\treturn\n\t\t}\n\t\tctx := req.Context()\n\t\trequestInfo, found := request.RequestInfoFrom(ctx)\n\t\tif !found {\n\t\t\tresponsewriters.InternalError(w, req, errors.New(\"no RequestInfo found in the context\"))\n\t\t\treturn\n\t\t}\n\t\t// Allow non-resource requests\n\t\tif !requestInfo.IsResourceRequest {\n\t\t\thandler.ServeHTTP(w, req)\n\t\t\treturn\n\t\t}\n\t\t// Allow read requests\n\t\tif requestInfo.Verb == \"get\" || requestInfo.Verb == \"list\" || requestInfo.Verb == \"watch\" {\n\t\t\thandler.ServeHTTP(w, req)\n\t\t\treturn\n\t\t}\n\t\t// Allow writes to the storage version API\n\t\tif requestInfo.APIGroup == \"internal.apiserver.k8s.io\" \u0026\u0026 requestInfo.Resource == \"storageversions\" {\n\t\t\thandler.ServeHTTP(w, req)\n\t\t\treturn\n\t\t}\n\t\t// The system namespace is required for apiserver-identity lease to exist. Allow the apiserver\n\t\t// itself to create namespaces.\n\t\t// NOTE: with this exception, if the bootstrap client writes namespaces with a new version,\n\t\t// and the upgraded apiserver dies before updating the StorageVersion for namespaces, the\n\t\t// storage migrator won't be able to tell these namespaces are stored in a different version in etcd.\n\t\t// Because the bootstrap client only creates system namespace and doesn't update them, this can\n\t\t// only happen if the upgraded apiserver is the first apiserver that kicks off namespace creation,\n\t\t// or if an upgraded server that joins an existing cluster has new system namespaces (other\n\t\t// than kube-system, kube-public, kube-node-lease) that need to be created.\n\t\tu, hasUser := request.UserFrom(ctx)\n\t\tif requestInfo.APIGroup == \"\" \u0026\u0026 requestInfo.Resource == \"namespaces\" \u0026\u0026\n\t\t\trequestInfo.Verb == \"create\" \u0026\u0026 hasUser \u0026\u0026\n\t\t\tu.GetName() == user.APIServerUser \u0026\u0026 contains(u.GetGroups(), user.SystemPrivilegedGroup) {\n\t\t\thandler.ServeHTTP(w, req)\n\t\t\treturn\n\t\t}\n\t\t// Allow writes to the lease API in kube-system. The storage version API depends on the\n\t\t// apiserver-identity leases to operate. Leases in kube-system are either apiserver-identity\n\t\t// lease (which gets garbage collected when stale) or leader-election leases (which gets\n\t\t// periodically updated by system components). Both types of leases won't be stale in etcd.\n\t\tif requestInfo.APIGroup == \"coordination.k8s.io\" \u0026\u0026 requestInfo.Resource == \"leases\" \u0026\u0026\n\t\t\trequestInfo.Namespace == metav1.NamespaceSystem {\n\t\t\thandler.ServeHTTP(w, req)\n\t\t\treturn\n\t\t}\n\t\t// If the resource's StorageVersion is not in the to-be-updated list, let it pass.\n\t\t// Non-persisted resources are not in the to-be-updated list, so they will pass.\n\t\tgr := schema.GroupResource{Group: requestInfo.APIGroup, Resource: requestInfo.Resource}\n\t\tif !svm.PendingUpdate(gr) {\n\t\t\thandler.ServeHTTP(w, req)\n\t\t\treturn\n\t\t}\n\n\t\tgv := schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}\n\t\tresponsewriters.ErrorNegotiated(apierrors.NewServiceUnavailable(fmt.Sprintf(\"wait for storage version registration to complete for resource: %v, last seen error: %v\", gr, svm.LastUpdateError(gr))), s, gv, w, req)\n\t})\n}","line":{"from":36,"to":112}} {"id":100017437,"name":"contains","signature":"func contains(s []string, e string) bool","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/storageversion.go","code":"func contains(s []string, e string) bool {\n\tfor _, a := range s {\n\t\tif a == e {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":114,"to":121}} {"id":100017438,"name":"WithTracing","signature":"func WithTracing(handler http.Handler, tp trace.TracerProvider) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/traces.go","code":"// WithTracing adds tracing to requests if the incoming request is sampled\nfunc WithTracing(handler http.Handler, tp trace.TracerProvider) http.Handler {\n\topts := []otelhttp.Option{\n\t\totelhttp.WithPropagators(tracing.Propagators()),\n\t\totelhttp.WithPublicEndpoint(),\n\t\totelhttp.WithTracerProvider(tp),\n\t}\n\t// With Noop TracerProvider, the otelhttp still handles context propagation.\n\t// See https://github.com/open-telemetry/opentelemetry-go/tree/main/example/passthrough\n\treturn otelhttp.NewHandler(handler, \"KubernetesAPI\", opts...)\n}","line":{"from":28,"to":38}} {"id":100017439,"name":"WithWarningRecorder","signature":"func WithWarningRecorder(handler http.Handler) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/warning.go","code":"// WithWarningRecorder attaches a deduplicating k8s.io/apiserver/pkg/warning#WarningRecorder to the request context.\nfunc WithWarningRecorder(handler http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\trecorder := \u0026recorder{writer: w}\n\t\treq = req.WithContext(warning.WithWarningRecorder(req.Context(), recorder))\n\t\thandler.ServeHTTP(w, req)\n\t})\n}","line":{"from":30,"to":37}} {"id":100017440,"name":"AddWarning","signature":"func (r *recorder) AddWarning(agent, text string)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/warning.go","code":"func (r *recorder) AddWarning(agent, text string) {\n\tif len(text) == 0 {\n\t\treturn\n\t}\n\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\n\t// if we've already exceeded our limit and are already truncating, return early\n\tif r.written \u003e= truncateAtTotalRunes \u0026\u0026 r.truncating {\n\t\treturn\n\t}\n\n\t// init if needed\n\tif r.recorded == nil {\n\t\tr.recorded = map[string]bool{}\n\t}\n\n\t// dedupe if already warned\n\tif r.recorded[text] {\n\t\treturn\n\t}\n\tr.recorded[text] = true\n\tr.ordered = append(r.ordered, recordedWarning{agent: agent, text: text})\n\n\t// truncate on a rune boundary, if needed\n\ttextRuneLength := utf8.RuneCountInString(text)\n\tif r.truncating \u0026\u0026 textRuneLength \u003e truncateItemRunes {\n\t\ttext = string([]rune(text)[:truncateItemRunes])\n\t\ttextRuneLength = truncateItemRunes\n\t}\n\n\t// compute the header\n\theader, err := net.NewWarningHeader(299, agent, text)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// if this fits within our limit, or we're already truncating, write and return\n\tif r.written+textRuneLength \u003c= truncateAtTotalRunes || r.truncating {\n\t\tr.written += textRuneLength\n\t\tr.writer.Header().Add(\"Warning\", header)\n\t\treturn\n\t}\n\n\t// otherwise, enable truncation, reset, and replay the existing items as truncated warnings\n\tr.truncating = true\n\tr.written = 0\n\tr.writer.Header().Del(\"Warning\")\n\tutilruntime.HandleError(fmt.Errorf(\"exceeded max warning header size, truncating\"))\n\tfor _, w := range r.ordered {\n\t\tagent := w.agent\n\t\ttext := w.text\n\n\t\ttextRuneLength := utf8.RuneCountInString(text)\n\t\tif textRuneLength \u003e truncateItemRunes {\n\t\t\ttext = string([]rune(text)[:truncateItemRunes])\n\t\t\ttextRuneLength = truncateItemRunes\n\t\t}\n\t\tif header, err := net.NewWarningHeader(299, agent, text); err == nil {\n\t\t\tr.written += textRuneLength\n\t\t\tr.writer.Header().Add(\"Warning\", header)\n\t\t}\n\t}\n}","line":{"from":69,"to":133}} {"id":100017441,"name":"WithLatencyTrackers","signature":"func WithLatencyTrackers(handler http.Handler) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/webhook_duration.go","code":"// WithLatencyTrackers adds a LatencyTrackers instance to the\n// context associated with a request so that we can measure latency\n// incurred in various components within the apiserver.\nfunc WithLatencyTrackers(handler http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tctx := req.Context()\n\t\trequestInfo, ok := request.RequestInfoFrom(ctx)\n\t\tif !ok {\n\t\t\thandleError(w, req, http.StatusInternalServerError, fmt.Errorf(\"no RequestInfo found in context, handler chain must be wrong\"))\n\t\t\treturn\n\t\t}\n\n\t\tif watchVerbs.Has(requestInfo.Verb) {\n\t\t\thandler.ServeHTTP(w, req)\n\t\t\treturn\n\t\t}\n\n\t\treq = req.WithContext(request.WithLatencyTrackers(ctx))\n\t\tw = responsewriter.WrapForHTTP1Or2(\u0026writeLatencyTracker{\n\t\t\tResponseWriter: w,\n\t\t\tctx: req.Context(),\n\t\t})\n\n\t\thandler.ServeHTTP(w, req)\n\t})\n}","line":{"from":34,"to":59}} {"id":100017442,"name":"Unwrap","signature":"func (wt *writeLatencyTracker) Unwrap() http.ResponseWriter","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/webhook_duration.go","code":"func (wt *writeLatencyTracker) Unwrap() http.ResponseWriter {\n\treturn wt.ResponseWriter\n}","line":{"from":69,"to":71}} {"id":100017443,"name":"Write","signature":"func (wt *writeLatencyTracker) Write(bs []byte) (int, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/filters/webhook_duration.go","code":"func (wt *writeLatencyTracker) Write(bs []byte) (int, error) {\n\tstartedAt := time.Now()\n\tdefer func() {\n\t\trequest.TrackResponseWriteLatency(wt.ctx, time.Since(startedAt))\n\t}()\n\n\treturn wt.ResponseWriter.Write(bs)\n}","line":{"from":73,"to":80}} {"id":100017444,"name":"InstallREST","signature":"func (g *APIGroupVersion) InstallREST(container *restful.Container) ([]apidiscoveryv2beta1.APIResourceDiscovery, []*storageversion.ResourceInfo, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/groupversion.go","code":"// InstallREST registers the REST handlers (storage, watch, proxy and redirect) into a restful Container.\n// It is expected that the provided path root prefix will serve all operations. Root MUST NOT end\n// in a slash.\nfunc (g *APIGroupVersion) InstallREST(container *restful.Container) ([]apidiscoveryv2beta1.APIResourceDiscovery, []*storageversion.ResourceInfo, error) {\n\tprefix := path.Join(g.Root, g.GroupVersion.Group, g.GroupVersion.Version)\n\tinstaller := \u0026APIInstaller{\n\t\tgroup: g,\n\t\tprefix: prefix,\n\t\tminRequestTimeout: g.MinRequestTimeout,\n\t}\n\n\tapiResources, resourceInfos, ws, registrationErrors := installer.Install()\n\tversionDiscoveryHandler := discovery.NewAPIVersionHandler(g.Serializer, g.GroupVersion, staticLister{apiResources})\n\tversionDiscoveryHandler.AddToWebService(ws)\n\tcontainer.Add(ws)\n\taggregatedDiscoveryResources, err := ConvertGroupVersionIntoToDiscovery(apiResources)\n\tif err != nil {\n\t\tregistrationErrors = append(registrationErrors, err)\n\t}\n\treturn aggregatedDiscoveryResources, removeNonPersistedResources(resourceInfos), utilerrors.NewAggregate(registrationErrors)\n}","line":{"from":102,"to":122}} {"id":100017445,"name":"removeNonPersistedResources","signature":"func removeNonPersistedResources(infos []*storageversion.ResourceInfo) []*storageversion.ResourceInfo","file":"staging/src/k8s.io/apiserver/pkg/endpoints/groupversion.go","code":"func removeNonPersistedResources(infos []*storageversion.ResourceInfo) []*storageversion.ResourceInfo {\n\tvar filtered []*storageversion.ResourceInfo\n\tfor _, info := range infos {\n\t\t// if EncodingVersion is empty, then the apiserver does not\n\t\t// need to register this resource via the storage version API,\n\t\t// thus we can remove it.\n\t\tif info != nil \u0026\u0026 len(info.EncodingVersion) \u003e 0 {\n\t\t\tfiltered = append(filtered, info)\n\t\t}\n\t}\n\treturn filtered\n}","line":{"from":124,"to":135}} {"id":100017446,"name":"ListAPIResources","signature":"func (s staticLister) ListAPIResources() []metav1.APIResource","file":"staging/src/k8s.io/apiserver/pkg/endpoints/groupversion.go","code":"func (s staticLister) ListAPIResources() []metav1.APIResource {\n\treturn s.list\n}","line":{"from":142,"to":144}} {"id":100017447,"name":"createHandler","signature":"func createHandler(r rest.NamedCreater, scope *RequestScope, admit admission.Interface, includeName bool) http.HandlerFunc","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/create.go","code":"func createHandler(r rest.NamedCreater, scope *RequestScope, admit admission.Interface, includeName bool) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, req *http.Request) {\n\t\tctx := req.Context()\n\t\t// For performance tracking purposes.\n\t\tctx, span := tracing.Start(ctx, \"Create\", traceFields(req)...)\n\t\tdefer span.End(500 * time.Millisecond)\n\n\t\tnamespace, name, err := scope.Namer.Name(req)\n\t\tif err != nil {\n\t\t\tif includeName {\n\t\t\t\t// name was required, return\n\t\t\t\tscope.err(err, w, req)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// otherwise attempt to look up the namespace\n\t\t\tnamespace, err = scope.Namer.Namespace(req)\n\t\t\tif err != nil {\n\t\t\t\tscope.err(err, w, req)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t// enforce a timeout of at most requestTimeoutUpperBound (34s) or less if the user-provided\n\t\t// timeout inside the parent context is lower than requestTimeoutUpperBound.\n\t\tctx, cancel := context.WithTimeout(ctx, requestTimeoutUpperBound)\n\t\tdefer cancel()\n\t\toutputMediaType, _, err := negotiation.NegotiateOutputMediaType(req, scope.Serializer, scope)\n\t\tif err != nil {\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\n\t\tgv := scope.Kind.GroupVersion()\n\t\ts, err := negotiation.NegotiateInputSerializer(req, false, scope.Serializer)\n\t\tif err != nil {\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\n\t\tbody, err := limitedReadBodyWithRecordMetric(ctx, req, scope.MaxRequestBodyBytes, scope.Resource.GroupResource().String(), requestmetrics.Create)\n\t\tif err != nil {\n\t\t\tspan.AddEvent(\"limitedReadBody failed\", attribute.Int(\"len\", len(body)), attribute.String(\"err\", err.Error()))\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\t\tspan.AddEvent(\"limitedReadBody succeeded\", attribute.Int(\"len\", len(body)))\n\n\t\toptions := \u0026metav1.CreateOptions{}\n\t\tvalues := req.URL.Query()\n\t\tif err := metainternalversionscheme.ParameterCodec.DecodeParameters(values, scope.MetaGroupVersion, options); err != nil {\n\t\t\terr = errors.NewBadRequest(err.Error())\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\t\tif errs := validation.ValidateCreateOptions(options); len(errs) \u003e 0 {\n\t\t\terr := errors.NewInvalid(schema.GroupKind{Group: metav1.GroupName, Kind: \"CreateOptions\"}, \"\", errs)\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\t\toptions.TypeMeta.SetGroupVersionKind(metav1.SchemeGroupVersion.WithKind(\"CreateOptions\"))\n\n\t\tdefaultGVK := scope.Kind\n\t\toriginal := r.New()\n\n\t\tvalidationDirective := fieldValidation(options.FieldValidation)\n\t\tdecodeSerializer := s.Serializer\n\t\tif validationDirective == metav1.FieldValidationWarn || validationDirective == metav1.FieldValidationStrict {\n\t\t\tdecodeSerializer = s.StrictSerializer\n\t\t}\n\n\t\tdecoder := scope.Serializer.DecoderToVersion(decodeSerializer, scope.HubGroupVersion)\n\t\tspan.AddEvent(\"About to convert to expected version\")\n\t\tobj, gvk, err := decoder.Decode(body, \u0026defaultGVK, original)\n\t\tif err != nil {\n\t\t\tstrictError, isStrictError := runtime.AsStrictDecodingError(err)\n\t\t\tswitch {\n\t\t\tcase isStrictError \u0026\u0026 obj != nil \u0026\u0026 validationDirective == metav1.FieldValidationWarn:\n\t\t\t\taddStrictDecodingWarnings(req.Context(), strictError.Errors())\n\t\t\tcase isStrictError \u0026\u0026 validationDirective == metav1.FieldValidationIgnore:\n\t\t\t\tklog.Warningf(\"unexpected strict error when field validation is set to ignore\")\n\t\t\t\tfallthrough\n\t\t\tdefault:\n\t\t\t\terr = transformDecodeError(scope.Typer, err, original, gvk, body)\n\t\t\t\tscope.err(err, w, req)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tobjGV := gvk.GroupVersion()\n\t\tif !scope.AcceptsGroupVersion(objGV) {\n\t\t\terr = errors.NewBadRequest(fmt.Sprintf(\"the API version in the data (%s) does not match the expected API version (%v)\", objGV.String(), gv.String()))\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\t\tspan.AddEvent(\"Conversion done\")\n\n\t\t// On create, get name from new object if unset\n\t\tif len(name) == 0 {\n\t\t\t_, name, _ = scope.Namer.ObjectName(obj)\n\t\t}\n\t\tif len(namespace) == 0 \u0026\u0026 scope.Resource == namespaceGVR {\n\t\t\tnamespace = name\n\t\t}\n\t\tctx = request.WithNamespace(ctx, namespace)\n\n\t\tadmit = admission.WithAudit(admit)\n\t\taudit.LogRequestObject(req.Context(), obj, objGV, scope.Resource, scope.Subresource, scope.Serializer)\n\n\t\tuserInfo, _ := request.UserFrom(ctx)\n\n\t\tif objectMeta, err := meta.Accessor(obj); err == nil {\n\t\t\tpreserveObjectMetaSystemFields := false\n\t\t\tif c, ok := r.(rest.SubresourceObjectMetaPreserver); ok \u0026\u0026 len(scope.Subresource) \u003e 0 {\n\t\t\t\tpreserveObjectMetaSystemFields = c.PreserveRequestObjectMetaSystemFieldsOnSubresourceCreate()\n\t\t\t}\n\t\t\tif !preserveObjectMetaSystemFields {\n\t\t\t\trest.WipeObjectMetaSystemFields(objectMeta)\n\t\t\t}\n\n\t\t\t// ensure namespace on the object is correct, or error if a conflicting namespace was set in the object\n\t\t\tif err := rest.EnsureObjectNamespaceMatchesRequestNamespace(rest.ExpectedNamespaceForResource(namespace, scope.Resource), objectMeta); err != nil {\n\t\t\t\tscope.err(err, w, req)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tspan.AddEvent(\"About to store object in database\")\n\t\tadmissionAttributes := admission.NewAttributesRecord(obj, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Create, options, dryrun.IsDryRun(options.DryRun), userInfo)\n\t\trequestFunc := func() (runtime.Object, error) {\n\t\t\treturn r.Create(\n\t\t\t\tctx,\n\t\t\t\tname,\n\t\t\t\tobj,\n\t\t\t\trest.AdmissionToValidateObjectFunc(admit, admissionAttributes, scope),\n\t\t\t\toptions,\n\t\t\t)\n\t\t}\n\t\t// Dedup owner references before updating managed fields\n\t\tdedupOwnerReferencesAndAddWarning(obj, req.Context(), false)\n\t\tresult, err := finisher.FinishRequest(ctx, func() (runtime.Object, error) {\n\t\t\tif scope.FieldManager != nil {\n\t\t\t\tliveObj, err := scope.Creater.New(scope.Kind)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"failed to create new object (Create for %v): %v\", scope.Kind, err)\n\t\t\t\t}\n\t\t\t\tobj = scope.FieldManager.UpdateNoErrors(liveObj, obj, managerOrUserAgent(options.FieldManager, req.UserAgent()))\n\t\t\t\tadmit = fieldmanager.NewManagedFieldsValidatingAdmissionController(admit)\n\t\t\t}\n\t\t\tif mutatingAdmission, ok := admit.(admission.MutationInterface); ok \u0026\u0026 mutatingAdmission.Handles(admission.Create) {\n\t\t\t\tif err := mutatingAdmission.Admit(ctx, admissionAttributes, scope); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Dedup owner references again after mutating admission happens\n\t\t\tdedupOwnerReferencesAndAddWarning(obj, req.Context(), true)\n\t\t\tresult, err := requestFunc()\n\t\t\t// If the object wasn't committed to storage because it's serialized size was too large,\n\t\t\t// it is safe to remove managedFields (which can be large) and try again.\n\t\t\tif isTooLargeError(err) {\n\t\t\t\tif accessor, accessorErr := meta.Accessor(obj); accessorErr == nil {\n\t\t\t\t\taccessor.SetManagedFields(nil)\n\t\t\t\t\tresult, err = requestFunc()\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result, err\n\t\t})\n\t\tif err != nil {\n\t\t\tspan.AddEvent(\"Write to database call failed\", attribute.Int(\"len\", len(body)), attribute.String(\"err\", err.Error()))\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\t\tspan.AddEvent(\"Write to database call succeeded\", attribute.Int(\"len\", len(body)))\n\n\t\tcode := http.StatusCreated\n\t\tstatus, ok := result.(*metav1.Status)\n\t\tif ok \u0026\u0026 status.Code == 0 {\n\t\t\tstatus.Code = int32(code)\n\t\t}\n\n\t\tspan.AddEvent(\"About to write a response\")\n\t\tdefer span.AddEvent(\"Writing http response done\")\n\t\ttransformResponseObject(ctx, scope, req, w, code, outputMediaType, result)\n\t}\n}","line":{"from":53,"to":237}} {"id":100017448,"name":"CreateNamedResource","signature":"func CreateNamedResource(r rest.NamedCreater, scope *RequestScope, admission admission.Interface) http.HandlerFunc","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/create.go","code":"// CreateNamedResource returns a function that will handle a resource creation with name.\nfunc CreateNamedResource(r rest.NamedCreater, scope *RequestScope, admission admission.Interface) http.HandlerFunc {\n\treturn createHandler(r, scope, admission, true)\n}","line":{"from":239,"to":242}} {"id":100017449,"name":"CreateResource","signature":"func CreateResource(r rest.Creater, scope *RequestScope, admission admission.Interface) http.HandlerFunc","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/create.go","code":"// CreateResource returns a function that will handle a resource creation.\nfunc CreateResource(r rest.Creater, scope *RequestScope, admission admission.Interface) http.HandlerFunc {\n\treturn createHandler(\u0026namedCreaterAdapter{r}, scope, admission, false)\n}","line":{"from":244,"to":247}} {"id":100017450,"name":"Create","signature":"func (c *namedCreaterAdapter) Create(ctx context.Context, name string, obj runtime.Object, createValidatingAdmission rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/create.go","code":"func (c *namedCreaterAdapter) Create(ctx context.Context, name string, obj runtime.Object, createValidatingAdmission rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {\n\treturn c.Creater.Create(ctx, obj, createValidatingAdmission, options)\n}","line":{"from":253,"to":255}} {"id":100017451,"name":"managerOrUserAgent","signature":"func managerOrUserAgent(manager, userAgent string) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/create.go","code":"// manager is assumed to be already a valid value, we need to make\n// userAgent into a valid value too.\nfunc managerOrUserAgent(manager, userAgent string) string {\n\tif manager != \"\" {\n\t\treturn manager\n\t}\n\treturn prefixFromUserAgent(userAgent)\n}","line":{"from":257,"to":264}} {"id":100017452,"name":"prefixFromUserAgent","signature":"func prefixFromUserAgent(u string) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/create.go","code":"// prefixFromUserAgent takes the characters preceding the first /, quote\n// unprintable character and then trim what's beyond the\n// FieldManagerMaxLength limit.\nfunc prefixFromUserAgent(u string) string {\n\tm := strings.Split(u, \"/\")[0]\n\tbuf := bytes.NewBuffer(nil)\n\tfor _, r := range m {\n\t\t// Ignore non-printable characters\n\t\tif !unicode.IsPrint(r) {\n\t\t\tcontinue\n\t\t}\n\t\t// Only append if we have room for it\n\t\tif buf.Len()+utf8.RuneLen(r) \u003e validation.FieldManagerMaxLength {\n\t\t\tbreak\n\t\t}\n\t\tbuf.WriteRune(r)\n\t}\n\treturn buf.String()\n}","line":{"from":266,"to":284}} {"id":100017453,"name":"DeleteResource","signature":"func DeleteResource(r rest.GracefulDeleter, allowsOptions bool, scope *RequestScope, admit admission.Interface) http.HandlerFunc","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/delete.go","code":"// DeleteResource returns a function that will handle a resource deletion\n// TODO admission here becomes solely validating admission\nfunc DeleteResource(r rest.GracefulDeleter, allowsOptions bool, scope *RequestScope, admit admission.Interface) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, req *http.Request) {\n\t\tctx := req.Context()\n\t\t// For performance tracking purposes.\n\t\tctx, span := tracing.Start(ctx, \"Delete\", traceFields(req)...)\n\t\tdefer span.End(500 * time.Millisecond)\n\n\t\tnamespace, name, err := scope.Namer.Name(req)\n\t\tif err != nil {\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\n\t\t// enforce a timeout of at most requestTimeoutUpperBound (34s) or less if the user-provided\n\t\t// timeout inside the parent context is lower than requestTimeoutUpperBound.\n\t\tctx, cancel := context.WithTimeout(ctx, requestTimeoutUpperBound)\n\t\tdefer cancel()\n\n\t\tctx = request.WithNamespace(ctx, namespace)\n\t\tadmit = admission.WithAudit(admit)\n\n\t\toutputMediaType, _, err := negotiation.NegotiateOutputMediaType(req, scope.Serializer, scope)\n\t\tif err != nil {\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\n\t\toptions := \u0026metav1.DeleteOptions{}\n\t\tif allowsOptions {\n\t\t\tbody, err := limitedReadBodyWithRecordMetric(ctx, req, scope.MaxRequestBodyBytes, scope.Resource.GroupResource().String(), requestmetrics.Delete)\n\t\t\tif err != nil {\n\t\t\t\tspan.AddEvent(\"limitedReadBody failed\", attribute.Int(\"len\", len(body)), attribute.String(\"err\", err.Error()))\n\t\t\t\tscope.err(err, w, req)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tspan.AddEvent(\"limitedReadBody succeeded\", attribute.Int(\"len\", len(body)))\n\t\t\tif len(body) \u003e 0 {\n\t\t\t\ts, err := negotiation.NegotiateInputSerializer(req, false, metainternalversionscheme.Codecs)\n\t\t\t\tif err != nil {\n\t\t\t\t\tscope.err(err, w, req)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// For backwards compatibility, we need to allow existing clients to submit per group DeleteOptions\n\t\t\t\t// It is also allowed to pass a body with meta.k8s.io/v1.DeleteOptions\n\t\t\t\tdefaultGVK := scope.MetaGroupVersion.WithKind(\"DeleteOptions\")\n\t\t\t\tobj, gvk, err := metainternalversionscheme.Codecs.DecoderToVersion(s.Serializer, defaultGVK.GroupVersion()).Decode(body, \u0026defaultGVK, options)\n\t\t\t\tif err != nil {\n\t\t\t\t\tscope.err(err, w, req)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif obj != options {\n\t\t\t\t\tscope.err(fmt.Errorf(\"decoded object cannot be converted to DeleteOptions\"), w, req)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tspan.AddEvent(\"Decoded delete options\")\n\n\t\t\t\tobjGV := gvk.GroupVersion()\n\t\t\t\taudit.LogRequestObject(req.Context(), obj, objGV, scope.Resource, scope.Subresource, metainternalversionscheme.Codecs)\n\t\t\t\tspan.AddEvent(\"Recorded the audit event\")\n\t\t\t} else {\n\t\t\t\tif err := metainternalversionscheme.ParameterCodec.DecodeParameters(req.URL.Query(), scope.MetaGroupVersion, options); err != nil {\n\t\t\t\t\terr = errors.NewBadRequest(err.Error())\n\t\t\t\t\tscope.err(err, w, req)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif errs := validation.ValidateDeleteOptions(options); len(errs) \u003e 0 {\n\t\t\terr := errors.NewInvalid(schema.GroupKind{Group: metav1.GroupName, Kind: \"DeleteOptions\"}, \"\", errs)\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\t\toptions.TypeMeta.SetGroupVersionKind(metav1.SchemeGroupVersion.WithKind(\"DeleteOptions\"))\n\n\t\tspan.AddEvent(\"About to delete object from database\")\n\t\twasDeleted := true\n\t\tuserInfo, _ := request.UserFrom(ctx)\n\t\tstaticAdmissionAttrs := admission.NewAttributesRecord(nil, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Delete, options, dryrun.IsDryRun(options.DryRun), userInfo)\n\t\tresult, err := finisher.FinishRequest(ctx, func() (runtime.Object, error) {\n\t\t\tobj, deleted, err := r.Delete(ctx, name, rest.AdmissionToValidateObjectDeleteFunc(admit, staticAdmissionAttrs, scope), options)\n\t\t\twasDeleted = deleted\n\t\t\treturn obj, err\n\t\t})\n\t\tif err != nil {\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\t\tspan.AddEvent(\"Object deleted from database\")\n\n\t\tstatus := http.StatusOK\n\t\t// Return http.StatusAccepted if the resource was not deleted immediately and\n\t\t// user requested cascading deletion by setting OrphanDependents=false.\n\t\t// Note: We want to do this always if resource was not deleted immediately, but\n\t\t// that will break existing clients.\n\t\t// Other cases where resource is not instantly deleted are: namespace deletion\n\t\t// and pod graceful deletion.\n\t\t//nolint:staticcheck // SA1019 backwards compatibility\n\t\t//nolint: staticcheck\n\t\tif !wasDeleted \u0026\u0026 options.OrphanDependents != nil \u0026\u0026 !*options.OrphanDependents {\n\t\t\tstatus = http.StatusAccepted\n\t\t}\n\t\t// if the rest.Deleter returns a nil object, fill out a status. Callers may return a valid\n\t\t// object with the response.\n\t\tif result == nil {\n\t\t\tresult = \u0026metav1.Status{\n\t\t\t\tStatus: metav1.StatusSuccess,\n\t\t\t\tCode: int32(status),\n\t\t\t\tDetails: \u0026metav1.StatusDetails{\n\t\t\t\t\tName: name,\n\t\t\t\t\tKind: scope.Kind.Kind,\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\n\t\tspan.AddEvent(\"About to write a response\")\n\t\tdefer span.AddEvent(\"Writing http response done\")\n\t\ttransformResponseObject(ctx, scope, req, w, status, outputMediaType, result)\n\t}\n}","line":{"from":48,"to":168}} {"id":100017454,"name":"DeleteCollection","signature":"func DeleteCollection(r rest.CollectionDeleter, checkBody bool, scope *RequestScope, admit admission.Interface) http.HandlerFunc","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/delete.go","code":"// DeleteCollection returns a function that will handle a collection deletion\nfunc DeleteCollection(r rest.CollectionDeleter, checkBody bool, scope *RequestScope, admit admission.Interface) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, req *http.Request) {\n\t\tctx := req.Context()\n\t\tctx, span := tracing.Start(ctx, \"Delete\", traceFields(req)...)\n\t\tdefer span.End(500 * time.Millisecond)\n\n\t\tnamespace, err := scope.Namer.Namespace(req)\n\t\tif err != nil {\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\n\t\t// DELETECOLLECTION can be a lengthy operation,\n\t\t// we should not impose any 34s timeout here.\n\t\t// NOTE: This is similar to LIST which does not enforce a 34s timeout.\n\t\tctx = request.WithNamespace(ctx, namespace)\n\n\t\toutputMediaType, _, err := negotiation.NegotiateOutputMediaType(req, scope.Serializer, scope)\n\t\tif err != nil {\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\n\t\tlistOptions := metainternalversion.ListOptions{}\n\t\tif err := metainternalversionscheme.ParameterCodec.DecodeParameters(req.URL.Query(), scope.MetaGroupVersion, \u0026listOptions); err != nil {\n\t\t\terr = errors.NewBadRequest(err.Error())\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\n\t\tmetainternalversion.SetListOptionsDefaults(\u0026listOptions, utilfeature.DefaultFeatureGate.Enabled(features.WatchList))\n\t\tif errs := metainternalversionvalidation.ValidateListOptions(\u0026listOptions, utilfeature.DefaultFeatureGate.Enabled(features.WatchList)); len(errs) \u003e 0 {\n\t\t\terr := errors.NewInvalid(schema.GroupKind{Group: metav1.GroupName, Kind: \"ListOptions\"}, \"\", errs)\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\n\t\t// transform fields\n\t\t// TODO: DecodeParametersInto should do this.\n\t\tif listOptions.FieldSelector != nil {\n\t\t\tfn := func(label, value string) (newLabel, newValue string, err error) {\n\t\t\t\treturn scope.Convertor.ConvertFieldLabel(scope.Kind, label, value)\n\t\t\t}\n\t\t\tif listOptions.FieldSelector, err = listOptions.FieldSelector.Transform(fn); err != nil {\n\t\t\t\t// TODO: allow bad request to set field causes based on query parameters\n\t\t\t\terr = errors.NewBadRequest(err.Error())\n\t\t\t\tscope.err(err, w, req)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\toptions := \u0026metav1.DeleteOptions{}\n\t\tif checkBody {\n\t\t\tbody, err := limitedReadBodyWithRecordMetric(ctx, req, scope.MaxRequestBodyBytes, scope.Resource.GroupResource().String(), requestmetrics.DeleteCollection)\n\t\t\tif err != nil {\n\t\t\t\tspan.AddEvent(\"limitedReadBody failed\", attribute.Int(\"len\", len(body)), attribute.String(\"err\", err.Error()))\n\t\t\t\tscope.err(err, w, req)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tspan.AddEvent(\"limitedReadBody succeeded\", attribute.Int(\"len\", len(body)))\n\t\t\tif len(body) \u003e 0 {\n\t\t\t\ts, err := negotiation.NegotiateInputSerializer(req, false, metainternalversionscheme.Codecs)\n\t\t\t\tif err != nil {\n\t\t\t\t\tscope.err(err, w, req)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// For backwards compatibility, we need to allow existing clients to submit per group DeleteOptions\n\t\t\t\t// It is also allowed to pass a body with meta.k8s.io/v1.DeleteOptions\n\t\t\t\tdefaultGVK := scope.MetaGroupVersion.WithKind(\"DeleteOptions\")\n\t\t\t\tobj, gvk, err := metainternalversionscheme.Codecs.DecoderToVersion(s.Serializer, defaultGVK.GroupVersion()).Decode(body, \u0026defaultGVK, options)\n\t\t\t\tif err != nil {\n\t\t\t\t\tscope.err(err, w, req)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif obj != options {\n\t\t\t\t\tscope.err(fmt.Errorf(\"decoded object cannot be converted to DeleteOptions\"), w, req)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tobjGV := gvk.GroupVersion()\n\t\t\t\taudit.LogRequestObject(req.Context(), obj, objGV, scope.Resource, scope.Subresource, metainternalversionscheme.Codecs)\n\t\t\t} else {\n\t\t\t\tif err := metainternalversionscheme.ParameterCodec.DecodeParameters(req.URL.Query(), scope.MetaGroupVersion, options); err != nil {\n\t\t\t\t\terr = errors.NewBadRequest(err.Error())\n\t\t\t\t\tscope.err(err, w, req)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif errs := validation.ValidateDeleteOptions(options); len(errs) \u003e 0 {\n\t\t\terr := errors.NewInvalid(schema.GroupKind{Group: metav1.GroupName, Kind: \"DeleteOptions\"}, \"\", errs)\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\t\toptions.TypeMeta.SetGroupVersionKind(metav1.SchemeGroupVersion.WithKind(\"DeleteOptions\"))\n\n\t\tadmit = admission.WithAudit(admit)\n\t\tuserInfo, _ := request.UserFrom(ctx)\n\t\tstaticAdmissionAttrs := admission.NewAttributesRecord(nil, nil, scope.Kind, namespace, \"\", scope.Resource, scope.Subresource, admission.Delete, options, dryrun.IsDryRun(options.DryRun), userInfo)\n\t\tresult, err := finisher.FinishRequest(ctx, func() (runtime.Object, error) {\n\t\t\treturn r.DeleteCollection(ctx, rest.AdmissionToValidateObjectDeleteFunc(admit, staticAdmissionAttrs, scope), options, \u0026listOptions)\n\t\t})\n\t\tif err != nil {\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\n\t\t// if the rest.Deleter returns a nil object, fill out a status. Callers may return a valid\n\t\t// object with the response.\n\t\tif result == nil {\n\t\t\tresult = \u0026metav1.Status{\n\t\t\t\tStatus: metav1.StatusSuccess,\n\t\t\t\tCode: http.StatusOK,\n\t\t\t\tDetails: \u0026metav1.StatusDetails{\n\t\t\t\t\tKind: scope.Kind.Kind,\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\n\t\tspan.AddEvent(\"About to write a response\")\n\t\tdefer span.AddEvent(\"Writing http response done\")\n\t\ttransformResponseObject(ctx, scope, req, w, http.StatusOK, outputMediaType, result)\n\t}\n}","line":{"from":170,"to":294}} {"id":100017455,"name":"NewManagedFieldsValidatingAdmissionController","signature":"func NewManagedFieldsValidatingAdmissionController(wrap admission.Interface) admission.Interface","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/admission.go","code":"// NewManagedFieldsValidatingAdmissionController validates the managedFields after calling\n// the provided admission and resets them to their original state if they got changed to an invalid value\nfunc NewManagedFieldsValidatingAdmissionController(wrap admission.Interface) admission.Interface {\n\tif wrap == nil {\n\t\treturn nil\n\t}\n\treturn \u0026managedFieldsValidatingAdmissionController{wrap: wrap}\n}","line":{"from":33,"to":40}} {"id":100017456,"name":"Handles","signature":"func (admit *managedFieldsValidatingAdmissionController) Handles(operation admission.Operation) bool","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/admission.go","code":"// Handles calls the wrapped admission.Interface if applicable\nfunc (admit *managedFieldsValidatingAdmissionController) Handles(operation admission.Operation) bool {\n\treturn admit.wrap.Handles(operation)\n}","line":{"from":50,"to":53}} {"id":100017457,"name":"Admit","signature":"func (admit *managedFieldsValidatingAdmissionController) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/admission.go","code":"// Admit calls the wrapped admission.Interface if applicable and resets the managedFields to their state before admission if they\n// got modified in an invalid way\nfunc (admit *managedFieldsValidatingAdmissionController) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {\n\tmutationInterface, isMutationInterface := admit.wrap.(admission.MutationInterface)\n\tif !isMutationInterface {\n\t\treturn nil\n\t}\n\tobjectMeta, err := meta.Accessor(a.GetObject())\n\tif err != nil {\n\t\t// the object we are dealing with doesn't have object metadata defined\n\t\t// in that case we don't have to keep track of the managedField\n\t\t// just call the wrapped admission\n\t\treturn mutationInterface.Admit(ctx, a, o)\n\t}\n\tmanagedFieldsBeforeAdmission := objectMeta.GetManagedFields()\n\tif err := mutationInterface.Admit(ctx, a, o); err != nil {\n\t\treturn err\n\t}\n\tmanagedFieldsAfterAdmission := objectMeta.GetManagedFields()\n\tif err := managedfields.ValidateManagedFields(managedFieldsAfterAdmission); err != nil {\n\t\tobjectMeta.SetManagedFields(managedFieldsBeforeAdmission)\n\t\twarning.AddWarning(ctx, \"\",\n\t\t\tfmt.Sprintf(InvalidManagedFieldsAfterMutatingAdmissionWarningFormat,\n\t\t\t\terr.Error()),\n\t\t)\n\t}\n\treturn nil\n}","line":{"from":55,"to":82}} {"id":100017458,"name":"Validate","signature":"func (admit *managedFieldsValidatingAdmissionController) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/admission.go","code":"// Validate calls the wrapped admission.Interface if aplicable\nfunc (admit *managedFieldsValidatingAdmissionController) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {\n\tif validationInterface, isValidationInterface := admit.wrap.(admission.ValidationInterface); isValidationInterface {\n\t\treturn validationInterface.Validate(ctx, a, o)\n\t}\n\treturn nil\n}","line":{"from":84,"to":90}} {"id":100017459,"name":"getAvoidTimestampEqualities","signature":"func getAvoidTimestampEqualities() conversion.Equalities","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/equality.go","code":"func getAvoidTimestampEqualities() conversion.Equalities {\n\tinitAvoidTimestampEqualities.Do(func() {\n\t\tif avoidNoopTimestampUpdatesString, exists := os.LookupEnv(\"KUBE_APISERVER_AVOID_NOOP_SSA_TIMESTAMP_UPDATES\"); exists {\n\t\t\tif ret, err := strconv.ParseBool(avoidNoopTimestampUpdatesString); err == nil \u0026\u0026 !ret {\n\t\t\t\t// leave avoidTimestampEqualities empty.\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\tklog.Errorf(\"failed to parse envar KUBE_APISERVER_AVOID_NOOP_SSA_TIMESTAMP_UPDATES: %v\", err)\n\t\t\t}\n\t\t}\n\n\t\tvar eqs = equality.Semantic.Copy()\n\t\terr := eqs.AddFunc(\n\t\t\tfunc(a, b metav1.ManagedFieldsEntry) bool {\n\t\t\t\t// Two objects' managed fields are equivalent if, ignoring timestamp,\n\t\t\t\t//\tthe objects are deeply equal.\n\t\t\t\ta.Time = nil\n\t\t\t\tb.Time = nil\n\t\t\t\treturn reflect.DeepEqual(a, b)\n\t\t\t},\n\t\t)\n\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"failed to instantiate semantic equalities: %w\", err))\n\t\t}\n\n\t\tavoidTimestampEqualities = eqs\n\t})\n\treturn avoidTimestampEqualities\n}","line":{"from":42,"to":71}} {"id":100017460,"name":"IgnoreManagedFieldsTimestampsTransformer","signature":"func IgnoreManagedFieldsTimestampsTransformer(","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/equality.go","code":"// IgnoreManagedFieldsTimestampsTransformer reverts timestamp updates\n// if the non-managed parts of the object are equivalent\nfunc IgnoreManagedFieldsTimestampsTransformer(\n\t_ context.Context,\n\tnewObj runtime.Object,\n\toldObj runtime.Object,\n) (res runtime.Object, err error) {\n\tequalities := getAvoidTimestampEqualities()\n\tif len(equalities.Equalities) == 0 {\n\t\treturn newObj, nil\n\t}\n\n\toutcome := \"unequal_objects_fast\"\n\tstart := time.Now()\n\terr = nil\n\tres = nil\n\n\tdefer func() {\n\t\tif err != nil {\n\t\t\toutcome = \"error\"\n\t\t}\n\n\t\tmetrics.RecordTimestampComparisonLatency(outcome, time.Since(start))\n\t}()\n\n\t// If managedFields modulo timestamps are unchanged\n\t//\t\tand\n\t//\trest of object is unchanged\n\t//\t\tthen\n\t//\trevert any changes to timestamps in managed fields\n\t//\t\t(to prevent spurious ResourceVersion bump)\n\t//\n\t// Procecure:\n\t// Do a quicker check to see if just managed fields modulo timestamps are\n\t//\tunchanged. If so, then do the full, slower check.\n\t//\n\t// In most cases which actually update the object, the managed fields modulo\n\t//\ttimestamp check will fail, and we will be able to return early.\n\t//\n\t// In other cases, the managed fields may be exactly the same,\n\t// \texcept for timestamp, but the objects are the different. This is the\n\t//\tslow path which checks the full object.\n\toldAccessor, err := meta.Accessor(oldObj)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to acquire accessor for oldObj: %v\", err)\n\t}\n\n\taccessor, err := meta.Accessor(newObj)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to acquire accessor for newObj: %v\", err)\n\t}\n\n\toldManagedFields := oldAccessor.GetManagedFields()\n\tnewManagedFields := accessor.GetManagedFields()\n\n\tif len(oldManagedFields) != len(newManagedFields) {\n\t\t// Return early if any managed fields entry was added/removed.\n\t\t// We want to retain user expectation that even if they write to a field\n\t\t// whose value did not change, they will still result as the field\n\t\t// manager at the end.\n\t\treturn newObj, nil\n\t} else if len(newManagedFields) == 0 {\n\t\t// This transformation only makes sense when managedFields are\n\t\t// non-empty\n\t\treturn newObj, nil\n\t}\n\n\t// This transformation only makes sense if the managed fields has at least one\n\t// changed timestamp; and are otherwise equal. Return early if there are no\n\t// changed timestamps.\n\tallTimesUnchanged := true\n\tfor i, e := range newManagedFields {\n\t\tif !e.Time.Equal(oldManagedFields[i].Time) {\n\t\t\tallTimesUnchanged = false\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif allTimesUnchanged {\n\t\treturn newObj, nil\n\t}\n\n\t// This condition ensures the managed fields are always compared first. If\n\t//\tthis check fails, the if statement will short circuit. If the check\n\t// \tsucceeds the slow path is taken which compares entire objects.\n\tif !equalities.DeepEqualWithNilDifferentFromEmpty(oldManagedFields, newManagedFields) {\n\t\treturn newObj, nil\n\t}\n\n\tif equalities.DeepEqualWithNilDifferentFromEmpty(newObj, oldObj) {\n\t\t// Remove any changed timestamps, so that timestamp is not the only\n\t\t// change seen by etcd.\n\t\t//\n\t\t// newManagedFields is known to be exactly pairwise equal to\n\t\t// oldManagedFields except for timestamps.\n\t\t//\n\t\t// Simply replace possibly changed new timestamps with their old values.\n\t\tfor idx := 0; idx \u003c len(oldManagedFields); idx++ {\n\t\t\tnewManagedFields[idx].Time = oldManagedFields[idx].Time\n\t\t}\n\n\t\taccessor.SetManagedFields(newManagedFields)\n\t\toutcome = \"equal_objects\"\n\t\treturn newObj, nil\n\t}\n\n\toutcome = \"unequal_objects_slow\"\n\treturn newObj, nil\n}","line":{"from":73,"to":181}} {"id":100017461,"name":"Return","signature":"func (r *result) Return() (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/finisher/finisher.go","code":"// Return processes the result returned by a ResultFunc function\nfunc (r *result) Return() (runtime.Object, error) {\n\tswitch {\n\tcase r.reason != nil:\n\t\t// panic has higher precedence, the goroutine executing ResultFunc has panic'd,\n\t\t// so propagate a panic to the caller.\n\t\tpanic(r.reason)\n\tcase r.err != nil:\n\t\treturn nil, r.err\n\tdefault:\n\t\t// if we are here, it means neither a panic, nor an error\n\t\tif status, ok := r.object.(*metav1.Status); ok {\n\t\t\t// An api.Status object with status != success is considered an \"error\",\n\t\t\t// which interrupts the normal response flow.\n\t\t\tif status.Status != metav1.StatusSuccess {\n\t\t\t\treturn nil, errors.FromObject(status)\n\t\t\t}\n\t\t}\n\t\treturn r.object, nil\n\t}\n}","line":{"from":47,"to":67}} {"id":100017462,"name":"FinishRequest","signature":"func FinishRequest(ctx context.Context, fn ResultFunc) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/finisher/finisher.go","code":"// FinishRequest makes a given ResultFunc asynchronous and handles errors returned by the response.\nfunc FinishRequest(ctx context.Context, fn ResultFunc) (runtime.Object, error) {\n\treturn finishRequest(ctx, fn, postTimeoutLoggerWait, logPostTimeoutResult)\n}","line":{"from":82,"to":85}} {"id":100017463,"name":"finishRequest","signature":"func finishRequest(ctx context.Context, fn ResultFunc, postTimeoutWait time.Duration, postTimeoutLogger PostTimeoutLoggerFunc) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/finisher/finisher.go","code":"func finishRequest(ctx context.Context, fn ResultFunc, postTimeoutWait time.Duration, postTimeoutLogger PostTimeoutLoggerFunc) (runtime.Object, error) {\n\t// the channel needs to be buffered since the post-timeout receiver goroutine\n\t// waits up to 5 minutes for the child goroutine to return.\n\tresultCh := make(chan *result, 1)\n\n\tgo func() {\n\t\tresult := \u0026result{}\n\n\t\t// panics don't cross goroutine boundaries, so we have to handle ourselves\n\t\tdefer func() {\n\t\t\treason := recover()\n\t\t\tif reason != nil {\n\t\t\t\t// do not wrap the sentinel ErrAbortHandler panic value\n\t\t\t\tif reason != http.ErrAbortHandler {\n\t\t\t\t\t// Same as stdlib http server code. Manually allocate stack\n\t\t\t\t\t// trace buffer size to prevent excessively large logs\n\t\t\t\t\tconst size = 64 \u003c\u003c 10\n\t\t\t\t\tbuf := make([]byte, size)\n\t\t\t\t\tbuf = buf[:goruntime.Stack(buf, false)]\n\t\t\t\t\treason = fmt.Sprintf(\"%v\\n%s\", reason, buf)\n\t\t\t\t}\n\n\t\t\t\t// store the panic reason into the result.\n\t\t\t\tresult.reason = reason\n\t\t\t}\n\n\t\t\t// Propagate the result to the parent goroutine\n\t\t\tresultCh \u003c- result\n\t\t}()\n\n\t\tif object, err := fn(); err != nil {\n\t\t\tresult.err = err\n\t\t} else {\n\t\t\tresult.object = object\n\t\t}\n\t}()\n\n\tselect {\n\tcase result := \u003c-resultCh:\n\t\treturn result.Return()\n\tcase \u003c-ctx.Done():\n\t\t// we are going to send a timeout response to the caller, but the asynchronous goroutine\n\t\t// (sender) is still executing the ResultFunc function.\n\t\t// kick off a goroutine (receiver) here to wait for the sender (goroutine executing ResultFunc)\n\t\t// to send the result and then log details of the result.\n\t\tdefer func() {\n\t\t\tgo func() {\n\t\t\t\ttimedOutAt := time.Now()\n\n\t\t\t\tvar result *result\n\t\t\t\tselect {\n\t\t\t\tcase result = \u003c-resultCh:\n\t\t\t\tcase \u003c-time.After(postTimeoutWait):\n\t\t\t\t\t// we will not wait forever, if we are here then we know that some sender\n\t\t\t\t\t// goroutines are taking longer than postTimeoutWait.\n\t\t\t\t}\n\t\t\t\tpostTimeoutLogger(timedOutAt, result)\n\t\t\t}()\n\t\t}()\n\t\treturn nil, errors.NewTimeoutError(fmt.Sprintf(\"request did not complete within requested timeout - %s\", ctx.Err()), 0)\n\t}\n}","line":{"from":87,"to":148}} {"id":100017464,"name":"logPostTimeoutResult","signature":"func logPostTimeoutResult(timedOutAt time.Time, r *result)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/finisher/finisher.go","code":"// logPostTimeoutResult logs a panic or an error from the result that the sender (goroutine that is\n// executing the ResultFunc function) has sent to the receiver after the request had timed out.\n// timedOutAt is the time the request had been timed out\nfunc logPostTimeoutResult(timedOutAt time.Time, r *result) {\n\tif r == nil {\n\t\t// we are using r == nil to indicate that the child goroutine never returned a result.\n\t\tmetrics.RecordRequestPostTimeout(metrics.PostTimeoutSourceRestHandler, metrics.PostTimeoutHandlerPending)\n\t\tklog.Errorf(\"FinishRequest: post-timeout activity, waited for %s, child goroutine has not returned yet\", time.Since(timedOutAt))\n\t\treturn\n\t}\n\n\tvar status string\n\tswitch {\n\tcase r.reason != nil:\n\t\t// a non empty reason inside a result object indicates that there was a panic.\n\t\tstatus = metrics.PostTimeoutHandlerPanic\n\tcase r.err != nil:\n\t\tstatus = metrics.PostTimeoutHandlerError\n\tdefault:\n\t\tstatus = metrics.PostTimeoutHandlerOK\n\t}\n\n\tmetrics.RecordRequestPostTimeout(metrics.PostTimeoutSourceRestHandler, status)\n\terr := fmt.Errorf(\"FinishRequest: post-timeout activity - time-elapsed: %s, panicked: %t, err: %v, panic-reason: %v\",\n\t\ttime.Since(timedOutAt), r.reason != nil, r.err, r.reason)\n\tutilruntime.HandleError(err)\n}","line":{"from":150,"to":176}} {"id":100017465,"name":"getResourceHandler","signature":"func getResourceHandler(scope *RequestScope, getter getterFunc) http.HandlerFunc","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/get.go","code":"// getResourceHandler is an HTTP handler function for get requests. It delegates to the\n// passed-in getterFunc to perform the actual get.\nfunc getResourceHandler(scope *RequestScope, getter getterFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, req *http.Request) {\n\t\tctx := req.Context()\n\t\tctx, span := tracing.Start(ctx, \"Get\", traceFields(req)...)\n\t\tdefer span.End(500 * time.Millisecond)\n\n\t\tnamespace, name, err := scope.Namer.Name(req)\n\t\tif err != nil {\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\t\tctx = request.WithNamespace(ctx, namespace)\n\n\t\toutputMediaType, _, err := negotiation.NegotiateOutputMediaType(req, scope.Serializer, scope)\n\t\tif err != nil {\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\n\t\tresult, err := getter(ctx, name, req)\n\t\tif err != nil {\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\n\t\tspan.AddEvent(\"About to write a response\")\n\t\tdefer span.AddEvent(\"Writing http response done\")\n\t\ttransformResponseObject(ctx, scope, req, w, http.StatusOK, outputMediaType, result)\n\t}\n}","line":{"from":53,"to":84}} {"id":100017466,"name":"GetResource","signature":"func GetResource(r rest.Getter, scope *RequestScope) http.HandlerFunc","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/get.go","code":"// GetResource returns a function that handles retrieving a single resource from a rest.Storage object.\nfunc GetResource(r rest.Getter, scope *RequestScope) http.HandlerFunc {\n\treturn getResourceHandler(scope,\n\t\tfunc(ctx context.Context, name string, req *http.Request) (runtime.Object, error) {\n\t\t\t// check for export\n\t\t\toptions := metav1.GetOptions{}\n\t\t\tif values := req.URL.Query(); len(values) \u003e 0 {\n\t\t\t\tif len(values[\"export\"]) \u003e 0 {\n\t\t\t\t\texportBool := true\n\t\t\t\t\texportStrings := values[\"export\"]\n\t\t\t\t\terr := runtime.Convert_Slice_string_To_bool(\u0026exportStrings, \u0026exportBool, nil)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, errors.NewBadRequest(fmt.Sprintf(\"the export parameter cannot be parsed: %v\", err))\n\t\t\t\t\t}\n\t\t\t\t\tif exportBool {\n\t\t\t\t\t\treturn nil, errors.NewBadRequest(\"the export parameter, deprecated since v1.14, is no longer supported\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif err := metainternalversionscheme.ParameterCodec.DecodeParameters(values, scope.MetaGroupVersion, \u0026options); err != nil {\n\t\t\t\t\terr = errors.NewBadRequest(err.Error())\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\ttracing.SpanFromContext(ctx).AddEvent(\"About to Get from storage\")\n\t\t\treturn r.Get(ctx, name, \u0026options)\n\t\t})\n}","line":{"from":86,"to":112}} {"id":100017467,"name":"GetResourceWithOptions","signature":"func GetResourceWithOptions(r rest.GetterWithOptions, scope *RequestScope, isSubresource bool) http.HandlerFunc","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/get.go","code":"// GetResourceWithOptions returns a function that handles retrieving a single resource from a rest.Storage object.\nfunc GetResourceWithOptions(r rest.GetterWithOptions, scope *RequestScope, isSubresource bool) http.HandlerFunc {\n\treturn getResourceHandler(scope,\n\t\tfunc(ctx context.Context, name string, req *http.Request) (runtime.Object, error) {\n\t\t\topts, subpath, subpathKey := r.NewGetOptions()\n\t\t\tspan := tracing.SpanFromContext(ctx)\n\t\t\tspan.AddEvent(\"About to process Get options\")\n\t\t\tif err := getRequestOptions(req, scope, opts, subpath, subpathKey, isSubresource); err != nil {\n\t\t\t\terr = errors.NewBadRequest(err.Error())\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tspan.AddEvent(\"About to Get from storage\")\n\t\t\treturn r.Get(ctx, name, opts)\n\t\t})\n}","line":{"from":114,"to":128}} {"id":100017468,"name":"getRequestOptions","signature":"func getRequestOptions(req *http.Request, scope *RequestScope, into runtime.Object, subpath bool, subpathKey string, isSubresource bool) error","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/get.go","code":"// getRequestOptions parses out options and can include path information. The path information shouldn't include the subresource.\nfunc getRequestOptions(req *http.Request, scope *RequestScope, into runtime.Object, subpath bool, subpathKey string, isSubresource bool) error {\n\tif into == nil {\n\t\treturn nil\n\t}\n\n\tquery := req.URL.Query()\n\tif subpath {\n\t\tnewQuery := make(url.Values)\n\t\tfor k, v := range query {\n\t\t\tnewQuery[k] = v\n\t\t}\n\n\t\tctx := req.Context()\n\t\trequestInfo, _ := request.RequestInfoFrom(ctx)\n\t\tstartingIndex := 2\n\t\tif isSubresource {\n\t\t\tstartingIndex = 3\n\t\t}\n\n\t\tp := strings.Join(requestInfo.Parts[startingIndex:], \"/\")\n\n\t\t// ensure non-empty subpaths correctly reflect a leading slash\n\t\tif len(p) \u003e 0 \u0026\u0026 !strings.HasPrefix(p, \"/\") {\n\t\t\tp = \"/\" + p\n\t\t}\n\n\t\t// ensure subpaths correctly reflect the presence of a trailing slash on the original request\n\t\tif strings.HasSuffix(requestInfo.Path, \"/\") \u0026\u0026 !strings.HasSuffix(p, \"/\") {\n\t\t\tp += \"/\"\n\t\t}\n\n\t\tnewQuery[subpathKey] = []string{p}\n\t\tquery = newQuery\n\t}\n\treturn scope.ParameterCodec.DecodeParameters(query, scope.Kind.GroupVersion(), into)\n}","line":{"from":130,"to":166}} {"id":100017469,"name":"ListResource","signature":"func ListResource(r rest.Lister, rw rest.Watcher, scope *RequestScope, forceWatch bool, minRequestTimeout time.Duration) http.HandlerFunc","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/get.go","code":"func ListResource(r rest.Lister, rw rest.Watcher, scope *RequestScope, forceWatch bool, minRequestTimeout time.Duration) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, req *http.Request) {\n\t\tctx := req.Context()\n\t\t// For performance tracking purposes.\n\t\tctx, span := tracing.Start(ctx, \"List\", traceFields(req)...)\n\n\t\tnamespace, err := scope.Namer.Namespace(req)\n\t\tif err != nil {\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\n\t\t// Watches for single objects are routed to this function.\n\t\t// Treat a name parameter the same as a field selector entry.\n\t\thasName := true\n\t\t_, name, err := scope.Namer.Name(req)\n\t\tif err != nil {\n\t\t\thasName = false\n\t\t}\n\n\t\tctx = request.WithNamespace(ctx, namespace)\n\n\t\toutputMediaType, _, err := negotiation.NegotiateOutputMediaType(req, scope.Serializer, scope)\n\t\tif err != nil {\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\n\t\topts := metainternalversion.ListOptions{}\n\t\tif err := metainternalversionscheme.ParameterCodec.DecodeParameters(req.URL.Query(), scope.MetaGroupVersion, \u0026opts); err != nil {\n\t\t\terr = errors.NewBadRequest(err.Error())\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\n\t\tmetainternalversion.SetListOptionsDefaults(\u0026opts, utilfeature.DefaultFeatureGate.Enabled(features.WatchList))\n\t\tif errs := metainternalversionvalidation.ValidateListOptions(\u0026opts, utilfeature.DefaultFeatureGate.Enabled(features.WatchList)); len(errs) \u003e 0 {\n\t\t\terr := errors.NewInvalid(schema.GroupKind{Group: metav1.GroupName, Kind: \"ListOptions\"}, \"\", errs)\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\n\t\t// transform fields\n\t\t// TODO: DecodeParametersInto should do this.\n\t\tif opts.FieldSelector != nil {\n\t\t\tfn := func(label, value string) (newLabel, newValue string, err error) {\n\t\t\t\treturn scope.Convertor.ConvertFieldLabel(scope.Kind, label, value)\n\t\t\t}\n\t\t\tif opts.FieldSelector, err = opts.FieldSelector.Transform(fn); err != nil {\n\t\t\t\t// TODO: allow bad request to set field causes based on query parameters\n\t\t\t\terr = errors.NewBadRequest(err.Error())\n\t\t\t\tscope.err(err, w, req)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tif hasName {\n\t\t\t// metadata.name is the canonical internal name.\n\t\t\t// SelectionPredicate will notice that this is a request for\n\t\t\t// a single object and optimize the storage query accordingly.\n\t\t\tnameSelector := fields.OneTermEqualSelector(\"metadata.name\", name)\n\n\t\t\t// Note that fieldSelector setting explicitly the \"metadata.name\"\n\t\t\t// will result in reaching this branch (as the value of that field\n\t\t\t// is propagated to requestInfo as the name parameter.\n\t\t\t// That said, the allowed field selectors in this branch are:\n\t\t\t// nil, fields.Everything and field selector matching metadata.name\n\t\t\t// for our name.\n\t\t\tif opts.FieldSelector != nil \u0026\u0026 !opts.FieldSelector.Empty() {\n\t\t\t\tselectedName, ok := opts.FieldSelector.RequiresExactMatch(\"metadata.name\")\n\t\t\t\tif !ok || name != selectedName {\n\t\t\t\t\tscope.err(errors.NewBadRequest(\"fieldSelector metadata.name doesn't match requested name\"), w, req)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\topts.FieldSelector = nameSelector\n\t\t\t}\n\t\t}\n\n\t\tif opts.Watch || forceWatch {\n\t\t\tif rw == nil {\n\t\t\t\tscope.err(errors.NewMethodNotSupported(scope.Resource.GroupResource(), \"watch\"), w, req)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// TODO: Currently we explicitly ignore ?timeout= and use only ?timeoutSeconds=.\n\t\t\ttimeout := time.Duration(0)\n\t\t\tif opts.TimeoutSeconds != nil {\n\t\t\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t\t\t}\n\t\t\tif timeout == 0 \u0026\u0026 minRequestTimeout \u003e 0 {\n\t\t\t\ttimeout = time.Duration(float64(minRequestTimeout) * (rand.Float64() + 1.0))\n\t\t\t}\n\t\t\tklog.V(3).InfoS(\"Starting watch\", \"path\", req.URL.Path, \"resourceVersion\", opts.ResourceVersion, \"labels\", opts.LabelSelector, \"fields\", opts.FieldSelector, \"timeout\", timeout)\n\t\t\tctx, cancel := context.WithTimeout(ctx, timeout)\n\t\t\tdefer cancel()\n\t\t\twatcher, err := rw.Watch(ctx, \u0026opts)\n\t\t\tif err != nil {\n\t\t\t\tscope.err(err, w, req)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequestInfo, _ := request.RequestInfoFrom(ctx)\n\t\t\tmetrics.RecordLongRunning(req, requestInfo, metrics.APIServerComponent, func() {\n\t\t\t\tserveWatch(watcher, scope, outputMediaType, req, w, timeout)\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\t// Log only long List requests (ignore Watch).\n\t\tdefer span.End(500 * time.Millisecond)\n\t\tspan.AddEvent(\"About to List from storage\")\n\t\tresult, err := r.List(ctx, \u0026opts)\n\t\tif err != nil {\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\t\tspan.AddEvent(\"Listing from storage done\")\n\t\tdefer span.AddEvent(\"Writing http response done\", attribute.Int(\"count\", meta.LenList(result)))\n\t\ttransformResponseObject(ctx, scope, req, w, http.StatusOK, outputMediaType, result)\n\t}\n}","line":{"from":168,"to":287}} {"id":100017470,"name":"String","signature":"func (lazy *lazyTruncatedUserAgent) String() string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/helpers.go","code":"func (lazy *lazyTruncatedUserAgent) String() string {\n\tua := \"unknown\"\n\tif lazy.req != nil {\n\t\tua = utilnet.GetHTTPClient(lazy.req)\n\t\tif len(ua) \u003e maxUserAgentLength {\n\t\t\tua = ua[:maxUserAgentLength] + userAgentTruncateSuffix\n\t\t}\n\t}\n\treturn ua\n}","line":{"from":39,"to":48}} {"id":100017471,"name":"String","signature":"func (lazy *lazyClientIP) String() string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/helpers.go","code":"func (lazy *lazyClientIP) String() string {\n\tif lazy.req != nil {\n\t\tif ip := utilnet.GetClientIP(lazy.req); ip != nil {\n\t\t\treturn ip.String()\n\t\t}\n\t}\n\treturn \"unknown\"\n}","line":{"from":56,"to":63}} {"id":100017472,"name":"String","signature":"func (lazy *lazyAccept) String() string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/helpers.go","code":"func (lazy *lazyAccept) String() string {\n\tif lazy.req != nil {\n\t\taccept := lazy.req.Header.Get(\"Accept\")\n\t\treturn accept\n\t}\n\n\treturn \"unknown\"\n}","line":{"from":71,"to":78}} {"id":100017473,"name":"String","signature":"func (lazy *lazyAuditID) String() string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/helpers.go","code":"func (lazy *lazyAuditID) String() string {\n\tif lazy.req != nil {\n\t\treturn audit.GetAuditIDTruncated(lazy.req.Context())\n\t}\n\n\treturn \"unknown\"\n}","line":{"from":86,"to":92}} {"id":100017474,"name":"String","signature":"func (lazy *lazyVerb) String() string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/helpers.go","code":"func (lazy *lazyVerb) String() string {\n\tif lazy.req == nil {\n\t\treturn \"unknown\"\n\t}\n\treturn metrics.NormalizedVerb(lazy.req)\n}","line":{"from":100,"to":105}} {"id":100017475,"name":"String","signature":"func (lazy *lazyResource) String() string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/helpers.go","code":"func (lazy *lazyResource) String() string {\n\tif lazy.req != nil {\n\t\tctx := lazy.req.Context()\n\t\trequestInfo, ok := apirequest.RequestInfoFrom(ctx)\n\t\tif ok {\n\t\t\treturn requestInfo.Resource\n\t\t}\n\t}\n\n\treturn \"unknown\"\n}","line":{"from":113,"to":123}} {"id":100017476,"name":"String","signature":"func (lazy *lazyScope) String() string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/helpers.go","code":"func (lazy *lazyScope) String() string {\n\tif lazy.req != nil {\n\t\tctx := lazy.req.Context()\n\t\trequestInfo, ok := apirequest.RequestInfoFrom(ctx)\n\t\tif ok {\n\t\t\treturn metrics.CleanScope(requestInfo)\n\t\t}\n\t}\n\n\treturn \"unknown\"\n}","line":{"from":131,"to":141}} {"id":100017477,"name":"RecordRequestBodySize","signature":"func RecordRequestBodySize(ctx context.Context, resource string, verb RequestBodyVerb, size int)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/metrics/metrics.go","code":"func RecordRequestBodySize(ctx context.Context, resource string, verb RequestBodyVerb, size int) {\n\tRequestBodySizes.WithContext(ctx).WithLabelValues(resource, string(verb)).Observe(float64(size))\n}","line":{"from":49,"to":51}} {"id":100017478,"name":"Namespace","signature":"func (n ContextBasedNaming) Namespace(req *http.Request) (namespace string, err error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/namer.go","code":"func (n ContextBasedNaming) Namespace(req *http.Request) (namespace string, err error) {\n\trequestInfo, ok := request.RequestInfoFrom(req.Context())\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"missing requestInfo\")\n\t}\n\treturn requestInfo.Namespace, nil\n}","line":{"from":49,"to":55}} {"id":100017479,"name":"Name","signature":"func (n ContextBasedNaming) Name(req *http.Request) (namespace, name string, err error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/namer.go","code":"func (n ContextBasedNaming) Name(req *http.Request) (namespace, name string, err error) {\n\trequestInfo, ok := request.RequestInfoFrom(req.Context())\n\tif !ok {\n\t\treturn \"\", \"\", fmt.Errorf(\"missing requestInfo\")\n\t}\n\n\tif len(requestInfo.Name) == 0 {\n\t\treturn \"\", \"\", errEmptyName\n\t}\n\treturn requestInfo.Namespace, requestInfo.Name, nil\n}","line":{"from":57,"to":67}} {"id":100017480,"name":"ObjectName","signature":"func (n ContextBasedNaming) ObjectName(obj runtime.Object) (namespace, name string, err error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/namer.go","code":"func (n ContextBasedNaming) ObjectName(obj runtime.Object) (namespace, name string, err error) {\n\tname, err = n.Namer.Name(obj)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tif len(name) == 0 {\n\t\treturn \"\", \"\", errEmptyName\n\t}\n\tnamespace, err = n.Namer.Namespace(obj)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\treturn namespace, name, err\n}","line":{"from":69,"to":82}} {"id":100017481,"name":"NewNotAcceptableError","signature":"func NewNotAcceptableError(accepted []string) error","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/errors.go","code":"// NewNotAcceptableError returns an error of NotAcceptable which contains specified string\nfunc NewNotAcceptableError(accepted []string) error {\n\treturn errNotAcceptable{accepted}\n}","line":{"from":32,"to":35}} {"id":100017482,"name":"Error","signature":"func (e errNotAcceptable) Error() string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/errors.go","code":"func (e errNotAcceptable) Error() string {\n\treturn fmt.Sprintf(\"only the following media types are accepted: %v\", strings.Join(e.accepted, \", \"))\n}","line":{"from":37,"to":39}} {"id":100017483,"name":"Status","signature":"func (e errNotAcceptable) Status() metav1.Status","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/errors.go","code":"func (e errNotAcceptable) Status() metav1.Status {\n\treturn metav1.Status{\n\t\tStatus: metav1.StatusFailure,\n\t\tCode: http.StatusNotAcceptable,\n\t\tReason: metav1.StatusReasonNotAcceptable,\n\t\tMessage: e.Error(),\n\t}\n}","line":{"from":41,"to":48}} {"id":100017484,"name":"NewNotAcceptableConversionError","signature":"func NewNotAcceptableConversionError(target string, accepted []string) error","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/errors.go","code":"// NewNotAcceptableConversionError returns an error indicating that the desired\n// API transformation to the target group version kind string is not accepted and\n// only the listed mime types are allowed. This is temporary while Table does not\n// yet support protobuf encoding.\nfunc NewNotAcceptableConversionError(target string, accepted []string) error {\n\treturn errNotAcceptableConversion{target, accepted}\n}","line":{"from":57,"to":63}} {"id":100017485,"name":"Error","signature":"func (e errNotAcceptableConversion) Error() string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/errors.go","code":"func (e errNotAcceptableConversion) Error() string {\n\treturn fmt.Sprintf(\"only the following media types are accepted when converting to %s: %v\", e.target, strings.Join(e.accepted, \", \"))\n}","line":{"from":65,"to":67}} {"id":100017486,"name":"Status","signature":"func (e errNotAcceptableConversion) Status() metav1.Status","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/errors.go","code":"func (e errNotAcceptableConversion) Status() metav1.Status {\n\treturn metav1.Status{\n\t\tStatus: metav1.StatusFailure,\n\t\tCode: http.StatusNotAcceptable,\n\t\tReason: metav1.StatusReasonNotAcceptable,\n\t\tMessage: e.Error(),\n\t}\n}","line":{"from":69,"to":76}} {"id":100017487,"name":"NewUnsupportedMediaTypeError","signature":"func NewUnsupportedMediaTypeError(accepted []string) error","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/errors.go","code":"// NewUnsupportedMediaTypeError returns an error of UnsupportedMediaType which contains specified string\nfunc NewUnsupportedMediaTypeError(accepted []string) error {\n\treturn errUnsupportedMediaType{accepted}\n}","line":{"from":83,"to":86}} {"id":100017488,"name":"Error","signature":"func (e errUnsupportedMediaType) Error() string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/errors.go","code":"func (e errUnsupportedMediaType) Error() string {\n\treturn fmt.Sprintf(\"the body of the request was in an unknown format - accepted media types include: %v\", strings.Join(e.accepted, \", \"))\n}","line":{"from":88,"to":90}} {"id":100017489,"name":"Status","signature":"func (e errUnsupportedMediaType) Status() metav1.Status","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/errors.go","code":"func (e errUnsupportedMediaType) Status() metav1.Status {\n\treturn metav1.Status{\n\t\tStatus: metav1.StatusFailure,\n\t\tCode: http.StatusUnsupportedMediaType,\n\t\tReason: metav1.StatusReasonUnsupportedMediaType,\n\t\tMessage: e.Error(),\n\t}\n}","line":{"from":92,"to":99}} {"id":100017490,"name":"MediaTypesForSerializer","signature":"func MediaTypesForSerializer(ns runtime.NegotiatedSerializer) (mediaTypes, streamMediaTypes []string)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/negotiate.go","code":"// MediaTypesForSerializer returns a list of media and stream media types for the server.\nfunc MediaTypesForSerializer(ns runtime.NegotiatedSerializer) (mediaTypes, streamMediaTypes []string) {\n\tfor _, info := range ns.SupportedMediaTypes() {\n\t\tmediaTypes = append(mediaTypes, info.MediaType)\n\t\tif info.StreamSerializer != nil {\n\t\t\t// stream=watch is the existing mime-type parameter for watch\n\t\t\tstreamMediaTypes = append(streamMediaTypes, info.MediaType+\";stream=watch\")\n\t\t}\n\t}\n\treturn mediaTypes, streamMediaTypes\n}","line":{"from":31,"to":41}} {"id":100017491,"name":"NegotiateOutputMediaType","signature":"func NegotiateOutputMediaType(req *http.Request, ns runtime.NegotiatedSerializer, restrictions EndpointRestrictions) (MediaTypeOptions, runtime.SerializerInfo, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/negotiate.go","code":"// NegotiateOutputMediaType negotiates the output structured media type and a serializer, or\n// returns an error.\nfunc NegotiateOutputMediaType(req *http.Request, ns runtime.NegotiatedSerializer, restrictions EndpointRestrictions) (MediaTypeOptions, runtime.SerializerInfo, error) {\n\tmediaType, ok := NegotiateMediaTypeOptions(req.Header.Get(\"Accept\"), ns.SupportedMediaTypes(), restrictions)\n\tif !ok {\n\t\tsupported, _ := MediaTypesForSerializer(ns)\n\t\treturn mediaType, runtime.SerializerInfo{}, NewNotAcceptableError(supported)\n\t}\n\t// TODO: move into resthandler\n\tinfo := mediaType.Accepted\n\tif (mediaType.Pretty || isPrettyPrint(req)) \u0026\u0026 info.PrettySerializer != nil {\n\t\tinfo.Serializer = info.PrettySerializer\n\t}\n\treturn mediaType, info, nil\n}","line":{"from":43,"to":57}} {"id":100017492,"name":"NegotiateOutputMediaTypeStream","signature":"func NegotiateOutputMediaTypeStream(req *http.Request, ns runtime.NegotiatedSerializer, restrictions EndpointRestrictions) (runtime.SerializerInfo, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/negotiate.go","code":"// NegotiateOutputMediaTypeStream returns a stream serializer for the given request.\nfunc NegotiateOutputMediaTypeStream(req *http.Request, ns runtime.NegotiatedSerializer, restrictions EndpointRestrictions) (runtime.SerializerInfo, error) {\n\tmediaType, ok := NegotiateMediaTypeOptions(req.Header.Get(\"Accept\"), ns.SupportedMediaTypes(), restrictions)\n\tif !ok || mediaType.Accepted.StreamSerializer == nil {\n\t\t_, supported := MediaTypesForSerializer(ns)\n\t\treturn runtime.SerializerInfo{}, NewNotAcceptableError(supported)\n\t}\n\treturn mediaType.Accepted, nil\n}","line":{"from":59,"to":67}} {"id":100017493,"name":"NegotiateInputSerializer","signature":"func NegotiateInputSerializer(req *http.Request, streaming bool, ns runtime.NegotiatedSerializer) (runtime.SerializerInfo, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/negotiate.go","code":"// NegotiateInputSerializer returns the input serializer for the provided request.\nfunc NegotiateInputSerializer(req *http.Request, streaming bool, ns runtime.NegotiatedSerializer) (runtime.SerializerInfo, error) {\n\tmediaType := req.Header.Get(\"Content-Type\")\n\treturn NegotiateInputSerializerForMediaType(mediaType, streaming, ns)\n}","line":{"from":69,"to":73}} {"id":100017494,"name":"NegotiateInputSerializerForMediaType","signature":"func NegotiateInputSerializerForMediaType(mediaType string, streaming bool, ns runtime.NegotiatedSerializer) (runtime.SerializerInfo, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/negotiate.go","code":"// NegotiateInputSerializerForMediaType returns the appropriate serializer for the given media type or an error.\nfunc NegotiateInputSerializerForMediaType(mediaType string, streaming bool, ns runtime.NegotiatedSerializer) (runtime.SerializerInfo, error) {\n\tmediaTypes := ns.SupportedMediaTypes()\n\tif len(mediaType) == 0 {\n\t\tmediaType = mediaTypes[0].MediaType\n\t}\n\tif mediaType, _, err := mime.ParseMediaType(mediaType); err == nil {\n\t\tif info, ok := runtime.SerializerInfoForMediaType(mediaTypes, mediaType); ok {\n\t\t\treturn info, nil\n\t\t}\n\t}\n\n\tsupported, streamingSupported := MediaTypesForSerializer(ns)\n\tif streaming {\n\t\treturn runtime.SerializerInfo{}, NewUnsupportedMediaTypeError(streamingSupported)\n\t}\n\treturn runtime.SerializerInfo{}, NewUnsupportedMediaTypeError(supported)\n}","line":{"from":75,"to":92}} {"id":100017495,"name":"isPrettyPrint","signature":"func isPrettyPrint(req *http.Request) bool","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/negotiate.go","code":"// isPrettyPrint returns true if the \"pretty\" query parameter is true or if the User-Agent\n// matches known \"human\" clients.\nfunc isPrettyPrint(req *http.Request) bool {\n\t// DEPRECATED: should be part of the content type\n\tif req.URL != nil {\n\t\t// avoid an allocation caused by parsing the URL query\n\t\tif strings.Contains(req.URL.RawQuery, \"pretty\") {\n\t\t\tpp := req.URL.Query().Get(\"pretty\")\n\t\t\tif len(pp) \u003e 0 {\n\t\t\t\tpretty, _ := strconv.ParseBool(pp)\n\t\t\t\treturn pretty\n\t\t\t}\n\t\t}\n\t}\n\tuserAgent := req.UserAgent()\n\t// This covers basic all browsers and cli http tools\n\tif strings.HasPrefix(userAgent, \"curl\") || strings.HasPrefix(userAgent, \"Wget\") || strings.HasPrefix(userAgent, \"Mozilla/5.0\") {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":94,"to":114}} {"id":100017496,"name":"AllowsMediaTypeTransform","signature":"func (emptyEndpointRestrictions) AllowsMediaTypeTransform(mimeType string, mimeSubType string, gvk *schema.GroupVersionKind) bool","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/negotiate.go","code":"func (emptyEndpointRestrictions) AllowsMediaTypeTransform(mimeType string, mimeSubType string, gvk *schema.GroupVersionKind) bool {\n\treturn gvk == nil\n}","line":{"from":137,"to":139}} {"id":100017497,"name":"AllowsServerVersion","signature":"func (emptyEndpointRestrictions) AllowsServerVersion(string) bool { return false }","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/negotiate.go","code":"func (emptyEndpointRestrictions) AllowsServerVersion(string) bool { return false }","line":{"from":140,"to":140}} {"id":100017498,"name":"AllowsStreamSchema","signature":"func (emptyEndpointRestrictions) AllowsStreamSchema(s string) bool { return s == \"watch\" }","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/negotiate.go","code":"func (emptyEndpointRestrictions) AllowsStreamSchema(s string) bool { return s == \"watch\" }","line":{"from":141,"to":141}} {"id":100017499,"name":"acceptMediaTypeOptions","signature":"func acceptMediaTypeOptions(params map[string]string, accepts *runtime.SerializerInfo, endpoint EndpointRestrictions) (MediaTypeOptions, bool)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/negotiate.go","code":"// acceptMediaTypeOptions returns an options object that matches the provided media type params. If\n// it returns false, the provided options are not allowed and the media type must be skipped. These\n// parameters are unversioned and may not be changed.\nfunc acceptMediaTypeOptions(params map[string]string, accepts *runtime.SerializerInfo, endpoint EndpointRestrictions) (MediaTypeOptions, bool) {\n\tvar options MediaTypeOptions\n\n\t// extract all known parameters\n\tfor k, v := range params {\n\t\tswitch k {\n\n\t\t// controls transformation of the object when returned\n\t\tcase \"as\":\n\t\t\tif options.Convert == nil {\n\t\t\t\toptions.Convert = \u0026schema.GroupVersionKind{}\n\t\t\t}\n\t\t\toptions.Convert.Kind = v\n\t\tcase \"g\":\n\t\t\tif options.Convert == nil {\n\t\t\t\toptions.Convert = \u0026schema.GroupVersionKind{}\n\t\t\t}\n\t\t\toptions.Convert.Group = v\n\t\tcase \"v\":\n\t\t\tif options.Convert == nil {\n\t\t\t\toptions.Convert = \u0026schema.GroupVersionKind{}\n\t\t\t}\n\t\t\toptions.Convert.Version = v\n\n\t\t// controls the streaming schema\n\t\tcase \"stream\":\n\t\t\tif len(v) \u003e 0 \u0026\u0026 (accepts.StreamSerializer == nil || !endpoint.AllowsStreamSchema(v)) {\n\t\t\t\treturn MediaTypeOptions{}, false\n\t\t\t}\n\t\t\toptions.Stream = v\n\n\t\t// controls the version of the server API group used\n\t\t// for generic output\n\t\tcase \"sv\":\n\t\t\tif len(v) \u003e 0 \u0026\u0026 !endpoint.AllowsServerVersion(v) {\n\t\t\t\treturn MediaTypeOptions{}, false\n\t\t\t}\n\t\t\toptions.UseServerVersion = v\n\n\t\t// if specified, the server should transform the returned\n\t\t// output and remove fields that are always server specified,\n\t\t// or which fit the default behavior.\n\t\tcase \"export\":\n\t\t\toptions.Export = v == \"1\"\n\n\t\t// if specified, the pretty serializer will be used\n\t\tcase \"pretty\":\n\t\t\toptions.Pretty = v == \"1\"\n\n\t\tdefault:\n\t\t\toptions.Unrecognized = append(options.Unrecognized, k)\n\t\t}\n\t}\n\n\tif !endpoint.AllowsMediaTypeTransform(accepts.MediaTypeType, accepts.MediaTypeSubType, options.Convert) {\n\t\treturn MediaTypeOptions{}, false\n\t}\n\n\toptions.Accepted = *accepts\n\treturn options, true\n}","line":{"from":172,"to":235}} {"id":100017500,"name":"NegotiateMediaTypeOptions","signature":"func NegotiateMediaTypeOptions(header string, accepted []runtime.SerializerInfo, endpoint EndpointRestrictions) (MediaTypeOptions, bool)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/negotiation/negotiate.go","code":"// NegotiateMediaTypeOptions returns the most appropriate content type given the accept header and\n// a list of alternatives along with the accepted media type parameters.\nfunc NegotiateMediaTypeOptions(header string, accepted []runtime.SerializerInfo, endpoint EndpointRestrictions) (MediaTypeOptions, bool) {\n\tif len(header) == 0 \u0026\u0026 len(accepted) \u003e 0 {\n\t\treturn MediaTypeOptions{\n\t\t\tAccepted: accepted[0],\n\t\t}, true\n\t}\n\n\tclauses := goautoneg.ParseAccept(header)\n\tfor i := range clauses {\n\t\tclause := \u0026clauses[i]\n\t\tfor i := range accepted {\n\t\t\taccepts := \u0026accepted[i]\n\t\t\tswitch {\n\t\t\tcase clause.Type == accepts.MediaTypeType \u0026\u0026 clause.SubType == accepts.MediaTypeSubType,\n\t\t\t\tclause.Type == accepts.MediaTypeType \u0026\u0026 clause.SubType == \"*\",\n\t\t\t\tclause.Type == \"*\" \u0026\u0026 clause.SubType == \"*\":\n\t\t\t\tif retVal, ret := acceptMediaTypeOptions(clause.Params, accepts, endpoint); ret {\n\t\t\t\t\treturn retVal, true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn MediaTypeOptions{}, false\n}","line":{"from":237,"to":263}} {"id":100017501,"name":"PatchResource","signature":"func PatchResource(r rest.Patcher, scope *RequestScope, admit admission.Interface, patchTypes []string) http.HandlerFunc","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/patch.go","code":"// PatchResource returns a function that will handle a resource patch.\nfunc PatchResource(r rest.Patcher, scope *RequestScope, admit admission.Interface, patchTypes []string) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, req *http.Request) {\n\t\tctx := req.Context()\n\t\t// For performance tracking purposes.\n\t\tctx, span := tracing.Start(ctx, \"Patch\", traceFields(req)...)\n\t\tdefer span.End(500 * time.Millisecond)\n\n\t\t// Do this first, otherwise name extraction can fail for unrecognized content types\n\t\t// TODO: handle this in negotiation\n\t\tcontentType := req.Header.Get(\"Content-Type\")\n\t\t// Remove \"; charset=\" if included in header.\n\t\tif idx := strings.Index(contentType, \";\"); idx \u003e 0 {\n\t\t\tcontentType = contentType[:idx]\n\t\t}\n\t\tpatchType := types.PatchType(contentType)\n\n\t\t// Ensure the patchType is one we support\n\t\tif !sets.NewString(patchTypes...).Has(contentType) {\n\t\t\tscope.err(negotiation.NewUnsupportedMediaTypeError(patchTypes), w, req)\n\t\t\treturn\n\t\t}\n\n\t\tnamespace, name, err := scope.Namer.Name(req)\n\t\tif err != nil {\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\n\t\t// enforce a timeout of at most requestTimeoutUpperBound (34s) or less if the user-provided\n\t\t// timeout inside the parent context is lower than requestTimeoutUpperBound.\n\t\tctx, cancel := context.WithTimeout(ctx, requestTimeoutUpperBound)\n\t\tdefer cancel()\n\n\t\tctx = request.WithNamespace(ctx, namespace)\n\n\t\toutputMediaType, _, err := negotiation.NegotiateOutputMediaType(req, scope.Serializer, scope)\n\t\tif err != nil {\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\n\t\tpatchBytes, err := limitedReadBodyWithRecordMetric(ctx, req, scope.MaxRequestBodyBytes, scope.Resource.GroupResource().String(), requestmetrics.Patch)\n\t\tif err != nil {\n\t\t\tspan.AddEvent(\"limitedReadBody failed\", attribute.Int(\"len\", len(patchBytes)), attribute.String(\"err\", err.Error()))\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\t\tspan.AddEvent(\"limitedReadBody succeeded\", attribute.Int(\"len\", len(patchBytes)))\n\n\t\toptions := \u0026metav1.PatchOptions{}\n\t\tif err := metainternalversionscheme.ParameterCodec.DecodeParameters(req.URL.Query(), scope.MetaGroupVersion, options); err != nil {\n\t\t\terr = errors.NewBadRequest(err.Error())\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\t\tif errs := validation.ValidatePatchOptions(options, patchType); len(errs) \u003e 0 {\n\t\t\terr := errors.NewInvalid(schema.GroupKind{Group: metav1.GroupName, Kind: \"PatchOptions\"}, \"\", errs)\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\t\toptions.TypeMeta.SetGroupVersionKind(metav1.SchemeGroupVersion.WithKind(\"PatchOptions\"))\n\n\t\tadmit = admission.WithAudit(admit)\n\n\t\taudit.LogRequestPatch(req.Context(), patchBytes)\n\t\tspan.AddEvent(\"Recorded the audit event\")\n\n\t\tbaseContentType := runtime.ContentTypeJSON\n\t\tif patchType == types.ApplyPatchType {\n\t\t\tbaseContentType = runtime.ContentTypeYAML\n\t\t}\n\t\ts, ok := runtime.SerializerInfoForMediaType(scope.Serializer.SupportedMediaTypes(), baseContentType)\n\t\tif !ok {\n\t\t\tscope.err(fmt.Errorf(\"no serializer defined for %v\", baseContentType), w, req)\n\t\t\treturn\n\t\t}\n\t\tgv := scope.Kind.GroupVersion()\n\n\t\tvalidationDirective := fieldValidation(options.FieldValidation)\n\t\tdecodeSerializer := s.Serializer\n\t\tif validationDirective == metav1.FieldValidationWarn || validationDirective == metav1.FieldValidationStrict {\n\t\t\tdecodeSerializer = s.StrictSerializer\n\t\t}\n\n\t\tcodec := runtime.NewCodec(\n\t\t\tscope.Serializer.EncoderForVersion(s.Serializer, gv),\n\t\t\tscope.Serializer.DecoderToVersion(decodeSerializer, scope.HubGroupVersion),\n\t\t)\n\n\t\tuserInfo, _ := request.UserFrom(ctx)\n\t\tstaticCreateAttributes := admission.NewAttributesRecord(\n\t\t\tnil,\n\t\t\tnil,\n\t\t\tscope.Kind,\n\t\t\tnamespace,\n\t\t\tname,\n\t\t\tscope.Resource,\n\t\t\tscope.Subresource,\n\t\t\tadmission.Create,\n\t\t\tpatchToCreateOptions(options),\n\t\t\tdryrun.IsDryRun(options.DryRun),\n\t\t\tuserInfo)\n\t\tstaticUpdateAttributes := admission.NewAttributesRecord(\n\t\t\tnil,\n\t\t\tnil,\n\t\t\tscope.Kind,\n\t\t\tnamespace,\n\t\t\tname,\n\t\t\tscope.Resource,\n\t\t\tscope.Subresource,\n\t\t\tadmission.Update,\n\t\t\tpatchToUpdateOptions(options),\n\t\t\tdryrun.IsDryRun(options.DryRun),\n\t\t\tuserInfo,\n\t\t)\n\n\t\tif scope.FieldManager != nil {\n\t\t\tadmit = fieldmanager.NewManagedFieldsValidatingAdmissionController(admit)\n\t\t}\n\t\tmutatingAdmission, _ := admit.(admission.MutationInterface)\n\t\tcreateAuthorizerAttributes := authorizer.AttributesRecord{\n\t\t\tUser: userInfo,\n\t\t\tResourceRequest: true,\n\t\t\tPath: req.URL.Path,\n\t\t\tVerb: \"create\",\n\t\t\tAPIGroup: scope.Resource.Group,\n\t\t\tAPIVersion: scope.Resource.Version,\n\t\t\tResource: scope.Resource.Resource,\n\t\t\tSubresource: scope.Subresource,\n\t\t\tNamespace: namespace,\n\t\t\tName: name,\n\t\t}\n\n\t\tp := patcher{\n\t\t\tnamer: scope.Namer,\n\t\t\tcreater: scope.Creater,\n\t\t\tdefaulter: scope.Defaulter,\n\t\t\ttyper: scope.Typer,\n\t\t\tunsafeConvertor: scope.UnsafeConvertor,\n\t\t\tkind: scope.Kind,\n\t\t\tresource: scope.Resource,\n\t\t\tsubresource: scope.Subresource,\n\t\t\tdryRun: dryrun.IsDryRun(options.DryRun),\n\t\t\tvalidationDirective: validationDirective,\n\n\t\t\tobjectInterfaces: scope,\n\n\t\t\thubGroupVersion: scope.HubGroupVersion,\n\n\t\t\tcreateValidation: withAuthorization(rest.AdmissionToValidateObjectFunc(admit, staticCreateAttributes, scope), scope.Authorizer, createAuthorizerAttributes),\n\t\t\tupdateValidation: rest.AdmissionToValidateObjectUpdateFunc(admit, staticUpdateAttributes, scope),\n\t\t\tadmissionCheck: mutatingAdmission,\n\n\t\t\tcodec: codec,\n\n\t\t\toptions: options,\n\n\t\t\trestPatcher: r,\n\t\t\tname: name,\n\t\t\tpatchType: patchType,\n\t\t\tpatchBytes: patchBytes,\n\t\t\tuserAgent: req.UserAgent(),\n\t\t}\n\n\t\tresult, wasCreated, err := p.patchResource(ctx, scope)\n\t\tif err != nil {\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\t\tspan.AddEvent(\"Object stored in database\")\n\n\t\tstatus := http.StatusOK\n\t\tif wasCreated {\n\t\t\tstatus = http.StatusCreated\n\t\t}\n\n\t\tspan.AddEvent(\"About to write a response\")\n\t\tdefer span.AddEvent(\"Writing http response done\")\n\t\ttransformResponseObject(ctx, scope, req, w, status, outputMediaType, result)\n\t}\n}","line":{"from":63,"to":244}} {"id":100017502,"name":"applyPatchToCurrentObject","signature":"func (p *jsonPatcher) applyPatchToCurrentObject(requestContext context.Context, currentObject runtime.Object) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/patch.go","code":"func (p *jsonPatcher) applyPatchToCurrentObject(requestContext context.Context, currentObject runtime.Object) (runtime.Object, error) {\n\t// Encode will convert \u0026 return a versioned object in JSON.\n\tcurrentObjJS, err := runtime.Encode(p.codec, currentObject)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Apply the patch.\n\tpatchedObjJS, appliedStrictErrs, err := p.applyJSPatch(currentObjJS)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Construct the resulting typed, unversioned object.\n\tobjToUpdate := p.restPatcher.New()\n\tif err := runtime.DecodeInto(p.codec, patchedObjJS, objToUpdate); err != nil {\n\t\tstrictError, isStrictError := runtime.AsStrictDecodingError(err)\n\t\tswitch {\n\t\tcase !isStrictError:\n\t\t\t// disregard any appliedStrictErrs, because it's an incomplete\n\t\t\t// list of strict errors given that we don't know what fields were\n\t\t\t// unknown because DecodeInto failed. Non-strict errors trump in this case.\n\t\t\treturn nil, errors.NewInvalid(schema.GroupKind{}, \"\", field.ErrorList{\n\t\t\t\tfield.Invalid(field.NewPath(\"patch\"), string(patchedObjJS), err.Error()),\n\t\t\t})\n\t\tcase p.validationDirective == metav1.FieldValidationWarn:\n\t\t\taddStrictDecodingWarnings(requestContext, append(appliedStrictErrs, strictError.Errors()...))\n\t\tdefault:\n\t\t\tstrictDecodingError := runtime.NewStrictDecodingError(append(appliedStrictErrs, strictError.Errors()...))\n\t\t\treturn nil, errors.NewInvalid(schema.GroupKind{}, \"\", field.ErrorList{\n\t\t\t\tfield.Invalid(field.NewPath(\"patch\"), string(patchedObjJS), strictDecodingError.Error()),\n\t\t\t})\n\t\t}\n\t} else if len(appliedStrictErrs) \u003e 0 {\n\t\tswitch {\n\t\tcase p.validationDirective == metav1.FieldValidationWarn:\n\t\t\taddStrictDecodingWarnings(requestContext, appliedStrictErrs)\n\t\tdefault:\n\t\t\treturn nil, errors.NewInvalid(schema.GroupKind{}, \"\", field.ErrorList{\n\t\t\t\tfield.Invalid(field.NewPath(\"patch\"), string(patchedObjJS), runtime.NewStrictDecodingError(appliedStrictErrs).Error()),\n\t\t\t})\n\t\t}\n\t}\n\n\tif p.fieldManager != nil {\n\t\tobjToUpdate = p.fieldManager.UpdateNoErrors(currentObject, objToUpdate, managerOrUserAgent(p.options.FieldManager, p.userAgent))\n\t}\n\treturn objToUpdate, nil\n}","line":{"from":304,"to":352}} {"id":100017503,"name":"createNewObject","signature":"func (p *jsonPatcher) createNewObject(_ context.Context) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/patch.go","code":"func (p *jsonPatcher) createNewObject(_ context.Context) (runtime.Object, error) {\n\treturn nil, errors.NewNotFound(p.resource.GroupResource(), p.name)\n}","line":{"from":354,"to":356}} {"id":100017504,"name":"applyJSPatch","signature":"func (p *jsonPatcher) applyJSPatch(versionedJS []byte) (patchedJS []byte, strictErrors []error, retErr error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/patch.go","code":"// applyJSPatch applies the patch. Input and output objects must both have\n// the external version, since that is what the patch must have been constructed against.\nfunc (p *jsonPatcher) applyJSPatch(versionedJS []byte) (patchedJS []byte, strictErrors []error, retErr error) {\n\tswitch p.patchType {\n\tcase types.JSONPatchType:\n\t\tif p.validationDirective == metav1.FieldValidationStrict || p.validationDirective == metav1.FieldValidationWarn {\n\t\t\tvar v []jsonPatchOp\n\t\t\tvar err error\n\t\t\tif strictErrors, err = kjson.UnmarshalStrict(p.patchBytes, \u0026v); err != nil {\n\t\t\t\treturn nil, nil, errors.NewBadRequest(fmt.Sprintf(\"error decoding patch: %v\", err))\n\t\t\t}\n\t\t\tfor i, e := range strictErrors {\n\t\t\t\tstrictErrors[i] = fmt.Errorf(\"json patch %v\", e)\n\t\t\t}\n\t\t}\n\n\t\tpatchObj, err := jsonpatch.DecodePatch(p.patchBytes)\n\t\tif err != nil {\n\t\t\treturn nil, nil, errors.NewBadRequest(err.Error())\n\t\t}\n\t\tif len(patchObj) \u003e maxJSONPatchOperations {\n\t\t\treturn nil, nil, errors.NewRequestEntityTooLargeError(\n\t\t\t\tfmt.Sprintf(\"The allowed maximum operations in a JSON patch is %d, got %d\",\n\t\t\t\t\tmaxJSONPatchOperations, len(patchObj)))\n\t\t}\n\t\tpatchedJS, err := patchObj.Apply(versionedJS)\n\t\tif err != nil {\n\t\t\treturn nil, nil, errors.NewGenericServerResponse(http.StatusUnprocessableEntity, \"\", schema.GroupResource{}, \"\", err.Error(), 0, false)\n\t\t}\n\t\treturn patchedJS, strictErrors, nil\n\tcase types.MergePatchType:\n\t\tif p.validationDirective == metav1.FieldValidationStrict || p.validationDirective == metav1.FieldValidationWarn {\n\t\t\tv := map[string]interface{}{}\n\t\t\tvar err error\n\t\t\tstrictErrors, err = kjson.UnmarshalStrict(p.patchBytes, \u0026v)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, errors.NewBadRequest(fmt.Sprintf(\"error decoding patch: %v\", err))\n\t\t\t}\n\t\t}\n\n\t\tpatchedJS, retErr = jsonpatch.MergePatch(versionedJS, p.patchBytes)\n\t\tif retErr == jsonpatch.ErrBadJSONPatch {\n\t\t\treturn nil, nil, errors.NewBadRequest(retErr.Error())\n\t\t}\n\t\treturn patchedJS, strictErrors, retErr\n\tdefault:\n\t\t// only here as a safety net - go-restful filters content-type\n\t\treturn nil, nil, fmt.Errorf(\"unknown Content-Type header for patch: %v\", p.patchType)\n\t}\n}","line":{"from":365,"to":414}} {"id":100017505,"name":"applyPatchToCurrentObject","signature":"func (p *smpPatcher) applyPatchToCurrentObject(requestContext context.Context, currentObject runtime.Object) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/patch.go","code":"func (p *smpPatcher) applyPatchToCurrentObject(requestContext context.Context, currentObject runtime.Object) (runtime.Object, error) {\n\t// Since the patch is applied on versioned objects, we need to convert the\n\t// current object to versioned representation first.\n\tcurrentVersionedObject, err := p.unsafeConvertor.ConvertToVersion(currentObject, p.kind.GroupVersion())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tversionedObjToUpdate, err := p.creater.New(p.kind)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := strategicPatchObject(requestContext, p.defaulter, currentVersionedObject, p.patchBytes, versionedObjToUpdate, p.schemaReferenceObj, p.validationDirective); err != nil {\n\t\treturn nil, err\n\t}\n\t// Convert the object back to the hub version\n\tnewObj, err := p.unsafeConvertor.ConvertToVersion(versionedObjToUpdate, p.hubGroupVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif p.fieldManager != nil {\n\t\tnewObj = p.fieldManager.UpdateNoErrors(currentObject, newObj, managerOrUserAgent(p.options.FieldManager, p.userAgent))\n\t}\n\treturn newObj, nil\n}","line":{"from":424,"to":448}} {"id":100017506,"name":"createNewObject","signature":"func (p *smpPatcher) createNewObject(_ context.Context) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/patch.go","code":"func (p *smpPatcher) createNewObject(_ context.Context) (runtime.Object, error) {\n\treturn nil, errors.NewNotFound(p.resource.GroupResource(), p.name)\n}","line":{"from":450,"to":452}} {"id":100017507,"name":"applyPatchToCurrentObject","signature":"func (p *applyPatcher) applyPatchToCurrentObject(requestContext context.Context, obj runtime.Object) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/patch.go","code":"func (p *applyPatcher) applyPatchToCurrentObject(requestContext context.Context, obj runtime.Object) (runtime.Object, error) {\n\tforce := false\n\tif p.options.Force != nil {\n\t\tforce = *p.options.Force\n\t}\n\tif p.fieldManager == nil {\n\t\tpanic(\"FieldManager must be installed to run apply\")\n\t}\n\n\tpatchObj := \u0026unstructured.Unstructured{Object: map[string]interface{}{}}\n\tif err := yaml.Unmarshal(p.patch, \u0026patchObj.Object); err != nil {\n\t\treturn nil, errors.NewBadRequest(fmt.Sprintf(\"error decoding YAML: %v\", err))\n\t}\n\n\tobj, err := p.fieldManager.Apply(obj, patchObj, p.options.FieldManager, force)\n\tif err != nil {\n\t\treturn obj, err\n\t}\n\n\t// TODO: spawn something to track deciding whether a fieldValidation=Strict\n\t// fatal error should return before an error from the apply operation\n\tif p.validationDirective == metav1.FieldValidationStrict || p.validationDirective == metav1.FieldValidationWarn {\n\t\tif err := yaml.UnmarshalStrict(p.patch, \u0026map[string]interface{}{}); err != nil {\n\t\t\tif p.validationDirective == metav1.FieldValidationStrict {\n\t\t\t\treturn nil, errors.NewBadRequest(fmt.Sprintf(\"error strict decoding YAML: %v\", err))\n\t\t\t}\n\t\t\taddStrictDecodingWarnings(requestContext, []error{err})\n\t\t}\n\t}\n\treturn obj, nil\n}","line":{"from":464,"to":494}} {"id":100017508,"name":"createNewObject","signature":"func (p *applyPatcher) createNewObject(requestContext context.Context) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/patch.go","code":"func (p *applyPatcher) createNewObject(requestContext context.Context) (runtime.Object, error) {\n\tobj, err := p.creater.New(p.kind)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create new object: %v\", err)\n\t}\n\treturn p.applyPatchToCurrentObject(requestContext, obj)\n}","line":{"from":496,"to":502}} {"id":100017509,"name":"strategicPatchObject","signature":"func strategicPatchObject(","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/patch.go","code":"// strategicPatchObject applies a strategic merge patch of `patchBytes` to\n// `originalObject` and stores the result in `objToUpdate`.\n// It additionally returns the map[string]interface{} representation of the\n// `originalObject` and `patchBytes`.\n// NOTE: Both `originalObject` and `objToUpdate` are supposed to be versioned.\nfunc strategicPatchObject(\n\trequestContext context.Context,\n\tdefaulter runtime.ObjectDefaulter,\n\toriginalObject runtime.Object,\n\tpatchBytes []byte,\n\tobjToUpdate runtime.Object,\n\tschemaReferenceObj runtime.Object,\n\tvalidationDirective string,\n) error {\n\toriginalObjMap, err := runtime.DefaultUnstructuredConverter.ToUnstructured(originalObject)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpatchMap := make(map[string]interface{})\n\tvar strictErrs []error\n\tif validationDirective == metav1.FieldValidationWarn || validationDirective == metav1.FieldValidationStrict {\n\t\tstrictErrs, err = kjson.UnmarshalStrict(patchBytes, \u0026patchMap)\n\t\tif err != nil {\n\t\t\treturn errors.NewBadRequest(err.Error())\n\t\t}\n\t} else {\n\t\tif err = kjson.UnmarshalCaseSensitivePreserveInts(patchBytes, \u0026patchMap); err != nil {\n\t\t\treturn errors.NewBadRequest(err.Error())\n\t\t}\n\t}\n\n\tif err := applyPatchToObject(requestContext, defaulter, originalObjMap, patchMap, objToUpdate, schemaReferenceObj, strictErrs, validationDirective); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":504,"to":540}} {"id":100017510,"name":"applyPatch","signature":"func (p *patcher) applyPatch(ctx context.Context, _, currentObject runtime.Object) (objToUpdate runtime.Object, patchErr error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/patch.go","code":"// applyPatch is called every time GuaranteedUpdate asks for the updated object,\n// and is given the currently persisted object as input.\n// TODO: rename this function because the name implies it is related to applyPatcher\nfunc (p *patcher) applyPatch(ctx context.Context, _, currentObject runtime.Object) (objToUpdate runtime.Object, patchErr error) {\n\t// Make sure we actually have a persisted currentObject\n\ttracing.SpanFromContext(ctx).AddEvent(\"About to apply patch\")\n\tcurrentObjectHasUID, err := hasUID(currentObject)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if !currentObjectHasUID {\n\t\tobjToUpdate, patchErr = p.mechanism.createNewObject(ctx)\n\t} else {\n\t\tobjToUpdate, patchErr = p.mechanism.applyPatchToCurrentObject(ctx, currentObject)\n\t}\n\n\tif patchErr != nil {\n\t\treturn nil, patchErr\n\t}\n\n\tobjToUpdateHasUID, err := hasUID(objToUpdate)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif objToUpdateHasUID \u0026\u0026 !currentObjectHasUID {\n\t\taccessor, err := meta.Accessor(objToUpdate)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, errors.NewConflict(p.resource.GroupResource(), p.name, fmt.Errorf(\"uid mismatch: the provided object specified uid %s, and no existing object was found\", accessor.GetUID()))\n\t}\n\n\t// if this object supports namespace info\n\tif objectMeta, err := meta.Accessor(objToUpdate); err == nil {\n\t\t// ensure namespace on the object is correct, or error if a conflicting namespace was set in the object\n\t\tif err := rest.EnsureObjectNamespaceMatchesRequestNamespace(rest.ExpectedNamespaceForResource(p.namespace, p.resource), objectMeta); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif err := checkName(objToUpdate, p.name, p.namespace, p.namer); err != nil {\n\t\treturn nil, err\n\t}\n\treturn objToUpdate, nil\n}","line":{"from":542,"to":585}} {"id":100017511,"name":"admissionAttributes","signature":"func (p *patcher) admissionAttributes(ctx context.Context, updatedObject runtime.Object, currentObject runtime.Object, operation admission.Operation, operationOptions runtime.Object) admission.Attributes","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/patch.go","code":"func (p *patcher) admissionAttributes(ctx context.Context, updatedObject runtime.Object, currentObject runtime.Object, operation admission.Operation, operationOptions runtime.Object) admission.Attributes {\n\tuserInfo, _ := request.UserFrom(ctx)\n\treturn admission.NewAttributesRecord(updatedObject, currentObject, p.kind, p.namespace, p.name, p.resource, p.subresource, operation, operationOptions, p.dryRun, userInfo)\n}","line":{"from":587,"to":590}} {"id":100017512,"name":"applyAdmission","signature":"func (p *patcher) applyAdmission(ctx context.Context, patchedObject runtime.Object, currentObject runtime.Object) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/patch.go","code":"// applyAdmission is called every time GuaranteedUpdate asks for the updated object,\n// and is given the currently persisted object and the patched object as input.\n// TODO: rename this function because the name implies it is related to applyPatcher\nfunc (p *patcher) applyAdmission(ctx context.Context, patchedObject runtime.Object, currentObject runtime.Object) (runtime.Object, error) {\n\ttracing.SpanFromContext(ctx).AddEvent(\"About to check admission control\")\n\tvar operation admission.Operation\n\tvar options runtime.Object\n\tif hasUID, err := hasUID(currentObject); err != nil {\n\t\treturn nil, err\n\t} else if !hasUID {\n\t\toperation = admission.Create\n\t\tcurrentObject = nil\n\t\toptions = patchToCreateOptions(p.options)\n\t} else {\n\t\toperation = admission.Update\n\t\toptions = patchToUpdateOptions(p.options)\n\t}\n\tif p.admissionCheck != nil \u0026\u0026 p.admissionCheck.Handles(operation) {\n\t\tattributes := p.admissionAttributes(ctx, patchedObject, currentObject, operation, options)\n\t\treturn patchedObject, p.admissionCheck.Admit(ctx, attributes, p.objectInterfaces)\n\t}\n\treturn patchedObject, nil\n}","line":{"from":592,"to":614}} {"id":100017513,"name":"patchResource","signature":"func (p *patcher) patchResource(ctx context.Context, scope *RequestScope) (runtime.Object, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/patch.go","code":"// patchResource divides PatchResource for easier unit testing\nfunc (p *patcher) patchResource(ctx context.Context, scope *RequestScope) (runtime.Object, bool, error) {\n\tp.namespace = request.NamespaceValue(ctx)\n\tswitch p.patchType {\n\tcase types.JSONPatchType, types.MergePatchType:\n\t\tp.mechanism = \u0026jsonPatcher{\n\t\t\tpatcher: p,\n\t\t\tfieldManager: scope.FieldManager,\n\t\t}\n\tcase types.StrategicMergePatchType:\n\t\tschemaReferenceObj, err := p.unsafeConvertor.ConvertToVersion(p.restPatcher.New(), p.kind.GroupVersion())\n\t\tif err != nil {\n\t\t\treturn nil, false, err\n\t\t}\n\t\tp.mechanism = \u0026smpPatcher{\n\t\t\tpatcher: p,\n\t\t\tschemaReferenceObj: schemaReferenceObj,\n\t\t\tfieldManager: scope.FieldManager,\n\t\t}\n\t// this case is unreachable if ServerSideApply is not enabled because we will have already rejected the content type\n\tcase types.ApplyPatchType:\n\t\tp.mechanism = \u0026applyPatcher{\n\t\t\tfieldManager: scope.FieldManager,\n\t\t\tpatch: p.patchBytes,\n\t\t\toptions: p.options,\n\t\t\tcreater: p.creater,\n\t\t\tkind: p.kind,\n\t\t\tuserAgent: p.userAgent,\n\t\t\tvalidationDirective: p.validationDirective,\n\t\t}\n\t\tp.forceAllowCreate = true\n\tdefault:\n\t\treturn nil, false, fmt.Errorf(\"%v: unimplemented patch type\", p.patchType)\n\t}\n\tdedupOwnerReferencesTransformer := func(_ context.Context, obj, _ runtime.Object) (runtime.Object, error) {\n\t\t// Dedup owner references after mutating admission happens\n\t\tdedupOwnerReferencesAndAddWarning(obj, ctx, true)\n\t\treturn obj, nil\n\t}\n\n\ttransformers := []rest.TransformFunc{p.applyPatch, p.applyAdmission, dedupOwnerReferencesTransformer}\n\tif scope.FieldManager != nil {\n\t\ttransformers = append(transformers, fieldmanager.IgnoreManagedFieldsTimestampsTransformer)\n\t}\n\n\twasCreated := false\n\tp.updatedObjectInfo = rest.DefaultUpdatedObjectInfo(nil, transformers...)\n\trequestFunc := func() (runtime.Object, error) {\n\t\t// Pass in UpdateOptions to override UpdateStrategy.AllowUpdateOnCreate\n\t\toptions := patchToUpdateOptions(p.options)\n\t\tupdateObject, created, updateErr := p.restPatcher.Update(ctx, p.name, p.updatedObjectInfo, p.createValidation, p.updateValidation, p.forceAllowCreate, options)\n\t\twasCreated = created\n\t\treturn updateObject, updateErr\n\t}\n\tresult, err := finisher.FinishRequest(ctx, func() (runtime.Object, error) {\n\n\t\tresult, err := requestFunc()\n\t\t// If the object wasn't committed to storage because it's serialized size was too large,\n\t\t// it is safe to remove managedFields (which can be large) and try again.\n\t\tif isTooLargeError(err) \u0026\u0026 p.patchType != types.ApplyPatchType {\n\t\t\tif _, accessorErr := meta.Accessor(p.restPatcher.New()); accessorErr == nil {\n\t\t\t\tp.updatedObjectInfo = rest.DefaultUpdatedObjectInfo(nil,\n\t\t\t\t\tp.applyPatch,\n\t\t\t\t\tp.applyAdmission,\n\t\t\t\t\tdedupOwnerReferencesTransformer,\n\t\t\t\t\tfunc(_ context.Context, obj, _ runtime.Object) (runtime.Object, error) {\n\t\t\t\t\t\taccessor, _ := meta.Accessor(obj)\n\t\t\t\t\t\taccessor.SetManagedFields(nil)\n\t\t\t\t\t\treturn obj, nil\n\t\t\t\t\t})\n\t\t\t\tresult, err = requestFunc()\n\t\t\t}\n\t\t}\n\t\treturn result, err\n\t})\n\treturn result, wasCreated, err\n}","line":{"from":616,"to":692}} {"id":100017514,"name":"applyPatchToObject","signature":"func applyPatchToObject(","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/patch.go","code":"// applyPatchToObject applies a strategic merge patch of \u003cpatchMap\u003e to\n// \u003coriginalMap\u003e and stores the result in \u003cobjToUpdate\u003e.\n// NOTE: \u003cobjToUpdate\u003e must be a versioned object.\nfunc applyPatchToObject(\n\trequestContext context.Context,\n\tdefaulter runtime.ObjectDefaulter,\n\toriginalMap map[string]interface{},\n\tpatchMap map[string]interface{},\n\tobjToUpdate runtime.Object,\n\tschemaReferenceObj runtime.Object,\n\tstrictErrs []error,\n\tvalidationDirective string,\n) error {\n\tpatchedObjMap, err := strategicpatch.StrategicMergeMapPatch(originalMap, patchMap, schemaReferenceObj)\n\tif err != nil {\n\t\treturn interpretStrategicMergePatchError(err)\n\t}\n\n\t// Rather than serialize the patched map to JSON, then decode it to an object, we go directly from a map to an object\n\tconverter := runtime.DefaultUnstructuredConverter\n\treturnUnknownFields := validationDirective == metav1.FieldValidationWarn || validationDirective == metav1.FieldValidationStrict\n\tif err := converter.FromUnstructuredWithValidation(patchedObjMap, objToUpdate, returnUnknownFields); err != nil {\n\t\tstrictError, isStrictError := runtime.AsStrictDecodingError(err)\n\t\tswitch {\n\t\tcase !isStrictError:\n\t\t\t// disregard any sttrictErrs, because it's an incomplete\n\t\t\t// list of strict errors given that we don't know what fields were\n\t\t\t// unknown because StrategicMergeMapPatch failed.\n\t\t\t// Non-strict errors trump in this case.\n\t\t\treturn errors.NewInvalid(schema.GroupKind{}, \"\", field.ErrorList{\n\t\t\t\tfield.Invalid(field.NewPath(\"patch\"), fmt.Sprintf(\"%+v\", patchMap), err.Error()),\n\t\t\t})\n\t\tcase validationDirective == metav1.FieldValidationWarn:\n\t\t\taddStrictDecodingWarnings(requestContext, append(strictErrs, strictError.Errors()...))\n\t\tdefault:\n\t\t\tstrictDecodingError := runtime.NewStrictDecodingError(append(strictErrs, strictError.Errors()...))\n\t\t\treturn errors.NewInvalid(schema.GroupKind{}, \"\", field.ErrorList{\n\t\t\t\tfield.Invalid(field.NewPath(\"patch\"), fmt.Sprintf(\"%+v\", patchMap), strictDecodingError.Error()),\n\t\t\t})\n\t\t}\n\t} else if len(strictErrs) \u003e 0 {\n\t\tswitch {\n\t\tcase validationDirective == metav1.FieldValidationWarn:\n\t\t\taddStrictDecodingWarnings(requestContext, strictErrs)\n\t\tdefault:\n\t\t\treturn errors.NewInvalid(schema.GroupKind{}, \"\", field.ErrorList{\n\t\t\t\tfield.Invalid(field.NewPath(\"patch\"), fmt.Sprintf(\"%+v\", patchMap), runtime.NewStrictDecodingError(strictErrs).Error()),\n\t\t\t})\n\t\t}\n\t}\n\n\t// Decoding from JSON to a versioned object would apply defaults, so we do the same here\n\tdefaulter.Default(objToUpdate)\n\n\treturn nil\n}","line":{"from":694,"to":749}} {"id":100017515,"name":"interpretStrategicMergePatchError","signature":"func interpretStrategicMergePatchError(err error) error","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/patch.go","code":"// interpretStrategicMergePatchError interprets the error type and returns an error with appropriate HTTP code.\nfunc interpretStrategicMergePatchError(err error) error {\n\tswitch err {\n\tcase mergepatch.ErrBadJSONDoc, mergepatch.ErrBadPatchFormatForPrimitiveList, mergepatch.ErrBadPatchFormatForRetainKeys, mergepatch.ErrBadPatchFormatForSetElementOrderList, mergepatch.ErrUnsupportedStrategicMergePatchFormat:\n\t\treturn errors.NewBadRequest(err.Error())\n\tcase mergepatch.ErrNoListOfLists, mergepatch.ErrPatchContentNotMatchRetainKeys:\n\t\treturn errors.NewGenericServerResponse(http.StatusUnprocessableEntity, \"\", schema.GroupResource{}, \"\", err.Error(), 0, false)\n\tdefault:\n\t\treturn err\n\t}\n}","line":{"from":751,"to":761}} {"id":100017516,"name":"patchToUpdateOptions","signature":"func patchToUpdateOptions(po *metav1.PatchOptions) *metav1.UpdateOptions","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/patch.go","code":"// patchToUpdateOptions creates an UpdateOptions with the same field values as the provided PatchOptions.\nfunc patchToUpdateOptions(po *metav1.PatchOptions) *metav1.UpdateOptions {\n\tif po == nil {\n\t\treturn nil\n\t}\n\tuo := \u0026metav1.UpdateOptions{\n\t\tDryRun: po.DryRun,\n\t\tFieldManager: po.FieldManager,\n\t\tFieldValidation: po.FieldValidation,\n\t}\n\tuo.TypeMeta.SetGroupVersionKind(metav1.SchemeGroupVersion.WithKind(\"UpdateOptions\"))\n\treturn uo\n}","line":{"from":763,"to":775}} {"id":100017517,"name":"patchToCreateOptions","signature":"func patchToCreateOptions(po *metav1.PatchOptions) *metav1.CreateOptions","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/patch.go","code":"// patchToCreateOptions creates an CreateOptions with the same field values as the provided PatchOptions.\nfunc patchToCreateOptions(po *metav1.PatchOptions) *metav1.CreateOptions {\n\tif po == nil {\n\t\treturn nil\n\t}\n\tco := \u0026metav1.CreateOptions{\n\t\tDryRun: po.DryRun,\n\t\tFieldManager: po.FieldManager,\n\t\tFieldValidation: po.FieldValidation,\n\t}\n\tco.TypeMeta.SetGroupVersionKind(metav1.SchemeGroupVersion.WithKind(\"CreateOptions\"))\n\treturn co\n}","line":{"from":777,"to":789}} {"id":100017518,"name":"transformObject","signature":"func transformObject(ctx context.Context, obj runtime.Object, opts interface{}, mediaType negotiation.MediaTypeOptions, scope *RequestScope, req *http.Request) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/response.go","code":"// transformObject takes the object as returned by storage and ensures it is in\n// the client's desired form, as well as ensuring any API level fields like self-link\n// are properly set.\nfunc transformObject(ctx context.Context, obj runtime.Object, opts interface{}, mediaType negotiation.MediaTypeOptions, scope *RequestScope, req *http.Request) (runtime.Object, error) {\n\tif co, ok := obj.(runtime.CacheableObject); ok {\n\t\tif mediaType.Convert != nil {\n\t\t\t// Non-nil mediaType.Convert means that some conversion of the object\n\t\t\t// has to happen. Currently conversion may potentially modify the\n\t\t\t// object or assume something about it (e.g. asTable operates on\n\t\t\t// reflection, which won't work for any wrapper).\n\t\t\t// To ensure it will work correctly, let's operate on base objects\n\t\t\t// and not cache it for now.\n\t\t\t//\n\t\t\t// TODO: Long-term, transformObject should be changed so that it\n\t\t\t// implements runtime.Encoder interface.\n\t\t\treturn doTransformObject(ctx, co.GetObject(), opts, mediaType, scope, req)\n\t\t}\n\t}\n\treturn doTransformObject(ctx, obj, opts, mediaType, scope, req)\n}","line":{"from":37,"to":56}} {"id":100017519,"name":"doTransformObject","signature":"func doTransformObject(ctx context.Context, obj runtime.Object, opts interface{}, mediaType negotiation.MediaTypeOptions, scope *RequestScope, req *http.Request) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/response.go","code":"func doTransformObject(ctx context.Context, obj runtime.Object, opts interface{}, mediaType negotiation.MediaTypeOptions, scope *RequestScope, req *http.Request) (runtime.Object, error) {\n\tif _, ok := obj.(*metav1.Status); ok {\n\t\treturn obj, nil\n\t}\n\n\t// ensure that for empty lists we don't return \u003cnil\u003e items.\n\t// This is safe to modify without deep-copying the object, as\n\t// List objects themselves are never cached.\n\tif meta.IsListType(obj) \u0026\u0026 meta.LenList(obj) == 0 {\n\t\tif err := meta.SetList(obj, []runtime.Object{}); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tswitch target := mediaType.Convert; {\n\tcase target == nil:\n\t\treturn obj, nil\n\n\tcase target.Kind == \"PartialObjectMetadata\":\n\t\treturn asPartialObjectMetadata(obj, target.GroupVersion())\n\n\tcase target.Kind == \"PartialObjectMetadataList\":\n\t\treturn asPartialObjectMetadataList(obj, target.GroupVersion())\n\n\tcase target.Kind == \"Table\":\n\t\toptions, ok := opts.(*metav1.TableOptions)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"unexpected TableOptions, got %T\", opts)\n\t\t}\n\t\treturn asTable(ctx, obj, options, scope, target.GroupVersion())\n\n\tdefault:\n\t\taccepted, _ := negotiation.MediaTypesForSerializer(metainternalversionscheme.Codecs)\n\t\terr := negotiation.NewNotAcceptableError(accepted)\n\t\treturn nil, err\n\t}\n}","line":{"from":58,"to":94}} {"id":100017520,"name":"optionsForTransform","signature":"func optionsForTransform(mediaType negotiation.MediaTypeOptions, req *http.Request) (interface{}, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/response.go","code":"// optionsForTransform will load and validate any additional query parameter options for\n// a conversion or return an error.\nfunc optionsForTransform(mediaType negotiation.MediaTypeOptions, req *http.Request) (interface{}, error) {\n\tswitch target := mediaType.Convert; {\n\tcase target == nil:\n\tcase target.Kind == \"Table\" \u0026\u0026 (target.GroupVersion() == metav1beta1.SchemeGroupVersion || target.GroupVersion() == metav1.SchemeGroupVersion):\n\t\topts := \u0026metav1.TableOptions{}\n\t\tif err := metainternalversionscheme.ParameterCodec.DecodeParameters(req.URL.Query(), metav1.SchemeGroupVersion, opts); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tswitch errs := validation.ValidateTableOptions(opts); len(errs) {\n\t\tcase 0:\n\t\t\treturn opts, nil\n\t\tcase 1:\n\t\t\treturn nil, errors.NewBadRequest(fmt.Sprintf(\"Unable to convert to Table as requested: %v\", errs[0].Error()))\n\t\tdefault:\n\t\t\treturn nil, errors.NewBadRequest(fmt.Sprintf(\"Unable to convert to Table as requested: %v\", errs))\n\t\t}\n\t}\n\treturn nil, nil\n}","line":{"from":96,"to":116}} {"id":100017521,"name":"targetEncodingForTransform","signature":"func targetEncodingForTransform(scope *RequestScope, mediaType negotiation.MediaTypeOptions, req *http.Request) (schema.GroupVersionKind, runtime.NegotiatedSerializer, bool)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/response.go","code":"// targetEncodingForTransform returns the appropriate serializer for the input media type\nfunc targetEncodingForTransform(scope *RequestScope, mediaType negotiation.MediaTypeOptions, req *http.Request) (schema.GroupVersionKind, runtime.NegotiatedSerializer, bool) {\n\tswitch target := mediaType.Convert; {\n\tcase target == nil:\n\tcase (target.Kind == \"PartialObjectMetadata\" || target.Kind == \"PartialObjectMetadataList\" || target.Kind == \"Table\") \u0026\u0026\n\t\t(target.GroupVersion() == metav1beta1.SchemeGroupVersion || target.GroupVersion() == metav1.SchemeGroupVersion):\n\t\treturn *target, metainternalversionscheme.Codecs, true\n\t}\n\treturn scope.Kind, scope.Serializer, false\n}","line":{"from":118,"to":127}} {"id":100017522,"name":"transformResponseObject","signature":"func transformResponseObject(ctx context.Context, scope *RequestScope, req *http.Request, w http.ResponseWriter, statusCode int, mediaType negotiation.MediaTypeOptions, result runtime.Object)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/response.go","code":"// transformResponseObject takes an object loaded from storage and performs any necessary transformations.\n// Will write the complete response object.\nfunc transformResponseObject(ctx context.Context, scope *RequestScope, req *http.Request, w http.ResponseWriter, statusCode int, mediaType negotiation.MediaTypeOptions, result runtime.Object) {\n\toptions, err := optionsForTransform(mediaType, req)\n\tif err != nil {\n\t\tscope.err(err, w, req)\n\t\treturn\n\t}\n\n\tvar obj runtime.Object\n\tdo := func() {\n\t\tobj, err = transformObject(ctx, result, options, mediaType, scope, req)\n\t}\n\tendpointsrequest.TrackTransformResponseObjectLatency(ctx, do)\n\n\tif err != nil {\n\t\tscope.err(err, w, req)\n\t\treturn\n\t}\n\tkind, serializer, _ := targetEncodingForTransform(scope, mediaType, req)\n\tresponsewriters.WriteObjectNegotiated(serializer, scope, kind.GroupVersion(), w, req, statusCode, obj, false)\n}","line":{"from":129,"to":150}} {"id":100017523,"name":"newNotAcceptableError","signature":"func newNotAcceptableError(message string) error","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/response.go","code":"func newNotAcceptableError(message string) error {\n\treturn errNotAcceptable{message}\n}","line":{"from":157,"to":159}} {"id":100017524,"name":"Error","signature":"func (e errNotAcceptable) Error() string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/response.go","code":"func (e errNotAcceptable) Error() string {\n\treturn e.message\n}","line":{"from":161,"to":163}} {"id":100017525,"name":"Status","signature":"func (e errNotAcceptable) Status() metav1.Status","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/response.go","code":"func (e errNotAcceptable) Status() metav1.Status {\n\treturn metav1.Status{\n\t\tStatus: metav1.StatusFailure,\n\t\tCode: http.StatusNotAcceptable,\n\t\tReason: metav1.StatusReason(\"NotAcceptable\"),\n\t\tMessage: e.Error(),\n\t}\n}","line":{"from":165,"to":172}} {"id":100017526,"name":"asTable","signature":"func asTable(ctx context.Context, result runtime.Object, opts *metav1.TableOptions, scope *RequestScope, groupVersion schema.GroupVersion) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/response.go","code":"func asTable(ctx context.Context, result runtime.Object, opts *metav1.TableOptions, scope *RequestScope, groupVersion schema.GroupVersion) (runtime.Object, error) {\n\tswitch groupVersion {\n\tcase metav1beta1.SchemeGroupVersion, metav1.SchemeGroupVersion:\n\tdefault:\n\t\treturn nil, newNotAcceptableError(fmt.Sprintf(\"no Table exists in group version %s\", groupVersion))\n\t}\n\n\tobj, err := scope.TableConvertor.ConvertToTable(ctx, result, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttable := (*metav1.Table)(obj)\n\n\tfor i := range table.Rows {\n\t\titem := \u0026table.Rows[i]\n\t\tswitch opts.IncludeObject {\n\t\tcase metav1.IncludeObject:\n\t\t\titem.Object.Object, err = scope.Convertor.ConvertToVersion(item.Object.Object, scope.Kind.GroupVersion())\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t// TODO: rely on defaulting for the value here?\n\t\tcase metav1.IncludeMetadata, \"\":\n\t\t\tm, err := meta.Accessor(item.Object.Object)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\t// TODO: turn this into an internal type and do conversion in order to get object kind automatically set?\n\t\t\tpartial := meta.AsPartialObjectMetadata(m)\n\t\t\tpartial.GetObjectKind().SetGroupVersionKind(groupVersion.WithKind(\"PartialObjectMetadata\"))\n\t\t\titem.Object.Object = partial\n\t\tcase metav1.IncludeNone:\n\t\t\titem.Object.Object = nil\n\t\tdefault:\n\t\t\terr = errors.NewBadRequest(fmt.Sprintf(\"unrecognized includeObject value: %q\", opts.IncludeObject))\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn table, nil\n}","line":{"from":174,"to":215}} {"id":100017527,"name":"asPartialObjectMetadata","signature":"func asPartialObjectMetadata(result runtime.Object, groupVersion schema.GroupVersion) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/response.go","code":"func asPartialObjectMetadata(result runtime.Object, groupVersion schema.GroupVersion) (runtime.Object, error) {\n\tif meta.IsListType(result) {\n\t\terr := newNotAcceptableError(fmt.Sprintf(\"you requested PartialObjectMetadata, but the requested object is a list (%T)\", result))\n\t\treturn nil, err\n\t}\n\tswitch groupVersion {\n\tcase metav1beta1.SchemeGroupVersion, metav1.SchemeGroupVersion:\n\tdefault:\n\t\treturn nil, newNotAcceptableError(fmt.Sprintf(\"no PartialObjectMetadataList exists in group version %s\", groupVersion))\n\t}\n\tm, err := meta.Accessor(result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpartial := meta.AsPartialObjectMetadata(m)\n\tpartial.GetObjectKind().SetGroupVersionKind(groupVersion.WithKind(\"PartialObjectMetadata\"))\n\treturn partial, nil\n}","line":{"from":217,"to":234}} {"id":100017528,"name":"asPartialObjectMetadataList","signature":"func asPartialObjectMetadataList(result runtime.Object, groupVersion schema.GroupVersion) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/response.go","code":"func asPartialObjectMetadataList(result runtime.Object, groupVersion schema.GroupVersion) (runtime.Object, error) {\n\tli, ok := result.(metav1.ListInterface)\n\tif !ok {\n\t\treturn nil, newNotAcceptableError(fmt.Sprintf(\"you requested PartialObjectMetadataList, but the requested object is not a list (%T)\", result))\n\t}\n\n\tgvk := groupVersion.WithKind(\"PartialObjectMetadata\")\n\tswitch {\n\tcase groupVersion == metav1beta1.SchemeGroupVersion:\n\t\tlist := \u0026metav1beta1.PartialObjectMetadataList{}\n\t\terr := meta.EachListItem(result, func(obj runtime.Object) error {\n\t\t\tm, err := meta.Accessor(obj)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tpartial := meta.AsPartialObjectMetadata(m)\n\t\t\tpartial.GetObjectKind().SetGroupVersionKind(gvk)\n\t\t\tlist.Items = append(list.Items, *partial)\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlist.ResourceVersion = li.GetResourceVersion()\n\t\tlist.Continue = li.GetContinue()\n\t\tlist.RemainingItemCount = li.GetRemainingItemCount()\n\t\treturn list, nil\n\n\tcase groupVersion == metav1.SchemeGroupVersion:\n\t\tlist := \u0026metav1.PartialObjectMetadataList{}\n\t\terr := meta.EachListItem(result, func(obj runtime.Object) error {\n\t\t\tm, err := meta.Accessor(obj)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tpartial := meta.AsPartialObjectMetadata(m)\n\t\t\tpartial.GetObjectKind().SetGroupVersionKind(gvk)\n\t\t\tlist.Items = append(list.Items, *partial)\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlist.ResourceVersion = li.GetResourceVersion()\n\t\tlist.Continue = li.GetContinue()\n\t\tlist.RemainingItemCount = li.GetRemainingItemCount()\n\t\treturn list, nil\n\n\tdefault:\n\t\treturn nil, newNotAcceptableError(fmt.Sprintf(\"no PartialObjectMetadataList exists in group version %s\", groupVersion))\n\t}\n}","line":{"from":236,"to":287}} {"id":100017529,"name":"Forbidden","signature":"func Forbidden(ctx context.Context, attributes authorizer.Attributes, w http.ResponseWriter, req *http.Request, reason string, s runtime.NegotiatedSerializer)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters/errors.go","code":"// Forbidden renders a simple forbidden error\nfunc Forbidden(ctx context.Context, attributes authorizer.Attributes, w http.ResponseWriter, req *http.Request, reason string, s runtime.NegotiatedSerializer) {\n\tmsg := sanitizer.Replace(forbiddenMessage(attributes))\n\tw.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\n\tvar errMsg string\n\tif len(reason) == 0 {\n\t\terrMsg = fmt.Sprintf(\"%s\", msg)\n\t} else {\n\t\terrMsg = fmt.Sprintf(\"%s: %s\", msg, reason)\n\t}\n\tgv := schema.GroupVersion{Group: attributes.GetAPIGroup(), Version: attributes.GetAPIVersion()}\n\tgr := schema.GroupResource{Group: attributes.GetAPIGroup(), Resource: attributes.GetResource()}\n\tErrorNegotiated(apierrors.NewForbidden(gr, attributes.GetName(), fmt.Errorf(errMsg)), s, gv, w, req)\n}","line":{"from":35,"to":49}} {"id":100017530,"name":"forbiddenMessage","signature":"func forbiddenMessage(attributes authorizer.Attributes) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters/errors.go","code":"func forbiddenMessage(attributes authorizer.Attributes) string {\n\tusername := \"\"\n\tif user := attributes.GetUser(); user != nil {\n\t\tusername = user.GetName()\n\t}\n\n\tif !attributes.IsResourceRequest() {\n\t\treturn fmt.Sprintf(\"User %q cannot %s path %q\", username, attributes.GetVerb(), attributes.GetPath())\n\t}\n\n\tresource := attributes.GetResource()\n\tif subresource := attributes.GetSubresource(); len(subresource) \u003e 0 {\n\t\tresource = resource + \"/\" + subresource\n\t}\n\n\tif ns := attributes.GetNamespace(); len(ns) \u003e 0 {\n\t\treturn fmt.Sprintf(\"User %q cannot %s resource %q in API group %q in the namespace %q\", username, attributes.GetVerb(), resource, attributes.GetAPIGroup(), ns)\n\t}\n\n\treturn fmt.Sprintf(\"User %q cannot %s resource %q in API group %q at the cluster scope\", username, attributes.GetVerb(), resource, attributes.GetAPIGroup())\n}","line":{"from":51,"to":71}} {"id":100017531,"name":"InternalError","signature":"func InternalError(w http.ResponseWriter, req *http.Request, err error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters/errors.go","code":"// InternalError renders a simple internal error\nfunc InternalError(w http.ResponseWriter, req *http.Request, err error) {\n\thttp.Error(w, sanitizer.Replace(fmt.Sprintf(\"Internal Server Error: %q: %v\", req.RequestURI, err)),\n\t\thttp.StatusInternalServerError)\n\tutilruntime.HandleError(err)\n}","line":{"from":73,"to":78}} {"id":100017532,"name":"ErrorToAPIStatus","signature":"func ErrorToAPIStatus(err error) *metav1.Status","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters/status.go","code":"// ErrorToAPIStatus converts an error to an metav1.Status object.\nfunc ErrorToAPIStatus(err error) *metav1.Status {\n\tswitch t := err.(type) {\n\tcase statusError:\n\t\tstatus := t.Status()\n\t\tif len(status.Status) == 0 {\n\t\t\tstatus.Status = metav1.StatusFailure\n\t\t}\n\t\tswitch status.Status {\n\t\tcase metav1.StatusSuccess:\n\t\t\tif status.Code == 0 {\n\t\t\t\tstatus.Code = http.StatusOK\n\t\t\t}\n\t\tcase metav1.StatusFailure:\n\t\t\tif status.Code == 0 {\n\t\t\t\tstatus.Code = http.StatusInternalServerError\n\t\t\t}\n\t\tdefault:\n\t\t\truntime.HandleError(fmt.Errorf(\"apiserver received an error with wrong status field : %#+v\", err))\n\t\t\tif status.Code == 0 {\n\t\t\t\tstatus.Code = http.StatusInternalServerError\n\t\t\t}\n\t\t}\n\t\tstatus.Kind = \"Status\"\n\t\tstatus.APIVersion = \"v1\"\n\t\t//TODO: check for invalid responses\n\t\treturn \u0026status\n\tdefault:\n\t\tstatus := http.StatusInternalServerError\n\t\tswitch {\n\t\t//TODO: replace me with NewConflictErr\n\t\tcase storage.IsConflict(err):\n\t\t\tstatus = http.StatusConflict\n\t\t}\n\t\t// Log errors that were not converted to an error status\n\t\t// by REST storage - these typically indicate programmer\n\t\t// error by not using pkg/api/errors, or unexpected failure\n\t\t// cases.\n\t\truntime.HandleError(fmt.Errorf(\"apiserver received an error that is not an metav1.Status: %#+v: %v\", err, err))\n\t\treturn \u0026metav1.Status{\n\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\tKind: \"Status\",\n\t\t\t\tAPIVersion: \"v1\",\n\t\t\t},\n\t\t\tStatus: metav1.StatusFailure,\n\t\t\tCode: int32(status),\n\t\t\tReason: metav1.StatusReasonUnknown,\n\t\t\tMessage: err.Error(),\n\t\t}\n\t}\n}","line":{"from":33,"to":83}} {"id":100017533,"name":"StreamObject","signature":"func StreamObject(statusCode int, gv schema.GroupVersion, s runtime.NegotiatedSerializer, stream rest.ResourceStreamer, w http.ResponseWriter, req *http.Request)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters/writers.go","code":"// StreamObject performs input stream negotiation from a ResourceStreamer and writes that to the response.\n// If the client requests a websocket upgrade, negotiate for a websocket reader protocol (because many\n// browser clients cannot easily handle binary streaming protocols).\nfunc StreamObject(statusCode int, gv schema.GroupVersion, s runtime.NegotiatedSerializer, stream rest.ResourceStreamer, w http.ResponseWriter, req *http.Request) {\n\tout, flush, contentType, err := stream.InputStream(req.Context(), gv.String(), req.Header.Get(\"Accept\"))\n\tif err != nil {\n\t\tErrorNegotiated(err, s, gv, w, req)\n\t\treturn\n\t}\n\tif out == nil {\n\t\t// No output provided - return StatusNoContent\n\t\tw.WriteHeader(http.StatusNoContent)\n\t\treturn\n\t}\n\tdefer out.Close()\n\n\tif wsstream.IsWebSocketRequest(req) {\n\t\tr := wsstream.NewReader(out, true, wsstream.NewDefaultReaderProtocols())\n\t\tif err := r.Copy(w, req); err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"error encountered while streaming results via websocket: %v\", err))\n\t\t}\n\t\treturn\n\t}\n\n\tif len(contentType) == 0 {\n\t\tcontentType = \"application/octet-stream\"\n\t}\n\tw.Header().Set(\"Content-Type\", contentType)\n\tw.WriteHeader(statusCode)\n\t// Flush headers, if possible\n\tif flusher, ok := w.(http.Flusher); ok {\n\t\tflusher.Flush()\n\t}\n\twriter := w.(io.Writer)\n\tif flush {\n\t\twriter = flushwriter.Wrap(w)\n\t}\n\tio.Copy(writer, out)\n}","line":{"from":49,"to":87}} {"id":100017534,"name":"SerializeObject","signature":"func SerializeObject(mediaType string, encoder runtime.Encoder, hw http.ResponseWriter, req *http.Request, statusCode int, object runtime.Object)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters/writers.go","code":"// SerializeObject renders an object in the content type negotiated by the client using the provided encoder.\n// The context is optional and can be nil. This method will perform optional content compression if requested by\n// a client and the feature gate for APIResponseCompression is enabled.\nfunc SerializeObject(mediaType string, encoder runtime.Encoder, hw http.ResponseWriter, req *http.Request, statusCode int, object runtime.Object) {\n\tctx := req.Context()\n\tctx, span := tracing.Start(ctx, \"SerializeObject\",\n\t\tattribute.String(\"audit-id\", audit.GetAuditIDTruncated(ctx)),\n\t\tattribute.String(\"method\", req.Method),\n\t\tattribute.String(\"url\", req.URL.Path),\n\t\tattribute.String(\"protocol\", req.Proto),\n\t\tattribute.String(\"mediaType\", mediaType),\n\t\tattribute.String(\"encoder\", string(encoder.Identifier())))\n\tdefer span.End(5 * time.Second)\n\n\tw := \u0026deferredResponseWriter{\n\t\tmediaType: mediaType,\n\t\tstatusCode: statusCode,\n\t\tcontentEncoding: negotiateContentEncoding(req),\n\t\thw: hw,\n\t\tctx: ctx,\n\t}\n\n\terr := encoder.Encode(object, w)\n\tif err == nil {\n\t\terr = w.Close()\n\t\tif err != nil {\n\t\t\t// we cannot write an error to the writer anymore as the Encode call was successful.\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"apiserver was unable to close cleanly the response writer: %v\", err))\n\t\t}\n\t\treturn\n\t}\n\n\t// make a best effort to write the object if a failure is detected\n\tutilruntime.HandleError(fmt.Errorf(\"apiserver was unable to write a JSON response: %v\", err))\n\tstatus := ErrorToAPIStatus(err)\n\tcandidateStatusCode := int(status.Code)\n\t// if the current status code is successful, allow the error's status code to overwrite it\n\tif statusCode \u003e= http.StatusOK \u0026\u0026 statusCode \u003c http.StatusBadRequest {\n\t\tw.statusCode = candidateStatusCode\n\t}\n\toutput, err := runtime.Encode(encoder, status)\n\tif err != nil {\n\t\tw.mediaType = \"text/plain\"\n\t\toutput = []byte(fmt.Sprintf(\"%s: %s\", status.Reason, status.Message))\n\t}\n\tif _, err := w.Write(output); err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"apiserver was unable to write a fallback JSON response: %v\", err))\n\t}\n\tw.Close()\n}","line":{"from":89,"to":138}} {"id":100017535,"name":"negotiateContentEncoding","signature":"func negotiateContentEncoding(req *http.Request) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters/writers.go","code":"// negotiateContentEncoding returns a supported client-requested content encoding for the\n// provided request. It will return the empty string if no supported content encoding was\n// found or if response compression is disabled.\nfunc negotiateContentEncoding(req *http.Request) string {\n\tencoding := req.Header.Get(\"Accept-Encoding\")\n\tif len(encoding) == 0 {\n\t\treturn \"\"\n\t}\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.APIResponseCompression) {\n\t\treturn \"\"\n\t}\n\tfor len(encoding) \u003e 0 {\n\t\tvar token string\n\t\tif next := strings.Index(encoding, \",\"); next != -1 {\n\t\t\ttoken = encoding[:next]\n\t\t\tencoding = encoding[next+1:]\n\t\t} else {\n\t\t\ttoken = encoding\n\t\t\tencoding = \"\"\n\t\t}\n\t\tswitch strings.TrimSpace(token) {\n\t\tcase \"gzip\":\n\t\t\treturn \"gzip\"\n\t\t}\n\t}\n\treturn \"\"\n}","line":{"from":161,"to":187}} {"id":100017536,"name":"Write","signature":"func (w *deferredResponseWriter) Write(p []byte) (n int, err error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters/writers.go","code":"func (w *deferredResponseWriter) Write(p []byte) (n int, err error) {\n\tctx := w.ctx\n\tspan := tracing.SpanFromContext(ctx)\n\t// This Step usually wraps in-memory object serialization.\n\tspan.AddEvent(\"About to start writing response\", attribute.Int(\"size\", len(p)))\n\n\tfirstWrite := !w.hasWritten\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tspan.AddEvent(\"Write call failed\",\n\t\t\t\tattribute.String(\"writer\", fmt.Sprintf(\"%T\", w.w)),\n\t\t\t\tattribute.Int(\"size\", len(p)),\n\t\t\t\tattribute.Bool(\"firstWrite\", firstWrite),\n\t\t\t\tattribute.String(\"err\", err.Error()))\n\t\t} else {\n\t\t\tspan.AddEvent(\"Write call succeeded\",\n\t\t\t\tattribute.String(\"writer\", fmt.Sprintf(\"%T\", w.w)),\n\t\t\t\tattribute.Int(\"size\", len(p)),\n\t\t\t\tattribute.Bool(\"firstWrite\", firstWrite))\n\t\t}\n\t}()\n\tif w.hasWritten {\n\t\treturn w.w.Write(p)\n\t}\n\tw.hasWritten = true\n\n\thw := w.hw\n\theader := hw.Header()\n\tswitch {\n\tcase w.contentEncoding == \"gzip\" \u0026\u0026 len(p) \u003e defaultGzipThresholdBytes:\n\t\theader.Set(\"Content-Encoding\", \"gzip\")\n\t\theader.Add(\"Vary\", \"Accept-Encoding\")\n\n\t\tgw := gzipPool.Get().(*gzip.Writer)\n\t\tgw.Reset(hw)\n\n\t\tw.w = gw\n\tdefault:\n\t\tw.w = hw\n\t}\n\n\theader.Set(\"Content-Type\", w.mediaType)\n\thw.WriteHeader(w.statusCode)\n\treturn w.w.Write(p)\n}","line":{"from":201,"to":245}} {"id":100017537,"name":"Close","signature":"func (w *deferredResponseWriter) Close() error","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters/writers.go","code":"func (w *deferredResponseWriter) Close() error {\n\tif !w.hasWritten {\n\t\treturn nil\n\t}\n\tvar err error\n\tswitch t := w.w.(type) {\n\tcase *gzip.Writer:\n\t\terr = t.Close()\n\t\tt.Reset(nil)\n\t\tgzipPool.Put(t)\n\t}\n\treturn err\n}","line":{"from":247,"to":259}} {"id":100017538,"name":"WriteObjectNegotiated","signature":"func WriteObjectNegotiated(s runtime.NegotiatedSerializer, restrictions negotiation.EndpointRestrictions, gv schema.GroupVersion, w http.ResponseWriter, req *http.Request, statusCode int, object runtime.Object, listGVKInContentType bool)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters/writers.go","code":"// WriteObjectNegotiated renders an object in the content type negotiated by the client.\nfunc WriteObjectNegotiated(s runtime.NegotiatedSerializer, restrictions negotiation.EndpointRestrictions, gv schema.GroupVersion, w http.ResponseWriter, req *http.Request, statusCode int, object runtime.Object, listGVKInContentType bool) {\n\tstream, ok := object.(rest.ResourceStreamer)\n\tif ok {\n\t\trequestInfo, _ := request.RequestInfoFrom(req.Context())\n\t\tmetrics.RecordLongRunning(req, requestInfo, metrics.APIServerComponent, func() {\n\t\t\tStreamObject(statusCode, gv, s, stream, w, req)\n\t\t})\n\t\treturn\n\t}\n\n\tmediaType, serializer, err := negotiation.NegotiateOutputMediaType(req, s, restrictions)\n\tif err != nil {\n\t\t// if original statusCode was not successful we need to return the original error\n\t\t// we cannot hide it behind negotiation problems\n\t\tif statusCode \u003c http.StatusOK || statusCode \u003e= http.StatusBadRequest {\n\t\t\tWriteRawJSON(int(statusCode), object, w)\n\t\t\treturn\n\t\t}\n\t\tstatus := ErrorToAPIStatus(err)\n\t\tWriteRawJSON(int(status.Code), status, w)\n\t\treturn\n\t}\n\n\taudit.LogResponseObject(req.Context(), object, gv, s)\n\n\tencoder := s.EncoderForVersion(serializer.Serializer, gv)\n\trequest.TrackSerializeResponseObjectLatency(req.Context(), func() {\n\t\tif listGVKInContentType {\n\t\t\tSerializeObject(generateMediaTypeWithGVK(serializer.MediaType, mediaType.Convert), encoder, w, req, statusCode, object)\n\t\t} else {\n\t\t\tSerializeObject(serializer.MediaType, encoder, w, req, statusCode, object)\n\t\t}\n\t})\n}","line":{"from":261,"to":295}} {"id":100017539,"name":"generateMediaTypeWithGVK","signature":"func generateMediaTypeWithGVK(mediaType string, gvk *schema.GroupVersionKind) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters/writers.go","code":"func generateMediaTypeWithGVK(mediaType string, gvk *schema.GroupVersionKind) string {\n\tif gvk == nil {\n\t\treturn mediaType\n\t}\n\tif gvk.Group != \"\" {\n\t\tmediaType += \";g=\" + gvk.Group\n\t}\n\tif gvk.Version != \"\" {\n\t\tmediaType += \";v=\" + gvk.Version\n\t}\n\tif gvk.Kind != \"\" {\n\t\tmediaType += \";as=\" + gvk.Kind\n\t}\n\treturn mediaType\n}","line":{"from":297,"to":311}} {"id":100017540,"name":"ErrorNegotiated","signature":"func ErrorNegotiated(err error, s runtime.NegotiatedSerializer, gv schema.GroupVersion, w http.ResponseWriter, req *http.Request) int","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters/writers.go","code":"// ErrorNegotiated renders an error to the response. Returns the HTTP status code of the error.\n// The context is optional and may be nil.\nfunc ErrorNegotiated(err error, s runtime.NegotiatedSerializer, gv schema.GroupVersion, w http.ResponseWriter, req *http.Request) int {\n\tstatus := ErrorToAPIStatus(err)\n\tcode := int(status.Code)\n\t// when writing an error, check to see if the status indicates a retry after period\n\tif status.Details != nil \u0026\u0026 status.Details.RetryAfterSeconds \u003e 0 {\n\t\tdelay := strconv.Itoa(int(status.Details.RetryAfterSeconds))\n\t\tw.Header().Set(\"Retry-After\", delay)\n\t}\n\n\tif code == http.StatusNoContent {\n\t\tw.WriteHeader(code)\n\t\treturn code\n\t}\n\n\tWriteObjectNegotiated(s, negotiation.DefaultEndpointRestrictions, gv, w, req, code, status, false)\n\treturn code\n}","line":{"from":313,"to":331}} {"id":100017541,"name":"WriteRawJSON","signature":"func WriteRawJSON(statusCode int, object interface{}, w http.ResponseWriter)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters/writers.go","code":"// WriteRawJSON writes a non-API object in JSON.\nfunc WriteRawJSON(statusCode int, object interface{}, w http.ResponseWriter) {\n\toutput, err := json.MarshalIndent(object, \"\", \" \")\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(statusCode)\n\tw.Write(output)\n}","line":{"from":333,"to":343}} {"id":100017542,"name":"err","signature":"func (scope *RequestScope) err(err error, w http.ResponseWriter, req *http.Request)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"func (scope *RequestScope) err(err error, w http.ResponseWriter, req *http.Request) {\n\tresponsewriters.ErrorNegotiated(err, scope.Serializer, scope.Kind.GroupVersion(), w, req)\n}","line":{"from":112,"to":114}} {"id":100017543,"name":"AcceptsGroupVersion","signature":"func (scope *RequestScope) AcceptsGroupVersion(gv schema.GroupVersion) bool","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"// AcceptsGroupVersion returns true if the specified GroupVersion is allowed\n// in create and update requests.\nfunc (scope *RequestScope) AcceptsGroupVersion(gv schema.GroupVersion) bool {\n\t// If there's a custom acceptor, delegate to it. This is extremely rare.\n\tif scope.AcceptsGroupVersionDelegate != nil {\n\t\treturn scope.AcceptsGroupVersionDelegate.AcceptsGroupVersion(gv)\n\t}\n\t// Fall back to only allowing the singular Kind. This is the typical behavior.\n\treturn gv == scope.Kind.GroupVersion()\n}","line":{"from":116,"to":125}} {"id":100017544,"name":"AllowsMediaTypeTransform","signature":"func (scope *RequestScope) AllowsMediaTypeTransform(mimeType, mimeSubType string, gvk *schema.GroupVersionKind) bool","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"func (scope *RequestScope) AllowsMediaTypeTransform(mimeType, mimeSubType string, gvk *schema.GroupVersionKind) bool {\n\t// some handlers like CRDs can't serve all the mime types that PartialObjectMetadata or Table can - if\n\t// gvk is nil (no conversion) allow StandardSerializers to further restrict the set of mime types.\n\tif gvk == nil {\n\t\tif len(scope.StandardSerializers) == 0 {\n\t\t\treturn true\n\t\t}\n\t\tfor _, info := range scope.StandardSerializers {\n\t\t\tif info.MediaTypeType == mimeType \u0026\u0026 info.MediaTypeSubType == mimeSubType {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\t// TODO: this is temporary, replace with an abstraction calculated at endpoint installation time\n\tif gvk.GroupVersion() == metav1beta1.SchemeGroupVersion || gvk.GroupVersion() == metav1.SchemeGroupVersion {\n\t\tswitch gvk.Kind {\n\t\tcase \"Table\":\n\t\t\treturn scope.TableConvertor != nil \u0026\u0026\n\t\t\t\tmimeType == \"application\" \u0026\u0026\n\t\t\t\t(mimeSubType == \"json\" || mimeSubType == \"yaml\")\n\t\tcase \"PartialObjectMetadata\", \"PartialObjectMetadataList\":\n\t\t\t// TODO: should delineate between lists and non-list endpoints\n\t\t\treturn true\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn false\n}","line":{"from":127,"to":157}} {"id":100017545,"name":"AllowsServerVersion","signature":"func (scope *RequestScope) AllowsServerVersion(version string) bool","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"func (scope *RequestScope) AllowsServerVersion(version string) bool {\n\treturn version == scope.MetaGroupVersion.Version\n}","line":{"from":159,"to":161}} {"id":100017546,"name":"AllowsStreamSchema","signature":"func (scope *RequestScope) AllowsStreamSchema(s string) bool","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"func (scope *RequestScope) AllowsStreamSchema(s string) bool {\n\treturn s == \"watch\"\n}","line":{"from":163,"to":165}} {"id":100017547,"name":"GetObjectCreater","signature":"func (r *RequestScope) GetObjectCreater() runtime.ObjectCreater { return r.Creater }","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"func (r *RequestScope) GetObjectCreater() runtime.ObjectCreater { return r.Creater }","line":{"from":169,"to":169}} {"id":100017548,"name":"GetObjectTyper","signature":"func (r *RequestScope) GetObjectTyper() runtime.ObjectTyper { return r.Typer }","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"func (r *RequestScope) GetObjectTyper() runtime.ObjectTyper { return r.Typer }","line":{"from":170,"to":170}} {"id":100017549,"name":"GetObjectDefaulter","signature":"func (r *RequestScope) GetObjectDefaulter() runtime.ObjectDefaulter { return r.Defaulter }","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"func (r *RequestScope) GetObjectDefaulter() runtime.ObjectDefaulter { return r.Defaulter }","line":{"from":171,"to":171}} {"id":100017550,"name":"GetObjectConvertor","signature":"func (r *RequestScope) GetObjectConvertor() runtime.ObjectConvertor { return r.Convertor }","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"func (r *RequestScope) GetObjectConvertor() runtime.ObjectConvertor { return r.Convertor }","line":{"from":172,"to":172}} {"id":100017551,"name":"GetEquivalentResourceMapper","signature":"func (r *RequestScope) GetEquivalentResourceMapper() runtime.EquivalentResourceMapper","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"func (r *RequestScope) GetEquivalentResourceMapper() runtime.EquivalentResourceMapper {\n\treturn r.EquivalentResourceMapper\n}","line":{"from":173,"to":175}} {"id":100017552,"name":"ConnectResource","signature":"func ConnectResource(connecter rest.Connecter, scope *RequestScope, admit admission.Interface, restPath string, isSubresource bool) http.HandlerFunc","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"// ConnectResource returns a function that handles a connect request on a rest.Storage object.\nfunc ConnectResource(connecter rest.Connecter, scope *RequestScope, admit admission.Interface, restPath string, isSubresource bool) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, req *http.Request) {\n\t\tif isDryRun(req.URL) {\n\t\t\tscope.err(errors.NewBadRequest(\"dryRun is not supported\"), w, req)\n\t\t\treturn\n\t\t}\n\n\t\tnamespace, name, err := scope.Namer.Name(req)\n\t\tif err != nil {\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\t\tctx := req.Context()\n\t\tctx = request.WithNamespace(ctx, namespace)\n\t\tadmit = admission.WithAudit(admit)\n\n\t\topts, subpath, subpathKey := connecter.NewConnectOptions()\n\t\tif err := getRequestOptions(req, scope, opts, subpath, subpathKey, isSubresource); err != nil {\n\t\t\terr = errors.NewBadRequest(err.Error())\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\t\tif admit != nil \u0026\u0026 admit.Handles(admission.Connect) {\n\t\t\tuserInfo, _ := request.UserFrom(ctx)\n\t\t\t// TODO: remove the mutating admission here as soon as we have ported all plugin that handle CONNECT\n\t\t\tif mutatingAdmission, ok := admit.(admission.MutationInterface); ok {\n\t\t\t\terr = mutatingAdmission.Admit(ctx, admission.NewAttributesRecord(opts, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Connect, nil, false, userInfo), scope)\n\t\t\t\tif err != nil {\n\t\t\t\t\tscope.err(err, w, req)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tif validatingAdmission, ok := admit.(admission.ValidationInterface); ok {\n\t\t\t\terr = validatingAdmission.Validate(ctx, admission.NewAttributesRecord(opts, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Connect, nil, false, userInfo), scope)\n\t\t\t\tif err != nil {\n\t\t\t\t\tscope.err(err, w, req)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\trequestInfo, _ := request.RequestInfoFrom(ctx)\n\t\tmetrics.RecordLongRunning(req, requestInfo, metrics.APIServerComponent, func() {\n\t\t\thandler, err := connecter.Connect(ctx, name, opts, \u0026responder{scope: scope, req: req, w: w})\n\t\t\tif err != nil {\n\t\t\t\tscope.err(err, w, req)\n\t\t\t\treturn\n\t\t\t}\n\t\t\thandler.ServeHTTP(w, req)\n\t\t})\n\t}\n}","line":{"from":177,"to":228}} {"id":100017553,"name":"Object","signature":"func (r *responder) Object(statusCode int, obj runtime.Object)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"func (r *responder) Object(statusCode int, obj runtime.Object) {\n\tresponsewriters.WriteObjectNegotiated(r.scope.Serializer, r.scope, r.scope.Kind.GroupVersion(), r.w, r.req, statusCode, obj, false)\n}","line":{"from":237,"to":239}} {"id":100017554,"name":"Error","signature":"func (r *responder) Error(err error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"func (r *responder) Error(err error) {\n\tr.scope.err(err, r.w, r.req)\n}","line":{"from":241,"to":243}} {"id":100017555,"name":"transformDecodeError","signature":"func transformDecodeError(typer runtime.ObjectTyper, baseErr error, into runtime.Object, gvk *schema.GroupVersionKind, body []byte) error","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"// transformDecodeError adds additional information into a bad-request api error when a decode fails.\nfunc transformDecodeError(typer runtime.ObjectTyper, baseErr error, into runtime.Object, gvk *schema.GroupVersionKind, body []byte) error {\n\tobjGVKs, _, err := typer.ObjectKinds(into)\n\tif err != nil {\n\t\treturn errors.NewBadRequest(err.Error())\n\t}\n\tobjGVK := objGVKs[0]\n\tif gvk != nil \u0026\u0026 len(gvk.Kind) \u003e 0 {\n\t\treturn errors.NewBadRequest(fmt.Sprintf(\"%s in version %q cannot be handled as a %s: %v\", gvk.Kind, gvk.Version, objGVK.Kind, baseErr))\n\t}\n\tsummary := summarizeData(body, 30)\n\treturn errors.NewBadRequest(fmt.Sprintf(\"the object provided is unrecognized (must be of type %s): %v (%s)\", objGVK.Kind, baseErr, summary))\n}","line":{"from":245,"to":257}} {"id":100017556,"name":"hasUID","signature":"func hasUID(obj runtime.Object) (bool, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"func hasUID(obj runtime.Object) (bool, error) {\n\tif obj == nil {\n\t\treturn false, nil\n\t}\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn false, errors.NewInternalError(err)\n\t}\n\tif len(accessor.GetUID()) == 0 {\n\t\treturn false, nil\n\t}\n\treturn true, nil\n}","line":{"from":259,"to":271}} {"id":100017557,"name":"checkName","signature":"func checkName(obj runtime.Object, name, namespace string, namer ScopeNamer) error","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"// checkName checks the provided name against the request\nfunc checkName(obj runtime.Object, name, namespace string, namer ScopeNamer) error {\n\tobjNamespace, objName, err := namer.ObjectName(obj)\n\tif err != nil {\n\t\treturn errors.NewBadRequest(fmt.Sprintf(\n\t\t\t\"the name of the object (%s based on URL) was undeterminable: %v\", name, err))\n\t}\n\tif objName != name {\n\t\treturn errors.NewBadRequest(fmt.Sprintf(\n\t\t\t\"the name of the object (%s) does not match the name on the URL (%s)\", objName, name))\n\t}\n\tif len(namespace) \u003e 0 {\n\t\tif len(objNamespace) \u003e 0 \u0026\u0026 objNamespace != namespace {\n\t\t\treturn errors.NewBadRequest(fmt.Sprintf(\n\t\t\t\t\"the namespace of the object (%s) does not match the namespace on the request (%s)\", objNamespace, namespace))\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":273,"to":292}} {"id":100017558,"name":"dedupOwnerReferences","signature":"func dedupOwnerReferences(refs []metav1.OwnerReference) ([]metav1.OwnerReference, []string)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"// dedupOwnerReferences dedups owner references over the entire entry.\n// NOTE: We don't know enough about the existing cases of owner references\n// sharing the same UID but different fields. Nor do we know what might break.\n// In the future we may just dedup/reject owner references with the same UID.\nfunc dedupOwnerReferences(refs []metav1.OwnerReference) ([]metav1.OwnerReference, []string) {\n\tvar result []metav1.OwnerReference\n\tvar duplicates []string\n\tseen := make(map[types.UID]struct{})\n\tfor _, ref := range refs {\n\t\t_, ok := seen[ref.UID]\n\t\t// Short-circuit if we haven't seen the UID before. Otherwise\n\t\t// check the entire list we have so far.\n\t\tif !ok || !hasOwnerReference(result, ref) {\n\t\t\tseen[ref.UID] = struct{}{}\n\t\t\tresult = append(result, ref)\n\t\t} else {\n\t\t\tduplicates = append(duplicates, string(ref.UID))\n\t\t}\n\t}\n\treturn result, duplicates\n}","line":{"from":294,"to":314}} {"id":100017559,"name":"hasOwnerReference","signature":"func hasOwnerReference(refs []metav1.OwnerReference, ref metav1.OwnerReference) bool","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"// hasOwnerReference returns true if refs has an item equal to ref. The function\n// focuses on semantic equality instead of memory equality, to catch duplicates\n// with different pointer addresses. The function uses apiequality.Semantic\n// instead of implementing its own comparison, to tolerate API changes to\n// metav1.OwnerReference.\n// NOTE: This is expensive, but we accept it because we've made sure it only\n// happens to owner references containing duplicate UIDs, plus typically the\n// number of items in the list should be small.\nfunc hasOwnerReference(refs []metav1.OwnerReference, ref metav1.OwnerReference) bool {\n\tfor _, r := range refs {\n\t\tif apiequality.Semantic.DeepEqual(r, ref) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":316,"to":331}} {"id":100017560,"name":"dedupOwnerReferencesAndAddWarning","signature":"func dedupOwnerReferencesAndAddWarning(obj runtime.Object, requestContext context.Context, afterMutatingAdmission bool)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"// dedupOwnerReferencesAndAddWarning dedups owner references in the object metadata.\n// If duplicates are found, the function records a warning to the provided context.\nfunc dedupOwnerReferencesAndAddWarning(obj runtime.Object, requestContext context.Context, afterMutatingAdmission bool) {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\t// The object doesn't have metadata. Nothing we need to do here.\n\t\treturn\n\t}\n\trefs := accessor.GetOwnerReferences()\n\tdeduped, duplicates := dedupOwnerReferences(refs)\n\tif len(duplicates) \u003e 0 {\n\t\t// NOTE: For CREATE and UPDATE requests the API server dedups both before and after mutating admission.\n\t\t// For PATCH request the API server only dedups after mutating admission.\n\t\tformat := DuplicateOwnerReferencesWarningFormat\n\t\tif afterMutatingAdmission {\n\t\t\tformat = DuplicateOwnerReferencesAfterMutatingAdmissionWarningFormat\n\t\t}\n\t\twarning.AddWarning(requestContext, \"\", fmt.Sprintf(format,\n\t\t\tstrings.Join(duplicates, \", \")))\n\t\taccessor.SetOwnerReferences(deduped)\n\t}\n}","line":{"from":333,"to":354}} {"id":100017561,"name":"summarizeData","signature":"func summarizeData(data []byte, maxLength int) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"func summarizeData(data []byte, maxLength int) string {\n\tswitch {\n\tcase len(data) == 0:\n\t\treturn \"\u003cempty\u003e\"\n\tcase data[0] == '{':\n\t\tif len(data) \u003e maxLength {\n\t\t\treturn string(data[:maxLength]) + \" ...\"\n\t\t}\n\t\treturn string(data)\n\tdefault:\n\t\tif len(data) \u003e maxLength {\n\t\t\treturn hex.EncodeToString(data[:maxLength]) + \" ...\"\n\t\t}\n\t\treturn hex.EncodeToString(data)\n\t}\n}","line":{"from":356,"to":371}} {"id":100017562,"name":"limitedReadBody","signature":"func limitedReadBody(req *http.Request, limit int64) ([]byte, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"func limitedReadBody(req *http.Request, limit int64) ([]byte, error) {\n\tdefer req.Body.Close()\n\tif limit \u003c= 0 {\n\t\treturn ioutil.ReadAll(req.Body)\n\t}\n\tlr := \u0026io.LimitedReader{\n\t\tR: req.Body,\n\t\tN: limit + 1,\n\t}\n\tdata, err := ioutil.ReadAll(lr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif lr.N \u003c= 0 {\n\t\treturn nil, errors.NewRequestEntityTooLargeError(fmt.Sprintf(\"limit is %d\", limit))\n\t}\n\treturn data, nil\n}","line":{"from":373,"to":390}} {"id":100017563,"name":"limitedReadBodyWithRecordMetric","signature":"func limitedReadBodyWithRecordMetric(ctx context.Context, req *http.Request, limit int64, resourceGroup string, verb requestmetrics.RequestBodyVerb) ([]byte, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"func limitedReadBodyWithRecordMetric(ctx context.Context, req *http.Request, limit int64, resourceGroup string, verb requestmetrics.RequestBodyVerb) ([]byte, error) {\n\treadBody, err := limitedReadBody(req, limit)\n\tif err == nil {\n\t\t// only record if we've read successfully\n\t\trequestmetrics.RecordRequestBodySize(ctx, resourceGroup, verb, len(readBody))\n\t}\n\treturn readBody, err\n}","line":{"from":392,"to":399}} {"id":100017564,"name":"isDryRun","signature":"func isDryRun(url *url.URL) bool","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"func isDryRun(url *url.URL) bool {\n\treturn len(url.Query()[\"dryRun\"]) != 0\n}","line":{"from":401,"to":403}} {"id":100017565,"name":"fieldValidation","signature":"func fieldValidation(directive string) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"// fieldValidation checks that the field validation feature is enabled\n// and returns a valid directive of either\n// - Ignore\n// - Warn (default)\n// - Strict\nfunc fieldValidation(directive string) string {\n\tif directive == \"\" {\n\t\treturn metav1.FieldValidationWarn\n\t}\n\treturn directive\n}","line":{"from":405,"to":415}} {"id":100017566,"name":"parseYAMLWarnings","signature":"func parseYAMLWarnings(errString string) []string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"// parseYAMLWarnings takes the strict decoding errors from the yaml decoder's output\n// and parses each individual warnings, or leaves the warning as is if\n// it does not look like a yaml strict decoding error.\nfunc parseYAMLWarnings(errString string) []string {\n\tvar trimmedString string\n\tif trimmedShortString := strings.TrimPrefix(errString, shortPrefix); len(trimmedShortString) \u003c len(errString) {\n\t\ttrimmedString = trimmedShortString\n\t} else if trimmedLongString := strings.TrimPrefix(errString, longPrefix); len(trimmedLongString) \u003c len(errString) {\n\t\ttrimmedString = trimmedLongString\n\t} else {\n\t\t// not a yaml error, return as-is\n\t\treturn []string{errString}\n\t}\n\n\tsplitStrings := strings.Split(trimmedString, \"\\n\")\n\tfor i, s := range splitStrings {\n\t\tsplitStrings[i] = strings.TrimSpace(s)\n\t}\n\treturn splitStrings\n}","line":{"from":417,"to":436}} {"id":100017567,"name":"addStrictDecodingWarnings","signature":"func addStrictDecodingWarnings(requestContext context.Context, errs []error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"// addStrictDecodingWarnings confirms that the error is a strict decoding error\n// and if so adds a warning for each strict decoding violation.\nfunc addStrictDecodingWarnings(requestContext context.Context, errs []error) {\n\tfor _, e := range errs {\n\t\tyamlWarnings := parseYAMLWarnings(e.Error())\n\t\tfor _, w := range yamlWarnings {\n\t\t\twarning.AddWarning(requestContext, \"\", w)\n\t\t}\n\t}\n}","line":{"from":438,"to":447}} {"id":100017568,"name":"isTooLargeError","signature":"func isTooLargeError(err error) bool","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go","code":"func isTooLargeError(err error) bool {\n\tif err != nil {\n\t\tif etcdErr, ok := err.(etcdError); ok {\n\t\t\tif etcdErr.Code() == grpccodes.InvalidArgument \u0026\u0026 etcdErr.Error() == \"etcdserver: request is too large\" {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\tif grpcErr, ok := err.(grpcError); ok {\n\t\t\tif grpcErr.GRPCStatus().Code() == grpccodes.ResourceExhausted \u0026\u0026 strings.Contains(grpcErr.GRPCStatus().Message(), \"trying to send message larger than max\") {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":458,"to":472}} {"id":100017569,"name":"traceFields","signature":"func traceFields(req *http.Request) []attribute.KeyValue","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/trace_util.go","code":"func traceFields(req *http.Request) []attribute.KeyValue {\n\treturn []attribute.KeyValue{\n\t\tattribute.Stringer(\"accept\", \u0026lazyAccept{req: req}),\n\t\tattribute.Stringer(\"audit-id\", \u0026lazyAuditID{req: req}),\n\t\tattribute.Stringer(\"client\", \u0026lazyClientIP{req: req}),\n\t\tattribute.String(\"protocol\", req.Proto),\n\t\tattribute.Stringer(\"resource\", \u0026lazyResource{req: req}),\n\t\tattribute.Stringer(\"scope\", \u0026lazyScope{req: req}),\n\t\tattribute.String(\"url\", req.URL.Path),\n\t\tattribute.Stringer(\"user-agent\", \u0026lazyTruncatedUserAgent{req: req}),\n\t\tattribute.Stringer(\"verb\", \u0026lazyVerb{req: req}),\n\t}\n}","line":{"from":25,"to":37}} {"id":100017570,"name":"UpdateResource","signature":"func UpdateResource(r rest.Updater, scope *RequestScope, admit admission.Interface) http.HandlerFunc","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/update.go","code":"// UpdateResource returns a function that will handle a resource update\nfunc UpdateResource(r rest.Updater, scope *RequestScope, admit admission.Interface) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, req *http.Request) {\n\t\tctx := req.Context()\n\t\t// For performance tracking purposes.\n\t\tctx, span := tracing.Start(ctx, \"Update\", traceFields(req)...)\n\t\tdefer span.End(500 * time.Millisecond)\n\n\t\tnamespace, name, err := scope.Namer.Name(req)\n\t\tif err != nil {\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\n\t\t// enforce a timeout of at most requestTimeoutUpperBound (34s) or less if the user-provided\n\t\t// timeout inside the parent context is lower than requestTimeoutUpperBound.\n\t\tctx, cancel := context.WithTimeout(ctx, requestTimeoutUpperBound)\n\t\tdefer cancel()\n\n\t\tctx = request.WithNamespace(ctx, namespace)\n\n\t\toutputMediaType, _, err := negotiation.NegotiateOutputMediaType(req, scope.Serializer, scope)\n\t\tif err != nil {\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\n\t\tbody, err := limitedReadBodyWithRecordMetric(ctx, req, scope.MaxRequestBodyBytes, scope.Resource.GroupResource().String(), requestmetrics.Update)\n\t\tif err != nil {\n\t\t\tspan.AddEvent(\"limitedReadBody failed\", attribute.Int(\"len\", len(body)), attribute.String(\"err\", err.Error()))\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\t\tspan.AddEvent(\"limitedReadBody succeeded\", attribute.Int(\"len\", len(body)))\n\n\t\toptions := \u0026metav1.UpdateOptions{}\n\t\tif err := metainternalversionscheme.ParameterCodec.DecodeParameters(req.URL.Query(), scope.MetaGroupVersion, options); err != nil {\n\t\t\terr = errors.NewBadRequest(err.Error())\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\t\tif errs := validation.ValidateUpdateOptions(options); len(errs) \u003e 0 {\n\t\t\terr := errors.NewInvalid(schema.GroupKind{Group: metav1.GroupName, Kind: \"UpdateOptions\"}, \"\", errs)\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\t\toptions.TypeMeta.SetGroupVersionKind(metav1.SchemeGroupVersion.WithKind(\"UpdateOptions\"))\n\n\t\ts, err := negotiation.NegotiateInputSerializer(req, false, scope.Serializer)\n\t\tif err != nil {\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\t\tdefaultGVK := scope.Kind\n\t\toriginal := r.New()\n\n\t\tvalidationDirective := fieldValidation(options.FieldValidation)\n\t\tdecodeSerializer := s.Serializer\n\t\tif validationDirective == metav1.FieldValidationWarn || validationDirective == metav1.FieldValidationStrict {\n\t\t\tdecodeSerializer = s.StrictSerializer\n\t\t}\n\n\t\tdecoder := scope.Serializer.DecoderToVersion(decodeSerializer, scope.HubGroupVersion)\n\t\tspan.AddEvent(\"About to convert to expected version\")\n\t\tobj, gvk, err := decoder.Decode(body, \u0026defaultGVK, original)\n\t\tif err != nil {\n\t\t\tstrictError, isStrictError := runtime.AsStrictDecodingError(err)\n\t\t\tswitch {\n\t\t\tcase isStrictError \u0026\u0026 obj != nil \u0026\u0026 validationDirective == metav1.FieldValidationWarn:\n\t\t\t\taddStrictDecodingWarnings(req.Context(), strictError.Errors())\n\t\t\tcase isStrictError \u0026\u0026 validationDirective == metav1.FieldValidationIgnore:\n\t\t\t\tklog.Warningf(\"unexpected strict error when field validation is set to ignore\")\n\t\t\t\tfallthrough\n\t\t\tdefault:\n\t\t\t\terr = transformDecodeError(scope.Typer, err, original, gvk, body)\n\t\t\t\tscope.err(err, w, req)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tobjGV := gvk.GroupVersion()\n\t\tif !scope.AcceptsGroupVersion(objGV) {\n\t\t\terr = errors.NewBadRequest(fmt.Sprintf(\"the API version in the data (%s) does not match the expected API version (%s)\", objGV, defaultGVK.GroupVersion()))\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\t\tspan.AddEvent(\"Conversion done\")\n\n\t\taudit.LogRequestObject(req.Context(), obj, objGV, scope.Resource, scope.Subresource, scope.Serializer)\n\t\tadmit = admission.WithAudit(admit)\n\n\t\t// if this object supports namespace info\n\t\tif objectMeta, err := meta.Accessor(obj); err == nil {\n\t\t\t// ensure namespace on the object is correct, or error if a conflicting namespace was set in the object\n\t\t\tif err := rest.EnsureObjectNamespaceMatchesRequestNamespace(rest.ExpectedNamespaceForResource(namespace, scope.Resource), objectMeta); err != nil {\n\t\t\t\tscope.err(err, w, req)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tif err := checkName(obj, name, namespace, scope.Namer); err != nil {\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\n\t\tuserInfo, _ := request.UserFrom(ctx)\n\t\ttransformers := []rest.TransformFunc{}\n\n\t\t// allows skipping managedFields update if the resulting object is too big\n\t\tshouldUpdateManagedFields := true\n\t\tif scope.FieldManager != nil {\n\t\t\tadmit = fieldmanager.NewManagedFieldsValidatingAdmissionController(admit)\n\t\t\ttransformers = append(transformers, func(_ context.Context, newObj, liveObj runtime.Object) (runtime.Object, error) {\n\t\t\t\tif shouldUpdateManagedFields {\n\t\t\t\t\treturn scope.FieldManager.UpdateNoErrors(liveObj, newObj, managerOrUserAgent(options.FieldManager, req.UserAgent())), nil\n\t\t\t\t}\n\t\t\t\treturn newObj, nil\n\t\t\t})\n\t\t}\n\n\t\tif mutatingAdmission, ok := admit.(admission.MutationInterface); ok {\n\t\t\ttransformers = append(transformers, func(ctx context.Context, newObj, oldObj runtime.Object) (runtime.Object, error) {\n\t\t\t\tisNotZeroObject, err := hasUID(oldObj)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"unexpected error when extracting UID from oldObj: %v\", err.Error())\n\t\t\t\t} else if !isNotZeroObject {\n\t\t\t\t\tif mutatingAdmission.Handles(admission.Create) {\n\t\t\t\t\t\treturn newObj, mutatingAdmission.Admit(ctx, admission.NewAttributesRecord(newObj, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Create, updateToCreateOptions(options), dryrun.IsDryRun(options.DryRun), userInfo), scope)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif mutatingAdmission.Handles(admission.Update) {\n\t\t\t\t\t\treturn newObj, mutatingAdmission.Admit(ctx, admission.NewAttributesRecord(newObj, oldObj, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Update, options, dryrun.IsDryRun(options.DryRun), userInfo), scope)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn newObj, nil\n\t\t\t})\n\t\t\ttransformers = append(transformers, func(ctx context.Context, newObj, oldObj runtime.Object) (runtime.Object, error) {\n\t\t\t\t// Dedup owner references again after mutating admission happens\n\t\t\t\tdedupOwnerReferencesAndAddWarning(newObj, req.Context(), true)\n\t\t\t\treturn newObj, nil\n\t\t\t})\n\t\t}\n\n\t\t// Ignore changes that only affect managed fields\n\t\t// timestamps. FieldManager can't know about changes\n\t\t// like normalized fields, defaulted fields and other\n\t\t// mutations.\n\t\t// Only makes sense when SSA field manager is being used\n\t\tif scope.FieldManager != nil {\n\t\t\ttransformers = append(transformers, fieldmanager.IgnoreManagedFieldsTimestampsTransformer)\n\t\t}\n\n\t\tcreateAuthorizerAttributes := authorizer.AttributesRecord{\n\t\t\tUser: userInfo,\n\t\t\tResourceRequest: true,\n\t\t\tPath: req.URL.Path,\n\t\t\tVerb: \"create\",\n\t\t\tAPIGroup: scope.Resource.Group,\n\t\t\tAPIVersion: scope.Resource.Version,\n\t\t\tResource: scope.Resource.Resource,\n\t\t\tSubresource: scope.Subresource,\n\t\t\tNamespace: namespace,\n\t\t\tName: name,\n\t\t}\n\n\t\tspan.AddEvent(\"About to store object in database\")\n\t\twasCreated := false\n\t\trequestFunc := func() (runtime.Object, error) {\n\t\t\tobj, created, err := r.Update(\n\t\t\t\tctx,\n\t\t\t\tname,\n\t\t\t\trest.DefaultUpdatedObjectInfo(obj, transformers...),\n\t\t\t\twithAuthorization(rest.AdmissionToValidateObjectFunc(\n\t\t\t\t\tadmit,\n\t\t\t\t\tadmission.NewAttributesRecord(nil, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Create, updateToCreateOptions(options), dryrun.IsDryRun(options.DryRun), userInfo), scope),\n\t\t\t\t\tscope.Authorizer, createAuthorizerAttributes),\n\t\t\t\trest.AdmissionToValidateObjectUpdateFunc(\n\t\t\t\t\tadmit,\n\t\t\t\t\tadmission.NewAttributesRecord(nil, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Update, options, dryrun.IsDryRun(options.DryRun), userInfo), scope),\n\t\t\t\tfalse,\n\t\t\t\toptions,\n\t\t\t)\n\t\t\twasCreated = created\n\t\t\treturn obj, err\n\t\t}\n\t\t// Dedup owner references before updating managed fields\n\t\tdedupOwnerReferencesAndAddWarning(obj, req.Context(), false)\n\t\tresult, err := finisher.FinishRequest(ctx, func() (runtime.Object, error) {\n\t\t\tresult, err := requestFunc()\n\t\t\t// If the object wasn't committed to storage because it's serialized size was too large,\n\t\t\t// it is safe to remove managedFields (which can be large) and try again.\n\t\t\tif isTooLargeError(err) \u0026\u0026 scope.FieldManager != nil {\n\t\t\t\tif accessor, accessorErr := meta.Accessor(obj); accessorErr == nil {\n\t\t\t\t\taccessor.SetManagedFields(nil)\n\t\t\t\t\tshouldUpdateManagedFields = false\n\t\t\t\t\tresult, err = requestFunc()\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result, err\n\t\t})\n\t\tif err != nil {\n\t\t\tspan.AddEvent(\"Write to database call failed\", attribute.Int(\"len\", len(body)), attribute.String(\"err\", err.Error()))\n\t\t\tscope.err(err, w, req)\n\t\t\treturn\n\t\t}\n\t\tspan.AddEvent(\"Write to database call succeeded\", attribute.Int(\"len\", len(body)))\n\n\t\tstatus := http.StatusOK\n\t\tif wasCreated {\n\t\t\tstatus = http.StatusCreated\n\t\t}\n\n\t\tspan.AddEvent(\"About to write a response\")\n\t\tdefer span.AddEvent(\"Writing http response done\")\n\t\ttransformResponseObject(ctx, scope, req, w, status, outputMediaType, result)\n\t}\n}","line":{"from":49,"to":265}} {"id":100017571,"name":"withAuthorization","signature":"func withAuthorization(validate rest.ValidateObjectFunc, a authorizer.Authorizer, attributes authorizer.Attributes) rest.ValidateObjectFunc","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/update.go","code":"func withAuthorization(validate rest.ValidateObjectFunc, a authorizer.Authorizer, attributes authorizer.Attributes) rest.ValidateObjectFunc {\n\tvar once sync.Once\n\tvar authorizerDecision authorizer.Decision\n\tvar authorizerReason string\n\tvar authorizerErr error\n\treturn func(ctx context.Context, obj runtime.Object) error {\n\t\tif a == nil {\n\t\t\treturn errors.NewInternalError(fmt.Errorf(\"no authorizer provided, unable to authorize a create on update\"))\n\t\t}\n\t\tonce.Do(func() {\n\t\t\tauthorizerDecision, authorizerReason, authorizerErr = a.Authorize(ctx, attributes)\n\t\t})\n\t\t// an authorizer like RBAC could encounter evaluation errors and still allow the request, so authorizer decision is checked before error here.\n\t\tif authorizerDecision == authorizer.DecisionAllow {\n\t\t\t// Continue to validating admission\n\t\t\treturn validate(ctx, obj)\n\t\t}\n\t\tif authorizerErr != nil {\n\t\t\treturn errors.NewInternalError(authorizerErr)\n\t\t}\n\n\t\t// The user is not authorized to perform this action, so we need to build the error response\n\t\tgr := schema.GroupResource{\n\t\t\tGroup: attributes.GetAPIGroup(),\n\t\t\tResource: attributes.GetResource(),\n\t\t}\n\t\tname := attributes.GetName()\n\t\terr := fmt.Errorf(\"%v\", authorizerReason)\n\t\treturn errors.NewForbidden(gr, name, err)\n\t}\n}","line":{"from":267,"to":297}} {"id":100017572,"name":"updateToCreateOptions","signature":"func updateToCreateOptions(uo *metav1.UpdateOptions) *metav1.CreateOptions","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/update.go","code":"// updateToCreateOptions creates a CreateOptions with the same field values as the provided UpdateOptions.\nfunc updateToCreateOptions(uo *metav1.UpdateOptions) *metav1.CreateOptions {\n\tif uo == nil {\n\t\treturn nil\n\t}\n\tco := \u0026metav1.CreateOptions{\n\t\tDryRun: uo.DryRun,\n\t\tFieldManager: uo.FieldManager,\n\t\tFieldValidation: uo.FieldValidation,\n\t}\n\tco.TypeMeta.SetGroupVersionKind(metav1.SchemeGroupVersion.WithKind(\"CreateOptions\"))\n\treturn co\n}","line":{"from":299,"to":311}} {"id":100017573,"name":"TimeoutCh","signature":"func (w *realTimeoutFactory) TimeoutCh() (\u003c-chan time.Time, func() bool)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/watch.go","code":"// TimeoutCh returns a channel which will receive something when the watch times out,\n// and a cleanup function to call when this happens.\nfunc (w *realTimeoutFactory) TimeoutCh() (\u003c-chan time.Time, func() bool) {\n\tif w.timeout == 0 {\n\t\treturn neverExitWatch, func() bool { return false }\n\t}\n\tt := time.NewTimer(w.timeout)\n\treturn t.C, t.Stop\n}","line":{"from":54,"to":62}} {"id":100017574,"name":"serveWatch","signature":"func serveWatch(watcher watch.Interface, scope *RequestScope, mediaTypeOptions negotiation.MediaTypeOptions, req *http.Request, w http.ResponseWriter, timeout time.Duration)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/watch.go","code":"// serveWatch will serve a watch response.\n// TODO: the functionality in this method and in WatchServer.Serve is not cleanly decoupled.\nfunc serveWatch(watcher watch.Interface, scope *RequestScope, mediaTypeOptions negotiation.MediaTypeOptions, req *http.Request, w http.ResponseWriter, timeout time.Duration) {\n\tdefer watcher.Stop()\n\n\toptions, err := optionsForTransform(mediaTypeOptions, req)\n\tif err != nil {\n\t\tscope.err(err, w, req)\n\t\treturn\n\t}\n\n\t// negotiate for the stream serializer from the scope's serializer\n\tserializer, err := negotiation.NegotiateOutputMediaTypeStream(req, scope.Serializer, scope)\n\tif err != nil {\n\t\tscope.err(err, w, req)\n\t\treturn\n\t}\n\tframer := serializer.StreamSerializer.Framer\n\tstreamSerializer := serializer.StreamSerializer.Serializer\n\tencoder := scope.Serializer.EncoderForVersion(streamSerializer, scope.Kind.GroupVersion())\n\tuseTextFraming := serializer.EncodesAsText\n\tif framer == nil {\n\t\tscope.err(fmt.Errorf(\"no framer defined for %q available for embedded encoding\", serializer.MediaType), w, req)\n\t\treturn\n\t}\n\t// TODO: next step, get back mediaTypeOptions from negotiate and return the exact value here\n\tmediaType := serializer.MediaType\n\tif mediaType != runtime.ContentTypeJSON {\n\t\tmediaType += \";stream=watch\"\n\t}\n\n\t// locate the appropriate embedded encoder based on the transform\n\tvar embeddedEncoder runtime.Encoder\n\tcontentKind, contentSerializer, transform := targetEncodingForTransform(scope, mediaTypeOptions, req)\n\tif transform {\n\t\tinfo, ok := runtime.SerializerInfoForMediaType(contentSerializer.SupportedMediaTypes(), serializer.MediaType)\n\t\tif !ok {\n\t\t\tscope.err(fmt.Errorf(\"no encoder for %q exists in the requested target %#v\", serializer.MediaType, contentSerializer), w, req)\n\t\t\treturn\n\t\t}\n\t\tembeddedEncoder = contentSerializer.EncoderForVersion(info.Serializer, contentKind.GroupVersion())\n\t} else {\n\t\tembeddedEncoder = scope.Serializer.EncoderForVersion(serializer.Serializer, contentKind.GroupVersion())\n\t}\n\n\tvar serverShuttingDownCh \u003c-chan struct{}\n\tif signals := apirequest.ServerShutdownSignalFrom(req.Context()); signals != nil {\n\t\tserverShuttingDownCh = signals.ShuttingDown()\n\t}\n\n\tctx := req.Context()\n\n\tserver := \u0026WatchServer{\n\t\tWatching: watcher,\n\t\tScope: scope,\n\n\t\tUseTextFraming: useTextFraming,\n\t\tMediaType: mediaType,\n\t\tFramer: framer,\n\t\tEncoder: encoder,\n\t\tEmbeddedEncoder: embeddedEncoder,\n\n\t\tFixup: func(obj runtime.Object) runtime.Object {\n\t\t\tresult, err := transformObject(ctx, obj, options, mediaTypeOptions, scope, req)\n\t\t\tif err != nil {\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"failed to transform object %v: %v\", reflect.TypeOf(obj), err))\n\t\t\t\treturn obj\n\t\t\t}\n\t\t\t// When we are transformed to a table, use the table options as the state for whether we\n\t\t\t// should print headers - on watch, we only want to print table headers on the first object\n\t\t\t// and omit them on subsequent events.\n\t\t\tif tableOptions, ok := options.(*metav1.TableOptions); ok {\n\t\t\t\ttableOptions.NoHeaders = true\n\t\t\t}\n\t\t\treturn result\n\t\t},\n\n\t\tTimeoutFactory: \u0026realTimeoutFactory{timeout},\n\t\tServerShuttingDownCh: serverShuttingDownCh,\n\t}\n\n\tserver.ServeHTTP(w, req)\n}","line":{"from":64,"to":146}} {"id":100017575,"name":"ServeHTTP","signature":"func (s *WatchServer) ServeHTTP(w http.ResponseWriter, req *http.Request)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/watch.go","code":"// ServeHTTP serves a series of encoded events via HTTP with Transfer-Encoding: chunked\n// or over a websocket connection.\nfunc (s *WatchServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tkind := s.Scope.Kind\n\n\tif wsstream.IsWebSocketRequest(req) {\n\t\tw.Header().Set(\"Content-Type\", s.MediaType)\n\t\twebsocket.Handler(s.HandleWS).ServeHTTP(w, req)\n\t\treturn\n\t}\n\n\tflusher, ok := w.(http.Flusher)\n\tif !ok {\n\t\terr := fmt.Errorf(\"unable to start watch - can't get http.Flusher: %#v\", w)\n\t\tutilruntime.HandleError(err)\n\t\ts.Scope.err(errors.NewInternalError(err), w, req)\n\t\treturn\n\t}\n\n\tframer := s.Framer.NewFrameWriter(w)\n\tif framer == nil {\n\t\t// programmer error\n\t\terr := fmt.Errorf(\"no stream framing support is available for media type %q\", s.MediaType)\n\t\tutilruntime.HandleError(err)\n\t\ts.Scope.err(errors.NewBadRequest(err.Error()), w, req)\n\t\treturn\n\t}\n\n\tvar e streaming.Encoder\n\tvar memoryAllocator runtime.MemoryAllocator\n\n\tif encoder, supportsAllocator := s.Encoder.(runtime.EncoderWithAllocator); supportsAllocator {\n\t\tmemoryAllocator = runtime.AllocatorPool.Get().(*runtime.Allocator)\n\t\tdefer runtime.AllocatorPool.Put(memoryAllocator)\n\t\te = streaming.NewEncoderWithAllocator(framer, encoder, memoryAllocator)\n\t} else {\n\t\te = streaming.NewEncoder(framer, s.Encoder)\n\t}\n\n\t// ensure the connection times out\n\ttimeoutCh, cleanup := s.TimeoutFactory.TimeoutCh()\n\tdefer cleanup()\n\n\t// begin the stream\n\tw.Header().Set(\"Content-Type\", s.MediaType)\n\tw.Header().Set(\"Transfer-Encoding\", \"chunked\")\n\tw.WriteHeader(http.StatusOK)\n\tflusher.Flush()\n\n\tvar unknown runtime.Unknown\n\tinternalEvent := \u0026metav1.InternalEvent{}\n\toutEvent := \u0026metav1.WatchEvent{}\n\tbuf := \u0026bytes.Buffer{}\n\tch := s.Watching.ResultChan()\n\tdone := req.Context().Done()\n\n\tembeddedEncodeFn := s.EmbeddedEncoder.Encode\n\tif encoder, supportsAllocator := s.EmbeddedEncoder.(runtime.EncoderWithAllocator); supportsAllocator {\n\t\tif memoryAllocator == nil {\n\t\t\t// don't put the allocator inside the embeddedEncodeFn as that would allocate memory on every call.\n\t\t\t// instead, we allocate the buffer for the entire watch session and release it when we close the connection.\n\t\t\tmemoryAllocator = runtime.AllocatorPool.Get().(*runtime.Allocator)\n\t\t\tdefer runtime.AllocatorPool.Put(memoryAllocator)\n\t\t}\n\t\tembeddedEncodeFn = func(obj runtime.Object, w io.Writer) error {\n\t\t\treturn encoder.EncodeWithAllocator(obj, w, memoryAllocator)\n\t\t}\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase \u003c-s.ServerShuttingDownCh:\n\t\t\t// the server has signaled that it is shutting down (not accepting\n\t\t\t// any new request), all active watch request(s) should return\n\t\t\t// immediately here. The WithWatchTerminationDuringShutdown server\n\t\t\t// filter will ensure that the response to the client is rate\n\t\t\t// limited in order to avoid any thundering herd issue when the\n\t\t\t// client(s) try to reestablish the WATCH on the other\n\t\t\t// available apiserver instance(s).\n\t\t\treturn\n\t\tcase \u003c-done:\n\t\t\treturn\n\t\tcase \u003c-timeoutCh:\n\t\t\treturn\n\t\tcase event, ok := \u003c-ch:\n\t\t\tif !ok {\n\t\t\t\t// End of results.\n\t\t\t\treturn\n\t\t\t}\n\t\t\tmetrics.WatchEvents.WithContext(req.Context()).WithLabelValues(kind.Group, kind.Version, kind.Kind).Inc()\n\n\t\t\tobj := s.Fixup(event.Object)\n\t\t\tif err := embeddedEncodeFn(obj, buf); err != nil {\n\t\t\t\t// unexpected error\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"unable to encode watch object %T: %v\", obj, err))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// ContentType is not required here because we are defaulting to the serializer\n\t\t\t// type\n\t\t\tunknown.Raw = buf.Bytes()\n\t\t\tevent.Object = \u0026unknown\n\t\t\tmetrics.WatchEventsSizes.WithContext(req.Context()).WithLabelValues(kind.Group, kind.Version, kind.Kind).Observe(float64(len(unknown.Raw)))\n\n\t\t\t*outEvent = metav1.WatchEvent{}\n\n\t\t\t// create the external type directly and encode it. Clients will only recognize the serialization we provide.\n\t\t\t// The internal event is being reused, not reallocated so its just a few extra assignments to do it this way\n\t\t\t// and we get the benefit of using conversion functions which already have to stay in sync\n\t\t\t*internalEvent = metav1.InternalEvent(event)\n\t\t\terr := metav1.Convert_v1_InternalEvent_To_v1_WatchEvent(internalEvent, outEvent, nil)\n\t\t\tif err != nil {\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"unable to convert watch object: %v\", err))\n\t\t\t\t// client disconnect.\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err := e.Encode(outEvent); err != nil {\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"unable to encode watch object %T: %v (%#v)\", outEvent, err, e))\n\t\t\t\t// client disconnect.\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif len(ch) == 0 {\n\t\t\t\tflusher.Flush()\n\t\t\t}\n\n\t\t\tbuf.Reset()\n\t\t}\n\t}\n}","line":{"from":170,"to":298}} {"id":100017576,"name":"HandleWS","signature":"func (s *WatchServer) HandleWS(ws *websocket.Conn)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/handlers/watch.go","code":"// HandleWS implements a websocket handler.\nfunc (s *WatchServer) HandleWS(ws *websocket.Conn) {\n\tdefer ws.Close()\n\tdone := make(chan struct{})\n\n\tgo func() {\n\t\tdefer utilruntime.HandleCrash()\n\t\t// This blocks until the connection is closed.\n\t\t// Client should not send anything.\n\t\twsstream.IgnoreReceives(ws, 0)\n\t\t// Once the client closes, we should also close\n\t\tclose(done)\n\t}()\n\n\tvar unknown runtime.Unknown\n\tinternalEvent := \u0026metav1.InternalEvent{}\n\tbuf := \u0026bytes.Buffer{}\n\tstreamBuf := \u0026bytes.Buffer{}\n\tch := s.Watching.ResultChan()\n\n\tfor {\n\t\tselect {\n\t\tcase \u003c-done:\n\t\t\treturn\n\t\tcase event, ok := \u003c-ch:\n\t\t\tif !ok {\n\t\t\t\t// End of results.\n\t\t\t\treturn\n\t\t\t}\n\t\t\tobj := s.Fixup(event.Object)\n\t\t\tif err := s.EmbeddedEncoder.Encode(obj, buf); err != nil {\n\t\t\t\t// unexpected error\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"unable to encode watch object %T: %v\", obj, err))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// ContentType is not required here because we are defaulting to the serializer\n\t\t\t// type\n\t\t\tunknown.Raw = buf.Bytes()\n\t\t\tevent.Object = \u0026unknown\n\n\t\t\t// the internal event will be versioned by the encoder\n\t\t\t// create the external type directly and encode it. Clients will only recognize the serialization we provide.\n\t\t\t// The internal event is being reused, not reallocated so its just a few extra assignments to do it this way\n\t\t\t// and we get the benefit of using conversion functions which already have to stay in sync\n\t\t\toutEvent := \u0026metav1.WatchEvent{}\n\t\t\t*internalEvent = metav1.InternalEvent(event)\n\t\t\terr := metav1.Convert_v1_InternalEvent_To_v1_WatchEvent(internalEvent, outEvent, nil)\n\t\t\tif err != nil {\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"unable to convert watch object: %v\", err))\n\t\t\t\t// client disconnect.\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err := s.Encoder.Encode(outEvent, streamBuf); err != nil {\n\t\t\t\t// encoding error\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"unable to encode event: %v\", err))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif s.UseTextFraming {\n\t\t\t\tif err := websocket.Message.Send(ws, streamBuf.String()); err != nil {\n\t\t\t\t\t// Client disconnect.\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err := websocket.Message.Send(ws, streamBuf.Bytes()); err != nil {\n\t\t\t\t\t// Client disconnect.\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tbuf.Reset()\n\t\t\tstreamBuf.Reset()\n\t\t}\n\t}\n}","line":{"from":300,"to":373}} {"id":100017577,"name":"ConvertGroupVersionIntoToDiscovery","signature":"func ConvertGroupVersionIntoToDiscovery(list []metav1.APIResource) ([]apidiscoveryv2beta1.APIResourceDiscovery, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/installer.go","code":"func ConvertGroupVersionIntoToDiscovery(list []metav1.APIResource) ([]apidiscoveryv2beta1.APIResourceDiscovery, error) {\n\tvar apiResourceList []apidiscoveryv2beta1.APIResourceDiscovery\n\tparentResources := make(map[string]int)\n\n\t// Loop through all top-level resources\n\tfor _, r := range list {\n\t\tif strings.Contains(r.Name, \"/\") {\n\t\t\t// Skip subresources for now so we can get the list of resources\n\t\t\tcontinue\n\t\t}\n\n\t\tvar scope apidiscoveryv2beta1.ResourceScope\n\t\tif r.Namespaced {\n\t\t\tscope = apidiscoveryv2beta1.ScopeNamespace\n\t\t} else {\n\t\t\tscope = apidiscoveryv2beta1.ScopeCluster\n\t\t}\n\n\t\tresource := apidiscoveryv2beta1.APIResourceDiscovery{\n\t\t\tResource: r.Name,\n\t\t\tScope: scope,\n\t\t\tResponseKind: \u0026metav1.GroupVersionKind{\n\t\t\t\tGroup: r.Group,\n\t\t\t\tVersion: r.Version,\n\t\t\t\tKind: r.Kind,\n\t\t\t},\n\t\t\tVerbs: r.Verbs,\n\t\t\tShortNames: r.ShortNames,\n\t\t\tCategories: r.Categories,\n\t\t\tSingularResource: r.SingularName,\n\t\t}\n\t\tapiResourceList = append(apiResourceList, resource)\n\t\tparentResources[r.Name] = len(apiResourceList) - 1\n\t}\n\n\t// Loop through all subresources\n\tfor _, r := range list {\n\t\t// Split resource name and subresource name\n\t\tsplit := strings.SplitN(r.Name, \"/\", 2)\n\n\t\tif len(split) != 2 {\n\t\t\t// Skip parent resources\n\t\t\tcontinue\n\t\t}\n\n\t\tvar scope apidiscoveryv2beta1.ResourceScope\n\t\tif r.Namespaced {\n\t\t\tscope = apidiscoveryv2beta1.ScopeNamespace\n\t\t} else {\n\t\t\tscope = apidiscoveryv2beta1.ScopeCluster\n\t\t}\n\n\t\tparentidx, exists := parentResources[split[0]]\n\t\tif !exists {\n\t\t\t// If a subresource exists without a parent, create a parent\n\t\t\tapiResourceList = append(apiResourceList, apidiscoveryv2beta1.APIResourceDiscovery{\n\t\t\t\tResource: split[0],\n\t\t\t\tScope: scope,\n\t\t\t})\n\t\t\tparentidx = len(apiResourceList) - 1\n\t\t\tparentResources[split[0]] = parentidx\n\t\t}\n\n\t\tif apiResourceList[parentidx].Scope != scope {\n\t\t\treturn nil, fmt.Errorf(\"Error: Parent %s (scope: %s) and subresource %s (scope: %s) scope do not match\", split[0], apiResourceList[parentidx].Scope, split[1], scope)\n\t\t\t//\n\t\t}\n\n\t\tsubresource := apidiscoveryv2beta1.APISubresourceDiscovery{\n\t\t\tSubresource: split[1],\n\t\t\tVerbs: r.Verbs,\n\t\t}\n\t\tif r.Kind != \"\" {\n\t\t\tsubresource.ResponseKind = \u0026metav1.GroupVersionKind{\n\t\t\t\tGroup: r.Group,\n\t\t\t\tVersion: r.Version,\n\t\t\t\tKind: r.Kind,\n\t\t\t}\n\t\t}\n\t\tapiResourceList[parentidx].Subresources = append(apiResourceList[parentidx].Subresources, subresource)\n\t}\n\n\treturn apiResourceList, nil\n}","line":{"from":72,"to":155}} {"id":100017578,"name":"Install","signature":"func (a *APIInstaller) Install() ([]metav1.APIResource, []*storageversion.ResourceInfo, *restful.WebService, []error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/installer.go","code":"// Install handlers for API resources.\nfunc (a *APIInstaller) Install() ([]metav1.APIResource, []*storageversion.ResourceInfo, *restful.WebService, []error) {\n\tvar apiResources []metav1.APIResource\n\tvar resourceInfos []*storageversion.ResourceInfo\n\tvar errors []error\n\tws := a.newWebService()\n\n\t// Register the paths in a deterministic (sorted) order to get a deterministic swagger spec.\n\tpaths := make([]string, len(a.group.Storage))\n\tvar i int = 0\n\tfor path := range a.group.Storage {\n\t\tpaths[i] = path\n\t\ti++\n\t}\n\tsort.Strings(paths)\n\tfor _, path := range paths {\n\t\tapiResource, resourceInfo, err := a.registerResourceHandlers(path, a.group.Storage[path], ws)\n\t\tif err != nil {\n\t\t\terrors = append(errors, fmt.Errorf(\"error in registering resource: %s, %v\", path, err))\n\t\t}\n\t\tif apiResource != nil {\n\t\t\tapiResources = append(apiResources, *apiResource)\n\t\t}\n\t\tif resourceInfo != nil {\n\t\t\tresourceInfos = append(resourceInfos, resourceInfo)\n\t\t}\n\t}\n\treturn apiResources, resourceInfos, ws, errors\n}","line":{"from":183,"to":211}} {"id":100017579,"name":"newWebService","signature":"func (a *APIInstaller) newWebService() *restful.WebService","file":"staging/src/k8s.io/apiserver/pkg/endpoints/installer.go","code":"// newWebService creates a new restful webservice with the api installer's prefix and version.\nfunc (a *APIInstaller) newWebService() *restful.WebService {\n\tws := new(restful.WebService)\n\tws.Path(a.prefix)\n\t// a.prefix contains \"prefix/group/version\"\n\tws.Doc(\"API at \" + a.prefix)\n\t// Backwards compatibility, we accepted objects with empty content-type at V1.\n\t// If we stop using go-restful, we can default empty content-type to application/json on an\n\t// endpoint by endpoint basis\n\tws.Consumes(\"*/*\")\n\tmediaTypes, streamMediaTypes := negotiation.MediaTypesForSerializer(a.group.Serializer)\n\tws.Produces(append(mediaTypes, streamMediaTypes...)...)\n\tws.ApiVersion(a.group.GroupVersion.String())\n\n\treturn ws\n}","line":{"from":213,"to":228}} {"id":100017580,"name":"getStorageVersionKind","signature":"func getStorageVersionKind(storageVersioner runtime.GroupVersioner, storage rest.Storage, typer runtime.ObjectTyper) (schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/installer.go","code":"// calculate the storage gvk, the gvk objects are converted to before persisted to the etcd.\nfunc getStorageVersionKind(storageVersioner runtime.GroupVersioner, storage rest.Storage, typer runtime.ObjectTyper) (schema.GroupVersionKind, error) {\n\tobject := storage.New()\n\tfqKinds, _, err := typer.ObjectKinds(object)\n\tif err != nil {\n\t\treturn schema.GroupVersionKind{}, err\n\t}\n\tgvk, ok := storageVersioner.KindForGroupVersionKinds(fqKinds)\n\tif !ok {\n\t\treturn schema.GroupVersionKind{}, fmt.Errorf(\"cannot find the storage version kind for %v\", reflect.TypeOf(object))\n\t}\n\treturn gvk, nil\n}","line":{"from":230,"to":242}} {"id":100017581,"name":"GetResourceKind","signature":"func GetResourceKind(groupVersion schema.GroupVersion, storage rest.Storage, typer runtime.ObjectTyper) (schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/installer.go","code":"// GetResourceKind returns the external group version kind registered for the given storage\n// object. If the storage object is a subresource and has an override supplied for it, it returns\n// the group version kind supplied in the override.\nfunc GetResourceKind(groupVersion schema.GroupVersion, storage rest.Storage, typer runtime.ObjectTyper) (schema.GroupVersionKind, error) {\n\t// Let the storage tell us exactly what GVK it has\n\tif gvkProvider, ok := storage.(rest.GroupVersionKindProvider); ok {\n\t\treturn gvkProvider.GroupVersionKind(groupVersion), nil\n\t}\n\n\tobject := storage.New()\n\tfqKinds, _, err := typer.ObjectKinds(object)\n\tif err != nil {\n\t\treturn schema.GroupVersionKind{}, err\n\t}\n\n\t// a given go type can have multiple potential fully qualified kinds. Find the one that corresponds with the group\n\t// we're trying to register here\n\tfqKindToRegister := schema.GroupVersionKind{}\n\tfor _, fqKind := range fqKinds {\n\t\tif fqKind.Group == groupVersion.Group {\n\t\t\tfqKindToRegister = groupVersion.WithKind(fqKind.Kind)\n\t\t\tbreak\n\t\t}\n\t}\n\tif fqKindToRegister.Empty() {\n\t\treturn schema.GroupVersionKind{}, fmt.Errorf(\"unable to locate fully qualified kind for %v: found %v when registering for %v\", reflect.TypeOf(object), fqKinds, groupVersion)\n\t}\n\n\t// group is guaranteed to match based on the check above\n\treturn fqKindToRegister, nil\n}","line":{"from":244,"to":274}} {"id":100017582,"name":"registerResourceHandlers","signature":"func (a *APIInstaller) registerResourceHandlers(path string, storage rest.Storage, ws *restful.WebService) (*metav1.APIResource, *storageversion.ResourceInfo, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/installer.go","code":"func (a *APIInstaller) registerResourceHandlers(path string, storage rest.Storage, ws *restful.WebService) (*metav1.APIResource, *storageversion.ResourceInfo, error) {\n\tadmit := a.group.Admit\n\n\toptionsExternalVersion := a.group.GroupVersion\n\tif a.group.OptionsExternalVersion != nil {\n\t\toptionsExternalVersion = *a.group.OptionsExternalVersion\n\t}\n\n\tresource, subresource, err := splitSubresource(path)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tgroup, version := a.group.GroupVersion.Group, a.group.GroupVersion.Version\n\n\tfqKindToRegister, err := GetResourceKind(a.group.GroupVersion, storage, a.group.Typer)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tversionedPtr, err := a.group.Creater.New(fqKindToRegister)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdefaultVersionedObject := indirectArbitraryPointer(versionedPtr)\n\tkind := fqKindToRegister.Kind\n\tisSubresource := len(subresource) \u003e 0\n\n\t// If there is a subresource, namespace scoping is defined by the parent resource\n\tvar namespaceScoped bool\n\tif isSubresource {\n\t\tparentStorage, ok := a.group.Storage[resource]\n\t\tif !ok {\n\t\t\treturn nil, nil, fmt.Errorf(\"missing parent storage: %q\", resource)\n\t\t}\n\t\tscoper, ok := parentStorage.(rest.Scoper)\n\t\tif !ok {\n\t\t\treturn nil, nil, fmt.Errorf(\"%q must implement scoper\", resource)\n\t\t}\n\t\tnamespaceScoped = scoper.NamespaceScoped()\n\n\t} else {\n\t\tscoper, ok := storage.(rest.Scoper)\n\t\tif !ok {\n\t\t\treturn nil, nil, fmt.Errorf(\"%q must implement scoper\", resource)\n\t\t}\n\t\tnamespaceScoped = scoper.NamespaceScoped()\n\t}\n\n\t// what verbs are supported by the storage, used to know what verbs we support per path\n\tcreater, isCreater := storage.(rest.Creater)\n\tnamedCreater, isNamedCreater := storage.(rest.NamedCreater)\n\tlister, isLister := storage.(rest.Lister)\n\tgetter, isGetter := storage.(rest.Getter)\n\tgetterWithOptions, isGetterWithOptions := storage.(rest.GetterWithOptions)\n\tgracefulDeleter, isGracefulDeleter := storage.(rest.GracefulDeleter)\n\tcollectionDeleter, isCollectionDeleter := storage.(rest.CollectionDeleter)\n\tupdater, isUpdater := storage.(rest.Updater)\n\tpatcher, isPatcher := storage.(rest.Patcher)\n\twatcher, isWatcher := storage.(rest.Watcher)\n\tconnecter, isConnecter := storage.(rest.Connecter)\n\tstorageMeta, isMetadata := storage.(rest.StorageMetadata)\n\tstorageVersionProvider, isStorageVersionProvider := storage.(rest.StorageVersionProvider)\n\tgvAcceptor, _ := storage.(rest.GroupVersionAcceptor)\n\tif !isMetadata {\n\t\tstorageMeta = defaultStorageMetadata{}\n\t}\n\n\tif isNamedCreater {\n\t\tisCreater = true\n\t}\n\n\tvar versionedList interface{}\n\tif isLister {\n\t\tlist := lister.NewList()\n\t\tlistGVKs, _, err := a.group.Typer.ObjectKinds(list)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tversionedListPtr, err := a.group.Creater.New(a.group.GroupVersion.WithKind(listGVKs[0].Kind))\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tversionedList = indirectArbitraryPointer(versionedListPtr)\n\t}\n\n\tversionedListOptions, err := a.group.Creater.New(optionsExternalVersion.WithKind(\"ListOptions\"))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tversionedCreateOptions, err := a.group.Creater.New(optionsExternalVersion.WithKind(\"CreateOptions\"))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tversionedPatchOptions, err := a.group.Creater.New(optionsExternalVersion.WithKind(\"PatchOptions\"))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tversionedUpdateOptions, err := a.group.Creater.New(optionsExternalVersion.WithKind(\"UpdateOptions\"))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar versionedDeleteOptions runtime.Object\n\tvar versionedDeleterObject interface{}\n\tdeleteReturnsDeletedObject := false\n\tif isGracefulDeleter {\n\t\tversionedDeleteOptions, err = a.group.Creater.New(optionsExternalVersion.WithKind(\"DeleteOptions\"))\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tversionedDeleterObject = indirectArbitraryPointer(versionedDeleteOptions)\n\n\t\tif mayReturnFullObjectDeleter, ok := storage.(rest.MayReturnFullObjectDeleter); ok {\n\t\t\tdeleteReturnsDeletedObject = mayReturnFullObjectDeleter.DeleteReturnsDeletedObject()\n\t\t}\n\t}\n\n\tversionedStatusPtr, err := a.group.Creater.New(optionsExternalVersion.WithKind(\"Status\"))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tversionedStatus := indirectArbitraryPointer(versionedStatusPtr)\n\tvar (\n\t\tgetOptions runtime.Object\n\t\tversionedGetOptions runtime.Object\n\t\tgetOptionsInternalKind schema.GroupVersionKind\n\t\tgetSubpath bool\n\t)\n\tif isGetterWithOptions {\n\t\tgetOptions, getSubpath, _ = getterWithOptions.NewGetOptions()\n\t\tgetOptionsInternalKinds, _, err := a.group.Typer.ObjectKinds(getOptions)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tgetOptionsInternalKind = getOptionsInternalKinds[0]\n\t\tversionedGetOptions, err = a.group.Creater.New(a.group.GroupVersion.WithKind(getOptionsInternalKind.Kind))\n\t\tif err != nil {\n\t\t\tversionedGetOptions, err = a.group.Creater.New(optionsExternalVersion.WithKind(getOptionsInternalKind.Kind))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t}\n\t\tisGetter = true\n\t}\n\n\tvar versionedWatchEvent interface{}\n\tif isWatcher {\n\t\tversionedWatchEventPtr, err := a.group.Creater.New(a.group.GroupVersion.WithKind(\"WatchEvent\"))\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tversionedWatchEvent = indirectArbitraryPointer(versionedWatchEventPtr)\n\t}\n\n\tvar (\n\t\tconnectOptions runtime.Object\n\t\tversionedConnectOptions runtime.Object\n\t\tconnectOptionsInternalKind schema.GroupVersionKind\n\t\tconnectSubpath bool\n\t)\n\tif isConnecter {\n\t\tconnectOptions, connectSubpath, _ = connecter.NewConnectOptions()\n\t\tif connectOptions != nil {\n\t\t\tconnectOptionsInternalKinds, _, err := a.group.Typer.ObjectKinds(connectOptions)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\n\t\t\tconnectOptionsInternalKind = connectOptionsInternalKinds[0]\n\t\t\tversionedConnectOptions, err = a.group.Creater.New(a.group.GroupVersion.WithKind(connectOptionsInternalKind.Kind))\n\t\t\tif err != nil {\n\t\t\t\tversionedConnectOptions, err = a.group.Creater.New(optionsExternalVersion.WithKind(connectOptionsInternalKind.Kind))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tallowWatchList := isWatcher \u0026\u0026 isLister // watching on lists is allowed only for kinds that support both watch and list.\n\tnameParam := ws.PathParameter(\"name\", \"name of the \"+kind).DataType(\"string\")\n\tpathParam := ws.PathParameter(\"path\", \"path to the resource\").DataType(\"string\")\n\n\tparams := []*restful.Parameter{}\n\tactions := []action{}\n\n\tvar resourceKind string\n\tkindProvider, ok := storage.(rest.KindProvider)\n\tif ok {\n\t\tresourceKind = kindProvider.Kind()\n\t} else {\n\t\tresourceKind = kind\n\t}\n\n\ttableProvider, isTableProvider := storage.(rest.TableConvertor)\n\tif isLister \u0026\u0026 !isTableProvider {\n\t\t// All listers must implement TableProvider\n\t\treturn nil, nil, fmt.Errorf(\"%q must implement TableConvertor\", resource)\n\t}\n\n\tvar apiResource metav1.APIResource\n\tif utilfeature.DefaultFeatureGate.Enabled(features.StorageVersionHash) \u0026\u0026\n\t\tisStorageVersionProvider \u0026\u0026\n\t\tstorageVersionProvider.StorageVersion() != nil {\n\t\tversioner := storageVersionProvider.StorageVersion()\n\t\tgvk, err := getStorageVersionKind(versioner, storage, a.group.Typer)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tapiResource.StorageVersionHash = discovery.StorageVersionHash(gvk.Group, gvk.Version, gvk.Kind)\n\t}\n\n\t// Get the list of actions for the given scope.\n\tswitch {\n\tcase !namespaceScoped:\n\t\t// Handle non-namespace scoped resources like nodes.\n\t\tresourcePath := resource\n\t\tresourceParams := params\n\t\titemPath := resourcePath + \"/{name}\"\n\t\tnameParams := append(params, nameParam)\n\t\tproxyParams := append(nameParams, pathParam)\n\t\tsuffix := \"\"\n\t\tif isSubresource {\n\t\t\tsuffix = \"/\" + subresource\n\t\t\titemPath = itemPath + suffix\n\t\t\tresourcePath = itemPath\n\t\t\tresourceParams = nameParams\n\t\t}\n\t\tapiResource.Name = path\n\t\tapiResource.Namespaced = false\n\t\tapiResource.Kind = resourceKind\n\t\tnamer := handlers.ContextBasedNaming{\n\t\t\tNamer: a.group.Namer,\n\t\t\tClusterScoped: true,\n\t\t}\n\n\t\t// Handler for standard REST verbs (GET, PUT, POST and DELETE).\n\t\t// Add actions at the resource path: /api/apiVersion/resource\n\t\tactions = appendIf(actions, action{\"LIST\", resourcePath, resourceParams, namer, false}, isLister)\n\t\tactions = appendIf(actions, action{\"POST\", resourcePath, resourceParams, namer, false}, isCreater)\n\t\tactions = appendIf(actions, action{\"DELETECOLLECTION\", resourcePath, resourceParams, namer, false}, isCollectionDeleter)\n\t\t// DEPRECATED in 1.11\n\t\tactions = appendIf(actions, action{\"WATCHLIST\", \"watch/\" + resourcePath, resourceParams, namer, false}, allowWatchList)\n\n\t\t// Add actions at the item path: /api/apiVersion/resource/{name}\n\t\tactions = appendIf(actions, action{\"GET\", itemPath, nameParams, namer, false}, isGetter)\n\t\tif getSubpath {\n\t\t\tactions = appendIf(actions, action{\"GET\", itemPath + \"/{path:*}\", proxyParams, namer, false}, isGetter)\n\t\t}\n\t\tactions = appendIf(actions, action{\"PUT\", itemPath, nameParams, namer, false}, isUpdater)\n\t\tactions = appendIf(actions, action{\"PATCH\", itemPath, nameParams, namer, false}, isPatcher)\n\t\tactions = appendIf(actions, action{\"DELETE\", itemPath, nameParams, namer, false}, isGracefulDeleter)\n\t\t// DEPRECATED in 1.11\n\t\tactions = appendIf(actions, action{\"WATCH\", \"watch/\" + itemPath, nameParams, namer, false}, isWatcher)\n\t\tactions = appendIf(actions, action{\"CONNECT\", itemPath, nameParams, namer, false}, isConnecter)\n\t\tactions = appendIf(actions, action{\"CONNECT\", itemPath + \"/{path:*}\", proxyParams, namer, false}, isConnecter \u0026\u0026 connectSubpath)\n\tdefault:\n\t\tnamespaceParamName := \"namespaces\"\n\t\t// Handler for standard REST verbs (GET, PUT, POST and DELETE).\n\t\tnamespaceParam := ws.PathParameter(\"namespace\", \"object name and auth scope, such as for teams and projects\").DataType(\"string\")\n\t\tnamespacedPath := namespaceParamName + \"/{namespace}/\" + resource\n\t\tnamespaceParams := []*restful.Parameter{namespaceParam}\n\n\t\tresourcePath := namespacedPath\n\t\tresourceParams := namespaceParams\n\t\titemPath := namespacedPath + \"/{name}\"\n\t\tnameParams := append(namespaceParams, nameParam)\n\t\tproxyParams := append(nameParams, pathParam)\n\t\titemPathSuffix := \"\"\n\t\tif isSubresource {\n\t\t\titemPathSuffix = \"/\" + subresource\n\t\t\titemPath = itemPath + itemPathSuffix\n\t\t\tresourcePath = itemPath\n\t\t\tresourceParams = nameParams\n\t\t}\n\t\tapiResource.Name = path\n\t\tapiResource.Namespaced = true\n\t\tapiResource.Kind = resourceKind\n\t\tnamer := handlers.ContextBasedNaming{\n\t\t\tNamer: a.group.Namer,\n\t\t\tClusterScoped: false,\n\t\t}\n\n\t\tactions = appendIf(actions, action{\"LIST\", resourcePath, resourceParams, namer, false}, isLister)\n\t\tactions = appendIf(actions, action{\"POST\", resourcePath, resourceParams, namer, false}, isCreater)\n\t\tactions = appendIf(actions, action{\"DELETECOLLECTION\", resourcePath, resourceParams, namer, false}, isCollectionDeleter)\n\t\t// DEPRECATED in 1.11\n\t\tactions = appendIf(actions, action{\"WATCHLIST\", \"watch/\" + resourcePath, resourceParams, namer, false}, allowWatchList)\n\n\t\tactions = appendIf(actions, action{\"GET\", itemPath, nameParams, namer, false}, isGetter)\n\t\tif getSubpath {\n\t\t\tactions = appendIf(actions, action{\"GET\", itemPath + \"/{path:*}\", proxyParams, namer, false}, isGetter)\n\t\t}\n\t\tactions = appendIf(actions, action{\"PUT\", itemPath, nameParams, namer, false}, isUpdater)\n\t\tactions = appendIf(actions, action{\"PATCH\", itemPath, nameParams, namer, false}, isPatcher)\n\t\tactions = appendIf(actions, action{\"DELETE\", itemPath, nameParams, namer, false}, isGracefulDeleter)\n\t\t// DEPRECATED in 1.11\n\t\tactions = appendIf(actions, action{\"WATCH\", \"watch/\" + itemPath, nameParams, namer, false}, isWatcher)\n\t\tactions = appendIf(actions, action{\"CONNECT\", itemPath, nameParams, namer, false}, isConnecter)\n\t\tactions = appendIf(actions, action{\"CONNECT\", itemPath + \"/{path:*}\", proxyParams, namer, false}, isConnecter \u0026\u0026 connectSubpath)\n\n\t\t// list or post across namespace.\n\t\t// For ex: LIST all pods in all namespaces by sending a LIST request at /api/apiVersion/pods.\n\t\t// TODO: more strongly type whether a resource allows these actions on \"all namespaces\" (bulk delete)\n\t\tif !isSubresource {\n\t\t\tactions = appendIf(actions, action{\"LIST\", resource, params, namer, true}, isLister)\n\t\t\t// DEPRECATED in 1.11\n\t\t\tactions = appendIf(actions, action{\"WATCHLIST\", \"watch/\" + resource, params, namer, true}, allowWatchList)\n\t\t}\n\t}\n\n\tvar resourceInfo *storageversion.ResourceInfo\n\tif utilfeature.DefaultFeatureGate.Enabled(features.StorageVersionAPI) \u0026\u0026\n\t\tutilfeature.DefaultFeatureGate.Enabled(features.APIServerIdentity) \u0026\u0026\n\t\tisStorageVersionProvider \u0026\u0026\n\t\tstorageVersionProvider.StorageVersion() != nil {\n\n\t\tversioner := storageVersionProvider.StorageVersion()\n\t\tencodingGVK, err := getStorageVersionKind(versioner, storage, a.group.Typer)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tdecodableVersions := []schema.GroupVersion{}\n\t\tif a.group.ConvertabilityChecker != nil {\n\t\t\tdecodableVersions = a.group.ConvertabilityChecker.VersionsForGroupKind(fqKindToRegister.GroupKind())\n\t\t}\n\t\tresourceInfo = \u0026storageversion.ResourceInfo{\n\t\t\tGroupResource: schema.GroupResource{\n\t\t\t\tGroup: a.group.GroupVersion.Group,\n\t\t\t\tResource: apiResource.Name,\n\t\t\t},\n\t\t\tEncodingVersion: encodingGVK.GroupVersion().String(),\n\t\t\t// We record EquivalentResourceMapper first instead of calculate\n\t\t\t// DecodableVersions immediately because API installation must\n\t\t\t// be completed first for us to know equivalent APIs\n\t\t\tEquivalentResourceMapper: a.group.EquivalentResourceRegistry,\n\n\t\t\tDirectlyDecodableVersions: decodableVersions,\n\t\t}\n\t}\n\n\t// Create Routes for the actions.\n\t// TODO: Add status documentation using Returns()\n\t// Errors (see api/errors/errors.go as well as go-restful router):\n\t// http.StatusNotFound, http.StatusMethodNotAllowed,\n\t// http.StatusUnsupportedMediaType, http.StatusNotAcceptable,\n\t// http.StatusBadRequest, http.StatusUnauthorized, http.StatusForbidden,\n\t// http.StatusRequestTimeout, http.StatusConflict, http.StatusPreconditionFailed,\n\t// http.StatusUnprocessableEntity, http.StatusInternalServerError,\n\t// http.StatusServiceUnavailable\n\t// and api error codes\n\t// Note that if we specify a versioned Status object here, we may need to\n\t// create one for the tests, also\n\t// Success:\n\t// http.StatusOK, http.StatusCreated, http.StatusAccepted, http.StatusNoContent\n\t//\n\t// test/integration/auth_test.go is currently the most comprehensive status code test\n\n\tfor _, s := range a.group.Serializer.SupportedMediaTypes() {\n\t\tif len(s.MediaTypeSubType) == 0 || len(s.MediaTypeType) == 0 {\n\t\t\treturn nil, nil, fmt.Errorf(\"all serializers in the group Serializer must have MediaTypeType and MediaTypeSubType set: %s\", s.MediaType)\n\t\t}\n\t}\n\tmediaTypes, streamMediaTypes := negotiation.MediaTypesForSerializer(a.group.Serializer)\n\tallMediaTypes := append(mediaTypes, streamMediaTypes...)\n\tws.Produces(allMediaTypes...)\n\n\tkubeVerbs := map[string]struct{}{}\n\treqScope := handlers.RequestScope{\n\t\tSerializer: a.group.Serializer,\n\t\tParameterCodec: a.group.ParameterCodec,\n\t\tCreater: a.group.Creater,\n\t\tConvertor: a.group.Convertor,\n\t\tDefaulter: a.group.Defaulter,\n\t\tTyper: a.group.Typer,\n\t\tUnsafeConvertor: a.group.UnsafeConvertor,\n\t\tAuthorizer: a.group.Authorizer,\n\n\t\tEquivalentResourceMapper: a.group.EquivalentResourceRegistry,\n\n\t\t// TODO: Check for the interface on storage\n\t\tTableConvertor: tableProvider,\n\n\t\t// TODO: This seems wrong for cross-group subresources. It makes an assumption that a subresource and its parent are in the same group version. Revisit this.\n\t\tResource: a.group.GroupVersion.WithResource(resource),\n\t\tSubresource: subresource,\n\t\tKind: fqKindToRegister,\n\n\t\tAcceptsGroupVersionDelegate: gvAcceptor,\n\n\t\tHubGroupVersion: schema.GroupVersion{Group: fqKindToRegister.Group, Version: runtime.APIVersionInternal},\n\n\t\tMetaGroupVersion: metav1.SchemeGroupVersion,\n\n\t\tMaxRequestBodyBytes: a.group.MaxRequestBodyBytes,\n\t}\n\tif a.group.MetaGroupVersion != nil {\n\t\treqScope.MetaGroupVersion = *a.group.MetaGroupVersion\n\t}\n\n\t// Use TypeConverter's nil-ness as a proxy for whether SSA/OpenAPI is enabled\n\t// This should be removed in the future and made unconditional\n\t// https://github.com/kubernetes/kubernetes/pull/114998\n\tif a.group.TypeConverter != nil {\n\t\tvar resetFields map[fieldpath.APIVersion]*fieldpath.Set\n\t\tif resetFieldsStrategy, isResetFieldsStrategy := storage.(rest.ResetFieldsStrategy); isResetFieldsStrategy {\n\t\t\tresetFields = resetFieldsStrategy.GetResetFields()\n\t\t}\n\n\t\treqScope.FieldManager, err = managedfields.NewDefaultFieldManager(\n\t\t\ta.group.TypeConverter,\n\t\t\ta.group.UnsafeConvertor,\n\t\t\ta.group.Defaulter,\n\t\t\ta.group.Creater,\n\t\t\tfqKindToRegister,\n\t\t\treqScope.HubGroupVersion,\n\t\t\tsubresource,\n\t\t\tresetFields,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"failed to create field manager: %v\", err)\n\t\t}\n\t}\n\n\tfor _, action := range actions {\n\t\tproducedObject := storageMeta.ProducesObject(action.Verb)\n\t\tif producedObject == nil {\n\t\t\tproducedObject = defaultVersionedObject\n\t\t}\n\t\treqScope.Namer = action.Namer\n\n\t\trequestScope := \"cluster\"\n\t\tvar namespaced string\n\t\tvar operationSuffix string\n\t\tif apiResource.Namespaced {\n\t\t\trequestScope = \"namespace\"\n\t\t\tnamespaced = \"Namespaced\"\n\t\t}\n\t\tif strings.HasSuffix(action.Path, \"/{path:*}\") {\n\t\t\trequestScope = \"resource\"\n\t\t\toperationSuffix = operationSuffix + \"WithPath\"\n\t\t}\n\t\tif strings.Index(action.Path, \"/{name}\") != -1 || action.Verb == \"POST\" {\n\t\t\trequestScope = \"resource\"\n\t\t}\n\t\tif action.AllNamespaces {\n\t\t\trequestScope = \"cluster\"\n\t\t\toperationSuffix = operationSuffix + \"ForAllNamespaces\"\n\t\t\tnamespaced = \"\"\n\t\t}\n\n\t\tif kubeVerb, found := toDiscoveryKubeVerb[action.Verb]; found {\n\t\t\tif len(kubeVerb) != 0 {\n\t\t\t\tkubeVerbs[kubeVerb] = struct{}{}\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, nil, fmt.Errorf(\"unknown action verb for discovery: %s\", action.Verb)\n\t\t}\n\n\t\troutes := []*restful.RouteBuilder{}\n\n\t\t// If there is a subresource, kind should be the parent's kind.\n\t\tif isSubresource {\n\t\t\tparentStorage, ok := a.group.Storage[resource]\n\t\t\tif !ok {\n\t\t\t\treturn nil, nil, fmt.Errorf(\"missing parent storage: %q\", resource)\n\t\t\t}\n\n\t\t\tfqParentKind, err := GetResourceKind(a.group.GroupVersion, parentStorage, a.group.Typer)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\tkind = fqParentKind.Kind\n\t\t}\n\n\t\tverbOverrider, needOverride := storage.(StorageMetricsOverride)\n\n\t\t// accumulate endpoint-level warnings\n\t\tvar (\n\t\t\twarnings []string\n\t\t\tdeprecated bool\n\t\t\tremovedRelease string\n\t\t)\n\n\t\t{\n\t\t\tversionedPtrWithGVK := versionedPtr.DeepCopyObject()\n\t\t\tversionedPtrWithGVK.GetObjectKind().SetGroupVersionKind(fqKindToRegister)\n\t\t\tcurrentMajor, currentMinor, _ := deprecation.MajorMinor(versioninfo.Get())\n\t\t\tdeprecated = deprecation.IsDeprecated(versionedPtrWithGVK, currentMajor, currentMinor)\n\t\t\tif deprecated {\n\t\t\t\tremovedRelease = deprecation.RemovedRelease(versionedPtrWithGVK)\n\t\t\t\twarnings = append(warnings, deprecation.WarningMessage(versionedPtrWithGVK))\n\t\t\t}\n\t\t}\n\n\t\tswitch action.Verb {\n\t\tcase \"GET\": // Get a resource.\n\t\t\tvar handler restful.RouteFunction\n\t\t\tif isGetterWithOptions {\n\t\t\t\thandler = restfulGetResourceWithOptions(getterWithOptions, reqScope, isSubresource)\n\t\t\t} else {\n\t\t\t\thandler = restfulGetResource(getter, reqScope)\n\t\t\t}\n\n\t\t\tif needOverride {\n\t\t\t\t// need change the reported verb\n\t\t\t\thandler = metrics.InstrumentRouteFunc(verbOverrider.OverrideMetricsVerb(action.Verb), group, version, resource, subresource, requestScope, metrics.APIServerComponent, deprecated, removedRelease, handler)\n\t\t\t} else {\n\t\t\t\thandler = metrics.InstrumentRouteFunc(action.Verb, group, version, resource, subresource, requestScope, metrics.APIServerComponent, deprecated, removedRelease, handler)\n\t\t\t}\n\t\t\thandler = utilwarning.AddWarningsHandler(handler, warnings)\n\n\t\t\tdoc := \"read the specified \" + kind\n\t\t\tif isSubresource {\n\t\t\t\tdoc = \"read \" + subresource + \" of the specified \" + kind\n\t\t\t}\n\t\t\troute := ws.GET(action.Path).To(handler).\n\t\t\t\tDoc(doc).\n\t\t\t\tParam(ws.QueryParameter(\"pretty\", \"If 'true', then the output is pretty printed.\")).\n\t\t\t\tOperation(\"read\"+namespaced+kind+strings.Title(subresource)+operationSuffix).\n\t\t\t\tProduces(append(storageMeta.ProducesMIMETypes(action.Verb), mediaTypes...)...).\n\t\t\t\tReturns(http.StatusOK, \"OK\", producedObject).\n\t\t\t\tWrites(producedObject)\n\t\t\tif isGetterWithOptions {\n\t\t\t\tif err := AddObjectParams(ws, route, versionedGetOptions); err != nil {\n\t\t\t\t\treturn nil, nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\taddParams(route, action.Params)\n\t\t\troutes = append(routes, route)\n\t\tcase \"LIST\": // List all resources of a kind.\n\t\t\tdoc := \"list objects of kind \" + kind\n\t\t\tif isSubresource {\n\t\t\t\tdoc = \"list \" + subresource + \" of objects of kind \" + kind\n\t\t\t}\n\t\t\thandler := metrics.InstrumentRouteFunc(action.Verb, group, version, resource, subresource, requestScope, metrics.APIServerComponent, deprecated, removedRelease, restfulListResource(lister, watcher, reqScope, false, a.minRequestTimeout))\n\t\t\thandler = utilwarning.AddWarningsHandler(handler, warnings)\n\t\t\troute := ws.GET(action.Path).To(handler).\n\t\t\t\tDoc(doc).\n\t\t\t\tParam(ws.QueryParameter(\"pretty\", \"If 'true', then the output is pretty printed.\")).\n\t\t\t\tOperation(\"list\"+namespaced+kind+strings.Title(subresource)+operationSuffix).\n\t\t\t\tProduces(append(storageMeta.ProducesMIMETypes(action.Verb), allMediaTypes...)...).\n\t\t\t\tReturns(http.StatusOK, \"OK\", versionedList).\n\t\t\t\tWrites(versionedList)\n\t\t\tif err := AddObjectParams(ws, route, versionedListOptions); err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\tswitch {\n\t\t\tcase isLister \u0026\u0026 isWatcher:\n\t\t\t\tdoc := \"list or watch objects of kind \" + kind\n\t\t\t\tif isSubresource {\n\t\t\t\t\tdoc = \"list or watch \" + subresource + \" of objects of kind \" + kind\n\t\t\t\t}\n\t\t\t\troute.Doc(doc)\n\t\t\tcase isWatcher:\n\t\t\t\tdoc := \"watch objects of kind \" + kind\n\t\t\t\tif isSubresource {\n\t\t\t\t\tdoc = \"watch \" + subresource + \"of objects of kind \" + kind\n\t\t\t\t}\n\t\t\t\troute.Doc(doc)\n\t\t\t}\n\t\t\taddParams(route, action.Params)\n\t\t\troutes = append(routes, route)\n\t\tcase \"PUT\": // Update a resource.\n\t\t\tdoc := \"replace the specified \" + kind\n\t\t\tif isSubresource {\n\t\t\t\tdoc = \"replace \" + subresource + \" of the specified \" + kind\n\t\t\t}\n\t\t\thandler := metrics.InstrumentRouteFunc(action.Verb, group, version, resource, subresource, requestScope, metrics.APIServerComponent, deprecated, removedRelease, restfulUpdateResource(updater, reqScope, admit))\n\t\t\thandler = utilwarning.AddWarningsHandler(handler, warnings)\n\t\t\troute := ws.PUT(action.Path).To(handler).\n\t\t\t\tDoc(doc).\n\t\t\t\tParam(ws.QueryParameter(\"pretty\", \"If 'true', then the output is pretty printed.\")).\n\t\t\t\tOperation(\"replace\"+namespaced+kind+strings.Title(subresource)+operationSuffix).\n\t\t\t\tProduces(append(storageMeta.ProducesMIMETypes(action.Verb), mediaTypes...)...).\n\t\t\t\tReturns(http.StatusOK, \"OK\", producedObject).\n\t\t\t\t// TODO: in some cases, the API may return a v1.Status instead of the versioned object\n\t\t\t\t// but currently go-restful can't handle multiple different objects being returned.\n\t\t\t\tReturns(http.StatusCreated, \"Created\", producedObject).\n\t\t\t\tReads(defaultVersionedObject).\n\t\t\t\tWrites(producedObject)\n\t\t\tif err := AddObjectParams(ws, route, versionedUpdateOptions); err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\taddParams(route, action.Params)\n\t\t\troutes = append(routes, route)\n\t\tcase \"PATCH\": // Partially update a resource\n\t\t\tdoc := \"partially update the specified \" + kind\n\t\t\tif isSubresource {\n\t\t\t\tdoc = \"partially update \" + subresource + \" of the specified \" + kind\n\t\t\t}\n\t\t\tsupportedTypes := []string{\n\t\t\t\tstring(types.JSONPatchType),\n\t\t\t\tstring(types.MergePatchType),\n\t\t\t\tstring(types.StrategicMergePatchType),\n\t\t\t\tstring(types.ApplyPatchType),\n\t\t\t}\n\t\t\thandler := metrics.InstrumentRouteFunc(action.Verb, group, version, resource, subresource, requestScope, metrics.APIServerComponent, deprecated, removedRelease, restfulPatchResource(patcher, reqScope, admit, supportedTypes))\n\t\t\thandler = utilwarning.AddWarningsHandler(handler, warnings)\n\t\t\troute := ws.PATCH(action.Path).To(handler).\n\t\t\t\tDoc(doc).\n\t\t\t\tParam(ws.QueryParameter(\"pretty\", \"If 'true', then the output is pretty printed.\")).\n\t\t\t\tConsumes(supportedTypes...).\n\t\t\t\tOperation(\"patch\"+namespaced+kind+strings.Title(subresource)+operationSuffix).\n\t\t\t\tProduces(append(storageMeta.ProducesMIMETypes(action.Verb), mediaTypes...)...).\n\t\t\t\tReturns(http.StatusOK, \"OK\", producedObject).\n\t\t\t\t// Patch can return 201 when a server side apply is requested\n\t\t\t\tReturns(http.StatusCreated, \"Created\", producedObject).\n\t\t\t\tReads(metav1.Patch{}).\n\t\t\t\tWrites(producedObject)\n\t\t\tif err := AddObjectParams(ws, route, versionedPatchOptions); err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\taddParams(route, action.Params)\n\t\t\troutes = append(routes, route)\n\t\tcase \"POST\": // Create a resource.\n\t\t\tvar handler restful.RouteFunction\n\t\t\tif isNamedCreater {\n\t\t\t\thandler = restfulCreateNamedResource(namedCreater, reqScope, admit)\n\t\t\t} else {\n\t\t\t\thandler = restfulCreateResource(creater, reqScope, admit)\n\t\t\t}\n\t\t\thandler = metrics.InstrumentRouteFunc(action.Verb, group, version, resource, subresource, requestScope, metrics.APIServerComponent, deprecated, removedRelease, handler)\n\t\t\thandler = utilwarning.AddWarningsHandler(handler, warnings)\n\t\t\tarticle := GetArticleForNoun(kind, \" \")\n\t\t\tdoc := \"create\" + article + kind\n\t\t\tif isSubresource {\n\t\t\t\tdoc = \"create \" + subresource + \" of\" + article + kind\n\t\t\t}\n\t\t\troute := ws.POST(action.Path).To(handler).\n\t\t\t\tDoc(doc).\n\t\t\t\tParam(ws.QueryParameter(\"pretty\", \"If 'true', then the output is pretty printed.\")).\n\t\t\t\tOperation(\"create\"+namespaced+kind+strings.Title(subresource)+operationSuffix).\n\t\t\t\tProduces(append(storageMeta.ProducesMIMETypes(action.Verb), mediaTypes...)...).\n\t\t\t\tReturns(http.StatusOK, \"OK\", producedObject).\n\t\t\t\t// TODO: in some cases, the API may return a v1.Status instead of the versioned object\n\t\t\t\t// but currently go-restful can't handle multiple different objects being returned.\n\t\t\t\tReturns(http.StatusCreated, \"Created\", producedObject).\n\t\t\t\tReturns(http.StatusAccepted, \"Accepted\", producedObject).\n\t\t\t\tReads(defaultVersionedObject).\n\t\t\t\tWrites(producedObject)\n\t\t\tif err := AddObjectParams(ws, route, versionedCreateOptions); err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\taddParams(route, action.Params)\n\t\t\troutes = append(routes, route)\n\t\tcase \"DELETE\": // Delete a resource.\n\t\t\tarticle := GetArticleForNoun(kind, \" \")\n\t\t\tdoc := \"delete\" + article + kind\n\t\t\tif isSubresource {\n\t\t\t\tdoc = \"delete \" + subresource + \" of\" + article + kind\n\t\t\t}\n\t\t\tdeleteReturnType := versionedStatus\n\t\t\tif deleteReturnsDeletedObject {\n\t\t\t\tdeleteReturnType = producedObject\n\t\t\t}\n\t\t\thandler := metrics.InstrumentRouteFunc(action.Verb, group, version, resource, subresource, requestScope, metrics.APIServerComponent, deprecated, removedRelease, restfulDeleteResource(gracefulDeleter, isGracefulDeleter, reqScope, admit))\n\t\t\thandler = utilwarning.AddWarningsHandler(handler, warnings)\n\t\t\troute := ws.DELETE(action.Path).To(handler).\n\t\t\t\tDoc(doc).\n\t\t\t\tParam(ws.QueryParameter(\"pretty\", \"If 'true', then the output is pretty printed.\")).\n\t\t\t\tOperation(\"delete\"+namespaced+kind+strings.Title(subresource)+operationSuffix).\n\t\t\t\tProduces(append(storageMeta.ProducesMIMETypes(action.Verb), mediaTypes...)...).\n\t\t\t\tWrites(deleteReturnType).\n\t\t\t\tReturns(http.StatusOK, \"OK\", deleteReturnType).\n\t\t\t\tReturns(http.StatusAccepted, \"Accepted\", deleteReturnType)\n\t\t\tif isGracefulDeleter {\n\t\t\t\troute.Reads(versionedDeleterObject)\n\t\t\t\troute.ParameterNamed(\"body\").Required(false)\n\t\t\t\tif err := AddObjectParams(ws, route, versionedDeleteOptions); err != nil {\n\t\t\t\t\treturn nil, nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\taddParams(route, action.Params)\n\t\t\troutes = append(routes, route)\n\t\tcase \"DELETECOLLECTION\":\n\t\t\tdoc := \"delete collection of \" + kind\n\t\t\tif isSubresource {\n\t\t\t\tdoc = \"delete collection of \" + subresource + \" of a \" + kind\n\t\t\t}\n\t\t\thandler := metrics.InstrumentRouteFunc(action.Verb, group, version, resource, subresource, requestScope, metrics.APIServerComponent, deprecated, removedRelease, restfulDeleteCollection(collectionDeleter, isCollectionDeleter, reqScope, admit))\n\t\t\thandler = utilwarning.AddWarningsHandler(handler, warnings)\n\t\t\troute := ws.DELETE(action.Path).To(handler).\n\t\t\t\tDoc(doc).\n\t\t\t\tParam(ws.QueryParameter(\"pretty\", \"If 'true', then the output is pretty printed.\")).\n\t\t\t\tOperation(\"deletecollection\"+namespaced+kind+strings.Title(subresource)+operationSuffix).\n\t\t\t\tProduces(append(storageMeta.ProducesMIMETypes(action.Verb), mediaTypes...)...).\n\t\t\t\tWrites(versionedStatus).\n\t\t\t\tReturns(http.StatusOK, \"OK\", versionedStatus)\n\t\t\tif isCollectionDeleter {\n\t\t\t\troute.Reads(versionedDeleterObject)\n\t\t\t\troute.ParameterNamed(\"body\").Required(false)\n\t\t\t\tif err := AddObjectParams(ws, route, versionedDeleteOptions); err != nil {\n\t\t\t\t\treturn nil, nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err := AddObjectParams(ws, route, versionedListOptions, \"watch\", \"allowWatchBookmarks\"); err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\taddParams(route, action.Params)\n\t\t\troutes = append(routes, route)\n\t\t// deprecated in 1.11\n\t\tcase \"WATCH\": // Watch a resource.\n\t\t\tdoc := \"watch changes to an object of kind \" + kind\n\t\t\tif isSubresource {\n\t\t\t\tdoc = \"watch changes to \" + subresource + \" of an object of kind \" + kind\n\t\t\t}\n\t\t\tdoc += \". deprecated: use the 'watch' parameter with a list operation instead, filtered to a single item with the 'fieldSelector' parameter.\"\n\t\t\thandler := metrics.InstrumentRouteFunc(action.Verb, group, version, resource, subresource, requestScope, metrics.APIServerComponent, deprecated, removedRelease, restfulListResource(lister, watcher, reqScope, true, a.minRequestTimeout))\n\t\t\thandler = utilwarning.AddWarningsHandler(handler, warnings)\n\t\t\troute := ws.GET(action.Path).To(handler).\n\t\t\t\tDoc(doc).\n\t\t\t\tParam(ws.QueryParameter(\"pretty\", \"If 'true', then the output is pretty printed.\")).\n\t\t\t\tOperation(\"watch\"+namespaced+kind+strings.Title(subresource)+operationSuffix).\n\t\t\t\tProduces(allMediaTypes...).\n\t\t\t\tReturns(http.StatusOK, \"OK\", versionedWatchEvent).\n\t\t\t\tWrites(versionedWatchEvent)\n\t\t\tif err := AddObjectParams(ws, route, versionedListOptions); err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\taddParams(route, action.Params)\n\t\t\troutes = append(routes, route)\n\t\t// deprecated in 1.11\n\t\tcase \"WATCHLIST\": // Watch all resources of a kind.\n\t\t\tdoc := \"watch individual changes to a list of \" + kind\n\t\t\tif isSubresource {\n\t\t\t\tdoc = \"watch individual changes to a list of \" + subresource + \" of \" + kind\n\t\t\t}\n\t\t\tdoc += \". deprecated: use the 'watch' parameter with a list operation instead.\"\n\t\t\thandler := metrics.InstrumentRouteFunc(action.Verb, group, version, resource, subresource, requestScope, metrics.APIServerComponent, deprecated, removedRelease, restfulListResource(lister, watcher, reqScope, true, a.minRequestTimeout))\n\t\t\thandler = utilwarning.AddWarningsHandler(handler, warnings)\n\t\t\troute := ws.GET(action.Path).To(handler).\n\t\t\t\tDoc(doc).\n\t\t\t\tParam(ws.QueryParameter(\"pretty\", \"If 'true', then the output is pretty printed.\")).\n\t\t\t\tOperation(\"watch\"+namespaced+kind+strings.Title(subresource)+\"List\"+operationSuffix).\n\t\t\t\tProduces(allMediaTypes...).\n\t\t\t\tReturns(http.StatusOK, \"OK\", versionedWatchEvent).\n\t\t\t\tWrites(versionedWatchEvent)\n\t\t\tif err := AddObjectParams(ws, route, versionedListOptions); err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\taddParams(route, action.Params)\n\t\t\troutes = append(routes, route)\n\t\tcase \"CONNECT\":\n\t\t\tfor _, method := range connecter.ConnectMethods() {\n\t\t\t\tconnectProducedObject := storageMeta.ProducesObject(method)\n\t\t\t\tif connectProducedObject == nil {\n\t\t\t\t\tconnectProducedObject = \"string\"\n\t\t\t\t}\n\t\t\t\tdoc := \"connect \" + method + \" requests to \" + kind\n\t\t\t\tif isSubresource {\n\t\t\t\t\tdoc = \"connect \" + method + \" requests to \" + subresource + \" of \" + kind\n\t\t\t\t}\n\t\t\t\thandler := metrics.InstrumentRouteFunc(action.Verb, group, version, resource, subresource, requestScope, metrics.APIServerComponent, deprecated, removedRelease, restfulConnectResource(connecter, reqScope, admit, path, isSubresource))\n\t\t\t\thandler = utilwarning.AddWarningsHandler(handler, warnings)\n\t\t\t\troute := ws.Method(method).Path(action.Path).\n\t\t\t\t\tTo(handler).\n\t\t\t\t\tDoc(doc).\n\t\t\t\t\tOperation(\"connect\" + strings.Title(strings.ToLower(method)) + namespaced + kind + strings.Title(subresource) + operationSuffix).\n\t\t\t\t\tProduces(\"*/*\").\n\t\t\t\t\tConsumes(\"*/*\").\n\t\t\t\t\tWrites(connectProducedObject)\n\t\t\t\tif versionedConnectOptions != nil {\n\t\t\t\t\tif err := AddObjectParams(ws, route, versionedConnectOptions); err != nil {\n\t\t\t\t\t\treturn nil, nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\taddParams(route, action.Params)\n\t\t\t\troutes = append(routes, route)\n\n\t\t\t\t// transform ConnectMethods to kube verbs\n\t\t\t\tif kubeVerb, found := toDiscoveryKubeVerb[method]; found {\n\t\t\t\t\tif len(kubeVerb) != 0 {\n\t\t\t\t\t\tkubeVerbs[kubeVerb] = struct{}{}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\treturn nil, nil, fmt.Errorf(\"unrecognized action verb: %s\", action.Verb)\n\t\t}\n\t\tfor _, route := range routes {\n\t\t\troute.Metadata(ROUTE_META_GVK, metav1.GroupVersionKind{\n\t\t\t\tGroup: reqScope.Kind.Group,\n\t\t\t\tVersion: reqScope.Kind.Version,\n\t\t\t\tKind: reqScope.Kind.Kind,\n\t\t\t})\n\t\t\troute.Metadata(ROUTE_META_ACTION, strings.ToLower(action.Verb))\n\t\t\tws.Route(route)\n\t\t}\n\t\t// Note: update GetAuthorizerAttributes() when adding a custom handler.\n\t}\n\n\tapiResource.Verbs = make([]string, 0, len(kubeVerbs))\n\tfor kubeVerb := range kubeVerbs {\n\t\tapiResource.Verbs = append(apiResource.Verbs, kubeVerb)\n\t}\n\tsort.Strings(apiResource.Verbs)\n\n\tif shortNamesProvider, ok := storage.(rest.ShortNamesProvider); ok {\n\t\tapiResource.ShortNames = shortNamesProvider.ShortNames()\n\t}\n\tif categoriesProvider, ok := storage.(rest.CategoriesProvider); ok {\n\t\tapiResource.Categories = categoriesProvider.Categories()\n\t}\n\tif !isSubresource {\n\t\tsingularNameProvider, ok := storage.(rest.SingularNameProvider)\n\t\tif !ok {\n\t\t\treturn nil, nil, fmt.Errorf(\"resource %s must implement SingularNameProvider\", resource)\n\t\t}\n\t\tapiResource.SingularName = singularNameProvider.GetSingularName()\n\t}\n\n\tif gvkProvider, ok := storage.(rest.GroupVersionKindProvider); ok {\n\t\tgvk := gvkProvider.GroupVersionKind(a.group.GroupVersion)\n\t\tapiResource.Group = gvk.Group\n\t\tapiResource.Version = gvk.Version\n\t\tapiResource.Kind = gvk.Kind\n\t}\n\n\t// Record the existence of the GVR and the corresponding GVK\n\ta.group.EquivalentResourceRegistry.RegisterKindFor(reqScope.Resource, reqScope.Subresource, fqKindToRegister)\n\n\treturn \u0026apiResource, resourceInfo, nil\n}","line":{"from":276,"to":1100}} {"id":100017583,"name":"indirectArbitraryPointer","signature":"func indirectArbitraryPointer(ptrToObject interface{}) interface{}","file":"staging/src/k8s.io/apiserver/pkg/endpoints/installer.go","code":"// indirectArbitraryPointer returns *ptrToObject for an arbitrary pointer\nfunc indirectArbitraryPointer(ptrToObject interface{}) interface{} {\n\treturn reflect.Indirect(reflect.ValueOf(ptrToObject)).Interface()\n}","line":{"from":1102,"to":1105}} {"id":100017584,"name":"appendIf","signature":"func appendIf(actions []action, a action, shouldAppend bool) []action","file":"staging/src/k8s.io/apiserver/pkg/endpoints/installer.go","code":"func appendIf(actions []action, a action, shouldAppend bool) []action {\n\tif shouldAppend {\n\t\tactions = append(actions, a)\n\t}\n\treturn actions\n}","line":{"from":1107,"to":1112}} {"id":100017585,"name":"addParams","signature":"func addParams(route *restful.RouteBuilder, params []*restful.Parameter)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/installer.go","code":"func addParams(route *restful.RouteBuilder, params []*restful.Parameter) {\n\tfor _, param := range params {\n\t\troute.Param(param)\n\t}\n}","line":{"from":1114,"to":1118}} {"id":100017586,"name":"AddObjectParams","signature":"func AddObjectParams(ws *restful.WebService, route *restful.RouteBuilder, obj interface{}, excludedNames ...string) error","file":"staging/src/k8s.io/apiserver/pkg/endpoints/installer.go","code":"// AddObjectParams converts a runtime.Object into a set of go-restful Param() definitions on the route.\n// The object must be a pointer to a struct; only fields at the top level of the struct that are not\n// themselves interfaces or structs are used; only fields with a json tag that is non empty (the standard\n// Go JSON behavior for omitting a field) become query parameters. The name of the query parameter is\n// the JSON field name. If a description struct tag is set on the field, that description is used on the\n// query parameter. In essence, it converts a standard JSON top level object into a query param schema.\nfunc AddObjectParams(ws *restful.WebService, route *restful.RouteBuilder, obj interface{}, excludedNames ...string) error {\n\tsv, err := conversion.EnforcePtr(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\tst := sv.Type()\n\texcludedNameSet := sets.NewString(excludedNames...)\n\tswitch st.Kind() {\n\tcase reflect.Struct:\n\t\tfor i := 0; i \u003c st.NumField(); i++ {\n\t\t\tname := st.Field(i).Name\n\t\t\tsf, ok := st.FieldByName(name)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tswitch sf.Type.Kind() {\n\t\t\tcase reflect.Interface, reflect.Struct:\n\t\t\tcase reflect.Pointer:\n\t\t\t\t// TODO: This is a hack to let metav1.Time through. This needs to be fixed in a more generic way eventually. bug #36191\n\t\t\t\tif (sf.Type.Elem().Kind() == reflect.Interface || sf.Type.Elem().Kind() == reflect.Struct) \u0026\u0026 strings.TrimPrefix(sf.Type.String(), \"*\") != \"metav1.Time\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfallthrough\n\t\t\tdefault:\n\t\t\t\tjsonTag := sf.Tag.Get(\"json\")\n\t\t\t\tif len(jsonTag) == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tjsonName := strings.SplitN(jsonTag, \",\", 2)[0]\n\t\t\t\tif len(jsonName) == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif excludedNameSet.Has(jsonName) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tvar desc string\n\t\t\t\tif docable, ok := obj.(documentable); ok {\n\t\t\t\t\tdesc = docable.SwaggerDoc()[jsonName]\n\t\t\t\t}\n\t\t\t\troute.Param(ws.QueryParameter(jsonName, desc).DataType(typeToJSON(sf.Type.String())))\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":1120,"to":1170}} {"id":100017587,"name":"typeToJSON","signature":"func typeToJSON(typeName string) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/installer.go","code":"// TODO: this is incomplete, expand as needed.\n// Convert the name of a golang type to the name of a JSON type\nfunc typeToJSON(typeName string) string {\n\tswitch typeName {\n\tcase \"bool\", \"*bool\":\n\t\treturn \"boolean\"\n\tcase \"uint8\", \"*uint8\", \"int\", \"*int\", \"int32\", \"*int32\", \"int64\", \"*int64\", \"uint32\", \"*uint32\", \"uint64\", \"*uint64\":\n\t\treturn \"integer\"\n\tcase \"float64\", \"*float64\", \"float32\", \"*float32\":\n\t\treturn \"number\"\n\tcase \"metav1.Time\", \"*metav1.Time\":\n\t\treturn \"string\"\n\tcase \"byte\", \"*byte\":\n\t\treturn \"string\"\n\tcase \"v1.DeletionPropagation\", \"*v1.DeletionPropagation\":\n\t\treturn \"string\"\n\tcase \"v1.ResourceVersionMatch\", \"*v1.ResourceVersionMatch\":\n\t\treturn \"string\"\n\tcase \"v1.IncludeObjectPolicy\", \"*v1.IncludeObjectPolicy\":\n\t\treturn \"string\"\n\n\t// TODO: Fix these when go-restful supports a way to specify an array query param:\n\t// https://github.com/emicklei/go-restful/issues/225\n\tcase \"[]string\", \"[]*string\":\n\t\treturn \"string\"\n\tcase \"[]int32\", \"[]*int32\":\n\t\treturn \"integer\"\n\n\tdefault:\n\t\treturn typeName\n\t}\n}","line":{"from":1172,"to":1203}} {"id":100017588,"name":"ProducesMIMETypes","signature":"func (defaultStorageMetadata) ProducesMIMETypes(verb string) []string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/installer.go","code":"func (defaultStorageMetadata) ProducesMIMETypes(verb string) []string {\n\treturn nil\n}","line":{"from":1211,"to":1213}} {"id":100017589,"name":"ProducesObject","signature":"func (defaultStorageMetadata) ProducesObject(verb string) interface{}","file":"staging/src/k8s.io/apiserver/pkg/endpoints/installer.go","code":"func (defaultStorageMetadata) ProducesObject(verb string) interface{} {\n\treturn nil\n}","line":{"from":1215,"to":1217}} {"id":100017590,"name":"splitSubresource","signature":"func splitSubresource(path string) (string, string, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/installer.go","code":"// splitSubresource checks if the given storage path is the path of a subresource and returns\n// the resource and subresource components.\nfunc splitSubresource(path string) (string, string, error) {\n\tvar resource, subresource string\n\tswitch parts := strings.Split(path, \"/\"); len(parts) {\n\tcase 2:\n\t\tresource, subresource = parts[0], parts[1]\n\tcase 1:\n\t\tresource = parts[0]\n\tdefault:\n\t\t// TODO: support deeper paths\n\t\treturn \"\", \"\", fmt.Errorf(\"api_installer allows only one or two segment paths (resource or resource/subresource)\")\n\t}\n\treturn resource, subresource, nil\n}","line":{"from":1219,"to":1233}} {"id":100017591,"name":"GetArticleForNoun","signature":"func GetArticleForNoun(noun string, padding string) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/installer.go","code":"// GetArticleForNoun returns the article needed for the given noun.\nfunc GetArticleForNoun(noun string, padding string) string {\n\tif !strings.HasSuffix(noun, \"ss\") \u0026\u0026 strings.HasSuffix(noun, \"s\") {\n\t\t// Plurals don't have an article.\n\t\t// Don't catch words like class\n\t\treturn fmt.Sprintf(\"%v\", padding)\n\t}\n\n\tarticle := \"a\"\n\tif isVowel(rune(noun[0])) {\n\t\tarticle = \"an\"\n\t}\n\n\treturn fmt.Sprintf(\"%s%s%s\", padding, article, padding)\n}","line":{"from":1235,"to":1249}} {"id":100017592,"name":"isVowel","signature":"func isVowel(c rune) bool","file":"staging/src/k8s.io/apiserver/pkg/endpoints/installer.go","code":"// isVowel returns true if the rune is a vowel (case insensitive).\nfunc isVowel(c rune) bool {\n\tvowels := []rune{'a', 'e', 'i', 'o', 'u'}\n\tfor _, value := range vowels {\n\t\tif value == unicode.ToLower(c) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":1251,"to":1260}} {"id":100017593,"name":"restfulListResource","signature":"func restfulListResource(r rest.Lister, rw rest.Watcher, scope handlers.RequestScope, forceWatch bool, minRequestTimeout time.Duration) restful.RouteFunction","file":"staging/src/k8s.io/apiserver/pkg/endpoints/installer.go","code":"func restfulListResource(r rest.Lister, rw rest.Watcher, scope handlers.RequestScope, forceWatch bool, minRequestTimeout time.Duration) restful.RouteFunction {\n\treturn func(req *restful.Request, res *restful.Response) {\n\t\thandlers.ListResource(r, rw, \u0026scope, forceWatch, minRequestTimeout)(res.ResponseWriter, req.Request)\n\t}\n}","line":{"from":1262,"to":1266}} {"id":100017594,"name":"restfulCreateNamedResource","signature":"func restfulCreateNamedResource(r rest.NamedCreater, scope handlers.RequestScope, admit admission.Interface) restful.RouteFunction","file":"staging/src/k8s.io/apiserver/pkg/endpoints/installer.go","code":"func restfulCreateNamedResource(r rest.NamedCreater, scope handlers.RequestScope, admit admission.Interface) restful.RouteFunction {\n\treturn func(req *restful.Request, res *restful.Response) {\n\t\thandlers.CreateNamedResource(r, \u0026scope, admit)(res.ResponseWriter, req.Request)\n\t}\n}","line":{"from":1268,"to":1272}} {"id":100017595,"name":"restfulCreateResource","signature":"func restfulCreateResource(r rest.Creater, scope handlers.RequestScope, admit admission.Interface) restful.RouteFunction","file":"staging/src/k8s.io/apiserver/pkg/endpoints/installer.go","code":"func restfulCreateResource(r rest.Creater, scope handlers.RequestScope, admit admission.Interface) restful.RouteFunction {\n\treturn func(req *restful.Request, res *restful.Response) {\n\t\thandlers.CreateResource(r, \u0026scope, admit)(res.ResponseWriter, req.Request)\n\t}\n}","line":{"from":1274,"to":1278}} {"id":100017596,"name":"restfulDeleteResource","signature":"func restfulDeleteResource(r rest.GracefulDeleter, allowsOptions bool, scope handlers.RequestScope, admit admission.Interface) restful.RouteFunction","file":"staging/src/k8s.io/apiserver/pkg/endpoints/installer.go","code":"func restfulDeleteResource(r rest.GracefulDeleter, allowsOptions bool, scope handlers.RequestScope, admit admission.Interface) restful.RouteFunction {\n\treturn func(req *restful.Request, res *restful.Response) {\n\t\thandlers.DeleteResource(r, allowsOptions, \u0026scope, admit)(res.ResponseWriter, req.Request)\n\t}\n}","line":{"from":1280,"to":1284}} {"id":100017597,"name":"restfulDeleteCollection","signature":"func restfulDeleteCollection(r rest.CollectionDeleter, checkBody bool, scope handlers.RequestScope, admit admission.Interface) restful.RouteFunction","file":"staging/src/k8s.io/apiserver/pkg/endpoints/installer.go","code":"func restfulDeleteCollection(r rest.CollectionDeleter, checkBody bool, scope handlers.RequestScope, admit admission.Interface) restful.RouteFunction {\n\treturn func(req *restful.Request, res *restful.Response) {\n\t\thandlers.DeleteCollection(r, checkBody, \u0026scope, admit)(res.ResponseWriter, req.Request)\n\t}\n}","line":{"from":1286,"to":1290}} {"id":100017598,"name":"restfulUpdateResource","signature":"func restfulUpdateResource(r rest.Updater, scope handlers.RequestScope, admit admission.Interface) restful.RouteFunction","file":"staging/src/k8s.io/apiserver/pkg/endpoints/installer.go","code":"func restfulUpdateResource(r rest.Updater, scope handlers.RequestScope, admit admission.Interface) restful.RouteFunction {\n\treturn func(req *restful.Request, res *restful.Response) {\n\t\thandlers.UpdateResource(r, \u0026scope, admit)(res.ResponseWriter, req.Request)\n\t}\n}","line":{"from":1292,"to":1296}} {"id":100017599,"name":"restfulPatchResource","signature":"func restfulPatchResource(r rest.Patcher, scope handlers.RequestScope, admit admission.Interface, supportedTypes []string) restful.RouteFunction","file":"staging/src/k8s.io/apiserver/pkg/endpoints/installer.go","code":"func restfulPatchResource(r rest.Patcher, scope handlers.RequestScope, admit admission.Interface, supportedTypes []string) restful.RouteFunction {\n\treturn func(req *restful.Request, res *restful.Response) {\n\t\thandlers.PatchResource(r, \u0026scope, admit, supportedTypes)(res.ResponseWriter, req.Request)\n\t}\n}","line":{"from":1298,"to":1302}} {"id":100017600,"name":"restfulGetResource","signature":"func restfulGetResource(r rest.Getter, scope handlers.RequestScope) restful.RouteFunction","file":"staging/src/k8s.io/apiserver/pkg/endpoints/installer.go","code":"func restfulGetResource(r rest.Getter, scope handlers.RequestScope) restful.RouteFunction {\n\treturn func(req *restful.Request, res *restful.Response) {\n\t\thandlers.GetResource(r, \u0026scope)(res.ResponseWriter, req.Request)\n\t}\n}","line":{"from":1304,"to":1308}} {"id":100017601,"name":"restfulGetResourceWithOptions","signature":"func restfulGetResourceWithOptions(r rest.GetterWithOptions, scope handlers.RequestScope, isSubresource bool) restful.RouteFunction","file":"staging/src/k8s.io/apiserver/pkg/endpoints/installer.go","code":"func restfulGetResourceWithOptions(r rest.GetterWithOptions, scope handlers.RequestScope, isSubresource bool) restful.RouteFunction {\n\treturn func(req *restful.Request, res *restful.Response) {\n\t\thandlers.GetResourceWithOptions(r, \u0026scope, isSubresource)(res.ResponseWriter, req.Request)\n\t}\n}","line":{"from":1310,"to":1314}} {"id":100017602,"name":"restfulConnectResource","signature":"func restfulConnectResource(connecter rest.Connecter, scope handlers.RequestScope, admit admission.Interface, restPath string, isSubresource bool) restful.RouteFunction","file":"staging/src/k8s.io/apiserver/pkg/endpoints/installer.go","code":"func restfulConnectResource(connecter rest.Connecter, scope handlers.RequestScope, admit admission.Interface, restPath string, isSubresource bool) restful.RouteFunction {\n\treturn func(req *restful.Request, res *restful.Response) {\n\t\thandlers.ConnectResource(connecter, \u0026scope, admit, restPath, isSubresource)(res.ResponseWriter, req.Request)\n\t}\n}","line":{"from":1316,"to":1320}} {"id":100017603,"name":"Register","signature":"func Register()","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"// Register all metrics.\nfunc Register() {\n\tregisterMetrics.Do(func() {\n\t\tfor _, metric := range metrics {\n\t\t\tlegacyregistry.MustRegister(metric)\n\t\t}\n\t})\n}","line":{"from":386,"to":393}} {"id":100017604,"name":"Reset","signature":"func Reset()","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"// Reset all metrics.\nfunc Reset() {\n\tfor _, metric := range metrics {\n\t\tmetric.Reset()\n\t}\n}","line":{"from":395,"to":400}} {"id":100017605,"name":"UpdateInflightRequestMetrics","signature":"func UpdateInflightRequestMetrics(phase string, nonmutating, mutating int)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"// UpdateInflightRequestMetrics reports concurrency metrics classified by\n// mutating vs Readonly.\nfunc UpdateInflightRequestMetrics(phase string, nonmutating, mutating int) {\n\tfor _, kc := range []struct {\n\t\tkind string\n\t\tcount int\n\t}{{ReadOnlyKind, nonmutating}, {MutatingKind, mutating}} {\n\t\tif phase == ExecutingPhase {\n\t\t\tcurrentInflightRequests.WithLabelValues(kc.kind).Set(float64(kc.count))\n\t\t} else {\n\t\t\tcurrentInqueueRequests.WithLabelValues(kc.kind).Set(float64(kc.count))\n\t\t}\n\t}\n}","line":{"from":402,"to":415}} {"id":100017606,"name":"RecordFilterLatency","signature":"func RecordFilterLatency(ctx context.Context, name string, elapsed time.Duration)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"func RecordFilterLatency(ctx context.Context, name string, elapsed time.Duration) {\n\trequestFilterDuration.WithContext(ctx).WithLabelValues(name).Observe(elapsed.Seconds())\n}","line":{"from":417,"to":419}} {"id":100017607,"name":"RecordTimestampComparisonLatency","signature":"func RecordTimestampComparisonLatency(codePath string, elapsed time.Duration)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"func RecordTimestampComparisonLatency(codePath string, elapsed time.Duration) {\n\trequestTimestampComparisonDuration.WithLabelValues(codePath).Observe(elapsed.Seconds())\n}","line":{"from":421,"to":423}} {"id":100017608,"name":"RecordRequestPostTimeout","signature":"func RecordRequestPostTimeout(source string, status string)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"func RecordRequestPostTimeout(source string, status string) {\n\trequestPostTimeoutTotal.WithLabelValues(source, status).Inc()\n}","line":{"from":425,"to":427}} {"id":100017609,"name":"RecordRequestAbort","signature":"func RecordRequestAbort(req *http.Request, requestInfo *request.RequestInfo)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"// RecordRequestAbort records that the request was aborted possibly due to a timeout.\nfunc RecordRequestAbort(req *http.Request, requestInfo *request.RequestInfo) {\n\tif requestInfo == nil {\n\t\trequestInfo = \u0026request.RequestInfo{Verb: req.Method, Path: req.URL.Path}\n\t}\n\n\tscope := CleanScope(requestInfo)\n\treportedVerb := cleanVerb(CanonicalVerb(strings.ToUpper(req.Method), scope), \"\", req, requestInfo)\n\tresource := requestInfo.Resource\n\tsubresource := requestInfo.Subresource\n\tgroup := requestInfo.APIGroup\n\tversion := requestInfo.APIVersion\n\n\trequestAbortsTotal.WithContext(req.Context()).WithLabelValues(reportedVerb, group, version, resource, subresource, scope).Inc()\n}","line":{"from":429,"to":443}} {"id":100017610,"name":"RecordDroppedRequest","signature":"func RecordDroppedRequest(req *http.Request, requestInfo *request.RequestInfo, component string, isMutatingRequest bool)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"// RecordDroppedRequest records that the request was rejected via http.TooManyRequests.\nfunc RecordDroppedRequest(req *http.Request, requestInfo *request.RequestInfo, component string, isMutatingRequest bool) {\n\tif requestInfo == nil {\n\t\trequestInfo = \u0026request.RequestInfo{Verb: req.Method, Path: req.URL.Path}\n\t}\n\tscope := CleanScope(requestInfo)\n\tdryRun := cleanDryRun(req.URL)\n\n\t// We don't use verb from \u003crequestInfo\u003e, as this may be propagated from\n\t// InstrumentRouteFunc which is registered in installer.go with predefined\n\t// list of verbs (different than those translated to RequestInfo).\n\t// However, we need to tweak it e.g. to differentiate GET from LIST.\n\treportedVerb := cleanVerb(CanonicalVerb(strings.ToUpper(req.Method), scope), \"\", req, requestInfo)\n\n\tif requestInfo.IsResourceRequest {\n\t\trequestCounter.WithContext(req.Context()).WithLabelValues(reportedVerb, dryRun, requestInfo.APIGroup, requestInfo.APIVersion, requestInfo.Resource, requestInfo.Subresource, scope, component, codeToString(http.StatusTooManyRequests)).Inc()\n\t} else {\n\t\trequestCounter.WithContext(req.Context()).WithLabelValues(reportedVerb, dryRun, \"\", \"\", \"\", requestInfo.Subresource, scope, component, codeToString(http.StatusTooManyRequests)).Inc()\n\t}\n}","line":{"from":445,"to":464}} {"id":100017611,"name":"RecordRequestTermination","signature":"func RecordRequestTermination(req *http.Request, requestInfo *request.RequestInfo, component string, code int)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"// RecordRequestTermination records that the request was terminated early as part of a resource\n// preservation or apiserver self-defense mechanism (e.g. timeouts, maxinflight throttling,\n// proxyHandler errors). RecordRequestTermination should only be called zero or one times\n// per request.\nfunc RecordRequestTermination(req *http.Request, requestInfo *request.RequestInfo, component string, code int) {\n\tif requestInfo == nil {\n\t\trequestInfo = \u0026request.RequestInfo{Verb: req.Method, Path: req.URL.Path}\n\t}\n\tscope := CleanScope(requestInfo)\n\n\t// We don't use verb from \u003crequestInfo\u003e, as this may be propagated from\n\t// InstrumentRouteFunc which is registered in installer.go with predefined\n\t// list of verbs (different than those translated to RequestInfo).\n\t// However, we need to tweak it e.g. to differentiate GET from LIST.\n\treportedVerb := cleanVerb(CanonicalVerb(strings.ToUpper(req.Method), scope), \"\", req, requestInfo)\n\n\tif requestInfo.IsResourceRequest {\n\t\trequestTerminationsTotal.WithContext(req.Context()).WithLabelValues(reportedVerb, requestInfo.APIGroup, requestInfo.APIVersion, requestInfo.Resource, requestInfo.Subresource, scope, component, codeToString(code)).Inc()\n\t} else {\n\t\trequestTerminationsTotal.WithContext(req.Context()).WithLabelValues(reportedVerb, \"\", \"\", \"\", requestInfo.Path, scope, component, codeToString(code)).Inc()\n\t}\n}","line":{"from":466,"to":487}} {"id":100017612,"name":"RecordLongRunning","signature":"func RecordLongRunning(req *http.Request, requestInfo *request.RequestInfo, component string, fn func())","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"// RecordLongRunning tracks the execution of a long running request against the API server. It provides an accurate count\n// of the total number of open long running requests. requestInfo may be nil if the caller is not in the normal request flow.\nfunc RecordLongRunning(req *http.Request, requestInfo *request.RequestInfo, component string, fn func()) {\n\tif requestInfo == nil {\n\t\trequestInfo = \u0026request.RequestInfo{Verb: req.Method, Path: req.URL.Path}\n\t}\n\tvar g compbasemetrics.GaugeMetric\n\tscope := CleanScope(requestInfo)\n\n\t// We don't use verb from \u003crequestInfo\u003e, as this may be propagated from\n\t// InstrumentRouteFunc which is registered in installer.go with predefined\n\t// list of verbs (different than those translated to RequestInfo).\n\t// However, we need to tweak it e.g. to differentiate GET from LIST.\n\treportedVerb := cleanVerb(CanonicalVerb(strings.ToUpper(req.Method), scope), \"\", req, requestInfo)\n\n\tif requestInfo.IsResourceRequest {\n\t\tg = longRunningRequestsGauge.WithContext(req.Context()).WithLabelValues(reportedVerb, requestInfo.APIGroup, requestInfo.APIVersion, requestInfo.Resource, requestInfo.Subresource, scope, component)\n\t} else {\n\t\tg = longRunningRequestsGauge.WithContext(req.Context()).WithLabelValues(reportedVerb, \"\", \"\", \"\", requestInfo.Path, scope, component)\n\t}\n\tg.Inc()\n\tdefer g.Dec()\n\tfn()\n}","line":{"from":489,"to":512}} {"id":100017613,"name":"MonitorRequest","signature":"func MonitorRequest(req *http.Request, verb, group, version, resource, subresource, scope, component string, deprecated bool, removedRelease string, httpCode, respSize int, elapsed time.Duration)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"// MonitorRequest handles standard transformations for client and the reported verb and then invokes Monitor to record\n// a request. verb must be uppercase to be backwards compatible with existing monitoring tooling.\nfunc MonitorRequest(req *http.Request, verb, group, version, resource, subresource, scope, component string, deprecated bool, removedRelease string, httpCode, respSize int, elapsed time.Duration) {\n\trequestInfo, ok := request.RequestInfoFrom(req.Context())\n\tif !ok || requestInfo == nil {\n\t\trequestInfo = \u0026request.RequestInfo{Verb: req.Method, Path: req.URL.Path}\n\t}\n\t// We don't use verb from \u003crequestInfo\u003e, as this may be propagated from\n\t// InstrumentRouteFunc which is registered in installer.go with predefined\n\t// list of verbs (different than those translated to RequestInfo).\n\t// However, we need to tweak it e.g. to differentiate GET from LIST.\n\treportedVerb := cleanVerb(CanonicalVerb(strings.ToUpper(req.Method), scope), verb, req, requestInfo)\n\n\tdryRun := cleanDryRun(req.URL)\n\telapsedSeconds := elapsed.Seconds()\n\trequestCounter.WithContext(req.Context()).WithLabelValues(reportedVerb, dryRun, group, version, resource, subresource, scope, component, codeToString(httpCode)).Inc()\n\t// MonitorRequest happens after authentication, so we can trust the username given by the request\n\tinfo, ok := request.UserFrom(req.Context())\n\tif ok \u0026\u0026 info.GetName() == user.APIServerUser {\n\t\tapiSelfRequestCounter.WithContext(req.Context()).WithLabelValues(reportedVerb, resource, subresource).Inc()\n\t}\n\tif deprecated {\n\t\tdeprecatedRequestGauge.WithContext(req.Context()).WithLabelValues(group, version, resource, subresource, removedRelease).Set(1)\n\t\taudit.AddAuditAnnotation(req.Context(), deprecatedAnnotationKey, \"true\")\n\t\tif len(removedRelease) \u003e 0 {\n\t\t\taudit.AddAuditAnnotation(req.Context(), removedReleaseAnnotationKey, removedRelease)\n\t\t}\n\t}\n\trequestLatencies.WithContext(req.Context()).WithLabelValues(reportedVerb, dryRun, group, version, resource, subresource, scope, component).Observe(elapsedSeconds)\n\tfieldValidation := cleanFieldValidation(req.URL)\n\tfieldValidationRequestLatencies.WithContext(req.Context()).WithLabelValues(fieldValidation)\n\n\tif wd, ok := request.LatencyTrackersFrom(req.Context()); ok {\n\t\tsliLatency := elapsedSeconds - (wd.MutatingWebhookTracker.GetLatency() + wd.ValidatingWebhookTracker.GetLatency() + wd.APFQueueWaitTracker.GetLatency()).Seconds()\n\t\trequestSloLatencies.WithContext(req.Context()).WithLabelValues(reportedVerb, group, version, resource, subresource, scope, component).Observe(sliLatency)\n\t\trequestSliLatencies.WithContext(req.Context()).WithLabelValues(reportedVerb, group, version, resource, subresource, scope, component).Observe(sliLatency)\n\t}\n\t// We are only interested in response sizes of read requests.\n\tif verb == \"GET\" || verb == \"LIST\" {\n\t\tresponseSizes.WithContext(req.Context()).WithLabelValues(reportedVerb, group, version, resource, subresource, scope, component).Observe(float64(respSize))\n\t}\n}","line":{"from":514,"to":555}} {"id":100017614,"name":"InstrumentRouteFunc","signature":"func InstrumentRouteFunc(verb, group, version, resource, subresource, scope, component string, deprecated bool, removedRelease string, routeFunc restful.RouteFunction) restful.RouteFunction","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"// InstrumentRouteFunc works like Prometheus' InstrumentHandlerFunc but wraps\n// the go-restful RouteFunction instead of a HandlerFunc plus some Kubernetes endpoint specific information.\nfunc InstrumentRouteFunc(verb, group, version, resource, subresource, scope, component string, deprecated bool, removedRelease string, routeFunc restful.RouteFunction) restful.RouteFunction {\n\treturn restful.RouteFunction(func(req *restful.Request, response *restful.Response) {\n\t\trequestReceivedTimestamp, ok := request.ReceivedTimestampFrom(req.Request.Context())\n\t\tif !ok {\n\t\t\trequestReceivedTimestamp = time.Now()\n\t\t}\n\n\t\tdelegate := \u0026ResponseWriterDelegator{ResponseWriter: response.ResponseWriter}\n\n\t\trw := responsewriter.WrapForHTTP1Or2(delegate)\n\t\tresponse.ResponseWriter = rw\n\n\t\trouteFunc(req, response)\n\n\t\tMonitorRequest(req.Request, verb, group, version, resource, subresource, scope, component, deprecated, removedRelease, delegate.Status(), delegate.ContentLength(), time.Since(requestReceivedTimestamp))\n\t})\n}","line":{"from":557,"to":575}} {"id":100017615,"name":"InstrumentHandlerFunc","signature":"func InstrumentHandlerFunc(verb, group, version, resource, subresource, scope, component string, deprecated bool, removedRelease string, handler http.HandlerFunc) http.HandlerFunc","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"// InstrumentHandlerFunc works like Prometheus' InstrumentHandlerFunc but adds some Kubernetes endpoint specific information.\nfunc InstrumentHandlerFunc(verb, group, version, resource, subresource, scope, component string, deprecated bool, removedRelease string, handler http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, req *http.Request) {\n\t\trequestReceivedTimestamp, ok := request.ReceivedTimestampFrom(req.Context())\n\t\tif !ok {\n\t\t\trequestReceivedTimestamp = time.Now()\n\t\t}\n\n\t\tdelegate := \u0026ResponseWriterDelegator{ResponseWriter: w}\n\t\tw = responsewriter.WrapForHTTP1Or2(delegate)\n\n\t\thandler(w, req)\n\n\t\tMonitorRequest(req, verb, group, version, resource, subresource, scope, component, deprecated, removedRelease, delegate.Status(), delegate.ContentLength(), time.Since(requestReceivedTimestamp))\n\t}\n}","line":{"from":577,"to":592}} {"id":100017616,"name":"NormalizedVerb","signature":"func NormalizedVerb(req *http.Request) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"// NormalizedVerb returns normalized verb\nfunc NormalizedVerb(req *http.Request) string {\n\tverb := req.Method\n\trequestInfo, ok := request.RequestInfoFrom(req.Context())\n\tif ok {\n\t\t// If we can find a requestInfo, we can get a scope, and then\n\t\t// we can convert GETs to LISTs when needed.\n\t\tscope := CleanScope(requestInfo)\n\t\tverb = CanonicalVerb(strings.ToUpper(verb), scope)\n\t}\n\n\t// mark APPLY requests, WATCH requests and CONNECT requests correctly.\n\treturn CleanVerb(verb, req, requestInfo)\n}","line":{"from":594,"to":607}} {"id":100017617,"name":"CleanScope","signature":"func CleanScope(requestInfo *request.RequestInfo) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"// CleanScope returns the scope of the request.\nfunc CleanScope(requestInfo *request.RequestInfo) string {\n\tif requestInfo.Name != \"\" || requestInfo.Verb == \"create\" {\n\t\treturn \"resource\"\n\t}\n\tif requestInfo.Namespace != \"\" {\n\t\treturn \"namespace\"\n\t}\n\tif requestInfo.IsResourceRequest {\n\t\treturn \"cluster\"\n\t}\n\t// this is the empty scope\n\treturn \"\"\n}","line":{"from":609,"to":622}} {"id":100017618,"name":"CanonicalVerb","signature":"func CanonicalVerb(verb string, scope string) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"// CanonicalVerb distinguishes LISTs from GETs (and HEADs). It assumes verb is\n// UPPERCASE.\nfunc CanonicalVerb(verb string, scope string) string {\n\tswitch verb {\n\tcase \"GET\", \"HEAD\":\n\t\tif scope != \"resource\" \u0026\u0026 scope != \"\" {\n\t\t\treturn \"LIST\"\n\t\t}\n\t\treturn \"GET\"\n\tdefault:\n\t\treturn verb\n\t}\n}","line":{"from":624,"to":636}} {"id":100017619,"name":"CleanVerb","signature":"func CleanVerb(verb string, request *http.Request, requestInfo *request.RequestInfo) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"// CleanVerb returns a normalized verb, so that it is easy to tell WATCH from\n// LIST, APPLY from PATCH and CONNECT from others.\nfunc CleanVerb(verb string, request *http.Request, requestInfo *request.RequestInfo) string {\n\treportedVerb := verb\n\tif suggestedVerb := getVerbIfWatch(request); suggestedVerb == \"WATCH\" {\n\t\treportedVerb = \"WATCH\"\n\t}\n\t// normalize the legacy WATCHLIST to WATCH to ensure users aren't surprised by metrics\n\tif verb == \"WATCHLIST\" {\n\t\treportedVerb = \"WATCH\"\n\t}\n\tif verb == \"PATCH\" \u0026\u0026 request.Header.Get(\"Content-Type\") == string(types.ApplyPatchType) {\n\t\treportedVerb = \"APPLY\"\n\t}\n\tif requestInfo != nil \u0026\u0026 requestInfo.IsResourceRequest \u0026\u0026 len(requestInfo.Subresource) \u003e 0 \u0026\u0026 validConnectRequests.Has(requestInfo.Subresource) {\n\t\treportedVerb = \"CONNECT\"\n\t}\n\treturn reportedVerb\n}","line":{"from":638,"to":656}} {"id":100017620,"name":"cleanVerb","signature":"func cleanVerb(verb, suggestedVerb string, request *http.Request, requestInfo *request.RequestInfo) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"// cleanVerb additionally ensures that unknown verbs don't clog up the metrics.\nfunc cleanVerb(verb, suggestedVerb string, request *http.Request, requestInfo *request.RequestInfo) string {\n\t// CanonicalVerb (being an input for this function) doesn't handle correctly the\n\t// deprecated path pattern for watch of:\n\t// GET /api/{version}/watch/{resource}\n\t// We correct it manually based on the pass verb from the installer.\n\tif suggestedVerb == \"WATCH\" || suggestedVerb == \"WATCHLIST\" {\n\t\treturn \"WATCH\"\n\t}\n\treportedVerb := CleanVerb(verb, request, requestInfo)\n\tif validRequestMethods.Has(reportedVerb) {\n\t\treturn reportedVerb\n\t}\n\treturn OtherRequestMethod\n}","line":{"from":658,"to":672}} {"id":100017621,"name":"getVerbIfWatch","signature":"func getVerbIfWatch(req *http.Request) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"// getVerbIfWatch additionally ensures that GET or List would be transformed to WATCH\nfunc getVerbIfWatch(req *http.Request) string {\n\tif strings.ToUpper(req.Method) == \"GET\" || strings.ToUpper(req.Method) == \"LIST\" {\n\t\t// see apimachinery/pkg/runtime/conversion.go Convert_Slice_string_To_bool\n\t\tif values := req.URL.Query()[\"watch\"]; len(values) \u003e 0 {\n\t\t\tif value := strings.ToLower(values[0]); value != \"0\" \u0026\u0026 value != \"false\" {\n\t\t\t\treturn \"WATCH\"\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\"\n}","line":{"from":674,"to":685}} {"id":100017622,"name":"cleanDryRun","signature":"func cleanDryRun(u *url.URL) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"func cleanDryRun(u *url.URL) string {\n\t// avoid allocating when we don't see dryRun in the query\n\tif !strings.Contains(u.RawQuery, \"dryRun\") {\n\t\treturn \"\"\n\t}\n\tdryRun := u.Query()[\"dryRun\"]\n\tif errs := validation.ValidateDryRun(nil, dryRun); len(errs) \u003e 0 {\n\t\treturn \"invalid\"\n\t}\n\t// Since dryRun could be valid with any arbitrarily long length\n\t// we have to dedup and sort the elements before joining them together\n\t// TODO: this is a fairly large allocation for what it does, consider\n\t// a sort and dedup in a single pass\n\treturn strings.Join(utilsets.NewString(dryRun...).List(), \",\")\n}","line":{"from":687,"to":701}} {"id":100017623,"name":"cleanFieldValidation","signature":"func cleanFieldValidation(u *url.URL) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"func cleanFieldValidation(u *url.URL) string {\n\t// avoid allocating when we don't see dryRun in the query\n\tif !strings.Contains(u.RawQuery, \"fieldValidation\") {\n\t\treturn \"\"\n\t}\n\tfieldValidation := u.Query()[\"fieldValidation\"]\n\tif len(fieldValidation) != 1 {\n\t\treturn \"invalid\"\n\t}\n\tif errs := validation.ValidateFieldValidation(nil, fieldValidation[0]); len(errs) \u003e 0 {\n\t\treturn \"invalid\"\n\t}\n\treturn fieldValidation[0]\n}","line":{"from":703,"to":716}} {"id":100017624,"name":"Unwrap","signature":"func (r *ResponseWriterDelegator) Unwrap() http.ResponseWriter","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"func (r *ResponseWriterDelegator) Unwrap() http.ResponseWriter {\n\treturn r.ResponseWriter\n}","line":{"from":730,"to":732}} {"id":100017625,"name":"WriteHeader","signature":"func (r *ResponseWriterDelegator) WriteHeader(code int)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"func (r *ResponseWriterDelegator) WriteHeader(code int) {\n\tr.status = code\n\tr.wroteHeader = true\n\tr.ResponseWriter.WriteHeader(code)\n}","line":{"from":734,"to":738}} {"id":100017626,"name":"Write","signature":"func (r *ResponseWriterDelegator) Write(b []byte) (int, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"func (r *ResponseWriterDelegator) Write(b []byte) (int, error) {\n\tif !r.wroteHeader {\n\t\tr.WriteHeader(http.StatusOK)\n\t}\n\tn, err := r.ResponseWriter.Write(b)\n\tr.written += int64(n)\n\treturn n, err\n}","line":{"from":740,"to":747}} {"id":100017627,"name":"Status","signature":"func (r *ResponseWriterDelegator) Status() int","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"func (r *ResponseWriterDelegator) Status() int {\n\treturn r.status\n}","line":{"from":749,"to":751}} {"id":100017628,"name":"ContentLength","signature":"func (r *ResponseWriterDelegator) ContentLength() int","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"func (r *ResponseWriterDelegator) ContentLength() int {\n\treturn int(r.written)\n}","line":{"from":753,"to":755}} {"id":100017629,"name":"codeToString","signature":"func codeToString(s int) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go","code":"// Small optimization over Itoa\nfunc codeToString(s int) string {\n\tswitch s {\n\tcase 100:\n\t\treturn \"100\"\n\tcase 101:\n\t\treturn \"101\"\n\n\tcase 200:\n\t\treturn \"200\"\n\tcase 201:\n\t\treturn \"201\"\n\tcase 202:\n\t\treturn \"202\"\n\tcase 203:\n\t\treturn \"203\"\n\tcase 204:\n\t\treturn \"204\"\n\tcase 205:\n\t\treturn \"205\"\n\tcase 206:\n\t\treturn \"206\"\n\n\tcase 300:\n\t\treturn \"300\"\n\tcase 301:\n\t\treturn \"301\"\n\tcase 302:\n\t\treturn \"302\"\n\tcase 304:\n\t\treturn \"304\"\n\tcase 305:\n\t\treturn \"305\"\n\tcase 307:\n\t\treturn \"307\"\n\n\tcase 400:\n\t\treturn \"400\"\n\tcase 401:\n\t\treturn \"401\"\n\tcase 402:\n\t\treturn \"402\"\n\tcase 403:\n\t\treturn \"403\"\n\tcase 404:\n\t\treturn \"404\"\n\tcase 405:\n\t\treturn \"405\"\n\tcase 406:\n\t\treturn \"406\"\n\tcase 407:\n\t\treturn \"407\"\n\tcase 408:\n\t\treturn \"408\"\n\tcase 409:\n\t\treturn \"409\"\n\tcase 410:\n\t\treturn \"410\"\n\tcase 411:\n\t\treturn \"411\"\n\tcase 412:\n\t\treturn \"412\"\n\tcase 413:\n\t\treturn \"413\"\n\tcase 414:\n\t\treturn \"414\"\n\tcase 415:\n\t\treturn \"415\"\n\tcase 416:\n\t\treturn \"416\"\n\tcase 417:\n\t\treturn \"417\"\n\tcase 418:\n\t\treturn \"418\"\n\n\tcase 500:\n\t\treturn \"500\"\n\tcase 501:\n\t\treturn \"501\"\n\tcase 502:\n\t\treturn \"502\"\n\tcase 503:\n\t\treturn \"503\"\n\tcase 504:\n\t\treturn \"504\"\n\tcase 505:\n\t\treturn \"505\"\n\n\tcase 428:\n\t\treturn \"428\"\n\tcase 429:\n\t\treturn \"429\"\n\tcase 431:\n\t\treturn \"431\"\n\tcase 511:\n\t\treturn \"511\"\n\n\tdefault:\n\t\treturn strconv.Itoa(s)\n\t}\n}","line":{"from":757,"to":857}} {"id":100017630,"name":"ToValidOperationID","signature":"func ToValidOperationID(s string, capitalizeFirstLetter bool) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/openapi/openapi.go","code":"// ToValidOperationID makes an string a valid op ID (e.g. removing punctuations and whitespaces and make it camel case)\nfunc ToValidOperationID(s string, capitalizeFirstLetter bool) string {\n\tvar buffer bytes.Buffer\n\tcapitalize := capitalizeFirstLetter\n\tfor i, r := range s {\n\t\tif unicode.IsLetter(r) || r == '_' || (i != 0 \u0026\u0026 unicode.IsDigit(r)) {\n\t\t\tif capitalize {\n\t\t\t\tbuffer.WriteRune(unicode.ToUpper(r))\n\t\t\t\tcapitalize = false\n\t\t\t} else {\n\t\t\t\tbuffer.WriteRune(r)\n\t\t\t}\n\t\t} else {\n\t\t\tcapitalize = true\n\t\t}\n\t}\n\treturn buffer.String()\n}","line":{"from":42,"to":59}} {"id":100017631,"name":"GetOperationIDAndTags","signature":"func GetOperationIDAndTags(r *restful.Route) (string, []string, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/openapi/openapi.go","code":"// GetOperationIDAndTags returns a customize operation ID and a list of tags for kubernetes API server's OpenAPI spec to prevent duplicate IDs.\nfunc GetOperationIDAndTags(r *restful.Route) (string, []string, error) {\n\top := r.Operation\n\tpath := r.Path\n\tvar tags []string\n\tprefix, exists := verbs.GetPrefix(op)\n\tif !exists {\n\t\treturn op, tags, fmt.Errorf(\"operation names should start with a verb. Cannot determine operation verb from %v\", op)\n\t}\n\top = op[len(prefix):]\n\tparts := strings.Split(strings.Trim(path, \"/\"), \"/\")\n\t// Assume /api is /apis/core, remove this when we actually server /api/... on /apis/core/...\n\tif len(parts) \u003e= 1 \u0026\u0026 parts[0] == \"api\" {\n\t\tparts = append([]string{\"apis\", \"core\"}, parts[1:]...)\n\t}\n\tif len(parts) \u003e= 2 \u0026\u0026 parts[0] == \"apis\" {\n\t\ttrimmed := strings.TrimSuffix(parts[1], \".k8s.io\")\n\t\tprefix = prefix + ToValidOperationID(trimmed, prefix != \"\")\n\t\ttag := ToValidOperationID(trimmed, false)\n\t\tif len(parts) \u003e 2 {\n\t\t\tprefix = prefix + ToValidOperationID(parts[2], prefix != \"\")\n\t\t\ttag = tag + \"_\" + ToValidOperationID(parts[2], false)\n\t\t}\n\t\ttags = append(tags, tag)\n\t} else if len(parts) \u003e= 1 {\n\t\ttags = append(tags, ToValidOperationID(parts[0], false))\n\t}\n\treturn prefix + ToValidOperationID(op, prefix != \"\"), tags, nil\n}","line":{"from":61,"to":89}} {"id":100017632,"name":"Len","signature":"func (s groupVersionKinds) Len() int","file":"staging/src/k8s.io/apiserver/pkg/endpoints/openapi/openapi.go","code":"func (s groupVersionKinds) Len() int {\n\treturn len(s)\n}","line":{"from":93,"to":95}} {"id":100017633,"name":"Swap","signature":"func (s groupVersionKinds) Swap(i, j int)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/openapi/openapi.go","code":"func (s groupVersionKinds) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}","line":{"from":97,"to":99}} {"id":100017634,"name":"Less","signature":"func (s groupVersionKinds) Less(i, j int) bool","file":"staging/src/k8s.io/apiserver/pkg/endpoints/openapi/openapi.go","code":"func (s groupVersionKinds) Less(i, j int) bool {\n\tif s[i].Group == s[j].Group {\n\t\tif s[i].Version == s[j].Version {\n\t\t\treturn s[i].Kind \u003c s[j].Kind\n\t\t}\n\t\treturn s[i].Version \u003c s[j].Version\n\t}\n\treturn s[i].Group \u003c s[j].Group\n}","line":{"from":101,"to":109}} {"id":100017635,"name":"JSON","signature":"func (s groupVersionKinds) JSON() []interface{}","file":"staging/src/k8s.io/apiserver/pkg/endpoints/openapi/openapi.go","code":"func (s groupVersionKinds) JSON() []interface{} {\n\tj := []interface{}{}\n\tfor _, gvk := range s {\n\t\tj = append(j, map[string]interface{}{\n\t\t\t\"group\": gvk.Group,\n\t\t\t\"version\": gvk.Version,\n\t\t\t\"kind\": gvk.Kind,\n\t\t})\n\t}\n\treturn j\n}","line":{"from":111,"to":121}} {"id":100017636,"name":"gvkConvert","signature":"func gvkConvert(gvk schema.GroupVersionKind) v1.GroupVersionKind","file":"staging/src/k8s.io/apiserver/pkg/endpoints/openapi/openapi.go","code":"func gvkConvert(gvk schema.GroupVersionKind) v1.GroupVersionKind {\n\treturn v1.GroupVersionKind{\n\t\tGroup: gvk.Group,\n\t\tVersion: gvk.Version,\n\t\tKind: gvk.Kind,\n\t}\n}","line":{"from":128,"to":134}} {"id":100017637,"name":"friendlyName","signature":"func friendlyName(name string) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/openapi/openapi.go","code":"func friendlyName(name string) string {\n\tnameParts := strings.Split(name, \"/\")\n\t// Reverse first part. e.g., io.k8s... instead of k8s.io...\n\tif len(nameParts) \u003e 0 \u0026\u0026 strings.Contains(nameParts[0], \".\") {\n\t\tparts := strings.Split(nameParts[0], \".\")\n\t\tfor i, j := 0, len(parts)-1; i \u003c j; i, j = i+1, j-1 {\n\t\t\tparts[i], parts[j] = parts[j], parts[i]\n\t\t}\n\t\tnameParts[0] = strings.Join(parts, \".\")\n\t}\n\treturn strings.Join(nameParts, \".\")\n}","line":{"from":136,"to":147}} {"id":100017638,"name":"typeName","signature":"func typeName(t reflect.Type) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/openapi/openapi.go","code":"func typeName(t reflect.Type) string {\n\tpath := t.PkgPath()\n\tif strings.Contains(path, \"/vendor/\") {\n\t\tpath = path[strings.Index(path, \"/vendor/\")+len(\"/vendor/\"):]\n\t}\n\treturn fmt.Sprintf(\"%s.%s\", path, t.Name())\n}","line":{"from":149,"to":155}} {"id":100017639,"name":"NewDefinitionNamer","signature":"func NewDefinitionNamer(schemes ...*runtime.Scheme) *DefinitionNamer","file":"staging/src/k8s.io/apiserver/pkg/endpoints/openapi/openapi.go","code":"// NewDefinitionNamer constructs a new DefinitionNamer to be used to customize OpenAPI spec.\nfunc NewDefinitionNamer(schemes ...*runtime.Scheme) *DefinitionNamer {\n\tret := \u0026DefinitionNamer{\n\t\ttypeGroupVersionKinds: map[string]groupVersionKinds{},\n\t}\n\tfor _, s := range schemes {\n\t\tfor gvk, rtype := range s.AllKnownTypes() {\n\t\t\tnewGVK := gvkConvert(gvk)\n\t\t\texists := false\n\t\t\tfor _, existingGVK := range ret.typeGroupVersionKinds[typeName(rtype)] {\n\t\t\t\tif newGVK == existingGVK {\n\t\t\t\t\texists = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !exists {\n\t\t\t\tret.typeGroupVersionKinds[typeName(rtype)] = append(ret.typeGroupVersionKinds[typeName(rtype)], newGVK)\n\t\t\t}\n\t\t}\n\t}\n\tfor _, gvk := range ret.typeGroupVersionKinds {\n\t\tsort.Sort(gvk)\n\t}\n\treturn ret\n}","line":{"from":157,"to":181}} {"id":100017640,"name":"GetDefinitionName","signature":"func (d *DefinitionNamer) GetDefinitionName(name string) (string, spec.Extensions)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/openapi/openapi.go","code":"// GetDefinitionName returns the name and tags for a given definition\nfunc (d *DefinitionNamer) GetDefinitionName(name string) (string, spec.Extensions) {\n\tif groupVersionKinds, ok := d.typeGroupVersionKinds[name]; ok {\n\t\treturn friendlyName(name), spec.Extensions{\n\t\t\textensionGVK: groupVersionKinds.JSON(),\n\t\t}\n\t}\n\treturn friendlyName(name), nil\n}","line":{"from":183,"to":191}} {"id":100017641,"name":"NewContext","signature":"func NewContext() context.Context","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/context.go","code":"// NewContext instantiates a base context object for request flows.\nfunc NewContext() context.Context {\n\treturn context.TODO()\n}","line":{"from":37,"to":40}} {"id":100017642,"name":"NewDefaultContext","signature":"func NewDefaultContext() context.Context","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/context.go","code":"// NewDefaultContext instantiates a base context object for request flows in the default namespace\nfunc NewDefaultContext() context.Context {\n\treturn WithNamespace(NewContext(), metav1.NamespaceDefault)\n}","line":{"from":42,"to":45}} {"id":100017643,"name":"WithValue","signature":"func WithValue(parent context.Context, key interface{}, val interface{}) context.Context","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/context.go","code":"// WithValue returns a copy of parent in which the value associated with key is val.\nfunc WithValue(parent context.Context, key interface{}, val interface{}) context.Context {\n\treturn context.WithValue(parent, key, val)\n}","line":{"from":47,"to":50}} {"id":100017644,"name":"WithNamespace","signature":"func WithNamespace(parent context.Context, namespace string) context.Context","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/context.go","code":"// WithNamespace returns a copy of parent in which the namespace value is set\nfunc WithNamespace(parent context.Context, namespace string) context.Context {\n\treturn WithValue(parent, namespaceKey, namespace)\n}","line":{"from":52,"to":55}} {"id":100017645,"name":"NamespaceFrom","signature":"func NamespaceFrom(ctx context.Context) (string, bool)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/context.go","code":"// NamespaceFrom returns the value of the namespace key on the ctx\nfunc NamespaceFrom(ctx context.Context) (string, bool) {\n\tnamespace, ok := ctx.Value(namespaceKey).(string)\n\treturn namespace, ok\n}","line":{"from":57,"to":61}} {"id":100017646,"name":"NamespaceValue","signature":"func NamespaceValue(ctx context.Context) string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/context.go","code":"// NamespaceValue returns the value of the namespace key on the ctx, or the empty string if none\nfunc NamespaceValue(ctx context.Context) string {\n\tnamespace, _ := NamespaceFrom(ctx)\n\treturn namespace\n}","line":{"from":63,"to":67}} {"id":100017647,"name":"WithUser","signature":"func WithUser(parent context.Context, user user.Info) context.Context","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/context.go","code":"// WithUser returns a copy of parent in which the user value is set\nfunc WithUser(parent context.Context, user user.Info) context.Context {\n\treturn WithValue(parent, userKey, user)\n}","line":{"from":69,"to":72}} {"id":100017648,"name":"UserFrom","signature":"func UserFrom(ctx context.Context) (user.Info, bool)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/context.go","code":"// UserFrom returns the value of the user key on the ctx\nfunc UserFrom(ctx context.Context) (user.Info, bool) {\n\tuser, ok := ctx.Value(userKey).(user.Info)\n\treturn user, ok\n}","line":{"from":74,"to":78}} {"id":100017649,"name":"WithReceivedTimestamp","signature":"func WithReceivedTimestamp(parent context.Context, receivedTimestamp time.Time) context.Context","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/received_time.go","code":"// WithReceivedTimestamp returns a copy of parent context in which the ReceivedTimestamp\n// (the time the request reached the apiserver) is set.\n//\n// If the specified ReceivedTimestamp is zero, no value is set and the parent context is returned as is.\nfunc WithReceivedTimestamp(parent context.Context, receivedTimestamp time.Time) context.Context {\n\tif receivedTimestamp.IsZero() {\n\t\treturn parent\n\t}\n\treturn WithValue(parent, requestReceivedTimestampKey, receivedTimestamp)\n}","line":{"from":30,"to":39}} {"id":100017650,"name":"ReceivedTimestampFrom","signature":"func ReceivedTimestampFrom(ctx context.Context) (time.Time, bool)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/received_time.go","code":"// ReceivedTimestampFrom returns the value of the ReceivedTimestamp key from the specified context.\nfunc ReceivedTimestampFrom(ctx context.Context) (time.Time, bool) {\n\tinfo, ok := ctx.Value(requestReceivedTimestampKey).(time.Time)\n\treturn info, ok\n}","line":{"from":41,"to":45}} {"id":100017651,"name":"NewRequestInfo","signature":"func (r *RequestInfoFactory) NewRequestInfo(req *http.Request) (*RequestInfo, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/requestinfo.go","code":"// TODO write an integration test against the swagger doc to test the RequestInfo and match up behavior to responses\n// NewRequestInfo returns the information from the http request. If error is not nil, RequestInfo holds the information as best it is known before the failure\n// It handles both resource and non-resource requests and fills in all the pertinent information for each.\n// Valid Inputs:\n// Resource paths\n// /apis/{api-group}/{version}/namespaces\n// /api/{version}/namespaces\n// /api/{version}/namespaces/{namespace}\n// /api/{version}/namespaces/{namespace}/{resource}\n// /api/{version}/namespaces/{namespace}/{resource}/{resourceName}\n// /api/{version}/{resource}\n// /api/{version}/{resource}/{resourceName}\n//\n// Special verbs without subresources:\n// /api/{version}/proxy/{resource}/{resourceName}\n// /api/{version}/proxy/namespaces/{namespace}/{resource}/{resourceName}\n//\n// Special verbs with subresources:\n// /api/{version}/watch/{resource}\n// /api/{version}/watch/namespaces/{namespace}/{resource}\n//\n// NonResource paths\n// /apis/{api-group}/{version}\n// /apis/{api-group}\n// /apis\n// /api/{version}\n// /api\n// /healthz\n// /\nfunc (r *RequestInfoFactory) NewRequestInfo(req *http.Request) (*RequestInfo, error) {\n\t// start with a non-resource request until proven otherwise\n\trequestInfo := RequestInfo{\n\t\tIsResourceRequest: false,\n\t\tPath: req.URL.Path,\n\t\tVerb: strings.ToLower(req.Method),\n\t}\n\n\tcurrentParts := splitPath(req.URL.Path)\n\tif len(currentParts) \u003c 3 {\n\t\t// return a non-resource request\n\t\treturn \u0026requestInfo, nil\n\t}\n\n\tif !r.APIPrefixes.Has(currentParts[0]) {\n\t\t// return a non-resource request\n\t\treturn \u0026requestInfo, nil\n\t}\n\trequestInfo.APIPrefix = currentParts[0]\n\tcurrentParts = currentParts[1:]\n\n\tif !r.GrouplessAPIPrefixes.Has(requestInfo.APIPrefix) {\n\t\t// one part (APIPrefix) has already been consumed, so this is actually \"do we have four parts?\"\n\t\tif len(currentParts) \u003c 3 {\n\t\t\t// return a non-resource request\n\t\t\treturn \u0026requestInfo, nil\n\t\t}\n\n\t\trequestInfo.APIGroup = currentParts[0]\n\t\tcurrentParts = currentParts[1:]\n\t}\n\n\trequestInfo.IsResourceRequest = true\n\trequestInfo.APIVersion = currentParts[0]\n\tcurrentParts = currentParts[1:]\n\n\t// handle input of form /{specialVerb}/*\n\tif specialVerbs.Has(currentParts[0]) {\n\t\tif len(currentParts) \u003c 2 {\n\t\t\treturn \u0026requestInfo, fmt.Errorf(\"unable to determine kind and namespace from url, %v\", req.URL)\n\t\t}\n\n\t\trequestInfo.Verb = currentParts[0]\n\t\tcurrentParts = currentParts[1:]\n\n\t} else {\n\t\tswitch req.Method {\n\t\tcase \"POST\":\n\t\t\trequestInfo.Verb = \"create\"\n\t\tcase \"GET\", \"HEAD\":\n\t\t\trequestInfo.Verb = \"get\"\n\t\tcase \"PUT\":\n\t\t\trequestInfo.Verb = \"update\"\n\t\tcase \"PATCH\":\n\t\t\trequestInfo.Verb = \"patch\"\n\t\tcase \"DELETE\":\n\t\t\trequestInfo.Verb = \"delete\"\n\t\tdefault:\n\t\t\trequestInfo.Verb = \"\"\n\t\t}\n\t}\n\n\t// URL forms: /namespaces/{namespace}/{kind}/*, where parts are adjusted to be relative to kind\n\tif currentParts[0] == \"namespaces\" {\n\t\tif len(currentParts) \u003e 1 {\n\t\t\trequestInfo.Namespace = currentParts[1]\n\n\t\t\t// if there is another step after the namespace name and it is not a known namespace subresource\n\t\t\t// move currentParts to include it as a resource in its own right\n\t\t\tif len(currentParts) \u003e 2 \u0026\u0026 !namespaceSubresources.Has(currentParts[2]) {\n\t\t\t\tcurrentParts = currentParts[2:]\n\t\t\t}\n\t\t}\n\t} else {\n\t\trequestInfo.Namespace = metav1.NamespaceNone\n\t}\n\n\t// parsing successful, so we now know the proper value for .Parts\n\trequestInfo.Parts = currentParts\n\n\t// parts look like: resource/resourceName/subresource/other/stuff/we/don't/interpret\n\tswitch {\n\tcase len(requestInfo.Parts) \u003e= 3 \u0026\u0026 !specialVerbsNoSubresources.Has(requestInfo.Verb):\n\t\trequestInfo.Subresource = requestInfo.Parts[2]\n\t\tfallthrough\n\tcase len(requestInfo.Parts) \u003e= 2:\n\t\trequestInfo.Name = requestInfo.Parts[1]\n\t\tfallthrough\n\tcase len(requestInfo.Parts) \u003e= 1:\n\t\trequestInfo.Resource = requestInfo.Parts[0]\n\t}\n\n\t// if there's no name on the request and we thought it was a get before, then the actual verb is a list or a watch\n\tif len(requestInfo.Name) == 0 \u0026\u0026 requestInfo.Verb == \"get\" {\n\t\topts := metainternalversion.ListOptions{}\n\t\tif err := metainternalversionscheme.ParameterCodec.DecodeParameters(req.URL.Query(), metav1.SchemeGroupVersion, \u0026opts); err != nil {\n\t\t\t// An error in parsing request will result in default to \"list\" and not setting \"name\" field.\n\t\t\tklog.ErrorS(err, \"Couldn't parse request\", \"request\", req.URL.Query())\n\t\t\t// Reset opts to not rely on partial results from parsing.\n\t\t\t// However, if watch is set, let's report it.\n\t\t\topts = metainternalversion.ListOptions{}\n\t\t\tif values := req.URL.Query()[\"watch\"]; len(values) \u003e 0 {\n\t\t\t\tswitch strings.ToLower(values[0]) {\n\t\t\t\tcase \"false\", \"0\":\n\t\t\t\tdefault:\n\t\t\t\t\topts.Watch = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif opts.Watch {\n\t\t\trequestInfo.Verb = \"watch\"\n\t\t} else {\n\t\t\trequestInfo.Verb = \"list\"\n\t\t}\n\n\t\tif opts.FieldSelector != nil {\n\t\t\tif name, ok := opts.FieldSelector.RequiresExactMatch(\"metadata.name\"); ok {\n\t\t\t\tif len(path.IsValidPathSegmentName(name)) == 0 {\n\t\t\t\t\trequestInfo.Name = name\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// if there's no name on the request and we thought it was a delete before, then the actual verb is deletecollection\n\tif len(requestInfo.Name) == 0 \u0026\u0026 requestInfo.Verb == \"delete\" {\n\t\trequestInfo.Verb = \"deletecollection\"\n\t}\n\n\treturn \u0026requestInfo, nil\n}","line":{"from":88,"to":247}} {"id":100017652,"name":"WithRequestInfo","signature":"func WithRequestInfo(parent context.Context, info *RequestInfo) context.Context","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/requestinfo.go","code":"// WithRequestInfo returns a copy of parent in which the request info value is set\nfunc WithRequestInfo(parent context.Context, info *RequestInfo) context.Context {\n\treturn WithValue(parent, requestInfoKey, info)\n}","line":{"from":256,"to":259}} {"id":100017653,"name":"RequestInfoFrom","signature":"func RequestInfoFrom(ctx context.Context) (*RequestInfo, bool)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/requestinfo.go","code":"// RequestInfoFrom returns the value of the RequestInfo key on the ctx\nfunc RequestInfoFrom(ctx context.Context) (*RequestInfo, bool) {\n\tinfo, ok := ctx.Value(requestInfoKey).(*RequestInfo)\n\treturn info, ok\n}","line":{"from":261,"to":265}} {"id":100017654,"name":"splitPath","signature":"func splitPath(path string) []string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/requestinfo.go","code":"// splitPath returns the segments for a URL path.\nfunc splitPath(path string) []string {\n\tpath = strings.Trim(path, \"/\")\n\tif path == \"\" {\n\t\treturn []string{}\n\t}\n\treturn strings.Split(path, \"/\")\n}","line":{"from":267,"to":274}} {"id":100017655,"name":"ServerShutdownSignalFrom","signature":"func ServerShutdownSignalFrom(ctx context.Context) ServerShutdownSignal","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/server_shutdown_signal.go","code":"// ServerShutdownSignalFrom returns the ServerShutdownSignal instance\n// associated with the request context.\n// If there is no ServerShutdownSignal asscoaied with the context,\n// nil is returned.\nfunc ServerShutdownSignalFrom(ctx context.Context) ServerShutdownSignal {\n\tev, _ := ctx.Value(serverShutdownSignalKey).(ServerShutdownSignal)\n\treturn ev\n}","line":{"from":38,"to":45}} {"id":100017656,"name":"WithServerShutdownSignal","signature":"func WithServerShutdownSignal(parent context.Context, window ServerShutdownSignal) context.Context","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/server_shutdown_signal.go","code":"// WithServerShutdownSignal returns a new context that stores\n// the ServerShutdownSignal interface instance.\nfunc WithServerShutdownSignal(parent context.Context, window ServerShutdownSignal) context.Context {\n\tif ServerShutdownSignalFrom(parent) != nil {\n\t\treturn parent // Avoid double registering.\n\t}\n\n\treturn context.WithValue(parent, serverShutdownSignalKey, window)\n}","line":{"from":47,"to":55}} {"id":100017657,"name":"sumDuration","signature":"func sumDuration(d1 time.Duration, d2 time.Duration) time.Duration","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/webhook_duration.go","code":"func sumDuration(d1 time.Duration, d2 time.Duration) time.Duration {\n\treturn d1 + d2\n}","line":{"from":27,"to":29}} {"id":100017658,"name":"maxDuration","signature":"func maxDuration(d1 time.Duration, d2 time.Duration) time.Duration","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/webhook_duration.go","code":"func maxDuration(d1 time.Duration, d2 time.Duration) time.Duration {\n\tif d1 \u003e d2 {\n\t\treturn d1\n\t}\n\treturn d2\n}","line":{"from":31,"to":36}} {"id":100017659,"name":"Track","signature":"func (t *durationTracker) Track(f func())","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/webhook_duration.go","code":"// Track measures time spent in given function and aggregates measured\n// duration using aggregateFunction\nfunc (t *durationTracker) Track(f func()) {\n\tstartedAt := t.clock.Now()\n\tdefer func() {\n\t\tduration := t.clock.Since(startedAt)\n\t\tt.mu.Lock()\n\t\tdefer t.mu.Unlock()\n\t\tt.latency = t.aggregateFunction(t.latency, duration)\n\t}()\n\n\tf()\n}","line":{"from":64,"to":76}} {"id":100017660,"name":"TrackDuration","signature":"func (t *durationTracker) TrackDuration(d time.Duration)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/webhook_duration.go","code":"// TrackDuration tracks latency from the given duration\n// using aggregateFunction\nfunc (t *durationTracker) TrackDuration(d time.Duration) {\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\tt.latency = t.aggregateFunction(t.latency, d)\n}","line":{"from":78,"to":84}} {"id":100017661,"name":"GetLatency","signature":"func (t *durationTracker) GetLatency() time.Duration","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/webhook_duration.go","code":"// GetLatency returns aggregated latency tracked by a tracker\nfunc (t *durationTracker) GetLatency() time.Duration {\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\treturn t.latency\n}","line":{"from":86,"to":91}} {"id":100017662,"name":"newSumLatencyTracker","signature":"func newSumLatencyTracker(c clock.Clock) DurationTracker","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/webhook_duration.go","code":"func newSumLatencyTracker(c clock.Clock) DurationTracker {\n\treturn \u0026durationTracker{\n\t\tclock: c,\n\t\taggregateFunction: sumDuration,\n\t}\n}","line":{"from":93,"to":98}} {"id":100017663,"name":"newMaxLatencyTracker","signature":"func newMaxLatencyTracker(c clock.Clock) DurationTracker","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/webhook_duration.go","code":"func newMaxLatencyTracker(c clock.Clock) DurationTracker {\n\treturn \u0026durationTracker{\n\t\tclock: c,\n\t\taggregateFunction: maxDuration,\n\t}\n}","line":{"from":100,"to":105}} {"id":100017664,"name":"WithLatencyTrackers","signature":"func WithLatencyTrackers(parent context.Context) context.Context","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/webhook_duration.go","code":"// WithLatencyTrackers returns a copy of parent context to which an\n// instance of LatencyTrackers is added.\nfunc WithLatencyTrackers(parent context.Context) context.Context {\n\treturn WithLatencyTrackersAndCustomClock(parent, clock.RealClock{})\n}","line":{"from":163,"to":167}} {"id":100017665,"name":"WithLatencyTrackersAndCustomClock","signature":"func WithLatencyTrackersAndCustomClock(parent context.Context, c clock.Clock) context.Context","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/webhook_duration.go","code":"// WithLatencyTrackersAndCustomClock returns a copy of parent context to which\n// an instance of LatencyTrackers is added. Tracers use given clock.\nfunc WithLatencyTrackersAndCustomClock(parent context.Context, c clock.Clock) context.Context {\n\treturn WithValue(parent, latencyTrackersKey, \u0026LatencyTrackers{\n\t\tMutatingWebhookTracker: newSumLatencyTracker(c),\n\t\tValidatingWebhookTracker: newMaxLatencyTracker(c),\n\t\tAPFQueueWaitTracker: newMaxLatencyTracker(c),\n\t\tStorageTracker: newSumLatencyTracker(c),\n\t\tTransformTracker: newSumLatencyTracker(c),\n\t\tSerializationTracker: newSumLatencyTracker(c),\n\t\tResponseWriteTracker: newSumLatencyTracker(c),\n\t})\n}","line":{"from":169,"to":181}} {"id":100017666,"name":"LatencyTrackersFrom","signature":"func LatencyTrackersFrom(ctx context.Context) (*LatencyTrackers, bool)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/webhook_duration.go","code":"// LatencyTrackersFrom returns the associated LatencyTrackers instance\n// from the specified context.\nfunc LatencyTrackersFrom(ctx context.Context) (*LatencyTrackers, bool) {\n\twd, ok := ctx.Value(latencyTrackersKey).(*LatencyTrackers)\n\treturn wd, ok \u0026\u0026 wd != nil\n}","line":{"from":183,"to":188}} {"id":100017667,"name":"TrackTransformResponseObjectLatency","signature":"func TrackTransformResponseObjectLatency(ctx context.Context, transform func())","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/webhook_duration.go","code":"// TrackTransformResponseObjectLatency is used to track latency incurred\n// inside the function that takes an object returned from the underlying\n// storage layer (etcd) and performs any necessary transformations\n// of the response object. This does not include the latency incurred in\n// serialization (json or protobuf) of the response object or writing of\n// it to the http ResponseWriter object.\n// When called multiple times, the latency incurred inside the\n// transform func each time will be summed up.\nfunc TrackTransformResponseObjectLatency(ctx context.Context, transform func()) {\n\tif tracker, ok := LatencyTrackersFrom(ctx); ok {\n\t\ttracker.TransformTracker.Track(transform)\n\t\treturn\n\t}\n\n\ttransform()\n}","line":{"from":190,"to":205}} {"id":100017668,"name":"TrackStorageLatency","signature":"func TrackStorageLatency(ctx context.Context, d time.Duration)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/webhook_duration.go","code":"// TrackStorageLatency is used to track latency incurred\n// inside the underlying storage layer.\n// When called multiple times, the latency provided will be summed up.\nfunc TrackStorageLatency(ctx context.Context, d time.Duration) {\n\tif tracker, ok := LatencyTrackersFrom(ctx); ok {\n\t\ttracker.StorageTracker.TrackDuration(d)\n\t}\n}","line":{"from":207,"to":214}} {"id":100017669,"name":"TrackSerializeResponseObjectLatency","signature":"func TrackSerializeResponseObjectLatency(ctx context.Context, f func())","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/webhook_duration.go","code":"// TrackSerializeResponseObjectLatency is used to track latency incurred in\n// serialization (json or protobuf) of the response object.\n// When called multiple times, the latency provided will be summed up.\nfunc TrackSerializeResponseObjectLatency(ctx context.Context, f func()) {\n\tif tracker, ok := LatencyTrackersFrom(ctx); ok {\n\t\ttracker.SerializationTracker.Track(f)\n\t\treturn\n\t}\n\n\tf()\n}","line":{"from":216,"to":226}} {"id":100017670,"name":"TrackResponseWriteLatency","signature":"func TrackResponseWriteLatency(ctx context.Context, d time.Duration)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/webhook_duration.go","code":"// TrackResponseWriteLatency is used to track latency incurred in writing\n// the serialized raw bytes to the http ResponseWriter object (via the\n// Write method) associated with the request.\n// When called multiple times, the latency provided will be summed up.\nfunc TrackResponseWriteLatency(ctx context.Context, d time.Duration) {\n\tif tracker, ok := LatencyTrackersFrom(ctx); ok {\n\t\ttracker.ResponseWriteTracker.TrackDuration(d)\n\t}\n}","line":{"from":228,"to":236}} {"id":100017671,"name":"TrackAPFQueueWaitLatency","signature":"func TrackAPFQueueWaitLatency(ctx context.Context, d time.Duration)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/webhook_duration.go","code":"// TrackAPFQueueWaitLatency is used to track latency incurred\n// by priority and fairness queues.\nfunc TrackAPFQueueWaitLatency(ctx context.Context, d time.Duration) {\n\tif tracker, ok := LatencyTrackersFrom(ctx); ok {\n\t\ttracker.APFQueueWaitTracker.TrackDuration(d)\n\t}\n}","line":{"from":238,"to":244}} {"id":100017672,"name":"AuditAnnotationsFromLatencyTrackers","signature":"func AuditAnnotationsFromLatencyTrackers(ctx context.Context) map[string]string","file":"staging/src/k8s.io/apiserver/pkg/endpoints/request/webhook_duration.go","code":"// AuditAnnotationsFromLatencyTrackers will inspect each latency tracker\n// associated with the request context and return a set of audit\n// annotations that can be added to the API audit entry.\nfunc AuditAnnotationsFromLatencyTrackers(ctx context.Context) map[string]string {\n\tconst (\n\t\ttransformLatencyKey = \"apiserver.latency.k8s.io/transform-response-object\"\n\t\tstorageLatencyKey = \"apiserver.latency.k8s.io/etcd\"\n\t\tserializationLatencyKey = \"apiserver.latency.k8s.io/serialize-response-object\"\n\t\tresponseWriteLatencyKey = \"apiserver.latency.k8s.io/response-write\"\n\t\tmutatingWebhookLatencyKey = \"apiserver.latency.k8s.io/mutating-webhook\"\n\t\tvalidatingWebhookLatencyKey = \"apiserver.latency.k8s.io/validating-webhook\"\n\t)\n\n\ttracker, ok := LatencyTrackersFrom(ctx)\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tannotations := map[string]string{}\n\tif latency := tracker.TransformTracker.GetLatency(); latency != 0 {\n\t\tannotations[transformLatencyKey] = latency.String()\n\t}\n\tif latency := tracker.StorageTracker.GetLatency(); latency != 0 {\n\t\tannotations[storageLatencyKey] = latency.String()\n\t}\n\tif latency := tracker.SerializationTracker.GetLatency(); latency != 0 {\n\t\tannotations[serializationLatencyKey] = latency.String()\n\t}\n\tif latency := tracker.ResponseWriteTracker.GetLatency(); latency != 0 {\n\t\tannotations[responseWriteLatencyKey] = latency.String()\n\t}\n\tif latency := tracker.MutatingWebhookTracker.GetLatency(); latency != 0 {\n\t\tannotations[mutatingWebhookLatencyKey] = latency.String()\n\t}\n\tif latency := tracker.ValidatingWebhookTracker.GetLatency(); latency != 0 {\n\t\tannotations[validatingWebhookLatencyKey] = latency.String()\n\t}\n\n\treturn annotations\n}","line":{"from":246,"to":285}} {"id":100017673,"name":"WrapForHTTP1Or2","signature":"func WrapForHTTP1Or2(decorator UserProvidedDecorator) http.ResponseWriter","file":"staging/src/k8s.io/apiserver/pkg/endpoints/responsewriter/wrapper.go","code":"// WrapForHTTP1Or2 accepts a user-provided decorator of an \"inner\" http.responseWriter\n// object and potentially wraps the user-provided decorator with a new http.ResponseWriter\n// object that implements http.CloseNotifier, http.Flusher, and/or http.Hijacker by\n// delegating to the user-provided decorator (if it implements the relevant method) or\n// the inner http.ResponseWriter (otherwise), so that the returned http.ResponseWriter\n// object implements the same subset of those interfaces as the inner http.ResponseWriter.\n//\n// This function handles the following three casses.\n// - The inner ResponseWriter implements `http.CloseNotifier`, `http.Flusher`,\n// and `http.Hijacker` (an HTTP/1.1 sever provides such a ResponseWriter).\n// - The inner ResponseWriter implements `http.CloseNotifier` and `http.Flusher`\n// but not `http.Hijacker` (an HTTP/2 server provides such a ResponseWriter).\n// - All the other cases collapse to this one, in which the given ResponseWriter is returned.\n//\n// There are three applicable terms:\n// - \"outer\": this is the ResponseWriter object returned by the WrapForHTTP1Or2 function.\n// - \"user-provided decorator\" or \"middle\": this is the user-provided decorator\n// that decorates an inner ResponseWriter object. A user-provided decorator\n// implements the UserProvidedDecorator interface. A user-provided decorator\n// may or may not implement http.CloseNotifier, http.Flusher or http.Hijacker.\n// - \"inner\": the ResponseWriter that the user-provided decorator extends.\nfunc WrapForHTTP1Or2(decorator UserProvidedDecorator) http.ResponseWriter {\n\t// from go net/http documentation:\n\t// The default HTTP/1.x and HTTP/2 ResponseWriter implementations support Flusher\n\t// Handlers should always test for this ability at runtime.\n\t//\n\t// The Hijacker interface is implemented by ResponseWriters that allow an HTTP handler\n\t// to take over the connection.\n\t// The default ResponseWriter for HTTP/1.x connections supports Hijacker, but HTTP/2 connections\n\t// intentionally do not. ResponseWriter wrappers may also not support Hijacker.\n\t// Handlers should always test for this ability at runtime\n\t//\n\t// The CloseNotifier interface is implemented by ResponseWriters which allow detecting\n\t// when the underlying connection has gone away.\n\t// Deprecated: the CloseNotifier interface predates Go's context package.\n\t// New code should use Request.Context instead.\n\tinner := decorator.Unwrap()\n\tif innerNotifierFlusher, ok := inner.(CloseNotifierFlusher); ok {\n\t\t// for HTTP/2 request, the default ResponseWriter object (http2responseWriter)\n\t\t// implements Flusher and CloseNotifier.\n\t\touterHTTP2 := outerWithCloseNotifyAndFlush{\n\t\t\tUserProvidedDecorator: decorator,\n\t\t\tInnerCloseNotifierFlusher: innerNotifierFlusher,\n\t\t}\n\n\t\tif innerHijacker, hijackable := inner.(http.Hijacker); hijackable {\n\t\t\t// for HTTP/1.x request the default implementation of ResponseWriter\n\t\t\t// also implement CloseNotifier, Flusher and Hijacker\n\t\t\treturn \u0026outerWithCloseNotifyFlushAndHijack{\n\t\t\t\touterWithCloseNotifyAndFlush: outerHTTP2,\n\t\t\t\tInnerHijacker: innerHijacker,\n\t\t\t}\n\t\t}\n\n\t\treturn outerHTTP2\n\t}\n\n\t// we should never be here for either http/1.x or http2 request\n\treturn decorator\n}","line":{"from":37,"to":96}} {"id":100017674,"name":"GetOriginal","signature":"func GetOriginal(w http.ResponseWriter) http.ResponseWriter","file":"staging/src/k8s.io/apiserver/pkg/endpoints/responsewriter/wrapper.go","code":"// GetOriginal goes through the chain of wrapped http.ResponseWriter objects\n// and returns the original http.ResponseWriter object provided to the first\n// request handler in the filter chain.\nfunc GetOriginal(w http.ResponseWriter) http.ResponseWriter {\n\tdecorator, ok := w.(UserProvidedDecorator)\n\tif !ok {\n\t\treturn w\n\t}\n\n\tinner := decorator.Unwrap()\n\tif inner == w {\n\t\t// infinite cycle here, we should never be here though.\n\t\tpanic(\"http.ResponseWriter decorator chain has a cycle\")\n\t}\n\n\treturn GetOriginal(inner)\n}","line":{"from":105,"to":121}} {"id":100017675,"name":"CloseNotify","signature":"func (wr outerWithCloseNotifyAndFlush) CloseNotify() \u003c-chan bool","file":"staging/src/k8s.io/apiserver/pkg/endpoints/responsewriter/wrapper.go","code":"func (wr outerWithCloseNotifyAndFlush) CloseNotify() \u003c-chan bool {\n\tif notifier, ok := wr.UserProvidedDecorator.(http.CloseNotifier); ok {\n\t\treturn notifier.CloseNotify()\n\t}\n\n\treturn wr.InnerCloseNotifierFlusher.CloseNotify()\n}","line":{"from":140,"to":146}} {"id":100017676,"name":"Flush","signature":"func (wr outerWithCloseNotifyAndFlush) Flush()","file":"staging/src/k8s.io/apiserver/pkg/endpoints/responsewriter/wrapper.go","code":"func (wr outerWithCloseNotifyAndFlush) Flush() {\n\tif flusher, ok := wr.UserProvidedDecorator.(http.Flusher); ok {\n\t\tflusher.Flush()\n\t\treturn\n\t}\n\n\twr.InnerCloseNotifierFlusher.Flush()\n}","line":{"from":148,"to":155}} {"id":100017677,"name":"Hijack","signature":"func (wr outerWithCloseNotifyFlushAndHijack) Hijack() (net.Conn, *bufio.ReadWriter, error)","file":"staging/src/k8s.io/apiserver/pkg/endpoints/responsewriter/wrapper.go","code":"func (wr outerWithCloseNotifyFlushAndHijack) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\tif hijacker, ok := wr.UserProvidedDecorator.(http.Hijacker); ok {\n\t\treturn hijacker.Hijack()\n\t}\n\n\treturn wr.InnerHijacker.Hijack()\n}","line":{"from":174,"to":180}} {"id":100017678,"name":"AddWarningsHandler","signature":"func AddWarningsHandler(handler restful.RouteFunction, warnings []string) restful.RouteFunction","file":"staging/src/k8s.io/apiserver/pkg/endpoints/warning/warning.go","code":"// AddWarningsHandler returns a handler that adds the provided warnings to all requests,\n// then delegates to the provided handler.\nfunc AddWarningsHandler(handler restful.RouteFunction, warnings []string) restful.RouteFunction {\n\tif len(warnings) == 0 {\n\t\treturn handler\n\t}\n\n\treturn func(req *restful.Request, res *restful.Response) {\n\t\tctx := req.Request.Context()\n\t\tfor _, msg := range warnings {\n\t\t\twarning.AddWarning(ctx, \"\", msg)\n\t\t}\n\t\thandler(req, res)\n\t}\n}","line":{"from":25,"to":39}} {"id":100017679,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/features/kube_features.go","code":"func init() {\n\truntime.Must(utilfeature.DefaultMutableFeatureGate.Add(defaultKubernetesFeatureGates))\n}","line":{"from":227,"to":229}} {"id":100017680,"name":"NewConfiguration","signature":"func NewConfiguration(evaluators []quota.Evaluator, ignoredResources map[schema.GroupResource]struct{}) quota.Configuration","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/configuration.go","code":"// NewConfiguration creates a quota configuration\nfunc NewConfiguration(evaluators []quota.Evaluator, ignoredResources map[schema.GroupResource]struct{}) quota.Configuration {\n\treturn \u0026simpleConfiguration{\n\t\tevaluators: evaluators,\n\t\tignoredResources: ignoredResources,\n\t}\n}","line":{"from":30,"to":36}} {"id":100017681,"name":"IgnoredResources","signature":"func (c *simpleConfiguration) IgnoredResources() map[schema.GroupResource]struct{}","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/configuration.go","code":"func (c *simpleConfiguration) IgnoredResources() map[schema.GroupResource]struct{} {\n\treturn c.ignoredResources\n}","line":{"from":38,"to":40}} {"id":100017682,"name":"Evaluators","signature":"func (c *simpleConfiguration) Evaluators() []quota.Evaluator","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/configuration.go","code":"func (c *simpleConfiguration) Evaluators() []quota.Evaluator {\n\treturn c.evaluators\n}","line":{"from":42,"to":44}} {"id":100017683,"name":"ListerFuncForResourceFunc","signature":"func ListerFuncForResourceFunc(f InformerForResourceFunc) quota.ListerForResourceFunc","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/evaluator.go","code":"// ListerFuncForResourceFunc knows how to provision a lister from an informer func.\n// The lister returns errors until the informer has synced.\nfunc ListerFuncForResourceFunc(f InformerForResourceFunc) quota.ListerForResourceFunc {\n\treturn func(gvr schema.GroupVersionResource) (cache.GenericLister, error) {\n\t\tinformer, err := f(gvr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn \u0026protectedLister{\n\t\t\thasSynced: cachedHasSynced(informer.Informer().HasSynced),\n\t\t\tnotReadyErr: fmt.Errorf(\"%v not yet synced\", gvr),\n\t\t\tdelegate: informer.Lister(),\n\t\t}, nil\n\t}\n}","line":{"from":37,"to":51}} {"id":100017684,"name":"cachedHasSynced","signature":"func cachedHasSynced(hasSynced func() bool) func() bool","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/evaluator.go","code":"// cachedHasSynced returns a function that calls hasSynced() until it returns true once, then returns true\nfunc cachedHasSynced(hasSynced func() bool) func() bool {\n\tcache := \u0026atomic.Bool{}\n\tcache.Store(false)\n\treturn func() bool {\n\t\tif cache.Load() {\n\t\t\t// short-circuit if already synced\n\t\t\treturn true\n\t\t}\n\t\tif hasSynced() {\n\t\t\t// remember we synced\n\t\t\tcache.Store(true)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n}","line":{"from":53,"to":69}} {"id":100017685,"name":"List","signature":"func (p *protectedLister) List(selector labels.Selector) (ret []runtime.Object, err error)","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/evaluator.go","code":"func (p *protectedLister) List(selector labels.Selector) (ret []runtime.Object, err error) {\n\tif !p.hasSynced() {\n\t\treturn nil, p.notReadyErr\n\t}\n\treturn p.delegate.List(selector)\n}","line":{"from":78,"to":83}} {"id":100017686,"name":"Get","signature":"func (p *protectedLister) Get(name string) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/evaluator.go","code":"func (p *protectedLister) Get(name string) (runtime.Object, error) {\n\tif !p.hasSynced() {\n\t\treturn nil, p.notReadyErr\n\t}\n\treturn p.delegate.Get(name)\n}","line":{"from":84,"to":89}} {"id":100017687,"name":"ByNamespace","signature":"func (p *protectedLister) ByNamespace(namespace string) cache.GenericNamespaceLister","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/evaluator.go","code":"func (p *protectedLister) ByNamespace(namespace string) cache.GenericNamespaceLister {\n\treturn \u0026protectedNamespaceLister{p.hasSynced, p.notReadyErr, p.delegate.ByNamespace(namespace)}\n}","line":{"from":90,"to":92}} {"id":100017688,"name":"List","signature":"func (p *protectedNamespaceLister) List(selector labels.Selector) (ret []runtime.Object, err error)","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/evaluator.go","code":"func (p *protectedNamespaceLister) List(selector labels.Selector) (ret []runtime.Object, err error) {\n\tif !p.hasSynced() {\n\t\treturn nil, p.notReadyErr\n\t}\n\treturn p.delegate.List(selector)\n}","line":{"from":101,"to":106}} {"id":100017689,"name":"Get","signature":"func (p *protectedNamespaceLister) Get(name string) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/evaluator.go","code":"func (p *protectedNamespaceLister) Get(name string) (runtime.Object, error) {\n\tif !p.hasSynced() {\n\t\treturn nil, p.notReadyErr\n\t}\n\treturn p.delegate.Get(name)\n}","line":{"from":107,"to":112}} {"id":100017690,"name":"ListResourceUsingListerFunc","signature":"func ListResourceUsingListerFunc(l quota.ListerForResourceFunc, resource schema.GroupVersionResource) ListFuncByNamespace","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/evaluator.go","code":"// ListResourceUsingListerFunc returns a listing function based on the shared informer factory for the specified resource.\nfunc ListResourceUsingListerFunc(l quota.ListerForResourceFunc, resource schema.GroupVersionResource) ListFuncByNamespace {\n\treturn func(namespace string) ([]runtime.Object, error) {\n\t\tlister, err := l(resource)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn lister.ByNamespace(namespace).List(labels.Everything())\n\t}\n}","line":{"from":114,"to":123}} {"id":100017691,"name":"ObjectCountQuotaResourceNameFor","signature":"func ObjectCountQuotaResourceNameFor(groupResource schema.GroupResource) corev1.ResourceName","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/evaluator.go","code":"// ObjectCountQuotaResourceNameFor returns the object count quota name for specified groupResource\nfunc ObjectCountQuotaResourceNameFor(groupResource schema.GroupResource) corev1.ResourceName {\n\tif len(groupResource.Group) == 0 {\n\t\treturn corev1.ResourceName(\"count/\" + groupResource.Resource)\n\t}\n\treturn corev1.ResourceName(\"count/\" + groupResource.Resource + \".\" + groupResource.Group)\n}","line":{"from":125,"to":131}} {"id":100017692,"name":"MatchesNoScopeFunc","signature":"func MatchesNoScopeFunc(scope corev1.ScopedResourceSelectorRequirement, object runtime.Object) (bool, error)","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/evaluator.go","code":"// MatchesNoScopeFunc returns false on all match checks\nfunc MatchesNoScopeFunc(scope corev1.ScopedResourceSelectorRequirement, object runtime.Object) (bool, error) {\n\treturn false, nil\n}","line":{"from":145,"to":148}} {"id":100017693,"name":"Matches","signature":"func Matches(","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/evaluator.go","code":"// Matches returns true if the quota matches the specified item.\nfunc Matches(\n\tresourceQuota *corev1.ResourceQuota, item runtime.Object,\n\tmatchFunc MatchingResourceNamesFunc, scopeFunc MatchesScopeFunc) (bool, error) {\n\tif resourceQuota == nil {\n\t\treturn false, fmt.Errorf(\"expected non-nil quota\")\n\t}\n\t// verify the quota matches on at least one resource\n\tmatchResource := len(matchFunc(quota.ResourceNames(resourceQuota.Status.Hard))) \u003e 0\n\t// by default, no scopes matches all\n\tmatchScope := true\n\tfor _, scope := range getScopeSelectorsFromQuota(resourceQuota) {\n\t\tinnerMatch, err := scopeFunc(scope, item)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tmatchScope = matchScope \u0026\u0026 innerMatch\n\t}\n\treturn matchResource \u0026\u0026 matchScope, nil\n}","line":{"from":150,"to":169}} {"id":100017694,"name":"getScopeSelectorsFromQuota","signature":"func getScopeSelectorsFromQuota(quota *corev1.ResourceQuota) []corev1.ScopedResourceSelectorRequirement","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/evaluator.go","code":"func getScopeSelectorsFromQuota(quota *corev1.ResourceQuota) []corev1.ScopedResourceSelectorRequirement {\n\tselectors := []corev1.ScopedResourceSelectorRequirement{}\n\tfor _, scope := range quota.Spec.Scopes {\n\t\tselectors = append(selectors, corev1.ScopedResourceSelectorRequirement{\n\t\t\tScopeName: scope,\n\t\t\tOperator: corev1.ScopeSelectorOpExists})\n\t}\n\tif quota.Spec.ScopeSelector != nil {\n\t\tselectors = append(selectors, quota.Spec.ScopeSelector.MatchExpressions...)\n\t}\n\treturn selectors\n}","line":{"from":171,"to":182}} {"id":100017695,"name":"CalculateUsageStats","signature":"func CalculateUsageStats(options quota.UsageStatsOptions,","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/evaluator.go","code":"// CalculateUsageStats is a utility function that knows how to calculate aggregate usage.\nfunc CalculateUsageStats(options quota.UsageStatsOptions,\n\tlistFunc ListFuncByNamespace,\n\tscopeFunc MatchesScopeFunc,\n\tusageFunc UsageFunc) (quota.UsageStats, error) {\n\t// default each tracked resource to zero\n\tresult := quota.UsageStats{Used: corev1.ResourceList{}}\n\tfor _, resourceName := range options.Resources {\n\t\tresult.Used[resourceName] = resource.Quantity{Format: resource.DecimalSI}\n\t}\n\titems, err := listFunc(options.Namespace)\n\tif err != nil {\n\t\treturn result, fmt.Errorf(\"failed to list content: %v\", err)\n\t}\n\tfor _, item := range items {\n\t\t// need to verify that the item matches the set of scopes\n\t\tmatchesScopes := true\n\t\tfor _, scope := range options.Scopes {\n\t\t\tinnerMatch, err := scopeFunc(corev1.ScopedResourceSelectorRequirement{ScopeName: scope, Operator: corev1.ScopeSelectorOpExists}, item)\n\t\t\tif err != nil {\n\t\t\t\treturn result, nil\n\t\t\t}\n\t\t\tif !innerMatch {\n\t\t\t\tmatchesScopes = false\n\t\t\t}\n\t\t}\n\t\tif options.ScopeSelector != nil {\n\t\t\tfor _, selector := range options.ScopeSelector.MatchExpressions {\n\t\t\t\tinnerMatch, err := scopeFunc(selector, item)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn result, nil\n\t\t\t\t}\n\t\t\t\tmatchesScopes = matchesScopes \u0026\u0026 innerMatch\n\t\t\t}\n\t\t}\n\t\t// only count usage if there was a match\n\t\tif matchesScopes {\n\t\t\tusage, err := usageFunc(item)\n\t\t\tif err != nil {\n\t\t\t\treturn result, err\n\t\t\t}\n\t\t\tresult.Used = quota.Add(result.Used, usage)\n\t\t}\n\t}\n\treturn result, nil\n}","line":{"from":184,"to":229}} {"id":100017696,"name":"Constraints","signature":"func (o *objectCountEvaluator) Constraints(required []corev1.ResourceName, item runtime.Object) error","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/evaluator.go","code":"// Constraints returns an error if the configured resource name is not in the required set.\nfunc (o *objectCountEvaluator) Constraints(required []corev1.ResourceName, item runtime.Object) error {\n\t// no-op for object counting\n\treturn nil\n}","line":{"from":245,"to":249}} {"id":100017697,"name":"Handles","signature":"func (o *objectCountEvaluator) Handles(a admission.Attributes) bool","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/evaluator.go","code":"// Handles returns true if the object count evaluator needs to track this attributes.\nfunc (o *objectCountEvaluator) Handles(a admission.Attributes) bool {\n\toperation := a.GetOperation()\n\treturn operation == admission.Create\n}","line":{"from":251,"to":255}} {"id":100017698,"name":"Matches","signature":"func (o *objectCountEvaluator) Matches(resourceQuota *corev1.ResourceQuota, item runtime.Object) (bool, error)","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/evaluator.go","code":"// Matches returns true if the evaluator matches the specified quota with the provided input item\nfunc (o *objectCountEvaluator) Matches(resourceQuota *corev1.ResourceQuota, item runtime.Object) (bool, error) {\n\treturn Matches(resourceQuota, item, o.MatchingResources, MatchesNoScopeFunc)\n}","line":{"from":257,"to":260}} {"id":100017699,"name":"MatchingResources","signature":"func (o *objectCountEvaluator) MatchingResources(input []corev1.ResourceName) []corev1.ResourceName","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/evaluator.go","code":"// MatchingResources takes the input specified list of resources and returns the set of resources it matches.\nfunc (o *objectCountEvaluator) MatchingResources(input []corev1.ResourceName) []corev1.ResourceName {\n\treturn quota.Intersection(input, o.resourceNames)\n}","line":{"from":262,"to":265}} {"id":100017700,"name":"MatchingScopes","signature":"func (o *objectCountEvaluator) MatchingScopes(item runtime.Object, scopes []corev1.ScopedResourceSelectorRequirement) ([]corev1.ScopedResourceSelectorRequirement, error)","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/evaluator.go","code":"// MatchingScopes takes the input specified list of scopes and input object. Returns the set of scopes resource matches.\nfunc (o *objectCountEvaluator) MatchingScopes(item runtime.Object, scopes []corev1.ScopedResourceSelectorRequirement) ([]corev1.ScopedResourceSelectorRequirement, error) {\n\treturn []corev1.ScopedResourceSelectorRequirement{}, nil\n}","line":{"from":267,"to":270}} {"id":100017701,"name":"UncoveredQuotaScopes","signature":"func (o *objectCountEvaluator) UncoveredQuotaScopes(limitedScopes []corev1.ScopedResourceSelectorRequirement, matchedQuotaScopes []corev1.ScopedResourceSelectorRequirement) ([]corev1.ScopedResourceSelectorRequirement, error)","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/evaluator.go","code":"// UncoveredQuotaScopes takes the input matched scopes which are limited by configuration and the matched quota scopes.\n// It returns the scopes which are in limited scopes but don't have a corresponding covering quota scope\nfunc (o *objectCountEvaluator) UncoveredQuotaScopes(limitedScopes []corev1.ScopedResourceSelectorRequirement, matchedQuotaScopes []corev1.ScopedResourceSelectorRequirement) ([]corev1.ScopedResourceSelectorRequirement, error) {\n\treturn []corev1.ScopedResourceSelectorRequirement{}, nil\n}","line":{"from":272,"to":276}} {"id":100017702,"name":"Usage","signature":"func (o *objectCountEvaluator) Usage(object runtime.Object) (corev1.ResourceList, error)","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/evaluator.go","code":"// Usage returns the resource usage for the specified object\nfunc (o *objectCountEvaluator) Usage(object runtime.Object) (corev1.ResourceList, error) {\n\tquantity := resource.NewQuantity(1, resource.DecimalSI)\n\tresourceList := corev1.ResourceList{}\n\tfor _, resourceName := range o.resourceNames {\n\t\tresourceList[resourceName] = *quantity\n\t}\n\treturn resourceList, nil\n}","line":{"from":278,"to":286}} {"id":100017703,"name":"GroupResource","signature":"func (o *objectCountEvaluator) GroupResource() schema.GroupResource","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/evaluator.go","code":"// GroupResource tracked by this evaluator\nfunc (o *objectCountEvaluator) GroupResource() schema.GroupResource {\n\treturn o.groupResource\n}","line":{"from":288,"to":291}} {"id":100017704,"name":"UsageStats","signature":"func (o *objectCountEvaluator) UsageStats(options quota.UsageStatsOptions) (quota.UsageStats, error)","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/evaluator.go","code":"// UsageStats calculates aggregate usage for the object.\nfunc (o *objectCountEvaluator) UsageStats(options quota.UsageStatsOptions) (quota.UsageStats, error) {\n\treturn CalculateUsageStats(options, o.listFuncByNamespace, MatchesNoScopeFunc, o.Usage)\n}","line":{"from":293,"to":296}} {"id":100017705,"name":"NewObjectCountEvaluator","signature":"func NewObjectCountEvaluator(","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/evaluator.go","code":"// NewObjectCountEvaluator returns an evaluator that can perform generic\n// object quota counting. It allows an optional alias for backwards compatibility\n// purposes for the legacy object counting names in quota. Unless its supporting\n// backward compatibility, alias should not be used.\nfunc NewObjectCountEvaluator(\n\tgroupResource schema.GroupResource, listFuncByNamespace ListFuncByNamespace,\n\talias corev1.ResourceName) quota.Evaluator {\n\n\tresourceNames := []corev1.ResourceName{ObjectCountQuotaResourceNameFor(groupResource)}\n\tif len(alias) \u003e 0 {\n\t\tresourceNames = append(resourceNames, alias)\n\t}\n\n\treturn \u0026objectCountEvaluator{\n\t\tgroupResource: groupResource,\n\t\tlistFuncByNamespace: listFuncByNamespace,\n\t\tresourceNames: resourceNames,\n\t}\n}","line":{"from":301,"to":319}} {"id":100017706,"name":"NewRegistry","signature":"func NewRegistry(evaluators []quota.Evaluator) quota.Registry","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/registry.go","code":"// NewRegistry creates a simple registry with initial list of evaluators\nfunc NewRegistry(evaluators []quota.Evaluator) quota.Registry {\n\treturn \u0026simpleRegistry{\n\t\tevaluators: evaluatorsByGroupResource(evaluators),\n\t}\n}","line":{"from":33,"to":38}} {"id":100017707,"name":"Add","signature":"func (r *simpleRegistry) Add(e quota.Evaluator)","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/registry.go","code":"func (r *simpleRegistry) Add(e quota.Evaluator) {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\tr.evaluators[e.GroupResource()] = e\n}","line":{"from":40,"to":44}} {"id":100017708,"name":"Remove","signature":"func (r *simpleRegistry) Remove(e quota.Evaluator)","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/registry.go","code":"func (r *simpleRegistry) Remove(e quota.Evaluator) {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\tdelete(r.evaluators, e.GroupResource())\n}","line":{"from":46,"to":50}} {"id":100017709,"name":"Get","signature":"func (r *simpleRegistry) Get(gr schema.GroupResource) quota.Evaluator","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/registry.go","code":"func (r *simpleRegistry) Get(gr schema.GroupResource) quota.Evaluator {\n\tr.lock.RLock()\n\tdefer r.lock.RUnlock()\n\treturn r.evaluators[gr]\n}","line":{"from":52,"to":56}} {"id":100017710,"name":"List","signature":"func (r *simpleRegistry) List() []quota.Evaluator","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/registry.go","code":"func (r *simpleRegistry) List() []quota.Evaluator {\n\tr.lock.RLock()\n\tdefer r.lock.RUnlock()\n\n\treturn evaluatorsList(r.evaluators)\n}","line":{"from":58,"to":63}} {"id":100017711,"name":"evaluatorsByGroupResource","signature":"func evaluatorsByGroupResource(items []quota.Evaluator) map[schema.GroupResource]quota.Evaluator","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/registry.go","code":"// evaluatorsByGroupResource converts a list of evaluators to a map by group resource.\nfunc evaluatorsByGroupResource(items []quota.Evaluator) map[schema.GroupResource]quota.Evaluator {\n\tresult := map[schema.GroupResource]quota.Evaluator{}\n\tfor _, item := range items {\n\t\tresult[item.GroupResource()] = item\n\t}\n\treturn result\n}","line":{"from":65,"to":72}} {"id":100017712,"name":"evaluatorsList","signature":"func evaluatorsList(input map[schema.GroupResource]quota.Evaluator) []quota.Evaluator","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/generic/registry.go","code":"// evaluatorsList converts a map of evaluators to list\nfunc evaluatorsList(input map[schema.GroupResource]quota.Evaluator) []quota.Evaluator {\n\tvar result []quota.Evaluator\n\tfor _, item := range input {\n\t\tresult = append(result, item)\n\t}\n\treturn result\n}","line":{"from":74,"to":81}} {"id":100017713,"name":"Equals","signature":"func Equals(a corev1.ResourceList, b corev1.ResourceList) bool","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/resources.go","code":"// Equals returns true if the two lists are equivalent\nfunc Equals(a corev1.ResourceList, b corev1.ResourceList) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\n\tfor key, value1 := range a {\n\t\tvalue2, found := b[key]\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t\tif value1.Cmp(value2) != 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}","line":{"from":29,"to":46}} {"id":100017714,"name":"LessThanOrEqual","signature":"func LessThanOrEqual(a corev1.ResourceList, b corev1.ResourceList) (bool, []corev1.ResourceName)","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/resources.go","code":"// LessThanOrEqual returns true if a \u003c b for each key in b\n// If false, it returns the keys in a that exceeded b\nfunc LessThanOrEqual(a corev1.ResourceList, b corev1.ResourceList) (bool, []corev1.ResourceName) {\n\tresult := true\n\tresourceNames := []corev1.ResourceName{}\n\tfor key, value := range b {\n\t\tif other, found := a[key]; found {\n\t\t\tif other.Cmp(value) \u003e 0 {\n\t\t\t\tresult = false\n\t\t\t\tresourceNames = append(resourceNames, key)\n\t\t\t}\n\t\t}\n\t}\n\treturn result, resourceNames\n}","line":{"from":48,"to":62}} {"id":100017715,"name":"Max","signature":"func Max(a corev1.ResourceList, b corev1.ResourceList) corev1.ResourceList","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/resources.go","code":"// Max returns the result of Max(a, b) for each named resource\nfunc Max(a corev1.ResourceList, b corev1.ResourceList) corev1.ResourceList {\n\tresult := corev1.ResourceList{}\n\tfor key, value := range a {\n\t\tif other, found := b[key]; found {\n\t\t\tif value.Cmp(other) \u003c= 0 {\n\t\t\t\tresult[key] = other.DeepCopy()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tresult[key] = value.DeepCopy()\n\t}\n\tfor key, value := range b {\n\t\tif _, found := result[key]; !found {\n\t\t\tresult[key] = value.DeepCopy()\n\t\t}\n\t}\n\treturn result\n}","line":{"from":64,"to":82}} {"id":100017716,"name":"Add","signature":"func Add(a corev1.ResourceList, b corev1.ResourceList) corev1.ResourceList","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/resources.go","code":"// Add returns the result of a + b for each named resource\nfunc Add(a corev1.ResourceList, b corev1.ResourceList) corev1.ResourceList {\n\tresult := corev1.ResourceList{}\n\tfor key, value := range a {\n\t\tquantity := value.DeepCopy()\n\t\tif other, found := b[key]; found {\n\t\t\tquantity.Add(other)\n\t\t}\n\t\tresult[key] = quantity\n\t}\n\tfor key, value := range b {\n\t\tif _, found := result[key]; !found {\n\t\t\tresult[key] = value.DeepCopy()\n\t\t}\n\t}\n\treturn result\n}","line":{"from":84,"to":100}} {"id":100017717,"name":"SubtractWithNonNegativeResult","signature":"func SubtractWithNonNegativeResult(a corev1.ResourceList, b corev1.ResourceList) corev1.ResourceList","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/resources.go","code":"// SubtractWithNonNegativeResult - subtracts and returns result of a - b but\n// makes sure we don't return negative values to prevent negative resource usage.\nfunc SubtractWithNonNegativeResult(a corev1.ResourceList, b corev1.ResourceList) corev1.ResourceList {\n\tzero := resource.MustParse(\"0\")\n\n\tresult := corev1.ResourceList{}\n\tfor key, value := range a {\n\t\tquantity := value.DeepCopy()\n\t\tif other, found := b[key]; found {\n\t\t\tquantity.Sub(other)\n\t\t}\n\t\tif quantity.Cmp(zero) \u003e 0 {\n\t\t\tresult[key] = quantity\n\t\t} else {\n\t\t\tresult[key] = zero\n\t\t}\n\t}\n\n\tfor key := range b {\n\t\tif _, found := result[key]; !found {\n\t\t\tresult[key] = zero\n\t\t}\n\t}\n\treturn result\n}","line":{"from":102,"to":126}} {"id":100017718,"name":"Subtract","signature":"func Subtract(a corev1.ResourceList, b corev1.ResourceList) corev1.ResourceList","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/resources.go","code":"// Subtract returns the result of a - b for each named resource\nfunc Subtract(a corev1.ResourceList, b corev1.ResourceList) corev1.ResourceList {\n\tresult := corev1.ResourceList{}\n\tfor key, value := range a {\n\t\tquantity := value.DeepCopy()\n\t\tif other, found := b[key]; found {\n\t\t\tquantity.Sub(other)\n\t\t}\n\t\tresult[key] = quantity\n\t}\n\tfor key, value := range b {\n\t\tif _, found := result[key]; !found {\n\t\t\tquantity := value.DeepCopy()\n\t\t\tquantity.Neg()\n\t\t\tresult[key] = quantity\n\t\t}\n\t}\n\treturn result\n}","line":{"from":128,"to":146}} {"id":100017719,"name":"Mask","signature":"func Mask(resources corev1.ResourceList, names []corev1.ResourceName) corev1.ResourceList","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/resources.go","code":"// Mask returns a new resource list that only has the values with the specified names\nfunc Mask(resources corev1.ResourceList, names []corev1.ResourceName) corev1.ResourceList {\n\tnameSet := ToSet(names)\n\tresult := corev1.ResourceList{}\n\tfor key, value := range resources {\n\t\tif nameSet.Has(string(key)) {\n\t\t\tresult[key] = value.DeepCopy()\n\t\t}\n\t}\n\treturn result\n}","line":{"from":148,"to":158}} {"id":100017720,"name":"ResourceNames","signature":"func ResourceNames(resources corev1.ResourceList) []corev1.ResourceName","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/resources.go","code":"// ResourceNames returns a list of all resource names in the ResourceList\nfunc ResourceNames(resources corev1.ResourceList) []corev1.ResourceName {\n\tresult := []corev1.ResourceName{}\n\tfor resourceName := range resources {\n\t\tresult = append(result, resourceName)\n\t}\n\treturn result\n}","line":{"from":160,"to":167}} {"id":100017721,"name":"Contains","signature":"func Contains(items []corev1.ResourceName, item corev1.ResourceName) bool","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/resources.go","code":"// Contains returns true if the specified item is in the list of items\nfunc Contains(items []corev1.ResourceName, item corev1.ResourceName) bool {\n\tfor _, i := range items {\n\t\tif i == item {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":169,"to":177}} {"id":100017722,"name":"ContainsPrefix","signature":"func ContainsPrefix(prefixSet []string, item corev1.ResourceName) bool","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/resources.go","code":"// ContainsPrefix returns true if the specified item has a prefix that contained in given prefix Set\nfunc ContainsPrefix(prefixSet []string, item corev1.ResourceName) bool {\n\tfor _, prefix := range prefixSet {\n\t\tif strings.HasPrefix(string(item), prefix) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":179,"to":187}} {"id":100017723,"name":"Intersection","signature":"func Intersection(a []corev1.ResourceName, b []corev1.ResourceName) []corev1.ResourceName","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/resources.go","code":"// Intersection returns the intersection of both list of resources, deduped and sorted\nfunc Intersection(a []corev1.ResourceName, b []corev1.ResourceName) []corev1.ResourceName {\n\tresult := make([]corev1.ResourceName, 0, len(a))\n\tfor _, item := range a {\n\t\tif Contains(result, item) {\n\t\t\tcontinue\n\t\t}\n\t\tif !Contains(b, item) {\n\t\t\tcontinue\n\t\t}\n\t\tresult = append(result, item)\n\t}\n\tsort.Slice(result, func(i, j int) bool { return result[i] \u003c result[j] })\n\treturn result\n}","line":{"from":189,"to":203}} {"id":100017724,"name":"Difference","signature":"func Difference(a []corev1.ResourceName, b []corev1.ResourceName) []corev1.ResourceName","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/resources.go","code":"// Difference returns the list of resources resulting from a-b, deduped and sorted\nfunc Difference(a []corev1.ResourceName, b []corev1.ResourceName) []corev1.ResourceName {\n\tresult := make([]corev1.ResourceName, 0, len(a))\n\tfor _, item := range a {\n\t\tif Contains(b, item) || Contains(result, item) {\n\t\t\tcontinue\n\t\t}\n\t\tresult = append(result, item)\n\t}\n\tsort.Slice(result, func(i, j int) bool { return result[i] \u003c result[j] })\n\treturn result\n}","line":{"from":205,"to":216}} {"id":100017725,"name":"IsZero","signature":"func IsZero(a corev1.ResourceList) bool","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/resources.go","code":"// IsZero returns true if each key maps to the quantity value 0\nfunc IsZero(a corev1.ResourceList) bool {\n\tzero := resource.MustParse(\"0\")\n\tfor _, v := range a {\n\t\tif v.Cmp(zero) != 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":218,"to":227}} {"id":100017726,"name":"RemoveZeros","signature":"func RemoveZeros(a corev1.ResourceList) corev1.ResourceList","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/resources.go","code":"// RemoveZeros returns a new resource list that only has no zero values\nfunc RemoveZeros(a corev1.ResourceList) corev1.ResourceList {\n\tresult := corev1.ResourceList{}\n\tfor key, value := range a {\n\t\tif !value.IsZero() {\n\t\t\tresult[key] = value\n\t\t}\n\t}\n\treturn result\n}","line":{"from":229,"to":238}} {"id":100017727,"name":"IsNegative","signature":"func IsNegative(a corev1.ResourceList) []corev1.ResourceName","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/resources.go","code":"// IsNegative returns the set of resource names that have a negative value.\nfunc IsNegative(a corev1.ResourceList) []corev1.ResourceName {\n\tresults := []corev1.ResourceName{}\n\tzero := resource.MustParse(\"0\")\n\tfor k, v := range a {\n\t\tif v.Cmp(zero) \u003c 0 {\n\t\t\tresults = append(results, k)\n\t\t}\n\t}\n\treturn results\n}","line":{"from":240,"to":250}} {"id":100017728,"name":"ToSet","signature":"func ToSet(resourceNames []corev1.ResourceName) sets.String","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/resources.go","code":"// ToSet takes a list of resource names and converts to a string set\nfunc ToSet(resourceNames []corev1.ResourceName) sets.String {\n\tresult := sets.NewString()\n\tfor _, resourceName := range resourceNames {\n\t\tresult.Insert(string(resourceName))\n\t}\n\treturn result\n}","line":{"from":252,"to":259}} {"id":100017729,"name":"CalculateUsage","signature":"func CalculateUsage(namespaceName string, scopes []corev1.ResourceQuotaScope, hardLimits corev1.ResourceList, registry Registry, scopeSelector *corev1.ScopeSelector) (corev1.ResourceList, error)","file":"staging/src/k8s.io/apiserver/pkg/quota/v1/resources.go","code":"// CalculateUsage calculates and returns the requested ResourceList usage.\n// If an error is returned, usage only contains the resources which encountered no calculation errors.\nfunc CalculateUsage(namespaceName string, scopes []corev1.ResourceQuotaScope, hardLimits corev1.ResourceList, registry Registry, scopeSelector *corev1.ScopeSelector) (corev1.ResourceList, error) {\n\t// find the intersection between the hard resources on the quota\n\t// and the resources this controller can track to know what we can\n\t// look to measure updated usage stats for\n\thardResources := ResourceNames(hardLimits)\n\tpotentialResources := []corev1.ResourceName{}\n\tevaluators := registry.List()\n\tfor _, evaluator := range evaluators {\n\t\tpotentialResources = append(potentialResources, evaluator.MatchingResources(hardResources)...)\n\t}\n\t// NOTE: the intersection just removes duplicates since the evaluator match intersects with hard\n\tmatchedResources := Intersection(hardResources, potentialResources)\n\n\terrors := []error{}\n\n\t// sum the observed usage from each evaluator\n\tnewUsage := corev1.ResourceList{}\n\tfor _, evaluator := range evaluators {\n\t\t// only trigger the evaluator if it matches a resource in the quota, otherwise, skip calculating anything\n\t\tintersection := evaluator.MatchingResources(matchedResources)\n\t\tif len(intersection) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tusageStatsOptions := UsageStatsOptions{Namespace: namespaceName, Scopes: scopes, Resources: intersection, ScopeSelector: scopeSelector}\n\t\tstats, err := evaluator.UsageStats(usageStatsOptions)\n\t\tif err != nil {\n\t\t\t// remember the error\n\t\t\terrors = append(errors, err)\n\t\t\t// exclude resources which encountered calculation errors\n\t\t\tmatchedResources = Difference(matchedResources, intersection)\n\t\t\tcontinue\n\t\t}\n\t\tnewUsage = Add(newUsage, stats.Used)\n\t}\n\n\t// mask the observed usage to only the set of resources tracked by this quota\n\t// merge our observed usage with the quota usage status\n\t// if the new usage is different than the last usage, we will need to do an update\n\tnewUsage = Mask(newUsage, matchedResources)\n\treturn newUsage, utilerrors.NewAggregate(errors)\n}","line":{"from":261,"to":304}} {"id":100017730,"name":"ObjectMetaFieldsSet","signature":"func ObjectMetaFieldsSet(objectMeta *metav1.ObjectMeta, hasNamespaceField bool) fields.Set","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/matcher.go","code":"// ObjectMetaFieldsSet returns a fields that represent the ObjectMeta.\nfunc ObjectMetaFieldsSet(objectMeta *metav1.ObjectMeta, hasNamespaceField bool) fields.Set {\n\tif !hasNamespaceField {\n\t\treturn fields.Set{\n\t\t\t\"metadata.name\": objectMeta.Name,\n\t\t}\n\t}\n\treturn fields.Set{\n\t\t\"metadata.name\": objectMeta.Name,\n\t\t\"metadata.namespace\": objectMeta.Namespace,\n\t}\n}","line":{"from":24,"to":35}} {"id":100017731,"name":"AddObjectMetaFieldsSet","signature":"func AddObjectMetaFieldsSet(source fields.Set, objectMeta *metav1.ObjectMeta, hasNamespaceField bool) fields.Set","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/matcher.go","code":"// AdObjectMetaField add fields that represent the ObjectMeta to source.\nfunc AddObjectMetaFieldsSet(source fields.Set, objectMeta *metav1.ObjectMeta, hasNamespaceField bool) fields.Set {\n\tsource[\"metadata.name\"] = objectMeta.Name\n\tif hasNamespaceField {\n\t\tsource[\"metadata.namespace\"] = objectMeta.Namespace\n\t}\n\treturn source\n}","line":{"from":37,"to":44}} {"id":100017732,"name":"MergeFieldsSets","signature":"func MergeFieldsSets(source fields.Set, fragment fields.Set) fields.Set","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/matcher.go","code":"// MergeFieldsSets merges a fields'set from fragment into the source.\nfunc MergeFieldsSets(source fields.Set, fragment fields.Set) fields.Set {\n\tfor k, value := range fragment {\n\t\tsource[k] = value\n\t}\n\treturn source\n}","line":{"from":46,"to":52}} {"id":100017733,"name":"GetRESTOptions","signature":"func (opts RESTOptions) GetRESTOptions(schema.GroupResource) (RESTOptions, error)","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/options.go","code":"// Implement RESTOptionsGetter so that RESTOptions can directly be used when available (i.e. tests)\nfunc (opts RESTOptions) GetRESTOptions(schema.GroupResource) (RESTOptions, error) {\n\treturn opts, nil\n}","line":{"from":41,"to":44}} {"id":100017734,"name":"newDecoratedWatcher","signature":"func newDecoratedWatcher(ctx context.Context, w watch.Interface, decorator func(runtime.Object)) *decoratedWatcher","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/decorated_watcher.go","code":"func newDecoratedWatcher(ctx context.Context, w watch.Interface, decorator func(runtime.Object)) *decoratedWatcher {\n\tctx, cancel := context.WithCancel(ctx)\n\td := \u0026decoratedWatcher{\n\t\tw: w,\n\t\tdecorator: decorator,\n\t\tcancel: cancel,\n\t\tresultCh: make(chan watch.Event),\n\t}\n\tgo d.run(ctx)\n\treturn d\n}","line":{"from":32,"to":42}} {"id":100017735,"name":"run","signature":"func (d *decoratedWatcher) run(ctx context.Context)","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/decorated_watcher.go","code":"// run decorates watch events from the underlying watcher until its result channel\n// is closed or the passed in context is done.\n// When run() returns, decoratedWatcher#resultCh is closed.\nfunc (d *decoratedWatcher) run(ctx context.Context) {\n\tvar recv, send watch.Event\n\tvar ok bool\n\tdefer close(d.resultCh)\n\tfor {\n\t\tselect {\n\t\tcase recv, ok = \u003c-d.w.ResultChan():\n\t\t\tif !ok {\n\t\t\t\t// The underlying channel was closed, cancel our context\n\t\t\t\td.cancel()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tswitch recv.Type {\n\t\t\tcase watch.Added, watch.Modified, watch.Deleted, watch.Bookmark:\n\t\t\t\td.decorator(recv.Object)\n\t\t\t\tsend = recv\n\t\t\tcase watch.Error:\n\t\t\t\tsend = recv\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase d.resultCh \u003c- send:\n\t\t\t\t// propagated event successfully\n\t\t\tcase \u003c-ctx.Done():\n\t\t\t\t// context timed out or was cancelled, stop the underlying watcher\n\t\t\t\td.w.Stop()\n\t\t\t\treturn\n\t\t\t}\n\t\tcase \u003c-ctx.Done():\n\t\t\t// context timed out or was cancelled, stop the underlying watcher\n\t\t\td.w.Stop()\n\t\t\treturn\n\t\t}\n\t}\n}","line":{"from":44,"to":80}} {"id":100017736,"name":"Stop","signature":"func (d *decoratedWatcher) Stop()","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/decorated_watcher.go","code":"func (d *decoratedWatcher) Stop() {\n\t// stop the underlying watcher\n\td.w.Stop()\n\t// cancel our context\n\td.cancel()\n}","line":{"from":82,"to":87}} {"id":100017737,"name":"ResultChan","signature":"func (d *decoratedWatcher) ResultChan() \u003c-chan watch.Event","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/decorated_watcher.go","code":"func (d *decoratedWatcher) ResultChan() \u003c-chan watch.Event {\n\treturn d.resultCh\n}","line":{"from":89,"to":91}} {"id":100017738,"name":"Versioner","signature":"func (s *DryRunnableStorage) Versioner() storage.Versioner","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/dryrun.go","code":"func (s *DryRunnableStorage) Versioner() storage.Versioner {\n\treturn s.Storage.Versioner()\n}","line":{"from":32,"to":34}} {"id":100017739,"name":"Create","signature":"func (s *DryRunnableStorage) Create(ctx context.Context, key string, obj, out runtime.Object, ttl uint64, dryRun bool) error","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/dryrun.go","code":"func (s *DryRunnableStorage) Create(ctx context.Context, key string, obj, out runtime.Object, ttl uint64, dryRun bool) error {\n\tif dryRun {\n\t\tif err := s.Storage.Get(ctx, key, storage.GetOptions{}, out); err == nil {\n\t\t\treturn storage.NewKeyExistsError(key, 0)\n\t\t}\n\t\treturn s.copyInto(obj, out)\n\t}\n\treturn s.Storage.Create(ctx, key, obj, out, ttl)\n}","line":{"from":36,"to":44}} {"id":100017740,"name":"Delete","signature":"func (s *DryRunnableStorage) Delete(ctx context.Context, key string, out runtime.Object, preconditions *storage.Preconditions, deleteValidation storage.ValidateObjectFunc, dryRun bool, cachedExistingObject runtime.Object) error","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/dryrun.go","code":"func (s *DryRunnableStorage) Delete(ctx context.Context, key string, out runtime.Object, preconditions *storage.Preconditions, deleteValidation storage.ValidateObjectFunc, dryRun bool, cachedExistingObject runtime.Object) error {\n\tif dryRun {\n\t\tif err := s.Storage.Get(ctx, key, storage.GetOptions{}, out); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := preconditions.Check(key, out); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn deleteValidation(ctx, out)\n\t}\n\treturn s.Storage.Delete(ctx, key, out, preconditions, deleteValidation, cachedExistingObject)\n}","line":{"from":46,"to":57}} {"id":100017741,"name":"Watch","signature":"func (s *DryRunnableStorage) Watch(ctx context.Context, key string, opts storage.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/dryrun.go","code":"func (s *DryRunnableStorage) Watch(ctx context.Context, key string, opts storage.ListOptions) (watch.Interface, error) {\n\treturn s.Storage.Watch(ctx, key, opts)\n}","line":{"from":59,"to":61}} {"id":100017742,"name":"Get","signature":"func (s *DryRunnableStorage) Get(ctx context.Context, key string, opts storage.GetOptions, objPtr runtime.Object) error","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/dryrun.go","code":"func (s *DryRunnableStorage) Get(ctx context.Context, key string, opts storage.GetOptions, objPtr runtime.Object) error {\n\treturn s.Storage.Get(ctx, key, opts, objPtr)\n}","line":{"from":63,"to":65}} {"id":100017743,"name":"GetList","signature":"func (s *DryRunnableStorage) GetList(ctx context.Context, key string, opts storage.ListOptions, listObj runtime.Object) error","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/dryrun.go","code":"func (s *DryRunnableStorage) GetList(ctx context.Context, key string, opts storage.ListOptions, listObj runtime.Object) error {\n\treturn s.Storage.GetList(ctx, key, opts, listObj)\n}","line":{"from":67,"to":69}} {"id":100017744,"name":"GuaranteedUpdate","signature":"func (s *DryRunnableStorage) GuaranteedUpdate(","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/dryrun.go","code":"func (s *DryRunnableStorage) GuaranteedUpdate(\n\tctx context.Context, key string, destination runtime.Object, ignoreNotFound bool,\n\tpreconditions *storage.Preconditions, tryUpdate storage.UpdateFunc, dryRun bool, cachedExistingObject runtime.Object) error {\n\tif dryRun {\n\t\terr := s.Storage.Get(ctx, key, storage.GetOptions{IgnoreNotFound: ignoreNotFound}, destination)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = preconditions.Check(key, destination)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\trev, err := s.Versioner().ObjectResourceVersion(destination)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tupdated, _, err := tryUpdate(destination, storage.ResponseMeta{ResourceVersion: rev})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn s.copyInto(updated, destination)\n\t}\n\treturn s.Storage.GuaranteedUpdate(ctx, key, destination, ignoreNotFound, preconditions, tryUpdate, cachedExistingObject)\n}","line":{"from":71,"to":94}} {"id":100017745,"name":"Count","signature":"func (s *DryRunnableStorage) Count(key string) (int64, error)","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/dryrun.go","code":"func (s *DryRunnableStorage) Count(key string) (int64, error) {\n\treturn s.Storage.Count(key)\n}","line":{"from":96,"to":98}} {"id":100017746,"name":"copyInto","signature":"func (s *DryRunnableStorage) copyInto(in, out runtime.Object) error","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/dryrun.go","code":"func (s *DryRunnableStorage) copyInto(in, out runtime.Object) error {\n\tvar data []byte\n\n\tdata, err := runtime.Encode(s.Codec, in)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, _, err = s.Codec.Decode(data, nil, out)\n\treturn err\n}","line":{"from":100,"to":109}} {"id":100017747,"name":"StorageWithCacher","signature":"func StorageWithCacher() generic.StorageDecorator","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/storage_factory.go","code":"// Creates a cacher based given storageConfig.\nfunc StorageWithCacher() generic.StorageDecorator {\n\treturn func(\n\t\tstorageConfig *storagebackend.ConfigForResource,\n\t\tresourcePrefix string,\n\t\tkeyFunc func(obj runtime.Object) (string, error),\n\t\tnewFunc func() runtime.Object,\n\t\tnewListFunc func() runtime.Object,\n\t\tgetAttrsFunc storage.AttrFunc,\n\t\ttriggerFuncs storage.IndexerFuncs,\n\t\tindexers *cache.Indexers) (storage.Interface, factory.DestroyFunc, error) {\n\n\t\ts, d, err := generic.NewRawStorage(storageConfig, newFunc)\n\t\tif err != nil {\n\t\t\treturn s, d, err\n\t\t}\n\t\tif klogV := klog.V(5); klogV.Enabled() {\n\t\t\t//nolint:logcheck // It complains about the key/value pairs because it cannot check them.\n\t\t\tklogV.InfoS(\"Storage caching is enabled\", objectTypeToArgs(newFunc())...)\n\t\t}\n\n\t\tcacherConfig := cacherstorage.Config{\n\t\t\tStorage: s,\n\t\t\tVersioner: storage.APIObjectVersioner{},\n\t\t\tGroupResource: storageConfig.GroupResource,\n\t\t\tResourcePrefix: resourcePrefix,\n\t\t\tKeyFunc: keyFunc,\n\t\t\tNewFunc: newFunc,\n\t\t\tNewListFunc: newListFunc,\n\t\t\tGetAttrsFunc: getAttrsFunc,\n\t\t\tIndexerFuncs: triggerFuncs,\n\t\t\tIndexers: indexers,\n\t\t\tCodec: storageConfig.Codec,\n\t\t}\n\t\tcacher, err := cacherstorage.NewCacherFromConfig(cacherConfig)\n\t\tif err != nil {\n\t\t\treturn nil, func() {}, err\n\t\t}\n\t\tvar once sync.Once\n\t\tdestroyFunc := func() {\n\t\t\tonce.Do(func() {\n\t\t\t\tcacher.Stop()\n\t\t\t\td()\n\t\t\t})\n\t\t}\n\n\t\treturn cacher, destroyFunc, nil\n\t}\n}","line":{"from":35,"to":83}} {"id":100017748,"name":"objectTypeToArgs","signature":"func objectTypeToArgs(obj runtime.Object) []interface{}","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/storage_factory.go","code":"func objectTypeToArgs(obj runtime.Object) []interface{} {\n\t// special-case unstructured objects that tell us their apiVersion/kind\n\tif u, isUnstructured := obj.(*unstructured.Unstructured); isUnstructured {\n\t\tif apiVersion, kind := u.GetAPIVersion(), u.GetKind(); len(apiVersion) \u003e 0 \u0026\u0026 len(kind) \u003e 0 {\n\t\t\treturn []interface{}{\"apiVersion\", apiVersion, \"kind\", kind}\n\t\t}\n\t}\n\n\t// otherwise just return the type\n\treturn []interface{}{\"type\", fmt.Sprintf(\"%T\", obj)}\n}","line":{"from":85,"to":95}} {"id":100017749,"name":"NamespaceKeyRootFunc","signature":"func NamespaceKeyRootFunc(ctx context.Context, prefix string) string","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// NamespaceKeyRootFunc is the default function for constructing storage paths\n// to resource directories enforcing namespace rules.\nfunc NamespaceKeyRootFunc(ctx context.Context, prefix string) string {\n\tkey := prefix\n\tns, ok := genericapirequest.NamespaceFrom(ctx)\n\tif ok \u0026\u0026 len(ns) \u003e 0 {\n\t\tkey = key + \"/\" + ns\n\t}\n\treturn key\n}","line":{"from":243,"to":252}} {"id":100017750,"name":"NamespaceKeyFunc","signature":"func NamespaceKeyFunc(ctx context.Context, prefix string, name string) (string, error)","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// NamespaceKeyFunc is the default function for constructing storage paths to\n// a resource relative to the given prefix enforcing namespace rules. If the\n// context does not contain a namespace, it errors.\nfunc NamespaceKeyFunc(ctx context.Context, prefix string, name string) (string, error) {\n\tkey := NamespaceKeyRootFunc(ctx, prefix)\n\tns, ok := genericapirequest.NamespaceFrom(ctx)\n\tif !ok || len(ns) == 0 {\n\t\treturn \"\", apierrors.NewBadRequest(\"Namespace parameter required.\")\n\t}\n\tif len(name) == 0 {\n\t\treturn \"\", apierrors.NewBadRequest(\"Name parameter required.\")\n\t}\n\tif msgs := path.IsValidPathSegmentName(name); len(msgs) != 0 {\n\t\treturn \"\", apierrors.NewBadRequest(fmt.Sprintf(\"Name parameter invalid: %q: %s\", name, strings.Join(msgs, \";\")))\n\t}\n\tkey = key + \"/\" + name\n\treturn key, nil\n}","line":{"from":254,"to":271}} {"id":100017751,"name":"NoNamespaceKeyFunc","signature":"func NoNamespaceKeyFunc(ctx context.Context, prefix string, name string) (string, error)","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// NoNamespaceKeyFunc is the default function for constructing storage paths\n// to a resource relative to the given prefix without a namespace.\nfunc NoNamespaceKeyFunc(ctx context.Context, prefix string, name string) (string, error) {\n\tif len(name) == 0 {\n\t\treturn \"\", apierrors.NewBadRequest(\"Name parameter required.\")\n\t}\n\tif msgs := path.IsValidPathSegmentName(name); len(msgs) != 0 {\n\t\treturn \"\", apierrors.NewBadRequest(fmt.Sprintf(\"Name parameter invalid: %q: %s\", name, strings.Join(msgs, \";\")))\n\t}\n\tkey := prefix + \"/\" + name\n\treturn key, nil\n}","line":{"from":273,"to":284}} {"id":100017752,"name":"New","signature":"func (e *Store) New() runtime.Object","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// New implements RESTStorage.New.\nfunc (e *Store) New() runtime.Object {\n\treturn e.NewFunc()\n}","line":{"from":286,"to":289}} {"id":100017753,"name":"Destroy","signature":"func (e *Store) Destroy()","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// Destroy cleans up its resources on shutdown.\nfunc (e *Store) Destroy() {\n\tif e.DestroyFunc != nil {\n\t\te.DestroyFunc()\n\t}\n}","line":{"from":291,"to":296}} {"id":100017754,"name":"NewList","signature":"func (e *Store) NewList() runtime.Object","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// NewList implements rest.Lister.\nfunc (e *Store) NewList() runtime.Object {\n\treturn e.NewListFunc()\n}","line":{"from":298,"to":301}} {"id":100017755,"name":"NamespaceScoped","signature":"func (e *Store) NamespaceScoped() bool","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// NamespaceScoped indicates whether the resource is namespaced\nfunc (e *Store) NamespaceScoped() bool {\n\tif e.CreateStrategy != nil {\n\t\treturn e.CreateStrategy.NamespaceScoped()\n\t}\n\tif e.UpdateStrategy != nil {\n\t\treturn e.UpdateStrategy.NamespaceScoped()\n\t}\n\n\tpanic(\"programmer error: no CRUD for resource, override NamespaceScoped too\")\n}","line":{"from":303,"to":313}} {"id":100017756,"name":"GetCreateStrategy","signature":"func (e *Store) GetCreateStrategy() rest.RESTCreateStrategy","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// GetCreateStrategy implements GenericStore.\nfunc (e *Store) GetCreateStrategy() rest.RESTCreateStrategy {\n\treturn e.CreateStrategy\n}","line":{"from":315,"to":318}} {"id":100017757,"name":"GetUpdateStrategy","signature":"func (e *Store) GetUpdateStrategy() rest.RESTUpdateStrategy","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// GetUpdateStrategy implements GenericStore.\nfunc (e *Store) GetUpdateStrategy() rest.RESTUpdateStrategy {\n\treturn e.UpdateStrategy\n}","line":{"from":320,"to":323}} {"id":100017758,"name":"GetDeleteStrategy","signature":"func (e *Store) GetDeleteStrategy() rest.RESTDeleteStrategy","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// GetDeleteStrategy implements GenericStore.\nfunc (e *Store) GetDeleteStrategy() rest.RESTDeleteStrategy {\n\treturn e.DeleteStrategy\n}","line":{"from":325,"to":328}} {"id":100017759,"name":"List","signature":"func (e *Store) List(ctx context.Context, options *metainternalversion.ListOptions) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// List returns a list of items matching labels and field according to the\n// store's PredicateFunc.\nfunc (e *Store) List(ctx context.Context, options *metainternalversion.ListOptions) (runtime.Object, error) {\n\tlabel := labels.Everything()\n\tif options != nil \u0026\u0026 options.LabelSelector != nil {\n\t\tlabel = options.LabelSelector\n\t}\n\tfield := fields.Everything()\n\tif options != nil \u0026\u0026 options.FieldSelector != nil {\n\t\tfield = options.FieldSelector\n\t}\n\tout, err := e.ListPredicate(ctx, e.PredicateFunc(label, field), options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif e.Decorator != nil {\n\t\te.Decorator(out)\n\t}\n\treturn out, nil\n}","line":{"from":330,"to":349}} {"id":100017760,"name":"ListPredicate","signature":"func (e *Store) ListPredicate(ctx context.Context, p storage.SelectionPredicate, options *metainternalversion.ListOptions) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// ListPredicate returns a list of all the items matching the given\n// SelectionPredicate.\nfunc (e *Store) ListPredicate(ctx context.Context, p storage.SelectionPredicate, options *metainternalversion.ListOptions) (runtime.Object, error) {\n\tif options == nil {\n\t\t// By default we should serve the request from etcd.\n\t\toptions = \u0026metainternalversion.ListOptions{ResourceVersion: \"\"}\n\t}\n\tp.Limit = options.Limit\n\tp.Continue = options.Continue\n\tlist := e.NewListFunc()\n\tqualifiedResource := e.qualifiedResourceFromContext(ctx)\n\tstorageOpts := storage.ListOptions{\n\t\tResourceVersion: options.ResourceVersion,\n\t\tResourceVersionMatch: options.ResourceVersionMatch,\n\t\tPredicate: p,\n\t\tRecursive: true,\n\t}\n\n\t// if we're not already namespace-scoped, see if the field selector narrows the scope of the watch\n\tif requestNamespace, _ := genericapirequest.NamespaceFrom(ctx); len(requestNamespace) == 0 {\n\t\tif selectorNamespace, ok := p.MatchesSingleNamespace(); ok {\n\t\t\tif len(validation.ValidateNamespaceName(selectorNamespace, false)) == 0 {\n\t\t\t\tctx = genericapirequest.WithNamespace(ctx, selectorNamespace)\n\t\t\t}\n\t\t}\n\t}\n\n\tif name, ok := p.MatchesSingle(); ok {\n\t\tif key, err := e.KeyFunc(ctx, name); err == nil {\n\t\t\tstorageOpts.Recursive = false\n\t\t\terr := e.Storage.GetList(ctx, key, storageOpts, list)\n\t\t\treturn list, storeerr.InterpretListError(err, qualifiedResource)\n\t\t}\n\t\t// if we cannot extract a key based on the current context, the optimization is skipped\n\t}\n\n\terr := e.Storage.GetList(ctx, e.KeyRootFunc(ctx), storageOpts, list)\n\treturn list, storeerr.InterpretListError(err, qualifiedResource)\n}","line":{"from":351,"to":389}} {"id":100017761,"name":"finishNothing","signature":"func finishNothing(context.Context, bool) {}","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// finishNothing is a do-nothing FinishFunc.\nfunc finishNothing(context.Context, bool) {}","line":{"from":391,"to":392}} {"id":100017762,"name":"Create","signature":"func (e *Store) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// Create inserts a new item according to the unique key from the object.\n// Note that registries may mutate the input object (e.g. in the strategy\n// hooks). Tests which call this might want to call DeepCopy if they expect to\n// be able to examine the input and output objects for differences.\nfunc (e *Store) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {\n\tvar finishCreate FinishFunc = finishNothing\n\n\t// Init metadata as early as possible.\n\tif objectMeta, err := meta.Accessor(obj); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\trest.FillObjectMetaSystemFields(objectMeta)\n\t\tif len(objectMeta.GetGenerateName()) \u003e 0 \u0026\u0026 len(objectMeta.GetName()) == 0 {\n\t\t\tobjectMeta.SetName(e.CreateStrategy.GenerateName(objectMeta.GetGenerateName()))\n\t\t}\n\t}\n\n\tif e.BeginCreate != nil {\n\t\tfn, err := e.BeginCreate(ctx, obj, options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfinishCreate = fn\n\t\tdefer func() {\n\t\t\tfinishCreate(ctx, false)\n\t\t}()\n\t}\n\n\tif err := rest.BeforeCreate(e.CreateStrategy, ctx, obj); err != nil {\n\t\treturn nil, err\n\t}\n\t// at this point we have a fully formed object. It is time to call the validators that the apiserver\n\t// handling chain wants to enforce.\n\tif createValidation != nil {\n\t\tif err := createValidation(ctx, obj.DeepCopyObject()); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tname, err := e.ObjectNameFunc(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkey, err := e.KeyFunc(ctx, name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tqualifiedResource := e.qualifiedResourceFromContext(ctx)\n\tttl, err := e.calculateTTL(obj, 0, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tout := e.NewFunc()\n\tif err := e.Storage.Create(ctx, key, obj, out, ttl, dryrun.IsDryRun(options.DryRun)); err != nil {\n\t\terr = storeerr.InterpretCreateError(err, qualifiedResource, name)\n\t\terr = rest.CheckGeneratedNameError(ctx, e.CreateStrategy, err, obj)\n\t\tif !apierrors.IsAlreadyExists(err) {\n\t\t\treturn nil, err\n\t\t}\n\t\tif errGet := e.Storage.Get(ctx, key, storage.GetOptions{}, out); errGet != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\taccessor, errGetAcc := meta.Accessor(out)\n\t\tif errGetAcc != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif accessor.GetDeletionTimestamp() != nil {\n\t\t\tmsg := \u0026err.(*apierrors.StatusError).ErrStatus.Message\n\t\t\t*msg = fmt.Sprintf(\"object is being deleted: %s\", *msg)\n\t\t}\n\t\treturn nil, err\n\t}\n\t// The operation has succeeded. Call the finish function if there is one,\n\t// and then make sure the defer doesn't call it again.\n\tfn := finishCreate\n\tfinishCreate = finishNothing\n\tfn(ctx, true)\n\n\tif e.AfterCreate != nil {\n\t\te.AfterCreate(out, options)\n\t}\n\tif e.Decorator != nil {\n\t\te.Decorator(out)\n\t}\n\treturn out, nil\n}","line":{"from":394,"to":479}} {"id":100017763,"name":"ShouldDeleteDuringUpdate","signature":"func ShouldDeleteDuringUpdate(ctx context.Context, key string, obj, existing runtime.Object) bool","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// ShouldDeleteDuringUpdate is the default function for\n// checking if an object should be deleted during an update.\n// It checks if the new object has no finalizers,\n// the existing object's deletionTimestamp is set, and\n// the existing object's deletionGracePeriodSeconds is 0 or nil\nfunc ShouldDeleteDuringUpdate(ctx context.Context, key string, obj, existing runtime.Object) bool {\n\tnewMeta, err := meta.Accessor(obj)\n\tif err != nil {\n\t\tutilruntime.HandleError(err)\n\t\treturn false\n\t}\n\toldMeta, err := meta.Accessor(existing)\n\tif err != nil {\n\t\tutilruntime.HandleError(err)\n\t\treturn false\n\t}\n\tif len(newMeta.GetFinalizers()) \u003e 0 {\n\t\t// don't delete with finalizers remaining in the new object\n\t\treturn false\n\t}\n\tif oldMeta.GetDeletionTimestamp() == nil {\n\t\t// don't delete if the existing object hasn't had a delete request made\n\t\treturn false\n\t}\n\t// delete if the existing object has no grace period or a grace period of 0\n\treturn oldMeta.GetDeletionGracePeriodSeconds() == nil || *oldMeta.GetDeletionGracePeriodSeconds() == 0\n}","line":{"from":481,"to":507}} {"id":100017764,"name":"deleteWithoutFinalizers","signature":"func (e *Store) deleteWithoutFinalizers(ctx context.Context, name, key string, obj runtime.Object, preconditions *storage.Preconditions, options *metav1.DeleteOptions) (runtime.Object, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// deleteWithoutFinalizers handles deleting an object ignoring its finalizer list.\n// Used for objects that are either been finalized or have never initialized.\nfunc (e *Store) deleteWithoutFinalizers(ctx context.Context, name, key string, obj runtime.Object, preconditions *storage.Preconditions, options *metav1.DeleteOptions) (runtime.Object, bool, error) {\n\tout := e.NewFunc()\n\tklog.V(6).InfoS(\"Going to delete object from registry, triggered by update\", \"object\", klog.KRef(genericapirequest.NamespaceValue(ctx), name))\n\t// Using the rest.ValidateAllObjectFunc because the request is an UPDATE request and has already passed the admission for the UPDATE verb.\n\tif err := e.Storage.Delete(ctx, key, out, preconditions, rest.ValidateAllObjectFunc, dryrun.IsDryRun(options.DryRun), nil); err != nil {\n\t\t// Deletion is racy, i.e., there could be multiple update\n\t\t// requests to remove all finalizers from the object, so we\n\t\t// ignore the NotFound error.\n\t\tif storage.IsNotFound(err) {\n\t\t\t_, err := e.finalizeDelete(ctx, obj, true, options)\n\t\t\t// clients are expecting an updated object if a PUT succeeded,\n\t\t\t// but finalizeDelete returns a metav1.Status, so return\n\t\t\t// the object in the request instead.\n\t\t\treturn obj, false, err\n\t\t}\n\t\treturn nil, false, storeerr.InterpretDeleteError(err, e.qualifiedResourceFromContext(ctx), name)\n\t}\n\t_, err := e.finalizeDelete(ctx, out, true, options)\n\t// clients are expecting an updated object if a PUT succeeded, but\n\t// finalizeDelete returns a metav1.Status, so return the object in\n\t// the request instead.\n\treturn obj, false, err\n}","line":{"from":509,"to":533}} {"id":100017765,"name":"Update","signature":"func (e *Store) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// Update performs an atomic update and set of the object. Returns the result of the update\n// or an error. If the registry allows create-on-update, the create flow will be executed.\n// A bool is returned along with the object and any errors, to indicate object creation.\nfunc (e *Store) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\tkey, err := e.KeyFunc(ctx, name)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\tvar (\n\t\tcreatingObj runtime.Object\n\t\tcreating = false\n\t)\n\n\tqualifiedResource := e.qualifiedResourceFromContext(ctx)\n\tstoragePreconditions := \u0026storage.Preconditions{}\n\tif preconditions := objInfo.Preconditions(); preconditions != nil {\n\t\tstoragePreconditions.UID = preconditions.UID\n\t\tstoragePreconditions.ResourceVersion = preconditions.ResourceVersion\n\t}\n\n\tout := e.NewFunc()\n\t// deleteObj is only used in case a deletion is carried out\n\tvar deleteObj runtime.Object\n\terr = e.Storage.GuaranteedUpdate(ctx, key, out, true, storagePreconditions, func(existing runtime.Object, res storage.ResponseMeta) (runtime.Object, *uint64, error) {\n\t\texistingResourceVersion, err := e.Storage.Versioner().ObjectResourceVersion(existing)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tif existingResourceVersion == 0 {\n\t\t\tif !e.UpdateStrategy.AllowCreateOnUpdate() \u0026\u0026 !forceAllowCreate {\n\t\t\t\treturn nil, nil, apierrors.NewNotFound(qualifiedResource, name)\n\t\t\t}\n\t\t}\n\n\t\t// Given the existing object, get the new object\n\t\tobj, err := objInfo.UpdatedObject(ctx, existing)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\t// If AllowUnconditionalUpdate() is true and the object specified by\n\t\t// the user does not have a resource version, then we populate it with\n\t\t// the latest version. Else, we check that the version specified by\n\t\t// the user matches the version of latest storage object.\n\t\tnewResourceVersion, err := e.Storage.Versioner().ObjectResourceVersion(obj)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tdoUnconditionalUpdate := newResourceVersion == 0 \u0026\u0026 e.UpdateStrategy.AllowUnconditionalUpdate()\n\n\t\tif existingResourceVersion == 0 {\n\t\t\t// Init metadata as early as possible.\n\t\t\tif objectMeta, err := meta.Accessor(obj); err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t} else {\n\t\t\t\trest.FillObjectMetaSystemFields(objectMeta)\n\t\t\t}\n\n\t\t\tvar finishCreate FinishFunc = finishNothing\n\n\t\t\tif e.BeginCreate != nil {\n\t\t\t\tfn, err := e.BeginCreate(ctx, obj, newCreateOptionsFromUpdateOptions(options))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, nil, err\n\t\t\t\t}\n\t\t\t\tfinishCreate = fn\n\t\t\t\tdefer func() {\n\t\t\t\t\tfinishCreate(ctx, false)\n\t\t\t\t}()\n\t\t\t}\n\n\t\t\tcreating = true\n\t\t\tcreatingObj = obj\n\t\t\tif err := rest.BeforeCreate(e.CreateStrategy, ctx, obj); err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\t// at this point we have a fully formed object. It is time to call the validators that the apiserver\n\t\t\t// handling chain wants to enforce.\n\t\t\tif createValidation != nil {\n\t\t\t\tif err := createValidation(ctx, obj.DeepCopyObject()); err != nil {\n\t\t\t\t\treturn nil, nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tttl, err := e.calculateTTL(obj, 0, false)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\n\t\t\t// The operation has succeeded. Call the finish function if there is one,\n\t\t\t// and then make sure the defer doesn't call it again.\n\t\t\tfn := finishCreate\n\t\t\tfinishCreate = finishNothing\n\t\t\tfn(ctx, true)\n\n\t\t\treturn obj, \u0026ttl, nil\n\t\t}\n\n\t\tcreating = false\n\t\tcreatingObj = nil\n\t\tif doUnconditionalUpdate {\n\t\t\t// Update the object's resource version to match the latest\n\t\t\t// storage object's resource version.\n\t\t\terr = e.Storage.Versioner().UpdateObject(obj, res.ResourceVersion)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t} else {\n\t\t\t// Check if the object's resource version matches the latest\n\t\t\t// resource version.\n\t\t\tif newResourceVersion == 0 {\n\t\t\t\t// TODO: The Invalid error should have a field for Resource.\n\t\t\t\t// After that field is added, we should fill the Resource and\n\t\t\t\t// leave the Kind field empty. See the discussion in #18526.\n\t\t\t\tqualifiedKind := schema.GroupKind{Group: qualifiedResource.Group, Kind: qualifiedResource.Resource}\n\t\t\t\tfieldErrList := field.ErrorList{field.Invalid(field.NewPath(\"metadata\").Child(\"resourceVersion\"), newResourceVersion, \"must be specified for an update\")}\n\t\t\t\treturn nil, nil, apierrors.NewInvalid(qualifiedKind, name, fieldErrList)\n\t\t\t}\n\t\t\tif newResourceVersion != existingResourceVersion {\n\t\t\t\treturn nil, nil, apierrors.NewConflict(qualifiedResource, name, fmt.Errorf(OptimisticLockErrorMsg))\n\t\t\t}\n\t\t}\n\n\t\tvar finishUpdate FinishFunc = finishNothing\n\n\t\tif e.BeginUpdate != nil {\n\t\t\tfn, err := e.BeginUpdate(ctx, obj, existing, options)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\tfinishUpdate = fn\n\t\t\tdefer func() {\n\t\t\t\tfinishUpdate(ctx, false)\n\t\t\t}()\n\t\t}\n\n\t\tif err := rest.BeforeUpdate(e.UpdateStrategy, ctx, obj, existing); err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\t// at this point we have a fully formed object. It is time to call the validators that the apiserver\n\t\t// handling chain wants to enforce.\n\t\tif updateValidation != nil {\n\t\t\tif err := updateValidation(ctx, obj.DeepCopyObject(), existing.DeepCopyObject()); err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t}\n\t\t// Check the default delete-during-update conditions, and store-specific conditions if provided\n\t\tif ShouldDeleteDuringUpdate(ctx, key, obj, existing) \u0026\u0026\n\t\t\t(e.ShouldDeleteDuringUpdate == nil || e.ShouldDeleteDuringUpdate(ctx, key, obj, existing)) {\n\t\t\tdeleteObj = obj\n\t\t\treturn nil, nil, errEmptiedFinalizers\n\t\t}\n\t\tttl, err := e.calculateTTL(obj, res.TTL, true)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\t// The operation has succeeded. Call the finish function if there is one,\n\t\t// and then make sure the defer doesn't call it again.\n\t\tfn := finishUpdate\n\t\tfinishUpdate = finishNothing\n\t\tfn(ctx, true)\n\n\t\tif int64(ttl) != res.TTL {\n\t\t\treturn obj, \u0026ttl, nil\n\t\t}\n\t\treturn obj, nil, nil\n\t}, dryrun.IsDryRun(options.DryRun), nil)\n\n\tif err != nil {\n\t\t// delete the object\n\t\tif err == errEmptiedFinalizers {\n\t\t\treturn e.deleteWithoutFinalizers(ctx, name, key, deleteObj, storagePreconditions, newDeleteOptionsFromUpdateOptions(options))\n\t\t}\n\t\tif creating {\n\t\t\terr = storeerr.InterpretCreateError(err, qualifiedResource, name)\n\t\t\terr = rest.CheckGeneratedNameError(ctx, e.CreateStrategy, err, creatingObj)\n\t\t} else {\n\t\t\terr = storeerr.InterpretUpdateError(err, qualifiedResource, name)\n\t\t}\n\t\treturn nil, false, err\n\t}\n\n\tif creating {\n\t\tif e.AfterCreate != nil {\n\t\t\te.AfterCreate(out, newCreateOptionsFromUpdateOptions(options))\n\t\t}\n\t} else {\n\t\tif e.AfterUpdate != nil {\n\t\t\te.AfterUpdate(out, options)\n\t\t}\n\t}\n\tif e.Decorator != nil {\n\t\te.Decorator(out)\n\t}\n\treturn out, creating, nil\n}","line":{"from":535,"to":731}} {"id":100017766,"name":"newCreateOptionsFromUpdateOptions","signature":"func newCreateOptionsFromUpdateOptions(in *metav1.UpdateOptions) *metav1.CreateOptions","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// This is a helper to convert UpdateOptions to CreateOptions for the\n// create-on-update path.\nfunc newCreateOptionsFromUpdateOptions(in *metav1.UpdateOptions) *metav1.CreateOptions {\n\tco := \u0026metav1.CreateOptions{\n\t\tDryRun: in.DryRun,\n\t\tFieldManager: in.FieldManager,\n\t\tFieldValidation: in.FieldValidation,\n\t}\n\tco.TypeMeta.SetGroupVersionKind(metav1.SchemeGroupVersion.WithKind(\"CreateOptions\"))\n\treturn co\n}","line":{"from":733,"to":743}} {"id":100017767,"name":"newDeleteOptionsFromUpdateOptions","signature":"func newDeleteOptionsFromUpdateOptions(in *metav1.UpdateOptions) *metav1.DeleteOptions","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// This is a helper to convert UpdateOptions to DeleteOptions for the\n// delete-on-update path.\nfunc newDeleteOptionsFromUpdateOptions(in *metav1.UpdateOptions) *metav1.DeleteOptions {\n\tdo := \u0026metav1.DeleteOptions{\n\t\tDryRun: in.DryRun,\n\t}\n\tdo.TypeMeta.SetGroupVersionKind(metav1.SchemeGroupVersion.WithKind(\"DeleteOptions\"))\n\treturn do\n}","line":{"from":745,"to":753}} {"id":100017768,"name":"Get","signature":"func (e *Store) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// Get retrieves the item from storage.\nfunc (e *Store) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\tobj := e.NewFunc()\n\tkey, err := e.KeyFunc(ctx, name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := e.Storage.Get(ctx, key, storage.GetOptions{ResourceVersion: options.ResourceVersion}, obj); err != nil {\n\t\treturn nil, storeerr.InterpretGetError(err, e.qualifiedResourceFromContext(ctx), name)\n\t}\n\tif e.Decorator != nil {\n\t\te.Decorator(obj)\n\t}\n\treturn obj, nil\n}","line":{"from":755,"to":769}} {"id":100017769,"name":"qualifiedResourceFromContext","signature":"func (e *Store) qualifiedResourceFromContext(ctx context.Context) schema.GroupResource","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// qualifiedResourceFromContext attempts to retrieve a GroupResource from the context's request info.\n// If the context has no request info, DefaultQualifiedResource is used.\nfunc (e *Store) qualifiedResourceFromContext(ctx context.Context) schema.GroupResource {\n\tif info, ok := genericapirequest.RequestInfoFrom(ctx); ok {\n\t\treturn schema.GroupResource{Group: info.APIGroup, Resource: info.Resource}\n\t}\n\t// some implementations access storage directly and thus the context has no RequestInfo\n\treturn e.DefaultQualifiedResource\n}","line":{"from":771,"to":779}} {"id":100017770,"name":"shouldOrphanDependents","signature":"func shouldOrphanDependents(ctx context.Context, e *Store, accessor metav1.Object, options *metav1.DeleteOptions) bool","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// shouldOrphanDependents returns true if the finalizer for orphaning should be set\n// updated for FinalizerOrphanDependents. In the order of highest to lowest\n// priority, there are three factors affect whether to add/remove the\n// FinalizerOrphanDependents: options, existing finalizers of the object,\n// and e.DeleteStrategy.DefaultGarbageCollectionPolicy.\nfunc shouldOrphanDependents(ctx context.Context, e *Store, accessor metav1.Object, options *metav1.DeleteOptions) bool {\n\t// Get default GC policy from this REST object type\n\tgcStrategy, ok := e.DeleteStrategy.(rest.GarbageCollectionDeleteStrategy)\n\tvar defaultGCPolicy rest.GarbageCollectionPolicy\n\tif ok {\n\t\tdefaultGCPolicy = gcStrategy.DefaultGarbageCollectionPolicy(ctx)\n\t}\n\n\tif defaultGCPolicy == rest.Unsupported {\n\t\t// return false to indicate that we should NOT orphan\n\t\treturn false\n\t}\n\n\t// An explicit policy was set at deletion time, that overrides everything\n\t//nolint:staticcheck // SA1019 backwards compatibility\n\tif options != nil \u0026\u0026 options.OrphanDependents != nil {\n\t\t//nolint:staticcheck // SA1019 backwards compatibility\n\t\treturn *options.OrphanDependents\n\t}\n\tif options != nil \u0026\u0026 options.PropagationPolicy != nil {\n\t\tswitch *options.PropagationPolicy {\n\t\tcase metav1.DeletePropagationOrphan:\n\t\t\treturn true\n\t\tcase metav1.DeletePropagationBackground, metav1.DeletePropagationForeground:\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// If a finalizer is set in the object, it overrides the default\n\t// validation should make sure the two cases won't be true at the same time.\n\tfinalizers := accessor.GetFinalizers()\n\tfor _, f := range finalizers {\n\t\tswitch f {\n\t\tcase metav1.FinalizerOrphanDependents:\n\t\t\treturn true\n\t\tcase metav1.FinalizerDeleteDependents:\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// Get default orphan policy from this REST object type if it exists\n\treturn defaultGCPolicy == rest.OrphanDependents\n}","line":{"from":787,"to":834}} {"id":100017771,"name":"shouldDeleteDependents","signature":"func shouldDeleteDependents(ctx context.Context, e *Store, accessor metav1.Object, options *metav1.DeleteOptions) bool","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// shouldDeleteDependents returns true if the finalizer for foreground deletion should be set\n// updated for FinalizerDeleteDependents. In the order of highest to lowest\n// priority, there are three factors affect whether to add/remove the\n// FinalizerDeleteDependents: options, existing finalizers of the object, and\n// e.DeleteStrategy.DefaultGarbageCollectionPolicy.\nfunc shouldDeleteDependents(ctx context.Context, e *Store, accessor metav1.Object, options *metav1.DeleteOptions) bool {\n\t// Get default GC policy from this REST object type\n\tif gcStrategy, ok := e.DeleteStrategy.(rest.GarbageCollectionDeleteStrategy); ok \u0026\u0026 gcStrategy.DefaultGarbageCollectionPolicy(ctx) == rest.Unsupported {\n\t\t// return false to indicate that we should NOT delete in foreground\n\t\treturn false\n\t}\n\n\t// If an explicit policy was set at deletion time, that overrides both\n\t//nolint:staticcheck // SA1019 backwards compatibility\n\tif options != nil \u0026\u0026 options.OrphanDependents != nil {\n\t\treturn false\n\t}\n\tif options != nil \u0026\u0026 options.PropagationPolicy != nil {\n\t\tswitch *options.PropagationPolicy {\n\t\tcase metav1.DeletePropagationForeground:\n\t\t\treturn true\n\t\tcase metav1.DeletePropagationBackground, metav1.DeletePropagationOrphan:\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// If a finalizer is set in the object, it overrides the default\n\t// validation has made sure the two cases won't be true at the same time.\n\tfinalizers := accessor.GetFinalizers()\n\tfor _, f := range finalizers {\n\t\tswitch f {\n\t\tcase metav1.FinalizerDeleteDependents:\n\t\t\treturn true\n\t\tcase metav1.FinalizerOrphanDependents:\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":836,"to":875}} {"id":100017772,"name":"deletionFinalizersForGarbageCollection","signature":"func deletionFinalizersForGarbageCollection(ctx context.Context, e *Store, accessor metav1.Object, options *metav1.DeleteOptions) (bool, []string)","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// deletionFinalizersForGarbageCollection analyzes the object and delete options\n// to determine whether the object is in need of finalization by the garbage\n// collector. If so, returns the set of deletion finalizers to apply and a bool\n// indicating whether the finalizer list has changed and is in need of updating.\n//\n// The finalizers returned are intended to be handled by the garbage collector.\n// If garbage collection is disabled for the store, this function returns false\n// to ensure finalizers aren't set which will never be cleared.\nfunc deletionFinalizersForGarbageCollection(ctx context.Context, e *Store, accessor metav1.Object, options *metav1.DeleteOptions) (bool, []string) {\n\tif !e.EnableGarbageCollection {\n\t\treturn false, []string{}\n\t}\n\tshouldOrphan := shouldOrphanDependents(ctx, e, accessor, options)\n\tshouldDeleteDependentInForeground := shouldDeleteDependents(ctx, e, accessor, options)\n\tnewFinalizers := []string{}\n\n\t// first remove both finalizers, add them back if needed.\n\tfor _, f := range accessor.GetFinalizers() {\n\t\tif f == metav1.FinalizerOrphanDependents || f == metav1.FinalizerDeleteDependents {\n\t\t\tcontinue\n\t\t}\n\t\tnewFinalizers = append(newFinalizers, f)\n\t}\n\n\tif shouldOrphan {\n\t\tnewFinalizers = append(newFinalizers, metav1.FinalizerOrphanDependents)\n\t}\n\tif shouldDeleteDependentInForeground {\n\t\tnewFinalizers = append(newFinalizers, metav1.FinalizerDeleteDependents)\n\t}\n\n\toldFinalizerSet := sets.NewString(accessor.GetFinalizers()...)\n\tnewFinalizersSet := sets.NewString(newFinalizers...)\n\tif oldFinalizerSet.Equal(newFinalizersSet) {\n\t\treturn false, accessor.GetFinalizers()\n\t}\n\treturn true, newFinalizers\n}","line":{"from":877,"to":914}} {"id":100017773,"name":"markAsDeleting","signature":"func markAsDeleting(obj runtime.Object, now time.Time) (err error)","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// markAsDeleting sets the obj's DeletionGracePeriodSeconds to 0, and sets the\n// DeletionTimestamp to \"now\" if there is no existing deletionTimestamp or if the existing\n// deletionTimestamp is further in future. Finalizers are watching for such updates and will\n// finalize the object if their IDs are present in the object's Finalizers list.\nfunc markAsDeleting(obj runtime.Object, now time.Time) (err error) {\n\tobjectMeta, kerr := meta.Accessor(obj)\n\tif kerr != nil {\n\t\treturn kerr\n\t}\n\t// This handles Generation bump for resources that don't support graceful\n\t// deletion. For resources that support graceful deletion is handle in\n\t// pkg/api/rest/delete.go\n\tif objectMeta.GetDeletionTimestamp() == nil \u0026\u0026 objectMeta.GetGeneration() \u003e 0 {\n\t\tobjectMeta.SetGeneration(objectMeta.GetGeneration() + 1)\n\t}\n\texistingDeletionTimestamp := objectMeta.GetDeletionTimestamp()\n\tif existingDeletionTimestamp == nil || existingDeletionTimestamp.After(now) {\n\t\tmetaNow := metav1.NewTime(now)\n\t\tobjectMeta.SetDeletionTimestamp(\u0026metaNow)\n\t}\n\tvar zero int64 = 0\n\tobjectMeta.SetDeletionGracePeriodSeconds(\u0026zero)\n\treturn nil\n}","line":{"from":916,"to":939}} {"id":100017774,"name":"updateForGracefulDeletionAndFinalizers","signature":"func (e *Store) updateForGracefulDeletionAndFinalizers(ctx context.Context, name, key string, options *metav1.DeleteOptions, preconditions storage.Preconditions, deleteValidation rest.ValidateObjectFunc, in runtime.Object) (err error, ignoreNotFound, deleteImmediately bool, out, lastExisting runtime.Object)","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// updateForGracefulDeletionAndFinalizers updates the given object for\n// graceful deletion and finalization by setting the deletion timestamp and\n// grace period seconds (graceful deletion) and updating the list of\n// finalizers (finalization); it returns:\n//\n// 1. an error\n// 2. a boolean indicating that the object was not found, but it should be\n// ignored\n// 3. a boolean indicating that the object's grace period is exhausted and it\n// should be deleted immediately\n// 4. a new output object with the state that was updated\n// 5. a copy of the last existing state of the object\nfunc (e *Store) updateForGracefulDeletionAndFinalizers(ctx context.Context, name, key string, options *metav1.DeleteOptions, preconditions storage.Preconditions, deleteValidation rest.ValidateObjectFunc, in runtime.Object) (err error, ignoreNotFound, deleteImmediately bool, out, lastExisting runtime.Object) {\n\tlastGraceful := int64(0)\n\tvar pendingFinalizers bool\n\tout = e.NewFunc()\n\terr = e.Storage.GuaranteedUpdate(\n\t\tctx,\n\t\tkey,\n\t\tout,\n\t\tfalse, /* ignoreNotFound */\n\t\t\u0026preconditions,\n\t\tstorage.SimpleUpdate(func(existing runtime.Object) (runtime.Object, error) {\n\t\t\tif err := deleteValidation(ctx, existing); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tgraceful, pendingGraceful, err := rest.BeforeDelete(e.DeleteStrategy, ctx, existing, options)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif pendingGraceful {\n\t\t\t\treturn nil, errAlreadyDeleting\n\t\t\t}\n\n\t\t\t// Add/remove the orphan finalizer as the options dictates.\n\t\t\t// Note that this occurs after checking pendingGraceufl, so\n\t\t\t// finalizers cannot be updated via DeleteOptions if deletion has\n\t\t\t// started.\n\t\t\texistingAccessor, err := meta.Accessor(existing)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tneedsUpdate, newFinalizers := deletionFinalizersForGarbageCollection(ctx, e, existingAccessor, options)\n\t\t\tif needsUpdate {\n\t\t\t\texistingAccessor.SetFinalizers(newFinalizers)\n\t\t\t}\n\n\t\t\tpendingFinalizers = len(existingAccessor.GetFinalizers()) != 0\n\t\t\tif !graceful {\n\t\t\t\t// set the DeleteGracePeriods to 0 if the object has pendingFinalizers but not supporting graceful deletion\n\t\t\t\tif pendingFinalizers {\n\t\t\t\t\tklog.V(6).InfoS(\"Object has pending finalizers, so the registry is going to update its status to deleting\",\n\t\t\t\t\t\t\"object\", klog.KRef(genericapirequest.NamespaceValue(ctx), name), \"gracePeriod\", time.Second*0)\n\t\t\t\t\terr = markAsDeleting(existing, time.Now())\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\treturn existing, nil\n\t\t\t\t}\n\t\t\t\treturn nil, errDeleteNow\n\t\t\t}\n\t\t\tlastGraceful = *options.GracePeriodSeconds\n\t\t\tlastExisting = existing\n\t\t\treturn existing, nil\n\t\t}),\n\t\tdryrun.IsDryRun(options.DryRun),\n\t\tnil,\n\t)\n\tswitch err {\n\tcase nil:\n\t\t// If there are pending finalizers, we never delete the object immediately.\n\t\tif pendingFinalizers {\n\t\t\treturn nil, false, false, out, lastExisting\n\t\t}\n\t\tif lastGraceful \u003e 0 {\n\t\t\treturn nil, false, false, out, lastExisting\n\t\t}\n\t\t// If we are here, the registry supports grace period mechanism and\n\t\t// we are intentionally delete gracelessly. In this case, we may\n\t\t// enter a race with other k8s components. If other component wins\n\t\t// the race, the object will not be found, and we should tolerate\n\t\t// the NotFound error. See\n\t\t// https://github.com/kubernetes/kubernetes/issues/19403 for\n\t\t// details.\n\t\treturn nil, true, true, out, lastExisting\n\tcase errDeleteNow:\n\t\t// we've updated the object to have a zero grace period, or it's already at 0, so\n\t\t// we should fall through and truly delete the object.\n\t\treturn nil, false, true, out, lastExisting\n\tcase errAlreadyDeleting:\n\t\tout, err = e.finalizeDelete(ctx, in, true, options)\n\t\treturn err, false, false, out, lastExisting\n\tdefault:\n\t\treturn storeerr.InterpretUpdateError(err, e.qualifiedResourceFromContext(ctx), name), false, false, out, lastExisting\n\t}\n}","line":{"from":941,"to":1036}} {"id":100017775,"name":"Delete","signature":"func (e *Store) Delete(ctx context.Context, name string, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions) (runtime.Object, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// Delete removes the item from storage.\n// options can be mutated by rest.BeforeDelete due to a graceful deletion strategy.\nfunc (e *Store) Delete(ctx context.Context, name string, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions) (runtime.Object, bool, error) {\n\tkey, err := e.KeyFunc(ctx, name)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\tobj := e.NewFunc()\n\tqualifiedResource := e.qualifiedResourceFromContext(ctx)\n\tif err = e.Storage.Get(ctx, key, storage.GetOptions{}, obj); err != nil {\n\t\treturn nil, false, storeerr.InterpretDeleteError(err, qualifiedResource, name)\n\t}\n\n\t// support older consumers of delete by treating \"nil\" as delete immediately\n\tif options == nil {\n\t\toptions = metav1.NewDeleteOptions(0)\n\t}\n\tvar preconditions storage.Preconditions\n\tif options.Preconditions != nil {\n\t\tpreconditions.UID = options.Preconditions.UID\n\t\tpreconditions.ResourceVersion = options.Preconditions.ResourceVersion\n\t}\n\tgraceful, pendingGraceful, err := rest.BeforeDelete(e.DeleteStrategy, ctx, obj, options)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\t// this means finalizers cannot be updated via DeleteOptions if a deletion is already pending\n\tif pendingGraceful {\n\t\tout, err := e.finalizeDelete(ctx, obj, false, options)\n\t\treturn out, false, err\n\t}\n\t// check if obj has pending finalizers\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn nil, false, apierrors.NewInternalError(err)\n\t}\n\tpendingFinalizers := len(accessor.GetFinalizers()) != 0\n\tvar ignoreNotFound bool\n\tvar deleteImmediately bool = true\n\tvar lastExisting, out runtime.Object\n\n\t// Handle combinations of graceful deletion and finalization by issuing\n\t// the correct updates.\n\tshouldUpdateFinalizers, _ := deletionFinalizersForGarbageCollection(ctx, e, accessor, options)\n\t// TODO: remove the check, because we support no-op updates now.\n\tif graceful || pendingFinalizers || shouldUpdateFinalizers {\n\t\terr, ignoreNotFound, deleteImmediately, out, lastExisting = e.updateForGracefulDeletionAndFinalizers(ctx, name, key, options, preconditions, deleteValidation, obj)\n\t\t// Update the preconditions.ResourceVersion if set since we updated the object.\n\t\tif err == nil \u0026\u0026 deleteImmediately \u0026\u0026 preconditions.ResourceVersion != nil {\n\t\t\taccessor, err = meta.Accessor(out)\n\t\t\tif err != nil {\n\t\t\t\treturn out, false, apierrors.NewInternalError(err)\n\t\t\t}\n\t\t\tresourceVersion := accessor.GetResourceVersion()\n\t\t\tpreconditions.ResourceVersion = \u0026resourceVersion\n\t\t}\n\t}\n\n\t// !deleteImmediately covers all cases where err != nil. We keep both to be future-proof.\n\tif !deleteImmediately || err != nil {\n\t\treturn out, false, err\n\t}\n\n\t// Going further in this function is not useful when we are\n\t// performing a dry-run request. Worse, it will actually\n\t// override \"out\" with the version of the object in database\n\t// that doesn't have the finalizer and deletiontimestamp set\n\t// (because the update above was dry-run too). If we already\n\t// have that version available, let's just return it now,\n\t// otherwise, we can call dry-run delete that will get us the\n\t// latest version of the object.\n\tif dryrun.IsDryRun(options.DryRun) \u0026\u0026 out != nil {\n\t\treturn out, true, nil\n\t}\n\n\t// delete immediately, or no graceful deletion supported\n\tklog.V(6).InfoS(\"Going to delete object from registry\", \"object\", klog.KRef(genericapirequest.NamespaceValue(ctx), name))\n\tout = e.NewFunc()\n\tif err := e.Storage.Delete(ctx, key, out, \u0026preconditions, storage.ValidateObjectFunc(deleteValidation), dryrun.IsDryRun(options.DryRun), nil); err != nil {\n\t\t// Please refer to the place where we set ignoreNotFound for the reason\n\t\t// why we ignore the NotFound error .\n\t\tif storage.IsNotFound(err) \u0026\u0026 ignoreNotFound \u0026\u0026 lastExisting != nil {\n\t\t\t// The lastExisting object may not be the last state of the object\n\t\t\t// before its deletion, but it's the best approximation.\n\t\t\tout, err := e.finalizeDelete(ctx, lastExisting, true, options)\n\t\t\treturn out, true, err\n\t\t}\n\t\treturn nil, false, storeerr.InterpretDeleteError(err, qualifiedResource, name)\n\t}\n\tout, err = e.finalizeDelete(ctx, out, true, options)\n\treturn out, true, err\n}","line":{"from":1038,"to":1129}} {"id":100017776,"name":"DeleteReturnsDeletedObject","signature":"func (e *Store) DeleteReturnsDeletedObject() bool","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// DeleteReturnsDeletedObject implements the rest.MayReturnFullObjectDeleter interface\nfunc (e *Store) DeleteReturnsDeletedObject() bool {\n\treturn e.ReturnDeletedObject\n}","line":{"from":1131,"to":1134}} {"id":100017777,"name":"DeleteCollection","signature":"func (e *Store) DeleteCollection(ctx context.Context, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions, listOptions *metainternalversion.ListOptions) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// DeleteCollection removes all items returned by List with a given ListOptions from storage.\n//\n// DeleteCollection is currently NOT atomic. It can happen that only subset of objects\n// will be deleted from storage, and then an error will be returned.\n// In case of success, the list of deleted objects will be returned.\nfunc (e *Store) DeleteCollection(ctx context.Context, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions, listOptions *metainternalversion.ListOptions) (runtime.Object, error) {\n\tif listOptions == nil {\n\t\tlistOptions = \u0026metainternalversion.ListOptions{}\n\t} else {\n\t\tlistOptions = listOptions.DeepCopy()\n\t}\n\n\tlistObj, err := e.List(ctx, listOptions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\titems, err := meta.ExtractList(listObj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(items) == 0 {\n\t\t// Nothing to delete, return now\n\t\treturn listObj, nil\n\t}\n\t// Spawn a number of goroutines, so that we can issue requests to storage\n\t// in parallel to speed up deletion.\n\t// It is proportional to the number of items to delete, up to\n\t// DeleteCollectionWorkers (it doesn't make much sense to spawn 16\n\t// workers to delete 10 items).\n\tworkersNumber := e.DeleteCollectionWorkers\n\tif workersNumber \u003e len(items) {\n\t\tworkersNumber = len(items)\n\t}\n\tif workersNumber \u003c 1 {\n\t\tworkersNumber = 1\n\t}\n\twg := sync.WaitGroup{}\n\ttoProcess := make(chan int, 2*workersNumber)\n\terrs := make(chan error, workersNumber+1)\n\tworkersExited := make(chan struct{})\n\n\twg.Add(workersNumber)\n\tfor i := 0; i \u003c workersNumber; i++ {\n\t\tgo func() {\n\t\t\t// panics don't cross goroutine boundaries\n\t\t\tdefer utilruntime.HandleCrash(func(panicReason interface{}) {\n\t\t\t\terrs \u003c- fmt.Errorf(\"DeleteCollection goroutine panicked: %v\", panicReason)\n\t\t\t})\n\t\t\tdefer wg.Done()\n\n\t\t\tfor index := range toProcess {\n\t\t\t\taccessor, err := meta.Accessor(items[index])\n\t\t\t\tif err != nil {\n\t\t\t\t\terrs \u003c- err\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// DeepCopy the deletion options because individual graceful deleters communicate changes via a mutating\n\t\t\t\t// function in the delete strategy called in the delete method. While that is always ugly, it works\n\t\t\t\t// when making a single call. When making multiple calls via delete collection, the mutation applied to\n\t\t\t\t// pod/A can change the option ultimately used for pod/B.\n\t\t\t\tif _, _, err := e.Delete(ctx, accessor.GetName(), deleteValidation, options.DeepCopy()); err != nil \u0026\u0026 !apierrors.IsNotFound(err) {\n\t\t\t\t\tklog.V(4).InfoS(\"Delete object in DeleteCollection failed\", \"object\", klog.KObj(accessor), \"err\", err)\n\t\t\t\t\terrs \u003c- err\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\t// In case of all workers exit, notify distributor.\n\tgo func() {\n\t\tdefer utilruntime.HandleCrash(func(panicReason interface{}) {\n\t\t\terrs \u003c- fmt.Errorf(\"DeleteCollection workers closer panicked: %v\", panicReason)\n\t\t})\n\t\twg.Wait()\n\t\tclose(workersExited)\n\t}()\n\n\tfunc() {\n\t\tdefer close(toProcess)\n\n\t\tfor i := 0; i \u003c len(items); i++ {\n\t\t\tselect {\n\t\t\tcase toProcess \u003c- i:\n\t\t\tcase \u003c-workersExited:\n\t\t\t\tklog.V(4).InfoS(\"workers already exited, and there are some items waiting to be processed\", \"finished\", i, \"total\", len(items))\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\t// Wait for all workers to exist.\n\t\u003c-workersExited\n\n\tselect {\n\tcase err := \u003c-errs:\n\t\treturn nil, err\n\tdefault:\n\t\treturn listObj, nil\n\t}\n}","line":{"from":1136,"to":1235}} {"id":100017778,"name":"finalizeDelete","signature":"func (e *Store) finalizeDelete(ctx context.Context, obj runtime.Object, runHooks bool, options *metav1.DeleteOptions) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// finalizeDelete runs the Store's AfterDelete hook if runHooks is set and\n// returns the decorated deleted object if appropriate.\nfunc (e *Store) finalizeDelete(ctx context.Context, obj runtime.Object, runHooks bool, options *metav1.DeleteOptions) (runtime.Object, error) {\n\tif runHooks \u0026\u0026 e.AfterDelete != nil {\n\t\te.AfterDelete(obj, options)\n\t}\n\tif e.ReturnDeletedObject {\n\t\tif e.Decorator != nil {\n\t\t\te.Decorator(obj)\n\t\t}\n\t\treturn obj, nil\n\t}\n\t// Return information about the deleted object, which enables clients to\n\t// verify that the object was actually deleted and not waiting for finalizers.\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tqualifiedResource := e.qualifiedResourceFromContext(ctx)\n\tdetails := \u0026metav1.StatusDetails{\n\t\tName: accessor.GetName(),\n\t\tGroup: qualifiedResource.Group,\n\t\tKind: qualifiedResource.Resource, // Yes we set Kind field to resource.\n\t\tUID: accessor.GetUID(),\n\t}\n\tstatus := \u0026metav1.Status{Status: metav1.StatusSuccess, Details: details}\n\treturn status, nil\n}","line":{"from":1237,"to":1264}} {"id":100017779,"name":"Watch","signature":"func (e *Store) Watch(ctx context.Context, options *metainternalversion.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// Watch makes a matcher for the given label and field, and calls\n// WatchPredicate. If possible, you should customize PredicateFunc to produce\n// a matcher that matches by key. SelectionPredicate does this for you\n// automatically.\nfunc (e *Store) Watch(ctx context.Context, options *metainternalversion.ListOptions) (watch.Interface, error) {\n\tlabel := labels.Everything()\n\tif options != nil \u0026\u0026 options.LabelSelector != nil {\n\t\tlabel = options.LabelSelector\n\t}\n\tfield := fields.Everything()\n\tif options != nil \u0026\u0026 options.FieldSelector != nil {\n\t\tfield = options.FieldSelector\n\t}\n\tpredicate := e.PredicateFunc(label, field)\n\n\tresourceVersion := \"\"\n\tif options != nil {\n\t\tresourceVersion = options.ResourceVersion\n\t\tpredicate.AllowWatchBookmarks = options.AllowWatchBookmarks\n\t}\n\treturn e.WatchPredicate(ctx, predicate, resourceVersion, options.SendInitialEvents)\n}","line":{"from":1266,"to":1287}} {"id":100017780,"name":"WatchPredicate","signature":"func (e *Store) WatchPredicate(ctx context.Context, p storage.SelectionPredicate, resourceVersion string, sendInitialEvents *bool) (watch.Interface, error)","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// WatchPredicate starts a watch for the items that matches.\nfunc (e *Store) WatchPredicate(ctx context.Context, p storage.SelectionPredicate, resourceVersion string, sendInitialEvents *bool) (watch.Interface, error) {\n\tstorageOpts := storage.ListOptions{ResourceVersion: resourceVersion, Predicate: p, Recursive: true, SendInitialEvents: sendInitialEvents}\n\n\t// if we're not already namespace-scoped, see if the field selector narrows the scope of the watch\n\tif requestNamespace, _ := genericapirequest.NamespaceFrom(ctx); len(requestNamespace) == 0 {\n\t\tif selectorNamespace, ok := p.MatchesSingleNamespace(); ok {\n\t\t\tif len(validation.ValidateNamespaceName(selectorNamespace, false)) == 0 {\n\t\t\t\tctx = genericapirequest.WithNamespace(ctx, selectorNamespace)\n\t\t\t}\n\t\t}\n\t}\n\n\tkey := e.KeyRootFunc(ctx)\n\tif name, ok := p.MatchesSingle(); ok {\n\t\tif k, err := e.KeyFunc(ctx, name); err == nil {\n\t\t\tkey = k\n\t\t\tstorageOpts.Recursive = false\n\t\t}\n\t\t// if we cannot extract a key based on the current context, the\n\t\t// optimization is skipped\n\t}\n\n\tw, err := e.Storage.Watch(ctx, key, storageOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif e.Decorator != nil {\n\t\treturn newDecoratedWatcher(ctx, w, e.Decorator), nil\n\t}\n\treturn w, nil\n}","line":{"from":1289,"to":1320}} {"id":100017781,"name":"calculateTTL","signature":"func (e *Store) calculateTTL(obj runtime.Object, defaultTTL int64, update bool) (ttl uint64, err error)","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// calculateTTL is a helper for retrieving the updated TTL for an object or\n// returning an error if the TTL cannot be calculated. The defaultTTL is\n// changed to 1 if less than zero. Zero means no TTL, not expire immediately.\nfunc (e *Store) calculateTTL(obj runtime.Object, defaultTTL int64, update bool) (ttl uint64, err error) {\n\t// TODO: validate this is assertion is still valid.\n\n\t// etcd may return a negative TTL for a node if the expiration has not\n\t// occurred due to server lag - we will ensure that the value is at least\n\t// set.\n\tif defaultTTL \u003c 0 {\n\t\tdefaultTTL = 1\n\t}\n\tttl = uint64(defaultTTL)\n\tif e.TTLFunc != nil {\n\t\tttl, err = e.TTLFunc(obj, ttl, update)\n\t}\n\treturn ttl, err\n}","line":{"from":1322,"to":1339}} {"id":100017782,"name":"CompleteWithOptions","signature":"func (e *Store) CompleteWithOptions(options *generic.StoreOptions) error","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// CompleteWithOptions updates the store with the provided options and\n// defaults common fields.\nfunc (e *Store) CompleteWithOptions(options *generic.StoreOptions) error {\n\tif e.DefaultQualifiedResource.Empty() {\n\t\treturn fmt.Errorf(\"store %#v must have a non-empty qualified resource\", e)\n\t}\n\tif e.SingularQualifiedResource.Empty() {\n\t\treturn fmt.Errorf(\"store %#v must have a non-empty singular qualified resource\", e)\n\t}\n\tif e.DefaultQualifiedResource.Group != e.SingularQualifiedResource.Group {\n\t\treturn fmt.Errorf(\"store for %#v, singular and plural qualified resource's group name's must match\", e)\n\t}\n\tif e.NewFunc == nil {\n\t\treturn fmt.Errorf(\"store for %s must have NewFunc set\", e.DefaultQualifiedResource.String())\n\t}\n\tif e.NewListFunc == nil {\n\t\treturn fmt.Errorf(\"store for %s must have NewListFunc set\", e.DefaultQualifiedResource.String())\n\t}\n\tif (e.KeyRootFunc == nil) != (e.KeyFunc == nil) {\n\t\treturn fmt.Errorf(\"store for %s must set both KeyRootFunc and KeyFunc or neither\", e.DefaultQualifiedResource.String())\n\t}\n\n\tif e.TableConvertor == nil {\n\t\treturn fmt.Errorf(\"store for %s must set TableConvertor; rest.NewDefaultTableConvertor(e.DefaultQualifiedResource) can be used to output just name/creation time\", e.DefaultQualifiedResource.String())\n\t}\n\n\tvar isNamespaced bool\n\tswitch {\n\tcase e.CreateStrategy != nil:\n\t\tisNamespaced = e.CreateStrategy.NamespaceScoped()\n\tcase e.UpdateStrategy != nil:\n\t\tisNamespaced = e.UpdateStrategy.NamespaceScoped()\n\tdefault:\n\t\treturn fmt.Errorf(\"store for %s must have CreateStrategy or UpdateStrategy set\", e.DefaultQualifiedResource.String())\n\t}\n\n\tif e.DeleteStrategy == nil {\n\t\treturn fmt.Errorf(\"store for %s must have DeleteStrategy set\", e.DefaultQualifiedResource.String())\n\t}\n\n\tif options.RESTOptions == nil {\n\t\treturn fmt.Errorf(\"options for %s must have RESTOptions set\", e.DefaultQualifiedResource.String())\n\t}\n\n\tattrFunc := options.AttrFunc\n\tif attrFunc == nil {\n\t\tif isNamespaced {\n\t\t\tattrFunc = storage.DefaultNamespaceScopedAttr\n\t\t} else {\n\t\t\tattrFunc = storage.DefaultClusterScopedAttr\n\t\t}\n\t}\n\tif e.PredicateFunc == nil {\n\t\te.PredicateFunc = func(label labels.Selector, field fields.Selector) storage.SelectionPredicate {\n\t\t\treturn storage.SelectionPredicate{\n\t\t\t\tLabel: label,\n\t\t\t\tField: field,\n\t\t\t\tGetAttrs: attrFunc,\n\t\t\t}\n\t\t}\n\t}\n\n\terr := validateIndexers(options.Indexers)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\topts, err := options.RESTOptions.GetRESTOptions(e.DefaultQualifiedResource)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// ResourcePrefix must come from the underlying factory\n\tprefix := opts.ResourcePrefix\n\tif !strings.HasPrefix(prefix, \"/\") {\n\t\tprefix = \"/\" + prefix\n\t}\n\tif prefix == \"/\" {\n\t\treturn fmt.Errorf(\"store for %s has an invalid prefix %q\", e.DefaultQualifiedResource.String(), opts.ResourcePrefix)\n\t}\n\n\t// Set the default behavior for storage key generation\n\tif e.KeyRootFunc == nil \u0026\u0026 e.KeyFunc == nil {\n\t\tif isNamespaced {\n\t\t\te.KeyRootFunc = func(ctx context.Context) string {\n\t\t\t\treturn NamespaceKeyRootFunc(ctx, prefix)\n\t\t\t}\n\t\t\te.KeyFunc = func(ctx context.Context, name string) (string, error) {\n\t\t\t\treturn NamespaceKeyFunc(ctx, prefix, name)\n\t\t\t}\n\t\t} else {\n\t\t\te.KeyRootFunc = func(ctx context.Context) string {\n\t\t\t\treturn prefix\n\t\t\t}\n\t\t\te.KeyFunc = func(ctx context.Context, name string) (string, error) {\n\t\t\t\treturn NoNamespaceKeyFunc(ctx, prefix, name)\n\t\t\t}\n\t\t}\n\t}\n\n\t// We adapt the store's keyFunc so that we can use it with the StorageDecorator\n\t// without making any assumptions about where objects are stored in etcd\n\tkeyFunc := func(obj runtime.Object) (string, error) {\n\t\taccessor, err := meta.Accessor(obj)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tif isNamespaced {\n\t\t\treturn e.KeyFunc(genericapirequest.WithNamespace(genericapirequest.NewContext(), accessor.GetNamespace()), accessor.GetName())\n\t\t}\n\n\t\treturn e.KeyFunc(genericapirequest.NewContext(), accessor.GetName())\n\t}\n\n\tif e.DeleteCollectionWorkers == 0 {\n\t\te.DeleteCollectionWorkers = opts.DeleteCollectionWorkers\n\t}\n\n\te.EnableGarbageCollection = opts.EnableGarbageCollection\n\n\tif e.ObjectNameFunc == nil {\n\t\te.ObjectNameFunc = func(obj runtime.Object) (string, error) {\n\t\t\taccessor, err := meta.Accessor(obj)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\treturn accessor.GetName(), nil\n\t\t}\n\t}\n\n\tif e.Storage.Storage == nil {\n\t\te.Storage.Codec = opts.StorageConfig.Codec\n\t\tvar err error\n\t\te.Storage.Storage, e.DestroyFunc, err = opts.Decorator(\n\t\t\topts.StorageConfig,\n\t\t\tprefix,\n\t\t\tkeyFunc,\n\t\t\te.NewFunc,\n\t\t\te.NewListFunc,\n\t\t\tattrFunc,\n\t\t\toptions.TriggerFunc,\n\t\t\toptions.Indexers,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\te.StorageVersioner = opts.StorageConfig.EncodeVersioner\n\n\t\tif opts.CountMetricPollPeriod \u003e 0 {\n\t\t\tstopFunc := e.startObservingCount(opts.CountMetricPollPeriod, opts.StorageObjectCountTracker)\n\t\t\tpreviousDestroy := e.DestroyFunc\n\t\t\tvar once sync.Once\n\t\t\te.DestroyFunc = func() {\n\t\t\t\tonce.Do(func() {\n\t\t\t\t\tstopFunc()\n\t\t\t\t\tif previousDestroy != nil {\n\t\t\t\t\t\tpreviousDestroy()\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":1341,"to":1506}} {"id":100017783,"name":"startObservingCount","signature":"func (e *Store) startObservingCount(period time.Duration, objectCountTracker flowcontrolrequest.StorageObjectCountTracker) func()","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// startObservingCount starts monitoring given prefix and periodically updating metrics. It returns a function to stop collection.\nfunc (e *Store) startObservingCount(period time.Duration, objectCountTracker flowcontrolrequest.StorageObjectCountTracker) func() {\n\tprefix := e.KeyRootFunc(genericapirequest.NewContext())\n\tresourceName := e.DefaultQualifiedResource.String()\n\tklog.V(2).InfoS(\"Monitoring resource count at path\", \"resource\", resourceName, \"path\", \"\u003cstorage-prefix\u003e/\"+prefix)\n\tstopCh := make(chan struct{})\n\tgo wait.JitterUntil(func() {\n\t\tcount, err := e.Storage.Count(prefix)\n\t\tif err != nil {\n\t\t\tklog.V(5).InfoS(\"Failed to update storage count metric\", \"err\", err)\n\t\t\tcount = -1\n\t\t}\n\n\t\tmetrics.UpdateObjectCount(resourceName, count)\n\t\tif objectCountTracker != nil {\n\t\t\tobjectCountTracker.Set(resourceName, count)\n\t\t}\n\t}, period, resourceCountPollPeriodJitter, true, stopCh)\n\treturn func() { close(stopCh) }\n}","line":{"from":1508,"to":1527}} {"id":100017784,"name":"ConvertToTable","signature":"func (e *Store) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"func (e *Store) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\tif e.TableConvertor != nil {\n\t\treturn e.TableConvertor.ConvertToTable(ctx, object, tableOptions)\n\t}\n\treturn rest.NewDefaultTableConvertor(e.DefaultQualifiedResource).ConvertToTable(ctx, object, tableOptions)\n}","line":{"from":1529,"to":1534}} {"id":100017785,"name":"StorageVersion","signature":"func (e *Store) StorageVersion() runtime.GroupVersioner","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"func (e *Store) StorageVersion() runtime.GroupVersioner {\n\treturn e.StorageVersioner\n}","line":{"from":1536,"to":1538}} {"id":100017786,"name":"GetResetFields","signature":"func (e *Store) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (e *Store) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tif e.ResetFieldsStrategy == nil {\n\t\treturn nil\n\t}\n\treturn e.ResetFieldsStrategy.GetResetFields()\n}","line":{"from":1540,"to":1546}} {"id":100017787,"name":"GetSingularName","signature":"func (e *Store) GetSingularName() string","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"func (e *Store) GetSingularName() string {\n\treturn e.SingularQualifiedResource.Resource\n}","line":{"from":1548,"to":1550}} {"id":100017788,"name":"validateIndexers","signature":"func validateIndexers(indexers *cache.Indexers) error","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go","code":"// validateIndexers will check the prefix of indexers.\nfunc validateIndexers(indexers *cache.Indexers) error {\n\tif indexers == nil {\n\t\treturn nil\n\t}\n\tfor indexName := range *indexers {\n\t\tif len(indexName) \u003c= 2 || (indexName[:2] != \"l:\" \u0026\u0026 indexName[:2] != \"f:\") {\n\t\t\treturn fmt.Errorf(\"index must prefix with \\\"l:\\\" or \\\"f:\\\"\")\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":1552,"to":1563}} {"id":100017789,"name":"Check","signature":"func (checker GenericHttpResponseChecker) Check(resp *http.Response) error","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/rest/response_checker.go","code":"func (checker GenericHttpResponseChecker) Check(resp *http.Response) error {\n\tif resp.StatusCode \u003c http.StatusOK || resp.StatusCode \u003e http.StatusPartialContent {\n\t\tdefer resp.Body.Close()\n\t\tbodyBytes, err := ioutil.ReadAll(io.LimitReader(resp.Body, maxReadLength))\n\t\tif err != nil {\n\t\t\treturn errors.NewInternalError(err)\n\t\t}\n\t\tbodyText := string(bodyBytes)\n\n\t\tswitch {\n\t\tcase resp.StatusCode == http.StatusInternalServerError:\n\t\t\treturn errors.NewInternalError(fmt.Errorf(\"%s\", bodyText))\n\t\tcase resp.StatusCode == http.StatusBadRequest:\n\t\t\treturn errors.NewBadRequest(bodyText)\n\t\tcase resp.StatusCode == http.StatusNotFound:\n\t\t\treturn errors.NewGenericServerResponse(resp.StatusCode, \"\", checker.QualifiedResource, checker.Name, bodyText, 0, false)\n\t\t}\n\t\treturn errors.NewGenericServerResponse(resp.StatusCode, \"\", checker.QualifiedResource, checker.Name, bodyText, 0, false)\n\t}\n\treturn nil\n}","line":{"from":47,"to":67}} {"id":100017790,"name":"NewGenericHttpResponseChecker","signature":"func NewGenericHttpResponseChecker(qualifiedResource schema.GroupResource, name string) GenericHttpResponseChecker","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/rest/response_checker.go","code":"func NewGenericHttpResponseChecker(qualifiedResource schema.GroupResource, name string) GenericHttpResponseChecker {\n\treturn GenericHttpResponseChecker{QualifiedResource: qualifiedResource, Name: name}\n}","line":{"from":69,"to":71}} {"id":100017791,"name":"GetObjectKind","signature":"func (obj *LocationStreamer) GetObjectKind() schema.ObjectKind","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/rest/streamer.go","code":"func (obj *LocationStreamer) GetObjectKind() schema.ObjectKind {\n\treturn schema.EmptyObjectKind\n}","line":{"from":58,"to":60}} {"id":100017792,"name":"DeepCopyObject","signature":"func (obj *LocationStreamer) DeepCopyObject() runtime.Object","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/rest/streamer.go","code":"func (obj *LocationStreamer) DeepCopyObject() runtime.Object {\n\tpanic(\"rest.LocationStreamer does not implement DeepCopyObject\")\n}","line":{"from":61,"to":63}} {"id":100017793,"name":"InputStream","signature":"func (s *LocationStreamer) InputStream(ctx context.Context, apiVersion, acceptHeader string) (stream io.ReadCloser, flush bool, contentType string, err error)","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/rest/streamer.go","code":"// InputStream returns a stream with the contents of the URL location. If no location is provided,\n// a null stream is returned.\nfunc (s *LocationStreamer) InputStream(ctx context.Context, apiVersion, acceptHeader string) (stream io.ReadCloser, flush bool, contentType string, err error) {\n\tif s.Location == nil {\n\t\t// If no location was provided, return a null stream\n\t\treturn nil, false, \"\", nil\n\t}\n\ttransport := s.Transport\n\tif transport == nil {\n\t\ttransport = http.DefaultTransport\n\t}\n\n\tclient := \u0026http.Client{\n\t\tTransport: transport,\n\t\tCheckRedirect: s.RedirectChecker,\n\t}\n\treq, err := http.NewRequest(\"GET\", s.Location.String(), nil)\n\tif err != nil {\n\t\treturn nil, false, \"\", fmt.Errorf(\"failed to construct request for %s, got %v\", s.Location.String(), err)\n\t}\n\t// Pass the parent context down to the request to ensure that the resources\n\t// will be release properly.\n\treq = req.WithContext(ctx)\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\t// TODO prefer segregate TLS errors more reliably, but we do want to increment a count\n\t\tif strings.Contains(err.Error(), \"x509:\") \u0026\u0026 s.TLSVerificationErrorCounter != nil {\n\t\t\ts.TLSVerificationErrorCounter.Inc()\n\t\t\tif s.DeprecatedTLSVerificationErrorCounter != nil {\n\t\t\t\ts.DeprecatedTLSVerificationErrorCounter.Inc()\n\t\t\t}\n\t\t}\n\t\treturn nil, false, \"\", err\n\t}\n\n\tif s.ResponseChecker != nil {\n\t\tif err = s.ResponseChecker.Check(resp); err != nil {\n\t\t\treturn nil, false, \"\", err\n\t\t}\n\t}\n\n\tcontentType = s.ContentType\n\tif len(contentType) == 0 {\n\t\tcontentType = resp.Header.Get(\"Content-Type\")\n\t\tif len(contentType) \u003e 0 {\n\t\t\tcontentType = strings.TrimSpace(strings.SplitN(contentType, \";\", 2)[0])\n\t\t}\n\t}\n\tflush = s.Flush\n\tstream = resp.Body\n\treturn\n}","line":{"from":65,"to":117}} {"id":100017794,"name":"PreventRedirects","signature":"func PreventRedirects(_ *http.Request, _ []*http.Request) error","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/rest/streamer.go","code":"// PreventRedirects is a redirect checker that prevents the client from following a redirect.\nfunc PreventRedirects(_ *http.Request, _ []*http.Request) error {\n\treturn errors.New(\"redirects forbidden\")\n}","line":{"from":119,"to":122}} {"id":100017795,"name":"UndecoratedStorage","signature":"func UndecoratedStorage(","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/storage_decorator.go","code":"// UndecoratedStorage returns the given a new storage from the given config\n// without any decoration.\nfunc UndecoratedStorage(\n\tconfig *storagebackend.ConfigForResource,\n\tresourcePrefix string,\n\tkeyFunc func(obj runtime.Object) (string, error),\n\tnewFunc func() runtime.Object,\n\tnewListFunc func() runtime.Object,\n\tgetAttrsFunc storage.AttrFunc,\n\ttrigger storage.IndexerFuncs,\n\tindexers *cache.Indexers) (storage.Interface, factory.DestroyFunc, error) {\n\treturn NewRawStorage(config, newFunc)\n}","line":{"from":39,"to":51}} {"id":100017796,"name":"NewRawStorage","signature":"func NewRawStorage(config *storagebackend.ConfigForResource, newFunc func() runtime.Object) (storage.Interface, factory.DestroyFunc, error)","file":"staging/src/k8s.io/apiserver/pkg/registry/generic/storage_decorator.go","code":"// NewRawStorage creates the low level kv storage. This is a work-around for current\n// two layer of same storage interface.\n// TODO: Once cacher is enabled on all registries (event registry is special), we will remove this method.\nfunc NewRawStorage(config *storagebackend.ConfigForResource, newFunc func() runtime.Object) (storage.Interface, factory.DestroyFunc, error) {\n\treturn factory.Create(*config, newFunc)\n}","line":{"from":53,"to":58}} {"id":100017797,"name":"BeforeCreate","signature":"func BeforeCreate(strategy RESTCreateStrategy, ctx context.Context, obj runtime.Object) error","file":"staging/src/k8s.io/apiserver/pkg/registry/rest/create.go","code":"// BeforeCreate ensures that common operations for all resources are performed on creation. It only returns\n// errors that can be converted to api.Status. It invokes PrepareForCreate, then Validate.\n// It returns nil if the object should be created.\nfunc BeforeCreate(strategy RESTCreateStrategy, ctx context.Context, obj runtime.Object) error {\n\tobjectMeta, kind, kerr := objectMetaAndKind(strategy, obj)\n\tif kerr != nil {\n\t\treturn kerr\n\t}\n\n\t// ensure that system-critical metadata has been populated\n\tif !metav1.HasObjectMetaSystemFieldValues(objectMeta) {\n\t\treturn errors.NewInternalError(fmt.Errorf(\"system metadata was not initialized\"))\n\t}\n\n\t// ensure the name has been generated\n\tif len(objectMeta.GetGenerateName()) \u003e 0 \u0026\u0026 len(objectMeta.GetName()) == 0 {\n\t\treturn errors.NewInternalError(fmt.Errorf(\"metadata.name was not generated\"))\n\t}\n\n\t// ensure namespace on the object is correct, or error if a conflicting namespace was set in the object\n\trequestNamespace, ok := genericapirequest.NamespaceFrom(ctx)\n\tif !ok {\n\t\treturn errors.NewInternalError(fmt.Errorf(\"no namespace information found in request context\"))\n\t}\n\tif err := EnsureObjectNamespaceMatchesRequestNamespace(ExpectedNamespaceForScope(requestNamespace, strategy.NamespaceScoped()), objectMeta); err != nil {\n\t\treturn err\n\t}\n\n\tstrategy.PrepareForCreate(ctx, obj)\n\n\tif errs := strategy.Validate(ctx, obj); len(errs) \u003e 0 {\n\t\treturn errors.NewInvalid(kind.GroupKind(), objectMeta.GetName(), errs)\n\t}\n\n\t// Custom validation (including name validation) passed\n\t// Now run common validation on object meta\n\t// Do this *after* custom validation so that specific error messages are shown whenever possible\n\tif errs := genericvalidation.ValidateObjectMetaAccessor(objectMeta, strategy.NamespaceScoped(), path.ValidatePathSegmentName, field.NewPath(\"metadata\")); len(errs) \u003e 0 {\n\t\treturn errors.NewInvalid(kind.GroupKind(), objectMeta.GetName(), errs)\n\t}\n\n\tfor _, w := range strategy.WarningsOnCreate(ctx, obj) {\n\t\twarning.AddWarning(ctx, \"\", w)\n\t}\n\n\tstrategy.Canonicalize(obj)\n\n\treturn nil\n}","line":{"from":92,"to":140}} {"id":100017798,"name":"CheckGeneratedNameError","signature":"func CheckGeneratedNameError(ctx context.Context, strategy RESTCreateStrategy, err error, obj runtime.Object) error","file":"staging/src/k8s.io/apiserver/pkg/registry/rest/create.go","code":"// CheckGeneratedNameError checks whether an error that occurred creating a resource is due\n// to generation being unable to pick a valid name.\nfunc CheckGeneratedNameError(ctx context.Context, strategy RESTCreateStrategy, err error, obj runtime.Object) error {\n\tif !errors.IsAlreadyExists(err) {\n\t\treturn err\n\t}\n\n\tobjectMeta, gvk, kerr := objectMetaAndKind(strategy, obj)\n\tif kerr != nil {\n\t\treturn kerr\n\t}\n\n\tif len(objectMeta.GetGenerateName()) == 0 {\n\t\t// If we don't have a generated name, return the original error (AlreadyExists).\n\t\t// When we're here, the user picked a name that is causing a conflict.\n\t\treturn err\n\t}\n\n\t// Get the group resource information from the context, if populated.\n\tgr := schema.GroupResource{}\n\tif requestInfo, found := genericapirequest.RequestInfoFrom(ctx); found {\n\t\tgr = schema.GroupResource{Group: gvk.Group, Resource: requestInfo.Resource}\n\t}\n\n\t// If we have a name and generated name, the server picked a name\n\t// that already exists.\n\treturn errors.NewGenerateNameConflict(gr, objectMeta.GetName(), 1)\n}","line":{"from":142,"to":169}} {"id":100017799,"name":"objectMetaAndKind","signature":"func objectMetaAndKind(typer runtime.ObjectTyper, obj runtime.Object) (metav1.Object, schema.GroupVersionKind, error)","file":"staging/src/k8s.io/apiserver/pkg/registry/rest/create.go","code":"// objectMetaAndKind retrieves kind and ObjectMeta from a runtime object, or returns an error.\nfunc objectMetaAndKind(typer runtime.ObjectTyper, obj runtime.Object) (metav1.Object, schema.GroupVersionKind, error) {\n\tobjectMeta, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn nil, schema.GroupVersionKind{}, errors.NewInternalError(err)\n\t}\n\tkinds, _, err := typer.ObjectKinds(obj)\n\tif err != nil {\n\t\treturn nil, schema.GroupVersionKind{}, errors.NewInternalError(err)\n\t}\n\treturn objectMeta, kinds[0], nil\n}","line":{"from":171,"to":182}} {"id":100017800,"name":"AdmissionToValidateObjectFunc","signature":"func AdmissionToValidateObjectFunc(admit admission.Interface, staticAttributes admission.Attributes, o admission.ObjectInterfaces) ValidateObjectFunc","file":"staging/src/k8s.io/apiserver/pkg/registry/rest/create.go","code":"// AdmissionToValidateObjectFunc converts validating admission to a rest validate object func\nfunc AdmissionToValidateObjectFunc(admit admission.Interface, staticAttributes admission.Attributes, o admission.ObjectInterfaces) ValidateObjectFunc {\n\tvalidatingAdmission, ok := admit.(admission.ValidationInterface)\n\tif !ok {\n\t\treturn func(ctx context.Context, obj runtime.Object) error { return nil }\n\t}\n\treturn func(ctx context.Context, obj runtime.Object) error {\n\t\tname := staticAttributes.GetName()\n\t\t// in case the generated name is populated\n\t\tif len(name) == 0 {\n\t\t\tif metadata, err := meta.Accessor(obj); err == nil {\n\t\t\t\tname = metadata.GetName()\n\t\t\t}\n\t\t}\n\n\t\tfinalAttributes := admission.NewAttributesRecord(\n\t\t\tobj,\n\t\t\tstaticAttributes.GetOldObject(),\n\t\t\tstaticAttributes.GetKind(),\n\t\t\tstaticAttributes.GetNamespace(),\n\t\t\tname,\n\t\t\tstaticAttributes.GetResource(),\n\t\t\tstaticAttributes.GetSubresource(),\n\t\t\tstaticAttributes.GetOperation(),\n\t\t\tstaticAttributes.GetOperationOptions(),\n\t\t\tstaticAttributes.IsDryRun(),\n\t\t\tstaticAttributes.GetUserInfo(),\n\t\t)\n\t\tif !validatingAdmission.Handles(finalAttributes.GetOperation()) {\n\t\t\treturn nil\n\t\t}\n\t\treturn validatingAdmission.Validate(ctx, finalAttributes, o)\n\t}\n}","line":{"from":190,"to":223}} {"id":100017801,"name":"BeforeDelete","signature":"func BeforeDelete(strategy RESTDeleteStrategy, ctx context.Context, obj runtime.Object, options *metav1.DeleteOptions) (graceful, gracefulPending bool, err error)","file":"staging/src/k8s.io/apiserver/pkg/registry/rest/delete.go","code":"// BeforeDelete tests whether the object can be gracefully deleted.\n// If graceful is set, the object should be gracefully deleted. If gracefulPending\n// is set, the object has already been gracefully deleted (and the provided grace\n// period is longer than the time to deletion). An error is returned if the\n// condition cannot be checked or the gracePeriodSeconds is invalid. The options\n// argument may be updated with default values if graceful is true. Second place\n// where we set deletionTimestamp is pkg/registry/generic/registry/store.go.\n// This function is responsible for setting deletionTimestamp during gracefulDeletion,\n// other one for cascading deletions.\nfunc BeforeDelete(strategy RESTDeleteStrategy, ctx context.Context, obj runtime.Object, options *metav1.DeleteOptions) (graceful, gracefulPending bool, err error) {\n\tobjectMeta, gvk, kerr := objectMetaAndKind(strategy, obj)\n\tif kerr != nil {\n\t\treturn false, false, kerr\n\t}\n\tif errs := validation.ValidateDeleteOptions(options); len(errs) \u003e 0 {\n\t\treturn false, false, errors.NewInvalid(schema.GroupKind{Group: metav1.GroupName, Kind: \"DeleteOptions\"}, \"\", errs)\n\t}\n\t// Checking the Preconditions here to fail early. They'll be enforced later on when we actually do the deletion, too.\n\tif options.Preconditions != nil {\n\t\tif options.Preconditions.UID != nil \u0026\u0026 *options.Preconditions.UID != objectMeta.GetUID() {\n\t\t\treturn false, false, errors.NewConflict(schema.GroupResource{Group: gvk.Group, Resource: gvk.Kind}, objectMeta.GetName(), fmt.Errorf(\"the UID in the precondition (%s) does not match the UID in record (%s). The object might have been deleted and then recreated\", *options.Preconditions.UID, objectMeta.GetUID()))\n\t\t}\n\t\tif options.Preconditions.ResourceVersion != nil \u0026\u0026 *options.Preconditions.ResourceVersion != objectMeta.GetResourceVersion() {\n\t\t\treturn false, false, errors.NewConflict(schema.GroupResource{Group: gvk.Group, Resource: gvk.Kind}, objectMeta.GetName(), fmt.Errorf(\"the ResourceVersion in the precondition (%s) does not match the ResourceVersion in record (%s). The object might have been modified\", *options.Preconditions.ResourceVersion, objectMeta.GetResourceVersion()))\n\t\t}\n\t}\n\n\t// Negative values will be treated as the value `1s` on the delete path.\n\tif gracePeriodSeconds := options.GracePeriodSeconds; gracePeriodSeconds != nil \u0026\u0026 *gracePeriodSeconds \u003c 0 {\n\t\toptions.GracePeriodSeconds = utilpointer.Int64(1)\n\t}\n\tif deletionGracePeriodSeconds := objectMeta.GetDeletionGracePeriodSeconds(); deletionGracePeriodSeconds != nil \u0026\u0026 *deletionGracePeriodSeconds \u003c 0 {\n\t\tobjectMeta.SetDeletionGracePeriodSeconds(utilpointer.Int64(1))\n\t}\n\n\tgracefulStrategy, ok := strategy.(RESTGracefulDeleteStrategy)\n\tif !ok {\n\t\t// If we're not deleting gracefully there's no point in updating Generation, as we won't update\n\t\t// the obcject before deleting it.\n\t\treturn false, false, nil\n\t}\n\t// if the object is already being deleted, no need to update generation.\n\tif objectMeta.GetDeletionTimestamp() != nil {\n\t\t// if we are already being deleted, we may only shorten the deletion grace period\n\t\t// this means the object was gracefully deleted previously but deletionGracePeriodSeconds was not set,\n\t\t// so we force deletion immediately\n\t\t// IMPORTANT:\n\t\t// The deletion operation happens in two phases.\n\t\t// 1. Update to set DeletionGracePeriodSeconds and DeletionTimestamp\n\t\t// 2. Delete the object from storage.\n\t\t// If the update succeeds, but the delete fails (network error, internal storage error, etc.),\n\t\t// a resource was previously left in a state that was non-recoverable. We\n\t\t// check if the existing stored resource has a grace period as 0 and if so\n\t\t// attempt to delete immediately in order to recover from this scenario.\n\t\tif objectMeta.GetDeletionGracePeriodSeconds() == nil || *objectMeta.GetDeletionGracePeriodSeconds() == 0 {\n\t\t\treturn false, false, nil\n\t\t}\n\t\t// only a shorter grace period may be provided by a user\n\t\tif options.GracePeriodSeconds != nil {\n\t\t\tperiod := int64(*options.GracePeriodSeconds)\n\t\t\tif period \u003e= *objectMeta.GetDeletionGracePeriodSeconds() {\n\t\t\t\treturn false, true, nil\n\t\t\t}\n\t\t\tnewDeletionTimestamp := metav1.NewTime(\n\t\t\t\tobjectMeta.GetDeletionTimestamp().Add(-time.Second * time.Duration(*objectMeta.GetDeletionGracePeriodSeconds())).\n\t\t\t\t\tAdd(time.Second * time.Duration(*options.GracePeriodSeconds)))\n\t\t\tobjectMeta.SetDeletionTimestamp(\u0026newDeletionTimestamp)\n\t\t\tobjectMeta.SetDeletionGracePeriodSeconds(\u0026period)\n\t\t\treturn true, false, nil\n\t\t}\n\t\t// graceful deletion is pending, do nothing\n\t\toptions.GracePeriodSeconds = objectMeta.GetDeletionGracePeriodSeconds()\n\t\treturn false, true, nil\n\t}\n\n\t// `CheckGracefulDelete` will be implemented by specific strategy\n\tif !gracefulStrategy.CheckGracefulDelete(ctx, obj, options) {\n\t\treturn false, false, nil\n\t}\n\n\tif options.GracePeriodSeconds == nil {\n\t\treturn false, false, errors.NewInternalError(fmt.Errorf(\"options.GracePeriodSeconds should not be nil\"))\n\t}\n\n\tnow := metav1.NewTime(metav1.Now().Add(time.Second * time.Duration(*options.GracePeriodSeconds)))\n\tobjectMeta.SetDeletionTimestamp(\u0026now)\n\tobjectMeta.SetDeletionGracePeriodSeconds(options.GracePeriodSeconds)\n\t// If it's the first graceful deletion we are going to set the DeletionTimestamp to non-nil.\n\t// Controllers of the object that's being deleted shouldn't take any nontrivial actions, hence its behavior changes.\n\t// Thus we need to bump object's Generation (if set). This handles generation bump during graceful deletion.\n\t// The bump for objects that don't support graceful deletion is handled in pkg/registry/generic/registry/store.go.\n\tif objectMeta.GetGeneration() \u003e 0 {\n\t\tobjectMeta.SetGeneration(objectMeta.GetGeneration() + 1)\n\t}\n\n\treturn true, false, nil\n}","line":{"from":66,"to":162}} {"id":100017802,"name":"AdmissionToValidateObjectDeleteFunc","signature":"func AdmissionToValidateObjectDeleteFunc(admit admission.Interface, staticAttributes admission.Attributes, objInterfaces admission.ObjectInterfaces) ValidateObjectFunc","file":"staging/src/k8s.io/apiserver/pkg/registry/rest/delete.go","code":"// AdmissionToValidateObjectDeleteFunc returns a admission validate func for object deletion\nfunc AdmissionToValidateObjectDeleteFunc(admit admission.Interface, staticAttributes admission.Attributes, objInterfaces admission.ObjectInterfaces) ValidateObjectFunc {\n\tmutatingAdmission, isMutatingAdmission := admit.(admission.MutationInterface)\n\tvalidatingAdmission, isValidatingAdmission := admit.(admission.ValidationInterface)\n\n\tmutating := isMutatingAdmission \u0026\u0026 mutatingAdmission.Handles(staticAttributes.GetOperation())\n\tvalidating := isValidatingAdmission \u0026\u0026 validatingAdmission.Handles(staticAttributes.GetOperation())\n\n\treturn func(ctx context.Context, old runtime.Object) error {\n\t\tif !mutating \u0026\u0026 !validating {\n\t\t\treturn nil\n\t\t}\n\t\tfinalAttributes := admission.NewAttributesRecord(\n\t\t\tnil,\n\t\t\t// Deep copy the object to avoid accidentally changing the object.\n\t\t\told.DeepCopyObject(),\n\t\t\tstaticAttributes.GetKind(),\n\t\t\tstaticAttributes.GetNamespace(),\n\t\t\tstaticAttributes.GetName(),\n\t\t\tstaticAttributes.GetResource(),\n\t\t\tstaticAttributes.GetSubresource(),\n\t\t\tstaticAttributes.GetOperation(),\n\t\t\tstaticAttributes.GetOperationOptions(),\n\t\t\tstaticAttributes.IsDryRun(),\n\t\t\tstaticAttributes.GetUserInfo(),\n\t\t)\n\t\tif mutating {\n\t\t\tif err := mutatingAdmission.Admit(ctx, finalAttributes, objInterfaces); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif validating {\n\t\t\tif err := validatingAdmission.Validate(ctx, finalAttributes, objInterfaces); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n}","line":{"from":164,"to":202}} {"id":100017803,"name":"WipeObjectMetaSystemFields","signature":"func WipeObjectMetaSystemFields(meta metav1.Object)","file":"staging/src/k8s.io/apiserver/pkg/registry/rest/meta.go","code":"// WipeObjectMetaSystemFields erases fields that are managed by the system on ObjectMeta.\nfunc WipeObjectMetaSystemFields(meta metav1.Object) {\n\tmeta.SetCreationTimestamp(metav1.Time{})\n\tmeta.SetUID(\"\")\n\tmeta.SetDeletionTimestamp(nil)\n\tmeta.SetDeletionGracePeriodSeconds(nil)\n\tmeta.SetSelfLink(\"\")\n}","line":{"from":26,"to":33}} {"id":100017804,"name":"FillObjectMetaSystemFields","signature":"func FillObjectMetaSystemFields(meta metav1.Object)","file":"staging/src/k8s.io/apiserver/pkg/registry/rest/meta.go","code":"// FillObjectMetaSystemFields populates fields that are managed by the system on ObjectMeta.\nfunc FillObjectMetaSystemFields(meta metav1.Object) {\n\tmeta.SetCreationTimestamp(metav1.Now())\n\tmeta.SetUID(uuid.NewUUID())\n}","line":{"from":35,"to":39}} {"id":100017805,"name":"EnsureObjectNamespaceMatchesRequestNamespace","signature":"func EnsureObjectNamespaceMatchesRequestNamespace(requestNamespace string, obj metav1.Object) error","file":"staging/src/k8s.io/apiserver/pkg/registry/rest/meta.go","code":"// EnsureObjectNamespaceMatchesRequestNamespace returns an error if obj.Namespace and requestNamespace\n// are both populated and do not match. If either is unpopulated, it modifies obj as needed to ensure\n// obj.GetNamespace() == requestNamespace.\nfunc EnsureObjectNamespaceMatchesRequestNamespace(requestNamespace string, obj metav1.Object) error {\n\tobjNamespace := obj.GetNamespace()\n\tswitch {\n\tcase objNamespace == requestNamespace:\n\t\t// already matches, no-op\n\t\treturn nil\n\n\tcase objNamespace == metav1.NamespaceNone:\n\t\t// unset, default to request namespace\n\t\tobj.SetNamespace(requestNamespace)\n\t\treturn nil\n\n\tcase requestNamespace == metav1.NamespaceNone:\n\t\t// cluster-scoped, clear namespace\n\t\tobj.SetNamespace(metav1.NamespaceNone)\n\t\treturn nil\n\n\tdefault:\n\t\t// mismatch, error\n\t\treturn errors.NewBadRequest(\"the namespace of the provided object does not match the namespace sent on the request\")\n\t}\n}","line":{"from":41,"to":65}} {"id":100017806,"name":"ExpectedNamespaceForScope","signature":"func ExpectedNamespaceForScope(requestNamespace string, namespaceScoped bool) string","file":"staging/src/k8s.io/apiserver/pkg/registry/rest/meta.go","code":"// ExpectedNamespaceForScope returns the expected namespace for a resource, given the request namespace and resource scope.\nfunc ExpectedNamespaceForScope(requestNamespace string, namespaceScoped bool) string {\n\tif namespaceScoped {\n\t\treturn requestNamespace\n\t}\n\treturn \"\"\n}","line":{"from":67,"to":73}} {"id":100017807,"name":"ExpectedNamespaceForResource","signature":"func ExpectedNamespaceForResource(requestNamespace string, resource schema.GroupVersionResource) string","file":"staging/src/k8s.io/apiserver/pkg/registry/rest/meta.go","code":"// ExpectedNamespaceForResource returns the expected namespace for a resource, given the request namespace.\nfunc ExpectedNamespaceForResource(requestNamespace string, resource schema.GroupVersionResource) string {\n\tif resource.Resource == \"namespaces\" \u0026\u0026 resource.Group == \"\" {\n\t\treturn \"\"\n\t}\n\treturn requestNamespace\n}","line":{"from":75,"to":81}} {"id":100017808,"name":"ValidateAllObjectFunc","signature":"func ValidateAllObjectFunc(ctx context.Context, obj runtime.Object) error","file":"staging/src/k8s.io/apiserver/pkg/registry/rest/rest.go","code":"// ValidateAllObjectFunc is a \"admit everything\" instance of ValidateObjectFunc.\nfunc ValidateAllObjectFunc(ctx context.Context, obj runtime.Object) error {\n\treturn nil\n}","line":{"from":237,"to":240}} {"id":100017809,"name":"ValidateAllObjectUpdateFunc","signature":"func ValidateAllObjectUpdateFunc(ctx context.Context, obj, old runtime.Object) error","file":"staging/src/k8s.io/apiserver/pkg/registry/rest/rest.go","code":"// ValidateAllObjectUpdateFunc is a \"admit everything\" instance of ValidateObjectUpdateFunc.\nfunc ValidateAllObjectUpdateFunc(ctx context.Context, obj, old runtime.Object) error {\n\treturn nil\n}","line":{"from":247,"to":250}} {"id":100017810,"name":"NewDefaultTableConvertor","signature":"func NewDefaultTableConvertor(defaultQualifiedResource schema.GroupResource) TableConvertor","file":"staging/src/k8s.io/apiserver/pkg/registry/rest/table.go","code":"// NewDefaultTableConvertor creates a default convertor; the provided resource is used for error messages\n// if no resource info can be determined from the context passed to ConvertToTable.\nfunc NewDefaultTableConvertor(defaultQualifiedResource schema.GroupResource) TableConvertor {\n\treturn defaultTableConvertor{defaultQualifiedResource: defaultQualifiedResource}\n}","line":{"from":36,"to":40}} {"id":100017811,"name":"ConvertToTable","signature":"func (c defaultTableConvertor) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"staging/src/k8s.io/apiserver/pkg/registry/rest/table.go","code":"func (c defaultTableConvertor) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\tvar table metav1.Table\n\tfn := func(obj runtime.Object) error {\n\t\tm, err := meta.Accessor(obj)\n\t\tif err != nil {\n\t\t\tresource := c.defaultQualifiedResource\n\t\t\tif info, ok := genericapirequest.RequestInfoFrom(ctx); ok {\n\t\t\t\tresource = schema.GroupResource{Group: info.APIGroup, Resource: info.Resource}\n\t\t\t}\n\t\t\treturn errNotAcceptable{resource: resource}\n\t\t}\n\t\ttable.Rows = append(table.Rows, metav1.TableRow{\n\t\t\tCells: []interface{}{m.GetName(), m.GetCreationTimestamp().Time.UTC().Format(time.RFC3339)},\n\t\t\tObject: runtime.RawExtension{Object: obj},\n\t\t})\n\t\treturn nil\n\t}\n\tswitch {\n\tcase meta.IsListType(object):\n\t\tif err := meta.EachListItem(object, fn); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tdefault:\n\t\tif err := fn(object); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif m, err := meta.ListAccessor(object); err == nil {\n\t\ttable.ResourceVersion = m.GetResourceVersion()\n\t\ttable.Continue = m.GetContinue()\n\t\ttable.RemainingItemCount = m.GetRemainingItemCount()\n\t} else {\n\t\tif m, err := meta.CommonAccessor(object); err == nil {\n\t\t\ttable.ResourceVersion = m.GetResourceVersion()\n\t\t}\n\t}\n\tif opt, ok := tableOptions.(*metav1.TableOptions); !ok || !opt.NoHeaders {\n\t\ttable.ColumnDefinitions = []metav1.TableColumnDefinition{\n\t\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: swaggerMetadataDescriptions[\"name\"]},\n\t\t\t{Name: \"Created At\", Type: \"date\", Description: swaggerMetadataDescriptions[\"creationTimestamp\"]},\n\t\t}\n\t}\n\treturn \u0026table, nil\n}","line":{"from":44,"to":87}} {"id":100017812,"name":"Error","signature":"func (e errNotAcceptable) Error() string","file":"staging/src/k8s.io/apiserver/pkg/registry/rest/table.go","code":"func (e errNotAcceptable) Error() string {\n\treturn fmt.Sprintf(\"the resource %s does not support being converted to a Table\", e.resource)\n}","line":{"from":94,"to":96}} {"id":100017813,"name":"Status","signature":"func (e errNotAcceptable) Status() metav1.Status","file":"staging/src/k8s.io/apiserver/pkg/registry/rest/table.go","code":"func (e errNotAcceptable) Status() metav1.Status {\n\treturn metav1.Status{\n\t\tStatus: metav1.StatusFailure,\n\t\tCode: http.StatusNotAcceptable,\n\t\tReason: metav1.StatusReason(\"NotAcceptable\"),\n\t\tMessage: e.Error(),\n\t}\n}","line":{"from":98,"to":105}} {"id":100017814,"name":"validateCommonFields","signature":"func validateCommonFields(obj, old runtime.Object, strategy RESTUpdateStrategy) (field.ErrorList, error)","file":"staging/src/k8s.io/apiserver/pkg/registry/rest/update.go","code":"// TODO: add other common fields that require global validation.\nfunc validateCommonFields(obj, old runtime.Object, strategy RESTUpdateStrategy) (field.ErrorList, error) {\n\tallErrs := field.ErrorList{}\n\tobjectMeta, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get new object metadata: %v\", err)\n\t}\n\toldObjectMeta, err := meta.Accessor(old)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get old object metadata: %v\", err)\n\t}\n\tallErrs = append(allErrs, genericvalidation.ValidateObjectMetaAccessor(objectMeta, strategy.NamespaceScoped(), path.ValidatePathSegmentName, field.NewPath(\"metadata\"))...)\n\tallErrs = append(allErrs, genericvalidation.ValidateObjectMetaAccessorUpdate(objectMeta, oldObjectMeta, field.NewPath(\"metadata\"))...)\n\n\treturn allErrs, nil\n}","line":{"from":86,"to":101}} {"id":100017815,"name":"BeforeUpdate","signature":"func BeforeUpdate(strategy RESTUpdateStrategy, ctx context.Context, obj, old runtime.Object) error","file":"staging/src/k8s.io/apiserver/pkg/registry/rest/update.go","code":"// BeforeUpdate ensures that common operations for all resources are performed on update. It only returns\n// errors that can be converted to api.Status. It will invoke update validation with the provided existing\n// and updated objects.\n// It sets zero values only if the object does not have a zero value for the respective field.\nfunc BeforeUpdate(strategy RESTUpdateStrategy, ctx context.Context, obj, old runtime.Object) error {\n\tobjectMeta, kind, kerr := objectMetaAndKind(strategy, obj)\n\tif kerr != nil {\n\t\treturn kerr\n\t}\n\n\t// ensure namespace on the object is correct, or error if a conflicting namespace was set in the object\n\trequestNamespace, ok := genericapirequest.NamespaceFrom(ctx)\n\tif !ok {\n\t\treturn errors.NewInternalError(fmt.Errorf(\"no namespace information found in request context\"))\n\t}\n\tif err := EnsureObjectNamespaceMatchesRequestNamespace(ExpectedNamespaceForScope(requestNamespace, strategy.NamespaceScoped()), objectMeta); err != nil {\n\t\treturn err\n\t}\n\n\t// Ensure requests cannot update generation\n\toldMeta, err := meta.Accessor(old)\n\tif err != nil {\n\t\treturn err\n\t}\n\tobjectMeta.SetGeneration(oldMeta.GetGeneration())\n\n\tstrategy.PrepareForUpdate(ctx, obj, old)\n\n\t// Use the existing UID if none is provided\n\tif len(objectMeta.GetUID()) == 0 {\n\t\tobjectMeta.SetUID(oldMeta.GetUID())\n\t}\n\t// ignore changes to timestamp\n\tif oldCreationTime := oldMeta.GetCreationTimestamp(); !oldCreationTime.IsZero() {\n\t\tobjectMeta.SetCreationTimestamp(oldMeta.GetCreationTimestamp())\n\t}\n\t// an update can never remove/change a deletion timestamp\n\tif !oldMeta.GetDeletionTimestamp().IsZero() {\n\t\tobjectMeta.SetDeletionTimestamp(oldMeta.GetDeletionTimestamp())\n\t}\n\t// an update can never remove/change grace period seconds\n\tif oldMeta.GetDeletionGracePeriodSeconds() != nil \u0026\u0026 objectMeta.GetDeletionGracePeriodSeconds() == nil {\n\t\tobjectMeta.SetDeletionGracePeriodSeconds(oldMeta.GetDeletionGracePeriodSeconds())\n\t}\n\n\t// Ensure some common fields, like UID, are validated for all resources.\n\terrs, err := validateCommonFields(obj, old, strategy)\n\tif err != nil {\n\t\treturn errors.NewInternalError(err)\n\t}\n\n\terrs = append(errs, strategy.ValidateUpdate(ctx, obj, old)...)\n\tif len(errs) \u003e 0 {\n\t\treturn errors.NewInvalid(kind.GroupKind(), objectMeta.GetName(), errs)\n\t}\n\n\tfor _, w := range strategy.WarningsOnUpdate(ctx, obj, old) {\n\t\twarning.AddWarning(ctx, \"\", w)\n\t}\n\n\tstrategy.Canonicalize(obj)\n\n\treturn nil\n}","line":{"from":103,"to":166}} {"id":100017816,"name":"DefaultUpdatedObjectInfo","signature":"func DefaultUpdatedObjectInfo(obj runtime.Object, transformers ...TransformFunc) UpdatedObjectInfo","file":"staging/src/k8s.io/apiserver/pkg/registry/rest/update.go","code":"// DefaultUpdatedObjectInfo returns an UpdatedObjectInfo impl based on the specified object.\nfunc DefaultUpdatedObjectInfo(obj runtime.Object, transformers ...TransformFunc) UpdatedObjectInfo {\n\treturn \u0026defaultUpdatedObjectInfo{obj, transformers}\n}","line":{"from":181,"to":184}} {"id":100017817,"name":"Preconditions","signature":"func (i *defaultUpdatedObjectInfo) Preconditions() *metav1.Preconditions","file":"staging/src/k8s.io/apiserver/pkg/registry/rest/update.go","code":"// Preconditions satisfies the UpdatedObjectInfo interface.\nfunc (i *defaultUpdatedObjectInfo) Preconditions() *metav1.Preconditions {\n\t// Attempt to get the UID out of the object\n\taccessor, err := meta.Accessor(i.obj)\n\tif err != nil {\n\t\t// If no UID can be read, no preconditions are possible\n\t\treturn nil\n\t}\n\n\t// If empty, no preconditions needed\n\tuid := accessor.GetUID()\n\tif len(uid) == 0 {\n\t\treturn nil\n\t}\n\n\treturn \u0026metav1.Preconditions{UID: \u0026uid}\n}","line":{"from":186,"to":202}} {"id":100017818,"name":"UpdatedObject","signature":"func (i *defaultUpdatedObjectInfo) UpdatedObject(ctx context.Context, oldObj runtime.Object) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/registry/rest/update.go","code":"// UpdatedObject satisfies the UpdatedObjectInfo interface.\n// It returns a copy of the held obj, passed through any configured transformers.\nfunc (i *defaultUpdatedObjectInfo) UpdatedObject(ctx context.Context, oldObj runtime.Object) (runtime.Object, error) {\n\tvar err error\n\t// Start with the configured object\n\tnewObj := i.obj\n\n\t// If the original is non-nil (might be nil if the first transformer builds the object from the oldObj), make a copy,\n\t// so we don't return the original. BeforeUpdate can mutate the returned object, doing things like clearing ResourceVersion.\n\t// If we're re-called, we need to be able to return the pristine version.\n\tif newObj != nil {\n\t\tnewObj = newObj.DeepCopyObject()\n\t}\n\n\t// Allow any configured transformers to update the new object\n\tfor _, transformer := range i.transformers {\n\t\tnewObj, err = transformer(ctx, newObj, oldObj)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn newObj, nil\n}","line":{"from":204,"to":227}} {"id":100017819,"name":"WrapUpdatedObjectInfo","signature":"func WrapUpdatedObjectInfo(objInfo UpdatedObjectInfo, transformers ...TransformFunc) UpdatedObjectInfo","file":"staging/src/k8s.io/apiserver/pkg/registry/rest/update.go","code":"// WrapUpdatedObjectInfo returns an UpdatedObjectInfo impl that delegates to\n// the specified objInfo, then calls the passed transformers\nfunc WrapUpdatedObjectInfo(objInfo UpdatedObjectInfo, transformers ...TransformFunc) UpdatedObjectInfo {\n\treturn \u0026wrappedUpdatedObjectInfo{objInfo, transformers}\n}","line":{"from":240,"to":244}} {"id":100017820,"name":"Preconditions","signature":"func (i *wrappedUpdatedObjectInfo) Preconditions() *metav1.Preconditions","file":"staging/src/k8s.io/apiserver/pkg/registry/rest/update.go","code":"// Preconditions satisfies the UpdatedObjectInfo interface.\nfunc (i *wrappedUpdatedObjectInfo) Preconditions() *metav1.Preconditions {\n\treturn i.objInfo.Preconditions()\n}","line":{"from":246,"to":249}} {"id":100017821,"name":"UpdatedObject","signature":"func (i *wrappedUpdatedObjectInfo) UpdatedObject(ctx context.Context, oldObj runtime.Object) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/registry/rest/update.go","code":"// UpdatedObject satisfies the UpdatedObjectInfo interface.\n// It delegates to the wrapped objInfo and passes the result through any configured transformers.\nfunc (i *wrappedUpdatedObjectInfo) UpdatedObject(ctx context.Context, oldObj runtime.Object) (runtime.Object, error) {\n\tnewObj, err := i.objInfo.UpdatedObject(ctx, oldObj)\n\tif err != nil {\n\t\treturn newObj, err\n\t}\n\n\t// Allow any configured transformers to update the new object or error\n\tfor _, transformer := range i.transformers {\n\t\tnewObj, err = transformer(ctx, newObj, oldObj)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn newObj, nil\n}","line":{"from":251,"to":268}} {"id":100017822,"name":"AdmissionToValidateObjectUpdateFunc","signature":"func AdmissionToValidateObjectUpdateFunc(admit admission.Interface, staticAttributes admission.Attributes, o admission.ObjectInterfaces) ValidateObjectUpdateFunc","file":"staging/src/k8s.io/apiserver/pkg/registry/rest/update.go","code":"// AdmissionToValidateObjectUpdateFunc converts validating admission to a rest validate object update func\nfunc AdmissionToValidateObjectUpdateFunc(admit admission.Interface, staticAttributes admission.Attributes, o admission.ObjectInterfaces) ValidateObjectUpdateFunc {\n\tvalidatingAdmission, ok := admit.(admission.ValidationInterface)\n\tif !ok {\n\t\treturn func(ctx context.Context, obj, old runtime.Object) error { return nil }\n\t}\n\treturn func(ctx context.Context, obj, old runtime.Object) error {\n\t\tfinalAttributes := admission.NewAttributesRecord(\n\t\t\tobj,\n\t\t\told,\n\t\t\tstaticAttributes.GetKind(),\n\t\t\tstaticAttributes.GetNamespace(),\n\t\t\tstaticAttributes.GetName(),\n\t\t\tstaticAttributes.GetResource(),\n\t\t\tstaticAttributes.GetSubresource(),\n\t\t\tstaticAttributes.GetOperation(),\n\t\t\tstaticAttributes.GetOperationOptions(),\n\t\t\tstaticAttributes.IsDryRun(),\n\t\t\tstaticAttributes.GetUserInfo(),\n\t\t)\n\t\tif !validatingAdmission.Handles(finalAttributes.GetOperation()) {\n\t\t\treturn nil\n\t\t}\n\t\treturn validatingAdmission.Validate(ctx, finalAttributes, o)\n\t}\n}","line":{"from":270,"to":295}} {"id":100017823,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/server/config.go","code":"func init() {\n\tutilruntime.Must(features.AddFeatureGates(utilfeature.DefaultMutableFeatureGate))\n}","line":{"from":358,"to":360}} {"id":100017824,"name":"NewConfig","signature":"func NewConfig(codecs serializer.CodecFactory) *Config","file":"staging/src/k8s.io/apiserver/pkg/server/config.go","code":"// NewConfig returns a Config struct with the default values\nfunc NewConfig(codecs serializer.CodecFactory) *Config {\n\tdefaultHealthChecks := []healthz.HealthChecker{healthz.PingHealthz, healthz.LogHealthz}\n\tvar id string\n\tif utilfeature.DefaultFeatureGate.Enabled(genericfeatures.APIServerIdentity) {\n\t\thostname, err := os.Hostname()\n\t\tif err != nil {\n\t\t\tklog.Fatalf(\"error getting hostname for apiserver identity: %v\", err)\n\t\t}\n\n\t\t// Since the hash needs to be unique across each kube-apiserver and aggregated apiservers,\n\t\t// the hash used for the identity should include both the hostname and the identity value.\n\t\t// TODO: receive the identity value as a parameter once the apiserver identity lease controller\n\t\t// post start hook is moved to generic apiserver.\n\t\tb := cryptobyte.NewBuilder(nil)\n\t\tb.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {\n\t\t\tb.AddBytes([]byte(hostname))\n\t\t})\n\t\tb.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {\n\t\t\tb.AddBytes([]byte(\"kube-apiserver\"))\n\t\t})\n\t\thashData, err := b.Bytes()\n\t\tif err != nil {\n\t\t\tklog.Fatalf(\"error building hash data for apiserver identity: %v\", err)\n\t\t}\n\n\t\thash := sha256.Sum256(hashData)\n\t\tid = \"apiserver-\" + strings.ToLower(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(hash[:16]))\n\t}\n\tlifecycleSignals := newLifecycleSignals()\n\n\treturn \u0026Config{\n\t\tSerializer: codecs,\n\t\tBuildHandlerChainFunc: DefaultBuildHandlerChain,\n\t\tNonLongRunningRequestWaitGroup: new(utilwaitgroup.SafeWaitGroup),\n\t\tWatchRequestWaitGroup: \u0026utilwaitgroup.RateLimitedSafeWaitGroup{},\n\t\tLegacyAPIGroupPrefixes: sets.NewString(DefaultLegacyAPIPrefix),\n\t\tDisabledPostStartHooks: sets.NewString(),\n\t\tPostStartHooks: map[string]PostStartHookConfigEntry{},\n\t\tHealthzChecks: append([]healthz.HealthChecker{}, defaultHealthChecks...),\n\t\tReadyzChecks: append([]healthz.HealthChecker{}, defaultHealthChecks...),\n\t\tLivezChecks: append([]healthz.HealthChecker{}, defaultHealthChecks...),\n\t\tEnableIndex: true,\n\t\tEnableDiscovery: true,\n\t\tEnableProfiling: true,\n\t\tDebugSocketPath: \"\",\n\t\tEnableMetrics: true,\n\t\tMaxRequestsInFlight: 400,\n\t\tMaxMutatingRequestsInFlight: 200,\n\t\tRequestTimeout: time.Duration(60) * time.Second,\n\t\tMinRequestTimeout: 1800,\n\t\tLivezGracePeriod: time.Duration(0),\n\t\tShutdownDelayDuration: time.Duration(0),\n\t\t// 1.5MB is the default client request size in bytes\n\t\t// the etcd server should accept. See\n\t\t// https://github.com/etcd-io/etcd/blob/release-3.4/embed/config.go#L56.\n\t\t// A request body might be encoded in json, and is converted to\n\t\t// proto when persisted in etcd, so we allow 2x as the largest size\n\t\t// increase the \"copy\" operations in a json patch may cause.\n\t\tJSONPatchMaxCopyBytes: int64(3 * 1024 * 1024),\n\t\t// 1.5MB is the recommended client request size in byte\n\t\t// the etcd server should accept. See\n\t\t// https://github.com/etcd-io/etcd/blob/release-3.4/embed/config.go#L56.\n\t\t// A request body might be encoded in json, and is converted to\n\t\t// proto when persisted in etcd, so we allow 2x as the largest request\n\t\t// body size to be accepted and decoded in a write request.\n\t\t// If this constant is changed, DefaultMaxRequestSizeBytes in k8s.io/apiserver/pkg/cel/limits.go\n\t\t// should be changed to reflect the new value, if the two haven't\n\t\t// been wired together already somehow.\n\t\tMaxRequestBodyBytes: int64(3 * 1024 * 1024),\n\n\t\t// Default to treating watch as a long-running operation\n\t\t// Generic API servers have no inherent long-running subresources\n\t\tLongRunningFunc: genericfilters.BasicLongRunningRequestCheck(sets.NewString(\"watch\"), sets.NewString()),\n\t\tlifecycleSignals: lifecycleSignals,\n\t\tStorageObjectCountTracker: flowcontrolrequest.NewStorageObjectCountTracker(),\n\t\tShutdownWatchTerminationGracePeriod: time.Duration(0),\n\n\t\tAPIServerID: id,\n\t\tStorageVersionManager: storageversion.NewDefaultManager(),\n\t\tTracerProvider: tracing.NewNoopTracerProvider(),\n\t}\n}","line":{"from":362,"to":444}} {"id":100017825,"name":"NewRecommendedConfig","signature":"func NewRecommendedConfig(codecs serializer.CodecFactory) *RecommendedConfig","file":"staging/src/k8s.io/apiserver/pkg/server/config.go","code":"// NewRecommendedConfig returns a RecommendedConfig struct with the default values\nfunc NewRecommendedConfig(codecs serializer.CodecFactory) *RecommendedConfig {\n\treturn \u0026RecommendedConfig{\n\t\tConfig: *NewConfig(codecs),\n\t}\n}","line":{"from":446,"to":451}} {"id":100017826,"name":"DefaultOpenAPIConfig","signature":"func DefaultOpenAPIConfig(getDefinitions openapicommon.GetOpenAPIDefinitions, defNamer *apiopenapi.DefinitionNamer) *openapicommon.Config","file":"staging/src/k8s.io/apiserver/pkg/server/config.go","code":"// DefaultOpenAPIConfig provides the default OpenAPIConfig used to build the OpenAPI V2 spec\nfunc DefaultOpenAPIConfig(getDefinitions openapicommon.GetOpenAPIDefinitions, defNamer *apiopenapi.DefinitionNamer) *openapicommon.Config {\n\treturn \u0026openapicommon.Config{\n\t\tProtocolList: []string{\"https\"},\n\t\tIgnorePrefixes: []string{},\n\t\tInfo: \u0026spec.Info{\n\t\t\tInfoProps: spec.InfoProps{\n\t\t\t\tTitle: \"Generic API Server\",\n\t\t\t},\n\t\t},\n\t\tDefaultResponse: \u0026spec.Response{\n\t\t\tResponseProps: spec.ResponseProps{\n\t\t\t\tDescription: \"Default Response.\",\n\t\t\t},\n\t\t},\n\t\tGetOperationIDAndTags: apiopenapi.GetOperationIDAndTags,\n\t\tGetDefinitionName: defNamer.GetDefinitionName,\n\t\tGetDefinitions: getDefinitions,\n\t}\n}","line":{"from":453,"to":472}} {"id":100017827,"name":"DefaultOpenAPIV3Config","signature":"func DefaultOpenAPIV3Config(getDefinitions openapicommon.GetOpenAPIDefinitions, defNamer *apiopenapi.DefinitionNamer) *openapicommon.Config","file":"staging/src/k8s.io/apiserver/pkg/server/config.go","code":"// DefaultOpenAPIV3Config provides the default OpenAPIV3Config used to build the OpenAPI V3 spec\nfunc DefaultOpenAPIV3Config(getDefinitions openapicommon.GetOpenAPIDefinitions, defNamer *apiopenapi.DefinitionNamer) *openapicommon.Config {\n\tdefaultConfig := DefaultOpenAPIConfig(getDefinitions, defNamer)\n\tdefaultConfig.Definitions = getDefinitions(func(name string) spec.Ref {\n\t\tdefName, _ := defaultConfig.GetDefinitionName(name)\n\t\treturn spec.MustCreateRef(\"#/components/schemas/\" + openapicommon.EscapeJsonPointer(defName))\n\t})\n\n\treturn defaultConfig\n}","line":{"from":474,"to":483}} {"id":100017828,"name":"ApplyClientCert","signature":"func (c *AuthenticationInfo) ApplyClientCert(clientCA dynamiccertificates.CAContentProvider, servingInfo *SecureServingInfo) error","file":"staging/src/k8s.io/apiserver/pkg/server/config.go","code":"func (c *AuthenticationInfo) ApplyClientCert(clientCA dynamiccertificates.CAContentProvider, servingInfo *SecureServingInfo) error {\n\tif servingInfo == nil {\n\t\treturn nil\n\t}\n\tif clientCA == nil {\n\t\treturn nil\n\t}\n\tif servingInfo.ClientCA == nil {\n\t\tservingInfo.ClientCA = clientCA\n\t\treturn nil\n\t}\n\n\tservingInfo.ClientCA = dynamiccertificates.NewUnionCAContentProvider(servingInfo.ClientCA, clientCA)\n\treturn nil\n}","line":{"from":485,"to":499}} {"id":100017829,"name":"AddHealthChecks","signature":"func (c *Config) AddHealthChecks(healthChecks ...healthz.HealthChecker)","file":"staging/src/k8s.io/apiserver/pkg/server/config.go","code":"// AddHealthChecks adds a health check to our config to be exposed by the health endpoints\n// of our configured apiserver. We should prefer this to adding healthChecks directly to\n// the config unless we explicitly want to add a healthcheck only to a specific health endpoint.\nfunc (c *Config) AddHealthChecks(healthChecks ...healthz.HealthChecker) {\n\tc.HealthzChecks = append(c.HealthzChecks, healthChecks...)\n\tc.LivezChecks = append(c.LivezChecks, healthChecks...)\n\tc.ReadyzChecks = append(c.ReadyzChecks, healthChecks...)\n}","line":{"from":517,"to":524}} {"id":100017830,"name":"AddReadyzChecks","signature":"func (c *Config) AddReadyzChecks(healthChecks ...healthz.HealthChecker)","file":"staging/src/k8s.io/apiserver/pkg/server/config.go","code":"// AddReadyzChecks adds a health check to our config to be exposed by the readyz endpoint\n// of our configured apiserver.\nfunc (c *Config) AddReadyzChecks(healthChecks ...healthz.HealthChecker) {\n\tc.ReadyzChecks = append(c.ReadyzChecks, healthChecks...)\n}","line":{"from":526,"to":530}} {"id":100017831,"name":"AddPostStartHook","signature":"func (c *Config) AddPostStartHook(name string, hook PostStartHookFunc) error","file":"staging/src/k8s.io/apiserver/pkg/server/config.go","code":"// AddPostStartHook allows you to add a PostStartHook that will later be added to the server itself in a New call.\n// Name conflicts will cause an error.\nfunc (c *Config) AddPostStartHook(name string, hook PostStartHookFunc) error {\n\tif len(name) == 0 {\n\t\treturn fmt.Errorf(\"missing name\")\n\t}\n\tif hook == nil {\n\t\treturn fmt.Errorf(\"hook func may not be nil: %q\", name)\n\t}\n\tif c.DisabledPostStartHooks.Has(name) {\n\t\tklog.V(1).Infof(\"skipping %q because it was explicitly disabled\", name)\n\t\treturn nil\n\t}\n\n\tif postStartHook, exists := c.PostStartHooks[name]; exists {\n\t\t// this is programmer error, but it can be hard to debug\n\t\treturn fmt.Errorf(\"unable to add %q because it was already registered by: %s\", name, postStartHook.originatingStack)\n\t}\n\tc.PostStartHooks[name] = PostStartHookConfigEntry{hook: hook, originatingStack: string(debug.Stack())}\n\n\treturn nil\n}","line":{"from":532,"to":553}} {"id":100017832,"name":"AddPostStartHookOrDie","signature":"func (c *Config) AddPostStartHookOrDie(name string, hook PostStartHookFunc)","file":"staging/src/k8s.io/apiserver/pkg/server/config.go","code":"// AddPostStartHookOrDie allows you to add a PostStartHook, but dies on failure.\nfunc (c *Config) AddPostStartHookOrDie(name string, hook PostStartHookFunc) {\n\tif err := c.AddPostStartHook(name, hook); err != nil {\n\t\tklog.Fatalf(\"Error registering PostStartHook %q: %v\", name, err)\n\t}\n}","line":{"from":555,"to":560}} {"id":100017833,"name":"completeOpenAPI","signature":"func completeOpenAPI(config *openapicommon.Config, version *version.Info)","file":"staging/src/k8s.io/apiserver/pkg/server/config.go","code":"func completeOpenAPI(config *openapicommon.Config, version *version.Info) {\n\tif config == nil {\n\t\treturn\n\t}\n\tif config.SecurityDefinitions != nil {\n\t\t// Setup OpenAPI security: all APIs will have the same authentication for now.\n\t\tconfig.DefaultSecurity = []map[string][]string{}\n\t\tkeys := []string{}\n\t\tfor k := range *config.SecurityDefinitions {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t\tsort.Strings(keys)\n\t\tfor _, k := range keys {\n\t\t\tconfig.DefaultSecurity = append(config.DefaultSecurity, map[string][]string{k: {}})\n\t\t}\n\t\tif config.CommonResponses == nil {\n\t\t\tconfig.CommonResponses = map[int]spec.Response{}\n\t\t}\n\t\tif _, exists := config.CommonResponses[http.StatusUnauthorized]; !exists {\n\t\t\tconfig.CommonResponses[http.StatusUnauthorized] = spec.Response{\n\t\t\t\tResponseProps: spec.ResponseProps{\n\t\t\t\t\tDescription: \"Unauthorized\",\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t}\n\t// make sure we populate info, and info.version, if not manually set\n\tif config.Info == nil {\n\t\tconfig.Info = \u0026spec.Info{}\n\t}\n\tif config.Info.Version == \"\" {\n\t\tif version != nil {\n\t\t\tconfig.Info.Version = strings.Split(version.String(), \"-\")[0]\n\t\t} else {\n\t\t\tconfig.Info.Version = \"unversioned\"\n\t\t}\n\t}\n}","line":{"from":562,"to":599}} {"id":100017834,"name":"DrainedNotify","signature":"func (c *Config) DrainedNotify() \u003c-chan struct{}","file":"staging/src/k8s.io/apiserver/pkg/server/config.go","code":"// DrainedNotify returns a lifecycle signal of genericapiserver already drained while shutting down.\nfunc (c *Config) DrainedNotify() \u003c-chan struct{} {\n\treturn c.lifecycleSignals.InFlightRequestsDrained.Signaled()\n}","line":{"from":601,"to":604}} {"id":100017835,"name":"Complete","signature":"func (c *Config) Complete(informers informers.SharedInformerFactory) CompletedConfig","file":"staging/src/k8s.io/apiserver/pkg/server/config.go","code":"// Complete fills in any fields not set that are required to have valid data and can be derived\n// from other fields. If you're going to `ApplyOptions`, do that first. It's mutating the receiver.\nfunc (c *Config) Complete(informers informers.SharedInformerFactory) CompletedConfig {\n\tif len(c.ExternalAddress) == 0 \u0026\u0026 c.PublicAddress != nil {\n\t\tc.ExternalAddress = c.PublicAddress.String()\n\t}\n\n\t// if there is no port, and we listen on one securely, use that one\n\tif _, _, err := net.SplitHostPort(c.ExternalAddress); err != nil {\n\t\tif c.SecureServing == nil {\n\t\t\tklog.Fatalf(\"cannot derive external address port without listening on a secure port.\")\n\t\t}\n\t\t_, port, err := c.SecureServing.HostPort()\n\t\tif err != nil {\n\t\t\tklog.Fatalf(\"cannot derive external address from the secure port: %v\", err)\n\t\t}\n\t\tc.ExternalAddress = net.JoinHostPort(c.ExternalAddress, strconv.Itoa(port))\n\t}\n\n\tcompleteOpenAPI(c.OpenAPIConfig, c.Version)\n\tcompleteOpenAPI(c.OpenAPIV3Config, c.Version)\n\n\tif c.DiscoveryAddresses == nil {\n\t\tc.DiscoveryAddresses = discovery.DefaultAddresses{DefaultAddress: c.ExternalAddress}\n\t}\n\n\tAuthorizeClientBearerToken(c.LoopbackClientConfig, \u0026c.Authentication, \u0026c.Authorization)\n\n\tif c.RequestInfoResolver == nil {\n\t\tc.RequestInfoResolver = NewRequestInfoResolver(c)\n\t}\n\n\tif c.EquivalentResourceRegistry == nil {\n\t\tif c.RESTOptionsGetter == nil {\n\t\t\tc.EquivalentResourceRegistry = runtime.NewEquivalentResourceRegistry()\n\t\t} else {\n\t\t\tc.EquivalentResourceRegistry = runtime.NewEquivalentResourceRegistryWithIdentity(func(groupResource schema.GroupResource) string {\n\t\t\t\t// use the storage prefix as the key if possible\n\t\t\t\tif opts, err := c.RESTOptionsGetter.GetRESTOptions(groupResource); err == nil {\n\t\t\t\t\treturn opts.ResourcePrefix\n\t\t\t\t}\n\t\t\t\t// otherwise return \"\" to use the default key (parent GV name)\n\t\t\t\treturn \"\"\n\t\t\t})\n\t\t}\n\t}\n\n\treturn CompletedConfig{\u0026completedConfig{c, informers}}\n}","line":{"from":606,"to":654}} {"id":100017836,"name":"Complete","signature":"func (c *RecommendedConfig) Complete() CompletedConfig","file":"staging/src/k8s.io/apiserver/pkg/server/config.go","code":"// Complete fills in any fields not set that are required to have valid data and can be derived\n// from other fields. If you're going to `ApplyOptions`, do that first. It's mutating the receiver.\nfunc (c *RecommendedConfig) Complete() CompletedConfig {\n\treturn c.Config.Complete(c.SharedInformerFactory)\n}","line":{"from":656,"to":660}} {"id":100017837,"name":"New","signature":"func (c completedConfig) New(name string, delegationTarget DelegationTarget) (*GenericAPIServer, error)","file":"staging/src/k8s.io/apiserver/pkg/server/config.go","code":"// New creates a new server which logically combines the handling chain with the passed server.\n// name is used to differentiate for logging. The handler chain in particular can be difficult as it starts delegating.\n// delegationTarget may not be nil.\nfunc (c completedConfig) New(name string, delegationTarget DelegationTarget) (*GenericAPIServer, error) {\n\tif c.Serializer == nil {\n\t\treturn nil, fmt.Errorf(\"Genericapiserver.New() called with config.Serializer == nil\")\n\t}\n\tif c.LoopbackClientConfig == nil {\n\t\treturn nil, fmt.Errorf(\"Genericapiserver.New() called with config.LoopbackClientConfig == nil\")\n\t}\n\tif c.EquivalentResourceRegistry == nil {\n\t\treturn nil, fmt.Errorf(\"Genericapiserver.New() called with config.EquivalentResourceRegistry == nil\")\n\t}\n\n\thandlerChainBuilder := func(handler http.Handler) http.Handler {\n\t\treturn c.BuildHandlerChainFunc(handler, c.Config)\n\t}\n\n\tvar debugSocket *routes.DebugSocket\n\tif c.DebugSocketPath != \"\" {\n\t\tdebugSocket = routes.NewDebugSocket(c.DebugSocketPath)\n\t}\n\n\tapiServerHandler := NewAPIServerHandler(name, c.Serializer, handlerChainBuilder, delegationTarget.UnprotectedHandler())\n\n\ts := \u0026GenericAPIServer{\n\t\tdiscoveryAddresses: c.DiscoveryAddresses,\n\t\tLoopbackClientConfig: c.LoopbackClientConfig,\n\t\tlegacyAPIGroupPrefixes: c.LegacyAPIGroupPrefixes,\n\t\tadmissionControl: c.AdmissionControl,\n\t\tSerializer: c.Serializer,\n\t\tAuditBackend: c.AuditBackend,\n\t\tAuthorizer: c.Authorization.Authorizer,\n\t\tdelegationTarget: delegationTarget,\n\t\tEquivalentResourceRegistry: c.EquivalentResourceRegistry,\n\t\tNonLongRunningRequestWaitGroup: c.NonLongRunningRequestWaitGroup,\n\t\tWatchRequestWaitGroup: c.WatchRequestWaitGroup,\n\t\tHandler: apiServerHandler,\n\t\tUnprotectedDebugSocket: debugSocket,\n\n\t\tlistedPathProvider: apiServerHandler,\n\n\t\tminRequestTimeout: time.Duration(c.MinRequestTimeout) * time.Second,\n\t\tShutdownTimeout: c.RequestTimeout,\n\t\tShutdownDelayDuration: c.ShutdownDelayDuration,\n\t\tShutdownWatchTerminationGracePeriod: c.ShutdownWatchTerminationGracePeriod,\n\t\tSecureServingInfo: c.SecureServing,\n\t\tExternalAddress: c.ExternalAddress,\n\n\t\topenAPIConfig: c.OpenAPIConfig,\n\t\topenAPIV3Config: c.OpenAPIV3Config,\n\t\tskipOpenAPIInstallation: c.SkipOpenAPIInstallation,\n\n\t\tpostStartHooks: map[string]postStartHookEntry{},\n\t\tpreShutdownHooks: map[string]preShutdownHookEntry{},\n\t\tdisabledPostStartHooks: c.DisabledPostStartHooks,\n\n\t\thealthzChecks: c.HealthzChecks,\n\t\tlivezChecks: c.LivezChecks,\n\t\treadyzChecks: c.ReadyzChecks,\n\t\tlivezGracePeriod: c.LivezGracePeriod,\n\n\t\tDiscoveryGroupManager: discovery.NewRootAPIsHandler(c.DiscoveryAddresses, c.Serializer),\n\n\t\tmaxRequestBodyBytes: c.MaxRequestBodyBytes,\n\t\tlivezClock: clock.RealClock{},\n\n\t\tlifecycleSignals: c.lifecycleSignals,\n\t\tShutdownSendRetryAfter: c.ShutdownSendRetryAfter,\n\n\t\tAPIServerID: c.APIServerID,\n\t\tStorageVersionManager: c.StorageVersionManager,\n\n\t\tVersion: c.Version,\n\n\t\tmuxAndDiscoveryCompleteSignals: map[string]\u003c-chan struct{}{},\n\t}\n\n\tif utilfeature.DefaultFeatureGate.Enabled(genericfeatures.AggregatedDiscoveryEndpoint) {\n\t\tmanager := c.AggregatedDiscoveryGroupManager\n\t\tif manager == nil {\n\t\t\tmanager = discoveryendpoint.NewResourceManager(\"apis\")\n\t\t}\n\t\ts.AggregatedDiscoveryGroupManager = manager\n\t\ts.AggregatedLegacyDiscoveryGroupManager = discoveryendpoint.NewResourceManager(\"api\")\n\t}\n\tfor {\n\t\tif c.JSONPatchMaxCopyBytes \u003c= 0 {\n\t\t\tbreak\n\t\t}\n\t\texisting := atomic.LoadInt64(\u0026jsonpatch.AccumulatedCopySizeLimit)\n\t\tif existing \u003e 0 \u0026\u0026 existing \u003c c.JSONPatchMaxCopyBytes {\n\t\t\tbreak\n\t\t}\n\t\tif atomic.CompareAndSwapInt64(\u0026jsonpatch.AccumulatedCopySizeLimit, existing, c.JSONPatchMaxCopyBytes) {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// first add poststarthooks from delegated targets\n\tfor k, v := range delegationTarget.PostStartHooks() {\n\t\ts.postStartHooks[k] = v\n\t}\n\n\tfor k, v := range delegationTarget.PreShutdownHooks() {\n\t\ts.preShutdownHooks[k] = v\n\t}\n\n\t// add poststarthooks that were preconfigured. Using the add method will give us an error if the same name has already been registered.\n\tfor name, preconfiguredPostStartHook := range c.PostStartHooks {\n\t\tif err := s.AddPostStartHook(name, preconfiguredPostStartHook.hook); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// register mux signals from the delegated server\n\tfor k, v := range delegationTarget.MuxAndDiscoveryCompleteSignals() {\n\t\tif err := s.RegisterMuxAndDiscoveryCompleteSignal(k, v); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tgenericApiServerHookName := \"generic-apiserver-start-informers\"\n\tif c.SharedInformerFactory != nil {\n\t\tif !s.isPostStartHookRegistered(genericApiServerHookName) {\n\t\t\terr := s.AddPostStartHook(genericApiServerHookName, func(context PostStartHookContext) error {\n\t\t\t\tc.SharedInformerFactory.Start(context.StopCh)\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\t// TODO: Once we get rid of /healthz consider changing this to post-start-hook.\n\t\terr := s.AddReadyzChecks(healthz.NewInformerSyncHealthz(c.SharedInformerFactory))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tconst priorityAndFairnessConfigConsumerHookName = \"priority-and-fairness-config-consumer\"\n\tif s.isPostStartHookRegistered(priorityAndFairnessConfigConsumerHookName) {\n\t} else if c.FlowControl != nil {\n\t\terr := s.AddPostStartHook(priorityAndFairnessConfigConsumerHookName, func(context PostStartHookContext) error {\n\t\t\tgo c.FlowControl.Run(context.StopCh)\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// TODO(yue9944882): plumb pre-shutdown-hook for request-management system?\n\t} else {\n\t\tklog.V(3).Infof(\"Not requested to run hook %s\", priorityAndFairnessConfigConsumerHookName)\n\t}\n\n\t// Add PostStartHooks for maintaining the watermarks for the Priority-and-Fairness and the Max-in-Flight filters.\n\tif c.FlowControl != nil {\n\t\tconst priorityAndFairnessFilterHookName = \"priority-and-fairness-filter\"\n\t\tif !s.isPostStartHookRegistered(priorityAndFairnessFilterHookName) {\n\t\t\terr := s.AddPostStartHook(priorityAndFairnessFilterHookName, func(context PostStartHookContext) error {\n\t\t\t\tgenericfilters.StartPriorityAndFairnessWatermarkMaintenance(context.StopCh)\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t} else {\n\t\tconst maxInFlightFilterHookName = \"max-in-flight-filter\"\n\t\tif !s.isPostStartHookRegistered(maxInFlightFilterHookName) {\n\t\t\terr := s.AddPostStartHook(maxInFlightFilterHookName, func(context PostStartHookContext) error {\n\t\t\t\tgenericfilters.StartMaxInFlightWatermarkMaintenance(context.StopCh)\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\t// Add PostStartHook for maintenaing the object count tracker.\n\tif c.StorageObjectCountTracker != nil {\n\t\tconst storageObjectCountTrackerHookName = \"storage-object-count-tracker-hook\"\n\t\tif !s.isPostStartHookRegistered(storageObjectCountTrackerHookName) {\n\t\t\tif err := s.AddPostStartHook(storageObjectCountTrackerHookName, func(context PostStartHookContext) error {\n\t\t\t\tgo c.StorageObjectCountTracker.RunUntil(context.StopCh)\n\t\t\t\treturn nil\n\t\t\t}); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, delegateCheck := range delegationTarget.HealthzChecks() {\n\t\tskip := false\n\t\tfor _, existingCheck := range c.HealthzChecks {\n\t\t\tif existingCheck.Name() == delegateCheck.Name() {\n\t\t\t\tskip = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif skip {\n\t\t\tcontinue\n\t\t}\n\t\ts.AddHealthChecks(delegateCheck)\n\t}\n\ts.RegisterDestroyFunc(func() {\n\t\tif err := c.Config.TracerProvider.Shutdown(context.Background()); err != nil {\n\t\t\tklog.Errorf(\"failed to shut down tracer provider: %v\", err)\n\t\t}\n\t})\n\n\ts.listedPathProvider = routes.ListedPathProviders{s.listedPathProvider, delegationTarget}\n\n\tinstallAPI(s, c.Config)\n\n\t// use the UnprotectedHandler from the delegation target to ensure that we don't attempt to double authenticator, authorize,\n\t// or some other part of the filter chain in delegation cases.\n\tif delegationTarget.UnprotectedHandler() == nil \u0026\u0026 c.EnableIndex {\n\t\ts.Handler.NonGoRestfulMux.NotFoundHandler(routes.IndexLister{\n\t\t\tStatusCode: http.StatusNotFound,\n\t\t\tPathProvider: s.listedPathProvider,\n\t\t})\n\t}\n\n\treturn s, nil\n}","line":{"from":662,"to":888}} {"id":100017838,"name":"BuildHandlerChainWithStorageVersionPrecondition","signature":"func BuildHandlerChainWithStorageVersionPrecondition(apiHandler http.Handler, c *Config) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/server/config.go","code":"func BuildHandlerChainWithStorageVersionPrecondition(apiHandler http.Handler, c *Config) http.Handler {\n\t// WithStorageVersionPrecondition needs the WithRequestInfo to run first\n\thandler := genericapifilters.WithStorageVersionPrecondition(apiHandler, c.StorageVersionManager, c.Serializer)\n\treturn DefaultBuildHandlerChain(handler, c)\n}","line":{"from":890,"to":894}} {"id":100017839,"name":"DefaultBuildHandlerChain","signature":"func DefaultBuildHandlerChain(apiHandler http.Handler, c *Config) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/server/config.go","code":"func DefaultBuildHandlerChain(apiHandler http.Handler, c *Config) http.Handler {\n\thandler := filterlatency.TrackCompleted(apiHandler)\n\thandler = genericapifilters.WithAuthorization(handler, c.Authorization.Authorizer, c.Serializer)\n\thandler = filterlatency.TrackStarted(handler, c.TracerProvider, \"authorization\")\n\n\tif c.FlowControl != nil {\n\t\tworkEstimatorCfg := flowcontrolrequest.DefaultWorkEstimatorConfig()\n\t\trequestWorkEstimator := flowcontrolrequest.NewWorkEstimator(\n\t\t\tc.StorageObjectCountTracker.Get, c.FlowControl.GetInterestedWatchCount, workEstimatorCfg)\n\t\thandler = filterlatency.TrackCompleted(handler)\n\t\thandler = genericfilters.WithPriorityAndFairness(handler, c.LongRunningFunc, c.FlowControl, requestWorkEstimator)\n\t\thandler = filterlatency.TrackStarted(handler, c.TracerProvider, \"priorityandfairness\")\n\t} else {\n\t\thandler = genericfilters.WithMaxInFlightLimit(handler, c.MaxRequestsInFlight, c.MaxMutatingRequestsInFlight, c.LongRunningFunc)\n\t}\n\n\thandler = filterlatency.TrackCompleted(handler)\n\thandler = genericapifilters.WithImpersonation(handler, c.Authorization.Authorizer, c.Serializer)\n\thandler = filterlatency.TrackStarted(handler, c.TracerProvider, \"impersonation\")\n\n\thandler = filterlatency.TrackCompleted(handler)\n\thandler = genericapifilters.WithAudit(handler, c.AuditBackend, c.AuditPolicyRuleEvaluator, c.LongRunningFunc)\n\thandler = filterlatency.TrackStarted(handler, c.TracerProvider, \"audit\")\n\n\tfailedHandler := genericapifilters.Unauthorized(c.Serializer)\n\tfailedHandler = genericapifilters.WithFailedAuthenticationAudit(failedHandler, c.AuditBackend, c.AuditPolicyRuleEvaluator)\n\n\tfailedHandler = filterlatency.TrackCompleted(failedHandler)\n\thandler = filterlatency.TrackCompleted(handler)\n\thandler = genericapifilters.WithAuthentication(handler, c.Authentication.Authenticator, failedHandler, c.Authentication.APIAudiences, c.Authentication.RequestHeaderConfig)\n\thandler = filterlatency.TrackStarted(handler, c.TracerProvider, \"authentication\")\n\n\thandler = genericfilters.WithCORS(handler, c.CorsAllowedOriginList, nil, nil, nil, \"true\")\n\n\t// WithTimeoutForNonLongRunningRequests will call the rest of the request handling in a go-routine with the\n\t// context with deadline. The go-routine can keep running, while the timeout logic will return a timeout to the client.\n\thandler = genericfilters.WithTimeoutForNonLongRunningRequests(handler, c.LongRunningFunc)\n\n\thandler = genericapifilters.WithRequestDeadline(handler, c.AuditBackend, c.AuditPolicyRuleEvaluator,\n\t\tc.LongRunningFunc, c.Serializer, c.RequestTimeout)\n\thandler = genericfilters.WithWaitGroup(handler, c.LongRunningFunc, c.NonLongRunningRequestWaitGroup)\n\tif c.ShutdownWatchTerminationGracePeriod \u003e 0 {\n\t\thandler = genericfilters.WithWatchTerminationDuringShutdown(handler, c.lifecycleSignals, c.WatchRequestWaitGroup)\n\t}\n\tif c.SecureServing != nil \u0026\u0026 !c.SecureServing.DisableHTTP2 \u0026\u0026 c.GoawayChance \u003e 0 {\n\t\thandler = genericfilters.WithProbabilisticGoaway(handler, c.GoawayChance)\n\t}\n\thandler = genericapifilters.WithWarningRecorder(handler)\n\thandler = genericapifilters.WithCacheControl(handler)\n\thandler = genericfilters.WithHSTS(handler, c.HSTSDirectives)\n\tif c.ShutdownSendRetryAfter {\n\t\thandler = genericfilters.WithRetryAfter(handler, c.lifecycleSignals.NotAcceptingNewRequest.Signaled())\n\t}\n\thandler = genericfilters.WithHTTPLogging(handler)\n\tif utilfeature.DefaultFeatureGate.Enabled(genericfeatures.APIServerTracing) {\n\t\thandler = genericapifilters.WithTracing(handler, c.TracerProvider)\n\t}\n\thandler = genericapifilters.WithLatencyTrackers(handler)\n\thandler = genericapifilters.WithRequestInfo(handler, c.RequestInfoResolver)\n\thandler = genericapifilters.WithRequestReceivedTimestamp(handler)\n\thandler = genericapifilters.WithMuxAndDiscoveryComplete(handler, c.lifecycleSignals.MuxAndDiscoveryComplete.Signaled())\n\thandler = genericfilters.WithPanicRecovery(handler, c.RequestInfoResolver)\n\thandler = genericapifilters.WithAuditInit(handler)\n\treturn handler\n}","line":{"from":896,"to":960}} {"id":100017840,"name":"installAPI","signature":"func installAPI(s *GenericAPIServer, c *Config)","file":"staging/src/k8s.io/apiserver/pkg/server/config.go","code":"func installAPI(s *GenericAPIServer, c *Config) {\n\tif c.EnableIndex {\n\t\troutes.Index{}.Install(s.listedPathProvider, s.Handler.NonGoRestfulMux)\n\t}\n\tif c.EnableProfiling {\n\t\troutes.Profiling{}.Install(s.Handler.NonGoRestfulMux)\n\t\tif c.EnableContentionProfiling {\n\t\t\tgoruntime.SetBlockProfileRate(1)\n\t\t}\n\t\t// so far, only logging related endpoints are considered valid to add for these debug flags.\n\t\troutes.DebugFlags{}.Install(s.Handler.NonGoRestfulMux, \"v\", routes.StringFlagPutHandler(logs.GlogSetter))\n\t}\n\tif s.UnprotectedDebugSocket != nil {\n\t\ts.UnprotectedDebugSocket.InstallProfiling()\n\t\ts.UnprotectedDebugSocket.InstallDebugFlag(\"v\", routes.StringFlagPutHandler(logs.GlogSetter))\n\t\tif c.EnableContentionProfiling {\n\t\t\tgoruntime.SetBlockProfileRate(1)\n\t\t}\n\t}\n\n\tif c.EnableMetrics {\n\t\tif c.EnableProfiling {\n\t\t\troutes.MetricsWithReset{}.Install(s.Handler.NonGoRestfulMux)\n\t\t\tif utilfeature.DefaultFeatureGate.Enabled(features.ComponentSLIs) {\n\t\t\t\tslis.SLIMetricsWithReset{}.Install(s.Handler.NonGoRestfulMux)\n\t\t\t}\n\t\t} else {\n\t\t\troutes.DefaultMetrics{}.Install(s.Handler.NonGoRestfulMux)\n\t\t\tif utilfeature.DefaultFeatureGate.Enabled(features.ComponentSLIs) {\n\t\t\t\tslis.SLIMetrics{}.Install(s.Handler.NonGoRestfulMux)\n\t\t\t}\n\t\t}\n\t}\n\n\troutes.Version{Version: c.Version}.Install(s.Handler.GoRestfulContainer)\n\n\tif c.EnableDiscovery {\n\t\tif utilfeature.DefaultFeatureGate.Enabled(genericfeatures.AggregatedDiscoveryEndpoint) {\n\t\t\twrapped := discoveryendpoint.WrapAggregatedDiscoveryToHandler(s.DiscoveryGroupManager, s.AggregatedDiscoveryGroupManager)\n\t\t\ts.Handler.GoRestfulContainer.Add(wrapped.GenerateWebService(\"/apis\", metav1.APIGroupList{}))\n\t\t} else {\n\t\t\ts.Handler.GoRestfulContainer.Add(s.DiscoveryGroupManager.WebService())\n\t\t}\n\t}\n\tif c.FlowControl != nil \u0026\u0026 utilfeature.DefaultFeatureGate.Enabled(genericfeatures.APIPriorityAndFairness) {\n\t\tc.FlowControl.Install(s.Handler.NonGoRestfulMux)\n\t}\n}","line":{"from":962,"to":1009}} {"id":100017841,"name":"NewRequestInfoResolver","signature":"func NewRequestInfoResolver(c *Config) *apirequest.RequestInfoFactory","file":"staging/src/k8s.io/apiserver/pkg/server/config.go","code":"func NewRequestInfoResolver(c *Config) *apirequest.RequestInfoFactory {\n\tapiPrefixes := sets.NewString(strings.Trim(APIGroupPrefix, \"/\")) // all possible API prefixes\n\tlegacyAPIPrefixes := sets.String{} // APIPrefixes that won't have groups (legacy)\n\tfor legacyAPIPrefix := range c.LegacyAPIGroupPrefixes {\n\t\tapiPrefixes.Insert(strings.Trim(legacyAPIPrefix, \"/\"))\n\t\tlegacyAPIPrefixes.Insert(strings.Trim(legacyAPIPrefix, \"/\"))\n\t}\n\n\treturn \u0026apirequest.RequestInfoFactory{\n\t\tAPIPrefixes: apiPrefixes,\n\t\tGrouplessAPIPrefixes: legacyAPIPrefixes,\n\t}\n}","line":{"from":1011,"to":1023}} {"id":100017842,"name":"HostPort","signature":"func (s *SecureServingInfo) HostPort() (string, int, error)","file":"staging/src/k8s.io/apiserver/pkg/server/config.go","code":"func (s *SecureServingInfo) HostPort() (string, int, error) {\n\tif s == nil || s.Listener == nil {\n\t\treturn \"\", 0, fmt.Errorf(\"no listener found\")\n\t}\n\taddr := s.Listener.Addr().String()\n\thost, portStr, err := net.SplitHostPort(addr)\n\tif err != nil {\n\t\treturn \"\", 0, fmt.Errorf(\"failed to get port from listener address %q: %v\", addr, err)\n\t}\n\tport, err := utilsnet.ParsePort(portStr, true)\n\tif err != nil {\n\t\treturn \"\", 0, fmt.Errorf(\"invalid non-numeric port %q\", portStr)\n\t}\n\treturn host, port, nil\n}","line":{"from":1025,"to":1039}} {"id":100017843,"name":"AuthorizeClientBearerToken","signature":"func AuthorizeClientBearerToken(loopback *restclient.Config, authn *AuthenticationInfo, authz *AuthorizationInfo)","file":"staging/src/k8s.io/apiserver/pkg/server/config.go","code":"// AuthorizeClientBearerToken wraps the authenticator and authorizer in loopback authentication logic\n// if the loopback client config is specified AND it has a bearer token. Note that if either authn or\n// authz is nil, this function won't add a token authenticator or authorizer.\nfunc AuthorizeClientBearerToken(loopback *restclient.Config, authn *AuthenticationInfo, authz *AuthorizationInfo) {\n\tif loopback == nil || len(loopback.BearerToken) == 0 {\n\t\treturn\n\t}\n\tif authn == nil || authz == nil {\n\t\t// prevent nil pointer panic\n\t\treturn\n\t}\n\tif authn.Authenticator == nil || authz.Authorizer == nil {\n\t\t// authenticator or authorizer might be nil if we want to bypass authz/authn\n\t\t// and we also do nothing in this case.\n\t\treturn\n\t}\n\n\tprivilegedLoopbackToken := loopback.BearerToken\n\tvar uid = uuid.New().String()\n\ttokens := make(map[string]*user.DefaultInfo)\n\ttokens[privilegedLoopbackToken] = \u0026user.DefaultInfo{\n\t\tName: user.APIServerUser,\n\t\tUID: uid,\n\t\tGroups: []string{user.SystemPrivilegedGroup},\n\t}\n\n\ttokenAuthenticator := authenticatorfactory.NewFromTokens(tokens, authn.APIAudiences)\n\tauthn.Authenticator = authenticatorunion.New(tokenAuthenticator, authn.Authenticator)\n}","line":{"from":1041,"to":1069}} {"id":100017844,"name":"NewClientConfig","signature":"func (s *SecureServingInfo) NewClientConfig(caCert []byte) (*restclient.Config, error)","file":"staging/src/k8s.io/apiserver/pkg/server/config_selfclient.go","code":"func (s *SecureServingInfo) NewClientConfig(caCert []byte) (*restclient.Config, error) {\n\tif s == nil || (s.Cert == nil \u0026\u0026 len(s.SNICerts) == 0) {\n\t\treturn nil, nil\n\t}\n\n\thost, port, err := LoopbackHostPort(s.Listener.Addr().String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026restclient.Config{\n\t\t// Do not limit loopback client QPS.\n\t\tQPS: -1,\n\t\tHost: \"https://\" + net.JoinHostPort(host, port),\n\t\tTLSClientConfig: restclient.TLSClientConfig{\n\t\t\tCAData: caCert,\n\t\t},\n\t}, nil\n}","line":{"from":31,"to":49}} {"id":100017845,"name":"NewLoopbackClientConfig","signature":"func (s *SecureServingInfo) NewLoopbackClientConfig(token string, loopbackCert []byte) (*restclient.Config, error)","file":"staging/src/k8s.io/apiserver/pkg/server/config_selfclient.go","code":"func (s *SecureServingInfo) NewLoopbackClientConfig(token string, loopbackCert []byte) (*restclient.Config, error) {\n\tc, err := s.NewClientConfig(loopbackCert)\n\tif err != nil || c == nil {\n\t\treturn c, err\n\t}\n\n\tc.BearerToken = token\n\t// override the ServerName to select our loopback certificate via SNI. This name is also\n\t// used by the client to compare the returns server certificate against.\n\tc.TLSClientConfig.ServerName = LoopbackClientServerNameOverride\n\n\treturn c, nil\n}","line":{"from":51,"to":63}} {"id":100017846,"name":"LoopbackHostPort","signature":"func LoopbackHostPort(bindAddress string) (string, string, error)","file":"staging/src/k8s.io/apiserver/pkg/server/config_selfclient.go","code":"// LoopbackHostPort returns the host and port loopback REST clients should use\n// to contact the server.\nfunc LoopbackHostPort(bindAddress string) (string, string, error) {\n\thost, port, err := net.SplitHostPort(bindAddress)\n\tif err != nil {\n\t\t// should never happen\n\t\treturn \"\", \"\", fmt.Errorf(\"invalid server bind address: %q\", bindAddress)\n\t}\n\n\tisIPv6 := netutils.IsIPv6String(host)\n\n\t// Value is expected to be an IP or DNS name, not \"0.0.0.0\".\n\tif host == \"0.0.0.0\" || host == \"::\" {\n\t\t// Get ip of local interface, but fall back to \"localhost\".\n\t\t// Note that \"localhost\" is resolved with the external nameserver first with Go's stdlib.\n\t\t// So if localhost.\u003cyoursearchdomain\u003e resolves, we don't get a 127.0.0.1 as expected.\n\t\thost = getLoopbackAddress(isIPv6)\n\t}\n\treturn host, port, nil\n}","line":{"from":65,"to":84}} {"id":100017847,"name":"getLoopbackAddress","signature":"func getLoopbackAddress(wantIPv6 bool) string","file":"staging/src/k8s.io/apiserver/pkg/server/config_selfclient.go","code":"// getLoopbackAddress returns the ip address of local loopback interface. If any error occurs or loopback interface is not found, will fall back to \"localhost\"\nfunc getLoopbackAddress(wantIPv6 bool) string {\n\taddrs, err := net.InterfaceAddrs()\n\tif err == nil {\n\t\tfor _, address := range addrs {\n\t\t\tif ipnet, ok := address.(*net.IPNet); ok \u0026\u0026 ipnet.IP.IsLoopback() \u0026\u0026 wantIPv6 == netutils.IsIPv6(ipnet.IP) {\n\t\t\t\treturn ipnet.IP.String()\n\t\t\t}\n\t\t}\n\t}\n\treturn \"localhost\"\n}","line":{"from":86,"to":97}} {"id":100017848,"name":"NewResourceExpirationEvaluator","signature":"func NewResourceExpirationEvaluator(currentVersion apimachineryversion.Info) (ResourceExpirationEvaluator, error)","file":"staging/src/k8s.io/apiserver/pkg/server/deleted_kinds.go","code":"func NewResourceExpirationEvaluator(currentVersion apimachineryversion.Info) (ResourceExpirationEvaluator, error) {\n\tret := \u0026resourceExpirationEvaluator{\n\t\tstrictRemovedHandlingInAlpha: false,\n\t}\n\tif len(currentVersion.Major) \u003e 0 {\n\t\tcurrentMajor64, err := strconv.ParseInt(currentVersion.Major, 10, 32)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tret.currentMajor = int(currentMajor64)\n\t}\n\tif len(currentVersion.Minor) \u003e 0 {\n\t\t// split the \"normal\" + and - for semver stuff\n\t\tminorString := strings.Split(currentVersion.Minor, \"+\")[0]\n\t\tminorString = strings.Split(minorString, \"-\")[0]\n\t\tminorString = strings.Split(minorString, \".\")[0]\n\t\tcurrentMinor64, err := strconv.ParseInt(minorString, 10, 32)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tret.currentMinor = int(currentMinor64)\n\t}\n\n\tret.isAlpha = strings.Contains(currentVersion.GitVersion, \"alpha\")\n\n\tif envString, ok := os.LookupEnv(\"KUBE_APISERVER_STRICT_REMOVED_API_HANDLING_IN_ALPHA\"); !ok {\n\t\t// do nothing\n\t} else if envBool, err := strconv.ParseBool(envString); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tret.strictRemovedHandlingInAlpha = envBool\n\t}\n\n\tif envString, ok := os.LookupEnv(\"KUBE_APISERVER_SERVE_REMOVED_APIS_FOR_ONE_RELEASE\"); !ok {\n\t\t// do nothing\n\t} else if envBool, err := strconv.ParseBool(envString); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tret.serveRemovedAPIsOneMoreRelease = envBool\n\t}\n\n\treturn ret, nil\n}","line":{"from":56,"to":98}} {"id":100017849,"name":"shouldServe","signature":"func (e *resourceExpirationEvaluator) shouldServe(gv schema.GroupVersion, versioner runtime.ObjectVersioner, resourceServingInfo rest.Storage) bool","file":"staging/src/k8s.io/apiserver/pkg/server/deleted_kinds.go","code":"func (e *resourceExpirationEvaluator) shouldServe(gv schema.GroupVersion, versioner runtime.ObjectVersioner, resourceServingInfo rest.Storage) bool {\n\tinternalPtr := resourceServingInfo.New()\n\n\ttarget := gv\n\t// honor storage that overrides group version (used for things like scale subresources)\n\tif versionProvider, ok := resourceServingInfo.(rest.GroupVersionKindProvider); ok {\n\t\ttarget = versionProvider.GroupVersionKind(target).GroupVersion()\n\t}\n\n\tversionedPtr, err := versioner.ConvertToVersion(internalPtr, target)\n\tif err != nil {\n\t\tutilruntime.HandleError(err)\n\t\treturn false\n\t}\n\n\tremoved, ok := versionedPtr.(removedInterface)\n\tif !ok {\n\t\treturn true\n\t}\n\tmajorRemoved, minorRemoved := removed.APILifecycleRemoved()\n\treturn e.ShouldServeForVersion(majorRemoved, minorRemoved)\n}","line":{"from":100,"to":121}} {"id":100017850,"name":"ShouldServeForVersion","signature":"func (e *resourceExpirationEvaluator) ShouldServeForVersion(majorRemoved, minorRemoved int) bool","file":"staging/src/k8s.io/apiserver/pkg/server/deleted_kinds.go","code":"func (e *resourceExpirationEvaluator) ShouldServeForVersion(majorRemoved, minorRemoved int) bool {\n\tif e.currentMajor \u003c majorRemoved {\n\t\treturn true\n\t}\n\tif e.currentMajor \u003e majorRemoved {\n\t\treturn false\n\t}\n\tif e.currentMinor \u003c minorRemoved {\n\t\treturn true\n\t}\n\tif e.currentMinor \u003e minorRemoved {\n\t\treturn false\n\t}\n\t// at this point major and minor are equal, so this API should be removed when the current release GAs.\n\t// If this is an alpha tag, don't remove by default, but allow the option.\n\t// If the cluster-admin has requested serving one more release, allow it.\n\tif e.isAlpha \u0026\u0026 e.strictRemovedHandlingInAlpha { // don't serve in alpha if we want strict handling\n\t\treturn false\n\t}\n\tif e.isAlpha { // alphas are allowed to continue serving expired betas while we clean up the test\n\t\treturn true\n\t}\n\tif e.serveRemovedAPIsOneMoreRelease { // cluster-admins are allowed to kick the can one release down the road\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":123,"to":149}} {"id":100017851,"name":"RemoveDeletedKinds","signature":"func (e *resourceExpirationEvaluator) RemoveDeletedKinds(groupName string, versioner runtime.ObjectVersioner, versionedResourcesStorageMap map[string]map[string]rest.Storage)","file":"staging/src/k8s.io/apiserver/pkg/server/deleted_kinds.go","code":"// removeDeletedKinds inspects the storage map and modifies it in place by removing storage for kinds that have been deleted.\n// versionedResourcesStorageMap mirrors the field on APIGroupInfo, it's a map from version to resource to the storage.\nfunc (e *resourceExpirationEvaluator) RemoveDeletedKinds(groupName string, versioner runtime.ObjectVersioner, versionedResourcesStorageMap map[string]map[string]rest.Storage) {\n\tversionsToRemove := sets.NewString()\n\tfor apiVersion := range sets.StringKeySet(versionedResourcesStorageMap) {\n\t\tversionToResource := versionedResourcesStorageMap[apiVersion]\n\t\tresourcesToRemove := sets.NewString()\n\t\tfor resourceName, resourceServingInfo := range versionToResource {\n\t\t\tif !e.shouldServe(schema.GroupVersion{Group: groupName, Version: apiVersion}, versioner, resourceServingInfo) {\n\t\t\t\tresourcesToRemove.Insert(resourceName)\n\t\t\t}\n\t\t}\n\n\t\tfor resourceName := range versionedResourcesStorageMap[apiVersion] {\n\t\t\tif !shouldRemoveResourceAndSubresources(resourcesToRemove, resourceName) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tklog.V(1).Infof(\"Removing resource %v.%v.%v because it is time to stop serving it per APILifecycle.\", resourceName, apiVersion, groupName)\n\t\t\tdelete(versionToResource, resourceName)\n\t\t}\n\t\tversionedResourcesStorageMap[apiVersion] = versionToResource\n\n\t\tif len(versionedResourcesStorageMap[apiVersion]) == 0 {\n\t\t\tversionsToRemove.Insert(apiVersion)\n\t\t}\n\t}\n\n\tfor _, apiVersion := range versionsToRemove.List() {\n\t\tklog.V(1).Infof(\"Removing version %v.%v because it is time to stop serving it because it has no resources per APILifecycle.\", apiVersion, groupName)\n\t\tdelete(versionedResourcesStorageMap, apiVersion)\n\t}\n}","line":{"from":155,"to":187}} {"id":100017852,"name":"shouldRemoveResourceAndSubresources","signature":"func shouldRemoveResourceAndSubresources(resourcesToRemove sets.String, resourceName string) bool","file":"staging/src/k8s.io/apiserver/pkg/server/deleted_kinds.go","code":"func shouldRemoveResourceAndSubresources(resourcesToRemove sets.String, resourceName string) bool {\n\tfor _, resourceToRemove := range resourcesToRemove.List() {\n\t\tif resourceName == resourceToRemove {\n\t\t\treturn true\n\t\t}\n\t\t// our API works on nesting, so you can have deployments, deployments/status, and deployments/scale. Not all subresources\n\t\t// serve the parent type, but if the parent type (deployments in this case), has been removed, it's subresources should be removed too.\n\t\tif strings.HasPrefix(resourceName, resourceToRemove+\"/\") {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":189,"to":201}} {"id":100017853,"name":"Serve","signature":"func (s *DeprecatedInsecureServingInfo) Serve(handler http.Handler, shutdownTimeout time.Duration, stopCh \u003c-chan struct{}) error","file":"staging/src/k8s.io/apiserver/pkg/server/deprecated_insecure_serving.go","code":"// Serve starts an insecure http server with the given handler. It fails only if\n// the initial listen call fails. It does not block.\nfunc (s *DeprecatedInsecureServingInfo) Serve(handler http.Handler, shutdownTimeout time.Duration, stopCh \u003c-chan struct{}) error {\n\tinsecureServer := \u0026http.Server{\n\t\tAddr: s.Listener.Addr().String(),\n\t\tHandler: handler,\n\t\tMaxHeaderBytes: 1 \u003c\u003c 20,\n\n\t\tIdleTimeout: 90 * time.Second, // matches http.DefaultTransport keep-alive timeout\n\t\tReadHeaderTimeout: 32 * time.Second, // just shy of requestTimeoutUpperBound\n\t}\n\n\tif len(s.Name) \u003e 0 {\n\t\tklog.Infof(\"Serving %s insecurely on %s\", s.Name, s.Listener.Addr())\n\t} else {\n\t\tklog.Infof(\"Serving insecurely on %s\", s.Listener.Addr())\n\t}\n\t_, _, err := RunServer(insecureServer, s.Listener, shutdownTimeout, stopCh)\n\t// NOTE: we do not handle stoppedCh returned by RunServer for graceful termination here\n\treturn err\n}","line":{"from":41,"to":61}} {"id":100017854,"name":"NewLoopbackClientConfig","signature":"func (s *DeprecatedInsecureServingInfo) NewLoopbackClientConfig() (*rest.Config, error)","file":"staging/src/k8s.io/apiserver/pkg/server/deprecated_insecure_serving.go","code":"func (s *DeprecatedInsecureServingInfo) NewLoopbackClientConfig() (*rest.Config, error) {\n\tif s == nil {\n\t\treturn nil, nil\n\t}\n\n\thost, port, err := LoopbackHostPort(s.Listener.Addr().String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026rest.Config{\n\t\tHost: \"http://\" + net.JoinHostPort(host, port),\n\t\t// Increase QPS limits. The client is currently passed to all admission plugins,\n\t\t// and those can be throttled in case of higher load on apiserver - see #22340 and #22422\n\t\t// for more details. Once #22422 is fixed, we may want to remove it.\n\t\tQPS: 50,\n\t\tBurst: 100,\n\t}, nil\n}","line":{"from":63,"to":81}} {"id":100017855,"name":"AuthenticateRequest","signature":"func (InsecureSuperuser) AuthenticateRequest(req *http.Request) (*authenticator.Response, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/server/deprecated_insecure_serving.go","code":"func (InsecureSuperuser) AuthenticateRequest(req *http.Request) (*authenticator.Response, bool, error) {\n\tauds, _ := authenticator.AudiencesFrom(req.Context())\n\treturn \u0026authenticator.Response{\n\t\tUser: \u0026user.DefaultInfo{\n\t\t\tName: \"system:unsecured\",\n\t\t\tGroups: []string{user.SystemPrivilegedGroup, user.AllAuthenticated},\n\t\t},\n\t\tAudiences: auds,\n\t}, true, nil\n}","line":{"from":88,"to":97}} {"id":100017856,"name":"Equal","signature":"func (c *certKeyContent) Equal(rhs *certKeyContent) bool","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/cert_key.go","code":"func (c *certKeyContent) Equal(rhs *certKeyContent) bool {\n\tif c == nil || rhs == nil {\n\t\treturn c == rhs\n\t}\n\n\treturn bytes.Equal(c.key, rhs.key) \u0026\u0026 bytes.Equal(c.cert, rhs.cert)\n}","line":{"from":29,"to":35}} {"id":100017857,"name":"Equal","signature":"func (c *sniCertKeyContent) Equal(rhs *sniCertKeyContent) bool","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/cert_key.go","code":"func (c *sniCertKeyContent) Equal(rhs *sniCertKeyContent) bool {\n\tif c == nil || rhs == nil {\n\t\treturn c == rhs\n\t}\n\n\tif len(c.sniNames) != len(rhs.sniNames) {\n\t\treturn false\n\t}\n\n\tfor i := range c.sniNames {\n\t\tif c.sniNames[i] != rhs.sniNames[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn c.certKeyContent.Equal(\u0026rhs.certKeyContent)\n}","line":{"from":43,"to":59}} {"id":100017858,"name":"Equal","signature":"func (c *dynamicCertificateContent) Equal(rhs *dynamicCertificateContent) bool","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/client_ca.go","code":"func (c *dynamicCertificateContent) Equal(rhs *dynamicCertificateContent) bool {\n\tif c == nil || rhs == nil {\n\t\treturn c == rhs\n\t}\n\n\tif !c.clientCA.Equal(\u0026rhs.clientCA) {\n\t\treturn false\n\t}\n\n\tif !c.servingCert.Equal(\u0026rhs.servingCert) {\n\t\treturn false\n\t}\n\n\tif len(c.sniCerts) != len(rhs.sniCerts) {\n\t\treturn false\n\t}\n\n\tfor i := range c.sniCerts {\n\t\tif !c.sniCerts[i].Equal(\u0026rhs.sniCerts[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}","line":{"from":37,"to":61}} {"id":100017859,"name":"Equal","signature":"func (c *caBundleContent) Equal(rhs *caBundleContent) bool","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/client_ca.go","code":"func (c *caBundleContent) Equal(rhs *caBundleContent) bool {\n\tif c == nil || rhs == nil {\n\t\treturn c == rhs\n\t}\n\n\treturn bytes.Equal(c.caBundle, rhs.caBundle)\n}","line":{"from":63,"to":69}} {"id":100017860,"name":"NewDynamicCAFromConfigMapController","signature":"func NewDynamicCAFromConfigMapController(purpose, namespace, name, key string, kubeClient kubernetes.Interface) (*ConfigMapCAController, error)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/configmap_cafile_content.go","code":"// NewDynamicCAFromConfigMapController returns a CAContentProvider based on a configmap that automatically reloads content.\n// It is near-realtime via an informer.\nfunc NewDynamicCAFromConfigMapController(purpose, namespace, name, key string, kubeClient kubernetes.Interface) (*ConfigMapCAController, error) {\n\tif len(purpose) == 0 {\n\t\treturn nil, fmt.Errorf(\"missing purpose for ca bundle\")\n\t}\n\tif len(namespace) == 0 {\n\t\treturn nil, fmt.Errorf(\"missing namespace for ca bundle\")\n\t}\n\tif len(name) == 0 {\n\t\treturn nil, fmt.Errorf(\"missing name for ca bundle\")\n\t}\n\tif len(key) == 0 {\n\t\treturn nil, fmt.Errorf(\"missing key for ca bundle\")\n\t}\n\tcaContentName := fmt.Sprintf(\"%s::%s::%s::%s\", purpose, namespace, name, key)\n\n\t// we construct our own informer because we need such a small subset of the information available. Just one namespace.\n\tuncastConfigmapInformer := corev1informers.NewFilteredConfigMapInformer(kubeClient, namespace, 12*time.Hour, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, func(listOptions *v1.ListOptions) {\n\t\tlistOptions.FieldSelector = fields.OneTermEqualSelector(\"metadata.name\", name).String()\n\t})\n\n\tconfigmapLister := corev1listers.NewConfigMapLister(uncastConfigmapInformer.GetIndexer())\n\n\tc := \u0026ConfigMapCAController{\n\t\tname: caContentName,\n\t\tconfigmapNamespace: namespace,\n\t\tconfigmapName: name,\n\t\tconfigmapKey: key,\n\t\tconfigmapLister: configmapLister,\n\t\tconfigMapInformer: uncastConfigmapInformer,\n\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), fmt.Sprintf(\"DynamicConfigMapCABundle-%s\", purpose)),\n\t\tpreRunCaches: []cache.InformerSynced{uncastConfigmapInformer.HasSynced},\n\t}\n\n\tuncastConfigmapInformer.AddEventHandler(cache.FilteringResourceEventHandler{\n\t\tFilterFunc: func(obj interface{}) bool {\n\t\t\tif cast, ok := obj.(*corev1.ConfigMap); ok {\n\t\t\t\treturn cast.Name == c.configmapName \u0026\u0026 cast.Namespace == c.configmapNamespace\n\t\t\t}\n\t\t\tif tombstone, ok := obj.(cache.DeletedFinalStateUnknown); ok {\n\t\t\t\tif cast, ok := tombstone.Obj.(*corev1.ConfigMap); ok {\n\t\t\t\t\treturn cast.Name == c.configmapName \u0026\u0026 cast.Namespace == c.configmapNamespace\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true // always return true just in case. The checks are fairly cheap\n\t\t},\n\t\tHandler: cache.ResourceEventHandlerFuncs{\n\t\t\t// we have a filter, so any time we're called, we may as well queue. We only ever check one configmap\n\t\t\t// so we don't have to be choosy about our key.\n\t\t\tAddFunc: func(obj interface{}) {\n\t\t\t\tc.queue.Add(c.keyFn())\n\t\t\t},\n\t\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\t\tc.queue.Add(c.keyFn())\n\t\t\t},\n\t\t\tDeleteFunc: func(obj interface{}) {\n\t\t\t\tc.queue.Add(c.keyFn())\n\t\t\t},\n\t\t},\n\t})\n\n\treturn c, nil\n}","line":{"from":65,"to":129}} {"id":100017861,"name":"keyFn","signature":"func (c *ConfigMapCAController) keyFn() string","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/configmap_cafile_content.go","code":"func (c *ConfigMapCAController) keyFn() string {\n\t// this format matches DeletionHandlingMetaNamespaceKeyFunc for our single key\n\treturn c.configmapNamespace + \"/\" + c.configmapName\n}","line":{"from":131,"to":134}} {"id":100017862,"name":"AddListener","signature":"func (c *ConfigMapCAController) AddListener(listener Listener)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/configmap_cafile_content.go","code":"// AddListener adds a listener to be notified when the CA content changes.\nfunc (c *ConfigMapCAController) AddListener(listener Listener) {\n\tc.listeners = append(c.listeners, listener)\n}","line":{"from":136,"to":139}} {"id":100017863,"name":"loadCABundle","signature":"func (c *ConfigMapCAController) loadCABundle() error","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/configmap_cafile_content.go","code":"// loadCABundle determines the next set of content for the file.\nfunc (c *ConfigMapCAController) loadCABundle() error {\n\tconfigMap, err := c.configmapLister.ConfigMaps(c.configmapNamespace).Get(c.configmapName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcaBundle := configMap.Data[c.configmapKey]\n\tif len(caBundle) == 0 {\n\t\treturn fmt.Errorf(\"missing content for CA bundle %q\", c.Name())\n\t}\n\n\t// check to see if we have a change. If the values are the same, do nothing.\n\tif !c.hasCAChanged([]byte(caBundle)) {\n\t\treturn nil\n\t}\n\n\tcaBundleAndVerifier, err := newCABundleAndVerifier(c.Name(), []byte(caBundle))\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.caBundle.Store(caBundleAndVerifier)\n\n\tfor _, listener := range c.listeners {\n\t\tlistener.Enqueue()\n\t}\n\n\treturn nil\n}","line":{"from":141,"to":168}} {"id":100017864,"name":"hasCAChanged","signature":"func (c *ConfigMapCAController) hasCAChanged(caBundle []byte) bool","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/configmap_cafile_content.go","code":"// hasCAChanged returns true if the caBundle is different than the current.\nfunc (c *ConfigMapCAController) hasCAChanged(caBundle []byte) bool {\n\tuncastExisting := c.caBundle.Load()\n\tif uncastExisting == nil {\n\t\treturn true\n\t}\n\n\t// check to see if we have a change. If the values are the same, do nothing.\n\texisting, ok := uncastExisting.(*caBundleAndVerifier)\n\tif !ok {\n\t\treturn true\n\t}\n\tif !bytes.Equal(existing.caBundle, caBundle) {\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":170,"to":187}} {"id":100017865,"name":"RunOnce","signature":"func (c *ConfigMapCAController) RunOnce(ctx context.Context) error","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/configmap_cafile_content.go","code":"// RunOnce runs a single sync loop\nfunc (c *ConfigMapCAController) RunOnce(ctx context.Context) error {\n\t// Ignore the error when running once because when using a dynamically loaded ca file, because we think it's better to have nothing for\n\t// a brief time than completely crash. If crashing is necessary, higher order logic like a healthcheck and cause failures.\n\t_ = c.loadCABundle()\n\treturn nil\n}","line":{"from":189,"to":195}} {"id":100017866,"name":"Run","signature":"func (c *ConfigMapCAController) Run(ctx context.Context, workers int)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/configmap_cafile_content.go","code":"// Run starts the kube-apiserver and blocks until stopCh is closed.\nfunc (c *ConfigMapCAController) Run(ctx context.Context, workers int) {\n\tdefer utilruntime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\n\tklog.InfoS(\"Starting controller\", \"name\", c.name)\n\tdefer klog.InfoS(\"Shutting down controller\", \"name\", c.name)\n\n\t// we have a personal informer that is narrowly scoped, start it.\n\tgo c.configMapInformer.Run(ctx.Done())\n\n\t// wait for your secondary caches to fill before starting your work\n\tif !cache.WaitForNamedCacheSync(c.name, ctx.Done(), c.preRunCaches...) {\n\t\treturn\n\t}\n\n\t// doesn't matter what workers say, only start one.\n\tgo wait.Until(c.runWorker, time.Second, ctx.Done())\n\n\t// start timer that rechecks every minute, just in case. this also serves to prime the controller quickly.\n\tgo wait.PollImmediateUntil(FileRefreshDuration, func() (bool, error) {\n\t\tc.queue.Add(workItemKey)\n\t\treturn false, nil\n\t}, ctx.Done())\n\n\t\u003c-ctx.Done()\n}","line":{"from":197,"to":223}} {"id":100017867,"name":"runWorker","signature":"func (c *ConfigMapCAController) runWorker()","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/configmap_cafile_content.go","code":"func (c *ConfigMapCAController) runWorker() {\n\tfor c.processNextWorkItem() {\n\t}\n}","line":{"from":225,"to":228}} {"id":100017868,"name":"processNextWorkItem","signature":"func (c *ConfigMapCAController) processNextWorkItem() bool","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/configmap_cafile_content.go","code":"func (c *ConfigMapCAController) processNextWorkItem() bool {\n\tdsKey, quit := c.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.queue.Done(dsKey)\n\n\terr := c.loadCABundle()\n\tif err == nil {\n\t\tc.queue.Forget(dsKey)\n\t\treturn true\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"%v failed with : %v\", dsKey, err))\n\tc.queue.AddRateLimited(dsKey)\n\n\treturn true\n}","line":{"from":230,"to":247}} {"id":100017869,"name":"Name","signature":"func (c *ConfigMapCAController) Name() string","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/configmap_cafile_content.go","code":"// Name is just an identifier\nfunc (c *ConfigMapCAController) Name() string {\n\treturn c.name\n}","line":{"from":249,"to":252}} {"id":100017870,"name":"CurrentCABundleContent","signature":"func (c *ConfigMapCAController) CurrentCABundleContent() []byte","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/configmap_cafile_content.go","code":"// CurrentCABundleContent provides ca bundle byte content\nfunc (c *ConfigMapCAController) CurrentCABundleContent() []byte {\n\tuncastObj := c.caBundle.Load()\n\tif uncastObj == nil {\n\t\treturn nil // this can happen if we've been unable load data from the apiserver for some reason\n\t}\n\n\treturn c.caBundle.Load().(*caBundleAndVerifier).caBundle\n}","line":{"from":254,"to":262}} {"id":100017871,"name":"VerifyOptions","signature":"func (c *ConfigMapCAController) VerifyOptions() (x509.VerifyOptions, bool)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/configmap_cafile_content.go","code":"// VerifyOptions provides verifyoptions compatible with authenticators\nfunc (c *ConfigMapCAController) VerifyOptions() (x509.VerifyOptions, bool) {\n\tuncastObj := c.caBundle.Load()\n\tif uncastObj == nil {\n\t\t// This can happen if we've been unable load data from the apiserver for some reason.\n\t\t// In this case, we should not accept any connections on the basis of this ca bundle.\n\t\treturn x509.VerifyOptions{}, false\n\t}\n\n\treturn uncastObj.(*caBundleAndVerifier).verifyOptions, true\n}","line":{"from":264,"to":274}} {"id":100017872,"name":"NewDynamicCAContentFromFile","signature":"func NewDynamicCAContentFromFile(purpose, filename string) (*DynamicFileCAContent, error)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_cafile_content.go","code":"// NewDynamicCAContentFromFile returns a CAContentProvider based on a filename that automatically reloads content\nfunc NewDynamicCAContentFromFile(purpose, filename string) (*DynamicFileCAContent, error) {\n\tif len(filename) == 0 {\n\t\treturn nil, fmt.Errorf(\"missing filename for ca bundle\")\n\t}\n\tname := fmt.Sprintf(\"%s::%s\", purpose, filename)\n\n\tret := \u0026DynamicFileCAContent{\n\t\tname: name,\n\t\tfilename: filename,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), fmt.Sprintf(\"DynamicCABundle-%s\", purpose)),\n\t}\n\tif err := ret.loadCABundle(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ret, nil\n}","line":{"from":75,"to":92}} {"id":100017873,"name":"AddListener","signature":"func (c *DynamicFileCAContent) AddListener(listener Listener)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_cafile_content.go","code":"// AddListener adds a listener to be notified when the CA content changes.\nfunc (c *DynamicFileCAContent) AddListener(listener Listener) {\n\tc.listeners = append(c.listeners, listener)\n}","line":{"from":94,"to":97}} {"id":100017874,"name":"loadCABundle","signature":"func (c *DynamicFileCAContent) loadCABundle() error","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_cafile_content.go","code":"// loadCABundle determines the next set of content for the file.\nfunc (c *DynamicFileCAContent) loadCABundle() error {\n\tcaBundle, err := ioutil.ReadFile(c.filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(caBundle) == 0 {\n\t\treturn fmt.Errorf(\"missing content for CA bundle %q\", c.Name())\n\t}\n\n\t// check to see if we have a change. If the values are the same, do nothing.\n\tif !c.hasCAChanged(caBundle) {\n\t\treturn nil\n\t}\n\n\tcaBundleAndVerifier, err := newCABundleAndVerifier(c.Name(), caBundle)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.caBundle.Store(caBundleAndVerifier)\n\tklog.V(2).InfoS(\"Loaded a new CA Bundle and Verifier\", \"name\", c.Name())\n\n\tfor _, listener := range c.listeners {\n\t\tlistener.Enqueue()\n\t}\n\n\treturn nil\n}","line":{"from":99,"to":126}} {"id":100017875,"name":"hasCAChanged","signature":"func (c *DynamicFileCAContent) hasCAChanged(caBundle []byte) bool","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_cafile_content.go","code":"// hasCAChanged returns true if the caBundle is different than the current.\nfunc (c *DynamicFileCAContent) hasCAChanged(caBundle []byte) bool {\n\tuncastExisting := c.caBundle.Load()\n\tif uncastExisting == nil {\n\t\treturn true\n\t}\n\n\t// check to see if we have a change. If the values are the same, do nothing.\n\texisting, ok := uncastExisting.(*caBundleAndVerifier)\n\tif !ok {\n\t\treturn true\n\t}\n\tif !bytes.Equal(existing.caBundle, caBundle) {\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":128,"to":145}} {"id":100017876,"name":"RunOnce","signature":"func (c *DynamicFileCAContent) RunOnce(ctx context.Context) error","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_cafile_content.go","code":"// RunOnce runs a single sync loop\nfunc (c *DynamicFileCAContent) RunOnce(ctx context.Context) error {\n\treturn c.loadCABundle()\n}","line":{"from":147,"to":150}} {"id":100017877,"name":"Run","signature":"func (c *DynamicFileCAContent) Run(ctx context.Context, workers int)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_cafile_content.go","code":"// Run starts the controller and blocks until stopCh is closed.\nfunc (c *DynamicFileCAContent) Run(ctx context.Context, workers int) {\n\tdefer utilruntime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\n\tklog.InfoS(\"Starting controller\", \"name\", c.name)\n\tdefer klog.InfoS(\"Shutting down controller\", \"name\", c.name)\n\n\t// doesn't matter what workers say, only start one.\n\tgo wait.Until(c.runWorker, time.Second, ctx.Done())\n\n\t// start the loop that watches the CA file until stopCh is closed.\n\tgo wait.Until(func() {\n\t\tif err := c.watchCAFile(ctx.Done()); err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to watch CA file, will retry later\")\n\t\t}\n\t}, time.Minute, ctx.Done())\n\n\t\u003c-ctx.Done()\n}","line":{"from":152,"to":171}} {"id":100017878,"name":"watchCAFile","signature":"func (c *DynamicFileCAContent) watchCAFile(stopCh \u003c-chan struct{}) error","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_cafile_content.go","code":"func (c *DynamicFileCAContent) watchCAFile(stopCh \u003c-chan struct{}) error {\n\t// Trigger a check here to ensure the content will be checked periodically even if the following watch fails.\n\tc.queue.Add(workItemKey)\n\n\tw, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating fsnotify watcher: %v\", err)\n\t}\n\tdefer w.Close()\n\n\tif err = w.Add(c.filename); err != nil {\n\t\treturn fmt.Errorf(\"error adding watch for file %s: %v\", c.filename, err)\n\t}\n\t// Trigger a check in case the file is updated before the watch starts.\n\tc.queue.Add(workItemKey)\n\n\tfor {\n\t\tselect {\n\t\tcase e := \u003c-w.Events:\n\t\t\tif err := c.handleWatchEvent(e, w); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase err := \u003c-w.Errors:\n\t\t\treturn fmt.Errorf(\"received fsnotify error: %v\", err)\n\t\tcase \u003c-stopCh:\n\t\t\treturn nil\n\t\t}\n\t}\n}","line":{"from":173,"to":201}} {"id":100017879,"name":"handleWatchEvent","signature":"func (c *DynamicFileCAContent) handleWatchEvent(e fsnotify.Event, w *fsnotify.Watcher) error","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_cafile_content.go","code":"// handleWatchEvent triggers reloading the CA file, and restarts a new watch if it's a Remove or Rename event.\nfunc (c *DynamicFileCAContent) handleWatchEvent(e fsnotify.Event, w *fsnotify.Watcher) error {\n\t// This should be executed after restarting the watch (if applicable) to ensure no file event will be missing.\n\tdefer c.queue.Add(workItemKey)\n\tif !e.Has(fsnotify.Remove) \u0026\u0026 !e.Has(fsnotify.Rename) {\n\t\treturn nil\n\t}\n\tif err := w.Remove(c.filename); err != nil {\n\t\tklog.InfoS(\"Failed to remove file watch, it may have been deleted\", \"file\", c.filename, \"err\", err)\n\t}\n\tif err := w.Add(c.filename); err != nil {\n\t\treturn fmt.Errorf(\"error adding watch for file %s: %v\", c.filename, err)\n\t}\n\treturn nil\n}","line":{"from":203,"to":217}} {"id":100017880,"name":"runWorker","signature":"func (c *DynamicFileCAContent) runWorker()","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_cafile_content.go","code":"func (c *DynamicFileCAContent) runWorker() {\n\tfor c.processNextWorkItem() {\n\t}\n}","line":{"from":219,"to":222}} {"id":100017881,"name":"processNextWorkItem","signature":"func (c *DynamicFileCAContent) processNextWorkItem() bool","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_cafile_content.go","code":"func (c *DynamicFileCAContent) processNextWorkItem() bool {\n\tdsKey, quit := c.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.queue.Done(dsKey)\n\n\terr := c.loadCABundle()\n\tif err == nil {\n\t\tc.queue.Forget(dsKey)\n\t\treturn true\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"%v failed with : %v\", dsKey, err))\n\tc.queue.AddRateLimited(dsKey)\n\n\treturn true\n}","line":{"from":224,"to":241}} {"id":100017882,"name":"Name","signature":"func (c *DynamicFileCAContent) Name() string","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_cafile_content.go","code":"// Name is just an identifier\nfunc (c *DynamicFileCAContent) Name() string {\n\treturn c.name\n}","line":{"from":243,"to":246}} {"id":100017883,"name":"CurrentCABundleContent","signature":"func (c *DynamicFileCAContent) CurrentCABundleContent() (cabundle []byte)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_cafile_content.go","code":"// CurrentCABundleContent provides ca bundle byte content\nfunc (c *DynamicFileCAContent) CurrentCABundleContent() (cabundle []byte) {\n\treturn c.caBundle.Load().(*caBundleAndVerifier).caBundle\n}","line":{"from":248,"to":251}} {"id":100017884,"name":"VerifyOptions","signature":"func (c *DynamicFileCAContent) VerifyOptions() (x509.VerifyOptions, bool)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_cafile_content.go","code":"// VerifyOptions provides verifyoptions compatible with authenticators\nfunc (c *DynamicFileCAContent) VerifyOptions() (x509.VerifyOptions, bool) {\n\tuncastObj := c.caBundle.Load()\n\tif uncastObj == nil {\n\t\treturn x509.VerifyOptions{}, false\n\t}\n\n\treturn uncastObj.(*caBundleAndVerifier).verifyOptions, true\n}","line":{"from":253,"to":261}} {"id":100017885,"name":"newCABundleAndVerifier","signature":"func newCABundleAndVerifier(name string, caBundle []byte) (*caBundleAndVerifier, error)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_cafile_content.go","code":"// newVerifyOptions creates a new verification func from a file. It reads the content and then fails.\n// It will return a nil function if you pass an empty CA file.\nfunc newCABundleAndVerifier(name string, caBundle []byte) (*caBundleAndVerifier, error) {\n\tif len(caBundle) == 0 {\n\t\treturn nil, fmt.Errorf(\"missing content for CA bundle %q\", name)\n\t}\n\n\t// Wrap with an x509 verifier\n\tvar err error\n\tverifyOptions := defaultVerifyOptions()\n\tverifyOptions.Roots, err = cert.NewPoolFromBytes(caBundle)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error loading CA bundle for %q: %v\", name, err)\n\t}\n\n\treturn \u0026caBundleAndVerifier{\n\t\tcaBundle: caBundle,\n\t\tverifyOptions: verifyOptions,\n\t}, nil\n}","line":{"from":263,"to":282}} {"id":100017886,"name":"defaultVerifyOptions","signature":"func defaultVerifyOptions() x509.VerifyOptions","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_cafile_content.go","code":"// defaultVerifyOptions returns VerifyOptions that use the system root certificates, current time,\n// and requires certificates to be valid for client auth (x509.ExtKeyUsageClientAuth)\nfunc defaultVerifyOptions() x509.VerifyOptions {\n\treturn x509.VerifyOptions{\n\t\tKeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},\n\t}\n}","line":{"from":284,"to":290}} {"id":100017887,"name":"NewDynamicServingContentFromFiles","signature":"func NewDynamicServingContentFromFiles(purpose, certFile, keyFile string) (*DynamicCertKeyPairContent, error)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_serving_content.go","code":"// NewDynamicServingContentFromFiles returns a dynamic CertKeyContentProvider based on a cert and key filename\nfunc NewDynamicServingContentFromFiles(purpose, certFile, keyFile string) (*DynamicCertKeyPairContent, error) {\n\tif len(certFile) == 0 || len(keyFile) == 0 {\n\t\treturn nil, fmt.Errorf(\"missing filename for serving cert\")\n\t}\n\tname := fmt.Sprintf(\"%s::%s::%s\", purpose, certFile, keyFile)\n\n\tret := \u0026DynamicCertKeyPairContent{\n\t\tname: name,\n\t\tcertFile: certFile,\n\t\tkeyFile: keyFile,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), fmt.Sprintf(\"DynamicCABundle-%s\", purpose)),\n\t}\n\tif err := ret.loadCertKeyPair(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ret, nil\n}","line":{"from":56,"to":74}} {"id":100017888,"name":"AddListener","signature":"func (c *DynamicCertKeyPairContent) AddListener(listener Listener)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_serving_content.go","code":"// AddListener adds a listener to be notified when the serving cert content changes.\nfunc (c *DynamicCertKeyPairContent) AddListener(listener Listener) {\n\tc.listeners = append(c.listeners, listener)\n}","line":{"from":76,"to":79}} {"id":100017889,"name":"loadCertKeyPair","signature":"func (c *DynamicCertKeyPairContent) loadCertKeyPair() error","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_serving_content.go","code":"// loadCertKeyPair determines the next set of content for the file.\nfunc (c *DynamicCertKeyPairContent) loadCertKeyPair() error {\n\tcert, err := ioutil.ReadFile(c.certFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tkey, err := ioutil.ReadFile(c.keyFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(cert) == 0 || len(key) == 0 {\n\t\treturn fmt.Errorf(\"missing content for serving cert %q\", c.Name())\n\t}\n\n\t// Ensure that the key matches the cert and both are valid\n\t_, err = tls.X509KeyPair(cert, key)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnewCertKey := \u0026certKeyContent{\n\t\tcert: cert,\n\t\tkey: key,\n\t}\n\n\t// check to see if we have a change. If the values are the same, do nothing.\n\texisting, ok := c.certKeyPair.Load().(*certKeyContent)\n\tif ok \u0026\u0026 existing != nil \u0026\u0026 existing.Equal(newCertKey) {\n\t\treturn nil\n\t}\n\n\tc.certKeyPair.Store(newCertKey)\n\tklog.V(2).InfoS(\"Loaded a new cert/key pair\", \"name\", c.Name())\n\n\tfor _, listener := range c.listeners {\n\t\tlistener.Enqueue()\n\t}\n\n\treturn nil\n}","line":{"from":81,"to":120}} {"id":100017890,"name":"RunOnce","signature":"func (c *DynamicCertKeyPairContent) RunOnce(ctx context.Context) error","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_serving_content.go","code":"// RunOnce runs a single sync loop\nfunc (c *DynamicCertKeyPairContent) RunOnce(ctx context.Context) error {\n\treturn c.loadCertKeyPair()\n}","line":{"from":122,"to":125}} {"id":100017891,"name":"Run","signature":"func (c *DynamicCertKeyPairContent) Run(ctx context.Context, workers int)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_serving_content.go","code":"// Run starts the controller and blocks until context is killed.\nfunc (c *DynamicCertKeyPairContent) Run(ctx context.Context, workers int) {\n\tdefer utilruntime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\n\tklog.InfoS(\"Starting controller\", \"name\", c.name)\n\tdefer klog.InfoS(\"Shutting down controller\", \"name\", c.name)\n\n\t// doesn't matter what workers say, only start one.\n\tgo wait.Until(c.runWorker, time.Second, ctx.Done())\n\n\t// start the loop that watches the cert and key files until stopCh is closed.\n\tgo wait.Until(func() {\n\t\tif err := c.watchCertKeyFile(ctx.Done()); err != nil {\n\t\t\tklog.ErrorS(err, \"Failed to watch cert and key file, will retry later\")\n\t\t}\n\t}, time.Minute, ctx.Done())\n\n\t\u003c-ctx.Done()\n}","line":{"from":127,"to":146}} {"id":100017892,"name":"watchCertKeyFile","signature":"func (c *DynamicCertKeyPairContent) watchCertKeyFile(stopCh \u003c-chan struct{}) error","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_serving_content.go","code":"func (c *DynamicCertKeyPairContent) watchCertKeyFile(stopCh \u003c-chan struct{}) error {\n\t// Trigger a check here to ensure the content will be checked periodically even if the following watch fails.\n\tc.queue.Add(workItemKey)\n\n\tw, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating fsnotify watcher: %v\", err)\n\t}\n\tdefer w.Close()\n\n\tif err := w.Add(c.certFile); err != nil {\n\t\treturn fmt.Errorf(\"error adding watch for file %s: %v\", c.certFile, err)\n\t}\n\tif err := w.Add(c.keyFile); err != nil {\n\t\treturn fmt.Errorf(\"error adding watch for file %s: %v\", c.keyFile, err)\n\t}\n\t// Trigger a check in case the file is updated before the watch starts.\n\tc.queue.Add(workItemKey)\n\n\tfor {\n\t\tselect {\n\t\tcase e := \u003c-w.Events:\n\t\t\tif err := c.handleWatchEvent(e, w); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase err := \u003c-w.Errors:\n\t\t\treturn fmt.Errorf(\"received fsnotify error: %v\", err)\n\t\tcase \u003c-stopCh:\n\t\t\treturn nil\n\t\t}\n\t}\n}","line":{"from":148,"to":179}} {"id":100017893,"name":"handleWatchEvent","signature":"func (c *DynamicCertKeyPairContent) handleWatchEvent(e fsnotify.Event, w *fsnotify.Watcher) error","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_serving_content.go","code":"// handleWatchEvent triggers reloading the cert and key file, and restarts a new watch if it's a Remove or Rename event.\n// If one file is updated before the other, the loadCertKeyPair method will catch the mismatch and will not apply the\n// change. When an event of the other file is received, it will trigger reloading the files again and the new content\n// will be loaded and used.\nfunc (c *DynamicCertKeyPairContent) handleWatchEvent(e fsnotify.Event, w *fsnotify.Watcher) error {\n\t// This should be executed after restarting the watch (if applicable) to ensure no file event will be missing.\n\tdefer c.queue.Add(workItemKey)\n\tif !e.Has(fsnotify.Remove) \u0026\u0026 !e.Has(fsnotify.Rename) {\n\t\treturn nil\n\t}\n\tif err := w.Remove(e.Name); err != nil {\n\t\tklog.InfoS(\"Failed to remove file watch, it may have been deleted\", \"file\", e.Name, \"err\", err)\n\t}\n\tif err := w.Add(e.Name); err != nil {\n\t\treturn fmt.Errorf(\"error adding watch for file %s: %v\", e.Name, err)\n\t}\n\treturn nil\n}","line":{"from":181,"to":198}} {"id":100017894,"name":"runWorker","signature":"func (c *DynamicCertKeyPairContent) runWorker()","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_serving_content.go","code":"func (c *DynamicCertKeyPairContent) runWorker() {\n\tfor c.processNextWorkItem() {\n\t}\n}","line":{"from":200,"to":203}} {"id":100017895,"name":"processNextWorkItem","signature":"func (c *DynamicCertKeyPairContent) processNextWorkItem() bool","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_serving_content.go","code":"func (c *DynamicCertKeyPairContent) processNextWorkItem() bool {\n\tdsKey, quit := c.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.queue.Done(dsKey)\n\n\terr := c.loadCertKeyPair()\n\tif err == nil {\n\t\tc.queue.Forget(dsKey)\n\t\treturn true\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"%v failed with : %v\", dsKey, err))\n\tc.queue.AddRateLimited(dsKey)\n\n\treturn true\n}","line":{"from":205,"to":222}} {"id":100017896,"name":"Name","signature":"func (c *DynamicCertKeyPairContent) Name() string","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_serving_content.go","code":"// Name is just an identifier\nfunc (c *DynamicCertKeyPairContent) Name() string {\n\treturn c.name\n}","line":{"from":224,"to":227}} {"id":100017897,"name":"CurrentCertKeyContent","signature":"func (c *DynamicCertKeyPairContent) CurrentCertKeyContent() ([]byte, []byte)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_serving_content.go","code":"// CurrentCertKeyContent provides cert and key byte content\nfunc (c *DynamicCertKeyPairContent) CurrentCertKeyContent() ([]byte, []byte) {\n\tcertKeyContent := c.certKeyPair.Load().(*certKeyContent)\n\treturn certKeyContent.cert, certKeyContent.key\n}","line":{"from":229,"to":233}} {"id":100017898,"name":"NewDynamicSNIContentFromFiles","signature":"func NewDynamicSNIContentFromFiles(purpose, certFile, keyFile string, sniNames ...string) (*DynamicFileSNIContent, error)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_sni_content.go","code":"// NewDynamicSNIContentFromFiles returns a dynamic SNICertKeyContentProvider based on a cert and key filename and explicit names\nfunc NewDynamicSNIContentFromFiles(purpose, certFile, keyFile string, sniNames ...string) (*DynamicFileSNIContent, error) {\n\tservingContent, err := NewDynamicServingContentFromFiles(purpose, certFile, keyFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret := \u0026DynamicFileSNIContent{\n\t\tDynamicCertKeyPairContent: servingContent,\n\t\tsniNames: sniNames,\n\t}\n\tif err := ret.loadCertKeyPair(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ret, nil\n}","line":{"from":28,"to":44}} {"id":100017899,"name":"SNINames","signature":"func (c *DynamicFileSNIContent) SNINames() []string","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/dynamic_sni_content.go","code":"// SNINames returns explicitly set SNI names for the certificate. These are not dynamic.\nfunc (c *DynamicFileSNIContent) SNINames() []string {\n\treturn c.sniNames\n}","line":{"from":46,"to":49}} {"id":100017900,"name":"BuildNamedCertificates","signature":"func (c *DynamicServingCertificateController) BuildNamedCertificates(sniCerts []sniCertKeyContent) (map[string]*tls.Certificate, error)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/named_certificates.go","code":"// BuildNamedCertificates returns a map of *tls.Certificate by name. It's\n// suitable for use in tls.Config#NamedCertificates. Returns an error if any of the certs\n// is invalid. Returns nil if len(certs) == 0\nfunc (c *DynamicServingCertificateController) BuildNamedCertificates(sniCerts []sniCertKeyContent) (map[string]*tls.Certificate, error) {\n\tnameToCertificate := map[string]*tls.Certificate{}\n\tbyNameExplicit := map[string]*tls.Certificate{}\n\n\t// Iterate backwards so that earlier certs take precedence in the names map\n\tfor i := len(sniCerts) - 1; i \u003e= 0; i-- {\n\t\tcert, err := tls.X509KeyPair(sniCerts[i].cert, sniCerts[i].key)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid SNI cert keypair [%d/%q]: %v\", i, c.sniCerts[i].Name(), err)\n\t\t}\n\n\t\t// error is not possible given above call to X509KeyPair\n\t\tx509Cert, _ := x509.ParseCertificate(cert.Certificate[0])\n\n\t\tnames := sniCerts[i].sniNames\n\t\tfor _, name := range names {\n\t\t\tbyNameExplicit[name] = \u0026cert\n\t\t}\n\n\t\tklog.V(2).InfoS(\"Loaded SNI cert\", \"index\", i, \"certName\", c.sniCerts[i].Name(), \"certDetail\", GetHumanCertDetail(x509Cert))\n\t\tif c.eventRecorder != nil {\n\t\t\tc.eventRecorder.Eventf(\u0026corev1.ObjectReference{Name: c.sniCerts[i].Name()}, nil, corev1.EventTypeWarning, \"TLSConfigChanged\", \"SNICertificateReload\", \"loaded SNI cert [%d/%q]: %s with explicit names %v\", i, c.sniCerts[i].Name(), GetHumanCertDetail(x509Cert), names)\n\t\t}\n\n\t\tif len(names) == 0 {\n\t\t\tnames = getCertificateNames(x509Cert)\n\t\t\tfor _, name := range names {\n\t\t\t\tnameToCertificate[name] = \u0026cert\n\t\t\t}\n\t\t}\n\t}\n\n\t// Explicitly set names must override\n\tfor k, v := range byNameExplicit {\n\t\tnameToCertificate[k] = v\n\t}\n\n\treturn nameToCertificate, nil\n}","line":{"from":31,"to":72}} {"id":100017901,"name":"getCertificateNames","signature":"func getCertificateNames(cert *x509.Certificate) []string","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/named_certificates.go","code":"// getCertificateNames returns names for an x509.Certificate. The names are\n// suitable for use in tls.Config#NamedCertificates.\nfunc getCertificateNames(cert *x509.Certificate) []string {\n\tvar names []string\n\n\tcn := cert.Subject.CommonName\n\tcnIsIP := netutils.ParseIPSloppy(cn) != nil\n\tcnIsValidDomain := cn == \"*\" || len(validation.IsDNS1123Subdomain(strings.TrimPrefix(cn, \"*.\"))) == 0\n\t// don't use the CN if it is a valid IP because our IP serving detection may unexpectedly use it to terminate the connection.\n\tif !cnIsIP \u0026\u0026 cnIsValidDomain {\n\t\tnames = append(names, cn)\n\t}\n\tnames = append(names, cert.DNSNames...)\n\t// intentionally all IPs in the cert are ignored as SNI forbids passing IPs\n\t// to select a cert. Before go 1.6 the tls happily passed IPs as SNI values.\n\n\treturn names\n}","line":{"from":74,"to":91}} {"id":100017902,"name":"NewStaticCAContent","signature":"func NewStaticCAContent(name string, caBundle []byte) (CAContentProvider, error)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/static_content.go","code":"// NewStaticCAContent returns a CAContentProvider that always returns the same value\nfunc NewStaticCAContent(name string, caBundle []byte) (CAContentProvider, error) {\n\tcaBundleAndVerifier, err := newCABundleAndVerifier(name, caBundle)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026staticCAContent{\n\t\tname: name,\n\t\tcaBundle: caBundleAndVerifier,\n\t}, nil\n}","line":{"from":31,"to":42}} {"id":100017903,"name":"Name","signature":"func (c *staticCAContent) Name() string","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/static_content.go","code":"// Name is just an identifier\nfunc (c *staticCAContent) Name() string {\n\treturn c.name\n}","line":{"from":44,"to":47}} {"id":100017904,"name":"AddListener","signature":"func (c *staticCAContent) AddListener(Listener) {}","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/static_content.go","code":"func (c *staticCAContent) AddListener(Listener) {}","line":{"from":49,"to":49}} {"id":100017905,"name":"CurrentCABundleContent","signature":"func (c *staticCAContent) CurrentCABundleContent() (cabundle []byte)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/static_content.go","code":"// CurrentCABundleContent provides ca bundle byte content\nfunc (c *staticCAContent) CurrentCABundleContent() (cabundle []byte) {\n\treturn c.caBundle.caBundle\n}","line":{"from":51,"to":54}} {"id":100017906,"name":"VerifyOptions","signature":"func (c *staticCAContent) VerifyOptions() (x509.VerifyOptions, bool)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/static_content.go","code":"func (c *staticCAContent) VerifyOptions() (x509.VerifyOptions, bool) {\n\treturn c.caBundle.verifyOptions, true\n}","line":{"from":56,"to":58}} {"id":100017907,"name":"NewStaticCertKeyContent","signature":"func NewStaticCertKeyContent(name string, cert, key []byte) (CertKeyContentProvider, error)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/static_content.go","code":"// NewStaticCertKeyContent returns a CertKeyContentProvider that always returns the same value\nfunc NewStaticCertKeyContent(name string, cert, key []byte) (CertKeyContentProvider, error) {\n\t// Ensure that the key matches the cert and both are valid\n\t_, err := tls.X509KeyPair(cert, key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026staticCertKeyContent{\n\t\tname: name,\n\t\tcert: cert,\n\t\tkey: key,\n\t}, nil\n}","line":{"from":66,"to":79}} {"id":100017908,"name":"Name","signature":"func (c *staticCertKeyContent) Name() string","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/static_content.go","code":"// Name is just an identifier\nfunc (c *staticCertKeyContent) Name() string {\n\treturn c.name\n}","line":{"from":81,"to":84}} {"id":100017909,"name":"AddListener","signature":"func (c *staticCertKeyContent) AddListener(Listener) {}","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/static_content.go","code":"func (c *staticCertKeyContent) AddListener(Listener) {}","line":{"from":86,"to":86}} {"id":100017910,"name":"CurrentCertKeyContent","signature":"func (c *staticCertKeyContent) CurrentCertKeyContent() ([]byte, []byte)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/static_content.go","code":"// CurrentCertKeyContent provides cert and key content\nfunc (c *staticCertKeyContent) CurrentCertKeyContent() ([]byte, []byte) {\n\treturn c.cert, c.key\n}","line":{"from":88,"to":91}} {"id":100017911,"name":"NewStaticSNICertKeyContent","signature":"func NewStaticSNICertKeyContent(name string, cert, key []byte, sniNames ...string) (SNICertKeyContentProvider, error)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/static_content.go","code":"// NewStaticSNICertKeyContent returns a SNICertKeyContentProvider that always returns the same value\nfunc NewStaticSNICertKeyContent(name string, cert, key []byte, sniNames ...string) (SNICertKeyContentProvider, error) {\n\t// Ensure that the key matches the cert and both are valid\n\t_, err := tls.X509KeyPair(cert, key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026staticSNICertKeyContent{\n\t\tstaticCertKeyContent: staticCertKeyContent{\n\t\t\tname: name,\n\t\t\tcert: cert,\n\t\t\tkey: key,\n\t\t},\n\t\tsniNames: sniNames,\n\t}, nil\n}","line":{"from":98,"to":114}} {"id":100017912,"name":"SNINames","signature":"func (c *staticSNICertKeyContent) SNINames() []string","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/static_content.go","code":"func (c *staticSNICertKeyContent) SNINames() []string {\n\treturn c.sniNames\n}","line":{"from":116,"to":118}} {"id":100017913,"name":"AddListener","signature":"func (c *staticSNICertKeyContent) AddListener(Listener) {}","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/static_content.go","code":"func (c *staticSNICertKeyContent) AddListener(Listener) {}","line":{"from":120,"to":120}} {"id":100017914,"name":"NewDynamicServingCertificateController","signature":"func NewDynamicServingCertificateController(","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/tlsconfig.go","code":"// NewDynamicServingCertificateController returns a controller that can be used to keep a TLSConfig up to date.\nfunc NewDynamicServingCertificateController(\n\tbaseTLSConfig *tls.Config,\n\tclientCA CAContentProvider,\n\tservingCert CertKeyContentProvider,\n\tsniCerts []SNICertKeyContentProvider,\n\teventRecorder events.EventRecorder,\n) *DynamicServingCertificateController {\n\tc := \u0026DynamicServingCertificateController{\n\t\tbaseTLSConfig: baseTLSConfig,\n\t\tclientCA: clientCA,\n\t\tservingCert: servingCert,\n\t\tsniCerts: sniCerts,\n\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"DynamicServingCertificateController\"),\n\t\teventRecorder: eventRecorder,\n\t}\n\n\treturn c\n}","line":{"from":65,"to":84}} {"id":100017915,"name":"GetConfigForClient","signature":"func (c *DynamicServingCertificateController) GetConfigForClient(clientHello *tls.ClientHelloInfo) (*tls.Config, error)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/tlsconfig.go","code":"// GetConfigForClient is an implementation of tls.Config.GetConfigForClient\nfunc (c *DynamicServingCertificateController) GetConfigForClient(clientHello *tls.ClientHelloInfo) (*tls.Config, error) {\n\tuncastObj := c.currentServingTLSConfig.Load()\n\tif uncastObj == nil {\n\t\treturn nil, errors.New(\"dynamiccertificates: configuration not ready\")\n\t}\n\ttlsConfig, ok := uncastObj.(*tls.Config)\n\tif !ok {\n\t\treturn nil, errors.New(\"dynamiccertificates: unexpected config type\")\n\t}\n\n\ttlsConfigCopy := tlsConfig.Clone()\n\n\t// if the client set SNI information, just use our \"normal\" SNI flow\n\tif len(clientHello.ServerName) \u003e 0 {\n\t\treturn tlsConfigCopy, nil\n\t}\n\n\t// if the client didn't set SNI, then we need to inspect the requested IP so that we can choose\n\t// a certificate from our list if we specifically handle that IP. This can happen when an IP is specifically mapped by name.\n\thost, _, err := net.SplitHostPort(clientHello.Conn.LocalAddr().String())\n\tif err != nil {\n\t\treturn tlsConfigCopy, nil\n\t}\n\n\tipCert, ok := tlsConfigCopy.NameToCertificate[host]\n\tif !ok {\n\t\treturn tlsConfigCopy, nil\n\t}\n\ttlsConfigCopy.Certificates = []tls.Certificate{*ipCert}\n\ttlsConfigCopy.NameToCertificate = nil\n\n\treturn tlsConfigCopy, nil\n}","line":{"from":86,"to":119}} {"id":100017916,"name":"newTLSContent","signature":"func (c *DynamicServingCertificateController) newTLSContent() (*dynamicCertificateContent, error)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/tlsconfig.go","code":"// newTLSContent determines the next set of content for overriding the baseTLSConfig.\nfunc (c *DynamicServingCertificateController) newTLSContent() (*dynamicCertificateContent, error) {\n\tnewContent := \u0026dynamicCertificateContent{}\n\n\tif c.clientCA != nil {\n\t\tcurrClientCABundle := c.clientCA.CurrentCABundleContent()\n\t\t// we allow removing all client ca bundles because the server is still secure when this happens. it just means\n\t\t// that there isn't a hint to clients about which client-cert to used. this happens when there is no client-ca\n\t\t// yet known for authentication, which can happen in aggregated apiservers and some kube-apiserver deployment modes.\n\t\tnewContent.clientCA = caBundleContent{caBundle: currClientCABundle}\n\t}\n\n\tif c.servingCert != nil {\n\t\tcurrServingCert, currServingKey := c.servingCert.CurrentCertKeyContent()\n\t\tif len(currServingCert) == 0 || len(currServingKey) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"not loading an empty serving certificate from %q\", c.servingCert.Name())\n\t\t}\n\n\t\tnewContent.servingCert = certKeyContent{cert: currServingCert, key: currServingKey}\n\t}\n\n\tfor i, sniCert := range c.sniCerts {\n\t\tcurrCert, currKey := sniCert.CurrentCertKeyContent()\n\t\tif len(currCert) == 0 || len(currKey) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"not loading an empty SNI certificate from %d/%q\", i, sniCert.Name())\n\t\t}\n\n\t\tnewContent.sniCerts = append(newContent.sniCerts, sniCertKeyContent{certKeyContent: certKeyContent{cert: currCert, key: currKey}, sniNames: sniCert.SNINames()})\n\t}\n\n\treturn newContent, nil\n}","line":{"from":121,"to":152}} {"id":100017917,"name":"syncCerts","signature":"func (c *DynamicServingCertificateController) syncCerts() error","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/tlsconfig.go","code":"// syncCerts gets newTLSContent, if it has changed from the existing, the content is parsed and stored for usage in\n// GetConfigForClient.\nfunc (c *DynamicServingCertificateController) syncCerts() error {\n\tnewContent, err := c.newTLSContent()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// if the content is the same as what we currently have, we can simply skip it. This works because we are single\n\t// threaded. If you ever make this multi-threaded, add a lock.\n\tif newContent.Equal(c.currentlyServedContent) {\n\t\treturn nil\n\t}\n\n\t// make a shallow copy and override the dynamic pieces which have changed.\n\tnewTLSConfigCopy := c.baseTLSConfig.Clone()\n\n\t// parse new content to add to TLSConfig\n\tif len(newContent.clientCA.caBundle) \u003e 0 {\n\t\tnewClientCAPool := x509.NewCertPool()\n\t\tnewClientCAs, err := cert.ParseCertsPEM(newContent.clientCA.caBundle)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to load client CA file %q: %v\", string(newContent.clientCA.caBundle), err)\n\t\t}\n\t\tfor i, cert := range newClientCAs {\n\t\t\tklog.V(2).InfoS(\"Loaded client CA\", \"index\", i, \"certName\", c.clientCA.Name(), \"certDetail\", GetHumanCertDetail(cert))\n\t\t\tif c.eventRecorder != nil {\n\t\t\t\tc.eventRecorder.Eventf(\u0026corev1.ObjectReference{Name: c.clientCA.Name()}, nil, corev1.EventTypeWarning, \"TLSConfigChanged\", \"CACertificateReload\", \"loaded client CA [%d/%q]: %s\", i, c.clientCA.Name(), GetHumanCertDetail(cert))\n\t\t\t}\n\n\t\t\tnewClientCAPool.AddCert(cert)\n\t\t}\n\n\t\tnewTLSConfigCopy.ClientCAs = newClientCAPool\n\t}\n\n\tif len(newContent.servingCert.cert) \u003e 0 \u0026\u0026 len(newContent.servingCert.key) \u003e 0 {\n\t\tcert, err := tls.X509KeyPair(newContent.servingCert.cert, newContent.servingCert.key)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid serving cert keypair: %v\", err)\n\t\t}\n\n\t\tx509Cert, err := x509.ParseCertificate(cert.Certificate[0])\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid serving cert: %v\", err)\n\t\t}\n\n\t\tklog.V(2).InfoS(\"Loaded serving cert\", \"certName\", c.servingCert.Name(), \"certDetail\", GetHumanCertDetail(x509Cert))\n\t\tif c.eventRecorder != nil {\n\t\t\tc.eventRecorder.Eventf(\u0026corev1.ObjectReference{Name: c.servingCert.Name()}, nil, corev1.EventTypeWarning, \"TLSConfigChanged\", \"ServingCertificateReload\", \"loaded serving cert [%q]: %s\", c.servingCert.Name(), GetHumanCertDetail(x509Cert))\n\t\t}\n\n\t\tnewTLSConfigCopy.Certificates = []tls.Certificate{cert}\n\t}\n\n\tif len(newContent.sniCerts) \u003e 0 {\n\t\tnewTLSConfigCopy.NameToCertificate, err = c.BuildNamedCertificates(newContent.sniCerts)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to build named certificate map: %v\", err)\n\t\t}\n\n\t\t// append all named certs. Otherwise, the go tls stack will think no SNI processing\n\t\t// is necessary because there is only one cert anyway.\n\t\t// Moreover, if servingCert is not set, the first SNI\n\t\t// cert will become the default cert. That's what we expect anyway.\n\t\tfor _, sniCert := range newTLSConfigCopy.NameToCertificate {\n\t\t\tnewTLSConfigCopy.Certificates = append(newTLSConfigCopy.Certificates, *sniCert)\n\t\t}\n\t}\n\n\t// store new values of content for serving.\n\tc.currentServingTLSConfig.Store(newTLSConfigCopy)\n\tc.currentlyServedContent = newContent // this is single threaded, so we have no locking issue\n\n\treturn nil\n}","line":{"from":154,"to":228}} {"id":100017918,"name":"RunOnce","signature":"func (c *DynamicServingCertificateController) RunOnce() error","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/tlsconfig.go","code":"// RunOnce runs a single sync step to ensure that we have a valid starting configuration.\nfunc (c *DynamicServingCertificateController) RunOnce() error {\n\treturn c.syncCerts()\n}","line":{"from":230,"to":233}} {"id":100017919,"name":"Run","signature":"func (c *DynamicServingCertificateController) Run(workers int, stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/tlsconfig.go","code":"// Run starts the kube-apiserver and blocks until stopCh is closed.\nfunc (c *DynamicServingCertificateController) Run(workers int, stopCh \u003c-chan struct{}) {\n\tdefer utilruntime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\n\tklog.InfoS(\"Starting DynamicServingCertificateController\")\n\tdefer klog.InfoS(\"Shutting down DynamicServingCertificateController\")\n\n\t// synchronously load once. We will trigger again, so ignoring any error is fine\n\t_ = c.RunOnce()\n\n\t// doesn't matter what workers say, only start one.\n\tgo wait.Until(c.runWorker, time.Second, stopCh)\n\n\t// start timer that rechecks every minute, just in case. this also serves to prime the controller quickly.\n\tgo wait.Until(func() {\n\t\tc.Enqueue()\n\t}, 1*time.Minute, stopCh)\n\n\t\u003c-stopCh\n}","line":{"from":235,"to":255}} {"id":100017920,"name":"runWorker","signature":"func (c *DynamicServingCertificateController) runWorker()","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/tlsconfig.go","code":"func (c *DynamicServingCertificateController) runWorker() {\n\tfor c.processNextWorkItem() {\n\t}\n}","line":{"from":257,"to":260}} {"id":100017921,"name":"processNextWorkItem","signature":"func (c *DynamicServingCertificateController) processNextWorkItem() bool","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/tlsconfig.go","code":"func (c *DynamicServingCertificateController) processNextWorkItem() bool {\n\tdsKey, quit := c.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.queue.Done(dsKey)\n\n\terr := c.syncCerts()\n\tif err == nil {\n\t\tc.queue.Forget(dsKey)\n\t\treturn true\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"%v failed with : %v\", dsKey, err))\n\tc.queue.AddRateLimited(dsKey)\n\n\treturn true\n}","line":{"from":262,"to":279}} {"id":100017922,"name":"Enqueue","signature":"func (c *DynamicServingCertificateController) Enqueue()","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/tlsconfig.go","code":"// Enqueue a method to allow separate control loops to cause the certificate controller to trigger and read content.\nfunc (c *DynamicServingCertificateController) Enqueue() {\n\tc.queue.Add(workItemKey)\n}","line":{"from":281,"to":284}} {"id":100017923,"name":"NewUnionCAContentProvider","signature":"func NewUnionCAContentProvider(caContentProviders ...CAContentProvider) CAContentProvider","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/union_content.go","code":"// NewUnionCAContentProvider returns a CAContentProvider that is a union of other CAContentProviders\nfunc NewUnionCAContentProvider(caContentProviders ...CAContentProvider) CAContentProvider {\n\treturn unionCAContent(caContentProviders)\n}","line":{"from":33,"to":36}} {"id":100017924,"name":"Name","signature":"func (c unionCAContent) Name() string","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/union_content.go","code":"// Name is just an identifier\nfunc (c unionCAContent) Name() string {\n\tnames := []string{}\n\tfor _, curr := range c {\n\t\tnames = append(names, curr.Name())\n\t}\n\treturn strings.Join(names, \",\")\n}","line":{"from":38,"to":45}} {"id":100017925,"name":"CurrentCABundleContent","signature":"func (c unionCAContent) CurrentCABundleContent() []byte","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/union_content.go","code":"// CurrentCABundleContent provides ca bundle byte content\nfunc (c unionCAContent) CurrentCABundleContent() []byte {\n\tcaBundles := [][]byte{}\n\tfor _, curr := range c {\n\t\tif currCABytes := curr.CurrentCABundleContent(); len(currCABytes) \u003e 0 {\n\t\t\tcaBundles = append(caBundles, []byte(strings.TrimSpace(string(currCABytes))))\n\t\t}\n\t}\n\n\treturn bytes.Join(caBundles, []byte(\"\\n\"))\n}","line":{"from":47,"to":57}} {"id":100017926,"name":"VerifyOptions","signature":"func (c unionCAContent) VerifyOptions() (x509.VerifyOptions, bool)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/union_content.go","code":"// CurrentCABundleContent provides ca bundle byte content\nfunc (c unionCAContent) VerifyOptions() (x509.VerifyOptions, bool) {\n\tcurrCABundle := c.CurrentCABundleContent()\n\tif len(currCABundle) == 0 {\n\t\treturn x509.VerifyOptions{}, false\n\t}\n\n\t// TODO make more efficient. This isn't actually used in any of our mainline paths. It's called to build the TLSConfig\n\t// TODO on file changes, but the actual authentication runs against the individual items, not the union.\n\tret, err := newCABundleAndVerifier(c.Name(), c.CurrentCABundleContent())\n\tif err != nil {\n\t\t// because we're made up of already vetted values, this indicates some kind of coding error\n\t\tpanic(err)\n\t}\n\n\treturn ret.verifyOptions, true\n}","line":{"from":59,"to":75}} {"id":100017927,"name":"AddListener","signature":"func (c unionCAContent) AddListener(listener Listener)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/union_content.go","code":"// AddListener adds a listener to be notified when the CA content changes.\nfunc (c unionCAContent) AddListener(listener Listener) {\n\tfor _, curr := range c {\n\t\tcurr.AddListener(listener)\n\t}\n}","line":{"from":77,"to":82}} {"id":100017928,"name":"RunOnce","signature":"func (c unionCAContent) RunOnce(ctx context.Context) error","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/union_content.go","code":"// AddListener adds a listener to be notified when the CA content changes.\nfunc (c unionCAContent) RunOnce(ctx context.Context) error {\n\terrors := []error{}\n\tfor _, curr := range c {\n\t\tif controller, ok := curr.(ControllerRunner); ok {\n\t\t\tif err := controller.RunOnce(ctx); err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn utilerrors.NewAggregate(errors)\n}","line":{"from":84,"to":96}} {"id":100017929,"name":"Run","signature":"func (c unionCAContent) Run(ctx context.Context, workers int)","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/union_content.go","code":"// Run runs the controller\nfunc (c unionCAContent) Run(ctx context.Context, workers int) {\n\tfor _, curr := range c {\n\t\tif controller, ok := curr.(ControllerRunner); ok {\n\t\t\tgo controller.Run(ctx, workers)\n\t\t}\n\t}\n}","line":{"from":98,"to":105}} {"id":100017930,"name":"GetHumanCertDetail","signature":"func GetHumanCertDetail(certificate *x509.Certificate) string","file":"staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates/util.go","code":"// GetHumanCertDetail is a convenient method for printing compact details of certificate that helps when debugging\n// kube-apiserver usage of certs.\nfunc GetHumanCertDetail(certificate *x509.Certificate) string {\n\thumanName := certificate.Subject.CommonName\n\tsignerHumanName := certificate.Issuer.CommonName\n\tif certificate.Subject.CommonName == certificate.Issuer.CommonName {\n\t\tsignerHumanName = \"\u003cself\u003e\"\n\t}\n\n\tusages := []string{}\n\tfor _, curr := range certificate.ExtKeyUsage {\n\t\tif curr == x509.ExtKeyUsageClientAuth {\n\t\t\tusages = append(usages, \"client\")\n\t\t\tcontinue\n\t\t}\n\t\tif curr == x509.ExtKeyUsageServerAuth {\n\t\t\tusages = append(usages, \"serving\")\n\t\t\tcontinue\n\t\t}\n\n\t\tusages = append(usages, fmt.Sprintf(\"%d\", curr))\n\t}\n\n\tvalidServingNames := []string{}\n\tfor _, ip := range certificate.IPAddresses {\n\t\tvalidServingNames = append(validServingNames, ip.String())\n\t}\n\tvalidServingNames = append(validServingNames, certificate.DNSNames...)\n\tservingString := \"\"\n\tif len(validServingNames) \u003e 0 {\n\t\tservingString = fmt.Sprintf(\" validServingFor=[%s]\", strings.Join(validServingNames, \",\"))\n\t}\n\n\tgroupString := \"\"\n\tif len(certificate.Subject.Organization) \u003e 0 {\n\t\tgroupString = fmt.Sprintf(\" groups=[%s]\", strings.Join(certificate.Subject.Organization, \",\"))\n\t}\n\n\treturn fmt.Sprintf(\"%q [%s]%s%s issuer=%q (%v to %v (now=%v))\", humanName, strings.Join(usages, \",\"), groupString, servingString, signerHumanName, certificate.NotBefore.UTC(), certificate.NotAfter.UTC(),\n\t\ttime.Now().UTC())\n}","line":{"from":26,"to":66}} {"id":100017931,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/config.go","code":"func init() {\n\tinstall.Install(cfgScheme)\n}","line":{"from":39,"to":41}} {"id":100017932,"name":"ReadEgressSelectorConfiguration","signature":"func ReadEgressSelectorConfiguration(configFilePath string) (*apiserver.EgressSelectorConfiguration, error)","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/config.go","code":"// ReadEgressSelectorConfiguration reads the egress selector configuration at the specified path.\n// It returns the loaded egress selector configuration if the input file aligns with the required syntax.\n// If it does not align with the provided syntax, it returns a default configuration which should function as a no-op.\n// It does this by returning a nil configuration, which preserves backward compatibility.\n// This works because prior to this there was no egress selector configuration.\n// It returns an error if the file did not exist.\nfunc ReadEgressSelectorConfiguration(configFilePath string) (*apiserver.EgressSelectorConfiguration, error) {\n\tif configFilePath == \"\" {\n\t\treturn nil, nil\n\t}\n\t// a file was provided, so we just read it.\n\tdata, err := ioutil.ReadFile(configFilePath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to read egress selector configuration from %q [%v]\", configFilePath, err)\n\t}\n\tvar decodedConfig v1beta1.EgressSelectorConfiguration\n\terr = yaml.Unmarshal(data, \u0026decodedConfig)\n\tif err != nil {\n\t\t// we got an error where the decode wasn't related to a missing type\n\t\treturn nil, err\n\t}\n\tif decodedConfig.Kind != \"EgressSelectorConfiguration\" {\n\t\treturn nil, fmt.Errorf(\"invalid service configuration object %q\", decodedConfig.Kind)\n\t}\n\tinternalConfig := \u0026apiserver.EgressSelectorConfiguration{}\n\tif err := cfgScheme.Convert(\u0026decodedConfig, internalConfig, nil); err != nil {\n\t\t// we got an error where the decode wasn't related to a missing type\n\t\treturn nil, err\n\t}\n\treturn internalConfig, nil\n}","line":{"from":43,"to":73}} {"id":100017933,"name":"ValidateEgressSelectorConfiguration","signature":"func ValidateEgressSelectorConfiguration(config *apiserver.EgressSelectorConfiguration) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/config.go","code":"// ValidateEgressSelectorConfiguration checks the apiserver.EgressSelectorConfiguration for\n// common configuration errors. It will return error for problems such as configuring mtls/cert\n// settings for protocol which do not support security. It will also try to catch errors such as\n// incorrect file paths. It will return nil if it does not find anything wrong.\nfunc ValidateEgressSelectorConfiguration(config *apiserver.EgressSelectorConfiguration) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif config == nil {\n\t\treturn allErrs // Treating a nil configuration as valid\n\t}\n\tfor _, service := range config.EgressSelections {\n\t\tfldPath := field.NewPath(\"service\", \"connection\")\n\t\tswitch service.Connection.ProxyProtocol {\n\t\tcase apiserver.ProtocolDirect:\n\t\t\tallErrs = append(allErrs, validateDirectConnection(service.Connection, fldPath)...)\n\t\tcase apiserver.ProtocolHTTPConnect:\n\t\t\tallErrs = append(allErrs, validateHTTPConnectTransport(service.Connection.Transport, fldPath)...)\n\t\tcase apiserver.ProtocolGRPC:\n\t\t\tallErrs = append(allErrs, validateGRPCTransport(service.Connection.Transport, fldPath)...)\n\t\tdefault:\n\t\t\tallErrs = append(allErrs, field.NotSupported(\n\t\t\t\tfldPath.Child(\"protocol\"),\n\t\t\t\tservice.Connection.ProxyProtocol,\n\t\t\t\t[]string{\n\t\t\t\t\tstring(apiserver.ProtocolDirect),\n\t\t\t\t\tstring(apiserver.ProtocolHTTPConnect),\n\t\t\t\t\tstring(apiserver.ProtocolGRPC),\n\t\t\t\t}))\n\t\t}\n\t}\n\n\tseen := sets.String{}\n\tfor i, service := range config.EgressSelections {\n\t\tcanonicalName := strings.ToLower(service.Name)\n\t\tfldPath := field.NewPath(\"service\", \"connection\")\n\t\t// no duplicate check\n\t\tif seen.Has(canonicalName) {\n\t\t\tallErrs = append(allErrs, field.Duplicate(fldPath.Index(i), canonicalName))\n\t\t\tcontinue\n\t\t}\n\t\tseen.Insert(canonicalName)\n\n\t\tif !validEgressSelectorNames.Has(canonicalName) {\n\t\t\tallErrs = append(allErrs, field.NotSupported(fldPath, canonicalName, validEgressSelectorNames.List()))\n\t\t\tcontinue\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":75,"to":123}} {"id":100017934,"name":"validateHTTPConnectTransport","signature":"func validateHTTPConnectTransport(transport *apiserver.Transport, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/config.go","code":"func validateHTTPConnectTransport(transport *apiserver.Transport, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif transport == nil {\n\t\tallErrs = append(allErrs, field.Required(\n\t\t\tfldPath.Child(\"transport\"),\n\t\t\t\"transport must be set for HTTPConnect\"))\n\t\treturn allErrs\n\t}\n\n\tif transport.TCP != nil \u0026\u0026 transport.UDS != nil {\n\t\tallErrs = append(allErrs, field.Invalid(\n\t\t\tfldPath.Child(\"tcp\"),\n\t\t\ttransport.TCP,\n\t\t\t\"TCP and UDS cannot both be set\"))\n\t} else if transport.TCP == nil \u0026\u0026 transport.UDS == nil {\n\t\tallErrs = append(allErrs, field.Required(\n\t\t\tfldPath.Child(\"tcp\"),\n\t\t\t\"One of TCP or UDS must be set\"))\n\t} else if transport.TCP != nil {\n\t\tallErrs = append(allErrs, validateTCPConnection(transport.TCP, fldPath)...)\n\t} else if transport.UDS != nil {\n\t\tallErrs = append(allErrs, validateUDSConnection(transport.UDS, fldPath)...)\n\t}\n\treturn allErrs\n}","line":{"from":125,"to":149}} {"id":100017935,"name":"validateGRPCTransport","signature":"func validateGRPCTransport(transport *apiserver.Transport, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/config.go","code":"func validateGRPCTransport(transport *apiserver.Transport, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif transport == nil {\n\t\tallErrs = append(allErrs, field.Required(\n\t\t\tfldPath.Child(\"transport\"),\n\t\t\t\"transport must be set for GRPC\"))\n\t\treturn allErrs\n\t}\n\n\tif transport.UDS != nil {\n\t\tallErrs = append(allErrs, validateUDSConnection(transport.UDS, fldPath)...)\n\t} else {\n\t\tallErrs = append(allErrs, field.Required(\n\t\t\tfldPath.Child(\"uds\"),\n\t\t\t\"UDS must be set with GRPC\"))\n\t}\n\treturn allErrs\n}","line":{"from":151,"to":168}} {"id":100017936,"name":"validateDirectConnection","signature":"func validateDirectConnection(connection apiserver.Connection, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/config.go","code":"func validateDirectConnection(connection apiserver.Connection, fldPath *field.Path) field.ErrorList {\n\tif connection.Transport != nil {\n\t\treturn field.ErrorList{field.Invalid(\n\t\t\tfldPath.Child(\"transport\"),\n\t\t\t\"direct\",\n\t\t\t\"Transport config should be absent for direct connect\"),\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":170,"to":180}} {"id":100017937,"name":"validateUDSConnection","signature":"func validateUDSConnection(udsConfig *apiserver.UDSTransport, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/config.go","code":"func validateUDSConnection(udsConfig *apiserver.UDSTransport, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif udsConfig.UDSName == \"\" {\n\t\tallErrs = append(allErrs, field.Invalid(\n\t\t\tfldPath.Child(\"udsName\"),\n\t\t\t\"nil\",\n\t\t\t\"UDSName should be present for UDS connections\"))\n\t}\n\treturn allErrs\n}","line":{"from":182,"to":191}} {"id":100017938,"name":"validateTCPConnection","signature":"func validateTCPConnection(tcpConfig *apiserver.TCPTransport, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/config.go","code":"func validateTCPConnection(tcpConfig *apiserver.TCPTransport, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif strings.HasPrefix(tcpConfig.URL, \"http://\") {\n\t\tif tcpConfig.TLSConfig != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(\n\t\t\t\tfldPath.Child(\"tlsConfig\"),\n\t\t\t\t\"nil\",\n\t\t\t\t\"TLSConfig config should not be present when using HTTP\"))\n\t\t}\n\t} else if strings.HasPrefix(tcpConfig.URL, \"https://\") {\n\t\treturn validateTLSConfig(tcpConfig.TLSConfig, fldPath)\n\t} else {\n\t\tallErrs = append(allErrs, field.Invalid(\n\t\t\tfldPath.Child(\"url\"),\n\t\t\ttcpConfig.URL,\n\t\t\t\"supported connection protocols are http:// and https://\"))\n\t}\n\treturn allErrs\n}","line":{"from":193,"to":212}} {"id":100017939,"name":"validateTLSConfig","signature":"func validateTLSConfig(tlsConfig *apiserver.TLSConfig, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/config.go","code":"func validateTLSConfig(tlsConfig *apiserver.TLSConfig, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif tlsConfig == nil {\n\t\tallErrs = append(allErrs, field.Required(\n\t\t\tfldPath.Child(\"tlsConfig\"),\n\t\t\t\"TLSConfig must be present when using HTTPS\"))\n\t\treturn allErrs\n\t}\n\tif tlsConfig.CABundle != \"\" {\n\t\tif exists, err := path.Exists(path.CheckFollowSymlink, tlsConfig.CABundle); !exists || err != nil {\n\t\t\tallErrs = append(allErrs, field.Invalid(\n\t\t\t\tfldPath.Child(\"tlsConfig\", \"caBundle\"),\n\t\t\t\ttlsConfig.CABundle,\n\t\t\t\t\"TLS config ca bundle does not exist\"))\n\t\t}\n\t}\n\tif tlsConfig.ClientCert == \"\" {\n\t\tallErrs = append(allErrs, field.Invalid(\n\t\t\tfldPath.Child(\"tlsConfig\", \"clientCert\"),\n\t\t\t\"nil\",\n\t\t\t\"Using TLS requires clientCert\"))\n\t} else if exists, err := path.Exists(path.CheckFollowSymlink, tlsConfig.ClientCert); !exists || err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(\n\t\t\tfldPath.Child(\"tlsConfig\", \"clientCert\"),\n\t\t\ttlsConfig.ClientCert,\n\t\t\t\"TLS client cert does not exist\"))\n\t}\n\tif tlsConfig.ClientKey == \"\" {\n\t\tallErrs = append(allErrs, field.Invalid(\n\t\t\tfldPath.Child(\"tlsConfig\", \"clientKey\"),\n\t\t\t\"nil\",\n\t\t\t\"Using TLS requires requires clientKey\"))\n\t} else if exists, err := path.Exists(path.CheckFollowSymlink, tlsConfig.ClientKey); !exists || err != nil {\n\t\tallErrs = append(allErrs, field.Invalid(\n\t\t\tfldPath.Child(\"tlsConfig\", \"clientKey\"),\n\t\t\ttlsConfig.ClientKey,\n\t\t\t\"TLS client key does not exist\"))\n\t}\n\treturn allErrs\n}","line":{"from":214,"to":254}} {"id":100017940,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/egress_selector.go","code":"func init() {\n\tclient.Metrics.RegisterMetrics(legacyregistry.Registerer())\n}","line":{"from":47,"to":49}} {"id":100017941,"name":"String","signature":"func (s EgressType) String() string","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/egress_selector.go","code":"// String returns the canonical string representation of the egress type\nfunc (s EgressType) String() string {\n\tswitch s {\n\tcase ControlPlane:\n\t\treturn \"controlplane\"\n\tcase Etcd:\n\t\treturn \"etcd\"\n\tcase Cluster:\n\t\treturn \"cluster\"\n\tdefault:\n\t\treturn \"invalid\"\n\t}\n}","line":{"from":80,"to":92}} {"id":100017942,"name":"AsNetworkContext","signature":"func (s EgressType) AsNetworkContext() NetworkContext","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/egress_selector.go","code":"// AsNetworkContext is a helper function to make it easy to get the basic NetworkContext objects.\nfunc (s EgressType) AsNetworkContext() NetworkContext {\n\treturn NetworkContext{EgressSelectionName: s}\n}","line":{"from":94,"to":97}} {"id":100017943,"name":"lookupServiceName","signature":"func lookupServiceName(name string) (EgressType, error)","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/egress_selector.go","code":"func lookupServiceName(name string) (EgressType, error) {\n\tswitch strings.ToLower(name) {\n\tcase \"controlplane\":\n\t\treturn ControlPlane, nil\n\tcase \"etcd\":\n\t\treturn Etcd, nil\n\tcase \"cluster\":\n\t\treturn Cluster, nil\n\t}\n\treturn -1, fmt.Errorf(\"unrecognized service name %s\", name)\n}","line":{"from":99,"to":109}} {"id":100017944,"name":"tunnelHTTPConnect","signature":"func tunnelHTTPConnect(proxyConn net.Conn, proxyAddress, addr string) (net.Conn, error)","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/egress_selector.go","code":"func tunnelHTTPConnect(proxyConn net.Conn, proxyAddress, addr string) (net.Conn, error) {\n\tfmt.Fprintf(proxyConn, \"CONNECT %s HTTP/1.1\\r\\nHost: %s\\r\\n\\r\\n\", addr, \"127.0.0.1\")\n\tbr := bufio.NewReader(proxyConn)\n\tres, err := http.ReadResponse(br, nil)\n\tif err != nil {\n\t\tproxyConn.Close()\n\t\treturn nil, fmt.Errorf(\"reading HTTP response from CONNECT to %s via proxy %s failed: %v\",\n\t\t\taddr, proxyAddress, err)\n\t}\n\tif res.StatusCode != 200 {\n\t\tproxyConn.Close()\n\t\treturn nil, fmt.Errorf(\"proxy error from %s while dialing %s, code %d: %v\",\n\t\t\tproxyAddress, addr, res.StatusCode, res.Status)\n\t}\n\n\t// It's safe to discard the bufio.Reader here and return the\n\t// original TCP conn directly because we only use this for\n\t// TLS, and in TLS the client speaks first, so we know there's\n\t// no unbuffered data. But we can double-check.\n\tif br.Buffered() \u003e 0 {\n\t\tproxyConn.Close()\n\t\treturn nil, fmt.Errorf(\"unexpected %d bytes of buffered data from CONNECT proxy %q\",\n\t\t\tbr.Buffered(), proxyAddress)\n\t}\n\treturn proxyConn, nil\n}","line":{"from":111,"to":136}} {"id":100017945,"name":"proxy","signature":"func (t *httpConnectProxier) proxy(ctx context.Context, addr string) (net.Conn, error)","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/egress_selector.go","code":"func (t *httpConnectProxier) proxy(ctx context.Context, addr string) (net.Conn, error) {\n\treturn tunnelHTTPConnect(t.conn, t.proxyAddress, addr)\n}","line":{"from":150,"to":152}} {"id":100017946,"name":"proxy","signature":"func (g *grpcProxier) proxy(ctx context.Context, addr string) (net.Conn, error)","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/egress_selector.go","code":"func (g *grpcProxier) proxy(ctx context.Context, addr string) (net.Conn, error) {\n\treturn g.tunnel.DialContext(ctx, \"tcp\", addr)\n}","line":{"from":160,"to":162}} {"id":100017947,"name":"connect","signature":"func (t *tcpHTTPConnectConnector) connect(ctx context.Context) (proxier, error)","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/egress_selector.go","code":"func (t *tcpHTTPConnectConnector) connect(ctx context.Context) (proxier, error) {\n\td := tls.Dialer{\n\t\tConfig: t.tlsConfig,\n\t}\n\tconn, err := d.DialContext(ctx, \"tcp\", t.proxyAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026httpConnectProxier{conn: conn, proxyAddress: t.proxyAddress}, nil\n}","line":{"from":179,"to":188}} {"id":100017948,"name":"connect","signature":"func (u *udsHTTPConnectConnector) connect(ctx context.Context) (proxier, error)","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/egress_selector.go","code":"func (u *udsHTTPConnectConnector) connect(ctx context.Context) (proxier, error) {\n\tvar d net.Dialer\n\tconn, err := d.DialContext(ctx, \"unix\", u.udsName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026httpConnectProxier{conn: conn, proxyAddress: u.udsName}, nil\n}","line":{"from":194,"to":201}} {"id":100017949,"name":"connect","signature":"func (u *udsGRPCConnector) connect(_ context.Context) (proxier, error)","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/egress_selector.go","code":"// connect establishes a connection to a proxy over gRPC.\n// TODO At the moment, it does not use the provided context.\nfunc (u *udsGRPCConnector) connect(_ context.Context) (proxier, error) {\n\tudsName := u.udsName\n\tdialOption := grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) {\n\t\tvar d net.Dialer\n\t\tc, err := d.DialContext(ctx, \"unix\", udsName)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"failed to create connection to uds name %s, error: %v\", udsName, err)\n\t\t}\n\t\treturn c, err\n\t})\n\n\t// CreateSingleUseGrpcTunnel() unfortunately couples dial and connection contexts. Because of that,\n\t// we cannot use ctx just for dialing and control the connection lifetime separately.\n\t// See https://github.com/kubernetes-sigs/apiserver-network-proxy/issues/357.\n\ttunnelCtx := context.TODO()\n\ttunnel, err := client.CreateSingleUseGrpcTunnel(tunnelCtx, udsName, dialOption,\n\t\tgrpc.WithBlock(),\n\t\tgrpc.WithReturnConnectionError(),\n\t\tgrpc.WithTimeout(30*time.Second), // matches http.DefaultTransport dial timeout\n\t\tgrpc.WithTransportCredentials(insecure.NewCredentials()))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026grpcProxier{tunnel: tunnel}, nil\n}","line":{"from":207,"to":233}} {"id":100017950,"name":"createDialer","signature":"func (d *dialerCreator) createDialer() utilnet.DialFunc","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/egress_selector.go","code":"func (d *dialerCreator) createDialer() utilnet.DialFunc {\n\tif d.direct {\n\t\treturn directDialer\n\t}\n\treturn func(ctx context.Context, network, addr string) (net.Conn, error) {\n\t\tctx, span := tracing.Start(ctx, fmt.Sprintf(\"Proxy via %s protocol over %s\", d.options.protocol, d.options.transport), attribute.String(\"address\", addr))\n\t\tdefer span.End(500 * time.Millisecond)\n\t\tstart := egressmetrics.Metrics.Clock().Now()\n\t\tegressmetrics.Metrics.ObserveDialStart(d.options.protocol, d.options.transport)\n\t\tproxier, err := d.connector.connect(ctx)\n\t\tif err != nil {\n\t\t\tegressmetrics.Metrics.ObserveDialFailure(d.options.protocol, d.options.transport, egressmetrics.StageConnect)\n\t\t\treturn nil, err\n\t\t}\n\t\tconn, err := proxier.proxy(ctx, addr)\n\t\tif err != nil {\n\t\t\tegressmetrics.Metrics.ObserveDialFailure(d.options.protocol, d.options.transport, egressmetrics.StageProxy)\n\t\t\treturn nil, err\n\t\t}\n\t\tegressmetrics.Metrics.ObserveDialLatency(egressmetrics.Metrics.Clock().Now().Sub(start), d.options.protocol, d.options.transport)\n\t\treturn conn, nil\n\t}\n}","line":{"from":246,"to":268}} {"id":100017951,"name":"getTLSConfig","signature":"func getTLSConfig(t *apiserver.TLSConfig) (*tls.Config, error)","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/egress_selector.go","code":"func getTLSConfig(t *apiserver.TLSConfig) (*tls.Config, error) {\n\tclientCert := t.ClientCert\n\tclientKey := t.ClientKey\n\tcaCert := t.CABundle\n\tclientCerts, err := tls.LoadX509KeyPair(clientCert, clientKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read key pair %s \u0026 %s, got %v\", clientCert, clientKey, err)\n\t}\n\tcertPool := x509.NewCertPool()\n\tif caCert != \"\" {\n\t\tcertBytes, err := ioutil.ReadFile(caCert)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to read cert file %s, got %v\", caCert, err)\n\t\t}\n\t\tok := certPool.AppendCertsFromPEM(certBytes)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"failed to append CA cert to the cert pool\")\n\t\t}\n\t} else {\n\t\t// Use host's root CA set instead of providing our own\n\t\tcertPool = nil\n\t}\n\treturn \u0026tls.Config{\n\t\tCertificates: []tls.Certificate{clientCerts},\n\t\tRootCAs: certPool,\n\t}, nil\n}","line":{"from":270,"to":296}} {"id":100017952,"name":"getProxyAddress","signature":"func getProxyAddress(urlString string) (string, error)","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/egress_selector.go","code":"func getProxyAddress(urlString string) (string, error) {\n\tproxyURL, err := url.Parse(urlString)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"invalid proxy server url %q: %v\", urlString, err)\n\t}\n\treturn proxyURL.Host, nil\n}","line":{"from":298,"to":304}} {"id":100017953,"name":"connectionToDialerCreator","signature":"func connectionToDialerCreator(c apiserver.Connection) (*dialerCreator, error)","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/egress_selector.go","code":"func connectionToDialerCreator(c apiserver.Connection) (*dialerCreator, error) {\n\tswitch c.ProxyProtocol {\n\n\tcase apiserver.ProtocolHTTPConnect:\n\t\tif c.Transport.UDS != nil {\n\t\t\treturn \u0026dialerCreator{\n\t\t\t\tconnector: \u0026udsHTTPConnectConnector{\n\t\t\t\t\tudsName: c.Transport.UDS.UDSName,\n\t\t\t\t},\n\t\t\t\toptions: metricsOptions{\n\t\t\t\t\ttransport: egressmetrics.TransportUDS,\n\t\t\t\t\tprotocol: egressmetrics.ProtocolHTTPConnect,\n\t\t\t\t},\n\t\t\t}, nil\n\t\t} else if c.Transport.TCP != nil {\n\t\t\ttlsConfig, err := getTLSConfig(c.Transport.TCP.TLSConfig)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tproxyAddress, err := getProxyAddress(c.Transport.TCP.URL)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn \u0026dialerCreator{\n\t\t\t\tconnector: \u0026tcpHTTPConnectConnector{\n\t\t\t\t\ttlsConfig: tlsConfig,\n\t\t\t\t\tproxyAddress: proxyAddress,\n\t\t\t\t},\n\t\t\t\toptions: metricsOptions{\n\t\t\t\t\ttransport: egressmetrics.TransportTCP,\n\t\t\t\t\tprotocol: egressmetrics.ProtocolHTTPConnect,\n\t\t\t\t},\n\t\t\t}, nil\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"Either a TCP or UDS transport must be specified\")\n\t\t}\n\tcase apiserver.ProtocolGRPC:\n\t\tif c.Transport.UDS != nil {\n\t\t\treturn \u0026dialerCreator{\n\t\t\t\tconnector: \u0026udsGRPCConnector{\n\t\t\t\t\tudsName: c.Transport.UDS.UDSName,\n\t\t\t\t},\n\t\t\t\toptions: metricsOptions{\n\t\t\t\t\ttransport: egressmetrics.TransportUDS,\n\t\t\t\t\tprotocol: egressmetrics.ProtocolGRPC,\n\t\t\t\t},\n\t\t\t}, nil\n\t\t}\n\t\treturn nil, fmt.Errorf(\"UDS transport must be specified for GRPC\")\n\tcase apiserver.ProtocolDirect:\n\t\treturn \u0026dialerCreator{direct: true}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unrecognized service connection protocol %q\", c.ProxyProtocol)\n\t}\n\n}","line":{"from":306,"to":361}} {"id":100017954,"name":"NewEgressSelector","signature":"func NewEgressSelector(config *apiserver.EgressSelectorConfiguration) (*EgressSelector, error)","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/egress_selector.go","code":"// NewEgressSelector configures lookup mechanism for Lookup.\n// It does so based on a EgressSelectorConfiguration which was read at startup.\nfunc NewEgressSelector(config *apiserver.EgressSelectorConfiguration) (*EgressSelector, error) {\n\tif config == nil || config.EgressSelections == nil {\n\t\t// No Connection Services configured, leaving the serviceMap empty, will return default dialer.\n\t\treturn nil, nil\n\t}\n\tcs := \u0026EgressSelector{\n\t\tegressToDialer: make(map[EgressType]utilnet.DialFunc),\n\t}\n\tfor _, service := range config.EgressSelections {\n\t\tname, err := lookupServiceName(service.Name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdialerCreator, err := connectionToDialerCreator(service.Connection)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to create dialer for egressSelection %q: %v\", name, err)\n\t\t}\n\t\tcs.egressToDialer[name] = dialerCreator.createDialer()\n\t}\n\treturn cs, nil\n}","line":{"from":363,"to":385}} {"id":100017955,"name":"NewEgressSelectorWithMap","signature":"func NewEgressSelectorWithMap(m map[EgressType]utilnet.DialFunc) *EgressSelector","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/egress_selector.go","code":"// NewEgressSelectorWithMap returns a EgressSelector with the supplied EgressType to DialFunc map.\nfunc NewEgressSelectorWithMap(m map[EgressType]utilnet.DialFunc) *EgressSelector {\n\tif m == nil {\n\t\tm = make(map[EgressType]utilnet.DialFunc)\n\t}\n\treturn \u0026EgressSelector{\n\t\tegressToDialer: m,\n\t}\n}","line":{"from":387,"to":395}} {"id":100017956,"name":"Lookup","signature":"func (cs *EgressSelector) Lookup(networkContext NetworkContext) (utilnet.DialFunc, error)","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/egress_selector.go","code":"// Lookup gets the dialer function for the network context.\n// This is configured for the Kubernetes API Server at startup.\nfunc (cs *EgressSelector) Lookup(networkContext NetworkContext) (utilnet.DialFunc, error) {\n\tif cs.egressToDialer == nil {\n\t\t// The round trip wrapper will over-ride the dialContext method appropriately\n\t\treturn nil, nil\n\t}\n\n\treturn cs.egressToDialer[networkContext.EgressSelectionName], nil\n}","line":{"from":397,"to":406}} {"id":100017957,"name":"newDialMetrics","signature":"func newDialMetrics() *DialMetrics","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/metrics/metrics.go","code":"// newDialMetrics create a new DialMetrics, configured with default metric names.\nfunc newDialMetrics() *DialMetrics {\n\tstarts := metrics.NewCounterVec(\n\t\t\u0026metrics.CounterOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: \"dial_start_total\",\n\t\t\tHelp: \"Dial starts, labeled by the protocol (http-connect or grpc) and transport (tcp or uds).\",\n\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t},\n\t\t[]string{\"protocol\", \"transport\"},\n\t)\n\n\tlatencies := metrics.NewHistogramVec(\n\t\t\u0026metrics.HistogramOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: \"dial_duration_seconds\",\n\t\t\tHelp: \"Dial latency histogram in seconds, labeled by the protocol (http-connect or grpc), transport (tcp or uds)\",\n\t\t\tBuckets: latencyBuckets,\n\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t},\n\t\t[]string{\"protocol\", \"transport\"},\n\t)\n\n\tfailures := metrics.NewCounterVec(\n\t\t\u0026metrics.CounterOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: \"dial_failure_count\",\n\t\t\tHelp: \"Dial failure count, labeled by the protocol (http-connect or grpc), transport (tcp or uds), and stage (connect or proxy). The stage indicates at which stage the dial failed\",\n\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t},\n\t\t[]string{\"protocol\", \"transport\", \"stage\"},\n\t)\n\n\tlegacyregistry.MustRegister(starts)\n\tlegacyregistry.MustRegister(latencies)\n\tlegacyregistry.MustRegister(failures)\n\treturn \u0026DialMetrics{starts: starts, latencies: latencies, failures: failures, clock: clock.RealClock{}}\n}","line":{"from":61,"to":101}} {"id":100017958,"name":"Clock","signature":"func (m *DialMetrics) Clock() clock.Clock","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/metrics/metrics.go","code":"// Clock returns the clock.\nfunc (m *DialMetrics) Clock() clock.Clock {\n\treturn m.clock\n}","line":{"from":103,"to":106}} {"id":100017959,"name":"SetClock","signature":"func (m *DialMetrics) SetClock(c clock.Clock)","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/metrics/metrics.go","code":"// SetClock sets the clock.\nfunc (m *DialMetrics) SetClock(c clock.Clock) {\n\tm.clock = c\n}","line":{"from":108,"to":111}} {"id":100017960,"name":"Reset","signature":"func (m *DialMetrics) Reset()","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/metrics/metrics.go","code":"// Reset resets the metrics.\nfunc (m *DialMetrics) Reset() {\n\tm.starts.Reset()\n\tm.latencies.Reset()\n\tm.failures.Reset()\n}","line":{"from":113,"to":118}} {"id":100017961,"name":"ObserveDialStart","signature":"func (m *DialMetrics) ObserveDialStart(protocol, transport string)","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/metrics/metrics.go","code":"// ObserveDialStart records the start of a dial attempt, labeled by protocol, transport.\nfunc (m *DialMetrics) ObserveDialStart(protocol, transport string) {\n\tm.starts.WithLabelValues(protocol, transport).Inc()\n}","line":{"from":120,"to":123}} {"id":100017962,"name":"ObserveDialLatency","signature":"func (m *DialMetrics) ObserveDialLatency(elapsed time.Duration, protocol, transport string)","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/metrics/metrics.go","code":"// ObserveDialLatency records the latency of a dial, labeled by protocol, transport.\nfunc (m *DialMetrics) ObserveDialLatency(elapsed time.Duration, protocol, transport string) {\n\tm.latencies.WithLabelValues(protocol, transport).Observe(elapsed.Seconds())\n}","line":{"from":125,"to":128}} {"id":100017963,"name":"ObserveDialFailure","signature":"func (m *DialMetrics) ObserveDialFailure(protocol, transport, stage string)","file":"staging/src/k8s.io/apiserver/pkg/server/egressselector/metrics/metrics.go","code":"// ObserveDialFailure records a failed dial, labeled by protocol, transport, and the stage the dial failed at.\nfunc (m *DialMetrics) ObserveDialFailure(protocol, transport, stage string) {\n\tm.failures.WithLabelValues(protocol, transport, stage).Inc()\n}","line":{"from":130,"to":133}} {"id":100017964,"name":"WithContentType","signature":"func WithContentType(handler http.Handler, contentType string) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/server/filters/content_type.go","code":"// WithContentType sets both the Content-Type and the X-Content-Type-Options (nosniff) header\nfunc WithContentType(handler http.Handler, contentType string) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", contentType)\n\t\tw.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\t\thandler.ServeHTTP(w, r)\n\t})\n}","line":{"from":21,"to":28}} {"id":100017965,"name":"WithCORS","signature":"func WithCORS(handler http.Handler, allowedOriginPatterns []string, allowedMethods []string, allowedHeaders []string, exposedHeaders []string, allowCredentials string) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/server/filters/cors.go","code":"// WithCORS is a simple CORS implementation that wraps an http Handler.\n// Pass nil for allowedMethods and allowedHeaders to use the defaults. If allowedOriginPatterns\n// is empty or nil, no CORS support is installed.\nfunc WithCORS(handler http.Handler, allowedOriginPatterns []string, allowedMethods []string, allowedHeaders []string, exposedHeaders []string, allowCredentials string) http.Handler {\n\tif len(allowedOriginPatterns) == 0 {\n\t\treturn handler\n\t}\n\tallowedOriginPatternsREs := allowedOriginRegexps(allowedOriginPatterns)\n\n\t// Set defaults for methods and headers if nothing was passed\n\tif allowedMethods == nil {\n\t\tallowedMethods = []string{\"POST\", \"GET\", \"OPTIONS\", \"PUT\", \"DELETE\", \"PATCH\"}\n\t}\n\tallowMethodsResponseHeader := strings.Join(allowedMethods, \", \")\n\n\tif allowedHeaders == nil {\n\t\tallowedHeaders = []string{\"Content-Type\", \"Content-Length\", \"Accept-Encoding\", \"X-CSRF-Token\", \"Authorization\", \"X-Requested-With\", \"If-Modified-Since\"}\n\t}\n\tallowHeadersResponseHeader := strings.Join(allowedHeaders, \", \")\n\n\tif exposedHeaders == nil {\n\t\texposedHeaders = []string{\"Date\"}\n\t}\n\texposeHeadersResponseHeader := strings.Join(exposedHeaders, \", \")\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\torigin := req.Header.Get(\"Origin\")\n\t\tif origin == \"\" {\n\t\t\thandler.ServeHTTP(w, req)\n\t\t\treturn\n\t\t}\n\t\tif !isOriginAllowed(origin, allowedOriginPatternsREs) {\n\t\t\thandler.ServeHTTP(w, req)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\tw.Header().Set(\"Access-Control-Allow-Methods\", allowMethodsResponseHeader)\n\t\tw.Header().Set(\"Access-Control-Allow-Headers\", allowHeadersResponseHeader)\n\t\tw.Header().Set(\"Access-Control-Expose-Headers\", exposeHeadersResponseHeader)\n\t\tw.Header().Set(\"Access-Control-Allow-Credentials\", allowCredentials)\n\n\t\t// Stop here if its a preflight OPTIONS request\n\t\tif req.Method == \"OPTIONS\" {\n\t\t\tw.WriteHeader(http.StatusNoContent)\n\t\t\treturn\n\t\t}\n\n\t\t// Dispatch to the next handler\n\t\thandler.ServeHTTP(w, req)\n\t})\n}","line":{"from":33,"to":84}} {"id":100017966,"name":"isOriginAllowed","signature":"func isOriginAllowed(originHeader string, allowedOriginPatternsREs []*regexp.Regexp) bool","file":"staging/src/k8s.io/apiserver/pkg/server/filters/cors.go","code":"// isOriginAllowed returns true if the given origin header in the\n// request is allowed CORS.\n//\n// From https://www.rfc-editor.org/rfc/rfc6454#page-13\n//\n//\t a) The origin header can contain host and/or port\n//\t\t\tserialized-origin = scheme \"://\" host [ \":\" port ]\n//\n//\t b) In some cases, a number of origins contribute to causing the user\n//\t agents to issue an HTTP request. In those cases, the user agent MAY\n//\t list all the origins in the Origin header field. For example, if the\n//\t HTTP request was initially issued by one origin but then later\n//\t redirected by another origin, the user agent MAY inform the server\n//\t that two origins were involved in causing the user agent to issue the\n//\t request\n//\t\t\torigin-list = serialized-origin *( SP serialized-origin )\nfunc isOriginAllowed(originHeader string, allowedOriginPatternsREs []*regexp.Regexp) bool {\n\tfor _, re := range allowedOriginPatternsREs {\n\t\tif re.MatchString(originHeader) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":86,"to":109}} {"id":100017967,"name":"allowedOriginRegexps","signature":"func allowedOriginRegexps(allowedOrigins []string) []*regexp.Regexp","file":"staging/src/k8s.io/apiserver/pkg/server/filters/cors.go","code":"func allowedOriginRegexps(allowedOrigins []string) []*regexp.Regexp {\n\tres, err := compileRegexps(allowedOrigins)\n\tif err != nil {\n\t\tklog.Fatalf(\"Invalid CORS allowed origin, --cors-allowed-origins flag was set to %v - %v\", strings.Join(allowedOrigins, \",\"), err)\n\t}\n\treturn res\n}","line":{"from":111,"to":117}} {"id":100017968,"name":"compileRegexps","signature":"func compileRegexps(regexpStrings []string) ([]*regexp.Regexp, error)","file":"staging/src/k8s.io/apiserver/pkg/server/filters/cors.go","code":"// Takes a list of strings and compiles them into a list of regular expressions\nfunc compileRegexps(regexpStrings []string) ([]*regexp.Regexp, error) {\n\tregexps := []*regexp.Regexp{}\n\tfor _, regexpStr := range regexpStrings {\n\t\tr, err := regexp.Compile(regexpStr)\n\t\tif err != nil {\n\t\t\treturn []*regexp.Regexp{}, err\n\t\t}\n\t\tregexps = append(regexps, r)\n\t}\n\treturn regexps, nil\n}","line":{"from":119,"to":130}} {"id":100017969,"name":"WithProbabilisticGoaway","signature":"func WithProbabilisticGoaway(inner http.Handler, chance float64) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/server/filters/goaway.go","code":"// WithProbabilisticGoaway returns an http.Handler that send GOAWAY probabilistically\n// according to the given chance for HTTP2 requests. After client receive GOAWAY,\n// the in-flight long-running requests will not be influenced, and the new requests\n// will use a new TCP connection to re-balancing to another server behind the load balance.\nfunc WithProbabilisticGoaway(inner http.Handler, chance float64) http.Handler {\n\treturn \u0026goaway{\n\t\thandler: inner,\n\t\tdecider: \u0026probabilisticGoawayDecider{\n\t\t\tchance: chance,\n\t\t\tnext: func() float64 {\n\t\t\t\trnd := randPool.Get().(*rand.Rand)\n\t\t\t\tret := rnd.Float64()\n\t\t\t\trandPool.Put(rnd)\n\t\t\t\treturn ret\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":40,"to":57}} {"id":100017970,"name":"ServeHTTP","signature":"func (h *goaway) ServeHTTP(w http.ResponseWriter, r *http.Request)","file":"staging/src/k8s.io/apiserver/pkg/server/filters/goaway.go","code":"// ServeHTTP implement HTTP handler\nfunc (h *goaway) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tif r.Proto == \"HTTP/2.0\" \u0026\u0026 h.decider.Goaway(r) {\n\t\t// Send a GOAWAY and tear down the TCP connection when idle.\n\t\tw.Header().Set(\"Connection\", \"close\")\n\t}\n\n\th.handler.ServeHTTP(w, r)\n}","line":{"from":65,"to":73}} {"id":100017971,"name":"Goaway","signature":"func (p *probabilisticGoawayDecider) Goaway(r *http.Request) bool","file":"staging/src/k8s.io/apiserver/pkg/server/filters/goaway.go","code":"// Goaway implement GoawayDecider\nfunc (p *probabilisticGoawayDecider) Goaway(r *http.Request) bool {\n\treturn p.next() \u003c p.chance\n}","line":{"from":81,"to":84}} {"id":100017972,"name":"WithHSTS","signature":"func WithHSTS(handler http.Handler, hstsDirectives []string) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/server/filters/hsts.go","code":"// WithHSTS is a simple HSTS implementation that wraps an http Handler.\n// If hstsDirectives is empty or nil, no HSTS support is installed.\nfunc WithHSTS(handler http.Handler, hstsDirectives []string) http.Handler {\n\tif len(hstsDirectives) == 0 {\n\t\treturn handler\n\t}\n\tallDirectives := strings.Join(hstsDirectives, \"; \")\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\t// Chrome and Mozilla Firefox maintain an HSTS preload list\n\t\t// issue : golang.org/issue/26162\n\t\t// Set the Strict-Transport-Security header if it is not already set\n\t\tif _, ok := w.Header()[\"Strict-Transport-Security\"]; !ok {\n\t\t\tw.Header().Set(\"Strict-Transport-Security\", allDirectives)\n\t\t}\n\t\thandler.ServeHTTP(w, req)\n\t})\n}","line":{"from":24,"to":40}} {"id":100017973,"name":"BasicLongRunningRequestCheck","signature":"func BasicLongRunningRequestCheck(longRunningVerbs, longRunningSubresources sets.String) apirequest.LongRunningRequestCheck","file":"staging/src/k8s.io/apiserver/pkg/server/filters/longrunning.go","code":"// BasicLongRunningRequestCheck returns true if the given request has one of the specified verbs or one of the specified subresources, or is a profiler request.\nfunc BasicLongRunningRequestCheck(longRunningVerbs, longRunningSubresources sets.String) apirequest.LongRunningRequestCheck {\n\treturn func(r *http.Request, requestInfo *apirequest.RequestInfo) bool {\n\t\tif longRunningVerbs.Has(requestInfo.Verb) {\n\t\t\treturn true\n\t\t}\n\t\tif requestInfo.IsResourceRequest \u0026\u0026 longRunningSubresources.Has(requestInfo.Subresource) {\n\t\t\treturn true\n\t\t}\n\t\tif !requestInfo.IsResourceRequest \u0026\u0026 strings.HasPrefix(requestInfo.Path, \"/debug/pprof/\") {\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n}","line":{"from":27,"to":41}} {"id":100017974,"name":"handleError","signature":"func handleError(w http.ResponseWriter, r *http.Request, err error)","file":"staging/src/k8s.io/apiserver/pkg/server/filters/maxinflight.go","code":"func handleError(w http.ResponseWriter, r *http.Request, err error) {\n\terrorMsg := fmt.Sprintf(\"Internal Server Error: %#v\", r.RequestURI)\n\thttp.Error(w, errorMsg, http.StatusInternalServerError)\n\tklog.Errorf(err.Error())\n}","line":{"from":51,"to":55}} {"id":100017975,"name":"recordMutating","signature":"func (w *requestWatermark) recordMutating(mutatingVal int)","file":"staging/src/k8s.io/apiserver/pkg/server/filters/maxinflight.go","code":"func (w *requestWatermark) recordMutating(mutatingVal int) {\n\tw.mutatingObserver.Set(float64(mutatingVal))\n\n\tw.lock.Lock()\n\tdefer w.lock.Unlock()\n\n\tif w.mutatingWatermark \u003c mutatingVal {\n\t\tw.mutatingWatermark = mutatingVal\n\t}\n}","line":{"from":65,"to":74}} {"id":100017976,"name":"recordReadOnly","signature":"func (w *requestWatermark) recordReadOnly(readOnlyVal int)","file":"staging/src/k8s.io/apiserver/pkg/server/filters/maxinflight.go","code":"func (w *requestWatermark) recordReadOnly(readOnlyVal int) {\n\tw.readOnlyObserver.Set(float64(readOnlyVal))\n\n\tw.lock.Lock()\n\tdefer w.lock.Unlock()\n\n\tif w.readOnlyWatermark \u003c readOnlyVal {\n\t\tw.readOnlyWatermark = readOnlyVal\n\t}\n}","line":{"from":76,"to":85}} {"id":100017977,"name":"startWatermarkMaintenance","signature":"func startWatermarkMaintenance(watermark *requestWatermark, stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/apiserver/pkg/server/filters/maxinflight.go","code":"// startWatermarkMaintenance starts the goroutines to observe and maintain the specified watermark.\nfunc startWatermarkMaintenance(watermark *requestWatermark, stopCh \u003c-chan struct{}) {\n\t// Periodically update the inflight usage metric.\n\tgo wait.Until(func() {\n\t\twatermark.lock.Lock()\n\t\treadOnlyWatermark := watermark.readOnlyWatermark\n\t\tmutatingWatermark := watermark.mutatingWatermark\n\t\twatermark.readOnlyWatermark = 0\n\t\twatermark.mutatingWatermark = 0\n\t\twatermark.lock.Unlock()\n\n\t\tmetrics.UpdateInflightRequestMetrics(watermark.phase, readOnlyWatermark, mutatingWatermark)\n\t}, inflightUsageMetricUpdatePeriod, stopCh)\n}","line":{"from":92,"to":105}} {"id":100017978,"name":"initMaxInFlight","signature":"func initMaxInFlight(nonMutatingLimit, mutatingLimit int)","file":"staging/src/k8s.io/apiserver/pkg/server/filters/maxinflight.go","code":"func initMaxInFlight(nonMutatingLimit, mutatingLimit int) {\n\tinitMaxInFlightOnce.Do(func() {\n\t\t// Fetching these gauges is delayed until after their underlying metric has been registered\n\t\t// so that this latches onto the efficient implementation.\n\t\twatermark.readOnlyObserver = fcmetrics.GetExecutingReadonlyConcurrency()\n\t\twatermark.mutatingObserver = fcmetrics.GetExecutingMutatingConcurrency()\n\t\tif nonMutatingLimit != 0 {\n\t\t\twatermark.readOnlyObserver.SetDenominator(float64(nonMutatingLimit))\n\t\t\tklog.V(2).InfoS(\"Set denominator for readonly requests\", \"limit\", nonMutatingLimit)\n\t\t}\n\t\tif mutatingLimit != 0 {\n\t\t\twatermark.mutatingObserver.SetDenominator(float64(mutatingLimit))\n\t\t\tklog.V(2).InfoS(\"Set denominator for mutating requests\", \"limit\", mutatingLimit)\n\t\t}\n\t})\n}","line":{"from":109,"to":124}} {"id":100017979,"name":"WithMaxInFlightLimit","signature":"func WithMaxInFlightLimit(","file":"staging/src/k8s.io/apiserver/pkg/server/filters/maxinflight.go","code":"// WithMaxInFlightLimit limits the number of in-flight requests to buffer size of the passed in channel.\nfunc WithMaxInFlightLimit(\n\thandler http.Handler,\n\tnonMutatingLimit int,\n\tmutatingLimit int,\n\tlongRunningRequestCheck apirequest.LongRunningRequestCheck,\n) http.Handler {\n\tif nonMutatingLimit == 0 \u0026\u0026 mutatingLimit == 0 {\n\t\treturn handler\n\t}\n\tvar nonMutatingChan chan bool\n\tvar mutatingChan chan bool\n\tif nonMutatingLimit != 0 {\n\t\tnonMutatingChan = make(chan bool, nonMutatingLimit)\n\t\tklog.V(2).InfoS(\"Initialized nonMutatingChan\", \"len\", nonMutatingLimit)\n\t} else {\n\t\tklog.V(2).InfoS(\"Running with nil nonMutatingChan\")\n\t}\n\tif mutatingLimit != 0 {\n\t\tmutatingChan = make(chan bool, mutatingLimit)\n\t\tklog.V(2).InfoS(\"Initialized mutatingChan\", \"len\", mutatingLimit)\n\t} else {\n\t\tklog.V(2).InfoS(\"Running with nil mutatingChan\")\n\t}\n\tinitMaxInFlight(nonMutatingLimit, mutatingLimit)\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tctx := r.Context()\n\t\trequestInfo, ok := apirequest.RequestInfoFrom(ctx)\n\t\tif !ok {\n\t\t\thandleError(w, r, fmt.Errorf(\"no RequestInfo found in context, handler chain must be wrong\"))\n\t\t\treturn\n\t\t}\n\n\t\t// Skip tracking long running events.\n\t\tif longRunningRequestCheck != nil \u0026\u0026 longRunningRequestCheck(r, requestInfo) {\n\t\t\thandler.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\tvar c chan bool\n\t\tisMutatingRequest := !nonMutatingRequestVerbs.Has(requestInfo.Verb)\n\t\tif isMutatingRequest {\n\t\t\tc = mutatingChan\n\t\t} else {\n\t\t\tc = nonMutatingChan\n\t\t}\n\n\t\tif c == nil {\n\t\t\thandler.ServeHTTP(w, r)\n\t\t} else {\n\n\t\t\tselect {\n\t\t\tcase c \u003c- true:\n\t\t\t\t// We note the concurrency level both while the\n\t\t\t\t// request is being served and after it is done being\n\t\t\t\t// served, because both states contribute to the\n\t\t\t\t// sampled stats on concurrency.\n\t\t\t\tif isMutatingRequest {\n\t\t\t\t\twatermark.recordMutating(len(c))\n\t\t\t\t} else {\n\t\t\t\t\twatermark.recordReadOnly(len(c))\n\t\t\t\t}\n\t\t\t\tdefer func() {\n\t\t\t\t\t\u003c-c\n\t\t\t\t\tif isMutatingRequest {\n\t\t\t\t\t\twatermark.recordMutating(len(c))\n\t\t\t\t\t} else {\n\t\t\t\t\t\twatermark.recordReadOnly(len(c))\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t\thandler.ServeHTTP(w, r)\n\n\t\t\tdefault:\n\t\t\t\t// at this point we're about to return a 429, BUT not all actors should be rate limited. A system:master is so powerful\n\t\t\t\t// that they should always get an answer. It's a super-admin or a loopback connection.\n\t\t\t\tif currUser, ok := apirequest.UserFrom(ctx); ok {\n\t\t\t\t\tfor _, group := range currUser.GetGroups() {\n\t\t\t\t\t\tif group == user.SystemPrivilegedGroup {\n\t\t\t\t\t\t\thandler.ServeHTTP(w, r)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// We need to split this data between buckets used for throttling.\n\t\t\t\tmetrics.RecordDroppedRequest(r, requestInfo, metrics.APIServerComponent, isMutatingRequest)\n\t\t\t\tmetrics.RecordRequestTermination(r, requestInfo, metrics.APIServerComponent, http.StatusTooManyRequests)\n\t\t\t\ttooManyRequests(r, w)\n\t\t\t}\n\t\t}\n\t})\n}","line":{"from":126,"to":217}} {"id":100017980,"name":"StartMaxInFlightWatermarkMaintenance","signature":"func StartMaxInFlightWatermarkMaintenance(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/apiserver/pkg/server/filters/maxinflight.go","code":"// StartMaxInFlightWatermarkMaintenance starts the goroutines to observe and maintain watermarks for max-in-flight\n// requests.\nfunc StartMaxInFlightWatermarkMaintenance(stopCh \u003c-chan struct{}) {\n\tstartWatermarkMaintenance(watermark, stopCh)\n}","line":{"from":219,"to":223}} {"id":100017981,"name":"tooManyRequests","signature":"func tooManyRequests(req *http.Request, w http.ResponseWriter)","file":"staging/src/k8s.io/apiserver/pkg/server/filters/maxinflight.go","code":"func tooManyRequests(req *http.Request, w http.ResponseWriter) {\n\t// Return a 429 status indicating \"Too Many Requests\"\n\tw.Header().Set(\"Retry-After\", retryAfter)\n\thttp.Error(w, \"Too many requests, please try again later.\", http.StatusTooManyRequests)\n}","line":{"from":225,"to":229}} {"id":100017982,"name":"truncateLogField","signature":"func truncateLogField(s string) string","file":"staging/src/k8s.io/apiserver/pkg/server/filters/priority-and-fairness.go","code":"func truncateLogField(s string) string {\n\tconst maxFieldLogLength = 64\n\n\tif len(s) \u003e maxFieldLogLength {\n\t\ts = s[0:maxFieldLogLength]\n\t}\n\treturn s\n}","line":{"from":59,"to":66}} {"id":100017983,"name":"WithPriorityAndFairness","signature":"func WithPriorityAndFairness(","file":"staging/src/k8s.io/apiserver/pkg/server/filters/priority-and-fairness.go","code":"// WithPriorityAndFairness limits the number of in-flight\n// requests in a fine-grained way.\nfunc WithPriorityAndFairness(\n\thandler http.Handler,\n\tlongRunningRequestCheck apirequest.LongRunningRequestCheck,\n\tfcIfc utilflowcontrol.Interface,\n\tworkEstimator flowcontrolrequest.WorkEstimatorFunc,\n) http.Handler {\n\tif fcIfc == nil {\n\t\tklog.Warningf(\"priority and fairness support not found, skipping\")\n\t\treturn handler\n\t}\n\tinitAPFOnce.Do(func() {\n\t\tinitMaxInFlight(0, 0)\n\t\t// Fetching these gauges is delayed until after their underlying metric has been registered\n\t\t// so that this latches onto the efficient implementation.\n\t\twaitingMark.readOnlyObserver = fcmetrics.GetWaitingReadonlyConcurrency()\n\t\twaitingMark.mutatingObserver = fcmetrics.GetWaitingMutatingConcurrency()\n\t})\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tctx := r.Context()\n\t\trequestInfo, ok := apirequest.RequestInfoFrom(ctx)\n\t\tif !ok {\n\t\t\thandleError(w, r, fmt.Errorf(\"no RequestInfo found in context\"))\n\t\t\treturn\n\t\t}\n\t\tuser, ok := apirequest.UserFrom(ctx)\n\t\tif !ok {\n\t\t\thandleError(w, r, fmt.Errorf(\"no User found in context\"))\n\t\t\treturn\n\t\t}\n\n\t\tisWatchRequest := watchVerbs.Has(requestInfo.Verb)\n\n\t\t// Skip tracking long running non-watch requests.\n\t\tif longRunningRequestCheck != nil \u0026\u0026 longRunningRequestCheck(r, requestInfo) \u0026\u0026 !isWatchRequest {\n\t\t\tklog.V(6).Infof(\"Serving RequestInfo=%#+v, user.Info=%#+v as longrunning\\n\", requestInfo, user)\n\t\t\thandler.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\tvar classification *PriorityAndFairnessClassification\n\t\tnoteFn := func(fs *flowcontrol.FlowSchema, pl *flowcontrol.PriorityLevelConfiguration, flowDistinguisher string) {\n\t\t\tclassification = \u0026PriorityAndFairnessClassification{\n\t\t\t\tFlowSchemaName: fs.Name,\n\t\t\t\tFlowSchemaUID: fs.UID,\n\t\t\t\tPriorityLevelName: pl.Name,\n\t\t\t\tPriorityLevelUID: pl.UID}\n\n\t\t\thttplog.AddKeyValue(ctx, \"apf_pl\", truncateLogField(pl.Name))\n\t\t\thttplog.AddKeyValue(ctx, \"apf_fs\", truncateLogField(fs.Name))\n\t\t}\n\t\t// estimateWork is called, if at all, after noteFn\n\t\testimateWork := func() flowcontrolrequest.WorkEstimate {\n\t\t\tif classification == nil {\n\t\t\t\t// workEstimator is being invoked before classification of\n\t\t\t\t// the request has completed, we should never be here though.\n\t\t\t\tklog.ErrorS(fmt.Errorf(\"workEstimator is being invoked before classification of the request has completed\"),\n\t\t\t\t\t\"Using empty FlowSchema and PriorityLevelConfiguration name\", \"verb\", r.Method, \"URI\", r.RequestURI)\n\n\t\t\t\treturn workEstimator(r, \"\", \"\")\n\t\t\t}\n\n\t\t\tworkEstimate := workEstimator(r, classification.FlowSchemaName, classification.PriorityLevelName)\n\n\t\t\tfcmetrics.ObserveWorkEstimatedSeats(classification.PriorityLevelName, classification.FlowSchemaName, workEstimate.MaxSeats())\n\t\t\thttplog.AddKeyValue(ctx, \"apf_iseats\", workEstimate.InitialSeats)\n\t\t\thttplog.AddKeyValue(ctx, \"apf_fseats\", workEstimate.FinalSeats)\n\t\t\thttplog.AddKeyValue(ctx, \"apf_additionalLatency\", workEstimate.AdditionalLatency)\n\n\t\t\treturn workEstimate\n\t\t}\n\n\t\tvar served bool\n\t\tisMutatingRequest := !nonMutatingRequestVerbs.Has(requestInfo.Verb)\n\t\tnoteExecutingDelta := func(delta int32) {\n\t\t\tif isMutatingRequest {\n\t\t\t\twatermark.recordMutating(int(atomic.AddInt32(\u0026atomicMutatingExecuting, delta)))\n\t\t\t} else {\n\t\t\t\twatermark.recordReadOnly(int(atomic.AddInt32(\u0026atomicReadOnlyExecuting, delta)))\n\t\t\t}\n\t\t}\n\t\tnoteWaitingDelta := func(delta int32) {\n\t\t\tif isMutatingRequest {\n\t\t\t\twaitingMark.recordMutating(int(atomic.AddInt32(\u0026atomicMutatingWaiting, delta)))\n\t\t\t} else {\n\t\t\t\twaitingMark.recordReadOnly(int(atomic.AddInt32(\u0026atomicReadOnlyWaiting, delta)))\n\t\t\t}\n\t\t}\n\t\tqueueNote := func(inQueue bool) {\n\t\t\tif inQueue {\n\t\t\t\tnoteWaitingDelta(1)\n\t\t\t} else {\n\t\t\t\tnoteWaitingDelta(-1)\n\t\t\t}\n\t\t}\n\n\t\tdigest := utilflowcontrol.RequestDigest{\n\t\t\tRequestInfo: requestInfo,\n\t\t\tUser: user,\n\t\t}\n\n\t\tif isWatchRequest {\n\t\t\t// This channel blocks calling handler.ServeHTTP() until closed, and is closed inside execute().\n\t\t\t// If APF rejects the request, it is never closed.\n\t\t\tshouldStartWatchCh := make(chan struct{})\n\n\t\t\twatchInitializationSignal := newInitializationSignal()\n\t\t\t// This wraps the request passed to handler.ServeHTTP(),\n\t\t\t// setting a context that plumbs watchInitializationSignal to storage\n\t\t\tvar watchReq *http.Request\n\t\t\t// This is set inside execute(), prior to closing shouldStartWatchCh.\n\t\t\t// If the request is rejected by APF it is left nil.\n\t\t\tvar forgetWatch utilflowcontrol.ForgetWatchFunc\n\n\t\t\tdefer func() {\n\t\t\t\t// Protect from the situation when request will not reach storage layer\n\t\t\t\t// and the initialization signal will not be send.\n\t\t\t\tif watchInitializationSignal != nil {\n\t\t\t\t\twatchInitializationSignal.Signal()\n\t\t\t\t}\n\t\t\t\t// Forget the watcher if it was registered.\n\t\t\t\t//\n\t\t\t\t// // This is race-free because by this point, one of the following occurred:\n\t\t\t\t// case \u003c-shouldStartWatchCh: execute() completed the assignment to forgetWatch\n\t\t\t\t// case \u003c-resultCh: Handle() completed, and Handle() does not return\n\t\t\t\t// while execute() is running\n\t\t\t\tif forgetWatch != nil {\n\t\t\t\t\tforgetWatch()\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\texecute := func() {\n\t\t\t\tstartedAt := time.Now()\n\t\t\t\tdefer func() {\n\t\t\t\t\thttplog.AddKeyValue(ctx, \"apf_init_latency\", time.Since(startedAt))\n\t\t\t\t}()\n\t\t\t\tnoteExecutingDelta(1)\n\t\t\t\tdefer noteExecutingDelta(-1)\n\t\t\t\tserved = true\n\t\t\t\tsetResponseHeaders(classification, w)\n\n\t\t\t\tforgetWatch = fcIfc.RegisterWatch(r)\n\n\t\t\t\t// Notify the main thread that we're ready to start the watch.\n\t\t\t\tclose(shouldStartWatchCh)\n\n\t\t\t\t// Wait until the request is finished from the APF point of view\n\t\t\t\t// (which is when its initialization is done).\n\t\t\t\twatchInitializationSignal.Wait()\n\t\t\t}\n\n\t\t\t// Ensure that an item can be put to resultCh asynchronously.\n\t\t\tresultCh := make(chan interface{}, 1)\n\n\t\t\t// Call Handle in a separate goroutine.\n\t\t\t// The reason for it is that from APF point of view, the request processing\n\t\t\t// finishes as soon as watch is initialized (which is generally orders of\n\t\t\t// magnitude faster then the watch request itself). This means that Handle()\n\t\t\t// call finishes much faster and for performance reasons we want to reduce\n\t\t\t// the number of running goroutines - so we run the shorter thing in a\n\t\t\t// dedicated goroutine and the actual watch handler in the main one.\n\t\t\tgo func() {\n\t\t\t\tdefer func() {\n\t\t\t\t\terr := recover()\n\t\t\t\t\t// do not wrap the sentinel ErrAbortHandler panic value\n\t\t\t\t\tif err != nil \u0026\u0026 err != http.ErrAbortHandler {\n\t\t\t\t\t\t// Same as stdlib http server code. Manually allocate stack\n\t\t\t\t\t\t// trace buffer size to prevent excessively large logs\n\t\t\t\t\t\tconst size = 64 \u003c\u003c 10\n\t\t\t\t\t\tbuf := make([]byte, size)\n\t\t\t\t\t\tbuf = buf[:runtime.Stack(buf, false)]\n\t\t\t\t\t\terr = fmt.Sprintf(\"%v\\n%s\", err, buf)\n\t\t\t\t\t}\n\n\t\t\t\t\t// Ensure that the result is put into resultCh independently of the panic.\n\t\t\t\t\tresultCh \u003c- err\n\t\t\t\t}()\n\n\t\t\t\t// We create handleCtx with explicit cancelation function.\n\t\t\t\t// The reason for it is that Handle() underneath may start additional goroutine\n\t\t\t\t// that is blocked on context cancellation. However, from APF point of view,\n\t\t\t\t// we don't want to wait until the whole watch request is processed (which is\n\t\t\t\t// when it context is actually cancelled) - we want to unblock the goroutine as\n\t\t\t\t// soon as the request is processed from the APF point of view.\n\t\t\t\t//\n\t\t\t\t// Note that we explicitly do NOT call the actuall handler using that context\n\t\t\t\t// to avoid cancelling request too early.\n\t\t\t\thandleCtx, handleCtxCancel := context.WithCancel(ctx)\n\t\t\t\tdefer handleCtxCancel()\n\n\t\t\t\t// Note that Handle will return irrespective of whether the request\n\t\t\t\t// executes or is rejected. In the latter case, the function will return\n\t\t\t\t// without calling the passed `execute` function.\n\t\t\t\tfcIfc.Handle(handleCtx, digest, noteFn, estimateWork, queueNote, execute)\n\t\t\t}()\n\n\t\t\tselect {\n\t\t\tcase \u003c-shouldStartWatchCh:\n\t\t\t\twatchCtx := utilflowcontrol.WithInitializationSignal(ctx, watchInitializationSignal)\n\t\t\t\twatchReq = r.WithContext(watchCtx)\n\t\t\t\thandler.ServeHTTP(w, watchReq)\n\t\t\t\t// Protect from the situation when request will not reach storage layer\n\t\t\t\t// and the initialization signal will not be send.\n\t\t\t\t// It has to happen before waiting on the resultCh below.\n\t\t\t\twatchInitializationSignal.Signal()\n\t\t\t\t// TODO: Consider finishing the request as soon as Handle call panics.\n\t\t\t\tif err := \u003c-resultCh; err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\tcase err := \u003c-resultCh:\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\texecute := func() {\n\t\t\t\tnoteExecutingDelta(1)\n\t\t\t\tdefer noteExecutingDelta(-1)\n\t\t\t\tserved = true\n\t\t\t\tsetResponseHeaders(classification, w)\n\n\t\t\t\thandler.ServeHTTP(w, r)\n\t\t\t}\n\n\t\t\tfcIfc.Handle(ctx, digest, noteFn, estimateWork, queueNote, execute)\n\t\t}\n\n\t\tif !served {\n\t\t\tsetResponseHeaders(classification, w)\n\n\t\t\tepmetrics.RecordDroppedRequest(r, requestInfo, epmetrics.APIServerComponent, isMutatingRequest)\n\t\t\tepmetrics.RecordRequestTermination(r, requestInfo, epmetrics.APIServerComponent, http.StatusTooManyRequests)\n\t\t\ttooManyRequests(r, w)\n\t\t}\n\t})\n}","line":{"from":70,"to":306}} {"id":100017984,"name":"StartPriorityAndFairnessWatermarkMaintenance","signature":"func StartPriorityAndFairnessWatermarkMaintenance(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/apiserver/pkg/server/filters/priority-and-fairness.go","code":"// StartPriorityAndFairnessWatermarkMaintenance starts the goroutines to observe and maintain watermarks for\n// priority-and-fairness requests.\nfunc StartPriorityAndFairnessWatermarkMaintenance(stopCh \u003c-chan struct{}) {\n\tstartWatermarkMaintenance(watermark, stopCh)\n\tstartWatermarkMaintenance(waitingMark, stopCh)\n}","line":{"from":308,"to":313}} {"id":100017985,"name":"setResponseHeaders","signature":"func setResponseHeaders(classification *PriorityAndFairnessClassification, w http.ResponseWriter)","file":"staging/src/k8s.io/apiserver/pkg/server/filters/priority-and-fairness.go","code":"func setResponseHeaders(classification *PriorityAndFairnessClassification, w http.ResponseWriter) {\n\tif classification == nil {\n\t\treturn\n\t}\n\n\t// We intentionally set the UID of the flow-schema and priority-level instead of name. This is so that\n\t// the names that cluster-admins choose for categorization and priority levels are not exposed, also\n\t// the names might make it obvious to the users that they are rejected due to classification with low priority.\n\tw.Header().Set(flowcontrol.ResponseHeaderMatchedPriorityLevelConfigurationUID, string(classification.PriorityLevelUID))\n\tw.Header().Set(flowcontrol.ResponseHeaderMatchedFlowSchemaUID, string(classification.FlowSchemaUID))\n}","line":{"from":315,"to":325}} {"id":100017986,"name":"WithTimeoutForNonLongRunningRequests","signature":"func WithTimeoutForNonLongRunningRequests(handler http.Handler, longRunning apirequest.LongRunningRequestCheck) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/server/filters/timeout.go","code":"// WithTimeoutForNonLongRunningRequests times out non-long-running requests after the time given by timeout.\nfunc WithTimeoutForNonLongRunningRequests(handler http.Handler, longRunning apirequest.LongRunningRequestCheck) http.Handler {\n\tif longRunning == nil {\n\t\treturn handler\n\t}\n\ttimeoutFunc := func(req *http.Request) (*http.Request, bool, func(), *apierrors.StatusError) {\n\t\t// TODO unify this with apiserver.MaxInFlightLimit\n\t\tctx := req.Context()\n\n\t\trequestInfo, ok := apirequest.RequestInfoFrom(ctx)\n\t\tif !ok {\n\t\t\t// if this happens, the handler chain isn't setup correctly because there is no request info\n\t\t\treturn req, false, func() {}, apierrors.NewInternalError(fmt.Errorf(\"no request info found for request during timeout\"))\n\t\t}\n\n\t\tif longRunning(req, requestInfo) {\n\t\t\treturn req, true, nil, nil\n\t\t}\n\n\t\tpostTimeoutFn := func() {\n\t\t\tmetrics.RecordRequestTermination(req, requestInfo, metrics.APIServerComponent, http.StatusGatewayTimeout)\n\t\t}\n\t\treturn req, false, postTimeoutFn, apierrors.NewTimeoutError(\"request did not complete within the allotted timeout\", 0)\n\t}\n\treturn WithTimeout(handler, timeoutFunc)\n}","line":{"from":37,"to":62}} {"id":100017987,"name":"WithTimeout","signature":"func WithTimeout(h http.Handler, timeoutFunc timeoutFunc) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/server/filters/timeout.go","code":"// WithTimeout returns an http.Handler that runs h with a timeout\n// determined by timeoutFunc. The new http.Handler calls h.ServeHTTP to handle\n// each request, but if a call runs for longer than its time limit, the\n// handler responds with a 504 Gateway Timeout error and the message\n// provided. (If msg is empty, a suitable default message will be sent.) After\n// the handler times out, writes by h to its http.ResponseWriter will return\n// http.ErrHandlerTimeout. If timeoutFunc returns a nil timeout channel, no\n// timeout will be enforced. recordFn is a function that will be invoked whenever\n// a timeout happens.\nfunc WithTimeout(h http.Handler, timeoutFunc timeoutFunc) http.Handler {\n\treturn \u0026timeoutHandler{h, timeoutFunc}\n}","line":{"from":66,"to":77}} {"id":100017988,"name":"ServeHTTP","signature":"func (t *timeoutHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)","file":"staging/src/k8s.io/apiserver/pkg/server/filters/timeout.go","code":"func (t *timeoutHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tr, longRunning, postTimeoutFn, err := t.timeout(r)\n\tif longRunning {\n\t\tt.handler.ServeHTTP(w, r)\n\t\treturn\n\t}\n\n\ttimeoutCh := r.Context().Done()\n\n\t// resultCh is used as both errCh and stopCh\n\tresultCh := make(chan interface{})\n\tvar tw timeoutWriter\n\ttw, w = newTimeoutWriter(w)\n\n\t// Make a copy of request and work on it in new goroutine\n\t// to avoid race condition when accessing/modifying request (e.g. headers)\n\trCopy := r.Clone(r.Context())\n\tgo func() {\n\t\tdefer func() {\n\t\t\terr := recover()\n\t\t\t// do not wrap the sentinel ErrAbortHandler panic value\n\t\t\tif err != nil \u0026\u0026 err != http.ErrAbortHandler {\n\t\t\t\t// Same as stdlib http server code. Manually allocate stack\n\t\t\t\t// trace buffer size to prevent excessively large logs\n\t\t\t\tconst size = 64 \u003c\u003c 10\n\t\t\t\tbuf := make([]byte, size)\n\t\t\t\tbuf = buf[:runtime.Stack(buf, false)]\n\t\t\t\terr = fmt.Sprintf(\"%v\\n%s\", err, buf)\n\t\t\t}\n\t\t\tresultCh \u003c- err\n\t\t}()\n\t\tt.handler.ServeHTTP(w, rCopy)\n\t}()\n\tselect {\n\tcase err := \u003c-resultCh:\n\t\t// panic if error occurs; stop otherwise\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn\n\tcase \u003c-timeoutCh:\n\t\tdefer func() {\n\t\t\t// resultCh needs to have a reader, since the function doing\n\t\t\t// the work needs to send to it. This is defer'd to ensure it runs\n\t\t\t// ever if the post timeout work itself panics.\n\t\t\tgo func() {\n\t\t\t\ttimedOutAt := time.Now()\n\t\t\t\tres := \u003c-resultCh\n\n\t\t\t\tstatus := metrics.PostTimeoutHandlerOK\n\t\t\t\tif res != nil {\n\t\t\t\t\t// a non nil res indicates that there was a panic.\n\t\t\t\t\tstatus = metrics.PostTimeoutHandlerPanic\n\t\t\t\t}\n\n\t\t\t\tmetrics.RecordRequestPostTimeout(metrics.PostTimeoutSourceTimeoutHandler, status)\n\t\t\t\terr := fmt.Errorf(\"post-timeout activity - time-elapsed: %s, %v %q result: %v\",\n\t\t\t\t\ttime.Since(timedOutAt), r.Method, r.URL.Path, res)\n\t\t\t\tutilruntime.HandleError(err)\n\t\t\t}()\n\t\t}()\n\t\thttplog.SetStacktracePredicate(r.Context(), func(status int) bool {\n\t\t\treturn false\n\t\t})\n\t\tdefer postTimeoutFn()\n\t\ttw.timeout(err)\n\t}\n}","line":{"from":84,"to":151}} {"id":100017989,"name":"newTimeoutWriter","signature":"func newTimeoutWriter(w http.ResponseWriter) (timeoutWriter, http.ResponseWriter)","file":"staging/src/k8s.io/apiserver/pkg/server/filters/timeout.go","code":"func newTimeoutWriter(w http.ResponseWriter) (timeoutWriter, http.ResponseWriter) {\n\tbase := \u0026baseTimeoutWriter{w: w, handlerHeaders: w.Header().Clone()}\n\twrapped := responsewriter.WrapForHTTP1Or2(base)\n\n\treturn base, wrapped\n}","line":{"from":158,"to":163}} {"id":100017990,"name":"Unwrap","signature":"func (tw *baseTimeoutWriter) Unwrap() http.ResponseWriter","file":"staging/src/k8s.io/apiserver/pkg/server/filters/timeout.go","code":"func (tw *baseTimeoutWriter) Unwrap() http.ResponseWriter {\n\treturn tw.w\n}","line":{"from":183,"to":185}} {"id":100017991,"name":"Header","signature":"func (tw *baseTimeoutWriter) Header() http.Header","file":"staging/src/k8s.io/apiserver/pkg/server/filters/timeout.go","code":"func (tw *baseTimeoutWriter) Header() http.Header {\n\ttw.mu.Lock()\n\tdefer tw.mu.Unlock()\n\n\tif tw.timedOut {\n\t\treturn http.Header{}\n\t}\n\n\treturn tw.handlerHeaders\n}","line":{"from":187,"to":196}} {"id":100017992,"name":"Write","signature":"func (tw *baseTimeoutWriter) Write(p []byte) (int, error)","file":"staging/src/k8s.io/apiserver/pkg/server/filters/timeout.go","code":"func (tw *baseTimeoutWriter) Write(p []byte) (int, error) {\n\ttw.mu.Lock()\n\tdefer tw.mu.Unlock()\n\n\tif tw.timedOut {\n\t\treturn 0, http.ErrHandlerTimeout\n\t}\n\tif tw.hijacked {\n\t\treturn 0, http.ErrHijacked\n\t}\n\n\tif !tw.wroteHeader {\n\t\tcopyHeaders(tw.w.Header(), tw.handlerHeaders)\n\t\ttw.wroteHeader = true\n\t}\n\treturn tw.w.Write(p)\n}","line":{"from":198,"to":214}} {"id":100017993,"name":"Flush","signature":"func (tw *baseTimeoutWriter) Flush()","file":"staging/src/k8s.io/apiserver/pkg/server/filters/timeout.go","code":"func (tw *baseTimeoutWriter) Flush() {\n\ttw.mu.Lock()\n\tdefer tw.mu.Unlock()\n\n\tif tw.timedOut {\n\t\treturn\n\t}\n\n\t// the outer ResponseWriter object returned by WrapForHTTP1Or2 implements\n\t// http.Flusher if the inner object (tw.w) implements http.Flusher.\n\ttw.w.(http.Flusher).Flush()\n}","line":{"from":216,"to":227}} {"id":100017994,"name":"WriteHeader","signature":"func (tw *baseTimeoutWriter) WriteHeader(code int)","file":"staging/src/k8s.io/apiserver/pkg/server/filters/timeout.go","code":"func (tw *baseTimeoutWriter) WriteHeader(code int) {\n\ttw.mu.Lock()\n\tdefer tw.mu.Unlock()\n\n\tif tw.timedOut || tw.wroteHeader || tw.hijacked {\n\t\treturn\n\t}\n\n\tcopyHeaders(tw.w.Header(), tw.handlerHeaders)\n\ttw.wroteHeader = true\n\ttw.w.WriteHeader(code)\n}","line":{"from":229,"to":240}} {"id":100017995,"name":"copyHeaders","signature":"func copyHeaders(dst, src http.Header)","file":"staging/src/k8s.io/apiserver/pkg/server/filters/timeout.go","code":"func copyHeaders(dst, src http.Header) {\n\tfor k, v := range src {\n\t\tdst[k] = v\n\t}\n}","line":{"from":242,"to":246}} {"id":100017996,"name":"timeout","signature":"func (tw *baseTimeoutWriter) timeout(err *apierrors.StatusError)","file":"staging/src/k8s.io/apiserver/pkg/server/filters/timeout.go","code":"func (tw *baseTimeoutWriter) timeout(err *apierrors.StatusError) {\n\ttw.mu.Lock()\n\tdefer tw.mu.Unlock()\n\n\ttw.timedOut = true\n\n\t// The timeout writer has not been used by the inner handler.\n\t// We can safely timeout the HTTP request by sending by a timeout\n\t// handler\n\tif !tw.wroteHeader \u0026\u0026 !tw.hijacked {\n\t\ttw.w.WriteHeader(http.StatusGatewayTimeout)\n\t\tenc := json.NewEncoder(tw.w)\n\t\tenc.Encode(\u0026err.ErrStatus)\n\t} else {\n\t\t// The timeout writer has been used by the inner handler. There is\n\t\t// no way to timeout the HTTP request at the point. We have to shutdown\n\t\t// the connection for HTTP1 or reset stream for HTTP2.\n\t\t//\n\t\t// Note from the golang's docs:\n\t\t// If ServeHTTP panics, the server (the caller of ServeHTTP) assumes\n\t\t// that the effect of the panic was isolated to the active request.\n\t\t// It recovers the panic, logs a stack trace to the server error log,\n\t\t// and either closes the network connection or sends an HTTP/2\n\t\t// RST_STREAM, depending on the HTTP protocol. To abort a handler so\n\t\t// the client sees an interrupted response but the server doesn't log\n\t\t// an error, panic with the value ErrAbortHandler.\n\t\t//\n\t\t// We are throwing http.ErrAbortHandler deliberately so that a client is notified and to suppress a not helpful stacktrace in the logs\n\t\tpanic(http.ErrAbortHandler)\n\t}\n}","line":{"from":248,"to":278}} {"id":100017997,"name":"CloseNotify","signature":"func (tw *baseTimeoutWriter) CloseNotify() \u003c-chan bool","file":"staging/src/k8s.io/apiserver/pkg/server/filters/timeout.go","code":"func (tw *baseTimeoutWriter) CloseNotify() \u003c-chan bool {\n\ttw.mu.Lock()\n\tdefer tw.mu.Unlock()\n\n\tif tw.timedOut {\n\t\tdone := make(chan bool)\n\t\tclose(done)\n\t\treturn done\n\t}\n\n\t// the outer ResponseWriter object returned by WrapForHTTP1Or2 implements\n\t// http.CloseNotifier if the inner object (tw.w) implements http.CloseNotifier.\n\treturn tw.w.(http.CloseNotifier).CloseNotify()\n}","line":{"from":280,"to":293}} {"id":100017998,"name":"Hijack","signature":"func (tw *baseTimeoutWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)","file":"staging/src/k8s.io/apiserver/pkg/server/filters/timeout.go","code":"func (tw *baseTimeoutWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\ttw.mu.Lock()\n\tdefer tw.mu.Unlock()\n\n\tif tw.timedOut {\n\t\treturn nil, nil, http.ErrHandlerTimeout\n\t}\n\n\t// the outer ResponseWriter object returned by WrapForHTTP1Or2 implements\n\t// http.Hijacker if the inner object (tw.w) implements http.Hijacker.\n\tconn, rw, err := tw.w.(http.Hijacker).Hijack()\n\tif err == nil {\n\t\ttw.hijacked = true\n\t}\n\treturn conn, rw, err\n}","line":{"from":295,"to":310}} {"id":100017999,"name":"WithWaitGroup","signature":"func WithWaitGroup(handler http.Handler, longRunning apirequest.LongRunningRequestCheck, wg RequestWaitGroup) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/server/filters/waitgroup.go","code":"// WithWaitGroup adds all non long-running requests to wait group, which is used for graceful shutdown.\nfunc WithWaitGroup(handler http.Handler, longRunning apirequest.LongRunningRequestCheck, wg RequestWaitGroup) http.Handler {\n\t// NOTE: both WithWaitGroup and WithRetryAfter must use the same exact isRequestExemptFunc 'isRequestExemptFromRetryAfter,\n\t// otherwise SafeWaitGroup might wait indefinitely and will prevent the server from shutting down gracefully.\n\treturn withWaitGroup(handler, longRunning, wg, isRequestExemptFromRetryAfter)\n}","line":{"from":47,"to":52}} {"id":100018000,"name":"withWaitGroup","signature":"func withWaitGroup(handler http.Handler, longRunning apirequest.LongRunningRequestCheck, wg RequestWaitGroup, isRequestExemptFn isRequestExemptFunc) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/server/filters/waitgroup.go","code":"func withWaitGroup(handler http.Handler, longRunning apirequest.LongRunningRequestCheck, wg RequestWaitGroup, isRequestExemptFn isRequestExemptFunc) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tctx := req.Context()\n\t\trequestInfo, ok := apirequest.RequestInfoFrom(ctx)\n\t\tif !ok {\n\t\t\t// if this happens, the handler chain isn't setup correctly because there is no request info\n\t\t\tresponsewriters.InternalError(w, req, errors.New(\"no RequestInfo found in the context\"))\n\t\t\treturn\n\t\t}\n\n\t\tif longRunning(req, requestInfo) {\n\t\t\thandler.ServeHTTP(w, req)\n\t\t\treturn\n\t\t}\n\n\t\tif err := wg.Add(1); err != nil {\n\t\t\t// shutdown delay duration has elapsed and SafeWaitGroup.Wait has been invoked,\n\t\t\t// this means 'WithRetryAfter' has started sending Retry-After response.\n\t\t\t// we are going to exempt the same set of requests that WithRetryAfter are\n\t\t\t// exempting from being rejected with a Retry-After response.\n\t\t\tif isRequestExemptFn(req) {\n\t\t\t\thandler.ServeHTTP(w, req)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// When apiserver is shutting down, signal clients to retry\n\t\t\t// There is a good chance the client hit a different server, so a tight retry is good for client responsiveness.\n\t\t\twaitGroupWriteRetryAfterToResponse(w)\n\t\t\treturn\n\t\t}\n\n\t\tdefer wg.Done()\n\t\thandler.ServeHTTP(w, req)\n\t})\n}","line":{"from":54,"to":88}} {"id":100018001,"name":"waitGroupWriteRetryAfterToResponse","signature":"func waitGroupWriteRetryAfterToResponse(w http.ResponseWriter)","file":"staging/src/k8s.io/apiserver/pkg/server/filters/waitgroup.go","code":"func waitGroupWriteRetryAfterToResponse(w http.ResponseWriter) {\n\tw.Header().Add(\"Retry-After\", \"1\")\n\tw.Header().Set(\"Content-Type\", runtime.ContentTypeJSON)\n\tw.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\tstatusErr := apierrors.NewServiceUnavailable(\"apiserver is shutting down\").Status()\n\tw.WriteHeader(int(statusErr.Code))\n\tfmt.Fprintln(w, runtime.EncodeOrDie(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), \u0026statusErr))\n}","line":{"from":90,"to":97}} {"id":100018002,"name":"WithWatchTerminationDuringShutdown","signature":"func WithWatchTerminationDuringShutdown(handler http.Handler, termination apirequest.ServerShutdownSignal, wg RequestWaitGroup) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/server/filters/watch_termination.go","code":"func WithWatchTerminationDuringShutdown(handler http.Handler, termination apirequest.ServerShutdownSignal, wg RequestWaitGroup) http.Handler {\n\tif termination == nil || wg == nil {\n\t\tklog.Warningf(\"watch termination during shutdown not attached to the handler chain\")\n\t\treturn handler\n\t}\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tctx := req.Context()\n\t\trequestInfo, ok := apirequest.RequestInfoFrom(ctx)\n\t\tif !ok {\n\t\t\t// if this happens, the handler chain isn't setup correctly because there is no request info\n\t\t\tresponsewriters.InternalError(w, req, errors.New(\"no RequestInfo found in the context\"))\n\t\t\treturn\n\t\t}\n\t\tif !watchVerbs.Has(requestInfo.Verb) {\n\t\t\thandler.ServeHTTP(w, req)\n\t\t\treturn\n\t\t}\n\n\t\tif err := wg.Add(1); err != nil {\n\t\t\t// When apiserver is shutting down, signal clients to retry\n\t\t\t// There is a good chance the client hit a different server, so a tight retry is good for client responsiveness.\n\t\t\twaitGroupWriteRetryAfterToResponse(w)\n\t\t\treturn\n\t\t}\n\n\t\t// attach ServerShutdownSignal to the watch request so that the\n\t\t// watch handler loop can return as soon as the server signals\n\t\t// that it is shutting down.\n\t\tctx = apirequest.WithServerShutdownSignal(req.Context(), termination)\n\t\treq = req.WithContext(ctx)\n\n\t\tdefer wg.Done()\n\t\thandler.ServeHTTP(w, req)\n\t})\n}","line":{"from":28,"to":62}} {"id":100018003,"name":"WithRetryAfter","signature":"func WithRetryAfter(handler http.Handler, shutdownDelayDurationElapsedCh \u003c-chan struct{}) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/server/filters/with_retry_after.go","code":"// WithRetryAfter rejects any incoming new request(s) with a 429\n// if the specified shutdownDelayDurationElapsedFn channel is closed\n//\n// It includes new request(s) on a new or an existing TCP connection\n// Any new request(s) arriving after shutdownDelayDurationElapsedFn is closed\n// are replied with a 429 and the following response headers:\n// - 'Retry-After: N` (so client can retry after N seconds, hopefully on a new apiserver instance)\n// - 'Connection: close': tear down the TCP connection\n//\n// TODO: is there a way to merge WithWaitGroup and this filter?\nfunc WithRetryAfter(handler http.Handler, shutdownDelayDurationElapsedCh \u003c-chan struct{}) http.Handler {\n\tshutdownRetryAfterParams := \u0026retryAfterParams{\n\t\tTearDownConnection: true,\n\t\tMessage: \"The apiserver is shutting down, please try again later.\",\n\t}\n\n\t// NOTE: both WithRetryAfter and WithWaitGroup must use the same exact isRequestExemptFunc 'isRequestExemptFromRetryAfter,\n\t// otherwise SafeWaitGroup might wait indefinitely and will prevent the server from shutting down gracefully.\n\treturn withRetryAfter(handler, isRequestExemptFromRetryAfter, func() (*retryAfterParams, bool) {\n\t\tselect {\n\t\tcase \u003c-shutdownDelayDurationElapsedCh:\n\t\t\treturn shutdownRetryAfterParams, true\n\t\tdefault:\n\t\t\treturn nil, false\n\t\t}\n\t})\n}","line":{"from":55,"to":81}} {"id":100018004,"name":"withRetryAfter","signature":"func withRetryAfter(handler http.Handler, isRequestExemptFn isRequestExemptFunc, shouldRespondWithRetryAfterFn shouldRespondWithRetryAfterFunc) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/server/filters/with_retry_after.go","code":"func withRetryAfter(handler http.Handler, isRequestExemptFn isRequestExemptFunc, shouldRespondWithRetryAfterFn shouldRespondWithRetryAfterFunc) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tparams, send := shouldRespondWithRetryAfterFn()\n\t\tif !send || isRequestExemptFn(req) {\n\t\t\thandler.ServeHTTP(w, req)\n\t\t\treturn\n\t\t}\n\n\t\t// If we are here this means it's time to send Retry-After response\n\t\t//\n\t\t// Copied from net/http2 library\n\t\t// \"Connection\" headers aren't allowed in HTTP/2 (RFC 7540, 8.1.2.2),\n\t\t// but respect \"Connection\" == \"close\" to mean sending a GOAWAY and tearing\n\t\t// down the TCP connection when idle, like we do for HTTP/1.\n\t\tif params.TearDownConnection {\n\t\t\tw.Header().Set(\"Connection\", \"close\")\n\t\t}\n\n\t\t// Return a 429 status asking the client to try again after 5 seconds\n\t\tw.Header().Set(\"Retry-After\", \"5\")\n\t\thttp.Error(w, params.Message, http.StatusTooManyRequests)\n\t})\n}","line":{"from":83,"to":105}} {"id":100018005,"name":"isRequestExemptFromRetryAfter","signature":"func isRequestExemptFromRetryAfter(r *http.Request) bool","file":"staging/src/k8s.io/apiserver/pkg/server/filters/with_retry_after.go","code":"// isRequestExemptFromRetryAfter returns true if the given request should be exempt\n// from being rejected with a 'Retry-After' response.\n// NOTE: both 'WithRetryAfter' and 'WithWaitGroup' filters should use this function\n// to exempt the set of requests from being rejected or tracked.\nfunc isRequestExemptFromRetryAfter(r *http.Request) bool {\n\treturn isKubeApiserverUserAgent(r) || hasExemptPathPrefix(r)\n}","line":{"from":107,"to":113}} {"id":100018006,"name":"isKubeApiserverUserAgent","signature":"func isKubeApiserverUserAgent(req *http.Request) bool","file":"staging/src/k8s.io/apiserver/pkg/server/filters/with_retry_after.go","code":"// isKubeApiserverUserAgent returns true if the user-agent matches\n// the one set by the local loopback.\n// NOTE: we can't look up the authenticated user informaion from the\n// request context since the authentication filter has not executed yet.\nfunc isKubeApiserverUserAgent(req *http.Request) bool {\n\treturn strings.HasPrefix(req.UserAgent(), \"kube-apiserver/\")\n}","line":{"from":115,"to":121}} {"id":100018007,"name":"hasExemptPathPrefix","signature":"func hasExemptPathPrefix(r *http.Request) bool","file":"staging/src/k8s.io/apiserver/pkg/server/filters/with_retry_after.go","code":"func hasExemptPathPrefix(r *http.Request) bool {\n\tfor _, whiteListedPrefix := range pathPrefixesExemptFromRetryAfter {\n\t\tif strings.HasPrefix(r.URL.Path, whiteListedPrefix) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":123,"to":130}} {"id":100018008,"name":"WithPanicRecovery","signature":"func WithPanicRecovery(handler http.Handler, resolver request.RequestInfoResolver) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/server/filters/wrap.go","code":"// WithPanicRecovery wraps an http Handler to recover and log panics (except in the special case of http.ErrAbortHandler panics, which suppress logging).\nfunc WithPanicRecovery(handler http.Handler, resolver request.RequestInfoResolver) http.Handler {\n\treturn withPanicRecovery(handler, func(w http.ResponseWriter, req *http.Request, err interface{}) {\n\t\tif err == http.ErrAbortHandler {\n\t\t\t// Honor the http.ErrAbortHandler sentinel panic value\n\t\t\t//\n\t\t\t// If ServeHTTP panics, the server (the caller of ServeHTTP) assumes\n\t\t\t// that the effect of the panic was isolated to the active request.\n\t\t\t// It recovers the panic, logs a stack trace to the server error log,\n\t\t\t// and either closes the network connection or sends an HTTP/2\n\t\t\t// RST_STREAM, depending on the HTTP protocol. To abort a handler so\n\t\t\t// the client sees an interrupted response but the server doesn't log\n\t\t\t// an error, panic with the value ErrAbortHandler.\n\t\t\t//\n\t\t\t// Note that HandleCrash function is actually crashing, after calling the handlers\n\t\t\tif info, err := resolver.NewRequestInfo(req); err != nil {\n\t\t\t\tmetrics.RecordRequestAbort(req, nil)\n\t\t\t} else {\n\t\t\t\tmetrics.RecordRequestAbort(req, info)\n\t\t\t}\n\t\t\t// This call can have different handlers, but the default chain rate limits. Call it after the metrics are updated\n\t\t\t// in case the rate limit delays it. If you outrun the rate for this one timed out requests, something has gone\n\t\t\t// seriously wrong with your server, but generally having a logging signal for timeouts is useful.\n\t\t\truntime.HandleError(fmt.Errorf(\"timeout or abort while handling: method=%v URI=%q audit-ID=%q\", req.Method, req.RequestURI, audit.GetAuditIDTruncated(req.Context())))\n\t\t\treturn\n\t\t}\n\t\thttp.Error(w, \"This request caused apiserver to panic. Look in the logs for details.\", http.StatusInternalServerError)\n\t\tklog.ErrorS(nil, \"apiserver panic'd\", \"method\", req.Method, \"URI\", req.RequestURI, \"auditID\", audit.GetAuditIDTruncated(req.Context()))\n\t})\n}","line":{"from":31,"to":60}} {"id":100018009,"name":"WithHTTPLogging","signature":"func WithHTTPLogging(handler http.Handler) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/server/filters/wrap.go","code":"// WithHTTPLogging enables logging of incoming requests.\nfunc WithHTTPLogging(handler http.Handler) http.Handler {\n\treturn httplog.WithLogging(handler, httplog.DefaultStacktracePred)\n}","line":{"from":62,"to":65}} {"id":100018010,"name":"withPanicRecovery","signature":"func withPanicRecovery(handler http.Handler, crashHandler func(http.ResponseWriter, *http.Request, interface{})) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/server/filters/wrap.go","code":"func withPanicRecovery(handler http.Handler, crashHandler func(http.ResponseWriter, *http.Request, interface{})) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tdefer runtime.HandleCrash(func(err interface{}) {\n\t\t\tcrashHandler(w, req, err)\n\t\t})\n\n\t\t// Dispatch to the internal handler\n\t\thandler.ServeHTTP(w, req)\n\t})\n}","line":{"from":67,"to":76}} {"id":100018011,"name":"destroyStorage","signature":"func (a *APIGroupInfo) destroyStorage()","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"func (a *APIGroupInfo) destroyStorage() {\n\tfor _, stores := range a.VersionedResourcesStorageMap {\n\t\tfor _, store := range stores {\n\t\t\tstore.Destroy()\n\t\t}\n\t}\n}","line":{"from":95,"to":101}} {"id":100018012,"name":"UnprotectedHandler","signature":"func (s *GenericAPIServer) UnprotectedHandler() http.Handler","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"func (s *GenericAPIServer) UnprotectedHandler() http.Handler {\n\t// when we delegate, we need the server we're delegating to choose whether or not to use gorestful\n\treturn s.Handler.Director\n}","line":{"from":321,"to":324}} {"id":100018013,"name":"PostStartHooks","signature":"func (s *GenericAPIServer) PostStartHooks() map[string]postStartHookEntry","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"func (s *GenericAPIServer) PostStartHooks() map[string]postStartHookEntry {\n\treturn s.postStartHooks\n}","line":{"from":325,"to":327}} {"id":100018014,"name":"PreShutdownHooks","signature":"func (s *GenericAPIServer) PreShutdownHooks() map[string]preShutdownHookEntry","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"func (s *GenericAPIServer) PreShutdownHooks() map[string]preShutdownHookEntry {\n\treturn s.preShutdownHooks\n}","line":{"from":328,"to":330}} {"id":100018015,"name":"HealthzChecks","signature":"func (s *GenericAPIServer) HealthzChecks() []healthz.HealthChecker","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"func (s *GenericAPIServer) HealthzChecks() []healthz.HealthChecker {\n\treturn s.healthzChecks\n}","line":{"from":331,"to":333}} {"id":100018016,"name":"ListedPaths","signature":"func (s *GenericAPIServer) ListedPaths() []string","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"func (s *GenericAPIServer) ListedPaths() []string {\n\treturn s.listedPathProvider.ListedPaths()\n}","line":{"from":334,"to":336}} {"id":100018017,"name":"NextDelegate","signature":"func (s *GenericAPIServer) NextDelegate() DelegationTarget","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"func (s *GenericAPIServer) NextDelegate() DelegationTarget {\n\treturn s.delegationTarget\n}","line":{"from":338,"to":340}} {"id":100018018,"name":"RegisterMuxAndDiscoveryCompleteSignal","signature":"func (s *GenericAPIServer) RegisterMuxAndDiscoveryCompleteSignal(signalName string, signal \u003c-chan struct{}) error","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"// RegisterMuxAndDiscoveryCompleteSignal registers the given signal that will be used to determine if all known\n// HTTP paths have been registered. It is okay to call this method after instantiating the generic server but before running.\nfunc (s *GenericAPIServer) RegisterMuxAndDiscoveryCompleteSignal(signalName string, signal \u003c-chan struct{}) error {\n\tif _, exists := s.muxAndDiscoveryCompleteSignals[signalName]; exists {\n\t\treturn fmt.Errorf(\"%s already registered\", signalName)\n\t}\n\ts.muxAndDiscoveryCompleteSignals[signalName] = signal\n\treturn nil\n}","line":{"from":342,"to":350}} {"id":100018019,"name":"MuxAndDiscoveryCompleteSignals","signature":"func (s *GenericAPIServer) MuxAndDiscoveryCompleteSignals() map[string]\u003c-chan struct{}","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"func (s *GenericAPIServer) MuxAndDiscoveryCompleteSignals() map[string]\u003c-chan struct{} {\n\treturn s.muxAndDiscoveryCompleteSignals\n}","line":{"from":352,"to":354}} {"id":100018020,"name":"RegisterDestroyFunc","signature":"func (s *GenericAPIServer) RegisterDestroyFunc(destroyFn func())","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"// RegisterDestroyFunc registers a function that will be called during Destroy().\n// The function have to be idempotent and prepared to be called more than once.\nfunc (s *GenericAPIServer) RegisterDestroyFunc(destroyFn func()) {\n\ts.destroyFns = append(s.destroyFns, destroyFn)\n}","line":{"from":356,"to":360}} {"id":100018021,"name":"Destroy","signature":"func (s *GenericAPIServer) Destroy()","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"// Destroy cleans up all its and its delegation target resources on shutdown.\n// It starts with destroying its own resources and later proceeds with\n// its delegation target.\nfunc (s *GenericAPIServer) Destroy() {\n\tfor _, destroyFn := range s.destroyFns {\n\t\tdestroyFn()\n\t}\n\tif s.delegationTarget != nil {\n\t\ts.delegationTarget.Destroy()\n\t}\n}","line":{"from":362,"to":372}} {"id":100018022,"name":"NewEmptyDelegate","signature":"func NewEmptyDelegate() DelegationTarget","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"func NewEmptyDelegate() DelegationTarget {\n\treturn emptyDelegate{}\n}","line":{"from":380,"to":382}} {"id":100018023,"name":"NewEmptyDelegateWithCustomHandler","signature":"func NewEmptyDelegateWithCustomHandler(handler http.Handler) DelegationTarget","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"// NewEmptyDelegateWithCustomHandler allows for registering a custom handler usually for special handling of 404 requests\nfunc NewEmptyDelegateWithCustomHandler(handler http.Handler) DelegationTarget {\n\treturn emptyDelegate{handler}\n}","line":{"from":384,"to":387}} {"id":100018024,"name":"UnprotectedHandler","signature":"func (s emptyDelegate) UnprotectedHandler() http.Handler","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"func (s emptyDelegate) UnprotectedHandler() http.Handler {\n\treturn s.handler\n}","line":{"from":389,"to":391}} {"id":100018025,"name":"PostStartHooks","signature":"func (s emptyDelegate) PostStartHooks() map[string]postStartHookEntry","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"func (s emptyDelegate) PostStartHooks() map[string]postStartHookEntry {\n\treturn map[string]postStartHookEntry{}\n}","line":{"from":392,"to":394}} {"id":100018026,"name":"PreShutdownHooks","signature":"func (s emptyDelegate) PreShutdownHooks() map[string]preShutdownHookEntry","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"func (s emptyDelegate) PreShutdownHooks() map[string]preShutdownHookEntry {\n\treturn map[string]preShutdownHookEntry{}\n}","line":{"from":395,"to":397}} {"id":100018027,"name":"HealthzChecks","signature":"func (s emptyDelegate) HealthzChecks() []healthz.HealthChecker","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"func (s emptyDelegate) HealthzChecks() []healthz.HealthChecker {\n\treturn []healthz.HealthChecker{}\n}","line":{"from":398,"to":400}} {"id":100018028,"name":"ListedPaths","signature":"func (s emptyDelegate) ListedPaths() []string","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"func (s emptyDelegate) ListedPaths() []string {\n\treturn []string{}\n}","line":{"from":401,"to":403}} {"id":100018029,"name":"NextDelegate","signature":"func (s emptyDelegate) NextDelegate() DelegationTarget","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"func (s emptyDelegate) NextDelegate() DelegationTarget {\n\treturn nil\n}","line":{"from":404,"to":406}} {"id":100018030,"name":"PrepareRun","signature":"func (s emptyDelegate) PrepareRun() preparedGenericAPIServer","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"func (s emptyDelegate) PrepareRun() preparedGenericAPIServer {\n\treturn preparedGenericAPIServer{nil}\n}","line":{"from":407,"to":409}} {"id":100018031,"name":"MuxAndDiscoveryCompleteSignals","signature":"func (s emptyDelegate) MuxAndDiscoveryCompleteSignals() map[string]\u003c-chan struct{}","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"func (s emptyDelegate) MuxAndDiscoveryCompleteSignals() map[string]\u003c-chan struct{} {\n\treturn map[string]\u003c-chan struct{}{}\n}","line":{"from":410,"to":412}} {"id":100018032,"name":"Destroy","signature":"func (s emptyDelegate) Destroy()","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"func (s emptyDelegate) Destroy() {\n}","line":{"from":413,"to":414}} {"id":100018033,"name":"PrepareRun","signature":"func (s *GenericAPIServer) PrepareRun() preparedGenericAPIServer","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"// PrepareRun does post API installation setup steps. It calls recursively the same function of the delegates.\nfunc (s *GenericAPIServer) PrepareRun() preparedGenericAPIServer {\n\ts.delegationTarget.PrepareRun()\n\n\tif s.openAPIConfig != nil \u0026\u0026 !s.skipOpenAPIInstallation {\n\t\ts.OpenAPIVersionedService, s.StaticOpenAPISpec = routes.OpenAPI{\n\t\t\tConfig: s.openAPIConfig,\n\t\t}.InstallV2(s.Handler.GoRestfulContainer, s.Handler.NonGoRestfulMux)\n\t}\n\n\tif s.openAPIV3Config != nil \u0026\u0026 !s.skipOpenAPIInstallation {\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.OpenAPIV3) {\n\t\t\ts.OpenAPIV3VersionedService = routes.OpenAPI{\n\t\t\t\tConfig: s.openAPIV3Config,\n\t\t\t}.InstallV3(s.Handler.GoRestfulContainer, s.Handler.NonGoRestfulMux)\n\t\t}\n\t}\n\n\ts.installHealthz()\n\ts.installLivez()\n\n\t// as soon as shutdown is initiated, readiness should start failing\n\treadinessStopCh := s.lifecycleSignals.ShutdownInitiated.Signaled()\n\terr := s.addReadyzShutdownCheck(readinessStopCh)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to install readyz shutdown check %s\", err)\n\t}\n\ts.installReadyz()\n\n\treturn preparedGenericAPIServer{s}\n}","line":{"from":421,"to":451}} {"id":100018034,"name":"Run","signature":"func (s preparedGenericAPIServer) Run(stopCh \u003c-chan struct{}) error","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"// Run spawns the secure http server. It only returns if stopCh is closed\n// or the secure port cannot be listened on initially.\n// This is the diagram of what channels/signals are dependent on each other:\n//\n// | stopCh\n// | |\n// | ---------------------------------------------------------\n// | | |\n// | ShutdownInitiated (shutdownInitiatedCh) |\n// | | |\n// | (ShutdownDelayDuration) (PreShutdownHooks)\n// | | |\n// | AfterShutdownDelayDuration (delayedStopCh) PreShutdownHooksStopped (preShutdownHooksHasStoppedCh)\n// | | |\n// | |-------------------------------------------------------|\n// | |\n// | |\n// | NotAcceptingNewRequest (notAcceptingNewRequestCh)\n// | |\n// | |\n// | |----------------------------------------------------------------------------------|\n// | | | | |\n// | [without [with | |\n// | ShutdownSendRetryAfter] ShutdownSendRetryAfter] | |\n// | | | | |\n// | | ---------------| |\n// | | | |\n// | | |----------------|-----------------------| |\n// | | | | |\n// | | (NonLongRunningRequestWaitGroup::Wait) (WatchRequestWaitGroup::Wait) |\n// | | | | |\n// | | |------------------|---------------------| |\n// | | | |\n// | | InFlightRequestsDrained (drainedCh) |\n// | | | |\n// | |-------------------|---------------------|----------------------------------------|\n// | | |\n// | stopHttpServerCh (AuditBackend::Shutdown())\n// | |\n// | listenerStoppedCh\n// | |\n// | HTTPServerStoppedListening (httpServerStoppedListeningCh)\nfunc (s preparedGenericAPIServer) Run(stopCh \u003c-chan struct{}) error {\n\tdelayedStopCh := s.lifecycleSignals.AfterShutdownDelayDuration\n\tshutdownInitiatedCh := s.lifecycleSignals.ShutdownInitiated\n\n\t// Clean up resources on shutdown.\n\tdefer s.Destroy()\n\n\t// If UDS profiling is enabled, start a local http server listening on that socket\n\tif s.UnprotectedDebugSocket != nil {\n\t\tgo func() {\n\t\t\tdefer utilruntime.HandleCrash()\n\t\t\tklog.Error(s.UnprotectedDebugSocket.Run(stopCh))\n\t\t}()\n\t}\n\n\t// spawn a new goroutine for closing the MuxAndDiscoveryComplete signal\n\t// registration happens during construction of the generic api server\n\t// the last server in the chain aggregates signals from the previous instances\n\tgo func() {\n\t\tfor _, muxAndDiscoveryCompletedSignal := range s.GenericAPIServer.MuxAndDiscoveryCompleteSignals() {\n\t\t\tselect {\n\t\t\tcase \u003c-muxAndDiscoveryCompletedSignal:\n\t\t\t\tcontinue\n\t\t\tcase \u003c-stopCh:\n\t\t\t\tklog.V(1).Infof(\"haven't completed %s, stop requested\", s.lifecycleSignals.MuxAndDiscoveryComplete.Name())\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\ts.lifecycleSignals.MuxAndDiscoveryComplete.Signal()\n\t\tklog.V(1).Infof(\"%s has all endpoints registered and discovery information is complete\", s.lifecycleSignals.MuxAndDiscoveryComplete.Name())\n\t}()\n\n\tgo func() {\n\t\tdefer delayedStopCh.Signal()\n\t\tdefer klog.V(1).InfoS(\"[graceful-termination] shutdown event\", \"name\", delayedStopCh.Name())\n\n\t\t\u003c-stopCh\n\n\t\t// As soon as shutdown is initiated, /readyz should start returning failure.\n\t\t// This gives the load balancer a window defined by ShutdownDelayDuration to detect that /readyz is red\n\t\t// and stop sending traffic to this server.\n\t\tshutdownInitiatedCh.Signal()\n\t\tklog.V(1).InfoS(\"[graceful-termination] shutdown event\", \"name\", shutdownInitiatedCh.Name())\n\n\t\ttime.Sleep(s.ShutdownDelayDuration)\n\t}()\n\n\t// close socket after delayed stopCh\n\tshutdownTimeout := s.ShutdownTimeout\n\tif s.ShutdownSendRetryAfter {\n\t\t// when this mode is enabled, we do the following:\n\t\t// - the server will continue to listen until all existing requests in flight\n\t\t// (not including active long running requests) have been drained.\n\t\t// - once drained, http Server Shutdown is invoked with a timeout of 2s,\n\t\t// net/http waits for 1s for the peer to respond to a GO_AWAY frame, so\n\t\t// we should wait for a minimum of 2s\n\t\tshutdownTimeout = 2 * time.Second\n\t\tklog.V(1).InfoS(\"[graceful-termination] using HTTP Server shutdown timeout\", \"shutdownTimeout\", shutdownTimeout)\n\t}\n\n\tnotAcceptingNewRequestCh := s.lifecycleSignals.NotAcceptingNewRequest\n\tdrainedCh := s.lifecycleSignals.InFlightRequestsDrained\n\tstopHttpServerCh := make(chan struct{})\n\tgo func() {\n\t\tdefer close(stopHttpServerCh)\n\n\t\ttimeToStopHttpServerCh := notAcceptingNewRequestCh.Signaled()\n\t\tif s.ShutdownSendRetryAfter {\n\t\t\ttimeToStopHttpServerCh = drainedCh.Signaled()\n\t\t}\n\n\t\t\u003c-timeToStopHttpServerCh\n\t}()\n\n\t// Start the audit backend before any request comes in. This means we must call Backend.Run\n\t// before http server start serving. Otherwise the Backend.ProcessEvents call might block.\n\t// AuditBackend.Run will stop as soon as all in-flight requests are drained.\n\tif s.AuditBackend != nil {\n\t\tif err := s.AuditBackend.Run(drainedCh.Signaled()); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to run the audit backend: %v\", err)\n\t\t}\n\t}\n\n\tstoppedCh, listenerStoppedCh, err := s.NonBlockingRun(stopHttpServerCh, shutdownTimeout)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\thttpServerStoppedListeningCh := s.lifecycleSignals.HTTPServerStoppedListening\n\tgo func() {\n\t\t\u003c-listenerStoppedCh\n\t\thttpServerStoppedListeningCh.Signal()\n\t\tklog.V(1).InfoS(\"[graceful-termination] shutdown event\", \"name\", httpServerStoppedListeningCh.Name())\n\t}()\n\n\t// we don't accept new request as soon as both ShutdownDelayDuration has\n\t// elapsed and preshutdown hooks have completed.\n\tpreShutdownHooksHasStoppedCh := s.lifecycleSignals.PreShutdownHooksStopped\n\tgo func() {\n\t\tdefer klog.V(1).InfoS(\"[graceful-termination] shutdown event\", \"name\", notAcceptingNewRequestCh.Name())\n\t\tdefer notAcceptingNewRequestCh.Signal()\n\n\t\t// wait for the delayed stopCh before closing the handler chain\n\t\t\u003c-delayedStopCh.Signaled()\n\n\t\t// Additionally wait for preshutdown hooks to also be finished, as some of them need\n\t\t// to send API calls to clean up after themselves (e.g. lease reconcilers removing\n\t\t// itself from the active servers).\n\t\t\u003c-preShutdownHooksHasStoppedCh.Signaled()\n\t}()\n\n\t// wait for all in-flight non-long running requests to finish\n\tnonLongRunningRequestDrainedCh := make(chan struct{})\n\tgo func() {\n\t\tdefer close(nonLongRunningRequestDrainedCh)\n\t\tdefer klog.V(1).Info(\"[graceful-termination] in-flight non long-running request(s) have drained\")\n\n\t\t// wait for the delayed stopCh before closing the handler chain (it rejects everything after Wait has been called).\n\t\t\u003c-notAcceptingNewRequestCh.Signaled()\n\n\t\t// Wait for all requests to finish, which are bounded by the RequestTimeout variable.\n\t\t// once NonLongRunningRequestWaitGroup.Wait is invoked, the apiserver is\n\t\t// expected to reject any incoming request with a {503, Retry-After}\n\t\t// response via the WithWaitGroup filter. On the contrary, we observe\n\t\t// that incoming request(s) get a 'connection refused' error, this is\n\t\t// because, at this point, we have called 'Server.Shutdown' and\n\t\t// net/http server has stopped listening. This causes incoming\n\t\t// request to get a 'connection refused' error.\n\t\t// On the other hand, if 'ShutdownSendRetryAfter' is enabled incoming\n\t\t// requests will be rejected with a {429, Retry-After} since\n\t\t// 'Server.Shutdown' will be invoked only after in-flight requests\n\t\t// have been drained.\n\t\t// TODO: can we consolidate these two modes of graceful termination?\n\t\ts.NonLongRunningRequestWaitGroup.Wait()\n\t}()\n\n\t// wait for all in-flight watches to finish\n\tactiveWatchesDrainedCh := make(chan struct{})\n\tgo func() {\n\t\tdefer close(activeWatchesDrainedCh)\n\n\t\t\u003c-notAcceptingNewRequestCh.Signaled()\n\t\tif s.ShutdownWatchTerminationGracePeriod \u003c= time.Duration(0) {\n\t\t\tklog.V(1).InfoS(\"[graceful-termination] not going to wait for active watch request(s) to drain\")\n\t\t\treturn\n\t\t}\n\n\t\t// Wait for all active watches to finish\n\t\tgrace := s.ShutdownWatchTerminationGracePeriod\n\t\tactiveBefore, activeAfter, err := s.WatchRequestWaitGroup.Wait(func(count int) (utilwaitgroup.RateLimiter, context.Context, context.CancelFunc) {\n\t\t\tqps := float64(count) / grace.Seconds()\n\t\t\t// TODO: we don't want the QPS (max requests drained per second) to\n\t\t\t// get below a certain floor value, since we want the server to\n\t\t\t// drain the active watch requests as soon as possible.\n\t\t\t// For now, it's hard coded to 200, and it is subject to change\n\t\t\t// based on the result from the scale testing.\n\t\t\tif qps \u003c 200 {\n\t\t\t\tqps = 200\n\t\t\t}\n\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), grace)\n\t\t\t// We don't expect more than one token to be consumed\n\t\t\t// in a single Wait call, so setting burst to 1.\n\t\t\treturn rate.NewLimiter(rate.Limit(qps), 1), ctx, cancel\n\t\t})\n\t\tklog.V(1).InfoS(\"[graceful-termination] active watch request(s) have drained\",\n\t\t\t\"duration\", grace, \"activeWatchesBefore\", activeBefore, \"activeWatchesAfter\", activeAfter, \"error\", err)\n\t}()\n\n\tgo func() {\n\t\tdefer klog.V(1).InfoS(\"[graceful-termination] shutdown event\", \"name\", drainedCh.Name())\n\t\tdefer drainedCh.Signal()\n\n\t\t\u003c-nonLongRunningRequestDrainedCh\n\t\t\u003c-activeWatchesDrainedCh\n\t}()\n\n\tklog.V(1).Info(\"[graceful-termination] waiting for shutdown to be initiated\")\n\t\u003c-stopCh\n\n\t// run shutdown hooks directly. This includes deregistering from\n\t// the kubernetes endpoint in case of kube-apiserver.\n\tfunc() {\n\t\tdefer func() {\n\t\t\tpreShutdownHooksHasStoppedCh.Signal()\n\t\t\tklog.V(1).InfoS(\"[graceful-termination] pre-shutdown hooks completed\", \"name\", preShutdownHooksHasStoppedCh.Name())\n\t\t}()\n\t\terr = s.RunPreShutdownHooks()\n\t}()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Wait for all requests in flight to drain, bounded by the RequestTimeout variable.\n\t\u003c-drainedCh.Signaled()\n\n\tif s.AuditBackend != nil {\n\t\ts.AuditBackend.Shutdown()\n\t\tklog.V(1).InfoS(\"[graceful-termination] audit backend shutdown completed\")\n\t}\n\n\t// wait for stoppedCh that is closed when the graceful termination (server.Shutdown) is finished.\n\t\u003c-listenerStoppedCh\n\t\u003c-stoppedCh\n\n\tklog.V(1).Info(\"[graceful-termination] apiserver is exiting\")\n\treturn nil\n}","line":{"from":453,"to":702}} {"id":100018035,"name":"NonBlockingRun","signature":"func (s preparedGenericAPIServer) NonBlockingRun(stopCh \u003c-chan struct{}, shutdownTimeout time.Duration) (\u003c-chan struct{}, \u003c-chan struct{}, error)","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"// NonBlockingRun spawns the secure http server. An error is\n// returned if the secure port cannot be listened on.\n// The returned channel is closed when the (asynchronous) termination is finished.\nfunc (s preparedGenericAPIServer) NonBlockingRun(stopCh \u003c-chan struct{}, shutdownTimeout time.Duration) (\u003c-chan struct{}, \u003c-chan struct{}, error) {\n\t// Use an internal stop channel to allow cleanup of the listeners on error.\n\tinternalStopCh := make(chan struct{})\n\tvar stoppedCh \u003c-chan struct{}\n\tvar listenerStoppedCh \u003c-chan struct{}\n\tif s.SecureServingInfo != nil \u0026\u0026 s.Handler != nil {\n\t\tvar err error\n\t\tstoppedCh, listenerStoppedCh, err = s.SecureServingInfo.Serve(s.Handler, shutdownTimeout, internalStopCh)\n\t\tif err != nil {\n\t\t\tclose(internalStopCh)\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\t// Now that listener have bound successfully, it is the\n\t// responsibility of the caller to close the provided channel to\n\t// ensure cleanup.\n\tgo func() {\n\t\t\u003c-stopCh\n\t\tclose(internalStopCh)\n\t}()\n\n\ts.RunPostStartHooks(stopCh)\n\n\tif _, err := systemd.SdNotify(true, \"READY=1\\n\"); err != nil {\n\t\tklog.Errorf(\"Unable to send systemd daemon successful start message: %v\\n\", err)\n\t}\n\n\treturn stoppedCh, listenerStoppedCh, nil\n}","line":{"from":704,"to":736}} {"id":100018036,"name":"installAPIResources","signature":"func (s *GenericAPIServer) installAPIResources(apiPrefix string, apiGroupInfo *APIGroupInfo, openAPIModels map[string]*spec.Schema) error","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"// installAPIResources is a private method for installing the REST storage backing each api groupversionresource\nfunc (s *GenericAPIServer) installAPIResources(apiPrefix string, apiGroupInfo *APIGroupInfo, openAPIModels map[string]*spec.Schema) error {\n\tvar typeConverter managedfields.TypeConverter\n\n\tif len(openAPIModels) \u003e 0 {\n\t\tvar err error\n\t\ttypeConverter, err = managedfields.NewTypeConverter(openAPIModels, false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tvar resourceInfos []*storageversion.ResourceInfo\n\tfor _, groupVersion := range apiGroupInfo.PrioritizedVersions {\n\t\tif len(apiGroupInfo.VersionedResourcesStorageMap[groupVersion.Version]) == 0 {\n\t\t\tklog.Warningf(\"Skipping API %v because it has no resources.\", groupVersion)\n\t\t\tcontinue\n\t\t}\n\n\t\tapiGroupVersion, err := s.getAPIGroupVersion(apiGroupInfo, groupVersion, apiPrefix)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif apiGroupInfo.OptionsExternalVersion != nil {\n\t\t\tapiGroupVersion.OptionsExternalVersion = apiGroupInfo.OptionsExternalVersion\n\t\t}\n\t\tapiGroupVersion.TypeConverter = typeConverter\n\t\tapiGroupVersion.MaxRequestBodyBytes = s.maxRequestBodyBytes\n\n\t\tdiscoveryAPIResources, r, err := apiGroupVersion.InstallREST(s.Handler.GoRestfulContainer)\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to setup API %v: %v\", apiGroupInfo, err)\n\t\t}\n\t\tresourceInfos = append(resourceInfos, r...)\n\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.AggregatedDiscoveryEndpoint) {\n\t\t\t// Aggregated discovery only aggregates resources under /apis\n\t\t\tif apiPrefix == APIGroupPrefix {\n\t\t\t\ts.AggregatedDiscoveryGroupManager.AddGroupVersion(\n\t\t\t\t\tgroupVersion.Group,\n\t\t\t\t\tapidiscoveryv2beta1.APIVersionDiscovery{\n\t\t\t\t\t\tFreshness: apidiscoveryv2beta1.DiscoveryFreshnessCurrent,\n\t\t\t\t\t\tVersion: groupVersion.Version,\n\t\t\t\t\t\tResources: discoveryAPIResources,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\t// There is only one group version for legacy resources, priority can be defaulted to 0.\n\t\t\t\ts.AggregatedLegacyDiscoveryGroupManager.AddGroupVersion(\n\t\t\t\t\tgroupVersion.Group,\n\t\t\t\t\tapidiscoveryv2beta1.APIVersionDiscovery{\n\t\t\t\t\t\tFreshness: apidiscoveryv2beta1.DiscoveryFreshnessCurrent,\n\t\t\t\t\t\tVersion: groupVersion.Version,\n\t\t\t\t\t\tResources: discoveryAPIResources,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t}\n\n\ts.RegisterDestroyFunc(apiGroupInfo.destroyStorage)\n\n\tif utilfeature.DefaultFeatureGate.Enabled(features.StorageVersionAPI) \u0026\u0026\n\t\tutilfeature.DefaultFeatureGate.Enabled(features.APIServerIdentity) {\n\t\t// API installation happens before we start listening on the handlers,\n\t\t// therefore it is safe to register ResourceInfos here. The handler will block\n\t\t// write requests until the storage versions of the targeting resources are updated.\n\t\ts.StorageVersionManager.AddResourceInfo(resourceInfos...)\n\t}\n\n\treturn nil\n}","line":{"from":738,"to":810}} {"id":100018037,"name":"InstallLegacyAPIGroup","signature":"func (s *GenericAPIServer) InstallLegacyAPIGroup(apiPrefix string, apiGroupInfo *APIGroupInfo) error","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"// InstallLegacyAPIGroup exposes the given legacy api group in the API.\n// The \u003capiGroupInfo\u003e passed into this function shouldn't be used elsewhere as the\n// underlying storage will be destroyed on this servers shutdown.\nfunc (s *GenericAPIServer) InstallLegacyAPIGroup(apiPrefix string, apiGroupInfo *APIGroupInfo) error {\n\tif !s.legacyAPIGroupPrefixes.Has(apiPrefix) {\n\t\treturn fmt.Errorf(\"%q is not in the allowed legacy API prefixes: %v\", apiPrefix, s.legacyAPIGroupPrefixes.List())\n\t}\n\n\topenAPIModels, err := s.getOpenAPIModels(apiPrefix, apiGroupInfo)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to get openapi models: %v\", err)\n\t}\n\n\tif err := s.installAPIResources(apiPrefix, apiGroupInfo, openAPIModels); err != nil {\n\t\treturn err\n\t}\n\n\t// Install the version handler.\n\t// Add a handler at /\u003capiPrefix\u003e to enumerate the supported api versions.\n\tlegacyRootAPIHandler := discovery.NewLegacyRootAPIHandler(s.discoveryAddresses, s.Serializer, apiPrefix)\n\tif utilfeature.DefaultFeatureGate.Enabled(features.AggregatedDiscoveryEndpoint) {\n\t\twrapped := discoveryendpoint.WrapAggregatedDiscoveryToHandler(legacyRootAPIHandler, s.AggregatedLegacyDiscoveryGroupManager)\n\t\ts.Handler.GoRestfulContainer.Add(wrapped.GenerateWebService(\"/api\", metav1.APIVersions{}))\n\t} else {\n\t\ts.Handler.GoRestfulContainer.Add(legacyRootAPIHandler.WebService())\n\t}\n\n\treturn nil\n}","line":{"from":812,"to":840}} {"id":100018038,"name":"InstallAPIGroups","signature":"func (s *GenericAPIServer) InstallAPIGroups(apiGroupInfos ...*APIGroupInfo) error","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"// InstallAPIGroups exposes given api groups in the API.\n// The \u003capiGroupInfos\u003e passed into this function shouldn't be used elsewhere as the\n// underlying storage will be destroyed on this servers shutdown.\nfunc (s *GenericAPIServer) InstallAPIGroups(apiGroupInfos ...*APIGroupInfo) error {\n\tfor _, apiGroupInfo := range apiGroupInfos {\n\t\t// Do not register empty group or empty version. Doing so claims /apis/ for the wrong entity to be returned.\n\t\t// Catching these here places the error much closer to its origin\n\t\tif len(apiGroupInfo.PrioritizedVersions[0].Group) == 0 {\n\t\t\treturn fmt.Errorf(\"cannot register handler with an empty group for %#v\", *apiGroupInfo)\n\t\t}\n\t\tif len(apiGroupInfo.PrioritizedVersions[0].Version) == 0 {\n\t\t\treturn fmt.Errorf(\"cannot register handler with an empty version for %#v\", *apiGroupInfo)\n\t\t}\n\t}\n\n\topenAPIModels, err := s.getOpenAPIModels(APIGroupPrefix, apiGroupInfos...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to get openapi models: %v\", err)\n\t}\n\n\tfor _, apiGroupInfo := range apiGroupInfos {\n\t\tif err := s.installAPIResources(APIGroupPrefix, apiGroupInfo, openAPIModels); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to install api resources: %v\", err)\n\t\t}\n\n\t\t// setup discovery\n\t\t// Install the version handler.\n\t\t// Add a handler at /apis/\u003cgroupName\u003e to enumerate all versions supported by this group.\n\t\tapiVersionsForDiscovery := []metav1.GroupVersionForDiscovery{}\n\t\tfor _, groupVersion := range apiGroupInfo.PrioritizedVersions {\n\t\t\t// Check the config to make sure that we elide versions that don't have any resources\n\t\t\tif len(apiGroupInfo.VersionedResourcesStorageMap[groupVersion.Version]) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tapiVersionsForDiscovery = append(apiVersionsForDiscovery, metav1.GroupVersionForDiscovery{\n\t\t\t\tGroupVersion: groupVersion.String(),\n\t\t\t\tVersion: groupVersion.Version,\n\t\t\t})\n\t\t}\n\t\tpreferredVersionForDiscovery := metav1.GroupVersionForDiscovery{\n\t\t\tGroupVersion: apiGroupInfo.PrioritizedVersions[0].String(),\n\t\t\tVersion: apiGroupInfo.PrioritizedVersions[0].Version,\n\t\t}\n\t\tapiGroup := metav1.APIGroup{\n\t\t\tName: apiGroupInfo.PrioritizedVersions[0].Group,\n\t\t\tVersions: apiVersionsForDiscovery,\n\t\t\tPreferredVersion: preferredVersionForDiscovery,\n\t\t}\n\n\t\ts.DiscoveryGroupManager.AddGroup(apiGroup)\n\t\ts.Handler.GoRestfulContainer.Add(discovery.NewAPIGroupHandler(s.Serializer, apiGroup).WebService())\n\t}\n\treturn nil\n}","line":{"from":842,"to":895}} {"id":100018039,"name":"InstallAPIGroup","signature":"func (s *GenericAPIServer) InstallAPIGroup(apiGroupInfo *APIGroupInfo) error","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"// InstallAPIGroup exposes the given api group in the API.\n// The \u003capiGroupInfo\u003e passed into this function shouldn't be used elsewhere as the\n// underlying storage will be destroyed on this servers shutdown.\nfunc (s *GenericAPIServer) InstallAPIGroup(apiGroupInfo *APIGroupInfo) error {\n\treturn s.InstallAPIGroups(apiGroupInfo)\n}","line":{"from":897,"to":902}} {"id":100018040,"name":"getAPIGroupVersion","signature":"func (s *GenericAPIServer) getAPIGroupVersion(apiGroupInfo *APIGroupInfo, groupVersion schema.GroupVersion, apiPrefix string) (*genericapi.APIGroupVersion, error)","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"func (s *GenericAPIServer) getAPIGroupVersion(apiGroupInfo *APIGroupInfo, groupVersion schema.GroupVersion, apiPrefix string) (*genericapi.APIGroupVersion, error) {\n\tstorage := make(map[string]rest.Storage)\n\tfor k, v := range apiGroupInfo.VersionedResourcesStorageMap[groupVersion.Version] {\n\t\tif strings.ToLower(k) != k {\n\t\t\treturn nil, fmt.Errorf(\"resource names must be lowercase only, not %q\", k)\n\t\t}\n\t\tstorage[k] = v\n\t}\n\tversion := s.newAPIGroupVersion(apiGroupInfo, groupVersion)\n\tversion.Root = apiPrefix\n\tversion.Storage = storage\n\treturn version, nil\n}","line":{"from":904,"to":916}} {"id":100018041,"name":"newAPIGroupVersion","signature":"func (s *GenericAPIServer) newAPIGroupVersion(apiGroupInfo *APIGroupInfo, groupVersion schema.GroupVersion) *genericapi.APIGroupVersion","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"func (s *GenericAPIServer) newAPIGroupVersion(apiGroupInfo *APIGroupInfo, groupVersion schema.GroupVersion) *genericapi.APIGroupVersion {\n\treturn \u0026genericapi.APIGroupVersion{\n\t\tGroupVersion: groupVersion,\n\t\tMetaGroupVersion: apiGroupInfo.MetaGroupVersion,\n\n\t\tParameterCodec: apiGroupInfo.ParameterCodec,\n\t\tSerializer: apiGroupInfo.NegotiatedSerializer,\n\t\tCreater: apiGroupInfo.Scheme,\n\t\tConvertor: apiGroupInfo.Scheme,\n\t\tConvertabilityChecker: apiGroupInfo.Scheme,\n\t\tUnsafeConvertor: runtime.UnsafeObjectConvertor(apiGroupInfo.Scheme),\n\t\tDefaulter: apiGroupInfo.Scheme,\n\t\tTyper: apiGroupInfo.Scheme,\n\t\tNamer: runtime.Namer(meta.NewAccessor()),\n\n\t\tEquivalentResourceRegistry: s.EquivalentResourceRegistry,\n\n\t\tAdmit: s.admissionControl,\n\t\tMinRequestTimeout: s.minRequestTimeout,\n\t\tAuthorizer: s.Authorizer,\n\t}\n}","line":{"from":918,"to":939}} {"id":100018042,"name":"NewDefaultAPIGroupInfo","signature":"func NewDefaultAPIGroupInfo(group string, scheme *runtime.Scheme, parameterCodec runtime.ParameterCodec, codecs serializer.CodecFactory) APIGroupInfo","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"// NewDefaultAPIGroupInfo returns an APIGroupInfo stubbed with \"normal\" values\n// exposed for easier composition from other packages\nfunc NewDefaultAPIGroupInfo(group string, scheme *runtime.Scheme, parameterCodec runtime.ParameterCodec, codecs serializer.CodecFactory) APIGroupInfo {\n\treturn APIGroupInfo{\n\t\tPrioritizedVersions: scheme.PrioritizedVersionsForGroup(group),\n\t\tVersionedResourcesStorageMap: map[string]map[string]rest.Storage{},\n\t\t// TODO unhardcode this. It was hardcoded before, but we need to re-evaluate\n\t\tOptionsExternalVersion: \u0026schema.GroupVersion{Version: \"v1\"},\n\t\tScheme: scheme,\n\t\tParameterCodec: parameterCodec,\n\t\tNegotiatedSerializer: codecs,\n\t}\n}","line":{"from":941,"to":953}} {"id":100018043,"name":"getOpenAPIModels","signature":"func (s *GenericAPIServer) getOpenAPIModels(apiPrefix string, apiGroupInfos ...*APIGroupInfo) (map[string]*spec.Schema, error)","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"// getOpenAPIModels is a private method for getting the OpenAPI models\nfunc (s *GenericAPIServer) getOpenAPIModels(apiPrefix string, apiGroupInfos ...*APIGroupInfo) (map[string]*spec.Schema, error) {\n\tif s.openAPIV3Config == nil {\n\t\t//!TODO: A future work should add a requirement that\n\t\t// OpenAPIV3 config is required. May require some refactoring of tests.\n\t\treturn nil, nil\n\t}\n\tpathsToIgnore := openapiutil.NewTrie(s.openAPIConfig.IgnorePrefixes)\n\tresourceNames := make([]string, 0)\n\tfor _, apiGroupInfo := range apiGroupInfos {\n\t\tgroupResources, err := getResourceNamesForGroup(apiPrefix, apiGroupInfo, pathsToIgnore)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresourceNames = append(resourceNames, groupResources...)\n\t}\n\n\t// Build the openapi definitions for those resources and convert it to proto models\n\topenAPISpec, err := openapibuilder3.BuildOpenAPIDefinitionsForResources(s.openAPIV3Config, resourceNames...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, apiGroupInfo := range apiGroupInfos {\n\t\tapiGroupInfo.StaticOpenAPISpec = openAPISpec\n\t}\n\treturn openAPISpec, nil\n}","line":{"from":955,"to":981}} {"id":100018044,"name":"getResourceNamesForGroup","signature":"func getResourceNamesForGroup(apiPrefix string, apiGroupInfo *APIGroupInfo, pathsToIgnore openapiutil.Trie) ([]string, error)","file":"staging/src/k8s.io/apiserver/pkg/server/genericapiserver.go","code":"// getResourceNamesForGroup is a private method for getting the canonical names for each resource to build in an api group\nfunc getResourceNamesForGroup(apiPrefix string, apiGroupInfo *APIGroupInfo, pathsToIgnore openapiutil.Trie) ([]string, error) {\n\t// Get the canonical names of every resource we need to build in this api group\n\tresourceNames := make([]string, 0)\n\tfor _, groupVersion := range apiGroupInfo.PrioritizedVersions {\n\t\tfor resource, storage := range apiGroupInfo.VersionedResourcesStorageMap[groupVersion.Version] {\n\t\t\tpath := gpath.Join(apiPrefix, groupVersion.Group, groupVersion.Version, resource)\n\t\t\tif !pathsToIgnore.HasPrefix(path) {\n\t\t\t\tkind, err := genericapi.GetResourceKind(groupVersion, storage, apiGroupInfo.Scheme)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tsampleObject, err := apiGroupInfo.Scheme.New(kind)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tname := openapiutil.GetCanonicalTypeName(sampleObject)\n\t\t\t\tresourceNames = append(resourceNames, name)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn resourceNames, nil\n}","line":{"from":983,"to":1006}} {"id":100018045,"name":"NewAPIServerHandler","signature":"func NewAPIServerHandler(name string, s runtime.NegotiatedSerializer, handlerChainBuilder HandlerChainBuilderFn, notFoundHandler http.Handler) *APIServerHandler","file":"staging/src/k8s.io/apiserver/pkg/server/handler.go","code":"func NewAPIServerHandler(name string, s runtime.NegotiatedSerializer, handlerChainBuilder HandlerChainBuilderFn, notFoundHandler http.Handler) *APIServerHandler {\n\tnonGoRestfulMux := mux.NewPathRecorderMux(name)\n\tif notFoundHandler != nil {\n\t\tnonGoRestfulMux.NotFoundHandler(notFoundHandler)\n\t}\n\n\tgorestfulContainer := restful.NewContainer()\n\tgorestfulContainer.ServeMux = http.NewServeMux()\n\tgorestfulContainer.Router(restful.CurlyRouter{}) // e.g. for proxy/{kind}/{name}/{*}\n\tgorestfulContainer.RecoverHandler(func(panicReason interface{}, httpWriter http.ResponseWriter) {\n\t\tlogStackOnRecover(s, panicReason, httpWriter)\n\t})\n\tgorestfulContainer.ServiceErrorHandler(func(serviceErr restful.ServiceError, request *restful.Request, response *restful.Response) {\n\t\tserviceErrorHandler(s, serviceErr, request, response)\n\t})\n\n\tdirector := director{\n\t\tname: name,\n\t\tgoRestfulContainer: gorestfulContainer,\n\t\tnonGoRestfulMux: nonGoRestfulMux,\n\t}\n\n\treturn \u0026APIServerHandler{\n\t\tFullHandlerChain: handlerChainBuilder(director),\n\t\tGoRestfulContainer: gorestfulContainer,\n\t\tNonGoRestfulMux: nonGoRestfulMux,\n\t\tDirector: director,\n\t}\n}","line":{"from":73,"to":101}} {"id":100018046,"name":"ListedPaths","signature":"func (a *APIServerHandler) ListedPaths() []string","file":"staging/src/k8s.io/apiserver/pkg/server/handler.go","code":"// ListedPaths returns the paths that should be shown under /\nfunc (a *APIServerHandler) ListedPaths() []string {\n\tvar handledPaths []string\n\t// Extract the paths handled using restful.WebService\n\tfor _, ws := range a.GoRestfulContainer.RegisteredWebServices() {\n\t\thandledPaths = append(handledPaths, ws.RootPath())\n\t}\n\thandledPaths = append(handledPaths, a.NonGoRestfulMux.ListedPaths()...)\n\tsort.Strings(handledPaths)\n\n\treturn handledPaths\n}","line":{"from":103,"to":114}} {"id":100018047,"name":"ServeHTTP","signature":"func (d director) ServeHTTP(w http.ResponseWriter, req *http.Request)","file":"staging/src/k8s.io/apiserver/pkg/server/handler.go","code":"func (d director) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tpath := req.URL.Path\n\n\t// check to see if our webservices want to claim this path\n\tfor _, ws := range d.goRestfulContainer.RegisteredWebServices() {\n\t\tswitch {\n\t\tcase ws.RootPath() == \"/apis\":\n\t\t\t// if we are exactly /apis or /apis/, then we need special handling in loop.\n\t\t\t// normally these are passed to the nonGoRestfulMux, but if discovery is enabled, it will go directly.\n\t\t\t// We can't rely on a prefix match since /apis matches everything (see the big comment on Director above)\n\t\t\tif path == \"/apis\" || path == \"/apis/\" {\n\t\t\t\tklog.V(5).Infof(\"%v: %v %q satisfied by gorestful with webservice %v\", d.name, req.Method, path, ws.RootPath())\n\t\t\t\t// don't use servemux here because gorestful servemuxes get messed up when removing webservices\n\t\t\t\t// TODO fix gorestful, remove TPRs, or stop using gorestful\n\t\t\t\td.goRestfulContainer.Dispatch(w, req)\n\t\t\t\treturn\n\t\t\t}\n\n\t\tcase strings.HasPrefix(path, ws.RootPath()):\n\t\t\t// ensure an exact match or a path boundary match\n\t\t\tif len(path) == len(ws.RootPath()) || path[len(ws.RootPath())] == '/' {\n\t\t\t\tklog.V(5).Infof(\"%v: %v %q satisfied by gorestful with webservice %v\", d.name, req.Method, path, ws.RootPath())\n\t\t\t\t// don't use servemux here because gorestful servemuxes get messed up when removing webservices\n\t\t\t\t// TODO fix gorestful, remove TPRs, or stop using gorestful\n\t\t\t\td.goRestfulContainer.Dispatch(w, req)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\t// if we didn't find a match, then we just skip gorestful altogether\n\tklog.V(5).Infof(\"%v: %v %q satisfied by nonGoRestful\", d.name, req.Method, path)\n\td.nonGoRestfulMux.ServeHTTP(w, req)\n}","line":{"from":122,"to":155}} {"id":100018048,"name":"logStackOnRecover","signature":"func logStackOnRecover(s runtime.NegotiatedSerializer, panicReason interface{}, w http.ResponseWriter)","file":"staging/src/k8s.io/apiserver/pkg/server/handler.go","code":"// TODO: Unify with RecoverPanics?\nfunc logStackOnRecover(s runtime.NegotiatedSerializer, panicReason interface{}, w http.ResponseWriter) {\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(fmt.Sprintf(\"recover from panic situation: - %v\\r\\n\", panicReason))\n\tfor i := 2; ; i++ {\n\t\t_, file, line, ok := rt.Caller(i)\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\tbuffer.WriteString(fmt.Sprintf(\" %s:%d\\r\\n\", file, line))\n\t}\n\tklog.Errorln(buffer.String())\n\n\theaders := http.Header{}\n\tif ct := w.Header().Get(\"Content-Type\"); len(ct) \u003e 0 {\n\t\theaders.Set(\"Accept\", ct)\n\t}\n\tresponsewriters.ErrorNegotiated(apierrors.NewGenericServerResponse(http.StatusInternalServerError, \"\", schema.GroupResource{}, \"\", \"\", 0, false), s, schema.GroupVersion{}, w, \u0026http.Request{Header: headers})\n}","line":{"from":157,"to":175}} {"id":100018049,"name":"serviceErrorHandler","signature":"func serviceErrorHandler(s runtime.NegotiatedSerializer, serviceErr restful.ServiceError, request *restful.Request, resp *restful.Response)","file":"staging/src/k8s.io/apiserver/pkg/server/handler.go","code":"func serviceErrorHandler(s runtime.NegotiatedSerializer, serviceErr restful.ServiceError, request *restful.Request, resp *restful.Response) {\n\tresponsewriters.ErrorNegotiated(\n\t\tapierrors.NewGenericServerResponse(serviceErr.Code, \"\", schema.GroupResource{}, \"\", serviceErr.Message, 0, false),\n\t\ts,\n\t\tschema.GroupVersion{},\n\t\tresp,\n\t\trequest.Request,\n\t)\n}","line":{"from":177,"to":185}} {"id":100018050,"name":"ServeHTTP","signature":"func (a *APIServerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)","file":"staging/src/k8s.io/apiserver/pkg/server/handler.go","code":"// ServeHTTP makes it an http.Handler\nfunc (a *APIServerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ta.FullHandlerChain.ServeHTTP(w, r)\n}","line":{"from":187,"to":190}} {"id":100018051,"name":"AddHealthChecks","signature":"func (s *GenericAPIServer) AddHealthChecks(checks ...healthz.HealthChecker) error","file":"staging/src/k8s.io/apiserver/pkg/server/healthz.go","code":"// AddHealthChecks adds HealthCheck(s) to health endpoints (healthz, livez, readyz) but\n// configures the liveness grace period to be zero, which means we expect this health check\n// to immediately indicate that the apiserver is unhealthy.\nfunc (s *GenericAPIServer) AddHealthChecks(checks ...healthz.HealthChecker) error {\n\t// we opt for a delay of zero here, because this entrypoint adds generic health checks\n\t// and not health checks which are specifically related to kube-apiserver boot-sequences.\n\treturn s.addHealthChecks(0, checks...)\n}","line":{"from":28,"to":35}} {"id":100018052,"name":"AddBootSequenceHealthChecks","signature":"func (s *GenericAPIServer) AddBootSequenceHealthChecks(checks ...healthz.HealthChecker) error","file":"staging/src/k8s.io/apiserver/pkg/server/healthz.go","code":"// AddBootSequenceHealthChecks adds health checks to the old healthz endpoint (for backwards compatibility reasons)\n// as well as livez and readyz. The livez grace period is defined by the value of the\n// command-line flag --livez-grace-period; before the grace period elapses, the livez health checks\n// will default to healthy. One may want to set a grace period in order to prevent the kubelet from restarting\n// the kube-apiserver due to long-ish boot sequences. Readyz health checks, on the other hand, have no grace period,\n// since readyz should fail until boot fully completes.\nfunc (s *GenericAPIServer) AddBootSequenceHealthChecks(checks ...healthz.HealthChecker) error {\n\treturn s.addHealthChecks(s.livezGracePeriod, checks...)\n}","line":{"from":37,"to":45}} {"id":100018053,"name":"addHealthChecks","signature":"func (s *GenericAPIServer) addHealthChecks(livezGracePeriod time.Duration, checks ...healthz.HealthChecker) error","file":"staging/src/k8s.io/apiserver/pkg/server/healthz.go","code":"// addHealthChecks adds health checks to healthz, livez, and readyz. The delay passed in will set\n// a corresponding grace period on livez.\nfunc (s *GenericAPIServer) addHealthChecks(livezGracePeriod time.Duration, checks ...healthz.HealthChecker) error {\n\ts.healthzLock.Lock()\n\tdefer s.healthzLock.Unlock()\n\tif s.healthzChecksInstalled {\n\t\treturn fmt.Errorf(\"unable to add because the healthz endpoint has already been created\")\n\t}\n\ts.healthzChecks = append(s.healthzChecks, checks...)\n\tif err := s.AddLivezChecks(livezGracePeriod, checks...); err != nil {\n\t\treturn err\n\t}\n\treturn s.AddReadyzChecks(checks...)\n}","line":{"from":47,"to":60}} {"id":100018054,"name":"AddReadyzChecks","signature":"func (s *GenericAPIServer) AddReadyzChecks(checks ...healthz.HealthChecker) error","file":"staging/src/k8s.io/apiserver/pkg/server/healthz.go","code":"// AddReadyzChecks allows you to add a HealthCheck to readyz.\nfunc (s *GenericAPIServer) AddReadyzChecks(checks ...healthz.HealthChecker) error {\n\ts.readyzLock.Lock()\n\tdefer s.readyzLock.Unlock()\n\tif s.readyzChecksInstalled {\n\t\treturn fmt.Errorf(\"unable to add because the readyz endpoint has already been created\")\n\t}\n\ts.readyzChecks = append(s.readyzChecks, checks...)\n\treturn nil\n}","line":{"from":62,"to":71}} {"id":100018055,"name":"AddLivezChecks","signature":"func (s *GenericAPIServer) AddLivezChecks(delay time.Duration, checks ...healthz.HealthChecker) error","file":"staging/src/k8s.io/apiserver/pkg/server/healthz.go","code":"// AddLivezChecks allows you to add a HealthCheck to livez.\nfunc (s *GenericAPIServer) AddLivezChecks(delay time.Duration, checks ...healthz.HealthChecker) error {\n\ts.livezLock.Lock()\n\tdefer s.livezLock.Unlock()\n\tif s.livezChecksInstalled {\n\t\treturn fmt.Errorf(\"unable to add because the livez endpoint has already been created\")\n\t}\n\tfor _, check := range checks {\n\t\ts.livezChecks = append(s.livezChecks, delayedHealthCheck(check, s.livezClock, delay))\n\t}\n\treturn nil\n}","line":{"from":73,"to":84}} {"id":100018056,"name":"addReadyzShutdownCheck","signature":"func (s *GenericAPIServer) addReadyzShutdownCheck(stopCh \u003c-chan struct{}) error","file":"staging/src/k8s.io/apiserver/pkg/server/healthz.go","code":"// addReadyzShutdownCheck is a convenience function for adding a readyz shutdown check, so\n// that we can register that the api-server is no longer ready while we attempt to gracefully\n// shutdown.\nfunc (s *GenericAPIServer) addReadyzShutdownCheck(stopCh \u003c-chan struct{}) error {\n\treturn s.AddReadyzChecks(shutdownCheck{stopCh})\n}","line":{"from":86,"to":91}} {"id":100018057,"name":"installHealthz","signature":"func (s *GenericAPIServer) installHealthz()","file":"staging/src/k8s.io/apiserver/pkg/server/healthz.go","code":"// installHealthz creates the healthz endpoint for this server\nfunc (s *GenericAPIServer) installHealthz() {\n\ts.healthzLock.Lock()\n\tdefer s.healthzLock.Unlock()\n\ts.healthzChecksInstalled = true\n\thealthz.InstallHandler(s.Handler.NonGoRestfulMux, s.healthzChecks...)\n}","line":{"from":93,"to":99}} {"id":100018058,"name":"installReadyz","signature":"func (s *GenericAPIServer) installReadyz()","file":"staging/src/k8s.io/apiserver/pkg/server/healthz.go","code":"// installReadyz creates the readyz endpoint for this server.\nfunc (s *GenericAPIServer) installReadyz() {\n\ts.readyzLock.Lock()\n\tdefer s.readyzLock.Unlock()\n\ts.readyzChecksInstalled = true\n\thealthz.InstallReadyzHandlerWithHealthyFunc(s.Handler.NonGoRestfulMux, func() {\n\t\t// note: InstallReadyzHandlerWithHealthyFunc guarantees that this is called only once\n\t\ts.lifecycleSignals.HasBeenReady.Signal()\n\t}, s.readyzChecks...)\n}","line":{"from":101,"to":110}} {"id":100018059,"name":"installLivez","signature":"func (s *GenericAPIServer) installLivez()","file":"staging/src/k8s.io/apiserver/pkg/server/healthz.go","code":"// installLivez creates the livez endpoint for this server.\nfunc (s *GenericAPIServer) installLivez() {\n\ts.livezLock.Lock()\n\tdefer s.livezLock.Unlock()\n\ts.livezChecksInstalled = true\n\thealthz.InstallLivezHandler(s.Handler.NonGoRestfulMux, s.livezChecks...)\n}","line":{"from":112,"to":118}} {"id":100018060,"name":"Name","signature":"func (shutdownCheck) Name() string","file":"staging/src/k8s.io/apiserver/pkg/server/healthz.go","code":"func (shutdownCheck) Name() string {\n\treturn \"shutdown\"\n}","line":{"from":126,"to":128}} {"id":100018061,"name":"Check","signature":"func (c shutdownCheck) Check(req *http.Request) error","file":"staging/src/k8s.io/apiserver/pkg/server/healthz.go","code":"func (c shutdownCheck) Check(req *http.Request) error {\n\tselect {\n\tcase \u003c-c.StopCh:\n\t\treturn fmt.Errorf(\"process is shutting down\")\n\tdefault:\n\t}\n\treturn nil\n}","line":{"from":130,"to":137}} {"id":100018062,"name":"delayedHealthCheck","signature":"func delayedHealthCheck(check healthz.HealthChecker, clock clock.Clock, delay time.Duration) healthz.HealthChecker","file":"staging/src/k8s.io/apiserver/pkg/server/healthz.go","code":"// delayedHealthCheck wraps a health check which will not fail until the explicitly defined delay has elapsed. This\n// is intended for use primarily for livez health checks.\nfunc delayedHealthCheck(check healthz.HealthChecker, clock clock.Clock, delay time.Duration) healthz.HealthChecker {\n\treturn delayedLivezCheck{\n\t\tcheck,\n\t\tclock.Now().Add(delay),\n\t\tclock,\n\t}\n}","line":{"from":139,"to":147}} {"id":100018063,"name":"Name","signature":"func (c delayedLivezCheck) Name() string","file":"staging/src/k8s.io/apiserver/pkg/server/healthz.go","code":"func (c delayedLivezCheck) Name() string {\n\treturn c.check.Name()\n}","line":{"from":155,"to":157}} {"id":100018064,"name":"Check","signature":"func (c delayedLivezCheck) Check(req *http.Request) error","file":"staging/src/k8s.io/apiserver/pkg/server/healthz.go","code":"func (c delayedLivezCheck) Check(req *http.Request) error {\n\tif c.clock.Now().After(c.startCheck) {\n\t\treturn c.check.Check(req)\n\t}\n\treturn nil\n}","line":{"from":159,"to":164}} {"id":100018065,"name":"Name","signature":"func (ping) Name() string","file":"staging/src/k8s.io/apiserver/pkg/server/healthz/healthz.go","code":"func (ping) Name() string {\n\treturn \"ping\"\n}","line":{"from":50,"to":52}} {"id":100018066,"name":"Check","signature":"func (ping) Check(_ *http.Request) error","file":"staging/src/k8s.io/apiserver/pkg/server/healthz/healthz.go","code":"// PingHealthz is a health check that returns true.\nfunc (ping) Check(_ *http.Request) error {\n\treturn nil\n}","line":{"from":54,"to":57}} {"id":100018067,"name":"Name","signature":"func (l *log) Name() string","file":"staging/src/k8s.io/apiserver/pkg/server/healthz/healthz.go","code":"func (l *log) Name() string {\n\treturn \"log\"\n}","line":{"from":67,"to":69}} {"id":100018068,"name":"Check","signature":"func (l *log) Check(_ *http.Request) error","file":"staging/src/k8s.io/apiserver/pkg/server/healthz/healthz.go","code":"func (l *log) Check(_ *http.Request) error {\n\tl.startOnce.Do(func() {\n\t\tl.lastVerified.Store(time.Now())\n\t\tgo wait.Forever(func() {\n\t\t\tklog.Flush()\n\t\t\tl.lastVerified.Store(time.Now())\n\t\t}, time.Minute)\n\t})\n\n\tlastVerified := l.lastVerified.Load().(time.Time)\n\tif time.Since(lastVerified) \u003c (2 * time.Minute) {\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"logging blocked\")\n}","line":{"from":71,"to":85}} {"id":100018069,"name":"NewInformerSyncHealthz","signature":"func NewInformerSyncHealthz(cacheSyncWaiter cacheSyncWaiter) HealthChecker","file":"staging/src/k8s.io/apiserver/pkg/server/healthz/healthz.go","code":"// NewInformerSyncHealthz returns a new HealthChecker that will pass only if all informers in the given cacheSyncWaiter sync.\nfunc NewInformerSyncHealthz(cacheSyncWaiter cacheSyncWaiter) HealthChecker {\n\treturn \u0026informerSync{\n\t\tcacheSyncWaiter: cacheSyncWaiter,\n\t}\n}","line":{"from":97,"to":102}} {"id":100018070,"name":"Name","signature":"func (i *informerSync) Name() string","file":"staging/src/k8s.io/apiserver/pkg/server/healthz/healthz.go","code":"func (i *informerSync) Name() string {\n\treturn \"informer-sync\"\n}","line":{"from":104,"to":106}} {"id":100018071,"name":"Check","signature":"func (i *informerSync) Check(_ *http.Request) error","file":"staging/src/k8s.io/apiserver/pkg/server/healthz/healthz.go","code":"func (i *informerSync) Check(_ *http.Request) error {\n\tstopCh := make(chan struct{})\n\t// Close stopCh to force checking if informers are synced now.\n\tclose(stopCh)\n\n\tinformersByStarted := make(map[bool][]string)\n\tfor informerType, started := range i.cacheSyncWaiter.WaitForCacheSync(stopCh) {\n\t\tinformersByStarted[started] = append(informersByStarted[started], informerType.String())\n\t}\n\n\tif notStarted := informersByStarted[false]; len(notStarted) \u003e 0 {\n\t\treturn fmt.Errorf(\"%d informers not started yet: %v\", len(notStarted), notStarted)\n\t}\n\treturn nil\n}","line":{"from":108,"to":122}} {"id":100018072,"name":"NamedCheck","signature":"func NamedCheck(name string, check func(r *http.Request) error) HealthChecker","file":"staging/src/k8s.io/apiserver/pkg/server/healthz/healthz.go","code":"// NamedCheck returns a healthz checker for the given name and function.\nfunc NamedCheck(name string, check func(r *http.Request) error) HealthChecker {\n\treturn \u0026healthzCheck{name, check}\n}","line":{"from":124,"to":127}} {"id":100018073,"name":"InstallHandler","signature":"func InstallHandler(mux mux, checks ...HealthChecker)","file":"staging/src/k8s.io/apiserver/pkg/server/healthz/healthz.go","code":"// InstallHandler registers handlers for health checking on the path\n// \"/healthz\" to mux. *All handlers* for mux must be specified in\n// exactly one call to InstallHandler. Calling InstallHandler more\n// than once for the same mux will result in a panic.\nfunc InstallHandler(mux mux, checks ...HealthChecker) {\n\tInstallPathHandler(mux, \"/healthz\", checks...)\n}","line":{"from":129,"to":135}} {"id":100018074,"name":"InstallReadyzHandler","signature":"func InstallReadyzHandler(mux mux, checks ...HealthChecker)","file":"staging/src/k8s.io/apiserver/pkg/server/healthz/healthz.go","code":"// InstallReadyzHandler registers handlers for health checking on the path\n// \"/readyz\" to mux. *All handlers* for mux must be specified in\n// exactly one call to InstallHandler. Calling InstallHandler more\n// than once for the same mux will result in a panic.\nfunc InstallReadyzHandler(mux mux, checks ...HealthChecker) {\n\tInstallPathHandler(mux, \"/readyz\", checks...)\n}","line":{"from":137,"to":143}} {"id":100018075,"name":"InstallReadyzHandlerWithHealthyFunc","signature":"func InstallReadyzHandlerWithHealthyFunc(mux mux, firstTimeReady func(), checks ...HealthChecker)","file":"staging/src/k8s.io/apiserver/pkg/server/healthz/healthz.go","code":"// InstallReadyzHandlerWithHealthyFunc is like InstallReadyzHandler, but in addition call firstTimeReady\n// the first time /readyz succeeds.\nfunc InstallReadyzHandlerWithHealthyFunc(mux mux, firstTimeReady func(), checks ...HealthChecker) {\n\tInstallPathHandlerWithHealthyFunc(mux, \"/readyz\", firstTimeReady, checks...)\n}","line":{"from":145,"to":149}} {"id":100018076,"name":"InstallLivezHandler","signature":"func InstallLivezHandler(mux mux, checks ...HealthChecker)","file":"staging/src/k8s.io/apiserver/pkg/server/healthz/healthz.go","code":"// InstallLivezHandler registers handlers for liveness checking on the path\n// \"/livez\" to mux. *All handlers* for mux must be specified in\n// exactly one call to InstallHandler. Calling InstallHandler more\n// than once for the same mux will result in a panic.\nfunc InstallLivezHandler(mux mux, checks ...HealthChecker) {\n\tInstallPathHandler(mux, \"/livez\", checks...)\n}","line":{"from":151,"to":157}} {"id":100018077,"name":"InstallPathHandler","signature":"func InstallPathHandler(mux mux, path string, checks ...HealthChecker)","file":"staging/src/k8s.io/apiserver/pkg/server/healthz/healthz.go","code":"// InstallPathHandler registers handlers for health checking on\n// a specific path to mux. *All handlers* for the path must be\n// specified in exactly one call to InstallPathHandler. Calling\n// InstallPathHandler more than once for the same path and mux will\n// result in a panic.\nfunc InstallPathHandler(mux mux, path string, checks ...HealthChecker) {\n\tInstallPathHandlerWithHealthyFunc(mux, path, nil, checks...)\n}","line":{"from":159,"to":166}} {"id":100018078,"name":"InstallPathHandlerWithHealthyFunc","signature":"func InstallPathHandlerWithHealthyFunc(mux mux, path string, firstTimeHealthy func(), checks ...HealthChecker)","file":"staging/src/k8s.io/apiserver/pkg/server/healthz/healthz.go","code":"// InstallPathHandlerWithHealthyFunc is like InstallPathHandler, but calls firstTimeHealthy exactly once\n// when the handler succeeds for the first time.\nfunc InstallPathHandlerWithHealthyFunc(mux mux, path string, firstTimeHealthy func(), checks ...HealthChecker) {\n\tif len(checks) == 0 {\n\t\tklog.V(5).Info(\"No default health checks specified. Installing the ping handler.\")\n\t\tchecks = []HealthChecker{PingHealthz}\n\t}\n\n\tklog.V(5).Infof(\"Installing health checkers for (%v): %v\", path, formatQuoted(checkerNames(checks...)...))\n\n\tname := strings.Split(strings.TrimPrefix(path, \"/\"), \"/\")[0]\n\tmux.Handle(path,\n\t\tmetrics.InstrumentHandlerFunc(\"GET\",\n\t\t\t/* group = */ \"\",\n\t\t\t/* version = */ \"\",\n\t\t\t/* resource = */ \"\",\n\t\t\t/* subresource = */ path,\n\t\t\t/* scope = */ \"\",\n\t\t\t/* component = */ \"\",\n\t\t\t/* deprecated */ false,\n\t\t\t/* removedRelease */ \"\",\n\t\t\thandleRootHealth(name, firstTimeHealthy, checks...)))\n\tfor _, check := range checks {\n\t\tmux.Handle(fmt.Sprintf(\"%s/%v\", path, check.Name()), adaptCheckToHandler(check.Check))\n\t}\n}","line":{"from":168,"to":193}} {"id":100018079,"name":"Name","signature":"func (c *healthzCheck) Name() string","file":"staging/src/k8s.io/apiserver/pkg/server/healthz/healthz.go","code":"func (c *healthzCheck) Name() string {\n\treturn c.name\n}","line":{"from":208,"to":210}} {"id":100018080,"name":"Check","signature":"func (c *healthzCheck) Check(r *http.Request) error","file":"staging/src/k8s.io/apiserver/pkg/server/healthz/healthz.go","code":"func (c *healthzCheck) Check(r *http.Request) error {\n\treturn c.check(r)\n}","line":{"from":212,"to":214}} {"id":100018081,"name":"getExcludedChecks","signature":"func getExcludedChecks(r *http.Request) sets.String","file":"staging/src/k8s.io/apiserver/pkg/server/healthz/healthz.go","code":"// getExcludedChecks extracts the health check names to be excluded from the query param\nfunc getExcludedChecks(r *http.Request) sets.String {\n\tchecks, found := r.URL.Query()[\"exclude\"]\n\tif found {\n\t\treturn sets.NewString(checks...)\n\t}\n\treturn sets.NewString()\n}","line":{"from":216,"to":223}} {"id":100018082,"name":"handleRootHealth","signature":"func handleRootHealth(name string, firstTimeHealthy func(), checks ...HealthChecker) http.HandlerFunc","file":"staging/src/k8s.io/apiserver/pkg/server/healthz/healthz.go","code":"// handleRootHealth returns an http.HandlerFunc that serves the provided checks.\nfunc handleRootHealth(name string, firstTimeHealthy func(), checks ...HealthChecker) http.HandlerFunc {\n\tvar notifyOnce sync.Once\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\texcluded := getExcludedChecks(r)\n\t\t// failedVerboseLogOutput is for output to the log. It indicates detailed failed output information for the log.\n\t\tvar failedVerboseLogOutput bytes.Buffer\n\t\tvar failedChecks []string\n\t\tvar individualCheckOutput bytes.Buffer\n\t\tfor _, check := range checks {\n\t\t\t// no-op the check if we've specified we want to exclude the check\n\t\t\tif excluded.Has(check.Name()) {\n\t\t\t\texcluded.Delete(check.Name())\n\t\t\t\tfmt.Fprintf(\u0026individualCheckOutput, \"[+]%s excluded: ok\\n\", check.Name())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := check.Check(r); err != nil {\n\t\t\t\tslis.ObserveHealthcheck(context.Background(), check.Name(), name, slis.Error)\n\t\t\t\t// don't include the error since this endpoint is public. If someone wants more detail\n\t\t\t\t// they should have explicit permission to the detailed checks.\n\t\t\t\tfmt.Fprintf(\u0026individualCheckOutput, \"[-]%s failed: reason withheld\\n\", check.Name())\n\t\t\t\t// but we do want detailed information for our log\n\t\t\t\tfmt.Fprintf(\u0026failedVerboseLogOutput, \"[-]%s failed: %v\\n\", check.Name(), err)\n\t\t\t\tfailedChecks = append(failedChecks, check.Name())\n\t\t\t} else {\n\t\t\t\tslis.ObserveHealthcheck(context.Background(), check.Name(), name, slis.Success)\n\t\t\t\tfmt.Fprintf(\u0026individualCheckOutput, \"[+]%s ok\\n\", check.Name())\n\t\t\t}\n\t\t}\n\t\tif excluded.Len() \u003e 0 {\n\t\t\tfmt.Fprintf(\u0026individualCheckOutput, \"warn: some health checks cannot be excluded: no matches for %s\\n\", formatQuoted(excluded.List()...))\n\t\t\tklog.V(6).Infof(\"cannot exclude some health checks, no health checks are installed matching %s\",\n\t\t\t\tformatQuoted(excluded.List()...))\n\t\t}\n\t\t// always be verbose on failure\n\t\tif len(failedChecks) \u003e 0 {\n\t\t\tklog.V(2).Infof(\"%s check failed: %s\\n%v\", strings.Join(failedChecks, \",\"), name, failedVerboseLogOutput.String())\n\t\t\thttplog.SetStacktracePredicate(r.Context(), func(int) bool { return false })\n\t\t\thttp.Error(w, fmt.Sprintf(\"%s%s check failed\", individualCheckOutput.String(), name), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\t// signal first time this is healthy\n\t\tif firstTimeHealthy != nil {\n\t\t\tnotifyOnce.Do(firstTimeHealthy)\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"text/plain; charset=utf-8\")\n\t\tw.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\t\tif _, found := r.URL.Query()[\"verbose\"]; !found {\n\t\t\tfmt.Fprint(w, \"ok\")\n\t\t\treturn\n\t\t}\n\n\t\tindividualCheckOutput.WriteTo(w)\n\t\tfmt.Fprintf(w, \"%s check passed\\n\", name)\n\t}\n}","line":{"from":225,"to":282}} {"id":100018083,"name":"adaptCheckToHandler","signature":"func adaptCheckToHandler(c func(r *http.Request) error) http.HandlerFunc","file":"staging/src/k8s.io/apiserver/pkg/server/healthz/healthz.go","code":"// adaptCheckToHandler returns an http.HandlerFunc that serves the provided checks.\nfunc adaptCheckToHandler(c func(r *http.Request) error) http.HandlerFunc {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\terr := c(r)\n\t\tif err != nil {\n\t\t\thttp.Error(w, fmt.Sprintf(\"internal server error: %v\", err), http.StatusInternalServerError)\n\t\t} else {\n\t\t\tfmt.Fprint(w, \"ok\")\n\t\t}\n\t})\n}","line":{"from":284,"to":294}} {"id":100018084,"name":"checkerNames","signature":"func checkerNames(checks ...HealthChecker) []string","file":"staging/src/k8s.io/apiserver/pkg/server/healthz/healthz.go","code":"// checkerNames returns the names of the checks in the same order as passed in.\nfunc checkerNames(checks ...HealthChecker) []string {\n\t// accumulate the names of checks for printing them out.\n\tcheckerNames := make([]string, 0, len(checks))\n\tfor _, check := range checks {\n\t\tcheckerNames = append(checkerNames, check.Name())\n\t}\n\treturn checkerNames\n}","line":{"from":296,"to":304}} {"id":100018085,"name":"formatQuoted","signature":"func formatQuoted(names ...string) string","file":"staging/src/k8s.io/apiserver/pkg/server/healthz/healthz.go","code":"// formatQuoted returns a formatted string of the health check names,\n// preserving the order passed in.\nfunc formatQuoted(names ...string) string {\n\tquoted := make([]string, 0, len(names))\n\tfor _, name := range names {\n\t\tquoted = append(quoted, fmt.Sprintf(\"%q\", name))\n\t}\n\treturn strings.Join(quoted, \",\")\n}","line":{"from":306,"to":314}} {"id":100018086,"name":"AddPostStartHook","signature":"func (s *GenericAPIServer) AddPostStartHook(name string, hook PostStartHookFunc) error","file":"staging/src/k8s.io/apiserver/pkg/server/hooks.go","code":"// AddPostStartHook allows you to add a PostStartHook.\nfunc (s *GenericAPIServer) AddPostStartHook(name string, hook PostStartHookFunc) error {\n\tif len(name) == 0 {\n\t\treturn fmt.Errorf(\"missing name\")\n\t}\n\tif hook == nil {\n\t\treturn fmt.Errorf(\"hook func may not be nil: %q\", name)\n\t}\n\tif s.disabledPostStartHooks.Has(name) {\n\t\tklog.V(1).Infof(\"skipping %q because it was explicitly disabled\", name)\n\t\treturn nil\n\t}\n\n\ts.postStartHookLock.Lock()\n\tdefer s.postStartHookLock.Unlock()\n\n\tif s.postStartHooksCalled {\n\t\treturn fmt.Errorf(\"unable to add %q because PostStartHooks have already been called\", name)\n\t}\n\tif postStartHook, exists := s.postStartHooks[name]; exists {\n\t\t// this is programmer error, but it can be hard to debug\n\t\treturn fmt.Errorf(\"unable to add %q because it was already registered by: %s\", name, postStartHook.originatingStack)\n\t}\n\n\t// done is closed when the poststarthook is finished. This is used by the health check to be able to indicate\n\t// that the poststarthook is finished\n\tdone := make(chan struct{})\n\tif err := s.AddBootSequenceHealthChecks(postStartHookHealthz{name: \"poststarthook/\" + name, done: done}); err != nil {\n\t\treturn err\n\t}\n\ts.postStartHooks[name] = postStartHookEntry{hook: hook, originatingStack: string(debug.Stack()), done: done}\n\n\treturn nil\n}","line":{"from":81,"to":114}} {"id":100018087,"name":"AddPostStartHookOrDie","signature":"func (s *GenericAPIServer) AddPostStartHookOrDie(name string, hook PostStartHookFunc)","file":"staging/src/k8s.io/apiserver/pkg/server/hooks.go","code":"// AddPostStartHookOrDie allows you to add a PostStartHook, but dies on failure\nfunc (s *GenericAPIServer) AddPostStartHookOrDie(name string, hook PostStartHookFunc) {\n\tif err := s.AddPostStartHook(name, hook); err != nil {\n\t\tklog.Fatalf(\"Error registering PostStartHook %q: %v\", name, err)\n\t}\n}","line":{"from":116,"to":121}} {"id":100018088,"name":"AddPreShutdownHook","signature":"func (s *GenericAPIServer) AddPreShutdownHook(name string, hook PreShutdownHookFunc) error","file":"staging/src/k8s.io/apiserver/pkg/server/hooks.go","code":"// AddPreShutdownHook allows you to add a PreShutdownHook.\nfunc (s *GenericAPIServer) AddPreShutdownHook(name string, hook PreShutdownHookFunc) error {\n\tif len(name) == 0 {\n\t\treturn fmt.Errorf(\"missing name\")\n\t}\n\tif hook == nil {\n\t\treturn nil\n\t}\n\n\ts.preShutdownHookLock.Lock()\n\tdefer s.preShutdownHookLock.Unlock()\n\n\tif s.preShutdownHooksCalled {\n\t\treturn fmt.Errorf(\"unable to add %q because PreShutdownHooks have already been called\", name)\n\t}\n\tif _, exists := s.preShutdownHooks[name]; exists {\n\t\treturn fmt.Errorf(\"unable to add %q because it is already registered\", name)\n\t}\n\n\ts.preShutdownHooks[name] = preShutdownHookEntry{hook: hook}\n\n\treturn nil\n}","line":{"from":123,"to":145}} {"id":100018089,"name":"AddPreShutdownHookOrDie","signature":"func (s *GenericAPIServer) AddPreShutdownHookOrDie(name string, hook PreShutdownHookFunc)","file":"staging/src/k8s.io/apiserver/pkg/server/hooks.go","code":"// AddPreShutdownHookOrDie allows you to add a PostStartHook, but dies on failure\nfunc (s *GenericAPIServer) AddPreShutdownHookOrDie(name string, hook PreShutdownHookFunc) {\n\tif err := s.AddPreShutdownHook(name, hook); err != nil {\n\t\tklog.Fatalf(\"Error registering PreShutdownHook %q: %v\", name, err)\n\t}\n}","line":{"from":147,"to":152}} {"id":100018090,"name":"RunPostStartHooks","signature":"func (s *GenericAPIServer) RunPostStartHooks(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/apiserver/pkg/server/hooks.go","code":"// RunPostStartHooks runs the PostStartHooks for the server\nfunc (s *GenericAPIServer) RunPostStartHooks(stopCh \u003c-chan struct{}) {\n\ts.postStartHookLock.Lock()\n\tdefer s.postStartHookLock.Unlock()\n\ts.postStartHooksCalled = true\n\n\tcontext := PostStartHookContext{\n\t\tLoopbackClientConfig: s.LoopbackClientConfig,\n\t\tStopCh: stopCh,\n\t}\n\n\tfor hookName, hookEntry := range s.postStartHooks {\n\t\tgo runPostStartHook(hookName, hookEntry, context)\n\t}\n}","line":{"from":154,"to":168}} {"id":100018091,"name":"RunPreShutdownHooks","signature":"func (s *GenericAPIServer) RunPreShutdownHooks() error","file":"staging/src/k8s.io/apiserver/pkg/server/hooks.go","code":"// RunPreShutdownHooks runs the PreShutdownHooks for the server\nfunc (s *GenericAPIServer) RunPreShutdownHooks() error {\n\tvar errorList []error\n\n\ts.preShutdownHookLock.Lock()\n\tdefer s.preShutdownHookLock.Unlock()\n\ts.preShutdownHooksCalled = true\n\n\tfor hookName, hookEntry := range s.preShutdownHooks {\n\t\tif err := runPreShutdownHook(hookName, hookEntry); err != nil {\n\t\t\terrorList = append(errorList, err)\n\t\t}\n\t}\n\treturn utilerrors.NewAggregate(errorList)\n}","line":{"from":170,"to":184}} {"id":100018092,"name":"isPostStartHookRegistered","signature":"func (s *GenericAPIServer) isPostStartHookRegistered(name string) bool","file":"staging/src/k8s.io/apiserver/pkg/server/hooks.go","code":"// isPostStartHookRegistered checks whether a given PostStartHook is registered\nfunc (s *GenericAPIServer) isPostStartHookRegistered(name string) bool {\n\ts.postStartHookLock.Lock()\n\tdefer s.postStartHookLock.Unlock()\n\t_, exists := s.postStartHooks[name]\n\treturn exists\n}","line":{"from":186,"to":192}} {"id":100018093,"name":"runPostStartHook","signature":"func runPostStartHook(name string, entry postStartHookEntry, context PostStartHookContext)","file":"staging/src/k8s.io/apiserver/pkg/server/hooks.go","code":"func runPostStartHook(name string, entry postStartHookEntry, context PostStartHookContext) {\n\tvar err error\n\tfunc() {\n\t\t// don't let the hook *accidentally* panic and kill the server\n\t\tdefer utilruntime.HandleCrash()\n\t\terr = entry.hook(context)\n\t}()\n\t// if the hook intentionally wants to kill server, let it.\n\tif err != nil {\n\t\tklog.Fatalf(\"PostStartHook %q failed: %v\", name, err)\n\t}\n\tclose(entry.done)\n}","line":{"from":194,"to":206}} {"id":100018094,"name":"runPreShutdownHook","signature":"func runPreShutdownHook(name string, entry preShutdownHookEntry) error","file":"staging/src/k8s.io/apiserver/pkg/server/hooks.go","code":"func runPreShutdownHook(name string, entry preShutdownHookEntry) error {\n\tvar err error\n\tfunc() {\n\t\t// don't let the hook *accidentally* panic and kill the server\n\t\tdefer utilruntime.HandleCrash()\n\t\terr = entry.hook()\n\t}()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"PreShutdownHook %q failed: %v\", name, err)\n\t}\n\treturn nil\n}","line":{"from":208,"to":219}} {"id":100018095,"name":"Name","signature":"func (h postStartHookHealthz) Name() string","file":"staging/src/k8s.io/apiserver/pkg/server/hooks.go","code":"func (h postStartHookHealthz) Name() string {\n\treturn h.name\n}","line":{"from":232,"to":234}} {"id":100018096,"name":"Check","signature":"func (h postStartHookHealthz) Check(req *http.Request) error","file":"staging/src/k8s.io/apiserver/pkg/server/hooks.go","code":"func (h postStartHookHealthz) Check(req *http.Request) error {\n\tselect {\n\tcase \u003c-h.done:\n\t\treturn nil\n\tdefault:\n\t\treturn errHookNotFinished\n\t}\n}","line":{"from":238,"to":245}} {"id":100018097,"name":"Unwrap","signature":"func (rl *respLogger) Unwrap() http.ResponseWriter","file":"staging/src/k8s.io/apiserver/pkg/server/httplog/httplog.go","code":"func (rl *respLogger) Unwrap() http.ResponseWriter {\n\treturn rl.w\n}","line":{"from":82,"to":84}} {"id":100018098,"name":"Addf","signature":"func (passthroughLogger) Addf(format string, data ...interface{})","file":"staging/src/k8s.io/apiserver/pkg/server/httplog/httplog.go","code":"// Addf logs info immediately.\nfunc (passthroughLogger) Addf(format string, data ...interface{}) {\n\tklog.V(2).Info(fmt.Sprintf(format, data...))\n}","line":{"from":89,"to":92}} {"id":100018099,"name":"DefaultStacktracePred","signature":"func DefaultStacktracePred(status int) bool","file":"staging/src/k8s.io/apiserver/pkg/server/httplog/httplog.go","code":"// DefaultStacktracePred is the default implementation of StacktracePred.\nfunc DefaultStacktracePred(status int) bool {\n\treturn (status \u003c http.StatusOK || status \u003e= http.StatusInternalServerError) \u0026\u0026 status != http.StatusSwitchingProtocols\n}","line":{"from":94,"to":97}} {"id":100018100,"name":"WithLogging","signature":"func WithLogging(handler http.Handler, pred StacktracePred) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/server/httplog/httplog.go","code":"// WithLogging wraps the handler with logging.\nfunc WithLogging(handler http.Handler, pred StacktracePred) http.Handler {\n\treturn withLogging(handler, pred, func() bool {\n\t\treturn klog.V(withLoggingLevel).Enabled()\n\t})\n}","line":{"from":101,"to":106}} {"id":100018101,"name":"withLogging","signature":"func withLogging(handler http.Handler, stackTracePred StacktracePred, shouldLogRequest ShouldLogRequestPred) http.Handler","file":"staging/src/k8s.io/apiserver/pkg/server/httplog/httplog.go","code":"func withLogging(handler http.Handler, stackTracePred StacktracePred, shouldLogRequest ShouldLogRequestPred) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tif !shouldLogRequest() {\n\t\t\thandler.ServeHTTP(w, req)\n\t\t\treturn\n\t\t}\n\n\t\tctx := req.Context()\n\t\tif old := respLoggerFromRequest(req); old != nil {\n\t\t\tpanic(\"multiple WithLogging calls!\")\n\t\t}\n\n\t\tstartTime := time.Now()\n\t\tif receivedTimestamp, ok := request.ReceivedTimestampFrom(ctx); ok {\n\t\t\tstartTime = receivedTimestamp\n\t\t}\n\n\t\trl := newLoggedWithStartTime(req, w, startTime)\n\t\trl.StacktraceWhen(stackTracePred)\n\t\treq = req.WithContext(context.WithValue(ctx, respLoggerContextKey, rl))\n\t\tdefer rl.Log()\n\n\t\tw = responsewriter.WrapForHTTP1Or2(rl)\n\t\thandler.ServeHTTP(w, req)\n\t})\n}","line":{"from":108,"to":133}} {"id":100018102,"name":"respLoggerFromContext","signature":"func respLoggerFromContext(ctx context.Context) *respLogger","file":"staging/src/k8s.io/apiserver/pkg/server/httplog/httplog.go","code":"// respLoggerFromContext returns the respLogger or nil.\nfunc respLoggerFromContext(ctx context.Context) *respLogger {\n\tval := ctx.Value(respLoggerContextKey)\n\tif rl, ok := val.(*respLogger); ok {\n\t\treturn rl\n\t}\n\treturn nil\n}","line":{"from":135,"to":142}} {"id":100018103,"name":"respLoggerFromRequest","signature":"func respLoggerFromRequest(req *http.Request) *respLogger","file":"staging/src/k8s.io/apiserver/pkg/server/httplog/httplog.go","code":"func respLoggerFromRequest(req *http.Request) *respLogger {\n\treturn respLoggerFromContext(req.Context())\n}","line":{"from":144,"to":146}} {"id":100018104,"name":"newLoggedWithStartTime","signature":"func newLoggedWithStartTime(req *http.Request, w http.ResponseWriter, startTime time.Time) *respLogger","file":"staging/src/k8s.io/apiserver/pkg/server/httplog/httplog.go","code":"func newLoggedWithStartTime(req *http.Request, w http.ResponseWriter, startTime time.Time) *respLogger {\n\tlogger := \u0026respLogger{\n\t\tstartTime: startTime,\n\t\treq: req,\n\t\tuserAgent: req.UserAgent(),\n\t\tw: w,\n\t\tlogStacktracePred: DefaultStacktracePred,\n\t}\n\treturn logger\n}","line":{"from":148,"to":157}} {"id":100018105,"name":"newLogged","signature":"func newLogged(req *http.Request, w http.ResponseWriter) *respLogger","file":"staging/src/k8s.io/apiserver/pkg/server/httplog/httplog.go","code":"// newLogged turns a normal response writer into a logged response writer.\nfunc newLogged(req *http.Request, w http.ResponseWriter) *respLogger {\n\treturn newLoggedWithStartTime(req, w, time.Now())\n}","line":{"from":159,"to":162}} {"id":100018106,"name":"LogOf","signature":"func LogOf(req *http.Request, w http.ResponseWriter) logger","file":"staging/src/k8s.io/apiserver/pkg/server/httplog/httplog.go","code":"// LogOf returns the logger hiding in w. If there is not an existing logger\n// then a passthroughLogger will be created which will log to stdout immediately\n// when Addf is called.\nfunc LogOf(req *http.Request, w http.ResponseWriter) logger {\n\tif rl := respLoggerFromRequest(req); rl != nil {\n\t\treturn rl\n\t}\n\treturn \u0026passthroughLogger{}\n}","line":{"from":164,"to":172}} {"id":100018107,"name":"Unlogged","signature":"func Unlogged(req *http.Request, w http.ResponseWriter) http.ResponseWriter","file":"staging/src/k8s.io/apiserver/pkg/server/httplog/httplog.go","code":"// Unlogged returns the original ResponseWriter, or w if it is not our inserted logger.\nfunc Unlogged(req *http.Request, w http.ResponseWriter) http.ResponseWriter {\n\tif rl := respLoggerFromRequest(req); rl != nil {\n\t\treturn rl.w\n\t}\n\treturn w\n}","line":{"from":174,"to":180}} {"id":100018108,"name":"StacktraceWhen","signature":"func (rl *respLogger) StacktraceWhen(pred StacktracePred) *respLogger","file":"staging/src/k8s.io/apiserver/pkg/server/httplog/httplog.go","code":"// StacktraceWhen sets the stacktrace logging predicate, which decides when to log a stacktrace.\n// There's a default, so you don't need to call this unless you don't like the default.\nfunc (rl *respLogger) StacktraceWhen(pred StacktracePred) *respLogger {\n\trl.mutex.Lock()\n\tdefer rl.mutex.Unlock()\n\trl.logStacktracePred = pred\n\treturn rl\n}","line":{"from":182,"to":189}} {"id":100018109,"name":"StatusIsNot","signature":"func StatusIsNot(statuses ...int) StacktracePred","file":"staging/src/k8s.io/apiserver/pkg/server/httplog/httplog.go","code":"// StatusIsNot returns a StacktracePred which will cause stacktraces to be logged\n// for any status *not* in the given list.\nfunc StatusIsNot(statuses ...int) StacktracePred {\n\tstatusesNoTrace := map[int]bool{}\n\tfor _, s := range statuses {\n\t\tstatusesNoTrace[s] = true\n\t}\n\treturn func(status int) bool {\n\t\t_, ok := statusesNoTrace[status]\n\t\treturn !ok\n\t}\n}","line":{"from":191,"to":202}} {"id":100018110,"name":"Addf","signature":"func (rl *respLogger) Addf(format string, data ...interface{})","file":"staging/src/k8s.io/apiserver/pkg/server/httplog/httplog.go","code":"// Addf adds additional data to be logged with this request.\nfunc (rl *respLogger) Addf(format string, data ...interface{}) {\n\trl.mutex.Lock()\n\tdefer rl.mutex.Unlock()\n\trl.addedInfo.WriteString(\"\\n\")\n\trl.addedInfo.WriteString(fmt.Sprintf(format, data...))\n}","line":{"from":204,"to":210}} {"id":100018111,"name":"AddInfof","signature":"func AddInfof(ctx context.Context, format string, data ...interface{})","file":"staging/src/k8s.io/apiserver/pkg/server/httplog/httplog.go","code":"func AddInfof(ctx context.Context, format string, data ...interface{}) {\n\tif rl := respLoggerFromContext(ctx); rl != nil {\n\t\trl.Addf(format, data...)\n\t}\n}","line":{"from":212,"to":216}} {"id":100018112,"name":"AddKeyValue","signature":"func (rl *respLogger) AddKeyValue(key string, value interface{})","file":"staging/src/k8s.io/apiserver/pkg/server/httplog/httplog.go","code":"func (rl *respLogger) AddKeyValue(key string, value interface{}) {\n\trl.mutex.Lock()\n\tdefer rl.mutex.Unlock()\n\trl.addedKeyValuePairs = append(rl.addedKeyValuePairs, key, value)\n}","line":{"from":218,"to":222}} {"id":100018113,"name":"AddKeyValue","signature":"func AddKeyValue(ctx context.Context, key string, value interface{})","file":"staging/src/k8s.io/apiserver/pkg/server/httplog/httplog.go","code":"// AddKeyValue adds a (key, value) pair to the httplog associated\n// with the request.\n// Use this function if you want your data to show up in httplog\n// in a more structured and readable way.\nfunc AddKeyValue(ctx context.Context, key string, value interface{}) {\n\tif rl := respLoggerFromContext(ctx); rl != nil {\n\t\trl.AddKeyValue(key, value)\n\t}\n}","line":{"from":224,"to":232}} {"id":100018114,"name":"SetStacktracePredicate","signature":"func SetStacktracePredicate(ctx context.Context, pred StacktracePred)","file":"staging/src/k8s.io/apiserver/pkg/server/httplog/httplog.go","code":"// SetStacktracePredicate sets a custom stacktrace predicate for the\n// logger associated with the given request context.\nfunc SetStacktracePredicate(ctx context.Context, pred StacktracePred) {\n\tif rl := respLoggerFromContext(ctx); rl != nil {\n\t\trl.StacktraceWhen(pred)\n\t}\n}","line":{"from":234,"to":240}} {"id":100018115,"name":"Log","signature":"func (rl *respLogger) Log()","file":"staging/src/k8s.io/apiserver/pkg/server/httplog/httplog.go","code":"// Log is intended to be called once at the end of your request handler, via defer\nfunc (rl *respLogger) Log() {\n\tlatency := time.Since(rl.startTime)\n\tauditID := audit.GetAuditIDTruncated(rl.req.Context())\n\tverb := metrics.NormalizedVerb(rl.req)\n\n\tkeysAndValues := []interface{}{\n\t\t\"verb\", verb,\n\t\t\"URI\", rl.req.RequestURI,\n\t\t\"latency\", latency,\n\t\t// We can't get UserAgent from rl.req.UserAgent() here as it accesses headers map,\n\t\t// which can be modified in another goroutine when apiserver request times out.\n\t\t// For example authentication filter modifies request's headers,\n\t\t// This can cause apiserver to crash with unrecoverable fatal error.\n\t\t// More info about concurrent read and write for maps: https://golang.org/doc/go1.6#runtime\n\t\t\"userAgent\", rl.userAgent,\n\t\t\"audit-ID\", auditID,\n\t\t\"srcIP\", rl.req.RemoteAddr,\n\t}\n\t// Lock for accessing addedKeyValuePairs and addedInfo\n\trl.mutex.Lock()\n\tdefer rl.mutex.Unlock()\n\tkeysAndValues = append(keysAndValues, rl.addedKeyValuePairs...)\n\n\tif rl.hijacked {\n\t\tkeysAndValues = append(keysAndValues, \"hijacked\", true)\n\t} else {\n\t\tkeysAndValues = append(keysAndValues, \"resp\", rl.status)\n\t\tif len(rl.statusStack) \u003e 0 {\n\t\t\tkeysAndValues = append(keysAndValues, \"statusStack\", rl.statusStack)\n\t\t}\n\t\tinfo := rl.addedInfo.String()\n\t\tif len(info) \u003e 0 {\n\t\t\tkeysAndValues = append(keysAndValues, \"addedInfo\", info)\n\t\t}\n\t}\n\n\tklog.V(withLoggingLevel).InfoSDepth(1, \"HTTP\", keysAndValues...)\n}","line":{"from":242,"to":280}} {"id":100018116,"name":"Header","signature":"func (rl *respLogger) Header() http.Header","file":"staging/src/k8s.io/apiserver/pkg/server/httplog/httplog.go","code":"// Header implements http.ResponseWriter.\nfunc (rl *respLogger) Header() http.Header {\n\treturn rl.w.Header()\n}","line":{"from":282,"to":285}} {"id":100018117,"name":"Write","signature":"func (rl *respLogger) Write(b []byte) (int, error)","file":"staging/src/k8s.io/apiserver/pkg/server/httplog/httplog.go","code":"// Write implements http.ResponseWriter.\nfunc (rl *respLogger) Write(b []byte) (int, error) {\n\tif !rl.statusRecorded {\n\t\trl.recordStatus(http.StatusOK) // Default if WriteHeader hasn't been called\n\t}\n\tif rl.captureErrorOutput {\n\t\trl.Addf(\"logging error output: %q\\n\", string(b))\n\t}\n\treturn rl.w.Write(b)\n}","line":{"from":287,"to":296}} {"id":100018118,"name":"WriteHeader","signature":"func (rl *respLogger) WriteHeader(status int)","file":"staging/src/k8s.io/apiserver/pkg/server/httplog/httplog.go","code":"// WriteHeader implements http.ResponseWriter.\nfunc (rl *respLogger) WriteHeader(status int) {\n\trl.recordStatus(status)\n\trl.w.WriteHeader(status)\n}","line":{"from":298,"to":302}} {"id":100018119,"name":"Hijack","signature":"func (rl *respLogger) Hijack() (net.Conn, *bufio.ReadWriter, error)","file":"staging/src/k8s.io/apiserver/pkg/server/httplog/httplog.go","code":"func (rl *respLogger) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\trl.hijacked = true\n\n\t// the outer ResponseWriter object returned by WrapForHTTP1Or2 implements\n\t// http.Hijacker if the inner object (rl.w) implements http.Hijacker.\n\treturn rl.w.(http.Hijacker).Hijack()\n}","line":{"from":304,"to":310}} {"id":100018120,"name":"recordStatus","signature":"func (rl *respLogger) recordStatus(status int)","file":"staging/src/k8s.io/apiserver/pkg/server/httplog/httplog.go","code":"func (rl *respLogger) recordStatus(status int) {\n\trl.mutex.Lock()\n\tdefer rl.mutex.Unlock()\n\trl.status = status\n\trl.statusRecorded = true\n\tif rl.logStacktracePred(status) {\n\t\t// Only log stacks for errors\n\t\tstack := make([]byte, 50*1024)\n\t\tstack = stack[:runtime.Stack(stack, false)]\n\t\trl.statusStack = \"\\n\" + string(stack)\n\t\trl.captureErrorOutput = true\n\t} else {\n\t\trl.statusStack = \"\"\n\t}\n}","line":{"from":312,"to":326}} {"id":100018121,"name":"ShuttingDown","signature":"func (s lifecycleSignals) ShuttingDown() \u003c-chan struct{}","file":"staging/src/k8s.io/apiserver/pkg/server/lifecycle_signals.go","code":"// ShuttingDown returns the lifecycle signal that is signaled when\n// the server is not accepting any new requests.\n// this is the lifecycle event that is exported to the request handler\n// logic to indicate that the server is shutting down.\nfunc (s lifecycleSignals) ShuttingDown() \u003c-chan struct{} {\n\treturn s.NotAcceptingNewRequest.Signaled()\n}","line":{"from":149,"to":155}} {"id":100018122,"name":"newLifecycleSignals","signature":"func newLifecycleSignals() lifecycleSignals","file":"staging/src/k8s.io/apiserver/pkg/server/lifecycle_signals.go","code":"// newLifecycleSignals returns an instance of lifecycleSignals interface to be used\n// to coordinate lifecycle of the apiserver\nfunc newLifecycleSignals() lifecycleSignals {\n\treturn lifecycleSignals{\n\t\tShutdownInitiated: newNamedChannelWrapper(\"ShutdownInitiated\"),\n\t\tAfterShutdownDelayDuration: newNamedChannelWrapper(\"AfterShutdownDelayDuration\"),\n\t\tPreShutdownHooksStopped: newNamedChannelWrapper(\"PreShutdownHooksStopped\"),\n\t\tNotAcceptingNewRequest: newNamedChannelWrapper(\"NotAcceptingNewRequest\"),\n\t\tInFlightRequestsDrained: newNamedChannelWrapper(\"InFlightRequestsDrained\"),\n\t\tHTTPServerStoppedListening: newNamedChannelWrapper(\"HTTPServerStoppedListening\"),\n\t\tHasBeenReady: newNamedChannelWrapper(\"HasBeenReady\"),\n\t\tMuxAndDiscoveryComplete: newNamedChannelWrapper(\"MuxAndDiscoveryComplete\"),\n\t}\n}","line":{"from":157,"to":170}} {"id":100018123,"name":"newNamedChannelWrapper","signature":"func newNamedChannelWrapper(name string) lifecycleSignal","file":"staging/src/k8s.io/apiserver/pkg/server/lifecycle_signals.go","code":"func newNamedChannelWrapper(name string) lifecycleSignal {\n\treturn \u0026namedChannelWrapper{\n\t\tname: name,\n\t\tonce: sync.Once{},\n\t\tch: make(chan struct{}),\n\t}\n}","line":{"from":172,"to":178}} {"id":100018124,"name":"Signal","signature":"func (e *namedChannelWrapper) Signal()","file":"staging/src/k8s.io/apiserver/pkg/server/lifecycle_signals.go","code":"func (e *namedChannelWrapper) Signal() {\n\te.once.Do(func() {\n\t\tclose(e.ch)\n\t})\n}","line":{"from":186,"to":190}} {"id":100018125,"name":"Signaled","signature":"func (e *namedChannelWrapper) Signaled() \u003c-chan struct{}","file":"staging/src/k8s.io/apiserver/pkg/server/lifecycle_signals.go","code":"func (e *namedChannelWrapper) Signaled() \u003c-chan struct{} {\n\treturn e.ch\n}","line":{"from":192,"to":194}} {"id":100018126,"name":"Name","signature":"func (e *namedChannelWrapper) Name() string","file":"staging/src/k8s.io/apiserver/pkg/server/lifecycle_signals.go","code":"func (e *namedChannelWrapper) Name() string {\n\treturn e.name\n}","line":{"from":196,"to":198}} {"id":100018127,"name":"NewPathRecorderMux","signature":"func NewPathRecorderMux(name string) *PathRecorderMux","file":"staging/src/k8s.io/apiserver/pkg/server/mux/pathrecorder.go","code":"// NewPathRecorderMux creates a new PathRecorderMux\nfunc NewPathRecorderMux(name string) *PathRecorderMux {\n\tret := \u0026PathRecorderMux{\n\t\tname: name,\n\t\tpathToHandler: map[string]http.Handler{},\n\t\tprefixToHandler: map[string]http.Handler{},\n\t\tmux: atomic.Value{},\n\t\texposedPaths: []string{},\n\t\tpathStacks: map[string]string{},\n\t}\n\n\tret.mux.Store(\u0026pathHandler{notFoundHandler: http.NotFoundHandler()})\n\treturn ret\n}","line":{"from":82,"to":95}} {"id":100018128,"name":"ListedPaths","signature":"func (m *PathRecorderMux) ListedPaths() []string","file":"staging/src/k8s.io/apiserver/pkg/server/mux/pathrecorder.go","code":"// ListedPaths returns the registered handler exposedPaths.\nfunc (m *PathRecorderMux) ListedPaths() []string {\n\thandledPaths := append([]string{}, m.exposedPaths...)\n\tsort.Strings(handledPaths)\n\n\treturn handledPaths\n}","line":{"from":97,"to":103}} {"id":100018129,"name":"trackCallers","signature":"func (m *PathRecorderMux) trackCallers(path string)","file":"staging/src/k8s.io/apiserver/pkg/server/mux/pathrecorder.go","code":"func (m *PathRecorderMux) trackCallers(path string) {\n\tstack := string(debug.Stack())\n\tif existingStack, ok := m.pathStacks[path]; ok {\n\t\tutilruntime.HandleError(fmt.Errorf(\"duplicate path registration of %q: original registration from %v\\n\\nnew registration from %v\", path, existingStack, stack))\n\t}\n\tm.pathStacks[path] = stack\n}","line":{"from":105,"to":111}} {"id":100018130,"name":"refreshMuxLocked","signature":"func (m *PathRecorderMux) refreshMuxLocked()","file":"staging/src/k8s.io/apiserver/pkg/server/mux/pathrecorder.go","code":"// refreshMuxLocked creates a new mux and must be called while locked. Otherwise the view of handlers may\n// not be consistent\nfunc (m *PathRecorderMux) refreshMuxLocked() {\n\tnewMux := \u0026pathHandler{\n\t\tmuxName: m.name,\n\t\tpathToHandler: map[string]http.Handler{},\n\t\tprefixHandlers: []prefixHandler{},\n\t\tnotFoundHandler: http.NotFoundHandler(),\n\t}\n\tif m.notFoundHandler != nil {\n\t\tnewMux.notFoundHandler = m.notFoundHandler\n\t}\n\tfor path, handler := range m.pathToHandler {\n\t\tnewMux.pathToHandler[path] = handler\n\t}\n\n\tkeys := sets.StringKeySet(m.prefixToHandler).List()\n\tsort.Sort(sort.Reverse(byPrefixPriority(keys)))\n\tfor _, prefix := range keys {\n\t\tnewMux.prefixHandlers = append(newMux.prefixHandlers, prefixHandler{\n\t\t\tprefix: prefix,\n\t\t\thandler: m.prefixToHandler[prefix],\n\t\t})\n\t}\n\n\tm.mux.Store(newMux)\n}","line":{"from":113,"to":139}} {"id":100018131,"name":"NotFoundHandler","signature":"func (m *PathRecorderMux) NotFoundHandler(notFoundHandler http.Handler)","file":"staging/src/k8s.io/apiserver/pkg/server/mux/pathrecorder.go","code":"// NotFoundHandler sets the handler to use if there's no match for a give path\nfunc (m *PathRecorderMux) NotFoundHandler(notFoundHandler http.Handler) {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\n\tm.notFoundHandler = notFoundHandler\n\n\tm.refreshMuxLocked()\n}","line":{"from":141,"to":149}} {"id":100018132,"name":"Unregister","signature":"func (m *PathRecorderMux) Unregister(path string)","file":"staging/src/k8s.io/apiserver/pkg/server/mux/pathrecorder.go","code":"// Unregister removes a path from the mux.\nfunc (m *PathRecorderMux) Unregister(path string) {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\n\tdelete(m.pathToHandler, path)\n\tdelete(m.prefixToHandler, path)\n\tdelete(m.pathStacks, path)\n\tfor i := range m.exposedPaths {\n\t\tif m.exposedPaths[i] == path {\n\t\t\tm.exposedPaths = append(m.exposedPaths[:i], m.exposedPaths[i+1:]...)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tm.refreshMuxLocked()\n}","line":{"from":151,"to":167}} {"id":100018133,"name":"Handle","signature":"func (m *PathRecorderMux) Handle(path string, handler http.Handler)","file":"staging/src/k8s.io/apiserver/pkg/server/mux/pathrecorder.go","code":"// Handle registers the handler for the given pattern.\n// If a handler already exists for pattern, Handle panics.\nfunc (m *PathRecorderMux) Handle(path string, handler http.Handler) {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\tm.trackCallers(path)\n\n\tm.exposedPaths = append(m.exposedPaths, path)\n\tm.pathToHandler[path] = handler\n\tm.refreshMuxLocked()\n}","line":{"from":169,"to":179}} {"id":100018134,"name":"HandleFunc","signature":"func (m *PathRecorderMux) HandleFunc(path string, handler func(http.ResponseWriter, *http.Request))","file":"staging/src/k8s.io/apiserver/pkg/server/mux/pathrecorder.go","code":"// HandleFunc registers the handler function for the given pattern.\n// If a handler already exists for pattern, Handle panics.\nfunc (m *PathRecorderMux) HandleFunc(path string, handler func(http.ResponseWriter, *http.Request)) {\n\tm.Handle(path, http.HandlerFunc(handler))\n}","line":{"from":181,"to":185}} {"id":100018135,"name":"UnlistedHandle","signature":"func (m *PathRecorderMux) UnlistedHandle(path string, handler http.Handler)","file":"staging/src/k8s.io/apiserver/pkg/server/mux/pathrecorder.go","code":"// UnlistedHandle registers the handler for the given pattern, but doesn't list it.\n// If a handler already exists for pattern, Handle panics.\nfunc (m *PathRecorderMux) UnlistedHandle(path string, handler http.Handler) {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\tm.trackCallers(path)\n\n\tm.pathToHandler[path] = handler\n\tm.refreshMuxLocked()\n}","line":{"from":187,"to":196}} {"id":100018136,"name":"UnlistedHandleFunc","signature":"func (m *PathRecorderMux) UnlistedHandleFunc(path string, handler func(http.ResponseWriter, *http.Request))","file":"staging/src/k8s.io/apiserver/pkg/server/mux/pathrecorder.go","code":"// UnlistedHandleFunc registers the handler function for the given pattern, but doesn't list it.\n// If a handler already exists for pattern, Handle panics.\nfunc (m *PathRecorderMux) UnlistedHandleFunc(path string, handler func(http.ResponseWriter, *http.Request)) {\n\tm.UnlistedHandle(path, http.HandlerFunc(handler))\n}","line":{"from":198,"to":202}} {"id":100018137,"name":"HandlePrefix","signature":"func (m *PathRecorderMux) HandlePrefix(path string, handler http.Handler)","file":"staging/src/k8s.io/apiserver/pkg/server/mux/pathrecorder.go","code":"// HandlePrefix is like Handle, but matches for anything under the path. Like a standard golang trailing slash.\nfunc (m *PathRecorderMux) HandlePrefix(path string, handler http.Handler) {\n\tif !strings.HasSuffix(path, \"/\") {\n\t\tpanic(fmt.Sprintf(\"%q must end in a trailing slash\", path))\n\t}\n\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\tm.trackCallers(path)\n\n\tm.exposedPaths = append(m.exposedPaths, path)\n\tm.prefixToHandler[path] = handler\n\tm.refreshMuxLocked()\n}","line":{"from":204,"to":217}} {"id":100018138,"name":"UnlistedHandlePrefix","signature":"func (m *PathRecorderMux) UnlistedHandlePrefix(path string, handler http.Handler)","file":"staging/src/k8s.io/apiserver/pkg/server/mux/pathrecorder.go","code":"// UnlistedHandlePrefix is like UnlistedHandle, but matches for anything under the path. Like a standard golang trailing slash.\nfunc (m *PathRecorderMux) UnlistedHandlePrefix(path string, handler http.Handler) {\n\tif !strings.HasSuffix(path, \"/\") {\n\t\tpanic(fmt.Sprintf(\"%q must end in a trailing slash\", path))\n\t}\n\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\tm.trackCallers(path)\n\n\tm.prefixToHandler[path] = handler\n\tm.refreshMuxLocked()\n}","line":{"from":219,"to":231}} {"id":100018139,"name":"ServeHTTP","signature":"func (m *PathRecorderMux) ServeHTTP(w http.ResponseWriter, r *http.Request)","file":"staging/src/k8s.io/apiserver/pkg/server/mux/pathrecorder.go","code":"// ServeHTTP makes it an http.Handler\nfunc (m *PathRecorderMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tm.mux.Load().(*pathHandler).ServeHTTP(w, r)\n}","line":{"from":233,"to":236}} {"id":100018140,"name":"ServeHTTP","signature":"func (h *pathHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)","file":"staging/src/k8s.io/apiserver/pkg/server/mux/pathrecorder.go","code":"// ServeHTTP makes it an http.Handler\nfunc (h *pathHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tif exactHandler, ok := h.pathToHandler[r.URL.Path]; ok {\n\t\tklog.V(5).Infof(\"%v: %q satisfied by exact match\", h.muxName, r.URL.Path)\n\t\texactHandler.ServeHTTP(w, r)\n\t\treturn\n\t}\n\n\tfor _, prefixHandler := range h.prefixHandlers {\n\t\tif strings.HasPrefix(r.URL.Path, prefixHandler.prefix) {\n\t\t\tklog.V(5).Infof(\"%v: %q satisfied by prefix %v\", h.muxName, r.URL.Path, prefixHandler.prefix)\n\t\t\tprefixHandler.handler.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\t}\n\n\tklog.V(5).Infof(\"%v: %q satisfied by NotFoundHandler\", h.muxName, r.URL.Path)\n\th.notFoundHandler.ServeHTTP(w, r)\n}","line":{"from":238,"to":256}} {"id":100018141,"name":"Len","signature":"func (s byPrefixPriority) Len() int { return len(s) }","file":"staging/src/k8s.io/apiserver/pkg/server/mux/pathrecorder.go","code":"func (s byPrefixPriority) Len() int { return len(s) }","line":{"from":263,"to":263}} {"id":100018142,"name":"Swap","signature":"func (s byPrefixPriority) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","file":"staging/src/k8s.io/apiserver/pkg/server/mux/pathrecorder.go","code":"func (s byPrefixPriority) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","line":{"from":264,"to":264}} {"id":100018143,"name":"Less","signature":"func (s byPrefixPriority) Less(i, j int) bool","file":"staging/src/k8s.io/apiserver/pkg/server/mux/pathrecorder.go","code":"func (s byPrefixPriority) Less(i, j int) bool {\n\tlhsNumParts := strings.Count(s[i], \"/\")\n\trhsNumParts := strings.Count(s[j], \"/\")\n\tif lhsNumParts != rhsNumParts {\n\t\treturn lhsNumParts \u003c rhsNumParts\n\t}\n\n\tlhsLen := len(s[i])\n\trhsLen := len(s[j])\n\tif lhsLen != rhsLen {\n\t\treturn lhsLen \u003c rhsLen\n\t}\n\n\treturn strings.Compare(s[i], s[j]) \u003c 0\n}","line":{"from":265,"to":279}} {"id":100018144,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/server/options/admission.go","code":"func init() {\n\tutilruntime.Must(apiserverapi.AddToScheme(configScheme))\n\tutilruntime.Must(apiserverapiv1alpha1.AddToScheme(configScheme))\n\tutilruntime.Must(apiserverapiv1.AddToScheme(configScheme))\n}","line":{"from":48,"to":52}} {"id":100018145,"name":"NewAdmissionOptions","signature":"func NewAdmissionOptions() *AdmissionOptions","file":"staging/src/k8s.io/apiserver/pkg/server/options/admission.go","code":"// NewAdmissionOptions creates a new instance of AdmissionOptions\n// Note:\n//\n//\tIn addition it calls RegisterAllAdmissionPlugins to register\n//\tall generic admission plugins.\n//\n//\tProvides the list of RecommendedPluginOrder that holds sane values\n//\tthat can be used by servers that don't care about admission chain.\n//\tServers that do care can overwrite/append that field after creation.\nfunc NewAdmissionOptions() *AdmissionOptions {\n\toptions := \u0026AdmissionOptions{\n\t\tPlugins: admission.NewPlugins(),\n\t\tDecorators: admission.Decorators{admission.DecoratorFunc(admissionmetrics.WithControllerMetrics)},\n\t\t// This list is mix of mutating admission plugins and validating\n\t\t// admission plugins. The apiserver always runs the validating ones\n\t\t// after all the mutating ones, so their relative order in this list\n\t\t// doesn't matter.\n\t\tRecommendedPluginOrder: []string{lifecycle.PluginName, mutatingwebhook.PluginName, validatingadmissionpolicy.PluginName, validatingwebhook.PluginName},\n\t\tDefaultOffPlugins: sets.NewString(),\n\t}\n\tserver.RegisterAllAdmissionPlugins(options.Plugins)\n\treturn options\n}","line":{"from":73,"to":95}} {"id":100018146,"name":"AddFlags","signature":"func (a *AdmissionOptions) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/apiserver/pkg/server/options/admission.go","code":"// AddFlags adds flags related to admission for a specific APIServer to the specified FlagSet\nfunc (a *AdmissionOptions) AddFlags(fs *pflag.FlagSet) {\n\tif a == nil {\n\t\treturn\n\t}\n\n\tfs.StringSliceVar(\u0026a.EnablePlugins, \"enable-admission-plugins\", a.EnablePlugins, \"\"+\n\t\t\"admission plugins that should be enabled in addition to default enabled ones (\"+\n\t\tstrings.Join(a.defaultEnabledPluginNames(), \", \")+\"). \"+\n\t\t\"Comma-delimited list of admission plugins: \"+strings.Join(a.Plugins.Registered(), \", \")+\". \"+\n\t\t\"The order of plugins in this flag does not matter.\")\n\tfs.StringSliceVar(\u0026a.DisablePlugins, \"disable-admission-plugins\", a.DisablePlugins, \"\"+\n\t\t\"admission plugins that should be disabled although they are in the default enabled plugins list (\"+\n\t\tstrings.Join(a.defaultEnabledPluginNames(), \", \")+\"). \"+\n\t\t\"Comma-delimited list of admission plugins: \"+strings.Join(a.Plugins.Registered(), \", \")+\". \"+\n\t\t\"The order of plugins in this flag does not matter.\")\n\tfs.StringVar(\u0026a.ConfigFile, \"admission-control-config-file\", a.ConfigFile,\n\t\t\"File with admission control configuration.\")\n}","line":{"from":97,"to":115}} {"id":100018147,"name":"ApplyTo","signature":"func (a *AdmissionOptions) ApplyTo(","file":"staging/src/k8s.io/apiserver/pkg/server/options/admission.go","code":"// ApplyTo adds the admission chain to the server configuration.\n// In case admission plugin names were not provided by a cluster-admin they will be prepared from the recommended/default values.\n// In addition the method lazily initializes a generic plugin that is appended to the list of pluginInitializers\n// note this method uses:\n//\n//\tgenericconfig.Authorizer\nfunc (a *AdmissionOptions) ApplyTo(\n\tc *server.Config,\n\tinformers informers.SharedInformerFactory,\n\tkubeAPIServerClientConfig *rest.Config,\n\tfeatures featuregate.FeatureGate,\n\tpluginInitializers ...admission.PluginInitializer,\n) error {\n\tif a == nil {\n\t\treturn nil\n\t}\n\n\t// Admission depends on CoreAPI to set SharedInformerFactory and ClientConfig.\n\tif informers == nil {\n\t\treturn fmt.Errorf(\"admission depends on a Kubernetes core API shared informer, it cannot be nil\")\n\t}\n\n\tpluginNames := a.enabledPluginNames()\n\n\tpluginsConfigProvider, err := admission.ReadAdmissionConfiguration(pluginNames, a.ConfigFile, configScheme)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to read plugin config: %v\", err)\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(kubeAPIServerClientConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdynamicClient, err := dynamic.NewForConfig(kubeAPIServerClientConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgenericInitializer := initializer.New(clientset, dynamicClient, informers, c.Authorization.Authorizer, features, c.DrainedNotify())\n\tinitializersChain := admission.PluginInitializers{genericInitializer}\n\tinitializersChain = append(initializersChain, pluginInitializers...)\n\n\tadmissionChain, err := a.Plugins.NewFromPlugins(pluginNames, pluginsConfigProvider, initializersChain, a.Decorators)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.AdmissionControl = admissionmetrics.WithStepMetrics(admissionChain)\n\treturn nil\n}","line":{"from":117,"to":165}} {"id":100018148,"name":"Validate","signature":"func (a *AdmissionOptions) Validate() []error","file":"staging/src/k8s.io/apiserver/pkg/server/options/admission.go","code":"// Validate verifies flags passed to AdmissionOptions.\nfunc (a *AdmissionOptions) Validate() []error {\n\tif a == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\n\tregisteredPlugins := sets.NewString(a.Plugins.Registered()...)\n\tfor _, name := range a.EnablePlugins {\n\t\tif !registeredPlugins.Has(name) {\n\t\t\terrs = append(errs, fmt.Errorf(\"enable-admission-plugins plugin %q is unknown\", name))\n\t\t}\n\t}\n\n\tfor _, name := range a.DisablePlugins {\n\t\tif !registeredPlugins.Has(name) {\n\t\t\terrs = append(errs, fmt.Errorf(\"disable-admission-plugins plugin %q is unknown\", name))\n\t\t}\n\t}\n\n\tenablePlugins := sets.NewString(a.EnablePlugins...)\n\tdisablePlugins := sets.NewString(a.DisablePlugins...)\n\tif len(enablePlugins.Intersection(disablePlugins).List()) \u003e 0 {\n\t\terrs = append(errs, fmt.Errorf(\"%v in enable-admission-plugins and disable-admission-plugins \"+\n\t\t\t\"overlapped\", enablePlugins.Intersection(disablePlugins).List()))\n\t}\n\n\t// Verify RecommendedPluginOrder.\n\trecommendPlugins := sets.NewString(a.RecommendedPluginOrder...)\n\tintersections := registeredPlugins.Intersection(recommendPlugins)\n\tif !intersections.Equal(recommendPlugins) {\n\t\t// Developer error, this should never run in.\n\t\terrs = append(errs, fmt.Errorf(\"plugins %v in RecommendedPluginOrder are not registered\",\n\t\t\trecommendPlugins.Difference(intersections).List()))\n\t}\n\tif !intersections.Equal(registeredPlugins) {\n\t\t// Developer error, this should never run in.\n\t\terrs = append(errs, fmt.Errorf(\"plugins %v registered are not in RecommendedPluginOrder\",\n\t\t\tregisteredPlugins.Difference(intersections).List()))\n\t}\n\n\treturn errs\n}","line":{"from":167,"to":210}} {"id":100018149,"name":"enabledPluginNames","signature":"func (a *AdmissionOptions) enabledPluginNames() []string","file":"staging/src/k8s.io/apiserver/pkg/server/options/admission.go","code":"// enabledPluginNames makes use of RecommendedPluginOrder, DefaultOffPlugins,\n// EnablePlugins, DisablePlugins fields\n// to prepare a list of ordered plugin names that are enabled.\nfunc (a *AdmissionOptions) enabledPluginNames() []string {\n\tallOffPlugins := append(a.DefaultOffPlugins.List(), a.DisablePlugins...)\n\tdisabledPlugins := sets.NewString(allOffPlugins...)\n\tenabledPlugins := sets.NewString(a.EnablePlugins...)\n\tdisabledPlugins = disabledPlugins.Difference(enabledPlugins)\n\n\torderedPlugins := []string{}\n\tfor _, plugin := range a.RecommendedPluginOrder {\n\t\tif !disabledPlugins.Has(plugin) {\n\t\t\torderedPlugins = append(orderedPlugins, plugin)\n\t\t}\n\t}\n\n\treturn orderedPlugins\n}","line":{"from":212,"to":229}} {"id":100018150,"name":"defaultEnabledPluginNames","signature":"func (a *AdmissionOptions) defaultEnabledPluginNames() []string","file":"staging/src/k8s.io/apiserver/pkg/server/options/admission.go","code":"// Return names of plugins which are enabled by default\nfunc (a *AdmissionOptions) defaultEnabledPluginNames() []string {\n\tdefaultOnPluginNames := []string{}\n\tfor _, pluginName := range a.RecommendedPluginOrder {\n\t\tif !a.DefaultOffPlugins.Has(pluginName) {\n\t\t\tdefaultOnPluginNames = append(defaultOnPluginNames, pluginName)\n\t\t}\n\t}\n\n\treturn defaultOnPluginNames\n}","line":{"from":231,"to":241}} {"id":100018151,"name":"NewAPIEnablementOptions","signature":"func NewAPIEnablementOptions() *APIEnablementOptions","file":"staging/src/k8s.io/apiserver/pkg/server/options/api_enablement.go","code":"func NewAPIEnablementOptions() *APIEnablementOptions {\n\treturn \u0026APIEnablementOptions{\n\t\tRuntimeConfig: make(cliflag.ConfigurationMap),\n\t}\n}","line":{"from":37,"to":41}} {"id":100018152,"name":"AddFlags","signature":"func (s *APIEnablementOptions) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/apiserver/pkg/server/options/api_enablement.go","code":"// AddFlags adds flags for a specific APIServer to the specified FlagSet\nfunc (s *APIEnablementOptions) AddFlags(fs *pflag.FlagSet) {\n\tfs.Var(\u0026s.RuntimeConfig, \"runtime-config\", \"\"+\n\t\t\"A set of key=value pairs that enable or disable built-in APIs. Supported options are:\\n\"+\n\t\t\"v1=true|false for the core API group\\n\"+\n\t\t\"\u003cgroup\u003e/\u003cversion\u003e=true|false for a specific API group and version (e.g. apps/v1=true)\\n\"+\n\t\t\"api/all=true|false controls all API versions\\n\"+\n\t\t\"api/ga=true|false controls all API versions of the form v[0-9]+\\n\"+\n\t\t\"api/beta=true|false controls all API versions of the form v[0-9]+beta[0-9]+\\n\"+\n\t\t\"api/alpha=true|false controls all API versions of the form v[0-9]+alpha[0-9]+\\n\"+\n\t\t\"api/legacy is deprecated, and will be removed in a future version\")\n}","line":{"from":43,"to":54}} {"id":100018153,"name":"Validate","signature":"func (s *APIEnablementOptions) Validate(registries ...GroupRegistry) []error","file":"staging/src/k8s.io/apiserver/pkg/server/options/api_enablement.go","code":"// Validate validates RuntimeConfig with a list of registries.\n// Usually this list only has one element, the apiserver registry of the process.\n// But in the advanced (and usually not recommended) case of delegated apiservers there can be more.\n// Validate will filter out the known groups of each registry.\n// If anything is left over after that, an error is returned.\nfunc (s *APIEnablementOptions) Validate(registries ...GroupRegistry) []error {\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\terrors := []error{}\n\tif s.RuntimeConfig[resourceconfig.APIAll] == \"false\" \u0026\u0026 len(s.RuntimeConfig) == 1 {\n\t\t// Do not allow only set api/all=false, in such case apiserver startup has no meaning.\n\t\treturn append(errors, fmt.Errorf(\"invalid key with only %v=false\", resourceconfig.APIAll))\n\t}\n\n\tgroups, err := resourceconfig.ParseGroups(s.RuntimeConfig)\n\tif err != nil {\n\t\treturn append(errors, err)\n\t}\n\n\tfor _, registry := range registries {\n\t\t// filter out known groups\n\t\tgroups = unknownGroups(groups, registry)\n\t}\n\tif len(groups) != 0 {\n\t\terrors = append(errors, fmt.Errorf(\"unknown api groups %s\", strings.Join(groups, \",\")))\n\t}\n\n\treturn errors\n}","line":{"from":56,"to":86}} {"id":100018154,"name":"ApplyTo","signature":"func (s *APIEnablementOptions) ApplyTo(c *server.Config, defaultResourceConfig *serverstore.ResourceConfig, registry resourceconfig.GroupVersionRegistry) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/api_enablement.go","code":"// ApplyTo override MergedResourceConfig with defaults and registry\nfunc (s *APIEnablementOptions) ApplyTo(c *server.Config, defaultResourceConfig *serverstore.ResourceConfig, registry resourceconfig.GroupVersionRegistry) error {\n\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\tmergedResourceConfig, err := resourceconfig.MergeAPIResourceConfigs(defaultResourceConfig, s.RuntimeConfig, registry)\n\tc.MergedResourceConfig = mergedResourceConfig\n\n\treturn err\n}","line":{"from":88,"to":99}} {"id":100018155,"name":"unknownGroups","signature":"func unknownGroups(groups []string, registry GroupRegistry) []string","file":"staging/src/k8s.io/apiserver/pkg/server/options/api_enablement.go","code":"func unknownGroups(groups []string, registry GroupRegistry) []string {\n\tunknownGroups := []string{}\n\tfor _, group := range groups {\n\t\tif !registry.IsGroupRegistered(group) {\n\t\t\tunknownGroups = append(unknownGroups, group)\n\t\t}\n\t}\n\treturn unknownGroups\n}","line":{"from":101,"to":109}} {"id":100018156,"name":"appendBackend","signature":"func appendBackend(existing, newBackend audit.Backend) audit.Backend","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"func appendBackend(existing, newBackend audit.Backend) audit.Backend {\n\tif existing == nil {\n\t\treturn newBackend\n\t}\n\tif newBackend == nil {\n\t\treturn existing\n\t}\n\treturn audit.Union(existing, newBackend)\n}","line":{"from":57,"to":65}} {"id":100018157,"name":"NewAuditOptions","signature":"func NewAuditOptions() *AuditOptions","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"func NewAuditOptions() *AuditOptions {\n\treturn \u0026AuditOptions{\n\t\tWebhookOptions: AuditWebhookOptions{\n\t\t\tInitialBackoff: pluginwebhook.DefaultInitialBackoffDelay,\n\t\t\tBatchOptions: AuditBatchOptions{\n\t\t\t\tMode: ModeBatch,\n\t\t\t\tBatchConfig: defaultWebhookBatchConfig(),\n\t\t\t},\n\t\t\tTruncateOptions: NewAuditTruncateOptions(),\n\t\t\tGroupVersionString: \"audit.k8s.io/v1\",\n\t\t},\n\t\tLogOptions: AuditLogOptions{\n\t\t\tFormat: pluginlog.FormatJson,\n\t\t\tBatchOptions: AuditBatchOptions{\n\t\t\t\tMode: ModeBlocking,\n\t\t\t\tBatchConfig: defaultLogBatchConfig(),\n\t\t\t},\n\t\t\tTruncateOptions: NewAuditTruncateOptions(),\n\t\t\tGroupVersionString: \"audit.k8s.io/v1\",\n\t\t},\n\t}\n}","line":{"from":155,"to":176}} {"id":100018158,"name":"NewAuditTruncateOptions","signature":"func NewAuditTruncateOptions() AuditTruncateOptions","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"func NewAuditTruncateOptions() AuditTruncateOptions {\n\treturn AuditTruncateOptions{\n\t\tEnabled: false,\n\t\tTruncateConfig: plugintruncate.Config{\n\t\t\tMaxBatchSize: 10 * 1024 * 1024, // 10MB\n\t\t\tMaxEventSize: 100 * 1024, // 100KB\n\t\t},\n\t}\n}","line":{"from":178,"to":186}} {"id":100018159,"name":"Validate","signature":"func (o *AuditOptions) Validate() []error","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"// Validate checks invalid config combination\nfunc (o *AuditOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tvar allErrors []error\n\tallErrors = append(allErrors, o.LogOptions.Validate()...)\n\tallErrors = append(allErrors, o.WebhookOptions.Validate()...)\n\n\treturn allErrors\n}","line":{"from":188,"to":199}} {"id":100018160,"name":"validateBackendMode","signature":"func validateBackendMode(pluginName string, mode string) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"func validateBackendMode(pluginName string, mode string) error {\n\tfor _, m := range AllowedModes {\n\t\tif m == mode {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"invalid audit %s mode %s, allowed modes are %q\", pluginName, mode, strings.Join(AllowedModes, \",\"))\n}","line":{"from":201,"to":208}} {"id":100018161,"name":"validateBackendBatchOptions","signature":"func validateBackendBatchOptions(pluginName string, options AuditBatchOptions) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"func validateBackendBatchOptions(pluginName string, options AuditBatchOptions) error {\n\tif err := validateBackendMode(pluginName, options.Mode); err != nil {\n\t\treturn err\n\t}\n\tif options.Mode != ModeBatch {\n\t\t// Don't validate the unused options.\n\t\treturn nil\n\t}\n\tconfig := options.BatchConfig\n\tif config.BufferSize \u003c= 0 {\n\t\treturn fmt.Errorf(\"invalid audit batch %s buffer size %v, must be a positive number\", pluginName, config.BufferSize)\n\t}\n\tif config.MaxBatchSize \u003c= 0 {\n\t\treturn fmt.Errorf(\"invalid audit batch %s max batch size %v, must be a positive number\", pluginName, config.MaxBatchSize)\n\t}\n\tif config.ThrottleEnable {\n\t\tif config.ThrottleQPS \u003c= 0 {\n\t\t\treturn fmt.Errorf(\"invalid audit batch %s throttle QPS %v, must be a positive number\", pluginName, config.ThrottleQPS)\n\t\t}\n\t\tif config.ThrottleBurst \u003c= 0 {\n\t\t\treturn fmt.Errorf(\"invalid audit batch %s throttle burst %v, must be a positive number\", pluginName, config.ThrottleBurst)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":210,"to":234}} {"id":100018162,"name":"validateGroupVersionString","signature":"func validateGroupVersionString(groupVersion string) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"func validateGroupVersionString(groupVersion string) error {\n\tgv, err := schema.ParseGroupVersion(groupVersion)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !knownGroupVersion(gv) {\n\t\treturn fmt.Errorf(\"invalid group version, allowed versions are %q\", knownGroupVersions)\n\t}\n\tif gv != auditv1.SchemeGroupVersion {\n\t\tklog.Warningf(\"%q is deprecated and will be removed in a future release, use %q instead\", gv, auditv1.SchemeGroupVersion)\n\t}\n\treturn nil\n}","line":{"from":240,"to":252}} {"id":100018163,"name":"knownGroupVersion","signature":"func knownGroupVersion(gv schema.GroupVersion) bool","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"func knownGroupVersion(gv schema.GroupVersion) bool {\n\tfor _, knownGv := range knownGroupVersions {\n\t\tif gv == knownGv {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":254,"to":261}} {"id":100018164,"name":"AddFlags","signature":"func (o *AuditOptions) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"func (o *AuditOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.StringVar(\u0026o.PolicyFile, \"audit-policy-file\", o.PolicyFile,\n\t\t\"Path to the file that defines the audit policy configuration.\")\n\n\to.LogOptions.AddFlags(fs)\n\to.LogOptions.BatchOptions.AddFlags(pluginlog.PluginName, fs)\n\to.LogOptions.TruncateOptions.AddFlags(pluginlog.PluginName, fs)\n\to.WebhookOptions.AddFlags(fs)\n\to.WebhookOptions.BatchOptions.AddFlags(pluginwebhook.PluginName, fs)\n\to.WebhookOptions.TruncateOptions.AddFlags(pluginwebhook.PluginName, fs)\n}","line":{"from":263,"to":277}} {"id":100018165,"name":"ApplyTo","signature":"func (o *AuditOptions) ApplyTo(","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"func (o *AuditOptions) ApplyTo(\n\tc *server.Config,\n) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tif c == nil {\n\t\treturn fmt.Errorf(\"server config must be non-nil\")\n\t}\n\n\t// 1. Build policy evaluator\n\tevaluator, err := o.newPolicyRuleEvaluator()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// 2. Build log backend\n\tvar logBackend audit.Backend\n\tw, err := o.LogOptions.getWriter()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif w != nil {\n\t\tif evaluator == nil {\n\t\t\tklog.V(2).Info(\"No audit policy file provided, no events will be recorded for log backend\")\n\t\t} else {\n\t\t\tlogBackend = o.LogOptions.newBackend(w)\n\t\t}\n\t}\n\n\t// 3. Build webhook backend\n\tvar webhookBackend audit.Backend\n\tif o.WebhookOptions.enabled() {\n\t\tif evaluator == nil {\n\t\t\tklog.V(2).Info(\"No audit policy file provided, no events will be recorded for webhook backend\")\n\t\t} else {\n\t\t\tif c.EgressSelector != nil {\n\t\t\t\tvar egressDialer utilnet.DialFunc\n\t\t\t\tegressDialer, err = c.EgressSelector.Lookup(egressselector.ControlPlane.AsNetworkContext())\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\twebhookBackend, err = o.WebhookOptions.newUntruncatedBackend(egressDialer)\n\t\t\t} else {\n\t\t\t\twebhookBackend, err = o.WebhookOptions.newUntruncatedBackend(nil)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tgroupVersion, err := schema.ParseGroupVersion(o.WebhookOptions.GroupVersionString)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// 4. Apply dynamic options.\n\tvar dynamicBackend audit.Backend\n\tif webhookBackend != nil {\n\t\t// if only webhook is enabled wrap it in the truncate options\n\t\tdynamicBackend = o.WebhookOptions.TruncateOptions.wrapBackend(webhookBackend, groupVersion)\n\t}\n\n\t// 5. Set the policy rule evaluator\n\tc.AuditPolicyRuleEvaluator = evaluator\n\n\t// 6. Join the log backend with the webhooks\n\tc.AuditBackend = appendBackend(logBackend, dynamicBackend)\n\n\tif c.AuditBackend != nil {\n\t\tklog.V(2).Infof(\"Using audit backend: %s\", c.AuditBackend)\n\t}\n\treturn nil\n}","line":{"from":279,"to":353}} {"id":100018166,"name":"newPolicyRuleEvaluator","signature":"func (o *AuditOptions) newPolicyRuleEvaluator() (audit.PolicyRuleEvaluator, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"func (o *AuditOptions) newPolicyRuleEvaluator() (audit.PolicyRuleEvaluator, error) {\n\tif o.PolicyFile == \"\" {\n\t\treturn nil, nil\n\t}\n\n\tp, err := policy.LoadPolicyFromFile(o.PolicyFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"loading audit policy file: %v\", err)\n\t}\n\treturn policy.NewPolicyRuleEvaluator(p), nil\n}","line":{"from":355,"to":365}} {"id":100018167,"name":"AddFlags","signature":"func (o *AuditBatchOptions) AddFlags(pluginName string, fs *pflag.FlagSet)","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"func (o *AuditBatchOptions) AddFlags(pluginName string, fs *pflag.FlagSet) {\n\tfs.StringVar(\u0026o.Mode, fmt.Sprintf(\"audit-%s-mode\", pluginName), o.Mode,\n\t\t\"Strategy for sending audit events. Blocking indicates sending events should block\"+\n\t\t\t\" server responses. Batch causes the backend to buffer and write events\"+\n\t\t\t\" asynchronously. Known modes are \"+strings.Join(AllowedModes, \",\")+\".\")\n\tfs.IntVar(\u0026o.BatchConfig.BufferSize, fmt.Sprintf(\"audit-%s-batch-buffer-size\", pluginName),\n\t\to.BatchConfig.BufferSize, \"The size of the buffer to store events before \"+\n\t\t\t\"batching and writing. Only used in batch mode.\")\n\tfs.IntVar(\u0026o.BatchConfig.MaxBatchSize, fmt.Sprintf(\"audit-%s-batch-max-size\", pluginName),\n\t\to.BatchConfig.MaxBatchSize, \"The maximum size of a batch. Only used in batch mode.\")\n\tfs.DurationVar(\u0026o.BatchConfig.MaxBatchWait, fmt.Sprintf(\"audit-%s-batch-max-wait\", pluginName),\n\t\to.BatchConfig.MaxBatchWait, \"The amount of time to wait before force writing the \"+\n\t\t\t\"batch that hadn't reached the max size. Only used in batch mode.\")\n\tfs.BoolVar(\u0026o.BatchConfig.ThrottleEnable, fmt.Sprintf(\"audit-%s-batch-throttle-enable\", pluginName),\n\t\to.BatchConfig.ThrottleEnable, \"Whether batching throttling is enabled. Only used in batch mode.\")\n\tfs.Float32Var(\u0026o.BatchConfig.ThrottleQPS, fmt.Sprintf(\"audit-%s-batch-throttle-qps\", pluginName),\n\t\to.BatchConfig.ThrottleQPS, \"Maximum average number of batches per second. \"+\n\t\t\t\"Only used in batch mode.\")\n\tfs.IntVar(\u0026o.BatchConfig.ThrottleBurst, fmt.Sprintf(\"audit-%s-batch-throttle-burst\", pluginName),\n\t\to.BatchConfig.ThrottleBurst, \"Maximum number of requests sent at the same \"+\n\t\t\t\"moment if ThrottleQPS was not utilized before. Only used in batch mode.\")\n}","line":{"from":367,"to":388}} {"id":100018168,"name":"ProcessEvents","signature":"func (i *ignoreErrorsBackend) ProcessEvents(ev ...*auditinternal.Event) bool","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"func (i *ignoreErrorsBackend) ProcessEvents(ev ...*auditinternal.Event) bool {\n\ti.Backend.ProcessEvents(ev...)\n\treturn true\n}","line":{"from":394,"to":397}} {"id":100018169,"name":"String","signature":"func (i *ignoreErrorsBackend) String() string","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"func (i *ignoreErrorsBackend) String() string {\n\treturn fmt.Sprintf(\"ignoreErrors\u003c%s\u003e\", i.Backend)\n}","line":{"from":399,"to":401}} {"id":100018170,"name":"wrapBackend","signature":"func (o *AuditBatchOptions) wrapBackend(delegate audit.Backend) audit.Backend","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"func (o *AuditBatchOptions) wrapBackend(delegate audit.Backend) audit.Backend {\n\tif o.Mode == ModeBlockingStrict {\n\t\treturn delegate\n\t}\n\tif o.Mode == ModeBlocking {\n\t\treturn \u0026ignoreErrorsBackend{Backend: delegate}\n\t}\n\treturn pluginbuffered.NewBackend(delegate, o.BatchConfig)\n}","line":{"from":403,"to":411}} {"id":100018171,"name":"Validate","signature":"func (o *AuditTruncateOptions) Validate(pluginName string) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"func (o *AuditTruncateOptions) Validate(pluginName string) error {\n\tconfig := o.TruncateConfig\n\tif config.MaxEventSize \u003c= 0 {\n\t\treturn fmt.Errorf(\"invalid audit truncate %s max event size %v, must be a positive number\", pluginName, config.MaxEventSize)\n\t}\n\tif config.MaxBatchSize \u003c config.MaxEventSize {\n\t\treturn fmt.Errorf(\"invalid audit truncate %s max batch size %v, must be greater than \"+\n\t\t\t\"max event size (%v)\", pluginName, config.MaxBatchSize, config.MaxEventSize)\n\t}\n\treturn nil\n}","line":{"from":413,"to":423}} {"id":100018172,"name":"AddFlags","signature":"func (o *AuditTruncateOptions) AddFlags(pluginName string, fs *pflag.FlagSet)","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"func (o *AuditTruncateOptions) AddFlags(pluginName string, fs *pflag.FlagSet) {\n\tfs.BoolVar(\u0026o.Enabled, fmt.Sprintf(\"audit-%s-truncate-enabled\", pluginName),\n\t\to.Enabled, \"Whether event and batch truncating is enabled.\")\n\tfs.Int64Var(\u0026o.TruncateConfig.MaxBatchSize, fmt.Sprintf(\"audit-%s-truncate-max-batch-size\", pluginName),\n\t\to.TruncateConfig.MaxBatchSize, \"Maximum size of the batch sent to the underlying backend. \"+\n\t\t\t\"Actual serialized size can be several hundreds of bytes greater. If a batch exceeds this limit, \"+\n\t\t\t\"it is split into several batches of smaller size.\")\n\tfs.Int64Var(\u0026o.TruncateConfig.MaxEventSize, fmt.Sprintf(\"audit-%s-truncate-max-event-size\", pluginName),\n\t\to.TruncateConfig.MaxEventSize, \"Maximum size of the audit event sent to the underlying backend. \"+\n\t\t\t\"If the size of an event is greater than this number, first request and response are removed, and \"+\n\t\t\t\"if this doesn't reduce the size enough, event is discarded.\")\n}","line":{"from":425,"to":436}} {"id":100018173,"name":"wrapBackend","signature":"func (o *AuditTruncateOptions) wrapBackend(delegate audit.Backend, gv schema.GroupVersion) audit.Backend","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"func (o *AuditTruncateOptions) wrapBackend(delegate audit.Backend, gv schema.GroupVersion) audit.Backend {\n\tif !o.Enabled {\n\t\treturn delegate\n\t}\n\treturn plugintruncate.NewBackend(delegate, o.TruncateConfig, gv)\n}","line":{"from":438,"to":443}} {"id":100018174,"name":"AddFlags","signature":"func (o *AuditLogOptions) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"func (o *AuditLogOptions) AddFlags(fs *pflag.FlagSet) {\n\tfs.StringVar(\u0026o.Path, \"audit-log-path\", o.Path,\n\t\t\"If set, all requests coming to the apiserver will be logged to this file. '-' means standard out.\")\n\tfs.IntVar(\u0026o.MaxAge, \"audit-log-maxage\", o.MaxAge,\n\t\t\"The maximum number of days to retain old audit log files based on the timestamp encoded in their filename.\")\n\tfs.IntVar(\u0026o.MaxBackups, \"audit-log-maxbackup\", o.MaxBackups,\n\t\t\"The maximum number of old audit log files to retain. Setting a value of 0 will mean there's no restriction on the number of files.\")\n\tfs.IntVar(\u0026o.MaxSize, \"audit-log-maxsize\", o.MaxSize,\n\t\t\"The maximum size in megabytes of the audit log file before it gets rotated.\")\n\tfs.StringVar(\u0026o.Format, \"audit-log-format\", o.Format,\n\t\t\"Format of saved audits. \\\"legacy\\\" indicates 1-line text format for each event.\"+\n\t\t\t\" \\\"json\\\" indicates structured json format. Known formats are \"+\n\t\t\tstrings.Join(pluginlog.AllowedFormats, \",\")+\".\")\n\tfs.StringVar(\u0026o.GroupVersionString, \"audit-log-version\", o.GroupVersionString,\n\t\t\"API group and version used for serializing audit events written to log.\")\n\tfs.BoolVar(\u0026o.Compress, \"audit-log-compress\", o.Compress, \"If set, the rotated log files will be compressed using gzip.\")\n}","line":{"from":445,"to":461}} {"id":100018175,"name":"Validate","signature":"func (o *AuditLogOptions) Validate() []error","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"func (o *AuditLogOptions) Validate() []error {\n\t// Check whether the log backend is enabled based on the options.\n\tif !o.enabled() {\n\t\treturn nil\n\t}\n\n\tvar allErrors []error\n\n\tif err := validateBackendBatchOptions(pluginlog.PluginName, o.BatchOptions); err != nil {\n\t\tallErrors = append(allErrors, err)\n\t}\n\tif err := o.TruncateOptions.Validate(pluginlog.PluginName); err != nil {\n\t\tallErrors = append(allErrors, err)\n\t}\n\n\tif err := validateGroupVersionString(o.GroupVersionString); err != nil {\n\t\tallErrors = append(allErrors, err)\n\t}\n\n\t// Check log format\n\tif !sets.NewString(pluginlog.AllowedFormats...).Has(o.Format) {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"invalid audit log format %s, allowed formats are %q\", o.Format, strings.Join(pluginlog.AllowedFormats, \",\")))\n\t}\n\n\t// Check validities of MaxAge, MaxBackups and MaxSize of log options, if file log backend is enabled.\n\tif o.MaxAge \u003c 0 {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"--audit-log-maxage %v can't be a negative number\", o.MaxAge))\n\t}\n\tif o.MaxBackups \u003c 0 {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"--audit-log-maxbackup %v can't be a negative number\", o.MaxBackups))\n\t}\n\tif o.MaxSize \u003c 0 {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"--audit-log-maxsize %v can't be a negative number\", o.MaxSize))\n\t}\n\n\treturn allErrors\n}","line":{"from":463,"to":499}} {"id":100018176,"name":"enabled","signature":"func (o *AuditLogOptions) enabled() bool","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"// Check whether the log backend is enabled based on the options.\nfunc (o *AuditLogOptions) enabled() bool {\n\treturn o != nil \u0026\u0026 o.Path != \"\"\n}","line":{"from":501,"to":504}} {"id":100018177,"name":"getWriter","signature":"func (o *AuditLogOptions) getWriter() (io.Writer, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"func (o *AuditLogOptions) getWriter() (io.Writer, error) {\n\tif !o.enabled() {\n\t\treturn nil, nil\n\t}\n\n\tif o.Path == \"-\" {\n\t\treturn os.Stdout, nil\n\t}\n\n\tif err := o.ensureLogFile(); err != nil {\n\t\treturn nil, fmt.Errorf(\"ensureLogFile: %w\", err)\n\t}\n\n\treturn \u0026lumberjack.Logger{\n\t\tFilename: o.Path,\n\t\tMaxAge: o.MaxAge,\n\t\tMaxBackups: o.MaxBackups,\n\t\tMaxSize: o.MaxSize,\n\t\tCompress: o.Compress,\n\t}, nil\n}","line":{"from":506,"to":526}} {"id":100018178,"name":"ensureLogFile","signature":"func (o *AuditLogOptions) ensureLogFile() error","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"func (o *AuditLogOptions) ensureLogFile() error {\n\tif err := os.MkdirAll(filepath.Dir(o.Path), 0700); err != nil {\n\t\treturn err\n\t}\n\tmode := os.FileMode(0600)\n\tf, err := os.OpenFile(o.Path, os.O_CREATE|os.O_APPEND|os.O_RDWR, mode)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn f.Close()\n}","line":{"from":528,"to":538}} {"id":100018179,"name":"newBackend","signature":"func (o *AuditLogOptions) newBackend(w io.Writer) audit.Backend","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"func (o *AuditLogOptions) newBackend(w io.Writer) audit.Backend {\n\tgroupVersion, _ := schema.ParseGroupVersion(o.GroupVersionString)\n\tlog := pluginlog.NewBackend(w, o.Format, groupVersion)\n\tlog = o.BatchOptions.wrapBackend(log)\n\tlog = o.TruncateOptions.wrapBackend(log, groupVersion)\n\treturn log\n}","line":{"from":540,"to":546}} {"id":100018180,"name":"AddFlags","signature":"func (o *AuditWebhookOptions) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"func (o *AuditWebhookOptions) AddFlags(fs *pflag.FlagSet) {\n\tfs.StringVar(\u0026o.ConfigFile, \"audit-webhook-config-file\", o.ConfigFile,\n\t\t\"Path to a kubeconfig formatted file that defines the audit webhook configuration.\")\n\tfs.DurationVar(\u0026o.InitialBackoff, \"audit-webhook-initial-backoff\",\n\t\to.InitialBackoff, \"The amount of time to wait before retrying the first failed request.\")\n\tfs.DurationVar(\u0026o.InitialBackoff, \"audit-webhook-batch-initial-backoff\",\n\t\to.InitialBackoff, \"The amount of time to wait before retrying the first failed request.\")\n\tfs.MarkDeprecated(\"audit-webhook-batch-initial-backoff\",\n\t\t\"Deprecated, use --audit-webhook-initial-backoff instead.\")\n\tfs.StringVar(\u0026o.GroupVersionString, \"audit-webhook-version\", o.GroupVersionString,\n\t\t\"API group and version used for serializing audit events written to webhook.\")\n}","line":{"from":548,"to":559}} {"id":100018181,"name":"Validate","signature":"func (o *AuditWebhookOptions) Validate() []error","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"func (o *AuditWebhookOptions) Validate() []error {\n\tif !o.enabled() {\n\t\treturn nil\n\t}\n\n\tvar allErrors []error\n\tif err := validateBackendBatchOptions(pluginwebhook.PluginName, o.BatchOptions); err != nil {\n\t\tallErrors = append(allErrors, err)\n\t}\n\tif err := o.TruncateOptions.Validate(pluginwebhook.PluginName); err != nil {\n\t\tallErrors = append(allErrors, err)\n\t}\n\n\tif err := validateGroupVersionString(o.GroupVersionString); err != nil {\n\t\tallErrors = append(allErrors, err)\n\t}\n\treturn allErrors\n}","line":{"from":561,"to":578}} {"id":100018182,"name":"enabled","signature":"func (o *AuditWebhookOptions) enabled() bool","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"func (o *AuditWebhookOptions) enabled() bool {\n\treturn o != nil \u0026\u0026 o.ConfigFile != \"\"\n}","line":{"from":580,"to":582}} {"id":100018183,"name":"newUntruncatedBackend","signature":"func (o *AuditWebhookOptions) newUntruncatedBackend(customDial utilnet.DialFunc) (audit.Backend, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"// newUntruncatedBackend returns a webhook backend without the truncate options applied\n// this is done so that the same trucate backend can wrap both the webhook and dynamic backends\nfunc (o *AuditWebhookOptions) newUntruncatedBackend(customDial utilnet.DialFunc) (audit.Backend, error) {\n\tgroupVersion, _ := schema.ParseGroupVersion(o.GroupVersionString)\n\twebhook, err := pluginwebhook.NewBackend(o.ConfigFile, groupVersion, webhook.DefaultRetryBackoffWithInitialDelay(o.InitialBackoff), customDial)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"initializing audit webhook: %v\", err)\n\t}\n\twebhook = o.BatchOptions.wrapBackend(webhook)\n\treturn webhook, nil\n}","line":{"from":584,"to":594}} {"id":100018184,"name":"defaultWebhookBatchConfig","signature":"func defaultWebhookBatchConfig() pluginbuffered.BatchConfig","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"// defaultWebhookBatchConfig returns the default BatchConfig used by the Webhook backend.\nfunc defaultWebhookBatchConfig() pluginbuffered.BatchConfig {\n\treturn pluginbuffered.BatchConfig{\n\t\tBufferSize: defaultBatchBufferSize,\n\t\tMaxBatchSize: defaultBatchMaxSize,\n\t\tMaxBatchWait: defaultBatchMaxWait,\n\n\t\tThrottleEnable: true,\n\t\tThrottleQPS: defaultBatchThrottleQPS,\n\t\tThrottleBurst: defaultBatchThrottleBurst,\n\n\t\tAsyncDelegate: true,\n\t}\n}","line":{"from":596,"to":609}} {"id":100018185,"name":"defaultLogBatchConfig","signature":"func defaultLogBatchConfig() pluginbuffered.BatchConfig","file":"staging/src/k8s.io/apiserver/pkg/server/options/audit.go","code":"// defaultLogBatchConfig returns the default BatchConfig used by the Log backend.\nfunc defaultLogBatchConfig() pluginbuffered.BatchConfig {\n\treturn pluginbuffered.BatchConfig{\n\t\tBufferSize: defaultBatchBufferSize,\n\t\t// Batching is not useful for the log-file backend.\n\t\t// MaxBatchWait ignored.\n\t\tMaxBatchSize: 1,\n\t\tThrottleEnable: false,\n\t\t// Asynchronous log threads just create lock contention.\n\t\tAsyncDelegate: false,\n\t}\n}","line":{"from":611,"to":622}} {"id":100018186,"name":"DefaultAuthWebhookRetryBackoff","signature":"func DefaultAuthWebhookRetryBackoff() *wait.Backoff","file":"staging/src/k8s.io/apiserver/pkg/server/options/authentication.go","code":"// DefaultAuthWebhookRetryBackoff is the default backoff parameters for\n// both authentication and authorization webhook used by the apiserver.\nfunc DefaultAuthWebhookRetryBackoff() *wait.Backoff {\n\treturn \u0026wait.Backoff{\n\t\tDuration: 500 * time.Millisecond,\n\t\tFactor: 1.5,\n\t\tJitter: 0.2,\n\t\tSteps: 5,\n\t}\n}","line":{"from":41,"to":50}} {"id":100018187,"name":"Validate","signature":"func (s *RequestHeaderAuthenticationOptions) Validate() []error","file":"staging/src/k8s.io/apiserver/pkg/server/options/authentication.go","code":"func (s *RequestHeaderAuthenticationOptions) Validate() []error {\n\tallErrors := []error{}\n\n\tif err := checkForWhiteSpaceOnly(\"requestheader-username-headers\", s.UsernameHeaders...); err != nil {\n\t\tallErrors = append(allErrors, err)\n\t}\n\tif err := checkForWhiteSpaceOnly(\"requestheader-group-headers\", s.GroupHeaders...); err != nil {\n\t\tallErrors = append(allErrors, err)\n\t}\n\tif err := checkForWhiteSpaceOnly(\"requestheader-extra-headers-prefix\", s.ExtraHeaderPrefixes...); err != nil {\n\t\tallErrors = append(allErrors, err)\n\t}\n\tif err := checkForWhiteSpaceOnly(\"requestheader-allowed-names\", s.AllowedNames...); err != nil {\n\t\tallErrors = append(allErrors, err)\n\t}\n\n\tif len(s.UsernameHeaders) \u003e 0 \u0026\u0026 !caseInsensitiveHas(s.UsernameHeaders, \"X-Remote-User\") {\n\t\tklog.Warningf(\"--requestheader-username-headers is set without specifying the standard X-Remote-User header - API aggregation will not work\")\n\t}\n\tif len(s.GroupHeaders) \u003e 0 \u0026\u0026 !caseInsensitiveHas(s.GroupHeaders, \"X-Remote-Group\") {\n\t\tklog.Warningf(\"--requestheader-group-headers is set without specifying the standard X-Remote-Group header - API aggregation will not work\")\n\t}\n\tif len(s.ExtraHeaderPrefixes) \u003e 0 \u0026\u0026 !caseInsensitiveHas(s.ExtraHeaderPrefixes, \"X-Remote-Extra-\") {\n\t\tklog.Warningf(\"--requestheader-extra-headers-prefix is set without specifying the standard X-Remote-Extra- header prefix - API aggregation will not work\")\n\t}\n\n\treturn allErrors\n}","line":{"from":63,"to":90}} {"id":100018188,"name":"checkForWhiteSpaceOnly","signature":"func checkForWhiteSpaceOnly(flag string, headerNames ...string) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/authentication.go","code":"func checkForWhiteSpaceOnly(flag string, headerNames ...string) error {\n\tfor _, headerName := range headerNames {\n\t\tif len(strings.TrimSpace(headerName)) == 0 {\n\t\t\treturn fmt.Errorf(\"empty value in %q\", flag)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":92,"to":100}} {"id":100018189,"name":"caseInsensitiveHas","signature":"func caseInsensitiveHas(headers []string, header string) bool","file":"staging/src/k8s.io/apiserver/pkg/server/options/authentication.go","code":"func caseInsensitiveHas(headers []string, header string) bool {\n\tfor _, h := range headers {\n\t\tif strings.EqualFold(h, header) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":102,"to":109}} {"id":100018190,"name":"AddFlags","signature":"func (s *RequestHeaderAuthenticationOptions) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/apiserver/pkg/server/options/authentication.go","code":"func (s *RequestHeaderAuthenticationOptions) AddFlags(fs *pflag.FlagSet) {\n\tif s == nil {\n\t\treturn\n\t}\n\n\tfs.StringSliceVar(\u0026s.UsernameHeaders, \"requestheader-username-headers\", s.UsernameHeaders, \"\"+\n\t\t\"List of request headers to inspect for usernames. X-Remote-User is common.\")\n\n\tfs.StringSliceVar(\u0026s.GroupHeaders, \"requestheader-group-headers\", s.GroupHeaders, \"\"+\n\t\t\"List of request headers to inspect for groups. X-Remote-Group is suggested.\")\n\n\tfs.StringSliceVar(\u0026s.ExtraHeaderPrefixes, \"requestheader-extra-headers-prefix\", s.ExtraHeaderPrefixes, \"\"+\n\t\t\"List of request header prefixes to inspect. X-Remote-Extra- is suggested.\")\n\n\tfs.StringVar(\u0026s.ClientCAFile, \"requestheader-client-ca-file\", s.ClientCAFile, \"\"+\n\t\t\"Root certificate bundle to use to verify client certificates on incoming requests \"+\n\t\t\"before trusting usernames in headers specified by --requestheader-username-headers. \"+\n\t\t\"WARNING: generally do not depend on authorization being already done for incoming requests.\")\n\n\tfs.StringSliceVar(\u0026s.AllowedNames, \"requestheader-allowed-names\", s.AllowedNames, \"\"+\n\t\t\"List of client certificate common names to allow to provide usernames in headers \"+\n\t\t\"specified by --requestheader-username-headers. If empty, any client certificate validated \"+\n\t\t\"by the authorities in --requestheader-client-ca-file is allowed.\")\n}","line":{"from":111,"to":134}} {"id":100018191,"name":"ToAuthenticationRequestHeaderConfig","signature":"func (s *RequestHeaderAuthenticationOptions) ToAuthenticationRequestHeaderConfig() (*authenticatorfactory.RequestHeaderConfig, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/authentication.go","code":"// ToAuthenticationRequestHeaderConfig returns a RequestHeaderConfig config object for these options\n// if necessary, nil otherwise.\nfunc (s *RequestHeaderAuthenticationOptions) ToAuthenticationRequestHeaderConfig() (*authenticatorfactory.RequestHeaderConfig, error) {\n\tif len(s.ClientCAFile) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tcaBundleProvider, err := dynamiccertificates.NewDynamicCAContentFromFile(\"request-header\", s.ClientCAFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026authenticatorfactory.RequestHeaderConfig{\n\t\tUsernameHeaders: headerrequest.StaticStringSlice(s.UsernameHeaders),\n\t\tGroupHeaders: headerrequest.StaticStringSlice(s.GroupHeaders),\n\t\tExtraHeaderPrefixes: headerrequest.StaticStringSlice(s.ExtraHeaderPrefixes),\n\t\tCAContentProvider: caBundleProvider,\n\t\tAllowedClientNames: headerrequest.StaticStringSlice(s.AllowedNames),\n\t}, nil\n}","line":{"from":136,"to":155}} {"id":100018192,"name":"GetClientCAContentProvider","signature":"func (s *ClientCertAuthenticationOptions) GetClientCAContentProvider() (dynamiccertificates.CAContentProvider, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/authentication.go","code":"// GetClientVerifyOptionFn provides verify options for your authenticator while respecting the preferred order of verifiers.\nfunc (s *ClientCertAuthenticationOptions) GetClientCAContentProvider() (dynamiccertificates.CAContentProvider, error) {\n\tif s.CAContentProvider != nil {\n\t\treturn s.CAContentProvider, nil\n\t}\n\n\tif len(s.ClientCA) == 0 {\n\t\treturn nil, nil\n\t}\n\n\treturn dynamiccertificates.NewDynamicCAContentFromFile(\"client-ca-bundle\", s.ClientCA)\n}","line":{"from":169,"to":180}} {"id":100018193,"name":"AddFlags","signature":"func (s *ClientCertAuthenticationOptions) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/apiserver/pkg/server/options/authentication.go","code":"func (s *ClientCertAuthenticationOptions) AddFlags(fs *pflag.FlagSet) {\n\tfs.StringVar(\u0026s.ClientCA, \"client-ca-file\", s.ClientCA, \"\"+\n\t\t\"If set, any request presenting a client certificate signed by one of \"+\n\t\t\"the authorities in the client-ca-file is authenticated with an identity \"+\n\t\t\"corresponding to the CommonName of the client certificate.\")\n}","line":{"from":182,"to":187}} {"id":100018194,"name":"NewDelegatingAuthenticationOptions","signature":"func NewDelegatingAuthenticationOptions() *DelegatingAuthenticationOptions","file":"staging/src/k8s.io/apiserver/pkg/server/options/authentication.go","code":"func NewDelegatingAuthenticationOptions() *DelegatingAuthenticationOptions {\n\treturn \u0026DelegatingAuthenticationOptions{\n\t\t// very low for responsiveness, but high enough to handle storms\n\t\tCacheTTL: 10 * time.Second,\n\t\tClientCert: ClientCertAuthenticationOptions{},\n\t\tRequestHeader: RequestHeaderAuthenticationOptions{\n\t\t\tUsernameHeaders: []string{\"x-remote-user\"},\n\t\t\tGroupHeaders: []string{\"x-remote-group\"},\n\t\t\tExtraHeaderPrefixes: []string{\"x-remote-extra-\"},\n\t\t},\n\t\tWebhookRetryBackoff: DefaultAuthWebhookRetryBackoff(),\n\t\tTokenRequestTimeout: 10 * time.Second,\n\t}\n}","line":{"from":229,"to":242}} {"id":100018195,"name":"WithCustomRetryBackoff","signature":"func (s *DelegatingAuthenticationOptions) WithCustomRetryBackoff(backoff wait.Backoff)","file":"staging/src/k8s.io/apiserver/pkg/server/options/authentication.go","code":"// WithCustomRetryBackoff sets the custom backoff parameters for the authentication webhook retry logic.\nfunc (s *DelegatingAuthenticationOptions) WithCustomRetryBackoff(backoff wait.Backoff) {\n\ts.WebhookRetryBackoff = \u0026backoff\n}","line":{"from":244,"to":247}} {"id":100018196,"name":"WithRequestTimeout","signature":"func (s *DelegatingAuthenticationOptions) WithRequestTimeout(timeout time.Duration)","file":"staging/src/k8s.io/apiserver/pkg/server/options/authentication.go","code":"// WithRequestTimeout sets the given timeout for requests made by the authentication webhook client.\nfunc (s *DelegatingAuthenticationOptions) WithRequestTimeout(timeout time.Duration) {\n\ts.TokenRequestTimeout = timeout\n}","line":{"from":249,"to":252}} {"id":100018197,"name":"WithCustomRoundTripper","signature":"func (s *DelegatingAuthenticationOptions) WithCustomRoundTripper(rt transport.WrapperFunc)","file":"staging/src/k8s.io/apiserver/pkg/server/options/authentication.go","code":"// WithCustomRoundTripper allows for specifying a middleware function for custom HTTP behaviour for the authentication webhook client.\nfunc (s *DelegatingAuthenticationOptions) WithCustomRoundTripper(rt transport.WrapperFunc) {\n\ts.CustomRoundTripperFn = rt\n}","line":{"from":254,"to":257}} {"id":100018198,"name":"Validate","signature":"func (s *DelegatingAuthenticationOptions) Validate() []error","file":"staging/src/k8s.io/apiserver/pkg/server/options/authentication.go","code":"func (s *DelegatingAuthenticationOptions) Validate() []error {\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\tallErrors := []error{}\n\tallErrors = append(allErrors, s.RequestHeader.Validate()...)\n\n\tif s.WebhookRetryBackoff != nil \u0026\u0026 s.WebhookRetryBackoff.Steps \u003c= 0 {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"number of webhook retry attempts must be greater than 1, but is: %d\", s.WebhookRetryBackoff.Steps))\n\t}\n\n\treturn allErrors\n}","line":{"from":259,"to":272}} {"id":100018199,"name":"AddFlags","signature":"func (s *DelegatingAuthenticationOptions) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/apiserver/pkg/server/options/authentication.go","code":"func (s *DelegatingAuthenticationOptions) AddFlags(fs *pflag.FlagSet) {\n\tif s == nil {\n\t\treturn\n\t}\n\n\tvar optionalKubeConfigSentence string\n\tif s.RemoteKubeConfigFileOptional {\n\t\toptionalKubeConfigSentence = \" This is optional. If empty, all token requests are considered to be anonymous and no client CA is looked up in the cluster.\"\n\t}\n\tfs.StringVar(\u0026s.RemoteKubeConfigFile, \"authentication-kubeconfig\", s.RemoteKubeConfigFile, \"\"+\n\t\t\"kubeconfig file pointing at the 'core' kubernetes server with enough rights to create \"+\n\t\t\"tokenreviews.authentication.k8s.io.\"+optionalKubeConfigSentence)\n\n\tfs.DurationVar(\u0026s.CacheTTL, \"authentication-token-webhook-cache-ttl\", s.CacheTTL,\n\t\t\"The duration to cache responses from the webhook token authenticator.\")\n\n\ts.ClientCert.AddFlags(fs)\n\ts.RequestHeader.AddFlags(fs)\n\n\tfs.BoolVar(\u0026s.SkipInClusterLookup, \"authentication-skip-lookup\", s.SkipInClusterLookup, \"\"+\n\t\t\"If false, the authentication-kubeconfig will be used to lookup missing authentication \"+\n\t\t\"configuration from the cluster.\")\n\tfs.BoolVar(\u0026s.TolerateInClusterLookupFailure, \"authentication-tolerate-lookup-failure\", s.TolerateInClusterLookupFailure, \"\"+\n\t\t\"If true, failures to look up missing authentication configuration from the cluster are not considered fatal. \"+\n\t\t\"Note that this can result in authentication that treats all requests as anonymous.\")\n}","line":{"from":274,"to":299}} {"id":100018200,"name":"ApplyTo","signature":"func (s *DelegatingAuthenticationOptions) ApplyTo(authenticationInfo *server.AuthenticationInfo, servingInfo *server.SecureServingInfo, openAPIConfig *openapicommon.Config) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/authentication.go","code":"func (s *DelegatingAuthenticationOptions) ApplyTo(authenticationInfo *server.AuthenticationInfo, servingInfo *server.SecureServingInfo, openAPIConfig *openapicommon.Config) error {\n\tif s == nil {\n\t\tauthenticationInfo.Authenticator = nil\n\t\treturn nil\n\t}\n\n\tcfg := authenticatorfactory.DelegatingAuthenticatorConfig{\n\t\tAnonymous: !s.DisableAnonymous,\n\t\tCacheTTL: s.CacheTTL,\n\t\tWebhookRetryBackoff: s.WebhookRetryBackoff,\n\t\tTokenAccessReviewTimeout: s.TokenRequestTimeout,\n\t}\n\n\tclient, err := s.getClient()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get delegated authentication kubeconfig: %v\", err)\n\t}\n\n\t// configure token review\n\tif client != nil {\n\t\tcfg.TokenAccessReviewClient = client.AuthenticationV1()\n\t}\n\n\t// get the clientCA information\n\tclientCASpecified := s.ClientCert != ClientCertAuthenticationOptions{}\n\tvar clientCAProvider dynamiccertificates.CAContentProvider\n\tif clientCASpecified {\n\t\tclientCAProvider, err = s.ClientCert.GetClientCAContentProvider()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to load client CA provider: %v\", err)\n\t\t}\n\t\tcfg.ClientCertificateCAContentProvider = clientCAProvider\n\t\tif err = authenticationInfo.ApplyClientCert(cfg.ClientCertificateCAContentProvider, servingInfo); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to assign client CA provider: %v\", err)\n\t\t}\n\n\t} else if !s.SkipInClusterLookup {\n\t\tif client == nil {\n\t\t\tklog.Warningf(\"No authentication-kubeconfig provided in order to lookup client-ca-file in configmap/%s in %s, so client certificate authentication won't work.\", authenticationConfigMapName, authenticationConfigMapNamespace)\n\t\t} else {\n\t\t\tclientCAProvider, err = dynamiccertificates.NewDynamicCAFromConfigMapController(\"client-ca\", authenticationConfigMapNamespace, authenticationConfigMapName, \"client-ca-file\", client)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to load configmap based client CA file: %v\", err)\n\t\t\t}\n\t\t\tcfg.ClientCertificateCAContentProvider = clientCAProvider\n\t\t\tif err = authenticationInfo.ApplyClientCert(cfg.ClientCertificateCAContentProvider, servingInfo); err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to assign configmap based client CA file: %v\", err)\n\t\t\t}\n\n\t\t}\n\t}\n\n\trequestHeaderCAFileSpecified := len(s.RequestHeader.ClientCAFile) \u003e 0\n\tvar requestHeaderConfig *authenticatorfactory.RequestHeaderConfig\n\tif requestHeaderCAFileSpecified {\n\t\trequestHeaderConfig, err = s.RequestHeader.ToAuthenticationRequestHeaderConfig()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to create request header authentication config: %v\", err)\n\t\t}\n\n\t} else if !s.SkipInClusterLookup {\n\t\tif client == nil {\n\t\t\tklog.Warningf(\"No authentication-kubeconfig provided in order to lookup requestheader-client-ca-file in configmap/%s in %s, so request-header client certificate authentication won't work.\", authenticationConfigMapName, authenticationConfigMapNamespace)\n\t\t} else {\n\t\t\trequestHeaderConfig, err = s.createRequestHeaderConfig(client)\n\t\t\tif err != nil {\n\t\t\t\tif s.TolerateInClusterLookupFailure {\n\t\t\t\t\tklog.Warningf(\"Error looking up in-cluster authentication configuration: %v\", err)\n\t\t\t\t\tklog.Warning(\"Continuing without authentication configuration. This may treat all requests as anonymous.\")\n\t\t\t\t\tklog.Warning(\"To require authentication configuration lookup to succeed, set --authentication-tolerate-lookup-failure=false\")\n\t\t\t\t} else {\n\t\t\t\t\treturn fmt.Errorf(\"unable to load configmap based request-header-client-ca-file: %v\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif requestHeaderConfig != nil {\n\t\tcfg.RequestHeaderConfig = requestHeaderConfig\n\t\tauthenticationInfo.RequestHeaderConfig = requestHeaderConfig\n\t\tif err = authenticationInfo.ApplyClientCert(cfg.RequestHeaderConfig.CAContentProvider, servingInfo); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to load request-header-client-ca-file: %v\", err)\n\t\t}\n\t}\n\n\t// create authenticator\n\tauthenticator, securityDefinitions, err := cfg.New()\n\tif err != nil {\n\t\treturn err\n\t}\n\tauthenticationInfo.Authenticator = authenticator\n\tif openAPIConfig != nil {\n\t\topenAPIConfig.SecurityDefinitions = securityDefinitions\n\t}\n\n\treturn nil\n}","line":{"from":301,"to":396}} {"id":100018201,"name":"createRequestHeaderConfig","signature":"func (s *DelegatingAuthenticationOptions) createRequestHeaderConfig(client kubernetes.Interface) (*authenticatorfactory.RequestHeaderConfig, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/authentication.go","code":"func (s *DelegatingAuthenticationOptions) createRequestHeaderConfig(client kubernetes.Interface) (*authenticatorfactory.RequestHeaderConfig, error) {\n\tdynamicRequestHeaderProvider, err := newDynamicRequestHeaderController(client)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create request header authentication config: %v\", err)\n\t}\n\n\t// look up authentication configuration in the cluster and in case of an err defer to authentication-tolerate-lookup-failure flag\n\t// We are passing the context to ProxyCerts.RunOnce as it needs to implement RunOnce(ctx) however the\n\t// context is not used at all. So passing a empty context shouldn't be a problem\n\tctx := context.TODO()\n\tif err := dynamicRequestHeaderProvider.RunOnce(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026authenticatorfactory.RequestHeaderConfig{\n\t\tCAContentProvider: dynamicRequestHeaderProvider,\n\t\tUsernameHeaders: headerrequest.StringSliceProvider(headerrequest.StringSliceProviderFunc(dynamicRequestHeaderProvider.UsernameHeaders)),\n\t\tGroupHeaders: headerrequest.StringSliceProvider(headerrequest.StringSliceProviderFunc(dynamicRequestHeaderProvider.GroupHeaders)),\n\t\tExtraHeaderPrefixes: headerrequest.StringSliceProvider(headerrequest.StringSliceProviderFunc(dynamicRequestHeaderProvider.ExtraHeaderPrefixes)),\n\t\tAllowedClientNames: headerrequest.StringSliceProvider(headerrequest.StringSliceProviderFunc(dynamicRequestHeaderProvider.AllowedClientNames)),\n\t}, nil\n}","line":{"from":407,"to":428}} {"id":100018202,"name":"getClient","signature":"func (s *DelegatingAuthenticationOptions) getClient() (kubernetes.Interface, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/authentication.go","code":"// getClient returns a Kubernetes clientset. If s.RemoteKubeConfigFileOptional is true, nil will be returned\n// if no kubeconfig is specified by the user and the in-cluster config is not found.\nfunc (s *DelegatingAuthenticationOptions) getClient() (kubernetes.Interface, error) {\n\tvar clientConfig *rest.Config\n\tvar err error\n\tif len(s.RemoteKubeConfigFile) \u003e 0 {\n\t\tloadingRules := \u0026clientcmd.ClientConfigLoadingRules{ExplicitPath: s.RemoteKubeConfigFile}\n\t\tloader := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, \u0026clientcmd.ConfigOverrides{})\n\n\t\tclientConfig, err = loader.ClientConfig()\n\t} else {\n\t\t// without the remote kubeconfig file, try to use the in-cluster config. Most addon API servers will\n\t\t// use this path. If it is optional, ignore errors.\n\t\tclientConfig, err = rest.InClusterConfig()\n\t\tif err != nil \u0026\u0026 s.RemoteKubeConfigFileOptional {\n\t\t\tif err != rest.ErrNotInCluster {\n\t\t\t\tklog.Warningf(\"failed to read in-cluster kubeconfig for delegated authentication: %v\", err)\n\t\t\t}\n\t\t\treturn nil, nil\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get delegated authentication kubeconfig: %v\", err)\n\t}\n\n\t// set high qps/burst limits since this will effectively limit API server responsiveness\n\tclientConfig.QPS = 200\n\tclientConfig.Burst = 400\n\t// do not set a timeout on the http client, instead use context for cancellation\n\t// if multiple timeouts were set, the request will pick the smaller timeout to be applied, leaving other useless.\n\t//\n\t// see https://github.com/golang/go/blob/a937729c2c2f6950a32bc5cd0f5b88700882f078/src/net/http/client.go#L364\n\tif s.CustomRoundTripperFn != nil {\n\t\tclientConfig.Wrap(s.CustomRoundTripperFn)\n\t}\n\n\treturn kubernetes.NewForConfig(clientConfig)\n}","line":{"from":430,"to":467}} {"id":100018203,"name":"newDynamicRequestHeaderController","signature":"func newDynamicRequestHeaderController(client kubernetes.Interface) (*DynamicRequestHeaderController, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/authentication_dynamic_request_header.go","code":"// newDynamicRequestHeaderController creates a new controller that implements DynamicRequestHeaderController\nfunc newDynamicRequestHeaderController(client kubernetes.Interface) (*DynamicRequestHeaderController, error) {\n\trequestHeaderCAController, err := dynamiccertificates.NewDynamicCAFromConfigMapController(\n\t\t\"client-ca\",\n\t\tauthenticationConfigMapNamespace,\n\t\tauthenticationConfigMapName,\n\t\t\"requestheader-client-ca-file\",\n\t\tclient)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create DynamicCAFromConfigMap controller: %v\", err)\n\t}\n\n\trequestHeaderAuthRequestController := headerrequest.NewRequestHeaderAuthRequestController(\n\t\tauthenticationConfigMapName,\n\t\tauthenticationConfigMapNamespace,\n\t\tclient,\n\t\t\"requestheader-username-headers\",\n\t\t\"requestheader-group-headers\",\n\t\t\"requestheader-extra-headers-prefix\",\n\t\t\"requestheader-allowed-names\",\n\t)\n\treturn \u0026DynamicRequestHeaderController{\n\t\tConfigMapCAController: requestHeaderCAController,\n\t\tRequestHeaderAuthRequestController: requestHeaderAuthRequestController,\n\t}, nil\n}","line":{"from":41,"to":66}} {"id":100018204,"name":"RunOnce","signature":"func (c *DynamicRequestHeaderController) RunOnce(ctx context.Context) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/authentication_dynamic_request_header.go","code":"func (c *DynamicRequestHeaderController) RunOnce(ctx context.Context) error {\n\terrs := []error{}\n\terrs = append(errs, c.ConfigMapCAController.RunOnce(ctx))\n\terrs = append(errs, c.RequestHeaderAuthRequestController.RunOnce(ctx))\n\treturn errors.NewAggregate(errs)\n}","line":{"from":68,"to":73}} {"id":100018205,"name":"Run","signature":"func (c *DynamicRequestHeaderController) Run(ctx context.Context, workers int)","file":"staging/src/k8s.io/apiserver/pkg/server/options/authentication_dynamic_request_header.go","code":"func (c *DynamicRequestHeaderController) Run(ctx context.Context, workers int) {\n\tgo c.ConfigMapCAController.Run(ctx, workers)\n\tgo c.RequestHeaderAuthRequestController.Run(ctx, workers)\n\t\u003c-ctx.Done()\n}","line":{"from":75,"to":79}} {"id":100018206,"name":"NewDelegatingAuthorizationOptions","signature":"func NewDelegatingAuthorizationOptions() *DelegatingAuthorizationOptions","file":"staging/src/k8s.io/apiserver/pkg/server/options/authorization.go","code":"func NewDelegatingAuthorizationOptions() *DelegatingAuthorizationOptions {\n\treturn \u0026DelegatingAuthorizationOptions{\n\t\t// very low for responsiveness, but high enough to handle storms\n\t\tAllowCacheTTL: 10 * time.Second,\n\t\tDenyCacheTTL: 10 * time.Second,\n\t\tClientTimeout: 10 * time.Second,\n\t\tWebhookRetryBackoff: DefaultAuthWebhookRetryBackoff(),\n\t\t// This allows the kubelet to always get health and readiness without causing an authorization check.\n\t\t// This field can be cleared by callers if they don't want this behavior.\n\t\tAlwaysAllowPaths: []string{\"/healthz\", \"/readyz\", \"/livez\"},\n\t\t// In an authorization call delegated to a kube-apiserver (the expected common-case), system:masters has full\n\t\t// authority in a hard-coded authorizer. This means that our default can reasonably be to skip an authorization\n\t\t// check for system:masters.\n\t\t// This field can be cleared by callers if they don't want this behavior.\n\t\tAlwaysAllowGroups: []string{\"system:masters\"},\n\t}\n}","line":{"from":78,"to":94}} {"id":100018207,"name":"WithAlwaysAllowGroups","signature":"func (s *DelegatingAuthorizationOptions) WithAlwaysAllowGroups(groups ...string) *DelegatingAuthorizationOptions","file":"staging/src/k8s.io/apiserver/pkg/server/options/authorization.go","code":"// WithAlwaysAllowGroups appends the list of paths to AlwaysAllowGroups\nfunc (s *DelegatingAuthorizationOptions) WithAlwaysAllowGroups(groups ...string) *DelegatingAuthorizationOptions {\n\ts.AlwaysAllowGroups = append(s.AlwaysAllowGroups, groups...)\n\treturn s\n}","line":{"from":96,"to":100}} {"id":100018208,"name":"WithAlwaysAllowPaths","signature":"func (s *DelegatingAuthorizationOptions) WithAlwaysAllowPaths(paths ...string) *DelegatingAuthorizationOptions","file":"staging/src/k8s.io/apiserver/pkg/server/options/authorization.go","code":"// WithAlwaysAllowPaths appends the list of paths to AlwaysAllowPaths\nfunc (s *DelegatingAuthorizationOptions) WithAlwaysAllowPaths(paths ...string) *DelegatingAuthorizationOptions {\n\ts.AlwaysAllowPaths = append(s.AlwaysAllowPaths, paths...)\n\treturn s\n}","line":{"from":102,"to":106}} {"id":100018209,"name":"WithClientTimeout","signature":"func (s *DelegatingAuthorizationOptions) WithClientTimeout(timeout time.Duration)","file":"staging/src/k8s.io/apiserver/pkg/server/options/authorization.go","code":"// WithClientTimeout sets the given timeout for SAR client used by this authorizer\nfunc (s *DelegatingAuthorizationOptions) WithClientTimeout(timeout time.Duration) {\n\ts.ClientTimeout = timeout\n}","line":{"from":108,"to":111}} {"id":100018210,"name":"WithCustomRetryBackoff","signature":"func (s *DelegatingAuthorizationOptions) WithCustomRetryBackoff(backoff wait.Backoff)","file":"staging/src/k8s.io/apiserver/pkg/server/options/authorization.go","code":"// WithCustomRetryBackoff sets the custom backoff parameters for the authorization webhook retry logic.\nfunc (s *DelegatingAuthorizationOptions) WithCustomRetryBackoff(backoff wait.Backoff) {\n\ts.WebhookRetryBackoff = \u0026backoff\n}","line":{"from":113,"to":116}} {"id":100018211,"name":"WithCustomRoundTripper","signature":"func (s *DelegatingAuthorizationOptions) WithCustomRoundTripper(rt transport.WrapperFunc)","file":"staging/src/k8s.io/apiserver/pkg/server/options/authorization.go","code":"// WithCustomRoundTripper allows for specifying a middleware function for custom HTTP behaviour for the authorization webhook client.\nfunc (s *DelegatingAuthorizationOptions) WithCustomRoundTripper(rt transport.WrapperFunc) {\n\ts.CustomRoundTripperFn = rt\n}","line":{"from":118,"to":121}} {"id":100018212,"name":"Validate","signature":"func (s *DelegatingAuthorizationOptions) Validate() []error","file":"staging/src/k8s.io/apiserver/pkg/server/options/authorization.go","code":"func (s *DelegatingAuthorizationOptions) Validate() []error {\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\tallErrors := []error{}\n\tif s.WebhookRetryBackoff != nil \u0026\u0026 s.WebhookRetryBackoff.Steps \u003c= 0 {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"number of webhook retry attempts must be greater than 1, but is: %d\", s.WebhookRetryBackoff.Steps))\n\t}\n\n\treturn allErrors\n}","line":{"from":123,"to":134}} {"id":100018213,"name":"AddFlags","signature":"func (s *DelegatingAuthorizationOptions) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/apiserver/pkg/server/options/authorization.go","code":"func (s *DelegatingAuthorizationOptions) AddFlags(fs *pflag.FlagSet) {\n\tif s == nil {\n\t\treturn\n\t}\n\n\tvar optionalKubeConfigSentence string\n\tif s.RemoteKubeConfigFileOptional {\n\t\toptionalKubeConfigSentence = \" This is optional. If empty, all requests not skipped by authorization are forbidden.\"\n\t}\n\tfs.StringVar(\u0026s.RemoteKubeConfigFile, \"authorization-kubeconfig\", s.RemoteKubeConfigFile,\n\t\t\"kubeconfig file pointing at the 'core' kubernetes server with enough rights to create \"+\n\t\t\t\"subjectaccessreviews.authorization.k8s.io.\"+optionalKubeConfigSentence)\n\n\tfs.DurationVar(\u0026s.AllowCacheTTL, \"authorization-webhook-cache-authorized-ttl\",\n\t\ts.AllowCacheTTL,\n\t\t\"The duration to cache 'authorized' responses from the webhook authorizer.\")\n\n\tfs.DurationVar(\u0026s.DenyCacheTTL,\n\t\t\"authorization-webhook-cache-unauthorized-ttl\", s.DenyCacheTTL,\n\t\t\"The duration to cache 'unauthorized' responses from the webhook authorizer.\")\n\n\tfs.StringSliceVar(\u0026s.AlwaysAllowPaths, \"authorization-always-allow-paths\", s.AlwaysAllowPaths,\n\t\t\"A list of HTTP paths to skip during authorization, i.e. these are authorized without \"+\n\t\t\t\"contacting the 'core' kubernetes server.\")\n}","line":{"from":136,"to":160}} {"id":100018214,"name":"ApplyTo","signature":"func (s *DelegatingAuthorizationOptions) ApplyTo(c *server.AuthorizationInfo) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/authorization.go","code":"func (s *DelegatingAuthorizationOptions) ApplyTo(c *server.AuthorizationInfo) error {\n\tif s == nil {\n\t\tc.Authorizer = authorizerfactory.NewAlwaysAllowAuthorizer()\n\t\treturn nil\n\t}\n\n\tclient, err := s.getClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.Authorizer, err = s.toAuthorizer(client)\n\treturn err\n}","line":{"from":162,"to":175}} {"id":100018215,"name":"toAuthorizer","signature":"func (s *DelegatingAuthorizationOptions) toAuthorizer(client kubernetes.Interface) (authorizer.Authorizer, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/authorization.go","code":"func (s *DelegatingAuthorizationOptions) toAuthorizer(client kubernetes.Interface) (authorizer.Authorizer, error) {\n\tvar authorizers []authorizer.Authorizer\n\n\tif len(s.AlwaysAllowGroups) \u003e 0 {\n\t\tauthorizers = append(authorizers, authorizerfactory.NewPrivilegedGroups(s.AlwaysAllowGroups...))\n\t}\n\n\tif len(s.AlwaysAllowPaths) \u003e 0 {\n\t\ta, err := path.NewAuthorizer(s.AlwaysAllowPaths)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tauthorizers = append(authorizers, a)\n\t}\n\n\tif client == nil {\n\t\tklog.Warning(\"No authorization-kubeconfig provided, so SubjectAccessReview of authorization tokens won't work.\")\n\t} else {\n\t\tcfg := authorizerfactory.DelegatingAuthorizerConfig{\n\t\t\tSubjectAccessReviewClient: client.AuthorizationV1(),\n\t\t\tAllowCacheTTL: s.AllowCacheTTL,\n\t\t\tDenyCacheTTL: s.DenyCacheTTL,\n\t\t\tWebhookRetryBackoff: s.WebhookRetryBackoff,\n\t\t}\n\t\tdelegatedAuthorizer, err := cfg.New()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tauthorizers = append(authorizers, delegatedAuthorizer)\n\t}\n\n\treturn union.New(authorizers...), nil\n}","line":{"from":177,"to":209}} {"id":100018216,"name":"getClient","signature":"func (s *DelegatingAuthorizationOptions) getClient() (kubernetes.Interface, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/authorization.go","code":"func (s *DelegatingAuthorizationOptions) getClient() (kubernetes.Interface, error) {\n\tvar clientConfig *rest.Config\n\tvar err error\n\tif len(s.RemoteKubeConfigFile) \u003e 0 {\n\t\tloadingRules := \u0026clientcmd.ClientConfigLoadingRules{ExplicitPath: s.RemoteKubeConfigFile}\n\t\tloader := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, \u0026clientcmd.ConfigOverrides{})\n\n\t\tclientConfig, err = loader.ClientConfig()\n\t} else {\n\t\t// without the remote kubeconfig file, try to use the in-cluster config. Most addon API servers will\n\t\t// use this path. If it is optional, ignore errors.\n\t\tclientConfig, err = rest.InClusterConfig()\n\t\tif err != nil \u0026\u0026 s.RemoteKubeConfigFileOptional {\n\t\t\tif err != rest.ErrNotInCluster {\n\t\t\t\tklog.Warningf(\"failed to read in-cluster kubeconfig for delegated authorization: %v\", err)\n\t\t\t}\n\t\t\treturn nil, nil\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get delegated authorization kubeconfig: %v\", err)\n\t}\n\n\t// set high qps/burst limits since this will effectively limit API server responsiveness\n\tclientConfig.QPS = 200\n\tclientConfig.Burst = 400\n\tclientConfig.Timeout = s.ClientTimeout\n\tif s.CustomRoundTripperFn != nil {\n\t\tclientConfig.Wrap(s.CustomRoundTripperFn)\n\t}\n\n\treturn kubernetes.NewForConfig(clientConfig)\n}","line":{"from":211,"to":243}} {"id":100018217,"name":"NewCoreAPIOptions","signature":"func NewCoreAPIOptions() *CoreAPIOptions","file":"staging/src/k8s.io/apiserver/pkg/server/options/coreapi.go","code":"func NewCoreAPIOptions() *CoreAPIOptions {\n\treturn \u0026CoreAPIOptions{}\n}","line":{"from":41,"to":43}} {"id":100018218,"name":"AddFlags","signature":"func (o *CoreAPIOptions) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/apiserver/pkg/server/options/coreapi.go","code":"func (o *CoreAPIOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.StringVar(\u0026o.CoreAPIKubeconfigPath, \"kubeconfig\", o.CoreAPIKubeconfigPath,\n\t\t\"kubeconfig file pointing at the 'core' kubernetes server.\")\n}","line":{"from":45,"to":52}} {"id":100018219,"name":"ApplyTo","signature":"func (o *CoreAPIOptions) ApplyTo(config *server.RecommendedConfig) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/coreapi.go","code":"func (o *CoreAPIOptions) ApplyTo(config *server.RecommendedConfig) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\t// create shared informer for Kubernetes APIs\n\tvar kubeconfig *rest.Config\n\tvar err error\n\tif len(o.CoreAPIKubeconfigPath) \u003e 0 {\n\t\tloadingRules := \u0026clientcmd.ClientConfigLoadingRules{ExplicitPath: o.CoreAPIKubeconfigPath}\n\t\tloader := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, \u0026clientcmd.ConfigOverrides{})\n\t\tkubeconfig, err = loader.ClientConfig()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to load kubeconfig at %q: %v\", o.CoreAPIKubeconfigPath, err)\n\t\t}\n\t} else {\n\t\tkubeconfig, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif feature.DefaultFeatureGate.Enabled(features.APIServerTracing) {\n\t\tkubeconfig.Wrap(tracing.WrapperFor(config.TracerProvider))\n\t}\n\tclientgoExternalClient, err := clientgoclientset.NewForConfig(kubeconfig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create Kubernetes clientset: %v\", err)\n\t}\n\tconfig.ClientConfig = kubeconfig\n\tconfig.SharedInformerFactory = clientgoinformers.NewSharedInformerFactory(clientgoExternalClient, 10*time.Minute)\n\n\treturn nil\n}","line":{"from":54,"to":86}} {"id":100018220,"name":"Validate","signature":"func (o *CoreAPIOptions) Validate() []error","file":"staging/src/k8s.io/apiserver/pkg/server/options/coreapi.go","code":"func (o *CoreAPIOptions) Validate() []error {\n\treturn nil\n}","line":{"from":88,"to":90}} {"id":100018221,"name":"Validate","signature":"func (s *DeprecatedInsecureServingOptions) Validate() []error","file":"staging/src/k8s.io/apiserver/pkg/server/options/deprecated_insecure_serving.go","code":"// Validate ensures that the insecure port values within the range of the port.\nfunc (s *DeprecatedInsecureServingOptions) Validate() []error {\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\terrors := []error{}\n\n\tif s.BindPort \u003c 0 || s.BindPort \u003e 65535 {\n\t\terrors = append(errors, fmt.Errorf(\"insecure port %v must be between 0 and 65535, inclusive. 0 for turning off insecure (HTTP) port\", s.BindPort))\n\t}\n\n\treturn errors\n}","line":{"from":48,"to":61}} {"id":100018222,"name":"AddFlags","signature":"func (s *DeprecatedInsecureServingOptions) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/apiserver/pkg/server/options/deprecated_insecure_serving.go","code":"// AddFlags adds flags related to insecure serving to the specified FlagSet.\nfunc (s *DeprecatedInsecureServingOptions) AddFlags(fs *pflag.FlagSet) {\n\tif s == nil {\n\t\treturn\n\t}\n\n\tfs.IPVar(\u0026s.BindAddress, \"insecure-bind-address\", s.BindAddress, \"\"+\n\t\t\"The IP address on which to serve the --insecure-port (set to 0.0.0.0 or :: for listening in all interfaces and IP families).\")\n\t// Though this flag is deprecated, we discovered security concerns over how to do health checks without it e.g. #43784\n\tfs.MarkDeprecated(\"insecure-bind-address\", \"This flag will be removed in a future version.\")\n\tfs.Lookup(\"insecure-bind-address\").Hidden = false\n\n\tfs.IntVar(\u0026s.BindPort, \"insecure-port\", s.BindPort, \"\"+\n\t\t\"The port on which to serve unsecured, unauthenticated access.\")\n\t// Though this flag is deprecated, we discovered security concerns over how to do health checks without it e.g. #43784\n\tfs.MarkDeprecated(\"insecure-port\", \"This flag will be removed in a future version.\")\n\tfs.Lookup(\"insecure-port\").Hidden = false\n}","line":{"from":63,"to":80}} {"id":100018223,"name":"AddUnqualifiedFlags","signature":"func (s *DeprecatedInsecureServingOptions) AddUnqualifiedFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/apiserver/pkg/server/options/deprecated_insecure_serving.go","code":"// AddUnqualifiedFlags adds flags related to insecure serving without the --insecure prefix to the specified FlagSet.\nfunc (s *DeprecatedInsecureServingOptions) AddUnqualifiedFlags(fs *pflag.FlagSet) {\n\tif s == nil {\n\t\treturn\n\t}\n\n\tfs.IPVar(\u0026s.BindAddress, \"address\", s.BindAddress,\n\t\t\"The IP address on which to serve the insecure --port (set to '0.0.0.0' or '::' for listening in all interfaces and IP families).\")\n\tfs.MarkDeprecated(\"address\", \"see --bind-address instead.\")\n\tfs.Lookup(\"address\").Hidden = false\n\n\tfs.IntVar(\u0026s.BindPort, \"port\", s.BindPort, \"The port on which to serve unsecured, unauthenticated access. Set to 0 to disable.\")\n\tfs.MarkDeprecated(\"port\", \"see --secure-port instead.\")\n\tfs.Lookup(\"port\").Hidden = false\n}","line":{"from":82,"to":96}} {"id":100018224,"name":"ApplyTo","signature":"func (s *DeprecatedInsecureServingOptions) ApplyTo(c **server.DeprecatedInsecureServingInfo) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/deprecated_insecure_serving.go","code":"// ApplyTo adds DeprecatedInsecureServingOptions to the insecureserverinfo and kube-controller manager configuration.\n// Note: the double pointer allows to set the *DeprecatedInsecureServingInfo to nil without referencing the struct hosting this pointer.\nfunc (s *DeprecatedInsecureServingOptions) ApplyTo(c **server.DeprecatedInsecureServingInfo) error {\n\tif s == nil {\n\t\treturn nil\n\t}\n\tif s.BindPort \u003c= 0 {\n\t\treturn nil\n\t}\n\n\tif s.Listener == nil {\n\t\tvar err error\n\t\tlisten := CreateListener\n\t\tif s.ListenFunc != nil {\n\t\t\tlisten = s.ListenFunc\n\t\t}\n\t\taddr := net.JoinHostPort(s.BindAddress.String(), fmt.Sprintf(\"%d\", s.BindPort))\n\t\ts.Listener, s.BindPort, err = listen(s.BindNetwork, addr, net.ListenConfig{})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create listener: %v\", err)\n\t\t}\n\t}\n\n\t*c = \u0026server.DeprecatedInsecureServingInfo{\n\t\tListener: s.Listener,\n\t}\n\n\treturn nil\n}","line":{"from":98,"to":126}} {"id":100018225,"name":"NewEgressSelectorOptions","signature":"func NewEgressSelectorOptions() *EgressSelectorOptions","file":"staging/src/k8s.io/apiserver/pkg/server/options/egress_selector.go","code":"// NewEgressSelectorOptions creates a new instance of EgressSelectorOptions\n//\n// The option is to point to a configuration file for egress/konnectivity.\n// This determines which types of requests use egress/konnectivity and how they use it.\n// If empty the API Server will attempt to connect directly using the network.\nfunc NewEgressSelectorOptions() *EgressSelectorOptions {\n\treturn \u0026EgressSelectorOptions{}\n}","line":{"from":36,"to":43}} {"id":100018226,"name":"AddFlags","signature":"func (o *EgressSelectorOptions) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/apiserver/pkg/server/options/egress_selector.go","code":"// AddFlags adds flags related to admission for a specific APIServer to the specified FlagSet\nfunc (o *EgressSelectorOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.StringVar(\u0026o.ConfigFile, \"egress-selector-config-file\", o.ConfigFile,\n\t\t\"File with apiserver egress selector configuration.\")\n}","line":{"from":45,"to":53}} {"id":100018227,"name":"ApplyTo","signature":"func (o *EgressSelectorOptions) ApplyTo(c *server.Config) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/egress_selector.go","code":"// ApplyTo adds the egress selector settings to the server configuration.\n// In case egress selector settings were not provided by a cluster-admin\n// they will be prepared from the recommended/default/no-op values.\nfunc (o *EgressSelectorOptions) ApplyTo(c *server.Config) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tnpConfig, err := egressselector.ReadEgressSelectorConfiguration(o.ConfigFile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to read egress selector config: %v\", err)\n\t}\n\terrs := egressselector.ValidateEgressSelectorConfiguration(npConfig)\n\tif len(errs) \u003e 0 {\n\t\treturn fmt.Errorf(\"failed to validate egress selector configuration: %v\", errs.ToAggregate())\n\t}\n\n\tcs, err := egressselector.NewEgressSelector(npConfig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to setup egress selector with config %#v: %v\", npConfig, err)\n\t}\n\tc.EgressSelector = cs\n\treturn nil\n}","line":{"from":55,"to":78}} {"id":100018228,"name":"Validate","signature":"func (o *EgressSelectorOptions) Validate() []error","file":"staging/src/k8s.io/apiserver/pkg/server/options/egress_selector.go","code":"// Validate verifies flags passed to EgressSelectorOptions.\nfunc (o *EgressSelectorOptions) Validate() []error {\n\tif o == nil || o.ConfigFile == \"\" {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\n\tif exists, err := path.Exists(path.CheckFollowSymlink, o.ConfigFile); !exists || err != nil {\n\t\terrs = append(errs, fmt.Errorf(\"egress-selector-config-file %s does not exist\", o.ConfigFile))\n\t}\n\n\treturn errs\n}","line":{"from":80,"to":93}} {"id":100018229,"name":"Name","signature":"func (k kmsHealthChecker) Name() string","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"func (k kmsHealthChecker) Name() string {\n\treturn kmsReloadHealthCheckName\n}","line":{"from":130,"to":132}} {"id":100018230,"name":"Check","signature":"func (k kmsHealthChecker) Check(req *http.Request) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"func (k kmsHealthChecker) Check(req *http.Request) error {\n\tvar errs []error\n\n\tfor i := range k {\n\t\tchecker := k[i]\n\t\tif err := checker.Check(req); err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"%s: %w\", checker.Name(), err))\n\t\t}\n\t}\n\n\treturn utilerrors.Reduce(utilerrors.NewAggregate(errs))\n}","line":{"from":134,"to":145}} {"id":100018231,"name":"toHealthzCheck","signature":"func (h *kmsPluginProbe) toHealthzCheck(idx int) healthz.HealthChecker","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"func (h *kmsPluginProbe) toHealthzCheck(idx int) healthz.HealthChecker {\n\treturn healthz.NamedCheck(fmt.Sprintf(\"kms-provider-%d\", idx), func(r *http.Request) error {\n\t\treturn h.check()\n\t})\n}","line":{"from":147,"to":151}} {"id":100018232,"name":"toHealthzCheck","signature":"func (h *kmsv2PluginProbe) toHealthzCheck(idx int) healthz.HealthChecker","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"func (h *kmsv2PluginProbe) toHealthzCheck(idx int) healthz.HealthChecker {\n\treturn healthz.NamedCheck(fmt.Sprintf(\"kms-provider-%d\", idx), func(r *http.Request) error {\n\t\treturn h.check(r.Context())\n\t})\n}","line":{"from":153,"to":157}} {"id":100018233,"name":"LoadEncryptionConfig","signature":"func LoadEncryptionConfig(ctx context.Context, filepath string, reload bool) (*EncryptionConfiguration, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"// LoadEncryptionConfig parses and validates the encryption config specified by filepath.\n// It may launch multiple go routines whose lifecycle is controlled by ctx.\n// In case of an error, the caller is responsible for canceling ctx to clean up any go routines that may have been launched.\n// If reload is true, or KMS v2 plugins are used with no KMS v1 plugins, the returned slice of health checkers will always be of length 1.\nfunc LoadEncryptionConfig(ctx context.Context, filepath string, reload bool) (*EncryptionConfiguration, error) {\n\tconfig, contentHash, err := loadConfig(filepath, reload)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while parsing file: %w\", err)\n\t}\n\n\ttransformers, kmsHealthChecks, kmsUsed, err := getTransformerOverridesAndKMSPluginHealthzCheckers(ctx, config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while building transformers: %w\", err)\n\t}\n\n\tif reload || (kmsUsed.v2Used \u0026\u0026 !kmsUsed.v1Used) {\n\t\tkmsHealthChecks = []healthz.HealthChecker{kmsHealthChecker(kmsHealthChecks)}\n\t}\n\n\t// KMSCloseGracePeriod is the duration we will wait before closing old transformers.\n\t// The way we calculate is as follows:\n\t// 1. Sum all timeouts across all KMS plugins. (check kmsPrefixTransformer for differences between v1 and v2)\n\t// 2. Multiply that by 2 (to allow for some buffer)\n\t// The reason we sum all timeout is because kmsHealthChecker() will run all health checks serially\n\treturn \u0026EncryptionConfiguration{\n\t\tTransformers: transformers,\n\t\tHealthChecks: kmsHealthChecks,\n\t\tEncryptionFileContentHash: contentHash,\n\t\tKMSCloseGracePeriod: 2 * kmsUsed.kmsTimeoutSum,\n\t}, nil\n}","line":{"from":175,"to":205}} {"id":100018234,"name":"getTransformerOverridesAndKMSPluginHealthzCheckers","signature":"func getTransformerOverridesAndKMSPluginHealthzCheckers(ctx context.Context, config *apiserverconfig.EncryptionConfiguration) (map[schema.GroupResource]value.Transformer, []healthz.HealthChecker, *kmsState, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"// getTransformerOverridesAndKMSPluginHealthzCheckers creates the set of transformers and KMS healthz checks based on the given config.\n// It may launch multiple go routines whose lifecycle is controlled by ctx.\n// In case of an error, the caller is responsible for canceling ctx to clean up any go routines that may have been launched.\nfunc getTransformerOverridesAndKMSPluginHealthzCheckers(ctx context.Context, config *apiserverconfig.EncryptionConfiguration) (map[schema.GroupResource]value.Transformer, []healthz.HealthChecker, *kmsState, error) {\n\tvar kmsHealthChecks []healthz.HealthChecker\n\ttransformers, probes, kmsUsed, err := getTransformerOverridesAndKMSPluginProbes(ctx, config)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tfor i := range probes {\n\t\tprobe := probes[i]\n\t\tkmsHealthChecks = append(kmsHealthChecks, probe.toHealthzCheck(i))\n\t}\n\n\treturn transformers, kmsHealthChecks, kmsUsed, nil\n}","line":{"from":207,"to":222}} {"id":100018235,"name":"getTransformerOverridesAndKMSPluginProbes","signature":"func getTransformerOverridesAndKMSPluginProbes(ctx context.Context, config *apiserverconfig.EncryptionConfiguration) (map[schema.GroupResource]value.Transformer, []healthChecker, *kmsState, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"// getTransformerOverridesAndKMSPluginProbes creates the set of transformers and KMS probes based on the given config.\n// It may launch multiple go routines whose lifecycle is controlled by ctx.\n// In case of an error, the caller is responsible for canceling ctx to clean up any go routines that may have been launched.\nfunc getTransformerOverridesAndKMSPluginProbes(ctx context.Context, config *apiserverconfig.EncryptionConfiguration) (map[schema.GroupResource]value.Transformer, []healthChecker, *kmsState, error) {\n\tresourceToPrefixTransformer := map[schema.GroupResource][]value.PrefixTransformer{}\n\tvar probes []healthChecker\n\tvar kmsUsed kmsState\n\n\t// For each entry in the configuration\n\tfor _, resourceConfig := range config.Resources {\n\t\tresourceConfig := resourceConfig\n\n\t\ttransformers, p, used, err := prefixTransformersAndProbes(ctx, resourceConfig)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t\tkmsUsed.accumulate(used)\n\n\t\t// For each resource, create a list of providers to use\n\t\tfor _, resource := range resourceConfig.Resources {\n\t\t\tresource := resource\n\t\t\tgr := schema.ParseGroupResource(resource)\n\n\t\t\t// check if resource is masked by *.group rule\n\t\t\tanyResourceInGroup := schema.GroupResource{Group: gr.Group, Resource: \"*\"}\n\t\t\tif _, masked := resourceToPrefixTransformer[anyResourceInGroup]; masked {\n\t\t\t\t// an earlier rule already configured a transformer for *.group, masking this rule\n\t\t\t\t// return error since this is not allowed\n\t\t\t\treturn nil, nil, nil, fmt.Errorf(\"resource %q is masked by earlier rule %q\", grYAMLString(gr), grYAMLString(anyResourceInGroup))\n\t\t\t}\n\n\t\t\tif _, masked := resourceToPrefixTransformer[anyGroupAnyResource]; masked {\n\t\t\t\t// an earlier rule already configured a transformer for *.*, masking this rule\n\t\t\t\t// return error since this is not allowed\n\t\t\t\treturn nil, nil, nil, fmt.Errorf(\"resource %q is masked by earlier rule %q\", grYAMLString(gr), grYAMLString(anyGroupAnyResource))\n\t\t\t}\n\n\t\t\tresourceToPrefixTransformer[gr] = append(resourceToPrefixTransformer[gr], transformers...)\n\t\t}\n\n\t\tprobes = append(probes, p...)\n\t}\n\n\ttransformers := make(map[schema.GroupResource]value.Transformer, len(resourceToPrefixTransformer))\n\tfor gr, transList := range resourceToPrefixTransformer {\n\t\tgr := gr\n\t\ttransList := transList\n\t\ttransformers[gr] = value.NewPrefixTransformers(fmt.Errorf(\"no matching prefix found\"), transList...)\n\t}\n\n\treturn transformers, probes, \u0026kmsUsed, nil\n}","line":{"from":228,"to":279}} {"id":100018236,"name":"check","signature":"func (h *kmsPluginProbe) check() error","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"// check encrypts and decrypts test data against KMS-Plugin's gRPC endpoint.\nfunc (h *kmsPluginProbe) check() error {\n\th.l.Lock()\n\tdefer h.l.Unlock()\n\n\tif (time.Since(h.lastResponse.received)) \u003c h.ttl {\n\t\treturn h.lastResponse.err\n\t}\n\n\tp, err := h.service.Encrypt([]byte(\"ping\"))\n\tif err != nil {\n\t\th.lastResponse = \u0026kmsPluginHealthzResponse{err: err, received: time.Now()}\n\t\th.ttl = kmsPluginHealthzNegativeTTL\n\t\treturn fmt.Errorf(\"failed to perform encrypt section of the healthz check for KMS Provider %s, error: %w\", h.name, err)\n\t}\n\n\tif _, err := h.service.Decrypt(p); err != nil {\n\t\th.lastResponse = \u0026kmsPluginHealthzResponse{err: err, received: time.Now()}\n\t\th.ttl = kmsPluginHealthzNegativeTTL\n\t\treturn fmt.Errorf(\"failed to perform decrypt section of the healthz check for KMS Provider %s, error: %w\", h.name, err)\n\t}\n\n\th.lastResponse = \u0026kmsPluginHealthzResponse{err: nil, received: time.Now()}\n\th.ttl = kmsPluginHealthzPositiveTTL\n\treturn nil\n}","line":{"from":281,"to":306}} {"id":100018237,"name":"check","signature":"func (h *kmsv2PluginProbe) check(ctx context.Context) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"// check gets the healthz status of the KMSv2-Plugin using the Status() method.\nfunc (h *kmsv2PluginProbe) check(ctx context.Context) error {\n\th.l.Lock()\n\tdefer h.l.Unlock()\n\n\tif time.Since(h.lastResponse.received) \u003c h.ttl {\n\t\treturn h.lastResponse.err\n\t}\n\n\tp, err := h.service.Status(ctx)\n\tif err != nil {\n\t\th.lastResponse = \u0026kmsPluginHealthzResponse{err: err, received: time.Now()}\n\t\th.ttl = kmsPluginHealthzNegativeTTL\n\t\treturn fmt.Errorf(\"failed to perform status section of the healthz check for KMS Provider %s, error: %w\", h.name, err)\n\t}\n\n\tif err := h.isKMSv2ProviderHealthyAndMaybeRotateDEK(ctx, p); err != nil {\n\t\th.lastResponse = \u0026kmsPluginHealthzResponse{err: err, received: time.Now()}\n\t\th.ttl = kmsPluginHealthzNegativeTTL\n\t\treturn err\n\t}\n\n\th.lastResponse = \u0026kmsPluginHealthzResponse{err: nil, received: time.Now()}\n\th.ttl = kmsPluginHealthzPositiveTTL\n\treturn nil\n}","line":{"from":308,"to":333}} {"id":100018238,"name":"rotateDEKOnKeyIDChange","signature":"func (h *kmsv2PluginProbe) rotateDEKOnKeyIDChange(ctx context.Context, statusKeyID, uid string) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"// rotateDEKOnKeyIDChange tries to rotate to a new DEK if the key ID returned by Status does not match the\n// current state. If a successful rotation is performed, the new DEK and keyID overwrite the existing state.\n// On any failure during rotation (including mismatch between status and encrypt calls), the current state is\n// preserved and will remain valid to use for encryption until its expiration (the system attempts to coast).\n// If the key ID returned by Status matches the current state, the expiration of the current state is extended\n// and no rotation is performed.\nfunc (h *kmsv2PluginProbe) rotateDEKOnKeyIDChange(ctx context.Context, statusKeyID, uid string) error {\n\t// we do not check ValidateEncryptCapability here because it is fine to re-use an old key\n\t// that was marked as expired during an unhealthy period. As long as the key ID matches\n\t// what we expect then there is no need to rotate here.\n\tstate, errState := h.getCurrentState()\n\n\t// allow reads indefinitely in all cases\n\t// allow writes indefinitely as long as there is no error\n\t// allow writes for only up to kmsv2PluginWriteDEKMaxTTL from now when there are errors\n\t// we start the timer before we make the network call because kmsv2PluginWriteDEKMaxTTL is meant to be the upper bound\n\texpirationTimestamp := envelopekmsv2.NowFunc().Add(kmsv2PluginWriteDEKMaxTTL)\n\n\t// state is valid and status keyID is unchanged from when we generated this DEK so there is no need to rotate it\n\t// just move the expiration of the current state forward by the reuse interval\n\tif errState == nil \u0026\u0026 state.KeyID == statusKeyID {\n\t\tstate.ExpirationTimestamp = expirationTimestamp\n\t\th.state.Store(\u0026state)\n\t\treturn nil\n\t}\n\n\ttransformer, resp, cacheKey, errGen := envelopekmsv2.GenerateTransformer(ctx, uid, h.service)\n\n\tif resp == nil {\n\t\tresp = \u0026kmsservice.EncryptResponse{} // avoid nil panics\n\t}\n\n\t// happy path, should be the common case\n\t// TODO maybe add success metrics?\n\tif errGen == nil \u0026\u0026 resp.KeyID == statusKeyID {\n\t\th.state.Store(\u0026envelopekmsv2.State{\n\t\t\tTransformer: transformer,\n\t\t\tEncryptedDEK: resp.Ciphertext,\n\t\t\tKeyID: resp.KeyID,\n\t\t\tAnnotations: resp.Annotations,\n\t\t\tUID: uid,\n\t\t\tExpirationTimestamp: expirationTimestamp,\n\t\t\tCacheKey: cacheKey,\n\t\t})\n\t\tklog.V(6).InfoS(\"successfully rotated DEK\",\n\t\t\t\"uid\", uid,\n\t\t\t\"newKeyID\", resp.KeyID,\n\t\t\t\"oldKeyID\", state.KeyID,\n\t\t\t\"expirationTimestamp\", expirationTimestamp.Format(time.RFC3339),\n\t\t)\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"failed to rotate DEK uid=%q, errState=%v, errGen=%v, statusKeyID=%q, encryptKeyID=%q, stateKeyID=%q, expirationTimestamp=%s\",\n\t\tuid, errState, errGen, statusKeyID, resp.KeyID, state.KeyID, state.ExpirationTimestamp.Format(time.RFC3339))\n}","line":{"from":335,"to":390}} {"id":100018239,"name":"getCurrentState","signature":"func (h *kmsv2PluginProbe) getCurrentState() (envelopekmsv2.State, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"// getCurrentState returns the latest state from the last status and encrypt calls.\n// If the returned error is nil, the state is considered valid indefinitely for read requests.\n// For write requests, the caller must also check that state.ValidateEncryptCapability does not error.\nfunc (h *kmsv2PluginProbe) getCurrentState() (envelopekmsv2.State, error) {\n\tstate := *h.state.Load()\n\n\tif state.Transformer == nil {\n\t\treturn envelopekmsv2.State{}, fmt.Errorf(\"got unexpected nil transformer\")\n\t}\n\n\tif len(state.EncryptedDEK) == 0 {\n\t\treturn envelopekmsv2.State{}, fmt.Errorf(\"got unexpected empty EncryptedDEK\")\n\t}\n\n\tif len(state.KeyID) == 0 {\n\t\treturn envelopekmsv2.State{}, fmt.Errorf(\"got unexpected empty keyID\")\n\t}\n\n\tif state.ExpirationTimestamp.IsZero() {\n\t\treturn envelopekmsv2.State{}, fmt.Errorf(\"got unexpected zero expirationTimestamp\")\n\t}\n\n\tif len(state.CacheKey) == 0 {\n\t\treturn envelopekmsv2.State{}, fmt.Errorf(\"got unexpected empty cacheKey\")\n\t}\n\n\treturn state, nil\n}","line":{"from":392,"to":419}} {"id":100018240,"name":"isKMSv2ProviderHealthyAndMaybeRotateDEK","signature":"func (h *kmsv2PluginProbe) isKMSv2ProviderHealthyAndMaybeRotateDEK(ctx context.Context, response *kmsservice.StatusResponse) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"func (h *kmsv2PluginProbe) isKMSv2ProviderHealthyAndMaybeRotateDEK(ctx context.Context, response *kmsservice.StatusResponse) error {\n\tvar errs []error\n\tif response.Healthz != \"ok\" {\n\t\terrs = append(errs, fmt.Errorf(\"got unexpected healthz status: %s\", response.Healthz))\n\t}\n\tif response.Version != envelopekmsv2.KMSAPIVersion {\n\t\terrs = append(errs, fmt.Errorf(\"expected KMSv2 API version %s, got %s\", envelopekmsv2.KMSAPIVersion, response.Version))\n\t}\n\n\tif errCode, err := envelopekmsv2.ValidateKeyID(response.KeyID); err != nil {\n\t\tmetrics.RecordInvalidKeyIDFromStatus(h.name, string(errCode))\n\t\terrs = append(errs, fmt.Errorf(\"got invalid KMSv2 KeyID %q: %w\", response.KeyID, err))\n\t} else {\n\t\tmetrics.RecordKeyIDFromStatus(h.name, response.KeyID)\n\t\t// unconditionally append as we filter out nil errors below\n\t\terrs = append(errs, h.rotateDEKOnKeyIDChange(ctx, response.KeyID, string(uuid.NewUUID())))\n\t}\n\n\tif err := utilerrors.Reduce(utilerrors.NewAggregate(errs)); err != nil {\n\t\treturn fmt.Errorf(\"kmsv2 Provider %s is not healthy, error: %w\", h.name, err)\n\t}\n\treturn nil\n}","line":{"from":421,"to":443}} {"id":100018241,"name":"loadConfig","signature":"func loadConfig(filepath string, reload bool) (*apiserverconfig.EncryptionConfiguration, string, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"// loadConfig parses the encryption configuration file at filepath and returns the parsed config and hash of the file.\nfunc loadConfig(filepath string, reload bool) (*apiserverconfig.EncryptionConfiguration, string, error) {\n\tf, err := os.Open(filepath)\n\tif err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"error opening encryption provider configuration file %q: %w\", filepath, err)\n\t}\n\tdefer f.Close()\n\n\tdata, err := io.ReadAll(f)\n\tif err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"could not read contents: %w\", err)\n\t}\n\tif len(data) == 0 {\n\t\treturn nil, \"\", fmt.Errorf(\"encryption provider configuration file %q is empty\", filepath)\n\t}\n\n\tscheme := runtime.NewScheme()\n\tcodecs := serializer.NewCodecFactory(scheme)\n\tutilruntime.Must(apiserverconfig.AddToScheme(scheme))\n\tutilruntime.Must(apiserverconfigv1.AddToScheme(scheme))\n\n\tconfigObj, gvk, err := codecs.UniversalDecoder().Decode(data, nil, nil)\n\tif err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"error decoding encryption provider configuration file %q: %w\", filepath, err)\n\t}\n\tconfig, ok := configObj.(*apiserverconfig.EncryptionConfiguration)\n\tif !ok {\n\t\treturn nil, \"\", fmt.Errorf(\"got unexpected config type: %v\", gvk)\n\t}\n\n\treturn config, computeEncryptionConfigHash(data), validation.ValidateEncryptionConfiguration(config, reload).ToAggregate()\n}","line":{"from":445,"to":476}} {"id":100018242,"name":"prefixTransformersAndProbes","signature":"func prefixTransformersAndProbes(ctx context.Context, config apiserverconfig.ResourceConfiguration) ([]value.PrefixTransformer, []healthChecker, *kmsState, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"// prefixTransformersAndProbes creates the set of transformers and KMS probes based on the given resource config.\n// It may launch multiple go routines whose lifecycle is controlled by ctx.\n// In case of an error, the caller is responsible for canceling ctx to clean up any go routines that may have been launched.\nfunc prefixTransformersAndProbes(ctx context.Context, config apiserverconfig.ResourceConfiguration) ([]value.PrefixTransformer, []healthChecker, *kmsState, error) {\n\tvar transformers []value.PrefixTransformer\n\tvar probes []healthChecker\n\tvar kmsUsed kmsState\n\n\tfor _, provider := range config.Providers {\n\t\tprovider := provider\n\t\tvar (\n\t\t\ttransformer value.PrefixTransformer\n\t\t\ttransformerErr error\n\t\t\tprobe healthChecker\n\t\t\tused *kmsState\n\t\t)\n\n\t\tswitch {\n\t\tcase provider.AESGCM != nil:\n\t\t\ttransformer, transformerErr = aesPrefixTransformer(provider.AESGCM, aestransformer.NewGCMTransformer, aesGCMTransformerPrefixV1)\n\n\t\tcase provider.AESCBC != nil:\n\t\t\tcbcTransformer := func(block cipher.Block) (value.Transformer, error) {\n\t\t\t\treturn aestransformer.NewCBCTransformer(block), nil\n\t\t\t}\n\t\t\ttransformer, transformerErr = aesPrefixTransformer(provider.AESCBC, cbcTransformer, aesCBCTransformerPrefixV1)\n\n\t\tcase provider.Secretbox != nil:\n\t\t\ttransformer, transformerErr = secretboxPrefixTransformer(provider.Secretbox)\n\n\t\tcase provider.KMS != nil:\n\t\t\ttransformer, probe, used, transformerErr = kmsPrefixTransformer(ctx, provider.KMS)\n\t\t\tif transformerErr == nil {\n\t\t\t\tprobes = append(probes, probe)\n\t\t\t\tkmsUsed.accumulate(used)\n\t\t\t}\n\n\t\tcase provider.Identity != nil:\n\t\t\ttransformer = value.PrefixTransformer{\n\t\t\t\tTransformer: identity.NewEncryptCheckTransformer(),\n\t\t\t\tPrefix: []byte{},\n\t\t\t}\n\n\t\tdefault:\n\t\t\treturn nil, nil, nil, errors.New(\"provider does not contain any of the expected providers: KMS, AESGCM, AESCBC, Secretbox, Identity\")\n\t\t}\n\n\t\tif transformerErr != nil {\n\t\t\treturn nil, nil, nil, transformerErr\n\t\t}\n\n\t\ttransformers = append(transformers, transformer)\n\t}\n\n\treturn transformers, probes, \u0026kmsUsed, nil\n}","line":{"from":478,"to":533}} {"id":100018243,"name":"aesPrefixTransformer","signature":"func aesPrefixTransformer(config *apiserverconfig.AESConfiguration, fn blockTransformerFunc, prefix string) (value.PrefixTransformer, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"func aesPrefixTransformer(config *apiserverconfig.AESConfiguration, fn blockTransformerFunc, prefix string) (value.PrefixTransformer, error) {\n\tvar result value.PrefixTransformer\n\n\tif len(config.Keys) == 0 {\n\t\treturn result, fmt.Errorf(\"aes provider has no valid keys\")\n\t}\n\tfor _, key := range config.Keys {\n\t\tkey := key\n\t\tif key.Name == \"\" {\n\t\t\treturn result, fmt.Errorf(\"key with invalid name provided\")\n\t\t}\n\t\tif key.Secret == \"\" {\n\t\t\treturn result, fmt.Errorf(\"key %v has no provided secret\", key.Name)\n\t\t}\n\t}\n\n\tkeyTransformers := []value.PrefixTransformer{}\n\n\tfor _, keyData := range config.Keys {\n\t\tkeyData := keyData\n\t\tkey, err := base64.StdEncoding.DecodeString(keyData.Secret)\n\t\tif err != nil {\n\t\t\treturn result, fmt.Errorf(\"could not obtain secret for named key %s: %w\", keyData.Name, err)\n\t\t}\n\t\tblock, err := aes.NewCipher(key)\n\t\tif err != nil {\n\t\t\treturn result, fmt.Errorf(\"error while creating cipher for named key %s: %w\", keyData.Name, err)\n\t\t}\n\t\ttransformer, err := fn(block)\n\t\tif err != nil {\n\t\t\treturn result, fmt.Errorf(\"error while creating transformer for named key %s: %w\", keyData.Name, err)\n\t\t}\n\n\t\t// Create a new PrefixTransformer for this key\n\t\tkeyTransformers = append(keyTransformers,\n\t\t\tvalue.PrefixTransformer{\n\t\t\t\tTransformer: transformer,\n\t\t\t\tPrefix: []byte(keyData.Name + \":\"),\n\t\t\t})\n\t}\n\n\t// Create a prefixTransformer which can choose between these keys\n\tkeyTransformer := value.NewPrefixTransformers(\n\t\tfmt.Errorf(\"no matching key was found for the provided AES transformer\"), keyTransformers...)\n\n\t// Create a PrefixTransformer which shall later be put in a list with other providers\n\tresult = value.PrefixTransformer{\n\t\tTransformer: keyTransformer,\n\t\tPrefix: []byte(prefix),\n\t}\n\treturn result, nil\n}","line":{"from":537,"to":588}} {"id":100018244,"name":"secretboxPrefixTransformer","signature":"func secretboxPrefixTransformer(config *apiserverconfig.SecretboxConfiguration) (value.PrefixTransformer, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"func secretboxPrefixTransformer(config *apiserverconfig.SecretboxConfiguration) (value.PrefixTransformer, error) {\n\tvar result value.PrefixTransformer\n\n\tif len(config.Keys) == 0 {\n\t\treturn result, fmt.Errorf(\"secretbox provider has no valid keys\")\n\t}\n\tfor _, key := range config.Keys {\n\t\tkey := key\n\t\tif key.Name == \"\" {\n\t\t\treturn result, fmt.Errorf(\"key with invalid name provided\")\n\t\t}\n\t\tif key.Secret == \"\" {\n\t\t\treturn result, fmt.Errorf(\"key %v has no provided secret\", key.Name)\n\t\t}\n\t}\n\n\tkeyTransformers := []value.PrefixTransformer{}\n\n\tfor _, keyData := range config.Keys {\n\t\tkeyData := keyData\n\t\tkey, err := base64.StdEncoding.DecodeString(keyData.Secret)\n\t\tif err != nil {\n\t\t\treturn result, fmt.Errorf(\"could not obtain secret for named key %s: %s\", keyData.Name, err)\n\t\t}\n\n\t\tif len(key) != 32 {\n\t\t\treturn result, fmt.Errorf(\"expected key size 32 for secretbox provider, got %v\", len(key))\n\t\t}\n\n\t\tkeyArray := [32]byte{}\n\t\tcopy(keyArray[:], key)\n\n\t\t// Create a new PrefixTransformer for this key\n\t\tkeyTransformers = append(keyTransformers,\n\t\t\tvalue.PrefixTransformer{\n\t\t\t\tTransformer: secretbox.NewSecretboxTransformer(keyArray),\n\t\t\t\tPrefix: []byte(keyData.Name + \":\"),\n\t\t\t})\n\t}\n\n\t// Create a prefixTransformer which can choose between these keys\n\tkeyTransformer := value.NewPrefixTransformers(\n\t\tfmt.Errorf(\"no matching key was found for the provided Secretbox transformer\"), keyTransformers...)\n\n\t// Create a PrefixTransformer which shall later be put in a list with other providers\n\tresult = value.PrefixTransformer{\n\t\tTransformer: keyTransformer,\n\t\tPrefix: []byte(secretboxTransformerPrefixV1),\n\t}\n\treturn result, nil\n}","line":{"from":590,"to":640}} {"id":100018245,"name":"accumulate","signature":"func (s *kmsState) accumulate(other *kmsState)","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"// accumulate computes the KMS state by:\n// - determining which KMS plugin versions are in use\n// - calculating kmsTimeoutSum which is used as transformTracker.kmsCloseGracePeriod\n// DynamicTransformers.Set waits for this period before closing old transformers after a config reload\nfunc (s *kmsState) accumulate(other *kmsState) {\n\ts.v1Used = s.v1Used || other.v1Used\n\ts.v2Used = s.v2Used || other.v2Used\n\ts.kmsTimeoutSum += other.kmsTimeoutSum\n}","line":{"from":655,"to":663}} {"id":100018246,"name":"kmsPrefixTransformer","signature":"func kmsPrefixTransformer(ctx context.Context, config *apiserverconfig.KMSConfiguration) (value.PrefixTransformer, healthChecker, *kmsState, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"// kmsPrefixTransformer creates a KMS transformer and probe based on the given KMS config.\n// It may launch multiple go routines whose lifecycle is controlled by ctx.\n// In case of an error, the caller is responsible for canceling ctx to clean up any go routines that may have been launched.\nfunc kmsPrefixTransformer(ctx context.Context, config *apiserverconfig.KMSConfiguration) (value.PrefixTransformer, healthChecker, *kmsState, error) {\n\tkmsName := config.Name\n\tswitch config.APIVersion {\n\tcase kmsAPIVersionV1:\n\t\tenvelopeService, err := envelopeServiceFactory(ctx, config.Endpoint, config.Timeout.Duration)\n\t\tif err != nil {\n\t\t\treturn value.PrefixTransformer{}, nil, nil, fmt.Errorf(\"could not configure KMSv1-Plugin's probe %q, error: %w\", kmsName, err)\n\t\t}\n\n\t\tprobe := \u0026kmsPluginProbe{\n\t\t\tname: kmsName,\n\t\t\tttl: kmsPluginHealthzNegativeTTL,\n\t\t\tservice: envelopeService,\n\t\t\tl: \u0026sync.Mutex{},\n\t\t\tlastResponse: \u0026kmsPluginHealthzResponse{},\n\t\t}\n\n\t\ttransformer := envelopePrefixTransformer(config, envelopeService, kmsTransformerPrefixV1)\n\n\t\treturn transformer, probe, \u0026kmsState{\n\t\t\tv1Used: true,\n\t\t\t// for v1 we will do encrypt and decrypt for health check. Since these are serial operations, we will double the timeout.\n\t\t\tkmsTimeoutSum: 2 * config.Timeout.Duration,\n\t\t}, nil\n\n\tcase kmsAPIVersionV2:\n\t\tif !utilfeature.DefaultFeatureGate.Enabled(features.KMSv2) {\n\t\t\treturn value.PrefixTransformer{}, nil, nil, fmt.Errorf(\"could not configure KMSv2 plugin %q, KMSv2 feature is not enabled\", kmsName)\n\t\t}\n\n\t\tenvelopeService, err := EnvelopeKMSv2ServiceFactory(ctx, config.Endpoint, config.Name, config.Timeout.Duration)\n\t\tif err != nil {\n\t\t\treturn value.PrefixTransformer{}, nil, nil, fmt.Errorf(\"could not configure KMSv2-Plugin's probe %q, error: %w\", kmsName, err)\n\t\t}\n\n\t\tprobe := \u0026kmsv2PluginProbe{\n\t\t\tname: kmsName,\n\t\t\tttl: kmsPluginHealthzNegativeTTL,\n\t\t\tservice: envelopeService,\n\t\t\tl: \u0026sync.Mutex{},\n\t\t\tlastResponse: \u0026kmsPluginHealthzResponse{},\n\t\t}\n\t\t// initialize state so that Load always works\n\t\tprobe.state.Store(\u0026envelopekmsv2.State{})\n\n\t\trunProbeCheckAndLog := func(ctx context.Context) error {\n\t\t\tif err := probe.check(ctx); err != nil {\n\t\t\t\tklog.VDepth(1, 2).ErrorS(err, \"kms plugin failed health check probe\", \"name\", kmsName)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\t// on the happy path where the plugin is healthy and available on server start,\n\t\t// prime keyID and DEK by running the check inline once (this also prevents unit tests from flaking)\n\t\t// ignore the error here since we want to support the plugin starting up async with the API server\n\t\t_ = runProbeCheckAndLog(ctx)\n\t\t// make sure that the plugin's key ID is reasonably up-to-date\n\t\t// also, make sure that our DEK is up-to-date to with said key ID (if it expires the server will fail all writes)\n\t\t// if this background loop ever stops running, the server will become unfunctional after kmsv2PluginWriteDEKMaxTTL\n\t\tgo wait.PollUntilWithContext(\n\t\t\tctx,\n\t\t\tkmsv2PluginHealthzPositiveInterval,\n\t\t\tfunc(ctx context.Context) (bool, error) {\n\t\t\t\tif err := runProbeCheckAndLog(ctx); err == nil {\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\n\t\t\t\t// TODO add integration test for quicker error poll on failure\n\t\t\t\t// if we fail, block the outer polling and start a new quicker poll inline\n\t\t\t\t// this limits the chance that our DEK expires during a transient failure\n\t\t\t\t_ = wait.PollUntilWithContext(\n\t\t\t\t\tctx,\n\t\t\t\t\tkmsv2PluginHealthzNegativeInterval,\n\t\t\t\t\tfunc(ctx context.Context) (bool, error) {\n\t\t\t\t\t\treturn runProbeCheckAndLog(ctx) == nil, nil\n\t\t\t\t\t},\n\t\t\t\t)\n\n\t\t\t\treturn false, nil\n\t\t\t})\n\n\t\t// using AES-GCM by default for encrypting data with KMSv2\n\t\ttransformer := value.PrefixTransformer{\n\t\t\tTransformer: envelopekmsv2.NewEnvelopeTransformer(envelopeService, kmsName, probe.getCurrentState),\n\t\t\tPrefix: []byte(kmsTransformerPrefixV2 + kmsName + \":\"),\n\t\t}\n\n\t\treturn transformer, probe, \u0026kmsState{\n\t\t\tv2Used: true,\n\t\t\tkmsTimeoutSum: config.Timeout.Duration,\n\t\t}, nil\n\n\tdefault:\n\t\treturn value.PrefixTransformer{}, nil, nil, fmt.Errorf(\"could not configure KMS plugin %q, unsupported KMS API version %q\", kmsName, config.APIVersion)\n\t}\n}","line":{"from":665,"to":764}} {"id":100018247,"name":"envelopePrefixTransformer","signature":"func envelopePrefixTransformer(config *apiserverconfig.KMSConfiguration, envelopeService envelope.Service, prefix string) value.PrefixTransformer","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"func envelopePrefixTransformer(config *apiserverconfig.KMSConfiguration, envelopeService envelope.Service, prefix string) value.PrefixTransformer {\n\tbaseTransformerFunc := func(block cipher.Block) (value.Transformer, error) {\n\t\tgcm, err := aestransformer.NewGCMTransformer(block)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// v1.24: write using AES-CBC only but support reads via AES-CBC and AES-GCM (so we can move to AES-GCM)\n\t\t// v1.25: write using AES-GCM only but support reads via AES-GCM and fallback to AES-CBC for backwards compatibility\n\t\t// TODO(aramase): Post v1.25: We cannot drop CBC read support until we automate storage migration.\n\t\t// We could have a release note that hard requires users to perform storage migration.\n\t\treturn unionTransformers{gcm, aestransformer.NewCBCTransformer(block)}, nil\n\t}\n\n\treturn value.PrefixTransformer{\n\t\tTransformer: envelope.NewEnvelopeTransformer(envelopeService, int(*config.CacheSize), baseTransformerFunc),\n\t\tPrefix: []byte(prefix + config.Name + \":\"),\n\t}\n}","line":{"from":766,"to":784}} {"id":100018248,"name":"TransformFromStorage","signature":"func (u unionTransformers) TransformFromStorage(ctx context.Context, data []byte, dataCtx value.Context) (out []byte, stale bool, err error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"func (u unionTransformers) TransformFromStorage(ctx context.Context, data []byte, dataCtx value.Context) (out []byte, stale bool, err error) {\n\tvar errs []error\n\tfor i := range u {\n\t\ttransformer := u[i]\n\t\tresult, stale, err := transformer.TransformFromStorage(ctx, data, dataCtx)\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t\tcontinue\n\t\t}\n\t\t// when i != 0, we have transformed the data from storage using the new transformer,\n\t\t// we want to issue a write to etcd even if the contents of the data haven't changed\n\t\treturn result, stale || i != 0, nil\n\t}\n\tif err := utilerrors.Reduce(utilerrors.NewAggregate(errs)); err != nil {\n\t\treturn nil, false, err\n\t}\n\treturn nil, false, fmt.Errorf(\"unionTransformers: unable to transform from storage\")\n}","line":{"from":788,"to":805}} {"id":100018249,"name":"TransformToStorage","signature":"func (u unionTransformers) TransformToStorage(ctx context.Context, data []byte, dataCtx value.Context) (out []byte, err error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"func (u unionTransformers) TransformToStorage(ctx context.Context, data []byte, dataCtx value.Context) (out []byte, err error) {\n\treturn u[0].TransformToStorage(ctx, data, dataCtx)\n}","line":{"from":807,"to":809}} {"id":100018250,"name":"computeEncryptionConfigHash","signature":"func computeEncryptionConfigHash(data []byte) string","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"// computeEncryptionConfigHash returns the expected hash for an encryption config file that has been loaded as bytes.\n// We use a hash instead of the raw file contents when tracking changes to avoid holding any encryption keys in memory outside of their associated transformers.\n// This hash must be used in-memory and not externalized to the process because it has no cross-release stability guarantees.\nfunc computeEncryptionConfigHash(data []byte) string {\n\treturn fmt.Sprintf(\"%x\", sha256.Sum256(data))\n}","line":{"from":811,"to":816}} {"id":100018251,"name":"NewDynamicTransformers","signature":"func NewDynamicTransformers(","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"// NewDynamicTransformers returns transformers, health checks for kms providers and an ability to close transformers.\nfunc NewDynamicTransformers(\n\ttransformerOverrides map[schema.GroupResource]value.Transformer,\n\tkmsPluginHealthzCheck healthz.HealthChecker,\n\tcloseTransformers context.CancelFunc,\n\tkmsCloseGracePeriod time.Duration,\n) *DynamicTransformers {\n\tdynamicTransformers := \u0026DynamicTransformers{\n\t\ttransformTracker: \u0026atomic.Value{},\n\t}\n\n\ttracker := \u0026transformTracker{\n\t\ttransformerOverrides: transformerOverrides,\n\t\tkmsPluginHealthzCheck: kmsPluginHealthzCheck,\n\t\tcloseTransformers: closeTransformers,\n\t\tkmsCloseGracePeriod: kmsCloseGracePeriod,\n\t}\n\tdynamicTransformers.transformTracker.Store(tracker)\n\n\treturn dynamicTransformers\n}","line":{"from":834,"to":854}} {"id":100018252,"name":"Check","signature":"func (d *DynamicTransformers) Check(req *http.Request) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"// Check implements healthz.HealthChecker\nfunc (d *DynamicTransformers) Check(req *http.Request) error {\n\treturn d.transformTracker.Load().(*transformTracker).kmsPluginHealthzCheck.Check(req)\n}","line":{"from":856,"to":859}} {"id":100018253,"name":"Name","signature":"func (d *DynamicTransformers) Name() string","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"// Name implements healthz.HealthChecker\nfunc (d *DynamicTransformers) Name() string {\n\treturn kmsReloadHealthCheckName\n}","line":{"from":861,"to":864}} {"id":100018254,"name":"TransformerForResource","signature":"func (d *DynamicTransformers) TransformerForResource(resource schema.GroupResource) value.Transformer","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"// TransformerForResource returns the transformer for the given resource.\nfunc (d *DynamicTransformers) TransformerForResource(resource schema.GroupResource) value.Transformer {\n\treturn \u0026resourceTransformer{\n\t\tresource: resource,\n\t\ttransformTracker: d.transformTracker,\n\t}\n}","line":{"from":866,"to":872}} {"id":100018255,"name":"Set","signature":"func (d *DynamicTransformers) Set(","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"// Set sets the transformer overrides. This method is not go routine safe and must only be called by the same, single caller throughout the lifetime of this object.\nfunc (d *DynamicTransformers) Set(\n\ttransformerOverrides map[schema.GroupResource]value.Transformer,\n\tcloseTransformers context.CancelFunc,\n\tkmsPluginHealthzCheck healthz.HealthChecker,\n\tkmsCloseGracePeriod time.Duration,\n) {\n\t// store new values\n\tnewTransformTracker := \u0026transformTracker{\n\t\ttransformerOverrides: transformerOverrides,\n\t\tcloseTransformers: closeTransformers,\n\t\tkmsPluginHealthzCheck: kmsPluginHealthzCheck,\n\t\tkmsCloseGracePeriod: kmsCloseGracePeriod,\n\t}\n\n\t// update new transformer overrides\n\toldTransformTracker := d.transformTracker.Swap(newTransformTracker).(*transformTracker)\n\n\t// close old transformers once we wait for grpc request to finish any in-flight requests.\n\t// by the time we spawn this go routine, the new transformers have already been set and will be used for new requests.\n\t// if the server starts shutting down during sleep duration then the transformers will correctly closed early because their lifetime is tied to the api-server drain notifier.\n\tgo func() {\n\t\ttime.Sleep(oldTransformTracker.kmsCloseGracePeriod)\n\t\toldTransformTracker.closeTransformers()\n\t}()\n}","line":{"from":874,"to":899}} {"id":100018256,"name":"TransformFromStorage","signature":"func (r *resourceTransformer) TransformFromStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"func (r *resourceTransformer) TransformFromStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, bool, error) {\n\treturn r.transformer().TransformFromStorage(ctx, data, dataCtx)\n}","line":{"from":908,"to":910}} {"id":100018257,"name":"TransformToStorage","signature":"func (r *resourceTransformer) TransformToStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"func (r *resourceTransformer) TransformToStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, error) {\n\treturn r.transformer().TransformToStorage(ctx, data, dataCtx)\n}","line":{"from":912,"to":914}} {"id":100018258,"name":"transformer","signature":"func (r *resourceTransformer) transformer() value.Transformer","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"func (r *resourceTransformer) transformer() value.Transformer {\n\treturn transformerFromOverrides(r.transformTracker.Load().(*transformTracker).transformerOverrides, r.resource)\n}","line":{"from":916,"to":918}} {"id":100018259,"name":"TransformerForResource","signature":"func (s StaticTransformers) TransformerForResource(resource schema.GroupResource) value.Transformer","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"func (s StaticTransformers) TransformerForResource(resource schema.GroupResource) value.Transformer {\n\treturn transformerFromOverrides(s, resource)\n}","line":{"from":928,"to":930}} {"id":100018260,"name":"transformerFromOverrides","signature":"func transformerFromOverrides(transformerOverrides map[schema.GroupResource]value.Transformer, resource schema.GroupResource) value.Transformer","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"func transformerFromOverrides(transformerOverrides map[schema.GroupResource]value.Transformer, resource schema.GroupResource) value.Transformer {\n\tif transformer := transformerOverrides[resource]; transformer != nil {\n\t\treturn transformer\n\t}\n\n\tif transformer := transformerOverrides[schema.GroupResource{\n\t\tGroup: resource.Group,\n\t\tResource: \"*\",\n\t}]; transformer != nil {\n\t\treturn transformer\n\t}\n\n\tif transformer := transformerOverrides[anyGroupAnyResource]; transformer != nil {\n\t\treturn transformer\n\t}\n\n\treturn identity.NewEncryptCheckTransformer()\n}","line":{"from":937,"to":954}} {"id":100018261,"name":"grYAMLString","signature":"func grYAMLString(gr schema.GroupResource) string","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/config.go","code":"func grYAMLString(gr schema.GroupResource) string {\n\tif gr.Group == \"\" \u0026\u0026 gr.Resource == \"*\" {\n\t\treturn \"*.\"\n\t}\n\n\treturn gr.String()\n}","line":{"from":956,"to":962}} {"id":100018262,"name":"NewDynamicEncryptionConfiguration","signature":"func NewDynamicEncryptionConfiguration(","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/controller/controller.go","code":"// NewDynamicEncryptionConfiguration returns controller that dynamically reacts to changes in encryption config file.\nfunc NewDynamicEncryptionConfiguration(\n\tname, filePath string,\n\tdynamicTransformers *encryptionconfig.DynamicTransformers,\n\tconfigContentHash string,\n) *DynamicKMSEncryptionConfigContent {\n\tencryptionConfig := \u0026DynamicKMSEncryptionConfigContent{\n\t\tname: name,\n\t\tfilePath: filePath,\n\t\tlastLoadedEncryptionConfigHash: configContentHash,\n\t\tdynamicTransformers: dynamicTransformers,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), name),\n\t}\n\tencryptionConfig.queue.Add(workqueueKey) // to avoid missing any file changes that occur in between the initial load and Run\n\n\treturn encryptionConfig\n}","line":{"from":54,"to":70}} {"id":100018263,"name":"Run","signature":"func (d *DynamicKMSEncryptionConfigContent) Run(ctx context.Context)","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/controller/controller.go","code":"// Run starts the controller and blocks until stopCh is closed.\nfunc (d *DynamicKMSEncryptionConfigContent) Run(ctx context.Context) {\n\tdefer utilruntime.HandleCrash()\n\tdefer d.queue.ShutDown()\n\n\tklog.InfoS(\"Starting controller\", \"name\", d.name)\n\tdefer klog.InfoS(\"Shutting down controller\", \"name\", d.name)\n\n\t// start worker for processing content\n\tgo wait.UntilWithContext(ctx, d.runWorker, time.Second)\n\n\t// start the loop that watches the encryption config file until stopCh is closed.\n\tgo wait.UntilWithContext(ctx, func(ctx context.Context) {\n\t\tif err := d.watchEncryptionConfigFile(ctx); err != nil {\n\t\t\t// if there is an error while setting up or handling the watches, this will ensure that we will process the config file.\n\t\t\tdefer d.queue.Add(workqueueKey)\n\t\t\tklog.ErrorS(err, \"Failed to watch encryption config file, will retry later\")\n\t\t}\n\t}, time.Second)\n\n\t\u003c-ctx.Done()\n}","line":{"from":72,"to":93}} {"id":100018264,"name":"watchEncryptionConfigFile","signature":"func (d *DynamicKMSEncryptionConfigContent) watchEncryptionConfigFile(ctx context.Context) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/controller/controller.go","code":"func (d *DynamicKMSEncryptionConfigContent) watchEncryptionConfigFile(ctx context.Context) error {\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating fsnotify watcher: %w\", err)\n\t}\n\tdefer watcher.Close()\n\n\tif err = watcher.Add(d.filePath); err != nil {\n\t\treturn fmt.Errorf(\"error adding watch for file %s: %w\", d.filePath, err)\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase event := \u003c-watcher.Events:\n\t\t\tif err := d.handleWatchEvent(event, watcher); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase err := \u003c-watcher.Errors:\n\t\t\treturn fmt.Errorf(\"received fsnotify error: %w\", err)\n\t\tcase \u003c-ctx.Done():\n\t\t\treturn nil\n\t\t}\n\t}\n}","line":{"from":95,"to":118}} {"id":100018265,"name":"handleWatchEvent","signature":"func (d *DynamicKMSEncryptionConfigContent) handleWatchEvent(event fsnotify.Event, watcher *fsnotify.Watcher) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/controller/controller.go","code":"func (d *DynamicKMSEncryptionConfigContent) handleWatchEvent(event fsnotify.Event, watcher *fsnotify.Watcher) error {\n\t// This should be executed after restarting the watch (if applicable) to ensure no file event will be missing.\n\tdefer d.queue.Add(workqueueKey)\n\n\t// return if file has not been removed or renamed.\n\tif event.Op\u0026(fsnotify.Remove|fsnotify.Rename) == 0 {\n\t\treturn nil\n\t}\n\n\tif err := watcher.Remove(d.filePath); err != nil {\n\t\tklog.V(2).InfoS(\"Failed to remove file watch, it may have been deleted\", \"file\", d.filePath, \"err\", err)\n\t}\n\tif err := watcher.Add(d.filePath); err != nil {\n\t\treturn fmt.Errorf(\"error adding watch for file %s: %w\", d.filePath, err)\n\t}\n\n\treturn nil\n}","line":{"from":120,"to":137}} {"id":100018266,"name":"runWorker","signature":"func (d *DynamicKMSEncryptionConfigContent) runWorker(ctx context.Context)","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/controller/controller.go","code":"// runWorker to process file content\nfunc (d *DynamicKMSEncryptionConfigContent) runWorker(ctx context.Context) {\n\tfor d.processNextWorkItem(ctx) {\n\t}\n}","line":{"from":139,"to":143}} {"id":100018267,"name":"processNextWorkItem","signature":"func (d *DynamicKMSEncryptionConfigContent) processNextWorkItem(serverCtx context.Context) bool","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/controller/controller.go","code":"// processNextWorkItem processes file content when there is a message in the queue.\nfunc (d *DynamicKMSEncryptionConfigContent) processNextWorkItem(serverCtx context.Context) bool {\n\t// key here is dummy item in the queue to trigger file content processing.\n\tkey, quit := d.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer d.queue.Done(key)\n\n\tvar (\n\t\tupdatedEffectiveConfig bool\n\t\terr error\n\t\tencryptionConfiguration *encryptionconfig.EncryptionConfiguration\n\t\tconfigChanged bool\n\t)\n\n\t// get context to close the new transformers (on error cases and on the next reload)\n\t// serverCtx is attached to the API server's lifecycle so we will always close transformers on shut down\n\tctx, closeTransformers := context.WithCancel(serverCtx)\n\n\tdefer func() {\n\t\t// TODO: increment success metric when updatedEffectiveConfig=true\n\n\t\t// TODO can work queue metrics help here?\n\n\t\tif !updatedEffectiveConfig {\n\t\t\t// avoid leaking if we're not using the newly constructed transformers (due to an error or them not being changed)\n\t\t\tcloseTransformers()\n\t\t}\n\t\tif err != nil {\n\t\t\t// TODO: increment failure metric\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"error processing encryption config file %s: %v\", d.filePath, err))\n\t\t\t// add dummy item back to the queue to trigger file content processing.\n\t\t\td.queue.AddRateLimited(key)\n\t\t}\n\t}()\n\n\tencryptionConfiguration, configChanged, err = d.processEncryptionConfig(ctx)\n\tif err != nil {\n\t\treturn true\n\t}\n\tif !configChanged {\n\t\treturn true\n\t}\n\n\tif len(encryptionConfiguration.HealthChecks) != 1 {\n\t\terr = fmt.Errorf(\"unexpected number of healthz checks: %d. Should have only one\", len(encryptionConfiguration.HealthChecks))\n\t\treturn true\n\t}\n\t// get healthz checks for all new KMS plugins.\n\tif err = d.validateNewTransformersHealth(ctx, encryptionConfiguration.HealthChecks[0], encryptionConfiguration.KMSCloseGracePeriod); err != nil {\n\t\treturn true\n\t}\n\n\t// update transformers.\n\t// when reload=true there must always be one healthz check.\n\td.dynamicTransformers.Set(\n\t\tencryptionConfiguration.Transformers,\n\t\tcloseTransformers,\n\t\tencryptionConfiguration.HealthChecks[0],\n\t\tencryptionConfiguration.KMSCloseGracePeriod,\n\t)\n\n\t// update local copy of recent config content once update is successful.\n\td.lastLoadedEncryptionConfigHash = encryptionConfiguration.EncryptionFileContentHash\n\tklog.V(2).InfoS(\"Loaded new kms encryption config content\", \"name\", d.name)\n\n\tupdatedEffectiveConfig = true\n\treturn true\n}","line":{"from":145,"to":214}} {"id":100018268,"name":"processEncryptionConfig","signature":"func (d *DynamicKMSEncryptionConfigContent) processEncryptionConfig(ctx context.Context) (","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/controller/controller.go","code":"// loadEncryptionConfig processes the next set of content from the file.\nfunc (d *DynamicKMSEncryptionConfigContent) processEncryptionConfig(ctx context.Context) (\n\tencryptionConfiguration *encryptionconfig.EncryptionConfiguration,\n\tconfigChanged bool,\n\terr error,\n) {\n\t// this code path will only execute if reload=true. So passing true explicitly.\n\tencryptionConfiguration, err = encryptionconfig.LoadEncryptionConfig(ctx, d.filePath, true)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\t// check if encryptionConfig is different from the current. Do nothing if they are the same.\n\tif encryptionConfiguration.EncryptionFileContentHash == d.lastLoadedEncryptionConfigHash {\n\t\tklog.V(4).InfoS(\"Encryption config has not changed\", \"name\", d.name)\n\t\treturn nil, false, nil\n\t}\n\treturn encryptionConfiguration, true, nil\n}","line":{"from":216,"to":234}} {"id":100018269,"name":"validateNewTransformersHealth","signature":"func (d *DynamicKMSEncryptionConfigContent) validateNewTransformersHealth(","file":"staging/src/k8s.io/apiserver/pkg/server/options/encryptionconfig/controller/controller.go","code":"func (d *DynamicKMSEncryptionConfigContent) validateNewTransformersHealth(\n\tctx context.Context,\n\tkmsPluginHealthzCheck healthz.HealthChecker,\n\tkmsPluginCloseGracePeriod time.Duration,\n) error {\n\t// test if new transformers are healthy\n\tvar healthCheckError error\n\n\tif kmsPluginCloseGracePeriod \u003c 10*time.Second {\n\t\tkmsPluginCloseGracePeriod = 10 * time.Second\n\t}\n\n\t// really make sure that the immediate check does not hang\n\tvar cancel context.CancelFunc\n\tctx, cancel = context.WithTimeout(ctx, kmsPluginCloseGracePeriod)\n\tdefer cancel()\n\n\tpollErr := wait.PollImmediateWithContext(ctx, 100*time.Millisecond, kmsPluginCloseGracePeriod, func(ctx context.Context) (bool, error) {\n\t\t// create a fake http get request to health check endpoint\n\t\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf(\"/healthz/%s\", kmsPluginHealthzCheck.Name()), nil)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\thealthCheckError = kmsPluginHealthzCheck.Check(req)\n\t\treturn healthCheckError == nil, nil\n\t})\n\tif pollErr != nil {\n\t\treturn fmt.Errorf(\"health check for new transformers failed, polling error %v: %w\", pollErr, healthCheckError)\n\t}\n\tklog.V(2).InfoS(\"Health check succeeded\")\n\treturn nil\n}","line":{"from":236,"to":268}} {"id":100018270,"name":"NewEtcdOptions","signature":"func NewEtcdOptions(backendConfig *storagebackend.Config) *EtcdOptions","file":"staging/src/k8s.io/apiserver/pkg/server/options/etcd.go","code":"func NewEtcdOptions(backendConfig *storagebackend.Config) *EtcdOptions {\n\toptions := \u0026EtcdOptions{\n\t\tStorageConfig: *backendConfig,\n\t\tDefaultStorageMediaType: \"application/json\",\n\t\tDeleteCollectionWorkers: 1,\n\t\tEnableGarbageCollection: true,\n\t\tEnableWatchCache: true,\n\t\tDefaultWatchCacheSize: 100,\n\t}\n\toptions.StorageConfig.CountMetricPollPeriod = time.Minute\n\treturn options\n}","line":{"from":81,"to":92}} {"id":100018271,"name":"Validate","signature":"func (s *EtcdOptions) Validate() []error","file":"staging/src/k8s.io/apiserver/pkg/server/options/etcd.go","code":"func (s *EtcdOptions) Validate() []error {\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\tallErrors := []error{}\n\tif len(s.StorageConfig.Transport.ServerList) == 0 {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"--etcd-servers must be specified\"))\n\t}\n\n\tif s.StorageConfig.Type != storagebackend.StorageTypeUnset \u0026\u0026 !storageTypes.Has(s.StorageConfig.Type) {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"--storage-backend invalid, allowed values: %s. If not specified, it will default to 'etcd3'\", strings.Join(storageTypes.List(), \", \")))\n\t}\n\n\tfor _, override := range s.EtcdServersOverrides {\n\t\ttokens := strings.Split(override, \"#\")\n\t\tif len(tokens) != 2 {\n\t\t\tallErrors = append(allErrors, fmt.Errorf(\"--etcd-servers-overrides invalid, must be of format: group/resource#servers, where servers are URLs, semicolon separated\"))\n\t\t\tcontinue\n\t\t}\n\n\t\tapiresource := strings.Split(tokens[0], \"/\")\n\t\tif len(apiresource) != 2 {\n\t\t\tallErrors = append(allErrors, fmt.Errorf(\"--etcd-servers-overrides invalid, must be of format: group/resource#servers, where servers are URLs, semicolon separated\"))\n\t\t\tcontinue\n\t\t}\n\n\t}\n\n\tif len(s.EncryptionProviderConfigFilepath) == 0 \u0026\u0026 s.EncryptionProviderConfigAutomaticReload {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"--encryption-provider-config-automatic-reload must be set with --encryption-provider-config\"))\n\t}\n\n\treturn allErrors\n}","line":{"from":94,"to":128}} {"id":100018272,"name":"AddFlags","signature":"func (s *EtcdOptions) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/apiserver/pkg/server/options/etcd.go","code":"// AddFlags adds flags related to etcd storage for a specific APIServer to the specified FlagSet\nfunc (s *EtcdOptions) AddFlags(fs *pflag.FlagSet) {\n\tif s == nil {\n\t\treturn\n\t}\n\n\tfs.StringSliceVar(\u0026s.EtcdServersOverrides, \"etcd-servers-overrides\", s.EtcdServersOverrides, \"\"+\n\t\t\"Per-resource etcd servers overrides, comma separated. The individual override \"+\n\t\t\"format: group/resource#servers, where servers are URLs, semicolon separated. \"+\n\t\t\"Note that this applies only to resources compiled into this server binary. \")\n\n\tfs.StringVar(\u0026s.DefaultStorageMediaType, \"storage-media-type\", s.DefaultStorageMediaType, \"\"+\n\t\t\"The media type to use to store objects in storage. \"+\n\t\t\"Some resources or storage backends may only support a specific media type and will ignore this setting. \"+\n\t\t\"Supported media types: [application/json, application/yaml, application/vnd.kubernetes.protobuf]\")\n\tfs.IntVar(\u0026s.DeleteCollectionWorkers, \"delete-collection-workers\", s.DeleteCollectionWorkers,\n\t\t\"Number of workers spawned for DeleteCollection call. These are used to speed up namespace cleanup.\")\n\n\tfs.BoolVar(\u0026s.EnableGarbageCollection, \"enable-garbage-collector\", s.EnableGarbageCollection, \"\"+\n\t\t\"Enables the generic garbage collector. MUST be synced with the corresponding flag \"+\n\t\t\"of the kube-controller-manager.\")\n\n\tfs.BoolVar(\u0026s.EnableWatchCache, \"watch-cache\", s.EnableWatchCache,\n\t\t\"Enable watch caching in the apiserver\")\n\n\tfs.IntVar(\u0026s.DefaultWatchCacheSize, \"default-watch-cache-size\", s.DefaultWatchCacheSize,\n\t\t\"Default watch cache size. If zero, watch cache will be disabled for resources that do not have a default watch size set.\")\n\n\tfs.MarkDeprecated(\"default-watch-cache-size\",\n\t\t\"watch caches are sized automatically and this flag will be removed in a future version\")\n\n\tfs.StringSliceVar(\u0026s.WatchCacheSizes, \"watch-cache-sizes\", s.WatchCacheSizes, \"\"+\n\t\t\"Watch cache size settings for some resources (pods, nodes, etc.), comma separated. \"+\n\t\t\"The individual setting format: resource[.group]#size, where resource is lowercase plural (no version), \"+\n\t\t\"group is omitted for resources of apiVersion v1 (the legacy core API) and included for others, \"+\n\t\t\"and size is a number. This option is only meaningful for resources built into the apiserver, \"+\n\t\t\"not ones defined by CRDs or aggregated from external servers, and is only consulted if the \"+\n\t\t\"watch-cache is enabled. The only meaningful size setting to supply here is zero, which means to \"+\n\t\t\"disable watch caching for the associated resource; all non-zero values are equivalent and mean \"+\n\t\t\"to not disable watch caching for that resource\")\n\n\tfs.StringVar(\u0026s.StorageConfig.Type, \"storage-backend\", s.StorageConfig.Type,\n\t\t\"The storage backend for persistence. Options: 'etcd3' (default).\")\n\n\tfs.StringSliceVar(\u0026s.StorageConfig.Transport.ServerList, \"etcd-servers\", s.StorageConfig.Transport.ServerList,\n\t\t\"List of etcd servers to connect with (scheme://ip:port), comma separated.\")\n\n\tfs.StringVar(\u0026s.StorageConfig.Prefix, \"etcd-prefix\", s.StorageConfig.Prefix,\n\t\t\"The prefix to prepend to all resource paths in etcd.\")\n\n\tfs.StringVar(\u0026s.StorageConfig.Transport.KeyFile, \"etcd-keyfile\", s.StorageConfig.Transport.KeyFile,\n\t\t\"SSL key file used to secure etcd communication.\")\n\n\tfs.StringVar(\u0026s.StorageConfig.Transport.CertFile, \"etcd-certfile\", s.StorageConfig.Transport.CertFile,\n\t\t\"SSL certification file used to secure etcd communication.\")\n\n\tfs.StringVar(\u0026s.StorageConfig.Transport.TrustedCAFile, \"etcd-cafile\", s.StorageConfig.Transport.TrustedCAFile,\n\t\t\"SSL Certificate Authority file used to secure etcd communication.\")\n\n\tfs.StringVar(\u0026s.EncryptionProviderConfigFilepath, \"encryption-provider-config\", s.EncryptionProviderConfigFilepath,\n\t\t\"The file containing configuration for encryption providers to be used for storing secrets in etcd\")\n\n\tfs.BoolVar(\u0026s.EncryptionProviderConfigAutomaticReload, \"encryption-provider-config-automatic-reload\", s.EncryptionProviderConfigAutomaticReload,\n\t\t\"Determines if the file set by --encryption-provider-config should be automatically reloaded if the disk contents change. \"+\n\t\t\t\"Setting this to true disables the ability to uniquely identify distinct KMS plugins via the API server healthz endpoints.\")\n\n\tfs.DurationVar(\u0026s.StorageConfig.CompactionInterval, \"etcd-compaction-interval\", s.StorageConfig.CompactionInterval,\n\t\t\"The interval of compaction requests. If 0, the compaction request from apiserver is disabled.\")\n\n\tfs.DurationVar(\u0026s.StorageConfig.CountMetricPollPeriod, \"etcd-count-metric-poll-period\", s.StorageConfig.CountMetricPollPeriod, \"\"+\n\t\t\"Frequency of polling etcd for number of resources per type. 0 disables the metric collection.\")\n\n\tfs.DurationVar(\u0026s.StorageConfig.DBMetricPollInterval, \"etcd-db-metric-poll-interval\", s.StorageConfig.DBMetricPollInterval,\n\t\t\"The interval of requests to poll etcd and update metric. 0 disables the metric collection\")\n\n\tfs.DurationVar(\u0026s.StorageConfig.HealthcheckTimeout, \"etcd-healthcheck-timeout\", s.StorageConfig.HealthcheckTimeout,\n\t\t\"The timeout to use when checking etcd health.\")\n\n\tfs.DurationVar(\u0026s.StorageConfig.ReadycheckTimeout, \"etcd-readycheck-timeout\", s.StorageConfig.ReadycheckTimeout,\n\t\t\"The timeout to use when checking etcd readiness\")\n\n\tfs.Int64Var(\u0026s.StorageConfig.LeaseManagerConfig.ReuseDurationSeconds, \"lease-reuse-duration-seconds\", s.StorageConfig.LeaseManagerConfig.ReuseDurationSeconds,\n\t\t\"The time in seconds that each lease is reused. A lower value could avoid large number of objects reusing the same lease. Notice that a too small value may cause performance problems at storage layer.\")\n}","line":{"from":130,"to":213}} {"id":100018273,"name":"Complete","signature":"func (s *EtcdOptions) Complete(","file":"staging/src/k8s.io/apiserver/pkg/server/options/etcd.go","code":"// Complete must be called exactly once before using any of the Apply methods. It is responsible for setting\n// up objects that must be created once and reused across multiple invocations such as storage transformers.\n// This method mutates the receiver (EtcdOptions). It must never mutate the inputs.\nfunc (s *EtcdOptions) Complete(\n\tstorageObjectCountTracker flowcontrolrequest.StorageObjectCountTracker,\n\tstopCh \u003c-chan struct{},\n\taddPostStartHook func(name string, hook server.PostStartHookFunc) error,\n) error {\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\tif s.complete {\n\t\treturn fmt.Errorf(\"EtcdOptions.Complete called more than once\")\n\t}\n\n\tif len(s.EncryptionProviderConfigFilepath) != 0 {\n\t\tctxServer := wait.ContextForChannel(stopCh)\n\t\t// nolint:govet // The only code path where closeTransformers does not get called is when it gets stored in dynamicTransformers.\n\t\tctxTransformers, closeTransformers := context.WithCancel(ctxServer)\n\n\t\tencryptionConfiguration, err := encryptionconfig.LoadEncryptionConfig(ctxTransformers, s.EncryptionProviderConfigFilepath, s.EncryptionProviderConfigAutomaticReload)\n\t\tif err != nil {\n\t\t\t// in case of error, we want to close partially initialized (if any) transformers\n\t\t\tcloseTransformers()\n\t\t\treturn err\n\t\t}\n\n\t\t// enable kms hot reload controller only if the config file is set to be automatically reloaded\n\t\tif s.EncryptionProviderConfigAutomaticReload {\n\t\t\t// with reload=true we will always have 1 health check\n\t\t\tif len(encryptionConfiguration.HealthChecks) != 1 {\n\t\t\t\t// in case of error, we want to close partially initialized (if any) transformers\n\t\t\t\tcloseTransformers()\n\t\t\t\treturn fmt.Errorf(\"failed to start kms encryption config hot reload controller. only 1 health check should be available when reload is enabled\")\n\t\t\t}\n\n\t\t\t// Here the dynamic transformers take ownership of the transformers and their cancellation.\n\t\t\tdynamicTransformers := encryptionconfig.NewDynamicTransformers(encryptionConfiguration.Transformers, encryptionConfiguration.HealthChecks[0], closeTransformers, encryptionConfiguration.KMSCloseGracePeriod)\n\n\t\t\t// add post start hook to start hot reload controller\n\t\t\t// adding this hook here will ensure that it gets configured exactly once\n\t\t\terr = addPostStartHook(\n\t\t\t\t\"start-encryption-provider-config-automatic-reload\",\n\t\t\t\tfunc(_ server.PostStartHookContext) error {\n\t\t\t\t\tdynamicEncryptionConfigController := encryptionconfigcontroller.NewDynamicEncryptionConfiguration(\n\t\t\t\t\t\t\"encryption-provider-config-automatic-reload-controller\",\n\t\t\t\t\t\ts.EncryptionProviderConfigFilepath,\n\t\t\t\t\t\tdynamicTransformers,\n\t\t\t\t\t\tencryptionConfiguration.EncryptionFileContentHash,\n\t\t\t\t\t)\n\n\t\t\t\t\tgo dynamicEncryptionConfigController.Run(ctxServer)\n\n\t\t\t\t\treturn nil\n\t\t\t\t},\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\t// in case of error, we want to close partially initialized (if any) transformers\n\t\t\t\tcloseTransformers()\n\t\t\t\treturn fmt.Errorf(\"failed to add post start hook for kms encryption config hot reload controller: %w\", err)\n\t\t\t}\n\n\t\t\ts.resourceTransformers = dynamicTransformers\n\t\t\ts.kmsPluginHealthzChecks = []healthz.HealthChecker{dynamicTransformers}\n\t\t} else {\n\t\t\ts.resourceTransformers = encryptionconfig.StaticTransformers(encryptionConfiguration.Transformers)\n\t\t\ts.kmsPluginHealthzChecks = encryptionConfiguration.HealthChecks\n\t\t}\n\t}\n\n\ts.StorageConfig.StorageObjectCountTracker = storageObjectCountTracker\n\n\ts.complete = true\n\n\t// nolint:govet // The only code path where closeTransformers does not get called is when it gets stored in dynamicTransformers.\n\treturn nil\n}","line":{"from":215,"to":292}} {"id":100018274,"name":"ApplyTo","signature":"func (s *EtcdOptions) ApplyTo(c *server.Config) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/etcd.go","code":"// ApplyTo mutates the provided server.Config. It must never mutate the receiver (EtcdOptions).\nfunc (s *EtcdOptions) ApplyTo(c *server.Config) error {\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\treturn s.ApplyWithStorageFactoryTo(\u0026SimpleStorageFactory{StorageConfig: s.StorageConfig}, c)\n}","line":{"from":294,"to":301}} {"id":100018275,"name":"ApplyWithStorageFactoryTo","signature":"func (s *EtcdOptions) ApplyWithStorageFactoryTo(factory serverstorage.StorageFactory, c *server.Config) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/etcd.go","code":"// ApplyWithStorageFactoryTo mutates the provided server.Config. It must never mutate the receiver (EtcdOptions).\nfunc (s *EtcdOptions) ApplyWithStorageFactoryTo(factory serverstorage.StorageFactory, c *server.Config) error {\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\tif !s.complete {\n\t\treturn fmt.Errorf(\"EtcdOptions.Apply called without completion\")\n\t}\n\n\tif !s.SkipHealthEndpoints {\n\t\tif err := s.addEtcdHealthEndpoint(c); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif s.resourceTransformers != nil {\n\t\tfactory = \u0026transformerStorageFactory{\n\t\t\tdelegate: factory,\n\t\t\tresourceTransformers: s.resourceTransformers,\n\t\t}\n\t}\n\n\tc.RESTOptionsGetter = \u0026StorageFactoryRestOptionsFactory{Options: *s, StorageFactory: factory}\n\treturn nil\n}","line":{"from":303,"to":328}} {"id":100018276,"name":"addEtcdHealthEndpoint","signature":"func (s *EtcdOptions) addEtcdHealthEndpoint(c *server.Config) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/etcd.go","code":"func (s *EtcdOptions) addEtcdHealthEndpoint(c *server.Config) error {\n\thealthCheck, err := storagefactory.CreateHealthCheck(s.StorageConfig, c.DrainedNotify())\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.AddHealthChecks(healthz.NamedCheck(\"etcd\", func(r *http.Request) error {\n\t\treturn healthCheck()\n\t}))\n\n\treadyCheck, err := storagefactory.CreateReadyCheck(s.StorageConfig, c.DrainedNotify())\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.AddReadyzChecks(healthz.NamedCheck(\"etcd-readiness\", func(r *http.Request) error {\n\t\treturn readyCheck()\n\t}))\n\n\tc.AddHealthChecks(s.kmsPluginHealthzChecks...)\n\n\treturn nil\n}","line":{"from":330,"to":350}} {"id":100018277,"name":"GetRESTOptions","signature":"func (f *StorageFactoryRestOptionsFactory) GetRESTOptions(resource schema.GroupResource) (generic.RESTOptions, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/etcd.go","code":"func (f *StorageFactoryRestOptionsFactory) GetRESTOptions(resource schema.GroupResource) (generic.RESTOptions, error) {\n\tstorageConfig, err := f.StorageFactory.NewConfig(resource)\n\tif err != nil {\n\t\treturn generic.RESTOptions{}, fmt.Errorf(\"unable to find storage destination for %v, due to %v\", resource, err.Error())\n\t}\n\n\tret := generic.RESTOptions{\n\t\tStorageConfig: storageConfig,\n\t\tDecorator: generic.UndecoratedStorage,\n\t\tDeleteCollectionWorkers: f.Options.DeleteCollectionWorkers,\n\t\tEnableGarbageCollection: f.Options.EnableGarbageCollection,\n\t\tResourcePrefix: f.StorageFactory.ResourcePrefix(resource),\n\t\tCountMetricPollPeriod: f.Options.StorageConfig.CountMetricPollPeriod,\n\t\tStorageObjectCountTracker: f.Options.StorageConfig.StorageObjectCountTracker,\n\t}\n\n\tif f.Options.EnableWatchCache {\n\t\tsizes, err := ParseWatchCacheSizes(f.Options.WatchCacheSizes)\n\t\tif err != nil {\n\t\t\treturn generic.RESTOptions{}, err\n\t\t}\n\t\tsize, ok := sizes[resource]\n\t\tif ok \u0026\u0026 size \u003e 0 {\n\t\t\tklog.Warningf(\"Dropping watch-cache-size for %v - watchCache size is now dynamic\", resource)\n\t\t}\n\t\tif ok \u0026\u0026 size \u003c= 0 {\n\t\t\tklog.V(3).InfoS(\"Not using watch cache\", \"resource\", resource)\n\t\t\tret.Decorator = generic.UndecoratedStorage\n\t\t} else {\n\t\t\tklog.V(3).InfoS(\"Using watch cache\", \"resource\", resource)\n\t\t\tret.Decorator = genericregistry.StorageWithCacher()\n\t\t}\n\t}\n\n\treturn ret, nil\n}","line":{"from":357,"to":392}} {"id":100018278,"name":"ParseWatchCacheSizes","signature":"func ParseWatchCacheSizes(cacheSizes []string) (map[schema.GroupResource]int, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/etcd.go","code":"// ParseWatchCacheSizes turns a list of cache size values into a map of group resources\n// to requested sizes.\nfunc ParseWatchCacheSizes(cacheSizes []string) (map[schema.GroupResource]int, error) {\n\twatchCacheSizes := make(map[schema.GroupResource]int)\n\tfor _, c := range cacheSizes {\n\t\ttokens := strings.Split(c, \"#\")\n\t\tif len(tokens) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"invalid value of watch cache size: %s\", c)\n\t\t}\n\n\t\tsize, err := strconv.Atoi(tokens[1])\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid size of watch cache size: %s\", c)\n\t\t}\n\t\tif size \u003c 0 {\n\t\t\treturn nil, fmt.Errorf(\"watch cache size cannot be negative: %s\", c)\n\t\t}\n\t\twatchCacheSizes[schema.ParseGroupResource(tokens[0])] = size\n\t}\n\treturn watchCacheSizes, nil\n}","line":{"from":394,"to":414}} {"id":100018279,"name":"WriteWatchCacheSizes","signature":"func WriteWatchCacheSizes(watchCacheSizes map[schema.GroupResource]int) ([]string, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/etcd.go","code":"// WriteWatchCacheSizes turns a map of cache size values into a list of string specifications.\nfunc WriteWatchCacheSizes(watchCacheSizes map[schema.GroupResource]int) ([]string, error) {\n\tvar cacheSizes []string\n\n\tfor resource, size := range watchCacheSizes {\n\t\tif size \u003c 0 {\n\t\t\treturn nil, fmt.Errorf(\"watch cache size cannot be negative for resource %s\", resource)\n\t\t}\n\t\tcacheSizes = append(cacheSizes, fmt.Sprintf(\"%s#%d\", resource.String(), size))\n\t}\n\treturn cacheSizes, nil\n}","line":{"from":416,"to":427}} {"id":100018280,"name":"NewConfig","signature":"func (s *SimpleStorageFactory) NewConfig(resource schema.GroupResource) (*storagebackend.ConfigForResource, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/etcd.go","code":"func (s *SimpleStorageFactory) NewConfig(resource schema.GroupResource) (*storagebackend.ConfigForResource, error) {\n\treturn s.StorageConfig.ForResource(resource), nil\n}","line":{"from":439,"to":441}} {"id":100018281,"name":"ResourcePrefix","signature":"func (s *SimpleStorageFactory) ResourcePrefix(resource schema.GroupResource) string","file":"staging/src/k8s.io/apiserver/pkg/server/options/etcd.go","code":"func (s *SimpleStorageFactory) ResourcePrefix(resource schema.GroupResource) string {\n\treturn resource.Group + \"/\" + resource.Resource\n}","line":{"from":443,"to":445}} {"id":100018282,"name":"Configs","signature":"func (s *SimpleStorageFactory) Configs() []storagebackend.Config","file":"staging/src/k8s.io/apiserver/pkg/server/options/etcd.go","code":"func (s *SimpleStorageFactory) Configs() []storagebackend.Config {\n\treturn serverstorage.Configs(s.StorageConfig)\n}","line":{"from":447,"to":449}} {"id":100018283,"name":"Backends","signature":"func (s *SimpleStorageFactory) Backends() []serverstorage.Backend","file":"staging/src/k8s.io/apiserver/pkg/server/options/etcd.go","code":"func (s *SimpleStorageFactory) Backends() []serverstorage.Backend {\n\t// nothing should ever call this method but we still provide a functional implementation\n\treturn serverstorage.Backends(s.StorageConfig)\n}","line":{"from":451,"to":454}} {"id":100018284,"name":"NewConfig","signature":"func (t *transformerStorageFactory) NewConfig(resource schema.GroupResource) (*storagebackend.ConfigForResource, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/etcd.go","code":"func (t *transformerStorageFactory) NewConfig(resource schema.GroupResource) (*storagebackend.ConfigForResource, error) {\n\tconfig, err := t.delegate.NewConfig(resource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfigCopy := *config\n\tresourceConfig := configCopy.Config\n\tresourceConfig.Transformer = t.resourceTransformers.TransformerForResource(resource)\n\tconfigCopy.Config = resourceConfig\n\n\treturn \u0026configCopy, nil\n}","line":{"from":463,"to":475}} {"id":100018285,"name":"ResourcePrefix","signature":"func (t *transformerStorageFactory) ResourcePrefix(resource schema.GroupResource) string","file":"staging/src/k8s.io/apiserver/pkg/server/options/etcd.go","code":"func (t *transformerStorageFactory) ResourcePrefix(resource schema.GroupResource) string {\n\treturn t.delegate.ResourcePrefix(resource)\n}","line":{"from":477,"to":479}} {"id":100018286,"name":"Configs","signature":"func (t *transformerStorageFactory) Configs() []storagebackend.Config","file":"staging/src/k8s.io/apiserver/pkg/server/options/etcd.go","code":"func (t *transformerStorageFactory) Configs() []storagebackend.Config {\n\treturn t.delegate.Configs()\n}","line":{"from":481,"to":483}} {"id":100018287,"name":"Backends","signature":"func (t *transformerStorageFactory) Backends() []serverstorage.Backend","file":"staging/src/k8s.io/apiserver/pkg/server/options/etcd.go","code":"func (t *transformerStorageFactory) Backends() []serverstorage.Backend {\n\treturn t.delegate.Backends()\n}","line":{"from":485,"to":487}} {"id":100018288,"name":"NewFeatureOptions","signature":"func NewFeatureOptions() *FeatureOptions","file":"staging/src/k8s.io/apiserver/pkg/server/options/feature.go","code":"func NewFeatureOptions() *FeatureOptions {\n\tdefaults := server.NewConfig(serializer.CodecFactory{})\n\n\treturn \u0026FeatureOptions{\n\t\tEnableProfiling: defaults.EnableProfiling,\n\t\tDebugSocketPath: defaults.DebugSocketPath,\n\t\tEnableContentionProfiling: defaults.EnableContentionProfiling,\n\t}\n}","line":{"from":32,"to":40}} {"id":100018289,"name":"AddFlags","signature":"func (o *FeatureOptions) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/apiserver/pkg/server/options/feature.go","code":"func (o *FeatureOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.BoolVar(\u0026o.EnableProfiling, \"profiling\", o.EnableProfiling,\n\t\t\"Enable profiling via web interface host:port/debug/pprof/\")\n\tfs.BoolVar(\u0026o.EnableContentionProfiling, \"contention-profiling\", o.EnableContentionProfiling,\n\t\t\"Enable block profiling, if profiling is enabled\")\n\tfs.StringVar(\u0026o.DebugSocketPath, \"debug-socket-path\", o.DebugSocketPath,\n\t\t\"Use an unprotected (no authn/authz) unix-domain socket for profiling with the given path\")\n}","line":{"from":42,"to":53}} {"id":100018290,"name":"ApplyTo","signature":"func (o *FeatureOptions) ApplyTo(c *server.Config) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/feature.go","code":"func (o *FeatureOptions) ApplyTo(c *server.Config) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tc.EnableProfiling = o.EnableProfiling\n\tc.DebugSocketPath = o.DebugSocketPath\n\tc.EnableContentionProfiling = o.EnableContentionProfiling\n\n\treturn nil\n}","line":{"from":55,"to":65}} {"id":100018291,"name":"Validate","signature":"func (o *FeatureOptions) Validate() []error","file":"staging/src/k8s.io/apiserver/pkg/server/options/feature.go","code":"func (o *FeatureOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\treturn errs\n}","line":{"from":67,"to":74}} {"id":100018292,"name":"NewRecommendedOptions","signature":"func NewRecommendedOptions(prefix string, codec runtime.Codec) *RecommendedOptions","file":"staging/src/k8s.io/apiserver/pkg/server/options/recommended.go","code":"func NewRecommendedOptions(prefix string, codec runtime.Codec) *RecommendedOptions {\n\tsso := NewSecureServingOptions()\n\n\t// We are composing recommended options for an aggregated api-server,\n\t// whose client is typically a proxy multiplexing many operations ---\n\t// notably including long-running ones --- into one HTTP/2 connection\n\t// into this server. So allow many concurrent operations.\n\tsso.HTTP2MaxStreamsPerConnection = 1000\n\n\treturn \u0026RecommendedOptions{\n\t\tEtcd: NewEtcdOptions(storagebackend.NewDefaultConfig(prefix, codec)),\n\t\tSecureServing: sso.WithLoopback(),\n\t\tAuthentication: NewDelegatingAuthenticationOptions(),\n\t\tAuthorization: NewDelegatingAuthorizationOptions(),\n\t\tAudit: NewAuditOptions(),\n\t\tFeatures: NewFeatureOptions(),\n\t\tCoreAPI: NewCoreAPIOptions(),\n\t\t// Wired a global by default that sadly people will abuse to have different meanings in different repos.\n\t\t// Please consider creating your own FeatureGate so you can have a consistent meaning for what a variable contains\n\t\t// across different repos. Future you will thank you.\n\t\tFeatureGate: feature.DefaultFeatureGate,\n\t\tExtraAdmissionInitializers: func(c *server.RecommendedConfig) ([]admission.PluginInitializer, error) { return nil, nil },\n\t\tAdmission: NewAdmissionOptions(),\n\t\tEgressSelector: NewEgressSelectorOptions(),\n\t\tTraces: NewTracingOptions(),\n\t}\n}","line":{"from":60,"to":86}} {"id":100018293,"name":"AddFlags","signature":"func (o *RecommendedOptions) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/apiserver/pkg/server/options/recommended.go","code":"func (o *RecommendedOptions) AddFlags(fs *pflag.FlagSet) {\n\to.Etcd.AddFlags(fs)\n\to.SecureServing.AddFlags(fs)\n\to.Authentication.AddFlags(fs)\n\to.Authorization.AddFlags(fs)\n\to.Audit.AddFlags(fs)\n\to.Features.AddFlags(fs)\n\to.CoreAPI.AddFlags(fs)\n\to.Admission.AddFlags(fs)\n\to.EgressSelector.AddFlags(fs)\n\to.Traces.AddFlags(fs)\n}","line":{"from":88,"to":99}} {"id":100018294,"name":"ApplyTo","signature":"func (o *RecommendedOptions) ApplyTo(config *server.RecommendedConfig) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/recommended.go","code":"// ApplyTo adds RecommendedOptions to the server configuration.\n// pluginInitializers can be empty, it is only need for additional initializers.\nfunc (o *RecommendedOptions) ApplyTo(config *server.RecommendedConfig) error {\n\tif err := o.Etcd.Complete(config.Config.StorageObjectCountTracker, config.Config.DrainedNotify(), config.Config.AddPostStartHook); err != nil {\n\t\treturn err\n\t}\n\tif err := o.Etcd.ApplyTo(\u0026config.Config); err != nil {\n\t\treturn err\n\t}\n\tif err := o.EgressSelector.ApplyTo(\u0026config.Config); err != nil {\n\t\treturn err\n\t}\n\tif err := o.Traces.ApplyTo(config.Config.EgressSelector, \u0026config.Config); err != nil {\n\t\treturn err\n\t}\n\tif err := o.SecureServing.ApplyTo(\u0026config.Config.SecureServing, \u0026config.Config.LoopbackClientConfig); err != nil {\n\t\treturn err\n\t}\n\tif err := o.Authentication.ApplyTo(\u0026config.Config.Authentication, config.SecureServing, config.OpenAPIConfig); err != nil {\n\t\treturn err\n\t}\n\tif err := o.Authorization.ApplyTo(\u0026config.Config.Authorization); err != nil {\n\t\treturn err\n\t}\n\tif err := o.Audit.ApplyTo(\u0026config.Config); err != nil {\n\t\treturn err\n\t}\n\tif err := o.Features.ApplyTo(\u0026config.Config); err != nil {\n\t\treturn err\n\t}\n\tif err := o.CoreAPI.ApplyTo(config); err != nil {\n\t\treturn err\n\t}\n\tif initializers, err := o.ExtraAdmissionInitializers(config); err != nil {\n\t\treturn err\n\t} else if err := o.Admission.ApplyTo(\u0026config.Config, config.SharedInformerFactory, config.ClientConfig, o.FeatureGate, initializers...); err != nil {\n\t\treturn err\n\t}\n\tif feature.DefaultFeatureGate.Enabled(features.APIPriorityAndFairness) {\n\t\tif config.ClientConfig != nil {\n\t\t\tif config.MaxRequestsInFlight+config.MaxMutatingRequestsInFlight \u003c= 0 {\n\t\t\t\treturn fmt.Errorf(\"invalid configuration: MaxRequestsInFlight=%d and MaxMutatingRequestsInFlight=%d; they must add up to something positive\", config.MaxRequestsInFlight, config.MaxMutatingRequestsInFlight)\n\n\t\t\t}\n\t\t\tconfig.FlowControl = utilflowcontrol.New(\n\t\t\t\tconfig.SharedInformerFactory,\n\t\t\t\tkubernetes.NewForConfigOrDie(config.ClientConfig).FlowcontrolV1beta3(),\n\t\t\t\tconfig.MaxRequestsInFlight+config.MaxMutatingRequestsInFlight,\n\t\t\t\tconfig.RequestTimeout/4,\n\t\t\t)\n\t\t} else {\n\t\t\tklog.Warningf(\"Neither kubeconfig is provided nor service-account is mounted, so APIPriorityAndFairness will be disabled\")\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":101,"to":156}} {"id":100018295,"name":"Validate","signature":"func (o *RecommendedOptions) Validate() []error","file":"staging/src/k8s.io/apiserver/pkg/server/options/recommended.go","code":"func (o *RecommendedOptions) Validate() []error {\n\terrors := []error{}\n\terrors = append(errors, o.Etcd.Validate()...)\n\terrors = append(errors, o.SecureServing.Validate()...)\n\terrors = append(errors, o.Authentication.Validate()...)\n\terrors = append(errors, o.Authorization.Validate()...)\n\terrors = append(errors, o.Audit.Validate()...)\n\terrors = append(errors, o.Features.Validate()...)\n\terrors = append(errors, o.CoreAPI.Validate()...)\n\terrors = append(errors, o.Admission.Validate()...)\n\terrors = append(errors, o.EgressSelector.Validate()...)\n\terrors = append(errors, o.Traces.Validate()...)\n\n\treturn errors\n}","line":{"from":158,"to":172}} {"id":100018296,"name":"NewServerRunOptions","signature":"func NewServerRunOptions() *ServerRunOptions","file":"staging/src/k8s.io/apiserver/pkg/server/options/server_run_options.go","code":"func NewServerRunOptions() *ServerRunOptions {\n\tdefaults := server.NewConfig(serializer.CodecFactory{})\n\treturn \u0026ServerRunOptions{\n\t\tMaxRequestsInFlight: defaults.MaxRequestsInFlight,\n\t\tMaxMutatingRequestsInFlight: defaults.MaxMutatingRequestsInFlight,\n\t\tRequestTimeout: defaults.RequestTimeout,\n\t\tLivezGracePeriod: defaults.LivezGracePeriod,\n\t\tMinRequestTimeout: defaults.MinRequestTimeout,\n\t\tShutdownDelayDuration: defaults.ShutdownDelayDuration,\n\t\tShutdownWatchTerminationGracePeriod: defaults.ShutdownWatchTerminationGracePeriod,\n\t\tJSONPatchMaxCopyBytes: defaults.JSONPatchMaxCopyBytes,\n\t\tMaxRequestBodyBytes: defaults.MaxRequestBodyBytes,\n\t\tEnablePriorityAndFairness: true,\n\t\tShutdownSendRetryAfter: false,\n\t}\n}","line":{"from":95,"to":110}} {"id":100018297,"name":"ApplyTo","signature":"func (s *ServerRunOptions) ApplyTo(c *server.Config) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/server_run_options.go","code":"// ApplyTo applies the run options to the method receiver and returns self\nfunc (s *ServerRunOptions) ApplyTo(c *server.Config) error {\n\tc.CorsAllowedOriginList = s.CorsAllowedOriginList\n\tc.HSTSDirectives = s.HSTSDirectives\n\tc.ExternalAddress = s.ExternalHost\n\tc.MaxRequestsInFlight = s.MaxRequestsInFlight\n\tc.MaxMutatingRequestsInFlight = s.MaxMutatingRequestsInFlight\n\tc.LivezGracePeriod = s.LivezGracePeriod\n\tc.RequestTimeout = s.RequestTimeout\n\tc.GoawayChance = s.GoawayChance\n\tc.MinRequestTimeout = s.MinRequestTimeout\n\tc.ShutdownDelayDuration = s.ShutdownDelayDuration\n\tc.JSONPatchMaxCopyBytes = s.JSONPatchMaxCopyBytes\n\tc.MaxRequestBodyBytes = s.MaxRequestBodyBytes\n\tc.PublicAddress = s.AdvertiseAddress\n\tc.ShutdownSendRetryAfter = s.ShutdownSendRetryAfter\n\tc.ShutdownWatchTerminationGracePeriod = s.ShutdownWatchTerminationGracePeriod\n\n\treturn nil\n}","line":{"from":112,"to":131}} {"id":100018298,"name":"DefaultAdvertiseAddress","signature":"func (s *ServerRunOptions) DefaultAdvertiseAddress(secure *SecureServingOptions) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/server_run_options.go","code":"// DefaultAdvertiseAddress sets the field AdvertiseAddress if unset. The field will be set based on the SecureServingOptions.\nfunc (s *ServerRunOptions) DefaultAdvertiseAddress(secure *SecureServingOptions) error {\n\tif secure == nil {\n\t\treturn nil\n\t}\n\n\tif s.AdvertiseAddress == nil || s.AdvertiseAddress.IsUnspecified() {\n\t\thostIP, err := secure.DefaultExternalAddress()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Unable to find suitable network address.error='%v'. \"+\n\t\t\t\t\"Try to set the AdvertiseAddress directly or provide a valid BindAddress to fix this.\", err)\n\t\t}\n\t\ts.AdvertiseAddress = hostIP\n\t}\n\n\treturn nil\n}","line":{"from":133,"to":149}} {"id":100018299,"name":"Validate","signature":"func (s *ServerRunOptions) Validate() []error","file":"staging/src/k8s.io/apiserver/pkg/server/options/server_run_options.go","code":"// Validate checks validation of ServerRunOptions\nfunc (s *ServerRunOptions) Validate() []error {\n\terrors := []error{}\n\n\tif s.LivezGracePeriod \u003c 0 {\n\t\terrors = append(errors, fmt.Errorf(\"--livez-grace-period can not be a negative value\"))\n\t}\n\n\tif s.MaxRequestsInFlight \u003c 0 {\n\t\terrors = append(errors, fmt.Errorf(\"--max-requests-inflight can not be negative value\"))\n\t}\n\tif s.MaxMutatingRequestsInFlight \u003c 0 {\n\t\terrors = append(errors, fmt.Errorf(\"--max-mutating-requests-inflight can not be negative value\"))\n\t}\n\n\tif s.RequestTimeout.Nanoseconds() \u003c 0 {\n\t\terrors = append(errors, fmt.Errorf(\"--request-timeout can not be negative value\"))\n\t}\n\n\tif s.GoawayChance \u003c 0 || s.GoawayChance \u003e 0.02 {\n\t\terrors = append(errors, fmt.Errorf(\"--goaway-chance can not be less than 0 or greater than 0.02\"))\n\t}\n\n\tif s.MinRequestTimeout \u003c 0 {\n\t\terrors = append(errors, fmt.Errorf(\"--min-request-timeout can not be negative value\"))\n\t}\n\n\tif s.ShutdownDelayDuration \u003c 0 {\n\t\terrors = append(errors, fmt.Errorf(\"--shutdown-delay-duration can not be negative value\"))\n\t}\n\n\tif s.ShutdownWatchTerminationGracePeriod \u003c 0 {\n\t\terrors = append(errors, fmt.Errorf(\"shutdown-watch-termination-grace-period, if provided, can not be a negative value\"))\n\t}\n\n\tif s.JSONPatchMaxCopyBytes \u003c 0 {\n\t\terrors = append(errors, fmt.Errorf(\"ServerRunOptions.JSONPatchMaxCopyBytes can not be negative value\"))\n\t}\n\n\tif s.MaxRequestBodyBytes \u003c 0 {\n\t\terrors = append(errors, fmt.Errorf(\"ServerRunOptions.MaxRequestBodyBytes can not be negative value\"))\n\t}\n\n\tif err := validateHSTSDirectives(s.HSTSDirectives); err != nil {\n\t\terrors = append(errors, err)\n\t}\n\n\tif err := validateCorsAllowedOriginList(s.CorsAllowedOriginList); err != nil {\n\t\terrors = append(errors, err)\n\t}\n\treturn errors\n}","line":{"from":151,"to":202}} {"id":100018300,"name":"validateHSTSDirectives","signature":"func validateHSTSDirectives(hstsDirectives []string) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/server_run_options.go","code":"func validateHSTSDirectives(hstsDirectives []string) error {\n\t// HSTS Headers format: Strict-Transport-Security:max-age=expireTime [;includeSubDomains] [;preload]\n\t// See https://tools.ietf.org/html/rfc6797#section-6.1 for more information\n\tallErrors := []error{}\n\tfor _, hstsDirective := range hstsDirectives {\n\t\tif len(strings.TrimSpace(hstsDirective)) == 0 {\n\t\t\tallErrors = append(allErrors, fmt.Errorf(\"empty value in strict-transport-security-directives\"))\n\t\t\tcontinue\n\t\t}\n\t\tif hstsDirective != \"includeSubDomains\" \u0026\u0026 hstsDirective != \"preload\" {\n\t\t\tmaxAgeDirective := strings.Split(hstsDirective, \"=\")\n\t\t\tif len(maxAgeDirective) != 2 || maxAgeDirective[0] != \"max-age\" {\n\t\t\t\tallErrors = append(allErrors, fmt.Errorf(\"--strict-transport-security-directives invalid, allowed values: max-age=expireTime, includeSubDomains, preload. see https://tools.ietf.org/html/rfc6797#section-6.1 for more information\"))\n\t\t\t}\n\t\t}\n\t}\n\treturn errors.NewAggregate(allErrors)\n}","line":{"from":204,"to":221}} {"id":100018301,"name":"validateCorsAllowedOriginList","signature":"func validateCorsAllowedOriginList(corsAllowedOriginList []string) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/server_run_options.go","code":"func validateCorsAllowedOriginList(corsAllowedOriginList []string) error {\n\tallErrors := []error{}\n\tvalidateRegexFn := func(regexpStr string) error {\n\t\tif _, err := regexp.Compile(regexpStr); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// the regular expression should pin to the start and end of the host\n\t\t// in the origin header, this will prevent CVE-2022-1996.\n\t\t// possible ways it can pin to the start of host in the origin header:\n\t\t// - match the start of the origin with '^'\n\t\t// - match what separates the scheme and host with '//' or '://',\n\t\t// this pins to the start of host in the origin header.\n\t\t// possible ways it can match the end of the host in the origin header:\n\t\t// - match the end of the origin with '$'\n\t\t// - with a capture group that matches the host and port separator '(:|$)'\n\t\t// We will relax the validation to check if these regex markers\n\t\t// are present in the user specified expression.\n\t\tvar pinStart, pinEnd bool\n\t\tfor _, prefix := range []string{\"^\", \"//\"} {\n\t\t\tif strings.Contains(regexpStr, prefix) {\n\t\t\t\tpinStart = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tfor _, suffix := range []string{\"$\", \":\"} {\n\t\t\tif strings.Contains(regexpStr, suffix) {\n\t\t\t\tpinEnd = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !pinStart || !pinEnd {\n\t\t\treturn fmt.Errorf(\"regular expression does not pin to start/end of host in the origin header\")\n\t\t}\n\t\treturn nil\n\t}\n\n\tfor _, regexp := range corsAllowedOriginList {\n\t\tif len(regexp) == 0 {\n\t\t\tallErrors = append(allErrors, fmt.Errorf(\"empty value in --cors-allowed-origins, help: %s\", corsAllowedOriginsHelpText))\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := validateRegexFn(regexp); err != nil {\n\t\t\terr = fmt.Errorf(\"--cors-allowed-origins has an invalid regular expression: %v, help: %s\", err, corsAllowedOriginsHelpText)\n\t\t\tallErrors = append(allErrors, err)\n\t\t}\n\t}\n\treturn errors.NewAggregate(allErrors)\n}","line":{"from":223,"to":272}} {"id":100018302,"name":"AddUniversalFlags","signature":"func (s *ServerRunOptions) AddUniversalFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/apiserver/pkg/server/options/server_run_options.go","code":"// AddUniversalFlags adds flags for a specific APIServer to the specified FlagSet\nfunc (s *ServerRunOptions) AddUniversalFlags(fs *pflag.FlagSet) {\n\t// Note: the weird \"\"+ in below lines seems to be the only way to get gofmt to\n\t// arrange these text blocks sensibly. Grrr.\n\n\tfs.IPVar(\u0026s.AdvertiseAddress, \"advertise-address\", s.AdvertiseAddress, \"\"+\n\t\t\"The IP address on which to advertise the apiserver to members of the cluster. This \"+\n\t\t\"address must be reachable by the rest of the cluster. If blank, the --bind-address \"+\n\t\t\"will be used. If --bind-address is unspecified, the host's default interface will \"+\n\t\t\"be used.\")\n\n\tfs.StringSliceVar(\u0026s.CorsAllowedOriginList, \"cors-allowed-origins\", s.CorsAllowedOriginList, corsAllowedOriginsHelpText)\n\n\tfs.StringSliceVar(\u0026s.HSTSDirectives, \"strict-transport-security-directives\", s.HSTSDirectives, \"\"+\n\t\t\"List of directives for HSTS, comma separated. If this list is empty, then HSTS directives will not \"+\n\t\t\"be added. Example: 'max-age=31536000,includeSubDomains,preload'\")\n\n\tfs.StringVar(\u0026s.ExternalHost, \"external-hostname\", s.ExternalHost,\n\t\t\"The hostname to use when generating externalized URLs for this master (e.g. Swagger API Docs or OpenID Discovery).\")\n\n\tfs.IntVar(\u0026s.MaxRequestsInFlight, \"max-requests-inflight\", s.MaxRequestsInFlight, \"\"+\n\t\t\"This and --max-mutating-requests-inflight are summed to determine the server's total concurrency limit \"+\n\t\t\"(which must be positive) if --enable-priority-and-fairness is true. \"+\n\t\t\"Otherwise, this flag limits the maximum number of non-mutating requests in flight, \"+\n\t\t\"or a zero value disables the limit completely.\")\n\n\tfs.IntVar(\u0026s.MaxMutatingRequestsInFlight, \"max-mutating-requests-inflight\", s.MaxMutatingRequestsInFlight, \"\"+\n\t\t\"This and --max-requests-inflight are summed to determine the server's total concurrency limit \"+\n\t\t\"(which must be positive) if --enable-priority-and-fairness is true. \"+\n\t\t\"Otherwise, this flag limits the maximum number of mutating requests in flight, \"+\n\t\t\"or a zero value disables the limit completely.\")\n\n\tfs.DurationVar(\u0026s.RequestTimeout, \"request-timeout\", s.RequestTimeout, \"\"+\n\t\t\"An optional field indicating the duration a handler must keep a request open before timing \"+\n\t\t\"it out. This is the default request timeout for requests but may be overridden by flags such as \"+\n\t\t\"--min-request-timeout for specific types of requests.\")\n\n\tfs.Float64Var(\u0026s.GoawayChance, \"goaway-chance\", s.GoawayChance, \"\"+\n\t\t\"To prevent HTTP/2 clients from getting stuck on a single apiserver, randomly close a connection (GOAWAY). \"+\n\t\t\"The client's other in-flight requests won't be affected, and the client will reconnect, likely landing on a different apiserver after going through the load balancer again. \"+\n\t\t\"This argument sets the fraction of requests that will be sent a GOAWAY. Clusters with single apiservers, or which don't use a load balancer, should NOT enable this. \"+\n\t\t\"Min is 0 (off), Max is .02 (1/50 requests); .001 (1/1000) is a recommended starting point.\")\n\n\tfs.DurationVar(\u0026s.LivezGracePeriod, \"livez-grace-period\", s.LivezGracePeriod, \"\"+\n\t\t\"This option represents the maximum amount of time it should take for apiserver to complete its startup sequence \"+\n\t\t\"and become live. From apiserver's start time to when this amount of time has elapsed, /livez will assume \"+\n\t\t\"that unfinished post-start hooks will complete successfully and therefore return true.\")\n\n\tfs.IntVar(\u0026s.MinRequestTimeout, \"min-request-timeout\", s.MinRequestTimeout, \"\"+\n\t\t\"An optional field indicating the minimum number of seconds a handler must keep \"+\n\t\t\"a request open before timing it out. Currently only honored by the watch request \"+\n\t\t\"handler, which picks a randomized value above this number as the connection timeout, \"+\n\t\t\"to spread out load.\")\n\n\tfs.BoolVar(\u0026s.EnablePriorityAndFairness, \"enable-priority-and-fairness\", s.EnablePriorityAndFairness, \"\"+\n\t\t\"If true and the APIPriorityAndFairness feature gate is enabled, replace the max-in-flight handler with an enhanced one that queues and dispatches with priority and fairness\")\n\n\tfs.DurationVar(\u0026s.ShutdownDelayDuration, \"shutdown-delay-duration\", s.ShutdownDelayDuration, \"\"+\n\t\t\"Time to delay the termination. During that time the server keeps serving requests normally. The endpoints /healthz and /livez \"+\n\t\t\"will return success, but /readyz immediately returns failure. Graceful termination starts after this delay \"+\n\t\t\"has elapsed. This can be used to allow load balancer to stop sending traffic to this server.\")\n\n\tfs.BoolVar(\u0026s.ShutdownSendRetryAfter, \"shutdown-send-retry-after\", s.ShutdownSendRetryAfter, \"\"+\n\t\t\"If true the HTTP Server will continue listening until all non long running request(s) in flight have been drained, \"+\n\t\t\"during this window all incoming requests will be rejected with a status code 429 and a 'Retry-After' response header, \"+\n\t\t\"in addition 'Connection: close' response header is set in order to tear down the TCP connection when idle.\")\n\n\tfs.DurationVar(\u0026s.ShutdownWatchTerminationGracePeriod, \"shutdown-watch-termination-grace-period\", s.ShutdownWatchTerminationGracePeriod, \"\"+\n\t\t\"This option, if set, represents the maximum amount of grace period the apiserver will wait \"+\n\t\t\"for active watch request(s) to drain during the graceful server shutdown window.\")\n\n\tutilfeature.DefaultMutableFeatureGate.AddFlag(fs)\n}","line":{"from":274,"to":346}} {"id":100018303,"name":"NewSecureServingOptions","signature":"func NewSecureServingOptions() *SecureServingOptions","file":"staging/src/k8s.io/apiserver/pkg/server/options/serving.go","code":"func NewSecureServingOptions() *SecureServingOptions {\n\treturn \u0026SecureServingOptions{\n\t\tBindAddress: netutils.ParseIPSloppy(\"0.0.0.0\"),\n\t\tBindPort: 443,\n\t\tServerCert: GeneratableKeyCert{\n\t\t\tPairName: \"apiserver\",\n\t\t\tCertDirectory: \"apiserver.local.config/certificates\",\n\t\t},\n\t}\n}","line":{"from":110,"to":119}} {"id":100018304,"name":"DefaultExternalAddress","signature":"func (s *SecureServingOptions) DefaultExternalAddress() (net.IP, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/serving.go","code":"func (s *SecureServingOptions) DefaultExternalAddress() (net.IP, error) {\n\tif s.ExternalAddress != nil \u0026\u0026 !s.ExternalAddress.IsUnspecified() {\n\t\treturn s.ExternalAddress, nil\n\t}\n\treturn utilnet.ResolveBindAddress(s.BindAddress)\n}","line":{"from":121,"to":126}} {"id":100018305,"name":"Validate","signature":"func (s *SecureServingOptions) Validate() []error","file":"staging/src/k8s.io/apiserver/pkg/server/options/serving.go","code":"func (s *SecureServingOptions) Validate() []error {\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\terrors := []error{}\n\n\tif s.Required \u0026\u0026 s.BindPort \u003c 1 || s.BindPort \u003e 65535 {\n\t\terrors = append(errors, fmt.Errorf(\"--secure-port %v must be between 1 and 65535, inclusive. It cannot be turned off with 0\", s.BindPort))\n\t} else if s.BindPort \u003c 0 || s.BindPort \u003e 65535 {\n\t\terrors = append(errors, fmt.Errorf(\"--secure-port %v must be between 0 and 65535, inclusive. 0 for turning off secure port\", s.BindPort))\n\t}\n\n\tif (len(s.ServerCert.CertKey.CertFile) != 0 || len(s.ServerCert.CertKey.KeyFile) != 0) \u0026\u0026 s.ServerCert.GeneratedCert != nil {\n\t\terrors = append(errors, fmt.Errorf(\"cert/key file and in-memory certificate cannot both be set\"))\n\t}\n\n\treturn errors\n}","line":{"from":128,"to":146}} {"id":100018306,"name":"AddFlags","signature":"func (s *SecureServingOptions) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/apiserver/pkg/server/options/serving.go","code":"func (s *SecureServingOptions) AddFlags(fs *pflag.FlagSet) {\n\tif s == nil {\n\t\treturn\n\t}\n\n\tfs.IPVar(\u0026s.BindAddress, \"bind-address\", s.BindAddress, \"\"+\n\t\t\"The IP address on which to listen for the --secure-port port. The \"+\n\t\t\"associated interface(s) must be reachable by the rest of the cluster, and by CLI/web \"+\n\t\t\"clients. If blank or an unspecified address (0.0.0.0 or ::), all interfaces will be used.\")\n\n\tdesc := \"The port on which to serve HTTPS with authentication and authorization.\"\n\tif s.Required {\n\t\tdesc += \" It cannot be switched off with 0.\"\n\t} else {\n\t\tdesc += \" If 0, don't serve HTTPS at all.\"\n\t}\n\tfs.IntVar(\u0026s.BindPort, \"secure-port\", s.BindPort, desc)\n\n\tfs.StringVar(\u0026s.ServerCert.CertDirectory, \"cert-dir\", s.ServerCert.CertDirectory, \"\"+\n\t\t\"The directory where the TLS certs are located. \"+\n\t\t\"If --tls-cert-file and --tls-private-key-file are provided, this flag will be ignored.\")\n\n\tfs.StringVar(\u0026s.ServerCert.CertKey.CertFile, \"tls-cert-file\", s.ServerCert.CertKey.CertFile, \"\"+\n\t\t\"File containing the default x509 Certificate for HTTPS. (CA cert, if any, concatenated \"+\n\t\t\"after server cert). If HTTPS serving is enabled, and --tls-cert-file and \"+\n\t\t\"--tls-private-key-file are not provided, a self-signed certificate and key \"+\n\t\t\"are generated for the public address and saved to the directory specified by --cert-dir.\")\n\n\tfs.StringVar(\u0026s.ServerCert.CertKey.KeyFile, \"tls-private-key-file\", s.ServerCert.CertKey.KeyFile,\n\t\t\"File containing the default x509 private key matching --tls-cert-file.\")\n\n\ttlsCipherPreferredValues := cliflag.PreferredTLSCipherNames()\n\ttlsCipherInsecureValues := cliflag.InsecureTLSCipherNames()\n\tfs.StringSliceVar(\u0026s.CipherSuites, \"tls-cipher-suites\", s.CipherSuites,\n\t\t\"Comma-separated list of cipher suites for the server. \"+\n\t\t\t\"If omitted, the default Go cipher suites will be used. \\n\"+\n\t\t\t\"Preferred values: \"+strings.Join(tlsCipherPreferredValues, \", \")+\". \\n\"+\n\t\t\t\"Insecure values: \"+strings.Join(tlsCipherInsecureValues, \", \")+\".\")\n\n\ttlsPossibleVersions := cliflag.TLSPossibleVersions()\n\tfs.StringVar(\u0026s.MinTLSVersion, \"tls-min-version\", s.MinTLSVersion,\n\t\t\"Minimum TLS version supported. \"+\n\t\t\t\"Possible values: \"+strings.Join(tlsPossibleVersions, \", \"))\n\n\tfs.Var(cliflag.NewNamedCertKeyArray(\u0026s.SNICertKeys), \"tls-sni-cert-key\", \"\"+\n\t\t\"A pair of x509 certificate and private key file paths, optionally suffixed with a list of \"+\n\t\t\"domain patterns which are fully qualified domain names, possibly with prefixed wildcard \"+\n\t\t\"segments. The domain patterns also allow IP addresses, but IPs should only be used if \"+\n\t\t\"the apiserver has visibility to the IP address requested by a client. \"+\n\t\t\"If no domain patterns are provided, the names of the certificate are \"+\n\t\t\"extracted. Non-wildcard matches trump over wildcard matches, explicit domain patterns \"+\n\t\t\"trump over extracted names. For multiple key/certificate pairs, use the \"+\n\t\t\"--tls-sni-cert-key multiple times. \"+\n\t\t\"Examples: \\\"example.crt,example.key\\\" or \\\"foo.crt,foo.key:*.foo.com,foo.com\\\".\")\n\n\tfs.IntVar(\u0026s.HTTP2MaxStreamsPerConnection, \"http2-max-streams-per-connection\", s.HTTP2MaxStreamsPerConnection, \"\"+\n\t\t\"The limit that the server gives to clients for \"+\n\t\t\"the maximum number of streams in an HTTP/2 connection. \"+\n\t\t\"Zero means to use golang's default.\")\n\n\tfs.BoolVar(\u0026s.PermitPortSharing, \"permit-port-sharing\", s.PermitPortSharing,\n\t\t\"If true, SO_REUSEPORT will be used when binding the port, which allows \"+\n\t\t\t\"more than one instance to bind on the same address and port. [default=false]\")\n\n\tfs.BoolVar(\u0026s.PermitAddressSharing, \"permit-address-sharing\", s.PermitAddressSharing,\n\t\t\"If true, SO_REUSEADDR will be used when binding the port. This allows binding \"+\n\t\t\t\"to wildcard IPs like 0.0.0.0 and specific IPs in parallel, and it avoids waiting \"+\n\t\t\t\"for the kernel to release sockets in TIME_WAIT state. [default=false]\")\n}","line":{"from":148,"to":216}} {"id":100018307,"name":"ApplyTo","signature":"func (s *SecureServingOptions) ApplyTo(config **server.SecureServingInfo) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/serving.go","code":"// ApplyTo fills up serving information in the server configuration.\nfunc (s *SecureServingOptions) ApplyTo(config **server.SecureServingInfo) error {\n\tif s == nil {\n\t\treturn nil\n\t}\n\tif s.BindPort \u003c= 0 \u0026\u0026 s.Listener == nil {\n\t\treturn nil\n\t}\n\n\tif s.Listener == nil {\n\t\tvar err error\n\t\taddr := net.JoinHostPort(s.BindAddress.String(), strconv.Itoa(s.BindPort))\n\n\t\tc := net.ListenConfig{}\n\n\t\tctls := multipleControls{}\n\t\tif s.PermitPortSharing {\n\t\t\tctls = append(ctls, permitPortReuse)\n\t\t}\n\t\tif s.PermitAddressSharing {\n\t\t\tctls = append(ctls, permitAddressReuse)\n\t\t}\n\t\tif len(ctls) \u003e 0 {\n\t\t\tc.Control = ctls.Control\n\t\t}\n\n\t\ts.Listener, s.BindPort, err = CreateListener(s.BindNetwork, addr, c)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create listener: %v\", err)\n\t\t}\n\t} else {\n\t\tif _, ok := s.Listener.Addr().(*net.TCPAddr); !ok {\n\t\t\treturn fmt.Errorf(\"failed to parse ip and port from listener\")\n\t\t}\n\t\ts.BindPort = s.Listener.Addr().(*net.TCPAddr).Port\n\t\ts.BindAddress = s.Listener.Addr().(*net.TCPAddr).IP\n\t}\n\n\t*config = \u0026server.SecureServingInfo{\n\t\tListener: s.Listener,\n\t\tHTTP2MaxStreamsPerConnection: s.HTTP2MaxStreamsPerConnection,\n\t}\n\tc := *config\n\n\tserverCertFile, serverKeyFile := s.ServerCert.CertKey.CertFile, s.ServerCert.CertKey.KeyFile\n\t// load main cert\n\tif len(serverCertFile) != 0 || len(serverKeyFile) != 0 {\n\t\tvar err error\n\t\tc.Cert, err = dynamiccertificates.NewDynamicServingContentFromFiles(\"serving-cert\", serverCertFile, serverKeyFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else if s.ServerCert.GeneratedCert != nil {\n\t\tc.Cert = s.ServerCert.GeneratedCert\n\t}\n\n\tif len(s.CipherSuites) != 0 {\n\t\tcipherSuites, err := cliflag.TLSCipherSuites(s.CipherSuites)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc.CipherSuites = cipherSuites\n\t}\n\n\tvar err error\n\tc.MinTLSVersion, err = cliflag.TLSVersion(s.MinTLSVersion)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// load SNI certs\n\tnamedTLSCerts := make([]dynamiccertificates.SNICertKeyContentProvider, 0, len(s.SNICertKeys))\n\tfor _, nck := range s.SNICertKeys {\n\t\ttlsCert, err := dynamiccertificates.NewDynamicSNIContentFromFiles(\"sni-serving-cert\", nck.CertFile, nck.KeyFile, nck.Names...)\n\t\tnamedTLSCerts = append(namedTLSCerts, tlsCert)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to load SNI cert and key: %v\", err)\n\t\t}\n\t}\n\tc.SNICerts = namedTLSCerts\n\n\treturn nil\n}","line":{"from":218,"to":300}} {"id":100018308,"name":"MaybeDefaultWithSelfSignedCerts","signature":"func (s *SecureServingOptions) MaybeDefaultWithSelfSignedCerts(publicAddress string, alternateDNS []string, alternateIPs []net.IP) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/serving.go","code":"func (s *SecureServingOptions) MaybeDefaultWithSelfSignedCerts(publicAddress string, alternateDNS []string, alternateIPs []net.IP) error {\n\tif s == nil || (s.BindPort == 0 \u0026\u0026 s.Listener == nil) {\n\t\treturn nil\n\t}\n\tkeyCert := \u0026s.ServerCert.CertKey\n\tif len(keyCert.CertFile) != 0 || len(keyCert.KeyFile) != 0 {\n\t\treturn nil\n\t}\n\n\tcanReadCertAndKey := false\n\tif len(s.ServerCert.CertDirectory) \u003e 0 {\n\t\tif len(s.ServerCert.PairName) == 0 {\n\t\t\treturn fmt.Errorf(\"PairName is required if CertDirectory is set\")\n\t\t}\n\t\tkeyCert.CertFile = path.Join(s.ServerCert.CertDirectory, s.ServerCert.PairName+\".crt\")\n\t\tkeyCert.KeyFile = path.Join(s.ServerCert.CertDirectory, s.ServerCert.PairName+\".key\")\n\t\tif canRead, err := certutil.CanReadCertAndKey(keyCert.CertFile, keyCert.KeyFile); err != nil {\n\t\t\treturn err\n\t\t} else {\n\t\t\tcanReadCertAndKey = canRead\n\t\t}\n\t}\n\n\tif !canReadCertAndKey {\n\t\t// add either the bind address or localhost to the valid alternates\n\t\tif s.BindAddress.IsUnspecified() {\n\t\t\talternateDNS = append(alternateDNS, \"localhost\")\n\t\t} else {\n\t\t\talternateIPs = append(alternateIPs, s.BindAddress)\n\t\t}\n\n\t\tif cert, key, err := certutil.GenerateSelfSignedCertKeyWithFixtures(publicAddress, alternateIPs, alternateDNS, s.ServerCert.FixtureDirectory); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to generate self signed cert: %v\", err)\n\t\t} else if len(keyCert.CertFile) \u003e 0 \u0026\u0026 len(keyCert.KeyFile) \u003e 0 {\n\t\t\tif err := certutil.WriteCert(keyCert.CertFile, cert); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := keyutil.WriteKey(keyCert.KeyFile, key); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tklog.Infof(\"Generated self-signed cert (%s, %s)\", keyCert.CertFile, keyCert.KeyFile)\n\t\t} else {\n\t\t\ts.ServerCert.GeneratedCert, err = dynamiccertificates.NewStaticCertKeyContent(\"Generated self signed cert\", cert, key)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tklog.Infof(\"Generated self-signed cert in-memory\")\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":302,"to":353}} {"id":100018309,"name":"CreateListener","signature":"func CreateListener(network, addr string, config net.ListenConfig) (net.Listener, int, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/serving.go","code":"func CreateListener(network, addr string, config net.ListenConfig) (net.Listener, int, error) {\n\tif len(network) == 0 {\n\t\tnetwork = \"tcp\"\n\t}\n\n\tln, err := config.Listen(context.TODO(), network, addr)\n\tif err != nil {\n\t\treturn nil, 0, fmt.Errorf(\"failed to listen on %v: %v\", addr, err)\n\t}\n\n\t// get port\n\ttcpAddr, ok := ln.Addr().(*net.TCPAddr)\n\tif !ok {\n\t\tln.Close()\n\t\treturn nil, 0, fmt.Errorf(\"invalid listen address: %q\", ln.Addr().String())\n\t}\n\n\treturn ln, tcpAddr.Port, nil\n}","line":{"from":355,"to":373}} {"id":100018310,"name":"Control","signature":"func (mcs multipleControls) Control(network, addr string, conn syscall.RawConn) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/serving.go","code":"func (mcs multipleControls) Control(network, addr string, conn syscall.RawConn) error {\n\tfor _, c := range mcs {\n\t\tif err := c(network, addr, conn); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":377,"to":384}} {"id":100018311,"name":"permitPortReuse","signature":"func permitPortReuse(network, addr string, conn syscall.RawConn) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/serving_unix.go","code":"func permitPortReuse(network, addr string, conn syscall.RawConn) error {\n\treturn conn.Control(func(fd uintptr) {\n\t\tif err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, unix.SO_REUSEPORT, 1); err != nil {\n\t\t\tklog.Warningf(\"failed to set SO_REUSEPORT on socket: %v\", err)\n\t\t}\n\t})\n}","line":{"from":30,"to":36}} {"id":100018312,"name":"permitAddressReuse","signature":"func permitAddressReuse(network, addr string, conn syscall.RawConn) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/serving_unix.go","code":"func permitAddressReuse(network, addr string, conn syscall.RawConn) error {\n\treturn conn.Control(func(fd uintptr) {\n\t\tif err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, unix.SO_REUSEADDR, 1); err != nil {\n\t\t\tklog.Warningf(\"failed to set SO_REUSEADDR on socket: %v\", err)\n\t\t}\n\t})\n}","line":{"from":38,"to":44}} {"id":100018313,"name":"permitPortReuse","signature":"func permitPortReuse(network, address string, c syscall.RawConn) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/serving_windows.go","code":"func permitPortReuse(network, address string, c syscall.RawConn) error {\n\treturn fmt.Errorf(\"port reuse is not supported on Windows\")\n}","line":{"from":27,"to":29}} {"id":100018314,"name":"permitAddressReuse","signature":"func permitAddressReuse(network, addr string, conn syscall.RawConn) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/serving_windows.go","code":"// Windows supports SO_REUSEADDR, but it may cause undefined behavior, as\n// there is no protection against port hijacking.\nfunc permitAddressReuse(network, addr string, conn syscall.RawConn) error {\n\treturn fmt.Errorf(\"address reuse is not supported on Windows\")\n}","line":{"from":31,"to":35}} {"id":100018315,"name":"WithLoopback","signature":"func (o *SecureServingOptions) WithLoopback() *SecureServingOptionsWithLoopback","file":"staging/src/k8s.io/apiserver/pkg/server/options/serving_with_loopback.go","code":"func (o *SecureServingOptions) WithLoopback() *SecureServingOptionsWithLoopback {\n\treturn \u0026SecureServingOptionsWithLoopback{o}\n}","line":{"from":34,"to":36}} {"id":100018316,"name":"ApplyTo","signature":"func (s *SecureServingOptionsWithLoopback) ApplyTo(secureServingInfo **server.SecureServingInfo, loopbackClientConfig **rest.Config) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/serving_with_loopback.go","code":"// ApplyTo fills up serving information in the server configuration.\nfunc (s *SecureServingOptionsWithLoopback) ApplyTo(secureServingInfo **server.SecureServingInfo, loopbackClientConfig **rest.Config) error {\n\tif s == nil || s.SecureServingOptions == nil || secureServingInfo == nil {\n\t\treturn nil\n\t}\n\n\tif err := s.SecureServingOptions.ApplyTo(secureServingInfo); err != nil {\n\t\treturn err\n\t}\n\n\tif *secureServingInfo == nil || loopbackClientConfig == nil {\n\t\treturn nil\n\t}\n\n\t// create self-signed cert+key with the fake server.LoopbackClientServerNameOverride and\n\t// let the server return it when the loopback client connects.\n\tcertPem, keyPem, err := certutil.GenerateSelfSignedCertKey(server.LoopbackClientServerNameOverride, nil, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to generate self-signed certificate for loopback connection: %v\", err)\n\t}\n\tcertProvider, err := dynamiccertificates.NewStaticSNICertKeyContent(\"self-signed loopback\", certPem, keyPem, server.LoopbackClientServerNameOverride)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to generate self-signed certificate for loopback connection: %v\", err)\n\t}\n\n\t// Write to the front of SNICerts so that this overrides any other certs with the same name\n\t(*secureServingInfo).SNICerts = append([]dynamiccertificates.SNICertKeyContentProvider{certProvider}, (*secureServingInfo).SNICerts...)\n\n\tsecureLoopbackClientConfig, err := (*secureServingInfo).NewLoopbackClientConfig(uuid.New().String(), certPem)\n\tswitch {\n\t// if we failed and there's no fallback loopback client config, we need to fail\n\tcase err != nil \u0026\u0026 *loopbackClientConfig == nil:\n\t\t(*secureServingInfo).SNICerts = (*secureServingInfo).SNICerts[1:]\n\t\treturn err\n\n\t// if we failed, but we already have a fallback loopback client config (usually insecure), allow it\n\tcase err != nil \u0026\u0026 *loopbackClientConfig != nil:\n\n\tdefault:\n\t\t*loopbackClientConfig = secureLoopbackClientConfig\n\t}\n\n\treturn nil\n}","line":{"from":38,"to":81}} {"id":100018317,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/server/options/tracing.go","code":"func init() {\n\tinstall.Install(cfgScheme)\n}","line":{"from":51,"to":53}} {"id":100018318,"name":"NewTracingOptions","signature":"func NewTracingOptions() *TracingOptions","file":"staging/src/k8s.io/apiserver/pkg/server/options/tracing.go","code":"// NewTracingOptions creates a new instance of TracingOptions\nfunc NewTracingOptions() *TracingOptions {\n\treturn \u0026TracingOptions{}\n}","line":{"from":62,"to":65}} {"id":100018319,"name":"AddFlags","signature":"func (o *TracingOptions) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/apiserver/pkg/server/options/tracing.go","code":"// AddFlags adds flags related to tracing to the specified FlagSet\nfunc (o *TracingOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.StringVar(\u0026o.ConfigFile, \"tracing-config-file\", o.ConfigFile,\n\t\t\"File with apiserver tracing configuration.\")\n}","line":{"from":67,"to":75}} {"id":100018320,"name":"ApplyTo","signature":"func (o *TracingOptions) ApplyTo(es *egressselector.EgressSelector, c *server.Config) error","file":"staging/src/k8s.io/apiserver/pkg/server/options/tracing.go","code":"// ApplyTo fills up Tracing config with options.\nfunc (o *TracingOptions) ApplyTo(es *egressselector.EgressSelector, c *server.Config) error {\n\tif o == nil || o.ConfigFile == \"\" {\n\t\treturn nil\n\t}\n\tif !feature.DefaultFeatureGate.Enabled(features.APIServerTracing) {\n\t\treturn fmt.Errorf(\"APIServerTracing feature is not enabled, but tracing config file was provided\")\n\t}\n\n\ttraceConfig, err := ReadTracingConfiguration(o.ConfigFile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to read tracing config: %v\", err)\n\t}\n\n\terrs := tracingapi.ValidateTracingConfiguration(traceConfig, feature.DefaultFeatureGate, nil)\n\tif len(errs) \u003e 0 {\n\t\treturn fmt.Errorf(\"failed to validate tracing configuration: %v\", errs.ToAggregate())\n\t}\n\n\topts := []otlptracegrpc.Option{}\n\tif es != nil {\n\t\t// Only use the egressselector dialer if egressselector is enabled.\n\t\t// Endpoint is on the \"ControlPlane\" network\n\t\tegressDialer, err := es.Lookup(egressselector.ControlPlane.AsNetworkContext())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif egressDialer != nil {\n\t\t\totelDialer := func(ctx context.Context, addr string) (net.Conn, error) {\n\t\t\t\treturn egressDialer(ctx, \"tcp\", addr)\n\t\t\t}\n\t\t\topts = append(opts, otlptracegrpc.WithDialOption(grpc.WithContextDialer(otelDialer)))\n\t\t}\n\t}\n\n\tresourceOpts := []resource.Option{\n\t\tresource.WithAttributes(\n\t\t\tsemconv.ServiceNameKey.String(apiserverService),\n\t\t\tsemconv.ServiceInstanceIDKey.String(c.APIServerID),\n\t\t),\n\t}\n\ttp, err := tracing.NewProvider(context.Background(), traceConfig, opts, resourceOpts)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.TracerProvider = tp\n\tif c.LoopbackClientConfig != nil {\n\t\tc.LoopbackClientConfig.Wrap(tracing.WrapperFor(c.TracerProvider))\n\t}\n\treturn nil\n}","line":{"from":77,"to":127}} {"id":100018321,"name":"Validate","signature":"func (o *TracingOptions) Validate() (errs []error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/tracing.go","code":"// Validate verifies flags passed to TracingOptions.\nfunc (o *TracingOptions) Validate() (errs []error) {\n\tif o == nil || o.ConfigFile == \"\" {\n\t\treturn\n\t}\n\n\tif exists, err := path.Exists(path.CheckFollowSymlink, o.ConfigFile); !exists {\n\t\terrs = append(errs, fmt.Errorf(\"tracing-config-file %s does not exist\", o.ConfigFile))\n\t} else if err != nil {\n\t\terrs = append(errs, fmt.Errorf(\"error checking if tracing-config-file %s exists: %v\", o.ConfigFile, err))\n\t}\n\treturn\n}","line":{"from":129,"to":141}} {"id":100018322,"name":"ReadTracingConfiguration","signature":"func ReadTracingConfiguration(configFilePath string) (*tracingapi.TracingConfiguration, error)","file":"staging/src/k8s.io/apiserver/pkg/server/options/tracing.go","code":"// ReadTracingConfiguration reads the tracing configuration from a file\nfunc ReadTracingConfiguration(configFilePath string) (*tracingapi.TracingConfiguration, error) {\n\tif configFilePath == \"\" {\n\t\treturn nil, fmt.Errorf(\"tracing config file was empty\")\n\t}\n\tdata, err := ioutil.ReadFile(configFilePath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to read tracing configuration from %q: %v\", configFilePath, err)\n\t}\n\tinternalConfig := \u0026apiserver.TracingConfiguration{}\n\t// this handles json/yaml/whatever, and decodes all registered version to the internal version\n\tif err := runtime.DecodeInto(codecs.UniversalDecoder(), data, internalConfig); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to decode tracing configuration data: %v\", err)\n\t}\n\treturn \u0026internalConfig.TracingConfiguration, nil\n}","line":{"from":143,"to":158}} {"id":100018323,"name":"RegisterAllAdmissionPlugins","signature":"func RegisterAllAdmissionPlugins(plugins *admission.Plugins)","file":"staging/src/k8s.io/apiserver/pkg/server/plugins.go","code":"// RegisterAllAdmissionPlugins registers all admission plugins\nfunc RegisterAllAdmissionPlugins(plugins *admission.Plugins) {\n\tlifecycle.Register(plugins)\n\tvalidatingwebhook.Register(plugins)\n\tmutatingwebhook.Register(plugins)\n\tvalidatingadmissionpolicy.Register(plugins)\n}","line":{"from":28,"to":34}} {"id":100018324,"name":"MergeResourceEncodingConfigs","signature":"func MergeResourceEncodingConfigs(","file":"staging/src/k8s.io/apiserver/pkg/server/resourceconfig/helpers.go","code":"// MergeResourceEncodingConfigs merges the given defaultResourceConfig with specific GroupVersionResource overrides.\nfunc MergeResourceEncodingConfigs(\n\tdefaultResourceEncoding *serverstore.DefaultResourceEncodingConfig,\n\tresourceEncodingOverrides []schema.GroupVersionResource,\n) *serverstore.DefaultResourceEncodingConfig {\n\tresourceEncodingConfig := defaultResourceEncoding\n\tfor _, gvr := range resourceEncodingOverrides {\n\t\tresourceEncodingConfig.SetResourceEncoding(gvr.GroupResource(), gvr.GroupVersion(),\n\t\t\tschema.GroupVersion{Group: gvr.Group, Version: runtime.APIVersionInternal})\n\t}\n\treturn resourceEncodingConfig\n}","line":{"from":41,"to":52}} {"id":100018325,"name":"MergeAPIResourceConfigs","signature":"func MergeAPIResourceConfigs(","file":"staging/src/k8s.io/apiserver/pkg/server/resourceconfig/helpers.go","code":"// MergeAPIResourceConfigs merges the given defaultAPIResourceConfig with the given resourceConfigOverrides.\n// Exclude the groups not registered in registry, and check if version is\n// not registered in group, then it will fail.\nfunc MergeAPIResourceConfigs(\n\tdefaultAPIResourceConfig *serverstore.ResourceConfig,\n\tresourceConfigOverrides cliflag.ConfigurationMap,\n\tregistry GroupVersionRegistry,\n) (*serverstore.ResourceConfig, error) {\n\tresourceConfig := defaultAPIResourceConfig\n\toverrides := resourceConfigOverrides\n\n\tfor _, flag := range groupVersionMatchersOrder {\n\t\tif value, ok := overrides[flag]; ok {\n\t\t\tif value == \"false\" {\n\t\t\t\tresourceConfig.DisableMatchingVersions(groupVersionMatchers[flag])\n\t\t\t} else if value == \"true\" {\n\t\t\t\tresourceConfig.EnableMatchingVersions(groupVersionMatchers[flag])\n\t\t\t} else {\n\t\t\t\treturn nil, fmt.Errorf(\"invalid value %v=%v\", flag, value)\n\t\t\t}\n\t\t}\n\t}\n\n\ttype versionEnablementPreference struct {\n\t\tkey string\n\t\tenabled bool\n\t\tgroupVersion schema.GroupVersion\n\t}\n\ttype resourceEnablementPreference struct {\n\t\tkey string\n\t\tenabled bool\n\t\tgroupVersionResource schema.GroupVersionResource\n\t}\n\tversionPreferences := []versionEnablementPreference{}\n\tresourcePreferences := []resourceEnablementPreference{}\n\n\t// \"\u003cresourceSpecifier\u003e={true|false} allows users to enable/disable API.\n\t// This takes preference over api/all, if specified.\n\t// Iterate through all group/version overrides specified in runtimeConfig.\n\tfor key := range overrides {\n\t\t// Have already handled them above. Can skip them here.\n\t\tif _, ok := groupVersionMatchers[key]; ok {\n\t\t\tcontinue\n\t\t}\n\n\t\ttokens := strings.Split(key, \"/\")\n\t\tif len(tokens) \u003c 2 || len(tokens) \u003e 3 {\n\t\t\tcontinue\n\t\t}\n\t\tgroupVersionString := tokens[0] + \"/\" + tokens[1]\n\t\tgroupVersion, err := schema.ParseGroupVersion(groupVersionString)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid key %s\", key)\n\t\t}\n\n\t\t// Exclude group not registered into the registry.\n\t\tif !registry.IsGroupRegistered(groupVersion.Group) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Verify that the groupVersion is registered into registry.\n\t\tif !registry.IsVersionRegistered(groupVersion) {\n\t\t\treturn nil, fmt.Errorf(\"group version %s that has not been registered\", groupVersion.String())\n\t\t}\n\t\tenabled, err := getRuntimeConfigValue(overrides, key, false)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tswitch len(tokens) {\n\t\tcase 2:\n\t\t\tversionPreferences = append(versionPreferences, versionEnablementPreference{\n\t\t\t\tkey: key,\n\t\t\t\tenabled: enabled,\n\t\t\t\tgroupVersion: groupVersion,\n\t\t\t})\n\t\tcase 3:\n\t\t\tif strings.ToLower(tokens[2]) != tokens[2] {\n\t\t\t\treturn nil, fmt.Errorf(\"invalid key %v: group/version/resource and resource is always lowercase plural, not %q\", key, tokens[2])\n\t\t\t}\n\t\t\tresourcePreferences = append(resourcePreferences, resourceEnablementPreference{\n\t\t\t\tkey: key,\n\t\t\t\tenabled: enabled,\n\t\t\t\tgroupVersionResource: groupVersion.WithResource(tokens[2]),\n\t\t\t})\n\t\t}\n\t}\n\n\t// apply version preferences first, so that we can remove the hardcoded resource preferences that are being overridden\n\tfor _, versionPreference := range versionPreferences {\n\t\tif versionPreference.enabled {\n\t\t\t// enable the groupVersion for \"group/version=true\"\n\t\t\tresourceConfig.EnableVersions(versionPreference.groupVersion)\n\n\t\t} else {\n\t\t\t// disable the groupVersion only for \"group/version=false\"\n\t\t\tresourceConfig.DisableVersions(versionPreference.groupVersion)\n\t\t}\n\t}\n\n\t// apply resource preferences last, so they have the highest priority\n\tfor _, resourcePreference := range resourcePreferences {\n\t\tif resourcePreference.enabled {\n\t\t\t// enable the resource for \"group/version/resource=true\"\n\t\t\tresourceConfig.EnableResources(resourcePreference.groupVersionResource)\n\t\t} else {\n\t\t\tresourceConfig.DisableResources(resourcePreference.groupVersionResource)\n\t\t}\n\t}\n\n\treturn resourceConfig, nil\n}","line":{"from":81,"to":192}} {"id":100018326,"name":"getRuntimeConfigValue","signature":"func getRuntimeConfigValue(overrides cliflag.ConfigurationMap, apiKey string, defaultValue bool) (bool, error)","file":"staging/src/k8s.io/apiserver/pkg/server/resourceconfig/helpers.go","code":"func getRuntimeConfigValue(overrides cliflag.ConfigurationMap, apiKey string, defaultValue bool) (bool, error) {\n\tflagValue, ok := overrides[apiKey]\n\tif ok {\n\t\tif flagValue == \"\" {\n\t\t\treturn true, nil\n\t\t}\n\t\tboolValue, err := strconv.ParseBool(flagValue)\n\t\tif err != nil {\n\t\t\treturn false, fmt.Errorf(\"invalid value of %s: %s, err: %v\", apiKey, flagValue, err)\n\t\t}\n\t\treturn boolValue, nil\n\t}\n\treturn defaultValue, nil\n}","line":{"from":194,"to":207}} {"id":100018327,"name":"ParseGroups","signature":"func ParseGroups(resourceConfig cliflag.ConfigurationMap) ([]string, error)","file":"staging/src/k8s.io/apiserver/pkg/server/resourceconfig/helpers.go","code":"// ParseGroups takes in resourceConfig and returns parsed groups.\nfunc ParseGroups(resourceConfig cliflag.ConfigurationMap) ([]string, error) {\n\tgroups := []string{}\n\tfor key := range resourceConfig {\n\t\tif _, ok := groupVersionMatchers[key]; ok {\n\t\t\tcontinue\n\t\t}\n\t\ttokens := strings.Split(key, \"/\")\n\t\tif len(tokens) != 2 \u0026\u0026 len(tokens) != 3 {\n\t\t\treturn groups, fmt.Errorf(\"runtime-config invalid key %s\", key)\n\t\t}\n\t\tgroupVersionString := tokens[0] + \"/\" + tokens[1]\n\t\tgroupVersion, err := schema.ParseGroupVersion(groupVersionString)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"runtime-config invalid key %s\", key)\n\t\t}\n\t\tgroups = append(groups, groupVersion.Group)\n\t}\n\n\treturn groups, nil\n}","line":{"from":209,"to":229}} {"id":100018328,"name":"NewDebugSocket","signature":"func NewDebugSocket(path string) *DebugSocket","file":"staging/src/k8s.io/apiserver/pkg/server/routes/debugsocket.go","code":"// NewDebugSocket creates a new DebugSocket for the given path.\nfunc NewDebugSocket(path string) *DebugSocket {\n\treturn \u0026DebugSocket{\n\t\tpath: path,\n\t\tmux: http.NewServeMux(),\n\t}\n}","line":{"from":34,"to":40}} {"id":100018329,"name":"InstallProfiling","signature":"func (s *DebugSocket) InstallProfiling()","file":"staging/src/k8s.io/apiserver/pkg/server/routes/debugsocket.go","code":"// InstallProfiling installs profiling endpoints in the socket.\nfunc (s *DebugSocket) InstallProfiling() {\n\ts.mux.HandleFunc(\"/debug/pprof\", redirectTo(\"/debug/pprof/\"))\n\ts.mux.HandleFunc(\"/debug/pprof/\", pprof.Index)\n\ts.mux.HandleFunc(\"/debug/pprof/cmdline\", pprof.Cmdline)\n\ts.mux.HandleFunc(\"/debug/pprof/profile\", pprof.Profile)\n\ts.mux.HandleFunc(\"/debug/pprof/symbol\", pprof.Symbol)\n\ts.mux.HandleFunc(\"/debug/pprof/trace\", pprof.Trace)\n}","line":{"from":42,"to":50}} {"id":100018330,"name":"InstallDebugFlag","signature":"func (s *DebugSocket) InstallDebugFlag(flag string, handler func(http.ResponseWriter, *http.Request))","file":"staging/src/k8s.io/apiserver/pkg/server/routes/debugsocket.go","code":"// InstallDebugFlag installs debug flag endpoints in the socket.\nfunc (s *DebugSocket) InstallDebugFlag(flag string, handler func(http.ResponseWriter, *http.Request)) {\n\tf := DebugFlags{}\n\ts.mux.HandleFunc(\"/debug/flags\", f.Index)\n\ts.mux.HandleFunc(\"/debug/flags/\", f.Index)\n\n\turl := path.Join(\"/debug/flags\", flag)\n\ts.mux.HandleFunc(url, handler)\n\n\tf.addFlag(flag)\n}","line":{"from":52,"to":62}} {"id":100018331,"name":"Run","signature":"func (s *DebugSocket) Run(stopCh \u003c-chan struct{}) error","file":"staging/src/k8s.io/apiserver/pkg/server/routes/debugsocket.go","code":"// Run starts the server and waits for stopCh to be closed to close the server.\nfunc (s *DebugSocket) Run(stopCh \u003c-chan struct{}) error {\n\tif err := os.Remove(s.path); err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"failed to remove (%v): %v\", s.path, err)\n\t}\n\n\tl, err := net.Listen(\"unix\", s.path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"listen error (%v): %v\", s.path, err)\n\t}\n\tdefer l.Close()\n\n\tsrv := http.Server{Handler: s.mux}\n\tgo func() {\n\t\t\u003c-stopCh\n\t\tsrv.Close()\n\t}()\n\treturn srv.Serve(l)\n}","line":{"from":64,"to":82}} {"id":100018332,"name":"Install","signature":"func (f DebugFlags) Install(c *mux.PathRecorderMux, flag string, handler func(http.ResponseWriter, *http.Request))","file":"staging/src/k8s.io/apiserver/pkg/server/routes/flags.go","code":"// Install registers the APIServer's flags handler.\nfunc (f DebugFlags) Install(c *mux.PathRecorderMux, flag string, handler func(http.ResponseWriter, *http.Request)) {\n\tc.UnlistedHandle(\"/debug/flags\", http.HandlerFunc(f.Index))\n\tc.UnlistedHandlePrefix(\"/debug/flags/\", http.HandlerFunc(f.Index))\n\n\turl := path.Join(\"/debug/flags\", flag)\n\tc.UnlistedHandleFunc(url, handler)\n\n\tf.addFlag(flag)\n}","line":{"from":41,"to":50}} {"id":100018333,"name":"Index","signature":"func (f DebugFlags) Index(w http.ResponseWriter, r *http.Request)","file":"staging/src/k8s.io/apiserver/pkg/server/routes/flags.go","code":"// Index responds with the `/debug/flags` request.\n// For example, \"/debug/flags/v\" serves the \"--v\" flag.\n// Index responds to a request for \"/debug/flags/\" with an HTML page\n// listing the available flags.\nfunc (f DebugFlags) Index(w http.ResponseWriter, r *http.Request) {\n\tlock.RLock()\n\tdefer lock.RUnlock()\n\tif err := indexTmpl.Execute(w, registeredFlags); err != nil {\n\t\tklog.Error(err)\n\t}\n}","line":{"from":52,"to":62}} {"id":100018334,"name":"addFlag","signature":"func (f DebugFlags) addFlag(flag string)","file":"staging/src/k8s.io/apiserver/pkg/server/routes/flags.go","code":"func (f DebugFlags) addFlag(flag string) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tregisteredFlags[flag] = debugFlag{flag}\n}","line":{"from":87,"to":91}} {"id":100018335,"name":"StringFlagPutHandler","signature":"func StringFlagPutHandler(setter StringFlagSetterFunc) http.HandlerFunc","file":"staging/src/k8s.io/apiserver/pkg/server/routes/flags.go","code":"// StringFlagPutHandler wraps an http Handler to set string type flag.\nfunc StringFlagPutHandler(setter StringFlagSetterFunc) http.HandlerFunc {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tswitch {\n\t\tcase req.Method == \"PUT\":\n\t\t\tbody, err := ioutil.ReadAll(req.Body)\n\t\t\tif err != nil {\n\t\t\t\twritePlainText(http.StatusBadRequest, \"error reading request body: \"+err.Error(), w)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdefer req.Body.Close()\n\t\t\tresponse, err := setter(string(body))\n\t\t\tif err != nil {\n\t\t\t\twritePlainText(http.StatusBadRequest, err.Error(), w)\n\t\t\t\treturn\n\t\t\t}\n\t\t\twritePlainText(http.StatusOK, response, w)\n\t\t\treturn\n\t\tdefault:\n\t\t\twritePlainText(http.StatusNotAcceptable, \"unsupported http method\", w)\n\t\t\treturn\n\t\t}\n\t})\n}","line":{"from":96,"to":119}} {"id":100018336,"name":"writePlainText","signature":"func writePlainText(statusCode int, text string, w http.ResponseWriter)","file":"staging/src/k8s.io/apiserver/pkg/server/routes/flags.go","code":"// writePlainText renders a simple string response.\nfunc writePlainText(statusCode int, text string, w http.ResponseWriter) {\n\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\tw.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\tw.WriteHeader(statusCode)\n\tfmt.Fprintln(w, text)\n}","line":{"from":121,"to":127}} {"id":100018337,"name":"ListedPaths","signature":"func (p ListedPathProviders) ListedPaths() []string","file":"staging/src/k8s.io/apiserver/pkg/server/routes/index.go","code":"// ListedPaths unions and sorts the included paths.\nfunc (p ListedPathProviders) ListedPaths() []string {\n\tret := sets.String{}\n\tfor _, provider := range p {\n\t\tfor _, path := range provider.ListedPaths() {\n\t\t\tret.Insert(path)\n\t\t}\n\t}\n\n\treturn ret.List()\n}","line":{"from":37,"to":47}} {"id":100018338,"name":"Install","signature":"func (i Index) Install(pathProvider ListedPathProvider, mux *mux.PathRecorderMux)","file":"staging/src/k8s.io/apiserver/pkg/server/routes/index.go","code":"// Install adds the Index webservice to the given mux.\nfunc (i Index) Install(pathProvider ListedPathProvider, mux *mux.PathRecorderMux) {\n\thandler := IndexLister{StatusCode: http.StatusOK, PathProvider: pathProvider}\n\n\tmux.UnlistedHandle(\"/\", handler)\n\tmux.UnlistedHandle(\"/index.html\", handler)\n}","line":{"from":52,"to":58}} {"id":100018339,"name":"ServeHTTP","signature":"func (i IndexLister) ServeHTTP(w http.ResponseWriter, r *http.Request)","file":"staging/src/k8s.io/apiserver/pkg/server/routes/index.go","code":"// ServeHTTP serves the available paths.\nfunc (i IndexLister) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tresponsewriters.WriteRawJSON(i.StatusCode, metav1.RootPaths{Paths: i.PathProvider.ListedPaths()}, w)\n}","line":{"from":66,"to":69}} {"id":100018340,"name":"Install","signature":"func (m DefaultMetrics) Install(c *mux.PathRecorderMux)","file":"staging/src/k8s.io/apiserver/pkg/server/routes/metrics.go","code":"// Install adds the DefaultMetrics handler\nfunc (m DefaultMetrics) Install(c *mux.PathRecorderMux) {\n\tregister()\n\tc.Handle(\"/metrics\", legacyregistry.Handler())\n}","line":{"from":31,"to":35}} {"id":100018341,"name":"Install","signature":"func (m MetricsWithReset) Install(c *mux.PathRecorderMux)","file":"staging/src/k8s.io/apiserver/pkg/server/routes/metrics.go","code":"// Install adds the MetricsWithReset handler\nfunc (m MetricsWithReset) Install(c *mux.PathRecorderMux) {\n\tregister()\n\tc.Handle(\"/metrics\", legacyregistry.HandlerWithReset())\n}","line":{"from":41,"to":45}} {"id":100018342,"name":"register","signature":"func register()","file":"staging/src/k8s.io/apiserver/pkg/server/routes/metrics.go","code":"// register apiserver and etcd metrics\nfunc register() {\n\tapimetrics.Register()\n\tcachermetrics.Register()\n\tetcd3metrics.Register()\n\tflowcontrolmetrics.Register()\n}","line":{"from":47,"to":53}} {"id":100018343,"name":"InstallV2","signature":"func (oa OpenAPI) InstallV2(c *restful.Container, mux *mux.PathRecorderMux) (*handler.OpenAPIService, *spec.Swagger)","file":"staging/src/k8s.io/apiserver/pkg/server/routes/openapi.go","code":"// Install adds the SwaggerUI webservice to the given mux.\nfunc (oa OpenAPI) InstallV2(c *restful.Container, mux *mux.PathRecorderMux) (*handler.OpenAPIService, *spec.Swagger) {\n\tspec, err := builder2.BuildOpenAPISpecFromRoutes(restfuladapter.AdaptWebServices(c.RegisteredWebServices()), oa.Config)\n\tif err != nil {\n\t\tklog.Fatalf(\"Failed to build open api spec for root: %v\", err)\n\t}\n\tspec.Definitions = handler.PruneDefaults(spec.Definitions)\n\topenAPIVersionedService := handler.NewOpenAPIService(spec)\n\terr = openAPIVersionedService.RegisterOpenAPIVersionedService(\"/openapi/v2\", mux)\n\tif err != nil {\n\t\tklog.Fatalf(\"Failed to register versioned open api spec for root: %v\", err)\n\t}\n\n\treturn openAPIVersionedService, spec\n}","line":{"from":38,"to":52}} {"id":100018344,"name":"InstallV3","signature":"func (oa OpenAPI) InstallV3(c *restful.Container, mux *mux.PathRecorderMux) *handler3.OpenAPIService","file":"staging/src/k8s.io/apiserver/pkg/server/routes/openapi.go","code":"// InstallV3 adds the static group/versions defined in the RegisteredWebServices to the OpenAPI v3 spec\nfunc (oa OpenAPI) InstallV3(c *restful.Container, mux *mux.PathRecorderMux) *handler3.OpenAPIService {\n\topenAPIVersionedService := handler3.NewOpenAPIService()\n\terr := openAPIVersionedService.RegisterOpenAPIV3VersionedService(\"/openapi/v3\", mux)\n\tif err != nil {\n\t\tklog.Fatalf(\"Failed to register versioned open api spec for root: %v\", err)\n\t}\n\n\tgrouped := make(map[string][]*restful.WebService)\n\n\tfor _, t := range c.RegisteredWebServices() {\n\t\t// Strip the \"/\" prefix from the name\n\t\tgvName := t.RootPath()[1:]\n\t\tgrouped[gvName] = []*restful.WebService{t}\n\t}\n\n\tfor gv, ws := range grouped {\n\t\tspec, err := builder3.BuildOpenAPISpecFromRoutes(restfuladapter.AdaptWebServices(ws), oa.Config)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to build OpenAPI v3 for group %s, %q\", gv, err)\n\n\t\t}\n\t\topenAPIVersionedService.UpdateGroupVersion(gv, spec)\n\t}\n\treturn openAPIVersionedService\n}","line":{"from":54,"to":79}} {"id":100018345,"name":"Install","signature":"func (d Profiling) Install(c *mux.PathRecorderMux)","file":"staging/src/k8s.io/apiserver/pkg/server/routes/profiling.go","code":"// Install adds the Profiling webservice to the given mux.\nfunc (d Profiling) Install(c *mux.PathRecorderMux) {\n\tc.UnlistedHandleFunc(\"/debug/pprof\", redirectTo(\"/debug/pprof/\"))\n\tc.UnlistedHandlePrefix(\"/debug/pprof/\", http.HandlerFunc(pprof.Index))\n\tc.UnlistedHandleFunc(\"/debug/pprof/profile\", pprof.Profile)\n\tc.UnlistedHandleFunc(\"/debug/pprof/symbol\", pprof.Symbol)\n\tc.UnlistedHandleFunc(\"/debug/pprof/trace\", pprof.Trace)\n}","line":{"from":29,"to":36}} {"id":100018346,"name":"redirectTo","signature":"func redirectTo(to string) func(http.ResponseWriter, *http.Request)","file":"staging/src/k8s.io/apiserver/pkg/server/routes/profiling.go","code":"// redirectTo redirects request to a certain destination.\nfunc redirectTo(to string) func(http.ResponseWriter, *http.Request) {\n\treturn func(rw http.ResponseWriter, req *http.Request) {\n\t\thttp.Redirect(rw, req, to, http.StatusFound)\n\t}\n}","line":{"from":38,"to":43}} {"id":100018347,"name":"Install","signature":"func (v Version) Install(c *restful.Container)","file":"staging/src/k8s.io/apiserver/pkg/server/routes/version.go","code":"// Install registers the APIServer's `/version` handler.\nfunc (v Version) Install(c *restful.Container) {\n\tif v.Version == nil {\n\t\treturn\n\t}\n\n\t// Set up a service to return the git code version.\n\tversionWS := new(restful.WebService)\n\tversionWS.Path(\"/version\")\n\tversionWS.Doc(\"git code version from which this is built\")\n\tversionWS.Route(\n\t\tversionWS.GET(\"/\").To(v.handleVersion).\n\t\t\tDoc(\"get the code version\").\n\t\t\tOperation(\"getCodeVersion\").\n\t\t\tProduces(restful.MIME_JSON).\n\t\t\tConsumes(restful.MIME_JSON).\n\t\t\tWrites(version.Info{}))\n\n\tc.Add(versionWS)\n}","line":{"from":33,"to":52}} {"id":100018348,"name":"handleVersion","signature":"func (v Version) handleVersion(req *restful.Request, resp *restful.Response)","file":"staging/src/k8s.io/apiserver/pkg/server/routes/version.go","code":"// handleVersion writes the server's version information.\nfunc (v Version) handleVersion(req *restful.Request, resp *restful.Response) {\n\tresponsewriters.WriteRawJSON(http.StatusOK, *v.Version, resp.ResponseWriter)\n}","line":{"from":54,"to":57}} {"id":100018349,"name":"tlsConfig","signature":"func (s *SecureServingInfo) tlsConfig(stopCh \u003c-chan struct{}) (*tls.Config, error)","file":"staging/src/k8s.io/apiserver/pkg/server/secure_serving.go","code":"// tlsConfig produces the tls.Config to serve with.\nfunc (s *SecureServingInfo) tlsConfig(stopCh \u003c-chan struct{}) (*tls.Config, error) {\n\ttlsConfig := \u0026tls.Config{\n\t\t// Can't use SSLv3 because of POODLE and BEAST\n\t\t// Can't use TLSv1.0 because of POODLE and BEAST using CBC cipher\n\t\t// Can't use TLSv1.1 because of RC4 cipher usage\n\t\tMinVersion: tls.VersionTLS12,\n\t\t// enable HTTP2 for go's 1.7 HTTP Server\n\t\tNextProtos: []string{\"h2\", \"http/1.1\"},\n\t}\n\n\t// these are static aspects of the tls.Config\n\tif s.DisableHTTP2 {\n\t\tklog.Info(\"Forcing use of http/1.1 only\")\n\t\ttlsConfig.NextProtos = []string{\"http/1.1\"}\n\t}\n\tif s.MinTLSVersion \u003e 0 {\n\t\ttlsConfig.MinVersion = s.MinTLSVersion\n\t}\n\tif len(s.CipherSuites) \u003e 0 {\n\t\ttlsConfig.CipherSuites = s.CipherSuites\n\t\tinsecureCiphers := flag.InsecureTLSCiphers()\n\t\tfor i := 0; i \u003c len(s.CipherSuites); i++ {\n\t\t\tfor cipherName, cipherID := range insecureCiphers {\n\t\t\t\tif s.CipherSuites[i] == cipherID {\n\t\t\t\t\tklog.Warningf(\"Use of insecure cipher '%s' detected.\", cipherName)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif s.ClientCA != nil {\n\t\t// Populate PeerCertificates in requests, but don't reject connections without certificates\n\t\t// This allows certificates to be validated by authenticators, while still allowing other auth types\n\t\ttlsConfig.ClientAuth = tls.RequestClientCert\n\t}\n\n\tif s.ClientCA != nil || s.Cert != nil || len(s.SNICerts) \u003e 0 {\n\t\tdynamicCertificateController := dynamiccertificates.NewDynamicServingCertificateController(\n\t\t\ttlsConfig,\n\t\t\ts.ClientCA,\n\t\t\ts.Cert,\n\t\t\ts.SNICerts,\n\t\t\tnil, // TODO see how to plumb an event recorder down in here. For now this results in simply klog messages.\n\t\t)\n\n\t\tif s.ClientCA != nil {\n\t\t\ts.ClientCA.AddListener(dynamicCertificateController)\n\t\t}\n\t\tif s.Cert != nil {\n\t\t\ts.Cert.AddListener(dynamicCertificateController)\n\t\t}\n\t\t// generate a context from stopCh. This is to avoid modifying files which are relying on apiserver\n\t\t// TODO: See if we can pass ctx to the current method\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tgo func() {\n\t\t\tselect {\n\t\t\tcase \u003c-stopCh:\n\t\t\t\tcancel() // stopCh closed, so cancel our context\n\t\t\tcase \u003c-ctx.Done():\n\t\t\t}\n\t\t}()\n\t\t// start controllers if possible\n\t\tif controller, ok := s.ClientCA.(dynamiccertificates.ControllerRunner); ok {\n\t\t\t// runonce to try to prime data. If this fails, it's ok because we fail closed.\n\t\t\t// Files are required to be populated already, so this is for convenience.\n\t\t\tif err := controller.RunOnce(ctx); err != nil {\n\t\t\t\tklog.Warningf(\"Initial population of client CA failed: %v\", err)\n\t\t\t}\n\n\t\t\tgo controller.Run(ctx, 1)\n\t\t}\n\t\tif controller, ok := s.Cert.(dynamiccertificates.ControllerRunner); ok {\n\t\t\t// runonce to try to prime data. If this fails, it's ok because we fail closed.\n\t\t\t// Files are required to be populated already, so this is for convenience.\n\t\t\tif err := controller.RunOnce(ctx); err != nil {\n\t\t\t\tklog.Warningf(\"Initial population of default serving certificate failed: %v\", err)\n\t\t\t}\n\n\t\t\tgo controller.Run(ctx, 1)\n\t\t}\n\t\tfor _, sniCert := range s.SNICerts {\n\t\t\tsniCert.AddListener(dynamicCertificateController)\n\t\t\tif controller, ok := sniCert.(dynamiccertificates.ControllerRunner); ok {\n\t\t\t\t// runonce to try to prime data. If this fails, it's ok because we fail closed.\n\t\t\t\t// Files are required to be populated already, so this is for convenience.\n\t\t\t\tif err := controller.RunOnce(ctx); err != nil {\n\t\t\t\t\tklog.Warningf(\"Initial population of SNI serving certificate failed: %v\", err)\n\t\t\t\t}\n\n\t\t\t\tgo controller.Run(ctx, 1)\n\t\t\t}\n\t\t}\n\n\t\t// runonce to try to prime data. If this fails, it's ok because we fail closed.\n\t\t// Files are required to be populated already, so this is for convenience.\n\t\tif err := dynamicCertificateController.RunOnce(); err != nil {\n\t\t\tklog.Warningf(\"Initial population of dynamic certificates failed: %v\", err)\n\t\t}\n\t\tgo dynamicCertificateController.Run(1, stopCh)\n\n\t\ttlsConfig.GetConfigForClient = dynamicCertificateController.GetConfigForClient\n\t}\n\n\treturn tlsConfig, nil\n}","line":{"from":44,"to":149}} {"id":100018350,"name":"Serve","signature":"func (s *SecureServingInfo) Serve(handler http.Handler, shutdownTimeout time.Duration, stopCh \u003c-chan struct{}) (\u003c-chan struct{}, \u003c-chan struct{}, error)","file":"staging/src/k8s.io/apiserver/pkg/server/secure_serving.go","code":"// Serve runs the secure http server. It fails only if certificates cannot be loaded or the initial listen call fails.\n// The actual server loop (stoppable by closing stopCh) runs in a go routine, i.e. Serve does not block.\n// It returns a stoppedCh that is closed when all non-hijacked active requests have been processed.\n// It returns a listenerStoppedCh that is closed when the underlying http Server has stopped listening.\nfunc (s *SecureServingInfo) Serve(handler http.Handler, shutdownTimeout time.Duration, stopCh \u003c-chan struct{}) (\u003c-chan struct{}, \u003c-chan struct{}, error) {\n\tif s.Listener == nil {\n\t\treturn nil, nil, fmt.Errorf(\"listener must not be nil\")\n\t}\n\n\ttlsConfig, err := s.tlsConfig(stopCh)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tsecureServer := \u0026http.Server{\n\t\tAddr: s.Listener.Addr().String(),\n\t\tHandler: handler,\n\t\tMaxHeaderBytes: 1 \u003c\u003c 20,\n\t\tTLSConfig: tlsConfig,\n\n\t\tIdleTimeout: 90 * time.Second, // matches http.DefaultTransport keep-alive timeout\n\t\tReadHeaderTimeout: 32 * time.Second, // just shy of requestTimeoutUpperBound\n\t}\n\n\t// At least 99% of serialized resources in surveyed clusters were smaller than 256kb.\n\t// This should be big enough to accommodate most API POST requests in a single frame,\n\t// and small enough to allow a per connection buffer of this size multiplied by `MaxConcurrentStreams`.\n\tconst resourceBody99Percentile = 256 * 1024\n\n\thttp2Options := \u0026http2.Server{\n\t\tIdleTimeout: 90 * time.Second, // matches http.DefaultTransport keep-alive timeout\n\t}\n\n\t// shrink the per-stream buffer and max framesize from the 1MB default while still accommodating most API POST requests in a single frame\n\thttp2Options.MaxUploadBufferPerStream = resourceBody99Percentile\n\thttp2Options.MaxReadFrameSize = resourceBody99Percentile\n\n\t// use the overridden concurrent streams setting or make the default of 250 explicit so we can size MaxUploadBufferPerConnection appropriately\n\tif s.HTTP2MaxStreamsPerConnection \u003e 0 {\n\t\thttp2Options.MaxConcurrentStreams = uint32(s.HTTP2MaxStreamsPerConnection)\n\t} else {\n\t\thttp2Options.MaxConcurrentStreams = 250\n\t}\n\n\t// increase the connection buffer size from the 1MB default to handle the specified number of concurrent streams\n\thttp2Options.MaxUploadBufferPerConnection = http2Options.MaxUploadBufferPerStream * int32(http2Options.MaxConcurrentStreams)\n\n\tif !s.DisableHTTP2 {\n\t\t// apply settings to the server\n\t\tif err := http2.ConfigureServer(secureServer, http2Options); err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"error configuring http2: %v\", err)\n\t\t}\n\t}\n\n\t// use tlsHandshakeErrorWriter to handle messages of tls handshake error\n\ttlsErrorWriter := \u0026tlsHandshakeErrorWriter{os.Stderr}\n\ttlsErrorLogger := log.New(tlsErrorWriter, \"\", 0)\n\tsecureServer.ErrorLog = tlsErrorLogger\n\n\tklog.Infof(\"Serving securely on %s\", secureServer.Addr)\n\treturn RunServer(secureServer, s.Listener, shutdownTimeout, stopCh)\n}","line":{"from":151,"to":212}} {"id":100018351,"name":"RunServer","signature":"func RunServer(","file":"staging/src/k8s.io/apiserver/pkg/server/secure_serving.go","code":"// RunServer spawns a go-routine continuously serving until the stopCh is\n// closed.\n// It returns a stoppedCh that is closed when all non-hijacked active requests\n// have been processed.\n// This function does not block\n// TODO: make private when insecure serving is gone from the kube-apiserver\nfunc RunServer(\n\tserver *http.Server,\n\tln net.Listener,\n\tshutDownTimeout time.Duration,\n\tstopCh \u003c-chan struct{},\n) (\u003c-chan struct{}, \u003c-chan struct{}, error) {\n\tif ln == nil {\n\t\treturn nil, nil, fmt.Errorf(\"listener must not be nil\")\n\t}\n\n\t// Shutdown server gracefully.\n\tserverShutdownCh, listenerStoppedCh := make(chan struct{}), make(chan struct{})\n\tgo func() {\n\t\tdefer close(serverShutdownCh)\n\t\t\u003c-stopCh\n\t\tctx, cancel := context.WithTimeout(context.Background(), shutDownTimeout)\n\t\tserver.Shutdown(ctx)\n\t\tcancel()\n\t}()\n\n\tgo func() {\n\t\tdefer utilruntime.HandleCrash()\n\t\tdefer close(listenerStoppedCh)\n\n\t\tvar listener net.Listener\n\t\tlistener = tcpKeepAliveListener{ln}\n\t\tif server.TLSConfig != nil {\n\t\t\tlistener = tls.NewListener(listener, server.TLSConfig)\n\t\t}\n\n\t\terr := server.Serve(listener)\n\n\t\tmsg := fmt.Sprintf(\"Stopped listening on %s\", ln.Addr().String())\n\t\tselect {\n\t\tcase \u003c-stopCh:\n\t\t\tklog.Info(msg)\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"%s due to error: %v\", msg, err))\n\t\t}\n\t}()\n\n\treturn serverShutdownCh, listenerStoppedCh, nil\n}","line":{"from":214,"to":262}} {"id":100018352,"name":"Accept","signature":"func (ln tcpKeepAliveListener) Accept() (net.Conn, error)","file":"staging/src/k8s.io/apiserver/pkg/server/secure_serving.go","code":"func (ln tcpKeepAliveListener) Accept() (net.Conn, error) {\n\tc, err := ln.Listener.Accept()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif tc, ok := c.(*net.TCPConn); ok {\n\t\ttc.SetKeepAlive(true)\n\t\ttc.SetKeepAlivePeriod(defaultKeepAlivePeriod)\n\t}\n\treturn c, nil\n}","line":{"from":274,"to":284}} {"id":100018353,"name":"Write","signature":"func (w *tlsHandshakeErrorWriter) Write(p []byte) (int, error)","file":"staging/src/k8s.io/apiserver/pkg/server/secure_serving.go","code":"func (w *tlsHandshakeErrorWriter) Write(p []byte) (int, error) {\n\tif strings.Contains(string(p), tlsHandshakeErrorPrefix) {\n\t\tklog.V(5).Info(string(p))\n\t\tmetrics.TLSHandshakeErrors.Inc()\n\t\treturn len(p), nil\n\t}\n\n\t// for non tls handshake error, log it as usual\n\treturn w.out.Write(p)\n}","line":{"from":294,"to":303}} {"id":100018354,"name":"SetupSignalHandler","signature":"func SetupSignalHandler() \u003c-chan struct{}","file":"staging/src/k8s.io/apiserver/pkg/server/signal.go","code":"// SetupSignalHandler registered for SIGTERM and SIGINT. A stop channel is returned\n// which is closed on one of these signals. If a second signal is caught, the program\n// is terminated with exit code 1.\n// Only one of SetupSignalContext and SetupSignalHandler should be called, and only can\n// be called once.\nfunc SetupSignalHandler() \u003c-chan struct{} {\n\treturn SetupSignalContext().Done()\n}","line":{"from":28,"to":35}} {"id":100018355,"name":"SetupSignalContext","signature":"func SetupSignalContext() context.Context","file":"staging/src/k8s.io/apiserver/pkg/server/signal.go","code":"// SetupSignalContext is same as SetupSignalHandler, but a context.Context is returned.\n// Only one of SetupSignalContext and SetupSignalHandler should be called, and only can\n// be called once.\nfunc SetupSignalContext() context.Context {\n\tclose(onlyOneSignalHandler) // panics when called twice\n\n\tshutdownHandler = make(chan os.Signal, 2)\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tsignal.Notify(shutdownHandler, shutdownSignals...)\n\tgo func() {\n\t\t\u003c-shutdownHandler\n\t\tcancel()\n\t\t\u003c-shutdownHandler\n\t\tos.Exit(1) // second signal. Exit directly.\n\t}()\n\n\treturn ctx\n}","line":{"from":37,"to":55}} {"id":100018356,"name":"RequestShutdown","signature":"func RequestShutdown() bool","file":"staging/src/k8s.io/apiserver/pkg/server/signal.go","code":"// RequestShutdown emulates a received event that is considered as shutdown signal (SIGTERM/SIGINT)\n// This returns whether a handler was notified\nfunc RequestShutdown() bool {\n\tif shutdownHandler != nil {\n\t\tselect {\n\t\tcase shutdownHandler \u003c- shutdownSignals[0]:\n\t\t\treturn true\n\t\tdefault:\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":57,"to":69}} {"id":100018357,"name":"NewResourceConfig","signature":"func NewResourceConfig() *ResourceConfig","file":"staging/src/k8s.io/apiserver/pkg/server/storage/resource_config.go","code":"func NewResourceConfig() *ResourceConfig {\n\treturn \u0026ResourceConfig{GroupVersionConfigs: map[schema.GroupVersion]bool{}, ResourceConfigs: map[schema.GroupVersionResource]bool{}}\n}","line":{"from":36,"to":38}} {"id":100018358,"name":"DisableMatchingVersions","signature":"func (o *ResourceConfig) DisableMatchingVersions(matcher func(gv schema.GroupVersion) bool)","file":"staging/src/k8s.io/apiserver/pkg/server/storage/resource_config.go","code":"// DisableMatchingVersions disables all group/versions for which the matcher function returns true.\n// This will remove any preferences previously set on individual resources.\nfunc (o *ResourceConfig) DisableMatchingVersions(matcher func(gv schema.GroupVersion) bool) {\n\tfor version := range o.GroupVersionConfigs {\n\t\tif matcher(version) {\n\t\t\to.GroupVersionConfigs[version] = false\n\t\t\to.removeMatchingResourcePreferences(resourceMatcherForVersion(version))\n\t\t}\n\t}\n}","line":{"from":40,"to":49}} {"id":100018359,"name":"EnableMatchingVersions","signature":"func (o *ResourceConfig) EnableMatchingVersions(matcher func(gv schema.GroupVersion) bool)","file":"staging/src/k8s.io/apiserver/pkg/server/storage/resource_config.go","code":"// EnableMatchingVersions enables all group/versions for which the matcher function returns true.\n// This will remove any preferences previously set on individual resources.\nfunc (o *ResourceConfig) EnableMatchingVersions(matcher func(gv schema.GroupVersion) bool) {\n\tfor version := range o.GroupVersionConfigs {\n\t\tif matcher(version) {\n\t\t\to.GroupVersionConfigs[version] = true\n\t\t\to.removeMatchingResourcePreferences(resourceMatcherForVersion(version))\n\t\t}\n\t}\n}","line":{"from":51,"to":60}} {"id":100018360,"name":"resourceMatcherForVersion","signature":"func resourceMatcherForVersion(gv schema.GroupVersion) func(gvr schema.GroupVersionResource) bool","file":"staging/src/k8s.io/apiserver/pkg/server/storage/resource_config.go","code":"// resourceMatcherForVersion matches resources in the specified version\nfunc resourceMatcherForVersion(gv schema.GroupVersion) func(gvr schema.GroupVersionResource) bool {\n\treturn func(gvr schema.GroupVersionResource) bool {\n\t\treturn gv == gvr.GroupVersion()\n\t}\n}","line":{"from":62,"to":67}} {"id":100018361,"name":"removeMatchingResourcePreferences","signature":"func (o *ResourceConfig) removeMatchingResourcePreferences(matcher func(gvr schema.GroupVersionResource) bool)","file":"staging/src/k8s.io/apiserver/pkg/server/storage/resource_config.go","code":"// removeMatchingResourcePreferences removes individual resource preferences that match. This is useful when an override of a version or level enablement should\n// override the previously individual preferences.\nfunc (o *ResourceConfig) removeMatchingResourcePreferences(matcher func(gvr schema.GroupVersionResource) bool) {\n\tkeysToRemove := []schema.GroupVersionResource{}\n\tfor k := range o.ResourceConfigs {\n\t\tif matcher(k) {\n\t\t\tkeysToRemove = append(keysToRemove, k)\n\t\t}\n\t}\n\tfor _, k := range keysToRemove {\n\t\tdelete(o.ResourceConfigs, k)\n\t}\n}","line":{"from":69,"to":81}} {"id":100018362,"name":"DisableVersions","signature":"func (o *ResourceConfig) DisableVersions(versions ...schema.GroupVersion)","file":"staging/src/k8s.io/apiserver/pkg/server/storage/resource_config.go","code":"// DisableVersions disables the versions entirely.\n// This will remove any preferences previously set on individual resources.\nfunc (o *ResourceConfig) DisableVersions(versions ...schema.GroupVersion) {\n\tfor _, version := range versions {\n\t\to.GroupVersionConfigs[version] = false\n\n\t\t// a preference about a version takes priority over the previously set resources\n\t\to.removeMatchingResourcePreferences(resourceMatcherForVersion(version))\n\t}\n}","line":{"from":83,"to":92}} {"id":100018363,"name":"EnableVersions","signature":"func (o *ResourceConfig) EnableVersions(versions ...schema.GroupVersion)","file":"staging/src/k8s.io/apiserver/pkg/server/storage/resource_config.go","code":"// EnableVersions enables all resources in a given groupVersion.\n// This will remove any preferences previously set on individual resources.\nfunc (o *ResourceConfig) EnableVersions(versions ...schema.GroupVersion) {\n\tfor _, version := range versions {\n\t\to.GroupVersionConfigs[version] = true\n\n\t\t// a preference about a version takes priority over the previously set resources\n\t\to.removeMatchingResourcePreferences(resourceMatcherForVersion(version))\n\t}\n\n}","line":{"from":94,"to":104}} {"id":100018364,"name":"versionEnabled","signature":"func (o *ResourceConfig) versionEnabled(version schema.GroupVersion) bool","file":"staging/src/k8s.io/apiserver/pkg/server/storage/resource_config.go","code":"// TODO this must be removed and we enable/disable individual resources.\nfunc (o *ResourceConfig) versionEnabled(version schema.GroupVersion) bool {\n\tenabled, _ := o.GroupVersionConfigs[version]\n\treturn enabled\n}","line":{"from":106,"to":110}} {"id":100018365,"name":"DisableResources","signature":"func (o *ResourceConfig) DisableResources(resources ...schema.GroupVersionResource)","file":"staging/src/k8s.io/apiserver/pkg/server/storage/resource_config.go","code":"func (o *ResourceConfig) DisableResources(resources ...schema.GroupVersionResource) {\n\tfor _, resource := range resources {\n\t\to.ResourceConfigs[resource] = false\n\t}\n}","line":{"from":112,"to":116}} {"id":100018366,"name":"EnableResources","signature":"func (o *ResourceConfig) EnableResources(resources ...schema.GroupVersionResource)","file":"staging/src/k8s.io/apiserver/pkg/server/storage/resource_config.go","code":"func (o *ResourceConfig) EnableResources(resources ...schema.GroupVersionResource) {\n\tfor _, resource := range resources {\n\t\to.ResourceConfigs[resource] = true\n\t}\n}","line":{"from":118,"to":122}} {"id":100018367,"name":"ResourceEnabled","signature":"func (o *ResourceConfig) ResourceEnabled(resource schema.GroupVersionResource) bool","file":"staging/src/k8s.io/apiserver/pkg/server/storage/resource_config.go","code":"func (o *ResourceConfig) ResourceEnabled(resource schema.GroupVersionResource) bool {\n\t// if a resource is explicitly set, that takes priority over the preference of the version.\n\tresourceEnabled, explicitlySet := o.ResourceConfigs[resource]\n\tif explicitlySet {\n\t\treturn resourceEnabled\n\t}\n\n\tif !o.versionEnabled(resource.GroupVersion()) {\n\t\treturn false\n\t}\n\t// they are enabled by default.\n\treturn true\n}","line":{"from":124,"to":136}} {"id":100018368,"name":"AnyResourceForGroupEnabled","signature":"func (o *ResourceConfig) AnyResourceForGroupEnabled(group string) bool","file":"staging/src/k8s.io/apiserver/pkg/server/storage/resource_config.go","code":"func (o *ResourceConfig) AnyResourceForGroupEnabled(group string) bool {\n\tfor version := range o.GroupVersionConfigs {\n\t\tif version.Group == group {\n\t\t\tif o.versionEnabled(version) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\tfor resource := range o.ResourceConfigs {\n\t\tif resource.Group == group \u0026\u0026 o.ResourceEnabled(resource) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":138,"to":153}} {"id":100018369,"name":"NewDefaultResourceEncodingConfig","signature":"func NewDefaultResourceEncodingConfig(scheme *runtime.Scheme) *DefaultResourceEncodingConfig","file":"staging/src/k8s.io/apiserver/pkg/server/storage/resource_encoding_config.go","code":"func NewDefaultResourceEncodingConfig(scheme *runtime.Scheme) *DefaultResourceEncodingConfig {\n\treturn \u0026DefaultResourceEncodingConfig{resources: map[schema.GroupResource]*OverridingResourceEncoding{}, scheme: scheme}\n}","line":{"from":49,"to":51}} {"id":100018370,"name":"SetResourceEncoding","signature":"func (o *DefaultResourceEncodingConfig) SetResourceEncoding(resourceBeingStored schema.GroupResource, externalEncodingVersion, internalVersion schema.GroupVersion)","file":"staging/src/k8s.io/apiserver/pkg/server/storage/resource_encoding_config.go","code":"func (o *DefaultResourceEncodingConfig) SetResourceEncoding(resourceBeingStored schema.GroupResource, externalEncodingVersion, internalVersion schema.GroupVersion) {\n\to.resources[resourceBeingStored] = \u0026OverridingResourceEncoding{\n\t\tExternalResourceEncoding: externalEncodingVersion,\n\t\tInternalResourceEncoding: internalVersion,\n\t}\n}","line":{"from":53,"to":58}} {"id":100018371,"name":"StorageEncodingFor","signature":"func (o *DefaultResourceEncodingConfig) StorageEncodingFor(resource schema.GroupResource) (schema.GroupVersion, error)","file":"staging/src/k8s.io/apiserver/pkg/server/storage/resource_encoding_config.go","code":"func (o *DefaultResourceEncodingConfig) StorageEncodingFor(resource schema.GroupResource) (schema.GroupVersion, error) {\n\tif !o.scheme.IsGroupRegistered(resource.Group) {\n\t\treturn schema.GroupVersion{}, fmt.Errorf(\"group %q is not registered in scheme\", resource.Group)\n\t}\n\n\tresourceOverride, resourceExists := o.resources[resource]\n\tif resourceExists {\n\t\treturn resourceOverride.ExternalResourceEncoding, nil\n\t}\n\n\t// return the most preferred external version for the group\n\treturn o.scheme.PrioritizedVersionsForGroup(resource.Group)[0], nil\n}","line":{"from":60,"to":72}} {"id":100018372,"name":"InMemoryEncodingFor","signature":"func (o *DefaultResourceEncodingConfig) InMemoryEncodingFor(resource schema.GroupResource) (schema.GroupVersion, error)","file":"staging/src/k8s.io/apiserver/pkg/server/storage/resource_encoding_config.go","code":"func (o *DefaultResourceEncodingConfig) InMemoryEncodingFor(resource schema.GroupResource) (schema.GroupVersion, error) {\n\tif !o.scheme.IsGroupRegistered(resource.Group) {\n\t\treturn schema.GroupVersion{}, fmt.Errorf(\"group %q is not registered in scheme\", resource.Group)\n\t}\n\n\tresourceOverride, resourceExists := o.resources[resource]\n\tif resourceExists {\n\t\treturn resourceOverride.InternalResourceEncoding, nil\n\t}\n\treturn schema.GroupVersion{Group: resource.Group, Version: runtime.APIVersionInternal}, nil\n}","line":{"from":74,"to":84}} {"id":100018373,"name":"NewStorageCodec","signature":"func NewStorageCodec(opts StorageCodecConfig) (runtime.Codec, runtime.GroupVersioner, error)","file":"staging/src/k8s.io/apiserver/pkg/server/storage/storage_codec.go","code":"// NewStorageCodec assembles a storage codec for the provided storage media type, the provided serializer, and the requested\n// storage and memory versions.\nfunc NewStorageCodec(opts StorageCodecConfig) (runtime.Codec, runtime.GroupVersioner, error) {\n\tmediaType, _, err := mime.ParseMediaType(opts.StorageMediaType)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"%q is not a valid mime-type\", opts.StorageMediaType)\n\t}\n\n\tsupportedMediaTypes := opts.StorageSerializer.SupportedMediaTypes()\n\tserializer, ok := runtime.SerializerInfoForMediaType(supportedMediaTypes, mediaType)\n\tif !ok {\n\t\tsupportedMediaTypeList := make([]string, len(supportedMediaTypes))\n\t\tfor i, mediaType := range supportedMediaTypes {\n\t\t\tsupportedMediaTypeList[i] = mediaType.MediaType\n\t\t}\n\t\treturn nil, nil, fmt.Errorf(\"unable to find serializer for %q, supported media types: %v\", mediaType, supportedMediaTypeList)\n\t}\n\n\ts := serializer.Serializer\n\n\t// Give callers the opportunity to wrap encoders and decoders. For decoders, each returned decoder will\n\t// be passed to the recognizer so that multiple decoders are available.\n\tvar encoder runtime.Encoder = s\n\tif opts.EncoderDecoratorFn != nil {\n\t\tencoder = opts.EncoderDecoratorFn(encoder)\n\t}\n\tdecoders := []runtime.Decoder{\n\t\t// selected decoder as the primary\n\t\ts,\n\t\t// universal deserializer as a fallback\n\t\topts.StorageSerializer.UniversalDeserializer(),\n\t\t// base64-wrapped universal deserializer as a last resort.\n\t\t// this allows reading base64-encoded protobuf, which should only exist if etcd2+protobuf was used at some point.\n\t\t// data written that way could exist in etcd2, or could have been migrated to etcd3.\n\t\t// TODO: flag this type of data if we encounter it, require migration (read to decode, write to persist using a supported encoder), and remove in 1.8\n\t\truntime.NewBase64Serializer(nil, opts.StorageSerializer.UniversalDeserializer()),\n\t}\n\tif opts.DecoderDecoratorFn != nil {\n\t\tdecoders = opts.DecoderDecoratorFn(decoders)\n\t}\n\n\tencodeVersioner := runtime.NewMultiGroupVersioner(\n\t\topts.StorageVersion,\n\t\tschema.GroupKind{Group: opts.StorageVersion.Group},\n\t\tschema.GroupKind{Group: opts.MemoryVersion.Group},\n\t)\n\n\t// Ensure the storage receives the correct version.\n\tencoder = opts.StorageSerializer.EncoderForVersion(\n\t\tencoder,\n\t\tencodeVersioner,\n\t)\n\tdecoder := opts.StorageSerializer.DecoderToVersion(\n\t\trecognizer.NewDecoder(decoders...),\n\t\truntime.NewCoercingMultiGroupVersioner(\n\t\t\topts.MemoryVersion,\n\t\t\tschema.GroupKind{Group: opts.MemoryVersion.Group},\n\t\t\tschema.GroupKind{Group: opts.StorageVersion.Group},\n\t\t),\n\t)\n\n\treturn runtime.NewCodec(encoder, decoder), encodeVersioner, nil\n}","line":{"from":41,"to":103}} {"id":100018374,"name":"Apply","signature":"func (o groupResourceOverrides) Apply(config *storagebackend.Config, options *StorageCodecConfig)","file":"staging/src/k8s.io/apiserver/pkg/server/storage/storage_factory.go","code":"// Apply overrides the provided config and options if the override has a value in that position\nfunc (o groupResourceOverrides) Apply(config *storagebackend.Config, options *StorageCodecConfig) {\n\tif len(o.etcdLocation) \u003e 0 {\n\t\tconfig.Transport.ServerList = o.etcdLocation\n\t}\n\tif len(o.etcdPrefix) \u003e 0 {\n\t\tconfig.Prefix = o.etcdPrefix\n\t}\n\n\tif len(o.mediaType) \u003e 0 {\n\t\toptions.StorageMediaType = o.mediaType\n\t}\n\tif o.serializer != nil {\n\t\toptions.StorageSerializer = o.serializer\n\t}\n\tif o.encoderDecoratorFn != nil {\n\t\toptions.EncoderDecoratorFn = o.encoderDecoratorFn\n\t}\n\tif o.decoderDecoratorFn != nil {\n\t\toptions.DecoderDecoratorFn = o.decoderDecoratorFn\n\t}\n\tif o.disablePaging {\n\t\tconfig.Paging = false\n\t}\n}","line":{"from":121,"to":145}} {"id":100018375,"name":"NewDefaultStorageFactory","signature":"func NewDefaultStorageFactory(","file":"staging/src/k8s.io/apiserver/pkg/server/storage/storage_factory.go","code":"func NewDefaultStorageFactory(\n\tconfig storagebackend.Config,\n\tdefaultMediaType string,\n\tdefaultSerializer runtime.StorageSerializer,\n\tresourceEncodingConfig ResourceEncodingConfig,\n\tresourceConfig APIResourceConfigSource,\n\tspecialDefaultResourcePrefixes map[schema.GroupResource]string,\n) *DefaultStorageFactory {\n\tconfig.Paging = utilfeature.DefaultFeatureGate.Enabled(features.APIListChunking)\n\tif len(defaultMediaType) == 0 {\n\t\tdefaultMediaType = runtime.ContentTypeJSON\n\t}\n\treturn \u0026DefaultStorageFactory{\n\t\tStorageConfig: config,\n\t\tOverrides: map[schema.GroupResource]groupResourceOverrides{},\n\t\tDefaultMediaType: defaultMediaType,\n\t\tDefaultSerializer: defaultSerializer,\n\t\tResourceEncodingConfig: resourceEncodingConfig,\n\t\tAPIResourceConfigSource: resourceConfig,\n\t\tDefaultResourcePrefixes: specialDefaultResourcePrefixes,\n\n\t\tnewStorageCodecFn: NewStorageCodec,\n\t}\n}","line":{"from":151,"to":174}} {"id":100018376,"name":"SetEtcdLocation","signature":"func (s *DefaultStorageFactory) SetEtcdLocation(groupResource schema.GroupResource, location []string)","file":"staging/src/k8s.io/apiserver/pkg/server/storage/storage_factory.go","code":"func (s *DefaultStorageFactory) SetEtcdLocation(groupResource schema.GroupResource, location []string) {\n\toverrides := s.Overrides[groupResource]\n\toverrides.etcdLocation = location\n\ts.Overrides[groupResource] = overrides\n}","line":{"from":176,"to":180}} {"id":100018377,"name":"SetEtcdPrefix","signature":"func (s *DefaultStorageFactory) SetEtcdPrefix(groupResource schema.GroupResource, prefix string)","file":"staging/src/k8s.io/apiserver/pkg/server/storage/storage_factory.go","code":"func (s *DefaultStorageFactory) SetEtcdPrefix(groupResource schema.GroupResource, prefix string) {\n\toverrides := s.Overrides[groupResource]\n\toverrides.etcdPrefix = prefix\n\ts.Overrides[groupResource] = overrides\n}","line":{"from":182,"to":186}} {"id":100018378,"name":"SetDisableAPIListChunking","signature":"func (s *DefaultStorageFactory) SetDisableAPIListChunking(groupResource schema.GroupResource)","file":"staging/src/k8s.io/apiserver/pkg/server/storage/storage_factory.go","code":"// SetDisableAPIListChunking allows a specific resource to disable paging at the storage layer, to prevent\n// exposure of key names in continuations. This may be overridden by feature gates.\nfunc (s *DefaultStorageFactory) SetDisableAPIListChunking(groupResource schema.GroupResource) {\n\toverrides := s.Overrides[groupResource]\n\toverrides.disablePaging = true\n\ts.Overrides[groupResource] = overrides\n}","line":{"from":188,"to":194}} {"id":100018379,"name":"SetResourceEtcdPrefix","signature":"func (s *DefaultStorageFactory) SetResourceEtcdPrefix(groupResource schema.GroupResource, prefix string)","file":"staging/src/k8s.io/apiserver/pkg/server/storage/storage_factory.go","code":"// SetResourceEtcdPrefix sets the prefix for a resource, but not the base-dir. You'll end up in `etcdPrefix/resourceEtcdPrefix`.\nfunc (s *DefaultStorageFactory) SetResourceEtcdPrefix(groupResource schema.GroupResource, prefix string) {\n\toverrides := s.Overrides[groupResource]\n\toverrides.etcdResourcePrefix = prefix\n\ts.Overrides[groupResource] = overrides\n}","line":{"from":196,"to":201}} {"id":100018380,"name":"SetSerializer","signature":"func (s *DefaultStorageFactory) SetSerializer(groupResource schema.GroupResource, mediaType string, serializer runtime.StorageSerializer)","file":"staging/src/k8s.io/apiserver/pkg/server/storage/storage_factory.go","code":"func (s *DefaultStorageFactory) SetSerializer(groupResource schema.GroupResource, mediaType string, serializer runtime.StorageSerializer) {\n\toverrides := s.Overrides[groupResource]\n\toverrides.mediaType = mediaType\n\toverrides.serializer = serializer\n\ts.Overrides[groupResource] = overrides\n}","line":{"from":203,"to":208}} {"id":100018381,"name":"AddCohabitatingResources","signature":"func (s *DefaultStorageFactory) AddCohabitatingResources(groupResources ...schema.GroupResource)","file":"staging/src/k8s.io/apiserver/pkg/server/storage/storage_factory.go","code":"// AddCohabitatingResources links resources together the order of the slice matters! its the priority order of lookup for finding a storage location\nfunc (s *DefaultStorageFactory) AddCohabitatingResources(groupResources ...schema.GroupResource) {\n\tfor _, groupResource := range groupResources {\n\t\toverrides := s.Overrides[groupResource]\n\t\toverrides.cohabitatingResources = groupResources\n\t\ts.Overrides[groupResource] = overrides\n\t}\n}","line":{"from":210,"to":217}} {"id":100018382,"name":"AddSerializationChains","signature":"func (s *DefaultStorageFactory) AddSerializationChains(encoderDecoratorFn func(runtime.Encoder) runtime.Encoder, decoderDecoratorFn func([]runtime.Decoder) []runtime.Decoder, groupResources ...schema.GroupResource)","file":"staging/src/k8s.io/apiserver/pkg/server/storage/storage_factory.go","code":"func (s *DefaultStorageFactory) AddSerializationChains(encoderDecoratorFn func(runtime.Encoder) runtime.Encoder, decoderDecoratorFn func([]runtime.Decoder) []runtime.Decoder, groupResources ...schema.GroupResource) {\n\tfor _, groupResource := range groupResources {\n\t\toverrides := s.Overrides[groupResource]\n\t\toverrides.encoderDecoratorFn = encoderDecoratorFn\n\t\toverrides.decoderDecoratorFn = decoderDecoratorFn\n\t\ts.Overrides[groupResource] = overrides\n\t}\n}","line":{"from":219,"to":226}} {"id":100018383,"name":"getAllResourcesAlias","signature":"func getAllResourcesAlias(resource schema.GroupResource) schema.GroupResource","file":"staging/src/k8s.io/apiserver/pkg/server/storage/storage_factory.go","code":"func getAllResourcesAlias(resource schema.GroupResource) schema.GroupResource {\n\treturn schema.GroupResource{Group: resource.Group, Resource: AllResources}\n}","line":{"from":228,"to":230}} {"id":100018384,"name":"getStorageGroupResource","signature":"func (s *DefaultStorageFactory) getStorageGroupResource(groupResource schema.GroupResource) schema.GroupResource","file":"staging/src/k8s.io/apiserver/pkg/server/storage/storage_factory.go","code":"func (s *DefaultStorageFactory) getStorageGroupResource(groupResource schema.GroupResource) schema.GroupResource {\n\tfor _, potentialStorageResource := range s.Overrides[groupResource].cohabitatingResources {\n\t\t// TODO deads2k or liggitt determine if have ever stored any of our cohabitating resources in a different location on new clusters\n\t\tif s.APIResourceConfigSource.AnyResourceForGroupEnabled(potentialStorageResource.Group) {\n\t\t\treturn potentialStorageResource\n\t\t}\n\t}\n\n\treturn groupResource\n}","line":{"from":232,"to":241}} {"id":100018385,"name":"NewConfig","signature":"func (s *DefaultStorageFactory) NewConfig(groupResource schema.GroupResource) (*storagebackend.ConfigForResource, error)","file":"staging/src/k8s.io/apiserver/pkg/server/storage/storage_factory.go","code":"// New finds the storage destination for the given group and resource. It will\n// return an error if the group has no storage destination configured.\nfunc (s *DefaultStorageFactory) NewConfig(groupResource schema.GroupResource) (*storagebackend.ConfigForResource, error) {\n\tchosenStorageResource := s.getStorageGroupResource(groupResource)\n\n\t// operate on copy\n\tstorageConfig := s.StorageConfig\n\tcodecConfig := StorageCodecConfig{\n\t\tStorageMediaType: s.DefaultMediaType,\n\t\tStorageSerializer: s.DefaultSerializer,\n\t}\n\n\tif override, ok := s.Overrides[getAllResourcesAlias(chosenStorageResource)]; ok {\n\t\toverride.Apply(\u0026storageConfig, \u0026codecConfig)\n\t}\n\tif override, ok := s.Overrides[chosenStorageResource]; ok {\n\t\toverride.Apply(\u0026storageConfig, \u0026codecConfig)\n\t}\n\n\tvar err error\n\tcodecConfig.StorageVersion, err = s.ResourceEncodingConfig.StorageEncodingFor(chosenStorageResource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcodecConfig.MemoryVersion, err = s.ResourceEncodingConfig.InMemoryEncodingFor(groupResource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcodecConfig.Config = storageConfig\n\n\tstorageConfig.Codec, storageConfig.EncodeVersioner, err = s.newStorageCodecFn(codecConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tklog.V(3).Infof(\"storing %v in %v, reading as %v from %#v\", groupResource, codecConfig.StorageVersion, codecConfig.MemoryVersion, codecConfig.Config)\n\n\treturn storageConfig.ForResource(groupResource), nil\n}","line":{"from":243,"to":280}} {"id":100018386,"name":"Configs","signature":"func (s *DefaultStorageFactory) Configs() []storagebackend.Config","file":"staging/src/k8s.io/apiserver/pkg/server/storage/storage_factory.go","code":"// Configs implements StorageFactory.\nfunc (s *DefaultStorageFactory) Configs() []storagebackend.Config {\n\treturn configs(s.StorageConfig, s.Overrides)\n}","line":{"from":282,"to":285}} {"id":100018387,"name":"Configs","signature":"func Configs(storageConfig storagebackend.Config) []storagebackend.Config","file":"staging/src/k8s.io/apiserver/pkg/server/storage/storage_factory.go","code":"// Configs gets configurations for all of registered storage destinations.\nfunc Configs(storageConfig storagebackend.Config) []storagebackend.Config {\n\treturn configs(storageConfig, nil)\n}","line":{"from":287,"to":290}} {"id":100018388,"name":"configs","signature":"func configs(storageConfig storagebackend.Config, grOverrides map[schema.GroupResource]groupResourceOverrides) []storagebackend.Config","file":"staging/src/k8s.io/apiserver/pkg/server/storage/storage_factory.go","code":"// Returns all storage configurations including those for group resource overrides\nfunc configs(storageConfig storagebackend.Config, grOverrides map[schema.GroupResource]groupResourceOverrides) []storagebackend.Config {\n\tlocations := sets.NewString()\n\tconfigs := []storagebackend.Config{}\n\tfor _, loc := range storageConfig.Transport.ServerList {\n\t\t// copy\n\t\tnewConfig := storageConfig\n\t\tnewConfig.Transport.ServerList = []string{loc}\n\t\tconfigs = append(configs, newConfig)\n\t\tlocations.Insert(loc)\n\t}\n\n\tfor _, override := range grOverrides {\n\t\tfor _, loc := range override.etcdLocation {\n\t\t\tif locations.Has(loc) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// copy\n\t\t\tnewConfig := storageConfig\n\t\t\toverride.Apply(\u0026newConfig, \u0026StorageCodecConfig{})\n\t\t\tnewConfig.Transport.ServerList = []string{loc}\n\t\t\tconfigs = append(configs, newConfig)\n\t\t\tlocations.Insert(loc)\n\t\t}\n\t}\n\treturn configs\n}","line":{"from":292,"to":318}} {"id":100018389,"name":"Backends","signature":"func (s *DefaultStorageFactory) Backends() []Backend","file":"staging/src/k8s.io/apiserver/pkg/server/storage/storage_factory.go","code":"// Backends implements StorageFactory.\nfunc (s *DefaultStorageFactory) Backends() []Backend {\n\treturn backends(s.StorageConfig, s.Overrides)\n}","line":{"from":320,"to":323}} {"id":100018390,"name":"Backends","signature":"func Backends(storageConfig storagebackend.Config) []Backend","file":"staging/src/k8s.io/apiserver/pkg/server/storage/storage_factory.go","code":"// Backends returns all backends for all registered storage destinations.\n// Used for getting all instances for health validations.\n// Deprecated: Validate health by passing storagebackend.Config directly to storagefactory.CreateProber.\nfunc Backends(storageConfig storagebackend.Config) []Backend {\n\treturn backends(storageConfig, nil)\n}","line":{"from":325,"to":330}} {"id":100018391,"name":"backends","signature":"func backends(storageConfig storagebackend.Config, grOverrides map[schema.GroupResource]groupResourceOverrides) []Backend","file":"staging/src/k8s.io/apiserver/pkg/server/storage/storage_factory.go","code":"func backends(storageConfig storagebackend.Config, grOverrides map[schema.GroupResource]groupResourceOverrides) []Backend {\n\tservers := sets.NewString(storageConfig.Transport.ServerList...)\n\n\tfor _, overrides := range grOverrides {\n\t\tservers.Insert(overrides.etcdLocation...)\n\t}\n\n\ttlsConfig := \u0026tls.Config{\n\t\tInsecureSkipVerify: true,\n\t}\n\tif len(storageConfig.Transport.CertFile) \u003e 0 \u0026\u0026 len(storageConfig.Transport.KeyFile) \u003e 0 {\n\t\tcert, err := tls.LoadX509KeyPair(storageConfig.Transport.CertFile, storageConfig.Transport.KeyFile)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"failed to load key pair while getting backends: %s\", err)\n\t\t} else {\n\t\t\ttlsConfig.Certificates = []tls.Certificate{cert}\n\t\t}\n\t}\n\tif len(storageConfig.Transport.TrustedCAFile) \u003e 0 {\n\t\tif caCert, err := ioutil.ReadFile(storageConfig.Transport.TrustedCAFile); err != nil {\n\t\t\tklog.Errorf(\"failed to read ca file while getting backends: %s\", err)\n\t\t} else {\n\t\t\tcaPool := x509.NewCertPool()\n\t\t\tcaPool.AppendCertsFromPEM(caCert)\n\t\t\ttlsConfig.RootCAs = caPool\n\t\t\ttlsConfig.InsecureSkipVerify = false\n\t\t}\n\t}\n\n\tbackends := []Backend{}\n\tfor server := range servers {\n\t\tbackends = append(backends, Backend{\n\t\t\tServer: server,\n\t\t\t// We can't share TLSConfig across different backends to avoid races.\n\t\t\t// For more details see: https://pr.k8s.io/59338\n\t\t\tTLSConfig: tlsConfig.Clone(),\n\t\t})\n\t}\n\treturn backends\n}","line":{"from":332,"to":371}} {"id":100018392,"name":"ResourcePrefix","signature":"func (s *DefaultStorageFactory) ResourcePrefix(groupResource schema.GroupResource) string","file":"staging/src/k8s.io/apiserver/pkg/server/storage/storage_factory.go","code":"func (s *DefaultStorageFactory) ResourcePrefix(groupResource schema.GroupResource) string {\n\tchosenStorageResource := s.getStorageGroupResource(groupResource)\n\tgroupOverride := s.Overrides[getAllResourcesAlias(chosenStorageResource)]\n\texactResourceOverride := s.Overrides[chosenStorageResource]\n\n\tetcdResourcePrefix := s.DefaultResourcePrefixes[chosenStorageResource]\n\tif len(groupOverride.etcdResourcePrefix) \u003e 0 {\n\t\tetcdResourcePrefix = groupOverride.etcdResourcePrefix\n\t}\n\tif len(exactResourceOverride.etcdResourcePrefix) \u003e 0 {\n\t\tetcdResourcePrefix = exactResourceOverride.etcdResourcePrefix\n\t}\n\tif len(etcdResourcePrefix) == 0 {\n\t\tetcdResourcePrefix = strings.ToLower(chosenStorageResource.Resource)\n\t}\n\n\treturn etcdResourcePrefix\n}","line":{"from":373,"to":390}} {"id":100018393,"name":"UpdateObject","signature":"func (a APIObjectVersioner) UpdateObject(obj runtime.Object, resourceVersion uint64) error","file":"staging/src/k8s.io/apiserver/pkg/storage/api_object_versioner.go","code":"// UpdateObject implements Versioner\nfunc (a APIObjectVersioner) UpdateObject(obj runtime.Object, resourceVersion uint64) error {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\tversionString := \"\"\n\tif resourceVersion != 0 {\n\t\tversionString = strconv.FormatUint(resourceVersion, 10)\n\t}\n\taccessor.SetResourceVersion(versionString)\n\treturn nil\n}","line":{"from":32,"to":44}} {"id":100018394,"name":"UpdateList","signature":"func (a APIObjectVersioner) UpdateList(obj runtime.Object, resourceVersion uint64, nextKey string, count *int64) error","file":"staging/src/k8s.io/apiserver/pkg/storage/api_object_versioner.go","code":"// UpdateList implements Versioner\nfunc (a APIObjectVersioner) UpdateList(obj runtime.Object, resourceVersion uint64, nextKey string, count *int64) error {\n\tif resourceVersion == 0 {\n\t\treturn fmt.Errorf(\"illegal resource version from storage: %d\", resourceVersion)\n\t}\n\tlistAccessor, err := meta.ListAccessor(obj)\n\tif err != nil || listAccessor == nil {\n\t\treturn err\n\t}\n\tversionString := strconv.FormatUint(resourceVersion, 10)\n\tlistAccessor.SetResourceVersion(versionString)\n\tlistAccessor.SetContinue(nextKey)\n\tlistAccessor.SetRemainingItemCount(count)\n\treturn nil\n}","line":{"from":46,"to":60}} {"id":100018395,"name":"PrepareObjectForStorage","signature":"func (a APIObjectVersioner) PrepareObjectForStorage(obj runtime.Object) error","file":"staging/src/k8s.io/apiserver/pkg/storage/api_object_versioner.go","code":"// PrepareObjectForStorage clears resourceVersion and selfLink prior to writing to etcd.\nfunc (a APIObjectVersioner) PrepareObjectForStorage(obj runtime.Object) error {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\taccessor.SetResourceVersion(\"\")\n\taccessor.SetSelfLink(\"\")\n\treturn nil\n}","line":{"from":62,"to":71}} {"id":100018396,"name":"ObjectResourceVersion","signature":"func (a APIObjectVersioner) ObjectResourceVersion(obj runtime.Object) (uint64, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/api_object_versioner.go","code":"// ObjectResourceVersion implements Versioner\nfunc (a APIObjectVersioner) ObjectResourceVersion(obj runtime.Object) (uint64, error) {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tversion := accessor.GetResourceVersion()\n\tif len(version) == 0 {\n\t\treturn 0, nil\n\t}\n\treturn strconv.ParseUint(version, 10, 64)\n}","line":{"from":73,"to":84}} {"id":100018397,"name":"ParseResourceVersion","signature":"func (a APIObjectVersioner) ParseResourceVersion(resourceVersion string) (uint64, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/api_object_versioner.go","code":"// ParseResourceVersion takes a resource version argument and converts it to\n// the etcd version. For watch we should pass to helper.Watch(). Because resourceVersion is\n// an opaque value, the default watch behavior for non-zero watch is to watch\n// the next value (if you pass \"1\", you will see updates from \"2\" onwards).\nfunc (a APIObjectVersioner) ParseResourceVersion(resourceVersion string) (uint64, error) {\n\tif resourceVersion == \"\" || resourceVersion == \"0\" {\n\t\treturn 0, nil\n\t}\n\tversion, err := strconv.ParseUint(resourceVersion, 10, 64)\n\tif err != nil {\n\t\treturn 0, NewInvalidError(field.ErrorList{\n\t\t\t// Validation errors are supposed to return version-specific field\n\t\t\t// paths, but this is probably close enough.\n\t\t\tfield.Invalid(field.NewPath(\"resourceVersion\"), resourceVersion, err.Error()),\n\t\t})\n\t}\n\treturn version, nil\n}","line":{"from":86,"to":103}} {"id":100018398,"name":"CompareResourceVersion","signature":"func (a APIObjectVersioner) CompareResourceVersion(lhs, rhs runtime.Object) int","file":"staging/src/k8s.io/apiserver/pkg/storage/api_object_versioner.go","code":"// CompareResourceVersion compares etcd resource versions. Outside this API they are all strings,\n// but etcd resource versions are special, they're actually ints, so we can easily compare them.\nfunc (a APIObjectVersioner) CompareResourceVersion(lhs, rhs runtime.Object) int {\n\tlhsVersion, err := a.ObjectResourceVersion(lhs)\n\tif err != nil {\n\t\t// coder error\n\t\tpanic(err)\n\t}\n\trhsVersion, err := a.ObjectResourceVersion(rhs)\n\tif err != nil {\n\t\t// coder error\n\t\tpanic(err)\n\t}\n\n\tif lhsVersion == rhsVersion {\n\t\treturn 0\n\t}\n\tif lhsVersion \u003c rhsVersion {\n\t\treturn -1\n\t}\n\n\treturn 1\n}","line":{"from":108,"to":130}} {"id":100018399,"name":"newCacheWatcher","signature":"func newCacheWatcher(","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cache_watcher.go","code":"func newCacheWatcher(\n\tchanSize int,\n\tfilter filterWithAttrsFunc,\n\tforget func(bool),\n\tversioner storage.Versioner,\n\tdeadline time.Time,\n\tallowWatchBookmarks bool,\n\tgroupResource schema.GroupResource,\n\tidentifier string,\n) *cacheWatcher {\n\treturn \u0026cacheWatcher{\n\t\tinput: make(chan *watchCacheEvent, chanSize),\n\t\tresult: make(chan watch.Event, chanSize),\n\t\tdone: make(chan struct{}),\n\t\tfilter: filter,\n\t\tstopped: false,\n\t\tforget: forget,\n\t\tversioner: versioner,\n\t\tdeadline: deadline,\n\t\tallowWatchBookmarks: allowWatchBookmarks,\n\t\tgroupResource: groupResource,\n\t\tidentifier: identifier,\n\t}\n}","line":{"from":91,"to":114}} {"id":100018400,"name":"ResultChan","signature":"func (c *cacheWatcher) ResultChan() \u003c-chan watch.Event","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cache_watcher.go","code":"// Implements watch.Interface.\nfunc (c *cacheWatcher) ResultChan() \u003c-chan watch.Event {\n\treturn c.result\n}","line":{"from":116,"to":119}} {"id":100018401,"name":"Stop","signature":"func (c *cacheWatcher) Stop()","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cache_watcher.go","code":"// Implements watch.Interface.\nfunc (c *cacheWatcher) Stop() {\n\tc.forget(false)\n}","line":{"from":121,"to":124}} {"id":100018402,"name":"stopLocked","signature":"func (c *cacheWatcher) stopLocked()","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cache_watcher.go","code":"// we rely on the fact that stopLocked is actually protected by Cacher.Lock()\nfunc (c *cacheWatcher) stopLocked() {\n\tif !c.stopped {\n\t\tc.stopped = true\n\t\t// stop without draining the input channel was requested.\n\t\tif !c.drainInputBuffer {\n\t\t\tclose(c.done)\n\t\t}\n\t\tclose(c.input)\n\t}\n\n\t// Even if the watcher was already stopped, if it previously was\n\t// using draining mode and it's not using it now we need to\n\t// close the done channel now. Otherwise we could leak the\n\t// processing goroutine if it will be trying to put more objects\n\t// into result channel, the channel will be full and there will\n\t// already be noone on the processing the events on the receiving end.\n\tif !c.drainInputBuffer \u0026\u0026 !c.isDoneChannelClosedLocked() {\n\t\tclose(c.done)\n\t}\n}","line":{"from":126,"to":146}} {"id":100018403,"name":"nonblockingAdd","signature":"func (c *cacheWatcher) nonblockingAdd(event *watchCacheEvent) bool","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cache_watcher.go","code":"func (c *cacheWatcher) nonblockingAdd(event *watchCacheEvent) bool {\n\t// if the bookmarkAfterResourceVersion hasn't been seen\n\t// we will try to deliver a bookmark event every second.\n\t// the following check will discard a bookmark event\n\t// if it is \u003c than the bookmarkAfterResourceVersion\n\t// so that we don't pollute the input channel\n\tif event.Type == watch.Bookmark \u0026\u0026 event.ResourceVersion \u003c c.bookmarkAfterResourceVersion {\n\t\treturn false\n\t}\n\tselect {\n\tcase c.input \u003c- event:\n\t\tc.markBookmarkAfterRvAsReceived(event)\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":148,"to":164}} {"id":100018404,"name":"add","signature":"func (c *cacheWatcher) add(event *watchCacheEvent, timer *time.Timer) bool","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cache_watcher.go","code":"// Nil timer means that add will not block (if it can't send event immediately, it will break the watcher)\n//\n// Note that bookmark events are never added via the add method only via the nonblockingAdd.\n// Changing this behaviour will require moving the markBookmarkAfterRvAsReceived method\nfunc (c *cacheWatcher) add(event *watchCacheEvent, timer *time.Timer) bool {\n\t// Try to send the event immediately, without blocking.\n\tif c.nonblockingAdd(event) {\n\t\treturn true\n\t}\n\n\tcloseFunc := func() {\n\t\t// This means that we couldn't send event to that watcher.\n\t\t// Since we don't want to block on it infinitely,\n\t\t// we simply terminate it.\n\t\tklog.V(1).Infof(\"Forcing %v watcher close due to unresponsiveness: %v. len(c.input) = %v, len(c.result) = %v\", c.groupResource.String(), c.identifier, len(c.input), len(c.result))\n\t\tmetrics.TerminatedWatchersCounter.WithLabelValues(c.groupResource.String()).Inc()\n\t\t// This means that we couldn't send event to that watcher.\n\t\t// Since we don't want to block on it infinitely, we simply terminate it.\n\n\t\t// we are graceful = false, when:\n\t\t//\n\t\t// (a) The bookmarkAfterResourceVersionReceived hasn't been received,\n\t\t// we can safely terminate the watcher. Because the client is waiting\n\t\t// for this specific bookmark, and we even haven't received one.\n\t\t// (b) We have seen the bookmarkAfterResourceVersion, and it was sent already to the client.\n\t\t// We can simply terminate the watcher.\n\n\t\t// we are graceful = true, when:\n\t\t//\n\t\t// (a) We have seen a bookmark, but it hasn't been sent to the client yet.\n\t\t// That means we should drain the input buffer which contains\n\t\t// the bookmarkAfterResourceVersion we want. We do that to make progress\n\t\t// as clients can re-establish a new watch with the given RV and receive\n\t\t// further notifications.\n\t\tgraceful := func() bool {\n\t\t\tc.stateMutex.Lock()\n\t\t\tdefer c.stateMutex.Unlock()\n\t\t\treturn c.state == cacheWatcherBookmarkReceived\n\t\t}()\n\t\tklog.V(1).Infof(\"Forcing %v watcher close due to unresponsiveness: %v. len(c.input) = %v, len(c.result) = %v, graceful = %v\", c.groupResource.String(), c.identifier, len(c.input), len(c.result), graceful)\n\t\tc.forget(graceful)\n\t}\n\n\tif timer == nil {\n\t\tcloseFunc()\n\t\treturn false\n\t}\n\n\t// OK, block sending, but only until timer fires.\n\tselect {\n\tcase c.input \u003c- event:\n\t\treturn true\n\tcase \u003c-timer.C:\n\t\tcloseFunc()\n\t\treturn false\n\t}\n}","line":{"from":166,"to":222}} {"id":100018405,"name":"nextBookmarkTime","signature":"func (c *cacheWatcher) nextBookmarkTime(now time.Time, bookmarkFrequency time.Duration) (time.Time, bool)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cache_watcher.go","code":"func (c *cacheWatcher) nextBookmarkTime(now time.Time, bookmarkFrequency time.Duration) (time.Time, bool) {\n\t// We try to send bookmarks:\n\t//\n\t// (a) right before the watcher timeout - for now we simply set it 2s before\n\t// the deadline\n\t//\n\t// (b) roughly every minute\n\t//\n\t// (c) immediately when the bookmarkAfterResourceVersion wasn't confirmed\n\t// in this scenario the client have already seen (or is in the process of sending)\n\t// all initial data and is interested in seeing\n\t// a specific RV value (aka. the bookmarkAfterResourceVersion)\n\t// since we don't know when the cacher will see the RV we increase frequency\n\t//\n\t// (b) gives us periodicity if the watch breaks due to unexpected\n\t// conditions, (a) ensures that on timeout the watcher is as close to\n\t// now as possible - this covers 99% of cases.\n\n\tif !c.wasBookmarkAfterRvReceived() {\n\t\treturn time.Time{}, true // schedule immediately\n\t}\n\n\theartbeatTime := now.Add(bookmarkFrequency)\n\tif c.deadline.IsZero() {\n\t\t// Timeout is set by our client libraries (e.g. reflector) as well as defaulted by\n\t\t// apiserver if properly configured. So this shoudln't happen in practice.\n\t\treturn heartbeatTime, true\n\t}\n\tif pretimeoutTime := c.deadline.Add(-2 * time.Second); pretimeoutTime.Before(heartbeatTime) {\n\t\theartbeatTime = pretimeoutTime\n\t}\n\n\tif heartbeatTime.Before(now) {\n\t\treturn time.Time{}, false\n\t}\n\treturn heartbeatTime, true\n}","line":{"from":224,"to":260}} {"id":100018406,"name":"wasBookmarkAfterRvReceived","signature":"func (c *cacheWatcher) wasBookmarkAfterRvReceived() bool","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cache_watcher.go","code":"// wasBookmarkAfterRvReceived same as wasBookmarkAfterRvReceivedLocked just acquires a lock\nfunc (c *cacheWatcher) wasBookmarkAfterRvReceived() bool {\n\tc.stateMutex.Lock()\n\tdefer c.stateMutex.Unlock()\n\treturn c.wasBookmarkAfterRvReceivedLocked()\n}","line":{"from":262,"to":267}} {"id":100018407,"name":"wasBookmarkAfterRvReceivedLocked","signature":"func (c *cacheWatcher) wasBookmarkAfterRvReceivedLocked() bool","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cache_watcher.go","code":"// wasBookmarkAfterRvReceivedLocked checks if the given cacheWatcher\n// have seen a bookmark event \u003e= bookmarkAfterResourceVersion\nfunc (c *cacheWatcher) wasBookmarkAfterRvReceivedLocked() bool {\n\treturn c.state != cacheWatcherWaitingForBookmark\n}","line":{"from":269,"to":273}} {"id":100018408,"name":"markBookmarkAfterRvAsReceived","signature":"func (c *cacheWatcher) markBookmarkAfterRvAsReceived(event *watchCacheEvent)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cache_watcher.go","code":"// markBookmarkAfterRvAsReceived indicates that the given cacheWatcher\n// have seen a bookmark event \u003e= bookmarkAfterResourceVersion\nfunc (c *cacheWatcher) markBookmarkAfterRvAsReceived(event *watchCacheEvent) {\n\tif event.Type == watch.Bookmark {\n\t\tc.stateMutex.Lock()\n\t\tdefer c.stateMutex.Unlock()\n\t\tif c.wasBookmarkAfterRvReceivedLocked() {\n\t\t\treturn\n\t\t}\n\t\t// bookmark events are scheduled by startDispatchingBookmarkEvents method\n\t\t// since we received a bookmark event that means we have\n\t\t// converged towards the expected RV and it is okay to update the state so that\n\t\t// this cacher can be scheduler for a regular bookmark events\n\t\tc.state = cacheWatcherBookmarkReceived\n\t}\n}","line":{"from":275,"to":290}} {"id":100018409,"name":"wasBookmarkAfterRvSentLocked","signature":"func (c *cacheWatcher) wasBookmarkAfterRvSentLocked() bool","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cache_watcher.go","code":"// wasBookmarkAfterRvSentLocked checks if a bookmark event\n// with an RV \u003e= the bookmarkAfterResourceVersion has been sent by this watcher\nfunc (c *cacheWatcher) wasBookmarkAfterRvSentLocked() bool {\n\treturn c.state == cacheWatcherBookmarkSent\n}","line":{"from":292,"to":296}} {"id":100018410,"name":"wasBookmarkAfterRvSent","signature":"func (c *cacheWatcher) wasBookmarkAfterRvSent() bool","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cache_watcher.go","code":"// wasBookmarkAfterRvSent same as wasBookmarkAfterRvSentLocked just acquires a lock\nfunc (c *cacheWatcher) wasBookmarkAfterRvSent() bool {\n\tc.stateMutex.Lock()\n\tdefer c.stateMutex.Unlock()\n\treturn c.wasBookmarkAfterRvSentLocked()\n}","line":{"from":298,"to":303}} {"id":100018411,"name":"markBookmarkAfterRvSent","signature":"func (c *cacheWatcher) markBookmarkAfterRvSent(event *watchCacheEvent)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cache_watcher.go","code":"// markBookmarkAfterRvSent indicates that the given cacheWatcher\n// have sent a bookmark event with an RV \u003e= the bookmarkAfterResourceVersion\n//\n// this function relies on the fact that the nonblockingAdd method\n// won't admit a bookmark event with an RV \u003c the bookmarkAfterResourceVersion\n// so the first received bookmark event is considered to match the bookmarkAfterResourceVersion\nfunc (c *cacheWatcher) markBookmarkAfterRvSent(event *watchCacheEvent) {\n\t// note that bookmark events are not so common so will acquire a lock every ~60 second or so\n\tif event.Type == watch.Bookmark {\n\t\tc.stateMutex.Lock()\n\t\tdefer c.stateMutex.Unlock()\n\t\tif !c.wasBookmarkAfterRvSentLocked() {\n\t\t\tc.state = cacheWatcherBookmarkSent\n\t\t}\n\t}\n}","line":{"from":305,"to":320}} {"id":100018412,"name":"setBookmarkAfterResourceVersion","signature":"func (c *cacheWatcher) setBookmarkAfterResourceVersion(bookmarkAfterResourceVersion uint64)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cache_watcher.go","code":"// setBookmarkAfterResourceVersion sets the bookmarkAfterResourceVersion and the state associated with it\nfunc (c *cacheWatcher) setBookmarkAfterResourceVersion(bookmarkAfterResourceVersion uint64) {\n\tstate := cacheWatcherWaitingForBookmark\n\tif bookmarkAfterResourceVersion == 0 {\n\t\tstate = cacheWatcherBookmarkSent // if no specific RV was requested we assume no-op\n\t}\n\tc.state = state\n\tc.bookmarkAfterResourceVersion = bookmarkAfterResourceVersion\n}","line":{"from":322,"to":330}} {"id":100018413,"name":"setDrainInputBufferLocked","signature":"func (c *cacheWatcher) setDrainInputBufferLocked(drain bool)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cache_watcher.go","code":"// setDrainInputBufferLocked if set to true indicates that we should delay closing this watcher\n// until we send all events residing in the input buffer.\nfunc (c *cacheWatcher) setDrainInputBufferLocked(drain bool) {\n\tc.drainInputBuffer = drain\n}","line":{"from":332,"to":336}} {"id":100018414,"name":"isDoneChannelClosedLocked","signature":"func (c *cacheWatcher) isDoneChannelClosedLocked() bool","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cache_watcher.go","code":"// isDoneChannelClosed checks if c.done channel is closed\nfunc (c *cacheWatcher) isDoneChannelClosedLocked() bool {\n\tselect {\n\tcase \u003c-c.done:\n\t\treturn true\n\tdefault:\n\t}\n\treturn false\n}","line":{"from":338,"to":346}} {"id":100018415,"name":"getMutableObject","signature":"func getMutableObject(object runtime.Object) runtime.Object","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cache_watcher.go","code":"func getMutableObject(object runtime.Object) runtime.Object {\n\tif _, ok := object.(*cachingObject); ok {\n\t\t// It is safe to return without deep-copy, because the underlying\n\t\t// object will lazily perform deep-copy on the first try to change\n\t\t// any of its fields.\n\t\treturn object\n\t}\n\treturn object.DeepCopyObject()\n}","line":{"from":348,"to":356}} {"id":100018416,"name":"updateResourceVersion","signature":"func updateResourceVersion(object runtime.Object, versioner storage.Versioner, resourceVersion uint64)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cache_watcher.go","code":"func updateResourceVersion(object runtime.Object, versioner storage.Versioner, resourceVersion uint64) {\n\tif err := versioner.UpdateObject(object, resourceVersion); err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"failure to version api object (%d) %#v: %v\", resourceVersion, object, err))\n\t}\n}","line":{"from":358,"to":362}} {"id":100018417,"name":"convertToWatchEvent","signature":"func (c *cacheWatcher) convertToWatchEvent(event *watchCacheEvent) *watch.Event","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cache_watcher.go","code":"func (c *cacheWatcher) convertToWatchEvent(event *watchCacheEvent) *watch.Event {\n\tif event.Type == watch.Bookmark {\n\t\te := \u0026watch.Event{Type: watch.Bookmark, Object: event.Object.DeepCopyObject()}\n\t\tif !c.wasBookmarkAfterRvSent() {\n\t\t\tobjMeta, err := meta.Accessor(e.Object)\n\t\t\tif err != nil {\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"error while accessing object's metadata gr: %v, identifier: %v, obj: %#v, err: %v\", c.groupResource, c.identifier, e.Object, err))\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tobjAnnotations := objMeta.GetAnnotations()\n\t\t\tif objAnnotations == nil {\n\t\t\t\tobjAnnotations = map[string]string{}\n\t\t\t}\n\t\t\tobjAnnotations[\"k8s.io/initial-events-end\"] = \"true\"\n\t\t\tobjMeta.SetAnnotations(objAnnotations)\n\t\t}\n\t\treturn e\n\t}\n\n\tcurObjPasses := event.Type != watch.Deleted \u0026\u0026 c.filter(event.Key, event.ObjLabels, event.ObjFields)\n\toldObjPasses := false\n\tif event.PrevObject != nil {\n\t\toldObjPasses = c.filter(event.Key, event.PrevObjLabels, event.PrevObjFields)\n\t}\n\tif !curObjPasses \u0026\u0026 !oldObjPasses {\n\t\t// Watcher is not interested in that object.\n\t\treturn nil\n\t}\n\n\tswitch {\n\tcase curObjPasses \u0026\u0026 !oldObjPasses:\n\t\treturn \u0026watch.Event{Type: watch.Added, Object: getMutableObject(event.Object)}\n\tcase curObjPasses \u0026\u0026 oldObjPasses:\n\t\treturn \u0026watch.Event{Type: watch.Modified, Object: getMutableObject(event.Object)}\n\tcase !curObjPasses \u0026\u0026 oldObjPasses:\n\t\t// return a delete event with the previous object content, but with the event's resource version\n\t\toldObj := getMutableObject(event.PrevObject)\n\t\t// We know that if oldObj is cachingObject (which can only be set via\n\t\t// setCachingObjects), its resourceVersion is already set correctly and\n\t\t// we don't need to update it. However, since cachingObject efficiently\n\t\t// handles noop updates, we avoid this microoptimization here.\n\t\tupdateResourceVersion(oldObj, c.versioner, event.ResourceVersion)\n\t\treturn \u0026watch.Event{Type: watch.Deleted, Object: oldObj}\n\t}\n\n\treturn nil\n}","line":{"from":364,"to":410}} {"id":100018418,"name":"sendWatchCacheEvent","signature":"func (c *cacheWatcher) sendWatchCacheEvent(event *watchCacheEvent)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cache_watcher.go","code":"// NOTE: sendWatchCacheEvent is assumed to not modify \u003cevent\u003e !!!\nfunc (c *cacheWatcher) sendWatchCacheEvent(event *watchCacheEvent) {\n\twatchEvent := c.convertToWatchEvent(event)\n\tif watchEvent == nil {\n\t\t// Watcher is not interested in that object.\n\t\treturn\n\t}\n\n\t// We need to ensure that if we put event X to the c.result, all\n\t// previous events were already put into it before, no matter whether\n\t// c.done is close or not.\n\t// Thus we cannot simply select from c.done and c.result and this\n\t// would give us non-determinism.\n\t// At the same time, we don't want to block infinitely on putting\n\t// to c.result, when c.done is already closed.\n\t//\n\t// This ensures that with c.done already close, we at most once go\n\t// into the next select after this. With that, no matter which\n\t// statement we choose there, we will deliver only consecutive\n\t// events.\n\tselect {\n\tcase \u003c-c.done:\n\t\treturn\n\tdefault:\n\t}\n\n\tselect {\n\tcase c.result \u003c- *watchEvent:\n\t\tc.markBookmarkAfterRvSent(event)\n\tcase \u003c-c.done:\n\t}\n}","line":{"from":412,"to":443}} {"id":100018419,"name":"processInterval","signature":"func (c *cacheWatcher) processInterval(ctx context.Context, cacheInterval *watchCacheInterval, resourceVersion uint64)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cache_watcher.go","code":"func (c *cacheWatcher) processInterval(ctx context.Context, cacheInterval *watchCacheInterval, resourceVersion uint64) {\n\tdefer utilruntime.HandleCrash()\n\tdefer close(c.result)\n\tdefer c.Stop()\n\n\t// Check how long we are processing initEvents.\n\t// As long as these are not processed, we are not processing\n\t// any incoming events, so if it takes long, we may actually\n\t// block all watchers for some time.\n\t// TODO: From the logs it seems that there happens processing\n\t// times even up to 1s which is very long. However, this doesn't\n\t// depend that much on the number of initEvents. E.g. from the\n\t// 2000-node Kubemark run we have logs like this, e.g.:\n\t// ... processing 13862 initEvents took 66.808689ms\n\t// ... processing 14040 initEvents took 993.532539ms\n\t// We should understand what is blocking us in those cases (e.g.\n\t// is it lack of CPU, network, or sth else) and potentially\n\t// consider increase size of result buffer in those cases.\n\tconst initProcessThreshold = 500 * time.Millisecond\n\tstartTime := time.Now()\n\n\tinitEventCount := 0\n\tfor {\n\t\tevent, err := cacheInterval.Next()\n\t\tif err != nil {\n\t\t\t// An error indicates that the cache interval\n\t\t\t// has been invalidated and can no longer serve\n\t\t\t// events.\n\t\t\t//\n\t\t\t// Initially we considered sending an \"out-of-history\"\n\t\t\t// Error event in this case, but because historically\n\t\t\t// such events weren't sent out of the watchCache, we\n\t\t\t// decided not to. This is still ok, because on watch\n\t\t\t// closure, the watcher will try to re-instantiate the\n\t\t\t// watch and then will get an explicit \"out-of-history\"\n\t\t\t// window. There is potential for optimization, but for\n\t\t\t// now, in order to be on the safe side and not break\n\t\t\t// custom clients, the cost of it is something that we\n\t\t\t// are fully accepting.\n\t\t\tklog.Warningf(\"couldn't retrieve watch event to serve: %#v\", err)\n\t\t\treturn\n\t\t}\n\t\tif event == nil {\n\t\t\tbreak\n\t\t}\n\t\tc.sendWatchCacheEvent(event)\n\n\t\t// With some events already sent, update resourceVersion so that\n\t\t// events that were buffered and not yet processed won't be delivered\n\t\t// to this watcher second time causing going back in time.\n\t\t//\n\t\t// There is one case where events are not necessary ordered by\n\t\t// resourceVersion, being a case of watching from resourceVersion=0,\n\t\t// which at the beginning returns the state of each objects.\n\t\t// For the purpose of it, we need to max it with the resource version\n\t\t// that we have so far.\n\t\tif event.ResourceVersion \u003e resourceVersion {\n\t\t\tresourceVersion = event.ResourceVersion\n\t\t}\n\t\tinitEventCount++\n\t}\n\n\tif initEventCount \u003e 0 {\n\t\tmetrics.InitCounter.WithLabelValues(c.groupResource.String()).Add(float64(initEventCount))\n\t}\n\tprocessingTime := time.Since(startTime)\n\tif processingTime \u003e initProcessThreshold {\n\t\tklog.V(2).Infof(\"processing %d initEvents of %s (%s) took %v\", initEventCount, c.groupResource, c.identifier, processingTime)\n\t}\n\n\tc.process(ctx, resourceVersion)\n}","line":{"from":445,"to":516}} {"id":100018420,"name":"process","signature":"func (c *cacheWatcher) process(ctx context.Context, resourceVersion uint64)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cache_watcher.go","code":"func (c *cacheWatcher) process(ctx context.Context, resourceVersion uint64) {\n\t// At this point we already start processing incoming watch events.\n\t// However, the init event can still be processed because their serialization\n\t// and sending to the client happens asynchrnously.\n\t// TODO: As describe in the KEP, we would like to estimate that by delaying\n\t// the initialization signal proportionally to the number of events to\n\t// process, but we're leaving this to the tuning phase.\n\tutilflowcontrol.WatchInitialized(ctx)\n\n\tfor {\n\t\tselect {\n\t\tcase event, ok := \u003c-c.input:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// only send events newer than resourceVersion\n\t\t\t// or a bookmark event with an RV equal to resourceVersion\n\t\t\t// if we haven't sent one to the client\n\t\t\tif event.ResourceVersion \u003e resourceVersion || (event.Type == watch.Bookmark \u0026\u0026 event.ResourceVersion == resourceVersion \u0026\u0026 !c.wasBookmarkAfterRvSent()) {\n\t\t\t\tc.sendWatchCacheEvent(event)\n\t\t\t}\n\t\tcase \u003c-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}","line":{"from":518,"to":543}} {"id":100018421,"name":"addWatcher","signature":"func (wm watchersMap) addWatcher(w *cacheWatcher, number int)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"func (wm watchersMap) addWatcher(w *cacheWatcher, number int) {\n\twm[number] = w\n}","line":{"from":112,"to":114}} {"id":100018422,"name":"deleteWatcher","signature":"func (wm watchersMap) deleteWatcher(number int, done func(*cacheWatcher))","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"func (wm watchersMap) deleteWatcher(number int, done func(*cacheWatcher)) {\n\tif watcher, ok := wm[number]; ok {\n\t\tdelete(wm, number)\n\t\tdone(watcher)\n\t}\n}","line":{"from":116,"to":121}} {"id":100018423,"name":"terminateAll","signature":"func (wm watchersMap) terminateAll(done func(*cacheWatcher))","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"func (wm watchersMap) terminateAll(done func(*cacheWatcher)) {\n\tfor key, watcher := range wm {\n\t\tdelete(wm, key)\n\t\tdone(watcher)\n\t}\n}","line":{"from":123,"to":128}} {"id":100018424,"name":"addWatcher","signature":"func (i *indexedWatchers) addWatcher(w *cacheWatcher, number int, scope namespacedName, value string, supported bool)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"func (i *indexedWatchers) addWatcher(w *cacheWatcher, number int, scope namespacedName, value string, supported bool) {\n\tif supported {\n\t\tif _, ok := i.valueWatchers[value]; !ok {\n\t\t\ti.valueWatchers[value] = watchersMap{}\n\t\t}\n\t\ti.valueWatchers[value].addWatcher(w, number)\n\t} else {\n\t\tscopedWatchers, ok := i.allWatchers[scope]\n\t\tif !ok {\n\t\t\tscopedWatchers = watchersMap{}\n\t\t\ti.allWatchers[scope] = scopedWatchers\n\t\t}\n\t\tscopedWatchers.addWatcher(w, number)\n\t}\n}","line":{"from":135,"to":149}} {"id":100018425,"name":"deleteWatcher","signature":"func (i *indexedWatchers) deleteWatcher(number int, scope namespacedName, value string, supported bool, done func(*cacheWatcher))","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"func (i *indexedWatchers) deleteWatcher(number int, scope namespacedName, value string, supported bool, done func(*cacheWatcher)) {\n\tif supported {\n\t\ti.valueWatchers[value].deleteWatcher(number, done)\n\t\tif len(i.valueWatchers[value]) == 0 {\n\t\t\tdelete(i.valueWatchers, value)\n\t\t}\n\t} else {\n\t\ti.allWatchers[scope].deleteWatcher(number, done)\n\t\tif len(i.allWatchers[scope]) == 0 {\n\t\t\tdelete(i.allWatchers, scope)\n\t\t}\n\t}\n}","line":{"from":151,"to":163}} {"id":100018426,"name":"terminateAll","signature":"func (i *indexedWatchers) terminateAll(groupResource schema.GroupResource, done func(*cacheWatcher))","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"func (i *indexedWatchers) terminateAll(groupResource schema.GroupResource, done func(*cacheWatcher)) {\n\t// note that we don't have to call setDrainInputBufferLocked method on the watchers\n\t// because we take advantage of the default value - stop immediately\n\t// also watchers that have had already its draining strategy set\n\t// are no longer available (they were removed from the allWatchers and the valueWatchers maps)\n\tif len(i.allWatchers) \u003e 0 || len(i.valueWatchers) \u003e 0 {\n\t\tklog.Warningf(\"Terminating all watchers from cacher %v\", groupResource)\n\t}\n\tfor _, watchers := range i.allWatchers {\n\t\twatchers.terminateAll(done)\n\t}\n\tfor _, watchers := range i.valueWatchers {\n\t\twatchers.terminateAll(done)\n\t}\n\ti.allWatchers = map[namespacedName]watchersMap{}\n\ti.valueWatchers = map[string]watchersMap{}\n}","line":{"from":165,"to":181}} {"id":100018427,"name":"newTimeBucketWatchers","signature":"func newTimeBucketWatchers(clock clock.Clock, bookmarkFrequency time.Duration) *watcherBookmarkTimeBuckets","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"func newTimeBucketWatchers(clock clock.Clock, bookmarkFrequency time.Duration) *watcherBookmarkTimeBuckets {\n\treturn \u0026watcherBookmarkTimeBuckets{\n\t\twatchersBuckets: make(map[int64][]*cacheWatcher),\n\t\tcreateTime: clock.Now(),\n\t\tstartBucketID: 0,\n\t\tclock: clock,\n\t\tbookmarkFrequency: bookmarkFrequency,\n\t}\n}","line":{"from":196,"to":204}} {"id":100018428,"name":"addWatcher","signature":"func (t *watcherBookmarkTimeBuckets) addWatcher(w *cacheWatcher) bool","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// adds a watcher to the bucket, if the deadline is before the start, it will be\n// added to the first one.\nfunc (t *watcherBookmarkTimeBuckets) addWatcher(w *cacheWatcher) bool {\n\t// note that the returned time can be before t.createTime,\n\t// especially in cases when the nextBookmarkTime method\n\t// give us the zero value of type Time\n\t// so buckedID can hold a negative value\n\tnextTime, ok := w.nextBookmarkTime(t.clock.Now(), t.bookmarkFrequency)\n\tif !ok {\n\t\treturn false\n\t}\n\tbucketID := int64(nextTime.Sub(t.createTime) / time.Second)\n\tt.lock.Lock()\n\tdefer t.lock.Unlock()\n\tif bucketID \u003c t.startBucketID {\n\t\tbucketID = t.startBucketID\n\t}\n\twatchers := t.watchersBuckets[bucketID]\n\tt.watchersBuckets[bucketID] = append(watchers, w)\n\treturn true\n}","line":{"from":206,"to":226}} {"id":100018429,"name":"popExpiredWatchers","signature":"func (t *watcherBookmarkTimeBuckets) popExpiredWatchers() [][]*cacheWatcher","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"func (t *watcherBookmarkTimeBuckets) popExpiredWatchers() [][]*cacheWatcher {\n\tcurrentBucketID := int64(t.clock.Since(t.createTime) / time.Second)\n\t// There should be one or two elements in almost all cases\n\texpiredWatchers := make([][]*cacheWatcher, 0, 2)\n\tt.lock.Lock()\n\tdefer t.lock.Unlock()\n\tfor ; t.startBucketID \u003c= currentBucketID; t.startBucketID++ {\n\t\tif watchers, ok := t.watchersBuckets[t.startBucketID]; ok {\n\t\t\tdelete(t.watchersBuckets, t.startBucketID)\n\t\t\texpiredWatchers = append(expiredWatchers, watchers)\n\t\t}\n\t}\n\treturn expiredWatchers\n}","line":{"from":228,"to":241}} {"id":100018430,"name":"NewCacherFromConfig","signature":"func NewCacherFromConfig(config Config) (*Cacher, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// NewCacherFromConfig creates a new Cacher responsible for servicing WATCH and LIST requests from\n// its internal cache and updating its cache in the background based on the\n// given configuration.\nfunc NewCacherFromConfig(config Config) (*Cacher, error) {\n\tstopCh := make(chan struct{})\n\tobj := config.NewFunc()\n\t// Give this error when it is constructed rather than when you get the\n\t// first watch item, because it's much easier to track down that way.\n\tif err := runtime.CheckCodec(config.Codec, obj); err != nil {\n\t\treturn nil, fmt.Errorf(\"storage codec doesn't seem to match given type: %v\", err)\n\t}\n\n\tvar indexedTrigger *indexedTriggerFunc\n\tif config.IndexerFuncs != nil {\n\t\t// For now, we don't support multiple trigger functions defined\n\t\t// for a given resource.\n\t\tif len(config.IndexerFuncs) \u003e 1 {\n\t\t\treturn nil, fmt.Errorf(\"cacher %s doesn't support more than one IndexerFunc: \", reflect.TypeOf(obj).String())\n\t\t}\n\t\tfor key, value := range config.IndexerFuncs {\n\t\t\tif value != nil {\n\t\t\t\tindexedTrigger = \u0026indexedTriggerFunc{\n\t\t\t\t\tindexName: key,\n\t\t\t\t\tindexerFunc: value,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif config.Clock == nil {\n\t\tconfig.Clock = clock.RealClock{}\n\t}\n\tobjType := reflect.TypeOf(obj)\n\tcacher := \u0026Cacher{\n\t\tresourcePrefix: config.ResourcePrefix,\n\t\tready: newReady(),\n\t\tstorage: config.Storage,\n\t\tobjectType: objType,\n\t\tgroupResource: config.GroupResource,\n\t\tversioner: config.Versioner,\n\t\tnewFunc: config.NewFunc,\n\t\tnewListFunc: config.NewListFunc,\n\t\tindexedTrigger: indexedTrigger,\n\t\twatcherIdx: 0,\n\t\twatchers: indexedWatchers{\n\t\t\tallWatchers: make(map[namespacedName]watchersMap),\n\t\t\tvalueWatchers: make(map[string]watchersMap),\n\t\t},\n\t\t// TODO: Figure out the correct value for the buffer size.\n\t\tincoming: make(chan watchCacheEvent, 100),\n\t\tdispatchTimeoutBudget: newTimeBudget(),\n\t\t// We need to (potentially) stop both:\n\t\t// - wait.Until go-routine\n\t\t// - reflector.ListAndWatch\n\t\t// and there are no guarantees on the order that they will stop.\n\t\t// So we will be simply closing the channel, and synchronizing on the WaitGroup.\n\t\tstopCh: stopCh,\n\t\tclock: config.Clock,\n\t\ttimer: time.NewTimer(time.Duration(0)),\n\t\tbookmarkWatchers: newTimeBucketWatchers(config.Clock, defaultBookmarkFrequency),\n\t}\n\n\t// Ensure that timer is stopped.\n\tif !cacher.timer.Stop() {\n\t\t// Consume triggered (but not yet received) timer event\n\t\t// so that future reuse does not get a spurious timeout.\n\t\t\u003c-cacher.timer.C\n\t}\n\n\twatchCache := newWatchCache(\n\t\tconfig.KeyFunc, cacher.processEvent, config.GetAttrsFunc, config.Versioner, config.Indexers, config.Clock, config.GroupResource)\n\tlisterWatcher := NewCacherListerWatcher(config.Storage, config.ResourcePrefix, config.NewListFunc)\n\treflectorName := \"storage/cacher.go:\" + config.ResourcePrefix\n\n\treflector := cache.NewNamedReflector(reflectorName, listerWatcher, obj, watchCache, 0)\n\t// Configure reflector's pager to for an appropriate pagination chunk size for fetching data from\n\t// storage. The pager falls back to full list if paginated list calls fail due to an \"Expired\" error.\n\treflector.WatchListPageSize = storageWatchListPageSize\n\t// When etcd loses leader for 3 cycles, it returns error \"no leader\".\n\t// We don't want to terminate all watchers as recreating all watchers puts high load on api-server.\n\t// In most of the cases, leader is reelected within few cycles.\n\treflector.MaxInternalErrorRetryDuration = time.Second * 30\n\t// since the watch-list is provided by the watch cache instruct\n\t// the reflector to issue a regular LIST against the store\n\treflector.UseWatchList = false\n\n\tcacher.watchCache = watchCache\n\tcacher.reflector = reflector\n\n\tgo cacher.dispatchEvents()\n\n\tcacher.stopWg.Add(1)\n\tgo func() {\n\t\tdefer cacher.stopWg.Done()\n\t\tdefer cacher.terminateAllWatchers()\n\t\twait.Until(\n\t\t\tfunc() {\n\t\t\t\tif !cacher.isStopped() {\n\t\t\t\t\tcacher.startCaching(stopCh)\n\t\t\t\t}\n\t\t\t}, time.Second, stopCh,\n\t\t)\n\t}()\n\n\treturn cacher, nil\n}","line":{"from":336,"to":441}} {"id":100018431,"name":"startCaching","signature":"func (c *Cacher) startCaching(stopChannel \u003c-chan struct{})","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"func (c *Cacher) startCaching(stopChannel \u003c-chan struct{}) {\n\t// The 'usable' lock is always 'RLock'able when it is safe to use the cache.\n\t// It is safe to use the cache after a successful list until a disconnection.\n\t// We start with usable (write) locked. The below OnReplace function will\n\t// unlock it after a successful list. The below defer will then re-lock\n\t// it when this function exits (always due to disconnection), only if\n\t// we actually got a successful list. This cycle will repeat as needed.\n\tsuccessfulList := false\n\tc.watchCache.SetOnReplace(func() {\n\t\tsuccessfulList = true\n\t\tc.ready.set(true)\n\t\tklog.V(1).Infof(\"cacher (%v): initialized\", c.groupResource.String())\n\t\tmetrics.WatchCacheInitializations.WithLabelValues(c.groupResource.String()).Inc()\n\t})\n\tdefer func() {\n\t\tif successfulList {\n\t\t\tc.ready.set(false)\n\t\t}\n\t}()\n\n\tc.terminateAllWatchers()\n\t// Note that since onReplace may be not called due to errors, we explicitly\n\t// need to retry it on errors under lock.\n\t// Also note that startCaching is called in a loop, so there's no need\n\t// to have another loop here.\n\tif err := c.reflector.ListAndWatch(stopChannel); err != nil {\n\t\tklog.Errorf(\"cacher (%v): unexpected ListAndWatch error: %v; reinitializing...\", c.groupResource.String(), err)\n\t}\n}","line":{"from":443,"to":471}} {"id":100018432,"name":"Versioner","signature":"func (c *Cacher) Versioner() storage.Versioner","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// Versioner implements storage.Interface.\nfunc (c *Cacher) Versioner() storage.Versioner {\n\treturn c.storage.Versioner()\n}","line":{"from":473,"to":476}} {"id":100018433,"name":"Create","signature":"func (c *Cacher) Create(ctx context.Context, key string, obj, out runtime.Object, ttl uint64) error","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// Create implements storage.Interface.\nfunc (c *Cacher) Create(ctx context.Context, key string, obj, out runtime.Object, ttl uint64) error {\n\treturn c.storage.Create(ctx, key, obj, out, ttl)\n}","line":{"from":478,"to":481}} {"id":100018434,"name":"Delete","signature":"func (c *Cacher) Delete(","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// Delete implements storage.Interface.\nfunc (c *Cacher) Delete(\n\tctx context.Context, key string, out runtime.Object, preconditions *storage.Preconditions,\n\tvalidateDeletion storage.ValidateObjectFunc, _ runtime.Object) error {\n\t// Ignore the suggestion and try to pass down the current version of the object\n\t// read from cache.\n\tif elem, exists, err := c.watchCache.GetByKey(key); err != nil {\n\t\tklog.Errorf(\"GetByKey returned error: %v\", err)\n\t} else if exists {\n\t\t// DeepCopy the object since we modify resource version when serializing the\n\t\t// current object.\n\t\tcurrObj := elem.(*storeElement).Object.DeepCopyObject()\n\t\treturn c.storage.Delete(ctx, key, out, preconditions, validateDeletion, currObj)\n\t}\n\t// If we couldn't get the object, fallback to no-suggestion.\n\treturn c.storage.Delete(ctx, key, out, preconditions, validateDeletion, nil)\n}","line":{"from":483,"to":499}} {"id":100018435,"name":"Watch","signature":"func (c *Cacher) Watch(ctx context.Context, key string, opts storage.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// Watch implements storage.Interface.\nfunc (c *Cacher) Watch(ctx context.Context, key string, opts storage.ListOptions) (watch.Interface, error) {\n\tpred := opts.Predicate\n\t// if the watch-list feature wasn't set and the resourceVersion is unset\n\t// ensure that the rv from which the watch is being served, is the latest\n\t// one. \"latest\" is ensured by serving the watch from\n\t// the underlying storage.\n\t//\n\t// it should never happen due to our validation but let's just be super-safe here\n\t// and disable sendingInitialEvents when the feature wasn't enabled\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.WatchList) \u0026\u0026 opts.SendInitialEvents != nil {\n\t\topts.SendInitialEvents = nil\n\t}\n\tif opts.SendInitialEvents == nil \u0026\u0026 opts.ResourceVersion == \"\" {\n\t\treturn c.storage.Watch(ctx, key, opts)\n\t}\n\trequestedWatchRV, err := c.versioner.ParseResourceVersion(opts.ResourceVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treadyGeneration, err := c.ready.waitAndReadGeneration(ctx)\n\tif err != nil {\n\t\treturn nil, errors.NewServiceUnavailable(err.Error())\n\t}\n\n\t// determine the namespace and name scope of the watch, first from the request, secondarily from the field selector\n\tscope := namespacedName{}\n\tif requestNamespace, ok := request.NamespaceFrom(ctx); ok \u0026\u0026 len(requestNamespace) \u003e 0 {\n\t\tscope.namespace = requestNamespace\n\t} else if selectorNamespace, ok := pred.Field.RequiresExactMatch(\"metadata.namespace\"); ok {\n\t\tscope.namespace = selectorNamespace\n\t}\n\tif requestInfo, ok := request.RequestInfoFrom(ctx); ok \u0026\u0026 requestInfo != nil \u0026\u0026 len(requestInfo.Name) \u003e 0 {\n\t\tscope.name = requestInfo.Name\n\t} else if selectorName, ok := pred.Field.RequiresExactMatch(\"metadata.name\"); ok {\n\t\tscope.name = selectorName\n\t}\n\n\ttriggerValue, triggerSupported := \"\", false\n\tif c.indexedTrigger != nil {\n\t\tfor _, field := range pred.IndexFields {\n\t\t\tif field == c.indexedTrigger.indexName {\n\t\t\t\tif value, ok := pred.Field.RequiresExactMatch(field); ok {\n\t\t\t\t\ttriggerValue, triggerSupported = value, true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// It boils down to a tradeoff between:\n\t// - having it as small as possible to reduce memory usage\n\t// - having it large enough to ensure that watchers that need to process\n\t// a bunch of changes have enough buffer to avoid from blocking other\n\t// watchers on our watcher having a processing hiccup\n\tchanSize := c.watchCache.suggestedWatchChannelSize(c.indexedTrigger != nil, triggerSupported)\n\n\t// Determine a function that computes the bookmarkAfterResourceVersion\n\tbookmarkAfterResourceVersionFn, err := c.getBookmarkAfterResourceVersionLockedFunc(ctx, requestedWatchRV, opts)\n\tif err != nil {\n\t\treturn newErrWatcher(err), nil\n\t}\n\n\t// Determine a function that computes the watchRV we should start from\n\tstartWatchResourceVersionFn, err := c.getStartResourceVersionForWatchLockedFunc(ctx, requestedWatchRV, opts)\n\tif err != nil {\n\t\treturn newErrWatcher(err), nil\n\t}\n\n\t// Determine watch timeout('0' means deadline is not set, ignore checking)\n\tdeadline, _ := ctx.Deadline()\n\n\tidentifier := fmt.Sprintf(\"key: %q, labels: %q, fields: %q\", key, pred.Label, pred.Field)\n\n\t// Create a watcher here to reduce memory allocations under lock,\n\t// given that memory allocation may trigger GC and block the thread.\n\t// Also note that emptyFunc is a placeholder, until we will be able\n\t// to compute watcher.forget function (which has to happen under lock).\n\twatcher := newCacheWatcher(\n\t\tchanSize,\n\t\tfilterWithAttrsFunction(key, pred),\n\t\temptyFunc,\n\t\tc.versioner,\n\t\tdeadline,\n\t\tpred.AllowWatchBookmarks,\n\t\tc.groupResource,\n\t\tidentifier,\n\t)\n\n\t// We explicitly use thread unsafe version and do locking ourself to ensure that\n\t// no new events will be processed in the meantime. The watchCache will be unlocked\n\t// on return from this function.\n\t// Note that we cannot do it under Cacher lock, to avoid a deadlock, since the\n\t// underlying watchCache is calling processEvent under its lock.\n\tc.watchCache.RLock()\n\tdefer c.watchCache.RUnlock()\n\tforceAllEvents, err := c.waitUntilWatchCacheFreshAndForceAllEvents(ctx, requestedWatchRV, opts)\n\tif err != nil {\n\t\treturn newErrWatcher(err), nil\n\t}\n\tstartWatchRV := startWatchResourceVersionFn()\n\tvar cacheInterval *watchCacheInterval\n\tif forceAllEvents {\n\t\tcacheInterval, err = c.watchCache.getIntervalFromStoreLocked()\n\t} else {\n\t\tcacheInterval, err = c.watchCache.getAllEventsSinceLocked(startWatchRV)\n\t}\n\tif err != nil {\n\t\t// To match the uncached watch implementation, once we have passed authn/authz/admission,\n\t\t// and successfully parsed a resource version, other errors must fail with a watch event of type ERROR,\n\t\t// rather than a directly returned error.\n\t\treturn newErrWatcher(err), nil\n\t}\n\n\taddedWatcher := false\n\tfunc() {\n\t\tc.Lock()\n\t\tdefer c.Unlock()\n\n\t\tif generation, ok := c.ready.checkAndReadGeneration(); generation != readyGeneration || !ok {\n\t\t\t// We went unready or are already on a different generation.\n\t\t\t// Avoid registering and starting the watch as it will have to be\n\t\t\t// terminated immediately anyway.\n\t\t\treturn\n\t\t}\n\n\t\t// Update watcher.forget function once we can compute it.\n\t\twatcher.forget = forgetWatcher(c, watcher, c.watcherIdx, scope, triggerValue, triggerSupported)\n\t\t// Update the bookMarkAfterResourceVersion\n\t\twatcher.setBookmarkAfterResourceVersion(bookmarkAfterResourceVersionFn())\n\t\tc.watchers.addWatcher(watcher, c.watcherIdx, scope, triggerValue, triggerSupported)\n\t\taddedWatcher = true\n\n\t\t// Add it to the queue only when the client support watch bookmarks.\n\t\tif watcher.allowWatchBookmarks {\n\t\t\tc.bookmarkWatchers.addWatcher(watcher)\n\t\t}\n\t\tc.watcherIdx++\n\t}()\n\n\tif !addedWatcher {\n\t\t// Watcher isn't really started at this point, so it's safe to just drop it.\n\t\t//\n\t\t// We're simulating the immediate watch termination, which boils down to simply\n\t\t// closing the watcher.\n\t\treturn newImmediateCloseWatcher(), nil\n\t}\n\n\tgo watcher.processInterval(ctx, cacheInterval, startWatchRV)\n\treturn watcher, nil\n}","line":{"from":506,"to":656}} {"id":100018436,"name":"Get","signature":"func (c *Cacher) Get(ctx context.Context, key string, opts storage.GetOptions, objPtr runtime.Object) error","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// Get implements storage.Interface.\nfunc (c *Cacher) Get(ctx context.Context, key string, opts storage.GetOptions, objPtr runtime.Object) error {\n\tif opts.ResourceVersion == \"\" {\n\t\t// If resourceVersion is not specified, serve it from underlying\n\t\t// storage (for backward compatibility).\n\t\treturn c.storage.Get(ctx, key, opts, objPtr)\n\t}\n\n\t// If resourceVersion is specified, serve it from cache.\n\t// It's guaranteed that the returned value is at least that\n\t// fresh as the given resourceVersion.\n\tgetRV, err := c.versioner.ParseResourceVersion(opts.ResourceVersion)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif getRV == 0 \u0026\u0026 !c.ready.check() {\n\t\t// If Cacher is not yet initialized and we don't require any specific\n\t\t// minimal resource version, simply forward the request to storage.\n\t\treturn c.storage.Get(ctx, key, opts, objPtr)\n\t}\n\n\t// Do not create a trace - it's not for free and there are tons\n\t// of Get requests. We can add it if it will be really needed.\n\tif err := c.ready.wait(ctx); err != nil {\n\t\treturn errors.NewServiceUnavailable(err.Error())\n\t}\n\n\tobjVal, err := conversion.EnforcePtr(objPtr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tobj, exists, readResourceVersion, err := c.watchCache.WaitUntilFreshAndGet(ctx, getRV, key)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif exists {\n\t\telem, ok := obj.(*storeElement)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"non *storeElement returned from storage: %v\", obj)\n\t\t}\n\t\tobjVal.Set(reflect.ValueOf(elem.Object).Elem())\n\t} else {\n\t\tobjVal.Set(reflect.Zero(objVal.Type()))\n\t\tif !opts.IgnoreNotFound {\n\t\t\treturn storage.NewKeyNotFoundError(key, int64(readResourceVersion))\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":658,"to":709}} {"id":100018437,"name":"shouldDelegateList","signature":"func shouldDelegateList(opts storage.ListOptions) bool","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// NOTICE: Keep in sync with shouldListFromStorage function in\n//\n//\tstaging/src/k8s.io/apiserver/pkg/util/flowcontrol/request/list_work_estimator.go\nfunc shouldDelegateList(opts storage.ListOptions) bool {\n\tresourceVersion := opts.ResourceVersion\n\tpred := opts.Predicate\n\tmatch := opts.ResourceVersionMatch\n\tpagingEnabled := utilfeature.DefaultFeatureGate.Enabled(features.APIListChunking)\n\thasContinuation := pagingEnabled \u0026\u0026 len(pred.Continue) \u003e 0\n\thasLimit := pagingEnabled \u0026\u0026 pred.Limit \u003e 0 \u0026\u0026 resourceVersion != \"0\"\n\tunsupportedMatch := match != \"\" \u0026\u0026 match != metav1.ResourceVersionMatchNotOlderThan\n\n\t// If resourceVersion is not specified, serve it from underlying\n\t// storage (for backward compatibility). If a continuation is\n\t// requested, serve it from the underlying storage as well.\n\t// Limits are only sent to storage when resourceVersion is non-zero\n\t// since the watch cache isn't able to perform continuations, and\n\t// limits are ignored when resource version is zero\n\treturn resourceVersion == \"\" || hasContinuation || hasLimit || unsupportedMatch\n}","line":{"from":711,"to":730}} {"id":100018438,"name":"listItems","signature":"func (c *Cacher) listItems(ctx context.Context, listRV uint64, key string, pred storage.SelectionPredicate, recursive bool) ([]interface{}, uint64, string, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"func (c *Cacher) listItems(ctx context.Context, listRV uint64, key string, pred storage.SelectionPredicate, recursive bool) ([]interface{}, uint64, string, error) {\n\tif !recursive {\n\t\tobj, exists, readResourceVersion, err := c.watchCache.WaitUntilFreshAndGet(ctx, listRV, key)\n\t\tif err != nil {\n\t\t\treturn nil, 0, \"\", err\n\t\t}\n\t\tif exists {\n\t\t\treturn []interface{}{obj}, readResourceVersion, \"\", nil\n\t\t}\n\t\treturn nil, readResourceVersion, \"\", nil\n\t}\n\treturn c.watchCache.WaitUntilFreshAndList(ctx, listRV, pred.MatcherIndex())\n}","line":{"from":732,"to":744}} {"id":100018439,"name":"GetList","signature":"func (c *Cacher) GetList(ctx context.Context, key string, opts storage.ListOptions, listObj runtime.Object) error","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// GetList implements storage.Interface\nfunc (c *Cacher) GetList(ctx context.Context, key string, opts storage.ListOptions, listObj runtime.Object) error {\n\trecursive := opts.Recursive\n\tresourceVersion := opts.ResourceVersion\n\tpred := opts.Predicate\n\tif shouldDelegateList(opts) {\n\t\treturn c.storage.GetList(ctx, key, opts, listObj)\n\t}\n\n\t// If resourceVersion is specified, serve it from cache.\n\t// It's guaranteed that the returned value is at least that\n\t// fresh as the given resourceVersion.\n\tlistRV, err := c.versioner.ParseResourceVersion(resourceVersion)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif listRV == 0 \u0026\u0026 !c.ready.check() {\n\t\t// If Cacher is not yet initialized and we don't require any specific\n\t\t// minimal resource version, simply forward the request to storage.\n\t\treturn c.storage.GetList(ctx, key, opts, listObj)\n\t}\n\n\tctx, span := tracing.Start(ctx, \"cacher list\",\n\t\tattribute.String(\"audit-id\", audit.GetAuditIDTruncated(ctx)),\n\t\tattribute.Stringer(\"type\", c.groupResource))\n\tdefer span.End(500 * time.Millisecond)\n\n\tif err := c.ready.wait(ctx); err != nil {\n\t\treturn errors.NewServiceUnavailable(err.Error())\n\t}\n\tspan.AddEvent(\"Ready\")\n\n\t// List elements with at least 'listRV' from cache.\n\tlistPtr, err := meta.GetItemsPtr(listObj)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlistVal, err := conversion.EnforcePtr(listPtr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif listVal.Kind() != reflect.Slice {\n\t\treturn fmt.Errorf(\"need a pointer to slice, got %v\", listVal.Kind())\n\t}\n\tfilter := filterWithAttrsFunction(key, pred)\n\n\tobjs, readResourceVersion, indexUsed, err := c.listItems(ctx, listRV, key, pred, recursive)\n\tif err != nil {\n\t\treturn err\n\t}\n\tspan.AddEvent(\"Listed items from cache\", attribute.Int(\"count\", len(objs)))\n\tif len(objs) \u003e listVal.Cap() \u0026\u0026 pred.Label.Empty() \u0026\u0026 pred.Field.Empty() {\n\t\t// Resize the slice appropriately, since we already know that none\n\t\t// of the elements will be filtered out.\n\t\tlistVal.Set(reflect.MakeSlice(reflect.SliceOf(c.objectType.Elem()), 0, len(objs)))\n\t\tspan.AddEvent(\"Resized result\")\n\t}\n\tfor _, obj := range objs {\n\t\telem, ok := obj.(*storeElement)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"non *storeElement returned from storage: %v\", obj)\n\t\t}\n\t\tif filter(elem.Key, elem.Labels, elem.Fields) {\n\t\t\tlistVal.Set(reflect.Append(listVal, reflect.ValueOf(elem.Object).Elem()))\n\t\t}\n\t}\n\tif listVal.IsNil() {\n\t\t// Ensure that we never return a nil Items pointer in the result for consistency.\n\t\tlistVal.Set(reflect.MakeSlice(listVal.Type(), 0, 0))\n\t}\n\tspan.AddEvent(\"Filtered items\", attribute.Int(\"count\", listVal.Len()))\n\tif c.versioner != nil {\n\t\tif err := c.versioner.UpdateList(listObj, readResourceVersion, \"\", nil); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tmetrics.RecordListCacheMetrics(c.resourcePrefix, indexUsed, len(objs), listVal.Len())\n\treturn nil\n}","line":{"from":746,"to":825}} {"id":100018440,"name":"GuaranteedUpdate","signature":"func (c *Cacher) GuaranteedUpdate(","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// GuaranteedUpdate implements storage.Interface.\nfunc (c *Cacher) GuaranteedUpdate(\n\tctx context.Context, key string, destination runtime.Object, ignoreNotFound bool,\n\tpreconditions *storage.Preconditions, tryUpdate storage.UpdateFunc, _ runtime.Object) error {\n\t// Ignore the suggestion and try to pass down the current version of the object\n\t// read from cache.\n\tif elem, exists, err := c.watchCache.GetByKey(key); err != nil {\n\t\tklog.Errorf(\"GetByKey returned error: %v\", err)\n\t} else if exists {\n\t\t// DeepCopy the object since we modify resource version when serializing the\n\t\t// current object.\n\t\tcurrObj := elem.(*storeElement).Object.DeepCopyObject()\n\t\treturn c.storage.GuaranteedUpdate(ctx, key, destination, ignoreNotFound, preconditions, tryUpdate, currObj)\n\t}\n\t// If we couldn't get the object, fallback to no-suggestion.\n\treturn c.storage.GuaranteedUpdate(ctx, key, destination, ignoreNotFound, preconditions, tryUpdate, nil)\n}","line":{"from":827,"to":843}} {"id":100018441,"name":"Count","signature":"func (c *Cacher) Count(pathPrefix string) (int64, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// Count implements storage.Interface.\nfunc (c *Cacher) Count(pathPrefix string) (int64, error) {\n\treturn c.storage.Count(pathPrefix)\n}","line":{"from":845,"to":848}} {"id":100018442,"name":"baseObjectThreadUnsafe","signature":"func baseObjectThreadUnsafe(object runtime.Object) runtime.Object","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// baseObjectThreadUnsafe omits locking for cachingObject.\nfunc baseObjectThreadUnsafe(object runtime.Object) runtime.Object {\n\tif co, ok := object.(*cachingObject); ok {\n\t\treturn co.object\n\t}\n\treturn object\n}","line":{"from":850,"to":856}} {"id":100018443,"name":"triggerValuesThreadUnsafe","signature":"func (c *Cacher) triggerValuesThreadUnsafe(event *watchCacheEvent) ([]string, bool)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"func (c *Cacher) triggerValuesThreadUnsafe(event *watchCacheEvent) ([]string, bool) {\n\tif c.indexedTrigger == nil {\n\t\treturn nil, false\n\t}\n\n\tresult := make([]string, 0, 2)\n\tresult = append(result, c.indexedTrigger.indexerFunc(baseObjectThreadUnsafe(event.Object)))\n\tif event.PrevObject == nil {\n\t\treturn result, true\n\t}\n\tprevTriggerValue := c.indexedTrigger.indexerFunc(baseObjectThreadUnsafe(event.PrevObject))\n\tif result[0] != prevTriggerValue {\n\t\tresult = append(result, prevTriggerValue)\n\t}\n\treturn result, true\n}","line":{"from":858,"to":873}} {"id":100018444,"name":"processEvent","signature":"func (c *Cacher) processEvent(event *watchCacheEvent)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"func (c *Cacher) processEvent(event *watchCacheEvent) {\n\tif curLen := int64(len(c.incoming)); c.incomingHWM.Update(curLen) {\n\t\t// Monitor if this gets backed up, and how much.\n\t\tklog.V(1).Infof(\"cacher (%v): %v objects queued in incoming channel.\", c.groupResource.String(), curLen)\n\t}\n\tc.incoming \u003c- *event\n}","line":{"from":875,"to":881}} {"id":100018445,"name":"dispatchEvents","signature":"func (c *Cacher) dispatchEvents()","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"func (c *Cacher) dispatchEvents() {\n\t// Jitter to help level out any aggregate load.\n\tbookmarkTimer := c.clock.NewTimer(wait.Jitter(time.Second, 0.25))\n\tdefer bookmarkTimer.Stop()\n\n\tlastProcessedResourceVersion := uint64(0)\n\tfor {\n\t\tselect {\n\t\tcase event, ok := \u003c-c.incoming:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// Don't dispatch bookmarks coming from the storage layer.\n\t\t\t// They can be very frequent (even to the level of subseconds)\n\t\t\t// to allow efficient watch resumption on kube-apiserver restarts,\n\t\t\t// and propagating them down may overload the whole system.\n\t\t\t//\n\t\t\t// TODO: If at some point we decide the performance and scalability\n\t\t\t// footprint is acceptable, this is the place to hook them in.\n\t\t\t// However, we then need to check if this was called as a result\n\t\t\t// of a bookmark event or regular Add/Update/Delete operation by\n\t\t\t// checking if resourceVersion here has changed.\n\t\t\tif event.Type != watch.Bookmark {\n\t\t\t\tc.dispatchEvent(\u0026event)\n\t\t\t}\n\t\t\tlastProcessedResourceVersion = event.ResourceVersion\n\t\t\tmetrics.EventsCounter.WithLabelValues(c.groupResource.String()).Inc()\n\t\tcase \u003c-bookmarkTimer.C():\n\t\t\tbookmarkTimer.Reset(wait.Jitter(time.Second, 0.25))\n\t\t\t// Never send a bookmark event if we did not see an event here, this is fine\n\t\t\t// because we don't provide any guarantees on sending bookmarks.\n\t\t\tif lastProcessedResourceVersion == 0 {\n\t\t\t\t// pop expired watchers in case there has been no update\n\t\t\t\tc.bookmarkWatchers.popExpiredWatchers()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbookmarkEvent := \u0026watchCacheEvent{\n\t\t\t\tType: watch.Bookmark,\n\t\t\t\tObject: c.newFunc(),\n\t\t\t\tResourceVersion: lastProcessedResourceVersion,\n\t\t\t}\n\t\t\tif err := c.versioner.UpdateObject(bookmarkEvent.Object, bookmarkEvent.ResourceVersion); err != nil {\n\t\t\t\tklog.Errorf(\"failure to set resourceVersion to %d on bookmark event %+v\", bookmarkEvent.ResourceVersion, bookmarkEvent.Object)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc.dispatchEvent(bookmarkEvent)\n\t\tcase \u003c-c.stopCh:\n\t\t\treturn\n\t\t}\n\t}\n}","line":{"from":883,"to":933}} {"id":100018446,"name":"setCachingObjects","signature":"func setCachingObjects(event *watchCacheEvent, versioner storage.Versioner)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"func setCachingObjects(event *watchCacheEvent, versioner storage.Versioner) {\n\tswitch event.Type {\n\tcase watch.Added, watch.Modified:\n\t\tif object, err := newCachingObject(event.Object); err == nil {\n\t\t\tevent.Object = object\n\t\t} else {\n\t\t\tklog.Errorf(\"couldn't create cachingObject from: %#v\", event.Object)\n\t\t}\n\t\t// Don't wrap PrevObject for update event (for create events it is nil).\n\t\t// We only encode those to deliver DELETE watch events, so if\n\t\t// event.Object is not nil it can be used only for watchers for which\n\t\t// selector was satisfied for its previous version and is no longer\n\t\t// satisfied for the current version.\n\t\t// This is rare enough that it doesn't justify making deep-copy of the\n\t\t// object (done by newCachingObject) every time.\n\tcase watch.Deleted:\n\t\t// Don't wrap Object for delete events - these are not to deliver any\n\t\t// events. Only wrap PrevObject.\n\t\tif object, err := newCachingObject(event.PrevObject); err == nil {\n\t\t\t// Update resource version of the object.\n\t\t\t// event.PrevObject is used to deliver DELETE watch events and\n\t\t\t// for them, we set resourceVersion to \u003ccurrent\u003e instead of\n\t\t\t// the resourceVersion of the last modification of the object.\n\t\t\tupdateResourceVersion(object, versioner, event.ResourceVersion)\n\t\t\tevent.PrevObject = object\n\t\t} else {\n\t\t\tklog.Errorf(\"couldn't create cachingObject from: %#v\", event.Object)\n\t\t}\n\t}\n}","line":{"from":935,"to":964}} {"id":100018447,"name":"dispatchEvent","signature":"func (c *Cacher) dispatchEvent(event *watchCacheEvent)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"func (c *Cacher) dispatchEvent(event *watchCacheEvent) {\n\tc.startDispatching(event)\n\tdefer c.finishDispatching()\n\t// Watchers stopped after startDispatching will be delayed to finishDispatching,\n\n\t// Since add() can block, we explicitly add when cacher is unlocked.\n\t// Dispatching event in nonblocking way first, which make faster watchers\n\t// not be blocked by slower ones.\n\tif event.Type == watch.Bookmark {\n\t\tfor _, watcher := range c.watchersBuffer {\n\t\t\twatcher.nonblockingAdd(event)\n\t\t}\n\t} else {\n\t\t// Set up caching of object serializations only for dispatching this event.\n\t\t//\n\t\t// Storing serializations in memory would result in increased memory usage,\n\t\t// but it would help for caching encodings for watches started from old\n\t\t// versions. However, we still don't have a convincing data that the gain\n\t\t// from it justifies increased memory usage, so for now we drop the cached\n\t\t// serializations after dispatching this event.\n\t\t//\n\t\t// Given that CachingObject is just wrapping the object and not perfoming\n\t\t// deep-copying (until some field is explicitly being modified), we create\n\t\t// it unconditionally to ensure safety and reduce deep-copying.\n\t\t//\n\t\t// Make a shallow copy to allow overwriting Object and PrevObject.\n\t\twcEvent := *event\n\t\tsetCachingObjects(\u0026wcEvent, c.versioner)\n\t\tevent = \u0026wcEvent\n\n\t\tc.blockedWatchers = c.blockedWatchers[:0]\n\t\tfor _, watcher := range c.watchersBuffer {\n\t\t\tif !watcher.nonblockingAdd(event) {\n\t\t\t\tc.blockedWatchers = append(c.blockedWatchers, watcher)\n\t\t\t}\n\t\t}\n\n\t\tif len(c.blockedWatchers) \u003e 0 {\n\t\t\t// dispatchEvent is called very often, so arrange\n\t\t\t// to reuse timers instead of constantly allocating.\n\t\t\tstartTime := time.Now()\n\t\t\ttimeout := c.dispatchTimeoutBudget.takeAvailable()\n\t\t\tc.timer.Reset(timeout)\n\n\t\t\t// Send event to all blocked watchers. As long as timer is running,\n\t\t\t// `add` will wait for the watcher to unblock. After timeout,\n\t\t\t// `add` will not wait, but immediately close a still blocked watcher.\n\t\t\t// Hence, every watcher gets the chance to unblock itself while timer\n\t\t\t// is running, not only the first ones in the list.\n\t\t\ttimer := c.timer\n\t\t\tfor _, watcher := range c.blockedWatchers {\n\t\t\t\tif !watcher.add(event, timer) {\n\t\t\t\t\t// fired, clean the timer by set it to nil.\n\t\t\t\t\ttimer = nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Stop the timer if it is not fired\n\t\t\tif timer != nil \u0026\u0026 !timer.Stop() {\n\t\t\t\t// Consume triggered (but not yet received) timer event\n\t\t\t\t// so that future reuse does not get a spurious timeout.\n\t\t\t\t\u003c-timer.C\n\t\t\t}\n\n\t\t\tc.dispatchTimeoutBudget.returnUnused(timeout - time.Since(startTime))\n\t\t}\n\t}\n}","line":{"from":966,"to":1033}} {"id":100018448,"name":"startDispatchingBookmarkEventsLocked","signature":"func (c *Cacher) startDispatchingBookmarkEventsLocked()","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"func (c *Cacher) startDispatchingBookmarkEventsLocked() {\n\t// Pop already expired watchers. However, explicitly ignore stopped ones,\n\t// as we don't delete watcher from bookmarkWatchers when it is stopped.\n\tfor _, watchers := range c.bookmarkWatchers.popExpiredWatchers() {\n\t\tfor _, watcher := range watchers {\n\t\t\t// c.Lock() is held here.\n\t\t\t// watcher.stopThreadUnsafe() is protected by c.Lock()\n\t\t\tif watcher.stopped {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc.watchersBuffer = append(c.watchersBuffer, watcher)\n\t\t\tc.expiredBookmarkWatchers = append(c.expiredBookmarkWatchers, watcher)\n\t\t}\n\t}\n}","line":{"from":1035,"to":1049}} {"id":100018449,"name":"startDispatching","signature":"func (c *Cacher) startDispatching(event *watchCacheEvent)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// startDispatching chooses watchers potentially interested in a given event\n// a marks dispatching as true.\nfunc (c *Cacher) startDispatching(event *watchCacheEvent) {\n\t// It is safe to call triggerValuesThreadUnsafe here, because at this\n\t// point only this thread can access this event (we create a separate\n\t// watchCacheEvent for every dispatch).\n\ttriggerValues, supported := c.triggerValuesThreadUnsafe(event)\n\n\tc.Lock()\n\tdefer c.Unlock()\n\n\tc.dispatching = true\n\t// We are reusing the slice to avoid memory reallocations in every\n\t// dispatchEvent() call. That may prevent Go GC from freeing items\n\t// from previous phases that are sitting behind the current length\n\t// of the slice, but there is only a limited number of those and the\n\t// gain from avoiding memory allocations is much bigger.\n\tc.watchersBuffer = c.watchersBuffer[:0]\n\n\tif event.Type == watch.Bookmark {\n\t\tc.startDispatchingBookmarkEventsLocked()\n\t\t// return here to reduce following code indentation and diff\n\t\treturn\n\t}\n\n\t// iterate over watchers for each applicable namespace/name tuple\n\tnamespace := event.ObjFields[\"metadata.namespace\"]\n\tname := event.ObjFields[\"metadata.name\"]\n\tif len(namespace) \u003e 0 {\n\t\tif len(name) \u003e 0 {\n\t\t\t// namespaced watchers scoped by name\n\t\t\tfor _, watcher := range c.watchers.allWatchers[namespacedName{namespace: namespace, name: name}] {\n\t\t\t\tc.watchersBuffer = append(c.watchersBuffer, watcher)\n\t\t\t}\n\t\t}\n\t\t// namespaced watchers not scoped by name\n\t\tfor _, watcher := range c.watchers.allWatchers[namespacedName{namespace: namespace}] {\n\t\t\tc.watchersBuffer = append(c.watchersBuffer, watcher)\n\t\t}\n\t}\n\tif len(name) \u003e 0 {\n\t\t// cluster-wide watchers scoped by name\n\t\tfor _, watcher := range c.watchers.allWatchers[namespacedName{name: name}] {\n\t\t\tc.watchersBuffer = append(c.watchersBuffer, watcher)\n\t\t}\n\t}\n\t// cluster-wide watchers unscoped by name\n\tfor _, watcher := range c.watchers.allWatchers[namespacedName{}] {\n\t\tc.watchersBuffer = append(c.watchersBuffer, watcher)\n\t}\n\n\tif supported {\n\t\t// Iterate over watchers interested in the given values of the trigger.\n\t\tfor _, triggerValue := range triggerValues {\n\t\t\tfor _, watcher := range c.watchers.valueWatchers[triggerValue] {\n\t\t\t\tc.watchersBuffer = append(c.watchersBuffer, watcher)\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// supported equal to false generally means that trigger function\n\t\t// is not defined (or not aware of any indexes). In this case,\n\t\t// watchers filters should generally also don't generate any\n\t\t// trigger values, but can cause problems in case of some\n\t\t// misconfiguration. Thus we paranoidly leave this branch.\n\n\t\t// Iterate over watchers interested in exact values for all values.\n\t\tfor _, watchers := range c.watchers.valueWatchers {\n\t\t\tfor _, watcher := range watchers {\n\t\t\t\tc.watchersBuffer = append(c.watchersBuffer, watcher)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":1051,"to":1123}} {"id":100018450,"name":"finishDispatching","signature":"func (c *Cacher) finishDispatching()","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// finishDispatching stops all the watchers that were supposed to be\n// stopped in the meantime, but it was deferred to avoid closing input\n// channels of watchers, as add() may still have writing to it.\n// It also marks dispatching as false.\nfunc (c *Cacher) finishDispatching() {\n\tc.Lock()\n\tdefer c.Unlock()\n\tc.dispatching = false\n\tfor _, watcher := range c.watchersToStop {\n\t\twatcher.stopLocked()\n\t}\n\tc.watchersToStop = c.watchersToStop[:0]\n\n\tfor _, watcher := range c.expiredBookmarkWatchers {\n\t\tif watcher.stopped {\n\t\t\tcontinue\n\t\t}\n\t\t// requeue the watcher for the next bookmark if needed.\n\t\tc.bookmarkWatchers.addWatcher(watcher)\n\t}\n\tc.expiredBookmarkWatchers = c.expiredBookmarkWatchers[:0]\n}","line":{"from":1125,"to":1146}} {"id":100018451,"name":"terminateAllWatchers","signature":"func (c *Cacher) terminateAllWatchers()","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"func (c *Cacher) terminateAllWatchers() {\n\tc.Lock()\n\tdefer c.Unlock()\n\tc.watchers.terminateAll(c.groupResource, c.stopWatcherLocked)\n}","line":{"from":1148,"to":1152}} {"id":100018452,"name":"stopWatcherLocked","signature":"func (c *Cacher) stopWatcherLocked(watcher *cacheWatcher)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"func (c *Cacher) stopWatcherLocked(watcher *cacheWatcher) {\n\tif c.dispatching {\n\t\tc.watchersToStop = append(c.watchersToStop, watcher)\n\t} else {\n\t\twatcher.stopLocked()\n\t}\n}","line":{"from":1154,"to":1160}} {"id":100018453,"name":"isStopped","signature":"func (c *Cacher) isStopped() bool","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"func (c *Cacher) isStopped() bool {\n\tc.stopLock.RLock()\n\tdefer c.stopLock.RUnlock()\n\treturn c.stopped\n}","line":{"from":1162,"to":1166}} {"id":100018454,"name":"Stop","signature":"func (c *Cacher) Stop()","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// Stop implements the graceful termination.\nfunc (c *Cacher) Stop() {\n\tc.stopLock.Lock()\n\tif c.stopped {\n\t\t// avoid stopping twice (note: cachers are shared with subresources)\n\t\tc.stopLock.Unlock()\n\t\treturn\n\t}\n\tc.stopped = true\n\tc.ready.stop()\n\tc.stopLock.Unlock()\n\tclose(c.stopCh)\n\tc.stopWg.Wait()\n}","line":{"from":1168,"to":1181}} {"id":100018455,"name":"forgetWatcher","signature":"func forgetWatcher(c *Cacher, w *cacheWatcher, index int, scope namespacedName, triggerValue string, triggerSupported bool) func(bool)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"func forgetWatcher(c *Cacher, w *cacheWatcher, index int, scope namespacedName, triggerValue string, triggerSupported bool) func(bool) {\n\treturn func(drainWatcher bool) {\n\t\tc.Lock()\n\t\tdefer c.Unlock()\n\n\t\tw.setDrainInputBufferLocked(drainWatcher)\n\n\t\t// It's possible that the watcher is already not in the structure (e.g. in case of\n\t\t// simultaneous Stop() and terminateAllWatchers(), but it is safe to call stopLocked()\n\t\t// on a watcher multiple times.\n\t\tc.watchers.deleteWatcher(index, scope, triggerValue, triggerSupported, c.stopWatcherLocked)\n\t}\n}","line":{"from":1183,"to":1195}} {"id":100018456,"name":"filterWithAttrsFunction","signature":"func filterWithAttrsFunction(key string, p storage.SelectionPredicate) filterWithAttrsFunc","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"func filterWithAttrsFunction(key string, p storage.SelectionPredicate) filterWithAttrsFunc {\n\tfilterFunc := func(objKey string, label labels.Set, field fields.Set) bool {\n\t\tif !hasPathPrefix(objKey, key) {\n\t\t\treturn false\n\t\t}\n\t\treturn p.MatchesObjectAttributes(label, field)\n\t}\n\treturn filterFunc\n}","line":{"from":1197,"to":1205}} {"id":100018457,"name":"LastSyncResourceVersion","signature":"func (c *Cacher) LastSyncResourceVersion() (uint64, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// LastSyncResourceVersion returns resource version to which the underlying cache is synced.\nfunc (c *Cacher) LastSyncResourceVersion() (uint64, error) {\n\tif err := c.ready.wait(context.Background()); err != nil {\n\t\treturn 0, errors.NewServiceUnavailable(err.Error())\n\t}\n\n\tresourceVersion := c.reflector.LastSyncResourceVersion()\n\treturn c.versioner.ParseResourceVersion(resourceVersion)\n}","line":{"from":1207,"to":1215}} {"id":100018458,"name":"getCurrentResourceVersionFromStorage","signature":"func (c *Cacher) getCurrentResourceVersionFromStorage(ctx context.Context) (uint64, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// getCurrentResourceVersionFromStorage gets the current resource version from the underlying storage engine.\n// this method issues an empty list request and reads only the ResourceVersion from the object metadata\nfunc (c *Cacher) getCurrentResourceVersionFromStorage(ctx context.Context) (uint64, error) {\n\tif c.newListFunc == nil {\n\t\treturn 0, fmt.Errorf(\"newListFunction wasn't provided for %v\", c.objectType)\n\t}\n\temptyList := c.newListFunc()\n\tpred := storage.SelectionPredicate{\n\t\tLabel: labels.Everything(),\n\t\tField: fields.Everything(),\n\t\tLimit: 1, // just in case we actually hit something\n\t}\n\n\terr := c.storage.GetList(ctx, c.resourcePrefix, storage.ListOptions{Predicate: pred}, emptyList)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\temptyListAccessor, err := meta.ListAccessor(emptyList)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif emptyListAccessor == nil {\n\t\treturn 0, fmt.Errorf(\"unable to extract a list accessor from %T\", emptyList)\n\t}\n\n\tcurrentResourceVersion, err := strconv.Atoi(emptyListAccessor.GetResourceVersion())\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif currentResourceVersion == 0 {\n\t\treturn 0, fmt.Errorf(\"the current resource version must be greater than 0\")\n\t}\n\treturn uint64(currentResourceVersion), nil\n}","line":{"from":1217,"to":1251}} {"id":100018459,"name":"getBookmarkAfterResourceVersionLockedFunc","signature":"func (c *Cacher) getBookmarkAfterResourceVersionLockedFunc(ctx context.Context, parsedResourceVersion uint64, opts storage.ListOptions) (func() uint64, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// getBookmarkAfterResourceVersionLockedFunc returns a function that\n// spits a ResourceVersion after which the bookmark event will be delivered.\n//\n// The returned function must be called under the watchCache lock.\nfunc (c *Cacher) getBookmarkAfterResourceVersionLockedFunc(ctx context.Context, parsedResourceVersion uint64, opts storage.ListOptions) (func() uint64, error) {\n\tif opts.SendInitialEvents == nil || *opts.SendInitialEvents == false || !opts.Predicate.AllowWatchBookmarks {\n\t\treturn func() uint64 { return 0 }, nil\n\t}\n\treturn c.getCommonResourceVersionLockedFunc(ctx, parsedResourceVersion, opts)\n}","line":{"from":1253,"to":1262}} {"id":100018460,"name":"getStartResourceVersionForWatchLockedFunc","signature":"func (c *Cacher) getStartResourceVersionForWatchLockedFunc(ctx context.Context, parsedWatchResourceVersion uint64, opts storage.ListOptions) (func() uint64, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// getStartResourceVersionForWatchLockedFunc returns a function that\n// spits a ResourceVersion the watch will be started from.\n// Depending on the input parameters the semantics of the returned ResourceVersion are:\n// - start at Exact (return parsedWatchResourceVersion)\n// - start at Most Recent (return an RV from etcd)\n// - start at Any (return the current watchCache's RV)\n//\n// The returned function must be called under the watchCache lock.\nfunc (c *Cacher) getStartResourceVersionForWatchLockedFunc(ctx context.Context, parsedWatchResourceVersion uint64, opts storage.ListOptions) (func() uint64, error) {\n\tif opts.SendInitialEvents == nil || *opts.SendInitialEvents == true {\n\t\treturn func() uint64 { return parsedWatchResourceVersion }, nil\n\t}\n\treturn c.getCommonResourceVersionLockedFunc(ctx, parsedWatchResourceVersion, opts)\n}","line":{"from":1264,"to":1277}} {"id":100018461,"name":"getCommonResourceVersionLockedFunc","signature":"func (c *Cacher) getCommonResourceVersionLockedFunc(ctx context.Context, parsedWatchResourceVersion uint64, opts storage.ListOptions) (func() uint64, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// getCommonResourceVersionLockedFunc a helper that simply computes a ResourceVersion\n// based on the input parameters. Please examine callers of this method to get more context.\n//\n// The returned function must be called under the watchCache lock.\nfunc (c *Cacher) getCommonResourceVersionLockedFunc(ctx context.Context, parsedWatchResourceVersion uint64, opts storage.ListOptions) (func() uint64, error) {\n\tswitch {\n\tcase len(opts.ResourceVersion) == 0:\n\t\trv, err := c.getCurrentResourceVersionFromStorage(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn func() uint64 { return rv }, nil\n\tcase parsedWatchResourceVersion == 0:\n\t\t// here we assume that watchCache locked is already held\n\t\treturn func() uint64 { return c.watchCache.resourceVersion }, nil\n\tdefault:\n\t\treturn func() uint64 { return parsedWatchResourceVersion }, nil\n\t}\n}","line":{"from":1279,"to":1297}} {"id":100018462,"name":"waitUntilWatchCacheFreshAndForceAllEvents","signature":"func (c *Cacher) waitUntilWatchCacheFreshAndForceAllEvents(ctx context.Context, requestedWatchRV uint64, opts storage.ListOptions) (bool, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// waitUntilWatchCacheFreshAndForceAllEvents waits until cache is at least\n// as fresh as given requestedWatchRV if sendInitialEvents was requested.\n// Additionally, it instructs the caller whether it should ask for\n// all events from the cache (full state) or not.\nfunc (c *Cacher) waitUntilWatchCacheFreshAndForceAllEvents(ctx context.Context, requestedWatchRV uint64, opts storage.ListOptions) (bool, error) {\n\tif opts.SendInitialEvents != nil \u0026\u0026 *opts.SendInitialEvents == true {\n\t\terr := c.watchCache.waitUntilFreshAndBlock(ctx, requestedWatchRV)\n\t\tdefer c.watchCache.RUnlock()\n\t\treturn err == nil, err\n\t}\n\treturn false, nil\n}","line":{"from":1299,"to":1310}} {"id":100018463,"name":"NewCacherListerWatcher","signature":"func NewCacherListerWatcher(storage storage.Interface, resourcePrefix string, newListFunc func() runtime.Object) cache.ListerWatcher","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// NewCacherListerWatcher returns a storage.Interface backed ListerWatcher.\nfunc NewCacherListerWatcher(storage storage.Interface, resourcePrefix string, newListFunc func() runtime.Object) cache.ListerWatcher {\n\treturn \u0026cacherListerWatcher{\n\t\tstorage: storage,\n\t\tresourcePrefix: resourcePrefix,\n\t\tnewListFunc: newListFunc,\n\t}\n}","line":{"from":1319,"to":1326}} {"id":100018464,"name":"List","signature":"func (lw *cacherListerWatcher) List(options metav1.ListOptions) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// Implements cache.ListerWatcher interface.\nfunc (lw *cacherListerWatcher) List(options metav1.ListOptions) (runtime.Object, error) {\n\tlist := lw.newListFunc()\n\tpred := storage.SelectionPredicate{\n\t\tLabel: labels.Everything(),\n\t\tField: fields.Everything(),\n\t\tLimit: options.Limit,\n\t\tContinue: options.Continue,\n\t}\n\n\tstorageOpts := storage.ListOptions{\n\t\tResourceVersionMatch: options.ResourceVersionMatch,\n\t\tPredicate: pred,\n\t\tRecursive: true,\n\t}\n\tif err := lw.storage.GetList(context.TODO(), lw.resourcePrefix, storageOpts, list); err != nil {\n\t\treturn nil, err\n\t}\n\treturn list, nil\n}","line":{"from":1328,"to":1347}} {"id":100018465,"name":"Watch","signature":"func (lw *cacherListerWatcher) Watch(options metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// Implements cache.ListerWatcher interface.\nfunc (lw *cacherListerWatcher) Watch(options metav1.ListOptions) (watch.Interface, error) {\n\topts := storage.ListOptions{\n\t\tResourceVersion: options.ResourceVersion,\n\t\tPredicate: storage.Everything,\n\t\tRecursive: true,\n\t\tProgressNotify: true,\n\t}\n\treturn lw.storage.Watch(context.TODO(), lw.resourcePrefix, opts)\n}","line":{"from":1349,"to":1358}} {"id":100018466,"name":"newErrWatcher","signature":"func newErrWatcher(err error) *errWatcher","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"func newErrWatcher(err error) *errWatcher {\n\t// Create an error event\n\terrEvent := watch.Event{Type: watch.Error}\n\tswitch err := err.(type) {\n\tcase runtime.Object:\n\t\terrEvent.Object = err\n\tcase *errors.StatusError:\n\t\terrEvent.Object = \u0026err.ErrStatus\n\tdefault:\n\t\terrEvent.Object = \u0026metav1.Status{\n\t\t\tStatus: metav1.StatusFailure,\n\t\t\tMessage: err.Error(),\n\t\t\tReason: metav1.StatusReasonInternalError,\n\t\t\tCode: http.StatusInternalServerError,\n\t\t}\n\t}\n\n\t// Create a watcher with room for a single event, populate it, and close the channel\n\twatcher := \u0026errWatcher{result: make(chan watch.Event, 1)}\n\twatcher.result \u003c- errEvent\n\tclose(watcher.result)\n\n\treturn watcher\n}","line":{"from":1365,"to":1388}} {"id":100018467,"name":"ResultChan","signature":"func (c *errWatcher) ResultChan() \u003c-chan watch.Event","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// Implements watch.Interface.\nfunc (c *errWatcher) ResultChan() \u003c-chan watch.Event {\n\treturn c.result\n}","line":{"from":1390,"to":1393}} {"id":100018468,"name":"Stop","signature":"func (c *errWatcher) Stop()","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// Implements watch.Interface.\nfunc (c *errWatcher) Stop() {\n\t// no-op\n}","line":{"from":1395,"to":1398}} {"id":100018469,"name":"newImmediateCloseWatcher","signature":"func newImmediateCloseWatcher() *immediateCloseWatcher","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"func newImmediateCloseWatcher() *immediateCloseWatcher {\n\twatcher := \u0026immediateCloseWatcher{result: make(chan watch.Event)}\n\tclose(watcher.result)\n\treturn watcher\n}","line":{"from":1405,"to":1409}} {"id":100018470,"name":"ResultChan","signature":"func (c *immediateCloseWatcher) ResultChan() \u003c-chan watch.Event","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// Implements watch.Interface.\nfunc (c *immediateCloseWatcher) ResultChan() \u003c-chan watch.Event {\n\treturn c.result\n}","line":{"from":1411,"to":1414}} {"id":100018471,"name":"Stop","signature":"func (c *immediateCloseWatcher) Stop()","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go","code":"// Implements watch.Interface.\nfunc (c *immediateCloseWatcher) Stop() {\n\t// no-op\n}","line":{"from":1416,"to":1419}} {"id":100018472,"name":"newCachingObject","signature":"func newCachingObject(object runtime.Object) (*cachingObject, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"// newCachingObject performs a deep copy of the given object and wraps it\n// into a cachingObject.\n// An error is returned if it's not possible to cast the object to\n// metav1.Object type.\nfunc newCachingObject(object runtime.Object) (*cachingObject, error) {\n\tif obj, ok := object.(metaRuntimeInterface); ok {\n\t\tresult := \u0026cachingObject{\n\t\t\tobject: obj,\n\t\t\tdeepCopied: false,\n\t\t}\n\t\tresult.serializations.Store(make(serializationsCache))\n\t\treturn result, nil\n\t}\n\treturn nil, fmt.Errorf(\"can't cast object to metav1.Object: %#v\", object)\n}","line":{"from":86,"to":100}} {"id":100018473,"name":"getSerializationResult","signature":"func (o *cachingObject) getSerializationResult(id runtime.Identifier) *serializationResult","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) getSerializationResult(id runtime.Identifier) *serializationResult {\n\t// Fast-path for getting from cache.\n\tserializations := o.serializations.Load().(serializationsCache)\n\tif result, exists := serializations[id]; exists {\n\t\treturn result\n\t}\n\n\t// Slow-path (that may require insert).\n\to.lock.Lock()\n\tdefer o.lock.Unlock()\n\n\tserializations = o.serializations.Load().(serializationsCache)\n\t// Check if in the meantime it wasn't inserted.\n\tif result, exists := serializations[id]; exists {\n\t\treturn result\n\t}\n\n\t// Insert an entry for \u003cid\u003e. This requires copy of existing map.\n\tnewSerializations := make(serializationsCache)\n\tfor k, v := range serializations {\n\t\tnewSerializations[k] = v\n\t}\n\tresult := \u0026serializationResult{}\n\tnewSerializations[id] = result\n\to.serializations.Store(newSerializations)\n\treturn result\n}","line":{"from":102,"to":128}} {"id":100018474,"name":"CacheEncode","signature":"func (o *cachingObject) CacheEncode(id runtime.Identifier, encode func(runtime.Object, io.Writer) error, w io.Writer) error","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"// CacheEncode implements runtime.CacheableObject interface.\n// It serializes the object and writes the result to given io.Writer trying\n// to first use the already cached result and falls back to a given encode\n// function in case of cache miss.\n// It assumes that for a given identifier, the encode function always encodes\n// each input object into the same output format.\nfunc (o *cachingObject) CacheEncode(id runtime.Identifier, encode func(runtime.Object, io.Writer) error, w io.Writer) error {\n\tresult := o.getSerializationResult(id)\n\tresult.once.Do(func() {\n\t\tbuffer := bytes.NewBuffer(nil)\n\t\t// TODO(wojtek-t): This is currently making a copy to avoid races\n\t\t// in cases where encoding is making subtle object modifications,\n\t\t// e.g. #82497\n\t\t// Figure out if we can somehow avoid this under some conditions.\n\t\tresult.err = encode(o.GetObject(), buffer)\n\t\tresult.raw = buffer.Bytes()\n\t})\n\t// Once invoked, fields of serialization will not change.\n\tif result.err != nil {\n\t\treturn result.err\n\t}\n\t_, err := w.Write(result.raw)\n\treturn err\n}","line":{"from":130,"to":153}} {"id":100018475,"name":"GetObject","signature":"func (o *cachingObject) GetObject() runtime.Object","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"// GetObject implements runtime.CacheableObject interface.\n// It returns deep-copy of the wrapped object to return ownership of it\n// to the called according to the contract of the interface.\nfunc (o *cachingObject) GetObject() runtime.Object {\n\to.lock.RLock()\n\tdefer o.lock.RUnlock()\n\treturn o.object.DeepCopyObject().(metaRuntimeInterface)\n}","line":{"from":155,"to":162}} {"id":100018476,"name":"GetObjectKind","signature":"func (o *cachingObject) GetObjectKind() schema.ObjectKind","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"// GetObjectKind implements runtime.Object interface.\nfunc (o *cachingObject) GetObjectKind() schema.ObjectKind {\n\to.lock.RLock()\n\tdefer o.lock.RUnlock()\n\treturn o.object.GetObjectKind()\n}","line":{"from":164,"to":169}} {"id":100018477,"name":"DeepCopyObject","signature":"func (o *cachingObject) DeepCopyObject() runtime.Object","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"// DeepCopyObject implements runtime.Object interface.\nfunc (o *cachingObject) DeepCopyObject() runtime.Object {\n\t// DeepCopyObject on cachingObject is not expected to be called anywhere.\n\t// However, to be on the safe-side, we implement it, though given the\n\t// cache is only an optimization we ignore copying it.\n\tresult := \u0026cachingObject{\n\t\tdeepCopied: true,\n\t}\n\tresult.serializations.Store(make(serializationsCache))\n\n\to.lock.RLock()\n\tdefer o.lock.RUnlock()\n\tresult.object = o.object.DeepCopyObject().(metaRuntimeInterface)\n\treturn result\n}","line":{"from":171,"to":185}} {"id":100018478,"name":"shouldLogCacheInvalidation","signature":"func shouldLogCacheInvalidation(now time.Time) bool","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"// shouldLogCacheInvalidation allows for logging cache-invalidation\n// at most once per second (to avoid spamming logs in case of issues).\nfunc shouldLogCacheInvalidation(now time.Time) bool {\n\tinvalidationCacheTimestampLock.Lock()\n\tdefer invalidationCacheTimestampLock.Unlock()\n\tif invalidationCacheTimestamp.Add(time.Second).Before(now) {\n\t\tinvalidationCacheTimestamp = now\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":192,"to":202}} {"id":100018479,"name":"invalidateCacheLocked","signature":"func (o *cachingObject) invalidateCacheLocked()","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) invalidateCacheLocked() {\n\tif cache, ok := o.serializations.Load().(serializationsCache); ok \u0026\u0026 len(cache) == 0 {\n\t\treturn\n\t}\n\t// We don't expect cache invalidation to happen - so we want\n\t// to log the stacktrace to allow debugging if that will happen.\n\t// OTOH, we don't want to spam logs with it.\n\t// So we try to log it at most once per second.\n\tif shouldLogCacheInvalidation(time.Now()) {\n\t\tklog.Warningf(\"Unexpected cache invalidation for %#v\\n%s\", o.object, string(debug.Stack()))\n\t}\n\to.serializations.Store(make(serializationsCache))\n}","line":{"from":204,"to":216}} {"id":100018480,"name":"conditionalSet","signature":"func (o *cachingObject) conditionalSet(isNoop func() bool, set func())","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) conditionalSet(isNoop func() bool, set func()) {\n\tif fastPath := func() bool {\n\t\to.lock.RLock()\n\t\tdefer o.lock.RUnlock()\n\t\treturn isNoop()\n\t}(); fastPath {\n\t\treturn\n\t}\n\to.lock.Lock()\n\tdefer o.lock.Unlock()\n\tif isNoop() {\n\t\treturn\n\t}\n\tif !o.deepCopied {\n\t\to.object = o.object.DeepCopyObject().(metaRuntimeInterface)\n\t\to.deepCopied = true\n\t}\n\to.invalidateCacheLocked()\n\tset()\n}","line":{"from":223,"to":242}} {"id":100018481,"name":"GetNamespace","signature":"func (o *cachingObject) GetNamespace() string","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) GetNamespace() string {\n\to.lock.RLock()\n\tdefer o.lock.RUnlock()\n\treturn o.object.GetNamespace()\n}","line":{"from":244,"to":248}} {"id":100018482,"name":"SetNamespace","signature":"func (o *cachingObject) SetNamespace(namespace string)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) SetNamespace(namespace string) {\n\to.conditionalSet(\n\t\tfunc() bool { return o.object.GetNamespace() == namespace },\n\t\tfunc() { o.object.SetNamespace(namespace) },\n\t)\n}","line":{"from":249,"to":254}} {"id":100018483,"name":"GetName","signature":"func (o *cachingObject) GetName() string","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) GetName() string {\n\to.lock.RLock()\n\tdefer o.lock.RUnlock()\n\treturn o.object.GetName()\n}","line":{"from":255,"to":259}} {"id":100018484,"name":"SetName","signature":"func (o *cachingObject) SetName(name string)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) SetName(name string) {\n\to.conditionalSet(\n\t\tfunc() bool { return o.object.GetName() == name },\n\t\tfunc() { o.object.SetName(name) },\n\t)\n}","line":{"from":260,"to":265}} {"id":100018485,"name":"GetGenerateName","signature":"func (o *cachingObject) GetGenerateName() string","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) GetGenerateName() string {\n\to.lock.RLock()\n\tdefer o.lock.RUnlock()\n\treturn o.object.GetGenerateName()\n}","line":{"from":266,"to":270}} {"id":100018486,"name":"SetGenerateName","signature":"func (o *cachingObject) SetGenerateName(name string)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) SetGenerateName(name string) {\n\to.conditionalSet(\n\t\tfunc() bool { return o.object.GetGenerateName() == name },\n\t\tfunc() { o.object.SetGenerateName(name) },\n\t)\n}","line":{"from":271,"to":276}} {"id":100018487,"name":"GetUID","signature":"func (o *cachingObject) GetUID() types.UID","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) GetUID() types.UID {\n\to.lock.RLock()\n\tdefer o.lock.RUnlock()\n\treturn o.object.GetUID()\n}","line":{"from":277,"to":281}} {"id":100018488,"name":"SetUID","signature":"func (o *cachingObject) SetUID(uid types.UID)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) SetUID(uid types.UID) {\n\to.conditionalSet(\n\t\tfunc() bool { return o.object.GetUID() == uid },\n\t\tfunc() { o.object.SetUID(uid) },\n\t)\n}","line":{"from":282,"to":287}} {"id":100018489,"name":"GetResourceVersion","signature":"func (o *cachingObject) GetResourceVersion() string","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) GetResourceVersion() string {\n\to.lock.RLock()\n\tdefer o.lock.RUnlock()\n\treturn o.object.GetResourceVersion()\n}","line":{"from":288,"to":292}} {"id":100018490,"name":"SetResourceVersion","signature":"func (o *cachingObject) SetResourceVersion(version string)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) SetResourceVersion(version string) {\n\to.conditionalSet(\n\t\tfunc() bool { return o.object.GetResourceVersion() == version },\n\t\tfunc() { o.object.SetResourceVersion(version) },\n\t)\n}","line":{"from":293,"to":298}} {"id":100018491,"name":"GetGeneration","signature":"func (o *cachingObject) GetGeneration() int64","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) GetGeneration() int64 {\n\to.lock.RLock()\n\tdefer o.lock.RUnlock()\n\treturn o.object.GetGeneration()\n}","line":{"from":299,"to":303}} {"id":100018492,"name":"SetGeneration","signature":"func (o *cachingObject) SetGeneration(generation int64)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) SetGeneration(generation int64) {\n\to.conditionalSet(\n\t\tfunc() bool { return o.object.GetGeneration() == generation },\n\t\tfunc() { o.object.SetGeneration(generation) },\n\t)\n}","line":{"from":304,"to":309}} {"id":100018493,"name":"GetSelfLink","signature":"func (o *cachingObject) GetSelfLink() string","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) GetSelfLink() string {\n\to.lock.RLock()\n\tdefer o.lock.RUnlock()\n\treturn o.object.GetSelfLink()\n}","line":{"from":310,"to":314}} {"id":100018494,"name":"SetSelfLink","signature":"func (o *cachingObject) SetSelfLink(selfLink string)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) SetSelfLink(selfLink string) {\n\to.conditionalSet(\n\t\tfunc() bool { return o.object.GetSelfLink() == selfLink },\n\t\tfunc() { o.object.SetSelfLink(selfLink) },\n\t)\n}","line":{"from":315,"to":320}} {"id":100018495,"name":"GetCreationTimestamp","signature":"func (o *cachingObject) GetCreationTimestamp() metav1.Time","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) GetCreationTimestamp() metav1.Time {\n\to.lock.RLock()\n\tdefer o.lock.RUnlock()\n\treturn o.object.GetCreationTimestamp()\n}","line":{"from":321,"to":325}} {"id":100018496,"name":"SetCreationTimestamp","signature":"func (o *cachingObject) SetCreationTimestamp(timestamp metav1.Time)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) SetCreationTimestamp(timestamp metav1.Time) {\n\to.conditionalSet(\n\t\tfunc() bool { return o.object.GetCreationTimestamp() == timestamp },\n\t\tfunc() { o.object.SetCreationTimestamp(timestamp) },\n\t)\n}","line":{"from":326,"to":331}} {"id":100018497,"name":"GetDeletionTimestamp","signature":"func (o *cachingObject) GetDeletionTimestamp() *metav1.Time","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) GetDeletionTimestamp() *metav1.Time {\n\to.lock.RLock()\n\tdefer o.lock.RUnlock()\n\treturn o.object.GetDeletionTimestamp()\n}","line":{"from":332,"to":336}} {"id":100018498,"name":"SetDeletionTimestamp","signature":"func (o *cachingObject) SetDeletionTimestamp(timestamp *metav1.Time)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) SetDeletionTimestamp(timestamp *metav1.Time) {\n\to.conditionalSet(\n\t\tfunc() bool { return o.object.GetDeletionTimestamp() == timestamp },\n\t\tfunc() { o.object.SetDeletionTimestamp(timestamp) },\n\t)\n}","line":{"from":337,"to":342}} {"id":100018499,"name":"GetDeletionGracePeriodSeconds","signature":"func (o *cachingObject) GetDeletionGracePeriodSeconds() *int64","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) GetDeletionGracePeriodSeconds() *int64 {\n\to.lock.RLock()\n\tdefer o.lock.RUnlock()\n\treturn o.object.GetDeletionGracePeriodSeconds()\n}","line":{"from":343,"to":347}} {"id":100018500,"name":"SetDeletionGracePeriodSeconds","signature":"func (o *cachingObject) SetDeletionGracePeriodSeconds(gracePeriodSeconds *int64)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) SetDeletionGracePeriodSeconds(gracePeriodSeconds *int64) {\n\to.conditionalSet(\n\t\tfunc() bool { return o.object.GetDeletionGracePeriodSeconds() == gracePeriodSeconds },\n\t\tfunc() { o.object.SetDeletionGracePeriodSeconds(gracePeriodSeconds) },\n\t)\n}","line":{"from":348,"to":353}} {"id":100018501,"name":"GetLabels","signature":"func (o *cachingObject) GetLabels() map[string]string","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) GetLabels() map[string]string {\n\to.lock.RLock()\n\tdefer o.lock.RUnlock()\n\treturn o.object.GetLabels()\n}","line":{"from":354,"to":358}} {"id":100018502,"name":"SetLabels","signature":"func (o *cachingObject) SetLabels(labels map[string]string)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) SetLabels(labels map[string]string) {\n\to.conditionalSet(\n\t\tfunc() bool { return reflect.DeepEqual(o.object.GetLabels(), labels) },\n\t\tfunc() { o.object.SetLabels(labels) },\n\t)\n}","line":{"from":359,"to":364}} {"id":100018503,"name":"GetAnnotations","signature":"func (o *cachingObject) GetAnnotations() map[string]string","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) GetAnnotations() map[string]string {\n\to.lock.RLock()\n\tdefer o.lock.RUnlock()\n\treturn o.object.GetAnnotations()\n}","line":{"from":365,"to":369}} {"id":100018504,"name":"SetAnnotations","signature":"func (o *cachingObject) SetAnnotations(annotations map[string]string)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) SetAnnotations(annotations map[string]string) {\n\to.conditionalSet(\n\t\tfunc() bool { return reflect.DeepEqual(o.object.GetAnnotations(), annotations) },\n\t\tfunc() { o.object.SetAnnotations(annotations) },\n\t)\n}","line":{"from":370,"to":375}} {"id":100018505,"name":"GetFinalizers","signature":"func (o *cachingObject) GetFinalizers() []string","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) GetFinalizers() []string {\n\to.lock.RLock()\n\tdefer o.lock.RUnlock()\n\treturn o.object.GetFinalizers()\n}","line":{"from":376,"to":380}} {"id":100018506,"name":"SetFinalizers","signature":"func (o *cachingObject) SetFinalizers(finalizers []string)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) SetFinalizers(finalizers []string) {\n\to.conditionalSet(\n\t\tfunc() bool { return reflect.DeepEqual(o.object.GetFinalizers(), finalizers) },\n\t\tfunc() { o.object.SetFinalizers(finalizers) },\n\t)\n}","line":{"from":381,"to":386}} {"id":100018507,"name":"GetOwnerReferences","signature":"func (o *cachingObject) GetOwnerReferences() []metav1.OwnerReference","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) GetOwnerReferences() []metav1.OwnerReference {\n\to.lock.RLock()\n\tdefer o.lock.RUnlock()\n\treturn o.object.GetOwnerReferences()\n}","line":{"from":387,"to":391}} {"id":100018508,"name":"SetOwnerReferences","signature":"func (o *cachingObject) SetOwnerReferences(references []metav1.OwnerReference)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) SetOwnerReferences(references []metav1.OwnerReference) {\n\to.conditionalSet(\n\t\tfunc() bool { return reflect.DeepEqual(o.object.GetOwnerReferences(), references) },\n\t\tfunc() { o.object.SetOwnerReferences(references) },\n\t)\n}","line":{"from":392,"to":397}} {"id":100018509,"name":"GetManagedFields","signature":"func (o *cachingObject) GetManagedFields() []metav1.ManagedFieldsEntry","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) GetManagedFields() []metav1.ManagedFieldsEntry {\n\to.lock.RLock()\n\tdefer o.lock.RUnlock()\n\treturn o.object.GetManagedFields()\n}","line":{"from":398,"to":402}} {"id":100018510,"name":"SetManagedFields","signature":"func (o *cachingObject) SetManagedFields(managedFields []metav1.ManagedFieldsEntry)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/caching_object.go","code":"func (o *cachingObject) SetManagedFields(managedFields []metav1.ManagedFieldsEntry) {\n\to.conditionalSet(\n\t\tfunc() bool { return reflect.DeepEqual(o.object.GetManagedFields(), managedFields) },\n\t\tfunc() { o.object.SetManagedFields(managedFields) },\n\t)\n}","line":{"from":403,"to":408}} {"id":100018511,"name":"Register","signature":"func Register()","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/metrics/metrics.go","code":"// Register all metrics.\nfunc Register() {\n\t// Register the metrics.\n\tregisterMetrics.Do(func() {\n\t\tlegacyregistry.MustRegister(listCacheCount)\n\t\tlegacyregistry.MustRegister(listCacheNumFetched)\n\t\tlegacyregistry.MustRegister(listCacheNumReturned)\n\t\tlegacyregistry.MustRegister(InitCounter)\n\t\tlegacyregistry.MustRegister(EventsReceivedCounter)\n\t\tlegacyregistry.MustRegister(EventsCounter)\n\t\tlegacyregistry.MustRegister(TerminatedWatchersCounter)\n\t\tlegacyregistry.MustRegister(watchCacheCapacityIncreaseTotal)\n\t\tlegacyregistry.MustRegister(watchCacheCapacityDecreaseTotal)\n\t\tlegacyregistry.MustRegister(WatchCacheCapacity)\n\t\tlegacyregistry.MustRegister(WatchCacheInitializations)\n\t})\n}","line":{"from":153,"to":169}} {"id":100018512,"name":"RecordListCacheMetrics","signature":"func RecordListCacheMetrics(resourcePrefix, indexName string, numFetched, numReturned int)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/metrics/metrics.go","code":"// RecordListCacheMetrics notes various metrics of the cost to serve a LIST request\nfunc RecordListCacheMetrics(resourcePrefix, indexName string, numFetched, numReturned int) {\n\tlistCacheCount.WithLabelValues(resourcePrefix, indexName).Inc()\n\tlistCacheNumFetched.WithLabelValues(resourcePrefix, indexName).Add(float64(numFetched))\n\tlistCacheNumReturned.WithLabelValues(resourcePrefix).Add(float64(numReturned))\n}","line":{"from":171,"to":176}} {"id":100018513,"name":"RecordsWatchCacheCapacityChange","signature":"func RecordsWatchCacheCapacityChange(objType string, old, new int)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/metrics/metrics.go","code":"// RecordsWatchCacheCapacityChange record watchCache capacity resize(increase or decrease) operations.\nfunc RecordsWatchCacheCapacityChange(objType string, old, new int) {\n\tWatchCacheCapacity.WithLabelValues(objType).Set(float64(new))\n\tif old \u003c new {\n\t\twatchCacheCapacityIncreaseTotal.WithLabelValues(objType).Inc()\n\t\treturn\n\t}\n\twatchCacheCapacityDecreaseTotal.WithLabelValues(objType).Inc()\n}","line":{"from":178,"to":186}} {"id":100018514,"name":"newReady","signature":"func newReady() *ready","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/ready.go","code":"func newReady() *ready {\n\treturn \u0026ready{\n\t\twaitCh: make(chan struct{}),\n\t\tstate: Pending,\n\t}\n}","line":{"from":48,"to":53}} {"id":100018515,"name":"done","signature":"func (r *ready) done() chan struct{}","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/ready.go","code":"// done close the channel once the state is Ready or Stopped\nfunc (r *ready) done() chan struct{} {\n\tr.restartLock.Lock()\n\tdefer r.restartLock.Unlock()\n\treturn r.waitCh\n}","line":{"from":55,"to":60}} {"id":100018516,"name":"wait","signature":"func (r *ready) wait(ctx context.Context) error","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/ready.go","code":"// wait blocks until it is Ready or Stopped, it returns an error if is Stopped.\nfunc (r *ready) wait(ctx context.Context) error {\n\t_, err := r.waitAndReadGeneration(ctx)\n\treturn err\n}","line":{"from":62,"to":66}} {"id":100018517,"name":"waitAndReadGeneration","signature":"func (r *ready) waitAndReadGeneration(ctx context.Context) (int, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/ready.go","code":"// waitAndReadGenration blocks until it is Ready or Stopped and returns number\n// of times we entered ready state if Ready and error otherwise.\nfunc (r *ready) waitAndReadGeneration(ctx context.Context) (int, error) {\n\tfor {\n\t\t// r.done() only blocks if state is Pending\n\t\tselect {\n\t\tcase \u003c-ctx.Done():\n\t\t\treturn 0, ctx.Err()\n\t\tcase \u003c-r.done():\n\t\t}\n\n\t\tr.lock.RLock()\n\t\tswitch r.state {\n\t\tcase Pending:\n\t\t\t// since we allow to switch between the states Pending and Ready\n\t\t\t// if there is a quick transition from Pending -\u003e Ready -\u003e Pending\n\t\t\t// a process that was waiting can get unblocked and see a Pending\n\t\t\t// state again. If the state is Pending we have to wait again to\n\t\t\t// avoid an inconsistent state on the system, with some processes not\n\t\t\t// waiting despite the state moved back to Pending.\n\t\t\tr.lock.RUnlock()\n\t\tcase Ready:\n\t\t\tgeneration := r.generation\n\t\t\tr.lock.RUnlock()\n\t\t\treturn generation, nil\n\t\tcase Stopped:\n\t\t\tr.lock.RUnlock()\n\t\t\treturn 0, fmt.Errorf(\"apiserver cacher is stopped\")\n\t\tdefault:\n\t\t\tr.lock.RUnlock()\n\t\t\treturn 0, fmt.Errorf(\"unexpected apiserver cache state: %v\", r.state)\n\t\t}\n\t}\n}","line":{"from":68,"to":101}} {"id":100018518,"name":"check","signature":"func (r *ready) check() bool","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/ready.go","code":"// check returns true only if it is Ready.\nfunc (r *ready) check() bool {\n\t_, ok := r.checkAndReadGeneration()\n\treturn ok\n}","line":{"from":103,"to":107}} {"id":100018519,"name":"checkAndReadGeneration","signature":"func (r *ready) checkAndReadGeneration() (int, bool)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/ready.go","code":"// checkAndReadGeneration returns the current generation and whether it is Ready.\nfunc (r *ready) checkAndReadGeneration() (int, bool) {\n\tr.lock.RLock()\n\tdefer r.lock.RUnlock()\n\treturn r.generation, r.state == Ready\n}","line":{"from":109,"to":114}} {"id":100018520,"name":"set","signature":"func (r *ready) set(ok bool)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/ready.go","code":"// set the state to Pending (false) or Ready (true), it does not have effect if the state is Stopped.\nfunc (r *ready) set(ok bool) {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\tif r.state == Stopped {\n\t\treturn\n\t}\n\tif ok \u0026\u0026 r.state == Pending {\n\t\tr.state = Ready\n\t\tr.generation++\n\t\tselect {\n\t\tcase \u003c-r.waitCh:\n\t\tdefault:\n\t\t\tclose(r.waitCh)\n\t\t}\n\t} else if !ok \u0026\u0026 r.state == Ready {\n\t\t// creating the waitCh can be racy if\n\t\t// something enter the wait() method\n\t\tselect {\n\t\tcase \u003c-r.waitCh:\n\t\t\tr.restartLock.Lock()\n\t\t\tr.waitCh = make(chan struct{})\n\t\t\tr.restartLock.Unlock()\n\t\tdefault:\n\t\t}\n\t\tr.state = Pending\n\t}\n}","line":{"from":116,"to":143}} {"id":100018521,"name":"stop","signature":"func (r *ready) stop()","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/ready.go","code":"// stop the condition variable and set it as Stopped. This state is irreversible.\nfunc (r *ready) stop() {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\tif r.state != Stopped {\n\t\tr.state = Stopped\n\t}\n\tselect {\n\tcase \u003c-r.waitCh:\n\tdefault:\n\t\tclose(r.waitCh)\n\t}\n}","line":{"from":145,"to":157}} {"id":100018522,"name":"newTimeBudget","signature":"func newTimeBudget() timeBudget","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/time_budget.go","code":"func newTimeBudget() timeBudget {\n\tresult := \u0026timeBudgetImpl{\n\t\tclock: clock.RealClock{},\n\t\tbudget: time.Duration(0),\n\t\trefresh: refreshPerSecond,\n\t\tmaxBudget: maxBudget,\n\t}\n\tresult.last = result.clock.Now()\n\treturn result\n}","line":{"from":60,"to":69}} {"id":100018523,"name":"takeAvailable","signature":"func (t *timeBudgetImpl) takeAvailable() time.Duration","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/time_budget.go","code":"func (t *timeBudgetImpl) takeAvailable() time.Duration {\n\tt.Lock()\n\tdefer t.Unlock()\n\t// budget accumulated since last access\n\tnow := t.clock.Now()\n\tacc := now.Sub(t.last).Seconds() * t.refresh.Seconds()\n\tif acc \u003c 0 {\n\t\tacc = 0\n\t}\n\t// update current budget and store the current time\n\tif t.budget = t.budget + time.Duration(acc*1e9); t.budget \u003e t.maxBudget {\n\t\tt.budget = t.maxBudget\n\t}\n\tt.last = now\n\tresult := t.budget\n\tt.budget = time.Duration(0)\n\treturn result\n}","line":{"from":71,"to":88}} {"id":100018524,"name":"returnUnused","signature":"func (t *timeBudgetImpl) returnUnused(unused time.Duration)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/time_budget.go","code":"func (t *timeBudgetImpl) returnUnused(unused time.Duration) {\n\tt.Lock()\n\tdefer t.Unlock()\n\tif unused \u003c 0 {\n\t\t// We used more than allowed.\n\t\treturn\n\t}\n\t// add the unused time directly to the budget\n\t// takeAvailable() will take into account the elapsed time\n\tif t.budget = t.budget + unused; t.budget \u003e t.maxBudget {\n\t\tt.budget = t.maxBudget\n\t}\n}","line":{"from":90,"to":102}} {"id":100018525,"name":"hasPathPrefix","signature":"func hasPathPrefix(s, pathPrefix string) bool","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/util.go","code":"// hasPathPrefix returns true if the string matches pathPrefix exactly, or if is prefixed with pathPrefix at a path segment boundary\nfunc hasPathPrefix(s, pathPrefix string) bool {\n\t// Short circuit if s doesn't contain the prefix at all\n\tif !strings.HasPrefix(s, pathPrefix) {\n\t\treturn false\n\t}\n\n\tpathPrefixLength := len(pathPrefix)\n\n\tif len(s) == pathPrefixLength {\n\t\t// Exact match\n\t\treturn true\n\t}\n\tif strings.HasSuffix(pathPrefix, \"/\") {\n\t\t// pathPrefix already ensured a path segment boundary\n\t\treturn true\n\t}\n\tif s[pathPrefixLength:pathPrefixLength+1] == \"/\" {\n\t\t// The next character in s is a path segment boundary\n\t\t// Check this instead of normalizing pathPrefix to avoid allocating on every call\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":23,"to":46}} {"id":100018526,"name":"max","signature":"func max(a, b int) int","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/util.go","code":"func max(a, b int) int {\n\tif a \u003e b {\n\t\treturn a\n\t}\n\treturn b\n}","line":{"from":48,"to":53}} {"id":100018527,"name":"min","signature":"func min(a, b int) int","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/util.go","code":"func min(a, b int) int {\n\tif a \u003c b {\n\t\treturn a\n\t}\n\treturn b\n}","line":{"from":55,"to":60}} {"id":100018528,"name":"storeElementKey","signature":"func storeElementKey(obj interface{}) (string, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"func storeElementKey(obj interface{}) (string, error) {\n\telem, ok := obj.(*storeElement)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"not a storeElement: %v\", obj)\n\t}\n\treturn elem.Key, nil\n}","line":{"from":95,"to":101}} {"id":100018529,"name":"storeElementObject","signature":"func storeElementObject(obj interface{}) (runtime.Object, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"func storeElementObject(obj interface{}) (runtime.Object, error) {\n\telem, ok := obj.(*storeElement)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"not a storeElement: %v\", obj)\n\t}\n\treturn elem.Object, nil\n}","line":{"from":103,"to":109}} {"id":100018530,"name":"storeElementIndexFunc","signature":"func storeElementIndexFunc(objIndexFunc cache.IndexFunc) cache.IndexFunc","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"func storeElementIndexFunc(objIndexFunc cache.IndexFunc) cache.IndexFunc {\n\treturn func(obj interface{}) (strings []string, e error) {\n\t\tseo, err := storeElementObject(obj)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn objIndexFunc(seo)\n\t}\n}","line":{"from":111,"to":119}} {"id":100018531,"name":"storeElementIndexers","signature":"func storeElementIndexers(indexers *cache.Indexers) cache.Indexers","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"func storeElementIndexers(indexers *cache.Indexers) cache.Indexers {\n\tif indexers == nil {\n\t\treturn cache.Indexers{}\n\t}\n\tret := cache.Indexers{}\n\tfor indexName, indexFunc := range *indexers {\n\t\tret[indexName] = storeElementIndexFunc(indexFunc)\n\t}\n\treturn ret\n}","line":{"from":121,"to":130}} {"id":100018532,"name":"newWatchCache","signature":"func newWatchCache(","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"func newWatchCache(\n\tkeyFunc func(runtime.Object) (string, error),\n\teventHandler func(*watchCacheEvent),\n\tgetAttrsFunc func(runtime.Object) (labels.Set, fields.Set, error),\n\tversioner storage.Versioner,\n\tindexers *cache.Indexers,\n\tclock clock.Clock,\n\tgroupResource schema.GroupResource) *watchCache {\n\twc := \u0026watchCache{\n\t\tcapacity: defaultLowerBoundCapacity,\n\t\tkeyFunc: keyFunc,\n\t\tgetAttrsFunc: getAttrsFunc,\n\t\tcache: make([]*watchCacheEvent, defaultLowerBoundCapacity),\n\t\tlowerBoundCapacity: defaultLowerBoundCapacity,\n\t\tupperBoundCapacity: defaultUpperBoundCapacity,\n\t\tstartIndex: 0,\n\t\tendIndex: 0,\n\t\tstore: cache.NewIndexer(storeElementKey, storeElementIndexers(indexers)),\n\t\tresourceVersion: 0,\n\t\tlistResourceVersion: 0,\n\t\teventHandler: eventHandler,\n\t\tclock: clock,\n\t\tversioner: versioner,\n\t\tgroupResource: groupResource,\n\t}\n\tmetrics.WatchCacheCapacity.WithLabelValues(groupResource.String()).Set(float64(wc.capacity))\n\twc.cond = sync.NewCond(wc.RLocker())\n\twc.indexValidator = wc.isIndexValidLocked\n\n\treturn wc\n}","line":{"from":201,"to":231}} {"id":100018533,"name":"Add","signature":"func (w *watchCache) Add(obj interface{}) error","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"// Add takes runtime.Object as an argument.\nfunc (w *watchCache) Add(obj interface{}) error {\n\tobject, resourceVersion, err := w.objectToVersionedRuntimeObject(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\tevent := watch.Event{Type: watch.Added, Object: object}\n\n\tf := func(elem *storeElement) error { return w.store.Add(elem) }\n\treturn w.processEvent(event, resourceVersion, f)\n}","line":{"from":233,"to":243}} {"id":100018534,"name":"Update","signature":"func (w *watchCache) Update(obj interface{}) error","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"// Update takes runtime.Object as an argument.\nfunc (w *watchCache) Update(obj interface{}) error {\n\tobject, resourceVersion, err := w.objectToVersionedRuntimeObject(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\tevent := watch.Event{Type: watch.Modified, Object: object}\n\n\tf := func(elem *storeElement) error { return w.store.Update(elem) }\n\treturn w.processEvent(event, resourceVersion, f)\n}","line":{"from":245,"to":255}} {"id":100018535,"name":"Delete","signature":"func (w *watchCache) Delete(obj interface{}) error","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"// Delete takes runtime.Object as an argument.\nfunc (w *watchCache) Delete(obj interface{}) error {\n\tobject, resourceVersion, err := w.objectToVersionedRuntimeObject(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\tevent := watch.Event{Type: watch.Deleted, Object: object}\n\n\tf := func(elem *storeElement) error { return w.store.Delete(elem) }\n\treturn w.processEvent(event, resourceVersion, f)\n}","line":{"from":257,"to":267}} {"id":100018536,"name":"objectToVersionedRuntimeObject","signature":"func (w *watchCache) objectToVersionedRuntimeObject(obj interface{}) (runtime.Object, uint64, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"func (w *watchCache) objectToVersionedRuntimeObject(obj interface{}) (runtime.Object, uint64, error) {\n\tobject, ok := obj.(runtime.Object)\n\tif !ok {\n\t\treturn nil, 0, fmt.Errorf(\"obj does not implement runtime.Object interface: %v\", obj)\n\t}\n\tresourceVersion, err := w.versioner.ObjectResourceVersion(object)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\treturn object, resourceVersion, nil\n}","line":{"from":269,"to":279}} {"id":100018537,"name":"processEvent","signature":"func (w *watchCache) processEvent(event watch.Event, resourceVersion uint64, updateFunc func(*storeElement) error) error","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"// processEvent is safe as long as there is at most one call to it in flight\n// at any point in time.\nfunc (w *watchCache) processEvent(event watch.Event, resourceVersion uint64, updateFunc func(*storeElement) error) error {\n\tmetrics.EventsReceivedCounter.WithLabelValues(w.groupResource.String()).Inc()\n\n\tkey, err := w.keyFunc(event.Object)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't compute key: %v\", err)\n\t}\n\telem := \u0026storeElement{Key: key, Object: event.Object}\n\telem.Labels, elem.Fields, err = w.getAttrsFunc(event.Object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twcEvent := \u0026watchCacheEvent{\n\t\tType: event.Type,\n\t\tObject: elem.Object,\n\t\tObjLabels: elem.Labels,\n\t\tObjFields: elem.Fields,\n\t\tKey: key,\n\t\tResourceVersion: resourceVersion,\n\t\tRecordTime: w.clock.Now(),\n\t}\n\n\tif err := func() error {\n\t\t// TODO: We should consider moving this lock below after the watchCacheEvent\n\t\t// is created. In such situation, the only problematic scenario is Replace(\n\t\t// happening after getting object from store and before acquiring a lock.\n\t\t// Maybe introduce another lock for this purpose.\n\t\tw.Lock()\n\t\tdefer w.Unlock()\n\n\t\tprevious, exists, err := w.store.Get(elem)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif exists {\n\t\t\tpreviousElem := previous.(*storeElement)\n\t\t\twcEvent.PrevObject = previousElem.Object\n\t\t\twcEvent.PrevObjLabels = previousElem.Labels\n\t\t\twcEvent.PrevObjFields = previousElem.Fields\n\t\t}\n\n\t\tw.updateCache(wcEvent)\n\t\tw.resourceVersion = resourceVersion\n\t\tdefer w.cond.Broadcast()\n\n\t\treturn updateFunc(elem)\n\t}(); err != nil {\n\t\treturn err\n\t}\n\n\t// Avoid calling event handler under lock.\n\t// This is safe as long as there is at most one call to Add/Update/Delete and\n\t// UpdateResourceVersion in flight at any point in time, which is true now,\n\t// because reflector calls them synchronously from its main thread.\n\tif w.eventHandler != nil {\n\t\tw.eventHandler(wcEvent)\n\t}\n\treturn nil\n}","line":{"from":281,"to":342}} {"id":100018538,"name":"updateCache","signature":"func (w *watchCache) updateCache(event *watchCacheEvent)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"// Assumes that lock is already held for write.\nfunc (w *watchCache) updateCache(event *watchCacheEvent) {\n\tw.resizeCacheLocked(event.RecordTime)\n\tif w.isCacheFullLocked() {\n\t\t// Cache is full - remove the oldest element.\n\t\tw.startIndex++\n\t\tw.removedEventSinceRelist = true\n\t}\n\tw.cache[w.endIndex%w.capacity] = event\n\tw.endIndex++\n}","line":{"from":344,"to":354}} {"id":100018539,"name":"resizeCacheLocked","signature":"func (w *watchCache) resizeCacheLocked(eventTime time.Time)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"// resizeCacheLocked resizes the cache if necessary:\n// - increases capacity by 2x if cache is full and all cached events occurred within last eventFreshDuration.\n// - decreases capacity by 2x when recent quarter of events occurred outside of eventFreshDuration(protect watchCache from flapping).\nfunc (w *watchCache) resizeCacheLocked(eventTime time.Time) {\n\tif w.isCacheFullLocked() \u0026\u0026 eventTime.Sub(w.cache[w.startIndex%w.capacity].RecordTime) \u003c eventFreshDuration {\n\t\tcapacity := min(w.capacity*2, w.upperBoundCapacity)\n\t\tif capacity \u003e w.capacity {\n\t\t\tw.doCacheResizeLocked(capacity)\n\t\t}\n\t\treturn\n\t}\n\tif w.isCacheFullLocked() \u0026\u0026 eventTime.Sub(w.cache[(w.endIndex-w.capacity/4)%w.capacity].RecordTime) \u003e eventFreshDuration {\n\t\tcapacity := max(w.capacity/2, w.lowerBoundCapacity)\n\t\tif capacity \u003c w.capacity {\n\t\t\tw.doCacheResizeLocked(capacity)\n\t\t}\n\t\treturn\n\t}\n}","line":{"from":356,"to":374}} {"id":100018540,"name":"isCacheFullLocked","signature":"func (w *watchCache) isCacheFullLocked() bool","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"// isCacheFullLocked used to judge whether watchCacheEvent is full.\n// Assumes that lock is already held for write.\nfunc (w *watchCache) isCacheFullLocked() bool {\n\treturn w.endIndex == w.startIndex+w.capacity\n}","line":{"from":376,"to":380}} {"id":100018541,"name":"doCacheResizeLocked","signature":"func (w *watchCache) doCacheResizeLocked(capacity int)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"// doCacheResizeLocked resize watchCache's event array with different capacity.\n// Assumes that lock is already held for write.\nfunc (w *watchCache) doCacheResizeLocked(capacity int) {\n\tnewCache := make([]*watchCacheEvent, capacity)\n\tif capacity \u003c w.capacity {\n\t\t// adjust startIndex if cache capacity shrink.\n\t\tw.startIndex = w.endIndex - capacity\n\t}\n\tfor i := w.startIndex; i \u003c w.endIndex; i++ {\n\t\tnewCache[i%capacity] = w.cache[i%w.capacity]\n\t}\n\tw.cache = newCache\n\tmetrics.RecordsWatchCacheCapacityChange(w.groupResource.String(), w.capacity, capacity)\n\tw.capacity = capacity\n}","line":{"from":382,"to":396}} {"id":100018542,"name":"UpdateResourceVersion","signature":"func (w *watchCache) UpdateResourceVersion(resourceVersion string)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"func (w *watchCache) UpdateResourceVersion(resourceVersion string) {\n\trv, err := w.versioner.ParseResourceVersion(resourceVersion)\n\tif err != nil {\n\t\tklog.Errorf(\"Couldn't parse resourceVersion: %v\", err)\n\t\treturn\n\t}\n\n\tfunc() {\n\t\tw.Lock()\n\t\tdefer w.Unlock()\n\t\tw.resourceVersion = rv\n\t}()\n\n\t// Avoid calling event handler under lock.\n\t// This is safe as long as there is at most one call to Add/Update/Delete and\n\t// UpdateResourceVersion in flight at any point in time, which is true now,\n\t// because reflector calls them synchronously from its main thread.\n\tif w.eventHandler != nil {\n\t\twcEvent := \u0026watchCacheEvent{\n\t\t\tType: watch.Bookmark,\n\t\t\tResourceVersion: rv,\n\t\t}\n\t\tw.eventHandler(wcEvent)\n\t}\n}","line":{"from":398,"to":422}} {"id":100018543,"name":"List","signature":"func (w *watchCache) List() []interface{}","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"// List returns list of pointers to \u003cstoreElement\u003e objects.\nfunc (w *watchCache) List() []interface{} {\n\treturn w.store.List()\n}","line":{"from":424,"to":427}} {"id":100018544,"name":"waitUntilFreshAndBlock","signature":"func (w *watchCache) waitUntilFreshAndBlock(ctx context.Context, resourceVersion uint64) error","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"// waitUntilFreshAndBlock waits until cache is at least as fresh as given \u003cresourceVersion\u003e.\n// NOTE: This function acquired lock and doesn't release it.\n// You HAVE TO explicitly call w.RUnlock() after this function.\nfunc (w *watchCache) waitUntilFreshAndBlock(ctx context.Context, resourceVersion uint64) error {\n\tstartTime := w.clock.Now()\n\n\t// In case resourceVersion is 0, we accept arbitrarily stale result.\n\t// As a result, the condition in the below for loop will never be\n\t// satisfied (w.resourceVersion is never negative), this call will\n\t// never hit the w.cond.Wait().\n\t// As a result - we can optimize the code by not firing the wakeup\n\t// function (and avoid starting a gorotuine), especially given that\n\t// resourceVersion=0 is the most common case.\n\tif resourceVersion \u003e 0 {\n\t\tgo func() {\n\t\t\t// Wake us up when the time limit has expired. The docs\n\t\t\t// promise that time.After (well, NewTimer, which it calls)\n\t\t\t// will wait *at least* the duration given. Since this go\n\t\t\t// routine starts sometime after we record the start time, and\n\t\t\t// it will wake up the loop below sometime after the broadcast,\n\t\t\t// we don't need to worry about waking it up before the time\n\t\t\t// has expired accidentally.\n\t\t\t\u003c-w.clock.After(blockTimeout)\n\t\t\tw.cond.Broadcast()\n\t\t}()\n\t}\n\n\tw.RLock()\n\tspan := tracing.SpanFromContext(ctx)\n\tspan.AddEvent(\"watchCache locked acquired\")\n\tfor w.resourceVersion \u003c resourceVersion {\n\t\tif w.clock.Since(startTime) \u003e= blockTimeout {\n\t\t\t// Request that the client retry after 'resourceVersionTooHighRetrySeconds' seconds.\n\t\t\treturn storage.NewTooLargeResourceVersionError(resourceVersion, w.resourceVersion, resourceVersionTooHighRetrySeconds)\n\t\t}\n\t\tw.cond.Wait()\n\t}\n\tspan.AddEvent(\"watchCache fresh enough\")\n\treturn nil\n}","line":{"from":429,"to":468}} {"id":100018545,"name":"Len","signature":"func (s sortableStoreElements) Len() int","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"func (s sortableStoreElements) Len() int {\n\treturn len(s)\n}","line":{"from":472,"to":474}} {"id":100018546,"name":"Less","signature":"func (s sortableStoreElements) Less(i, j int) bool","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"func (s sortableStoreElements) Less(i, j int) bool {\n\treturn s[i].(*storeElement).Key \u003c s[j].(*storeElement).Key\n}","line":{"from":476,"to":478}} {"id":100018547,"name":"Swap","signature":"func (s sortableStoreElements) Swap(i, j int)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"func (s sortableStoreElements) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}","line":{"from":480,"to":482}} {"id":100018548,"name":"WaitUntilFreshAndList","signature":"func (w *watchCache) WaitUntilFreshAndList(ctx context.Context, resourceVersion uint64, matchValues []storage.MatchValue) ([]interface{}, uint64, string, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"// WaitUntilFreshAndList returns list of pointers to `storeElement` objects along\n// with their ResourceVersion and the name of the index, if any, that was used.\nfunc (w *watchCache) WaitUntilFreshAndList(ctx context.Context, resourceVersion uint64, matchValues []storage.MatchValue) ([]interface{}, uint64, string, error) {\n\terr := w.waitUntilFreshAndBlock(ctx, resourceVersion)\n\tdefer w.RUnlock()\n\tif err != nil {\n\t\treturn nil, 0, \"\", err\n\t}\n\n\tresult, rv, index, err := func() ([]interface{}, uint64, string, error) {\n\t\t// This isn't the place where we do \"final filtering\" - only some \"prefiltering\" is happening here. So the only\n\t\t// requirement here is to NOT miss anything that should be returned. We can return as many non-matching items as we\n\t\t// want - they will be filtered out later. The fact that we return less things is only further performance improvement.\n\t\t// TODO: if multiple indexes match, return the one with the fewest items, so as to do as much filtering as possible.\n\t\tfor _, matchValue := range matchValues {\n\t\t\tif result, err := w.store.ByIndex(matchValue.IndexName, matchValue.Value); err == nil {\n\t\t\t\treturn result, w.resourceVersion, matchValue.IndexName, nil\n\t\t\t}\n\t\t}\n\t\treturn w.store.List(), w.resourceVersion, \"\", nil\n\t}()\n\n\tsort.Sort(sortableStoreElements(result))\n\treturn result, rv, index, err\n}","line":{"from":484,"to":508}} {"id":100018549,"name":"WaitUntilFreshAndGet","signature":"func (w *watchCache) WaitUntilFreshAndGet(ctx context.Context, resourceVersion uint64, key string) (interface{}, bool, uint64, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"// WaitUntilFreshAndGet returns a pointers to \u003cstoreElement\u003e object.\nfunc (w *watchCache) WaitUntilFreshAndGet(ctx context.Context, resourceVersion uint64, key string) (interface{}, bool, uint64, error) {\n\terr := w.waitUntilFreshAndBlock(ctx, resourceVersion)\n\tdefer w.RUnlock()\n\tif err != nil {\n\t\treturn nil, false, 0, err\n\t}\n\tvalue, exists, err := w.store.GetByKey(key)\n\treturn value, exists, w.resourceVersion, err\n}","line":{"from":510,"to":519}} {"id":100018550,"name":"ListKeys","signature":"func (w *watchCache) ListKeys() []string","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"func (w *watchCache) ListKeys() []string {\n\treturn w.store.ListKeys()\n}","line":{"from":521,"to":523}} {"id":100018551,"name":"Get","signature":"func (w *watchCache) Get(obj interface{}) (interface{}, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"// Get takes runtime.Object as a parameter. However, it returns\n// pointer to \u003cstoreElement\u003e.\nfunc (w *watchCache) Get(obj interface{}) (interface{}, bool, error) {\n\tobject, ok := obj.(runtime.Object)\n\tif !ok {\n\t\treturn nil, false, fmt.Errorf(\"obj does not implement runtime.Object interface: %v\", obj)\n\t}\n\tkey, err := w.keyFunc(object)\n\tif err != nil {\n\t\treturn nil, false, fmt.Errorf(\"couldn't compute key: %v\", err)\n\t}\n\n\treturn w.store.Get(\u0026storeElement{Key: key, Object: object})\n}","line":{"from":525,"to":538}} {"id":100018552,"name":"GetByKey","signature":"func (w *watchCache) GetByKey(key string) (interface{}, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"// GetByKey returns pointer to \u003cstoreElement\u003e.\nfunc (w *watchCache) GetByKey(key string) (interface{}, bool, error) {\n\treturn w.store.GetByKey(key)\n}","line":{"from":540,"to":543}} {"id":100018553,"name":"Replace","signature":"func (w *watchCache) Replace(objs []interface{}, resourceVersion string) error","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"// Replace takes slice of runtime.Object as a parameter.\nfunc (w *watchCache) Replace(objs []interface{}, resourceVersion string) error {\n\tversion, err := w.versioner.ParseResourceVersion(resourceVersion)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttoReplace := make([]interface{}, 0, len(objs))\n\tfor _, obj := range objs {\n\t\tobject, ok := obj.(runtime.Object)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"didn't get runtime.Object for replace: %#v\", obj)\n\t\t}\n\t\tkey, err := w.keyFunc(object)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't compute key: %v\", err)\n\t\t}\n\t\tobjLabels, objFields, err := w.getAttrsFunc(object)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttoReplace = append(toReplace, \u0026storeElement{\n\t\t\tKey: key,\n\t\t\tObject: object,\n\t\t\tLabels: objLabels,\n\t\t\tFields: objFields,\n\t\t})\n\t}\n\n\tw.Lock()\n\tdefer w.Unlock()\n\n\t// Ensure startIndex never decreases, so that existing watchCacheInterval\n\t// instances get \"invalid\" errors if the try to download from the buffer\n\t// using their own start/end indexes calculated from previous buffer\n\t// content.\n\n\t// Empty the cyclic buffer, ensuring startIndex doesn't decrease.\n\tw.startIndex = w.endIndex\n\tw.removedEventSinceRelist = false\n\n\tif err := w.store.Replace(toReplace, resourceVersion); err != nil {\n\t\treturn err\n\t}\n\tw.listResourceVersion = version\n\tw.resourceVersion = version\n\tif w.onReplace != nil {\n\t\tw.onReplace()\n\t}\n\tw.cond.Broadcast()\n\tklog.V(3).Infof(\"Replace watchCache (rev: %v) \", resourceVersion)\n\treturn nil\n}","line":{"from":545,"to":597}} {"id":100018554,"name":"SetOnReplace","signature":"func (w *watchCache) SetOnReplace(onReplace func())","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"func (w *watchCache) SetOnReplace(onReplace func()) {\n\tw.Lock()\n\tdefer w.Unlock()\n\tw.onReplace = onReplace\n}","line":{"from":599,"to":603}} {"id":100018555,"name":"Resync","signature":"func (w *watchCache) Resync() error","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"func (w *watchCache) Resync() error {\n\t// Nothing to do\n\treturn nil\n}","line":{"from":605,"to":608}} {"id":100018556,"name":"currentCapacity","signature":"func (w *watchCache) currentCapacity() int","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"func (w *watchCache) currentCapacity() int {\n\tw.Lock()\n\tdefer w.Unlock()\n\treturn w.capacity\n}","line":{"from":610,"to":614}} {"id":100018557,"name":"suggestedWatchChannelSize","signature":"func (w *watchCache) suggestedWatchChannelSize(indexExists, triggerUsed bool) int","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"func (w *watchCache) suggestedWatchChannelSize(indexExists, triggerUsed bool) int {\n\t// To estimate the channel size we use a heuristic that a channel\n\t// should roughly be able to keep one second of history.\n\t// We don't have an exact data, but given we store updates from\n\t// the last \u003ceventFreshDuration\u003e, we approach it by dividing the\n\t// capacity by the length of the history window.\n\tchanSize := int(math.Ceil(float64(w.currentCapacity()) / eventFreshDuration.Seconds()))\n\n\t// Finally we adjust the size to avoid ending with too low or\n\t// to large values.\n\tif chanSize \u003c minWatchChanSize {\n\t\tchanSize = minWatchChanSize\n\t}\n\tvar maxChanSize int\n\tswitch {\n\tcase indexExists \u0026\u0026 triggerUsed:\n\t\tmaxChanSize = maxWatchChanSizeWithIndexAndTrigger\n\tcase indexExists \u0026\u0026 !triggerUsed:\n\t\tmaxChanSize = maxWatchChanSizeWithIndexWithoutTrigger\n\tcase !indexExists:\n\t\tmaxChanSize = maxWatchChanSizeWithoutIndex\n\t}\n\tif chanSize \u003e maxChanSize {\n\t\tchanSize = maxChanSize\n\t}\n\treturn chanSize\n}","line":{"from":635,"to":661}} {"id":100018558,"name":"isIndexValidLocked","signature":"func (w *watchCache) isIndexValidLocked(index int) bool","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"// isIndexValidLocked checks if a given index is still valid.\n// This assumes that the lock is held.\nfunc (w *watchCache) isIndexValidLocked(index int) bool {\n\treturn index \u003e= w.startIndex\n}","line":{"from":663,"to":667}} {"id":100018559,"name":"getAllEventsSinceLocked","signature":"func (w *watchCache) getAllEventsSinceLocked(resourceVersion uint64) (*watchCacheInterval, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"// getAllEventsSinceLocked returns a watchCacheInterval that can be used to\n// retrieve events since a certain resourceVersion. This function assumes to\n// be called under the watchCache lock.\nfunc (w *watchCache) getAllEventsSinceLocked(resourceVersion uint64) (*watchCacheInterval, error) {\n\tsize := w.endIndex - w.startIndex\n\tvar oldest uint64\n\tswitch {\n\tcase w.listResourceVersion \u003e 0 \u0026\u0026 !w.removedEventSinceRelist:\n\t\t// If no event was removed from the buffer since last relist, the oldest watch\n\t\t// event we can deliver is one greater than the resource version of the list.\n\t\toldest = w.listResourceVersion + 1\n\tcase size \u003e 0:\n\t\t// If the previous condition is not satisfied: either some event was already\n\t\t// removed from the buffer or we've never completed a list (the latter can\n\t\t// only happen in unit tests that populate the buffer without performing\n\t\t// list/replace operations), the oldest watch event we can deliver is the first\n\t\t// one in the buffer.\n\t\toldest = w.cache[w.startIndex%w.capacity].ResourceVersion\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"watch cache isn't correctly initialized\")\n\t}\n\n\tif resourceVersion == 0 {\n\t\t// resourceVersion = 0 means that we don't require any specific starting point\n\t\t// and we would like to start watching from ~now.\n\t\t// However, to keep backward compatibility, we additionally need to return the\n\t\t// current state and only then start watching from that point.\n\t\t//\n\t\t// TODO: In v2 api, we should stop returning the current state - #13969.\n\t\treturn w.getIntervalFromStoreLocked()\n\t}\n\tif resourceVersion \u003c oldest-1 {\n\t\treturn nil, errors.NewResourceExpired(fmt.Sprintf(\"too old resource version: %d (%d)\", resourceVersion, oldest-1))\n\t}\n\n\t// Binary search the smallest index at which resourceVersion is greater than the given one.\n\tf := func(i int) bool {\n\t\treturn w.cache[(w.startIndex+i)%w.capacity].ResourceVersion \u003e resourceVersion\n\t}\n\tfirst := sort.Search(size, f)\n\tindexerFunc := func(i int) *watchCacheEvent {\n\t\treturn w.cache[i%w.capacity]\n\t}\n\tci := newCacheInterval(w.startIndex+first, w.endIndex, indexerFunc, w.indexValidator, \u0026w.RWMutex)\n\treturn ci, nil\n}","line":{"from":669,"to":714}} {"id":100018560,"name":"getIntervalFromStoreLocked","signature":"func (w *watchCache) getIntervalFromStoreLocked() (*watchCacheInterval, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache.go","code":"// getIntervalFromStoreLocked returns a watchCacheInterval\n// that covers the entire storage state.\n// This function assumes to be called under the watchCache lock.\nfunc (w *watchCache) getIntervalFromStoreLocked() (*watchCacheInterval, error) {\n\tci, err := newCacheIntervalFromStore(w.resourceVersion, w.store, w.getAttrsFunc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ci, nil\n}","line":{"from":716,"to":725}} {"id":100018561,"name":"newCacheInterval","signature":"func newCacheInterval(startIndex, endIndex int, indexer indexerFunc, indexValidator indexValidator, locker sync.Locker) *watchCacheInterval","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache_interval.go","code":"func newCacheInterval(startIndex, endIndex int, indexer indexerFunc, indexValidator indexValidator, locker sync.Locker) *watchCacheInterval {\n\treturn \u0026watchCacheInterval{\n\t\tstartIndex: startIndex,\n\t\tendIndex: endIndex,\n\t\tindexer: indexer,\n\t\tindexValidator: indexValidator,\n\t\tbuffer: \u0026watchCacheIntervalBuffer{buffer: make([]*watchCacheEvent, bufferSize)},\n\t\tlock: locker,\n\t}\n}","line":{"from":106,"to":115}} {"id":100018562,"name":"newCacheIntervalFromStore","signature":"func newCacheIntervalFromStore(resourceVersion uint64, store cache.Indexer, getAttrsFunc attrFunc) (*watchCacheInterval, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache_interval.go","code":"// newCacheIntervalFromStore is meant to handle the case of rv=0, such that the events\n// returned by Next() need to be events from a List() done on the underlying store of\n// the watch cache.\nfunc newCacheIntervalFromStore(resourceVersion uint64, store cache.Indexer, getAttrsFunc attrFunc) (*watchCacheInterval, error) {\n\tbuffer := \u0026watchCacheIntervalBuffer{}\n\tallItems := store.List()\n\tbuffer.buffer = make([]*watchCacheEvent, len(allItems))\n\tfor i, item := range allItems {\n\t\telem, ok := item.(*storeElement)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"not a storeElement: %v\", elem)\n\t\t}\n\t\tobjLabels, objFields, err := getAttrsFunc(elem.Object)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbuffer.buffer[i] = \u0026watchCacheEvent{\n\t\t\tType: watch.Added,\n\t\t\tObject: elem.Object,\n\t\t\tObjLabels: objLabels,\n\t\t\tObjFields: objFields,\n\t\t\tKey: elem.Key,\n\t\t\tResourceVersion: resourceVersion,\n\t\t}\n\t\tbuffer.endIndex++\n\t}\n\tci := \u0026watchCacheInterval{\n\t\tstartIndex: 0,\n\t\t// Simulate that we already have all the events we're looking for.\n\t\tendIndex: 0,\n\t\tbuffer: buffer,\n\t}\n\n\treturn ci, nil\n}","line":{"from":117,"to":151}} {"id":100018563,"name":"Next","signature":"func (wci *watchCacheInterval) Next() (*watchCacheEvent, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache_interval.go","code":"// Next returns the next item in the cache interval provided the cache\n// interval is still valid. An error is returned if the interval is\n// invalidated.\nfunc (wci *watchCacheInterval) Next() (*watchCacheEvent, error) {\n\t// if there are items in the buffer to return, return from\n\t// the buffer.\n\tif event, exists := wci.buffer.next(); exists {\n\t\treturn event, nil\n\t}\n\t// check if there are still other events in this interval\n\t// that can be processed.\n\tif wci.startIndex \u003e= wci.endIndex {\n\t\treturn nil, nil\n\t}\n\twci.lock.Lock()\n\tdefer wci.lock.Unlock()\n\n\tif valid := wci.indexValidator(wci.startIndex); !valid {\n\t\treturn nil, fmt.Errorf(\"cache interval invalidated, interval startIndex: %d\", wci.startIndex)\n\t}\n\n\twci.fillBuffer()\n\tif event, exists := wci.buffer.next(); exists {\n\t\treturn event, nil\n\t}\n\treturn nil, nil\n}","line":{"from":153,"to":179}} {"id":100018564,"name":"fillBuffer","signature":"func (wci *watchCacheInterval) fillBuffer()","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache_interval.go","code":"func (wci *watchCacheInterval) fillBuffer() {\n\twci.buffer.startIndex = 0\n\twci.buffer.endIndex = 0\n\tfor wci.startIndex \u003c wci.endIndex \u0026\u0026 !wci.buffer.isFull() {\n\t\tevent := wci.indexer(wci.startIndex)\n\t\tif event == nil {\n\t\t\tbreak\n\t\t}\n\t\twci.buffer.buffer[wci.buffer.endIndex] = event\n\t\twci.buffer.endIndex++\n\t\twci.startIndex++\n\t}\n}","line":{"from":181,"to":193}} {"id":100018565,"name":"next","signature":"func (wcib *watchCacheIntervalBuffer) next() (*watchCacheEvent, bool)","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache_interval.go","code":"// next returns the next event present in the interval buffer provided\n// it is not empty.\nfunc (wcib *watchCacheIntervalBuffer) next() (*watchCacheEvent, bool) {\n\tif wcib.isEmpty() {\n\t\treturn nil, false\n\t}\n\tnext := wcib.buffer[wcib.startIndex]\n\twcib.startIndex++\n\treturn next, true\n}","line":{"from":209,"to":218}} {"id":100018566,"name":"isFull","signature":"func (wcib *watchCacheIntervalBuffer) isFull() bool","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache_interval.go","code":"func (wcib *watchCacheIntervalBuffer) isFull() bool {\n\treturn wcib.endIndex \u003e= bufferSize\n}","line":{"from":220,"to":222}} {"id":100018567,"name":"isEmpty","signature":"func (wcib *watchCacheIntervalBuffer) isEmpty() bool","file":"staging/src/k8s.io/apiserver/pkg/storage/cacher/watch_cache_interval.go","code":"func (wcib *watchCacheIntervalBuffer) isEmpty() bool {\n\treturn wcib.startIndex == wcib.endIndex\n}","line":{"from":224,"to":226}} {"id":100018568,"name":"DecodeContinue","signature":"func DecodeContinue(continueValue, keyPrefix string) (fromKey string, rv int64, err error)","file":"staging/src/k8s.io/apiserver/pkg/storage/continue.go","code":"// DecodeContinue transforms an encoded predicate from into a versioned struct.\n// TODO: return a typed error that instructs clients that they must relist\nfunc DecodeContinue(continueValue, keyPrefix string) (fromKey string, rv int64, err error) {\n\tdata, err := base64.RawURLEncoding.DecodeString(continueValue)\n\tif err != nil {\n\t\treturn \"\", 0, fmt.Errorf(\"%w: %v\", ErrGenericInvalidKey, err)\n\t}\n\tvar c continueToken\n\tif err := json.Unmarshal(data, \u0026c); err != nil {\n\t\treturn \"\", 0, fmt.Errorf(\"%w: %v\", ErrGenericInvalidKey, err)\n\t}\n\tswitch c.APIVersion {\n\tcase \"meta.k8s.io/v1\":\n\t\tif c.ResourceVersion == 0 {\n\t\t\treturn \"\", 0, ErrInvalidStartRV\n\t\t}\n\t\tif len(c.StartKey) == 0 {\n\t\t\treturn \"\", 0, ErrEmptyStartKey\n\t\t}\n\t\t// defend against path traversal attacks by clients - path.Clean will ensure that startKey cannot\n\t\t// be at a higher level of the hierarchy, and so when we append the key prefix we will end up with\n\t\t// continue start key that is fully qualified and cannot range over anything less specific than\n\t\t// keyPrefix.\n\t\tkey := c.StartKey\n\t\tif !strings.HasPrefix(key, \"/\") {\n\t\t\tkey = \"/\" + key\n\t\t}\n\t\tcleaned := path.Clean(key)\n\t\tif cleaned != key {\n\t\t\treturn \"\", 0, fmt.Errorf(\"%w: %v\", ErrGenericInvalidKey, c.StartKey)\n\t\t}\n\t\treturn keyPrefix + cleaned[1:], c.ResourceVersion, nil\n\tdefault:\n\t\treturn \"\", 0, fmt.Errorf(\"%w %v\", ErrUnrecognizedEncodedVersion, c.APIVersion)\n\t}\n}","line":{"from":45,"to":80}} {"id":100018569,"name":"EncodeContinue","signature":"func EncodeContinue(key, keyPrefix string, resourceVersion int64) (string, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/continue.go","code":"// EncodeContinue returns a string representing the encoded continuation of the current query.\nfunc EncodeContinue(key, keyPrefix string, resourceVersion int64) (string, error) {\n\tnextKey := strings.TrimPrefix(key, keyPrefix)\n\tif nextKey == key {\n\t\treturn \"\", fmt.Errorf(\"unable to encode next field: the key and key prefix do not match\")\n\t}\n\tout, err := json.Marshal(\u0026continueToken{APIVersion: \"meta.k8s.io/v1\", ResourceVersion: resourceVersion, StartKey: nextKey})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn base64.RawURLEncoding.EncodeToString(out), nil\n}","line":{"from":82,"to":93}} {"id":100018570,"name":"NewKeyNotFoundError","signature":"func NewKeyNotFoundError(key string, rv int64) *StorageError","file":"staging/src/k8s.io/apiserver/pkg/storage/errors.go","code":"func NewKeyNotFoundError(key string, rv int64) *StorageError {\n\treturn \u0026StorageError{\n\t\tCode: ErrCodeKeyNotFound,\n\t\tKey: key,\n\t\tResourceVersion: rv,\n\t}\n}","line":{"from":43,"to":49}} {"id":100018571,"name":"NewKeyExistsError","signature":"func NewKeyExistsError(key string, rv int64) *StorageError","file":"staging/src/k8s.io/apiserver/pkg/storage/errors.go","code":"func NewKeyExistsError(key string, rv int64) *StorageError {\n\treturn \u0026StorageError{\n\t\tCode: ErrCodeKeyExists,\n\t\tKey: key,\n\t\tResourceVersion: rv,\n\t}\n}","line":{"from":51,"to":57}} {"id":100018572,"name":"NewResourceVersionConflictsError","signature":"func NewResourceVersionConflictsError(key string, rv int64) *StorageError","file":"staging/src/k8s.io/apiserver/pkg/storage/errors.go","code":"func NewResourceVersionConflictsError(key string, rv int64) *StorageError {\n\treturn \u0026StorageError{\n\t\tCode: ErrCodeResourceVersionConflicts,\n\t\tKey: key,\n\t\tResourceVersion: rv,\n\t}\n}","line":{"from":59,"to":65}} {"id":100018573,"name":"NewUnreachableError","signature":"func NewUnreachableError(key string, rv int64) *StorageError","file":"staging/src/k8s.io/apiserver/pkg/storage/errors.go","code":"func NewUnreachableError(key string, rv int64) *StorageError {\n\treturn \u0026StorageError{\n\t\tCode: ErrCodeUnreachable,\n\t\tKey: key,\n\t\tResourceVersion: rv,\n\t}\n}","line":{"from":67,"to":73}} {"id":100018574,"name":"NewInvalidObjError","signature":"func NewInvalidObjError(key, msg string) *StorageError","file":"staging/src/k8s.io/apiserver/pkg/storage/errors.go","code":"func NewInvalidObjError(key, msg string) *StorageError {\n\treturn \u0026StorageError{\n\t\tCode: ErrCodeInvalidObj,\n\t\tKey: key,\n\t\tAdditionalErrorMsg: msg,\n\t}\n}","line":{"from":75,"to":81}} {"id":100018575,"name":"Error","signature":"func (e *StorageError) Error() string","file":"staging/src/k8s.io/apiserver/pkg/storage/errors.go","code":"func (e *StorageError) Error() string {\n\treturn fmt.Sprintf(\"StorageError: %s, Code: %d, Key: %s, ResourceVersion: %d, AdditionalErrorMsg: %s\",\n\t\terrCodeToMessage[e.Code], e.Code, e.Key, e.ResourceVersion, e.AdditionalErrorMsg)\n}","line":{"from":90,"to":93}} {"id":100018576,"name":"IsNotFound","signature":"func IsNotFound(err error) bool","file":"staging/src/k8s.io/apiserver/pkg/storage/errors.go","code":"// IsNotFound returns true if and only if err is \"key\" not found error.\nfunc IsNotFound(err error) bool {\n\treturn isErrCode(err, ErrCodeKeyNotFound)\n}","line":{"from":95,"to":98}} {"id":100018577,"name":"IsExist","signature":"func IsExist(err error) bool","file":"staging/src/k8s.io/apiserver/pkg/storage/errors.go","code":"// IsExist returns true if and only if err is \"key\" already exists error.\nfunc IsExist(err error) bool {\n\treturn isErrCode(err, ErrCodeKeyExists)\n}","line":{"from":100,"to":103}} {"id":100018578,"name":"IsUnreachable","signature":"func IsUnreachable(err error) bool","file":"staging/src/k8s.io/apiserver/pkg/storage/errors.go","code":"// IsUnreachable returns true if and only if err indicates the server could not be reached.\nfunc IsUnreachable(err error) bool {\n\treturn isErrCode(err, ErrCodeUnreachable)\n}","line":{"from":105,"to":108}} {"id":100018579,"name":"IsConflict","signature":"func IsConflict(err error) bool","file":"staging/src/k8s.io/apiserver/pkg/storage/errors.go","code":"// IsConflict returns true if and only if err is a write conflict.\nfunc IsConflict(err error) bool {\n\treturn isErrCode(err, ErrCodeResourceVersionConflicts)\n}","line":{"from":110,"to":113}} {"id":100018580,"name":"IsInvalidObj","signature":"func IsInvalidObj(err error) bool","file":"staging/src/k8s.io/apiserver/pkg/storage/errors.go","code":"// IsInvalidObj returns true if and only if err is invalid error\nfunc IsInvalidObj(err error) bool {\n\treturn isErrCode(err, ErrCodeInvalidObj)\n}","line":{"from":115,"to":118}} {"id":100018581,"name":"isErrCode","signature":"func isErrCode(err error, code int) bool","file":"staging/src/k8s.io/apiserver/pkg/storage/errors.go","code":"func isErrCode(err error, code int) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\tif e, ok := err.(*StorageError); ok {\n\t\treturn e.Code == code\n\t}\n\treturn false\n}","line":{"from":120,"to":128}} {"id":100018582,"name":"Error","signature":"func (e InvalidError) Error() string","file":"staging/src/k8s.io/apiserver/pkg/storage/errors.go","code":"func (e InvalidError) Error() string {\n\treturn e.Errs.ToAggregate().Error()\n}","line":{"from":136,"to":138}} {"id":100018583,"name":"IsInvalidError","signature":"func IsInvalidError(err error) bool","file":"staging/src/k8s.io/apiserver/pkg/storage/errors.go","code":"// IsInvalidError returns true if and only if err is an InvalidError.\nfunc IsInvalidError(err error) bool {\n\t_, ok := err.(InvalidError)\n\treturn ok\n}","line":{"from":140,"to":144}} {"id":100018584,"name":"NewInvalidError","signature":"func NewInvalidError(errors field.ErrorList) InvalidError","file":"staging/src/k8s.io/apiserver/pkg/storage/errors.go","code":"func NewInvalidError(errors field.ErrorList) InvalidError {\n\treturn InvalidError{errors}\n}","line":{"from":146,"to":148}} {"id":100018585,"name":"Error","signature":"func (e InternalError) Error() string","file":"staging/src/k8s.io/apiserver/pkg/storage/errors.go","code":"func (e InternalError) Error() string {\n\treturn e.Reason\n}","line":{"from":156,"to":158}} {"id":100018586,"name":"IsInternalError","signature":"func IsInternalError(err error) bool","file":"staging/src/k8s.io/apiserver/pkg/storage/errors.go","code":"// IsInternalError returns true if and only if err is an InternalError.\nfunc IsInternalError(err error) bool {\n\t_, ok := err.(InternalError)\n\treturn ok\n}","line":{"from":160,"to":164}} {"id":100018587,"name":"NewInternalError","signature":"func NewInternalError(reason string) InternalError","file":"staging/src/k8s.io/apiserver/pkg/storage/errors.go","code":"func NewInternalError(reason string) InternalError {\n\treturn InternalError{reason}\n}","line":{"from":166,"to":168}} {"id":100018588,"name":"NewInternalErrorf","signature":"func NewInternalErrorf(format string, a ...interface{}) InternalError","file":"staging/src/k8s.io/apiserver/pkg/storage/errors.go","code":"func NewInternalErrorf(format string, a ...interface{}) InternalError {\n\treturn InternalError{fmt.Sprintf(format, a...)}\n}","line":{"from":170,"to":172}} {"id":100018589,"name":"NewTooLargeResourceVersionError","signature":"func NewTooLargeResourceVersionError(minimumResourceVersion, currentRevision uint64, retrySeconds int) error","file":"staging/src/k8s.io/apiserver/pkg/storage/errors.go","code":"// NewTooLargeResourceVersionError returns a timeout error with the given retrySeconds for a request for\n// a minimum resource version that is larger than the largest currently available resource version for a requested resource.\nfunc NewTooLargeResourceVersionError(minimumResourceVersion, currentRevision uint64, retrySeconds int) error {\n\terr := errors.NewTimeoutError(fmt.Sprintf(\"Too large resource version: %d, current: %d\", minimumResourceVersion, currentRevision), retrySeconds)\n\terr.ErrStatus.Details.Causes = []metav1.StatusCause{\n\t\t{\n\t\t\tType: metav1.CauseTypeResourceVersionTooLarge,\n\t\t\tMessage: tooLargeResourceVersionCauseMsg,\n\t\t},\n\t}\n\treturn err\n}","line":{"from":176,"to":187}} {"id":100018590,"name":"IsTooLargeResourceVersion","signature":"func IsTooLargeResourceVersion(err error) bool","file":"staging/src/k8s.io/apiserver/pkg/storage/errors.go","code":"// IsTooLargeResourceVersion returns true if the error is a TooLargeResourceVersion error.\nfunc IsTooLargeResourceVersion(err error) bool {\n\tif !errors.IsTimeout(err) {\n\t\treturn false\n\t}\n\treturn errors.HasStatusCause(err, metav1.CauseTypeResourceVersionTooLarge)\n}","line":{"from":189,"to":195}} {"id":100018591,"name":"InterpretListError","signature":"func InterpretListError(err error, qualifiedResource schema.GroupResource) error","file":"staging/src/k8s.io/apiserver/pkg/storage/errors/storage.go","code":"// InterpretListError converts a generic error on a retrieval\n// operation into the appropriate API error.\nfunc InterpretListError(err error, qualifiedResource schema.GroupResource) error {\n\tswitch {\n\tcase storage.IsNotFound(err):\n\t\treturn errors.NewNotFound(qualifiedResource, \"\")\n\tcase storage.IsUnreachable(err):\n\t\treturn errors.NewServerTimeout(qualifiedResource, \"list\", 2) // TODO: make configurable or handled at a higher level\n\tcase storage.IsInternalError(err):\n\t\treturn errors.NewInternalError(err)\n\tdefault:\n\t\treturn err\n\t}\n}","line":{"from":25,"to":38}} {"id":100018592,"name":"InterpretGetError","signature":"func InterpretGetError(err error, qualifiedResource schema.GroupResource, name string) error","file":"staging/src/k8s.io/apiserver/pkg/storage/errors/storage.go","code":"// InterpretGetError converts a generic error on a retrieval\n// operation into the appropriate API error.\nfunc InterpretGetError(err error, qualifiedResource schema.GroupResource, name string) error {\n\tswitch {\n\tcase storage.IsNotFound(err):\n\t\treturn errors.NewNotFound(qualifiedResource, name)\n\tcase storage.IsUnreachable(err):\n\t\treturn errors.NewServerTimeout(qualifiedResource, \"get\", 2) // TODO: make configurable or handled at a higher level\n\tcase storage.IsInternalError(err):\n\t\treturn errors.NewInternalError(err)\n\tdefault:\n\t\treturn err\n\t}\n}","line":{"from":40,"to":53}} {"id":100018593,"name":"InterpretCreateError","signature":"func InterpretCreateError(err error, qualifiedResource schema.GroupResource, name string) error","file":"staging/src/k8s.io/apiserver/pkg/storage/errors/storage.go","code":"// InterpretCreateError converts a generic error on a create\n// operation into the appropriate API error.\nfunc InterpretCreateError(err error, qualifiedResource schema.GroupResource, name string) error {\n\tswitch {\n\tcase storage.IsExist(err):\n\t\treturn errors.NewAlreadyExists(qualifiedResource, name)\n\tcase storage.IsUnreachable(err):\n\t\treturn errors.NewServerTimeout(qualifiedResource, \"create\", 2) // TODO: make configurable or handled at a higher level\n\tcase storage.IsInternalError(err):\n\t\treturn errors.NewInternalError(err)\n\tdefault:\n\t\treturn err\n\t}\n}","line":{"from":55,"to":68}} {"id":100018594,"name":"InterpretUpdateError","signature":"func InterpretUpdateError(err error, qualifiedResource schema.GroupResource, name string) error","file":"staging/src/k8s.io/apiserver/pkg/storage/errors/storage.go","code":"// InterpretUpdateError converts a generic error on an update\n// operation into the appropriate API error.\nfunc InterpretUpdateError(err error, qualifiedResource schema.GroupResource, name string) error {\n\tswitch {\n\tcase storage.IsConflict(err), storage.IsExist(err), storage.IsInvalidObj(err):\n\t\treturn errors.NewConflict(qualifiedResource, name, err)\n\tcase storage.IsUnreachable(err):\n\t\treturn errors.NewServerTimeout(qualifiedResource, \"update\", 2) // TODO: make configurable or handled at a higher level\n\tcase storage.IsNotFound(err):\n\t\treturn errors.NewNotFound(qualifiedResource, name)\n\tcase storage.IsInternalError(err):\n\t\treturn errors.NewInternalError(err)\n\tdefault:\n\t\treturn err\n\t}\n}","line":{"from":70,"to":85}} {"id":100018595,"name":"InterpretDeleteError","signature":"func InterpretDeleteError(err error, qualifiedResource schema.GroupResource, name string) error","file":"staging/src/k8s.io/apiserver/pkg/storage/errors/storage.go","code":"// InterpretDeleteError converts a generic error on a delete\n// operation into the appropriate API error.\nfunc InterpretDeleteError(err error, qualifiedResource schema.GroupResource, name string) error {\n\tswitch {\n\tcase storage.IsNotFound(err):\n\t\treturn errors.NewNotFound(qualifiedResource, name)\n\tcase storage.IsUnreachable(err):\n\t\treturn errors.NewServerTimeout(qualifiedResource, \"delete\", 2) // TODO: make configurable or handled at a higher level\n\tcase storage.IsConflict(err), storage.IsExist(err), storage.IsInvalidObj(err):\n\t\treturn errors.NewConflict(qualifiedResource, name, err)\n\tcase storage.IsInternalError(err):\n\t\treturn errors.NewInternalError(err)\n\tdefault:\n\t\treturn err\n\t}\n}","line":{"from":87,"to":102}} {"id":100018596,"name":"InterpretWatchError","signature":"func InterpretWatchError(err error, resource schema.GroupResource, name string) error","file":"staging/src/k8s.io/apiserver/pkg/storage/errors/storage.go","code":"// InterpretWatchError converts a generic error on a watch\n// operation into the appropriate API error.\nfunc InterpretWatchError(err error, resource schema.GroupResource, name string) error {\n\tswitch {\n\tcase storage.IsInvalidError(err):\n\t\tinvalidError, _ := err.(storage.InvalidError)\n\t\treturn errors.NewInvalid(schema.GroupKind{Group: resource.Group, Kind: resource.Resource}, name, invalidError.Errs)\n\tcase storage.IsInternalError(err):\n\t\treturn errors.NewInternalError(err)\n\tdefault:\n\t\treturn err\n\t}\n}","line":{"from":104,"to":116}} {"id":100018597,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/compact.go","code":"func init() {\n\tendpointsMap = make(map[string]struct{})\n}","line":{"from":38,"to":40}} {"id":100018598,"name":"StartCompactor","signature":"func StartCompactor(ctx context.Context, client *clientv3.Client, compactInterval time.Duration)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/compact.go","code":"// StartCompactor starts a compactor in the background to compact old version of keys that's not needed.\n// By default, we save the most recent 5 minutes data and compact versions \u003e 5minutes ago.\n// It should be enough for slow watchers and to tolerate burst.\n// TODO: We might keep a longer history (12h) in the future once storage API can take advantage of past version of keys.\nfunc StartCompactor(ctx context.Context, client *clientv3.Client, compactInterval time.Duration) {\n\tendpointsMapMu.Lock()\n\tdefer endpointsMapMu.Unlock()\n\n\t// In one process, we can have only one compactor for one cluster.\n\t// Currently we rely on endpoints to differentiate clusters.\n\tfor _, ep := range client.Endpoints() {\n\t\tif _, ok := endpointsMap[ep]; ok {\n\t\t\tklog.V(4).Infof(\"compactor already exists for endpoints %v\", client.Endpoints())\n\t\t\treturn\n\t\t}\n\t}\n\tfor _, ep := range client.Endpoints() {\n\t\tendpointsMap[ep] = struct{}{}\n\t}\n\n\tif compactInterval != 0 {\n\t\tgo compactor(ctx, client, compactInterval)\n\t}\n}","line":{"from":42,"to":65}} {"id":100018599,"name":"compactor","signature":"func compactor(ctx context.Context, client *clientv3.Client, interval time.Duration)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/compact.go","code":"// compactor periodically compacts historical versions of keys in etcd.\n// It will compact keys with versions older than given interval.\n// In other words, after compaction, it will only contain keys set during last interval.\n// Any API call for the older versions of keys will return error.\n// Interval is the time interval between each compaction. The first compaction happens after \"interval\".\nfunc compactor(ctx context.Context, client *clientv3.Client, interval time.Duration) {\n\t// Technical definitions:\n\t// We have a special key in etcd defined as *compactRevKey*.\n\t// compactRevKey's value will be set to the string of last compacted revision.\n\t// compactRevKey's version will be used as logical time for comparison. THe version is referred as compact time.\n\t// Initially, because the key doesn't exist, the compact time (version) is 0.\n\t//\n\t// Algorithm:\n\t// - Compare to see if (local compact_time) = (remote compact_time).\n\t// - If yes, increment both local and remote compact_time, and do a compaction.\n\t// - If not, set local to remote compact_time.\n\t//\n\t// Technical details/insights:\n\t//\n\t// The protocol here is lease based. If one compactor CAS successfully, the others would know it when they fail in\n\t// CAS later and would try again in 5 minutes. If an APIServer crashed, another one would \"take over\" the lease.\n\t//\n\t// For example, in the following diagram, we have a compactor C1 doing compaction in t1, t2. Another compactor C2\n\t// at t1' (t1 \u003c t1' \u003c t2) would CAS fail, set its known oldRev to rev at t1', and try again in t2' (t2' \u003e t2).\n\t// If C1 crashed and wouldn't compact at t2, C2 would CAS successfully at t2'.\n\t//\n\t// oldRev(t2) curRev(t2)\n\t// +\n\t// oldRev curRev |\n\t// + + |\n\t// | | |\n\t// | | t1' | t2'\n\t// +---v-------------v----^---------v------^----\u003e\n\t// t0 t1 t2\n\t//\n\t// We have the guarantees:\n\t// - in normal cases, the interval is 5 minutes.\n\t// - in failover, the interval is \u003e5m and \u003c10m\n\t//\n\t// FAQ:\n\t// - What if time is not accurate? We don't care as long as someone did the compaction. Atomicity is ensured using\n\t// etcd API.\n\t// - What happened under heavy load scenarios? Initially, each apiserver will do only one compaction\n\t// every 5 minutes. This is very unlikely affecting or affected w.r.t. server load.\n\n\tvar compactTime int64\n\tvar rev int64\n\tvar err error\n\tfor {\n\t\tselect {\n\t\tcase \u003c-time.After(interval):\n\t\tcase \u003c-ctx.Done():\n\t\t\treturn\n\t\t}\n\n\t\tcompactTime, rev, err = compact(ctx, client, compactTime, rev)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"etcd: endpoint (%v) compact failed: %v\", client.Endpoints(), err)\n\t\t\tcontinue\n\t\t}\n\t}\n}","line":{"from":67,"to":128}} {"id":100018600,"name":"compact","signature":"func compact(ctx context.Context, client *clientv3.Client, t, rev int64) (int64, int64, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/compact.go","code":"// compact compacts etcd store and returns current rev.\n// It will return the current compact time and global revision if no error occurred.\n// Note that CAS fail will not incur any error.\nfunc compact(ctx context.Context, client *clientv3.Client, t, rev int64) (int64, int64, error) {\n\tresp, err := client.KV.Txn(ctx).If(\n\t\tclientv3.Compare(clientv3.Version(compactRevKey), \"=\", t),\n\t).Then(\n\t\tclientv3.OpPut(compactRevKey, strconv.FormatInt(rev, 10)), // Expect side effect: increment Version\n\t).Else(\n\t\tclientv3.OpGet(compactRevKey),\n\t).Commit()\n\tif err != nil {\n\t\treturn t, rev, err\n\t}\n\n\tcurRev := resp.Header.Revision\n\n\tif !resp.Succeeded {\n\t\tcurTime := resp.Responses[0].GetResponseRange().Kvs[0].Version\n\t\treturn curTime, curRev, nil\n\t}\n\tcurTime := t + 1\n\n\tif rev == 0 {\n\t\t// We don't compact on bootstrap.\n\t\treturn curTime, curRev, nil\n\t}\n\tif _, err = client.Compact(ctx, rev); err != nil {\n\t\treturn curTime, curRev, err\n\t}\n\tklog.V(4).Infof(\"etcd: compacted rev (%d), endpoints (%v)\", rev, client.Endpoints())\n\treturn curTime, curRev, nil\n}","line":{"from":130,"to":162}} {"id":100018601,"name":"interpretWatchError","signature":"func interpretWatchError(err error) error","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/errors.go","code":"func interpretWatchError(err error) error {\n\tswitch {\n\tcase err == etcdrpc.ErrCompacted:\n\t\treturn errors.NewResourceExpired(\"The resourceVersion for the provided watch is too old.\")\n\t}\n\treturn err\n}","line":{"from":27,"to":33}} {"id":100018602,"name":"interpretListError","signature":"func interpretListError(err error, paging bool, continueKey, keyPrefix string) error","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/errors.go","code":"func interpretListError(err error, paging bool, continueKey, keyPrefix string) error {\n\tswitch {\n\tcase err == etcdrpc.ErrCompacted:\n\t\tif paging {\n\t\t\treturn handleCompactedErrorForPaging(continueKey, keyPrefix)\n\t\t}\n\t\treturn errors.NewResourceExpired(expired)\n\t}\n\treturn err\n}","line":{"from":49,"to":58}} {"id":100018603,"name":"handleCompactedErrorForPaging","signature":"func handleCompactedErrorForPaging(continueKey, keyPrefix string) error","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/errors.go","code":"func handleCompactedErrorForPaging(continueKey, keyPrefix string) error {\n\t// continueToken.ResoureVersion=-1 means that the apiserver can\n\t// continue the list at the latest resource version. We don't use rv=0\n\t// for this purpose to distinguish from a bad token that has empty rv.\n\tnewToken, err := storage.EncodeContinue(continueKey, keyPrefix, -1)\n\tif err != nil {\n\t\tutilruntime.HandleError(err)\n\t\treturn errors.NewResourceExpired(continueExpired)\n\t}\n\tstatusError := errors.NewResourceExpired(inconsistentContinue)\n\tstatusError.ErrStatus.ListMeta.Continue = newToken\n\treturn statusError\n}","line":{"from":60,"to":72}} {"id":100018604,"name":"parseKV","signature":"func parseKV(kv *mvccpb.KeyValue) *event","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/event.go","code":"// parseKV converts a KeyValue retrieved from an initial sync() listing to a synthetic isCreated event.\nfunc parseKV(kv *mvccpb.KeyValue) *event {\n\treturn \u0026event{\n\t\tkey: string(kv.Key),\n\t\tvalue: kv.Value,\n\t\tprevValue: nil,\n\t\trev: kv.ModRevision,\n\t\tisDeleted: false,\n\t\tisCreated: true,\n\t}\n}","line":{"from":35,"to":45}} {"id":100018605,"name":"parseEvent","signature":"func parseEvent(e *clientv3.Event) (*event, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/event.go","code":"func parseEvent(e *clientv3.Event) (*event, error) {\n\tif !e.IsCreate() \u0026\u0026 e.PrevKv == nil {\n\t\t// If the previous value is nil, error. One example of how this is possible is if the previous value has been compacted already.\n\t\treturn nil, fmt.Errorf(\"etcd event received with PrevKv=nil (key=%q, modRevision=%d, type=%s)\", string(e.Kv.Key), e.Kv.ModRevision, e.Type.String())\n\n\t}\n\tret := \u0026event{\n\t\tkey: string(e.Kv.Key),\n\t\tvalue: e.Kv.Value,\n\t\trev: e.Kv.ModRevision,\n\t\tisDeleted: e.Type == clientv3.EventTypeDelete,\n\t\tisCreated: e.IsCreate(),\n\t}\n\tif e.PrevKv != nil {\n\t\tret.prevValue = e.PrevKv.Value\n\t}\n\treturn ret, nil\n}","line":{"from":47,"to":64}} {"id":100018606,"name":"progressNotifyEvent","signature":"func progressNotifyEvent(rev int64) *event","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/event.go","code":"func progressNotifyEvent(rev int64) *event {\n\treturn \u0026event{\n\t\trev: rev,\n\t\tisProgressNotify: true,\n\t}\n}","line":{"from":66,"to":71}} {"id":100018607,"name":"EtcdHealthCheck","signature":"func EtcdHealthCheck(data []byte) error","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/healthcheck.go","code":"// EtcdHealthCheck decodes data returned from etcd /healthz handler.\n// Deprecated: Validate health by passing storagebackend.Config directly to storagefactory.CreateProber.\nfunc EtcdHealthCheck(data []byte) error {\n\tobj := etcdHealth{}\n\tif err := json.Unmarshal(data, \u0026obj); err != nil {\n\t\treturn err\n\t}\n\tif obj.Health != \"true\" {\n\t\treturn fmt.Errorf(\"Unhealthy status: %s\", obj.Health)\n\t}\n\treturn nil\n}","line":{"from":30,"to":41}} {"id":100018608,"name":"NewETCDLatencyTracker","signature":"func NewETCDLatencyTracker(delegate clientv3.KV) clientv3.KV","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/latency_tracker.go","code":"// NewETCDLatencyTracker returns an implementation of\n// clientv3.KV that times the calls from the specified\n// 'delegate' KV instance in order to track latency incurred.\nfunc NewETCDLatencyTracker(delegate clientv3.KV) clientv3.KV {\n\treturn \u0026clientV3KVLatencyTracker{KV: delegate}\n}","line":{"from":27,"to":32}} {"id":100018609,"name":"Put","signature":"func (c *clientV3KVLatencyTracker) Put(ctx context.Context, key, val string, opts ...clientv3.OpOption) (*clientv3.PutResponse, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/latency_tracker.go","code":"func (c *clientV3KVLatencyTracker) Put(ctx context.Context, key, val string, opts ...clientv3.OpOption) (*clientv3.PutResponse, error) {\n\tstartedAt := time.Now()\n\tdefer func() {\n\t\tendpointsrequest.TrackStorageLatency(ctx, time.Since(startedAt))\n\t}()\n\n\treturn c.KV.Put(ctx, key, val, opts...)\n}","line":{"from":55,"to":62}} {"id":100018610,"name":"Get","signature":"func (c *clientV3KVLatencyTracker) Get(ctx context.Context, key string, opts ...clientv3.OpOption) (*clientv3.GetResponse, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/latency_tracker.go","code":"func (c *clientV3KVLatencyTracker) Get(ctx context.Context, key string, opts ...clientv3.OpOption) (*clientv3.GetResponse, error) {\n\tstartedAt := time.Now()\n\tdefer func() {\n\t\tendpointsrequest.TrackStorageLatency(ctx, time.Since(startedAt))\n\t}()\n\n\treturn c.KV.Get(ctx, key, opts...)\n}","line":{"from":64,"to":71}} {"id":100018611,"name":"Delete","signature":"func (c *clientV3KVLatencyTracker) Delete(ctx context.Context, key string, opts ...clientv3.OpOption) (*clientv3.DeleteResponse, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/latency_tracker.go","code":"func (c *clientV3KVLatencyTracker) Delete(ctx context.Context, key string, opts ...clientv3.OpOption) (*clientv3.DeleteResponse, error) {\n\tstartedAt := time.Now()\n\tdefer func() {\n\t\tendpointsrequest.TrackStorageLatency(ctx, time.Since(startedAt))\n\t}()\n\n\treturn c.KV.Delete(ctx, key, opts...)\n}","line":{"from":73,"to":80}} {"id":100018612,"name":"Do","signature":"func (c *clientV3KVLatencyTracker) Do(ctx context.Context, op clientv3.Op) (clientv3.OpResponse, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/latency_tracker.go","code":"func (c *clientV3KVLatencyTracker) Do(ctx context.Context, op clientv3.Op) (clientv3.OpResponse, error) {\n\tstartedAt := time.Now()\n\tdefer func() {\n\t\tendpointsrequest.TrackStorageLatency(ctx, time.Since(startedAt))\n\t}()\n\n\treturn c.KV.Do(ctx, op)\n}","line":{"from":82,"to":89}} {"id":100018613,"name":"Txn","signature":"func (c *clientV3KVLatencyTracker) Txn(ctx context.Context) clientv3.Txn","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/latency_tracker.go","code":"func (c *clientV3KVLatencyTracker) Txn(ctx context.Context) clientv3.Txn {\n\treturn \u0026clientV3TxnTracker{ctx: ctx, Txn: c.KV.Txn(ctx)}\n}","line":{"from":91,"to":93}} {"id":100018614,"name":"Commit","signature":"func (t *clientV3TxnTracker) Commit() (*clientv3.TxnResponse, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/latency_tracker.go","code":"func (t *clientV3TxnTracker) Commit() (*clientv3.TxnResponse, error) {\n\tstartedAt := time.Now()\n\tdefer func() {\n\t\tendpointsrequest.TrackStorageLatency(t.ctx, time.Since(startedAt))\n\t}()\n\n\treturn t.Txn.Commit()\n}","line":{"from":100,"to":107}} {"id":100018615,"name":"NewDefaultLeaseManagerConfig","signature":"func NewDefaultLeaseManagerConfig() LeaseManagerConfig","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/lease_manager.go","code":"// NewDefaultLeaseManagerConfig creates a LeaseManagerConfig with default values\nfunc NewDefaultLeaseManagerConfig() LeaseManagerConfig {\n\treturn LeaseManagerConfig{\n\t\tReuseDurationSeconds: defaultLeaseReuseDurationSeconds,\n\t\tMaxObjectCount: defaultLeaseMaxObjectCount,\n\t}\n}","line":{"from":41,"to":47}} {"id":100018616,"name":"newDefaultLeaseManager","signature":"func newDefaultLeaseManager(client *clientv3.Client, config LeaseManagerConfig) *leaseManager","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/lease_manager.go","code":"// newDefaultLeaseManager creates a new lease manager using default setting.\nfunc newDefaultLeaseManager(client *clientv3.Client, config LeaseManagerConfig) *leaseManager {\n\tif config.MaxObjectCount \u003c= 0 {\n\t\tconfig.MaxObjectCount = defaultLeaseMaxObjectCount\n\t}\n\treturn newLeaseManager(client, config.ReuseDurationSeconds, 0.05, config.MaxObjectCount)\n}","line":{"from":68,"to":74}} {"id":100018617,"name":"newLeaseManager","signature":"func newLeaseManager(client *clientv3.Client, leaseReuseDurationSeconds int64, leaseReuseDurationPercent float64, maxObjectCount int64) *leaseManager","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/lease_manager.go","code":"// newLeaseManager creates a new lease manager with the number of buffered\n// leases, lease reuse duration in seconds and percentage. The percentage\n// value x means x*100%.\nfunc newLeaseManager(client *clientv3.Client, leaseReuseDurationSeconds int64, leaseReuseDurationPercent float64, maxObjectCount int64) *leaseManager {\n\treturn \u0026leaseManager{\n\t\tclient: client,\n\t\tleaseReuseDurationSeconds: leaseReuseDurationSeconds,\n\t\tleaseReuseDurationPercent: leaseReuseDurationPercent,\n\t\tleaseMaxAttachedObjectCount: maxObjectCount,\n\t}\n}","line":{"from":76,"to":86}} {"id":100018618,"name":"GetLease","signature":"func (l *leaseManager) GetLease(ctx context.Context, ttl int64) (clientv3.LeaseID, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/lease_manager.go","code":"// GetLease returns a lease based on requested ttl: if the cached previous\n// lease can be reused, reuse it; otherwise request a new one from etcd.\nfunc (l *leaseManager) GetLease(ctx context.Context, ttl int64) (clientv3.LeaseID, error) {\n\tnow := time.Now()\n\tl.leaseMu.Lock()\n\tdefer l.leaseMu.Unlock()\n\t// check if previous lease can be reused\n\treuseDurationSeconds := l.getReuseDurationSecondsLocked(ttl)\n\tvalid := now.Add(time.Duration(ttl) * time.Second).Before(l.prevLeaseExpirationTime)\n\tsufficient := now.Add(time.Duration(ttl+reuseDurationSeconds) * time.Second).After(l.prevLeaseExpirationTime)\n\n\t// We count all operations that happened in the same lease, regardless of success or failure.\n\t// Currently each GetLease call only attach 1 object\n\tl.leaseAttachedObjectCount++\n\n\tif valid \u0026\u0026 sufficient \u0026\u0026 l.leaseAttachedObjectCount \u003c= l.leaseMaxAttachedObjectCount {\n\t\treturn l.prevLeaseID, nil\n\t}\n\n\t// request a lease with a little extra ttl from etcd\n\tttl += reuseDurationSeconds\n\tlcr, err := l.client.Lease.Grant(ctx, ttl)\n\tif err != nil {\n\t\treturn clientv3.LeaseID(0), err\n\t}\n\t// cache the new lease id\n\tl.prevLeaseID = lcr.ID\n\tl.prevLeaseExpirationTime = now.Add(time.Duration(ttl) * time.Second)\n\t// refresh count\n\tmetrics.UpdateLeaseObjectCount(l.leaseAttachedObjectCount)\n\tl.leaseAttachedObjectCount = 1\n\treturn lcr.ID, nil\n}","line":{"from":88,"to":120}} {"id":100018619,"name":"getReuseDurationSecondsLocked","signature":"func (l *leaseManager) getReuseDurationSecondsLocked(ttl int64) int64","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/lease_manager.go","code":"// getReuseDurationSecondsLocked returns the reusable duration in seconds\n// based on the configuration. Lock has to be acquired before calling this\n// function.\nfunc (l *leaseManager) getReuseDurationSecondsLocked(ttl int64) int64 {\n\treuseDurationSeconds := int64(l.leaseReuseDurationPercent * float64(ttl))\n\tif reuseDurationSeconds \u003e l.leaseReuseDurationSeconds {\n\t\treuseDurationSeconds = l.leaseReuseDurationSeconds\n\t}\n\treturn reuseDurationSeconds\n}","line":{"from":122,"to":131}} {"id":100018620,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/logger.go","code":"func init() {\n\tgrpclog.SetLoggerV2(klogWrapper{})\n}","line":{"from":26,"to":28}} {"id":100018621,"name":"Info","signature":"func (klogWrapper) Info(args ...interface{})","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/logger.go","code":"func (klogWrapper) Info(args ...interface{}) {\n\tif klogV := klog.V(5); klogV.Enabled() {\n\t\tklogV.InfoSDepth(klogWrapperDepth, fmt.Sprint(args...))\n\t}\n}","line":{"from":34,"to":38}} {"id":100018622,"name":"Infoln","signature":"func (klogWrapper) Infoln(args ...interface{})","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/logger.go","code":"func (klogWrapper) Infoln(args ...interface{}) {\n\tif klogV := klog.V(5); klogV.Enabled() {\n\t\tklogV.InfoSDepth(klogWrapperDepth, fmt.Sprintln(args...))\n\t}\n}","line":{"from":40,"to":44}} {"id":100018623,"name":"Infof","signature":"func (klogWrapper) Infof(format string, args ...interface{})","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/logger.go","code":"func (klogWrapper) Infof(format string, args ...interface{}) {\n\tif klogV := klog.V(5); klogV.Enabled() {\n\t\tklog.V(5).InfoSDepth(klogWrapperDepth, fmt.Sprintf(format, args...))\n\t}\n}","line":{"from":46,"to":50}} {"id":100018624,"name":"Warning","signature":"func (klogWrapper) Warning(args ...interface{})","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/logger.go","code":"func (klogWrapper) Warning(args ...interface{}) {\n\tklog.WarningDepth(klogWrapperDepth, args...)\n}","line":{"from":52,"to":54}} {"id":100018625,"name":"Warningln","signature":"func (klogWrapper) Warningln(args ...interface{})","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/logger.go","code":"func (klogWrapper) Warningln(args ...interface{}) {\n\tklog.WarningDepth(klogWrapperDepth, fmt.Sprintln(args...))\n}","line":{"from":56,"to":58}} {"id":100018626,"name":"Warningf","signature":"func (klogWrapper) Warningf(format string, args ...interface{})","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/logger.go","code":"func (klogWrapper) Warningf(format string, args ...interface{}) {\n\tklog.WarningDepth(klogWrapperDepth, fmt.Sprintf(format, args...))\n}","line":{"from":60,"to":62}} {"id":100018627,"name":"Error","signature":"func (klogWrapper) Error(args ...interface{})","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/logger.go","code":"func (klogWrapper) Error(args ...interface{}) {\n\tklog.ErrorDepth(klogWrapperDepth, args...)\n}","line":{"from":64,"to":66}} {"id":100018628,"name":"Errorln","signature":"func (klogWrapper) Errorln(args ...interface{})","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/logger.go","code":"func (klogWrapper) Errorln(args ...interface{}) {\n\tklog.ErrorDepth(klogWrapperDepth, fmt.Sprintln(args...))\n}","line":{"from":68,"to":70}} {"id":100018629,"name":"Errorf","signature":"func (klogWrapper) Errorf(format string, args ...interface{})","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/logger.go","code":"func (klogWrapper) Errorf(format string, args ...interface{}) {\n\tklog.ErrorDepth(klogWrapperDepth, fmt.Sprintf(format, args...))\n}","line":{"from":72,"to":74}} {"id":100018630,"name":"Fatal","signature":"func (klogWrapper) Fatal(args ...interface{})","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/logger.go","code":"func (klogWrapper) Fatal(args ...interface{}) {\n\tklog.FatalDepth(klogWrapperDepth, args...)\n}","line":{"from":76,"to":78}} {"id":100018631,"name":"Fatalln","signature":"func (klogWrapper) Fatalln(args ...interface{})","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/logger.go","code":"func (klogWrapper) Fatalln(args ...interface{}) {\n\tklog.FatalDepth(klogWrapperDepth, fmt.Sprintln(args...))\n}","line":{"from":80,"to":82}} {"id":100018632,"name":"Fatalf","signature":"func (klogWrapper) Fatalf(format string, args ...interface{})","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/logger.go","code":"func (klogWrapper) Fatalf(format string, args ...interface{}) {\n\tklog.FatalDepth(klogWrapperDepth, fmt.Sprintf(format, args...))\n}","line":{"from":84,"to":86}} {"id":100018633,"name":"V","signature":"func (klogWrapper) V(l int) bool","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/logger.go","code":"func (klogWrapper) V(l int) bool {\n\treturn bool(klog.V(klog.Level(l)).Enabled())\n}","line":{"from":88,"to":90}} {"id":100018634,"name":"Register","signature":"func Register()","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/metrics/metrics.go","code":"// Register all metrics.\nfunc Register() {\n\t// Register the metrics.\n\tregisterMetrics.Do(func() {\n\t\tlegacyregistry.MustRegister(etcdRequestLatency)\n\t\tlegacyregistry.MustRegister(objectCounts)\n\t\tlegacyregistry.MustRegister(dbTotalSize)\n\t\tlegacyregistry.MustRegister(etcdBookmarkCounts)\n\t\tlegacyregistry.MustRegister(etcdLeaseObjectCounts)\n\t\tlegacyregistry.MustRegister(listStorageCount)\n\t\tlegacyregistry.MustRegister(listStorageNumFetched)\n\t\tlegacyregistry.MustRegister(listStorageNumSelectorEvals)\n\t\tlegacyregistry.MustRegister(listStorageNumReturned)\n\t\tlegacyregistry.MustRegister(decodeErrorCounts)\n\t})\n}","line":{"from":138,"to":153}} {"id":100018635,"name":"UpdateObjectCount","signature":"func UpdateObjectCount(resourcePrefix string, count int64)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/metrics/metrics.go","code":"// UpdateObjectCount sets the apiserver_storage_object_counts metric.\nfunc UpdateObjectCount(resourcePrefix string, count int64) {\n\tobjectCounts.WithLabelValues(resourcePrefix).Set(float64(count))\n}","line":{"from":155,"to":158}} {"id":100018636,"name":"RecordEtcdRequestLatency","signature":"func RecordEtcdRequestLatency(verb, resource string, startTime time.Time)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/metrics/metrics.go","code":"// RecordEtcdRequestLatency sets the etcd_request_duration_seconds metrics.\nfunc RecordEtcdRequestLatency(verb, resource string, startTime time.Time) {\n\tetcdRequestLatency.WithLabelValues(verb, resource).Observe(sinceInSeconds(startTime))\n}","line":{"from":160,"to":163}} {"id":100018637,"name":"RecordEtcdEvent","signature":"func RecordEtcdEvent(resource string)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/metrics/metrics.go","code":"// RecordEtcdEvent updated the etcd_events_received_total metric.\nfunc RecordEtcdEvent(resource string) {\n\tetcdEventsReceivedCounts.WithLabelValues(resource).Inc()\n}","line":{"from":165,"to":168}} {"id":100018638,"name":"RecordEtcdBookmark","signature":"func RecordEtcdBookmark(resource string)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/metrics/metrics.go","code":"// RecordEtcdBookmark updates the etcd_bookmark_counts metric.\nfunc RecordEtcdBookmark(resource string) {\n\tetcdBookmarkCounts.WithLabelValues(resource).Inc()\n}","line":{"from":170,"to":173}} {"id":100018639,"name":"RecordDecodeError","signature":"func RecordDecodeError(resource string)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/metrics/metrics.go","code":"// RecordDecodeError sets the storage_decode_errors metrics.\nfunc RecordDecodeError(resource string) {\n\tdecodeErrorCounts.WithLabelValues(resource).Inc()\n}","line":{"from":175,"to":178}} {"id":100018640,"name":"Reset","signature":"func Reset()","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/metrics/metrics.go","code":"// Reset resets the etcd_request_duration_seconds metric.\nfunc Reset() {\n\tetcdRequestLatency.Reset()\n}","line":{"from":180,"to":183}} {"id":100018641,"name":"sinceInSeconds","signature":"func sinceInSeconds(start time.Time) float64","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/metrics/metrics.go","code":"// sinceInSeconds gets the time since the specified start in seconds.\nfunc sinceInSeconds(start time.Time) float64 {\n\treturn time.Since(start).Seconds()\n}","line":{"from":185,"to":188}} {"id":100018642,"name":"UpdateEtcdDbSize","signature":"func UpdateEtcdDbSize(ep string, size int64)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/metrics/metrics.go","code":"// UpdateEtcdDbSize sets the etcd_db_total_size_in_bytes metric.\nfunc UpdateEtcdDbSize(ep string, size int64) {\n\tdbTotalSize.WithLabelValues(ep).Set(float64(size))\n}","line":{"from":190,"to":193}} {"id":100018643,"name":"UpdateLeaseObjectCount","signature":"func UpdateLeaseObjectCount(count int64)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/metrics/metrics.go","code":"// UpdateLeaseObjectCount sets the etcd_lease_object_counts metric.\nfunc UpdateLeaseObjectCount(count int64) {\n\t// Currently we only store one previous lease, since all the events have the same ttl.\n\t// See pkg/storage/etcd3/lease_manager.go\n\tetcdLeaseObjectCounts.WithLabelValues().Observe(float64(count))\n}","line":{"from":195,"to":200}} {"id":100018644,"name":"RecordStorageListMetrics","signature":"func RecordStorageListMetrics(resource string, numFetched, numEvald, numReturned int)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/metrics/metrics.go","code":"// RecordListEtcd3Metrics notes various metrics of the cost to serve a LIST request\nfunc RecordStorageListMetrics(resource string, numFetched, numEvald, numReturned int) {\n\tlistStorageCount.WithLabelValues(resource).Inc()\n\tlistStorageNumFetched.WithLabelValues(resource).Add(float64(numFetched))\n\tlistStorageNumSelectorEvals.WithLabelValues(resource).Add(float64(numEvald))\n\tlistStorageNumReturned.WithLabelValues(resource).Add(float64(numReturned))\n}","line":{"from":202,"to":208}} {"id":100018645,"name":"serverReachable","signature":"func (EtcdConnection) serverReachable(connURL *url.URL) bool","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/preflight/checks.go","code":"func (EtcdConnection) serverReachable(connURL *url.URL) bool {\n\tscheme := connURL.Scheme\n\tif scheme == \"http\" || scheme == \"https\" || scheme == \"tcp\" {\n\t\tscheme = \"tcp\"\n\t}\n\tif conn, err := net.DialTimeout(scheme, connURL.Host, connectionTimeout); err == nil {\n\t\tdefer conn.Close()\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":34,"to":44}} {"id":100018646,"name":"parseServerURI","signature":"func parseServerURI(serverURI string) (*url.URL, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/preflight/checks.go","code":"func parseServerURI(serverURI string) (*url.URL, error) {\n\tconnURL, err := url.Parse(serverURI)\n\tif err != nil {\n\t\treturn \u0026url.URL{}, fmt.Errorf(\"unable to parse etcd url: %v\", err)\n\t}\n\treturn connURL, nil\n}","line":{"from":46,"to":52}} {"id":100018647,"name":"CheckEtcdServers","signature":"func (con EtcdConnection) CheckEtcdServers() (done bool, err error)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/preflight/checks.go","code":"// CheckEtcdServers will attempt to reach all etcd servers once. If any\n// can be reached, return true.\nfunc (con EtcdConnection) CheckEtcdServers() (done bool, err error) {\n\t// Attempt to reach every Etcd server randomly.\n\tserverNumber := len(con.ServerList)\n\tserverPerms := rand.Perm(serverNumber)\n\tfor _, index := range serverPerms {\n\t\thost, err := parseServerURI(con.ServerList[index])\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif con.serverReachable(host) {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}","line":{"from":54,"to":70}} {"id":100018648,"name":"AuthenticatedData","signature":"func (d authenticatedDataString) AuthenticatedData() []byte","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go","code":"// AuthenticatedData implements the value.Context interface.\nfunc (d authenticatedDataString) AuthenticatedData() []byte {\n\treturn []byte(string(d))\n}","line":{"from":68,"to":71}} {"id":100018649,"name":"New","signature":"func New(c *clientv3.Client, codec runtime.Codec, newFunc func() runtime.Object, prefix string, groupResource schema.GroupResource, transformer value.Transformer, pagingEnabled bool, leaseManagerConfig LeaseManagerConfig) storage.Interface","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go","code":"// New returns an etcd3 implementation of storage.Interface.\nfunc New(c *clientv3.Client, codec runtime.Codec, newFunc func() runtime.Object, prefix string, groupResource schema.GroupResource, transformer value.Transformer, pagingEnabled bool, leaseManagerConfig LeaseManagerConfig) storage.Interface {\n\treturn newStore(c, codec, newFunc, prefix, groupResource, transformer, pagingEnabled, leaseManagerConfig)\n}","line":{"from":96,"to":99}} {"id":100018650,"name":"newStore","signature":"func newStore(c *clientv3.Client, codec runtime.Codec, newFunc func() runtime.Object, prefix string, groupResource schema.GroupResource, transformer value.Transformer, pagingEnabled bool, leaseManagerConfig LeaseManagerConfig) *store","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go","code":"func newStore(c *clientv3.Client, codec runtime.Codec, newFunc func() runtime.Object, prefix string, groupResource schema.GroupResource, transformer value.Transformer, pagingEnabled bool, leaseManagerConfig LeaseManagerConfig) *store {\n\tversioner := storage.APIObjectVersioner{}\n\t// for compatibility with etcd2 impl.\n\t// no-op for default prefix of '/registry'.\n\t// keeps compatibility with etcd2 impl for custom prefixes that don't start with '/'\n\tpathPrefix := path.Join(\"/\", prefix)\n\tif !strings.HasSuffix(pathPrefix, \"/\") {\n\t\t// Ensure the pathPrefix ends in \"/\" here to simplify key concatenation later.\n\t\tpathPrefix += \"/\"\n\t}\n\tresult := \u0026store{\n\t\tclient: c,\n\t\tcodec: codec,\n\t\tversioner: versioner,\n\t\ttransformer: transformer,\n\t\tpagingEnabled: pagingEnabled,\n\t\tpathPrefix: pathPrefix,\n\t\tgroupResource: groupResource,\n\t\tgroupResourceString: groupResource.String(),\n\t\twatcher: newWatcher(c, codec, groupResource, newFunc, versioner),\n\t\tleaseManager: newDefaultLeaseManager(c, leaseManagerConfig),\n\t}\n\treturn result\n}","line":{"from":101,"to":124}} {"id":100018651,"name":"Versioner","signature":"func (s *store) Versioner() storage.Versioner","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go","code":"// Versioner implements storage.Interface.Versioner.\nfunc (s *store) Versioner() storage.Versioner {\n\treturn s.versioner\n}","line":{"from":126,"to":129}} {"id":100018652,"name":"Get","signature":"func (s *store) Get(ctx context.Context, key string, opts storage.GetOptions, out runtime.Object) error","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go","code":"// Get implements storage.Interface.Get.\nfunc (s *store) Get(ctx context.Context, key string, opts storage.GetOptions, out runtime.Object) error {\n\tpreparedKey, err := s.prepareKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstartTime := time.Now()\n\tgetResp, err := s.client.KV.Get(ctx, preparedKey)\n\tmetrics.RecordEtcdRequestLatency(\"get\", s.groupResourceString, startTime)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = s.validateMinimumResourceVersion(opts.ResourceVersion, uint64(getResp.Header.Revision)); err != nil {\n\t\treturn err\n\t}\n\n\tif len(getResp.Kvs) == 0 {\n\t\tif opts.IgnoreNotFound {\n\t\t\treturn runtime.SetZeroValue(out)\n\t\t}\n\t\treturn storage.NewKeyNotFoundError(preparedKey, 0)\n\t}\n\tkv := getResp.Kvs[0]\n\n\tdata, _, err := s.transformer.TransformFromStorage(ctx, kv.Value, authenticatedDataString(preparedKey))\n\tif err != nil {\n\t\treturn storage.NewInternalError(err.Error())\n\t}\n\n\terr = decode(s.codec, s.versioner, data, out, kv.ModRevision)\n\tif err != nil {\n\t\trecordDecodeError(s.groupResourceString, preparedKey)\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":131,"to":166}} {"id":100018653,"name":"Create","signature":"func (s *store) Create(ctx context.Context, key string, obj, out runtime.Object, ttl uint64) error","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go","code":"// Create implements storage.Interface.Create.\nfunc (s *store) Create(ctx context.Context, key string, obj, out runtime.Object, ttl uint64) error {\n\tpreparedKey, err := s.prepareKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tctx, span := tracing.Start(ctx, \"Create etcd3\",\n\t\tattribute.String(\"audit-id\", audit.GetAuditIDTruncated(ctx)),\n\t\tattribute.String(\"key\", key),\n\t\tattribute.String(\"type\", getTypeName(obj)),\n\t\tattribute.String(\"resource\", s.groupResourceString),\n\t)\n\tdefer span.End(500 * time.Millisecond)\n\tif version, err := s.versioner.ObjectResourceVersion(obj); err == nil \u0026\u0026 version != 0 {\n\t\treturn errors.New(\"resourceVersion should not be set on objects to be created\")\n\t}\n\tif err := s.versioner.PrepareObjectForStorage(obj); err != nil {\n\t\treturn fmt.Errorf(\"PrepareObjectForStorage failed: %v\", err)\n\t}\n\tspan.AddEvent(\"About to Encode\")\n\tdata, err := runtime.Encode(s.codec, obj)\n\tif err != nil {\n\t\tspan.AddEvent(\"Encode failed\", attribute.Int(\"len\", len(data)), attribute.String(\"err\", err.Error()))\n\t\treturn err\n\t}\n\tspan.AddEvent(\"Encode succeeded\", attribute.Int(\"len\", len(data)))\n\n\topts, err := s.ttlOpts(ctx, int64(ttl))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnewData, err := s.transformer.TransformToStorage(ctx, data, authenticatedDataString(preparedKey))\n\tif err != nil {\n\t\tspan.AddEvent(\"TransformToStorage failed\", attribute.String(\"err\", err.Error()))\n\t\treturn storage.NewInternalError(err.Error())\n\t}\n\tspan.AddEvent(\"TransformToStorage succeeded\")\n\n\tstartTime := time.Now()\n\ttxnResp, err := s.client.KV.Txn(ctx).If(\n\t\tnotFound(preparedKey),\n\t).Then(\n\t\tclientv3.OpPut(preparedKey, string(newData), opts...),\n\t).Commit()\n\tmetrics.RecordEtcdRequestLatency(\"create\", s.groupResourceString, startTime)\n\tif err != nil {\n\t\tspan.AddEvent(\"Txn call failed\", attribute.String(\"err\", err.Error()))\n\t\treturn err\n\t}\n\tspan.AddEvent(\"Txn call succeeded\")\n\n\tif !txnResp.Succeeded {\n\t\treturn storage.NewKeyExistsError(preparedKey, 0)\n\t}\n\n\tif out != nil {\n\t\tputResp := txnResp.Responses[0].GetResponsePut()\n\t\terr = decode(s.codec, s.versioner, data, out, putResp.Header.Revision)\n\t\tif err != nil {\n\t\t\tspan.AddEvent(\"decode failed\", attribute.Int(\"len\", len(data)), attribute.String(\"err\", err.Error()))\n\t\t\trecordDecodeError(s.groupResourceString, preparedKey)\n\t\t\treturn err\n\t\t}\n\t\tspan.AddEvent(\"decode succeeded\", attribute.Int(\"len\", len(data)))\n\t}\n\treturn nil\n}","line":{"from":168,"to":235}} {"id":100018654,"name":"Delete","signature":"func (s *store) Delete(","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go","code":"// Delete implements storage.Interface.Delete.\nfunc (s *store) Delete(\n\tctx context.Context, key string, out runtime.Object, preconditions *storage.Preconditions,\n\tvalidateDeletion storage.ValidateObjectFunc, cachedExistingObject runtime.Object) error {\n\tpreparedKey, err := s.prepareKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv, err := conversion.EnforcePtr(out)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to convert output object to pointer: %v\", err)\n\t}\n\treturn s.conditionalDelete(ctx, preparedKey, out, v, preconditions, validateDeletion, cachedExistingObject)\n}","line":{"from":237,"to":250}} {"id":100018655,"name":"conditionalDelete","signature":"func (s *store) conditionalDelete(","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go","code":"func (s *store) conditionalDelete(\n\tctx context.Context, key string, out runtime.Object, v reflect.Value, preconditions *storage.Preconditions,\n\tvalidateDeletion storage.ValidateObjectFunc, cachedExistingObject runtime.Object) error {\n\tgetCurrentState := func() (*objState, error) {\n\t\tstartTime := time.Now()\n\t\tgetResp, err := s.client.KV.Get(ctx, key)\n\t\tmetrics.RecordEtcdRequestLatency(\"get\", s.groupResourceString, startTime)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn s.getState(ctx, getResp, key, v, false)\n\t}\n\n\tvar origState *objState\n\tvar err error\n\tvar origStateIsCurrent bool\n\tif cachedExistingObject != nil {\n\t\torigState, err = s.getStateFromObject(cachedExistingObject)\n\t} else {\n\t\torigState, err = getCurrentState()\n\t\torigStateIsCurrent = true\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor {\n\t\tif preconditions != nil {\n\t\t\tif err := preconditions.Check(key, origState.obj); err != nil {\n\t\t\t\tif origStateIsCurrent {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\t// It's possible we're working with stale data.\n\t\t\t\t// Remember the revision of the potentially stale data and the resulting update error\n\t\t\t\tcachedRev := origState.rev\n\t\t\t\tcachedUpdateErr := err\n\n\t\t\t\t// Actually fetch\n\t\t\t\torigState, err = getCurrentState()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\torigStateIsCurrent = true\n\n\t\t\t\t// it turns out our cached data was not stale, return the error\n\t\t\t\tif cachedRev == origState.rev {\n\t\t\t\t\treturn cachedUpdateErr\n\t\t\t\t}\n\n\t\t\t\t// Retry\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif err := validateDeletion(ctx, origState.obj); err != nil {\n\t\t\tif origStateIsCurrent {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// It's possible we're working with stale data.\n\t\t\t// Remember the revision of the potentially stale data and the resulting update error\n\t\t\tcachedRev := origState.rev\n\t\t\tcachedUpdateErr := err\n\n\t\t\t// Actually fetch\n\t\t\torigState, err = getCurrentState()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torigStateIsCurrent = true\n\n\t\t\t// it turns out our cached data was not stale, return the error\n\t\t\tif cachedRev == origState.rev {\n\t\t\t\treturn cachedUpdateErr\n\t\t\t}\n\n\t\t\t// Retry\n\t\t\tcontinue\n\t\t}\n\n\t\tstartTime := time.Now()\n\t\ttxnResp, err := s.client.KV.Txn(ctx).If(\n\t\t\tclientv3.Compare(clientv3.ModRevision(key), \"=\", origState.rev),\n\t\t).Then(\n\t\t\tclientv3.OpDelete(key),\n\t\t).Else(\n\t\t\tclientv3.OpGet(key),\n\t\t).Commit()\n\t\tmetrics.RecordEtcdRequestLatency(\"delete\", s.groupResourceString, startTime)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !txnResp.Succeeded {\n\t\t\tgetResp := (*clientv3.GetResponse)(txnResp.Responses[0].GetResponseRange())\n\t\t\tklog.V(4).Infof(\"deletion of %s failed because of a conflict, going to retry\", key)\n\t\t\torigState, err = s.getState(ctx, getResp, key, v, false)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torigStateIsCurrent = true\n\t\t\tcontinue\n\t\t}\n\n\t\tif len(txnResp.Responses) == 0 || txnResp.Responses[0].GetResponseDeleteRange() == nil {\n\t\t\treturn errors.New(fmt.Sprintf(\"invalid DeleteRange response: %v\", txnResp.Responses))\n\t\t}\n\t\tdeleteResp := txnResp.Responses[0].GetResponseDeleteRange()\n\t\tif deleteResp.Header == nil {\n\t\t\treturn errors.New(\"invalid DeleteRange response - nil header\")\n\t\t}\n\t\terr = decode(s.codec, s.versioner, origState.data, out, deleteResp.Header.Revision)\n\t\tif err != nil {\n\t\t\trecordDecodeError(s.groupResourceString, key)\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n}","line":{"from":252,"to":369}} {"id":100018656,"name":"GuaranteedUpdate","signature":"func (s *store) GuaranteedUpdate(","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go","code":"// GuaranteedUpdate implements storage.Interface.GuaranteedUpdate.\nfunc (s *store) GuaranteedUpdate(\n\tctx context.Context, key string, destination runtime.Object, ignoreNotFound bool,\n\tpreconditions *storage.Preconditions, tryUpdate storage.UpdateFunc, cachedExistingObject runtime.Object) error {\n\tpreparedKey, err := s.prepareKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tctx, span := tracing.Start(ctx, \"GuaranteedUpdate etcd3\",\n\t\tattribute.String(\"audit-id\", audit.GetAuditIDTruncated(ctx)),\n\t\tattribute.String(\"key\", key),\n\t\tattribute.String(\"type\", getTypeName(destination)),\n\t\tattribute.String(\"resource\", s.groupResourceString))\n\tdefer span.End(500 * time.Millisecond)\n\n\tv, err := conversion.EnforcePtr(destination)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to convert output object to pointer: %v\", err)\n\t}\n\n\tgetCurrentState := func() (*objState, error) {\n\t\tstartTime := time.Now()\n\t\tgetResp, err := s.client.KV.Get(ctx, preparedKey)\n\t\tmetrics.RecordEtcdRequestLatency(\"get\", s.groupResourceString, startTime)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn s.getState(ctx, getResp, preparedKey, v, ignoreNotFound)\n\t}\n\n\tvar origState *objState\n\tvar origStateIsCurrent bool\n\tif cachedExistingObject != nil {\n\t\torigState, err = s.getStateFromObject(cachedExistingObject)\n\t} else {\n\t\torigState, err = getCurrentState()\n\t\torigStateIsCurrent = true\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tspan.AddEvent(\"initial value restored\")\n\n\ttransformContext := authenticatedDataString(preparedKey)\n\tfor {\n\t\tif err := preconditions.Check(preparedKey, origState.obj); err != nil {\n\t\t\t// If our data is already up to date, return the error\n\t\t\tif origStateIsCurrent {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// It's possible we were working with stale data\n\t\t\t// Actually fetch\n\t\t\torigState, err = getCurrentState()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torigStateIsCurrent = true\n\t\t\t// Retry\n\t\t\tcontinue\n\t\t}\n\n\t\tret, ttl, err := s.updateState(origState, tryUpdate)\n\t\tif err != nil {\n\t\t\t// If our data is already up to date, return the error\n\t\t\tif origStateIsCurrent {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// It's possible we were working with stale data\n\t\t\t// Remember the revision of the potentially stale data and the resulting update error\n\t\t\tcachedRev := origState.rev\n\t\t\tcachedUpdateErr := err\n\n\t\t\t// Actually fetch\n\t\t\torigState, err = getCurrentState()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torigStateIsCurrent = true\n\n\t\t\t// it turns out our cached data was not stale, return the error\n\t\t\tif cachedRev == origState.rev {\n\t\t\t\treturn cachedUpdateErr\n\t\t\t}\n\n\t\t\t// Retry\n\t\t\tcontinue\n\t\t}\n\n\t\tspan.AddEvent(\"About to Encode\")\n\t\tdata, err := runtime.Encode(s.codec, ret)\n\t\tif err != nil {\n\t\t\tspan.AddEvent(\"Encode failed\", attribute.Int(\"len\", len(data)), attribute.String(\"err\", err.Error()))\n\t\t\treturn err\n\t\t}\n\t\tspan.AddEvent(\"Encode succeeded\", attribute.Int(\"len\", len(data)))\n\t\tif !origState.stale \u0026\u0026 bytes.Equal(data, origState.data) {\n\t\t\t// if we skipped the original Get in this loop, we must refresh from\n\t\t\t// etcd in order to be sure the data in the store is equivalent to\n\t\t\t// our desired serialization\n\t\t\tif !origStateIsCurrent {\n\t\t\t\torigState, err = getCurrentState()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\torigStateIsCurrent = true\n\t\t\t\tif !bytes.Equal(data, origState.data) {\n\t\t\t\t\t// original data changed, restart loop\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\t// recheck that the data from etcd is not stale before short-circuiting a write\n\t\t\tif !origState.stale {\n\t\t\t\terr = decode(s.codec, s.versioner, origState.data, destination, origState.rev)\n\t\t\t\tif err != nil {\n\t\t\t\t\trecordDecodeError(s.groupResourceString, preparedKey)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\tnewData, err := s.transformer.TransformToStorage(ctx, data, transformContext)\n\t\tif err != nil {\n\t\t\tspan.AddEvent(\"TransformToStorage failed\", attribute.String(\"err\", err.Error()))\n\t\t\treturn storage.NewInternalError(err.Error())\n\t\t}\n\t\tspan.AddEvent(\"TransformToStorage succeeded\")\n\n\t\topts, err := s.ttlOpts(ctx, int64(ttl))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tspan.AddEvent(\"Transaction prepared\")\n\n\t\tstartTime := time.Now()\n\t\ttxnResp, err := s.client.KV.Txn(ctx).If(\n\t\t\tclientv3.Compare(clientv3.ModRevision(preparedKey), \"=\", origState.rev),\n\t\t).Then(\n\t\t\tclientv3.OpPut(preparedKey, string(newData), opts...),\n\t\t).Else(\n\t\t\tclientv3.OpGet(preparedKey),\n\t\t).Commit()\n\t\tmetrics.RecordEtcdRequestLatency(\"update\", s.groupResourceString, startTime)\n\t\tif err != nil {\n\t\t\tspan.AddEvent(\"Txn call failed\", attribute.String(\"err\", err.Error()))\n\t\t\treturn err\n\t\t}\n\t\tspan.AddEvent(\"Txn call completed\")\n\t\tspan.AddEvent(\"Transaction committed\")\n\t\tif !txnResp.Succeeded {\n\t\t\tgetResp := (*clientv3.GetResponse)(txnResp.Responses[0].GetResponseRange())\n\t\t\tklog.V(4).Infof(\"GuaranteedUpdate of %s failed because of a conflict, going to retry\", preparedKey)\n\t\t\torigState, err = s.getState(ctx, getResp, preparedKey, v, ignoreNotFound)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tspan.AddEvent(\"Retry value restored\")\n\t\t\torigStateIsCurrent = true\n\t\t\tcontinue\n\t\t}\n\t\tputResp := txnResp.Responses[0].GetResponsePut()\n\n\t\terr = decode(s.codec, s.versioner, data, destination, putResp.Header.Revision)\n\t\tif err != nil {\n\t\t\tspan.AddEvent(\"decode failed\", attribute.Int(\"len\", len(data)), attribute.String(\"err\", err.Error()))\n\t\t\trecordDecodeError(s.groupResourceString, preparedKey)\n\t\t\treturn err\n\t\t}\n\t\tspan.AddEvent(\"decode succeeded\", attribute.Int(\"len\", len(data)))\n\t\treturn nil\n\t}\n}","line":{"from":371,"to":544}} {"id":100018657,"name":"getNewItemFunc","signature":"func getNewItemFunc(listObj runtime.Object, v reflect.Value) func() runtime.Object","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go","code":"func getNewItemFunc(listObj runtime.Object, v reflect.Value) func() runtime.Object {\n\t// For unstructured lists with a target group/version, preserve the group/version in the instantiated list items\n\tif unstructuredList, isUnstructured := listObj.(*unstructured.UnstructuredList); isUnstructured {\n\t\tif apiVersion := unstructuredList.GetAPIVersion(); len(apiVersion) \u003e 0 {\n\t\t\treturn func() runtime.Object {\n\t\t\t\treturn \u0026unstructured.Unstructured{Object: map[string]interface{}{\"apiVersion\": apiVersion}}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Otherwise just instantiate an empty item\n\telem := v.Type().Elem()\n\treturn func() runtime.Object {\n\t\treturn reflect.New(elem).Interface().(runtime.Object)\n\t}\n}","line":{"from":546,"to":561}} {"id":100018658,"name":"Count","signature":"func (s *store) Count(key string) (int64, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go","code":"func (s *store) Count(key string) (int64, error) {\n\tpreparedKey, err := s.prepareKey(key)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// We need to make sure the key ended with \"/\" so that we only get children \"directories\".\n\t// e.g. if we have key \"/a\", \"/a/b\", \"/ab\", getting keys with prefix \"/a\" will return all three,\n\t// while with prefix \"/a/\" will return only \"/a/b\" which is the correct answer.\n\tif !strings.HasSuffix(preparedKey, \"/\") {\n\t\tpreparedKey += \"/\"\n\t}\n\n\tstartTime := time.Now()\n\tgetResp, err := s.client.KV.Get(context.Background(), preparedKey, clientv3.WithRange(clientv3.GetPrefixRangeEnd(preparedKey)), clientv3.WithCountOnly())\n\tmetrics.RecordEtcdRequestLatency(\"listWithCount\", preparedKey, startTime)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn getResp.Count, nil\n}","line":{"from":563,"to":583}} {"id":100018659,"name":"GetList","signature":"func (s *store) GetList(ctx context.Context, key string, opts storage.ListOptions, listObj runtime.Object) error","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go","code":"// GetList implements storage.Interface.\nfunc (s *store) GetList(ctx context.Context, key string, opts storage.ListOptions, listObj runtime.Object) error {\n\tpreparedKey, err := s.prepareKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\trecursive := opts.Recursive\n\tresourceVersion := opts.ResourceVersion\n\tmatch := opts.ResourceVersionMatch\n\tpred := opts.Predicate\n\tctx, span := tracing.Start(ctx, fmt.Sprintf(\"List(recursive=%v) etcd3\", recursive),\n\t\tattribute.String(\"audit-id\", audit.GetAuditIDTruncated(ctx)),\n\t\tattribute.String(\"key\", key),\n\t\tattribute.String(\"resourceVersion\", resourceVersion),\n\t\tattribute.String(\"resourceVersionMatch\", string(match)),\n\t\tattribute.Int(\"limit\", int(pred.Limit)),\n\t\tattribute.String(\"continue\", pred.Continue))\n\tdefer span.End(500 * time.Millisecond)\n\tlistPtr, err := meta.GetItemsPtr(listObj)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv, err := conversion.EnforcePtr(listPtr)\n\tif err != nil || v.Kind() != reflect.Slice {\n\t\treturn fmt.Errorf(\"need ptr to slice: %v\", err)\n\t}\n\n\t// For recursive lists, we need to make sure the key ended with \"/\" so that we only\n\t// get children \"directories\". e.g. if we have key \"/a\", \"/a/b\", \"/ab\", getting keys\n\t// with prefix \"/a\" will return all three, while with prefix \"/a/\" will return only\n\t// \"/a/b\" which is the correct answer.\n\tif recursive \u0026\u0026 !strings.HasSuffix(preparedKey, \"/\") {\n\t\tpreparedKey += \"/\"\n\t}\n\tkeyPrefix := preparedKey\n\n\t// set the appropriate clientv3 options to filter the returned data set\n\tvar limitOption *clientv3.OpOption\n\tlimit := pred.Limit\n\tvar paging bool\n\toptions := make([]clientv3.OpOption, 0, 4)\n\tif s.pagingEnabled \u0026\u0026 pred.Limit \u003e 0 {\n\t\tpaging = true\n\t\toptions = append(options, clientv3.WithLimit(limit))\n\t\tlimitOption = \u0026options[len(options)-1]\n\t}\n\n\tnewItemFunc := getNewItemFunc(listObj, v)\n\n\tvar fromRV *uint64\n\tif len(resourceVersion) \u003e 0 {\n\t\tparsedRV, err := s.versioner.ParseResourceVersion(resourceVersion)\n\t\tif err != nil {\n\t\t\treturn apierrors.NewBadRequest(fmt.Sprintf(\"invalid resource version: %v\", err))\n\t\t}\n\t\tfromRV = \u0026parsedRV\n\t}\n\n\tvar returnedRV, continueRV, withRev int64\n\tvar continueKey string\n\tswitch {\n\tcase recursive \u0026\u0026 s.pagingEnabled \u0026\u0026 len(pred.Continue) \u003e 0:\n\t\tcontinueKey, continueRV, err = storage.DecodeContinue(pred.Continue, keyPrefix)\n\t\tif err != nil {\n\t\t\treturn apierrors.NewBadRequest(fmt.Sprintf(\"invalid continue token: %v\", err))\n\t\t}\n\n\t\tif len(resourceVersion) \u003e 0 \u0026\u0026 resourceVersion != \"0\" {\n\t\t\treturn apierrors.NewBadRequest(\"specifying resource version is not allowed when using continue\")\n\t\t}\n\n\t\trangeEnd := clientv3.GetPrefixRangeEnd(keyPrefix)\n\t\toptions = append(options, clientv3.WithRange(rangeEnd))\n\t\tpreparedKey = continueKey\n\n\t\t// If continueRV \u003e 0, the LIST request needs a specific resource version.\n\t\t// continueRV==0 is invalid.\n\t\t// If continueRV \u003c 0, the request is for the latest resource version.\n\t\tif continueRV \u003e 0 {\n\t\t\twithRev = continueRV\n\t\t\treturnedRV = continueRV\n\t\t}\n\tcase recursive \u0026\u0026 s.pagingEnabled \u0026\u0026 pred.Limit \u003e 0:\n\t\tif fromRV != nil {\n\t\t\tswitch match {\n\t\t\tcase metav1.ResourceVersionMatchNotOlderThan:\n\t\t\t\t// The not older than constraint is checked after we get a response from etcd,\n\t\t\t\t// and returnedRV is then set to the revision we get from the etcd response.\n\t\t\tcase metav1.ResourceVersionMatchExact:\n\t\t\t\treturnedRV = int64(*fromRV)\n\t\t\t\twithRev = returnedRV\n\t\t\tcase \"\": // legacy case\n\t\t\t\tif *fromRV \u003e 0 {\n\t\t\t\t\treturnedRV = int64(*fromRV)\n\t\t\t\t\twithRev = returnedRV\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"unknown ResourceVersionMatch value: %v\", match)\n\t\t\t}\n\t\t}\n\n\t\trangeEnd := clientv3.GetPrefixRangeEnd(keyPrefix)\n\t\toptions = append(options, clientv3.WithRange(rangeEnd))\n\tdefault:\n\t\tif fromRV != nil {\n\t\t\tswitch match {\n\t\t\tcase metav1.ResourceVersionMatchNotOlderThan:\n\t\t\t\t// The not older than constraint is checked after we get a response from etcd,\n\t\t\t\t// and returnedRV is then set to the revision we get from the etcd response.\n\t\t\tcase metav1.ResourceVersionMatchExact:\n\t\t\t\treturnedRV = int64(*fromRV)\n\t\t\t\twithRev = returnedRV\n\t\t\tcase \"\": // legacy case\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"unknown ResourceVersionMatch value: %v\", match)\n\t\t\t}\n\t\t}\n\n\t\tif recursive {\n\t\t\toptions = append(options, clientv3.WithPrefix())\n\t\t}\n\t}\n\tif withRev != 0 {\n\t\toptions = append(options, clientv3.WithRev(withRev))\n\t}\n\n\t// loop until we have filled the requested limit from etcd or there are no more results\n\tvar lastKey []byte\n\tvar hasMore bool\n\tvar getResp *clientv3.GetResponse\n\tvar numFetched int\n\tvar numEvald int\n\t// Because these metrics are for understanding the costs of handling LIST requests,\n\t// get them recorded even in error cases.\n\tdefer func() {\n\t\tnumReturn := v.Len()\n\t\tmetrics.RecordStorageListMetrics(s.groupResourceString, numFetched, numEvald, numReturn)\n\t}()\n\tfor {\n\t\tstartTime := time.Now()\n\t\tgetResp, err = s.client.KV.Get(ctx, preparedKey, options...)\n\t\tif recursive {\n\t\t\tmetrics.RecordEtcdRequestLatency(\"list\", s.groupResourceString, startTime)\n\t\t} else {\n\t\t\tmetrics.RecordEtcdRequestLatency(\"get\", s.groupResourceString, startTime)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn interpretListError(err, len(pred.Continue) \u003e 0, continueKey, keyPrefix)\n\t\t}\n\t\tnumFetched += len(getResp.Kvs)\n\t\tif err = s.validateMinimumResourceVersion(resourceVersion, uint64(getResp.Header.Revision)); err != nil {\n\t\t\treturn err\n\t\t}\n\t\thasMore = getResp.More\n\n\t\tif len(getResp.Kvs) == 0 \u0026\u0026 getResp.More {\n\t\t\treturn fmt.Errorf(\"no results were found, but etcd indicated there were more values remaining\")\n\t\t}\n\n\t\t// avoid small allocations for the result slice, since this can be called in many\n\t\t// different contexts and we don't know how significantly the result will be filtered\n\t\tif pred.Empty() {\n\t\t\tgrowSlice(v, len(getResp.Kvs))\n\t\t} else {\n\t\t\tgrowSlice(v, 2048, len(getResp.Kvs))\n\t\t}\n\n\t\t// take items from the response until the bucket is full, filtering as we go\n\t\tfor i, kv := range getResp.Kvs {\n\t\t\tif paging \u0026\u0026 int64(v.Len()) \u003e= pred.Limit {\n\t\t\t\thasMore = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tlastKey = kv.Key\n\n\t\t\tdata, _, err := s.transformer.TransformFromStorage(ctx, kv.Value, authenticatedDataString(kv.Key))\n\t\t\tif err != nil {\n\t\t\t\treturn storage.NewInternalErrorf(\"unable to transform key %q: %v\", kv.Key, err)\n\t\t\t}\n\n\t\t\tif err := appendListItem(v, data, uint64(kv.ModRevision), pred, s.codec, s.versioner, newItemFunc); err != nil {\n\t\t\t\trecordDecodeError(s.groupResourceString, string(kv.Key))\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tnumEvald++\n\n\t\t\t// free kv early. Long lists can take O(seconds) to decode.\n\t\t\tgetResp.Kvs[i] = nil\n\t\t}\n\n\t\t// indicate to the client which resource version was returned\n\t\tif returnedRV == 0 {\n\t\t\treturnedRV = getResp.Header.Revision\n\t\t}\n\n\t\t// no more results remain or we didn't request paging\n\t\tif !hasMore || !paging {\n\t\t\tbreak\n\t\t}\n\t\t// we're paging but we have filled our bucket\n\t\tif int64(v.Len()) \u003e= pred.Limit {\n\t\t\tbreak\n\t\t}\n\n\t\tif limit \u003c maxLimit {\n\t\t\t// We got incomplete result due to field/label selector dropping the object.\n\t\t\t// Double page size to reduce total number of calls to etcd.\n\t\t\tlimit *= 2\n\t\t\tif limit \u003e maxLimit {\n\t\t\t\tlimit = maxLimit\n\t\t\t}\n\t\t\t*limitOption = clientv3.WithLimit(limit)\n\t\t}\n\t\tpreparedKey = string(lastKey) + \"\\x00\"\n\t\tif withRev == 0 {\n\t\t\twithRev = returnedRV\n\t\t\toptions = append(options, clientv3.WithRev(withRev))\n\t\t}\n\t}\n\tif v.IsNil() {\n\t\t// Ensure that we never return a nil Items pointer in the result for consistency.\n\t\tv.Set(reflect.MakeSlice(v.Type(), 0, 0))\n\t}\n\n\t// instruct the client to begin querying from immediately after the last key we returned\n\t// we never return a key that the client wouldn't be allowed to see\n\tif hasMore {\n\t\t// we want to start immediately after the last key\n\t\tnext, err := storage.EncodeContinue(string(lastKey)+\"\\x00\", keyPrefix, returnedRV)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar remainingItemCount *int64\n\t\t// getResp.Count counts in objects that do not match the pred.\n\t\t// Instead of returning inaccurate count for non-empty selectors, we return nil.\n\t\t// Only set remainingItemCount if the predicate is empty.\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.RemainingItemCount) {\n\t\t\tif pred.Empty() {\n\t\t\t\tc := int64(getResp.Count - pred.Limit)\n\t\t\t\tremainingItemCount = \u0026c\n\t\t\t}\n\t\t}\n\t\treturn s.versioner.UpdateList(listObj, uint64(returnedRV), next, remainingItemCount)\n\t}\n\n\t// no continuation\n\treturn s.versioner.UpdateList(listObj, uint64(returnedRV), \"\", nil)\n}","line":{"from":585,"to":832}} {"id":100018660,"name":"growSlice","signature":"func growSlice(v reflect.Value, maxCapacity int, sizes ...int)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go","code":"// growSlice takes a slice value and grows its capacity up\n// to the maximum of the passed sizes or maxCapacity, whichever\n// is smaller. Above maxCapacity decisions about allocation are left\n// to the Go runtime on append. This allows a caller to make an\n// educated guess about the potential size of the total list while\n// still avoiding overly aggressive initial allocation. If sizes\n// is empty maxCapacity will be used as the size to grow.\nfunc growSlice(v reflect.Value, maxCapacity int, sizes ...int) {\n\tcap := v.Cap()\n\tmax := cap\n\tfor _, size := range sizes {\n\t\tif size \u003e max {\n\t\t\tmax = size\n\t\t}\n\t}\n\tif len(sizes) == 0 || max \u003e maxCapacity {\n\t\tmax = maxCapacity\n\t}\n\tif max \u003c= cap {\n\t\treturn\n\t}\n\tif v.Len() \u003e 0 {\n\t\textra := reflect.MakeSlice(v.Type(), v.Len(), max)\n\t\treflect.Copy(extra, v)\n\t\tv.Set(extra)\n\t} else {\n\t\textra := reflect.MakeSlice(v.Type(), 0, max)\n\t\tv.Set(extra)\n\t}\n}","line":{"from":834,"to":863}} {"id":100018661,"name":"Watch","signature":"func (s *store) Watch(ctx context.Context, key string, opts storage.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go","code":"// Watch implements storage.Interface.Watch.\nfunc (s *store) Watch(ctx context.Context, key string, opts storage.ListOptions) (watch.Interface, error) {\n\tif opts.SendInitialEvents != nil {\n\t\treturn nil, apierrors.NewInvalid(\n\t\t\tschema.GroupKind{Group: s.groupResource.Group, Kind: s.groupResource.Resource},\n\t\t\t\"\",\n\t\t\tfield.ErrorList{field.Forbidden(field.NewPath(\"sendInitialEvents\"), \"for watch is unsupported by an etcd cluster\")},\n\t\t)\n\t}\n\tpreparedKey, err := s.prepareKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trev, err := s.versioner.ParseResourceVersion(opts.ResourceVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s.watcher.Watch(ctx, preparedKey, int64(rev), opts.Recursive, opts.ProgressNotify, s.transformer, opts.Predicate)\n}","line":{"from":865,"to":883}} {"id":100018662,"name":"getState","signature":"func (s *store) getState(ctx context.Context, getResp *clientv3.GetResponse, key string, v reflect.Value, ignoreNotFound bool) (*objState, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go","code":"func (s *store) getState(ctx context.Context, getResp *clientv3.GetResponse, key string, v reflect.Value, ignoreNotFound bool) (*objState, error) {\n\tstate := \u0026objState{\n\t\tmeta: \u0026storage.ResponseMeta{},\n\t}\n\n\tif u, ok := v.Addr().Interface().(runtime.Unstructured); ok {\n\t\tstate.obj = u.NewEmptyInstance()\n\t} else {\n\t\tstate.obj = reflect.New(v.Type()).Interface().(runtime.Object)\n\t}\n\n\tif len(getResp.Kvs) == 0 {\n\t\tif !ignoreNotFound {\n\t\t\treturn nil, storage.NewKeyNotFoundError(key, 0)\n\t\t}\n\t\tif err := runtime.SetZeroValue(state.obj); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tdata, stale, err := s.transformer.TransformFromStorage(ctx, getResp.Kvs[0].Value, authenticatedDataString(key))\n\t\tif err != nil {\n\t\t\treturn nil, storage.NewInternalError(err.Error())\n\t\t}\n\t\tstate.rev = getResp.Kvs[0].ModRevision\n\t\tstate.meta.ResourceVersion = uint64(state.rev)\n\t\tstate.data = data\n\t\tstate.stale = stale\n\t\tif err := decode(s.codec, s.versioner, state.data, state.obj, state.rev); err != nil {\n\t\t\trecordDecodeError(s.groupResourceString, key)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn state, nil\n}","line":{"from":885,"to":918}} {"id":100018663,"name":"getStateFromObject","signature":"func (s *store) getStateFromObject(obj runtime.Object) (*objState, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go","code":"func (s *store) getStateFromObject(obj runtime.Object) (*objState, error) {\n\tstate := \u0026objState{\n\t\tobj: obj,\n\t\tmeta: \u0026storage.ResponseMeta{},\n\t}\n\n\trv, err := s.versioner.ObjectResourceVersion(obj)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"couldn't get resource version: %v\", err)\n\t}\n\tstate.rev = int64(rv)\n\tstate.meta.ResourceVersion = uint64(state.rev)\n\n\t// Compute the serialized form - for that we need to temporarily clean\n\t// its resource version field (those are not stored in etcd).\n\tif err := s.versioner.PrepareObjectForStorage(obj); err != nil {\n\t\treturn nil, fmt.Errorf(\"PrepareObjectForStorage failed: %v\", err)\n\t}\n\tstate.data, err = runtime.Encode(s.codec, obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := s.versioner.UpdateObject(state.obj, uint64(rv)); err != nil {\n\t\tklog.Errorf(\"failed to update object version: %v\", err)\n\t}\n\treturn state, nil\n}","line":{"from":920,"to":946}} {"id":100018664,"name":"updateState","signature":"func (s *store) updateState(st *objState, userUpdate storage.UpdateFunc) (runtime.Object, uint64, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go","code":"func (s *store) updateState(st *objState, userUpdate storage.UpdateFunc) (runtime.Object, uint64, error) {\n\tret, ttlPtr, err := userUpdate(st.obj, *st.meta)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\tif err := s.versioner.PrepareObjectForStorage(ret); err != nil {\n\t\treturn nil, 0, fmt.Errorf(\"PrepareObjectForStorage failed: %v\", err)\n\t}\n\tvar ttl uint64\n\tif ttlPtr != nil {\n\t\tttl = *ttlPtr\n\t}\n\treturn ret, ttl, nil\n}","line":{"from":948,"to":962}} {"id":100018665,"name":"ttlOpts","signature":"func (s *store) ttlOpts(ctx context.Context, ttl int64) ([]clientv3.OpOption, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go","code":"// ttlOpts returns client options based on given ttl.\n// ttl: if ttl is non-zero, it will attach the key to a lease with ttl of roughly the same length\nfunc (s *store) ttlOpts(ctx context.Context, ttl int64) ([]clientv3.OpOption, error) {\n\tif ttl == 0 {\n\t\treturn nil, nil\n\t}\n\tid, err := s.leaseManager.GetLease(ctx, ttl)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn []clientv3.OpOption{clientv3.WithLease(id)}, nil\n}","line":{"from":964,"to":975}} {"id":100018666,"name":"validateMinimumResourceVersion","signature":"func (s *store) validateMinimumResourceVersion(minimumResourceVersion string, actualRevision uint64) error","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go","code":"// validateMinimumResourceVersion returns a 'too large resource' version error when the provided minimumResourceVersion is\n// greater than the most recent actualRevision available from storage.\nfunc (s *store) validateMinimumResourceVersion(minimumResourceVersion string, actualRevision uint64) error {\n\tif minimumResourceVersion == \"\" {\n\t\treturn nil\n\t}\n\tminimumRV, err := s.versioner.ParseResourceVersion(minimumResourceVersion)\n\tif err != nil {\n\t\treturn apierrors.NewBadRequest(fmt.Sprintf(\"invalid resource version: %v\", err))\n\t}\n\t// Enforce the storage.Interface guarantee that the resource version of the returned data\n\t// \"will be at least 'resourceVersion'\".\n\tif minimumRV \u003e actualRevision {\n\t\treturn storage.NewTooLargeResourceVersionError(minimumRV, actualRevision, 0)\n\t}\n\treturn nil\n}","line":{"from":977,"to":993}} {"id":100018667,"name":"prepareKey","signature":"func (s *store) prepareKey(key string) (string, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go","code":"func (s *store) prepareKey(key string) (string, error) {\n\tif key == \"..\" ||\n\t\tstrings.HasPrefix(key, \"../\") ||\n\t\tstrings.HasSuffix(key, \"/..\") ||\n\t\tstrings.Contains(key, \"/../\") {\n\t\treturn \"\", fmt.Errorf(\"invalid key: %q\", key)\n\t}\n\tif key == \".\" ||\n\t\tstrings.HasPrefix(key, \"./\") ||\n\t\tstrings.HasSuffix(key, \"/.\") ||\n\t\tstrings.Contains(key, \"/./\") {\n\t\treturn \"\", fmt.Errorf(\"invalid key: %q\", key)\n\t}\n\tif key == \"\" || key == \"/\" {\n\t\treturn \"\", fmt.Errorf(\"empty key: %q\", key)\n\t}\n\t// We ensured that pathPrefix ends in '/' in construction, so skip any leading '/' in the key now.\n\tstartIndex := 0\n\tif key[0] == '/' {\n\t\tstartIndex = 1\n\t}\n\treturn s.pathPrefix + key[startIndex:], nil\n}","line":{"from":995,"to":1017}} {"id":100018668,"name":"decode","signature":"func decode(codec runtime.Codec, versioner storage.Versioner, value []byte, objPtr runtime.Object, rev int64) error","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go","code":"// decode decodes value of bytes into object. It will also set the object resource version to rev.\n// On success, objPtr would be set to the object.\nfunc decode(codec runtime.Codec, versioner storage.Versioner, value []byte, objPtr runtime.Object, rev int64) error {\n\tif _, err := conversion.EnforcePtr(objPtr); err != nil {\n\t\treturn fmt.Errorf(\"unable to convert output object to pointer: %v\", err)\n\t}\n\t_, _, err := codec.Decode(value, nil, objPtr)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// being unable to set the version does not prevent the object from being extracted\n\tif err := versioner.UpdateObject(objPtr, uint64(rev)); err != nil {\n\t\tklog.Errorf(\"failed to update object version: %v\", err)\n\t}\n\treturn nil\n}","line":{"from":1019,"to":1034}} {"id":100018669,"name":"appendListItem","signature":"func appendListItem(v reflect.Value, data []byte, rev uint64, pred storage.SelectionPredicate, codec runtime.Codec, versioner storage.Versioner, newItemFunc func() runtime.Object) error","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go","code":"// appendListItem decodes and appends the object (if it passes filter) to v, which must be a slice.\nfunc appendListItem(v reflect.Value, data []byte, rev uint64, pred storage.SelectionPredicate, codec runtime.Codec, versioner storage.Versioner, newItemFunc func() runtime.Object) error {\n\tobj, _, err := codec.Decode(data, nil, newItemFunc())\n\tif err != nil {\n\t\treturn err\n\t}\n\t// being unable to set the version does not prevent the object from being extracted\n\tif err := versioner.UpdateObject(obj, rev); err != nil {\n\t\tklog.Errorf(\"failed to update object version: %v\", err)\n\t}\n\tif matched, err := pred.Matches(obj); err == nil \u0026\u0026 matched {\n\t\tv.Set(reflect.Append(v, reflect.ValueOf(obj).Elem()))\n\t}\n\treturn nil\n}","line":{"from":1036,"to":1050}} {"id":100018670,"name":"recordDecodeError","signature":"func recordDecodeError(resource string, key string)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go","code":"// recordDecodeError record decode error split by object type.\nfunc recordDecodeError(resource string, key string) {\n\tmetrics.RecordDecodeError(resource)\n\tklog.V(4).Infof(\"Decoding %s \\\"%s\\\" failed\", resource, key)\n}","line":{"from":1052,"to":1056}} {"id":100018671,"name":"notFound","signature":"func notFound(key string) clientv3.Cmp","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go","code":"func notFound(key string) clientv3.Cmp {\n\treturn clientv3.Compare(clientv3.ModRevision(key), \"=\", 0)\n}","line":{"from":1058,"to":1060}} {"id":100018672,"name":"getTypeName","signature":"func getTypeName(obj interface{}) string","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go","code":"// getTypeName returns type name of an object for reporting purposes.\nfunc getTypeName(obj interface{}) string {\n\treturn reflect.TypeOf(obj).String()\n}","line":{"from":1062,"to":1065}} {"id":100018673,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/watcher.go","code":"func init() {\n\t// check to see if we are running in a test environment\n\tTestOnlySetFatalOnDecodeError(true)\n\tfatalOnDecodeError, _ = strconv.ParseBool(os.Getenv(\"KUBE_PANIC_WATCH_DECODE_ERROR\"))\n}","line":{"from":54,"to":58}} {"id":100018674,"name":"TestOnlySetFatalOnDecodeError","signature":"func TestOnlySetFatalOnDecodeError(b bool)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/watcher.go","code":"// TestOnlySetFatalOnDecodeError should only be used for cases where decode errors are expected and need to be tested. e.g. conversion webhooks.\nfunc TestOnlySetFatalOnDecodeError(b bool) {\n\tfatalOnDecodeError = b\n}","line":{"from":60,"to":63}} {"id":100018675,"name":"newWatcher","signature":"func newWatcher(client *clientv3.Client, codec runtime.Codec, groupResource schema.GroupResource, newFunc func() runtime.Object, versioner storage.Versioner) *watcher","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/watcher.go","code":"func newWatcher(client *clientv3.Client, codec runtime.Codec, groupResource schema.GroupResource, newFunc func() runtime.Object, versioner storage.Versioner) *watcher {\n\tres := \u0026watcher{\n\t\tclient: client,\n\t\tcodec: codec,\n\t\tgroupResource: groupResource,\n\t\tnewFunc: newFunc,\n\t\tversioner: versioner,\n\t}\n\tif newFunc == nil {\n\t\tres.objectType = \"\u003cunknown\u003e\"\n\t} else {\n\t\tres.objectType = reflect.TypeOf(newFunc()).String()\n\t}\n\treturn res\n}","line":{"from":90,"to":104}} {"id":100018676,"name":"Watch","signature":"func (w *watcher) Watch(ctx context.Context, key string, rev int64, recursive, progressNotify bool, transformer value.Transformer, pred storage.SelectionPredicate) (watch.Interface, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/watcher.go","code":"// Watch watches on a key and returns a watch.Interface that transfers relevant notifications.\n// If rev is zero, it will return the existing object(s) and then start watching from\n// the maximum revision+1 from returned objects.\n// If rev is non-zero, it will watch events happened after given revision.\n// If recursive is false, it watches on given key.\n// If recursive is true, it watches any children and directories under the key, excluding the root key itself.\n// pred must be non-nil. Only if pred matches the change, it will be returned.\nfunc (w *watcher) Watch(ctx context.Context, key string, rev int64, recursive, progressNotify bool, transformer value.Transformer, pred storage.SelectionPredicate) (watch.Interface, error) {\n\tif recursive \u0026\u0026 !strings.HasSuffix(key, \"/\") {\n\t\tkey += \"/\"\n\t}\n\twc := w.createWatchChan(ctx, key, rev, recursive, progressNotify, transformer, pred)\n\tgo wc.run()\n\n\t// For etcd watch we don't have an easy way to answer whether the watch\n\t// has already caught up. So in the initial version (given that watchcache\n\t// is by default enabled for all resources but Events), we just deliver\n\t// the initialization signal immediately. Improving this will be explored\n\t// in the future.\n\tutilflowcontrol.WatchInitialized(ctx)\n\n\treturn wc, nil\n}","line":{"from":106,"to":128}} {"id":100018677,"name":"createWatchChan","signature":"func (w *watcher) createWatchChan(ctx context.Context, key string, rev int64, recursive, progressNotify bool, transformer value.Transformer, pred storage.SelectionPredicate) *watchChan","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/watcher.go","code":"func (w *watcher) createWatchChan(ctx context.Context, key string, rev int64, recursive, progressNotify bool, transformer value.Transformer, pred storage.SelectionPredicate) *watchChan {\n\twc := \u0026watchChan{\n\t\twatcher: w,\n\t\ttransformer: transformer,\n\t\tkey: key,\n\t\tinitialRev: rev,\n\t\trecursive: recursive,\n\t\tprogressNotify: progressNotify,\n\t\tinternalPred: pred,\n\t\tincomingEventChan: make(chan *event, incomingBufSize),\n\t\tresultChan: make(chan watch.Event, outgoingBufSize),\n\t\terrChan: make(chan error, 1),\n\t}\n\tif pred.Empty() {\n\t\t// The filter doesn't filter out any object.\n\t\twc.internalPred = storage.Everything\n\t}\n\n\t// The etcd server waits until it cannot find a leader for 3 election\n\t// timeouts to cancel existing streams. 3 is currently a hard coded\n\t// constant. The election timeout defaults to 1000ms. If the cluster is\n\t// healthy, when the leader is stopped, the leadership transfer should be\n\t// smooth. (leader transfers its leadership before stopping). If leader is\n\t// hard killed, other servers will take an election timeout to realize\n\t// leader lost and start campaign.\n\twc.ctx, wc.cancel = context.WithCancel(clientv3.WithRequireLeader(ctx))\n\treturn wc\n}","line":{"from":130,"to":157}} {"id":100018678,"name":"isCancelError","signature":"func isCancelError(err error) bool","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/watcher.go","code":"func isCancelError(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\tif err == context.Canceled {\n\t\treturn true\n\t}\n\tif etcdErr, ok := err.(etcdError); ok \u0026\u0026 etcdErr.Code() == grpccodes.Canceled {\n\t\treturn true\n\t}\n\tif grpcErr, ok := err.(grpcError); ok \u0026\u0026 grpcErr.GRPCStatus().Code() == grpccodes.Canceled {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":168,"to":182}} {"id":100018679,"name":"run","signature":"func (wc *watchChan) run()","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/watcher.go","code":"func (wc *watchChan) run() {\n\twatchClosedCh := make(chan struct{})\n\tgo wc.startWatching(watchClosedCh)\n\n\tvar resultChanWG sync.WaitGroup\n\tresultChanWG.Add(1)\n\tgo wc.processEvent(\u0026resultChanWG)\n\n\tselect {\n\tcase err := \u003c-wc.errChan:\n\t\tif isCancelError(err) {\n\t\t\tbreak\n\t\t}\n\t\terrResult := transformErrorToEvent(err)\n\t\tif errResult != nil {\n\t\t\t// error result is guaranteed to be received by user before closing ResultChan.\n\t\t\tselect {\n\t\t\tcase wc.resultChan \u003c- *errResult:\n\t\t\tcase \u003c-wc.ctx.Done(): // user has given up all results\n\t\t\t}\n\t\t}\n\tcase \u003c-watchClosedCh:\n\tcase \u003c-wc.ctx.Done(): // user cancel\n\t}\n\n\t// We use wc.ctx to reap all goroutines. Under whatever condition, we should stop them all.\n\t// It's fine to double cancel.\n\twc.cancel()\n\n\t// we need to wait until resultChan wouldn't be used anymore\n\tresultChanWG.Wait()\n\tclose(wc.resultChan)\n}","line":{"from":184,"to":216}} {"id":100018680,"name":"Stop","signature":"func (wc *watchChan) Stop()","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/watcher.go","code":"func (wc *watchChan) Stop() {\n\twc.cancel()\n}","line":{"from":218,"to":220}} {"id":100018681,"name":"ResultChan","signature":"func (wc *watchChan) ResultChan() \u003c-chan watch.Event","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/watcher.go","code":"func (wc *watchChan) ResultChan() \u003c-chan watch.Event {\n\treturn wc.resultChan\n}","line":{"from":222,"to":224}} {"id":100018682,"name":"sync","signature":"func (wc *watchChan) sync() error","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/watcher.go","code":"// sync tries to retrieve existing data and send them to process.\n// The revision to watch will be set to the revision in response.\n// All events sent will have isCreated=true\nfunc (wc *watchChan) sync() error {\n\topts := []clientv3.OpOption{}\n\tif wc.recursive {\n\t\topts = append(opts, clientv3.WithPrefix())\n\t}\n\tgetResp, err := wc.watcher.client.Get(wc.ctx, wc.key, opts...)\n\tif err != nil {\n\t\treturn err\n\t}\n\twc.initialRev = getResp.Header.Revision\n\tfor _, kv := range getResp.Kvs {\n\t\twc.sendEvent(parseKV(kv))\n\t}\n\treturn nil\n}","line":{"from":226,"to":243}} {"id":100018683,"name":"logWatchChannelErr","signature":"func logWatchChannelErr(err error)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/watcher.go","code":"func logWatchChannelErr(err error) {\n\tswitch {\n\tcase strings.Contains(err.Error(), \"mvcc: required revision has been compacted\"):\n\t\t// mvcc revision compaction which is regarded as warning, not error\n\t\tklog.Warningf(\"watch chan error: %v\", err)\n\tcase isCancelError(err):\n\t\t// expected when watches close, no need to log\n\tdefault:\n\t\tklog.Errorf(\"watch chan error: %v\", err)\n\t}\n}","line":{"from":245,"to":255}} {"id":100018684,"name":"startWatching","signature":"func (wc *watchChan) startWatching(watchClosedCh chan struct{})","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/watcher.go","code":"// startWatching does:\n// - get current objects if initialRev=0; set initialRev to current rev\n// - watch on given key and send events to process.\nfunc (wc *watchChan) startWatching(watchClosedCh chan struct{}) {\n\tif wc.initialRev == 0 {\n\t\tif err := wc.sync(); err != nil {\n\t\t\tklog.Errorf(\"failed to sync with latest state: %v\", err)\n\t\t\twc.sendError(err)\n\t\t\treturn\n\t\t}\n\t}\n\topts := []clientv3.OpOption{clientv3.WithRev(wc.initialRev + 1), clientv3.WithPrevKV()}\n\tif wc.recursive {\n\t\topts = append(opts, clientv3.WithPrefix())\n\t}\n\tif wc.progressNotify {\n\t\topts = append(opts, clientv3.WithProgressNotify())\n\t}\n\twch := wc.watcher.client.Watch(wc.ctx, wc.key, opts...)\n\tfor wres := range wch {\n\t\tif wres.Err() != nil {\n\t\t\terr := wres.Err()\n\t\t\t// If there is an error on server (e.g. compaction), the channel will return it before closed.\n\t\t\tlogWatchChannelErr(err)\n\t\t\twc.sendError(err)\n\t\t\treturn\n\t\t}\n\t\tif wres.IsProgressNotify() {\n\t\t\twc.sendEvent(progressNotifyEvent(wres.Header.GetRevision()))\n\t\t\tmetrics.RecordEtcdBookmark(wc.watcher.groupResource.String())\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, e := range wres.Events {\n\t\t\tmetrics.RecordEtcdEvent(wc.watcher.groupResource.String())\n\t\t\tparsedEvent, err := parseEvent(e)\n\t\t\tif err != nil {\n\t\t\t\tlogWatchChannelErr(err)\n\t\t\t\twc.sendError(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\twc.sendEvent(parsedEvent)\n\t\t}\n\t}\n\t// When we come to this point, it's only possible that client side ends the watch.\n\t// e.g. cancel the context, close the client.\n\t// If this watch chan is broken and context isn't cancelled, other goroutines will still hang.\n\t// We should notify the main thread that this goroutine has exited.\n\tclose(watchClosedCh)\n}","line":{"from":257,"to":306}} {"id":100018685,"name":"processEvent","signature":"func (wc *watchChan) processEvent(wg *sync.WaitGroup)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/watcher.go","code":"// processEvent processes events from etcd watcher and sends results to resultChan.\nfunc (wc *watchChan) processEvent(wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\n\tfor {\n\t\tselect {\n\t\tcase e := \u003c-wc.incomingEventChan:\n\t\t\tres := wc.transform(e)\n\t\t\tif res == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(wc.resultChan) == outgoingBufSize {\n\t\t\t\tklog.V(3).InfoS(\"Fast watcher, slow processing. Probably caused by slow dispatching events to watchers\", \"outgoingEvents\", outgoingBufSize, \"objectType\", wc.watcher.objectType, \"groupResource\", wc.watcher.groupResource)\n\t\t\t}\n\t\t\t// If user couldn't receive results fast enough, we also block incoming events from watcher.\n\t\t\t// Because storing events in local will cause more memory usage.\n\t\t\t// The worst case would be closing the fast watcher.\n\t\t\tselect {\n\t\t\tcase wc.resultChan \u003c- *res:\n\t\t\tcase \u003c-wc.ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\tcase \u003c-wc.ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}","line":{"from":308,"to":334}} {"id":100018686,"name":"filter","signature":"func (wc *watchChan) filter(obj runtime.Object) bool","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/watcher.go","code":"func (wc *watchChan) filter(obj runtime.Object) bool {\n\tif wc.internalPred.Empty() {\n\t\treturn true\n\t}\n\tmatched, err := wc.internalPred.Matches(obj)\n\treturn err == nil \u0026\u0026 matched\n}","line":{"from":336,"to":342}} {"id":100018687,"name":"acceptAll","signature":"func (wc *watchChan) acceptAll() bool","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/watcher.go","code":"func (wc *watchChan) acceptAll() bool {\n\treturn wc.internalPred.Empty()\n}","line":{"from":344,"to":346}} {"id":100018688,"name":"transform","signature":"func (wc *watchChan) transform(e *event) (res *watch.Event)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/watcher.go","code":"// transform transforms an event into a result for user if not filtered.\nfunc (wc *watchChan) transform(e *event) (res *watch.Event) {\n\tcurObj, oldObj, err := wc.prepareObjs(e)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to prepare current and previous objects: %v\", err)\n\t\twc.sendError(err)\n\t\treturn nil\n\t}\n\n\tswitch {\n\tcase e.isProgressNotify:\n\t\tif wc.watcher.newFunc == nil {\n\t\t\treturn nil\n\t\t}\n\t\tobject := wc.watcher.newFunc()\n\t\tif err := wc.watcher.versioner.UpdateObject(object, uint64(e.rev)); err != nil {\n\t\t\tklog.Errorf(\"failed to propagate object version: %v\", err)\n\t\t\treturn nil\n\t\t}\n\t\tres = \u0026watch.Event{\n\t\t\tType: watch.Bookmark,\n\t\t\tObject: object,\n\t\t}\n\tcase e.isDeleted:\n\t\tif !wc.filter(oldObj) {\n\t\t\treturn nil\n\t\t}\n\t\tres = \u0026watch.Event{\n\t\t\tType: watch.Deleted,\n\t\t\tObject: oldObj,\n\t\t}\n\tcase e.isCreated:\n\t\tif !wc.filter(curObj) {\n\t\t\treturn nil\n\t\t}\n\t\tres = \u0026watch.Event{\n\t\t\tType: watch.Added,\n\t\t\tObject: curObj,\n\t\t}\n\tdefault:\n\t\tif wc.acceptAll() {\n\t\t\tres = \u0026watch.Event{\n\t\t\t\tType: watch.Modified,\n\t\t\t\tObject: curObj,\n\t\t\t}\n\t\t\treturn res\n\t\t}\n\t\tcurObjPasses := wc.filter(curObj)\n\t\toldObjPasses := wc.filter(oldObj)\n\t\tswitch {\n\t\tcase curObjPasses \u0026\u0026 oldObjPasses:\n\t\t\tres = \u0026watch.Event{\n\t\t\t\tType: watch.Modified,\n\t\t\t\tObject: curObj,\n\t\t\t}\n\t\tcase curObjPasses \u0026\u0026 !oldObjPasses:\n\t\t\tres = \u0026watch.Event{\n\t\t\t\tType: watch.Added,\n\t\t\t\tObject: curObj,\n\t\t\t}\n\t\tcase !curObjPasses \u0026\u0026 oldObjPasses:\n\t\t\tres = \u0026watch.Event{\n\t\t\t\tType: watch.Deleted,\n\t\t\t\tObject: oldObj,\n\t\t\t}\n\t\t}\n\t}\n\treturn res\n}","line":{"from":348,"to":416}} {"id":100018689,"name":"transformErrorToEvent","signature":"func transformErrorToEvent(err error) *watch.Event","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/watcher.go","code":"func transformErrorToEvent(err error) *watch.Event {\n\terr = interpretWatchError(err)\n\tif _, ok := err.(apierrors.APIStatus); !ok {\n\t\terr = apierrors.NewInternalError(err)\n\t}\n\tstatus := err.(apierrors.APIStatus).Status()\n\treturn \u0026watch.Event{\n\t\tType: watch.Error,\n\t\tObject: \u0026status,\n\t}\n}","line":{"from":418,"to":428}} {"id":100018690,"name":"sendError","signature":"func (wc *watchChan) sendError(err error)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/watcher.go","code":"func (wc *watchChan) sendError(err error) {\n\tselect {\n\tcase wc.errChan \u003c- err:\n\tcase \u003c-wc.ctx.Done():\n\t}\n}","line":{"from":430,"to":435}} {"id":100018691,"name":"sendEvent","signature":"func (wc *watchChan) sendEvent(e *event)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/watcher.go","code":"func (wc *watchChan) sendEvent(e *event) {\n\tif len(wc.incomingEventChan) == incomingBufSize {\n\t\tklog.V(3).InfoS(\"Fast watcher, slow processing. Probably caused by slow decoding, user not receiving fast, or other processing logic\", \"incomingEvents\", incomingBufSize, \"objectType\", wc.watcher.objectType, \"groupResource\", wc.watcher.groupResource)\n\t}\n\tselect {\n\tcase wc.incomingEventChan \u003c- e:\n\tcase \u003c-wc.ctx.Done():\n\t}\n}","line":{"from":437,"to":445}} {"id":100018692,"name":"prepareObjs","signature":"func (wc *watchChan) prepareObjs(e *event) (curObj runtime.Object, oldObj runtime.Object, err error)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/watcher.go","code":"func (wc *watchChan) prepareObjs(e *event) (curObj runtime.Object, oldObj runtime.Object, err error) {\n\tif e.isProgressNotify {\n\t\t// progressNotify events doesn't contain neither current nor previous object version,\n\t\treturn nil, nil, nil\n\t}\n\n\tif !e.isDeleted {\n\t\tdata, _, err := wc.transformer.TransformFromStorage(wc.ctx, e.value, authenticatedDataString(e.key))\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tcurObj, err = decodeObj(wc.watcher.codec, wc.watcher.versioner, data, e.rev)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\t// We need to decode prevValue, only if this is deletion event or\n\t// the underlying filter doesn't accept all objects (otherwise we\n\t// know that the filter for previous object will return true and\n\t// we need the object only to compute whether it was filtered out\n\t// before).\n\tif len(e.prevValue) \u003e 0 \u0026\u0026 (e.isDeleted || !wc.acceptAll()) {\n\t\tdata, _, err := wc.transformer.TransformFromStorage(wc.ctx, e.prevValue, authenticatedDataString(e.key))\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\t// Note that this sends the *old* object with the etcd revision for the time at\n\t\t// which it gets deleted.\n\t\toldObj, err = decodeObj(wc.watcher.codec, wc.watcher.versioner, data, e.rev)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\treturn curObj, oldObj, nil\n}","line":{"from":447,"to":481}} {"id":100018693,"name":"decodeObj","signature":"func decodeObj(codec runtime.Codec, versioner storage.Versioner, data []byte, rev int64) (_ runtime.Object, err error)","file":"staging/src/k8s.io/apiserver/pkg/storage/etcd3/watcher.go","code":"func decodeObj(codec runtime.Codec, versioner storage.Versioner, data []byte, rev int64) (_ runtime.Object, err error) {\n\tobj, err := runtime.Decode(codec, []byte(data))\n\tif err != nil {\n\t\tif fatalOnDecodeError {\n\t\t\t// we are running in a test environment and thus an\n\t\t\t// error here is due to a coder mistake if the defer\n\t\t\t// does not catch it\n\t\t\tpanic(err)\n\t\t}\n\t\treturn nil, err\n\t}\n\t// ensure resource version is set on the object we load from etcd\n\tif err := versioner.UpdateObject(obj, uint64(rev)); err != nil {\n\t\treturn nil, fmt.Errorf(\"failure to version api object (%d) %#v: %v\", rev, obj, err)\n\t}\n\treturn obj, nil\n}","line":{"from":483,"to":499}} {"id":100018694,"name":"ValidateAllObjectFunc","signature":"func ValidateAllObjectFunc(ctx context.Context, obj runtime.Object) error","file":"staging/src/k8s.io/apiserver/pkg/storage/interfaces.go","code":"// ValidateAllObjectFunc is a \"admit everything\" instance of ValidateObjectFunc.\nfunc ValidateAllObjectFunc(ctx context.Context, obj runtime.Object) error {\n\treturn nil\n}","line":{"from":107,"to":110}} {"id":100018695,"name":"NewUIDPreconditions","signature":"func NewUIDPreconditions(uid string) *Preconditions","file":"staging/src/k8s.io/apiserver/pkg/storage/interfaces.go","code":"// NewUIDPreconditions returns a Preconditions with UID set.\nfunc NewUIDPreconditions(uid string) *Preconditions {\n\tu := types.UID(uid)\n\treturn \u0026Preconditions{UID: \u0026u}\n}","line":{"from":122,"to":126}} {"id":100018696,"name":"Check","signature":"func (p *Preconditions) Check(key string, obj runtime.Object) error","file":"staging/src/k8s.io/apiserver/pkg/storage/interfaces.go","code":"func (p *Preconditions) Check(key string, obj runtime.Object) error {\n\tif p == nil {\n\t\treturn nil\n\t}\n\tobjMeta, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn NewInternalErrorf(\n\t\t\t\"can't enforce preconditions %v on un-introspectable object %v, got error: %v\",\n\t\t\t*p,\n\t\t\tobj,\n\t\t\terr)\n\t}\n\tif p.UID != nil \u0026\u0026 *p.UID != objMeta.GetUID() {\n\t\terr := fmt.Sprintf(\n\t\t\t\"Precondition failed: UID in precondition: %v, UID in object meta: %v\",\n\t\t\t*p.UID,\n\t\t\tobjMeta.GetUID())\n\t\treturn NewInvalidObjError(key, err)\n\t}\n\tif p.ResourceVersion != nil \u0026\u0026 *p.ResourceVersion != objMeta.GetResourceVersion() {\n\t\terr := fmt.Sprintf(\n\t\t\t\"Precondition failed: ResourceVersion in precondition: %v, ResourceVersion in object meta: %v\",\n\t\t\t*p.ResourceVersion,\n\t\t\tobjMeta.GetResourceVersion())\n\t\treturn NewInvalidObjError(key, err)\n\t}\n\treturn nil\n}","line":{"from":128,"to":155}} {"id":100018697,"name":"GenerateName","signature":"func (simpleNameGenerator) GenerateName(base string) string","file":"staging/src/k8s.io/apiserver/pkg/storage/names/generate.go","code":"func (simpleNameGenerator) GenerateName(base string) string {\n\tif len(base) \u003e MaxGeneratedNameLength {\n\t\tbase = base[:MaxGeneratedNameLength]\n\t}\n\treturn fmt.Sprintf(\"%s%s\", base, utilrand.String(randomLength))\n}","line":{"from":49,"to":54}} {"id":100018698,"name":"DefaultClusterScopedAttr","signature":"func DefaultClusterScopedAttr(obj runtime.Object) (labels.Set, fields.Set, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/selection_predicate.go","code":"func DefaultClusterScopedAttr(obj runtime.Object) (labels.Set, fields.Set, error) {\n\tmetadata, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tfieldSet := fields.Set{\n\t\t\"metadata.name\": metadata.GetName(),\n\t}\n\n\treturn labels.Set(metadata.GetLabels()), fieldSet, nil\n}","line":{"from":34,"to":44}} {"id":100018699,"name":"DefaultNamespaceScopedAttr","signature":"func DefaultNamespaceScopedAttr(obj runtime.Object) (labels.Set, fields.Set, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/selection_predicate.go","code":"func DefaultNamespaceScopedAttr(obj runtime.Object) (labels.Set, fields.Set, error) {\n\tmetadata, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tfieldSet := fields.Set{\n\t\t\"metadata.name\": metadata.GetName(),\n\t\t\"metadata.namespace\": metadata.GetNamespace(),\n\t}\n\n\treturn labels.Set(metadata.GetLabels()), fieldSet, nil\n}","line":{"from":46,"to":57}} {"id":100018700,"name":"WithFieldMutation","signature":"func (f AttrFunc) WithFieldMutation(fieldMutator FieldMutationFunc) AttrFunc","file":"staging/src/k8s.io/apiserver/pkg/storage/selection_predicate.go","code":"func (f AttrFunc) WithFieldMutation(fieldMutator FieldMutationFunc) AttrFunc {\n\treturn func(obj runtime.Object) (labels.Set, fields.Set, error) {\n\t\tlabelSet, fieldSet, err := f(obj)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tif err := fieldMutator(obj, fieldSet); err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\treturn labelSet, fieldSet, nil\n\t}\n}","line":{"from":59,"to":70}} {"id":100018701,"name":"Matches","signature":"func (s *SelectionPredicate) Matches(obj runtime.Object) (bool, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/selection_predicate.go","code":"// Matches returns true if the given object's labels and fields (as\n// returned by s.GetAttrs) match s.Label and s.Field. An error is\n// returned if s.GetAttrs fails.\nfunc (s *SelectionPredicate) Matches(obj runtime.Object) (bool, error) {\n\tif s.Empty() {\n\t\treturn true, nil\n\t}\n\tlabels, fields, err := s.GetAttrs(obj)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tmatched := s.Label.Matches(labels)\n\tif matched \u0026\u0026 s.Field != nil {\n\t\tmatched = matched \u0026\u0026 s.Field.Matches(fields)\n\t}\n\treturn matched, nil\n}","line":{"from":84,"to":100}} {"id":100018702,"name":"MatchesObjectAttributes","signature":"func (s *SelectionPredicate) MatchesObjectAttributes(l labels.Set, f fields.Set) bool","file":"staging/src/k8s.io/apiserver/pkg/storage/selection_predicate.go","code":"// MatchesObjectAttributes returns true if the given labels and fields\n// match s.Label and s.Field.\nfunc (s *SelectionPredicate) MatchesObjectAttributes(l labels.Set, f fields.Set) bool {\n\tif s.Label.Empty() \u0026\u0026 s.Field.Empty() {\n\t\treturn true\n\t}\n\tmatched := s.Label.Matches(l)\n\tif matched \u0026\u0026 s.Field != nil {\n\t\tmatched = (matched \u0026\u0026 s.Field.Matches(f))\n\t}\n\treturn matched\n}","line":{"from":102,"to":113}} {"id":100018703,"name":"MatchesSingleNamespace","signature":"func (s *SelectionPredicate) MatchesSingleNamespace() (string, bool)","file":"staging/src/k8s.io/apiserver/pkg/storage/selection_predicate.go","code":"// MatchesSingleNamespace will return (namespace, true) if and only if s.Field matches on the object's\n// namespace.\nfunc (s *SelectionPredicate) MatchesSingleNamespace() (string, bool) {\n\tif len(s.Continue) \u003e 0 {\n\t\treturn \"\", false\n\t}\n\tif namespace, ok := s.Field.RequiresExactMatch(\"metadata.namespace\"); ok {\n\t\treturn namespace, true\n\t}\n\treturn \"\", false\n}","line":{"from":115,"to":125}} {"id":100018704,"name":"MatchesSingle","signature":"func (s *SelectionPredicate) MatchesSingle() (string, bool)","file":"staging/src/k8s.io/apiserver/pkg/storage/selection_predicate.go","code":"// MatchesSingle will return (name, true) if and only if s.Field matches on the object's\n// name.\nfunc (s *SelectionPredicate) MatchesSingle() (string, bool) {\n\tif len(s.Continue) \u003e 0 {\n\t\treturn \"\", false\n\t}\n\t// TODO: should be namespace.name\n\tif name, ok := s.Field.RequiresExactMatch(\"metadata.name\"); ok {\n\t\treturn name, true\n\t}\n\treturn \"\", false\n}","line":{"from":127,"to":138}} {"id":100018705,"name":"Empty","signature":"func (s *SelectionPredicate) Empty() bool","file":"staging/src/k8s.io/apiserver/pkg/storage/selection_predicate.go","code":"// Empty returns true if the predicate performs no filtering.\nfunc (s *SelectionPredicate) Empty() bool {\n\treturn s.Label.Empty() \u0026\u0026 s.Field.Empty()\n}","line":{"from":140,"to":143}} {"id":100018706,"name":"MatcherIndex","signature":"func (s *SelectionPredicate) MatcherIndex() []MatchValue","file":"staging/src/k8s.io/apiserver/pkg/storage/selection_predicate.go","code":"// For any index defined by IndexFields, if a matcher can match only (a subset)\n// of objects that return \u003cvalue\u003e for a given index, a pair (\u003cindex name\u003e, \u003cvalue\u003e)\n// wil be returned.\nfunc (s *SelectionPredicate) MatcherIndex() []MatchValue {\n\tvar result []MatchValue\n\tfor _, field := range s.IndexFields {\n\t\tif value, ok := s.Field.RequiresExactMatch(field); ok {\n\t\t\tresult = append(result, MatchValue{IndexName: FieldIndex(field), Value: value})\n\t\t}\n\t}\n\tfor _, label := range s.IndexLabels {\n\t\tif value, ok := s.Label.RequiresExactMatch(label); ok {\n\t\t\tresult = append(result, MatchValue{IndexName: LabelIndex(label), Value: value})\n\t\t}\n\t}\n\treturn result\n}","line":{"from":145,"to":161}} {"id":100018707,"name":"LabelIndex","signature":"func LabelIndex(label string) string","file":"staging/src/k8s.io/apiserver/pkg/storage/selection_predicate.go","code":"// LabelIndex add prefix for label index.\nfunc LabelIndex(label string) string {\n\treturn \"l:\" + label\n}","line":{"from":163,"to":166}} {"id":100018708,"name":"FieldIndex","signature":"func FieldIndex(field string) string","file":"staging/src/k8s.io/apiserver/pkg/storage/selection_predicate.go","code":"// FiledIndex add prefix for field index.\nfunc FieldIndex(field string) string {\n\treturn \"f:\" + field\n}","line":{"from":168,"to":171}} {"id":100018709,"name":"ForResource","signature":"func (config *Config) ForResource(resource schema.GroupResource) *ConfigForResource","file":"staging/src/k8s.io/apiserver/pkg/storage/storagebackend/config.go","code":"// ForResource specializes to the given resource\nfunc (config *Config) ForResource(resource schema.GroupResource) *ConfigForResource {\n\treturn \u0026ConfigForResource{\n\t\tConfig: *config,\n\t\tGroupResource: resource,\n\t}\n}","line":{"from":108,"to":114}} {"id":100018710,"name":"NewDefaultConfig","signature":"func NewDefaultConfig(prefix string, codec runtime.Codec) *Config","file":"staging/src/k8s.io/apiserver/pkg/storage/storagebackend/config.go","code":"func NewDefaultConfig(prefix string, codec runtime.Codec) *Config {\n\treturn \u0026Config{\n\t\tPaging: true,\n\t\tPrefix: prefix,\n\t\tCodec: codec,\n\t\tCompactionInterval: DefaultCompactInterval,\n\t\tDBMetricPollInterval: DefaultDBMetricPollInterval,\n\t\tHealthcheckTimeout: DefaultHealthcheckTimeout,\n\t\tReadycheckTimeout: DefaultReadinessTimeout,\n\t\tLeaseManagerConfig: etcd3.NewDefaultLeaseManagerConfig(),\n\t\tTransport: TransportConfig{TracerProvider: oteltrace.NewNoopTracerProvider()},\n\t}\n}","line":{"from":116,"to":128}} {"id":100018711,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/storage/storagebackend/factory/etcd3.go","code":"func init() {\n\t// grpcprom auto-registers (via an init function) their client metrics, since we are opting out of\n\t// using the global prometheus registry and using our own wrapped global registry,\n\t// we need to explicitly register these metrics to our global registry here.\n\t// For reference: https://github.com/kubernetes/kubernetes/pull/81387\n\tlegacyregistry.RawMustRegister(grpcprom.DefaultClientMetrics)\n\tdbMetricsMonitors = make(map[string]struct{})\n\n\tl, err := logutil.CreateDefaultZapLogger(etcdClientDebugLevel())\n\tif err != nil {\n\t\tl = zap.NewNop()\n\t}\n\tetcd3ClientLogger = l.Named(\"etcd-client\")\n}","line":{"from":80,"to":93}} {"id":100018712,"name":"etcdClientDebugLevel","signature":"func etcdClientDebugLevel() zapcore.Level","file":"staging/src/k8s.io/apiserver/pkg/storage/storagebackend/factory/etcd3.go","code":"// etcdClientDebugLevel translates ETCD_CLIENT_DEBUG into zap log level.\n// NOTE(negz): This is a copy of a private etcd client function:\n// https://github.com/etcd-io/etcd/blob/v3.5.4/client/v3/logger.go#L47\nfunc etcdClientDebugLevel() zapcore.Level {\n\tenvLevel := os.Getenv(\"ETCD_CLIENT_DEBUG\")\n\tif envLevel == \"\" || envLevel == \"true\" {\n\t\treturn zapcore.InfoLevel\n\t}\n\tvar l zapcore.Level\n\tif err := l.Set(envLevel); err == nil {\n\t\tlog.Printf(\"Deprecated env ETCD_CLIENT_DEBUG value. Using default level: 'info'\")\n\t\treturn zapcore.InfoLevel\n\t}\n\treturn l\n}","line":{"from":95,"to":109}} {"id":100018713,"name":"newETCD3HealthCheck","signature":"func newETCD3HealthCheck(c storagebackend.Config, stopCh \u003c-chan struct{}) (func() error, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/storagebackend/factory/etcd3.go","code":"func newETCD3HealthCheck(c storagebackend.Config, stopCh \u003c-chan struct{}) (func() error, error) {\n\ttimeout := storagebackend.DefaultHealthcheckTimeout\n\tif c.HealthcheckTimeout != time.Duration(0) {\n\t\ttimeout = c.HealthcheckTimeout\n\t}\n\treturn newETCD3Check(c, timeout, stopCh)\n}","line":{"from":111,"to":117}} {"id":100018714,"name":"newETCD3ReadyCheck","signature":"func newETCD3ReadyCheck(c storagebackend.Config, stopCh \u003c-chan struct{}) (func() error, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/storagebackend/factory/etcd3.go","code":"func newETCD3ReadyCheck(c storagebackend.Config, stopCh \u003c-chan struct{}) (func() error, error) {\n\ttimeout := storagebackend.DefaultReadinessTimeout\n\tif c.ReadycheckTimeout != time.Duration(0) {\n\t\ttimeout = c.ReadycheckTimeout\n\t}\n\treturn newETCD3Check(c, timeout, stopCh)\n}","line":{"from":119,"to":125}} {"id":100018715,"name":"Store","signature":"func (a *atomicLastError) Store(err error, t time.Time)","file":"staging/src/k8s.io/apiserver/pkg/storage/storagebackend/factory/etcd3.go","code":"func (a *atomicLastError) Store(err error, t time.Time) {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\tif a.timestamp.IsZero() || a.timestamp.Before(t) {\n\t\ta.err = err\n\t\ta.timestamp = t\n\t}\n}","line":{"from":136,"to":143}} {"id":100018716,"name":"Load","signature":"func (a *atomicLastError) Load() error","file":"staging/src/k8s.io/apiserver/pkg/storage/storagebackend/factory/etcd3.go","code":"func (a *atomicLastError) Load() error {\n\ta.mu.RLock()\n\tdefer a.mu.RUnlock()\n\treturn a.err\n}","line":{"from":145,"to":149}} {"id":100018717,"name":"newETCD3Check","signature":"func newETCD3Check(c storagebackend.Config, timeout time.Duration, stopCh \u003c-chan struct{}) (func() error, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/storagebackend/factory/etcd3.go","code":"func newETCD3Check(c storagebackend.Config, timeout time.Duration, stopCh \u003c-chan struct{}) (func() error, error) {\n\t// constructing the etcd v3 client blocks and times out if etcd is not available.\n\t// retry in a loop in the background until we successfully create the client, storing the client or error encountered\n\n\tlock := sync.RWMutex{}\n\tvar prober *etcd3Prober\n\tclientErr := fmt.Errorf(\"etcd client connection not yet established\")\n\n\tgo wait.PollUntil(time.Second, func() (bool, error) {\n\t\tnewProber, err := newETCD3Prober(c)\n\t\tlock.Lock()\n\t\tdefer lock.Unlock()\n\t\t// Ensure that server is already not shutting down.\n\t\tselect {\n\t\tcase \u003c-stopCh:\n\t\t\tif err == nil {\n\t\t\t\tnewProber.Close()\n\t\t\t}\n\t\t\treturn true, nil\n\t\tdefault:\n\t\t}\n\t\tif err != nil {\n\t\t\tclientErr = err\n\t\t\treturn false, nil\n\t\t}\n\t\tprober = newProber\n\t\tclientErr = nil\n\t\treturn true, nil\n\t}, stopCh)\n\n\t// Close the client on shutdown.\n\tgo func() {\n\t\tdefer utilruntime.HandleCrash()\n\t\t\u003c-stopCh\n\n\t\tlock.Lock()\n\t\tdefer lock.Unlock()\n\t\tif prober != nil {\n\t\t\tprober.Close()\n\t\t\tclientErr = fmt.Errorf(\"server is shutting down\")\n\t\t}\n\t}()\n\n\t// limit to a request every half of the configured timeout with a maximum burst of one\n\t// rate limited requests will receive the last request sent error (note: not the last received response)\n\tlimiter := rate.NewLimiter(rate.Every(timeout/2), 1)\n\t// initial state is the clientErr\n\tlastError := \u0026atomicLastError{err: fmt.Errorf(\"etcd client connection not yet established\")}\n\n\treturn func() error {\n\t\t// Given that client is closed on shutdown we hold the lock for\n\t\t// the entire period of healthcheck call to ensure that client will\n\t\t// not be closed during healthcheck.\n\t\t// Given that healthchecks has a 2s timeout, worst case of blocking\n\t\t// shutdown for additional 2s seems acceptable.\n\t\tlock.RLock()\n\t\tdefer lock.RUnlock()\n\n\t\tif clientErr != nil {\n\t\t\treturn clientErr\n\t\t}\n\t\tif limiter.Allow() == false {\n\t\t\treturn lastError.Load()\n\t\t}\n\t\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\t\tdefer cancel()\n\t\tnow := time.Now()\n\t\terr := prober.Probe(ctx)\n\t\tlastError.Store(err, now)\n\t\treturn err\n\t}, nil\n}","line":{"from":151,"to":222}} {"id":100018718,"name":"newETCD3Prober","signature":"func newETCD3Prober(c storagebackend.Config) (*etcd3Prober, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/storagebackend/factory/etcd3.go","code":"func newETCD3Prober(c storagebackend.Config) (*etcd3Prober, error) {\n\tclient, err := newETCD3Client(c.Transport)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026etcd3Prober{\n\t\tclient: client,\n\t\tprefix: c.Prefix,\n\t}, nil\n}","line":{"from":224,"to":233}} {"id":100018719,"name":"Close","signature":"func (p *etcd3Prober) Close() error","file":"staging/src/k8s.io/apiserver/pkg/storage/storagebackend/factory/etcd3.go","code":"func (p *etcd3Prober) Close() error {\n\tp.mux.Lock()\n\tdefer p.mux.Unlock()\n\tif !p.closed {\n\t\tp.closed = true\n\t\treturn p.client.Close()\n\t}\n\treturn fmt.Errorf(\"prober was closed\")\n}","line":{"from":243,"to":251}} {"id":100018720,"name":"Probe","signature":"func (p *etcd3Prober) Probe(ctx context.Context) error","file":"staging/src/k8s.io/apiserver/pkg/storage/storagebackend/factory/etcd3.go","code":"func (p *etcd3Prober) Probe(ctx context.Context) error {\n\tp.mux.RLock()\n\tdefer p.mux.RUnlock()\n\tif p.closed {\n\t\treturn fmt.Errorf(\"prober was closed\")\n\t}\n\t// See https://github.com/etcd-io/etcd/blob/c57f8b3af865d1b531b979889c602ba14377420e/etcdctl/ctlv3/command/ep_command.go#L118\n\t_, err := p.client.Get(ctx, path.Join(\"/\", p.prefix, \"health\"))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting data from etcd: %w\", err)\n\t}\n\treturn nil\n}","line":{"from":253,"to":265}} {"id":100018721,"name":"startCompactorOnce","signature":"func startCompactorOnce(c storagebackend.TransportConfig, interval time.Duration) (func(), error)","file":"staging/src/k8s.io/apiserver/pkg/storage/storagebackend/factory/etcd3.go","code":"// startCompactorOnce start one compactor per transport. If the interval get smaller on repeated calls, the\n// compactor is replaced. A destroy func is returned. If all destroy funcs with the same transport are called,\n// the compactor is stopped.\nfunc startCompactorOnce(c storagebackend.TransportConfig, interval time.Duration) (func(), error) {\n\tcompactorsMu.Lock()\n\tdefer compactorsMu.Unlock()\n\n\tkey := fmt.Sprintf(\"%v\", c) // gives: {[server1 server2] keyFile certFile caFile}\n\tif compactor, foundBefore := compactors[key]; !foundBefore || compactor.interval \u003e interval {\n\t\tcompactorClient, err := newETCD3Client(c)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif foundBefore {\n\t\t\t// replace compactor\n\t\t\tcompactor.cancel()\n\t\t\tcompactor.client.Close()\n\t\t} else {\n\t\t\t// start new compactor\n\t\t\tcompactor = \u0026runningCompactor{}\n\t\t\tcompactors[key] = compactor\n\t\t}\n\n\t\tctx, cancel := context.WithCancel(context.Background())\n\n\t\tcompactor.interval = interval\n\t\tcompactor.cancel = cancel\n\t\tcompactor.client = compactorClient\n\n\t\tetcd3.StartCompactor(ctx, compactorClient, interval)\n\t}\n\n\tcompactors[key].refs++\n\n\treturn func() {\n\t\tcompactorsMu.Lock()\n\t\tdefer compactorsMu.Unlock()\n\n\t\tcompactor := compactors[key]\n\t\tcompactor.refs--\n\t\tif compactor.refs == 0 {\n\t\t\tcompactor.cancel()\n\t\t\tcompactor.client.Close()\n\t\t\tdelete(compactors, key)\n\t\t}\n\t}, nil\n}","line":{"from":355,"to":402}} {"id":100018722,"name":"newETCD3Storage","signature":"func newETCD3Storage(c storagebackend.ConfigForResource, newFunc func() runtime.Object) (storage.Interface, DestroyFunc, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/storagebackend/factory/etcd3.go","code":"func newETCD3Storage(c storagebackend.ConfigForResource, newFunc func() runtime.Object) (storage.Interface, DestroyFunc, error) {\n\tstopCompactor, err := startCompactorOnce(c.Transport, c.CompactionInterval)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tclient, err := newETCD3Client(c.Transport)\n\tif err != nil {\n\t\tstopCompactor()\n\t\treturn nil, nil, err\n\t}\n\n\t// decorate the KV instance so we can track etcd latency per request.\n\tclient.KV = etcd3.NewETCDLatencyTracker(client.KV)\n\n\tstopDBSizeMonitor, err := startDBSizeMonitorPerEndpoint(client, c.DBMetricPollInterval)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar once sync.Once\n\tdestroyFunc := func() {\n\t\t// we know that storage destroy funcs are called multiple times (due to reuse in subresources).\n\t\t// Hence, we only destroy once.\n\t\t// TODO: fix duplicated storage destroy calls higher level\n\t\tonce.Do(func() {\n\t\t\tstopCompactor()\n\t\t\tstopDBSizeMonitor()\n\t\t\tclient.Close()\n\t\t})\n\t}\n\ttransformer := c.Transformer\n\tif transformer == nil {\n\t\ttransformer = identity.NewEncryptCheckTransformer()\n\t}\n\treturn etcd3.New(client, c.Codec, newFunc, c.Prefix, c.GroupResource, transformer, c.Paging, c.LeaseManagerConfig), destroyFunc, nil\n}","line":{"from":404,"to":440}} {"id":100018723,"name":"startDBSizeMonitorPerEndpoint","signature":"func startDBSizeMonitorPerEndpoint(client *clientv3.Client, interval time.Duration) (func(), error)","file":"staging/src/k8s.io/apiserver/pkg/storage/storagebackend/factory/etcd3.go","code":"// startDBSizeMonitorPerEndpoint starts a loop to monitor etcd database size and update the\n// corresponding metric etcd_db_total_size_in_bytes for each etcd server endpoint.\nfunc startDBSizeMonitorPerEndpoint(client *clientv3.Client, interval time.Duration) (func(), error) {\n\tif interval == 0 {\n\t\treturn func() {}, nil\n\t}\n\tdbMetricsMonitorsMu.Lock()\n\tdefer dbMetricsMonitorsMu.Unlock()\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tfor _, ep := range client.Endpoints() {\n\t\tif _, found := dbMetricsMonitors[ep]; found {\n\t\t\tcontinue\n\t\t}\n\t\tdbMetricsMonitors[ep] = struct{}{}\n\t\tendpoint := ep\n\t\tklog.V(4).Infof(\"Start monitoring storage db size metric for endpoint %s with polling interval %v\", endpoint, interval)\n\t\tgo wait.JitterUntilWithContext(ctx, func(context.Context) {\n\t\t\tepStatus, err := client.Maintenance.Status(ctx, endpoint)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get storage db size for ep %s: %v\", endpoint, err)\n\t\t\t\tmetrics.UpdateEtcdDbSize(endpoint, -1)\n\t\t\t} else {\n\t\t\t\tmetrics.UpdateEtcdDbSize(endpoint, epStatus.DbSize)\n\t\t\t}\n\t\t}, interval, dbMetricsMonitorJitter, true)\n\t}\n\n\treturn func() {\n\t\tcancel()\n\t}, nil\n}","line":{"from":442,"to":473}} {"id":100018724,"name":"Create","signature":"func Create(c storagebackend.ConfigForResource, newFunc func() runtime.Object) (storage.Interface, DestroyFunc, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/storagebackend/factory/factory.go","code":"// Create creates a storage backend based on given config.\nfunc Create(c storagebackend.ConfigForResource, newFunc func() runtime.Object) (storage.Interface, DestroyFunc, error) {\n\tswitch c.Type {\n\tcase storagebackend.StorageTypeETCD2:\n\t\treturn nil, nil, fmt.Errorf(\"%s is no longer a supported storage backend\", c.Type)\n\tcase storagebackend.StorageTypeUnset, storagebackend.StorageTypeETCD3:\n\t\treturn newETCD3Storage(c, newFunc)\n\tdefault:\n\t\treturn nil, nil, fmt.Errorf(\"unknown storage type: %s\", c.Type)\n\t}\n}","line":{"from":31,"to":41}} {"id":100018725,"name":"CreateHealthCheck","signature":"func CreateHealthCheck(c storagebackend.Config, stopCh \u003c-chan struct{}) (func() error, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/storagebackend/factory/factory.go","code":"// CreateHealthCheck creates a healthcheck function based on given config.\nfunc CreateHealthCheck(c storagebackend.Config, stopCh \u003c-chan struct{}) (func() error, error) {\n\tswitch c.Type {\n\tcase storagebackend.StorageTypeETCD2:\n\t\treturn nil, fmt.Errorf(\"%s is no longer a supported storage backend\", c.Type)\n\tcase storagebackend.StorageTypeUnset, storagebackend.StorageTypeETCD3:\n\t\treturn newETCD3HealthCheck(c, stopCh)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown storage type: %s\", c.Type)\n\t}\n}","line":{"from":43,"to":53}} {"id":100018726,"name":"CreateReadyCheck","signature":"func CreateReadyCheck(c storagebackend.Config, stopCh \u003c-chan struct{}) (func() error, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/storagebackend/factory/factory.go","code":"func CreateReadyCheck(c storagebackend.Config, stopCh \u003c-chan struct{}) (func() error, error) {\n\tswitch c.Type {\n\tcase storagebackend.StorageTypeETCD2:\n\t\treturn nil, fmt.Errorf(\"%s is no longer a supported storage backend\", c.Type)\n\tcase storagebackend.StorageTypeUnset, storagebackend.StorageTypeETCD3:\n\t\treturn newETCD3ReadyCheck(c, stopCh)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown storage type: %s\", c.Type)\n\t}\n}","line":{"from":55,"to":64}} {"id":100018727,"name":"CreateProber","signature":"func CreateProber(c storagebackend.Config) (Prober, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/storagebackend/factory/factory.go","code":"func CreateProber(c storagebackend.Config) (Prober, error) {\n\tswitch c.Type {\n\tcase storagebackend.StorageTypeETCD2:\n\t\treturn nil, fmt.Errorf(\"%s is no longer a supported storage backend\", c.Type)\n\tcase storagebackend.StorageTypeUnset, storagebackend.StorageTypeETCD3:\n\t\treturn newETCD3Prober(c)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown storage type: %s\", c.Type)\n\t}\n}","line":{"from":66,"to":75}} {"id":100018728,"name":"SimpleUpdate","signature":"func SimpleUpdate(fn SimpleUpdateFunc) UpdateFunc","file":"staging/src/k8s.io/apiserver/pkg/storage/util.go","code":"// SimpleUpdateFunc converts SimpleUpdateFunc into UpdateFunc\nfunc SimpleUpdate(fn SimpleUpdateFunc) UpdateFunc {\n\treturn func(input runtime.Object, _ ResponseMeta) (runtime.Object, *uint64, error) {\n\t\tout, err := fn(input)\n\t\treturn out, nil, err\n\t}\n}","line":{"from":30,"to":36}} {"id":100018729,"name":"EverythingFunc","signature":"func EverythingFunc(runtime.Object) bool","file":"staging/src/k8s.io/apiserver/pkg/storage/util.go","code":"func EverythingFunc(runtime.Object) bool {\n\treturn true\n}","line":{"from":38,"to":40}} {"id":100018730,"name":"NamespaceKeyFunc","signature":"func NamespaceKeyFunc(prefix string, obj runtime.Object) (string, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/util.go","code":"func NamespaceKeyFunc(prefix string, obj runtime.Object) (string, error) {\n\tmeta, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tname := meta.GetName()\n\tif msgs := path.IsValidPathSegmentName(name); len(msgs) != 0 {\n\t\treturn \"\", fmt.Errorf(\"invalid name: %v\", msgs)\n\t}\n\treturn prefix + \"/\" + meta.GetNamespace() + \"/\" + name, nil\n}","line":{"from":42,"to":52}} {"id":100018731,"name":"NoNamespaceKeyFunc","signature":"func NoNamespaceKeyFunc(prefix string, obj runtime.Object) (string, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/util.go","code":"func NoNamespaceKeyFunc(prefix string, obj runtime.Object) (string, error) {\n\tmeta, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tname := meta.GetName()\n\tif msgs := path.IsValidPathSegmentName(name); len(msgs) != 0 {\n\t\treturn \"\", fmt.Errorf(\"invalid name: %v\", msgs)\n\t}\n\treturn prefix + \"/\" + name, nil\n}","line":{"from":54,"to":64}} {"id":100018732,"name":"Update","signature":"func (hwm *HighWaterMark) Update(current int64) bool","file":"staging/src/k8s.io/apiserver/pkg/storage/util.go","code":"// Update returns true if and only if 'current' is the highest value ever seen.\nfunc (hwm *HighWaterMark) Update(current int64) bool {\n\tfor {\n\t\told := atomic.LoadInt64((*int64)(hwm))\n\t\tif current \u003c= old {\n\t\t\treturn false\n\t\t}\n\t\tif atomic.CompareAndSwapInt64((*int64)(hwm), old, current) {\n\t\t\treturn true\n\t\t}\n\t}\n}","line":{"from":70,"to":81}} {"id":100018733,"name":"NewGCMTransformer","signature":"func NewGCMTransformer(block cipher.Block) (value.Transformer, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/aes/aes.go","code":"// NewGCMTransformer takes the given block cipher and performs encryption and decryption on the given data.\n// It implements AEAD encryption of the provided values given a cipher.Block algorithm.\n// The authenticated data provided as part of the value.Context method must match when the same\n// value is set to and loaded from storage. In order to ensure that values cannot be copied by\n// an attacker from a location under their control, use characteristics of the storage location\n// (such as the etcd key) as part of the authenticated data.\n//\n// Because this mode requires a generated IV and IV reuse is a known weakness of AES-GCM, keys\n// must be rotated before a birthday attack becomes feasible. NIST SP 800-38D\n// (http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf) recommends using the same\n// key with random 96-bit nonces (the default nonce length) no more than 2^32 times, and\n// therefore transformers using this implementation *must* ensure they allow for frequent key\n// rotation. Future work should include investigation of AES-GCM-SIV as an alternative to\n// random nonces.\nfunc NewGCMTransformer(block cipher.Block) (value.Transformer, error) {\n\taead, err := newGCM(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026gcm{aead: aead, nonceFunc: randomNonce}, nil\n}","line":{"from":42,"to":63}} {"id":100018734,"name":"NewGCMTransformerWithUniqueKeyUnsafe","signature":"func NewGCMTransformerWithUniqueKeyUnsafe() (value.Transformer, []byte, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/aes/aes.go","code":"// NewGCMTransformerWithUniqueKeyUnsafe is the same as NewGCMTransformer but is unsafe for general\n// use because it makes assumptions about the key underlying the block cipher. Specifically,\n// it uses a 96-bit nonce where the first 32 bits are random data and the remaining 64 bits are\n// a monotonically incrementing atomic counter. This means that the key must be randomly generated\n// on process startup and must never be used for encryption outside the lifetime of the process.\n// Unlike NewGCMTransformer, this function is immune to the birthday attack and thus the key can\n// be used for 2^64-1 writes without rotation. Furthermore, cryptographic wear out of AES-GCM with\n// a sequential nonce occurs after 2^64 encryptions, which is not a concern for our use cases.\n// Even if that occurs, the nonce counter would overflow and crash the process. We have no concerns\n// around plaintext length because all stored items are small (less than 2 MB). To prevent the\n// chance of the block cipher being accidentally re-used, it is not taken in as input. Instead,\n// a new random key is generated and returned on every invocation of this function. This key is\n// used as the input to the block cipher. If the key is stored and retrieved at a later point,\n// it can be passed to NewGCMTransformer(aes.NewCipher(key)) to construct a transformer capable\n// of decrypting values encrypted by this transformer (that transformer must not be used for encryption).\nfunc NewGCMTransformerWithUniqueKeyUnsafe() (value.Transformer, []byte, error) {\n\tkey, err := generateKey(32)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tnonceGen := \u0026nonceGenerator{\n\t\t// we start the nonce counter at one billion so that we are\n\t\t// guaranteed to detect rollover across different go routines\n\t\tzero: 1_000_000_000,\n\t\tfatal: die,\n\t}\n\tnonceGen.nonce.Add(nonceGen.zero)\n\n\ttransformer, err := newGCMTransformerWithUniqueKeyUnsafe(block, nonceGen)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn transformer, key, nil\n}","line":{"from":65,"to":103}} {"id":100018735,"name":"newGCMTransformerWithUniqueKeyUnsafe","signature":"func newGCMTransformerWithUniqueKeyUnsafe(block cipher.Block, nonceGen *nonceGenerator) (value.Transformer, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/aes/aes.go","code":"func newGCMTransformerWithUniqueKeyUnsafe(block cipher.Block, nonceGen *nonceGenerator) (value.Transformer, error) {\n\taead, err := newGCM(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnonceFunc := func(b []byte) error {\n\t\t// we only need 8 bytes to store our 64 bit incrementing nonce\n\t\t// instead of leaving the unused bytes as zeros, set those to random bits\n\t\t// this mostly protects us from weird edge cases like a VM restore that rewinds our atomic counter\n\t\trandNonceSize := len(b) - 8\n\n\t\tif err := randomNonce(b[:randNonceSize]); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tnonceGen.next(b[randNonceSize:])\n\n\t\treturn nil\n\t}\n\n\treturn \u0026gcm{aead: aead, nonceFunc: nonceFunc}, nil\n}","line":{"from":105,"to":127}} {"id":100018736,"name":"newGCM","signature":"func newGCM(block cipher.Block) (cipher.AEAD, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/aes/aes.go","code":"func newGCM(block cipher.Block) (cipher.AEAD, error) {\n\taead, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif nonceSize := aead.NonceSize(); nonceSize != 12 { // all data in etcd will be broken if this ever changes\n\t\treturn nil, fmt.Errorf(\"crypto/cipher.NewGCM returned unexpected nonce size: %d\", nonceSize)\n\t}\n\treturn aead, nil\n}","line":{"from":129,"to":138}} {"id":100018737,"name":"randomNonce","signature":"func randomNonce(b []byte) error","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/aes/aes.go","code":"func randomNonce(b []byte) error {\n\t_, err := rand.Read(b)\n\treturn err\n}","line":{"from":140,"to":143}} {"id":100018738,"name":"next","signature":"func (n *nonceGenerator) next(b []byte)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/aes/aes.go","code":"func (n *nonceGenerator) next(b []byte) {\n\tincrementingNonce := n.nonce.Add(1)\n\tif incrementingNonce \u003c= n.zero {\n\t\t// this should never happen, and is unrecoverable if it does\n\t\tn.fatal(\"aes-gcm detected nonce overflow - cryptographic wear out has occurred\")\n\t}\n\tbinary.LittleEndian.PutUint64(b, incrementingNonce)\n}","line":{"from":153,"to":160}} {"id":100018739,"name":"die","signature":"func die(msg string)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/aes/aes.go","code":"func die(msg string) {\n\t// nolint:logcheck // we want the stack traces, log flushing, and process exiting logic from FatalDepth\n\tklog.FatalDepth(1, msg)\n}","line":{"from":162,"to":165}} {"id":100018740,"name":"generateKey","signature":"func generateKey(length int) (key []byte, err error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/aes/aes.go","code":"// generateKey generates a random key using system randomness.\nfunc generateKey(length int) (key []byte, err error) {\n\tdefer func(start time.Time) {\n\t\tvalue.RecordDataKeyGeneration(start, err)\n\t}(time.Now())\n\tkey = make([]byte, length)\n\tif _, err = rand.Read(key); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn key, nil\n}","line":{"from":167,"to":178}} {"id":100018741,"name":"TransformFromStorage","signature":"func (t *gcm) TransformFromStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/aes/aes.go","code":"func (t *gcm) TransformFromStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, bool, error) {\n\tnonceSize := t.aead.NonceSize()\n\tif len(data) \u003c nonceSize {\n\t\treturn nil, false, errors.New(\"the stored data was shorter than the required size\")\n\t}\n\tresult, err := t.aead.Open(nil, data[:nonceSize], data[nonceSize:], dataCtx.AuthenticatedData())\n\treturn result, false, err\n}","line":{"from":180,"to":187}} {"id":100018742,"name":"TransformToStorage","signature":"func (t *gcm) TransformToStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/aes/aes.go","code":"func (t *gcm) TransformToStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, error) {\n\tnonceSize := t.aead.NonceSize()\n\tresult := make([]byte, nonceSize+t.aead.Overhead()+len(data))\n\n\tif err := t.nonceFunc(result[:nonceSize]); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to write nonce for AES-GCM: %w\", err)\n\t}\n\n\tcipherText := t.aead.Seal(result[nonceSize:nonceSize], result[:nonceSize], data, dataCtx.AuthenticatedData())\n\treturn result[:nonceSize+len(cipherText)], nil\n}","line":{"from":189,"to":199}} {"id":100018743,"name":"NewCBCTransformer","signature":"func NewCBCTransformer(block cipher.Block) value.Transformer","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/aes/aes.go","code":"// NewCBCTransformer takes the given block cipher and performs encryption and decryption on the given\n// data.\nfunc NewCBCTransformer(block cipher.Block) value.Transformer {\n\treturn \u0026cbc{block: block}\n}","line":{"from":206,"to":210}} {"id":100018744,"name":"TransformFromStorage","signature":"func (t *cbc) TransformFromStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/aes/aes.go","code":"func (t *cbc) TransformFromStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, bool, error) {\n\tblockSize := aes.BlockSize\n\tif len(data) \u003c blockSize {\n\t\treturn nil, false, errors.New(\"the stored data was shorter than the required size\")\n\t}\n\tiv := data[:blockSize]\n\tdata = data[blockSize:]\n\n\tif len(data)%blockSize != 0 {\n\t\treturn nil, false, errInvalidBlockSize\n\t}\n\n\tresult := make([]byte, len(data))\n\tcopy(result, data)\n\tmode := cipher.NewCBCDecrypter(t.block, iv)\n\tmode.CryptBlocks(result, result)\n\n\t// remove and verify PKCS#7 padding for CBC\n\tc := result[len(result)-1]\n\tpaddingSize := int(c)\n\tsize := len(result) - paddingSize\n\tif paddingSize == 0 || paddingSize \u003e len(result) {\n\t\treturn nil, false, errInvalidPKCS7Data\n\t}\n\tfor i := 0; i \u003c paddingSize; i++ {\n\t\tif result[size+i] != c {\n\t\t\treturn nil, false, errInvalidPKCS7Padding\n\t\t}\n\t}\n\n\treturn result[:size], false, nil\n}","line":{"from":218,"to":249}} {"id":100018745,"name":"TransformToStorage","signature":"func (t *cbc) TransformToStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/aes/aes.go","code":"func (t *cbc) TransformToStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, error) {\n\tblockSize := aes.BlockSize\n\tpaddingSize := blockSize - (len(data) % blockSize)\n\tresult := make([]byte, blockSize+len(data)+paddingSize)\n\tiv := result[:blockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn nil, errors.New(\"unable to read sufficient random bytes\")\n\t}\n\tcopy(result[blockSize:], data)\n\n\t// add PKCS#7 padding for CBC\n\tcopy(result[blockSize+len(data):], bytes.Repeat([]byte{byte(paddingSize)}, paddingSize))\n\n\tmode := cipher.NewCBCEncrypter(t.block, iv)\n\tmode.CryptBlocks(result[blockSize:], result[blockSize:])\n\treturn result, nil\n}","line":{"from":251,"to":267}} {"id":100018746,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/envelope.go","code":"func init() {\n\tvalue.RegisterMetrics()\n\tmetrics.RegisterMetrics()\n}","line":{"from":36,"to":39}} {"id":100018747,"name":"NewEnvelopeTransformer","signature":"func NewEnvelopeTransformer(envelopeService Service, cacheSize int, baseTransformerFunc func(cipher.Block) (value.Transformer, error)) value.Transformer","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/envelope.go","code":"// NewEnvelopeTransformer returns a transformer which implements a KEK-DEK based envelope encryption scheme.\n// It uses envelopeService to encrypt and decrypt DEKs. Respective DEKs (in encrypted form) are prepended to\n// the data items they encrypt. A cache (of size cacheSize) is maintained to store the most recently\n// used decrypted DEKs in memory.\nfunc NewEnvelopeTransformer(envelopeService Service, cacheSize int, baseTransformerFunc func(cipher.Block) (value.Transformer, error)) value.Transformer {\n\tvar (\n\t\tcache *lru.Cache\n\t)\n\n\tif cacheSize \u003e 0 {\n\t\tcache = lru.New(cacheSize)\n\t}\n\treturn \u0026envelopeTransformer{\n\t\tenvelopeService: envelopeService,\n\t\ttransformers: cache,\n\t\tbaseTransformerFunc: baseTransformerFunc,\n\t\tcacheEnabled: cacheSize \u003e 0,\n\t\tcacheSize: cacheSize,\n\t}\n}","line":{"from":62,"to":81}} {"id":100018748,"name":"TransformFromStorage","signature":"func (t *envelopeTransformer) TransformFromStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/envelope.go","code":"// TransformFromStorage decrypts data encrypted by this transformer using envelope encryption.\nfunc (t *envelopeTransformer) TransformFromStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, bool, error) {\n\tmetrics.RecordArrival(metrics.FromStorageLabel, time.Now())\n\n\t// Read the 16 bit length-of-DEK encoded at the start of the encrypted DEK. 16 bits can\n\t// represent a maximum key length of 65536 bytes. We are using a 256 bit key, whose\n\t// length cannot fit in 8 bits (1 byte). Thus, we use 16 bits (2 bytes) to store the length.\n\tvar encKey cryptobyte.String\n\ts := cryptobyte.String(data)\n\tif ok := s.ReadUint16LengthPrefixed(\u0026encKey); !ok {\n\t\treturn nil, false, fmt.Errorf(\"invalid data encountered by envelope transformer: failed to read uint16 length prefixed data\")\n\t}\n\n\tencData := []byte(s)\n\n\t// Look up the decrypted DEK from cache or Envelope.\n\ttransformer := t.getTransformer(encKey)\n\tif transformer == nil {\n\t\tif t.cacheEnabled {\n\t\t\tvalue.RecordCacheMiss()\n\t\t}\n\t\tkey, err := t.envelopeService.Decrypt(encKey)\n\t\tif err != nil {\n\t\t\t// Do NOT wrap this err using fmt.Errorf() or similar functions\n\t\t\t// because this gRPC status error has useful error code when\n\t\t\t// record the metric.\n\t\t\treturn nil, false, err\n\t\t}\n\n\t\ttransformer, err = t.addTransformer(encKey, key)\n\t\tif err != nil {\n\t\t\treturn nil, false, err\n\t\t}\n\t}\n\n\treturn transformer.TransformFromStorage(ctx, encData, dataCtx)\n}","line":{"from":83,"to":119}} {"id":100018749,"name":"TransformToStorage","signature":"func (t *envelopeTransformer) TransformToStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/envelope.go","code":"// TransformToStorage encrypts data to be written to disk using envelope encryption.\nfunc (t *envelopeTransformer) TransformToStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, error) {\n\tmetrics.RecordArrival(metrics.ToStorageLabel, time.Now())\n\tnewKey, err := generateKey(32)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tencKey, err := t.envelopeService.Encrypt(newKey)\n\tif err != nil {\n\t\t// Do NOT wrap this err using fmt.Errorf() or similar functions\n\t\t// because this gRPC status error has useful error code when\n\t\t// record the metric.\n\t\treturn nil, err\n\t}\n\n\ttransformer, err := t.addTransformer(encKey, newKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult, err := transformer.TransformToStorage(ctx, data, dataCtx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Append the length of the encrypted DEK as the first 2 bytes.\n\tb := cryptobyte.NewBuilder(nil)\n\tb.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {\n\t\tb.AddBytes([]byte(encKey))\n\t})\n\tb.AddBytes(result)\n\n\treturn b.Bytes()\n}","line":{"from":121,"to":154}} {"id":100018750,"name":"addTransformer","signature":"func (t *envelopeTransformer) addTransformer(encKey []byte, key []byte) (value.Transformer, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/envelope.go","code":"// addTransformer inserts a new transformer to the Envelope cache of DEKs for future reads.\nfunc (t *envelopeTransformer) addTransformer(encKey []byte, key []byte) (value.Transformer, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttransformer, err := t.baseTransformerFunc(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Use base64 of encKey as the key into the cache because hashicorp/golang-lru\n\t// cannot hash []uint8.\n\tif t.cacheEnabled {\n\t\tt.transformers.Add(base64.StdEncoding.EncodeToString(encKey), transformer)\n\t\tmetrics.RecordDekCacheFillPercent(float64(t.transformers.Len()) / float64(t.cacheSize))\n\t}\n\treturn transformer, nil\n}","line":{"from":158,"to":176}} {"id":100018751,"name":"getTransformer","signature":"func (t *envelopeTransformer) getTransformer(encKey []byte) value.Transformer","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/envelope.go","code":"// getTransformer fetches the transformer corresponding to encKey from cache, if it exists.\nfunc (t *envelopeTransformer) getTransformer(encKey []byte) value.Transformer {\n\tif !t.cacheEnabled {\n\t\treturn nil\n\t}\n\n\t_transformer, found := t.transformers.Get(base64.StdEncoding.EncodeToString(encKey))\n\tif found {\n\t\treturn _transformer.(value.Transformer)\n\t}\n\treturn nil\n}","line":{"from":178,"to":189}} {"id":100018752,"name":"generateKey","signature":"func generateKey(length int) (key []byte, err error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/envelope.go","code":"// generateKey generates a random key using system randomness.\nfunc generateKey(length int) (key []byte, err error) {\n\tdefer func(start time.Time) {\n\t\tvalue.RecordDataKeyGeneration(start, err)\n\t}(time.Now())\n\tkey = make([]byte, length)\n\tif _, err = rand.Read(key); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn key, nil\n}","line":{"from":191,"to":202}} {"id":100018753,"name":"NewGRPCService","signature":"func NewGRPCService(ctx context.Context, endpoint string, callTimeout time.Duration) (Service, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/grpc_service.go","code":"// NewGRPCService returns an envelope.Service which use gRPC to communicate the remote KMS provider.\nfunc NewGRPCService(ctx context.Context, endpoint string, callTimeout time.Duration) (Service, error) {\n\tklog.V(4).InfoS(\"Configure KMS provider\", \"endpoint\", endpoint)\n\n\taddr, err := util.ParseEndpoint(endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts := \u0026gRPCService{callTimeout: callTimeout}\n\ts.connection, err = grpc.Dial(\n\t\taddr,\n\t\tgrpc.WithTransportCredentials(insecure.NewCredentials()),\n\t\tgrpc.WithUnaryInterceptor(s.interceptor),\n\t\tgrpc.WithDefaultCallOptions(grpc.WaitForReady(true)),\n\t\tgrpc.WithContextDialer(\n\t\t\tfunc(context.Context, string) (net.Conn, error) {\n\t\t\t\t// Ignoring addr and timeout arguments:\n\t\t\t\t// addr - comes from the closure\n\t\t\t\tc, err := net.DialUnix(unixProtocol, nil, \u0026net.UnixAddr{Name: addr})\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"failed to create connection to unix socket\", \"addr\", addr)\n\t\t\t\t} else {\n\t\t\t\t\tklog.V(4).InfoS(\"Successfully dialed Unix socket\", \"addr\", addr)\n\t\t\t\t}\n\t\t\t\treturn c, err\n\t\t\t}))\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create connection to %s, error: %v\", endpoint, err)\n\t}\n\n\ts.kmsClient = kmsapi.NewKeyManagementServiceClient(s.connection)\n\n\tgo func() {\n\t\tdefer utilruntime.HandleCrash()\n\n\t\t\u003c-ctx.Done()\n\t\t_ = s.connection.Close()\n\t}()\n\n\treturn s, nil\n}","line":{"from":54,"to":96}} {"id":100018754,"name":"checkAPIVersion","signature":"func (g *gRPCService) checkAPIVersion(ctx context.Context) error","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/grpc_service.go","code":"func (g *gRPCService) checkAPIVersion(ctx context.Context) error {\n\tg.mux.Lock()\n\tdefer g.mux.Unlock()\n\n\tif g.versionChecked {\n\t\treturn nil\n\t}\n\n\trequest := \u0026kmsapi.VersionRequest{Version: kmsapiVersion}\n\tresponse, err := g.kmsClient.Version(ctx, request)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed get version from remote KMS provider: %v\", err)\n\t}\n\tif response.Version != kmsapiVersion {\n\t\treturn fmt.Errorf(versionErrorf, response.Version, kmsapiVersion)\n\t}\n\tg.versionChecked = true\n\n\tklog.V(4).InfoS(\"KMS provider api version verified\", \"version\", response.Version)\n\treturn nil\n}","line":{"from":98,"to":118}} {"id":100018755,"name":"Decrypt","signature":"func (g *gRPCService) Decrypt(cipher []byte) ([]byte, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/grpc_service.go","code":"// Decrypt a given data string to obtain the original byte data.\nfunc (g *gRPCService) Decrypt(cipher []byte) ([]byte, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), g.callTimeout)\n\tdefer cancel()\n\n\trequest := \u0026kmsapi.DecryptRequest{Cipher: cipher, Version: kmsapiVersion}\n\tresponse, err := g.kmsClient.Decrypt(ctx, request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn response.Plain, nil\n}","line":{"from":120,"to":131}} {"id":100018756,"name":"Encrypt","signature":"func (g *gRPCService) Encrypt(plain []byte) ([]byte, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/grpc_service.go","code":"// Encrypt bytes to a string ciphertext.\nfunc (g *gRPCService) Encrypt(plain []byte) ([]byte, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), g.callTimeout)\n\tdefer cancel()\n\n\trequest := \u0026kmsapi.EncryptRequest{Plain: plain, Version: kmsapiVersion}\n\tresponse, err := g.kmsClient.Encrypt(ctx, request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn response.Cipher, nil\n}","line":{"from":133,"to":144}} {"id":100018757,"name":"interceptor","signature":"func (g *gRPCService) interceptor(","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/grpc_service.go","code":"func (g *gRPCService) interceptor(\n\tctx context.Context,\n\tmethod string,\n\treq interface{},\n\treply interface{},\n\tcc *grpc.ClientConn,\n\tinvoker grpc.UnaryInvoker,\n\topts ...grpc.CallOption,\n) error {\n\tif !kmsapi.IsVersionCheckMethod(method) {\n\t\tif err := g.checkAPIVersion(ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn invoker(ctx, method, req, reply, cc, opts...)\n}","line":{"from":146,"to":162}} {"id":100018758,"name":"newSimpleCache","signature":"func newSimpleCache(clock clock.Clock, ttl time.Duration) *simpleCache","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/cache.go","code":"func newSimpleCache(clock clock.Clock, ttl time.Duration) *simpleCache {\n\treturn \u0026simpleCache{\n\t\tcache: utilcache.NewExpiringWithClock(clock),\n\t\tttl: ttl,\n\t\thashPool: \u0026sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn sha256.New()\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":52,"to":62}} {"id":100018759,"name":"get","signature":"func (c *simpleCache) get(key []byte) decryptTransformer","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/cache.go","code":"// given a key, return the transformer, or nil if it does not exist in the cache\nfunc (c *simpleCache) get(key []byte) decryptTransformer {\n\trecord, ok := c.cache.Get(c.keyFunc(key))\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn record.(decryptTransformer)\n}","line":{"from":64,"to":71}} {"id":100018760,"name":"set","signature":"func (c *simpleCache) set(key []byte, transformer decryptTransformer)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/cache.go","code":"// set caches the record for the key\nfunc (c *simpleCache) set(key []byte, transformer decryptTransformer) {\n\tif len(key) == 0 {\n\t\tpanic(\"key must not be empty\")\n\t}\n\tif transformer == nil {\n\t\tpanic(\"transformer must not be nil\")\n\t}\n\tc.cache.Set(c.keyFunc(key), transformer, c.ttl)\n}","line":{"from":73,"to":82}} {"id":100018761,"name":"keyFunc","signature":"func (c *simpleCache) keyFunc(s []byte) string","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/cache.go","code":"// keyFunc generates a string key by hashing the inputs.\n// This lowers the memory requirement of the cache.\nfunc (c *simpleCache) keyFunc(s []byte) string {\n\th := c.hashPool.Get().(hash.Hash)\n\th.Reset()\n\n\tif _, err := h.Write(s); err != nil {\n\t\tpanic(err) // Write() on hash never fails\n\t}\n\tkey := toString(h.Sum(nil)) // skip base64 encoding to save an allocation\n\tc.hashPool.Put(h)\n\n\treturn key\n}","line":{"from":84,"to":97}} {"id":100018762,"name":"toString","signature":"func toString(b []byte) string","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/cache.go","code":"// toString performs unholy acts to avoid allocations\nfunc toString(b []byte) string {\n\t// unsafe.SliceData relies on cap whereas we want to rely on len\n\tif len(b) == 0 {\n\t\treturn \"\"\n\t}\n\t// Copied from go 1.20.1 strings.Builder.String\n\t// https://github.com/golang/go/blob/202a1a57064127c3f19d96df57b9f9586145e21c/src/strings/builder.go#L48\n\treturn unsafe.String(unsafe.SliceData(b), len(b))\n}","line":{"from":99,"to":108}} {"id":100018763,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/envelope.go","code":"func init() {\n\tvalue.RegisterMetrics()\n\tmetrics.RegisterMetrics()\n}","line":{"from":45,"to":48}} {"id":100018764,"name":"ValidateEncryptCapability","signature":"func (s *State) ValidateEncryptCapability() error","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/envelope.go","code":"func (s *State) ValidateEncryptCapability() error {\n\tif now := NowFunc(); now.After(s.ExpirationTimestamp) {\n\t\treturn fmt.Errorf(\"EDEK with keyID %q expired at %s (current time is %s)\",\n\t\t\ts.KeyID, s.ExpirationTimestamp.Format(time.RFC3339), now.Format(time.RFC3339))\n\t}\n\treturn nil\n}","line":{"from":98,"to":104}} {"id":100018765,"name":"NewEnvelopeTransformer","signature":"func NewEnvelopeTransformer(envelopeService kmsservice.Service, providerName string, stateFunc StateFunc) value.Transformer","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/envelope.go","code":"// NewEnvelopeTransformer returns a transformer which implements a KEK-DEK based envelope encryption scheme.\n// It uses envelopeService to encrypt and decrypt DEKs. Respective DEKs (in encrypted form) are prepended to\n// the data items they encrypt.\nfunc NewEnvelopeTransformer(envelopeService kmsservice.Service, providerName string, stateFunc StateFunc) value.Transformer {\n\treturn newEnvelopeTransformerWithClock(envelopeService, providerName, stateFunc, cacheTTL, clock.RealClock{})\n}","line":{"from":115,"to":120}} {"id":100018766,"name":"newEnvelopeTransformerWithClock","signature":"func newEnvelopeTransformerWithClock(envelopeService kmsservice.Service, providerName string, stateFunc StateFunc, cacheTTL time.Duration, clock clock.Clock) value.Transformer","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/envelope.go","code":"func newEnvelopeTransformerWithClock(envelopeService kmsservice.Service, providerName string, stateFunc StateFunc, cacheTTL time.Duration, clock clock.Clock) value.Transformer {\n\treturn \u0026envelopeTransformer{\n\t\tenvelopeService: envelopeService,\n\t\tproviderName: providerName,\n\t\tstateFunc: stateFunc,\n\t\tcache: newSimpleCache(clock, cacheTTL),\n\t}\n}","line":{"from":122,"to":129}} {"id":100018767,"name":"TransformFromStorage","signature":"func (t *envelopeTransformer) TransformFromStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/envelope.go","code":"// TransformFromStorage decrypts data encrypted by this transformer using envelope encryption.\nfunc (t *envelopeTransformer) TransformFromStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, bool, error) {\n\t// Deserialize the EncryptedObject from the data.\n\tencryptedObject, err := t.doDecode(data)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\t// TODO: consider marking state.EncryptedDEK != encryptedObject.EncryptedDEK as a stale read to support DEK defragmentation\n\t// at a minimum we should have a metric that helps the user understand if DEK fragmentation is high\n\tstate, err := t.stateFunc() // no need to call state.ValidateEncryptCapability on reads\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\tencryptedObjectCacheKey, err := generateCacheKey(encryptedObject.EncryptedDEK, encryptedObject.KeyID, encryptedObject.Annotations)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\t// Look up the decrypted DEK from cache first\n\ttransformer := t.cache.get(encryptedObjectCacheKey)\n\n\t// fallback to the envelope service if we do not have the transformer locally\n\tif transformer == nil {\n\t\tvalue.RecordCacheMiss()\n\n\t\trequestInfo := getRequestInfoFromContext(ctx)\n\t\tuid := string(uuid.NewUUID())\n\t\tklog.V(6).InfoS(\"decrypting content using envelope service\", \"uid\", uid, \"key\", string(dataCtx.AuthenticatedData()),\n\t\t\t\"group\", requestInfo.APIGroup, \"version\", requestInfo.APIVersion, \"resource\", requestInfo.Resource, \"subresource\", requestInfo.Subresource,\n\t\t\t\"verb\", requestInfo.Verb, \"namespace\", requestInfo.Namespace, \"name\", requestInfo.Name)\n\n\t\tkey, err := t.envelopeService.Decrypt(ctx, uid, \u0026kmsservice.DecryptRequest{\n\t\t\tCiphertext: encryptedObject.EncryptedDEK,\n\t\t\tKeyID: encryptedObject.KeyID,\n\t\t\tAnnotations: encryptedObject.Annotations,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, false, fmt.Errorf(\"failed to decrypt DEK, error: %w\", err)\n\t\t}\n\n\t\ttransformer, err = t.addTransformerForDecryption(encryptedObjectCacheKey, key)\n\t\tif err != nil {\n\t\t\treturn nil, false, err\n\t\t}\n\t}\n\tmetrics.RecordKeyID(metrics.FromStorageLabel, t.providerName, encryptedObject.KeyID)\n\n\tout, stale, err := transformer.TransformFromStorage(ctx, encryptedObject.EncryptedData, dataCtx)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\t// data is considered stale if the key ID does not match our current write transformer\n\treturn out, stale || encryptedObject.KeyID != state.KeyID, nil\n\n}","line":{"from":131,"to":188}} {"id":100018768,"name":"TransformToStorage","signature":"func (t *envelopeTransformer) TransformToStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/envelope.go","code":"// TransformToStorage encrypts data to be written to disk using envelope encryption.\nfunc (t *envelopeTransformer) TransformToStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, error) {\n\tstate, err := t.stateFunc()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := state.ValidateEncryptCapability(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// this prevents a cache miss every time the DEK rotates\n\t// this has the side benefit of causing the cache to perform a GC\n\t// TODO see if we can do this inside the stateFunc control loop\n\t// TODO(aramase): Add metrics for cache fill percentage with custom cache implementation.\n\tt.cache.set(state.CacheKey, state.Transformer)\n\n\trequestInfo := getRequestInfoFromContext(ctx)\n\tklog.V(6).InfoS(\"encrypting content using DEK\", \"uid\", state.UID, \"key\", string(dataCtx.AuthenticatedData()),\n\t\t\"group\", requestInfo.APIGroup, \"version\", requestInfo.APIVersion, \"resource\", requestInfo.Resource, \"subresource\", requestInfo.Subresource,\n\t\t\"verb\", requestInfo.Verb, \"namespace\", requestInfo.Namespace, \"name\", requestInfo.Name)\n\n\tresult, err := state.Transformer.TransformToStorage(ctx, data, dataCtx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmetrics.RecordKeyID(metrics.ToStorageLabel, t.providerName, state.KeyID)\n\n\tencObject := \u0026kmstypes.EncryptedObject{\n\t\tKeyID: state.KeyID,\n\t\tEncryptedDEK: state.EncryptedDEK,\n\t\tEncryptedData: result,\n\t\tAnnotations: state.Annotations,\n\t}\n\n\t// Serialize the EncryptedObject to a byte array.\n\treturn t.doEncode(encObject)\n}","line":{"from":190,"to":227}} {"id":100018769,"name":"addTransformerForDecryption","signature":"func (t *envelopeTransformer) addTransformerForDecryption(cacheKey []byte, key []byte) (decryptTransformer, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/envelope.go","code":"// addTransformerForDecryption inserts a new transformer to the Envelope cache of DEKs for future reads.\nfunc (t *envelopeTransformer) addTransformerForDecryption(cacheKey []byte, key []byte) (decryptTransformer, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// this is compatible with NewGCMTransformerWithUniqueKeyUnsafe for decryption\n\t// it would use random nonces for encryption but we never do that\n\ttransformer, err := aestransformer.NewGCMTransformer(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// TODO(aramase): Add metrics for cache fill percentage with custom cache implementation.\n\tt.cache.set(cacheKey, transformer)\n\treturn transformer, nil\n}","line":{"from":229,"to":244}} {"id":100018770,"name":"doEncode","signature":"func (t *envelopeTransformer) doEncode(request *kmstypes.EncryptedObject) ([]byte, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/envelope.go","code":"// doEncode encodes the EncryptedObject to a byte array.\nfunc (t *envelopeTransformer) doEncode(request *kmstypes.EncryptedObject) ([]byte, error) {\n\tif err := validateEncryptedObject(request); err != nil {\n\t\treturn nil, err\n\t}\n\treturn proto.Marshal(request)\n}","line":{"from":246,"to":252}} {"id":100018771,"name":"doDecode","signature":"func (t *envelopeTransformer) doDecode(originalData []byte) (*kmstypes.EncryptedObject, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/envelope.go","code":"// doDecode decodes the byte array to an EncryptedObject.\nfunc (t *envelopeTransformer) doDecode(originalData []byte) (*kmstypes.EncryptedObject, error) {\n\to := \u0026kmstypes.EncryptedObject{}\n\tif err := proto.Unmarshal(originalData, o); err != nil {\n\t\treturn nil, err\n\t}\n\t// validate the EncryptedObject\n\tif err := validateEncryptedObject(o); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn o, nil\n}","line":{"from":254,"to":266}} {"id":100018772,"name":"GenerateTransformer","signature":"func GenerateTransformer(ctx context.Context, uid string, envelopeService kmsservice.Service) (value.Transformer, *kmsservice.EncryptResponse, []byte, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/envelope.go","code":"func GenerateTransformer(ctx context.Context, uid string, envelopeService kmsservice.Service) (value.Transformer, *kmsservice.EncryptResponse, []byte, error) {\n\ttransformer, newKey, err := aestransformer.NewGCMTransformerWithUniqueKeyUnsafe()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tklog.V(6).InfoS(\"encrypting content using envelope service\", \"uid\", uid)\n\n\tresp, err := envelopeService.Encrypt(ctx, uid, newKey)\n\tif err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"failed to encrypt DEK, error: %w\", err)\n\t}\n\n\tif err := validateEncryptedObject(\u0026kmstypes.EncryptedObject{\n\t\tKeyID: resp.KeyID,\n\t\tEncryptedDEK: resp.Ciphertext,\n\t\tEncryptedData: []byte{0}, // any non-empty value to pass validation\n\t\tAnnotations: resp.Annotations,\n\t}); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tcacheKey, err := generateCacheKey(resp.Ciphertext, resp.KeyID, resp.Annotations)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\treturn transformer, resp, cacheKey, nil\n}","line":{"from":268,"to":296}} {"id":100018773,"name":"validateEncryptedObject","signature":"func validateEncryptedObject(o *kmstypes.EncryptedObject) error","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/envelope.go","code":"func validateEncryptedObject(o *kmstypes.EncryptedObject) error {\n\tif o == nil {\n\t\treturn fmt.Errorf(\"encrypted object is nil\")\n\t}\n\tif len(o.EncryptedData) == 0 {\n\t\treturn fmt.Errorf(\"encrypted data is empty\")\n\t}\n\tif err := validateEncryptedDEK(o.EncryptedDEK); err != nil {\n\t\treturn fmt.Errorf(\"failed to validate encrypted DEK: %w\", err)\n\t}\n\tif _, err := ValidateKeyID(o.KeyID); err != nil {\n\t\treturn fmt.Errorf(\"failed to validate key id: %w\", err)\n\t}\n\tif err := validateAnnotations(o.Annotations); err != nil {\n\t\treturn fmt.Errorf(\"failed to validate annotations: %w\", err)\n\t}\n\treturn nil\n}","line":{"from":298,"to":315}} {"id":100018774,"name":"validateEncryptedDEK","signature":"func validateEncryptedDEK(encryptedDEK []byte) error","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/envelope.go","code":"// validateEncryptedDEK tests the following:\n// 1. The encrypted DEK is not empty.\n// 2. The size of encrypted DEK is less than 1 kB.\nfunc validateEncryptedDEK(encryptedDEK []byte) error {\n\tif len(encryptedDEK) == 0 {\n\t\treturn fmt.Errorf(\"encrypted DEK is empty\")\n\t}\n\tif len(encryptedDEK) \u003e encryptedDEKMaxSize {\n\t\treturn fmt.Errorf(\"encrypted DEK is %d bytes, which exceeds the max size of %d\", len(encryptedDEK), encryptedDEKMaxSize)\n\t}\n\treturn nil\n}","line":{"from":317,"to":328}} {"id":100018775,"name":"validateAnnotations","signature":"func validateAnnotations(annotations map[string][]byte) error","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/envelope.go","code":"// validateAnnotations tests the following:\n// 1. checks if the annotation key is fully qualified\n// 2. The size of annotations keys + values is less than 32 kB.\nfunc validateAnnotations(annotations map[string][]byte) error {\n\tvar errs []error\n\tvar totalSize uint64\n\tfor k, v := range annotations {\n\t\tif fieldErr := validation.IsFullyQualifiedDomainName(field.NewPath(\"annotations\"), k); fieldErr != nil {\n\t\t\terrs = append(errs, fieldErr.ToAggregate())\n\t\t}\n\t\ttotalSize += uint64(len(k)) + uint64(len(v))\n\t}\n\tif totalSize \u003e annotationsMaxSize {\n\t\terrs = append(errs, fmt.Errorf(\"total size of annotations is %d, which exceeds the max size of %d\", totalSize, annotationsMaxSize))\n\t}\n\treturn utilerrors.NewAggregate(errs)\n}","line":{"from":330,"to":346}} {"id":100018776,"name":"ValidateKeyID","signature":"func ValidateKeyID(keyID string) (ErrCodeKeyID, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/envelope.go","code":"// ValidateKeyID tests the following:\n// 1. The keyID is not empty.\n// 2. The size of keyID is less than 1 kB.\nfunc ValidateKeyID(keyID string) (ErrCodeKeyID, error) {\n\tif len(keyID) == 0 {\n\t\treturn errKeyIDEmptyCode, fmt.Errorf(\"keyID is empty\")\n\t}\n\tif len(keyID) \u003e KeyIDMaxSize {\n\t\treturn errKeyIDTooLongCode, fmt.Errorf(\"keyID is %d bytes, which exceeds the max size of %d\", len(keyID), KeyIDMaxSize)\n\t}\n\treturn errKeyIDOKCode, nil\n}","line":{"from":348,"to":359}} {"id":100018777,"name":"getRequestInfoFromContext","signature":"func getRequestInfoFromContext(ctx context.Context) *genericapirequest.RequestInfo","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/envelope.go","code":"func getRequestInfoFromContext(ctx context.Context) *genericapirequest.RequestInfo {\n\tif reqInfo, found := genericapirequest.RequestInfoFrom(ctx); found {\n\t\treturn reqInfo\n\t}\n\treturn \u0026genericapirequest.RequestInfo{}\n}","line":{"from":361,"to":366}} {"id":100018778,"name":"generateCacheKey","signature":"func generateCacheKey(encryptedDEK []byte, keyID string, annotations map[string][]byte) ([]byte, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/envelope.go","code":"// generateCacheKey returns a key for the cache.\n// The key is a concatenation of:\n// 1. encryptedDEK\n// 2. keyID\n// 3. length of annotations\n// 4. annotations (sorted by key) - each annotation is a concatenation of:\n// a. annotation key\n// b. annotation value\nfunc generateCacheKey(encryptedDEK []byte, keyID string, annotations map[string][]byte) ([]byte, error) {\n\t// TODO(aramase): use sync pool buffer to avoid allocations\n\tb := cryptobyte.NewBuilder(nil)\n\tb.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {\n\t\tb.AddBytes(encryptedDEK)\n\t})\n\tb.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {\n\t\tb.AddBytes(toBytes(keyID))\n\t})\n\tif len(annotations) == 0 {\n\t\treturn b.Bytes()\n\t}\n\n\t// add the length of annotations to the cache key\n\tb.AddUint32(uint32(len(annotations)))\n\n\t// Sort the annotations by key.\n\tkeys := make([]string, 0, len(annotations))\n\tfor k := range annotations {\n\t\tk := k\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\tfor _, k := range keys {\n\t\t// The maximum size of annotations is annotationsMaxSize (32 kB) so we can safely\n\t\t// assume that the length of the key and value will fit in a uint16.\n\t\tb.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {\n\t\t\tb.AddBytes(toBytes(k))\n\t\t})\n\t\tb.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {\n\t\t\tb.AddBytes(annotations[k])\n\t\t})\n\t}\n\n\treturn b.Bytes()\n}","line":{"from":368,"to":411}} {"id":100018779,"name":"toBytes","signature":"func toBytes(s string) []byte","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/envelope.go","code":"// toBytes performs unholy acts to avoid allocations\nfunc toBytes(s string) []byte {\n\t// unsafe.StringData is unspecified for the empty string, so we provide a strict interpretation\n\tif len(s) == 0 {\n\t\treturn nil\n\t}\n\t// Copied from go 1.20.1 os.File.WriteString\n\t// https://github.com/golang/go/blob/202a1a57064127c3f19d96df57b9f9586145e21c/src/os/file.go#L246\n\treturn unsafe.Slice(unsafe.StringData(s), len(s))\n}","line":{"from":413,"to":422}} {"id":100018780,"name":"NewGRPCService","signature":"func NewGRPCService(ctx context.Context, endpoint, providerName string, callTimeout time.Duration) (kmsservice.Service, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/grpc_service.go","code":"// NewGRPCService returns an envelope.Service which use gRPC to communicate the remote KMS provider.\nfunc NewGRPCService(ctx context.Context, endpoint, providerName string, callTimeout time.Duration) (kmsservice.Service, error) {\n\tklog.V(4).InfoS(\"Configure KMS provider\", \"endpoint\", endpoint)\n\n\taddr, err := util.ParseEndpoint(endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts := \u0026gRPCService{callTimeout: callTimeout}\n\ts.connection, err = grpc.Dial(\n\t\taddr,\n\t\tgrpc.WithTransportCredentials(insecure.NewCredentials()),\n\t\tgrpc.WithDefaultCallOptions(grpc.WaitForReady(true)),\n\t\tgrpc.WithContextDialer(\n\t\t\tfunc(context.Context, string) (net.Conn, error) {\n\t\t\t\t// Ignoring addr and timeout arguments:\n\t\t\t\t// addr - comes from the closure\n\t\t\t\tc, err := net.DialUnix(unixProtocol, nil, \u0026net.UnixAddr{Name: addr})\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.ErrorS(err, \"failed to create connection to unix socket\", \"addr\", addr)\n\t\t\t\t} else {\n\t\t\t\t\tklog.V(4).InfoS(\"Successfully dialed Unix socket\", \"addr\", addr)\n\t\t\t\t}\n\t\t\t\treturn c, err\n\t\t\t}),\n\t\tgrpc.WithChainUnaryInterceptor(recordMetricsInterceptor(providerName)),\n\t)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create connection to %s, error: %v\", endpoint, err)\n\t}\n\n\ts.kmsClient = kmsapi.NewKeyManagementServiceClient(s.connection)\n\n\tgo func() {\n\t\tdefer utilruntime.HandleCrash()\n\n\t\t\u003c-ctx.Done()\n\t\t_ = s.connection.Close()\n\t}()\n\n\treturn s, nil\n}","line":{"from":49,"to":92}} {"id":100018781,"name":"Decrypt","signature":"func (g *gRPCService) Decrypt(ctx context.Context, uid string, req *kmsservice.DecryptRequest) ([]byte, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/grpc_service.go","code":"// Decrypt a given data string to obtain the original byte data.\nfunc (g *gRPCService) Decrypt(ctx context.Context, uid string, req *kmsservice.DecryptRequest) ([]byte, error) {\n\tctx, cancel := context.WithTimeout(ctx, g.callTimeout)\n\tdefer cancel()\n\n\trequest := \u0026kmsapi.DecryptRequest{\n\t\tCiphertext: req.Ciphertext,\n\t\tUid: uid,\n\t\tKeyId: req.KeyID,\n\t\tAnnotations: req.Annotations,\n\t}\n\tresponse, err := g.kmsClient.Decrypt(ctx, request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn response.Plaintext, nil\n}","line":{"from":94,"to":110}} {"id":100018782,"name":"Encrypt","signature":"func (g *gRPCService) Encrypt(ctx context.Context, uid string, plaintext []byte) (*kmsservice.EncryptResponse, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/grpc_service.go","code":"// Encrypt bytes to a string ciphertext.\nfunc (g *gRPCService) Encrypt(ctx context.Context, uid string, plaintext []byte) (*kmsservice.EncryptResponse, error) {\n\tctx, cancel := context.WithTimeout(ctx, g.callTimeout)\n\tdefer cancel()\n\n\trequest := \u0026kmsapi.EncryptRequest{\n\t\tPlaintext: plaintext,\n\t\tUid: uid,\n\t}\n\tresponse, err := g.kmsClient.Encrypt(ctx, request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026kmsservice.EncryptResponse{\n\t\tCiphertext: response.Ciphertext,\n\t\tKeyID: response.KeyId,\n\t\tAnnotations: response.Annotations,\n\t}, nil\n}","line":{"from":112,"to":130}} {"id":100018783,"name":"Status","signature":"func (g *gRPCService) Status(ctx context.Context) (*kmsservice.StatusResponse, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/grpc_service.go","code":"// Status returns the status of the KMSv2 provider.\nfunc (g *gRPCService) Status(ctx context.Context) (*kmsservice.StatusResponse, error) {\n\tctx, cancel := context.WithTimeout(ctx, g.callTimeout)\n\tdefer cancel()\n\n\trequest := \u0026kmsapi.StatusRequest{}\n\tresponse, err := g.kmsClient.Status(ctx, request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026kmsservice.StatusResponse{Version: response.Version, Healthz: response.Healthz, KeyID: response.KeyId}, nil\n}","line":{"from":132,"to":143}} {"id":100018784,"name":"recordMetricsInterceptor","signature":"func recordMetricsInterceptor(providerName string) grpc.UnaryClientInterceptor","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/grpc_service.go","code":"func recordMetricsInterceptor(providerName string) grpc.UnaryClientInterceptor {\n\treturn func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {\n\t\tstart := NowFunc()\n\t\trespErr := invoker(ctx, method, req, reply, cc, opts...)\n\t\telapsed := NowFunc().Sub(start)\n\t\tmetrics.RecordKMSOperationLatency(providerName, method, elapsed, respErr)\n\t\treturn respErr\n\t}\n}","line":{"from":145,"to":153}} {"id":100018785,"name":"registerLRUMetrics","signature":"func registerLRUMetrics()","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/metrics/metrics.go","code":"func registerLRUMetrics() {\n\tif keyIDHashTotalMetricLabels != nil {\n\t\tkeyIDHashTotalMetricLabels.Clear()\n\t}\n\tif keyIDHashStatusLastTimestampSecondsMetricLabels != nil {\n\t\tkeyIDHashStatusLastTimestampSecondsMetricLabels.Clear()\n\t}\n\n\tkeyIDHashTotalMetricLabels = lru.NewWithEvictionFunc(cacheSize, func(key lru.Key, _ interface{}) {\n\t\titem := key.(metricLabels)\n\t\tif deleted := KeyIDHashTotal.DeleteLabelValues(item.transformationType, item.providerName, item.keyIDHash); deleted {\n\t\t\tklog.InfoS(\"Deleted keyIDHashTotalMetricLabels\", \"transformationType\", item.transformationType,\n\t\t\t\t\"providerName\", item.providerName, \"keyIDHash\", item.keyIDHash)\n\t\t}\n\t\tif deleted := KeyIDHashLastTimestampSeconds.DeleteLabelValues(item.transformationType, item.providerName, item.keyIDHash); deleted {\n\t\t\tklog.InfoS(\"Deleted keyIDHashLastTimestampSecondsMetricLabels\", \"transformationType\", item.transformationType,\n\t\t\t\t\"providerName\", item.providerName, \"keyIDHash\", item.keyIDHash)\n\t\t}\n\t})\n\tkeyIDHashStatusLastTimestampSecondsMetricLabels = lru.NewWithEvictionFunc(cacheSize, func(key lru.Key, _ interface{}) {\n\t\titem := key.(metricLabels)\n\t\tif deleted := KeyIDHashStatusLastTimestampSeconds.DeleteLabelValues(item.providerName, item.keyIDHash); deleted {\n\t\t\tklog.InfoS(\"Deleted keyIDHashStatusLastTimestampSecondsMetricLabels\", \"providerName\", item.providerName, \"keyIDHash\", item.keyIDHash)\n\t\t}\n\t})\n}","line":{"from":164,"to":189}} {"id":100018786,"name":"RegisterMetrics","signature":"func RegisterMetrics()","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/metrics/metrics.go","code":"func RegisterMetrics() {\n\tregisterMetricsFunc.Do(func() {\n\t\tregisterLRUMetrics()\n\t\thashPool = \u0026sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn sha256.New()\n\t\t\t},\n\t\t}\n\t\tlegacyregistry.MustRegister(dekCacheFillPercent)\n\t\tlegacyregistry.MustRegister(dekCacheInterArrivals)\n\t\tlegacyregistry.MustRegister(KeyIDHashTotal)\n\t\tlegacyregistry.MustRegister(KeyIDHashLastTimestampSeconds)\n\t\tlegacyregistry.MustRegister(KeyIDHashStatusLastTimestampSeconds)\n\t\tlegacyregistry.MustRegister(InvalidKeyIDFromStatusTotal)\n\t\tlegacyregistry.MustRegister(KMSOperationsLatencyMetric)\n\t})\n}","line":{"from":190,"to":206}} {"id":100018787,"name":"RecordKeyID","signature":"func RecordKeyID(transformationType, providerName, keyID string)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/metrics/metrics.go","code":"// RecordKeyID records total count and last time in seconds when a KeyID was used for TransformFromStorage and TransformToStorage operations\nfunc RecordKeyID(transformationType, providerName, keyID string) {\n\tlockRecordKeyID.Lock()\n\tdefer lockRecordKeyID.Unlock()\n\n\tkeyIDHash := addLabelToCache(keyIDHashTotalMetricLabels, transformationType, providerName, keyID)\n\tKeyIDHashTotal.WithLabelValues(transformationType, providerName, keyIDHash).Inc()\n\tKeyIDHashLastTimestampSeconds.WithLabelValues(transformationType, providerName, keyIDHash).SetToCurrentTime()\n}","line":{"from":208,"to":216}} {"id":100018788,"name":"RecordKeyIDFromStatus","signature":"func RecordKeyIDFromStatus(providerName, keyID string)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/metrics/metrics.go","code":"// RecordKeyIDFromStatus records last time in seconds when a KeyID was returned by the Status RPC call.\nfunc RecordKeyIDFromStatus(providerName, keyID string) {\n\tlockRecordKeyIDStatus.Lock()\n\tdefer lockRecordKeyIDStatus.Unlock()\n\n\tkeyIDHash := addLabelToCache(keyIDHashStatusLastTimestampSecondsMetricLabels, \"\", providerName, keyID)\n\tKeyIDHashStatusLastTimestampSeconds.WithLabelValues(providerName, keyIDHash).SetToCurrentTime()\n}","line":{"from":218,"to":225}} {"id":100018789,"name":"RecordInvalidKeyIDFromStatus","signature":"func RecordInvalidKeyIDFromStatus(providerName, errCode string)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/metrics/metrics.go","code":"func RecordInvalidKeyIDFromStatus(providerName, errCode string) {\n\tInvalidKeyIDFromStatusTotal.WithLabelValues(providerName, errCode).Inc()\n}","line":{"from":227,"to":229}} {"id":100018790,"name":"RecordArrival","signature":"func RecordArrival(transformationType string, start time.Time)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/metrics/metrics.go","code":"func RecordArrival(transformationType string, start time.Time) {\n\tswitch transformationType {\n\tcase FromStorageLabel:\n\t\tlockLastFromStorage.Lock()\n\t\tdefer lockLastFromStorage.Unlock()\n\n\t\tif lastFromStorage.IsZero() {\n\t\t\tlastFromStorage = start\n\t\t}\n\t\tdekCacheInterArrivals.WithLabelValues(transformationType).Observe(start.Sub(lastFromStorage).Seconds())\n\t\tlastFromStorage = start\n\tcase ToStorageLabel:\n\t\tlockLastToStorage.Lock()\n\t\tdefer lockLastToStorage.Unlock()\n\n\t\tif lastToStorage.IsZero() {\n\t\t\tlastToStorage = start\n\t\t}\n\t\tdekCacheInterArrivals.WithLabelValues(transformationType).Observe(start.Sub(lastToStorage).Seconds())\n\t\tlastToStorage = start\n\t}\n}","line":{"from":231,"to":252}} {"id":100018791,"name":"RecordDekCacheFillPercent","signature":"func RecordDekCacheFillPercent(percent float64)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/metrics/metrics.go","code":"func RecordDekCacheFillPercent(percent float64) {\n\tdekCacheFillPercent.Set(percent)\n}","line":{"from":254,"to":256}} {"id":100018792,"name":"RecordKMSOperationLatency","signature":"func RecordKMSOperationLatency(providerName, methodName string, duration time.Duration, err error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/metrics/metrics.go","code":"// RecordKMSOperationLatency records the latency of KMS operation.\nfunc RecordKMSOperationLatency(providerName, methodName string, duration time.Duration, err error) {\n\tKMSOperationsLatencyMetric.WithLabelValues(providerName, methodName, getErrorCode(err)).Observe(duration.Seconds())\n}","line":{"from":258,"to":261}} {"id":100018793,"name":"getErrorCode","signature":"func getErrorCode(err error) string","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/metrics/metrics.go","code":"func getErrorCode(err error) string {\n\tif err == nil {\n\t\treturn codes.OK.String()\n\t}\n\n\t// handle errors wrapped with fmt.Errorf and similar\n\tvar s gRPCError\n\tif errors.As(err, \u0026s) {\n\t\treturn s.GRPCStatus().Code().String()\n\t}\n\n\t// This is not gRPC error. The operation must have failed before gRPC\n\t// method was called, otherwise we would get gRPC error.\n\treturn \"unknown-non-grpc\"\n}","line":{"from":267,"to":281}} {"id":100018794,"name":"getHash","signature":"func getHash(data string) string","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/metrics/metrics.go","code":"func getHash(data string) string {\n\th := hashPool.Get().(hash.Hash)\n\th.Reset()\n\th.Write([]byte(data))\n\tresult := fmt.Sprintf(\"sha256:%x\", h.Sum(nil))\n\thashPool.Put(h)\n\treturn result\n}","line":{"from":283,"to":290}} {"id":100018795,"name":"addLabelToCache","signature":"func addLabelToCache(c *lru.Cache, transformationType, providerName, keyID string) string","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/metrics/metrics.go","code":"func addLabelToCache(c *lru.Cache, transformationType, providerName, keyID string) string {\n\tkeyIDHash := \"\"\n\t// only get hash if the keyID is not empty\n\tif len(keyID) \u003e 0 {\n\t\tkeyIDHash = getHash(keyID)\n\t}\n\tc.Add(metricLabels{\n\t\ttransformationType: transformationType,\n\t\tproviderName: providerName,\n\t\tkeyIDHash: keyIDHash,\n\t}, nil) // value is irrelevant, this is a set and not a map\n\treturn keyIDHash\n}","line":{"from":292,"to":304}} {"id":100018796,"name":"NewEncryptCheckTransformer","signature":"func NewEncryptCheckTransformer() value.Transformer","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/identity/identity.go","code":"// NewEncryptCheckTransformer returns an identityTransformer which returns an error\n// on attempts to read encrypted data\nfunc NewEncryptCheckTransformer() value.Transformer {\n\treturn transformer\n}","line":{"from":37,"to":41}} {"id":100018797,"name":"TransformFromStorage","signature":"func (identityTransformer) TransformFromStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/identity/identity.go","code":"// TransformFromStorage returns the input bytes if the data is not encrypted\nfunc (identityTransformer) TransformFromStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, bool, error) {\n\t// identityTransformer has to return an error if the data is encoded using another transformer.\n\t// JSON data starts with '{'. Protobuf data has a prefix 'k8s[\\x00-\\xFF]'.\n\t// Prefix 'k8s:enc:' is reserved for encrypted data on disk.\n\tif bytes.HasPrefix(data, encryptedPrefix) {\n\t\treturn nil, false, errEncryptedData\n\t}\n\treturn data, false, nil\n}","line":{"from":43,"to":52}} {"id":100018798,"name":"TransformToStorage","signature":"func (identityTransformer) TransformToStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/identity/identity.go","code":"// TransformToStorage implements the Transformer interface for identityTransformer\nfunc (identityTransformer) TransformToStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, error) {\n\treturn data, nil\n}","line":{"from":54,"to":57}} {"id":100018799,"name":"NewSecretboxTransformer","signature":"func NewSecretboxTransformer(key [32]byte) value.Transformer","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/secretbox/secretbox.go","code":"// NewSecretboxTransformer takes the given key and performs encryption and decryption on the given\n// data.\nfunc NewSecretboxTransformer(key [32]byte) value.Transformer {\n\treturn \u0026secretboxTransformer{key: key}\n}","line":{"from":39,"to":43}} {"id":100018800,"name":"TransformFromStorage","signature":"func (t *secretboxTransformer) TransformFromStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/secretbox/secretbox.go","code":"func (t *secretboxTransformer) TransformFromStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, bool, error) {\n\tif len(data) \u003c (secretbox.Overhead + nonceSize) {\n\t\treturn nil, false, fmt.Errorf(\"the stored data was shorter than the required size\")\n\t}\n\tvar nonce [nonceSize]byte\n\tcopy(nonce[:], data[:nonceSize])\n\tdata = data[nonceSize:]\n\tout := make([]byte, 0, len(data)-secretbox.Overhead)\n\tresult, ok := secretbox.Open(out, data, \u0026nonce, \u0026t.key)\n\tif !ok {\n\t\treturn nil, false, fmt.Errorf(\"output array was not large enough for encryption\")\n\t}\n\treturn result, false, nil\n}","line":{"from":45,"to":58}} {"id":100018801,"name":"TransformToStorage","signature":"func (t *secretboxTransformer) TransformToStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/secretbox/secretbox.go","code":"func (t *secretboxTransformer) TransformToStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, error) {\n\tvar nonce [nonceSize]byte\n\tn, err := rand.Read(nonce[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif n != nonceSize {\n\t\treturn nil, fmt.Errorf(\"unable to read sufficient random bytes\")\n\t}\n\treturn secretbox.Seal(nonce[:], data, \u0026nonce, \u0026t.key), nil\n}","line":{"from":60,"to":70}} {"id":100018802,"name":"RegisterMetrics","signature":"func RegisterMetrics()","file":"staging/src/k8s.io/apiserver/pkg/storage/value/metrics.go","code":"func RegisterMetrics() {\n\tregisterMetrics.Do(func() {\n\t\tlegacyregistry.MustRegister(transformerLatencies)\n\t\tlegacyregistry.MustRegister(transformerOperationsTotal)\n\t\tlegacyregistry.MustRegister(envelopeTransformationCacheMissTotal)\n\t\tlegacyregistry.MustRegister(dataKeyGenerationLatencies)\n\t\tlegacyregistry.MustRegister(dataKeyGenerationFailuresTotal)\n\t})\n}","line":{"from":102,"to":110}} {"id":100018803,"name":"RecordTransformation","signature":"func RecordTransformation(transformationType, transformerPrefix string, elapsed time.Duration, err error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/metrics.go","code":"// RecordTransformation records latencies and count of TransformFromStorage and TransformToStorage operations.\n// Note that transformation_failures_total metric is deprecated, use transformation_operations_total instead.\nfunc RecordTransformation(transformationType, transformerPrefix string, elapsed time.Duration, err error) {\n\ttransformerOperationsTotal.WithLabelValues(transformationType, transformerPrefix, status.Code(err).String()).Inc()\n\n\tif err == nil {\n\t\ttransformerLatencies.WithLabelValues(transformationType, transformerPrefix).Observe(elapsed.Seconds())\n\t}\n}","line":{"from":112,"to":120}} {"id":100018804,"name":"RecordCacheMiss","signature":"func RecordCacheMiss()","file":"staging/src/k8s.io/apiserver/pkg/storage/value/metrics.go","code":"// RecordCacheMiss records a miss on Key Encryption Key(KEK) - call to KMS was required to decrypt KEK.\nfunc RecordCacheMiss() {\n\tenvelopeTransformationCacheMissTotal.Inc()\n}","line":{"from":122,"to":125}} {"id":100018805,"name":"RecordDataKeyGeneration","signature":"func RecordDataKeyGeneration(start time.Time, err error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/metrics.go","code":"// RecordDataKeyGeneration records latencies and count of Data Encryption Key generation operations.\nfunc RecordDataKeyGeneration(start time.Time, err error) {\n\tif err != nil {\n\t\tdataKeyGenerationFailuresTotal.Inc()\n\t\treturn\n\t}\n\n\tdataKeyGenerationLatencies.Observe(sinceInSeconds(start))\n}","line":{"from":127,"to":135}} {"id":100018806,"name":"sinceInSeconds","signature":"func sinceInSeconds(start time.Time) float64","file":"staging/src/k8s.io/apiserver/pkg/storage/value/metrics.go","code":"// sinceInSeconds gets the time since the specified start in seconds.\nfunc sinceInSeconds(start time.Time) float64 {\n\treturn time.Since(start).Seconds()\n}","line":{"from":137,"to":140}} {"id":100018807,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/storage/value/transformer.go","code":"func init() {\n\tRegisterMetrics()\n}","line":{"from":29,"to":31}} {"id":100018808,"name":"AuthenticatedData","signature":"func (c DefaultContext) AuthenticatedData() []byte { return c }","file":"staging/src/k8s.io/apiserver/pkg/storage/value/transformer.go","code":"// AuthenticatedData returns itself.\nfunc (c DefaultContext) AuthenticatedData() []byte { return c }","line":{"from":56,"to":57}} {"id":100018809,"name":"NewPrefixTransformers","signature":"func NewPrefixTransformers(err error, transformers ...PrefixTransformer) Transformer","file":"staging/src/k8s.io/apiserver/pkg/storage/value/transformer.go","code":"// NewPrefixTransformers supports the Transformer interface by checking the incoming data against the provided\n// prefixes in order. The first matching prefix will be used to transform the value (the prefix is stripped\n// before the Transformer interface is invoked). The first provided transformer will be used when writing to\n// the store.\nfunc NewPrefixTransformers(err error, transformers ...PrefixTransformer) Transformer {\n\tif err == nil {\n\t\terr = fmt.Errorf(\"the provided value does not match any of the supported transformers\")\n\t}\n\treturn \u0026prefixTransformers{\n\t\ttransformers: transformers,\n\t\terr: err,\n\t}\n}","line":{"from":72,"to":84}} {"id":100018810,"name":"TransformFromStorage","signature":"func (t *prefixTransformers) TransformFromStorage(ctx context.Context, data []byte, dataCtx Context) ([]byte, bool, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/transformer.go","code":"// TransformFromStorage finds the first transformer with a prefix matching the provided data and returns\n// the result of transforming the value. It will always mark any transformation as stale that is not using\n// the first transformer.\nfunc (t *prefixTransformers) TransformFromStorage(ctx context.Context, data []byte, dataCtx Context) ([]byte, bool, error) {\n\tstart := time.Now()\n\tvar errs []error\n\tfor i, transformer := range t.transformers {\n\t\tif bytes.HasPrefix(data, transformer.Prefix) {\n\t\t\tresult, stale, err := transformer.Transformer.TransformFromStorage(ctx, data[len(transformer.Prefix):], dataCtx)\n\t\t\t// To migrate away from encryption, user can specify an identity transformer higher up\n\t\t\t// (in the config file) than the encryption transformer. In that scenario, the identity transformer needs to\n\t\t\t// identify (during reads from disk) whether the data being read is encrypted or not. If the data is encrypted,\n\t\t\t// it shall throw an error, but that error should not prevent the next subsequent transformer from being tried.\n\t\t\tif len(transformer.Prefix) == 0 \u0026\u0026 err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(transformer.Prefix) == 0 {\n\t\t\t\tRecordTransformation(\"from_storage\", \"identity\", time.Since(start), err)\n\t\t\t} else {\n\t\t\t\tRecordTransformation(\"from_storage\", string(transformer.Prefix), time.Since(start), err)\n\t\t\t}\n\n\t\t\t// It is valid to have overlapping prefixes when the same encryption provider\n\t\t\t// is specified multiple times but with different keys (the first provider is\n\t\t\t// being rotated to and some later provider is being rotated away from).\n\t\t\t//\n\t\t\t// Example:\n\t\t\t//\n\t\t\t// {\n\t\t\t// \"aescbc\": {\n\t\t\t// \"keys\": [\n\t\t\t// {\n\t\t\t// \"name\": \"2\",\n\t\t\t// \"secret\": \"some key 2\"\n\t\t\t// }\n\t\t\t// ]\n\t\t\t// }\n\t\t\t// },\n\t\t\t// {\n\t\t\t// \"aescbc\": {\n\t\t\t// \"keys\": [\n\t\t\t// {\n\t\t\t// \"name\": \"1\",\n\t\t\t// \"secret\": \"some key 1\"\n\t\t\t// }\n\t\t\t// ]\n\t\t\t// }\n\t\t\t// },\n\t\t\t//\n\t\t\t// The transformers for both aescbc configs share the prefix k8s:enc:aescbc:v1:\n\t\t\t// but a failure in the first one should not prevent a later match from being attempted.\n\t\t\t// Thus we never short-circuit on a prefix match that results in an error.\n\t\t\tif err != nil {\n\t\t\t\terrs = append(errs, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\treturn result, stale || i != 0, err\n\t\t}\n\t}\n\tif err := errors.Reduce(errors.NewAggregate(errs)); err != nil {\n\t\treturn nil, false, err\n\t}\n\tRecordTransformation(\"from_storage\", \"unknown\", time.Since(start), t.err)\n\treturn nil, false, t.err\n}","line":{"from":86,"to":151}} {"id":100018811,"name":"TransformToStorage","signature":"func (t *prefixTransformers) TransformToStorage(ctx context.Context, data []byte, dataCtx Context) ([]byte, error)","file":"staging/src/k8s.io/apiserver/pkg/storage/value/transformer.go","code":"// TransformToStorage uses the first transformer and adds its prefix to the data.\nfunc (t *prefixTransformers) TransformToStorage(ctx context.Context, data []byte, dataCtx Context) ([]byte, error) {\n\tstart := time.Now()\n\ttransformer := t.transformers[0]\n\tresult, err := transformer.Transformer.TransformToStorage(ctx, data, dataCtx)\n\tRecordTransformation(\"to_storage\", string(transformer.Prefix), time.Since(start), err)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprefixedData := make([]byte, len(transformer.Prefix), len(result)+len(transformer.Prefix))\n\tcopy(prefixedData, transformer.Prefix)\n\tprefixedData = append(prefixedData, result...)\n\treturn prefixedData, nil\n}","line":{"from":153,"to":166}} {"id":100018812,"name":"NewDefaultManager","signature":"func NewDefaultManager() Manager","file":"staging/src/k8s.io/apiserver/pkg/storageversion/manager.go","code":"// NewDefaultManager creates a new defaultManager.\nfunc NewDefaultManager() Manager {\n\ts := \u0026defaultManager{}\n\ts.completed.Store(false)\n\ts.managedResourceInfos = make(map[*ResourceInfo]struct{})\n\ts.managedStatus = make(map[schema.GroupResource]*updateStatus)\n\treturn s\n}","line":{"from":84,"to":91}} {"id":100018813,"name":"AddResourceInfo","signature":"func (s *defaultManager) AddResourceInfo(resources ...*ResourceInfo)","file":"staging/src/k8s.io/apiserver/pkg/storageversion/manager.go","code":"// AddResourceInfo adds ResourceInfo to the manager.\nfunc (s *defaultManager) AddResourceInfo(resources ...*ResourceInfo) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tfor _, r := range resources {\n\t\ts.managedResourceInfos[r] = struct{}{}\n\t\ts.addPendingManagedStatusLocked(r)\n\t}\n}","line":{"from":93,"to":101}} {"id":100018814,"name":"addPendingManagedStatusLocked","signature":"func (s *defaultManager) addPendingManagedStatusLocked(r *ResourceInfo)","file":"staging/src/k8s.io/apiserver/pkg/storageversion/manager.go","code":"func (s *defaultManager) addPendingManagedStatusLocked(r *ResourceInfo) {\n\tgvrs := r.EquivalentResourceMapper.EquivalentResourcesFor(r.GroupResource.WithVersion(\"\"), \"\")\n\tfor _, gvr := range gvrs {\n\t\tgr := gvr.GroupResource()\n\t\tif _, ok := s.managedStatus[gr]; !ok {\n\t\t\ts.managedStatus[gr] = \u0026updateStatus{}\n\t\t}\n\t}\n}","line":{"from":103,"to":111}} {"id":100018815,"name":"UpdateStorageVersions","signature":"func (s *defaultManager) UpdateStorageVersions(kubeAPIServerClientConfig *rest.Config, serverID string)","file":"staging/src/k8s.io/apiserver/pkg/storageversion/manager.go","code":"// UpdateStorageVersions tries to update the StorageVersions of the recorded resources\nfunc (s *defaultManager) UpdateStorageVersions(kubeAPIServerClientConfig *rest.Config, serverID string) {\n\tclientset, err := kubernetes.NewForConfig(kubeAPIServerClientConfig)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"failed to get clientset: %v\", err))\n\t\treturn\n\t}\n\tsc := clientset.InternalV1alpha1().StorageVersions()\n\n\ts.mu.RLock()\n\tresources := []ResourceInfo{}\n\tfor resource := range s.managedResourceInfos {\n\t\tresources = append(resources, *resource)\n\t}\n\ts.mu.RUnlock()\n\thasFailure := false\n\t// Sorting the list to make sure we have a consistent dedup result, and\n\t// therefore avoid creating unnecessarily duplicated StorageVersion objects.\n\t// For example, extensions.ingresses and networking.k8s.io.ingresses share\n\t// the same underlying storage. Without sorting, in an HA cluster, one\n\t// apiserver may dedup and update StorageVersion for extensions.ingresses,\n\t// while another apiserver may dedup and update StorageVersion for\n\t// networking.k8s.io.ingresses. The storage migrator (which migrates objects\n\t// per GroupResource) will migrate these resources twice, since both\n\t// StorageVersion objects have CommonEncodingVersion (each with one server registered).\n\tsortResourceInfosByGroupResource(resources)\n\tfor _, r := range dedupResourceInfos(resources) {\n\t\tdecodableVersions := decodableVersions(r.DirectlyDecodableVersions, r.EquivalentResourceMapper, r.GroupResource)\n\t\tgr := r.GroupResource\n\t\t// Group must be a valid subdomain in DNS (RFC 1123)\n\t\tif len(gr.Group) == 0 {\n\t\t\tgr.Group = \"core\"\n\t\t}\n\t\tif err := updateStorageVersionFor(sc, serverID, gr, r.EncodingVersion, decodableVersions); err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"failed to update storage version for %v: %v\", r.GroupResource, err))\n\t\t\ts.recordStatusFailure(\u0026r, err)\n\t\t\thasFailure = true\n\t\t\tcontinue\n\t\t}\n\t\tklog.V(2).Infof(\"successfully updated storage version for %v\", r.GroupResource)\n\t\ts.recordStatusSuccess(\u0026r)\n\t}\n\tif hasFailure {\n\t\treturn\n\t}\n\tklog.V(2).Infof(\"storage version updates complete\")\n\ts.setComplete()\n}","line":{"from":113,"to":160}} {"id":100018816,"name":"dedupResourceInfos","signature":"func dedupResourceInfos(infos []ResourceInfo) []ResourceInfo","file":"staging/src/k8s.io/apiserver/pkg/storageversion/manager.go","code":"// dedupResourceInfos dedups ResourceInfos with the same underlying storage.\n// ResourceInfos from the same Group with different Versions share the same underlying storage.\n// ResourceInfos from different Groups may share the same underlying storage, e.g.\n// networking.k8s.io ingresses and extensions ingresses. The StorageVersion manager\n// only needs to update one StorageVersion for the equivalent Groups.\nfunc dedupResourceInfos(infos []ResourceInfo) []ResourceInfo {\n\tvar ret []ResourceInfo\n\tseen := make(map[schema.GroupResource]struct{})\n\tfor _, info := range infos {\n\t\tgr := info.GroupResource\n\t\tif _, ok := seen[gr]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tgvrs := info.EquivalentResourceMapper.EquivalentResourcesFor(gr.WithVersion(\"\"), \"\")\n\t\tfor _, gvr := range gvrs {\n\t\t\tseen[gvr.GroupResource()] = struct{}{}\n\t\t}\n\t\tret = append(ret, info)\n\t}\n\treturn ret\n}","line":{"from":162,"to":182}} {"id":100018817,"name":"sortResourceInfosByGroupResource","signature":"func sortResourceInfosByGroupResource(infos []ResourceInfo)","file":"staging/src/k8s.io/apiserver/pkg/storageversion/manager.go","code":"func sortResourceInfosByGroupResource(infos []ResourceInfo) {\n\tsort.Sort(byGroupResource(infos))\n}","line":{"from":184,"to":186}} {"id":100018818,"name":"Len","signature":"func (s byGroupResource) Len() int { return len(s) }","file":"staging/src/k8s.io/apiserver/pkg/storageversion/manager.go","code":"func (s byGroupResource) Len() int { return len(s) }","line":{"from":190,"to":190}} {"id":100018819,"name":"Less","signature":"func (s byGroupResource) Less(i, j int) bool","file":"staging/src/k8s.io/apiserver/pkg/storageversion/manager.go","code":"func (s byGroupResource) Less(i, j int) bool {\n\tif s[i].GroupResource.Group == s[j].GroupResource.Group {\n\t\treturn s[i].GroupResource.Resource \u003c s[j].GroupResource.Resource\n\t}\n\treturn s[i].GroupResource.Group \u003c s[j].GroupResource.Group\n}","line":{"from":192,"to":197}} {"id":100018820,"name":"Swap","signature":"func (s byGroupResource) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","file":"staging/src/k8s.io/apiserver/pkg/storageversion/manager.go","code":"func (s byGroupResource) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","line":{"from":199,"to":199}} {"id":100018821,"name":"recordStatusSuccess","signature":"func (s *defaultManager) recordStatusSuccess(r *ResourceInfo)","file":"staging/src/k8s.io/apiserver/pkg/storageversion/manager.go","code":"// recordStatusSuccess marks updated ResourceInfo as completed.\nfunc (s *defaultManager) recordStatusSuccess(r *ResourceInfo) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\ts.recordStatusSuccessLocked(r)\n}","line":{"from":201,"to":206}} {"id":100018822,"name":"recordStatusSuccessLocked","signature":"func (s *defaultManager) recordStatusSuccessLocked(r *ResourceInfo)","file":"staging/src/k8s.io/apiserver/pkg/storageversion/manager.go","code":"func (s *defaultManager) recordStatusSuccessLocked(r *ResourceInfo) {\n\tgvrs := r.EquivalentResourceMapper.EquivalentResourcesFor(r.GroupResource.WithVersion(\"\"), \"\")\n\tfor _, gvr := range gvrs {\n\t\ts.recordSuccessGroupResourceLocked(gvr.GroupResource())\n\t}\n}","line":{"from":208,"to":213}} {"id":100018823,"name":"recordSuccessGroupResourceLocked","signature":"func (s *defaultManager) recordSuccessGroupResourceLocked(gr schema.GroupResource)","file":"staging/src/k8s.io/apiserver/pkg/storageversion/manager.go","code":"func (s *defaultManager) recordSuccessGroupResourceLocked(gr schema.GroupResource) {\n\tif _, ok := s.managedStatus[gr]; !ok {\n\t\treturn\n\t}\n\ts.managedStatus[gr].done = true\n\ts.managedStatus[gr].lastErr = nil\n}","line":{"from":215,"to":221}} {"id":100018824,"name":"recordStatusFailure","signature":"func (s *defaultManager) recordStatusFailure(r *ResourceInfo, err error)","file":"staging/src/k8s.io/apiserver/pkg/storageversion/manager.go","code":"// recordStatusFailure records latest error updating ResourceInfo.\nfunc (s *defaultManager) recordStatusFailure(r *ResourceInfo, err error) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\ts.recordStatusFailureLocked(r, err)\n}","line":{"from":223,"to":228}} {"id":100018825,"name":"recordStatusFailureLocked","signature":"func (s *defaultManager) recordStatusFailureLocked(r *ResourceInfo, err error)","file":"staging/src/k8s.io/apiserver/pkg/storageversion/manager.go","code":"func (s *defaultManager) recordStatusFailureLocked(r *ResourceInfo, err error) {\n\tgvrs := r.EquivalentResourceMapper.EquivalentResourcesFor(r.GroupResource.WithVersion(\"\"), \"\")\n\tfor _, gvr := range gvrs {\n\t\ts.recordErrorGroupResourceLocked(gvr.GroupResource(), err)\n\t}\n}","line":{"from":230,"to":235}} {"id":100018826,"name":"recordErrorGroupResourceLocked","signature":"func (s *defaultManager) recordErrorGroupResourceLocked(gr schema.GroupResource, err error)","file":"staging/src/k8s.io/apiserver/pkg/storageversion/manager.go","code":"func (s *defaultManager) recordErrorGroupResourceLocked(gr schema.GroupResource, err error) {\n\tif _, ok := s.managedStatus[gr]; !ok {\n\t\treturn\n\t}\n\ts.managedStatus[gr].lastErr = err\n}","line":{"from":237,"to":242}} {"id":100018827,"name":"PendingUpdate","signature":"func (s *defaultManager) PendingUpdate(gr schema.GroupResource) bool","file":"staging/src/k8s.io/apiserver/pkg/storageversion/manager.go","code":"// PendingUpdate returns if the StorageVersion of a resource is still wait to be updated.\nfunc (s *defaultManager) PendingUpdate(gr schema.GroupResource) bool {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\tif _, ok := s.managedStatus[gr]; !ok {\n\t\treturn false\n\t}\n\treturn !s.managedStatus[gr].done\n}","line":{"from":244,"to":252}} {"id":100018828,"name":"LastUpdateError","signature":"func (s *defaultManager) LastUpdateError(gr schema.GroupResource) error","file":"staging/src/k8s.io/apiserver/pkg/storageversion/manager.go","code":"// LastUpdateError returns the last error hit when updating the storage version of the given resource.\nfunc (s *defaultManager) LastUpdateError(gr schema.GroupResource) error {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\tif _, ok := s.managedStatus[gr]; !ok {\n\t\treturn fmt.Errorf(\"couldn't find managed status for %v\", gr)\n\t}\n\treturn s.managedStatus[gr].lastErr\n}","line":{"from":254,"to":262}} {"id":100018829,"name":"setComplete","signature":"func (s *defaultManager) setComplete()","file":"staging/src/k8s.io/apiserver/pkg/storageversion/manager.go","code":"// setComplete marks the completion of updating StorageVersions. No write requests need to be blocked anymore.\nfunc (s *defaultManager) setComplete() {\n\ts.completed.Store(true)\n}","line":{"from":264,"to":267}} {"id":100018830,"name":"Completed","signature":"func (s *defaultManager) Completed() bool","file":"staging/src/k8s.io/apiserver/pkg/storageversion/manager.go","code":"// Completed returns if updating StorageVersions has completed.\nfunc (s *defaultManager) Completed() bool {\n\treturn s.completed.Load()\n}","line":{"from":269,"to":272}} {"id":100018831,"name":"decodableVersions","signature":"func decodableVersions(directlyDecodableVersions []schema.GroupVersion, e runtime.EquivalentResourceRegistry, gr schema.GroupResource) []string","file":"staging/src/k8s.io/apiserver/pkg/storageversion/manager.go","code":"func decodableVersions(directlyDecodableVersions []schema.GroupVersion, e runtime.EquivalentResourceRegistry, gr schema.GroupResource) []string {\n\tvar versions []string\n\tfor _, decodableVersions := range directlyDecodableVersions {\n\t\tversions = append(versions, decodableVersions.String())\n\t}\n\n\tdecodingGVRs := e.EquivalentResourcesFor(gr.WithVersion(\"\"), \"\")\n\tfor _, v := range decodingGVRs {\n\t\tfound := false\n\t\tfor _, existingVersion := range versions {\n\t\t\tif existingVersion == v.GroupVersion().String() {\n\t\t\t\tfound = true\n\t\t\t}\n\t\t}\n\t\tif found {\n\t\t\tcontinue\n\t\t}\n\t\tversions = append(versions, v.GroupVersion().String())\n\t}\n\treturn versions\n}","line":{"from":274,"to":294}} {"id":100018832,"name":"SetCommonEncodingVersion","signature":"func SetCommonEncodingVersion(sv *v1alpha1.StorageVersion)","file":"staging/src/k8s.io/apiserver/pkg/storageversion/updater.go","code":"// SetCommonEncodingVersion updates the CommonEncodingVersion and the AllEncodingVersionsEqual\n// condition based on the StorageVersions.\nfunc SetCommonEncodingVersion(sv *v1alpha1.StorageVersion) {\n\tvar oldCommonEncodingVersion *string\n\tif sv.Status.CommonEncodingVersion != nil {\n\t\tversion := *sv.Status.CommonEncodingVersion\n\t\toldCommonEncodingVersion = \u0026version\n\t}\n\tsv.Status.CommonEncodingVersion = nil\n\tif len(sv.Status.StorageVersions) != 0 {\n\t\tfirstVersion := sv.Status.StorageVersions[0].EncodingVersion\n\t\tagreed := true\n\t\tfor _, ssv := range sv.Status.StorageVersions {\n\t\t\tif ssv.EncodingVersion != firstVersion {\n\t\t\t\tagreed = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif agreed {\n\t\t\tsv.Status.CommonEncodingVersion = \u0026firstVersion\n\t\t}\n\t}\n\n\tcondition := v1alpha1.StorageVersionCondition{\n\t\tType: v1alpha1.AllEncodingVersionsEqual,\n\t\tStatus: v1alpha1.ConditionFalse,\n\t\tObservedGeneration: sv.Generation,\n\t\tLastTransitionTime: metav1.NewTime(time.Now()),\n\t\tReason: \"CommonEncodingVersionUnset\",\n\t\tMessage: \"Common encoding version unset\",\n\t}\n\tif sv.Status.CommonEncodingVersion != nil {\n\t\tcondition.Status = v1alpha1.ConditionTrue\n\t\tcondition.Reason = \"CommonEncodingVersionSet\"\n\t\tcondition.Message = \"Common encoding version set\"\n\t}\n\tforceTransition := false\n\tif oldCommonEncodingVersion != nil \u0026\u0026 sv.Status.CommonEncodingVersion != nil \u0026\u0026\n\t\t*oldCommonEncodingVersion != *sv.Status.CommonEncodingVersion {\n\t\tforceTransition = true\n\t}\n\tsetStatusCondition(\u0026sv.Status.Conditions, condition, forceTransition)\n}","line":{"from":38,"to":80}} {"id":100018833,"name":"findStatusCondition","signature":"func findStatusCondition(conditions []v1alpha1.StorageVersionCondition,","file":"staging/src/k8s.io/apiserver/pkg/storageversion/updater.go","code":"func findStatusCondition(conditions []v1alpha1.StorageVersionCondition,\n\tconditionType v1alpha1.StorageVersionConditionType) *v1alpha1.StorageVersionCondition {\n\tfor i := range conditions {\n\t\tif conditions[i].Type == conditionType {\n\t\t\treturn \u0026conditions[i]\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":82,"to":90}} {"id":100018834,"name":"setStatusCondition","signature":"func setStatusCondition(conditions *[]v1alpha1.StorageVersionCondition, newCondition v1alpha1.StorageVersionCondition,","file":"staging/src/k8s.io/apiserver/pkg/storageversion/updater.go","code":"// setStatusCondition sets the corresponding condition in conditions to newCondition.\n// conditions must be non-nil.\n// 1. if the condition of the specified type already exists: all fields of the existing condition are updated to\n// newCondition, LastTransitionTime is set to now if the new status differs from the old status\n// 2. if a condition of the specified type does not exist: LastTransitionTime is set to now() if unset,\n// and newCondition is appended\n//\n// NOTE: forceTransition allows overwriting LastTransitionTime even when the status doesn't change.\nfunc setStatusCondition(conditions *[]v1alpha1.StorageVersionCondition, newCondition v1alpha1.StorageVersionCondition,\n\tforceTransition bool) {\n\tif conditions == nil {\n\t\treturn\n\t}\n\n\tif newCondition.LastTransitionTime.IsZero() {\n\t\tnewCondition.LastTransitionTime = metav1.NewTime(time.Now())\n\t}\n\texistingCondition := findStatusCondition(*conditions, newCondition.Type)\n\tif existingCondition == nil {\n\t\t*conditions = append(*conditions, newCondition)\n\t\treturn\n\t}\n\n\tstatusChanged := existingCondition.Status != newCondition.Status\n\tif statusChanged || forceTransition {\n\t\texistingCondition.LastTransitionTime = newCondition.LastTransitionTime\n\t}\n\texistingCondition.Status = newCondition.Status\n\texistingCondition.Reason = newCondition.Reason\n\texistingCondition.Message = newCondition.Message\n\texistingCondition.ObservedGeneration = newCondition.ObservedGeneration\n}","line":{"from":92,"to":123}} {"id":100018835,"name":"updateStorageVersionFor","signature":"func updateStorageVersionFor(c Client, apiserverID string, gr schema.GroupResource, encodingVersion string, decodableVersions []string) error","file":"staging/src/k8s.io/apiserver/pkg/storageversion/updater.go","code":"// updateStorageVersionFor updates the storage version object for the resource.\nfunc updateStorageVersionFor(c Client, apiserverID string, gr schema.GroupResource, encodingVersion string, decodableVersions []string) error {\n\tretries := 3\n\tvar retry int\n\tvar err error\n\tfor retry \u003c retries {\n\t\terr = singleUpdate(c, apiserverID, gr, encodingVersion, decodableVersions)\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\t\tif apierrors.IsAlreadyExists(err) || apierrors.IsConflict(err) {\n\t\t\ttime.Sleep(1 * time.Second)\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"retry %d, failed to update storage version for %v: %v\", retry, gr, err)\n\t\t\tretry++\n\t\t\ttime.Sleep(1 * time.Second)\n\t\t}\n\t}\n\treturn err\n}","line":{"from":125,"to":146}} {"id":100018836,"name":"singleUpdate","signature":"func singleUpdate(c Client, apiserverID string, gr schema.GroupResource, encodingVersion string, decodableVersions []string) error","file":"staging/src/k8s.io/apiserver/pkg/storageversion/updater.go","code":"func singleUpdate(c Client, apiserverID string, gr schema.GroupResource, encodingVersion string, decodableVersions []string) error {\n\tshouldCreate := false\n\tname := fmt.Sprintf(\"%s.%s\", gr.Group, gr.Resource)\n\tsv, err := c.Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil \u0026\u0026 !apierrors.IsNotFound(err) {\n\t\treturn err\n\t}\n\tif apierrors.IsNotFound(err) {\n\t\tshouldCreate = true\n\t\tsv = \u0026v1alpha1.StorageVersion{}\n\t\tsv.ObjectMeta.Name = name\n\t}\n\tupdatedSV := localUpdateStorageVersion(sv, apiserverID, encodingVersion, decodableVersions)\n\tif shouldCreate {\n\t\tcreatedSV, err := c.Create(context.TODO(), updatedSV, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// assign the calculated status to the object just created, then update status\n\t\tcreatedSV.Status = updatedSV.Status\n\t\t_, err = c.UpdateStatus(context.TODO(), createdSV, metav1.UpdateOptions{})\n\t\treturn err\n\t}\n\t_, err = c.UpdateStatus(context.TODO(), updatedSV, metav1.UpdateOptions{})\n\treturn err\n}","line":{"from":148,"to":173}} {"id":100018837,"name":"localUpdateStorageVersion","signature":"func localUpdateStorageVersion(sv *v1alpha1.StorageVersion, apiserverID, encodingVersion string, decodableVersions []string) *v1alpha1.StorageVersion","file":"staging/src/k8s.io/apiserver/pkg/storageversion/updater.go","code":"// localUpdateStorageVersion updates the input storageversion with given server storageversion info.\n// The function updates the input storageversion in place.\nfunc localUpdateStorageVersion(sv *v1alpha1.StorageVersion, apiserverID, encodingVersion string, decodableVersions []string) *v1alpha1.StorageVersion {\n\tnewSSV := v1alpha1.ServerStorageVersion{\n\t\tAPIServerID: apiserverID,\n\t\tEncodingVersion: encodingVersion,\n\t\tDecodableVersions: decodableVersions,\n\t}\n\tfoundSSV := false\n\tfor i, ssv := range sv.Status.StorageVersions {\n\t\tif ssv.APIServerID == apiserverID {\n\t\t\tsv.Status.StorageVersions[i] = newSSV\n\t\t\tfoundSSV = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !foundSSV {\n\t\tsv.Status.StorageVersions = append(sv.Status.StorageVersions, newSSV)\n\t}\n\tSetCommonEncodingVersion(sv)\n\treturn sv\n}","line":{"from":175,"to":196}} {"id":100018838,"name":"SetFlowSchemaCondition","signature":"func SetFlowSchemaCondition(flowSchema *flowcontrol.FlowSchema, newCondition flowcontrol.FlowSchemaCondition)","file":"staging/src/k8s.io/apiserver/pkg/util/apihelpers/helpers.go","code":"// SetFlowSchemaCondition sets conditions.\nfunc SetFlowSchemaCondition(flowSchema *flowcontrol.FlowSchema, newCondition flowcontrol.FlowSchemaCondition) {\n\texistingCondition := GetFlowSchemaConditionByType(flowSchema, newCondition.Type)\n\tif existingCondition == nil {\n\t\tflowSchema.Status.Conditions = append(flowSchema.Status.Conditions, newCondition)\n\t\treturn\n\t}\n\n\tif existingCondition.Status != newCondition.Status {\n\t\texistingCondition.Status = newCondition.Status\n\t\texistingCondition.LastTransitionTime = newCondition.LastTransitionTime\n\t}\n\n\texistingCondition.Reason = newCondition.Reason\n\texistingCondition.Message = newCondition.Message\n}","line":{"from":25,"to":40}} {"id":100018839,"name":"GetFlowSchemaConditionByType","signature":"func GetFlowSchemaConditionByType(flowSchema *flowcontrol.FlowSchema, conditionType flowcontrol.FlowSchemaConditionType) *flowcontrol.FlowSchemaCondition","file":"staging/src/k8s.io/apiserver/pkg/util/apihelpers/helpers.go","code":"// GetFlowSchemaConditionByType gets conditions.\nfunc GetFlowSchemaConditionByType(flowSchema *flowcontrol.FlowSchema, conditionType flowcontrol.FlowSchemaConditionType) *flowcontrol.FlowSchemaCondition {\n\tfor i := range flowSchema.Status.Conditions {\n\t\tif flowSchema.Status.Conditions[i].Type == conditionType {\n\t\t\treturn \u0026flowSchema.Status.Conditions[i]\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":42,"to":50}} {"id":100018840,"name":"SetPriorityLevelConfigurationCondition","signature":"func SetPriorityLevelConfigurationCondition(priorityLevel *flowcontrol.PriorityLevelConfiguration, newCondition flowcontrol.PriorityLevelConfigurationCondition)","file":"staging/src/k8s.io/apiserver/pkg/util/apihelpers/helpers.go","code":"// SetPriorityLevelConfigurationCondition sets conditions.\nfunc SetPriorityLevelConfigurationCondition(priorityLevel *flowcontrol.PriorityLevelConfiguration, newCondition flowcontrol.PriorityLevelConfigurationCondition) {\n\texistingCondition := GetPriorityLevelConfigurationConditionByType(priorityLevel, newCondition.Type)\n\tif existingCondition == nil {\n\t\tpriorityLevel.Status.Conditions = append(priorityLevel.Status.Conditions, newCondition)\n\t\treturn\n\t}\n\n\tif existingCondition.Status != newCondition.Status {\n\t\texistingCondition.Status = newCondition.Status\n\t\texistingCondition.LastTransitionTime = newCondition.LastTransitionTime\n\t}\n\n\texistingCondition.Reason = newCondition.Reason\n\texistingCondition.Message = newCondition.Message\n}","line":{"from":52,"to":67}} {"id":100018841,"name":"GetPriorityLevelConfigurationConditionByType","signature":"func GetPriorityLevelConfigurationConditionByType(priorityLevel *flowcontrol.PriorityLevelConfiguration, conditionType flowcontrol.PriorityLevelConfigurationConditionType) *flowcontrol.PriorityLevelConfigurationCondition","file":"staging/src/k8s.io/apiserver/pkg/util/apihelpers/helpers.go","code":"// GetPriorityLevelConfigurationConditionByType gets conditions.\nfunc GetPriorityLevelConfigurationConditionByType(priorityLevel *flowcontrol.PriorityLevelConfiguration, conditionType flowcontrol.PriorityLevelConfigurationConditionType) *flowcontrol.PriorityLevelConfigurationCondition {\n\tfor i := range priorityLevel.Status.Conditions {\n\t\tif priorityLevel.Status.Conditions[i].Type == conditionType {\n\t\t\treturn \u0026priorityLevel.Status.Conditions[i]\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":69,"to":77}} {"id":100018842,"name":"Len","signature":"func (s FlowSchemaSequence) Len() int","file":"staging/src/k8s.io/apiserver/pkg/util/apihelpers/helpers.go","code":"func (s FlowSchemaSequence) Len() int {\n\treturn len(s)\n}","line":{"from":85,"to":87}} {"id":100018843,"name":"Less","signature":"func (s FlowSchemaSequence) Less(i, j int) bool","file":"staging/src/k8s.io/apiserver/pkg/util/apihelpers/helpers.go","code":"func (s FlowSchemaSequence) Less(i, j int) bool {\n\t// the flow-schema w/ lower matching-precedence is prior\n\tif ip, jp := s[i].Spec.MatchingPrecedence, s[j].Spec.MatchingPrecedence; ip != jp {\n\t\treturn ip \u003c jp\n\t}\n\t// sort alphabetically\n\treturn s[i].Name \u003c s[j].Name\n}","line":{"from":89,"to":96}} {"id":100018844,"name":"Swap","signature":"func (s FlowSchemaSequence) Swap(i, j int)","file":"staging/src/k8s.io/apiserver/pkg/util/apihelpers/helpers.go","code":"func (s FlowSchemaSequence) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}","line":{"from":98,"to":100}} {"id":100018845,"name":"IsDryRun","signature":"func IsDryRun(flag []string) bool","file":"staging/src/k8s.io/apiserver/pkg/util/dryrun/dryrun.go","code":"// IsDryRun returns true if the DryRun flag is an actual dry-run.\nfunc IsDryRun(flag []string) bool {\n\treturn len(flag) \u003e 0\n}","line":{"from":19,"to":22}} {"id":100018846,"name":"WithInitializationSignal","signature":"func WithInitializationSignal(ctx context.Context, signal InitializationSignal) context.Context","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_context.go","code":"// WithInitializationSignal creates a copy of parent context with\n// priority and fairness initialization signal value.\nfunc WithInitializationSignal(ctx context.Context, signal InitializationSignal) context.Context {\n\treturn context.WithValue(ctx, priorityAndFairnessInitializationSignalKey, signal)\n}","line":{"from":33,"to":37}} {"id":100018847,"name":"initializationSignalFrom","signature":"func initializationSignalFrom(ctx context.Context) (InitializationSignal, bool)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_context.go","code":"// initializationSignalFrom returns an initialization signal function\n// which when called signals that watch initialization has already finished\n// to priority and fairness dispatcher.\nfunc initializationSignalFrom(ctx context.Context) (InitializationSignal, bool) {\n\tsignal, ok := ctx.Value(priorityAndFairnessInitializationSignalKey).(InitializationSignal)\n\treturn signal, ok \u0026\u0026 signal != nil\n}","line":{"from":39,"to":45}} {"id":100018848,"name":"WatchInitialized","signature":"func WatchInitialized(ctx context.Context)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_context.go","code":"// WatchInitialized sends a signal to priority and fairness dispatcher\n// that a given watch request has already been initialized.\nfunc WatchInitialized(ctx context.Context) {\n\tif signal, ok := initializationSignalFrom(ctx); ok {\n\t\tsignal.Signal()\n\t}\n}","line":{"from":47,"to":53}} {"id":100018849,"name":"RequestDelegated","signature":"func RequestDelegated(ctx context.Context)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_context.go","code":"// RequestDelegated informs the priority and fairness dispatcher that\n// a given request has been delegated to an aggregated API\n// server. No-op when priority and fairness is disabled.\nfunc RequestDelegated(ctx context.Context) {\n\t// The watch initialization signal doesn't traverse request\n\t// boundaries, so we generously fire it as soon as we know\n\t// that the request won't be serviced locally. Safe to call\n\t// for non-watch requests.\n\tWatchInitialized(ctx)\n}","line":{"from":55,"to":64}} {"id":100018850,"name":"NewInitializationSignal","signature":"func NewInitializationSignal() InitializationSignal","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_context.go","code":"func NewInitializationSignal() InitializationSignal {\n\treturn \u0026initializationSignal{\n\t\tonce: sync.Once{},\n\t\tdone: make(chan struct{}),\n\t}\n}","line":{"from":80,"to":85}} {"id":100018851,"name":"Signal","signature":"func (i *initializationSignal) Signal()","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_context.go","code":"func (i *initializationSignal) Signal() {\n\ti.once.Do(func() { close(i.done) })\n}","line":{"from":87,"to":89}} {"id":100018852,"name":"Wait","signature":"func (i *initializationSignal) Wait()","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_context.go","code":"func (i *initializationSignal) Wait() {\n\t\u003c-i.done\n}","line":{"from":91,"to":93}} {"id":100018853,"name":"update","signature":"func (stats *seatDemandStats) update(obs fq.IntegratorResults)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"func (stats *seatDemandStats) update(obs fq.IntegratorResults) {\n\tstats.avg = obs.Average\n\tstats.stdDev = obs.Deviation\n\tstats.highWatermark = obs.Max\n\tenvelope := obs.Average + obs.Deviation\n\tstats.smoothed = math.Max(envelope, seatDemandSmoothingCoefficient*stats.smoothed+(1-seatDemandSmoothingCoefficient)*envelope)\n}","line":{"from":255,"to":261}} {"id":100018854,"name":"newTestableController","signature":"func newTestableController(config TestableConfig) *configController","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"// NewTestableController is extra flexible to facilitate testing\nfunc newTestableController(config TestableConfig) *configController {\n\tcfgCtlr := \u0026configController{\n\t\tname: config.Name,\n\t\tclock: config.Clock,\n\t\tqueueSetFactory: config.QueueSetFactory,\n\t\treqsGaugeVec: config.ReqsGaugeVec,\n\t\texecSeatsGaugeVec: config.ExecSeatsGaugeVec,\n\t\tasFieldManager: config.AsFieldManager,\n\t\tfoundToDangling: config.FoundToDangling,\n\t\tserverConcurrencyLimit: config.ServerConcurrencyLimit,\n\t\trequestWaitLimit: config.RequestWaitLimit,\n\t\tflowcontrolClient: config.FlowcontrolClient,\n\t\tpriorityLevelStates: make(map[string]*priorityLevelState),\n\t\tWatchTracker: NewWatchTracker(),\n\t}\n\tklog.V(2).Infof(\"NewTestableController %q with serverConcurrencyLimit=%d, requestWaitLimit=%s, name=%s, asFieldManager=%q\", cfgCtlr.name, cfgCtlr.serverConcurrencyLimit, cfgCtlr.requestWaitLimit, cfgCtlr.name, cfgCtlr.asFieldManager)\n\t// Start with longish delay because conflicts will be between\n\t// different processes, so take some time to go away.\n\tcfgCtlr.configQueue = workqueue.NewNamedRateLimitingQueue(workqueue.NewItemExponentialFailureRateLimiter(200*time.Millisecond, 8*time.Hour), \"priority_and_fairness_config_queue\")\n\t// ensure the data structure reflects the mandatory config\n\tcfgCtlr.lockAndDigestConfigObjects(nil, nil)\n\tfci := config.InformerFactory.Flowcontrol().V1beta3()\n\tpli := fci.PriorityLevelConfigurations()\n\tfsi := fci.FlowSchemas()\n\tcfgCtlr.plLister = pli.Lister()\n\tcfgCtlr.plInformerSynced = pli.Informer().HasSynced\n\tcfgCtlr.fsLister = fsi.Lister()\n\tcfgCtlr.fsInformerSynced = fsi.Informer().HasSynced\n\tpli.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tpl := obj.(*flowcontrol.PriorityLevelConfiguration)\n\t\t\tklog.V(7).Infof(\"Triggered API priority and fairness config reloading in %s due to creation of PLC %s\", cfgCtlr.name, pl.Name)\n\t\t\tcfgCtlr.configQueue.Add(0)\n\t\t},\n\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\tnewPL := newObj.(*flowcontrol.PriorityLevelConfiguration)\n\t\t\toldPL := oldObj.(*flowcontrol.PriorityLevelConfiguration)\n\t\t\tif !apiequality.Semantic.DeepEqual(oldPL.Spec, newPL.Spec) {\n\t\t\t\tklog.V(7).Infof(\"Triggered API priority and fairness config reloading in %s due to spec update of PLC %s\", cfgCtlr.name, newPL.Name)\n\t\t\t\tcfgCtlr.configQueue.Add(0)\n\t\t\t} else {\n\t\t\t\tklog.V(7).Infof(\"No trigger API priority and fairness config reloading in %s due to spec non-change of PLC %s\", cfgCtlr.name, newPL.Name)\n\t\t\t}\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tname, _ := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)\n\t\t\tklog.V(7).Infof(\"Triggered API priority and fairness config reloading in %s due to deletion of PLC %s\", cfgCtlr.name, name)\n\t\t\tcfgCtlr.configQueue.Add(0)\n\n\t\t}})\n\tfsi.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tfs := obj.(*flowcontrol.FlowSchema)\n\t\t\tklog.V(7).Infof(\"Triggered API priority and fairness config reloading in %s due to creation of FS %s\", cfgCtlr.name, fs.Name)\n\t\t\tcfgCtlr.configQueue.Add(0)\n\t\t},\n\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\tnewFS := newObj.(*flowcontrol.FlowSchema)\n\t\t\toldFS := oldObj.(*flowcontrol.FlowSchema)\n\t\t\t// Changes to either Spec or Status are relevant. The\n\t\t\t// concern is that we might, in some future release, want\n\t\t\t// different behavior than is implemented now. One of the\n\t\t\t// hardest questions is how does an operator roll out the\n\t\t\t// new release in a cluster with multiple kube-apiservers\n\t\t\t// --- in a way that works no matter what servers crash\n\t\t\t// and restart when. If this handler reacts only to\n\t\t\t// changes in Spec then we have a scenario in which the\n\t\t\t// rollout leaves the old Status in place. The scenario\n\t\t\t// ends with this subsequence: deploy the last new server\n\t\t\t// before deleting the last old server, and in between\n\t\t\t// those two operations the last old server crashes and\n\t\t\t// recovers. The chosen solution is making this controller\n\t\t\t// insist on maintaining the particular state that it\n\t\t\t// establishes.\n\t\t\tif !(apiequality.Semantic.DeepEqual(oldFS.Spec, newFS.Spec) \u0026\u0026\n\t\t\t\tapiequality.Semantic.DeepEqual(oldFS.Status, newFS.Status)) {\n\t\t\t\tklog.V(7).Infof(\"Triggered API priority and fairness config reloading in %s due to spec and/or status update of FS %s\", cfgCtlr.name, newFS.Name)\n\t\t\t\tcfgCtlr.configQueue.Add(0)\n\t\t\t} else {\n\t\t\t\tklog.V(7).Infof(\"No trigger of API priority and fairness config reloading in %s due to spec and status non-change of FS %s\", cfgCtlr.name, newFS.Name)\n\t\t\t}\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tname, _ := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)\n\t\t\tklog.V(7).Infof(\"Triggered API priority and fairness config reloading in %s due to deletion of FS %s\", cfgCtlr.name, name)\n\t\t\tcfgCtlr.configQueue.Add(0)\n\n\t\t}})\n\treturn cfgCtlr\n}","line":{"from":263,"to":353}} {"id":100018855,"name":"Run","signature":"func (cfgCtlr *configController) Run(stopCh \u003c-chan struct{}) error","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"func (cfgCtlr *configController) Run(stopCh \u003c-chan struct{}) error {\n\tdefer utilruntime.HandleCrash()\n\n\t// Let the config worker stop when we are done\n\tdefer cfgCtlr.configQueue.ShutDown()\n\n\tklog.Info(\"Starting API Priority and Fairness config controller\")\n\tif ok := cache.WaitForCacheSync(stopCh, cfgCtlr.plInformerSynced, cfgCtlr.fsInformerSynced); !ok {\n\t\treturn fmt.Errorf(\"Never achieved initial sync\")\n\t}\n\n\tklog.Info(\"Running API Priority and Fairness config worker\")\n\tgo wait.Until(cfgCtlr.runWorker, time.Second, stopCh)\n\n\tklog.Info(\"Running API Priority and Fairness periodic rebalancing process\")\n\tgo wait.Until(cfgCtlr.updateBorrowing, borrowingAdjustmentPeriod, stopCh)\n\n\t\u003c-stopCh\n\tklog.Info(\"Shutting down API Priority and Fairness config worker\")\n\treturn nil\n}","line":{"from":355,"to":375}} {"id":100018856,"name":"updateBorrowing","signature":"func (cfgCtlr *configController) updateBorrowing()","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"func (cfgCtlr *configController) updateBorrowing() {\n\tcfgCtlr.lock.Lock()\n\tdefer cfgCtlr.lock.Unlock()\n\tcfgCtlr.updateBorrowingLocked(true, cfgCtlr.priorityLevelStates)\n}","line":{"from":377,"to":381}} {"id":100018857,"name":"updateBorrowingLocked","signature":"func (cfgCtlr *configController) updateBorrowingLocked(setCompleters bool, plStates map[string]*priorityLevelState)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"func (cfgCtlr *configController) updateBorrowingLocked(setCompleters bool, plStates map[string]*priorityLevelState) {\n\titems := make([]allocProblemItem, 0, len(plStates))\n\tplNames := make([]string, 0, len(plStates))\n\tfor plName, plState := range plStates {\n\t\tif plState.pl.Spec.Limited == nil {\n\t\t\tcontinue\n\t\t}\n\t\tobs := plState.seatDemandIntegrator.Reset()\n\t\tplState.seatDemandStats.update(obs)\n\t\t// Lower bound on this priority level's adjusted concurreny limit is the lesser of:\n\t\t// - its seat demamd high watermark over the last adjustment period, and\n\t\t// - its configured concurrency limit.\n\t\t// BUT: we do not want this to be lower than the lower bound from configuration.\n\t\t// See KEP-1040 for a more detailed explanation.\n\t\tminCurrentCL := math.Max(float64(plState.minCL), math.Min(float64(plState.nominalCL), plState.seatDemandStats.highWatermark))\n\t\tplNames = append(plNames, plName)\n\t\titems = append(items, allocProblemItem{\n\t\t\tlowerBound: minCurrentCL,\n\t\t\tupperBound: float64(plState.maxCL),\n\t\t\ttarget: math.Max(minCurrentCL, plState.seatDemandStats.smoothed),\n\t\t})\n\t}\n\tif len(items) == 0 \u0026\u0026 cfgCtlr.nominalCLSum \u003e 0 {\n\t\tklog.ErrorS(nil, \"Impossible: no non-exempt priority levels\", \"plStates\", cfgCtlr.priorityLevelStates)\n\t\treturn\n\t}\n\tallocs, fairFrac, err := computeConcurrencyAllocation(cfgCtlr.nominalCLSum, items)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Unable to derive new concurrency limits\", \"plNames\", plNames, \"items\", items)\n\t\tallocs = make([]float64, len(items))\n\t\tfor idx, plName := range plNames {\n\t\t\tplState := plStates[plName]\n\t\t\tif plState.pl.Spec.Limited == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tallocs[idx] = float64(plState.currentCL)\n\t\t}\n\t}\n\tfor idx, plName := range plNames {\n\t\tplState := plStates[plName]\n\t\tif plState.pl.Spec.Limited == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif setCompleters {\n\t\t\tqsCompleter, err := queueSetCompleterForPL(cfgCtlr.queueSetFactory, plState.queues,\n\t\t\t\tplState.pl, cfgCtlr.requestWaitLimit, plState.reqsGaugePair, plState.execSeatsObs,\n\t\t\t\tmetrics.NewUnionGauge(plState.seatDemandIntegrator, plState.seatDemandRatioedGauge))\n\t\t\tif err != nil {\n\t\t\t\tklog.ErrorS(err, \"Inconceivable! Configuration error in existing priority level\", \"pl\", plState.pl)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tplState.qsCompleter = qsCompleter\n\t\t}\n\t\tcurrentCL := int(math.Round(float64(allocs[idx])))\n\t\trelChange := relDiff(float64(currentCL), float64(plState.currentCL))\n\t\tplState.currentCL = currentCL\n\t\tmetrics.NotePriorityLevelConcurrencyAdjustment(plState.pl.Name, plState.seatDemandStats.highWatermark, plState.seatDemandStats.avg, plState.seatDemandStats.stdDev, plState.seatDemandStats.smoothed, float64(items[idx].target), currentCL)\n\t\tlogLevel := klog.Level(4)\n\t\tif relChange \u003e= 0.05 {\n\t\t\tlogLevel = 2\n\t\t}\n\t\tklog.V(logLevel).InfoS(\"Update CurrentCL\", \"plName\", plName, \"seatDemandHighWatermark\", plState.seatDemandStats.highWatermark, \"seatDemandAvg\", plState.seatDemandStats.avg, \"seatDemandStdev\", plState.seatDemandStats.stdDev, \"seatDemandSmoothed\", plState.seatDemandStats.smoothed, \"fairFrac\", fairFrac, \"currentCL\", currentCL, \"backstop\", err != nil)\n\t\tplState.queues = plState.qsCompleter.Complete(fq.DispatchingConfig{ConcurrencyLimit: currentCL})\n\t}\n\tmetrics.SetFairFrac(float64(fairFrac))\n}","line":{"from":383,"to":448}} {"id":100018858,"name":"runWorker","signature":"func (cfgCtlr *configController) runWorker()","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"// runWorker is the logic of the one and only worker goroutine. We\n// limit the number to one in order to obviate explicit\n// synchronization around access to `cfgCtlr.mostRecentUpdates`.\nfunc (cfgCtlr *configController) runWorker() {\n\tfor cfgCtlr.processNextWorkItem() {\n\t}\n}","line":{"from":450,"to":456}} {"id":100018859,"name":"processNextWorkItem","signature":"func (cfgCtlr *configController) processNextWorkItem() bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"// processNextWorkItem works on one entry from the work queue.\n// Only invoke this in the one and only worker goroutine.\nfunc (cfgCtlr *configController) processNextWorkItem() bool {\n\tobj, shutdown := cfgCtlr.configQueue.Get()\n\tif shutdown {\n\t\treturn false\n\t}\n\n\tfunc(obj interface{}) {\n\t\tdefer cfgCtlr.configQueue.Done(obj)\n\t\tspecificDelay, err := cfgCtlr.syncOne()\n\t\tswitch {\n\t\tcase err != nil:\n\t\t\tklog.Error(err)\n\t\t\tcfgCtlr.configQueue.AddRateLimited(obj)\n\t\tcase specificDelay \u003e 0:\n\t\t\tcfgCtlr.configQueue.AddAfter(obj, specificDelay)\n\t\tdefault:\n\t\t\tcfgCtlr.configQueue.Forget(obj)\n\t\t}\n\t}(obj)\n\n\treturn true\n}","line":{"from":458,"to":481}} {"id":100018860,"name":"syncOne","signature":"func (cfgCtlr *configController) syncOne() (specificDelay time.Duration, err error)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"// syncOne does one full synchronization. It reads all the API\n// objects that configure API Priority and Fairness and updates the\n// local configController accordingly.\n// Only invoke this in the one and only worker goroutine\nfunc (cfgCtlr *configController) syncOne() (specificDelay time.Duration, err error) {\n\tklog.V(5).Infof(\"%s syncOne at %s\", cfgCtlr.name, cfgCtlr.clock.Now().Format(timeFmt))\n\tall := labels.Everything()\n\tnewPLs, err := cfgCtlr.plLister.List(all)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"unable to list PriorityLevelConfiguration objects: %w\", err)\n\t}\n\tnewFSs, err := cfgCtlr.fsLister.List(all)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"unable to list FlowSchema objects: %w\", err)\n\t}\n\treturn cfgCtlr.digestConfigObjects(newPLs, newFSs)\n}","line":{"from":483,"to":499}} {"id":100018861,"name":"digestConfigObjects","signature":"func (cfgCtlr *configController) digestConfigObjects(newPLs []*flowcontrol.PriorityLevelConfiguration, newFSs []*flowcontrol.FlowSchema) (time.Duration, error)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"// digestConfigObjects is given all the API objects that configure\n// cfgCtlr and writes its consequent new configState.\n// Only invoke this in the one and only worker goroutine\nfunc (cfgCtlr *configController) digestConfigObjects(newPLs []*flowcontrol.PriorityLevelConfiguration, newFSs []*flowcontrol.FlowSchema) (time.Duration, error) {\n\tfsStatusUpdates := cfgCtlr.lockAndDigestConfigObjects(newPLs, newFSs)\n\tvar errs []error\n\tcurrResult := updateAttempt{\n\t\ttimeUpdated: cfgCtlr.clock.Now(),\n\t\tupdatedItems: sets.String{},\n\t}\n\tvar suggestedDelay time.Duration\n\tfor _, fsu := range fsStatusUpdates {\n\t\t// if we should skip this name, indicate we will need a delay, but continue with other entries\n\t\tif cfgCtlr.shouldDelayUpdate(fsu.flowSchema.Name) {\n\t\t\tif suggestedDelay == 0 {\n\t\t\t\tsuggestedDelay = time.Duration(30+rand.Intn(45)) * time.Second\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// if we are going to issue an update, be sure we track every name we update so we know if we update it too often.\n\t\tcurrResult.updatedItems.Insert(fsu.flowSchema.Name)\n\t\tif klogV := klog.V(4); klogV.Enabled() {\n\t\t\tklogV.Infof(\"%s writing Condition %s to FlowSchema %s, which had ResourceVersion=%s, because its previous value was %s, diff: %s\",\n\t\t\t\tcfgCtlr.name, fsu.condition, fsu.flowSchema.Name, fsu.flowSchema.ResourceVersion, fcfmt.Fmt(fsu.oldValue), cmp.Diff(fsu.oldValue, fsu.condition))\n\t\t}\n\n\t\tif err := apply(cfgCtlr.flowcontrolClient.FlowSchemas(), fsu, cfgCtlr.asFieldManager); err != nil {\n\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\t// This object has been deleted. A notification is coming\n\t\t\t\t// and nothing more needs to be done here.\n\t\t\t\tklog.V(5).Infof(\"%s at %s: attempted update of concurrently deleted FlowSchema %s; nothing more needs to be done\", cfgCtlr.name, cfgCtlr.clock.Now().Format(timeFmt), fsu.flowSchema.Name)\n\t\t\t} else {\n\t\t\t\terrs = append(errs, fmt.Errorf(\"failed to set a status.condition for FlowSchema %s: %w\", fsu.flowSchema.Name, err))\n\t\t\t}\n\t\t}\n\t}\n\tcfgCtlr.addUpdateResult(currResult)\n\n\treturn suggestedDelay, utilerrors.NewAggregate(errs)\n}","line":{"from":538,"to":578}} {"id":100018862,"name":"apply","signature":"func apply(client flowcontrolclient.FlowSchemaInterface, fsu fsStatusUpdate, asFieldManager string) error","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"func apply(client flowcontrolclient.FlowSchemaInterface, fsu fsStatusUpdate, asFieldManager string) error {\n\tapplyOptions := metav1.ApplyOptions{FieldManager: asFieldManager, Force: true}\n\n\t// the condition field in fsStatusUpdate holds the new condition we want to update.\n\t// TODO: this will break when we have multiple conditions for a flowschema\n\t_, err := client.ApplyStatus(context.TODO(), toFlowSchemaApplyConfiguration(fsu), applyOptions)\n\treturn err\n}","line":{"from":580,"to":587}} {"id":100018863,"name":"toFlowSchemaApplyConfiguration","signature":"func toFlowSchemaApplyConfiguration(fsUpdate fsStatusUpdate) *flowcontrolapplyconfiguration.FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"func toFlowSchemaApplyConfiguration(fsUpdate fsStatusUpdate) *flowcontrolapplyconfiguration.FlowSchemaApplyConfiguration {\n\tcondition := flowcontrolapplyconfiguration.FlowSchemaCondition().\n\t\tWithType(fsUpdate.condition.Type).\n\t\tWithStatus(fsUpdate.condition.Status).\n\t\tWithReason(fsUpdate.condition.Reason).\n\t\tWithLastTransitionTime(fsUpdate.condition.LastTransitionTime).\n\t\tWithMessage(fsUpdate.condition.Message)\n\n\treturn flowcontrolapplyconfiguration.FlowSchema(fsUpdate.flowSchema.Name).\n\t\tWithStatus(flowcontrolapplyconfiguration.FlowSchemaStatus().\n\t\t\tWithConditions(condition),\n\t\t)\n}","line":{"from":589,"to":601}} {"id":100018864,"name":"shouldDelayUpdate","signature":"func (cfgCtlr *configController) shouldDelayUpdate(flowSchemaName string) bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"// shouldDelayUpdate checks to see if a flowschema has been updated too often and returns true if a delay is needed.\n// Only invoke this in the one and only worker goroutine\nfunc (cfgCtlr *configController) shouldDelayUpdate(flowSchemaName string) bool {\n\tnumUpdatesInPastMinute := 0\n\toneMinuteAgo := cfgCtlr.clock.Now().Add(-1 * time.Minute)\n\tfor idx, update := range cfgCtlr.mostRecentUpdates {\n\t\tif oneMinuteAgo.After(update.timeUpdated) {\n\t\t\t// this and the remaining items are no longer relevant\n\t\t\tcfgCtlr.mostRecentUpdates = cfgCtlr.mostRecentUpdates[:idx]\n\t\t\treturn false\n\t\t}\n\t\tif update.updatedItems.Has(flowSchemaName) {\n\t\t\tnumUpdatesInPastMinute++\n\t\t\tif numUpdatesInPastMinute \u003e 5 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":603,"to":622}} {"id":100018865,"name":"addUpdateResult","signature":"func (cfgCtlr *configController) addUpdateResult(result updateAttempt)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"// addUpdateResult adds the result. It isn't a ring buffer because\n// this is small and rate limited.\n// Only invoke this in the one and only worker goroutine\nfunc (cfgCtlr *configController) addUpdateResult(result updateAttempt) {\n\tcfgCtlr.mostRecentUpdates = append([]updateAttempt{result}, cfgCtlr.mostRecentUpdates...)\n}","line":{"from":624,"to":629}} {"id":100018866,"name":"lockAndDigestConfigObjects","signature":"func (cfgCtlr *configController) lockAndDigestConfigObjects(newPLs []*flowcontrol.PriorityLevelConfiguration, newFSs []*flowcontrol.FlowSchema) []fsStatusUpdate","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"func (cfgCtlr *configController) lockAndDigestConfigObjects(newPLs []*flowcontrol.PriorityLevelConfiguration, newFSs []*flowcontrol.FlowSchema) []fsStatusUpdate {\n\tcfgCtlr.lock.Lock()\n\tdefer cfgCtlr.lock.Unlock()\n\tmeal := cfgMeal{\n\t\tcfgCtlr: cfgCtlr,\n\t\tnewPLStates: make(map[string]*priorityLevelState),\n\t}\n\n\tmeal.digestNewPLsLocked(newPLs)\n\tmeal.digestFlowSchemasLocked(newFSs)\n\tmeal.processOldPLsLocked()\n\n\t// Supply missing mandatory PriorityLevelConfiguration objects\n\tif !meal.haveExemptPL {\n\t\tmeal.imaginePL(fcboot.MandatoryPriorityLevelConfigurationExempt, cfgCtlr.requestWaitLimit)\n\t}\n\tif !meal.haveCatchAllPL {\n\t\tmeal.imaginePL(fcboot.MandatoryPriorityLevelConfigurationCatchAll, cfgCtlr.requestWaitLimit)\n\t}\n\n\tmeal.finishQueueSetReconfigsLocked()\n\n\t// The new config has been constructed\n\tcfgCtlr.priorityLevelStates = meal.newPLStates\n\tklog.V(5).InfoS(\"Switched to new API Priority and Fairness configuration\", \"maxWaitingRequests\", meal.maxWaitingRequests, \"maxExecutinRequests\", meal.maxExecutingRequests)\n\n\tmetrics.GetWaitingReadonlyConcurrency().SetDenominator(float64(meal.maxWaitingRequests))\n\tmetrics.GetWaitingMutatingConcurrency().SetDenominator(float64(meal.maxWaitingRequests))\n\tmetrics.GetExecutingReadonlyConcurrency().SetDenominator(float64(meal.maxExecutingRequests))\n\tmetrics.GetExecutingMutatingConcurrency().SetDenominator(float64(meal.maxExecutingRequests))\n\n\treturn meal.fsStatusUpdates\n}","line":{"from":631,"to":663}} {"id":100018867,"name":"digestNewPLsLocked","signature":"func (meal *cfgMeal) digestNewPLsLocked(newPLs []*flowcontrol.PriorityLevelConfiguration)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"// Digest the new set of PriorityLevelConfiguration objects.\n// Pretend broken ones do not exist.\nfunc (meal *cfgMeal) digestNewPLsLocked(newPLs []*flowcontrol.PriorityLevelConfiguration) {\n\tfor _, pl := range newPLs {\n\t\tstate := meal.cfgCtlr.priorityLevelStates[pl.Name]\n\t\tif state == nil {\n\t\t\tlabelValues := []string{pl.Name}\n\t\t\tstate = \u0026priorityLevelState{\n\t\t\t\treqsGaugePair: metrics.RatioedGaugeVecPhasedElementPair(meal.cfgCtlr.reqsGaugeVec, 1, 1, labelValues),\n\t\t\t\texecSeatsObs: meal.cfgCtlr.execSeatsGaugeVec.NewForLabelValuesSafe(0, 1, labelValues),\n\t\t\t\tseatDemandIntegrator: fq.NewNamedIntegrator(meal.cfgCtlr.clock, pl.Name),\n\t\t\t\tseatDemandRatioedGauge: metrics.ApiserverSeatDemands.NewForLabelValuesSafe(0, 1, []string{pl.Name}),\n\t\t\t}\n\t\t}\n\t\tqsCompleter, err := queueSetCompleterForPL(meal.cfgCtlr.queueSetFactory, state.queues,\n\t\t\tpl, meal.cfgCtlr.requestWaitLimit, state.reqsGaugePair, state.execSeatsObs,\n\t\t\tmetrics.NewUnionGauge(state.seatDemandIntegrator, state.seatDemandRatioedGauge))\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"Ignoring PriorityLevelConfiguration object %s because its spec (%s) is broken: %s\", pl.Name, fcfmt.Fmt(pl.Spec), err)\n\t\t\tcontinue\n\t\t}\n\t\tmeal.newPLStates[pl.Name] = state\n\t\tstate.pl = pl\n\t\tstate.qsCompleter = qsCompleter\n\t\tif state.quiescing { // it was undesired, but no longer\n\t\t\tklog.V(3).Infof(\"Priority level %q was undesired and has become desired again\", pl.Name)\n\t\t\tstate.quiescing = false\n\t\t}\n\t\tif state.pl.Spec.Limited != nil {\n\t\t\tmeal.shareSum += float64(state.pl.Spec.Limited.NominalConcurrencyShares)\n\t\t}\n\t\tmeal.haveExemptPL = meal.haveExemptPL || pl.Name == flowcontrol.PriorityLevelConfigurationNameExempt\n\t\tmeal.haveCatchAllPL = meal.haveCatchAllPL || pl.Name == flowcontrol.PriorityLevelConfigurationNameCatchAll\n\t}\n}","line":{"from":665,"to":699}} {"id":100018868,"name":"digestFlowSchemasLocked","signature":"func (meal *cfgMeal) digestFlowSchemasLocked(newFSs []*flowcontrol.FlowSchema)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"// Digest the given FlowSchema objects. Ones that reference a missing\n// or broken priority level are not to be passed on to the filter for\n// use. We do this before holding over old priority levels so that\n// requests stop going to those levels and FlowSchemaStatus values\n// reflect this. This function also adds any missing mandatory\n// FlowSchema objects. The given objects must all have distinct\n// names.\nfunc (meal *cfgMeal) digestFlowSchemasLocked(newFSs []*flowcontrol.FlowSchema) {\n\tfsSeq := make(apihelpers.FlowSchemaSequence, 0, len(newFSs))\n\tfsMap := make(map[string]*flowcontrol.FlowSchema, len(newFSs))\n\tvar haveExemptFS, haveCatchAllFS bool\n\tfor i, fs := range newFSs {\n\t\totherFS := fsMap[fs.Name]\n\t\tif otherFS != nil {\n\t\t\t// This client is forbidden to do this.\n\t\t\tpanic(fmt.Sprintf(\"Given two FlowSchema objects with the same name: %s and %s\", fcfmt.Fmt(otherFS), fcfmt.Fmt(fs)))\n\t\t}\n\t\tfsMap[fs.Name] = fs\n\t\t_, goodPriorityRef := meal.newPLStates[fs.Spec.PriorityLevelConfiguration.Name]\n\n\t\t// Ensure the object's status reflects whether its priority\n\t\t// level reference is broken.\n\t\t//\n\t\t// TODO: consider not even trying if server is not handling\n\t\t// requests yet.\n\t\tmeal.presyncFlowSchemaStatus(fs, meal.cfgCtlr.foundToDangling(goodPriorityRef), fs.Spec.PriorityLevelConfiguration.Name)\n\n\t\tif !goodPriorityRef {\n\t\t\tklog.V(6).Infof(\"Ignoring FlowSchema %s because of bad priority level reference %q\", fs.Name, fs.Spec.PriorityLevelConfiguration.Name)\n\t\t\tcontinue\n\t\t}\n\t\tfsSeq = append(fsSeq, newFSs[i])\n\t\thaveExemptFS = haveExemptFS || fs.Name == flowcontrol.FlowSchemaNameExempt\n\t\thaveCatchAllFS = haveCatchAllFS || fs.Name == flowcontrol.FlowSchemaNameCatchAll\n\t}\n\t// sort into the order to be used for matching\n\tsort.Sort(fsSeq)\n\n\t// Supply missing mandatory FlowSchemas, in correct position\n\tif !haveExemptFS {\n\t\tfsSeq = append(apihelpers.FlowSchemaSequence{fcboot.MandatoryFlowSchemaExempt}, fsSeq...)\n\t}\n\tif !haveCatchAllFS {\n\t\tfsSeq = append(fsSeq, fcboot.MandatoryFlowSchemaCatchAll)\n\t}\n\n\tmeal.cfgCtlr.flowSchemas = fsSeq\n\tklogV := klog.V(5)\n\tif klogV.Enabled() {\n\t\tfor _, fs := range fsSeq {\n\t\t\tklogV.Infof(\"Using FlowSchema %s\", fcfmt.Fmt(fs))\n\t\t}\n\t}\n}","line":{"from":701,"to":754}} {"id":100018869,"name":"processOldPLsLocked","signature":"func (meal *cfgMeal) processOldPLsLocked()","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"// Consider all the priority levels in the previous configuration.\n// Keep the ones that are in the new config, supply mandatory\n// behavior, or are still busy; for the rest: drop it if it has no\n// queues, otherwise start the quiescing process if that has not\n// already been started.\nfunc (meal *cfgMeal) processOldPLsLocked() {\n\tfor plName, plState := range meal.cfgCtlr.priorityLevelStates {\n\t\tif meal.newPLStates[plName] != nil {\n\t\t\t// Still desired and already updated\n\t\t\tcontinue\n\t\t}\n\t\tif plName == flowcontrol.PriorityLevelConfigurationNameExempt \u0026\u0026 !meal.haveExemptPL || plName == flowcontrol.PriorityLevelConfigurationNameCatchAll \u0026\u0026 !meal.haveCatchAllPL {\n\t\t\t// BTW, we know the Spec has not changed because the\n\t\t\t// mandatory objects have immutable Specs\n\t\t\tklog.V(3).Infof(\"Retaining mandatory priority level %q despite lack of API object\", plName)\n\t\t} else {\n\t\t\tif plState.queues == nil || plState.numPending == 0 \u0026\u0026 plState.queues.IsIdle() {\n\t\t\t\t// Either there are no queues or they are done\n\t\t\t\t// draining and no use is coming from another\n\t\t\t\t// goroutine\n\t\t\t\tklog.V(3).Infof(\"Removing undesired priority level %q (nilQueues=%v), Type=%v\", plName, plState.queues == nil, plState.pl.Spec.Type)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !plState.quiescing {\n\t\t\t\tklog.V(3).Infof(\"Priority level %q became undesired\", plName)\n\t\t\t\tplState.quiescing = true\n\t\t\t}\n\t\t}\n\t\tvar err error\n\t\tplState.qsCompleter, err = queueSetCompleterForPL(meal.cfgCtlr.queueSetFactory, plState.queues,\n\t\t\tplState.pl, meal.cfgCtlr.requestWaitLimit, plState.reqsGaugePair, plState.execSeatsObs,\n\t\t\tmetrics.NewUnionGauge(plState.seatDemandIntegrator, plState.seatDemandRatioedGauge))\n\t\tif err != nil {\n\t\t\t// This can not happen because queueSetCompleterForPL already approved this config\n\t\t\tpanic(fmt.Sprintf(\"%s from name=%q spec=%s\", err, plName, fcfmt.Fmt(plState.pl.Spec)))\n\t\t}\n\t\tif plState.pl.Spec.Limited != nil {\n\t\t\t// We deliberately include the lingering priority levels\n\t\t\t// here so that their queues get some concurrency and they\n\t\t\t// continue to drain. During this interim a lingering\n\t\t\t// priority level continues to get a concurrency\n\t\t\t// allocation determined by all the share values in the\n\t\t\t// regular way.\n\t\t\tmeal.shareSum += float64(plState.pl.Spec.Limited.NominalConcurrencyShares)\n\t\t}\n\t\tmeal.haveExemptPL = meal.haveExemptPL || plName == flowcontrol.PriorityLevelConfigurationNameExempt\n\t\tmeal.haveCatchAllPL = meal.haveCatchAllPL || plName == flowcontrol.PriorityLevelConfigurationNameCatchAll\n\t\tmeal.newPLStates[plName] = plState\n\t}\n}","line":{"from":756,"to":805}} {"id":100018870,"name":"finishQueueSetReconfigsLocked","signature":"func (meal *cfgMeal) finishQueueSetReconfigsLocked()","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"// For all the priority levels of the new config, divide up the\n// server's total concurrency limit among them and create/update their\n// QueueSets.\nfunc (meal *cfgMeal) finishQueueSetReconfigsLocked() {\n\tfor plName, plState := range meal.newPLStates {\n\t\tif plState.pl.Spec.Limited == nil {\n\t\t\tklog.V(5).Infof(\"Using exempt priority level %q: quiescing=%v\", plName, plState.quiescing)\n\t\t\tcontinue\n\t\t}\n\n\t\tlimited := plState.pl.Spec.Limited\n\t\t// The use of math.Ceil here means that the results might sum\n\t\t// to a little more than serverConcurrencyLimit but the\n\t\t// difference will be negligible.\n\t\tconcurrencyLimit := int(math.Ceil(float64(meal.cfgCtlr.serverConcurrencyLimit) * float64(limited.NominalConcurrencyShares) / meal.shareSum))\n\t\tvar lendableCL, borrowingCL int\n\t\tif limited.LendablePercent != nil {\n\t\t\tlendableCL = int(math.Round(float64(concurrencyLimit) * float64(*limited.LendablePercent) / 100))\n\t\t}\n\t\tif limited.BorrowingLimitPercent != nil {\n\t\t\tborrowingCL = int(math.Round(float64(concurrencyLimit) * float64(*limited.BorrowingLimitPercent) / 100))\n\t\t} else {\n\t\t\tborrowingCL = meal.cfgCtlr.serverConcurrencyLimit\n\t\t}\n\t\tmetrics.SetPriorityLevelConfiguration(plName, concurrencyLimit, concurrencyLimit-lendableCL, concurrencyLimit+borrowingCL)\n\t\tplState.seatDemandRatioedGauge.SetDenominator(float64(concurrencyLimit))\n\t\tcfgChanged := plState.nominalCL != concurrencyLimit || plState.minCL != concurrencyLimit-lendableCL || plState.maxCL != concurrencyLimit+borrowingCL\n\t\tplState.nominalCL = concurrencyLimit\n\t\tplState.minCL = concurrencyLimit - lendableCL\n\t\tplState.maxCL = concurrencyLimit + borrowingCL\n\t\tmeal.maxExecutingRequests += concurrencyLimit\n\t\tvar waitLimit int\n\t\tif qCfg := limited.LimitResponse.Queuing; qCfg != nil {\n\t\t\twaitLimit = int(qCfg.Queues * qCfg.QueueLengthLimit)\n\t\t}\n\t\tmeal.maxWaitingRequests += waitLimit\n\n\t\tif plState.queues == nil {\n\t\t\tinitialCL := concurrencyLimit - lendableCL/2\n\t\t\tklog.V(2).Infof(\"Introducing queues for priority level %q: config=%s, nominalCL=%d, lendableCL=%d, borrowingCL=%d, currentCL=%d, quiescing=%v (shares=%v, shareSum=%v)\", plName, fcfmt.Fmt(plState.pl.Spec), concurrencyLimit, lendableCL, borrowingCL, initialCL, plState.quiescing, plState.pl.Spec.Limited.NominalConcurrencyShares, meal.shareSum)\n\t\t\tplState.seatDemandStats = seatDemandStats{}\n\t\t\tplState.currentCL = initialCL\n\t\t} else {\n\t\t\tlogLevel := klog.Level(5)\n\t\t\tif cfgChanged {\n\t\t\t\tlogLevel = 2\n\t\t\t}\n\t\t\tklog.V(logLevel).Infof(\"Retaining queues for priority level %q: config=%s, nominalCL=%d, lendableCL=%d, borrowingCL=%d, currentCL=%d, quiescing=%v, numPending=%d (shares=%v, shareSum=%v)\", plName, fcfmt.Fmt(plState.pl.Spec), concurrencyLimit, lendableCL, borrowingCL, plState.currentCL, plState.quiescing, plState.numPending, plState.pl.Spec.Limited.NominalConcurrencyShares, meal.shareSum)\n\t\t}\n\t}\n\tmeal.cfgCtlr.nominalCLSum = meal.maxExecutingRequests\n\tmeal.cfgCtlr.updateBorrowingLocked(false, meal.newPLStates)\n}","line":{"from":807,"to":859}} {"id":100018871,"name":"queueSetCompleterForPL","signature":"func queueSetCompleterForPL(qsf fq.QueueSetFactory, queues fq.QueueSet, pl *flowcontrol.PriorityLevelConfiguration, requestWaitLimit time.Duration, reqsIntPair metrics.RatioedGaugePair, execSeatsObs metrics.RatioedGauge, seatDemandGauge metrics.Gauge) (fq.QueueSetCompleter, error)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"// queueSetCompleterForPL returns an appropriate QueueSetCompleter for the\n// given priority level configuration. Returns nil if that config\n// does not call for limiting. Returns nil and an error if the given\n// object is malformed in a way that is a problem for this package.\nfunc queueSetCompleterForPL(qsf fq.QueueSetFactory, queues fq.QueueSet, pl *flowcontrol.PriorityLevelConfiguration, requestWaitLimit time.Duration, reqsIntPair metrics.RatioedGaugePair, execSeatsObs metrics.RatioedGauge, seatDemandGauge metrics.Gauge) (fq.QueueSetCompleter, error) {\n\tif (pl.Spec.Type == flowcontrol.PriorityLevelEnablementExempt) != (pl.Spec.Limited == nil) {\n\t\treturn nil, errors.New(\"broken union structure at the top\")\n\t}\n\tif (pl.Spec.Type == flowcontrol.PriorityLevelEnablementExempt) != (pl.Name == flowcontrol.PriorityLevelConfigurationNameExempt) {\n\t\t// This package does not attempt to cope with a priority level dynamically switching between exempt and not.\n\t\treturn nil, errors.New(\"non-alignment between name and type\")\n\t}\n\tif pl.Spec.Limited == nil {\n\t\treturn nil, nil\n\t}\n\tif (pl.Spec.Limited.LimitResponse.Type == flowcontrol.LimitResponseTypeReject) != (pl.Spec.Limited.LimitResponse.Queuing == nil) {\n\t\treturn nil, errors.New(\"broken union structure for limit response\")\n\t}\n\tqcAPI := pl.Spec.Limited.LimitResponse.Queuing\n\tqcQS := fq.QueuingConfig{Name: pl.Name}\n\tif qcAPI != nil {\n\t\tqcQS = fq.QueuingConfig{Name: pl.Name,\n\t\t\tDesiredNumQueues: int(qcAPI.Queues),\n\t\t\tQueueLengthLimit: int(qcAPI.QueueLengthLimit),\n\t\t\tHandSize: int(qcAPI.HandSize),\n\t\t\tRequestWaitLimit: requestWaitLimit,\n\t\t}\n\t}\n\tvar qsc fq.QueueSetCompleter\n\tvar err error\n\tif queues != nil {\n\t\tqsc, err = queues.BeginConfigChange(qcQS)\n\t} else {\n\t\tqsc, err = qsf.BeginConstruction(qcQS, reqsIntPair, execSeatsObs, seatDemandGauge)\n\t}\n\tif err != nil {\n\t\terr = fmt.Errorf(\"priority level %q has QueuingConfiguration %#+v, which is invalid: %w\", pl.Name, qcAPI, err)\n\t}\n\treturn qsc, err\n}","line":{"from":861,"to":900}} {"id":100018872,"name":"presyncFlowSchemaStatus","signature":"func (meal *cfgMeal) presyncFlowSchemaStatus(fs *flowcontrol.FlowSchema, isDangling bool, plName string)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"func (meal *cfgMeal) presyncFlowSchemaStatus(fs *flowcontrol.FlowSchema, isDangling bool, plName string) {\n\tdanglingCondition := apihelpers.GetFlowSchemaConditionByType(fs, flowcontrol.FlowSchemaConditionDangling)\n\tif danglingCondition == nil {\n\t\tdanglingCondition = \u0026flowcontrol.FlowSchemaCondition{\n\t\t\tType: flowcontrol.FlowSchemaConditionDangling,\n\t\t}\n\t}\n\tdesiredStatus := flowcontrol.ConditionFalse\n\tvar desiredReason, desiredMessage string\n\tif isDangling {\n\t\tdesiredStatus = flowcontrol.ConditionTrue\n\t\tdesiredReason = \"NotFound\"\n\t\tdesiredMessage = fmt.Sprintf(\"This FlowSchema references the PriorityLevelConfiguration object named %q but there is no such object\", plName)\n\t} else {\n\t\tdesiredReason = \"Found\"\n\t\tdesiredMessage = fmt.Sprintf(\"This FlowSchema references the PriorityLevelConfiguration object named %q and it exists\", plName)\n\t}\n\tif danglingCondition.Status == desiredStatus \u0026\u0026 danglingCondition.Reason == desiredReason \u0026\u0026 danglingCondition.Message == desiredMessage {\n\t\treturn\n\t}\n\tnow := meal.cfgCtlr.clock.Now()\n\tmeal.fsStatusUpdates = append(meal.fsStatusUpdates, fsStatusUpdate{\n\t\tflowSchema: fs,\n\t\tcondition: flowcontrol.FlowSchemaCondition{\n\t\t\tType: flowcontrol.FlowSchemaConditionDangling,\n\t\t\tStatus: desiredStatus,\n\t\t\tLastTransitionTime: metav1.NewTime(now),\n\t\t\tReason: desiredReason,\n\t\t\tMessage: desiredMessage,\n\t\t},\n\t\toldValue: *danglingCondition})\n}","line":{"from":902,"to":933}} {"id":100018873,"name":"imaginePL","signature":"func (meal *cfgMeal) imaginePL(proto *flowcontrol.PriorityLevelConfiguration, requestWaitLimit time.Duration)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"// imaginePL adds a priority level based on one of the mandatory ones\n// that does not actually exist (right now) as a real API object.\nfunc (meal *cfgMeal) imaginePL(proto *flowcontrol.PriorityLevelConfiguration, requestWaitLimit time.Duration) {\n\tklog.V(3).Infof(\"No %s PriorityLevelConfiguration found, imagining one\", proto.Name)\n\tlabelValues := []string{proto.Name}\n\treqsGaugePair := metrics.RatioedGaugeVecPhasedElementPair(meal.cfgCtlr.reqsGaugeVec, 1, 1, labelValues)\n\texecSeatsObs := meal.cfgCtlr.execSeatsGaugeVec.NewForLabelValuesSafe(0, 1, labelValues)\n\tseatDemandIntegrator := fq.NewNamedIntegrator(meal.cfgCtlr.clock, proto.Name)\n\tseatDemandRatioedGauge := metrics.ApiserverSeatDemands.NewForLabelValuesSafe(0, 1, []string{proto.Name})\n\tqsCompleter, err := queueSetCompleterForPL(meal.cfgCtlr.queueSetFactory, nil, proto,\n\t\trequestWaitLimit, reqsGaugePair, execSeatsObs,\n\t\tmetrics.NewUnionGauge(seatDemandIntegrator, seatDemandRatioedGauge))\n\tif err != nil {\n\t\t// This can not happen because proto is one of the mandatory\n\t\t// objects and these are not erroneous\n\t\tpanic(err)\n\t}\n\tmeal.newPLStates[proto.Name] = \u0026priorityLevelState{\n\t\tpl: proto,\n\t\tqsCompleter: qsCompleter,\n\t\treqsGaugePair: reqsGaugePair,\n\t\texecSeatsObs: execSeatsObs,\n\t\tseatDemandIntegrator: seatDemandIntegrator,\n\t\tseatDemandRatioedGauge: seatDemandRatioedGauge,\n\t}\n\tif proto.Spec.Limited != nil {\n\t\tmeal.shareSum += float64(proto.Spec.Limited.NominalConcurrencyShares)\n\t}\n}","line":{"from":935,"to":963}} {"id":100018874,"name":"Finish","signature":"func (immediateRequest) Finish(execute func()) bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"func (immediateRequest) Finish(execute func()) bool {\n\texecute()\n\treturn false\n}","line":{"from":967,"to":970}} {"id":100018875,"name":"startRequest","signature":"func (cfgCtlr *configController) startRequest(ctx context.Context, rd RequestDigest,","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"// startRequest classifies and, if appropriate, enqueues the request.\n// Returns a nil Request if and only if the request is to be rejected.\n// The returned bool indicates whether the request is exempt from\n// limitation. The startWaitingTime is when the request started\n// waiting in its queue, or `Time{}` if this did not happen.\nfunc (cfgCtlr *configController) startRequest(ctx context.Context, rd RequestDigest,\n\tnoteFn func(fs *flowcontrol.FlowSchema, pl *flowcontrol.PriorityLevelConfiguration, flowDistinguisher string),\n\tworkEstimator func() fcrequest.WorkEstimate,\n\tqueueNoteFn fq.QueueNoteFn) (fs *flowcontrol.FlowSchema, pl *flowcontrol.PriorityLevelConfiguration, isExempt bool, req fq.Request, startWaitingTime time.Time) {\n\tklog.V(7).Infof(\"startRequest(%#+v)\", rd)\n\tcfgCtlr.lock.RLock()\n\tdefer cfgCtlr.lock.RUnlock()\n\tvar selectedFlowSchema, catchAllFlowSchema *flowcontrol.FlowSchema\n\tfor _, fs := range cfgCtlr.flowSchemas {\n\t\tif matchesFlowSchema(rd, fs) {\n\t\t\tselectedFlowSchema = fs\n\t\t\tbreak\n\t\t}\n\t\tif fs.Name == flowcontrol.FlowSchemaNameCatchAll {\n\t\t\tcatchAllFlowSchema = fs\n\t\t}\n\t}\n\tif selectedFlowSchema == nil {\n\t\t// This should never happen. If the requestDigest's User is a part of\n\t\t// system:authenticated or system:unauthenticated, the catch-all flow\n\t\t// schema should match it. However, if that invariant somehow fails,\n\t\t// fallback to the catch-all flow schema anyway.\n\t\tif catchAllFlowSchema == nil {\n\t\t\t// This should absolutely never, ever happen! APF guarantees two\n\t\t\t// undeletable flow schemas at all times: an exempt flow schema and a\n\t\t\t// catch-all flow schema.\n\t\t\tpanic(fmt.Sprintf(\"no fallback catch-all flow schema found for request %#+v and user %#+v\", rd.RequestInfo, rd.User))\n\t\t}\n\t\tselectedFlowSchema = catchAllFlowSchema\n\t\tklog.Warningf(\"no match found for request %#+v and user %#+v; selecting catchAll=%s as fallback flow schema\", rd.RequestInfo, rd.User, fcfmt.Fmt(selectedFlowSchema))\n\t}\n\tplName := selectedFlowSchema.Spec.PriorityLevelConfiguration.Name\n\tplState := cfgCtlr.priorityLevelStates[plName]\n\tif plState.pl.Spec.Type == flowcontrol.PriorityLevelEnablementExempt {\n\t\tnoteFn(selectedFlowSchema, plState.pl, \"\")\n\t\tklog.V(7).Infof(\"startRequest(%#+v) =\u003e fsName=%q, distMethod=%#+v, plName=%q, immediate\", rd, selectedFlowSchema.Name, selectedFlowSchema.Spec.DistinguisherMethod, plName)\n\t\treturn selectedFlowSchema, plState.pl, true, immediateRequest{}, time.Time{}\n\t}\n\tvar numQueues int32\n\tif plState.pl.Spec.Limited.LimitResponse.Type == flowcontrol.LimitResponseTypeQueue {\n\t\tnumQueues = plState.pl.Spec.Limited.LimitResponse.Queuing.Queues\n\t}\n\tvar flowDistinguisher string\n\tvar hashValue uint64\n\tif numQueues \u003e 1 {\n\t\tflowDistinguisher = computeFlowDistinguisher(rd, selectedFlowSchema.Spec.DistinguisherMethod)\n\t\thashValue = hashFlowID(selectedFlowSchema.Name, flowDistinguisher)\n\t}\n\n\tnoteFn(selectedFlowSchema, plState.pl, flowDistinguisher)\n\tworkEstimate := workEstimator()\n\n\tstartWaitingTime = cfgCtlr.clock.Now()\n\tklog.V(7).Infof(\"startRequest(%#+v) =\u003e fsName=%q, distMethod=%#+v, plName=%q, numQueues=%d\", rd, selectedFlowSchema.Name, selectedFlowSchema.Spec.DistinguisherMethod, plName, numQueues)\n\treq, idle := plState.queues.StartRequest(ctx, \u0026workEstimate, hashValue, flowDistinguisher, selectedFlowSchema.Name, rd.RequestInfo, rd.User, queueNoteFn)\n\tif idle {\n\t\tcfgCtlr.maybeReapReadLocked(plName, plState)\n\t}\n\treturn selectedFlowSchema, plState.pl, false, req, startWaitingTime\n}","line":{"from":972,"to":1036}} {"id":100018876,"name":"maybeReap","signature":"func (cfgCtlr *configController) maybeReap(plName string)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"// maybeReap will remove the last internal traces of the named\n// priority level if it has no more use. Call this after getting a\n// clue that the given priority level is undesired and idle.\nfunc (cfgCtlr *configController) maybeReap(plName string) {\n\tcfgCtlr.lock.RLock()\n\tdefer cfgCtlr.lock.RUnlock()\n\tplState := cfgCtlr.priorityLevelStates[plName]\n\tif plState == nil {\n\t\tklog.V(7).Infof(\"plName=%s, plState==nil\", plName)\n\t\treturn\n\t}\n\tif plState.queues == nil {\n\t\tklog.V(7).Infof(\"plName=%s, plState.queues==nil\", plName)\n\t\treturn\n\t}\n\tuseless := plState.quiescing \u0026\u0026 plState.numPending == 0 \u0026\u0026 plState.queues.IsIdle()\n\tklog.V(7).Infof(\"plState.quiescing=%v, plState.numPending=%d, useless=%v\", plState.quiescing, plState.numPending, useless)\n\tif !useless {\n\t\treturn\n\t}\n\tklog.V(3).Infof(\"Triggered API priority and fairness config reloading because priority level %s is undesired and idle\", plName)\n\tcfgCtlr.configQueue.Add(0)\n}","line":{"from":1038,"to":1060}} {"id":100018877,"name":"maybeReapReadLocked","signature":"func (cfgCtlr *configController) maybeReapReadLocked(plName string, plState *priorityLevelState)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"// maybeReapLocked requires the cfgCtlr's lock to already be held and\n// will remove the last internal traces of the named priority level if\n// it has no more use. Call this if both (1) plState.queues is\n// non-nil and reported being idle, and (2) cfgCtlr's lock has not\n// been released since then.\nfunc (cfgCtlr *configController) maybeReapReadLocked(plName string, plState *priorityLevelState) {\n\tif !(plState.quiescing \u0026\u0026 plState.numPending == 0) {\n\t\treturn\n\t}\n\tklog.V(3).Infof(\"Triggered API priority and fairness config reloading because priority level %s is undesired and idle\", plName)\n\tcfgCtlr.configQueue.Add(0)\n}","line":{"from":1062,"to":1073}} {"id":100018878,"name":"computeFlowDistinguisher","signature":"func computeFlowDistinguisher(rd RequestDigest, method *flowcontrol.FlowDistinguisherMethod) string","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"// computeFlowDistinguisher extracts the flow distinguisher according to the given method\nfunc computeFlowDistinguisher(rd RequestDigest, method *flowcontrol.FlowDistinguisherMethod) string {\n\tif method == nil {\n\t\treturn \"\"\n\t}\n\tswitch method.Type {\n\tcase flowcontrol.FlowDistinguisherMethodByUserType:\n\t\treturn rd.User.GetName()\n\tcase flowcontrol.FlowDistinguisherMethodByNamespaceType:\n\t\treturn rd.RequestInfo.Namespace\n\tdefault:\n\t\t// this line shall never reach\n\t\tpanic(\"invalid flow-distinguisher method\")\n\t}\n}","line":{"from":1075,"to":1089}} {"id":100018879,"name":"hashFlowID","signature":"func hashFlowID(fsName, fDistinguisher string) uint64","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"func hashFlowID(fsName, fDistinguisher string) uint64 {\n\thash := sha256.New()\n\tvar sep = [1]byte{0}\n\thash.Write([]byte(fsName))\n\thash.Write(sep[:])\n\thash.Write([]byte(fDistinguisher))\n\tvar sum [32]byte\n\thash.Sum(sum[:0])\n\treturn binary.LittleEndian.Uint64(sum[:8])\n}","line":{"from":1091,"to":1100}} {"id":100018880,"name":"relDiff","signature":"func relDiff(x, y float64) float64","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller.go","code":"func relDiff(x, y float64) float64 {\n\tdiff := math.Abs(x - y)\n\tden := math.Max(math.Abs(x), math.Abs(y))\n\tif den == 0 {\n\t\treturn 0\n\t}\n\treturn diff / den\n}","line":{"from":1102,"to":1109}} {"id":100018881,"name":"Install","signature":"func (cfgCtlr *configController) Install(c *mux.PathRecorderMux)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller_debug.go","code":"func (cfgCtlr *configController) Install(c *mux.PathRecorderMux) {\n\t// TODO(yue9944882): handle \"Accept\" header properly\n\t// debugging dumps a CSV content for three levels of granularity\n\t// 1. row per priority-level\n\tc.UnlistedHandleFunc(\"/debug/api_priority_and_fairness/dump_priority_levels\", cfgCtlr.dumpPriorityLevels)\n\t// 2. row per queue\n\tc.UnlistedHandleFunc(\"/debug/api_priority_and_fairness/dump_queues\", cfgCtlr.dumpQueues)\n\t// 3. row per request\n\tc.UnlistedHandleFunc(\"/debug/api_priority_and_fairness/dump_requests\", cfgCtlr.dumpRequests)\n}","line":{"from":38,"to":47}} {"id":100018882,"name":"dumpPriorityLevels","signature":"func (cfgCtlr *configController) dumpPriorityLevels(w http.ResponseWriter, r *http.Request)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller_debug.go","code":"func (cfgCtlr *configController) dumpPriorityLevels(w http.ResponseWriter, r *http.Request) {\n\tcfgCtlr.lock.Lock()\n\tdefer cfgCtlr.lock.Unlock()\n\ttabWriter := tabwriter.NewWriter(w, 8, 0, 1, ' ', 0)\n\tcolumnHeaders := []string{\n\t\t\"PriorityLevelName\", // 1\n\t\t\"ActiveQueues\", // 2\n\t\t\"IsIdle\", // 3\n\t\t\"IsQuiescing\", // 4\n\t\t\"WaitingRequests\", // 5\n\t\t\"ExecutingRequests\", // 6\n\t\t\"DispatchedRequests\", // 7\n\t\t\"RejectedRequests\", // 8\n\t\t\"TimedoutRequests\", // 9\n\t\t\"CancelledRequests\", // 10\n\t}\n\ttabPrint(tabWriter, rowForHeaders(columnHeaders))\n\tendLine(tabWriter)\n\tplNames := make([]string, 0, len(cfgCtlr.priorityLevelStates))\n\tfor plName := range cfgCtlr.priorityLevelStates {\n\t\tplNames = append(plNames, plName)\n\t}\n\tsort.Strings(plNames)\n\tfor i := range plNames {\n\t\tplState, ok := cfgCtlr.priorityLevelStates[plNames[i]]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tif plState.queues == nil {\n\t\t\ttabPrint(tabWriter, row(\n\t\t\t\tplState.pl.Name, // 1\n\t\t\t\t\"\u003cnone\u003e\", // 2\n\t\t\t\t\"\u003cnone\u003e\", // 3\n\t\t\t\t\"\u003cnone\u003e\", // 4\n\t\t\t\t\"\u003cnone\u003e\", // 5\n\t\t\t\t\"\u003cnone\u003e\", // 6\n\t\t\t\t\"\u003cnone\u003e\", // 7\n\t\t\t\t\"\u003cnone\u003e\", // 8\n\t\t\t\t\"\u003cnone\u003e\", // 9\n\t\t\t\t\"\u003cnone\u003e\", // 10\n\t\t\t))\n\t\t\tendLine(tabWriter)\n\t\t\tcontinue\n\t\t}\n\t\tqueueSetDigest := plState.queues.Dump(false)\n\t\tactiveQueueNum := 0\n\t\tfor _, q := range queueSetDigest.Queues {\n\t\t\tif len(q.Requests) \u003e 0 {\n\t\t\t\tactiveQueueNum++\n\t\t\t}\n\t\t}\n\n\t\ttabPrint(tabWriter, rowForPriorityLevel(\n\t\t\tplState.pl.Name, // 1\n\t\t\tactiveQueueNum, // 2\n\t\t\tplState.queues.IsIdle(), // 3\n\t\t\tplState.quiescing, // 4\n\t\t\tqueueSetDigest.Waiting, // 5\n\t\t\tqueueSetDigest.Executing, // 6\n\t\t\tqueueSetDigest.Dispatched, // 7\n\t\t\tqueueSetDigest.Rejected, // 8\n\t\t\tqueueSetDigest.Timedout, // 9\n\t\t\tqueueSetDigest.Cancelled, // 10\n\t\t))\n\t\tendLine(tabWriter)\n\t}\n\truntime.HandleError(tabWriter.Flush())\n}","line":{"from":49,"to":117}} {"id":100018883,"name":"dumpQueues","signature":"func (cfgCtlr *configController) dumpQueues(w http.ResponseWriter, r *http.Request)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller_debug.go","code":"func (cfgCtlr *configController) dumpQueues(w http.ResponseWriter, r *http.Request) {\n\tcfgCtlr.lock.Lock()\n\tdefer cfgCtlr.lock.Unlock()\n\ttabWriter := tabwriter.NewWriter(w, 8, 0, 1, ' ', 0)\n\tcolumnHeaders := []string{\n\t\t\"PriorityLevelName\", // 1\n\t\t\"Index\", // 2\n\t\t\"PendingRequests\", // 3\n\t\t\"ExecutingRequests\", // 4\n\t\t\"SeatsInUse\", // 5\n\t\t\"NextDispatchR\", // 6\n\t\t\"InitialSeatsSum\", // 7\n\t\t\"MaxSeatsSum\", // 8\n\t\t\"TotalWorkSum\", // 9\n\t}\n\ttabPrint(tabWriter, rowForHeaders(columnHeaders))\n\tendLine(tabWriter)\n\tfor _, plState := range cfgCtlr.priorityLevelStates {\n\t\tif plState.queues == nil {\n\t\t\ttabPrint(tabWriter, row(\n\t\t\t\tplState.pl.Name, // 1\n\t\t\t\t\"\u003cnone\u003e\", // 2\n\t\t\t\t\"\u003cnone\u003e\", // 3\n\t\t\t\t\"\u003cnone\u003e\", // 4\n\t\t\t\t\"\u003cnone\u003e\", // 5\n\t\t\t\t\"\u003cnone\u003e\", // 6\n\t\t\t\t\"\u003cnone\u003e\", // 7\n\t\t\t\t\"\u003cnone\u003e\", // 8\n\t\t\t\t\"\u003cnone\u003e\", // 9\n\t\t\t))\n\t\t\tendLine(tabWriter)\n\t\t\tcontinue\n\t\t}\n\t\tqueueSetDigest := plState.queues.Dump(false)\n\t\tfor i, q := range queueSetDigest.Queues {\n\t\t\ttabPrint(tabWriter, row(\n\t\t\t\tplState.pl.Name, // 1 - \"PriorityLevelName\"\n\t\t\t\tstrconv.Itoa(i), // 2 - \"Index\"\n\t\t\t\tstrconv.Itoa(len(q.Requests)), // 3 - \"PendingRequests\"\n\t\t\t\tstrconv.Itoa(q.ExecutingRequests), // 4 - \"ExecutingRequests\"\n\t\t\t\tstrconv.Itoa(q.SeatsInUse), // 5 - \"SeatsInUse\"\n\t\t\t\tq.NextDispatchR, // 6 - \"NextDispatchR\"\n\t\t\t\tstrconv.Itoa(q.QueueSum.InitialSeatsSum), // 7 - \"InitialSeatsSum\"\n\t\t\t\tstrconv.Itoa(q.QueueSum.MaxSeatsSum), // 8 - \"MaxSeatsSum\"\n\t\t\t\tq.QueueSum.TotalWorkSum, // 9 - \"TotalWorkSum\"\n\t\t\t))\n\t\t\tendLine(tabWriter)\n\t\t}\n\t}\n\truntime.HandleError(tabWriter.Flush())\n}","line":{"from":119,"to":169}} {"id":100018884,"name":"dumpRequests","signature":"func (cfgCtlr *configController) dumpRequests(w http.ResponseWriter, r *http.Request)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller_debug.go","code":"func (cfgCtlr *configController) dumpRequests(w http.ResponseWriter, r *http.Request) {\n\tcfgCtlr.lock.Lock()\n\tdefer cfgCtlr.lock.Unlock()\n\n\tincludeRequestDetails := len(r.URL.Query().Get(queryIncludeRequestDetails)) \u003e 0\n\n\ttabWriter := tabwriter.NewWriter(w, 8, 0, 1, ' ', 0)\n\ttabPrint(tabWriter, rowForHeaders([]string{\n\t\t\"PriorityLevelName\", // 1\n\t\t\"FlowSchemaName\", // 2\n\t\t\"QueueIndex\", // 3\n\t\t\"RequestIndexInQueue\", // 4\n\t\t\"FlowDistingsher\", // 5\n\t\t\"ArriveTime\", // 6\n\t\t\"InitialSeats\", // 7\n\t\t\"FinalSeats\", // 8\n\t\t\"AdditionalLatency\", // 9\n\t}))\n\tif includeRequestDetails {\n\t\tcontinueLine(tabWriter)\n\t\ttabPrint(tabWriter, rowForHeaders([]string{\n\t\t\t\"UserName\", // 10\n\t\t\t\"Verb\", // 11\n\t\t\t\"APIPath\", // 12\n\t\t\t\"Namespace\", // 13\n\t\t\t\"Name\", // 14\n\t\t\t\"APIVersion\", // 15\n\t\t\t\"Resource\", // 16\n\t\t\t\"SubResource\", // 17\n\t\t}))\n\t}\n\tendLine(tabWriter)\n\tfor _, plState := range cfgCtlr.priorityLevelStates {\n\t\tif plState.queues == nil {\n\t\t\tcontinue\n\t\t}\n\t\tqueueSetDigest := plState.queues.Dump(includeRequestDetails)\n\t\tfor iq, q := range queueSetDigest.Queues {\n\t\t\tfor ir, r := range q.Requests {\n\t\t\t\ttabPrint(tabWriter, row(\n\t\t\t\t\tplState.pl.Name, // 1\n\t\t\t\t\tr.MatchedFlowSchema, // 2\n\t\t\t\t\tstrconv.Itoa(iq), // 3\n\t\t\t\t\tstrconv.Itoa(ir), // 4\n\t\t\t\t\tr.FlowDistinguisher, // 5\n\t\t\t\t\tr.ArriveTime.UTC().Format(time.RFC3339Nano), // 6\n\t\t\t\t\tstrconv.Itoa(int(r.WorkEstimate.InitialSeats)), // 7\n\t\t\t\t\tstrconv.Itoa(int(r.WorkEstimate.FinalSeats)), // 8\n\t\t\t\t\tr.WorkEstimate.AdditionalLatency.String(), // 9\n\t\t\t\t))\n\t\t\t\tif includeRequestDetails {\n\t\t\t\t\tcontinueLine(tabWriter)\n\t\t\t\t\ttabPrint(tabWriter, rowForRequestDetails(\n\t\t\t\t\t\tr.UserName, // 10\n\t\t\t\t\t\tr.RequestInfo.Verb, // 11\n\t\t\t\t\t\tr.RequestInfo.Path, // 12\n\t\t\t\t\t\tr.RequestInfo.Namespace, // 13\n\t\t\t\t\t\tr.RequestInfo.Name, // 14\n\t\t\t\t\t\tschema.GroupVersion{\n\t\t\t\t\t\t\tGroup: r.RequestInfo.APIGroup,\n\t\t\t\t\t\t\tVersion: r.RequestInfo.APIVersion,\n\t\t\t\t\t\t}.String(), // 15\n\t\t\t\t\t\tr.RequestInfo.Resource, // 16\n\t\t\t\t\t\tr.RequestInfo.Subresource, // 17\n\t\t\t\t\t))\n\t\t\t\t}\n\t\t\t\tendLine(tabWriter)\n\t\t\t}\n\t\t}\n\t}\n\truntime.HandleError(tabWriter.Flush())\n}","line":{"from":171,"to":242}} {"id":100018885,"name":"tabPrint","signature":"func tabPrint(w io.Writer, row string)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller_debug.go","code":"func tabPrint(w io.Writer, row string) {\n\t_, err := fmt.Fprint(w, row)\n\truntime.HandleError(err)\n}","line":{"from":244,"to":247}} {"id":100018886,"name":"continueLine","signature":"func continueLine(w io.Writer)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller_debug.go","code":"func continueLine(w io.Writer) {\n\t_, err := fmt.Fprint(w, \",\\t\")\n\truntime.HandleError(err)\n}","line":{"from":249,"to":252}} {"id":100018887,"name":"endLine","signature":"func endLine(w io.Writer)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller_debug.go","code":"func endLine(w io.Writer) {\n\t_, err := fmt.Fprint(w, \"\\n\")\n\truntime.HandleError(err)\n}","line":{"from":253,"to":256}} {"id":100018888,"name":"rowForHeaders","signature":"func rowForHeaders(headers []string) string","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller_debug.go","code":"func rowForHeaders(headers []string) string {\n\treturn row(headers...)\n}","line":{"from":258,"to":260}} {"id":100018889,"name":"rowForPriorityLevel","signature":"func rowForPriorityLevel(plName string, activeQueues int, isIdle, isQuiescing bool, waitingRequests, executingRequests int,","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller_debug.go","code":"func rowForPriorityLevel(plName string, activeQueues int, isIdle, isQuiescing bool, waitingRequests, executingRequests int,\n\tdispatchedReqeusts, rejectedRequests, timedoutRequests, cancelledRequests int) string {\n\treturn row(\n\t\tplName,\n\t\tstrconv.Itoa(activeQueues),\n\t\tstrconv.FormatBool(isIdle),\n\t\tstrconv.FormatBool(isQuiescing),\n\t\tstrconv.Itoa(waitingRequests),\n\t\tstrconv.Itoa(executingRequests),\n\t\tstrconv.Itoa(dispatchedReqeusts),\n\t\tstrconv.Itoa(rejectedRequests),\n\t\tstrconv.Itoa(timedoutRequests),\n\t\tstrconv.Itoa(cancelledRequests),\n\t)\n}","line":{"from":262,"to":276}} {"id":100018890,"name":"rowForRequestDetails","signature":"func rowForRequestDetails(username, verb, path, namespace, name, apiVersion, resource, subResource string) string","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller_debug.go","code":"func rowForRequestDetails(username, verb, path, namespace, name, apiVersion, resource, subResource string) string {\n\treturn row(\n\t\tusername,\n\t\tverb,\n\t\tpath,\n\t\tnamespace,\n\t\tname,\n\t\tapiVersion,\n\t\tresource,\n\t\tsubResource,\n\t)\n}","line":{"from":278,"to":289}} {"id":100018891,"name":"row","signature":"func row(columns ...string) string","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_controller_debug.go","code":"func row(columns ...string) string {\n\treturn strings.Join(columns, \",\\t\")\n}","line":{"from":291,"to":293}} {"id":100018892,"name":"New","signature":"func New(","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_filter.go","code":"// New creates a new instance to implement API priority and fairness\nfunc New(\n\tinformerFactory kubeinformers.SharedInformerFactory,\n\tflowcontrolClient flowcontrolclient.FlowcontrolV1beta3Interface,\n\tserverConcurrencyLimit int,\n\trequestWaitLimit time.Duration,\n) Interface {\n\tclk := eventclock.Real{}\n\treturn NewTestable(TestableConfig{\n\t\tName: \"Controller\",\n\t\tClock: clk,\n\t\tAsFieldManager: ConfigConsumerAsFieldManager,\n\t\tFoundToDangling: func(found bool) bool { return !found },\n\t\tInformerFactory: informerFactory,\n\t\tFlowcontrolClient: flowcontrolClient,\n\t\tServerConcurrencyLimit: serverConcurrencyLimit,\n\t\tRequestWaitLimit: requestWaitLimit,\n\t\tReqsGaugeVec: metrics.PriorityLevelConcurrencyGaugeVec,\n\t\tExecSeatsGaugeVec: metrics.PriorityLevelExecutionSeatsGaugeVec,\n\t\tQueueSetFactory: fqs.NewQueueSetFactory(clk),\n\t})\n}","line":{"from":84,"to":105}} {"id":100018893,"name":"NewTestable","signature":"func NewTestable(config TestableConfig) Interface","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_filter.go","code":"// NewTestable is extra flexible to facilitate testing\nfunc NewTestable(config TestableConfig) Interface {\n\treturn newTestableController(config)\n}","line":{"from":151,"to":154}} {"id":100018894,"name":"Handle","signature":"func (cfgCtlr *configController) Handle(ctx context.Context, requestDigest RequestDigest,","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_filter.go","code":"func (cfgCtlr *configController) Handle(ctx context.Context, requestDigest RequestDigest,\n\tnoteFn func(fs *flowcontrol.FlowSchema, pl *flowcontrol.PriorityLevelConfiguration, flowDistinguisher string),\n\tworkEstimator func() fcrequest.WorkEstimate,\n\tqueueNoteFn fq.QueueNoteFn,\n\texecFn func()) {\n\tfs, pl, isExempt, req, startWaitingTime := cfgCtlr.startRequest(ctx, requestDigest, noteFn, workEstimator, queueNoteFn)\n\tqueued := startWaitingTime != time.Time{}\n\tif req == nil {\n\t\tif queued {\n\t\t\tobserveQueueWaitTime(ctx, pl.Name, fs.Name, strconv.FormatBool(req != nil), cfgCtlr.clock.Since(startWaitingTime))\n\t\t}\n\t\tklog.V(7).Infof(\"Handle(%#+v) =\u003e fsName=%q, distMethod=%#+v, plName=%q, isExempt=%v, reject\", requestDigest, fs.Name, fs.Spec.DistinguisherMethod, pl.Name, isExempt)\n\t\treturn\n\t}\n\tklog.V(7).Infof(\"Handle(%#+v) =\u003e fsName=%q, distMethod=%#+v, plName=%q, isExempt=%v, queued=%v\", requestDigest, fs.Name, fs.Spec.DistinguisherMethod, pl.Name, isExempt, queued)\n\tvar executed bool\n\tidle, panicking := true, true\n\tdefer func() {\n\t\tklog.V(7).Infof(\"Handle(%#+v) =\u003e fsName=%q, distMethod=%#+v, plName=%q, isExempt=%v, queued=%v, Finish() =\u003e panicking=%v idle=%v\",\n\t\t\trequestDigest, fs.Name, fs.Spec.DistinguisherMethod, pl.Name, isExempt, queued, panicking, idle)\n\t\tif idle {\n\t\t\tcfgCtlr.maybeReap(pl.Name)\n\t\t}\n\t}()\n\tidle = req.Finish(func() {\n\t\tif queued {\n\t\t\tobserveQueueWaitTime(ctx, pl.Name, fs.Name, strconv.FormatBool(req != nil), cfgCtlr.clock.Since(startWaitingTime))\n\t\t}\n\t\tmetrics.AddDispatch(ctx, pl.Name, fs.Name)\n\t\tfqs.OnRequestDispatched(req)\n\t\texecuted = true\n\t\tstartExecutionTime := cfgCtlr.clock.Now()\n\t\tdefer func() {\n\t\t\texecutionTime := cfgCtlr.clock.Since(startExecutionTime)\n\t\t\thttplog.AddKeyValue(ctx, \"apf_execution_time\", executionTime)\n\t\t\tmetrics.ObserveExecutionDuration(ctx, pl.Name, fs.Name, executionTime)\n\t\t}()\n\t\texecFn()\n\t})\n\tif queued \u0026\u0026 !executed {\n\t\tobserveQueueWaitTime(ctx, pl.Name, fs.Name, strconv.FormatBool(req != nil), cfgCtlr.clock.Since(startWaitingTime))\n\t}\n\tpanicking = false\n}","line":{"from":156,"to":199}} {"id":100018895,"name":"observeQueueWaitTime","signature":"func observeQueueWaitTime(ctx context.Context, priorityLevelName, flowSchemaName, execute string, waitTime time.Duration)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/apf_filter.go","code":"func observeQueueWaitTime(ctx context.Context, priorityLevelName, flowSchemaName, execute string, waitTime time.Duration) {\n\tmetrics.ObserveWaitingDuration(ctx, priorityLevelName, flowSchemaName, execute, waitTime)\n\tendpointsrequest.TrackAPFQueueWaitLatency(ctx, waitTime)\n}","line":{"from":201,"to":204}} {"id":100018896,"name":"initIndices","signature":"func (rap *relativeAllocProblem) initIndices() *relativeAllocProblem","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/conc_alloc.go","code":"// initIndices fills in ascendingIndices and sorts them\nfunc (rap *relativeAllocProblem) initIndices() *relativeAllocProblem {\n\trap.ascendingIndices = make([]int, len(rap.items)*2)\n\tfor idx := 0; idx \u003c len(rap.ascendingIndices); idx++ {\n\t\trap.ascendingIndices[idx] = idx\n\t}\n\tsort.Sort(rap)\n\treturn rap\n}","line":{"from":49,"to":57}} {"id":100018897,"name":"getItemIndex","signature":"func (rap *relativeAllocProblem) getItemIndex(idx int) (int, bool)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/conc_alloc.go","code":"func (rap *relativeAllocProblem) getItemIndex(idx int) (int, bool) {\n\tpackedIndex := rap.ascendingIndices[idx]\n\titemIndex := packedIndex / 2\n\treturn itemIndex, packedIndex == itemIndex*2\n}","line":{"from":59,"to":63}} {"id":100018898,"name":"decode","signature":"func (rap *relativeAllocProblem) decode(idx int) (float64, int, bool)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/conc_alloc.go","code":"// decode(J) returns the bound associated with ascendingIndices[J], the associated items index,\n// and a bool indicating whether the bound is the item's lower bound.\nfunc (rap *relativeAllocProblem) decode(idx int) (float64, int, bool) {\n\titemIdx, lower := rap.getItemIndex(idx)\n\tif lower {\n\t\treturn rap.items[itemIdx].relativeLowerBound, itemIdx, lower\n\t}\n\treturn rap.items[itemIdx].relativeUpperBound, itemIdx, lower\n}","line":{"from":65,"to":73}} {"id":100018899,"name":"getProportion","signature":"func (rap *relativeAllocProblem) getProportion(idx int) float64","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/conc_alloc.go","code":"func (rap *relativeAllocProblem) getProportion(idx int) float64 {\n\tprop, _, _ := rap.decode(idx)\n\treturn prop\n}","line":{"from":75,"to":78}} {"id":100018900,"name":"Len","signature":"func (rap *relativeAllocProblem) Len() int { return len(rap.items) * 2 }","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/conc_alloc.go","code":"func (rap *relativeAllocProblem) Len() int { return len(rap.items) * 2 }","line":{"from":80,"to":80}} {"id":100018901,"name":"Less","signature":"func (rap *relativeAllocProblem) Less(i, j int) bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/conc_alloc.go","code":"func (rap *relativeAllocProblem) Less(i, j int) bool {\n\treturn rap.getProportion(i) \u003c rap.getProportion(j)\n}","line":{"from":82,"to":84}} {"id":100018902,"name":"Swap","signature":"func (rap *relativeAllocProblem) Swap(i, j int)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/conc_alloc.go","code":"func (rap *relativeAllocProblem) Swap(i, j int) {\n\trap.ascendingIndices[i], rap.ascendingIndices[j] = rap.ascendingIndices[j], rap.ascendingIndices[i]\n}","line":{"from":86,"to":88}} {"id":100018903,"name":"note","signature":"func (mm *minMax) note(x float64)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/conc_alloc.go","code":"// note scans one more number\nfunc (mm *minMax) note(x float64) {\n\tmm.min = math.Min(mm.min, x)\n\tmm.max = math.Max(mm.max, x)\n}","line":{"from":96,"to":100}} {"id":100018904,"name":"computeConcurrencyAllocation","signature":"func computeConcurrencyAllocation(requiredSum int, classes []allocProblemItem) ([]float64, float64, error)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/conc_alloc.go","code":"// computeConcurrencyAllocation returns the unique `allocs []float64`, and\n// an associated `fairProp float64`, that jointly have\n// all of the following properties (to the degree that floating point calculations allow)\n// if possible otherwise returns an error saying why it is impossible.\n// `allocs` sums to `requiredSum`.\n// For each J in [0, len(classes)):\n// 1. `classes[J].lowerBound \u003c= allocs[J] \u003c= classes[J].upperBound` and\n// 2. exactly one of the following is true:\n// 2a. `allocs[J] == fairProp * classes[J].target`,\n// 2b. `allocs[J] == classes[J].lowerBound \u0026\u0026 classes[J].lowerBound \u003e fairProp * classes[J].target`, or\n// 2c. `allocs[J] == classes[J].upperBound \u0026\u0026 classes[J].upperBound \u003c fairProp * classes[J].target`.\n//\n// Each allocProblemItem is required to have `target \u003e= lowerBound \u003e= 0` and `upperBound \u003e= lowerBound`.\n// A target smaller than MinTarget is treated as if it were MinTarget.\nfunc computeConcurrencyAllocation(requiredSum int, classes []allocProblemItem) ([]float64, float64, error) {\n\tif requiredSum \u003c 0 {\n\t\treturn nil, 0, errors.New(\"negative sums are not supported\")\n\t}\n\trequiredSumF := float64(requiredSum)\n\tvar lowSum, highSum, targetSum float64\n\tubRange := minMax{min: float64(math.MaxFloat32)}\n\tlbRange := minMax{min: float64(math.MaxFloat32)}\n\trelativeItems := make([]relativeAllocItem, len(classes))\n\tfor idx, item := range classes {\n\t\ttarget := item.target\n\t\tif item.lowerBound \u003c 0 {\n\t\t\treturn nil, 0, fmt.Errorf(\"lower bound %d is %v but negative lower bounds are not allowed\", idx, item.lowerBound)\n\t\t}\n\t\tif target \u003c item.lowerBound {\n\t\t\treturn nil, 0, fmt.Errorf(\"target %d is %v, which is below its lower bound of %v\", idx, target, item.lowerBound)\n\t\t}\n\t\tif item.upperBound \u003c item.lowerBound {\n\t\t\treturn nil, 0, fmt.Errorf(\"upper bound %d is %v but should not be less than the lower bound %v\", idx, item.upperBound, item.lowerBound)\n\t\t}\n\t\tif target \u003c MinTarget {\n\t\t\t// tweak this to a non-zero value so avoid dividing by zero\n\t\t\ttarget = MinTarget\n\t\t}\n\t\tlowSum += item.lowerBound\n\t\thighSum += item.upperBound\n\t\ttargetSum += target\n\t\trelativeItem := relativeAllocItem{\n\t\t\ttarget: target,\n\t\t\trelativeLowerBound: item.lowerBound / target,\n\t\t\trelativeUpperBound: item.upperBound / target,\n\t\t}\n\t\tubRange.note(relativeItem.relativeUpperBound)\n\t\tlbRange.note(relativeItem.relativeLowerBound)\n\t\trelativeItems[idx] = relativeItem\n\t}\n\tif lbRange.max \u003e 1 {\n\t\treturn nil, 0, fmt.Errorf(\"lbRange.max-1=%v, which is impossible because lbRange.max can not be greater than 1\", lbRange.max-1)\n\t}\n\tif lowSum-requiredSumF \u003e epsilon {\n\t\treturn nil, 0, fmt.Errorf(\"lower bounds sum to %v, which is higher than the required sum of %v\", lowSum, requiredSum)\n\t}\n\tif requiredSumF-highSum \u003e epsilon {\n\t\treturn nil, 0, fmt.Errorf(\"upper bounds sum to %v, which is lower than the required sum of %v\", highSum, requiredSum)\n\t}\n\tans := make([]float64, len(classes))\n\tif requiredSum == 0 {\n\t\treturn ans, 0, nil\n\t}\n\tif lowSum-requiredSumF \u003e -epsilon { // no wiggle room, constrained from below\n\t\tfor idx, item := range classes {\n\t\t\tans[idx] = item.lowerBound\n\t\t}\n\t\treturn ans, lbRange.min, nil\n\t}\n\tif requiredSumF-highSum \u003e -epsilon { // no wiggle room, constrained from above\n\t\tfor idx, item := range classes {\n\t\t\tans[idx] = item.upperBound\n\t\t}\n\t\treturn ans, ubRange.max, nil\n\t}\n\t// Now we know the solution is a unique fairProp in [lbRange.min, ubRange.max].\n\t// See if the solution does not run into any bounds.\n\tfairProp := requiredSumF / targetSum\n\tif lbRange.max \u003c= fairProp \u0026\u0026 fairProp \u003c= ubRange.min { // no bounds matter\n\t\tfor idx := range classes {\n\t\t\tans[idx] = relativeItems[idx].target * fairProp\n\t\t}\n\t\treturn ans, fairProp, nil\n\t}\n\t// Sadly, some bounds matter.\n\t// We find the solution by sorting the bounds and considering progressively\n\t// higher values of fairProp, starting from lbRange.min.\n\trap := (\u0026relativeAllocProblem{items: relativeItems}).initIndices()\n\tsumSoFar := lowSum\n\tfairProp = lbRange.min\n\tvar sensitiveTargetSum, deltaSensitiveTargetSum float64\n\tvar numSensitiveClasses, deltaSensitiveClasses int\n\tvar nextIdx int\n\t// `nextIdx` is the next `rap` index to consider.\n\t// `sumSoFar` is what the allocs would sum to if the current\n\t// value of `fairProp` solves the problem.\n\t// If the current value of fairProp were the answer then\n\t// `sumSoFar == requiredSum`.\n\t// Otherwise the next increment in fairProp involves changing the allocations\n\t// of `numSensitiveClasses` classes whose targets sum to `sensitiveTargetSum`;\n\t// for the other classes, an upper or lower bound has applied and will continue to apply.\n\t// The last increment of nextIdx calls for adding `deltaSensitiveClasses`\n\t// to `numSensitiveClasses` and adding `deltaSensitiveTargetSum` to `sensitiveTargetSum`.\n\tfor sumSoFar \u003c requiredSumF {\n\t\t// There might be more than one bound that is equal to the current value\n\t\t// of fairProp; find all of them because they will all be relevant to\n\t\t// the next change in fairProp.\n\t\t// Set nextBound to the next bound that is NOT equal to fairProp,\n\t\t// and advance nextIdx to the index of that bound.\n\t\tvar nextBound float64\n\t\tfor {\n\t\t\tsensitiveTargetSum += deltaSensitiveTargetSum\n\t\t\tnumSensitiveClasses += deltaSensitiveClasses\n\t\t\tif nextIdx \u003e= rap.Len() {\n\t\t\t\treturn nil, 0, fmt.Errorf(\"impossible: ran out of bounds to consider in bound-constrained problem\")\n\t\t\t}\n\t\t\tvar itemIdx int\n\t\t\tvar lower bool\n\t\t\tnextBound, itemIdx, lower = rap.decode(nextIdx)\n\t\t\tif lower {\n\t\t\t\tdeltaSensitiveClasses = 1\n\t\t\t\tdeltaSensitiveTargetSum = rap.items[itemIdx].target\n\t\t\t} else {\n\t\t\t\tdeltaSensitiveClasses = -1\n\t\t\t\tdeltaSensitiveTargetSum = -rap.items[itemIdx].target\n\t\t\t}\n\t\t\tnextIdx++\n\t\t\tif nextBound \u003e fairProp {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\t// fairProp can increase to nextBound without passing any intermediate bounds.\n\t\tif numSensitiveClasses == 0 {\n\t\t\t// No classes are affected by the next range of fairProp; skip right past it\n\t\t\tfairProp = nextBound\n\t\t\tcontinue\n\t\t}\n\t\t// See whether fairProp can increase to the solution before passing the next bound.\n\t\tdeltaFairProp := (requiredSumF - sumSoFar) / sensitiveTargetSum\n\t\tnextProp := fairProp + deltaFairProp\n\t\tif nextProp \u003c= nextBound {\n\t\t\tfairProp = nextProp\n\t\t\tbreak\n\t\t}\n\t\t// No, fairProp has to increase above nextBound\n\t\tsumSoFar += (nextBound - fairProp) * sensitiveTargetSum\n\t\tfairProp = nextBound\n\t}\n\tfor idx, item := range classes {\n\t\tans[idx] = math.Max(item.lowerBound, math.Min(item.upperBound, fairProp*relativeItems[idx].target))\n\t}\n\treturn ans, fairProp, nil\n}","line":{"from":105,"to":257}} {"id":100018905,"name":"EventAfterDuration","signature":"func (Real) EventAfterDuration(f EventFunc, d time.Duration)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/eventclock/real.go","code":"// EventAfterDuration schedules an EventFunc\nfunc (Real) EventAfterDuration(f EventFunc, d time.Duration) {\n\tch := time.After(d)\n\tgo func() {\n\t\tt := \u003c-ch\n\t\tf(t)\n\t}()\n}","line":{"from":32,"to":39}} {"id":100018906,"name":"EventAfterTime","signature":"func (r Real) EventAfterTime(f EventFunc, t time.Time)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/eventclock/real.go","code":"// EventAfterTime schedules an EventFunc\nfunc (r Real) EventAfterTime(f EventFunc, t time.Time) {\n\tr.EventAfterDuration(f, time.Until(t))\n}","line":{"from":41,"to":44}} {"id":100018907,"name":"Equal","signature":"func (x *IntegratorResults) Equal(y *IntegratorResults) bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/integrator.go","code":"// Equal tests for semantic equality.\n// This considers all NaN values to be equal to each other.\nfunc (x *IntegratorResults) Equal(y *IntegratorResults) bool {\n\treturn x == y || x != nil \u0026\u0026 y != nil \u0026\u0026 x.Duration == y.Duration \u0026\u0026 x.Min == y.Min \u0026\u0026 x.Max == y.Max \u0026\u0026 (x.Average == y.Average || math.IsNaN(x.Average) \u0026\u0026 math.IsNaN(y.Average)) \u0026\u0026 (x.Deviation == y.Deviation || math.IsNaN(x.Deviation) \u0026\u0026 math.IsNaN(y.Deviation))\n}","line":{"from":50,"to":54}} {"id":100018908,"name":"NewNamedIntegrator","signature":"func NewNamedIntegrator(clock clock.PassiveClock, name string) Integrator","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/integrator.go","code":"// NewNamedIntegrator makes one that uses the given clock and name\nfunc NewNamedIntegrator(clock clock.PassiveClock, name string) Integrator {\n\treturn \u0026integrator{\n\t\tname: name,\n\t\tclock: clock,\n\t\tlastTime: clock.Now(),\n\t}\n}","line":{"from":66,"to":73}} {"id":100018909,"name":"Set","signature":"func (igr *integrator) Set(x float64)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/integrator.go","code":"func (igr *integrator) Set(x float64) {\n\tigr.Lock()\n\tigr.setLocked(x)\n\tigr.Unlock()\n}","line":{"from":75,"to":79}} {"id":100018910,"name":"Add","signature":"func (igr *integrator) Add(deltaX float64)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/integrator.go","code":"func (igr *integrator) Add(deltaX float64) {\n\tigr.Lock()\n\tigr.setLocked(igr.x + deltaX)\n\tigr.Unlock()\n}","line":{"from":81,"to":85}} {"id":100018911,"name":"Inc","signature":"func (igr *integrator) Inc()","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/integrator.go","code":"func (igr *integrator) Inc() {\n\tigr.Add(1)\n}","line":{"from":87,"to":89}} {"id":100018912,"name":"Dec","signature":"func (igr *integrator) Dec()","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/integrator.go","code":"func (igr *integrator) Dec() {\n\tigr.Add(-1)\n}","line":{"from":91,"to":93}} {"id":100018913,"name":"SetToCurrentTime","signature":"func (igr *integrator) SetToCurrentTime()","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/integrator.go","code":"func (igr *integrator) SetToCurrentTime() {\n\tigr.Set(float64(time.Now().UnixNano()))\n}","line":{"from":95,"to":97}} {"id":100018914,"name":"setLocked","signature":"func (igr *integrator) setLocked(x float64)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/integrator.go","code":"func (igr *integrator) setLocked(x float64) {\n\tigr.updateLocked()\n\tigr.x = x\n\tif x \u003c igr.min {\n\t\tigr.min = x\n\t}\n\tif x \u003e igr.max {\n\t\tigr.max = x\n\t}\n}","line":{"from":99,"to":108}} {"id":100018915,"name":"updateLocked","signature":"func (igr *integrator) updateLocked()","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/integrator.go","code":"func (igr *integrator) updateLocked() {\n\tnow := igr.clock.Now()\n\tdt := now.Sub(igr.lastTime).Seconds()\n\tigr.lastTime = now\n\tigr.moments = igr.moments.Add(ConstantMoments(dt, igr.x))\n}","line":{"from":110,"to":115}} {"id":100018916,"name":"GetResults","signature":"func (igr *integrator) GetResults() IntegratorResults","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/integrator.go","code":"func (igr *integrator) GetResults() IntegratorResults {\n\tigr.Lock()\n\tdefer igr.Unlock()\n\treturn igr.getResultsLocked()\n}","line":{"from":117,"to":121}} {"id":100018917,"name":"Reset","signature":"func (igr *integrator) Reset() IntegratorResults","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/integrator.go","code":"func (igr *integrator) Reset() IntegratorResults {\n\tigr.Lock()\n\tdefer igr.Unlock()\n\tresults := igr.getResultsLocked()\n\tigr.moments = Moments{}\n\tigr.min = igr.x\n\tigr.max = igr.x\n\treturn results\n}","line":{"from":123,"to":131}} {"id":100018918,"name":"getResultsLocked","signature":"func (igr *integrator) getResultsLocked() (results IntegratorResults)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/integrator.go","code":"func (igr *integrator) getResultsLocked() (results IntegratorResults) {\n\tigr.updateLocked()\n\tresults.Min, results.Max = igr.min, igr.max\n\tresults.Duration = igr.moments.ElapsedSeconds\n\tresults.Average, results.Deviation = igr.moments.AvgAndStdDev()\n\treturn\n}","line":{"from":133,"to":139}} {"id":100018919,"name":"ConstantMoments","signature":"func ConstantMoments(dt, x float64) Moments","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/integrator.go","code":"// ConstantMoments is for a constant X\nfunc ConstantMoments(dt, x float64) Moments {\n\treturn Moments{\n\t\tElapsedSeconds: dt,\n\t\tIntegralX: x * dt,\n\t\tIntegralXX: x * x * dt,\n\t}\n}","line":{"from":149,"to":156}} {"id":100018920,"name":"Add","signature":"func (igr Moments) Add(ogr Moments) Moments","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/integrator.go","code":"// Add combines over two ranges of time\nfunc (igr Moments) Add(ogr Moments) Moments {\n\treturn Moments{\n\t\tElapsedSeconds: igr.ElapsedSeconds + ogr.ElapsedSeconds,\n\t\tIntegralX: igr.IntegralX + ogr.IntegralX,\n\t\tIntegralXX: igr.IntegralXX + ogr.IntegralXX,\n\t}\n}","line":{"from":158,"to":165}} {"id":100018921,"name":"Sub","signature":"func (igr Moments) Sub(ogr Moments) Moments","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/integrator.go","code":"// Sub finds the difference between a range of time and a subrange\nfunc (igr Moments) Sub(ogr Moments) Moments {\n\treturn Moments{\n\t\tElapsedSeconds: igr.ElapsedSeconds - ogr.ElapsedSeconds,\n\t\tIntegralX: igr.IntegralX - ogr.IntegralX,\n\t\tIntegralXX: igr.IntegralXX - ogr.IntegralXX,\n\t}\n}","line":{"from":167,"to":174}} {"id":100018922,"name":"AvgAndStdDev","signature":"func (igr Moments) AvgAndStdDev() (float64, float64)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/integrator.go","code":"// AvgAndStdDev returns the average and standard devation\nfunc (igr Moments) AvgAndStdDev() (float64, float64) {\n\tif igr.ElapsedSeconds \u003c= 0 {\n\t\treturn math.NaN(), math.NaN()\n\t}\n\tavg := igr.IntegralX / igr.ElapsedSeconds\n\t// standard deviation is sqrt( average( (x - xbar)^2 ) )\n\t// = sqrt( Integral( x^2 + xbar^2 -2*x*xbar dt ) / Duration )\n\t// = sqrt( ( Integral( x^2 dt ) + Duration * xbar^2 - 2*xbar*Integral(x dt) ) / Duration)\n\t// = sqrt( Integral(x^2 dt)/Duration - xbar^2 )\n\tvariance := igr.IntegralXX/igr.ElapsedSeconds - avg*avg\n\tif variance \u003e= 0 {\n\t\treturn avg, math.Sqrt(variance)\n\t}\n\treturn avg, math.NaN()\n}","line":{"from":176,"to":191}} {"id":100018923,"name":"NewWriteOnce","signature":"func NewWriteOnce(initial interface{}, doneCh \u003c-chan struct{}, doneVal interface{}) WriteOnce","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/promise/promise.go","code":"// NewWriteOnce makes a new thread-safe WriteOnce.\n//\n// If `initial` is non-nil then that value is Set at creation time.\n//\n// If a `Get` is waiting soon after `doneCh` becomes selectable (which\n// never happens for the nil channel) then `Set(doneVal)` effectively\n// happens at that time.\nfunc NewWriteOnce(initial interface{}, doneCh \u003c-chan struct{}, doneVal interface{}) WriteOnce {\n\tp := \u0026promise{\n\t\tdoneCh: doneCh,\n\t\tdoneVal: doneVal,\n\t\tsetCh: make(chan struct{}),\n\t}\n\tif initial != nil {\n\t\tp.Set(initial)\n\t}\n\treturn p\n}","line":{"from":34,"to":51}} {"id":100018924,"name":"Get","signature":"func (p *promise) Get() interface{}","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/promise/promise.go","code":"func (p *promise) Get() interface{} {\n\tselect {\n\tcase \u003c-p.setCh:\n\tcase \u003c-p.doneCh:\n\t\tp.Set(p.doneVal)\n\t}\n\treturn p.value\n}","line":{"from":53,"to":60}} {"id":100018925,"name":"Set","signature":"func (p *promise) Set(value interface{}) bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/promise/promise.go","code":"func (p *promise) Set(value interface{}) bool {\n\tvar ans bool\n\tp.onceler.Do(func() {\n\t\tp.value = value\n\t\tclose(p.setCh)\n\t\tans = true\n\t})\n\treturn ans\n}","line":{"from":62,"to":70}} {"id":100018926,"name":"newRequestFIFO","signature":"func newRequestFIFO() fifo","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/fifo_list.go","code":"func newRequestFIFO() fifo {\n\treturn \u0026requestFIFO{\n\t\tList: list.New(),\n\t}\n}","line":{"from":77,"to":81}} {"id":100018927,"name":"Length","signature":"func (l *requestFIFO) Length() int","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/fifo_list.go","code":"func (l *requestFIFO) Length() int {\n\treturn l.Len()\n}","line":{"from":83,"to":85}} {"id":100018928,"name":"QueueSum","signature":"func (l *requestFIFO) QueueSum() queueSum","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/fifo_list.go","code":"func (l *requestFIFO) QueueSum() queueSum {\n\treturn l.sum\n}","line":{"from":87,"to":89}} {"id":100018929,"name":"Enqueue","signature":"func (l *requestFIFO) Enqueue(req *request) removeFromFIFOFunc","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/fifo_list.go","code":"func (l *requestFIFO) Enqueue(req *request) removeFromFIFOFunc {\n\te := l.PushBack(req)\n\taddToQueueSum(\u0026l.sum, req)\n\n\treturn func() *request {\n\t\tif e.Value == nil {\n\t\t\treturn nil\n\t\t}\n\t\tl.Remove(e)\n\t\te.Value = nil\n\t\tdeductFromQueueSum(\u0026l.sum, req)\n\t\treturn req\n\t}\n}","line":{"from":91,"to":104}} {"id":100018930,"name":"Dequeue","signature":"func (l *requestFIFO) Dequeue() (*request, bool)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/fifo_list.go","code":"func (l *requestFIFO) Dequeue() (*request, bool) {\n\treturn l.getFirst(true)\n}","line":{"from":106,"to":108}} {"id":100018931,"name":"Peek","signature":"func (l *requestFIFO) Peek() (*request, bool)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/fifo_list.go","code":"func (l *requestFIFO) Peek() (*request, bool) {\n\treturn l.getFirst(false)\n}","line":{"from":110,"to":112}} {"id":100018932,"name":"getFirst","signature":"func (l *requestFIFO) getFirst(remove bool) (*request, bool)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/fifo_list.go","code":"func (l *requestFIFO) getFirst(remove bool) (*request, bool) {\n\te := l.Front()\n\tif e == nil {\n\t\treturn nil, false\n\t}\n\n\tif remove {\n\t\tdefer func() {\n\t\t\tl.Remove(e)\n\t\t\te.Value = nil\n\t\t}()\n\t}\n\n\trequest, ok := e.Value.(*request)\n\tif remove \u0026\u0026 ok {\n\t\tdeductFromQueueSum(\u0026l.sum, request)\n\t}\n\treturn request, ok\n}","line":{"from":114,"to":132}} {"id":100018933,"name":"Walk","signature":"func (l *requestFIFO) Walk(f walkFunc)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/fifo_list.go","code":"func (l *requestFIFO) Walk(f walkFunc) {\n\tvar next *list.Element\n\tfor current := l.Front(); current != nil; current = next {\n\t\tnext = current.Next() // f is allowed to remove current\n\t\tif r, ok := current.Value.(*request); ok {\n\t\t\tif !f(r) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":134,"to":144}} {"id":100018934,"name":"addToQueueSum","signature":"func addToQueueSum(sum *queueSum, req *request)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/fifo_list.go","code":"func addToQueueSum(sum *queueSum, req *request) {\n\tsum.InitialSeatsSum += req.InitialSeats()\n\tsum.MaxSeatsSum += req.MaxSeats()\n\tsum.TotalWorkSum += req.totalWork()\n}","line":{"from":146,"to":150}} {"id":100018935,"name":"deductFromQueueSum","signature":"func deductFromQueueSum(sum *queueSum, req *request)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/fifo_list.go","code":"func deductFromQueueSum(sum *queueSum, req *request) {\n\tsum.InitialSeatsSum -= req.InitialSeats()\n\tsum.MaxSeatsSum -= req.MaxSeats()\n\tsum.TotalWorkSum -= req.totalWork()\n}","line":{"from":152,"to":156}} {"id":100018936,"name":"NewQueueSetFactory","signature":"func NewQueueSetFactory(c eventclock.Interface) fq.QueueSetFactory","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"// NewQueueSetFactory creates a new QueueSetFactory object\nfunc NewQueueSetFactory(c eventclock.Interface) fq.QueueSetFactory {\n\treturn newTestableQueueSetFactory(c, ordinaryPromiseFactoryFactory)\n}","line":{"from":169,"to":172}} {"id":100018937,"name":"newTestableQueueSetFactory","signature":"func newTestableQueueSetFactory(c eventclock.Interface, promiseFactoryFactory promiseFactoryFactory) fq.QueueSetFactory","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"// newTestableQueueSetFactory creates a new QueueSetFactory object with the given promiseFactoryFactory\nfunc newTestableQueueSetFactory(c eventclock.Interface, promiseFactoryFactory promiseFactoryFactory) fq.QueueSetFactory {\n\treturn \u0026queueSetFactory{\n\t\tclock: c,\n\t\tpromiseFactoryFactory: promiseFactoryFactory,\n\t}\n}","line":{"from":174,"to":180}} {"id":100018938,"name":"BeginConstruction","signature":"func (qsf *queueSetFactory) BeginConstruction(qCfg fq.QueuingConfig, reqsGaugePair metrics.RatioedGaugePair, execSeatsGauge metrics.RatioedGauge, seatDemandIntegrator metrics.Gauge) (fq.QueueSetCompleter, error)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"func (qsf *queueSetFactory) BeginConstruction(qCfg fq.QueuingConfig, reqsGaugePair metrics.RatioedGaugePair, execSeatsGauge metrics.RatioedGauge, seatDemandIntegrator metrics.Gauge) (fq.QueueSetCompleter, error) {\n\tdealer, err := checkConfig(qCfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026queueSetCompleter{\n\t\tfactory: qsf,\n\t\treqsGaugePair: reqsGaugePair,\n\t\texecSeatsGauge: execSeatsGauge,\n\t\tseatDemandIntegrator: seatDemandIntegrator,\n\t\tqCfg: qCfg,\n\t\tdealer: dealer}, nil\n}","line":{"from":182,"to":194}} {"id":100018939,"name":"checkConfig","signature":"func checkConfig(qCfg fq.QueuingConfig) (*shufflesharding.Dealer, error)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"// checkConfig returns a non-nil Dealer if the config is valid and\n// calls for one, and returns a non-nil error if the given config is\n// invalid.\nfunc checkConfig(qCfg fq.QueuingConfig) (*shufflesharding.Dealer, error) {\n\tif qCfg.DesiredNumQueues == 0 {\n\t\treturn nil, nil\n\t}\n\tdealer, err := shufflesharding.NewDealer(qCfg.DesiredNumQueues, qCfg.HandSize)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"the QueueSetConfig implies an invalid shuffle sharding config (DesiredNumQueues is deckSize): %w\", err)\n\t}\n\treturn dealer, err\n}","line":{"from":196,"to":208}} {"id":100018940,"name":"Complete","signature":"func (qsc *queueSetCompleter) Complete(dCfg fq.DispatchingConfig) fq.QueueSet","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"func (qsc *queueSetCompleter) Complete(dCfg fq.DispatchingConfig) fq.QueueSet {\n\tqs := qsc.theSet\n\tif qs == nil {\n\t\tqs = \u0026queueSet{\n\t\t\tclock: qsc.factory.clock,\n\t\t\testimatedServiceDuration: 3 * time.Millisecond,\n\t\t\treqsGaugePair: qsc.reqsGaugePair,\n\t\t\texecSeatsGauge: qsc.execSeatsGauge,\n\t\t\tseatDemandIntegrator: qsc.seatDemandIntegrator,\n\t\t\tqCfg: qsc.qCfg,\n\t\t\tcurrentR: 0,\n\t\t\tlastRealTime: qsc.factory.clock.Now(),\n\t\t}\n\t\tqs.promiseFactory = qsc.factory.promiseFactoryFactory(qs)\n\t}\n\tqs.setConfiguration(context.Background(), qsc.qCfg, qsc.dealer, dCfg)\n\treturn qs\n}","line":{"from":210,"to":227}} {"id":100018941,"name":"createQueues","signature":"func createQueues(n, baseIndex int) []*queue","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"// createQueues is a helper method for initializing an array of n queues\nfunc createQueues(n, baseIndex int) []*queue {\n\tfqqueues := make([]*queue, n)\n\tfor i := 0; i \u003c n; i++ {\n\t\tfqqueues[i] = \u0026queue{index: baseIndex + i, requests: newRequestFIFO()}\n\t}\n\treturn fqqueues\n}","line":{"from":229,"to":236}} {"id":100018942,"name":"BeginConfigChange","signature":"func (qs *queueSet) BeginConfigChange(qCfg fq.QueuingConfig) (fq.QueueSetCompleter, error)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"func (qs *queueSet) BeginConfigChange(qCfg fq.QueuingConfig) (fq.QueueSetCompleter, error) {\n\tdealer, err := checkConfig(qCfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026queueSetCompleter{\n\t\ttheSet: qs,\n\t\tqCfg: qCfg,\n\t\tdealer: dealer}, nil\n}","line":{"from":238,"to":247}} {"id":100018943,"name":"setConfiguration","signature":"func (qs *queueSet) setConfiguration(ctx context.Context, qCfg fq.QueuingConfig, dealer *shufflesharding.Dealer, dCfg fq.DispatchingConfig)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"// setConfiguration is used to set the configuration for a queueSet.\n// Update handling for when fields are updated is handled here as well -\n// eg: if DesiredNum is increased, setConfiguration reconciles by\n// adding more queues.\nfunc (qs *queueSet) setConfiguration(ctx context.Context, qCfg fq.QueuingConfig, dealer *shufflesharding.Dealer, dCfg fq.DispatchingConfig) {\n\tqs.lockAndSyncTime(ctx)\n\tdefer qs.lock.Unlock()\n\n\tif qCfg.DesiredNumQueues \u003e 0 {\n\t\t// Adding queues is the only thing that requires immediate action\n\t\t// Removing queues is handled by attrition, removing a queue when\n\t\t// it goes empty and there are too many.\n\t\tnumQueues := len(qs.queues)\n\t\tif qCfg.DesiredNumQueues \u003e numQueues {\n\t\t\tqs.queues = append(qs.queues,\n\t\t\t\tcreateQueues(qCfg.DesiredNumQueues-numQueues, len(qs.queues))...)\n\t\t}\n\t} else {\n\t\tqCfg.QueueLengthLimit = qs.qCfg.QueueLengthLimit\n\t\tqCfg.HandSize = qs.qCfg.HandSize\n\t\tqCfg.RequestWaitLimit = qs.qCfg.RequestWaitLimit\n\t}\n\n\tqs.qCfg = qCfg\n\tqs.dCfg = dCfg\n\tqs.dealer = dealer\n\tqll := qCfg.QueueLengthLimit\n\tif qll \u003c 1 {\n\t\tqll = 1\n\t}\n\tif qCfg.DesiredNumQueues \u003e 0 {\n\t\tqll *= qCfg.DesiredNumQueues\n\t}\n\tqs.reqsGaugePair.RequestsWaiting.SetDenominator(float64(qll))\n\tqs.reqsGaugePair.RequestsExecuting.SetDenominator(float64(dCfg.ConcurrencyLimit))\n\tqs.execSeatsGauge.SetDenominator(float64(dCfg.ConcurrencyLimit))\n\n\tqs.dispatchAsMuchAsPossibleLocked()\n}","line":{"from":249,"to":287}} {"id":100018944,"name":"StartRequest","signature":"func (qs *queueSet) StartRequest(ctx context.Context, workEstimate *fqrequest.WorkEstimate, hashValue uint64, flowDistinguisher, fsName string, descr1, descr2 interface{}, queueNoteFn fq.QueueNoteFn) (fq.Request, bool)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"// StartRequest begins the process of handling a request. We take the\n// approach of updating the metrics about total requests queued and\n// executing at each point where there is a change in that quantity,\n// because the metrics --- and only the metrics --- track that\n// quantity per FlowSchema.\n// The queueSet's promiseFactory is invoked once if the returned Request is non-nil,\n// not invoked if the Request is nil.\nfunc (qs *queueSet) StartRequest(ctx context.Context, workEstimate *fqrequest.WorkEstimate, hashValue uint64, flowDistinguisher, fsName string, descr1, descr2 interface{}, queueNoteFn fq.QueueNoteFn) (fq.Request, bool) {\n\tqs.lockAndSyncTime(ctx)\n\tdefer qs.lock.Unlock()\n\tvar req *request\n\n\t// ========================================================================\n\t// Step 0:\n\t// Apply only concurrency limit, if zero queues desired\n\tif qs.qCfg.DesiredNumQueues \u003c 1 {\n\t\tif !qs.canAccommodateSeatsLocked(workEstimate.MaxSeats()) {\n\t\t\tklog.V(5).Infof(\"QS(%s): rejecting request %q %#+v %#+v because %d seats are asked for, %d seats are in use (%d are executing) and the limit is %d\",\n\t\t\t\tqs.qCfg.Name, fsName, descr1, descr2, workEstimate, qs.totSeatsInUse, qs.totRequestsExecuting, qs.dCfg.ConcurrencyLimit)\n\t\t\tqs.totRequestsRejected++\n\t\t\tmetrics.AddReject(ctx, qs.qCfg.Name, fsName, \"concurrency-limit\")\n\t\t\treturn nil, qs.isIdleLocked()\n\t\t}\n\t\treq = qs.dispatchSansQueueLocked(ctx, workEstimate, flowDistinguisher, fsName, descr1, descr2)\n\t\treturn req, false\n\t}\n\n\t// ========================================================================\n\t// Step 1:\n\t// 1) Start with shuffle sharding, to pick a queue.\n\t// 2) Reject old requests that have been waiting too long\n\t// 3) Reject current request if there is not enough concurrency shares and\n\t// we are at max queue length\n\t// 4) If not rejected, create a request and enqueue\n\treq = qs.timeoutOldRequestsAndRejectOrEnqueueLocked(ctx, workEstimate, hashValue, flowDistinguisher, fsName, descr1, descr2, queueNoteFn)\n\t// req == nil means that the request was rejected - no remaining\n\t// concurrency shares and at max queue length already\n\tif req == nil {\n\t\tklog.V(5).Infof(\"QS(%s): rejecting request %q %#+v %#+v due to queue full\", qs.qCfg.Name, fsName, descr1, descr2)\n\t\tqs.totRequestsRejected++\n\t\tmetrics.AddReject(ctx, qs.qCfg.Name, fsName, \"queue-full\")\n\t\treturn nil, qs.isIdleLocked()\n\t}\n\n\t// ========================================================================\n\t// Step 2:\n\t// The next step is to invoke the method that dequeues as much\n\t// as possible.\n\t// This method runs a loop, as long as there are non-empty\n\t// queues and the number currently executing is less than the\n\t// assured concurrency value. The body of the loop uses the\n\t// fair queuing technique to pick a queue and dispatch a\n\t// request from that queue.\n\tqs.dispatchAsMuchAsPossibleLocked()\n\n\treturn req, false\n}","line":{"from":304,"to":360}} {"id":100018945,"name":"ordinaryPromiseFactoryFactory","signature":"func ordinaryPromiseFactoryFactory(qs *queueSet) promiseFactory","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"// ordinaryPromiseFactoryFactory is the promiseFactoryFactory that\n// a queueSetFactory would ordinarily use.\n// Test code might use something different.\nfunc ordinaryPromiseFactoryFactory(qs *queueSet) promiseFactory {\n\treturn promise.NewWriteOnce\n}","line":{"from":362,"to":367}} {"id":100018946,"name":"MaxSeats","signature":"func (req *request) MaxSeats() int","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"// MaxSeats returns the maximum number of seats this request requires, it is\n// the maxumum of the two - WorkEstimate.InitialSeats, WorkEstimate.FinalSeats.\nfunc (req *request) MaxSeats() int {\n\treturn req.workEstimate.MaxSeats()\n}","line":{"from":369,"to":373}} {"id":100018947,"name":"InitialSeats","signature":"func (req *request) InitialSeats() int","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"func (req *request) InitialSeats() int {\n\treturn int(req.workEstimate.InitialSeats)\n}","line":{"from":375,"to":377}} {"id":100018948,"name":"NoteQueued","signature":"func (req *request) NoteQueued(inQueue bool)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"func (req *request) NoteQueued(inQueue bool) {\n\tif req.queueNoteFn != nil {\n\t\treq.queueNoteFn(inQueue)\n\t}\n}","line":{"from":379,"to":383}} {"id":100018949,"name":"Finish","signature":"func (req *request) Finish(execFn func()) bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"func (req *request) Finish(execFn func()) bool {\n\texec, idle := req.wait()\n\tif !exec {\n\t\treturn idle\n\t}\n\tfunc() {\n\t\tdefer func() {\n\t\t\tidle = req.qs.finishRequestAndDispatchAsMuchAsPossible(req)\n\t\t}()\n\n\t\texecFn()\n\t}()\n\n\treturn idle\n}","line":{"from":385,"to":399}} {"id":100018950,"name":"wait","signature":"func (req *request) wait() (bool, bool)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"func (req *request) wait() (bool, bool) {\n\tqs := req.qs\n\n\t// ========================================================================\n\t// Step 3:\n\t// The final step is to wait on a decision from\n\t// somewhere and then act on it.\n\tdecisionAny := req.decision.Get()\n\tqs.lockAndSyncTime(req.ctx)\n\tdefer qs.lock.Unlock()\n\tif req.waitStarted {\n\t\t// This can not happen, because the client is forbidden to\n\t\t// call Wait twice on the same request\n\t\tklog.Errorf(\"Duplicate call to the Wait method! Immediately returning execute=false. QueueSet=%s, startTime=%s, descr1=%#+v, descr2=%#+v\", req.qs.qCfg.Name, req.startTime, req.descr1, req.descr2)\n\t\treturn false, qs.isIdleLocked()\n\t}\n\treq.waitStarted = true\n\tswitch decisionAny {\n\tcase decisionReject:\n\t\tklog.V(5).Infof(\"QS(%s): request %#+v %#+v timed out after being enqueued\\n\", qs.qCfg.Name, req.descr1, req.descr2)\n\t\tqs.totRequestsRejected++\n\t\tqs.totRequestsTimedout++\n\t\tmetrics.AddReject(req.ctx, qs.qCfg.Name, req.fsName, \"time-out\")\n\t\treturn false, qs.isIdleLocked()\n\tcase decisionCancel:\n\tcase decisionExecute:\n\t\tklog.V(5).Infof(\"QS(%s): Dispatching request %#+v %#+v from its queue\", qs.qCfg.Name, req.descr1, req.descr2)\n\t\treturn true, false\n\tdefault:\n\t\t// This can not happen, all possible values are handled above\n\t\tklog.Errorf(\"QS(%s): Impossible decision (type %T, value %#+v) for request %#+v %#+v! Treating as cancel\", qs.qCfg.Name, decisionAny, decisionAny, req.descr1, req.descr2)\n\t}\n\t// TODO(aaron-prindle) add metrics for this case\n\tklog.V(5).Infof(\"QS(%s): Ejecting request %#+v %#+v from its queue\", qs.qCfg.Name, req.descr1, req.descr2)\n\t// remove the request from the queue as it has timed out\n\tqueue := req.queue\n\tif req.removeFromQueueLocked() != nil {\n\t\tdefer qs.boundNextDispatchLocked(queue)\n\t\tqs.totRequestsWaiting--\n\t\tqs.totSeatsWaiting -= req.MaxSeats()\n\t\tqs.totRequestsRejected++\n\t\tqs.totRequestsCancelled++\n\t\tmetrics.AddReject(req.ctx, qs.qCfg.Name, req.fsName, \"cancelled\")\n\t\tmetrics.AddRequestsInQueues(req.ctx, qs.qCfg.Name, req.fsName, -1)\n\t\treq.NoteQueued(false)\n\t\tqs.reqsGaugePair.RequestsWaiting.Add(-1)\n\t\tqs.seatDemandIntegrator.Set(float64(qs.totSeatsInUse + qs.totSeatsWaiting))\n\t}\n\treturn false, qs.isIdleLocked()\n}","line":{"from":401,"to":450}} {"id":100018951,"name":"IsIdle","signature":"func (qs *queueSet) IsIdle() bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"func (qs *queueSet) IsIdle() bool {\n\tqs.lock.Lock()\n\tdefer qs.lock.Unlock()\n\treturn qs.isIdleLocked()\n}","line":{"from":452,"to":456}} {"id":100018952,"name":"isIdleLocked","signature":"func (qs *queueSet) isIdleLocked() bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"func (qs *queueSet) isIdleLocked() bool {\n\treturn qs.totRequestsWaiting == 0 \u0026\u0026 qs.totRequestsExecuting == 0\n}","line":{"from":458,"to":460}} {"id":100018953,"name":"lockAndSyncTime","signature":"func (qs *queueSet) lockAndSyncTime(ctx context.Context)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"// lockAndSyncTime acquires the lock and updates the virtual time.\n// Doing them together avoids the mistake of modifying some queue state\n// before calling syncTimeLocked.\nfunc (qs *queueSet) lockAndSyncTime(ctx context.Context) {\n\tqs.lock.Lock()\n\tqs.syncTimeLocked(ctx)\n}","line":{"from":462,"to":468}} {"id":100018954,"name":"syncTimeLocked","signature":"func (qs *queueSet) syncTimeLocked(ctx context.Context)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"// syncTimeLocked updates the virtual time based on the assumption\n// that the current state of the queues has been in effect since\n// `qs.lastRealTime`. Thus, it should be invoked after acquiring the\n// lock and before modifying the state of any queue.\nfunc (qs *queueSet) syncTimeLocked(ctx context.Context) {\n\trealNow := qs.clock.Now()\n\ttimeSinceLast := realNow.Sub(qs.lastRealTime)\n\tqs.lastRealTime = realNow\n\tprevR := qs.currentR\n\tincrR := fqrequest.SeatsTimesDuration(qs.getVirtualTimeRatioLocked(), timeSinceLast)\n\tqs.currentR = prevR + incrR\n\tswitch {\n\tcase prevR \u003e qs.currentR:\n\t\tklog.ErrorS(errors.New(\"queueset::currentR overflow\"), \"Overflow\", \"QS\", qs.qCfg.Name, \"when\", realNow.Format(nsTimeFmt), \"prevR\", prevR, \"incrR\", incrR, \"currentR\", qs.currentR)\n\tcase qs.currentR \u003e= highR:\n\t\tqs.advanceEpoch(ctx, realNow, incrR)\n\t}\n\tmetrics.SetCurrentR(qs.qCfg.Name, qs.currentR.ToFloat())\n}","line":{"from":470,"to":488}} {"id":100018955,"name":"advanceEpoch","signature":"func (qs *queueSet) advanceEpoch(ctx context.Context, now time.Time, incrR fqrequest.SeatSeconds)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"// advanceEpoch subtracts rDecrement from the global progress meter R\n// and all the readings that have been taked from that meter.\n// The now and incrR parameters are only used to add info to the log messages.\nfunc (qs *queueSet) advanceEpoch(ctx context.Context, now time.Time, incrR fqrequest.SeatSeconds) {\n\toldR := qs.currentR\n\tqs.currentR -= rDecrement\n\tklog.InfoS(\"Advancing epoch\", \"QS\", qs.qCfg.Name, \"when\", now.Format(nsTimeFmt), \"oldR\", oldR, \"newR\", qs.currentR, \"incrR\", incrR)\n\tsuccess := true\n\tfor qIdx, queue := range qs.queues {\n\t\tif queue.requests.Length() == 0 \u0026\u0026 queue.requestsExecuting == 0 {\n\t\t\t// Do not just decrement, the value could be quite outdated.\n\t\t\t// It is safe to reset to zero in this case, because the next request\n\t\t\t// will overwrite the zero with `qs.currentR`.\n\t\t\tqueue.nextDispatchR = 0\n\t\t\tcontinue\n\t\t}\n\t\toldNextDispatchR := queue.nextDispatchR\n\t\tqueue.nextDispatchR -= rDecrement\n\t\tif queue.nextDispatchR \u003e oldNextDispatchR {\n\t\t\tklog.ErrorS(errors.New(\"queue::nextDispatchR underflow\"), \"Underflow\", \"QS\", qs.qCfg.Name, \"queue\", qIdx, \"oldNextDispatchR\", oldNextDispatchR, \"newNextDispatchR\", queue.nextDispatchR, \"incrR\", incrR)\n\t\t\tsuccess = false\n\t\t}\n\t\tqueue.requests.Walk(func(req *request) bool {\n\t\t\toldArrivalR := req.arrivalR\n\t\t\treq.arrivalR -= rDecrement\n\t\t\tif req.arrivalR \u003e oldArrivalR {\n\t\t\t\tklog.ErrorS(errors.New(\"request::arrivalR underflow\"), \"Underflow\", \"QS\", qs.qCfg.Name, \"queue\", qIdx, \"request\", *req, \"oldArrivalR\", oldArrivalR, \"incrR\", incrR)\n\t\t\t\tsuccess = false\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t}\n\tmetrics.AddEpochAdvance(ctx, qs.qCfg.Name, success)\n}","line":{"from":498,"to":531}} {"id":100018956,"name":"getVirtualTimeRatioLocked","signature":"func (qs *queueSet) getVirtualTimeRatioLocked() float64","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"// getVirtualTimeRatio calculates the rate at which virtual time has\n// been advancing, according to the logic in `doc.go`.\nfunc (qs *queueSet) getVirtualTimeRatioLocked() float64 {\n\tactiveQueues := 0\n\tseatsRequested := 0\n\tfor _, queue := range qs.queues {\n\t\t// here we want the sum of the maximum width of the requests in this queue since our\n\t\t// goal is to find the maximum rate at which the queue could work.\n\t\tseatsRequested += (queue.seatsInUse + queue.requests.QueueSum().MaxSeatsSum)\n\t\tif queue.requests.Length() \u003e 0 || queue.requestsExecuting \u003e 0 {\n\t\t\tactiveQueues++\n\t\t}\n\t}\n\tif activeQueues == 0 {\n\t\treturn 0\n\t}\n\treturn math.Min(float64(seatsRequested), float64(qs.dCfg.ConcurrencyLimit)) / float64(activeQueues)\n}","line":{"from":533,"to":550}} {"id":100018957,"name":"timeoutOldRequestsAndRejectOrEnqueueLocked","signature":"func (qs *queueSet) timeoutOldRequestsAndRejectOrEnqueueLocked(ctx context.Context, workEstimate *fqrequest.WorkEstimate, hashValue uint64, flowDistinguisher, fsName string, descr1, descr2 interface{}, queueNoteFn fq.QueueNoteFn) *request","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"// timeoutOldRequestsAndRejectOrEnqueueLocked encapsulates the logic required\n// to validate and enqueue a request for the queueSet/QueueSet:\n// 1) Start with shuffle sharding, to pick a queue.\n// 2) Reject old requests that have been waiting too long\n// 3) Reject current request if there is not enough concurrency shares and\n// we are at max queue length\n// 4) If not rejected, create a request and enqueue\n// returns the enqueud request on a successful enqueue\n// returns nil in the case that there is no available concurrency or\n// the queuelengthlimit has been reached\nfunc (qs *queueSet) timeoutOldRequestsAndRejectOrEnqueueLocked(ctx context.Context, workEstimate *fqrequest.WorkEstimate, hashValue uint64, flowDistinguisher, fsName string, descr1, descr2 interface{}, queueNoteFn fq.QueueNoteFn) *request {\n\t// Start with the shuffle sharding, to pick a queue.\n\tqueueIdx := qs.shuffleShardLocked(hashValue, descr1, descr2)\n\tqueue := qs.queues[queueIdx]\n\t// The next step is the logic to reject requests that have been waiting too long\n\tqs.removeTimedOutRequestsFromQueueToBoundLocked(queue, fsName)\n\t// NOTE: currently timeout is only checked for each new request. This means that there can be\n\t// requests that are in the queue longer than the timeout if there are no new requests\n\t// We prefer the simplicity over the promptness, at least for now.\n\n\tdefer qs.boundNextDispatchLocked(queue)\n\n\t// Create a request and enqueue\n\treq := \u0026request{\n\t\tqs: qs,\n\t\tfsName: fsName,\n\t\tflowDistinguisher: flowDistinguisher,\n\t\tctx: ctx,\n\t\tdecision: qs.promiseFactory(nil, ctx.Done(), decisionCancel),\n\t\tarrivalTime: qs.clock.Now(),\n\t\tarrivalR: qs.currentR,\n\t\tqueue: queue,\n\t\tdescr1: descr1,\n\t\tdescr2: descr2,\n\t\tqueueNoteFn: queueNoteFn,\n\t\tworkEstimate: qs.completeWorkEstimate(workEstimate),\n\t}\n\tif ok := qs.rejectOrEnqueueToBoundLocked(req); !ok {\n\t\treturn nil\n\t}\n\tmetrics.ObserveQueueLength(ctx, qs.qCfg.Name, fsName, queue.requests.Length())\n\treturn req\n}","line":{"from":552,"to":594}} {"id":100018958,"name":"shuffleShardLocked","signature":"func (qs *queueSet) shuffleShardLocked(hashValue uint64, descr1, descr2 interface{}) int","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"// shuffleShardLocked uses shuffle sharding to select a queue index\n// using the given hashValue and the shuffle sharding parameters of the queueSet.\nfunc (qs *queueSet) shuffleShardLocked(hashValue uint64, descr1, descr2 interface{}) int {\n\tvar backHand [8]int\n\t// Deal into a data structure, so that the order of visit below is not necessarily the order of the deal.\n\t// This removes bias in the case of flows with overlapping hands.\n\thand := qs.dealer.DealIntoHand(hashValue, backHand[:])\n\thandSize := len(hand)\n\toffset := qs.enqueues % handSize\n\tqs.enqueues++\n\tbestQueueIdx := -1\n\tminQueueSeatSeconds := fqrequest.MaxSeatSeconds\n\tfor i := 0; i \u003c handSize; i++ {\n\t\tqueueIdx := hand[(offset+i)%handSize]\n\t\tqueue := qs.queues[queueIdx]\n\t\tqueueSum := queue.requests.QueueSum()\n\n\t\t// this is the total amount of work in seat-seconds for requests\n\t\t// waiting in this queue, we will select the queue with the minimum.\n\t\tthisQueueSeatSeconds := queueSum.TotalWorkSum\n\t\tklog.V(7).Infof(\"QS(%s): For request %#+v %#+v considering queue %d with sum: %#v and %d seats in use, nextDispatchR=%v\", qs.qCfg.Name, descr1, descr2, queueIdx, queueSum, queue.seatsInUse, queue.nextDispatchR)\n\t\tif thisQueueSeatSeconds \u003c minQueueSeatSeconds {\n\t\t\tminQueueSeatSeconds = thisQueueSeatSeconds\n\t\t\tbestQueueIdx = queueIdx\n\t\t}\n\t}\n\tif klogV := klog.V(6); klogV.Enabled() {\n\t\tchosenQueue := qs.queues[bestQueueIdx]\n\t\tklogV.Infof(\"QS(%s) at t=%s R=%v: For request %#+v %#+v chose queue %d, with sum: %#v \u0026 %d seats in use \u0026 nextDispatchR=%v\", qs.qCfg.Name, qs.clock.Now().Format(nsTimeFmt), qs.currentR, descr1, descr2, bestQueueIdx, chosenQueue.requests.QueueSum(), chosenQueue.seatsInUse, chosenQueue.nextDispatchR)\n\t}\n\treturn bestQueueIdx\n}","line":{"from":596,"to":627}} {"id":100018959,"name":"removeTimedOutRequestsFromQueueToBoundLocked","signature":"func (qs *queueSet) removeTimedOutRequestsFromQueueToBoundLocked(queue *queue, fsName string)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"// removeTimedOutRequestsFromQueueToBoundLocked rejects old requests that have been enqueued\n// past the requestWaitLimit\nfunc (qs *queueSet) removeTimedOutRequestsFromQueueToBoundLocked(queue *queue, fsName string) {\n\ttimeoutCount := 0\n\tdisqueueSeats := 0\n\tnow := qs.clock.Now()\n\treqs := queue.requests\n\t// reqs are sorted oldest -\u003e newest\n\t// can short circuit loop (break) if oldest requests are not timing out\n\t// as newer requests also will not have timed out\n\n\t// now - requestWaitLimit = arrivalLimit\n\tarrivalLimit := now.Add(-qs.qCfg.RequestWaitLimit)\n\treqs.Walk(func(req *request) bool {\n\t\tif arrivalLimit.After(req.arrivalTime) {\n\t\t\tif req.decision.Set(decisionReject) \u0026\u0026 req.removeFromQueueLocked() != nil {\n\t\t\t\ttimeoutCount++\n\t\t\t\tdisqueueSeats += req.MaxSeats()\n\t\t\t\treq.NoteQueued(false)\n\t\t\t\tmetrics.AddRequestsInQueues(req.ctx, qs.qCfg.Name, req.fsName, -1)\n\t\t\t}\n\t\t\t// we need to check if the next request has timed out.\n\t\t\treturn true\n\t\t}\n\t\t// since reqs are sorted oldest -\u003e newest, we are done here.\n\t\treturn false\n\t})\n\n\t// remove timed out requests from queue\n\tif timeoutCount \u003e 0 {\n\t\tqs.totRequestsWaiting -= timeoutCount\n\t\tqs.totSeatsWaiting -= disqueueSeats\n\t\tqs.reqsGaugePair.RequestsWaiting.Add(float64(-timeoutCount))\n\t\tqs.seatDemandIntegrator.Set(float64(qs.totSeatsInUse + qs.totSeatsWaiting))\n\t}\n}","line":{"from":629,"to":664}} {"id":100018960,"name":"rejectOrEnqueueToBoundLocked","signature":"func (qs *queueSet) rejectOrEnqueueToBoundLocked(request *request) bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"// rejectOrEnqueueToBoundLocked rejects or enqueues the newly arrived\n// request, which has been assigned to a queue. If up against the\n// queue length limit and the concurrency limit then returns false.\n// Otherwise enqueues and returns true.\nfunc (qs *queueSet) rejectOrEnqueueToBoundLocked(request *request) bool {\n\tqueue := request.queue\n\tcurQueueLength := queue.requests.Length()\n\t// rejects the newly arrived request if resource criteria not met\n\tif qs.totSeatsInUse \u003e= qs.dCfg.ConcurrencyLimit \u0026\u0026\n\t\tcurQueueLength \u003e= qs.qCfg.QueueLengthLimit {\n\t\treturn false\n\t}\n\n\tqs.enqueueToBoundLocked(request)\n\treturn true\n}","line":{"from":666,"to":681}} {"id":100018961,"name":"enqueueToBoundLocked","signature":"func (qs *queueSet) enqueueToBoundLocked(request *request)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"// enqueues a request into its queue.\nfunc (qs *queueSet) enqueueToBoundLocked(request *request) {\n\tqueue := request.queue\n\tnow := qs.clock.Now()\n\tif queue.requests.Length() == 0 \u0026\u0026 queue.requestsExecuting == 0 {\n\t\t// the queue’s start R is set to the virtual time.\n\t\tqueue.nextDispatchR = qs.currentR\n\t\tklogV := klog.V(6)\n\t\tif klogV.Enabled() {\n\t\t\tklogV.Infof(\"QS(%s) at t=%s R=%v: initialized queue %d start R due to request %#+v %#+v\", qs.qCfg.Name, now.Format(nsTimeFmt), queue.nextDispatchR, queue.index, request.descr1, request.descr2)\n\t\t}\n\t}\n\trequest.removeFromQueueLocked = queue.requests.Enqueue(request)\n\tqs.totRequestsWaiting++\n\tqs.totSeatsWaiting += request.MaxSeats()\n\tmetrics.AddRequestsInQueues(request.ctx, qs.qCfg.Name, request.fsName, 1)\n\trequest.NoteQueued(true)\n\tqs.reqsGaugePair.RequestsWaiting.Add(1)\n\tqs.seatDemandIntegrator.Set(float64(qs.totSeatsInUse + qs.totSeatsWaiting))\n}","line":{"from":683,"to":702}} {"id":100018962,"name":"dispatchAsMuchAsPossibleLocked","signature":"func (qs *queueSet) dispatchAsMuchAsPossibleLocked()","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"// dispatchAsMuchAsPossibleLocked does as many dispatches as possible now.\nfunc (qs *queueSet) dispatchAsMuchAsPossibleLocked() {\n\tfor qs.totRequestsWaiting != 0 \u0026\u0026 qs.totSeatsInUse \u003c qs.dCfg.ConcurrencyLimit \u0026\u0026 qs.dispatchLocked() {\n\t}\n}","line":{"from":704,"to":708}} {"id":100018963,"name":"dispatchSansQueueLocked","signature":"func (qs *queueSet) dispatchSansQueueLocked(ctx context.Context, workEstimate *fqrequest.WorkEstimate, flowDistinguisher, fsName string, descr1, descr2 interface{}) *request","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"func (qs *queueSet) dispatchSansQueueLocked(ctx context.Context, workEstimate *fqrequest.WorkEstimate, flowDistinguisher, fsName string, descr1, descr2 interface{}) *request {\n\t// does not call metrics.SetDispatchMetrics because there is no queuing and thus no interesting virtual world\n\tnow := qs.clock.Now()\n\treq := \u0026request{\n\t\tqs: qs,\n\t\tfsName: fsName,\n\t\tflowDistinguisher: flowDistinguisher,\n\t\tctx: ctx,\n\t\tstartTime: now,\n\t\tdecision: qs.promiseFactory(decisionExecute, ctx.Done(), decisionCancel),\n\t\tarrivalTime: now,\n\t\tarrivalR: qs.currentR,\n\t\tdescr1: descr1,\n\t\tdescr2: descr2,\n\t\tworkEstimate: qs.completeWorkEstimate(workEstimate),\n\t}\n\tqs.totRequestsExecuting++\n\tqs.totSeatsInUse += req.MaxSeats()\n\tmetrics.AddRequestsExecuting(ctx, qs.qCfg.Name, fsName, 1)\n\tmetrics.AddRequestConcurrencyInUse(qs.qCfg.Name, fsName, req.MaxSeats())\n\tqs.reqsGaugePair.RequestsExecuting.Add(1)\n\tqs.execSeatsGauge.Add(float64(req.MaxSeats()))\n\tqs.seatDemandIntegrator.Set(float64(qs.totSeatsInUse + qs.totSeatsWaiting))\n\tklogV := klog.V(5)\n\tif klogV.Enabled() {\n\t\tklogV.Infof(\"QS(%s) at t=%s R=%v: immediate dispatch of request %q %#+v %#+v, qs will have %d executing\", qs.qCfg.Name, now.Format(nsTimeFmt), qs.currentR, fsName, descr1, descr2, qs.totRequestsExecuting)\n\t}\n\treturn req\n}","line":{"from":710,"to":738}} {"id":100018964,"name":"dispatchLocked","signature":"func (qs *queueSet) dispatchLocked() bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"// dispatchLocked uses the Fair Queuing for Server Requests method to\n// select a queue and dispatch the oldest request in that queue. The\n// return value indicates whether a request was dequeued; this will\n// be false when either all queues are empty or the request at the head\n// of the next queue cannot be dispatched.\nfunc (qs *queueSet) dispatchLocked() bool {\n\tqueue, request := qs.findDispatchQueueToBoundLocked()\n\tif queue == nil {\n\t\treturn false\n\t}\n\tif request == nil { // This should never happen. But if it does...\n\t\treturn false\n\t}\n\tqs.totRequestsWaiting--\n\tqs.totSeatsWaiting -= request.MaxSeats()\n\tmetrics.AddRequestsInQueues(request.ctx, qs.qCfg.Name, request.fsName, -1)\n\trequest.NoteQueued(false)\n\tqs.reqsGaugePair.RequestsWaiting.Add(-1)\n\tdefer qs.boundNextDispatchLocked(queue)\n\tif !request.decision.Set(decisionExecute) {\n\t\tqs.seatDemandIntegrator.Set(float64(qs.totSeatsInUse + qs.totSeatsWaiting))\n\t\treturn true\n\t}\n\trequest.startTime = qs.clock.Now()\n\t// At this moment the request leaves its queue and starts\n\t// executing. We do not recognize any interim state between\n\t// \"queued\" and \"executing\". While that means \"executing\"\n\t// includes a little overhead from this package, this is not a\n\t// problem because other overhead is also included.\n\tqs.totRequestsExecuting++\n\tqs.totSeatsInUse += request.MaxSeats()\n\tqueue.requestsExecuting++\n\tqueue.seatsInUse += request.MaxSeats()\n\tmetrics.AddRequestsExecuting(request.ctx, qs.qCfg.Name, request.fsName, 1)\n\tmetrics.AddRequestConcurrencyInUse(qs.qCfg.Name, request.fsName, request.MaxSeats())\n\tqs.reqsGaugePair.RequestsExecuting.Add(1)\n\tqs.execSeatsGauge.Add(float64(request.MaxSeats()))\n\tqs.seatDemandIntegrator.Set(float64(qs.totSeatsInUse + qs.totSeatsWaiting))\n\tklogV := klog.V(6)\n\tif klogV.Enabled() {\n\t\tklogV.Infof(\"QS(%s) at t=%s R=%v: dispatching request %#+v %#+v work %v from queue %d with start R %v, queue will have %d waiting \u0026 %d requests occupying %d seats, set will have %d seats occupied\",\n\t\t\tqs.qCfg.Name, request.startTime.Format(nsTimeFmt), qs.currentR, request.descr1, request.descr2,\n\t\t\trequest.workEstimate, queue.index, queue.nextDispatchR, queue.requests.Length(), queue.requestsExecuting, queue.seatsInUse, qs.totSeatsInUse)\n\t}\n\t// When a request is dequeued for service -\u003e qs.virtualStart += G * width\n\tif request.totalWork() \u003e rDecrement/100 { // A single increment should never be so big\n\t\tklog.Errorf(\"QS(%s) at t=%s R=%v: dispatching request %#+v %#+v with implausibly high work %v from queue %d with start R %v\",\n\t\t\tqs.qCfg.Name, request.startTime.Format(nsTimeFmt), qs.currentR, request.descr1, request.descr2,\n\t\t\trequest.workEstimate, queue.index, queue.nextDispatchR)\n\t}\n\tqueue.nextDispatchR += request.totalWork()\n\treturn true\n}","line":{"from":740,"to":792}} {"id":100018965,"name":"canAccommodateSeatsLocked","signature":"func (qs *queueSet) canAccommodateSeatsLocked(seats int) bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"// canAccommodateSeatsLocked returns true if this queueSet has enough\n// seats available to accommodate a request with the given number of seats,\n// otherwise it returns false.\nfunc (qs *queueSet) canAccommodateSeatsLocked(seats int) bool {\n\tswitch {\n\tcase seats \u003e qs.dCfg.ConcurrencyLimit:\n\t\t// we have picked the queue with the minimum virtual finish time, but\n\t\t// the number of seats this request asks for exceeds the concurrency limit.\n\t\t// TODO: this is a quick fix for now, once we have borrowing in place we will not need it\n\t\tif qs.totRequestsExecuting == 0 {\n\t\t\t// TODO: apply additional lateny associated with this request, as described in the KEP\n\t\t\treturn true\n\t\t}\n\t\t// wait for all \"currently\" executing requests in this queueSet\n\t\t// to finish before we can execute this request.\n\t\treturn false\n\tcase qs.totSeatsInUse+seats \u003e qs.dCfg.ConcurrencyLimit:\n\t\treturn false\n\t}\n\n\treturn true\n}","line":{"from":794,"to":815}} {"id":100018966,"name":"findDispatchQueueToBoundLocked","signature":"func (qs *queueSet) findDispatchQueueToBoundLocked() (*queue, *request)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"// findDispatchQueueToBoundLocked examines the queues in round robin order and\n// returns the first one of those for which the virtual finish time of\n// the oldest waiting request is minimal, and also returns that request.\n// Returns nils if the head of the selected queue can not be dispatched now,\n// in which case the caller does not need to follow up with`qs.boundNextDispatchLocked`.\nfunc (qs *queueSet) findDispatchQueueToBoundLocked() (*queue, *request) {\n\tminVirtualFinish := fqrequest.MaxSeatSeconds\n\tsMin := fqrequest.MaxSeatSeconds\n\tdsMin := fqrequest.MaxSeatSeconds\n\tsMax := fqrequest.MinSeatSeconds\n\tdsMax := fqrequest.MinSeatSeconds\n\tvar minQueue *queue\n\tvar minIndex int\n\tnq := len(qs.queues)\n\tfor range qs.queues {\n\t\tqs.robinIndex = (qs.robinIndex + 1) % nq\n\t\tqueue := qs.queues[qs.robinIndex]\n\t\toldestWaiting, _ := queue.requests.Peek()\n\t\tif oldestWaiting != nil {\n\t\t\tsMin = ssMin(sMin, queue.nextDispatchR)\n\t\t\tsMax = ssMax(sMax, queue.nextDispatchR)\n\t\t\testimatedWorkInProgress := fqrequest.SeatsTimesDuration(float64(queue.seatsInUse), qs.estimatedServiceDuration)\n\t\t\tdsMin = ssMin(dsMin, queue.nextDispatchR-estimatedWorkInProgress)\n\t\t\tdsMax = ssMax(dsMax, queue.nextDispatchR-estimatedWorkInProgress)\n\t\t\tcurrentVirtualFinish := queue.nextDispatchR + oldestWaiting.totalWork()\n\t\t\tklog.V(11).InfoS(\"Considering queue to dispatch\", \"queueSet\", qs.qCfg.Name, \"queue\", qs.robinIndex, \"finishR\", currentVirtualFinish)\n\t\t\tif currentVirtualFinish \u003c minVirtualFinish {\n\t\t\t\tminVirtualFinish = currentVirtualFinish\n\t\t\t\tminQueue = queue\n\t\t\t\tminIndex = qs.robinIndex\n\t\t\t}\n\t\t}\n\t}\n\n\toldestReqFromMinQueue, _ := minQueue.requests.Peek()\n\tif oldestReqFromMinQueue == nil {\n\t\t// This cannot happen\n\t\tklog.ErrorS(errors.New(\"selected queue is empty\"), \"Impossible\", \"queueSet\", qs.qCfg.Name)\n\t\treturn nil, nil\n\t}\n\tif !qs.canAccommodateSeatsLocked(oldestReqFromMinQueue.MaxSeats()) {\n\t\t// since we have not picked the queue with the minimum virtual finish\n\t\t// time, we are not going to advance the round robin index here.\n\t\tklogV := klog.V(4)\n\t\tif klogV.Enabled() {\n\t\t\tklogV.Infof(\"QS(%s): request %v %v seats %d cannot be dispatched from queue %d, waiting for currently executing requests to complete, %d requests are occupying %d seats and the limit is %d\",\n\t\t\t\tqs.qCfg.Name, oldestReqFromMinQueue.descr1, oldestReqFromMinQueue.descr2, oldestReqFromMinQueue.MaxSeats(), minQueue.index, qs.totRequestsExecuting, qs.totSeatsInUse, qs.dCfg.ConcurrencyLimit)\n\t\t}\n\t\tmetrics.AddDispatchWithNoAccommodation(qs.qCfg.Name, oldestReqFromMinQueue.fsName)\n\t\treturn nil, nil\n\t}\n\toldestReqFromMinQueue.removeFromQueueLocked()\n\n\t// If the requested final seats exceed capacity of that queue,\n\t// we reduce them to current capacity and adjust additional latency\n\t// to preserve the total amount of work.\n\tif oldestReqFromMinQueue.workEstimate.FinalSeats \u003e uint64(qs.dCfg.ConcurrencyLimit) {\n\t\tfinalSeats := uint64(qs.dCfg.ConcurrencyLimit)\n\t\tadditionalLatency := oldestReqFromMinQueue.workEstimate.finalWork.DurationPerSeat(float64(finalSeats))\n\t\toldestReqFromMinQueue.workEstimate.FinalSeats = finalSeats\n\t\toldestReqFromMinQueue.workEstimate.AdditionalLatency = additionalLatency\n\t}\n\n\t// we set the round robin indexing to start at the chose queue\n\t// for the next round. This way the non-selected queues\n\t// win in the case that the virtual finish times are the same\n\tqs.robinIndex = minIndex\n\n\tif minQueue.nextDispatchR \u003c oldestReqFromMinQueue.arrivalR {\n\t\tklog.ErrorS(errors.New(\"dispatch before arrival\"), \"Inconceivable!\", \"QS\", qs.qCfg.Name, \"queue\", minQueue.index, \"dispatchR\", minQueue.nextDispatchR, \"request\", oldestReqFromMinQueue)\n\t}\n\tmetrics.SetDispatchMetrics(qs.qCfg.Name, qs.currentR.ToFloat(), minQueue.nextDispatchR.ToFloat(), sMin.ToFloat(), sMax.ToFloat(), dsMin.ToFloat(), dsMax.ToFloat())\n\treturn minQueue, oldestReqFromMinQueue\n}","line":{"from":817,"to":890}} {"id":100018967,"name":"ssMin","signature":"func ssMin(a, b fqrequest.SeatSeconds) fqrequest.SeatSeconds","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"func ssMin(a, b fqrequest.SeatSeconds) fqrequest.SeatSeconds {\n\tif a \u003e b {\n\t\treturn b\n\t}\n\treturn a\n}","line":{"from":892,"to":897}} {"id":100018968,"name":"ssMax","signature":"func ssMax(a, b fqrequest.SeatSeconds) fqrequest.SeatSeconds","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"func ssMax(a, b fqrequest.SeatSeconds) fqrequest.SeatSeconds {\n\tif a \u003c b {\n\t\treturn b\n\t}\n\treturn a\n}","line":{"from":899,"to":904}} {"id":100018969,"name":"finishRequestAndDispatchAsMuchAsPossible","signature":"func (qs *queueSet) finishRequestAndDispatchAsMuchAsPossible(req *request) bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"// finishRequestAndDispatchAsMuchAsPossible is a convenience method\n// which calls finishRequest for a given request and then dispatches\n// as many requests as possible. This is all of what needs to be done\n// once a request finishes execution or is canceled. This returns a bool\n// indicating whether the QueueSet is now idle.\nfunc (qs *queueSet) finishRequestAndDispatchAsMuchAsPossible(req *request) bool {\n\tqs.lockAndSyncTime(req.ctx)\n\tdefer qs.lock.Unlock()\n\n\tqs.finishRequestLocked(req)\n\tqs.dispatchAsMuchAsPossibleLocked()\n\treturn qs.isIdleLocked()\n}","line":{"from":906,"to":918}} {"id":100018970,"name":"finishRequestLocked","signature":"func (qs *queueSet) finishRequestLocked(r *request)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"// finishRequestLocked is a callback that should be used when a\n// previously dispatched request has completed it's service. This\n// callback updates important state in the queueSet\nfunc (qs *queueSet) finishRequestLocked(r *request) {\n\tnow := qs.clock.Now()\n\tqs.totRequestsExecuting--\n\tmetrics.AddRequestsExecuting(r.ctx, qs.qCfg.Name, r.fsName, -1)\n\tqs.reqsGaugePair.RequestsExecuting.Add(-1)\n\n\tactualServiceDuration := now.Sub(r.startTime)\n\n\t// TODO: for now we keep the logic localized so it is easier to see\n\t// how the counters are tracked for queueset and queue, in future we\n\t// can refactor to move this function.\n\treleaseSeatsLocked := func() {\n\t\tdefer qs.removeQueueIfEmptyLocked(r)\n\n\t\tqs.totSeatsInUse -= r.MaxSeats()\n\t\tmetrics.AddRequestConcurrencyInUse(qs.qCfg.Name, r.fsName, -r.MaxSeats())\n\t\tqs.execSeatsGauge.Add(-float64(r.MaxSeats()))\n\t\tqs.seatDemandIntegrator.Set(float64(qs.totSeatsInUse + qs.totSeatsWaiting))\n\t\tif r.queue != nil {\n\t\t\tr.queue.seatsInUse -= r.MaxSeats()\n\t\t}\n\t}\n\n\tdefer func() {\n\t\tklogV := klog.V(6)\n\t\tif r.workEstimate.AdditionalLatency \u003c= 0 {\n\t\t\t// release the seats allocated to this request immediately\n\t\t\treleaseSeatsLocked()\n\t\t\tif !klogV.Enabled() {\n\t\t\t} else if r.queue != nil {\n\t\t\t\tklogV.Infof(\"QS(%s) at t=%s R=%v: request %#+v %#+v finished all use of %d seats, adjusted queue %d start R to %v due to service time %.9fs, queue will have %d requests with %#v waiting \u0026 %d requests occupying %d seats\",\n\t\t\t\t\tqs.qCfg.Name, now.Format(nsTimeFmt), qs.currentR, r.descr1, r.descr2, r.workEstimate.MaxSeats(), r.queue.index,\n\t\t\t\t\tr.queue.nextDispatchR, actualServiceDuration.Seconds(), r.queue.requests.Length(), r.queue.requests.QueueSum(), r.queue.requestsExecuting, r.queue.seatsInUse)\n\t\t\t} else {\n\t\t\t\tklogV.Infof(\"QS(%s) at t=%s R=%v: request %#+v %#+v finished all use of %d seats, qs will have %d requests occupying %d seats\", qs.qCfg.Name, now.Format(nsTimeFmt), qs.currentR, r.descr1, r.descr2, r.workEstimate.InitialSeats, qs.totRequestsExecuting, qs.totSeatsInUse)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tadditionalLatency := r.workEstimate.AdditionalLatency\n\t\tif !klogV.Enabled() {\n\t\t} else if r.queue != nil {\n\t\t\tklogV.Infof(\"QS(%s) at t=%s R=%v: request %#+v %#+v finished main use of %d seats but lingering on %d seats for %v seconds, adjusted queue %d start R to %v due to service time %.9fs, queue will have %d requests with %#v waiting \u0026 %d requests occupying %d seats\",\n\t\t\t\tqs.qCfg.Name, now.Format(nsTimeFmt), qs.currentR, r.descr1, r.descr2, r.workEstimate.InitialSeats, r.workEstimate.FinalSeats, additionalLatency.Seconds(), r.queue.index,\n\t\t\t\tr.queue.nextDispatchR, actualServiceDuration.Seconds(), r.queue.requests.Length(), r.queue.requests.QueueSum(), r.queue.requestsExecuting, r.queue.seatsInUse)\n\t\t} else {\n\t\t\tklogV.Infof(\"QS(%s) at t=%s R=%v: request %#+v %#+v finished main use of %d seats but lingering on %d seats for %v seconds, qs will have %d requests occupying %d seats\", qs.qCfg.Name, now.Format(nsTimeFmt), qs.currentR, r.descr1, r.descr2, r.workEstimate.InitialSeats, r.workEstimate.FinalSeats, additionalLatency.Seconds(), qs.totRequestsExecuting, qs.totSeatsInUse)\n\t\t}\n\t\t// EventAfterDuration will execute the event func in a new goroutine,\n\t\t// so the seats allocated to this request will be released after\n\t\t// AdditionalLatency elapses, this ensures that the additional\n\t\t// latency has no impact on the user experience.\n\t\tqs.clock.EventAfterDuration(func(_ time.Time) {\n\t\t\tqs.lockAndSyncTime(r.ctx)\n\t\t\tdefer qs.lock.Unlock()\n\t\t\tnow := qs.clock.Now()\n\t\t\treleaseSeatsLocked()\n\t\t\tif !klogV.Enabled() {\n\t\t\t} else if r.queue != nil {\n\t\t\t\tklogV.Infof(\"QS(%s) at t=%s R=%v: request %#+v %#+v finished lingering on %d seats, queue %d will have %d requests with %#v waiting \u0026 %d requests occupying %d seats\",\n\t\t\t\t\tqs.qCfg.Name, now.Format(nsTimeFmt), qs.currentR, r.descr1, r.descr2, r.workEstimate.FinalSeats, r.queue.index,\n\t\t\t\t\tr.queue.requests.Length(), r.queue.requests.QueueSum(), r.queue.requestsExecuting, r.queue.seatsInUse)\n\t\t\t} else {\n\t\t\t\tklogV.Infof(\"QS(%s) at t=%s R=%v: request %#+v %#+v finished lingering on %d seats, qs will have %d requests occupying %d seats\", qs.qCfg.Name, now.Format(nsTimeFmt), qs.currentR, r.descr1, r.descr2, r.workEstimate.FinalSeats, qs.totRequestsExecuting, qs.totSeatsInUse)\n\t\t\t}\n\t\t\tqs.dispatchAsMuchAsPossibleLocked()\n\t\t}, additionalLatency)\n\t}()\n\n\tif r.queue != nil {\n\t\t// request has finished, remove from requests executing\n\t\tr.queue.requestsExecuting--\n\n\t\t// When a request finishes being served, and the actual service time was S,\n\t\t// the queue’s start R is decremented by (G - S)*width.\n\t\tr.queue.nextDispatchR -= fqrequest.SeatsTimesDuration(float64(r.InitialSeats()), qs.estimatedServiceDuration-actualServiceDuration)\n\t\tqs.boundNextDispatchLocked(r.queue)\n\t}\n}","line":{"from":920,"to":1001}} {"id":100018971,"name":"boundNextDispatchLocked","signature":"func (qs *queueSet) boundNextDispatchLocked(queue *queue)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"// boundNextDispatchLocked applies the anti-windup hack.\n// We need a hack because all non-empty queues are allocated the same\n// number of seats. A queue that can not use all those seats and does\n// not go empty accumulates a progresively earlier `virtualStart` compared\n// to queues that are using more than they are allocated.\n// The following hack addresses the first side of that inequity,\n// by insisting that dispatch in the virtual world not precede arrival.\nfunc (qs *queueSet) boundNextDispatchLocked(queue *queue) {\n\toldestReqFromMinQueue, _ := queue.requests.Peek()\n\tif oldestReqFromMinQueue == nil {\n\t\treturn\n\t}\n\tvar virtualStartBound = oldestReqFromMinQueue.arrivalR\n\tif queue.nextDispatchR \u003c virtualStartBound {\n\t\tif klogV := klog.V(4); klogV.Enabled() {\n\t\t\tklogV.InfoS(\"AntiWindup tweaked queue\", \"QS\", qs.qCfg.Name, \"queue\", queue.index, \"time\", qs.clock.Now().Format(nsTimeFmt), \"requestDescr1\", oldestReqFromMinQueue.descr1, \"requestDescr2\", oldestReqFromMinQueue.descr2, \"newVirtualStart\", virtualStartBound, \"deltaVirtualStart\", (virtualStartBound - queue.nextDispatchR))\n\t\t}\n\t\tqueue.nextDispatchR = virtualStartBound\n\t}\n}","line":{"from":1003,"to":1022}} {"id":100018972,"name":"removeQueueIfEmptyLocked","signature":"func (qs *queueSet) removeQueueIfEmptyLocked(r *request)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"func (qs *queueSet) removeQueueIfEmptyLocked(r *request) {\n\tif r.queue == nil {\n\t\treturn\n\t}\n\n\t// If there are more queues than desired and this one has no\n\t// requests then remove it\n\tif len(qs.queues) \u003e qs.qCfg.DesiredNumQueues \u0026\u0026\n\t\tr.queue.requests.Length() == 0 \u0026\u0026\n\t\tr.queue.requestsExecuting == 0 {\n\t\tqs.queues = removeQueueAndUpdateIndexes(qs.queues, r.queue.index)\n\n\t\t// decrement here to maintain the invariant that (qs.robinIndex+1) % numQueues\n\t\t// is the index of the next queue after the one last dispatched from\n\t\tif qs.robinIndex \u003e= r.queue.index {\n\t\t\tqs.robinIndex--\n\t\t}\n\t}\n}","line":{"from":1024,"to":1042}} {"id":100018973,"name":"removeQueueAndUpdateIndexes","signature":"func removeQueueAndUpdateIndexes(queues []*queue, index int) []*queue","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"// removeQueueAndUpdateIndexes uses reslicing to remove an index from a slice\n// and then updates the 'index' field of the queues to be correct\nfunc removeQueueAndUpdateIndexes(queues []*queue, index int) []*queue {\n\tkeptQueues := append(queues[:index], queues[index+1:]...)\n\tfor i := index; i \u003c len(keptQueues); i++ {\n\t\tkeptQueues[i].index--\n\t}\n\treturn keptQueues\n}","line":{"from":1044,"to":1052}} {"id":100018974,"name":"Dump","signature":"func (qs *queueSet) Dump(includeRequestDetails bool) debug.QueueSetDump","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"func (qs *queueSet) Dump(includeRequestDetails bool) debug.QueueSetDump {\n\tqs.lock.Lock()\n\tdefer qs.lock.Unlock()\n\td := debug.QueueSetDump{\n\t\tQueues: make([]debug.QueueDump, len(qs.queues)),\n\t\tWaiting: qs.totRequestsWaiting,\n\t\tExecuting: qs.totRequestsExecuting,\n\t\tSeatsInUse: qs.totSeatsInUse,\n\t\tSeatsWaiting: qs.totSeatsWaiting,\n\t\tDispatched: qs.totRequestsDispatched,\n\t\tRejected: qs.totRequestsRejected,\n\t\tTimedout: qs.totRequestsTimedout,\n\t\tCancelled: qs.totRequestsCancelled,\n\t}\n\tfor i, q := range qs.queues {\n\t\td.Queues[i] = q.dumpLocked(includeRequestDetails)\n\t}\n\treturn d\n}","line":{"from":1054,"to":1072}} {"id":100018975,"name":"OnRequestDispatched","signature":"func OnRequestDispatched(r fq.Request)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/queueset.go","code":"func OnRequestDispatched(r fq.Request) {\n\treq, ok := r.(*request)\n\tif !ok {\n\t\treturn\n\t}\n\n\tqs := req.qs\n\tif qs != nil {\n\t\tqs.lock.Lock()\n\t\tdefer qs.lock.Unlock()\n\t\tqs.totRequestsDispatched++\n\t}\n}","line":{"from":1074,"to":1086}} {"id":100018976,"name":"totalWork","signature":"func (req *request) totalWork() fcrequest.SeatSeconds","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/types.go","code":"func (req *request) totalWork() fcrequest.SeatSeconds {\n\treturn req.workEstimate.totalWork\n}","line":{"from":126,"to":128}} {"id":100018977,"name":"completeWorkEstimate","signature":"func (qs *queueSet) completeWorkEstimate(we *fcrequest.WorkEstimate) completedWorkEstimate","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/types.go","code":"func (qs *queueSet) completeWorkEstimate(we *fcrequest.WorkEstimate) completedWorkEstimate {\n\tfinalWork := qs.computeFinalWork(we)\n\treturn completedWorkEstimate{\n\t\tWorkEstimate: *we,\n\t\ttotalWork: qs.computeInitialWork(we) + finalWork,\n\t\tfinalWork: finalWork,\n\t}\n}","line":{"from":130,"to":137}} {"id":100018978,"name":"computeInitialWork","signature":"func (qs *queueSet) computeInitialWork(we *fcrequest.WorkEstimate) fcrequest.SeatSeconds","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/types.go","code":"func (qs *queueSet) computeInitialWork(we *fcrequest.WorkEstimate) fcrequest.SeatSeconds {\n\treturn fcrequest.SeatsTimesDuration(float64(we.InitialSeats), qs.estimatedServiceDuration)\n}","line":{"from":139,"to":141}} {"id":100018979,"name":"computeFinalWork","signature":"func (qs *queueSet) computeFinalWork(we *fcrequest.WorkEstimate) fcrequest.SeatSeconds","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/types.go","code":"func (qs *queueSet) computeFinalWork(we *fcrequest.WorkEstimate) fcrequest.SeatSeconds {\n\treturn fcrequest.SeatsTimesDuration(float64(we.FinalSeats), we.AdditionalLatency)\n}","line":{"from":143,"to":145}} {"id":100018980,"name":"dumpLocked","signature":"func (q *queue) dumpLocked(includeDetails bool) debug.QueueDump","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/fairqueuing/queueset/types.go","code":"func (q *queue) dumpLocked(includeDetails bool) debug.QueueDump {\n\tdigest := make([]debug.RequestDump, q.requests.Length())\n\ti := 0\n\tq.requests.Walk(func(r *request) bool {\n\t\t// dump requests.\n\t\tdigest[i].MatchedFlowSchema = r.fsName\n\t\tdigest[i].FlowDistinguisher = r.flowDistinguisher\n\t\tdigest[i].ArriveTime = r.arrivalTime\n\t\tdigest[i].StartTime = r.startTime\n\t\tdigest[i].WorkEstimate = r.workEstimate.WorkEstimate\n\t\tif includeDetails {\n\t\t\tuserInfo, _ := genericrequest.UserFrom(r.ctx)\n\t\t\tdigest[i].UserName = userInfo.GetName()\n\t\t\trequestInfo, ok := genericrequest.RequestInfoFrom(r.ctx)\n\t\t\tif ok {\n\t\t\t\tdigest[i].RequestInfo = *requestInfo\n\t\t\t}\n\t\t}\n\t\ti++\n\t\treturn true\n\t})\n\n\tsum := q.requests.QueueSum()\n\tqueueSum := debug.QueueSum{\n\t\tInitialSeatsSum: sum.InitialSeatsSum,\n\t\tMaxSeatsSum: sum.MaxSeatsSum,\n\t\tTotalWorkSum: sum.TotalWorkSum.String(),\n\t}\n\n\treturn debug.QueueDump{\n\t\tNextDispatchR: q.nextDispatchR.String(),\n\t\tRequests: digest,\n\t\tExecutingRequests: q.requestsExecuting,\n\t\tSeatsInUse: q.seatsInUse,\n\t\tQueueSum: queueSum,\n\t}\n}","line":{"from":147,"to":183}} {"id":100018981,"name":"Fmt","signature":"func Fmt(val interface{}) Stringer","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/format/formatting.go","code":"// Fmt marks the given value for custom formatting by this package.\nfunc Fmt(val interface{}) Stringer {\n\treturn Stringer{val}\n}","line":{"from":38,"to":41}} {"id":100018982,"name":"String","signature":"func (sr Stringer) String() string","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/format/formatting.go","code":"// String formats to a string in full detail\nfunc (sr Stringer) String() string {\n\tif sr.val == nil {\n\t\treturn \"nil\"\n\t}\n\tswitch typed := sr.val.(type) {\n\tcase *flowcontrol.FlowSchema,\n\t\tflowcontrol.FlowSchema,\n\t\tflowcontrol.FlowSchemaSpec,\n\t\tflowcontrol.FlowDistinguisherMethod,\n\t\t*flowcontrol.FlowDistinguisherMethod,\n\t\t*flowcontrol.PolicyRulesWithSubjects,\n\t\tflowcontrol.PolicyRulesWithSubjects,\n\t\tflowcontrol.Subject,\n\t\tflowcontrol.ResourcePolicyRule,\n\t\tflowcontrol.NonResourcePolicyRule,\n\t\tflowcontrol.FlowSchemaCondition,\n\t\t*flowcontrol.PriorityLevelConfiguration,\n\t\tflowcontrol.PriorityLevelConfiguration,\n\t\tflowcontrol.PriorityLevelConfigurationSpec,\n\t\t*flowcontrol.LimitedPriorityLevelConfiguration,\n\t\tflowcontrol.LimitedPriorityLevelConfiguration,\n\t\tflowcontrol.LimitResponse,\n\t\t*flowcontrol.QueuingConfiguration,\n\t\tflowcontrol.QueuingConfiguration:\n\t\treturn ToJSON(sr.val)\n\tcase []user.Info:\n\t\treturn FmtUsers(typed)\n\tcase []*request.RequestInfo:\n\t\treturn FmtRequests(typed)\n\tdefault:\n\t\treturn fmt.Sprintf(\"%#+v\", sr.val)\n\t}\n}","line":{"from":43,"to":76}} {"id":100018983,"name":"ToJSON","signature":"func ToJSON(val interface{}) string","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/format/formatting.go","code":"// ToJSON converts using encoding/json and handles errors by\n// formatting them\nfunc ToJSON(val interface{}) string {\n\tbs, err := json.Marshal(val)\n\tstr := string(bs)\n\tif err != nil {\n\t\tstr = str + \"\u003c\" + err.Error() + \"\u003e\"\n\t}\n\treturn str\n}","line":{"from":78,"to":87}} {"id":100018984,"name":"FmtPriorityLevelConfiguration","signature":"func FmtPriorityLevelConfiguration(pl *flowcontrol.PriorityLevelConfiguration) string","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/format/formatting.go","code":"// FmtPriorityLevelConfiguration returns a golang source expression\n// equivalent to the given value\nfunc FmtPriorityLevelConfiguration(pl *flowcontrol.PriorityLevelConfiguration) string {\n\tif pl == nil {\n\t\treturn \"nil\"\n\t}\n\tvar buf bytes.Buffer\n\tbuf.WriteString(fmt.Sprintf(\"\u0026flowcontrolv1beta3.PriorityLevelConfiguration{ObjectMeta: %#+v, Spec: \",\n\t\tpl.ObjectMeta))\n\tBufferPriorityLevelConfigurationSpec(\u0026buf, \u0026pl.Spec)\n\tbuf.WriteString(fmt.Sprintf(\", Status: %#+v}\", pl.Status))\n\treturn buf.String()\n}","line":{"from":89,"to":101}} {"id":100018985,"name":"FmtPriorityLevelConfigurationSpec","signature":"func FmtPriorityLevelConfigurationSpec(plSpec *flowcontrol.PriorityLevelConfigurationSpec) string","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/format/formatting.go","code":"// FmtPriorityLevelConfigurationSpec returns a golang source\n// expression equivalent to the given value\nfunc FmtPriorityLevelConfigurationSpec(plSpec *flowcontrol.PriorityLevelConfigurationSpec) string {\n\tvar buf bytes.Buffer\n\tBufferPriorityLevelConfigurationSpec(\u0026buf, plSpec)\n\treturn buf.String()\n}","line":{"from":103,"to":109}} {"id":100018986,"name":"BufferPriorityLevelConfigurationSpec","signature":"func BufferPriorityLevelConfigurationSpec(buf *bytes.Buffer, plSpec *flowcontrol.PriorityLevelConfigurationSpec)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/format/formatting.go","code":"// BufferPriorityLevelConfigurationSpec writes a golang source\n// expression for the given value to the given buffer\nfunc BufferPriorityLevelConfigurationSpec(buf *bytes.Buffer, plSpec *flowcontrol.PriorityLevelConfigurationSpec) {\n\tbuf.WriteString(fmt.Sprintf(\"flowcontrolv1beta3.PriorityLevelConfigurationSpec{Type: %#v\", plSpec.Type))\n\tif plSpec.Limited != nil {\n\t\tbuf.WriteString(fmt.Sprintf(\", Limited: \u0026flowcontrol.LimitedPriorityLevelConfiguration{NominalConcurrencyShares:%d, LimitResponse:flowcontrol.LimitResponse{Type:%#v\", plSpec.Limited.NominalConcurrencyShares, plSpec.Limited.LimitResponse.Type))\n\t\tif plSpec.Limited.LimitResponse.Queuing != nil {\n\t\t\tbuf.WriteString(fmt.Sprintf(\", Queuing:\u0026%#+v\", *plSpec.Limited.LimitResponse.Queuing))\n\t\t}\n\t\tbuf.WriteString(\" } }\")\n\t}\n\tbuf.WriteString(\"}\")\n}","line":{"from":111,"to":123}} {"id":100018987,"name":"FmtFlowSchema","signature":"func FmtFlowSchema(fs *flowcontrol.FlowSchema) string","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/format/formatting.go","code":"// FmtFlowSchema produces a golang source expression of the value.\nfunc FmtFlowSchema(fs *flowcontrol.FlowSchema) string {\n\tif fs == nil {\n\t\treturn \"nil\"\n\t}\n\tvar buf bytes.Buffer\n\tbuf.WriteString(fmt.Sprintf(\"\u0026flowcontrolv1beta3.FlowSchema{ObjectMeta: %#+v, Spec: \",\n\t\tfs.ObjectMeta))\n\tBufferFlowSchemaSpec(\u0026buf, \u0026fs.Spec)\n\tbuf.WriteString(fmt.Sprintf(\", Status: %#+v}\", fs.Status))\n\treturn buf.String()\n}","line":{"from":125,"to":136}} {"id":100018988,"name":"FmtFlowSchemaSpec","signature":"func FmtFlowSchemaSpec(fsSpec *flowcontrol.FlowSchemaSpec) string","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/format/formatting.go","code":"// FmtFlowSchemaSpec produces a golang source expression equivalent to\n// the given spec\nfunc FmtFlowSchemaSpec(fsSpec *flowcontrol.FlowSchemaSpec) string {\n\tvar buf bytes.Buffer\n\tBufferFlowSchemaSpec(\u0026buf, fsSpec)\n\treturn buf.String()\n}","line":{"from":138,"to":144}} {"id":100018989,"name":"BufferFlowSchemaSpec","signature":"func BufferFlowSchemaSpec(buf *bytes.Buffer, fsSpec *flowcontrol.FlowSchemaSpec)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/format/formatting.go","code":"// BufferFlowSchemaSpec writes a golang source expression for the\n// given value to the given buffer\nfunc BufferFlowSchemaSpec(buf *bytes.Buffer, fsSpec *flowcontrol.FlowSchemaSpec) {\n\tbuf.WriteString(fmt.Sprintf(\"flowcontrolv1beta3.FlowSchemaSpec{PriorityLevelConfiguration: %#+v, MatchingPrecedence: %d, DistinguisherMethod: \",\n\t\tfsSpec.PriorityLevelConfiguration,\n\t\tfsSpec.MatchingPrecedence))\n\tif fsSpec.DistinguisherMethod == nil {\n\t\tbuf.WriteString(\"nil\")\n\t} else {\n\t\tbuf.WriteString(fmt.Sprintf(\"\u0026%#+v\", *fsSpec.DistinguisherMethod))\n\t}\n\tbuf.WriteString(\", Rules: []flowcontrol.PolicyRulesWithSubjects{\")\n\tfor idx, rule := range fsSpec.Rules {\n\t\tif idx \u003e 0 {\n\t\t\tbuf.WriteString(\", \")\n\t\t}\n\t\tBufferFmtPolicyRulesWithSubjectsSlim(buf, rule)\n\t}\n\tbuf.WriteString(\"}}\")\n}","line":{"from":146,"to":165}} {"id":100018990,"name":"FmtPolicyRulesWithSubjects","signature":"func FmtPolicyRulesWithSubjects(rule flowcontrol.PolicyRulesWithSubjects) string","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/format/formatting.go","code":"// FmtPolicyRulesWithSubjects produces a golang source expression of the value.\nfunc FmtPolicyRulesWithSubjects(rule flowcontrol.PolicyRulesWithSubjects) string {\n\treturn \"flowcontrolv1beta3.PolicyRulesWithSubjects\" + FmtPolicyRulesWithSubjectsSlim(rule)\n}","line":{"from":167,"to":170}} {"id":100018991,"name":"FmtPolicyRulesWithSubjectsSlim","signature":"func FmtPolicyRulesWithSubjectsSlim(rule flowcontrol.PolicyRulesWithSubjects) string","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/format/formatting.go","code":"// FmtPolicyRulesWithSubjectsSlim produces a golang source expression\n// of the value but without the leading type name. See above for an\n// example context where this is useful.\nfunc FmtPolicyRulesWithSubjectsSlim(rule flowcontrol.PolicyRulesWithSubjects) string {\n\tvar buf bytes.Buffer\n\tBufferFmtPolicyRulesWithSubjectsSlim(\u0026buf, rule)\n\treturn buf.String()\n}","line":{"from":172,"to":179}} {"id":100018992,"name":"BufferFmtPolicyRulesWithSubjectsSlim","signature":"func BufferFmtPolicyRulesWithSubjectsSlim(buf *bytes.Buffer, rule flowcontrol.PolicyRulesWithSubjects)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/format/formatting.go","code":"// BufferFmtPolicyRulesWithSubjectsSlim writes a golang source\n// expression for the given value to the given buffer but excludes the\n// leading type name\nfunc BufferFmtPolicyRulesWithSubjectsSlim(buf *bytes.Buffer, rule flowcontrol.PolicyRulesWithSubjects) {\n\tbuf.WriteString(\"{Subjects: []flowcontrolv1beta3.Subject{\")\n\tfor jdx, subj := range rule.Subjects {\n\t\tif jdx \u003e 0 {\n\t\t\tbuf.WriteString(\", \")\n\t\t}\n\t\tbuf.WriteString(fmt.Sprintf(\"{Kind: %q\", subj.Kind))\n\t\tif subj.User != nil {\n\t\t\tbuf.WriteString(fmt.Sprintf(\", User: \u0026%#+v\", *subj.User))\n\t\t}\n\t\tif subj.Group != nil {\n\t\t\tbuf.WriteString(fmt.Sprintf(\", Group: \u0026%#+v\", *subj.Group))\n\t\t}\n\t\tif subj.ServiceAccount != nil {\n\t\t\tbuf.WriteString(fmt.Sprintf(\", ServiceAccount: \u0026%#+v\", *subj.ServiceAccount))\n\t\t}\n\t\tbuf.WriteString(\"}\")\n\t}\n\tbuf.WriteString(fmt.Sprintf(\"}, ResourceRules: %#+v, NonResourceRules: %#+v}\", rule.ResourceRules, rule.NonResourceRules))\n}","line":{"from":181,"to":203}} {"id":100018993,"name":"FmtUsers","signature":"func FmtUsers(list []user.Info) string","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/format/formatting.go","code":"// FmtUsers produces a golang source expression of the value.\nfunc FmtUsers(list []user.Info) string {\n\tvar buf bytes.Buffer\n\tbuf.WriteString(\"[]user.Info{\")\n\tfor idx, member := range list {\n\t\tif idx \u003e 0 {\n\t\t\tbuf.WriteString(\", \")\n\t\t}\n\t\tbuf.WriteString(fmt.Sprintf(\"%#+v\", member))\n\t}\n\tbuf.WriteString(\"}\")\n\treturn buf.String()\n}","line":{"from":205,"to":217}} {"id":100018994,"name":"FmtRequests","signature":"func FmtRequests(list []*request.RequestInfo) string","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/format/formatting.go","code":"// FmtRequests produces a golang source expression of the value.\nfunc FmtRequests(list []*request.RequestInfo) string {\n\tvar buf bytes.Buffer\n\tbuf.WriteString(\"[]*request.RequestInfo{\")\n\tfor idx, member := range list {\n\t\tif idx \u003e 0 {\n\t\t\tbuf.WriteString(\", \")\n\t\t}\n\t\tbuf.WriteString(fmt.Sprintf(\"%#+v\", member))\n\t}\n\tbuf.WriteString(\"}\")\n\treturn buf.String()\n}","line":{"from":219,"to":231}} {"id":100018995,"name":"GoString","signature":"func (rd RequestDigest) GoString() string","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/formatting.go","code":"// GoString produces a golang source expression of the value.\nfunc (rd RequestDigest) GoString() string {\n\treturn fmt.Sprintf(\"RequestDigest{RequestInfo: %#+v, User: %#+v}\", rd.RequestInfo, rd.User)\n}","line":{"from":27,"to":30}} {"id":100018996,"name":"GoString","signature":"func (pls *priorityLevelState) GoString() string","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/formatting.go","code":"// GoString produces a golang source expression of the value.\nfunc (pls *priorityLevelState) GoString() string {\n\tif pls == nil {\n\t\treturn \"nil\"\n\t}\n\treturn fmt.Sprintf(\"\u0026priorityLevelState{pl:%s, qsCompleter:%#+v, queues:%#+v, quiescing:%#v, numPending:%d}\", fcfmt.Fmt(pls.pl), pls.qsCompleter, pls.queues, pls.quiescing, pls.numPending)\n}","line":{"from":34,"to":40}} {"id":100018997,"name":"Register","signature":"func Register()","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/metrics.go","code":"// Register all metrics.\nfunc Register() {\n\tregisterMetrics.Do(func() {\n\t\tfor _, metric := range metrics {\n\t\t\tlegacyregistry.MustRegister(metric)\n\t\t}\n\t})\n}","line":{"from":55,"to":62}} {"id":100018998,"name":"Reset","signature":"func Reset()","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/metrics.go","code":"// Reset all resettable metrics to zero\nfunc Reset() {\n\tfor _, metric := range metrics {\n\t\tif rm, ok := metric.(resettable); ok {\n\t\t\trm.Reset()\n\t\t}\n\t}\n}","line":{"from":68,"to":75}} {"id":100018999,"name":"GatherAndCompare","signature":"func GatherAndCompare(expected string, metricNames ...string) error","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/metrics.go","code":"// GatherAndCompare the given metrics with the given Prometheus syntax expected value\nfunc GatherAndCompare(expected string, metricNames ...string) error {\n\treturn basemetricstestutil.GatherAndCompare(legacyregistry.DefaultGatherer, strings.NewReader(expected), metricNames...)\n}","line":{"from":77,"to":80}} {"id":100019000,"name":"Append","signature":"func (rs Registerables) Append(more ...compbasemetrics.Registerable) Registerables","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/metrics.go","code":"// Append adds more\nfunc (rs Registerables) Append(more ...compbasemetrics.Registerable) Registerables {\n\treturn append(rs, more...)\n}","line":{"from":85,"to":88}} {"id":100019001,"name":"getGauge","signature":"func (io *indexOnce) getGauge() RatioedGauge","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/metrics.go","code":"func (io *indexOnce) getGauge() RatioedGauge {\n\tio.once.Do(func() {\n\t\tio.gauge = readWriteConcurrencyGaugeVec.NewForLabelValuesSafe(0, 1, io.labelValues)\n\t})\n\treturn io.gauge\n}","line":{"from":477,"to":482}} {"id":100019002,"name":"AddRequestsInQueues","signature":"func AddRequestsInQueues(ctx context.Context, priorityLevel, flowSchema string, delta int)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/metrics.go","code":"// AddRequestsInQueues adds the given delta to the gauge of the # of requests in the queues of the specified flowSchema and priorityLevel\nfunc AddRequestsInQueues(ctx context.Context, priorityLevel, flowSchema string, delta int) {\n\tapiserverCurrentInqueueRequests.WithLabelValues(priorityLevel, flowSchema).Add(float64(delta))\n}","line":{"from":501,"to":504}} {"id":100019003,"name":"AddRequestsExecuting","signature":"func AddRequestsExecuting(ctx context.Context, priorityLevel, flowSchema string, delta int)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/metrics.go","code":"// AddRequestsExecuting adds the given delta to the gauge of executing requests of the given flowSchema and priorityLevel\nfunc AddRequestsExecuting(ctx context.Context, priorityLevel, flowSchema string, delta int) {\n\tapiserverCurrentExecutingRequests.WithLabelValues(priorityLevel, flowSchema).Add(float64(delta))\n}","line":{"from":506,"to":509}} {"id":100019004,"name":"SetCurrentR","signature":"func SetCurrentR(priorityLevel string, r float64)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/metrics.go","code":"// SetCurrentR sets the current-R (virtualTime) gauge for the given priority level\nfunc SetCurrentR(priorityLevel string, r float64) {\n\tapiserverCurrentR.WithLabelValues(priorityLevel).Set(r)\n}","line":{"from":511,"to":514}} {"id":100019005,"name":"SetDispatchMetrics","signature":"func SetDispatchMetrics(priorityLevel string, r, s, sMin, sMax, discountedSMin, discountedSMax float64)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/metrics.go","code":"// SetLatestS sets the latest-S (virtual time of dispatched request) gauge for the given priority level\nfunc SetDispatchMetrics(priorityLevel string, r, s, sMin, sMax, discountedSMin, discountedSMax float64) {\n\tapiserverDispatchR.WithLabelValues(priorityLevel).Set(r)\n\tapiserverLatestS.WithLabelValues(priorityLevel).Set(s)\n\tapiserverNextSBounds.WithLabelValues(priorityLevel, \"min\").Set(sMin)\n\tapiserverNextSBounds.WithLabelValues(priorityLevel, \"max\").Set(sMax)\n\tapiserverNextDiscountedSBounds.WithLabelValues(priorityLevel, \"min\").Set(discountedSMin)\n\tapiserverNextDiscountedSBounds.WithLabelValues(priorityLevel, \"max\").Set(discountedSMax)\n}","line":{"from":516,"to":524}} {"id":100019006,"name":"AddRequestConcurrencyInUse","signature":"func AddRequestConcurrencyInUse(priorityLevel, flowSchema string, delta int)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/metrics.go","code":"// AddRequestConcurrencyInUse adds the given delta to the gauge of concurrency in use by\n// the currently executing requests of the given flowSchema and priorityLevel\nfunc AddRequestConcurrencyInUse(priorityLevel, flowSchema string, delta int) {\n\tapiserverRequestConcurrencyInUse.WithLabelValues(priorityLevel, flowSchema).Add(float64(delta))\n}","line":{"from":526,"to":530}} {"id":100019007,"name":"AddReject","signature":"func AddReject(ctx context.Context, priorityLevel, flowSchema, reason string)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/metrics.go","code":"// AddReject increments the # of rejected requests for flow control\nfunc AddReject(ctx context.Context, priorityLevel, flowSchema, reason string) {\n\tapiserverRejectedRequestsTotal.WithContext(ctx).WithLabelValues(priorityLevel, flowSchema, reason).Add(1)\n}","line":{"from":532,"to":535}} {"id":100019008,"name":"AddDispatch","signature":"func AddDispatch(ctx context.Context, priorityLevel, flowSchema string)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/metrics.go","code":"// AddDispatch increments the # of dispatched requests for flow control\nfunc AddDispatch(ctx context.Context, priorityLevel, flowSchema string) {\n\tapiserverDispatchedRequestsTotal.WithContext(ctx).WithLabelValues(priorityLevel, flowSchema).Add(1)\n}","line":{"from":537,"to":540}} {"id":100019009,"name":"ObserveQueueLength","signature":"func ObserveQueueLength(ctx context.Context, priorityLevel, flowSchema string, length int)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/metrics.go","code":"// ObserveQueueLength observes the queue length for flow control\nfunc ObserveQueueLength(ctx context.Context, priorityLevel, flowSchema string, length int) {\n\tapiserverRequestQueueLength.WithContext(ctx).WithLabelValues(priorityLevel, flowSchema).Observe(float64(length))\n}","line":{"from":542,"to":545}} {"id":100019010,"name":"ObserveWaitingDuration","signature":"func ObserveWaitingDuration(ctx context.Context, priorityLevel, flowSchema, execute string, waitTime time.Duration)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/metrics.go","code":"// ObserveWaitingDuration observes the queue length for flow control\nfunc ObserveWaitingDuration(ctx context.Context, priorityLevel, flowSchema, execute string, waitTime time.Duration) {\n\tapiserverRequestWaitingSeconds.WithContext(ctx).WithLabelValues(priorityLevel, flowSchema, execute).Observe(waitTime.Seconds())\n}","line":{"from":547,"to":550}} {"id":100019011,"name":"ObserveExecutionDuration","signature":"func ObserveExecutionDuration(ctx context.Context, priorityLevel, flowSchema string, executionTime time.Duration)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/metrics.go","code":"// ObserveExecutionDuration observes the execution duration for flow control\nfunc ObserveExecutionDuration(ctx context.Context, priorityLevel, flowSchema string, executionTime time.Duration) {\n\treqType := \"regular\"\n\tif requestInfo, ok := apirequest.RequestInfoFrom(ctx); ok \u0026\u0026 requestInfo.Verb == \"watch\" {\n\t\treqType = requestInfo.Verb\n\t}\n\tapiserverRequestExecutionSeconds.WithContext(ctx).WithLabelValues(priorityLevel, flowSchema, reqType).Observe(executionTime.Seconds())\n}","line":{"from":552,"to":559}} {"id":100019012,"name":"ObserveWatchCount","signature":"func ObserveWatchCount(ctx context.Context, priorityLevel, flowSchema string, count int)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/metrics.go","code":"// ObserveWatchCount notes a sampling of a watch count\nfunc ObserveWatchCount(ctx context.Context, priorityLevel, flowSchema string, count int) {\n\twatchCountSamples.WithLabelValues(priorityLevel, flowSchema).Observe(float64(count))\n}","line":{"from":561,"to":564}} {"id":100019013,"name":"AddEpochAdvance","signature":"func AddEpochAdvance(ctx context.Context, priorityLevel string, success bool)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/metrics.go","code":"// AddEpochAdvance notes an advance of the progress meter baseline for a given priority level\nfunc AddEpochAdvance(ctx context.Context, priorityLevel string, success bool) {\n\tapiserverEpochAdvances.WithContext(ctx).WithLabelValues(priorityLevel, strconv.FormatBool(success)).Inc()\n}","line":{"from":566,"to":569}} {"id":100019014,"name":"ObserveWorkEstimatedSeats","signature":"func ObserveWorkEstimatedSeats(priorityLevel, flowSchema string, seats int)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/metrics.go","code":"// ObserveWorkEstimatedSeats notes a sampling of estimated seats associated with a request\nfunc ObserveWorkEstimatedSeats(priorityLevel, flowSchema string, seats int) {\n\tapiserverWorkEstimatedSeats.WithLabelValues(priorityLevel, flowSchema).Observe(float64(seats))\n}","line":{"from":571,"to":574}} {"id":100019015,"name":"AddDispatchWithNoAccommodation","signature":"func AddDispatchWithNoAccommodation(priorityLevel, flowSchema string)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/metrics.go","code":"// AddDispatchWithNoAccommodation keeps track of number of times dispatch attempt results\n// in a non accommodation due to lack of available seats.\nfunc AddDispatchWithNoAccommodation(priorityLevel, flowSchema string) {\n\tapiserverDispatchWithNoAccommodation.WithLabelValues(priorityLevel, flowSchema).Inc()\n}","line":{"from":576,"to":580}} {"id":100019016,"name":"SetPriorityLevelConfiguration","signature":"func SetPriorityLevelConfiguration(priorityLevel string, nominalCL, minCL, maxCL int)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/metrics.go","code":"func SetPriorityLevelConfiguration(priorityLevel string, nominalCL, minCL, maxCL int) {\n\tapiserverRequestConcurrencyLimit.WithLabelValues(priorityLevel).Set(float64(nominalCL))\n\tapiserverNominalConcurrencyLimits.WithLabelValues(priorityLevel).Set(float64(nominalCL))\n\tapiserverMinimumConcurrencyLimits.WithLabelValues(priorityLevel).Set(float64(minCL))\n\tapiserverMaximumConcurrencyLimits.WithLabelValues(priorityLevel).Set(float64(maxCL))\n}","line":{"from":582,"to":587}} {"id":100019017,"name":"NotePriorityLevelConcurrencyAdjustment","signature":"func NotePriorityLevelConcurrencyAdjustment(priorityLevel string, seatDemandHWM, seatDemandAvg, seatDemandStdev, seatDemandSmoothed, seatDemandTarget float64, currentCL int)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/metrics.go","code":"func NotePriorityLevelConcurrencyAdjustment(priorityLevel string, seatDemandHWM, seatDemandAvg, seatDemandStdev, seatDemandSmoothed, seatDemandTarget float64, currentCL int) {\n\tapiserverSeatDemandHighWatermarks.WithLabelValues(priorityLevel).Set(seatDemandHWM)\n\tapiserverSeatDemandAverages.WithLabelValues(priorityLevel).Set(seatDemandAvg)\n\tapiserverSeatDemandStandardDeviations.WithLabelValues(priorityLevel).Set(seatDemandStdev)\n\tapiserverSeatDemandSmootheds.WithLabelValues(priorityLevel).Set(seatDemandSmoothed)\n\tapiserverSeatDemandTargets.WithLabelValues(priorityLevel).Set(seatDemandTarget)\n\tapiserverCurrentConcurrencyLimits.WithLabelValues(priorityLevel).Set(float64(currentCL))\n}","line":{"from":589,"to":596}} {"id":100019018,"name":"SetFairFrac","signature":"func SetFairFrac(fairFrac float64)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/metrics.go","code":"func SetFairFrac(fairFrac float64) {\n\tapiserverFairFracs.Set(fairFrac)\n}","line":{"from":598,"to":600}} {"id":100019019,"name":"NewTimingRatioHistogram","signature":"func NewTimingRatioHistogram(opts *TimingRatioHistogramOpts) *TimingRatioHistogram","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/timing_ratio_histogram.go","code":"// NewTimingHistogram returns an object which is TimingHistogram-like. However, nothing\n// will be measured until the histogram is registered in at least one registry.\nfunc NewTimingRatioHistogram(opts *TimingRatioHistogramOpts) *TimingRatioHistogram {\n\treturn NewTestableTimingRatioHistogram(time.Now, opts)\n}","line":{"from":65,"to":69}} {"id":100019020,"name":"NewTestableTimingRatioHistogram","signature":"func NewTestableTimingRatioHistogram(nowFunc func() time.Time, opts *TimingRatioHistogramOpts) *TimingRatioHistogram","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/timing_ratio_histogram.go","code":"// NewTestableTimingHistogram adds injection of the clock\nfunc NewTestableTimingRatioHistogram(nowFunc func() time.Time, opts *TimingRatioHistogramOpts) *TimingRatioHistogram {\n\t//nolint:govet // copylocks: assignment copies lock value to ratioedOpts: k8s.io/component-base/metrics.TimingHistogramOpts contains sync.Once contains sync.Mutex\n\tratioedOpts := opts.TimingHistogramOpts\n\tratioedOpts.InitialValue /= opts.InitialDenominator\n\tth := compbasemetrics.NewTestableTimingHistogram(nowFunc, \u0026ratioedOpts)\n\treturn \u0026TimingRatioHistogram{\n\t\tRegisterable: th,\n\t\ttimingRatioHistogramInner: timingRatioHistogramInner{\n\t\t\tnowFunc: nowFunc,\n\t\t\tgetGaugeOfRatio: func() Gauge { return th },\n\t\t\tnumerator: opts.InitialValue,\n\t\t\tdenominator: opts.InitialDenominator,\n\t\t}}\n}","line":{"from":71,"to":85}} {"id":100019021,"name":"Set","signature":"func (trh *timingRatioHistogramInner) Set(numerator float64)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/timing_ratio_histogram.go","code":"func (trh *timingRatioHistogramInner) Set(numerator float64) {\n\ttrh.Lock()\n\tdefer trh.Unlock()\n\ttrh.numerator = numerator\n\tratio := numerator / trh.denominator\n\ttrh.getGaugeOfRatio().Set(ratio)\n}","line":{"from":87,"to":93}} {"id":100019022,"name":"Add","signature":"func (trh *timingRatioHistogramInner) Add(deltaNumerator float64)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/timing_ratio_histogram.go","code":"func (trh *timingRatioHistogramInner) Add(deltaNumerator float64) {\n\ttrh.Lock()\n\tdefer trh.Unlock()\n\tnumerator := trh.numerator + deltaNumerator\n\ttrh.numerator = numerator\n\tratio := numerator / trh.denominator\n\ttrh.getGaugeOfRatio().Set(ratio)\n}","line":{"from":95,"to":102}} {"id":100019023,"name":"Sub","signature":"func (trh *timingRatioHistogramInner) Sub(deltaNumerator float64)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/timing_ratio_histogram.go","code":"func (trh *timingRatioHistogramInner) Sub(deltaNumerator float64) {\n\ttrh.Add(-deltaNumerator)\n}","line":{"from":104,"to":106}} {"id":100019024,"name":"Inc","signature":"func (trh *timingRatioHistogramInner) Inc()","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/timing_ratio_histogram.go","code":"func (trh *timingRatioHistogramInner) Inc() {\n\ttrh.Add(1)\n}","line":{"from":108,"to":110}} {"id":100019025,"name":"Dec","signature":"func (trh *timingRatioHistogramInner) Dec()","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/timing_ratio_histogram.go","code":"func (trh *timingRatioHistogramInner) Dec() {\n\ttrh.Add(-1)\n}","line":{"from":112,"to":114}} {"id":100019026,"name":"SetToCurrentTime","signature":"func (trh *timingRatioHistogramInner) SetToCurrentTime()","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/timing_ratio_histogram.go","code":"func (trh *timingRatioHistogramInner) SetToCurrentTime() {\n\ttrh.Set(float64(trh.nowFunc().Sub(time.Unix(0, 0))))\n}","line":{"from":116,"to":118}} {"id":100019027,"name":"SetDenominator","signature":"func (trh *timingRatioHistogramInner) SetDenominator(denominator float64)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/timing_ratio_histogram.go","code":"func (trh *timingRatioHistogramInner) SetDenominator(denominator float64) {\n\ttrh.Lock()\n\tdefer trh.Unlock()\n\ttrh.denominator = denominator\n\tratio := trh.numerator / denominator\n\ttrh.getGaugeOfRatio().Set(ratio)\n}","line":{"from":120,"to":126}} {"id":100019028,"name":"WithContext","signature":"func (trh *timingRatioHistogramInner) WithContext(ctx context.Context) RatioedGauge","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/timing_ratio_histogram.go","code":"// WithContext allows the normal TimingHistogram metric to pass in context.\n// The context is no-op at the current level of development.\nfunc (trh *timingRatioHistogramInner) WithContext(ctx context.Context) RatioedGauge {\n\treturn trh\n}","line":{"from":128,"to":132}} {"id":100019029,"name":"NewTimingRatioHistogramVec","signature":"func NewTimingRatioHistogramVec(opts *compbasemetrics.TimingHistogramOpts, labelNames ...string) *TimingRatioHistogramVec","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/timing_ratio_histogram.go","code":"// NewTimingHistogramVec constructs a new vector.\n// `opts.InitialValue` is the initial ratio, but this applies\n// only for the tiny period of time until NewForLabelValuesSafe sets\n// the ratio based on the given initial numerator and denominator.\n// Thus there is a tiny splinter of time during member construction when\n// its underlying TimingHistogram is given the initial numerator rather than\n// the initial ratio (which is obviously a non-issue when both are zero).\n// Note the difficulties associated with extracting a member\n// before registering the vector.\nfunc NewTimingRatioHistogramVec(opts *compbasemetrics.TimingHistogramOpts, labelNames ...string) *TimingRatioHistogramVec {\n\treturn NewTestableTimingRatioHistogramVec(time.Now, opts, labelNames...)\n}","line":{"from":147,"to":158}} {"id":100019030,"name":"NewTestableTimingRatioHistogramVec","signature":"func NewTestableTimingRatioHistogramVec(nowFunc func() time.Time, opts *compbasemetrics.TimingHistogramOpts, labelNames ...string) *TimingRatioHistogramVec","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/timing_ratio_histogram.go","code":"// NewTestableTimingHistogramVec adds injection of the clock.\nfunc NewTestableTimingRatioHistogramVec(nowFunc func() time.Time, opts *compbasemetrics.TimingHistogramOpts, labelNames ...string) *TimingRatioHistogramVec {\n\tdelegate := compbasemetrics.NewTestableTimingHistogramVec(nowFunc, opts, labelNames)\n\treturn \u0026TimingRatioHistogramVec{\n\t\tRegisterable: delegate,\n\t\tdelegate: delegate,\n\t}\n}","line":{"from":160,"to":167}} {"id":100019031,"name":"metrics","signature":"func (v *TimingRatioHistogramVec) metrics() Registerables","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/timing_ratio_histogram.go","code":"func (v *TimingRatioHistogramVec) metrics() Registerables {\n\treturn Registerables{v}\n}","line":{"from":169,"to":171}} {"id":100019032,"name":"NewForLabelValuesChecked","signature":"func (v *TimingRatioHistogramVec) NewForLabelValuesChecked(initialNumerator, initialDenominator float64, labelValues []string) (RatioedGauge, error)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/timing_ratio_histogram.go","code":"// NewForLabelValuesChecked will return an error if this vec is not hidden and not yet registered\n// or there is a syntactic problem with the labelValues.\nfunc (v *TimingRatioHistogramVec) NewForLabelValuesChecked(initialNumerator, initialDenominator float64, labelValues []string) (RatioedGauge, error) {\n\tunderMember, err := v.delegate.WithLabelValuesChecked(labelValues...)\n\tif err != nil {\n\t\treturn noopRatioed{}, err\n\t}\n\tunderMember.Set(initialNumerator / initialDenominator)\n\treturn \u0026timingRatioHistogramInner{\n\t\tgetGaugeOfRatio: func() Gauge { return underMember },\n\t\tnumerator: initialNumerator,\n\t\tdenominator: initialDenominator,\n\t}, nil\n}","line":{"from":173,"to":186}} {"id":100019033,"name":"NewForLabelValuesSafe","signature":"func (v *TimingRatioHistogramVec) NewForLabelValuesSafe(initialNumerator, initialDenominator float64, labelValues []string) RatioedGauge","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/timing_ratio_histogram.go","code":"// NewForLabelValuesSafe is the same as NewForLabelValuesChecked in cases where that does not\n// return an error. When the unsafe version returns an error due to the vector not being\n// registered yet, the safe version returns an object that implements its methods\n// by looking up the relevant vector member in each call (thus getting a non-noop after registration).\n// In the other error cases the object returned here is a noop.\nfunc (v *TimingRatioHistogramVec) NewForLabelValuesSafe(initialNumerator, initialDenominator float64, labelValues []string) RatioedGauge {\n\ttro, err := v.NewForLabelValuesChecked(initialNumerator, initialDenominator, labelValues)\n\tif err == nil {\n\t\tklog.V(3).InfoS(\"TimingRatioHistogramVec.NewForLabelValuesSafe hit the efficient case\", \"fqName\", v.FQName(), \"labelValues\", labelValues)\n\t\treturn tro\n\t}\n\tif !compbasemetrics.ErrIsNotRegistered(err) {\n\t\tklog.ErrorS(err, \"Failed to extract TimingRatioHistogramVec member, using noop instead\", \"vectorname\", v.FQName(), \"labelValues\", labelValues)\n\t\treturn tro\n\t}\n\tklog.V(3).InfoS(\"TimingRatioHistogramVec.NewForLabelValuesSafe hit the inefficient case\", \"fqName\", v.FQName(), \"labelValues\", labelValues)\n\t// At this point we know v.NewForLabelValuesChecked(..) returns a permanent noop,\n\t// which we precisely want to avoid using. Instead, make our own gauge that\n\t// fetches the element on every Set.\n\treturn \u0026timingRatioHistogramInner{\n\t\tgetGaugeOfRatio: func() Gauge { return v.delegate.WithLabelValues(labelValues...) },\n\t\tnumerator: initialNumerator,\n\t\tdenominator: initialDenominator,\n\t}\n}","line":{"from":188,"to":212}} {"id":100019034,"name":"Set","signature":"func (noopRatioed) Set(float64) {}","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/timing_ratio_histogram.go","code":"func (noopRatioed) Set(float64) {}","line":{"from":216,"to":216}} {"id":100019035,"name":"Add","signature":"func (noopRatioed) Add(float64) {}","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/timing_ratio_histogram.go","code":"func (noopRatioed) Add(float64) {}","line":{"from":217,"to":217}} {"id":100019036,"name":"Sub","signature":"func (noopRatioed) Sub(float64) {}","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/timing_ratio_histogram.go","code":"func (noopRatioed) Sub(float64) {}","line":{"from":218,"to":218}} {"id":100019037,"name":"Inc","signature":"func (noopRatioed) Inc() {}","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/timing_ratio_histogram.go","code":"func (noopRatioed) Inc() {}","line":{"from":219,"to":219}} {"id":100019038,"name":"Dec","signature":"func (noopRatioed) Dec() {}","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/timing_ratio_histogram.go","code":"func (noopRatioed) Dec() {}","line":{"from":220,"to":220}} {"id":100019039,"name":"SetToCurrentTime","signature":"func (noopRatioed) SetToCurrentTime() {}","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/timing_ratio_histogram.go","code":"func (noopRatioed) SetToCurrentTime() {}","line":{"from":221,"to":221}} {"id":100019040,"name":"SetDenominator","signature":"func (noopRatioed) SetDenominator(float64) {}","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/timing_ratio_histogram.go","code":"func (noopRatioed) SetDenominator(float64) {}","line":{"from":222,"to":222}} {"id":100019041,"name":"Reset","signature":"func (v *TimingRatioHistogramVec) Reset()","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/timing_ratio_histogram.go","code":"func (v *TimingRatioHistogramVec) Reset() {\n\tv.delegate.Reset()\n}","line":{"from":224,"to":226}} {"id":100019042,"name":"NewUnionGauge","signature":"func NewUnionGauge(elts ...Gauge) Gauge","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/union_gauge.go","code":"// NewUnionGauge constructs a Gauge that delegates to all of the given Gauges\nfunc NewUnionGauge(elts ...Gauge) Gauge {\n\treturn unionGauge(elts)\n}","line":{"from":23,"to":26}} {"id":100019043,"name":"Set","signature":"func (ug unionGauge) Set(x float64)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/union_gauge.go","code":"func (ug unionGauge) Set(x float64) {\n\tfor _, gauge := range ug {\n\t\tgauge.Set(x)\n\t}\n}","line":{"from":28,"to":32}} {"id":100019044,"name":"Add","signature":"func (ug unionGauge) Add(x float64)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/union_gauge.go","code":"func (ug unionGauge) Add(x float64) {\n\tfor _, gauge := range ug {\n\t\tgauge.Add(x)\n\t}\n}","line":{"from":34,"to":38}} {"id":100019045,"name":"Inc","signature":"func (ug unionGauge) Inc()","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/union_gauge.go","code":"func (ug unionGauge) Inc() {\n\tfor _, gauge := range ug {\n\t\tgauge.Inc()\n\t}\n}","line":{"from":40,"to":44}} {"id":100019046,"name":"Dec","signature":"func (ug unionGauge) Dec()","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/union_gauge.go","code":"func (ug unionGauge) Dec() {\n\tfor _, gauge := range ug {\n\t\tgauge.Dec()\n\t}\n}","line":{"from":46,"to":50}} {"id":100019047,"name":"SetToCurrentTime","signature":"func (ug unionGauge) SetToCurrentTime()","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/union_gauge.go","code":"func (ug unionGauge) SetToCurrentTime() {\n\tfor _, gauge := range ug {\n\t\tgauge.SetToCurrentTime()\n\t}\n}","line":{"from":52,"to":56}} {"id":100019048,"name":"RatioedGaugeVecPhasedElementPair","signature":"func RatioedGaugeVecPhasedElementPair(vec RatioedGaugeVec, initialWaitingDenominator, initialExecutingDenominator float64, labelValues []string) RatioedGaugePair","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/metrics/vec_element_pair.go","code":"// RatioedGaugeVecPhasedElementPair extracts a pair of elements that differ in handling phase\nfunc RatioedGaugeVecPhasedElementPair(vec RatioedGaugeVec, initialWaitingDenominator, initialExecutingDenominator float64, labelValues []string) RatioedGaugePair {\n\treturn RatioedGaugePair{\n\t\tRequestsWaiting: vec.NewForLabelValuesSafe(0, initialWaitingDenominator, append([]string{LabelValueWaiting}, labelValues...)),\n\t\tRequestsExecuting: vec.NewForLabelValuesSafe(0, initialExecutingDenominator, append([]string{LabelValueExecuting}, labelValues...)),\n\t}\n}","line":{"from":19,"to":25}} {"id":100019049,"name":"DefaultWorkEstimatorConfig","signature":"func DefaultWorkEstimatorConfig() *WorkEstimatorConfig","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/request/config.go","code":"// DefaultWorkEstimatorConfig creates a new WorkEstimatorConfig with default values.\nfunc DefaultWorkEstimatorConfig() *WorkEstimatorConfig {\n\treturn \u0026WorkEstimatorConfig{\n\t\tMinimumSeats: minimumSeats,\n\t\tMaximumSeats: maximumSeats,\n\t\tListWorkEstimatorConfig: defaultListWorkEstimatorConfig(),\n\t\tMutatingWorkEstimatorConfig: defaultMutatingWorkEstimatorConfig(),\n\t}\n}","line":{"from":65,"to":73}} {"id":100019050,"name":"defaultListWorkEstimatorConfig","signature":"func defaultListWorkEstimatorConfig() *ListWorkEstimatorConfig","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/request/config.go","code":"// defaultListWorkEstimatorConfig creates a new ListWorkEstimatorConfig with default values.\nfunc defaultListWorkEstimatorConfig() *ListWorkEstimatorConfig {\n\treturn \u0026ListWorkEstimatorConfig{ObjectsPerSeat: objectsPerSeat}\n}","line":{"from":75,"to":78}} {"id":100019051,"name":"defaultMutatingWorkEstimatorConfig","signature":"func defaultMutatingWorkEstimatorConfig() *MutatingWorkEstimatorConfig","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/request/config.go","code":"// defaultMutatingWorkEstimatorConfig creates a new MutatingWorkEstimatorConfig with default values.\nfunc defaultMutatingWorkEstimatorConfig() *MutatingWorkEstimatorConfig {\n\treturn \u0026MutatingWorkEstimatorConfig{\n\t\tEnabled: enableMutatingWorkEstimator,\n\t\tEventAdditionalDuration: metav1.Duration{Duration: eventAdditionalDuration},\n\t\tWatchesPerSeat: watchesPerSeat,\n\t}\n}","line":{"from":80,"to":87}} {"id":100019052,"name":"eventAdditionalDuration","signature":"func (c *MutatingWorkEstimatorConfig) eventAdditionalDuration() time.Duration","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/request/config.go","code":"// eventAdditionalDuration converts eventAdditionalDurationMs to a time.Duration type.\nfunc (c *MutatingWorkEstimatorConfig) eventAdditionalDuration() time.Duration {\n\treturn c.EventAdditionalDuration.Duration\n}","line":{"from":89,"to":92}} {"id":100019053,"name":"newListWorkEstimator","signature":"func newListWorkEstimator(countFn objectCountGetterFunc, config *WorkEstimatorConfig) WorkEstimatorFunc","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/request/list_work_estimator.go","code":"func newListWorkEstimator(countFn objectCountGetterFunc, config *WorkEstimatorConfig) WorkEstimatorFunc {\n\testimator := \u0026listWorkEstimator{\n\t\tconfig: config,\n\t\tcountGetterFn: countFn,\n\t}\n\treturn estimator.estimate\n}","line":{"from":32,"to":38}} {"id":100019054,"name":"estimate","signature":"func (e *listWorkEstimator) estimate(r *http.Request, flowSchemaName, priorityLevelName string) WorkEstimate","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/request/list_work_estimator.go","code":"func (e *listWorkEstimator) estimate(r *http.Request, flowSchemaName, priorityLevelName string) WorkEstimate {\n\trequestInfo, ok := apirequest.RequestInfoFrom(r.Context())\n\tif !ok {\n\t\t// no RequestInfo should never happen, but to be on the safe side\n\t\t// let's return maximumSeats\n\t\treturn WorkEstimate{InitialSeats: e.config.MaximumSeats}\n\t}\n\n\tif requestInfo.Name != \"\" {\n\t\t// Requests with metadata.name specified are usually executed as get\n\t\t// requests in storage layer so their width should be 1.\n\t\t// Example of such list requests:\n\t\t// /apis/certificates.k8s.io/v1/certificatesigningrequests?fieldSelector=metadata.name%3Dcsr-xxs4m\n\t\t// /api/v1/namespaces/test/configmaps?fieldSelector=metadata.name%3Dbig-deployment-1\u0026limit=500\u0026resourceVersion=0\n\t\treturn WorkEstimate{InitialSeats: e.config.MinimumSeats}\n\t}\n\n\tquery := r.URL.Query()\n\tlistOptions := metav1.ListOptions{}\n\tif err := metav1.Convert_url_Values_To_v1_ListOptions(\u0026query, \u0026listOptions, nil); err != nil {\n\t\tklog.ErrorS(err, \"Failed to convert options while estimating work for the list request\")\n\n\t\t// This request is destined to fail in the validation layer,\n\t\t// return maximumSeats for this request to be consistent.\n\t\treturn WorkEstimate{InitialSeats: e.config.MaximumSeats}\n\t}\n\tisListFromCache := !shouldListFromStorage(query, \u0026listOptions)\n\n\tnumStored, err := e.countGetterFn(key(requestInfo))\n\tswitch {\n\tcase err == ObjectCountStaleErr:\n\t\t// object count going stale is indicative of degradation, so we should\n\t\t// be conservative here and allocate maximum seats to this list request.\n\t\t// NOTE: if a CRD is removed, its count will go stale first and then the\n\t\t// pruner will eventually remove the CRD from the cache.\n\t\treturn WorkEstimate{InitialSeats: e.config.MaximumSeats}\n\tcase err == ObjectCountNotFoundErr:\n\t\t// there are multiple scenarios in which we can see this error:\n\t\t// a. the type is truly unknown, a typo on the caller's part.\n\t\t// b. the count has gone stale for too long and the pruner\n\t\t// has removed the type from the cache.\n\t\t// c. the type is an aggregated resource that is served by a\n\t\t// different apiserver (thus its object count is not updated)\n\t\t// we don't have a way to distinguish between those situations.\n\t\t// However, in case c, the request is delegated to a different apiserver,\n\t\t// and thus its cost for our server is minimal. To avoid the situation\n\t\t// when aggregated API calls are overestimated, we allocate the minimum\n\t\t// possible seats (see #109106 as an example when being more conservative\n\t\t// led to problems).\n\t\treturn WorkEstimate{InitialSeats: e.config.MinimumSeats}\n\tcase err != nil:\n\t\t// we should never be here since Get returns either ObjectCountStaleErr or\n\t\t// ObjectCountNotFoundErr, return maximumSeats to be on the safe side.\n\t\tklog.ErrorS(err, \"Unexpected error from object count tracker\")\n\t\treturn WorkEstimate{InitialSeats: e.config.MaximumSeats}\n\t}\n\n\tlimit := numStored\n\tif utilfeature.DefaultFeatureGate.Enabled(features.APIListChunking) \u0026\u0026 listOptions.Limit \u003e 0 \u0026\u0026\n\t\tlistOptions.Limit \u003c numStored {\n\t\tlimit = listOptions.Limit\n\t}\n\n\tvar estimatedObjectsToBeProcessed int64\n\n\tswitch {\n\tcase isListFromCache:\n\t\t// TODO: For resources that implement indexes at the watchcache level,\n\t\t// we need to adjust the cost accordingly\n\t\testimatedObjectsToBeProcessed = numStored\n\tcase listOptions.FieldSelector != \"\" || listOptions.LabelSelector != \"\":\n\t\testimatedObjectsToBeProcessed = numStored + limit\n\tdefault:\n\t\testimatedObjectsToBeProcessed = 2 * limit\n\t}\n\n\t// for now, our rough estimate is to allocate one seat to each 100 obejcts that\n\t// will be processed by the list request.\n\t// we will come up with a different formula for the transformation function and/or\n\t// fine tune this number in future iteratons.\n\tseats := uint64(math.Ceil(float64(estimatedObjectsToBeProcessed) / e.config.ObjectsPerSeat))\n\n\t// make sure we never return a seat of zero\n\tif seats \u003c e.config.MinimumSeats {\n\t\tseats = e.config.MinimumSeats\n\t}\n\tif seats \u003e e.config.MaximumSeats {\n\t\tseats = e.config.MaximumSeats\n\t}\n\treturn WorkEstimate{InitialSeats: seats}\n}","line":{"from":45,"to":135}} {"id":100019055,"name":"key","signature":"func key(requestInfo *apirequest.RequestInfo) string","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/request/list_work_estimator.go","code":"func key(requestInfo *apirequest.RequestInfo) string {\n\tgroupResource := \u0026schema.GroupResource{\n\t\tGroup: requestInfo.APIGroup,\n\t\tResource: requestInfo.Resource,\n\t}\n\treturn groupResource.String()\n}","line":{"from":137,"to":143}} {"id":100019056,"name":"shouldListFromStorage","signature":"func shouldListFromStorage(query url.Values, opts *metav1.ListOptions) bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/request/list_work_estimator.go","code":"// NOTICE: Keep in sync with shouldDelegateList function in\n//\n//\tstaging/src/k8s.io/apiserver/pkg/storage/cacher/cacher.go\nfunc shouldListFromStorage(query url.Values, opts *metav1.ListOptions) bool {\n\tresourceVersion := opts.ResourceVersion\n\tmatch := opts.ResourceVersionMatch\n\tpagingEnabled := utilfeature.DefaultFeatureGate.Enabled(features.APIListChunking)\n\thasContinuation := pagingEnabled \u0026\u0026 len(opts.Continue) \u003e 0\n\thasLimit := pagingEnabled \u0026\u0026 opts.Limit \u003e 0 \u0026\u0026 resourceVersion != \"0\"\n\tunsupportedMatch := match != \"\" \u0026\u0026 match != metav1.ResourceVersionMatchNotOlderThan\n\n\treturn resourceVersion == \"\" || hasContinuation || hasLimit || unsupportedMatch\n}","line":{"from":145,"to":157}} {"id":100019057,"name":"newMutatingWorkEstimator","signature":"func newMutatingWorkEstimator(countFn watchCountGetterFunc, config *WorkEstimatorConfig) WorkEstimatorFunc","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/request/mutating_work_estimator.go","code":"func newMutatingWorkEstimator(countFn watchCountGetterFunc, config *WorkEstimatorConfig) WorkEstimatorFunc {\n\testimator := \u0026mutatingWorkEstimator{\n\t\tconfig: config,\n\t\tcountFn: countFn,\n\t}\n\treturn estimator.estimate\n}","line":{"from":28,"to":34}} {"id":100019058,"name":"estimate","signature":"func (e *mutatingWorkEstimator) estimate(r *http.Request, flowSchemaName, priorityLevelName string) WorkEstimate","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/request/mutating_work_estimator.go","code":"func (e *mutatingWorkEstimator) estimate(r *http.Request, flowSchemaName, priorityLevelName string) WorkEstimate {\n\t// TODO(wojtekt): Remove once we tune the algorithm to not fail\n\t// scalability tests.\n\tif !e.config.Enabled {\n\t\treturn WorkEstimate{\n\t\t\tInitialSeats: 1,\n\t\t}\n\t}\n\n\trequestInfo, ok := apirequest.RequestInfoFrom(r.Context())\n\tif !ok {\n\t\t// no RequestInfo should never happen, but to be on the safe side\n\t\t// let's return a large value.\n\t\treturn WorkEstimate{\n\t\t\tInitialSeats: 1,\n\t\t\tFinalSeats: e.config.MaximumSeats,\n\t\t\tAdditionalLatency: e.config.eventAdditionalDuration(),\n\t\t}\n\t}\n\n\tif isRequestExemptFromWatchEvents(requestInfo) {\n\t\treturn WorkEstimate{\n\t\t\tInitialSeats: e.config.MinimumSeats,\n\t\t\tFinalSeats: 0,\n\t\t\tAdditionalLatency: time.Duration(0),\n\t\t}\n\t}\n\n\twatchCount := e.countFn(requestInfo)\n\tmetrics.ObserveWatchCount(r.Context(), priorityLevelName, flowSchemaName, watchCount)\n\n\t// The cost of the request associated with the watchers of that event\n\t// consists of three parts:\n\t// - cost of going through the event change logic\n\t// - cost of serialization of the event\n\t// - cost of processing an event object for each watcher (e.g. filtering,\n\t// sending data over network)\n\t// We're starting simple to get some operational experience with it and\n\t// we will work on tuning the algorithm later. Given that the actual work\n\t// associated with processing watch events is happening in multiple\n\t// goroutines (proportional to the number of watchers) that are all\n\t// resumed at once, as a starting point we assume that each such goroutine\n\t// is taking 1/Nth of a seat for M milliseconds.\n\t// We allow the accounting of that work in P\u0026F to be reshaped into another\n\t// rectangle of equal area for practical reasons.\n\tvar finalSeats uint64\n\tvar additionalLatency time.Duration\n\n\t// TODO: Make this unconditional after we tune the algorithm better.\n\t// Technically, there is an overhead connected to processing an event after\n\t// the request finishes even if there is a small number of watches.\n\t// However, until we tune the estimation we want to stay on the safe side\n\t// an avoid introducing additional latency for almost every single request.\n\tif watchCount \u003e= int(e.config.WatchesPerSeat) {\n\t\t// TODO: As described in the KEP, we should take into account that not all\n\t\t// events are equal and try to estimate the cost of a single event based on\n\t\t// some historical data about size of events.\n\t\tfinalSeats = uint64(math.Ceil(float64(watchCount) / e.config.WatchesPerSeat))\n\t\tfinalWork := SeatsTimesDuration(float64(finalSeats), e.config.eventAdditionalDuration())\n\n\t\t// While processing individual events is highly parallel,\n\t\t// the design/implementation of P\u0026F has a couple limitations that\n\t\t// make using this assumption in the P\u0026F implementation very\n\t\t// inefficient because:\n\t\t// - we reserve max(initialSeats, finalSeats) for time of executing\n\t\t// both phases of the request\n\t\t// - even more importantly, when a given `wide` request is the one to\n\t\t// be dispatched, we are not dispatching any other request until\n\t\t// we accumulate enough seats to dispatch the nominated one, even\n\t\t// if currently unoccupied seats would allow for dispatching some\n\t\t// other requests in the meantime\n\t\t// As a consequence of these, the wider the request, the more capacity\n\t\t// will effectively be blocked and unused during dispatching and\n\t\t// executing this request.\n\t\t//\n\t\t// To mitigate the impact of it, we're capping the maximum number of\n\t\t// seats that can be assigned to a given request. Thanks to it:\n\t\t// 1) we reduce the amount of seat-seconds that are \"wasted\" during\n\t\t// dispatching and executing initial phase of the request\n\t\t// 2) we are not changing the finalWork estimate - just potentially\n\t\t// reshaping it to be narrower and longer. As long as the maximum\n\t\t// seats setting will prevent dispatching too many requests at once\n\t\t// to prevent overloading kube-apiserver (and/or etcd or the VM or\n\t\t// a physical machine it is running on), we believe the relaxed\n\t\t// version should be good enough to achieve the P\u0026F goals.\n\t\t//\n\t\t// TODO: Confirm that the current cap of maximumSeats allow us to\n\t\t// achieve the above.\n\t\tif finalSeats \u003e e.config.MaximumSeats {\n\t\t\tfinalSeats = e.config.MaximumSeats\n\t\t}\n\t\tadditionalLatency = finalWork.DurationPerSeat(float64(finalSeats))\n\t}\n\n\treturn WorkEstimate{\n\t\tInitialSeats: 1,\n\t\tFinalSeats: finalSeats,\n\t\tAdditionalLatency: additionalLatency,\n\t}\n}","line":{"from":41,"to":140}} {"id":100019059,"name":"isRequestExemptFromWatchEvents","signature":"func isRequestExemptFromWatchEvents(requestInfo *apirequest.RequestInfo) bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/request/mutating_work_estimator.go","code":"func isRequestExemptFromWatchEvents(requestInfo *apirequest.RequestInfo) bool {\n\t// Creating token for service account does not produce any event,\n\t// but still serviceaccounts can have multiple watchers.\n\tif requestInfo.Resource == \"serviceaccounts\" \u0026\u0026 requestInfo.Subresource == \"token\" {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":142,"to":149}} {"id":100019060,"name":"NewStorageObjectCountTracker","signature":"func NewStorageObjectCountTracker() StorageObjectCountTracker","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/request/object_count_tracker.go","code":"// NewStorageObjectCountTracker returns an instance of\n// StorageObjectCountTracker interface that can be used to\n// keep track of the total number of objects for each resource.\nfunc NewStorageObjectCountTracker() StorageObjectCountTracker {\n\treturn \u0026objectCountTracker{\n\t\tclock: \u0026clock.RealClock{},\n\t\tcounts: map[string]*timestampedCount{},\n\t}\n}","line":{"from":72,"to":80}} {"id":100019061,"name":"Set","signature":"func (t *objectCountTracker) Set(groupResource string, count int64)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/request/object_count_tracker.go","code":"func (t *objectCountTracker) Set(groupResource string, count int64) {\n\tif count \u003c= -1 {\n\t\t// a value of -1 indicates that the 'Count' call failed to contact\n\t\t// the storage layer, in most cases this error can be transient.\n\t\t// we will continue to work with the count that is in the cache\n\t\t// up to a certain threshold defined by staleTolerationThreshold.\n\t\t// in case this becomes a non transient error then the count for\n\t\t// the given resource will will eventually be removed from\n\t\t// the cache by the pruner.\n\t\treturn\n\t}\n\n\tnow := t.clock.Now()\n\n\t// lock for writing\n\tt.lock.Lock()\n\tdefer t.lock.Unlock()\n\n\tif item, ok := t.counts[groupResource]; ok {\n\t\titem.count = count\n\t\titem.lastUpdatedAt = now\n\t\treturn\n\t}\n\n\tt.counts[groupResource] = \u0026timestampedCount{\n\t\tcount: count,\n\t\tlastUpdatedAt: now,\n\t}\n}","line":{"from":98,"to":126}} {"id":100019062,"name":"Get","signature":"func (t *objectCountTracker) Get(groupResource string) (int64, error)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/request/object_count_tracker.go","code":"func (t *objectCountTracker) Get(groupResource string) (int64, error) {\n\tstaleThreshold := t.clock.Now().Add(-staleTolerationThreshold)\n\n\tt.lock.RLock()\n\tdefer t.lock.RUnlock()\n\n\tif item, ok := t.counts[groupResource]; ok {\n\t\tif item.lastUpdatedAt.Before(staleThreshold) {\n\t\t\treturn item.count, ObjectCountStaleErr\n\t\t}\n\t\treturn item.count, nil\n\t}\n\treturn 0, ObjectCountNotFoundErr\n}","line":{"from":128,"to":141}} {"id":100019063,"name":"RunUntil","signature":"func (t *objectCountTracker) RunUntil(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/request/object_count_tracker.go","code":"// RunUntil runs all the necessary maintenance.\nfunc (t *objectCountTracker) RunUntil(stopCh \u003c-chan struct{}) {\n\twait.PollUntil(\n\t\tpruneInterval,\n\t\tfunc() (bool, error) {\n\t\t\t// always prune at every pruneInterval\n\t\t\treturn false, t.prune(pruneInterval)\n\t\t}, stopCh)\n\tklog.InfoS(\"StorageObjectCountTracker pruner is exiting\")\n}","line":{"from":143,"to":152}} {"id":100019064,"name":"prune","signature":"func (t *objectCountTracker) prune(threshold time.Duration) error","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/request/object_count_tracker.go","code":"func (t *objectCountTracker) prune(threshold time.Duration) error {\n\toldestLastUpdatedAtAllowed := t.clock.Now().Add(-threshold)\n\n\t// lock for writing\n\tt.lock.Lock()\n\tdefer t.lock.Unlock()\n\n\tfor groupResource, count := range t.counts {\n\t\tif count.lastUpdatedAt.After(oldestLastUpdatedAtAllowed) {\n\t\t\tcontinue\n\t\t}\n\t\tdelete(t.counts, groupResource)\n\t}\n\n\treturn nil\n}","line":{"from":154,"to":169}} {"id":100019065,"name":"SeatsTimesDuration","signature":"func SeatsTimesDuration(seats float64, duration time.Duration) SeatSeconds","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/request/seat_seconds.go","code":"// SeatsTimeDuration produces the SeatSeconds value for the given factors.\n// This is intended only to produce small values, increments in work\n// rather than amount of work done since process start.\nfunc SeatsTimesDuration(seats float64, duration time.Duration) SeatSeconds {\n\treturn SeatSeconds(math.Round(seats * float64(duration/time.Nanosecond) / (1e9 / ssScale)))\n}","line":{"from":37,"to":42}} {"id":100019066,"name":"ToFloat","signature":"func (ss SeatSeconds) ToFloat() float64","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/request/seat_seconds.go","code":"// ToFloat converts to a floating-point representation.\n// This conversion may lose precision.\nfunc (ss SeatSeconds) ToFloat() float64 {\n\treturn float64(ss) / ssScale\n}","line":{"from":44,"to":48}} {"id":100019067,"name":"DurationPerSeat","signature":"func (ss SeatSeconds) DurationPerSeat(seats float64) time.Duration","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/request/seat_seconds.go","code":"// DurationPerSeat returns duration per seat.\n// This division may lose precision.\nfunc (ss SeatSeconds) DurationPerSeat(seats float64) time.Duration {\n\treturn time.Duration(float64(ss) / seats * (float64(time.Second) / ssScale))\n}","line":{"from":50,"to":54}} {"id":100019068,"name":"String","signature":"func (ss SeatSeconds) String() string","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/request/seat_seconds.go","code":"// String converts to a string.\n// This is suitable for large as well as small values.\nfunc (ss SeatSeconds) String() string {\n\tconst div = SeatSeconds(ssScale)\n\tquo := ss / div\n\trem := ss - quo*div\n\treturn fmt.Sprintf(\"%d.%08dss\", quo, rem)\n}","line":{"from":56,"to":63}} {"id":100019069,"name":"MaxSeats","signature":"func (we *WorkEstimate) MaxSeats() int","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/request/width.go","code":"// MaxSeats returns the maximum number of seats the request occupies over the\n// phases of being served.\nfunc (we *WorkEstimate) MaxSeats() int {\n\tif we.InitialSeats \u003e= we.FinalSeats {\n\t\treturn int(we.InitialSeats)\n\t}\n\n\treturn int(we.FinalSeats)\n}","line":{"from":46,"to":54}} {"id":100019070,"name":"NewWorkEstimator","signature":"func NewWorkEstimator(objectCountFn objectCountGetterFunc, watchCountFn watchCountGetterFunc, config *WorkEstimatorConfig) WorkEstimatorFunc","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/request/width.go","code":"// NewWorkEstimator estimates the work that will be done by a given request,\n// if no WorkEstimatorFunc matches the given request then the default\n// work estimate of 1 seat is allocated to the request.\nfunc NewWorkEstimator(objectCountFn objectCountGetterFunc, watchCountFn watchCountGetterFunc, config *WorkEstimatorConfig) WorkEstimatorFunc {\n\testimator := \u0026workEstimator{\n\t\tminimumSeats: config.MinimumSeats,\n\t\tmaximumSeats: config.MaximumSeats,\n\t\tlistWorkEstimator: newListWorkEstimator(objectCountFn, config),\n\t\tmutatingWorkEstimator: newMutatingWorkEstimator(watchCountFn, config),\n\t}\n\treturn estimator.estimate\n}","line":{"from":64,"to":75}} {"id":100019071,"name":"EstimateWork","signature":"func (e WorkEstimatorFunc) EstimateWork(r *http.Request, flowSchemaName, priorityLevelName string) WorkEstimate","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/request/width.go","code":"func (e WorkEstimatorFunc) EstimateWork(r *http.Request, flowSchemaName, priorityLevelName string) WorkEstimate {\n\treturn e(r, flowSchemaName, priorityLevelName)\n}","line":{"from":82,"to":84}} {"id":100019072,"name":"estimate","signature":"func (e *workEstimator) estimate(r *http.Request, flowSchemaName, priorityLevelName string) WorkEstimate","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/request/width.go","code":"func (e *workEstimator) estimate(r *http.Request, flowSchemaName, priorityLevelName string) WorkEstimate {\n\trequestInfo, ok := apirequest.RequestInfoFrom(r.Context())\n\tif !ok {\n\t\tklog.ErrorS(fmt.Errorf(\"no RequestInfo found in context\"), \"Failed to estimate work for the request\", \"URI\", r.RequestURI)\n\t\t// no RequestInfo should never happen, but to be on the safe side let's return maximumSeats\n\t\treturn WorkEstimate{InitialSeats: e.maximumSeats}\n\t}\n\n\tswitch requestInfo.Verb {\n\tcase \"list\":\n\t\treturn e.listWorkEstimator.EstimateWork(r, flowSchemaName, priorityLevelName)\n\tcase \"create\", \"update\", \"patch\", \"delete\":\n\t\treturn e.mutatingWorkEstimator.EstimateWork(r, flowSchemaName, priorityLevelName)\n\t}\n\n\treturn WorkEstimate{InitialSeats: e.minimumSeats}\n}","line":{"from":97,"to":113}} {"id":100019073,"name":"matchesFlowSchema","signature":"func matchesFlowSchema(digest RequestDigest, flowSchema *flowcontrol.FlowSchema) bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/rule.go","code":"// Tests whether a given request and FlowSchema match. Nobody mutates\n// either input.\nfunc matchesFlowSchema(digest RequestDigest, flowSchema *flowcontrol.FlowSchema) bool {\n\tfor _, policyRule := range flowSchema.Spec.Rules {\n\t\tif matchesPolicyRule(digest, \u0026policyRule) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":28,"to":37}} {"id":100019074,"name":"matchesPolicyRule","signature":"func matchesPolicyRule(digest RequestDigest, policyRule *flowcontrol.PolicyRulesWithSubjects) bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/rule.go","code":"func matchesPolicyRule(digest RequestDigest, policyRule *flowcontrol.PolicyRulesWithSubjects) bool {\n\tif !matchesASubject(digest.User, policyRule.Subjects) {\n\t\treturn false\n\t}\n\tif digest.RequestInfo.IsResourceRequest {\n\t\treturn matchesAResourceRule(digest.RequestInfo, policyRule.ResourceRules)\n\t}\n\treturn matchesANonResourceRule(digest.RequestInfo, policyRule.NonResourceRules)\n}","line":{"from":39,"to":47}} {"id":100019075,"name":"matchesASubject","signature":"func matchesASubject(user user.Info, subjects []flowcontrol.Subject) bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/rule.go","code":"func matchesASubject(user user.Info, subjects []flowcontrol.Subject) bool {\n\tfor _, subject := range subjects {\n\t\tif matchesSubject(user, subject) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":49,"to":56}} {"id":100019076,"name":"matchesSubject","signature":"func matchesSubject(user user.Info, subject flowcontrol.Subject) bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/rule.go","code":"func matchesSubject(user user.Info, subject flowcontrol.Subject) bool {\n\tswitch subject.Kind {\n\tcase flowcontrol.SubjectKindUser:\n\t\treturn subject.User != nil \u0026\u0026 (subject.User.Name == flowcontrol.NameAll || subject.User.Name == user.GetName())\n\tcase flowcontrol.SubjectKindGroup:\n\t\tif subject.Group == nil {\n\t\t\treturn false\n\t\t}\n\t\tseek := subject.Group.Name\n\t\tif seek == \"*\" {\n\t\t\treturn true\n\t\t}\n\t\tfor _, userGroup := range user.GetGroups() {\n\t\t\tif userGroup == seek {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\tcase flowcontrol.SubjectKindServiceAccount:\n\t\tif subject.ServiceAccount == nil {\n\t\t\treturn false\n\t\t}\n\t\tif subject.ServiceAccount.Name == flowcontrol.NameAll {\n\t\t\treturn serviceAccountMatchesNamespace(subject.ServiceAccount.Namespace, user.GetName())\n\t\t}\n\t\treturn serviceaccount.MatchesUsername(subject.ServiceAccount.Namespace, subject.ServiceAccount.Name, user.GetName())\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":58,"to":87}} {"id":100019077,"name":"serviceAccountMatchesNamespace","signature":"func serviceAccountMatchesNamespace(namespace string, username string) bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/rule.go","code":"// serviceAccountMatchesNamespace checks whether the provided service account username matches the namespace, without\n// allocating. Use this when checking a service account namespace against a known string.\n// This is copied from `k8s.io/apiserver/pkg/authentication/serviceaccount::MatchesUsername` and simplified to not check the name part.\nfunc serviceAccountMatchesNamespace(namespace string, username string) bool {\n\tconst (\n\t\tServiceAccountUsernamePrefix = \"system:serviceaccount:\"\n\t\tServiceAccountUsernameSeparator = \":\"\n\t)\n\tif !strings.HasPrefix(username, ServiceAccountUsernamePrefix) {\n\t\treturn false\n\t}\n\tusername = username[len(ServiceAccountUsernamePrefix):]\n\n\tif !strings.HasPrefix(username, namespace) {\n\t\treturn false\n\t}\n\tusername = username[len(namespace):]\n\n\treturn strings.HasPrefix(username, ServiceAccountUsernameSeparator)\n}","line":{"from":89,"to":108}} {"id":100019078,"name":"matchesAResourceRule","signature":"func matchesAResourceRule(ri *request.RequestInfo, rules []flowcontrol.ResourcePolicyRule) bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/rule.go","code":"func matchesAResourceRule(ri *request.RequestInfo, rules []flowcontrol.ResourcePolicyRule) bool {\n\tfor _, rr := range rules {\n\t\tif matchesResourcePolicyRule(ri, rr) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":110,"to":117}} {"id":100019079,"name":"matchesResourcePolicyRule","signature":"func matchesResourcePolicyRule(ri *request.RequestInfo, policyRule flowcontrol.ResourcePolicyRule) bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/rule.go","code":"func matchesResourcePolicyRule(ri *request.RequestInfo, policyRule flowcontrol.ResourcePolicyRule) bool {\n\tif !matchPolicyRuleVerb(policyRule.Verbs, ri.Verb) {\n\t\treturn false\n\t}\n\tif !matchPolicyRuleResource(policyRule.Resources, ri.Resource, ri.Subresource) {\n\t\treturn false\n\t}\n\tif !matchPolicyRuleAPIGroup(policyRule.APIGroups, ri.APIGroup) {\n\t\treturn false\n\t}\n\tif len(ri.Namespace) == 0 {\n\t\treturn policyRule.ClusterScope\n\t}\n\treturn containsString(ri.Namespace, policyRule.Namespaces, flowcontrol.NamespaceEvery)\n}","line":{"from":119,"to":133}} {"id":100019080,"name":"matchesANonResourceRule","signature":"func matchesANonResourceRule(ri *request.RequestInfo, rules []flowcontrol.NonResourcePolicyRule) bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/rule.go","code":"func matchesANonResourceRule(ri *request.RequestInfo, rules []flowcontrol.NonResourcePolicyRule) bool {\n\tfor _, rr := range rules {\n\t\tif matchesNonResourcePolicyRule(ri, rr) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":135,"to":142}} {"id":100019081,"name":"matchesNonResourcePolicyRule","signature":"func matchesNonResourcePolicyRule(ri *request.RequestInfo, policyRule flowcontrol.NonResourcePolicyRule) bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/rule.go","code":"func matchesNonResourcePolicyRule(ri *request.RequestInfo, policyRule flowcontrol.NonResourcePolicyRule) bool {\n\tif !matchPolicyRuleVerb(policyRule.Verbs, ri.Verb) {\n\t\treturn false\n\t}\n\treturn matchPolicyRuleNonResourceURL(policyRule.NonResourceURLs, ri.Path)\n}","line":{"from":144,"to":149}} {"id":100019082,"name":"matchPolicyRuleVerb","signature":"func matchPolicyRuleVerb(policyRuleVerbs []string, requestVerb string) bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/rule.go","code":"func matchPolicyRuleVerb(policyRuleVerbs []string, requestVerb string) bool {\n\treturn containsString(requestVerb, policyRuleVerbs, flowcontrol.VerbAll)\n}","line":{"from":151,"to":153}} {"id":100019083,"name":"matchPolicyRuleNonResourceURL","signature":"func matchPolicyRuleNonResourceURL(policyRuleRequestURLs []string, requestPath string) bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/rule.go","code":"func matchPolicyRuleNonResourceURL(policyRuleRequestURLs []string, requestPath string) bool {\n\tfor _, rulePath := range policyRuleRequestURLs {\n\t\tif rulePath == flowcontrol.NonResourceAll || rulePath == requestPath {\n\t\t\treturn true\n\t\t}\n\t\trulePrefix := strings.TrimSuffix(rulePath, \"*\")\n\t\tif !strings.HasSuffix(rulePrefix, \"/\") {\n\t\t\trulePrefix = rulePrefix + \"/\"\n\t\t}\n\t\tif strings.HasPrefix(requestPath, rulePrefix) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":155,"to":169}} {"id":100019084,"name":"matchPolicyRuleAPIGroup","signature":"func matchPolicyRuleAPIGroup(policyRuleAPIGroups []string, requestAPIGroup string) bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/rule.go","code":"func matchPolicyRuleAPIGroup(policyRuleAPIGroups []string, requestAPIGroup string) bool {\n\treturn containsString(requestAPIGroup, policyRuleAPIGroups, flowcontrol.APIGroupAll)\n}","line":{"from":171,"to":173}} {"id":100019085,"name":"rsJoin","signature":"func rsJoin(requestResource, requestSubresource string) string","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/rule.go","code":"func rsJoin(requestResource, requestSubresource string) string {\n\tseekString := requestResource\n\tif requestSubresource != \"\" {\n\t\tseekString = requestResource + \"/\" + requestSubresource\n\t}\n\treturn seekString\n}","line":{"from":175,"to":181}} {"id":100019086,"name":"matchPolicyRuleResource","signature":"func matchPolicyRuleResource(policyRuleRequestResources []string, requestResource, requestSubresource string) bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/rule.go","code":"func matchPolicyRuleResource(policyRuleRequestResources []string, requestResource, requestSubresource string) bool {\n\treturn containsString(rsJoin(requestResource, requestSubresource), policyRuleRequestResources, flowcontrol.ResourceAll)\n}","line":{"from":183,"to":185}} {"id":100019087,"name":"containsString","signature":"func containsString(x string, list []string, wildcard string) bool","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/rule.go","code":"// containsString returns true if either `x` or `wildcard` is in\n// `list`. The wildcard is not a pattern to match against `x`; rather\n// the presence of the wildcard in the list is the caller's way of\n// saying that all values of `x` should match the list. This function\n// assumes that if `wildcard` is in `list` then it is the only member\n// of the list, which is enforced by validation.\nfunc containsString(x string, list []string, wildcard string) bool {\n\tif len(list) == 1 \u0026\u0026 list[0] == wildcard {\n\t\treturn true\n\t}\n\tfor _, y := range list {\n\t\tif x == y {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":187,"to":203}} {"id":100019088,"name":"getBuiltinIndexes","signature":"func getBuiltinIndexes() builtinIndexes","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/watch_tracker.go","code":"func getBuiltinIndexes() builtinIndexes {\n\t// The only existing indexes as of now are:\n\t// - spec.nodeName for pods\n\t// - metadata.Name for nodes, secrets and configmaps\n\t// However, we can ignore the latter, because the requestInfo.Name\n\t// is set for them (i.e. we already catch them correctly).\n\treturn map[string]string{\n\t\t\"pods\": \"spec.nodeName\",\n\t}\n}","line":{"from":78,"to":87}} {"id":100019089,"name":"NewWatchTracker","signature":"func NewWatchTracker() WatchTracker","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/watch_tracker.go","code":"func NewWatchTracker() WatchTracker {\n\treturn \u0026watchTracker{\n\t\tindexes: getBuiltinIndexes(),\n\t\twatchCount: make(map[watchIdentifier]int),\n\t}\n}","line":{"from":100,"to":105}} {"id":100019090,"name":"getIndexValue","signature":"func getIndexValue(r *http.Request, field string) string","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/watch_tracker.go","code":"func getIndexValue(r *http.Request, field string) string {\n\topts := metainternalversion.ListOptions{}\n\tif err := scheme.ParameterCodec.DecodeParameters(r.URL.Query(), metav1.SchemeGroupVersion, \u0026opts); err != nil {\n\t\tklog.Warningf(\"Couldn't parse list options for %v: %v\", r.URL.Query(), err)\n\t\treturn unsetValue\n\t}\n\tif opts.FieldSelector == nil {\n\t\treturn unsetValue\n\t}\n\tif value, ok := opts.FieldSelector.RequiresExactMatch(field); ok {\n\t\treturn value\n\t}\n\treturn unsetValue\n}","line":{"from":111,"to":124}} {"id":100019091,"name":"RegisterWatch","signature":"func (w *watchTracker) RegisterWatch(r *http.Request) ForgetWatchFunc","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/watch_tracker.go","code":"// RegisterWatch implements WatchTracker interface.\nfunc (w *watchTracker) RegisterWatch(r *http.Request) ForgetWatchFunc {\n\trequestInfo, ok := request.RequestInfoFrom(r.Context())\n\tif !ok || requestInfo == nil || requestInfo.Verb != \"watch\" {\n\t\treturn nil\n\t}\n\n\tvar index *indexValue\n\tif indexField, ok := w.indexes[requestInfo.Resource]; ok {\n\t\tindex = \u0026indexValue{\n\t\t\tresource: requestInfo.Resource,\n\t\t\tvalue: getIndexValue(r, indexField),\n\t\t}\n\t}\n\n\tidentifier := \u0026watchIdentifier{\n\t\tapiGroup: requestInfo.APIGroup,\n\t\tresource: requestInfo.Resource,\n\t\tnamespace: requestInfo.Namespace,\n\t\tname: requestInfo.Name,\n\t}\n\n\tw.lock.Lock()\n\tdefer w.lock.Unlock()\n\tw.updateIndexLocked(identifier, index, 1)\n\treturn w.forgetWatch(identifier, index)\n}","line":{"from":131,"to":157}} {"id":100019092,"name":"updateIndexLocked","signature":"func (w *watchTracker) updateIndexLocked(identifier *watchIdentifier, index *indexValue, incr int)","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/watch_tracker.go","code":"func (w *watchTracker) updateIndexLocked(identifier *watchIdentifier, index *indexValue, incr int) {\n\tif index == nil {\n\t\tw.watchCount[*identifier] += incr\n\t} else {\n\t\t// For resources with defined index, for a given watch event we are\n\t\t// only processing the watchers that:\n\t\t// (a) do not specify field selector for an index field\n\t\t// (b) do specify field selector with the value equal to the value\n\t\t// coming from the processed object\n\t\t//\n\t\t// TODO(wojtek-t): For the sake of making progress and initially\n\t\t// simplifying the implementation, we approximate (b) for all values\n\t\t// as the value for an empty string. The assumption we're making here\n\t\t// is that the difference between the actual number of watchers that\n\t\t// will be processed, i.e. (a)+(b) above and the one from our\n\t\t// approximation i.e. (a)+[(b) for field value of \"\"] will be small.\n\t\t// This seem to be true in almost all production clusters, which makes\n\t\t// it a reasonable first step simplification to unblock progres on it.\n\t\tif index.value == unsetValue || index.value == \"\" {\n\t\t\tw.watchCount[*identifier] += incr\n\t\t}\n\t}\n}","line":{"from":159,"to":181}} {"id":100019093,"name":"forgetWatch","signature":"func (w *watchTracker) forgetWatch(identifier *watchIdentifier, index *indexValue) ForgetWatchFunc","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/watch_tracker.go","code":"func (w *watchTracker) forgetWatch(identifier *watchIdentifier, index *indexValue) ForgetWatchFunc {\n\treturn func() {\n\t\tw.lock.Lock()\n\t\tdefer w.lock.Unlock()\n\n\t\tw.updateIndexLocked(identifier, index, -1)\n\t\tif w.watchCount[*identifier] == 0 {\n\t\t\tdelete(w.watchCount, *identifier)\n\t\t}\n\t}\n}","line":{"from":183,"to":193}} {"id":100019094,"name":"GetInterestedWatchCount","signature":"func (w *watchTracker) GetInterestedWatchCount(requestInfo *request.RequestInfo) int","file":"staging/src/k8s.io/apiserver/pkg/util/flowcontrol/watch_tracker.go","code":"// GetInterestedWatchCount implements WatchTracker interface.\n//\n// TODO(wojtek-t): As of now, requestInfo for object creation (POST) doesn't\n// contain the Name field set. Figure out if we can somehow get it for the\n// more accurate cost estimation.\n//\n// TODO(wojtek-t): Figure out how to approach DELETECOLLECTION calls.\nfunc (w *watchTracker) GetInterestedWatchCount(requestInfo *request.RequestInfo) int {\n\tif requestInfo == nil || readOnlyVerbs.Has(requestInfo.Verb) {\n\t\treturn 0\n\t}\n\n\tresult := 0\n\t// The watches that we're interested in include:\n\t// - watches for all objects of a resource type (no namespace and name specified)\n\t// - watches for all objects of a resource type in the same namespace (no name specified)\n\t// - watched interested in this particular object\n\tidentifier := \u0026watchIdentifier{\n\t\tapiGroup: requestInfo.APIGroup,\n\t\tresource: requestInfo.Resource,\n\t}\n\n\tw.lock.Lock()\n\tdefer w.lock.Unlock()\n\n\tresult += w.watchCount[*identifier]\n\n\tif requestInfo.Namespace != \"\" {\n\t\tidentifier.namespace = requestInfo.Namespace\n\t\tresult += w.watchCount[*identifier]\n\t}\n\n\tif requestInfo.Name != \"\" {\n\t\tidentifier.name = requestInfo.Name\n\t\tresult += w.watchCount[*identifier]\n\t}\n\n\treturn result\n}","line":{"from":195,"to":233}} {"id":100019095,"name":"Wrap","signature":"func Wrap(w io.Writer) io.Writer","file":"staging/src/k8s.io/apiserver/pkg/util/flushwriter/writer.go","code":"// Wrap wraps an io.Writer into a writer that flushes after every write if\n// the writer implements the Flusher interface.\nfunc Wrap(w io.Writer) io.Writer {\n\tfw := \u0026flushWriter{\n\t\twriter: w,\n\t}\n\tif flusher, ok := w.(http.Flusher); ok {\n\t\tfw.flusher = flusher\n\t}\n\treturn fw\n}","line":{"from":24,"to":34}} {"id":100019096,"name":"Write","signature":"func (fw *flushWriter) Write(p []byte) (n int, err error)","file":"staging/src/k8s.io/apiserver/pkg/util/flushwriter/writer.go","code":"// Write is a FlushWriter implementation of the io.Writer that sends any buffered\n// data to the client.\nfunc (fw *flushWriter) Write(p []byte) (n int, err error) {\n\tn, err = fw.writer.Write(p)\n\tif err != nil {\n\t\treturn\n\t}\n\tif fw.flusher != nil {\n\t\tfw.flusher.Flush()\n\t}\n\treturn\n}","line":{"from":42,"to":53}} {"id":100019097,"name":"New","signature":"func New(serializer runtime.NegotiatedSerializer, isMuxAndDiscoveryCompleteFn func(ctx context.Context) bool) *Handler","file":"staging/src/k8s.io/apiserver/pkg/util/notfoundhandler/not_found_handler.go","code":"// New returns an HTTP handler that is meant to be executed at the end of the delegation chain.\n// It checks if the request have been made before the server has installed all known HTTP paths.\n// In that case it returns a 503 response otherwise it returns a 404.\n//\n// Note that we don't want to add additional checks to the readyz path as it might prevent fixing bricked clusters.\n// This specific handler is meant to \"protect\" requests that arrive before the paths and handlers are fully initialized.\nfunc New(serializer runtime.NegotiatedSerializer, isMuxAndDiscoveryCompleteFn func(ctx context.Context) bool) *Handler {\n\treturn \u0026Handler{serializer: serializer, isMuxAndDiscoveryCompleteFn: isMuxAndDiscoveryCompleteFn}\n}","line":{"from":31,"to":39}} {"id":100019098,"name":"ServeHTTP","signature":"func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request)","file":"staging/src/k8s.io/apiserver/pkg/util/notfoundhandler/not_found_handler.go","code":"func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\tif !h.isMuxAndDiscoveryCompleteFn(req.Context()) {\n\t\terrMsg := \"the request has been made before all known HTTP paths have been installed, please try again\"\n\t\terr := apierrors.NewServiceUnavailable(errMsg)\n\t\tif err.ErrStatus.Details == nil {\n\t\t\terr.ErrStatus.Details = \u0026metav1.StatusDetails{}\n\t\t}\n\t\terr.ErrStatus.Details.RetryAfterSeconds = int32(5)\n\n\t\tgv := schema.GroupVersion{Group: \"unknown\", Version: \"unknown\"}\n\t\trequestInfo, ok := apirequest.RequestInfoFrom(req.Context())\n\t\tif ok {\n\t\t\tgv.Group = requestInfo.APIGroup\n\t\t\tgv.Version = requestInfo.APIVersion\n\t\t}\n\t\tresponsewriters.ErrorNegotiated(err, h.serializer, gv, rw, req)\n\t\treturn\n\t}\n\thttp.NotFound(rw, req)\n}","line":{"from":46,"to":65}} {"id":100019099,"name":"GetOpenAPIDefinitionsWithoutDisabledFeatures","signature":"func GetOpenAPIDefinitionsWithoutDisabledFeatures(GetOpenAPIDefinitions common.GetOpenAPIDefinitions) common.GetOpenAPIDefinitions","file":"staging/src/k8s.io/apiserver/pkg/util/openapi/enablement.go","code":"// GetOpenAPIDefinitionsWithoutDisabledFeatures wraps a GetOpenAPIDefinitions to revert\n// any change to the schema that was made by disabled features.\nfunc GetOpenAPIDefinitionsWithoutDisabledFeatures(GetOpenAPIDefinitions common.GetOpenAPIDefinitions) common.GetOpenAPIDefinitions {\n\treturn func(ref common.ReferenceCallback) map[string]common.OpenAPIDefinition {\n\t\tdefs := GetOpenAPIDefinitions(ref)\n\t\trestoreDefinitions(defs)\n\t\treturn defs\n\t}\n}","line":{"from":32,"to":40}} {"id":100019100,"name":"restoreDefinitions","signature":"func restoreDefinitions(defs map[string]common.OpenAPIDefinition)","file":"staging/src/k8s.io/apiserver/pkg/util/openapi/enablement.go","code":"// restoreDefinitions restores any changes by disabled features from definition map.\nfunc restoreDefinitions(defs map[string]common.OpenAPIDefinition) {\n\t// revert changes from OpenAPIEnums\n\tif !utilfeature.DefaultFeatureGate.Enabled(genericfeatures.OpenAPIEnums) {\n\t\tfor gvk, def := range defs {\n\t\t\torig := \u0026def.Schema\n\t\t\tif ret := pruneEnums(orig); ret != orig {\n\t\t\t\tdef.Schema = *ret\n\t\t\t\tdefs[gvk] = def\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":42,"to":54}} {"id":100019101,"name":"pruneEnums","signature":"func pruneEnums(schema *spec.Schema) *spec.Schema","file":"staging/src/k8s.io/apiserver/pkg/util/openapi/enablement.go","code":"func pruneEnums(schema *spec.Schema) *spec.Schema {\n\twalker := schemamutation.Walker{\n\t\tSchemaCallback: func(schema *spec.Schema) *spec.Schema {\n\t\t\torig := schema\n\t\t\tclone := func() {\n\t\t\t\tif orig == schema { // if schema has not been mutated yet\n\t\t\t\t\tschema = new(spec.Schema)\n\t\t\t\t\t*schema = *orig // make a clone from orig to schema\n\t\t\t\t}\n\t\t\t}\n\t\t\tif headerIndex := strings.Index(schema.Description, enumTypeDescriptionHeader); headerIndex != -1 {\n\t\t\t\t// remove the enum section from description.\n\t\t\t\t// note that the new lines before the header should be removed too,\n\t\t\t\t// thus the slice range.\n\t\t\t\tclone()\n\t\t\t\tschema.Description = strings.TrimSpace(schema.Description[:headerIndex])\n\t\t\t}\n\t\t\tif len(schema.Enum) != 0 {\n\t\t\t\t// remove the enum field\n\t\t\t\tclone()\n\t\t\t\tschema.Enum = nil\n\t\t\t}\n\t\t\treturn schema\n\t\t},\n\t\tRefCallback: schemamutation.RefCallbackNoop,\n\t}\n\treturn walker.WalkSchema(schema)\n}","line":{"from":56,"to":83}} {"id":100019102,"name":"ToProtoModels","signature":"func ToProtoModels(openAPISpec *spec.Swagger) (proto.Models, error)","file":"staging/src/k8s.io/apiserver/pkg/util/openapi/proto.go","code":"// ToProtoModels builds the proto formatted models from OpenAPI spec\nfunc ToProtoModels(openAPISpec *spec.Swagger) (proto.Models, error) {\n\tspecBytes, err := json.MarshalIndent(openAPISpec, \" \", \" \")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdoc, err := openapi_v2.ParseDocument(specBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmodels, err := proto.NewOpenAPIData(doc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn models, nil\n}","line":{"from":28,"to":46}} {"id":100019103,"name":"findServicePort","signature":"func findServicePort(svc *v1.Service, port int32) (*v1.ServicePort, error)","file":"staging/src/k8s.io/apiserver/pkg/util/proxy/proxy.go","code":"// findServicePort finds the service port by name or numerically.\nfunc findServicePort(svc *v1.Service, port int32) (*v1.ServicePort, error) {\n\tfor _, svcPort := range svc.Spec.Ports {\n\t\tif svcPort.Port == port {\n\t\t\treturn \u0026svcPort, nil\n\t\t}\n\t}\n\treturn nil, errors.NewServiceUnavailable(fmt.Sprintf(\"no service port %d found for service %q\", port, svc.Name))\n}","line":{"from":31,"to":39}} {"id":100019104,"name":"ResolveEndpoint","signature":"func ResolveEndpoint(services listersv1.ServiceLister, endpoints listersv1.EndpointsLister, namespace, id string, port int32) (*url.URL, error)","file":"staging/src/k8s.io/apiserver/pkg/util/proxy/proxy.go","code":"// ResolveEndpoint returns a URL to which one can send traffic for the specified service.\nfunc ResolveEndpoint(services listersv1.ServiceLister, endpoints listersv1.EndpointsLister, namespace, id string, port int32) (*url.URL, error) {\n\tsvc, err := services.Services(namespace).Get(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch {\n\tcase svc.Spec.Type == v1.ServiceTypeClusterIP, svc.Spec.Type == v1.ServiceTypeLoadBalancer, svc.Spec.Type == v1.ServiceTypeNodePort:\n\t\t// these are fine\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported service type %q\", svc.Spec.Type)\n\t}\n\n\tsvcPort, err := findServicePort(svc, port)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\teps, err := endpoints.Endpoints(namespace).Get(svc.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(eps.Subsets) == 0 {\n\t\treturn nil, errors.NewServiceUnavailable(fmt.Sprintf(\"no endpoints available for service %q\", svc.Name))\n\t}\n\n\t// Pick a random Subset to start searching from.\n\tssSeed := rand.Intn(len(eps.Subsets))\n\n\t// Find a Subset that has the port.\n\tfor ssi := 0; ssi \u003c len(eps.Subsets); ssi++ {\n\t\tss := \u0026eps.Subsets[(ssSeed+ssi)%len(eps.Subsets)]\n\t\tif len(ss.Addresses) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tfor i := range ss.Ports {\n\t\t\tif ss.Ports[i].Name == svcPort.Name {\n\t\t\t\t// Pick a random address.\n\t\t\t\tip := ss.Addresses[rand.Intn(len(ss.Addresses))].IP\n\t\t\t\tport := int(ss.Ports[i].Port)\n\t\t\t\treturn \u0026url.URL{\n\t\t\t\t\tScheme: \"https\",\n\t\t\t\t\tHost: net.JoinHostPort(ip, strconv.Itoa(port)),\n\t\t\t\t}, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, errors.NewServiceUnavailable(fmt.Sprintf(\"no endpoints available for service %q\", id))\n}","line":{"from":41,"to":90}} {"id":100019105,"name":"ResolveCluster","signature":"func ResolveCluster(services listersv1.ServiceLister, namespace, id string, port int32) (*url.URL, error)","file":"staging/src/k8s.io/apiserver/pkg/util/proxy/proxy.go","code":"func ResolveCluster(services listersv1.ServiceLister, namespace, id string, port int32) (*url.URL, error) {\n\tsvc, err := services.Services(namespace).Get(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch {\n\tcase svc.Spec.Type == v1.ServiceTypeClusterIP \u0026\u0026 svc.Spec.ClusterIP == v1.ClusterIPNone:\n\t\treturn nil, fmt.Errorf(`cannot route to service with ClusterIP \"None\"`)\n\t// use IP from a clusterIP for these service types\n\tcase svc.Spec.Type == v1.ServiceTypeClusterIP, svc.Spec.Type == v1.ServiceTypeLoadBalancer, svc.Spec.Type == v1.ServiceTypeNodePort:\n\t\tsvcPort, err := findServicePort(svc, port)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn \u0026url.URL{\n\t\t\tScheme: \"https\",\n\t\t\tHost: net.JoinHostPort(svc.Spec.ClusterIP, fmt.Sprintf(\"%d\", svcPort.Port)),\n\t\t}, nil\n\tcase svc.Spec.Type == v1.ServiceTypeExternalName:\n\t\treturn \u0026url.URL{\n\t\t\tScheme: \"https\",\n\t\t\tHost: net.JoinHostPort(svc.Spec.ExternalName, fmt.Sprintf(\"%d\", port)),\n\t\t}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported service type %q\", svc.Spec.Type)\n\t}\n}","line":{"from":92,"to":119}} {"id":100019106,"name":"RequiredEntropyBits","signature":"func RequiredEntropyBits(deckSize, handSize int) int","file":"staging/src/k8s.io/apiserver/pkg/util/shufflesharding/shufflesharding.go","code":"// RequiredEntropyBits makes a quick and slightly conservative estimate of the number\n// of bits of hash value that are consumed in shuffle sharding a deck of the given size\n// to a hand of the given size. The result is meaningful only if\n// 1 \u003c= handSize \u003c= deckSize \u003c= 1\u003c\u003c26.\nfunc RequiredEntropyBits(deckSize, handSize int) int {\n\treturn int(math.Ceil(math.Log2(float64(deckSize)) * float64(handSize)))\n}","line":{"from":30,"to":36}} {"id":100019107,"name":"NewDealer","signature":"func NewDealer(deckSize, handSize int) (*Dealer, error)","file":"staging/src/k8s.io/apiserver/pkg/util/shufflesharding/shufflesharding.go","code":"// NewDealer will create a Dealer with the given deckSize and handSize, will return error when\n// deckSize or handSize is invalid as below.\n// 1. deckSize or handSize is not positive\n// 2. handSize is greater than deckSize\n// 3. deckSize is impractically large (greater than 1\u003c\u003c26)\n// 4. required entropy bits of deckSize and handSize is greater than MaxHashBits\nfunc NewDealer(deckSize, handSize int) (*Dealer, error) {\n\tif deckSize \u003c= 0 || handSize \u003c= 0 {\n\t\treturn nil, fmt.Errorf(\"deckSize %d or handSize %d is not positive\", deckSize, handSize)\n\t}\n\tif handSize \u003e deckSize {\n\t\treturn nil, fmt.Errorf(\"handSize %d is greater than deckSize %d\", handSize, deckSize)\n\t}\n\tif deckSize \u003e 1\u003c\u003c26 {\n\t\treturn nil, fmt.Errorf(\"deckSize %d is impractically large\", deckSize)\n\t}\n\tif RequiredEntropyBits(deckSize, handSize) \u003e MaxHashBits {\n\t\treturn nil, fmt.Errorf(\"required entropy bits of deckSize %d and handSize %d is greater than %d\", deckSize, handSize, MaxHashBits)\n\t}\n\n\treturn \u0026Dealer{\n\t\tdeckSize: deckSize,\n\t\thandSize: handSize,\n\t}, nil\n}","line":{"from":45,"to":69}} {"id":100019108,"name":"Deal","signature":"func (d *Dealer) Deal(hashValue uint64, pick func(int))","file":"staging/src/k8s.io/apiserver/pkg/util/shufflesharding/shufflesharding.go","code":"// Deal shuffles a card deck and deals a hand of cards, using the given hashValue as the source of entropy.\n// The deck size and hand size are properties of the Dealer.\n// This function synchronously makes sequential calls to pick, one for each dealt card.\n// Each card is identified by an integer in the range [0, deckSize).\n// For example, for deckSize=128 and handSize=4 this function might call pick(14); pick(73); pick(119); pick(26).\nfunc (d *Dealer) Deal(hashValue uint64, pick func(int)) {\n\t// 15 is the largest possible value of handSize\n\tvar remainders [15]int\n\n\tfor i := 0; i \u003c d.handSize; i++ {\n\t\thashValueNext := hashValue / uint64(d.deckSize-i)\n\t\tremainders[i] = int(hashValue - uint64(d.deckSize-i)*hashValueNext)\n\t\thashValue = hashValueNext\n\t}\n\n\tfor i := 0; i \u003c d.handSize; i++ {\n\t\tcard := remainders[i]\n\t\tfor j := i; j \u003e 0; j-- {\n\t\t\tif card \u003e= remainders[j-1] {\n\t\t\t\tcard++\n\t\t\t}\n\t\t}\n\t\tpick(card)\n\t}\n}","line":{"from":71,"to":95}} {"id":100019109,"name":"DealIntoHand","signature":"func (d *Dealer) DealIntoHand(hashValue uint64, hand []int) []int","file":"staging/src/k8s.io/apiserver/pkg/util/shufflesharding/shufflesharding.go","code":"// DealIntoHand shuffles and deals according to the Dealer's parameters,\n// using the given hashValue as the source of entropy and then\n// returns the dealt cards as a slice of `int`.\n// If `hand` has the correct length as Dealer's handSize, it will be used as-is and no allocations will be made.\n// If `hand` is nil or too small, it will be extended (performing an allocation).\n// If `hand` is too large, a sub-slice will be returned.\nfunc (d *Dealer) DealIntoHand(hashValue uint64, hand []int) []int {\n\th := hand[:0]\n\td.Deal(hashValue, func(card int) { h = append(h, card) })\n\treturn h\n}","line":{"from":97,"to":107}} {"id":100019110,"name":"NewDefaultAuthenticationInfoResolverWrapper","signature":"func NewDefaultAuthenticationInfoResolverWrapper(","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/authentication.go","code":"// NewDefaultAuthenticationInfoResolverWrapper builds a default authn resolver wrapper\nfunc NewDefaultAuthenticationInfoResolverWrapper(\n\tproxyTransport *http.Transport,\n\tegressSelector *egressselector.EgressSelector,\n\tkubeapiserverClientConfig *rest.Config,\n\ttp trace.TracerProvider) AuthenticationInfoResolverWrapper {\n\n\twebhookAuthResolverWrapper := func(delegate AuthenticationInfoResolver) AuthenticationInfoResolver {\n\t\treturn \u0026AuthenticationInfoResolverDelegator{\n\t\t\tClientConfigForFunc: func(hostPort string) (*rest.Config, error) {\n\t\t\t\tif hostPort == \"kubernetes.default.svc:443\" {\n\t\t\t\t\treturn kubeapiserverClientConfig, nil\n\t\t\t\t}\n\t\t\t\tret, err := delegate.ClientConfigFor(hostPort)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif feature.DefaultFeatureGate.Enabled(features.APIServerTracing) {\n\t\t\t\t\tret.Wrap(tracing.WrapperFor(tp))\n\t\t\t\t}\n\n\t\t\t\tif egressSelector != nil {\n\t\t\t\t\tnetworkContext := egressselector.ControlPlane.AsNetworkContext()\n\t\t\t\t\tvar egressDialer utilnet.DialFunc\n\t\t\t\t\tegressDialer, err = egressSelector.Lookup(networkContext)\n\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\n\t\t\t\t\tret.Dial = egressDialer\n\t\t\t\t}\n\t\t\t\treturn ret, nil\n\t\t\t},\n\t\t\tClientConfigForServiceFunc: func(serviceName, serviceNamespace string, servicePort int) (*rest.Config, error) {\n\t\t\t\tif serviceName == \"kubernetes\" \u0026\u0026 serviceNamespace == corev1.NamespaceDefault \u0026\u0026 servicePort == 443 {\n\t\t\t\t\treturn kubeapiserverClientConfig, nil\n\t\t\t\t}\n\t\t\t\tret, err := delegate.ClientConfigForService(serviceName, serviceNamespace, servicePort)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif feature.DefaultFeatureGate.Enabled(features.APIServerTracing) {\n\t\t\t\t\tret.Wrap(tracing.WrapperFor(tp))\n\t\t\t\t}\n\n\t\t\t\tif egressSelector != nil {\n\t\t\t\t\tnetworkContext := egressselector.Cluster.AsNetworkContext()\n\t\t\t\t\tvar egressDialer utilnet.DialFunc\n\t\t\t\t\tegressDialer, err = egressSelector.Lookup(networkContext)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\n\t\t\t\t\tret.Dial = egressDialer\n\t\t\t\t} else if proxyTransport != nil \u0026\u0026 proxyTransport.DialContext != nil {\n\t\t\t\t\tret.Dial = proxyTransport.DialContext\n\t\t\t\t}\n\t\t\t\treturn ret, nil\n\t\t\t},\n\t\t}\n\t}\n\treturn webhookAuthResolverWrapper\n}","line":{"from":45,"to":108}} {"id":100019111,"name":"ClientConfigFor","signature":"func (a *AuthenticationInfoResolverDelegator) ClientConfigFor(hostPort string) (*rest.Config, error)","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/authentication.go","code":"// ClientConfigFor returns client config for given hostPort.\nfunc (a *AuthenticationInfoResolverDelegator) ClientConfigFor(hostPort string) (*rest.Config, error) {\n\treturn a.ClientConfigForFunc(hostPort)\n}","line":{"from":126,"to":129}} {"id":100019112,"name":"ClientConfigForService","signature":"func (a *AuthenticationInfoResolverDelegator) ClientConfigForService(serviceName, serviceNamespace string, servicePort int) (*rest.Config, error)","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/authentication.go","code":"// ClientConfigForService returns client config for given service.\nfunc (a *AuthenticationInfoResolverDelegator) ClientConfigForService(serviceName, serviceNamespace string, servicePort int) (*rest.Config, error) {\n\treturn a.ClientConfigForServiceFunc(serviceName, serviceNamespace, servicePort)\n}","line":{"from":131,"to":134}} {"id":100019113,"name":"NewDefaultAuthenticationInfoResolver","signature":"func NewDefaultAuthenticationInfoResolver(kubeconfigFile string) (AuthenticationInfoResolver, error)","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/authentication.go","code":"// NewDefaultAuthenticationInfoResolver generates an AuthenticationInfoResolver\n// that builds rest.Config based on the kubeconfig file. kubeconfigFile is the\n// path to the kubeconfig.\nfunc NewDefaultAuthenticationInfoResolver(kubeconfigFile string) (AuthenticationInfoResolver, error) {\n\tif len(kubeconfigFile) == 0 {\n\t\treturn \u0026defaultAuthenticationInfoResolver{}, nil\n\t}\n\n\tloadingRules := clientcmd.NewDefaultClientConfigLoadingRules()\n\tloadingRules.ExplicitPath = kubeconfigFile\n\tloader := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, \u0026clientcmd.ConfigOverrides{})\n\tclientConfig, err := loader.RawConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026defaultAuthenticationInfoResolver{kubeconfig: clientConfig}, nil\n}","line":{"from":140,"to":157}} {"id":100019114,"name":"ClientConfigFor","signature":"func (c *defaultAuthenticationInfoResolver) ClientConfigFor(hostPort string) (*rest.Config, error)","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/authentication.go","code":"func (c *defaultAuthenticationInfoResolver) ClientConfigFor(hostPort string) (*rest.Config, error) {\n\treturn c.clientConfig(hostPort)\n}","line":{"from":159,"to":161}} {"id":100019115,"name":"ClientConfigForService","signature":"func (c *defaultAuthenticationInfoResolver) ClientConfigForService(serviceName, serviceNamespace string, servicePort int) (*rest.Config, error)","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/authentication.go","code":"func (c *defaultAuthenticationInfoResolver) ClientConfigForService(serviceName, serviceNamespace string, servicePort int) (*rest.Config, error) {\n\treturn c.clientConfig(net.JoinHostPort(serviceName+\".\"+serviceNamespace+\".svc\", strconv.Itoa(servicePort)))\n}","line":{"from":163,"to":165}} {"id":100019116,"name":"clientConfig","signature":"func (c *defaultAuthenticationInfoResolver) clientConfig(target string) (*rest.Config, error)","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/authentication.go","code":"func (c *defaultAuthenticationInfoResolver) clientConfig(target string) (*rest.Config, error) {\n\t// exact match\n\tif authConfig, ok := c.kubeconfig.AuthInfos[target]; ok {\n\t\treturn restConfigFromKubeconfig(authConfig)\n\t}\n\n\t// star prefixed match\n\tserverSteps := strings.Split(target, \".\")\n\tfor i := 1; i \u003c len(serverSteps); i++ {\n\t\tnickName := \"*.\" + strings.Join(serverSteps[i:], \".\")\n\t\tif authConfig, ok := c.kubeconfig.AuthInfos[nickName]; ok {\n\t\t\treturn restConfigFromKubeconfig(authConfig)\n\t\t}\n\t}\n\n\t// If target included the default https port (443), search again without the port\n\tif target, port, err := net.SplitHostPort(target); err == nil \u0026\u0026 port == \"443\" {\n\t\t// exact match without port\n\t\tif authConfig, ok := c.kubeconfig.AuthInfos[target]; ok {\n\t\t\treturn restConfigFromKubeconfig(authConfig)\n\t\t}\n\n\t\t// star prefixed match without port\n\t\tserverSteps := strings.Split(target, \".\")\n\t\tfor i := 1; i \u003c len(serverSteps); i++ {\n\t\t\tnickName := \"*.\" + strings.Join(serverSteps[i:], \".\")\n\t\t\tif authConfig, ok := c.kubeconfig.AuthInfos[nickName]; ok {\n\t\t\t\treturn restConfigFromKubeconfig(authConfig)\n\t\t\t}\n\t\t}\n\t}\n\n\t// if we're trying to hit the kube-apiserver and there wasn't an explicit config, use the in-cluster config\n\tif target == \"kubernetes.default.svc:443\" {\n\t\t// if we can find an in-cluster-config use that. If we can't, fall through.\n\t\tinClusterConfig, err := rest.InClusterConfig()\n\t\tif err == nil {\n\t\t\treturn setGlobalDefaults(inClusterConfig), nil\n\t\t}\n\t}\n\n\t// star (default) match\n\tif authConfig, ok := c.kubeconfig.AuthInfos[\"*\"]; ok {\n\t\treturn restConfigFromKubeconfig(authConfig)\n\t}\n\n\t// use the current context from the kubeconfig if possible\n\tif len(c.kubeconfig.CurrentContext) \u003e 0 {\n\t\tif currContext, ok := c.kubeconfig.Contexts[c.kubeconfig.CurrentContext]; ok {\n\t\t\tif len(currContext.AuthInfo) \u003e 0 {\n\t\t\t\tif currAuth, ok := c.kubeconfig.AuthInfos[currContext.AuthInfo]; ok {\n\t\t\t\t\treturn restConfigFromKubeconfig(currAuth)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// anonymous\n\treturn setGlobalDefaults(\u0026rest.Config{}), nil\n}","line":{"from":167,"to":226}} {"id":100019117,"name":"restConfigFromKubeconfig","signature":"func restConfigFromKubeconfig(configAuthInfo *clientcmdapi.AuthInfo) (*rest.Config, error)","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/authentication.go","code":"func restConfigFromKubeconfig(configAuthInfo *clientcmdapi.AuthInfo) (*rest.Config, error) {\n\tconfig := \u0026rest.Config{}\n\n\t// blindly overwrite existing values based on precedence\n\tif len(configAuthInfo.Token) \u003e 0 {\n\t\tconfig.BearerToken = configAuthInfo.Token\n\t\tconfig.BearerTokenFile = configAuthInfo.TokenFile\n\t} else if len(configAuthInfo.TokenFile) \u003e 0 {\n\t\ttokenBytes, err := ioutil.ReadFile(configAuthInfo.TokenFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tconfig.BearerToken = string(tokenBytes)\n\t\tconfig.BearerTokenFile = configAuthInfo.TokenFile\n\t}\n\tif len(configAuthInfo.Impersonate) \u003e 0 {\n\t\tconfig.Impersonate = rest.ImpersonationConfig{\n\t\t\tUserName: configAuthInfo.Impersonate,\n\t\t\tGroups: configAuthInfo.ImpersonateGroups,\n\t\t\tExtra: configAuthInfo.ImpersonateUserExtra,\n\t\t}\n\t}\n\tif len(configAuthInfo.ClientCertificate) \u003e 0 || len(configAuthInfo.ClientCertificateData) \u003e 0 {\n\t\tconfig.CertFile = configAuthInfo.ClientCertificate\n\t\tconfig.CertData = configAuthInfo.ClientCertificateData\n\t\tconfig.KeyFile = configAuthInfo.ClientKey\n\t\tconfig.KeyData = configAuthInfo.ClientKeyData\n\t}\n\tif len(configAuthInfo.Username) \u003e 0 || len(configAuthInfo.Password) \u003e 0 {\n\t\tconfig.Username = configAuthInfo.Username\n\t\tconfig.Password = configAuthInfo.Password\n\t}\n\tif configAuthInfo.Exec != nil {\n\t\tconfig.ExecProvider = configAuthInfo.Exec.DeepCopy()\n\t}\n\tif configAuthInfo.AuthProvider != nil {\n\t\treturn nil, fmt.Errorf(\"auth provider not supported\")\n\t}\n\n\treturn setGlobalDefaults(config), nil\n}","line":{"from":228,"to":268}} {"id":100019118,"name":"setGlobalDefaults","signature":"func setGlobalDefaults(config *rest.Config) *rest.Config","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/authentication.go","code":"func setGlobalDefaults(config *rest.Config) *rest.Config {\n\tconfig.UserAgent = \"kube-apiserver-admission\"\n\tconfig.Timeout = 30 * time.Second\n\n\treturn config\n}","line":{"from":270,"to":275}} {"id":100019119,"name":"NewClientManager","signature":"func NewClientManager(gvs []schema.GroupVersion, addToSchemaFuncs ...func(s *runtime.Scheme) error) (ClientManager, error)","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/client.go","code":"// NewClientManager creates a clientManager.\nfunc NewClientManager(gvs []schema.GroupVersion, addToSchemaFuncs ...func(s *runtime.Scheme) error) (ClientManager, error) {\n\tcache := lru.New(defaultCacheSize)\n\thookScheme := runtime.NewScheme()\n\tfor _, addToSchemaFunc := range addToSchemaFuncs {\n\t\tif err := addToSchemaFunc(hookScheme); err != nil {\n\t\t\treturn ClientManager{}, err\n\t\t}\n\t}\n\treturn ClientManager{\n\t\tcache: cache,\n\t\tnegotiatedSerializer: serializer.NegotiatedSerializerWrapper(runtime.SerializerInfo{\n\t\t\tSerializer: serializer.NewCodecFactory(hookScheme).LegacyCodec(gvs...),\n\t\t}),\n\t}, nil\n}","line":{"from":66,"to":81}} {"id":100019120,"name":"SetAuthenticationInfoResolverWrapper","signature":"func (cm *ClientManager) SetAuthenticationInfoResolverWrapper(wrapper AuthenticationInfoResolverWrapper)","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/client.go","code":"// SetAuthenticationInfoResolverWrapper sets the\n// AuthenticationInfoResolverWrapper.\nfunc (cm *ClientManager) SetAuthenticationInfoResolverWrapper(wrapper AuthenticationInfoResolverWrapper) {\n\tif wrapper != nil {\n\t\tcm.authInfoResolver = wrapper(cm.authInfoResolver)\n\t}\n}","line":{"from":83,"to":89}} {"id":100019121,"name":"SetAuthenticationInfoResolver","signature":"func (cm *ClientManager) SetAuthenticationInfoResolver(resolver AuthenticationInfoResolver)","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/client.go","code":"// SetAuthenticationInfoResolver sets the AuthenticationInfoResolver.\nfunc (cm *ClientManager) SetAuthenticationInfoResolver(resolver AuthenticationInfoResolver) {\n\tcm.authInfoResolver = resolver\n}","line":{"from":91,"to":94}} {"id":100019122,"name":"SetServiceResolver","signature":"func (cm *ClientManager) SetServiceResolver(sr ServiceResolver)","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/client.go","code":"// SetServiceResolver sets the ServiceResolver.\nfunc (cm *ClientManager) SetServiceResolver(sr ServiceResolver) {\n\tif sr != nil {\n\t\tcm.serviceResolver = sr\n\t}\n}","line":{"from":96,"to":101}} {"id":100019123,"name":"Validate","signature":"func (cm *ClientManager) Validate() error","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/client.go","code":"// Validate checks if ClientManager is properly set up.\nfunc (cm *ClientManager) Validate() error {\n\tvar errs []error\n\tif cm.negotiatedSerializer == nil {\n\t\terrs = append(errs, fmt.Errorf(\"the clientManager requires a negotiatedSerializer\"))\n\t}\n\tif cm.serviceResolver == nil {\n\t\terrs = append(errs, fmt.Errorf(\"the clientManager requires a serviceResolver\"))\n\t}\n\tif cm.authInfoResolver == nil {\n\t\terrs = append(errs, fmt.Errorf(\"the clientManager requires an authInfoResolver\"))\n\t}\n\treturn utilerrors.NewAggregate(errs)\n}","line":{"from":103,"to":116}} {"id":100019124,"name":"HookClient","signature":"func (cm *ClientManager) HookClient(cc ClientConfig) (*rest.RESTClient, error)","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/client.go","code":"// HookClient get a RESTClient from the cache, or constructs one based on the\n// webhook configuration.\nfunc (cm *ClientManager) HookClient(cc ClientConfig) (*rest.RESTClient, error) {\n\tccWithNoName := cc\n\tccWithNoName.Name = \"\"\n\tcacheKey, err := json.Marshal(ccWithNoName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif client, ok := cm.cache.Get(string(cacheKey)); ok {\n\t\treturn client.(*rest.RESTClient), nil\n\t}\n\n\tcomplete := func(cfg *rest.Config) (*rest.RESTClient, error) {\n\t\t// Avoid client-side rate limiting talking to the webhook backend.\n\t\t// Rate limiting should happen when deciding how many requests to serve.\n\t\tcfg.QPS = -1\n\n\t\t// Combine CAData from the config with any existing CA bundle provided\n\t\tif len(cfg.TLSClientConfig.CAData) \u003e 0 {\n\t\t\tcfg.TLSClientConfig.CAData = append(cfg.TLSClientConfig.CAData, '\\n')\n\t\t}\n\t\tcfg.TLSClientConfig.CAData = append(cfg.TLSClientConfig.CAData, cc.CABundle...)\n\n\t\t// Use http/1.1 instead of http/2.\n\t\t// This is a workaround for http/2-enabled clients not load-balancing concurrent requests to multiple backends.\n\t\t// See https://issue.k8s.io/75791 for details.\n\t\tcfg.NextProtos = []string{\"http/1.1\"}\n\n\t\tcfg.ContentConfig.NegotiatedSerializer = cm.negotiatedSerializer\n\t\tcfg.ContentConfig.ContentType = runtime.ContentTypeJSON\n\n\t\t// Add a transport wrapper that allows detection of TLS connections to\n\t\t// servers with serving certificates with deprecated characteristics\n\t\tcfg.Wrap(x509metrics.NewDeprecatedCertificateRoundTripperWrapperConstructor(\n\t\t\tx509MissingSANCounter,\n\t\t\tx509InsecureSHA1Counter,\n\t\t))\n\n\t\tclient, err := rest.UnversionedRESTClientFor(cfg)\n\t\tif err == nil {\n\t\t\tcm.cache.Add(string(cacheKey), client)\n\t\t}\n\t\treturn client, err\n\t}\n\n\tif cc.Service != nil {\n\t\tport := cc.Service.Port\n\t\tif port == 0 {\n\t\t\t// Default to port 443 if no service port is specified\n\t\t\tport = 443\n\t\t}\n\n\t\trestConfig, err := cm.authInfoResolver.ClientConfigForService(cc.Service.Name, cc.Service.Namespace, int(port))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcfg := rest.CopyConfig(restConfig)\n\t\tserverName := cc.Service.Name + \".\" + cc.Service.Namespace + \".svc\"\n\n\t\thost := net.JoinHostPort(serverName, strconv.Itoa(int(port)))\n\t\tcfg.Host = \"https://\" + host\n\t\tcfg.APIPath = cc.Service.Path\n\t\t// Set the server name if not already set\n\t\tif len(cfg.TLSClientConfig.ServerName) == 0 {\n\t\t\tcfg.TLSClientConfig.ServerName = serverName\n\t\t}\n\n\t\tdelegateDialer := cfg.Dial\n\t\tif delegateDialer == nil {\n\t\t\tvar d net.Dialer\n\t\t\tdelegateDialer = d.DialContext\n\t\t}\n\t\tcfg.Dial = func(ctx context.Context, network, addr string) (net.Conn, error) {\n\t\t\tif addr == host {\n\t\t\t\tu, err := cm.serviceResolver.ResolveEndpoint(cc.Service.Namespace, cc.Service.Name, port)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\taddr = u.Host\n\t\t\t}\n\t\t\treturn delegateDialer(ctx, network, addr)\n\t\t}\n\n\t\treturn complete(cfg)\n\t}\n\n\tif cc.URL == \"\" {\n\t\treturn nil, \u0026ErrCallingWebhook{WebhookName: cc.Name, Reason: errors.New(\"webhook configuration must have either service or URL\")}\n\t}\n\n\tu, err := url.Parse(cc.URL)\n\tif err != nil {\n\t\treturn nil, \u0026ErrCallingWebhook{WebhookName: cc.Name, Reason: fmt.Errorf(\"Unparsable URL: %v\", err)}\n\t}\n\n\thostPort := u.Host\n\tif len(u.Port()) == 0 {\n\t\t// Default to port 443 if no port is specified\n\t\thostPort = net.JoinHostPort(hostPort, \"443\")\n\t}\n\n\trestConfig, err := cm.authInfoResolver.ClientConfigFor(hostPort)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcfg := rest.CopyConfig(restConfig)\n\tcfg.Host = u.Scheme + \"://\" + u.Host\n\tcfg.APIPath = u.Path\n\n\treturn complete(cfg)\n}","line":{"from":118,"to":230}} {"id":100019125,"name":"Error","signature":"func (e *ErrCallingWebhook) Error() string","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/error.go","code":"func (e *ErrCallingWebhook) Error() string {\n\tif e.Reason != nil {\n\t\treturn fmt.Sprintf(\"failed calling webhook %q: %v\", e.WebhookName, e.Reason)\n\t}\n\treturn fmt.Sprintf(\"failed calling webhook %q; no further details available\", e.WebhookName)\n}","line":{"from":34,"to":39}} {"id":100019126,"name":"Error","signature":"func (e *ErrWebhookRejection) Error() string","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/error.go","code":"func (e *ErrWebhookRejection) Error() string {\n\treturn e.Status.Error()\n}","line":{"from":46,"to":48}} {"id":100019127,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/metrics.go","code":"func init() {\n\tlegacyregistry.MustRegister(x509MissingSANCounter)\n\tlegacyregistry.MustRegister(x509InsecureSHA1Counter)\n}","line":{"from":49,"to":52}} {"id":100019128,"name":"NewDefaultServiceResolver","signature":"func NewDefaultServiceResolver() ServiceResolver","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/serviceresolver.go","code":"// NewDefaultServiceResolver creates a new default server resolver.\nfunc NewDefaultServiceResolver() ServiceResolver {\n\treturn \u0026defaultServiceResolver{}\n}","line":{"from":32,"to":35}} {"id":100019129,"name":"ResolveEndpoint","signature":"func (sr defaultServiceResolver) ResolveEndpoint(namespace, name string, port int32) (*url.URL, error)","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/serviceresolver.go","code":"// ResolveEndpoint constructs a service URL from a given namespace and name\n// note that the name, namespace, and port are required and by default all\n// created addresses use HTTPS scheme.\n// for example:\n//\n//\tname=ross namespace=andromeda resolves to https://ross.andromeda.svc:443\nfunc (sr defaultServiceResolver) ResolveEndpoint(namespace, name string, port int32) (*url.URL, error) {\n\tif len(name) == 0 || len(namespace) == 0 || port == 0 {\n\t\treturn nil, errors.New(\"cannot resolve an empty service name or namespace or port\")\n\t}\n\treturn \u0026url.URL{Scheme: \"https\", Host: fmt.Sprintf(\"%s.%s.svc:%d\", name, namespace, port)}, nil\n}","line":{"from":37,"to":48}} {"id":100019130,"name":"ValidateWebhookURL","signature":"func ValidateWebhookURL(fldPath *field.Path, URL string, forceHttps bool) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/validation.go","code":"// ValidateWebhookURL validates webhook's URL.\nfunc ValidateWebhookURL(fldPath *field.Path, URL string, forceHttps bool) field.ErrorList {\n\tvar allErrors field.ErrorList\n\tconst form = \"; desired format: https://host[/path]\"\n\tif u, err := url.Parse(URL); err != nil {\n\t\tallErrors = append(allErrors, field.Required(fldPath, \"url must be a valid URL: \"+err.Error()+form))\n\t} else {\n\t\tif forceHttps \u0026\u0026 u.Scheme != \"https\" {\n\t\t\tallErrors = append(allErrors, field.Invalid(fldPath, u.Scheme, \"'https' is the only allowed URL scheme\"+form))\n\t\t}\n\t\tif len(u.Host) == 0 {\n\t\t\tallErrors = append(allErrors, field.Invalid(fldPath, u.Host, \"host must be specified\"+form))\n\t\t}\n\t\tif u.User != nil {\n\t\t\tallErrors = append(allErrors, field.Invalid(fldPath, u.User.String(), \"user information is not permitted in the URL\"))\n\t\t}\n\t\tif len(u.Fragment) != 0 {\n\t\t\tallErrors = append(allErrors, field.Invalid(fldPath, u.Fragment, \"fragments are not permitted in the URL\"))\n\t\t}\n\t\tif len(u.RawQuery) != 0 {\n\t\t\tallErrors = append(allErrors, field.Invalid(fldPath, u.RawQuery, \"query parameters are not permitted in the URL\"))\n\t\t}\n\t}\n\treturn allErrors\n}","line":{"from":28,"to":52}} {"id":100019131,"name":"ValidateWebhookService","signature":"func ValidateWebhookService(fldPath *field.Path, namespace, name string, path *string, port int32) field.ErrorList","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/validation.go","code":"func ValidateWebhookService(fldPath *field.Path, namespace, name string, path *string, port int32) field.ErrorList {\n\tvar allErrors field.ErrorList\n\n\tif len(name) == 0 {\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"name\"), \"service name is required\"))\n\t}\n\n\tif len(namespace) == 0 {\n\t\tallErrors = append(allErrors, field.Required(fldPath.Child(\"namespace\"), \"service namespace is required\"))\n\t}\n\n\tif errs := validation.IsValidPortNum(int(port)); errs != nil {\n\t\tallErrors = append(allErrors, field.Invalid(fldPath.Child(\"port\"), port, \"port is not valid: \"+strings.Join(errs, \", \")))\n\t}\n\n\tif path == nil {\n\t\treturn allErrors\n\t}\n\n\t// TODO: replace below with url.Parse + verifying that host is empty?\n\n\turlPath := *path\n\tif urlPath == \"/\" || len(urlPath) == 0 {\n\t\treturn allErrors\n\t}\n\tif urlPath == \"//\" {\n\t\tallErrors = append(allErrors, field.Invalid(fldPath.Child(\"path\"), urlPath, \"segment[0] may not be empty\"))\n\t\treturn allErrors\n\t}\n\n\tif !strings.HasPrefix(urlPath, \"/\") {\n\t\tallErrors = append(allErrors, field.Invalid(fldPath.Child(\"path\"), urlPath, \"must start with a '/'\"))\n\t}\n\n\turlPathToCheck := urlPath[1:]\n\tif strings.HasSuffix(urlPathToCheck, \"/\") {\n\t\turlPathToCheck = urlPathToCheck[:len(urlPathToCheck)-1]\n\t}\n\tsteps := strings.Split(urlPathToCheck, \"/\")\n\tfor i, step := range steps {\n\t\tif len(step) == 0 {\n\t\t\tallErrors = append(allErrors, field.Invalid(fldPath.Child(\"path\"), urlPath, fmt.Sprintf(\"segment[%d] may not be empty\", i)))\n\t\t\tcontinue\n\t\t}\n\t\tfailures := validation.IsDNS1123Subdomain(step)\n\t\tfor _, failure := range failures {\n\t\t\tallErrors = append(allErrors, field.Invalid(fldPath.Child(\"path\"), urlPath, fmt.Sprintf(\"segment[%d]: %v\", i, failure)))\n\t\t}\n\t}\n\n\treturn allErrors\n}","line":{"from":54,"to":105}} {"id":100019132,"name":"DefaultRetryBackoffWithInitialDelay","signature":"func DefaultRetryBackoffWithInitialDelay(initialBackoffDelay time.Duration) wait.Backoff","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/webhook.go","code":"// DefaultRetryBackoffWithInitialDelay returns the default backoff parameters for webhook retry from a given initial delay.\n// Handy for the client that provides a custom initial delay only.\nfunc DefaultRetryBackoffWithInitialDelay(initialBackoffDelay time.Duration) wait.Backoff {\n\treturn wait.Backoff{\n\t\tDuration: initialBackoffDelay,\n\t\tFactor: 1.5,\n\t\tJitter: 0.2,\n\t\tSteps: 5,\n\t}\n}","line":{"from":40,"to":49}} {"id":100019133,"name":"DefaultShouldRetry","signature":"func DefaultShouldRetry(err error) bool","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/webhook.go","code":"// DefaultShouldRetry is a default implementation for the GenericWebhook ShouldRetry function property.\n// If the error reason is one of: networking (connection reset) or http (InternalServerError (500), GatewayTimeout (504), TooManyRequests (429)),\n// or apierrors.SuggestsClientDelay() returns true, then the function advises a retry.\n// Otherwise it returns false for an immediate fail.\nfunc DefaultShouldRetry(err error) bool {\n\t// these errors indicate a transient error that should be retried.\n\tif utilnet.IsConnectionReset(err) || apierrors.IsInternalError(err) || apierrors.IsTimeout(err) || apierrors.IsTooManyRequests(err) {\n\t\treturn true\n\t}\n\t// if the error sends the Retry-After header, we respect it as an explicit confirmation we should retry.\n\tif _, shouldRetry := apierrors.SuggestsClientDelay(err); shouldRetry {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":59,"to":73}} {"id":100019134,"name":"NewGenericWebhook","signature":"func NewGenericWebhook(scheme *runtime.Scheme, codecFactory serializer.CodecFactory, config *rest.Config, groupVersions []schema.GroupVersion, retryBackoff wait.Backoff) (*GenericWebhook, error)","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/webhook.go","code":"// NewGenericWebhook creates a new GenericWebhook from the provided rest.Config.\nfunc NewGenericWebhook(scheme *runtime.Scheme, codecFactory serializer.CodecFactory, config *rest.Config, groupVersions []schema.GroupVersion, retryBackoff wait.Backoff) (*GenericWebhook, error) {\n\tfor _, groupVersion := range groupVersions {\n\t\tif !scheme.IsVersionRegistered(groupVersion) {\n\t\t\treturn nil, fmt.Errorf(\"webhook plugin requires enabling extension resource: %s\", groupVersion)\n\t\t}\n\t}\n\n\tclientConfig := rest.CopyConfig(config)\n\n\tcodec := codecFactory.LegacyCodec(groupVersions...)\n\tclientConfig.ContentConfig.NegotiatedSerializer = serializer.NegotiatedSerializerWrapper(runtime.SerializerInfo{Serializer: codec})\n\n\tclientConfig.Wrap(x509metrics.NewDeprecatedCertificateRoundTripperWrapperConstructor(\n\t\tx509MissingSANCounter,\n\t\tx509InsecureSHA1Counter,\n\t))\n\n\trestClient, err := rest.UnversionedRESTClientFor(clientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026GenericWebhook{restClient, retryBackoff, DefaultShouldRetry}, nil\n}","line":{"from":75,"to":99}} {"id":100019135,"name":"WithExponentialBackoff","signature":"func (g *GenericWebhook) WithExponentialBackoff(ctx context.Context, webhookFn func() rest.Result) rest.Result","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/webhook.go","code":"// WithExponentialBackoff will retry webhookFn() as specified by the given backoff parameters with exponentially\n// increasing backoff when it returns an error for which this GenericWebhook's ShouldRetry function returns true,\n// confirming it to be retriable. If no ShouldRetry has been defined for the webhook,\n// then the default one is used (DefaultShouldRetry).\nfunc (g *GenericWebhook) WithExponentialBackoff(ctx context.Context, webhookFn func() rest.Result) rest.Result {\n\tvar result rest.Result\n\tshouldRetry := g.ShouldRetry\n\tif shouldRetry == nil {\n\t\tshouldRetry = DefaultShouldRetry\n\t}\n\tWithExponentialBackoff(ctx, g.RetryBackoff, func() error {\n\t\tresult = webhookFn()\n\t\treturn result.Error()\n\t}, shouldRetry)\n\treturn result\n}","line":{"from":101,"to":116}} {"id":100019136,"name":"WithExponentialBackoff","signature":"func WithExponentialBackoff(ctx context.Context, retryBackoff wait.Backoff, webhookFn func() error, shouldRetry func(error) bool) error","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/webhook.go","code":"// WithExponentialBackoff will retry webhookFn up to 5 times with exponentially increasing backoff when\n// it returns an error for which shouldRetry returns true, confirming it to be retriable.\nfunc WithExponentialBackoff(ctx context.Context, retryBackoff wait.Backoff, webhookFn func() error, shouldRetry func(error) bool) error {\n\t// having a webhook error allows us to track the last actual webhook error for requests that\n\t// are later cancelled or time out.\n\tvar webhookErr error\n\terr := wait.ExponentialBackoffWithContext(ctx, retryBackoff, func(_ context.Context) (bool, error) {\n\t\twebhookErr = webhookFn()\n\t\tif shouldRetry(webhookErr) {\n\t\t\treturn false, nil\n\t\t}\n\t\tif webhookErr != nil {\n\t\t\treturn false, webhookErr\n\t\t}\n\t\treturn true, nil\n\t})\n\n\tswitch {\n\t// we check for webhookErr first, if webhookErr is set it's the most important error to return.\n\tcase webhookErr != nil:\n\t\treturn webhookErr\n\tcase err != nil:\n\t\treturn fmt.Errorf(\"webhook call failed: %s\", err.Error())\n\tdefault:\n\t\treturn nil\n\t}\n}","line":{"from":118,"to":144}} {"id":100019137,"name":"LoadKubeconfig","signature":"func LoadKubeconfig(kubeConfigFile string, customDial utilnet.DialFunc) (*rest.Config, error)","file":"staging/src/k8s.io/apiserver/pkg/util/webhook/webhook.go","code":"func LoadKubeconfig(kubeConfigFile string, customDial utilnet.DialFunc) (*rest.Config, error) {\n\tloadingRules := clientcmd.NewDefaultClientConfigLoadingRules()\n\tloadingRules.ExplicitPath = kubeConfigFile\n\tloader := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, \u0026clientcmd.ConfigOverrides{})\n\n\tclientConfig, err := loader.ClientConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclientConfig.Dial = customDial\n\n\t// Kubeconfigs can't set a timeout, this can only be set through a command line flag.\n\t//\n\t// https://github.com/kubernetes/client-go/blob/master/tools/clientcmd/overrides.go\n\t//\n\t// Set this to something reasonable so request to webhooks don't hang forever.\n\tclientConfig.Timeout = defaultRequestTimeout\n\n\t// Avoid client-side rate limiting talking to the webhook backend.\n\t// Rate limiting should happen when deciding how many requests to serve.\n\tclientConfig.QPS = -1\n\n\treturn clientConfig, nil\n}","line":{"from":146,"to":170}} {"id":100019138,"name":"IsWebSocketRequest","signature":"func IsWebSocketRequest(req *http.Request) bool","file":"staging/src/k8s.io/apiserver/pkg/util/wsstream/conn.go","code":"// IsWebSocketRequest returns true if the incoming request contains connection upgrade headers\n// for WebSockets.\nfunc IsWebSocketRequest(req *http.Request) bool {\n\tif !strings.EqualFold(req.Header.Get(\"Upgrade\"), \"websocket\") {\n\t\treturn false\n\t}\n\treturn connectionUpgradeRegex.MatchString(strings.ToLower(req.Header.Get(\"Connection\")))\n}","line":{"from":85,"to":92}} {"id":100019139,"name":"IgnoreReceives","signature":"func IgnoreReceives(ws *websocket.Conn, timeout time.Duration)","file":"staging/src/k8s.io/apiserver/pkg/util/wsstream/conn.go","code":"// IgnoreReceives reads from a WebSocket until it is closed, then returns. If timeout is set, the\n// read and write deadlines are pushed every time a new message is received.\nfunc IgnoreReceives(ws *websocket.Conn, timeout time.Duration) {\n\tdefer runtime.HandleCrash()\n\tvar data []byte\n\tfor {\n\t\tresetTimeout(ws, timeout)\n\t\tif err := websocket.Message.Receive(ws, \u0026data); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n}","line":{"from":94,"to":105}} {"id":100019140,"name":"handshake","signature":"func handshake(config *websocket.Config, req *http.Request, allowed []string) error","file":"staging/src/k8s.io/apiserver/pkg/util/wsstream/conn.go","code":"// handshake ensures the provided user protocol matches one of the allowed protocols. It returns\n// no error if no protocol is specified.\nfunc handshake(config *websocket.Config, req *http.Request, allowed []string) error {\n\tprotocols := config.Protocol\n\tif len(protocols) == 0 {\n\t\tprotocols = []string{\"\"}\n\t}\n\n\tfor _, protocol := range protocols {\n\t\tfor _, allow := range allowed {\n\t\t\tif allow == protocol {\n\t\t\t\tconfig.Protocol = []string{protocol}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"requested protocol(s) are not supported: %v; supports %v\", config.Protocol, allowed)\n}","line":{"from":107,"to":125}} {"id":100019141,"name":"NewDefaultChannelProtocols","signature":"func NewDefaultChannelProtocols(channels []ChannelType) map[string]ChannelProtocolConfig","file":"staging/src/k8s.io/apiserver/pkg/util/wsstream/conn.go","code":"// NewDefaultChannelProtocols returns a channel protocol map with the\n// subprotocols \"\", \"channel.k8s.io\", \"base64.channel.k8s.io\" and the given\n// channels.\nfunc NewDefaultChannelProtocols(channels []ChannelType) map[string]ChannelProtocolConfig {\n\treturn map[string]ChannelProtocolConfig{\n\t\t\"\": {Binary: true, Channels: channels},\n\t\tChannelWebSocketProtocol: {Binary: true, Channels: channels},\n\t\tBase64ChannelWebSocketProtocol: {Binary: false, Channels: channels},\n\t}\n}","line":{"from":133,"to":142}} {"id":100019142,"name":"NewConn","signature":"func NewConn(protocols map[string]ChannelProtocolConfig) *Conn","file":"staging/src/k8s.io/apiserver/pkg/util/wsstream/conn.go","code":"// NewConn creates a WebSocket connection that supports a set of channels. Channels begin each\n// web socket message with a single byte indicating the channel number (0-N). 255 is reserved for\n// future use. The channel types for each channel are passed as an array, supporting the different\n// duplex modes. Read and Write refer to whether the channel can be used as a Reader or Writer.\n//\n// The protocols parameter maps subprotocol names to ChannelProtocols. The empty string subprotocol\n// name is used if websocket.Config.Protocol is empty.\nfunc NewConn(protocols map[string]ChannelProtocolConfig) *Conn {\n\treturn \u0026Conn{\n\t\tready: make(chan struct{}),\n\t\tprotocols: protocols,\n\t}\n}","line":{"from":155,"to":167}} {"id":100019143,"name":"SetIdleTimeout","signature":"func (conn *Conn) SetIdleTimeout(duration time.Duration)","file":"staging/src/k8s.io/apiserver/pkg/util/wsstream/conn.go","code":"// SetIdleTimeout sets the interval for both reads and writes before timeout. If not specified,\n// there is no timeout on the connection.\nfunc (conn *Conn) SetIdleTimeout(duration time.Duration) {\n\tconn.timeout = duration\n}","line":{"from":169,"to":173}} {"id":100019144,"name":"Open","signature":"func (conn *Conn) Open(w http.ResponseWriter, req *http.Request) (string, []io.ReadWriteCloser, error)","file":"staging/src/k8s.io/apiserver/pkg/util/wsstream/conn.go","code":"// Open the connection and create channels for reading and writing. It returns\n// the selected subprotocol, a slice of channels and an error.\nfunc (conn *Conn) Open(w http.ResponseWriter, req *http.Request) (string, []io.ReadWriteCloser, error) {\n\tgo func() {\n\t\tdefer runtime.HandleCrash()\n\t\tdefer conn.Close()\n\t\twebsocket.Server{Handshake: conn.handshake, Handler: conn.handle}.ServeHTTP(w, req)\n\t}()\n\t\u003c-conn.ready\n\trwc := make([]io.ReadWriteCloser, len(conn.channels))\n\tfor i := range conn.channels {\n\t\trwc[i] = conn.channels[i]\n\t}\n\treturn conn.selectedProtocol, rwc, nil\n}","line":{"from":175,"to":189}} {"id":100019145,"name":"initialize","signature":"func (conn *Conn) initialize(ws *websocket.Conn)","file":"staging/src/k8s.io/apiserver/pkg/util/wsstream/conn.go","code":"func (conn *Conn) initialize(ws *websocket.Conn) {\n\tnegotiated := ws.Config().Protocol\n\tconn.selectedProtocol = negotiated[0]\n\tp := conn.protocols[conn.selectedProtocol]\n\tif p.Binary {\n\t\tconn.codec = rawCodec\n\t} else {\n\t\tconn.codec = base64Codec\n\t}\n\tconn.ws = ws\n\tconn.channels = make([]*websocketChannel, len(p.Channels))\n\tfor i, t := range p.Channels {\n\t\tswitch t {\n\t\tcase ReadChannel:\n\t\t\tconn.channels[i] = newWebsocketChannel(conn, byte(i), true, false)\n\t\tcase WriteChannel:\n\t\t\tconn.channels[i] = newWebsocketChannel(conn, byte(i), false, true)\n\t\tcase ReadWriteChannel:\n\t\t\tconn.channels[i] = newWebsocketChannel(conn, byte(i), true, true)\n\t\tcase IgnoreChannel:\n\t\t\tconn.channels[i] = newWebsocketChannel(conn, byte(i), false, false)\n\t\t}\n\t}\n\n\tclose(conn.ready)\n}","line":{"from":191,"to":216}} {"id":100019146,"name":"handshake","signature":"func (conn *Conn) handshake(config *websocket.Config, req *http.Request) error","file":"staging/src/k8s.io/apiserver/pkg/util/wsstream/conn.go","code":"func (conn *Conn) handshake(config *websocket.Config, req *http.Request) error {\n\tsupportedProtocols := make([]string, 0, len(conn.protocols))\n\tfor p := range conn.protocols {\n\t\tsupportedProtocols = append(supportedProtocols, p)\n\t}\n\treturn handshake(config, req, supportedProtocols)\n}","line":{"from":218,"to":224}} {"id":100019147,"name":"resetTimeout","signature":"func (conn *Conn) resetTimeout()","file":"staging/src/k8s.io/apiserver/pkg/util/wsstream/conn.go","code":"func (conn *Conn) resetTimeout() {\n\tif conn.timeout \u003e 0 {\n\t\tconn.ws.SetDeadline(time.Now().Add(conn.timeout))\n\t}\n}","line":{"from":226,"to":230}} {"id":100019148,"name":"Close","signature":"func (conn *Conn) Close() error","file":"staging/src/k8s.io/apiserver/pkg/util/wsstream/conn.go","code":"// Close is only valid after Open has been called\nfunc (conn *Conn) Close() error {\n\t\u003c-conn.ready\n\tfor _, s := range conn.channels {\n\t\ts.Close()\n\t}\n\tconn.ws.Close()\n\treturn nil\n}","line":{"from":232,"to":240}} {"id":100019149,"name":"handle","signature":"func (conn *Conn) handle(ws *websocket.Conn)","file":"staging/src/k8s.io/apiserver/pkg/util/wsstream/conn.go","code":"// handle implements a websocket handler.\nfunc (conn *Conn) handle(ws *websocket.Conn) {\n\tdefer conn.Close()\n\tconn.initialize(ws)\n\n\tfor {\n\t\tconn.resetTimeout()\n\t\tvar data []byte\n\t\tif err := websocket.Message.Receive(ws, \u0026data); err != nil {\n\t\t\tif err != io.EOF {\n\t\t\t\tklog.Errorf(\"Error on socket receive: %v\", err)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tif len(data) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tchannel := data[0]\n\t\tif conn.codec == base64Codec {\n\t\t\tchannel = channel - '0'\n\t\t}\n\t\tdata = data[1:]\n\t\tif int(channel) \u003e= len(conn.channels) {\n\t\t\tklog.V(6).Infof(\"Frame is targeted for a reader %d that is not valid, possible protocol error\", channel)\n\t\t\tcontinue\n\t\t}\n\t\tif _, err := conn.channels[channel].DataFromSocket(data); err != nil {\n\t\t\tklog.Errorf(\"Unable to write frame to %d: %v\\n%s\", channel, err, string(data))\n\t\t\tcontinue\n\t\t}\n\t}\n}","line":{"from":242,"to":273}} {"id":100019150,"name":"write","signature":"func (conn *Conn) write(num byte, data []byte) (int, error)","file":"staging/src/k8s.io/apiserver/pkg/util/wsstream/conn.go","code":"// write multiplexes the specified channel onto the websocket\nfunc (conn *Conn) write(num byte, data []byte) (int, error) {\n\tconn.resetTimeout()\n\tswitch conn.codec {\n\tcase rawCodec:\n\t\tframe := make([]byte, len(data)+1)\n\t\tframe[0] = num\n\t\tcopy(frame[1:], data)\n\t\tif err := websocket.Message.Send(conn.ws, frame); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\tcase base64Codec:\n\t\tframe := string('0'+num) + base64.StdEncoding.EncodeToString(data)\n\t\tif err := websocket.Message.Send(conn.ws, frame); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn len(data), nil\n}","line":{"from":275,"to":293}} {"id":100019151,"name":"newWebsocketChannel","signature":"func newWebsocketChannel(conn *Conn, num byte, read, write bool) *websocketChannel","file":"staging/src/k8s.io/apiserver/pkg/util/wsstream/conn.go","code":"// newWebsocketChannel creates a pipe for writing to a websocket. Do not write to this pipe\n// prior to the connection being opened. It may be no, half, or full duplex depending on\n// read and write.\nfunc newWebsocketChannel(conn *Conn, num byte, read, write bool) *websocketChannel {\n\tr, w := io.Pipe()\n\treturn \u0026websocketChannel{conn, num, r, w, read, write}\n}","line":{"from":305,"to":311}} {"id":100019152,"name":"Write","signature":"func (p *websocketChannel) Write(data []byte) (int, error)","file":"staging/src/k8s.io/apiserver/pkg/util/wsstream/conn.go","code":"func (p *websocketChannel) Write(data []byte) (int, error) {\n\tif !p.write {\n\t\treturn len(data), nil\n\t}\n\treturn p.conn.write(p.num, data)\n}","line":{"from":313,"to":318}} {"id":100019153,"name":"DataFromSocket","signature":"func (p *websocketChannel) DataFromSocket(data []byte) (int, error)","file":"staging/src/k8s.io/apiserver/pkg/util/wsstream/conn.go","code":"// DataFromSocket is invoked by the connection receiver to move data from the connection\n// into a specific channel.\nfunc (p *websocketChannel) DataFromSocket(data []byte) (int, error) {\n\tif !p.read {\n\t\treturn len(data), nil\n\t}\n\n\tswitch p.conn.codec {\n\tcase rawCodec:\n\t\treturn p.w.Write(data)\n\tcase base64Codec:\n\t\tdst := make([]byte, len(data))\n\t\tn, err := base64.StdEncoding.Decode(dst, data)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\treturn p.w.Write(dst[:n])\n\t}\n\treturn 0, nil\n}","line":{"from":320,"to":339}} {"id":100019154,"name":"Read","signature":"func (p *websocketChannel) Read(data []byte) (int, error)","file":"staging/src/k8s.io/apiserver/pkg/util/wsstream/conn.go","code":"func (p *websocketChannel) Read(data []byte) (int, error) {\n\tif !p.read {\n\t\treturn 0, io.EOF\n\t}\n\treturn p.r.Read(data)\n}","line":{"from":341,"to":346}} {"id":100019155,"name":"Close","signature":"func (p *websocketChannel) Close() error","file":"staging/src/k8s.io/apiserver/pkg/util/wsstream/conn.go","code":"func (p *websocketChannel) Close() error {\n\treturn p.w.Close()\n}","line":{"from":348,"to":350}} {"id":100019156,"name":"NewDefaultReaderProtocols","signature":"func NewDefaultReaderProtocols() map[string]ReaderProtocolConfig","file":"staging/src/k8s.io/apiserver/pkg/util/wsstream/stream.go","code":"// NewDefaultReaderProtocols returns a stream protocol map with the\n// subprotocols \"\", \"channel.k8s.io\", \"base64.channel.k8s.io\".\nfunc NewDefaultReaderProtocols() map[string]ReaderProtocolConfig {\n\treturn map[string]ReaderProtocolConfig{\n\t\t\"\": {Binary: true},\n\t\tbinaryWebSocketProtocol: {Binary: true},\n\t\tbase64BinaryWebSocketProtocol: {Binary: false},\n\t}\n}","line":{"from":47,"to":55}} {"id":100019157,"name":"NewReader","signature":"func NewReader(r io.Reader, ping bool, protocols map[string]ReaderProtocolConfig) *Reader","file":"staging/src/k8s.io/apiserver/pkg/util/wsstream/stream.go","code":"// NewReader creates a WebSocket pipe that will copy the contents of r to a provided\n// WebSocket connection. If ping is true, a zero length message will be sent to the client\n// before the stream begins reading.\n//\n// The protocols parameter maps subprotocol names to StreamProtocols. The empty string\n// subprotocol name is used if websocket.Config.Protocol is empty.\nfunc NewReader(r io.Reader, ping bool, protocols map[string]ReaderProtocolConfig) *Reader {\n\treturn \u0026Reader{\n\t\tr: r,\n\t\terr: make(chan error),\n\t\tping: ping,\n\t\tprotocols: protocols,\n\t\thandleCrash: runtime.HandleCrash,\n\t}\n}","line":{"from":69,"to":83}} {"id":100019158,"name":"SetIdleTimeout","signature":"func (r *Reader) SetIdleTimeout(duration time.Duration)","file":"staging/src/k8s.io/apiserver/pkg/util/wsstream/stream.go","code":"// SetIdleTimeout sets the interval for both reads and writes before timeout. If not specified,\n// there is no timeout on the reader.\nfunc (r *Reader) SetIdleTimeout(duration time.Duration) {\n\tr.timeout = duration\n}","line":{"from":85,"to":89}} {"id":100019159,"name":"handshake","signature":"func (r *Reader) handshake(config *websocket.Config, req *http.Request) error","file":"staging/src/k8s.io/apiserver/pkg/util/wsstream/stream.go","code":"func (r *Reader) handshake(config *websocket.Config, req *http.Request) error {\n\tsupportedProtocols := make([]string, 0, len(r.protocols))\n\tfor p := range r.protocols {\n\t\tsupportedProtocols = append(supportedProtocols, p)\n\t}\n\treturn handshake(config, req, supportedProtocols)\n}","line":{"from":91,"to":97}} {"id":100019160,"name":"Copy","signature":"func (r *Reader) Copy(w http.ResponseWriter, req *http.Request) error","file":"staging/src/k8s.io/apiserver/pkg/util/wsstream/stream.go","code":"// Copy the reader to the response. The created WebSocket is closed after this\n// method completes.\nfunc (r *Reader) Copy(w http.ResponseWriter, req *http.Request) error {\n\tgo func() {\n\t\tdefer r.handleCrash()\n\t\twebsocket.Server{Handshake: r.handshake, Handler: r.handle}.ServeHTTP(w, req)\n\t}()\n\treturn \u003c-r.err\n}","line":{"from":99,"to":107}} {"id":100019161,"name":"handle","signature":"func (r *Reader) handle(ws *websocket.Conn)","file":"staging/src/k8s.io/apiserver/pkg/util/wsstream/stream.go","code":"// handle implements a WebSocket handler.\nfunc (r *Reader) handle(ws *websocket.Conn) {\n\t// Close the connection when the client requests it, or when we finish streaming, whichever happens first\n\tcloseConnOnce := \u0026sync.Once{}\n\tcloseConn := func() {\n\t\tcloseConnOnce.Do(func() {\n\t\t\tws.Close()\n\t\t})\n\t}\n\n\tnegotiated := ws.Config().Protocol\n\tr.selectedProtocol = negotiated[0]\n\tdefer close(r.err)\n\tdefer closeConn()\n\n\tgo func() {\n\t\tdefer runtime.HandleCrash()\n\t\t// This blocks until the connection is closed.\n\t\t// Client should not send anything.\n\t\tIgnoreReceives(ws, r.timeout)\n\t\t// Once the client closes, we should also close\n\t\tcloseConn()\n\t}()\n\n\tr.err \u003c- messageCopy(ws, r.r, !r.protocols[r.selectedProtocol].Binary, r.ping, r.timeout)\n}","line":{"from":109,"to":134}} {"id":100019162,"name":"resetTimeout","signature":"func resetTimeout(ws *websocket.Conn, timeout time.Duration)","file":"staging/src/k8s.io/apiserver/pkg/util/wsstream/stream.go","code":"func resetTimeout(ws *websocket.Conn, timeout time.Duration) {\n\tif timeout \u003e 0 {\n\t\tws.SetDeadline(time.Now().Add(timeout))\n\t}\n}","line":{"from":136,"to":140}} {"id":100019163,"name":"messageCopy","signature":"func messageCopy(ws *websocket.Conn, r io.Reader, base64Encode, ping bool, timeout time.Duration) error","file":"staging/src/k8s.io/apiserver/pkg/util/wsstream/stream.go","code":"func messageCopy(ws *websocket.Conn, r io.Reader, base64Encode, ping bool, timeout time.Duration) error {\n\tbuf := make([]byte, 2048)\n\tif ping {\n\t\tresetTimeout(ws, timeout)\n\t\tif base64Encode {\n\t\t\tif err := websocket.Message.Send(ws, \"\"); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tif err := websocket.Message.Send(ws, []byte{}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\tfor {\n\t\tresetTimeout(ws, timeout)\n\t\tn, err := r.Read(buf)\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tif n \u003e 0 {\n\t\t\tif base64Encode {\n\t\t\t\tif err := websocket.Message.Send(ws, base64.StdEncoding.EncodeToString(buf[:n])); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err := websocket.Message.Send(ws, buf[:n]); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":142,"to":177}} {"id":100019164,"name":"IncreaseMetricsCounter","signature":"func (c *counterRaiser) IncreaseMetricsCounter(req *http.Request)","file":"staging/src/k8s.io/apiserver/pkg/util/x509metrics/server_cert_deprecations.go","code":"func (c *counterRaiser) IncreaseMetricsCounter(req *http.Request) {\n\tif req != nil \u0026\u0026 req.URL != nil {\n\t\tif hostname := req.URL.Hostname(); len(hostname) \u003e 0 {\n\t\t\tprefix := fmt.Sprintf(\"%s.invalid-cert.kubernetes.io\", c.id)\n\t\t\tklog.Infof(\"%s: invalid certificate detected connecting to %q: %s\", prefix, hostname, c.reason)\n\t\t\taudit.AddAuditAnnotation(req.Context(), prefix+\"/\"+hostname, c.reason)\n\t\t}\n\t}\n\tc.counter.Inc()\n}","line":{"from":64,"to":73}} {"id":100019165,"name":"NewDeprecatedCertificateRoundTripperWrapperConstructor","signature":"func NewDeprecatedCertificateRoundTripperWrapperConstructor(missingSAN, sha1 *metrics.Counter) func(rt http.RoundTripper) http.RoundTripper","file":"staging/src/k8s.io/apiserver/pkg/util/x509metrics/server_cert_deprecations.go","code":"// NewDeprecatedCertificateRoundTripperWrapperConstructor returns a RoundTripper wrapper that's usable within ClientConfig.Wrap.\n//\n// It increases the `missingSAN` counter whenever:\n// 1. we get a x509.HostnameError with string `x509: certificate relies on legacy Common Name field`\n// which indicates an error caused by the deprecation of Common Name field when veryfing remote\n// hostname\n// 2. the server certificate in response contains no SAN. This indicates that this binary run\n// with the GODEBUG=x509ignoreCN=0 in env\n//\n// It increases the `sha1` counter whenever:\n// 1. we get a x509.InsecureAlgorithmError with string `SHA1`\n// which indicates an error caused by an insecure SHA1 signature\n// 2. the server certificate in response contains a SHA1WithRSA or ECDSAWithSHA1 signature.\n// This indicates that this binary run with the GODEBUG=x509sha1=1 in env\nfunc NewDeprecatedCertificateRoundTripperWrapperConstructor(missingSAN, sha1 *metrics.Counter) func(rt http.RoundTripper) http.RoundTripper {\n\treturn func(rt http.RoundTripper) http.RoundTripper {\n\t\treturn \u0026x509DeprecatedCertificateMetricsRTWrapper{\n\t\t\trt: rt,\n\t\t\tcheckers: []deprecatedCertificateAttributeChecker{\n\t\t\t\tNewSANDeprecatedChecker(missingSAN),\n\t\t\t\tNewSHA1SignatureDeprecatedChecker(sha1),\n\t\t\t},\n\t\t}\n\t}\n}","line":{"from":75,"to":99}} {"id":100019166,"name":"RoundTrip","signature":"func (w *x509DeprecatedCertificateMetricsRTWrapper) RoundTrip(req *http.Request) (*http.Response, error)","file":"staging/src/k8s.io/apiserver/pkg/util/x509metrics/server_cert_deprecations.go","code":"func (w *x509DeprecatedCertificateMetricsRTWrapper) RoundTrip(req *http.Request) (*http.Response, error) {\n\tresp, err := w.rt.RoundTrip(req)\n\n\tif err != nil {\n\t\tfor _, checker := range w.checkers {\n\t\t\tif checker.CheckRoundTripError(err) {\n\t\t\t\tchecker.IncreaseMetricsCounter(req)\n\t\t\t}\n\t\t}\n\t} else if resp != nil {\n\t\tif resp.TLS != nil \u0026\u0026 len(resp.TLS.PeerCertificates) \u003e 0 {\n\t\t\tfor _, checker := range w.checkers {\n\t\t\t\tif checker.CheckPeerCertificates(resp.TLS.PeerCertificates) {\n\t\t\t\t\tchecker.IncreaseMetricsCounter(req)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn resp, err\n}","line":{"from":101,"to":121}} {"id":100019167,"name":"WrappedRoundTripper","signature":"func (w *x509DeprecatedCertificateMetricsRTWrapper) WrappedRoundTripper() http.RoundTripper","file":"staging/src/k8s.io/apiserver/pkg/util/x509metrics/server_cert_deprecations.go","code":"func (w *x509DeprecatedCertificateMetricsRTWrapper) WrappedRoundTripper() http.RoundTripper {\n\treturn w.rt\n}","line":{"from":123,"to":125}} {"id":100019168,"name":"NewSANDeprecatedChecker","signature":"func NewSANDeprecatedChecker(counter *metrics.Counter) *missingSANChecker","file":"staging/src/k8s.io/apiserver/pkg/util/x509metrics/server_cert_deprecations.go","code":"func NewSANDeprecatedChecker(counter *metrics.Counter) *missingSANChecker {\n\treturn \u0026missingSANChecker{\n\t\tcounterRaiser: counterRaiser{\n\t\t\tcounter: counter,\n\t\t\tid: \"missing-san\",\n\t\t\treason: \"relies on a legacy Common Name field instead of the SAN extension for subject validation\",\n\t\t},\n\t}\n}","line":{"from":133,"to":141}} {"id":100019169,"name":"CheckRoundTripError","signature":"func (c *missingSANChecker) CheckRoundTripError(err error) bool","file":"staging/src/k8s.io/apiserver/pkg/util/x509metrics/server_cert_deprecations.go","code":"// CheckRoundTripError returns true when we're running w/o GODEBUG=x509ignoreCN=0\n// and the client reports a HostnameError about the legacy CN fields\nfunc (c *missingSANChecker) CheckRoundTripError(err error) bool {\n\tif err != nil \u0026\u0026 errors.As(err, \u0026x509.HostnameError{}) \u0026\u0026 strings.Contains(err.Error(), \"x509: certificate relies on legacy Common Name field\") {\n\t\t// increase the count of registered failures due to Go 1.15 x509 cert Common Name deprecation\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":143,"to":152}} {"id":100019170,"name":"CheckPeerCertificates","signature":"func (c *missingSANChecker) CheckPeerCertificates(peerCertificates []*x509.Certificate) bool","file":"staging/src/k8s.io/apiserver/pkg/util/x509metrics/server_cert_deprecations.go","code":"// CheckPeerCertificates returns true when the server response contains\n// a leaf certificate w/o the SAN extension\nfunc (c *missingSANChecker) CheckPeerCertificates(peerCertificates []*x509.Certificate) bool {\n\tif len(peerCertificates) \u003e 0 {\n\t\tif serverCert := peerCertificates[0]; !hasSAN(serverCert) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":154,"to":164}} {"id":100019171,"name":"hasSAN","signature":"func hasSAN(c *x509.Certificate) bool","file":"staging/src/k8s.io/apiserver/pkg/util/x509metrics/server_cert_deprecations.go","code":"func hasSAN(c *x509.Certificate) bool {\n\tsanOID := []int{2, 5, 29, 17}\n\n\tfor _, e := range c.Extensions {\n\t\tif e.Id.Equal(sanOID) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":166,"to":175}} {"id":100019172,"name":"NewSHA1SignatureDeprecatedChecker","signature":"func NewSHA1SignatureDeprecatedChecker(counter *metrics.Counter) *sha1SignatureChecker","file":"staging/src/k8s.io/apiserver/pkg/util/x509metrics/server_cert_deprecations.go","code":"func NewSHA1SignatureDeprecatedChecker(counter *metrics.Counter) *sha1SignatureChecker {\n\treturn \u0026sha1SignatureChecker{\n\t\tcounterRaiser: \u0026counterRaiser{\n\t\t\tcounter: counter,\n\t\t\tid: \"insecure-sha1\",\n\t\t\treason: \"uses an insecure SHA-1 signature\",\n\t\t},\n\t}\n}","line":{"from":181,"to":189}} {"id":100019173,"name":"CheckRoundTripError","signature":"func (c *sha1SignatureChecker) CheckRoundTripError(err error) bool","file":"staging/src/k8s.io/apiserver/pkg/util/x509metrics/server_cert_deprecations.go","code":"// CheckRoundTripError returns true when we're running w/o GODEBUG=x509sha1=1\n// and the client reports an InsecureAlgorithmError about a SHA1 signature\nfunc (c *sha1SignatureChecker) CheckRoundTripError(err error) bool {\n\tvar unknownAuthorityError x509.UnknownAuthorityError\n\tif err == nil {\n\t\treturn false\n\t}\n\tif !errors.As(err, \u0026unknownAuthorityError) {\n\t\treturn false\n\t}\n\n\terrMsg := err.Error()\n\tif strIdx := strings.Index(errMsg, \"x509: cannot verify signature: insecure algorithm\"); strIdx != -1 \u0026\u0026 strings.Contains(errMsg[strIdx:], \"SHA1\") {\n\t\t// increase the count of registered failures due to Go 1.18 x509 sha1 signature deprecation\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":191,"to":209}} {"id":100019174,"name":"CheckPeerCertificates","signature":"func (c *sha1SignatureChecker) CheckPeerCertificates(peerCertificates []*x509.Certificate) bool","file":"staging/src/k8s.io/apiserver/pkg/util/x509metrics/server_cert_deprecations.go","code":"// CheckPeerCertificates returns true when the server response contains\n// a non-root non-self-signed certificate with a deprecated SHA1 signature\nfunc (c *sha1SignatureChecker) CheckPeerCertificates(peerCertificates []*x509.Certificate) bool {\n\t// check all received non-self-signed certificates for deprecated signing algorithms\n\tfor _, cert := range peerCertificates {\n\t\tif cert.SignatureAlgorithm == x509.SHA1WithRSA || cert.SignatureAlgorithm == x509.ECDSAWithSHA1 {\n\t\t\t// the SHA-1 deprecation does not involve self-signed root certificates\n\t\t\tif !reflect.DeepEqual(cert.Issuer, cert.Subject) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":211,"to":225}} {"id":100019175,"name":"WithWarningRecorder","signature":"func WithWarningRecorder(ctx context.Context, recorder Recorder) context.Context","file":"staging/src/k8s.io/apiserver/pkg/warning/context.go","code":"// WithWarningRecorder returns a new context that wraps the provided context and contains the provided Recorder implementation.\n// The returned context can be passed to AddWarning().\nfunc WithWarningRecorder(ctx context.Context, recorder Recorder) context.Context {\n\treturn context.WithValue(ctx, warningRecorderKey, recorder)\n}","line":{"from":39,"to":43}} {"id":100019176,"name":"warningRecorderFrom","signature":"func warningRecorderFrom(ctx context.Context) (Recorder, bool)","file":"staging/src/k8s.io/apiserver/pkg/warning/context.go","code":"func warningRecorderFrom(ctx context.Context) (Recorder, bool) {\n\trecorder, ok := ctx.Value(warningRecorderKey).(Recorder)\n\treturn recorder, ok\n}","line":{"from":45,"to":48}} {"id":100019177,"name":"AddWarning","signature":"func AddWarning(ctx context.Context, agent string, text string)","file":"staging/src/k8s.io/apiserver/pkg/warning/context.go","code":"// AddWarning records a warning for the specified agent and text to the Recorder added to the provided context using WithWarningRecorder().\n// If no Recorder exists in the provided context, this is a no-op.\n// agent must be valid UTF-8, and must not contain spaces, quotes, backslashes, or control characters.\n// text must be valid UTF-8, and must not contain control characters.\nfunc AddWarning(ctx context.Context, agent string, text string) {\n\trecorder, ok := warningRecorderFrom(ctx)\n\tif !ok {\n\t\treturn\n\t}\n\trecorder.AddWarning(agent, text)\n}","line":{"from":50,"to":60}} {"id":100019178,"name":"NewBackend","signature":"func NewBackend(delegate audit.Backend, config BatchConfig) audit.Backend","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/buffered/buffered.go","code":"// NewBackend returns a buffered audit backend that wraps delegate backend.\n// Buffered backend automatically runs and shuts down the delegate backend.\nfunc NewBackend(delegate audit.Backend, config BatchConfig) audit.Backend {\n\tvar throttle flowcontrol.RateLimiter\n\tif config.ThrottleEnable {\n\t\tthrottle = flowcontrol.NewTokenBucketRateLimiter(config.ThrottleQPS, config.ThrottleBurst)\n\t}\n\treturn \u0026bufferedBackend{\n\t\tdelegateBackend: delegate,\n\t\tbuffer: make(chan *auditinternal.Event, config.BufferSize),\n\t\tmaxBatchSize: config.MaxBatchSize,\n\t\tmaxBatchWait: config.MaxBatchWait,\n\t\tasyncDelegate: config.AsyncDelegate,\n\t\tshutdownCh: make(chan struct{}),\n\t\twg: sync.WaitGroup{},\n\t\tthrottle: throttle,\n\t}\n}","line":{"from":87,"to":104}} {"id":100019179,"name":"Run","signature":"func (b *bufferedBackend) Run(stopCh \u003c-chan struct{}) error","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/buffered/buffered.go","code":"func (b *bufferedBackend) Run(stopCh \u003c-chan struct{}) error {\n\tgo func() {\n\t\t// Signal that the working routine has exited.\n\t\tdefer close(b.shutdownCh)\n\n\t\tb.processIncomingEvents(stopCh)\n\n\t\t// Handle the events that were received after the last buffer\n\t\t// scraping and before this line. Since the buffer is closed, no new\n\t\t// events will come through.\n\t\tallEventsProcessed := false\n\t\ttimer := make(chan time.Time)\n\t\tfor !allEventsProcessed {\n\t\t\tallEventsProcessed = func() bool {\n\t\t\t\t// Recover from any panic in order to try to process all remaining events.\n\t\t\t\t// Note, that in case of a panic, the return value will be false and\n\t\t\t\t// the loop execution will continue.\n\t\t\t\tdefer runtime.HandleCrash()\n\n\t\t\t\tevents := b.collectEvents(timer, wait.NeverStop)\n\t\t\t\tb.processEvents(events)\n\t\t\t\treturn len(events) == 0\n\t\t\t}()\n\t\t}\n\t}()\n\treturn b.delegateBackend.Run(stopCh)\n}","line":{"from":106,"to":132}} {"id":100019180,"name":"Shutdown","signature":"func (b *bufferedBackend) Shutdown()","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/buffered/buffered.go","code":"// Shutdown blocks until stopCh passed to the Run method is closed and all\n// events added prior to that moment are batched and sent to the delegate backend.\nfunc (b *bufferedBackend) Shutdown() {\n\t// Wait until the routine spawned in Run method exits.\n\t\u003c-b.shutdownCh\n\n\t// Wait until all sending routines exit.\n\t//\n\t// - When b.shutdownCh is closed, we know that the goroutine in Run has terminated.\n\t// - This means that processIncomingEvents has terminated.\n\t// - Which means that b.buffer is closed and cannot accept any new events anymore.\n\t// - Because processEvents is called synchronously from the Run goroutine, the waitgroup has its final value.\n\t// Hence wg.Wait will not miss any more outgoing batches.\n\tb.wg.Wait()\n\n\tb.delegateBackend.Shutdown()\n}","line":{"from":134,"to":150}} {"id":100019181,"name":"processIncomingEvents","signature":"func (b *bufferedBackend) processIncomingEvents(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/buffered/buffered.go","code":"// processIncomingEvents runs a loop that collects events from the buffer. When\n// b.stopCh is closed, processIncomingEvents stops and closes the buffer.\nfunc (b *bufferedBackend) processIncomingEvents(stopCh \u003c-chan struct{}) {\n\tdefer close(b.buffer)\n\n\tvar (\n\t\tmaxWaitChan \u003c-chan time.Time\n\t\tmaxWaitTimer *time.Timer\n\t)\n\t// Only use max wait batching if batching is enabled.\n\tif b.maxBatchSize \u003e 1 {\n\t\tmaxWaitTimer = time.NewTimer(b.maxBatchWait)\n\t\tmaxWaitChan = maxWaitTimer.C\n\t\tdefer maxWaitTimer.Stop()\n\t}\n\n\tfor {\n\t\tfunc() {\n\t\t\t// Recover from any panics caused by this function so a panic in the\n\t\t\t// goroutine can't bring down the main routine.\n\t\t\tdefer runtime.HandleCrash()\n\n\t\t\tif b.maxBatchSize \u003e 1 {\n\t\t\t\tmaxWaitTimer.Reset(b.maxBatchWait)\n\t\t\t}\n\t\t\tb.processEvents(b.collectEvents(maxWaitChan, stopCh))\n\t\t}()\n\n\t\tselect {\n\t\tcase \u003c-stopCh:\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\t}\n}","line":{"from":152,"to":186}} {"id":100019182,"name":"collectEvents","signature":"func (b *bufferedBackend) collectEvents(timer \u003c-chan time.Time, stopCh \u003c-chan struct{}) []*auditinternal.Event","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/buffered/buffered.go","code":"// collectEvents attempts to collect some number of events in a batch.\n//\n// The following things can cause collectEvents to stop and return the list\n// of events:\n//\n// - Maximum number of events for a batch.\n// - Timer has passed.\n// - Buffer channel is closed and empty.\n// - stopCh is closed.\nfunc (b *bufferedBackend) collectEvents(timer \u003c-chan time.Time, stopCh \u003c-chan struct{}) []*auditinternal.Event {\n\tvar events []*auditinternal.Event\n\nL:\n\tfor i := 0; i \u003c b.maxBatchSize; i++ {\n\t\tselect {\n\t\tcase ev, ok := \u003c-b.buffer:\n\t\t\t// Buffer channel was closed and no new events will follow.\n\t\t\tif !ok {\n\t\t\t\tbreak L\n\t\t\t}\n\t\t\tevents = append(events, ev)\n\t\tcase \u003c-timer:\n\t\t\t// Timer has expired. Send currently accumulated batch.\n\t\t\tbreak L\n\t\tcase \u003c-stopCh:\n\t\t\t// Backend has been stopped. Send currently accumulated batch.\n\t\t\tbreak L\n\t\t}\n\t}\n\n\treturn events\n}","line":{"from":188,"to":219}} {"id":100019183,"name":"processEvents","signature":"func (b *bufferedBackend) processEvents(events []*auditinternal.Event)","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/buffered/buffered.go","code":"// processEvents process the batch events in a goroutine using delegateBackend's ProcessEvents.\nfunc (b *bufferedBackend) processEvents(events []*auditinternal.Event) {\n\tif len(events) == 0 {\n\t\treturn\n\t}\n\n\t// TODO(audit): Should control the number of active goroutines\n\t// if one goroutine takes 5 seconds to finish, the number of goroutines can be 5 * defaultBatchThrottleQPS\n\tif b.throttle != nil {\n\t\tb.throttle.Accept()\n\t}\n\n\tif b.asyncDelegate {\n\t\tb.wg.Add(1)\n\t\tgo func() {\n\t\t\tdefer b.wg.Done()\n\t\t\tdefer runtime.HandleCrash()\n\n\t\t\t// Execute the real processing in a goroutine to keep it from blocking.\n\t\t\t// This lets the batching routine continue draining the queue immediately.\n\t\t\tb.delegateBackend.ProcessEvents(events...)\n\t\t}()\n\t} else {\n\t\tfunc() {\n\t\t\tdefer runtime.HandleCrash()\n\n\t\t\t// Execute the real processing in a goroutine to keep it from blocking.\n\t\t\t// This lets the batching routine continue draining the queue immediately.\n\t\t\tb.delegateBackend.ProcessEvents(events...)\n\t\t}()\n\t}\n}","line":{"from":221,"to":252}} {"id":100019184,"name":"ProcessEvents","signature":"func (b *bufferedBackend) ProcessEvents(ev ...*auditinternal.Event) bool","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/buffered/buffered.go","code":"func (b *bufferedBackend) ProcessEvents(ev ...*auditinternal.Event) bool {\n\t// The following mechanism is in place to support the situation when audit\n\t// events are still coming after the backend was stopped.\n\tvar sendErr error\n\tvar evIndex int\n\n\t// If the delegateBackend was shutdown and the buffer channel was closed, an\n\t// attempt to add an event to it will result in panic that we should\n\t// recover from.\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tsendErr = fmt.Errorf(\"audit backend shut down\")\n\t\t}\n\t\tif sendErr != nil {\n\t\t\taudit.HandlePluginError(PluginName, sendErr, ev[evIndex:]...)\n\t\t}\n\t}()\n\n\tfor i, e := range ev {\n\t\tevIndex = i\n\t\t// Per the audit.Backend interface these events are reused after being\n\t\t// sent to the Sink. Deep copy and send the copy to the queue.\n\t\tevent := e.DeepCopy()\n\n\t\tselect {\n\t\tcase b.buffer \u003c- event:\n\t\tdefault:\n\t\t\tsendErr = fmt.Errorf(\"audit buffer queue blocked\")\n\t\t\treturn true\n\t\t}\n\t}\n\treturn true\n}","line":{"from":254,"to":286}} {"id":100019185,"name":"String","signature":"func (b *bufferedBackend) String() string","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/buffered/buffered.go","code":"func (b *bufferedBackend) String() string {\n\treturn fmt.Sprintf(\"%s\u003c%s\u003e\", PluginName, b.delegateBackend)\n}","line":{"from":288,"to":290}} {"id":100019186,"name":"NewBackend","signature":"func NewBackend(out io.Writer, format string, groupVersion schema.GroupVersion) audit.Backend","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/log/backend.go","code":"func NewBackend(out io.Writer, format string, groupVersion schema.GroupVersion) audit.Backend {\n\treturn \u0026backend{\n\t\tout: out,\n\t\tformat: format,\n\t\tencoder: audit.Codecs.LegacyCodec(groupVersion),\n\t}\n}","line":{"from":54,"to":60}} {"id":100019187,"name":"ProcessEvents","signature":"func (b *backend) ProcessEvents(events ...*auditinternal.Event) bool","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/log/backend.go","code":"func (b *backend) ProcessEvents(events ...*auditinternal.Event) bool {\n\tsuccess := true\n\tfor _, ev := range events {\n\t\tsuccess = b.logEvent(ev) \u0026\u0026 success\n\t}\n\treturn success\n}","line":{"from":62,"to":68}} {"id":100019188,"name":"logEvent","signature":"func (b *backend) logEvent(ev *auditinternal.Event) bool","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/log/backend.go","code":"func (b *backend) logEvent(ev *auditinternal.Event) bool {\n\tline := \"\"\n\tswitch b.format {\n\tcase FormatLegacy:\n\t\tline = audit.EventString(ev) + \"\\n\"\n\tcase FormatJson:\n\t\tbs, err := runtime.Encode(b.encoder, ev)\n\t\tif err != nil {\n\t\t\taudit.HandlePluginError(PluginName, err, ev)\n\t\t\treturn false\n\t\t}\n\t\tline = string(bs[:])\n\tdefault:\n\t\taudit.HandlePluginError(PluginName, fmt.Errorf(\"log format %q is not in list of known formats (%s)\",\n\t\t\tb.format, strings.Join(AllowedFormats, \",\")), ev)\n\t\treturn false\n\t}\n\tif _, err := fmt.Fprint(b.out, line); err != nil {\n\t\taudit.HandlePluginError(PluginName, err, ev)\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":70,"to":92}} {"id":100019189,"name":"Run","signature":"func (b *backend) Run(stopCh \u003c-chan struct{}) error","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/log/backend.go","code":"func (b *backend) Run(stopCh \u003c-chan struct{}) error {\n\treturn nil\n}","line":{"from":94,"to":96}} {"id":100019190,"name":"Shutdown","signature":"func (b *backend) Shutdown()","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/log/backend.go","code":"func (b *backend) Shutdown() {\n\t// Nothing to do here.\n}","line":{"from":98,"to":100}} {"id":100019191,"name":"String","signature":"func (b *backend) String() string","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/log/backend.go","code":"func (b *backend) String() string {\n\treturn PluginName\n}","line":{"from":102,"to":104}} {"id":100019192,"name":"NewBackend","signature":"func NewBackend(delegateBackend audit.Backend, config Config, groupVersion schema.GroupVersion) audit.Backend","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/truncate/truncate.go","code":"// NewBackend returns a new truncating backend, using configuration passed in the parameters.\n// Truncate backend automatically runs and shut downs the delegate backend.\nfunc NewBackend(delegateBackend audit.Backend, config Config, groupVersion schema.GroupVersion) audit.Backend {\n\treturn \u0026backend{\n\t\tdelegateBackend: delegateBackend,\n\t\tc: config,\n\t\te: audit.Codecs.LegacyCodec(groupVersion),\n\t}\n}","line":{"from":64,"to":72}} {"id":100019193,"name":"ProcessEvents","signature":"func (b *backend) ProcessEvents(events ...*auditinternal.Event) bool","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/truncate/truncate.go","code":"func (b *backend) ProcessEvents(events ...*auditinternal.Event) bool {\n\tvar errors []error\n\tvar impacted []*auditinternal.Event\n\tvar batch []*auditinternal.Event\n\tvar batchSize int64\n\tsuccess := true\n\tfor _, event := range events {\n\t\tsize, err := b.calcSize(event)\n\t\t// If event was correctly serialized, but the size is more than allowed\n\t\t// and it makes sense to do trimming, i.e. there's a request and/or\n\t\t// response present, try to strip away request and response.\n\t\tif err == nil \u0026\u0026 size \u003e b.c.MaxEventSize \u0026\u0026 event.Level.GreaterOrEqual(auditinternal.LevelRequest) {\n\t\t\tevent = truncate(event)\n\t\t\tsize, err = b.calcSize(event)\n\t\t}\n\t\tif err != nil {\n\t\t\terrors = append(errors, err)\n\t\t\timpacted = append(impacted, event)\n\t\t\tcontinue\n\t\t}\n\t\tif size \u003e b.c.MaxEventSize {\n\t\t\terrors = append(errors, fmt.Errorf(\"event is too large even after truncating\"))\n\t\t\timpacted = append(impacted, event)\n\t\t\tcontinue\n\t\t}\n\n\t\tif len(batch) \u003e 0 \u0026\u0026 batchSize+size \u003e b.c.MaxBatchSize {\n\t\t\tsuccess = b.delegateBackend.ProcessEvents(batch...) \u0026\u0026 success\n\t\t\tbatch = []*auditinternal.Event{}\n\t\t\tbatchSize = 0\n\t\t}\n\n\t\tbatchSize += size\n\t\tbatch = append(batch, event)\n\t}\n\n\tif len(batch) \u003e 0 {\n\t\tsuccess = b.delegateBackend.ProcessEvents(batch...) \u0026\u0026 success\n\t}\n\n\tif len(impacted) \u003e 0 {\n\t\taudit.HandlePluginError(PluginName, utilerrors.NewAggregate(errors), impacted...)\n\t}\n\treturn success\n}","line":{"from":74,"to":118}} {"id":100019194,"name":"truncate","signature":"func truncate(e *auditinternal.Event) *auditinternal.Event","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/truncate/truncate.go","code":"// truncate removed request and response objects from the audit events,\n// to try and keep at least metadata.\nfunc truncate(e *auditinternal.Event) *auditinternal.Event {\n\t// Make a shallow copy to avoid copying response/request objects.\n\tnewEvent := \u0026auditinternal.Event{}\n\t*newEvent = *e\n\n\tnewEvent.RequestObject = nil\n\tnewEvent.ResponseObject = nil\n\n\tif newEvent.Annotations == nil {\n\t\tnewEvent.Annotations = make(map[string]string)\n\t}\n\tnewEvent.Annotations[annotationKey] = annotationValue\n\n\treturn newEvent\n}","line":{"from":120,"to":136}} {"id":100019195,"name":"Run","signature":"func (b *backend) Run(stopCh \u003c-chan struct{}) error","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/truncate/truncate.go","code":"func (b *backend) Run(stopCh \u003c-chan struct{}) error {\n\treturn b.delegateBackend.Run(stopCh)\n}","line":{"from":138,"to":140}} {"id":100019196,"name":"Shutdown","signature":"func (b *backend) Shutdown()","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/truncate/truncate.go","code":"func (b *backend) Shutdown() {\n\tb.delegateBackend.Shutdown()\n}","line":{"from":142,"to":144}} {"id":100019197,"name":"calcSize","signature":"func (b *backend) calcSize(e *auditinternal.Event) (int64, error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/truncate/truncate.go","code":"func (b *backend) calcSize(e *auditinternal.Event) (int64, error) {\n\ts := \u0026sizer{}\n\tif err := b.e.Encode(e, s); err != nil {\n\t\treturn 0, err\n\t}\n\treturn s.Size, nil\n}","line":{"from":146,"to":152}} {"id":100019198,"name":"String","signature":"func (b *backend) String() string","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/truncate/truncate.go","code":"func (b *backend) String() string {\n\treturn fmt.Sprintf(\"%s\u003c%s\u003e\", PluginName, b.delegateBackend)\n}","line":{"from":154,"to":156}} {"id":100019199,"name":"Write","signature":"func (s *sizer) Write(p []byte) (n int, err error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/truncate/truncate.go","code":"func (s *sizer) Write(p []byte) (n int, err error) {\n\ts.Size += int64(len(p))\n\treturn len(p), nil\n}","line":{"from":162,"to":165}} {"id":100019200,"name":"init","signature":"func init()","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/webhook/webhook.go","code":"func init() {\n\tinstall.Install(audit.Scheme)\n}","line":{"from":47,"to":49}} {"id":100019201,"name":"retryOnError","signature":"func retryOnError(err error) bool","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/webhook/webhook.go","code":"// retryOnError enforces the webhook client to retry requests\n// on error regardless of its nature.\n// The default implementation considers a very limited set of\n// 'retriable' errors, assuming correct use of HTTP codes by\n// external webhooks.\n// That may easily lead to dropped audit events. In fact, there is\n// hardly any error that could be a justified reason NOT to retry\n// sending audit events if there is even a slight chance that the\n// receiving service gets back to normal at some point.\nfunc retryOnError(err error) bool {\n\tif err != nil {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":51,"to":65}} {"id":100019202,"name":"loadWebhook","signature":"func loadWebhook(configFile string, groupVersion schema.GroupVersion, retryBackoff wait.Backoff, customDial utilnet.DialFunc) (*webhook.GenericWebhook, error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/webhook/webhook.go","code":"func loadWebhook(configFile string, groupVersion schema.GroupVersion, retryBackoff wait.Backoff, customDial utilnet.DialFunc) (*webhook.GenericWebhook, error) {\n\tclientConfig, err := webhook.LoadKubeconfig(configFile, customDial)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tw, err := webhook.NewGenericWebhook(audit.Scheme, audit.Codecs, clientConfig,\n\t\t[]schema.GroupVersion{groupVersion}, retryBackoff)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tw.ShouldRetry = retryOnError\n\treturn w, nil\n}","line":{"from":67,"to":80}} {"id":100019203,"name":"NewDynamicBackend","signature":"func NewDynamicBackend(rc *rest.RESTClient, retryBackoff wait.Backoff) audit.Backend","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/webhook/webhook.go","code":"// NewDynamicBackend returns an audit backend configured from a REST client that\n// sends events over HTTP to an external service.\nfunc NewDynamicBackend(rc *rest.RESTClient, retryBackoff wait.Backoff) audit.Backend {\n\treturn \u0026backend{\n\t\tw: \u0026webhook.GenericWebhook{\n\t\t\tRestClient: rc,\n\t\t\tRetryBackoff: retryBackoff,\n\t\t\tShouldRetry: retryOnError,\n\t\t},\n\t\tname: fmt.Sprintf(\"dynamic_%s\", PluginName),\n\t}\n}","line":{"from":87,"to":98}} {"id":100019204,"name":"NewBackend","signature":"func NewBackend(kubeConfigFile string, groupVersion schema.GroupVersion, retryBackoff wait.Backoff, customDial utilnet.DialFunc) (audit.Backend, error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/webhook/webhook.go","code":"// NewBackend returns an audit backend that sends events over HTTP to an external service.\nfunc NewBackend(kubeConfigFile string, groupVersion schema.GroupVersion, retryBackoff wait.Backoff, customDial utilnet.DialFunc) (audit.Backend, error) {\n\tw, err := loadWebhook(kubeConfigFile, groupVersion, retryBackoff, customDial)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026backend{w: w, name: PluginName}, nil\n}","line":{"from":100,"to":107}} {"id":100019205,"name":"Run","signature":"func (b *backend) Run(stopCh \u003c-chan struct{}) error","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/webhook/webhook.go","code":"func (b *backend) Run(stopCh \u003c-chan struct{}) error {\n\treturn nil\n}","line":{"from":109,"to":111}} {"id":100019206,"name":"Shutdown","signature":"func (b *backend) Shutdown()","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/webhook/webhook.go","code":"func (b *backend) Shutdown() {\n\t// nothing to do here\n}","line":{"from":113,"to":115}} {"id":100019207,"name":"ProcessEvents","signature":"func (b *backend) ProcessEvents(ev ...*auditinternal.Event) bool","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/webhook/webhook.go","code":"func (b *backend) ProcessEvents(ev ...*auditinternal.Event) bool {\n\tif err := b.processEvents(ev...); err != nil {\n\t\taudit.HandlePluginError(b.String(), err, ev...)\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":117,"to":123}} {"id":100019208,"name":"processEvents","signature":"func (b *backend) processEvents(ev ...*auditinternal.Event) error","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/webhook/webhook.go","code":"func (b *backend) processEvents(ev ...*auditinternal.Event) error {\n\tvar list auditinternal.EventList\n\tfor _, e := range ev {\n\t\tlist.Items = append(list.Items, *e)\n\t}\n\treturn b.w.WithExponentialBackoff(context.Background(), func() rest.Result {\n\t\tctx, span := tracing.Start(context.Background(), \"Call Audit Events webhook\",\n\t\t\tattribute.String(\"name\", b.name),\n\t\t\tattribute.Int(\"event-count\", len(list.Items)),\n\t\t)\n\t\t// Only log audit webhook traces that exceed a 25ms per object limit plus a 50ms\n\t\t// request overhead allowance. The high per object limit used here is primarily to\n\t\t// allow enough time for the serialization/deserialization of audit events, which\n\t\t// contain nested request and response objects plus additional event fields.\n\t\tdefer span.End(time.Duration(50+25*len(list.Items)) * time.Millisecond)\n\t\treturn b.w.RestClient.Post().Body(\u0026list).Do(ctx)\n\t}).Error()\n}","line":{"from":125,"to":142}} {"id":100019209,"name":"String","signature":"func (b *backend) String() string","file":"staging/src/k8s.io/apiserver/plugin/pkg/audit/webhook/webhook.go","code":"func (b *backend) String() string {\n\treturn b.name\n}","line":{"from":144,"to":146}} {"id":100019210,"name":"initVerifier","signature":"func initVerifier(ctx context.Context, config *oidc.Config, iss string) (*oidc.IDTokenVerifier, error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/oidc/oidc.go","code":"// initVerifier creates a new ID token verifier for the given configuration and issuer URL. On success, calls setVerifier with the\n// resulting verifier.\nfunc initVerifier(ctx context.Context, config *oidc.Config, iss string) (*oidc.IDTokenVerifier, error) {\n\tprovider, err := oidc.NewProvider(ctx, iss)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"init verifier failed: %v\", err)\n\t}\n\treturn provider.Verifier(config), nil\n}","line":{"from":130,"to":138}} {"id":100019211,"name":"newAsyncIDTokenVerifier","signature":"func newAsyncIDTokenVerifier(ctx context.Context, c *oidc.Config, iss string) *asyncIDTokenVerifier","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/oidc/oidc.go","code":"// newAsyncIDTokenVerifier creates a new asynchronous token verifier. The\n// verifier is available immediately, but may remain uninitialized for some time\n// after creation.\nfunc newAsyncIDTokenVerifier(ctx context.Context, c *oidc.Config, iss string) *asyncIDTokenVerifier {\n\tt := \u0026asyncIDTokenVerifier{}\n\n\tsync := make(chan struct{})\n\t// Polls indefinitely in an attempt to initialize the distributed claims\n\t// verifier, or until context canceled.\n\tinitFn := func() (done bool, err error) {\n\t\tklog.V(4).Infof(\"oidc authenticator: attempting init: iss=%v\", iss)\n\t\tv, err := initVerifier(ctx, c, iss)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"oidc authenticator: async token verifier for issuer: %q: %v\", iss, err)\n\t\t\treturn false, nil\n\t\t}\n\t\tt.m.Lock()\n\t\tdefer t.m.Unlock()\n\t\tt.v = v\n\t\tclose(sync)\n\t\treturn true, nil\n\t}\n\n\tgo func() {\n\t\tif done, _ := initFn(); !done {\n\t\t\tgo wait.PollUntil(time.Second*10, initFn, ctx.Done())\n\t\t}\n\t}()\n\n\tif synchronizeTokenIDVerifierForTest {\n\t\t\u003c-sync\n\t}\n\n\treturn t\n}","line":{"from":151,"to":185}} {"id":100019212,"name":"verifier","signature":"func (a *asyncIDTokenVerifier) verifier() *oidc.IDTokenVerifier","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/oidc/oidc.go","code":"// verifier returns the underlying ID token verifier, or nil if one is not yet initialized.\nfunc (a *asyncIDTokenVerifier) verifier() *oidc.IDTokenVerifier {\n\ta.m.Lock()\n\tdefer a.m.Unlock()\n\treturn a.v\n}","line":{"from":187,"to":192}} {"id":100019213,"name":"setVerifier","signature":"func (a *Authenticator) setVerifier(v *oidc.IDTokenVerifier)","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/oidc/oidc.go","code":"func (a *Authenticator) setVerifier(v *oidc.IDTokenVerifier) {\n\ta.verifier.Store(v)\n}","line":{"from":213,"to":215}} {"id":100019214,"name":"idTokenVerifier","signature":"func (a *Authenticator) idTokenVerifier() (*oidc.IDTokenVerifier, bool)","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/oidc/oidc.go","code":"func (a *Authenticator) idTokenVerifier() (*oidc.IDTokenVerifier, bool) {\n\tif v := a.verifier.Load(); v != nil {\n\t\treturn v.(*oidc.IDTokenVerifier), true\n\t}\n\treturn nil, false\n}","line":{"from":217,"to":222}} {"id":100019215,"name":"Close","signature":"func (a *Authenticator) Close()","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/oidc/oidc.go","code":"func (a *Authenticator) Close() {\n\ta.cancel()\n}","line":{"from":224,"to":226}} {"id":100019216,"name":"New","signature":"func New(opts Options) (*Authenticator, error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/oidc/oidc.go","code":"func New(opts Options) (*Authenticator, error) {\n\turl, err := url.Parse(opts.IssuerURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif url.Scheme != \"https\" {\n\t\treturn nil, fmt.Errorf(\"'oidc-issuer-url' (%q) has invalid scheme (%q), require 'https'\", opts.IssuerURL, url.Scheme)\n\t}\n\n\tif opts.UsernameClaim == \"\" {\n\t\treturn nil, errors.New(\"no username claim provided\")\n\t}\n\n\tsupportedSigningAlgs := opts.SupportedSigningAlgs\n\tif len(supportedSigningAlgs) == 0 {\n\t\t// RS256 is the default recommended by OpenID Connect and an 'alg' value\n\t\t// providers are required to implement.\n\t\tsupportedSigningAlgs = []string{oidc.RS256}\n\t}\n\tfor _, alg := range supportedSigningAlgs {\n\t\tif !allowedSigningAlgs[alg] {\n\t\t\treturn nil, fmt.Errorf(\"oidc: unsupported signing alg: %q\", alg)\n\t\t}\n\t}\n\n\tif opts.Client != nil \u0026\u0026 opts.CAContentProvider != nil {\n\t\treturn nil, fmt.Errorf(\"oidc: Client and CAContentProvider are mutually exclusive\")\n\t}\n\n\tclient := opts.Client\n\n\tif client == nil {\n\t\tvar roots *x509.CertPool\n\t\tif opts.CAContentProvider != nil {\n\t\t\t// TODO(enj): make this reload CA data dynamically\n\t\t\troots, err = certutil.NewPoolFromBytes(opts.CAContentProvider.CurrentCABundleContent())\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"Failed to read the CA contents: %v\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tklog.Info(\"OIDC: No x509 certificates provided, will use host's root CA set\")\n\t\t}\n\n\t\t// Copied from http.DefaultTransport.\n\t\ttr := net.SetTransportDefaults(\u0026http.Transport{\n\t\t\t// According to golang's doc, if RootCAs is nil,\n\t\t\t// TLS uses the host's root CA set.\n\t\t\tTLSClientConfig: \u0026tls.Config{RootCAs: roots},\n\t\t})\n\n\t\tclient = \u0026http.Client{Transport: tr, Timeout: 30 * time.Second}\n\t}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tctx = oidc.ClientContext(ctx, client)\n\n\tnow := opts.now\n\tif now == nil {\n\t\tnow = time.Now\n\t}\n\n\tverifierConfig := \u0026oidc.Config{\n\t\tClientID: opts.ClientID,\n\t\tSupportedSigningAlgs: supportedSigningAlgs,\n\t\tNow: now,\n\t}\n\n\tvar resolver *claimResolver\n\tif opts.GroupsClaim != \"\" {\n\t\tresolver = newClaimResolver(opts.GroupsClaim, client, verifierConfig)\n\t}\n\n\tauthenticator := \u0026Authenticator{\n\t\tissuerURL: opts.IssuerURL,\n\t\tusernameClaim: opts.UsernameClaim,\n\t\tusernamePrefix: opts.UsernamePrefix,\n\t\tgroupsClaim: opts.GroupsClaim,\n\t\tgroupsPrefix: opts.GroupsPrefix,\n\t\trequiredClaims: opts.RequiredClaims,\n\t\tcancel: cancel,\n\t\tresolver: resolver,\n\t}\n\n\tif opts.KeySet != nil {\n\t\t// We already have a key set, synchronously initialize the verifier.\n\t\tauthenticator.setVerifier(oidc.NewVerifier(opts.IssuerURL, opts.KeySet, verifierConfig))\n\t} else {\n\t\t// Asynchronously attempt to initialize the authenticator. This enables\n\t\t// self-hosted providers, providers that run on top of Kubernetes itself.\n\t\tgo wait.PollImmediateUntil(10*time.Second, func() (done bool, err error) {\n\t\t\tprovider, err := oidc.NewProvider(ctx, opts.IssuerURL)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"oidc authenticator: initializing plugin: %v\", err)\n\t\t\t\treturn false, nil\n\t\t\t}\n\n\t\t\tverifier := provider.Verifier(verifierConfig)\n\t\t\tauthenticator.setVerifier(verifier)\n\t\t\treturn true, nil\n\t\t}, ctx.Done())\n\t}\n\n\treturn authenticator, nil\n}","line":{"from":242,"to":346}} {"id":100019217,"name":"untrustedIssuer","signature":"func untrustedIssuer(token string) (string, error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/oidc/oidc.go","code":"// untrustedIssuer extracts an untrusted \"iss\" claim from the given JWT token,\n// or returns an error if the token can not be parsed. Since the JWT is not\n// verified, the returned issuer should not be trusted.\nfunc untrustedIssuer(token string) (string, error) {\n\tparts := strings.Split(token, \".\")\n\tif len(parts) != 3 {\n\t\treturn \"\", fmt.Errorf(\"malformed token\")\n\t}\n\tpayload, err := base64.RawURLEncoding.DecodeString(parts[1])\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error decoding token: %v\", err)\n\t}\n\tclaims := struct {\n\t\t// WARNING: this JWT is not verified. Do not trust these claims.\n\t\tIssuer string `json:\"iss\"`\n\t}{}\n\tif err := json.Unmarshal(payload, \u0026claims); err != nil {\n\t\treturn \"\", fmt.Errorf(\"while unmarshaling token: %v\", err)\n\t}\n\t// Coalesce the legacy GoogleIss with the new one.\n\t//\n\t// http://openid.net/specs/openid-connect-core-1_0.html#GoogleIss\n\tif claims.Issuer == \"accounts.google.com\" {\n\t\treturn \"https://accounts.google.com\", nil\n\t}\n\treturn claims.Issuer, nil\n}","line":{"from":348,"to":374}} {"id":100019218,"name":"hasCorrectIssuer","signature":"func hasCorrectIssuer(iss, tokenData string) bool","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/oidc/oidc.go","code":"func hasCorrectIssuer(iss, tokenData string) bool {\n\tuiss, err := untrustedIssuer(tokenData)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif uiss != iss {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":376,"to":385}} {"id":100019219,"name":"newClaimResolver","signature":"func newClaimResolver(claim string, client *http.Client, config *oidc.Config) *claimResolver","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/oidc/oidc.go","code":"// newClaimResolver creates a new resolver for distributed claims.\nfunc newClaimResolver(claim string, client *http.Client, config *oidc.Config) *claimResolver {\n\treturn \u0026claimResolver{claim: claim, client: client, config: config, verifierPerIssuer: map[string]*asyncIDTokenVerifier{}}\n}","line":{"from":423,"to":426}} {"id":100019220,"name":"Verifier","signature":"func (r *claimResolver) Verifier(iss string) (*oidc.IDTokenVerifier, error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/oidc/oidc.go","code":"// Verifier returns either the verifier for the specified issuer, or error.\nfunc (r *claimResolver) Verifier(iss string) (*oidc.IDTokenVerifier, error) {\n\tr.m.Lock()\n\tav := r.verifierPerIssuer[iss]\n\tif av == nil {\n\t\t// This lazy init should normally be very quick.\n\t\t// TODO: Make this context cancelable.\n\t\tctx := oidc.ClientContext(context.Background(), r.client)\n\t\tav = newAsyncIDTokenVerifier(ctx, r.config, iss)\n\t\tr.verifierPerIssuer[iss] = av\n\t}\n\tr.m.Unlock()\n\n\tv := av.verifier()\n\tif v == nil {\n\t\treturn nil, fmt.Errorf(\"verifier not initialized for issuer: %q\", iss)\n\t}\n\treturn v, nil\n}","line":{"from":428,"to":446}} {"id":100019221,"name":"expand","signature":"func (r *claimResolver) expand(c claims) error","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/oidc/oidc.go","code":"// expand extracts the distributed claims from claim names and claim sources.\n// The extracted claim value is pulled up into the supplied claims.\n//\n// Distributed claims are of the form as seen below, and are defined in the\n// OIDC Connect Core 1.0, section 5.6.2.\n// See: https://openid.net/specs/openid-connect-core-1_0.html#AggregatedDistributedClaims\n//\n//\t{\n//\t ... (other normal claims)...\n//\t \"_claim_names\": {\n//\t \"groups\": \"src1\"\n//\t },\n//\t \"_claim_sources\": {\n//\t \"src1\": {\n//\t \"endpoint\": \"https://www.example.com\",\n//\t \"access_token\": \"f005ba11\"\n//\t },\n//\t },\n//\t}\nfunc (r *claimResolver) expand(c claims) error {\n\tconst (\n\t\t// The claim containing a map of endpoint references per claim.\n\t\t// OIDC Connect Core 1.0, section 5.6.2.\n\t\tclaimNamesKey = \"_claim_names\"\n\t\t// The claim containing endpoint specifications.\n\t\t// OIDC Connect Core 1.0, section 5.6.2.\n\t\tclaimSourcesKey = \"_claim_sources\"\n\t)\n\n\t_, ok := c[r.claim]\n\tif ok {\n\t\t// There already is a normal claim, skip resolving.\n\t\treturn nil\n\t}\n\tnames, ok := c[claimNamesKey]\n\tif !ok {\n\t\t// No _claim_names, no keys to look up.\n\t\treturn nil\n\t}\n\n\tclaimToSource := map[string]string{}\n\tif err := json.Unmarshal([]byte(names), \u0026claimToSource); err != nil {\n\t\treturn fmt.Errorf(\"oidc: error parsing distributed claim names: %v\", err)\n\t}\n\n\trawSources, ok := c[claimSourcesKey]\n\tif !ok {\n\t\t// Having _claim_names claim, but no _claim_sources is not an expected\n\t\t// state.\n\t\treturn fmt.Errorf(\"oidc: no claim sources\")\n\t}\n\n\tvar sources map[string]endpoint\n\tif err := json.Unmarshal([]byte(rawSources), \u0026sources); err != nil {\n\t\t// The claims sources claim is malformed, this is not an expected state.\n\t\treturn fmt.Errorf(\"oidc: could not parse claim sources: %v\", err)\n\t}\n\n\tsrc, ok := claimToSource[r.claim]\n\tif !ok {\n\t\t// No distributed claim present.\n\t\treturn nil\n\t}\n\tep, ok := sources[src]\n\tif !ok {\n\t\treturn fmt.Errorf(\"id token _claim_names contained a source %s missing in _claims_sources\", src)\n\t}\n\tif ep.URL == \"\" {\n\t\t// This is maybe an aggregated claim (ep.JWT != \"\").\n\t\treturn nil\n\t}\n\treturn r.resolve(ep, c)\n}","line":{"from":448,"to":520}} {"id":100019222,"name":"resolve","signature":"func (r *claimResolver) resolve(endpoint endpoint, allClaims claims) error","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/oidc/oidc.go","code":"// resolve requests distributed claims from all endpoints passed in,\n// and inserts the lookup results into allClaims.\nfunc (r *claimResolver) resolve(endpoint endpoint, allClaims claims) error {\n\t// TODO: cache resolved claims.\n\tjwt, err := getClaimJWT(r.client, endpoint.URL, endpoint.AccessToken)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"while getting distributed claim %q: %v\", r.claim, err)\n\t}\n\tuntrustedIss, err := untrustedIssuer(jwt)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"getting untrusted issuer from endpoint %v failed for claim %q: %v\", endpoint.URL, r.claim, err)\n\t}\n\tv, err := r.Verifier(untrustedIss)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"verifying untrusted issuer %v failed: %v\", untrustedIss, err)\n\t}\n\tt, err := v.Verify(context.Background(), jwt)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"verify distributed claim token: %v\", err)\n\t}\n\tvar distClaims claims\n\tif err := t.Claims(\u0026distClaims); err != nil {\n\t\treturn fmt.Errorf(\"could not parse distributed claims for claim %v: %v\", r.claim, err)\n\t}\n\tvalue, ok := distClaims[r.claim]\n\tif !ok {\n\t\treturn fmt.Errorf(\"jwt returned by distributed claim endpoint %q did not contain claim: %v\", endpoint.URL, r.claim)\n\t}\n\tallClaims[r.claim] = value\n\treturn nil\n}","line":{"from":522,"to":552}} {"id":100019223,"name":"AuthenticateToken","signature":"func (a *Authenticator) AuthenticateToken(ctx context.Context, token string) (*authenticator.Response, bool, error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/oidc/oidc.go","code":"func (a *Authenticator) AuthenticateToken(ctx context.Context, token string) (*authenticator.Response, bool, error) {\n\tif !hasCorrectIssuer(a.issuerURL, token) {\n\t\treturn nil, false, nil\n\t}\n\n\tverifier, ok := a.idTokenVerifier()\n\tif !ok {\n\t\treturn nil, false, fmt.Errorf(\"oidc: authenticator not initialized\")\n\t}\n\n\tidToken, err := verifier.Verify(ctx, token)\n\tif err != nil {\n\t\treturn nil, false, fmt.Errorf(\"oidc: verify token: %v\", err)\n\t}\n\n\tvar c claims\n\tif err := idToken.Claims(\u0026c); err != nil {\n\t\treturn nil, false, fmt.Errorf(\"oidc: parse claims: %v\", err)\n\t}\n\tif a.resolver != nil {\n\t\tif err := a.resolver.expand(c); err != nil {\n\t\t\treturn nil, false, fmt.Errorf(\"oidc: could not expand distributed claims: %v\", err)\n\t\t}\n\t}\n\n\tvar username string\n\tif err := c.unmarshalClaim(a.usernameClaim, \u0026username); err != nil {\n\t\treturn nil, false, fmt.Errorf(\"oidc: parse username claims %q: %v\", a.usernameClaim, err)\n\t}\n\n\tif a.usernameClaim == \"email\" {\n\t\t// If the email_verified claim is present, ensure the email is valid.\n\t\t// https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims\n\t\tif hasEmailVerified := c.hasClaim(\"email_verified\"); hasEmailVerified {\n\t\t\tvar emailVerified bool\n\t\t\tif err := c.unmarshalClaim(\"email_verified\", \u0026emailVerified); err != nil {\n\t\t\t\treturn nil, false, fmt.Errorf(\"oidc: parse 'email_verified' claim: %v\", err)\n\t\t\t}\n\n\t\t\t// If the email_verified claim is present we have to verify it is set to `true`.\n\t\t\tif !emailVerified {\n\t\t\t\treturn nil, false, fmt.Errorf(\"oidc: email not verified\")\n\t\t\t}\n\t\t}\n\t}\n\n\tif a.usernamePrefix != \"\" {\n\t\tusername = a.usernamePrefix + username\n\t}\n\n\tinfo := \u0026user.DefaultInfo{Name: username}\n\tif a.groupsClaim != \"\" {\n\t\tif _, ok := c[a.groupsClaim]; ok {\n\t\t\t// Some admins want to use string claims like \"role\" as the group value.\n\t\t\t// Allow the group claim to be a single string instead of an array.\n\t\t\t//\n\t\t\t// See: https://github.com/kubernetes/kubernetes/issues/33290\n\t\t\tvar groups stringOrArray\n\t\t\tif err := c.unmarshalClaim(a.groupsClaim, \u0026groups); err != nil {\n\t\t\t\treturn nil, false, fmt.Errorf(\"oidc: parse groups claim %q: %v\", a.groupsClaim, err)\n\t\t\t}\n\t\t\tinfo.Groups = []string(groups)\n\t\t}\n\t}\n\n\tif a.groupsPrefix != \"\" {\n\t\tfor i, group := range info.Groups {\n\t\t\tinfo.Groups[i] = a.groupsPrefix + group\n\t\t}\n\t}\n\n\t// check to ensure all required claims are present in the ID token and have matching values.\n\tfor claim, value := range a.requiredClaims {\n\t\tif !c.hasClaim(claim) {\n\t\t\treturn nil, false, fmt.Errorf(\"oidc: required claim %s not present in ID token\", claim)\n\t\t}\n\n\t\t// NOTE: Only string values are supported as valid required claim values.\n\t\tvar claimValue string\n\t\tif err := c.unmarshalClaim(claim, \u0026claimValue); err != nil {\n\t\t\treturn nil, false, fmt.Errorf(\"oidc: parse claim %s: %v\", claim, err)\n\t\t}\n\t\tif claimValue != value {\n\t\t\treturn nil, false, fmt.Errorf(\"oidc: required claim %s value does not match. Got = %s, want = %s\", claim, claimValue, value)\n\t\t}\n\t}\n\n\treturn \u0026authenticator.Response{User: info}, true, nil\n}","line":{"from":554,"to":642}} {"id":100019224,"name":"getClaimJWT","signature":"func getClaimJWT(client *http.Client, url, accessToken string) (string, error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/oidc/oidc.go","code":"// getClaimJWT gets a distributed claim JWT from url, using the supplied access\n// token as bearer token. If the access token is \"\", the authorization header\n// will not be set.\n// TODO: Allow passing in JSON hints to the IDP.\nfunc getClaimJWT(client *http.Client, url, accessToken string) (string, error) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\t// TODO: Allow passing request body with configurable information.\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"while calling %v: %v\", url, err)\n\t}\n\tif accessToken != \"\" {\n\t\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"Bearer %v\", accessToken))\n\t}\n\treq = req.WithContext(ctx)\n\tresponse, err := client.Do(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer response.Body.Close()\n\t// Report non-OK status code as an error.\n\tif response.StatusCode \u003c http.StatusOK || response.StatusCode \u003e http.StatusIMUsed {\n\t\treturn \"\", fmt.Errorf(\"error while getting distributed claim JWT: %v\", response.Status)\n\t}\n\tresponseBytes, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"could not decode distributed claim response\")\n\t}\n\treturn string(responseBytes), nil\n}","line":{"from":644,"to":675}} {"id":100019225,"name":"UnmarshalJSON","signature":"func (s *stringOrArray) UnmarshalJSON(b []byte) error","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/oidc/oidc.go","code":"func (s *stringOrArray) UnmarshalJSON(b []byte) error {\n\tvar a []string\n\tif err := json.Unmarshal(b, \u0026a); err == nil {\n\t\t*s = a\n\t\treturn nil\n\t}\n\tvar str string\n\tif err := json.Unmarshal(b, \u0026str); err != nil {\n\t\treturn err\n\t}\n\t*s = []string{str}\n\treturn nil\n}","line":{"from":679,"to":691}} {"id":100019226,"name":"unmarshalClaim","signature":"func (c claims) unmarshalClaim(name string, v interface{}) error","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/oidc/oidc.go","code":"func (c claims) unmarshalClaim(name string, v interface{}) error {\n\tval, ok := c[name]\n\tif !ok {\n\t\treturn fmt.Errorf(\"claim not present\")\n\t}\n\treturn json.Unmarshal([]byte(val), v)\n}","line":{"from":695,"to":701}} {"id":100019227,"name":"hasClaim","signature":"func (c claims) hasClaim(name string) bool","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/oidc/oidc.go","code":"func (c claims) hasClaim(name string) bool {\n\tif _, ok := c[name]; !ok {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":703,"to":708}} {"id":100019228,"name":"RequestTotal","signature":"func (noopMetrics) RequestTotal(context.Context, string) {}","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/webhook/metrics.go","code":"func (noopMetrics) RequestTotal(context.Context, string) {}","line":{"from":34,"to":34}} {"id":100019229,"name":"RequestLatency","signature":"func (noopMetrics) RequestLatency(context.Context, string, float64) {}","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/webhook/metrics.go","code":"func (noopMetrics) RequestLatency(context.Context, string, float64) {}","line":{"from":35,"to":35}} {"id":100019230,"name":"DefaultRetryBackoff","signature":"func DefaultRetryBackoff() *wait.Backoff","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/webhook/webhook.go","code":"// DefaultRetryBackoff returns the default backoff parameters for webhook retry.\nfunc DefaultRetryBackoff() *wait.Backoff {\n\tbackoff := webhook.DefaultRetryBackoffWithInitialDelay(500 * time.Millisecond)\n\treturn \u0026backoff\n}","line":{"from":42,"to":46}} {"id":100019231,"name":"NewFromInterface","signature":"func NewFromInterface(tokenReview authenticationv1client.AuthenticationV1Interface, implicitAuds authenticator.Audiences, retryBackoff wait.Backoff, requestTimeout time.Duration, metrics AuthenticatorMetrics) (*WebhookTokenAuthenticator, error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/webhook/webhook.go","code":"// NewFromInterface creates a webhook authenticator using the given tokenReview\n// client. It is recommend to wrap this authenticator with the token cache\n// authenticator implemented in\n// k8s.io/apiserver/pkg/authentication/token/cache.\nfunc NewFromInterface(tokenReview authenticationv1client.AuthenticationV1Interface, implicitAuds authenticator.Audiences, retryBackoff wait.Backoff, requestTimeout time.Duration, metrics AuthenticatorMetrics) (*WebhookTokenAuthenticator, error) {\n\ttokenReviewClient := \u0026tokenReviewV1Client{tokenReview.RESTClient()}\n\treturn newWithBackoff(tokenReviewClient, retryBackoff, implicitAuds, requestTimeout, metrics)\n}","line":{"from":63,"to":70}} {"id":100019232,"name":"New","signature":"func New(config *rest.Config, version string, implicitAuds authenticator.Audiences, retryBackoff wait.Backoff) (*WebhookTokenAuthenticator, error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/webhook/webhook.go","code":"// New creates a new WebhookTokenAuthenticator from the provided rest\n// config. It is recommend to wrap this authenticator with the token cache\n// authenticator implemented in\n// k8s.io/apiserver/pkg/authentication/token/cache.\nfunc New(config *rest.Config, version string, implicitAuds authenticator.Audiences, retryBackoff wait.Backoff) (*WebhookTokenAuthenticator, error) {\n\ttokenReview, err := tokenReviewInterfaceFromConfig(config, version, retryBackoff)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newWithBackoff(tokenReview, retryBackoff, implicitAuds, time.Duration(0), AuthenticatorMetrics{\n\t\tRecordRequestTotal: noopMetrics{}.RequestTotal,\n\t\tRecordRequestLatency: noopMetrics{}.RequestLatency,\n\t})\n}","line":{"from":72,"to":85}} {"id":100019233,"name":"newWithBackoff","signature":"func newWithBackoff(tokenReview tokenReviewer, retryBackoff wait.Backoff, implicitAuds authenticator.Audiences, requestTimeout time.Duration, metrics AuthenticatorMetrics) (*WebhookTokenAuthenticator, error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/webhook/webhook.go","code":"// newWithBackoff allows tests to skip the sleep.\nfunc newWithBackoff(tokenReview tokenReviewer, retryBackoff wait.Backoff, implicitAuds authenticator.Audiences, requestTimeout time.Duration, metrics AuthenticatorMetrics) (*WebhookTokenAuthenticator, error) {\n\treturn \u0026WebhookTokenAuthenticator{\n\t\ttokenReview,\n\t\tretryBackoff,\n\t\timplicitAuds,\n\t\trequestTimeout,\n\t\tmetrics,\n\t}, nil\n}","line":{"from":87,"to":96}} {"id":100019234,"name":"AuthenticateToken","signature":"func (w *WebhookTokenAuthenticator) AuthenticateToken(ctx context.Context, token string) (*authenticator.Response, bool, error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/webhook/webhook.go","code":"// AuthenticateToken implements the authenticator.Token interface.\nfunc (w *WebhookTokenAuthenticator) AuthenticateToken(ctx context.Context, token string) (*authenticator.Response, bool, error) {\n\t// We take implicit audiences of the API server at WebhookTokenAuthenticator\n\t// construction time. The outline of how we validate audience here is:\n\t//\n\t// * if the ctx is not audience limited, don't do any audience validation.\n\t// * if ctx is audience-limited, add the audiences to the tokenreview spec\n\t// * if the tokenreview returns with audiences in the status that intersect\n\t// with the audiences in the ctx, copy into the response and return success\n\t// * if the tokenreview returns without an audience in the status, ensure\n\t// the ctx audiences intersect with the implicit audiences, and set the\n\t// intersection in the response.\n\t// * otherwise return unauthenticated.\n\twantAuds, checkAuds := authenticator.AudiencesFrom(ctx)\n\tr := \u0026authenticationv1.TokenReview{\n\t\tSpec: authenticationv1.TokenReviewSpec{\n\t\t\tToken: token,\n\t\t\tAudiences: wantAuds,\n\t\t},\n\t}\n\tvar (\n\t\tresult *authenticationv1.TokenReview\n\t\tauds authenticator.Audiences\n\t\tcancel context.CancelFunc\n\t)\n\n\t// set a hard timeout if it was defined\n\t// if the child has a shorter deadline then it will expire first,\n\t// otherwise if the parent has a shorter deadline then the parent will expire and it will be propagate to the child\n\tif w.requestTimeout \u003e 0 {\n\t\tctx, cancel = context.WithTimeout(ctx, w.requestTimeout)\n\t\tdefer cancel()\n\t}\n\n\t// WithExponentialBackoff will return tokenreview create error (tokenReviewErr) if any.\n\tif err := webhook.WithExponentialBackoff(ctx, w.retryBackoff, func() error {\n\t\tvar tokenReviewErr error\n\t\tvar statusCode int\n\n\t\tstart := time.Now()\n\t\tresult, statusCode, tokenReviewErr = w.tokenReview.Create(ctx, r, metav1.CreateOptions{})\n\t\tlatency := time.Since(start)\n\n\t\tif statusCode != 0 {\n\t\t\tw.metrics.RecordRequestTotal(ctx, strconv.Itoa(statusCode))\n\t\t\tw.metrics.RecordRequestLatency(ctx, strconv.Itoa(statusCode), latency.Seconds())\n\t\t\treturn tokenReviewErr\n\t\t}\n\n\t\tif tokenReviewErr != nil {\n\t\t\tw.metrics.RecordRequestTotal(ctx, \"\u003cerror\u003e\")\n\t\t\tw.metrics.RecordRequestLatency(ctx, \"\u003cerror\u003e\", latency.Seconds())\n\t\t}\n\t\treturn tokenReviewErr\n\t}, webhook.DefaultShouldRetry); err != nil {\n\t\t// An error here indicates bad configuration or an outage. Log for debugging.\n\t\tklog.Errorf(\"Failed to make webhook authenticator request: %v\", err)\n\t\treturn nil, false, err\n\t}\n\n\tif checkAuds {\n\t\tgotAuds := w.implicitAuds\n\t\tif len(result.Status.Audiences) \u003e 0 {\n\t\t\tgotAuds = result.Status.Audiences\n\t\t}\n\t\tauds = wantAuds.Intersect(gotAuds)\n\t\tif len(auds) == 0 {\n\t\t\treturn nil, false, nil\n\t\t}\n\t}\n\n\tr.Status = result.Status\n\tif !r.Status.Authenticated {\n\t\tvar err error\n\t\tif len(r.Status.Error) != 0 {\n\t\t\terr = errors.New(r.Status.Error)\n\t\t}\n\t\treturn nil, false, err\n\t}\n\n\tvar extra map[string][]string\n\tif r.Status.User.Extra != nil {\n\t\textra = map[string][]string{}\n\t\tfor k, v := range r.Status.User.Extra {\n\t\t\textra[k] = v\n\t\t}\n\t}\n\n\treturn \u0026authenticator.Response{\n\t\tUser: \u0026user.DefaultInfo{\n\t\t\tName: r.Status.User.Username,\n\t\t\tUID: r.Status.User.UID,\n\t\t\tGroups: r.Status.User.Groups,\n\t\t\tExtra: extra,\n\t\t},\n\t\tAudiences: auds,\n\t}, true, nil\n}","line":{"from":98,"to":195}} {"id":100019235,"name":"tokenReviewInterfaceFromConfig","signature":"func tokenReviewInterfaceFromConfig(config *rest.Config, version string, retryBackoff wait.Backoff) (tokenReviewer, error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/webhook/webhook.go","code":"// tokenReviewInterfaceFromConfig builds a client from the specified kubeconfig file,\n// and returns a TokenReviewInterface that uses that client. Note that the client submits TokenReview\n// requests to the exact path specified in the kubeconfig file, so arbitrary non-API servers can be targeted.\nfunc tokenReviewInterfaceFromConfig(config *rest.Config, version string, retryBackoff wait.Backoff) (tokenReviewer, error) {\n\tlocalScheme := runtime.NewScheme()\n\tif err := scheme.AddToScheme(localScheme); err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch version {\n\tcase authenticationv1.SchemeGroupVersion.Version:\n\t\tgroupVersions := []schema.GroupVersion{authenticationv1.SchemeGroupVersion}\n\t\tif err := localScheme.SetVersionPriority(groupVersions...); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tgw, err := webhook.NewGenericWebhook(localScheme, scheme.Codecs, config, groupVersions, retryBackoff)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn \u0026tokenReviewV1ClientGW{gw.RestClient}, nil\n\n\tcase authenticationv1beta1.SchemeGroupVersion.Version:\n\t\tgroupVersions := []schema.GroupVersion{authenticationv1beta1.SchemeGroupVersion}\n\t\tif err := localScheme.SetVersionPriority(groupVersions...); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tgw, err := webhook.NewGenericWebhook(localScheme, scheme.Codecs, config, groupVersions, retryBackoff)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn \u0026tokenReviewV1beta1ClientGW{gw.RestClient}, nil\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"unsupported authentication webhook version %q, supported versions are %q, %q\",\n\t\t\tversion,\n\t\t\tauthenticationv1.SchemeGroupVersion.Version,\n\t\t\tauthenticationv1beta1.SchemeGroupVersion.Version,\n\t\t)\n\t}\n\n}","line":{"from":197,"to":238}} {"id":100019236,"name":"Create","signature":"func (c *tokenReviewV1Client) Create(ctx context.Context, tokenReview *authenticationv1.TokenReview, opts metav1.CreateOptions) (result *authenticationv1.TokenReview, statusCode int, err error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/webhook/webhook.go","code":"// Create takes the representation of a tokenReview and creates it. Returns the server's representation of the tokenReview, HTTP status code and an error, if there is any.\nfunc (c *tokenReviewV1Client) Create(ctx context.Context, tokenReview *authenticationv1.TokenReview, opts metav1.CreateOptions) (result *authenticationv1.TokenReview, statusCode int, err error) {\n\tresult = \u0026authenticationv1.TokenReview{}\n\n\trestResult := c.client.Post().\n\t\tResource(\"tokenreviews\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(tokenReview).\n\t\tDo(ctx)\n\n\trestResult.StatusCode(\u0026statusCode)\n\terr = restResult.Into(result)\n\treturn\n}","line":{"from":244,"to":257}} {"id":100019237,"name":"Create","signature":"func (c *tokenReviewV1ClientGW) Create(ctx context.Context, tokenReview *authenticationv1.TokenReview, opts metav1.CreateOptions) (result *authenticationv1.TokenReview, statusCode int, err error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/webhook/webhook.go","code":"// Create takes the representation of a tokenReview and creates it. Returns the server's representation of the tokenReview, HTTP status code and an error, if there is any.\nfunc (c *tokenReviewV1ClientGW) Create(ctx context.Context, tokenReview *authenticationv1.TokenReview, opts metav1.CreateOptions) (result *authenticationv1.TokenReview, statusCode int, err error) {\n\tresult = \u0026authenticationv1.TokenReview{}\n\n\trestResult := c.client.Post().\n\t\tBody(tokenReview).\n\t\tDo(ctx)\n\n\trestResult.StatusCode(\u0026statusCode)\n\terr = restResult.Into(result)\n\treturn\n}","line":{"from":264,"to":275}} {"id":100019238,"name":"Create","signature":"func (t *tokenReviewV1beta1ClientGW) Create(ctx context.Context, review *authenticationv1.TokenReview, _ metav1.CreateOptions) (*authenticationv1.TokenReview, int, error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/webhook/webhook.go","code":"func (t *tokenReviewV1beta1ClientGW) Create(ctx context.Context, review *authenticationv1.TokenReview, _ metav1.CreateOptions) (*authenticationv1.TokenReview, int, error) {\n\tvar statusCode int\n\tv1beta1Review := \u0026authenticationv1beta1.TokenReview{Spec: v1SpecToV1beta1Spec(\u0026review.Spec)}\n\tv1beta1Result := \u0026authenticationv1beta1.TokenReview{}\n\n\trestResult := t.client.Post().Body(v1beta1Review).Do(ctx)\n\trestResult.StatusCode(\u0026statusCode)\n\terr := restResult.Into(v1beta1Result)\n\tif err != nil {\n\t\treturn nil, statusCode, err\n\t}\n\treview.Status = v1beta1StatusToV1Status(\u0026v1beta1Result.Status)\n\treturn review, statusCode, nil\n}","line":{"from":282,"to":295}} {"id":100019239,"name":"v1SpecToV1beta1Spec","signature":"func v1SpecToV1beta1Spec(in *authenticationv1.TokenReviewSpec) authenticationv1beta1.TokenReviewSpec","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/webhook/webhook.go","code":"func v1SpecToV1beta1Spec(in *authenticationv1.TokenReviewSpec) authenticationv1beta1.TokenReviewSpec {\n\treturn authenticationv1beta1.TokenReviewSpec{\n\t\tToken: in.Token,\n\t\tAudiences: in.Audiences,\n\t}\n}","line":{"from":297,"to":302}} {"id":100019240,"name":"v1beta1StatusToV1Status","signature":"func v1beta1StatusToV1Status(in *authenticationv1beta1.TokenReviewStatus) authenticationv1.TokenReviewStatus","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/webhook/webhook.go","code":"func v1beta1StatusToV1Status(in *authenticationv1beta1.TokenReviewStatus) authenticationv1.TokenReviewStatus {\n\treturn authenticationv1.TokenReviewStatus{\n\t\tAuthenticated: in.Authenticated,\n\t\tUser: v1beta1UserToV1User(in.User),\n\t\tAudiences: in.Audiences,\n\t\tError: in.Error,\n\t}\n}","line":{"from":304,"to":311}} {"id":100019241,"name":"v1beta1UserToV1User","signature":"func v1beta1UserToV1User(u authenticationv1beta1.UserInfo) authenticationv1.UserInfo","file":"staging/src/k8s.io/apiserver/plugin/pkg/authenticator/token/webhook/webhook.go","code":"func v1beta1UserToV1User(u authenticationv1beta1.UserInfo) authenticationv1.UserInfo {\n\tvar extra map[string]authenticationv1.ExtraValue\n\tif u.Extra != nil {\n\t\textra = make(map[string]authenticationv1.ExtraValue, len(u.Extra))\n\t\tfor k, v := range u.Extra {\n\t\t\textra[k] = authenticationv1.ExtraValue(v)\n\t\t}\n\t}\n\treturn authenticationv1.UserInfo{\n\t\tUsername: u.Username,\n\t\tUID: u.UID,\n\t\tGroups: u.Groups,\n\t\tExtra: extra,\n\t}\n}","line":{"from":313,"to":327}} {"id":100019242,"name":"RecordRequestTotal","signature":"func (noopMetrics) RecordRequestTotal(context.Context, string) {}","file":"staging/src/k8s.io/apiserver/plugin/pkg/authorizer/webhook/metrics.go","code":"func (noopMetrics) RecordRequestTotal(context.Context, string) {}","line":{"from":34,"to":34}} {"id":100019243,"name":"RecordRequestLatency","signature":"func (noopMetrics) RecordRequestLatency(context.Context, string, float64) {}","file":"staging/src/k8s.io/apiserver/plugin/pkg/authorizer/webhook/metrics.go","code":"func (noopMetrics) RecordRequestLatency(context.Context, string, float64) {}","line":{"from":35,"to":35}} {"id":100019244,"name":"DefaultRetryBackoff","signature":"func DefaultRetryBackoff() *wait.Backoff","file":"staging/src/k8s.io/apiserver/plugin/pkg/authorizer/webhook/webhook.go","code":"// DefaultRetryBackoff returns the default backoff parameters for webhook retry.\nfunc DefaultRetryBackoff() *wait.Backoff {\n\tbackoff := webhook.DefaultRetryBackoffWithInitialDelay(500 * time.Millisecond)\n\treturn \u0026backoff\n}","line":{"from":48,"to":52}} {"id":100019245,"name":"NewFromInterface","signature":"func NewFromInterface(subjectAccessReview authorizationv1client.AuthorizationV1Interface, authorizedTTL, unauthorizedTTL time.Duration, retryBackoff wait.Backoff, metrics AuthorizerMetrics) (*WebhookAuthorizer, error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/authorizer/webhook/webhook.go","code":"// NewFromInterface creates a WebhookAuthorizer using the given subjectAccessReview client\nfunc NewFromInterface(subjectAccessReview authorizationv1client.AuthorizationV1Interface, authorizedTTL, unauthorizedTTL time.Duration, retryBackoff wait.Backoff, metrics AuthorizerMetrics) (*WebhookAuthorizer, error) {\n\treturn newWithBackoff(\u0026subjectAccessReviewV1Client{subjectAccessReview.RESTClient()}, authorizedTTL, unauthorizedTTL, retryBackoff, metrics)\n}","line":{"from":71,"to":74}} {"id":100019246,"name":"New","signature":"func New(config *rest.Config, version string, authorizedTTL, unauthorizedTTL time.Duration, retryBackoff wait.Backoff) (*WebhookAuthorizer, error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/authorizer/webhook/webhook.go","code":"// New creates a new WebhookAuthorizer from the provided kubeconfig file.\n// The config's cluster field is used to refer to the remote service, user refers to the returned authorizer.\n//\n//\t# clusters refers to the remote service.\n//\tclusters:\n//\t- name: name-of-remote-authz-service\n//\t cluster:\n//\t certificate-authority: /path/to/ca.pem # CA for verifying the remote service.\n//\t server: https://authz.example.com/authorize # URL of remote service to query. Must use 'https'.\n//\n//\t# users refers to the API server's webhook configuration.\n//\tusers:\n//\t- name: name-of-api-server\n//\t user:\n//\t client-certificate: /path/to/cert.pem # cert for the webhook plugin to use\n//\t client-key: /path/to/key.pem # key matching the cert\n//\n// For additional HTTP configuration, refer to the kubeconfig documentation\n// https://kubernetes.io/docs/user-guide/kubeconfig-file/.\nfunc New(config *rest.Config, version string, authorizedTTL, unauthorizedTTL time.Duration, retryBackoff wait.Backoff) (*WebhookAuthorizer, error) {\n\tsubjectAccessReview, err := subjectAccessReviewInterfaceFromConfig(config, version, retryBackoff)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newWithBackoff(subjectAccessReview, authorizedTTL, unauthorizedTTL, retryBackoff, AuthorizerMetrics{\n\t\tRecordRequestTotal: noopMetrics{}.RecordRequestTotal,\n\t\tRecordRequestLatency: noopMetrics{}.RecordRequestLatency,\n\t})\n}","line":{"from":76,"to":104}} {"id":100019247,"name":"newWithBackoff","signature":"func newWithBackoff(subjectAccessReview subjectAccessReviewer, authorizedTTL, unauthorizedTTL time.Duration, retryBackoff wait.Backoff, metrics AuthorizerMetrics) (*WebhookAuthorizer, error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/authorizer/webhook/webhook.go","code":"// newWithBackoff allows tests to skip the sleep.\nfunc newWithBackoff(subjectAccessReview subjectAccessReviewer, authorizedTTL, unauthorizedTTL time.Duration, retryBackoff wait.Backoff, metrics AuthorizerMetrics) (*WebhookAuthorizer, error) {\n\treturn \u0026WebhookAuthorizer{\n\t\tsubjectAccessReview: subjectAccessReview,\n\t\tresponseCache: cache.NewLRUExpireCache(8192),\n\t\tauthorizedTTL: authorizedTTL,\n\t\tunauthorizedTTL: unauthorizedTTL,\n\t\tretryBackoff: retryBackoff,\n\t\tdecisionOnError: authorizer.DecisionNoOpinion,\n\t\tmetrics: metrics,\n\t}, nil\n}","line":{"from":106,"to":117}} {"id":100019248,"name":"Authorize","signature":"func (w *WebhookAuthorizer) Authorize(ctx context.Context, attr authorizer.Attributes) (decision authorizer.Decision, reason string, err error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/authorizer/webhook/webhook.go","code":"// Authorize makes a REST request to the remote service describing the attempted action as a JSON\n// serialized api.authorization.v1beta1.SubjectAccessReview object. An example request body is\n// provided below.\n//\n//\t{\n//\t \"apiVersion\": \"authorization.k8s.io/v1beta1\",\n//\t \"kind\": \"SubjectAccessReview\",\n//\t \"spec\": {\n//\t \"resourceAttributes\": {\n//\t \"namespace\": \"kittensandponies\",\n//\t \"verb\": \"GET\",\n//\t \"group\": \"group3\",\n//\t \"resource\": \"pods\"\n//\t },\n//\t \"user\": \"jane\",\n//\t \"group\": [\n//\t \"group1\",\n//\t \"group2\"\n//\t ]\n//\t }\n//\t}\n//\n// The remote service is expected to fill the SubjectAccessReviewStatus field to either allow or\n// disallow access. A permissive response would return:\n//\n//\t{\n//\t \"apiVersion\": \"authorization.k8s.io/v1beta1\",\n//\t \"kind\": \"SubjectAccessReview\",\n//\t \"status\": {\n//\t \"allowed\": true\n//\t }\n//\t}\n//\n// To disallow access, the remote service would return:\n//\n//\t{\n//\t \"apiVersion\": \"authorization.k8s.io/v1beta1\",\n//\t \"kind\": \"SubjectAccessReview\",\n//\t \"status\": {\n//\t \"allowed\": false,\n//\t \"reason\": \"user does not have read access to the namespace\"\n//\t }\n//\t}\n//\n// TODO(mikedanese): We should eventually support failing closed when we\n// encounter an error. We are failing open now to preserve backwards compatible\n// behavior.\nfunc (w *WebhookAuthorizer) Authorize(ctx context.Context, attr authorizer.Attributes) (decision authorizer.Decision, reason string, err error) {\n\tr := \u0026authorizationv1.SubjectAccessReview{}\n\tif user := attr.GetUser(); user != nil {\n\t\tr.Spec = authorizationv1.SubjectAccessReviewSpec{\n\t\t\tUser: user.GetName(),\n\t\t\tUID: user.GetUID(),\n\t\t\tGroups: user.GetGroups(),\n\t\t\tExtra: convertToSARExtra(user.GetExtra()),\n\t\t}\n\t}\n\n\tif attr.IsResourceRequest() {\n\t\tr.Spec.ResourceAttributes = \u0026authorizationv1.ResourceAttributes{\n\t\t\tNamespace: attr.GetNamespace(),\n\t\t\tVerb: attr.GetVerb(),\n\t\t\tGroup: attr.GetAPIGroup(),\n\t\t\tVersion: attr.GetAPIVersion(),\n\t\t\tResource: attr.GetResource(),\n\t\t\tSubresource: attr.GetSubresource(),\n\t\t\tName: attr.GetName(),\n\t\t}\n\t} else {\n\t\tr.Spec.NonResourceAttributes = \u0026authorizationv1.NonResourceAttributes{\n\t\t\tPath: attr.GetPath(),\n\t\t\tVerb: attr.GetVerb(),\n\t\t}\n\t}\n\tkey, err := json.Marshal(r.Spec)\n\tif err != nil {\n\t\treturn w.decisionOnError, \"\", err\n\t}\n\tif entry, ok := w.responseCache.Get(string(key)); ok {\n\t\tr.Status = entry.(authorizationv1.SubjectAccessReviewStatus)\n\t} else {\n\t\tvar result *authorizationv1.SubjectAccessReview\n\t\t// WithExponentialBackoff will return SAR create error (sarErr) if any.\n\t\tif err := webhook.WithExponentialBackoff(ctx, w.retryBackoff, func() error {\n\t\t\tvar sarErr error\n\t\t\tvar statusCode int\n\n\t\t\tstart := time.Now()\n\t\t\tresult, statusCode, sarErr = w.subjectAccessReview.Create(ctx, r, metav1.CreateOptions{})\n\t\t\tlatency := time.Since(start)\n\n\t\t\tif statusCode != 0 {\n\t\t\t\tw.metrics.RecordRequestTotal(ctx, strconv.Itoa(statusCode))\n\t\t\t\tw.metrics.RecordRequestLatency(ctx, strconv.Itoa(statusCode), latency.Seconds())\n\t\t\t\treturn sarErr\n\t\t\t}\n\n\t\t\tif sarErr != nil {\n\t\t\t\tw.metrics.RecordRequestTotal(ctx, \"\u003cerror\u003e\")\n\t\t\t\tw.metrics.RecordRequestLatency(ctx, \"\u003cerror\u003e\", latency.Seconds())\n\t\t\t}\n\n\t\t\treturn sarErr\n\t\t}, webhook.DefaultShouldRetry); err != nil {\n\t\t\tklog.Errorf(\"Failed to make webhook authorizer request: %v\", err)\n\t\t\treturn w.decisionOnError, \"\", err\n\t\t}\n\n\t\tr.Status = result.Status\n\t\tif shouldCache(attr) {\n\t\t\tif r.Status.Allowed {\n\t\t\t\tw.responseCache.Add(string(key), r.Status, w.authorizedTTL)\n\t\t\t} else {\n\t\t\t\tw.responseCache.Add(string(key), r.Status, w.unauthorizedTTL)\n\t\t\t}\n\t\t}\n\t}\n\tswitch {\n\tcase r.Status.Denied \u0026\u0026 r.Status.Allowed:\n\t\treturn authorizer.DecisionDeny, r.Status.Reason, fmt.Errorf(\"webhook subject access review returned both allow and deny response\")\n\tcase r.Status.Denied:\n\t\treturn authorizer.DecisionDeny, r.Status.Reason, nil\n\tcase r.Status.Allowed:\n\t\treturn authorizer.DecisionAllow, r.Status.Reason, nil\n\tdefault:\n\t\treturn authorizer.DecisionNoOpinion, r.Status.Reason, nil\n\t}\n\n}","line":{"from":119,"to":247}} {"id":100019249,"name":"RulesFor","signature":"func (w *WebhookAuthorizer) RulesFor(user user.Info, namespace string) ([]authorizer.ResourceRuleInfo, []authorizer.NonResourceRuleInfo, bool, error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/authorizer/webhook/webhook.go","code":"// TODO: need to finish the method to get the rules when using webhook mode\nfunc (w *WebhookAuthorizer) RulesFor(user user.Info, namespace string) ([]authorizer.ResourceRuleInfo, []authorizer.NonResourceRuleInfo, bool, error) {\n\tvar (\n\t\tresourceRules []authorizer.ResourceRuleInfo\n\t\tnonResourceRules []authorizer.NonResourceRuleInfo\n\t)\n\tincomplete := true\n\treturn resourceRules, nonResourceRules, incomplete, fmt.Errorf(\"webhook authorizer does not support user rule resolution\")\n}","line":{"from":249,"to":257}} {"id":100019250,"name":"convertToSARExtra","signature":"func convertToSARExtra(extra map[string][]string) map[string]authorizationv1.ExtraValue","file":"staging/src/k8s.io/apiserver/plugin/pkg/authorizer/webhook/webhook.go","code":"func convertToSARExtra(extra map[string][]string) map[string]authorizationv1.ExtraValue {\n\tif extra == nil {\n\t\treturn nil\n\t}\n\tret := map[string]authorizationv1.ExtraValue{}\n\tfor k, v := range extra {\n\t\tret[k] = authorizationv1.ExtraValue(v)\n\t}\n\n\treturn ret\n}","line":{"from":259,"to":269}} {"id":100019251,"name":"subjectAccessReviewInterfaceFromConfig","signature":"func subjectAccessReviewInterfaceFromConfig(config *rest.Config, version string, retryBackoff wait.Backoff) (subjectAccessReviewer, error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/authorizer/webhook/webhook.go","code":"// subjectAccessReviewInterfaceFromConfig builds a client from the specified kubeconfig file,\n// and returns a SubjectAccessReviewInterface that uses that client. Note that the client submits SubjectAccessReview\n// requests to the exact path specified in the kubeconfig file, so arbitrary non-API servers can be targeted.\nfunc subjectAccessReviewInterfaceFromConfig(config *rest.Config, version string, retryBackoff wait.Backoff) (subjectAccessReviewer, error) {\n\tlocalScheme := runtime.NewScheme()\n\tif err := scheme.AddToScheme(localScheme); err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch version {\n\tcase authorizationv1.SchemeGroupVersion.Version:\n\t\tgroupVersions := []schema.GroupVersion{authorizationv1.SchemeGroupVersion}\n\t\tif err := localScheme.SetVersionPriority(groupVersions...); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tgw, err := webhook.NewGenericWebhook(localScheme, scheme.Codecs, config, groupVersions, retryBackoff)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn \u0026subjectAccessReviewV1ClientGW{gw.RestClient}, nil\n\n\tcase authorizationv1beta1.SchemeGroupVersion.Version:\n\t\tgroupVersions := []schema.GroupVersion{authorizationv1beta1.SchemeGroupVersion}\n\t\tif err := localScheme.SetVersionPriority(groupVersions...); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tgw, err := webhook.NewGenericWebhook(localScheme, scheme.Codecs, config, groupVersions, retryBackoff)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn \u0026subjectAccessReviewV1beta1ClientGW{gw.RestClient}, nil\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"unsupported webhook authorizer version %q, supported versions are %q, %q\",\n\t\t\tversion,\n\t\t\tauthorizationv1.SchemeGroupVersion.Version,\n\t\t\tauthorizationv1beta1.SchemeGroupVersion.Version,\n\t\t)\n\t}\n}","line":{"from":271,"to":311}} {"id":100019252,"name":"Create","signature":"func (t *subjectAccessReviewV1Client) Create(ctx context.Context, subjectAccessReview *authorizationv1.SubjectAccessReview, opts metav1.CreateOptions) (result *authorizationv1.SubjectAccessReview, statusCode int, err error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/authorizer/webhook/webhook.go","code":"func (t *subjectAccessReviewV1Client) Create(ctx context.Context, subjectAccessReview *authorizationv1.SubjectAccessReview, opts metav1.CreateOptions) (result *authorizationv1.SubjectAccessReview, statusCode int, err error) {\n\tresult = \u0026authorizationv1.SubjectAccessReview{}\n\n\trestResult := t.client.Post().\n\t\tResource(\"subjectaccessreviews\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(subjectAccessReview).\n\t\tDo(ctx)\n\n\trestResult.StatusCode(\u0026statusCode)\n\terr = restResult.Into(result)\n\treturn\n}","line":{"from":317,"to":329}} {"id":100019253,"name":"Create","signature":"func (t *subjectAccessReviewV1ClientGW) Create(ctx context.Context, subjectAccessReview *authorizationv1.SubjectAccessReview, _ metav1.CreateOptions) (*authorizationv1.SubjectAccessReview, int, error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/authorizer/webhook/webhook.go","code":"func (t *subjectAccessReviewV1ClientGW) Create(ctx context.Context, subjectAccessReview *authorizationv1.SubjectAccessReview, _ metav1.CreateOptions) (*authorizationv1.SubjectAccessReview, int, error) {\n\tvar statusCode int\n\tresult := \u0026authorizationv1.SubjectAccessReview{}\n\n\trestResult := t.client.Post().Body(subjectAccessReview).Do(ctx)\n\n\trestResult.StatusCode(\u0026statusCode)\n\terr := restResult.Into(result)\n\n\treturn result, statusCode, err\n}","line":{"from":336,"to":346}} {"id":100019254,"name":"Create","signature":"func (t *subjectAccessReviewV1beta1ClientGW) Create(ctx context.Context, subjectAccessReview *authorizationv1.SubjectAccessReview, _ metav1.CreateOptions) (*authorizationv1.SubjectAccessReview, int, error)","file":"staging/src/k8s.io/apiserver/plugin/pkg/authorizer/webhook/webhook.go","code":"func (t *subjectAccessReviewV1beta1ClientGW) Create(ctx context.Context, subjectAccessReview *authorizationv1.SubjectAccessReview, _ metav1.CreateOptions) (*authorizationv1.SubjectAccessReview, int, error) {\n\tvar statusCode int\n\tv1beta1Review := \u0026authorizationv1beta1.SubjectAccessReview{Spec: v1SpecToV1beta1Spec(\u0026subjectAccessReview.Spec)}\n\tv1beta1Result := \u0026authorizationv1beta1.SubjectAccessReview{}\n\n\trestResult := t.client.Post().Body(v1beta1Review).Do(ctx)\n\n\trestResult.StatusCode(\u0026statusCode)\n\terr := restResult.Into(v1beta1Result)\n\tif err == nil {\n\t\tsubjectAccessReview.Status = v1beta1StatusToV1Status(\u0026v1beta1Result.Status)\n\t}\n\treturn subjectAccessReview, statusCode, err\n}","line":{"from":353,"to":366}} {"id":100019255,"name":"shouldCache","signature":"func shouldCache(attr authorizer.Attributes) bool","file":"staging/src/k8s.io/apiserver/plugin/pkg/authorizer/webhook/webhook.go","code":"// shouldCache determines whether it is safe to cache the given request attributes. If the\n// requester-controlled attributes are too large, this may be a DoS attempt, so we skip the cache.\nfunc shouldCache(attr authorizer.Attributes) bool {\n\tcontrolledAttrSize := int64(len(attr.GetNamespace())) +\n\t\tint64(len(attr.GetVerb())) +\n\t\tint64(len(attr.GetAPIGroup())) +\n\t\tint64(len(attr.GetAPIVersion())) +\n\t\tint64(len(attr.GetResource())) +\n\t\tint64(len(attr.GetSubresource())) +\n\t\tint64(len(attr.GetName())) +\n\t\tint64(len(attr.GetPath()))\n\treturn controlledAttrSize \u003c maxControlledAttrCacheSize\n}","line":{"from":368,"to":380}} {"id":100019256,"name":"v1beta1StatusToV1Status","signature":"func v1beta1StatusToV1Status(in *authorizationv1beta1.SubjectAccessReviewStatus) authorizationv1.SubjectAccessReviewStatus","file":"staging/src/k8s.io/apiserver/plugin/pkg/authorizer/webhook/webhook.go","code":"func v1beta1StatusToV1Status(in *authorizationv1beta1.SubjectAccessReviewStatus) authorizationv1.SubjectAccessReviewStatus {\n\treturn authorizationv1.SubjectAccessReviewStatus{\n\t\tAllowed: in.Allowed,\n\t\tDenied: in.Denied,\n\t\tReason: in.Reason,\n\t\tEvaluationError: in.EvaluationError,\n\t}\n}","line":{"from":382,"to":389}} {"id":100019257,"name":"v1SpecToV1beta1Spec","signature":"func v1SpecToV1beta1Spec(in *authorizationv1.SubjectAccessReviewSpec) authorizationv1beta1.SubjectAccessReviewSpec","file":"staging/src/k8s.io/apiserver/plugin/pkg/authorizer/webhook/webhook.go","code":"func v1SpecToV1beta1Spec(in *authorizationv1.SubjectAccessReviewSpec) authorizationv1beta1.SubjectAccessReviewSpec {\n\treturn authorizationv1beta1.SubjectAccessReviewSpec{\n\t\tResourceAttributes: v1ResourceAttributesToV1beta1ResourceAttributes(in.ResourceAttributes),\n\t\tNonResourceAttributes: v1NonResourceAttributesToV1beta1NonResourceAttributes(in.NonResourceAttributes),\n\t\tUser: in.User,\n\t\tGroups: in.Groups,\n\t\tExtra: v1ExtraToV1beta1Extra(in.Extra),\n\t\tUID: in.UID,\n\t}\n}","line":{"from":391,"to":400}} {"id":100019258,"name":"v1ResourceAttributesToV1beta1ResourceAttributes","signature":"func v1ResourceAttributesToV1beta1ResourceAttributes(in *authorizationv1.ResourceAttributes) *authorizationv1beta1.ResourceAttributes","file":"staging/src/k8s.io/apiserver/plugin/pkg/authorizer/webhook/webhook.go","code":"func v1ResourceAttributesToV1beta1ResourceAttributes(in *authorizationv1.ResourceAttributes) *authorizationv1beta1.ResourceAttributes {\n\tif in == nil {\n\t\treturn nil\n\t}\n\treturn \u0026authorizationv1beta1.ResourceAttributes{\n\t\tNamespace: in.Namespace,\n\t\tVerb: in.Verb,\n\t\tGroup: in.Group,\n\t\tVersion: in.Version,\n\t\tResource: in.Resource,\n\t\tSubresource: in.Subresource,\n\t\tName: in.Name,\n\t}\n}","line":{"from":402,"to":415}} {"id":100019259,"name":"v1NonResourceAttributesToV1beta1NonResourceAttributes","signature":"func v1NonResourceAttributesToV1beta1NonResourceAttributes(in *authorizationv1.NonResourceAttributes) *authorizationv1beta1.NonResourceAttributes","file":"staging/src/k8s.io/apiserver/plugin/pkg/authorizer/webhook/webhook.go","code":"func v1NonResourceAttributesToV1beta1NonResourceAttributes(in *authorizationv1.NonResourceAttributes) *authorizationv1beta1.NonResourceAttributes {\n\tif in == nil {\n\t\treturn nil\n\t}\n\treturn \u0026authorizationv1beta1.NonResourceAttributes{\n\t\tPath: in.Path,\n\t\tVerb: in.Verb,\n\t}\n}","line":{"from":417,"to":425}} {"id":100019260,"name":"v1ExtraToV1beta1Extra","signature":"func v1ExtraToV1beta1Extra(in map[string]authorizationv1.ExtraValue) map[string]authorizationv1beta1.ExtraValue","file":"staging/src/k8s.io/apiserver/plugin/pkg/authorizer/webhook/webhook.go","code":"func v1ExtraToV1beta1Extra(in map[string]authorizationv1.ExtraValue) map[string]authorizationv1beta1.ExtraValue {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tret := make(map[string]authorizationv1beta1.ExtraValue, len(in))\n\tfor k, v := range in {\n\t\tret[k] = authorizationv1beta1.ExtraValue(v)\n\t}\n\treturn ret\n}","line":{"from":427,"to":436}} {"id":100019261,"name":"NewResourceBuilderFlags","signature":"func NewResourceBuilderFlags() *ResourceBuilderFlags","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/builder_flags.go","code":"// NewResourceBuilderFlags returns a default ResourceBuilderFlags\nfunc NewResourceBuilderFlags() *ResourceBuilderFlags {\n\tfilenames := []string{}\n\n\treturn \u0026ResourceBuilderFlags{\n\t\tFileNameFlags: \u0026FileNameFlags{\n\t\t\tUsage: \"identifying the resource.\",\n\t\t\tFilenames: \u0026filenames,\n\t\t\tRecursive: boolPtr(true),\n\t\t},\n\t}\n}","line":{"from":42,"to":53}} {"id":100019262,"name":"WithFile","signature":"func (o *ResourceBuilderFlags) WithFile(recurse bool, files ...string) *ResourceBuilderFlags","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/builder_flags.go","code":"// WithFile sets the FileNameFlags.\n// If recurse is set, it will process directory recursively. Useful when you want to manage related manifests\n// organized within the same directory.\nfunc (o *ResourceBuilderFlags) WithFile(recurse bool, files ...string) *ResourceBuilderFlags {\n\to.FileNameFlags = \u0026FileNameFlags{\n\t\tUsage: \"identifying the resource.\",\n\t\tFilenames: \u0026files,\n\t\tRecursive: boolPtr(recurse),\n\t}\n\n\treturn o\n}","line":{"from":55,"to":66}} {"id":100019263,"name":"WithLabelSelector","signature":"func (o *ResourceBuilderFlags) WithLabelSelector(selector string) *ResourceBuilderFlags","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/builder_flags.go","code":"// WithLabelSelector sets the LabelSelector flag\nfunc (o *ResourceBuilderFlags) WithLabelSelector(selector string) *ResourceBuilderFlags {\n\to.LabelSelector = \u0026selector\n\treturn o\n}","line":{"from":68,"to":72}} {"id":100019264,"name":"WithFieldSelector","signature":"func (o *ResourceBuilderFlags) WithFieldSelector(selector string) *ResourceBuilderFlags","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/builder_flags.go","code":"// WithFieldSelector sets the FieldSelector flag\nfunc (o *ResourceBuilderFlags) WithFieldSelector(selector string) *ResourceBuilderFlags {\n\to.FieldSelector = \u0026selector\n\treturn o\n}","line":{"from":74,"to":78}} {"id":100019265,"name":"WithAllNamespaces","signature":"func (o *ResourceBuilderFlags) WithAllNamespaces(defaultVal bool) *ResourceBuilderFlags","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/builder_flags.go","code":"// WithAllNamespaces sets the AllNamespaces flag\nfunc (o *ResourceBuilderFlags) WithAllNamespaces(defaultVal bool) *ResourceBuilderFlags {\n\to.AllNamespaces = \u0026defaultVal\n\treturn o\n}","line":{"from":80,"to":84}} {"id":100019266,"name":"WithAll","signature":"func (o *ResourceBuilderFlags) WithAll(defaultVal bool) *ResourceBuilderFlags","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/builder_flags.go","code":"// WithAll sets the All flag\nfunc (o *ResourceBuilderFlags) WithAll(defaultVal bool) *ResourceBuilderFlags {\n\to.All = \u0026defaultVal\n\treturn o\n}","line":{"from":86,"to":90}} {"id":100019267,"name":"WithLocal","signature":"func (o *ResourceBuilderFlags) WithLocal(defaultVal bool) *ResourceBuilderFlags","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/builder_flags.go","code":"// WithLocal sets the Local flag\nfunc (o *ResourceBuilderFlags) WithLocal(defaultVal bool) *ResourceBuilderFlags {\n\to.Local = \u0026defaultVal\n\treturn o\n}","line":{"from":92,"to":96}} {"id":100019268,"name":"WithScheme","signature":"func (o *ResourceBuilderFlags) WithScheme(scheme *runtime.Scheme) *ResourceBuilderFlags","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/builder_flags.go","code":"// WithScheme sets the Scheme flag\nfunc (o *ResourceBuilderFlags) WithScheme(scheme *runtime.Scheme) *ResourceBuilderFlags {\n\to.Scheme = scheme\n\treturn o\n}","line":{"from":98,"to":102}} {"id":100019269,"name":"WithLatest","signature":"func (o *ResourceBuilderFlags) WithLatest() *ResourceBuilderFlags","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/builder_flags.go","code":"// WithLatest sets the Latest flag\nfunc (o *ResourceBuilderFlags) WithLatest() *ResourceBuilderFlags {\n\to.Latest = true\n\treturn o\n}","line":{"from":104,"to":108}} {"id":100019270,"name":"StopOnError","signature":"func (o *ResourceBuilderFlags) StopOnError() *ResourceBuilderFlags","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/builder_flags.go","code":"// StopOnError sets the StopOnFirstError flag\nfunc (o *ResourceBuilderFlags) StopOnError() *ResourceBuilderFlags {\n\to.StopOnFirstError = true\n\treturn o\n}","line":{"from":110,"to":114}} {"id":100019271,"name":"AddFlags","signature":"func (o *ResourceBuilderFlags) AddFlags(flagset *pflag.FlagSet)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/builder_flags.go","code":"// AddFlags registers flags for finding resources\nfunc (o *ResourceBuilderFlags) AddFlags(flagset *pflag.FlagSet) {\n\to.FileNameFlags.AddFlags(flagset)\n\n\tif o.LabelSelector != nil {\n\t\tflagset.StringVarP(o.LabelSelector, \"selector\", \"l\", *o.LabelSelector, \"Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)\")\n\t}\n\tif o.FieldSelector != nil {\n\t\tflagset.StringVar(o.FieldSelector, \"field-selector\", *o.FieldSelector, \"Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector key1=value1,key2=value2). The server only supports a limited number of field queries per type.\")\n\t}\n\tif o.AllNamespaces != nil {\n\t\tflagset.BoolVarP(o.AllNamespaces, \"all-namespaces\", \"A\", *o.AllNamespaces, \"If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace.\")\n\t}\n\tif o.All != nil {\n\t\tflagset.BoolVar(o.All, \"all\", *o.All, \"Select all resources in the namespace of the specified resource types\")\n\t}\n\tif o.Local != nil {\n\t\tflagset.BoolVar(o.Local, \"local\", *o.Local, \"If true, annotation will NOT contact api-server but run locally.\")\n\t}\n}","line":{"from":116,"to":135}} {"id":100019272,"name":"ToBuilder","signature":"func (o *ResourceBuilderFlags) ToBuilder(restClientGetter RESTClientGetter, resources []string) ResourceFinder","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/builder_flags.go","code":"// ToBuilder gives you back a resource finder to visit resources that are located\nfunc (o *ResourceBuilderFlags) ToBuilder(restClientGetter RESTClientGetter, resources []string) ResourceFinder {\n\tnamespace, enforceNamespace, namespaceErr := restClientGetter.ToRawKubeConfigLoader().Namespace()\n\n\tbuilder := resource.NewBuilder(restClientGetter).\n\t\tNamespaceParam(namespace).DefaultNamespace()\n\n\tif o.AllNamespaces != nil {\n\t\tbuilder.AllNamespaces(*o.AllNamespaces)\n\t}\n\n\tif o.Scheme != nil {\n\t\tbuilder.WithScheme(o.Scheme, o.Scheme.PrioritizedVersionsAllGroups()...)\n\t} else {\n\t\tbuilder.Unstructured()\n\t}\n\n\tif o.FileNameFlags != nil {\n\t\topts := o.FileNameFlags.ToOptions()\n\t\tbuilder.FilenameParam(enforceNamespace, \u0026opts)\n\t}\n\n\tif o.Local == nil || !*o.Local {\n\t\t// resource type/name tuples only work non-local\n\t\tif o.All != nil {\n\t\t\tbuilder.ResourceTypeOrNameArgs(*o.All, resources...)\n\t\t} else {\n\t\t\tbuilder.ResourceTypeOrNameArgs(false, resources...)\n\t\t}\n\t\t// label selectors only work non-local (for now)\n\t\tif o.LabelSelector != nil {\n\t\t\tbuilder.LabelSelectorParam(*o.LabelSelector)\n\t\t}\n\t\t// field selectors only work non-local (forever)\n\t\tif o.FieldSelector != nil {\n\t\t\tbuilder.FieldSelectorParam(*o.FieldSelector)\n\t\t}\n\t\t// latest only works non-local (forever)\n\t\tif o.Latest {\n\t\t\tbuilder.Latest()\n\t\t}\n\n\t} else {\n\t\tbuilder.Local()\n\n\t\tif len(resources) \u003e 0 {\n\t\t\tbuilder.AddError(resource.LocalResourceError)\n\t\t}\n\t}\n\n\tif !o.StopOnFirstError {\n\t\tbuilder.ContinueOnError()\n\t}\n\n\treturn \u0026ResourceFindBuilderWrapper{\n\t\tbuilder: builder.\n\t\t\tFlatten(). // I think we're going to recommend this everywhere\n\t\t\tAddError(namespaceErr),\n\t}\n}","line":{"from":137,"to":196}} {"id":100019273,"name":"Do","signature":"func (b *ResourceFindBuilderWrapper) Do() resource.Visitor","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/builder_flags.go","code":"// Do finds you resources to check\nfunc (b *ResourceFindBuilderWrapper) Do() resource.Visitor {\n\treturn b.builder.Do()\n}","line":{"from":203,"to":206}} {"id":100019274,"name":"Do","signature":"func (fn ResourceFinderFunc) Do() resource.Visitor","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/builder_flags.go","code":"// Do implements ResourceFinder\nfunc (fn ResourceFinderFunc) Do() resource.Visitor {\n\treturn fn()\n}","line":{"from":217,"to":220}} {"id":100019275,"name":"ResourceFinderForResult","signature":"func ResourceFinderForResult(result resource.Visitor) ResourceFinder","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/builder_flags.go","code":"// ResourceFinderForResult skins a visitor for re-use as a ResourceFinder\nfunc ResourceFinderForResult(result resource.Visitor) ResourceFinder {\n\treturn ResourceFinderFunc(func() resource.Visitor {\n\t\treturn result\n\t})\n}","line":{"from":222,"to":227}} {"id":100019276,"name":"boolPtr","signature":"func boolPtr(val bool) *bool","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/builder_flags.go","code":"func boolPtr(val bool) *bool {\n\treturn \u0026val\n}","line":{"from":229,"to":231}} {"id":100019277,"name":"RawConfig","signature":"func (c *clientConfig) RawConfig() (clientcmdapi.Config, error)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/client_config.go","code":"func (c *clientConfig) RawConfig() (clientcmdapi.Config, error) {\n\tconfig, err := c.defaultClientConfig.RawConfig()\n\t// replace client-go's ErrEmptyConfig error with our custom, more verbose version\n\tif clientcmd.IsEmptyConfig(err) {\n\t\treturn config, ErrEmptyConfig\n\t}\n\treturn config, err\n}","line":{"from":43,"to":50}} {"id":100019278,"name":"ClientConfig","signature":"func (c *clientConfig) ClientConfig() (*restclient.Config, error)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/client_config.go","code":"func (c *clientConfig) ClientConfig() (*restclient.Config, error) {\n\tconfig, err := c.defaultClientConfig.ClientConfig()\n\t// replace client-go's ErrEmptyConfig error with our custom, more verbose version\n\tif clientcmd.IsEmptyConfig(err) {\n\t\treturn config, ErrEmptyConfig\n\t}\n\treturn config, err\n}","line":{"from":52,"to":59}} {"id":100019279,"name":"Namespace","signature":"func (c *clientConfig) Namespace() (string, bool, error)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/client_config.go","code":"func (c *clientConfig) Namespace() (string, bool, error) {\n\tnamespace, ok, err := c.defaultClientConfig.Namespace()\n\t// replace client-go's ErrEmptyConfig error with our custom, more verbose version\n\tif clientcmd.IsEmptyConfig(err) {\n\t\treturn namespace, ok, ErrEmptyConfig\n\t}\n\treturn namespace, ok, err\n}","line":{"from":61,"to":68}} {"id":100019280,"name":"ConfigAccess","signature":"func (c *clientConfig) ConfigAccess() clientcmd.ConfigAccess","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/client_config.go","code":"func (c *clientConfig) ConfigAccess() clientcmd.ConfigAccess {\n\treturn c.defaultClientConfig.ConfigAccess()\n}","line":{"from":70,"to":72}} {"id":100019281,"name":"RoundTrip","signature":"func (c *CommandHeaderRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/command_headers.go","code":"// CommandHeaderRoundTripper adds Request headers before delegating to standard\n// round tripper. These headers are kubectl command headers which\n// detail the kubectl command. See SIG CLI KEP 859:\n//\n//\thttps://github.com/kubernetes/enhancements/tree/master/keps/sig-cli/859-kubectl-headers\nfunc (c *CommandHeaderRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {\n\tfor header, value := range c.Headers {\n\t\treq.Header.Set(header, value)\n\t}\n\treturn c.Delegate.RoundTrip(req)\n}","line":{"from":40,"to":50}} {"id":100019282,"name":"ParseCommandHeaders","signature":"func (c *CommandHeaderRoundTripper) ParseCommandHeaders(cmd *cobra.Command, args []string)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/command_headers.go","code":"// ParseCommandHeaders fills in a map of custom headers into the CommandHeaderRoundTripper. These\n// headers are then filled into each request. For details on the custom headers see:\n//\n//\thttps://github.com/kubernetes/enhancements/tree/master/keps/sig-cli/859-kubectl-headers\n//\n// Each call overwrites the previously parsed command headers (not additive).\n// TODO(seans3): Parse/add flags removing PII from flag values.\nfunc (c *CommandHeaderRoundTripper) ParseCommandHeaders(cmd *cobra.Command, args []string) {\n\tif cmd == nil {\n\t\treturn\n\t}\n\t// Overwrites previously parsed command headers (headers not additive).\n\tc.Headers = map[string]string{}\n\t// Session identifier to aggregate multiple Requests from single kubectl command.\n\tuid := uuid.New().String()\n\tc.Headers[kubectlSessionHeader] = uid\n\t// Iterate up the hierarchy of commands from the leaf command to create\n\t// the full command string. Example: kubectl create secret generic\n\tcmdStrs := []string{}\n\tfor cmd.HasParent() {\n\t\tparent := cmd.Parent()\n\t\tcurrName := strings.TrimSpace(cmd.Name())\n\t\tcmdStrs = append([]string{currName}, cmdStrs...)\n\t\tcmd = parent\n\t}\n\tcurrName := strings.TrimSpace(cmd.Name())\n\tcmdStrs = append([]string{currName}, cmdStrs...)\n\tif len(cmdStrs) \u003e 0 {\n\t\tc.Headers[kubectlCommandHeader] = strings.Join(cmdStrs, \" \")\n\t}\n}","line":{"from":52,"to":82}} {"id":100019283,"name":"CancelRequest","signature":"func (c *CommandHeaderRoundTripper) CancelRequest(req *http.Request)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/command_headers.go","code":"// CancelRequest is propagated to the Delegate RoundTripper within\n// if the wrapped RoundTripper implements this function.\nfunc (c *CommandHeaderRoundTripper) CancelRequest(req *http.Request) {\n\ttype canceler interface {\n\t\tCancelRequest(*http.Request)\n\t}\n\t// If possible, call \"CancelRequest\" on the wrapped Delegate RoundTripper.\n\tif cr, ok := c.Delegate.(canceler); ok {\n\t\tcr.CancelRequest(req)\n\t}\n}","line":{"from":84,"to":94}} {"id":100019284,"name":"ToRESTConfig","signature":"func (f *ConfigFlags) ToRESTConfig() (*rest.Config, error)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go","code":"// ToRESTConfig implements RESTClientGetter.\n// Returns a REST client configuration based on a provided path\n// to a .kubeconfig file, loading rules, and config flag overrides.\n// Expects the AddFlags method to have been called. If WrapConfigFn\n// is non-nil this function can transform config before return.\nfunc (f *ConfigFlags) ToRESTConfig() (*rest.Config, error) {\n\tc, err := f.ToRawKubeConfigLoader().ClientConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif f.WrapConfigFn != nil {\n\t\treturn f.WrapConfigFn(c), nil\n\t}\n\treturn c, nil\n}","line":{"from":127,"to":141}} {"id":100019285,"name":"ToRawKubeConfigLoader","signature":"func (f *ConfigFlags) ToRawKubeConfigLoader() clientcmd.ClientConfig","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go","code":"// ToRawKubeConfigLoader binds config flag values to config overrides\n// Returns an interactive clientConfig if the password flag is enabled,\n// or a non-interactive clientConfig otherwise.\nfunc (f *ConfigFlags) ToRawKubeConfigLoader() clientcmd.ClientConfig {\n\tif f.usePersistentConfig {\n\t\treturn f.toRawKubePersistentConfigLoader()\n\t}\n\treturn f.toRawKubeConfigLoader()\n}","line":{"from":143,"to":151}} {"id":100019286,"name":"toRawKubeConfigLoader","signature":"func (f *ConfigFlags) toRawKubeConfigLoader() clientcmd.ClientConfig","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go","code":"func (f *ConfigFlags) toRawKubeConfigLoader() clientcmd.ClientConfig {\n\tloadingRules := clientcmd.NewDefaultClientConfigLoadingRules()\n\t// use the standard defaults for this client command\n\t// DEPRECATED: remove and replace with something more accurate\n\tloadingRules.DefaultClientConfig = \u0026clientcmd.DefaultClientConfig\n\n\tif f.KubeConfig != nil {\n\t\tloadingRules.ExplicitPath = *f.KubeConfig\n\t}\n\n\toverrides := \u0026clientcmd.ConfigOverrides{ClusterDefaults: clientcmd.ClusterDefaults}\n\n\t// bind auth info flag values to overrides\n\tif f.CertFile != nil {\n\t\toverrides.AuthInfo.ClientCertificate = *f.CertFile\n\t}\n\tif f.KeyFile != nil {\n\t\toverrides.AuthInfo.ClientKey = *f.KeyFile\n\t}\n\tif f.BearerToken != nil {\n\t\toverrides.AuthInfo.Token = *f.BearerToken\n\t}\n\tif f.Impersonate != nil {\n\t\toverrides.AuthInfo.Impersonate = *f.Impersonate\n\t}\n\tif f.ImpersonateUID != nil {\n\t\toverrides.AuthInfo.ImpersonateUID = *f.ImpersonateUID\n\t}\n\tif f.ImpersonateGroup != nil {\n\t\toverrides.AuthInfo.ImpersonateGroups = *f.ImpersonateGroup\n\t}\n\tif f.Username != nil {\n\t\toverrides.AuthInfo.Username = *f.Username\n\t}\n\tif f.Password != nil {\n\t\toverrides.AuthInfo.Password = *f.Password\n\t}\n\n\t// bind cluster flags\n\tif f.APIServer != nil {\n\t\toverrides.ClusterInfo.Server = *f.APIServer\n\t}\n\tif f.TLSServerName != nil {\n\t\toverrides.ClusterInfo.TLSServerName = *f.TLSServerName\n\t}\n\tif f.CAFile != nil {\n\t\toverrides.ClusterInfo.CertificateAuthority = *f.CAFile\n\t}\n\tif f.Insecure != nil {\n\t\toverrides.ClusterInfo.InsecureSkipTLSVerify = *f.Insecure\n\t}\n\tif f.DisableCompression != nil {\n\t\toverrides.ClusterInfo.DisableCompression = *f.DisableCompression\n\t}\n\n\t// bind context flags\n\tif f.Context != nil {\n\t\toverrides.CurrentContext = *f.Context\n\t}\n\tif f.ClusterName != nil {\n\t\toverrides.Context.Cluster = *f.ClusterName\n\t}\n\tif f.AuthInfoName != nil {\n\t\toverrides.Context.AuthInfo = *f.AuthInfoName\n\t}\n\tif f.Namespace != nil {\n\t\toverrides.Context.Namespace = *f.Namespace\n\t}\n\n\tif f.Timeout != nil {\n\t\toverrides.Timeout = *f.Timeout\n\t}\n\n\t// we only have an interactive prompt when a password is allowed\n\tif f.Password == nil {\n\t\treturn \u0026clientConfig{clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, overrides)}\n\t}\n\treturn \u0026clientConfig{clientcmd.NewInteractiveDeferredLoadingClientConfig(loadingRules, overrides, os.Stdin)}\n}","line":{"from":153,"to":231}} {"id":100019287,"name":"toRawKubePersistentConfigLoader","signature":"func (f *ConfigFlags) toRawKubePersistentConfigLoader() clientcmd.ClientConfig","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go","code":"// toRawKubePersistentConfigLoader binds config flag values to config overrides\n// Returns a persistent clientConfig for propagation.\nfunc (f *ConfigFlags) toRawKubePersistentConfigLoader() clientcmd.ClientConfig {\n\tf.clientConfigLock.Lock()\n\tdefer f.clientConfigLock.Unlock()\n\n\tif f.clientConfig == nil {\n\t\tf.clientConfig = f.toRawKubeConfigLoader()\n\t}\n\n\treturn f.clientConfig\n}","line":{"from":233,"to":244}} {"id":100019288,"name":"ToDiscoveryClient","signature":"func (f *ConfigFlags) ToDiscoveryClient() (discovery.CachedDiscoveryInterface, error)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go","code":"// ToDiscoveryClient implements RESTClientGetter.\n// Expects the AddFlags method to have been called.\n// Returns a CachedDiscoveryInterface using a computed RESTConfig.\nfunc (f *ConfigFlags) ToDiscoveryClient() (discovery.CachedDiscoveryInterface, error) {\n\tif f.usePersistentConfig {\n\t\treturn f.toPersistentDiscoveryClient()\n\t}\n\treturn f.toDiscoveryClient()\n}","line":{"from":246,"to":254}} {"id":100019289,"name":"toPersistentDiscoveryClient","signature":"func (f *ConfigFlags) toPersistentDiscoveryClient() (discovery.CachedDiscoveryInterface, error)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go","code":"func (f *ConfigFlags) toPersistentDiscoveryClient() (discovery.CachedDiscoveryInterface, error) {\n\tf.discoveryClientLock.Lock()\n\tdefer f.discoveryClientLock.Unlock()\n\n\tif f.discoveryClient == nil {\n\t\tdiscoveryClient, err := f.toDiscoveryClient()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tf.discoveryClient = discoveryClient\n\t}\n\treturn f.discoveryClient, nil\n}","line":{"from":256,"to":268}} {"id":100019290,"name":"toDiscoveryClient","signature":"func (f *ConfigFlags) toDiscoveryClient() (discovery.CachedDiscoveryInterface, error)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go","code":"func (f *ConfigFlags) toDiscoveryClient() (discovery.CachedDiscoveryInterface, error) {\n\tconfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig.Burst = f.discoveryBurst\n\tconfig.QPS = f.discoveryQPS\n\n\tcacheDir := getDefaultCacheDir()\n\n\t// retrieve a user-provided value for the \"cache-dir\"\n\t// override httpCacheDir and discoveryCacheDir if user-value is given.\n\t// user-provided value has higher precedence than default\n\t// and KUBECACHEDIR environment variable.\n\tif f.CacheDir != nil \u0026\u0026 *f.CacheDir != \"\" \u0026\u0026 *f.CacheDir != getDefaultCacheDir() {\n\t\tcacheDir = *f.CacheDir\n\t}\n\n\thttpCacheDir := filepath.Join(cacheDir, \"http\")\n\tdiscoveryCacheDir := computeDiscoverCacheDir(filepath.Join(cacheDir, \"discovery\"), config.Host)\n\n\treturn diskcached.NewCachedDiscoveryClientForConfig(config, discoveryCacheDir, httpCacheDir, time.Duration(6*time.Hour))\n}","line":{"from":270,"to":293}} {"id":100019291,"name":"getDefaultCacheDir","signature":"func getDefaultCacheDir() string","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go","code":"// getDefaultCacheDir returns default caching directory path.\n// it first looks at KUBECACHEDIR env var if it is set, otherwise\n// it returns standard kube cache dir.\nfunc getDefaultCacheDir() string {\n\tif kcd := os.Getenv(\"KUBECACHEDIR\"); kcd != \"\" {\n\t\treturn kcd\n\t}\n\n\treturn filepath.Join(homedir.HomeDir(), \".kube\", \"cache\")\n}","line":{"from":295,"to":304}} {"id":100019292,"name":"ToRESTMapper","signature":"func (f *ConfigFlags) ToRESTMapper() (meta.RESTMapper, error)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go","code":"// ToRESTMapper returns a mapper.\nfunc (f *ConfigFlags) ToRESTMapper() (meta.RESTMapper, error) {\n\tif f.usePersistentConfig {\n\t\treturn f.toPersistentRESTMapper()\n\t}\n\treturn f.toRESTMapper()\n}","line":{"from":306,"to":312}} {"id":100019293,"name":"toPersistentRESTMapper","signature":"func (f *ConfigFlags) toPersistentRESTMapper() (meta.RESTMapper, error)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go","code":"func (f *ConfigFlags) toPersistentRESTMapper() (meta.RESTMapper, error) {\n\tf.restMapperLock.Lock()\n\tdefer f.restMapperLock.Unlock()\n\n\tif f.restMapper == nil {\n\t\trestMapper, err := f.toRESTMapper()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tf.restMapper = restMapper\n\t}\n\treturn f.restMapper, nil\n}","line":{"from":314,"to":326}} {"id":100019294,"name":"toRESTMapper","signature":"func (f *ConfigFlags) toRESTMapper() (meta.RESTMapper, error)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go","code":"func (f *ConfigFlags) toRESTMapper() (meta.RESTMapper, error) {\n\tdiscoveryClient, err := f.ToDiscoveryClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmapper := restmapper.NewDeferredDiscoveryRESTMapper(discoveryClient)\n\texpander := restmapper.NewShortcutExpander(mapper, discoveryClient)\n\treturn expander, nil\n}","line":{"from":328,"to":337}} {"id":100019295,"name":"AddFlags","signature":"func (f *ConfigFlags) AddFlags(flags *pflag.FlagSet)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go","code":"// AddFlags binds client configuration flags to a given flagset\nfunc (f *ConfigFlags) AddFlags(flags *pflag.FlagSet) {\n\tif f.KubeConfig != nil {\n\t\tflags.StringVar(f.KubeConfig, \"kubeconfig\", *f.KubeConfig, \"Path to the kubeconfig file to use for CLI requests.\")\n\t}\n\tif f.CacheDir != nil {\n\t\tflags.StringVar(f.CacheDir, flagCacheDir, *f.CacheDir, \"Default cache directory\")\n\t}\n\n\t// add config options\n\tif f.CertFile != nil {\n\t\tflags.StringVar(f.CertFile, flagCertFile, *f.CertFile, \"Path to a client certificate file for TLS\")\n\t}\n\tif f.KeyFile != nil {\n\t\tflags.StringVar(f.KeyFile, flagKeyFile, *f.KeyFile, \"Path to a client key file for TLS\")\n\t}\n\tif f.BearerToken != nil {\n\t\tflags.StringVar(f.BearerToken, flagBearerToken, *f.BearerToken, \"Bearer token for authentication to the API server\")\n\t}\n\tif f.Impersonate != nil {\n\t\tflags.StringVar(f.Impersonate, flagImpersonate, *f.Impersonate, \"Username to impersonate for the operation. User could be a regular user or a service account in a namespace.\")\n\t}\n\tif f.ImpersonateUID != nil {\n\t\tflags.StringVar(f.ImpersonateUID, flagImpersonateUID, *f.ImpersonateUID, \"UID to impersonate for the operation.\")\n\t}\n\tif f.ImpersonateGroup != nil {\n\t\tflags.StringArrayVar(f.ImpersonateGroup, flagImpersonateGroup, *f.ImpersonateGroup, \"Group to impersonate for the operation, this flag can be repeated to specify multiple groups.\")\n\t}\n\tif f.Username != nil {\n\t\tflags.StringVar(f.Username, flagUsername, *f.Username, \"Username for basic authentication to the API server\")\n\t}\n\tif f.Password != nil {\n\t\tflags.StringVar(f.Password, flagPassword, *f.Password, \"Password for basic authentication to the API server\")\n\t}\n\tif f.ClusterName != nil {\n\t\tflags.StringVar(f.ClusterName, flagClusterName, *f.ClusterName, \"The name of the kubeconfig cluster to use\")\n\t}\n\tif f.AuthInfoName != nil {\n\t\tflags.StringVar(f.AuthInfoName, flagAuthInfoName, *f.AuthInfoName, \"The name of the kubeconfig user to use\")\n\t}\n\tif f.Namespace != nil {\n\t\tflags.StringVarP(f.Namespace, flagNamespace, \"n\", *f.Namespace, \"If present, the namespace scope for this CLI request\")\n\t}\n\tif f.Context != nil {\n\t\tflags.StringVar(f.Context, flagContext, *f.Context, \"The name of the kubeconfig context to use\")\n\t}\n\n\tif f.APIServer != nil {\n\t\tflags.StringVarP(f.APIServer, flagAPIServer, \"s\", *f.APIServer, \"The address and port of the Kubernetes API server\")\n\t}\n\tif f.TLSServerName != nil {\n\t\tflags.StringVar(f.TLSServerName, flagTLSServerName, *f.TLSServerName, \"Server name to use for server certificate validation. If it is not provided, the hostname used to contact the server is used\")\n\t}\n\tif f.Insecure != nil {\n\t\tflags.BoolVar(f.Insecure, flagInsecure, *f.Insecure, \"If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure\")\n\t}\n\tif f.CAFile != nil {\n\t\tflags.StringVar(f.CAFile, flagCAFile, *f.CAFile, \"Path to a cert file for the certificate authority\")\n\t}\n\tif f.Timeout != nil {\n\t\tflags.StringVar(f.Timeout, flagTimeout, *f.Timeout, \"The length of time to wait before giving up on a single server request. Non-zero values should contain a corresponding time unit (e.g. 1s, 2m, 3h). A value of zero means don't timeout requests.\")\n\t}\n\tif f.DisableCompression != nil {\n\t\tflags.BoolVar(f.DisableCompression, flagDisableCompression, *f.DisableCompression, \"If true, opt-out of response compression for all requests to the server\")\n\t}\n}","line":{"from":339,"to":404}} {"id":100019296,"name":"WithDeprecatedPasswordFlag","signature":"func (f *ConfigFlags) WithDeprecatedPasswordFlag() *ConfigFlags","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go","code":"// WithDeprecatedPasswordFlag enables the username and password config flags\nfunc (f *ConfigFlags) WithDeprecatedPasswordFlag() *ConfigFlags {\n\tf.Username = utilpointer.String(\"\")\n\tf.Password = utilpointer.String(\"\")\n\treturn f\n}","line":{"from":406,"to":411}} {"id":100019297,"name":"WithDiscoveryBurst","signature":"func (f *ConfigFlags) WithDiscoveryBurst(discoveryBurst int) *ConfigFlags","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go","code":"// WithDiscoveryBurst sets the RESTClient burst for discovery.\nfunc (f *ConfigFlags) WithDiscoveryBurst(discoveryBurst int) *ConfigFlags {\n\tf.discoveryBurst = discoveryBurst\n\treturn f\n}","line":{"from":413,"to":417}} {"id":100019298,"name":"WithDiscoveryQPS","signature":"func (f *ConfigFlags) WithDiscoveryQPS(discoveryQPS float32) *ConfigFlags","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go","code":"// WithDiscoveryQPS sets the RESTClient QPS for discovery.\nfunc (f *ConfigFlags) WithDiscoveryQPS(discoveryQPS float32) *ConfigFlags {\n\tf.discoveryQPS = discoveryQPS\n\treturn f\n}","line":{"from":419,"to":423}} {"id":100019299,"name":"WithWrapConfigFn","signature":"func (f *ConfigFlags) WithWrapConfigFn(wrapConfigFn func(*rest.Config) *rest.Config) *ConfigFlags","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go","code":"// WithWrapConfigFn allows providing a wrapper function for the client Config.\nfunc (f *ConfigFlags) WithWrapConfigFn(wrapConfigFn func(*rest.Config) *rest.Config) *ConfigFlags {\n\tf.WrapConfigFn = wrapConfigFn\n\treturn f\n}","line":{"from":425,"to":429}} {"id":100019300,"name":"NewConfigFlags","signature":"func NewConfigFlags(usePersistentConfig bool) *ConfigFlags","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go","code":"// NewConfigFlags returns ConfigFlags with default values set\nfunc NewConfigFlags(usePersistentConfig bool) *ConfigFlags {\n\timpersonateGroup := []string{}\n\tinsecure := false\n\tdisableCompression := false\n\n\treturn \u0026ConfigFlags{\n\t\tInsecure: \u0026insecure,\n\t\tTimeout: utilpointer.String(\"0\"),\n\t\tKubeConfig: utilpointer.String(\"\"),\n\n\t\tCacheDir: utilpointer.String(getDefaultCacheDir()),\n\t\tClusterName: utilpointer.String(\"\"),\n\t\tAuthInfoName: utilpointer.String(\"\"),\n\t\tContext: utilpointer.String(\"\"),\n\t\tNamespace: utilpointer.String(\"\"),\n\t\tAPIServer: utilpointer.String(\"\"),\n\t\tTLSServerName: utilpointer.String(\"\"),\n\t\tCertFile: utilpointer.String(\"\"),\n\t\tKeyFile: utilpointer.String(\"\"),\n\t\tCAFile: utilpointer.String(\"\"),\n\t\tBearerToken: utilpointer.String(\"\"),\n\t\tImpersonate: utilpointer.String(\"\"),\n\t\tImpersonateUID: utilpointer.String(\"\"),\n\t\tImpersonateGroup: \u0026impersonateGroup,\n\t\tDisableCompression: \u0026disableCompression,\n\n\t\tusePersistentConfig: usePersistentConfig,\n\t\t// The more groups you have, the more discovery requests you need to make.\n\t\t// with a burst of 300, we will not be rate-limiting for most clusters but\n\t\t// the safeguard will still be here. This config is only used for discovery.\n\t\tdiscoveryBurst: 300,\n\t}\n}","line":{"from":431,"to":464}} {"id":100019301,"name":"computeDiscoverCacheDir","signature":"func computeDiscoverCacheDir(parentDir, host string) string","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go","code":"// computeDiscoverCacheDir takes the parentDir and the host and comes up with a \"usually non-colliding\" name.\nfunc computeDiscoverCacheDir(parentDir, host string) string {\n\t// strip the optional scheme from host if its there:\n\tschemelessHost := strings.Replace(strings.Replace(host, \"https://\", \"\", 1), \"http://\", \"\", 1)\n\t// now do a simple collapse of non-AZ09 characters. Collisions are possible but unlikely. Even if we do collide the problem is short lived\n\tsafeHost := overlyCautiousIllegalFileCharacters.ReplaceAllString(schemelessHost, \"_\")\n\treturn filepath.Join(parentDir, safeHost)\n}","line":{"from":469,"to":476}} {"id":100019302,"name":"ToOptions","signature":"func (o *FileNameFlags) ToOptions() resource.FilenameOptions","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/filename_flags.go","code":"// ToOptions creates a new FileNameOptions struct and sets FilenameOptions based on FileNameflags\nfunc (o *FileNameFlags) ToOptions() resource.FilenameOptions {\n\toptions := resource.FilenameOptions{}\n\n\tif o == nil {\n\t\treturn options\n\t}\n\n\tif o.Recursive != nil {\n\t\toptions.Recursive = *o.Recursive\n\t}\n\tif o.Filenames != nil {\n\t\toptions.Filenames = *o.Filenames\n\t}\n\tif o.Kustomize != nil {\n\t\toptions.Kustomize = *o.Kustomize\n\t}\n\n\treturn options\n}","line":{"from":40,"to":59}} {"id":100019303,"name":"AddFlags","signature":"func (o *FileNameFlags) AddFlags(flags *pflag.FlagSet)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/filename_flags.go","code":"// AddFlags binds file name flags to a given flagset\nfunc (o *FileNameFlags) AddFlags(flags *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tif o.Recursive != nil {\n\t\tflags.BoolVarP(o.Recursive, \"recursive\", \"R\", *o.Recursive, \"Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.\")\n\t}\n\tif o.Filenames != nil {\n\t\tflags.StringSliceVarP(o.Filenames, \"filename\", \"f\", *o.Filenames, o.Usage)\n\t\tannotations := make([]string, 0, len(resource.FileExtensions))\n\t\tfor _, ext := range resource.FileExtensions {\n\t\t\tannotations = append(annotations, strings.TrimLeft(ext, \".\"))\n\t\t}\n\t\tflags.SetAnnotation(\"filename\", cobra.BashCompFilenameExt, annotations)\n\t}\n\tif o.Kustomize != nil {\n\t\tflags.StringVarP(o.Kustomize, \"kustomize\", \"k\", *o.Kustomize,\n\t\t\t\"Process a kustomization directory. This flag can't be used together with -f or -R.\")\n\t}\n}","line":{"from":61,"to":82}} {"id":100019304,"name":"NewTestIOStreams","signature":"func NewTestIOStreams() (IOStreams, *bytes.Buffer, *bytes.Buffer, *bytes.Buffer)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/io_options.go","code":"// NewTestIOStreams returns a valid IOStreams and in, out, errout buffers for unit tests\nfunc NewTestIOStreams() (IOStreams, *bytes.Buffer, *bytes.Buffer, *bytes.Buffer) {\n\tin := \u0026bytes.Buffer{}\n\tout := \u0026bytes.Buffer{}\n\terrOut := \u0026bytes.Buffer{}\n\n\treturn IOStreams{\n\t\tIn: in,\n\t\tOut: out,\n\t\tErrOut: errOut,\n\t}, in, out, errOut\n}","line":{"from":36,"to":47}} {"id":100019305,"name":"NewTestIOStreamsDiscard","signature":"func NewTestIOStreamsDiscard() IOStreams","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/io_options.go","code":"// NewTestIOStreamsDiscard returns a valid IOStreams that just discards\nfunc NewTestIOStreamsDiscard() IOStreams {\n\tin := \u0026bytes.Buffer{}\n\treturn IOStreams{\n\t\tIn: in,\n\t\tOut: ioutil.Discard,\n\t\tErrOut: ioutil.Discard,\n\t}\n}","line":{"from":49,"to":57}} {"id":100019306,"name":"AllowedFormats","signature":"func (f *JSONYamlPrintFlags) AllowedFormats() []string","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/json_yaml_flags.go","code":"// AllowedFormats returns slice of string of allowed JSONYaml printing format\nfunc (f *JSONYamlPrintFlags) AllowedFormats() []string {\n\tif f == nil {\n\t\treturn []string{}\n\t}\n\treturn []string{\"json\", \"yaml\"}\n}","line":{"from":27,"to":33}} {"id":100019307,"name":"ToPrinter","signature":"func (f *JSONYamlPrintFlags) ToPrinter(outputFormat string) (printers.ResourcePrinter, error)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/json_yaml_flags.go","code":"// ToPrinter receives an outputFormat and returns a printer capable of\n// handling --output=(yaml|json) printing.\n// Returns false if the specified outputFormat does not match a supported format.\n// Supported Format types can be found in pkg/printers/printers.go\nfunc (f *JSONYamlPrintFlags) ToPrinter(outputFormat string) (printers.ResourcePrinter, error) {\n\tvar printer printers.ResourcePrinter\n\n\toutputFormat = strings.ToLower(outputFormat)\n\tswitch outputFormat {\n\tcase \"json\":\n\t\tprinter = \u0026printers.JSONPrinter{}\n\tcase \"yaml\":\n\t\tprinter = \u0026printers.YAMLPrinter{}\n\tdefault:\n\t\treturn nil, NoCompatiblePrinterError{OutputFormat: \u0026outputFormat, AllowedFormats: f.AllowedFormats()}\n\t}\n\n\tif !f.ShowManagedFields {\n\t\tprinter = \u0026printers.OmitManagedFieldsPrinter{Delegate: printer}\n\t}\n\treturn printer, nil\n}","line":{"from":42,"to":63}} {"id":100019308,"name":"AddFlags","signature":"func (f *JSONYamlPrintFlags) AddFlags(c *cobra.Command)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/json_yaml_flags.go","code":"// AddFlags receives a *cobra.Command reference and binds\n// flags related to JSON or Yaml printing to it\nfunc (f *JSONYamlPrintFlags) AddFlags(c *cobra.Command) {\n\tif f == nil {\n\t\treturn\n\t}\n\n\tc.Flags().BoolVar(\u0026f.ShowManagedFields, \"show-managed-fields\", f.ShowManagedFields, \"If true, keep the managedFields when printing objects in JSON or YAML format.\")\n}","line":{"from":65,"to":73}} {"id":100019309,"name":"NewJSONYamlPrintFlags","signature":"func NewJSONYamlPrintFlags() *JSONYamlPrintFlags","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/json_yaml_flags.go","code":"// NewJSONYamlPrintFlags returns flags associated with\n// yaml or json printing, with default values set.\nfunc NewJSONYamlPrintFlags() *JSONYamlPrintFlags {\n\treturn \u0026JSONYamlPrintFlags{}\n}","line":{"from":75,"to":79}} {"id":100019310,"name":"AllowedFormats","signature":"func (f *JSONPathPrintFlags) AllowedFormats() []string","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/jsonpath_flags.go","code":"// AllowedFormats returns slice of string of allowed JSONPath printing format\nfunc (f *JSONPathPrintFlags) AllowedFormats() []string {\n\tformats := make([]string, 0, len(jsonFormats))\n\tfor format := range jsonFormats {\n\t\tformats = append(formats, format)\n\t}\n\tsort.Strings(formats)\n\treturn formats\n}","line":{"from":49,"to":57}} {"id":100019311,"name":"ToPrinter","signature":"func (f *JSONPathPrintFlags) ToPrinter(templateFormat string) (printers.ResourcePrinter, error)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/jsonpath_flags.go","code":"// ToPrinter receives an templateFormat and returns a printer capable of\n// handling --template format printing.\n// Returns false if the specified templateFormat does not match a template format.\nfunc (f *JSONPathPrintFlags) ToPrinter(templateFormat string) (printers.ResourcePrinter, error) {\n\tif (f.TemplateArgument == nil || len(*f.TemplateArgument) == 0) \u0026\u0026 len(templateFormat) == 0 {\n\t\treturn nil, NoCompatiblePrinterError{Options: f, OutputFormat: \u0026templateFormat}\n\t}\n\n\ttemplateValue := \"\"\n\n\tif f.TemplateArgument == nil || len(*f.TemplateArgument) == 0 {\n\t\tfor format := range jsonFormats {\n\t\t\tformat = format + \"=\"\n\t\t\tif strings.HasPrefix(templateFormat, format) {\n\t\t\t\ttemplateValue = templateFormat[len(format):]\n\t\t\t\ttemplateFormat = format[:len(format)-1]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t} else {\n\t\ttemplateValue = *f.TemplateArgument\n\t}\n\n\tif _, supportedFormat := jsonFormats[templateFormat]; !supportedFormat {\n\t\treturn nil, NoCompatiblePrinterError{OutputFormat: \u0026templateFormat, AllowedFormats: f.AllowedFormats()}\n\t}\n\n\tif len(templateValue) == 0 {\n\t\treturn nil, fmt.Errorf(\"template format specified but no template given\")\n\t}\n\n\tif templateFormat == \"jsonpath-file\" {\n\t\tdata, err := ioutil.ReadFile(templateValue)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error reading --template %s, %v\", templateValue, err)\n\t\t}\n\n\t\ttemplateValue = string(data)\n\t}\n\n\tp, err := printers.NewJSONPathPrinter(templateValue)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing jsonpath %s, %v\", templateValue, err)\n\t}\n\n\tallowMissingKeys := true\n\tif f.AllowMissingKeys != nil {\n\t\tallowMissingKeys = *f.AllowMissingKeys\n\t}\n\n\tp.AllowMissingKeys(allowMissingKeys)\n\n\tif templateFormat == \"jsonpath-as-json\" {\n\t\tp.EnableJSONOutput(true)\n\t}\n\n\treturn p, nil\n}","line":{"from":59,"to":116}} {"id":100019312,"name":"AddFlags","signature":"func (f *JSONPathPrintFlags) AddFlags(c *cobra.Command)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/jsonpath_flags.go","code":"// AddFlags receives a *cobra.Command reference and binds\n// flags related to template printing to it\nfunc (f *JSONPathPrintFlags) AddFlags(c *cobra.Command) {\n\tif f.TemplateArgument != nil {\n\t\tc.Flags().StringVar(f.TemplateArgument, \"template\", *f.TemplateArgument, \"Template string or path to template file to use when --output=jsonpath, --output=jsonpath-file.\")\n\t\tc.MarkFlagFilename(\"template\")\n\t}\n\tif f.AllowMissingKeys != nil {\n\t\tc.Flags().BoolVar(f.AllowMissingKeys, \"allow-missing-template-keys\", *f.AllowMissingKeys, \"If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.\")\n\t}\n}","line":{"from":118,"to":128}} {"id":100019313,"name":"NewJSONPathPrintFlags","signature":"func NewJSONPathPrintFlags(templateValue string, allowMissingKeys bool) *JSONPathPrintFlags","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/jsonpath_flags.go","code":"// NewJSONPathPrintFlags returns flags associated with\n// --template printing, with default values set.\nfunc NewJSONPathPrintFlags(templateValue string, allowMissingKeys bool) *JSONPathPrintFlags {\n\treturn \u0026JSONPathPrintFlags{\n\t\tTemplateArgument: \u0026templateValue,\n\t\tAllowMissingKeys: \u0026allowMissingKeys,\n\t}\n}","line":{"from":130,"to":137}} {"id":100019314,"name":"AllowedFormats","signature":"func (f *KubeTemplatePrintFlags) AllowedFormats() []string","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/kube_template_flags.go","code":"// AllowedFormats returns slice of string of allowed GoTemplete and JSONPathPrint printing formats\nfunc (f *KubeTemplatePrintFlags) AllowedFormats() []string {\n\tif f == nil {\n\t\treturn []string{}\n\t}\n\treturn append(f.GoTemplatePrintFlags.AllowedFormats(), f.JSONPathPrintFlags.AllowedFormats()...)\n}","line":{"from":36,"to":42}} {"id":100019315,"name":"ToPrinter","signature":"func (f *KubeTemplatePrintFlags) ToPrinter(outputFormat string) (printers.ResourcePrinter, error)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/kube_template_flags.go","code":"// ToPrinter receives an outputFormat and returns a printer capable of\n// handling --template printing.\n// Returns false if the specified outputFormat does not match a supported format.\n// Supported Format types can be found in pkg/printers/printers.go\nfunc (f *KubeTemplatePrintFlags) ToPrinter(outputFormat string) (printers.ResourcePrinter, error) {\n\tif f == nil {\n\t\treturn nil, NoCompatiblePrinterError{}\n\t}\n\n\tif p, err := f.JSONPathPrintFlags.ToPrinter(outputFormat); !IsNoCompatiblePrinterError(err) {\n\t\treturn p, err\n\t}\n\treturn f.GoTemplatePrintFlags.ToPrinter(outputFormat)\n}","line":{"from":44,"to":57}} {"id":100019316,"name":"AddFlags","signature":"func (f *KubeTemplatePrintFlags) AddFlags(c *cobra.Command)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/kube_template_flags.go","code":"// AddFlags receives a *cobra.Command reference and binds\n// flags related to template printing to it\nfunc (f *KubeTemplatePrintFlags) AddFlags(c *cobra.Command) {\n\tif f == nil {\n\t\treturn\n\t}\n\n\tif f.TemplateArgument != nil {\n\t\tc.Flags().StringVar(f.TemplateArgument, \"template\", *f.TemplateArgument, \"Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].\")\n\t\tc.MarkFlagFilename(\"template\")\n\t}\n\tif f.AllowMissingKeys != nil {\n\t\tc.Flags().BoolVar(f.AllowMissingKeys, \"allow-missing-template-keys\", *f.AllowMissingKeys, \"If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.\")\n\t}\n}","line":{"from":59,"to":73}} {"id":100019317,"name":"NewKubeTemplatePrintFlags","signature":"func NewKubeTemplatePrintFlags() *KubeTemplatePrintFlags","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/kube_template_flags.go","code":"// NewKubeTemplatePrintFlags returns flags associated with\n// --template printing, with default values set.\nfunc NewKubeTemplatePrintFlags() *KubeTemplatePrintFlags {\n\tallowMissingKeysPtr := true\n\ttemplateArgPtr := \"\"\n\n\treturn \u0026KubeTemplatePrintFlags{\n\t\tGoTemplatePrintFlags: \u0026GoTemplatePrintFlags{\n\t\t\tTemplateArgument: \u0026templateArgPtr,\n\t\t\tAllowMissingKeys: \u0026allowMissingKeysPtr,\n\t\t},\n\t\tJSONPathPrintFlags: \u0026JSONPathPrintFlags{\n\t\t\tTemplateArgument: \u0026templateArgPtr,\n\t\t\tAllowMissingKeys: \u0026allowMissingKeysPtr,\n\t\t},\n\n\t\tTemplateArgument: \u0026templateArgPtr,\n\t\tAllowMissingKeys: \u0026allowMissingKeysPtr,\n\t}\n}","line":{"from":75,"to":94}} {"id":100019318,"name":"Complete","signature":"func (f *NamePrintFlags) Complete(successTemplate string) error","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/name_flags.go","code":"// Complete sets NamePrintFlags operation flag from successTemplate\nfunc (f *NamePrintFlags) Complete(successTemplate string) error {\n\tf.Operation = fmt.Sprintf(successTemplate, f.Operation)\n\treturn nil\n}","line":{"from":38,"to":42}} {"id":100019319,"name":"AllowedFormats","signature":"func (f *NamePrintFlags) AllowedFormats() []string","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/name_flags.go","code":"// AllowedFormats returns slice of string of allowed Name printing format\nfunc (f *NamePrintFlags) AllowedFormats() []string {\n\tif f == nil {\n\t\treturn []string{}\n\t}\n\treturn []string{\"name\"}\n}","line":{"from":44,"to":50}} {"id":100019320,"name":"ToPrinter","signature":"func (f *NamePrintFlags) ToPrinter(outputFormat string) (printers.ResourcePrinter, error)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/name_flags.go","code":"// ToPrinter receives an outputFormat and returns a printer capable of\n// handling --output=name printing.\n// Returns false if the specified outputFormat does not match a supported format.\n// Supported format types can be found in pkg/printers/printers.go\nfunc (f *NamePrintFlags) ToPrinter(outputFormat string) (printers.ResourcePrinter, error) {\n\tnamePrinter := \u0026printers.NamePrinter{\n\t\tOperation: f.Operation,\n\t}\n\n\toutputFormat = strings.ToLower(outputFormat)\n\tswitch outputFormat {\n\tcase \"name\":\n\t\tnamePrinter.ShortOutput = true\n\t\tfallthrough\n\tcase \"\":\n\t\treturn namePrinter, nil\n\tdefault:\n\t\treturn nil, NoCompatiblePrinterError{OutputFormat: \u0026outputFormat, AllowedFormats: f.AllowedFormats()}\n\t}\n}","line":{"from":52,"to":71}} {"id":100019321,"name":"AddFlags","signature":"func (f *NamePrintFlags) AddFlags(c *cobra.Command) {}","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/name_flags.go","code":"// AddFlags receives a *cobra.Command reference and binds\n// flags related to name printing to it\nfunc (f *NamePrintFlags) AddFlags(c *cobra.Command) {}","line":{"from":73,"to":75}} {"id":100019322,"name":"NewNamePrintFlags","signature":"func NewNamePrintFlags(operation string) *NamePrintFlags","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/name_flags.go","code":"// NewNamePrintFlags returns flags associated with\n// --name printing, with default values set.\nfunc NewNamePrintFlags(operation string) *NamePrintFlags {\n\treturn \u0026NamePrintFlags{\n\t\tOperation: operation,\n\t}\n}","line":{"from":77,"to":83}} {"id":100019323,"name":"Error","signature":"func (e NoCompatiblePrinterError) Error() string","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/print_flags.go","code":"func (e NoCompatiblePrinterError) Error() string {\n\toutput := \"\"\n\tif e.OutputFormat != nil {\n\t\toutput = *e.OutputFormat\n\t}\n\n\tsort.Strings(e.AllowedFormats)\n\treturn fmt.Sprintf(\"unable to match a printer suitable for the output format %q, allowed formats are: %s\", output, strings.Join(e.AllowedFormats, \",\"))\n}","line":{"from":38,"to":46}} {"id":100019324,"name":"IsNoCompatiblePrinterError","signature":"func IsNoCompatiblePrinterError(err error) bool","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/print_flags.go","code":"// IsNoCompatiblePrinterError returns true if it is a not a compatible printer\n// otherwise it will return false\nfunc IsNoCompatiblePrinterError(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\n\t_, ok := err.(NoCompatiblePrinterError)\n\treturn ok\n}","line":{"from":48,"to":57}} {"id":100019325,"name":"Complete","signature":"func (f *PrintFlags) Complete(successTemplate string) error","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/print_flags.go","code":"// Complete sets NamePrintFlags operation flag from successTemplate\nfunc (f *PrintFlags) Complete(successTemplate string) error {\n\treturn f.NamePrintFlags.Complete(successTemplate)\n}","line":{"from":76,"to":79}} {"id":100019326,"name":"AllowedFormats","signature":"func (f *PrintFlags) AllowedFormats() []string","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/print_flags.go","code":"// AllowedFormats returns slice of string of allowed JSONYaml/Name/Template printing format\nfunc (f *PrintFlags) AllowedFormats() []string {\n\tret := []string{}\n\tret = append(ret, f.JSONYamlPrintFlags.AllowedFormats()...)\n\tret = append(ret, f.NamePrintFlags.AllowedFormats()...)\n\tret = append(ret, f.TemplatePrinterFlags.AllowedFormats()...)\n\treturn ret\n}","line":{"from":81,"to":88}} {"id":100019327,"name":"ToPrinter","signature":"func (f *PrintFlags) ToPrinter() (printers.ResourcePrinter, error)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/print_flags.go","code":"// ToPrinter returns a printer capable of\n// handling --output or --template printing.\n// Returns false if the specified outputFormat does not match a supported format.\n// Supported format types can be found in pkg/printers/printers.go\nfunc (f *PrintFlags) ToPrinter() (printers.ResourcePrinter, error) {\n\toutputFormat := \"\"\n\tif f.OutputFormat != nil {\n\t\toutputFormat = *f.OutputFormat\n\t}\n\t// For backwards compatibility we want to support a --template argument given, even when no --output format is provided.\n\t// If no explicit output format has been provided via the --output flag, fallback\n\t// to honoring the --template argument.\n\ttemplateFlagSpecified := f.TemplatePrinterFlags != nil \u0026\u0026\n\t\tf.TemplatePrinterFlags.TemplateArgument != nil \u0026\u0026\n\t\tlen(*f.TemplatePrinterFlags.TemplateArgument) \u003e 0\n\toutputFlagSpecified := f.OutputFlagSpecified != nil \u0026\u0026 f.OutputFlagSpecified()\n\tif templateFlagSpecified \u0026\u0026 !outputFlagSpecified {\n\t\toutputFormat = \"go-template\"\n\t}\n\n\tif f.JSONYamlPrintFlags != nil {\n\t\tif p, err := f.JSONYamlPrintFlags.ToPrinter(outputFormat); !IsNoCompatiblePrinterError(err) {\n\t\t\treturn f.TypeSetterPrinter.WrapToPrinter(p, err)\n\t\t}\n\t}\n\n\tif f.NamePrintFlags != nil {\n\t\tif p, err := f.NamePrintFlags.ToPrinter(outputFormat); !IsNoCompatiblePrinterError(err) {\n\t\t\treturn f.TypeSetterPrinter.WrapToPrinter(p, err)\n\t\t}\n\t}\n\n\tif f.TemplatePrinterFlags != nil {\n\t\tif p, err := f.TemplatePrinterFlags.ToPrinter(outputFormat); !IsNoCompatiblePrinterError(err) {\n\t\t\treturn f.TypeSetterPrinter.WrapToPrinter(p, err)\n\t\t}\n\t}\n\n\treturn nil, NoCompatiblePrinterError{OutputFormat: f.OutputFormat, AllowedFormats: f.AllowedFormats()}\n}","line":{"from":90,"to":129}} {"id":100019328,"name":"AddFlags","signature":"func (f *PrintFlags) AddFlags(cmd *cobra.Command)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/print_flags.go","code":"// AddFlags receives a *cobra.Command reference and binds\n// flags related to JSON/Yaml/Name/Template printing to it\nfunc (f *PrintFlags) AddFlags(cmd *cobra.Command) {\n\tf.JSONYamlPrintFlags.AddFlags(cmd)\n\tf.NamePrintFlags.AddFlags(cmd)\n\tf.TemplatePrinterFlags.AddFlags(cmd)\n\n\tif f.OutputFormat != nil {\n\t\tcmd.Flags().StringVarP(f.OutputFormat, \"output\", \"o\", *f.OutputFormat, fmt.Sprintf(`Output format. One of: (%s).`, strings.Join(f.AllowedFormats(), \", \")))\n\t\tif f.OutputFlagSpecified == nil {\n\t\t\tf.OutputFlagSpecified = func() bool {\n\t\t\t\treturn cmd.Flag(\"output\").Changed\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":131,"to":146}} {"id":100019329,"name":"WithDefaultOutput","signature":"func (f *PrintFlags) WithDefaultOutput(output string) *PrintFlags","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/print_flags.go","code":"// WithDefaultOutput sets a default output format if one is not provided through a flag value\nfunc (f *PrintFlags) WithDefaultOutput(output string) *PrintFlags {\n\tf.OutputFormat = \u0026output\n\treturn f\n}","line":{"from":148,"to":152}} {"id":100019330,"name":"WithTypeSetter","signature":"func (f *PrintFlags) WithTypeSetter(scheme *runtime.Scheme) *PrintFlags","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/print_flags.go","code":"// WithTypeSetter sets a wrapper than will surround the returned printer with a printer to type resources\nfunc (f *PrintFlags) WithTypeSetter(scheme *runtime.Scheme) *PrintFlags {\n\tf.TypeSetterPrinter = printers.NewTypeSetter(scheme)\n\treturn f\n}","line":{"from":154,"to":158}} {"id":100019331,"name":"NewPrintFlags","signature":"func NewPrintFlags(operation string) *PrintFlags","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/print_flags.go","code":"// NewPrintFlags returns a default *PrintFlags\nfunc NewPrintFlags(operation string) *PrintFlags {\n\toutputFormat := \"\"\n\n\treturn \u0026PrintFlags{\n\t\tOutputFormat: \u0026outputFormat,\n\n\t\tJSONYamlPrintFlags: NewJSONYamlPrintFlags(),\n\t\tNamePrintFlags: NewNamePrintFlags(operation),\n\t\tTemplatePrinterFlags: NewKubeTemplatePrintFlags(),\n\t}\n}","line":{"from":160,"to":171}} {"id":100019332,"name":"ToRecorder","signature":"func (f *RecordFlags) ToRecorder() (Recorder, error)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/record_flags.go","code":"// ToRecorder returns a ChangeCause recorder if --record=false was not\n// explicitly given by the user\nfunc (f *RecordFlags) ToRecorder() (Recorder, error) {\n\tif f == nil {\n\t\treturn NoopRecorder{}, nil\n\t}\n\n\tshouldRecord := false\n\tif f.Record != nil {\n\t\tshouldRecord = *f.Record\n\t}\n\n\t// if flag was explicitly set to false by the user,\n\t// do not record\n\tif !shouldRecord {\n\t\treturn NoopRecorder{}, nil\n\t}\n\n\treturn \u0026ChangeCauseRecorder{\n\t\tchangeCause: f.changeCause,\n\t}, nil\n}","line":{"from":44,"to":65}} {"id":100019333,"name":"Complete","signature":"func (f *RecordFlags) Complete(cmd *cobra.Command) error","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/record_flags.go","code":"// Complete is called before the command is run, but after it is invoked to finish the state of the struct before use.\nfunc (f *RecordFlags) Complete(cmd *cobra.Command) error {\n\tif f == nil {\n\t\treturn nil\n\t}\n\n\tf.changeCause = parseCommandArguments(cmd)\n\treturn nil\n}","line":{"from":67,"to":75}} {"id":100019334,"name":"CompleteWithChangeCause","signature":"func (f *RecordFlags) CompleteWithChangeCause(cause string) error","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/record_flags.go","code":"// CompleteWithChangeCause alters changeCause value with a new cause\nfunc (f *RecordFlags) CompleteWithChangeCause(cause string) error {\n\tif f == nil {\n\t\treturn nil\n\t}\n\n\tf.changeCause = cause\n\treturn nil\n}","line":{"from":77,"to":85}} {"id":100019335,"name":"AddFlags","signature":"func (f *RecordFlags) AddFlags(cmd *cobra.Command)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/record_flags.go","code":"// AddFlags binds the requested flags to the provided flagset\n// TODO have this only take a flagset\nfunc (f *RecordFlags) AddFlags(cmd *cobra.Command) {\n\tif f == nil {\n\t\treturn\n\t}\n\n\tif f.Record != nil {\n\t\tcmd.Flags().BoolVar(f.Record, \"record\", *f.Record, \"Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists.\")\n\t\tcmd.Flags().MarkDeprecated(\"record\", \"--record will be removed in the future\")\n\t}\n}","line":{"from":87,"to":98}} {"id":100019336,"name":"NewRecordFlags","signature":"func NewRecordFlags() *RecordFlags","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/record_flags.go","code":"// NewRecordFlags provides a RecordFlags with reasonable default values set for use\nfunc NewRecordFlags() *RecordFlags {\n\trecord := false\n\n\treturn \u0026RecordFlags{\n\t\tRecord: \u0026record,\n\t}\n}","line":{"from":100,"to":107}} {"id":100019337,"name":"Record","signature":"func (r NoopRecorder) Record(obj runtime.Object) error","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/record_flags.go","code":"// Record implements Recorder\nfunc (r NoopRecorder) Record(obj runtime.Object) error {\n\treturn nil\n}","line":{"from":119,"to":122}} {"id":100019338,"name":"MakeRecordMergePatch","signature":"func (r NoopRecorder) MakeRecordMergePatch(obj runtime.Object) ([]byte, error)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/record_flags.go","code":"// MakeRecordMergePatch implements Recorder\nfunc (r NoopRecorder) MakeRecordMergePatch(obj runtime.Object) ([]byte, error) {\n\treturn nil, nil\n}","line":{"from":124,"to":127}} {"id":100019339,"name":"Record","signature":"func (r *ChangeCauseRecorder) Record(obj runtime.Object) error","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/record_flags.go","code":"// Record annotates a \"change-cause\" to a given info if either \"shouldRecord\" is true,\n// or the resource info previously contained a \"change-cause\" annotation.\nfunc (r *ChangeCauseRecorder) Record(obj runtime.Object) error {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\tannotations := accessor.GetAnnotations()\n\tif annotations == nil {\n\t\tannotations = make(map[string]string)\n\t}\n\tannotations[ChangeCauseAnnotation] = r.changeCause\n\taccessor.SetAnnotations(annotations)\n\treturn nil\n}","line":{"from":134,"to":148}} {"id":100019340,"name":"MakeRecordMergePatch","signature":"func (r *ChangeCauseRecorder) MakeRecordMergePatch(obj runtime.Object) ([]byte, error)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/record_flags.go","code":"// MakeRecordMergePatch produces a merge patch for updating the recording annotation.\nfunc (r *ChangeCauseRecorder) MakeRecordMergePatch(obj runtime.Object) ([]byte, error) {\n\t// copy so we don't mess with the original\n\tobjCopy := obj.DeepCopyObject()\n\tif err := r.Record(objCopy); err != nil {\n\t\treturn nil, err\n\t}\n\n\toldData, err := json.Marshal(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnewData, err := json.Marshal(objCopy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn jsonpatch.CreateMergePatch(oldData, newData)\n}","line":{"from":150,"to":168}} {"id":100019341,"name":"parseCommandArguments","signature":"func parseCommandArguments(cmd *cobra.Command) string","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/record_flags.go","code":"// parseCommandArguments will stringify and return all environment arguments ie. a command run by a client\n// using the factory.\n// Set showSecrets false to filter out stuff like secrets.\nfunc parseCommandArguments(cmd *cobra.Command) string {\n\tif len(os.Args) == 0 {\n\t\treturn \"\"\n\t}\n\n\tflags := \"\"\n\tparseFunc := func(flag *pflag.Flag, value string) error {\n\t\tflags = flags + \" --\" + flag.Name\n\t\tif set, ok := flag.Annotations[\"classified\"]; !ok || len(set) == 0 {\n\t\t\tflags = flags + \"=\" + value\n\t\t} else {\n\t\t\tflags = flags + \"=CLASSIFIED\"\n\t\t}\n\t\treturn nil\n\t}\n\tvar err error\n\terr = cmd.Flags().ParseAll(os.Args[1:], parseFunc)\n\tif err != nil || !cmd.Flags().Parsed() {\n\t\treturn \"\"\n\t}\n\n\targs := \"\"\n\tif arguments := cmd.Flags().Args(); len(arguments) \u003e 0 {\n\t\targs = \" \" + strings.Join(arguments, \" \")\n\t}\n\n\tbase := filepath.Base(os.Args[0])\n\treturn base + args + flags\n}","line":{"from":170,"to":201}} {"id":100019342,"name":"AllowedFormats","signature":"func (f *GoTemplatePrintFlags) AllowedFormats() []string","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/template_flags.go","code":"// AllowedFormats returns slice of string of allowed GoTemplatePrint printing format\nfunc (f *GoTemplatePrintFlags) AllowedFormats() []string {\n\tformats := make([]string, 0, len(templateFormats))\n\tfor format := range templateFormats {\n\t\tformats = append(formats, format)\n\t}\n\tsort.Strings(formats)\n\treturn formats\n}","line":{"from":50,"to":58}} {"id":100019343,"name":"ToPrinter","signature":"func (f *GoTemplatePrintFlags) ToPrinter(templateFormat string) (printers.ResourcePrinter, error)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/template_flags.go","code":"// ToPrinter receives an templateFormat and returns a printer capable of\n// handling --template format printing.\n// Returns false if the specified templateFormat does not match a template format.\nfunc (f *GoTemplatePrintFlags) ToPrinter(templateFormat string) (printers.ResourcePrinter, error) {\n\tif (f.TemplateArgument == nil || len(*f.TemplateArgument) == 0) \u0026\u0026 len(templateFormat) == 0 {\n\t\treturn nil, NoCompatiblePrinterError{Options: f, OutputFormat: \u0026templateFormat}\n\t}\n\n\ttemplateValue := \"\"\n\n\tif f.TemplateArgument == nil || len(*f.TemplateArgument) == 0 {\n\t\tfor format := range templateFormats {\n\t\t\tformat = format + \"=\"\n\t\t\tif strings.HasPrefix(templateFormat, format) {\n\t\t\t\ttemplateValue = templateFormat[len(format):]\n\t\t\t\ttemplateFormat = format[:len(format)-1]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t} else {\n\t\ttemplateValue = *f.TemplateArgument\n\t}\n\n\tif _, supportedFormat := templateFormats[templateFormat]; !supportedFormat {\n\t\treturn nil, NoCompatiblePrinterError{OutputFormat: \u0026templateFormat, AllowedFormats: f.AllowedFormats()}\n\t}\n\n\tif len(templateValue) == 0 {\n\t\treturn nil, fmt.Errorf(\"template format specified but no template given\")\n\t}\n\n\tif templateFormat == \"templatefile\" || templateFormat == \"go-template-file\" {\n\t\tdata, err := ioutil.ReadFile(templateValue)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error reading --template %s, %v\", templateValue, err)\n\t\t}\n\n\t\ttemplateValue = string(data)\n\t}\n\n\tp, err := printers.NewGoTemplatePrinter([]byte(templateValue))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing template %s, %v\", templateValue, err)\n\t}\n\n\tallowMissingKeys := true\n\tif f.AllowMissingKeys != nil {\n\t\tallowMissingKeys = *f.AllowMissingKeys\n\t}\n\n\tp.AllowMissingKeys(allowMissingKeys)\n\treturn p, nil\n}","line":{"from":60,"to":112}} {"id":100019344,"name":"AddFlags","signature":"func (f *GoTemplatePrintFlags) AddFlags(c *cobra.Command)","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/template_flags.go","code":"// AddFlags receives a *cobra.Command reference and binds\n// flags related to template printing to it\nfunc (f *GoTemplatePrintFlags) AddFlags(c *cobra.Command) {\n\tif f.TemplateArgument != nil {\n\t\tc.Flags().StringVar(f.TemplateArgument, \"template\", *f.TemplateArgument, \"Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].\")\n\t\tc.MarkFlagFilename(\"template\")\n\t}\n\tif f.AllowMissingKeys != nil {\n\t\tc.Flags().BoolVar(f.AllowMissingKeys, \"allow-missing-template-keys\", *f.AllowMissingKeys, \"If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.\")\n\t}\n}","line":{"from":114,"to":124}} {"id":100019345,"name":"NewGoTemplatePrintFlags","signature":"func NewGoTemplatePrintFlags() *GoTemplatePrintFlags","file":"staging/src/k8s.io/cli-runtime/pkg/genericclioptions/template_flags.go","code":"// NewGoTemplatePrintFlags returns flags associated with\n// --template printing, with default values set.\nfunc NewGoTemplatePrintFlags() *GoTemplatePrintFlags {\n\tallowMissingKeysPtr := true\n\ttemplateValuePtr := \"\"\n\n\treturn \u0026GoTemplatePrintFlags{\n\t\tTemplateArgument: \u0026templateValuePtr,\n\t\tAllowMissingKeys: \u0026allowMissingKeysPtr,\n\t}\n}","line":{"from":126,"to":136}} {"id":100019346,"name":"NewDiscardingPrinter","signature":"func NewDiscardingPrinter() ResourcePrinterFunc","file":"staging/src/k8s.io/cli-runtime/pkg/printers/discard.go","code":"// NewDiscardingPrinter is a printer that discards all objects\nfunc NewDiscardingPrinter() ResourcePrinterFunc {\n\treturn ResourcePrinterFunc(func(runtime.Object, io.Writer) error {\n\t\treturn nil\n\t})\n}","line":{"from":25,"to":30}} {"id":100019347,"name":"PrintObj","signature":"func (fn ResourcePrinterFunc) PrintObj(obj runtime.Object, w io.Writer) error","file":"staging/src/k8s.io/cli-runtime/pkg/printers/interface.go","code":"// PrintObj implements ResourcePrinter\nfunc (fn ResourcePrinterFunc) PrintObj(obj runtime.Object, w io.Writer) error {\n\treturn fn(obj, w)\n}","line":{"from":29,"to":32}} {"id":100019348,"name":"PrintObj","signature":"func (p *JSONPrinter) PrintObj(obj runtime.Object, w io.Writer) error","file":"staging/src/k8s.io/cli-runtime/pkg/printers/json.go","code":"// PrintObj is an implementation of ResourcePrinter.PrintObj which simply writes the object to the Writer.\nfunc (p *JSONPrinter) PrintObj(obj runtime.Object, w io.Writer) error {\n\t// we use reflect.Indirect here in order to obtain the actual value from a pointer.\n\t// we need an actual value in order to retrieve the package path for an object.\n\t// using reflect.Indirect indiscriminately is valid here, as all runtime.Objects are supposed to be pointers.\n\tif InternalObjectPreventer.IsForbidden(reflect.Indirect(reflect.ValueOf(obj)).Type().PkgPath()) {\n\t\treturn fmt.Errorf(InternalObjectPrinterErr)\n\t}\n\n\tswitch obj := obj.(type) {\n\tcase *metav1.WatchEvent:\n\t\tif InternalObjectPreventer.IsForbidden(reflect.Indirect(reflect.ValueOf(obj.Object.Object)).Type().PkgPath()) {\n\t\t\treturn fmt.Errorf(InternalObjectPrinterErr)\n\t\t}\n\t\tdata, err := json.Marshal(obj)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = w.Write(data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = w.Write([]byte{'\\n'})\n\t\treturn err\n\tcase *runtime.Unknown:\n\t\tvar buf bytes.Buffer\n\t\terr := json.Indent(\u0026buf, obj.Raw, \"\", \" \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tbuf.WriteRune('\\n')\n\t\t_, err = buf.WriteTo(w)\n\t\treturn err\n\t}\n\n\tif obj.GetObjectKind().GroupVersionKind().Empty() {\n\t\treturn fmt.Errorf(\"missing apiVersion or kind; try GetObjectKind().SetGroupVersionKind() if you know the type\")\n\t}\n\n\tdata, err := json.MarshalIndent(obj, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdata = append(data, '\\n')\n\t_, err = w.Write(data)\n\treturn err\n}","line":{"from":33,"to":79}} {"id":100019349,"name":"exists","signature":"func exists(item interface{}, indices ...interface{}) bool","file":"staging/src/k8s.io/cli-runtime/pkg/printers/jsonpath.go","code":"// exists returns true if it would be possible to call the index function\n// with these arguments.\n//\n// TODO: how to document this for users?\n//\n// index returns the result of indexing its first argument by the following\n// arguments. Thus \"index x 1 2 3\" is, in Go syntax, x[1][2][3]. Each\n// indexed item must be a map, slice, or array.\nfunc exists(item interface{}, indices ...interface{}) bool {\n\tv := reflect.ValueOf(item)\n\tfor _, i := range indices {\n\t\tindex := reflect.ValueOf(i)\n\t\tvar isNil bool\n\t\tif v, isNil = indirect(v); isNil {\n\t\t\treturn false\n\t\t}\n\t\tswitch v.Kind() {\n\t\tcase reflect.Array, reflect.Slice, reflect.String:\n\t\t\tvar x int64\n\t\t\tswitch index.Kind() {\n\t\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\t\t\tx = index.Int()\n\t\t\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:\n\t\t\t\tx = int64(index.Uint())\n\t\t\tdefault:\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif x \u003c 0 || x \u003e= int64(v.Len()) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tv = v.Index(int(x))\n\t\tcase reflect.Map:\n\t\t\tif !index.IsValid() {\n\t\t\t\tindex = reflect.Zero(v.Type().Key())\n\t\t\t}\n\t\t\tif !index.Type().AssignableTo(v.Type().Key()) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif x := v.MapIndex(index); x.IsValid() {\n\t\t\t\tv = x\n\t\t\t} else {\n\t\t\t\tv = reflect.Zero(v.Type().Elem())\n\t\t\t}\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\tif _, isNil := indirect(v); isNil {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":30,"to":81}} {"id":100019350,"name":"indirect","signature":"func indirect(v reflect.Value) (rv reflect.Value, isNil bool)","file":"staging/src/k8s.io/cli-runtime/pkg/printers/jsonpath.go","code":"// stolen from text/template\n// indirect returns the item at the end of indirection, and a bool to indicate if it's nil.\n// We indirect through pointers and empty interfaces (only) because\n// non-empty interfaces have methods we might need.\nfunc indirect(v reflect.Value) (rv reflect.Value, isNil bool) {\n\tfor ; v.Kind() == reflect.Pointer || v.Kind() == reflect.Interface; v = v.Elem() {\n\t\tif v.IsNil() {\n\t\t\treturn v, true\n\t\t}\n\t\tif v.Kind() == reflect.Interface \u0026\u0026 v.NumMethod() \u003e 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn v, false\n}","line":{"from":83,"to":97}} {"id":100019351,"name":"NewJSONPathPrinter","signature":"func NewJSONPathPrinter(tmpl string) (*JSONPathPrinter, error)","file":"staging/src/k8s.io/cli-runtime/pkg/printers/jsonpath.go","code":"func NewJSONPathPrinter(tmpl string) (*JSONPathPrinter, error) {\n\tj := jsonpath.New(\"out\")\n\tif err := j.Parse(tmpl); err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026JSONPathPrinter{\n\t\trawTemplate: tmpl,\n\t\tJSONPath: j,\n\t}, nil\n}","line":{"from":105,"to":114}} {"id":100019352,"name":"PrintObj","signature":"func (j *JSONPathPrinter) PrintObj(obj runtime.Object, w io.Writer) error","file":"staging/src/k8s.io/cli-runtime/pkg/printers/jsonpath.go","code":"// PrintObj formats the obj with the JSONPath Template.\nfunc (j *JSONPathPrinter) PrintObj(obj runtime.Object, w io.Writer) error {\n\t// we use reflect.Indirect here in order to obtain the actual value from a pointer.\n\t// we need an actual value in order to retrieve the package path for an object.\n\t// using reflect.Indirect indiscriminately is valid here, as all runtime.Objects are supposed to be pointers.\n\tif InternalObjectPreventer.IsForbidden(reflect.Indirect(reflect.ValueOf(obj)).Type().PkgPath()) {\n\t\treturn fmt.Errorf(InternalObjectPrinterErr)\n\t}\n\n\tvar queryObj interface{} = obj\n\tif unstructured, ok := obj.(runtime.Unstructured); ok {\n\t\tqueryObj = unstructured.UnstructuredContent()\n\t} else {\n\t\tdata, err := json.Marshal(obj)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tqueryObj = map[string]interface{}{}\n\t\tif err := json.Unmarshal(data, \u0026queryObj); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := j.JSONPath.Execute(w, queryObj); err != nil {\n\t\tbuf := bytes.NewBuffer(nil)\n\t\tfmt.Fprintf(buf, \"Error executing template: %v. Printing more information for debugging the template:\\n\", err)\n\t\tfmt.Fprintf(buf, \"\\ttemplate was:\\n\\t\\t%v\\n\", j.rawTemplate)\n\t\tfmt.Fprintf(buf, \"\\tobject given to jsonpath engine was:\\n\\t\\t%#v\\n\\n\", queryObj)\n\t\treturn fmt.Errorf(\"error executing jsonpath %q: %v\\n\", j.rawTemplate, buf.String())\n\t}\n\treturn nil\n}","line":{"from":116,"to":147}} {"id":100019353,"name":"omitManagedFields","signature":"func omitManagedFields(o runtime.Object) runtime.Object","file":"staging/src/k8s.io/cli-runtime/pkg/printers/managedfields.go","code":"func omitManagedFields(o runtime.Object) runtime.Object {\n\ta, err := meta.Accessor(o)\n\tif err != nil {\n\t\t// The object is not a `metav1.Object`, ignore it.\n\t\treturn o\n\t}\n\ta.SetManagedFields(nil)\n\treturn o\n}","line":{"from":34,"to":42}} {"id":100019354,"name":"PrintObj","signature":"func (p *OmitManagedFieldsPrinter) PrintObj(obj runtime.Object, w io.Writer) error","file":"staging/src/k8s.io/cli-runtime/pkg/printers/managedfields.go","code":"// PrintObj copies the object and omits the managed fields from the copied object before printing it.\nfunc (p *OmitManagedFieldsPrinter) PrintObj(obj runtime.Object, w io.Writer) error {\n\tif obj == nil {\n\t\treturn p.Delegate.PrintObj(obj, w)\n\t}\n\tif meta.IsListType(obj) {\n\t\tobj = obj.DeepCopyObject()\n\t\t_ = meta.EachListItem(obj, func(item runtime.Object) error {\n\t\t\tomitManagedFields(item)\n\t\t\treturn nil\n\t\t})\n\t} else if _, err := meta.Accessor(obj); err == nil {\n\t\tobj = omitManagedFields(obj.DeepCopyObject())\n\t}\n\treturn p.Delegate.PrintObj(obj, w)\n}","line":{"from":44,"to":59}} {"id":100019355,"name":"PrintObj","signature":"func (p *NamePrinter) PrintObj(obj runtime.Object, w io.Writer) error","file":"staging/src/k8s.io/cli-runtime/pkg/printers/name.go","code":"// PrintObj is an implementation of ResourcePrinter.PrintObj which decodes the object\n// and print \"resource/name\" pair. If the object is a List, print all items in it.\nfunc (p *NamePrinter) PrintObj(obj runtime.Object, w io.Writer) error {\n\tswitch castObj := obj.(type) {\n\tcase *metav1.WatchEvent:\n\t\tobj = castObj.Object.Object\n\t}\n\n\t// we use reflect.Indirect here in order to obtain the actual value from a pointer.\n\t// using reflect.Indirect indiscriminately is valid here, as all runtime.Objects are supposed to be pointers.\n\t// we need an actual value in order to retrieve the package path for an object.\n\tif InternalObjectPreventer.IsForbidden(reflect.Indirect(reflect.ValueOf(obj)).Type().PkgPath()) {\n\t\treturn fmt.Errorf(InternalObjectPrinterErr)\n\t}\n\n\tif meta.IsListType(obj) {\n\t\t// we allow unstructured lists for now because they always contain the GVK information. We should chase down\n\t\t// callers and stop them from passing unflattened lists\n\t\t// TODO chase the caller that is setting this and remove it.\n\t\tif _, ok := obj.(*unstructured.UnstructuredList); !ok {\n\t\t\treturn fmt.Errorf(\"list types are not supported by name printing: %T\", obj)\n\t\t}\n\n\t\titems, err := meta.ExtractList(obj)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, obj := range items {\n\t\t\tif err := p.PrintObj(obj, w); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\tif obj.GetObjectKind().GroupVersionKind().Empty() {\n\t\treturn fmt.Errorf(\"missing apiVersion or kind; try GetObjectKind().SetGroupVersionKind() if you know the type\")\n\t}\n\n\tname := \"\u003cunknown\u003e\"\n\tif acc, err := meta.Accessor(obj); err == nil {\n\t\tif n := acc.GetName(); len(n) \u003e 0 {\n\t\t\tname = n\n\t\t}\n\t}\n\n\treturn printObj(w, name, p.Operation, p.ShortOutput, GetObjectGroupKind(obj))\n}","line":{"from":43,"to":90}} {"id":100019356,"name":"GetObjectGroupKind","signature":"func GetObjectGroupKind(obj runtime.Object) schema.GroupKind","file":"staging/src/k8s.io/cli-runtime/pkg/printers/name.go","code":"func GetObjectGroupKind(obj runtime.Object) schema.GroupKind {\n\tif obj == nil {\n\t\treturn schema.GroupKind{Kind: \"\u003cunknown\u003e\"}\n\t}\n\tgroupVersionKind := obj.GetObjectKind().GroupVersionKind()\n\tif len(groupVersionKind.Kind) \u003e 0 {\n\t\treturn groupVersionKind.GroupKind()\n\t}\n\n\tif uns, ok := obj.(*unstructured.Unstructured); ok {\n\t\tif len(uns.GroupVersionKind().Kind) \u003e 0 {\n\t\t\treturn uns.GroupVersionKind().GroupKind()\n\t\t}\n\t}\n\n\treturn schema.GroupKind{Kind: \"\u003cunknown\u003e\"}\n}","line":{"from":92,"to":108}} {"id":100019357,"name":"printObj","signature":"func printObj(w io.Writer, name string, operation string, shortOutput bool, groupKind schema.GroupKind) error","file":"staging/src/k8s.io/cli-runtime/pkg/printers/name.go","code":"func printObj(w io.Writer, name string, operation string, shortOutput bool, groupKind schema.GroupKind) error {\n\tif len(groupKind.Kind) == 0 {\n\t\treturn fmt.Errorf(\"missing kind for resource with name %v\", name)\n\t}\n\n\tif len(operation) \u003e 0 {\n\t\toperation = \" \" + operation\n\t}\n\n\tif shortOutput {\n\t\toperation = \"\"\n\t}\n\n\tif len(groupKind.Group) == 0 {\n\t\tfmt.Fprintf(w, \"%s/%s%s\\n\", strings.ToLower(groupKind.Kind), name, operation)\n\t\treturn nil\n\t}\n\n\tfmt.Fprintf(w, \"%s.%s/%s%s\\n\", strings.ToLower(groupKind.Kind), groupKind.Group, name, operation)\n\treturn nil\n}","line":{"from":110,"to":130}} {"id":100019358,"name":"IsInternalObjectError","signature":"func IsInternalObjectError(err error) bool","file":"staging/src/k8s.io/cli-runtime/pkg/printers/sourcechecker.go","code":"func IsInternalObjectError(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\n\treturn err.Error() == InternalObjectPrinterErr\n}","line":{"from":35,"to":41}} {"id":100019359,"name":"IsForbidden","signature":"func (c *illegalPackageSourceChecker) IsForbidden(pkgPath string) bool","file":"staging/src/k8s.io/cli-runtime/pkg/printers/sourcechecker.go","code":"func (c *illegalPackageSourceChecker) IsForbidden(pkgPath string) bool {\n\tfor _, forbiddenPrefix := range c.disallowedPrefixes {\n\t\tif strings.HasPrefix(pkgPath, forbiddenPrefix) || strings.Contains(pkgPath, \"/vendor/\"+forbiddenPrefix) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":52,"to":60}} {"id":100019360,"name":"NewTablePrinter","signature":"func NewTablePrinter(options PrintOptions) ResourcePrinter","file":"staging/src/k8s.io/cli-runtime/pkg/printers/tableprinter.go","code":"// NewTablePrinter creates a printer suitable for calling PrintObj().\nfunc NewTablePrinter(options PrintOptions) ResourcePrinter {\n\tprinter := \u0026HumanReadablePrinter{\n\t\toptions: options,\n\t}\n\treturn printer\n}","line":{"from":79,"to":85}} {"id":100019361,"name":"printHeader","signature":"func printHeader(columnNames []string, w io.Writer) error","file":"staging/src/k8s.io/cli-runtime/pkg/printers/tableprinter.go","code":"func printHeader(columnNames []string, w io.Writer) error {\n\tif _, err := fmt.Fprintf(w, \"%s\\n\", strings.Join(columnNames, \"\\t\")); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":87,"to":92}} {"id":100019362,"name":"PrintObj","signature":"func (h *HumanReadablePrinter) PrintObj(obj runtime.Object, output io.Writer) error","file":"staging/src/k8s.io/cli-runtime/pkg/printers/tableprinter.go","code":"// PrintObj prints the obj in a human-friendly format according to the type of the obj.\nfunc (h *HumanReadablePrinter) PrintObj(obj runtime.Object, output io.Writer) error {\n\n\tif _, found := output.(*tabwriter.Writer); !found {\n\t\tw := GetNewTabWriter(output)\n\t\toutput = w\n\t\tdefer w.Flush()\n\t}\n\n\tvar eventType string\n\tif event, isEvent := obj.(*metav1.WatchEvent); isEvent {\n\t\teventType = event.Type\n\t\tobj = event.Object.Object\n\t}\n\n\t// Parameter \"obj\" is a table from server; print it.\n\t// display tables following the rules of options\n\tif table, ok := obj.(*metav1.Table); ok {\n\t\t// Do not print headers if this table has no column definitions, or they are the same as the last ones we printed\n\t\tlocalOptions := h.options\n\t\tif h.printedHeaders \u0026\u0026 (len(table.ColumnDefinitions) == 0 || reflect.DeepEqual(table.ColumnDefinitions, h.lastColumns)) {\n\t\t\tlocalOptions.NoHeaders = true\n\t\t}\n\n\t\tif len(table.ColumnDefinitions) == 0 {\n\t\t\t// If this table has no column definitions, use the columns from the last table we printed for decoration and layout.\n\t\t\t// This is done when receiving tables in watch events to save bandwidth.\n\t\t\ttable.ColumnDefinitions = h.lastColumns\n\t\t} else if !reflect.DeepEqual(table.ColumnDefinitions, h.lastColumns) {\n\t\t\t// If this table has column definitions, remember them for future use.\n\t\t\th.lastColumns = table.ColumnDefinitions\n\t\t\th.printedHeaders = false\n\t\t}\n\n\t\tif len(table.Rows) \u003e 0 {\n\t\t\th.printedHeaders = true\n\t\t}\n\n\t\tif err := decorateTable(table, localOptions); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(eventType) \u003e 0 {\n\t\t\tif err := addColumns(beginning, table,\n\t\t\t\t[]metav1.TableColumnDefinition{{Name: \"Event\", Type: \"string\"}},\n\t\t\t\t[]cellValueFunc{func(metav1.TableRow) (interface{}, error) { return formatEventType(eventType), nil }},\n\t\t\t); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn printTable(table, output, localOptions)\n\t}\n\n\t// Could not find print handler for \"obj\"; use the default or status print handler.\n\t// Print with the default or status handler, and use the columns from the last time\n\tvar handler *printHandler\n\tif _, isStatus := obj.(*metav1.Status); isStatus {\n\t\thandler = statusHandlerEntry\n\t} else {\n\t\thandler = defaultHandlerEntry\n\t}\n\n\tincludeHeaders := h.lastType != handler \u0026\u0026 !h.options.NoHeaders\n\n\tif h.lastType != nil \u0026\u0026 h.lastType != handler \u0026\u0026 !h.options.NoHeaders {\n\t\tfmt.Fprintln(output)\n\t}\n\n\tif err := printRowsForHandlerEntry(output, handler, eventType, obj, h.options, includeHeaders); err != nil {\n\t\treturn err\n\t}\n\th.lastType = handler\n\n\treturn nil\n}","line":{"from":94,"to":167}} {"id":100019363,"name":"printTable","signature":"func printTable(table *metav1.Table, output io.Writer, options PrintOptions) error","file":"staging/src/k8s.io/cli-runtime/pkg/printers/tableprinter.go","code":"// printTable prints a table to the provided output respecting the filtering rules for options\n// for wide columns and filtered rows. It filters out rows that are Completed. You should call\n// decorateTable if you receive a table from a remote server before calling printTable.\nfunc printTable(table *metav1.Table, output io.Writer, options PrintOptions) error {\n\tif !options.NoHeaders {\n\t\t// avoid printing headers if we have no rows to display\n\t\tif len(table.Rows) == 0 {\n\t\t\treturn nil\n\t\t}\n\n\t\tfirst := true\n\t\tfor _, column := range table.ColumnDefinitions {\n\t\t\tif !options.Wide \u0026\u0026 column.Priority != 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif first {\n\t\t\t\tfirst = false\n\t\t\t} else {\n\t\t\t\tfmt.Fprint(output, \"\\t\")\n\t\t\t}\n\t\t\tfmt.Fprint(output, strings.ToUpper(column.Name))\n\t\t}\n\t\tfmt.Fprintln(output)\n\t}\n\tfor _, row := range table.Rows {\n\t\tfirst := true\n\t\tfor i, cell := range row.Cells {\n\t\t\tif i \u003e= len(table.ColumnDefinitions) {\n\t\t\t\t// https://issue.k8s.io/66379\n\t\t\t\t// don't panic in case of bad output from the server, with more cells than column definitions\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcolumn := table.ColumnDefinitions[i]\n\t\t\tif !options.Wide \u0026\u0026 column.Priority != 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif first {\n\t\t\t\tfirst = false\n\t\t\t} else {\n\t\t\t\tfmt.Fprint(output, \"\\t\")\n\t\t\t}\n\t\t\tif cell != nil {\n\t\t\t\tswitch val := cell.(type) {\n\t\t\t\tcase string:\n\t\t\t\t\tprint := val\n\t\t\t\t\ttruncated := false\n\t\t\t\t\t// Truncate at the first newline, carriage return or formfeed\n\t\t\t\t\t// (treated as a newline by tabwriter).\n\t\t\t\t\tbreakchar := strings.IndexAny(print, \"\\f\\n\\r\")\n\t\t\t\t\tif breakchar \u003e= 0 {\n\t\t\t\t\t\ttruncated = true\n\t\t\t\t\t\tprint = print[:breakchar]\n\t\t\t\t\t}\n\t\t\t\t\tWriteEscaped(output, print)\n\t\t\t\t\tif truncated {\n\t\t\t\t\t\tfmt.Fprint(output, \"...\")\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\tWriteEscaped(output, fmt.Sprint(val))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfmt.Fprintln(output)\n\t}\n\treturn nil\n}","line":{"from":169,"to":234}} {"id":100019364,"name":"addColumns","signature":"func addColumns(pos columnAddPosition, table *metav1.Table, columns []metav1.TableColumnDefinition, valueFuncs []cellValueFunc) error","file":"staging/src/k8s.io/cli-runtime/pkg/printers/tableprinter.go","code":"func addColumns(pos columnAddPosition, table *metav1.Table, columns []metav1.TableColumnDefinition, valueFuncs []cellValueFunc) error {\n\tif len(columns) != len(valueFuncs) {\n\t\treturn fmt.Errorf(\"cannot prepend columns, unmatched value functions\")\n\t}\n\tif len(columns) == 0 {\n\t\treturn nil\n\t}\n\n\t// Compute the new rows\n\tnewRows := make([][]interface{}, len(table.Rows))\n\tfor i := range table.Rows {\n\t\tnewCells := make([]interface{}, 0, len(columns)+len(table.Rows[i].Cells))\n\n\t\tif pos == end {\n\t\t\t// If we're appending, start with the existing cells,\n\t\t\t// then add nil cells to match the number of columns\n\t\t\tnewCells = append(newCells, table.Rows[i].Cells...)\n\t\t\tfor len(newCells) \u003c len(table.ColumnDefinitions) {\n\t\t\t\tnewCells = append(newCells, nil)\n\t\t\t}\n\t\t}\n\n\t\t// Compute cells for new columns\n\t\tfor _, f := range valueFuncs {\n\t\t\tnewCell, err := f(table.Rows[i])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tnewCells = append(newCells, newCell)\n\t\t}\n\n\t\tif pos == beginning {\n\t\t\t// If we're prepending, add existing cells\n\t\t\tnewCells = append(newCells, table.Rows[i].Cells...)\n\t\t}\n\n\t\t// Remember the new cells for this row\n\t\tnewRows[i] = newCells\n\t}\n\n\t// All cells successfully computed, now replace columns and rows\n\tnewColumns := make([]metav1.TableColumnDefinition, 0, len(columns)+len(table.ColumnDefinitions))\n\tswitch pos {\n\tcase beginning:\n\t\tnewColumns = append(newColumns, columns...)\n\t\tnewColumns = append(newColumns, table.ColumnDefinitions...)\n\tcase end:\n\t\tnewColumns = append(newColumns, table.ColumnDefinitions...)\n\t\tnewColumns = append(newColumns, columns...)\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid column add position: %v\", pos)\n\t}\n\ttable.ColumnDefinitions = newColumns\n\tfor i := range table.Rows {\n\t\ttable.Rows[i].Cells = newRows[i]\n\t}\n\n\treturn nil\n}","line":{"from":245,"to":303}} {"id":100019365,"name":"decorateTable","signature":"func decorateTable(table *metav1.Table, options PrintOptions) error","file":"staging/src/k8s.io/cli-runtime/pkg/printers/tableprinter.go","code":"// decorateTable takes a table and attempts to add label columns and the\n// namespace column. It will fill empty columns with nil (if the object\n// does not expose metadata). It returns an error if the table cannot\n// be decorated.\nfunc decorateTable(table *metav1.Table, options PrintOptions) error {\n\twidth := len(table.ColumnDefinitions) + len(options.ColumnLabels)\n\tif options.WithNamespace {\n\t\twidth++\n\t}\n\tif options.ShowLabels {\n\t\twidth++\n\t}\n\n\tcolumns := table.ColumnDefinitions\n\n\tnameColumn := -1\n\tif options.WithKind \u0026\u0026 !options.Kind.Empty() {\n\t\tfor i := range columns {\n\t\t\tif columns[i].Format == \"name\" \u0026\u0026 columns[i].Type == \"string\" {\n\t\t\t\tnameColumn = i\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif width != len(table.ColumnDefinitions) {\n\t\tcolumns = make([]metav1.TableColumnDefinition, 0, width)\n\t\tif options.WithNamespace {\n\t\t\tcolumns = append(columns, metav1.TableColumnDefinition{\n\t\t\t\tName: \"Namespace\",\n\t\t\t\tType: \"string\",\n\t\t\t})\n\t\t}\n\t\tcolumns = append(columns, table.ColumnDefinitions...)\n\t\tfor _, label := range formatLabelHeaders(options.ColumnLabels) {\n\t\t\tcolumns = append(columns, metav1.TableColumnDefinition{\n\t\t\t\tName: label,\n\t\t\t\tType: \"string\",\n\t\t\t})\n\t\t}\n\t\tif options.ShowLabels {\n\t\t\tcolumns = append(columns, metav1.TableColumnDefinition{\n\t\t\t\tName: \"Labels\",\n\t\t\t\tType: \"string\",\n\t\t\t})\n\t\t}\n\t}\n\n\trows := table.Rows\n\n\tincludeLabels := len(options.ColumnLabels) \u003e 0 || options.ShowLabels\n\tif includeLabels || options.WithNamespace || nameColumn != -1 {\n\t\tfor i := range rows {\n\t\t\trow := rows[i]\n\n\t\t\tif nameColumn != -1 {\n\t\t\t\trow.Cells[nameColumn] = fmt.Sprintf(\"%s/%s\", strings.ToLower(options.Kind.String()), row.Cells[nameColumn])\n\t\t\t}\n\n\t\t\tvar m metav1.Object\n\t\t\tif obj := row.Object.Object; obj != nil {\n\t\t\t\tif acc, err := meta.Accessor(obj); err == nil {\n\t\t\t\t\tm = acc\n\t\t\t\t}\n\t\t\t}\n\t\t\t// if we can't get an accessor, fill out the appropriate columns with empty spaces\n\t\t\tif m == nil {\n\t\t\t\tif options.WithNamespace {\n\t\t\t\t\tr := make([]interface{}, 1, width)\n\t\t\t\t\trow.Cells = append(r, row.Cells...)\n\t\t\t\t}\n\t\t\t\tfor j := 0; j \u003c width-len(row.Cells); j++ {\n\t\t\t\t\trow.Cells = append(row.Cells, nil)\n\t\t\t\t}\n\t\t\t\trows[i] = row\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif options.WithNamespace {\n\t\t\t\tr := make([]interface{}, 1, width)\n\t\t\t\tr[0] = m.GetNamespace()\n\t\t\t\trow.Cells = append(r, row.Cells...)\n\t\t\t}\n\t\t\tif includeLabels {\n\t\t\t\trow.Cells = appendLabelCells(row.Cells, m.GetLabels(), options)\n\t\t\t}\n\t\t\trows[i] = row\n\t\t}\n\t}\n\n\ttable.ColumnDefinitions = columns\n\ttable.Rows = rows\n\treturn nil\n}","line":{"from":305,"to":398}} {"id":100019366,"name":"printRowsForHandlerEntry","signature":"func printRowsForHandlerEntry(output io.Writer, handler *printHandler, eventType string, obj runtime.Object, options PrintOptions, includeHeaders bool) error","file":"staging/src/k8s.io/cli-runtime/pkg/printers/tableprinter.go","code":"// printRowsForHandlerEntry prints the incremental table output (headers if the current type is\n// different from lastType) including all the rows in the object. It returns the current type\n// or an error, if any.\nfunc printRowsForHandlerEntry(output io.Writer, handler *printHandler, eventType string, obj runtime.Object, options PrintOptions, includeHeaders bool) error {\n\tvar results []reflect.Value\n\n\targs := []reflect.Value{reflect.ValueOf(obj), reflect.ValueOf(options)}\n\tresults = handler.printFunc.Call(args)\n\tif !results[1].IsNil() {\n\t\treturn results[1].Interface().(error)\n\t}\n\n\tif includeHeaders {\n\t\tvar headers []string\n\t\tfor _, column := range handler.columnDefinitions {\n\t\t\tif column.Priority != 0 \u0026\u0026 !options.Wide {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\theaders = append(headers, strings.ToUpper(column.Name))\n\t\t}\n\t\theaders = append(headers, formatLabelHeaders(options.ColumnLabels)...)\n\t\t// LABELS is always the last column.\n\t\theaders = append(headers, formatShowLabelsHeader(options.ShowLabels)...)\n\t\t// prepend namespace header\n\t\tif options.WithNamespace {\n\t\t\theaders = append(withNamespacePrefixColumns, headers...)\n\t\t}\n\t\t// prepend event type header\n\t\tif len(eventType) \u003e 0 {\n\t\t\theaders = append(withEventTypePrefixColumns, headers...)\n\t\t}\n\t\tprintHeader(headers, output)\n\t}\n\n\tif results[1].IsNil() {\n\t\trows := results[0].Interface().([]metav1.TableRow)\n\t\tprintRows(output, eventType, rows, options)\n\t\treturn nil\n\t}\n\treturn results[1].Interface().(error)\n}","line":{"from":400,"to":440}} {"id":100019367,"name":"formatEventType","signature":"func formatEventType(eventType string) string","file":"staging/src/k8s.io/cli-runtime/pkg/printers/tableprinter.go","code":"func formatEventType(eventType string) string {\n\tif formatted, ok := formattedEventType[eventType]; ok {\n\t\treturn formatted\n\t}\n\treturn eventType\n}","line":{"from":449,"to":454}} {"id":100019368,"name":"printRows","signature":"func printRows(output io.Writer, eventType string, rows []metav1.TableRow, options PrintOptions)","file":"staging/src/k8s.io/cli-runtime/pkg/printers/tableprinter.go","code":"// printRows writes the provided rows to output.\nfunc printRows(output io.Writer, eventType string, rows []metav1.TableRow, options PrintOptions) {\n\tfor _, row := range rows {\n\t\tif len(eventType) \u003e 0 {\n\t\t\tfmt.Fprint(output, formatEventType(eventType))\n\t\t\tfmt.Fprint(output, \"\\t\")\n\t\t}\n\t\tif options.WithNamespace {\n\t\t\tif obj := row.Object.Object; obj != nil {\n\t\t\t\tif m, err := meta.Accessor(obj); err == nil {\n\t\t\t\t\tfmt.Fprint(output, m.GetNamespace())\n\t\t\t\t}\n\t\t\t}\n\t\t\tfmt.Fprint(output, \"\\t\")\n\t\t}\n\n\t\tfor i, cell := range row.Cells {\n\t\t\tif i != 0 {\n\t\t\t\tfmt.Fprint(output, \"\\t\")\n\t\t\t} else {\n\t\t\t\t// TODO: remove this once we drop the legacy printers\n\t\t\t\tif options.WithKind \u0026\u0026 !options.Kind.Empty() {\n\t\t\t\t\tfmt.Fprintf(output, \"%s/%s\", strings.ToLower(options.Kind.String()), cell)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tfmt.Fprint(output, cell)\n\t\t}\n\n\t\thasLabels := len(options.ColumnLabels) \u003e 0\n\t\tif obj := row.Object.Object; obj != nil \u0026\u0026 (hasLabels || options.ShowLabels) {\n\t\t\tif m, err := meta.Accessor(obj); err == nil {\n\t\t\t\tfor _, value := range labelValues(m.GetLabels(), options) {\n\t\t\t\t\toutput.Write([]byte(\"\\t\"))\n\t\t\t\t\toutput.Write([]byte(value))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\toutput.Write([]byte(\"\\n\"))\n\t}\n}","line":{"from":456,"to":497}} {"id":100019369,"name":"formatLabelHeaders","signature":"func formatLabelHeaders(columnLabels []string) []string","file":"staging/src/k8s.io/cli-runtime/pkg/printers/tableprinter.go","code":"func formatLabelHeaders(columnLabels []string) []string {\n\tformHead := make([]string, len(columnLabels))\n\tfor i, l := range columnLabels {\n\t\tp := strings.Split(l, \"/\")\n\t\tformHead[i] = strings.ToUpper(p[len(p)-1])\n\t}\n\treturn formHead\n}","line":{"from":499,"to":506}} {"id":100019370,"name":"formatShowLabelsHeader","signature":"func formatShowLabelsHeader(showLabels bool) []string","file":"staging/src/k8s.io/cli-runtime/pkg/printers/tableprinter.go","code":"// headers for --show-labels=true\nfunc formatShowLabelsHeader(showLabels bool) []string {\n\tif showLabels {\n\t\treturn []string{\"LABELS\"}\n\t}\n\treturn nil\n}","line":{"from":508,"to":514}} {"id":100019371,"name":"labelValues","signature":"func labelValues(itemLabels map[string]string, opts PrintOptions) []string","file":"staging/src/k8s.io/cli-runtime/pkg/printers/tableprinter.go","code":"// labelValues returns a slice of value columns matching the requested print options.\nfunc labelValues(itemLabels map[string]string, opts PrintOptions) []string {\n\tvar values []string\n\tfor _, key := range opts.ColumnLabels {\n\t\tvalues = append(values, itemLabels[key])\n\t}\n\tif opts.ShowLabels {\n\t\tvalues = append(values, labels.FormatLabels(itemLabels))\n\t}\n\treturn values\n}","line":{"from":516,"to":526}} {"id":100019372,"name":"appendLabelCells","signature":"func appendLabelCells(values []interface{}, itemLabels map[string]string, opts PrintOptions) []interface{}","file":"staging/src/k8s.io/cli-runtime/pkg/printers/tableprinter.go","code":"// appendLabelCells returns a slice of value columns matching the requested print options.\n// Intended for use with tables.\nfunc appendLabelCells(values []interface{}, itemLabels map[string]string, opts PrintOptions) []interface{} {\n\tfor _, key := range opts.ColumnLabels {\n\t\tvalues = append(values, itemLabels[key])\n\t}\n\tif opts.ShowLabels {\n\t\tvalues = append(values, labels.FormatLabels(itemLabels))\n\t}\n\treturn values\n}","line":{"from":528,"to":538}} {"id":100019373,"name":"printStatus","signature":"func printStatus(obj runtime.Object, options PrintOptions) ([]metav1.TableRow, error)","file":"staging/src/k8s.io/cli-runtime/pkg/printers/tableprinter.go","code":"func printStatus(obj runtime.Object, options PrintOptions) ([]metav1.TableRow, error) {\n\tstatus, ok := obj.(*metav1.Status)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"expected *v1.Status, got %T\", obj)\n\t}\n\treturn []metav1.TableRow{{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t\tCells: []interface{}{status.Status, status.Reason, status.Message},\n\t}}, nil\n}","line":{"from":540,"to":549}} {"id":100019374,"name":"printObjectMeta","signature":"func printObjectMeta(obj runtime.Object, options PrintOptions) ([]metav1.TableRow, error)","file":"staging/src/k8s.io/cli-runtime/pkg/printers/tableprinter.go","code":"func printObjectMeta(obj runtime.Object, options PrintOptions) ([]metav1.TableRow, error) {\n\tif meta.IsListType(obj) {\n\t\trows := make([]metav1.TableRow, 0, 16)\n\t\terr := meta.EachListItem(obj, func(obj runtime.Object) error {\n\t\t\tnestedRows, err := printObjectMeta(obj, options)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\trows = append(rows, nestedRows...)\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn rows, nil\n\t}\n\n\trows := make([]metav1.TableRow, 0, 1)\n\tm, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trow := metav1.TableRow{\n\t\tObject: runtime.RawExtension{Object: obj},\n\t}\n\trow.Cells = append(row.Cells, m.GetName(), translateTimestampSince(m.GetCreationTimestamp()))\n\trows = append(rows, row)\n\treturn rows, nil\n}","line":{"from":551,"to":579}} {"id":100019375,"name":"translateTimestampSince","signature":"func translateTimestampSince(timestamp metav1.Time) string","file":"staging/src/k8s.io/cli-runtime/pkg/printers/tableprinter.go","code":"// translateTimestampSince returns the elapsed time since timestamp in\n// human-readable approximation.\nfunc translateTimestampSince(timestamp metav1.Time) string {\n\tif timestamp.IsZero() {\n\t\treturn \"\u003cunknown\u003e\"\n\t}\n\n\treturn duration.HumanDuration(time.Since(timestamp.Time))\n}","line":{"from":581,"to":589}} {"id":100019376,"name":"GetNewTabWriter","signature":"func GetNewTabWriter(output io.Writer) *tabwriter.Writer","file":"staging/src/k8s.io/cli-runtime/pkg/printers/tabwriter.go","code":"// GetNewTabWriter returns a tabwriter that translates tabbed columns in input into properly aligned text.\nfunc GetNewTabWriter(output io.Writer) *tabwriter.Writer {\n\treturn tabwriter.NewWriter(output, tabwriterMinWidth, tabwriterWidth, tabwriterPadding, tabwriterPadChar, tabwriterFlags)\n}","line":{"from":33,"to":36}} {"id":100019377,"name":"NewGoTemplatePrinter","signature":"func NewGoTemplatePrinter(tmpl []byte) (*GoTemplatePrinter, error)","file":"staging/src/k8s.io/cli-runtime/pkg/printers/template.go","code":"func NewGoTemplatePrinter(tmpl []byte) (*GoTemplatePrinter, error) {\n\tt, err := template.New(\"output\").\n\t\tFuncs(template.FuncMap{\n\t\t\t\"exists\": exists,\n\t\t\t\"base64decode\": base64decode,\n\t\t}).\n\t\tParse(string(tmpl))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026GoTemplatePrinter{\n\t\trawTemplate: string(tmpl),\n\t\ttemplate: t,\n\t}, nil\n}","line":{"from":36,"to":50}} {"id":100019378,"name":"AllowMissingKeys","signature":"func (p *GoTemplatePrinter) AllowMissingKeys(allow bool)","file":"staging/src/k8s.io/cli-runtime/pkg/printers/template.go","code":"// AllowMissingKeys tells the template engine if missing keys are allowed.\nfunc (p *GoTemplatePrinter) AllowMissingKeys(allow bool) {\n\tif allow {\n\t\tp.template.Option(\"missingkey=default\")\n\t} else {\n\t\tp.template.Option(\"missingkey=error\")\n\t}\n}","line":{"from":52,"to":59}} {"id":100019379,"name":"PrintObj","signature":"func (p *GoTemplatePrinter) PrintObj(obj runtime.Object, w io.Writer) error","file":"staging/src/k8s.io/cli-runtime/pkg/printers/template.go","code":"// PrintObj formats the obj with the Go Template.\nfunc (p *GoTemplatePrinter) PrintObj(obj runtime.Object, w io.Writer) error {\n\tif InternalObjectPreventer.IsForbidden(reflect.Indirect(reflect.ValueOf(obj)).Type().PkgPath()) {\n\t\treturn fmt.Errorf(InternalObjectPrinterErr)\n\t}\n\n\tvar data []byte\n\tvar err error\n\tdata, err = json.Marshal(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tout := map[string]interface{}{}\n\tif err := json.Unmarshal(data, \u0026out); err != nil {\n\t\treturn err\n\t}\n\tif err = p.safeExecute(w, out); err != nil {\n\t\t// It is way easier to debug this stuff when it shows up in\n\t\t// stdout instead of just stdin. So in addition to returning\n\t\t// a nice error, also print useful stuff with the writer.\n\t\tfmt.Fprintf(w, \"Error executing template: %v. Printing more information for debugging the template:\\n\", err)\n\t\tfmt.Fprintf(w, \"\\ttemplate was:\\n\\t\\t%v\\n\", p.rawTemplate)\n\t\tfmt.Fprintf(w, \"\\traw data was:\\n\\t\\t%v\\n\", string(data))\n\t\tfmt.Fprintf(w, \"\\tobject given to template engine was:\\n\\t\\t%+v\\n\\n\", out)\n\t\treturn fmt.Errorf(\"error executing template %q: %v\", p.rawTemplate, err)\n\t}\n\treturn nil\n}","line":{"from":61,"to":89}} {"id":100019380,"name":"safeExecute","signature":"func (p *GoTemplatePrinter) safeExecute(w io.Writer, obj interface{}) error","file":"staging/src/k8s.io/cli-runtime/pkg/printers/template.go","code":"// safeExecute tries to execute the template, but catches panics and returns an error\n// should the template engine panic.\nfunc (p *GoTemplatePrinter) safeExecute(w io.Writer, obj interface{}) error {\n\tvar panicErr error\n\t// Sorry for the double anonymous function. There's probably a clever way\n\t// to do this that has the defer'd func setting the value to be returned, but\n\t// that would be even less obvious.\n\tretErr := func() error {\n\t\tdefer func() {\n\t\t\tif x := recover(); x != nil {\n\t\t\t\tpanicErr = fmt.Errorf(\"caught panic: %+v\", x)\n\t\t\t}\n\t\t}()\n\t\treturn p.template.Execute(w, obj)\n\t}()\n\tif panicErr != nil {\n\t\treturn panicErr\n\t}\n\treturn retErr\n}","line":{"from":91,"to":110}} {"id":100019381,"name":"base64decode","signature":"func base64decode(v string) (string, error)","file":"staging/src/k8s.io/cli-runtime/pkg/printers/template.go","code":"func base64decode(v string) (string, error) {\n\tdata, err := base64.StdEncoding.DecodeString(v)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"base64 decode failed: %v\", err)\n\t}\n\treturn string(data), nil\n}","line":{"from":112,"to":118}} {"id":100019382,"name":"WriteEscaped","signature":"func WriteEscaped(writer io.Writer, output string) error","file":"staging/src/k8s.io/cli-runtime/pkg/printers/terminal.go","code":"// WriteEscaped replaces unsafe terminal characters with replacement strings\n// and writes them to the given writer.\nfunc WriteEscaped(writer io.Writer, output string) error {\n\t_, err := terminalEscaper.WriteString(writer, output)\n\treturn err\n}","line":{"from":28,"to":33}} {"id":100019383,"name":"EscapeTerminal","signature":"func EscapeTerminal(in string) string","file":"staging/src/k8s.io/cli-runtime/pkg/printers/terminal.go","code":"// EscapeTerminal escapes terminal special characters in a human readable (but\n// non-reversible) format.\nfunc EscapeTerminal(in string) string {\n\treturn terminalEscaper.Replace(in)\n}","line":{"from":35,"to":39}} {"id":100019384,"name":"NewTypeSetter","signature":"func NewTypeSetter(typer runtime.ObjectTyper) *TypeSetterPrinter","file":"staging/src/k8s.io/cli-runtime/pkg/printers/typesetter.go","code":"// NewTypeSetter constructs a wrapping printer with required params\nfunc NewTypeSetter(typer runtime.ObjectTyper) *TypeSetterPrinter {\n\treturn \u0026TypeSetterPrinter{Typer: typer}\n}","line":{"from":34,"to":37}} {"id":100019385,"name":"PrintObj","signature":"func (p *TypeSetterPrinter) PrintObj(obj runtime.Object, w io.Writer) error","file":"staging/src/k8s.io/cli-runtime/pkg/printers/typesetter.go","code":"// PrintObj is an implementation of ResourcePrinter.PrintObj which sets type information on the obj for the duration\n// of printing. It is NOT threadsafe.\nfunc (p *TypeSetterPrinter) PrintObj(obj runtime.Object, w io.Writer) error {\n\tif obj == nil {\n\t\treturn p.Delegate.PrintObj(obj, w)\n\t}\n\tif !obj.GetObjectKind().GroupVersionKind().Empty() {\n\t\treturn p.Delegate.PrintObj(obj, w)\n\t}\n\n\t// we were empty coming in, make sure we're empty going out. This makes the call thread-unsafe\n\tdefer func() {\n\t\tobj.GetObjectKind().SetGroupVersionKind(schema.GroupVersionKind{})\n\t}()\n\n\tgvks, _, err := p.Typer.ObjectKinds(obj)\n\tif err != nil {\n\t\t// printers wrapped by us expect to find the type information present\n\t\treturn fmt.Errorf(\"missing apiVersion or kind and cannot assign it; %v\", err)\n\t}\n\n\tfor _, gvk := range gvks {\n\t\tif len(gvk.Kind) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif len(gvk.Version) == 0 || gvk.Version == runtime.APIVersionInternal {\n\t\t\tcontinue\n\t\t}\n\t\tobj.GetObjectKind().SetGroupVersionKind(gvk)\n\t\tbreak\n\t}\n\n\treturn p.Delegate.PrintObj(obj, w)\n}","line":{"from":39,"to":72}} {"id":100019386,"name":"ToPrinter","signature":"func (p *TypeSetterPrinter) ToPrinter(delegate ResourcePrinter) ResourcePrinter","file":"staging/src/k8s.io/cli-runtime/pkg/printers/typesetter.go","code":"// ToPrinter returns a printer (not threadsafe!) that has been wrapped\nfunc (p *TypeSetterPrinter) ToPrinter(delegate ResourcePrinter) ResourcePrinter {\n\tif p == nil {\n\t\treturn delegate\n\t}\n\n\tp.Delegate = delegate\n\treturn p\n}","line":{"from":74,"to":82}} {"id":100019387,"name":"WrapToPrinter","signature":"func (p *TypeSetterPrinter) WrapToPrinter(delegate ResourcePrinter, err error) (ResourcePrinter, error)","file":"staging/src/k8s.io/cli-runtime/pkg/printers/typesetter.go","code":"// WrapToPrinter wraps the common ToPrinter method\nfunc (p *TypeSetterPrinter) WrapToPrinter(delegate ResourcePrinter, err error) (ResourcePrinter, error) {\n\tif err != nil {\n\t\treturn delegate, err\n\t}\n\tif p == nil {\n\t\treturn delegate, nil\n\t}\n\n\tp.Delegate = delegate\n\treturn p, nil\n}","line":{"from":84,"to":95}} {"id":100019388,"name":"NewWarningPrinter","signature":"func NewWarningPrinter(out io.Writer, opts WarningPrinterOptions) *WarningPrinter","file":"staging/src/k8s.io/cli-runtime/pkg/printers/warningprinter.go","code":"// NewWarningPrinter returns an implementation of warningPrinter that outputs warnings to the specified writer.\nfunc NewWarningPrinter(out io.Writer, opts WarningPrinterOptions) *WarningPrinter {\n\th := \u0026WarningPrinter{out: out, opts: opts}\n\treturn h\n}","line":{"from":42,"to":46}} {"id":100019389,"name":"Print","signature":"func (w *WarningPrinter) Print(message string)","file":"staging/src/k8s.io/cli-runtime/pkg/printers/warningprinter.go","code":"// Print prints warnings to the configured writer.\nfunc (w *WarningPrinter) Print(message string) {\n\tif w.opts.Color {\n\t\tfmt.Fprintf(w.out, \"%sWarning:%s %s\\n\", yellowColor, resetColor, message)\n\t} else {\n\t\tfmt.Fprintf(w.out, \"Warning: %s\\n\", message)\n\t}\n}","line":{"from":48,"to":55}} {"id":100019390,"name":"PrintObj","signature":"func (p *YAMLPrinter) PrintObj(obj runtime.Object, w io.Writer) error","file":"staging/src/k8s.io/cli-runtime/pkg/printers/yaml.go","code":"// PrintObj prints the data as YAML.\nfunc (p *YAMLPrinter) PrintObj(obj runtime.Object, w io.Writer) error {\n\t// we use reflect.Indirect here in order to obtain the actual value from a pointer.\n\t// we need an actual value in order to retrieve the package path for an object.\n\t// using reflect.Indirect indiscriminately is valid here, as all runtime.Objects are supposed to be pointers.\n\tif InternalObjectPreventer.IsForbidden(reflect.Indirect(reflect.ValueOf(obj)).Type().PkgPath()) {\n\t\treturn fmt.Errorf(InternalObjectPrinterErr)\n\t}\n\n\tcount := atomic.AddInt64(\u0026p.printCount, 1)\n\tif count \u003e 1 {\n\t\tif _, err := w.Write([]byte(\"---\\n\")); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tswitch obj := obj.(type) {\n\tcase *metav1.WatchEvent:\n\t\tif InternalObjectPreventer.IsForbidden(reflect.Indirect(reflect.ValueOf(obj.Object.Object)).Type().PkgPath()) {\n\t\t\treturn fmt.Errorf(InternalObjectPrinterErr)\n\t\t}\n\t\tdata, err := yaml.Marshal(obj)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = w.Write(data)\n\t\treturn err\n\tcase *runtime.Unknown:\n\t\tdata, err := yaml.JSONToYAML(obj.Raw)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = w.Write(data)\n\t\treturn err\n\t}\n\n\tif obj.GetObjectKind().GroupVersionKind().Empty() {\n\t\treturn fmt.Errorf(\"missing apiVersion or kind; try GetObjectKind().SetGroupVersionKind() if you know the type\")\n\t}\n\n\toutput, err := yaml.Marshal(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = fmt.Fprint(w, string(output))\n\treturn err\n}","line":{"from":39,"to":85}} {"id":100019391,"name":"IsUsageError","signature":"func IsUsageError(err error) bool","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// TODO: expand this to include other errors.\nfunc IsUsageError(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\treturn err == missingResourceError\n}","line":{"from":130,"to":136}} {"id":100019392,"name":"validate","signature":"func (o *FilenameOptions) validate() []error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"func (o *FilenameOptions) validate() []error {\n\tvar errs []error\n\tif len(o.Filenames) \u003e 0 \u0026\u0026 len(o.Kustomize) \u003e 0 {\n\t\terrs = append(errs, fmt.Errorf(\"only one of -f or -k can be specified\"))\n\t}\n\tif len(o.Kustomize) \u003e 0 \u0026\u0026 o.Recursive {\n\t\terrs = append(errs, fmt.Errorf(\"the -k flag can't be used with -f or -R\"))\n\t}\n\treturn errs\n}","line":{"from":144,"to":153}} {"id":100019393,"name":"RequireFilenameOrKustomize","signature":"func (o *FilenameOptions) RequireFilenameOrKustomize() error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"func (o *FilenameOptions) RequireFilenameOrKustomize() error {\n\tif len(o.Filenames) == 0 \u0026\u0026 len(o.Kustomize) == 0 {\n\t\treturn fmt.Errorf(\"must specify one of -f and -k\")\n\t}\n\treturn nil\n}","line":{"from":155,"to":160}} {"id":100019394,"name":"NewFakeBuilder","signature":"func NewFakeBuilder(fakeClientFn FakeClientFunc, restMapper RESTMapperFunc, categoryExpander CategoryExpanderFunc) *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"func NewFakeBuilder(fakeClientFn FakeClientFunc, restMapper RESTMapperFunc, categoryExpander CategoryExpanderFunc) *Builder {\n\tret := newBuilder(nil, restMapper, categoryExpander)\n\tret.fakeClientFn = fakeClientFn\n\treturn ret\n}","line":{"from":169,"to":173}} {"id":100019395,"name":"newBuilder","signature":"func newBuilder(clientConfigFn ClientConfigFunc, restMapper RESTMapperFunc, categoryExpander CategoryExpanderFunc) *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// NewBuilder creates a builder that operates on generic objects. At least one of\n// internal or unstructured must be specified.\n// TODO: Add versioned client (although versioned is still lossy)\n// TODO remove internal and unstructured mapper and instead have them set the negotiated serializer for use in the client\nfunc newBuilder(clientConfigFn ClientConfigFunc, restMapper RESTMapperFunc, categoryExpander CategoryExpanderFunc) *Builder {\n\treturn \u0026Builder{\n\t\tclientConfigFn: clientConfigFn,\n\t\trestMapperFn: restMapper,\n\t\tcategoryExpanderFn: categoryExpander,\n\t\trequireObject: true,\n\t}\n}","line":{"from":175,"to":186}} {"id":100019396,"name":"ToRESTConfig","signature":"func (noopClientGetter) ToRESTConfig() (*rest.Config, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"func (noopClientGetter) ToRESTConfig() (*rest.Config, error) {\n\treturn nil, fmt.Errorf(\"local operation only\")\n}","line":{"from":192,"to":194}} {"id":100019397,"name":"ToDiscoveryClient","signature":"func (noopClientGetter) ToDiscoveryClient() (discovery.CachedDiscoveryInterface, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"func (noopClientGetter) ToDiscoveryClient() (discovery.CachedDiscoveryInterface, error) {\n\treturn nil, fmt.Errorf(\"local operation only\")\n}","line":{"from":195,"to":197}} {"id":100019398,"name":"ToRESTMapper","signature":"func (noopClientGetter) ToRESTMapper() (meta.RESTMapper, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"func (noopClientGetter) ToRESTMapper() (meta.RESTMapper, error) {\n\treturn nil, fmt.Errorf(\"local operation only\")\n}","line":{"from":198,"to":200}} {"id":100019399,"name":"NewLocalBuilder","signature":"func NewLocalBuilder() *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// NewLocalBuilder returns a builder that is configured not to create REST clients and avoids asking the server for results.\nfunc NewLocalBuilder() *Builder {\n\treturn NewBuilder(noopClientGetter{}).Local()\n}","line":{"from":202,"to":205}} {"id":100019400,"name":"NewBuilder","signature":"func NewBuilder(restClientGetter RESTClientGetter) *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"func NewBuilder(restClientGetter RESTClientGetter) *Builder {\n\tcategoryExpanderFn := func() (restmapper.CategoryExpander, error) {\n\t\tdiscoveryClient, err := restClientGetter.ToDiscoveryClient()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn restmapper.NewDiscoveryCategoryExpander(discoveryClient), err\n\t}\n\n\treturn newBuilder(\n\t\trestClientGetter.ToRESTConfig,\n\t\trestClientGetter.ToRESTMapper,\n\t\t(\u0026cachingCategoryExpanderFunc{delegate: categoryExpanderFn}).ToCategoryExpander,\n\t)\n}","line":{"from":207,"to":221}} {"id":100019401,"name":"Schema","signature":"func (b *Builder) Schema(schema ContentValidator) *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"func (b *Builder) Schema(schema ContentValidator) *Builder {\n\tb.schema = schema\n\treturn b\n}","line":{"from":223,"to":226}} {"id":100019402,"name":"AddError","signature":"func (b *Builder) AddError(err error) *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"func (b *Builder) AddError(err error) *Builder {\n\tif err == nil {\n\t\treturn b\n\t}\n\tb.errs = append(b.errs, err)\n\treturn b\n}","line":{"from":228,"to":234}} {"id":100019403,"name":"FilenameParam","signature":"func (b *Builder) FilenameParam(enforceNamespace bool, filenameOptions *FilenameOptions) *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// FilenameParam groups input in two categories: URLs and files (files, directories, STDIN)\n// If enforceNamespace is false, namespaces in the specs will be allowed to\n// override the default namespace. If it is true, namespaces that don't match\n// will cause an error.\n// If ContinueOnError() is set prior to this method, objects on the path that are not\n// recognized will be ignored (but logged at V(2)).\nfunc (b *Builder) FilenameParam(enforceNamespace bool, filenameOptions *FilenameOptions) *Builder {\n\tif errs := filenameOptions.validate(); len(errs) \u003e 0 {\n\t\tb.errs = append(b.errs, errs...)\n\t\treturn b\n\t}\n\trecursive := filenameOptions.Recursive\n\tpaths := filenameOptions.Filenames\n\tfor _, s := range paths {\n\t\tswitch {\n\t\tcase s == \"-\":\n\t\t\tb.Stdin()\n\t\tcase strings.Index(s, \"http://\") == 0 || strings.Index(s, \"https://\") == 0:\n\t\t\turl, err := url.Parse(s)\n\t\t\tif err != nil {\n\t\t\t\tb.errs = append(b.errs, fmt.Errorf(\"the URL passed to filename %q is not valid: %v\", s, err))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tb.URL(defaultHttpGetAttempts, url)\n\t\tdefault:\n\t\t\tmatches, err := expandIfFilePattern(s)\n\t\t\tif err != nil {\n\t\t\t\tb.errs = append(b.errs, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !recursive \u0026\u0026 len(matches) == 1 {\n\t\t\t\tb.singleItemImplied = true\n\t\t\t}\n\t\t\tb.Path(recursive, matches...)\n\t\t}\n\t}\n\tif filenameOptions.Kustomize != \"\" {\n\t\tb.paths = append(\n\t\t\tb.paths,\n\t\t\t\u0026KustomizeVisitor{\n\t\t\t\tmapper: b.mapper,\n\t\t\t\tdirPath: filenameOptions.Kustomize,\n\t\t\t\tschema: b.schema,\n\t\t\t\tfSys: filesys.MakeFsOnDisk(),\n\t\t\t})\n\t}\n\n\tif enforceNamespace {\n\t\tb.RequireNamespace()\n\t}\n\n\treturn b\n}","line":{"from":236,"to":288}} {"id":100019404,"name":"Unstructured","signature":"func (b *Builder) Unstructured() *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// Unstructured updates the builder so that it will request and send unstructured\n// objects. Unstructured objects preserve all fields sent by the server in a map format\n// based on the object's JSON structure which means no data is lost when the client\n// reads and then writes an object. Use this mode in preference to Internal unless you\n// are working with Go types directly.\nfunc (b *Builder) Unstructured() *Builder {\n\tif b.mapper != nil {\n\t\tb.errs = append(b.errs, fmt.Errorf(\"another mapper was already selected, cannot use unstructured types\"))\n\t\treturn b\n\t}\n\tb.objectTyper = unstructuredscheme.NewUnstructuredObjectTyper()\n\tb.mapper = \u0026mapper{\n\t\tlocalFn: b.isLocal,\n\t\trestMapperFn: b.restMapperFn,\n\t\tclientFn: b.getClient,\n\t\tdecoder: \u0026metadataValidatingDecoder{unstructured.UnstructuredJSONScheme},\n\t}\n\n\treturn b\n}","line":{"from":290,"to":309}} {"id":100019405,"name":"WithScheme","signature":"func (b *Builder) WithScheme(scheme *runtime.Scheme, decodingVersions ...schema.GroupVersion) *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// WithScheme uses the scheme to manage typing, conversion (optional), and decoding. If decodingVersions\n// is empty, then you can end up with internal types. You have been warned.\nfunc (b *Builder) WithScheme(scheme *runtime.Scheme, decodingVersions ...schema.GroupVersion) *Builder {\n\tif b.mapper != nil {\n\t\tb.errs = append(b.errs, fmt.Errorf(\"another mapper was already selected, cannot use internal types\"))\n\t\treturn b\n\t}\n\tb.objectTyper = scheme\n\tcodecFactory := serializer.NewCodecFactory(scheme)\n\tnegotiatedSerializer := runtime.NegotiatedSerializer(codecFactory)\n\t// if you specified versions, you're specifying a desire for external types, which you don't want to round-trip through\n\t// internal types\n\tif len(decodingVersions) \u003e 0 {\n\t\tnegotiatedSerializer = codecFactory.WithoutConversion()\n\t}\n\tb.negotiatedSerializer = negotiatedSerializer\n\n\tb.mapper = \u0026mapper{\n\t\tlocalFn: b.isLocal,\n\t\trestMapperFn: b.restMapperFn,\n\t\tclientFn: b.getClient,\n\t\tdecoder: codecFactory.UniversalDecoder(decodingVersions...),\n\t}\n\n\treturn b\n}","line":{"from":311,"to":336}} {"id":100019406,"name":"LocalParam","signature":"func (b *Builder) LocalParam(local bool) *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// LocalParam calls Local() if local is true.\nfunc (b *Builder) LocalParam(local bool) *Builder {\n\tif local {\n\t\tb.Local()\n\t}\n\treturn b\n}","line":{"from":338,"to":344}} {"id":100019407,"name":"Local","signature":"func (b *Builder) Local() *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// Local will avoid asking the server for results.\nfunc (b *Builder) Local() *Builder {\n\tb.local = true\n\treturn b\n}","line":{"from":346,"to":350}} {"id":100019408,"name":"isLocal","signature":"func (b *Builder) isLocal() bool","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"func (b *Builder) isLocal() bool {\n\treturn b.local\n}","line":{"from":352,"to":354}} {"id":100019409,"name":"Mapper","signature":"func (b *Builder) Mapper() *mapper","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// Mapper returns a copy of the current mapper.\nfunc (b *Builder) Mapper() *mapper {\n\tmapper := *b.mapper\n\treturn \u0026mapper\n}","line":{"from":356,"to":360}} {"id":100019410,"name":"URL","signature":"func (b *Builder) URL(httpAttemptCount int, urls ...*url.URL) *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// URL accepts a number of URLs directly.\nfunc (b *Builder) URL(httpAttemptCount int, urls ...*url.URL) *Builder {\n\tfor _, u := range urls {\n\t\tb.paths = append(b.paths, \u0026URLVisitor{\n\t\t\tURL: u,\n\t\t\tStreamVisitor: NewStreamVisitor(nil, b.mapper, u.String(), b.schema),\n\t\t\tHttpAttemptCount: httpAttemptCount,\n\t\t})\n\t}\n\treturn b\n}","line":{"from":362,"to":372}} {"id":100019411,"name":"Stdin","signature":"func (b *Builder) Stdin() *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// Stdin will read objects from the standard input. If ContinueOnError() is set\n// prior to this method being called, objects in the stream that are unrecognized\n// will be ignored (but logged at V(2)). If StdinInUse() is set prior to this method\n// being called, an error will be recorded as there are multiple entities trying to use\n// the single standard input stream.\nfunc (b *Builder) Stdin() *Builder {\n\tb.stream = true\n\tif b.stdinInUse {\n\t\tb.errs = append(b.errs, StdinMultiUseError)\n\t}\n\tb.stdinInUse = true\n\tb.paths = append(b.paths, FileVisitorForSTDIN(b.mapper, b.schema))\n\treturn b\n}","line":{"from":374,"to":387}} {"id":100019412,"name":"StdinInUse","signature":"func (b *Builder) StdinInUse() *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// StdinInUse will mark standard input as in use by this Builder, and therefore standard\n// input should not be used by another entity. If Stdin() is set prior to this method\n// being called, an error will be recorded as there are multiple entities trying to use\n// the single standard input stream.\nfunc (b *Builder) StdinInUse() *Builder {\n\tif b.stdinInUse {\n\t\tb.errs = append(b.errs, StdinMultiUseError)\n\t}\n\tb.stdinInUse = true\n\treturn b\n}","line":{"from":389,"to":399}} {"id":100019413,"name":"Stream","signature":"func (b *Builder) Stream(r io.Reader, name string) *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// Stream will read objects from the provided reader, and if an error occurs will\n// include the name string in the error message. If ContinueOnError() is set\n// prior to this method being called, objects in the stream that are unrecognized\n// will be ignored (but logged at V(2)).\nfunc (b *Builder) Stream(r io.Reader, name string) *Builder {\n\tb.stream = true\n\tb.paths = append(b.paths, NewStreamVisitor(r, b.mapper, name, b.schema))\n\treturn b\n}","line":{"from":401,"to":409}} {"id":100019414,"name":"Path","signature":"func (b *Builder) Path(recursive bool, paths ...string) *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// Path accepts a set of paths that may be files, directories (all can containing\n// one or more resources). Creates a FileVisitor for each file and then each\n// FileVisitor is streaming the content to a StreamVisitor. If ContinueOnError() is set\n// prior to this method being called, objects on the path that are unrecognized will be\n// ignored (but logged at V(2)).\nfunc (b *Builder) Path(recursive bool, paths ...string) *Builder {\n\tfor _, p := range paths {\n\t\t_, err := os.Stat(p)\n\t\tif os.IsNotExist(err) {\n\t\t\tb.errs = append(b.errs, fmt.Errorf(pathNotExistError, p))\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\tb.errs = append(b.errs, fmt.Errorf(\"the path %q cannot be accessed: %v\", p, err))\n\t\t\tcontinue\n\t\t}\n\n\t\tvisitors, err := ExpandPathsToFileVisitors(b.mapper, p, recursive, FileExtensions, b.schema)\n\t\tif err != nil {\n\t\t\tb.errs = append(b.errs, fmt.Errorf(\"error reading %q: %v\", p, err))\n\t\t}\n\t\tif len(visitors) \u003e 1 {\n\t\t\tb.dir = true\n\t\t}\n\n\t\tb.paths = append(b.paths, visitors...)\n\t}\n\tif len(b.paths) == 0 \u0026\u0026 len(b.errs) == 0 {\n\t\tb.errs = append(b.errs, fmt.Errorf(\"error reading %v: recognized file extensions are %v\", paths, FileExtensions))\n\t}\n\treturn b\n}","line":{"from":411,"to":442}} {"id":100019415,"name":"ResourceTypes","signature":"func (b *Builder) ResourceTypes(types ...string) *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// ResourceTypes is a list of types of resources to operate on, when listing objects on\n// the server or retrieving objects that match a selector.\nfunc (b *Builder) ResourceTypes(types ...string) *Builder {\n\tb.resources = append(b.resources, types...)\n\treturn b\n}","line":{"from":444,"to":449}} {"id":100019416,"name":"ResourceNames","signature":"func (b *Builder) ResourceNames(resource string, names ...string) *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// ResourceNames accepts a default type and one or more names, and creates tuples of\n// resources\nfunc (b *Builder) ResourceNames(resource string, names ...string) *Builder {\n\tfor _, name := range names {\n\t\t// See if this input string is of type/name format\n\t\ttuple, ok, err := splitResourceTypeName(name)\n\t\tif err != nil {\n\t\t\tb.errs = append(b.errs, err)\n\t\t\treturn b\n\t\t}\n\n\t\tif ok {\n\t\t\tb.resourceTuples = append(b.resourceTuples, tuple)\n\t\t\tcontinue\n\t\t}\n\t\tif len(resource) == 0 {\n\t\t\tb.errs = append(b.errs, fmt.Errorf(\"the argument %q must be RESOURCE/NAME\", name))\n\t\t\tcontinue\n\t\t}\n\n\t\t// Use the given default type to create a resource tuple\n\t\tb.resourceTuples = append(b.resourceTuples, resourceTuple{Resource: resource, Name: name})\n\t}\n\treturn b\n}","line":{"from":451,"to":475}} {"id":100019417,"name":"LabelSelectorParam","signature":"func (b *Builder) LabelSelectorParam(s string) *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// LabelSelectorParam defines a selector that should be applied to the object types to load.\n// This will not affect files loaded from disk or URL. If the parameter is empty it is\n// a no-op - to select all resources invoke `b.LabelSelector(labels.Everything.String)`.\nfunc (b *Builder) LabelSelectorParam(s string) *Builder {\n\tselector := strings.TrimSpace(s)\n\tif len(selector) == 0 {\n\t\treturn b\n\t}\n\tif b.selectAll {\n\t\tb.errs = append(b.errs, fmt.Errorf(\"found non-empty label selector %q with previously set 'all' parameter. \", s))\n\t\treturn b\n\t}\n\treturn b.LabelSelector(selector)\n}","line":{"from":477,"to":490}} {"id":100019418,"name":"LabelSelector","signature":"func (b *Builder) LabelSelector(selector string) *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// LabelSelector accepts a selector directly and will filter the resulting list by that object.\n// Use LabelSelectorParam instead for user input.\nfunc (b *Builder) LabelSelector(selector string) *Builder {\n\tif len(selector) == 0 {\n\t\treturn b\n\t}\n\n\tb.labelSelector = \u0026selector\n\treturn b\n}","line":{"from":492,"to":501}} {"id":100019419,"name":"FieldSelectorParam","signature":"func (b *Builder) FieldSelectorParam(s string) *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// FieldSelectorParam defines a selector that should be applied to the object types to load.\n// This will not affect files loaded from disk or URL. If the parameter is empty it is\n// a no-op - to select all resources.\nfunc (b *Builder) FieldSelectorParam(s string) *Builder {\n\ts = strings.TrimSpace(s)\n\tif len(s) == 0 {\n\t\treturn b\n\t}\n\tif b.selectAll {\n\t\tb.errs = append(b.errs, fmt.Errorf(\"found non-empty field selector %q with previously set 'all' parameter. \", s))\n\t\treturn b\n\t}\n\tb.fieldSelector = \u0026s\n\treturn b\n}","line":{"from":503,"to":517}} {"id":100019420,"name":"NamespaceParam","signature":"func (b *Builder) NamespaceParam(namespace string) *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// NamespaceParam accepts the namespace that these resources should be\n// considered under from - used by DefaultNamespace() and RequireNamespace()\nfunc (b *Builder) NamespaceParam(namespace string) *Builder {\n\tb.namespace = namespace\n\treturn b\n}","line":{"from":519,"to":524}} {"id":100019421,"name":"DefaultNamespace","signature":"func (b *Builder) DefaultNamespace() *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// DefaultNamespace instructs the builder to set the namespace value for any object found\n// to NamespaceParam() if empty.\nfunc (b *Builder) DefaultNamespace() *Builder {\n\tb.defaultNamespace = true\n\treturn b\n}","line":{"from":526,"to":531}} {"id":100019422,"name":"AllNamespaces","signature":"func (b *Builder) AllNamespaces(allNamespace bool) *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// AllNamespaces instructs the builder to metav1.NamespaceAll as a namespace to request resources\n// across all of the namespace. This overrides the namespace set by NamespaceParam().\nfunc (b *Builder) AllNamespaces(allNamespace bool) *Builder {\n\tif allNamespace {\n\t\tb.namespace = metav1.NamespaceAll\n\t}\n\tb.allNamespace = allNamespace\n\treturn b\n}","line":{"from":533,"to":541}} {"id":100019423,"name":"RequireNamespace","signature":"func (b *Builder) RequireNamespace() *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// RequireNamespace instructs the builder to set the namespace value for any object found\n// to NamespaceParam() if empty, and if the value on the resource does not match\n// NamespaceParam() an error will be returned.\nfunc (b *Builder) RequireNamespace() *Builder {\n\tb.requireNamespace = true\n\treturn b\n}","line":{"from":543,"to":549}} {"id":100019424,"name":"RequestChunksOf","signature":"func (b *Builder) RequestChunksOf(chunkSize int64) *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// RequestChunksOf attempts to load responses from the server in batches of size limit\n// to avoid long delays loading and transferring very large lists. If unset defaults to\n// no chunking.\nfunc (b *Builder) RequestChunksOf(chunkSize int64) *Builder {\n\tb.limitChunks = chunkSize\n\treturn b\n}","line":{"from":551,"to":557}} {"id":100019425,"name":"TransformRequests","signature":"func (b *Builder) TransformRequests(opts ...RequestTransform) *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// TransformRequests alters API calls made by clients requested from this builder. Pass\n// an empty list to clear modifiers.\nfunc (b *Builder) TransformRequests(opts ...RequestTransform) *Builder {\n\tb.requestTransforms = opts\n\treturn b\n}","line":{"from":559,"to":564}} {"id":100019426,"name":"Subresource","signature":"func (b *Builder) Subresource(subresource string) *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// Subresource instructs the builder to retrieve the object at the\n// subresource path instead of the main resource path.\nfunc (b *Builder) Subresource(subresource string) *Builder {\n\tb.subresource = subresource\n\treturn b\n}","line":{"from":566,"to":571}} {"id":100019427,"name":"SelectAllParam","signature":"func (b *Builder) SelectAllParam(selectAll bool) *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// SelectEverythingParam\nfunc (b *Builder) SelectAllParam(selectAll bool) *Builder {\n\tif selectAll \u0026\u0026 (b.labelSelector != nil || b.fieldSelector != nil) {\n\t\tb.errs = append(b.errs, fmt.Errorf(\"setting 'all' parameter but found a non empty selector. \"))\n\t\treturn b\n\t}\n\tb.selectAll = selectAll\n\treturn b\n}","line":{"from":573,"to":581}} {"id":100019428,"name":"ResourceTypeOrNameArgs","signature":"func (b *Builder) ResourceTypeOrNameArgs(allowEmptySelector bool, args ...string) *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// ResourceTypeOrNameArgs indicates that the builder should accept arguments\n// of the form `(\u003ctype1\u003e[,\u003ctype2\u003e,...]|\u003ctype\u003e \u003cname1\u003e[,\u003cname2\u003e,...])`. When one argument is\n// received, the types provided will be retrieved from the server (and be comma delimited).\n// When two or more arguments are received, they must be a single type and resource name(s).\n// The allowEmptySelector permits to select all the resources (via Everything func).\nfunc (b *Builder) ResourceTypeOrNameArgs(allowEmptySelector bool, args ...string) *Builder {\n\targs = normalizeMultipleResourcesArgs(args)\n\tif ok, err := hasCombinedTypeArgs(args); ok {\n\t\tif err != nil {\n\t\t\tb.errs = append(b.errs, err)\n\t\t\treturn b\n\t\t}\n\t\tfor _, s := range args {\n\t\t\ttuple, ok, err := splitResourceTypeName(s)\n\t\t\tif err != nil {\n\t\t\t\tb.errs = append(b.errs, err)\n\t\t\t\treturn b\n\t\t\t}\n\t\t\tif ok {\n\t\t\t\tb.resourceTuples = append(b.resourceTuples, tuple)\n\t\t\t}\n\t\t}\n\t\treturn b\n\t}\n\tif len(args) \u003e 0 {\n\t\t// Try replacing aliases only in types\n\t\targs[0] = b.ReplaceAliases(args[0])\n\t}\n\tswitch {\n\tcase len(args) \u003e 2:\n\t\tb.names = append(b.names, args[1:]...)\n\t\tb.ResourceTypes(SplitResourceArgument(args[0])...)\n\tcase len(args) == 2:\n\t\tb.names = append(b.names, args[1])\n\t\tb.ResourceTypes(SplitResourceArgument(args[0])...)\n\tcase len(args) == 1:\n\t\tb.ResourceTypes(SplitResourceArgument(args[0])...)\n\t\tif b.labelSelector == nil \u0026\u0026 allowEmptySelector {\n\t\t\tselector := labels.Everything().String()\n\t\t\tb.labelSelector = \u0026selector\n\t\t}\n\tcase len(args) == 0:\n\tdefault:\n\t\tb.errs = append(b.errs, fmt.Errorf(\"arguments must consist of a resource or a resource and name\"))\n\t}\n\treturn b\n}","line":{"from":583,"to":629}} {"id":100019429,"name":"ReplaceAliases","signature":"func (b *Builder) ReplaceAliases(input string) string","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// ReplaceAliases accepts an argument and tries to expand any existing\n// aliases found in it\nfunc (b *Builder) ReplaceAliases(input string) string {\n\treplaced := []string{}\n\tfor _, arg := range strings.Split(input, \",\") {\n\t\tif b.categoryExpanderFn == nil {\n\t\t\tcontinue\n\t\t}\n\t\tcategoryExpander, err := b.categoryExpanderFn()\n\t\tif err != nil {\n\t\t\tb.AddError(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif resources, ok := categoryExpander.Expand(arg); ok {\n\t\t\tasStrings := []string{}\n\t\t\tfor _, resource := range resources {\n\t\t\t\tif len(resource.Group) == 0 {\n\t\t\t\t\tasStrings = append(asStrings, resource.Resource)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tasStrings = append(asStrings, resource.Resource+\".\"+resource.Group)\n\t\t\t}\n\t\t\targ = strings.Join(asStrings, \",\")\n\t\t}\n\t\treplaced = append(replaced, arg)\n\t}\n\treturn strings.Join(replaced, \",\")\n}","line":{"from":631,"to":659}} {"id":100019430,"name":"hasCombinedTypeArgs","signature":"func hasCombinedTypeArgs(args []string) (bool, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"func hasCombinedTypeArgs(args []string) (bool, error) {\n\thasSlash := 0\n\tfor _, s := range args {\n\t\tif strings.Contains(s, \"/\") {\n\t\t\thasSlash++\n\t\t}\n\t}\n\tswitch {\n\tcase hasSlash \u003e 0 \u0026\u0026 hasSlash == len(args):\n\t\treturn true, nil\n\tcase hasSlash \u003e 0 \u0026\u0026 hasSlash != len(args):\n\t\tbaseCmd := \"cmd\"\n\t\tif len(os.Args) \u003e 0 {\n\t\t\tbaseCmdSlice := strings.Split(os.Args[0], \"/\")\n\t\t\tbaseCmd = baseCmdSlice[len(baseCmdSlice)-1]\n\t\t}\n\t\treturn true, fmt.Errorf(\"there is no need to specify a resource type as a separate argument when passing arguments in resource/name form (e.g. '%s get resource/\u003cresource_name\u003e' instead of '%s get resource resource/\u003cresource_name\u003e'\", baseCmd, baseCmd)\n\tdefault:\n\t\treturn false, nil\n\t}\n}","line":{"from":661,"to":681}} {"id":100019431,"name":"normalizeMultipleResourcesArgs","signature":"func normalizeMultipleResourcesArgs(args []string) []string","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// Normalize args convert multiple resources to resource tuples, a,b,c d\n// as a transform to a/d b/d c/d\nfunc normalizeMultipleResourcesArgs(args []string) []string {\n\tif len(args) \u003e= 2 {\n\t\tresources := []string{}\n\t\tresources = append(resources, SplitResourceArgument(args[0])...)\n\t\tif len(resources) \u003e 1 {\n\t\t\tnames := []string{}\n\t\t\tnames = append(names, args[1:]...)\n\t\t\tnewArgs := []string{}\n\t\t\tfor _, resource := range resources {\n\t\t\t\tfor _, name := range names {\n\t\t\t\t\tnewArgs = append(newArgs, strings.Join([]string{resource, name}, \"/\"))\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn newArgs\n\t\t}\n\t}\n\treturn args\n}","line":{"from":683,"to":702}} {"id":100019432,"name":"splitResourceTypeName","signature":"func splitResourceTypeName(s string) (resourceTuple, bool, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// splitResourceTypeName handles type/name resource formats and returns a resource tuple\n// (empty or not), whether it successfully found one, and an error\nfunc splitResourceTypeName(s string) (resourceTuple, bool, error) {\n\tif !strings.Contains(s, \"/\") {\n\t\treturn resourceTuple{}, false, nil\n\t}\n\tseg := strings.Split(s, \"/\")\n\tif len(seg) != 2 {\n\t\treturn resourceTuple{}, false, fmt.Errorf(\"arguments in resource/name form may not have more than one slash\")\n\t}\n\tresource, name := seg[0], seg[1]\n\tif len(resource) == 0 || len(name) == 0 || len(SplitResourceArgument(resource)) != 1 {\n\t\treturn resourceTuple{}, false, fmt.Errorf(\"arguments in resource/name form must have a single resource and name\")\n\t}\n\treturn resourceTuple{Resource: resource, Name: name}, true, nil\n}","line":{"from":704,"to":719}} {"id":100019433,"name":"Flatten","signature":"func (b *Builder) Flatten() *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// Flatten will convert any objects with a field named \"Items\" that is an array of runtime.Object\n// compatible types into individual entries and give them their own items. The original object\n// is not passed to any visitors.\nfunc (b *Builder) Flatten() *Builder {\n\tb.flatten = true\n\treturn b\n}","line":{"from":721,"to":727}} {"id":100019434,"name":"Latest","signature":"func (b *Builder) Latest() *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// Latest will fetch the latest copy of any objects loaded from URLs or files from the server.\nfunc (b *Builder) Latest() *Builder {\n\tb.latest = true\n\treturn b\n}","line":{"from":729,"to":733}} {"id":100019435,"name":"RequireObject","signature":"func (b *Builder) RequireObject(require bool) *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// RequireObject ensures that resulting infos have an object set. If false, resulting info may not have an object set.\nfunc (b *Builder) RequireObject(require bool) *Builder {\n\tb.requireObject = require\n\treturn b\n}","line":{"from":735,"to":739}} {"id":100019436,"name":"ContinueOnError","signature":"func (b *Builder) ContinueOnError() *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// ContinueOnError will attempt to load and visit as many objects as possible, even if some visits\n// return errors or some objects cannot be loaded. The default behavior is to terminate after\n// the first error is returned from a VisitorFunc.\nfunc (b *Builder) ContinueOnError() *Builder {\n\tb.continueOnError = true\n\treturn b\n}","line":{"from":741,"to":747}} {"id":100019437,"name":"SingleResourceType","signature":"func (b *Builder) SingleResourceType() *Builder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// SingleResourceType will cause the builder to error if the user specifies more than a single type\n// of resource.\nfunc (b *Builder) SingleResourceType() *Builder {\n\tb.singleResourceType = true\n\treturn b\n}","line":{"from":749,"to":754}} {"id":100019438,"name":"mappingFor","signature":"func (b *Builder) mappingFor(resourceOrKindArg string) (*meta.RESTMapping, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// mappingFor returns the RESTMapping for the Kind given, or the Kind referenced by the resource.\n// Prefers a fully specified GroupVersionResource match. If one is not found, we match on a fully\n// specified GroupVersionKind, or fallback to a match on GroupKind.\nfunc (b *Builder) mappingFor(resourceOrKindArg string) (*meta.RESTMapping, error) {\n\tfullySpecifiedGVR, groupResource := schema.ParseResourceArg(resourceOrKindArg)\n\tgvk := schema.GroupVersionKind{}\n\trestMapper, err := b.restMapperFn()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif fullySpecifiedGVR != nil {\n\t\tgvk, _ = restMapper.KindFor(*fullySpecifiedGVR)\n\t}\n\tif gvk.Empty() {\n\t\tgvk, _ = restMapper.KindFor(groupResource.WithVersion(\"\"))\n\t}\n\tif !gvk.Empty() {\n\t\treturn restMapper.RESTMapping(gvk.GroupKind(), gvk.Version)\n\t}\n\n\tfullySpecifiedGVK, groupKind := schema.ParseKindArg(resourceOrKindArg)\n\tif fullySpecifiedGVK == nil {\n\t\tgvk := groupKind.WithVersion(\"\")\n\t\tfullySpecifiedGVK = \u0026gvk\n\t}\n\n\tif !fullySpecifiedGVK.Empty() {\n\t\tif mapping, err := restMapper.RESTMapping(fullySpecifiedGVK.GroupKind(), fullySpecifiedGVK.Version); err == nil {\n\t\t\treturn mapping, nil\n\t\t}\n\t}\n\n\tmapping, err := restMapper.RESTMapping(groupKind, gvk.Version)\n\tif err != nil {\n\t\t// if we error out here, it is because we could not match a resource or a kind\n\t\t// for the given argument. To maintain consistency with previous behavior,\n\t\t// announce that a resource type could not be found.\n\t\t// if the error is _not_ a *meta.NoKindMatchError, then we had trouble doing discovery,\n\t\t// so we should return the original error since it may help a user diagnose what is actually wrong\n\t\tif meta.IsNoMatchError(err) {\n\t\t\treturn nil, fmt.Errorf(\"the server doesn't have a resource type %q\", groupResource.Resource)\n\t\t}\n\t\treturn nil, err\n\t}\n\n\treturn mapping, nil\n}","line":{"from":756,"to":803}} {"id":100019439,"name":"resourceMappings","signature":"func (b *Builder) resourceMappings() ([]*meta.RESTMapping, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"func (b *Builder) resourceMappings() ([]*meta.RESTMapping, error) {\n\tif len(b.resources) \u003e 1 \u0026\u0026 b.singleResourceType {\n\t\treturn nil, fmt.Errorf(\"you may only specify a single resource type\")\n\t}\n\tmappings := []*meta.RESTMapping{}\n\tseen := map[schema.GroupVersionKind]bool{}\n\tfor _, r := range b.resources {\n\t\tmapping, err := b.mappingFor(r)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// This ensures the mappings for resources(shortcuts, plural) unique\n\t\tif seen[mapping.GroupVersionKind] {\n\t\t\tcontinue\n\t\t}\n\t\tseen[mapping.GroupVersionKind] = true\n\n\t\tmappings = append(mappings, mapping)\n\t}\n\treturn mappings, nil\n}","line":{"from":805,"to":825}} {"id":100019440,"name":"resourceTupleMappings","signature":"func (b *Builder) resourceTupleMappings() (map[string]*meta.RESTMapping, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"func (b *Builder) resourceTupleMappings() (map[string]*meta.RESTMapping, error) {\n\tmappings := make(map[string]*meta.RESTMapping)\n\tcanonical := make(map[schema.GroupVersionResource]struct{})\n\tfor _, r := range b.resourceTuples {\n\t\tif _, ok := mappings[r.Resource]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tmapping, err := b.mappingFor(r.Resource)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tmappings[r.Resource] = mapping\n\t\tcanonical[mapping.Resource] = struct{}{}\n\t}\n\tif len(canonical) \u003e 1 \u0026\u0026 b.singleResourceType {\n\t\treturn nil, fmt.Errorf(\"you may only specify a single resource type\")\n\t}\n\treturn mappings, nil\n}","line":{"from":827,"to":846}} {"id":100019441,"name":"visitorResult","signature":"func (b *Builder) visitorResult() *Result","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"func (b *Builder) visitorResult() *Result {\n\tif len(b.errs) \u003e 0 {\n\t\treturn \u0026Result{err: utilerrors.NewAggregate(b.errs)}\n\t}\n\n\tif b.selectAll {\n\t\tselector := labels.Everything().String()\n\t\tb.labelSelector = \u0026selector\n\t}\n\n\t// visit items specified by paths\n\tif len(b.paths) != 0 {\n\t\treturn b.visitByPaths()\n\t}\n\n\t// visit selectors\n\tif b.labelSelector != nil || b.fieldSelector != nil {\n\t\treturn b.visitBySelector()\n\t}\n\n\t// visit items specified by resource and name\n\tif len(b.resourceTuples) != 0 {\n\t\treturn b.visitByResource()\n\t}\n\n\t// visit items specified by name\n\tif len(b.names) != 0 {\n\t\treturn b.visitByName()\n\t}\n\n\tif len(b.resources) != 0 {\n\t\tfor _, r := range b.resources {\n\t\t\t_, err := b.mappingFor(r)\n\t\t\tif err != nil {\n\t\t\t\treturn \u0026Result{err: err}\n\t\t\t}\n\t\t}\n\t\treturn \u0026Result{err: fmt.Errorf(\"resource(s) were provided, but no name was specified\")}\n\t}\n\treturn \u0026Result{err: missingResourceError}\n}","line":{"from":848,"to":888}} {"id":100019442,"name":"visitBySelector","signature":"func (b *Builder) visitBySelector() *Result","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"func (b *Builder) visitBySelector() *Result {\n\tresult := \u0026Result{\n\t\ttargetsSingleItems: false,\n\t}\n\n\tif len(b.names) != 0 {\n\t\treturn result.withError(fmt.Errorf(\"name cannot be provided when a selector is specified\"))\n\t}\n\tif len(b.resourceTuples) != 0 {\n\t\treturn result.withError(fmt.Errorf(\"selectors and the all flag cannot be used when passing resource/name arguments\"))\n\t}\n\tif len(b.resources) == 0 {\n\t\treturn result.withError(fmt.Errorf(\"at least one resource must be specified to use a selector\"))\n\t}\n\tif len(b.subresource) != 0 {\n\t\treturn result.withError(fmt.Errorf(\"subresource cannot be used when bulk resources are specified\"))\n\t}\n\n\tmappings, err := b.resourceMappings()\n\tif err != nil {\n\t\tresult.err = err\n\t\treturn result\n\t}\n\n\tvar labelSelector, fieldSelector string\n\tif b.labelSelector != nil {\n\t\tlabelSelector = *b.labelSelector\n\t}\n\tif b.fieldSelector != nil {\n\t\tfieldSelector = *b.fieldSelector\n\t}\n\n\tvisitors := []Visitor{}\n\tfor _, mapping := range mappings {\n\t\tclient, err := b.getClient(mapping.GroupVersionKind.GroupVersion())\n\t\tif err != nil {\n\t\t\tresult.err = err\n\t\t\treturn result\n\t\t}\n\t\tselectorNamespace := b.namespace\n\t\tif mapping.Scope.Name() != meta.RESTScopeNameNamespace {\n\t\t\tselectorNamespace = \"\"\n\t\t}\n\t\tvisitors = append(visitors, NewSelector(client, mapping, selectorNamespace, labelSelector, fieldSelector, b.limitChunks))\n\t}\n\tif b.continueOnError {\n\t\tresult.visitor = EagerVisitorList(visitors)\n\t} else {\n\t\tresult.visitor = VisitorList(visitors)\n\t}\n\tresult.sources = visitors\n\treturn result\n}","line":{"from":890,"to":942}} {"id":100019443,"name":"getClient","signature":"func (b *Builder) getClient(gv schema.GroupVersion) (RESTClient, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"func (b *Builder) getClient(gv schema.GroupVersion) (RESTClient, error) {\n\tvar (\n\t\tclient RESTClient\n\t\terr error\n\t)\n\n\tswitch {\n\tcase b.fakeClientFn != nil:\n\t\tclient, err = b.fakeClientFn(gv)\n\tcase b.negotiatedSerializer != nil:\n\t\tclient, err = b.clientConfigFn.withStdinUnavailable(b.stdinInUse).clientForGroupVersion(gv, b.negotiatedSerializer)\n\tdefault:\n\t\tclient, err = b.clientConfigFn.withStdinUnavailable(b.stdinInUse).unstructuredClientForGroupVersion(gv)\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewClientWithOptions(client, b.requestTransforms...), nil\n}","line":{"from":944,"to":964}} {"id":100019444,"name":"visitByResource","signature":"func (b *Builder) visitByResource() *Result","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"func (b *Builder) visitByResource() *Result {\n\t// if b.singleItemImplied is false, this could be by default, so double-check length\n\t// of resourceTuples to determine if in fact it is singleItemImplied or not\n\tisSingleItemImplied := b.singleItemImplied\n\tif !isSingleItemImplied {\n\t\tisSingleItemImplied = len(b.resourceTuples) == 1\n\t}\n\n\tresult := \u0026Result{\n\t\tsingleItemImplied: isSingleItemImplied,\n\t\ttargetsSingleItems: true,\n\t}\n\n\tif len(b.resources) != 0 {\n\t\treturn result.withError(fmt.Errorf(\"you may not specify individual resources and bulk resources in the same call\"))\n\t}\n\n\t// retrieve one client for each resource\n\tmappings, err := b.resourceTupleMappings()\n\tif err != nil {\n\t\tresult.err = err\n\t\treturn result\n\t}\n\tclients := make(map[string]RESTClient)\n\tfor _, mapping := range mappings {\n\t\ts := fmt.Sprintf(\"%s/%s\", mapping.GroupVersionKind.GroupVersion().String(), mapping.Resource.Resource)\n\t\tif _, ok := clients[s]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tclient, err := b.getClient(mapping.GroupVersionKind.GroupVersion())\n\t\tif err != nil {\n\t\t\tresult.err = err\n\t\t\treturn result\n\t\t}\n\t\tclients[s] = client\n\t}\n\n\titems := []Visitor{}\n\tfor _, tuple := range b.resourceTuples {\n\t\tmapping, ok := mappings[tuple.Resource]\n\t\tif !ok {\n\t\t\treturn result.withError(fmt.Errorf(\"resource %q is not recognized: %v\", tuple.Resource, mappings))\n\t\t}\n\t\ts := fmt.Sprintf(\"%s/%s\", mapping.GroupVersionKind.GroupVersion().String(), mapping.Resource.Resource)\n\t\tclient, ok := clients[s]\n\t\tif !ok {\n\t\t\treturn result.withError(fmt.Errorf(\"could not find a client for resource %q\", tuple.Resource))\n\t\t}\n\n\t\tselectorNamespace := b.namespace\n\t\tif mapping.Scope.Name() != meta.RESTScopeNameNamespace {\n\t\t\tselectorNamespace = \"\"\n\t\t} else {\n\t\t\tif len(b.namespace) == 0 {\n\t\t\t\terrMsg := \"namespace may not be empty when retrieving a resource by name\"\n\t\t\t\tif b.allNamespace {\n\t\t\t\t\terrMsg = \"a resource cannot be retrieved by name across all namespaces\"\n\t\t\t\t}\n\t\t\t\treturn result.withError(fmt.Errorf(errMsg))\n\t\t\t}\n\t\t}\n\n\t\tinfo := \u0026Info{\n\t\t\tClient: client,\n\t\t\tMapping: mapping,\n\t\t\tNamespace: selectorNamespace,\n\t\t\tName: tuple.Name,\n\t\t\tSubresource: b.subresource,\n\t\t}\n\t\titems = append(items, info)\n\t}\n\n\tvar visitors Visitor\n\tif b.continueOnError {\n\t\tvisitors = EagerVisitorList(items)\n\t} else {\n\t\tvisitors = VisitorList(items)\n\t}\n\tresult.visitor = visitors\n\tresult.sources = items\n\treturn result\n}","line":{"from":966,"to":1047}} {"id":100019445,"name":"visitByName","signature":"func (b *Builder) visitByName() *Result","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"func (b *Builder) visitByName() *Result {\n\tresult := \u0026Result{\n\t\tsingleItemImplied: len(b.names) == 1,\n\t\ttargetsSingleItems: true,\n\t}\n\n\tif len(b.paths) != 0 {\n\t\treturn result.withError(fmt.Errorf(\"when paths, URLs, or stdin is provided as input, you may not specify a resource by arguments as well\"))\n\t}\n\tif len(b.resources) == 0 {\n\t\treturn result.withError(fmt.Errorf(\"you must provide a resource and a resource name together\"))\n\t}\n\tif len(b.resources) \u003e 1 {\n\t\treturn result.withError(fmt.Errorf(\"you must specify only one resource\"))\n\t}\n\n\tmappings, err := b.resourceMappings()\n\tif err != nil {\n\t\tresult.err = err\n\t\treturn result\n\t}\n\tmapping := mappings[0]\n\n\tclient, err := b.getClient(mapping.GroupVersionKind.GroupVersion())\n\tif err != nil {\n\t\tresult.err = err\n\t\treturn result\n\t}\n\n\tselectorNamespace := b.namespace\n\tif mapping.Scope.Name() != meta.RESTScopeNameNamespace {\n\t\tselectorNamespace = \"\"\n\t} else {\n\t\tif len(b.namespace) == 0 {\n\t\t\terrMsg := \"namespace may not be empty when retrieving a resource by name\"\n\t\t\tif b.allNamespace {\n\t\t\t\terrMsg = \"a resource cannot be retrieved by name across all namespaces\"\n\t\t\t}\n\t\t\treturn result.withError(fmt.Errorf(errMsg))\n\t\t}\n\t}\n\n\tvisitors := []Visitor{}\n\tfor _, name := range b.names {\n\t\tinfo := \u0026Info{\n\t\t\tClient: client,\n\t\t\tMapping: mapping,\n\t\t\tNamespace: selectorNamespace,\n\t\t\tName: name,\n\t\t\tSubresource: b.subresource,\n\t\t}\n\t\tvisitors = append(visitors, info)\n\t}\n\tresult.visitor = VisitorList(visitors)\n\tresult.sources = visitors\n\treturn result\n}","line":{"from":1049,"to":1105}} {"id":100019446,"name":"visitByPaths","signature":"func (b *Builder) visitByPaths() *Result","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"func (b *Builder) visitByPaths() *Result {\n\tresult := \u0026Result{\n\t\tsingleItemImplied: !b.dir \u0026\u0026 !b.stream \u0026\u0026 len(b.paths) == 1,\n\t\ttargetsSingleItems: true,\n\t}\n\n\tif len(b.resources) != 0 {\n\t\treturn result.withError(fmt.Errorf(\"when paths, URLs, or stdin is provided as input, you may not specify resource arguments as well\"))\n\t}\n\tif len(b.names) != 0 {\n\t\treturn result.withError(fmt.Errorf(\"name cannot be provided when a path is specified\"))\n\t}\n\tif len(b.resourceTuples) != 0 {\n\t\treturn result.withError(fmt.Errorf(\"resource/name arguments cannot be provided when a path is specified\"))\n\t}\n\n\tvar visitors Visitor\n\tif b.continueOnError {\n\t\tvisitors = EagerVisitorList(b.paths)\n\t} else {\n\t\tvisitors = VisitorList(b.paths)\n\t}\n\n\tif b.flatten {\n\t\tvisitors = NewFlattenListVisitor(visitors, b.objectTyper, b.mapper)\n\t}\n\n\t// only items from disk can be refetched\n\tif b.latest {\n\t\t// must set namespace prior to fetching\n\t\tif b.defaultNamespace {\n\t\t\tvisitors = NewDecoratedVisitor(visitors, SetNamespace(b.namespace))\n\t\t}\n\t\tvisitors = NewDecoratedVisitor(visitors, RetrieveLatest)\n\t}\n\tif b.labelSelector != nil {\n\t\tselector, err := labels.Parse(*b.labelSelector)\n\t\tif err != nil {\n\t\t\treturn result.withError(fmt.Errorf(\"the provided selector %q is not valid: %v\", *b.labelSelector, err))\n\t\t}\n\t\tvisitors = NewFilteredVisitor(visitors, FilterByLabelSelector(selector))\n\t}\n\tresult.visitor = visitors\n\tresult.sources = b.paths\n\treturn result\n}","line":{"from":1107,"to":1152}} {"id":100019447,"name":"Do","signature":"func (b *Builder) Do() *Result","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// Do returns a Result object with a Visitor for the resources identified by the Builder.\n// The visitor will respect the error behavior specified by ContinueOnError. Note that stream\n// inputs are consumed by the first execution - use Infos() or Object() on the Result to capture a list\n// for further iteration.\nfunc (b *Builder) Do() *Result {\n\tr := b.visitorResult()\n\tr.mapper = b.Mapper()\n\tif r.err != nil {\n\t\treturn r\n\t}\n\tif b.flatten {\n\t\tr.visitor = NewFlattenListVisitor(r.visitor, b.objectTyper, b.mapper)\n\t}\n\thelpers := []VisitorFunc{}\n\tif b.defaultNamespace {\n\t\thelpers = append(helpers, SetNamespace(b.namespace))\n\t}\n\tif b.requireNamespace {\n\t\thelpers = append(helpers, RequireNamespace(b.namespace))\n\t}\n\thelpers = append(helpers, FilterNamespace)\n\tif b.requireObject {\n\t\thelpers = append(helpers, RetrieveLazy)\n\t}\n\tif b.continueOnError {\n\t\tr.visitor = ContinueOnErrorVisitor{Visitor: r.visitor}\n\t}\n\tr.visitor = NewDecoratedVisitor(r.visitor, helpers...)\n\treturn r\n}","line":{"from":1154,"to":1183}} {"id":100019448,"name":"SplitResourceArgument","signature":"func SplitResourceArgument(arg string) []string","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// SplitResourceArgument splits the argument with commas and returns unique\n// strings in the original order.\nfunc SplitResourceArgument(arg string) []string {\n\tout := []string{}\n\tset := sets.NewString()\n\tfor _, s := range strings.Split(arg, \",\") {\n\t\tif set.Has(s) {\n\t\t\tcontinue\n\t\t}\n\t\tset.Insert(s)\n\t\tout = append(out, s)\n\t}\n\treturn out\n}","line":{"from":1185,"to":1198}} {"id":100019449,"name":"HasNames","signature":"func HasNames(args []string) (bool, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// HasNames returns true if the provided args contain resource names\nfunc HasNames(args []string) (bool, error) {\n\targs = normalizeMultipleResourcesArgs(args)\n\thasCombinedTypes, err := hasCombinedTypeArgs(args)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn hasCombinedTypes || len(args) \u003e 1, nil\n}","line":{"from":1200,"to":1208}} {"id":100019450,"name":"expandIfFilePattern","signature":"func expandIfFilePattern(pattern string) ([]string, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"// expandIfFilePattern returns all the filenames that match the input pattern\n// or the filename if it is a specific filename and not a pattern.\n// If the input is a pattern and it yields no result it will result in an error.\nfunc expandIfFilePattern(pattern string) ([]string, error) {\n\tif _, err := os.Stat(pattern); os.IsNotExist(err) {\n\t\tmatches, err := filepath.Glob(pattern)\n\t\tif err == nil \u0026\u0026 len(matches) == 0 {\n\t\t\treturn nil, fmt.Errorf(pathNotExistError, pattern)\n\t\t}\n\t\tif err == filepath.ErrBadPattern {\n\t\t\treturn nil, fmt.Errorf(\"pattern %q is not valid: %v\", pattern, err)\n\t\t}\n\t\treturn matches, err\n\t}\n\treturn []string{pattern}, nil\n}","line":{"from":1210,"to":1225}} {"id":100019451,"name":"ToCategoryExpander","signature":"func (c *cachingCategoryExpanderFunc) ToCategoryExpander() (restmapper.CategoryExpander, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/builder.go","code":"func (c *cachingCategoryExpanderFunc) ToCategoryExpander() (restmapper.CategoryExpander, error) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tif c.cached != nil {\n\t\treturn c.cached, nil\n\t}\n\n\tret, err := c.delegate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.cached = ret\n\treturn c.cached, nil\n}","line":{"from":1234,"to":1247}} {"id":100019452,"name":"clientForGroupVersion","signature":"func (clientConfigFn ClientConfigFunc) clientForGroupVersion(gv schema.GroupVersion, negotiatedSerializer runtime.NegotiatedSerializer) (RESTClient, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/client.go","code":"// TODO require negotiatedSerializer. leaving it optional lets us plumb current behavior and deal with the difference after major plumbing is complete\nfunc (clientConfigFn ClientConfigFunc) clientForGroupVersion(gv schema.GroupVersion, negotiatedSerializer runtime.NegotiatedSerializer) (RESTClient, error) {\n\tcfg, err := clientConfigFn()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif negotiatedSerializer != nil {\n\t\tcfg.ContentConfig.NegotiatedSerializer = negotiatedSerializer\n\t}\n\tcfg.GroupVersion = \u0026gv\n\tif len(gv.Group) == 0 {\n\t\tcfg.APIPath = \"/api\"\n\t} else {\n\t\tcfg.APIPath = \"/apis\"\n\t}\n\n\treturn rest.RESTClientFor(cfg)\n}","line":{"from":25,"to":42}} {"id":100019453,"name":"unstructuredClientForGroupVersion","signature":"func (clientConfigFn ClientConfigFunc) unstructuredClientForGroupVersion(gv schema.GroupVersion) (RESTClient, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/client.go","code":"func (clientConfigFn ClientConfigFunc) unstructuredClientForGroupVersion(gv schema.GroupVersion) (RESTClient, error) {\n\tcfg, err := clientConfigFn()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcfg.ContentConfig = UnstructuredPlusDefaultContentConfig()\n\tcfg.GroupVersion = \u0026gv\n\tif len(gv.Group) == 0 {\n\t\tcfg.APIPath = \"/api\"\n\t} else {\n\t\tcfg.APIPath = \"/apis\"\n\t}\n\n\treturn rest.RESTClientFor(cfg)\n}","line":{"from":44,"to":58}} {"id":100019454,"name":"withStdinUnavailable","signature":"func (clientConfigFn ClientConfigFunc) withStdinUnavailable(stdinUnavailable bool) ClientConfigFunc","file":"staging/src/k8s.io/cli-runtime/pkg/resource/client.go","code":"func (clientConfigFn ClientConfigFunc) withStdinUnavailable(stdinUnavailable bool) ClientConfigFunc {\n\treturn func() (*rest.Config, error) {\n\t\tcfg, err := clientConfigFn()\n\t\tif stdinUnavailable \u0026\u0026 cfg != nil \u0026\u0026 cfg.ExecProvider != nil {\n\t\t\tcfg.ExecProvider.StdinUnavailable = stdinUnavailable\n\t\t\tcfg.ExecProvider.StdinUnavailableMessage = \"used by stdin resource manifest reader\"\n\t\t}\n\t\treturn cfg, err\n\t}\n}","line":{"from":60,"to":69}} {"id":100019455,"name":"CRDFromDynamic","signature":"func CRDFromDynamic(client dynamic.Interface) CRDGetter","file":"staging/src/k8s.io/cli-runtime/pkg/resource/crd_finder.go","code":"func CRDFromDynamic(client dynamic.Interface) CRDGetter {\n\treturn func() ([]schema.GroupKind, error) {\n\t\tlist, err := client.Resource(schema.GroupVersionResource{\n\t\t\tGroup: \"apiextensions.k8s.io\",\n\t\t\tVersion: \"v1\",\n\t\t\tResource: \"customresourcedefinitions\",\n\t\t}).List(context.TODO(), metav1.ListOptions{})\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to list CRDs: %v\", err)\n\t\t}\n\t\tif list == nil {\n\t\t\treturn nil, nil\n\t\t}\n\n\t\tgks := []schema.GroupKind{}\n\n\t\t// We need to parse the list to get the gvk, I guess that's fine.\n\t\tfor _, crd := range (*list).Items {\n\t\t\t// Look for group, version, and kind\n\t\t\tgroup, _, _ := unstructured.NestedString(crd.Object, \"spec\", \"group\")\n\t\t\tkind, _, _ := unstructured.NestedString(crd.Object, \"spec\", \"names\", \"kind\")\n\n\t\t\tgks = append(gks, schema.GroupKind{\n\t\t\t\tGroup: group,\n\t\t\t\tKind: kind,\n\t\t\t})\n\t\t}\n\n\t\treturn gks, nil\n\t}\n}","line":{"from":34,"to":64}} {"id":100019456,"name":"NewCRDFinder","signature":"func NewCRDFinder(getter CRDGetter) CRDFinder","file":"staging/src/k8s.io/cli-runtime/pkg/resource/crd_finder.go","code":"func NewCRDFinder(getter CRDGetter) CRDFinder {\n\treturn \u0026crdFinder{\n\t\tgetter: getter,\n\t}\n}","line":{"from":72,"to":76}} {"id":100019457,"name":"cacheCRDs","signature":"func (f *crdFinder) cacheCRDs() error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/crd_finder.go","code":"func (f *crdFinder) cacheCRDs() error {\n\tif f.cache != nil {\n\t\treturn nil\n\t}\n\n\tlist, err := f.getter()\n\tif err != nil {\n\t\treturn err\n\t}\n\tf.cache = \u0026list\n\treturn nil\n}","line":{"from":83,"to":94}} {"id":100019458,"name":"findCRD","signature":"func (f *crdFinder) findCRD(gvk schema.GroupKind) bool","file":"staging/src/k8s.io/cli-runtime/pkg/resource/crd_finder.go","code":"func (f *crdFinder) findCRD(gvk schema.GroupKind) bool {\n\tfor _, crd := range *f.cache {\n\t\tif reflect.DeepEqual(gvk, crd) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":96,"to":103}} {"id":100019459,"name":"HasCRD","signature":"func (f *crdFinder) HasCRD(gvk schema.GroupKind) (bool, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/crd_finder.go","code":"func (f *crdFinder) HasCRD(gvk schema.GroupKind) (bool, error) {\n\tif err := f.cacheCRDs(); err != nil {\n\t\treturn false, err\n\t}\n\treturn f.findCRD(gvk), nil\n}","line":{"from":105,"to":110}} {"id":100019460,"name":"NewFallbackQueryParamVerifier","signature":"func NewFallbackQueryParamVerifier(primary Verifier, secondary Verifier) Verifier","file":"staging/src/k8s.io/cli-runtime/pkg/resource/fallback_query_param_verifier.go","code":"// NewFallbackQueryParamVerifier returns a new Verifier which will invoke the\n// initial/primary Verifier. If the primary Verifier is \"NotFound\", then the\n// secondary Verifier is invoked as a fallback.\nfunc NewFallbackQueryParamVerifier(primary Verifier, secondary Verifier) Verifier {\n\treturn \u0026fallbackQueryParamVerifier{\n\t\tprimary: primary,\n\t\tsecondary: secondary,\n\t}\n}","line":{"from":33,"to":41}} {"id":100019461,"name":"HasSupport","signature":"func (f *fallbackQueryParamVerifier) HasSupport(gvk schema.GroupVersionKind) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/fallback_query_param_verifier.go","code":"// HasSupport returns an error if the passed GVK does not support the\n// query param (fieldValidation), as determined by the primary and\n// secondary OpenAPI endpoints. The primary endoint is checked first,\n// but if there is an error retrieving the OpenAPI V3 document, the\n// secondary attempts to determine support. If the GVK supports the query param,\n// nil is returned.\nfunc (f *fallbackQueryParamVerifier) HasSupport(gvk schema.GroupVersionKind) error {\n\terr := f.primary.HasSupport(gvk)\n\t// If an error was returned from the primary OpenAPI endpoint,\n\t// we fallback to check the secondary OpenAPI endpoint for\n\t// any error *except* \"paramUnsupportedError\".\n\tif err != nil \u0026\u0026 !IsParamUnsupportedError(err) {\n\t\tklog.V(7).Infof(\"openapi v3 error...falling back to legacy: %s\", err)\n\t\terr = f.secondary.HasSupport(gvk)\n\t}\n\treturn err\n}","line":{"from":43,"to":59}} {"id":100019462,"name":"NewHelper","signature":"func NewHelper(client RESTClient, mapping *meta.RESTMapping) *Helper","file":"staging/src/k8s.io/cli-runtime/pkg/resource/helper.go","code":"// NewHelper creates a Helper from a ResourceMapping\nfunc NewHelper(client RESTClient, mapping *meta.RESTMapping) *Helper {\n\treturn \u0026Helper{\n\t\tResource: mapping.Resource.Resource,\n\t\tRESTClient: client,\n\t\tNamespaceScoped: mapping.Scope.Name() == meta.RESTScopeNameNamespace,\n\t}\n}","line":{"from":63,"to":70}} {"id":100019463,"name":"DryRun","signature":"func (m *Helper) DryRun(dryRun bool) *Helper","file":"staging/src/k8s.io/cli-runtime/pkg/resource/helper.go","code":"// DryRun, if true, will use server-side dry-run to not persist changes to storage.\n// Otherwise, changes will be persisted to storage.\nfunc (m *Helper) DryRun(dryRun bool) *Helper {\n\tm.ServerDryRun = dryRun\n\treturn m\n}","line":{"from":72,"to":77}} {"id":100019464,"name":"WithFieldManager","signature":"func (m *Helper) WithFieldManager(fieldManager string) *Helper","file":"staging/src/k8s.io/cli-runtime/pkg/resource/helper.go","code":"// WithFieldManager sets the field manager option to indicate the actor or entity\n// that is making changes in a create or update operation.\nfunc (m *Helper) WithFieldManager(fieldManager string) *Helper {\n\tm.FieldManager = fieldManager\n\treturn m\n}","line":{"from":79,"to":84}} {"id":100019465,"name":"WithFieldValidation","signature":"func (m *Helper) WithFieldValidation(validationDirective string) *Helper","file":"staging/src/k8s.io/cli-runtime/pkg/resource/helper.go","code":"// WithFieldValidation sets the field validation option to indicate\n// how the server should perform field validation (Ignore, Warn, or Strict).\nfunc (m *Helper) WithFieldValidation(validationDirective string) *Helper {\n\tm.FieldValidation = validationDirective\n\treturn m\n}","line":{"from":86,"to":91}} {"id":100019466,"name":"WithSubresource","signature":"func (m *Helper) WithSubresource(subresource string) *Helper","file":"staging/src/k8s.io/cli-runtime/pkg/resource/helper.go","code":"// Subresource sets the helper to access (\u003cresource\u003e/[ns/\u003cnamespace\u003e/]\u003cname\u003e/\u003csubresource\u003e)\nfunc (m *Helper) WithSubresource(subresource string) *Helper {\n\tm.Subresource = subresource\n\treturn m\n}","line":{"from":93,"to":97}} {"id":100019467,"name":"Get","signature":"func (m *Helper) Get(namespace, name string) (runtime.Object, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/helper.go","code":"func (m *Helper) Get(namespace, name string) (runtime.Object, error) {\n\treq := m.RESTClient.Get().\n\t\tNamespaceIfScoped(namespace, m.NamespaceScoped).\n\t\tResource(m.Resource).\n\t\tName(name).\n\t\tSubResource(m.Subresource)\n\treturn req.Do(context.TODO()).Get()\n}","line":{"from":99,"to":106}} {"id":100019468,"name":"List","signature":"func (m *Helper) List(namespace, apiVersion string, options *metav1.ListOptions) (runtime.Object, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/helper.go","code":"func (m *Helper) List(namespace, apiVersion string, options *metav1.ListOptions) (runtime.Object, error) {\n\treq := m.RESTClient.Get().\n\t\tNamespaceIfScoped(namespace, m.NamespaceScoped).\n\t\tResource(m.Resource).\n\t\tVersionedParams(options, metav1.ParameterCodec)\n\treturn req.Do(context.TODO()).Get()\n}","line":{"from":108,"to":114}} {"id":100019469,"name":"FollowContinue","signature":"func FollowContinue(initialOpts *metav1.ListOptions,","file":"staging/src/k8s.io/cli-runtime/pkg/resource/helper.go","code":"// FollowContinue handles the continue parameter returned by the API server when using list\n// chunking. To take advantage of this, the initial ListOptions provided by the consumer\n// should include a non-zero Limit parameter.\nfunc FollowContinue(initialOpts *metav1.ListOptions,\n\tlistFunc func(metav1.ListOptions) (runtime.Object, error)) error {\n\topts := initialOpts\n\tfor {\n\t\tlist, err := listFunc(*opts)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnextContinueToken, _ := metadataAccessor.Continue(list)\n\t\tif len(nextContinueToken) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\topts.Continue = nextContinueToken\n\t}\n}","line":{"from":116,"to":133}} {"id":100019470,"name":"EnhanceListError","signature":"func EnhanceListError(err error, opts metav1.ListOptions, subj string) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/helper.go","code":"// EnhanceListError augments errors typically returned by List operations with additional context,\n// making sure to retain the StatusError type when applicable.\nfunc EnhanceListError(err error, opts metav1.ListOptions, subj string) error {\n\tif apierrors.IsResourceExpired(err) {\n\t\treturn err\n\t}\n\tif apierrors.IsBadRequest(err) || apierrors.IsNotFound(err) {\n\t\tif se, ok := err.(*apierrors.StatusError); ok {\n\t\t\t// modify the message without hiding this is an API error\n\t\t\tif len(opts.LabelSelector) == 0 \u0026\u0026 len(opts.FieldSelector) == 0 {\n\t\t\t\tse.ErrStatus.Message = fmt.Sprintf(\"Unable to list %q: %v\", subj,\n\t\t\t\t\tse.ErrStatus.Message)\n\t\t\t} else {\n\t\t\t\tse.ErrStatus.Message = fmt.Sprintf(\n\t\t\t\t\t\"Unable to find %q that match label selector %q, field selector %q: %v\", subj,\n\t\t\t\t\topts.LabelSelector,\n\t\t\t\t\topts.FieldSelector, se.ErrStatus.Message)\n\t\t\t}\n\t\t\treturn se\n\t\t}\n\t\tif len(opts.LabelSelector) == 0 \u0026\u0026 len(opts.FieldSelector) == 0 {\n\t\t\treturn fmt.Errorf(\"Unable to list %q: %v\", subj, err)\n\t\t}\n\t\treturn fmt.Errorf(\"Unable to find %q that match label selector %q, field selector %q: %v\",\n\t\t\tsubj, opts.LabelSelector, opts.FieldSelector, err)\n\t}\n\treturn err\n}","line":{"from":135,"to":162}} {"id":100019471,"name":"Watch","signature":"func (m *Helper) Watch(namespace, apiVersion string, options *metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/helper.go","code":"func (m *Helper) Watch(namespace, apiVersion string, options *metav1.ListOptions) (watch.Interface, error) {\n\toptions.Watch = true\n\treturn m.RESTClient.Get().\n\t\tNamespaceIfScoped(namespace, m.NamespaceScoped).\n\t\tResource(m.Resource).\n\t\tVersionedParams(options, metav1.ParameterCodec).\n\t\tWatch(context.TODO())\n}","line":{"from":164,"to":171}} {"id":100019472,"name":"WatchSingle","signature":"func (m *Helper) WatchSingle(namespace, name, resourceVersion string) (watch.Interface, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/helper.go","code":"func (m *Helper) WatchSingle(namespace, name, resourceVersion string) (watch.Interface, error) {\n\treturn m.RESTClient.Get().\n\t\tNamespaceIfScoped(namespace, m.NamespaceScoped).\n\t\tResource(m.Resource).\n\t\tVersionedParams(\u0026metav1.ListOptions{\n\t\t\tResourceVersion: resourceVersion,\n\t\t\tWatch: true,\n\t\t\tFieldSelector: fields.OneTermEqualSelector(\"metadata.name\", name).String(),\n\t\t}, metav1.ParameterCodec).\n\t\tWatch(context.TODO())\n}","line":{"from":173,"to":183}} {"id":100019473,"name":"Delete","signature":"func (m *Helper) Delete(namespace, name string) (runtime.Object, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/helper.go","code":"func (m *Helper) Delete(namespace, name string) (runtime.Object, error) {\n\treturn m.DeleteWithOptions(namespace, name, nil)\n}","line":{"from":185,"to":187}} {"id":100019474,"name":"DeleteWithOptions","signature":"func (m *Helper) DeleteWithOptions(namespace, name string, options *metav1.DeleteOptions) (runtime.Object, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/helper.go","code":"func (m *Helper) DeleteWithOptions(namespace, name string, options *metav1.DeleteOptions) (runtime.Object, error) {\n\tif options == nil {\n\t\toptions = \u0026metav1.DeleteOptions{}\n\t}\n\tif m.ServerDryRun {\n\t\toptions.DryRun = []string{metav1.DryRunAll}\n\t}\n\n\treturn m.RESTClient.Delete().\n\t\tNamespaceIfScoped(namespace, m.NamespaceScoped).\n\t\tResource(m.Resource).\n\t\tName(name).\n\t\tBody(options).\n\t\tDo(context.TODO()).\n\t\tGet()\n}","line":{"from":189,"to":204}} {"id":100019475,"name":"Create","signature":"func (m *Helper) Create(namespace string, modify bool, obj runtime.Object) (runtime.Object, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/helper.go","code":"func (m *Helper) Create(namespace string, modify bool, obj runtime.Object) (runtime.Object, error) {\n\treturn m.CreateWithOptions(namespace, modify, obj, nil)\n}","line":{"from":206,"to":208}} {"id":100019476,"name":"CreateWithOptions","signature":"func (m *Helper) CreateWithOptions(namespace string, modify bool, obj runtime.Object, options *metav1.CreateOptions) (runtime.Object, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/helper.go","code":"func (m *Helper) CreateWithOptions(namespace string, modify bool, obj runtime.Object, options *metav1.CreateOptions) (runtime.Object, error) {\n\tif options == nil {\n\t\toptions = \u0026metav1.CreateOptions{}\n\t}\n\tif m.ServerDryRun {\n\t\toptions.DryRun = []string{metav1.DryRunAll}\n\t}\n\tif m.FieldManager != \"\" {\n\t\toptions.FieldManager = m.FieldManager\n\t}\n\tif m.FieldValidation != \"\" {\n\t\toptions.FieldValidation = m.FieldValidation\n\t}\n\tif modify {\n\t\t// Attempt to version the object based on client logic.\n\t\tversion, err := metadataAccessor.ResourceVersion(obj)\n\t\tif err != nil {\n\t\t\t// We don't know how to clear the version on this object, so send it to the server as is\n\t\t\treturn m.createResource(m.RESTClient, m.Resource, namespace, obj, options)\n\t\t}\n\t\tif version != \"\" {\n\t\t\tif err := metadataAccessor.SetResourceVersion(obj, \"\"); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn m.createResource(m.RESTClient, m.Resource, namespace, obj, options)\n}","line":{"from":210,"to":238}} {"id":100019477,"name":"createResource","signature":"func (m *Helper) createResource(c RESTClient, resource, namespace string, obj runtime.Object, options *metav1.CreateOptions) (runtime.Object, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/helper.go","code":"func (m *Helper) createResource(c RESTClient, resource, namespace string, obj runtime.Object, options *metav1.CreateOptions) (runtime.Object, error) {\n\treturn c.Post().\n\t\tNamespaceIfScoped(namespace, m.NamespaceScoped).\n\t\tResource(resource).\n\t\tVersionedParams(options, metav1.ParameterCodec).\n\t\tBody(obj).\n\t\tDo(context.TODO()).\n\t\tGet()\n}","line":{"from":240,"to":248}} {"id":100019478,"name":"Patch","signature":"func (m *Helper) Patch(namespace, name string, pt types.PatchType, data []byte, options *metav1.PatchOptions) (runtime.Object, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/helper.go","code":"func (m *Helper) Patch(namespace, name string, pt types.PatchType, data []byte, options *metav1.PatchOptions) (runtime.Object, error) {\n\tif options == nil {\n\t\toptions = \u0026metav1.PatchOptions{}\n\t}\n\tif m.ServerDryRun {\n\t\toptions.DryRun = []string{metav1.DryRunAll}\n\t}\n\tif m.FieldManager != \"\" {\n\t\toptions.FieldManager = m.FieldManager\n\t}\n\tif m.FieldValidation != \"\" {\n\t\toptions.FieldValidation = m.FieldValidation\n\t}\n\treturn m.RESTClient.Patch(pt).\n\t\tNamespaceIfScoped(namespace, m.NamespaceScoped).\n\t\tResource(m.Resource).\n\t\tName(name).\n\t\tSubResource(m.Subresource).\n\t\tVersionedParams(options, metav1.ParameterCodec).\n\t\tBody(data).\n\t\tDo(context.TODO()).\n\t\tGet()\n}","line":{"from":249,"to":271}} {"id":100019479,"name":"Replace","signature":"func (m *Helper) Replace(namespace, name string, overwrite bool, obj runtime.Object) (runtime.Object, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/helper.go","code":"func (m *Helper) Replace(namespace, name string, overwrite bool, obj runtime.Object) (runtime.Object, error) {\n\tc := m.RESTClient\n\tvar options = \u0026metav1.UpdateOptions{}\n\tif m.ServerDryRun {\n\t\toptions.DryRun = []string{metav1.DryRunAll}\n\t}\n\tif m.FieldManager != \"\" {\n\t\toptions.FieldManager = m.FieldManager\n\t}\n\tif m.FieldValidation != \"\" {\n\t\toptions.FieldValidation = m.FieldValidation\n\t}\n\n\t// Attempt to version the object based on client logic.\n\tversion, err := metadataAccessor.ResourceVersion(obj)\n\tif err != nil {\n\t\t// We don't know how to version this object, so send it to the server as is\n\t\treturn m.replaceResource(c, m.Resource, namespace, name, obj, options)\n\t}\n\tif version == \"\" \u0026\u0026 overwrite {\n\t\t// Retrieve the current version of the object to overwrite the server object\n\t\tserverObj, err := c.Get().NamespaceIfScoped(namespace, m.NamespaceScoped).Resource(m.Resource).Name(name).SubResource(m.Subresource).Do(context.TODO()).Get()\n\t\tif err != nil {\n\t\t\t// The object does not exist, but we want it to be created\n\t\t\treturn m.replaceResource(c, m.Resource, namespace, name, obj, options)\n\t\t}\n\t\tserverVersion, err := metadataAccessor.ResourceVersion(serverObj)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := metadataAccessor.SetResourceVersion(obj, serverVersion); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn m.replaceResource(c, m.Resource, namespace, name, obj, options)\n}","line":{"from":273,"to":309}} {"id":100019480,"name":"replaceResource","signature":"func (m *Helper) replaceResource(c RESTClient, resource, namespace, name string, obj runtime.Object, options *metav1.UpdateOptions) (runtime.Object, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/helper.go","code":"func (m *Helper) replaceResource(c RESTClient, resource, namespace, name string, obj runtime.Object, options *metav1.UpdateOptions) (runtime.Object, error) {\n\treturn c.Put().\n\t\tNamespaceIfScoped(namespace, m.NamespaceScoped).\n\t\tResource(resource).\n\t\tName(name).\n\t\tSubResource(m.Subresource).\n\t\tVersionedParams(options, metav1.ParameterCodec).\n\t\tBody(obj).\n\t\tDo(context.TODO()).\n\t\tGet()\n}","line":{"from":311,"to":321}} {"id":100019481,"name":"NewClientWithOptions","signature":"func NewClientWithOptions(c RESTClient, transforms ...RequestTransform) RESTClient","file":"staging/src/k8s.io/cli-runtime/pkg/resource/interfaces.go","code":"// NewClientWithOptions wraps the provided RESTClient and invokes each transform on each\n// newly created request.\nfunc NewClientWithOptions(c RESTClient, transforms ...RequestTransform) RESTClient {\n\tif len(transforms) == 0 {\n\t\treturn c\n\t}\n\treturn \u0026clientOptions{c: c, transforms: transforms}\n}","line":{"from":50,"to":57}} {"id":100019482,"name":"modify","signature":"func (c *clientOptions) modify(req *rest.Request) *rest.Request","file":"staging/src/k8s.io/cli-runtime/pkg/resource/interfaces.go","code":"func (c *clientOptions) modify(req *rest.Request) *rest.Request {\n\tfor _, transform := range c.transforms {\n\t\ttransform(req)\n\t}\n\treturn req\n}","line":{"from":64,"to":69}} {"id":100019483,"name":"Get","signature":"func (c *clientOptions) Get() *rest.Request","file":"staging/src/k8s.io/cli-runtime/pkg/resource/interfaces.go","code":"func (c *clientOptions) Get() *rest.Request {\n\treturn c.modify(c.c.Get())\n}","line":{"from":71,"to":73}} {"id":100019484,"name":"Post","signature":"func (c *clientOptions) Post() *rest.Request","file":"staging/src/k8s.io/cli-runtime/pkg/resource/interfaces.go","code":"func (c *clientOptions) Post() *rest.Request {\n\treturn c.modify(c.c.Post())\n}","line":{"from":75,"to":77}} {"id":100019485,"name":"Patch","signature":"func (c *clientOptions) Patch(t types.PatchType) *rest.Request","file":"staging/src/k8s.io/cli-runtime/pkg/resource/interfaces.go","code":"func (c *clientOptions) Patch(t types.PatchType) *rest.Request {\n\treturn c.modify(c.c.Patch(t))\n}","line":{"from":78,"to":80}} {"id":100019486,"name":"Delete","signature":"func (c *clientOptions) Delete() *rest.Request","file":"staging/src/k8s.io/cli-runtime/pkg/resource/interfaces.go","code":"func (c *clientOptions) Delete() *rest.Request {\n\treturn c.modify(c.c.Delete())\n}","line":{"from":81,"to":83}} {"id":100019487,"name":"Put","signature":"func (c *clientOptions) Put() *rest.Request","file":"staging/src/k8s.io/cli-runtime/pkg/resource/interfaces.go","code":"func (c *clientOptions) Put() *rest.Request {\n\treturn c.modify(c.c.Put())\n}","line":{"from":84,"to":86}} {"id":100019488,"name":"Visit","signature":"func (v *KustomizeVisitor) Visit(fn VisitorFunc) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/kustomizevisitor.go","code":"// Visit passes the result of a kustomize build to a StreamVisitor.\nfunc (v *KustomizeVisitor) Visit(fn VisitorFunc) error {\n\tkOpts := krusty.MakeDefaultOptions()\n\tkOpts.Reorder = krusty.ReorderOptionLegacy\n\tk := krusty.MakeKustomizer(kOpts)\n\tm, err := k.Run(v.fSys, v.dirPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.yml, err = m.AsYaml()\n\tif err != nil {\n\t\treturn err\n\t}\n\tsv := NewStreamVisitor(\n\t\tbytes.NewReader(v.yml), v.mapper, v.dirPath, v.schema)\n\treturn sv.Visit(fn)\n}","line":{"from":38,"to":54}} {"id":100019489,"name":"infoForData","signature":"func (m *mapper) infoForData(data []byte, source string) (*Info, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/mapper.go","code":"// InfoForData creates an Info object for the given data. An error is returned\n// if any of the decoding or client lookup steps fail. Name and namespace will be\n// set into Info if the mapping's MetadataAccessor can retrieve them.\nfunc (m *mapper) infoForData(data []byte, source string) (*Info, error) {\n\tobj, gvk, err := m.decoder.Decode(data, nil, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to decode %q: %v\", source, err)\n\t}\n\n\tname, _ := metadataAccessor.Name(obj)\n\tnamespace, _ := metadataAccessor.Namespace(obj)\n\tresourceVersion, _ := metadataAccessor.ResourceVersion(obj)\n\n\tret := \u0026Info{\n\t\tSource: source,\n\t\tNamespace: namespace,\n\t\tName: name,\n\t\tResourceVersion: resourceVersion,\n\n\t\tObject: obj,\n\t}\n\n\tif m.localFn == nil || !m.localFn() {\n\t\trestMapper, err := m.restMapperFn()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmapping, err := restMapper.RESTMapping(gvk.GroupKind(), gvk.Version)\n\t\tif err != nil {\n\t\t\tif _, ok := err.(*meta.NoKindMatchError); ok {\n\t\t\t\treturn nil, fmt.Errorf(\"resource mapping not found for name: %q namespace: %q from %q: %v\\nensure CRDs are installed first\",\n\t\t\t\t\tname, namespace, source, err)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"unable to recognize %q: %v\", source, err)\n\t\t}\n\t\tret.Mapping = mapping\n\n\t\tclient, err := m.clientFn(gvk.GroupVersion())\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to connect to a server to handle %q: %v\", mapping.Resource, err)\n\t\t}\n\t\tret.Client = client\n\t}\n\n\treturn ret, nil\n}","line":{"from":39,"to":84}} {"id":100019490,"name":"infoForObject","signature":"func (m *mapper) infoForObject(obj runtime.Object, typer runtime.ObjectTyper, preferredGVKs []schema.GroupVersionKind) (*Info, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/mapper.go","code":"// InfoForObject creates an Info object for the given Object. An error is returned\n// if the object cannot be introspected. Name and namespace will be set into Info\n// if the mapping's MetadataAccessor can retrieve them.\nfunc (m *mapper) infoForObject(obj runtime.Object, typer runtime.ObjectTyper, preferredGVKs []schema.GroupVersionKind) (*Info, error) {\n\tgroupVersionKinds, _, err := typer.ObjectKinds(obj)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to get type info from the object %q: %v\", reflect.TypeOf(obj), err)\n\t}\n\n\tgvk := groupVersionKinds[0]\n\tif len(groupVersionKinds) \u003e 1 \u0026\u0026 len(preferredGVKs) \u003e 0 {\n\t\tgvk = preferredObjectKind(groupVersionKinds, preferredGVKs)\n\t}\n\n\tname, _ := metadataAccessor.Name(obj)\n\tnamespace, _ := metadataAccessor.Namespace(obj)\n\tresourceVersion, _ := metadataAccessor.ResourceVersion(obj)\n\tret := \u0026Info{\n\t\tNamespace: namespace,\n\t\tName: name,\n\t\tResourceVersion: resourceVersion,\n\n\t\tObject: obj,\n\t}\n\n\tif m.localFn == nil || !m.localFn() {\n\t\trestMapper, err := m.restMapperFn()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmapping, err := restMapper.RESTMapping(gvk.GroupKind(), gvk.Version)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to recognize %v\", err)\n\t\t}\n\t\tret.Mapping = mapping\n\n\t\tclient, err := m.clientFn(gvk.GroupVersion())\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to connect to a server to handle %q: %v\", mapping.Resource, err)\n\t\t}\n\t\tret.Client = client\n\t}\n\n\treturn ret, nil\n}","line":{"from":86,"to":130}} {"id":100019491,"name":"preferredObjectKind","signature":"func preferredObjectKind(possibilities []schema.GroupVersionKind, preferences []schema.GroupVersionKind) schema.GroupVersionKind","file":"staging/src/k8s.io/cli-runtime/pkg/resource/mapper.go","code":"// preferredObjectKind picks the possibility that most closely matches the priority list in this order:\n// GroupVersionKind matches (exact match)\n// GroupKind matches\n// Group matches\nfunc preferredObjectKind(possibilities []schema.GroupVersionKind, preferences []schema.GroupVersionKind) schema.GroupVersionKind {\n\t// Exact match\n\tfor _, priority := range preferences {\n\t\tfor _, possibility := range possibilities {\n\t\t\tif possibility == priority {\n\t\t\t\treturn possibility\n\t\t\t}\n\t\t}\n\t}\n\n\t// GroupKind match\n\tfor _, priority := range preferences {\n\t\tfor _, possibility := range possibilities {\n\t\t\tif possibility.GroupKind() == priority.GroupKind() {\n\t\t\t\treturn possibility\n\t\t\t}\n\t\t}\n\t}\n\n\t// Group match\n\tfor _, priority := range preferences {\n\t\tfor _, possibility := range possibilities {\n\t\t\tif possibility.Group == priority.Group {\n\t\t\t\treturn possibility\n\t\t\t}\n\t\t}\n\t}\n\n\t// Just pick the first\n\treturn possibilities[0]\n}","line":{"from":132,"to":166}} {"id":100019492,"name":"Decode","signature":"func (m *metadataValidatingDecoder) Decode(data []byte, defaults *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/metadata_decoder.go","code":"func (m *metadataValidatingDecoder) Decode(data []byte, defaults *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {\n\tobj, gvk, err := m.decoder.Decode(data, defaults, into)\n\n\t// if we already errored, return\n\tif err != nil {\n\t\treturn obj, gvk, err\n\t}\n\n\t// if we're not unstructured, return\n\tif _, isUnstructured := obj.(runtime.Unstructured); !isUnstructured {\n\t\treturn obj, gvk, err\n\t}\n\n\t// make sure the data can decode into ObjectMeta before we return,\n\t// so we don't silently truncate schema errors in metadata later with accesser get/set calls\n\tv := \u0026metadataOnlyObject{}\n\tif typedErr := utiljson.Unmarshal(data, v); typedErr != nil {\n\t\treturn obj, gvk, typedErr\n\t}\n\treturn obj, gvk, err\n}","line":{"from":31,"to":51}} {"id":100019493,"name":"NewQueryParamVerifier","signature":"func NewQueryParamVerifier(dynamicClient dynamic.Interface, openAPIGetter discovery.OpenAPISchemaInterface, queryParam VerifiableQueryParam) *QueryParamVerifier","file":"staging/src/k8s.io/cli-runtime/pkg/resource/query_param_verifier.go","code":"func NewQueryParamVerifier(dynamicClient dynamic.Interface, openAPIGetter discovery.OpenAPISchemaInterface, queryParam VerifiableQueryParam) *QueryParamVerifier {\n\treturn \u0026QueryParamVerifier{\n\t\tfinder: NewCRDFinder(CRDFromDynamic(dynamicClient)),\n\t\topenAPIGetter: openAPIGetter,\n\t\tqueryParam: queryParam,\n\t}\n}","line":{"from":30,"to":36}} {"id":100019494,"name":"HasSupport","signature":"func (v *QueryParamVerifier) HasSupport(gvk schema.GroupVersionKind) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/query_param_verifier.go","code":"// HasSupport checks if the given gvk supports the query param configured on v\nfunc (v *QueryParamVerifier) HasSupport(gvk schema.GroupVersionKind) error {\n\tif (gvk == schema.GroupVersionKind{Version: \"v1\", Kind: \"List\"}) {\n\t\treturn NewParamUnsupportedError(gvk, v.queryParam)\n\t}\n\n\toapi, err := v.openAPIGetter.OpenAPISchema()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to download openapi: %v\", err)\n\t}\n\tsupports, err := supportsQueryParam(oapi, gvk, v.queryParam)\n\tif err != nil {\n\t\t// We assume that we couldn't find the type, then check for namespace:\n\t\tsupports, _ = supportsQueryParam(oapi, schema.GroupVersionKind{Group: \"\", Version: \"v1\", Kind: \"Namespace\"}, v.queryParam)\n\t\t// If namespace supports the query param, then we will support the query param for CRDs only.\n\t\tif supports {\n\t\t\tsupports, err = v.finder.HasCRD(gvk.GroupKind())\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to check CRD: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\tif !supports {\n\t\treturn NewParamUnsupportedError(gvk, v.queryParam)\n\t}\n\treturn nil\n}","line":{"from":73,"to":99}} {"id":100019495,"name":"NewParamUnsupportedError","signature":"func NewParamUnsupportedError(gvk schema.GroupVersionKind, param VerifiableQueryParam) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/query_param_verifier.go","code":"func NewParamUnsupportedError(gvk schema.GroupVersionKind, param VerifiableQueryParam) error {\n\treturn \u0026paramUnsupportedError{\n\t\tgvk: gvk,\n\t\tparam: param,\n\t}\n}","line":{"from":106,"to":111}} {"id":100019496,"name":"Error","signature":"func (e *paramUnsupportedError) Error() string","file":"staging/src/k8s.io/cli-runtime/pkg/resource/query_param_verifier.go","code":"func (e *paramUnsupportedError) Error() string {\n\treturn fmt.Sprintf(\"%v doesn't support %s\", e.gvk, e.param)\n}","line":{"from":113,"to":115}} {"id":100019497,"name":"IsParamUnsupportedError","signature":"func IsParamUnsupportedError(err error) bool","file":"staging/src/k8s.io/cli-runtime/pkg/resource/query_param_verifier.go","code":"func IsParamUnsupportedError(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\t_, ok := err.(*paramUnsupportedError)\n\treturn ok\n}","line":{"from":117,"to":123}} {"id":100019498,"name":"hasGVKExtension","signature":"func hasGVKExtension(extensions []*openapi_v2.NamedAny, gvk schema.GroupVersionKind) bool","file":"staging/src/k8s.io/cli-runtime/pkg/resource/query_param_verifier.go","code":"func hasGVKExtension(extensions []*openapi_v2.NamedAny, gvk schema.GroupVersionKind) bool {\n\tfor _, extension := range extensions {\n\t\tif extension.GetValue().GetYaml() == \"\" ||\n\t\t\textension.GetName() != \"x-kubernetes-group-version-kind\" {\n\t\t\tcontinue\n\t\t}\n\t\tvar value map[string]string\n\t\terr := yaml.Unmarshal([]byte(extension.GetValue().GetYaml()), \u0026value)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif value[\"group\"] == gvk.Group \u0026\u0026 value[\"kind\"] == gvk.Kind \u0026\u0026 value[\"version\"] == gvk.Version {\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\treturn false\n}","line":{"from":125,"to":143}} {"id":100019499,"name":"supportsQueryParam","signature":"func supportsQueryParam(doc *openapi_v2.Document, gvk schema.GroupVersionKind, queryParam VerifiableQueryParam) (bool, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/query_param_verifier.go","code":"// supportsQueryParam is a method that let's us look in the OpenAPI if the\n// specific group-version-kind supports the specific query parameter for\n// the PATCH end-point.\nfunc supportsQueryParam(doc *openapi_v2.Document, gvk schema.GroupVersionKind, queryParam VerifiableQueryParam) (bool, error) {\n\tfor _, path := range doc.GetPaths().GetPath() {\n\t\t// Is this describing the gvk we're looking for?\n\t\tif !hasGVKExtension(path.GetValue().GetPatch().GetVendorExtension(), gvk) {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, param := range path.GetValue().GetPatch().GetParameters() {\n\t\t\tif param.GetParameter().GetNonBodyParameter().GetQueryParameterSubSchema().GetName() == string(queryParam) {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\t\treturn false, nil\n\t}\n\n\treturn false, errors.New(\"couldn't find GVK in openapi\")\n}","line":{"from":145,"to":163}} {"id":100019500,"name":"NewQueryParamVerifierV3","signature":"func NewQueryParamVerifierV3(dynamicClient dynamic.Interface, oapiClient openapi.Client, queryParam VerifiableQueryParam) Verifier","file":"staging/src/k8s.io/cli-runtime/pkg/resource/query_param_verifier_v3.go","code":"// NewQueryParamVerifierV3 returns a pointer to the created queryParamVerifier3 struct,\n// which implements the Verifier interface. The caching characteristics of the\n// OpenAPI V3 specs are determined by the passed oapiClient. For memory caching, the\n// client should be wrapped beforehand as: cached.NewClient(oapiClient). The disk\n// caching is determined by the discovery client the oapiClient is created from.\nfunc NewQueryParamVerifierV3(dynamicClient dynamic.Interface, oapiClient openapi.Client, queryParam VerifiableQueryParam) Verifier {\n\treturn \u0026queryParamVerifierV3{\n\t\tfinder: NewCRDFinder(CRDFromDynamic(dynamicClient)),\n\t\troot: openapi3.NewRoot(oapiClient),\n\t\tqueryParam: queryParam,\n\t}\n}","line":{"from":32,"to":43}} {"id":100019501,"name":"HasSupport","signature":"func (v *queryParamVerifierV3) HasSupport(gvk schema.GroupVersionKind) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/query_param_verifier_v3.go","code":"// HasSupport returns nil error if the passed GVK supports the parameter\n// (stored in struct; usually \"fieldValidation\") for Patch endpoint.\n// Returns an error if the passed GVK does not support the query param,\n// or if another error occurred. If the Open API V3 spec for a CRD is not\n// found, then the spec for Namespace is checked for query param support instead.\nfunc (v *queryParamVerifierV3) HasSupport(gvk schema.GroupVersionKind) error {\n\tif (gvk == schema.GroupVersionKind{Version: \"v1\", Kind: \"List\"}) {\n\t\treturn NewParamUnsupportedError(gvk, v.queryParam)\n\t}\n\tgvSpec, err := v.root.GVSpec(gvk.GroupVersion())\n\tif err == nil {\n\t\treturn supportsQueryParamV3(gvSpec, gvk, v.queryParam)\n\t}\n\tif _, isErr := err.(*openapi3.GroupVersionNotFoundError); !isErr {\n\t\treturn err\n\t}\n\t// If the spec for the passed GVK is not found, then check if it is a CRD.\n\t// For CRD's substitute Namespace OpenAPI V3 spec to check if query param is supported.\n\tif found, _ := v.finder.HasCRD(gvk.GroupKind()); found {\n\t\tnamespaceSpec, err := v.root.GVSpec(namespaceGVK.GroupVersion())\n\t\tif err != nil {\n\t\t\t// If error retrieving Namespace spec, propagate error.\n\t\t\treturn err\n\t\t}\n\t\treturn supportsQueryParamV3(namespaceSpec, namespaceGVK, v.queryParam)\n\t}\n\treturn NewParamUnsupportedError(gvk, v.queryParam)\n}","line":{"from":56,"to":83}} {"id":100019502,"name":"hasGVKExtensionV3","signature":"func hasGVKExtensionV3(extensions spec.Extensions, gvk schema.GroupVersionKind) bool","file":"staging/src/k8s.io/cli-runtime/pkg/resource/query_param_verifier_v3.go","code":"// hasGVKExtensionV3 returns true if the passed OpenAPI extensions map contains\n// the passed GVK; false otherwise.\nfunc hasGVKExtensionV3(extensions spec.Extensions, gvk schema.GroupVersionKind) bool {\n\tvar oapiGVK map[string]string\n\terr := extensions.GetObject(\"x-kubernetes-group-version-kind\", \u0026oapiGVK)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif oapiGVK[\"group\"] == gvk.Group \u0026\u0026\n\t\toapiGVK[\"version\"] == gvk.Version \u0026\u0026\n\t\toapiGVK[\"kind\"] == gvk.Kind {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":85,"to":99}} {"id":100019503,"name":"supportsQueryParamV3","signature":"func supportsQueryParamV3(doc *spec3.OpenAPI, gvk schema.GroupVersionKind, queryParam VerifiableQueryParam) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/query_param_verifier_v3.go","code":"// supportsQueryParam is a method that let's us look in the OpenAPI if the\n// specific group-version-kind supports the specific query parameter for\n// the PATCH end-point. Returns nil if the passed GVK supports the passed\n// query parameter; otherwise, a \"paramUnsupportedError\" is returned (except\n// when an invalid document error is returned when an invalid OpenAPI V3\n// is passed in).\nfunc supportsQueryParamV3(doc *spec3.OpenAPI, gvk schema.GroupVersionKind, queryParam VerifiableQueryParam) error {\n\tif doc == nil || doc.Paths == nil {\n\t\treturn fmt.Errorf(\"Invalid OpenAPI V3 document\")\n\t}\n\tfor _, path := range doc.Paths.Paths {\n\t\t// If operation is not PATCH, then continue.\n\t\tif path == nil {\n\t\t\tcontinue\n\t\t}\n\t\top := path.PathProps.Patch\n\t\tif op == nil {\n\t\t\tcontinue\n\t\t}\n\t\t// Is this PATCH operation for the passed GVK?\n\t\tif !hasGVKExtensionV3(op.VendorExtensible.Extensions, gvk) {\n\t\t\tcontinue\n\t\t}\n\t\t// Now look for the query parameter among the parameters\n\t\t// for the PATCH operation.\n\t\tfor _, param := range op.OperationProps.Parameters {\n\t\t\tif param.ParameterProps.Name == string(queryParam) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\treturn NewParamUnsupportedError(gvk, queryParam)\n\t}\n\treturn fmt.Errorf(\"Path not found for GVK (%s) in OpenAPI V3 doc\", gvk)\n}","line":{"from":101,"to":134}} {"id":100019504,"name":"withError","signature":"func (r *Result) withError(err error) *Result","file":"staging/src/k8s.io/cli-runtime/pkg/resource/result.go","code":"// withError allows a fluent style for internal result code.\nfunc (r *Result) withError(err error) *Result {\n\tr.err = err\n\treturn r\n}","line":{"from":52,"to":56}} {"id":100019505,"name":"TargetsSingleItems","signature":"func (r *Result) TargetsSingleItems() bool","file":"staging/src/k8s.io/cli-runtime/pkg/resource/result.go","code":"// TargetsSingleItems returns true if any of the builder arguments pointed\n// to non-list calls (if the user explicitly asked for any object by name).\n// This includes directories, streams, URLs, and resource name tuples.\nfunc (r *Result) TargetsSingleItems() bool {\n\treturn r.targetsSingleItems\n}","line":{"from":58,"to":63}} {"id":100019506,"name":"IgnoreErrors","signature":"func (r *Result) IgnoreErrors(fns ...ErrMatchFunc) *Result","file":"staging/src/k8s.io/cli-runtime/pkg/resource/result.go","code":"// IgnoreErrors will filter errors that occur when by visiting the result\n// (but not errors that occur by creating the result in the first place),\n// eliminating any that match fns. This is best used in combination with\n// Builder.ContinueOnError(), where the visitors accumulate errors and return\n// them after visiting as a slice of errors. If no errors remain after\n// filtering, the various visitor methods on Result will return nil for\n// err.\nfunc (r *Result) IgnoreErrors(fns ...ErrMatchFunc) *Result {\n\tfor _, fn := range fns {\n\t\tr.ignoreErrors = append(r.ignoreErrors, utilerrors.Matcher(fn))\n\t}\n\treturn r\n}","line":{"from":65,"to":77}} {"id":100019507,"name":"Mapper","signature":"func (r *Result) Mapper() *mapper","file":"staging/src/k8s.io/cli-runtime/pkg/resource/result.go","code":"// Mapper returns a copy of the builder's mapper.\nfunc (r *Result) Mapper() *mapper {\n\treturn r.mapper\n}","line":{"from":79,"to":82}} {"id":100019508,"name":"Err","signature":"func (r *Result) Err() error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/result.go","code":"// Err returns one or more errors (via a util.ErrorList) that occurred prior\n// to visiting the elements in the visitor. To see all errors including those\n// that occur during visitation, invoke Infos().\nfunc (r *Result) Err() error {\n\treturn r.err\n}","line":{"from":84,"to":89}} {"id":100019509,"name":"Visit","signature":"func (r *Result) Visit(fn VisitorFunc) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/result.go","code":"// Visit implements the Visitor interface on the items described in the Builder.\n// Note that some visitor sources are not traversable more than once, or may\n// return different results. If you wish to operate on the same set of resources\n// multiple times, use the Infos() method.\nfunc (r *Result) Visit(fn VisitorFunc) error {\n\tif r.err != nil {\n\t\treturn r.err\n\t}\n\terr := r.visitor.Visit(fn)\n\treturn utilerrors.FilterOut(err, r.ignoreErrors...)\n}","line":{"from":91,"to":101}} {"id":100019510,"name":"IntoSingleItemImplied","signature":"func (r *Result) IntoSingleItemImplied(b *bool) *Result","file":"staging/src/k8s.io/cli-runtime/pkg/resource/result.go","code":"// IntoSingleItemImplied sets the provided boolean pointer to true if the Builder input\n// implies a single item, or multiple.\nfunc (r *Result) IntoSingleItemImplied(b *bool) *Result {\n\t*b = r.singleItemImplied\n\treturn r\n}","line":{"from":103,"to":108}} {"id":100019511,"name":"Infos","signature":"func (r *Result) Infos() ([]*Info, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/result.go","code":"// Infos returns an array of all of the resource infos retrieved via traversal.\n// Will attempt to traverse the entire set of visitors only once, and will return\n// a cached list on subsequent calls.\nfunc (r *Result) Infos() ([]*Info, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif r.info != nil {\n\t\treturn r.info, nil\n\t}\n\n\tinfos := []*Info{}\n\terr := r.visitor.Visit(func(info *Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tinfos = append(infos, info)\n\t\treturn nil\n\t})\n\terr = utilerrors.FilterOut(err, r.ignoreErrors...)\n\n\tr.info, r.err = infos, err\n\treturn infos, err\n}","line":{"from":110,"to":133}} {"id":100019512,"name":"Object","signature":"func (r *Result) Object() (runtime.Object, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/result.go","code":"// Object returns a single object representing the output of a single visit to all\n// found resources. If the Builder was a singular context (expected to return a\n// single resource by user input) and only a single resource was found, the resource\n// will be returned as is. Otherwise, the returned resources will be part of an\n// v1.List. The ResourceVersion of the v1.List will be set only if it is identical\n// across all infos returned.\nfunc (r *Result) Object() (runtime.Object, error) {\n\tinfos, err := r.Infos()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tversions := sets.String{}\n\tobjects := []runtime.Object{}\n\tfor _, info := range infos {\n\t\tif info.Object != nil {\n\t\t\tobjects = append(objects, info.Object)\n\t\t\tversions.Insert(info.ResourceVersion)\n\t\t}\n\t}\n\n\tif len(objects) == 1 {\n\t\tif r.singleItemImplied {\n\t\t\treturn objects[0], nil\n\t\t}\n\t\t// if the item is a list already, don't create another list\n\t\tif meta.IsListType(objects[0]) {\n\t\t\treturn objects[0], nil\n\t\t}\n\t}\n\n\tversion := \"\"\n\tif len(versions) == 1 {\n\t\tversion = versions.List()[0]\n\t}\n\n\treturn toV1List(objects, version), err\n}","line":{"from":135,"to":172}} {"id":100019513,"name":"toV1List","signature":"func toV1List(objects []runtime.Object, version string) runtime.Object","file":"staging/src/k8s.io/cli-runtime/pkg/resource/result.go","code":"// toV1List takes a slice of Objects + their version, and returns\n// a v1.List Object containing the objects in the Items field\nfunc toV1List(objects []runtime.Object, version string) runtime.Object {\n\traw := []runtime.RawExtension{}\n\tfor _, o := range objects {\n\t\traw = append(raw, runtime.RawExtension{Object: o})\n\t}\n\treturn \u0026v1.List{\n\t\tListMeta: metav1.ListMeta{\n\t\t\tResourceVersion: version,\n\t\t},\n\t\tItems: raw,\n\t}\n}","line":{"from":178,"to":191}} {"id":100019514,"name":"ResourceMapping","signature":"func (r *Result) ResourceMapping() (*meta.RESTMapping, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/result.go","code":"// ResourceMapping returns a single meta.RESTMapping representing the\n// resources located by the builder, or an error if more than one\n// mapping was found.\nfunc (r *Result) ResourceMapping() (*meta.RESTMapping, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tmappings := map[schema.GroupVersionResource]*meta.RESTMapping{}\n\tfor i := range r.sources {\n\t\tm, ok := r.sources[i].(ResourceMapping)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"a resource mapping could not be loaded from %v\", reflect.TypeOf(r.sources[i]))\n\t\t}\n\t\tmapping := m.ResourceMapping()\n\t\tmappings[mapping.Resource] = mapping\n\t}\n\tif len(mappings) != 1 {\n\t\treturn nil, fmt.Errorf(\"expected only a single resource type\")\n\t}\n\tfor _, mapping := range mappings {\n\t\treturn mapping, nil\n\t}\n\treturn nil, nil\n}","line":{"from":193,"to":216}} {"id":100019515,"name":"Watch","signature":"func (r *Result) Watch(resourceVersion string) (watch.Interface, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/result.go","code":"// Watch retrieves changes that occur on the server to the specified resource.\n// It currently supports watching a single source - if the resource source\n// (selectors or pure types) can be watched, they will be, otherwise the list\n// will be visited (equivalent to the Infos() call) and if there is a single\n// resource present, it will be watched, otherwise an error will be returned.\nfunc (r *Result) Watch(resourceVersion string) (watch.Interface, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\tif len(r.sources) != 1 {\n\t\treturn nil, fmt.Errorf(\"you may only watch a single resource or type of resource at a time\")\n\t}\n\tw, ok := r.sources[0].(Watchable)\n\tif !ok {\n\t\tinfo, err := r.Infos()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(info) != 1 {\n\t\t\treturn nil, fmt.Errorf(\"watch is only supported on individual resources and resource collections - %d resources were found\", len(info))\n\t\t}\n\t\treturn info[0].Watch(resourceVersion)\n\t}\n\treturn w.Watch(resourceVersion)\n}","line":{"from":218,"to":242}} {"id":100019516,"name":"Decode","signature":"func (dynamicCodec) Decode(data []byte, gvk *schema.GroupVersionKind, obj runtime.Object) (runtime.Object, *schema.GroupVersionKind, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/scheme.go","code":"func (dynamicCodec) Decode(data []byte, gvk *schema.GroupVersionKind, obj runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {\n\tobj, gvk, err := unstructured.UnstructuredJSONScheme.Decode(data, gvk, obj)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif strings.EqualFold(gvk.Kind, \"status\") \u0026\u0026 gvk.Version == \"v1\" \u0026\u0026 (gvk.Group == \"\" || gvk.Group == \"meta.k8s.io\") {\n\t\tif _, ok := obj.(*metav1.Status); !ok {\n\t\t\tobj = \u0026metav1.Status{}\n\t\t\terr := json.Unmarshal(data, obj)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn obj, gvk, nil\n}","line":{"from":38,"to":55}} {"id":100019517,"name":"Encode","signature":"func (dynamicCodec) Encode(obj runtime.Object, w io.Writer) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/scheme.go","code":"func (dynamicCodec) Encode(obj runtime.Object, w io.Writer) error {\n\t// There is no need to handle runtime.CacheableObject, as we only\n\t// fallback to other encoders here.\n\treturn unstructured.UnstructuredJSONScheme.Encode(obj, w)\n}","line":{"from":57,"to":61}} {"id":100019518,"name":"Identifier","signature":"func (dynamicCodec) Identifier() runtime.Identifier","file":"staging/src/k8s.io/cli-runtime/pkg/resource/scheme.go","code":"// Identifier implements runtime.Encoder interface.\nfunc (dynamicCodec) Identifier() runtime.Identifier {\n\treturn unstructured.UnstructuredJSONScheme.Identifier()\n}","line":{"from":63,"to":66}} {"id":100019519,"name":"UnstructuredPlusDefaultContentConfig","signature":"func UnstructuredPlusDefaultContentConfig() rest.ContentConfig","file":"staging/src/k8s.io/cli-runtime/pkg/resource/scheme.go","code":"// UnstructuredPlusDefaultContentConfig returns a rest.ContentConfig for dynamic types. It includes enough codecs to act as a \"normal\"\n// serializer for the rest.client with options, status and the like.\nfunc UnstructuredPlusDefaultContentConfig() rest.ContentConfig {\n\t// TODO: scheme.Codecs here should become \"pkg/apis/server/scheme\" which is the minimal core you need\n\t// to talk to a kubernetes server\n\tjsonInfo, _ := runtime.SerializerInfoForMediaType(scheme.Codecs.SupportedMediaTypes(), runtime.ContentTypeJSON)\n\n\tjsonInfo.Serializer = dynamicCodec{}\n\tjsonInfo.PrettySerializer = nil\n\treturn rest.ContentConfig{\n\t\tAcceptContentTypes: runtime.ContentTypeJSON,\n\t\tContentType: runtime.ContentTypeJSON,\n\t\tNegotiatedSerializer: serializer.NegotiatedSerializerWrapper(jsonInfo),\n\t}\n}","line":{"from":68,"to":82}} {"id":100019520,"name":"NewSelector","signature":"func NewSelector(client RESTClient, mapping *meta.RESTMapping, namespace, labelSelector, fieldSelector string, limitChunks int64) *Selector","file":"staging/src/k8s.io/cli-runtime/pkg/resource/selector.go","code":"// NewSelector creates a resource selector which hides details of getting items by their label selector.\nfunc NewSelector(client RESTClient, mapping *meta.RESTMapping, namespace, labelSelector, fieldSelector string, limitChunks int64) *Selector {\n\treturn \u0026Selector{\n\t\tClient: client,\n\t\tMapping: mapping,\n\t\tNamespace: namespace,\n\t\tLabelSelector: labelSelector,\n\t\tFieldSelector: fieldSelector,\n\t\tLimitChunks: limitChunks,\n\t}\n}","line":{"from":36,"to":46}} {"id":100019521,"name":"Visit","signature":"func (r *Selector) Visit(fn VisitorFunc) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/selector.go","code":"// Visit implements Visitor and uses request chunking by default.\nfunc (r *Selector) Visit(fn VisitorFunc) error {\n\thelper := NewHelper(r.Client, r.Mapping)\n\tinitialOpts := metav1.ListOptions{\n\t\tLabelSelector: r.LabelSelector,\n\t\tFieldSelector: r.FieldSelector,\n\t\tLimit: r.LimitChunks,\n\t}\n\treturn FollowContinue(\u0026initialOpts, func(options metav1.ListOptions) (runtime.Object, error) {\n\t\tlist, err := helper.List(\n\t\t\tr.Namespace,\n\t\t\tr.ResourceMapping().GroupVersionKind.GroupVersion().String(),\n\t\t\t\u0026options,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, EnhanceListError(err, options, r.Mapping.Resource.String())\n\t\t}\n\t\tresourceVersion, _ := metadataAccessor.ResourceVersion(list)\n\n\t\tinfo := \u0026Info{\n\t\t\tClient: r.Client,\n\t\t\tMapping: r.Mapping,\n\n\t\t\tNamespace: r.Namespace,\n\t\t\tResourceVersion: resourceVersion,\n\n\t\t\tObject: list,\n\t\t}\n\n\t\tif err := fn(info, nil); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn list, nil\n\t})\n}","line":{"from":48,"to":82}} {"id":100019522,"name":"Watch","signature":"func (r *Selector) Watch(resourceVersion string) (watch.Interface, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/selector.go","code":"func (r *Selector) Watch(resourceVersion string) (watch.Interface, error) {\n\treturn NewHelper(r.Client, r.Mapping).Watch(r.Namespace, r.ResourceMapping().GroupVersionKind.GroupVersion().String(),\n\t\t\u0026metav1.ListOptions{ResourceVersion: resourceVersion, LabelSelector: r.LabelSelector, FieldSelector: r.FieldSelector})\n}","line":{"from":84,"to":87}} {"id":100019523,"name":"ResourceMapping","signature":"func (r *Selector) ResourceMapping() *meta.RESTMapping","file":"staging/src/k8s.io/cli-runtime/pkg/resource/selector.go","code":"// ResourceMapping returns the mapping for this resource and implements ResourceMapping\nfunc (r *Selector) ResourceMapping() *meta.RESTMapping {\n\treturn r.Mapping\n}","line":{"from":89,"to":92}} {"id":100019524,"name":"Visit","signature":"func (i *Info) Visit(fn VisitorFunc) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"// Visit implements Visitor\nfunc (i *Info) Visit(fn VisitorFunc) error {\n\treturn fn(i, nil)\n}","line":{"from":93,"to":96}} {"id":100019525,"name":"Get","signature":"func (i *Info) Get() (err error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"// Get retrieves the object from the Namespace and Name fields\nfunc (i *Info) Get() (err error) {\n\tobj, err := NewHelper(i.Client, i.Mapping).WithSubresource(i.Subresource).Get(i.Namespace, i.Name)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) \u0026\u0026 len(i.Namespace) \u003e 0 \u0026\u0026 i.Namespace != metav1.NamespaceDefault \u0026\u0026 i.Namespace != metav1.NamespaceAll {\n\t\t\terr2 := i.Client.Get().AbsPath(\"api\", \"v1\", \"namespaces\", i.Namespace).Do(context.TODO()).Error()\n\t\t\tif err2 != nil \u0026\u0026 errors.IsNotFound(err2) {\n\t\t\t\treturn err2\n\t\t\t}\n\t\t}\n\t\treturn err\n\t}\n\ti.Object = obj\n\ti.ResourceVersion, _ = metadataAccessor.ResourceVersion(obj)\n\treturn nil\n}","line":{"from":98,"to":113}} {"id":100019526,"name":"Refresh","signature":"func (i *Info) Refresh(obj runtime.Object, ignoreError bool) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"// Refresh updates the object with another object. If ignoreError is set\n// the Object will be updated even if name, namespace, or resourceVersion\n// attributes cannot be loaded from the object.\nfunc (i *Info) Refresh(obj runtime.Object, ignoreError bool) error {\n\tname, err := metadataAccessor.Name(obj)\n\tif err != nil {\n\t\tif !ignoreError {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\ti.Name = name\n\t}\n\tnamespace, err := metadataAccessor.Namespace(obj)\n\tif err != nil {\n\t\tif !ignoreError {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\ti.Namespace = namespace\n\t}\n\tversion, err := metadataAccessor.ResourceVersion(obj)\n\tif err != nil {\n\t\tif !ignoreError {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\ti.ResourceVersion = version\n\t}\n\ti.Object = obj\n\treturn nil\n}","line":{"from":115,"to":145}} {"id":100019527,"name":"ObjectName","signature":"func (i *Info) ObjectName() string","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"// ObjectName returns an approximate form of the resource's kind/name.\nfunc (i *Info) ObjectName() string {\n\tif i.Mapping != nil {\n\t\treturn fmt.Sprintf(\"%s/%s\", i.Mapping.Resource.Resource, i.Name)\n\t}\n\tgvk := i.Object.GetObjectKind().GroupVersionKind()\n\tif len(gvk.Group) == 0 {\n\t\treturn fmt.Sprintf(\"%s/%s\", strings.ToLower(gvk.Kind), i.Name)\n\t}\n\treturn fmt.Sprintf(\"%s.%s/%s\\n\", strings.ToLower(gvk.Kind), gvk.Group, i.Name)\n}","line":{"from":147,"to":157}} {"id":100019528,"name":"String","signature":"func (i *Info) String() string","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"// String returns the general purpose string representation\nfunc (i *Info) String() string {\n\tbasicInfo := fmt.Sprintf(\"Name: %q, Namespace: %q\", i.Name, i.Namespace)\n\tif i.Mapping != nil {\n\t\tmappingInfo := fmt.Sprintf(\"Resource: %q, GroupVersionKind: %q\", i.Mapping.Resource.String(),\n\t\t\ti.Mapping.GroupVersionKind.String())\n\t\treturn fmt.Sprint(mappingInfo, \"\\n\", basicInfo)\n\t}\n\treturn basicInfo\n}","line":{"from":159,"to":168}} {"id":100019529,"name":"Namespaced","signature":"func (i *Info) Namespaced() bool","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"// Namespaced returns true if the object belongs to a namespace\nfunc (i *Info) Namespaced() bool {\n\tif i.Mapping != nil {\n\t\t// if we have RESTMapper info, use it\n\t\treturn i.Mapping.Scope.Name() == meta.RESTScopeNameNamespace\n\t}\n\t// otherwise, use the presence of a namespace in the info as an indicator\n\treturn len(i.Namespace) \u003e 0\n}","line":{"from":170,"to":178}} {"id":100019530,"name":"Watch","signature":"func (i *Info) Watch(resourceVersion string) (watch.Interface, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"// Watch returns server changes to this object after it was retrieved.\nfunc (i *Info) Watch(resourceVersion string) (watch.Interface, error) {\n\treturn NewHelper(i.Client, i.Mapping).WatchSingle(i.Namespace, i.Name, resourceVersion)\n}","line":{"from":180,"to":183}} {"id":100019531,"name":"ResourceMapping","signature":"func (i *Info) ResourceMapping() *meta.RESTMapping","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"// ResourceMapping returns the mapping for this resource and implements ResourceMapping\nfunc (i *Info) ResourceMapping() *meta.RESTMapping {\n\treturn i.Mapping\n}","line":{"from":185,"to":188}} {"id":100019532,"name":"Visit","signature":"func (l VisitorList) Visit(fn VisitorFunc) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"// Visit implements Visitor\nfunc (l VisitorList) Visit(fn VisitorFunc) error {\n\tfor i := range l {\n\t\tif err := l[i].Visit(fn); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":194,"to":202}} {"id":100019533,"name":"Visit","signature":"func (l EagerVisitorList) Visit(fn VisitorFunc) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"// Visit implements Visitor, and gathers errors that occur during processing until\n// all sub visitors have been visited.\nfunc (l EagerVisitorList) Visit(fn VisitorFunc) error {\n\tvar errs []error\n\tfor i := range l {\n\t\terr := l[i].Visit(func(info *Info, err error) error {\n\t\t\tif err != nil {\n\t\t\t\terrs = append(errs, err)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif err := fn(info, nil); err != nil {\n\t\t\t\terrs = append(errs, err)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\treturn utilerrors.NewAggregate(errs)\n}","line":{"from":208,"to":228}} {"id":100019534,"name":"ValidateSchema","signature":"func ValidateSchema(data []byte, schema ContentValidator) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"func ValidateSchema(data []byte, schema ContentValidator) error {\n\tif schema == nil {\n\t\treturn nil\n\t}\n\tif err := schema.ValidateBytes(data); err != nil {\n\t\treturn fmt.Errorf(\"error validating data: %v; %s\", err, stopValidateMessage)\n\t}\n\treturn nil\n}","line":{"from":230,"to":238}} {"id":100019535,"name":"Visit","signature":"func (v *URLVisitor) Visit(fn VisitorFunc) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"func (v *URLVisitor) Visit(fn VisitorFunc) error {\n\tbody, err := readHttpWithRetries(httpgetImpl, time.Second, v.URL.String(), v.HttpAttemptCount)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer body.Close()\n\tv.StreamVisitor.Reader = body\n\treturn v.StreamVisitor.Visit(fn)\n}","line":{"from":248,"to":256}} {"id":100019536,"name":"readHttpWithRetries","signature":"func readHttpWithRetries(get httpget, duration time.Duration, u string, attempts int) (io.ReadCloser, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"// readHttpWithRetries tries to http.Get the v.URL retries times before giving up.\nfunc readHttpWithRetries(get httpget, duration time.Duration, u string, attempts int) (io.ReadCloser, error) {\n\tvar err error\n\tif attempts \u003c= 0 {\n\t\treturn nil, fmt.Errorf(\"http attempts must be greater than 0, was %d\", attempts)\n\t}\n\tfor i := 0; i \u003c attempts; i++ {\n\t\tvar (\n\t\t\tstatusCode int\n\t\t\tstatus string\n\t\t\tbody io.ReadCloser\n\t\t)\n\t\tif i \u003e 0 {\n\t\t\ttime.Sleep(duration)\n\t\t}\n\n\t\t// Try to get the URL\n\t\tstatusCode, status, body, err = get(u)\n\n\t\t// Retry Errors\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif statusCode == http.StatusOK {\n\t\t\treturn body, nil\n\t\t}\n\t\tbody.Close()\n\t\t// Error - Set the error condition from the StatusCode\n\t\terr = fmt.Errorf(\"unable to read URL %q, server reported %s, status code=%d\", u, status, statusCode)\n\n\t\tif statusCode \u003e= 500 \u0026\u0026 statusCode \u003c 600 {\n\t\t\t// Retry 500's\n\t\t\tcontinue\n\t\t} else {\n\t\t\t// Don't retry other StatusCodes\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil, err\n}","line":{"from":258,"to":298}} {"id":100019537,"name":"httpgetImpl","signature":"func httpgetImpl(url string) (int, string, io.ReadCloser, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"// httpgetImpl Implements a function to retrieve a url and return the results.\nfunc httpgetImpl(url string) (int, string, io.ReadCloser, error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn 0, \"\", nil, err\n\t}\n\treturn resp.StatusCode, resp.Status, resp.Body, nil\n}","line":{"from":303,"to":310}} {"id":100019538,"name":"NewDecoratedVisitor","signature":"func NewDecoratedVisitor(v Visitor, fn ...VisitorFunc) Visitor","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"// NewDecoratedVisitor will create a visitor that invokes the provided visitor functions before\n// the user supplied visitor function is invoked, giving them the opportunity to mutate the Info\n// object or terminate early with an error.\nfunc NewDecoratedVisitor(v Visitor, fn ...VisitorFunc) Visitor {\n\tif len(fn) == 0 {\n\t\treturn v\n\t}\n\treturn DecoratedVisitor{v, fn}\n}","line":{"from":319,"to":327}} {"id":100019539,"name":"Visit","signature":"func (v DecoratedVisitor) Visit(fn VisitorFunc) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"// Visit implements Visitor\nfunc (v DecoratedVisitor) Visit(fn VisitorFunc) error {\n\treturn v.visitor.Visit(func(info *Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor i := range v.decorators {\n\t\t\tif err := v.decorators[i](info, nil); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn fn(info, nil)\n\t})\n}","line":{"from":329,"to":342}} {"id":100019540,"name":"Visit","signature":"func (v ContinueOnErrorVisitor) Visit(fn VisitorFunc) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"// Visit returns nil if no error occurs during traversal, a regular\n// error if one occurs, or if multiple errors occur, an aggregate\n// error. If the provided visitor fails on any individual item it\n// will not prevent the remaining items from being visited. An error\n// returned by the visitor directly may still result in some items\n// not being visited.\nfunc (v ContinueOnErrorVisitor) Visit(fn VisitorFunc) error {\n\tvar errs []error\n\terr := v.Visitor.Visit(func(info *Info, err error) error {\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t\treturn nil\n\t\t}\n\t\tif err := fn(info, nil); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\terrs = append(errs, err)\n\t}\n\tif len(errs) == 1 {\n\t\treturn errs[0]\n\t}\n\treturn utilerrors.NewAggregate(errs)\n}","line":{"from":351,"to":376}} {"id":100019541,"name":"NewFlattenListVisitor","signature":"func NewFlattenListVisitor(v Visitor, typer runtime.ObjectTyper, mapper *mapper) Visitor","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"// NewFlattenListVisitor creates a visitor that will expand list style runtime.Objects\n// into individual items and then visit them individually.\nfunc NewFlattenListVisitor(v Visitor, typer runtime.ObjectTyper, mapper *mapper) Visitor {\n\treturn FlattenListVisitor{v, typer, mapper}\n}","line":{"from":389,"to":393}} {"id":100019542,"name":"Visit","signature":"func (v FlattenListVisitor) Visit(fn VisitorFunc) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"func (v FlattenListVisitor) Visit(fn VisitorFunc) error {\n\treturn v.visitor.Visit(func(info *Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif info.Object == nil {\n\t\t\treturn fn(info, nil)\n\t\t}\n\t\tif !meta.IsListType(info.Object) {\n\t\t\treturn fn(info, nil)\n\t\t}\n\n\t\titems := []runtime.Object{}\n\t\titemsToProcess := []runtime.Object{info.Object}\n\n\t\tfor i := 0; i \u003c len(itemsToProcess); i++ {\n\t\t\tcurrObj := itemsToProcess[i]\n\t\t\tif !meta.IsListType(currObj) {\n\t\t\t\titems = append(items, currObj)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcurrItems, err := meta.ExtractList(currObj)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif errs := runtime.DecodeList(currItems, v.mapper.decoder); len(errs) \u003e 0 {\n\t\t\t\treturn utilerrors.NewAggregate(errs)\n\t\t\t}\n\t\t\titemsToProcess = append(itemsToProcess, currItems...)\n\t\t}\n\n\t\t// If we have a GroupVersionKind on the list, prioritize that when asking for info on the objects contained in the list\n\t\tvar preferredGVKs []schema.GroupVersionKind\n\t\tif info.Mapping != nil \u0026\u0026 !info.Mapping.GroupVersionKind.Empty() {\n\t\t\tpreferredGVKs = append(preferredGVKs, info.Mapping.GroupVersionKind)\n\t\t}\n\t\tvar errs []error\n\t\tfor i := range items {\n\t\t\titem, err := v.mapper.infoForObject(items[i], v.typer, preferredGVKs)\n\t\t\tif err != nil {\n\t\t\t\terrs = append(errs, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(info.ResourceVersion) != 0 {\n\t\t\t\titem.ResourceVersion = info.ResourceVersion\n\t\t\t}\n\t\t\t// propagate list source to items source\n\t\t\tif len(info.Source) != 0 {\n\t\t\t\titem.Source = info.Source\n\t\t\t}\n\t\t\tif err := fn(item, nil); err != nil {\n\t\t\t\terrs = append(errs, err)\n\t\t\t}\n\t\t}\n\t\treturn utilerrors.NewAggregate(errs)\n\t})\n}","line":{"from":395,"to":452}} {"id":100019543,"name":"ignoreFile","signature":"func ignoreFile(path string, extensions []string) bool","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"func ignoreFile(path string, extensions []string) bool {\n\tif len(extensions) == 0 {\n\t\treturn false\n\t}\n\text := filepath.Ext(path)\n\tfor _, s := range extensions {\n\t\tif s == ext {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":454,"to":465}} {"id":100019544,"name":"FileVisitorForSTDIN","signature":"func FileVisitorForSTDIN(mapper *mapper, schema ContentValidator) Visitor","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"// FileVisitorForSTDIN return a special FileVisitor just for STDIN\nfunc FileVisitorForSTDIN(mapper *mapper, schema ContentValidator) Visitor {\n\treturn \u0026FileVisitor{\n\t\tPath: constSTDINstr,\n\t\tStreamVisitor: NewStreamVisitor(nil, mapper, constSTDINstr, schema),\n\t}\n}","line":{"from":467,"to":473}} {"id":100019545,"name":"ExpandPathsToFileVisitors","signature":"func ExpandPathsToFileVisitors(mapper *mapper, paths string, recursive bool, extensions []string, schema ContentValidator) ([]Visitor, error)","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"// ExpandPathsToFileVisitors will return a slice of FileVisitors that will handle files from the provided path.\n// After FileVisitors open the files, they will pass an io.Reader to a StreamVisitor to do the reading. (stdin\n// is also taken care of). Paths argument also accepts a single file, and will return a single visitor\nfunc ExpandPathsToFileVisitors(mapper *mapper, paths string, recursive bool, extensions []string, schema ContentValidator) ([]Visitor, error) {\n\tvar visitors []Visitor\n\terr := filepath.Walk(paths, func(path string, fi os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif fi.IsDir() {\n\t\t\tif path != paths \u0026\u0026 !recursive {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\t// Don't check extension if the filepath was passed explicitly\n\t\tif path != paths \u0026\u0026 ignoreFile(path, extensions) {\n\t\t\treturn nil\n\t\t}\n\n\t\tvisitor := \u0026FileVisitor{\n\t\t\tPath: path,\n\t\t\tStreamVisitor: NewStreamVisitor(nil, mapper, path, schema),\n\t\t}\n\n\t\tvisitors = append(visitors, visitor)\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn visitors, nil\n}","line":{"from":475,"to":509}} {"id":100019546,"name":"Visit","signature":"func (v *FileVisitor) Visit(fn VisitorFunc) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"// Visit in a FileVisitor is just taking care of opening/closing files\nfunc (v *FileVisitor) Visit(fn VisitorFunc) error {\n\tvar f *os.File\n\tif v.Path == constSTDINstr {\n\t\tf = os.Stdin\n\t} else {\n\t\tvar err error\n\t\tf, err = os.Open(v.Path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\t}\n\n\t// TODO: Consider adding a flag to force to UTF16, apparently some\n\t// Windows tools don't write the BOM\n\tutf16bom := unicode.BOMOverride(unicode.UTF8.NewDecoder())\n\tv.StreamVisitor.Reader = transform.NewReader(f, utf16bom)\n\n\treturn v.StreamVisitor.Visit(fn)\n}","line":{"from":517,"to":537}} {"id":100019547,"name":"NewStreamVisitor","signature":"func NewStreamVisitor(r io.Reader, mapper *mapper, source string, schema ContentValidator) *StreamVisitor","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"// NewStreamVisitor is a helper function that is useful when we want to change the fields of the struct but keep calls the same.\nfunc NewStreamVisitor(r io.Reader, mapper *mapper, source string, schema ContentValidator) *StreamVisitor {\n\treturn \u0026StreamVisitor{\n\t\tReader: r,\n\t\tmapper: mapper,\n\t\tSource: source,\n\t\tSchema: schema,\n\t}\n}","line":{"from":551,"to":559}} {"id":100019548,"name":"Visit","signature":"func (v *StreamVisitor) Visit(fn VisitorFunc) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"// Visit implements Visitor over a stream. StreamVisitor is able to distinct multiple resources in one stream.\nfunc (v *StreamVisitor) Visit(fn VisitorFunc) error {\n\td := yaml.NewYAMLOrJSONDecoder(v.Reader, 4096)\n\tfor {\n\t\text := runtime.RawExtension{}\n\t\tif err := d.Decode(\u0026ext); err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"error parsing %s: %v\", v.Source, err)\n\t\t}\n\t\t// TODO: This needs to be able to handle object in other encodings and schemas.\n\t\text.Raw = bytes.TrimSpace(ext.Raw)\n\t\tif len(ext.Raw) == 0 || bytes.Equal(ext.Raw, []byte(\"null\")) {\n\t\t\tcontinue\n\t\t}\n\t\tif err := ValidateSchema(ext.Raw, v.Schema); err != nil {\n\t\t\treturn fmt.Errorf(\"error validating %q: %v\", v.Source, err)\n\t\t}\n\t\tinfo, err := v.infoForData(ext.Raw, v.Source)\n\t\tif err != nil {\n\t\t\tif fnErr := fn(info, err); fnErr != nil {\n\t\t\t\treturn fnErr\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif err := fn(info, nil); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}","line":{"from":561,"to":591}} {"id":100019549,"name":"UpdateObjectNamespace","signature":"func UpdateObjectNamespace(info *Info, err error) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"func UpdateObjectNamespace(info *Info, err error) error {\n\tif err != nil {\n\t\treturn err\n\t}\n\tif info.Object != nil {\n\t\treturn metadataAccessor.SetNamespace(info.Object, info.Namespace)\n\t}\n\treturn nil\n}","line":{"from":593,"to":601}} {"id":100019550,"name":"FilterNamespace","signature":"func FilterNamespace(info *Info, err error) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"// FilterNamespace omits the namespace if the object is not namespace scoped\nfunc FilterNamespace(info *Info, err error) error {\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !info.Namespaced() {\n\t\tinfo.Namespace = \"\"\n\t\tUpdateObjectNamespace(info, nil)\n\t}\n\treturn nil\n}","line":{"from":603,"to":613}} {"id":100019551,"name":"SetNamespace","signature":"func SetNamespace(namespace string) VisitorFunc","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"// SetNamespace ensures that every Info object visited will have a namespace\n// set. If info.Object is set, it will be mutated as well.\nfunc SetNamespace(namespace string) VisitorFunc {\n\treturn func(info *Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !info.Namespaced() {\n\t\t\treturn nil\n\t\t}\n\t\tif len(info.Namespace) == 0 {\n\t\t\tinfo.Namespace = namespace\n\t\t\tUpdateObjectNamespace(info, nil)\n\t\t}\n\t\treturn nil\n\t}\n}","line":{"from":615,"to":631}} {"id":100019552,"name":"RequireNamespace","signature":"func RequireNamespace(namespace string) VisitorFunc","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"// RequireNamespace will either set a namespace if none is provided on the\n// Info object, or if the namespace is set and does not match the provided\n// value, returns an error. This is intended to guard against administrators\n// accidentally operating on resources outside their namespace.\nfunc RequireNamespace(namespace string) VisitorFunc {\n\treturn func(info *Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !info.Namespaced() {\n\t\t\treturn nil\n\t\t}\n\t\tif len(info.Namespace) == 0 {\n\t\t\tinfo.Namespace = namespace\n\t\t\tUpdateObjectNamespace(info, nil)\n\t\t\treturn nil\n\t\t}\n\t\tif info.Namespace != namespace {\n\t\t\treturn fmt.Errorf(\"the namespace from the provided object %q does not match the namespace %q. You must pass '--namespace=%s' to perform this operation.\", info.Namespace, namespace, info.Namespace)\n\t\t}\n\t\treturn nil\n\t}\n}","line":{"from":633,"to":655}} {"id":100019553,"name":"RetrieveLatest","signature":"func RetrieveLatest(info *Info, err error) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"// RetrieveLatest updates the Object on each Info by invoking a standard client\n// Get.\nfunc RetrieveLatest(info *Info, err error) error {\n\tif err != nil {\n\t\treturn err\n\t}\n\tif meta.IsListType(info.Object) {\n\t\treturn fmt.Errorf(\"watch is only supported on individual resources and resource collections, but a list of resources is found\")\n\t}\n\tif len(info.Name) == 0 {\n\t\treturn nil\n\t}\n\tif info.Namespaced() \u0026\u0026 len(info.Namespace) == 0 {\n\t\treturn fmt.Errorf(\"no namespace set on resource %s %q\", info.Mapping.Resource, info.Name)\n\t}\n\treturn info.Get()\n}","line":{"from":657,"to":673}} {"id":100019554,"name":"RetrieveLazy","signature":"func RetrieveLazy(info *Info, err error) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"// RetrieveLazy updates the object if it has not been loaded yet.\nfunc RetrieveLazy(info *Info, err error) error {\n\tif err != nil {\n\t\treturn err\n\t}\n\tif info.Object == nil {\n\t\treturn info.Get()\n\t}\n\treturn nil\n}","line":{"from":675,"to":684}} {"id":100019555,"name":"NewFilteredVisitor","signature":"func NewFilteredVisitor(v Visitor, fn ...FilterFunc) Visitor","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"func NewFilteredVisitor(v Visitor, fn ...FilterFunc) Visitor {\n\tif len(fn) == 0 {\n\t\treturn v\n\t}\n\treturn FilteredVisitor{v, fn}\n}","line":{"from":693,"to":698}} {"id":100019556,"name":"Visit","signature":"func (v FilteredVisitor) Visit(fn VisitorFunc) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"func (v FilteredVisitor) Visit(fn VisitorFunc) error {\n\treturn v.visitor.Visit(func(info *Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, filter := range v.filters {\n\t\t\tok, err := filter(info, nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !ok {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\treturn fn(info, nil)\n\t})\n}","line":{"from":700,"to":716}} {"id":100019557,"name":"FilterByLabelSelector","signature":"func FilterByLabelSelector(s labels.Selector) FilterFunc","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"func FilterByLabelSelector(s labels.Selector) FilterFunc {\n\treturn func(info *Info, err error) (bool, error) {\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\ta, err := meta.Accessor(info.Object)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif !s.Matches(labels.Set(a.GetLabels())) {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t}\n}","line":{"from":718,"to":732}} {"id":100019558,"name":"Visit","signature":"func (infos InfoListVisitor) Visit(fn VisitorFunc) error","file":"staging/src/k8s.io/cli-runtime/pkg/resource/visitor.go","code":"func (infos InfoListVisitor) Visit(fn VisitorFunc) error {\n\tvar err error\n\tfor _, i := range infos {\n\t\terr = fn(i, err)\n\t}\n\treturn err\n}","line":{"from":736,"to":742}} {"id":100019559,"name":"MatchCondition","signature":"func MatchCondition() *MatchConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/matchcondition.go","code":"// MatchConditionApplyConfiguration constructs an declarative configuration of the MatchCondition type for use with\n// apply.\nfunc MatchCondition() *MatchConditionApplyConfiguration {\n\treturn \u0026MatchConditionApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100019560,"name":"WithName","signature":"func (b *MatchConditionApplyConfiguration) WithName(value string) *MatchConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/matchcondition.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *MatchConditionApplyConfiguration) WithName(value string) *MatchConditionApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100019561,"name":"WithExpression","signature":"func (b *MatchConditionApplyConfiguration) WithExpression(value string) *MatchConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/matchcondition.go","code":"// WithExpression sets the Expression field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Expression field is set to the value of the last call.\nfunc (b *MatchConditionApplyConfiguration) WithExpression(value string) *MatchConditionApplyConfiguration {\n\tb.Expression = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100019562,"name":"MutatingWebhook","signature":"func MutatingWebhook() *MutatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhook.go","code":"// MutatingWebhookApplyConfiguration constructs an declarative configuration of the MutatingWebhook type for use with\n// apply.\nfunc MutatingWebhook() *MutatingWebhookApplyConfiguration {\n\treturn \u0026MutatingWebhookApplyConfiguration{}\n}","line":{"from":43,"to":47}} {"id":100019563,"name":"WithName","signature":"func (b *MutatingWebhookApplyConfiguration) WithName(value string) *MutatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhook.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *MutatingWebhookApplyConfiguration) WithName(value string) *MutatingWebhookApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":49,"to":55}} {"id":100019564,"name":"WithClientConfig","signature":"func (b *MutatingWebhookApplyConfiguration) WithClientConfig(value *WebhookClientConfigApplyConfiguration) *MutatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhook.go","code":"// WithClientConfig sets the ClientConfig field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ClientConfig field is set to the value of the last call.\nfunc (b *MutatingWebhookApplyConfiguration) WithClientConfig(value *WebhookClientConfigApplyConfiguration) *MutatingWebhookApplyConfiguration {\n\tb.ClientConfig = value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100019565,"name":"WithRules","signature":"func (b *MutatingWebhookApplyConfiguration) WithRules(values ...*RuleWithOperationsApplyConfiguration) *MutatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhook.go","code":"// WithRules adds the given value to the Rules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Rules field.\nfunc (b *MutatingWebhookApplyConfiguration) WithRules(values ...*RuleWithOperationsApplyConfiguration) *MutatingWebhookApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRules\")\n\t\t}\n\t\tb.Rules = append(b.Rules, *values[i])\n\t}\n\treturn b\n}","line":{"from":65,"to":76}} {"id":100019566,"name":"WithFailurePolicy","signature":"func (b *MutatingWebhookApplyConfiguration) WithFailurePolicy(value admissionregistrationv1.FailurePolicyType) *MutatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhook.go","code":"// WithFailurePolicy sets the FailurePolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FailurePolicy field is set to the value of the last call.\nfunc (b *MutatingWebhookApplyConfiguration) WithFailurePolicy(value admissionregistrationv1.FailurePolicyType) *MutatingWebhookApplyConfiguration {\n\tb.FailurePolicy = \u0026value\n\treturn b\n}","line":{"from":78,"to":84}} {"id":100019567,"name":"WithMatchPolicy","signature":"func (b *MutatingWebhookApplyConfiguration) WithMatchPolicy(value admissionregistrationv1.MatchPolicyType) *MutatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhook.go","code":"// WithMatchPolicy sets the MatchPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MatchPolicy field is set to the value of the last call.\nfunc (b *MutatingWebhookApplyConfiguration) WithMatchPolicy(value admissionregistrationv1.MatchPolicyType) *MutatingWebhookApplyConfiguration {\n\tb.MatchPolicy = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100019568,"name":"WithNamespaceSelector","signature":"func (b *MutatingWebhookApplyConfiguration) WithNamespaceSelector(value *metav1.LabelSelectorApplyConfiguration) *MutatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhook.go","code":"// WithNamespaceSelector sets the NamespaceSelector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NamespaceSelector field is set to the value of the last call.\nfunc (b *MutatingWebhookApplyConfiguration) WithNamespaceSelector(value *metav1.LabelSelectorApplyConfiguration) *MutatingWebhookApplyConfiguration {\n\tb.NamespaceSelector = value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100019569,"name":"WithObjectSelector","signature":"func (b *MutatingWebhookApplyConfiguration) WithObjectSelector(value *metav1.LabelSelectorApplyConfiguration) *MutatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhook.go","code":"// WithObjectSelector sets the ObjectSelector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObjectSelector field is set to the value of the last call.\nfunc (b *MutatingWebhookApplyConfiguration) WithObjectSelector(value *metav1.LabelSelectorApplyConfiguration) *MutatingWebhookApplyConfiguration {\n\tb.ObjectSelector = value\n\treturn b\n}","line":{"from":102,"to":108}} {"id":100019570,"name":"WithSideEffects","signature":"func (b *MutatingWebhookApplyConfiguration) WithSideEffects(value admissionregistrationv1.SideEffectClass) *MutatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhook.go","code":"// WithSideEffects sets the SideEffects field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SideEffects field is set to the value of the last call.\nfunc (b *MutatingWebhookApplyConfiguration) WithSideEffects(value admissionregistrationv1.SideEffectClass) *MutatingWebhookApplyConfiguration {\n\tb.SideEffects = \u0026value\n\treturn b\n}","line":{"from":110,"to":116}} {"id":100019571,"name":"WithTimeoutSeconds","signature":"func (b *MutatingWebhookApplyConfiguration) WithTimeoutSeconds(value int32) *MutatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhook.go","code":"// WithTimeoutSeconds sets the TimeoutSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TimeoutSeconds field is set to the value of the last call.\nfunc (b *MutatingWebhookApplyConfiguration) WithTimeoutSeconds(value int32) *MutatingWebhookApplyConfiguration {\n\tb.TimeoutSeconds = \u0026value\n\treturn b\n}","line":{"from":118,"to":124}} {"id":100019572,"name":"WithAdmissionReviewVersions","signature":"func (b *MutatingWebhookApplyConfiguration) WithAdmissionReviewVersions(values ...string) *MutatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhook.go","code":"// WithAdmissionReviewVersions adds the given value to the AdmissionReviewVersions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the AdmissionReviewVersions field.\nfunc (b *MutatingWebhookApplyConfiguration) WithAdmissionReviewVersions(values ...string) *MutatingWebhookApplyConfiguration {\n\tfor i := range values {\n\t\tb.AdmissionReviewVersions = append(b.AdmissionReviewVersions, values[i])\n\t}\n\treturn b\n}","line":{"from":126,"to":134}} {"id":100019573,"name":"WithReinvocationPolicy","signature":"func (b *MutatingWebhookApplyConfiguration) WithReinvocationPolicy(value admissionregistrationv1.ReinvocationPolicyType) *MutatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhook.go","code":"// WithReinvocationPolicy sets the ReinvocationPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReinvocationPolicy field is set to the value of the last call.\nfunc (b *MutatingWebhookApplyConfiguration) WithReinvocationPolicy(value admissionregistrationv1.ReinvocationPolicyType) *MutatingWebhookApplyConfiguration {\n\tb.ReinvocationPolicy = \u0026value\n\treturn b\n}","line":{"from":136,"to":142}} {"id":100019574,"name":"WithMatchConditions","signature":"func (b *MutatingWebhookApplyConfiguration) WithMatchConditions(values ...*MatchConditionApplyConfiguration) *MutatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhook.go","code":"// WithMatchConditions adds the given value to the MatchConditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the MatchConditions field.\nfunc (b *MutatingWebhookApplyConfiguration) WithMatchConditions(values ...*MatchConditionApplyConfiguration) *MutatingWebhookApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithMatchConditions\")\n\t\t}\n\t\tb.MatchConditions = append(b.MatchConditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":144,"to":155}} {"id":100019575,"name":"MutatingWebhookConfiguration","signature":"func MutatingWebhookConfiguration(name string) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// MutatingWebhookConfiguration constructs an declarative configuration of the MutatingWebhookConfiguration type for use with\n// apply.\nfunc MutatingWebhookConfiguration(name string) *MutatingWebhookConfigurationApplyConfiguration {\n\tb := \u0026MutatingWebhookConfigurationApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"MutatingWebhookConfiguration\")\n\tb.WithAPIVersion(\"admissionregistration.k8s.io/v1\")\n\treturn b\n}","line":{"from":38,"to":46}} {"id":100019576,"name":"ExtractMutatingWebhookConfiguration","signature":"func ExtractMutatingWebhookConfiguration(mutatingWebhookConfiguration *apiadmissionregistrationv1.MutatingWebhookConfiguration, fieldManager string) (*MutatingWebhookConfigurationApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// ExtractMutatingWebhookConfiguration extracts the applied configuration owned by fieldManager from\n// mutatingWebhookConfiguration. If no managedFields are found in mutatingWebhookConfiguration for fieldManager, a\n// MutatingWebhookConfigurationApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// mutatingWebhookConfiguration must be a unmodified MutatingWebhookConfiguration API object that was retrieved from the Kubernetes API.\n// ExtractMutatingWebhookConfiguration provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractMutatingWebhookConfiguration(mutatingWebhookConfiguration *apiadmissionregistrationv1.MutatingWebhookConfiguration, fieldManager string) (*MutatingWebhookConfigurationApplyConfiguration, error) {\n\treturn extractMutatingWebhookConfiguration(mutatingWebhookConfiguration, fieldManager, \"\")\n}","line":{"from":48,"to":61}} {"id":100019577,"name":"ExtractMutatingWebhookConfigurationStatus","signature":"func ExtractMutatingWebhookConfigurationStatus(mutatingWebhookConfiguration *apiadmissionregistrationv1.MutatingWebhookConfiguration, fieldManager string) (*MutatingWebhookConfigurationApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// ExtractMutatingWebhookConfigurationStatus is the same as ExtractMutatingWebhookConfiguration except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractMutatingWebhookConfigurationStatus(mutatingWebhookConfiguration *apiadmissionregistrationv1.MutatingWebhookConfiguration, fieldManager string) (*MutatingWebhookConfigurationApplyConfiguration, error) {\n\treturn extractMutatingWebhookConfiguration(mutatingWebhookConfiguration, fieldManager, \"status\")\n}","line":{"from":63,"to":68}} {"id":100019578,"name":"extractMutatingWebhookConfiguration","signature":"func extractMutatingWebhookConfiguration(mutatingWebhookConfiguration *apiadmissionregistrationv1.MutatingWebhookConfiguration, fieldManager string, subresource string) (*MutatingWebhookConfigurationApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"func extractMutatingWebhookConfiguration(mutatingWebhookConfiguration *apiadmissionregistrationv1.MutatingWebhookConfiguration, fieldManager string, subresource string) (*MutatingWebhookConfigurationApplyConfiguration, error) {\n\tb := \u0026MutatingWebhookConfigurationApplyConfiguration{}\n\terr := managedfields.ExtractInto(mutatingWebhookConfiguration, internal.Parser().Type(\"io.k8s.api.admissionregistration.v1.MutatingWebhookConfiguration\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(mutatingWebhookConfiguration.Name)\n\n\tb.WithKind(\"MutatingWebhookConfiguration\")\n\tb.WithAPIVersion(\"admissionregistration.k8s.io/v1\")\n\treturn b, nil\n}","line":{"from":70,"to":81}} {"id":100019579,"name":"WithKind","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithKind(value string) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithKind(value string) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100019580,"name":"WithAPIVersion","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithAPIVersion(value string) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithAPIVersion(value string) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":91,"to":97}} {"id":100019581,"name":"WithName","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithName(value string) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithName(value string) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":99,"to":106}} {"id":100019582,"name":"WithGenerateName","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithGenerateName(value string) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithGenerateName(value string) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":108,"to":115}} {"id":100019583,"name":"WithNamespace","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithNamespace(value string) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithNamespace(value string) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":117,"to":124}} {"id":100019584,"name":"WithUID","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithUID(value types.UID) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithUID(value types.UID) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":126,"to":133}} {"id":100019585,"name":"WithResourceVersion","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithResourceVersion(value string) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithResourceVersion(value string) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":135,"to":142}} {"id":100019586,"name":"WithGeneration","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithGeneration(value int64) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithGeneration(value int64) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":144,"to":151}} {"id":100019587,"name":"WithCreationTimestamp","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithCreationTimestamp(value metav1.Time) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithCreationTimestamp(value metav1.Time) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":153,"to":160}} {"id":100019588,"name":"WithDeletionTimestamp","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":162,"to":169}} {"id":100019589,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":171,"to":178}} {"id":100019590,"name":"WithLabels","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithLabels(entries map[string]string) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithLabels(entries map[string]string) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":180,"to":193}} {"id":100019591,"name":"WithAnnotations","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithAnnotations(entries map[string]string) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithAnnotations(entries map[string]string) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":195,"to":208}} {"id":100019592,"name":"WithOwnerReferences","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":210,"to":222}} {"id":100019593,"name":"WithFinalizers","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithFinalizers(values ...string) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithFinalizers(values ...string) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":224,"to":233}} {"id":100019594,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"func (b *MutatingWebhookConfigurationApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":235,"to":239}} {"id":100019595,"name":"WithWebhooks","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithWebhooks(values ...*MutatingWebhookApplyConfiguration) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// WithWebhooks adds the given value to the Webhooks field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Webhooks field.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithWebhooks(values ...*MutatingWebhookApplyConfiguration) *MutatingWebhookConfigurationApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithWebhooks\")\n\t\t}\n\t\tb.Webhooks = append(b.Webhooks, *values[i])\n\t}\n\treturn b\n}","line":{"from":241,"to":252}} {"id":100019596,"name":"Rule","signature":"func Rule() *RuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/rule.go","code":"// RuleApplyConfiguration constructs an declarative configuration of the Rule type for use with\n// apply.\nfunc Rule() *RuleApplyConfiguration {\n\treturn \u0026RuleApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100019597,"name":"WithAPIGroups","signature":"func (b *RuleApplyConfiguration) WithAPIGroups(values ...string) *RuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/rule.go","code":"// WithAPIGroups adds the given value to the APIGroups field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the APIGroups field.\nfunc (b *RuleApplyConfiguration) WithAPIGroups(values ...string) *RuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.APIGroups = append(b.APIGroups, values[i])\n\t}\n\treturn b\n}","line":{"from":40,"to":48}} {"id":100019598,"name":"WithAPIVersions","signature":"func (b *RuleApplyConfiguration) WithAPIVersions(values ...string) *RuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/rule.go","code":"// WithAPIVersions adds the given value to the APIVersions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the APIVersions field.\nfunc (b *RuleApplyConfiguration) WithAPIVersions(values ...string) *RuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.APIVersions = append(b.APIVersions, values[i])\n\t}\n\treturn b\n}","line":{"from":50,"to":58}} {"id":100019599,"name":"WithResources","signature":"func (b *RuleApplyConfiguration) WithResources(values ...string) *RuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/rule.go","code":"// WithResources adds the given value to the Resources field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Resources field.\nfunc (b *RuleApplyConfiguration) WithResources(values ...string) *RuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.Resources = append(b.Resources, values[i])\n\t}\n\treturn b\n}","line":{"from":60,"to":68}} {"id":100019600,"name":"WithScope","signature":"func (b *RuleApplyConfiguration) WithScope(value v1.ScopeType) *RuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/rule.go","code":"// WithScope sets the Scope field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Scope field is set to the value of the last call.\nfunc (b *RuleApplyConfiguration) WithScope(value v1.ScopeType) *RuleApplyConfiguration {\n\tb.Scope = \u0026value\n\treturn b\n}","line":{"from":70,"to":76}} {"id":100019601,"name":"RuleWithOperations","signature":"func RuleWithOperations() *RuleWithOperationsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/rulewithoperations.go","code":"// RuleWithOperationsApplyConfiguration constructs an declarative configuration of the RuleWithOperations type for use with\n// apply.\nfunc RuleWithOperations() *RuleWithOperationsApplyConfiguration {\n\treturn \u0026RuleWithOperationsApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100019602,"name":"WithOperations","signature":"func (b *RuleWithOperationsApplyConfiguration) WithOperations(values ...v1.OperationType) *RuleWithOperationsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/rulewithoperations.go","code":"// WithOperations adds the given value to the Operations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Operations field.\nfunc (b *RuleWithOperationsApplyConfiguration) WithOperations(values ...v1.OperationType) *RuleWithOperationsApplyConfiguration {\n\tfor i := range values {\n\t\tb.Operations = append(b.Operations, values[i])\n\t}\n\treturn b\n}","line":{"from":38,"to":46}} {"id":100019603,"name":"WithAPIGroups","signature":"func (b *RuleWithOperationsApplyConfiguration) WithAPIGroups(values ...string) *RuleWithOperationsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/rulewithoperations.go","code":"// WithAPIGroups adds the given value to the APIGroups field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the APIGroups field.\nfunc (b *RuleWithOperationsApplyConfiguration) WithAPIGroups(values ...string) *RuleWithOperationsApplyConfiguration {\n\tfor i := range values {\n\t\tb.APIGroups = append(b.APIGroups, values[i])\n\t}\n\treturn b\n}","line":{"from":48,"to":56}} {"id":100019604,"name":"WithAPIVersions","signature":"func (b *RuleWithOperationsApplyConfiguration) WithAPIVersions(values ...string) *RuleWithOperationsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/rulewithoperations.go","code":"// WithAPIVersions adds the given value to the APIVersions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the APIVersions field.\nfunc (b *RuleWithOperationsApplyConfiguration) WithAPIVersions(values ...string) *RuleWithOperationsApplyConfiguration {\n\tfor i := range values {\n\t\tb.APIVersions = append(b.APIVersions, values[i])\n\t}\n\treturn b\n}","line":{"from":58,"to":66}} {"id":100019605,"name":"WithResources","signature":"func (b *RuleWithOperationsApplyConfiguration) WithResources(values ...string) *RuleWithOperationsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/rulewithoperations.go","code":"// WithResources adds the given value to the Resources field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Resources field.\nfunc (b *RuleWithOperationsApplyConfiguration) WithResources(values ...string) *RuleWithOperationsApplyConfiguration {\n\tfor i := range values {\n\t\tb.Resources = append(b.Resources, values[i])\n\t}\n\treturn b\n}","line":{"from":68,"to":76}} {"id":100019606,"name":"WithScope","signature":"func (b *RuleWithOperationsApplyConfiguration) WithScope(value v1.ScopeType) *RuleWithOperationsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/rulewithoperations.go","code":"// WithScope sets the Scope field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Scope field is set to the value of the last call.\nfunc (b *RuleWithOperationsApplyConfiguration) WithScope(value v1.ScopeType) *RuleWithOperationsApplyConfiguration {\n\tb.Scope = \u0026value\n\treturn b\n}","line":{"from":78,"to":84}} {"id":100019607,"name":"ServiceReference","signature":"func ServiceReference() *ServiceReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/servicereference.go","code":"// ServiceReferenceApplyConfiguration constructs an declarative configuration of the ServiceReference type for use with\n// apply.\nfunc ServiceReference() *ServiceReferenceApplyConfiguration {\n\treturn \u0026ServiceReferenceApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100019608,"name":"WithNamespace","signature":"func (b *ServiceReferenceApplyConfiguration) WithNamespace(value string) *ServiceReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/servicereference.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ServiceReferenceApplyConfiguration) WithNamespace(value string) *ServiceReferenceApplyConfiguration {\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100019609,"name":"WithName","signature":"func (b *ServiceReferenceApplyConfiguration) WithName(value string) *ServiceReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/servicereference.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ServiceReferenceApplyConfiguration) WithName(value string) *ServiceReferenceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100019610,"name":"WithPath","signature":"func (b *ServiceReferenceApplyConfiguration) WithPath(value string) *ServiceReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/servicereference.go","code":"// WithPath sets the Path field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Path field is set to the value of the last call.\nfunc (b *ServiceReferenceApplyConfiguration) WithPath(value string) *ServiceReferenceApplyConfiguration {\n\tb.Path = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100019611,"name":"WithPort","signature":"func (b *ServiceReferenceApplyConfiguration) WithPort(value int32) *ServiceReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/servicereference.go","code":"// WithPort sets the Port field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Port field is set to the value of the last call.\nfunc (b *ServiceReferenceApplyConfiguration) WithPort(value int32) *ServiceReferenceApplyConfiguration {\n\tb.Port = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100019612,"name":"ValidatingWebhook","signature":"func ValidatingWebhook() *ValidatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhook.go","code":"// ValidatingWebhookApplyConfiguration constructs an declarative configuration of the ValidatingWebhook type for use with\n// apply.\nfunc ValidatingWebhook() *ValidatingWebhookApplyConfiguration {\n\treturn \u0026ValidatingWebhookApplyConfiguration{}\n}","line":{"from":42,"to":46}} {"id":100019613,"name":"WithName","signature":"func (b *ValidatingWebhookApplyConfiguration) WithName(value string) *ValidatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhook.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ValidatingWebhookApplyConfiguration) WithName(value string) *ValidatingWebhookApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100019614,"name":"WithClientConfig","signature":"func (b *ValidatingWebhookApplyConfiguration) WithClientConfig(value *WebhookClientConfigApplyConfiguration) *ValidatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhook.go","code":"// WithClientConfig sets the ClientConfig field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ClientConfig field is set to the value of the last call.\nfunc (b *ValidatingWebhookApplyConfiguration) WithClientConfig(value *WebhookClientConfigApplyConfiguration) *ValidatingWebhookApplyConfiguration {\n\tb.ClientConfig = value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100019615,"name":"WithRules","signature":"func (b *ValidatingWebhookApplyConfiguration) WithRules(values ...*RuleWithOperationsApplyConfiguration) *ValidatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhook.go","code":"// WithRules adds the given value to the Rules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Rules field.\nfunc (b *ValidatingWebhookApplyConfiguration) WithRules(values ...*RuleWithOperationsApplyConfiguration) *ValidatingWebhookApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRules\")\n\t\t}\n\t\tb.Rules = append(b.Rules, *values[i])\n\t}\n\treturn b\n}","line":{"from":64,"to":75}} {"id":100019616,"name":"WithFailurePolicy","signature":"func (b *ValidatingWebhookApplyConfiguration) WithFailurePolicy(value admissionregistrationv1.FailurePolicyType) *ValidatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhook.go","code":"// WithFailurePolicy sets the FailurePolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FailurePolicy field is set to the value of the last call.\nfunc (b *ValidatingWebhookApplyConfiguration) WithFailurePolicy(value admissionregistrationv1.FailurePolicyType) *ValidatingWebhookApplyConfiguration {\n\tb.FailurePolicy = \u0026value\n\treturn b\n}","line":{"from":77,"to":83}} {"id":100019617,"name":"WithMatchPolicy","signature":"func (b *ValidatingWebhookApplyConfiguration) WithMatchPolicy(value admissionregistrationv1.MatchPolicyType) *ValidatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhook.go","code":"// WithMatchPolicy sets the MatchPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MatchPolicy field is set to the value of the last call.\nfunc (b *ValidatingWebhookApplyConfiguration) WithMatchPolicy(value admissionregistrationv1.MatchPolicyType) *ValidatingWebhookApplyConfiguration {\n\tb.MatchPolicy = \u0026value\n\treturn b\n}","line":{"from":85,"to":91}} {"id":100019618,"name":"WithNamespaceSelector","signature":"func (b *ValidatingWebhookApplyConfiguration) WithNamespaceSelector(value *metav1.LabelSelectorApplyConfiguration) *ValidatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhook.go","code":"// WithNamespaceSelector sets the NamespaceSelector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NamespaceSelector field is set to the value of the last call.\nfunc (b *ValidatingWebhookApplyConfiguration) WithNamespaceSelector(value *metav1.LabelSelectorApplyConfiguration) *ValidatingWebhookApplyConfiguration {\n\tb.NamespaceSelector = value\n\treturn b\n}","line":{"from":93,"to":99}} {"id":100019619,"name":"WithObjectSelector","signature":"func (b *ValidatingWebhookApplyConfiguration) WithObjectSelector(value *metav1.LabelSelectorApplyConfiguration) *ValidatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhook.go","code":"// WithObjectSelector sets the ObjectSelector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObjectSelector field is set to the value of the last call.\nfunc (b *ValidatingWebhookApplyConfiguration) WithObjectSelector(value *metav1.LabelSelectorApplyConfiguration) *ValidatingWebhookApplyConfiguration {\n\tb.ObjectSelector = value\n\treturn b\n}","line":{"from":101,"to":107}} {"id":100019620,"name":"WithSideEffects","signature":"func (b *ValidatingWebhookApplyConfiguration) WithSideEffects(value admissionregistrationv1.SideEffectClass) *ValidatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhook.go","code":"// WithSideEffects sets the SideEffects field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SideEffects field is set to the value of the last call.\nfunc (b *ValidatingWebhookApplyConfiguration) WithSideEffects(value admissionregistrationv1.SideEffectClass) *ValidatingWebhookApplyConfiguration {\n\tb.SideEffects = \u0026value\n\treturn b\n}","line":{"from":109,"to":115}} {"id":100019621,"name":"WithTimeoutSeconds","signature":"func (b *ValidatingWebhookApplyConfiguration) WithTimeoutSeconds(value int32) *ValidatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhook.go","code":"// WithTimeoutSeconds sets the TimeoutSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TimeoutSeconds field is set to the value of the last call.\nfunc (b *ValidatingWebhookApplyConfiguration) WithTimeoutSeconds(value int32) *ValidatingWebhookApplyConfiguration {\n\tb.TimeoutSeconds = \u0026value\n\treturn b\n}","line":{"from":117,"to":123}} {"id":100019622,"name":"WithAdmissionReviewVersions","signature":"func (b *ValidatingWebhookApplyConfiguration) WithAdmissionReviewVersions(values ...string) *ValidatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhook.go","code":"// WithAdmissionReviewVersions adds the given value to the AdmissionReviewVersions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the AdmissionReviewVersions field.\nfunc (b *ValidatingWebhookApplyConfiguration) WithAdmissionReviewVersions(values ...string) *ValidatingWebhookApplyConfiguration {\n\tfor i := range values {\n\t\tb.AdmissionReviewVersions = append(b.AdmissionReviewVersions, values[i])\n\t}\n\treturn b\n}","line":{"from":125,"to":133}} {"id":100019623,"name":"WithMatchConditions","signature":"func (b *ValidatingWebhookApplyConfiguration) WithMatchConditions(values ...*MatchConditionApplyConfiguration) *ValidatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhook.go","code":"// WithMatchConditions adds the given value to the MatchConditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the MatchConditions field.\nfunc (b *ValidatingWebhookApplyConfiguration) WithMatchConditions(values ...*MatchConditionApplyConfiguration) *ValidatingWebhookApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithMatchConditions\")\n\t\t}\n\t\tb.MatchConditions = append(b.MatchConditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":135,"to":146}} {"id":100019624,"name":"ValidatingWebhookConfiguration","signature":"func ValidatingWebhookConfiguration(name string) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// ValidatingWebhookConfiguration constructs an declarative configuration of the ValidatingWebhookConfiguration type for use with\n// apply.\nfunc ValidatingWebhookConfiguration(name string) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb := \u0026ValidatingWebhookConfigurationApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"ValidatingWebhookConfiguration\")\n\tb.WithAPIVersion(\"admissionregistration.k8s.io/v1\")\n\treturn b\n}","line":{"from":38,"to":46}} {"id":100019625,"name":"ExtractValidatingWebhookConfiguration","signature":"func ExtractValidatingWebhookConfiguration(validatingWebhookConfiguration *apiadmissionregistrationv1.ValidatingWebhookConfiguration, fieldManager string) (*ValidatingWebhookConfigurationApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// ExtractValidatingWebhookConfiguration extracts the applied configuration owned by fieldManager from\n// validatingWebhookConfiguration. If no managedFields are found in validatingWebhookConfiguration for fieldManager, a\n// ValidatingWebhookConfigurationApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// validatingWebhookConfiguration must be a unmodified ValidatingWebhookConfiguration API object that was retrieved from the Kubernetes API.\n// ExtractValidatingWebhookConfiguration provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractValidatingWebhookConfiguration(validatingWebhookConfiguration *apiadmissionregistrationv1.ValidatingWebhookConfiguration, fieldManager string) (*ValidatingWebhookConfigurationApplyConfiguration, error) {\n\treturn extractValidatingWebhookConfiguration(validatingWebhookConfiguration, fieldManager, \"\")\n}","line":{"from":48,"to":61}} {"id":100019626,"name":"ExtractValidatingWebhookConfigurationStatus","signature":"func ExtractValidatingWebhookConfigurationStatus(validatingWebhookConfiguration *apiadmissionregistrationv1.ValidatingWebhookConfiguration, fieldManager string) (*ValidatingWebhookConfigurationApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// ExtractValidatingWebhookConfigurationStatus is the same as ExtractValidatingWebhookConfiguration except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractValidatingWebhookConfigurationStatus(validatingWebhookConfiguration *apiadmissionregistrationv1.ValidatingWebhookConfiguration, fieldManager string) (*ValidatingWebhookConfigurationApplyConfiguration, error) {\n\treturn extractValidatingWebhookConfiguration(validatingWebhookConfiguration, fieldManager, \"status\")\n}","line":{"from":63,"to":68}} {"id":100019627,"name":"extractValidatingWebhookConfiguration","signature":"func extractValidatingWebhookConfiguration(validatingWebhookConfiguration *apiadmissionregistrationv1.ValidatingWebhookConfiguration, fieldManager string, subresource string) (*ValidatingWebhookConfigurationApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhookconfiguration.go","code":"func extractValidatingWebhookConfiguration(validatingWebhookConfiguration *apiadmissionregistrationv1.ValidatingWebhookConfiguration, fieldManager string, subresource string) (*ValidatingWebhookConfigurationApplyConfiguration, error) {\n\tb := \u0026ValidatingWebhookConfigurationApplyConfiguration{}\n\terr := managedfields.ExtractInto(validatingWebhookConfiguration, internal.Parser().Type(\"io.k8s.api.admissionregistration.v1.ValidatingWebhookConfiguration\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(validatingWebhookConfiguration.Name)\n\n\tb.WithKind(\"ValidatingWebhookConfiguration\")\n\tb.WithAPIVersion(\"admissionregistration.k8s.io/v1\")\n\treturn b, nil\n}","line":{"from":70,"to":81}} {"id":100019628,"name":"WithKind","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithKind(value string) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithKind(value string) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100019629,"name":"WithAPIVersion","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithAPIVersion(value string) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithAPIVersion(value string) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":91,"to":97}} {"id":100019630,"name":"WithName","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithName(value string) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithName(value string) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":99,"to":106}} {"id":100019631,"name":"WithGenerateName","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithGenerateName(value string) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithGenerateName(value string) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":108,"to":115}} {"id":100019632,"name":"WithNamespace","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithNamespace(value string) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithNamespace(value string) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":117,"to":124}} {"id":100019633,"name":"WithUID","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithUID(value types.UID) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithUID(value types.UID) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":126,"to":133}} {"id":100019634,"name":"WithResourceVersion","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithResourceVersion(value string) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithResourceVersion(value string) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":135,"to":142}} {"id":100019635,"name":"WithGeneration","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithGeneration(value int64) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithGeneration(value int64) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":144,"to":151}} {"id":100019636,"name":"WithCreationTimestamp","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":153,"to":160}} {"id":100019637,"name":"WithDeletionTimestamp","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":162,"to":169}} {"id":100019638,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":171,"to":178}} {"id":100019639,"name":"WithLabels","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithLabels(entries map[string]string) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithLabels(entries map[string]string) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":180,"to":193}} {"id":100019640,"name":"WithAnnotations","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithAnnotations(entries map[string]string) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithAnnotations(entries map[string]string) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":195,"to":208}} {"id":100019641,"name":"WithOwnerReferences","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":210,"to":222}} {"id":100019642,"name":"WithFinalizers","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithFinalizers(values ...string) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithFinalizers(values ...string) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":224,"to":233}} {"id":100019643,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhookconfiguration.go","code":"func (b *ValidatingWebhookConfigurationApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":235,"to":239}} {"id":100019644,"name":"WithWebhooks","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithWebhooks(values ...*ValidatingWebhookApplyConfiguration) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// WithWebhooks adds the given value to the Webhooks field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Webhooks field.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithWebhooks(values ...*ValidatingWebhookApplyConfiguration) *ValidatingWebhookConfigurationApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithWebhooks\")\n\t\t}\n\t\tb.Webhooks = append(b.Webhooks, *values[i])\n\t}\n\treturn b\n}","line":{"from":241,"to":252}} {"id":100019645,"name":"WebhookClientConfig","signature":"func WebhookClientConfig() *WebhookClientConfigApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/webhookclientconfig.go","code":"// WebhookClientConfigApplyConfiguration constructs an declarative configuration of the WebhookClientConfig type for use with\n// apply.\nfunc WebhookClientConfig() *WebhookClientConfigApplyConfiguration {\n\treturn \u0026WebhookClientConfigApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100019646,"name":"WithURL","signature":"func (b *WebhookClientConfigApplyConfiguration) WithURL(value string) *WebhookClientConfigApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/webhookclientconfig.go","code":"// WithURL sets the URL field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the URL field is set to the value of the last call.\nfunc (b *WebhookClientConfigApplyConfiguration) WithURL(value string) *WebhookClientConfigApplyConfiguration {\n\tb.URL = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100019647,"name":"WithService","signature":"func (b *WebhookClientConfigApplyConfiguration) WithService(value *ServiceReferenceApplyConfiguration) *WebhookClientConfigApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/webhookclientconfig.go","code":"// WithService sets the Service field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Service field is set to the value of the last call.\nfunc (b *WebhookClientConfigApplyConfiguration) WithService(value *ServiceReferenceApplyConfiguration) *WebhookClientConfigApplyConfiguration {\n\tb.Service = value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100019648,"name":"WithCABundle","signature":"func (b *WebhookClientConfigApplyConfiguration) WithCABundle(values ...byte) *WebhookClientConfigApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1/webhookclientconfig.go","code":"// WithCABundle adds the given value to the CABundle field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the CABundle field.\nfunc (b *WebhookClientConfigApplyConfiguration) WithCABundle(values ...byte) *WebhookClientConfigApplyConfiguration {\n\tfor i := range values {\n\t\tb.CABundle = append(b.CABundle, values[i])\n\t}\n\treturn b\n}","line":{"from":51,"to":59}} {"id":100019649,"name":"AuditAnnotation","signature":"func AuditAnnotation() *AuditAnnotationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/auditannotation.go","code":"// AuditAnnotationApplyConfiguration constructs an declarative configuration of the AuditAnnotation type for use with\n// apply.\nfunc AuditAnnotation() *AuditAnnotationApplyConfiguration {\n\treturn \u0026AuditAnnotationApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100019650,"name":"WithKey","signature":"func (b *AuditAnnotationApplyConfiguration) WithKey(value string) *AuditAnnotationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/auditannotation.go","code":"// WithKey sets the Key field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Key field is set to the value of the last call.\nfunc (b *AuditAnnotationApplyConfiguration) WithKey(value string) *AuditAnnotationApplyConfiguration {\n\tb.Key = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100019651,"name":"WithValueExpression","signature":"func (b *AuditAnnotationApplyConfiguration) WithValueExpression(value string) *AuditAnnotationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/auditannotation.go","code":"// WithValueExpression sets the ValueExpression field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ValueExpression field is set to the value of the last call.\nfunc (b *AuditAnnotationApplyConfiguration) WithValueExpression(value string) *AuditAnnotationApplyConfiguration {\n\tb.ValueExpression = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100019652,"name":"ExpressionWarning","signature":"func ExpressionWarning() *ExpressionWarningApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/expressionwarning.go","code":"// ExpressionWarningApplyConfiguration constructs an declarative configuration of the ExpressionWarning type for use with\n// apply.\nfunc ExpressionWarning() *ExpressionWarningApplyConfiguration {\n\treturn \u0026ExpressionWarningApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100019653,"name":"WithFieldRef","signature":"func (b *ExpressionWarningApplyConfiguration) WithFieldRef(value string) *ExpressionWarningApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/expressionwarning.go","code":"// WithFieldRef sets the FieldRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FieldRef field is set to the value of the last call.\nfunc (b *ExpressionWarningApplyConfiguration) WithFieldRef(value string) *ExpressionWarningApplyConfiguration {\n\tb.FieldRef = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100019654,"name":"WithWarning","signature":"func (b *ExpressionWarningApplyConfiguration) WithWarning(value string) *ExpressionWarningApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/expressionwarning.go","code":"// WithWarning sets the Warning field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Warning field is set to the value of the last call.\nfunc (b *ExpressionWarningApplyConfiguration) WithWarning(value string) *ExpressionWarningApplyConfiguration {\n\tb.Warning = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100019655,"name":"MatchCondition","signature":"func MatchCondition() *MatchConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/matchcondition.go","code":"// MatchConditionApplyConfiguration constructs an declarative configuration of the MatchCondition type for use with\n// apply.\nfunc MatchCondition() *MatchConditionApplyConfiguration {\n\treturn \u0026MatchConditionApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100019656,"name":"WithName","signature":"func (b *MatchConditionApplyConfiguration) WithName(value string) *MatchConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/matchcondition.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *MatchConditionApplyConfiguration) WithName(value string) *MatchConditionApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100019657,"name":"WithExpression","signature":"func (b *MatchConditionApplyConfiguration) WithExpression(value string) *MatchConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/matchcondition.go","code":"// WithExpression sets the Expression field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Expression field is set to the value of the last call.\nfunc (b *MatchConditionApplyConfiguration) WithExpression(value string) *MatchConditionApplyConfiguration {\n\tb.Expression = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100019658,"name":"MatchResources","signature":"func MatchResources() *MatchResourcesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/matchresources.go","code":"// MatchResourcesApplyConfiguration constructs an declarative configuration of the MatchResources type for use with\n// apply.\nfunc MatchResources() *MatchResourcesApplyConfiguration {\n\treturn \u0026MatchResourcesApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100019659,"name":"WithNamespaceSelector","signature":"func (b *MatchResourcesApplyConfiguration) WithNamespaceSelector(value *v1.LabelSelectorApplyConfiguration) *MatchResourcesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/matchresources.go","code":"// WithNamespaceSelector sets the NamespaceSelector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NamespaceSelector field is set to the value of the last call.\nfunc (b *MatchResourcesApplyConfiguration) WithNamespaceSelector(value *v1.LabelSelectorApplyConfiguration) *MatchResourcesApplyConfiguration {\n\tb.NamespaceSelector = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100019660,"name":"WithObjectSelector","signature":"func (b *MatchResourcesApplyConfiguration) WithObjectSelector(value *v1.LabelSelectorApplyConfiguration) *MatchResourcesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/matchresources.go","code":"// WithObjectSelector sets the ObjectSelector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObjectSelector field is set to the value of the last call.\nfunc (b *MatchResourcesApplyConfiguration) WithObjectSelector(value *v1.LabelSelectorApplyConfiguration) *MatchResourcesApplyConfiguration {\n\tb.ObjectSelector = value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100019661,"name":"WithResourceRules","signature":"func (b *MatchResourcesApplyConfiguration) WithResourceRules(values ...*NamedRuleWithOperationsApplyConfiguration) *MatchResourcesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/matchresources.go","code":"// WithResourceRules adds the given value to the ResourceRules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ResourceRules field.\nfunc (b *MatchResourcesApplyConfiguration) WithResourceRules(values ...*NamedRuleWithOperationsApplyConfiguration) *MatchResourcesApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithResourceRules\")\n\t\t}\n\t\tb.ResourceRules = append(b.ResourceRules, *values[i])\n\t}\n\treturn b\n}","line":{"from":58,"to":69}} {"id":100019662,"name":"WithExcludeResourceRules","signature":"func (b *MatchResourcesApplyConfiguration) WithExcludeResourceRules(values ...*NamedRuleWithOperationsApplyConfiguration) *MatchResourcesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/matchresources.go","code":"// WithExcludeResourceRules adds the given value to the ExcludeResourceRules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ExcludeResourceRules field.\nfunc (b *MatchResourcesApplyConfiguration) WithExcludeResourceRules(values ...*NamedRuleWithOperationsApplyConfiguration) *MatchResourcesApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithExcludeResourceRules\")\n\t\t}\n\t\tb.ExcludeResourceRules = append(b.ExcludeResourceRules, *values[i])\n\t}\n\treturn b\n}","line":{"from":71,"to":82}} {"id":100019663,"name":"WithMatchPolicy","signature":"func (b *MatchResourcesApplyConfiguration) WithMatchPolicy(value admissionregistrationv1alpha1.MatchPolicyType) *MatchResourcesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/matchresources.go","code":"// WithMatchPolicy sets the MatchPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MatchPolicy field is set to the value of the last call.\nfunc (b *MatchResourcesApplyConfiguration) WithMatchPolicy(value admissionregistrationv1alpha1.MatchPolicyType) *MatchResourcesApplyConfiguration {\n\tb.MatchPolicy = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100019664,"name":"NamedRuleWithOperations","signature":"func NamedRuleWithOperations() *NamedRuleWithOperationsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/namedrulewithoperations.go","code":"// NamedRuleWithOperationsApplyConfiguration constructs an declarative configuration of the NamedRuleWithOperations type for use with\n// apply.\nfunc NamedRuleWithOperations() *NamedRuleWithOperationsApplyConfiguration {\n\treturn \u0026NamedRuleWithOperationsApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100019665,"name":"WithResourceNames","signature":"func (b *NamedRuleWithOperationsApplyConfiguration) WithResourceNames(values ...string) *NamedRuleWithOperationsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/namedrulewithoperations.go","code":"// WithResourceNames adds the given value to the ResourceNames field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ResourceNames field.\nfunc (b *NamedRuleWithOperationsApplyConfiguration) WithResourceNames(values ...string) *NamedRuleWithOperationsApplyConfiguration {\n\tfor i := range values {\n\t\tb.ResourceNames = append(b.ResourceNames, values[i])\n\t}\n\treturn b\n}","line":{"from":39,"to":47}} {"id":100019666,"name":"WithOperations","signature":"func (b *NamedRuleWithOperationsApplyConfiguration) WithOperations(values ...admissionregistrationv1.OperationType) *NamedRuleWithOperationsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/namedrulewithoperations.go","code":"// WithOperations adds the given value to the Operations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Operations field.\nfunc (b *NamedRuleWithOperationsApplyConfiguration) WithOperations(values ...admissionregistrationv1.OperationType) *NamedRuleWithOperationsApplyConfiguration {\n\tfor i := range values {\n\t\tb.Operations = append(b.Operations, values[i])\n\t}\n\treturn b\n}","line":{"from":49,"to":57}} {"id":100019667,"name":"WithAPIGroups","signature":"func (b *NamedRuleWithOperationsApplyConfiguration) WithAPIGroups(values ...string) *NamedRuleWithOperationsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/namedrulewithoperations.go","code":"// WithAPIGroups adds the given value to the APIGroups field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the APIGroups field.\nfunc (b *NamedRuleWithOperationsApplyConfiguration) WithAPIGroups(values ...string) *NamedRuleWithOperationsApplyConfiguration {\n\tfor i := range values {\n\t\tb.APIGroups = append(b.APIGroups, values[i])\n\t}\n\treturn b\n}","line":{"from":59,"to":67}} {"id":100019668,"name":"WithAPIVersions","signature":"func (b *NamedRuleWithOperationsApplyConfiguration) WithAPIVersions(values ...string) *NamedRuleWithOperationsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/namedrulewithoperations.go","code":"// WithAPIVersions adds the given value to the APIVersions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the APIVersions field.\nfunc (b *NamedRuleWithOperationsApplyConfiguration) WithAPIVersions(values ...string) *NamedRuleWithOperationsApplyConfiguration {\n\tfor i := range values {\n\t\tb.APIVersions = append(b.APIVersions, values[i])\n\t}\n\treturn b\n}","line":{"from":69,"to":77}} {"id":100019669,"name":"WithResources","signature":"func (b *NamedRuleWithOperationsApplyConfiguration) WithResources(values ...string) *NamedRuleWithOperationsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/namedrulewithoperations.go","code":"// WithResources adds the given value to the Resources field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Resources field.\nfunc (b *NamedRuleWithOperationsApplyConfiguration) WithResources(values ...string) *NamedRuleWithOperationsApplyConfiguration {\n\tfor i := range values {\n\t\tb.Resources = append(b.Resources, values[i])\n\t}\n\treturn b\n}","line":{"from":79,"to":87}} {"id":100019670,"name":"WithScope","signature":"func (b *NamedRuleWithOperationsApplyConfiguration) WithScope(value admissionregistrationv1.ScopeType) *NamedRuleWithOperationsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/namedrulewithoperations.go","code":"// WithScope sets the Scope field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Scope field is set to the value of the last call.\nfunc (b *NamedRuleWithOperationsApplyConfiguration) WithScope(value admissionregistrationv1.ScopeType) *NamedRuleWithOperationsApplyConfiguration {\n\tb.Scope = \u0026value\n\treturn b\n}","line":{"from":89,"to":95}} {"id":100019671,"name":"ParamKind","signature":"func ParamKind() *ParamKindApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/paramkind.go","code":"// ParamKindApplyConfiguration constructs an declarative configuration of the ParamKind type for use with\n// apply.\nfunc ParamKind() *ParamKindApplyConfiguration {\n\treturn \u0026ParamKindApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100019672,"name":"WithAPIVersion","signature":"func (b *ParamKindApplyConfiguration) WithAPIVersion(value string) *ParamKindApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/paramkind.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ParamKindApplyConfiguration) WithAPIVersion(value string) *ParamKindApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100019673,"name":"WithKind","signature":"func (b *ParamKindApplyConfiguration) WithKind(value string) *ParamKindApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/paramkind.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ParamKindApplyConfiguration) WithKind(value string) *ParamKindApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100019674,"name":"ParamRef","signature":"func ParamRef() *ParamRefApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/paramref.go","code":"// ParamRefApplyConfiguration constructs an declarative configuration of the ParamRef type for use with\n// apply.\nfunc ParamRef() *ParamRefApplyConfiguration {\n\treturn \u0026ParamRefApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100019675,"name":"WithName","signature":"func (b *ParamRefApplyConfiguration) WithName(value string) *ParamRefApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/paramref.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ParamRefApplyConfiguration) WithName(value string) *ParamRefApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100019676,"name":"WithNamespace","signature":"func (b *ParamRefApplyConfiguration) WithNamespace(value string) *ParamRefApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/paramref.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ParamRefApplyConfiguration) WithNamespace(value string) *ParamRefApplyConfiguration {\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100019677,"name":"TypeChecking","signature":"func TypeChecking() *TypeCheckingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/typechecking.go","code":"// TypeCheckingApplyConfiguration constructs an declarative configuration of the TypeChecking type for use with\n// apply.\nfunc TypeChecking() *TypeCheckingApplyConfiguration {\n\treturn \u0026TypeCheckingApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100019678,"name":"WithExpressionWarnings","signature":"func (b *TypeCheckingApplyConfiguration) WithExpressionWarnings(values ...*ExpressionWarningApplyConfiguration) *TypeCheckingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/typechecking.go","code":"// WithExpressionWarnings adds the given value to the ExpressionWarnings field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ExpressionWarnings field.\nfunc (b *TypeCheckingApplyConfiguration) WithExpressionWarnings(values ...*ExpressionWarningApplyConfiguration) *TypeCheckingApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithExpressionWarnings\")\n\t\t}\n\t\tb.ExpressionWarnings = append(b.ExpressionWarnings, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100019679,"name":"ValidatingAdmissionPolicy","signature":"func ValidatingAdmissionPolicy(name string) *ValidatingAdmissionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// ValidatingAdmissionPolicy constructs an declarative configuration of the ValidatingAdmissionPolicy type for use with\n// apply.\nfunc ValidatingAdmissionPolicy(name string) *ValidatingAdmissionPolicyApplyConfiguration {\n\tb := \u0026ValidatingAdmissionPolicyApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"ValidatingAdmissionPolicy\")\n\tb.WithAPIVersion(\"admissionregistration.k8s.io/v1alpha1\")\n\treturn b\n}","line":{"from":39,"to":47}} {"id":100019680,"name":"ExtractValidatingAdmissionPolicy","signature":"func ExtractValidatingAdmissionPolicy(validatingAdmissionPolicy *admissionregistrationv1alpha1.ValidatingAdmissionPolicy, fieldManager string) (*ValidatingAdmissionPolicyApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// ExtractValidatingAdmissionPolicy extracts the applied configuration owned by fieldManager from\n// validatingAdmissionPolicy. If no managedFields are found in validatingAdmissionPolicy for fieldManager, a\n// ValidatingAdmissionPolicyApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// validatingAdmissionPolicy must be a unmodified ValidatingAdmissionPolicy API object that was retrieved from the Kubernetes API.\n// ExtractValidatingAdmissionPolicy provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractValidatingAdmissionPolicy(validatingAdmissionPolicy *admissionregistrationv1alpha1.ValidatingAdmissionPolicy, fieldManager string) (*ValidatingAdmissionPolicyApplyConfiguration, error) {\n\treturn extractValidatingAdmissionPolicy(validatingAdmissionPolicy, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100019681,"name":"ExtractValidatingAdmissionPolicyStatus","signature":"func ExtractValidatingAdmissionPolicyStatus(validatingAdmissionPolicy *admissionregistrationv1alpha1.ValidatingAdmissionPolicy, fieldManager string) (*ValidatingAdmissionPolicyApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// ExtractValidatingAdmissionPolicyStatus is the same as ExtractValidatingAdmissionPolicy except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractValidatingAdmissionPolicyStatus(validatingAdmissionPolicy *admissionregistrationv1alpha1.ValidatingAdmissionPolicy, fieldManager string) (*ValidatingAdmissionPolicyApplyConfiguration, error) {\n\treturn extractValidatingAdmissionPolicy(validatingAdmissionPolicy, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100019682,"name":"extractValidatingAdmissionPolicy","signature":"func extractValidatingAdmissionPolicy(validatingAdmissionPolicy *admissionregistrationv1alpha1.ValidatingAdmissionPolicy, fieldManager string, subresource string) (*ValidatingAdmissionPolicyApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"func extractValidatingAdmissionPolicy(validatingAdmissionPolicy *admissionregistrationv1alpha1.ValidatingAdmissionPolicy, fieldManager string, subresource string) (*ValidatingAdmissionPolicyApplyConfiguration, error) {\n\tb := \u0026ValidatingAdmissionPolicyApplyConfiguration{}\n\terr := managedfields.ExtractInto(validatingAdmissionPolicy, internal.Parser().Type(\"io.k8s.api.admissionregistration.v1alpha1.ValidatingAdmissionPolicy\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(validatingAdmissionPolicy.Name)\n\n\tb.WithKind(\"ValidatingAdmissionPolicy\")\n\tb.WithAPIVersion(\"admissionregistration.k8s.io/v1alpha1\")\n\treturn b, nil\n}","line":{"from":71,"to":82}} {"id":100019683,"name":"WithKind","signature":"func (b *ValidatingAdmissionPolicyApplyConfiguration) WithKind(value string) *ValidatingAdmissionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyApplyConfiguration) WithKind(value string) *ValidatingAdmissionPolicyApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100019684,"name":"WithAPIVersion","signature":"func (b *ValidatingAdmissionPolicyApplyConfiguration) WithAPIVersion(value string) *ValidatingAdmissionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyApplyConfiguration) WithAPIVersion(value string) *ValidatingAdmissionPolicyApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100019685,"name":"WithName","signature":"func (b *ValidatingAdmissionPolicyApplyConfiguration) WithName(value string) *ValidatingAdmissionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyApplyConfiguration) WithName(value string) *ValidatingAdmissionPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":100,"to":107}} {"id":100019686,"name":"WithGenerateName","signature":"func (b *ValidatingAdmissionPolicyApplyConfiguration) WithGenerateName(value string) *ValidatingAdmissionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyApplyConfiguration) WithGenerateName(value string) *ValidatingAdmissionPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":109,"to":116}} {"id":100019687,"name":"WithNamespace","signature":"func (b *ValidatingAdmissionPolicyApplyConfiguration) WithNamespace(value string) *ValidatingAdmissionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyApplyConfiguration) WithNamespace(value string) *ValidatingAdmissionPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":118,"to":125}} {"id":100019688,"name":"WithUID","signature":"func (b *ValidatingAdmissionPolicyApplyConfiguration) WithUID(value types.UID) *ValidatingAdmissionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyApplyConfiguration) WithUID(value types.UID) *ValidatingAdmissionPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":127,"to":134}} {"id":100019689,"name":"WithResourceVersion","signature":"func (b *ValidatingAdmissionPolicyApplyConfiguration) WithResourceVersion(value string) *ValidatingAdmissionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyApplyConfiguration) WithResourceVersion(value string) *ValidatingAdmissionPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":136,"to":143}} {"id":100019690,"name":"WithGeneration","signature":"func (b *ValidatingAdmissionPolicyApplyConfiguration) WithGeneration(value int64) *ValidatingAdmissionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyApplyConfiguration) WithGeneration(value int64) *ValidatingAdmissionPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":145,"to":152}} {"id":100019691,"name":"WithCreationTimestamp","signature":"func (b *ValidatingAdmissionPolicyApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ValidatingAdmissionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ValidatingAdmissionPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":154,"to":161}} {"id":100019692,"name":"WithDeletionTimestamp","signature":"func (b *ValidatingAdmissionPolicyApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ValidatingAdmissionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ValidatingAdmissionPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":163,"to":170}} {"id":100019693,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ValidatingAdmissionPolicyApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ValidatingAdmissionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ValidatingAdmissionPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":172,"to":179}} {"id":100019694,"name":"WithLabels","signature":"func (b *ValidatingAdmissionPolicyApplyConfiguration) WithLabels(entries map[string]string) *ValidatingAdmissionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ValidatingAdmissionPolicyApplyConfiguration) WithLabels(entries map[string]string) *ValidatingAdmissionPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":181,"to":194}} {"id":100019695,"name":"WithAnnotations","signature":"func (b *ValidatingAdmissionPolicyApplyConfiguration) WithAnnotations(entries map[string]string) *ValidatingAdmissionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ValidatingAdmissionPolicyApplyConfiguration) WithAnnotations(entries map[string]string) *ValidatingAdmissionPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100019696,"name":"WithOwnerReferences","signature":"func (b *ValidatingAdmissionPolicyApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ValidatingAdmissionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ValidatingAdmissionPolicyApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ValidatingAdmissionPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":211,"to":223}} {"id":100019697,"name":"WithFinalizers","signature":"func (b *ValidatingAdmissionPolicyApplyConfiguration) WithFinalizers(values ...string) *ValidatingAdmissionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ValidatingAdmissionPolicyApplyConfiguration) WithFinalizers(values ...string) *ValidatingAdmissionPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":225,"to":234}} {"id":100019698,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ValidatingAdmissionPolicyApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"func (b *ValidatingAdmissionPolicyApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":236,"to":240}} {"id":100019699,"name":"WithSpec","signature":"func (b *ValidatingAdmissionPolicyApplyConfiguration) WithSpec(value *ValidatingAdmissionPolicySpecApplyConfiguration) *ValidatingAdmissionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyApplyConfiguration) WithSpec(value *ValidatingAdmissionPolicySpecApplyConfiguration) *ValidatingAdmissionPolicyApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":242,"to":248}} {"id":100019700,"name":"WithStatus","signature":"func (b *ValidatingAdmissionPolicyApplyConfiguration) WithStatus(value *ValidatingAdmissionPolicyStatusApplyConfiguration) *ValidatingAdmissionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyApplyConfiguration) WithStatus(value *ValidatingAdmissionPolicyStatusApplyConfiguration) *ValidatingAdmissionPolicyApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":250,"to":256}} {"id":100019701,"name":"ValidatingAdmissionPolicyBinding","signature":"func ValidatingAdmissionPolicyBinding(name string) *ValidatingAdmissionPolicyBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// ValidatingAdmissionPolicyBinding constructs an declarative configuration of the ValidatingAdmissionPolicyBinding type for use with\n// apply.\nfunc ValidatingAdmissionPolicyBinding(name string) *ValidatingAdmissionPolicyBindingApplyConfiguration {\n\tb := \u0026ValidatingAdmissionPolicyBindingApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"ValidatingAdmissionPolicyBinding\")\n\tb.WithAPIVersion(\"admissionregistration.k8s.io/v1alpha1\")\n\treturn b\n}","line":{"from":38,"to":46}} {"id":100019702,"name":"ExtractValidatingAdmissionPolicyBinding","signature":"func ExtractValidatingAdmissionPolicyBinding(validatingAdmissionPolicyBinding *admissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding, fieldManager string) (*ValidatingAdmissionPolicyBindingApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// ExtractValidatingAdmissionPolicyBinding extracts the applied configuration owned by fieldManager from\n// validatingAdmissionPolicyBinding. If no managedFields are found in validatingAdmissionPolicyBinding for fieldManager, a\n// ValidatingAdmissionPolicyBindingApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// validatingAdmissionPolicyBinding must be a unmodified ValidatingAdmissionPolicyBinding API object that was retrieved from the Kubernetes API.\n// ExtractValidatingAdmissionPolicyBinding provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractValidatingAdmissionPolicyBinding(validatingAdmissionPolicyBinding *admissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding, fieldManager string) (*ValidatingAdmissionPolicyBindingApplyConfiguration, error) {\n\treturn extractValidatingAdmissionPolicyBinding(validatingAdmissionPolicyBinding, fieldManager, \"\")\n}","line":{"from":48,"to":61}} {"id":100019703,"name":"ExtractValidatingAdmissionPolicyBindingStatus","signature":"func ExtractValidatingAdmissionPolicyBindingStatus(validatingAdmissionPolicyBinding *admissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding, fieldManager string) (*ValidatingAdmissionPolicyBindingApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// ExtractValidatingAdmissionPolicyBindingStatus is the same as ExtractValidatingAdmissionPolicyBinding except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractValidatingAdmissionPolicyBindingStatus(validatingAdmissionPolicyBinding *admissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding, fieldManager string) (*ValidatingAdmissionPolicyBindingApplyConfiguration, error) {\n\treturn extractValidatingAdmissionPolicyBinding(validatingAdmissionPolicyBinding, fieldManager, \"status\")\n}","line":{"from":63,"to":68}} {"id":100019704,"name":"extractValidatingAdmissionPolicyBinding","signature":"func extractValidatingAdmissionPolicyBinding(validatingAdmissionPolicyBinding *admissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding, fieldManager string, subresource string) (*ValidatingAdmissionPolicyBindingApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"func extractValidatingAdmissionPolicyBinding(validatingAdmissionPolicyBinding *admissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding, fieldManager string, subresource string) (*ValidatingAdmissionPolicyBindingApplyConfiguration, error) {\n\tb := \u0026ValidatingAdmissionPolicyBindingApplyConfiguration{}\n\terr := managedfields.ExtractInto(validatingAdmissionPolicyBinding, internal.Parser().Type(\"io.k8s.api.admissionregistration.v1alpha1.ValidatingAdmissionPolicyBinding\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(validatingAdmissionPolicyBinding.Name)\n\n\tb.WithKind(\"ValidatingAdmissionPolicyBinding\")\n\tb.WithAPIVersion(\"admissionregistration.k8s.io/v1alpha1\")\n\treturn b, nil\n}","line":{"from":70,"to":81}} {"id":100019705,"name":"WithKind","signature":"func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithKind(value string) *ValidatingAdmissionPolicyBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithKind(value string) *ValidatingAdmissionPolicyBindingApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100019706,"name":"WithAPIVersion","signature":"func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithAPIVersion(value string) *ValidatingAdmissionPolicyBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithAPIVersion(value string) *ValidatingAdmissionPolicyBindingApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":91,"to":97}} {"id":100019707,"name":"WithName","signature":"func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithName(value string) *ValidatingAdmissionPolicyBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithName(value string) *ValidatingAdmissionPolicyBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":99,"to":106}} {"id":100019708,"name":"WithGenerateName","signature":"func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithGenerateName(value string) *ValidatingAdmissionPolicyBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithGenerateName(value string) *ValidatingAdmissionPolicyBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":108,"to":115}} {"id":100019709,"name":"WithNamespace","signature":"func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithNamespace(value string) *ValidatingAdmissionPolicyBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithNamespace(value string) *ValidatingAdmissionPolicyBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":117,"to":124}} {"id":100019710,"name":"WithUID","signature":"func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithUID(value types.UID) *ValidatingAdmissionPolicyBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithUID(value types.UID) *ValidatingAdmissionPolicyBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":126,"to":133}} {"id":100019711,"name":"WithResourceVersion","signature":"func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithResourceVersion(value string) *ValidatingAdmissionPolicyBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithResourceVersion(value string) *ValidatingAdmissionPolicyBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":135,"to":142}} {"id":100019712,"name":"WithGeneration","signature":"func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithGeneration(value int64) *ValidatingAdmissionPolicyBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithGeneration(value int64) *ValidatingAdmissionPolicyBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":144,"to":151}} {"id":100019713,"name":"WithCreationTimestamp","signature":"func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ValidatingAdmissionPolicyBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ValidatingAdmissionPolicyBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":153,"to":160}} {"id":100019714,"name":"WithDeletionTimestamp","signature":"func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ValidatingAdmissionPolicyBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ValidatingAdmissionPolicyBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":162,"to":169}} {"id":100019715,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ValidatingAdmissionPolicyBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ValidatingAdmissionPolicyBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":171,"to":178}} {"id":100019716,"name":"WithLabels","signature":"func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithLabels(entries map[string]string) *ValidatingAdmissionPolicyBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithLabels(entries map[string]string) *ValidatingAdmissionPolicyBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":180,"to":193}} {"id":100019717,"name":"WithAnnotations","signature":"func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithAnnotations(entries map[string]string) *ValidatingAdmissionPolicyBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithAnnotations(entries map[string]string) *ValidatingAdmissionPolicyBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":195,"to":208}} {"id":100019718,"name":"WithOwnerReferences","signature":"func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ValidatingAdmissionPolicyBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ValidatingAdmissionPolicyBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":210,"to":222}} {"id":100019719,"name":"WithFinalizers","signature":"func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithFinalizers(values ...string) *ValidatingAdmissionPolicyBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithFinalizers(values ...string) *ValidatingAdmissionPolicyBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":224,"to":233}} {"id":100019720,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":235,"to":239}} {"id":100019721,"name":"WithSpec","signature":"func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithSpec(value *ValidatingAdmissionPolicyBindingSpecApplyConfiguration) *ValidatingAdmissionPolicyBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithSpec(value *ValidatingAdmissionPolicyBindingSpecApplyConfiguration) *ValidatingAdmissionPolicyBindingApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":241,"to":247}} {"id":100019722,"name":"ValidatingAdmissionPolicyBindingSpec","signature":"func ValidatingAdmissionPolicyBindingSpec() *ValidatingAdmissionPolicyBindingSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybindingspec.go","code":"// ValidatingAdmissionPolicyBindingSpecApplyConfiguration constructs an declarative configuration of the ValidatingAdmissionPolicyBindingSpec type for use with\n// apply.\nfunc ValidatingAdmissionPolicyBindingSpec() *ValidatingAdmissionPolicyBindingSpecApplyConfiguration {\n\treturn \u0026ValidatingAdmissionPolicyBindingSpecApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100019723,"name":"WithPolicyName","signature":"func (b *ValidatingAdmissionPolicyBindingSpecApplyConfiguration) WithPolicyName(value string) *ValidatingAdmissionPolicyBindingSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybindingspec.go","code":"// WithPolicyName sets the PolicyName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PolicyName field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyBindingSpecApplyConfiguration) WithPolicyName(value string) *ValidatingAdmissionPolicyBindingSpecApplyConfiguration {\n\tb.PolicyName = \u0026value\n\treturn b\n}","line":{"from":40,"to":46}} {"id":100019724,"name":"WithParamRef","signature":"func (b *ValidatingAdmissionPolicyBindingSpecApplyConfiguration) WithParamRef(value *ParamRefApplyConfiguration) *ValidatingAdmissionPolicyBindingSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybindingspec.go","code":"// WithParamRef sets the ParamRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ParamRef field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyBindingSpecApplyConfiguration) WithParamRef(value *ParamRefApplyConfiguration) *ValidatingAdmissionPolicyBindingSpecApplyConfiguration {\n\tb.ParamRef = value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100019725,"name":"WithMatchResources","signature":"func (b *ValidatingAdmissionPolicyBindingSpecApplyConfiguration) WithMatchResources(value *MatchResourcesApplyConfiguration) *ValidatingAdmissionPolicyBindingSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybindingspec.go","code":"// WithMatchResources sets the MatchResources field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MatchResources field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyBindingSpecApplyConfiguration) WithMatchResources(value *MatchResourcesApplyConfiguration) *ValidatingAdmissionPolicyBindingSpecApplyConfiguration {\n\tb.MatchResources = value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100019726,"name":"WithValidationActions","signature":"func (b *ValidatingAdmissionPolicyBindingSpecApplyConfiguration) WithValidationActions(values ...admissionregistrationv1alpha1.ValidationAction) *ValidatingAdmissionPolicyBindingSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicybindingspec.go","code":"// WithValidationActions adds the given value to the ValidationActions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ValidationActions field.\nfunc (b *ValidatingAdmissionPolicyBindingSpecApplyConfiguration) WithValidationActions(values ...admissionregistrationv1alpha1.ValidationAction) *ValidatingAdmissionPolicyBindingSpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.ValidationActions = append(b.ValidationActions, values[i])\n\t}\n\treturn b\n}","line":{"from":64,"to":72}} {"id":100019727,"name":"ValidatingAdmissionPolicySpec","signature":"func ValidatingAdmissionPolicySpec() *ValidatingAdmissionPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicyspec.go","code":"// ValidatingAdmissionPolicySpecApplyConfiguration constructs an declarative configuration of the ValidatingAdmissionPolicySpec type for use with\n// apply.\nfunc ValidatingAdmissionPolicySpec() *ValidatingAdmissionPolicySpecApplyConfiguration {\n\treturn \u0026ValidatingAdmissionPolicySpecApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100019728,"name":"WithParamKind","signature":"func (b *ValidatingAdmissionPolicySpecApplyConfiguration) WithParamKind(value *ParamKindApplyConfiguration) *ValidatingAdmissionPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicyspec.go","code":"// WithParamKind sets the ParamKind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ParamKind field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicySpecApplyConfiguration) WithParamKind(value *ParamKindApplyConfiguration) *ValidatingAdmissionPolicySpecApplyConfiguration {\n\tb.ParamKind = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100019729,"name":"WithMatchConstraints","signature":"func (b *ValidatingAdmissionPolicySpecApplyConfiguration) WithMatchConstraints(value *MatchResourcesApplyConfiguration) *ValidatingAdmissionPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicyspec.go","code":"// WithMatchConstraints sets the MatchConstraints field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MatchConstraints field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicySpecApplyConfiguration) WithMatchConstraints(value *MatchResourcesApplyConfiguration) *ValidatingAdmissionPolicySpecApplyConfiguration {\n\tb.MatchConstraints = value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100019730,"name":"WithValidations","signature":"func (b *ValidatingAdmissionPolicySpecApplyConfiguration) WithValidations(values ...*ValidationApplyConfiguration) *ValidatingAdmissionPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicyspec.go","code":"// WithValidations adds the given value to the Validations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Validations field.\nfunc (b *ValidatingAdmissionPolicySpecApplyConfiguration) WithValidations(values ...*ValidationApplyConfiguration) *ValidatingAdmissionPolicySpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithValidations\")\n\t\t}\n\t\tb.Validations = append(b.Validations, *values[i])\n\t}\n\treturn b\n}","line":{"from":58,"to":69}} {"id":100019731,"name":"WithFailurePolicy","signature":"func (b *ValidatingAdmissionPolicySpecApplyConfiguration) WithFailurePolicy(value admissionregistrationv1alpha1.FailurePolicyType) *ValidatingAdmissionPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicyspec.go","code":"// WithFailurePolicy sets the FailurePolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FailurePolicy field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicySpecApplyConfiguration) WithFailurePolicy(value admissionregistrationv1alpha1.FailurePolicyType) *ValidatingAdmissionPolicySpecApplyConfiguration {\n\tb.FailurePolicy = \u0026value\n\treturn b\n}","line":{"from":71,"to":77}} {"id":100019732,"name":"WithAuditAnnotations","signature":"func (b *ValidatingAdmissionPolicySpecApplyConfiguration) WithAuditAnnotations(values ...*AuditAnnotationApplyConfiguration) *ValidatingAdmissionPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicyspec.go","code":"// WithAuditAnnotations adds the given value to the AuditAnnotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the AuditAnnotations field.\nfunc (b *ValidatingAdmissionPolicySpecApplyConfiguration) WithAuditAnnotations(values ...*AuditAnnotationApplyConfiguration) *ValidatingAdmissionPolicySpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithAuditAnnotations\")\n\t\t}\n\t\tb.AuditAnnotations = append(b.AuditAnnotations, *values[i])\n\t}\n\treturn b\n}","line":{"from":79,"to":90}} {"id":100019733,"name":"WithMatchConditions","signature":"func (b *ValidatingAdmissionPolicySpecApplyConfiguration) WithMatchConditions(values ...*MatchConditionApplyConfiguration) *ValidatingAdmissionPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicyspec.go","code":"// WithMatchConditions adds the given value to the MatchConditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the MatchConditions field.\nfunc (b *ValidatingAdmissionPolicySpecApplyConfiguration) WithMatchConditions(values ...*MatchConditionApplyConfiguration) *ValidatingAdmissionPolicySpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithMatchConditions\")\n\t\t}\n\t\tb.MatchConditions = append(b.MatchConditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":92,"to":103}} {"id":100019734,"name":"ValidatingAdmissionPolicyStatus","signature":"func ValidatingAdmissionPolicyStatus() *ValidatingAdmissionPolicyStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicystatus.go","code":"// ValidatingAdmissionPolicyStatusApplyConfiguration constructs an declarative configuration of the ValidatingAdmissionPolicyStatus type for use with\n// apply.\nfunc ValidatingAdmissionPolicyStatus() *ValidatingAdmissionPolicyStatusApplyConfiguration {\n\treturn \u0026ValidatingAdmissionPolicyStatusApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100019735,"name":"WithObservedGeneration","signature":"func (b *ValidatingAdmissionPolicyStatusApplyConfiguration) WithObservedGeneration(value int64) *ValidatingAdmissionPolicyStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicystatus.go","code":"// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObservedGeneration field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyStatusApplyConfiguration) WithObservedGeneration(value int64) *ValidatingAdmissionPolicyStatusApplyConfiguration {\n\tb.ObservedGeneration = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100019736,"name":"WithTypeChecking","signature":"func (b *ValidatingAdmissionPolicyStatusApplyConfiguration) WithTypeChecking(value *TypeCheckingApplyConfiguration) *ValidatingAdmissionPolicyStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicystatus.go","code":"// WithTypeChecking sets the TypeChecking field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TypeChecking field is set to the value of the last call.\nfunc (b *ValidatingAdmissionPolicyStatusApplyConfiguration) WithTypeChecking(value *TypeCheckingApplyConfiguration) *ValidatingAdmissionPolicyStatusApplyConfiguration {\n\tb.TypeChecking = value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100019737,"name":"WithConditions","signature":"func (b *ValidatingAdmissionPolicyStatusApplyConfiguration) WithConditions(values ...*v1.ConditionApplyConfiguration) *ValidatingAdmissionPolicyStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validatingadmissionpolicystatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *ValidatingAdmissionPolicyStatusApplyConfiguration) WithConditions(values ...*v1.ConditionApplyConfiguration) *ValidatingAdmissionPolicyStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":55,"to":66}} {"id":100019738,"name":"Validation","signature":"func Validation() *ValidationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validation.go","code":"// ValidationApplyConfiguration constructs an declarative configuration of the Validation type for use with\n// apply.\nfunc Validation() *ValidationApplyConfiguration {\n\treturn \u0026ValidationApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100019739,"name":"WithExpression","signature":"func (b *ValidationApplyConfiguration) WithExpression(value string) *ValidationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validation.go","code":"// WithExpression sets the Expression field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Expression field is set to the value of the last call.\nfunc (b *ValidationApplyConfiguration) WithExpression(value string) *ValidationApplyConfiguration {\n\tb.Expression = \u0026value\n\treturn b\n}","line":{"from":40,"to":46}} {"id":100019740,"name":"WithMessage","signature":"func (b *ValidationApplyConfiguration) WithMessage(value string) *ValidationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validation.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *ValidationApplyConfiguration) WithMessage(value string) *ValidationApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100019741,"name":"WithReason","signature":"func (b *ValidationApplyConfiguration) WithReason(value v1.StatusReason) *ValidationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validation.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *ValidationApplyConfiguration) WithReason(value v1.StatusReason) *ValidationApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100019742,"name":"WithMessageExpression","signature":"func (b *ValidationApplyConfiguration) WithMessageExpression(value string) *ValidationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1alpha1/validation.go","code":"// WithMessageExpression sets the MessageExpression field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MessageExpression field is set to the value of the last call.\nfunc (b *ValidationApplyConfiguration) WithMessageExpression(value string) *ValidationApplyConfiguration {\n\tb.MessageExpression = \u0026value\n\treturn b\n}","line":{"from":64,"to":70}} {"id":100019743,"name":"MatchCondition","signature":"func MatchCondition() *MatchConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/matchcondition.go","code":"// MatchConditionApplyConfiguration constructs an declarative configuration of the MatchCondition type for use with\n// apply.\nfunc MatchCondition() *MatchConditionApplyConfiguration {\n\treturn \u0026MatchConditionApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100019744,"name":"WithName","signature":"func (b *MatchConditionApplyConfiguration) WithName(value string) *MatchConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/matchcondition.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *MatchConditionApplyConfiguration) WithName(value string) *MatchConditionApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100019745,"name":"WithExpression","signature":"func (b *MatchConditionApplyConfiguration) WithExpression(value string) *MatchConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/matchcondition.go","code":"// WithExpression sets the Expression field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Expression field is set to the value of the last call.\nfunc (b *MatchConditionApplyConfiguration) WithExpression(value string) *MatchConditionApplyConfiguration {\n\tb.Expression = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100019746,"name":"MutatingWebhook","signature":"func MutatingWebhook() *MutatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhook.go","code":"// MutatingWebhookApplyConfiguration constructs an declarative configuration of the MutatingWebhook type for use with\n// apply.\nfunc MutatingWebhook() *MutatingWebhookApplyConfiguration {\n\treturn \u0026MutatingWebhookApplyConfiguration{}\n}","line":{"from":44,"to":48}} {"id":100019747,"name":"WithName","signature":"func (b *MutatingWebhookApplyConfiguration) WithName(value string) *MutatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhook.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *MutatingWebhookApplyConfiguration) WithName(value string) *MutatingWebhookApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100019748,"name":"WithClientConfig","signature":"func (b *MutatingWebhookApplyConfiguration) WithClientConfig(value *WebhookClientConfigApplyConfiguration) *MutatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhook.go","code":"// WithClientConfig sets the ClientConfig field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ClientConfig field is set to the value of the last call.\nfunc (b *MutatingWebhookApplyConfiguration) WithClientConfig(value *WebhookClientConfigApplyConfiguration) *MutatingWebhookApplyConfiguration {\n\tb.ClientConfig = value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100019749,"name":"WithRules","signature":"func (b *MutatingWebhookApplyConfiguration) WithRules(values ...*v1.RuleWithOperationsApplyConfiguration) *MutatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhook.go","code":"// WithRules adds the given value to the Rules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Rules field.\nfunc (b *MutatingWebhookApplyConfiguration) WithRules(values ...*v1.RuleWithOperationsApplyConfiguration) *MutatingWebhookApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRules\")\n\t\t}\n\t\tb.Rules = append(b.Rules, *values[i])\n\t}\n\treturn b\n}","line":{"from":66,"to":77}} {"id":100019750,"name":"WithFailurePolicy","signature":"func (b *MutatingWebhookApplyConfiguration) WithFailurePolicy(value admissionregistrationv1beta1.FailurePolicyType) *MutatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhook.go","code":"// WithFailurePolicy sets the FailurePolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FailurePolicy field is set to the value of the last call.\nfunc (b *MutatingWebhookApplyConfiguration) WithFailurePolicy(value admissionregistrationv1beta1.FailurePolicyType) *MutatingWebhookApplyConfiguration {\n\tb.FailurePolicy = \u0026value\n\treturn b\n}","line":{"from":79,"to":85}} {"id":100019751,"name":"WithMatchPolicy","signature":"func (b *MutatingWebhookApplyConfiguration) WithMatchPolicy(value admissionregistrationv1beta1.MatchPolicyType) *MutatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhook.go","code":"// WithMatchPolicy sets the MatchPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MatchPolicy field is set to the value of the last call.\nfunc (b *MutatingWebhookApplyConfiguration) WithMatchPolicy(value admissionregistrationv1beta1.MatchPolicyType) *MutatingWebhookApplyConfiguration {\n\tb.MatchPolicy = \u0026value\n\treturn b\n}","line":{"from":87,"to":93}} {"id":100019752,"name":"WithNamespaceSelector","signature":"func (b *MutatingWebhookApplyConfiguration) WithNamespaceSelector(value *metav1.LabelSelectorApplyConfiguration) *MutatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhook.go","code":"// WithNamespaceSelector sets the NamespaceSelector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NamespaceSelector field is set to the value of the last call.\nfunc (b *MutatingWebhookApplyConfiguration) WithNamespaceSelector(value *metav1.LabelSelectorApplyConfiguration) *MutatingWebhookApplyConfiguration {\n\tb.NamespaceSelector = value\n\treturn b\n}","line":{"from":95,"to":101}} {"id":100019753,"name":"WithObjectSelector","signature":"func (b *MutatingWebhookApplyConfiguration) WithObjectSelector(value *metav1.LabelSelectorApplyConfiguration) *MutatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhook.go","code":"// WithObjectSelector sets the ObjectSelector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObjectSelector field is set to the value of the last call.\nfunc (b *MutatingWebhookApplyConfiguration) WithObjectSelector(value *metav1.LabelSelectorApplyConfiguration) *MutatingWebhookApplyConfiguration {\n\tb.ObjectSelector = value\n\treturn b\n}","line":{"from":103,"to":109}} {"id":100019754,"name":"WithSideEffects","signature":"func (b *MutatingWebhookApplyConfiguration) WithSideEffects(value admissionregistrationv1beta1.SideEffectClass) *MutatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhook.go","code":"// WithSideEffects sets the SideEffects field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SideEffects field is set to the value of the last call.\nfunc (b *MutatingWebhookApplyConfiguration) WithSideEffects(value admissionregistrationv1beta1.SideEffectClass) *MutatingWebhookApplyConfiguration {\n\tb.SideEffects = \u0026value\n\treturn b\n}","line":{"from":111,"to":117}} {"id":100019755,"name":"WithTimeoutSeconds","signature":"func (b *MutatingWebhookApplyConfiguration) WithTimeoutSeconds(value int32) *MutatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhook.go","code":"// WithTimeoutSeconds sets the TimeoutSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TimeoutSeconds field is set to the value of the last call.\nfunc (b *MutatingWebhookApplyConfiguration) WithTimeoutSeconds(value int32) *MutatingWebhookApplyConfiguration {\n\tb.TimeoutSeconds = \u0026value\n\treturn b\n}","line":{"from":119,"to":125}} {"id":100019756,"name":"WithAdmissionReviewVersions","signature":"func (b *MutatingWebhookApplyConfiguration) WithAdmissionReviewVersions(values ...string) *MutatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhook.go","code":"// WithAdmissionReviewVersions adds the given value to the AdmissionReviewVersions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the AdmissionReviewVersions field.\nfunc (b *MutatingWebhookApplyConfiguration) WithAdmissionReviewVersions(values ...string) *MutatingWebhookApplyConfiguration {\n\tfor i := range values {\n\t\tb.AdmissionReviewVersions = append(b.AdmissionReviewVersions, values[i])\n\t}\n\treturn b\n}","line":{"from":127,"to":135}} {"id":100019757,"name":"WithReinvocationPolicy","signature":"func (b *MutatingWebhookApplyConfiguration) WithReinvocationPolicy(value admissionregistrationv1beta1.ReinvocationPolicyType) *MutatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhook.go","code":"// WithReinvocationPolicy sets the ReinvocationPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReinvocationPolicy field is set to the value of the last call.\nfunc (b *MutatingWebhookApplyConfiguration) WithReinvocationPolicy(value admissionregistrationv1beta1.ReinvocationPolicyType) *MutatingWebhookApplyConfiguration {\n\tb.ReinvocationPolicy = \u0026value\n\treturn b\n}","line":{"from":137,"to":143}} {"id":100019758,"name":"WithMatchConditions","signature":"func (b *MutatingWebhookApplyConfiguration) WithMatchConditions(values ...*MatchConditionApplyConfiguration) *MutatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhook.go","code":"// WithMatchConditions adds the given value to the MatchConditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the MatchConditions field.\nfunc (b *MutatingWebhookApplyConfiguration) WithMatchConditions(values ...*MatchConditionApplyConfiguration) *MutatingWebhookApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithMatchConditions\")\n\t\t}\n\t\tb.MatchConditions = append(b.MatchConditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":145,"to":156}} {"id":100019759,"name":"MutatingWebhookConfiguration","signature":"func MutatingWebhookConfiguration(name string) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// MutatingWebhookConfiguration constructs an declarative configuration of the MutatingWebhookConfiguration type for use with\n// apply.\nfunc MutatingWebhookConfiguration(name string) *MutatingWebhookConfigurationApplyConfiguration {\n\tb := \u0026MutatingWebhookConfigurationApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"MutatingWebhookConfiguration\")\n\tb.WithAPIVersion(\"admissionregistration.k8s.io/v1beta1\")\n\treturn b\n}","line":{"from":38,"to":46}} {"id":100019760,"name":"ExtractMutatingWebhookConfiguration","signature":"func ExtractMutatingWebhookConfiguration(mutatingWebhookConfiguration *admissionregistrationv1beta1.MutatingWebhookConfiguration, fieldManager string) (*MutatingWebhookConfigurationApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// ExtractMutatingWebhookConfiguration extracts the applied configuration owned by fieldManager from\n// mutatingWebhookConfiguration. If no managedFields are found in mutatingWebhookConfiguration for fieldManager, a\n// MutatingWebhookConfigurationApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// mutatingWebhookConfiguration must be a unmodified MutatingWebhookConfiguration API object that was retrieved from the Kubernetes API.\n// ExtractMutatingWebhookConfiguration provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractMutatingWebhookConfiguration(mutatingWebhookConfiguration *admissionregistrationv1beta1.MutatingWebhookConfiguration, fieldManager string) (*MutatingWebhookConfigurationApplyConfiguration, error) {\n\treturn extractMutatingWebhookConfiguration(mutatingWebhookConfiguration, fieldManager, \"\")\n}","line":{"from":48,"to":61}} {"id":100019761,"name":"ExtractMutatingWebhookConfigurationStatus","signature":"func ExtractMutatingWebhookConfigurationStatus(mutatingWebhookConfiguration *admissionregistrationv1beta1.MutatingWebhookConfiguration, fieldManager string) (*MutatingWebhookConfigurationApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// ExtractMutatingWebhookConfigurationStatus is the same as ExtractMutatingWebhookConfiguration except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractMutatingWebhookConfigurationStatus(mutatingWebhookConfiguration *admissionregistrationv1beta1.MutatingWebhookConfiguration, fieldManager string) (*MutatingWebhookConfigurationApplyConfiguration, error) {\n\treturn extractMutatingWebhookConfiguration(mutatingWebhookConfiguration, fieldManager, \"status\")\n}","line":{"from":63,"to":68}} {"id":100019762,"name":"extractMutatingWebhookConfiguration","signature":"func extractMutatingWebhookConfiguration(mutatingWebhookConfiguration *admissionregistrationv1beta1.MutatingWebhookConfiguration, fieldManager string, subresource string) (*MutatingWebhookConfigurationApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"func extractMutatingWebhookConfiguration(mutatingWebhookConfiguration *admissionregistrationv1beta1.MutatingWebhookConfiguration, fieldManager string, subresource string) (*MutatingWebhookConfigurationApplyConfiguration, error) {\n\tb := \u0026MutatingWebhookConfigurationApplyConfiguration{}\n\terr := managedfields.ExtractInto(mutatingWebhookConfiguration, internal.Parser().Type(\"io.k8s.api.admissionregistration.v1beta1.MutatingWebhookConfiguration\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(mutatingWebhookConfiguration.Name)\n\n\tb.WithKind(\"MutatingWebhookConfiguration\")\n\tb.WithAPIVersion(\"admissionregistration.k8s.io/v1beta1\")\n\treturn b, nil\n}","line":{"from":70,"to":81}} {"id":100019763,"name":"WithKind","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithKind(value string) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithKind(value string) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100019764,"name":"WithAPIVersion","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithAPIVersion(value string) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithAPIVersion(value string) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":91,"to":97}} {"id":100019765,"name":"WithName","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithName(value string) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithName(value string) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":99,"to":106}} {"id":100019766,"name":"WithGenerateName","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithGenerateName(value string) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithGenerateName(value string) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":108,"to":115}} {"id":100019767,"name":"WithNamespace","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithNamespace(value string) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithNamespace(value string) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":117,"to":124}} {"id":100019768,"name":"WithUID","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithUID(value types.UID) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithUID(value types.UID) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":126,"to":133}} {"id":100019769,"name":"WithResourceVersion","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithResourceVersion(value string) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithResourceVersion(value string) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":135,"to":142}} {"id":100019770,"name":"WithGeneration","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithGeneration(value int64) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithGeneration(value int64) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":144,"to":151}} {"id":100019771,"name":"WithCreationTimestamp","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithCreationTimestamp(value metav1.Time) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithCreationTimestamp(value metav1.Time) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":153,"to":160}} {"id":100019772,"name":"WithDeletionTimestamp","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":162,"to":169}} {"id":100019773,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":171,"to":178}} {"id":100019774,"name":"WithLabels","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithLabels(entries map[string]string) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithLabels(entries map[string]string) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":180,"to":193}} {"id":100019775,"name":"WithAnnotations","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithAnnotations(entries map[string]string) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithAnnotations(entries map[string]string) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":195,"to":208}} {"id":100019776,"name":"WithOwnerReferences","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":210,"to":222}} {"id":100019777,"name":"WithFinalizers","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithFinalizers(values ...string) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithFinalizers(values ...string) *MutatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":224,"to":233}} {"id":100019778,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"func (b *MutatingWebhookConfigurationApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":235,"to":239}} {"id":100019779,"name":"WithWebhooks","signature":"func (b *MutatingWebhookConfigurationApplyConfiguration) WithWebhooks(values ...*MutatingWebhookApplyConfiguration) *MutatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// WithWebhooks adds the given value to the Webhooks field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Webhooks field.\nfunc (b *MutatingWebhookConfigurationApplyConfiguration) WithWebhooks(values ...*MutatingWebhookApplyConfiguration) *MutatingWebhookConfigurationApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithWebhooks\")\n\t\t}\n\t\tb.Webhooks = append(b.Webhooks, *values[i])\n\t}\n\treturn b\n}","line":{"from":241,"to":252}} {"id":100019780,"name":"ServiceReference","signature":"func ServiceReference() *ServiceReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/servicereference.go","code":"// ServiceReferenceApplyConfiguration constructs an declarative configuration of the ServiceReference type for use with\n// apply.\nfunc ServiceReference() *ServiceReferenceApplyConfiguration {\n\treturn \u0026ServiceReferenceApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100019781,"name":"WithNamespace","signature":"func (b *ServiceReferenceApplyConfiguration) WithNamespace(value string) *ServiceReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/servicereference.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ServiceReferenceApplyConfiguration) WithNamespace(value string) *ServiceReferenceApplyConfiguration {\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100019782,"name":"WithName","signature":"func (b *ServiceReferenceApplyConfiguration) WithName(value string) *ServiceReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/servicereference.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ServiceReferenceApplyConfiguration) WithName(value string) *ServiceReferenceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100019783,"name":"WithPath","signature":"func (b *ServiceReferenceApplyConfiguration) WithPath(value string) *ServiceReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/servicereference.go","code":"// WithPath sets the Path field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Path field is set to the value of the last call.\nfunc (b *ServiceReferenceApplyConfiguration) WithPath(value string) *ServiceReferenceApplyConfiguration {\n\tb.Path = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100019784,"name":"WithPort","signature":"func (b *ServiceReferenceApplyConfiguration) WithPort(value int32) *ServiceReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/servicereference.go","code":"// WithPort sets the Port field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Port field is set to the value of the last call.\nfunc (b *ServiceReferenceApplyConfiguration) WithPort(value int32) *ServiceReferenceApplyConfiguration {\n\tb.Port = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100019785,"name":"ValidatingWebhook","signature":"func ValidatingWebhook() *ValidatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhook.go","code":"// ValidatingWebhookApplyConfiguration constructs an declarative configuration of the ValidatingWebhook type for use with\n// apply.\nfunc ValidatingWebhook() *ValidatingWebhookApplyConfiguration {\n\treturn \u0026ValidatingWebhookApplyConfiguration{}\n}","line":{"from":43,"to":47}} {"id":100019786,"name":"WithName","signature":"func (b *ValidatingWebhookApplyConfiguration) WithName(value string) *ValidatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhook.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ValidatingWebhookApplyConfiguration) WithName(value string) *ValidatingWebhookApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":49,"to":55}} {"id":100019787,"name":"WithClientConfig","signature":"func (b *ValidatingWebhookApplyConfiguration) WithClientConfig(value *WebhookClientConfigApplyConfiguration) *ValidatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhook.go","code":"// WithClientConfig sets the ClientConfig field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ClientConfig field is set to the value of the last call.\nfunc (b *ValidatingWebhookApplyConfiguration) WithClientConfig(value *WebhookClientConfigApplyConfiguration) *ValidatingWebhookApplyConfiguration {\n\tb.ClientConfig = value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100019788,"name":"WithRules","signature":"func (b *ValidatingWebhookApplyConfiguration) WithRules(values ...*v1.RuleWithOperationsApplyConfiguration) *ValidatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhook.go","code":"// WithRules adds the given value to the Rules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Rules field.\nfunc (b *ValidatingWebhookApplyConfiguration) WithRules(values ...*v1.RuleWithOperationsApplyConfiguration) *ValidatingWebhookApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRules\")\n\t\t}\n\t\tb.Rules = append(b.Rules, *values[i])\n\t}\n\treturn b\n}","line":{"from":65,"to":76}} {"id":100019789,"name":"WithFailurePolicy","signature":"func (b *ValidatingWebhookApplyConfiguration) WithFailurePolicy(value admissionregistrationv1beta1.FailurePolicyType) *ValidatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhook.go","code":"// WithFailurePolicy sets the FailurePolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FailurePolicy field is set to the value of the last call.\nfunc (b *ValidatingWebhookApplyConfiguration) WithFailurePolicy(value admissionregistrationv1beta1.FailurePolicyType) *ValidatingWebhookApplyConfiguration {\n\tb.FailurePolicy = \u0026value\n\treturn b\n}","line":{"from":78,"to":84}} {"id":100019790,"name":"WithMatchPolicy","signature":"func (b *ValidatingWebhookApplyConfiguration) WithMatchPolicy(value admissionregistrationv1beta1.MatchPolicyType) *ValidatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhook.go","code":"// WithMatchPolicy sets the MatchPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MatchPolicy field is set to the value of the last call.\nfunc (b *ValidatingWebhookApplyConfiguration) WithMatchPolicy(value admissionregistrationv1beta1.MatchPolicyType) *ValidatingWebhookApplyConfiguration {\n\tb.MatchPolicy = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100019791,"name":"WithNamespaceSelector","signature":"func (b *ValidatingWebhookApplyConfiguration) WithNamespaceSelector(value *metav1.LabelSelectorApplyConfiguration) *ValidatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhook.go","code":"// WithNamespaceSelector sets the NamespaceSelector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NamespaceSelector field is set to the value of the last call.\nfunc (b *ValidatingWebhookApplyConfiguration) WithNamespaceSelector(value *metav1.LabelSelectorApplyConfiguration) *ValidatingWebhookApplyConfiguration {\n\tb.NamespaceSelector = value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100019792,"name":"WithObjectSelector","signature":"func (b *ValidatingWebhookApplyConfiguration) WithObjectSelector(value *metav1.LabelSelectorApplyConfiguration) *ValidatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhook.go","code":"// WithObjectSelector sets the ObjectSelector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObjectSelector field is set to the value of the last call.\nfunc (b *ValidatingWebhookApplyConfiguration) WithObjectSelector(value *metav1.LabelSelectorApplyConfiguration) *ValidatingWebhookApplyConfiguration {\n\tb.ObjectSelector = value\n\treturn b\n}","line":{"from":102,"to":108}} {"id":100019793,"name":"WithSideEffects","signature":"func (b *ValidatingWebhookApplyConfiguration) WithSideEffects(value admissionregistrationv1beta1.SideEffectClass) *ValidatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhook.go","code":"// WithSideEffects sets the SideEffects field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SideEffects field is set to the value of the last call.\nfunc (b *ValidatingWebhookApplyConfiguration) WithSideEffects(value admissionregistrationv1beta1.SideEffectClass) *ValidatingWebhookApplyConfiguration {\n\tb.SideEffects = \u0026value\n\treturn b\n}","line":{"from":110,"to":116}} {"id":100019794,"name":"WithTimeoutSeconds","signature":"func (b *ValidatingWebhookApplyConfiguration) WithTimeoutSeconds(value int32) *ValidatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhook.go","code":"// WithTimeoutSeconds sets the TimeoutSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TimeoutSeconds field is set to the value of the last call.\nfunc (b *ValidatingWebhookApplyConfiguration) WithTimeoutSeconds(value int32) *ValidatingWebhookApplyConfiguration {\n\tb.TimeoutSeconds = \u0026value\n\treturn b\n}","line":{"from":118,"to":124}} {"id":100019795,"name":"WithAdmissionReviewVersions","signature":"func (b *ValidatingWebhookApplyConfiguration) WithAdmissionReviewVersions(values ...string) *ValidatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhook.go","code":"// WithAdmissionReviewVersions adds the given value to the AdmissionReviewVersions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the AdmissionReviewVersions field.\nfunc (b *ValidatingWebhookApplyConfiguration) WithAdmissionReviewVersions(values ...string) *ValidatingWebhookApplyConfiguration {\n\tfor i := range values {\n\t\tb.AdmissionReviewVersions = append(b.AdmissionReviewVersions, values[i])\n\t}\n\treturn b\n}","line":{"from":126,"to":134}} {"id":100019796,"name":"WithMatchConditions","signature":"func (b *ValidatingWebhookApplyConfiguration) WithMatchConditions(values ...*MatchConditionApplyConfiguration) *ValidatingWebhookApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhook.go","code":"// WithMatchConditions adds the given value to the MatchConditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the MatchConditions field.\nfunc (b *ValidatingWebhookApplyConfiguration) WithMatchConditions(values ...*MatchConditionApplyConfiguration) *ValidatingWebhookApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithMatchConditions\")\n\t\t}\n\t\tb.MatchConditions = append(b.MatchConditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":136,"to":147}} {"id":100019797,"name":"ValidatingWebhookConfiguration","signature":"func ValidatingWebhookConfiguration(name string) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// ValidatingWebhookConfiguration constructs an declarative configuration of the ValidatingWebhookConfiguration type for use with\n// apply.\nfunc ValidatingWebhookConfiguration(name string) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb := \u0026ValidatingWebhookConfigurationApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"ValidatingWebhookConfiguration\")\n\tb.WithAPIVersion(\"admissionregistration.k8s.io/v1beta1\")\n\treturn b\n}","line":{"from":38,"to":46}} {"id":100019798,"name":"ExtractValidatingWebhookConfiguration","signature":"func ExtractValidatingWebhookConfiguration(validatingWebhookConfiguration *admissionregistrationv1beta1.ValidatingWebhookConfiguration, fieldManager string) (*ValidatingWebhookConfigurationApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// ExtractValidatingWebhookConfiguration extracts the applied configuration owned by fieldManager from\n// validatingWebhookConfiguration. If no managedFields are found in validatingWebhookConfiguration for fieldManager, a\n// ValidatingWebhookConfigurationApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// validatingWebhookConfiguration must be a unmodified ValidatingWebhookConfiguration API object that was retrieved from the Kubernetes API.\n// ExtractValidatingWebhookConfiguration provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractValidatingWebhookConfiguration(validatingWebhookConfiguration *admissionregistrationv1beta1.ValidatingWebhookConfiguration, fieldManager string) (*ValidatingWebhookConfigurationApplyConfiguration, error) {\n\treturn extractValidatingWebhookConfiguration(validatingWebhookConfiguration, fieldManager, \"\")\n}","line":{"from":48,"to":61}} {"id":100019799,"name":"ExtractValidatingWebhookConfigurationStatus","signature":"func ExtractValidatingWebhookConfigurationStatus(validatingWebhookConfiguration *admissionregistrationv1beta1.ValidatingWebhookConfiguration, fieldManager string) (*ValidatingWebhookConfigurationApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// ExtractValidatingWebhookConfigurationStatus is the same as ExtractValidatingWebhookConfiguration except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractValidatingWebhookConfigurationStatus(validatingWebhookConfiguration *admissionregistrationv1beta1.ValidatingWebhookConfiguration, fieldManager string) (*ValidatingWebhookConfigurationApplyConfiguration, error) {\n\treturn extractValidatingWebhookConfiguration(validatingWebhookConfiguration, fieldManager, \"status\")\n}","line":{"from":63,"to":68}} {"id":100019800,"name":"extractValidatingWebhookConfiguration","signature":"func extractValidatingWebhookConfiguration(validatingWebhookConfiguration *admissionregistrationv1beta1.ValidatingWebhookConfiguration, fieldManager string, subresource string) (*ValidatingWebhookConfigurationApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"func extractValidatingWebhookConfiguration(validatingWebhookConfiguration *admissionregistrationv1beta1.ValidatingWebhookConfiguration, fieldManager string, subresource string) (*ValidatingWebhookConfigurationApplyConfiguration, error) {\n\tb := \u0026ValidatingWebhookConfigurationApplyConfiguration{}\n\terr := managedfields.ExtractInto(validatingWebhookConfiguration, internal.Parser().Type(\"io.k8s.api.admissionregistration.v1beta1.ValidatingWebhookConfiguration\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(validatingWebhookConfiguration.Name)\n\n\tb.WithKind(\"ValidatingWebhookConfiguration\")\n\tb.WithAPIVersion(\"admissionregistration.k8s.io/v1beta1\")\n\treturn b, nil\n}","line":{"from":70,"to":81}} {"id":100019801,"name":"WithKind","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithKind(value string) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithKind(value string) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100019802,"name":"WithAPIVersion","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithAPIVersion(value string) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithAPIVersion(value string) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":91,"to":97}} {"id":100019803,"name":"WithName","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithName(value string) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithName(value string) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":99,"to":106}} {"id":100019804,"name":"WithGenerateName","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithGenerateName(value string) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithGenerateName(value string) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":108,"to":115}} {"id":100019805,"name":"WithNamespace","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithNamespace(value string) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithNamespace(value string) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":117,"to":124}} {"id":100019806,"name":"WithUID","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithUID(value types.UID) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithUID(value types.UID) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":126,"to":133}} {"id":100019807,"name":"WithResourceVersion","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithResourceVersion(value string) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithResourceVersion(value string) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":135,"to":142}} {"id":100019808,"name":"WithGeneration","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithGeneration(value int64) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithGeneration(value int64) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":144,"to":151}} {"id":100019809,"name":"WithCreationTimestamp","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":153,"to":160}} {"id":100019810,"name":"WithDeletionTimestamp","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":162,"to":169}} {"id":100019811,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":171,"to":178}} {"id":100019812,"name":"WithLabels","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithLabels(entries map[string]string) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithLabels(entries map[string]string) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":180,"to":193}} {"id":100019813,"name":"WithAnnotations","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithAnnotations(entries map[string]string) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithAnnotations(entries map[string]string) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":195,"to":208}} {"id":100019814,"name":"WithOwnerReferences","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":210,"to":222}} {"id":100019815,"name":"WithFinalizers","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithFinalizers(values ...string) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithFinalizers(values ...string) *ValidatingWebhookConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":224,"to":233}} {"id":100019816,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"func (b *ValidatingWebhookConfigurationApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":235,"to":239}} {"id":100019817,"name":"WithWebhooks","signature":"func (b *ValidatingWebhookConfigurationApplyConfiguration) WithWebhooks(values ...*ValidatingWebhookApplyConfiguration) *ValidatingWebhookConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// WithWebhooks adds the given value to the Webhooks field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Webhooks field.\nfunc (b *ValidatingWebhookConfigurationApplyConfiguration) WithWebhooks(values ...*ValidatingWebhookApplyConfiguration) *ValidatingWebhookConfigurationApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithWebhooks\")\n\t\t}\n\t\tb.Webhooks = append(b.Webhooks, *values[i])\n\t}\n\treturn b\n}","line":{"from":241,"to":252}} {"id":100019818,"name":"WebhookClientConfig","signature":"func WebhookClientConfig() *WebhookClientConfigApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/webhookclientconfig.go","code":"// WebhookClientConfigApplyConfiguration constructs an declarative configuration of the WebhookClientConfig type for use with\n// apply.\nfunc WebhookClientConfig() *WebhookClientConfigApplyConfiguration {\n\treturn \u0026WebhookClientConfigApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100019819,"name":"WithURL","signature":"func (b *WebhookClientConfigApplyConfiguration) WithURL(value string) *WebhookClientConfigApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/webhookclientconfig.go","code":"// WithURL sets the URL field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the URL field is set to the value of the last call.\nfunc (b *WebhookClientConfigApplyConfiguration) WithURL(value string) *WebhookClientConfigApplyConfiguration {\n\tb.URL = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100019820,"name":"WithService","signature":"func (b *WebhookClientConfigApplyConfiguration) WithService(value *ServiceReferenceApplyConfiguration) *WebhookClientConfigApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/webhookclientconfig.go","code":"// WithService sets the Service field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Service field is set to the value of the last call.\nfunc (b *WebhookClientConfigApplyConfiguration) WithService(value *ServiceReferenceApplyConfiguration) *WebhookClientConfigApplyConfiguration {\n\tb.Service = value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100019821,"name":"WithCABundle","signature":"func (b *WebhookClientConfigApplyConfiguration) WithCABundle(values ...byte) *WebhookClientConfigApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1/webhookclientconfig.go","code":"// WithCABundle adds the given value to the CABundle field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the CABundle field.\nfunc (b *WebhookClientConfigApplyConfiguration) WithCABundle(values ...byte) *WebhookClientConfigApplyConfiguration {\n\tfor i := range values {\n\t\tb.CABundle = append(b.CABundle, values[i])\n\t}\n\treturn b\n}","line":{"from":51,"to":59}} {"id":100019822,"name":"ServerStorageVersion","signature":"func ServerStorageVersion() *ServerStorageVersionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/serverstorageversion.go","code":"// ServerStorageVersionApplyConfiguration constructs an declarative configuration of the ServerStorageVersion type for use with\n// apply.\nfunc ServerStorageVersion() *ServerStorageVersionApplyConfiguration {\n\treturn \u0026ServerStorageVersionApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100019823,"name":"WithAPIServerID","signature":"func (b *ServerStorageVersionApplyConfiguration) WithAPIServerID(value string) *ServerStorageVersionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/serverstorageversion.go","code":"// WithAPIServerID sets the APIServerID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIServerID field is set to the value of the last call.\nfunc (b *ServerStorageVersionApplyConfiguration) WithAPIServerID(value string) *ServerStorageVersionApplyConfiguration {\n\tb.APIServerID = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100019824,"name":"WithEncodingVersion","signature":"func (b *ServerStorageVersionApplyConfiguration) WithEncodingVersion(value string) *ServerStorageVersionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/serverstorageversion.go","code":"// WithEncodingVersion sets the EncodingVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the EncodingVersion field is set to the value of the last call.\nfunc (b *ServerStorageVersionApplyConfiguration) WithEncodingVersion(value string) *ServerStorageVersionApplyConfiguration {\n\tb.EncodingVersion = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100019825,"name":"WithDecodableVersions","signature":"func (b *ServerStorageVersionApplyConfiguration) WithDecodableVersions(values ...string) *ServerStorageVersionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/serverstorageversion.go","code":"// WithDecodableVersions adds the given value to the DecodableVersions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the DecodableVersions field.\nfunc (b *ServerStorageVersionApplyConfiguration) WithDecodableVersions(values ...string) *ServerStorageVersionApplyConfiguration {\n\tfor i := range values {\n\t\tb.DecodableVersions = append(b.DecodableVersions, values[i])\n\t}\n\treturn b\n}","line":{"from":51,"to":59}} {"id":100019826,"name":"StorageVersion","signature":"func StorageVersion(name string) *StorageVersionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversion.go","code":"// StorageVersion constructs an declarative configuration of the StorageVersion type for use with\n// apply.\nfunc StorageVersion(name string) *StorageVersionApplyConfiguration {\n\tb := \u0026StorageVersionApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"StorageVersion\")\n\tb.WithAPIVersion(\"internal.apiserver.k8s.io/v1alpha1\")\n\treturn b\n}","line":{"from":39,"to":47}} {"id":100019827,"name":"ExtractStorageVersion","signature":"func ExtractStorageVersion(storageVersion *v1alpha1.StorageVersion, fieldManager string) (*StorageVersionApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversion.go","code":"// ExtractStorageVersion extracts the applied configuration owned by fieldManager from\n// storageVersion. If no managedFields are found in storageVersion for fieldManager, a\n// StorageVersionApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// storageVersion must be a unmodified StorageVersion API object that was retrieved from the Kubernetes API.\n// ExtractStorageVersion provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractStorageVersion(storageVersion *v1alpha1.StorageVersion, fieldManager string) (*StorageVersionApplyConfiguration, error) {\n\treturn extractStorageVersion(storageVersion, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100019828,"name":"ExtractStorageVersionStatus","signature":"func ExtractStorageVersionStatus(storageVersion *v1alpha1.StorageVersion, fieldManager string) (*StorageVersionApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversion.go","code":"// ExtractStorageVersionStatus is the same as ExtractStorageVersion except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractStorageVersionStatus(storageVersion *v1alpha1.StorageVersion, fieldManager string) (*StorageVersionApplyConfiguration, error) {\n\treturn extractStorageVersion(storageVersion, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100019829,"name":"extractStorageVersion","signature":"func extractStorageVersion(storageVersion *v1alpha1.StorageVersion, fieldManager string, subresource string) (*StorageVersionApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversion.go","code":"func extractStorageVersion(storageVersion *v1alpha1.StorageVersion, fieldManager string, subresource string) (*StorageVersionApplyConfiguration, error) {\n\tb := \u0026StorageVersionApplyConfiguration{}\n\terr := managedfields.ExtractInto(storageVersion, internal.Parser().Type(\"io.k8s.api.apiserverinternal.v1alpha1.StorageVersion\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(storageVersion.Name)\n\n\tb.WithKind(\"StorageVersion\")\n\tb.WithAPIVersion(\"internal.apiserver.k8s.io/v1alpha1\")\n\treturn b, nil\n}","line":{"from":71,"to":82}} {"id":100019830,"name":"WithKind","signature":"func (b *StorageVersionApplyConfiguration) WithKind(value string) *StorageVersionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversion.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *StorageVersionApplyConfiguration) WithKind(value string) *StorageVersionApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100019831,"name":"WithAPIVersion","signature":"func (b *StorageVersionApplyConfiguration) WithAPIVersion(value string) *StorageVersionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversion.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *StorageVersionApplyConfiguration) WithAPIVersion(value string) *StorageVersionApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100019832,"name":"WithName","signature":"func (b *StorageVersionApplyConfiguration) WithName(value string) *StorageVersionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversion.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *StorageVersionApplyConfiguration) WithName(value string) *StorageVersionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":100,"to":107}} {"id":100019833,"name":"WithGenerateName","signature":"func (b *StorageVersionApplyConfiguration) WithGenerateName(value string) *StorageVersionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversion.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *StorageVersionApplyConfiguration) WithGenerateName(value string) *StorageVersionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":109,"to":116}} {"id":100019834,"name":"WithNamespace","signature":"func (b *StorageVersionApplyConfiguration) WithNamespace(value string) *StorageVersionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversion.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *StorageVersionApplyConfiguration) WithNamespace(value string) *StorageVersionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":118,"to":125}} {"id":100019835,"name":"WithUID","signature":"func (b *StorageVersionApplyConfiguration) WithUID(value types.UID) *StorageVersionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversion.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *StorageVersionApplyConfiguration) WithUID(value types.UID) *StorageVersionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":127,"to":134}} {"id":100019836,"name":"WithResourceVersion","signature":"func (b *StorageVersionApplyConfiguration) WithResourceVersion(value string) *StorageVersionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversion.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *StorageVersionApplyConfiguration) WithResourceVersion(value string) *StorageVersionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":136,"to":143}} {"id":100019837,"name":"WithGeneration","signature":"func (b *StorageVersionApplyConfiguration) WithGeneration(value int64) *StorageVersionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversion.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *StorageVersionApplyConfiguration) WithGeneration(value int64) *StorageVersionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":145,"to":152}} {"id":100019838,"name":"WithCreationTimestamp","signature":"func (b *StorageVersionApplyConfiguration) WithCreationTimestamp(value metav1.Time) *StorageVersionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversion.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *StorageVersionApplyConfiguration) WithCreationTimestamp(value metav1.Time) *StorageVersionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":154,"to":161}} {"id":100019839,"name":"WithDeletionTimestamp","signature":"func (b *StorageVersionApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *StorageVersionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversion.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *StorageVersionApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *StorageVersionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":163,"to":170}} {"id":100019840,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *StorageVersionApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *StorageVersionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversion.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *StorageVersionApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *StorageVersionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":172,"to":179}} {"id":100019841,"name":"WithLabels","signature":"func (b *StorageVersionApplyConfiguration) WithLabels(entries map[string]string) *StorageVersionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversion.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *StorageVersionApplyConfiguration) WithLabels(entries map[string]string) *StorageVersionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":181,"to":194}} {"id":100019842,"name":"WithAnnotations","signature":"func (b *StorageVersionApplyConfiguration) WithAnnotations(entries map[string]string) *StorageVersionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversion.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *StorageVersionApplyConfiguration) WithAnnotations(entries map[string]string) *StorageVersionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100019843,"name":"WithOwnerReferences","signature":"func (b *StorageVersionApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *StorageVersionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversion.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *StorageVersionApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *StorageVersionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":211,"to":223}} {"id":100019844,"name":"WithFinalizers","signature":"func (b *StorageVersionApplyConfiguration) WithFinalizers(values ...string) *StorageVersionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversion.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *StorageVersionApplyConfiguration) WithFinalizers(values ...string) *StorageVersionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":225,"to":234}} {"id":100019845,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *StorageVersionApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversion.go","code":"func (b *StorageVersionApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":236,"to":240}} {"id":100019846,"name":"WithSpec","signature":"func (b *StorageVersionApplyConfiguration) WithSpec(value v1alpha1.StorageVersionSpec) *StorageVersionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversion.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *StorageVersionApplyConfiguration) WithSpec(value v1alpha1.StorageVersionSpec) *StorageVersionApplyConfiguration {\n\tb.Spec = \u0026value\n\treturn b\n}","line":{"from":242,"to":248}} {"id":100019847,"name":"WithStatus","signature":"func (b *StorageVersionApplyConfiguration) WithStatus(value *StorageVersionStatusApplyConfiguration) *StorageVersionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversion.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *StorageVersionApplyConfiguration) WithStatus(value *StorageVersionStatusApplyConfiguration) *StorageVersionApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":250,"to":256}} {"id":100019848,"name":"StorageVersionCondition","signature":"func StorageVersionCondition() *StorageVersionConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversioncondition.go","code":"// StorageVersionConditionApplyConfiguration constructs an declarative configuration of the StorageVersionCondition type for use with\n// apply.\nfunc StorageVersionCondition() *StorageVersionConditionApplyConfiguration {\n\treturn \u0026StorageVersionConditionApplyConfiguration{}\n}","line":{"from":37,"to":41}} {"id":100019849,"name":"WithType","signature":"func (b *StorageVersionConditionApplyConfiguration) WithType(value v1alpha1.StorageVersionConditionType) *StorageVersionConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversioncondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *StorageVersionConditionApplyConfiguration) WithType(value v1alpha1.StorageVersionConditionType) *StorageVersionConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100019850,"name":"WithStatus","signature":"func (b *StorageVersionConditionApplyConfiguration) WithStatus(value v1alpha1.ConditionStatus) *StorageVersionConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversioncondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *StorageVersionConditionApplyConfiguration) WithStatus(value v1alpha1.ConditionStatus) *StorageVersionConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100019851,"name":"WithObservedGeneration","signature":"func (b *StorageVersionConditionApplyConfiguration) WithObservedGeneration(value int64) *StorageVersionConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversioncondition.go","code":"// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObservedGeneration field is set to the value of the last call.\nfunc (b *StorageVersionConditionApplyConfiguration) WithObservedGeneration(value int64) *StorageVersionConditionApplyConfiguration {\n\tb.ObservedGeneration = \u0026value\n\treturn b\n}","line":{"from":59,"to":65}} {"id":100019852,"name":"WithLastTransitionTime","signature":"func (b *StorageVersionConditionApplyConfiguration) WithLastTransitionTime(value v1.Time) *StorageVersionConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversioncondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *StorageVersionConditionApplyConfiguration) WithLastTransitionTime(value v1.Time) *StorageVersionConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100019853,"name":"WithReason","signature":"func (b *StorageVersionConditionApplyConfiguration) WithReason(value string) *StorageVersionConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversioncondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *StorageVersionConditionApplyConfiguration) WithReason(value string) *StorageVersionConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":75,"to":81}} {"id":100019854,"name":"WithMessage","signature":"func (b *StorageVersionConditionApplyConfiguration) WithMessage(value string) *StorageVersionConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversioncondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *StorageVersionConditionApplyConfiguration) WithMessage(value string) *StorageVersionConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100019855,"name":"StorageVersionStatus","signature":"func StorageVersionStatus() *StorageVersionStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversionstatus.go","code":"// StorageVersionStatusApplyConfiguration constructs an declarative configuration of the StorageVersionStatus type for use with\n// apply.\nfunc StorageVersionStatus() *StorageVersionStatusApplyConfiguration {\n\treturn \u0026StorageVersionStatusApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100019856,"name":"WithStorageVersions","signature":"func (b *StorageVersionStatusApplyConfiguration) WithStorageVersions(values ...*ServerStorageVersionApplyConfiguration) *StorageVersionStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversionstatus.go","code":"// WithStorageVersions adds the given value to the StorageVersions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the StorageVersions field.\nfunc (b *StorageVersionStatusApplyConfiguration) WithStorageVersions(values ...*ServerStorageVersionApplyConfiguration) *StorageVersionStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithStorageVersions\")\n\t\t}\n\t\tb.StorageVersions = append(b.StorageVersions, *values[i])\n\t}\n\treturn b\n}","line":{"from":35,"to":46}} {"id":100019857,"name":"WithCommonEncodingVersion","signature":"func (b *StorageVersionStatusApplyConfiguration) WithCommonEncodingVersion(value string) *StorageVersionStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversionstatus.go","code":"// WithCommonEncodingVersion sets the CommonEncodingVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CommonEncodingVersion field is set to the value of the last call.\nfunc (b *StorageVersionStatusApplyConfiguration) WithCommonEncodingVersion(value string) *StorageVersionStatusApplyConfiguration {\n\tb.CommonEncodingVersion = \u0026value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100019858,"name":"WithConditions","signature":"func (b *StorageVersionStatusApplyConfiguration) WithConditions(values ...*StorageVersionConditionApplyConfiguration) *StorageVersionStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apiserverinternal/v1alpha1/storageversionstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *StorageVersionStatusApplyConfiguration) WithConditions(values ...*StorageVersionConditionApplyConfiguration) *StorageVersionStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":56,"to":67}} {"id":100019859,"name":"ControllerRevision","signature":"func ControllerRevision(name, namespace string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/controllerrevision.go","code":"// ControllerRevision constructs an declarative configuration of the ControllerRevision type for use with\n// apply.\nfunc ControllerRevision(name, namespace string) *ControllerRevisionApplyConfiguration {\n\tb := \u0026ControllerRevisionApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"ControllerRevision\")\n\tb.WithAPIVersion(\"apps/v1\")\n\treturn b\n}","line":{"from":40,"to":49}} {"id":100019860,"name":"ExtractControllerRevision","signature":"func ExtractControllerRevision(controllerRevision *appsv1.ControllerRevision, fieldManager string) (*ControllerRevisionApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/controllerrevision.go","code":"// ExtractControllerRevision extracts the applied configuration owned by fieldManager from\n// controllerRevision. If no managedFields are found in controllerRevision for fieldManager, a\n// ControllerRevisionApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// controllerRevision must be a unmodified ControllerRevision API object that was retrieved from the Kubernetes API.\n// ExtractControllerRevision provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractControllerRevision(controllerRevision *appsv1.ControllerRevision, fieldManager string) (*ControllerRevisionApplyConfiguration, error) {\n\treturn extractControllerRevision(controllerRevision, fieldManager, \"\")\n}","line":{"from":51,"to":64}} {"id":100019861,"name":"ExtractControllerRevisionStatus","signature":"func ExtractControllerRevisionStatus(controllerRevision *appsv1.ControllerRevision, fieldManager string) (*ControllerRevisionApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/controllerrevision.go","code":"// ExtractControllerRevisionStatus is the same as ExtractControllerRevision except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractControllerRevisionStatus(controllerRevision *appsv1.ControllerRevision, fieldManager string) (*ControllerRevisionApplyConfiguration, error) {\n\treturn extractControllerRevision(controllerRevision, fieldManager, \"status\")\n}","line":{"from":66,"to":71}} {"id":100019862,"name":"extractControllerRevision","signature":"func extractControllerRevision(controllerRevision *appsv1.ControllerRevision, fieldManager string, subresource string) (*ControllerRevisionApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/controllerrevision.go","code":"func extractControllerRevision(controllerRevision *appsv1.ControllerRevision, fieldManager string, subresource string) (*ControllerRevisionApplyConfiguration, error) {\n\tb := \u0026ControllerRevisionApplyConfiguration{}\n\terr := managedfields.ExtractInto(controllerRevision, internal.Parser().Type(\"io.k8s.api.apps.v1.ControllerRevision\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(controllerRevision.Name)\n\tb.WithNamespace(controllerRevision.Namespace)\n\n\tb.WithKind(\"ControllerRevision\")\n\tb.WithAPIVersion(\"apps/v1\")\n\treturn b, nil\n}","line":{"from":73,"to":85}} {"id":100019863,"name":"WithKind","signature":"func (b *ControllerRevisionApplyConfiguration) WithKind(value string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/controllerrevision.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithKind(value string) *ControllerRevisionApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":87,"to":93}} {"id":100019864,"name":"WithAPIVersion","signature":"func (b *ControllerRevisionApplyConfiguration) WithAPIVersion(value string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/controllerrevision.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithAPIVersion(value string) *ControllerRevisionApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":95,"to":101}} {"id":100019865,"name":"WithName","signature":"func (b *ControllerRevisionApplyConfiguration) WithName(value string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/controllerrevision.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithName(value string) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":103,"to":110}} {"id":100019866,"name":"WithGenerateName","signature":"func (b *ControllerRevisionApplyConfiguration) WithGenerateName(value string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/controllerrevision.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithGenerateName(value string) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":112,"to":119}} {"id":100019867,"name":"WithNamespace","signature":"func (b *ControllerRevisionApplyConfiguration) WithNamespace(value string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/controllerrevision.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithNamespace(value string) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":121,"to":128}} {"id":100019868,"name":"WithUID","signature":"func (b *ControllerRevisionApplyConfiguration) WithUID(value types.UID) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/controllerrevision.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithUID(value types.UID) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":130,"to":137}} {"id":100019869,"name":"WithResourceVersion","signature":"func (b *ControllerRevisionApplyConfiguration) WithResourceVersion(value string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/controllerrevision.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithResourceVersion(value string) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":139,"to":146}} {"id":100019870,"name":"WithGeneration","signature":"func (b *ControllerRevisionApplyConfiguration) WithGeneration(value int64) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/controllerrevision.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithGeneration(value int64) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":148,"to":155}} {"id":100019871,"name":"WithCreationTimestamp","signature":"func (b *ControllerRevisionApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/controllerrevision.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":157,"to":164}} {"id":100019872,"name":"WithDeletionTimestamp","signature":"func (b *ControllerRevisionApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/controllerrevision.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":166,"to":173}} {"id":100019873,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ControllerRevisionApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/controllerrevision.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":175,"to":182}} {"id":100019874,"name":"WithLabels","signature":"func (b *ControllerRevisionApplyConfiguration) WithLabels(entries map[string]string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/controllerrevision.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ControllerRevisionApplyConfiguration) WithLabels(entries map[string]string) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":184,"to":197}} {"id":100019875,"name":"WithAnnotations","signature":"func (b *ControllerRevisionApplyConfiguration) WithAnnotations(entries map[string]string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/controllerrevision.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ControllerRevisionApplyConfiguration) WithAnnotations(entries map[string]string) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":199,"to":212}} {"id":100019876,"name":"WithOwnerReferences","signature":"func (b *ControllerRevisionApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/controllerrevision.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ControllerRevisionApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":214,"to":226}} {"id":100019877,"name":"WithFinalizers","signature":"func (b *ControllerRevisionApplyConfiguration) WithFinalizers(values ...string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/controllerrevision.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ControllerRevisionApplyConfiguration) WithFinalizers(values ...string) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":228,"to":237}} {"id":100019878,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ControllerRevisionApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/controllerrevision.go","code":"func (b *ControllerRevisionApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":239,"to":243}} {"id":100019879,"name":"WithData","signature":"func (b *ControllerRevisionApplyConfiguration) WithData(value runtime.RawExtension) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/controllerrevision.go","code":"// WithData sets the Data field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Data field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithData(value runtime.RawExtension) *ControllerRevisionApplyConfiguration {\n\tb.Data = \u0026value\n\treturn b\n}","line":{"from":245,"to":251}} {"id":100019880,"name":"WithRevision","signature":"func (b *ControllerRevisionApplyConfiguration) WithRevision(value int64) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/controllerrevision.go","code":"// WithRevision sets the Revision field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Revision field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithRevision(value int64) *ControllerRevisionApplyConfiguration {\n\tb.Revision = \u0026value\n\treturn b\n}","line":{"from":253,"to":259}} {"id":100019881,"name":"DaemonSet","signature":"func DaemonSet(name, namespace string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonset.go","code":"// DaemonSet constructs an declarative configuration of the DaemonSet type for use with\n// apply.\nfunc DaemonSet(name, namespace string) *DaemonSetApplyConfiguration {\n\tb := \u0026DaemonSetApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"DaemonSet\")\n\tb.WithAPIVersion(\"apps/v1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100019882,"name":"ExtractDaemonSet","signature":"func ExtractDaemonSet(daemonSet *apiappsv1.DaemonSet, fieldManager string) (*DaemonSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonset.go","code":"// ExtractDaemonSet extracts the applied configuration owned by fieldManager from\n// daemonSet. If no managedFields are found in daemonSet for fieldManager, a\n// DaemonSetApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// daemonSet must be a unmodified DaemonSet API object that was retrieved from the Kubernetes API.\n// ExtractDaemonSet provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractDaemonSet(daemonSet *apiappsv1.DaemonSet, fieldManager string) (*DaemonSetApplyConfiguration, error) {\n\treturn extractDaemonSet(daemonSet, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100019883,"name":"ExtractDaemonSetStatus","signature":"func ExtractDaemonSetStatus(daemonSet *apiappsv1.DaemonSet, fieldManager string) (*DaemonSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonset.go","code":"// ExtractDaemonSetStatus is the same as ExtractDaemonSet except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractDaemonSetStatus(daemonSet *apiappsv1.DaemonSet, fieldManager string) (*DaemonSetApplyConfiguration, error) {\n\treturn extractDaemonSet(daemonSet, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100019884,"name":"extractDaemonSet","signature":"func extractDaemonSet(daemonSet *apiappsv1.DaemonSet, fieldManager string, subresource string) (*DaemonSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonset.go","code":"func extractDaemonSet(daemonSet *apiappsv1.DaemonSet, fieldManager string, subresource string) (*DaemonSetApplyConfiguration, error) {\n\tb := \u0026DaemonSetApplyConfiguration{}\n\terr := managedfields.ExtractInto(daemonSet, internal.Parser().Type(\"io.k8s.api.apps.v1.DaemonSet\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(daemonSet.Name)\n\tb.WithNamespace(daemonSet.Namespace)\n\n\tb.WithKind(\"DaemonSet\")\n\tb.WithAPIVersion(\"apps/v1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100019885,"name":"WithKind","signature":"func (b *DaemonSetApplyConfiguration) WithKind(value string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonset.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithKind(value string) *DaemonSetApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100019886,"name":"WithAPIVersion","signature":"func (b *DaemonSetApplyConfiguration) WithAPIVersion(value string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonset.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithAPIVersion(value string) *DaemonSetApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100019887,"name":"WithName","signature":"func (b *DaemonSetApplyConfiguration) WithName(value string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonset.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithName(value string) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100019888,"name":"WithGenerateName","signature":"func (b *DaemonSetApplyConfiguration) WithGenerateName(value string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonset.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithGenerateName(value string) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100019889,"name":"WithNamespace","signature":"func (b *DaemonSetApplyConfiguration) WithNamespace(value string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonset.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithNamespace(value string) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100019890,"name":"WithUID","signature":"func (b *DaemonSetApplyConfiguration) WithUID(value types.UID) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonset.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithUID(value types.UID) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100019891,"name":"WithResourceVersion","signature":"func (b *DaemonSetApplyConfiguration) WithResourceVersion(value string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonset.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithResourceVersion(value string) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100019892,"name":"WithGeneration","signature":"func (b *DaemonSetApplyConfiguration) WithGeneration(value int64) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonset.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithGeneration(value int64) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100019893,"name":"WithCreationTimestamp","signature":"func (b *DaemonSetApplyConfiguration) WithCreationTimestamp(value metav1.Time) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonset.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithCreationTimestamp(value metav1.Time) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100019894,"name":"WithDeletionTimestamp","signature":"func (b *DaemonSetApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonset.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100019895,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *DaemonSetApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonset.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100019896,"name":"WithLabels","signature":"func (b *DaemonSetApplyConfiguration) WithLabels(entries map[string]string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonset.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *DaemonSetApplyConfiguration) WithLabels(entries map[string]string) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100019897,"name":"WithAnnotations","signature":"func (b *DaemonSetApplyConfiguration) WithAnnotations(entries map[string]string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonset.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *DaemonSetApplyConfiguration) WithAnnotations(entries map[string]string) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100019898,"name":"WithOwnerReferences","signature":"func (b *DaemonSetApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonset.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *DaemonSetApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100019899,"name":"WithFinalizers","signature":"func (b *DaemonSetApplyConfiguration) WithFinalizers(values ...string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonset.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *DaemonSetApplyConfiguration) WithFinalizers(values ...string) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100019900,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *DaemonSetApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonset.go","code":"func (b *DaemonSetApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100019901,"name":"WithSpec","signature":"func (b *DaemonSetApplyConfiguration) WithSpec(value *DaemonSetSpecApplyConfiguration) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonset.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithSpec(value *DaemonSetSpecApplyConfiguration) *DaemonSetApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100019902,"name":"WithStatus","signature":"func (b *DaemonSetApplyConfiguration) WithStatus(value *DaemonSetStatusApplyConfiguration) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonset.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithStatus(value *DaemonSetStatusApplyConfiguration) *DaemonSetApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100019903,"name":"DaemonSetCondition","signature":"func DaemonSetCondition() *DaemonSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonsetcondition.go","code":"// DaemonSetConditionApplyConfiguration constructs an declarative configuration of the DaemonSetCondition type for use with\n// apply.\nfunc DaemonSetCondition() *DaemonSetConditionApplyConfiguration {\n\treturn \u0026DaemonSetConditionApplyConfiguration{}\n}","line":{"from":37,"to":41}} {"id":100019904,"name":"WithType","signature":"func (b *DaemonSetConditionApplyConfiguration) WithType(value v1.DaemonSetConditionType) *DaemonSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonsetcondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *DaemonSetConditionApplyConfiguration) WithType(value v1.DaemonSetConditionType) *DaemonSetConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100019905,"name":"WithStatus","signature":"func (b *DaemonSetConditionApplyConfiguration) WithStatus(value corev1.ConditionStatus) *DaemonSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonsetcondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *DaemonSetConditionApplyConfiguration) WithStatus(value corev1.ConditionStatus) *DaemonSetConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100019906,"name":"WithLastTransitionTime","signature":"func (b *DaemonSetConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *DaemonSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonsetcondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *DaemonSetConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *DaemonSetConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":59,"to":65}} {"id":100019907,"name":"WithReason","signature":"func (b *DaemonSetConditionApplyConfiguration) WithReason(value string) *DaemonSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonsetcondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *DaemonSetConditionApplyConfiguration) WithReason(value string) *DaemonSetConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100019908,"name":"WithMessage","signature":"func (b *DaemonSetConditionApplyConfiguration) WithMessage(value string) *DaemonSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonsetcondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *DaemonSetConditionApplyConfiguration) WithMessage(value string) *DaemonSetConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":75,"to":81}} {"id":100019909,"name":"DaemonSetSpec","signature":"func DaemonSetSpec() *DaemonSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonsetspec.go","code":"// DaemonSetSpecApplyConfiguration constructs an declarative configuration of the DaemonSetSpec type for use with\n// apply.\nfunc DaemonSetSpec() *DaemonSetSpecApplyConfiguration {\n\treturn \u0026DaemonSetSpecApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100019910,"name":"WithSelector","signature":"func (b *DaemonSetSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *DaemonSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonsetspec.go","code":"// WithSelector sets the Selector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Selector field is set to the value of the last call.\nfunc (b *DaemonSetSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *DaemonSetSpecApplyConfiguration {\n\tb.Selector = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100019911,"name":"WithTemplate","signature":"func (b *DaemonSetSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *DaemonSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonsetspec.go","code":"// WithTemplate sets the Template field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Template field is set to the value of the last call.\nfunc (b *DaemonSetSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *DaemonSetSpecApplyConfiguration {\n\tb.Template = value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100019912,"name":"WithUpdateStrategy","signature":"func (b *DaemonSetSpecApplyConfiguration) WithUpdateStrategy(value *DaemonSetUpdateStrategyApplyConfiguration) *DaemonSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonsetspec.go","code":"// WithUpdateStrategy sets the UpdateStrategy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UpdateStrategy field is set to the value of the last call.\nfunc (b *DaemonSetSpecApplyConfiguration) WithUpdateStrategy(value *DaemonSetUpdateStrategyApplyConfiguration) *DaemonSetSpecApplyConfiguration {\n\tb.UpdateStrategy = value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100019913,"name":"WithMinReadySeconds","signature":"func (b *DaemonSetSpecApplyConfiguration) WithMinReadySeconds(value int32) *DaemonSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonsetspec.go","code":"// WithMinReadySeconds sets the MinReadySeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MinReadySeconds field is set to the value of the last call.\nfunc (b *DaemonSetSpecApplyConfiguration) WithMinReadySeconds(value int32) *DaemonSetSpecApplyConfiguration {\n\tb.MinReadySeconds = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100019914,"name":"WithRevisionHistoryLimit","signature":"func (b *DaemonSetSpecApplyConfiguration) WithRevisionHistoryLimit(value int32) *DaemonSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonsetspec.go","code":"// WithRevisionHistoryLimit sets the RevisionHistoryLimit field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RevisionHistoryLimit field is set to the value of the last call.\nfunc (b *DaemonSetSpecApplyConfiguration) WithRevisionHistoryLimit(value int32) *DaemonSetSpecApplyConfiguration {\n\tb.RevisionHistoryLimit = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100019915,"name":"DaemonSetStatus","signature":"func DaemonSetStatus() *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonsetstatus.go","code":"// DaemonSetStatusApplyConfiguration constructs an declarative configuration of the DaemonSetStatus type for use with\n// apply.\nfunc DaemonSetStatus() *DaemonSetStatusApplyConfiguration {\n\treturn \u0026DaemonSetStatusApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100019916,"name":"WithCurrentNumberScheduled","signature":"func (b *DaemonSetStatusApplyConfiguration) WithCurrentNumberScheduled(value int32) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonsetstatus.go","code":"// WithCurrentNumberScheduled sets the CurrentNumberScheduled field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CurrentNumberScheduled field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithCurrentNumberScheduled(value int32) *DaemonSetStatusApplyConfiguration {\n\tb.CurrentNumberScheduled = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100019917,"name":"WithNumberMisscheduled","signature":"func (b *DaemonSetStatusApplyConfiguration) WithNumberMisscheduled(value int32) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonsetstatus.go","code":"// WithNumberMisscheduled sets the NumberMisscheduled field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NumberMisscheduled field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithNumberMisscheduled(value int32) *DaemonSetStatusApplyConfiguration {\n\tb.NumberMisscheduled = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100019918,"name":"WithDesiredNumberScheduled","signature":"func (b *DaemonSetStatusApplyConfiguration) WithDesiredNumberScheduled(value int32) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonsetstatus.go","code":"// WithDesiredNumberScheduled sets the DesiredNumberScheduled field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DesiredNumberScheduled field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithDesiredNumberScheduled(value int32) *DaemonSetStatusApplyConfiguration {\n\tb.DesiredNumberScheduled = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100019919,"name":"WithNumberReady","signature":"func (b *DaemonSetStatusApplyConfiguration) WithNumberReady(value int32) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonsetstatus.go","code":"// WithNumberReady sets the NumberReady field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NumberReady field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithNumberReady(value int32) *DaemonSetStatusApplyConfiguration {\n\tb.NumberReady = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100019920,"name":"WithObservedGeneration","signature":"func (b *DaemonSetStatusApplyConfiguration) WithObservedGeneration(value int64) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonsetstatus.go","code":"// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObservedGeneration field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithObservedGeneration(value int64) *DaemonSetStatusApplyConfiguration {\n\tb.ObservedGeneration = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100019921,"name":"WithUpdatedNumberScheduled","signature":"func (b *DaemonSetStatusApplyConfiguration) WithUpdatedNumberScheduled(value int32) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonsetstatus.go","code":"// WithUpdatedNumberScheduled sets the UpdatedNumberScheduled field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UpdatedNumberScheduled field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithUpdatedNumberScheduled(value int32) *DaemonSetStatusApplyConfiguration {\n\tb.UpdatedNumberScheduled = \u0026value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100019922,"name":"WithNumberAvailable","signature":"func (b *DaemonSetStatusApplyConfiguration) WithNumberAvailable(value int32) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonsetstatus.go","code":"// WithNumberAvailable sets the NumberAvailable field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NumberAvailable field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithNumberAvailable(value int32) *DaemonSetStatusApplyConfiguration {\n\tb.NumberAvailable = \u0026value\n\treturn b\n}","line":{"from":90,"to":96}} {"id":100019923,"name":"WithNumberUnavailable","signature":"func (b *DaemonSetStatusApplyConfiguration) WithNumberUnavailable(value int32) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonsetstatus.go","code":"// WithNumberUnavailable sets the NumberUnavailable field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NumberUnavailable field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithNumberUnavailable(value int32) *DaemonSetStatusApplyConfiguration {\n\tb.NumberUnavailable = \u0026value\n\treturn b\n}","line":{"from":98,"to":104}} {"id":100019924,"name":"WithCollisionCount","signature":"func (b *DaemonSetStatusApplyConfiguration) WithCollisionCount(value int32) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonsetstatus.go","code":"// WithCollisionCount sets the CollisionCount field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CollisionCount field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithCollisionCount(value int32) *DaemonSetStatusApplyConfiguration {\n\tb.CollisionCount = \u0026value\n\treturn b\n}","line":{"from":106,"to":112}} {"id":100019925,"name":"WithConditions","signature":"func (b *DaemonSetStatusApplyConfiguration) WithConditions(values ...*DaemonSetConditionApplyConfiguration) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/daemonsetstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *DaemonSetStatusApplyConfiguration) WithConditions(values ...*DaemonSetConditionApplyConfiguration) *DaemonSetStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":114,"to":125}} {"id":100019926,"name":"Deployment","signature":"func Deployment(name, namespace string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deployment.go","code":"// Deployment constructs an declarative configuration of the Deployment type for use with\n// apply.\nfunc Deployment(name, namespace string) *DeploymentApplyConfiguration {\n\tb := \u0026DeploymentApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"Deployment\")\n\tb.WithAPIVersion(\"apps/v1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100019927,"name":"ExtractDeployment","signature":"func ExtractDeployment(deployment *apiappsv1.Deployment, fieldManager string) (*DeploymentApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deployment.go","code":"// ExtractDeployment extracts the applied configuration owned by fieldManager from\n// deployment. If no managedFields are found in deployment for fieldManager, a\n// DeploymentApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// deployment must be a unmodified Deployment API object that was retrieved from the Kubernetes API.\n// ExtractDeployment provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractDeployment(deployment *apiappsv1.Deployment, fieldManager string) (*DeploymentApplyConfiguration, error) {\n\treturn extractDeployment(deployment, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100019928,"name":"ExtractDeploymentStatus","signature":"func ExtractDeploymentStatus(deployment *apiappsv1.Deployment, fieldManager string) (*DeploymentApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deployment.go","code":"// ExtractDeploymentStatus is the same as ExtractDeployment except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractDeploymentStatus(deployment *apiappsv1.Deployment, fieldManager string) (*DeploymentApplyConfiguration, error) {\n\treturn extractDeployment(deployment, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100019929,"name":"extractDeployment","signature":"func extractDeployment(deployment *apiappsv1.Deployment, fieldManager string, subresource string) (*DeploymentApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deployment.go","code":"func extractDeployment(deployment *apiappsv1.Deployment, fieldManager string, subresource string) (*DeploymentApplyConfiguration, error) {\n\tb := \u0026DeploymentApplyConfiguration{}\n\terr := managedfields.ExtractInto(deployment, internal.Parser().Type(\"io.k8s.api.apps.v1.Deployment\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(deployment.Name)\n\tb.WithNamespace(deployment.Namespace)\n\n\tb.WithKind(\"Deployment\")\n\tb.WithAPIVersion(\"apps/v1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100019930,"name":"WithKind","signature":"func (b *DeploymentApplyConfiguration) WithKind(value string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deployment.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithKind(value string) *DeploymentApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100019931,"name":"WithAPIVersion","signature":"func (b *DeploymentApplyConfiguration) WithAPIVersion(value string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deployment.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithAPIVersion(value string) *DeploymentApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100019932,"name":"WithName","signature":"func (b *DeploymentApplyConfiguration) WithName(value string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deployment.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithName(value string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100019933,"name":"WithGenerateName","signature":"func (b *DeploymentApplyConfiguration) WithGenerateName(value string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deployment.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithGenerateName(value string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100019934,"name":"WithNamespace","signature":"func (b *DeploymentApplyConfiguration) WithNamespace(value string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deployment.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithNamespace(value string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100019935,"name":"WithUID","signature":"func (b *DeploymentApplyConfiguration) WithUID(value types.UID) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deployment.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithUID(value types.UID) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100019936,"name":"WithResourceVersion","signature":"func (b *DeploymentApplyConfiguration) WithResourceVersion(value string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deployment.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithResourceVersion(value string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100019937,"name":"WithGeneration","signature":"func (b *DeploymentApplyConfiguration) WithGeneration(value int64) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deployment.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithGeneration(value int64) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100019938,"name":"WithCreationTimestamp","signature":"func (b *DeploymentApplyConfiguration) WithCreationTimestamp(value metav1.Time) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deployment.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithCreationTimestamp(value metav1.Time) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100019939,"name":"WithDeletionTimestamp","signature":"func (b *DeploymentApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deployment.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100019940,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *DeploymentApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deployment.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100019941,"name":"WithLabels","signature":"func (b *DeploymentApplyConfiguration) WithLabels(entries map[string]string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deployment.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *DeploymentApplyConfiguration) WithLabels(entries map[string]string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100019942,"name":"WithAnnotations","signature":"func (b *DeploymentApplyConfiguration) WithAnnotations(entries map[string]string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deployment.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *DeploymentApplyConfiguration) WithAnnotations(entries map[string]string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100019943,"name":"WithOwnerReferences","signature":"func (b *DeploymentApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deployment.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *DeploymentApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100019944,"name":"WithFinalizers","signature":"func (b *DeploymentApplyConfiguration) WithFinalizers(values ...string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deployment.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *DeploymentApplyConfiguration) WithFinalizers(values ...string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100019945,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *DeploymentApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deployment.go","code":"func (b *DeploymentApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100019946,"name":"WithSpec","signature":"func (b *DeploymentApplyConfiguration) WithSpec(value *DeploymentSpecApplyConfiguration) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deployment.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithSpec(value *DeploymentSpecApplyConfiguration) *DeploymentApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100019947,"name":"WithStatus","signature":"func (b *DeploymentApplyConfiguration) WithStatus(value *DeploymentStatusApplyConfiguration) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deployment.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithStatus(value *DeploymentStatusApplyConfiguration) *DeploymentApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100019948,"name":"DeploymentCondition","signature":"func DeploymentCondition() *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentcondition.go","code":"// DeploymentConditionApplyConfiguration constructs an declarative configuration of the DeploymentCondition type for use with\n// apply.\nfunc DeploymentCondition() *DeploymentConditionApplyConfiguration {\n\treturn \u0026DeploymentConditionApplyConfiguration{}\n}","line":{"from":38,"to":42}} {"id":100019949,"name":"WithType","signature":"func (b *DeploymentConditionApplyConfiguration) WithType(value v1.DeploymentConditionType) *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentcondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *DeploymentConditionApplyConfiguration) WithType(value v1.DeploymentConditionType) *DeploymentConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100019950,"name":"WithStatus","signature":"func (b *DeploymentConditionApplyConfiguration) WithStatus(value corev1.ConditionStatus) *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentcondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *DeploymentConditionApplyConfiguration) WithStatus(value corev1.ConditionStatus) *DeploymentConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100019951,"name":"WithLastUpdateTime","signature":"func (b *DeploymentConditionApplyConfiguration) WithLastUpdateTime(value metav1.Time) *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentcondition.go","code":"// WithLastUpdateTime sets the LastUpdateTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastUpdateTime field is set to the value of the last call.\nfunc (b *DeploymentConditionApplyConfiguration) WithLastUpdateTime(value metav1.Time) *DeploymentConditionApplyConfiguration {\n\tb.LastUpdateTime = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100019952,"name":"WithLastTransitionTime","signature":"func (b *DeploymentConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentcondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *DeploymentConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *DeploymentConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":68,"to":74}} {"id":100019953,"name":"WithReason","signature":"func (b *DeploymentConditionApplyConfiguration) WithReason(value string) *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentcondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *DeploymentConditionApplyConfiguration) WithReason(value string) *DeploymentConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":76,"to":82}} {"id":100019954,"name":"WithMessage","signature":"func (b *DeploymentConditionApplyConfiguration) WithMessage(value string) *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentcondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *DeploymentConditionApplyConfiguration) WithMessage(value string) *DeploymentConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100019955,"name":"DeploymentSpec","signature":"func DeploymentSpec() *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentspec.go","code":"// DeploymentSpecApplyConfiguration constructs an declarative configuration of the DeploymentSpec type for use with\n// apply.\nfunc DeploymentSpec() *DeploymentSpecApplyConfiguration {\n\treturn \u0026DeploymentSpecApplyConfiguration{}\n}","line":{"from":39,"to":43}} {"id":100019956,"name":"WithReplicas","signature":"func (b *DeploymentSpecApplyConfiguration) WithReplicas(value int32) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentspec.go","code":"// WithReplicas sets the Replicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Replicas field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithReplicas(value int32) *DeploymentSpecApplyConfiguration {\n\tb.Replicas = \u0026value\n\treturn b\n}","line":{"from":45,"to":51}} {"id":100019957,"name":"WithSelector","signature":"func (b *DeploymentSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentspec.go","code":"// WithSelector sets the Selector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Selector field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *DeploymentSpecApplyConfiguration {\n\tb.Selector = value\n\treturn b\n}","line":{"from":53,"to":59}} {"id":100019958,"name":"WithTemplate","signature":"func (b *DeploymentSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentspec.go","code":"// WithTemplate sets the Template field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Template field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *DeploymentSpecApplyConfiguration {\n\tb.Template = value\n\treturn b\n}","line":{"from":61,"to":67}} {"id":100019959,"name":"WithStrategy","signature":"func (b *DeploymentSpecApplyConfiguration) WithStrategy(value *DeploymentStrategyApplyConfiguration) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentspec.go","code":"// WithStrategy sets the Strategy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Strategy field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithStrategy(value *DeploymentStrategyApplyConfiguration) *DeploymentSpecApplyConfiguration {\n\tb.Strategy = value\n\treturn b\n}","line":{"from":69,"to":75}} {"id":100019960,"name":"WithMinReadySeconds","signature":"func (b *DeploymentSpecApplyConfiguration) WithMinReadySeconds(value int32) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentspec.go","code":"// WithMinReadySeconds sets the MinReadySeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MinReadySeconds field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithMinReadySeconds(value int32) *DeploymentSpecApplyConfiguration {\n\tb.MinReadySeconds = \u0026value\n\treturn b\n}","line":{"from":77,"to":83}} {"id":100019961,"name":"WithRevisionHistoryLimit","signature":"func (b *DeploymentSpecApplyConfiguration) WithRevisionHistoryLimit(value int32) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentspec.go","code":"// WithRevisionHistoryLimit sets the RevisionHistoryLimit field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RevisionHistoryLimit field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithRevisionHistoryLimit(value int32) *DeploymentSpecApplyConfiguration {\n\tb.RevisionHistoryLimit = \u0026value\n\treturn b\n}","line":{"from":85,"to":91}} {"id":100019962,"name":"WithPaused","signature":"func (b *DeploymentSpecApplyConfiguration) WithPaused(value bool) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentspec.go","code":"// WithPaused sets the Paused field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Paused field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithPaused(value bool) *DeploymentSpecApplyConfiguration {\n\tb.Paused = \u0026value\n\treturn b\n}","line":{"from":93,"to":99}} {"id":100019963,"name":"WithProgressDeadlineSeconds","signature":"func (b *DeploymentSpecApplyConfiguration) WithProgressDeadlineSeconds(value int32) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentspec.go","code":"// WithProgressDeadlineSeconds sets the ProgressDeadlineSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ProgressDeadlineSeconds field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithProgressDeadlineSeconds(value int32) *DeploymentSpecApplyConfiguration {\n\tb.ProgressDeadlineSeconds = \u0026value\n\treturn b\n}","line":{"from":101,"to":107}} {"id":100019964,"name":"DeploymentStatus","signature":"func DeploymentStatus() *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentstatus.go","code":"// DeploymentStatusApplyConfiguration constructs an declarative configuration of the DeploymentStatus type for use with\n// apply.\nfunc DeploymentStatus() *DeploymentStatusApplyConfiguration {\n\treturn \u0026DeploymentStatusApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100019965,"name":"WithObservedGeneration","signature":"func (b *DeploymentStatusApplyConfiguration) WithObservedGeneration(value int64) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentstatus.go","code":"// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObservedGeneration field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithObservedGeneration(value int64) *DeploymentStatusApplyConfiguration {\n\tb.ObservedGeneration = \u0026value\n\treturn b\n}","line":{"from":40,"to":46}} {"id":100019966,"name":"WithReplicas","signature":"func (b *DeploymentStatusApplyConfiguration) WithReplicas(value int32) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentstatus.go","code":"// WithReplicas sets the Replicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Replicas field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithReplicas(value int32) *DeploymentStatusApplyConfiguration {\n\tb.Replicas = \u0026value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100019967,"name":"WithUpdatedReplicas","signature":"func (b *DeploymentStatusApplyConfiguration) WithUpdatedReplicas(value int32) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentstatus.go","code":"// WithUpdatedReplicas sets the UpdatedReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UpdatedReplicas field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithUpdatedReplicas(value int32) *DeploymentStatusApplyConfiguration {\n\tb.UpdatedReplicas = \u0026value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100019968,"name":"WithReadyReplicas","signature":"func (b *DeploymentStatusApplyConfiguration) WithReadyReplicas(value int32) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentstatus.go","code":"// WithReadyReplicas sets the ReadyReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadyReplicas field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithReadyReplicas(value int32) *DeploymentStatusApplyConfiguration {\n\tb.ReadyReplicas = \u0026value\n\treturn b\n}","line":{"from":64,"to":70}} {"id":100019969,"name":"WithAvailableReplicas","signature":"func (b *DeploymentStatusApplyConfiguration) WithAvailableReplicas(value int32) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentstatus.go","code":"// WithAvailableReplicas sets the AvailableReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AvailableReplicas field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithAvailableReplicas(value int32) *DeploymentStatusApplyConfiguration {\n\tb.AvailableReplicas = \u0026value\n\treturn b\n}","line":{"from":72,"to":78}} {"id":100019970,"name":"WithUnavailableReplicas","signature":"func (b *DeploymentStatusApplyConfiguration) WithUnavailableReplicas(value int32) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentstatus.go","code":"// WithUnavailableReplicas sets the UnavailableReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UnavailableReplicas field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithUnavailableReplicas(value int32) *DeploymentStatusApplyConfiguration {\n\tb.UnavailableReplicas = \u0026value\n\treturn b\n}","line":{"from":80,"to":86}} {"id":100019971,"name":"WithConditions","signature":"func (b *DeploymentStatusApplyConfiguration) WithConditions(values ...*DeploymentConditionApplyConfiguration) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *DeploymentStatusApplyConfiguration) WithConditions(values ...*DeploymentConditionApplyConfiguration) *DeploymentStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":88,"to":99}} {"id":100019972,"name":"WithCollisionCount","signature":"func (b *DeploymentStatusApplyConfiguration) WithCollisionCount(value int32) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentstatus.go","code":"// WithCollisionCount sets the CollisionCount field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CollisionCount field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithCollisionCount(value int32) *DeploymentStatusApplyConfiguration {\n\tb.CollisionCount = \u0026value\n\treturn b\n}","line":{"from":101,"to":107}} {"id":100019973,"name":"DeploymentStrategy","signature":"func DeploymentStrategy() *DeploymentStrategyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentstrategy.go","code":"// DeploymentStrategyApplyConfiguration constructs an declarative configuration of the DeploymentStrategy type for use with\n// apply.\nfunc DeploymentStrategy() *DeploymentStrategyApplyConfiguration {\n\treturn \u0026DeploymentStrategyApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100019974,"name":"WithType","signature":"func (b *DeploymentStrategyApplyConfiguration) WithType(value v1.DeploymentStrategyType) *DeploymentStrategyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentstrategy.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *DeploymentStrategyApplyConfiguration) WithType(value v1.DeploymentStrategyType) *DeploymentStrategyApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100019975,"name":"WithRollingUpdate","signature":"func (b *DeploymentStrategyApplyConfiguration) WithRollingUpdate(value *RollingUpdateDeploymentApplyConfiguration) *DeploymentStrategyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/deploymentstrategy.go","code":"// WithRollingUpdate sets the RollingUpdate field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RollingUpdate field is set to the value of the last call.\nfunc (b *DeploymentStrategyApplyConfiguration) WithRollingUpdate(value *RollingUpdateDeploymentApplyConfiguration) *DeploymentStrategyApplyConfiguration {\n\tb.RollingUpdate = value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100019976,"name":"ReplicaSet","signature":"func ReplicaSet(name, namespace string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicaset.go","code":"// ReplicaSet constructs an declarative configuration of the ReplicaSet type for use with\n// apply.\nfunc ReplicaSet(name, namespace string) *ReplicaSetApplyConfiguration {\n\tb := \u0026ReplicaSetApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"ReplicaSet\")\n\tb.WithAPIVersion(\"apps/v1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100019977,"name":"ExtractReplicaSet","signature":"func ExtractReplicaSet(replicaSet *apiappsv1.ReplicaSet, fieldManager string) (*ReplicaSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicaset.go","code":"// ExtractReplicaSet extracts the applied configuration owned by fieldManager from\n// replicaSet. If no managedFields are found in replicaSet for fieldManager, a\n// ReplicaSetApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// replicaSet must be a unmodified ReplicaSet API object that was retrieved from the Kubernetes API.\n// ExtractReplicaSet provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractReplicaSet(replicaSet *apiappsv1.ReplicaSet, fieldManager string) (*ReplicaSetApplyConfiguration, error) {\n\treturn extractReplicaSet(replicaSet, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100019978,"name":"ExtractReplicaSetStatus","signature":"func ExtractReplicaSetStatus(replicaSet *apiappsv1.ReplicaSet, fieldManager string) (*ReplicaSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicaset.go","code":"// ExtractReplicaSetStatus is the same as ExtractReplicaSet except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractReplicaSetStatus(replicaSet *apiappsv1.ReplicaSet, fieldManager string) (*ReplicaSetApplyConfiguration, error) {\n\treturn extractReplicaSet(replicaSet, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100019979,"name":"extractReplicaSet","signature":"func extractReplicaSet(replicaSet *apiappsv1.ReplicaSet, fieldManager string, subresource string) (*ReplicaSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicaset.go","code":"func extractReplicaSet(replicaSet *apiappsv1.ReplicaSet, fieldManager string, subresource string) (*ReplicaSetApplyConfiguration, error) {\n\tb := \u0026ReplicaSetApplyConfiguration{}\n\terr := managedfields.ExtractInto(replicaSet, internal.Parser().Type(\"io.k8s.api.apps.v1.ReplicaSet\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(replicaSet.Name)\n\tb.WithNamespace(replicaSet.Namespace)\n\n\tb.WithKind(\"ReplicaSet\")\n\tb.WithAPIVersion(\"apps/v1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100019980,"name":"WithKind","signature":"func (b *ReplicaSetApplyConfiguration) WithKind(value string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicaset.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithKind(value string) *ReplicaSetApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100019981,"name":"WithAPIVersion","signature":"func (b *ReplicaSetApplyConfiguration) WithAPIVersion(value string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicaset.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithAPIVersion(value string) *ReplicaSetApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100019982,"name":"WithName","signature":"func (b *ReplicaSetApplyConfiguration) WithName(value string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicaset.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithName(value string) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100019983,"name":"WithGenerateName","signature":"func (b *ReplicaSetApplyConfiguration) WithGenerateName(value string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicaset.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithGenerateName(value string) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100019984,"name":"WithNamespace","signature":"func (b *ReplicaSetApplyConfiguration) WithNamespace(value string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicaset.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithNamespace(value string) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100019985,"name":"WithUID","signature":"func (b *ReplicaSetApplyConfiguration) WithUID(value types.UID) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicaset.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithUID(value types.UID) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100019986,"name":"WithResourceVersion","signature":"func (b *ReplicaSetApplyConfiguration) WithResourceVersion(value string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicaset.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithResourceVersion(value string) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100019987,"name":"WithGeneration","signature":"func (b *ReplicaSetApplyConfiguration) WithGeneration(value int64) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicaset.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithGeneration(value int64) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100019988,"name":"WithCreationTimestamp","signature":"func (b *ReplicaSetApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicaset.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100019989,"name":"WithDeletionTimestamp","signature":"func (b *ReplicaSetApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicaset.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100019990,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ReplicaSetApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicaset.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100019991,"name":"WithLabels","signature":"func (b *ReplicaSetApplyConfiguration) WithLabels(entries map[string]string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicaset.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ReplicaSetApplyConfiguration) WithLabels(entries map[string]string) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100019992,"name":"WithAnnotations","signature":"func (b *ReplicaSetApplyConfiguration) WithAnnotations(entries map[string]string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicaset.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ReplicaSetApplyConfiguration) WithAnnotations(entries map[string]string) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100019993,"name":"WithOwnerReferences","signature":"func (b *ReplicaSetApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicaset.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ReplicaSetApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100019994,"name":"WithFinalizers","signature":"func (b *ReplicaSetApplyConfiguration) WithFinalizers(values ...string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicaset.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ReplicaSetApplyConfiguration) WithFinalizers(values ...string) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100019995,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ReplicaSetApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicaset.go","code":"func (b *ReplicaSetApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100019996,"name":"WithSpec","signature":"func (b *ReplicaSetApplyConfiguration) WithSpec(value *ReplicaSetSpecApplyConfiguration) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicaset.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithSpec(value *ReplicaSetSpecApplyConfiguration) *ReplicaSetApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100019997,"name":"WithStatus","signature":"func (b *ReplicaSetApplyConfiguration) WithStatus(value *ReplicaSetStatusApplyConfiguration) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicaset.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithStatus(value *ReplicaSetStatusApplyConfiguration) *ReplicaSetApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100019998,"name":"ReplicaSetCondition","signature":"func ReplicaSetCondition() *ReplicaSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicasetcondition.go","code":"// ReplicaSetConditionApplyConfiguration constructs an declarative configuration of the ReplicaSetCondition type for use with\n// apply.\nfunc ReplicaSetCondition() *ReplicaSetConditionApplyConfiguration {\n\treturn \u0026ReplicaSetConditionApplyConfiguration{}\n}","line":{"from":37,"to":41}} {"id":100019999,"name":"WithType","signature":"func (b *ReplicaSetConditionApplyConfiguration) WithType(value v1.ReplicaSetConditionType) *ReplicaSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicasetcondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *ReplicaSetConditionApplyConfiguration) WithType(value v1.ReplicaSetConditionType) *ReplicaSetConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100020000,"name":"WithStatus","signature":"func (b *ReplicaSetConditionApplyConfiguration) WithStatus(value corev1.ConditionStatus) *ReplicaSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicasetcondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *ReplicaSetConditionApplyConfiguration) WithStatus(value corev1.ConditionStatus) *ReplicaSetConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100020001,"name":"WithLastTransitionTime","signature":"func (b *ReplicaSetConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *ReplicaSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicasetcondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *ReplicaSetConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *ReplicaSetConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":59,"to":65}} {"id":100020002,"name":"WithReason","signature":"func (b *ReplicaSetConditionApplyConfiguration) WithReason(value string) *ReplicaSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicasetcondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *ReplicaSetConditionApplyConfiguration) WithReason(value string) *ReplicaSetConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100020003,"name":"WithMessage","signature":"func (b *ReplicaSetConditionApplyConfiguration) WithMessage(value string) *ReplicaSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicasetcondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *ReplicaSetConditionApplyConfiguration) WithMessage(value string) *ReplicaSetConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":75,"to":81}} {"id":100020004,"name":"ReplicaSetSpec","signature":"func ReplicaSetSpec() *ReplicaSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicasetspec.go","code":"// ReplicaSetSpecApplyConfiguration constructs an declarative configuration of the ReplicaSetSpec type for use with\n// apply.\nfunc ReplicaSetSpec() *ReplicaSetSpecApplyConfiguration {\n\treturn \u0026ReplicaSetSpecApplyConfiguration{}\n}","line":{"from":35,"to":39}} {"id":100020005,"name":"WithReplicas","signature":"func (b *ReplicaSetSpecApplyConfiguration) WithReplicas(value int32) *ReplicaSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicasetspec.go","code":"// WithReplicas sets the Replicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Replicas field is set to the value of the last call.\nfunc (b *ReplicaSetSpecApplyConfiguration) WithReplicas(value int32) *ReplicaSetSpecApplyConfiguration {\n\tb.Replicas = \u0026value\n\treturn b\n}","line":{"from":41,"to":47}} {"id":100020006,"name":"WithMinReadySeconds","signature":"func (b *ReplicaSetSpecApplyConfiguration) WithMinReadySeconds(value int32) *ReplicaSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicasetspec.go","code":"// WithMinReadySeconds sets the MinReadySeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MinReadySeconds field is set to the value of the last call.\nfunc (b *ReplicaSetSpecApplyConfiguration) WithMinReadySeconds(value int32) *ReplicaSetSpecApplyConfiguration {\n\tb.MinReadySeconds = \u0026value\n\treturn b\n}","line":{"from":49,"to":55}} {"id":100020007,"name":"WithSelector","signature":"func (b *ReplicaSetSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *ReplicaSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicasetspec.go","code":"// WithSelector sets the Selector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Selector field is set to the value of the last call.\nfunc (b *ReplicaSetSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *ReplicaSetSpecApplyConfiguration {\n\tb.Selector = value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100020008,"name":"WithTemplate","signature":"func (b *ReplicaSetSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *ReplicaSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicasetspec.go","code":"// WithTemplate sets the Template field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Template field is set to the value of the last call.\nfunc (b *ReplicaSetSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *ReplicaSetSpecApplyConfiguration {\n\tb.Template = value\n\treturn b\n}","line":{"from":65,"to":71}} {"id":100020009,"name":"ReplicaSetStatus","signature":"func ReplicaSetStatus() *ReplicaSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicasetstatus.go","code":"// ReplicaSetStatusApplyConfiguration constructs an declarative configuration of the ReplicaSetStatus type for use with\n// apply.\nfunc ReplicaSetStatus() *ReplicaSetStatusApplyConfiguration {\n\treturn \u0026ReplicaSetStatusApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100020010,"name":"WithReplicas","signature":"func (b *ReplicaSetStatusApplyConfiguration) WithReplicas(value int32) *ReplicaSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicasetstatus.go","code":"// WithReplicas sets the Replicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Replicas field is set to the value of the last call.\nfunc (b *ReplicaSetStatusApplyConfiguration) WithReplicas(value int32) *ReplicaSetStatusApplyConfiguration {\n\tb.Replicas = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100020011,"name":"WithFullyLabeledReplicas","signature":"func (b *ReplicaSetStatusApplyConfiguration) WithFullyLabeledReplicas(value int32) *ReplicaSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicasetstatus.go","code":"// WithFullyLabeledReplicas sets the FullyLabeledReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FullyLabeledReplicas field is set to the value of the last call.\nfunc (b *ReplicaSetStatusApplyConfiguration) WithFullyLabeledReplicas(value int32) *ReplicaSetStatusApplyConfiguration {\n\tb.FullyLabeledReplicas = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100020012,"name":"WithReadyReplicas","signature":"func (b *ReplicaSetStatusApplyConfiguration) WithReadyReplicas(value int32) *ReplicaSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicasetstatus.go","code":"// WithReadyReplicas sets the ReadyReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadyReplicas field is set to the value of the last call.\nfunc (b *ReplicaSetStatusApplyConfiguration) WithReadyReplicas(value int32) *ReplicaSetStatusApplyConfiguration {\n\tb.ReadyReplicas = \u0026value\n\treturn b\n}","line":{"from":54,"to":60}} {"id":100020013,"name":"WithAvailableReplicas","signature":"func (b *ReplicaSetStatusApplyConfiguration) WithAvailableReplicas(value int32) *ReplicaSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicasetstatus.go","code":"// WithAvailableReplicas sets the AvailableReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AvailableReplicas field is set to the value of the last call.\nfunc (b *ReplicaSetStatusApplyConfiguration) WithAvailableReplicas(value int32) *ReplicaSetStatusApplyConfiguration {\n\tb.AvailableReplicas = \u0026value\n\treturn b\n}","line":{"from":62,"to":68}} {"id":100020014,"name":"WithObservedGeneration","signature":"func (b *ReplicaSetStatusApplyConfiguration) WithObservedGeneration(value int64) *ReplicaSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicasetstatus.go","code":"// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObservedGeneration field is set to the value of the last call.\nfunc (b *ReplicaSetStatusApplyConfiguration) WithObservedGeneration(value int64) *ReplicaSetStatusApplyConfiguration {\n\tb.ObservedGeneration = \u0026value\n\treturn b\n}","line":{"from":70,"to":76}} {"id":100020015,"name":"WithConditions","signature":"func (b *ReplicaSetStatusApplyConfiguration) WithConditions(values ...*ReplicaSetConditionApplyConfiguration) *ReplicaSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/replicasetstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *ReplicaSetStatusApplyConfiguration) WithConditions(values ...*ReplicaSetConditionApplyConfiguration) *ReplicaSetStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":78,"to":89}} {"id":100020016,"name":"RollingUpdateDaemonSet","signature":"func RollingUpdateDaemonSet() *RollingUpdateDaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/rollingupdatedaemonset.go","code":"// RollingUpdateDaemonSetApplyConfiguration constructs an declarative configuration of the RollingUpdateDaemonSet type for use with\n// apply.\nfunc RollingUpdateDaemonSet() *RollingUpdateDaemonSetApplyConfiguration {\n\treturn \u0026RollingUpdateDaemonSetApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100020017,"name":"WithMaxUnavailable","signature":"func (b *RollingUpdateDaemonSetApplyConfiguration) WithMaxUnavailable(value intstr.IntOrString) *RollingUpdateDaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/rollingupdatedaemonset.go","code":"// WithMaxUnavailable sets the MaxUnavailable field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MaxUnavailable field is set to the value of the last call.\nfunc (b *RollingUpdateDaemonSetApplyConfiguration) WithMaxUnavailable(value intstr.IntOrString) *RollingUpdateDaemonSetApplyConfiguration {\n\tb.MaxUnavailable = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100020018,"name":"WithMaxSurge","signature":"func (b *RollingUpdateDaemonSetApplyConfiguration) WithMaxSurge(value intstr.IntOrString) *RollingUpdateDaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/rollingupdatedaemonset.go","code":"// WithMaxSurge sets the MaxSurge field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MaxSurge field is set to the value of the last call.\nfunc (b *RollingUpdateDaemonSetApplyConfiguration) WithMaxSurge(value intstr.IntOrString) *RollingUpdateDaemonSetApplyConfiguration {\n\tb.MaxSurge = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100020019,"name":"RollingUpdateDeployment","signature":"func RollingUpdateDeployment() *RollingUpdateDeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/rollingupdatedeployment.go","code":"// RollingUpdateDeploymentApplyConfiguration constructs an declarative configuration of the RollingUpdateDeployment type for use with\n// apply.\nfunc RollingUpdateDeployment() *RollingUpdateDeploymentApplyConfiguration {\n\treturn \u0026RollingUpdateDeploymentApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100020020,"name":"WithMaxUnavailable","signature":"func (b *RollingUpdateDeploymentApplyConfiguration) WithMaxUnavailable(value intstr.IntOrString) *RollingUpdateDeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/rollingupdatedeployment.go","code":"// WithMaxUnavailable sets the MaxUnavailable field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MaxUnavailable field is set to the value of the last call.\nfunc (b *RollingUpdateDeploymentApplyConfiguration) WithMaxUnavailable(value intstr.IntOrString) *RollingUpdateDeploymentApplyConfiguration {\n\tb.MaxUnavailable = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100020021,"name":"WithMaxSurge","signature":"func (b *RollingUpdateDeploymentApplyConfiguration) WithMaxSurge(value intstr.IntOrString) *RollingUpdateDeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/rollingupdatedeployment.go","code":"// WithMaxSurge sets the MaxSurge field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MaxSurge field is set to the value of the last call.\nfunc (b *RollingUpdateDeploymentApplyConfiguration) WithMaxSurge(value intstr.IntOrString) *RollingUpdateDeploymentApplyConfiguration {\n\tb.MaxSurge = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100020022,"name":"StatefulSet","signature":"func StatefulSet(name, namespace string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulset.go","code":"// StatefulSet constructs an declarative configuration of the StatefulSet type for use with\n// apply.\nfunc StatefulSet(name, namespace string) *StatefulSetApplyConfiguration {\n\tb := \u0026StatefulSetApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"StatefulSet\")\n\tb.WithAPIVersion(\"apps/v1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100020023,"name":"ExtractStatefulSet","signature":"func ExtractStatefulSet(statefulSet *apiappsv1.StatefulSet, fieldManager string) (*StatefulSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulset.go","code":"// ExtractStatefulSet extracts the applied configuration owned by fieldManager from\n// statefulSet. If no managedFields are found in statefulSet for fieldManager, a\n// StatefulSetApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// statefulSet must be a unmodified StatefulSet API object that was retrieved from the Kubernetes API.\n// ExtractStatefulSet provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractStatefulSet(statefulSet *apiappsv1.StatefulSet, fieldManager string) (*StatefulSetApplyConfiguration, error) {\n\treturn extractStatefulSet(statefulSet, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100020024,"name":"ExtractStatefulSetStatus","signature":"func ExtractStatefulSetStatus(statefulSet *apiappsv1.StatefulSet, fieldManager string) (*StatefulSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulset.go","code":"// ExtractStatefulSetStatus is the same as ExtractStatefulSet except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractStatefulSetStatus(statefulSet *apiappsv1.StatefulSet, fieldManager string) (*StatefulSetApplyConfiguration, error) {\n\treturn extractStatefulSet(statefulSet, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100020025,"name":"extractStatefulSet","signature":"func extractStatefulSet(statefulSet *apiappsv1.StatefulSet, fieldManager string, subresource string) (*StatefulSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulset.go","code":"func extractStatefulSet(statefulSet *apiappsv1.StatefulSet, fieldManager string, subresource string) (*StatefulSetApplyConfiguration, error) {\n\tb := \u0026StatefulSetApplyConfiguration{}\n\terr := managedfields.ExtractInto(statefulSet, internal.Parser().Type(\"io.k8s.api.apps.v1.StatefulSet\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(statefulSet.Name)\n\tb.WithNamespace(statefulSet.Namespace)\n\n\tb.WithKind(\"StatefulSet\")\n\tb.WithAPIVersion(\"apps/v1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100020026,"name":"WithKind","signature":"func (b *StatefulSetApplyConfiguration) WithKind(value string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulset.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithKind(value string) *StatefulSetApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100020027,"name":"WithAPIVersion","signature":"func (b *StatefulSetApplyConfiguration) WithAPIVersion(value string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulset.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithAPIVersion(value string) *StatefulSetApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100020028,"name":"WithName","signature":"func (b *StatefulSetApplyConfiguration) WithName(value string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulset.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithName(value string) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100020029,"name":"WithGenerateName","signature":"func (b *StatefulSetApplyConfiguration) WithGenerateName(value string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulset.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithGenerateName(value string) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100020030,"name":"WithNamespace","signature":"func (b *StatefulSetApplyConfiguration) WithNamespace(value string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulset.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithNamespace(value string) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100020031,"name":"WithUID","signature":"func (b *StatefulSetApplyConfiguration) WithUID(value types.UID) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulset.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithUID(value types.UID) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100020032,"name":"WithResourceVersion","signature":"func (b *StatefulSetApplyConfiguration) WithResourceVersion(value string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulset.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithResourceVersion(value string) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100020033,"name":"WithGeneration","signature":"func (b *StatefulSetApplyConfiguration) WithGeneration(value int64) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulset.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithGeneration(value int64) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100020034,"name":"WithCreationTimestamp","signature":"func (b *StatefulSetApplyConfiguration) WithCreationTimestamp(value metav1.Time) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulset.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithCreationTimestamp(value metav1.Time) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100020035,"name":"WithDeletionTimestamp","signature":"func (b *StatefulSetApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulset.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100020036,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *StatefulSetApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulset.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100020037,"name":"WithLabels","signature":"func (b *StatefulSetApplyConfiguration) WithLabels(entries map[string]string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulset.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *StatefulSetApplyConfiguration) WithLabels(entries map[string]string) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100020038,"name":"WithAnnotations","signature":"func (b *StatefulSetApplyConfiguration) WithAnnotations(entries map[string]string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulset.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *StatefulSetApplyConfiguration) WithAnnotations(entries map[string]string) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100020039,"name":"WithOwnerReferences","signature":"func (b *StatefulSetApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulset.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *StatefulSetApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100020040,"name":"WithFinalizers","signature":"func (b *StatefulSetApplyConfiguration) WithFinalizers(values ...string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulset.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *StatefulSetApplyConfiguration) WithFinalizers(values ...string) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100020041,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *StatefulSetApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulset.go","code":"func (b *StatefulSetApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100020042,"name":"WithSpec","signature":"func (b *StatefulSetApplyConfiguration) WithSpec(value *StatefulSetSpecApplyConfiguration) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulset.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithSpec(value *StatefulSetSpecApplyConfiguration) *StatefulSetApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100020043,"name":"WithStatus","signature":"func (b *StatefulSetApplyConfiguration) WithStatus(value *StatefulSetStatusApplyConfiguration) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulset.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithStatus(value *StatefulSetStatusApplyConfiguration) *StatefulSetApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100020044,"name":"StatefulSetCondition","signature":"func StatefulSetCondition() *StatefulSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetcondition.go","code":"// StatefulSetConditionApplyConfiguration constructs an declarative configuration of the StatefulSetCondition type for use with\n// apply.\nfunc StatefulSetCondition() *StatefulSetConditionApplyConfiguration {\n\treturn \u0026StatefulSetConditionApplyConfiguration{}\n}","line":{"from":37,"to":41}} {"id":100020045,"name":"WithType","signature":"func (b *StatefulSetConditionApplyConfiguration) WithType(value v1.StatefulSetConditionType) *StatefulSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetcondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *StatefulSetConditionApplyConfiguration) WithType(value v1.StatefulSetConditionType) *StatefulSetConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100020046,"name":"WithStatus","signature":"func (b *StatefulSetConditionApplyConfiguration) WithStatus(value corev1.ConditionStatus) *StatefulSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetcondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *StatefulSetConditionApplyConfiguration) WithStatus(value corev1.ConditionStatus) *StatefulSetConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100020047,"name":"WithLastTransitionTime","signature":"func (b *StatefulSetConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *StatefulSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetcondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *StatefulSetConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *StatefulSetConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":59,"to":65}} {"id":100020048,"name":"WithReason","signature":"func (b *StatefulSetConditionApplyConfiguration) WithReason(value string) *StatefulSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetcondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *StatefulSetConditionApplyConfiguration) WithReason(value string) *StatefulSetConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100020049,"name":"WithMessage","signature":"func (b *StatefulSetConditionApplyConfiguration) WithMessage(value string) *StatefulSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetcondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *StatefulSetConditionApplyConfiguration) WithMessage(value string) *StatefulSetConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":75,"to":81}} {"id":100020050,"name":"StatefulSetOrdinals","signature":"func StatefulSetOrdinals() *StatefulSetOrdinalsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetordinals.go","code":"// StatefulSetOrdinalsApplyConfiguration constructs an declarative configuration of the StatefulSetOrdinals type for use with\n// apply.\nfunc StatefulSetOrdinals() *StatefulSetOrdinalsApplyConfiguration {\n\treturn \u0026StatefulSetOrdinalsApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100020051,"name":"WithStart","signature":"func (b *StatefulSetOrdinalsApplyConfiguration) WithStart(value int32) *StatefulSetOrdinalsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetordinals.go","code":"// WithStart sets the Start field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Start field is set to the value of the last call.\nfunc (b *StatefulSetOrdinalsApplyConfiguration) WithStart(value int32) *StatefulSetOrdinalsApplyConfiguration {\n\tb.Start = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100020052,"name":"StatefulSetPersistentVolumeClaimRetentionPolicy","signature":"func StatefulSetPersistentVolumeClaimRetentionPolicy() *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetpersistentvolumeclaimretentionpolicy.go","code":"// StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration constructs an declarative configuration of the StatefulSetPersistentVolumeClaimRetentionPolicy type for use with\n// apply.\nfunc StatefulSetPersistentVolumeClaimRetentionPolicy() *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration {\n\treturn \u0026StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100020053,"name":"WithWhenDeleted","signature":"func (b *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration) WithWhenDeleted(value v1.PersistentVolumeClaimRetentionPolicyType) *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetpersistentvolumeclaimretentionpolicy.go","code":"// WithWhenDeleted sets the WhenDeleted field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the WhenDeleted field is set to the value of the last call.\nfunc (b *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration) WithWhenDeleted(value v1.PersistentVolumeClaimRetentionPolicyType) *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration {\n\tb.WhenDeleted = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100020054,"name":"WithWhenScaled","signature":"func (b *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration) WithWhenScaled(value v1.PersistentVolumeClaimRetentionPolicyType) *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetpersistentvolumeclaimretentionpolicy.go","code":"// WithWhenScaled sets the WhenScaled field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the WhenScaled field is set to the value of the last call.\nfunc (b *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration) WithWhenScaled(value v1.PersistentVolumeClaimRetentionPolicyType) *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration {\n\tb.WhenScaled = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100020055,"name":"StatefulSetSpec","signature":"func StatefulSetSpec() *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetspec.go","code":"// StatefulSetSpecApplyConfiguration constructs an declarative configuration of the StatefulSetSpec type for use with\n// apply.\nfunc StatefulSetSpec() *StatefulSetSpecApplyConfiguration {\n\treturn \u0026StatefulSetSpecApplyConfiguration{}\n}","line":{"from":43,"to":47}} {"id":100020056,"name":"WithReplicas","signature":"func (b *StatefulSetSpecApplyConfiguration) WithReplicas(value int32) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetspec.go","code":"// WithReplicas sets the Replicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Replicas field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithReplicas(value int32) *StatefulSetSpecApplyConfiguration {\n\tb.Replicas = \u0026value\n\treturn b\n}","line":{"from":49,"to":55}} {"id":100020057,"name":"WithSelector","signature":"func (b *StatefulSetSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetspec.go","code":"// WithSelector sets the Selector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Selector field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *StatefulSetSpecApplyConfiguration {\n\tb.Selector = value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100020058,"name":"WithTemplate","signature":"func (b *StatefulSetSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetspec.go","code":"// WithTemplate sets the Template field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Template field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *StatefulSetSpecApplyConfiguration {\n\tb.Template = value\n\treturn b\n}","line":{"from":65,"to":71}} {"id":100020059,"name":"WithVolumeClaimTemplates","signature":"func (b *StatefulSetSpecApplyConfiguration) WithVolumeClaimTemplates(values ...*corev1.PersistentVolumeClaimApplyConfiguration) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetspec.go","code":"// WithVolumeClaimTemplates adds the given value to the VolumeClaimTemplates field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the VolumeClaimTemplates field.\nfunc (b *StatefulSetSpecApplyConfiguration) WithVolumeClaimTemplates(values ...*corev1.PersistentVolumeClaimApplyConfiguration) *StatefulSetSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithVolumeClaimTemplates\")\n\t\t}\n\t\tb.VolumeClaimTemplates = append(b.VolumeClaimTemplates, *values[i])\n\t}\n\treturn b\n}","line":{"from":73,"to":84}} {"id":100020060,"name":"WithServiceName","signature":"func (b *StatefulSetSpecApplyConfiguration) WithServiceName(value string) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetspec.go","code":"// WithServiceName sets the ServiceName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ServiceName field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithServiceName(value string) *StatefulSetSpecApplyConfiguration {\n\tb.ServiceName = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100020061,"name":"WithPodManagementPolicy","signature":"func (b *StatefulSetSpecApplyConfiguration) WithPodManagementPolicy(value appsv1.PodManagementPolicyType) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetspec.go","code":"// WithPodManagementPolicy sets the PodManagementPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PodManagementPolicy field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithPodManagementPolicy(value appsv1.PodManagementPolicyType) *StatefulSetSpecApplyConfiguration {\n\tb.PodManagementPolicy = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100020062,"name":"WithUpdateStrategy","signature":"func (b *StatefulSetSpecApplyConfiguration) WithUpdateStrategy(value *StatefulSetUpdateStrategyApplyConfiguration) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetspec.go","code":"// WithUpdateStrategy sets the UpdateStrategy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UpdateStrategy field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithUpdateStrategy(value *StatefulSetUpdateStrategyApplyConfiguration) *StatefulSetSpecApplyConfiguration {\n\tb.UpdateStrategy = value\n\treturn b\n}","line":{"from":102,"to":108}} {"id":100020063,"name":"WithRevisionHistoryLimit","signature":"func (b *StatefulSetSpecApplyConfiguration) WithRevisionHistoryLimit(value int32) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetspec.go","code":"// WithRevisionHistoryLimit sets the RevisionHistoryLimit field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RevisionHistoryLimit field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithRevisionHistoryLimit(value int32) *StatefulSetSpecApplyConfiguration {\n\tb.RevisionHistoryLimit = \u0026value\n\treturn b\n}","line":{"from":110,"to":116}} {"id":100020064,"name":"WithMinReadySeconds","signature":"func (b *StatefulSetSpecApplyConfiguration) WithMinReadySeconds(value int32) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetspec.go","code":"// WithMinReadySeconds sets the MinReadySeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MinReadySeconds field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithMinReadySeconds(value int32) *StatefulSetSpecApplyConfiguration {\n\tb.MinReadySeconds = \u0026value\n\treturn b\n}","line":{"from":118,"to":124}} {"id":100020065,"name":"WithPersistentVolumeClaimRetentionPolicy","signature":"func (b *StatefulSetSpecApplyConfiguration) WithPersistentVolumeClaimRetentionPolicy(value *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetspec.go","code":"// WithPersistentVolumeClaimRetentionPolicy sets the PersistentVolumeClaimRetentionPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PersistentVolumeClaimRetentionPolicy field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithPersistentVolumeClaimRetentionPolicy(value *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration) *StatefulSetSpecApplyConfiguration {\n\tb.PersistentVolumeClaimRetentionPolicy = value\n\treturn b\n}","line":{"from":126,"to":132}} {"id":100020066,"name":"WithOrdinals","signature":"func (b *StatefulSetSpecApplyConfiguration) WithOrdinals(value *StatefulSetOrdinalsApplyConfiguration) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetspec.go","code":"// WithOrdinals sets the Ordinals field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Ordinals field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithOrdinals(value *StatefulSetOrdinalsApplyConfiguration) *StatefulSetSpecApplyConfiguration {\n\tb.Ordinals = value\n\treturn b\n}","line":{"from":134,"to":140}} {"id":100020067,"name":"StatefulSetStatus","signature":"func StatefulSetStatus() *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetstatus.go","code":"// StatefulSetStatusApplyConfiguration constructs an declarative configuration of the StatefulSetStatus type for use with\n// apply.\nfunc StatefulSetStatus() *StatefulSetStatusApplyConfiguration {\n\treturn \u0026StatefulSetStatusApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100020068,"name":"WithObservedGeneration","signature":"func (b *StatefulSetStatusApplyConfiguration) WithObservedGeneration(value int64) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetstatus.go","code":"// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObservedGeneration field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithObservedGeneration(value int64) *StatefulSetStatusApplyConfiguration {\n\tb.ObservedGeneration = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020069,"name":"WithReplicas","signature":"func (b *StatefulSetStatusApplyConfiguration) WithReplicas(value int32) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetstatus.go","code":"// WithReplicas sets the Replicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Replicas field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithReplicas(value int32) *StatefulSetStatusApplyConfiguration {\n\tb.Replicas = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100020070,"name":"WithReadyReplicas","signature":"func (b *StatefulSetStatusApplyConfiguration) WithReadyReplicas(value int32) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetstatus.go","code":"// WithReadyReplicas sets the ReadyReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadyReplicas field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithReadyReplicas(value int32) *StatefulSetStatusApplyConfiguration {\n\tb.ReadyReplicas = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100020071,"name":"WithCurrentReplicas","signature":"func (b *StatefulSetStatusApplyConfiguration) WithCurrentReplicas(value int32) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetstatus.go","code":"// WithCurrentReplicas sets the CurrentReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CurrentReplicas field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithCurrentReplicas(value int32) *StatefulSetStatusApplyConfiguration {\n\tb.CurrentReplicas = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100020072,"name":"WithUpdatedReplicas","signature":"func (b *StatefulSetStatusApplyConfiguration) WithUpdatedReplicas(value int32) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetstatus.go","code":"// WithUpdatedReplicas sets the UpdatedReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UpdatedReplicas field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithUpdatedReplicas(value int32) *StatefulSetStatusApplyConfiguration {\n\tb.UpdatedReplicas = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100020073,"name":"WithCurrentRevision","signature":"func (b *StatefulSetStatusApplyConfiguration) WithCurrentRevision(value string) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetstatus.go","code":"// WithCurrentRevision sets the CurrentRevision field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CurrentRevision field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithCurrentRevision(value string) *StatefulSetStatusApplyConfiguration {\n\tb.CurrentRevision = \u0026value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100020074,"name":"WithUpdateRevision","signature":"func (b *StatefulSetStatusApplyConfiguration) WithUpdateRevision(value string) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetstatus.go","code":"// WithUpdateRevision sets the UpdateRevision field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UpdateRevision field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithUpdateRevision(value string) *StatefulSetStatusApplyConfiguration {\n\tb.UpdateRevision = \u0026value\n\treturn b\n}","line":{"from":90,"to":96}} {"id":100020075,"name":"WithCollisionCount","signature":"func (b *StatefulSetStatusApplyConfiguration) WithCollisionCount(value int32) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetstatus.go","code":"// WithCollisionCount sets the CollisionCount field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CollisionCount field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithCollisionCount(value int32) *StatefulSetStatusApplyConfiguration {\n\tb.CollisionCount = \u0026value\n\treturn b\n}","line":{"from":98,"to":104}} {"id":100020076,"name":"WithConditions","signature":"func (b *StatefulSetStatusApplyConfiguration) WithConditions(values ...*StatefulSetConditionApplyConfiguration) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *StatefulSetStatusApplyConfiguration) WithConditions(values ...*StatefulSetConditionApplyConfiguration) *StatefulSetStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":106,"to":117}} {"id":100020077,"name":"WithAvailableReplicas","signature":"func (b *StatefulSetStatusApplyConfiguration) WithAvailableReplicas(value int32) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1/statefulsetstatus.go","code":"// WithAvailableReplicas sets the AvailableReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AvailableReplicas field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithAvailableReplicas(value int32) *StatefulSetStatusApplyConfiguration {\n\tb.AvailableReplicas = \u0026value\n\treturn b\n}","line":{"from":119,"to":125}} {"id":100020078,"name":"ControllerRevision","signature":"func ControllerRevision(name, namespace string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/controllerrevision.go","code":"// ControllerRevision constructs an declarative configuration of the ControllerRevision type for use with\n// apply.\nfunc ControllerRevision(name, namespace string) *ControllerRevisionApplyConfiguration {\n\tb := \u0026ControllerRevisionApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"ControllerRevision\")\n\tb.WithAPIVersion(\"apps/v1beta1\")\n\treturn b\n}","line":{"from":40,"to":49}} {"id":100020079,"name":"ExtractControllerRevision","signature":"func ExtractControllerRevision(controllerRevision *v1beta1.ControllerRevision, fieldManager string) (*ControllerRevisionApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/controllerrevision.go","code":"// ExtractControllerRevision extracts the applied configuration owned by fieldManager from\n// controllerRevision. If no managedFields are found in controllerRevision for fieldManager, a\n// ControllerRevisionApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// controllerRevision must be a unmodified ControllerRevision API object that was retrieved from the Kubernetes API.\n// ExtractControllerRevision provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractControllerRevision(controllerRevision *v1beta1.ControllerRevision, fieldManager string) (*ControllerRevisionApplyConfiguration, error) {\n\treturn extractControllerRevision(controllerRevision, fieldManager, \"\")\n}","line":{"from":51,"to":64}} {"id":100020080,"name":"ExtractControllerRevisionStatus","signature":"func ExtractControllerRevisionStatus(controllerRevision *v1beta1.ControllerRevision, fieldManager string) (*ControllerRevisionApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/controllerrevision.go","code":"// ExtractControllerRevisionStatus is the same as ExtractControllerRevision except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractControllerRevisionStatus(controllerRevision *v1beta1.ControllerRevision, fieldManager string) (*ControllerRevisionApplyConfiguration, error) {\n\treturn extractControllerRevision(controllerRevision, fieldManager, \"status\")\n}","line":{"from":66,"to":71}} {"id":100020081,"name":"extractControllerRevision","signature":"func extractControllerRevision(controllerRevision *v1beta1.ControllerRevision, fieldManager string, subresource string) (*ControllerRevisionApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/controllerrevision.go","code":"func extractControllerRevision(controllerRevision *v1beta1.ControllerRevision, fieldManager string, subresource string) (*ControllerRevisionApplyConfiguration, error) {\n\tb := \u0026ControllerRevisionApplyConfiguration{}\n\terr := managedfields.ExtractInto(controllerRevision, internal.Parser().Type(\"io.k8s.api.apps.v1beta1.ControllerRevision\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(controllerRevision.Name)\n\tb.WithNamespace(controllerRevision.Namespace)\n\n\tb.WithKind(\"ControllerRevision\")\n\tb.WithAPIVersion(\"apps/v1beta1\")\n\treturn b, nil\n}","line":{"from":73,"to":85}} {"id":100020082,"name":"WithKind","signature":"func (b *ControllerRevisionApplyConfiguration) WithKind(value string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/controllerrevision.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithKind(value string) *ControllerRevisionApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":87,"to":93}} {"id":100020083,"name":"WithAPIVersion","signature":"func (b *ControllerRevisionApplyConfiguration) WithAPIVersion(value string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/controllerrevision.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithAPIVersion(value string) *ControllerRevisionApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":95,"to":101}} {"id":100020084,"name":"WithName","signature":"func (b *ControllerRevisionApplyConfiguration) WithName(value string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/controllerrevision.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithName(value string) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":103,"to":110}} {"id":100020085,"name":"WithGenerateName","signature":"func (b *ControllerRevisionApplyConfiguration) WithGenerateName(value string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/controllerrevision.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithGenerateName(value string) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":112,"to":119}} {"id":100020086,"name":"WithNamespace","signature":"func (b *ControllerRevisionApplyConfiguration) WithNamespace(value string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/controllerrevision.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithNamespace(value string) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":121,"to":128}} {"id":100020087,"name":"WithUID","signature":"func (b *ControllerRevisionApplyConfiguration) WithUID(value types.UID) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/controllerrevision.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithUID(value types.UID) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":130,"to":137}} {"id":100020088,"name":"WithResourceVersion","signature":"func (b *ControllerRevisionApplyConfiguration) WithResourceVersion(value string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/controllerrevision.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithResourceVersion(value string) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":139,"to":146}} {"id":100020089,"name":"WithGeneration","signature":"func (b *ControllerRevisionApplyConfiguration) WithGeneration(value int64) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/controllerrevision.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithGeneration(value int64) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":148,"to":155}} {"id":100020090,"name":"WithCreationTimestamp","signature":"func (b *ControllerRevisionApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/controllerrevision.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":157,"to":164}} {"id":100020091,"name":"WithDeletionTimestamp","signature":"func (b *ControllerRevisionApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/controllerrevision.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":166,"to":173}} {"id":100020092,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ControllerRevisionApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/controllerrevision.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":175,"to":182}} {"id":100020093,"name":"WithLabels","signature":"func (b *ControllerRevisionApplyConfiguration) WithLabels(entries map[string]string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/controllerrevision.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ControllerRevisionApplyConfiguration) WithLabels(entries map[string]string) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":184,"to":197}} {"id":100020094,"name":"WithAnnotations","signature":"func (b *ControllerRevisionApplyConfiguration) WithAnnotations(entries map[string]string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/controllerrevision.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ControllerRevisionApplyConfiguration) WithAnnotations(entries map[string]string) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":199,"to":212}} {"id":100020095,"name":"WithOwnerReferences","signature":"func (b *ControllerRevisionApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/controllerrevision.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ControllerRevisionApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":214,"to":226}} {"id":100020096,"name":"WithFinalizers","signature":"func (b *ControllerRevisionApplyConfiguration) WithFinalizers(values ...string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/controllerrevision.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ControllerRevisionApplyConfiguration) WithFinalizers(values ...string) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":228,"to":237}} {"id":100020097,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ControllerRevisionApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/controllerrevision.go","code":"func (b *ControllerRevisionApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":239,"to":243}} {"id":100020098,"name":"WithData","signature":"func (b *ControllerRevisionApplyConfiguration) WithData(value runtime.RawExtension) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/controllerrevision.go","code":"// WithData sets the Data field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Data field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithData(value runtime.RawExtension) *ControllerRevisionApplyConfiguration {\n\tb.Data = \u0026value\n\treturn b\n}","line":{"from":245,"to":251}} {"id":100020099,"name":"WithRevision","signature":"func (b *ControllerRevisionApplyConfiguration) WithRevision(value int64) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/controllerrevision.go","code":"// WithRevision sets the Revision field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Revision field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithRevision(value int64) *ControllerRevisionApplyConfiguration {\n\tb.Revision = \u0026value\n\treturn b\n}","line":{"from":253,"to":259}} {"id":100020100,"name":"Deployment","signature":"func Deployment(name, namespace string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deployment.go","code":"// Deployment constructs an declarative configuration of the Deployment type for use with\n// apply.\nfunc Deployment(name, namespace string) *DeploymentApplyConfiguration {\n\tb := \u0026DeploymentApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"Deployment\")\n\tb.WithAPIVersion(\"apps/v1beta1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100020101,"name":"ExtractDeployment","signature":"func ExtractDeployment(deployment *appsv1beta1.Deployment, fieldManager string) (*DeploymentApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deployment.go","code":"// ExtractDeployment extracts the applied configuration owned by fieldManager from\n// deployment. If no managedFields are found in deployment for fieldManager, a\n// DeploymentApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// deployment must be a unmodified Deployment API object that was retrieved from the Kubernetes API.\n// ExtractDeployment provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractDeployment(deployment *appsv1beta1.Deployment, fieldManager string) (*DeploymentApplyConfiguration, error) {\n\treturn extractDeployment(deployment, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100020102,"name":"ExtractDeploymentStatus","signature":"func ExtractDeploymentStatus(deployment *appsv1beta1.Deployment, fieldManager string) (*DeploymentApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deployment.go","code":"// ExtractDeploymentStatus is the same as ExtractDeployment except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractDeploymentStatus(deployment *appsv1beta1.Deployment, fieldManager string) (*DeploymentApplyConfiguration, error) {\n\treturn extractDeployment(deployment, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100020103,"name":"extractDeployment","signature":"func extractDeployment(deployment *appsv1beta1.Deployment, fieldManager string, subresource string) (*DeploymentApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deployment.go","code":"func extractDeployment(deployment *appsv1beta1.Deployment, fieldManager string, subresource string) (*DeploymentApplyConfiguration, error) {\n\tb := \u0026DeploymentApplyConfiguration{}\n\terr := managedfields.ExtractInto(deployment, internal.Parser().Type(\"io.k8s.api.apps.v1beta1.Deployment\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(deployment.Name)\n\tb.WithNamespace(deployment.Namespace)\n\n\tb.WithKind(\"Deployment\")\n\tb.WithAPIVersion(\"apps/v1beta1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100020104,"name":"WithKind","signature":"func (b *DeploymentApplyConfiguration) WithKind(value string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deployment.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithKind(value string) *DeploymentApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100020105,"name":"WithAPIVersion","signature":"func (b *DeploymentApplyConfiguration) WithAPIVersion(value string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deployment.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithAPIVersion(value string) *DeploymentApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100020106,"name":"WithName","signature":"func (b *DeploymentApplyConfiguration) WithName(value string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deployment.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithName(value string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100020107,"name":"WithGenerateName","signature":"func (b *DeploymentApplyConfiguration) WithGenerateName(value string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deployment.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithGenerateName(value string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100020108,"name":"WithNamespace","signature":"func (b *DeploymentApplyConfiguration) WithNamespace(value string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deployment.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithNamespace(value string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100020109,"name":"WithUID","signature":"func (b *DeploymentApplyConfiguration) WithUID(value types.UID) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deployment.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithUID(value types.UID) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100020110,"name":"WithResourceVersion","signature":"func (b *DeploymentApplyConfiguration) WithResourceVersion(value string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deployment.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithResourceVersion(value string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100020111,"name":"WithGeneration","signature":"func (b *DeploymentApplyConfiguration) WithGeneration(value int64) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deployment.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithGeneration(value int64) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100020112,"name":"WithCreationTimestamp","signature":"func (b *DeploymentApplyConfiguration) WithCreationTimestamp(value metav1.Time) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deployment.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithCreationTimestamp(value metav1.Time) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100020113,"name":"WithDeletionTimestamp","signature":"func (b *DeploymentApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deployment.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100020114,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *DeploymentApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deployment.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100020115,"name":"WithLabels","signature":"func (b *DeploymentApplyConfiguration) WithLabels(entries map[string]string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deployment.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *DeploymentApplyConfiguration) WithLabels(entries map[string]string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100020116,"name":"WithAnnotations","signature":"func (b *DeploymentApplyConfiguration) WithAnnotations(entries map[string]string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deployment.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *DeploymentApplyConfiguration) WithAnnotations(entries map[string]string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100020117,"name":"WithOwnerReferences","signature":"func (b *DeploymentApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deployment.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *DeploymentApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100020118,"name":"WithFinalizers","signature":"func (b *DeploymentApplyConfiguration) WithFinalizers(values ...string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deployment.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *DeploymentApplyConfiguration) WithFinalizers(values ...string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100020119,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *DeploymentApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deployment.go","code":"func (b *DeploymentApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100020120,"name":"WithSpec","signature":"func (b *DeploymentApplyConfiguration) WithSpec(value *DeploymentSpecApplyConfiguration) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deployment.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithSpec(value *DeploymentSpecApplyConfiguration) *DeploymentApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100020121,"name":"WithStatus","signature":"func (b *DeploymentApplyConfiguration) WithStatus(value *DeploymentStatusApplyConfiguration) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deployment.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithStatus(value *DeploymentStatusApplyConfiguration) *DeploymentApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100020122,"name":"DeploymentCondition","signature":"func DeploymentCondition() *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentcondition.go","code":"// DeploymentConditionApplyConfiguration constructs an declarative configuration of the DeploymentCondition type for use with\n// apply.\nfunc DeploymentCondition() *DeploymentConditionApplyConfiguration {\n\treturn \u0026DeploymentConditionApplyConfiguration{}\n}","line":{"from":38,"to":42}} {"id":100020123,"name":"WithType","signature":"func (b *DeploymentConditionApplyConfiguration) WithType(value v1beta1.DeploymentConditionType) *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentcondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *DeploymentConditionApplyConfiguration) WithType(value v1beta1.DeploymentConditionType) *DeploymentConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100020124,"name":"WithStatus","signature":"func (b *DeploymentConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentcondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *DeploymentConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *DeploymentConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100020125,"name":"WithLastUpdateTime","signature":"func (b *DeploymentConditionApplyConfiguration) WithLastUpdateTime(value metav1.Time) *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentcondition.go","code":"// WithLastUpdateTime sets the LastUpdateTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastUpdateTime field is set to the value of the last call.\nfunc (b *DeploymentConditionApplyConfiguration) WithLastUpdateTime(value metav1.Time) *DeploymentConditionApplyConfiguration {\n\tb.LastUpdateTime = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100020126,"name":"WithLastTransitionTime","signature":"func (b *DeploymentConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentcondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *DeploymentConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *DeploymentConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":68,"to":74}} {"id":100020127,"name":"WithReason","signature":"func (b *DeploymentConditionApplyConfiguration) WithReason(value string) *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentcondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *DeploymentConditionApplyConfiguration) WithReason(value string) *DeploymentConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":76,"to":82}} {"id":100020128,"name":"WithMessage","signature":"func (b *DeploymentConditionApplyConfiguration) WithMessage(value string) *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentcondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *DeploymentConditionApplyConfiguration) WithMessage(value string) *DeploymentConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100020129,"name":"DeploymentSpec","signature":"func DeploymentSpec() *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentspec.go","code":"// DeploymentSpecApplyConfiguration constructs an declarative configuration of the DeploymentSpec type for use with\n// apply.\nfunc DeploymentSpec() *DeploymentSpecApplyConfiguration {\n\treturn \u0026DeploymentSpecApplyConfiguration{}\n}","line":{"from":40,"to":44}} {"id":100020130,"name":"WithReplicas","signature":"func (b *DeploymentSpecApplyConfiguration) WithReplicas(value int32) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentspec.go","code":"// WithReplicas sets the Replicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Replicas field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithReplicas(value int32) *DeploymentSpecApplyConfiguration {\n\tb.Replicas = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100020131,"name":"WithSelector","signature":"func (b *DeploymentSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentspec.go","code":"// WithSelector sets the Selector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Selector field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *DeploymentSpecApplyConfiguration {\n\tb.Selector = value\n\treturn b\n}","line":{"from":54,"to":60}} {"id":100020132,"name":"WithTemplate","signature":"func (b *DeploymentSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentspec.go","code":"// WithTemplate sets the Template field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Template field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *DeploymentSpecApplyConfiguration {\n\tb.Template = value\n\treturn b\n}","line":{"from":62,"to":68}} {"id":100020133,"name":"WithStrategy","signature":"func (b *DeploymentSpecApplyConfiguration) WithStrategy(value *DeploymentStrategyApplyConfiguration) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentspec.go","code":"// WithStrategy sets the Strategy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Strategy field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithStrategy(value *DeploymentStrategyApplyConfiguration) *DeploymentSpecApplyConfiguration {\n\tb.Strategy = value\n\treturn b\n}","line":{"from":70,"to":76}} {"id":100020134,"name":"WithMinReadySeconds","signature":"func (b *DeploymentSpecApplyConfiguration) WithMinReadySeconds(value int32) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentspec.go","code":"// WithMinReadySeconds sets the MinReadySeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MinReadySeconds field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithMinReadySeconds(value int32) *DeploymentSpecApplyConfiguration {\n\tb.MinReadySeconds = \u0026value\n\treturn b\n}","line":{"from":78,"to":84}} {"id":100020135,"name":"WithRevisionHistoryLimit","signature":"func (b *DeploymentSpecApplyConfiguration) WithRevisionHistoryLimit(value int32) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentspec.go","code":"// WithRevisionHistoryLimit sets the RevisionHistoryLimit field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RevisionHistoryLimit field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithRevisionHistoryLimit(value int32) *DeploymentSpecApplyConfiguration {\n\tb.RevisionHistoryLimit = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100020136,"name":"WithPaused","signature":"func (b *DeploymentSpecApplyConfiguration) WithPaused(value bool) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentspec.go","code":"// WithPaused sets the Paused field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Paused field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithPaused(value bool) *DeploymentSpecApplyConfiguration {\n\tb.Paused = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100020137,"name":"WithRollbackTo","signature":"func (b *DeploymentSpecApplyConfiguration) WithRollbackTo(value *RollbackConfigApplyConfiguration) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentspec.go","code":"// WithRollbackTo sets the RollbackTo field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RollbackTo field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithRollbackTo(value *RollbackConfigApplyConfiguration) *DeploymentSpecApplyConfiguration {\n\tb.RollbackTo = value\n\treturn b\n}","line":{"from":102,"to":108}} {"id":100020138,"name":"WithProgressDeadlineSeconds","signature":"func (b *DeploymentSpecApplyConfiguration) WithProgressDeadlineSeconds(value int32) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentspec.go","code":"// WithProgressDeadlineSeconds sets the ProgressDeadlineSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ProgressDeadlineSeconds field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithProgressDeadlineSeconds(value int32) *DeploymentSpecApplyConfiguration {\n\tb.ProgressDeadlineSeconds = \u0026value\n\treturn b\n}","line":{"from":110,"to":116}} {"id":100020139,"name":"DeploymentStatus","signature":"func DeploymentStatus() *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentstatus.go","code":"// DeploymentStatusApplyConfiguration constructs an declarative configuration of the DeploymentStatus type for use with\n// apply.\nfunc DeploymentStatus() *DeploymentStatusApplyConfiguration {\n\treturn \u0026DeploymentStatusApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100020140,"name":"WithObservedGeneration","signature":"func (b *DeploymentStatusApplyConfiguration) WithObservedGeneration(value int64) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentstatus.go","code":"// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObservedGeneration field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithObservedGeneration(value int64) *DeploymentStatusApplyConfiguration {\n\tb.ObservedGeneration = \u0026value\n\treturn b\n}","line":{"from":40,"to":46}} {"id":100020141,"name":"WithReplicas","signature":"func (b *DeploymentStatusApplyConfiguration) WithReplicas(value int32) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentstatus.go","code":"// WithReplicas sets the Replicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Replicas field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithReplicas(value int32) *DeploymentStatusApplyConfiguration {\n\tb.Replicas = \u0026value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100020142,"name":"WithUpdatedReplicas","signature":"func (b *DeploymentStatusApplyConfiguration) WithUpdatedReplicas(value int32) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentstatus.go","code":"// WithUpdatedReplicas sets the UpdatedReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UpdatedReplicas field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithUpdatedReplicas(value int32) *DeploymentStatusApplyConfiguration {\n\tb.UpdatedReplicas = \u0026value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100020143,"name":"WithReadyReplicas","signature":"func (b *DeploymentStatusApplyConfiguration) WithReadyReplicas(value int32) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentstatus.go","code":"// WithReadyReplicas sets the ReadyReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadyReplicas field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithReadyReplicas(value int32) *DeploymentStatusApplyConfiguration {\n\tb.ReadyReplicas = \u0026value\n\treturn b\n}","line":{"from":64,"to":70}} {"id":100020144,"name":"WithAvailableReplicas","signature":"func (b *DeploymentStatusApplyConfiguration) WithAvailableReplicas(value int32) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentstatus.go","code":"// WithAvailableReplicas sets the AvailableReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AvailableReplicas field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithAvailableReplicas(value int32) *DeploymentStatusApplyConfiguration {\n\tb.AvailableReplicas = \u0026value\n\treturn b\n}","line":{"from":72,"to":78}} {"id":100020145,"name":"WithUnavailableReplicas","signature":"func (b *DeploymentStatusApplyConfiguration) WithUnavailableReplicas(value int32) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentstatus.go","code":"// WithUnavailableReplicas sets the UnavailableReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UnavailableReplicas field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithUnavailableReplicas(value int32) *DeploymentStatusApplyConfiguration {\n\tb.UnavailableReplicas = \u0026value\n\treturn b\n}","line":{"from":80,"to":86}} {"id":100020146,"name":"WithConditions","signature":"func (b *DeploymentStatusApplyConfiguration) WithConditions(values ...*DeploymentConditionApplyConfiguration) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *DeploymentStatusApplyConfiguration) WithConditions(values ...*DeploymentConditionApplyConfiguration) *DeploymentStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":88,"to":99}} {"id":100020147,"name":"WithCollisionCount","signature":"func (b *DeploymentStatusApplyConfiguration) WithCollisionCount(value int32) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentstatus.go","code":"// WithCollisionCount sets the CollisionCount field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CollisionCount field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithCollisionCount(value int32) *DeploymentStatusApplyConfiguration {\n\tb.CollisionCount = \u0026value\n\treturn b\n}","line":{"from":101,"to":107}} {"id":100020148,"name":"DeploymentStrategy","signature":"func DeploymentStrategy() *DeploymentStrategyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentstrategy.go","code":"// DeploymentStrategyApplyConfiguration constructs an declarative configuration of the DeploymentStrategy type for use with\n// apply.\nfunc DeploymentStrategy() *DeploymentStrategyApplyConfiguration {\n\treturn \u0026DeploymentStrategyApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100020149,"name":"WithType","signature":"func (b *DeploymentStrategyApplyConfiguration) WithType(value v1beta1.DeploymentStrategyType) *DeploymentStrategyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentstrategy.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *DeploymentStrategyApplyConfiguration) WithType(value v1beta1.DeploymentStrategyType) *DeploymentStrategyApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100020150,"name":"WithRollingUpdate","signature":"func (b *DeploymentStrategyApplyConfiguration) WithRollingUpdate(value *RollingUpdateDeploymentApplyConfiguration) *DeploymentStrategyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/deploymentstrategy.go","code":"// WithRollingUpdate sets the RollingUpdate field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RollingUpdate field is set to the value of the last call.\nfunc (b *DeploymentStrategyApplyConfiguration) WithRollingUpdate(value *RollingUpdateDeploymentApplyConfiguration) *DeploymentStrategyApplyConfiguration {\n\tb.RollingUpdate = value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100020151,"name":"RollbackConfig","signature":"func RollbackConfig() *RollbackConfigApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/rollbackconfig.go","code":"// RollbackConfigApplyConfiguration constructs an declarative configuration of the RollbackConfig type for use with\n// apply.\nfunc RollbackConfig() *RollbackConfigApplyConfiguration {\n\treturn \u0026RollbackConfigApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100020152,"name":"WithRevision","signature":"func (b *RollbackConfigApplyConfiguration) WithRevision(value int64) *RollbackConfigApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/rollbackconfig.go","code":"// WithRevision sets the Revision field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Revision field is set to the value of the last call.\nfunc (b *RollbackConfigApplyConfiguration) WithRevision(value int64) *RollbackConfigApplyConfiguration {\n\tb.Revision = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100020153,"name":"RollingUpdateDeployment","signature":"func RollingUpdateDeployment() *RollingUpdateDeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/rollingupdatedeployment.go","code":"// RollingUpdateDeploymentApplyConfiguration constructs an declarative configuration of the RollingUpdateDeployment type for use with\n// apply.\nfunc RollingUpdateDeployment() *RollingUpdateDeploymentApplyConfiguration {\n\treturn \u0026RollingUpdateDeploymentApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100020154,"name":"WithMaxUnavailable","signature":"func (b *RollingUpdateDeploymentApplyConfiguration) WithMaxUnavailable(value intstr.IntOrString) *RollingUpdateDeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/rollingupdatedeployment.go","code":"// WithMaxUnavailable sets the MaxUnavailable field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MaxUnavailable field is set to the value of the last call.\nfunc (b *RollingUpdateDeploymentApplyConfiguration) WithMaxUnavailable(value intstr.IntOrString) *RollingUpdateDeploymentApplyConfiguration {\n\tb.MaxUnavailable = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100020155,"name":"WithMaxSurge","signature":"func (b *RollingUpdateDeploymentApplyConfiguration) WithMaxSurge(value intstr.IntOrString) *RollingUpdateDeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/rollingupdatedeployment.go","code":"// WithMaxSurge sets the MaxSurge field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MaxSurge field is set to the value of the last call.\nfunc (b *RollingUpdateDeploymentApplyConfiguration) WithMaxSurge(value intstr.IntOrString) *RollingUpdateDeploymentApplyConfiguration {\n\tb.MaxSurge = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100020156,"name":"StatefulSet","signature":"func StatefulSet(name, namespace string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulset.go","code":"// StatefulSet constructs an declarative configuration of the StatefulSet type for use with\n// apply.\nfunc StatefulSet(name, namespace string) *StatefulSetApplyConfiguration {\n\tb := \u0026StatefulSetApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"StatefulSet\")\n\tb.WithAPIVersion(\"apps/v1beta1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100020157,"name":"ExtractStatefulSet","signature":"func ExtractStatefulSet(statefulSet *appsv1beta1.StatefulSet, fieldManager string) (*StatefulSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulset.go","code":"// ExtractStatefulSet extracts the applied configuration owned by fieldManager from\n// statefulSet. If no managedFields are found in statefulSet for fieldManager, a\n// StatefulSetApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// statefulSet must be a unmodified StatefulSet API object that was retrieved from the Kubernetes API.\n// ExtractStatefulSet provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractStatefulSet(statefulSet *appsv1beta1.StatefulSet, fieldManager string) (*StatefulSetApplyConfiguration, error) {\n\treturn extractStatefulSet(statefulSet, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100020158,"name":"ExtractStatefulSetStatus","signature":"func ExtractStatefulSetStatus(statefulSet *appsv1beta1.StatefulSet, fieldManager string) (*StatefulSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulset.go","code":"// ExtractStatefulSetStatus is the same as ExtractStatefulSet except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractStatefulSetStatus(statefulSet *appsv1beta1.StatefulSet, fieldManager string) (*StatefulSetApplyConfiguration, error) {\n\treturn extractStatefulSet(statefulSet, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100020159,"name":"extractStatefulSet","signature":"func extractStatefulSet(statefulSet *appsv1beta1.StatefulSet, fieldManager string, subresource string) (*StatefulSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulset.go","code":"func extractStatefulSet(statefulSet *appsv1beta1.StatefulSet, fieldManager string, subresource string) (*StatefulSetApplyConfiguration, error) {\n\tb := \u0026StatefulSetApplyConfiguration{}\n\terr := managedfields.ExtractInto(statefulSet, internal.Parser().Type(\"io.k8s.api.apps.v1beta1.StatefulSet\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(statefulSet.Name)\n\tb.WithNamespace(statefulSet.Namespace)\n\n\tb.WithKind(\"StatefulSet\")\n\tb.WithAPIVersion(\"apps/v1beta1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100020160,"name":"WithKind","signature":"func (b *StatefulSetApplyConfiguration) WithKind(value string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulset.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithKind(value string) *StatefulSetApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100020161,"name":"WithAPIVersion","signature":"func (b *StatefulSetApplyConfiguration) WithAPIVersion(value string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulset.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithAPIVersion(value string) *StatefulSetApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100020162,"name":"WithName","signature":"func (b *StatefulSetApplyConfiguration) WithName(value string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulset.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithName(value string) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100020163,"name":"WithGenerateName","signature":"func (b *StatefulSetApplyConfiguration) WithGenerateName(value string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulset.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithGenerateName(value string) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100020164,"name":"WithNamespace","signature":"func (b *StatefulSetApplyConfiguration) WithNamespace(value string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulset.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithNamespace(value string) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100020165,"name":"WithUID","signature":"func (b *StatefulSetApplyConfiguration) WithUID(value types.UID) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulset.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithUID(value types.UID) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100020166,"name":"WithResourceVersion","signature":"func (b *StatefulSetApplyConfiguration) WithResourceVersion(value string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulset.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithResourceVersion(value string) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100020167,"name":"WithGeneration","signature":"func (b *StatefulSetApplyConfiguration) WithGeneration(value int64) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulset.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithGeneration(value int64) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100020168,"name":"WithCreationTimestamp","signature":"func (b *StatefulSetApplyConfiguration) WithCreationTimestamp(value metav1.Time) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulset.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithCreationTimestamp(value metav1.Time) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100020169,"name":"WithDeletionTimestamp","signature":"func (b *StatefulSetApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulset.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100020170,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *StatefulSetApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulset.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100020171,"name":"WithLabels","signature":"func (b *StatefulSetApplyConfiguration) WithLabels(entries map[string]string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulset.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *StatefulSetApplyConfiguration) WithLabels(entries map[string]string) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100020172,"name":"WithAnnotations","signature":"func (b *StatefulSetApplyConfiguration) WithAnnotations(entries map[string]string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulset.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *StatefulSetApplyConfiguration) WithAnnotations(entries map[string]string) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100020173,"name":"WithOwnerReferences","signature":"func (b *StatefulSetApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulset.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *StatefulSetApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100020174,"name":"WithFinalizers","signature":"func (b *StatefulSetApplyConfiguration) WithFinalizers(values ...string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulset.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *StatefulSetApplyConfiguration) WithFinalizers(values ...string) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100020175,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *StatefulSetApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulset.go","code":"func (b *StatefulSetApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100020176,"name":"WithSpec","signature":"func (b *StatefulSetApplyConfiguration) WithSpec(value *StatefulSetSpecApplyConfiguration) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulset.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithSpec(value *StatefulSetSpecApplyConfiguration) *StatefulSetApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100020177,"name":"WithStatus","signature":"func (b *StatefulSetApplyConfiguration) WithStatus(value *StatefulSetStatusApplyConfiguration) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulset.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithStatus(value *StatefulSetStatusApplyConfiguration) *StatefulSetApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100020178,"name":"StatefulSetCondition","signature":"func StatefulSetCondition() *StatefulSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetcondition.go","code":"// StatefulSetConditionApplyConfiguration constructs an declarative configuration of the StatefulSetCondition type for use with\n// apply.\nfunc StatefulSetCondition() *StatefulSetConditionApplyConfiguration {\n\treturn \u0026StatefulSetConditionApplyConfiguration{}\n}","line":{"from":37,"to":41}} {"id":100020179,"name":"WithType","signature":"func (b *StatefulSetConditionApplyConfiguration) WithType(value v1beta1.StatefulSetConditionType) *StatefulSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetcondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *StatefulSetConditionApplyConfiguration) WithType(value v1beta1.StatefulSetConditionType) *StatefulSetConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100020180,"name":"WithStatus","signature":"func (b *StatefulSetConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *StatefulSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetcondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *StatefulSetConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *StatefulSetConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100020181,"name":"WithLastTransitionTime","signature":"func (b *StatefulSetConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *StatefulSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetcondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *StatefulSetConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *StatefulSetConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":59,"to":65}} {"id":100020182,"name":"WithReason","signature":"func (b *StatefulSetConditionApplyConfiguration) WithReason(value string) *StatefulSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetcondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *StatefulSetConditionApplyConfiguration) WithReason(value string) *StatefulSetConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100020183,"name":"WithMessage","signature":"func (b *StatefulSetConditionApplyConfiguration) WithMessage(value string) *StatefulSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetcondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *StatefulSetConditionApplyConfiguration) WithMessage(value string) *StatefulSetConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":75,"to":81}} {"id":100020184,"name":"StatefulSetOrdinals","signature":"func StatefulSetOrdinals() *StatefulSetOrdinalsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetordinals.go","code":"// StatefulSetOrdinalsApplyConfiguration constructs an declarative configuration of the StatefulSetOrdinals type for use with\n// apply.\nfunc StatefulSetOrdinals() *StatefulSetOrdinalsApplyConfiguration {\n\treturn \u0026StatefulSetOrdinalsApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100020185,"name":"WithStart","signature":"func (b *StatefulSetOrdinalsApplyConfiguration) WithStart(value int32) *StatefulSetOrdinalsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetordinals.go","code":"// WithStart sets the Start field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Start field is set to the value of the last call.\nfunc (b *StatefulSetOrdinalsApplyConfiguration) WithStart(value int32) *StatefulSetOrdinalsApplyConfiguration {\n\tb.Start = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100020186,"name":"StatefulSetPersistentVolumeClaimRetentionPolicy","signature":"func StatefulSetPersistentVolumeClaimRetentionPolicy() *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetpersistentvolumeclaimretentionpolicy.go","code":"// StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration constructs an declarative configuration of the StatefulSetPersistentVolumeClaimRetentionPolicy type for use with\n// apply.\nfunc StatefulSetPersistentVolumeClaimRetentionPolicy() *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration {\n\treturn \u0026StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100020187,"name":"WithWhenDeleted","signature":"func (b *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration) WithWhenDeleted(value v1beta1.PersistentVolumeClaimRetentionPolicyType) *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetpersistentvolumeclaimretentionpolicy.go","code":"// WithWhenDeleted sets the WhenDeleted field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the WhenDeleted field is set to the value of the last call.\nfunc (b *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration) WithWhenDeleted(value v1beta1.PersistentVolumeClaimRetentionPolicyType) *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration {\n\tb.WhenDeleted = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100020188,"name":"WithWhenScaled","signature":"func (b *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration) WithWhenScaled(value v1beta1.PersistentVolumeClaimRetentionPolicyType) *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetpersistentvolumeclaimretentionpolicy.go","code":"// WithWhenScaled sets the WhenScaled field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the WhenScaled field is set to the value of the last call.\nfunc (b *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration) WithWhenScaled(value v1beta1.PersistentVolumeClaimRetentionPolicyType) *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration {\n\tb.WhenScaled = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100020189,"name":"StatefulSetSpec","signature":"func StatefulSetSpec() *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetspec.go","code":"// StatefulSetSpecApplyConfiguration constructs an declarative configuration of the StatefulSetSpec type for use with\n// apply.\nfunc StatefulSetSpec() *StatefulSetSpecApplyConfiguration {\n\treturn \u0026StatefulSetSpecApplyConfiguration{}\n}","line":{"from":43,"to":47}} {"id":100020190,"name":"WithReplicas","signature":"func (b *StatefulSetSpecApplyConfiguration) WithReplicas(value int32) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetspec.go","code":"// WithReplicas sets the Replicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Replicas field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithReplicas(value int32) *StatefulSetSpecApplyConfiguration {\n\tb.Replicas = \u0026value\n\treturn b\n}","line":{"from":49,"to":55}} {"id":100020191,"name":"WithSelector","signature":"func (b *StatefulSetSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetspec.go","code":"// WithSelector sets the Selector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Selector field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *StatefulSetSpecApplyConfiguration {\n\tb.Selector = value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100020192,"name":"WithTemplate","signature":"func (b *StatefulSetSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetspec.go","code":"// WithTemplate sets the Template field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Template field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *StatefulSetSpecApplyConfiguration {\n\tb.Template = value\n\treturn b\n}","line":{"from":65,"to":71}} {"id":100020193,"name":"WithVolumeClaimTemplates","signature":"func (b *StatefulSetSpecApplyConfiguration) WithVolumeClaimTemplates(values ...*corev1.PersistentVolumeClaimApplyConfiguration) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetspec.go","code":"// WithVolumeClaimTemplates adds the given value to the VolumeClaimTemplates field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the VolumeClaimTemplates field.\nfunc (b *StatefulSetSpecApplyConfiguration) WithVolumeClaimTemplates(values ...*corev1.PersistentVolumeClaimApplyConfiguration) *StatefulSetSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithVolumeClaimTemplates\")\n\t\t}\n\t\tb.VolumeClaimTemplates = append(b.VolumeClaimTemplates, *values[i])\n\t}\n\treturn b\n}","line":{"from":73,"to":84}} {"id":100020194,"name":"WithServiceName","signature":"func (b *StatefulSetSpecApplyConfiguration) WithServiceName(value string) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetspec.go","code":"// WithServiceName sets the ServiceName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ServiceName field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithServiceName(value string) *StatefulSetSpecApplyConfiguration {\n\tb.ServiceName = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100020195,"name":"WithPodManagementPolicy","signature":"func (b *StatefulSetSpecApplyConfiguration) WithPodManagementPolicy(value v1beta1.PodManagementPolicyType) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetspec.go","code":"// WithPodManagementPolicy sets the PodManagementPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PodManagementPolicy field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithPodManagementPolicy(value v1beta1.PodManagementPolicyType) *StatefulSetSpecApplyConfiguration {\n\tb.PodManagementPolicy = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100020196,"name":"WithUpdateStrategy","signature":"func (b *StatefulSetSpecApplyConfiguration) WithUpdateStrategy(value *StatefulSetUpdateStrategyApplyConfiguration) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetspec.go","code":"// WithUpdateStrategy sets the UpdateStrategy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UpdateStrategy field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithUpdateStrategy(value *StatefulSetUpdateStrategyApplyConfiguration) *StatefulSetSpecApplyConfiguration {\n\tb.UpdateStrategy = value\n\treturn b\n}","line":{"from":102,"to":108}} {"id":100020197,"name":"WithRevisionHistoryLimit","signature":"func (b *StatefulSetSpecApplyConfiguration) WithRevisionHistoryLimit(value int32) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetspec.go","code":"// WithRevisionHistoryLimit sets the RevisionHistoryLimit field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RevisionHistoryLimit field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithRevisionHistoryLimit(value int32) *StatefulSetSpecApplyConfiguration {\n\tb.RevisionHistoryLimit = \u0026value\n\treturn b\n}","line":{"from":110,"to":116}} {"id":100020198,"name":"WithMinReadySeconds","signature":"func (b *StatefulSetSpecApplyConfiguration) WithMinReadySeconds(value int32) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetspec.go","code":"// WithMinReadySeconds sets the MinReadySeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MinReadySeconds field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithMinReadySeconds(value int32) *StatefulSetSpecApplyConfiguration {\n\tb.MinReadySeconds = \u0026value\n\treturn b\n}","line":{"from":118,"to":124}} {"id":100020199,"name":"WithPersistentVolumeClaimRetentionPolicy","signature":"func (b *StatefulSetSpecApplyConfiguration) WithPersistentVolumeClaimRetentionPolicy(value *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetspec.go","code":"// WithPersistentVolumeClaimRetentionPolicy sets the PersistentVolumeClaimRetentionPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PersistentVolumeClaimRetentionPolicy field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithPersistentVolumeClaimRetentionPolicy(value *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration) *StatefulSetSpecApplyConfiguration {\n\tb.PersistentVolumeClaimRetentionPolicy = value\n\treturn b\n}","line":{"from":126,"to":132}} {"id":100020200,"name":"WithOrdinals","signature":"func (b *StatefulSetSpecApplyConfiguration) WithOrdinals(value *StatefulSetOrdinalsApplyConfiguration) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetspec.go","code":"// WithOrdinals sets the Ordinals field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Ordinals field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithOrdinals(value *StatefulSetOrdinalsApplyConfiguration) *StatefulSetSpecApplyConfiguration {\n\tb.Ordinals = value\n\treturn b\n}","line":{"from":134,"to":140}} {"id":100020201,"name":"StatefulSetStatus","signature":"func StatefulSetStatus() *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetstatus.go","code":"// StatefulSetStatusApplyConfiguration constructs an declarative configuration of the StatefulSetStatus type for use with\n// apply.\nfunc StatefulSetStatus() *StatefulSetStatusApplyConfiguration {\n\treturn \u0026StatefulSetStatusApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100020202,"name":"WithObservedGeneration","signature":"func (b *StatefulSetStatusApplyConfiguration) WithObservedGeneration(value int64) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetstatus.go","code":"// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObservedGeneration field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithObservedGeneration(value int64) *StatefulSetStatusApplyConfiguration {\n\tb.ObservedGeneration = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020203,"name":"WithReplicas","signature":"func (b *StatefulSetStatusApplyConfiguration) WithReplicas(value int32) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetstatus.go","code":"// WithReplicas sets the Replicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Replicas field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithReplicas(value int32) *StatefulSetStatusApplyConfiguration {\n\tb.Replicas = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100020204,"name":"WithReadyReplicas","signature":"func (b *StatefulSetStatusApplyConfiguration) WithReadyReplicas(value int32) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetstatus.go","code":"// WithReadyReplicas sets the ReadyReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadyReplicas field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithReadyReplicas(value int32) *StatefulSetStatusApplyConfiguration {\n\tb.ReadyReplicas = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100020205,"name":"WithCurrentReplicas","signature":"func (b *StatefulSetStatusApplyConfiguration) WithCurrentReplicas(value int32) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetstatus.go","code":"// WithCurrentReplicas sets the CurrentReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CurrentReplicas field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithCurrentReplicas(value int32) *StatefulSetStatusApplyConfiguration {\n\tb.CurrentReplicas = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100020206,"name":"WithUpdatedReplicas","signature":"func (b *StatefulSetStatusApplyConfiguration) WithUpdatedReplicas(value int32) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetstatus.go","code":"// WithUpdatedReplicas sets the UpdatedReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UpdatedReplicas field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithUpdatedReplicas(value int32) *StatefulSetStatusApplyConfiguration {\n\tb.UpdatedReplicas = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100020207,"name":"WithCurrentRevision","signature":"func (b *StatefulSetStatusApplyConfiguration) WithCurrentRevision(value string) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetstatus.go","code":"// WithCurrentRevision sets the CurrentRevision field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CurrentRevision field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithCurrentRevision(value string) *StatefulSetStatusApplyConfiguration {\n\tb.CurrentRevision = \u0026value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100020208,"name":"WithUpdateRevision","signature":"func (b *StatefulSetStatusApplyConfiguration) WithUpdateRevision(value string) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetstatus.go","code":"// WithUpdateRevision sets the UpdateRevision field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UpdateRevision field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithUpdateRevision(value string) *StatefulSetStatusApplyConfiguration {\n\tb.UpdateRevision = \u0026value\n\treturn b\n}","line":{"from":90,"to":96}} {"id":100020209,"name":"WithCollisionCount","signature":"func (b *StatefulSetStatusApplyConfiguration) WithCollisionCount(value int32) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetstatus.go","code":"// WithCollisionCount sets the CollisionCount field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CollisionCount field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithCollisionCount(value int32) *StatefulSetStatusApplyConfiguration {\n\tb.CollisionCount = \u0026value\n\treturn b\n}","line":{"from":98,"to":104}} {"id":100020210,"name":"WithConditions","signature":"func (b *StatefulSetStatusApplyConfiguration) WithConditions(values ...*StatefulSetConditionApplyConfiguration) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *StatefulSetStatusApplyConfiguration) WithConditions(values ...*StatefulSetConditionApplyConfiguration) *StatefulSetStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":106,"to":117}} {"id":100020211,"name":"WithAvailableReplicas","signature":"func (b *StatefulSetStatusApplyConfiguration) WithAvailableReplicas(value int32) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta1/statefulsetstatus.go","code":"// WithAvailableReplicas sets the AvailableReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AvailableReplicas field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithAvailableReplicas(value int32) *StatefulSetStatusApplyConfiguration {\n\tb.AvailableReplicas = \u0026value\n\treturn b\n}","line":{"from":119,"to":125}} {"id":100020212,"name":"ControllerRevision","signature":"func ControllerRevision(name, namespace string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/controllerrevision.go","code":"// ControllerRevision constructs an declarative configuration of the ControllerRevision type for use with\n// apply.\nfunc ControllerRevision(name, namespace string) *ControllerRevisionApplyConfiguration {\n\tb := \u0026ControllerRevisionApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"ControllerRevision\")\n\tb.WithAPIVersion(\"apps/v1beta2\")\n\treturn b\n}","line":{"from":40,"to":49}} {"id":100020213,"name":"ExtractControllerRevision","signature":"func ExtractControllerRevision(controllerRevision *v1beta2.ControllerRevision, fieldManager string) (*ControllerRevisionApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/controllerrevision.go","code":"// ExtractControllerRevision extracts the applied configuration owned by fieldManager from\n// controllerRevision. If no managedFields are found in controllerRevision for fieldManager, a\n// ControllerRevisionApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// controllerRevision must be a unmodified ControllerRevision API object that was retrieved from the Kubernetes API.\n// ExtractControllerRevision provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractControllerRevision(controllerRevision *v1beta2.ControllerRevision, fieldManager string) (*ControllerRevisionApplyConfiguration, error) {\n\treturn extractControllerRevision(controllerRevision, fieldManager, \"\")\n}","line":{"from":51,"to":64}} {"id":100020214,"name":"ExtractControllerRevisionStatus","signature":"func ExtractControllerRevisionStatus(controllerRevision *v1beta2.ControllerRevision, fieldManager string) (*ControllerRevisionApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/controllerrevision.go","code":"// ExtractControllerRevisionStatus is the same as ExtractControllerRevision except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractControllerRevisionStatus(controllerRevision *v1beta2.ControllerRevision, fieldManager string) (*ControllerRevisionApplyConfiguration, error) {\n\treturn extractControllerRevision(controllerRevision, fieldManager, \"status\")\n}","line":{"from":66,"to":71}} {"id":100020215,"name":"extractControllerRevision","signature":"func extractControllerRevision(controllerRevision *v1beta2.ControllerRevision, fieldManager string, subresource string) (*ControllerRevisionApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/controllerrevision.go","code":"func extractControllerRevision(controllerRevision *v1beta2.ControllerRevision, fieldManager string, subresource string) (*ControllerRevisionApplyConfiguration, error) {\n\tb := \u0026ControllerRevisionApplyConfiguration{}\n\terr := managedfields.ExtractInto(controllerRevision, internal.Parser().Type(\"io.k8s.api.apps.v1beta2.ControllerRevision\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(controllerRevision.Name)\n\tb.WithNamespace(controllerRevision.Namespace)\n\n\tb.WithKind(\"ControllerRevision\")\n\tb.WithAPIVersion(\"apps/v1beta2\")\n\treturn b, nil\n}","line":{"from":73,"to":85}} {"id":100020216,"name":"WithKind","signature":"func (b *ControllerRevisionApplyConfiguration) WithKind(value string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/controllerrevision.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithKind(value string) *ControllerRevisionApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":87,"to":93}} {"id":100020217,"name":"WithAPIVersion","signature":"func (b *ControllerRevisionApplyConfiguration) WithAPIVersion(value string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/controllerrevision.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithAPIVersion(value string) *ControllerRevisionApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":95,"to":101}} {"id":100020218,"name":"WithName","signature":"func (b *ControllerRevisionApplyConfiguration) WithName(value string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/controllerrevision.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithName(value string) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":103,"to":110}} {"id":100020219,"name":"WithGenerateName","signature":"func (b *ControllerRevisionApplyConfiguration) WithGenerateName(value string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/controllerrevision.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithGenerateName(value string) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":112,"to":119}} {"id":100020220,"name":"WithNamespace","signature":"func (b *ControllerRevisionApplyConfiguration) WithNamespace(value string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/controllerrevision.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithNamespace(value string) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":121,"to":128}} {"id":100020221,"name":"WithUID","signature":"func (b *ControllerRevisionApplyConfiguration) WithUID(value types.UID) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/controllerrevision.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithUID(value types.UID) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":130,"to":137}} {"id":100020222,"name":"WithResourceVersion","signature":"func (b *ControllerRevisionApplyConfiguration) WithResourceVersion(value string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/controllerrevision.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithResourceVersion(value string) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":139,"to":146}} {"id":100020223,"name":"WithGeneration","signature":"func (b *ControllerRevisionApplyConfiguration) WithGeneration(value int64) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/controllerrevision.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithGeneration(value int64) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":148,"to":155}} {"id":100020224,"name":"WithCreationTimestamp","signature":"func (b *ControllerRevisionApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/controllerrevision.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":157,"to":164}} {"id":100020225,"name":"WithDeletionTimestamp","signature":"func (b *ControllerRevisionApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/controllerrevision.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":166,"to":173}} {"id":100020226,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ControllerRevisionApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/controllerrevision.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":175,"to":182}} {"id":100020227,"name":"WithLabels","signature":"func (b *ControllerRevisionApplyConfiguration) WithLabels(entries map[string]string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/controllerrevision.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ControllerRevisionApplyConfiguration) WithLabels(entries map[string]string) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":184,"to":197}} {"id":100020228,"name":"WithAnnotations","signature":"func (b *ControllerRevisionApplyConfiguration) WithAnnotations(entries map[string]string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/controllerrevision.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ControllerRevisionApplyConfiguration) WithAnnotations(entries map[string]string) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":199,"to":212}} {"id":100020229,"name":"WithOwnerReferences","signature":"func (b *ControllerRevisionApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/controllerrevision.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ControllerRevisionApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":214,"to":226}} {"id":100020230,"name":"WithFinalizers","signature":"func (b *ControllerRevisionApplyConfiguration) WithFinalizers(values ...string) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/controllerrevision.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ControllerRevisionApplyConfiguration) WithFinalizers(values ...string) *ControllerRevisionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":228,"to":237}} {"id":100020231,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ControllerRevisionApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/controllerrevision.go","code":"func (b *ControllerRevisionApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":239,"to":243}} {"id":100020232,"name":"WithData","signature":"func (b *ControllerRevisionApplyConfiguration) WithData(value runtime.RawExtension) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/controllerrevision.go","code":"// WithData sets the Data field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Data field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithData(value runtime.RawExtension) *ControllerRevisionApplyConfiguration {\n\tb.Data = \u0026value\n\treturn b\n}","line":{"from":245,"to":251}} {"id":100020233,"name":"WithRevision","signature":"func (b *ControllerRevisionApplyConfiguration) WithRevision(value int64) *ControllerRevisionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/controllerrevision.go","code":"// WithRevision sets the Revision field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Revision field is set to the value of the last call.\nfunc (b *ControllerRevisionApplyConfiguration) WithRevision(value int64) *ControllerRevisionApplyConfiguration {\n\tb.Revision = \u0026value\n\treturn b\n}","line":{"from":253,"to":259}} {"id":100020234,"name":"DaemonSet","signature":"func DaemonSet(name, namespace string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonset.go","code":"// DaemonSet constructs an declarative configuration of the DaemonSet type for use with\n// apply.\nfunc DaemonSet(name, namespace string) *DaemonSetApplyConfiguration {\n\tb := \u0026DaemonSetApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"DaemonSet\")\n\tb.WithAPIVersion(\"apps/v1beta2\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100020235,"name":"ExtractDaemonSet","signature":"func ExtractDaemonSet(daemonSet *appsv1beta2.DaemonSet, fieldManager string) (*DaemonSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonset.go","code":"// ExtractDaemonSet extracts the applied configuration owned by fieldManager from\n// daemonSet. If no managedFields are found in daemonSet for fieldManager, a\n// DaemonSetApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// daemonSet must be a unmodified DaemonSet API object that was retrieved from the Kubernetes API.\n// ExtractDaemonSet provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractDaemonSet(daemonSet *appsv1beta2.DaemonSet, fieldManager string) (*DaemonSetApplyConfiguration, error) {\n\treturn extractDaemonSet(daemonSet, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100020236,"name":"ExtractDaemonSetStatus","signature":"func ExtractDaemonSetStatus(daemonSet *appsv1beta2.DaemonSet, fieldManager string) (*DaemonSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonset.go","code":"// ExtractDaemonSetStatus is the same as ExtractDaemonSet except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractDaemonSetStatus(daemonSet *appsv1beta2.DaemonSet, fieldManager string) (*DaemonSetApplyConfiguration, error) {\n\treturn extractDaemonSet(daemonSet, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100020237,"name":"extractDaemonSet","signature":"func extractDaemonSet(daemonSet *appsv1beta2.DaemonSet, fieldManager string, subresource string) (*DaemonSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonset.go","code":"func extractDaemonSet(daemonSet *appsv1beta2.DaemonSet, fieldManager string, subresource string) (*DaemonSetApplyConfiguration, error) {\n\tb := \u0026DaemonSetApplyConfiguration{}\n\terr := managedfields.ExtractInto(daemonSet, internal.Parser().Type(\"io.k8s.api.apps.v1beta2.DaemonSet\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(daemonSet.Name)\n\tb.WithNamespace(daemonSet.Namespace)\n\n\tb.WithKind(\"DaemonSet\")\n\tb.WithAPIVersion(\"apps/v1beta2\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100020238,"name":"WithKind","signature":"func (b *DaemonSetApplyConfiguration) WithKind(value string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonset.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithKind(value string) *DaemonSetApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100020239,"name":"WithAPIVersion","signature":"func (b *DaemonSetApplyConfiguration) WithAPIVersion(value string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonset.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithAPIVersion(value string) *DaemonSetApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100020240,"name":"WithName","signature":"func (b *DaemonSetApplyConfiguration) WithName(value string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonset.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithName(value string) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100020241,"name":"WithGenerateName","signature":"func (b *DaemonSetApplyConfiguration) WithGenerateName(value string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonset.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithGenerateName(value string) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100020242,"name":"WithNamespace","signature":"func (b *DaemonSetApplyConfiguration) WithNamespace(value string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonset.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithNamespace(value string) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100020243,"name":"WithUID","signature":"func (b *DaemonSetApplyConfiguration) WithUID(value types.UID) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonset.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithUID(value types.UID) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100020244,"name":"WithResourceVersion","signature":"func (b *DaemonSetApplyConfiguration) WithResourceVersion(value string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonset.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithResourceVersion(value string) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100020245,"name":"WithGeneration","signature":"func (b *DaemonSetApplyConfiguration) WithGeneration(value int64) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonset.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithGeneration(value int64) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100020246,"name":"WithCreationTimestamp","signature":"func (b *DaemonSetApplyConfiguration) WithCreationTimestamp(value metav1.Time) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonset.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithCreationTimestamp(value metav1.Time) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100020247,"name":"WithDeletionTimestamp","signature":"func (b *DaemonSetApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonset.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100020248,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *DaemonSetApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonset.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100020249,"name":"WithLabels","signature":"func (b *DaemonSetApplyConfiguration) WithLabels(entries map[string]string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonset.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *DaemonSetApplyConfiguration) WithLabels(entries map[string]string) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100020250,"name":"WithAnnotations","signature":"func (b *DaemonSetApplyConfiguration) WithAnnotations(entries map[string]string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonset.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *DaemonSetApplyConfiguration) WithAnnotations(entries map[string]string) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100020251,"name":"WithOwnerReferences","signature":"func (b *DaemonSetApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonset.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *DaemonSetApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100020252,"name":"WithFinalizers","signature":"func (b *DaemonSetApplyConfiguration) WithFinalizers(values ...string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonset.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *DaemonSetApplyConfiguration) WithFinalizers(values ...string) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100020253,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *DaemonSetApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonset.go","code":"func (b *DaemonSetApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100020254,"name":"WithSpec","signature":"func (b *DaemonSetApplyConfiguration) WithSpec(value *DaemonSetSpecApplyConfiguration) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonset.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithSpec(value *DaemonSetSpecApplyConfiguration) *DaemonSetApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100020255,"name":"WithStatus","signature":"func (b *DaemonSetApplyConfiguration) WithStatus(value *DaemonSetStatusApplyConfiguration) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonset.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithStatus(value *DaemonSetStatusApplyConfiguration) *DaemonSetApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100020256,"name":"DaemonSetCondition","signature":"func DaemonSetCondition() *DaemonSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonsetcondition.go","code":"// DaemonSetConditionApplyConfiguration constructs an declarative configuration of the DaemonSetCondition type for use with\n// apply.\nfunc DaemonSetCondition() *DaemonSetConditionApplyConfiguration {\n\treturn \u0026DaemonSetConditionApplyConfiguration{}\n}","line":{"from":37,"to":41}} {"id":100020257,"name":"WithType","signature":"func (b *DaemonSetConditionApplyConfiguration) WithType(value v1beta2.DaemonSetConditionType) *DaemonSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonsetcondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *DaemonSetConditionApplyConfiguration) WithType(value v1beta2.DaemonSetConditionType) *DaemonSetConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100020258,"name":"WithStatus","signature":"func (b *DaemonSetConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *DaemonSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonsetcondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *DaemonSetConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *DaemonSetConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100020259,"name":"WithLastTransitionTime","signature":"func (b *DaemonSetConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *DaemonSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonsetcondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *DaemonSetConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *DaemonSetConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":59,"to":65}} {"id":100020260,"name":"WithReason","signature":"func (b *DaemonSetConditionApplyConfiguration) WithReason(value string) *DaemonSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonsetcondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *DaemonSetConditionApplyConfiguration) WithReason(value string) *DaemonSetConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100020261,"name":"WithMessage","signature":"func (b *DaemonSetConditionApplyConfiguration) WithMessage(value string) *DaemonSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonsetcondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *DaemonSetConditionApplyConfiguration) WithMessage(value string) *DaemonSetConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":75,"to":81}} {"id":100020262,"name":"DaemonSetSpec","signature":"func DaemonSetSpec() *DaemonSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonsetspec.go","code":"// DaemonSetSpecApplyConfiguration constructs an declarative configuration of the DaemonSetSpec type for use with\n// apply.\nfunc DaemonSetSpec() *DaemonSetSpecApplyConfiguration {\n\treturn \u0026DaemonSetSpecApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100020263,"name":"WithSelector","signature":"func (b *DaemonSetSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *DaemonSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonsetspec.go","code":"// WithSelector sets the Selector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Selector field is set to the value of the last call.\nfunc (b *DaemonSetSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *DaemonSetSpecApplyConfiguration {\n\tb.Selector = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020264,"name":"WithTemplate","signature":"func (b *DaemonSetSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *DaemonSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonsetspec.go","code":"// WithTemplate sets the Template field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Template field is set to the value of the last call.\nfunc (b *DaemonSetSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *DaemonSetSpecApplyConfiguration {\n\tb.Template = value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100020265,"name":"WithUpdateStrategy","signature":"func (b *DaemonSetSpecApplyConfiguration) WithUpdateStrategy(value *DaemonSetUpdateStrategyApplyConfiguration) *DaemonSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonsetspec.go","code":"// WithUpdateStrategy sets the UpdateStrategy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UpdateStrategy field is set to the value of the last call.\nfunc (b *DaemonSetSpecApplyConfiguration) WithUpdateStrategy(value *DaemonSetUpdateStrategyApplyConfiguration) *DaemonSetSpecApplyConfiguration {\n\tb.UpdateStrategy = value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100020266,"name":"WithMinReadySeconds","signature":"func (b *DaemonSetSpecApplyConfiguration) WithMinReadySeconds(value int32) *DaemonSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonsetspec.go","code":"// WithMinReadySeconds sets the MinReadySeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MinReadySeconds field is set to the value of the last call.\nfunc (b *DaemonSetSpecApplyConfiguration) WithMinReadySeconds(value int32) *DaemonSetSpecApplyConfiguration {\n\tb.MinReadySeconds = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100020267,"name":"WithRevisionHistoryLimit","signature":"func (b *DaemonSetSpecApplyConfiguration) WithRevisionHistoryLimit(value int32) *DaemonSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonsetspec.go","code":"// WithRevisionHistoryLimit sets the RevisionHistoryLimit field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RevisionHistoryLimit field is set to the value of the last call.\nfunc (b *DaemonSetSpecApplyConfiguration) WithRevisionHistoryLimit(value int32) *DaemonSetSpecApplyConfiguration {\n\tb.RevisionHistoryLimit = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100020268,"name":"DaemonSetStatus","signature":"func DaemonSetStatus() *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonsetstatus.go","code":"// DaemonSetStatusApplyConfiguration constructs an declarative configuration of the DaemonSetStatus type for use with\n// apply.\nfunc DaemonSetStatus() *DaemonSetStatusApplyConfiguration {\n\treturn \u0026DaemonSetStatusApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100020269,"name":"WithCurrentNumberScheduled","signature":"func (b *DaemonSetStatusApplyConfiguration) WithCurrentNumberScheduled(value int32) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonsetstatus.go","code":"// WithCurrentNumberScheduled sets the CurrentNumberScheduled field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CurrentNumberScheduled field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithCurrentNumberScheduled(value int32) *DaemonSetStatusApplyConfiguration {\n\tb.CurrentNumberScheduled = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020270,"name":"WithNumberMisscheduled","signature":"func (b *DaemonSetStatusApplyConfiguration) WithNumberMisscheduled(value int32) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonsetstatus.go","code":"// WithNumberMisscheduled sets the NumberMisscheduled field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NumberMisscheduled field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithNumberMisscheduled(value int32) *DaemonSetStatusApplyConfiguration {\n\tb.NumberMisscheduled = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100020271,"name":"WithDesiredNumberScheduled","signature":"func (b *DaemonSetStatusApplyConfiguration) WithDesiredNumberScheduled(value int32) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonsetstatus.go","code":"// WithDesiredNumberScheduled sets the DesiredNumberScheduled field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DesiredNumberScheduled field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithDesiredNumberScheduled(value int32) *DaemonSetStatusApplyConfiguration {\n\tb.DesiredNumberScheduled = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100020272,"name":"WithNumberReady","signature":"func (b *DaemonSetStatusApplyConfiguration) WithNumberReady(value int32) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonsetstatus.go","code":"// WithNumberReady sets the NumberReady field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NumberReady field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithNumberReady(value int32) *DaemonSetStatusApplyConfiguration {\n\tb.NumberReady = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100020273,"name":"WithObservedGeneration","signature":"func (b *DaemonSetStatusApplyConfiguration) WithObservedGeneration(value int64) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonsetstatus.go","code":"// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObservedGeneration field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithObservedGeneration(value int64) *DaemonSetStatusApplyConfiguration {\n\tb.ObservedGeneration = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100020274,"name":"WithUpdatedNumberScheduled","signature":"func (b *DaemonSetStatusApplyConfiguration) WithUpdatedNumberScheduled(value int32) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonsetstatus.go","code":"// WithUpdatedNumberScheduled sets the UpdatedNumberScheduled field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UpdatedNumberScheduled field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithUpdatedNumberScheduled(value int32) *DaemonSetStatusApplyConfiguration {\n\tb.UpdatedNumberScheduled = \u0026value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100020275,"name":"WithNumberAvailable","signature":"func (b *DaemonSetStatusApplyConfiguration) WithNumberAvailable(value int32) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonsetstatus.go","code":"// WithNumberAvailable sets the NumberAvailable field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NumberAvailable field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithNumberAvailable(value int32) *DaemonSetStatusApplyConfiguration {\n\tb.NumberAvailable = \u0026value\n\treturn b\n}","line":{"from":90,"to":96}} {"id":100020276,"name":"WithNumberUnavailable","signature":"func (b *DaemonSetStatusApplyConfiguration) WithNumberUnavailable(value int32) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonsetstatus.go","code":"// WithNumberUnavailable sets the NumberUnavailable field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NumberUnavailable field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithNumberUnavailable(value int32) *DaemonSetStatusApplyConfiguration {\n\tb.NumberUnavailable = \u0026value\n\treturn b\n}","line":{"from":98,"to":104}} {"id":100020277,"name":"WithCollisionCount","signature":"func (b *DaemonSetStatusApplyConfiguration) WithCollisionCount(value int32) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonsetstatus.go","code":"// WithCollisionCount sets the CollisionCount field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CollisionCount field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithCollisionCount(value int32) *DaemonSetStatusApplyConfiguration {\n\tb.CollisionCount = \u0026value\n\treturn b\n}","line":{"from":106,"to":112}} {"id":100020278,"name":"WithConditions","signature":"func (b *DaemonSetStatusApplyConfiguration) WithConditions(values ...*DaemonSetConditionApplyConfiguration) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/daemonsetstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *DaemonSetStatusApplyConfiguration) WithConditions(values ...*DaemonSetConditionApplyConfiguration) *DaemonSetStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":114,"to":125}} {"id":100020279,"name":"Deployment","signature":"func Deployment(name, namespace string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deployment.go","code":"// Deployment constructs an declarative configuration of the Deployment type for use with\n// apply.\nfunc Deployment(name, namespace string) *DeploymentApplyConfiguration {\n\tb := \u0026DeploymentApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"Deployment\")\n\tb.WithAPIVersion(\"apps/v1beta2\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100020280,"name":"ExtractDeployment","signature":"func ExtractDeployment(deployment *appsv1beta2.Deployment, fieldManager string) (*DeploymentApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deployment.go","code":"// ExtractDeployment extracts the applied configuration owned by fieldManager from\n// deployment. If no managedFields are found in deployment for fieldManager, a\n// DeploymentApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// deployment must be a unmodified Deployment API object that was retrieved from the Kubernetes API.\n// ExtractDeployment provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractDeployment(deployment *appsv1beta2.Deployment, fieldManager string) (*DeploymentApplyConfiguration, error) {\n\treturn extractDeployment(deployment, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100020281,"name":"ExtractDeploymentStatus","signature":"func ExtractDeploymentStatus(deployment *appsv1beta2.Deployment, fieldManager string) (*DeploymentApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deployment.go","code":"// ExtractDeploymentStatus is the same as ExtractDeployment except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractDeploymentStatus(deployment *appsv1beta2.Deployment, fieldManager string) (*DeploymentApplyConfiguration, error) {\n\treturn extractDeployment(deployment, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100020282,"name":"extractDeployment","signature":"func extractDeployment(deployment *appsv1beta2.Deployment, fieldManager string, subresource string) (*DeploymentApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deployment.go","code":"func extractDeployment(deployment *appsv1beta2.Deployment, fieldManager string, subresource string) (*DeploymentApplyConfiguration, error) {\n\tb := \u0026DeploymentApplyConfiguration{}\n\terr := managedfields.ExtractInto(deployment, internal.Parser().Type(\"io.k8s.api.apps.v1beta2.Deployment\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(deployment.Name)\n\tb.WithNamespace(deployment.Namespace)\n\n\tb.WithKind(\"Deployment\")\n\tb.WithAPIVersion(\"apps/v1beta2\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100020283,"name":"WithKind","signature":"func (b *DeploymentApplyConfiguration) WithKind(value string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deployment.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithKind(value string) *DeploymentApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100020284,"name":"WithAPIVersion","signature":"func (b *DeploymentApplyConfiguration) WithAPIVersion(value string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deployment.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithAPIVersion(value string) *DeploymentApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100020285,"name":"WithName","signature":"func (b *DeploymentApplyConfiguration) WithName(value string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deployment.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithName(value string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100020286,"name":"WithGenerateName","signature":"func (b *DeploymentApplyConfiguration) WithGenerateName(value string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deployment.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithGenerateName(value string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100020287,"name":"WithNamespace","signature":"func (b *DeploymentApplyConfiguration) WithNamespace(value string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deployment.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithNamespace(value string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100020288,"name":"WithUID","signature":"func (b *DeploymentApplyConfiguration) WithUID(value types.UID) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deployment.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithUID(value types.UID) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100020289,"name":"WithResourceVersion","signature":"func (b *DeploymentApplyConfiguration) WithResourceVersion(value string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deployment.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithResourceVersion(value string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100020290,"name":"WithGeneration","signature":"func (b *DeploymentApplyConfiguration) WithGeneration(value int64) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deployment.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithGeneration(value int64) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100020291,"name":"WithCreationTimestamp","signature":"func (b *DeploymentApplyConfiguration) WithCreationTimestamp(value metav1.Time) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deployment.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithCreationTimestamp(value metav1.Time) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100020292,"name":"WithDeletionTimestamp","signature":"func (b *DeploymentApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deployment.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100020293,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *DeploymentApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deployment.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100020294,"name":"WithLabels","signature":"func (b *DeploymentApplyConfiguration) WithLabels(entries map[string]string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deployment.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *DeploymentApplyConfiguration) WithLabels(entries map[string]string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100020295,"name":"WithAnnotations","signature":"func (b *DeploymentApplyConfiguration) WithAnnotations(entries map[string]string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deployment.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *DeploymentApplyConfiguration) WithAnnotations(entries map[string]string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100020296,"name":"WithOwnerReferences","signature":"func (b *DeploymentApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deployment.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *DeploymentApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100020297,"name":"WithFinalizers","signature":"func (b *DeploymentApplyConfiguration) WithFinalizers(values ...string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deployment.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *DeploymentApplyConfiguration) WithFinalizers(values ...string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100020298,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *DeploymentApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deployment.go","code":"func (b *DeploymentApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100020299,"name":"WithSpec","signature":"func (b *DeploymentApplyConfiguration) WithSpec(value *DeploymentSpecApplyConfiguration) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deployment.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithSpec(value *DeploymentSpecApplyConfiguration) *DeploymentApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100020300,"name":"WithStatus","signature":"func (b *DeploymentApplyConfiguration) WithStatus(value *DeploymentStatusApplyConfiguration) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deployment.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithStatus(value *DeploymentStatusApplyConfiguration) *DeploymentApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100020301,"name":"DeploymentCondition","signature":"func DeploymentCondition() *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentcondition.go","code":"// DeploymentConditionApplyConfiguration constructs an declarative configuration of the DeploymentCondition type for use with\n// apply.\nfunc DeploymentCondition() *DeploymentConditionApplyConfiguration {\n\treturn \u0026DeploymentConditionApplyConfiguration{}\n}","line":{"from":38,"to":42}} {"id":100020302,"name":"WithType","signature":"func (b *DeploymentConditionApplyConfiguration) WithType(value v1beta2.DeploymentConditionType) *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentcondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *DeploymentConditionApplyConfiguration) WithType(value v1beta2.DeploymentConditionType) *DeploymentConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100020303,"name":"WithStatus","signature":"func (b *DeploymentConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentcondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *DeploymentConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *DeploymentConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100020304,"name":"WithLastUpdateTime","signature":"func (b *DeploymentConditionApplyConfiguration) WithLastUpdateTime(value metav1.Time) *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentcondition.go","code":"// WithLastUpdateTime sets the LastUpdateTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastUpdateTime field is set to the value of the last call.\nfunc (b *DeploymentConditionApplyConfiguration) WithLastUpdateTime(value metav1.Time) *DeploymentConditionApplyConfiguration {\n\tb.LastUpdateTime = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100020305,"name":"WithLastTransitionTime","signature":"func (b *DeploymentConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentcondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *DeploymentConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *DeploymentConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":68,"to":74}} {"id":100020306,"name":"WithReason","signature":"func (b *DeploymentConditionApplyConfiguration) WithReason(value string) *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentcondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *DeploymentConditionApplyConfiguration) WithReason(value string) *DeploymentConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":76,"to":82}} {"id":100020307,"name":"WithMessage","signature":"func (b *DeploymentConditionApplyConfiguration) WithMessage(value string) *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentcondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *DeploymentConditionApplyConfiguration) WithMessage(value string) *DeploymentConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100020308,"name":"DeploymentSpec","signature":"func DeploymentSpec() *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentspec.go","code":"// DeploymentSpecApplyConfiguration constructs an declarative configuration of the DeploymentSpec type for use with\n// apply.\nfunc DeploymentSpec() *DeploymentSpecApplyConfiguration {\n\treturn \u0026DeploymentSpecApplyConfiguration{}\n}","line":{"from":39,"to":43}} {"id":100020309,"name":"WithReplicas","signature":"func (b *DeploymentSpecApplyConfiguration) WithReplicas(value int32) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentspec.go","code":"// WithReplicas sets the Replicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Replicas field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithReplicas(value int32) *DeploymentSpecApplyConfiguration {\n\tb.Replicas = \u0026value\n\treturn b\n}","line":{"from":45,"to":51}} {"id":100020310,"name":"WithSelector","signature":"func (b *DeploymentSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentspec.go","code":"// WithSelector sets the Selector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Selector field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *DeploymentSpecApplyConfiguration {\n\tb.Selector = value\n\treturn b\n}","line":{"from":53,"to":59}} {"id":100020311,"name":"WithTemplate","signature":"func (b *DeploymentSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentspec.go","code":"// WithTemplate sets the Template field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Template field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *DeploymentSpecApplyConfiguration {\n\tb.Template = value\n\treturn b\n}","line":{"from":61,"to":67}} {"id":100020312,"name":"WithStrategy","signature":"func (b *DeploymentSpecApplyConfiguration) WithStrategy(value *DeploymentStrategyApplyConfiguration) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentspec.go","code":"// WithStrategy sets the Strategy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Strategy field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithStrategy(value *DeploymentStrategyApplyConfiguration) *DeploymentSpecApplyConfiguration {\n\tb.Strategy = value\n\treturn b\n}","line":{"from":69,"to":75}} {"id":100020313,"name":"WithMinReadySeconds","signature":"func (b *DeploymentSpecApplyConfiguration) WithMinReadySeconds(value int32) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentspec.go","code":"// WithMinReadySeconds sets the MinReadySeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MinReadySeconds field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithMinReadySeconds(value int32) *DeploymentSpecApplyConfiguration {\n\tb.MinReadySeconds = \u0026value\n\treturn b\n}","line":{"from":77,"to":83}} {"id":100020314,"name":"WithRevisionHistoryLimit","signature":"func (b *DeploymentSpecApplyConfiguration) WithRevisionHistoryLimit(value int32) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentspec.go","code":"// WithRevisionHistoryLimit sets the RevisionHistoryLimit field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RevisionHistoryLimit field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithRevisionHistoryLimit(value int32) *DeploymentSpecApplyConfiguration {\n\tb.RevisionHistoryLimit = \u0026value\n\treturn b\n}","line":{"from":85,"to":91}} {"id":100020315,"name":"WithPaused","signature":"func (b *DeploymentSpecApplyConfiguration) WithPaused(value bool) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentspec.go","code":"// WithPaused sets the Paused field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Paused field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithPaused(value bool) *DeploymentSpecApplyConfiguration {\n\tb.Paused = \u0026value\n\treturn b\n}","line":{"from":93,"to":99}} {"id":100020316,"name":"WithProgressDeadlineSeconds","signature":"func (b *DeploymentSpecApplyConfiguration) WithProgressDeadlineSeconds(value int32) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentspec.go","code":"// WithProgressDeadlineSeconds sets the ProgressDeadlineSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ProgressDeadlineSeconds field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithProgressDeadlineSeconds(value int32) *DeploymentSpecApplyConfiguration {\n\tb.ProgressDeadlineSeconds = \u0026value\n\treturn b\n}","line":{"from":101,"to":107}} {"id":100020317,"name":"DeploymentStatus","signature":"func DeploymentStatus() *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentstatus.go","code":"// DeploymentStatusApplyConfiguration constructs an declarative configuration of the DeploymentStatus type for use with\n// apply.\nfunc DeploymentStatus() *DeploymentStatusApplyConfiguration {\n\treturn \u0026DeploymentStatusApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100020318,"name":"WithObservedGeneration","signature":"func (b *DeploymentStatusApplyConfiguration) WithObservedGeneration(value int64) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentstatus.go","code":"// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObservedGeneration field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithObservedGeneration(value int64) *DeploymentStatusApplyConfiguration {\n\tb.ObservedGeneration = \u0026value\n\treturn b\n}","line":{"from":40,"to":46}} {"id":100020319,"name":"WithReplicas","signature":"func (b *DeploymentStatusApplyConfiguration) WithReplicas(value int32) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentstatus.go","code":"// WithReplicas sets the Replicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Replicas field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithReplicas(value int32) *DeploymentStatusApplyConfiguration {\n\tb.Replicas = \u0026value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100020320,"name":"WithUpdatedReplicas","signature":"func (b *DeploymentStatusApplyConfiguration) WithUpdatedReplicas(value int32) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentstatus.go","code":"// WithUpdatedReplicas sets the UpdatedReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UpdatedReplicas field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithUpdatedReplicas(value int32) *DeploymentStatusApplyConfiguration {\n\tb.UpdatedReplicas = \u0026value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100020321,"name":"WithReadyReplicas","signature":"func (b *DeploymentStatusApplyConfiguration) WithReadyReplicas(value int32) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentstatus.go","code":"// WithReadyReplicas sets the ReadyReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadyReplicas field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithReadyReplicas(value int32) *DeploymentStatusApplyConfiguration {\n\tb.ReadyReplicas = \u0026value\n\treturn b\n}","line":{"from":64,"to":70}} {"id":100020322,"name":"WithAvailableReplicas","signature":"func (b *DeploymentStatusApplyConfiguration) WithAvailableReplicas(value int32) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentstatus.go","code":"// WithAvailableReplicas sets the AvailableReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AvailableReplicas field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithAvailableReplicas(value int32) *DeploymentStatusApplyConfiguration {\n\tb.AvailableReplicas = \u0026value\n\treturn b\n}","line":{"from":72,"to":78}} {"id":100020323,"name":"WithUnavailableReplicas","signature":"func (b *DeploymentStatusApplyConfiguration) WithUnavailableReplicas(value int32) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentstatus.go","code":"// WithUnavailableReplicas sets the UnavailableReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UnavailableReplicas field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithUnavailableReplicas(value int32) *DeploymentStatusApplyConfiguration {\n\tb.UnavailableReplicas = \u0026value\n\treturn b\n}","line":{"from":80,"to":86}} {"id":100020324,"name":"WithConditions","signature":"func (b *DeploymentStatusApplyConfiguration) WithConditions(values ...*DeploymentConditionApplyConfiguration) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *DeploymentStatusApplyConfiguration) WithConditions(values ...*DeploymentConditionApplyConfiguration) *DeploymentStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":88,"to":99}} {"id":100020325,"name":"WithCollisionCount","signature":"func (b *DeploymentStatusApplyConfiguration) WithCollisionCount(value int32) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentstatus.go","code":"// WithCollisionCount sets the CollisionCount field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CollisionCount field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithCollisionCount(value int32) *DeploymentStatusApplyConfiguration {\n\tb.CollisionCount = \u0026value\n\treturn b\n}","line":{"from":101,"to":107}} {"id":100020326,"name":"DeploymentStrategy","signature":"func DeploymentStrategy() *DeploymentStrategyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentstrategy.go","code":"// DeploymentStrategyApplyConfiguration constructs an declarative configuration of the DeploymentStrategy type for use with\n// apply.\nfunc DeploymentStrategy() *DeploymentStrategyApplyConfiguration {\n\treturn \u0026DeploymentStrategyApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100020327,"name":"WithType","signature":"func (b *DeploymentStrategyApplyConfiguration) WithType(value v1beta2.DeploymentStrategyType) *DeploymentStrategyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentstrategy.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *DeploymentStrategyApplyConfiguration) WithType(value v1beta2.DeploymentStrategyType) *DeploymentStrategyApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100020328,"name":"WithRollingUpdate","signature":"func (b *DeploymentStrategyApplyConfiguration) WithRollingUpdate(value *RollingUpdateDeploymentApplyConfiguration) *DeploymentStrategyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/deploymentstrategy.go","code":"// WithRollingUpdate sets the RollingUpdate field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RollingUpdate field is set to the value of the last call.\nfunc (b *DeploymentStrategyApplyConfiguration) WithRollingUpdate(value *RollingUpdateDeploymentApplyConfiguration) *DeploymentStrategyApplyConfiguration {\n\tb.RollingUpdate = value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100020329,"name":"ReplicaSet","signature":"func ReplicaSet(name, namespace string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicaset.go","code":"// ReplicaSet constructs an declarative configuration of the ReplicaSet type for use with\n// apply.\nfunc ReplicaSet(name, namespace string) *ReplicaSetApplyConfiguration {\n\tb := \u0026ReplicaSetApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"ReplicaSet\")\n\tb.WithAPIVersion(\"apps/v1beta2\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100020330,"name":"ExtractReplicaSet","signature":"func ExtractReplicaSet(replicaSet *appsv1beta2.ReplicaSet, fieldManager string) (*ReplicaSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicaset.go","code":"// ExtractReplicaSet extracts the applied configuration owned by fieldManager from\n// replicaSet. If no managedFields are found in replicaSet for fieldManager, a\n// ReplicaSetApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// replicaSet must be a unmodified ReplicaSet API object that was retrieved from the Kubernetes API.\n// ExtractReplicaSet provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractReplicaSet(replicaSet *appsv1beta2.ReplicaSet, fieldManager string) (*ReplicaSetApplyConfiguration, error) {\n\treturn extractReplicaSet(replicaSet, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100020331,"name":"ExtractReplicaSetStatus","signature":"func ExtractReplicaSetStatus(replicaSet *appsv1beta2.ReplicaSet, fieldManager string) (*ReplicaSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicaset.go","code":"// ExtractReplicaSetStatus is the same as ExtractReplicaSet except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractReplicaSetStatus(replicaSet *appsv1beta2.ReplicaSet, fieldManager string) (*ReplicaSetApplyConfiguration, error) {\n\treturn extractReplicaSet(replicaSet, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100020332,"name":"extractReplicaSet","signature":"func extractReplicaSet(replicaSet *appsv1beta2.ReplicaSet, fieldManager string, subresource string) (*ReplicaSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicaset.go","code":"func extractReplicaSet(replicaSet *appsv1beta2.ReplicaSet, fieldManager string, subresource string) (*ReplicaSetApplyConfiguration, error) {\n\tb := \u0026ReplicaSetApplyConfiguration{}\n\terr := managedfields.ExtractInto(replicaSet, internal.Parser().Type(\"io.k8s.api.apps.v1beta2.ReplicaSet\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(replicaSet.Name)\n\tb.WithNamespace(replicaSet.Namespace)\n\n\tb.WithKind(\"ReplicaSet\")\n\tb.WithAPIVersion(\"apps/v1beta2\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100020333,"name":"WithKind","signature":"func (b *ReplicaSetApplyConfiguration) WithKind(value string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicaset.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithKind(value string) *ReplicaSetApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100020334,"name":"WithAPIVersion","signature":"func (b *ReplicaSetApplyConfiguration) WithAPIVersion(value string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicaset.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithAPIVersion(value string) *ReplicaSetApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100020335,"name":"WithName","signature":"func (b *ReplicaSetApplyConfiguration) WithName(value string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicaset.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithName(value string) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100020336,"name":"WithGenerateName","signature":"func (b *ReplicaSetApplyConfiguration) WithGenerateName(value string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicaset.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithGenerateName(value string) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100020337,"name":"WithNamespace","signature":"func (b *ReplicaSetApplyConfiguration) WithNamespace(value string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicaset.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithNamespace(value string) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100020338,"name":"WithUID","signature":"func (b *ReplicaSetApplyConfiguration) WithUID(value types.UID) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicaset.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithUID(value types.UID) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100020339,"name":"WithResourceVersion","signature":"func (b *ReplicaSetApplyConfiguration) WithResourceVersion(value string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicaset.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithResourceVersion(value string) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100020340,"name":"WithGeneration","signature":"func (b *ReplicaSetApplyConfiguration) WithGeneration(value int64) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicaset.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithGeneration(value int64) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100020341,"name":"WithCreationTimestamp","signature":"func (b *ReplicaSetApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicaset.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100020342,"name":"WithDeletionTimestamp","signature":"func (b *ReplicaSetApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicaset.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100020343,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ReplicaSetApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicaset.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100020344,"name":"WithLabels","signature":"func (b *ReplicaSetApplyConfiguration) WithLabels(entries map[string]string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicaset.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ReplicaSetApplyConfiguration) WithLabels(entries map[string]string) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100020345,"name":"WithAnnotations","signature":"func (b *ReplicaSetApplyConfiguration) WithAnnotations(entries map[string]string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicaset.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ReplicaSetApplyConfiguration) WithAnnotations(entries map[string]string) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100020346,"name":"WithOwnerReferences","signature":"func (b *ReplicaSetApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicaset.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ReplicaSetApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100020347,"name":"WithFinalizers","signature":"func (b *ReplicaSetApplyConfiguration) WithFinalizers(values ...string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicaset.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ReplicaSetApplyConfiguration) WithFinalizers(values ...string) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100020348,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ReplicaSetApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicaset.go","code":"func (b *ReplicaSetApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100020349,"name":"WithSpec","signature":"func (b *ReplicaSetApplyConfiguration) WithSpec(value *ReplicaSetSpecApplyConfiguration) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicaset.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithSpec(value *ReplicaSetSpecApplyConfiguration) *ReplicaSetApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100020350,"name":"WithStatus","signature":"func (b *ReplicaSetApplyConfiguration) WithStatus(value *ReplicaSetStatusApplyConfiguration) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicaset.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithStatus(value *ReplicaSetStatusApplyConfiguration) *ReplicaSetApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100020351,"name":"ReplicaSetCondition","signature":"func ReplicaSetCondition() *ReplicaSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicasetcondition.go","code":"// ReplicaSetConditionApplyConfiguration constructs an declarative configuration of the ReplicaSetCondition type for use with\n// apply.\nfunc ReplicaSetCondition() *ReplicaSetConditionApplyConfiguration {\n\treturn \u0026ReplicaSetConditionApplyConfiguration{}\n}","line":{"from":37,"to":41}} {"id":100020352,"name":"WithType","signature":"func (b *ReplicaSetConditionApplyConfiguration) WithType(value v1beta2.ReplicaSetConditionType) *ReplicaSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicasetcondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *ReplicaSetConditionApplyConfiguration) WithType(value v1beta2.ReplicaSetConditionType) *ReplicaSetConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100020353,"name":"WithStatus","signature":"func (b *ReplicaSetConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *ReplicaSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicasetcondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *ReplicaSetConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *ReplicaSetConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100020354,"name":"WithLastTransitionTime","signature":"func (b *ReplicaSetConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *ReplicaSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicasetcondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *ReplicaSetConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *ReplicaSetConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":59,"to":65}} {"id":100020355,"name":"WithReason","signature":"func (b *ReplicaSetConditionApplyConfiguration) WithReason(value string) *ReplicaSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicasetcondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *ReplicaSetConditionApplyConfiguration) WithReason(value string) *ReplicaSetConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100020356,"name":"WithMessage","signature":"func (b *ReplicaSetConditionApplyConfiguration) WithMessage(value string) *ReplicaSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicasetcondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *ReplicaSetConditionApplyConfiguration) WithMessage(value string) *ReplicaSetConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":75,"to":81}} {"id":100020357,"name":"ReplicaSetSpec","signature":"func ReplicaSetSpec() *ReplicaSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicasetspec.go","code":"// ReplicaSetSpecApplyConfiguration constructs an declarative configuration of the ReplicaSetSpec type for use with\n// apply.\nfunc ReplicaSetSpec() *ReplicaSetSpecApplyConfiguration {\n\treturn \u0026ReplicaSetSpecApplyConfiguration{}\n}","line":{"from":35,"to":39}} {"id":100020358,"name":"WithReplicas","signature":"func (b *ReplicaSetSpecApplyConfiguration) WithReplicas(value int32) *ReplicaSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicasetspec.go","code":"// WithReplicas sets the Replicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Replicas field is set to the value of the last call.\nfunc (b *ReplicaSetSpecApplyConfiguration) WithReplicas(value int32) *ReplicaSetSpecApplyConfiguration {\n\tb.Replicas = \u0026value\n\treturn b\n}","line":{"from":41,"to":47}} {"id":100020359,"name":"WithMinReadySeconds","signature":"func (b *ReplicaSetSpecApplyConfiguration) WithMinReadySeconds(value int32) *ReplicaSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicasetspec.go","code":"// WithMinReadySeconds sets the MinReadySeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MinReadySeconds field is set to the value of the last call.\nfunc (b *ReplicaSetSpecApplyConfiguration) WithMinReadySeconds(value int32) *ReplicaSetSpecApplyConfiguration {\n\tb.MinReadySeconds = \u0026value\n\treturn b\n}","line":{"from":49,"to":55}} {"id":100020360,"name":"WithSelector","signature":"func (b *ReplicaSetSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *ReplicaSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicasetspec.go","code":"// WithSelector sets the Selector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Selector field is set to the value of the last call.\nfunc (b *ReplicaSetSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *ReplicaSetSpecApplyConfiguration {\n\tb.Selector = value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100020361,"name":"WithTemplate","signature":"func (b *ReplicaSetSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *ReplicaSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicasetspec.go","code":"// WithTemplate sets the Template field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Template field is set to the value of the last call.\nfunc (b *ReplicaSetSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *ReplicaSetSpecApplyConfiguration {\n\tb.Template = value\n\treturn b\n}","line":{"from":65,"to":71}} {"id":100020362,"name":"ReplicaSetStatus","signature":"func ReplicaSetStatus() *ReplicaSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicasetstatus.go","code":"// ReplicaSetStatusApplyConfiguration constructs an declarative configuration of the ReplicaSetStatus type for use with\n// apply.\nfunc ReplicaSetStatus() *ReplicaSetStatusApplyConfiguration {\n\treturn \u0026ReplicaSetStatusApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100020363,"name":"WithReplicas","signature":"func (b *ReplicaSetStatusApplyConfiguration) WithReplicas(value int32) *ReplicaSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicasetstatus.go","code":"// WithReplicas sets the Replicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Replicas field is set to the value of the last call.\nfunc (b *ReplicaSetStatusApplyConfiguration) WithReplicas(value int32) *ReplicaSetStatusApplyConfiguration {\n\tb.Replicas = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100020364,"name":"WithFullyLabeledReplicas","signature":"func (b *ReplicaSetStatusApplyConfiguration) WithFullyLabeledReplicas(value int32) *ReplicaSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicasetstatus.go","code":"// WithFullyLabeledReplicas sets the FullyLabeledReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FullyLabeledReplicas field is set to the value of the last call.\nfunc (b *ReplicaSetStatusApplyConfiguration) WithFullyLabeledReplicas(value int32) *ReplicaSetStatusApplyConfiguration {\n\tb.FullyLabeledReplicas = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100020365,"name":"WithReadyReplicas","signature":"func (b *ReplicaSetStatusApplyConfiguration) WithReadyReplicas(value int32) *ReplicaSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicasetstatus.go","code":"// WithReadyReplicas sets the ReadyReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadyReplicas field is set to the value of the last call.\nfunc (b *ReplicaSetStatusApplyConfiguration) WithReadyReplicas(value int32) *ReplicaSetStatusApplyConfiguration {\n\tb.ReadyReplicas = \u0026value\n\treturn b\n}","line":{"from":54,"to":60}} {"id":100020366,"name":"WithAvailableReplicas","signature":"func (b *ReplicaSetStatusApplyConfiguration) WithAvailableReplicas(value int32) *ReplicaSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicasetstatus.go","code":"// WithAvailableReplicas sets the AvailableReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AvailableReplicas field is set to the value of the last call.\nfunc (b *ReplicaSetStatusApplyConfiguration) WithAvailableReplicas(value int32) *ReplicaSetStatusApplyConfiguration {\n\tb.AvailableReplicas = \u0026value\n\treturn b\n}","line":{"from":62,"to":68}} {"id":100020367,"name":"WithObservedGeneration","signature":"func (b *ReplicaSetStatusApplyConfiguration) WithObservedGeneration(value int64) *ReplicaSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicasetstatus.go","code":"// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObservedGeneration field is set to the value of the last call.\nfunc (b *ReplicaSetStatusApplyConfiguration) WithObservedGeneration(value int64) *ReplicaSetStatusApplyConfiguration {\n\tb.ObservedGeneration = \u0026value\n\treturn b\n}","line":{"from":70,"to":76}} {"id":100020368,"name":"WithConditions","signature":"func (b *ReplicaSetStatusApplyConfiguration) WithConditions(values ...*ReplicaSetConditionApplyConfiguration) *ReplicaSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/replicasetstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *ReplicaSetStatusApplyConfiguration) WithConditions(values ...*ReplicaSetConditionApplyConfiguration) *ReplicaSetStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":78,"to":89}} {"id":100020369,"name":"RollingUpdateDaemonSet","signature":"func RollingUpdateDaemonSet() *RollingUpdateDaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/rollingupdatedaemonset.go","code":"// RollingUpdateDaemonSetApplyConfiguration constructs an declarative configuration of the RollingUpdateDaemonSet type for use with\n// apply.\nfunc RollingUpdateDaemonSet() *RollingUpdateDaemonSetApplyConfiguration {\n\treturn \u0026RollingUpdateDaemonSetApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100020370,"name":"WithMaxUnavailable","signature":"func (b *RollingUpdateDaemonSetApplyConfiguration) WithMaxUnavailable(value intstr.IntOrString) *RollingUpdateDaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/rollingupdatedaemonset.go","code":"// WithMaxUnavailable sets the MaxUnavailable field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MaxUnavailable field is set to the value of the last call.\nfunc (b *RollingUpdateDaemonSetApplyConfiguration) WithMaxUnavailable(value intstr.IntOrString) *RollingUpdateDaemonSetApplyConfiguration {\n\tb.MaxUnavailable = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100020371,"name":"WithMaxSurge","signature":"func (b *RollingUpdateDaemonSetApplyConfiguration) WithMaxSurge(value intstr.IntOrString) *RollingUpdateDaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/rollingupdatedaemonset.go","code":"// WithMaxSurge sets the MaxSurge field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MaxSurge field is set to the value of the last call.\nfunc (b *RollingUpdateDaemonSetApplyConfiguration) WithMaxSurge(value intstr.IntOrString) *RollingUpdateDaemonSetApplyConfiguration {\n\tb.MaxSurge = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100020372,"name":"RollingUpdateDeployment","signature":"func RollingUpdateDeployment() *RollingUpdateDeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/rollingupdatedeployment.go","code":"// RollingUpdateDeploymentApplyConfiguration constructs an declarative configuration of the RollingUpdateDeployment type for use with\n// apply.\nfunc RollingUpdateDeployment() *RollingUpdateDeploymentApplyConfiguration {\n\treturn \u0026RollingUpdateDeploymentApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100020373,"name":"WithMaxUnavailable","signature":"func (b *RollingUpdateDeploymentApplyConfiguration) WithMaxUnavailable(value intstr.IntOrString) *RollingUpdateDeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/rollingupdatedeployment.go","code":"// WithMaxUnavailable sets the MaxUnavailable field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MaxUnavailable field is set to the value of the last call.\nfunc (b *RollingUpdateDeploymentApplyConfiguration) WithMaxUnavailable(value intstr.IntOrString) *RollingUpdateDeploymentApplyConfiguration {\n\tb.MaxUnavailable = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100020374,"name":"WithMaxSurge","signature":"func (b *RollingUpdateDeploymentApplyConfiguration) WithMaxSurge(value intstr.IntOrString) *RollingUpdateDeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/rollingupdatedeployment.go","code":"// WithMaxSurge sets the MaxSurge field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MaxSurge field is set to the value of the last call.\nfunc (b *RollingUpdateDeploymentApplyConfiguration) WithMaxSurge(value intstr.IntOrString) *RollingUpdateDeploymentApplyConfiguration {\n\tb.MaxSurge = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100020375,"name":"Scale","signature":"func Scale() *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/scale.go","code":"// ScaleApplyConfiguration constructs an declarative configuration of the Scale type for use with\n// apply.\nfunc Scale() *ScaleApplyConfiguration {\n\tb := \u0026ScaleApplyConfiguration{}\n\tb.WithKind(\"Scale\")\n\tb.WithAPIVersion(\"apps/v1beta2\")\n\treturn b\n}","line":{"from":37,"to":44}} {"id":100020376,"name":"WithKind","signature":"func (b *ScaleApplyConfiguration) WithKind(value string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/scale.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithKind(value string) *ScaleApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100020377,"name":"WithAPIVersion","signature":"func (b *ScaleApplyConfiguration) WithAPIVersion(value string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/scale.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithAPIVersion(value string) *ScaleApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":54,"to":60}} {"id":100020378,"name":"WithName","signature":"func (b *ScaleApplyConfiguration) WithName(value string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/scale.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithName(value string) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":62,"to":69}} {"id":100020379,"name":"WithGenerateName","signature":"func (b *ScaleApplyConfiguration) WithGenerateName(value string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/scale.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithGenerateName(value string) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":71,"to":78}} {"id":100020380,"name":"WithNamespace","signature":"func (b *ScaleApplyConfiguration) WithNamespace(value string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/scale.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithNamespace(value string) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":80,"to":87}} {"id":100020381,"name":"WithUID","signature":"func (b *ScaleApplyConfiguration) WithUID(value types.UID) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/scale.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithUID(value types.UID) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":89,"to":96}} {"id":100020382,"name":"WithResourceVersion","signature":"func (b *ScaleApplyConfiguration) WithResourceVersion(value string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/scale.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithResourceVersion(value string) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":98,"to":105}} {"id":100020383,"name":"WithGeneration","signature":"func (b *ScaleApplyConfiguration) WithGeneration(value int64) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/scale.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithGeneration(value int64) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":107,"to":114}} {"id":100020384,"name":"WithCreationTimestamp","signature":"func (b *ScaleApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/scale.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":116,"to":123}} {"id":100020385,"name":"WithDeletionTimestamp","signature":"func (b *ScaleApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/scale.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":125,"to":132}} {"id":100020386,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ScaleApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/scale.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":134,"to":141}} {"id":100020387,"name":"WithLabels","signature":"func (b *ScaleApplyConfiguration) WithLabels(entries map[string]string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/scale.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ScaleApplyConfiguration) WithLabels(entries map[string]string) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":143,"to":156}} {"id":100020388,"name":"WithAnnotations","signature":"func (b *ScaleApplyConfiguration) WithAnnotations(entries map[string]string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/scale.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ScaleApplyConfiguration) WithAnnotations(entries map[string]string) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":158,"to":171}} {"id":100020389,"name":"WithOwnerReferences","signature":"func (b *ScaleApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/scale.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ScaleApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":173,"to":185}} {"id":100020390,"name":"WithFinalizers","signature":"func (b *ScaleApplyConfiguration) WithFinalizers(values ...string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/scale.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ScaleApplyConfiguration) WithFinalizers(values ...string) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":187,"to":196}} {"id":100020391,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ScaleApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/scale.go","code":"func (b *ScaleApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":198,"to":202}} {"id":100020392,"name":"WithSpec","signature":"func (b *ScaleApplyConfiguration) WithSpec(value v1beta2.ScaleSpec) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/scale.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithSpec(value v1beta2.ScaleSpec) *ScaleApplyConfiguration {\n\tb.Spec = \u0026value\n\treturn b\n}","line":{"from":204,"to":210}} {"id":100020393,"name":"WithStatus","signature":"func (b *ScaleApplyConfiguration) WithStatus(value v1beta2.ScaleStatus) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/scale.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithStatus(value v1beta2.ScaleStatus) *ScaleApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":212,"to":218}} {"id":100020394,"name":"StatefulSet","signature":"func StatefulSet(name, namespace string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulset.go","code":"// StatefulSet constructs an declarative configuration of the StatefulSet type for use with\n// apply.\nfunc StatefulSet(name, namespace string) *StatefulSetApplyConfiguration {\n\tb := \u0026StatefulSetApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"StatefulSet\")\n\tb.WithAPIVersion(\"apps/v1beta2\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100020395,"name":"ExtractStatefulSet","signature":"func ExtractStatefulSet(statefulSet *appsv1beta2.StatefulSet, fieldManager string) (*StatefulSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulset.go","code":"// ExtractStatefulSet extracts the applied configuration owned by fieldManager from\n// statefulSet. If no managedFields are found in statefulSet for fieldManager, a\n// StatefulSetApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// statefulSet must be a unmodified StatefulSet API object that was retrieved from the Kubernetes API.\n// ExtractStatefulSet provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractStatefulSet(statefulSet *appsv1beta2.StatefulSet, fieldManager string) (*StatefulSetApplyConfiguration, error) {\n\treturn extractStatefulSet(statefulSet, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100020396,"name":"ExtractStatefulSetStatus","signature":"func ExtractStatefulSetStatus(statefulSet *appsv1beta2.StatefulSet, fieldManager string) (*StatefulSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulset.go","code":"// ExtractStatefulSetStatus is the same as ExtractStatefulSet except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractStatefulSetStatus(statefulSet *appsv1beta2.StatefulSet, fieldManager string) (*StatefulSetApplyConfiguration, error) {\n\treturn extractStatefulSet(statefulSet, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100020397,"name":"extractStatefulSet","signature":"func extractStatefulSet(statefulSet *appsv1beta2.StatefulSet, fieldManager string, subresource string) (*StatefulSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulset.go","code":"func extractStatefulSet(statefulSet *appsv1beta2.StatefulSet, fieldManager string, subresource string) (*StatefulSetApplyConfiguration, error) {\n\tb := \u0026StatefulSetApplyConfiguration{}\n\terr := managedfields.ExtractInto(statefulSet, internal.Parser().Type(\"io.k8s.api.apps.v1beta2.StatefulSet\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(statefulSet.Name)\n\tb.WithNamespace(statefulSet.Namespace)\n\n\tb.WithKind(\"StatefulSet\")\n\tb.WithAPIVersion(\"apps/v1beta2\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100020398,"name":"WithKind","signature":"func (b *StatefulSetApplyConfiguration) WithKind(value string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulset.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithKind(value string) *StatefulSetApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100020399,"name":"WithAPIVersion","signature":"func (b *StatefulSetApplyConfiguration) WithAPIVersion(value string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulset.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithAPIVersion(value string) *StatefulSetApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100020400,"name":"WithName","signature":"func (b *StatefulSetApplyConfiguration) WithName(value string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulset.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithName(value string) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100020401,"name":"WithGenerateName","signature":"func (b *StatefulSetApplyConfiguration) WithGenerateName(value string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulset.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithGenerateName(value string) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100020402,"name":"WithNamespace","signature":"func (b *StatefulSetApplyConfiguration) WithNamespace(value string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulset.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithNamespace(value string) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100020403,"name":"WithUID","signature":"func (b *StatefulSetApplyConfiguration) WithUID(value types.UID) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulset.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithUID(value types.UID) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100020404,"name":"WithResourceVersion","signature":"func (b *StatefulSetApplyConfiguration) WithResourceVersion(value string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulset.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithResourceVersion(value string) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100020405,"name":"WithGeneration","signature":"func (b *StatefulSetApplyConfiguration) WithGeneration(value int64) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulset.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithGeneration(value int64) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100020406,"name":"WithCreationTimestamp","signature":"func (b *StatefulSetApplyConfiguration) WithCreationTimestamp(value metav1.Time) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulset.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithCreationTimestamp(value metav1.Time) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100020407,"name":"WithDeletionTimestamp","signature":"func (b *StatefulSetApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulset.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100020408,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *StatefulSetApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulset.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100020409,"name":"WithLabels","signature":"func (b *StatefulSetApplyConfiguration) WithLabels(entries map[string]string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulset.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *StatefulSetApplyConfiguration) WithLabels(entries map[string]string) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100020410,"name":"WithAnnotations","signature":"func (b *StatefulSetApplyConfiguration) WithAnnotations(entries map[string]string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulset.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *StatefulSetApplyConfiguration) WithAnnotations(entries map[string]string) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100020411,"name":"WithOwnerReferences","signature":"func (b *StatefulSetApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulset.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *StatefulSetApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100020412,"name":"WithFinalizers","signature":"func (b *StatefulSetApplyConfiguration) WithFinalizers(values ...string) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulset.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *StatefulSetApplyConfiguration) WithFinalizers(values ...string) *StatefulSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100020413,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *StatefulSetApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulset.go","code":"func (b *StatefulSetApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100020414,"name":"WithSpec","signature":"func (b *StatefulSetApplyConfiguration) WithSpec(value *StatefulSetSpecApplyConfiguration) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulset.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithSpec(value *StatefulSetSpecApplyConfiguration) *StatefulSetApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100020415,"name":"WithStatus","signature":"func (b *StatefulSetApplyConfiguration) WithStatus(value *StatefulSetStatusApplyConfiguration) *StatefulSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulset.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *StatefulSetApplyConfiguration) WithStatus(value *StatefulSetStatusApplyConfiguration) *StatefulSetApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100020416,"name":"StatefulSetCondition","signature":"func StatefulSetCondition() *StatefulSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetcondition.go","code":"// StatefulSetConditionApplyConfiguration constructs an declarative configuration of the StatefulSetCondition type for use with\n// apply.\nfunc StatefulSetCondition() *StatefulSetConditionApplyConfiguration {\n\treturn \u0026StatefulSetConditionApplyConfiguration{}\n}","line":{"from":37,"to":41}} {"id":100020417,"name":"WithType","signature":"func (b *StatefulSetConditionApplyConfiguration) WithType(value v1beta2.StatefulSetConditionType) *StatefulSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetcondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *StatefulSetConditionApplyConfiguration) WithType(value v1beta2.StatefulSetConditionType) *StatefulSetConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100020418,"name":"WithStatus","signature":"func (b *StatefulSetConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *StatefulSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetcondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *StatefulSetConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *StatefulSetConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100020419,"name":"WithLastTransitionTime","signature":"func (b *StatefulSetConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *StatefulSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetcondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *StatefulSetConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *StatefulSetConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":59,"to":65}} {"id":100020420,"name":"WithReason","signature":"func (b *StatefulSetConditionApplyConfiguration) WithReason(value string) *StatefulSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetcondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *StatefulSetConditionApplyConfiguration) WithReason(value string) *StatefulSetConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100020421,"name":"WithMessage","signature":"func (b *StatefulSetConditionApplyConfiguration) WithMessage(value string) *StatefulSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetcondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *StatefulSetConditionApplyConfiguration) WithMessage(value string) *StatefulSetConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":75,"to":81}} {"id":100020422,"name":"StatefulSetOrdinals","signature":"func StatefulSetOrdinals() *StatefulSetOrdinalsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetordinals.go","code":"// StatefulSetOrdinalsApplyConfiguration constructs an declarative configuration of the StatefulSetOrdinals type for use with\n// apply.\nfunc StatefulSetOrdinals() *StatefulSetOrdinalsApplyConfiguration {\n\treturn \u0026StatefulSetOrdinalsApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100020423,"name":"WithStart","signature":"func (b *StatefulSetOrdinalsApplyConfiguration) WithStart(value int32) *StatefulSetOrdinalsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetordinals.go","code":"// WithStart sets the Start field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Start field is set to the value of the last call.\nfunc (b *StatefulSetOrdinalsApplyConfiguration) WithStart(value int32) *StatefulSetOrdinalsApplyConfiguration {\n\tb.Start = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100020424,"name":"StatefulSetPersistentVolumeClaimRetentionPolicy","signature":"func StatefulSetPersistentVolumeClaimRetentionPolicy() *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetpersistentvolumeclaimretentionpolicy.go","code":"// StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration constructs an declarative configuration of the StatefulSetPersistentVolumeClaimRetentionPolicy type for use with\n// apply.\nfunc StatefulSetPersistentVolumeClaimRetentionPolicy() *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration {\n\treturn \u0026StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100020425,"name":"WithWhenDeleted","signature":"func (b *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration) WithWhenDeleted(value v1beta2.PersistentVolumeClaimRetentionPolicyType) *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetpersistentvolumeclaimretentionpolicy.go","code":"// WithWhenDeleted sets the WhenDeleted field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the WhenDeleted field is set to the value of the last call.\nfunc (b *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration) WithWhenDeleted(value v1beta2.PersistentVolumeClaimRetentionPolicyType) *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration {\n\tb.WhenDeleted = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100020426,"name":"WithWhenScaled","signature":"func (b *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration) WithWhenScaled(value v1beta2.PersistentVolumeClaimRetentionPolicyType) *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetpersistentvolumeclaimretentionpolicy.go","code":"// WithWhenScaled sets the WhenScaled field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the WhenScaled field is set to the value of the last call.\nfunc (b *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration) WithWhenScaled(value v1beta2.PersistentVolumeClaimRetentionPolicyType) *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration {\n\tb.WhenScaled = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100020427,"name":"StatefulSetSpec","signature":"func StatefulSetSpec() *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetspec.go","code":"// StatefulSetSpecApplyConfiguration constructs an declarative configuration of the StatefulSetSpec type for use with\n// apply.\nfunc StatefulSetSpec() *StatefulSetSpecApplyConfiguration {\n\treturn \u0026StatefulSetSpecApplyConfiguration{}\n}","line":{"from":43,"to":47}} {"id":100020428,"name":"WithReplicas","signature":"func (b *StatefulSetSpecApplyConfiguration) WithReplicas(value int32) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetspec.go","code":"// WithReplicas sets the Replicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Replicas field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithReplicas(value int32) *StatefulSetSpecApplyConfiguration {\n\tb.Replicas = \u0026value\n\treturn b\n}","line":{"from":49,"to":55}} {"id":100020429,"name":"WithSelector","signature":"func (b *StatefulSetSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetspec.go","code":"// WithSelector sets the Selector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Selector field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *StatefulSetSpecApplyConfiguration {\n\tb.Selector = value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100020430,"name":"WithTemplate","signature":"func (b *StatefulSetSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetspec.go","code":"// WithTemplate sets the Template field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Template field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *StatefulSetSpecApplyConfiguration {\n\tb.Template = value\n\treturn b\n}","line":{"from":65,"to":71}} {"id":100020431,"name":"WithVolumeClaimTemplates","signature":"func (b *StatefulSetSpecApplyConfiguration) WithVolumeClaimTemplates(values ...*corev1.PersistentVolumeClaimApplyConfiguration) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetspec.go","code":"// WithVolumeClaimTemplates adds the given value to the VolumeClaimTemplates field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the VolumeClaimTemplates field.\nfunc (b *StatefulSetSpecApplyConfiguration) WithVolumeClaimTemplates(values ...*corev1.PersistentVolumeClaimApplyConfiguration) *StatefulSetSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithVolumeClaimTemplates\")\n\t\t}\n\t\tb.VolumeClaimTemplates = append(b.VolumeClaimTemplates, *values[i])\n\t}\n\treturn b\n}","line":{"from":73,"to":84}} {"id":100020432,"name":"WithServiceName","signature":"func (b *StatefulSetSpecApplyConfiguration) WithServiceName(value string) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetspec.go","code":"// WithServiceName sets the ServiceName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ServiceName field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithServiceName(value string) *StatefulSetSpecApplyConfiguration {\n\tb.ServiceName = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100020433,"name":"WithPodManagementPolicy","signature":"func (b *StatefulSetSpecApplyConfiguration) WithPodManagementPolicy(value v1beta2.PodManagementPolicyType) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetspec.go","code":"// WithPodManagementPolicy sets the PodManagementPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PodManagementPolicy field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithPodManagementPolicy(value v1beta2.PodManagementPolicyType) *StatefulSetSpecApplyConfiguration {\n\tb.PodManagementPolicy = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100020434,"name":"WithUpdateStrategy","signature":"func (b *StatefulSetSpecApplyConfiguration) WithUpdateStrategy(value *StatefulSetUpdateStrategyApplyConfiguration) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetspec.go","code":"// WithUpdateStrategy sets the UpdateStrategy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UpdateStrategy field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithUpdateStrategy(value *StatefulSetUpdateStrategyApplyConfiguration) *StatefulSetSpecApplyConfiguration {\n\tb.UpdateStrategy = value\n\treturn b\n}","line":{"from":102,"to":108}} {"id":100020435,"name":"WithRevisionHistoryLimit","signature":"func (b *StatefulSetSpecApplyConfiguration) WithRevisionHistoryLimit(value int32) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetspec.go","code":"// WithRevisionHistoryLimit sets the RevisionHistoryLimit field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RevisionHistoryLimit field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithRevisionHistoryLimit(value int32) *StatefulSetSpecApplyConfiguration {\n\tb.RevisionHistoryLimit = \u0026value\n\treturn b\n}","line":{"from":110,"to":116}} {"id":100020436,"name":"WithMinReadySeconds","signature":"func (b *StatefulSetSpecApplyConfiguration) WithMinReadySeconds(value int32) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetspec.go","code":"// WithMinReadySeconds sets the MinReadySeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MinReadySeconds field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithMinReadySeconds(value int32) *StatefulSetSpecApplyConfiguration {\n\tb.MinReadySeconds = \u0026value\n\treturn b\n}","line":{"from":118,"to":124}} {"id":100020437,"name":"WithPersistentVolumeClaimRetentionPolicy","signature":"func (b *StatefulSetSpecApplyConfiguration) WithPersistentVolumeClaimRetentionPolicy(value *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetspec.go","code":"// WithPersistentVolumeClaimRetentionPolicy sets the PersistentVolumeClaimRetentionPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PersistentVolumeClaimRetentionPolicy field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithPersistentVolumeClaimRetentionPolicy(value *StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration) *StatefulSetSpecApplyConfiguration {\n\tb.PersistentVolumeClaimRetentionPolicy = value\n\treturn b\n}","line":{"from":126,"to":132}} {"id":100020438,"name":"WithOrdinals","signature":"func (b *StatefulSetSpecApplyConfiguration) WithOrdinals(value *StatefulSetOrdinalsApplyConfiguration) *StatefulSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetspec.go","code":"// WithOrdinals sets the Ordinals field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Ordinals field is set to the value of the last call.\nfunc (b *StatefulSetSpecApplyConfiguration) WithOrdinals(value *StatefulSetOrdinalsApplyConfiguration) *StatefulSetSpecApplyConfiguration {\n\tb.Ordinals = value\n\treturn b\n}","line":{"from":134,"to":140}} {"id":100020439,"name":"StatefulSetStatus","signature":"func StatefulSetStatus() *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetstatus.go","code":"// StatefulSetStatusApplyConfiguration constructs an declarative configuration of the StatefulSetStatus type for use with\n// apply.\nfunc StatefulSetStatus() *StatefulSetStatusApplyConfiguration {\n\treturn \u0026StatefulSetStatusApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100020440,"name":"WithObservedGeneration","signature":"func (b *StatefulSetStatusApplyConfiguration) WithObservedGeneration(value int64) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetstatus.go","code":"// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObservedGeneration field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithObservedGeneration(value int64) *StatefulSetStatusApplyConfiguration {\n\tb.ObservedGeneration = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020441,"name":"WithReplicas","signature":"func (b *StatefulSetStatusApplyConfiguration) WithReplicas(value int32) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetstatus.go","code":"// WithReplicas sets the Replicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Replicas field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithReplicas(value int32) *StatefulSetStatusApplyConfiguration {\n\tb.Replicas = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100020442,"name":"WithReadyReplicas","signature":"func (b *StatefulSetStatusApplyConfiguration) WithReadyReplicas(value int32) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetstatus.go","code":"// WithReadyReplicas sets the ReadyReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadyReplicas field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithReadyReplicas(value int32) *StatefulSetStatusApplyConfiguration {\n\tb.ReadyReplicas = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100020443,"name":"WithCurrentReplicas","signature":"func (b *StatefulSetStatusApplyConfiguration) WithCurrentReplicas(value int32) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetstatus.go","code":"// WithCurrentReplicas sets the CurrentReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CurrentReplicas field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithCurrentReplicas(value int32) *StatefulSetStatusApplyConfiguration {\n\tb.CurrentReplicas = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100020444,"name":"WithUpdatedReplicas","signature":"func (b *StatefulSetStatusApplyConfiguration) WithUpdatedReplicas(value int32) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetstatus.go","code":"// WithUpdatedReplicas sets the UpdatedReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UpdatedReplicas field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithUpdatedReplicas(value int32) *StatefulSetStatusApplyConfiguration {\n\tb.UpdatedReplicas = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100020445,"name":"WithCurrentRevision","signature":"func (b *StatefulSetStatusApplyConfiguration) WithCurrentRevision(value string) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetstatus.go","code":"// WithCurrentRevision sets the CurrentRevision field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CurrentRevision field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithCurrentRevision(value string) *StatefulSetStatusApplyConfiguration {\n\tb.CurrentRevision = \u0026value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100020446,"name":"WithUpdateRevision","signature":"func (b *StatefulSetStatusApplyConfiguration) WithUpdateRevision(value string) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetstatus.go","code":"// WithUpdateRevision sets the UpdateRevision field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UpdateRevision field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithUpdateRevision(value string) *StatefulSetStatusApplyConfiguration {\n\tb.UpdateRevision = \u0026value\n\treturn b\n}","line":{"from":90,"to":96}} {"id":100020447,"name":"WithCollisionCount","signature":"func (b *StatefulSetStatusApplyConfiguration) WithCollisionCount(value int32) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetstatus.go","code":"// WithCollisionCount sets the CollisionCount field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CollisionCount field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithCollisionCount(value int32) *StatefulSetStatusApplyConfiguration {\n\tb.CollisionCount = \u0026value\n\treturn b\n}","line":{"from":98,"to":104}} {"id":100020448,"name":"WithConditions","signature":"func (b *StatefulSetStatusApplyConfiguration) WithConditions(values ...*StatefulSetConditionApplyConfiguration) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *StatefulSetStatusApplyConfiguration) WithConditions(values ...*StatefulSetConditionApplyConfiguration) *StatefulSetStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":106,"to":117}} {"id":100020449,"name":"WithAvailableReplicas","signature":"func (b *StatefulSetStatusApplyConfiguration) WithAvailableReplicas(value int32) *StatefulSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/apps/v1beta2/statefulsetstatus.go","code":"// WithAvailableReplicas sets the AvailableReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AvailableReplicas field is set to the value of the last call.\nfunc (b *StatefulSetStatusApplyConfiguration) WithAvailableReplicas(value int32) *StatefulSetStatusApplyConfiguration {\n\tb.AvailableReplicas = \u0026value\n\treturn b\n}","line":{"from":119,"to":125}} {"id":100020450,"name":"CrossVersionObjectReference","signature":"func CrossVersionObjectReference() *CrossVersionObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/crossversionobjectreference.go","code":"// CrossVersionObjectReferenceApplyConfiguration constructs an declarative configuration of the CrossVersionObjectReference type for use with\n// apply.\nfunc CrossVersionObjectReference() *CrossVersionObjectReferenceApplyConfiguration {\n\treturn \u0026CrossVersionObjectReferenceApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100020451,"name":"WithKind","signature":"func (b *CrossVersionObjectReferenceApplyConfiguration) WithKind(value string) *CrossVersionObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/crossversionobjectreference.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *CrossVersionObjectReferenceApplyConfiguration) WithKind(value string) *CrossVersionObjectReferenceApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100020452,"name":"WithName","signature":"func (b *CrossVersionObjectReferenceApplyConfiguration) WithName(value string) *CrossVersionObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/crossversionobjectreference.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *CrossVersionObjectReferenceApplyConfiguration) WithName(value string) *CrossVersionObjectReferenceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100020453,"name":"WithAPIVersion","signature":"func (b *CrossVersionObjectReferenceApplyConfiguration) WithAPIVersion(value string) *CrossVersionObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/crossversionobjectreference.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *CrossVersionObjectReferenceApplyConfiguration) WithAPIVersion(value string) *CrossVersionObjectReferenceApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100020454,"name":"HorizontalPodAutoscaler","signature":"func HorizontalPodAutoscaler(name, namespace string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscaler.go","code":"// HorizontalPodAutoscaler constructs an declarative configuration of the HorizontalPodAutoscaler type for use with\n// apply.\nfunc HorizontalPodAutoscaler(name, namespace string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb := \u0026HorizontalPodAutoscalerApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"HorizontalPodAutoscaler\")\n\tb.WithAPIVersion(\"autoscaling/v1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100020455,"name":"ExtractHorizontalPodAutoscaler","signature":"func ExtractHorizontalPodAutoscaler(horizontalPodAutoscaler *apiautoscalingv1.HorizontalPodAutoscaler, fieldManager string) (*HorizontalPodAutoscalerApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscaler.go","code":"// ExtractHorizontalPodAutoscaler extracts the applied configuration owned by fieldManager from\n// horizontalPodAutoscaler. If no managedFields are found in horizontalPodAutoscaler for fieldManager, a\n// HorizontalPodAutoscalerApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// horizontalPodAutoscaler must be a unmodified HorizontalPodAutoscaler API object that was retrieved from the Kubernetes API.\n// ExtractHorizontalPodAutoscaler provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractHorizontalPodAutoscaler(horizontalPodAutoscaler *apiautoscalingv1.HorizontalPodAutoscaler, fieldManager string) (*HorizontalPodAutoscalerApplyConfiguration, error) {\n\treturn extractHorizontalPodAutoscaler(horizontalPodAutoscaler, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100020456,"name":"ExtractHorizontalPodAutoscalerStatus","signature":"func ExtractHorizontalPodAutoscalerStatus(horizontalPodAutoscaler *apiautoscalingv1.HorizontalPodAutoscaler, fieldManager string) (*HorizontalPodAutoscalerApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscaler.go","code":"// ExtractHorizontalPodAutoscalerStatus is the same as ExtractHorizontalPodAutoscaler except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractHorizontalPodAutoscalerStatus(horizontalPodAutoscaler *apiautoscalingv1.HorizontalPodAutoscaler, fieldManager string) (*HorizontalPodAutoscalerApplyConfiguration, error) {\n\treturn extractHorizontalPodAutoscaler(horizontalPodAutoscaler, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100020457,"name":"extractHorizontalPodAutoscaler","signature":"func extractHorizontalPodAutoscaler(horizontalPodAutoscaler *apiautoscalingv1.HorizontalPodAutoscaler, fieldManager string, subresource string) (*HorizontalPodAutoscalerApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscaler.go","code":"func extractHorizontalPodAutoscaler(horizontalPodAutoscaler *apiautoscalingv1.HorizontalPodAutoscaler, fieldManager string, subresource string) (*HorizontalPodAutoscalerApplyConfiguration, error) {\n\tb := \u0026HorizontalPodAutoscalerApplyConfiguration{}\n\terr := managedfields.ExtractInto(horizontalPodAutoscaler, internal.Parser().Type(\"io.k8s.api.autoscaling.v1.HorizontalPodAutoscaler\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(horizontalPodAutoscaler.Name)\n\tb.WithNamespace(horizontalPodAutoscaler.Namespace)\n\n\tb.WithKind(\"HorizontalPodAutoscaler\")\n\tb.WithAPIVersion(\"autoscaling/v1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100020458,"name":"WithKind","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithKind(value string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscaler.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithKind(value string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100020459,"name":"WithAPIVersion","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithAPIVersion(value string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscaler.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithAPIVersion(value string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100020460,"name":"WithName","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithName(value string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscaler.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithName(value string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100020461,"name":"WithGenerateName","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithGenerateName(value string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscaler.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithGenerateName(value string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100020462,"name":"WithNamespace","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithNamespace(value string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscaler.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithNamespace(value string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100020463,"name":"WithUID","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithUID(value types.UID) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscaler.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithUID(value types.UID) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100020464,"name":"WithResourceVersion","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithResourceVersion(value string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscaler.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithResourceVersion(value string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100020465,"name":"WithGeneration","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithGeneration(value int64) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscaler.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithGeneration(value int64) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100020466,"name":"WithCreationTimestamp","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithCreationTimestamp(value metav1.Time) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscaler.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithCreationTimestamp(value metav1.Time) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100020467,"name":"WithDeletionTimestamp","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscaler.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100020468,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscaler.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100020469,"name":"WithLabels","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithLabels(entries map[string]string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscaler.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithLabels(entries map[string]string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100020470,"name":"WithAnnotations","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithAnnotations(entries map[string]string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscaler.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithAnnotations(entries map[string]string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100020471,"name":"WithOwnerReferences","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscaler.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100020472,"name":"WithFinalizers","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithFinalizers(values ...string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscaler.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithFinalizers(values ...string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100020473,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscaler.go","code":"func (b *HorizontalPodAutoscalerApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100020474,"name":"WithSpec","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithSpec(value *HorizontalPodAutoscalerSpecApplyConfiguration) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscaler.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithSpec(value *HorizontalPodAutoscalerSpecApplyConfiguration) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100020475,"name":"WithStatus","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithStatus(value *HorizontalPodAutoscalerStatusApplyConfiguration) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscaler.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithStatus(value *HorizontalPodAutoscalerStatusApplyConfiguration) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100020476,"name":"HorizontalPodAutoscalerSpec","signature":"func HorizontalPodAutoscalerSpec() *HorizontalPodAutoscalerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscalerspec.go","code":"// HorizontalPodAutoscalerSpecApplyConfiguration constructs an declarative configuration of the HorizontalPodAutoscalerSpec type for use with\n// apply.\nfunc HorizontalPodAutoscalerSpec() *HorizontalPodAutoscalerSpecApplyConfiguration {\n\treturn \u0026HorizontalPodAutoscalerSpecApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100020477,"name":"WithScaleTargetRef","signature":"func (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithScaleTargetRef(value *CrossVersionObjectReferenceApplyConfiguration) *HorizontalPodAutoscalerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscalerspec.go","code":"// WithScaleTargetRef sets the ScaleTargetRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ScaleTargetRef field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithScaleTargetRef(value *CrossVersionObjectReferenceApplyConfiguration) *HorizontalPodAutoscalerSpecApplyConfiguration {\n\tb.ScaleTargetRef = value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100020478,"name":"WithMinReplicas","signature":"func (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithMinReplicas(value int32) *HorizontalPodAutoscalerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscalerspec.go","code":"// WithMinReplicas sets the MinReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MinReplicas field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithMinReplicas(value int32) *HorizontalPodAutoscalerSpecApplyConfiguration {\n\tb.MinReplicas = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100020479,"name":"WithMaxReplicas","signature":"func (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithMaxReplicas(value int32) *HorizontalPodAutoscalerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscalerspec.go","code":"// WithMaxReplicas sets the MaxReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MaxReplicas field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithMaxReplicas(value int32) *HorizontalPodAutoscalerSpecApplyConfiguration {\n\tb.MaxReplicas = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100020480,"name":"WithTargetCPUUtilizationPercentage","signature":"func (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithTargetCPUUtilizationPercentage(value int32) *HorizontalPodAutoscalerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscalerspec.go","code":"// WithTargetCPUUtilizationPercentage sets the TargetCPUUtilizationPercentage field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TargetCPUUtilizationPercentage field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithTargetCPUUtilizationPercentage(value int32) *HorizontalPodAutoscalerSpecApplyConfiguration {\n\tb.TargetCPUUtilizationPercentage = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100020481,"name":"HorizontalPodAutoscalerStatus","signature":"func HorizontalPodAutoscalerStatus() *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscalerstatus.go","code":"// HorizontalPodAutoscalerStatusApplyConfiguration constructs an declarative configuration of the HorizontalPodAutoscalerStatus type for use with\n// apply.\nfunc HorizontalPodAutoscalerStatus() *HorizontalPodAutoscalerStatusApplyConfiguration {\n\treturn \u0026HorizontalPodAutoscalerStatusApplyConfiguration{}\n}","line":{"from":35,"to":39}} {"id":100020482,"name":"WithObservedGeneration","signature":"func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithObservedGeneration(value int64) *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscalerstatus.go","code":"// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObservedGeneration field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithObservedGeneration(value int64) *HorizontalPodAutoscalerStatusApplyConfiguration {\n\tb.ObservedGeneration = \u0026value\n\treturn b\n}","line":{"from":41,"to":47}} {"id":100020483,"name":"WithLastScaleTime","signature":"func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithLastScaleTime(value v1.Time) *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscalerstatus.go","code":"// WithLastScaleTime sets the LastScaleTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastScaleTime field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithLastScaleTime(value v1.Time) *HorizontalPodAutoscalerStatusApplyConfiguration {\n\tb.LastScaleTime = \u0026value\n\treturn b\n}","line":{"from":49,"to":55}} {"id":100020484,"name":"WithCurrentReplicas","signature":"func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithCurrentReplicas(value int32) *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscalerstatus.go","code":"// WithCurrentReplicas sets the CurrentReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CurrentReplicas field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithCurrentReplicas(value int32) *HorizontalPodAutoscalerStatusApplyConfiguration {\n\tb.CurrentReplicas = \u0026value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100020485,"name":"WithDesiredReplicas","signature":"func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithDesiredReplicas(value int32) *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscalerstatus.go","code":"// WithDesiredReplicas sets the DesiredReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DesiredReplicas field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithDesiredReplicas(value int32) *HorizontalPodAutoscalerStatusApplyConfiguration {\n\tb.DesiredReplicas = \u0026value\n\treturn b\n}","line":{"from":65,"to":71}} {"id":100020486,"name":"WithCurrentCPUUtilizationPercentage","signature":"func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithCurrentCPUUtilizationPercentage(value int32) *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/horizontalpodautoscalerstatus.go","code":"// WithCurrentCPUUtilizationPercentage sets the CurrentCPUUtilizationPercentage field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CurrentCPUUtilizationPercentage field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithCurrentCPUUtilizationPercentage(value int32) *HorizontalPodAutoscalerStatusApplyConfiguration {\n\tb.CurrentCPUUtilizationPercentage = \u0026value\n\treturn b\n}","line":{"from":73,"to":79}} {"id":100020487,"name":"Scale","signature":"func Scale() *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/scale.go","code":"// ScaleApplyConfiguration constructs an declarative configuration of the Scale type for use with\n// apply.\nfunc Scale() *ScaleApplyConfiguration {\n\tb := \u0026ScaleApplyConfiguration{}\n\tb.WithKind(\"Scale\")\n\tb.WithAPIVersion(\"autoscaling/v1\")\n\treturn b\n}","line":{"from":36,"to":43}} {"id":100020488,"name":"WithKind","signature":"func (b *ScaleApplyConfiguration) WithKind(value string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/scale.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithKind(value string) *ScaleApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":45,"to":51}} {"id":100020489,"name":"WithAPIVersion","signature":"func (b *ScaleApplyConfiguration) WithAPIVersion(value string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/scale.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithAPIVersion(value string) *ScaleApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":53,"to":59}} {"id":100020490,"name":"WithName","signature":"func (b *ScaleApplyConfiguration) WithName(value string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/scale.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithName(value string) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":61,"to":68}} {"id":100020491,"name":"WithGenerateName","signature":"func (b *ScaleApplyConfiguration) WithGenerateName(value string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/scale.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithGenerateName(value string) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":70,"to":77}} {"id":100020492,"name":"WithNamespace","signature":"func (b *ScaleApplyConfiguration) WithNamespace(value string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/scale.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithNamespace(value string) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":79,"to":86}} {"id":100020493,"name":"WithUID","signature":"func (b *ScaleApplyConfiguration) WithUID(value types.UID) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/scale.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithUID(value types.UID) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":88,"to":95}} {"id":100020494,"name":"WithResourceVersion","signature":"func (b *ScaleApplyConfiguration) WithResourceVersion(value string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/scale.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithResourceVersion(value string) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":97,"to":104}} {"id":100020495,"name":"WithGeneration","signature":"func (b *ScaleApplyConfiguration) WithGeneration(value int64) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/scale.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithGeneration(value int64) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":106,"to":113}} {"id":100020496,"name":"WithCreationTimestamp","signature":"func (b *ScaleApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/scale.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":115,"to":122}} {"id":100020497,"name":"WithDeletionTimestamp","signature":"func (b *ScaleApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/scale.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":124,"to":131}} {"id":100020498,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ScaleApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/scale.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":133,"to":140}} {"id":100020499,"name":"WithLabels","signature":"func (b *ScaleApplyConfiguration) WithLabels(entries map[string]string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/scale.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ScaleApplyConfiguration) WithLabels(entries map[string]string) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":142,"to":155}} {"id":100020500,"name":"WithAnnotations","signature":"func (b *ScaleApplyConfiguration) WithAnnotations(entries map[string]string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/scale.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ScaleApplyConfiguration) WithAnnotations(entries map[string]string) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":157,"to":170}} {"id":100020501,"name":"WithOwnerReferences","signature":"func (b *ScaleApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/scale.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ScaleApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":172,"to":184}} {"id":100020502,"name":"WithFinalizers","signature":"func (b *ScaleApplyConfiguration) WithFinalizers(values ...string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/scale.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ScaleApplyConfiguration) WithFinalizers(values ...string) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":186,"to":195}} {"id":100020503,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ScaleApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/scale.go","code":"func (b *ScaleApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":197,"to":201}} {"id":100020504,"name":"WithSpec","signature":"func (b *ScaleApplyConfiguration) WithSpec(value *ScaleSpecApplyConfiguration) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/scale.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithSpec(value *ScaleSpecApplyConfiguration) *ScaleApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":203,"to":209}} {"id":100020505,"name":"WithStatus","signature":"func (b *ScaleApplyConfiguration) WithStatus(value *ScaleStatusApplyConfiguration) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/scale.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithStatus(value *ScaleStatusApplyConfiguration) *ScaleApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":211,"to":217}} {"id":100020506,"name":"ScaleSpec","signature":"func ScaleSpec() *ScaleSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/scalespec.go","code":"// ScaleSpecApplyConfiguration constructs an declarative configuration of the ScaleSpec type for use with\n// apply.\nfunc ScaleSpec() *ScaleSpecApplyConfiguration {\n\treturn \u0026ScaleSpecApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100020507,"name":"WithReplicas","signature":"func (b *ScaleSpecApplyConfiguration) WithReplicas(value int32) *ScaleSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/scalespec.go","code":"// WithReplicas sets the Replicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Replicas field is set to the value of the last call.\nfunc (b *ScaleSpecApplyConfiguration) WithReplicas(value int32) *ScaleSpecApplyConfiguration {\n\tb.Replicas = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100020508,"name":"ScaleStatus","signature":"func ScaleStatus() *ScaleStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/scalestatus.go","code":"// ScaleStatusApplyConfiguration constructs an declarative configuration of the ScaleStatus type for use with\n// apply.\nfunc ScaleStatus() *ScaleStatusApplyConfiguration {\n\treturn \u0026ScaleStatusApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100020509,"name":"WithReplicas","signature":"func (b *ScaleStatusApplyConfiguration) WithReplicas(value int32) *ScaleStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/scalestatus.go","code":"// WithReplicas sets the Replicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Replicas field is set to the value of the last call.\nfunc (b *ScaleStatusApplyConfiguration) WithReplicas(value int32) *ScaleStatusApplyConfiguration {\n\tb.Replicas = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100020510,"name":"WithSelector","signature":"func (b *ScaleStatusApplyConfiguration) WithSelector(value string) *ScaleStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v1/scalestatus.go","code":"// WithSelector sets the Selector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Selector field is set to the value of the last call.\nfunc (b *ScaleStatusApplyConfiguration) WithSelector(value string) *ScaleStatusApplyConfiguration {\n\tb.Selector = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020511,"name":"ContainerResourceMetricSource","signature":"func ContainerResourceMetricSource() *ContainerResourceMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/containerresourcemetricsource.go","code":"// ContainerResourceMetricSourceApplyConfiguration constructs an declarative configuration of the ContainerResourceMetricSource type for use with\n// apply.\nfunc ContainerResourceMetricSource() *ContainerResourceMetricSourceApplyConfiguration {\n\treturn \u0026ContainerResourceMetricSourceApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100020512,"name":"WithName","signature":"func (b *ContainerResourceMetricSourceApplyConfiguration) WithName(value v1.ResourceName) *ContainerResourceMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/containerresourcemetricsource.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ContainerResourceMetricSourceApplyConfiguration) WithName(value v1.ResourceName) *ContainerResourceMetricSourceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100020513,"name":"WithTarget","signature":"func (b *ContainerResourceMetricSourceApplyConfiguration) WithTarget(value *MetricTargetApplyConfiguration) *ContainerResourceMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/containerresourcemetricsource.go","code":"// WithTarget sets the Target field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Target field is set to the value of the last call.\nfunc (b *ContainerResourceMetricSourceApplyConfiguration) WithTarget(value *MetricTargetApplyConfiguration) *ContainerResourceMetricSourceApplyConfiguration {\n\tb.Target = value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100020514,"name":"WithContainer","signature":"func (b *ContainerResourceMetricSourceApplyConfiguration) WithContainer(value string) *ContainerResourceMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/containerresourcemetricsource.go","code":"// WithContainer sets the Container field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Container field is set to the value of the last call.\nfunc (b *ContainerResourceMetricSourceApplyConfiguration) WithContainer(value string) *ContainerResourceMetricSourceApplyConfiguration {\n\tb.Container = \u0026value\n\treturn b\n}","line":{"from":55,"to":61}} {"id":100020515,"name":"ContainerResourceMetricStatus","signature":"func ContainerResourceMetricStatus() *ContainerResourceMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/containerresourcemetricstatus.go","code":"// ContainerResourceMetricStatusApplyConfiguration constructs an declarative configuration of the ContainerResourceMetricStatus type for use with\n// apply.\nfunc ContainerResourceMetricStatus() *ContainerResourceMetricStatusApplyConfiguration {\n\treturn \u0026ContainerResourceMetricStatusApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100020516,"name":"WithName","signature":"func (b *ContainerResourceMetricStatusApplyConfiguration) WithName(value v1.ResourceName) *ContainerResourceMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/containerresourcemetricstatus.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ContainerResourceMetricStatusApplyConfiguration) WithName(value v1.ResourceName) *ContainerResourceMetricStatusApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100020517,"name":"WithCurrent","signature":"func (b *ContainerResourceMetricStatusApplyConfiguration) WithCurrent(value *MetricValueStatusApplyConfiguration) *ContainerResourceMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/containerresourcemetricstatus.go","code":"// WithCurrent sets the Current field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Current field is set to the value of the last call.\nfunc (b *ContainerResourceMetricStatusApplyConfiguration) WithCurrent(value *MetricValueStatusApplyConfiguration) *ContainerResourceMetricStatusApplyConfiguration {\n\tb.Current = value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100020518,"name":"WithContainer","signature":"func (b *ContainerResourceMetricStatusApplyConfiguration) WithContainer(value string) *ContainerResourceMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/containerresourcemetricstatus.go","code":"// WithContainer sets the Container field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Container field is set to the value of the last call.\nfunc (b *ContainerResourceMetricStatusApplyConfiguration) WithContainer(value string) *ContainerResourceMetricStatusApplyConfiguration {\n\tb.Container = \u0026value\n\treturn b\n}","line":{"from":55,"to":61}} {"id":100020519,"name":"CrossVersionObjectReference","signature":"func CrossVersionObjectReference() *CrossVersionObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/crossversionobjectreference.go","code":"// CrossVersionObjectReferenceApplyConfiguration constructs an declarative configuration of the CrossVersionObjectReference type for use with\n// apply.\nfunc CrossVersionObjectReference() *CrossVersionObjectReferenceApplyConfiguration {\n\treturn \u0026CrossVersionObjectReferenceApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100020520,"name":"WithKind","signature":"func (b *CrossVersionObjectReferenceApplyConfiguration) WithKind(value string) *CrossVersionObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/crossversionobjectreference.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *CrossVersionObjectReferenceApplyConfiguration) WithKind(value string) *CrossVersionObjectReferenceApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100020521,"name":"WithName","signature":"func (b *CrossVersionObjectReferenceApplyConfiguration) WithName(value string) *CrossVersionObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/crossversionobjectreference.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *CrossVersionObjectReferenceApplyConfiguration) WithName(value string) *CrossVersionObjectReferenceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100020522,"name":"WithAPIVersion","signature":"func (b *CrossVersionObjectReferenceApplyConfiguration) WithAPIVersion(value string) *CrossVersionObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/crossversionobjectreference.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *CrossVersionObjectReferenceApplyConfiguration) WithAPIVersion(value string) *CrossVersionObjectReferenceApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100020523,"name":"ExternalMetricSource","signature":"func ExternalMetricSource() *ExternalMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/externalmetricsource.go","code":"// ExternalMetricSourceApplyConfiguration constructs an declarative configuration of the ExternalMetricSource type for use with\n// apply.\nfunc ExternalMetricSource() *ExternalMetricSourceApplyConfiguration {\n\treturn \u0026ExternalMetricSourceApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100020524,"name":"WithMetric","signature":"func (b *ExternalMetricSourceApplyConfiguration) WithMetric(value *MetricIdentifierApplyConfiguration) *ExternalMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/externalmetricsource.go","code":"// WithMetric sets the Metric field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Metric field is set to the value of the last call.\nfunc (b *ExternalMetricSourceApplyConfiguration) WithMetric(value *MetricIdentifierApplyConfiguration) *ExternalMetricSourceApplyConfiguration {\n\tb.Metric = value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100020525,"name":"WithTarget","signature":"func (b *ExternalMetricSourceApplyConfiguration) WithTarget(value *MetricTargetApplyConfiguration) *ExternalMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/externalmetricsource.go","code":"// WithTarget sets the Target field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Target field is set to the value of the last call.\nfunc (b *ExternalMetricSourceApplyConfiguration) WithTarget(value *MetricTargetApplyConfiguration) *ExternalMetricSourceApplyConfiguration {\n\tb.Target = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020526,"name":"ExternalMetricStatus","signature":"func ExternalMetricStatus() *ExternalMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/externalmetricstatus.go","code":"// ExternalMetricStatusApplyConfiguration constructs an declarative configuration of the ExternalMetricStatus type for use with\n// apply.\nfunc ExternalMetricStatus() *ExternalMetricStatusApplyConfiguration {\n\treturn \u0026ExternalMetricStatusApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100020527,"name":"WithMetric","signature":"func (b *ExternalMetricStatusApplyConfiguration) WithMetric(value *MetricIdentifierApplyConfiguration) *ExternalMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/externalmetricstatus.go","code":"// WithMetric sets the Metric field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Metric field is set to the value of the last call.\nfunc (b *ExternalMetricStatusApplyConfiguration) WithMetric(value *MetricIdentifierApplyConfiguration) *ExternalMetricStatusApplyConfiguration {\n\tb.Metric = value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100020528,"name":"WithCurrent","signature":"func (b *ExternalMetricStatusApplyConfiguration) WithCurrent(value *MetricValueStatusApplyConfiguration) *ExternalMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/externalmetricstatus.go","code":"// WithCurrent sets the Current field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Current field is set to the value of the last call.\nfunc (b *ExternalMetricStatusApplyConfiguration) WithCurrent(value *MetricValueStatusApplyConfiguration) *ExternalMetricStatusApplyConfiguration {\n\tb.Current = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020529,"name":"HorizontalPodAutoscaler","signature":"func HorizontalPodAutoscaler(name, namespace string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscaler.go","code":"// HorizontalPodAutoscaler constructs an declarative configuration of the HorizontalPodAutoscaler type for use with\n// apply.\nfunc HorizontalPodAutoscaler(name, namespace string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb := \u0026HorizontalPodAutoscalerApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"HorizontalPodAutoscaler\")\n\tb.WithAPIVersion(\"autoscaling/v2\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100020530,"name":"ExtractHorizontalPodAutoscaler","signature":"func ExtractHorizontalPodAutoscaler(horizontalPodAutoscaler *autoscalingv2.HorizontalPodAutoscaler, fieldManager string) (*HorizontalPodAutoscalerApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscaler.go","code":"// ExtractHorizontalPodAutoscaler extracts the applied configuration owned by fieldManager from\n// horizontalPodAutoscaler. If no managedFields are found in horizontalPodAutoscaler for fieldManager, a\n// HorizontalPodAutoscalerApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// horizontalPodAutoscaler must be a unmodified HorizontalPodAutoscaler API object that was retrieved from the Kubernetes API.\n// ExtractHorizontalPodAutoscaler provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractHorizontalPodAutoscaler(horizontalPodAutoscaler *autoscalingv2.HorizontalPodAutoscaler, fieldManager string) (*HorizontalPodAutoscalerApplyConfiguration, error) {\n\treturn extractHorizontalPodAutoscaler(horizontalPodAutoscaler, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100020531,"name":"ExtractHorizontalPodAutoscalerStatus","signature":"func ExtractHorizontalPodAutoscalerStatus(horizontalPodAutoscaler *autoscalingv2.HorizontalPodAutoscaler, fieldManager string) (*HorizontalPodAutoscalerApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscaler.go","code":"// ExtractHorizontalPodAutoscalerStatus is the same as ExtractHorizontalPodAutoscaler except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractHorizontalPodAutoscalerStatus(horizontalPodAutoscaler *autoscalingv2.HorizontalPodAutoscaler, fieldManager string) (*HorizontalPodAutoscalerApplyConfiguration, error) {\n\treturn extractHorizontalPodAutoscaler(horizontalPodAutoscaler, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100020532,"name":"extractHorizontalPodAutoscaler","signature":"func extractHorizontalPodAutoscaler(horizontalPodAutoscaler *autoscalingv2.HorizontalPodAutoscaler, fieldManager string, subresource string) (*HorizontalPodAutoscalerApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscaler.go","code":"func extractHorizontalPodAutoscaler(horizontalPodAutoscaler *autoscalingv2.HorizontalPodAutoscaler, fieldManager string, subresource string) (*HorizontalPodAutoscalerApplyConfiguration, error) {\n\tb := \u0026HorizontalPodAutoscalerApplyConfiguration{}\n\terr := managedfields.ExtractInto(horizontalPodAutoscaler, internal.Parser().Type(\"io.k8s.api.autoscaling.v2.HorizontalPodAutoscaler\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(horizontalPodAutoscaler.Name)\n\tb.WithNamespace(horizontalPodAutoscaler.Namespace)\n\n\tb.WithKind(\"HorizontalPodAutoscaler\")\n\tb.WithAPIVersion(\"autoscaling/v2\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100020533,"name":"WithKind","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithKind(value string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscaler.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithKind(value string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100020534,"name":"WithAPIVersion","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithAPIVersion(value string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscaler.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithAPIVersion(value string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100020535,"name":"WithName","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithName(value string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscaler.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithName(value string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100020536,"name":"WithGenerateName","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithGenerateName(value string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscaler.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithGenerateName(value string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100020537,"name":"WithNamespace","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithNamespace(value string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscaler.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithNamespace(value string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100020538,"name":"WithUID","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithUID(value types.UID) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscaler.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithUID(value types.UID) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100020539,"name":"WithResourceVersion","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithResourceVersion(value string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscaler.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithResourceVersion(value string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100020540,"name":"WithGeneration","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithGeneration(value int64) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscaler.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithGeneration(value int64) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100020541,"name":"WithCreationTimestamp","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithCreationTimestamp(value metav1.Time) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscaler.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithCreationTimestamp(value metav1.Time) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100020542,"name":"WithDeletionTimestamp","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscaler.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100020543,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscaler.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100020544,"name":"WithLabels","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithLabels(entries map[string]string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscaler.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithLabels(entries map[string]string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100020545,"name":"WithAnnotations","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithAnnotations(entries map[string]string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscaler.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithAnnotations(entries map[string]string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100020546,"name":"WithOwnerReferences","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscaler.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100020547,"name":"WithFinalizers","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithFinalizers(values ...string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscaler.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithFinalizers(values ...string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100020548,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscaler.go","code":"func (b *HorizontalPodAutoscalerApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100020549,"name":"WithSpec","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithSpec(value *HorizontalPodAutoscalerSpecApplyConfiguration) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscaler.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithSpec(value *HorizontalPodAutoscalerSpecApplyConfiguration) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100020550,"name":"WithStatus","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithStatus(value *HorizontalPodAutoscalerStatusApplyConfiguration) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscaler.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithStatus(value *HorizontalPodAutoscalerStatusApplyConfiguration) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100020551,"name":"HorizontalPodAutoscalerBehavior","signature":"func HorizontalPodAutoscalerBehavior() *HorizontalPodAutoscalerBehaviorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscalerbehavior.go","code":"// HorizontalPodAutoscalerBehaviorApplyConfiguration constructs an declarative configuration of the HorizontalPodAutoscalerBehavior type for use with\n// apply.\nfunc HorizontalPodAutoscalerBehavior() *HorizontalPodAutoscalerBehaviorApplyConfiguration {\n\treturn \u0026HorizontalPodAutoscalerBehaviorApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100020552,"name":"WithScaleUp","signature":"func (b *HorizontalPodAutoscalerBehaviorApplyConfiguration) WithScaleUp(value *HPAScalingRulesApplyConfiguration) *HorizontalPodAutoscalerBehaviorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscalerbehavior.go","code":"// WithScaleUp sets the ScaleUp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ScaleUp field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerBehaviorApplyConfiguration) WithScaleUp(value *HPAScalingRulesApplyConfiguration) *HorizontalPodAutoscalerBehaviorApplyConfiguration {\n\tb.ScaleUp = value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100020553,"name":"WithScaleDown","signature":"func (b *HorizontalPodAutoscalerBehaviorApplyConfiguration) WithScaleDown(value *HPAScalingRulesApplyConfiguration) *HorizontalPodAutoscalerBehaviorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscalerbehavior.go","code":"// WithScaleDown sets the ScaleDown field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ScaleDown field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerBehaviorApplyConfiguration) WithScaleDown(value *HPAScalingRulesApplyConfiguration) *HorizontalPodAutoscalerBehaviorApplyConfiguration {\n\tb.ScaleDown = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020554,"name":"HorizontalPodAutoscalerCondition","signature":"func HorizontalPodAutoscalerCondition() *HorizontalPodAutoscalerConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscalercondition.go","code":"// HorizontalPodAutoscalerConditionApplyConfiguration constructs an declarative configuration of the HorizontalPodAutoscalerCondition type for use with\n// apply.\nfunc HorizontalPodAutoscalerCondition() *HorizontalPodAutoscalerConditionApplyConfiguration {\n\treturn \u0026HorizontalPodAutoscalerConditionApplyConfiguration{}\n}","line":{"from":37,"to":41}} {"id":100020555,"name":"WithType","signature":"func (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithType(value v2.HorizontalPodAutoscalerConditionType) *HorizontalPodAutoscalerConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscalercondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithType(value v2.HorizontalPodAutoscalerConditionType) *HorizontalPodAutoscalerConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100020556,"name":"WithStatus","signature":"func (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *HorizontalPodAutoscalerConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscalercondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *HorizontalPodAutoscalerConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100020557,"name":"WithLastTransitionTime","signature":"func (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *HorizontalPodAutoscalerConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscalercondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *HorizontalPodAutoscalerConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":59,"to":65}} {"id":100020558,"name":"WithReason","signature":"func (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithReason(value string) *HorizontalPodAutoscalerConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscalercondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithReason(value string) *HorizontalPodAutoscalerConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100020559,"name":"WithMessage","signature":"func (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithMessage(value string) *HorizontalPodAutoscalerConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscalercondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithMessage(value string) *HorizontalPodAutoscalerConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":75,"to":81}} {"id":100020560,"name":"HorizontalPodAutoscalerSpec","signature":"func HorizontalPodAutoscalerSpec() *HorizontalPodAutoscalerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscalerspec.go","code":"// HorizontalPodAutoscalerSpecApplyConfiguration constructs an declarative configuration of the HorizontalPodAutoscalerSpec type for use with\n// apply.\nfunc HorizontalPodAutoscalerSpec() *HorizontalPodAutoscalerSpecApplyConfiguration {\n\treturn \u0026HorizontalPodAutoscalerSpecApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100020561,"name":"WithScaleTargetRef","signature":"func (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithScaleTargetRef(value *CrossVersionObjectReferenceApplyConfiguration) *HorizontalPodAutoscalerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscalerspec.go","code":"// WithScaleTargetRef sets the ScaleTargetRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ScaleTargetRef field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithScaleTargetRef(value *CrossVersionObjectReferenceApplyConfiguration) *HorizontalPodAutoscalerSpecApplyConfiguration {\n\tb.ScaleTargetRef = value\n\treturn b\n}","line":{"from":37,"to":43}} {"id":100020562,"name":"WithMinReplicas","signature":"func (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithMinReplicas(value int32) *HorizontalPodAutoscalerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscalerspec.go","code":"// WithMinReplicas sets the MinReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MinReplicas field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithMinReplicas(value int32) *HorizontalPodAutoscalerSpecApplyConfiguration {\n\tb.MinReplicas = \u0026value\n\treturn b\n}","line":{"from":45,"to":51}} {"id":100020563,"name":"WithMaxReplicas","signature":"func (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithMaxReplicas(value int32) *HorizontalPodAutoscalerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscalerspec.go","code":"// WithMaxReplicas sets the MaxReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MaxReplicas field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithMaxReplicas(value int32) *HorizontalPodAutoscalerSpecApplyConfiguration {\n\tb.MaxReplicas = \u0026value\n\treturn b\n}","line":{"from":53,"to":59}} {"id":100020564,"name":"WithMetrics","signature":"func (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithMetrics(values ...*MetricSpecApplyConfiguration) *HorizontalPodAutoscalerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscalerspec.go","code":"// WithMetrics adds the given value to the Metrics field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Metrics field.\nfunc (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithMetrics(values ...*MetricSpecApplyConfiguration) *HorizontalPodAutoscalerSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithMetrics\")\n\t\t}\n\t\tb.Metrics = append(b.Metrics, *values[i])\n\t}\n\treturn b\n}","line":{"from":61,"to":72}} {"id":100020565,"name":"WithBehavior","signature":"func (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithBehavior(value *HorizontalPodAutoscalerBehaviorApplyConfiguration) *HorizontalPodAutoscalerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscalerspec.go","code":"// WithBehavior sets the Behavior field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Behavior field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithBehavior(value *HorizontalPodAutoscalerBehaviorApplyConfiguration) *HorizontalPodAutoscalerSpecApplyConfiguration {\n\tb.Behavior = value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100020566,"name":"HorizontalPodAutoscalerStatus","signature":"func HorizontalPodAutoscalerStatus() *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscalerstatus.go","code":"// HorizontalPodAutoscalerStatusApplyConfiguration constructs an declarative configuration of the HorizontalPodAutoscalerStatus type for use with\n// apply.\nfunc HorizontalPodAutoscalerStatus() *HorizontalPodAutoscalerStatusApplyConfiguration {\n\treturn \u0026HorizontalPodAutoscalerStatusApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100020567,"name":"WithObservedGeneration","signature":"func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithObservedGeneration(value int64) *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscalerstatus.go","code":"// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObservedGeneration field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithObservedGeneration(value int64) *HorizontalPodAutoscalerStatusApplyConfiguration {\n\tb.ObservedGeneration = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020568,"name":"WithLastScaleTime","signature":"func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithLastScaleTime(value v1.Time) *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscalerstatus.go","code":"// WithLastScaleTime sets the LastScaleTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastScaleTime field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithLastScaleTime(value v1.Time) *HorizontalPodAutoscalerStatusApplyConfiguration {\n\tb.LastScaleTime = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100020569,"name":"WithCurrentReplicas","signature":"func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithCurrentReplicas(value int32) *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscalerstatus.go","code":"// WithCurrentReplicas sets the CurrentReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CurrentReplicas field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithCurrentReplicas(value int32) *HorizontalPodAutoscalerStatusApplyConfiguration {\n\tb.CurrentReplicas = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100020570,"name":"WithDesiredReplicas","signature":"func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithDesiredReplicas(value int32) *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscalerstatus.go","code":"// WithDesiredReplicas sets the DesiredReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DesiredReplicas field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithDesiredReplicas(value int32) *HorizontalPodAutoscalerStatusApplyConfiguration {\n\tb.DesiredReplicas = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100020571,"name":"WithCurrentMetrics","signature":"func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithCurrentMetrics(values ...*MetricStatusApplyConfiguration) *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscalerstatus.go","code":"// WithCurrentMetrics adds the given value to the CurrentMetrics field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the CurrentMetrics field.\nfunc (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithCurrentMetrics(values ...*MetricStatusApplyConfiguration) *HorizontalPodAutoscalerStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithCurrentMetrics\")\n\t\t}\n\t\tb.CurrentMetrics = append(b.CurrentMetrics, *values[i])\n\t}\n\treturn b\n}","line":{"from":74,"to":85}} {"id":100020572,"name":"WithConditions","signature":"func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithConditions(values ...*HorizontalPodAutoscalerConditionApplyConfiguration) *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/horizontalpodautoscalerstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithConditions(values ...*HorizontalPodAutoscalerConditionApplyConfiguration) *HorizontalPodAutoscalerStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":87,"to":98}} {"id":100020573,"name":"HPAScalingPolicy","signature":"func HPAScalingPolicy() *HPAScalingPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/hpascalingpolicy.go","code":"// HPAScalingPolicyApplyConfiguration constructs an declarative configuration of the HPAScalingPolicy type for use with\n// apply.\nfunc HPAScalingPolicy() *HPAScalingPolicyApplyConfiguration {\n\treturn \u0026HPAScalingPolicyApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100020574,"name":"WithType","signature":"func (b *HPAScalingPolicyApplyConfiguration) WithType(value v2.HPAScalingPolicyType) *HPAScalingPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/hpascalingpolicy.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *HPAScalingPolicyApplyConfiguration) WithType(value v2.HPAScalingPolicyType) *HPAScalingPolicyApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100020575,"name":"WithValue","signature":"func (b *HPAScalingPolicyApplyConfiguration) WithValue(value int32) *HPAScalingPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/hpascalingpolicy.go","code":"// WithValue sets the Value field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Value field is set to the value of the last call.\nfunc (b *HPAScalingPolicyApplyConfiguration) WithValue(value int32) *HPAScalingPolicyApplyConfiguration {\n\tb.Value = \u0026value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100020576,"name":"WithPeriodSeconds","signature":"func (b *HPAScalingPolicyApplyConfiguration) WithPeriodSeconds(value int32) *HPAScalingPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/hpascalingpolicy.go","code":"// WithPeriodSeconds sets the PeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PeriodSeconds field is set to the value of the last call.\nfunc (b *HPAScalingPolicyApplyConfiguration) WithPeriodSeconds(value int32) *HPAScalingPolicyApplyConfiguration {\n\tb.PeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":55,"to":61}} {"id":100020577,"name":"HPAScalingRules","signature":"func HPAScalingRules() *HPAScalingRulesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/hpascalingrules.go","code":"// HPAScalingRulesApplyConfiguration constructs an declarative configuration of the HPAScalingRules type for use with\n// apply.\nfunc HPAScalingRules() *HPAScalingRulesApplyConfiguration {\n\treturn \u0026HPAScalingRulesApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100020578,"name":"WithStabilizationWindowSeconds","signature":"func (b *HPAScalingRulesApplyConfiguration) WithStabilizationWindowSeconds(value int32) *HPAScalingRulesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/hpascalingrules.go","code":"// WithStabilizationWindowSeconds sets the StabilizationWindowSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StabilizationWindowSeconds field is set to the value of the last call.\nfunc (b *HPAScalingRulesApplyConfiguration) WithStabilizationWindowSeconds(value int32) *HPAScalingRulesApplyConfiguration {\n\tb.StabilizationWindowSeconds = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100020579,"name":"WithSelectPolicy","signature":"func (b *HPAScalingRulesApplyConfiguration) WithSelectPolicy(value v2.ScalingPolicySelect) *HPAScalingRulesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/hpascalingrules.go","code":"// WithSelectPolicy sets the SelectPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SelectPolicy field is set to the value of the last call.\nfunc (b *HPAScalingRulesApplyConfiguration) WithSelectPolicy(value v2.ScalingPolicySelect) *HPAScalingRulesApplyConfiguration {\n\tb.SelectPolicy = \u0026value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100020580,"name":"WithPolicies","signature":"func (b *HPAScalingRulesApplyConfiguration) WithPolicies(values ...*HPAScalingPolicyApplyConfiguration) *HPAScalingRulesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/hpascalingrules.go","code":"// WithPolicies adds the given value to the Policies field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Policies field.\nfunc (b *HPAScalingRulesApplyConfiguration) WithPolicies(values ...*HPAScalingPolicyApplyConfiguration) *HPAScalingRulesApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPolicies\")\n\t\t}\n\t\tb.Policies = append(b.Policies, *values[i])\n\t}\n\treturn b\n}","line":{"from":55,"to":66}} {"id":100020581,"name":"MetricIdentifier","signature":"func MetricIdentifier() *MetricIdentifierApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricidentifier.go","code":"// MetricIdentifierApplyConfiguration constructs an declarative configuration of the MetricIdentifier type for use with\n// apply.\nfunc MetricIdentifier() *MetricIdentifierApplyConfiguration {\n\treturn \u0026MetricIdentifierApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100020582,"name":"WithName","signature":"func (b *MetricIdentifierApplyConfiguration) WithName(value string) *MetricIdentifierApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricidentifier.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *MetricIdentifierApplyConfiguration) WithName(value string) *MetricIdentifierApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100020583,"name":"WithSelector","signature":"func (b *MetricIdentifierApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *MetricIdentifierApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricidentifier.go","code":"// WithSelector sets the Selector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Selector field is set to the value of the last call.\nfunc (b *MetricIdentifierApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *MetricIdentifierApplyConfiguration {\n\tb.Selector = value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100020584,"name":"MetricSpec","signature":"func MetricSpec() *MetricSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricspec.go","code":"// MetricSpecApplyConfiguration constructs an declarative configuration of the MetricSpec type for use with\n// apply.\nfunc MetricSpec() *MetricSpecApplyConfiguration {\n\treturn \u0026MetricSpecApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100020585,"name":"WithType","signature":"func (b *MetricSpecApplyConfiguration) WithType(value v2.MetricSourceType) *MetricSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricspec.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *MetricSpecApplyConfiguration) WithType(value v2.MetricSourceType) *MetricSpecApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020586,"name":"WithObject","signature":"func (b *MetricSpecApplyConfiguration) WithObject(value *ObjectMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricspec.go","code":"// WithObject sets the Object field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Object field is set to the value of the last call.\nfunc (b *MetricSpecApplyConfiguration) WithObject(value *ObjectMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration {\n\tb.Object = value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100020587,"name":"WithPods","signature":"func (b *MetricSpecApplyConfiguration) WithPods(value *PodsMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricspec.go","code":"// WithPods sets the Pods field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Pods field is set to the value of the last call.\nfunc (b *MetricSpecApplyConfiguration) WithPods(value *PodsMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration {\n\tb.Pods = value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100020588,"name":"WithResource","signature":"func (b *MetricSpecApplyConfiguration) WithResource(value *ResourceMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricspec.go","code":"// WithResource sets the Resource field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Resource field is set to the value of the last call.\nfunc (b *MetricSpecApplyConfiguration) WithResource(value *ResourceMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration {\n\tb.Resource = value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100020589,"name":"WithContainerResource","signature":"func (b *MetricSpecApplyConfiguration) WithContainerResource(value *ContainerResourceMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricspec.go","code":"// WithContainerResource sets the ContainerResource field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ContainerResource field is set to the value of the last call.\nfunc (b *MetricSpecApplyConfiguration) WithContainerResource(value *ContainerResourceMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration {\n\tb.ContainerResource = value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100020590,"name":"WithExternal","signature":"func (b *MetricSpecApplyConfiguration) WithExternal(value *ExternalMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricspec.go","code":"// WithExternal sets the External field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the External field is set to the value of the last call.\nfunc (b *MetricSpecApplyConfiguration) WithExternal(value *ExternalMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration {\n\tb.External = value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100020591,"name":"MetricStatus","signature":"func MetricStatus() *MetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricstatus.go","code":"// MetricStatusApplyConfiguration constructs an declarative configuration of the MetricStatus type for use with\n// apply.\nfunc MetricStatus() *MetricStatusApplyConfiguration {\n\treturn \u0026MetricStatusApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100020592,"name":"WithType","signature":"func (b *MetricStatusApplyConfiguration) WithType(value v2.MetricSourceType) *MetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricstatus.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *MetricStatusApplyConfiguration) WithType(value v2.MetricSourceType) *MetricStatusApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020593,"name":"WithObject","signature":"func (b *MetricStatusApplyConfiguration) WithObject(value *ObjectMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricstatus.go","code":"// WithObject sets the Object field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Object field is set to the value of the last call.\nfunc (b *MetricStatusApplyConfiguration) WithObject(value *ObjectMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration {\n\tb.Object = value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100020594,"name":"WithPods","signature":"func (b *MetricStatusApplyConfiguration) WithPods(value *PodsMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricstatus.go","code":"// WithPods sets the Pods field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Pods field is set to the value of the last call.\nfunc (b *MetricStatusApplyConfiguration) WithPods(value *PodsMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration {\n\tb.Pods = value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100020595,"name":"WithResource","signature":"func (b *MetricStatusApplyConfiguration) WithResource(value *ResourceMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricstatus.go","code":"// WithResource sets the Resource field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Resource field is set to the value of the last call.\nfunc (b *MetricStatusApplyConfiguration) WithResource(value *ResourceMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration {\n\tb.Resource = value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100020596,"name":"WithContainerResource","signature":"func (b *MetricStatusApplyConfiguration) WithContainerResource(value *ContainerResourceMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricstatus.go","code":"// WithContainerResource sets the ContainerResource field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ContainerResource field is set to the value of the last call.\nfunc (b *MetricStatusApplyConfiguration) WithContainerResource(value *ContainerResourceMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration {\n\tb.ContainerResource = value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100020597,"name":"WithExternal","signature":"func (b *MetricStatusApplyConfiguration) WithExternal(value *ExternalMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricstatus.go","code":"// WithExternal sets the External field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the External field is set to the value of the last call.\nfunc (b *MetricStatusApplyConfiguration) WithExternal(value *ExternalMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration {\n\tb.External = value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100020598,"name":"MetricTarget","signature":"func MetricTarget() *MetricTargetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/metrictarget.go","code":"// MetricTargetApplyConfiguration constructs an declarative configuration of the MetricTarget type for use with\n// apply.\nfunc MetricTarget() *MetricTargetApplyConfiguration {\n\treturn \u0026MetricTargetApplyConfiguration{}\n}","line":{"from":35,"to":39}} {"id":100020599,"name":"WithType","signature":"func (b *MetricTargetApplyConfiguration) WithType(value v2.MetricTargetType) *MetricTargetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/metrictarget.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *MetricTargetApplyConfiguration) WithType(value v2.MetricTargetType) *MetricTargetApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":41,"to":47}} {"id":100020600,"name":"WithValue","signature":"func (b *MetricTargetApplyConfiguration) WithValue(value resource.Quantity) *MetricTargetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/metrictarget.go","code":"// WithValue sets the Value field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Value field is set to the value of the last call.\nfunc (b *MetricTargetApplyConfiguration) WithValue(value resource.Quantity) *MetricTargetApplyConfiguration {\n\tb.Value = \u0026value\n\treturn b\n}","line":{"from":49,"to":55}} {"id":100020601,"name":"WithAverageValue","signature":"func (b *MetricTargetApplyConfiguration) WithAverageValue(value resource.Quantity) *MetricTargetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/metrictarget.go","code":"// WithAverageValue sets the AverageValue field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AverageValue field is set to the value of the last call.\nfunc (b *MetricTargetApplyConfiguration) WithAverageValue(value resource.Quantity) *MetricTargetApplyConfiguration {\n\tb.AverageValue = \u0026value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100020602,"name":"WithAverageUtilization","signature":"func (b *MetricTargetApplyConfiguration) WithAverageUtilization(value int32) *MetricTargetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/metrictarget.go","code":"// WithAverageUtilization sets the AverageUtilization field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AverageUtilization field is set to the value of the last call.\nfunc (b *MetricTargetApplyConfiguration) WithAverageUtilization(value int32) *MetricTargetApplyConfiguration {\n\tb.AverageUtilization = \u0026value\n\treturn b\n}","line":{"from":65,"to":71}} {"id":100020603,"name":"MetricValueStatus","signature":"func MetricValueStatus() *MetricValueStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricvaluestatus.go","code":"// MetricValueStatusApplyConfiguration constructs an declarative configuration of the MetricValueStatus type for use with\n// apply.\nfunc MetricValueStatus() *MetricValueStatusApplyConfiguration {\n\treturn \u0026MetricValueStatusApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100020604,"name":"WithValue","signature":"func (b *MetricValueStatusApplyConfiguration) WithValue(value resource.Quantity) *MetricValueStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricvaluestatus.go","code":"// WithValue sets the Value field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Value field is set to the value of the last call.\nfunc (b *MetricValueStatusApplyConfiguration) WithValue(value resource.Quantity) *MetricValueStatusApplyConfiguration {\n\tb.Value = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100020605,"name":"WithAverageValue","signature":"func (b *MetricValueStatusApplyConfiguration) WithAverageValue(value resource.Quantity) *MetricValueStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricvaluestatus.go","code":"// WithAverageValue sets the AverageValue field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AverageValue field is set to the value of the last call.\nfunc (b *MetricValueStatusApplyConfiguration) WithAverageValue(value resource.Quantity) *MetricValueStatusApplyConfiguration {\n\tb.AverageValue = \u0026value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100020606,"name":"WithAverageUtilization","signature":"func (b *MetricValueStatusApplyConfiguration) WithAverageUtilization(value int32) *MetricValueStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/metricvaluestatus.go","code":"// WithAverageUtilization sets the AverageUtilization field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AverageUtilization field is set to the value of the last call.\nfunc (b *MetricValueStatusApplyConfiguration) WithAverageUtilization(value int32) *MetricValueStatusApplyConfiguration {\n\tb.AverageUtilization = \u0026value\n\treturn b\n}","line":{"from":55,"to":61}} {"id":100020607,"name":"ObjectMetricSource","signature":"func ObjectMetricSource() *ObjectMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/objectmetricsource.go","code":"// ObjectMetricSourceApplyConfiguration constructs an declarative configuration of the ObjectMetricSource type for use with\n// apply.\nfunc ObjectMetricSource() *ObjectMetricSourceApplyConfiguration {\n\treturn \u0026ObjectMetricSourceApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100020608,"name":"WithDescribedObject","signature":"func (b *ObjectMetricSourceApplyConfiguration) WithDescribedObject(value *CrossVersionObjectReferenceApplyConfiguration) *ObjectMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/objectmetricsource.go","code":"// WithDescribedObject sets the DescribedObject field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DescribedObject field is set to the value of the last call.\nfunc (b *ObjectMetricSourceApplyConfiguration) WithDescribedObject(value *CrossVersionObjectReferenceApplyConfiguration) *ObjectMetricSourceApplyConfiguration {\n\tb.DescribedObject = value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100020609,"name":"WithTarget","signature":"func (b *ObjectMetricSourceApplyConfiguration) WithTarget(value *MetricTargetApplyConfiguration) *ObjectMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/objectmetricsource.go","code":"// WithTarget sets the Target field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Target field is set to the value of the last call.\nfunc (b *ObjectMetricSourceApplyConfiguration) WithTarget(value *MetricTargetApplyConfiguration) *ObjectMetricSourceApplyConfiguration {\n\tb.Target = value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100020610,"name":"WithMetric","signature":"func (b *ObjectMetricSourceApplyConfiguration) WithMetric(value *MetricIdentifierApplyConfiguration) *ObjectMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/objectmetricsource.go","code":"// WithMetric sets the Metric field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Metric field is set to the value of the last call.\nfunc (b *ObjectMetricSourceApplyConfiguration) WithMetric(value *MetricIdentifierApplyConfiguration) *ObjectMetricSourceApplyConfiguration {\n\tb.Metric = value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100020611,"name":"ObjectMetricStatus","signature":"func ObjectMetricStatus() *ObjectMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/objectmetricstatus.go","code":"// ObjectMetricStatusApplyConfiguration constructs an declarative configuration of the ObjectMetricStatus type for use with\n// apply.\nfunc ObjectMetricStatus() *ObjectMetricStatusApplyConfiguration {\n\treturn \u0026ObjectMetricStatusApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100020612,"name":"WithMetric","signature":"func (b *ObjectMetricStatusApplyConfiguration) WithMetric(value *MetricIdentifierApplyConfiguration) *ObjectMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/objectmetricstatus.go","code":"// WithMetric sets the Metric field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Metric field is set to the value of the last call.\nfunc (b *ObjectMetricStatusApplyConfiguration) WithMetric(value *MetricIdentifierApplyConfiguration) *ObjectMetricStatusApplyConfiguration {\n\tb.Metric = value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100020613,"name":"WithCurrent","signature":"func (b *ObjectMetricStatusApplyConfiguration) WithCurrent(value *MetricValueStatusApplyConfiguration) *ObjectMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/objectmetricstatus.go","code":"// WithCurrent sets the Current field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Current field is set to the value of the last call.\nfunc (b *ObjectMetricStatusApplyConfiguration) WithCurrent(value *MetricValueStatusApplyConfiguration) *ObjectMetricStatusApplyConfiguration {\n\tb.Current = value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100020614,"name":"WithDescribedObject","signature":"func (b *ObjectMetricStatusApplyConfiguration) WithDescribedObject(value *CrossVersionObjectReferenceApplyConfiguration) *ObjectMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/objectmetricstatus.go","code":"// WithDescribedObject sets the DescribedObject field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DescribedObject field is set to the value of the last call.\nfunc (b *ObjectMetricStatusApplyConfiguration) WithDescribedObject(value *CrossVersionObjectReferenceApplyConfiguration) *ObjectMetricStatusApplyConfiguration {\n\tb.DescribedObject = value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100020615,"name":"PodsMetricSource","signature":"func PodsMetricSource() *PodsMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/podsmetricsource.go","code":"// PodsMetricSourceApplyConfiguration constructs an declarative configuration of the PodsMetricSource type for use with\n// apply.\nfunc PodsMetricSource() *PodsMetricSourceApplyConfiguration {\n\treturn \u0026PodsMetricSourceApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100020616,"name":"WithMetric","signature":"func (b *PodsMetricSourceApplyConfiguration) WithMetric(value *MetricIdentifierApplyConfiguration) *PodsMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/podsmetricsource.go","code":"// WithMetric sets the Metric field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Metric field is set to the value of the last call.\nfunc (b *PodsMetricSourceApplyConfiguration) WithMetric(value *MetricIdentifierApplyConfiguration) *PodsMetricSourceApplyConfiguration {\n\tb.Metric = value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100020617,"name":"WithTarget","signature":"func (b *PodsMetricSourceApplyConfiguration) WithTarget(value *MetricTargetApplyConfiguration) *PodsMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/podsmetricsource.go","code":"// WithTarget sets the Target field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Target field is set to the value of the last call.\nfunc (b *PodsMetricSourceApplyConfiguration) WithTarget(value *MetricTargetApplyConfiguration) *PodsMetricSourceApplyConfiguration {\n\tb.Target = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020618,"name":"PodsMetricStatus","signature":"func PodsMetricStatus() *PodsMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/podsmetricstatus.go","code":"// PodsMetricStatusApplyConfiguration constructs an declarative configuration of the PodsMetricStatus type for use with\n// apply.\nfunc PodsMetricStatus() *PodsMetricStatusApplyConfiguration {\n\treturn \u0026PodsMetricStatusApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100020619,"name":"WithMetric","signature":"func (b *PodsMetricStatusApplyConfiguration) WithMetric(value *MetricIdentifierApplyConfiguration) *PodsMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/podsmetricstatus.go","code":"// WithMetric sets the Metric field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Metric field is set to the value of the last call.\nfunc (b *PodsMetricStatusApplyConfiguration) WithMetric(value *MetricIdentifierApplyConfiguration) *PodsMetricStatusApplyConfiguration {\n\tb.Metric = value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100020620,"name":"WithCurrent","signature":"func (b *PodsMetricStatusApplyConfiguration) WithCurrent(value *MetricValueStatusApplyConfiguration) *PodsMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/podsmetricstatus.go","code":"// WithCurrent sets the Current field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Current field is set to the value of the last call.\nfunc (b *PodsMetricStatusApplyConfiguration) WithCurrent(value *MetricValueStatusApplyConfiguration) *PodsMetricStatusApplyConfiguration {\n\tb.Current = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020621,"name":"ResourceMetricSource","signature":"func ResourceMetricSource() *ResourceMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/resourcemetricsource.go","code":"// ResourceMetricSourceApplyConfiguration constructs an declarative configuration of the ResourceMetricSource type for use with\n// apply.\nfunc ResourceMetricSource() *ResourceMetricSourceApplyConfiguration {\n\treturn \u0026ResourceMetricSourceApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100020622,"name":"WithName","signature":"func (b *ResourceMetricSourceApplyConfiguration) WithName(value v1.ResourceName) *ResourceMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/resourcemetricsource.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ResourceMetricSourceApplyConfiguration) WithName(value v1.ResourceName) *ResourceMetricSourceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100020623,"name":"WithTarget","signature":"func (b *ResourceMetricSourceApplyConfiguration) WithTarget(value *MetricTargetApplyConfiguration) *ResourceMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/resourcemetricsource.go","code":"// WithTarget sets the Target field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Target field is set to the value of the last call.\nfunc (b *ResourceMetricSourceApplyConfiguration) WithTarget(value *MetricTargetApplyConfiguration) *ResourceMetricSourceApplyConfiguration {\n\tb.Target = value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100020624,"name":"ResourceMetricStatus","signature":"func ResourceMetricStatus() *ResourceMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/resourcemetricstatus.go","code":"// ResourceMetricStatusApplyConfiguration constructs an declarative configuration of the ResourceMetricStatus type for use with\n// apply.\nfunc ResourceMetricStatus() *ResourceMetricStatusApplyConfiguration {\n\treturn \u0026ResourceMetricStatusApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100020625,"name":"WithName","signature":"func (b *ResourceMetricStatusApplyConfiguration) WithName(value v1.ResourceName) *ResourceMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/resourcemetricstatus.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ResourceMetricStatusApplyConfiguration) WithName(value v1.ResourceName) *ResourceMetricStatusApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100020626,"name":"WithCurrent","signature":"func (b *ResourceMetricStatusApplyConfiguration) WithCurrent(value *MetricValueStatusApplyConfiguration) *ResourceMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2/resourcemetricstatus.go","code":"// WithCurrent sets the Current field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Current field is set to the value of the last call.\nfunc (b *ResourceMetricStatusApplyConfiguration) WithCurrent(value *MetricValueStatusApplyConfiguration) *ResourceMetricStatusApplyConfiguration {\n\tb.Current = value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100020627,"name":"ContainerResourceMetricSource","signature":"func ContainerResourceMetricSource() *ContainerResourceMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/containerresourcemetricsource.go","code":"// ContainerResourceMetricSourceApplyConfiguration constructs an declarative configuration of the ContainerResourceMetricSource type for use with\n// apply.\nfunc ContainerResourceMetricSource() *ContainerResourceMetricSourceApplyConfiguration {\n\treturn \u0026ContainerResourceMetricSourceApplyConfiguration{}\n}","line":{"from":35,"to":39}} {"id":100020628,"name":"WithName","signature":"func (b *ContainerResourceMetricSourceApplyConfiguration) WithName(value v1.ResourceName) *ContainerResourceMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/containerresourcemetricsource.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ContainerResourceMetricSourceApplyConfiguration) WithName(value v1.ResourceName) *ContainerResourceMetricSourceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":41,"to":47}} {"id":100020629,"name":"WithTargetAverageUtilization","signature":"func (b *ContainerResourceMetricSourceApplyConfiguration) WithTargetAverageUtilization(value int32) *ContainerResourceMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/containerresourcemetricsource.go","code":"// WithTargetAverageUtilization sets the TargetAverageUtilization field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TargetAverageUtilization field is set to the value of the last call.\nfunc (b *ContainerResourceMetricSourceApplyConfiguration) WithTargetAverageUtilization(value int32) *ContainerResourceMetricSourceApplyConfiguration {\n\tb.TargetAverageUtilization = \u0026value\n\treturn b\n}","line":{"from":49,"to":55}} {"id":100020630,"name":"WithTargetAverageValue","signature":"func (b *ContainerResourceMetricSourceApplyConfiguration) WithTargetAverageValue(value resource.Quantity) *ContainerResourceMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/containerresourcemetricsource.go","code":"// WithTargetAverageValue sets the TargetAverageValue field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TargetAverageValue field is set to the value of the last call.\nfunc (b *ContainerResourceMetricSourceApplyConfiguration) WithTargetAverageValue(value resource.Quantity) *ContainerResourceMetricSourceApplyConfiguration {\n\tb.TargetAverageValue = \u0026value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100020631,"name":"WithContainer","signature":"func (b *ContainerResourceMetricSourceApplyConfiguration) WithContainer(value string) *ContainerResourceMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/containerresourcemetricsource.go","code":"// WithContainer sets the Container field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Container field is set to the value of the last call.\nfunc (b *ContainerResourceMetricSourceApplyConfiguration) WithContainer(value string) *ContainerResourceMetricSourceApplyConfiguration {\n\tb.Container = \u0026value\n\treturn b\n}","line":{"from":65,"to":71}} {"id":100020632,"name":"ContainerResourceMetricStatus","signature":"func ContainerResourceMetricStatus() *ContainerResourceMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/containerresourcemetricstatus.go","code":"// ContainerResourceMetricStatusApplyConfiguration constructs an declarative configuration of the ContainerResourceMetricStatus type for use with\n// apply.\nfunc ContainerResourceMetricStatus() *ContainerResourceMetricStatusApplyConfiguration {\n\treturn \u0026ContainerResourceMetricStatusApplyConfiguration{}\n}","line":{"from":35,"to":39}} {"id":100020633,"name":"WithName","signature":"func (b *ContainerResourceMetricStatusApplyConfiguration) WithName(value v1.ResourceName) *ContainerResourceMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/containerresourcemetricstatus.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ContainerResourceMetricStatusApplyConfiguration) WithName(value v1.ResourceName) *ContainerResourceMetricStatusApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":41,"to":47}} {"id":100020634,"name":"WithCurrentAverageUtilization","signature":"func (b *ContainerResourceMetricStatusApplyConfiguration) WithCurrentAverageUtilization(value int32) *ContainerResourceMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/containerresourcemetricstatus.go","code":"// WithCurrentAverageUtilization sets the CurrentAverageUtilization field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CurrentAverageUtilization field is set to the value of the last call.\nfunc (b *ContainerResourceMetricStatusApplyConfiguration) WithCurrentAverageUtilization(value int32) *ContainerResourceMetricStatusApplyConfiguration {\n\tb.CurrentAverageUtilization = \u0026value\n\treturn b\n}","line":{"from":49,"to":55}} {"id":100020635,"name":"WithCurrentAverageValue","signature":"func (b *ContainerResourceMetricStatusApplyConfiguration) WithCurrentAverageValue(value resource.Quantity) *ContainerResourceMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/containerresourcemetricstatus.go","code":"// WithCurrentAverageValue sets the CurrentAverageValue field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CurrentAverageValue field is set to the value of the last call.\nfunc (b *ContainerResourceMetricStatusApplyConfiguration) WithCurrentAverageValue(value resource.Quantity) *ContainerResourceMetricStatusApplyConfiguration {\n\tb.CurrentAverageValue = \u0026value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100020636,"name":"WithContainer","signature":"func (b *ContainerResourceMetricStatusApplyConfiguration) WithContainer(value string) *ContainerResourceMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/containerresourcemetricstatus.go","code":"// WithContainer sets the Container field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Container field is set to the value of the last call.\nfunc (b *ContainerResourceMetricStatusApplyConfiguration) WithContainer(value string) *ContainerResourceMetricStatusApplyConfiguration {\n\tb.Container = \u0026value\n\treturn b\n}","line":{"from":65,"to":71}} {"id":100020637,"name":"CrossVersionObjectReference","signature":"func CrossVersionObjectReference() *CrossVersionObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/crossversionobjectreference.go","code":"// CrossVersionObjectReferenceApplyConfiguration constructs an declarative configuration of the CrossVersionObjectReference type for use with\n// apply.\nfunc CrossVersionObjectReference() *CrossVersionObjectReferenceApplyConfiguration {\n\treturn \u0026CrossVersionObjectReferenceApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100020638,"name":"WithKind","signature":"func (b *CrossVersionObjectReferenceApplyConfiguration) WithKind(value string) *CrossVersionObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/crossversionobjectreference.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *CrossVersionObjectReferenceApplyConfiguration) WithKind(value string) *CrossVersionObjectReferenceApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100020639,"name":"WithName","signature":"func (b *CrossVersionObjectReferenceApplyConfiguration) WithName(value string) *CrossVersionObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/crossversionobjectreference.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *CrossVersionObjectReferenceApplyConfiguration) WithName(value string) *CrossVersionObjectReferenceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100020640,"name":"WithAPIVersion","signature":"func (b *CrossVersionObjectReferenceApplyConfiguration) WithAPIVersion(value string) *CrossVersionObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/crossversionobjectreference.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *CrossVersionObjectReferenceApplyConfiguration) WithAPIVersion(value string) *CrossVersionObjectReferenceApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100020641,"name":"ExternalMetricSource","signature":"func ExternalMetricSource() *ExternalMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/externalmetricsource.go","code":"// ExternalMetricSourceApplyConfiguration constructs an declarative configuration of the ExternalMetricSource type for use with\n// apply.\nfunc ExternalMetricSource() *ExternalMetricSourceApplyConfiguration {\n\treturn \u0026ExternalMetricSourceApplyConfiguration{}\n}","line":{"from":35,"to":39}} {"id":100020642,"name":"WithMetricName","signature":"func (b *ExternalMetricSourceApplyConfiguration) WithMetricName(value string) *ExternalMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/externalmetricsource.go","code":"// WithMetricName sets the MetricName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MetricName field is set to the value of the last call.\nfunc (b *ExternalMetricSourceApplyConfiguration) WithMetricName(value string) *ExternalMetricSourceApplyConfiguration {\n\tb.MetricName = \u0026value\n\treturn b\n}","line":{"from":41,"to":47}} {"id":100020643,"name":"WithMetricSelector","signature":"func (b *ExternalMetricSourceApplyConfiguration) WithMetricSelector(value *v1.LabelSelectorApplyConfiguration) *ExternalMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/externalmetricsource.go","code":"// WithMetricSelector sets the MetricSelector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MetricSelector field is set to the value of the last call.\nfunc (b *ExternalMetricSourceApplyConfiguration) WithMetricSelector(value *v1.LabelSelectorApplyConfiguration) *ExternalMetricSourceApplyConfiguration {\n\tb.MetricSelector = value\n\treturn b\n}","line":{"from":49,"to":55}} {"id":100020644,"name":"WithTargetValue","signature":"func (b *ExternalMetricSourceApplyConfiguration) WithTargetValue(value resource.Quantity) *ExternalMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/externalmetricsource.go","code":"// WithTargetValue sets the TargetValue field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TargetValue field is set to the value of the last call.\nfunc (b *ExternalMetricSourceApplyConfiguration) WithTargetValue(value resource.Quantity) *ExternalMetricSourceApplyConfiguration {\n\tb.TargetValue = \u0026value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100020645,"name":"WithTargetAverageValue","signature":"func (b *ExternalMetricSourceApplyConfiguration) WithTargetAverageValue(value resource.Quantity) *ExternalMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/externalmetricsource.go","code":"// WithTargetAverageValue sets the TargetAverageValue field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TargetAverageValue field is set to the value of the last call.\nfunc (b *ExternalMetricSourceApplyConfiguration) WithTargetAverageValue(value resource.Quantity) *ExternalMetricSourceApplyConfiguration {\n\tb.TargetAverageValue = \u0026value\n\treturn b\n}","line":{"from":65,"to":71}} {"id":100020646,"name":"ExternalMetricStatus","signature":"func ExternalMetricStatus() *ExternalMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/externalmetricstatus.go","code":"// ExternalMetricStatusApplyConfiguration constructs an declarative configuration of the ExternalMetricStatus type for use with\n// apply.\nfunc ExternalMetricStatus() *ExternalMetricStatusApplyConfiguration {\n\treturn \u0026ExternalMetricStatusApplyConfiguration{}\n}","line":{"from":35,"to":39}} {"id":100020647,"name":"WithMetricName","signature":"func (b *ExternalMetricStatusApplyConfiguration) WithMetricName(value string) *ExternalMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/externalmetricstatus.go","code":"// WithMetricName sets the MetricName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MetricName field is set to the value of the last call.\nfunc (b *ExternalMetricStatusApplyConfiguration) WithMetricName(value string) *ExternalMetricStatusApplyConfiguration {\n\tb.MetricName = \u0026value\n\treturn b\n}","line":{"from":41,"to":47}} {"id":100020648,"name":"WithMetricSelector","signature":"func (b *ExternalMetricStatusApplyConfiguration) WithMetricSelector(value *v1.LabelSelectorApplyConfiguration) *ExternalMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/externalmetricstatus.go","code":"// WithMetricSelector sets the MetricSelector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MetricSelector field is set to the value of the last call.\nfunc (b *ExternalMetricStatusApplyConfiguration) WithMetricSelector(value *v1.LabelSelectorApplyConfiguration) *ExternalMetricStatusApplyConfiguration {\n\tb.MetricSelector = value\n\treturn b\n}","line":{"from":49,"to":55}} {"id":100020649,"name":"WithCurrentValue","signature":"func (b *ExternalMetricStatusApplyConfiguration) WithCurrentValue(value resource.Quantity) *ExternalMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/externalmetricstatus.go","code":"// WithCurrentValue sets the CurrentValue field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CurrentValue field is set to the value of the last call.\nfunc (b *ExternalMetricStatusApplyConfiguration) WithCurrentValue(value resource.Quantity) *ExternalMetricStatusApplyConfiguration {\n\tb.CurrentValue = \u0026value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100020650,"name":"WithCurrentAverageValue","signature":"func (b *ExternalMetricStatusApplyConfiguration) WithCurrentAverageValue(value resource.Quantity) *ExternalMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/externalmetricstatus.go","code":"// WithCurrentAverageValue sets the CurrentAverageValue field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CurrentAverageValue field is set to the value of the last call.\nfunc (b *ExternalMetricStatusApplyConfiguration) WithCurrentAverageValue(value resource.Quantity) *ExternalMetricStatusApplyConfiguration {\n\tb.CurrentAverageValue = \u0026value\n\treturn b\n}","line":{"from":65,"to":71}} {"id":100020651,"name":"HorizontalPodAutoscaler","signature":"func HorizontalPodAutoscaler(name, namespace string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// HorizontalPodAutoscaler constructs an declarative configuration of the HorizontalPodAutoscaler type for use with\n// apply.\nfunc HorizontalPodAutoscaler(name, namespace string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb := \u0026HorizontalPodAutoscalerApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"HorizontalPodAutoscaler\")\n\tb.WithAPIVersion(\"autoscaling/v2beta1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100020652,"name":"ExtractHorizontalPodAutoscaler","signature":"func ExtractHorizontalPodAutoscaler(horizontalPodAutoscaler *autoscalingv2beta1.HorizontalPodAutoscaler, fieldManager string) (*HorizontalPodAutoscalerApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// ExtractHorizontalPodAutoscaler extracts the applied configuration owned by fieldManager from\n// horizontalPodAutoscaler. If no managedFields are found in horizontalPodAutoscaler for fieldManager, a\n// HorizontalPodAutoscalerApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// horizontalPodAutoscaler must be a unmodified HorizontalPodAutoscaler API object that was retrieved from the Kubernetes API.\n// ExtractHorizontalPodAutoscaler provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractHorizontalPodAutoscaler(horizontalPodAutoscaler *autoscalingv2beta1.HorizontalPodAutoscaler, fieldManager string) (*HorizontalPodAutoscalerApplyConfiguration, error) {\n\treturn extractHorizontalPodAutoscaler(horizontalPodAutoscaler, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100020653,"name":"ExtractHorizontalPodAutoscalerStatus","signature":"func ExtractHorizontalPodAutoscalerStatus(horizontalPodAutoscaler *autoscalingv2beta1.HorizontalPodAutoscaler, fieldManager string) (*HorizontalPodAutoscalerApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// ExtractHorizontalPodAutoscalerStatus is the same as ExtractHorizontalPodAutoscaler except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractHorizontalPodAutoscalerStatus(horizontalPodAutoscaler *autoscalingv2beta1.HorizontalPodAutoscaler, fieldManager string) (*HorizontalPodAutoscalerApplyConfiguration, error) {\n\treturn extractHorizontalPodAutoscaler(horizontalPodAutoscaler, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100020654,"name":"extractHorizontalPodAutoscaler","signature":"func extractHorizontalPodAutoscaler(horizontalPodAutoscaler *autoscalingv2beta1.HorizontalPodAutoscaler, fieldManager string, subresource string) (*HorizontalPodAutoscalerApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"func extractHorizontalPodAutoscaler(horizontalPodAutoscaler *autoscalingv2beta1.HorizontalPodAutoscaler, fieldManager string, subresource string) (*HorizontalPodAutoscalerApplyConfiguration, error) {\n\tb := \u0026HorizontalPodAutoscalerApplyConfiguration{}\n\terr := managedfields.ExtractInto(horizontalPodAutoscaler, internal.Parser().Type(\"io.k8s.api.autoscaling.v2beta1.HorizontalPodAutoscaler\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(horizontalPodAutoscaler.Name)\n\tb.WithNamespace(horizontalPodAutoscaler.Namespace)\n\n\tb.WithKind(\"HorizontalPodAutoscaler\")\n\tb.WithAPIVersion(\"autoscaling/v2beta1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100020655,"name":"WithKind","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithKind(value string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithKind(value string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100020656,"name":"WithAPIVersion","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithAPIVersion(value string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithAPIVersion(value string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100020657,"name":"WithName","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithName(value string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithName(value string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100020658,"name":"WithGenerateName","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithGenerateName(value string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithGenerateName(value string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100020659,"name":"WithNamespace","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithNamespace(value string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithNamespace(value string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100020660,"name":"WithUID","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithUID(value types.UID) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithUID(value types.UID) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100020661,"name":"WithResourceVersion","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithResourceVersion(value string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithResourceVersion(value string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100020662,"name":"WithGeneration","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithGeneration(value int64) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithGeneration(value int64) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100020663,"name":"WithCreationTimestamp","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithCreationTimestamp(value metav1.Time) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithCreationTimestamp(value metav1.Time) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100020664,"name":"WithDeletionTimestamp","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100020665,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100020666,"name":"WithLabels","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithLabels(entries map[string]string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithLabels(entries map[string]string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100020667,"name":"WithAnnotations","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithAnnotations(entries map[string]string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithAnnotations(entries map[string]string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100020668,"name":"WithOwnerReferences","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100020669,"name":"WithFinalizers","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithFinalizers(values ...string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithFinalizers(values ...string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100020670,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"func (b *HorizontalPodAutoscalerApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100020671,"name":"WithSpec","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithSpec(value *HorizontalPodAutoscalerSpecApplyConfiguration) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithSpec(value *HorizontalPodAutoscalerSpecApplyConfiguration) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100020672,"name":"WithStatus","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithStatus(value *HorizontalPodAutoscalerStatusApplyConfiguration) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithStatus(value *HorizontalPodAutoscalerStatusApplyConfiguration) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100020673,"name":"HorizontalPodAutoscalerCondition","signature":"func HorizontalPodAutoscalerCondition() *HorizontalPodAutoscalerConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscalercondition.go","code":"// HorizontalPodAutoscalerConditionApplyConfiguration constructs an declarative configuration of the HorizontalPodAutoscalerCondition type for use with\n// apply.\nfunc HorizontalPodAutoscalerCondition() *HorizontalPodAutoscalerConditionApplyConfiguration {\n\treturn \u0026HorizontalPodAutoscalerConditionApplyConfiguration{}\n}","line":{"from":37,"to":41}} {"id":100020674,"name":"WithType","signature":"func (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithType(value v2beta1.HorizontalPodAutoscalerConditionType) *HorizontalPodAutoscalerConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscalercondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithType(value v2beta1.HorizontalPodAutoscalerConditionType) *HorizontalPodAutoscalerConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100020675,"name":"WithStatus","signature":"func (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *HorizontalPodAutoscalerConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscalercondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *HorizontalPodAutoscalerConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100020676,"name":"WithLastTransitionTime","signature":"func (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *HorizontalPodAutoscalerConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscalercondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *HorizontalPodAutoscalerConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":59,"to":65}} {"id":100020677,"name":"WithReason","signature":"func (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithReason(value string) *HorizontalPodAutoscalerConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscalercondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithReason(value string) *HorizontalPodAutoscalerConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100020678,"name":"WithMessage","signature":"func (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithMessage(value string) *HorizontalPodAutoscalerConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscalercondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithMessage(value string) *HorizontalPodAutoscalerConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":75,"to":81}} {"id":100020679,"name":"HorizontalPodAutoscalerSpec","signature":"func HorizontalPodAutoscalerSpec() *HorizontalPodAutoscalerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscalerspec.go","code":"// HorizontalPodAutoscalerSpecApplyConfiguration constructs an declarative configuration of the HorizontalPodAutoscalerSpec type for use with\n// apply.\nfunc HorizontalPodAutoscalerSpec() *HorizontalPodAutoscalerSpecApplyConfiguration {\n\treturn \u0026HorizontalPodAutoscalerSpecApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100020680,"name":"WithScaleTargetRef","signature":"func (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithScaleTargetRef(value *CrossVersionObjectReferenceApplyConfiguration) *HorizontalPodAutoscalerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscalerspec.go","code":"// WithScaleTargetRef sets the ScaleTargetRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ScaleTargetRef field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithScaleTargetRef(value *CrossVersionObjectReferenceApplyConfiguration) *HorizontalPodAutoscalerSpecApplyConfiguration {\n\tb.ScaleTargetRef = value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100020681,"name":"WithMinReplicas","signature":"func (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithMinReplicas(value int32) *HorizontalPodAutoscalerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscalerspec.go","code":"// WithMinReplicas sets the MinReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MinReplicas field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithMinReplicas(value int32) *HorizontalPodAutoscalerSpecApplyConfiguration {\n\tb.MinReplicas = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100020682,"name":"WithMaxReplicas","signature":"func (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithMaxReplicas(value int32) *HorizontalPodAutoscalerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscalerspec.go","code":"// WithMaxReplicas sets the MaxReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MaxReplicas field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithMaxReplicas(value int32) *HorizontalPodAutoscalerSpecApplyConfiguration {\n\tb.MaxReplicas = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100020683,"name":"WithMetrics","signature":"func (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithMetrics(values ...*MetricSpecApplyConfiguration) *HorizontalPodAutoscalerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscalerspec.go","code":"// WithMetrics adds the given value to the Metrics field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Metrics field.\nfunc (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithMetrics(values ...*MetricSpecApplyConfiguration) *HorizontalPodAutoscalerSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithMetrics\")\n\t\t}\n\t\tb.Metrics = append(b.Metrics, *values[i])\n\t}\n\treturn b\n}","line":{"from":60,"to":71}} {"id":100020684,"name":"HorizontalPodAutoscalerStatus","signature":"func HorizontalPodAutoscalerStatus() *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscalerstatus.go","code":"// HorizontalPodAutoscalerStatusApplyConfiguration constructs an declarative configuration of the HorizontalPodAutoscalerStatus type for use with\n// apply.\nfunc HorizontalPodAutoscalerStatus() *HorizontalPodAutoscalerStatusApplyConfiguration {\n\treturn \u0026HorizontalPodAutoscalerStatusApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100020685,"name":"WithObservedGeneration","signature":"func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithObservedGeneration(value int64) *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscalerstatus.go","code":"// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObservedGeneration field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithObservedGeneration(value int64) *HorizontalPodAutoscalerStatusApplyConfiguration {\n\tb.ObservedGeneration = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020686,"name":"WithLastScaleTime","signature":"func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithLastScaleTime(value v1.Time) *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscalerstatus.go","code":"// WithLastScaleTime sets the LastScaleTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastScaleTime field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithLastScaleTime(value v1.Time) *HorizontalPodAutoscalerStatusApplyConfiguration {\n\tb.LastScaleTime = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100020687,"name":"WithCurrentReplicas","signature":"func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithCurrentReplicas(value int32) *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscalerstatus.go","code":"// WithCurrentReplicas sets the CurrentReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CurrentReplicas field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithCurrentReplicas(value int32) *HorizontalPodAutoscalerStatusApplyConfiguration {\n\tb.CurrentReplicas = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100020688,"name":"WithDesiredReplicas","signature":"func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithDesiredReplicas(value int32) *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscalerstatus.go","code":"// WithDesiredReplicas sets the DesiredReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DesiredReplicas field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithDesiredReplicas(value int32) *HorizontalPodAutoscalerStatusApplyConfiguration {\n\tb.DesiredReplicas = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100020689,"name":"WithCurrentMetrics","signature":"func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithCurrentMetrics(values ...*MetricStatusApplyConfiguration) *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscalerstatus.go","code":"// WithCurrentMetrics adds the given value to the CurrentMetrics field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the CurrentMetrics field.\nfunc (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithCurrentMetrics(values ...*MetricStatusApplyConfiguration) *HorizontalPodAutoscalerStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithCurrentMetrics\")\n\t\t}\n\t\tb.CurrentMetrics = append(b.CurrentMetrics, *values[i])\n\t}\n\treturn b\n}","line":{"from":74,"to":85}} {"id":100020690,"name":"WithConditions","signature":"func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithConditions(values ...*HorizontalPodAutoscalerConditionApplyConfiguration) *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/horizontalpodautoscalerstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithConditions(values ...*HorizontalPodAutoscalerConditionApplyConfiguration) *HorizontalPodAutoscalerStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":87,"to":98}} {"id":100020691,"name":"MetricSpec","signature":"func MetricSpec() *MetricSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/metricspec.go","code":"// MetricSpecApplyConfiguration constructs an declarative configuration of the MetricSpec type for use with\n// apply.\nfunc MetricSpec() *MetricSpecApplyConfiguration {\n\treturn \u0026MetricSpecApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100020692,"name":"WithType","signature":"func (b *MetricSpecApplyConfiguration) WithType(value v2beta1.MetricSourceType) *MetricSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/metricspec.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *MetricSpecApplyConfiguration) WithType(value v2beta1.MetricSourceType) *MetricSpecApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020693,"name":"WithObject","signature":"func (b *MetricSpecApplyConfiguration) WithObject(value *ObjectMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/metricspec.go","code":"// WithObject sets the Object field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Object field is set to the value of the last call.\nfunc (b *MetricSpecApplyConfiguration) WithObject(value *ObjectMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration {\n\tb.Object = value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100020694,"name":"WithPods","signature":"func (b *MetricSpecApplyConfiguration) WithPods(value *PodsMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/metricspec.go","code":"// WithPods sets the Pods field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Pods field is set to the value of the last call.\nfunc (b *MetricSpecApplyConfiguration) WithPods(value *PodsMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration {\n\tb.Pods = value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100020695,"name":"WithResource","signature":"func (b *MetricSpecApplyConfiguration) WithResource(value *ResourceMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/metricspec.go","code":"// WithResource sets the Resource field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Resource field is set to the value of the last call.\nfunc (b *MetricSpecApplyConfiguration) WithResource(value *ResourceMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration {\n\tb.Resource = value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100020696,"name":"WithContainerResource","signature":"func (b *MetricSpecApplyConfiguration) WithContainerResource(value *ContainerResourceMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/metricspec.go","code":"// WithContainerResource sets the ContainerResource field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ContainerResource field is set to the value of the last call.\nfunc (b *MetricSpecApplyConfiguration) WithContainerResource(value *ContainerResourceMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration {\n\tb.ContainerResource = value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100020697,"name":"WithExternal","signature":"func (b *MetricSpecApplyConfiguration) WithExternal(value *ExternalMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/metricspec.go","code":"// WithExternal sets the External field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the External field is set to the value of the last call.\nfunc (b *MetricSpecApplyConfiguration) WithExternal(value *ExternalMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration {\n\tb.External = value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100020698,"name":"MetricStatus","signature":"func MetricStatus() *MetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/metricstatus.go","code":"// MetricStatusApplyConfiguration constructs an declarative configuration of the MetricStatus type for use with\n// apply.\nfunc MetricStatus() *MetricStatusApplyConfiguration {\n\treturn \u0026MetricStatusApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100020699,"name":"WithType","signature":"func (b *MetricStatusApplyConfiguration) WithType(value v2beta1.MetricSourceType) *MetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/metricstatus.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *MetricStatusApplyConfiguration) WithType(value v2beta1.MetricSourceType) *MetricStatusApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020700,"name":"WithObject","signature":"func (b *MetricStatusApplyConfiguration) WithObject(value *ObjectMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/metricstatus.go","code":"// WithObject sets the Object field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Object field is set to the value of the last call.\nfunc (b *MetricStatusApplyConfiguration) WithObject(value *ObjectMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration {\n\tb.Object = value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100020701,"name":"WithPods","signature":"func (b *MetricStatusApplyConfiguration) WithPods(value *PodsMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/metricstatus.go","code":"// WithPods sets the Pods field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Pods field is set to the value of the last call.\nfunc (b *MetricStatusApplyConfiguration) WithPods(value *PodsMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration {\n\tb.Pods = value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100020702,"name":"WithResource","signature":"func (b *MetricStatusApplyConfiguration) WithResource(value *ResourceMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/metricstatus.go","code":"// WithResource sets the Resource field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Resource field is set to the value of the last call.\nfunc (b *MetricStatusApplyConfiguration) WithResource(value *ResourceMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration {\n\tb.Resource = value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100020703,"name":"WithContainerResource","signature":"func (b *MetricStatusApplyConfiguration) WithContainerResource(value *ContainerResourceMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/metricstatus.go","code":"// WithContainerResource sets the ContainerResource field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ContainerResource field is set to the value of the last call.\nfunc (b *MetricStatusApplyConfiguration) WithContainerResource(value *ContainerResourceMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration {\n\tb.ContainerResource = value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100020704,"name":"WithExternal","signature":"func (b *MetricStatusApplyConfiguration) WithExternal(value *ExternalMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/metricstatus.go","code":"// WithExternal sets the External field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the External field is set to the value of the last call.\nfunc (b *MetricStatusApplyConfiguration) WithExternal(value *ExternalMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration {\n\tb.External = value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100020705,"name":"ObjectMetricSource","signature":"func ObjectMetricSource() *ObjectMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/objectmetricsource.go","code":"// ObjectMetricSourceApplyConfiguration constructs an declarative configuration of the ObjectMetricSource type for use with\n// apply.\nfunc ObjectMetricSource() *ObjectMetricSourceApplyConfiguration {\n\treturn \u0026ObjectMetricSourceApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100020706,"name":"WithTarget","signature":"func (b *ObjectMetricSourceApplyConfiguration) WithTarget(value *CrossVersionObjectReferenceApplyConfiguration) *ObjectMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/objectmetricsource.go","code":"// WithTarget sets the Target field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Target field is set to the value of the last call.\nfunc (b *ObjectMetricSourceApplyConfiguration) WithTarget(value *CrossVersionObjectReferenceApplyConfiguration) *ObjectMetricSourceApplyConfiguration {\n\tb.Target = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020707,"name":"WithMetricName","signature":"func (b *ObjectMetricSourceApplyConfiguration) WithMetricName(value string) *ObjectMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/objectmetricsource.go","code":"// WithMetricName sets the MetricName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MetricName field is set to the value of the last call.\nfunc (b *ObjectMetricSourceApplyConfiguration) WithMetricName(value string) *ObjectMetricSourceApplyConfiguration {\n\tb.MetricName = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100020708,"name":"WithTargetValue","signature":"func (b *ObjectMetricSourceApplyConfiguration) WithTargetValue(value resource.Quantity) *ObjectMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/objectmetricsource.go","code":"// WithTargetValue sets the TargetValue field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TargetValue field is set to the value of the last call.\nfunc (b *ObjectMetricSourceApplyConfiguration) WithTargetValue(value resource.Quantity) *ObjectMetricSourceApplyConfiguration {\n\tb.TargetValue = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100020709,"name":"WithSelector","signature":"func (b *ObjectMetricSourceApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *ObjectMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/objectmetricsource.go","code":"// WithSelector sets the Selector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Selector field is set to the value of the last call.\nfunc (b *ObjectMetricSourceApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *ObjectMetricSourceApplyConfiguration {\n\tb.Selector = value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100020710,"name":"WithAverageValue","signature":"func (b *ObjectMetricSourceApplyConfiguration) WithAverageValue(value resource.Quantity) *ObjectMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/objectmetricsource.go","code":"// WithAverageValue sets the AverageValue field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AverageValue field is set to the value of the last call.\nfunc (b *ObjectMetricSourceApplyConfiguration) WithAverageValue(value resource.Quantity) *ObjectMetricSourceApplyConfiguration {\n\tb.AverageValue = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100020711,"name":"ObjectMetricStatus","signature":"func ObjectMetricStatus() *ObjectMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/objectmetricstatus.go","code":"// ObjectMetricStatusApplyConfiguration constructs an declarative configuration of the ObjectMetricStatus type for use with\n// apply.\nfunc ObjectMetricStatus() *ObjectMetricStatusApplyConfiguration {\n\treturn \u0026ObjectMetricStatusApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100020712,"name":"WithTarget","signature":"func (b *ObjectMetricStatusApplyConfiguration) WithTarget(value *CrossVersionObjectReferenceApplyConfiguration) *ObjectMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/objectmetricstatus.go","code":"// WithTarget sets the Target field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Target field is set to the value of the last call.\nfunc (b *ObjectMetricStatusApplyConfiguration) WithTarget(value *CrossVersionObjectReferenceApplyConfiguration) *ObjectMetricStatusApplyConfiguration {\n\tb.Target = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020713,"name":"WithMetricName","signature":"func (b *ObjectMetricStatusApplyConfiguration) WithMetricName(value string) *ObjectMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/objectmetricstatus.go","code":"// WithMetricName sets the MetricName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MetricName field is set to the value of the last call.\nfunc (b *ObjectMetricStatusApplyConfiguration) WithMetricName(value string) *ObjectMetricStatusApplyConfiguration {\n\tb.MetricName = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100020714,"name":"WithCurrentValue","signature":"func (b *ObjectMetricStatusApplyConfiguration) WithCurrentValue(value resource.Quantity) *ObjectMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/objectmetricstatus.go","code":"// WithCurrentValue sets the CurrentValue field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CurrentValue field is set to the value of the last call.\nfunc (b *ObjectMetricStatusApplyConfiguration) WithCurrentValue(value resource.Quantity) *ObjectMetricStatusApplyConfiguration {\n\tb.CurrentValue = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100020715,"name":"WithSelector","signature":"func (b *ObjectMetricStatusApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *ObjectMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/objectmetricstatus.go","code":"// WithSelector sets the Selector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Selector field is set to the value of the last call.\nfunc (b *ObjectMetricStatusApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *ObjectMetricStatusApplyConfiguration {\n\tb.Selector = value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100020716,"name":"WithAverageValue","signature":"func (b *ObjectMetricStatusApplyConfiguration) WithAverageValue(value resource.Quantity) *ObjectMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/objectmetricstatus.go","code":"// WithAverageValue sets the AverageValue field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AverageValue field is set to the value of the last call.\nfunc (b *ObjectMetricStatusApplyConfiguration) WithAverageValue(value resource.Quantity) *ObjectMetricStatusApplyConfiguration {\n\tb.AverageValue = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100020717,"name":"PodsMetricSource","signature":"func PodsMetricSource() *PodsMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/podsmetricsource.go","code":"// PodsMetricSourceApplyConfiguration constructs an declarative configuration of the PodsMetricSource type for use with\n// apply.\nfunc PodsMetricSource() *PodsMetricSourceApplyConfiguration {\n\treturn \u0026PodsMetricSourceApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100020718,"name":"WithMetricName","signature":"func (b *PodsMetricSourceApplyConfiguration) WithMetricName(value string) *PodsMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/podsmetricsource.go","code":"// WithMetricName sets the MetricName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MetricName field is set to the value of the last call.\nfunc (b *PodsMetricSourceApplyConfiguration) WithMetricName(value string) *PodsMetricSourceApplyConfiguration {\n\tb.MetricName = \u0026value\n\treturn b\n}","line":{"from":40,"to":46}} {"id":100020719,"name":"WithTargetAverageValue","signature":"func (b *PodsMetricSourceApplyConfiguration) WithTargetAverageValue(value resource.Quantity) *PodsMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/podsmetricsource.go","code":"// WithTargetAverageValue sets the TargetAverageValue field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TargetAverageValue field is set to the value of the last call.\nfunc (b *PodsMetricSourceApplyConfiguration) WithTargetAverageValue(value resource.Quantity) *PodsMetricSourceApplyConfiguration {\n\tb.TargetAverageValue = \u0026value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100020720,"name":"WithSelector","signature":"func (b *PodsMetricSourceApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *PodsMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/podsmetricsource.go","code":"// WithSelector sets the Selector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Selector field is set to the value of the last call.\nfunc (b *PodsMetricSourceApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *PodsMetricSourceApplyConfiguration {\n\tb.Selector = value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100020721,"name":"PodsMetricStatus","signature":"func PodsMetricStatus() *PodsMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/podsmetricstatus.go","code":"// PodsMetricStatusApplyConfiguration constructs an declarative configuration of the PodsMetricStatus type for use with\n// apply.\nfunc PodsMetricStatus() *PodsMetricStatusApplyConfiguration {\n\treturn \u0026PodsMetricStatusApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100020722,"name":"WithMetricName","signature":"func (b *PodsMetricStatusApplyConfiguration) WithMetricName(value string) *PodsMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/podsmetricstatus.go","code":"// WithMetricName sets the MetricName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MetricName field is set to the value of the last call.\nfunc (b *PodsMetricStatusApplyConfiguration) WithMetricName(value string) *PodsMetricStatusApplyConfiguration {\n\tb.MetricName = \u0026value\n\treturn b\n}","line":{"from":40,"to":46}} {"id":100020723,"name":"WithCurrentAverageValue","signature":"func (b *PodsMetricStatusApplyConfiguration) WithCurrentAverageValue(value resource.Quantity) *PodsMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/podsmetricstatus.go","code":"// WithCurrentAverageValue sets the CurrentAverageValue field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CurrentAverageValue field is set to the value of the last call.\nfunc (b *PodsMetricStatusApplyConfiguration) WithCurrentAverageValue(value resource.Quantity) *PodsMetricStatusApplyConfiguration {\n\tb.CurrentAverageValue = \u0026value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100020724,"name":"WithSelector","signature":"func (b *PodsMetricStatusApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *PodsMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/podsmetricstatus.go","code":"// WithSelector sets the Selector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Selector field is set to the value of the last call.\nfunc (b *PodsMetricStatusApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *PodsMetricStatusApplyConfiguration {\n\tb.Selector = value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100020725,"name":"ResourceMetricSource","signature":"func ResourceMetricSource() *ResourceMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/resourcemetricsource.go","code":"// ResourceMetricSourceApplyConfiguration constructs an declarative configuration of the ResourceMetricSource type for use with\n// apply.\nfunc ResourceMetricSource() *ResourceMetricSourceApplyConfiguration {\n\treturn \u0026ResourceMetricSourceApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100020726,"name":"WithName","signature":"func (b *ResourceMetricSourceApplyConfiguration) WithName(value v1.ResourceName) *ResourceMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/resourcemetricsource.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ResourceMetricSourceApplyConfiguration) WithName(value v1.ResourceName) *ResourceMetricSourceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":40,"to":46}} {"id":100020727,"name":"WithTargetAverageUtilization","signature":"func (b *ResourceMetricSourceApplyConfiguration) WithTargetAverageUtilization(value int32) *ResourceMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/resourcemetricsource.go","code":"// WithTargetAverageUtilization sets the TargetAverageUtilization field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TargetAverageUtilization field is set to the value of the last call.\nfunc (b *ResourceMetricSourceApplyConfiguration) WithTargetAverageUtilization(value int32) *ResourceMetricSourceApplyConfiguration {\n\tb.TargetAverageUtilization = \u0026value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100020728,"name":"WithTargetAverageValue","signature":"func (b *ResourceMetricSourceApplyConfiguration) WithTargetAverageValue(value resource.Quantity) *ResourceMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/resourcemetricsource.go","code":"// WithTargetAverageValue sets the TargetAverageValue field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TargetAverageValue field is set to the value of the last call.\nfunc (b *ResourceMetricSourceApplyConfiguration) WithTargetAverageValue(value resource.Quantity) *ResourceMetricSourceApplyConfiguration {\n\tb.TargetAverageValue = \u0026value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100020729,"name":"ResourceMetricStatus","signature":"func ResourceMetricStatus() *ResourceMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/resourcemetricstatus.go","code":"// ResourceMetricStatusApplyConfiguration constructs an declarative configuration of the ResourceMetricStatus type for use with\n// apply.\nfunc ResourceMetricStatus() *ResourceMetricStatusApplyConfiguration {\n\treturn \u0026ResourceMetricStatusApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100020730,"name":"WithName","signature":"func (b *ResourceMetricStatusApplyConfiguration) WithName(value v1.ResourceName) *ResourceMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/resourcemetricstatus.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ResourceMetricStatusApplyConfiguration) WithName(value v1.ResourceName) *ResourceMetricStatusApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":40,"to":46}} {"id":100020731,"name":"WithCurrentAverageUtilization","signature":"func (b *ResourceMetricStatusApplyConfiguration) WithCurrentAverageUtilization(value int32) *ResourceMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/resourcemetricstatus.go","code":"// WithCurrentAverageUtilization sets the CurrentAverageUtilization field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CurrentAverageUtilization field is set to the value of the last call.\nfunc (b *ResourceMetricStatusApplyConfiguration) WithCurrentAverageUtilization(value int32) *ResourceMetricStatusApplyConfiguration {\n\tb.CurrentAverageUtilization = \u0026value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100020732,"name":"WithCurrentAverageValue","signature":"func (b *ResourceMetricStatusApplyConfiguration) WithCurrentAverageValue(value resource.Quantity) *ResourceMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta1/resourcemetricstatus.go","code":"// WithCurrentAverageValue sets the CurrentAverageValue field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CurrentAverageValue field is set to the value of the last call.\nfunc (b *ResourceMetricStatusApplyConfiguration) WithCurrentAverageValue(value resource.Quantity) *ResourceMetricStatusApplyConfiguration {\n\tb.CurrentAverageValue = \u0026value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100020733,"name":"ContainerResourceMetricSource","signature":"func ContainerResourceMetricSource() *ContainerResourceMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/containerresourcemetricsource.go","code":"// ContainerResourceMetricSourceApplyConfiguration constructs an declarative configuration of the ContainerResourceMetricSource type for use with\n// apply.\nfunc ContainerResourceMetricSource() *ContainerResourceMetricSourceApplyConfiguration {\n\treturn \u0026ContainerResourceMetricSourceApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100020734,"name":"WithName","signature":"func (b *ContainerResourceMetricSourceApplyConfiguration) WithName(value v1.ResourceName) *ContainerResourceMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/containerresourcemetricsource.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ContainerResourceMetricSourceApplyConfiguration) WithName(value v1.ResourceName) *ContainerResourceMetricSourceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100020735,"name":"WithTarget","signature":"func (b *ContainerResourceMetricSourceApplyConfiguration) WithTarget(value *MetricTargetApplyConfiguration) *ContainerResourceMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/containerresourcemetricsource.go","code":"// WithTarget sets the Target field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Target field is set to the value of the last call.\nfunc (b *ContainerResourceMetricSourceApplyConfiguration) WithTarget(value *MetricTargetApplyConfiguration) *ContainerResourceMetricSourceApplyConfiguration {\n\tb.Target = value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100020736,"name":"WithContainer","signature":"func (b *ContainerResourceMetricSourceApplyConfiguration) WithContainer(value string) *ContainerResourceMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/containerresourcemetricsource.go","code":"// WithContainer sets the Container field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Container field is set to the value of the last call.\nfunc (b *ContainerResourceMetricSourceApplyConfiguration) WithContainer(value string) *ContainerResourceMetricSourceApplyConfiguration {\n\tb.Container = \u0026value\n\treturn b\n}","line":{"from":55,"to":61}} {"id":100020737,"name":"ContainerResourceMetricStatus","signature":"func ContainerResourceMetricStatus() *ContainerResourceMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/containerresourcemetricstatus.go","code":"// ContainerResourceMetricStatusApplyConfiguration constructs an declarative configuration of the ContainerResourceMetricStatus type for use with\n// apply.\nfunc ContainerResourceMetricStatus() *ContainerResourceMetricStatusApplyConfiguration {\n\treturn \u0026ContainerResourceMetricStatusApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100020738,"name":"WithName","signature":"func (b *ContainerResourceMetricStatusApplyConfiguration) WithName(value v1.ResourceName) *ContainerResourceMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/containerresourcemetricstatus.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ContainerResourceMetricStatusApplyConfiguration) WithName(value v1.ResourceName) *ContainerResourceMetricStatusApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100020739,"name":"WithCurrent","signature":"func (b *ContainerResourceMetricStatusApplyConfiguration) WithCurrent(value *MetricValueStatusApplyConfiguration) *ContainerResourceMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/containerresourcemetricstatus.go","code":"// WithCurrent sets the Current field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Current field is set to the value of the last call.\nfunc (b *ContainerResourceMetricStatusApplyConfiguration) WithCurrent(value *MetricValueStatusApplyConfiguration) *ContainerResourceMetricStatusApplyConfiguration {\n\tb.Current = value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100020740,"name":"WithContainer","signature":"func (b *ContainerResourceMetricStatusApplyConfiguration) WithContainer(value string) *ContainerResourceMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/containerresourcemetricstatus.go","code":"// WithContainer sets the Container field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Container field is set to the value of the last call.\nfunc (b *ContainerResourceMetricStatusApplyConfiguration) WithContainer(value string) *ContainerResourceMetricStatusApplyConfiguration {\n\tb.Container = \u0026value\n\treturn b\n}","line":{"from":55,"to":61}} {"id":100020741,"name":"CrossVersionObjectReference","signature":"func CrossVersionObjectReference() *CrossVersionObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/crossversionobjectreference.go","code":"// CrossVersionObjectReferenceApplyConfiguration constructs an declarative configuration of the CrossVersionObjectReference type for use with\n// apply.\nfunc CrossVersionObjectReference() *CrossVersionObjectReferenceApplyConfiguration {\n\treturn \u0026CrossVersionObjectReferenceApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100020742,"name":"WithKind","signature":"func (b *CrossVersionObjectReferenceApplyConfiguration) WithKind(value string) *CrossVersionObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/crossversionobjectreference.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *CrossVersionObjectReferenceApplyConfiguration) WithKind(value string) *CrossVersionObjectReferenceApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100020743,"name":"WithName","signature":"func (b *CrossVersionObjectReferenceApplyConfiguration) WithName(value string) *CrossVersionObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/crossversionobjectreference.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *CrossVersionObjectReferenceApplyConfiguration) WithName(value string) *CrossVersionObjectReferenceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100020744,"name":"WithAPIVersion","signature":"func (b *CrossVersionObjectReferenceApplyConfiguration) WithAPIVersion(value string) *CrossVersionObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/crossversionobjectreference.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *CrossVersionObjectReferenceApplyConfiguration) WithAPIVersion(value string) *CrossVersionObjectReferenceApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100020745,"name":"ExternalMetricSource","signature":"func ExternalMetricSource() *ExternalMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/externalmetricsource.go","code":"// ExternalMetricSourceApplyConfiguration constructs an declarative configuration of the ExternalMetricSource type for use with\n// apply.\nfunc ExternalMetricSource() *ExternalMetricSourceApplyConfiguration {\n\treturn \u0026ExternalMetricSourceApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100020746,"name":"WithMetric","signature":"func (b *ExternalMetricSourceApplyConfiguration) WithMetric(value *MetricIdentifierApplyConfiguration) *ExternalMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/externalmetricsource.go","code":"// WithMetric sets the Metric field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Metric field is set to the value of the last call.\nfunc (b *ExternalMetricSourceApplyConfiguration) WithMetric(value *MetricIdentifierApplyConfiguration) *ExternalMetricSourceApplyConfiguration {\n\tb.Metric = value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100020747,"name":"WithTarget","signature":"func (b *ExternalMetricSourceApplyConfiguration) WithTarget(value *MetricTargetApplyConfiguration) *ExternalMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/externalmetricsource.go","code":"// WithTarget sets the Target field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Target field is set to the value of the last call.\nfunc (b *ExternalMetricSourceApplyConfiguration) WithTarget(value *MetricTargetApplyConfiguration) *ExternalMetricSourceApplyConfiguration {\n\tb.Target = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020748,"name":"ExternalMetricStatus","signature":"func ExternalMetricStatus() *ExternalMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/externalmetricstatus.go","code":"// ExternalMetricStatusApplyConfiguration constructs an declarative configuration of the ExternalMetricStatus type for use with\n// apply.\nfunc ExternalMetricStatus() *ExternalMetricStatusApplyConfiguration {\n\treturn \u0026ExternalMetricStatusApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100020749,"name":"WithMetric","signature":"func (b *ExternalMetricStatusApplyConfiguration) WithMetric(value *MetricIdentifierApplyConfiguration) *ExternalMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/externalmetricstatus.go","code":"// WithMetric sets the Metric field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Metric field is set to the value of the last call.\nfunc (b *ExternalMetricStatusApplyConfiguration) WithMetric(value *MetricIdentifierApplyConfiguration) *ExternalMetricStatusApplyConfiguration {\n\tb.Metric = value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100020750,"name":"WithCurrent","signature":"func (b *ExternalMetricStatusApplyConfiguration) WithCurrent(value *MetricValueStatusApplyConfiguration) *ExternalMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/externalmetricstatus.go","code":"// WithCurrent sets the Current field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Current field is set to the value of the last call.\nfunc (b *ExternalMetricStatusApplyConfiguration) WithCurrent(value *MetricValueStatusApplyConfiguration) *ExternalMetricStatusApplyConfiguration {\n\tb.Current = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020751,"name":"HorizontalPodAutoscaler","signature":"func HorizontalPodAutoscaler(name, namespace string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// HorizontalPodAutoscaler constructs an declarative configuration of the HorizontalPodAutoscaler type for use with\n// apply.\nfunc HorizontalPodAutoscaler(name, namespace string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb := \u0026HorizontalPodAutoscalerApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"HorizontalPodAutoscaler\")\n\tb.WithAPIVersion(\"autoscaling/v2beta2\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100020752,"name":"ExtractHorizontalPodAutoscaler","signature":"func ExtractHorizontalPodAutoscaler(horizontalPodAutoscaler *autoscalingv2beta2.HorizontalPodAutoscaler, fieldManager string) (*HorizontalPodAutoscalerApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// ExtractHorizontalPodAutoscaler extracts the applied configuration owned by fieldManager from\n// horizontalPodAutoscaler. If no managedFields are found in horizontalPodAutoscaler for fieldManager, a\n// HorizontalPodAutoscalerApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// horizontalPodAutoscaler must be a unmodified HorizontalPodAutoscaler API object that was retrieved from the Kubernetes API.\n// ExtractHorizontalPodAutoscaler provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractHorizontalPodAutoscaler(horizontalPodAutoscaler *autoscalingv2beta2.HorizontalPodAutoscaler, fieldManager string) (*HorizontalPodAutoscalerApplyConfiguration, error) {\n\treturn extractHorizontalPodAutoscaler(horizontalPodAutoscaler, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100020753,"name":"ExtractHorizontalPodAutoscalerStatus","signature":"func ExtractHorizontalPodAutoscalerStatus(horizontalPodAutoscaler *autoscalingv2beta2.HorizontalPodAutoscaler, fieldManager string) (*HorizontalPodAutoscalerApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// ExtractHorizontalPodAutoscalerStatus is the same as ExtractHorizontalPodAutoscaler except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractHorizontalPodAutoscalerStatus(horizontalPodAutoscaler *autoscalingv2beta2.HorizontalPodAutoscaler, fieldManager string) (*HorizontalPodAutoscalerApplyConfiguration, error) {\n\treturn extractHorizontalPodAutoscaler(horizontalPodAutoscaler, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100020754,"name":"extractHorizontalPodAutoscaler","signature":"func extractHorizontalPodAutoscaler(horizontalPodAutoscaler *autoscalingv2beta2.HorizontalPodAutoscaler, fieldManager string, subresource string) (*HorizontalPodAutoscalerApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"func extractHorizontalPodAutoscaler(horizontalPodAutoscaler *autoscalingv2beta2.HorizontalPodAutoscaler, fieldManager string, subresource string) (*HorizontalPodAutoscalerApplyConfiguration, error) {\n\tb := \u0026HorizontalPodAutoscalerApplyConfiguration{}\n\terr := managedfields.ExtractInto(horizontalPodAutoscaler, internal.Parser().Type(\"io.k8s.api.autoscaling.v2beta2.HorizontalPodAutoscaler\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(horizontalPodAutoscaler.Name)\n\tb.WithNamespace(horizontalPodAutoscaler.Namespace)\n\n\tb.WithKind(\"HorizontalPodAutoscaler\")\n\tb.WithAPIVersion(\"autoscaling/v2beta2\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100020755,"name":"WithKind","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithKind(value string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithKind(value string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100020756,"name":"WithAPIVersion","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithAPIVersion(value string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithAPIVersion(value string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100020757,"name":"WithName","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithName(value string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithName(value string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100020758,"name":"WithGenerateName","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithGenerateName(value string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithGenerateName(value string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100020759,"name":"WithNamespace","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithNamespace(value string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithNamespace(value string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100020760,"name":"WithUID","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithUID(value types.UID) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithUID(value types.UID) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100020761,"name":"WithResourceVersion","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithResourceVersion(value string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithResourceVersion(value string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100020762,"name":"WithGeneration","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithGeneration(value int64) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithGeneration(value int64) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100020763,"name":"WithCreationTimestamp","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithCreationTimestamp(value metav1.Time) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithCreationTimestamp(value metav1.Time) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100020764,"name":"WithDeletionTimestamp","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100020765,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100020766,"name":"WithLabels","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithLabels(entries map[string]string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithLabels(entries map[string]string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100020767,"name":"WithAnnotations","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithAnnotations(entries map[string]string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithAnnotations(entries map[string]string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100020768,"name":"WithOwnerReferences","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100020769,"name":"WithFinalizers","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithFinalizers(values ...string) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithFinalizers(values ...string) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100020770,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"func (b *HorizontalPodAutoscalerApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100020771,"name":"WithSpec","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithSpec(value *HorizontalPodAutoscalerSpecApplyConfiguration) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithSpec(value *HorizontalPodAutoscalerSpecApplyConfiguration) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100020772,"name":"WithStatus","signature":"func (b *HorizontalPodAutoscalerApplyConfiguration) WithStatus(value *HorizontalPodAutoscalerStatusApplyConfiguration) *HorizontalPodAutoscalerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerApplyConfiguration) WithStatus(value *HorizontalPodAutoscalerStatusApplyConfiguration) *HorizontalPodAutoscalerApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100020773,"name":"HorizontalPodAutoscalerBehavior","signature":"func HorizontalPodAutoscalerBehavior() *HorizontalPodAutoscalerBehaviorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscalerbehavior.go","code":"// HorizontalPodAutoscalerBehaviorApplyConfiguration constructs an declarative configuration of the HorizontalPodAutoscalerBehavior type for use with\n// apply.\nfunc HorizontalPodAutoscalerBehavior() *HorizontalPodAutoscalerBehaviorApplyConfiguration {\n\treturn \u0026HorizontalPodAutoscalerBehaviorApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100020774,"name":"WithScaleUp","signature":"func (b *HorizontalPodAutoscalerBehaviorApplyConfiguration) WithScaleUp(value *HPAScalingRulesApplyConfiguration) *HorizontalPodAutoscalerBehaviorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscalerbehavior.go","code":"// WithScaleUp sets the ScaleUp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ScaleUp field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerBehaviorApplyConfiguration) WithScaleUp(value *HPAScalingRulesApplyConfiguration) *HorizontalPodAutoscalerBehaviorApplyConfiguration {\n\tb.ScaleUp = value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100020775,"name":"WithScaleDown","signature":"func (b *HorizontalPodAutoscalerBehaviorApplyConfiguration) WithScaleDown(value *HPAScalingRulesApplyConfiguration) *HorizontalPodAutoscalerBehaviorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscalerbehavior.go","code":"// WithScaleDown sets the ScaleDown field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ScaleDown field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerBehaviorApplyConfiguration) WithScaleDown(value *HPAScalingRulesApplyConfiguration) *HorizontalPodAutoscalerBehaviorApplyConfiguration {\n\tb.ScaleDown = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020776,"name":"HorizontalPodAutoscalerCondition","signature":"func HorizontalPodAutoscalerCondition() *HorizontalPodAutoscalerConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscalercondition.go","code":"// HorizontalPodAutoscalerConditionApplyConfiguration constructs an declarative configuration of the HorizontalPodAutoscalerCondition type for use with\n// apply.\nfunc HorizontalPodAutoscalerCondition() *HorizontalPodAutoscalerConditionApplyConfiguration {\n\treturn \u0026HorizontalPodAutoscalerConditionApplyConfiguration{}\n}","line":{"from":37,"to":41}} {"id":100020777,"name":"WithType","signature":"func (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithType(value v2beta2.HorizontalPodAutoscalerConditionType) *HorizontalPodAutoscalerConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscalercondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithType(value v2beta2.HorizontalPodAutoscalerConditionType) *HorizontalPodAutoscalerConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100020778,"name":"WithStatus","signature":"func (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *HorizontalPodAutoscalerConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscalercondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *HorizontalPodAutoscalerConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100020779,"name":"WithLastTransitionTime","signature":"func (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *HorizontalPodAutoscalerConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscalercondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *HorizontalPodAutoscalerConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":59,"to":65}} {"id":100020780,"name":"WithReason","signature":"func (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithReason(value string) *HorizontalPodAutoscalerConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscalercondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithReason(value string) *HorizontalPodAutoscalerConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100020781,"name":"WithMessage","signature":"func (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithMessage(value string) *HorizontalPodAutoscalerConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscalercondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerConditionApplyConfiguration) WithMessage(value string) *HorizontalPodAutoscalerConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":75,"to":81}} {"id":100020782,"name":"HorizontalPodAutoscalerSpec","signature":"func HorizontalPodAutoscalerSpec() *HorizontalPodAutoscalerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscalerspec.go","code":"// HorizontalPodAutoscalerSpecApplyConfiguration constructs an declarative configuration of the HorizontalPodAutoscalerSpec type for use with\n// apply.\nfunc HorizontalPodAutoscalerSpec() *HorizontalPodAutoscalerSpecApplyConfiguration {\n\treturn \u0026HorizontalPodAutoscalerSpecApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100020783,"name":"WithScaleTargetRef","signature":"func (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithScaleTargetRef(value *CrossVersionObjectReferenceApplyConfiguration) *HorizontalPodAutoscalerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscalerspec.go","code":"// WithScaleTargetRef sets the ScaleTargetRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ScaleTargetRef field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithScaleTargetRef(value *CrossVersionObjectReferenceApplyConfiguration) *HorizontalPodAutoscalerSpecApplyConfiguration {\n\tb.ScaleTargetRef = value\n\treturn b\n}","line":{"from":37,"to":43}} {"id":100020784,"name":"WithMinReplicas","signature":"func (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithMinReplicas(value int32) *HorizontalPodAutoscalerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscalerspec.go","code":"// WithMinReplicas sets the MinReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MinReplicas field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithMinReplicas(value int32) *HorizontalPodAutoscalerSpecApplyConfiguration {\n\tb.MinReplicas = \u0026value\n\treturn b\n}","line":{"from":45,"to":51}} {"id":100020785,"name":"WithMaxReplicas","signature":"func (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithMaxReplicas(value int32) *HorizontalPodAutoscalerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscalerspec.go","code":"// WithMaxReplicas sets the MaxReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MaxReplicas field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithMaxReplicas(value int32) *HorizontalPodAutoscalerSpecApplyConfiguration {\n\tb.MaxReplicas = \u0026value\n\treturn b\n}","line":{"from":53,"to":59}} {"id":100020786,"name":"WithMetrics","signature":"func (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithMetrics(values ...*MetricSpecApplyConfiguration) *HorizontalPodAutoscalerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscalerspec.go","code":"// WithMetrics adds the given value to the Metrics field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Metrics field.\nfunc (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithMetrics(values ...*MetricSpecApplyConfiguration) *HorizontalPodAutoscalerSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithMetrics\")\n\t\t}\n\t\tb.Metrics = append(b.Metrics, *values[i])\n\t}\n\treturn b\n}","line":{"from":61,"to":72}} {"id":100020787,"name":"WithBehavior","signature":"func (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithBehavior(value *HorizontalPodAutoscalerBehaviorApplyConfiguration) *HorizontalPodAutoscalerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscalerspec.go","code":"// WithBehavior sets the Behavior field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Behavior field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerSpecApplyConfiguration) WithBehavior(value *HorizontalPodAutoscalerBehaviorApplyConfiguration) *HorizontalPodAutoscalerSpecApplyConfiguration {\n\tb.Behavior = value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100020788,"name":"HorizontalPodAutoscalerStatus","signature":"func HorizontalPodAutoscalerStatus() *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscalerstatus.go","code":"// HorizontalPodAutoscalerStatusApplyConfiguration constructs an declarative configuration of the HorizontalPodAutoscalerStatus type for use with\n// apply.\nfunc HorizontalPodAutoscalerStatus() *HorizontalPodAutoscalerStatusApplyConfiguration {\n\treturn \u0026HorizontalPodAutoscalerStatusApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100020789,"name":"WithObservedGeneration","signature":"func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithObservedGeneration(value int64) *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscalerstatus.go","code":"// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObservedGeneration field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithObservedGeneration(value int64) *HorizontalPodAutoscalerStatusApplyConfiguration {\n\tb.ObservedGeneration = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020790,"name":"WithLastScaleTime","signature":"func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithLastScaleTime(value v1.Time) *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscalerstatus.go","code":"// WithLastScaleTime sets the LastScaleTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastScaleTime field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithLastScaleTime(value v1.Time) *HorizontalPodAutoscalerStatusApplyConfiguration {\n\tb.LastScaleTime = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100020791,"name":"WithCurrentReplicas","signature":"func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithCurrentReplicas(value int32) *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscalerstatus.go","code":"// WithCurrentReplicas sets the CurrentReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CurrentReplicas field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithCurrentReplicas(value int32) *HorizontalPodAutoscalerStatusApplyConfiguration {\n\tb.CurrentReplicas = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100020792,"name":"WithDesiredReplicas","signature":"func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithDesiredReplicas(value int32) *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscalerstatus.go","code":"// WithDesiredReplicas sets the DesiredReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DesiredReplicas field is set to the value of the last call.\nfunc (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithDesiredReplicas(value int32) *HorizontalPodAutoscalerStatusApplyConfiguration {\n\tb.DesiredReplicas = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100020793,"name":"WithCurrentMetrics","signature":"func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithCurrentMetrics(values ...*MetricStatusApplyConfiguration) *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscalerstatus.go","code":"// WithCurrentMetrics adds the given value to the CurrentMetrics field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the CurrentMetrics field.\nfunc (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithCurrentMetrics(values ...*MetricStatusApplyConfiguration) *HorizontalPodAutoscalerStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithCurrentMetrics\")\n\t\t}\n\t\tb.CurrentMetrics = append(b.CurrentMetrics, *values[i])\n\t}\n\treturn b\n}","line":{"from":74,"to":85}} {"id":100020794,"name":"WithConditions","signature":"func (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithConditions(values ...*HorizontalPodAutoscalerConditionApplyConfiguration) *HorizontalPodAutoscalerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/horizontalpodautoscalerstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *HorizontalPodAutoscalerStatusApplyConfiguration) WithConditions(values ...*HorizontalPodAutoscalerConditionApplyConfiguration) *HorizontalPodAutoscalerStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":87,"to":98}} {"id":100020795,"name":"HPAScalingPolicy","signature":"func HPAScalingPolicy() *HPAScalingPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/hpascalingpolicy.go","code":"// HPAScalingPolicyApplyConfiguration constructs an declarative configuration of the HPAScalingPolicy type for use with\n// apply.\nfunc HPAScalingPolicy() *HPAScalingPolicyApplyConfiguration {\n\treturn \u0026HPAScalingPolicyApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100020796,"name":"WithType","signature":"func (b *HPAScalingPolicyApplyConfiguration) WithType(value v2beta2.HPAScalingPolicyType) *HPAScalingPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/hpascalingpolicy.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *HPAScalingPolicyApplyConfiguration) WithType(value v2beta2.HPAScalingPolicyType) *HPAScalingPolicyApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100020797,"name":"WithValue","signature":"func (b *HPAScalingPolicyApplyConfiguration) WithValue(value int32) *HPAScalingPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/hpascalingpolicy.go","code":"// WithValue sets the Value field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Value field is set to the value of the last call.\nfunc (b *HPAScalingPolicyApplyConfiguration) WithValue(value int32) *HPAScalingPolicyApplyConfiguration {\n\tb.Value = \u0026value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100020798,"name":"WithPeriodSeconds","signature":"func (b *HPAScalingPolicyApplyConfiguration) WithPeriodSeconds(value int32) *HPAScalingPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/hpascalingpolicy.go","code":"// WithPeriodSeconds sets the PeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PeriodSeconds field is set to the value of the last call.\nfunc (b *HPAScalingPolicyApplyConfiguration) WithPeriodSeconds(value int32) *HPAScalingPolicyApplyConfiguration {\n\tb.PeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":55,"to":61}} {"id":100020799,"name":"HPAScalingRules","signature":"func HPAScalingRules() *HPAScalingRulesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/hpascalingrules.go","code":"// HPAScalingRulesApplyConfiguration constructs an declarative configuration of the HPAScalingRules type for use with\n// apply.\nfunc HPAScalingRules() *HPAScalingRulesApplyConfiguration {\n\treturn \u0026HPAScalingRulesApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100020800,"name":"WithStabilizationWindowSeconds","signature":"func (b *HPAScalingRulesApplyConfiguration) WithStabilizationWindowSeconds(value int32) *HPAScalingRulesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/hpascalingrules.go","code":"// WithStabilizationWindowSeconds sets the StabilizationWindowSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StabilizationWindowSeconds field is set to the value of the last call.\nfunc (b *HPAScalingRulesApplyConfiguration) WithStabilizationWindowSeconds(value int32) *HPAScalingRulesApplyConfiguration {\n\tb.StabilizationWindowSeconds = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100020801,"name":"WithSelectPolicy","signature":"func (b *HPAScalingRulesApplyConfiguration) WithSelectPolicy(value v2beta2.ScalingPolicySelect) *HPAScalingRulesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/hpascalingrules.go","code":"// WithSelectPolicy sets the SelectPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SelectPolicy field is set to the value of the last call.\nfunc (b *HPAScalingRulesApplyConfiguration) WithSelectPolicy(value v2beta2.ScalingPolicySelect) *HPAScalingRulesApplyConfiguration {\n\tb.SelectPolicy = \u0026value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100020802,"name":"WithPolicies","signature":"func (b *HPAScalingRulesApplyConfiguration) WithPolicies(values ...*HPAScalingPolicyApplyConfiguration) *HPAScalingRulesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/hpascalingrules.go","code":"// WithPolicies adds the given value to the Policies field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Policies field.\nfunc (b *HPAScalingRulesApplyConfiguration) WithPolicies(values ...*HPAScalingPolicyApplyConfiguration) *HPAScalingRulesApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPolicies\")\n\t\t}\n\t\tb.Policies = append(b.Policies, *values[i])\n\t}\n\treturn b\n}","line":{"from":55,"to":66}} {"id":100020803,"name":"MetricIdentifier","signature":"func MetricIdentifier() *MetricIdentifierApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/metricidentifier.go","code":"// MetricIdentifierApplyConfiguration constructs an declarative configuration of the MetricIdentifier type for use with\n// apply.\nfunc MetricIdentifier() *MetricIdentifierApplyConfiguration {\n\treturn \u0026MetricIdentifierApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100020804,"name":"WithName","signature":"func (b *MetricIdentifierApplyConfiguration) WithName(value string) *MetricIdentifierApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/metricidentifier.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *MetricIdentifierApplyConfiguration) WithName(value string) *MetricIdentifierApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100020805,"name":"WithSelector","signature":"func (b *MetricIdentifierApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *MetricIdentifierApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/metricidentifier.go","code":"// WithSelector sets the Selector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Selector field is set to the value of the last call.\nfunc (b *MetricIdentifierApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *MetricIdentifierApplyConfiguration {\n\tb.Selector = value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100020806,"name":"MetricSpec","signature":"func MetricSpec() *MetricSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/metricspec.go","code":"// MetricSpecApplyConfiguration constructs an declarative configuration of the MetricSpec type for use with\n// apply.\nfunc MetricSpec() *MetricSpecApplyConfiguration {\n\treturn \u0026MetricSpecApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100020807,"name":"WithType","signature":"func (b *MetricSpecApplyConfiguration) WithType(value v2beta2.MetricSourceType) *MetricSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/metricspec.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *MetricSpecApplyConfiguration) WithType(value v2beta2.MetricSourceType) *MetricSpecApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020808,"name":"WithObject","signature":"func (b *MetricSpecApplyConfiguration) WithObject(value *ObjectMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/metricspec.go","code":"// WithObject sets the Object field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Object field is set to the value of the last call.\nfunc (b *MetricSpecApplyConfiguration) WithObject(value *ObjectMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration {\n\tb.Object = value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100020809,"name":"WithPods","signature":"func (b *MetricSpecApplyConfiguration) WithPods(value *PodsMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/metricspec.go","code":"// WithPods sets the Pods field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Pods field is set to the value of the last call.\nfunc (b *MetricSpecApplyConfiguration) WithPods(value *PodsMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration {\n\tb.Pods = value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100020810,"name":"WithResource","signature":"func (b *MetricSpecApplyConfiguration) WithResource(value *ResourceMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/metricspec.go","code":"// WithResource sets the Resource field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Resource field is set to the value of the last call.\nfunc (b *MetricSpecApplyConfiguration) WithResource(value *ResourceMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration {\n\tb.Resource = value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100020811,"name":"WithContainerResource","signature":"func (b *MetricSpecApplyConfiguration) WithContainerResource(value *ContainerResourceMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/metricspec.go","code":"// WithContainerResource sets the ContainerResource field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ContainerResource field is set to the value of the last call.\nfunc (b *MetricSpecApplyConfiguration) WithContainerResource(value *ContainerResourceMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration {\n\tb.ContainerResource = value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100020812,"name":"WithExternal","signature":"func (b *MetricSpecApplyConfiguration) WithExternal(value *ExternalMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/metricspec.go","code":"// WithExternal sets the External field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the External field is set to the value of the last call.\nfunc (b *MetricSpecApplyConfiguration) WithExternal(value *ExternalMetricSourceApplyConfiguration) *MetricSpecApplyConfiguration {\n\tb.External = value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100020813,"name":"MetricStatus","signature":"func MetricStatus() *MetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/metricstatus.go","code":"// MetricStatusApplyConfiguration constructs an declarative configuration of the MetricStatus type for use with\n// apply.\nfunc MetricStatus() *MetricStatusApplyConfiguration {\n\treturn \u0026MetricStatusApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100020814,"name":"WithType","signature":"func (b *MetricStatusApplyConfiguration) WithType(value v2beta2.MetricSourceType) *MetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/metricstatus.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *MetricStatusApplyConfiguration) WithType(value v2beta2.MetricSourceType) *MetricStatusApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020815,"name":"WithObject","signature":"func (b *MetricStatusApplyConfiguration) WithObject(value *ObjectMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/metricstatus.go","code":"// WithObject sets the Object field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Object field is set to the value of the last call.\nfunc (b *MetricStatusApplyConfiguration) WithObject(value *ObjectMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration {\n\tb.Object = value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100020816,"name":"WithPods","signature":"func (b *MetricStatusApplyConfiguration) WithPods(value *PodsMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/metricstatus.go","code":"// WithPods sets the Pods field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Pods field is set to the value of the last call.\nfunc (b *MetricStatusApplyConfiguration) WithPods(value *PodsMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration {\n\tb.Pods = value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100020817,"name":"WithResource","signature":"func (b *MetricStatusApplyConfiguration) WithResource(value *ResourceMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/metricstatus.go","code":"// WithResource sets the Resource field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Resource field is set to the value of the last call.\nfunc (b *MetricStatusApplyConfiguration) WithResource(value *ResourceMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration {\n\tb.Resource = value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100020818,"name":"WithContainerResource","signature":"func (b *MetricStatusApplyConfiguration) WithContainerResource(value *ContainerResourceMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/metricstatus.go","code":"// WithContainerResource sets the ContainerResource field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ContainerResource field is set to the value of the last call.\nfunc (b *MetricStatusApplyConfiguration) WithContainerResource(value *ContainerResourceMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration {\n\tb.ContainerResource = value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100020819,"name":"WithExternal","signature":"func (b *MetricStatusApplyConfiguration) WithExternal(value *ExternalMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/metricstatus.go","code":"// WithExternal sets the External field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the External field is set to the value of the last call.\nfunc (b *MetricStatusApplyConfiguration) WithExternal(value *ExternalMetricStatusApplyConfiguration) *MetricStatusApplyConfiguration {\n\tb.External = value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100020820,"name":"MetricTarget","signature":"func MetricTarget() *MetricTargetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/metrictarget.go","code":"// MetricTargetApplyConfiguration constructs an declarative configuration of the MetricTarget type for use with\n// apply.\nfunc MetricTarget() *MetricTargetApplyConfiguration {\n\treturn \u0026MetricTargetApplyConfiguration{}\n}","line":{"from":35,"to":39}} {"id":100020821,"name":"WithType","signature":"func (b *MetricTargetApplyConfiguration) WithType(value v2beta2.MetricTargetType) *MetricTargetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/metrictarget.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *MetricTargetApplyConfiguration) WithType(value v2beta2.MetricTargetType) *MetricTargetApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":41,"to":47}} {"id":100020822,"name":"WithValue","signature":"func (b *MetricTargetApplyConfiguration) WithValue(value resource.Quantity) *MetricTargetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/metrictarget.go","code":"// WithValue sets the Value field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Value field is set to the value of the last call.\nfunc (b *MetricTargetApplyConfiguration) WithValue(value resource.Quantity) *MetricTargetApplyConfiguration {\n\tb.Value = \u0026value\n\treturn b\n}","line":{"from":49,"to":55}} {"id":100020823,"name":"WithAverageValue","signature":"func (b *MetricTargetApplyConfiguration) WithAverageValue(value resource.Quantity) *MetricTargetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/metrictarget.go","code":"// WithAverageValue sets the AverageValue field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AverageValue field is set to the value of the last call.\nfunc (b *MetricTargetApplyConfiguration) WithAverageValue(value resource.Quantity) *MetricTargetApplyConfiguration {\n\tb.AverageValue = \u0026value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100020824,"name":"WithAverageUtilization","signature":"func (b *MetricTargetApplyConfiguration) WithAverageUtilization(value int32) *MetricTargetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/metrictarget.go","code":"// WithAverageUtilization sets the AverageUtilization field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AverageUtilization field is set to the value of the last call.\nfunc (b *MetricTargetApplyConfiguration) WithAverageUtilization(value int32) *MetricTargetApplyConfiguration {\n\tb.AverageUtilization = \u0026value\n\treturn b\n}","line":{"from":65,"to":71}} {"id":100020825,"name":"MetricValueStatus","signature":"func MetricValueStatus() *MetricValueStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/metricvaluestatus.go","code":"// MetricValueStatusApplyConfiguration constructs an declarative configuration of the MetricValueStatus type for use with\n// apply.\nfunc MetricValueStatus() *MetricValueStatusApplyConfiguration {\n\treturn \u0026MetricValueStatusApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100020826,"name":"WithValue","signature":"func (b *MetricValueStatusApplyConfiguration) WithValue(value resource.Quantity) *MetricValueStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/metricvaluestatus.go","code":"// WithValue sets the Value field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Value field is set to the value of the last call.\nfunc (b *MetricValueStatusApplyConfiguration) WithValue(value resource.Quantity) *MetricValueStatusApplyConfiguration {\n\tb.Value = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100020827,"name":"WithAverageValue","signature":"func (b *MetricValueStatusApplyConfiguration) WithAverageValue(value resource.Quantity) *MetricValueStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/metricvaluestatus.go","code":"// WithAverageValue sets the AverageValue field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AverageValue field is set to the value of the last call.\nfunc (b *MetricValueStatusApplyConfiguration) WithAverageValue(value resource.Quantity) *MetricValueStatusApplyConfiguration {\n\tb.AverageValue = \u0026value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100020828,"name":"WithAverageUtilization","signature":"func (b *MetricValueStatusApplyConfiguration) WithAverageUtilization(value int32) *MetricValueStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/metricvaluestatus.go","code":"// WithAverageUtilization sets the AverageUtilization field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AverageUtilization field is set to the value of the last call.\nfunc (b *MetricValueStatusApplyConfiguration) WithAverageUtilization(value int32) *MetricValueStatusApplyConfiguration {\n\tb.AverageUtilization = \u0026value\n\treturn b\n}","line":{"from":55,"to":61}} {"id":100020829,"name":"ObjectMetricSource","signature":"func ObjectMetricSource() *ObjectMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/objectmetricsource.go","code":"// ObjectMetricSourceApplyConfiguration constructs an declarative configuration of the ObjectMetricSource type for use with\n// apply.\nfunc ObjectMetricSource() *ObjectMetricSourceApplyConfiguration {\n\treturn \u0026ObjectMetricSourceApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100020830,"name":"WithDescribedObject","signature":"func (b *ObjectMetricSourceApplyConfiguration) WithDescribedObject(value *CrossVersionObjectReferenceApplyConfiguration) *ObjectMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/objectmetricsource.go","code":"// WithDescribedObject sets the DescribedObject field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DescribedObject field is set to the value of the last call.\nfunc (b *ObjectMetricSourceApplyConfiguration) WithDescribedObject(value *CrossVersionObjectReferenceApplyConfiguration) *ObjectMetricSourceApplyConfiguration {\n\tb.DescribedObject = value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100020831,"name":"WithTarget","signature":"func (b *ObjectMetricSourceApplyConfiguration) WithTarget(value *MetricTargetApplyConfiguration) *ObjectMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/objectmetricsource.go","code":"// WithTarget sets the Target field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Target field is set to the value of the last call.\nfunc (b *ObjectMetricSourceApplyConfiguration) WithTarget(value *MetricTargetApplyConfiguration) *ObjectMetricSourceApplyConfiguration {\n\tb.Target = value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100020832,"name":"WithMetric","signature":"func (b *ObjectMetricSourceApplyConfiguration) WithMetric(value *MetricIdentifierApplyConfiguration) *ObjectMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/objectmetricsource.go","code":"// WithMetric sets the Metric field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Metric field is set to the value of the last call.\nfunc (b *ObjectMetricSourceApplyConfiguration) WithMetric(value *MetricIdentifierApplyConfiguration) *ObjectMetricSourceApplyConfiguration {\n\tb.Metric = value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100020833,"name":"ObjectMetricStatus","signature":"func ObjectMetricStatus() *ObjectMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/objectmetricstatus.go","code":"// ObjectMetricStatusApplyConfiguration constructs an declarative configuration of the ObjectMetricStatus type for use with\n// apply.\nfunc ObjectMetricStatus() *ObjectMetricStatusApplyConfiguration {\n\treturn \u0026ObjectMetricStatusApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100020834,"name":"WithMetric","signature":"func (b *ObjectMetricStatusApplyConfiguration) WithMetric(value *MetricIdentifierApplyConfiguration) *ObjectMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/objectmetricstatus.go","code":"// WithMetric sets the Metric field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Metric field is set to the value of the last call.\nfunc (b *ObjectMetricStatusApplyConfiguration) WithMetric(value *MetricIdentifierApplyConfiguration) *ObjectMetricStatusApplyConfiguration {\n\tb.Metric = value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100020835,"name":"WithCurrent","signature":"func (b *ObjectMetricStatusApplyConfiguration) WithCurrent(value *MetricValueStatusApplyConfiguration) *ObjectMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/objectmetricstatus.go","code":"// WithCurrent sets the Current field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Current field is set to the value of the last call.\nfunc (b *ObjectMetricStatusApplyConfiguration) WithCurrent(value *MetricValueStatusApplyConfiguration) *ObjectMetricStatusApplyConfiguration {\n\tb.Current = value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100020836,"name":"WithDescribedObject","signature":"func (b *ObjectMetricStatusApplyConfiguration) WithDescribedObject(value *CrossVersionObjectReferenceApplyConfiguration) *ObjectMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/objectmetricstatus.go","code":"// WithDescribedObject sets the DescribedObject field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DescribedObject field is set to the value of the last call.\nfunc (b *ObjectMetricStatusApplyConfiguration) WithDescribedObject(value *CrossVersionObjectReferenceApplyConfiguration) *ObjectMetricStatusApplyConfiguration {\n\tb.DescribedObject = value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100020837,"name":"PodsMetricSource","signature":"func PodsMetricSource() *PodsMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/podsmetricsource.go","code":"// PodsMetricSourceApplyConfiguration constructs an declarative configuration of the PodsMetricSource type for use with\n// apply.\nfunc PodsMetricSource() *PodsMetricSourceApplyConfiguration {\n\treturn \u0026PodsMetricSourceApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100020838,"name":"WithMetric","signature":"func (b *PodsMetricSourceApplyConfiguration) WithMetric(value *MetricIdentifierApplyConfiguration) *PodsMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/podsmetricsource.go","code":"// WithMetric sets the Metric field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Metric field is set to the value of the last call.\nfunc (b *PodsMetricSourceApplyConfiguration) WithMetric(value *MetricIdentifierApplyConfiguration) *PodsMetricSourceApplyConfiguration {\n\tb.Metric = value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100020839,"name":"WithTarget","signature":"func (b *PodsMetricSourceApplyConfiguration) WithTarget(value *MetricTargetApplyConfiguration) *PodsMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/podsmetricsource.go","code":"// WithTarget sets the Target field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Target field is set to the value of the last call.\nfunc (b *PodsMetricSourceApplyConfiguration) WithTarget(value *MetricTargetApplyConfiguration) *PodsMetricSourceApplyConfiguration {\n\tb.Target = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020840,"name":"PodsMetricStatus","signature":"func PodsMetricStatus() *PodsMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/podsmetricstatus.go","code":"// PodsMetricStatusApplyConfiguration constructs an declarative configuration of the PodsMetricStatus type for use with\n// apply.\nfunc PodsMetricStatus() *PodsMetricStatusApplyConfiguration {\n\treturn \u0026PodsMetricStatusApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100020841,"name":"WithMetric","signature":"func (b *PodsMetricStatusApplyConfiguration) WithMetric(value *MetricIdentifierApplyConfiguration) *PodsMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/podsmetricstatus.go","code":"// WithMetric sets the Metric field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Metric field is set to the value of the last call.\nfunc (b *PodsMetricStatusApplyConfiguration) WithMetric(value *MetricIdentifierApplyConfiguration) *PodsMetricStatusApplyConfiguration {\n\tb.Metric = value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100020842,"name":"WithCurrent","signature":"func (b *PodsMetricStatusApplyConfiguration) WithCurrent(value *MetricValueStatusApplyConfiguration) *PodsMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/podsmetricstatus.go","code":"// WithCurrent sets the Current field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Current field is set to the value of the last call.\nfunc (b *PodsMetricStatusApplyConfiguration) WithCurrent(value *MetricValueStatusApplyConfiguration) *PodsMetricStatusApplyConfiguration {\n\tb.Current = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100020843,"name":"ResourceMetricSource","signature":"func ResourceMetricSource() *ResourceMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/resourcemetricsource.go","code":"// ResourceMetricSourceApplyConfiguration constructs an declarative configuration of the ResourceMetricSource type for use with\n// apply.\nfunc ResourceMetricSource() *ResourceMetricSourceApplyConfiguration {\n\treturn \u0026ResourceMetricSourceApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100020844,"name":"WithName","signature":"func (b *ResourceMetricSourceApplyConfiguration) WithName(value v1.ResourceName) *ResourceMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/resourcemetricsource.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ResourceMetricSourceApplyConfiguration) WithName(value v1.ResourceName) *ResourceMetricSourceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100020845,"name":"WithTarget","signature":"func (b *ResourceMetricSourceApplyConfiguration) WithTarget(value *MetricTargetApplyConfiguration) *ResourceMetricSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/resourcemetricsource.go","code":"// WithTarget sets the Target field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Target field is set to the value of the last call.\nfunc (b *ResourceMetricSourceApplyConfiguration) WithTarget(value *MetricTargetApplyConfiguration) *ResourceMetricSourceApplyConfiguration {\n\tb.Target = value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100020846,"name":"ResourceMetricStatus","signature":"func ResourceMetricStatus() *ResourceMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/resourcemetricstatus.go","code":"// ResourceMetricStatusApplyConfiguration constructs an declarative configuration of the ResourceMetricStatus type for use with\n// apply.\nfunc ResourceMetricStatus() *ResourceMetricStatusApplyConfiguration {\n\treturn \u0026ResourceMetricStatusApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100020847,"name":"WithName","signature":"func (b *ResourceMetricStatusApplyConfiguration) WithName(value v1.ResourceName) *ResourceMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/resourcemetricstatus.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ResourceMetricStatusApplyConfiguration) WithName(value v1.ResourceName) *ResourceMetricStatusApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100020848,"name":"WithCurrent","signature":"func (b *ResourceMetricStatusApplyConfiguration) WithCurrent(value *MetricValueStatusApplyConfiguration) *ResourceMetricStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/autoscaling/v2beta2/resourcemetricstatus.go","code":"// WithCurrent sets the Current field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Current field is set to the value of the last call.\nfunc (b *ResourceMetricStatusApplyConfiguration) WithCurrent(value *MetricValueStatusApplyConfiguration) *ResourceMetricStatusApplyConfiguration {\n\tb.Current = value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100020849,"name":"CronJob","signature":"func CronJob(name, namespace string) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjob.go","code":"// CronJob constructs an declarative configuration of the CronJob type for use with\n// apply.\nfunc CronJob(name, namespace string) *CronJobApplyConfiguration {\n\tb := \u0026CronJobApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"CronJob\")\n\tb.WithAPIVersion(\"batch/v1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100020850,"name":"ExtractCronJob","signature":"func ExtractCronJob(cronJob *apibatchv1.CronJob, fieldManager string) (*CronJobApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjob.go","code":"// ExtractCronJob extracts the applied configuration owned by fieldManager from\n// cronJob. If no managedFields are found in cronJob for fieldManager, a\n// CronJobApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// cronJob must be a unmodified CronJob API object that was retrieved from the Kubernetes API.\n// ExtractCronJob provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractCronJob(cronJob *apibatchv1.CronJob, fieldManager string) (*CronJobApplyConfiguration, error) {\n\treturn extractCronJob(cronJob, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100020851,"name":"ExtractCronJobStatus","signature":"func ExtractCronJobStatus(cronJob *apibatchv1.CronJob, fieldManager string) (*CronJobApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjob.go","code":"// ExtractCronJobStatus is the same as ExtractCronJob except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractCronJobStatus(cronJob *apibatchv1.CronJob, fieldManager string) (*CronJobApplyConfiguration, error) {\n\treturn extractCronJob(cronJob, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100020852,"name":"extractCronJob","signature":"func extractCronJob(cronJob *apibatchv1.CronJob, fieldManager string, subresource string) (*CronJobApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjob.go","code":"func extractCronJob(cronJob *apibatchv1.CronJob, fieldManager string, subresource string) (*CronJobApplyConfiguration, error) {\n\tb := \u0026CronJobApplyConfiguration{}\n\terr := managedfields.ExtractInto(cronJob, internal.Parser().Type(\"io.k8s.api.batch.v1.CronJob\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(cronJob.Name)\n\tb.WithNamespace(cronJob.Namespace)\n\n\tb.WithKind(\"CronJob\")\n\tb.WithAPIVersion(\"batch/v1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100020853,"name":"WithKind","signature":"func (b *CronJobApplyConfiguration) WithKind(value string) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjob.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *CronJobApplyConfiguration) WithKind(value string) *CronJobApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100020854,"name":"WithAPIVersion","signature":"func (b *CronJobApplyConfiguration) WithAPIVersion(value string) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjob.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *CronJobApplyConfiguration) WithAPIVersion(value string) *CronJobApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100020855,"name":"WithName","signature":"func (b *CronJobApplyConfiguration) WithName(value string) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjob.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *CronJobApplyConfiguration) WithName(value string) *CronJobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100020856,"name":"WithGenerateName","signature":"func (b *CronJobApplyConfiguration) WithGenerateName(value string) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjob.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *CronJobApplyConfiguration) WithGenerateName(value string) *CronJobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100020857,"name":"WithNamespace","signature":"func (b *CronJobApplyConfiguration) WithNamespace(value string) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjob.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *CronJobApplyConfiguration) WithNamespace(value string) *CronJobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100020858,"name":"WithUID","signature":"func (b *CronJobApplyConfiguration) WithUID(value types.UID) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjob.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *CronJobApplyConfiguration) WithUID(value types.UID) *CronJobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100020859,"name":"WithResourceVersion","signature":"func (b *CronJobApplyConfiguration) WithResourceVersion(value string) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjob.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *CronJobApplyConfiguration) WithResourceVersion(value string) *CronJobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100020860,"name":"WithGeneration","signature":"func (b *CronJobApplyConfiguration) WithGeneration(value int64) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjob.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *CronJobApplyConfiguration) WithGeneration(value int64) *CronJobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100020861,"name":"WithCreationTimestamp","signature":"func (b *CronJobApplyConfiguration) WithCreationTimestamp(value metav1.Time) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjob.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *CronJobApplyConfiguration) WithCreationTimestamp(value metav1.Time) *CronJobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100020862,"name":"WithDeletionTimestamp","signature":"func (b *CronJobApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjob.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *CronJobApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *CronJobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100020863,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *CronJobApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjob.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *CronJobApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *CronJobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100020864,"name":"WithLabels","signature":"func (b *CronJobApplyConfiguration) WithLabels(entries map[string]string) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjob.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *CronJobApplyConfiguration) WithLabels(entries map[string]string) *CronJobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100020865,"name":"WithAnnotations","signature":"func (b *CronJobApplyConfiguration) WithAnnotations(entries map[string]string) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjob.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *CronJobApplyConfiguration) WithAnnotations(entries map[string]string) *CronJobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100020866,"name":"WithOwnerReferences","signature":"func (b *CronJobApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjob.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *CronJobApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *CronJobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100020867,"name":"WithFinalizers","signature":"func (b *CronJobApplyConfiguration) WithFinalizers(values ...string) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjob.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *CronJobApplyConfiguration) WithFinalizers(values ...string) *CronJobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100020868,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *CronJobApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjob.go","code":"func (b *CronJobApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100020869,"name":"WithSpec","signature":"func (b *CronJobApplyConfiguration) WithSpec(value *CronJobSpecApplyConfiguration) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjob.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *CronJobApplyConfiguration) WithSpec(value *CronJobSpecApplyConfiguration) *CronJobApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100020870,"name":"WithStatus","signature":"func (b *CronJobApplyConfiguration) WithStatus(value *CronJobStatusApplyConfiguration) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjob.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *CronJobApplyConfiguration) WithStatus(value *CronJobStatusApplyConfiguration) *CronJobApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100020871,"name":"CronJobSpec","signature":"func CronJobSpec() *CronJobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjobspec.go","code":"// CronJobSpecApplyConfiguration constructs an declarative configuration of the CronJobSpec type for use with\n// apply.\nfunc CronJobSpec() *CronJobSpecApplyConfiguration {\n\treturn \u0026CronJobSpecApplyConfiguration{}\n}","line":{"from":38,"to":42}} {"id":100020872,"name":"WithSchedule","signature":"func (b *CronJobSpecApplyConfiguration) WithSchedule(value string) *CronJobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjobspec.go","code":"// WithSchedule sets the Schedule field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Schedule field is set to the value of the last call.\nfunc (b *CronJobSpecApplyConfiguration) WithSchedule(value string) *CronJobSpecApplyConfiguration {\n\tb.Schedule = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100020873,"name":"WithTimeZone","signature":"func (b *CronJobSpecApplyConfiguration) WithTimeZone(value string) *CronJobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjobspec.go","code":"// WithTimeZone sets the TimeZone field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TimeZone field is set to the value of the last call.\nfunc (b *CronJobSpecApplyConfiguration) WithTimeZone(value string) *CronJobSpecApplyConfiguration {\n\tb.TimeZone = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100020874,"name":"WithStartingDeadlineSeconds","signature":"func (b *CronJobSpecApplyConfiguration) WithStartingDeadlineSeconds(value int64) *CronJobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjobspec.go","code":"// WithStartingDeadlineSeconds sets the StartingDeadlineSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StartingDeadlineSeconds field is set to the value of the last call.\nfunc (b *CronJobSpecApplyConfiguration) WithStartingDeadlineSeconds(value int64) *CronJobSpecApplyConfiguration {\n\tb.StartingDeadlineSeconds = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100020875,"name":"WithConcurrencyPolicy","signature":"func (b *CronJobSpecApplyConfiguration) WithConcurrencyPolicy(value v1.ConcurrencyPolicy) *CronJobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjobspec.go","code":"// WithConcurrencyPolicy sets the ConcurrencyPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ConcurrencyPolicy field is set to the value of the last call.\nfunc (b *CronJobSpecApplyConfiguration) WithConcurrencyPolicy(value v1.ConcurrencyPolicy) *CronJobSpecApplyConfiguration {\n\tb.ConcurrencyPolicy = \u0026value\n\treturn b\n}","line":{"from":68,"to":74}} {"id":100020876,"name":"WithSuspend","signature":"func (b *CronJobSpecApplyConfiguration) WithSuspend(value bool) *CronJobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjobspec.go","code":"// WithSuspend sets the Suspend field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Suspend field is set to the value of the last call.\nfunc (b *CronJobSpecApplyConfiguration) WithSuspend(value bool) *CronJobSpecApplyConfiguration {\n\tb.Suspend = \u0026value\n\treturn b\n}","line":{"from":76,"to":82}} {"id":100020877,"name":"WithJobTemplate","signature":"func (b *CronJobSpecApplyConfiguration) WithJobTemplate(value *JobTemplateSpecApplyConfiguration) *CronJobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjobspec.go","code":"// WithJobTemplate sets the JobTemplate field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the JobTemplate field is set to the value of the last call.\nfunc (b *CronJobSpecApplyConfiguration) WithJobTemplate(value *JobTemplateSpecApplyConfiguration) *CronJobSpecApplyConfiguration {\n\tb.JobTemplate = value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100020878,"name":"WithSuccessfulJobsHistoryLimit","signature":"func (b *CronJobSpecApplyConfiguration) WithSuccessfulJobsHistoryLimit(value int32) *CronJobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjobspec.go","code":"// WithSuccessfulJobsHistoryLimit sets the SuccessfulJobsHistoryLimit field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SuccessfulJobsHistoryLimit field is set to the value of the last call.\nfunc (b *CronJobSpecApplyConfiguration) WithSuccessfulJobsHistoryLimit(value int32) *CronJobSpecApplyConfiguration {\n\tb.SuccessfulJobsHistoryLimit = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100020879,"name":"WithFailedJobsHistoryLimit","signature":"func (b *CronJobSpecApplyConfiguration) WithFailedJobsHistoryLimit(value int32) *CronJobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjobspec.go","code":"// WithFailedJobsHistoryLimit sets the FailedJobsHistoryLimit field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FailedJobsHistoryLimit field is set to the value of the last call.\nfunc (b *CronJobSpecApplyConfiguration) WithFailedJobsHistoryLimit(value int32) *CronJobSpecApplyConfiguration {\n\tb.FailedJobsHistoryLimit = \u0026value\n\treturn b\n}","line":{"from":100,"to":106}} {"id":100020880,"name":"CronJobStatus","signature":"func CronJobStatus() *CronJobStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjobstatus.go","code":"// CronJobStatusApplyConfiguration constructs an declarative configuration of the CronJobStatus type for use with\n// apply.\nfunc CronJobStatus() *CronJobStatusApplyConfiguration {\n\treturn \u0026CronJobStatusApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100020881,"name":"WithActive","signature":"func (b *CronJobStatusApplyConfiguration) WithActive(values ...*v1.ObjectReferenceApplyConfiguration) *CronJobStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjobstatus.go","code":"// WithActive adds the given value to the Active field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Active field.\nfunc (b *CronJobStatusApplyConfiguration) WithActive(values ...*v1.ObjectReferenceApplyConfiguration) *CronJobStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithActive\")\n\t\t}\n\t\tb.Active = append(b.Active, *values[i])\n\t}\n\treturn b\n}","line":{"from":40,"to":51}} {"id":100020882,"name":"WithLastScheduleTime","signature":"func (b *CronJobStatusApplyConfiguration) WithLastScheduleTime(value metav1.Time) *CronJobStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjobstatus.go","code":"// WithLastScheduleTime sets the LastScheduleTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastScheduleTime field is set to the value of the last call.\nfunc (b *CronJobStatusApplyConfiguration) WithLastScheduleTime(value metav1.Time) *CronJobStatusApplyConfiguration {\n\tb.LastScheduleTime = \u0026value\n\treturn b\n}","line":{"from":53,"to":59}} {"id":100020883,"name":"WithLastSuccessfulTime","signature":"func (b *CronJobStatusApplyConfiguration) WithLastSuccessfulTime(value metav1.Time) *CronJobStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/cronjobstatus.go","code":"// WithLastSuccessfulTime sets the LastSuccessfulTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastSuccessfulTime field is set to the value of the last call.\nfunc (b *CronJobStatusApplyConfiguration) WithLastSuccessfulTime(value metav1.Time) *CronJobStatusApplyConfiguration {\n\tb.LastSuccessfulTime = \u0026value\n\treturn b\n}","line":{"from":61,"to":67}} {"id":100020884,"name":"Job","signature":"func Job(name, namespace string) *JobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/job.go","code":"// Job constructs an declarative configuration of the Job type for use with\n// apply.\nfunc Job(name, namespace string) *JobApplyConfiguration {\n\tb := \u0026JobApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"Job\")\n\tb.WithAPIVersion(\"batch/v1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100020885,"name":"ExtractJob","signature":"func ExtractJob(job *apibatchv1.Job, fieldManager string) (*JobApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/job.go","code":"// ExtractJob extracts the applied configuration owned by fieldManager from\n// job. If no managedFields are found in job for fieldManager, a\n// JobApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// job must be a unmodified Job API object that was retrieved from the Kubernetes API.\n// ExtractJob provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractJob(job *apibatchv1.Job, fieldManager string) (*JobApplyConfiguration, error) {\n\treturn extractJob(job, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100020886,"name":"ExtractJobStatus","signature":"func ExtractJobStatus(job *apibatchv1.Job, fieldManager string) (*JobApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/job.go","code":"// ExtractJobStatus is the same as ExtractJob except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractJobStatus(job *apibatchv1.Job, fieldManager string) (*JobApplyConfiguration, error) {\n\treturn extractJob(job, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100020887,"name":"extractJob","signature":"func extractJob(job *apibatchv1.Job, fieldManager string, subresource string) (*JobApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/job.go","code":"func extractJob(job *apibatchv1.Job, fieldManager string, subresource string) (*JobApplyConfiguration, error) {\n\tb := \u0026JobApplyConfiguration{}\n\terr := managedfields.ExtractInto(job, internal.Parser().Type(\"io.k8s.api.batch.v1.Job\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(job.Name)\n\tb.WithNamespace(job.Namespace)\n\n\tb.WithKind(\"Job\")\n\tb.WithAPIVersion(\"batch/v1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100020888,"name":"WithKind","signature":"func (b *JobApplyConfiguration) WithKind(value string) *JobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/job.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *JobApplyConfiguration) WithKind(value string) *JobApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100020889,"name":"WithAPIVersion","signature":"func (b *JobApplyConfiguration) WithAPIVersion(value string) *JobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/job.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *JobApplyConfiguration) WithAPIVersion(value string) *JobApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100020890,"name":"WithName","signature":"func (b *JobApplyConfiguration) WithName(value string) *JobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/job.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *JobApplyConfiguration) WithName(value string) *JobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100020891,"name":"WithGenerateName","signature":"func (b *JobApplyConfiguration) WithGenerateName(value string) *JobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/job.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *JobApplyConfiguration) WithGenerateName(value string) *JobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100020892,"name":"WithNamespace","signature":"func (b *JobApplyConfiguration) WithNamespace(value string) *JobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/job.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *JobApplyConfiguration) WithNamespace(value string) *JobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100020893,"name":"WithUID","signature":"func (b *JobApplyConfiguration) WithUID(value types.UID) *JobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/job.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *JobApplyConfiguration) WithUID(value types.UID) *JobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100020894,"name":"WithResourceVersion","signature":"func (b *JobApplyConfiguration) WithResourceVersion(value string) *JobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/job.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *JobApplyConfiguration) WithResourceVersion(value string) *JobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100020895,"name":"WithGeneration","signature":"func (b *JobApplyConfiguration) WithGeneration(value int64) *JobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/job.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *JobApplyConfiguration) WithGeneration(value int64) *JobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100020896,"name":"WithCreationTimestamp","signature":"func (b *JobApplyConfiguration) WithCreationTimestamp(value metav1.Time) *JobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/job.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *JobApplyConfiguration) WithCreationTimestamp(value metav1.Time) *JobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100020897,"name":"WithDeletionTimestamp","signature":"func (b *JobApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *JobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/job.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *JobApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *JobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100020898,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *JobApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *JobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/job.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *JobApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *JobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100020899,"name":"WithLabels","signature":"func (b *JobApplyConfiguration) WithLabels(entries map[string]string) *JobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/job.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *JobApplyConfiguration) WithLabels(entries map[string]string) *JobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100020900,"name":"WithAnnotations","signature":"func (b *JobApplyConfiguration) WithAnnotations(entries map[string]string) *JobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/job.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *JobApplyConfiguration) WithAnnotations(entries map[string]string) *JobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100020901,"name":"WithOwnerReferences","signature":"func (b *JobApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *JobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/job.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *JobApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *JobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100020902,"name":"WithFinalizers","signature":"func (b *JobApplyConfiguration) WithFinalizers(values ...string) *JobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/job.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *JobApplyConfiguration) WithFinalizers(values ...string) *JobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100020903,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *JobApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/job.go","code":"func (b *JobApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100020904,"name":"WithSpec","signature":"func (b *JobApplyConfiguration) WithSpec(value *JobSpecApplyConfiguration) *JobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/job.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *JobApplyConfiguration) WithSpec(value *JobSpecApplyConfiguration) *JobApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100020905,"name":"WithStatus","signature":"func (b *JobApplyConfiguration) WithStatus(value *JobStatusApplyConfiguration) *JobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/job.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *JobApplyConfiguration) WithStatus(value *JobStatusApplyConfiguration) *JobApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100020906,"name":"JobCondition","signature":"func JobCondition() *JobConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobcondition.go","code":"// JobConditionApplyConfiguration constructs an declarative configuration of the JobCondition type for use with\n// apply.\nfunc JobCondition() *JobConditionApplyConfiguration {\n\treturn \u0026JobConditionApplyConfiguration{}\n}","line":{"from":38,"to":42}} {"id":100020907,"name":"WithType","signature":"func (b *JobConditionApplyConfiguration) WithType(value v1.JobConditionType) *JobConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobcondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *JobConditionApplyConfiguration) WithType(value v1.JobConditionType) *JobConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100020908,"name":"WithStatus","signature":"func (b *JobConditionApplyConfiguration) WithStatus(value corev1.ConditionStatus) *JobConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobcondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *JobConditionApplyConfiguration) WithStatus(value corev1.ConditionStatus) *JobConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100020909,"name":"WithLastProbeTime","signature":"func (b *JobConditionApplyConfiguration) WithLastProbeTime(value metav1.Time) *JobConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobcondition.go","code":"// WithLastProbeTime sets the LastProbeTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastProbeTime field is set to the value of the last call.\nfunc (b *JobConditionApplyConfiguration) WithLastProbeTime(value metav1.Time) *JobConditionApplyConfiguration {\n\tb.LastProbeTime = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100020910,"name":"WithLastTransitionTime","signature":"func (b *JobConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *JobConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobcondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *JobConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *JobConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":68,"to":74}} {"id":100020911,"name":"WithReason","signature":"func (b *JobConditionApplyConfiguration) WithReason(value string) *JobConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobcondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *JobConditionApplyConfiguration) WithReason(value string) *JobConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":76,"to":82}} {"id":100020912,"name":"WithMessage","signature":"func (b *JobConditionApplyConfiguration) WithMessage(value string) *JobConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobcondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *JobConditionApplyConfiguration) WithMessage(value string) *JobConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100020913,"name":"JobSpec","signature":"func JobSpec() *JobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobspec.go","code":"// JobSpecApplyConfiguration constructs an declarative configuration of the JobSpec type for use with\n// apply.\nfunc JobSpec() *JobSpecApplyConfiguration {\n\treturn \u0026JobSpecApplyConfiguration{}\n}","line":{"from":43,"to":47}} {"id":100020914,"name":"WithParallelism","signature":"func (b *JobSpecApplyConfiguration) WithParallelism(value int32) *JobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobspec.go","code":"// WithParallelism sets the Parallelism field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Parallelism field is set to the value of the last call.\nfunc (b *JobSpecApplyConfiguration) WithParallelism(value int32) *JobSpecApplyConfiguration {\n\tb.Parallelism = \u0026value\n\treturn b\n}","line":{"from":49,"to":55}} {"id":100020915,"name":"WithCompletions","signature":"func (b *JobSpecApplyConfiguration) WithCompletions(value int32) *JobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobspec.go","code":"// WithCompletions sets the Completions field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Completions field is set to the value of the last call.\nfunc (b *JobSpecApplyConfiguration) WithCompletions(value int32) *JobSpecApplyConfiguration {\n\tb.Completions = \u0026value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100020916,"name":"WithActiveDeadlineSeconds","signature":"func (b *JobSpecApplyConfiguration) WithActiveDeadlineSeconds(value int64) *JobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobspec.go","code":"// WithActiveDeadlineSeconds sets the ActiveDeadlineSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ActiveDeadlineSeconds field is set to the value of the last call.\nfunc (b *JobSpecApplyConfiguration) WithActiveDeadlineSeconds(value int64) *JobSpecApplyConfiguration {\n\tb.ActiveDeadlineSeconds = \u0026value\n\treturn b\n}","line":{"from":65,"to":71}} {"id":100020917,"name":"WithPodFailurePolicy","signature":"func (b *JobSpecApplyConfiguration) WithPodFailurePolicy(value *PodFailurePolicyApplyConfiguration) *JobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobspec.go","code":"// WithPodFailurePolicy sets the PodFailurePolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PodFailurePolicy field is set to the value of the last call.\nfunc (b *JobSpecApplyConfiguration) WithPodFailurePolicy(value *PodFailurePolicyApplyConfiguration) *JobSpecApplyConfiguration {\n\tb.PodFailurePolicy = value\n\treturn b\n}","line":{"from":73,"to":79}} {"id":100020918,"name":"WithBackoffLimit","signature":"func (b *JobSpecApplyConfiguration) WithBackoffLimit(value int32) *JobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobspec.go","code":"// WithBackoffLimit sets the BackoffLimit field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the BackoffLimit field is set to the value of the last call.\nfunc (b *JobSpecApplyConfiguration) WithBackoffLimit(value int32) *JobSpecApplyConfiguration {\n\tb.BackoffLimit = \u0026value\n\treturn b\n}","line":{"from":81,"to":87}} {"id":100020919,"name":"WithSelector","signature":"func (b *JobSpecApplyConfiguration) WithSelector(value *metav1.LabelSelectorApplyConfiguration) *JobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobspec.go","code":"// WithSelector sets the Selector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Selector field is set to the value of the last call.\nfunc (b *JobSpecApplyConfiguration) WithSelector(value *metav1.LabelSelectorApplyConfiguration) *JobSpecApplyConfiguration {\n\tb.Selector = value\n\treturn b\n}","line":{"from":89,"to":95}} {"id":100020920,"name":"WithManualSelector","signature":"func (b *JobSpecApplyConfiguration) WithManualSelector(value bool) *JobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobspec.go","code":"// WithManualSelector sets the ManualSelector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ManualSelector field is set to the value of the last call.\nfunc (b *JobSpecApplyConfiguration) WithManualSelector(value bool) *JobSpecApplyConfiguration {\n\tb.ManualSelector = \u0026value\n\treturn b\n}","line":{"from":97,"to":103}} {"id":100020921,"name":"WithTemplate","signature":"func (b *JobSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *JobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobspec.go","code":"// WithTemplate sets the Template field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Template field is set to the value of the last call.\nfunc (b *JobSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *JobSpecApplyConfiguration {\n\tb.Template = value\n\treturn b\n}","line":{"from":105,"to":111}} {"id":100020922,"name":"WithTTLSecondsAfterFinished","signature":"func (b *JobSpecApplyConfiguration) WithTTLSecondsAfterFinished(value int32) *JobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobspec.go","code":"// WithTTLSecondsAfterFinished sets the TTLSecondsAfterFinished field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TTLSecondsAfterFinished field is set to the value of the last call.\nfunc (b *JobSpecApplyConfiguration) WithTTLSecondsAfterFinished(value int32) *JobSpecApplyConfiguration {\n\tb.TTLSecondsAfterFinished = \u0026value\n\treturn b\n}","line":{"from":113,"to":119}} {"id":100020923,"name":"WithCompletionMode","signature":"func (b *JobSpecApplyConfiguration) WithCompletionMode(value batchv1.CompletionMode) *JobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobspec.go","code":"// WithCompletionMode sets the CompletionMode field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CompletionMode field is set to the value of the last call.\nfunc (b *JobSpecApplyConfiguration) WithCompletionMode(value batchv1.CompletionMode) *JobSpecApplyConfiguration {\n\tb.CompletionMode = \u0026value\n\treturn b\n}","line":{"from":121,"to":127}} {"id":100020924,"name":"WithSuspend","signature":"func (b *JobSpecApplyConfiguration) WithSuspend(value bool) *JobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobspec.go","code":"// WithSuspend sets the Suspend field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Suspend field is set to the value of the last call.\nfunc (b *JobSpecApplyConfiguration) WithSuspend(value bool) *JobSpecApplyConfiguration {\n\tb.Suspend = \u0026value\n\treturn b\n}","line":{"from":129,"to":135}} {"id":100020925,"name":"JobStatus","signature":"func JobStatus() *JobStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobstatus.go","code":"// JobStatusApplyConfiguration constructs an declarative configuration of the JobStatus type for use with\n// apply.\nfunc JobStatus() *JobStatusApplyConfiguration {\n\treturn \u0026JobStatusApplyConfiguration{}\n}","line":{"from":39,"to":43}} {"id":100020926,"name":"WithConditions","signature":"func (b *JobStatusApplyConfiguration) WithConditions(values ...*JobConditionApplyConfiguration) *JobStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *JobStatusApplyConfiguration) WithConditions(values ...*JobConditionApplyConfiguration) *JobStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":45,"to":56}} {"id":100020927,"name":"WithStartTime","signature":"func (b *JobStatusApplyConfiguration) WithStartTime(value metav1.Time) *JobStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobstatus.go","code":"// WithStartTime sets the StartTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StartTime field is set to the value of the last call.\nfunc (b *JobStatusApplyConfiguration) WithStartTime(value metav1.Time) *JobStatusApplyConfiguration {\n\tb.StartTime = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100020928,"name":"WithCompletionTime","signature":"func (b *JobStatusApplyConfiguration) WithCompletionTime(value metav1.Time) *JobStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobstatus.go","code":"// WithCompletionTime sets the CompletionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CompletionTime field is set to the value of the last call.\nfunc (b *JobStatusApplyConfiguration) WithCompletionTime(value metav1.Time) *JobStatusApplyConfiguration {\n\tb.CompletionTime = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100020929,"name":"WithActive","signature":"func (b *JobStatusApplyConfiguration) WithActive(value int32) *JobStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobstatus.go","code":"// WithActive sets the Active field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Active field is set to the value of the last call.\nfunc (b *JobStatusApplyConfiguration) WithActive(value int32) *JobStatusApplyConfiguration {\n\tb.Active = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100020930,"name":"WithSucceeded","signature":"func (b *JobStatusApplyConfiguration) WithSucceeded(value int32) *JobStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobstatus.go","code":"// WithSucceeded sets the Succeeded field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Succeeded field is set to the value of the last call.\nfunc (b *JobStatusApplyConfiguration) WithSucceeded(value int32) *JobStatusApplyConfiguration {\n\tb.Succeeded = \u0026value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100020931,"name":"WithFailed","signature":"func (b *JobStatusApplyConfiguration) WithFailed(value int32) *JobStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobstatus.go","code":"// WithFailed sets the Failed field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Failed field is set to the value of the last call.\nfunc (b *JobStatusApplyConfiguration) WithFailed(value int32) *JobStatusApplyConfiguration {\n\tb.Failed = \u0026value\n\treturn b\n}","line":{"from":90,"to":96}} {"id":100020932,"name":"WithCompletedIndexes","signature":"func (b *JobStatusApplyConfiguration) WithCompletedIndexes(value string) *JobStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobstatus.go","code":"// WithCompletedIndexes sets the CompletedIndexes field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CompletedIndexes field is set to the value of the last call.\nfunc (b *JobStatusApplyConfiguration) WithCompletedIndexes(value string) *JobStatusApplyConfiguration {\n\tb.CompletedIndexes = \u0026value\n\treturn b\n}","line":{"from":98,"to":104}} {"id":100020933,"name":"WithUncountedTerminatedPods","signature":"func (b *JobStatusApplyConfiguration) WithUncountedTerminatedPods(value *UncountedTerminatedPodsApplyConfiguration) *JobStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobstatus.go","code":"// WithUncountedTerminatedPods sets the UncountedTerminatedPods field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UncountedTerminatedPods field is set to the value of the last call.\nfunc (b *JobStatusApplyConfiguration) WithUncountedTerminatedPods(value *UncountedTerminatedPodsApplyConfiguration) *JobStatusApplyConfiguration {\n\tb.UncountedTerminatedPods = value\n\treturn b\n}","line":{"from":106,"to":112}} {"id":100020934,"name":"WithReady","signature":"func (b *JobStatusApplyConfiguration) WithReady(value int32) *JobStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobstatus.go","code":"// WithReady sets the Ready field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Ready field is set to the value of the last call.\nfunc (b *JobStatusApplyConfiguration) WithReady(value int32) *JobStatusApplyConfiguration {\n\tb.Ready = \u0026value\n\treturn b\n}","line":{"from":114,"to":120}} {"id":100020935,"name":"JobTemplateSpec","signature":"func JobTemplateSpec() *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobtemplatespec.go","code":"// JobTemplateSpecApplyConfiguration constructs an declarative configuration of the JobTemplateSpec type for use with\n// apply.\nfunc JobTemplateSpec() *JobTemplateSpecApplyConfiguration {\n\treturn \u0026JobTemplateSpecApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100020936,"name":"WithName","signature":"func (b *JobTemplateSpecApplyConfiguration) WithName(value string) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobtemplatespec.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *JobTemplateSpecApplyConfiguration) WithName(value string) *JobTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":40,"to":47}} {"id":100020937,"name":"WithGenerateName","signature":"func (b *JobTemplateSpecApplyConfiguration) WithGenerateName(value string) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobtemplatespec.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *JobTemplateSpecApplyConfiguration) WithGenerateName(value string) *JobTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":49,"to":56}} {"id":100020938,"name":"WithNamespace","signature":"func (b *JobTemplateSpecApplyConfiguration) WithNamespace(value string) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobtemplatespec.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *JobTemplateSpecApplyConfiguration) WithNamespace(value string) *JobTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":58,"to":65}} {"id":100020939,"name":"WithUID","signature":"func (b *JobTemplateSpecApplyConfiguration) WithUID(value types.UID) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobtemplatespec.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *JobTemplateSpecApplyConfiguration) WithUID(value types.UID) *JobTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":67,"to":74}} {"id":100020940,"name":"WithResourceVersion","signature":"func (b *JobTemplateSpecApplyConfiguration) WithResourceVersion(value string) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobtemplatespec.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *JobTemplateSpecApplyConfiguration) WithResourceVersion(value string) *JobTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":76,"to":83}} {"id":100020941,"name":"WithGeneration","signature":"func (b *JobTemplateSpecApplyConfiguration) WithGeneration(value int64) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobtemplatespec.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *JobTemplateSpecApplyConfiguration) WithGeneration(value int64) *JobTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":85,"to":92}} {"id":100020942,"name":"WithCreationTimestamp","signature":"func (b *JobTemplateSpecApplyConfiguration) WithCreationTimestamp(value metav1.Time) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobtemplatespec.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *JobTemplateSpecApplyConfiguration) WithCreationTimestamp(value metav1.Time) *JobTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":94,"to":101}} {"id":100020943,"name":"WithDeletionTimestamp","signature":"func (b *JobTemplateSpecApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobtemplatespec.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *JobTemplateSpecApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *JobTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":103,"to":110}} {"id":100020944,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *JobTemplateSpecApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobtemplatespec.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *JobTemplateSpecApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *JobTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":112,"to":119}} {"id":100020945,"name":"WithLabels","signature":"func (b *JobTemplateSpecApplyConfiguration) WithLabels(entries map[string]string) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobtemplatespec.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *JobTemplateSpecApplyConfiguration) WithLabels(entries map[string]string) *JobTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":121,"to":134}} {"id":100020946,"name":"WithAnnotations","signature":"func (b *JobTemplateSpecApplyConfiguration) WithAnnotations(entries map[string]string) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobtemplatespec.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *JobTemplateSpecApplyConfiguration) WithAnnotations(entries map[string]string) *JobTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":136,"to":149}} {"id":100020947,"name":"WithOwnerReferences","signature":"func (b *JobTemplateSpecApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobtemplatespec.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *JobTemplateSpecApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *JobTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":151,"to":163}} {"id":100020948,"name":"WithFinalizers","signature":"func (b *JobTemplateSpecApplyConfiguration) WithFinalizers(values ...string) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobtemplatespec.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *JobTemplateSpecApplyConfiguration) WithFinalizers(values ...string) *JobTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":165,"to":174}} {"id":100020949,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *JobTemplateSpecApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobtemplatespec.go","code":"func (b *JobTemplateSpecApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":176,"to":180}} {"id":100020950,"name":"WithSpec","signature":"func (b *JobTemplateSpecApplyConfiguration) WithSpec(value *JobSpecApplyConfiguration) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/jobtemplatespec.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *JobTemplateSpecApplyConfiguration) WithSpec(value *JobSpecApplyConfiguration) *JobTemplateSpecApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":182,"to":188}} {"id":100020951,"name":"PodFailurePolicy","signature":"func PodFailurePolicy() *PodFailurePolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/podfailurepolicy.go","code":"// PodFailurePolicyApplyConfiguration constructs an declarative configuration of the PodFailurePolicy type for use with\n// apply.\nfunc PodFailurePolicy() *PodFailurePolicyApplyConfiguration {\n\treturn \u0026PodFailurePolicyApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100020952,"name":"WithRules","signature":"func (b *PodFailurePolicyApplyConfiguration) WithRules(values ...*PodFailurePolicyRuleApplyConfiguration) *PodFailurePolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/podfailurepolicy.go","code":"// WithRules adds the given value to the Rules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Rules field.\nfunc (b *PodFailurePolicyApplyConfiguration) WithRules(values ...*PodFailurePolicyRuleApplyConfiguration) *PodFailurePolicyApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRules\")\n\t\t}\n\t\tb.Rules = append(b.Rules, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100020953,"name":"PodFailurePolicyOnExitCodesRequirement","signature":"func PodFailurePolicyOnExitCodesRequirement() *PodFailurePolicyOnExitCodesRequirementApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/podfailurepolicyonexitcodesrequirement.go","code":"// PodFailurePolicyOnExitCodesRequirementApplyConfiguration constructs an declarative configuration of the PodFailurePolicyOnExitCodesRequirement type for use with\n// apply.\nfunc PodFailurePolicyOnExitCodesRequirement() *PodFailurePolicyOnExitCodesRequirementApplyConfiguration {\n\treturn \u0026PodFailurePolicyOnExitCodesRequirementApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100020954,"name":"WithContainerName","signature":"func (b *PodFailurePolicyOnExitCodesRequirementApplyConfiguration) WithContainerName(value string) *PodFailurePolicyOnExitCodesRequirementApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/podfailurepolicyonexitcodesrequirement.go","code":"// WithContainerName sets the ContainerName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ContainerName field is set to the value of the last call.\nfunc (b *PodFailurePolicyOnExitCodesRequirementApplyConfiguration) WithContainerName(value string) *PodFailurePolicyOnExitCodesRequirementApplyConfiguration {\n\tb.ContainerName = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100020955,"name":"WithOperator","signature":"func (b *PodFailurePolicyOnExitCodesRequirementApplyConfiguration) WithOperator(value v1.PodFailurePolicyOnExitCodesOperator) *PodFailurePolicyOnExitCodesRequirementApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/podfailurepolicyonexitcodesrequirement.go","code":"// WithOperator sets the Operator field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Operator field is set to the value of the last call.\nfunc (b *PodFailurePolicyOnExitCodesRequirementApplyConfiguration) WithOperator(value v1.PodFailurePolicyOnExitCodesOperator) *PodFailurePolicyOnExitCodesRequirementApplyConfiguration {\n\tb.Operator = \u0026value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100020956,"name":"WithValues","signature":"func (b *PodFailurePolicyOnExitCodesRequirementApplyConfiguration) WithValues(values ...int32) *PodFailurePolicyOnExitCodesRequirementApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/podfailurepolicyonexitcodesrequirement.go","code":"// WithValues adds the given value to the Values field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Values field.\nfunc (b *PodFailurePolicyOnExitCodesRequirementApplyConfiguration) WithValues(values ...int32) *PodFailurePolicyOnExitCodesRequirementApplyConfiguration {\n\tfor i := range values {\n\t\tb.Values = append(b.Values, values[i])\n\t}\n\treturn b\n}","line":{"from":55,"to":63}} {"id":100020957,"name":"PodFailurePolicyOnPodConditionsPattern","signature":"func PodFailurePolicyOnPodConditionsPattern() *PodFailurePolicyOnPodConditionsPatternApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/podfailurepolicyonpodconditionspattern.go","code":"// PodFailurePolicyOnPodConditionsPatternApplyConfiguration constructs an declarative configuration of the PodFailurePolicyOnPodConditionsPattern type for use with\n// apply.\nfunc PodFailurePolicyOnPodConditionsPattern() *PodFailurePolicyOnPodConditionsPatternApplyConfiguration {\n\treturn \u0026PodFailurePolicyOnPodConditionsPatternApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100020958,"name":"WithType","signature":"func (b *PodFailurePolicyOnPodConditionsPatternApplyConfiguration) WithType(value v1.PodConditionType) *PodFailurePolicyOnPodConditionsPatternApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/podfailurepolicyonpodconditionspattern.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *PodFailurePolicyOnPodConditionsPatternApplyConfiguration) WithType(value v1.PodConditionType) *PodFailurePolicyOnPodConditionsPatternApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100020959,"name":"WithStatus","signature":"func (b *PodFailurePolicyOnPodConditionsPatternApplyConfiguration) WithStatus(value v1.ConditionStatus) *PodFailurePolicyOnPodConditionsPatternApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/podfailurepolicyonpodconditionspattern.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *PodFailurePolicyOnPodConditionsPatternApplyConfiguration) WithStatus(value v1.ConditionStatus) *PodFailurePolicyOnPodConditionsPatternApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100020960,"name":"PodFailurePolicyRule","signature":"func PodFailurePolicyRule() *PodFailurePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/podfailurepolicyrule.go","code":"// PodFailurePolicyRuleApplyConfiguration constructs an declarative configuration of the PodFailurePolicyRule type for use with\n// apply.\nfunc PodFailurePolicyRule() *PodFailurePolicyRuleApplyConfiguration {\n\treturn \u0026PodFailurePolicyRuleApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100020961,"name":"WithAction","signature":"func (b *PodFailurePolicyRuleApplyConfiguration) WithAction(value v1.PodFailurePolicyAction) *PodFailurePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/podfailurepolicyrule.go","code":"// WithAction sets the Action field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Action field is set to the value of the last call.\nfunc (b *PodFailurePolicyRuleApplyConfiguration) WithAction(value v1.PodFailurePolicyAction) *PodFailurePolicyRuleApplyConfiguration {\n\tb.Action = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100020962,"name":"WithOnExitCodes","signature":"func (b *PodFailurePolicyRuleApplyConfiguration) WithOnExitCodes(value *PodFailurePolicyOnExitCodesRequirementApplyConfiguration) *PodFailurePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/podfailurepolicyrule.go","code":"// WithOnExitCodes sets the OnExitCodes field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the OnExitCodes field is set to the value of the last call.\nfunc (b *PodFailurePolicyRuleApplyConfiguration) WithOnExitCodes(value *PodFailurePolicyOnExitCodesRequirementApplyConfiguration) *PodFailurePolicyRuleApplyConfiguration {\n\tb.OnExitCodes = value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100020963,"name":"WithOnPodConditions","signature":"func (b *PodFailurePolicyRuleApplyConfiguration) WithOnPodConditions(values ...*PodFailurePolicyOnPodConditionsPatternApplyConfiguration) *PodFailurePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/podfailurepolicyrule.go","code":"// WithOnPodConditions adds the given value to the OnPodConditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OnPodConditions field.\nfunc (b *PodFailurePolicyRuleApplyConfiguration) WithOnPodConditions(values ...*PodFailurePolicyOnPodConditionsPatternApplyConfiguration) *PodFailurePolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOnPodConditions\")\n\t\t}\n\t\tb.OnPodConditions = append(b.OnPodConditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":55,"to":66}} {"id":100020964,"name":"UncountedTerminatedPods","signature":"func UncountedTerminatedPods() *UncountedTerminatedPodsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/uncountedterminatedpods.go","code":"// UncountedTerminatedPodsApplyConfiguration constructs an declarative configuration of the UncountedTerminatedPods type for use with\n// apply.\nfunc UncountedTerminatedPods() *UncountedTerminatedPodsApplyConfiguration {\n\treturn \u0026UncountedTerminatedPodsApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100020965,"name":"WithSucceeded","signature":"func (b *UncountedTerminatedPodsApplyConfiguration) WithSucceeded(values ...types.UID) *UncountedTerminatedPodsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/uncountedterminatedpods.go","code":"// WithSucceeded adds the given value to the Succeeded field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Succeeded field.\nfunc (b *UncountedTerminatedPodsApplyConfiguration) WithSucceeded(values ...types.UID) *UncountedTerminatedPodsApplyConfiguration {\n\tfor i := range values {\n\t\tb.Succeeded = append(b.Succeeded, values[i])\n\t}\n\treturn b\n}","line":{"from":38,"to":46}} {"id":100020966,"name":"WithFailed","signature":"func (b *UncountedTerminatedPodsApplyConfiguration) WithFailed(values ...types.UID) *UncountedTerminatedPodsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1/uncountedterminatedpods.go","code":"// WithFailed adds the given value to the Failed field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Failed field.\nfunc (b *UncountedTerminatedPodsApplyConfiguration) WithFailed(values ...types.UID) *UncountedTerminatedPodsApplyConfiguration {\n\tfor i := range values {\n\t\tb.Failed = append(b.Failed, values[i])\n\t}\n\treturn b\n}","line":{"from":48,"to":56}} {"id":100020967,"name":"CronJob","signature":"func CronJob(name, namespace string) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjob.go","code":"// CronJob constructs an declarative configuration of the CronJob type for use with\n// apply.\nfunc CronJob(name, namespace string) *CronJobApplyConfiguration {\n\tb := \u0026CronJobApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"CronJob\")\n\tb.WithAPIVersion(\"batch/v1beta1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100020968,"name":"ExtractCronJob","signature":"func ExtractCronJob(cronJob *batchv1beta1.CronJob, fieldManager string) (*CronJobApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjob.go","code":"// ExtractCronJob extracts the applied configuration owned by fieldManager from\n// cronJob. If no managedFields are found in cronJob for fieldManager, a\n// CronJobApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// cronJob must be a unmodified CronJob API object that was retrieved from the Kubernetes API.\n// ExtractCronJob provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractCronJob(cronJob *batchv1beta1.CronJob, fieldManager string) (*CronJobApplyConfiguration, error) {\n\treturn extractCronJob(cronJob, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100020969,"name":"ExtractCronJobStatus","signature":"func ExtractCronJobStatus(cronJob *batchv1beta1.CronJob, fieldManager string) (*CronJobApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjob.go","code":"// ExtractCronJobStatus is the same as ExtractCronJob except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractCronJobStatus(cronJob *batchv1beta1.CronJob, fieldManager string) (*CronJobApplyConfiguration, error) {\n\treturn extractCronJob(cronJob, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100020970,"name":"extractCronJob","signature":"func extractCronJob(cronJob *batchv1beta1.CronJob, fieldManager string, subresource string) (*CronJobApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjob.go","code":"func extractCronJob(cronJob *batchv1beta1.CronJob, fieldManager string, subresource string) (*CronJobApplyConfiguration, error) {\n\tb := \u0026CronJobApplyConfiguration{}\n\terr := managedfields.ExtractInto(cronJob, internal.Parser().Type(\"io.k8s.api.batch.v1beta1.CronJob\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(cronJob.Name)\n\tb.WithNamespace(cronJob.Namespace)\n\n\tb.WithKind(\"CronJob\")\n\tb.WithAPIVersion(\"batch/v1beta1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100020971,"name":"WithKind","signature":"func (b *CronJobApplyConfiguration) WithKind(value string) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjob.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *CronJobApplyConfiguration) WithKind(value string) *CronJobApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100020972,"name":"WithAPIVersion","signature":"func (b *CronJobApplyConfiguration) WithAPIVersion(value string) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjob.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *CronJobApplyConfiguration) WithAPIVersion(value string) *CronJobApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100020973,"name":"WithName","signature":"func (b *CronJobApplyConfiguration) WithName(value string) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjob.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *CronJobApplyConfiguration) WithName(value string) *CronJobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100020974,"name":"WithGenerateName","signature":"func (b *CronJobApplyConfiguration) WithGenerateName(value string) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjob.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *CronJobApplyConfiguration) WithGenerateName(value string) *CronJobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100020975,"name":"WithNamespace","signature":"func (b *CronJobApplyConfiguration) WithNamespace(value string) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjob.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *CronJobApplyConfiguration) WithNamespace(value string) *CronJobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100020976,"name":"WithUID","signature":"func (b *CronJobApplyConfiguration) WithUID(value types.UID) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjob.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *CronJobApplyConfiguration) WithUID(value types.UID) *CronJobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100020977,"name":"WithResourceVersion","signature":"func (b *CronJobApplyConfiguration) WithResourceVersion(value string) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjob.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *CronJobApplyConfiguration) WithResourceVersion(value string) *CronJobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100020978,"name":"WithGeneration","signature":"func (b *CronJobApplyConfiguration) WithGeneration(value int64) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjob.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *CronJobApplyConfiguration) WithGeneration(value int64) *CronJobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100020979,"name":"WithCreationTimestamp","signature":"func (b *CronJobApplyConfiguration) WithCreationTimestamp(value metav1.Time) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjob.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *CronJobApplyConfiguration) WithCreationTimestamp(value metav1.Time) *CronJobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100020980,"name":"WithDeletionTimestamp","signature":"func (b *CronJobApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjob.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *CronJobApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *CronJobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100020981,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *CronJobApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjob.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *CronJobApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *CronJobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100020982,"name":"WithLabels","signature":"func (b *CronJobApplyConfiguration) WithLabels(entries map[string]string) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjob.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *CronJobApplyConfiguration) WithLabels(entries map[string]string) *CronJobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100020983,"name":"WithAnnotations","signature":"func (b *CronJobApplyConfiguration) WithAnnotations(entries map[string]string) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjob.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *CronJobApplyConfiguration) WithAnnotations(entries map[string]string) *CronJobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100020984,"name":"WithOwnerReferences","signature":"func (b *CronJobApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjob.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *CronJobApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *CronJobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100020985,"name":"WithFinalizers","signature":"func (b *CronJobApplyConfiguration) WithFinalizers(values ...string) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjob.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *CronJobApplyConfiguration) WithFinalizers(values ...string) *CronJobApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100020986,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *CronJobApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjob.go","code":"func (b *CronJobApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100020987,"name":"WithSpec","signature":"func (b *CronJobApplyConfiguration) WithSpec(value *CronJobSpecApplyConfiguration) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjob.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *CronJobApplyConfiguration) WithSpec(value *CronJobSpecApplyConfiguration) *CronJobApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100020988,"name":"WithStatus","signature":"func (b *CronJobApplyConfiguration) WithStatus(value *CronJobStatusApplyConfiguration) *CronJobApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjob.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *CronJobApplyConfiguration) WithStatus(value *CronJobStatusApplyConfiguration) *CronJobApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100020989,"name":"CronJobSpec","signature":"func CronJobSpec() *CronJobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjobspec.go","code":"// CronJobSpecApplyConfiguration constructs an declarative configuration of the CronJobSpec type for use with\n// apply.\nfunc CronJobSpec() *CronJobSpecApplyConfiguration {\n\treturn \u0026CronJobSpecApplyConfiguration{}\n}","line":{"from":38,"to":42}} {"id":100020990,"name":"WithSchedule","signature":"func (b *CronJobSpecApplyConfiguration) WithSchedule(value string) *CronJobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjobspec.go","code":"// WithSchedule sets the Schedule field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Schedule field is set to the value of the last call.\nfunc (b *CronJobSpecApplyConfiguration) WithSchedule(value string) *CronJobSpecApplyConfiguration {\n\tb.Schedule = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100020991,"name":"WithTimeZone","signature":"func (b *CronJobSpecApplyConfiguration) WithTimeZone(value string) *CronJobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjobspec.go","code":"// WithTimeZone sets the TimeZone field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TimeZone field is set to the value of the last call.\nfunc (b *CronJobSpecApplyConfiguration) WithTimeZone(value string) *CronJobSpecApplyConfiguration {\n\tb.TimeZone = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100020992,"name":"WithStartingDeadlineSeconds","signature":"func (b *CronJobSpecApplyConfiguration) WithStartingDeadlineSeconds(value int64) *CronJobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjobspec.go","code":"// WithStartingDeadlineSeconds sets the StartingDeadlineSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StartingDeadlineSeconds field is set to the value of the last call.\nfunc (b *CronJobSpecApplyConfiguration) WithStartingDeadlineSeconds(value int64) *CronJobSpecApplyConfiguration {\n\tb.StartingDeadlineSeconds = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100020993,"name":"WithConcurrencyPolicy","signature":"func (b *CronJobSpecApplyConfiguration) WithConcurrencyPolicy(value v1beta1.ConcurrencyPolicy) *CronJobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjobspec.go","code":"// WithConcurrencyPolicy sets the ConcurrencyPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ConcurrencyPolicy field is set to the value of the last call.\nfunc (b *CronJobSpecApplyConfiguration) WithConcurrencyPolicy(value v1beta1.ConcurrencyPolicy) *CronJobSpecApplyConfiguration {\n\tb.ConcurrencyPolicy = \u0026value\n\treturn b\n}","line":{"from":68,"to":74}} {"id":100020994,"name":"WithSuspend","signature":"func (b *CronJobSpecApplyConfiguration) WithSuspend(value bool) *CronJobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjobspec.go","code":"// WithSuspend sets the Suspend field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Suspend field is set to the value of the last call.\nfunc (b *CronJobSpecApplyConfiguration) WithSuspend(value bool) *CronJobSpecApplyConfiguration {\n\tb.Suspend = \u0026value\n\treturn b\n}","line":{"from":76,"to":82}} {"id":100020995,"name":"WithJobTemplate","signature":"func (b *CronJobSpecApplyConfiguration) WithJobTemplate(value *JobTemplateSpecApplyConfiguration) *CronJobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjobspec.go","code":"// WithJobTemplate sets the JobTemplate field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the JobTemplate field is set to the value of the last call.\nfunc (b *CronJobSpecApplyConfiguration) WithJobTemplate(value *JobTemplateSpecApplyConfiguration) *CronJobSpecApplyConfiguration {\n\tb.JobTemplate = value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100020996,"name":"WithSuccessfulJobsHistoryLimit","signature":"func (b *CronJobSpecApplyConfiguration) WithSuccessfulJobsHistoryLimit(value int32) *CronJobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjobspec.go","code":"// WithSuccessfulJobsHistoryLimit sets the SuccessfulJobsHistoryLimit field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SuccessfulJobsHistoryLimit field is set to the value of the last call.\nfunc (b *CronJobSpecApplyConfiguration) WithSuccessfulJobsHistoryLimit(value int32) *CronJobSpecApplyConfiguration {\n\tb.SuccessfulJobsHistoryLimit = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100020997,"name":"WithFailedJobsHistoryLimit","signature":"func (b *CronJobSpecApplyConfiguration) WithFailedJobsHistoryLimit(value int32) *CronJobSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjobspec.go","code":"// WithFailedJobsHistoryLimit sets the FailedJobsHistoryLimit field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FailedJobsHistoryLimit field is set to the value of the last call.\nfunc (b *CronJobSpecApplyConfiguration) WithFailedJobsHistoryLimit(value int32) *CronJobSpecApplyConfiguration {\n\tb.FailedJobsHistoryLimit = \u0026value\n\treturn b\n}","line":{"from":100,"to":106}} {"id":100020998,"name":"CronJobStatus","signature":"func CronJobStatus() *CronJobStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjobstatus.go","code":"// CronJobStatusApplyConfiguration constructs an declarative configuration of the CronJobStatus type for use with\n// apply.\nfunc CronJobStatus() *CronJobStatusApplyConfiguration {\n\treturn \u0026CronJobStatusApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100020999,"name":"WithActive","signature":"func (b *CronJobStatusApplyConfiguration) WithActive(values ...*v1.ObjectReferenceApplyConfiguration) *CronJobStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjobstatus.go","code":"// WithActive adds the given value to the Active field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Active field.\nfunc (b *CronJobStatusApplyConfiguration) WithActive(values ...*v1.ObjectReferenceApplyConfiguration) *CronJobStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithActive\")\n\t\t}\n\t\tb.Active = append(b.Active, *values[i])\n\t}\n\treturn b\n}","line":{"from":40,"to":51}} {"id":100021000,"name":"WithLastScheduleTime","signature":"func (b *CronJobStatusApplyConfiguration) WithLastScheduleTime(value metav1.Time) *CronJobStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjobstatus.go","code":"// WithLastScheduleTime sets the LastScheduleTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastScheduleTime field is set to the value of the last call.\nfunc (b *CronJobStatusApplyConfiguration) WithLastScheduleTime(value metav1.Time) *CronJobStatusApplyConfiguration {\n\tb.LastScheduleTime = \u0026value\n\treturn b\n}","line":{"from":53,"to":59}} {"id":100021001,"name":"WithLastSuccessfulTime","signature":"func (b *CronJobStatusApplyConfiguration) WithLastSuccessfulTime(value metav1.Time) *CronJobStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/cronjobstatus.go","code":"// WithLastSuccessfulTime sets the LastSuccessfulTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastSuccessfulTime field is set to the value of the last call.\nfunc (b *CronJobStatusApplyConfiguration) WithLastSuccessfulTime(value metav1.Time) *CronJobStatusApplyConfiguration {\n\tb.LastSuccessfulTime = \u0026value\n\treturn b\n}","line":{"from":61,"to":67}} {"id":100021002,"name":"JobTemplateSpec","signature":"func JobTemplateSpec() *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/jobtemplatespec.go","code":"// JobTemplateSpecApplyConfiguration constructs an declarative configuration of the JobTemplateSpec type for use with\n// apply.\nfunc JobTemplateSpec() *JobTemplateSpecApplyConfiguration {\n\treturn \u0026JobTemplateSpecApplyConfiguration{}\n}","line":{"from":35,"to":39}} {"id":100021003,"name":"WithName","signature":"func (b *JobTemplateSpecApplyConfiguration) WithName(value string) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/jobtemplatespec.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *JobTemplateSpecApplyConfiguration) WithName(value string) *JobTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":41,"to":48}} {"id":100021004,"name":"WithGenerateName","signature":"func (b *JobTemplateSpecApplyConfiguration) WithGenerateName(value string) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/jobtemplatespec.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *JobTemplateSpecApplyConfiguration) WithGenerateName(value string) *JobTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":50,"to":57}} {"id":100021005,"name":"WithNamespace","signature":"func (b *JobTemplateSpecApplyConfiguration) WithNamespace(value string) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/jobtemplatespec.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *JobTemplateSpecApplyConfiguration) WithNamespace(value string) *JobTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":59,"to":66}} {"id":100021006,"name":"WithUID","signature":"func (b *JobTemplateSpecApplyConfiguration) WithUID(value types.UID) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/jobtemplatespec.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *JobTemplateSpecApplyConfiguration) WithUID(value types.UID) *JobTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":68,"to":75}} {"id":100021007,"name":"WithResourceVersion","signature":"func (b *JobTemplateSpecApplyConfiguration) WithResourceVersion(value string) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/jobtemplatespec.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *JobTemplateSpecApplyConfiguration) WithResourceVersion(value string) *JobTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":77,"to":84}} {"id":100021008,"name":"WithGeneration","signature":"func (b *JobTemplateSpecApplyConfiguration) WithGeneration(value int64) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/jobtemplatespec.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *JobTemplateSpecApplyConfiguration) WithGeneration(value int64) *JobTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":86,"to":93}} {"id":100021009,"name":"WithCreationTimestamp","signature":"func (b *JobTemplateSpecApplyConfiguration) WithCreationTimestamp(value metav1.Time) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/jobtemplatespec.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *JobTemplateSpecApplyConfiguration) WithCreationTimestamp(value metav1.Time) *JobTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":95,"to":102}} {"id":100021010,"name":"WithDeletionTimestamp","signature":"func (b *JobTemplateSpecApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/jobtemplatespec.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *JobTemplateSpecApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *JobTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":104,"to":111}} {"id":100021011,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *JobTemplateSpecApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/jobtemplatespec.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *JobTemplateSpecApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *JobTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":113,"to":120}} {"id":100021012,"name":"WithLabels","signature":"func (b *JobTemplateSpecApplyConfiguration) WithLabels(entries map[string]string) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/jobtemplatespec.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *JobTemplateSpecApplyConfiguration) WithLabels(entries map[string]string) *JobTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":122,"to":135}} {"id":100021013,"name":"WithAnnotations","signature":"func (b *JobTemplateSpecApplyConfiguration) WithAnnotations(entries map[string]string) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/jobtemplatespec.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *JobTemplateSpecApplyConfiguration) WithAnnotations(entries map[string]string) *JobTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":137,"to":150}} {"id":100021014,"name":"WithOwnerReferences","signature":"func (b *JobTemplateSpecApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/jobtemplatespec.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *JobTemplateSpecApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *JobTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":152,"to":164}} {"id":100021015,"name":"WithFinalizers","signature":"func (b *JobTemplateSpecApplyConfiguration) WithFinalizers(values ...string) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/jobtemplatespec.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *JobTemplateSpecApplyConfiguration) WithFinalizers(values ...string) *JobTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":166,"to":175}} {"id":100021016,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *JobTemplateSpecApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/jobtemplatespec.go","code":"func (b *JobTemplateSpecApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":177,"to":181}} {"id":100021017,"name":"WithSpec","signature":"func (b *JobTemplateSpecApplyConfiguration) WithSpec(value *batchv1.JobSpecApplyConfiguration) *JobTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/batch/v1beta1/jobtemplatespec.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *JobTemplateSpecApplyConfiguration) WithSpec(value *batchv1.JobSpecApplyConfiguration) *JobTemplateSpecApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":183,"to":189}} {"id":100021018,"name":"CertificateSigningRequest","signature":"func CertificateSigningRequest(name string) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequest.go","code":"// CertificateSigningRequest constructs an declarative configuration of the CertificateSigningRequest type for use with\n// apply.\nfunc CertificateSigningRequest(name string) *CertificateSigningRequestApplyConfiguration {\n\tb := \u0026CertificateSigningRequestApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"CertificateSigningRequest\")\n\tb.WithAPIVersion(\"certificates.k8s.io/v1\")\n\treturn b\n}","line":{"from":39,"to":47}} {"id":100021019,"name":"ExtractCertificateSigningRequest","signature":"func ExtractCertificateSigningRequest(certificateSigningRequest *apicertificatesv1.CertificateSigningRequest, fieldManager string) (*CertificateSigningRequestApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequest.go","code":"// ExtractCertificateSigningRequest extracts the applied configuration owned by fieldManager from\n// certificateSigningRequest. If no managedFields are found in certificateSigningRequest for fieldManager, a\n// CertificateSigningRequestApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// certificateSigningRequest must be a unmodified CertificateSigningRequest API object that was retrieved from the Kubernetes API.\n// ExtractCertificateSigningRequest provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractCertificateSigningRequest(certificateSigningRequest *apicertificatesv1.CertificateSigningRequest, fieldManager string) (*CertificateSigningRequestApplyConfiguration, error) {\n\treturn extractCertificateSigningRequest(certificateSigningRequest, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100021020,"name":"ExtractCertificateSigningRequestStatus","signature":"func ExtractCertificateSigningRequestStatus(certificateSigningRequest *apicertificatesv1.CertificateSigningRequest, fieldManager string) (*CertificateSigningRequestApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequest.go","code":"// ExtractCertificateSigningRequestStatus is the same as ExtractCertificateSigningRequest except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractCertificateSigningRequestStatus(certificateSigningRequest *apicertificatesv1.CertificateSigningRequest, fieldManager string) (*CertificateSigningRequestApplyConfiguration, error) {\n\treturn extractCertificateSigningRequest(certificateSigningRequest, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100021021,"name":"extractCertificateSigningRequest","signature":"func extractCertificateSigningRequest(certificateSigningRequest *apicertificatesv1.CertificateSigningRequest, fieldManager string, subresource string) (*CertificateSigningRequestApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequest.go","code":"func extractCertificateSigningRequest(certificateSigningRequest *apicertificatesv1.CertificateSigningRequest, fieldManager string, subresource string) (*CertificateSigningRequestApplyConfiguration, error) {\n\tb := \u0026CertificateSigningRequestApplyConfiguration{}\n\terr := managedfields.ExtractInto(certificateSigningRequest, internal.Parser().Type(\"io.k8s.api.certificates.v1.CertificateSigningRequest\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(certificateSigningRequest.Name)\n\n\tb.WithKind(\"CertificateSigningRequest\")\n\tb.WithAPIVersion(\"certificates.k8s.io/v1\")\n\treturn b, nil\n}","line":{"from":71,"to":82}} {"id":100021022,"name":"WithKind","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithKind(value string) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequest.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithKind(value string) *CertificateSigningRequestApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100021023,"name":"WithAPIVersion","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithAPIVersion(value string) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequest.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithAPIVersion(value string) *CertificateSigningRequestApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100021024,"name":"WithName","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithName(value string) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequest.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithName(value string) *CertificateSigningRequestApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":100,"to":107}} {"id":100021025,"name":"WithGenerateName","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithGenerateName(value string) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequest.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithGenerateName(value string) *CertificateSigningRequestApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":109,"to":116}} {"id":100021026,"name":"WithNamespace","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithNamespace(value string) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequest.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithNamespace(value string) *CertificateSigningRequestApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":118,"to":125}} {"id":100021027,"name":"WithUID","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithUID(value types.UID) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequest.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithUID(value types.UID) *CertificateSigningRequestApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":127,"to":134}} {"id":100021028,"name":"WithResourceVersion","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithResourceVersion(value string) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequest.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithResourceVersion(value string) *CertificateSigningRequestApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":136,"to":143}} {"id":100021029,"name":"WithGeneration","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithGeneration(value int64) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequest.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithGeneration(value int64) *CertificateSigningRequestApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":145,"to":152}} {"id":100021030,"name":"WithCreationTimestamp","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithCreationTimestamp(value metav1.Time) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequest.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithCreationTimestamp(value metav1.Time) *CertificateSigningRequestApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":154,"to":161}} {"id":100021031,"name":"WithDeletionTimestamp","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequest.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *CertificateSigningRequestApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":163,"to":170}} {"id":100021032,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequest.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *CertificateSigningRequestApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":172,"to":179}} {"id":100021033,"name":"WithLabels","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithLabels(entries map[string]string) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequest.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithLabels(entries map[string]string) *CertificateSigningRequestApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":181,"to":194}} {"id":100021034,"name":"WithAnnotations","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithAnnotations(entries map[string]string) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequest.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithAnnotations(entries map[string]string) *CertificateSigningRequestApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100021035,"name":"WithOwnerReferences","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequest.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *CertificateSigningRequestApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":211,"to":223}} {"id":100021036,"name":"WithFinalizers","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithFinalizers(values ...string) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequest.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithFinalizers(values ...string) *CertificateSigningRequestApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":225,"to":234}} {"id":100021037,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *CertificateSigningRequestApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequest.go","code":"func (b *CertificateSigningRequestApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":236,"to":240}} {"id":100021038,"name":"WithSpec","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithSpec(value *CertificateSigningRequestSpecApplyConfiguration) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequest.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithSpec(value *CertificateSigningRequestSpecApplyConfiguration) *CertificateSigningRequestApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":242,"to":248}} {"id":100021039,"name":"WithStatus","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithStatus(value *CertificateSigningRequestStatusApplyConfiguration) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequest.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithStatus(value *CertificateSigningRequestStatusApplyConfiguration) *CertificateSigningRequestApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":250,"to":256}} {"id":100021040,"name":"CertificateSigningRequestCondition","signature":"func CertificateSigningRequestCondition() *CertificateSigningRequestConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequestcondition.go","code":"// CertificateSigningRequestConditionApplyConfiguration constructs an declarative configuration of the CertificateSigningRequestCondition type for use with\n// apply.\nfunc CertificateSigningRequestCondition() *CertificateSigningRequestConditionApplyConfiguration {\n\treturn \u0026CertificateSigningRequestConditionApplyConfiguration{}\n}","line":{"from":38,"to":42}} {"id":100021041,"name":"WithType","signature":"func (b *CertificateSigningRequestConditionApplyConfiguration) WithType(value v1.RequestConditionType) *CertificateSigningRequestConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequestcondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *CertificateSigningRequestConditionApplyConfiguration) WithType(value v1.RequestConditionType) *CertificateSigningRequestConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100021042,"name":"WithStatus","signature":"func (b *CertificateSigningRequestConditionApplyConfiguration) WithStatus(value corev1.ConditionStatus) *CertificateSigningRequestConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequestcondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *CertificateSigningRequestConditionApplyConfiguration) WithStatus(value corev1.ConditionStatus) *CertificateSigningRequestConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100021043,"name":"WithReason","signature":"func (b *CertificateSigningRequestConditionApplyConfiguration) WithReason(value string) *CertificateSigningRequestConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequestcondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *CertificateSigningRequestConditionApplyConfiguration) WithReason(value string) *CertificateSigningRequestConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100021044,"name":"WithMessage","signature":"func (b *CertificateSigningRequestConditionApplyConfiguration) WithMessage(value string) *CertificateSigningRequestConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequestcondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *CertificateSigningRequestConditionApplyConfiguration) WithMessage(value string) *CertificateSigningRequestConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":68,"to":74}} {"id":100021045,"name":"WithLastUpdateTime","signature":"func (b *CertificateSigningRequestConditionApplyConfiguration) WithLastUpdateTime(value metav1.Time) *CertificateSigningRequestConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequestcondition.go","code":"// WithLastUpdateTime sets the LastUpdateTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastUpdateTime field is set to the value of the last call.\nfunc (b *CertificateSigningRequestConditionApplyConfiguration) WithLastUpdateTime(value metav1.Time) *CertificateSigningRequestConditionApplyConfiguration {\n\tb.LastUpdateTime = \u0026value\n\treturn b\n}","line":{"from":76,"to":82}} {"id":100021046,"name":"WithLastTransitionTime","signature":"func (b *CertificateSigningRequestConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *CertificateSigningRequestConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequestcondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *CertificateSigningRequestConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *CertificateSigningRequestConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100021047,"name":"CertificateSigningRequestSpec","signature":"func CertificateSigningRequestSpec() *CertificateSigningRequestSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequestspec.go","code":"// CertificateSigningRequestSpecApplyConfiguration constructs an declarative configuration of the CertificateSigningRequestSpec type for use with\n// apply.\nfunc CertificateSigningRequestSpec() *CertificateSigningRequestSpecApplyConfiguration {\n\treturn \u0026CertificateSigningRequestSpecApplyConfiguration{}\n}","line":{"from":38,"to":42}} {"id":100021048,"name":"WithRequest","signature":"func (b *CertificateSigningRequestSpecApplyConfiguration) WithRequest(values ...byte) *CertificateSigningRequestSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequestspec.go","code":"// WithRequest adds the given value to the Request field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Request field.\nfunc (b *CertificateSigningRequestSpecApplyConfiguration) WithRequest(values ...byte) *CertificateSigningRequestSpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.Request = append(b.Request, values[i])\n\t}\n\treturn b\n}","line":{"from":44,"to":52}} {"id":100021049,"name":"WithSignerName","signature":"func (b *CertificateSigningRequestSpecApplyConfiguration) WithSignerName(value string) *CertificateSigningRequestSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequestspec.go","code":"// WithSignerName sets the SignerName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SignerName field is set to the value of the last call.\nfunc (b *CertificateSigningRequestSpecApplyConfiguration) WithSignerName(value string) *CertificateSigningRequestSpecApplyConfiguration {\n\tb.SignerName = \u0026value\n\treturn b\n}","line":{"from":54,"to":60}} {"id":100021050,"name":"WithExpirationSeconds","signature":"func (b *CertificateSigningRequestSpecApplyConfiguration) WithExpirationSeconds(value int32) *CertificateSigningRequestSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequestspec.go","code":"// WithExpirationSeconds sets the ExpirationSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ExpirationSeconds field is set to the value of the last call.\nfunc (b *CertificateSigningRequestSpecApplyConfiguration) WithExpirationSeconds(value int32) *CertificateSigningRequestSpecApplyConfiguration {\n\tb.ExpirationSeconds = \u0026value\n\treturn b\n}","line":{"from":62,"to":68}} {"id":100021051,"name":"WithUsages","signature":"func (b *CertificateSigningRequestSpecApplyConfiguration) WithUsages(values ...v1.KeyUsage) *CertificateSigningRequestSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequestspec.go","code":"// WithUsages adds the given value to the Usages field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Usages field.\nfunc (b *CertificateSigningRequestSpecApplyConfiguration) WithUsages(values ...v1.KeyUsage) *CertificateSigningRequestSpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.Usages = append(b.Usages, values[i])\n\t}\n\treturn b\n}","line":{"from":70,"to":78}} {"id":100021052,"name":"WithUsername","signature":"func (b *CertificateSigningRequestSpecApplyConfiguration) WithUsername(value string) *CertificateSigningRequestSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequestspec.go","code":"// WithUsername sets the Username field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Username field is set to the value of the last call.\nfunc (b *CertificateSigningRequestSpecApplyConfiguration) WithUsername(value string) *CertificateSigningRequestSpecApplyConfiguration {\n\tb.Username = \u0026value\n\treturn b\n}","line":{"from":80,"to":86}} {"id":100021053,"name":"WithUID","signature":"func (b *CertificateSigningRequestSpecApplyConfiguration) WithUID(value string) *CertificateSigningRequestSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequestspec.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *CertificateSigningRequestSpecApplyConfiguration) WithUID(value string) *CertificateSigningRequestSpecApplyConfiguration {\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":88,"to":94}} {"id":100021054,"name":"WithGroups","signature":"func (b *CertificateSigningRequestSpecApplyConfiguration) WithGroups(values ...string) *CertificateSigningRequestSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequestspec.go","code":"// WithGroups adds the given value to the Groups field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Groups field.\nfunc (b *CertificateSigningRequestSpecApplyConfiguration) WithGroups(values ...string) *CertificateSigningRequestSpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.Groups = append(b.Groups, values[i])\n\t}\n\treturn b\n}","line":{"from":96,"to":104}} {"id":100021055,"name":"WithExtra","signature":"func (b *CertificateSigningRequestSpecApplyConfiguration) WithExtra(entries map[string]v1.ExtraValue) *CertificateSigningRequestSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequestspec.go","code":"// WithExtra puts the entries into the Extra field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Extra field,\n// overwriting an existing map entries in Extra field with the same key.\nfunc (b *CertificateSigningRequestSpecApplyConfiguration) WithExtra(entries map[string]v1.ExtraValue) *CertificateSigningRequestSpecApplyConfiguration {\n\tif b.Extra == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Extra = make(map[string]v1.ExtraValue, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Extra[k] = v\n\t}\n\treturn b\n}","line":{"from":106,"to":118}} {"id":100021056,"name":"CertificateSigningRequestStatus","signature":"func CertificateSigningRequestStatus() *CertificateSigningRequestStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequeststatus.go","code":"// CertificateSigningRequestStatusApplyConfiguration constructs an declarative configuration of the CertificateSigningRequestStatus type for use with\n// apply.\nfunc CertificateSigningRequestStatus() *CertificateSigningRequestStatusApplyConfiguration {\n\treturn \u0026CertificateSigningRequestStatusApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100021057,"name":"WithConditions","signature":"func (b *CertificateSigningRequestStatusApplyConfiguration) WithConditions(values ...*CertificateSigningRequestConditionApplyConfiguration) *CertificateSigningRequestStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequeststatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *CertificateSigningRequestStatusApplyConfiguration) WithConditions(values ...*CertificateSigningRequestConditionApplyConfiguration) *CertificateSigningRequestStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":34,"to":45}} {"id":100021058,"name":"WithCertificate","signature":"func (b *CertificateSigningRequestStatusApplyConfiguration) WithCertificate(values ...byte) *CertificateSigningRequestStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1/certificatesigningrequeststatus.go","code":"// WithCertificate adds the given value to the Certificate field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Certificate field.\nfunc (b *CertificateSigningRequestStatusApplyConfiguration) WithCertificate(values ...byte) *CertificateSigningRequestStatusApplyConfiguration {\n\tfor i := range values {\n\t\tb.Certificate = append(b.Certificate, values[i])\n\t}\n\treturn b\n}","line":{"from":47,"to":55}} {"id":100021059,"name":"ClusterTrustBundle","signature":"func ClusterTrustBundle(name string) *ClusterTrustBundleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundle.go","code":"// ClusterTrustBundle constructs an declarative configuration of the ClusterTrustBundle type for use with\n// apply.\nfunc ClusterTrustBundle(name string) *ClusterTrustBundleApplyConfiguration {\n\tb := \u0026ClusterTrustBundleApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"ClusterTrustBundle\")\n\tb.WithAPIVersion(\"certificates.k8s.io/v1alpha1\")\n\treturn b\n}","line":{"from":38,"to":46}} {"id":100021060,"name":"ExtractClusterTrustBundle","signature":"func ExtractClusterTrustBundle(clusterTrustBundle *certificatesv1alpha1.ClusterTrustBundle, fieldManager string) (*ClusterTrustBundleApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundle.go","code":"// ExtractClusterTrustBundle extracts the applied configuration owned by fieldManager from\n// clusterTrustBundle. If no managedFields are found in clusterTrustBundle for fieldManager, a\n// ClusterTrustBundleApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// clusterTrustBundle must be a unmodified ClusterTrustBundle API object that was retrieved from the Kubernetes API.\n// ExtractClusterTrustBundle provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractClusterTrustBundle(clusterTrustBundle *certificatesv1alpha1.ClusterTrustBundle, fieldManager string) (*ClusterTrustBundleApplyConfiguration, error) {\n\treturn extractClusterTrustBundle(clusterTrustBundle, fieldManager, \"\")\n}","line":{"from":48,"to":61}} {"id":100021061,"name":"ExtractClusterTrustBundleStatus","signature":"func ExtractClusterTrustBundleStatus(clusterTrustBundle *certificatesv1alpha1.ClusterTrustBundle, fieldManager string) (*ClusterTrustBundleApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundle.go","code":"// ExtractClusterTrustBundleStatus is the same as ExtractClusterTrustBundle except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractClusterTrustBundleStatus(clusterTrustBundle *certificatesv1alpha1.ClusterTrustBundle, fieldManager string) (*ClusterTrustBundleApplyConfiguration, error) {\n\treturn extractClusterTrustBundle(clusterTrustBundle, fieldManager, \"status\")\n}","line":{"from":63,"to":68}} {"id":100021062,"name":"extractClusterTrustBundle","signature":"func extractClusterTrustBundle(clusterTrustBundle *certificatesv1alpha1.ClusterTrustBundle, fieldManager string, subresource string) (*ClusterTrustBundleApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundle.go","code":"func extractClusterTrustBundle(clusterTrustBundle *certificatesv1alpha1.ClusterTrustBundle, fieldManager string, subresource string) (*ClusterTrustBundleApplyConfiguration, error) {\n\tb := \u0026ClusterTrustBundleApplyConfiguration{}\n\terr := managedfields.ExtractInto(clusterTrustBundle, internal.Parser().Type(\"io.k8s.api.certificates.v1alpha1.ClusterTrustBundle\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(clusterTrustBundle.Name)\n\n\tb.WithKind(\"ClusterTrustBundle\")\n\tb.WithAPIVersion(\"certificates.k8s.io/v1alpha1\")\n\treturn b, nil\n}","line":{"from":70,"to":81}} {"id":100021063,"name":"WithKind","signature":"func (b *ClusterTrustBundleApplyConfiguration) WithKind(value string) *ClusterTrustBundleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundle.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ClusterTrustBundleApplyConfiguration) WithKind(value string) *ClusterTrustBundleApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100021064,"name":"WithAPIVersion","signature":"func (b *ClusterTrustBundleApplyConfiguration) WithAPIVersion(value string) *ClusterTrustBundleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundle.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ClusterTrustBundleApplyConfiguration) WithAPIVersion(value string) *ClusterTrustBundleApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":91,"to":97}} {"id":100021065,"name":"WithName","signature":"func (b *ClusterTrustBundleApplyConfiguration) WithName(value string) *ClusterTrustBundleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundle.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ClusterTrustBundleApplyConfiguration) WithName(value string) *ClusterTrustBundleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":99,"to":106}} {"id":100021066,"name":"WithGenerateName","signature":"func (b *ClusterTrustBundleApplyConfiguration) WithGenerateName(value string) *ClusterTrustBundleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundle.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ClusterTrustBundleApplyConfiguration) WithGenerateName(value string) *ClusterTrustBundleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":108,"to":115}} {"id":100021067,"name":"WithNamespace","signature":"func (b *ClusterTrustBundleApplyConfiguration) WithNamespace(value string) *ClusterTrustBundleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundle.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ClusterTrustBundleApplyConfiguration) WithNamespace(value string) *ClusterTrustBundleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":117,"to":124}} {"id":100021068,"name":"WithUID","signature":"func (b *ClusterTrustBundleApplyConfiguration) WithUID(value types.UID) *ClusterTrustBundleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundle.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ClusterTrustBundleApplyConfiguration) WithUID(value types.UID) *ClusterTrustBundleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":126,"to":133}} {"id":100021069,"name":"WithResourceVersion","signature":"func (b *ClusterTrustBundleApplyConfiguration) WithResourceVersion(value string) *ClusterTrustBundleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundle.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ClusterTrustBundleApplyConfiguration) WithResourceVersion(value string) *ClusterTrustBundleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":135,"to":142}} {"id":100021070,"name":"WithGeneration","signature":"func (b *ClusterTrustBundleApplyConfiguration) WithGeneration(value int64) *ClusterTrustBundleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundle.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ClusterTrustBundleApplyConfiguration) WithGeneration(value int64) *ClusterTrustBundleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":144,"to":151}} {"id":100021071,"name":"WithCreationTimestamp","signature":"func (b *ClusterTrustBundleApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ClusterTrustBundleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundle.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ClusterTrustBundleApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ClusterTrustBundleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":153,"to":160}} {"id":100021072,"name":"WithDeletionTimestamp","signature":"func (b *ClusterTrustBundleApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ClusterTrustBundleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundle.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ClusterTrustBundleApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ClusterTrustBundleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":162,"to":169}} {"id":100021073,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ClusterTrustBundleApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ClusterTrustBundleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundle.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ClusterTrustBundleApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ClusterTrustBundleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":171,"to":178}} {"id":100021074,"name":"WithLabels","signature":"func (b *ClusterTrustBundleApplyConfiguration) WithLabels(entries map[string]string) *ClusterTrustBundleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundle.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ClusterTrustBundleApplyConfiguration) WithLabels(entries map[string]string) *ClusterTrustBundleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":180,"to":193}} {"id":100021075,"name":"WithAnnotations","signature":"func (b *ClusterTrustBundleApplyConfiguration) WithAnnotations(entries map[string]string) *ClusterTrustBundleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundle.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ClusterTrustBundleApplyConfiguration) WithAnnotations(entries map[string]string) *ClusterTrustBundleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":195,"to":208}} {"id":100021076,"name":"WithOwnerReferences","signature":"func (b *ClusterTrustBundleApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ClusterTrustBundleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundle.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ClusterTrustBundleApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ClusterTrustBundleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":210,"to":222}} {"id":100021077,"name":"WithFinalizers","signature":"func (b *ClusterTrustBundleApplyConfiguration) WithFinalizers(values ...string) *ClusterTrustBundleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundle.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ClusterTrustBundleApplyConfiguration) WithFinalizers(values ...string) *ClusterTrustBundleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":224,"to":233}} {"id":100021078,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ClusterTrustBundleApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundle.go","code":"func (b *ClusterTrustBundleApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":235,"to":239}} {"id":100021079,"name":"WithSpec","signature":"func (b *ClusterTrustBundleApplyConfiguration) WithSpec(value *ClusterTrustBundleSpecApplyConfiguration) *ClusterTrustBundleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundle.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *ClusterTrustBundleApplyConfiguration) WithSpec(value *ClusterTrustBundleSpecApplyConfiguration) *ClusterTrustBundleApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":241,"to":247}} {"id":100021080,"name":"ClusterTrustBundleSpec","signature":"func ClusterTrustBundleSpec() *ClusterTrustBundleSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundlespec.go","code":"// ClusterTrustBundleSpecApplyConfiguration constructs an declarative configuration of the ClusterTrustBundleSpec type for use with\n// apply.\nfunc ClusterTrustBundleSpec() *ClusterTrustBundleSpecApplyConfiguration {\n\treturn \u0026ClusterTrustBundleSpecApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100021081,"name":"WithSignerName","signature":"func (b *ClusterTrustBundleSpecApplyConfiguration) WithSignerName(value string) *ClusterTrustBundleSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundlespec.go","code":"// WithSignerName sets the SignerName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SignerName field is set to the value of the last call.\nfunc (b *ClusterTrustBundleSpecApplyConfiguration) WithSignerName(value string) *ClusterTrustBundleSpecApplyConfiguration {\n\tb.SignerName = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100021082,"name":"WithTrustBundle","signature":"func (b *ClusterTrustBundleSpecApplyConfiguration) WithTrustBundle(value string) *ClusterTrustBundleSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1alpha1/clustertrustbundlespec.go","code":"// WithTrustBundle sets the TrustBundle field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TrustBundle field is set to the value of the last call.\nfunc (b *ClusterTrustBundleSpecApplyConfiguration) WithTrustBundle(value string) *ClusterTrustBundleSpecApplyConfiguration {\n\tb.TrustBundle = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100021083,"name":"CertificateSigningRequest","signature":"func CertificateSigningRequest(name string) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequest.go","code":"// CertificateSigningRequest constructs an declarative configuration of the CertificateSigningRequest type for use with\n// apply.\nfunc CertificateSigningRequest(name string) *CertificateSigningRequestApplyConfiguration {\n\tb := \u0026CertificateSigningRequestApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"CertificateSigningRequest\")\n\tb.WithAPIVersion(\"certificates.k8s.io/v1beta1\")\n\treturn b\n}","line":{"from":39,"to":47}} {"id":100021084,"name":"ExtractCertificateSigningRequest","signature":"func ExtractCertificateSigningRequest(certificateSigningRequest *certificatesv1beta1.CertificateSigningRequest, fieldManager string) (*CertificateSigningRequestApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequest.go","code":"// ExtractCertificateSigningRequest extracts the applied configuration owned by fieldManager from\n// certificateSigningRequest. If no managedFields are found in certificateSigningRequest for fieldManager, a\n// CertificateSigningRequestApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// certificateSigningRequest must be a unmodified CertificateSigningRequest API object that was retrieved from the Kubernetes API.\n// ExtractCertificateSigningRequest provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractCertificateSigningRequest(certificateSigningRequest *certificatesv1beta1.CertificateSigningRequest, fieldManager string) (*CertificateSigningRequestApplyConfiguration, error) {\n\treturn extractCertificateSigningRequest(certificateSigningRequest, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100021085,"name":"ExtractCertificateSigningRequestStatus","signature":"func ExtractCertificateSigningRequestStatus(certificateSigningRequest *certificatesv1beta1.CertificateSigningRequest, fieldManager string) (*CertificateSigningRequestApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequest.go","code":"// ExtractCertificateSigningRequestStatus is the same as ExtractCertificateSigningRequest except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractCertificateSigningRequestStatus(certificateSigningRequest *certificatesv1beta1.CertificateSigningRequest, fieldManager string) (*CertificateSigningRequestApplyConfiguration, error) {\n\treturn extractCertificateSigningRequest(certificateSigningRequest, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100021086,"name":"extractCertificateSigningRequest","signature":"func extractCertificateSigningRequest(certificateSigningRequest *certificatesv1beta1.CertificateSigningRequest, fieldManager string, subresource string) (*CertificateSigningRequestApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequest.go","code":"func extractCertificateSigningRequest(certificateSigningRequest *certificatesv1beta1.CertificateSigningRequest, fieldManager string, subresource string) (*CertificateSigningRequestApplyConfiguration, error) {\n\tb := \u0026CertificateSigningRequestApplyConfiguration{}\n\terr := managedfields.ExtractInto(certificateSigningRequest, internal.Parser().Type(\"io.k8s.api.certificates.v1beta1.CertificateSigningRequest\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(certificateSigningRequest.Name)\n\n\tb.WithKind(\"CertificateSigningRequest\")\n\tb.WithAPIVersion(\"certificates.k8s.io/v1beta1\")\n\treturn b, nil\n}","line":{"from":71,"to":82}} {"id":100021087,"name":"WithKind","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithKind(value string) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequest.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithKind(value string) *CertificateSigningRequestApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100021088,"name":"WithAPIVersion","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithAPIVersion(value string) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequest.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithAPIVersion(value string) *CertificateSigningRequestApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100021089,"name":"WithName","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithName(value string) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequest.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithName(value string) *CertificateSigningRequestApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":100,"to":107}} {"id":100021090,"name":"WithGenerateName","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithGenerateName(value string) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequest.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithGenerateName(value string) *CertificateSigningRequestApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":109,"to":116}} {"id":100021091,"name":"WithNamespace","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithNamespace(value string) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequest.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithNamespace(value string) *CertificateSigningRequestApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":118,"to":125}} {"id":100021092,"name":"WithUID","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithUID(value types.UID) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequest.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithUID(value types.UID) *CertificateSigningRequestApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":127,"to":134}} {"id":100021093,"name":"WithResourceVersion","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithResourceVersion(value string) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequest.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithResourceVersion(value string) *CertificateSigningRequestApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":136,"to":143}} {"id":100021094,"name":"WithGeneration","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithGeneration(value int64) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequest.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithGeneration(value int64) *CertificateSigningRequestApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":145,"to":152}} {"id":100021095,"name":"WithCreationTimestamp","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithCreationTimestamp(value metav1.Time) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequest.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithCreationTimestamp(value metav1.Time) *CertificateSigningRequestApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":154,"to":161}} {"id":100021096,"name":"WithDeletionTimestamp","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequest.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *CertificateSigningRequestApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":163,"to":170}} {"id":100021097,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequest.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *CertificateSigningRequestApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":172,"to":179}} {"id":100021098,"name":"WithLabels","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithLabels(entries map[string]string) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequest.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithLabels(entries map[string]string) *CertificateSigningRequestApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":181,"to":194}} {"id":100021099,"name":"WithAnnotations","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithAnnotations(entries map[string]string) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequest.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithAnnotations(entries map[string]string) *CertificateSigningRequestApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100021100,"name":"WithOwnerReferences","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequest.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *CertificateSigningRequestApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":211,"to":223}} {"id":100021101,"name":"WithFinalizers","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithFinalizers(values ...string) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequest.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithFinalizers(values ...string) *CertificateSigningRequestApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":225,"to":234}} {"id":100021102,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *CertificateSigningRequestApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequest.go","code":"func (b *CertificateSigningRequestApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":236,"to":240}} {"id":100021103,"name":"WithSpec","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithSpec(value *CertificateSigningRequestSpecApplyConfiguration) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequest.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithSpec(value *CertificateSigningRequestSpecApplyConfiguration) *CertificateSigningRequestApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":242,"to":248}} {"id":100021104,"name":"WithStatus","signature":"func (b *CertificateSigningRequestApplyConfiguration) WithStatus(value *CertificateSigningRequestStatusApplyConfiguration) *CertificateSigningRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequest.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *CertificateSigningRequestApplyConfiguration) WithStatus(value *CertificateSigningRequestStatusApplyConfiguration) *CertificateSigningRequestApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":250,"to":256}} {"id":100021105,"name":"CertificateSigningRequestCondition","signature":"func CertificateSigningRequestCondition() *CertificateSigningRequestConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequestcondition.go","code":"// CertificateSigningRequestConditionApplyConfiguration constructs an declarative configuration of the CertificateSigningRequestCondition type for use with\n// apply.\nfunc CertificateSigningRequestCondition() *CertificateSigningRequestConditionApplyConfiguration {\n\treturn \u0026CertificateSigningRequestConditionApplyConfiguration{}\n}","line":{"from":38,"to":42}} {"id":100021106,"name":"WithType","signature":"func (b *CertificateSigningRequestConditionApplyConfiguration) WithType(value v1beta1.RequestConditionType) *CertificateSigningRequestConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequestcondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *CertificateSigningRequestConditionApplyConfiguration) WithType(value v1beta1.RequestConditionType) *CertificateSigningRequestConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100021107,"name":"WithStatus","signature":"func (b *CertificateSigningRequestConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *CertificateSigningRequestConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequestcondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *CertificateSigningRequestConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *CertificateSigningRequestConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100021108,"name":"WithReason","signature":"func (b *CertificateSigningRequestConditionApplyConfiguration) WithReason(value string) *CertificateSigningRequestConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequestcondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *CertificateSigningRequestConditionApplyConfiguration) WithReason(value string) *CertificateSigningRequestConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100021109,"name":"WithMessage","signature":"func (b *CertificateSigningRequestConditionApplyConfiguration) WithMessage(value string) *CertificateSigningRequestConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequestcondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *CertificateSigningRequestConditionApplyConfiguration) WithMessage(value string) *CertificateSigningRequestConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":68,"to":74}} {"id":100021110,"name":"WithLastUpdateTime","signature":"func (b *CertificateSigningRequestConditionApplyConfiguration) WithLastUpdateTime(value metav1.Time) *CertificateSigningRequestConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequestcondition.go","code":"// WithLastUpdateTime sets the LastUpdateTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastUpdateTime field is set to the value of the last call.\nfunc (b *CertificateSigningRequestConditionApplyConfiguration) WithLastUpdateTime(value metav1.Time) *CertificateSigningRequestConditionApplyConfiguration {\n\tb.LastUpdateTime = \u0026value\n\treturn b\n}","line":{"from":76,"to":82}} {"id":100021111,"name":"WithLastTransitionTime","signature":"func (b *CertificateSigningRequestConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *CertificateSigningRequestConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequestcondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *CertificateSigningRequestConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *CertificateSigningRequestConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100021112,"name":"CertificateSigningRequestSpec","signature":"func CertificateSigningRequestSpec() *CertificateSigningRequestSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequestspec.go","code":"// CertificateSigningRequestSpecApplyConfiguration constructs an declarative configuration of the CertificateSigningRequestSpec type for use with\n// apply.\nfunc CertificateSigningRequestSpec() *CertificateSigningRequestSpecApplyConfiguration {\n\treturn \u0026CertificateSigningRequestSpecApplyConfiguration{}\n}","line":{"from":38,"to":42}} {"id":100021113,"name":"WithRequest","signature":"func (b *CertificateSigningRequestSpecApplyConfiguration) WithRequest(values ...byte) *CertificateSigningRequestSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequestspec.go","code":"// WithRequest adds the given value to the Request field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Request field.\nfunc (b *CertificateSigningRequestSpecApplyConfiguration) WithRequest(values ...byte) *CertificateSigningRequestSpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.Request = append(b.Request, values[i])\n\t}\n\treturn b\n}","line":{"from":44,"to":52}} {"id":100021114,"name":"WithSignerName","signature":"func (b *CertificateSigningRequestSpecApplyConfiguration) WithSignerName(value string) *CertificateSigningRequestSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequestspec.go","code":"// WithSignerName sets the SignerName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SignerName field is set to the value of the last call.\nfunc (b *CertificateSigningRequestSpecApplyConfiguration) WithSignerName(value string) *CertificateSigningRequestSpecApplyConfiguration {\n\tb.SignerName = \u0026value\n\treturn b\n}","line":{"from":54,"to":60}} {"id":100021115,"name":"WithExpirationSeconds","signature":"func (b *CertificateSigningRequestSpecApplyConfiguration) WithExpirationSeconds(value int32) *CertificateSigningRequestSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequestspec.go","code":"// WithExpirationSeconds sets the ExpirationSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ExpirationSeconds field is set to the value of the last call.\nfunc (b *CertificateSigningRequestSpecApplyConfiguration) WithExpirationSeconds(value int32) *CertificateSigningRequestSpecApplyConfiguration {\n\tb.ExpirationSeconds = \u0026value\n\treturn b\n}","line":{"from":62,"to":68}} {"id":100021116,"name":"WithUsages","signature":"func (b *CertificateSigningRequestSpecApplyConfiguration) WithUsages(values ...v1beta1.KeyUsage) *CertificateSigningRequestSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequestspec.go","code":"// WithUsages adds the given value to the Usages field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Usages field.\nfunc (b *CertificateSigningRequestSpecApplyConfiguration) WithUsages(values ...v1beta1.KeyUsage) *CertificateSigningRequestSpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.Usages = append(b.Usages, values[i])\n\t}\n\treturn b\n}","line":{"from":70,"to":78}} {"id":100021117,"name":"WithUsername","signature":"func (b *CertificateSigningRequestSpecApplyConfiguration) WithUsername(value string) *CertificateSigningRequestSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequestspec.go","code":"// WithUsername sets the Username field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Username field is set to the value of the last call.\nfunc (b *CertificateSigningRequestSpecApplyConfiguration) WithUsername(value string) *CertificateSigningRequestSpecApplyConfiguration {\n\tb.Username = \u0026value\n\treturn b\n}","line":{"from":80,"to":86}} {"id":100021118,"name":"WithUID","signature":"func (b *CertificateSigningRequestSpecApplyConfiguration) WithUID(value string) *CertificateSigningRequestSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequestspec.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *CertificateSigningRequestSpecApplyConfiguration) WithUID(value string) *CertificateSigningRequestSpecApplyConfiguration {\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":88,"to":94}} {"id":100021119,"name":"WithGroups","signature":"func (b *CertificateSigningRequestSpecApplyConfiguration) WithGroups(values ...string) *CertificateSigningRequestSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequestspec.go","code":"// WithGroups adds the given value to the Groups field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Groups field.\nfunc (b *CertificateSigningRequestSpecApplyConfiguration) WithGroups(values ...string) *CertificateSigningRequestSpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.Groups = append(b.Groups, values[i])\n\t}\n\treturn b\n}","line":{"from":96,"to":104}} {"id":100021120,"name":"WithExtra","signature":"func (b *CertificateSigningRequestSpecApplyConfiguration) WithExtra(entries map[string]v1beta1.ExtraValue) *CertificateSigningRequestSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequestspec.go","code":"// WithExtra puts the entries into the Extra field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Extra field,\n// overwriting an existing map entries in Extra field with the same key.\nfunc (b *CertificateSigningRequestSpecApplyConfiguration) WithExtra(entries map[string]v1beta1.ExtraValue) *CertificateSigningRequestSpecApplyConfiguration {\n\tif b.Extra == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Extra = make(map[string]v1beta1.ExtraValue, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Extra[k] = v\n\t}\n\treturn b\n}","line":{"from":106,"to":118}} {"id":100021121,"name":"CertificateSigningRequestStatus","signature":"func CertificateSigningRequestStatus() *CertificateSigningRequestStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequeststatus.go","code":"// CertificateSigningRequestStatusApplyConfiguration constructs an declarative configuration of the CertificateSigningRequestStatus type for use with\n// apply.\nfunc CertificateSigningRequestStatus() *CertificateSigningRequestStatusApplyConfiguration {\n\treturn \u0026CertificateSigningRequestStatusApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100021122,"name":"WithConditions","signature":"func (b *CertificateSigningRequestStatusApplyConfiguration) WithConditions(values ...*CertificateSigningRequestConditionApplyConfiguration) *CertificateSigningRequestStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequeststatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *CertificateSigningRequestStatusApplyConfiguration) WithConditions(values ...*CertificateSigningRequestConditionApplyConfiguration) *CertificateSigningRequestStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":34,"to":45}} {"id":100021123,"name":"WithCertificate","signature":"func (b *CertificateSigningRequestStatusApplyConfiguration) WithCertificate(values ...byte) *CertificateSigningRequestStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/certificates/v1beta1/certificatesigningrequeststatus.go","code":"// WithCertificate adds the given value to the Certificate field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Certificate field.\nfunc (b *CertificateSigningRequestStatusApplyConfiguration) WithCertificate(values ...byte) *CertificateSigningRequestStatusApplyConfiguration {\n\tfor i := range values {\n\t\tb.Certificate = append(b.Certificate, values[i])\n\t}\n\treturn b\n}","line":{"from":47,"to":55}} {"id":100021124,"name":"Lease","signature":"func Lease(name, namespace string) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/lease.go","code":"// Lease constructs an declarative configuration of the Lease type for use with\n// apply.\nfunc Lease(name, namespace string) *LeaseApplyConfiguration {\n\tb := \u0026LeaseApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"Lease\")\n\tb.WithAPIVersion(\"coordination.k8s.io/v1\")\n\treturn b\n}","line":{"from":38,"to":47}} {"id":100021125,"name":"ExtractLease","signature":"func ExtractLease(lease *apicoordinationv1.Lease, fieldManager string) (*LeaseApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/lease.go","code":"// ExtractLease extracts the applied configuration owned by fieldManager from\n// lease. If no managedFields are found in lease for fieldManager, a\n// LeaseApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// lease must be a unmodified Lease API object that was retrieved from the Kubernetes API.\n// ExtractLease provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractLease(lease *apicoordinationv1.Lease, fieldManager string) (*LeaseApplyConfiguration, error) {\n\treturn extractLease(lease, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100021126,"name":"ExtractLeaseStatus","signature":"func ExtractLeaseStatus(lease *apicoordinationv1.Lease, fieldManager string) (*LeaseApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/lease.go","code":"// ExtractLeaseStatus is the same as ExtractLease except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractLeaseStatus(lease *apicoordinationv1.Lease, fieldManager string) (*LeaseApplyConfiguration, error) {\n\treturn extractLease(lease, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100021127,"name":"extractLease","signature":"func extractLease(lease *apicoordinationv1.Lease, fieldManager string, subresource string) (*LeaseApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/lease.go","code":"func extractLease(lease *apicoordinationv1.Lease, fieldManager string, subresource string) (*LeaseApplyConfiguration, error) {\n\tb := \u0026LeaseApplyConfiguration{}\n\terr := managedfields.ExtractInto(lease, internal.Parser().Type(\"io.k8s.api.coordination.v1.Lease\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(lease.Name)\n\tb.WithNamespace(lease.Namespace)\n\n\tb.WithKind(\"Lease\")\n\tb.WithAPIVersion(\"coordination.k8s.io/v1\")\n\treturn b, nil\n}","line":{"from":71,"to":83}} {"id":100021128,"name":"WithKind","signature":"func (b *LeaseApplyConfiguration) WithKind(value string) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/lease.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *LeaseApplyConfiguration) WithKind(value string) *LeaseApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":85,"to":91}} {"id":100021129,"name":"WithAPIVersion","signature":"func (b *LeaseApplyConfiguration) WithAPIVersion(value string) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/lease.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *LeaseApplyConfiguration) WithAPIVersion(value string) *LeaseApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":93,"to":99}} {"id":100021130,"name":"WithName","signature":"func (b *LeaseApplyConfiguration) WithName(value string) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/lease.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *LeaseApplyConfiguration) WithName(value string) *LeaseApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":101,"to":108}} {"id":100021131,"name":"WithGenerateName","signature":"func (b *LeaseApplyConfiguration) WithGenerateName(value string) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/lease.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *LeaseApplyConfiguration) WithGenerateName(value string) *LeaseApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":110,"to":117}} {"id":100021132,"name":"WithNamespace","signature":"func (b *LeaseApplyConfiguration) WithNamespace(value string) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/lease.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *LeaseApplyConfiguration) WithNamespace(value string) *LeaseApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":119,"to":126}} {"id":100021133,"name":"WithUID","signature":"func (b *LeaseApplyConfiguration) WithUID(value types.UID) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/lease.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *LeaseApplyConfiguration) WithUID(value types.UID) *LeaseApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":128,"to":135}} {"id":100021134,"name":"WithResourceVersion","signature":"func (b *LeaseApplyConfiguration) WithResourceVersion(value string) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/lease.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *LeaseApplyConfiguration) WithResourceVersion(value string) *LeaseApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":137,"to":144}} {"id":100021135,"name":"WithGeneration","signature":"func (b *LeaseApplyConfiguration) WithGeneration(value int64) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/lease.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *LeaseApplyConfiguration) WithGeneration(value int64) *LeaseApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":146,"to":153}} {"id":100021136,"name":"WithCreationTimestamp","signature":"func (b *LeaseApplyConfiguration) WithCreationTimestamp(value metav1.Time) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/lease.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *LeaseApplyConfiguration) WithCreationTimestamp(value metav1.Time) *LeaseApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":155,"to":162}} {"id":100021137,"name":"WithDeletionTimestamp","signature":"func (b *LeaseApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/lease.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *LeaseApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *LeaseApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":164,"to":171}} {"id":100021138,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *LeaseApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/lease.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *LeaseApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *LeaseApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":173,"to":180}} {"id":100021139,"name":"WithLabels","signature":"func (b *LeaseApplyConfiguration) WithLabels(entries map[string]string) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/lease.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *LeaseApplyConfiguration) WithLabels(entries map[string]string) *LeaseApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":182,"to":195}} {"id":100021140,"name":"WithAnnotations","signature":"func (b *LeaseApplyConfiguration) WithAnnotations(entries map[string]string) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/lease.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *LeaseApplyConfiguration) WithAnnotations(entries map[string]string) *LeaseApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":197,"to":210}} {"id":100021141,"name":"WithOwnerReferences","signature":"func (b *LeaseApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/lease.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *LeaseApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *LeaseApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":212,"to":224}} {"id":100021142,"name":"WithFinalizers","signature":"func (b *LeaseApplyConfiguration) WithFinalizers(values ...string) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/lease.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *LeaseApplyConfiguration) WithFinalizers(values ...string) *LeaseApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":226,"to":235}} {"id":100021143,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *LeaseApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/lease.go","code":"func (b *LeaseApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":237,"to":241}} {"id":100021144,"name":"WithSpec","signature":"func (b *LeaseApplyConfiguration) WithSpec(value *LeaseSpecApplyConfiguration) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/lease.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *LeaseApplyConfiguration) WithSpec(value *LeaseSpecApplyConfiguration) *LeaseApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":243,"to":249}} {"id":100021145,"name":"LeaseSpec","signature":"func LeaseSpec() *LeaseSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/leasespec.go","code":"// LeaseSpecApplyConfiguration constructs an declarative configuration of the LeaseSpec type for use with\n// apply.\nfunc LeaseSpec() *LeaseSpecApplyConfiguration {\n\treturn \u0026LeaseSpecApplyConfiguration{}\n}","line":{"from":35,"to":39}} {"id":100021146,"name":"WithHolderIdentity","signature":"func (b *LeaseSpecApplyConfiguration) WithHolderIdentity(value string) *LeaseSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/leasespec.go","code":"// WithHolderIdentity sets the HolderIdentity field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HolderIdentity field is set to the value of the last call.\nfunc (b *LeaseSpecApplyConfiguration) WithHolderIdentity(value string) *LeaseSpecApplyConfiguration {\n\tb.HolderIdentity = \u0026value\n\treturn b\n}","line":{"from":41,"to":47}} {"id":100021147,"name":"WithLeaseDurationSeconds","signature":"func (b *LeaseSpecApplyConfiguration) WithLeaseDurationSeconds(value int32) *LeaseSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/leasespec.go","code":"// WithLeaseDurationSeconds sets the LeaseDurationSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LeaseDurationSeconds field is set to the value of the last call.\nfunc (b *LeaseSpecApplyConfiguration) WithLeaseDurationSeconds(value int32) *LeaseSpecApplyConfiguration {\n\tb.LeaseDurationSeconds = \u0026value\n\treturn b\n}","line":{"from":49,"to":55}} {"id":100021148,"name":"WithAcquireTime","signature":"func (b *LeaseSpecApplyConfiguration) WithAcquireTime(value v1.MicroTime) *LeaseSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/leasespec.go","code":"// WithAcquireTime sets the AcquireTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AcquireTime field is set to the value of the last call.\nfunc (b *LeaseSpecApplyConfiguration) WithAcquireTime(value v1.MicroTime) *LeaseSpecApplyConfiguration {\n\tb.AcquireTime = \u0026value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100021149,"name":"WithRenewTime","signature":"func (b *LeaseSpecApplyConfiguration) WithRenewTime(value v1.MicroTime) *LeaseSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/leasespec.go","code":"// WithRenewTime sets the RenewTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RenewTime field is set to the value of the last call.\nfunc (b *LeaseSpecApplyConfiguration) WithRenewTime(value v1.MicroTime) *LeaseSpecApplyConfiguration {\n\tb.RenewTime = \u0026value\n\treturn b\n}","line":{"from":65,"to":71}} {"id":100021150,"name":"WithLeaseTransitions","signature":"func (b *LeaseSpecApplyConfiguration) WithLeaseTransitions(value int32) *LeaseSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1/leasespec.go","code":"// WithLeaseTransitions sets the LeaseTransitions field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LeaseTransitions field is set to the value of the last call.\nfunc (b *LeaseSpecApplyConfiguration) WithLeaseTransitions(value int32) *LeaseSpecApplyConfiguration {\n\tb.LeaseTransitions = \u0026value\n\treturn b\n}","line":{"from":73,"to":79}} {"id":100021151,"name":"Lease","signature":"func Lease(name, namespace string) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/lease.go","code":"// Lease constructs an declarative configuration of the Lease type for use with\n// apply.\nfunc Lease(name, namespace string) *LeaseApplyConfiguration {\n\tb := \u0026LeaseApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"Lease\")\n\tb.WithAPIVersion(\"coordination.k8s.io/v1beta1\")\n\treturn b\n}","line":{"from":38,"to":47}} {"id":100021152,"name":"ExtractLease","signature":"func ExtractLease(lease *coordinationv1beta1.Lease, fieldManager string) (*LeaseApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/lease.go","code":"// ExtractLease extracts the applied configuration owned by fieldManager from\n// lease. If no managedFields are found in lease for fieldManager, a\n// LeaseApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// lease must be a unmodified Lease API object that was retrieved from the Kubernetes API.\n// ExtractLease provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractLease(lease *coordinationv1beta1.Lease, fieldManager string) (*LeaseApplyConfiguration, error) {\n\treturn extractLease(lease, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100021153,"name":"ExtractLeaseStatus","signature":"func ExtractLeaseStatus(lease *coordinationv1beta1.Lease, fieldManager string) (*LeaseApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/lease.go","code":"// ExtractLeaseStatus is the same as ExtractLease except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractLeaseStatus(lease *coordinationv1beta1.Lease, fieldManager string) (*LeaseApplyConfiguration, error) {\n\treturn extractLease(lease, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100021154,"name":"extractLease","signature":"func extractLease(lease *coordinationv1beta1.Lease, fieldManager string, subresource string) (*LeaseApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/lease.go","code":"func extractLease(lease *coordinationv1beta1.Lease, fieldManager string, subresource string) (*LeaseApplyConfiguration, error) {\n\tb := \u0026LeaseApplyConfiguration{}\n\terr := managedfields.ExtractInto(lease, internal.Parser().Type(\"io.k8s.api.coordination.v1beta1.Lease\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(lease.Name)\n\tb.WithNamespace(lease.Namespace)\n\n\tb.WithKind(\"Lease\")\n\tb.WithAPIVersion(\"coordination.k8s.io/v1beta1\")\n\treturn b, nil\n}","line":{"from":71,"to":83}} {"id":100021155,"name":"WithKind","signature":"func (b *LeaseApplyConfiguration) WithKind(value string) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/lease.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *LeaseApplyConfiguration) WithKind(value string) *LeaseApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":85,"to":91}} {"id":100021156,"name":"WithAPIVersion","signature":"func (b *LeaseApplyConfiguration) WithAPIVersion(value string) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/lease.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *LeaseApplyConfiguration) WithAPIVersion(value string) *LeaseApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":93,"to":99}} {"id":100021157,"name":"WithName","signature":"func (b *LeaseApplyConfiguration) WithName(value string) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/lease.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *LeaseApplyConfiguration) WithName(value string) *LeaseApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":101,"to":108}} {"id":100021158,"name":"WithGenerateName","signature":"func (b *LeaseApplyConfiguration) WithGenerateName(value string) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/lease.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *LeaseApplyConfiguration) WithGenerateName(value string) *LeaseApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":110,"to":117}} {"id":100021159,"name":"WithNamespace","signature":"func (b *LeaseApplyConfiguration) WithNamespace(value string) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/lease.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *LeaseApplyConfiguration) WithNamespace(value string) *LeaseApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":119,"to":126}} {"id":100021160,"name":"WithUID","signature":"func (b *LeaseApplyConfiguration) WithUID(value types.UID) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/lease.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *LeaseApplyConfiguration) WithUID(value types.UID) *LeaseApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":128,"to":135}} {"id":100021161,"name":"WithResourceVersion","signature":"func (b *LeaseApplyConfiguration) WithResourceVersion(value string) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/lease.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *LeaseApplyConfiguration) WithResourceVersion(value string) *LeaseApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":137,"to":144}} {"id":100021162,"name":"WithGeneration","signature":"func (b *LeaseApplyConfiguration) WithGeneration(value int64) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/lease.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *LeaseApplyConfiguration) WithGeneration(value int64) *LeaseApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":146,"to":153}} {"id":100021163,"name":"WithCreationTimestamp","signature":"func (b *LeaseApplyConfiguration) WithCreationTimestamp(value metav1.Time) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/lease.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *LeaseApplyConfiguration) WithCreationTimestamp(value metav1.Time) *LeaseApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":155,"to":162}} {"id":100021164,"name":"WithDeletionTimestamp","signature":"func (b *LeaseApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/lease.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *LeaseApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *LeaseApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":164,"to":171}} {"id":100021165,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *LeaseApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/lease.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *LeaseApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *LeaseApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":173,"to":180}} {"id":100021166,"name":"WithLabels","signature":"func (b *LeaseApplyConfiguration) WithLabels(entries map[string]string) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/lease.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *LeaseApplyConfiguration) WithLabels(entries map[string]string) *LeaseApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":182,"to":195}} {"id":100021167,"name":"WithAnnotations","signature":"func (b *LeaseApplyConfiguration) WithAnnotations(entries map[string]string) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/lease.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *LeaseApplyConfiguration) WithAnnotations(entries map[string]string) *LeaseApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":197,"to":210}} {"id":100021168,"name":"WithOwnerReferences","signature":"func (b *LeaseApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/lease.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *LeaseApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *LeaseApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":212,"to":224}} {"id":100021169,"name":"WithFinalizers","signature":"func (b *LeaseApplyConfiguration) WithFinalizers(values ...string) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/lease.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *LeaseApplyConfiguration) WithFinalizers(values ...string) *LeaseApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":226,"to":235}} {"id":100021170,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *LeaseApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/lease.go","code":"func (b *LeaseApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":237,"to":241}} {"id":100021171,"name":"WithSpec","signature":"func (b *LeaseApplyConfiguration) WithSpec(value *LeaseSpecApplyConfiguration) *LeaseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/lease.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *LeaseApplyConfiguration) WithSpec(value *LeaseSpecApplyConfiguration) *LeaseApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":243,"to":249}} {"id":100021172,"name":"LeaseSpec","signature":"func LeaseSpec() *LeaseSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/leasespec.go","code":"// LeaseSpecApplyConfiguration constructs an declarative configuration of the LeaseSpec type for use with\n// apply.\nfunc LeaseSpec() *LeaseSpecApplyConfiguration {\n\treturn \u0026LeaseSpecApplyConfiguration{}\n}","line":{"from":35,"to":39}} {"id":100021173,"name":"WithHolderIdentity","signature":"func (b *LeaseSpecApplyConfiguration) WithHolderIdentity(value string) *LeaseSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/leasespec.go","code":"// WithHolderIdentity sets the HolderIdentity field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HolderIdentity field is set to the value of the last call.\nfunc (b *LeaseSpecApplyConfiguration) WithHolderIdentity(value string) *LeaseSpecApplyConfiguration {\n\tb.HolderIdentity = \u0026value\n\treturn b\n}","line":{"from":41,"to":47}} {"id":100021174,"name":"WithLeaseDurationSeconds","signature":"func (b *LeaseSpecApplyConfiguration) WithLeaseDurationSeconds(value int32) *LeaseSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/leasespec.go","code":"// WithLeaseDurationSeconds sets the LeaseDurationSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LeaseDurationSeconds field is set to the value of the last call.\nfunc (b *LeaseSpecApplyConfiguration) WithLeaseDurationSeconds(value int32) *LeaseSpecApplyConfiguration {\n\tb.LeaseDurationSeconds = \u0026value\n\treturn b\n}","line":{"from":49,"to":55}} {"id":100021175,"name":"WithAcquireTime","signature":"func (b *LeaseSpecApplyConfiguration) WithAcquireTime(value v1.MicroTime) *LeaseSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/leasespec.go","code":"// WithAcquireTime sets the AcquireTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AcquireTime field is set to the value of the last call.\nfunc (b *LeaseSpecApplyConfiguration) WithAcquireTime(value v1.MicroTime) *LeaseSpecApplyConfiguration {\n\tb.AcquireTime = \u0026value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100021176,"name":"WithRenewTime","signature":"func (b *LeaseSpecApplyConfiguration) WithRenewTime(value v1.MicroTime) *LeaseSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/leasespec.go","code":"// WithRenewTime sets the RenewTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RenewTime field is set to the value of the last call.\nfunc (b *LeaseSpecApplyConfiguration) WithRenewTime(value v1.MicroTime) *LeaseSpecApplyConfiguration {\n\tb.RenewTime = \u0026value\n\treturn b\n}","line":{"from":65,"to":71}} {"id":100021177,"name":"WithLeaseTransitions","signature":"func (b *LeaseSpecApplyConfiguration) WithLeaseTransitions(value int32) *LeaseSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/coordination/v1beta1/leasespec.go","code":"// WithLeaseTransitions sets the LeaseTransitions field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LeaseTransitions field is set to the value of the last call.\nfunc (b *LeaseSpecApplyConfiguration) WithLeaseTransitions(value int32) *LeaseSpecApplyConfiguration {\n\tb.LeaseTransitions = \u0026value\n\treturn b\n}","line":{"from":73,"to":79}} {"id":100021178,"name":"Affinity","signature":"func Affinity() *AffinityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/affinity.go","code":"// AffinityApplyConfiguration constructs an declarative configuration of the Affinity type for use with\n// apply.\nfunc Affinity() *AffinityApplyConfiguration {\n\treturn \u0026AffinityApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100021179,"name":"WithNodeAffinity","signature":"func (b *AffinityApplyConfiguration) WithNodeAffinity(value *NodeAffinityApplyConfiguration) *AffinityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/affinity.go","code":"// WithNodeAffinity sets the NodeAffinity field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NodeAffinity field is set to the value of the last call.\nfunc (b *AffinityApplyConfiguration) WithNodeAffinity(value *NodeAffinityApplyConfiguration) *AffinityApplyConfiguration {\n\tb.NodeAffinity = value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100021180,"name":"WithPodAffinity","signature":"func (b *AffinityApplyConfiguration) WithPodAffinity(value *PodAffinityApplyConfiguration) *AffinityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/affinity.go","code":"// WithPodAffinity sets the PodAffinity field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PodAffinity field is set to the value of the last call.\nfunc (b *AffinityApplyConfiguration) WithPodAffinity(value *PodAffinityApplyConfiguration) *AffinityApplyConfiguration {\n\tb.PodAffinity = value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100021181,"name":"WithPodAntiAffinity","signature":"func (b *AffinityApplyConfiguration) WithPodAntiAffinity(value *PodAntiAffinityApplyConfiguration) *AffinityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/affinity.go","code":"// WithPodAntiAffinity sets the PodAntiAffinity field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PodAntiAffinity field is set to the value of the last call.\nfunc (b *AffinityApplyConfiguration) WithPodAntiAffinity(value *PodAntiAffinityApplyConfiguration) *AffinityApplyConfiguration {\n\tb.PodAntiAffinity = value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100021182,"name":"AttachedVolume","signature":"func AttachedVolume() *AttachedVolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/attachedvolume.go","code":"// AttachedVolumeApplyConfiguration constructs an declarative configuration of the AttachedVolume type for use with\n// apply.\nfunc AttachedVolume() *AttachedVolumeApplyConfiguration {\n\treturn \u0026AttachedVolumeApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100021183,"name":"WithName","signature":"func (b *AttachedVolumeApplyConfiguration) WithName(value v1.UniqueVolumeName) *AttachedVolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/attachedvolume.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *AttachedVolumeApplyConfiguration) WithName(value v1.UniqueVolumeName) *AttachedVolumeApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100021184,"name":"WithDevicePath","signature":"func (b *AttachedVolumeApplyConfiguration) WithDevicePath(value string) *AttachedVolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/attachedvolume.go","code":"// WithDevicePath sets the DevicePath field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DevicePath field is set to the value of the last call.\nfunc (b *AttachedVolumeApplyConfiguration) WithDevicePath(value string) *AttachedVolumeApplyConfiguration {\n\tb.DevicePath = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100021185,"name":"AWSElasticBlockStoreVolumeSource","signature":"func AWSElasticBlockStoreVolumeSource() *AWSElasticBlockStoreVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/awselasticblockstorevolumesource.go","code":"// AWSElasticBlockStoreVolumeSourceApplyConfiguration constructs an declarative configuration of the AWSElasticBlockStoreVolumeSource type for use with\n// apply.\nfunc AWSElasticBlockStoreVolumeSource() *AWSElasticBlockStoreVolumeSourceApplyConfiguration {\n\treturn \u0026AWSElasticBlockStoreVolumeSourceApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100021186,"name":"WithVolumeID","signature":"func (b *AWSElasticBlockStoreVolumeSourceApplyConfiguration) WithVolumeID(value string) *AWSElasticBlockStoreVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/awselasticblockstorevolumesource.go","code":"// WithVolumeID sets the VolumeID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the VolumeID field is set to the value of the last call.\nfunc (b *AWSElasticBlockStoreVolumeSourceApplyConfiguration) WithVolumeID(value string) *AWSElasticBlockStoreVolumeSourceApplyConfiguration {\n\tb.VolumeID = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100021187,"name":"WithFSType","signature":"func (b *AWSElasticBlockStoreVolumeSourceApplyConfiguration) WithFSType(value string) *AWSElasticBlockStoreVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/awselasticblockstorevolumesource.go","code":"// WithFSType sets the FSType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSType field is set to the value of the last call.\nfunc (b *AWSElasticBlockStoreVolumeSourceApplyConfiguration) WithFSType(value string) *AWSElasticBlockStoreVolumeSourceApplyConfiguration {\n\tb.FSType = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100021188,"name":"WithPartition","signature":"func (b *AWSElasticBlockStoreVolumeSourceApplyConfiguration) WithPartition(value int32) *AWSElasticBlockStoreVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/awselasticblockstorevolumesource.go","code":"// WithPartition sets the Partition field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Partition field is set to the value of the last call.\nfunc (b *AWSElasticBlockStoreVolumeSourceApplyConfiguration) WithPartition(value int32) *AWSElasticBlockStoreVolumeSourceApplyConfiguration {\n\tb.Partition = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100021189,"name":"WithReadOnly","signature":"func (b *AWSElasticBlockStoreVolumeSourceApplyConfiguration) WithReadOnly(value bool) *AWSElasticBlockStoreVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/awselasticblockstorevolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *AWSElasticBlockStoreVolumeSourceApplyConfiguration) WithReadOnly(value bool) *AWSElasticBlockStoreVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100021190,"name":"AzureDiskVolumeSource","signature":"func AzureDiskVolumeSource() *AzureDiskVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/azurediskvolumesource.go","code":"// AzureDiskVolumeSourceApplyConfiguration constructs an declarative configuration of the AzureDiskVolumeSource type for use with\n// apply.\nfunc AzureDiskVolumeSource() *AzureDiskVolumeSourceApplyConfiguration {\n\treturn \u0026AzureDiskVolumeSourceApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100021191,"name":"WithDiskName","signature":"func (b *AzureDiskVolumeSourceApplyConfiguration) WithDiskName(value string) *AzureDiskVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/azurediskvolumesource.go","code":"// WithDiskName sets the DiskName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DiskName field is set to the value of the last call.\nfunc (b *AzureDiskVolumeSourceApplyConfiguration) WithDiskName(value string) *AzureDiskVolumeSourceApplyConfiguration {\n\tb.DiskName = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100021192,"name":"WithDataDiskURI","signature":"func (b *AzureDiskVolumeSourceApplyConfiguration) WithDataDiskURI(value string) *AzureDiskVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/azurediskvolumesource.go","code":"// WithDataDiskURI sets the DataDiskURI field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DataDiskURI field is set to the value of the last call.\nfunc (b *AzureDiskVolumeSourceApplyConfiguration) WithDataDiskURI(value string) *AzureDiskVolumeSourceApplyConfiguration {\n\tb.DataDiskURI = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100021193,"name":"WithCachingMode","signature":"func (b *AzureDiskVolumeSourceApplyConfiguration) WithCachingMode(value v1.AzureDataDiskCachingMode) *AzureDiskVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/azurediskvolumesource.go","code":"// WithCachingMode sets the CachingMode field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CachingMode field is set to the value of the last call.\nfunc (b *AzureDiskVolumeSourceApplyConfiguration) WithCachingMode(value v1.AzureDataDiskCachingMode) *AzureDiskVolumeSourceApplyConfiguration {\n\tb.CachingMode = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100021194,"name":"WithFSType","signature":"func (b *AzureDiskVolumeSourceApplyConfiguration) WithFSType(value string) *AzureDiskVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/azurediskvolumesource.go","code":"// WithFSType sets the FSType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSType field is set to the value of the last call.\nfunc (b *AzureDiskVolumeSourceApplyConfiguration) WithFSType(value string) *AzureDiskVolumeSourceApplyConfiguration {\n\tb.FSType = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100021195,"name":"WithReadOnly","signature":"func (b *AzureDiskVolumeSourceApplyConfiguration) WithReadOnly(value bool) *AzureDiskVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/azurediskvolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *AzureDiskVolumeSourceApplyConfiguration) WithReadOnly(value bool) *AzureDiskVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100021196,"name":"WithKind","signature":"func (b *AzureDiskVolumeSourceApplyConfiguration) WithKind(value v1.AzureDataDiskKind) *AzureDiskVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/azurediskvolumesource.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *AzureDiskVolumeSourceApplyConfiguration) WithKind(value v1.AzureDataDiskKind) *AzureDiskVolumeSourceApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100021197,"name":"AzureFilePersistentVolumeSource","signature":"func AzureFilePersistentVolumeSource() *AzureFilePersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/azurefilepersistentvolumesource.go","code":"// AzureFilePersistentVolumeSourceApplyConfiguration constructs an declarative configuration of the AzureFilePersistentVolumeSource type for use with\n// apply.\nfunc AzureFilePersistentVolumeSource() *AzureFilePersistentVolumeSourceApplyConfiguration {\n\treturn \u0026AzureFilePersistentVolumeSourceApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100021198,"name":"WithSecretName","signature":"func (b *AzureFilePersistentVolumeSourceApplyConfiguration) WithSecretName(value string) *AzureFilePersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/azurefilepersistentvolumesource.go","code":"// WithSecretName sets the SecretName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecretName field is set to the value of the last call.\nfunc (b *AzureFilePersistentVolumeSourceApplyConfiguration) WithSecretName(value string) *AzureFilePersistentVolumeSourceApplyConfiguration {\n\tb.SecretName = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100021199,"name":"WithShareName","signature":"func (b *AzureFilePersistentVolumeSourceApplyConfiguration) WithShareName(value string) *AzureFilePersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/azurefilepersistentvolumesource.go","code":"// WithShareName sets the ShareName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ShareName field is set to the value of the last call.\nfunc (b *AzureFilePersistentVolumeSourceApplyConfiguration) WithShareName(value string) *AzureFilePersistentVolumeSourceApplyConfiguration {\n\tb.ShareName = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100021200,"name":"WithReadOnly","signature":"func (b *AzureFilePersistentVolumeSourceApplyConfiguration) WithReadOnly(value bool) *AzureFilePersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/azurefilepersistentvolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *AzureFilePersistentVolumeSourceApplyConfiguration) WithReadOnly(value bool) *AzureFilePersistentVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100021201,"name":"WithSecretNamespace","signature":"func (b *AzureFilePersistentVolumeSourceApplyConfiguration) WithSecretNamespace(value string) *AzureFilePersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/azurefilepersistentvolumesource.go","code":"// WithSecretNamespace sets the SecretNamespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecretNamespace field is set to the value of the last call.\nfunc (b *AzureFilePersistentVolumeSourceApplyConfiguration) WithSecretNamespace(value string) *AzureFilePersistentVolumeSourceApplyConfiguration {\n\tb.SecretNamespace = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100021202,"name":"AzureFileVolumeSource","signature":"func AzureFileVolumeSource() *AzureFileVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/azurefilevolumesource.go","code":"// AzureFileVolumeSourceApplyConfiguration constructs an declarative configuration of the AzureFileVolumeSource type for use with\n// apply.\nfunc AzureFileVolumeSource() *AzureFileVolumeSourceApplyConfiguration {\n\treturn \u0026AzureFileVolumeSourceApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100021203,"name":"WithSecretName","signature":"func (b *AzureFileVolumeSourceApplyConfiguration) WithSecretName(value string) *AzureFileVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/azurefilevolumesource.go","code":"// WithSecretName sets the SecretName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecretName field is set to the value of the last call.\nfunc (b *AzureFileVolumeSourceApplyConfiguration) WithSecretName(value string) *AzureFileVolumeSourceApplyConfiguration {\n\tb.SecretName = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100021204,"name":"WithShareName","signature":"func (b *AzureFileVolumeSourceApplyConfiguration) WithShareName(value string) *AzureFileVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/azurefilevolumesource.go","code":"// WithShareName sets the ShareName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ShareName field is set to the value of the last call.\nfunc (b *AzureFileVolumeSourceApplyConfiguration) WithShareName(value string) *AzureFileVolumeSourceApplyConfiguration {\n\tb.ShareName = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100021205,"name":"WithReadOnly","signature":"func (b *AzureFileVolumeSourceApplyConfiguration) WithReadOnly(value bool) *AzureFileVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/azurefilevolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *AzureFileVolumeSourceApplyConfiguration) WithReadOnly(value bool) *AzureFileVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100021206,"name":"Capabilities","signature":"func Capabilities() *CapabilitiesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/capabilities.go","code":"// CapabilitiesApplyConfiguration constructs an declarative configuration of the Capabilities type for use with\n// apply.\nfunc Capabilities() *CapabilitiesApplyConfiguration {\n\treturn \u0026CapabilitiesApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100021207,"name":"WithAdd","signature":"func (b *CapabilitiesApplyConfiguration) WithAdd(values ...v1.Capability) *CapabilitiesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/capabilities.go","code":"// WithAdd adds the given value to the Add field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Add field.\nfunc (b *CapabilitiesApplyConfiguration) WithAdd(values ...v1.Capability) *CapabilitiesApplyConfiguration {\n\tfor i := range values {\n\t\tb.Add = append(b.Add, values[i])\n\t}\n\treturn b\n}","line":{"from":38,"to":46}} {"id":100021208,"name":"WithDrop","signature":"func (b *CapabilitiesApplyConfiguration) WithDrop(values ...v1.Capability) *CapabilitiesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/capabilities.go","code":"// WithDrop adds the given value to the Drop field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Drop field.\nfunc (b *CapabilitiesApplyConfiguration) WithDrop(values ...v1.Capability) *CapabilitiesApplyConfiguration {\n\tfor i := range values {\n\t\tb.Drop = append(b.Drop, values[i])\n\t}\n\treturn b\n}","line":{"from":48,"to":56}} {"id":100021209,"name":"CephFSPersistentVolumeSource","signature":"func CephFSPersistentVolumeSource() *CephFSPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/cephfspersistentvolumesource.go","code":"// CephFSPersistentVolumeSourceApplyConfiguration constructs an declarative configuration of the CephFSPersistentVolumeSource type for use with\n// apply.\nfunc CephFSPersistentVolumeSource() *CephFSPersistentVolumeSourceApplyConfiguration {\n\treturn \u0026CephFSPersistentVolumeSourceApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100021210,"name":"WithMonitors","signature":"func (b *CephFSPersistentVolumeSourceApplyConfiguration) WithMonitors(values ...string) *CephFSPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/cephfspersistentvolumesource.go","code":"// WithMonitors adds the given value to the Monitors field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Monitors field.\nfunc (b *CephFSPersistentVolumeSourceApplyConfiguration) WithMonitors(values ...string) *CephFSPersistentVolumeSourceApplyConfiguration {\n\tfor i := range values {\n\t\tb.Monitors = append(b.Monitors, values[i])\n\t}\n\treturn b\n}","line":{"from":38,"to":46}} {"id":100021211,"name":"WithPath","signature":"func (b *CephFSPersistentVolumeSourceApplyConfiguration) WithPath(value string) *CephFSPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/cephfspersistentvolumesource.go","code":"// WithPath sets the Path field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Path field is set to the value of the last call.\nfunc (b *CephFSPersistentVolumeSourceApplyConfiguration) WithPath(value string) *CephFSPersistentVolumeSourceApplyConfiguration {\n\tb.Path = \u0026value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100021212,"name":"WithUser","signature":"func (b *CephFSPersistentVolumeSourceApplyConfiguration) WithUser(value string) *CephFSPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/cephfspersistentvolumesource.go","code":"// WithUser sets the User field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the User field is set to the value of the last call.\nfunc (b *CephFSPersistentVolumeSourceApplyConfiguration) WithUser(value string) *CephFSPersistentVolumeSourceApplyConfiguration {\n\tb.User = \u0026value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100021213,"name":"WithSecretFile","signature":"func (b *CephFSPersistentVolumeSourceApplyConfiguration) WithSecretFile(value string) *CephFSPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/cephfspersistentvolumesource.go","code":"// WithSecretFile sets the SecretFile field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecretFile field is set to the value of the last call.\nfunc (b *CephFSPersistentVolumeSourceApplyConfiguration) WithSecretFile(value string) *CephFSPersistentVolumeSourceApplyConfiguration {\n\tb.SecretFile = \u0026value\n\treturn b\n}","line":{"from":64,"to":70}} {"id":100021214,"name":"WithSecretRef","signature":"func (b *CephFSPersistentVolumeSourceApplyConfiguration) WithSecretRef(value *SecretReferenceApplyConfiguration) *CephFSPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/cephfspersistentvolumesource.go","code":"// WithSecretRef sets the SecretRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecretRef field is set to the value of the last call.\nfunc (b *CephFSPersistentVolumeSourceApplyConfiguration) WithSecretRef(value *SecretReferenceApplyConfiguration) *CephFSPersistentVolumeSourceApplyConfiguration {\n\tb.SecretRef = value\n\treturn b\n}","line":{"from":72,"to":78}} {"id":100021215,"name":"WithReadOnly","signature":"func (b *CephFSPersistentVolumeSourceApplyConfiguration) WithReadOnly(value bool) *CephFSPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/cephfspersistentvolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *CephFSPersistentVolumeSourceApplyConfiguration) WithReadOnly(value bool) *CephFSPersistentVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":80,"to":86}} {"id":100021216,"name":"CephFSVolumeSource","signature":"func CephFSVolumeSource() *CephFSVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/cephfsvolumesource.go","code":"// CephFSVolumeSourceApplyConfiguration constructs an declarative configuration of the CephFSVolumeSource type for use with\n// apply.\nfunc CephFSVolumeSource() *CephFSVolumeSourceApplyConfiguration {\n\treturn \u0026CephFSVolumeSourceApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100021217,"name":"WithMonitors","signature":"func (b *CephFSVolumeSourceApplyConfiguration) WithMonitors(values ...string) *CephFSVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/cephfsvolumesource.go","code":"// WithMonitors adds the given value to the Monitors field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Monitors field.\nfunc (b *CephFSVolumeSourceApplyConfiguration) WithMonitors(values ...string) *CephFSVolumeSourceApplyConfiguration {\n\tfor i := range values {\n\t\tb.Monitors = append(b.Monitors, values[i])\n\t}\n\treturn b\n}","line":{"from":38,"to":46}} {"id":100021218,"name":"WithPath","signature":"func (b *CephFSVolumeSourceApplyConfiguration) WithPath(value string) *CephFSVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/cephfsvolumesource.go","code":"// WithPath sets the Path field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Path field is set to the value of the last call.\nfunc (b *CephFSVolumeSourceApplyConfiguration) WithPath(value string) *CephFSVolumeSourceApplyConfiguration {\n\tb.Path = \u0026value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100021219,"name":"WithUser","signature":"func (b *CephFSVolumeSourceApplyConfiguration) WithUser(value string) *CephFSVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/cephfsvolumesource.go","code":"// WithUser sets the User field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the User field is set to the value of the last call.\nfunc (b *CephFSVolumeSourceApplyConfiguration) WithUser(value string) *CephFSVolumeSourceApplyConfiguration {\n\tb.User = \u0026value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100021220,"name":"WithSecretFile","signature":"func (b *CephFSVolumeSourceApplyConfiguration) WithSecretFile(value string) *CephFSVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/cephfsvolumesource.go","code":"// WithSecretFile sets the SecretFile field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecretFile field is set to the value of the last call.\nfunc (b *CephFSVolumeSourceApplyConfiguration) WithSecretFile(value string) *CephFSVolumeSourceApplyConfiguration {\n\tb.SecretFile = \u0026value\n\treturn b\n}","line":{"from":64,"to":70}} {"id":100021221,"name":"WithSecretRef","signature":"func (b *CephFSVolumeSourceApplyConfiguration) WithSecretRef(value *LocalObjectReferenceApplyConfiguration) *CephFSVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/cephfsvolumesource.go","code":"// WithSecretRef sets the SecretRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecretRef field is set to the value of the last call.\nfunc (b *CephFSVolumeSourceApplyConfiguration) WithSecretRef(value *LocalObjectReferenceApplyConfiguration) *CephFSVolumeSourceApplyConfiguration {\n\tb.SecretRef = value\n\treturn b\n}","line":{"from":72,"to":78}} {"id":100021222,"name":"WithReadOnly","signature":"func (b *CephFSVolumeSourceApplyConfiguration) WithReadOnly(value bool) *CephFSVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/cephfsvolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *CephFSVolumeSourceApplyConfiguration) WithReadOnly(value bool) *CephFSVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":80,"to":86}} {"id":100021223,"name":"CinderPersistentVolumeSource","signature":"func CinderPersistentVolumeSource() *CinderPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/cinderpersistentvolumesource.go","code":"// CinderPersistentVolumeSourceApplyConfiguration constructs an declarative configuration of the CinderPersistentVolumeSource type for use with\n// apply.\nfunc CinderPersistentVolumeSource() *CinderPersistentVolumeSourceApplyConfiguration {\n\treturn \u0026CinderPersistentVolumeSourceApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100021224,"name":"WithVolumeID","signature":"func (b *CinderPersistentVolumeSourceApplyConfiguration) WithVolumeID(value string) *CinderPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/cinderpersistentvolumesource.go","code":"// WithVolumeID sets the VolumeID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the VolumeID field is set to the value of the last call.\nfunc (b *CinderPersistentVolumeSourceApplyConfiguration) WithVolumeID(value string) *CinderPersistentVolumeSourceApplyConfiguration {\n\tb.VolumeID = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100021225,"name":"WithFSType","signature":"func (b *CinderPersistentVolumeSourceApplyConfiguration) WithFSType(value string) *CinderPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/cinderpersistentvolumesource.go","code":"// WithFSType sets the FSType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSType field is set to the value of the last call.\nfunc (b *CinderPersistentVolumeSourceApplyConfiguration) WithFSType(value string) *CinderPersistentVolumeSourceApplyConfiguration {\n\tb.FSType = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100021226,"name":"WithReadOnly","signature":"func (b *CinderPersistentVolumeSourceApplyConfiguration) WithReadOnly(value bool) *CinderPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/cinderpersistentvolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *CinderPersistentVolumeSourceApplyConfiguration) WithReadOnly(value bool) *CinderPersistentVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100021227,"name":"WithSecretRef","signature":"func (b *CinderPersistentVolumeSourceApplyConfiguration) WithSecretRef(value *SecretReferenceApplyConfiguration) *CinderPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/cinderpersistentvolumesource.go","code":"// WithSecretRef sets the SecretRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecretRef field is set to the value of the last call.\nfunc (b *CinderPersistentVolumeSourceApplyConfiguration) WithSecretRef(value *SecretReferenceApplyConfiguration) *CinderPersistentVolumeSourceApplyConfiguration {\n\tb.SecretRef = value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100021228,"name":"CinderVolumeSource","signature":"func CinderVolumeSource() *CinderVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/cindervolumesource.go","code":"// CinderVolumeSourceApplyConfiguration constructs an declarative configuration of the CinderVolumeSource type for use with\n// apply.\nfunc CinderVolumeSource() *CinderVolumeSourceApplyConfiguration {\n\treturn \u0026CinderVolumeSourceApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100021229,"name":"WithVolumeID","signature":"func (b *CinderVolumeSourceApplyConfiguration) WithVolumeID(value string) *CinderVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/cindervolumesource.go","code":"// WithVolumeID sets the VolumeID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the VolumeID field is set to the value of the last call.\nfunc (b *CinderVolumeSourceApplyConfiguration) WithVolumeID(value string) *CinderVolumeSourceApplyConfiguration {\n\tb.VolumeID = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100021230,"name":"WithFSType","signature":"func (b *CinderVolumeSourceApplyConfiguration) WithFSType(value string) *CinderVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/cindervolumesource.go","code":"// WithFSType sets the FSType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSType field is set to the value of the last call.\nfunc (b *CinderVolumeSourceApplyConfiguration) WithFSType(value string) *CinderVolumeSourceApplyConfiguration {\n\tb.FSType = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100021231,"name":"WithReadOnly","signature":"func (b *CinderVolumeSourceApplyConfiguration) WithReadOnly(value bool) *CinderVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/cindervolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *CinderVolumeSourceApplyConfiguration) WithReadOnly(value bool) *CinderVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100021232,"name":"WithSecretRef","signature":"func (b *CinderVolumeSourceApplyConfiguration) WithSecretRef(value *LocalObjectReferenceApplyConfiguration) *CinderVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/cindervolumesource.go","code":"// WithSecretRef sets the SecretRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecretRef field is set to the value of the last call.\nfunc (b *CinderVolumeSourceApplyConfiguration) WithSecretRef(value *LocalObjectReferenceApplyConfiguration) *CinderVolumeSourceApplyConfiguration {\n\tb.SecretRef = value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100021233,"name":"ClaimSource","signature":"func ClaimSource() *ClaimSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/claimsource.go","code":"// ClaimSourceApplyConfiguration constructs an declarative configuration of the ClaimSource type for use with\n// apply.\nfunc ClaimSource() *ClaimSourceApplyConfiguration {\n\treturn \u0026ClaimSourceApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100021234,"name":"WithResourceClaimName","signature":"func (b *ClaimSourceApplyConfiguration) WithResourceClaimName(value string) *ClaimSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/claimsource.go","code":"// WithResourceClaimName sets the ResourceClaimName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceClaimName field is set to the value of the last call.\nfunc (b *ClaimSourceApplyConfiguration) WithResourceClaimName(value string) *ClaimSourceApplyConfiguration {\n\tb.ResourceClaimName = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100021235,"name":"WithResourceClaimTemplateName","signature":"func (b *ClaimSourceApplyConfiguration) WithResourceClaimTemplateName(value string) *ClaimSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/claimsource.go","code":"// WithResourceClaimTemplateName sets the ResourceClaimTemplateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceClaimTemplateName field is set to the value of the last call.\nfunc (b *ClaimSourceApplyConfiguration) WithResourceClaimTemplateName(value string) *ClaimSourceApplyConfiguration {\n\tb.ResourceClaimTemplateName = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100021236,"name":"ClientIPConfig","signature":"func ClientIPConfig() *ClientIPConfigApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/clientipconfig.go","code":"// ClientIPConfigApplyConfiguration constructs an declarative configuration of the ClientIPConfig type for use with\n// apply.\nfunc ClientIPConfig() *ClientIPConfigApplyConfiguration {\n\treturn \u0026ClientIPConfigApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100021237,"name":"WithTimeoutSeconds","signature":"func (b *ClientIPConfigApplyConfiguration) WithTimeoutSeconds(value int32) *ClientIPConfigApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/clientipconfig.go","code":"// WithTimeoutSeconds sets the TimeoutSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TimeoutSeconds field is set to the value of the last call.\nfunc (b *ClientIPConfigApplyConfiguration) WithTimeoutSeconds(value int32) *ClientIPConfigApplyConfiguration {\n\tb.TimeoutSeconds = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100021238,"name":"ComponentCondition","signature":"func ComponentCondition() *ComponentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/componentcondition.go","code":"// ComponentConditionApplyConfiguration constructs an declarative configuration of the ComponentCondition type for use with\n// apply.\nfunc ComponentCondition() *ComponentConditionApplyConfiguration {\n\treturn \u0026ComponentConditionApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100021239,"name":"WithType","signature":"func (b *ComponentConditionApplyConfiguration) WithType(value v1.ComponentConditionType) *ComponentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/componentcondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *ComponentConditionApplyConfiguration) WithType(value v1.ComponentConditionType) *ComponentConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":40,"to":46}} {"id":100021240,"name":"WithStatus","signature":"func (b *ComponentConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *ComponentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/componentcondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *ComponentConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *ComponentConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100021241,"name":"WithMessage","signature":"func (b *ComponentConditionApplyConfiguration) WithMessage(value string) *ComponentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/componentcondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *ComponentConditionApplyConfiguration) WithMessage(value string) *ComponentConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100021242,"name":"WithError","signature":"func (b *ComponentConditionApplyConfiguration) WithError(value string) *ComponentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/componentcondition.go","code":"// WithError sets the Error field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Error field is set to the value of the last call.\nfunc (b *ComponentConditionApplyConfiguration) WithError(value string) *ComponentConditionApplyConfiguration {\n\tb.Error = \u0026value\n\treturn b\n}","line":{"from":64,"to":70}} {"id":100021243,"name":"ComponentStatus","signature":"func ComponentStatus(name string) *ComponentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/componentstatus.go","code":"// ComponentStatus constructs an declarative configuration of the ComponentStatus type for use with\n// apply.\nfunc ComponentStatus(name string) *ComponentStatusApplyConfiguration {\n\tb := \u0026ComponentStatusApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"ComponentStatus\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b\n}","line":{"from":38,"to":46}} {"id":100021244,"name":"ExtractComponentStatus","signature":"func ExtractComponentStatus(componentStatus *apicorev1.ComponentStatus, fieldManager string) (*ComponentStatusApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/componentstatus.go","code":"// ExtractComponentStatus extracts the applied configuration owned by fieldManager from\n// componentStatus. If no managedFields are found in componentStatus for fieldManager, a\n// ComponentStatusApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// componentStatus must be a unmodified ComponentStatus API object that was retrieved from the Kubernetes API.\n// ExtractComponentStatus provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractComponentStatus(componentStatus *apicorev1.ComponentStatus, fieldManager string) (*ComponentStatusApplyConfiguration, error) {\n\treturn extractComponentStatus(componentStatus, fieldManager, \"\")\n}","line":{"from":48,"to":61}} {"id":100021245,"name":"ExtractComponentStatusStatus","signature":"func ExtractComponentStatusStatus(componentStatus *apicorev1.ComponentStatus, fieldManager string) (*ComponentStatusApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/componentstatus.go","code":"// ExtractComponentStatusStatus is the same as ExtractComponentStatus except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractComponentStatusStatus(componentStatus *apicorev1.ComponentStatus, fieldManager string) (*ComponentStatusApplyConfiguration, error) {\n\treturn extractComponentStatus(componentStatus, fieldManager, \"status\")\n}","line":{"from":63,"to":68}} {"id":100021246,"name":"extractComponentStatus","signature":"func extractComponentStatus(componentStatus *apicorev1.ComponentStatus, fieldManager string, subresource string) (*ComponentStatusApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/componentstatus.go","code":"func extractComponentStatus(componentStatus *apicorev1.ComponentStatus, fieldManager string, subresource string) (*ComponentStatusApplyConfiguration, error) {\n\tb := \u0026ComponentStatusApplyConfiguration{}\n\terr := managedfields.ExtractInto(componentStatus, internal.Parser().Type(\"io.k8s.api.core.v1.ComponentStatus\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(componentStatus.Name)\n\n\tb.WithKind(\"ComponentStatus\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b, nil\n}","line":{"from":70,"to":81}} {"id":100021247,"name":"WithKind","signature":"func (b *ComponentStatusApplyConfiguration) WithKind(value string) *ComponentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/componentstatus.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ComponentStatusApplyConfiguration) WithKind(value string) *ComponentStatusApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100021248,"name":"WithAPIVersion","signature":"func (b *ComponentStatusApplyConfiguration) WithAPIVersion(value string) *ComponentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/componentstatus.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ComponentStatusApplyConfiguration) WithAPIVersion(value string) *ComponentStatusApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":91,"to":97}} {"id":100021249,"name":"WithName","signature":"func (b *ComponentStatusApplyConfiguration) WithName(value string) *ComponentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/componentstatus.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ComponentStatusApplyConfiguration) WithName(value string) *ComponentStatusApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":99,"to":106}} {"id":100021250,"name":"WithGenerateName","signature":"func (b *ComponentStatusApplyConfiguration) WithGenerateName(value string) *ComponentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/componentstatus.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ComponentStatusApplyConfiguration) WithGenerateName(value string) *ComponentStatusApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":108,"to":115}} {"id":100021251,"name":"WithNamespace","signature":"func (b *ComponentStatusApplyConfiguration) WithNamespace(value string) *ComponentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/componentstatus.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ComponentStatusApplyConfiguration) WithNamespace(value string) *ComponentStatusApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":117,"to":124}} {"id":100021252,"name":"WithUID","signature":"func (b *ComponentStatusApplyConfiguration) WithUID(value types.UID) *ComponentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/componentstatus.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ComponentStatusApplyConfiguration) WithUID(value types.UID) *ComponentStatusApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":126,"to":133}} {"id":100021253,"name":"WithResourceVersion","signature":"func (b *ComponentStatusApplyConfiguration) WithResourceVersion(value string) *ComponentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/componentstatus.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ComponentStatusApplyConfiguration) WithResourceVersion(value string) *ComponentStatusApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":135,"to":142}} {"id":100021254,"name":"WithGeneration","signature":"func (b *ComponentStatusApplyConfiguration) WithGeneration(value int64) *ComponentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/componentstatus.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ComponentStatusApplyConfiguration) WithGeneration(value int64) *ComponentStatusApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":144,"to":151}} {"id":100021255,"name":"WithCreationTimestamp","signature":"func (b *ComponentStatusApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ComponentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/componentstatus.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ComponentStatusApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ComponentStatusApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":153,"to":160}} {"id":100021256,"name":"WithDeletionTimestamp","signature":"func (b *ComponentStatusApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ComponentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/componentstatus.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ComponentStatusApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ComponentStatusApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":162,"to":169}} {"id":100021257,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ComponentStatusApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ComponentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/componentstatus.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ComponentStatusApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ComponentStatusApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":171,"to":178}} {"id":100021258,"name":"WithLabels","signature":"func (b *ComponentStatusApplyConfiguration) WithLabels(entries map[string]string) *ComponentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/componentstatus.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ComponentStatusApplyConfiguration) WithLabels(entries map[string]string) *ComponentStatusApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":180,"to":193}} {"id":100021259,"name":"WithAnnotations","signature":"func (b *ComponentStatusApplyConfiguration) WithAnnotations(entries map[string]string) *ComponentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/componentstatus.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ComponentStatusApplyConfiguration) WithAnnotations(entries map[string]string) *ComponentStatusApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":195,"to":208}} {"id":100021260,"name":"WithOwnerReferences","signature":"func (b *ComponentStatusApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ComponentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/componentstatus.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ComponentStatusApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ComponentStatusApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":210,"to":222}} {"id":100021261,"name":"WithFinalizers","signature":"func (b *ComponentStatusApplyConfiguration) WithFinalizers(values ...string) *ComponentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/componentstatus.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ComponentStatusApplyConfiguration) WithFinalizers(values ...string) *ComponentStatusApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":224,"to":233}} {"id":100021262,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ComponentStatusApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/componentstatus.go","code":"func (b *ComponentStatusApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":235,"to":239}} {"id":100021263,"name":"WithConditions","signature":"func (b *ComponentStatusApplyConfiguration) WithConditions(values ...*ComponentConditionApplyConfiguration) *ComponentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/componentstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *ComponentStatusApplyConfiguration) WithConditions(values ...*ComponentConditionApplyConfiguration) *ComponentStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":241,"to":252}} {"id":100021264,"name":"ConfigMap","signature":"func ConfigMap(name, namespace string) *ConfigMapApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmap.go","code":"// ConfigMap constructs an declarative configuration of the ConfigMap type for use with\n// apply.\nfunc ConfigMap(name, namespace string) *ConfigMapApplyConfiguration {\n\tb := \u0026ConfigMapApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"ConfigMap\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b\n}","line":{"from":40,"to":49}} {"id":100021265,"name":"ExtractConfigMap","signature":"func ExtractConfigMap(configMap *corev1.ConfigMap, fieldManager string) (*ConfigMapApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmap.go","code":"// ExtractConfigMap extracts the applied configuration owned by fieldManager from\n// configMap. If no managedFields are found in configMap for fieldManager, a\n// ConfigMapApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// configMap must be a unmodified ConfigMap API object that was retrieved from the Kubernetes API.\n// ExtractConfigMap provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractConfigMap(configMap *corev1.ConfigMap, fieldManager string) (*ConfigMapApplyConfiguration, error) {\n\treturn extractConfigMap(configMap, fieldManager, \"\")\n}","line":{"from":51,"to":64}} {"id":100021266,"name":"ExtractConfigMapStatus","signature":"func ExtractConfigMapStatus(configMap *corev1.ConfigMap, fieldManager string) (*ConfigMapApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmap.go","code":"// ExtractConfigMapStatus is the same as ExtractConfigMap except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractConfigMapStatus(configMap *corev1.ConfigMap, fieldManager string) (*ConfigMapApplyConfiguration, error) {\n\treturn extractConfigMap(configMap, fieldManager, \"status\")\n}","line":{"from":66,"to":71}} {"id":100021267,"name":"extractConfigMap","signature":"func extractConfigMap(configMap *corev1.ConfigMap, fieldManager string, subresource string) (*ConfigMapApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmap.go","code":"func extractConfigMap(configMap *corev1.ConfigMap, fieldManager string, subresource string) (*ConfigMapApplyConfiguration, error) {\n\tb := \u0026ConfigMapApplyConfiguration{}\n\terr := managedfields.ExtractInto(configMap, internal.Parser().Type(\"io.k8s.api.core.v1.ConfigMap\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(configMap.Name)\n\tb.WithNamespace(configMap.Namespace)\n\n\tb.WithKind(\"ConfigMap\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b, nil\n}","line":{"from":73,"to":85}} {"id":100021268,"name":"WithKind","signature":"func (b *ConfigMapApplyConfiguration) WithKind(value string) *ConfigMapApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmap.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ConfigMapApplyConfiguration) WithKind(value string) *ConfigMapApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":87,"to":93}} {"id":100021269,"name":"WithAPIVersion","signature":"func (b *ConfigMapApplyConfiguration) WithAPIVersion(value string) *ConfigMapApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmap.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ConfigMapApplyConfiguration) WithAPIVersion(value string) *ConfigMapApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":95,"to":101}} {"id":100021270,"name":"WithName","signature":"func (b *ConfigMapApplyConfiguration) WithName(value string) *ConfigMapApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmap.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ConfigMapApplyConfiguration) WithName(value string) *ConfigMapApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":103,"to":110}} {"id":100021271,"name":"WithGenerateName","signature":"func (b *ConfigMapApplyConfiguration) WithGenerateName(value string) *ConfigMapApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmap.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ConfigMapApplyConfiguration) WithGenerateName(value string) *ConfigMapApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":112,"to":119}} {"id":100021272,"name":"WithNamespace","signature":"func (b *ConfigMapApplyConfiguration) WithNamespace(value string) *ConfigMapApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmap.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ConfigMapApplyConfiguration) WithNamespace(value string) *ConfigMapApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":121,"to":128}} {"id":100021273,"name":"WithUID","signature":"func (b *ConfigMapApplyConfiguration) WithUID(value types.UID) *ConfigMapApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmap.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ConfigMapApplyConfiguration) WithUID(value types.UID) *ConfigMapApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":130,"to":137}} {"id":100021274,"name":"WithResourceVersion","signature":"func (b *ConfigMapApplyConfiguration) WithResourceVersion(value string) *ConfigMapApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmap.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ConfigMapApplyConfiguration) WithResourceVersion(value string) *ConfigMapApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":139,"to":146}} {"id":100021275,"name":"WithGeneration","signature":"func (b *ConfigMapApplyConfiguration) WithGeneration(value int64) *ConfigMapApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmap.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ConfigMapApplyConfiguration) WithGeneration(value int64) *ConfigMapApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":148,"to":155}} {"id":100021276,"name":"WithCreationTimestamp","signature":"func (b *ConfigMapApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ConfigMapApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmap.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ConfigMapApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ConfigMapApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":157,"to":164}} {"id":100021277,"name":"WithDeletionTimestamp","signature":"func (b *ConfigMapApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ConfigMapApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmap.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ConfigMapApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ConfigMapApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":166,"to":173}} {"id":100021278,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ConfigMapApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ConfigMapApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmap.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ConfigMapApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ConfigMapApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":175,"to":182}} {"id":100021279,"name":"WithLabels","signature":"func (b *ConfigMapApplyConfiguration) WithLabels(entries map[string]string) *ConfigMapApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmap.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ConfigMapApplyConfiguration) WithLabels(entries map[string]string) *ConfigMapApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":184,"to":197}} {"id":100021280,"name":"WithAnnotations","signature":"func (b *ConfigMapApplyConfiguration) WithAnnotations(entries map[string]string) *ConfigMapApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmap.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ConfigMapApplyConfiguration) WithAnnotations(entries map[string]string) *ConfigMapApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":199,"to":212}} {"id":100021281,"name":"WithOwnerReferences","signature":"func (b *ConfigMapApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ConfigMapApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmap.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ConfigMapApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ConfigMapApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":214,"to":226}} {"id":100021282,"name":"WithFinalizers","signature":"func (b *ConfigMapApplyConfiguration) WithFinalizers(values ...string) *ConfigMapApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmap.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ConfigMapApplyConfiguration) WithFinalizers(values ...string) *ConfigMapApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":228,"to":237}} {"id":100021283,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ConfigMapApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmap.go","code":"func (b *ConfigMapApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":239,"to":243}} {"id":100021284,"name":"WithImmutable","signature":"func (b *ConfigMapApplyConfiguration) WithImmutable(value bool) *ConfigMapApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmap.go","code":"// WithImmutable sets the Immutable field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Immutable field is set to the value of the last call.\nfunc (b *ConfigMapApplyConfiguration) WithImmutable(value bool) *ConfigMapApplyConfiguration {\n\tb.Immutable = \u0026value\n\treturn b\n}","line":{"from":245,"to":251}} {"id":100021285,"name":"WithData","signature":"func (b *ConfigMapApplyConfiguration) WithData(entries map[string]string) *ConfigMapApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmap.go","code":"// WithData puts the entries into the Data field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Data field,\n// overwriting an existing map entries in Data field with the same key.\nfunc (b *ConfigMapApplyConfiguration) WithData(entries map[string]string) *ConfigMapApplyConfiguration {\n\tif b.Data == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Data = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Data[k] = v\n\t}\n\treturn b\n}","line":{"from":253,"to":265}} {"id":100021286,"name":"WithBinaryData","signature":"func (b *ConfigMapApplyConfiguration) WithBinaryData(entries map[string][]byte) *ConfigMapApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmap.go","code":"// WithBinaryData puts the entries into the BinaryData field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the BinaryData field,\n// overwriting an existing map entries in BinaryData field with the same key.\nfunc (b *ConfigMapApplyConfiguration) WithBinaryData(entries map[string][]byte) *ConfigMapApplyConfiguration {\n\tif b.BinaryData == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.BinaryData = make(map[string][]byte, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.BinaryData[k] = v\n\t}\n\treturn b\n}","line":{"from":267,"to":279}} {"id":100021287,"name":"ConfigMapEnvSource","signature":"func ConfigMapEnvSource() *ConfigMapEnvSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmapenvsource.go","code":"// ConfigMapEnvSourceApplyConfiguration constructs an declarative configuration of the ConfigMapEnvSource type for use with\n// apply.\nfunc ConfigMapEnvSource() *ConfigMapEnvSourceApplyConfiguration {\n\treturn \u0026ConfigMapEnvSourceApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100021288,"name":"WithName","signature":"func (b *ConfigMapEnvSourceApplyConfiguration) WithName(value string) *ConfigMapEnvSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmapenvsource.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ConfigMapEnvSourceApplyConfiguration) WithName(value string) *ConfigMapEnvSourceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100021289,"name":"WithOptional","signature":"func (b *ConfigMapEnvSourceApplyConfiguration) WithOptional(value bool) *ConfigMapEnvSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmapenvsource.go","code":"// WithOptional sets the Optional field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Optional field is set to the value of the last call.\nfunc (b *ConfigMapEnvSourceApplyConfiguration) WithOptional(value bool) *ConfigMapEnvSourceApplyConfiguration {\n\tb.Optional = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100021290,"name":"ConfigMapKeySelector","signature":"func ConfigMapKeySelector() *ConfigMapKeySelectorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmapkeyselector.go","code":"// ConfigMapKeySelectorApplyConfiguration constructs an declarative configuration of the ConfigMapKeySelector type for use with\n// apply.\nfunc ConfigMapKeySelector() *ConfigMapKeySelectorApplyConfiguration {\n\treturn \u0026ConfigMapKeySelectorApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100021291,"name":"WithName","signature":"func (b *ConfigMapKeySelectorApplyConfiguration) WithName(value string) *ConfigMapKeySelectorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmapkeyselector.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ConfigMapKeySelectorApplyConfiguration) WithName(value string) *ConfigMapKeySelectorApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100021292,"name":"WithKey","signature":"func (b *ConfigMapKeySelectorApplyConfiguration) WithKey(value string) *ConfigMapKeySelectorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmapkeyselector.go","code":"// WithKey sets the Key field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Key field is set to the value of the last call.\nfunc (b *ConfigMapKeySelectorApplyConfiguration) WithKey(value string) *ConfigMapKeySelectorApplyConfiguration {\n\tb.Key = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100021293,"name":"WithOptional","signature":"func (b *ConfigMapKeySelectorApplyConfiguration) WithOptional(value bool) *ConfigMapKeySelectorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmapkeyselector.go","code":"// WithOptional sets the Optional field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Optional field is set to the value of the last call.\nfunc (b *ConfigMapKeySelectorApplyConfiguration) WithOptional(value bool) *ConfigMapKeySelectorApplyConfiguration {\n\tb.Optional = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100021294,"name":"ConfigMapNodeConfigSource","signature":"func ConfigMapNodeConfigSource() *ConfigMapNodeConfigSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmapnodeconfigsource.go","code":"// ConfigMapNodeConfigSourceApplyConfiguration constructs an declarative configuration of the ConfigMapNodeConfigSource type for use with\n// apply.\nfunc ConfigMapNodeConfigSource() *ConfigMapNodeConfigSourceApplyConfiguration {\n\treturn \u0026ConfigMapNodeConfigSourceApplyConfiguration{}\n}","line":{"from":35,"to":39}} {"id":100021295,"name":"WithNamespace","signature":"func (b *ConfigMapNodeConfigSourceApplyConfiguration) WithNamespace(value string) *ConfigMapNodeConfigSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmapnodeconfigsource.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ConfigMapNodeConfigSourceApplyConfiguration) WithNamespace(value string) *ConfigMapNodeConfigSourceApplyConfiguration {\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":41,"to":47}} {"id":100021296,"name":"WithName","signature":"func (b *ConfigMapNodeConfigSourceApplyConfiguration) WithName(value string) *ConfigMapNodeConfigSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmapnodeconfigsource.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ConfigMapNodeConfigSourceApplyConfiguration) WithName(value string) *ConfigMapNodeConfigSourceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":49,"to":55}} {"id":100021297,"name":"WithUID","signature":"func (b *ConfigMapNodeConfigSourceApplyConfiguration) WithUID(value types.UID) *ConfigMapNodeConfigSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmapnodeconfigsource.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ConfigMapNodeConfigSourceApplyConfiguration) WithUID(value types.UID) *ConfigMapNodeConfigSourceApplyConfiguration {\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100021298,"name":"WithResourceVersion","signature":"func (b *ConfigMapNodeConfigSourceApplyConfiguration) WithResourceVersion(value string) *ConfigMapNodeConfigSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmapnodeconfigsource.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ConfigMapNodeConfigSourceApplyConfiguration) WithResourceVersion(value string) *ConfigMapNodeConfigSourceApplyConfiguration {\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":65,"to":71}} {"id":100021299,"name":"WithKubeletConfigKey","signature":"func (b *ConfigMapNodeConfigSourceApplyConfiguration) WithKubeletConfigKey(value string) *ConfigMapNodeConfigSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmapnodeconfigsource.go","code":"// WithKubeletConfigKey sets the KubeletConfigKey field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the KubeletConfigKey field is set to the value of the last call.\nfunc (b *ConfigMapNodeConfigSourceApplyConfiguration) WithKubeletConfigKey(value string) *ConfigMapNodeConfigSourceApplyConfiguration {\n\tb.KubeletConfigKey = \u0026value\n\treturn b\n}","line":{"from":73,"to":79}} {"id":100021300,"name":"ConfigMapProjection","signature":"func ConfigMapProjection() *ConfigMapProjectionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmapprojection.go","code":"// ConfigMapProjectionApplyConfiguration constructs an declarative configuration of the ConfigMapProjection type for use with\n// apply.\nfunc ConfigMapProjection() *ConfigMapProjectionApplyConfiguration {\n\treturn \u0026ConfigMapProjectionApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100021301,"name":"WithName","signature":"func (b *ConfigMapProjectionApplyConfiguration) WithName(value string) *ConfigMapProjectionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmapprojection.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ConfigMapProjectionApplyConfiguration) WithName(value string) *ConfigMapProjectionApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100021302,"name":"WithItems","signature":"func (b *ConfigMapProjectionApplyConfiguration) WithItems(values ...*KeyToPathApplyConfiguration) *ConfigMapProjectionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmapprojection.go","code":"// WithItems adds the given value to the Items field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Items field.\nfunc (b *ConfigMapProjectionApplyConfiguration) WithItems(values ...*KeyToPathApplyConfiguration) *ConfigMapProjectionApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithItems\")\n\t\t}\n\t\tb.Items = append(b.Items, *values[i])\n\t}\n\treturn b\n}","line":{"from":43,"to":54}} {"id":100021303,"name":"WithOptional","signature":"func (b *ConfigMapProjectionApplyConfiguration) WithOptional(value bool) *ConfigMapProjectionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmapprojection.go","code":"// WithOptional sets the Optional field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Optional field is set to the value of the last call.\nfunc (b *ConfigMapProjectionApplyConfiguration) WithOptional(value bool) *ConfigMapProjectionApplyConfiguration {\n\tb.Optional = \u0026value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100021304,"name":"ConfigMapVolumeSource","signature":"func ConfigMapVolumeSource() *ConfigMapVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmapvolumesource.go","code":"// ConfigMapVolumeSourceApplyConfiguration constructs an declarative configuration of the ConfigMapVolumeSource type for use with\n// apply.\nfunc ConfigMapVolumeSource() *ConfigMapVolumeSourceApplyConfiguration {\n\treturn \u0026ConfigMapVolumeSourceApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100021305,"name":"WithName","signature":"func (b *ConfigMapVolumeSourceApplyConfiguration) WithName(value string) *ConfigMapVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmapvolumesource.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ConfigMapVolumeSourceApplyConfiguration) WithName(value string) *ConfigMapVolumeSourceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100021306,"name":"WithItems","signature":"func (b *ConfigMapVolumeSourceApplyConfiguration) WithItems(values ...*KeyToPathApplyConfiguration) *ConfigMapVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmapvolumesource.go","code":"// WithItems adds the given value to the Items field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Items field.\nfunc (b *ConfigMapVolumeSourceApplyConfiguration) WithItems(values ...*KeyToPathApplyConfiguration) *ConfigMapVolumeSourceApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithItems\")\n\t\t}\n\t\tb.Items = append(b.Items, *values[i])\n\t}\n\treturn b\n}","line":{"from":44,"to":55}} {"id":100021307,"name":"WithDefaultMode","signature":"func (b *ConfigMapVolumeSourceApplyConfiguration) WithDefaultMode(value int32) *ConfigMapVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmapvolumesource.go","code":"// WithDefaultMode sets the DefaultMode field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DefaultMode field is set to the value of the last call.\nfunc (b *ConfigMapVolumeSourceApplyConfiguration) WithDefaultMode(value int32) *ConfigMapVolumeSourceApplyConfiguration {\n\tb.DefaultMode = \u0026value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100021308,"name":"WithOptional","signature":"func (b *ConfigMapVolumeSourceApplyConfiguration) WithOptional(value bool) *ConfigMapVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/configmapvolumesource.go","code":"// WithOptional sets the Optional field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Optional field is set to the value of the last call.\nfunc (b *ConfigMapVolumeSourceApplyConfiguration) WithOptional(value bool) *ConfigMapVolumeSourceApplyConfiguration {\n\tb.Optional = \u0026value\n\treturn b\n}","line":{"from":65,"to":71}} {"id":100021309,"name":"Container","signature":"func Container() *ContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/container.go","code":"// ContainerApplyConfiguration constructs an declarative configuration of the Container type for use with\n// apply.\nfunc Container() *ContainerApplyConfiguration {\n\treturn \u0026ContainerApplyConfiguration{}\n}","line":{"from":53,"to":57}} {"id":100021310,"name":"WithName","signature":"func (b *ContainerApplyConfiguration) WithName(value string) *ContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/container.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ContainerApplyConfiguration) WithName(value string) *ContainerApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":59,"to":65}} {"id":100021311,"name":"WithImage","signature":"func (b *ContainerApplyConfiguration) WithImage(value string) *ContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/container.go","code":"// WithImage sets the Image field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Image field is set to the value of the last call.\nfunc (b *ContainerApplyConfiguration) WithImage(value string) *ContainerApplyConfiguration {\n\tb.Image = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100021312,"name":"WithCommand","signature":"func (b *ContainerApplyConfiguration) WithCommand(values ...string) *ContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/container.go","code":"// WithCommand adds the given value to the Command field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Command field.\nfunc (b *ContainerApplyConfiguration) WithCommand(values ...string) *ContainerApplyConfiguration {\n\tfor i := range values {\n\t\tb.Command = append(b.Command, values[i])\n\t}\n\treturn b\n}","line":{"from":75,"to":83}} {"id":100021313,"name":"WithArgs","signature":"func (b *ContainerApplyConfiguration) WithArgs(values ...string) *ContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/container.go","code":"// WithArgs adds the given value to the Args field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Args field.\nfunc (b *ContainerApplyConfiguration) WithArgs(values ...string) *ContainerApplyConfiguration {\n\tfor i := range values {\n\t\tb.Args = append(b.Args, values[i])\n\t}\n\treturn b\n}","line":{"from":85,"to":93}} {"id":100021314,"name":"WithWorkingDir","signature":"func (b *ContainerApplyConfiguration) WithWorkingDir(value string) *ContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/container.go","code":"// WithWorkingDir sets the WorkingDir field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the WorkingDir field is set to the value of the last call.\nfunc (b *ContainerApplyConfiguration) WithWorkingDir(value string) *ContainerApplyConfiguration {\n\tb.WorkingDir = \u0026value\n\treturn b\n}","line":{"from":95,"to":101}} {"id":100021315,"name":"WithPorts","signature":"func (b *ContainerApplyConfiguration) WithPorts(values ...*ContainerPortApplyConfiguration) *ContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/container.go","code":"// WithPorts adds the given value to the Ports field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Ports field.\nfunc (b *ContainerApplyConfiguration) WithPorts(values ...*ContainerPortApplyConfiguration) *ContainerApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPorts\")\n\t\t}\n\t\tb.Ports = append(b.Ports, *values[i])\n\t}\n\treturn b\n}","line":{"from":103,"to":114}} {"id":100021316,"name":"WithEnvFrom","signature":"func (b *ContainerApplyConfiguration) WithEnvFrom(values ...*EnvFromSourceApplyConfiguration) *ContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/container.go","code":"// WithEnvFrom adds the given value to the EnvFrom field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the EnvFrom field.\nfunc (b *ContainerApplyConfiguration) WithEnvFrom(values ...*EnvFromSourceApplyConfiguration) *ContainerApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithEnvFrom\")\n\t\t}\n\t\tb.EnvFrom = append(b.EnvFrom, *values[i])\n\t}\n\treturn b\n}","line":{"from":116,"to":127}} {"id":100021317,"name":"WithEnv","signature":"func (b *ContainerApplyConfiguration) WithEnv(values ...*EnvVarApplyConfiguration) *ContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/container.go","code":"// WithEnv adds the given value to the Env field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Env field.\nfunc (b *ContainerApplyConfiguration) WithEnv(values ...*EnvVarApplyConfiguration) *ContainerApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithEnv\")\n\t\t}\n\t\tb.Env = append(b.Env, *values[i])\n\t}\n\treturn b\n}","line":{"from":129,"to":140}} {"id":100021318,"name":"WithResources","signature":"func (b *ContainerApplyConfiguration) WithResources(value *ResourceRequirementsApplyConfiguration) *ContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/container.go","code":"// WithResources sets the Resources field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Resources field is set to the value of the last call.\nfunc (b *ContainerApplyConfiguration) WithResources(value *ResourceRequirementsApplyConfiguration) *ContainerApplyConfiguration {\n\tb.Resources = value\n\treturn b\n}","line":{"from":142,"to":148}} {"id":100021319,"name":"WithResizePolicy","signature":"func (b *ContainerApplyConfiguration) WithResizePolicy(values ...*ContainerResizePolicyApplyConfiguration) *ContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/container.go","code":"// WithResizePolicy adds the given value to the ResizePolicy field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ResizePolicy field.\nfunc (b *ContainerApplyConfiguration) WithResizePolicy(values ...*ContainerResizePolicyApplyConfiguration) *ContainerApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithResizePolicy\")\n\t\t}\n\t\tb.ResizePolicy = append(b.ResizePolicy, *values[i])\n\t}\n\treturn b\n}","line":{"from":150,"to":161}} {"id":100021320,"name":"WithVolumeMounts","signature":"func (b *ContainerApplyConfiguration) WithVolumeMounts(values ...*VolumeMountApplyConfiguration) *ContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/container.go","code":"// WithVolumeMounts adds the given value to the VolumeMounts field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the VolumeMounts field.\nfunc (b *ContainerApplyConfiguration) WithVolumeMounts(values ...*VolumeMountApplyConfiguration) *ContainerApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithVolumeMounts\")\n\t\t}\n\t\tb.VolumeMounts = append(b.VolumeMounts, *values[i])\n\t}\n\treturn b\n}","line":{"from":163,"to":174}} {"id":100021321,"name":"WithVolumeDevices","signature":"func (b *ContainerApplyConfiguration) WithVolumeDevices(values ...*VolumeDeviceApplyConfiguration) *ContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/container.go","code":"// WithVolumeDevices adds the given value to the VolumeDevices field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the VolumeDevices field.\nfunc (b *ContainerApplyConfiguration) WithVolumeDevices(values ...*VolumeDeviceApplyConfiguration) *ContainerApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithVolumeDevices\")\n\t\t}\n\t\tb.VolumeDevices = append(b.VolumeDevices, *values[i])\n\t}\n\treturn b\n}","line":{"from":176,"to":187}} {"id":100021322,"name":"WithLivenessProbe","signature":"func (b *ContainerApplyConfiguration) WithLivenessProbe(value *ProbeApplyConfiguration) *ContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/container.go","code":"// WithLivenessProbe sets the LivenessProbe field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LivenessProbe field is set to the value of the last call.\nfunc (b *ContainerApplyConfiguration) WithLivenessProbe(value *ProbeApplyConfiguration) *ContainerApplyConfiguration {\n\tb.LivenessProbe = value\n\treturn b\n}","line":{"from":189,"to":195}} {"id":100021323,"name":"WithReadinessProbe","signature":"func (b *ContainerApplyConfiguration) WithReadinessProbe(value *ProbeApplyConfiguration) *ContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/container.go","code":"// WithReadinessProbe sets the ReadinessProbe field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadinessProbe field is set to the value of the last call.\nfunc (b *ContainerApplyConfiguration) WithReadinessProbe(value *ProbeApplyConfiguration) *ContainerApplyConfiguration {\n\tb.ReadinessProbe = value\n\treturn b\n}","line":{"from":197,"to":203}} {"id":100021324,"name":"WithStartupProbe","signature":"func (b *ContainerApplyConfiguration) WithStartupProbe(value *ProbeApplyConfiguration) *ContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/container.go","code":"// WithStartupProbe sets the StartupProbe field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StartupProbe field is set to the value of the last call.\nfunc (b *ContainerApplyConfiguration) WithStartupProbe(value *ProbeApplyConfiguration) *ContainerApplyConfiguration {\n\tb.StartupProbe = value\n\treturn b\n}","line":{"from":205,"to":211}} {"id":100021325,"name":"WithLifecycle","signature":"func (b *ContainerApplyConfiguration) WithLifecycle(value *LifecycleApplyConfiguration) *ContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/container.go","code":"// WithLifecycle sets the Lifecycle field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Lifecycle field is set to the value of the last call.\nfunc (b *ContainerApplyConfiguration) WithLifecycle(value *LifecycleApplyConfiguration) *ContainerApplyConfiguration {\n\tb.Lifecycle = value\n\treturn b\n}","line":{"from":213,"to":219}} {"id":100021326,"name":"WithTerminationMessagePath","signature":"func (b *ContainerApplyConfiguration) WithTerminationMessagePath(value string) *ContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/container.go","code":"// WithTerminationMessagePath sets the TerminationMessagePath field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TerminationMessagePath field is set to the value of the last call.\nfunc (b *ContainerApplyConfiguration) WithTerminationMessagePath(value string) *ContainerApplyConfiguration {\n\tb.TerminationMessagePath = \u0026value\n\treturn b\n}","line":{"from":221,"to":227}} {"id":100021327,"name":"WithTerminationMessagePolicy","signature":"func (b *ContainerApplyConfiguration) WithTerminationMessagePolicy(value corev1.TerminationMessagePolicy) *ContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/container.go","code":"// WithTerminationMessagePolicy sets the TerminationMessagePolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TerminationMessagePolicy field is set to the value of the last call.\nfunc (b *ContainerApplyConfiguration) WithTerminationMessagePolicy(value corev1.TerminationMessagePolicy) *ContainerApplyConfiguration {\n\tb.TerminationMessagePolicy = \u0026value\n\treturn b\n}","line":{"from":229,"to":235}} {"id":100021328,"name":"WithImagePullPolicy","signature":"func (b *ContainerApplyConfiguration) WithImagePullPolicy(value corev1.PullPolicy) *ContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/container.go","code":"// WithImagePullPolicy sets the ImagePullPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ImagePullPolicy field is set to the value of the last call.\nfunc (b *ContainerApplyConfiguration) WithImagePullPolicy(value corev1.PullPolicy) *ContainerApplyConfiguration {\n\tb.ImagePullPolicy = \u0026value\n\treturn b\n}","line":{"from":237,"to":243}} {"id":100021329,"name":"WithSecurityContext","signature":"func (b *ContainerApplyConfiguration) WithSecurityContext(value *SecurityContextApplyConfiguration) *ContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/container.go","code":"// WithSecurityContext sets the SecurityContext field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecurityContext field is set to the value of the last call.\nfunc (b *ContainerApplyConfiguration) WithSecurityContext(value *SecurityContextApplyConfiguration) *ContainerApplyConfiguration {\n\tb.SecurityContext = value\n\treturn b\n}","line":{"from":245,"to":251}} {"id":100021330,"name":"WithStdin","signature":"func (b *ContainerApplyConfiguration) WithStdin(value bool) *ContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/container.go","code":"// WithStdin sets the Stdin field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Stdin field is set to the value of the last call.\nfunc (b *ContainerApplyConfiguration) WithStdin(value bool) *ContainerApplyConfiguration {\n\tb.Stdin = \u0026value\n\treturn b\n}","line":{"from":253,"to":259}} {"id":100021331,"name":"WithStdinOnce","signature":"func (b *ContainerApplyConfiguration) WithStdinOnce(value bool) *ContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/container.go","code":"// WithStdinOnce sets the StdinOnce field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StdinOnce field is set to the value of the last call.\nfunc (b *ContainerApplyConfiguration) WithStdinOnce(value bool) *ContainerApplyConfiguration {\n\tb.StdinOnce = \u0026value\n\treturn b\n}","line":{"from":261,"to":267}} {"id":100021332,"name":"WithTTY","signature":"func (b *ContainerApplyConfiguration) WithTTY(value bool) *ContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/container.go","code":"// WithTTY sets the TTY field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TTY field is set to the value of the last call.\nfunc (b *ContainerApplyConfiguration) WithTTY(value bool) *ContainerApplyConfiguration {\n\tb.TTY = \u0026value\n\treturn b\n}","line":{"from":269,"to":275}} {"id":100021333,"name":"ContainerImage","signature":"func ContainerImage() *ContainerImageApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerimage.go","code":"// ContainerImageApplyConfiguration constructs an declarative configuration of the ContainerImage type for use with\n// apply.\nfunc ContainerImage() *ContainerImageApplyConfiguration {\n\treturn \u0026ContainerImageApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100021334,"name":"WithNames","signature":"func (b *ContainerImageApplyConfiguration) WithNames(values ...string) *ContainerImageApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerimage.go","code":"// WithNames adds the given value to the Names field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Names field.\nfunc (b *ContainerImageApplyConfiguration) WithNames(values ...string) *ContainerImageApplyConfiguration {\n\tfor i := range values {\n\t\tb.Names = append(b.Names, values[i])\n\t}\n\treturn b\n}","line":{"from":34,"to":42}} {"id":100021335,"name":"WithSizeBytes","signature":"func (b *ContainerImageApplyConfiguration) WithSizeBytes(value int64) *ContainerImageApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerimage.go","code":"// WithSizeBytes sets the SizeBytes field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SizeBytes field is set to the value of the last call.\nfunc (b *ContainerImageApplyConfiguration) WithSizeBytes(value int64) *ContainerImageApplyConfiguration {\n\tb.SizeBytes = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100021336,"name":"ContainerPort","signature":"func ContainerPort() *ContainerPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerport.go","code":"// ContainerPortApplyConfiguration constructs an declarative configuration of the ContainerPort type for use with\n// apply.\nfunc ContainerPort() *ContainerPortApplyConfiguration {\n\treturn \u0026ContainerPortApplyConfiguration{}\n}","line":{"from":35,"to":39}} {"id":100021337,"name":"WithName","signature":"func (b *ContainerPortApplyConfiguration) WithName(value string) *ContainerPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerport.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ContainerPortApplyConfiguration) WithName(value string) *ContainerPortApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":41,"to":47}} {"id":100021338,"name":"WithHostPort","signature":"func (b *ContainerPortApplyConfiguration) WithHostPort(value int32) *ContainerPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerport.go","code":"// WithHostPort sets the HostPort field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HostPort field is set to the value of the last call.\nfunc (b *ContainerPortApplyConfiguration) WithHostPort(value int32) *ContainerPortApplyConfiguration {\n\tb.HostPort = \u0026value\n\treturn b\n}","line":{"from":49,"to":55}} {"id":100021339,"name":"WithContainerPort","signature":"func (b *ContainerPortApplyConfiguration) WithContainerPort(value int32) *ContainerPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerport.go","code":"// WithContainerPort sets the ContainerPort field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ContainerPort field is set to the value of the last call.\nfunc (b *ContainerPortApplyConfiguration) WithContainerPort(value int32) *ContainerPortApplyConfiguration {\n\tb.ContainerPort = \u0026value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100021340,"name":"WithProtocol","signature":"func (b *ContainerPortApplyConfiguration) WithProtocol(value v1.Protocol) *ContainerPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerport.go","code":"// WithProtocol sets the Protocol field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Protocol field is set to the value of the last call.\nfunc (b *ContainerPortApplyConfiguration) WithProtocol(value v1.Protocol) *ContainerPortApplyConfiguration {\n\tb.Protocol = \u0026value\n\treturn b\n}","line":{"from":65,"to":71}} {"id":100021341,"name":"WithHostIP","signature":"func (b *ContainerPortApplyConfiguration) WithHostIP(value string) *ContainerPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerport.go","code":"// WithHostIP sets the HostIP field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HostIP field is set to the value of the last call.\nfunc (b *ContainerPortApplyConfiguration) WithHostIP(value string) *ContainerPortApplyConfiguration {\n\tb.HostIP = \u0026value\n\treturn b\n}","line":{"from":73,"to":79}} {"id":100021342,"name":"ContainerResizePolicy","signature":"func ContainerResizePolicy() *ContainerResizePolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerresizepolicy.go","code":"// ContainerResizePolicyApplyConfiguration constructs an declarative configuration of the ContainerResizePolicy type for use with\n// apply.\nfunc ContainerResizePolicy() *ContainerResizePolicyApplyConfiguration {\n\treturn \u0026ContainerResizePolicyApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100021343,"name":"WithResourceName","signature":"func (b *ContainerResizePolicyApplyConfiguration) WithResourceName(value v1.ResourceName) *ContainerResizePolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerresizepolicy.go","code":"// WithResourceName sets the ResourceName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceName field is set to the value of the last call.\nfunc (b *ContainerResizePolicyApplyConfiguration) WithResourceName(value v1.ResourceName) *ContainerResizePolicyApplyConfiguration {\n\tb.ResourceName = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100021344,"name":"WithRestartPolicy","signature":"func (b *ContainerResizePolicyApplyConfiguration) WithRestartPolicy(value v1.ResourceResizeRestartPolicy) *ContainerResizePolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerresizepolicy.go","code":"// WithRestartPolicy sets the RestartPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RestartPolicy field is set to the value of the last call.\nfunc (b *ContainerResizePolicyApplyConfiguration) WithRestartPolicy(value v1.ResourceResizeRestartPolicy) *ContainerResizePolicyApplyConfiguration {\n\tb.RestartPolicy = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100021345,"name":"ContainerState","signature":"func ContainerState() *ContainerStateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstate.go","code":"// ContainerStateApplyConfiguration constructs an declarative configuration of the ContainerState type for use with\n// apply.\nfunc ContainerState() *ContainerStateApplyConfiguration {\n\treturn \u0026ContainerStateApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100021346,"name":"WithWaiting","signature":"func (b *ContainerStateApplyConfiguration) WithWaiting(value *ContainerStateWaitingApplyConfiguration) *ContainerStateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstate.go","code":"// WithWaiting sets the Waiting field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Waiting field is set to the value of the last call.\nfunc (b *ContainerStateApplyConfiguration) WithWaiting(value *ContainerStateWaitingApplyConfiguration) *ContainerStateApplyConfiguration {\n\tb.Waiting = value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100021347,"name":"WithRunning","signature":"func (b *ContainerStateApplyConfiguration) WithRunning(value *ContainerStateRunningApplyConfiguration) *ContainerStateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstate.go","code":"// WithRunning sets the Running field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Running field is set to the value of the last call.\nfunc (b *ContainerStateApplyConfiguration) WithRunning(value *ContainerStateRunningApplyConfiguration) *ContainerStateApplyConfiguration {\n\tb.Running = value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100021348,"name":"WithTerminated","signature":"func (b *ContainerStateApplyConfiguration) WithTerminated(value *ContainerStateTerminatedApplyConfiguration) *ContainerStateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstate.go","code":"// WithTerminated sets the Terminated field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Terminated field is set to the value of the last call.\nfunc (b *ContainerStateApplyConfiguration) WithTerminated(value *ContainerStateTerminatedApplyConfiguration) *ContainerStateApplyConfiguration {\n\tb.Terminated = value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100021349,"name":"ContainerStateRunning","signature":"func ContainerStateRunning() *ContainerStateRunningApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstaterunning.go","code":"// ContainerStateRunningApplyConfiguration constructs an declarative configuration of the ContainerStateRunning type for use with\n// apply.\nfunc ContainerStateRunning() *ContainerStateRunningApplyConfiguration {\n\treturn \u0026ContainerStateRunningApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100021350,"name":"WithStartedAt","signature":"func (b *ContainerStateRunningApplyConfiguration) WithStartedAt(value v1.Time) *ContainerStateRunningApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstaterunning.go","code":"// WithStartedAt sets the StartedAt field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StartedAt field is set to the value of the last call.\nfunc (b *ContainerStateRunningApplyConfiguration) WithStartedAt(value v1.Time) *ContainerStateRunningApplyConfiguration {\n\tb.StartedAt = \u0026value\n\treturn b\n}","line":{"from":37,"to":43}} {"id":100021351,"name":"ContainerStateTerminated","signature":"func ContainerStateTerminated() *ContainerStateTerminatedApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstateterminated.go","code":"// ContainerStateTerminatedApplyConfiguration constructs an declarative configuration of the ContainerStateTerminated type for use with\n// apply.\nfunc ContainerStateTerminated() *ContainerStateTerminatedApplyConfiguration {\n\treturn \u0026ContainerStateTerminatedApplyConfiguration{}\n}","line":{"from":37,"to":41}} {"id":100021352,"name":"WithExitCode","signature":"func (b *ContainerStateTerminatedApplyConfiguration) WithExitCode(value int32) *ContainerStateTerminatedApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstateterminated.go","code":"// WithExitCode sets the ExitCode field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ExitCode field is set to the value of the last call.\nfunc (b *ContainerStateTerminatedApplyConfiguration) WithExitCode(value int32) *ContainerStateTerminatedApplyConfiguration {\n\tb.ExitCode = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100021353,"name":"WithSignal","signature":"func (b *ContainerStateTerminatedApplyConfiguration) WithSignal(value int32) *ContainerStateTerminatedApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstateterminated.go","code":"// WithSignal sets the Signal field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Signal field is set to the value of the last call.\nfunc (b *ContainerStateTerminatedApplyConfiguration) WithSignal(value int32) *ContainerStateTerminatedApplyConfiguration {\n\tb.Signal = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100021354,"name":"WithReason","signature":"func (b *ContainerStateTerminatedApplyConfiguration) WithReason(value string) *ContainerStateTerminatedApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstateterminated.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *ContainerStateTerminatedApplyConfiguration) WithReason(value string) *ContainerStateTerminatedApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":59,"to":65}} {"id":100021355,"name":"WithMessage","signature":"func (b *ContainerStateTerminatedApplyConfiguration) WithMessage(value string) *ContainerStateTerminatedApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstateterminated.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *ContainerStateTerminatedApplyConfiguration) WithMessage(value string) *ContainerStateTerminatedApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100021356,"name":"WithStartedAt","signature":"func (b *ContainerStateTerminatedApplyConfiguration) WithStartedAt(value v1.Time) *ContainerStateTerminatedApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstateterminated.go","code":"// WithStartedAt sets the StartedAt field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StartedAt field is set to the value of the last call.\nfunc (b *ContainerStateTerminatedApplyConfiguration) WithStartedAt(value v1.Time) *ContainerStateTerminatedApplyConfiguration {\n\tb.StartedAt = \u0026value\n\treturn b\n}","line":{"from":75,"to":81}} {"id":100021357,"name":"WithFinishedAt","signature":"func (b *ContainerStateTerminatedApplyConfiguration) WithFinishedAt(value v1.Time) *ContainerStateTerminatedApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstateterminated.go","code":"// WithFinishedAt sets the FinishedAt field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FinishedAt field is set to the value of the last call.\nfunc (b *ContainerStateTerminatedApplyConfiguration) WithFinishedAt(value v1.Time) *ContainerStateTerminatedApplyConfiguration {\n\tb.FinishedAt = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100021358,"name":"WithContainerID","signature":"func (b *ContainerStateTerminatedApplyConfiguration) WithContainerID(value string) *ContainerStateTerminatedApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstateterminated.go","code":"// WithContainerID sets the ContainerID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ContainerID field is set to the value of the last call.\nfunc (b *ContainerStateTerminatedApplyConfiguration) WithContainerID(value string) *ContainerStateTerminatedApplyConfiguration {\n\tb.ContainerID = \u0026value\n\treturn b\n}","line":{"from":91,"to":97}} {"id":100021359,"name":"ContainerStateWaiting","signature":"func ContainerStateWaiting() *ContainerStateWaitingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstatewaiting.go","code":"// ContainerStateWaitingApplyConfiguration constructs an declarative configuration of the ContainerStateWaiting type for use with\n// apply.\nfunc ContainerStateWaiting() *ContainerStateWaitingApplyConfiguration {\n\treturn \u0026ContainerStateWaitingApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100021360,"name":"WithReason","signature":"func (b *ContainerStateWaitingApplyConfiguration) WithReason(value string) *ContainerStateWaitingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstatewaiting.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *ContainerStateWaitingApplyConfiguration) WithReason(value string) *ContainerStateWaitingApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100021361,"name":"WithMessage","signature":"func (b *ContainerStateWaitingApplyConfiguration) WithMessage(value string) *ContainerStateWaitingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstatewaiting.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *ContainerStateWaitingApplyConfiguration) WithMessage(value string) *ContainerStateWaitingApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100021362,"name":"ContainerStatus","signature":"func ContainerStatus() *ContainerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstatus.go","code":"// ContainerStatusApplyConfiguration constructs an declarative configuration of the ContainerStatus type for use with\n// apply.\nfunc ContainerStatus() *ContainerStatusApplyConfiguration {\n\treturn \u0026ContainerStatusApplyConfiguration{}\n}","line":{"from":41,"to":45}} {"id":100021363,"name":"WithName","signature":"func (b *ContainerStatusApplyConfiguration) WithName(value string) *ContainerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstatus.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ContainerStatusApplyConfiguration) WithName(value string) *ContainerStatusApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100021364,"name":"WithState","signature":"func (b *ContainerStatusApplyConfiguration) WithState(value *ContainerStateApplyConfiguration) *ContainerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstatus.go","code":"// WithState sets the State field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the State field is set to the value of the last call.\nfunc (b *ContainerStatusApplyConfiguration) WithState(value *ContainerStateApplyConfiguration) *ContainerStatusApplyConfiguration {\n\tb.State = value\n\treturn b\n}","line":{"from":55,"to":61}} {"id":100021365,"name":"WithLastTerminationState","signature":"func (b *ContainerStatusApplyConfiguration) WithLastTerminationState(value *ContainerStateApplyConfiguration) *ContainerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstatus.go","code":"// WithLastTerminationState sets the LastTerminationState field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTerminationState field is set to the value of the last call.\nfunc (b *ContainerStatusApplyConfiguration) WithLastTerminationState(value *ContainerStateApplyConfiguration) *ContainerStatusApplyConfiguration {\n\tb.LastTerminationState = value\n\treturn b\n}","line":{"from":63,"to":69}} {"id":100021366,"name":"WithReady","signature":"func (b *ContainerStatusApplyConfiguration) WithReady(value bool) *ContainerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstatus.go","code":"// WithReady sets the Ready field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Ready field is set to the value of the last call.\nfunc (b *ContainerStatusApplyConfiguration) WithReady(value bool) *ContainerStatusApplyConfiguration {\n\tb.Ready = \u0026value\n\treturn b\n}","line":{"from":71,"to":77}} {"id":100021367,"name":"WithRestartCount","signature":"func (b *ContainerStatusApplyConfiguration) WithRestartCount(value int32) *ContainerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstatus.go","code":"// WithRestartCount sets the RestartCount field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RestartCount field is set to the value of the last call.\nfunc (b *ContainerStatusApplyConfiguration) WithRestartCount(value int32) *ContainerStatusApplyConfiguration {\n\tb.RestartCount = \u0026value\n\treturn b\n}","line":{"from":79,"to":85}} {"id":100021368,"name":"WithImage","signature":"func (b *ContainerStatusApplyConfiguration) WithImage(value string) *ContainerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstatus.go","code":"// WithImage sets the Image field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Image field is set to the value of the last call.\nfunc (b *ContainerStatusApplyConfiguration) WithImage(value string) *ContainerStatusApplyConfiguration {\n\tb.Image = \u0026value\n\treturn b\n}","line":{"from":87,"to":93}} {"id":100021369,"name":"WithImageID","signature":"func (b *ContainerStatusApplyConfiguration) WithImageID(value string) *ContainerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstatus.go","code":"// WithImageID sets the ImageID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ImageID field is set to the value of the last call.\nfunc (b *ContainerStatusApplyConfiguration) WithImageID(value string) *ContainerStatusApplyConfiguration {\n\tb.ImageID = \u0026value\n\treturn b\n}","line":{"from":95,"to":101}} {"id":100021370,"name":"WithContainerID","signature":"func (b *ContainerStatusApplyConfiguration) WithContainerID(value string) *ContainerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstatus.go","code":"// WithContainerID sets the ContainerID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ContainerID field is set to the value of the last call.\nfunc (b *ContainerStatusApplyConfiguration) WithContainerID(value string) *ContainerStatusApplyConfiguration {\n\tb.ContainerID = \u0026value\n\treturn b\n}","line":{"from":103,"to":109}} {"id":100021371,"name":"WithStarted","signature":"func (b *ContainerStatusApplyConfiguration) WithStarted(value bool) *ContainerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstatus.go","code":"// WithStarted sets the Started field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Started field is set to the value of the last call.\nfunc (b *ContainerStatusApplyConfiguration) WithStarted(value bool) *ContainerStatusApplyConfiguration {\n\tb.Started = \u0026value\n\treturn b\n}","line":{"from":111,"to":117}} {"id":100021372,"name":"WithAllocatedResources","signature":"func (b *ContainerStatusApplyConfiguration) WithAllocatedResources(value corev1.ResourceList) *ContainerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstatus.go","code":"// WithAllocatedResources sets the AllocatedResources field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AllocatedResources field is set to the value of the last call.\nfunc (b *ContainerStatusApplyConfiguration) WithAllocatedResources(value corev1.ResourceList) *ContainerStatusApplyConfiguration {\n\tb.AllocatedResources = \u0026value\n\treturn b\n}","line":{"from":119,"to":125}} {"id":100021373,"name":"WithResources","signature":"func (b *ContainerStatusApplyConfiguration) WithResources(value *ResourceRequirementsApplyConfiguration) *ContainerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/containerstatus.go","code":"// WithResources sets the Resources field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Resources field is set to the value of the last call.\nfunc (b *ContainerStatusApplyConfiguration) WithResources(value *ResourceRequirementsApplyConfiguration) *ContainerStatusApplyConfiguration {\n\tb.Resources = value\n\treturn b\n}","line":{"from":127,"to":133}} {"id":100021374,"name":"CSIPersistentVolumeSource","signature":"func CSIPersistentVolumeSource() *CSIPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/csipersistentvolumesource.go","code":"// CSIPersistentVolumeSourceApplyConfiguration constructs an declarative configuration of the CSIPersistentVolumeSource type for use with\n// apply.\nfunc CSIPersistentVolumeSource() *CSIPersistentVolumeSourceApplyConfiguration {\n\treturn \u0026CSIPersistentVolumeSourceApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100021375,"name":"WithDriver","signature":"func (b *CSIPersistentVolumeSourceApplyConfiguration) WithDriver(value string) *CSIPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/csipersistentvolumesource.go","code":"// WithDriver sets the Driver field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Driver field is set to the value of the last call.\nfunc (b *CSIPersistentVolumeSourceApplyConfiguration) WithDriver(value string) *CSIPersistentVolumeSourceApplyConfiguration {\n\tb.Driver = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100021376,"name":"WithVolumeHandle","signature":"func (b *CSIPersistentVolumeSourceApplyConfiguration) WithVolumeHandle(value string) *CSIPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/csipersistentvolumesource.go","code":"// WithVolumeHandle sets the VolumeHandle field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the VolumeHandle field is set to the value of the last call.\nfunc (b *CSIPersistentVolumeSourceApplyConfiguration) WithVolumeHandle(value string) *CSIPersistentVolumeSourceApplyConfiguration {\n\tb.VolumeHandle = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100021377,"name":"WithReadOnly","signature":"func (b *CSIPersistentVolumeSourceApplyConfiguration) WithReadOnly(value bool) *CSIPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/csipersistentvolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *CSIPersistentVolumeSourceApplyConfiguration) WithReadOnly(value bool) *CSIPersistentVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100021378,"name":"WithFSType","signature":"func (b *CSIPersistentVolumeSourceApplyConfiguration) WithFSType(value string) *CSIPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/csipersistentvolumesource.go","code":"// WithFSType sets the FSType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSType field is set to the value of the last call.\nfunc (b *CSIPersistentVolumeSourceApplyConfiguration) WithFSType(value string) *CSIPersistentVolumeSourceApplyConfiguration {\n\tb.FSType = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100021379,"name":"WithVolumeAttributes","signature":"func (b *CSIPersistentVolumeSourceApplyConfiguration) WithVolumeAttributes(entries map[string]string) *CSIPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/csipersistentvolumesource.go","code":"// WithVolumeAttributes puts the entries into the VolumeAttributes field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the VolumeAttributes field,\n// overwriting an existing map entries in VolumeAttributes field with the same key.\nfunc (b *CSIPersistentVolumeSourceApplyConfiguration) WithVolumeAttributes(entries map[string]string) *CSIPersistentVolumeSourceApplyConfiguration {\n\tif b.VolumeAttributes == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.VolumeAttributes = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.VolumeAttributes[k] = v\n\t}\n\treturn b\n}","line":{"from":74,"to":86}} {"id":100021380,"name":"WithControllerPublishSecretRef","signature":"func (b *CSIPersistentVolumeSourceApplyConfiguration) WithControllerPublishSecretRef(value *SecretReferenceApplyConfiguration) *CSIPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/csipersistentvolumesource.go","code":"// WithControllerPublishSecretRef sets the ControllerPublishSecretRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ControllerPublishSecretRef field is set to the value of the last call.\nfunc (b *CSIPersistentVolumeSourceApplyConfiguration) WithControllerPublishSecretRef(value *SecretReferenceApplyConfiguration) *CSIPersistentVolumeSourceApplyConfiguration {\n\tb.ControllerPublishSecretRef = value\n\treturn b\n}","line":{"from":88,"to":94}} {"id":100021381,"name":"WithNodeStageSecretRef","signature":"func (b *CSIPersistentVolumeSourceApplyConfiguration) WithNodeStageSecretRef(value *SecretReferenceApplyConfiguration) *CSIPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/csipersistentvolumesource.go","code":"// WithNodeStageSecretRef sets the NodeStageSecretRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NodeStageSecretRef field is set to the value of the last call.\nfunc (b *CSIPersistentVolumeSourceApplyConfiguration) WithNodeStageSecretRef(value *SecretReferenceApplyConfiguration) *CSIPersistentVolumeSourceApplyConfiguration {\n\tb.NodeStageSecretRef = value\n\treturn b\n}","line":{"from":96,"to":102}} {"id":100021382,"name":"WithNodePublishSecretRef","signature":"func (b *CSIPersistentVolumeSourceApplyConfiguration) WithNodePublishSecretRef(value *SecretReferenceApplyConfiguration) *CSIPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/csipersistentvolumesource.go","code":"// WithNodePublishSecretRef sets the NodePublishSecretRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NodePublishSecretRef field is set to the value of the last call.\nfunc (b *CSIPersistentVolumeSourceApplyConfiguration) WithNodePublishSecretRef(value *SecretReferenceApplyConfiguration) *CSIPersistentVolumeSourceApplyConfiguration {\n\tb.NodePublishSecretRef = value\n\treturn b\n}","line":{"from":104,"to":110}} {"id":100021383,"name":"WithControllerExpandSecretRef","signature":"func (b *CSIPersistentVolumeSourceApplyConfiguration) WithControllerExpandSecretRef(value *SecretReferenceApplyConfiguration) *CSIPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/csipersistentvolumesource.go","code":"// WithControllerExpandSecretRef sets the ControllerExpandSecretRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ControllerExpandSecretRef field is set to the value of the last call.\nfunc (b *CSIPersistentVolumeSourceApplyConfiguration) WithControllerExpandSecretRef(value *SecretReferenceApplyConfiguration) *CSIPersistentVolumeSourceApplyConfiguration {\n\tb.ControllerExpandSecretRef = value\n\treturn b\n}","line":{"from":112,"to":118}} {"id":100021384,"name":"WithNodeExpandSecretRef","signature":"func (b *CSIPersistentVolumeSourceApplyConfiguration) WithNodeExpandSecretRef(value *SecretReferenceApplyConfiguration) *CSIPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/csipersistentvolumesource.go","code":"// WithNodeExpandSecretRef sets the NodeExpandSecretRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NodeExpandSecretRef field is set to the value of the last call.\nfunc (b *CSIPersistentVolumeSourceApplyConfiguration) WithNodeExpandSecretRef(value *SecretReferenceApplyConfiguration) *CSIPersistentVolumeSourceApplyConfiguration {\n\tb.NodeExpandSecretRef = value\n\treturn b\n}","line":{"from":120,"to":126}} {"id":100021385,"name":"CSIVolumeSource","signature":"func CSIVolumeSource() *CSIVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/csivolumesource.go","code":"// CSIVolumeSourceApplyConfiguration constructs an declarative configuration of the CSIVolumeSource type for use with\n// apply.\nfunc CSIVolumeSource() *CSIVolumeSourceApplyConfiguration {\n\treturn \u0026CSIVolumeSourceApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100021386,"name":"WithDriver","signature":"func (b *CSIVolumeSourceApplyConfiguration) WithDriver(value string) *CSIVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/csivolumesource.go","code":"// WithDriver sets the Driver field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Driver field is set to the value of the last call.\nfunc (b *CSIVolumeSourceApplyConfiguration) WithDriver(value string) *CSIVolumeSourceApplyConfiguration {\n\tb.Driver = \u0026value\n\treturn b\n}","line":{"from":37,"to":43}} {"id":100021387,"name":"WithReadOnly","signature":"func (b *CSIVolumeSourceApplyConfiguration) WithReadOnly(value bool) *CSIVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/csivolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *CSIVolumeSourceApplyConfiguration) WithReadOnly(value bool) *CSIVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":45,"to":51}} {"id":100021388,"name":"WithFSType","signature":"func (b *CSIVolumeSourceApplyConfiguration) WithFSType(value string) *CSIVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/csivolumesource.go","code":"// WithFSType sets the FSType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSType field is set to the value of the last call.\nfunc (b *CSIVolumeSourceApplyConfiguration) WithFSType(value string) *CSIVolumeSourceApplyConfiguration {\n\tb.FSType = \u0026value\n\treturn b\n}","line":{"from":53,"to":59}} {"id":100021389,"name":"WithVolumeAttributes","signature":"func (b *CSIVolumeSourceApplyConfiguration) WithVolumeAttributes(entries map[string]string) *CSIVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/csivolumesource.go","code":"// WithVolumeAttributes puts the entries into the VolumeAttributes field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the VolumeAttributes field,\n// overwriting an existing map entries in VolumeAttributes field with the same key.\nfunc (b *CSIVolumeSourceApplyConfiguration) WithVolumeAttributes(entries map[string]string) *CSIVolumeSourceApplyConfiguration {\n\tif b.VolumeAttributes == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.VolumeAttributes = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.VolumeAttributes[k] = v\n\t}\n\treturn b\n}","line":{"from":61,"to":73}} {"id":100021390,"name":"WithNodePublishSecretRef","signature":"func (b *CSIVolumeSourceApplyConfiguration) WithNodePublishSecretRef(value *LocalObjectReferenceApplyConfiguration) *CSIVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/csivolumesource.go","code":"// WithNodePublishSecretRef sets the NodePublishSecretRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NodePublishSecretRef field is set to the value of the last call.\nfunc (b *CSIVolumeSourceApplyConfiguration) WithNodePublishSecretRef(value *LocalObjectReferenceApplyConfiguration) *CSIVolumeSourceApplyConfiguration {\n\tb.NodePublishSecretRef = value\n\treturn b\n}","line":{"from":75,"to":81}} {"id":100021391,"name":"DaemonEndpoint","signature":"func DaemonEndpoint() *DaemonEndpointApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/daemonendpoint.go","code":"// DaemonEndpointApplyConfiguration constructs an declarative configuration of the DaemonEndpoint type for use with\n// apply.\nfunc DaemonEndpoint() *DaemonEndpointApplyConfiguration {\n\treturn \u0026DaemonEndpointApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100021392,"name":"WithPort","signature":"func (b *DaemonEndpointApplyConfiguration) WithPort(value int32) *DaemonEndpointApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/daemonendpoint.go","code":"// WithPort sets the Port field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Port field is set to the value of the last call.\nfunc (b *DaemonEndpointApplyConfiguration) WithPort(value int32) *DaemonEndpointApplyConfiguration {\n\tb.Port = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100021393,"name":"DownwardAPIProjection","signature":"func DownwardAPIProjection() *DownwardAPIProjectionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/downwardapiprojection.go","code":"// DownwardAPIProjectionApplyConfiguration constructs an declarative configuration of the DownwardAPIProjection type for use with\n// apply.\nfunc DownwardAPIProjection() *DownwardAPIProjectionApplyConfiguration {\n\treturn \u0026DownwardAPIProjectionApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100021394,"name":"WithItems","signature":"func (b *DownwardAPIProjectionApplyConfiguration) WithItems(values ...*DownwardAPIVolumeFileApplyConfiguration) *DownwardAPIProjectionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/downwardapiprojection.go","code":"// WithItems adds the given value to the Items field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Items field.\nfunc (b *DownwardAPIProjectionApplyConfiguration) WithItems(values ...*DownwardAPIVolumeFileApplyConfiguration) *DownwardAPIProjectionApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithItems\")\n\t\t}\n\t\tb.Items = append(b.Items, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100021395,"name":"DownwardAPIVolumeFile","signature":"func DownwardAPIVolumeFile() *DownwardAPIVolumeFileApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/downwardapivolumefile.go","code":"// DownwardAPIVolumeFileApplyConfiguration constructs an declarative configuration of the DownwardAPIVolumeFile type for use with\n// apply.\nfunc DownwardAPIVolumeFile() *DownwardAPIVolumeFileApplyConfiguration {\n\treturn \u0026DownwardAPIVolumeFileApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100021396,"name":"WithPath","signature":"func (b *DownwardAPIVolumeFileApplyConfiguration) WithPath(value string) *DownwardAPIVolumeFileApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/downwardapivolumefile.go","code":"// WithPath sets the Path field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Path field is set to the value of the last call.\nfunc (b *DownwardAPIVolumeFileApplyConfiguration) WithPath(value string) *DownwardAPIVolumeFileApplyConfiguration {\n\tb.Path = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100021397,"name":"WithFieldRef","signature":"func (b *DownwardAPIVolumeFileApplyConfiguration) WithFieldRef(value *ObjectFieldSelectorApplyConfiguration) *DownwardAPIVolumeFileApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/downwardapivolumefile.go","code":"// WithFieldRef sets the FieldRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FieldRef field is set to the value of the last call.\nfunc (b *DownwardAPIVolumeFileApplyConfiguration) WithFieldRef(value *ObjectFieldSelectorApplyConfiguration) *DownwardAPIVolumeFileApplyConfiguration {\n\tb.FieldRef = value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100021398,"name":"WithResourceFieldRef","signature":"func (b *DownwardAPIVolumeFileApplyConfiguration) WithResourceFieldRef(value *ResourceFieldSelectorApplyConfiguration) *DownwardAPIVolumeFileApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/downwardapivolumefile.go","code":"// WithResourceFieldRef sets the ResourceFieldRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceFieldRef field is set to the value of the last call.\nfunc (b *DownwardAPIVolumeFileApplyConfiguration) WithResourceFieldRef(value *ResourceFieldSelectorApplyConfiguration) *DownwardAPIVolumeFileApplyConfiguration {\n\tb.ResourceFieldRef = value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100021399,"name":"WithMode","signature":"func (b *DownwardAPIVolumeFileApplyConfiguration) WithMode(value int32) *DownwardAPIVolumeFileApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/downwardapivolumefile.go","code":"// WithMode sets the Mode field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Mode field is set to the value of the last call.\nfunc (b *DownwardAPIVolumeFileApplyConfiguration) WithMode(value int32) *DownwardAPIVolumeFileApplyConfiguration {\n\tb.Mode = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100021400,"name":"DownwardAPIVolumeSource","signature":"func DownwardAPIVolumeSource() *DownwardAPIVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/downwardapivolumesource.go","code":"// DownwardAPIVolumeSourceApplyConfiguration constructs an declarative configuration of the DownwardAPIVolumeSource type for use with\n// apply.\nfunc DownwardAPIVolumeSource() *DownwardAPIVolumeSourceApplyConfiguration {\n\treturn \u0026DownwardAPIVolumeSourceApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100021401,"name":"WithItems","signature":"func (b *DownwardAPIVolumeSourceApplyConfiguration) WithItems(values ...*DownwardAPIVolumeFileApplyConfiguration) *DownwardAPIVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/downwardapivolumesource.go","code":"// WithItems adds the given value to the Items field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Items field.\nfunc (b *DownwardAPIVolumeSourceApplyConfiguration) WithItems(values ...*DownwardAPIVolumeFileApplyConfiguration) *DownwardAPIVolumeSourceApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithItems\")\n\t\t}\n\t\tb.Items = append(b.Items, *values[i])\n\t}\n\treturn b\n}","line":{"from":34,"to":45}} {"id":100021402,"name":"WithDefaultMode","signature":"func (b *DownwardAPIVolumeSourceApplyConfiguration) WithDefaultMode(value int32) *DownwardAPIVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/downwardapivolumesource.go","code":"// WithDefaultMode sets the DefaultMode field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DefaultMode field is set to the value of the last call.\nfunc (b *DownwardAPIVolumeSourceApplyConfiguration) WithDefaultMode(value int32) *DownwardAPIVolumeSourceApplyConfiguration {\n\tb.DefaultMode = \u0026value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100021403,"name":"EmptyDirVolumeSource","signature":"func EmptyDirVolumeSource() *EmptyDirVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/emptydirvolumesource.go","code":"// EmptyDirVolumeSourceApplyConfiguration constructs an declarative configuration of the EmptyDirVolumeSource type for use with\n// apply.\nfunc EmptyDirVolumeSource() *EmptyDirVolumeSourceApplyConfiguration {\n\treturn \u0026EmptyDirVolumeSourceApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100021404,"name":"WithMedium","signature":"func (b *EmptyDirVolumeSourceApplyConfiguration) WithMedium(value v1.StorageMedium) *EmptyDirVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/emptydirvolumesource.go","code":"// WithMedium sets the Medium field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Medium field is set to the value of the last call.\nfunc (b *EmptyDirVolumeSourceApplyConfiguration) WithMedium(value v1.StorageMedium) *EmptyDirVolumeSourceApplyConfiguration {\n\tb.Medium = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100021405,"name":"WithSizeLimit","signature":"func (b *EmptyDirVolumeSourceApplyConfiguration) WithSizeLimit(value resource.Quantity) *EmptyDirVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/emptydirvolumesource.go","code":"// WithSizeLimit sets the SizeLimit field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SizeLimit field is set to the value of the last call.\nfunc (b *EmptyDirVolumeSourceApplyConfiguration) WithSizeLimit(value resource.Quantity) *EmptyDirVolumeSourceApplyConfiguration {\n\tb.SizeLimit = \u0026value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100021406,"name":"EndpointAddress","signature":"func EndpointAddress() *EndpointAddressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpointaddress.go","code":"// EndpointAddressApplyConfiguration constructs an declarative configuration of the EndpointAddress type for use with\n// apply.\nfunc EndpointAddress() *EndpointAddressApplyConfiguration {\n\treturn \u0026EndpointAddressApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100021407,"name":"WithIP","signature":"func (b *EndpointAddressApplyConfiguration) WithIP(value string) *EndpointAddressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpointaddress.go","code":"// WithIP sets the IP field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the IP field is set to the value of the last call.\nfunc (b *EndpointAddressApplyConfiguration) WithIP(value string) *EndpointAddressApplyConfiguration {\n\tb.IP = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100021408,"name":"WithHostname","signature":"func (b *EndpointAddressApplyConfiguration) WithHostname(value string) *EndpointAddressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpointaddress.go","code":"// WithHostname sets the Hostname field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Hostname field is set to the value of the last call.\nfunc (b *EndpointAddressApplyConfiguration) WithHostname(value string) *EndpointAddressApplyConfiguration {\n\tb.Hostname = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100021409,"name":"WithNodeName","signature":"func (b *EndpointAddressApplyConfiguration) WithNodeName(value string) *EndpointAddressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpointaddress.go","code":"// WithNodeName sets the NodeName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NodeName field is set to the value of the last call.\nfunc (b *EndpointAddressApplyConfiguration) WithNodeName(value string) *EndpointAddressApplyConfiguration {\n\tb.NodeName = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100021410,"name":"WithTargetRef","signature":"func (b *EndpointAddressApplyConfiguration) WithTargetRef(value *ObjectReferenceApplyConfiguration) *EndpointAddressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpointaddress.go","code":"// WithTargetRef sets the TargetRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TargetRef field is set to the value of the last call.\nfunc (b *EndpointAddressApplyConfiguration) WithTargetRef(value *ObjectReferenceApplyConfiguration) *EndpointAddressApplyConfiguration {\n\tb.TargetRef = value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100021411,"name":"EndpointPort","signature":"func EndpointPort() *EndpointPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpointport.go","code":"// EndpointPortApplyConfiguration constructs an declarative configuration of the EndpointPort type for use with\n// apply.\nfunc EndpointPort() *EndpointPortApplyConfiguration {\n\treturn \u0026EndpointPortApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100021412,"name":"WithName","signature":"func (b *EndpointPortApplyConfiguration) WithName(value string) *EndpointPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpointport.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *EndpointPortApplyConfiguration) WithName(value string) *EndpointPortApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":40,"to":46}} {"id":100021413,"name":"WithPort","signature":"func (b *EndpointPortApplyConfiguration) WithPort(value int32) *EndpointPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpointport.go","code":"// WithPort sets the Port field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Port field is set to the value of the last call.\nfunc (b *EndpointPortApplyConfiguration) WithPort(value int32) *EndpointPortApplyConfiguration {\n\tb.Port = \u0026value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100021414,"name":"WithProtocol","signature":"func (b *EndpointPortApplyConfiguration) WithProtocol(value v1.Protocol) *EndpointPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpointport.go","code":"// WithProtocol sets the Protocol field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Protocol field is set to the value of the last call.\nfunc (b *EndpointPortApplyConfiguration) WithProtocol(value v1.Protocol) *EndpointPortApplyConfiguration {\n\tb.Protocol = \u0026value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100021415,"name":"WithAppProtocol","signature":"func (b *EndpointPortApplyConfiguration) WithAppProtocol(value string) *EndpointPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpointport.go","code":"// WithAppProtocol sets the AppProtocol field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AppProtocol field is set to the value of the last call.\nfunc (b *EndpointPortApplyConfiguration) WithAppProtocol(value string) *EndpointPortApplyConfiguration {\n\tb.AppProtocol = \u0026value\n\treturn b\n}","line":{"from":64,"to":70}} {"id":100021416,"name":"Endpoints","signature":"func Endpoints(name, namespace string) *EndpointsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpoints.go","code":"// Endpoints constructs an declarative configuration of the Endpoints type for use with\n// apply.\nfunc Endpoints(name, namespace string) *EndpointsApplyConfiguration {\n\tb := \u0026EndpointsApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"Endpoints\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b\n}","line":{"from":38,"to":47}} {"id":100021417,"name":"ExtractEndpoints","signature":"func ExtractEndpoints(endpoints *apicorev1.Endpoints, fieldManager string) (*EndpointsApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpoints.go","code":"// ExtractEndpoints extracts the applied configuration owned by fieldManager from\n// endpoints. If no managedFields are found in endpoints for fieldManager, a\n// EndpointsApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// endpoints must be a unmodified Endpoints API object that was retrieved from the Kubernetes API.\n// ExtractEndpoints provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractEndpoints(endpoints *apicorev1.Endpoints, fieldManager string) (*EndpointsApplyConfiguration, error) {\n\treturn extractEndpoints(endpoints, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100021418,"name":"ExtractEndpointsStatus","signature":"func ExtractEndpointsStatus(endpoints *apicorev1.Endpoints, fieldManager string) (*EndpointsApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpoints.go","code":"// ExtractEndpointsStatus is the same as ExtractEndpoints except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractEndpointsStatus(endpoints *apicorev1.Endpoints, fieldManager string) (*EndpointsApplyConfiguration, error) {\n\treturn extractEndpoints(endpoints, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100021419,"name":"extractEndpoints","signature":"func extractEndpoints(endpoints *apicorev1.Endpoints, fieldManager string, subresource string) (*EndpointsApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpoints.go","code":"func extractEndpoints(endpoints *apicorev1.Endpoints, fieldManager string, subresource string) (*EndpointsApplyConfiguration, error) {\n\tb := \u0026EndpointsApplyConfiguration{}\n\terr := managedfields.ExtractInto(endpoints, internal.Parser().Type(\"io.k8s.api.core.v1.Endpoints\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(endpoints.Name)\n\tb.WithNamespace(endpoints.Namespace)\n\n\tb.WithKind(\"Endpoints\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b, nil\n}","line":{"from":71,"to":83}} {"id":100021420,"name":"WithKind","signature":"func (b *EndpointsApplyConfiguration) WithKind(value string) *EndpointsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpoints.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *EndpointsApplyConfiguration) WithKind(value string) *EndpointsApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":85,"to":91}} {"id":100021421,"name":"WithAPIVersion","signature":"func (b *EndpointsApplyConfiguration) WithAPIVersion(value string) *EndpointsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpoints.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *EndpointsApplyConfiguration) WithAPIVersion(value string) *EndpointsApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":93,"to":99}} {"id":100021422,"name":"WithName","signature":"func (b *EndpointsApplyConfiguration) WithName(value string) *EndpointsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpoints.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *EndpointsApplyConfiguration) WithName(value string) *EndpointsApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":101,"to":108}} {"id":100021423,"name":"WithGenerateName","signature":"func (b *EndpointsApplyConfiguration) WithGenerateName(value string) *EndpointsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpoints.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *EndpointsApplyConfiguration) WithGenerateName(value string) *EndpointsApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":110,"to":117}} {"id":100021424,"name":"WithNamespace","signature":"func (b *EndpointsApplyConfiguration) WithNamespace(value string) *EndpointsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpoints.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *EndpointsApplyConfiguration) WithNamespace(value string) *EndpointsApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":119,"to":126}} {"id":100021425,"name":"WithUID","signature":"func (b *EndpointsApplyConfiguration) WithUID(value types.UID) *EndpointsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpoints.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *EndpointsApplyConfiguration) WithUID(value types.UID) *EndpointsApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":128,"to":135}} {"id":100021426,"name":"WithResourceVersion","signature":"func (b *EndpointsApplyConfiguration) WithResourceVersion(value string) *EndpointsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpoints.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *EndpointsApplyConfiguration) WithResourceVersion(value string) *EndpointsApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":137,"to":144}} {"id":100021427,"name":"WithGeneration","signature":"func (b *EndpointsApplyConfiguration) WithGeneration(value int64) *EndpointsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpoints.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *EndpointsApplyConfiguration) WithGeneration(value int64) *EndpointsApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":146,"to":153}} {"id":100021428,"name":"WithCreationTimestamp","signature":"func (b *EndpointsApplyConfiguration) WithCreationTimestamp(value metav1.Time) *EndpointsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpoints.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *EndpointsApplyConfiguration) WithCreationTimestamp(value metav1.Time) *EndpointsApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":155,"to":162}} {"id":100021429,"name":"WithDeletionTimestamp","signature":"func (b *EndpointsApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *EndpointsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpoints.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *EndpointsApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *EndpointsApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":164,"to":171}} {"id":100021430,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *EndpointsApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *EndpointsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpoints.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *EndpointsApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *EndpointsApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":173,"to":180}} {"id":100021431,"name":"WithLabels","signature":"func (b *EndpointsApplyConfiguration) WithLabels(entries map[string]string) *EndpointsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpoints.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *EndpointsApplyConfiguration) WithLabels(entries map[string]string) *EndpointsApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":182,"to":195}} {"id":100021432,"name":"WithAnnotations","signature":"func (b *EndpointsApplyConfiguration) WithAnnotations(entries map[string]string) *EndpointsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpoints.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *EndpointsApplyConfiguration) WithAnnotations(entries map[string]string) *EndpointsApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":197,"to":210}} {"id":100021433,"name":"WithOwnerReferences","signature":"func (b *EndpointsApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *EndpointsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpoints.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *EndpointsApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *EndpointsApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":212,"to":224}} {"id":100021434,"name":"WithFinalizers","signature":"func (b *EndpointsApplyConfiguration) WithFinalizers(values ...string) *EndpointsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpoints.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *EndpointsApplyConfiguration) WithFinalizers(values ...string) *EndpointsApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":226,"to":235}} {"id":100021435,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *EndpointsApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpoints.go","code":"func (b *EndpointsApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":237,"to":241}} {"id":100021436,"name":"WithSubsets","signature":"func (b *EndpointsApplyConfiguration) WithSubsets(values ...*EndpointSubsetApplyConfiguration) *EndpointsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpoints.go","code":"// WithSubsets adds the given value to the Subsets field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Subsets field.\nfunc (b *EndpointsApplyConfiguration) WithSubsets(values ...*EndpointSubsetApplyConfiguration) *EndpointsApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithSubsets\")\n\t\t}\n\t\tb.Subsets = append(b.Subsets, *values[i])\n\t}\n\treturn b\n}","line":{"from":243,"to":254}} {"id":100021437,"name":"EndpointSubset","signature":"func EndpointSubset() *EndpointSubsetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpointsubset.go","code":"// EndpointSubsetApplyConfiguration constructs an declarative configuration of the EndpointSubset type for use with\n// apply.\nfunc EndpointSubset() *EndpointSubsetApplyConfiguration {\n\treturn \u0026EndpointSubsetApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100021438,"name":"WithAddresses","signature":"func (b *EndpointSubsetApplyConfiguration) WithAddresses(values ...*EndpointAddressApplyConfiguration) *EndpointSubsetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpointsubset.go","code":"// WithAddresses adds the given value to the Addresses field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Addresses field.\nfunc (b *EndpointSubsetApplyConfiguration) WithAddresses(values ...*EndpointAddressApplyConfiguration) *EndpointSubsetApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithAddresses\")\n\t\t}\n\t\tb.Addresses = append(b.Addresses, *values[i])\n\t}\n\treturn b\n}","line":{"from":35,"to":46}} {"id":100021439,"name":"WithNotReadyAddresses","signature":"func (b *EndpointSubsetApplyConfiguration) WithNotReadyAddresses(values ...*EndpointAddressApplyConfiguration) *EndpointSubsetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpointsubset.go","code":"// WithNotReadyAddresses adds the given value to the NotReadyAddresses field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the NotReadyAddresses field.\nfunc (b *EndpointSubsetApplyConfiguration) WithNotReadyAddresses(values ...*EndpointAddressApplyConfiguration) *EndpointSubsetApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithNotReadyAddresses\")\n\t\t}\n\t\tb.NotReadyAddresses = append(b.NotReadyAddresses, *values[i])\n\t}\n\treturn b\n}","line":{"from":48,"to":59}} {"id":100021440,"name":"WithPorts","signature":"func (b *EndpointSubsetApplyConfiguration) WithPorts(values ...*EndpointPortApplyConfiguration) *EndpointSubsetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/endpointsubset.go","code":"// WithPorts adds the given value to the Ports field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Ports field.\nfunc (b *EndpointSubsetApplyConfiguration) WithPorts(values ...*EndpointPortApplyConfiguration) *EndpointSubsetApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPorts\")\n\t\t}\n\t\tb.Ports = append(b.Ports, *values[i])\n\t}\n\treturn b\n}","line":{"from":61,"to":72}} {"id":100021441,"name":"EnvFromSource","signature":"func EnvFromSource() *EnvFromSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/envfromsource.go","code":"// EnvFromSourceApplyConfiguration constructs an declarative configuration of the EnvFromSource type for use with\n// apply.\nfunc EnvFromSource() *EnvFromSourceApplyConfiguration {\n\treturn \u0026EnvFromSourceApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100021442,"name":"WithPrefix","signature":"func (b *EnvFromSourceApplyConfiguration) WithPrefix(value string) *EnvFromSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/envfromsource.go","code":"// WithPrefix sets the Prefix field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Prefix field is set to the value of the last call.\nfunc (b *EnvFromSourceApplyConfiguration) WithPrefix(value string) *EnvFromSourceApplyConfiguration {\n\tb.Prefix = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100021443,"name":"WithConfigMapRef","signature":"func (b *EnvFromSourceApplyConfiguration) WithConfigMapRef(value *ConfigMapEnvSourceApplyConfiguration) *EnvFromSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/envfromsource.go","code":"// WithConfigMapRef sets the ConfigMapRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ConfigMapRef field is set to the value of the last call.\nfunc (b *EnvFromSourceApplyConfiguration) WithConfigMapRef(value *ConfigMapEnvSourceApplyConfiguration) *EnvFromSourceApplyConfiguration {\n\tb.ConfigMapRef = value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100021444,"name":"WithSecretRef","signature":"func (b *EnvFromSourceApplyConfiguration) WithSecretRef(value *SecretEnvSourceApplyConfiguration) *EnvFromSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/envfromsource.go","code":"// WithSecretRef sets the SecretRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecretRef field is set to the value of the last call.\nfunc (b *EnvFromSourceApplyConfiguration) WithSecretRef(value *SecretEnvSourceApplyConfiguration) *EnvFromSourceApplyConfiguration {\n\tb.SecretRef = value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100021445,"name":"EnvVar","signature":"func EnvVar() *EnvVarApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/envvar.go","code":"// EnvVarApplyConfiguration constructs an declarative configuration of the EnvVar type for use with\n// apply.\nfunc EnvVar() *EnvVarApplyConfiguration {\n\treturn \u0026EnvVarApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100021446,"name":"WithName","signature":"func (b *EnvVarApplyConfiguration) WithName(value string) *EnvVarApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/envvar.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *EnvVarApplyConfiguration) WithName(value string) *EnvVarApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100021447,"name":"WithValue","signature":"func (b *EnvVarApplyConfiguration) WithValue(value string) *EnvVarApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/envvar.go","code":"// WithValue sets the Value field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Value field is set to the value of the last call.\nfunc (b *EnvVarApplyConfiguration) WithValue(value string) *EnvVarApplyConfiguration {\n\tb.Value = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100021448,"name":"WithValueFrom","signature":"func (b *EnvVarApplyConfiguration) WithValueFrom(value *EnvVarSourceApplyConfiguration) *EnvVarApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/envvar.go","code":"// WithValueFrom sets the ValueFrom field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ValueFrom field is set to the value of the last call.\nfunc (b *EnvVarApplyConfiguration) WithValueFrom(value *EnvVarSourceApplyConfiguration) *EnvVarApplyConfiguration {\n\tb.ValueFrom = value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100021449,"name":"EnvVarSource","signature":"func EnvVarSource() *EnvVarSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/envvarsource.go","code":"// EnvVarSourceApplyConfiguration constructs an declarative configuration of the EnvVarSource type for use with\n// apply.\nfunc EnvVarSource() *EnvVarSourceApplyConfiguration {\n\treturn \u0026EnvVarSourceApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100021450,"name":"WithFieldRef","signature":"func (b *EnvVarSourceApplyConfiguration) WithFieldRef(value *ObjectFieldSelectorApplyConfiguration) *EnvVarSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/envvarsource.go","code":"// WithFieldRef sets the FieldRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FieldRef field is set to the value of the last call.\nfunc (b *EnvVarSourceApplyConfiguration) WithFieldRef(value *ObjectFieldSelectorApplyConfiguration) *EnvVarSourceApplyConfiguration {\n\tb.FieldRef = value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100021451,"name":"WithResourceFieldRef","signature":"func (b *EnvVarSourceApplyConfiguration) WithResourceFieldRef(value *ResourceFieldSelectorApplyConfiguration) *EnvVarSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/envvarsource.go","code":"// WithResourceFieldRef sets the ResourceFieldRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceFieldRef field is set to the value of the last call.\nfunc (b *EnvVarSourceApplyConfiguration) WithResourceFieldRef(value *ResourceFieldSelectorApplyConfiguration) *EnvVarSourceApplyConfiguration {\n\tb.ResourceFieldRef = value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100021452,"name":"WithConfigMapKeyRef","signature":"func (b *EnvVarSourceApplyConfiguration) WithConfigMapKeyRef(value *ConfigMapKeySelectorApplyConfiguration) *EnvVarSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/envvarsource.go","code":"// WithConfigMapKeyRef sets the ConfigMapKeyRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ConfigMapKeyRef field is set to the value of the last call.\nfunc (b *EnvVarSourceApplyConfiguration) WithConfigMapKeyRef(value *ConfigMapKeySelectorApplyConfiguration) *EnvVarSourceApplyConfiguration {\n\tb.ConfigMapKeyRef = value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100021453,"name":"WithSecretKeyRef","signature":"func (b *EnvVarSourceApplyConfiguration) WithSecretKeyRef(value *SecretKeySelectorApplyConfiguration) *EnvVarSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/envvarsource.go","code":"// WithSecretKeyRef sets the SecretKeyRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecretKeyRef field is set to the value of the last call.\nfunc (b *EnvVarSourceApplyConfiguration) WithSecretKeyRef(value *SecretKeySelectorApplyConfiguration) *EnvVarSourceApplyConfiguration {\n\tb.SecretKeyRef = value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100021454,"name":"EphemeralContainer","signature":"func EphemeralContainer() *EphemeralContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go","code":"// EphemeralContainerApplyConfiguration constructs an declarative configuration of the EphemeralContainer type for use with\n// apply.\nfunc EphemeralContainer() *EphemeralContainerApplyConfiguration {\n\treturn \u0026EphemeralContainerApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100021455,"name":"WithName","signature":"func (b *EphemeralContainerApplyConfiguration) WithName(value string) *EphemeralContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *EphemeralContainerApplyConfiguration) WithName(value string) *EphemeralContainerApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100021456,"name":"WithImage","signature":"func (b *EphemeralContainerApplyConfiguration) WithImage(value string) *EphemeralContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go","code":"// WithImage sets the Image field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Image field is set to the value of the last call.\nfunc (b *EphemeralContainerApplyConfiguration) WithImage(value string) *EphemeralContainerApplyConfiguration {\n\tb.Image = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100021457,"name":"WithCommand","signature":"func (b *EphemeralContainerApplyConfiguration) WithCommand(values ...string) *EphemeralContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go","code":"// WithCommand adds the given value to the Command field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Command field.\nfunc (b *EphemeralContainerApplyConfiguration) WithCommand(values ...string) *EphemeralContainerApplyConfiguration {\n\tfor i := range values {\n\t\tb.Command = append(b.Command, values[i])\n\t}\n\treturn b\n}","line":{"from":54,"to":62}} {"id":100021458,"name":"WithArgs","signature":"func (b *EphemeralContainerApplyConfiguration) WithArgs(values ...string) *EphemeralContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go","code":"// WithArgs adds the given value to the Args field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Args field.\nfunc (b *EphemeralContainerApplyConfiguration) WithArgs(values ...string) *EphemeralContainerApplyConfiguration {\n\tfor i := range values {\n\t\tb.Args = append(b.Args, values[i])\n\t}\n\treturn b\n}","line":{"from":64,"to":72}} {"id":100021459,"name":"WithWorkingDir","signature":"func (b *EphemeralContainerApplyConfiguration) WithWorkingDir(value string) *EphemeralContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go","code":"// WithWorkingDir sets the WorkingDir field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the WorkingDir field is set to the value of the last call.\nfunc (b *EphemeralContainerApplyConfiguration) WithWorkingDir(value string) *EphemeralContainerApplyConfiguration {\n\tb.WorkingDir = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100021460,"name":"WithPorts","signature":"func (b *EphemeralContainerApplyConfiguration) WithPorts(values ...*ContainerPortApplyConfiguration) *EphemeralContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go","code":"// WithPorts adds the given value to the Ports field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Ports field.\nfunc (b *EphemeralContainerApplyConfiguration) WithPorts(values ...*ContainerPortApplyConfiguration) *EphemeralContainerApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPorts\")\n\t\t}\n\t\tb.Ports = append(b.Ports, *values[i])\n\t}\n\treturn b\n}","line":{"from":82,"to":93}} {"id":100021461,"name":"WithEnvFrom","signature":"func (b *EphemeralContainerApplyConfiguration) WithEnvFrom(values ...*EnvFromSourceApplyConfiguration) *EphemeralContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go","code":"// WithEnvFrom adds the given value to the EnvFrom field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the EnvFrom field.\nfunc (b *EphemeralContainerApplyConfiguration) WithEnvFrom(values ...*EnvFromSourceApplyConfiguration) *EphemeralContainerApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithEnvFrom\")\n\t\t}\n\t\tb.EnvFrom = append(b.EnvFrom, *values[i])\n\t}\n\treturn b\n}","line":{"from":95,"to":106}} {"id":100021462,"name":"WithEnv","signature":"func (b *EphemeralContainerApplyConfiguration) WithEnv(values ...*EnvVarApplyConfiguration) *EphemeralContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go","code":"// WithEnv adds the given value to the Env field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Env field.\nfunc (b *EphemeralContainerApplyConfiguration) WithEnv(values ...*EnvVarApplyConfiguration) *EphemeralContainerApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithEnv\")\n\t\t}\n\t\tb.Env = append(b.Env, *values[i])\n\t}\n\treturn b\n}","line":{"from":108,"to":119}} {"id":100021463,"name":"WithResources","signature":"func (b *EphemeralContainerApplyConfiguration) WithResources(value *ResourceRequirementsApplyConfiguration) *EphemeralContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go","code":"// WithResources sets the Resources field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Resources field is set to the value of the last call.\nfunc (b *EphemeralContainerApplyConfiguration) WithResources(value *ResourceRequirementsApplyConfiguration) *EphemeralContainerApplyConfiguration {\n\tb.Resources = value\n\treturn b\n}","line":{"from":121,"to":127}} {"id":100021464,"name":"WithResizePolicy","signature":"func (b *EphemeralContainerApplyConfiguration) WithResizePolicy(values ...*ContainerResizePolicyApplyConfiguration) *EphemeralContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go","code":"// WithResizePolicy adds the given value to the ResizePolicy field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ResizePolicy field.\nfunc (b *EphemeralContainerApplyConfiguration) WithResizePolicy(values ...*ContainerResizePolicyApplyConfiguration) *EphemeralContainerApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithResizePolicy\")\n\t\t}\n\t\tb.ResizePolicy = append(b.ResizePolicy, *values[i])\n\t}\n\treturn b\n}","line":{"from":129,"to":140}} {"id":100021465,"name":"WithVolumeMounts","signature":"func (b *EphemeralContainerApplyConfiguration) WithVolumeMounts(values ...*VolumeMountApplyConfiguration) *EphemeralContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go","code":"// WithVolumeMounts adds the given value to the VolumeMounts field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the VolumeMounts field.\nfunc (b *EphemeralContainerApplyConfiguration) WithVolumeMounts(values ...*VolumeMountApplyConfiguration) *EphemeralContainerApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithVolumeMounts\")\n\t\t}\n\t\tb.VolumeMounts = append(b.VolumeMounts, *values[i])\n\t}\n\treturn b\n}","line":{"from":142,"to":153}} {"id":100021466,"name":"WithVolumeDevices","signature":"func (b *EphemeralContainerApplyConfiguration) WithVolumeDevices(values ...*VolumeDeviceApplyConfiguration) *EphemeralContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go","code":"// WithVolumeDevices adds the given value to the VolumeDevices field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the VolumeDevices field.\nfunc (b *EphemeralContainerApplyConfiguration) WithVolumeDevices(values ...*VolumeDeviceApplyConfiguration) *EphemeralContainerApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithVolumeDevices\")\n\t\t}\n\t\tb.VolumeDevices = append(b.VolumeDevices, *values[i])\n\t}\n\treturn b\n}","line":{"from":155,"to":166}} {"id":100021467,"name":"WithLivenessProbe","signature":"func (b *EphemeralContainerApplyConfiguration) WithLivenessProbe(value *ProbeApplyConfiguration) *EphemeralContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go","code":"// WithLivenessProbe sets the LivenessProbe field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LivenessProbe field is set to the value of the last call.\nfunc (b *EphemeralContainerApplyConfiguration) WithLivenessProbe(value *ProbeApplyConfiguration) *EphemeralContainerApplyConfiguration {\n\tb.LivenessProbe = value\n\treturn b\n}","line":{"from":168,"to":174}} {"id":100021468,"name":"WithReadinessProbe","signature":"func (b *EphemeralContainerApplyConfiguration) WithReadinessProbe(value *ProbeApplyConfiguration) *EphemeralContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go","code":"// WithReadinessProbe sets the ReadinessProbe field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadinessProbe field is set to the value of the last call.\nfunc (b *EphemeralContainerApplyConfiguration) WithReadinessProbe(value *ProbeApplyConfiguration) *EphemeralContainerApplyConfiguration {\n\tb.ReadinessProbe = value\n\treturn b\n}","line":{"from":176,"to":182}} {"id":100021469,"name":"WithStartupProbe","signature":"func (b *EphemeralContainerApplyConfiguration) WithStartupProbe(value *ProbeApplyConfiguration) *EphemeralContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go","code":"// WithStartupProbe sets the StartupProbe field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StartupProbe field is set to the value of the last call.\nfunc (b *EphemeralContainerApplyConfiguration) WithStartupProbe(value *ProbeApplyConfiguration) *EphemeralContainerApplyConfiguration {\n\tb.StartupProbe = value\n\treturn b\n}","line":{"from":184,"to":190}} {"id":100021470,"name":"WithLifecycle","signature":"func (b *EphemeralContainerApplyConfiguration) WithLifecycle(value *LifecycleApplyConfiguration) *EphemeralContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go","code":"// WithLifecycle sets the Lifecycle field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Lifecycle field is set to the value of the last call.\nfunc (b *EphemeralContainerApplyConfiguration) WithLifecycle(value *LifecycleApplyConfiguration) *EphemeralContainerApplyConfiguration {\n\tb.Lifecycle = value\n\treturn b\n}","line":{"from":192,"to":198}} {"id":100021471,"name":"WithTerminationMessagePath","signature":"func (b *EphemeralContainerApplyConfiguration) WithTerminationMessagePath(value string) *EphemeralContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go","code":"// WithTerminationMessagePath sets the TerminationMessagePath field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TerminationMessagePath field is set to the value of the last call.\nfunc (b *EphemeralContainerApplyConfiguration) WithTerminationMessagePath(value string) *EphemeralContainerApplyConfiguration {\n\tb.TerminationMessagePath = \u0026value\n\treturn b\n}","line":{"from":200,"to":206}} {"id":100021472,"name":"WithTerminationMessagePolicy","signature":"func (b *EphemeralContainerApplyConfiguration) WithTerminationMessagePolicy(value corev1.TerminationMessagePolicy) *EphemeralContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go","code":"// WithTerminationMessagePolicy sets the TerminationMessagePolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TerminationMessagePolicy field is set to the value of the last call.\nfunc (b *EphemeralContainerApplyConfiguration) WithTerminationMessagePolicy(value corev1.TerminationMessagePolicy) *EphemeralContainerApplyConfiguration {\n\tb.TerminationMessagePolicy = \u0026value\n\treturn b\n}","line":{"from":208,"to":214}} {"id":100021473,"name":"WithImagePullPolicy","signature":"func (b *EphemeralContainerApplyConfiguration) WithImagePullPolicy(value corev1.PullPolicy) *EphemeralContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go","code":"// WithImagePullPolicy sets the ImagePullPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ImagePullPolicy field is set to the value of the last call.\nfunc (b *EphemeralContainerApplyConfiguration) WithImagePullPolicy(value corev1.PullPolicy) *EphemeralContainerApplyConfiguration {\n\tb.ImagePullPolicy = \u0026value\n\treturn b\n}","line":{"from":216,"to":222}} {"id":100021474,"name":"WithSecurityContext","signature":"func (b *EphemeralContainerApplyConfiguration) WithSecurityContext(value *SecurityContextApplyConfiguration) *EphemeralContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go","code":"// WithSecurityContext sets the SecurityContext field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecurityContext field is set to the value of the last call.\nfunc (b *EphemeralContainerApplyConfiguration) WithSecurityContext(value *SecurityContextApplyConfiguration) *EphemeralContainerApplyConfiguration {\n\tb.SecurityContext = value\n\treturn b\n}","line":{"from":224,"to":230}} {"id":100021475,"name":"WithStdin","signature":"func (b *EphemeralContainerApplyConfiguration) WithStdin(value bool) *EphemeralContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go","code":"// WithStdin sets the Stdin field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Stdin field is set to the value of the last call.\nfunc (b *EphemeralContainerApplyConfiguration) WithStdin(value bool) *EphemeralContainerApplyConfiguration {\n\tb.Stdin = \u0026value\n\treturn b\n}","line":{"from":232,"to":238}} {"id":100021476,"name":"WithStdinOnce","signature":"func (b *EphemeralContainerApplyConfiguration) WithStdinOnce(value bool) *EphemeralContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go","code":"// WithStdinOnce sets the StdinOnce field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StdinOnce field is set to the value of the last call.\nfunc (b *EphemeralContainerApplyConfiguration) WithStdinOnce(value bool) *EphemeralContainerApplyConfiguration {\n\tb.StdinOnce = \u0026value\n\treturn b\n}","line":{"from":240,"to":246}} {"id":100021477,"name":"WithTTY","signature":"func (b *EphemeralContainerApplyConfiguration) WithTTY(value bool) *EphemeralContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go","code":"// WithTTY sets the TTY field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TTY field is set to the value of the last call.\nfunc (b *EphemeralContainerApplyConfiguration) WithTTY(value bool) *EphemeralContainerApplyConfiguration {\n\tb.TTY = \u0026value\n\treturn b\n}","line":{"from":248,"to":254}} {"id":100021478,"name":"WithTargetContainerName","signature":"func (b *EphemeralContainerApplyConfiguration) WithTargetContainerName(value string) *EphemeralContainerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainer.go","code":"// WithTargetContainerName sets the TargetContainerName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TargetContainerName field is set to the value of the last call.\nfunc (b *EphemeralContainerApplyConfiguration) WithTargetContainerName(value string) *EphemeralContainerApplyConfiguration {\n\tb.TargetContainerName = \u0026value\n\treturn b\n}","line":{"from":256,"to":262}} {"id":100021479,"name":"EphemeralContainerCommon","signature":"func EphemeralContainerCommon() *EphemeralContainerCommonApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainercommon.go","code":"// EphemeralContainerCommonApplyConfiguration constructs an declarative configuration of the EphemeralContainerCommon type for use with\n// apply.\nfunc EphemeralContainerCommon() *EphemeralContainerCommonApplyConfiguration {\n\treturn \u0026EphemeralContainerCommonApplyConfiguration{}\n}","line":{"from":53,"to":57}} {"id":100021480,"name":"WithName","signature":"func (b *EphemeralContainerCommonApplyConfiguration) WithName(value string) *EphemeralContainerCommonApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainercommon.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *EphemeralContainerCommonApplyConfiguration) WithName(value string) *EphemeralContainerCommonApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":59,"to":65}} {"id":100021481,"name":"WithImage","signature":"func (b *EphemeralContainerCommonApplyConfiguration) WithImage(value string) *EphemeralContainerCommonApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainercommon.go","code":"// WithImage sets the Image field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Image field is set to the value of the last call.\nfunc (b *EphemeralContainerCommonApplyConfiguration) WithImage(value string) *EphemeralContainerCommonApplyConfiguration {\n\tb.Image = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100021482,"name":"WithCommand","signature":"func (b *EphemeralContainerCommonApplyConfiguration) WithCommand(values ...string) *EphemeralContainerCommonApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainercommon.go","code":"// WithCommand adds the given value to the Command field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Command field.\nfunc (b *EphemeralContainerCommonApplyConfiguration) WithCommand(values ...string) *EphemeralContainerCommonApplyConfiguration {\n\tfor i := range values {\n\t\tb.Command = append(b.Command, values[i])\n\t}\n\treturn b\n}","line":{"from":75,"to":83}} {"id":100021483,"name":"WithArgs","signature":"func (b *EphemeralContainerCommonApplyConfiguration) WithArgs(values ...string) *EphemeralContainerCommonApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainercommon.go","code":"// WithArgs adds the given value to the Args field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Args field.\nfunc (b *EphemeralContainerCommonApplyConfiguration) WithArgs(values ...string) *EphemeralContainerCommonApplyConfiguration {\n\tfor i := range values {\n\t\tb.Args = append(b.Args, values[i])\n\t}\n\treturn b\n}","line":{"from":85,"to":93}} {"id":100021484,"name":"WithWorkingDir","signature":"func (b *EphemeralContainerCommonApplyConfiguration) WithWorkingDir(value string) *EphemeralContainerCommonApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainercommon.go","code":"// WithWorkingDir sets the WorkingDir field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the WorkingDir field is set to the value of the last call.\nfunc (b *EphemeralContainerCommonApplyConfiguration) WithWorkingDir(value string) *EphemeralContainerCommonApplyConfiguration {\n\tb.WorkingDir = \u0026value\n\treturn b\n}","line":{"from":95,"to":101}} {"id":100021485,"name":"WithPorts","signature":"func (b *EphemeralContainerCommonApplyConfiguration) WithPorts(values ...*ContainerPortApplyConfiguration) *EphemeralContainerCommonApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainercommon.go","code":"// WithPorts adds the given value to the Ports field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Ports field.\nfunc (b *EphemeralContainerCommonApplyConfiguration) WithPorts(values ...*ContainerPortApplyConfiguration) *EphemeralContainerCommonApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPorts\")\n\t\t}\n\t\tb.Ports = append(b.Ports, *values[i])\n\t}\n\treturn b\n}","line":{"from":103,"to":114}} {"id":100021486,"name":"WithEnvFrom","signature":"func (b *EphemeralContainerCommonApplyConfiguration) WithEnvFrom(values ...*EnvFromSourceApplyConfiguration) *EphemeralContainerCommonApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainercommon.go","code":"// WithEnvFrom adds the given value to the EnvFrom field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the EnvFrom field.\nfunc (b *EphemeralContainerCommonApplyConfiguration) WithEnvFrom(values ...*EnvFromSourceApplyConfiguration) *EphemeralContainerCommonApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithEnvFrom\")\n\t\t}\n\t\tb.EnvFrom = append(b.EnvFrom, *values[i])\n\t}\n\treturn b\n}","line":{"from":116,"to":127}} {"id":100021487,"name":"WithEnv","signature":"func (b *EphemeralContainerCommonApplyConfiguration) WithEnv(values ...*EnvVarApplyConfiguration) *EphemeralContainerCommonApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainercommon.go","code":"// WithEnv adds the given value to the Env field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Env field.\nfunc (b *EphemeralContainerCommonApplyConfiguration) WithEnv(values ...*EnvVarApplyConfiguration) *EphemeralContainerCommonApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithEnv\")\n\t\t}\n\t\tb.Env = append(b.Env, *values[i])\n\t}\n\treturn b\n}","line":{"from":129,"to":140}} {"id":100021488,"name":"WithResources","signature":"func (b *EphemeralContainerCommonApplyConfiguration) WithResources(value *ResourceRequirementsApplyConfiguration) *EphemeralContainerCommonApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainercommon.go","code":"// WithResources sets the Resources field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Resources field is set to the value of the last call.\nfunc (b *EphemeralContainerCommonApplyConfiguration) WithResources(value *ResourceRequirementsApplyConfiguration) *EphemeralContainerCommonApplyConfiguration {\n\tb.Resources = value\n\treturn b\n}","line":{"from":142,"to":148}} {"id":100021489,"name":"WithResizePolicy","signature":"func (b *EphemeralContainerCommonApplyConfiguration) WithResizePolicy(values ...*ContainerResizePolicyApplyConfiguration) *EphemeralContainerCommonApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainercommon.go","code":"// WithResizePolicy adds the given value to the ResizePolicy field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ResizePolicy field.\nfunc (b *EphemeralContainerCommonApplyConfiguration) WithResizePolicy(values ...*ContainerResizePolicyApplyConfiguration) *EphemeralContainerCommonApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithResizePolicy\")\n\t\t}\n\t\tb.ResizePolicy = append(b.ResizePolicy, *values[i])\n\t}\n\treturn b\n}","line":{"from":150,"to":161}} {"id":100021490,"name":"WithVolumeMounts","signature":"func (b *EphemeralContainerCommonApplyConfiguration) WithVolumeMounts(values ...*VolumeMountApplyConfiguration) *EphemeralContainerCommonApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainercommon.go","code":"// WithVolumeMounts adds the given value to the VolumeMounts field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the VolumeMounts field.\nfunc (b *EphemeralContainerCommonApplyConfiguration) WithVolumeMounts(values ...*VolumeMountApplyConfiguration) *EphemeralContainerCommonApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithVolumeMounts\")\n\t\t}\n\t\tb.VolumeMounts = append(b.VolumeMounts, *values[i])\n\t}\n\treturn b\n}","line":{"from":163,"to":174}} {"id":100021491,"name":"WithVolumeDevices","signature":"func (b *EphemeralContainerCommonApplyConfiguration) WithVolumeDevices(values ...*VolumeDeviceApplyConfiguration) *EphemeralContainerCommonApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainercommon.go","code":"// WithVolumeDevices adds the given value to the VolumeDevices field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the VolumeDevices field.\nfunc (b *EphemeralContainerCommonApplyConfiguration) WithVolumeDevices(values ...*VolumeDeviceApplyConfiguration) *EphemeralContainerCommonApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithVolumeDevices\")\n\t\t}\n\t\tb.VolumeDevices = append(b.VolumeDevices, *values[i])\n\t}\n\treturn b\n}","line":{"from":176,"to":187}} {"id":100021492,"name":"WithLivenessProbe","signature":"func (b *EphemeralContainerCommonApplyConfiguration) WithLivenessProbe(value *ProbeApplyConfiguration) *EphemeralContainerCommonApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainercommon.go","code":"// WithLivenessProbe sets the LivenessProbe field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LivenessProbe field is set to the value of the last call.\nfunc (b *EphemeralContainerCommonApplyConfiguration) WithLivenessProbe(value *ProbeApplyConfiguration) *EphemeralContainerCommonApplyConfiguration {\n\tb.LivenessProbe = value\n\treturn b\n}","line":{"from":189,"to":195}} {"id":100021493,"name":"WithReadinessProbe","signature":"func (b *EphemeralContainerCommonApplyConfiguration) WithReadinessProbe(value *ProbeApplyConfiguration) *EphemeralContainerCommonApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainercommon.go","code":"// WithReadinessProbe sets the ReadinessProbe field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadinessProbe field is set to the value of the last call.\nfunc (b *EphemeralContainerCommonApplyConfiguration) WithReadinessProbe(value *ProbeApplyConfiguration) *EphemeralContainerCommonApplyConfiguration {\n\tb.ReadinessProbe = value\n\treturn b\n}","line":{"from":197,"to":203}} {"id":100021494,"name":"WithStartupProbe","signature":"func (b *EphemeralContainerCommonApplyConfiguration) WithStartupProbe(value *ProbeApplyConfiguration) *EphemeralContainerCommonApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainercommon.go","code":"// WithStartupProbe sets the StartupProbe field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StartupProbe field is set to the value of the last call.\nfunc (b *EphemeralContainerCommonApplyConfiguration) WithStartupProbe(value *ProbeApplyConfiguration) *EphemeralContainerCommonApplyConfiguration {\n\tb.StartupProbe = value\n\treturn b\n}","line":{"from":205,"to":211}} {"id":100021495,"name":"WithLifecycle","signature":"func (b *EphemeralContainerCommonApplyConfiguration) WithLifecycle(value *LifecycleApplyConfiguration) *EphemeralContainerCommonApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainercommon.go","code":"// WithLifecycle sets the Lifecycle field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Lifecycle field is set to the value of the last call.\nfunc (b *EphemeralContainerCommonApplyConfiguration) WithLifecycle(value *LifecycleApplyConfiguration) *EphemeralContainerCommonApplyConfiguration {\n\tb.Lifecycle = value\n\treturn b\n}","line":{"from":213,"to":219}} {"id":100021496,"name":"WithTerminationMessagePath","signature":"func (b *EphemeralContainerCommonApplyConfiguration) WithTerminationMessagePath(value string) *EphemeralContainerCommonApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainercommon.go","code":"// WithTerminationMessagePath sets the TerminationMessagePath field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TerminationMessagePath field is set to the value of the last call.\nfunc (b *EphemeralContainerCommonApplyConfiguration) WithTerminationMessagePath(value string) *EphemeralContainerCommonApplyConfiguration {\n\tb.TerminationMessagePath = \u0026value\n\treturn b\n}","line":{"from":221,"to":227}} {"id":100021497,"name":"WithTerminationMessagePolicy","signature":"func (b *EphemeralContainerCommonApplyConfiguration) WithTerminationMessagePolicy(value corev1.TerminationMessagePolicy) *EphemeralContainerCommonApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainercommon.go","code":"// WithTerminationMessagePolicy sets the TerminationMessagePolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TerminationMessagePolicy field is set to the value of the last call.\nfunc (b *EphemeralContainerCommonApplyConfiguration) WithTerminationMessagePolicy(value corev1.TerminationMessagePolicy) *EphemeralContainerCommonApplyConfiguration {\n\tb.TerminationMessagePolicy = \u0026value\n\treturn b\n}","line":{"from":229,"to":235}} {"id":100021498,"name":"WithImagePullPolicy","signature":"func (b *EphemeralContainerCommonApplyConfiguration) WithImagePullPolicy(value corev1.PullPolicy) *EphemeralContainerCommonApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainercommon.go","code":"// WithImagePullPolicy sets the ImagePullPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ImagePullPolicy field is set to the value of the last call.\nfunc (b *EphemeralContainerCommonApplyConfiguration) WithImagePullPolicy(value corev1.PullPolicy) *EphemeralContainerCommonApplyConfiguration {\n\tb.ImagePullPolicy = \u0026value\n\treturn b\n}","line":{"from":237,"to":243}} {"id":100021499,"name":"WithSecurityContext","signature":"func (b *EphemeralContainerCommonApplyConfiguration) WithSecurityContext(value *SecurityContextApplyConfiguration) *EphemeralContainerCommonApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainercommon.go","code":"// WithSecurityContext sets the SecurityContext field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecurityContext field is set to the value of the last call.\nfunc (b *EphemeralContainerCommonApplyConfiguration) WithSecurityContext(value *SecurityContextApplyConfiguration) *EphemeralContainerCommonApplyConfiguration {\n\tb.SecurityContext = value\n\treturn b\n}","line":{"from":245,"to":251}} {"id":100021500,"name":"WithStdin","signature":"func (b *EphemeralContainerCommonApplyConfiguration) WithStdin(value bool) *EphemeralContainerCommonApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainercommon.go","code":"// WithStdin sets the Stdin field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Stdin field is set to the value of the last call.\nfunc (b *EphemeralContainerCommonApplyConfiguration) WithStdin(value bool) *EphemeralContainerCommonApplyConfiguration {\n\tb.Stdin = \u0026value\n\treturn b\n}","line":{"from":253,"to":259}} {"id":100021501,"name":"WithStdinOnce","signature":"func (b *EphemeralContainerCommonApplyConfiguration) WithStdinOnce(value bool) *EphemeralContainerCommonApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainercommon.go","code":"// WithStdinOnce sets the StdinOnce field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StdinOnce field is set to the value of the last call.\nfunc (b *EphemeralContainerCommonApplyConfiguration) WithStdinOnce(value bool) *EphemeralContainerCommonApplyConfiguration {\n\tb.StdinOnce = \u0026value\n\treturn b\n}","line":{"from":261,"to":267}} {"id":100021502,"name":"WithTTY","signature":"func (b *EphemeralContainerCommonApplyConfiguration) WithTTY(value bool) *EphemeralContainerCommonApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralcontainercommon.go","code":"// WithTTY sets the TTY field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TTY field is set to the value of the last call.\nfunc (b *EphemeralContainerCommonApplyConfiguration) WithTTY(value bool) *EphemeralContainerCommonApplyConfiguration {\n\tb.TTY = \u0026value\n\treturn b\n}","line":{"from":269,"to":275}} {"id":100021503,"name":"EphemeralVolumeSource","signature":"func EphemeralVolumeSource() *EphemeralVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralvolumesource.go","code":"// EphemeralVolumeSourceApplyConfiguration constructs an declarative configuration of the EphemeralVolumeSource type for use with\n// apply.\nfunc EphemeralVolumeSource() *EphemeralVolumeSourceApplyConfiguration {\n\treturn \u0026EphemeralVolumeSourceApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100021504,"name":"WithVolumeClaimTemplate","signature":"func (b *EphemeralVolumeSourceApplyConfiguration) WithVolumeClaimTemplate(value *PersistentVolumeClaimTemplateApplyConfiguration) *EphemeralVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/ephemeralvolumesource.go","code":"// WithVolumeClaimTemplate sets the VolumeClaimTemplate field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the VolumeClaimTemplate field is set to the value of the last call.\nfunc (b *EphemeralVolumeSourceApplyConfiguration) WithVolumeClaimTemplate(value *PersistentVolumeClaimTemplateApplyConfiguration) *EphemeralVolumeSourceApplyConfiguration {\n\tb.VolumeClaimTemplate = value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100021505,"name":"Event","signature":"func Event(name, namespace string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// Event constructs an declarative configuration of the Event type for use with\n// apply.\nfunc Event(name, namespace string) *EventApplyConfiguration {\n\tb := \u0026EventApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"Event\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b\n}","line":{"from":51,"to":60}} {"id":100021506,"name":"ExtractEvent","signature":"func ExtractEvent(event *apicorev1.Event, fieldManager string) (*EventApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// ExtractEvent extracts the applied configuration owned by fieldManager from\n// event. If no managedFields are found in event for fieldManager, a\n// EventApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// event must be a unmodified Event API object that was retrieved from the Kubernetes API.\n// ExtractEvent provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractEvent(event *apicorev1.Event, fieldManager string) (*EventApplyConfiguration, error) {\n\treturn extractEvent(event, fieldManager, \"\")\n}","line":{"from":62,"to":75}} {"id":100021507,"name":"ExtractEventStatus","signature":"func ExtractEventStatus(event *apicorev1.Event, fieldManager string) (*EventApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// ExtractEventStatus is the same as ExtractEvent except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractEventStatus(event *apicorev1.Event, fieldManager string) (*EventApplyConfiguration, error) {\n\treturn extractEvent(event, fieldManager, \"status\")\n}","line":{"from":77,"to":82}} {"id":100021508,"name":"extractEvent","signature":"func extractEvent(event *apicorev1.Event, fieldManager string, subresource string) (*EventApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"func extractEvent(event *apicorev1.Event, fieldManager string, subresource string) (*EventApplyConfiguration, error) {\n\tb := \u0026EventApplyConfiguration{}\n\terr := managedfields.ExtractInto(event, internal.Parser().Type(\"io.k8s.api.core.v1.Event\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(event.Name)\n\tb.WithNamespace(event.Namespace)\n\n\tb.WithKind(\"Event\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b, nil\n}","line":{"from":84,"to":96}} {"id":100021509,"name":"WithKind","signature":"func (b *EventApplyConfiguration) WithKind(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithKind(value string) *EventApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":98,"to":104}} {"id":100021510,"name":"WithAPIVersion","signature":"func (b *EventApplyConfiguration) WithAPIVersion(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithAPIVersion(value string) *EventApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":106,"to":112}} {"id":100021511,"name":"WithName","signature":"func (b *EventApplyConfiguration) WithName(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithName(value string) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":114,"to":121}} {"id":100021512,"name":"WithGenerateName","signature":"func (b *EventApplyConfiguration) WithGenerateName(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithGenerateName(value string) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":123,"to":130}} {"id":100021513,"name":"WithNamespace","signature":"func (b *EventApplyConfiguration) WithNamespace(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithNamespace(value string) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":132,"to":139}} {"id":100021514,"name":"WithUID","signature":"func (b *EventApplyConfiguration) WithUID(value types.UID) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithUID(value types.UID) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":141,"to":148}} {"id":100021515,"name":"WithResourceVersion","signature":"func (b *EventApplyConfiguration) WithResourceVersion(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithResourceVersion(value string) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":150,"to":157}} {"id":100021516,"name":"WithGeneration","signature":"func (b *EventApplyConfiguration) WithGeneration(value int64) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithGeneration(value int64) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":159,"to":166}} {"id":100021517,"name":"WithCreationTimestamp","signature":"func (b *EventApplyConfiguration) WithCreationTimestamp(value metav1.Time) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithCreationTimestamp(value metav1.Time) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":168,"to":175}} {"id":100021518,"name":"WithDeletionTimestamp","signature":"func (b *EventApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":177,"to":184}} {"id":100021519,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *EventApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":186,"to":193}} {"id":100021520,"name":"WithLabels","signature":"func (b *EventApplyConfiguration) WithLabels(entries map[string]string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *EventApplyConfiguration) WithLabels(entries map[string]string) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":195,"to":208}} {"id":100021521,"name":"WithAnnotations","signature":"func (b *EventApplyConfiguration) WithAnnotations(entries map[string]string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *EventApplyConfiguration) WithAnnotations(entries map[string]string) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":210,"to":223}} {"id":100021522,"name":"WithOwnerReferences","signature":"func (b *EventApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *EventApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":225,"to":237}} {"id":100021523,"name":"WithFinalizers","signature":"func (b *EventApplyConfiguration) WithFinalizers(values ...string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *EventApplyConfiguration) WithFinalizers(values ...string) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":239,"to":248}} {"id":100021524,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *EventApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"func (b *EventApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":250,"to":254}} {"id":100021525,"name":"WithInvolvedObject","signature":"func (b *EventApplyConfiguration) WithInvolvedObject(value *ObjectReferenceApplyConfiguration) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithInvolvedObject sets the InvolvedObject field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the InvolvedObject field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithInvolvedObject(value *ObjectReferenceApplyConfiguration) *EventApplyConfiguration {\n\tb.InvolvedObject = value\n\treturn b\n}","line":{"from":256,"to":262}} {"id":100021526,"name":"WithReason","signature":"func (b *EventApplyConfiguration) WithReason(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithReason(value string) *EventApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":264,"to":270}} {"id":100021527,"name":"WithMessage","signature":"func (b *EventApplyConfiguration) WithMessage(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithMessage(value string) *EventApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":272,"to":278}} {"id":100021528,"name":"WithSource","signature":"func (b *EventApplyConfiguration) WithSource(value *EventSourceApplyConfiguration) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithSource sets the Source field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Source field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithSource(value *EventSourceApplyConfiguration) *EventApplyConfiguration {\n\tb.Source = value\n\treturn b\n}","line":{"from":280,"to":286}} {"id":100021529,"name":"WithFirstTimestamp","signature":"func (b *EventApplyConfiguration) WithFirstTimestamp(value metav1.Time) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithFirstTimestamp sets the FirstTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FirstTimestamp field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithFirstTimestamp(value metav1.Time) *EventApplyConfiguration {\n\tb.FirstTimestamp = \u0026value\n\treturn b\n}","line":{"from":288,"to":294}} {"id":100021530,"name":"WithLastTimestamp","signature":"func (b *EventApplyConfiguration) WithLastTimestamp(value metav1.Time) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithLastTimestamp sets the LastTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTimestamp field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithLastTimestamp(value metav1.Time) *EventApplyConfiguration {\n\tb.LastTimestamp = \u0026value\n\treturn b\n}","line":{"from":296,"to":302}} {"id":100021531,"name":"WithCount","signature":"func (b *EventApplyConfiguration) WithCount(value int32) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithCount sets the Count field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Count field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithCount(value int32) *EventApplyConfiguration {\n\tb.Count = \u0026value\n\treturn b\n}","line":{"from":304,"to":310}} {"id":100021532,"name":"WithType","signature":"func (b *EventApplyConfiguration) WithType(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithType(value string) *EventApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":312,"to":318}} {"id":100021533,"name":"WithEventTime","signature":"func (b *EventApplyConfiguration) WithEventTime(value metav1.MicroTime) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithEventTime sets the EventTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the EventTime field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithEventTime(value metav1.MicroTime) *EventApplyConfiguration {\n\tb.EventTime = \u0026value\n\treturn b\n}","line":{"from":320,"to":326}} {"id":100021534,"name":"WithSeries","signature":"func (b *EventApplyConfiguration) WithSeries(value *EventSeriesApplyConfiguration) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithSeries sets the Series field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Series field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithSeries(value *EventSeriesApplyConfiguration) *EventApplyConfiguration {\n\tb.Series = value\n\treturn b\n}","line":{"from":328,"to":334}} {"id":100021535,"name":"WithAction","signature":"func (b *EventApplyConfiguration) WithAction(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithAction sets the Action field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Action field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithAction(value string) *EventApplyConfiguration {\n\tb.Action = \u0026value\n\treturn b\n}","line":{"from":336,"to":342}} {"id":100021536,"name":"WithRelated","signature":"func (b *EventApplyConfiguration) WithRelated(value *ObjectReferenceApplyConfiguration) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithRelated sets the Related field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Related field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithRelated(value *ObjectReferenceApplyConfiguration) *EventApplyConfiguration {\n\tb.Related = value\n\treturn b\n}","line":{"from":344,"to":350}} {"id":100021537,"name":"WithReportingController","signature":"func (b *EventApplyConfiguration) WithReportingController(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithReportingController sets the ReportingController field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReportingController field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithReportingController(value string) *EventApplyConfiguration {\n\tb.ReportingController = \u0026value\n\treturn b\n}","line":{"from":352,"to":358}} {"id":100021538,"name":"WithReportingInstance","signature":"func (b *EventApplyConfiguration) WithReportingInstance(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/event.go","code":"// WithReportingInstance sets the ReportingInstance field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReportingInstance field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithReportingInstance(value string) *EventApplyConfiguration {\n\tb.ReportingInstance = \u0026value\n\treturn b\n}","line":{"from":360,"to":366}} {"id":100021539,"name":"EventSeries","signature":"func EventSeries() *EventSeriesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/eventseries.go","code":"// EventSeriesApplyConfiguration constructs an declarative configuration of the EventSeries type for use with\n// apply.\nfunc EventSeries() *EventSeriesApplyConfiguration {\n\treturn \u0026EventSeriesApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100021540,"name":"WithCount","signature":"func (b *EventSeriesApplyConfiguration) WithCount(value int32) *EventSeriesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/eventseries.go","code":"// WithCount sets the Count field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Count field is set to the value of the last call.\nfunc (b *EventSeriesApplyConfiguration) WithCount(value int32) *EventSeriesApplyConfiguration {\n\tb.Count = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100021541,"name":"WithLastObservedTime","signature":"func (b *EventSeriesApplyConfiguration) WithLastObservedTime(value v1.MicroTime) *EventSeriesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/eventseries.go","code":"// WithLastObservedTime sets the LastObservedTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastObservedTime field is set to the value of the last call.\nfunc (b *EventSeriesApplyConfiguration) WithLastObservedTime(value v1.MicroTime) *EventSeriesApplyConfiguration {\n\tb.LastObservedTime = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100021542,"name":"EventSource","signature":"func EventSource() *EventSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/eventsource.go","code":"// EventSourceApplyConfiguration constructs an declarative configuration of the EventSource type for use with\n// apply.\nfunc EventSource() *EventSourceApplyConfiguration {\n\treturn \u0026EventSourceApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100021543,"name":"WithComponent","signature":"func (b *EventSourceApplyConfiguration) WithComponent(value string) *EventSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/eventsource.go","code":"// WithComponent sets the Component field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Component field is set to the value of the last call.\nfunc (b *EventSourceApplyConfiguration) WithComponent(value string) *EventSourceApplyConfiguration {\n\tb.Component = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100021544,"name":"WithHost","signature":"func (b *EventSourceApplyConfiguration) WithHost(value string) *EventSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/eventsource.go","code":"// WithHost sets the Host field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Host field is set to the value of the last call.\nfunc (b *EventSourceApplyConfiguration) WithHost(value string) *EventSourceApplyConfiguration {\n\tb.Host = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100021545,"name":"ExecAction","signature":"func ExecAction() *ExecActionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/execaction.go","code":"// ExecActionApplyConfiguration constructs an declarative configuration of the ExecAction type for use with\n// apply.\nfunc ExecAction() *ExecActionApplyConfiguration {\n\treturn \u0026ExecActionApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100021546,"name":"WithCommand","signature":"func (b *ExecActionApplyConfiguration) WithCommand(values ...string) *ExecActionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/execaction.go","code":"// WithCommand adds the given value to the Command field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Command field.\nfunc (b *ExecActionApplyConfiguration) WithCommand(values ...string) *ExecActionApplyConfiguration {\n\tfor i := range values {\n\t\tb.Command = append(b.Command, values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":41}} {"id":100021547,"name":"FCVolumeSource","signature":"func FCVolumeSource() *FCVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/fcvolumesource.go","code":"// FCVolumeSourceApplyConfiguration constructs an declarative configuration of the FCVolumeSource type for use with\n// apply.\nfunc FCVolumeSource() *FCVolumeSourceApplyConfiguration {\n\treturn \u0026FCVolumeSourceApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100021548,"name":"WithTargetWWNs","signature":"func (b *FCVolumeSourceApplyConfiguration) WithTargetWWNs(values ...string) *FCVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/fcvolumesource.go","code":"// WithTargetWWNs adds the given value to the TargetWWNs field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the TargetWWNs field.\nfunc (b *FCVolumeSourceApplyConfiguration) WithTargetWWNs(values ...string) *FCVolumeSourceApplyConfiguration {\n\tfor i := range values {\n\t\tb.TargetWWNs = append(b.TargetWWNs, values[i])\n\t}\n\treturn b\n}","line":{"from":37,"to":45}} {"id":100021549,"name":"WithLun","signature":"func (b *FCVolumeSourceApplyConfiguration) WithLun(value int32) *FCVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/fcvolumesource.go","code":"// WithLun sets the Lun field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Lun field is set to the value of the last call.\nfunc (b *FCVolumeSourceApplyConfiguration) WithLun(value int32) *FCVolumeSourceApplyConfiguration {\n\tb.Lun = \u0026value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100021550,"name":"WithFSType","signature":"func (b *FCVolumeSourceApplyConfiguration) WithFSType(value string) *FCVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/fcvolumesource.go","code":"// WithFSType sets the FSType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSType field is set to the value of the last call.\nfunc (b *FCVolumeSourceApplyConfiguration) WithFSType(value string) *FCVolumeSourceApplyConfiguration {\n\tb.FSType = \u0026value\n\treturn b\n}","line":{"from":55,"to":61}} {"id":100021551,"name":"WithReadOnly","signature":"func (b *FCVolumeSourceApplyConfiguration) WithReadOnly(value bool) *FCVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/fcvolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *FCVolumeSourceApplyConfiguration) WithReadOnly(value bool) *FCVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":63,"to":69}} {"id":100021552,"name":"WithWWIDs","signature":"func (b *FCVolumeSourceApplyConfiguration) WithWWIDs(values ...string) *FCVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/fcvolumesource.go","code":"// WithWWIDs adds the given value to the WWIDs field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the WWIDs field.\nfunc (b *FCVolumeSourceApplyConfiguration) WithWWIDs(values ...string) *FCVolumeSourceApplyConfiguration {\n\tfor i := range values {\n\t\tb.WWIDs = append(b.WWIDs, values[i])\n\t}\n\treturn b\n}","line":{"from":71,"to":79}} {"id":100021553,"name":"FlexPersistentVolumeSource","signature":"func FlexPersistentVolumeSource() *FlexPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/flexpersistentvolumesource.go","code":"// FlexPersistentVolumeSourceApplyConfiguration constructs an declarative configuration of the FlexPersistentVolumeSource type for use with\n// apply.\nfunc FlexPersistentVolumeSource() *FlexPersistentVolumeSourceApplyConfiguration {\n\treturn \u0026FlexPersistentVolumeSourceApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100021554,"name":"WithDriver","signature":"func (b *FlexPersistentVolumeSourceApplyConfiguration) WithDriver(value string) *FlexPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/flexpersistentvolumesource.go","code":"// WithDriver sets the Driver field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Driver field is set to the value of the last call.\nfunc (b *FlexPersistentVolumeSourceApplyConfiguration) WithDriver(value string) *FlexPersistentVolumeSourceApplyConfiguration {\n\tb.Driver = \u0026value\n\treturn b\n}","line":{"from":37,"to":43}} {"id":100021555,"name":"WithFSType","signature":"func (b *FlexPersistentVolumeSourceApplyConfiguration) WithFSType(value string) *FlexPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/flexpersistentvolumesource.go","code":"// WithFSType sets the FSType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSType field is set to the value of the last call.\nfunc (b *FlexPersistentVolumeSourceApplyConfiguration) WithFSType(value string) *FlexPersistentVolumeSourceApplyConfiguration {\n\tb.FSType = \u0026value\n\treturn b\n}","line":{"from":45,"to":51}} {"id":100021556,"name":"WithSecretRef","signature":"func (b *FlexPersistentVolumeSourceApplyConfiguration) WithSecretRef(value *SecretReferenceApplyConfiguration) *FlexPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/flexpersistentvolumesource.go","code":"// WithSecretRef sets the SecretRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecretRef field is set to the value of the last call.\nfunc (b *FlexPersistentVolumeSourceApplyConfiguration) WithSecretRef(value *SecretReferenceApplyConfiguration) *FlexPersistentVolumeSourceApplyConfiguration {\n\tb.SecretRef = value\n\treturn b\n}","line":{"from":53,"to":59}} {"id":100021557,"name":"WithReadOnly","signature":"func (b *FlexPersistentVolumeSourceApplyConfiguration) WithReadOnly(value bool) *FlexPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/flexpersistentvolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *FlexPersistentVolumeSourceApplyConfiguration) WithReadOnly(value bool) *FlexPersistentVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":61,"to":67}} {"id":100021558,"name":"WithOptions","signature":"func (b *FlexPersistentVolumeSourceApplyConfiguration) WithOptions(entries map[string]string) *FlexPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/flexpersistentvolumesource.go","code":"// WithOptions puts the entries into the Options field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Options field,\n// overwriting an existing map entries in Options field with the same key.\nfunc (b *FlexPersistentVolumeSourceApplyConfiguration) WithOptions(entries map[string]string) *FlexPersistentVolumeSourceApplyConfiguration {\n\tif b.Options == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Options = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Options[k] = v\n\t}\n\treturn b\n}","line":{"from":69,"to":81}} {"id":100021559,"name":"FlexVolumeSource","signature":"func FlexVolumeSource() *FlexVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/flexvolumesource.go","code":"// FlexVolumeSourceApplyConfiguration constructs an declarative configuration of the FlexVolumeSource type for use with\n// apply.\nfunc FlexVolumeSource() *FlexVolumeSourceApplyConfiguration {\n\treturn \u0026FlexVolumeSourceApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100021560,"name":"WithDriver","signature":"func (b *FlexVolumeSourceApplyConfiguration) WithDriver(value string) *FlexVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/flexvolumesource.go","code":"// WithDriver sets the Driver field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Driver field is set to the value of the last call.\nfunc (b *FlexVolumeSourceApplyConfiguration) WithDriver(value string) *FlexVolumeSourceApplyConfiguration {\n\tb.Driver = \u0026value\n\treturn b\n}","line":{"from":37,"to":43}} {"id":100021561,"name":"WithFSType","signature":"func (b *FlexVolumeSourceApplyConfiguration) WithFSType(value string) *FlexVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/flexvolumesource.go","code":"// WithFSType sets the FSType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSType field is set to the value of the last call.\nfunc (b *FlexVolumeSourceApplyConfiguration) WithFSType(value string) *FlexVolumeSourceApplyConfiguration {\n\tb.FSType = \u0026value\n\treturn b\n}","line":{"from":45,"to":51}} {"id":100021562,"name":"WithSecretRef","signature":"func (b *FlexVolumeSourceApplyConfiguration) WithSecretRef(value *LocalObjectReferenceApplyConfiguration) *FlexVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/flexvolumesource.go","code":"// WithSecretRef sets the SecretRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecretRef field is set to the value of the last call.\nfunc (b *FlexVolumeSourceApplyConfiguration) WithSecretRef(value *LocalObjectReferenceApplyConfiguration) *FlexVolumeSourceApplyConfiguration {\n\tb.SecretRef = value\n\treturn b\n}","line":{"from":53,"to":59}} {"id":100021563,"name":"WithReadOnly","signature":"func (b *FlexVolumeSourceApplyConfiguration) WithReadOnly(value bool) *FlexVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/flexvolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *FlexVolumeSourceApplyConfiguration) WithReadOnly(value bool) *FlexVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":61,"to":67}} {"id":100021564,"name":"WithOptions","signature":"func (b *FlexVolumeSourceApplyConfiguration) WithOptions(entries map[string]string) *FlexVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/flexvolumesource.go","code":"// WithOptions puts the entries into the Options field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Options field,\n// overwriting an existing map entries in Options field with the same key.\nfunc (b *FlexVolumeSourceApplyConfiguration) WithOptions(entries map[string]string) *FlexVolumeSourceApplyConfiguration {\n\tif b.Options == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Options = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Options[k] = v\n\t}\n\treturn b\n}","line":{"from":69,"to":81}} {"id":100021565,"name":"FlockerVolumeSource","signature":"func FlockerVolumeSource() *FlockerVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/flockervolumesource.go","code":"// FlockerVolumeSourceApplyConfiguration constructs an declarative configuration of the FlockerVolumeSource type for use with\n// apply.\nfunc FlockerVolumeSource() *FlockerVolumeSourceApplyConfiguration {\n\treturn \u0026FlockerVolumeSourceApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100021566,"name":"WithDatasetName","signature":"func (b *FlockerVolumeSourceApplyConfiguration) WithDatasetName(value string) *FlockerVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/flockervolumesource.go","code":"// WithDatasetName sets the DatasetName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DatasetName field is set to the value of the last call.\nfunc (b *FlockerVolumeSourceApplyConfiguration) WithDatasetName(value string) *FlockerVolumeSourceApplyConfiguration {\n\tb.DatasetName = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100021567,"name":"WithDatasetUUID","signature":"func (b *FlockerVolumeSourceApplyConfiguration) WithDatasetUUID(value string) *FlockerVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/flockervolumesource.go","code":"// WithDatasetUUID sets the DatasetUUID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DatasetUUID field is set to the value of the last call.\nfunc (b *FlockerVolumeSourceApplyConfiguration) WithDatasetUUID(value string) *FlockerVolumeSourceApplyConfiguration {\n\tb.DatasetUUID = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100021568,"name":"GCEPersistentDiskVolumeSource","signature":"func GCEPersistentDiskVolumeSource() *GCEPersistentDiskVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/gcepersistentdiskvolumesource.go","code":"// GCEPersistentDiskVolumeSourceApplyConfiguration constructs an declarative configuration of the GCEPersistentDiskVolumeSource type for use with\n// apply.\nfunc GCEPersistentDiskVolumeSource() *GCEPersistentDiskVolumeSourceApplyConfiguration {\n\treturn \u0026GCEPersistentDiskVolumeSourceApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100021569,"name":"WithPDName","signature":"func (b *GCEPersistentDiskVolumeSourceApplyConfiguration) WithPDName(value string) *GCEPersistentDiskVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/gcepersistentdiskvolumesource.go","code":"// WithPDName sets the PDName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PDName field is set to the value of the last call.\nfunc (b *GCEPersistentDiskVolumeSourceApplyConfiguration) WithPDName(value string) *GCEPersistentDiskVolumeSourceApplyConfiguration {\n\tb.PDName = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100021570,"name":"WithFSType","signature":"func (b *GCEPersistentDiskVolumeSourceApplyConfiguration) WithFSType(value string) *GCEPersistentDiskVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/gcepersistentdiskvolumesource.go","code":"// WithFSType sets the FSType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSType field is set to the value of the last call.\nfunc (b *GCEPersistentDiskVolumeSourceApplyConfiguration) WithFSType(value string) *GCEPersistentDiskVolumeSourceApplyConfiguration {\n\tb.FSType = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100021571,"name":"WithPartition","signature":"func (b *GCEPersistentDiskVolumeSourceApplyConfiguration) WithPartition(value int32) *GCEPersistentDiskVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/gcepersistentdiskvolumesource.go","code":"// WithPartition sets the Partition field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Partition field is set to the value of the last call.\nfunc (b *GCEPersistentDiskVolumeSourceApplyConfiguration) WithPartition(value int32) *GCEPersistentDiskVolumeSourceApplyConfiguration {\n\tb.Partition = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100021572,"name":"WithReadOnly","signature":"func (b *GCEPersistentDiskVolumeSourceApplyConfiguration) WithReadOnly(value bool) *GCEPersistentDiskVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/gcepersistentdiskvolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *GCEPersistentDiskVolumeSourceApplyConfiguration) WithReadOnly(value bool) *GCEPersistentDiskVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100021573,"name":"GitRepoVolumeSource","signature":"func GitRepoVolumeSource() *GitRepoVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/gitrepovolumesource.go","code":"// GitRepoVolumeSourceApplyConfiguration constructs an declarative configuration of the GitRepoVolumeSource type for use with\n// apply.\nfunc GitRepoVolumeSource() *GitRepoVolumeSourceApplyConfiguration {\n\treturn \u0026GitRepoVolumeSourceApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100021574,"name":"WithRepository","signature":"func (b *GitRepoVolumeSourceApplyConfiguration) WithRepository(value string) *GitRepoVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/gitrepovolumesource.go","code":"// WithRepository sets the Repository field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Repository field is set to the value of the last call.\nfunc (b *GitRepoVolumeSourceApplyConfiguration) WithRepository(value string) *GitRepoVolumeSourceApplyConfiguration {\n\tb.Repository = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100021575,"name":"WithRevision","signature":"func (b *GitRepoVolumeSourceApplyConfiguration) WithRevision(value string) *GitRepoVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/gitrepovolumesource.go","code":"// WithRevision sets the Revision field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Revision field is set to the value of the last call.\nfunc (b *GitRepoVolumeSourceApplyConfiguration) WithRevision(value string) *GitRepoVolumeSourceApplyConfiguration {\n\tb.Revision = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100021576,"name":"WithDirectory","signature":"func (b *GitRepoVolumeSourceApplyConfiguration) WithDirectory(value string) *GitRepoVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/gitrepovolumesource.go","code":"// WithDirectory sets the Directory field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Directory field is set to the value of the last call.\nfunc (b *GitRepoVolumeSourceApplyConfiguration) WithDirectory(value string) *GitRepoVolumeSourceApplyConfiguration {\n\tb.Directory = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100021577,"name":"GlusterfsPersistentVolumeSource","signature":"func GlusterfsPersistentVolumeSource() *GlusterfsPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/glusterfspersistentvolumesource.go","code":"// GlusterfsPersistentVolumeSourceApplyConfiguration constructs an declarative configuration of the GlusterfsPersistentVolumeSource type for use with\n// apply.\nfunc GlusterfsPersistentVolumeSource() *GlusterfsPersistentVolumeSourceApplyConfiguration {\n\treturn \u0026GlusterfsPersistentVolumeSourceApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100021578,"name":"WithEndpointsName","signature":"func (b *GlusterfsPersistentVolumeSourceApplyConfiguration) WithEndpointsName(value string) *GlusterfsPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/glusterfspersistentvolumesource.go","code":"// WithEndpointsName sets the EndpointsName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the EndpointsName field is set to the value of the last call.\nfunc (b *GlusterfsPersistentVolumeSourceApplyConfiguration) WithEndpointsName(value string) *GlusterfsPersistentVolumeSourceApplyConfiguration {\n\tb.EndpointsName = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100021579,"name":"WithPath","signature":"func (b *GlusterfsPersistentVolumeSourceApplyConfiguration) WithPath(value string) *GlusterfsPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/glusterfspersistentvolumesource.go","code":"// WithPath sets the Path field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Path field is set to the value of the last call.\nfunc (b *GlusterfsPersistentVolumeSourceApplyConfiguration) WithPath(value string) *GlusterfsPersistentVolumeSourceApplyConfiguration {\n\tb.Path = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100021580,"name":"WithReadOnly","signature":"func (b *GlusterfsPersistentVolumeSourceApplyConfiguration) WithReadOnly(value bool) *GlusterfsPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/glusterfspersistentvolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *GlusterfsPersistentVolumeSourceApplyConfiguration) WithReadOnly(value bool) *GlusterfsPersistentVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100021581,"name":"WithEndpointsNamespace","signature":"func (b *GlusterfsPersistentVolumeSourceApplyConfiguration) WithEndpointsNamespace(value string) *GlusterfsPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/glusterfspersistentvolumesource.go","code":"// WithEndpointsNamespace sets the EndpointsNamespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the EndpointsNamespace field is set to the value of the last call.\nfunc (b *GlusterfsPersistentVolumeSourceApplyConfiguration) WithEndpointsNamespace(value string) *GlusterfsPersistentVolumeSourceApplyConfiguration {\n\tb.EndpointsNamespace = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100021582,"name":"GlusterfsVolumeSource","signature":"func GlusterfsVolumeSource() *GlusterfsVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/glusterfsvolumesource.go","code":"// GlusterfsVolumeSourceApplyConfiguration constructs an declarative configuration of the GlusterfsVolumeSource type for use with\n// apply.\nfunc GlusterfsVolumeSource() *GlusterfsVolumeSourceApplyConfiguration {\n\treturn \u0026GlusterfsVolumeSourceApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100021583,"name":"WithEndpointsName","signature":"func (b *GlusterfsVolumeSourceApplyConfiguration) WithEndpointsName(value string) *GlusterfsVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/glusterfsvolumesource.go","code":"// WithEndpointsName sets the EndpointsName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the EndpointsName field is set to the value of the last call.\nfunc (b *GlusterfsVolumeSourceApplyConfiguration) WithEndpointsName(value string) *GlusterfsVolumeSourceApplyConfiguration {\n\tb.EndpointsName = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100021584,"name":"WithPath","signature":"func (b *GlusterfsVolumeSourceApplyConfiguration) WithPath(value string) *GlusterfsVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/glusterfsvolumesource.go","code":"// WithPath sets the Path field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Path field is set to the value of the last call.\nfunc (b *GlusterfsVolumeSourceApplyConfiguration) WithPath(value string) *GlusterfsVolumeSourceApplyConfiguration {\n\tb.Path = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100021585,"name":"WithReadOnly","signature":"func (b *GlusterfsVolumeSourceApplyConfiguration) WithReadOnly(value bool) *GlusterfsVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/glusterfsvolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *GlusterfsVolumeSourceApplyConfiguration) WithReadOnly(value bool) *GlusterfsVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100021586,"name":"GRPCAction","signature":"func GRPCAction() *GRPCActionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/grpcaction.go","code":"// GRPCActionApplyConfiguration constructs an declarative configuration of the GRPCAction type for use with\n// apply.\nfunc GRPCAction() *GRPCActionApplyConfiguration {\n\treturn \u0026GRPCActionApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100021587,"name":"WithPort","signature":"func (b *GRPCActionApplyConfiguration) WithPort(value int32) *GRPCActionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/grpcaction.go","code":"// WithPort sets the Port field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Port field is set to the value of the last call.\nfunc (b *GRPCActionApplyConfiguration) WithPort(value int32) *GRPCActionApplyConfiguration {\n\tb.Port = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100021588,"name":"WithService","signature":"func (b *GRPCActionApplyConfiguration) WithService(value string) *GRPCActionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/grpcaction.go","code":"// WithService sets the Service field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Service field is set to the value of the last call.\nfunc (b *GRPCActionApplyConfiguration) WithService(value string) *GRPCActionApplyConfiguration {\n\tb.Service = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100021589,"name":"HostAlias","signature":"func HostAlias() *HostAliasApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/hostalias.go","code":"// HostAliasApplyConfiguration constructs an declarative configuration of the HostAlias type for use with\n// apply.\nfunc HostAlias() *HostAliasApplyConfiguration {\n\treturn \u0026HostAliasApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100021590,"name":"WithIP","signature":"func (b *HostAliasApplyConfiguration) WithIP(value string) *HostAliasApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/hostalias.go","code":"// WithIP sets the IP field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the IP field is set to the value of the last call.\nfunc (b *HostAliasApplyConfiguration) WithIP(value string) *HostAliasApplyConfiguration {\n\tb.IP = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100021591,"name":"WithHostnames","signature":"func (b *HostAliasApplyConfiguration) WithHostnames(values ...string) *HostAliasApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/hostalias.go","code":"// WithHostnames adds the given value to the Hostnames field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Hostnames field.\nfunc (b *HostAliasApplyConfiguration) WithHostnames(values ...string) *HostAliasApplyConfiguration {\n\tfor i := range values {\n\t\tb.Hostnames = append(b.Hostnames, values[i])\n\t}\n\treturn b\n}","line":{"from":42,"to":50}} {"id":100021592,"name":"HostPathVolumeSource","signature":"func HostPathVolumeSource() *HostPathVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/hostpathvolumesource.go","code":"// HostPathVolumeSourceApplyConfiguration constructs an declarative configuration of the HostPathVolumeSource type for use with\n// apply.\nfunc HostPathVolumeSource() *HostPathVolumeSourceApplyConfiguration {\n\treturn \u0026HostPathVolumeSourceApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100021593,"name":"WithPath","signature":"func (b *HostPathVolumeSourceApplyConfiguration) WithPath(value string) *HostPathVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/hostpathvolumesource.go","code":"// WithPath sets the Path field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Path field is set to the value of the last call.\nfunc (b *HostPathVolumeSourceApplyConfiguration) WithPath(value string) *HostPathVolumeSourceApplyConfiguration {\n\tb.Path = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100021594,"name":"WithType","signature":"func (b *HostPathVolumeSourceApplyConfiguration) WithType(value v1.HostPathType) *HostPathVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/hostpathvolumesource.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *HostPathVolumeSourceApplyConfiguration) WithType(value v1.HostPathType) *HostPathVolumeSourceApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100021595,"name":"HTTPGetAction","signature":"func HTTPGetAction() *HTTPGetActionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/httpgetaction.go","code":"// HTTPGetActionApplyConfiguration constructs an declarative configuration of the HTTPGetAction type for use with\n// apply.\nfunc HTTPGetAction() *HTTPGetActionApplyConfiguration {\n\treturn \u0026HTTPGetActionApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100021596,"name":"WithPath","signature":"func (b *HTTPGetActionApplyConfiguration) WithPath(value string) *HTTPGetActionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/httpgetaction.go","code":"// WithPath sets the Path field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Path field is set to the value of the last call.\nfunc (b *HTTPGetActionApplyConfiguration) WithPath(value string) *HTTPGetActionApplyConfiguration {\n\tb.Path = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100021597,"name":"WithPort","signature":"func (b *HTTPGetActionApplyConfiguration) WithPort(value intstr.IntOrString) *HTTPGetActionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/httpgetaction.go","code":"// WithPort sets the Port field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Port field is set to the value of the last call.\nfunc (b *HTTPGetActionApplyConfiguration) WithPort(value intstr.IntOrString) *HTTPGetActionApplyConfiguration {\n\tb.Port = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100021598,"name":"WithHost","signature":"func (b *HTTPGetActionApplyConfiguration) WithHost(value string) *HTTPGetActionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/httpgetaction.go","code":"// WithHost sets the Host field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Host field is set to the value of the last call.\nfunc (b *HTTPGetActionApplyConfiguration) WithHost(value string) *HTTPGetActionApplyConfiguration {\n\tb.Host = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100021599,"name":"WithScheme","signature":"func (b *HTTPGetActionApplyConfiguration) WithScheme(value v1.URIScheme) *HTTPGetActionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/httpgetaction.go","code":"// WithScheme sets the Scheme field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Scheme field is set to the value of the last call.\nfunc (b *HTTPGetActionApplyConfiguration) WithScheme(value v1.URIScheme) *HTTPGetActionApplyConfiguration {\n\tb.Scheme = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100021600,"name":"WithHTTPHeaders","signature":"func (b *HTTPGetActionApplyConfiguration) WithHTTPHeaders(values ...*HTTPHeaderApplyConfiguration) *HTTPGetActionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/httpgetaction.go","code":"// WithHTTPHeaders adds the given value to the HTTPHeaders field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the HTTPHeaders field.\nfunc (b *HTTPGetActionApplyConfiguration) WithHTTPHeaders(values ...*HTTPHeaderApplyConfiguration) *HTTPGetActionApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithHTTPHeaders\")\n\t\t}\n\t\tb.HTTPHeaders = append(b.HTTPHeaders, *values[i])\n\t}\n\treturn b\n}","line":{"from":74,"to":85}} {"id":100021601,"name":"HTTPHeader","signature":"func HTTPHeader() *HTTPHeaderApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/httpheader.go","code":"// HTTPHeaderApplyConfiguration constructs an declarative configuration of the HTTPHeader type for use with\n// apply.\nfunc HTTPHeader() *HTTPHeaderApplyConfiguration {\n\treturn \u0026HTTPHeaderApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100021602,"name":"WithName","signature":"func (b *HTTPHeaderApplyConfiguration) WithName(value string) *HTTPHeaderApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/httpheader.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *HTTPHeaderApplyConfiguration) WithName(value string) *HTTPHeaderApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100021603,"name":"WithValue","signature":"func (b *HTTPHeaderApplyConfiguration) WithValue(value string) *HTTPHeaderApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/httpheader.go","code":"// WithValue sets the Value field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Value field is set to the value of the last call.\nfunc (b *HTTPHeaderApplyConfiguration) WithValue(value string) *HTTPHeaderApplyConfiguration {\n\tb.Value = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100021604,"name":"ISCSIPersistentVolumeSource","signature":"func ISCSIPersistentVolumeSource() *ISCSIPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/iscsipersistentvolumesource.go","code":"// ISCSIPersistentVolumeSourceApplyConfiguration constructs an declarative configuration of the ISCSIPersistentVolumeSource type for use with\n// apply.\nfunc ISCSIPersistentVolumeSource() *ISCSIPersistentVolumeSourceApplyConfiguration {\n\treturn \u0026ISCSIPersistentVolumeSourceApplyConfiguration{}\n}","line":{"from":37,"to":41}} {"id":100021605,"name":"WithTargetPortal","signature":"func (b *ISCSIPersistentVolumeSourceApplyConfiguration) WithTargetPortal(value string) *ISCSIPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/iscsipersistentvolumesource.go","code":"// WithTargetPortal sets the TargetPortal field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TargetPortal field is set to the value of the last call.\nfunc (b *ISCSIPersistentVolumeSourceApplyConfiguration) WithTargetPortal(value string) *ISCSIPersistentVolumeSourceApplyConfiguration {\n\tb.TargetPortal = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100021606,"name":"WithIQN","signature":"func (b *ISCSIPersistentVolumeSourceApplyConfiguration) WithIQN(value string) *ISCSIPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/iscsipersistentvolumesource.go","code":"// WithIQN sets the IQN field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the IQN field is set to the value of the last call.\nfunc (b *ISCSIPersistentVolumeSourceApplyConfiguration) WithIQN(value string) *ISCSIPersistentVolumeSourceApplyConfiguration {\n\tb.IQN = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100021607,"name":"WithLun","signature":"func (b *ISCSIPersistentVolumeSourceApplyConfiguration) WithLun(value int32) *ISCSIPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/iscsipersistentvolumesource.go","code":"// WithLun sets the Lun field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Lun field is set to the value of the last call.\nfunc (b *ISCSIPersistentVolumeSourceApplyConfiguration) WithLun(value int32) *ISCSIPersistentVolumeSourceApplyConfiguration {\n\tb.Lun = \u0026value\n\treturn b\n}","line":{"from":59,"to":65}} {"id":100021608,"name":"WithISCSIInterface","signature":"func (b *ISCSIPersistentVolumeSourceApplyConfiguration) WithISCSIInterface(value string) *ISCSIPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/iscsipersistentvolumesource.go","code":"// WithISCSIInterface sets the ISCSIInterface field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ISCSIInterface field is set to the value of the last call.\nfunc (b *ISCSIPersistentVolumeSourceApplyConfiguration) WithISCSIInterface(value string) *ISCSIPersistentVolumeSourceApplyConfiguration {\n\tb.ISCSIInterface = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100021609,"name":"WithFSType","signature":"func (b *ISCSIPersistentVolumeSourceApplyConfiguration) WithFSType(value string) *ISCSIPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/iscsipersistentvolumesource.go","code":"// WithFSType sets the FSType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSType field is set to the value of the last call.\nfunc (b *ISCSIPersistentVolumeSourceApplyConfiguration) WithFSType(value string) *ISCSIPersistentVolumeSourceApplyConfiguration {\n\tb.FSType = \u0026value\n\treturn b\n}","line":{"from":75,"to":81}} {"id":100021610,"name":"WithReadOnly","signature":"func (b *ISCSIPersistentVolumeSourceApplyConfiguration) WithReadOnly(value bool) *ISCSIPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/iscsipersistentvolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *ISCSIPersistentVolumeSourceApplyConfiguration) WithReadOnly(value bool) *ISCSIPersistentVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100021611,"name":"WithPortals","signature":"func (b *ISCSIPersistentVolumeSourceApplyConfiguration) WithPortals(values ...string) *ISCSIPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/iscsipersistentvolumesource.go","code":"// WithPortals adds the given value to the Portals field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Portals field.\nfunc (b *ISCSIPersistentVolumeSourceApplyConfiguration) WithPortals(values ...string) *ISCSIPersistentVolumeSourceApplyConfiguration {\n\tfor i := range values {\n\t\tb.Portals = append(b.Portals, values[i])\n\t}\n\treturn b\n}","line":{"from":91,"to":99}} {"id":100021612,"name":"WithDiscoveryCHAPAuth","signature":"func (b *ISCSIPersistentVolumeSourceApplyConfiguration) WithDiscoveryCHAPAuth(value bool) *ISCSIPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/iscsipersistentvolumesource.go","code":"// WithDiscoveryCHAPAuth sets the DiscoveryCHAPAuth field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DiscoveryCHAPAuth field is set to the value of the last call.\nfunc (b *ISCSIPersistentVolumeSourceApplyConfiguration) WithDiscoveryCHAPAuth(value bool) *ISCSIPersistentVolumeSourceApplyConfiguration {\n\tb.DiscoveryCHAPAuth = \u0026value\n\treturn b\n}","line":{"from":101,"to":107}} {"id":100021613,"name":"WithSessionCHAPAuth","signature":"func (b *ISCSIPersistentVolumeSourceApplyConfiguration) WithSessionCHAPAuth(value bool) *ISCSIPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/iscsipersistentvolumesource.go","code":"// WithSessionCHAPAuth sets the SessionCHAPAuth field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SessionCHAPAuth field is set to the value of the last call.\nfunc (b *ISCSIPersistentVolumeSourceApplyConfiguration) WithSessionCHAPAuth(value bool) *ISCSIPersistentVolumeSourceApplyConfiguration {\n\tb.SessionCHAPAuth = \u0026value\n\treturn b\n}","line":{"from":109,"to":115}} {"id":100021614,"name":"WithSecretRef","signature":"func (b *ISCSIPersistentVolumeSourceApplyConfiguration) WithSecretRef(value *SecretReferenceApplyConfiguration) *ISCSIPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/iscsipersistentvolumesource.go","code":"// WithSecretRef sets the SecretRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecretRef field is set to the value of the last call.\nfunc (b *ISCSIPersistentVolumeSourceApplyConfiguration) WithSecretRef(value *SecretReferenceApplyConfiguration) *ISCSIPersistentVolumeSourceApplyConfiguration {\n\tb.SecretRef = value\n\treturn b\n}","line":{"from":117,"to":123}} {"id":100021615,"name":"WithInitiatorName","signature":"func (b *ISCSIPersistentVolumeSourceApplyConfiguration) WithInitiatorName(value string) *ISCSIPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/iscsipersistentvolumesource.go","code":"// WithInitiatorName sets the InitiatorName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the InitiatorName field is set to the value of the last call.\nfunc (b *ISCSIPersistentVolumeSourceApplyConfiguration) WithInitiatorName(value string) *ISCSIPersistentVolumeSourceApplyConfiguration {\n\tb.InitiatorName = \u0026value\n\treturn b\n}","line":{"from":125,"to":131}} {"id":100021616,"name":"ISCSIVolumeSource","signature":"func ISCSIVolumeSource() *ISCSIVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/iscsivolumesource.go","code":"// ISCSIVolumeSourceApplyConfiguration constructs an declarative configuration of the ISCSIVolumeSource type for use with\n// apply.\nfunc ISCSIVolumeSource() *ISCSIVolumeSourceApplyConfiguration {\n\treturn \u0026ISCSIVolumeSourceApplyConfiguration{}\n}","line":{"from":37,"to":41}} {"id":100021617,"name":"WithTargetPortal","signature":"func (b *ISCSIVolumeSourceApplyConfiguration) WithTargetPortal(value string) *ISCSIVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/iscsivolumesource.go","code":"// WithTargetPortal sets the TargetPortal field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TargetPortal field is set to the value of the last call.\nfunc (b *ISCSIVolumeSourceApplyConfiguration) WithTargetPortal(value string) *ISCSIVolumeSourceApplyConfiguration {\n\tb.TargetPortal = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100021618,"name":"WithIQN","signature":"func (b *ISCSIVolumeSourceApplyConfiguration) WithIQN(value string) *ISCSIVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/iscsivolumesource.go","code":"// WithIQN sets the IQN field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the IQN field is set to the value of the last call.\nfunc (b *ISCSIVolumeSourceApplyConfiguration) WithIQN(value string) *ISCSIVolumeSourceApplyConfiguration {\n\tb.IQN = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100021619,"name":"WithLun","signature":"func (b *ISCSIVolumeSourceApplyConfiguration) WithLun(value int32) *ISCSIVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/iscsivolumesource.go","code":"// WithLun sets the Lun field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Lun field is set to the value of the last call.\nfunc (b *ISCSIVolumeSourceApplyConfiguration) WithLun(value int32) *ISCSIVolumeSourceApplyConfiguration {\n\tb.Lun = \u0026value\n\treturn b\n}","line":{"from":59,"to":65}} {"id":100021620,"name":"WithISCSIInterface","signature":"func (b *ISCSIVolumeSourceApplyConfiguration) WithISCSIInterface(value string) *ISCSIVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/iscsivolumesource.go","code":"// WithISCSIInterface sets the ISCSIInterface field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ISCSIInterface field is set to the value of the last call.\nfunc (b *ISCSIVolumeSourceApplyConfiguration) WithISCSIInterface(value string) *ISCSIVolumeSourceApplyConfiguration {\n\tb.ISCSIInterface = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100021621,"name":"WithFSType","signature":"func (b *ISCSIVolumeSourceApplyConfiguration) WithFSType(value string) *ISCSIVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/iscsivolumesource.go","code":"// WithFSType sets the FSType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSType field is set to the value of the last call.\nfunc (b *ISCSIVolumeSourceApplyConfiguration) WithFSType(value string) *ISCSIVolumeSourceApplyConfiguration {\n\tb.FSType = \u0026value\n\treturn b\n}","line":{"from":75,"to":81}} {"id":100021622,"name":"WithReadOnly","signature":"func (b *ISCSIVolumeSourceApplyConfiguration) WithReadOnly(value bool) *ISCSIVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/iscsivolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *ISCSIVolumeSourceApplyConfiguration) WithReadOnly(value bool) *ISCSIVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100021623,"name":"WithPortals","signature":"func (b *ISCSIVolumeSourceApplyConfiguration) WithPortals(values ...string) *ISCSIVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/iscsivolumesource.go","code":"// WithPortals adds the given value to the Portals field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Portals field.\nfunc (b *ISCSIVolumeSourceApplyConfiguration) WithPortals(values ...string) *ISCSIVolumeSourceApplyConfiguration {\n\tfor i := range values {\n\t\tb.Portals = append(b.Portals, values[i])\n\t}\n\treturn b\n}","line":{"from":91,"to":99}} {"id":100021624,"name":"WithDiscoveryCHAPAuth","signature":"func (b *ISCSIVolumeSourceApplyConfiguration) WithDiscoveryCHAPAuth(value bool) *ISCSIVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/iscsivolumesource.go","code":"// WithDiscoveryCHAPAuth sets the DiscoveryCHAPAuth field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DiscoveryCHAPAuth field is set to the value of the last call.\nfunc (b *ISCSIVolumeSourceApplyConfiguration) WithDiscoveryCHAPAuth(value bool) *ISCSIVolumeSourceApplyConfiguration {\n\tb.DiscoveryCHAPAuth = \u0026value\n\treturn b\n}","line":{"from":101,"to":107}} {"id":100021625,"name":"WithSessionCHAPAuth","signature":"func (b *ISCSIVolumeSourceApplyConfiguration) WithSessionCHAPAuth(value bool) *ISCSIVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/iscsivolumesource.go","code":"// WithSessionCHAPAuth sets the SessionCHAPAuth field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SessionCHAPAuth field is set to the value of the last call.\nfunc (b *ISCSIVolumeSourceApplyConfiguration) WithSessionCHAPAuth(value bool) *ISCSIVolumeSourceApplyConfiguration {\n\tb.SessionCHAPAuth = \u0026value\n\treturn b\n}","line":{"from":109,"to":115}} {"id":100021626,"name":"WithSecretRef","signature":"func (b *ISCSIVolumeSourceApplyConfiguration) WithSecretRef(value *LocalObjectReferenceApplyConfiguration) *ISCSIVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/iscsivolumesource.go","code":"// WithSecretRef sets the SecretRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecretRef field is set to the value of the last call.\nfunc (b *ISCSIVolumeSourceApplyConfiguration) WithSecretRef(value *LocalObjectReferenceApplyConfiguration) *ISCSIVolumeSourceApplyConfiguration {\n\tb.SecretRef = value\n\treturn b\n}","line":{"from":117,"to":123}} {"id":100021627,"name":"WithInitiatorName","signature":"func (b *ISCSIVolumeSourceApplyConfiguration) WithInitiatorName(value string) *ISCSIVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/iscsivolumesource.go","code":"// WithInitiatorName sets the InitiatorName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the InitiatorName field is set to the value of the last call.\nfunc (b *ISCSIVolumeSourceApplyConfiguration) WithInitiatorName(value string) *ISCSIVolumeSourceApplyConfiguration {\n\tb.InitiatorName = \u0026value\n\treturn b\n}","line":{"from":125,"to":131}} {"id":100021628,"name":"KeyToPath","signature":"func KeyToPath() *KeyToPathApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/keytopath.go","code":"// KeyToPathApplyConfiguration constructs an declarative configuration of the KeyToPath type for use with\n// apply.\nfunc KeyToPath() *KeyToPathApplyConfiguration {\n\treturn \u0026KeyToPathApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100021629,"name":"WithKey","signature":"func (b *KeyToPathApplyConfiguration) WithKey(value string) *KeyToPathApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/keytopath.go","code":"// WithKey sets the Key field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Key field is set to the value of the last call.\nfunc (b *KeyToPathApplyConfiguration) WithKey(value string) *KeyToPathApplyConfiguration {\n\tb.Key = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100021630,"name":"WithPath","signature":"func (b *KeyToPathApplyConfiguration) WithPath(value string) *KeyToPathApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/keytopath.go","code":"// WithPath sets the Path field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Path field is set to the value of the last call.\nfunc (b *KeyToPathApplyConfiguration) WithPath(value string) *KeyToPathApplyConfiguration {\n\tb.Path = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100021631,"name":"WithMode","signature":"func (b *KeyToPathApplyConfiguration) WithMode(value int32) *KeyToPathApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/keytopath.go","code":"// WithMode sets the Mode field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Mode field is set to the value of the last call.\nfunc (b *KeyToPathApplyConfiguration) WithMode(value int32) *KeyToPathApplyConfiguration {\n\tb.Mode = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100021632,"name":"Lifecycle","signature":"func Lifecycle() *LifecycleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/lifecycle.go","code":"// LifecycleApplyConfiguration constructs an declarative configuration of the Lifecycle type for use with\n// apply.\nfunc Lifecycle() *LifecycleApplyConfiguration {\n\treturn \u0026LifecycleApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100021633,"name":"WithPostStart","signature":"func (b *LifecycleApplyConfiguration) WithPostStart(value *LifecycleHandlerApplyConfiguration) *LifecycleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/lifecycle.go","code":"// WithPostStart sets the PostStart field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PostStart field is set to the value of the last call.\nfunc (b *LifecycleApplyConfiguration) WithPostStart(value *LifecycleHandlerApplyConfiguration) *LifecycleApplyConfiguration {\n\tb.PostStart = value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100021634,"name":"WithPreStop","signature":"func (b *LifecycleApplyConfiguration) WithPreStop(value *LifecycleHandlerApplyConfiguration) *LifecycleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/lifecycle.go","code":"// WithPreStop sets the PreStop field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PreStop field is set to the value of the last call.\nfunc (b *LifecycleApplyConfiguration) WithPreStop(value *LifecycleHandlerApplyConfiguration) *LifecycleApplyConfiguration {\n\tb.PreStop = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100021635,"name":"LifecycleHandler","signature":"func LifecycleHandler() *LifecycleHandlerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/lifecyclehandler.go","code":"// LifecycleHandlerApplyConfiguration constructs an declarative configuration of the LifecycleHandler type for use with\n// apply.\nfunc LifecycleHandler() *LifecycleHandlerApplyConfiguration {\n\treturn \u0026LifecycleHandlerApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100021636,"name":"WithExec","signature":"func (b *LifecycleHandlerApplyConfiguration) WithExec(value *ExecActionApplyConfiguration) *LifecycleHandlerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/lifecyclehandler.go","code":"// WithExec sets the Exec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Exec field is set to the value of the last call.\nfunc (b *LifecycleHandlerApplyConfiguration) WithExec(value *ExecActionApplyConfiguration) *LifecycleHandlerApplyConfiguration {\n\tb.Exec = value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100021637,"name":"WithHTTPGet","signature":"func (b *LifecycleHandlerApplyConfiguration) WithHTTPGet(value *HTTPGetActionApplyConfiguration) *LifecycleHandlerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/lifecyclehandler.go","code":"// WithHTTPGet sets the HTTPGet field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HTTPGet field is set to the value of the last call.\nfunc (b *LifecycleHandlerApplyConfiguration) WithHTTPGet(value *HTTPGetActionApplyConfiguration) *LifecycleHandlerApplyConfiguration {\n\tb.HTTPGet = value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100021638,"name":"WithTCPSocket","signature":"func (b *LifecycleHandlerApplyConfiguration) WithTCPSocket(value *TCPSocketActionApplyConfiguration) *LifecycleHandlerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/lifecyclehandler.go","code":"// WithTCPSocket sets the TCPSocket field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TCPSocket field is set to the value of the last call.\nfunc (b *LifecycleHandlerApplyConfiguration) WithTCPSocket(value *TCPSocketActionApplyConfiguration) *LifecycleHandlerApplyConfiguration {\n\tb.TCPSocket = value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100021639,"name":"LimitRange","signature":"func LimitRange(name, namespace string) *LimitRangeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrange.go","code":"// LimitRange constructs an declarative configuration of the LimitRange type for use with\n// apply.\nfunc LimitRange(name, namespace string) *LimitRangeApplyConfiguration {\n\tb := \u0026LimitRangeApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"LimitRange\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b\n}","line":{"from":38,"to":47}} {"id":100021640,"name":"ExtractLimitRange","signature":"func ExtractLimitRange(limitRange *apicorev1.LimitRange, fieldManager string) (*LimitRangeApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrange.go","code":"// ExtractLimitRange extracts the applied configuration owned by fieldManager from\n// limitRange. If no managedFields are found in limitRange for fieldManager, a\n// LimitRangeApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// limitRange must be a unmodified LimitRange API object that was retrieved from the Kubernetes API.\n// ExtractLimitRange provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractLimitRange(limitRange *apicorev1.LimitRange, fieldManager string) (*LimitRangeApplyConfiguration, error) {\n\treturn extractLimitRange(limitRange, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100021641,"name":"ExtractLimitRangeStatus","signature":"func ExtractLimitRangeStatus(limitRange *apicorev1.LimitRange, fieldManager string) (*LimitRangeApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrange.go","code":"// ExtractLimitRangeStatus is the same as ExtractLimitRange except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractLimitRangeStatus(limitRange *apicorev1.LimitRange, fieldManager string) (*LimitRangeApplyConfiguration, error) {\n\treturn extractLimitRange(limitRange, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100021642,"name":"extractLimitRange","signature":"func extractLimitRange(limitRange *apicorev1.LimitRange, fieldManager string, subresource string) (*LimitRangeApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrange.go","code":"func extractLimitRange(limitRange *apicorev1.LimitRange, fieldManager string, subresource string) (*LimitRangeApplyConfiguration, error) {\n\tb := \u0026LimitRangeApplyConfiguration{}\n\terr := managedfields.ExtractInto(limitRange, internal.Parser().Type(\"io.k8s.api.core.v1.LimitRange\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(limitRange.Name)\n\tb.WithNamespace(limitRange.Namespace)\n\n\tb.WithKind(\"LimitRange\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b, nil\n}","line":{"from":71,"to":83}} {"id":100021643,"name":"WithKind","signature":"func (b *LimitRangeApplyConfiguration) WithKind(value string) *LimitRangeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrange.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *LimitRangeApplyConfiguration) WithKind(value string) *LimitRangeApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":85,"to":91}} {"id":100021644,"name":"WithAPIVersion","signature":"func (b *LimitRangeApplyConfiguration) WithAPIVersion(value string) *LimitRangeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrange.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *LimitRangeApplyConfiguration) WithAPIVersion(value string) *LimitRangeApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":93,"to":99}} {"id":100021645,"name":"WithName","signature":"func (b *LimitRangeApplyConfiguration) WithName(value string) *LimitRangeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrange.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *LimitRangeApplyConfiguration) WithName(value string) *LimitRangeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":101,"to":108}} {"id":100021646,"name":"WithGenerateName","signature":"func (b *LimitRangeApplyConfiguration) WithGenerateName(value string) *LimitRangeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrange.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *LimitRangeApplyConfiguration) WithGenerateName(value string) *LimitRangeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":110,"to":117}} {"id":100021647,"name":"WithNamespace","signature":"func (b *LimitRangeApplyConfiguration) WithNamespace(value string) *LimitRangeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrange.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *LimitRangeApplyConfiguration) WithNamespace(value string) *LimitRangeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":119,"to":126}} {"id":100021648,"name":"WithUID","signature":"func (b *LimitRangeApplyConfiguration) WithUID(value types.UID) *LimitRangeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrange.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *LimitRangeApplyConfiguration) WithUID(value types.UID) *LimitRangeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":128,"to":135}} {"id":100021649,"name":"WithResourceVersion","signature":"func (b *LimitRangeApplyConfiguration) WithResourceVersion(value string) *LimitRangeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrange.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *LimitRangeApplyConfiguration) WithResourceVersion(value string) *LimitRangeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":137,"to":144}} {"id":100021650,"name":"WithGeneration","signature":"func (b *LimitRangeApplyConfiguration) WithGeneration(value int64) *LimitRangeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrange.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *LimitRangeApplyConfiguration) WithGeneration(value int64) *LimitRangeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":146,"to":153}} {"id":100021651,"name":"WithCreationTimestamp","signature":"func (b *LimitRangeApplyConfiguration) WithCreationTimestamp(value metav1.Time) *LimitRangeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrange.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *LimitRangeApplyConfiguration) WithCreationTimestamp(value metav1.Time) *LimitRangeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":155,"to":162}} {"id":100021652,"name":"WithDeletionTimestamp","signature":"func (b *LimitRangeApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *LimitRangeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrange.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *LimitRangeApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *LimitRangeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":164,"to":171}} {"id":100021653,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *LimitRangeApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *LimitRangeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrange.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *LimitRangeApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *LimitRangeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":173,"to":180}} {"id":100021654,"name":"WithLabels","signature":"func (b *LimitRangeApplyConfiguration) WithLabels(entries map[string]string) *LimitRangeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrange.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *LimitRangeApplyConfiguration) WithLabels(entries map[string]string) *LimitRangeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":182,"to":195}} {"id":100021655,"name":"WithAnnotations","signature":"func (b *LimitRangeApplyConfiguration) WithAnnotations(entries map[string]string) *LimitRangeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrange.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *LimitRangeApplyConfiguration) WithAnnotations(entries map[string]string) *LimitRangeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":197,"to":210}} {"id":100021656,"name":"WithOwnerReferences","signature":"func (b *LimitRangeApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *LimitRangeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrange.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *LimitRangeApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *LimitRangeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":212,"to":224}} {"id":100021657,"name":"WithFinalizers","signature":"func (b *LimitRangeApplyConfiguration) WithFinalizers(values ...string) *LimitRangeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrange.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *LimitRangeApplyConfiguration) WithFinalizers(values ...string) *LimitRangeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":226,"to":235}} {"id":100021658,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *LimitRangeApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrange.go","code":"func (b *LimitRangeApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":237,"to":241}} {"id":100021659,"name":"WithSpec","signature":"func (b *LimitRangeApplyConfiguration) WithSpec(value *LimitRangeSpecApplyConfiguration) *LimitRangeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrange.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *LimitRangeApplyConfiguration) WithSpec(value *LimitRangeSpecApplyConfiguration) *LimitRangeApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":243,"to":249}} {"id":100021660,"name":"LimitRangeItem","signature":"func LimitRangeItem() *LimitRangeItemApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrangeitem.go","code":"// LimitRangeItemApplyConfiguration constructs an declarative configuration of the LimitRangeItem type for use with\n// apply.\nfunc LimitRangeItem() *LimitRangeItemApplyConfiguration {\n\treturn \u0026LimitRangeItemApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100021661,"name":"WithType","signature":"func (b *LimitRangeItemApplyConfiguration) WithType(value v1.LimitType) *LimitRangeItemApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrangeitem.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *LimitRangeItemApplyConfiguration) WithType(value v1.LimitType) *LimitRangeItemApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100021662,"name":"WithMax","signature":"func (b *LimitRangeItemApplyConfiguration) WithMax(value v1.ResourceList) *LimitRangeItemApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrangeitem.go","code":"// WithMax sets the Max field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Max field is set to the value of the last call.\nfunc (b *LimitRangeItemApplyConfiguration) WithMax(value v1.ResourceList) *LimitRangeItemApplyConfiguration {\n\tb.Max = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100021663,"name":"WithMin","signature":"func (b *LimitRangeItemApplyConfiguration) WithMin(value v1.ResourceList) *LimitRangeItemApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrangeitem.go","code":"// WithMin sets the Min field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Min field is set to the value of the last call.\nfunc (b *LimitRangeItemApplyConfiguration) WithMin(value v1.ResourceList) *LimitRangeItemApplyConfiguration {\n\tb.Min = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100021664,"name":"WithDefault","signature":"func (b *LimitRangeItemApplyConfiguration) WithDefault(value v1.ResourceList) *LimitRangeItemApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrangeitem.go","code":"// WithDefault sets the Default field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Default field is set to the value of the last call.\nfunc (b *LimitRangeItemApplyConfiguration) WithDefault(value v1.ResourceList) *LimitRangeItemApplyConfiguration {\n\tb.Default = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100021665,"name":"WithDefaultRequest","signature":"func (b *LimitRangeItemApplyConfiguration) WithDefaultRequest(value v1.ResourceList) *LimitRangeItemApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrangeitem.go","code":"// WithDefaultRequest sets the DefaultRequest field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DefaultRequest field is set to the value of the last call.\nfunc (b *LimitRangeItemApplyConfiguration) WithDefaultRequest(value v1.ResourceList) *LimitRangeItemApplyConfiguration {\n\tb.DefaultRequest = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100021666,"name":"WithMaxLimitRequestRatio","signature":"func (b *LimitRangeItemApplyConfiguration) WithMaxLimitRequestRatio(value v1.ResourceList) *LimitRangeItemApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrangeitem.go","code":"// WithMaxLimitRequestRatio sets the MaxLimitRequestRatio field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MaxLimitRequestRatio field is set to the value of the last call.\nfunc (b *LimitRangeItemApplyConfiguration) WithMaxLimitRequestRatio(value v1.ResourceList) *LimitRangeItemApplyConfiguration {\n\tb.MaxLimitRequestRatio = \u0026value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100021667,"name":"LimitRangeSpec","signature":"func LimitRangeSpec() *LimitRangeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrangespec.go","code":"// LimitRangeSpecApplyConfiguration constructs an declarative configuration of the LimitRangeSpec type for use with\n// apply.\nfunc LimitRangeSpec() *LimitRangeSpecApplyConfiguration {\n\treturn \u0026LimitRangeSpecApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100021668,"name":"WithLimits","signature":"func (b *LimitRangeSpecApplyConfiguration) WithLimits(values ...*LimitRangeItemApplyConfiguration) *LimitRangeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/limitrangespec.go","code":"// WithLimits adds the given value to the Limits field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Limits field.\nfunc (b *LimitRangeSpecApplyConfiguration) WithLimits(values ...*LimitRangeItemApplyConfiguration) *LimitRangeSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithLimits\")\n\t\t}\n\t\tb.Limits = append(b.Limits, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100021669,"name":"LoadBalancerIngress","signature":"func LoadBalancerIngress() *LoadBalancerIngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/loadbalanceringress.go","code":"// LoadBalancerIngressApplyConfiguration constructs an declarative configuration of the LoadBalancerIngress type for use with\n// apply.\nfunc LoadBalancerIngress() *LoadBalancerIngressApplyConfiguration {\n\treturn \u0026LoadBalancerIngressApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100021670,"name":"WithIP","signature":"func (b *LoadBalancerIngressApplyConfiguration) WithIP(value string) *LoadBalancerIngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/loadbalanceringress.go","code":"// WithIP sets the IP field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the IP field is set to the value of the last call.\nfunc (b *LoadBalancerIngressApplyConfiguration) WithIP(value string) *LoadBalancerIngressApplyConfiguration {\n\tb.IP = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100021671,"name":"WithHostname","signature":"func (b *LoadBalancerIngressApplyConfiguration) WithHostname(value string) *LoadBalancerIngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/loadbalanceringress.go","code":"// WithHostname sets the Hostname field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Hostname field is set to the value of the last call.\nfunc (b *LoadBalancerIngressApplyConfiguration) WithHostname(value string) *LoadBalancerIngressApplyConfiguration {\n\tb.Hostname = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100021672,"name":"WithPorts","signature":"func (b *LoadBalancerIngressApplyConfiguration) WithPorts(values ...*PortStatusApplyConfiguration) *LoadBalancerIngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/loadbalanceringress.go","code":"// WithPorts adds the given value to the Ports field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Ports field.\nfunc (b *LoadBalancerIngressApplyConfiguration) WithPorts(values ...*PortStatusApplyConfiguration) *LoadBalancerIngressApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPorts\")\n\t\t}\n\t\tb.Ports = append(b.Ports, *values[i])\n\t}\n\treturn b\n}","line":{"from":51,"to":62}} {"id":100021673,"name":"LoadBalancerStatus","signature":"func LoadBalancerStatus() *LoadBalancerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/loadbalancerstatus.go","code":"// LoadBalancerStatusApplyConfiguration constructs an declarative configuration of the LoadBalancerStatus type for use with\n// apply.\nfunc LoadBalancerStatus() *LoadBalancerStatusApplyConfiguration {\n\treturn \u0026LoadBalancerStatusApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100021674,"name":"WithIngress","signature":"func (b *LoadBalancerStatusApplyConfiguration) WithIngress(values ...*LoadBalancerIngressApplyConfiguration) *LoadBalancerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/loadbalancerstatus.go","code":"// WithIngress adds the given value to the Ingress field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Ingress field.\nfunc (b *LoadBalancerStatusApplyConfiguration) WithIngress(values ...*LoadBalancerIngressApplyConfiguration) *LoadBalancerStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithIngress\")\n\t\t}\n\t\tb.Ingress = append(b.Ingress, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100021675,"name":"LocalObjectReference","signature":"func LocalObjectReference() *LocalObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/localobjectreference.go","code":"// LocalObjectReferenceApplyConfiguration constructs an declarative configuration of the LocalObjectReference type for use with\n// apply.\nfunc LocalObjectReference() *LocalObjectReferenceApplyConfiguration {\n\treturn \u0026LocalObjectReferenceApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100021676,"name":"WithName","signature":"func (b *LocalObjectReferenceApplyConfiguration) WithName(value string) *LocalObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/localobjectreference.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *LocalObjectReferenceApplyConfiguration) WithName(value string) *LocalObjectReferenceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100021677,"name":"LocalVolumeSource","signature":"func LocalVolumeSource() *LocalVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/localvolumesource.go","code":"// LocalVolumeSourceApplyConfiguration constructs an declarative configuration of the LocalVolumeSource type for use with\n// apply.\nfunc LocalVolumeSource() *LocalVolumeSourceApplyConfiguration {\n\treturn \u0026LocalVolumeSourceApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100021678,"name":"WithPath","signature":"func (b *LocalVolumeSourceApplyConfiguration) WithPath(value string) *LocalVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/localvolumesource.go","code":"// WithPath sets the Path field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Path field is set to the value of the last call.\nfunc (b *LocalVolumeSourceApplyConfiguration) WithPath(value string) *LocalVolumeSourceApplyConfiguration {\n\tb.Path = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100021679,"name":"WithFSType","signature":"func (b *LocalVolumeSourceApplyConfiguration) WithFSType(value string) *LocalVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/localvolumesource.go","code":"// WithFSType sets the FSType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSType field is set to the value of the last call.\nfunc (b *LocalVolumeSourceApplyConfiguration) WithFSType(value string) *LocalVolumeSourceApplyConfiguration {\n\tb.FSType = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100021680,"name":"Namespace","signature":"func Namespace(name string) *NamespaceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespace.go","code":"// Namespace constructs an declarative configuration of the Namespace type for use with\n// apply.\nfunc Namespace(name string) *NamespaceApplyConfiguration {\n\tb := \u0026NamespaceApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"Namespace\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b\n}","line":{"from":39,"to":47}} {"id":100021681,"name":"ExtractNamespace","signature":"func ExtractNamespace(namespace *apicorev1.Namespace, fieldManager string) (*NamespaceApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespace.go","code":"// ExtractNamespace extracts the applied configuration owned by fieldManager from\n// namespace. If no managedFields are found in namespace for fieldManager, a\n// NamespaceApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// namespace must be a unmodified Namespace API object that was retrieved from the Kubernetes API.\n// ExtractNamespace provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractNamespace(namespace *apicorev1.Namespace, fieldManager string) (*NamespaceApplyConfiguration, error) {\n\treturn extractNamespace(namespace, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100021682,"name":"ExtractNamespaceStatus","signature":"func ExtractNamespaceStatus(namespace *apicorev1.Namespace, fieldManager string) (*NamespaceApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespace.go","code":"// ExtractNamespaceStatus is the same as ExtractNamespace except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractNamespaceStatus(namespace *apicorev1.Namespace, fieldManager string) (*NamespaceApplyConfiguration, error) {\n\treturn extractNamespace(namespace, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100021683,"name":"extractNamespace","signature":"func extractNamespace(namespace *apicorev1.Namespace, fieldManager string, subresource string) (*NamespaceApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespace.go","code":"func extractNamespace(namespace *apicorev1.Namespace, fieldManager string, subresource string) (*NamespaceApplyConfiguration, error) {\n\tb := \u0026NamespaceApplyConfiguration{}\n\terr := managedfields.ExtractInto(namespace, internal.Parser().Type(\"io.k8s.api.core.v1.Namespace\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(namespace.Name)\n\n\tb.WithKind(\"Namespace\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b, nil\n}","line":{"from":71,"to":82}} {"id":100021684,"name":"WithKind","signature":"func (b *NamespaceApplyConfiguration) WithKind(value string) *NamespaceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespace.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *NamespaceApplyConfiguration) WithKind(value string) *NamespaceApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100021685,"name":"WithAPIVersion","signature":"func (b *NamespaceApplyConfiguration) WithAPIVersion(value string) *NamespaceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespace.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *NamespaceApplyConfiguration) WithAPIVersion(value string) *NamespaceApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100021686,"name":"WithName","signature":"func (b *NamespaceApplyConfiguration) WithName(value string) *NamespaceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespace.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *NamespaceApplyConfiguration) WithName(value string) *NamespaceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":100,"to":107}} {"id":100021687,"name":"WithGenerateName","signature":"func (b *NamespaceApplyConfiguration) WithGenerateName(value string) *NamespaceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespace.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *NamespaceApplyConfiguration) WithGenerateName(value string) *NamespaceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":109,"to":116}} {"id":100021688,"name":"WithNamespace","signature":"func (b *NamespaceApplyConfiguration) WithNamespace(value string) *NamespaceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespace.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *NamespaceApplyConfiguration) WithNamespace(value string) *NamespaceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":118,"to":125}} {"id":100021689,"name":"WithUID","signature":"func (b *NamespaceApplyConfiguration) WithUID(value types.UID) *NamespaceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespace.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *NamespaceApplyConfiguration) WithUID(value types.UID) *NamespaceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":127,"to":134}} {"id":100021690,"name":"WithResourceVersion","signature":"func (b *NamespaceApplyConfiguration) WithResourceVersion(value string) *NamespaceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespace.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *NamespaceApplyConfiguration) WithResourceVersion(value string) *NamespaceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":136,"to":143}} {"id":100021691,"name":"WithGeneration","signature":"func (b *NamespaceApplyConfiguration) WithGeneration(value int64) *NamespaceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespace.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *NamespaceApplyConfiguration) WithGeneration(value int64) *NamespaceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":145,"to":152}} {"id":100021692,"name":"WithCreationTimestamp","signature":"func (b *NamespaceApplyConfiguration) WithCreationTimestamp(value metav1.Time) *NamespaceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespace.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *NamespaceApplyConfiguration) WithCreationTimestamp(value metav1.Time) *NamespaceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":154,"to":161}} {"id":100021693,"name":"WithDeletionTimestamp","signature":"func (b *NamespaceApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *NamespaceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespace.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *NamespaceApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *NamespaceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":163,"to":170}} {"id":100021694,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *NamespaceApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *NamespaceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespace.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *NamespaceApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *NamespaceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":172,"to":179}} {"id":100021695,"name":"WithLabels","signature":"func (b *NamespaceApplyConfiguration) WithLabels(entries map[string]string) *NamespaceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespace.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *NamespaceApplyConfiguration) WithLabels(entries map[string]string) *NamespaceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":181,"to":194}} {"id":100021696,"name":"WithAnnotations","signature":"func (b *NamespaceApplyConfiguration) WithAnnotations(entries map[string]string) *NamespaceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespace.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *NamespaceApplyConfiguration) WithAnnotations(entries map[string]string) *NamespaceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100021697,"name":"WithOwnerReferences","signature":"func (b *NamespaceApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *NamespaceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespace.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *NamespaceApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *NamespaceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":211,"to":223}} {"id":100021698,"name":"WithFinalizers","signature":"func (b *NamespaceApplyConfiguration) WithFinalizers(values ...string) *NamespaceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespace.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *NamespaceApplyConfiguration) WithFinalizers(values ...string) *NamespaceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":225,"to":234}} {"id":100021699,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *NamespaceApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespace.go","code":"func (b *NamespaceApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":236,"to":240}} {"id":100021700,"name":"WithSpec","signature":"func (b *NamespaceApplyConfiguration) WithSpec(value *NamespaceSpecApplyConfiguration) *NamespaceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespace.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *NamespaceApplyConfiguration) WithSpec(value *NamespaceSpecApplyConfiguration) *NamespaceApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":242,"to":248}} {"id":100021701,"name":"WithStatus","signature":"func (b *NamespaceApplyConfiguration) WithStatus(value *NamespaceStatusApplyConfiguration) *NamespaceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespace.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *NamespaceApplyConfiguration) WithStatus(value *NamespaceStatusApplyConfiguration) *NamespaceApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":250,"to":256}} {"id":100021702,"name":"NamespaceCondition","signature":"func NamespaceCondition() *NamespaceConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespacecondition.go","code":"// NamespaceConditionApplyConfiguration constructs an declarative configuration of the NamespaceCondition type for use with\n// apply.\nfunc NamespaceCondition() *NamespaceConditionApplyConfiguration {\n\treturn \u0026NamespaceConditionApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100021703,"name":"WithType","signature":"func (b *NamespaceConditionApplyConfiguration) WithType(value v1.NamespaceConditionType) *NamespaceConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespacecondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *NamespaceConditionApplyConfiguration) WithType(value v1.NamespaceConditionType) *NamespaceConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100021704,"name":"WithStatus","signature":"func (b *NamespaceConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *NamespaceConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespacecondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *NamespaceConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *NamespaceConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100021705,"name":"WithLastTransitionTime","signature":"func (b *NamespaceConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *NamespaceConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespacecondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *NamespaceConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *NamespaceConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100021706,"name":"WithReason","signature":"func (b *NamespaceConditionApplyConfiguration) WithReason(value string) *NamespaceConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespacecondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *NamespaceConditionApplyConfiguration) WithReason(value string) *NamespaceConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100021707,"name":"WithMessage","signature":"func (b *NamespaceConditionApplyConfiguration) WithMessage(value string) *NamespaceConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespacecondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *NamespaceConditionApplyConfiguration) WithMessage(value string) *NamespaceConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100021708,"name":"NamespaceSpec","signature":"func NamespaceSpec() *NamespaceSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespacespec.go","code":"// NamespaceSpecApplyConfiguration constructs an declarative configuration of the NamespaceSpec type for use with\n// apply.\nfunc NamespaceSpec() *NamespaceSpecApplyConfiguration {\n\treturn \u0026NamespaceSpecApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100021709,"name":"WithFinalizers","signature":"func (b *NamespaceSpecApplyConfiguration) WithFinalizers(values ...v1.FinalizerName) *NamespaceSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespacespec.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *NamespaceSpecApplyConfiguration) WithFinalizers(values ...v1.FinalizerName) *NamespaceSpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":37,"to":45}} {"id":100021710,"name":"NamespaceStatus","signature":"func NamespaceStatus() *NamespaceStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespacestatus.go","code":"// NamespaceStatusApplyConfiguration constructs an declarative configuration of the NamespaceStatus type for use with\n// apply.\nfunc NamespaceStatus() *NamespaceStatusApplyConfiguration {\n\treturn \u0026NamespaceStatusApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100021711,"name":"WithPhase","signature":"func (b *NamespaceStatusApplyConfiguration) WithPhase(value v1.NamespacePhase) *NamespaceStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespacestatus.go","code":"// WithPhase sets the Phase field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Phase field is set to the value of the last call.\nfunc (b *NamespaceStatusApplyConfiguration) WithPhase(value v1.NamespacePhase) *NamespaceStatusApplyConfiguration {\n\tb.Phase = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100021712,"name":"WithConditions","signature":"func (b *NamespaceStatusApplyConfiguration) WithConditions(values ...*NamespaceConditionApplyConfiguration) *NamespaceStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/namespacestatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *NamespaceStatusApplyConfiguration) WithConditions(values ...*NamespaceConditionApplyConfiguration) *NamespaceStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":46,"to":57}} {"id":100021713,"name":"NFSVolumeSource","signature":"func NFSVolumeSource() *NFSVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nfsvolumesource.go","code":"// NFSVolumeSourceApplyConfiguration constructs an declarative configuration of the NFSVolumeSource type for use with\n// apply.\nfunc NFSVolumeSource() *NFSVolumeSourceApplyConfiguration {\n\treturn \u0026NFSVolumeSourceApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100021714,"name":"WithServer","signature":"func (b *NFSVolumeSourceApplyConfiguration) WithServer(value string) *NFSVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nfsvolumesource.go","code":"// WithServer sets the Server field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Server field is set to the value of the last call.\nfunc (b *NFSVolumeSourceApplyConfiguration) WithServer(value string) *NFSVolumeSourceApplyConfiguration {\n\tb.Server = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100021715,"name":"WithPath","signature":"func (b *NFSVolumeSourceApplyConfiguration) WithPath(value string) *NFSVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nfsvolumesource.go","code":"// WithPath sets the Path field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Path field is set to the value of the last call.\nfunc (b *NFSVolumeSourceApplyConfiguration) WithPath(value string) *NFSVolumeSourceApplyConfiguration {\n\tb.Path = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100021716,"name":"WithReadOnly","signature":"func (b *NFSVolumeSourceApplyConfiguration) WithReadOnly(value bool) *NFSVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nfsvolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *NFSVolumeSourceApplyConfiguration) WithReadOnly(value bool) *NFSVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100021717,"name":"Node","signature":"func Node(name string) *NodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/node.go","code":"// Node constructs an declarative configuration of the Node type for use with\n// apply.\nfunc Node(name string) *NodeApplyConfiguration {\n\tb := \u0026NodeApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"Node\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b\n}","line":{"from":39,"to":47}} {"id":100021718,"name":"ExtractNode","signature":"func ExtractNode(node *apicorev1.Node, fieldManager string) (*NodeApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/node.go","code":"// ExtractNode extracts the applied configuration owned by fieldManager from\n// node. If no managedFields are found in node for fieldManager, a\n// NodeApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// node must be a unmodified Node API object that was retrieved from the Kubernetes API.\n// ExtractNode provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractNode(node *apicorev1.Node, fieldManager string) (*NodeApplyConfiguration, error) {\n\treturn extractNode(node, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100021719,"name":"ExtractNodeStatus","signature":"func ExtractNodeStatus(node *apicorev1.Node, fieldManager string) (*NodeApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/node.go","code":"// ExtractNodeStatus is the same as ExtractNode except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractNodeStatus(node *apicorev1.Node, fieldManager string) (*NodeApplyConfiguration, error) {\n\treturn extractNode(node, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100021720,"name":"extractNode","signature":"func extractNode(node *apicorev1.Node, fieldManager string, subresource string) (*NodeApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/node.go","code":"func extractNode(node *apicorev1.Node, fieldManager string, subresource string) (*NodeApplyConfiguration, error) {\n\tb := \u0026NodeApplyConfiguration{}\n\terr := managedfields.ExtractInto(node, internal.Parser().Type(\"io.k8s.api.core.v1.Node\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(node.Name)\n\n\tb.WithKind(\"Node\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b, nil\n}","line":{"from":71,"to":82}} {"id":100021721,"name":"WithKind","signature":"func (b *NodeApplyConfiguration) WithKind(value string) *NodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/node.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *NodeApplyConfiguration) WithKind(value string) *NodeApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100021722,"name":"WithAPIVersion","signature":"func (b *NodeApplyConfiguration) WithAPIVersion(value string) *NodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/node.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *NodeApplyConfiguration) WithAPIVersion(value string) *NodeApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100021723,"name":"WithName","signature":"func (b *NodeApplyConfiguration) WithName(value string) *NodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/node.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *NodeApplyConfiguration) WithName(value string) *NodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":100,"to":107}} {"id":100021724,"name":"WithGenerateName","signature":"func (b *NodeApplyConfiguration) WithGenerateName(value string) *NodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/node.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *NodeApplyConfiguration) WithGenerateName(value string) *NodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":109,"to":116}} {"id":100021725,"name":"WithNamespace","signature":"func (b *NodeApplyConfiguration) WithNamespace(value string) *NodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/node.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *NodeApplyConfiguration) WithNamespace(value string) *NodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":118,"to":125}} {"id":100021726,"name":"WithUID","signature":"func (b *NodeApplyConfiguration) WithUID(value types.UID) *NodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/node.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *NodeApplyConfiguration) WithUID(value types.UID) *NodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":127,"to":134}} {"id":100021727,"name":"WithResourceVersion","signature":"func (b *NodeApplyConfiguration) WithResourceVersion(value string) *NodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/node.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *NodeApplyConfiguration) WithResourceVersion(value string) *NodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":136,"to":143}} {"id":100021728,"name":"WithGeneration","signature":"func (b *NodeApplyConfiguration) WithGeneration(value int64) *NodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/node.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *NodeApplyConfiguration) WithGeneration(value int64) *NodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":145,"to":152}} {"id":100021729,"name":"WithCreationTimestamp","signature":"func (b *NodeApplyConfiguration) WithCreationTimestamp(value metav1.Time) *NodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/node.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *NodeApplyConfiguration) WithCreationTimestamp(value metav1.Time) *NodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":154,"to":161}} {"id":100021730,"name":"WithDeletionTimestamp","signature":"func (b *NodeApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *NodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/node.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *NodeApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *NodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":163,"to":170}} {"id":100021731,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *NodeApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *NodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/node.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *NodeApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *NodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":172,"to":179}} {"id":100021732,"name":"WithLabels","signature":"func (b *NodeApplyConfiguration) WithLabels(entries map[string]string) *NodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/node.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *NodeApplyConfiguration) WithLabels(entries map[string]string) *NodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":181,"to":194}} {"id":100021733,"name":"WithAnnotations","signature":"func (b *NodeApplyConfiguration) WithAnnotations(entries map[string]string) *NodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/node.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *NodeApplyConfiguration) WithAnnotations(entries map[string]string) *NodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100021734,"name":"WithOwnerReferences","signature":"func (b *NodeApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *NodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/node.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *NodeApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *NodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":211,"to":223}} {"id":100021735,"name":"WithFinalizers","signature":"func (b *NodeApplyConfiguration) WithFinalizers(values ...string) *NodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/node.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *NodeApplyConfiguration) WithFinalizers(values ...string) *NodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":225,"to":234}} {"id":100021736,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *NodeApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/node.go","code":"func (b *NodeApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":236,"to":240}} {"id":100021737,"name":"WithSpec","signature":"func (b *NodeApplyConfiguration) WithSpec(value *NodeSpecApplyConfiguration) *NodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/node.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *NodeApplyConfiguration) WithSpec(value *NodeSpecApplyConfiguration) *NodeApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":242,"to":248}} {"id":100021738,"name":"WithStatus","signature":"func (b *NodeApplyConfiguration) WithStatus(value *NodeStatusApplyConfiguration) *NodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/node.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *NodeApplyConfiguration) WithStatus(value *NodeStatusApplyConfiguration) *NodeApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":250,"to":256}} {"id":100021739,"name":"NodeAddress","signature":"func NodeAddress() *NodeAddressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodeaddress.go","code":"// NodeAddressApplyConfiguration constructs an declarative configuration of the NodeAddress type for use with\n// apply.\nfunc NodeAddress() *NodeAddressApplyConfiguration {\n\treturn \u0026NodeAddressApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100021740,"name":"WithType","signature":"func (b *NodeAddressApplyConfiguration) WithType(value v1.NodeAddressType) *NodeAddressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodeaddress.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *NodeAddressApplyConfiguration) WithType(value v1.NodeAddressType) *NodeAddressApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100021741,"name":"WithAddress","signature":"func (b *NodeAddressApplyConfiguration) WithAddress(value string) *NodeAddressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodeaddress.go","code":"// WithAddress sets the Address field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Address field is set to the value of the last call.\nfunc (b *NodeAddressApplyConfiguration) WithAddress(value string) *NodeAddressApplyConfiguration {\n\tb.Address = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100021742,"name":"NodeAffinity","signature":"func NodeAffinity() *NodeAffinityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodeaffinity.go","code":"// NodeAffinityApplyConfiguration constructs an declarative configuration of the NodeAffinity type for use with\n// apply.\nfunc NodeAffinity() *NodeAffinityApplyConfiguration {\n\treturn \u0026NodeAffinityApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100021743,"name":"WithRequiredDuringSchedulingIgnoredDuringExecution","signature":"func (b *NodeAffinityApplyConfiguration) WithRequiredDuringSchedulingIgnoredDuringExecution(value *NodeSelectorApplyConfiguration) *NodeAffinityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodeaffinity.go","code":"// WithRequiredDuringSchedulingIgnoredDuringExecution sets the RequiredDuringSchedulingIgnoredDuringExecution field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RequiredDuringSchedulingIgnoredDuringExecution field is set to the value of the last call.\nfunc (b *NodeAffinityApplyConfiguration) WithRequiredDuringSchedulingIgnoredDuringExecution(value *NodeSelectorApplyConfiguration) *NodeAffinityApplyConfiguration {\n\tb.RequiredDuringSchedulingIgnoredDuringExecution = value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100021744,"name":"WithPreferredDuringSchedulingIgnoredDuringExecution","signature":"func (b *NodeAffinityApplyConfiguration) WithPreferredDuringSchedulingIgnoredDuringExecution(values ...*PreferredSchedulingTermApplyConfiguration) *NodeAffinityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodeaffinity.go","code":"// WithPreferredDuringSchedulingIgnoredDuringExecution adds the given value to the PreferredDuringSchedulingIgnoredDuringExecution field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the PreferredDuringSchedulingIgnoredDuringExecution field.\nfunc (b *NodeAffinityApplyConfiguration) WithPreferredDuringSchedulingIgnoredDuringExecution(values ...*PreferredSchedulingTermApplyConfiguration) *NodeAffinityApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPreferredDuringSchedulingIgnoredDuringExecution\")\n\t\t}\n\t\tb.PreferredDuringSchedulingIgnoredDuringExecution = append(b.PreferredDuringSchedulingIgnoredDuringExecution, *values[i])\n\t}\n\treturn b\n}","line":{"from":42,"to":53}} {"id":100021745,"name":"NodeCondition","signature":"func NodeCondition() *NodeConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodecondition.go","code":"// NodeConditionApplyConfiguration constructs an declarative configuration of the NodeCondition type for use with\n// apply.\nfunc NodeCondition() *NodeConditionApplyConfiguration {\n\treturn \u0026NodeConditionApplyConfiguration{}\n}","line":{"from":37,"to":41}} {"id":100021746,"name":"WithType","signature":"func (b *NodeConditionApplyConfiguration) WithType(value v1.NodeConditionType) *NodeConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodecondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *NodeConditionApplyConfiguration) WithType(value v1.NodeConditionType) *NodeConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100021747,"name":"WithStatus","signature":"func (b *NodeConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *NodeConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodecondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *NodeConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *NodeConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100021748,"name":"WithLastHeartbeatTime","signature":"func (b *NodeConditionApplyConfiguration) WithLastHeartbeatTime(value metav1.Time) *NodeConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodecondition.go","code":"// WithLastHeartbeatTime sets the LastHeartbeatTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastHeartbeatTime field is set to the value of the last call.\nfunc (b *NodeConditionApplyConfiguration) WithLastHeartbeatTime(value metav1.Time) *NodeConditionApplyConfiguration {\n\tb.LastHeartbeatTime = \u0026value\n\treturn b\n}","line":{"from":59,"to":65}} {"id":100021749,"name":"WithLastTransitionTime","signature":"func (b *NodeConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *NodeConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodecondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *NodeConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *NodeConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100021750,"name":"WithReason","signature":"func (b *NodeConditionApplyConfiguration) WithReason(value string) *NodeConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodecondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *NodeConditionApplyConfiguration) WithReason(value string) *NodeConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":75,"to":81}} {"id":100021751,"name":"WithMessage","signature":"func (b *NodeConditionApplyConfiguration) WithMessage(value string) *NodeConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodecondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *NodeConditionApplyConfiguration) WithMessage(value string) *NodeConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100021752,"name":"NodeConfigSource","signature":"func NodeConfigSource() *NodeConfigSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodeconfigsource.go","code":"// NodeConfigSourceApplyConfiguration constructs an declarative configuration of the NodeConfigSource type for use with\n// apply.\nfunc NodeConfigSource() *NodeConfigSourceApplyConfiguration {\n\treturn \u0026NodeConfigSourceApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100021753,"name":"WithConfigMap","signature":"func (b *NodeConfigSourceApplyConfiguration) WithConfigMap(value *ConfigMapNodeConfigSourceApplyConfiguration) *NodeConfigSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodeconfigsource.go","code":"// WithConfigMap sets the ConfigMap field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ConfigMap field is set to the value of the last call.\nfunc (b *NodeConfigSourceApplyConfiguration) WithConfigMap(value *ConfigMapNodeConfigSourceApplyConfiguration) *NodeConfigSourceApplyConfiguration {\n\tb.ConfigMap = value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100021754,"name":"NodeConfigStatus","signature":"func NodeConfigStatus() *NodeConfigStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodeconfigstatus.go","code":"// NodeConfigStatusApplyConfiguration constructs an declarative configuration of the NodeConfigStatus type for use with\n// apply.\nfunc NodeConfigStatus() *NodeConfigStatusApplyConfiguration {\n\treturn \u0026NodeConfigStatusApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100021755,"name":"WithAssigned","signature":"func (b *NodeConfigStatusApplyConfiguration) WithAssigned(value *NodeConfigSourceApplyConfiguration) *NodeConfigStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodeconfigstatus.go","code":"// WithAssigned sets the Assigned field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Assigned field is set to the value of the last call.\nfunc (b *NodeConfigStatusApplyConfiguration) WithAssigned(value *NodeConfigSourceApplyConfiguration) *NodeConfigStatusApplyConfiguration {\n\tb.Assigned = value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100021756,"name":"WithActive","signature":"func (b *NodeConfigStatusApplyConfiguration) WithActive(value *NodeConfigSourceApplyConfiguration) *NodeConfigStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodeconfigstatus.go","code":"// WithActive sets the Active field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Active field is set to the value of the last call.\nfunc (b *NodeConfigStatusApplyConfiguration) WithActive(value *NodeConfigSourceApplyConfiguration) *NodeConfigStatusApplyConfiguration {\n\tb.Active = value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100021757,"name":"WithLastKnownGood","signature":"func (b *NodeConfigStatusApplyConfiguration) WithLastKnownGood(value *NodeConfigSourceApplyConfiguration) *NodeConfigStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodeconfigstatus.go","code":"// WithLastKnownGood sets the LastKnownGood field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastKnownGood field is set to the value of the last call.\nfunc (b *NodeConfigStatusApplyConfiguration) WithLastKnownGood(value *NodeConfigSourceApplyConfiguration) *NodeConfigStatusApplyConfiguration {\n\tb.LastKnownGood = value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100021758,"name":"WithError","signature":"func (b *NodeConfigStatusApplyConfiguration) WithError(value string) *NodeConfigStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodeconfigstatus.go","code":"// WithError sets the Error field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Error field is set to the value of the last call.\nfunc (b *NodeConfigStatusApplyConfiguration) WithError(value string) *NodeConfigStatusApplyConfiguration {\n\tb.Error = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100021759,"name":"NodeDaemonEndpoints","signature":"func NodeDaemonEndpoints() *NodeDaemonEndpointsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodedaemonendpoints.go","code":"// NodeDaemonEndpointsApplyConfiguration constructs an declarative configuration of the NodeDaemonEndpoints type for use with\n// apply.\nfunc NodeDaemonEndpoints() *NodeDaemonEndpointsApplyConfiguration {\n\treturn \u0026NodeDaemonEndpointsApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100021760,"name":"WithKubeletEndpoint","signature":"func (b *NodeDaemonEndpointsApplyConfiguration) WithKubeletEndpoint(value *DaemonEndpointApplyConfiguration) *NodeDaemonEndpointsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodedaemonendpoints.go","code":"// WithKubeletEndpoint sets the KubeletEndpoint field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the KubeletEndpoint field is set to the value of the last call.\nfunc (b *NodeDaemonEndpointsApplyConfiguration) WithKubeletEndpoint(value *DaemonEndpointApplyConfiguration) *NodeDaemonEndpointsApplyConfiguration {\n\tb.KubeletEndpoint = value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100021761,"name":"NodeSelector","signature":"func NodeSelector() *NodeSelectorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodeselector.go","code":"// NodeSelectorApplyConfiguration constructs an declarative configuration of the NodeSelector type for use with\n// apply.\nfunc NodeSelector() *NodeSelectorApplyConfiguration {\n\treturn \u0026NodeSelectorApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100021762,"name":"WithNodeSelectorTerms","signature":"func (b *NodeSelectorApplyConfiguration) WithNodeSelectorTerms(values ...*NodeSelectorTermApplyConfiguration) *NodeSelectorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodeselector.go","code":"// WithNodeSelectorTerms adds the given value to the NodeSelectorTerms field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the NodeSelectorTerms field.\nfunc (b *NodeSelectorApplyConfiguration) WithNodeSelectorTerms(values ...*NodeSelectorTermApplyConfiguration) *NodeSelectorApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithNodeSelectorTerms\")\n\t\t}\n\t\tb.NodeSelectorTerms = append(b.NodeSelectorTerms, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100021763,"name":"NodeSelectorRequirement","signature":"func NodeSelectorRequirement() *NodeSelectorRequirementApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodeselectorrequirement.go","code":"// NodeSelectorRequirementApplyConfiguration constructs an declarative configuration of the NodeSelectorRequirement type for use with\n// apply.\nfunc NodeSelectorRequirement() *NodeSelectorRequirementApplyConfiguration {\n\treturn \u0026NodeSelectorRequirementApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100021764,"name":"WithKey","signature":"func (b *NodeSelectorRequirementApplyConfiguration) WithKey(value string) *NodeSelectorRequirementApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodeselectorrequirement.go","code":"// WithKey sets the Key field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Key field is set to the value of the last call.\nfunc (b *NodeSelectorRequirementApplyConfiguration) WithKey(value string) *NodeSelectorRequirementApplyConfiguration {\n\tb.Key = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100021765,"name":"WithOperator","signature":"func (b *NodeSelectorRequirementApplyConfiguration) WithOperator(value v1.NodeSelectorOperator) *NodeSelectorRequirementApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodeselectorrequirement.go","code":"// WithOperator sets the Operator field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Operator field is set to the value of the last call.\nfunc (b *NodeSelectorRequirementApplyConfiguration) WithOperator(value v1.NodeSelectorOperator) *NodeSelectorRequirementApplyConfiguration {\n\tb.Operator = \u0026value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100021766,"name":"WithValues","signature":"func (b *NodeSelectorRequirementApplyConfiguration) WithValues(values ...string) *NodeSelectorRequirementApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodeselectorrequirement.go","code":"// WithValues adds the given value to the Values field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Values field.\nfunc (b *NodeSelectorRequirementApplyConfiguration) WithValues(values ...string) *NodeSelectorRequirementApplyConfiguration {\n\tfor i := range values {\n\t\tb.Values = append(b.Values, values[i])\n\t}\n\treturn b\n}","line":{"from":55,"to":63}} {"id":100021767,"name":"NodeSelectorTerm","signature":"func NodeSelectorTerm() *NodeSelectorTermApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodeselectorterm.go","code":"// NodeSelectorTermApplyConfiguration constructs an declarative configuration of the NodeSelectorTerm type for use with\n// apply.\nfunc NodeSelectorTerm() *NodeSelectorTermApplyConfiguration {\n\treturn \u0026NodeSelectorTermApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100021768,"name":"WithMatchExpressions","signature":"func (b *NodeSelectorTermApplyConfiguration) WithMatchExpressions(values ...*NodeSelectorRequirementApplyConfiguration) *NodeSelectorTermApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodeselectorterm.go","code":"// WithMatchExpressions adds the given value to the MatchExpressions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the MatchExpressions field.\nfunc (b *NodeSelectorTermApplyConfiguration) WithMatchExpressions(values ...*NodeSelectorRequirementApplyConfiguration) *NodeSelectorTermApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithMatchExpressions\")\n\t\t}\n\t\tb.MatchExpressions = append(b.MatchExpressions, *values[i])\n\t}\n\treturn b\n}","line":{"from":34,"to":45}} {"id":100021769,"name":"WithMatchFields","signature":"func (b *NodeSelectorTermApplyConfiguration) WithMatchFields(values ...*NodeSelectorRequirementApplyConfiguration) *NodeSelectorTermApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodeselectorterm.go","code":"// WithMatchFields adds the given value to the MatchFields field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the MatchFields field.\nfunc (b *NodeSelectorTermApplyConfiguration) WithMatchFields(values ...*NodeSelectorRequirementApplyConfiguration) *NodeSelectorTermApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithMatchFields\")\n\t\t}\n\t\tb.MatchFields = append(b.MatchFields, *values[i])\n\t}\n\treturn b\n}","line":{"from":47,"to":58}} {"id":100021770,"name":"NodeSpec","signature":"func NodeSpec() *NodeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodespec.go","code":"// NodeSpecApplyConfiguration constructs an declarative configuration of the NodeSpec type for use with\n// apply.\nfunc NodeSpec() *NodeSpecApplyConfiguration {\n\treturn \u0026NodeSpecApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100021771,"name":"WithPodCIDR","signature":"func (b *NodeSpecApplyConfiguration) WithPodCIDR(value string) *NodeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodespec.go","code":"// WithPodCIDR sets the PodCIDR field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PodCIDR field is set to the value of the last call.\nfunc (b *NodeSpecApplyConfiguration) WithPodCIDR(value string) *NodeSpecApplyConfiguration {\n\tb.PodCIDR = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100021772,"name":"WithPodCIDRs","signature":"func (b *NodeSpecApplyConfiguration) WithPodCIDRs(values ...string) *NodeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodespec.go","code":"// WithPodCIDRs adds the given value to the PodCIDRs field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the PodCIDRs field.\nfunc (b *NodeSpecApplyConfiguration) WithPodCIDRs(values ...string) *NodeSpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.PodCIDRs = append(b.PodCIDRs, values[i])\n\t}\n\treturn b\n}","line":{"from":47,"to":55}} {"id":100021773,"name":"WithProviderID","signature":"func (b *NodeSpecApplyConfiguration) WithProviderID(value string) *NodeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodespec.go","code":"// WithProviderID sets the ProviderID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ProviderID field is set to the value of the last call.\nfunc (b *NodeSpecApplyConfiguration) WithProviderID(value string) *NodeSpecApplyConfiguration {\n\tb.ProviderID = \u0026value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100021774,"name":"WithUnschedulable","signature":"func (b *NodeSpecApplyConfiguration) WithUnschedulable(value bool) *NodeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodespec.go","code":"// WithUnschedulable sets the Unschedulable field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Unschedulable field is set to the value of the last call.\nfunc (b *NodeSpecApplyConfiguration) WithUnschedulable(value bool) *NodeSpecApplyConfiguration {\n\tb.Unschedulable = \u0026value\n\treturn b\n}","line":{"from":65,"to":71}} {"id":100021775,"name":"WithTaints","signature":"func (b *NodeSpecApplyConfiguration) WithTaints(values ...*TaintApplyConfiguration) *NodeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodespec.go","code":"// WithTaints adds the given value to the Taints field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Taints field.\nfunc (b *NodeSpecApplyConfiguration) WithTaints(values ...*TaintApplyConfiguration) *NodeSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithTaints\")\n\t\t}\n\t\tb.Taints = append(b.Taints, *values[i])\n\t}\n\treturn b\n}","line":{"from":73,"to":84}} {"id":100021776,"name":"WithConfigSource","signature":"func (b *NodeSpecApplyConfiguration) WithConfigSource(value *NodeConfigSourceApplyConfiguration) *NodeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodespec.go","code":"// WithConfigSource sets the ConfigSource field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ConfigSource field is set to the value of the last call.\nfunc (b *NodeSpecApplyConfiguration) WithConfigSource(value *NodeConfigSourceApplyConfiguration) *NodeSpecApplyConfiguration {\n\tb.ConfigSource = value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100021777,"name":"WithDoNotUseExternalID","signature":"func (b *NodeSpecApplyConfiguration) WithDoNotUseExternalID(value string) *NodeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodespec.go","code":"// WithDoNotUseExternalID sets the DoNotUseExternalID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DoNotUseExternalID field is set to the value of the last call.\nfunc (b *NodeSpecApplyConfiguration) WithDoNotUseExternalID(value string) *NodeSpecApplyConfiguration {\n\tb.DoNotUseExternalID = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100021778,"name":"NodeStatus","signature":"func NodeStatus() *NodeStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodestatus.go","code":"// NodeStatusApplyConfiguration constructs an declarative configuration of the NodeStatus type for use with\n// apply.\nfunc NodeStatus() *NodeStatusApplyConfiguration {\n\treturn \u0026NodeStatusApplyConfiguration{}\n}","line":{"from":41,"to":45}} {"id":100021779,"name":"WithCapacity","signature":"func (b *NodeStatusApplyConfiguration) WithCapacity(value v1.ResourceList) *NodeStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodestatus.go","code":"// WithCapacity sets the Capacity field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Capacity field is set to the value of the last call.\nfunc (b *NodeStatusApplyConfiguration) WithCapacity(value v1.ResourceList) *NodeStatusApplyConfiguration {\n\tb.Capacity = \u0026value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100021780,"name":"WithAllocatable","signature":"func (b *NodeStatusApplyConfiguration) WithAllocatable(value v1.ResourceList) *NodeStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodestatus.go","code":"// WithAllocatable sets the Allocatable field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Allocatable field is set to the value of the last call.\nfunc (b *NodeStatusApplyConfiguration) WithAllocatable(value v1.ResourceList) *NodeStatusApplyConfiguration {\n\tb.Allocatable = \u0026value\n\treturn b\n}","line":{"from":55,"to":61}} {"id":100021781,"name":"WithPhase","signature":"func (b *NodeStatusApplyConfiguration) WithPhase(value v1.NodePhase) *NodeStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodestatus.go","code":"// WithPhase sets the Phase field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Phase field is set to the value of the last call.\nfunc (b *NodeStatusApplyConfiguration) WithPhase(value v1.NodePhase) *NodeStatusApplyConfiguration {\n\tb.Phase = \u0026value\n\treturn b\n}","line":{"from":63,"to":69}} {"id":100021782,"name":"WithConditions","signature":"func (b *NodeStatusApplyConfiguration) WithConditions(values ...*NodeConditionApplyConfiguration) *NodeStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodestatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *NodeStatusApplyConfiguration) WithConditions(values ...*NodeConditionApplyConfiguration) *NodeStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":71,"to":82}} {"id":100021783,"name":"WithAddresses","signature":"func (b *NodeStatusApplyConfiguration) WithAddresses(values ...*NodeAddressApplyConfiguration) *NodeStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodestatus.go","code":"// WithAddresses adds the given value to the Addresses field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Addresses field.\nfunc (b *NodeStatusApplyConfiguration) WithAddresses(values ...*NodeAddressApplyConfiguration) *NodeStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithAddresses\")\n\t\t}\n\t\tb.Addresses = append(b.Addresses, *values[i])\n\t}\n\treturn b\n}","line":{"from":84,"to":95}} {"id":100021784,"name":"WithDaemonEndpoints","signature":"func (b *NodeStatusApplyConfiguration) WithDaemonEndpoints(value *NodeDaemonEndpointsApplyConfiguration) *NodeStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodestatus.go","code":"// WithDaemonEndpoints sets the DaemonEndpoints field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DaemonEndpoints field is set to the value of the last call.\nfunc (b *NodeStatusApplyConfiguration) WithDaemonEndpoints(value *NodeDaemonEndpointsApplyConfiguration) *NodeStatusApplyConfiguration {\n\tb.DaemonEndpoints = value\n\treturn b\n}","line":{"from":97,"to":103}} {"id":100021785,"name":"WithNodeInfo","signature":"func (b *NodeStatusApplyConfiguration) WithNodeInfo(value *NodeSystemInfoApplyConfiguration) *NodeStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodestatus.go","code":"// WithNodeInfo sets the NodeInfo field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NodeInfo field is set to the value of the last call.\nfunc (b *NodeStatusApplyConfiguration) WithNodeInfo(value *NodeSystemInfoApplyConfiguration) *NodeStatusApplyConfiguration {\n\tb.NodeInfo = value\n\treturn b\n}","line":{"from":105,"to":111}} {"id":100021786,"name":"WithImages","signature":"func (b *NodeStatusApplyConfiguration) WithImages(values ...*ContainerImageApplyConfiguration) *NodeStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodestatus.go","code":"// WithImages adds the given value to the Images field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Images field.\nfunc (b *NodeStatusApplyConfiguration) WithImages(values ...*ContainerImageApplyConfiguration) *NodeStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithImages\")\n\t\t}\n\t\tb.Images = append(b.Images, *values[i])\n\t}\n\treturn b\n}","line":{"from":113,"to":124}} {"id":100021787,"name":"WithVolumesInUse","signature":"func (b *NodeStatusApplyConfiguration) WithVolumesInUse(values ...v1.UniqueVolumeName) *NodeStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodestatus.go","code":"// WithVolumesInUse adds the given value to the VolumesInUse field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the VolumesInUse field.\nfunc (b *NodeStatusApplyConfiguration) WithVolumesInUse(values ...v1.UniqueVolumeName) *NodeStatusApplyConfiguration {\n\tfor i := range values {\n\t\tb.VolumesInUse = append(b.VolumesInUse, values[i])\n\t}\n\treturn b\n}","line":{"from":126,"to":134}} {"id":100021788,"name":"WithVolumesAttached","signature":"func (b *NodeStatusApplyConfiguration) WithVolumesAttached(values ...*AttachedVolumeApplyConfiguration) *NodeStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodestatus.go","code":"// WithVolumesAttached adds the given value to the VolumesAttached field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the VolumesAttached field.\nfunc (b *NodeStatusApplyConfiguration) WithVolumesAttached(values ...*AttachedVolumeApplyConfiguration) *NodeStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithVolumesAttached\")\n\t\t}\n\t\tb.VolumesAttached = append(b.VolumesAttached, *values[i])\n\t}\n\treturn b\n}","line":{"from":136,"to":147}} {"id":100021789,"name":"WithConfig","signature":"func (b *NodeStatusApplyConfiguration) WithConfig(value *NodeConfigStatusApplyConfiguration) *NodeStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodestatus.go","code":"// WithConfig sets the Config field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Config field is set to the value of the last call.\nfunc (b *NodeStatusApplyConfiguration) WithConfig(value *NodeConfigStatusApplyConfiguration) *NodeStatusApplyConfiguration {\n\tb.Config = value\n\treturn b\n}","line":{"from":149,"to":155}} {"id":100021790,"name":"NodeSystemInfo","signature":"func NodeSystemInfo() *NodeSystemInfoApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodesysteminfo.go","code":"// NodeSystemInfoApplyConfiguration constructs an declarative configuration of the NodeSystemInfo type for use with\n// apply.\nfunc NodeSystemInfo() *NodeSystemInfoApplyConfiguration {\n\treturn \u0026NodeSystemInfoApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100021791,"name":"WithMachineID","signature":"func (b *NodeSystemInfoApplyConfiguration) WithMachineID(value string) *NodeSystemInfoApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodesysteminfo.go","code":"// WithMachineID sets the MachineID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MachineID field is set to the value of the last call.\nfunc (b *NodeSystemInfoApplyConfiguration) WithMachineID(value string) *NodeSystemInfoApplyConfiguration {\n\tb.MachineID = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100021792,"name":"WithSystemUUID","signature":"func (b *NodeSystemInfoApplyConfiguration) WithSystemUUID(value string) *NodeSystemInfoApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodesysteminfo.go","code":"// WithSystemUUID sets the SystemUUID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SystemUUID field is set to the value of the last call.\nfunc (b *NodeSystemInfoApplyConfiguration) WithSystemUUID(value string) *NodeSystemInfoApplyConfiguration {\n\tb.SystemUUID = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100021793,"name":"WithBootID","signature":"func (b *NodeSystemInfoApplyConfiguration) WithBootID(value string) *NodeSystemInfoApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodesysteminfo.go","code":"// WithBootID sets the BootID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the BootID field is set to the value of the last call.\nfunc (b *NodeSystemInfoApplyConfiguration) WithBootID(value string) *NodeSystemInfoApplyConfiguration {\n\tb.BootID = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100021794,"name":"WithKernelVersion","signature":"func (b *NodeSystemInfoApplyConfiguration) WithKernelVersion(value string) *NodeSystemInfoApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodesysteminfo.go","code":"// WithKernelVersion sets the KernelVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the KernelVersion field is set to the value of the last call.\nfunc (b *NodeSystemInfoApplyConfiguration) WithKernelVersion(value string) *NodeSystemInfoApplyConfiguration {\n\tb.KernelVersion = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100021795,"name":"WithOSImage","signature":"func (b *NodeSystemInfoApplyConfiguration) WithOSImage(value string) *NodeSystemInfoApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodesysteminfo.go","code":"// WithOSImage sets the OSImage field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the OSImage field is set to the value of the last call.\nfunc (b *NodeSystemInfoApplyConfiguration) WithOSImage(value string) *NodeSystemInfoApplyConfiguration {\n\tb.OSImage = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100021796,"name":"WithContainerRuntimeVersion","signature":"func (b *NodeSystemInfoApplyConfiguration) WithContainerRuntimeVersion(value string) *NodeSystemInfoApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodesysteminfo.go","code":"// WithContainerRuntimeVersion sets the ContainerRuntimeVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ContainerRuntimeVersion field is set to the value of the last call.\nfunc (b *NodeSystemInfoApplyConfiguration) WithContainerRuntimeVersion(value string) *NodeSystemInfoApplyConfiguration {\n\tb.ContainerRuntimeVersion = \u0026value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100021797,"name":"WithKubeletVersion","signature":"func (b *NodeSystemInfoApplyConfiguration) WithKubeletVersion(value string) *NodeSystemInfoApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodesysteminfo.go","code":"// WithKubeletVersion sets the KubeletVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the KubeletVersion field is set to the value of the last call.\nfunc (b *NodeSystemInfoApplyConfiguration) WithKubeletVersion(value string) *NodeSystemInfoApplyConfiguration {\n\tb.KubeletVersion = \u0026value\n\treturn b\n}","line":{"from":90,"to":96}} {"id":100021798,"name":"WithKubeProxyVersion","signature":"func (b *NodeSystemInfoApplyConfiguration) WithKubeProxyVersion(value string) *NodeSystemInfoApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodesysteminfo.go","code":"// WithKubeProxyVersion sets the KubeProxyVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the KubeProxyVersion field is set to the value of the last call.\nfunc (b *NodeSystemInfoApplyConfiguration) WithKubeProxyVersion(value string) *NodeSystemInfoApplyConfiguration {\n\tb.KubeProxyVersion = \u0026value\n\treturn b\n}","line":{"from":98,"to":104}} {"id":100021799,"name":"WithOperatingSystem","signature":"func (b *NodeSystemInfoApplyConfiguration) WithOperatingSystem(value string) *NodeSystemInfoApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodesysteminfo.go","code":"// WithOperatingSystem sets the OperatingSystem field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the OperatingSystem field is set to the value of the last call.\nfunc (b *NodeSystemInfoApplyConfiguration) WithOperatingSystem(value string) *NodeSystemInfoApplyConfiguration {\n\tb.OperatingSystem = \u0026value\n\treturn b\n}","line":{"from":106,"to":112}} {"id":100021800,"name":"WithArchitecture","signature":"func (b *NodeSystemInfoApplyConfiguration) WithArchitecture(value string) *NodeSystemInfoApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/nodesysteminfo.go","code":"// WithArchitecture sets the Architecture field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Architecture field is set to the value of the last call.\nfunc (b *NodeSystemInfoApplyConfiguration) WithArchitecture(value string) *NodeSystemInfoApplyConfiguration {\n\tb.Architecture = \u0026value\n\treturn b\n}","line":{"from":114,"to":120}} {"id":100021801,"name":"ObjectFieldSelector","signature":"func ObjectFieldSelector() *ObjectFieldSelectorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/objectfieldselector.go","code":"// ObjectFieldSelectorApplyConfiguration constructs an declarative configuration of the ObjectFieldSelector type for use with\n// apply.\nfunc ObjectFieldSelector() *ObjectFieldSelectorApplyConfiguration {\n\treturn \u0026ObjectFieldSelectorApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100021802,"name":"WithAPIVersion","signature":"func (b *ObjectFieldSelectorApplyConfiguration) WithAPIVersion(value string) *ObjectFieldSelectorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/objectfieldselector.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ObjectFieldSelectorApplyConfiguration) WithAPIVersion(value string) *ObjectFieldSelectorApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100021803,"name":"WithFieldPath","signature":"func (b *ObjectFieldSelectorApplyConfiguration) WithFieldPath(value string) *ObjectFieldSelectorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/objectfieldselector.go","code":"// WithFieldPath sets the FieldPath field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FieldPath field is set to the value of the last call.\nfunc (b *ObjectFieldSelectorApplyConfiguration) WithFieldPath(value string) *ObjectFieldSelectorApplyConfiguration {\n\tb.FieldPath = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100021804,"name":"ObjectReference","signature":"func ObjectReference() *ObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/objectreference.go","code":"// ObjectReferenceApplyConfiguration constructs an declarative configuration of the ObjectReference type for use with\n// apply.\nfunc ObjectReference() *ObjectReferenceApplyConfiguration {\n\treturn \u0026ObjectReferenceApplyConfiguration{}\n}","line":{"from":37,"to":41}} {"id":100021805,"name":"WithKind","signature":"func (b *ObjectReferenceApplyConfiguration) WithKind(value string) *ObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/objectreference.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ObjectReferenceApplyConfiguration) WithKind(value string) *ObjectReferenceApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100021806,"name":"WithNamespace","signature":"func (b *ObjectReferenceApplyConfiguration) WithNamespace(value string) *ObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/objectreference.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ObjectReferenceApplyConfiguration) WithNamespace(value string) *ObjectReferenceApplyConfiguration {\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100021807,"name":"WithName","signature":"func (b *ObjectReferenceApplyConfiguration) WithName(value string) *ObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/objectreference.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ObjectReferenceApplyConfiguration) WithName(value string) *ObjectReferenceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":59,"to":65}} {"id":100021808,"name":"WithUID","signature":"func (b *ObjectReferenceApplyConfiguration) WithUID(value types.UID) *ObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/objectreference.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ObjectReferenceApplyConfiguration) WithUID(value types.UID) *ObjectReferenceApplyConfiguration {\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100021809,"name":"WithAPIVersion","signature":"func (b *ObjectReferenceApplyConfiguration) WithAPIVersion(value string) *ObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/objectreference.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ObjectReferenceApplyConfiguration) WithAPIVersion(value string) *ObjectReferenceApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":75,"to":81}} {"id":100021810,"name":"WithResourceVersion","signature":"func (b *ObjectReferenceApplyConfiguration) WithResourceVersion(value string) *ObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/objectreference.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ObjectReferenceApplyConfiguration) WithResourceVersion(value string) *ObjectReferenceApplyConfiguration {\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100021811,"name":"WithFieldPath","signature":"func (b *ObjectReferenceApplyConfiguration) WithFieldPath(value string) *ObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/objectreference.go","code":"// WithFieldPath sets the FieldPath field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FieldPath field is set to the value of the last call.\nfunc (b *ObjectReferenceApplyConfiguration) WithFieldPath(value string) *ObjectReferenceApplyConfiguration {\n\tb.FieldPath = \u0026value\n\treturn b\n}","line":{"from":91,"to":97}} {"id":100021812,"name":"PersistentVolume","signature":"func PersistentVolume(name string) *PersistentVolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolume.go","code":"// PersistentVolume constructs an declarative configuration of the PersistentVolume type for use with\n// apply.\nfunc PersistentVolume(name string) *PersistentVolumeApplyConfiguration {\n\tb := \u0026PersistentVolumeApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"PersistentVolume\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b\n}","line":{"from":39,"to":47}} {"id":100021813,"name":"ExtractPersistentVolume","signature":"func ExtractPersistentVolume(persistentVolume *apicorev1.PersistentVolume, fieldManager string) (*PersistentVolumeApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolume.go","code":"// ExtractPersistentVolume extracts the applied configuration owned by fieldManager from\n// persistentVolume. If no managedFields are found in persistentVolume for fieldManager, a\n// PersistentVolumeApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// persistentVolume must be a unmodified PersistentVolume API object that was retrieved from the Kubernetes API.\n// ExtractPersistentVolume provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractPersistentVolume(persistentVolume *apicorev1.PersistentVolume, fieldManager string) (*PersistentVolumeApplyConfiguration, error) {\n\treturn extractPersistentVolume(persistentVolume, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100021814,"name":"ExtractPersistentVolumeStatus","signature":"func ExtractPersistentVolumeStatus(persistentVolume *apicorev1.PersistentVolume, fieldManager string) (*PersistentVolumeApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolume.go","code":"// ExtractPersistentVolumeStatus is the same as ExtractPersistentVolume except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractPersistentVolumeStatus(persistentVolume *apicorev1.PersistentVolume, fieldManager string) (*PersistentVolumeApplyConfiguration, error) {\n\treturn extractPersistentVolume(persistentVolume, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100021815,"name":"extractPersistentVolume","signature":"func extractPersistentVolume(persistentVolume *apicorev1.PersistentVolume, fieldManager string, subresource string) (*PersistentVolumeApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolume.go","code":"func extractPersistentVolume(persistentVolume *apicorev1.PersistentVolume, fieldManager string, subresource string) (*PersistentVolumeApplyConfiguration, error) {\n\tb := \u0026PersistentVolumeApplyConfiguration{}\n\terr := managedfields.ExtractInto(persistentVolume, internal.Parser().Type(\"io.k8s.api.core.v1.PersistentVolume\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(persistentVolume.Name)\n\n\tb.WithKind(\"PersistentVolume\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b, nil\n}","line":{"from":71,"to":82}} {"id":100021816,"name":"WithKind","signature":"func (b *PersistentVolumeApplyConfiguration) WithKind(value string) *PersistentVolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolume.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *PersistentVolumeApplyConfiguration) WithKind(value string) *PersistentVolumeApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100021817,"name":"WithAPIVersion","signature":"func (b *PersistentVolumeApplyConfiguration) WithAPIVersion(value string) *PersistentVolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolume.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *PersistentVolumeApplyConfiguration) WithAPIVersion(value string) *PersistentVolumeApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100021818,"name":"WithName","signature":"func (b *PersistentVolumeApplyConfiguration) WithName(value string) *PersistentVolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolume.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *PersistentVolumeApplyConfiguration) WithName(value string) *PersistentVolumeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":100,"to":107}} {"id":100021819,"name":"WithGenerateName","signature":"func (b *PersistentVolumeApplyConfiguration) WithGenerateName(value string) *PersistentVolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolume.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *PersistentVolumeApplyConfiguration) WithGenerateName(value string) *PersistentVolumeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":109,"to":116}} {"id":100021820,"name":"WithNamespace","signature":"func (b *PersistentVolumeApplyConfiguration) WithNamespace(value string) *PersistentVolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolume.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *PersistentVolumeApplyConfiguration) WithNamespace(value string) *PersistentVolumeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":118,"to":125}} {"id":100021821,"name":"WithUID","signature":"func (b *PersistentVolumeApplyConfiguration) WithUID(value types.UID) *PersistentVolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolume.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *PersistentVolumeApplyConfiguration) WithUID(value types.UID) *PersistentVolumeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":127,"to":134}} {"id":100021822,"name":"WithResourceVersion","signature":"func (b *PersistentVolumeApplyConfiguration) WithResourceVersion(value string) *PersistentVolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolume.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *PersistentVolumeApplyConfiguration) WithResourceVersion(value string) *PersistentVolumeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":136,"to":143}} {"id":100021823,"name":"WithGeneration","signature":"func (b *PersistentVolumeApplyConfiguration) WithGeneration(value int64) *PersistentVolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolume.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *PersistentVolumeApplyConfiguration) WithGeneration(value int64) *PersistentVolumeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":145,"to":152}} {"id":100021824,"name":"WithCreationTimestamp","signature":"func (b *PersistentVolumeApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PersistentVolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolume.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *PersistentVolumeApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PersistentVolumeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":154,"to":161}} {"id":100021825,"name":"WithDeletionTimestamp","signature":"func (b *PersistentVolumeApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PersistentVolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolume.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *PersistentVolumeApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PersistentVolumeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":163,"to":170}} {"id":100021826,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *PersistentVolumeApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PersistentVolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolume.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *PersistentVolumeApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PersistentVolumeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":172,"to":179}} {"id":100021827,"name":"WithLabels","signature":"func (b *PersistentVolumeApplyConfiguration) WithLabels(entries map[string]string) *PersistentVolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolume.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *PersistentVolumeApplyConfiguration) WithLabels(entries map[string]string) *PersistentVolumeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":181,"to":194}} {"id":100021828,"name":"WithAnnotations","signature":"func (b *PersistentVolumeApplyConfiguration) WithAnnotations(entries map[string]string) *PersistentVolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolume.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *PersistentVolumeApplyConfiguration) WithAnnotations(entries map[string]string) *PersistentVolumeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100021829,"name":"WithOwnerReferences","signature":"func (b *PersistentVolumeApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PersistentVolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolume.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *PersistentVolumeApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PersistentVolumeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":211,"to":223}} {"id":100021830,"name":"WithFinalizers","signature":"func (b *PersistentVolumeApplyConfiguration) WithFinalizers(values ...string) *PersistentVolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolume.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *PersistentVolumeApplyConfiguration) WithFinalizers(values ...string) *PersistentVolumeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":225,"to":234}} {"id":100021831,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *PersistentVolumeApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolume.go","code":"func (b *PersistentVolumeApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":236,"to":240}} {"id":100021832,"name":"WithSpec","signature":"func (b *PersistentVolumeApplyConfiguration) WithSpec(value *PersistentVolumeSpecApplyConfiguration) *PersistentVolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolume.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *PersistentVolumeApplyConfiguration) WithSpec(value *PersistentVolumeSpecApplyConfiguration) *PersistentVolumeApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":242,"to":248}} {"id":100021833,"name":"WithStatus","signature":"func (b *PersistentVolumeApplyConfiguration) WithStatus(value *PersistentVolumeStatusApplyConfiguration) *PersistentVolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolume.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *PersistentVolumeApplyConfiguration) WithStatus(value *PersistentVolumeStatusApplyConfiguration) *PersistentVolumeApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":250,"to":256}} {"id":100021834,"name":"PersistentVolumeClaim","signature":"func PersistentVolumeClaim(name, namespace string) *PersistentVolumeClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaim.go","code":"// PersistentVolumeClaim constructs an declarative configuration of the PersistentVolumeClaim type for use with\n// apply.\nfunc PersistentVolumeClaim(name, namespace string) *PersistentVolumeClaimApplyConfiguration {\n\tb := \u0026PersistentVolumeClaimApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"PersistentVolumeClaim\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100021835,"name":"ExtractPersistentVolumeClaim","signature":"func ExtractPersistentVolumeClaim(persistentVolumeClaim *apicorev1.PersistentVolumeClaim, fieldManager string) (*PersistentVolumeClaimApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaim.go","code":"// ExtractPersistentVolumeClaim extracts the applied configuration owned by fieldManager from\n// persistentVolumeClaim. If no managedFields are found in persistentVolumeClaim for fieldManager, a\n// PersistentVolumeClaimApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// persistentVolumeClaim must be a unmodified PersistentVolumeClaim API object that was retrieved from the Kubernetes API.\n// ExtractPersistentVolumeClaim provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractPersistentVolumeClaim(persistentVolumeClaim *apicorev1.PersistentVolumeClaim, fieldManager string) (*PersistentVolumeClaimApplyConfiguration, error) {\n\treturn extractPersistentVolumeClaim(persistentVolumeClaim, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100021836,"name":"ExtractPersistentVolumeClaimStatus","signature":"func ExtractPersistentVolumeClaimStatus(persistentVolumeClaim *apicorev1.PersistentVolumeClaim, fieldManager string) (*PersistentVolumeClaimApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaim.go","code":"// ExtractPersistentVolumeClaimStatus is the same as ExtractPersistentVolumeClaim except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractPersistentVolumeClaimStatus(persistentVolumeClaim *apicorev1.PersistentVolumeClaim, fieldManager string) (*PersistentVolumeClaimApplyConfiguration, error) {\n\treturn extractPersistentVolumeClaim(persistentVolumeClaim, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100021837,"name":"extractPersistentVolumeClaim","signature":"func extractPersistentVolumeClaim(persistentVolumeClaim *apicorev1.PersistentVolumeClaim, fieldManager string, subresource string) (*PersistentVolumeClaimApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaim.go","code":"func extractPersistentVolumeClaim(persistentVolumeClaim *apicorev1.PersistentVolumeClaim, fieldManager string, subresource string) (*PersistentVolumeClaimApplyConfiguration, error) {\n\tb := \u0026PersistentVolumeClaimApplyConfiguration{}\n\terr := managedfields.ExtractInto(persistentVolumeClaim, internal.Parser().Type(\"io.k8s.api.core.v1.PersistentVolumeClaim\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(persistentVolumeClaim.Name)\n\tb.WithNamespace(persistentVolumeClaim.Namespace)\n\n\tb.WithKind(\"PersistentVolumeClaim\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100021838,"name":"WithKind","signature":"func (b *PersistentVolumeClaimApplyConfiguration) WithKind(value string) *PersistentVolumeClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaim.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimApplyConfiguration) WithKind(value string) *PersistentVolumeClaimApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100021839,"name":"WithAPIVersion","signature":"func (b *PersistentVolumeClaimApplyConfiguration) WithAPIVersion(value string) *PersistentVolumeClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaim.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimApplyConfiguration) WithAPIVersion(value string) *PersistentVolumeClaimApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100021840,"name":"WithName","signature":"func (b *PersistentVolumeClaimApplyConfiguration) WithName(value string) *PersistentVolumeClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaim.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimApplyConfiguration) WithName(value string) *PersistentVolumeClaimApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100021841,"name":"WithGenerateName","signature":"func (b *PersistentVolumeClaimApplyConfiguration) WithGenerateName(value string) *PersistentVolumeClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaim.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimApplyConfiguration) WithGenerateName(value string) *PersistentVolumeClaimApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100021842,"name":"WithNamespace","signature":"func (b *PersistentVolumeClaimApplyConfiguration) WithNamespace(value string) *PersistentVolumeClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaim.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimApplyConfiguration) WithNamespace(value string) *PersistentVolumeClaimApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100021843,"name":"WithUID","signature":"func (b *PersistentVolumeClaimApplyConfiguration) WithUID(value types.UID) *PersistentVolumeClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaim.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimApplyConfiguration) WithUID(value types.UID) *PersistentVolumeClaimApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100021844,"name":"WithResourceVersion","signature":"func (b *PersistentVolumeClaimApplyConfiguration) WithResourceVersion(value string) *PersistentVolumeClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaim.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimApplyConfiguration) WithResourceVersion(value string) *PersistentVolumeClaimApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100021845,"name":"WithGeneration","signature":"func (b *PersistentVolumeClaimApplyConfiguration) WithGeneration(value int64) *PersistentVolumeClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaim.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimApplyConfiguration) WithGeneration(value int64) *PersistentVolumeClaimApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100021846,"name":"WithCreationTimestamp","signature":"func (b *PersistentVolumeClaimApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PersistentVolumeClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaim.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PersistentVolumeClaimApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100021847,"name":"WithDeletionTimestamp","signature":"func (b *PersistentVolumeClaimApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PersistentVolumeClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaim.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PersistentVolumeClaimApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100021848,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *PersistentVolumeClaimApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PersistentVolumeClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaim.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PersistentVolumeClaimApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100021849,"name":"WithLabels","signature":"func (b *PersistentVolumeClaimApplyConfiguration) WithLabels(entries map[string]string) *PersistentVolumeClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaim.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *PersistentVolumeClaimApplyConfiguration) WithLabels(entries map[string]string) *PersistentVolumeClaimApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100021850,"name":"WithAnnotations","signature":"func (b *PersistentVolumeClaimApplyConfiguration) WithAnnotations(entries map[string]string) *PersistentVolumeClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaim.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *PersistentVolumeClaimApplyConfiguration) WithAnnotations(entries map[string]string) *PersistentVolumeClaimApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100021851,"name":"WithOwnerReferences","signature":"func (b *PersistentVolumeClaimApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PersistentVolumeClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaim.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *PersistentVolumeClaimApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PersistentVolumeClaimApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100021852,"name":"WithFinalizers","signature":"func (b *PersistentVolumeClaimApplyConfiguration) WithFinalizers(values ...string) *PersistentVolumeClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaim.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *PersistentVolumeClaimApplyConfiguration) WithFinalizers(values ...string) *PersistentVolumeClaimApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100021853,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *PersistentVolumeClaimApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaim.go","code":"func (b *PersistentVolumeClaimApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100021854,"name":"WithSpec","signature":"func (b *PersistentVolumeClaimApplyConfiguration) WithSpec(value *PersistentVolumeClaimSpecApplyConfiguration) *PersistentVolumeClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaim.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimApplyConfiguration) WithSpec(value *PersistentVolumeClaimSpecApplyConfiguration) *PersistentVolumeClaimApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100021855,"name":"WithStatus","signature":"func (b *PersistentVolumeClaimApplyConfiguration) WithStatus(value *PersistentVolumeClaimStatusApplyConfiguration) *PersistentVolumeClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaim.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimApplyConfiguration) WithStatus(value *PersistentVolumeClaimStatusApplyConfiguration) *PersistentVolumeClaimApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100021856,"name":"PersistentVolumeClaimCondition","signature":"func PersistentVolumeClaimCondition() *PersistentVolumeClaimConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimcondition.go","code":"// PersistentVolumeClaimConditionApplyConfiguration constructs an declarative configuration of the PersistentVolumeClaimCondition type for use with\n// apply.\nfunc PersistentVolumeClaimCondition() *PersistentVolumeClaimConditionApplyConfiguration {\n\treturn \u0026PersistentVolumeClaimConditionApplyConfiguration{}\n}","line":{"from":37,"to":41}} {"id":100021857,"name":"WithType","signature":"func (b *PersistentVolumeClaimConditionApplyConfiguration) WithType(value v1.PersistentVolumeClaimConditionType) *PersistentVolumeClaimConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimcondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimConditionApplyConfiguration) WithType(value v1.PersistentVolumeClaimConditionType) *PersistentVolumeClaimConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100021858,"name":"WithStatus","signature":"func (b *PersistentVolumeClaimConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *PersistentVolumeClaimConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimcondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *PersistentVolumeClaimConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100021859,"name":"WithLastProbeTime","signature":"func (b *PersistentVolumeClaimConditionApplyConfiguration) WithLastProbeTime(value metav1.Time) *PersistentVolumeClaimConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimcondition.go","code":"// WithLastProbeTime sets the LastProbeTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastProbeTime field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimConditionApplyConfiguration) WithLastProbeTime(value metav1.Time) *PersistentVolumeClaimConditionApplyConfiguration {\n\tb.LastProbeTime = \u0026value\n\treturn b\n}","line":{"from":59,"to":65}} {"id":100021860,"name":"WithLastTransitionTime","signature":"func (b *PersistentVolumeClaimConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *PersistentVolumeClaimConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimcondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *PersistentVolumeClaimConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100021861,"name":"WithReason","signature":"func (b *PersistentVolumeClaimConditionApplyConfiguration) WithReason(value string) *PersistentVolumeClaimConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimcondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimConditionApplyConfiguration) WithReason(value string) *PersistentVolumeClaimConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":75,"to":81}} {"id":100021862,"name":"WithMessage","signature":"func (b *PersistentVolumeClaimConditionApplyConfiguration) WithMessage(value string) *PersistentVolumeClaimConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimcondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimConditionApplyConfiguration) WithMessage(value string) *PersistentVolumeClaimConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100021863,"name":"PersistentVolumeClaimSpec","signature":"func PersistentVolumeClaimSpec() *PersistentVolumeClaimSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimspec.go","code":"// PersistentVolumeClaimSpecApplyConfiguration constructs an declarative configuration of the PersistentVolumeClaimSpec type for use with\n// apply.\nfunc PersistentVolumeClaimSpec() *PersistentVolumeClaimSpecApplyConfiguration {\n\treturn \u0026PersistentVolumeClaimSpecApplyConfiguration{}\n}","line":{"from":39,"to":43}} {"id":100021864,"name":"WithAccessModes","signature":"func (b *PersistentVolumeClaimSpecApplyConfiguration) WithAccessModes(values ...v1.PersistentVolumeAccessMode) *PersistentVolumeClaimSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimspec.go","code":"// WithAccessModes adds the given value to the AccessModes field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the AccessModes field.\nfunc (b *PersistentVolumeClaimSpecApplyConfiguration) WithAccessModes(values ...v1.PersistentVolumeAccessMode) *PersistentVolumeClaimSpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.AccessModes = append(b.AccessModes, values[i])\n\t}\n\treturn b\n}","line":{"from":45,"to":53}} {"id":100021865,"name":"WithSelector","signature":"func (b *PersistentVolumeClaimSpecApplyConfiguration) WithSelector(value *metav1.LabelSelectorApplyConfiguration) *PersistentVolumeClaimSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimspec.go","code":"// WithSelector sets the Selector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Selector field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimSpecApplyConfiguration) WithSelector(value *metav1.LabelSelectorApplyConfiguration) *PersistentVolumeClaimSpecApplyConfiguration {\n\tb.Selector = value\n\treturn b\n}","line":{"from":55,"to":61}} {"id":100021866,"name":"WithResources","signature":"func (b *PersistentVolumeClaimSpecApplyConfiguration) WithResources(value *ResourceRequirementsApplyConfiguration) *PersistentVolumeClaimSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimspec.go","code":"// WithResources sets the Resources field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Resources field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimSpecApplyConfiguration) WithResources(value *ResourceRequirementsApplyConfiguration) *PersistentVolumeClaimSpecApplyConfiguration {\n\tb.Resources = value\n\treturn b\n}","line":{"from":63,"to":69}} {"id":100021867,"name":"WithVolumeName","signature":"func (b *PersistentVolumeClaimSpecApplyConfiguration) WithVolumeName(value string) *PersistentVolumeClaimSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimspec.go","code":"// WithVolumeName sets the VolumeName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the VolumeName field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimSpecApplyConfiguration) WithVolumeName(value string) *PersistentVolumeClaimSpecApplyConfiguration {\n\tb.VolumeName = \u0026value\n\treturn b\n}","line":{"from":71,"to":77}} {"id":100021868,"name":"WithStorageClassName","signature":"func (b *PersistentVolumeClaimSpecApplyConfiguration) WithStorageClassName(value string) *PersistentVolumeClaimSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimspec.go","code":"// WithStorageClassName sets the StorageClassName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StorageClassName field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimSpecApplyConfiguration) WithStorageClassName(value string) *PersistentVolumeClaimSpecApplyConfiguration {\n\tb.StorageClassName = \u0026value\n\treturn b\n}","line":{"from":79,"to":85}} {"id":100021869,"name":"WithVolumeMode","signature":"func (b *PersistentVolumeClaimSpecApplyConfiguration) WithVolumeMode(value v1.PersistentVolumeMode) *PersistentVolumeClaimSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimspec.go","code":"// WithVolumeMode sets the VolumeMode field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the VolumeMode field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimSpecApplyConfiguration) WithVolumeMode(value v1.PersistentVolumeMode) *PersistentVolumeClaimSpecApplyConfiguration {\n\tb.VolumeMode = \u0026value\n\treturn b\n}","line":{"from":87,"to":93}} {"id":100021870,"name":"WithDataSource","signature":"func (b *PersistentVolumeClaimSpecApplyConfiguration) WithDataSource(value *TypedLocalObjectReferenceApplyConfiguration) *PersistentVolumeClaimSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimspec.go","code":"// WithDataSource sets the DataSource field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DataSource field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimSpecApplyConfiguration) WithDataSource(value *TypedLocalObjectReferenceApplyConfiguration) *PersistentVolumeClaimSpecApplyConfiguration {\n\tb.DataSource = value\n\treturn b\n}","line":{"from":95,"to":101}} {"id":100021871,"name":"WithDataSourceRef","signature":"func (b *PersistentVolumeClaimSpecApplyConfiguration) WithDataSourceRef(value *TypedObjectReferenceApplyConfiguration) *PersistentVolumeClaimSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimspec.go","code":"// WithDataSourceRef sets the DataSourceRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DataSourceRef field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimSpecApplyConfiguration) WithDataSourceRef(value *TypedObjectReferenceApplyConfiguration) *PersistentVolumeClaimSpecApplyConfiguration {\n\tb.DataSourceRef = value\n\treturn b\n}","line":{"from":103,"to":109}} {"id":100021872,"name":"PersistentVolumeClaimStatus","signature":"func PersistentVolumeClaimStatus() *PersistentVolumeClaimStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimstatus.go","code":"// PersistentVolumeClaimStatusApplyConfiguration constructs an declarative configuration of the PersistentVolumeClaimStatus type for use with\n// apply.\nfunc PersistentVolumeClaimStatus() *PersistentVolumeClaimStatusApplyConfiguration {\n\treturn \u0026PersistentVolumeClaimStatusApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100021873,"name":"WithPhase","signature":"func (b *PersistentVolumeClaimStatusApplyConfiguration) WithPhase(value v1.PersistentVolumeClaimPhase) *PersistentVolumeClaimStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimstatus.go","code":"// WithPhase sets the Phase field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Phase field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimStatusApplyConfiguration) WithPhase(value v1.PersistentVolumeClaimPhase) *PersistentVolumeClaimStatusApplyConfiguration {\n\tb.Phase = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100021874,"name":"WithAccessModes","signature":"func (b *PersistentVolumeClaimStatusApplyConfiguration) WithAccessModes(values ...v1.PersistentVolumeAccessMode) *PersistentVolumeClaimStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimstatus.go","code":"// WithAccessModes adds the given value to the AccessModes field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the AccessModes field.\nfunc (b *PersistentVolumeClaimStatusApplyConfiguration) WithAccessModes(values ...v1.PersistentVolumeAccessMode) *PersistentVolumeClaimStatusApplyConfiguration {\n\tfor i := range values {\n\t\tb.AccessModes = append(b.AccessModes, values[i])\n\t}\n\treturn b\n}","line":{"from":50,"to":58}} {"id":100021875,"name":"WithCapacity","signature":"func (b *PersistentVolumeClaimStatusApplyConfiguration) WithCapacity(value v1.ResourceList) *PersistentVolumeClaimStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimstatus.go","code":"// WithCapacity sets the Capacity field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Capacity field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimStatusApplyConfiguration) WithCapacity(value v1.ResourceList) *PersistentVolumeClaimStatusApplyConfiguration {\n\tb.Capacity = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100021876,"name":"WithConditions","signature":"func (b *PersistentVolumeClaimStatusApplyConfiguration) WithConditions(values ...*PersistentVolumeClaimConditionApplyConfiguration) *PersistentVolumeClaimStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *PersistentVolumeClaimStatusApplyConfiguration) WithConditions(values ...*PersistentVolumeClaimConditionApplyConfiguration) *PersistentVolumeClaimStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":68,"to":79}} {"id":100021877,"name":"WithAllocatedResources","signature":"func (b *PersistentVolumeClaimStatusApplyConfiguration) WithAllocatedResources(value v1.ResourceList) *PersistentVolumeClaimStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimstatus.go","code":"// WithAllocatedResources sets the AllocatedResources field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AllocatedResources field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimStatusApplyConfiguration) WithAllocatedResources(value v1.ResourceList) *PersistentVolumeClaimStatusApplyConfiguration {\n\tb.AllocatedResources = \u0026value\n\treturn b\n}","line":{"from":81,"to":87}} {"id":100021878,"name":"WithResizeStatus","signature":"func (b *PersistentVolumeClaimStatusApplyConfiguration) WithResizeStatus(value v1.PersistentVolumeClaimResizeStatus) *PersistentVolumeClaimStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimstatus.go","code":"// WithResizeStatus sets the ResizeStatus field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResizeStatus field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimStatusApplyConfiguration) WithResizeStatus(value v1.PersistentVolumeClaimResizeStatus) *PersistentVolumeClaimStatusApplyConfiguration {\n\tb.ResizeStatus = \u0026value\n\treturn b\n}","line":{"from":89,"to":95}} {"id":100021879,"name":"PersistentVolumeClaimTemplate","signature":"func PersistentVolumeClaimTemplate() *PersistentVolumeClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimtemplate.go","code":"// PersistentVolumeClaimTemplateApplyConfiguration constructs an declarative configuration of the PersistentVolumeClaimTemplate type for use with\n// apply.\nfunc PersistentVolumeClaimTemplate() *PersistentVolumeClaimTemplateApplyConfiguration {\n\treturn \u0026PersistentVolumeClaimTemplateApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100021880,"name":"WithName","signature":"func (b *PersistentVolumeClaimTemplateApplyConfiguration) WithName(value string) *PersistentVolumeClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimtemplate.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimTemplateApplyConfiguration) WithName(value string) *PersistentVolumeClaimTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":40,"to":47}} {"id":100021881,"name":"WithGenerateName","signature":"func (b *PersistentVolumeClaimTemplateApplyConfiguration) WithGenerateName(value string) *PersistentVolumeClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimtemplate.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimTemplateApplyConfiguration) WithGenerateName(value string) *PersistentVolumeClaimTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":49,"to":56}} {"id":100021882,"name":"WithNamespace","signature":"func (b *PersistentVolumeClaimTemplateApplyConfiguration) WithNamespace(value string) *PersistentVolumeClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimtemplate.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimTemplateApplyConfiguration) WithNamespace(value string) *PersistentVolumeClaimTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":58,"to":65}} {"id":100021883,"name":"WithUID","signature":"func (b *PersistentVolumeClaimTemplateApplyConfiguration) WithUID(value types.UID) *PersistentVolumeClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimtemplate.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimTemplateApplyConfiguration) WithUID(value types.UID) *PersistentVolumeClaimTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":67,"to":74}} {"id":100021884,"name":"WithResourceVersion","signature":"func (b *PersistentVolumeClaimTemplateApplyConfiguration) WithResourceVersion(value string) *PersistentVolumeClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimtemplate.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimTemplateApplyConfiguration) WithResourceVersion(value string) *PersistentVolumeClaimTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":76,"to":83}} {"id":100021885,"name":"WithGeneration","signature":"func (b *PersistentVolumeClaimTemplateApplyConfiguration) WithGeneration(value int64) *PersistentVolumeClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimtemplate.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimTemplateApplyConfiguration) WithGeneration(value int64) *PersistentVolumeClaimTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":85,"to":92}} {"id":100021886,"name":"WithCreationTimestamp","signature":"func (b *PersistentVolumeClaimTemplateApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PersistentVolumeClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimtemplate.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimTemplateApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PersistentVolumeClaimTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":94,"to":101}} {"id":100021887,"name":"WithDeletionTimestamp","signature":"func (b *PersistentVolumeClaimTemplateApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PersistentVolumeClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimtemplate.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimTemplateApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PersistentVolumeClaimTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":103,"to":110}} {"id":100021888,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *PersistentVolumeClaimTemplateApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PersistentVolumeClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimtemplate.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimTemplateApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PersistentVolumeClaimTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":112,"to":119}} {"id":100021889,"name":"WithLabels","signature":"func (b *PersistentVolumeClaimTemplateApplyConfiguration) WithLabels(entries map[string]string) *PersistentVolumeClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimtemplate.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *PersistentVolumeClaimTemplateApplyConfiguration) WithLabels(entries map[string]string) *PersistentVolumeClaimTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":121,"to":134}} {"id":100021890,"name":"WithAnnotations","signature":"func (b *PersistentVolumeClaimTemplateApplyConfiguration) WithAnnotations(entries map[string]string) *PersistentVolumeClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimtemplate.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *PersistentVolumeClaimTemplateApplyConfiguration) WithAnnotations(entries map[string]string) *PersistentVolumeClaimTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":136,"to":149}} {"id":100021891,"name":"WithOwnerReferences","signature":"func (b *PersistentVolumeClaimTemplateApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PersistentVolumeClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimtemplate.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *PersistentVolumeClaimTemplateApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PersistentVolumeClaimTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":151,"to":163}} {"id":100021892,"name":"WithFinalizers","signature":"func (b *PersistentVolumeClaimTemplateApplyConfiguration) WithFinalizers(values ...string) *PersistentVolumeClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimtemplate.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *PersistentVolumeClaimTemplateApplyConfiguration) WithFinalizers(values ...string) *PersistentVolumeClaimTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":165,"to":174}} {"id":100021893,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *PersistentVolumeClaimTemplateApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimtemplate.go","code":"func (b *PersistentVolumeClaimTemplateApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":176,"to":180}} {"id":100021894,"name":"WithSpec","signature":"func (b *PersistentVolumeClaimTemplateApplyConfiguration) WithSpec(value *PersistentVolumeClaimSpecApplyConfiguration) *PersistentVolumeClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimtemplate.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimTemplateApplyConfiguration) WithSpec(value *PersistentVolumeClaimSpecApplyConfiguration) *PersistentVolumeClaimTemplateApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":182,"to":188}} {"id":100021895,"name":"PersistentVolumeClaimVolumeSource","signature":"func PersistentVolumeClaimVolumeSource() *PersistentVolumeClaimVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimvolumesource.go","code":"// PersistentVolumeClaimVolumeSourceApplyConfiguration constructs an declarative configuration of the PersistentVolumeClaimVolumeSource type for use with\n// apply.\nfunc PersistentVolumeClaimVolumeSource() *PersistentVolumeClaimVolumeSourceApplyConfiguration {\n\treturn \u0026PersistentVolumeClaimVolumeSourceApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100021896,"name":"WithClaimName","signature":"func (b *PersistentVolumeClaimVolumeSourceApplyConfiguration) WithClaimName(value string) *PersistentVolumeClaimVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimvolumesource.go","code":"// WithClaimName sets the ClaimName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ClaimName field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimVolumeSourceApplyConfiguration) WithClaimName(value string) *PersistentVolumeClaimVolumeSourceApplyConfiguration {\n\tb.ClaimName = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100021897,"name":"WithReadOnly","signature":"func (b *PersistentVolumeClaimVolumeSourceApplyConfiguration) WithReadOnly(value bool) *PersistentVolumeClaimVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumeclaimvolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *PersistentVolumeClaimVolumeSourceApplyConfiguration) WithReadOnly(value bool) *PersistentVolumeClaimVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100021898,"name":"PersistentVolumeSource","signature":"func PersistentVolumeSource() *PersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumesource.go","code":"// PersistentVolumeSourceApplyConfiguration constructs an declarative configuration of the PersistentVolumeSource type for use with\n// apply.\nfunc PersistentVolumeSource() *PersistentVolumeSourceApplyConfiguration {\n\treturn \u0026PersistentVolumeSourceApplyConfiguration{}\n}","line":{"from":48,"to":52}} {"id":100021899,"name":"WithGCEPersistentDisk","signature":"func (b *PersistentVolumeSourceApplyConfiguration) WithGCEPersistentDisk(value *GCEPersistentDiskVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumesource.go","code":"// WithGCEPersistentDisk sets the GCEPersistentDisk field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GCEPersistentDisk field is set to the value of the last call.\nfunc (b *PersistentVolumeSourceApplyConfiguration) WithGCEPersistentDisk(value *GCEPersistentDiskVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration {\n\tb.GCEPersistentDisk = value\n\treturn b\n}","line":{"from":54,"to":60}} {"id":100021900,"name":"WithAWSElasticBlockStore","signature":"func (b *PersistentVolumeSourceApplyConfiguration) WithAWSElasticBlockStore(value *AWSElasticBlockStoreVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumesource.go","code":"// WithAWSElasticBlockStore sets the AWSElasticBlockStore field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AWSElasticBlockStore field is set to the value of the last call.\nfunc (b *PersistentVolumeSourceApplyConfiguration) WithAWSElasticBlockStore(value *AWSElasticBlockStoreVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration {\n\tb.AWSElasticBlockStore = value\n\treturn b\n}","line":{"from":62,"to":68}} {"id":100021901,"name":"WithHostPath","signature":"func (b *PersistentVolumeSourceApplyConfiguration) WithHostPath(value *HostPathVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumesource.go","code":"// WithHostPath sets the HostPath field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HostPath field is set to the value of the last call.\nfunc (b *PersistentVolumeSourceApplyConfiguration) WithHostPath(value *HostPathVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration {\n\tb.HostPath = value\n\treturn b\n}","line":{"from":70,"to":76}} {"id":100021902,"name":"WithGlusterfs","signature":"func (b *PersistentVolumeSourceApplyConfiguration) WithGlusterfs(value *GlusterfsPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumesource.go","code":"// WithGlusterfs sets the Glusterfs field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Glusterfs field is set to the value of the last call.\nfunc (b *PersistentVolumeSourceApplyConfiguration) WithGlusterfs(value *GlusterfsPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration {\n\tb.Glusterfs = value\n\treturn b\n}","line":{"from":78,"to":84}} {"id":100021903,"name":"WithNFS","signature":"func (b *PersistentVolumeSourceApplyConfiguration) WithNFS(value *NFSVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumesource.go","code":"// WithNFS sets the NFS field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NFS field is set to the value of the last call.\nfunc (b *PersistentVolumeSourceApplyConfiguration) WithNFS(value *NFSVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration {\n\tb.NFS = value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100021904,"name":"WithRBD","signature":"func (b *PersistentVolumeSourceApplyConfiguration) WithRBD(value *RBDPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumesource.go","code":"// WithRBD sets the RBD field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RBD field is set to the value of the last call.\nfunc (b *PersistentVolumeSourceApplyConfiguration) WithRBD(value *RBDPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration {\n\tb.RBD = value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100021905,"name":"WithISCSI","signature":"func (b *PersistentVolumeSourceApplyConfiguration) WithISCSI(value *ISCSIPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumesource.go","code":"// WithISCSI sets the ISCSI field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ISCSI field is set to the value of the last call.\nfunc (b *PersistentVolumeSourceApplyConfiguration) WithISCSI(value *ISCSIPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration {\n\tb.ISCSI = value\n\treturn b\n}","line":{"from":102,"to":108}} {"id":100021906,"name":"WithCinder","signature":"func (b *PersistentVolumeSourceApplyConfiguration) WithCinder(value *CinderPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumesource.go","code":"// WithCinder sets the Cinder field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Cinder field is set to the value of the last call.\nfunc (b *PersistentVolumeSourceApplyConfiguration) WithCinder(value *CinderPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration {\n\tb.Cinder = value\n\treturn b\n}","line":{"from":110,"to":116}} {"id":100021907,"name":"WithCephFS","signature":"func (b *PersistentVolumeSourceApplyConfiguration) WithCephFS(value *CephFSPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumesource.go","code":"// WithCephFS sets the CephFS field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CephFS field is set to the value of the last call.\nfunc (b *PersistentVolumeSourceApplyConfiguration) WithCephFS(value *CephFSPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration {\n\tb.CephFS = value\n\treturn b\n}","line":{"from":118,"to":124}} {"id":100021908,"name":"WithFC","signature":"func (b *PersistentVolumeSourceApplyConfiguration) WithFC(value *FCVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumesource.go","code":"// WithFC sets the FC field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FC field is set to the value of the last call.\nfunc (b *PersistentVolumeSourceApplyConfiguration) WithFC(value *FCVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration {\n\tb.FC = value\n\treturn b\n}","line":{"from":126,"to":132}} {"id":100021909,"name":"WithFlocker","signature":"func (b *PersistentVolumeSourceApplyConfiguration) WithFlocker(value *FlockerVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumesource.go","code":"// WithFlocker sets the Flocker field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Flocker field is set to the value of the last call.\nfunc (b *PersistentVolumeSourceApplyConfiguration) WithFlocker(value *FlockerVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration {\n\tb.Flocker = value\n\treturn b\n}","line":{"from":134,"to":140}} {"id":100021910,"name":"WithFlexVolume","signature":"func (b *PersistentVolumeSourceApplyConfiguration) WithFlexVolume(value *FlexPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumesource.go","code":"// WithFlexVolume sets the FlexVolume field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FlexVolume field is set to the value of the last call.\nfunc (b *PersistentVolumeSourceApplyConfiguration) WithFlexVolume(value *FlexPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration {\n\tb.FlexVolume = value\n\treturn b\n}","line":{"from":142,"to":148}} {"id":100021911,"name":"WithAzureFile","signature":"func (b *PersistentVolumeSourceApplyConfiguration) WithAzureFile(value *AzureFilePersistentVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumesource.go","code":"// WithAzureFile sets the AzureFile field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AzureFile field is set to the value of the last call.\nfunc (b *PersistentVolumeSourceApplyConfiguration) WithAzureFile(value *AzureFilePersistentVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration {\n\tb.AzureFile = value\n\treturn b\n}","line":{"from":150,"to":156}} {"id":100021912,"name":"WithVsphereVolume","signature":"func (b *PersistentVolumeSourceApplyConfiguration) WithVsphereVolume(value *VsphereVirtualDiskVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumesource.go","code":"// WithVsphereVolume sets the VsphereVolume field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the VsphereVolume field is set to the value of the last call.\nfunc (b *PersistentVolumeSourceApplyConfiguration) WithVsphereVolume(value *VsphereVirtualDiskVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration {\n\tb.VsphereVolume = value\n\treturn b\n}","line":{"from":158,"to":164}} {"id":100021913,"name":"WithQuobyte","signature":"func (b *PersistentVolumeSourceApplyConfiguration) WithQuobyte(value *QuobyteVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumesource.go","code":"// WithQuobyte sets the Quobyte field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Quobyte field is set to the value of the last call.\nfunc (b *PersistentVolumeSourceApplyConfiguration) WithQuobyte(value *QuobyteVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration {\n\tb.Quobyte = value\n\treturn b\n}","line":{"from":166,"to":172}} {"id":100021914,"name":"WithAzureDisk","signature":"func (b *PersistentVolumeSourceApplyConfiguration) WithAzureDisk(value *AzureDiskVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumesource.go","code":"// WithAzureDisk sets the AzureDisk field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AzureDisk field is set to the value of the last call.\nfunc (b *PersistentVolumeSourceApplyConfiguration) WithAzureDisk(value *AzureDiskVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration {\n\tb.AzureDisk = value\n\treturn b\n}","line":{"from":174,"to":180}} {"id":100021915,"name":"WithPhotonPersistentDisk","signature":"func (b *PersistentVolumeSourceApplyConfiguration) WithPhotonPersistentDisk(value *PhotonPersistentDiskVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumesource.go","code":"// WithPhotonPersistentDisk sets the PhotonPersistentDisk field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PhotonPersistentDisk field is set to the value of the last call.\nfunc (b *PersistentVolumeSourceApplyConfiguration) WithPhotonPersistentDisk(value *PhotonPersistentDiskVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration {\n\tb.PhotonPersistentDisk = value\n\treturn b\n}","line":{"from":182,"to":188}} {"id":100021916,"name":"WithPortworxVolume","signature":"func (b *PersistentVolumeSourceApplyConfiguration) WithPortworxVolume(value *PortworxVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumesource.go","code":"// WithPortworxVolume sets the PortworxVolume field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PortworxVolume field is set to the value of the last call.\nfunc (b *PersistentVolumeSourceApplyConfiguration) WithPortworxVolume(value *PortworxVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration {\n\tb.PortworxVolume = value\n\treturn b\n}","line":{"from":190,"to":196}} {"id":100021917,"name":"WithScaleIO","signature":"func (b *PersistentVolumeSourceApplyConfiguration) WithScaleIO(value *ScaleIOPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumesource.go","code":"// WithScaleIO sets the ScaleIO field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ScaleIO field is set to the value of the last call.\nfunc (b *PersistentVolumeSourceApplyConfiguration) WithScaleIO(value *ScaleIOPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration {\n\tb.ScaleIO = value\n\treturn b\n}","line":{"from":198,"to":204}} {"id":100021918,"name":"WithLocal","signature":"func (b *PersistentVolumeSourceApplyConfiguration) WithLocal(value *LocalVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumesource.go","code":"// WithLocal sets the Local field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Local field is set to the value of the last call.\nfunc (b *PersistentVolumeSourceApplyConfiguration) WithLocal(value *LocalVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration {\n\tb.Local = value\n\treturn b\n}","line":{"from":206,"to":212}} {"id":100021919,"name":"WithStorageOS","signature":"func (b *PersistentVolumeSourceApplyConfiguration) WithStorageOS(value *StorageOSPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumesource.go","code":"// WithStorageOS sets the StorageOS field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StorageOS field is set to the value of the last call.\nfunc (b *PersistentVolumeSourceApplyConfiguration) WithStorageOS(value *StorageOSPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration {\n\tb.StorageOS = value\n\treturn b\n}","line":{"from":214,"to":220}} {"id":100021920,"name":"WithCSI","signature":"func (b *PersistentVolumeSourceApplyConfiguration) WithCSI(value *CSIPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumesource.go","code":"// WithCSI sets the CSI field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CSI field is set to the value of the last call.\nfunc (b *PersistentVolumeSourceApplyConfiguration) WithCSI(value *CSIPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSourceApplyConfiguration {\n\tb.CSI = value\n\treturn b\n}","line":{"from":222,"to":228}} {"id":100021921,"name":"PersistentVolumeSpec","signature":"func PersistentVolumeSpec() *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// PersistentVolumeSpecApplyConfiguration constructs an declarative configuration of the PersistentVolumeSpec type for use with\n// apply.\nfunc PersistentVolumeSpec() *PersistentVolumeSpecApplyConfiguration {\n\treturn \u0026PersistentVolumeSpecApplyConfiguration{}\n}","line":{"from":39,"to":43}} {"id":100021922,"name":"WithCapacity","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithCapacity(value v1.ResourceList) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithCapacity sets the Capacity field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Capacity field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithCapacity(value v1.ResourceList) *PersistentVolumeSpecApplyConfiguration {\n\tb.Capacity = \u0026value\n\treturn b\n}","line":{"from":45,"to":51}} {"id":100021923,"name":"WithGCEPersistentDisk","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithGCEPersistentDisk(value *GCEPersistentDiskVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithGCEPersistentDisk sets the GCEPersistentDisk field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GCEPersistentDisk field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithGCEPersistentDisk(value *GCEPersistentDiskVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration {\n\tb.GCEPersistentDisk = value\n\treturn b\n}","line":{"from":53,"to":59}} {"id":100021924,"name":"WithAWSElasticBlockStore","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithAWSElasticBlockStore(value *AWSElasticBlockStoreVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithAWSElasticBlockStore sets the AWSElasticBlockStore field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AWSElasticBlockStore field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithAWSElasticBlockStore(value *AWSElasticBlockStoreVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration {\n\tb.AWSElasticBlockStore = value\n\treturn b\n}","line":{"from":61,"to":67}} {"id":100021925,"name":"WithHostPath","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithHostPath(value *HostPathVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithHostPath sets the HostPath field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HostPath field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithHostPath(value *HostPathVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration {\n\tb.HostPath = value\n\treturn b\n}","line":{"from":69,"to":75}} {"id":100021926,"name":"WithGlusterfs","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithGlusterfs(value *GlusterfsPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithGlusterfs sets the Glusterfs field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Glusterfs field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithGlusterfs(value *GlusterfsPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration {\n\tb.Glusterfs = value\n\treturn b\n}","line":{"from":77,"to":83}} {"id":100021927,"name":"WithNFS","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithNFS(value *NFSVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithNFS sets the NFS field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NFS field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithNFS(value *NFSVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration {\n\tb.NFS = value\n\treturn b\n}","line":{"from":85,"to":91}} {"id":100021928,"name":"WithRBD","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithRBD(value *RBDPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithRBD sets the RBD field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RBD field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithRBD(value *RBDPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration {\n\tb.RBD = value\n\treturn b\n}","line":{"from":93,"to":99}} {"id":100021929,"name":"WithISCSI","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithISCSI(value *ISCSIPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithISCSI sets the ISCSI field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ISCSI field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithISCSI(value *ISCSIPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration {\n\tb.ISCSI = value\n\treturn b\n}","line":{"from":101,"to":107}} {"id":100021930,"name":"WithCinder","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithCinder(value *CinderPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithCinder sets the Cinder field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Cinder field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithCinder(value *CinderPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration {\n\tb.Cinder = value\n\treturn b\n}","line":{"from":109,"to":115}} {"id":100021931,"name":"WithCephFS","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithCephFS(value *CephFSPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithCephFS sets the CephFS field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CephFS field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithCephFS(value *CephFSPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration {\n\tb.CephFS = value\n\treturn b\n}","line":{"from":117,"to":123}} {"id":100021932,"name":"WithFC","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithFC(value *FCVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithFC sets the FC field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FC field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithFC(value *FCVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration {\n\tb.FC = value\n\treturn b\n}","line":{"from":125,"to":131}} {"id":100021933,"name":"WithFlocker","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithFlocker(value *FlockerVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithFlocker sets the Flocker field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Flocker field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithFlocker(value *FlockerVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration {\n\tb.Flocker = value\n\treturn b\n}","line":{"from":133,"to":139}} {"id":100021934,"name":"WithFlexVolume","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithFlexVolume(value *FlexPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithFlexVolume sets the FlexVolume field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FlexVolume field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithFlexVolume(value *FlexPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration {\n\tb.FlexVolume = value\n\treturn b\n}","line":{"from":141,"to":147}} {"id":100021935,"name":"WithAzureFile","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithAzureFile(value *AzureFilePersistentVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithAzureFile sets the AzureFile field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AzureFile field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithAzureFile(value *AzureFilePersistentVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration {\n\tb.AzureFile = value\n\treturn b\n}","line":{"from":149,"to":155}} {"id":100021936,"name":"WithVsphereVolume","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithVsphereVolume(value *VsphereVirtualDiskVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithVsphereVolume sets the VsphereVolume field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the VsphereVolume field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithVsphereVolume(value *VsphereVirtualDiskVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration {\n\tb.VsphereVolume = value\n\treturn b\n}","line":{"from":157,"to":163}} {"id":100021937,"name":"WithQuobyte","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithQuobyte(value *QuobyteVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithQuobyte sets the Quobyte field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Quobyte field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithQuobyte(value *QuobyteVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration {\n\tb.Quobyte = value\n\treturn b\n}","line":{"from":165,"to":171}} {"id":100021938,"name":"WithAzureDisk","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithAzureDisk(value *AzureDiskVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithAzureDisk sets the AzureDisk field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AzureDisk field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithAzureDisk(value *AzureDiskVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration {\n\tb.AzureDisk = value\n\treturn b\n}","line":{"from":173,"to":179}} {"id":100021939,"name":"WithPhotonPersistentDisk","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithPhotonPersistentDisk(value *PhotonPersistentDiskVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithPhotonPersistentDisk sets the PhotonPersistentDisk field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PhotonPersistentDisk field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithPhotonPersistentDisk(value *PhotonPersistentDiskVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration {\n\tb.PhotonPersistentDisk = value\n\treturn b\n}","line":{"from":181,"to":187}} {"id":100021940,"name":"WithPortworxVolume","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithPortworxVolume(value *PortworxVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithPortworxVolume sets the PortworxVolume field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PortworxVolume field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithPortworxVolume(value *PortworxVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration {\n\tb.PortworxVolume = value\n\treturn b\n}","line":{"from":189,"to":195}} {"id":100021941,"name":"WithScaleIO","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithScaleIO(value *ScaleIOPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithScaleIO sets the ScaleIO field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ScaleIO field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithScaleIO(value *ScaleIOPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration {\n\tb.ScaleIO = value\n\treturn b\n}","line":{"from":197,"to":203}} {"id":100021942,"name":"WithLocal","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithLocal(value *LocalVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithLocal sets the Local field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Local field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithLocal(value *LocalVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration {\n\tb.Local = value\n\treturn b\n}","line":{"from":205,"to":211}} {"id":100021943,"name":"WithStorageOS","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithStorageOS(value *StorageOSPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithStorageOS sets the StorageOS field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StorageOS field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithStorageOS(value *StorageOSPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration {\n\tb.StorageOS = value\n\treturn b\n}","line":{"from":213,"to":219}} {"id":100021944,"name":"WithCSI","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithCSI(value *CSIPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithCSI sets the CSI field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CSI field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithCSI(value *CSIPersistentVolumeSourceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration {\n\tb.CSI = value\n\treturn b\n}","line":{"from":221,"to":227}} {"id":100021945,"name":"WithAccessModes","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithAccessModes(values ...v1.PersistentVolumeAccessMode) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithAccessModes adds the given value to the AccessModes field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the AccessModes field.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithAccessModes(values ...v1.PersistentVolumeAccessMode) *PersistentVolumeSpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.AccessModes = append(b.AccessModes, values[i])\n\t}\n\treturn b\n}","line":{"from":229,"to":237}} {"id":100021946,"name":"WithClaimRef","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithClaimRef(value *ObjectReferenceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithClaimRef sets the ClaimRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ClaimRef field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithClaimRef(value *ObjectReferenceApplyConfiguration) *PersistentVolumeSpecApplyConfiguration {\n\tb.ClaimRef = value\n\treturn b\n}","line":{"from":239,"to":245}} {"id":100021947,"name":"WithPersistentVolumeReclaimPolicy","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithPersistentVolumeReclaimPolicy(value v1.PersistentVolumeReclaimPolicy) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithPersistentVolumeReclaimPolicy sets the PersistentVolumeReclaimPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PersistentVolumeReclaimPolicy field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithPersistentVolumeReclaimPolicy(value v1.PersistentVolumeReclaimPolicy) *PersistentVolumeSpecApplyConfiguration {\n\tb.PersistentVolumeReclaimPolicy = \u0026value\n\treturn b\n}","line":{"from":247,"to":253}} {"id":100021948,"name":"WithStorageClassName","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithStorageClassName(value string) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithStorageClassName sets the StorageClassName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StorageClassName field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithStorageClassName(value string) *PersistentVolumeSpecApplyConfiguration {\n\tb.StorageClassName = \u0026value\n\treturn b\n}","line":{"from":255,"to":261}} {"id":100021949,"name":"WithMountOptions","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithMountOptions(values ...string) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithMountOptions adds the given value to the MountOptions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the MountOptions field.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithMountOptions(values ...string) *PersistentVolumeSpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.MountOptions = append(b.MountOptions, values[i])\n\t}\n\treturn b\n}","line":{"from":263,"to":271}} {"id":100021950,"name":"WithVolumeMode","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithVolumeMode(value v1.PersistentVolumeMode) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithVolumeMode sets the VolumeMode field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the VolumeMode field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithVolumeMode(value v1.PersistentVolumeMode) *PersistentVolumeSpecApplyConfiguration {\n\tb.VolumeMode = \u0026value\n\treturn b\n}","line":{"from":273,"to":279}} {"id":100021951,"name":"WithNodeAffinity","signature":"func (b *PersistentVolumeSpecApplyConfiguration) WithNodeAffinity(value *VolumeNodeAffinityApplyConfiguration) *PersistentVolumeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumespec.go","code":"// WithNodeAffinity sets the NodeAffinity field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NodeAffinity field is set to the value of the last call.\nfunc (b *PersistentVolumeSpecApplyConfiguration) WithNodeAffinity(value *VolumeNodeAffinityApplyConfiguration) *PersistentVolumeSpecApplyConfiguration {\n\tb.NodeAffinity = value\n\treturn b\n}","line":{"from":281,"to":287}} {"id":100021952,"name":"PersistentVolumeStatus","signature":"func PersistentVolumeStatus() *PersistentVolumeStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumestatus.go","code":"// PersistentVolumeStatusApplyConfiguration constructs an declarative configuration of the PersistentVolumeStatus type for use with\n// apply.\nfunc PersistentVolumeStatus() *PersistentVolumeStatusApplyConfiguration {\n\treturn \u0026PersistentVolumeStatusApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100021953,"name":"WithPhase","signature":"func (b *PersistentVolumeStatusApplyConfiguration) WithPhase(value v1.PersistentVolumePhase) *PersistentVolumeStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumestatus.go","code":"// WithPhase sets the Phase field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Phase field is set to the value of the last call.\nfunc (b *PersistentVolumeStatusApplyConfiguration) WithPhase(value v1.PersistentVolumePhase) *PersistentVolumeStatusApplyConfiguration {\n\tb.Phase = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100021954,"name":"WithMessage","signature":"func (b *PersistentVolumeStatusApplyConfiguration) WithMessage(value string) *PersistentVolumeStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumestatus.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *PersistentVolumeStatusApplyConfiguration) WithMessage(value string) *PersistentVolumeStatusApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100021955,"name":"WithReason","signature":"func (b *PersistentVolumeStatusApplyConfiguration) WithReason(value string) *PersistentVolumeStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/persistentvolumestatus.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *PersistentVolumeStatusApplyConfiguration) WithReason(value string) *PersistentVolumeStatusApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":55,"to":61}} {"id":100021956,"name":"PhotonPersistentDiskVolumeSource","signature":"func PhotonPersistentDiskVolumeSource() *PhotonPersistentDiskVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/photonpersistentdiskvolumesource.go","code":"// PhotonPersistentDiskVolumeSourceApplyConfiguration constructs an declarative configuration of the PhotonPersistentDiskVolumeSource type for use with\n// apply.\nfunc PhotonPersistentDiskVolumeSource() *PhotonPersistentDiskVolumeSourceApplyConfiguration {\n\treturn \u0026PhotonPersistentDiskVolumeSourceApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100021957,"name":"WithPdID","signature":"func (b *PhotonPersistentDiskVolumeSourceApplyConfiguration) WithPdID(value string) *PhotonPersistentDiskVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/photonpersistentdiskvolumesource.go","code":"// WithPdID sets the PdID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PdID field is set to the value of the last call.\nfunc (b *PhotonPersistentDiskVolumeSourceApplyConfiguration) WithPdID(value string) *PhotonPersistentDiskVolumeSourceApplyConfiguration {\n\tb.PdID = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100021958,"name":"WithFSType","signature":"func (b *PhotonPersistentDiskVolumeSourceApplyConfiguration) WithFSType(value string) *PhotonPersistentDiskVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/photonpersistentdiskvolumesource.go","code":"// WithFSType sets the FSType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSType field is set to the value of the last call.\nfunc (b *PhotonPersistentDiskVolumeSourceApplyConfiguration) WithFSType(value string) *PhotonPersistentDiskVolumeSourceApplyConfiguration {\n\tb.FSType = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100021959,"name":"Pod","signature":"func Pod(name, namespace string) *PodApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/pod.go","code":"// Pod constructs an declarative configuration of the Pod type for use with\n// apply.\nfunc Pod(name, namespace string) *PodApplyConfiguration {\n\tb := \u0026PodApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"Pod\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100021960,"name":"ExtractPod","signature":"func ExtractPod(pod *apicorev1.Pod, fieldManager string) (*PodApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/pod.go","code":"// ExtractPod extracts the applied configuration owned by fieldManager from\n// pod. If no managedFields are found in pod for fieldManager, a\n// PodApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// pod must be a unmodified Pod API object that was retrieved from the Kubernetes API.\n// ExtractPod provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractPod(pod *apicorev1.Pod, fieldManager string) (*PodApplyConfiguration, error) {\n\treturn extractPod(pod, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100021961,"name":"ExtractPodStatus","signature":"func ExtractPodStatus(pod *apicorev1.Pod, fieldManager string) (*PodApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/pod.go","code":"// ExtractPodStatus is the same as ExtractPod except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractPodStatus(pod *apicorev1.Pod, fieldManager string) (*PodApplyConfiguration, error) {\n\treturn extractPod(pod, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100021962,"name":"extractPod","signature":"func extractPod(pod *apicorev1.Pod, fieldManager string, subresource string) (*PodApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/pod.go","code":"func extractPod(pod *apicorev1.Pod, fieldManager string, subresource string) (*PodApplyConfiguration, error) {\n\tb := \u0026PodApplyConfiguration{}\n\terr := managedfields.ExtractInto(pod, internal.Parser().Type(\"io.k8s.api.core.v1.Pod\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(pod.Name)\n\tb.WithNamespace(pod.Namespace)\n\n\tb.WithKind(\"Pod\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100021963,"name":"WithKind","signature":"func (b *PodApplyConfiguration) WithKind(value string) *PodApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/pod.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *PodApplyConfiguration) WithKind(value string) *PodApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100021964,"name":"WithAPIVersion","signature":"func (b *PodApplyConfiguration) WithAPIVersion(value string) *PodApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/pod.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *PodApplyConfiguration) WithAPIVersion(value string) *PodApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100021965,"name":"WithName","signature":"func (b *PodApplyConfiguration) WithName(value string) *PodApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/pod.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *PodApplyConfiguration) WithName(value string) *PodApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100021966,"name":"WithGenerateName","signature":"func (b *PodApplyConfiguration) WithGenerateName(value string) *PodApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/pod.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *PodApplyConfiguration) WithGenerateName(value string) *PodApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100021967,"name":"WithNamespace","signature":"func (b *PodApplyConfiguration) WithNamespace(value string) *PodApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/pod.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *PodApplyConfiguration) WithNamespace(value string) *PodApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100021968,"name":"WithUID","signature":"func (b *PodApplyConfiguration) WithUID(value types.UID) *PodApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/pod.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *PodApplyConfiguration) WithUID(value types.UID) *PodApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100021969,"name":"WithResourceVersion","signature":"func (b *PodApplyConfiguration) WithResourceVersion(value string) *PodApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/pod.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *PodApplyConfiguration) WithResourceVersion(value string) *PodApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100021970,"name":"WithGeneration","signature":"func (b *PodApplyConfiguration) WithGeneration(value int64) *PodApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/pod.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *PodApplyConfiguration) WithGeneration(value int64) *PodApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100021971,"name":"WithCreationTimestamp","signature":"func (b *PodApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PodApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/pod.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *PodApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PodApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100021972,"name":"WithDeletionTimestamp","signature":"func (b *PodApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PodApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/pod.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *PodApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PodApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100021973,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *PodApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PodApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/pod.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *PodApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PodApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100021974,"name":"WithLabels","signature":"func (b *PodApplyConfiguration) WithLabels(entries map[string]string) *PodApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/pod.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *PodApplyConfiguration) WithLabels(entries map[string]string) *PodApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100021975,"name":"WithAnnotations","signature":"func (b *PodApplyConfiguration) WithAnnotations(entries map[string]string) *PodApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/pod.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *PodApplyConfiguration) WithAnnotations(entries map[string]string) *PodApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100021976,"name":"WithOwnerReferences","signature":"func (b *PodApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PodApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/pod.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *PodApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PodApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100021977,"name":"WithFinalizers","signature":"func (b *PodApplyConfiguration) WithFinalizers(values ...string) *PodApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/pod.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *PodApplyConfiguration) WithFinalizers(values ...string) *PodApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100021978,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *PodApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/pod.go","code":"func (b *PodApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100021979,"name":"WithSpec","signature":"func (b *PodApplyConfiguration) WithSpec(value *PodSpecApplyConfiguration) *PodApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/pod.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *PodApplyConfiguration) WithSpec(value *PodSpecApplyConfiguration) *PodApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100021980,"name":"WithStatus","signature":"func (b *PodApplyConfiguration) WithStatus(value *PodStatusApplyConfiguration) *PodApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/pod.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *PodApplyConfiguration) WithStatus(value *PodStatusApplyConfiguration) *PodApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100021981,"name":"PodAffinity","signature":"func PodAffinity() *PodAffinityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podaffinity.go","code":"// PodAffinityApplyConfiguration constructs an declarative configuration of the PodAffinity type for use with\n// apply.\nfunc PodAffinity() *PodAffinityApplyConfiguration {\n\treturn \u0026PodAffinityApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100021982,"name":"WithRequiredDuringSchedulingIgnoredDuringExecution","signature":"func (b *PodAffinityApplyConfiguration) WithRequiredDuringSchedulingIgnoredDuringExecution(values ...*PodAffinityTermApplyConfiguration) *PodAffinityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podaffinity.go","code":"// WithRequiredDuringSchedulingIgnoredDuringExecution adds the given value to the RequiredDuringSchedulingIgnoredDuringExecution field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the RequiredDuringSchedulingIgnoredDuringExecution field.\nfunc (b *PodAffinityApplyConfiguration) WithRequiredDuringSchedulingIgnoredDuringExecution(values ...*PodAffinityTermApplyConfiguration) *PodAffinityApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRequiredDuringSchedulingIgnoredDuringExecution\")\n\t\t}\n\t\tb.RequiredDuringSchedulingIgnoredDuringExecution = append(b.RequiredDuringSchedulingIgnoredDuringExecution, *values[i])\n\t}\n\treturn b\n}","line":{"from":34,"to":45}} {"id":100021983,"name":"WithPreferredDuringSchedulingIgnoredDuringExecution","signature":"func (b *PodAffinityApplyConfiguration) WithPreferredDuringSchedulingIgnoredDuringExecution(values ...*WeightedPodAffinityTermApplyConfiguration) *PodAffinityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podaffinity.go","code":"// WithPreferredDuringSchedulingIgnoredDuringExecution adds the given value to the PreferredDuringSchedulingIgnoredDuringExecution field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the PreferredDuringSchedulingIgnoredDuringExecution field.\nfunc (b *PodAffinityApplyConfiguration) WithPreferredDuringSchedulingIgnoredDuringExecution(values ...*WeightedPodAffinityTermApplyConfiguration) *PodAffinityApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPreferredDuringSchedulingIgnoredDuringExecution\")\n\t\t}\n\t\tb.PreferredDuringSchedulingIgnoredDuringExecution = append(b.PreferredDuringSchedulingIgnoredDuringExecution, *values[i])\n\t}\n\treturn b\n}","line":{"from":47,"to":58}} {"id":100021984,"name":"PodAffinityTerm","signature":"func PodAffinityTerm() *PodAffinityTermApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podaffinityterm.go","code":"// PodAffinityTermApplyConfiguration constructs an declarative configuration of the PodAffinityTerm type for use with\n// apply.\nfunc PodAffinityTerm() *PodAffinityTermApplyConfiguration {\n\treturn \u0026PodAffinityTermApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100021985,"name":"WithLabelSelector","signature":"func (b *PodAffinityTermApplyConfiguration) WithLabelSelector(value *v1.LabelSelectorApplyConfiguration) *PodAffinityTermApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podaffinityterm.go","code":"// WithLabelSelector sets the LabelSelector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LabelSelector field is set to the value of the last call.\nfunc (b *PodAffinityTermApplyConfiguration) WithLabelSelector(value *v1.LabelSelectorApplyConfiguration) *PodAffinityTermApplyConfiguration {\n\tb.LabelSelector = value\n\treturn b\n}","line":{"from":40,"to":46}} {"id":100021986,"name":"WithNamespaces","signature":"func (b *PodAffinityTermApplyConfiguration) WithNamespaces(values ...string) *PodAffinityTermApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podaffinityterm.go","code":"// WithNamespaces adds the given value to the Namespaces field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Namespaces field.\nfunc (b *PodAffinityTermApplyConfiguration) WithNamespaces(values ...string) *PodAffinityTermApplyConfiguration {\n\tfor i := range values {\n\t\tb.Namespaces = append(b.Namespaces, values[i])\n\t}\n\treturn b\n}","line":{"from":48,"to":56}} {"id":100021987,"name":"WithTopologyKey","signature":"func (b *PodAffinityTermApplyConfiguration) WithTopologyKey(value string) *PodAffinityTermApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podaffinityterm.go","code":"// WithTopologyKey sets the TopologyKey field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TopologyKey field is set to the value of the last call.\nfunc (b *PodAffinityTermApplyConfiguration) WithTopologyKey(value string) *PodAffinityTermApplyConfiguration {\n\tb.TopologyKey = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100021988,"name":"WithNamespaceSelector","signature":"func (b *PodAffinityTermApplyConfiguration) WithNamespaceSelector(value *v1.LabelSelectorApplyConfiguration) *PodAffinityTermApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podaffinityterm.go","code":"// WithNamespaceSelector sets the NamespaceSelector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NamespaceSelector field is set to the value of the last call.\nfunc (b *PodAffinityTermApplyConfiguration) WithNamespaceSelector(value *v1.LabelSelectorApplyConfiguration) *PodAffinityTermApplyConfiguration {\n\tb.NamespaceSelector = value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100021989,"name":"PodAntiAffinity","signature":"func PodAntiAffinity() *PodAntiAffinityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podantiaffinity.go","code":"// PodAntiAffinityApplyConfiguration constructs an declarative configuration of the PodAntiAffinity type for use with\n// apply.\nfunc PodAntiAffinity() *PodAntiAffinityApplyConfiguration {\n\treturn \u0026PodAntiAffinityApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100021990,"name":"WithRequiredDuringSchedulingIgnoredDuringExecution","signature":"func (b *PodAntiAffinityApplyConfiguration) WithRequiredDuringSchedulingIgnoredDuringExecution(values ...*PodAffinityTermApplyConfiguration) *PodAntiAffinityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podantiaffinity.go","code":"// WithRequiredDuringSchedulingIgnoredDuringExecution adds the given value to the RequiredDuringSchedulingIgnoredDuringExecution field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the RequiredDuringSchedulingIgnoredDuringExecution field.\nfunc (b *PodAntiAffinityApplyConfiguration) WithRequiredDuringSchedulingIgnoredDuringExecution(values ...*PodAffinityTermApplyConfiguration) *PodAntiAffinityApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRequiredDuringSchedulingIgnoredDuringExecution\")\n\t\t}\n\t\tb.RequiredDuringSchedulingIgnoredDuringExecution = append(b.RequiredDuringSchedulingIgnoredDuringExecution, *values[i])\n\t}\n\treturn b\n}","line":{"from":34,"to":45}} {"id":100021991,"name":"WithPreferredDuringSchedulingIgnoredDuringExecution","signature":"func (b *PodAntiAffinityApplyConfiguration) WithPreferredDuringSchedulingIgnoredDuringExecution(values ...*WeightedPodAffinityTermApplyConfiguration) *PodAntiAffinityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podantiaffinity.go","code":"// WithPreferredDuringSchedulingIgnoredDuringExecution adds the given value to the PreferredDuringSchedulingIgnoredDuringExecution field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the PreferredDuringSchedulingIgnoredDuringExecution field.\nfunc (b *PodAntiAffinityApplyConfiguration) WithPreferredDuringSchedulingIgnoredDuringExecution(values ...*WeightedPodAffinityTermApplyConfiguration) *PodAntiAffinityApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPreferredDuringSchedulingIgnoredDuringExecution\")\n\t\t}\n\t\tb.PreferredDuringSchedulingIgnoredDuringExecution = append(b.PreferredDuringSchedulingIgnoredDuringExecution, *values[i])\n\t}\n\treturn b\n}","line":{"from":47,"to":58}} {"id":100021992,"name":"PodCondition","signature":"func PodCondition() *PodConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podcondition.go","code":"// PodConditionApplyConfiguration constructs an declarative configuration of the PodCondition type for use with\n// apply.\nfunc PodCondition() *PodConditionApplyConfiguration {\n\treturn \u0026PodConditionApplyConfiguration{}\n}","line":{"from":37,"to":41}} {"id":100021993,"name":"WithType","signature":"func (b *PodConditionApplyConfiguration) WithType(value v1.PodConditionType) *PodConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podcondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *PodConditionApplyConfiguration) WithType(value v1.PodConditionType) *PodConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100021994,"name":"WithStatus","signature":"func (b *PodConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *PodConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podcondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *PodConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *PodConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100021995,"name":"WithLastProbeTime","signature":"func (b *PodConditionApplyConfiguration) WithLastProbeTime(value metav1.Time) *PodConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podcondition.go","code":"// WithLastProbeTime sets the LastProbeTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastProbeTime field is set to the value of the last call.\nfunc (b *PodConditionApplyConfiguration) WithLastProbeTime(value metav1.Time) *PodConditionApplyConfiguration {\n\tb.LastProbeTime = \u0026value\n\treturn b\n}","line":{"from":59,"to":65}} {"id":100021996,"name":"WithLastTransitionTime","signature":"func (b *PodConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *PodConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podcondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *PodConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *PodConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100021997,"name":"WithReason","signature":"func (b *PodConditionApplyConfiguration) WithReason(value string) *PodConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podcondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *PodConditionApplyConfiguration) WithReason(value string) *PodConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":75,"to":81}} {"id":100021998,"name":"WithMessage","signature":"func (b *PodConditionApplyConfiguration) WithMessage(value string) *PodConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podcondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *PodConditionApplyConfiguration) WithMessage(value string) *PodConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100021999,"name":"PodDNSConfig","signature":"func PodDNSConfig() *PodDNSConfigApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/poddnsconfig.go","code":"// PodDNSConfigApplyConfiguration constructs an declarative configuration of the PodDNSConfig type for use with\n// apply.\nfunc PodDNSConfig() *PodDNSConfigApplyConfiguration {\n\treturn \u0026PodDNSConfigApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100022000,"name":"WithNameservers","signature":"func (b *PodDNSConfigApplyConfiguration) WithNameservers(values ...string) *PodDNSConfigApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/poddnsconfig.go","code":"// WithNameservers adds the given value to the Nameservers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Nameservers field.\nfunc (b *PodDNSConfigApplyConfiguration) WithNameservers(values ...string) *PodDNSConfigApplyConfiguration {\n\tfor i := range values {\n\t\tb.Nameservers = append(b.Nameservers, values[i])\n\t}\n\treturn b\n}","line":{"from":35,"to":43}} {"id":100022001,"name":"WithSearches","signature":"func (b *PodDNSConfigApplyConfiguration) WithSearches(values ...string) *PodDNSConfigApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/poddnsconfig.go","code":"// WithSearches adds the given value to the Searches field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Searches field.\nfunc (b *PodDNSConfigApplyConfiguration) WithSearches(values ...string) *PodDNSConfigApplyConfiguration {\n\tfor i := range values {\n\t\tb.Searches = append(b.Searches, values[i])\n\t}\n\treturn b\n}","line":{"from":45,"to":53}} {"id":100022002,"name":"WithOptions","signature":"func (b *PodDNSConfigApplyConfiguration) WithOptions(values ...*PodDNSConfigOptionApplyConfiguration) *PodDNSConfigApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/poddnsconfig.go","code":"// WithOptions adds the given value to the Options field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Options field.\nfunc (b *PodDNSConfigApplyConfiguration) WithOptions(values ...*PodDNSConfigOptionApplyConfiguration) *PodDNSConfigApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOptions\")\n\t\t}\n\t\tb.Options = append(b.Options, *values[i])\n\t}\n\treturn b\n}","line":{"from":55,"to":66}} {"id":100022003,"name":"PodDNSConfigOption","signature":"func PodDNSConfigOption() *PodDNSConfigOptionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/poddnsconfigoption.go","code":"// PodDNSConfigOptionApplyConfiguration constructs an declarative configuration of the PodDNSConfigOption type for use with\n// apply.\nfunc PodDNSConfigOption() *PodDNSConfigOptionApplyConfiguration {\n\treturn \u0026PodDNSConfigOptionApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100022004,"name":"WithName","signature":"func (b *PodDNSConfigOptionApplyConfiguration) WithName(value string) *PodDNSConfigOptionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/poddnsconfigoption.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *PodDNSConfigOptionApplyConfiguration) WithName(value string) *PodDNSConfigOptionApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100022005,"name":"WithValue","signature":"func (b *PodDNSConfigOptionApplyConfiguration) WithValue(value string) *PodDNSConfigOptionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/poddnsconfigoption.go","code":"// WithValue sets the Value field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Value field is set to the value of the last call.\nfunc (b *PodDNSConfigOptionApplyConfiguration) WithValue(value string) *PodDNSConfigOptionApplyConfiguration {\n\tb.Value = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100022006,"name":"PodIP","signature":"func PodIP() *PodIPApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podip.go","code":"// PodIPApplyConfiguration constructs an declarative configuration of the PodIP type for use with\n// apply.\nfunc PodIP() *PodIPApplyConfiguration {\n\treturn \u0026PodIPApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100022007,"name":"WithIP","signature":"func (b *PodIPApplyConfiguration) WithIP(value string) *PodIPApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podip.go","code":"// WithIP sets the IP field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the IP field is set to the value of the last call.\nfunc (b *PodIPApplyConfiguration) WithIP(value string) *PodIPApplyConfiguration {\n\tb.IP = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100022008,"name":"PodOS","signature":"func PodOS() *PodOSApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podos.go","code":"// PodOSApplyConfiguration constructs an declarative configuration of the PodOS type for use with\n// apply.\nfunc PodOS() *PodOSApplyConfiguration {\n\treturn \u0026PodOSApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100022009,"name":"WithName","signature":"func (b *PodOSApplyConfiguration) WithName(value v1.OSName) *PodOSApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podos.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *PodOSApplyConfiguration) WithName(value v1.OSName) *PodOSApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":37,"to":43}} {"id":100022010,"name":"PodReadinessGate","signature":"func PodReadinessGate() *PodReadinessGateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podreadinessgate.go","code":"// PodReadinessGateApplyConfiguration constructs an declarative configuration of the PodReadinessGate type for use with\n// apply.\nfunc PodReadinessGate() *PodReadinessGateApplyConfiguration {\n\treturn \u0026PodReadinessGateApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100022011,"name":"WithConditionType","signature":"func (b *PodReadinessGateApplyConfiguration) WithConditionType(value v1.PodConditionType) *PodReadinessGateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podreadinessgate.go","code":"// WithConditionType sets the ConditionType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ConditionType field is set to the value of the last call.\nfunc (b *PodReadinessGateApplyConfiguration) WithConditionType(value v1.PodConditionType) *PodReadinessGateApplyConfiguration {\n\tb.ConditionType = \u0026value\n\treturn b\n}","line":{"from":37,"to":43}} {"id":100022012,"name":"PodResourceClaim","signature":"func PodResourceClaim() *PodResourceClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podresourceclaim.go","code":"// PodResourceClaimApplyConfiguration constructs an declarative configuration of the PodResourceClaim type for use with\n// apply.\nfunc PodResourceClaim() *PodResourceClaimApplyConfiguration {\n\treturn \u0026PodResourceClaimApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100022013,"name":"WithName","signature":"func (b *PodResourceClaimApplyConfiguration) WithName(value string) *PodResourceClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podresourceclaim.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *PodResourceClaimApplyConfiguration) WithName(value string) *PodResourceClaimApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100022014,"name":"WithSource","signature":"func (b *PodResourceClaimApplyConfiguration) WithSource(value *ClaimSourceApplyConfiguration) *PodResourceClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podresourceclaim.go","code":"// WithSource sets the Source field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Source field is set to the value of the last call.\nfunc (b *PodResourceClaimApplyConfiguration) WithSource(value *ClaimSourceApplyConfiguration) *PodResourceClaimApplyConfiguration {\n\tb.Source = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100022015,"name":"PodSchedulingGate","signature":"func PodSchedulingGate() *PodSchedulingGateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podschedulinggate.go","code":"// PodSchedulingGateApplyConfiguration constructs an declarative configuration of the PodSchedulingGate type for use with\n// apply.\nfunc PodSchedulingGate() *PodSchedulingGateApplyConfiguration {\n\treturn \u0026PodSchedulingGateApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100022016,"name":"WithName","signature":"func (b *PodSchedulingGateApplyConfiguration) WithName(value string) *PodSchedulingGateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podschedulinggate.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *PodSchedulingGateApplyConfiguration) WithName(value string) *PodSchedulingGateApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100022017,"name":"PodSecurityContext","signature":"func PodSecurityContext() *PodSecurityContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podsecuritycontext.go","code":"// PodSecurityContextApplyConfiguration constructs an declarative configuration of the PodSecurityContext type for use with\n// apply.\nfunc PodSecurityContext() *PodSecurityContextApplyConfiguration {\n\treturn \u0026PodSecurityContextApplyConfiguration{}\n}","line":{"from":40,"to":44}} {"id":100022018,"name":"WithSELinuxOptions","signature":"func (b *PodSecurityContextApplyConfiguration) WithSELinuxOptions(value *SELinuxOptionsApplyConfiguration) *PodSecurityContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podsecuritycontext.go","code":"// WithSELinuxOptions sets the SELinuxOptions field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SELinuxOptions field is set to the value of the last call.\nfunc (b *PodSecurityContextApplyConfiguration) WithSELinuxOptions(value *SELinuxOptionsApplyConfiguration) *PodSecurityContextApplyConfiguration {\n\tb.SELinuxOptions = value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100022019,"name":"WithWindowsOptions","signature":"func (b *PodSecurityContextApplyConfiguration) WithWindowsOptions(value *WindowsSecurityContextOptionsApplyConfiguration) *PodSecurityContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podsecuritycontext.go","code":"// WithWindowsOptions sets the WindowsOptions field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the WindowsOptions field is set to the value of the last call.\nfunc (b *PodSecurityContextApplyConfiguration) WithWindowsOptions(value *WindowsSecurityContextOptionsApplyConfiguration) *PodSecurityContextApplyConfiguration {\n\tb.WindowsOptions = value\n\treturn b\n}","line":{"from":54,"to":60}} {"id":100022020,"name":"WithRunAsUser","signature":"func (b *PodSecurityContextApplyConfiguration) WithRunAsUser(value int64) *PodSecurityContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podsecuritycontext.go","code":"// WithRunAsUser sets the RunAsUser field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RunAsUser field is set to the value of the last call.\nfunc (b *PodSecurityContextApplyConfiguration) WithRunAsUser(value int64) *PodSecurityContextApplyConfiguration {\n\tb.RunAsUser = \u0026value\n\treturn b\n}","line":{"from":62,"to":68}} {"id":100022021,"name":"WithRunAsGroup","signature":"func (b *PodSecurityContextApplyConfiguration) WithRunAsGroup(value int64) *PodSecurityContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podsecuritycontext.go","code":"// WithRunAsGroup sets the RunAsGroup field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RunAsGroup field is set to the value of the last call.\nfunc (b *PodSecurityContextApplyConfiguration) WithRunAsGroup(value int64) *PodSecurityContextApplyConfiguration {\n\tb.RunAsGroup = \u0026value\n\treturn b\n}","line":{"from":70,"to":76}} {"id":100022022,"name":"WithRunAsNonRoot","signature":"func (b *PodSecurityContextApplyConfiguration) WithRunAsNonRoot(value bool) *PodSecurityContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podsecuritycontext.go","code":"// WithRunAsNonRoot sets the RunAsNonRoot field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RunAsNonRoot field is set to the value of the last call.\nfunc (b *PodSecurityContextApplyConfiguration) WithRunAsNonRoot(value bool) *PodSecurityContextApplyConfiguration {\n\tb.RunAsNonRoot = \u0026value\n\treturn b\n}","line":{"from":78,"to":84}} {"id":100022023,"name":"WithSupplementalGroups","signature":"func (b *PodSecurityContextApplyConfiguration) WithSupplementalGroups(values ...int64) *PodSecurityContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podsecuritycontext.go","code":"// WithSupplementalGroups adds the given value to the SupplementalGroups field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the SupplementalGroups field.\nfunc (b *PodSecurityContextApplyConfiguration) WithSupplementalGroups(values ...int64) *PodSecurityContextApplyConfiguration {\n\tfor i := range values {\n\t\tb.SupplementalGroups = append(b.SupplementalGroups, values[i])\n\t}\n\treturn b\n}","line":{"from":86,"to":94}} {"id":100022024,"name":"WithFSGroup","signature":"func (b *PodSecurityContextApplyConfiguration) WithFSGroup(value int64) *PodSecurityContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podsecuritycontext.go","code":"// WithFSGroup sets the FSGroup field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSGroup field is set to the value of the last call.\nfunc (b *PodSecurityContextApplyConfiguration) WithFSGroup(value int64) *PodSecurityContextApplyConfiguration {\n\tb.FSGroup = \u0026value\n\treturn b\n}","line":{"from":96,"to":102}} {"id":100022025,"name":"WithSysctls","signature":"func (b *PodSecurityContextApplyConfiguration) WithSysctls(values ...*SysctlApplyConfiguration) *PodSecurityContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podsecuritycontext.go","code":"// WithSysctls adds the given value to the Sysctls field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Sysctls field.\nfunc (b *PodSecurityContextApplyConfiguration) WithSysctls(values ...*SysctlApplyConfiguration) *PodSecurityContextApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithSysctls\")\n\t\t}\n\t\tb.Sysctls = append(b.Sysctls, *values[i])\n\t}\n\treturn b\n}","line":{"from":104,"to":115}} {"id":100022026,"name":"WithFSGroupChangePolicy","signature":"func (b *PodSecurityContextApplyConfiguration) WithFSGroupChangePolicy(value corev1.PodFSGroupChangePolicy) *PodSecurityContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podsecuritycontext.go","code":"// WithFSGroupChangePolicy sets the FSGroupChangePolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSGroupChangePolicy field is set to the value of the last call.\nfunc (b *PodSecurityContextApplyConfiguration) WithFSGroupChangePolicy(value corev1.PodFSGroupChangePolicy) *PodSecurityContextApplyConfiguration {\n\tb.FSGroupChangePolicy = \u0026value\n\treturn b\n}","line":{"from":117,"to":123}} {"id":100022027,"name":"WithSeccompProfile","signature":"func (b *PodSecurityContextApplyConfiguration) WithSeccompProfile(value *SeccompProfileApplyConfiguration) *PodSecurityContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podsecuritycontext.go","code":"// WithSeccompProfile sets the SeccompProfile field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SeccompProfile field is set to the value of the last call.\nfunc (b *PodSecurityContextApplyConfiguration) WithSeccompProfile(value *SeccompProfileApplyConfiguration) *PodSecurityContextApplyConfiguration {\n\tb.SeccompProfile = value\n\treturn b\n}","line":{"from":125,"to":131}} {"id":100022028,"name":"PodSpec","signature":"func PodSpec() *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// PodSpecApplyConfiguration constructs an declarative configuration of the PodSpec type for use with\n// apply.\nfunc PodSpec() *PodSpecApplyConfiguration {\n\treturn \u0026PodSpecApplyConfiguration{}\n}","line":{"from":69,"to":73}} {"id":100022029,"name":"WithVolumes","signature":"func (b *PodSpecApplyConfiguration) WithVolumes(values ...*VolumeApplyConfiguration) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithVolumes adds the given value to the Volumes field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Volumes field.\nfunc (b *PodSpecApplyConfiguration) WithVolumes(values ...*VolumeApplyConfiguration) *PodSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithVolumes\")\n\t\t}\n\t\tb.Volumes = append(b.Volumes, *values[i])\n\t}\n\treturn b\n}","line":{"from":75,"to":86}} {"id":100022030,"name":"WithInitContainers","signature":"func (b *PodSpecApplyConfiguration) WithInitContainers(values ...*ContainerApplyConfiguration) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithInitContainers adds the given value to the InitContainers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the InitContainers field.\nfunc (b *PodSpecApplyConfiguration) WithInitContainers(values ...*ContainerApplyConfiguration) *PodSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithInitContainers\")\n\t\t}\n\t\tb.InitContainers = append(b.InitContainers, *values[i])\n\t}\n\treturn b\n}","line":{"from":88,"to":99}} {"id":100022031,"name":"WithContainers","signature":"func (b *PodSpecApplyConfiguration) WithContainers(values ...*ContainerApplyConfiguration) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithContainers adds the given value to the Containers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Containers field.\nfunc (b *PodSpecApplyConfiguration) WithContainers(values ...*ContainerApplyConfiguration) *PodSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithContainers\")\n\t\t}\n\t\tb.Containers = append(b.Containers, *values[i])\n\t}\n\treturn b\n}","line":{"from":101,"to":112}} {"id":100022032,"name":"WithEphemeralContainers","signature":"func (b *PodSpecApplyConfiguration) WithEphemeralContainers(values ...*EphemeralContainerApplyConfiguration) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithEphemeralContainers adds the given value to the EphemeralContainers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the EphemeralContainers field.\nfunc (b *PodSpecApplyConfiguration) WithEphemeralContainers(values ...*EphemeralContainerApplyConfiguration) *PodSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithEphemeralContainers\")\n\t\t}\n\t\tb.EphemeralContainers = append(b.EphemeralContainers, *values[i])\n\t}\n\treturn b\n}","line":{"from":114,"to":125}} {"id":100022033,"name":"WithRestartPolicy","signature":"func (b *PodSpecApplyConfiguration) WithRestartPolicy(value corev1.RestartPolicy) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithRestartPolicy sets the RestartPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RestartPolicy field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithRestartPolicy(value corev1.RestartPolicy) *PodSpecApplyConfiguration {\n\tb.RestartPolicy = \u0026value\n\treturn b\n}","line":{"from":127,"to":133}} {"id":100022034,"name":"WithTerminationGracePeriodSeconds","signature":"func (b *PodSpecApplyConfiguration) WithTerminationGracePeriodSeconds(value int64) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithTerminationGracePeriodSeconds sets the TerminationGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TerminationGracePeriodSeconds field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithTerminationGracePeriodSeconds(value int64) *PodSpecApplyConfiguration {\n\tb.TerminationGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":135,"to":141}} {"id":100022035,"name":"WithActiveDeadlineSeconds","signature":"func (b *PodSpecApplyConfiguration) WithActiveDeadlineSeconds(value int64) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithActiveDeadlineSeconds sets the ActiveDeadlineSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ActiveDeadlineSeconds field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithActiveDeadlineSeconds(value int64) *PodSpecApplyConfiguration {\n\tb.ActiveDeadlineSeconds = \u0026value\n\treturn b\n}","line":{"from":143,"to":149}} {"id":100022036,"name":"WithDNSPolicy","signature":"func (b *PodSpecApplyConfiguration) WithDNSPolicy(value corev1.DNSPolicy) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithDNSPolicy sets the DNSPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DNSPolicy field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithDNSPolicy(value corev1.DNSPolicy) *PodSpecApplyConfiguration {\n\tb.DNSPolicy = \u0026value\n\treturn b\n}","line":{"from":151,"to":157}} {"id":100022037,"name":"WithNodeSelector","signature":"func (b *PodSpecApplyConfiguration) WithNodeSelector(entries map[string]string) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithNodeSelector puts the entries into the NodeSelector field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the NodeSelector field,\n// overwriting an existing map entries in NodeSelector field with the same key.\nfunc (b *PodSpecApplyConfiguration) WithNodeSelector(entries map[string]string) *PodSpecApplyConfiguration {\n\tif b.NodeSelector == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.NodeSelector = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.NodeSelector[k] = v\n\t}\n\treturn b\n}","line":{"from":159,"to":171}} {"id":100022038,"name":"WithServiceAccountName","signature":"func (b *PodSpecApplyConfiguration) WithServiceAccountName(value string) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithServiceAccountName sets the ServiceAccountName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ServiceAccountName field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithServiceAccountName(value string) *PodSpecApplyConfiguration {\n\tb.ServiceAccountName = \u0026value\n\treturn b\n}","line":{"from":173,"to":179}} {"id":100022039,"name":"WithDeprecatedServiceAccount","signature":"func (b *PodSpecApplyConfiguration) WithDeprecatedServiceAccount(value string) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithDeprecatedServiceAccount sets the DeprecatedServiceAccount field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeprecatedServiceAccount field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithDeprecatedServiceAccount(value string) *PodSpecApplyConfiguration {\n\tb.DeprecatedServiceAccount = \u0026value\n\treturn b\n}","line":{"from":181,"to":187}} {"id":100022040,"name":"WithAutomountServiceAccountToken","signature":"func (b *PodSpecApplyConfiguration) WithAutomountServiceAccountToken(value bool) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithAutomountServiceAccountToken sets the AutomountServiceAccountToken field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AutomountServiceAccountToken field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithAutomountServiceAccountToken(value bool) *PodSpecApplyConfiguration {\n\tb.AutomountServiceAccountToken = \u0026value\n\treturn b\n}","line":{"from":189,"to":195}} {"id":100022041,"name":"WithNodeName","signature":"func (b *PodSpecApplyConfiguration) WithNodeName(value string) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithNodeName sets the NodeName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NodeName field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithNodeName(value string) *PodSpecApplyConfiguration {\n\tb.NodeName = \u0026value\n\treturn b\n}","line":{"from":197,"to":203}} {"id":100022042,"name":"WithHostNetwork","signature":"func (b *PodSpecApplyConfiguration) WithHostNetwork(value bool) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithHostNetwork sets the HostNetwork field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HostNetwork field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithHostNetwork(value bool) *PodSpecApplyConfiguration {\n\tb.HostNetwork = \u0026value\n\treturn b\n}","line":{"from":205,"to":211}} {"id":100022043,"name":"WithHostPID","signature":"func (b *PodSpecApplyConfiguration) WithHostPID(value bool) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithHostPID sets the HostPID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HostPID field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithHostPID(value bool) *PodSpecApplyConfiguration {\n\tb.HostPID = \u0026value\n\treturn b\n}","line":{"from":213,"to":219}} {"id":100022044,"name":"WithHostIPC","signature":"func (b *PodSpecApplyConfiguration) WithHostIPC(value bool) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithHostIPC sets the HostIPC field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HostIPC field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithHostIPC(value bool) *PodSpecApplyConfiguration {\n\tb.HostIPC = \u0026value\n\treturn b\n}","line":{"from":221,"to":227}} {"id":100022045,"name":"WithShareProcessNamespace","signature":"func (b *PodSpecApplyConfiguration) WithShareProcessNamespace(value bool) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithShareProcessNamespace sets the ShareProcessNamespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ShareProcessNamespace field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithShareProcessNamespace(value bool) *PodSpecApplyConfiguration {\n\tb.ShareProcessNamespace = \u0026value\n\treturn b\n}","line":{"from":229,"to":235}} {"id":100022046,"name":"WithSecurityContext","signature":"func (b *PodSpecApplyConfiguration) WithSecurityContext(value *PodSecurityContextApplyConfiguration) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithSecurityContext sets the SecurityContext field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecurityContext field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithSecurityContext(value *PodSecurityContextApplyConfiguration) *PodSpecApplyConfiguration {\n\tb.SecurityContext = value\n\treturn b\n}","line":{"from":237,"to":243}} {"id":100022047,"name":"WithImagePullSecrets","signature":"func (b *PodSpecApplyConfiguration) WithImagePullSecrets(values ...*LocalObjectReferenceApplyConfiguration) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithImagePullSecrets adds the given value to the ImagePullSecrets field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ImagePullSecrets field.\nfunc (b *PodSpecApplyConfiguration) WithImagePullSecrets(values ...*LocalObjectReferenceApplyConfiguration) *PodSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithImagePullSecrets\")\n\t\t}\n\t\tb.ImagePullSecrets = append(b.ImagePullSecrets, *values[i])\n\t}\n\treturn b\n}","line":{"from":245,"to":256}} {"id":100022048,"name":"WithHostname","signature":"func (b *PodSpecApplyConfiguration) WithHostname(value string) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithHostname sets the Hostname field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Hostname field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithHostname(value string) *PodSpecApplyConfiguration {\n\tb.Hostname = \u0026value\n\treturn b\n}","line":{"from":258,"to":264}} {"id":100022049,"name":"WithSubdomain","signature":"func (b *PodSpecApplyConfiguration) WithSubdomain(value string) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithSubdomain sets the Subdomain field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Subdomain field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithSubdomain(value string) *PodSpecApplyConfiguration {\n\tb.Subdomain = \u0026value\n\treturn b\n}","line":{"from":266,"to":272}} {"id":100022050,"name":"WithAffinity","signature":"func (b *PodSpecApplyConfiguration) WithAffinity(value *AffinityApplyConfiguration) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithAffinity sets the Affinity field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Affinity field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithAffinity(value *AffinityApplyConfiguration) *PodSpecApplyConfiguration {\n\tb.Affinity = value\n\treturn b\n}","line":{"from":274,"to":280}} {"id":100022051,"name":"WithSchedulerName","signature":"func (b *PodSpecApplyConfiguration) WithSchedulerName(value string) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithSchedulerName sets the SchedulerName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SchedulerName field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithSchedulerName(value string) *PodSpecApplyConfiguration {\n\tb.SchedulerName = \u0026value\n\treturn b\n}","line":{"from":282,"to":288}} {"id":100022052,"name":"WithTolerations","signature":"func (b *PodSpecApplyConfiguration) WithTolerations(values ...*TolerationApplyConfiguration) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithTolerations adds the given value to the Tolerations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Tolerations field.\nfunc (b *PodSpecApplyConfiguration) WithTolerations(values ...*TolerationApplyConfiguration) *PodSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithTolerations\")\n\t\t}\n\t\tb.Tolerations = append(b.Tolerations, *values[i])\n\t}\n\treturn b\n}","line":{"from":290,"to":301}} {"id":100022053,"name":"WithHostAliases","signature":"func (b *PodSpecApplyConfiguration) WithHostAliases(values ...*HostAliasApplyConfiguration) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithHostAliases adds the given value to the HostAliases field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the HostAliases field.\nfunc (b *PodSpecApplyConfiguration) WithHostAliases(values ...*HostAliasApplyConfiguration) *PodSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithHostAliases\")\n\t\t}\n\t\tb.HostAliases = append(b.HostAliases, *values[i])\n\t}\n\treturn b\n}","line":{"from":303,"to":314}} {"id":100022054,"name":"WithPriorityClassName","signature":"func (b *PodSpecApplyConfiguration) WithPriorityClassName(value string) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithPriorityClassName sets the PriorityClassName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PriorityClassName field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithPriorityClassName(value string) *PodSpecApplyConfiguration {\n\tb.PriorityClassName = \u0026value\n\treturn b\n}","line":{"from":316,"to":322}} {"id":100022055,"name":"WithPriority","signature":"func (b *PodSpecApplyConfiguration) WithPriority(value int32) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithPriority sets the Priority field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Priority field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithPriority(value int32) *PodSpecApplyConfiguration {\n\tb.Priority = \u0026value\n\treturn b\n}","line":{"from":324,"to":330}} {"id":100022056,"name":"WithDNSConfig","signature":"func (b *PodSpecApplyConfiguration) WithDNSConfig(value *PodDNSConfigApplyConfiguration) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithDNSConfig sets the DNSConfig field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DNSConfig field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithDNSConfig(value *PodDNSConfigApplyConfiguration) *PodSpecApplyConfiguration {\n\tb.DNSConfig = value\n\treturn b\n}","line":{"from":332,"to":338}} {"id":100022057,"name":"WithReadinessGates","signature":"func (b *PodSpecApplyConfiguration) WithReadinessGates(values ...*PodReadinessGateApplyConfiguration) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithReadinessGates adds the given value to the ReadinessGates field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ReadinessGates field.\nfunc (b *PodSpecApplyConfiguration) WithReadinessGates(values ...*PodReadinessGateApplyConfiguration) *PodSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithReadinessGates\")\n\t\t}\n\t\tb.ReadinessGates = append(b.ReadinessGates, *values[i])\n\t}\n\treturn b\n}","line":{"from":340,"to":351}} {"id":100022058,"name":"WithRuntimeClassName","signature":"func (b *PodSpecApplyConfiguration) WithRuntimeClassName(value string) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithRuntimeClassName sets the RuntimeClassName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RuntimeClassName field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithRuntimeClassName(value string) *PodSpecApplyConfiguration {\n\tb.RuntimeClassName = \u0026value\n\treturn b\n}","line":{"from":353,"to":359}} {"id":100022059,"name":"WithEnableServiceLinks","signature":"func (b *PodSpecApplyConfiguration) WithEnableServiceLinks(value bool) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithEnableServiceLinks sets the EnableServiceLinks field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the EnableServiceLinks field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithEnableServiceLinks(value bool) *PodSpecApplyConfiguration {\n\tb.EnableServiceLinks = \u0026value\n\treturn b\n}","line":{"from":361,"to":367}} {"id":100022060,"name":"WithPreemptionPolicy","signature":"func (b *PodSpecApplyConfiguration) WithPreemptionPolicy(value corev1.PreemptionPolicy) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithPreemptionPolicy sets the PreemptionPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PreemptionPolicy field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithPreemptionPolicy(value corev1.PreemptionPolicy) *PodSpecApplyConfiguration {\n\tb.PreemptionPolicy = \u0026value\n\treturn b\n}","line":{"from":369,"to":375}} {"id":100022061,"name":"WithOverhead","signature":"func (b *PodSpecApplyConfiguration) WithOverhead(value corev1.ResourceList) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithOverhead sets the Overhead field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Overhead field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithOverhead(value corev1.ResourceList) *PodSpecApplyConfiguration {\n\tb.Overhead = \u0026value\n\treturn b\n}","line":{"from":377,"to":383}} {"id":100022062,"name":"WithTopologySpreadConstraints","signature":"func (b *PodSpecApplyConfiguration) WithTopologySpreadConstraints(values ...*TopologySpreadConstraintApplyConfiguration) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithTopologySpreadConstraints adds the given value to the TopologySpreadConstraints field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the TopologySpreadConstraints field.\nfunc (b *PodSpecApplyConfiguration) WithTopologySpreadConstraints(values ...*TopologySpreadConstraintApplyConfiguration) *PodSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithTopologySpreadConstraints\")\n\t\t}\n\t\tb.TopologySpreadConstraints = append(b.TopologySpreadConstraints, *values[i])\n\t}\n\treturn b\n}","line":{"from":385,"to":396}} {"id":100022063,"name":"WithSetHostnameAsFQDN","signature":"func (b *PodSpecApplyConfiguration) WithSetHostnameAsFQDN(value bool) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithSetHostnameAsFQDN sets the SetHostnameAsFQDN field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SetHostnameAsFQDN field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithSetHostnameAsFQDN(value bool) *PodSpecApplyConfiguration {\n\tb.SetHostnameAsFQDN = \u0026value\n\treturn b\n}","line":{"from":398,"to":404}} {"id":100022064,"name":"WithOS","signature":"func (b *PodSpecApplyConfiguration) WithOS(value *PodOSApplyConfiguration) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithOS sets the OS field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the OS field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithOS(value *PodOSApplyConfiguration) *PodSpecApplyConfiguration {\n\tb.OS = value\n\treturn b\n}","line":{"from":406,"to":412}} {"id":100022065,"name":"WithHostUsers","signature":"func (b *PodSpecApplyConfiguration) WithHostUsers(value bool) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithHostUsers sets the HostUsers field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HostUsers field is set to the value of the last call.\nfunc (b *PodSpecApplyConfiguration) WithHostUsers(value bool) *PodSpecApplyConfiguration {\n\tb.HostUsers = \u0026value\n\treturn b\n}","line":{"from":414,"to":420}} {"id":100022066,"name":"WithSchedulingGates","signature":"func (b *PodSpecApplyConfiguration) WithSchedulingGates(values ...*PodSchedulingGateApplyConfiguration) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithSchedulingGates adds the given value to the SchedulingGates field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the SchedulingGates field.\nfunc (b *PodSpecApplyConfiguration) WithSchedulingGates(values ...*PodSchedulingGateApplyConfiguration) *PodSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithSchedulingGates\")\n\t\t}\n\t\tb.SchedulingGates = append(b.SchedulingGates, *values[i])\n\t}\n\treturn b\n}","line":{"from":422,"to":433}} {"id":100022067,"name":"WithResourceClaims","signature":"func (b *PodSpecApplyConfiguration) WithResourceClaims(values ...*PodResourceClaimApplyConfiguration) *PodSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podspec.go","code":"// WithResourceClaims adds the given value to the ResourceClaims field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ResourceClaims field.\nfunc (b *PodSpecApplyConfiguration) WithResourceClaims(values ...*PodResourceClaimApplyConfiguration) *PodSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithResourceClaims\")\n\t\t}\n\t\tb.ResourceClaims = append(b.ResourceClaims, *values[i])\n\t}\n\treturn b\n}","line":{"from":435,"to":446}} {"id":100022068,"name":"PodStatus","signature":"func PodStatus() *PodStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podstatus.go","code":"// PodStatusApplyConfiguration constructs an declarative configuration of the PodStatus type for use with\n// apply.\nfunc PodStatus() *PodStatusApplyConfiguration {\n\treturn \u0026PodStatusApplyConfiguration{}\n}","line":{"from":45,"to":49}} {"id":100022069,"name":"WithPhase","signature":"func (b *PodStatusApplyConfiguration) WithPhase(value v1.PodPhase) *PodStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podstatus.go","code":"// WithPhase sets the Phase field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Phase field is set to the value of the last call.\nfunc (b *PodStatusApplyConfiguration) WithPhase(value v1.PodPhase) *PodStatusApplyConfiguration {\n\tb.Phase = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100022070,"name":"WithConditions","signature":"func (b *PodStatusApplyConfiguration) WithConditions(values ...*PodConditionApplyConfiguration) *PodStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *PodStatusApplyConfiguration) WithConditions(values ...*PodConditionApplyConfiguration) *PodStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":59,"to":70}} {"id":100022071,"name":"WithMessage","signature":"func (b *PodStatusApplyConfiguration) WithMessage(value string) *PodStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podstatus.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *PodStatusApplyConfiguration) WithMessage(value string) *PodStatusApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":72,"to":78}} {"id":100022072,"name":"WithReason","signature":"func (b *PodStatusApplyConfiguration) WithReason(value string) *PodStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podstatus.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *PodStatusApplyConfiguration) WithReason(value string) *PodStatusApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":80,"to":86}} {"id":100022073,"name":"WithNominatedNodeName","signature":"func (b *PodStatusApplyConfiguration) WithNominatedNodeName(value string) *PodStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podstatus.go","code":"// WithNominatedNodeName sets the NominatedNodeName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NominatedNodeName field is set to the value of the last call.\nfunc (b *PodStatusApplyConfiguration) WithNominatedNodeName(value string) *PodStatusApplyConfiguration {\n\tb.NominatedNodeName = \u0026value\n\treturn b\n}","line":{"from":88,"to":94}} {"id":100022074,"name":"WithHostIP","signature":"func (b *PodStatusApplyConfiguration) WithHostIP(value string) *PodStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podstatus.go","code":"// WithHostIP sets the HostIP field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HostIP field is set to the value of the last call.\nfunc (b *PodStatusApplyConfiguration) WithHostIP(value string) *PodStatusApplyConfiguration {\n\tb.HostIP = \u0026value\n\treturn b\n}","line":{"from":96,"to":102}} {"id":100022075,"name":"WithPodIP","signature":"func (b *PodStatusApplyConfiguration) WithPodIP(value string) *PodStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podstatus.go","code":"// WithPodIP sets the PodIP field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PodIP field is set to the value of the last call.\nfunc (b *PodStatusApplyConfiguration) WithPodIP(value string) *PodStatusApplyConfiguration {\n\tb.PodIP = \u0026value\n\treturn b\n}","line":{"from":104,"to":110}} {"id":100022076,"name":"WithPodIPs","signature":"func (b *PodStatusApplyConfiguration) WithPodIPs(values ...*PodIPApplyConfiguration) *PodStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podstatus.go","code":"// WithPodIPs adds the given value to the PodIPs field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the PodIPs field.\nfunc (b *PodStatusApplyConfiguration) WithPodIPs(values ...*PodIPApplyConfiguration) *PodStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPodIPs\")\n\t\t}\n\t\tb.PodIPs = append(b.PodIPs, *values[i])\n\t}\n\treturn b\n}","line":{"from":112,"to":123}} {"id":100022077,"name":"WithStartTime","signature":"func (b *PodStatusApplyConfiguration) WithStartTime(value metav1.Time) *PodStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podstatus.go","code":"// WithStartTime sets the StartTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StartTime field is set to the value of the last call.\nfunc (b *PodStatusApplyConfiguration) WithStartTime(value metav1.Time) *PodStatusApplyConfiguration {\n\tb.StartTime = \u0026value\n\treturn b\n}","line":{"from":125,"to":131}} {"id":100022078,"name":"WithInitContainerStatuses","signature":"func (b *PodStatusApplyConfiguration) WithInitContainerStatuses(values ...*ContainerStatusApplyConfiguration) *PodStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podstatus.go","code":"// WithInitContainerStatuses adds the given value to the InitContainerStatuses field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the InitContainerStatuses field.\nfunc (b *PodStatusApplyConfiguration) WithInitContainerStatuses(values ...*ContainerStatusApplyConfiguration) *PodStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithInitContainerStatuses\")\n\t\t}\n\t\tb.InitContainerStatuses = append(b.InitContainerStatuses, *values[i])\n\t}\n\treturn b\n}","line":{"from":133,"to":144}} {"id":100022079,"name":"WithContainerStatuses","signature":"func (b *PodStatusApplyConfiguration) WithContainerStatuses(values ...*ContainerStatusApplyConfiguration) *PodStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podstatus.go","code":"// WithContainerStatuses adds the given value to the ContainerStatuses field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ContainerStatuses field.\nfunc (b *PodStatusApplyConfiguration) WithContainerStatuses(values ...*ContainerStatusApplyConfiguration) *PodStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithContainerStatuses\")\n\t\t}\n\t\tb.ContainerStatuses = append(b.ContainerStatuses, *values[i])\n\t}\n\treturn b\n}","line":{"from":146,"to":157}} {"id":100022080,"name":"WithQOSClass","signature":"func (b *PodStatusApplyConfiguration) WithQOSClass(value v1.PodQOSClass) *PodStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podstatus.go","code":"// WithQOSClass sets the QOSClass field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the QOSClass field is set to the value of the last call.\nfunc (b *PodStatusApplyConfiguration) WithQOSClass(value v1.PodQOSClass) *PodStatusApplyConfiguration {\n\tb.QOSClass = \u0026value\n\treturn b\n}","line":{"from":159,"to":165}} {"id":100022081,"name":"WithEphemeralContainerStatuses","signature":"func (b *PodStatusApplyConfiguration) WithEphemeralContainerStatuses(values ...*ContainerStatusApplyConfiguration) *PodStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podstatus.go","code":"// WithEphemeralContainerStatuses adds the given value to the EphemeralContainerStatuses field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the EphemeralContainerStatuses field.\nfunc (b *PodStatusApplyConfiguration) WithEphemeralContainerStatuses(values ...*ContainerStatusApplyConfiguration) *PodStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithEphemeralContainerStatuses\")\n\t\t}\n\t\tb.EphemeralContainerStatuses = append(b.EphemeralContainerStatuses, *values[i])\n\t}\n\treturn b\n}","line":{"from":167,"to":178}} {"id":100022082,"name":"WithResize","signature":"func (b *PodStatusApplyConfiguration) WithResize(value v1.PodResizeStatus) *PodStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podstatus.go","code":"// WithResize sets the Resize field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Resize field is set to the value of the last call.\nfunc (b *PodStatusApplyConfiguration) WithResize(value v1.PodResizeStatus) *PodStatusApplyConfiguration {\n\tb.Resize = \u0026value\n\treturn b\n}","line":{"from":180,"to":186}} {"id":100022083,"name":"PodTemplate","signature":"func PodTemplate(name, namespace string) *PodTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplate.go","code":"// PodTemplate constructs an declarative configuration of the PodTemplate type for use with\n// apply.\nfunc PodTemplate(name, namespace string) *PodTemplateApplyConfiguration {\n\tb := \u0026PodTemplateApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"PodTemplate\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b\n}","line":{"from":38,"to":47}} {"id":100022084,"name":"ExtractPodTemplate","signature":"func ExtractPodTemplate(podTemplate *apicorev1.PodTemplate, fieldManager string) (*PodTemplateApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplate.go","code":"// ExtractPodTemplate extracts the applied configuration owned by fieldManager from\n// podTemplate. If no managedFields are found in podTemplate for fieldManager, a\n// PodTemplateApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// podTemplate must be a unmodified PodTemplate API object that was retrieved from the Kubernetes API.\n// ExtractPodTemplate provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractPodTemplate(podTemplate *apicorev1.PodTemplate, fieldManager string) (*PodTemplateApplyConfiguration, error) {\n\treturn extractPodTemplate(podTemplate, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100022085,"name":"ExtractPodTemplateStatus","signature":"func ExtractPodTemplateStatus(podTemplate *apicorev1.PodTemplate, fieldManager string) (*PodTemplateApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplate.go","code":"// ExtractPodTemplateStatus is the same as ExtractPodTemplate except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractPodTemplateStatus(podTemplate *apicorev1.PodTemplate, fieldManager string) (*PodTemplateApplyConfiguration, error) {\n\treturn extractPodTemplate(podTemplate, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100022086,"name":"extractPodTemplate","signature":"func extractPodTemplate(podTemplate *apicorev1.PodTemplate, fieldManager string, subresource string) (*PodTemplateApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplate.go","code":"func extractPodTemplate(podTemplate *apicorev1.PodTemplate, fieldManager string, subresource string) (*PodTemplateApplyConfiguration, error) {\n\tb := \u0026PodTemplateApplyConfiguration{}\n\terr := managedfields.ExtractInto(podTemplate, internal.Parser().Type(\"io.k8s.api.core.v1.PodTemplate\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(podTemplate.Name)\n\tb.WithNamespace(podTemplate.Namespace)\n\n\tb.WithKind(\"PodTemplate\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b, nil\n}","line":{"from":71,"to":83}} {"id":100022087,"name":"WithKind","signature":"func (b *PodTemplateApplyConfiguration) WithKind(value string) *PodTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplate.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *PodTemplateApplyConfiguration) WithKind(value string) *PodTemplateApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":85,"to":91}} {"id":100022088,"name":"WithAPIVersion","signature":"func (b *PodTemplateApplyConfiguration) WithAPIVersion(value string) *PodTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplate.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *PodTemplateApplyConfiguration) WithAPIVersion(value string) *PodTemplateApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":93,"to":99}} {"id":100022089,"name":"WithName","signature":"func (b *PodTemplateApplyConfiguration) WithName(value string) *PodTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplate.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *PodTemplateApplyConfiguration) WithName(value string) *PodTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":101,"to":108}} {"id":100022090,"name":"WithGenerateName","signature":"func (b *PodTemplateApplyConfiguration) WithGenerateName(value string) *PodTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplate.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *PodTemplateApplyConfiguration) WithGenerateName(value string) *PodTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":110,"to":117}} {"id":100022091,"name":"WithNamespace","signature":"func (b *PodTemplateApplyConfiguration) WithNamespace(value string) *PodTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplate.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *PodTemplateApplyConfiguration) WithNamespace(value string) *PodTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":119,"to":126}} {"id":100022092,"name":"WithUID","signature":"func (b *PodTemplateApplyConfiguration) WithUID(value types.UID) *PodTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplate.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *PodTemplateApplyConfiguration) WithUID(value types.UID) *PodTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":128,"to":135}} {"id":100022093,"name":"WithResourceVersion","signature":"func (b *PodTemplateApplyConfiguration) WithResourceVersion(value string) *PodTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplate.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *PodTemplateApplyConfiguration) WithResourceVersion(value string) *PodTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":137,"to":144}} {"id":100022094,"name":"WithGeneration","signature":"func (b *PodTemplateApplyConfiguration) WithGeneration(value int64) *PodTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplate.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *PodTemplateApplyConfiguration) WithGeneration(value int64) *PodTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":146,"to":153}} {"id":100022095,"name":"WithCreationTimestamp","signature":"func (b *PodTemplateApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PodTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplate.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *PodTemplateApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PodTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":155,"to":162}} {"id":100022096,"name":"WithDeletionTimestamp","signature":"func (b *PodTemplateApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PodTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplate.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *PodTemplateApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PodTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":164,"to":171}} {"id":100022097,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *PodTemplateApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PodTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplate.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *PodTemplateApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PodTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":173,"to":180}} {"id":100022098,"name":"WithLabels","signature":"func (b *PodTemplateApplyConfiguration) WithLabels(entries map[string]string) *PodTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplate.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *PodTemplateApplyConfiguration) WithLabels(entries map[string]string) *PodTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":182,"to":195}} {"id":100022099,"name":"WithAnnotations","signature":"func (b *PodTemplateApplyConfiguration) WithAnnotations(entries map[string]string) *PodTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplate.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *PodTemplateApplyConfiguration) WithAnnotations(entries map[string]string) *PodTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":197,"to":210}} {"id":100022100,"name":"WithOwnerReferences","signature":"func (b *PodTemplateApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PodTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplate.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *PodTemplateApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PodTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":212,"to":224}} {"id":100022101,"name":"WithFinalizers","signature":"func (b *PodTemplateApplyConfiguration) WithFinalizers(values ...string) *PodTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplate.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *PodTemplateApplyConfiguration) WithFinalizers(values ...string) *PodTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":226,"to":235}} {"id":100022102,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *PodTemplateApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplate.go","code":"func (b *PodTemplateApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":237,"to":241}} {"id":100022103,"name":"WithTemplate","signature":"func (b *PodTemplateApplyConfiguration) WithTemplate(value *PodTemplateSpecApplyConfiguration) *PodTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplate.go","code":"// WithTemplate sets the Template field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Template field is set to the value of the last call.\nfunc (b *PodTemplateApplyConfiguration) WithTemplate(value *PodTemplateSpecApplyConfiguration) *PodTemplateApplyConfiguration {\n\tb.Template = value\n\treturn b\n}","line":{"from":243,"to":249}} {"id":100022104,"name":"PodTemplateSpec","signature":"func PodTemplateSpec() *PodTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplatespec.go","code":"// PodTemplateSpecApplyConfiguration constructs an declarative configuration of the PodTemplateSpec type for use with\n// apply.\nfunc PodTemplateSpec() *PodTemplateSpecApplyConfiguration {\n\treturn \u0026PodTemplateSpecApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100022105,"name":"WithName","signature":"func (b *PodTemplateSpecApplyConfiguration) WithName(value string) *PodTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplatespec.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *PodTemplateSpecApplyConfiguration) WithName(value string) *PodTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":40,"to":47}} {"id":100022106,"name":"WithGenerateName","signature":"func (b *PodTemplateSpecApplyConfiguration) WithGenerateName(value string) *PodTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplatespec.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *PodTemplateSpecApplyConfiguration) WithGenerateName(value string) *PodTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":49,"to":56}} {"id":100022107,"name":"WithNamespace","signature":"func (b *PodTemplateSpecApplyConfiguration) WithNamespace(value string) *PodTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplatespec.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *PodTemplateSpecApplyConfiguration) WithNamespace(value string) *PodTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":58,"to":65}} {"id":100022108,"name":"WithUID","signature":"func (b *PodTemplateSpecApplyConfiguration) WithUID(value types.UID) *PodTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplatespec.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *PodTemplateSpecApplyConfiguration) WithUID(value types.UID) *PodTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":67,"to":74}} {"id":100022109,"name":"WithResourceVersion","signature":"func (b *PodTemplateSpecApplyConfiguration) WithResourceVersion(value string) *PodTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplatespec.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *PodTemplateSpecApplyConfiguration) WithResourceVersion(value string) *PodTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":76,"to":83}} {"id":100022110,"name":"WithGeneration","signature":"func (b *PodTemplateSpecApplyConfiguration) WithGeneration(value int64) *PodTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplatespec.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *PodTemplateSpecApplyConfiguration) WithGeneration(value int64) *PodTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":85,"to":92}} {"id":100022111,"name":"WithCreationTimestamp","signature":"func (b *PodTemplateSpecApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PodTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplatespec.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *PodTemplateSpecApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PodTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":94,"to":101}} {"id":100022112,"name":"WithDeletionTimestamp","signature":"func (b *PodTemplateSpecApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PodTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplatespec.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *PodTemplateSpecApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PodTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":103,"to":110}} {"id":100022113,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *PodTemplateSpecApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PodTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplatespec.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *PodTemplateSpecApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PodTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":112,"to":119}} {"id":100022114,"name":"WithLabels","signature":"func (b *PodTemplateSpecApplyConfiguration) WithLabels(entries map[string]string) *PodTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplatespec.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *PodTemplateSpecApplyConfiguration) WithLabels(entries map[string]string) *PodTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":121,"to":134}} {"id":100022115,"name":"WithAnnotations","signature":"func (b *PodTemplateSpecApplyConfiguration) WithAnnotations(entries map[string]string) *PodTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplatespec.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *PodTemplateSpecApplyConfiguration) WithAnnotations(entries map[string]string) *PodTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":136,"to":149}} {"id":100022116,"name":"WithOwnerReferences","signature":"func (b *PodTemplateSpecApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PodTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplatespec.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *PodTemplateSpecApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PodTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":151,"to":163}} {"id":100022117,"name":"WithFinalizers","signature":"func (b *PodTemplateSpecApplyConfiguration) WithFinalizers(values ...string) *PodTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplatespec.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *PodTemplateSpecApplyConfiguration) WithFinalizers(values ...string) *PodTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":165,"to":174}} {"id":100022118,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *PodTemplateSpecApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplatespec.go","code":"func (b *PodTemplateSpecApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":176,"to":180}} {"id":100022119,"name":"WithSpec","signature":"func (b *PodTemplateSpecApplyConfiguration) WithSpec(value *PodSpecApplyConfiguration) *PodTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/podtemplatespec.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *PodTemplateSpecApplyConfiguration) WithSpec(value *PodSpecApplyConfiguration) *PodTemplateSpecApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":182,"to":188}} {"id":100022120,"name":"PortStatus","signature":"func PortStatus() *PortStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/portstatus.go","code":"// PortStatusApplyConfiguration constructs an declarative configuration of the PortStatus type for use with\n// apply.\nfunc PortStatus() *PortStatusApplyConfiguration {\n\treturn \u0026PortStatusApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100022121,"name":"WithPort","signature":"func (b *PortStatusApplyConfiguration) WithPort(value int32) *PortStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/portstatus.go","code":"// WithPort sets the Port field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Port field is set to the value of the last call.\nfunc (b *PortStatusApplyConfiguration) WithPort(value int32) *PortStatusApplyConfiguration {\n\tb.Port = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100022122,"name":"WithProtocol","signature":"func (b *PortStatusApplyConfiguration) WithProtocol(value v1.Protocol) *PortStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/portstatus.go","code":"// WithProtocol sets the Protocol field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Protocol field is set to the value of the last call.\nfunc (b *PortStatusApplyConfiguration) WithProtocol(value v1.Protocol) *PortStatusApplyConfiguration {\n\tb.Protocol = \u0026value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100022123,"name":"WithError","signature":"func (b *PortStatusApplyConfiguration) WithError(value string) *PortStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/portstatus.go","code":"// WithError sets the Error field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Error field is set to the value of the last call.\nfunc (b *PortStatusApplyConfiguration) WithError(value string) *PortStatusApplyConfiguration {\n\tb.Error = \u0026value\n\treturn b\n}","line":{"from":55,"to":61}} {"id":100022124,"name":"PortworxVolumeSource","signature":"func PortworxVolumeSource() *PortworxVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/portworxvolumesource.go","code":"// PortworxVolumeSourceApplyConfiguration constructs an declarative configuration of the PortworxVolumeSource type for use with\n// apply.\nfunc PortworxVolumeSource() *PortworxVolumeSourceApplyConfiguration {\n\treturn \u0026PortworxVolumeSourceApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100022125,"name":"WithVolumeID","signature":"func (b *PortworxVolumeSourceApplyConfiguration) WithVolumeID(value string) *PortworxVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/portworxvolumesource.go","code":"// WithVolumeID sets the VolumeID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the VolumeID field is set to the value of the last call.\nfunc (b *PortworxVolumeSourceApplyConfiguration) WithVolumeID(value string) *PortworxVolumeSourceApplyConfiguration {\n\tb.VolumeID = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100022126,"name":"WithFSType","signature":"func (b *PortworxVolumeSourceApplyConfiguration) WithFSType(value string) *PortworxVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/portworxvolumesource.go","code":"// WithFSType sets the FSType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSType field is set to the value of the last call.\nfunc (b *PortworxVolumeSourceApplyConfiguration) WithFSType(value string) *PortworxVolumeSourceApplyConfiguration {\n\tb.FSType = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100022127,"name":"WithReadOnly","signature":"func (b *PortworxVolumeSourceApplyConfiguration) WithReadOnly(value bool) *PortworxVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/portworxvolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *PortworxVolumeSourceApplyConfiguration) WithReadOnly(value bool) *PortworxVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100022128,"name":"PreferredSchedulingTerm","signature":"func PreferredSchedulingTerm() *PreferredSchedulingTermApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/preferredschedulingterm.go","code":"// PreferredSchedulingTermApplyConfiguration constructs an declarative configuration of the PreferredSchedulingTerm type for use with\n// apply.\nfunc PreferredSchedulingTerm() *PreferredSchedulingTermApplyConfiguration {\n\treturn \u0026PreferredSchedulingTermApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100022129,"name":"WithWeight","signature":"func (b *PreferredSchedulingTermApplyConfiguration) WithWeight(value int32) *PreferredSchedulingTermApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/preferredschedulingterm.go","code":"// WithWeight sets the Weight field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Weight field is set to the value of the last call.\nfunc (b *PreferredSchedulingTermApplyConfiguration) WithWeight(value int32) *PreferredSchedulingTermApplyConfiguration {\n\tb.Weight = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100022130,"name":"WithPreference","signature":"func (b *PreferredSchedulingTermApplyConfiguration) WithPreference(value *NodeSelectorTermApplyConfiguration) *PreferredSchedulingTermApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/preferredschedulingterm.go","code":"// WithPreference sets the Preference field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Preference field is set to the value of the last call.\nfunc (b *PreferredSchedulingTermApplyConfiguration) WithPreference(value *NodeSelectorTermApplyConfiguration) *PreferredSchedulingTermApplyConfiguration {\n\tb.Preference = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100022131,"name":"Probe","signature":"func Probe() *ProbeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/probe.go","code":"// ProbeApplyConfiguration constructs an declarative configuration of the Probe type for use with\n// apply.\nfunc Probe() *ProbeApplyConfiguration {\n\treturn \u0026ProbeApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100022132,"name":"WithExec","signature":"func (b *ProbeApplyConfiguration) WithExec(value *ExecActionApplyConfiguration) *ProbeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/probe.go","code":"// WithExec sets the Exec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Exec field is set to the value of the last call.\nfunc (b *ProbeApplyConfiguration) WithExec(value *ExecActionApplyConfiguration) *ProbeApplyConfiguration {\n\tb.Exec = value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100022133,"name":"WithHTTPGet","signature":"func (b *ProbeApplyConfiguration) WithHTTPGet(value *HTTPGetActionApplyConfiguration) *ProbeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/probe.go","code":"// WithHTTPGet sets the HTTPGet field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HTTPGet field is set to the value of the last call.\nfunc (b *ProbeApplyConfiguration) WithHTTPGet(value *HTTPGetActionApplyConfiguration) *ProbeApplyConfiguration {\n\tb.HTTPGet = value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100022134,"name":"WithTCPSocket","signature":"func (b *ProbeApplyConfiguration) WithTCPSocket(value *TCPSocketActionApplyConfiguration) *ProbeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/probe.go","code":"// WithTCPSocket sets the TCPSocket field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TCPSocket field is set to the value of the last call.\nfunc (b *ProbeApplyConfiguration) WithTCPSocket(value *TCPSocketActionApplyConfiguration) *ProbeApplyConfiguration {\n\tb.TCPSocket = value\n\treturn b\n}","line":{"from":55,"to":61}} {"id":100022135,"name":"WithGRPC","signature":"func (b *ProbeApplyConfiguration) WithGRPC(value *GRPCActionApplyConfiguration) *ProbeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/probe.go","code":"// WithGRPC sets the GRPC field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GRPC field is set to the value of the last call.\nfunc (b *ProbeApplyConfiguration) WithGRPC(value *GRPCActionApplyConfiguration) *ProbeApplyConfiguration {\n\tb.GRPC = value\n\treturn b\n}","line":{"from":63,"to":69}} {"id":100022136,"name":"WithInitialDelaySeconds","signature":"func (b *ProbeApplyConfiguration) WithInitialDelaySeconds(value int32) *ProbeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/probe.go","code":"// WithInitialDelaySeconds sets the InitialDelaySeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the InitialDelaySeconds field is set to the value of the last call.\nfunc (b *ProbeApplyConfiguration) WithInitialDelaySeconds(value int32) *ProbeApplyConfiguration {\n\tb.InitialDelaySeconds = \u0026value\n\treturn b\n}","line":{"from":71,"to":77}} {"id":100022137,"name":"WithTimeoutSeconds","signature":"func (b *ProbeApplyConfiguration) WithTimeoutSeconds(value int32) *ProbeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/probe.go","code":"// WithTimeoutSeconds sets the TimeoutSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TimeoutSeconds field is set to the value of the last call.\nfunc (b *ProbeApplyConfiguration) WithTimeoutSeconds(value int32) *ProbeApplyConfiguration {\n\tb.TimeoutSeconds = \u0026value\n\treturn b\n}","line":{"from":79,"to":85}} {"id":100022138,"name":"WithPeriodSeconds","signature":"func (b *ProbeApplyConfiguration) WithPeriodSeconds(value int32) *ProbeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/probe.go","code":"// WithPeriodSeconds sets the PeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PeriodSeconds field is set to the value of the last call.\nfunc (b *ProbeApplyConfiguration) WithPeriodSeconds(value int32) *ProbeApplyConfiguration {\n\tb.PeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":87,"to":93}} {"id":100022139,"name":"WithSuccessThreshold","signature":"func (b *ProbeApplyConfiguration) WithSuccessThreshold(value int32) *ProbeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/probe.go","code":"// WithSuccessThreshold sets the SuccessThreshold field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SuccessThreshold field is set to the value of the last call.\nfunc (b *ProbeApplyConfiguration) WithSuccessThreshold(value int32) *ProbeApplyConfiguration {\n\tb.SuccessThreshold = \u0026value\n\treturn b\n}","line":{"from":95,"to":101}} {"id":100022140,"name":"WithFailureThreshold","signature":"func (b *ProbeApplyConfiguration) WithFailureThreshold(value int32) *ProbeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/probe.go","code":"// WithFailureThreshold sets the FailureThreshold field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FailureThreshold field is set to the value of the last call.\nfunc (b *ProbeApplyConfiguration) WithFailureThreshold(value int32) *ProbeApplyConfiguration {\n\tb.FailureThreshold = \u0026value\n\treturn b\n}","line":{"from":103,"to":109}} {"id":100022141,"name":"WithTerminationGracePeriodSeconds","signature":"func (b *ProbeApplyConfiguration) WithTerminationGracePeriodSeconds(value int64) *ProbeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/probe.go","code":"// WithTerminationGracePeriodSeconds sets the TerminationGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TerminationGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ProbeApplyConfiguration) WithTerminationGracePeriodSeconds(value int64) *ProbeApplyConfiguration {\n\tb.TerminationGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":111,"to":117}} {"id":100022142,"name":"ProbeHandler","signature":"func ProbeHandler() *ProbeHandlerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/probehandler.go","code":"// ProbeHandlerApplyConfiguration constructs an declarative configuration of the ProbeHandler type for use with\n// apply.\nfunc ProbeHandler() *ProbeHandlerApplyConfiguration {\n\treturn \u0026ProbeHandlerApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100022143,"name":"WithExec","signature":"func (b *ProbeHandlerApplyConfiguration) WithExec(value *ExecActionApplyConfiguration) *ProbeHandlerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/probehandler.go","code":"// WithExec sets the Exec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Exec field is set to the value of the last call.\nfunc (b *ProbeHandlerApplyConfiguration) WithExec(value *ExecActionApplyConfiguration) *ProbeHandlerApplyConfiguration {\n\tb.Exec = value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100022144,"name":"WithHTTPGet","signature":"func (b *ProbeHandlerApplyConfiguration) WithHTTPGet(value *HTTPGetActionApplyConfiguration) *ProbeHandlerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/probehandler.go","code":"// WithHTTPGet sets the HTTPGet field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HTTPGet field is set to the value of the last call.\nfunc (b *ProbeHandlerApplyConfiguration) WithHTTPGet(value *HTTPGetActionApplyConfiguration) *ProbeHandlerApplyConfiguration {\n\tb.HTTPGet = value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100022145,"name":"WithTCPSocket","signature":"func (b *ProbeHandlerApplyConfiguration) WithTCPSocket(value *TCPSocketActionApplyConfiguration) *ProbeHandlerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/probehandler.go","code":"// WithTCPSocket sets the TCPSocket field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TCPSocket field is set to the value of the last call.\nfunc (b *ProbeHandlerApplyConfiguration) WithTCPSocket(value *TCPSocketActionApplyConfiguration) *ProbeHandlerApplyConfiguration {\n\tb.TCPSocket = value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100022146,"name":"WithGRPC","signature":"func (b *ProbeHandlerApplyConfiguration) WithGRPC(value *GRPCActionApplyConfiguration) *ProbeHandlerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/probehandler.go","code":"// WithGRPC sets the GRPC field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GRPC field is set to the value of the last call.\nfunc (b *ProbeHandlerApplyConfiguration) WithGRPC(value *GRPCActionApplyConfiguration) *ProbeHandlerApplyConfiguration {\n\tb.GRPC = value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100022147,"name":"ProjectedVolumeSource","signature":"func ProjectedVolumeSource() *ProjectedVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/projectedvolumesource.go","code":"// ProjectedVolumeSourceApplyConfiguration constructs an declarative configuration of the ProjectedVolumeSource type for use with\n// apply.\nfunc ProjectedVolumeSource() *ProjectedVolumeSourceApplyConfiguration {\n\treturn \u0026ProjectedVolumeSourceApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100022148,"name":"WithSources","signature":"func (b *ProjectedVolumeSourceApplyConfiguration) WithSources(values ...*VolumeProjectionApplyConfiguration) *ProjectedVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/projectedvolumesource.go","code":"// WithSources adds the given value to the Sources field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Sources field.\nfunc (b *ProjectedVolumeSourceApplyConfiguration) WithSources(values ...*VolumeProjectionApplyConfiguration) *ProjectedVolumeSourceApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithSources\")\n\t\t}\n\t\tb.Sources = append(b.Sources, *values[i])\n\t}\n\treturn b\n}","line":{"from":34,"to":45}} {"id":100022149,"name":"WithDefaultMode","signature":"func (b *ProjectedVolumeSourceApplyConfiguration) WithDefaultMode(value int32) *ProjectedVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/projectedvolumesource.go","code":"// WithDefaultMode sets the DefaultMode field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DefaultMode field is set to the value of the last call.\nfunc (b *ProjectedVolumeSourceApplyConfiguration) WithDefaultMode(value int32) *ProjectedVolumeSourceApplyConfiguration {\n\tb.DefaultMode = \u0026value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100022150,"name":"QuobyteVolumeSource","signature":"func QuobyteVolumeSource() *QuobyteVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/quobytevolumesource.go","code":"// QuobyteVolumeSourceApplyConfiguration constructs an declarative configuration of the QuobyteVolumeSource type for use with\n// apply.\nfunc QuobyteVolumeSource() *QuobyteVolumeSourceApplyConfiguration {\n\treturn \u0026QuobyteVolumeSourceApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100022151,"name":"WithRegistry","signature":"func (b *QuobyteVolumeSourceApplyConfiguration) WithRegistry(value string) *QuobyteVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/quobytevolumesource.go","code":"// WithRegistry sets the Registry field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Registry field is set to the value of the last call.\nfunc (b *QuobyteVolumeSourceApplyConfiguration) WithRegistry(value string) *QuobyteVolumeSourceApplyConfiguration {\n\tb.Registry = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100022152,"name":"WithVolume","signature":"func (b *QuobyteVolumeSourceApplyConfiguration) WithVolume(value string) *QuobyteVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/quobytevolumesource.go","code":"// WithVolume sets the Volume field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Volume field is set to the value of the last call.\nfunc (b *QuobyteVolumeSourceApplyConfiguration) WithVolume(value string) *QuobyteVolumeSourceApplyConfiguration {\n\tb.Volume = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100022153,"name":"WithReadOnly","signature":"func (b *QuobyteVolumeSourceApplyConfiguration) WithReadOnly(value bool) *QuobyteVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/quobytevolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *QuobyteVolumeSourceApplyConfiguration) WithReadOnly(value bool) *QuobyteVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":54,"to":60}} {"id":100022154,"name":"WithUser","signature":"func (b *QuobyteVolumeSourceApplyConfiguration) WithUser(value string) *QuobyteVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/quobytevolumesource.go","code":"// WithUser sets the User field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the User field is set to the value of the last call.\nfunc (b *QuobyteVolumeSourceApplyConfiguration) WithUser(value string) *QuobyteVolumeSourceApplyConfiguration {\n\tb.User = \u0026value\n\treturn b\n}","line":{"from":62,"to":68}} {"id":100022155,"name":"WithGroup","signature":"func (b *QuobyteVolumeSourceApplyConfiguration) WithGroup(value string) *QuobyteVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/quobytevolumesource.go","code":"// WithGroup sets the Group field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Group field is set to the value of the last call.\nfunc (b *QuobyteVolumeSourceApplyConfiguration) WithGroup(value string) *QuobyteVolumeSourceApplyConfiguration {\n\tb.Group = \u0026value\n\treturn b\n}","line":{"from":70,"to":76}} {"id":100022156,"name":"WithTenant","signature":"func (b *QuobyteVolumeSourceApplyConfiguration) WithTenant(value string) *QuobyteVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/quobytevolumesource.go","code":"// WithTenant sets the Tenant field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Tenant field is set to the value of the last call.\nfunc (b *QuobyteVolumeSourceApplyConfiguration) WithTenant(value string) *QuobyteVolumeSourceApplyConfiguration {\n\tb.Tenant = \u0026value\n\treturn b\n}","line":{"from":78,"to":84}} {"id":100022157,"name":"RBDPersistentVolumeSource","signature":"func RBDPersistentVolumeSource() *RBDPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/rbdpersistentvolumesource.go","code":"// RBDPersistentVolumeSourceApplyConfiguration constructs an declarative configuration of the RBDPersistentVolumeSource type for use with\n// apply.\nfunc RBDPersistentVolumeSource() *RBDPersistentVolumeSourceApplyConfiguration {\n\treturn \u0026RBDPersistentVolumeSourceApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100022158,"name":"WithCephMonitors","signature":"func (b *RBDPersistentVolumeSourceApplyConfiguration) WithCephMonitors(values ...string) *RBDPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/rbdpersistentvolumesource.go","code":"// WithCephMonitors adds the given value to the CephMonitors field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the CephMonitors field.\nfunc (b *RBDPersistentVolumeSourceApplyConfiguration) WithCephMonitors(values ...string) *RBDPersistentVolumeSourceApplyConfiguration {\n\tfor i := range values {\n\t\tb.CephMonitors = append(b.CephMonitors, values[i])\n\t}\n\treturn b\n}","line":{"from":40,"to":48}} {"id":100022159,"name":"WithRBDImage","signature":"func (b *RBDPersistentVolumeSourceApplyConfiguration) WithRBDImage(value string) *RBDPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/rbdpersistentvolumesource.go","code":"// WithRBDImage sets the RBDImage field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RBDImage field is set to the value of the last call.\nfunc (b *RBDPersistentVolumeSourceApplyConfiguration) WithRBDImage(value string) *RBDPersistentVolumeSourceApplyConfiguration {\n\tb.RBDImage = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100022160,"name":"WithFSType","signature":"func (b *RBDPersistentVolumeSourceApplyConfiguration) WithFSType(value string) *RBDPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/rbdpersistentvolumesource.go","code":"// WithFSType sets the FSType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSType field is set to the value of the last call.\nfunc (b *RBDPersistentVolumeSourceApplyConfiguration) WithFSType(value string) *RBDPersistentVolumeSourceApplyConfiguration {\n\tb.FSType = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100022161,"name":"WithRBDPool","signature":"func (b *RBDPersistentVolumeSourceApplyConfiguration) WithRBDPool(value string) *RBDPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/rbdpersistentvolumesource.go","code":"// WithRBDPool sets the RBDPool field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RBDPool field is set to the value of the last call.\nfunc (b *RBDPersistentVolumeSourceApplyConfiguration) WithRBDPool(value string) *RBDPersistentVolumeSourceApplyConfiguration {\n\tb.RBDPool = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100022162,"name":"WithRadosUser","signature":"func (b *RBDPersistentVolumeSourceApplyConfiguration) WithRadosUser(value string) *RBDPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/rbdpersistentvolumesource.go","code":"// WithRadosUser sets the RadosUser field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RadosUser field is set to the value of the last call.\nfunc (b *RBDPersistentVolumeSourceApplyConfiguration) WithRadosUser(value string) *RBDPersistentVolumeSourceApplyConfiguration {\n\tb.RadosUser = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100022163,"name":"WithKeyring","signature":"func (b *RBDPersistentVolumeSourceApplyConfiguration) WithKeyring(value string) *RBDPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/rbdpersistentvolumesource.go","code":"// WithKeyring sets the Keyring field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Keyring field is set to the value of the last call.\nfunc (b *RBDPersistentVolumeSourceApplyConfiguration) WithKeyring(value string) *RBDPersistentVolumeSourceApplyConfiguration {\n\tb.Keyring = \u0026value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100022164,"name":"WithSecretRef","signature":"func (b *RBDPersistentVolumeSourceApplyConfiguration) WithSecretRef(value *SecretReferenceApplyConfiguration) *RBDPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/rbdpersistentvolumesource.go","code":"// WithSecretRef sets the SecretRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecretRef field is set to the value of the last call.\nfunc (b *RBDPersistentVolumeSourceApplyConfiguration) WithSecretRef(value *SecretReferenceApplyConfiguration) *RBDPersistentVolumeSourceApplyConfiguration {\n\tb.SecretRef = value\n\treturn b\n}","line":{"from":90,"to":96}} {"id":100022165,"name":"WithReadOnly","signature":"func (b *RBDPersistentVolumeSourceApplyConfiguration) WithReadOnly(value bool) *RBDPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/rbdpersistentvolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *RBDPersistentVolumeSourceApplyConfiguration) WithReadOnly(value bool) *RBDPersistentVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":98,"to":104}} {"id":100022166,"name":"RBDVolumeSource","signature":"func RBDVolumeSource() *RBDVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/rbdvolumesource.go","code":"// RBDVolumeSourceApplyConfiguration constructs an declarative configuration of the RBDVolumeSource type for use with\n// apply.\nfunc RBDVolumeSource() *RBDVolumeSourceApplyConfiguration {\n\treturn \u0026RBDVolumeSourceApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100022167,"name":"WithCephMonitors","signature":"func (b *RBDVolumeSourceApplyConfiguration) WithCephMonitors(values ...string) *RBDVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/rbdvolumesource.go","code":"// WithCephMonitors adds the given value to the CephMonitors field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the CephMonitors field.\nfunc (b *RBDVolumeSourceApplyConfiguration) WithCephMonitors(values ...string) *RBDVolumeSourceApplyConfiguration {\n\tfor i := range values {\n\t\tb.CephMonitors = append(b.CephMonitors, values[i])\n\t}\n\treturn b\n}","line":{"from":40,"to":48}} {"id":100022168,"name":"WithRBDImage","signature":"func (b *RBDVolumeSourceApplyConfiguration) WithRBDImage(value string) *RBDVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/rbdvolumesource.go","code":"// WithRBDImage sets the RBDImage field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RBDImage field is set to the value of the last call.\nfunc (b *RBDVolumeSourceApplyConfiguration) WithRBDImage(value string) *RBDVolumeSourceApplyConfiguration {\n\tb.RBDImage = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100022169,"name":"WithFSType","signature":"func (b *RBDVolumeSourceApplyConfiguration) WithFSType(value string) *RBDVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/rbdvolumesource.go","code":"// WithFSType sets the FSType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSType field is set to the value of the last call.\nfunc (b *RBDVolumeSourceApplyConfiguration) WithFSType(value string) *RBDVolumeSourceApplyConfiguration {\n\tb.FSType = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100022170,"name":"WithRBDPool","signature":"func (b *RBDVolumeSourceApplyConfiguration) WithRBDPool(value string) *RBDVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/rbdvolumesource.go","code":"// WithRBDPool sets the RBDPool field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RBDPool field is set to the value of the last call.\nfunc (b *RBDVolumeSourceApplyConfiguration) WithRBDPool(value string) *RBDVolumeSourceApplyConfiguration {\n\tb.RBDPool = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100022171,"name":"WithRadosUser","signature":"func (b *RBDVolumeSourceApplyConfiguration) WithRadosUser(value string) *RBDVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/rbdvolumesource.go","code":"// WithRadosUser sets the RadosUser field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RadosUser field is set to the value of the last call.\nfunc (b *RBDVolumeSourceApplyConfiguration) WithRadosUser(value string) *RBDVolumeSourceApplyConfiguration {\n\tb.RadosUser = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100022172,"name":"WithKeyring","signature":"func (b *RBDVolumeSourceApplyConfiguration) WithKeyring(value string) *RBDVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/rbdvolumesource.go","code":"// WithKeyring sets the Keyring field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Keyring field is set to the value of the last call.\nfunc (b *RBDVolumeSourceApplyConfiguration) WithKeyring(value string) *RBDVolumeSourceApplyConfiguration {\n\tb.Keyring = \u0026value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100022173,"name":"WithSecretRef","signature":"func (b *RBDVolumeSourceApplyConfiguration) WithSecretRef(value *LocalObjectReferenceApplyConfiguration) *RBDVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/rbdvolumesource.go","code":"// WithSecretRef sets the SecretRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecretRef field is set to the value of the last call.\nfunc (b *RBDVolumeSourceApplyConfiguration) WithSecretRef(value *LocalObjectReferenceApplyConfiguration) *RBDVolumeSourceApplyConfiguration {\n\tb.SecretRef = value\n\treturn b\n}","line":{"from":90,"to":96}} {"id":100022174,"name":"WithReadOnly","signature":"func (b *RBDVolumeSourceApplyConfiguration) WithReadOnly(value bool) *RBDVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/rbdvolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *RBDVolumeSourceApplyConfiguration) WithReadOnly(value bool) *RBDVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":98,"to":104}} {"id":100022175,"name":"ReplicationController","signature":"func ReplicationController(name, namespace string) *ReplicationControllerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontroller.go","code":"// ReplicationController constructs an declarative configuration of the ReplicationController type for use with\n// apply.\nfunc ReplicationController(name, namespace string) *ReplicationControllerApplyConfiguration {\n\tb := \u0026ReplicationControllerApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"ReplicationController\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100022176,"name":"ExtractReplicationController","signature":"func ExtractReplicationController(replicationController *apicorev1.ReplicationController, fieldManager string) (*ReplicationControllerApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontroller.go","code":"// ExtractReplicationController extracts the applied configuration owned by fieldManager from\n// replicationController. If no managedFields are found in replicationController for fieldManager, a\n// ReplicationControllerApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// replicationController must be a unmodified ReplicationController API object that was retrieved from the Kubernetes API.\n// ExtractReplicationController provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractReplicationController(replicationController *apicorev1.ReplicationController, fieldManager string) (*ReplicationControllerApplyConfiguration, error) {\n\treturn extractReplicationController(replicationController, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100022177,"name":"ExtractReplicationControllerStatus","signature":"func ExtractReplicationControllerStatus(replicationController *apicorev1.ReplicationController, fieldManager string) (*ReplicationControllerApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontroller.go","code":"// ExtractReplicationControllerStatus is the same as ExtractReplicationController except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractReplicationControllerStatus(replicationController *apicorev1.ReplicationController, fieldManager string) (*ReplicationControllerApplyConfiguration, error) {\n\treturn extractReplicationController(replicationController, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100022178,"name":"extractReplicationController","signature":"func extractReplicationController(replicationController *apicorev1.ReplicationController, fieldManager string, subresource string) (*ReplicationControllerApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontroller.go","code":"func extractReplicationController(replicationController *apicorev1.ReplicationController, fieldManager string, subresource string) (*ReplicationControllerApplyConfiguration, error) {\n\tb := \u0026ReplicationControllerApplyConfiguration{}\n\terr := managedfields.ExtractInto(replicationController, internal.Parser().Type(\"io.k8s.api.core.v1.ReplicationController\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(replicationController.Name)\n\tb.WithNamespace(replicationController.Namespace)\n\n\tb.WithKind(\"ReplicationController\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100022179,"name":"WithKind","signature":"func (b *ReplicationControllerApplyConfiguration) WithKind(value string) *ReplicationControllerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontroller.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ReplicationControllerApplyConfiguration) WithKind(value string) *ReplicationControllerApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100022180,"name":"WithAPIVersion","signature":"func (b *ReplicationControllerApplyConfiguration) WithAPIVersion(value string) *ReplicationControllerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontroller.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ReplicationControllerApplyConfiguration) WithAPIVersion(value string) *ReplicationControllerApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100022181,"name":"WithName","signature":"func (b *ReplicationControllerApplyConfiguration) WithName(value string) *ReplicationControllerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontroller.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ReplicationControllerApplyConfiguration) WithName(value string) *ReplicationControllerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100022182,"name":"WithGenerateName","signature":"func (b *ReplicationControllerApplyConfiguration) WithGenerateName(value string) *ReplicationControllerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontroller.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ReplicationControllerApplyConfiguration) WithGenerateName(value string) *ReplicationControllerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100022183,"name":"WithNamespace","signature":"func (b *ReplicationControllerApplyConfiguration) WithNamespace(value string) *ReplicationControllerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontroller.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ReplicationControllerApplyConfiguration) WithNamespace(value string) *ReplicationControllerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100022184,"name":"WithUID","signature":"func (b *ReplicationControllerApplyConfiguration) WithUID(value types.UID) *ReplicationControllerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontroller.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ReplicationControllerApplyConfiguration) WithUID(value types.UID) *ReplicationControllerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100022185,"name":"WithResourceVersion","signature":"func (b *ReplicationControllerApplyConfiguration) WithResourceVersion(value string) *ReplicationControllerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontroller.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ReplicationControllerApplyConfiguration) WithResourceVersion(value string) *ReplicationControllerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100022186,"name":"WithGeneration","signature":"func (b *ReplicationControllerApplyConfiguration) WithGeneration(value int64) *ReplicationControllerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontroller.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ReplicationControllerApplyConfiguration) WithGeneration(value int64) *ReplicationControllerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100022187,"name":"WithCreationTimestamp","signature":"func (b *ReplicationControllerApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ReplicationControllerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontroller.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ReplicationControllerApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ReplicationControllerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100022188,"name":"WithDeletionTimestamp","signature":"func (b *ReplicationControllerApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ReplicationControllerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontroller.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ReplicationControllerApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ReplicationControllerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100022189,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ReplicationControllerApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ReplicationControllerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontroller.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ReplicationControllerApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ReplicationControllerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100022190,"name":"WithLabels","signature":"func (b *ReplicationControllerApplyConfiguration) WithLabels(entries map[string]string) *ReplicationControllerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontroller.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ReplicationControllerApplyConfiguration) WithLabels(entries map[string]string) *ReplicationControllerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100022191,"name":"WithAnnotations","signature":"func (b *ReplicationControllerApplyConfiguration) WithAnnotations(entries map[string]string) *ReplicationControllerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontroller.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ReplicationControllerApplyConfiguration) WithAnnotations(entries map[string]string) *ReplicationControllerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100022192,"name":"WithOwnerReferences","signature":"func (b *ReplicationControllerApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ReplicationControllerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontroller.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ReplicationControllerApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ReplicationControllerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100022193,"name":"WithFinalizers","signature":"func (b *ReplicationControllerApplyConfiguration) WithFinalizers(values ...string) *ReplicationControllerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontroller.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ReplicationControllerApplyConfiguration) WithFinalizers(values ...string) *ReplicationControllerApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100022194,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ReplicationControllerApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontroller.go","code":"func (b *ReplicationControllerApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100022195,"name":"WithSpec","signature":"func (b *ReplicationControllerApplyConfiguration) WithSpec(value *ReplicationControllerSpecApplyConfiguration) *ReplicationControllerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontroller.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *ReplicationControllerApplyConfiguration) WithSpec(value *ReplicationControllerSpecApplyConfiguration) *ReplicationControllerApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100022196,"name":"WithStatus","signature":"func (b *ReplicationControllerApplyConfiguration) WithStatus(value *ReplicationControllerStatusApplyConfiguration) *ReplicationControllerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontroller.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *ReplicationControllerApplyConfiguration) WithStatus(value *ReplicationControllerStatusApplyConfiguration) *ReplicationControllerApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100022197,"name":"ReplicationControllerCondition","signature":"func ReplicationControllerCondition() *ReplicationControllerConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontrollercondition.go","code":"// ReplicationControllerConditionApplyConfiguration constructs an declarative configuration of the ReplicationControllerCondition type for use with\n// apply.\nfunc ReplicationControllerCondition() *ReplicationControllerConditionApplyConfiguration {\n\treturn \u0026ReplicationControllerConditionApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100022198,"name":"WithType","signature":"func (b *ReplicationControllerConditionApplyConfiguration) WithType(value v1.ReplicationControllerConditionType) *ReplicationControllerConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontrollercondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *ReplicationControllerConditionApplyConfiguration) WithType(value v1.ReplicationControllerConditionType) *ReplicationControllerConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100022199,"name":"WithStatus","signature":"func (b *ReplicationControllerConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *ReplicationControllerConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontrollercondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *ReplicationControllerConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *ReplicationControllerConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100022200,"name":"WithLastTransitionTime","signature":"func (b *ReplicationControllerConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *ReplicationControllerConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontrollercondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *ReplicationControllerConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *ReplicationControllerConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100022201,"name":"WithReason","signature":"func (b *ReplicationControllerConditionApplyConfiguration) WithReason(value string) *ReplicationControllerConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontrollercondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *ReplicationControllerConditionApplyConfiguration) WithReason(value string) *ReplicationControllerConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100022202,"name":"WithMessage","signature":"func (b *ReplicationControllerConditionApplyConfiguration) WithMessage(value string) *ReplicationControllerConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontrollercondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *ReplicationControllerConditionApplyConfiguration) WithMessage(value string) *ReplicationControllerConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100022203,"name":"ReplicationControllerSpec","signature":"func ReplicationControllerSpec() *ReplicationControllerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontrollerspec.go","code":"// ReplicationControllerSpecApplyConfiguration constructs an declarative configuration of the ReplicationControllerSpec type for use with\n// apply.\nfunc ReplicationControllerSpec() *ReplicationControllerSpecApplyConfiguration {\n\treturn \u0026ReplicationControllerSpecApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100022204,"name":"WithReplicas","signature":"func (b *ReplicationControllerSpecApplyConfiguration) WithReplicas(value int32) *ReplicationControllerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontrollerspec.go","code":"// WithReplicas sets the Replicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Replicas field is set to the value of the last call.\nfunc (b *ReplicationControllerSpecApplyConfiguration) WithReplicas(value int32) *ReplicationControllerSpecApplyConfiguration {\n\tb.Replicas = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100022205,"name":"WithMinReadySeconds","signature":"func (b *ReplicationControllerSpecApplyConfiguration) WithMinReadySeconds(value int32) *ReplicationControllerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontrollerspec.go","code":"// WithMinReadySeconds sets the MinReadySeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MinReadySeconds field is set to the value of the last call.\nfunc (b *ReplicationControllerSpecApplyConfiguration) WithMinReadySeconds(value int32) *ReplicationControllerSpecApplyConfiguration {\n\tb.MinReadySeconds = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100022206,"name":"WithSelector","signature":"func (b *ReplicationControllerSpecApplyConfiguration) WithSelector(entries map[string]string) *ReplicationControllerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontrollerspec.go","code":"// WithSelector puts the entries into the Selector field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Selector field,\n// overwriting an existing map entries in Selector field with the same key.\nfunc (b *ReplicationControllerSpecApplyConfiguration) WithSelector(entries map[string]string) *ReplicationControllerSpecApplyConfiguration {\n\tif b.Selector == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Selector = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Selector[k] = v\n\t}\n\treturn b\n}","line":{"from":52,"to":64}} {"id":100022207,"name":"WithTemplate","signature":"func (b *ReplicationControllerSpecApplyConfiguration) WithTemplate(value *PodTemplateSpecApplyConfiguration) *ReplicationControllerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontrollerspec.go","code":"// WithTemplate sets the Template field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Template field is set to the value of the last call.\nfunc (b *ReplicationControllerSpecApplyConfiguration) WithTemplate(value *PodTemplateSpecApplyConfiguration) *ReplicationControllerSpecApplyConfiguration {\n\tb.Template = value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100022208,"name":"ReplicationControllerStatus","signature":"func ReplicationControllerStatus() *ReplicationControllerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontrollerstatus.go","code":"// ReplicationControllerStatusApplyConfiguration constructs an declarative configuration of the ReplicationControllerStatus type for use with\n// apply.\nfunc ReplicationControllerStatus() *ReplicationControllerStatusApplyConfiguration {\n\treturn \u0026ReplicationControllerStatusApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100022209,"name":"WithReplicas","signature":"func (b *ReplicationControllerStatusApplyConfiguration) WithReplicas(value int32) *ReplicationControllerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontrollerstatus.go","code":"// WithReplicas sets the Replicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Replicas field is set to the value of the last call.\nfunc (b *ReplicationControllerStatusApplyConfiguration) WithReplicas(value int32) *ReplicationControllerStatusApplyConfiguration {\n\tb.Replicas = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100022210,"name":"WithFullyLabeledReplicas","signature":"func (b *ReplicationControllerStatusApplyConfiguration) WithFullyLabeledReplicas(value int32) *ReplicationControllerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontrollerstatus.go","code":"// WithFullyLabeledReplicas sets the FullyLabeledReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FullyLabeledReplicas field is set to the value of the last call.\nfunc (b *ReplicationControllerStatusApplyConfiguration) WithFullyLabeledReplicas(value int32) *ReplicationControllerStatusApplyConfiguration {\n\tb.FullyLabeledReplicas = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100022211,"name":"WithReadyReplicas","signature":"func (b *ReplicationControllerStatusApplyConfiguration) WithReadyReplicas(value int32) *ReplicationControllerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontrollerstatus.go","code":"// WithReadyReplicas sets the ReadyReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadyReplicas field is set to the value of the last call.\nfunc (b *ReplicationControllerStatusApplyConfiguration) WithReadyReplicas(value int32) *ReplicationControllerStatusApplyConfiguration {\n\tb.ReadyReplicas = \u0026value\n\treturn b\n}","line":{"from":54,"to":60}} {"id":100022212,"name":"WithAvailableReplicas","signature":"func (b *ReplicationControllerStatusApplyConfiguration) WithAvailableReplicas(value int32) *ReplicationControllerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontrollerstatus.go","code":"// WithAvailableReplicas sets the AvailableReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AvailableReplicas field is set to the value of the last call.\nfunc (b *ReplicationControllerStatusApplyConfiguration) WithAvailableReplicas(value int32) *ReplicationControllerStatusApplyConfiguration {\n\tb.AvailableReplicas = \u0026value\n\treturn b\n}","line":{"from":62,"to":68}} {"id":100022213,"name":"WithObservedGeneration","signature":"func (b *ReplicationControllerStatusApplyConfiguration) WithObservedGeneration(value int64) *ReplicationControllerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontrollerstatus.go","code":"// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObservedGeneration field is set to the value of the last call.\nfunc (b *ReplicationControllerStatusApplyConfiguration) WithObservedGeneration(value int64) *ReplicationControllerStatusApplyConfiguration {\n\tb.ObservedGeneration = \u0026value\n\treturn b\n}","line":{"from":70,"to":76}} {"id":100022214,"name":"WithConditions","signature":"func (b *ReplicationControllerStatusApplyConfiguration) WithConditions(values ...*ReplicationControllerConditionApplyConfiguration) *ReplicationControllerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/replicationcontrollerstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *ReplicationControllerStatusApplyConfiguration) WithConditions(values ...*ReplicationControllerConditionApplyConfiguration) *ReplicationControllerStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":78,"to":89}} {"id":100022215,"name":"ResourceClaim","signature":"func ResourceClaim() *ResourceClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourceclaim.go","code":"// ResourceClaimApplyConfiguration constructs an declarative configuration of the ResourceClaim type for use with\n// apply.\nfunc ResourceClaim() *ResourceClaimApplyConfiguration {\n\treturn \u0026ResourceClaimApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100022216,"name":"WithName","signature":"func (b *ResourceClaimApplyConfiguration) WithName(value string) *ResourceClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourceclaim.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ResourceClaimApplyConfiguration) WithName(value string) *ResourceClaimApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100022217,"name":"ResourceFieldSelector","signature":"func ResourceFieldSelector() *ResourceFieldSelectorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcefieldselector.go","code":"// ResourceFieldSelectorApplyConfiguration constructs an declarative configuration of the ResourceFieldSelector type for use with\n// apply.\nfunc ResourceFieldSelector() *ResourceFieldSelectorApplyConfiguration {\n\treturn \u0026ResourceFieldSelectorApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100022218,"name":"WithContainerName","signature":"func (b *ResourceFieldSelectorApplyConfiguration) WithContainerName(value string) *ResourceFieldSelectorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcefieldselector.go","code":"// WithContainerName sets the ContainerName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ContainerName field is set to the value of the last call.\nfunc (b *ResourceFieldSelectorApplyConfiguration) WithContainerName(value string) *ResourceFieldSelectorApplyConfiguration {\n\tb.ContainerName = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100022219,"name":"WithResource","signature":"func (b *ResourceFieldSelectorApplyConfiguration) WithResource(value string) *ResourceFieldSelectorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcefieldselector.go","code":"// WithResource sets the Resource field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Resource field is set to the value of the last call.\nfunc (b *ResourceFieldSelectorApplyConfiguration) WithResource(value string) *ResourceFieldSelectorApplyConfiguration {\n\tb.Resource = \u0026value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100022220,"name":"WithDivisor","signature":"func (b *ResourceFieldSelectorApplyConfiguration) WithDivisor(value resource.Quantity) *ResourceFieldSelectorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcefieldselector.go","code":"// WithDivisor sets the Divisor field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Divisor field is set to the value of the last call.\nfunc (b *ResourceFieldSelectorApplyConfiguration) WithDivisor(value resource.Quantity) *ResourceFieldSelectorApplyConfiguration {\n\tb.Divisor = \u0026value\n\treturn b\n}","line":{"from":55,"to":61}} {"id":100022221,"name":"ResourceQuota","signature":"func ResourceQuota(name, namespace string) *ResourceQuotaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequota.go","code":"// ResourceQuota constructs an declarative configuration of the ResourceQuota type for use with\n// apply.\nfunc ResourceQuota(name, namespace string) *ResourceQuotaApplyConfiguration {\n\tb := \u0026ResourceQuotaApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"ResourceQuota\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100022222,"name":"ExtractResourceQuota","signature":"func ExtractResourceQuota(resourceQuota *apicorev1.ResourceQuota, fieldManager string) (*ResourceQuotaApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequota.go","code":"// ExtractResourceQuota extracts the applied configuration owned by fieldManager from\n// resourceQuota. If no managedFields are found in resourceQuota for fieldManager, a\n// ResourceQuotaApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// resourceQuota must be a unmodified ResourceQuota API object that was retrieved from the Kubernetes API.\n// ExtractResourceQuota provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractResourceQuota(resourceQuota *apicorev1.ResourceQuota, fieldManager string) (*ResourceQuotaApplyConfiguration, error) {\n\treturn extractResourceQuota(resourceQuota, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100022223,"name":"ExtractResourceQuotaStatus","signature":"func ExtractResourceQuotaStatus(resourceQuota *apicorev1.ResourceQuota, fieldManager string) (*ResourceQuotaApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequota.go","code":"// ExtractResourceQuotaStatus is the same as ExtractResourceQuota except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractResourceQuotaStatus(resourceQuota *apicorev1.ResourceQuota, fieldManager string) (*ResourceQuotaApplyConfiguration, error) {\n\treturn extractResourceQuota(resourceQuota, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100022224,"name":"extractResourceQuota","signature":"func extractResourceQuota(resourceQuota *apicorev1.ResourceQuota, fieldManager string, subresource string) (*ResourceQuotaApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequota.go","code":"func extractResourceQuota(resourceQuota *apicorev1.ResourceQuota, fieldManager string, subresource string) (*ResourceQuotaApplyConfiguration, error) {\n\tb := \u0026ResourceQuotaApplyConfiguration{}\n\terr := managedfields.ExtractInto(resourceQuota, internal.Parser().Type(\"io.k8s.api.core.v1.ResourceQuota\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(resourceQuota.Name)\n\tb.WithNamespace(resourceQuota.Namespace)\n\n\tb.WithKind(\"ResourceQuota\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100022225,"name":"WithKind","signature":"func (b *ResourceQuotaApplyConfiguration) WithKind(value string) *ResourceQuotaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequota.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ResourceQuotaApplyConfiguration) WithKind(value string) *ResourceQuotaApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100022226,"name":"WithAPIVersion","signature":"func (b *ResourceQuotaApplyConfiguration) WithAPIVersion(value string) *ResourceQuotaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequota.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ResourceQuotaApplyConfiguration) WithAPIVersion(value string) *ResourceQuotaApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100022227,"name":"WithName","signature":"func (b *ResourceQuotaApplyConfiguration) WithName(value string) *ResourceQuotaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequota.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ResourceQuotaApplyConfiguration) WithName(value string) *ResourceQuotaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100022228,"name":"WithGenerateName","signature":"func (b *ResourceQuotaApplyConfiguration) WithGenerateName(value string) *ResourceQuotaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequota.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ResourceQuotaApplyConfiguration) WithGenerateName(value string) *ResourceQuotaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100022229,"name":"WithNamespace","signature":"func (b *ResourceQuotaApplyConfiguration) WithNamespace(value string) *ResourceQuotaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequota.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ResourceQuotaApplyConfiguration) WithNamespace(value string) *ResourceQuotaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100022230,"name":"WithUID","signature":"func (b *ResourceQuotaApplyConfiguration) WithUID(value types.UID) *ResourceQuotaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequota.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ResourceQuotaApplyConfiguration) WithUID(value types.UID) *ResourceQuotaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100022231,"name":"WithResourceVersion","signature":"func (b *ResourceQuotaApplyConfiguration) WithResourceVersion(value string) *ResourceQuotaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequota.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ResourceQuotaApplyConfiguration) WithResourceVersion(value string) *ResourceQuotaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100022232,"name":"WithGeneration","signature":"func (b *ResourceQuotaApplyConfiguration) WithGeneration(value int64) *ResourceQuotaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequota.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ResourceQuotaApplyConfiguration) WithGeneration(value int64) *ResourceQuotaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100022233,"name":"WithCreationTimestamp","signature":"func (b *ResourceQuotaApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ResourceQuotaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequota.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ResourceQuotaApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ResourceQuotaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100022234,"name":"WithDeletionTimestamp","signature":"func (b *ResourceQuotaApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ResourceQuotaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequota.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ResourceQuotaApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ResourceQuotaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100022235,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ResourceQuotaApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ResourceQuotaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequota.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ResourceQuotaApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ResourceQuotaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100022236,"name":"WithLabels","signature":"func (b *ResourceQuotaApplyConfiguration) WithLabels(entries map[string]string) *ResourceQuotaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequota.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ResourceQuotaApplyConfiguration) WithLabels(entries map[string]string) *ResourceQuotaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100022237,"name":"WithAnnotations","signature":"func (b *ResourceQuotaApplyConfiguration) WithAnnotations(entries map[string]string) *ResourceQuotaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequota.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ResourceQuotaApplyConfiguration) WithAnnotations(entries map[string]string) *ResourceQuotaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100022238,"name":"WithOwnerReferences","signature":"func (b *ResourceQuotaApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ResourceQuotaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequota.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ResourceQuotaApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ResourceQuotaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100022239,"name":"WithFinalizers","signature":"func (b *ResourceQuotaApplyConfiguration) WithFinalizers(values ...string) *ResourceQuotaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequota.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ResourceQuotaApplyConfiguration) WithFinalizers(values ...string) *ResourceQuotaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100022240,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ResourceQuotaApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequota.go","code":"func (b *ResourceQuotaApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100022241,"name":"WithSpec","signature":"func (b *ResourceQuotaApplyConfiguration) WithSpec(value *ResourceQuotaSpecApplyConfiguration) *ResourceQuotaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequota.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *ResourceQuotaApplyConfiguration) WithSpec(value *ResourceQuotaSpecApplyConfiguration) *ResourceQuotaApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100022242,"name":"WithStatus","signature":"func (b *ResourceQuotaApplyConfiguration) WithStatus(value *ResourceQuotaStatusApplyConfiguration) *ResourceQuotaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequota.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *ResourceQuotaApplyConfiguration) WithStatus(value *ResourceQuotaStatusApplyConfiguration) *ResourceQuotaApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100022243,"name":"ResourceQuotaSpec","signature":"func ResourceQuotaSpec() *ResourceQuotaSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequotaspec.go","code":"// ResourceQuotaSpecApplyConfiguration constructs an declarative configuration of the ResourceQuotaSpec type for use with\n// apply.\nfunc ResourceQuotaSpec() *ResourceQuotaSpecApplyConfiguration {\n\treturn \u0026ResourceQuotaSpecApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100022244,"name":"WithHard","signature":"func (b *ResourceQuotaSpecApplyConfiguration) WithHard(value v1.ResourceList) *ResourceQuotaSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequotaspec.go","code":"// WithHard sets the Hard field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Hard field is set to the value of the last call.\nfunc (b *ResourceQuotaSpecApplyConfiguration) WithHard(value v1.ResourceList) *ResourceQuotaSpecApplyConfiguration {\n\tb.Hard = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100022245,"name":"WithScopes","signature":"func (b *ResourceQuotaSpecApplyConfiguration) WithScopes(values ...v1.ResourceQuotaScope) *ResourceQuotaSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequotaspec.go","code":"// WithScopes adds the given value to the Scopes field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Scopes field.\nfunc (b *ResourceQuotaSpecApplyConfiguration) WithScopes(values ...v1.ResourceQuotaScope) *ResourceQuotaSpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.Scopes = append(b.Scopes, values[i])\n\t}\n\treturn b\n}","line":{"from":47,"to":55}} {"id":100022246,"name":"WithScopeSelector","signature":"func (b *ResourceQuotaSpecApplyConfiguration) WithScopeSelector(value *ScopeSelectorApplyConfiguration) *ResourceQuotaSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequotaspec.go","code":"// WithScopeSelector sets the ScopeSelector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ScopeSelector field is set to the value of the last call.\nfunc (b *ResourceQuotaSpecApplyConfiguration) WithScopeSelector(value *ScopeSelectorApplyConfiguration) *ResourceQuotaSpecApplyConfiguration {\n\tb.ScopeSelector = value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100022247,"name":"ResourceQuotaStatus","signature":"func ResourceQuotaStatus() *ResourceQuotaStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequotastatus.go","code":"// ResourceQuotaStatusApplyConfiguration constructs an declarative configuration of the ResourceQuotaStatus type for use with\n// apply.\nfunc ResourceQuotaStatus() *ResourceQuotaStatusApplyConfiguration {\n\treturn \u0026ResourceQuotaStatusApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100022248,"name":"WithHard","signature":"func (b *ResourceQuotaStatusApplyConfiguration) WithHard(value v1.ResourceList) *ResourceQuotaStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequotastatus.go","code":"// WithHard sets the Hard field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Hard field is set to the value of the last call.\nfunc (b *ResourceQuotaStatusApplyConfiguration) WithHard(value v1.ResourceList) *ResourceQuotaStatusApplyConfiguration {\n\tb.Hard = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100022249,"name":"WithUsed","signature":"func (b *ResourceQuotaStatusApplyConfiguration) WithUsed(value v1.ResourceList) *ResourceQuotaStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcequotastatus.go","code":"// WithUsed sets the Used field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Used field is set to the value of the last call.\nfunc (b *ResourceQuotaStatusApplyConfiguration) WithUsed(value v1.ResourceList) *ResourceQuotaStatusApplyConfiguration {\n\tb.Used = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100022250,"name":"ResourceRequirements","signature":"func ResourceRequirements() *ResourceRequirementsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcerequirements.go","code":"// ResourceRequirementsApplyConfiguration constructs an declarative configuration of the ResourceRequirements type for use with\n// apply.\nfunc ResourceRequirements() *ResourceRequirementsApplyConfiguration {\n\treturn \u0026ResourceRequirementsApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100022251,"name":"WithLimits","signature":"func (b *ResourceRequirementsApplyConfiguration) WithLimits(value v1.ResourceList) *ResourceRequirementsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcerequirements.go","code":"// WithLimits sets the Limits field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Limits field is set to the value of the last call.\nfunc (b *ResourceRequirementsApplyConfiguration) WithLimits(value v1.ResourceList) *ResourceRequirementsApplyConfiguration {\n\tb.Limits = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100022252,"name":"WithRequests","signature":"func (b *ResourceRequirementsApplyConfiguration) WithRequests(value v1.ResourceList) *ResourceRequirementsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcerequirements.go","code":"// WithRequests sets the Requests field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Requests field is set to the value of the last call.\nfunc (b *ResourceRequirementsApplyConfiguration) WithRequests(value v1.ResourceList) *ResourceRequirementsApplyConfiguration {\n\tb.Requests = \u0026value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100022253,"name":"WithClaims","signature":"func (b *ResourceRequirementsApplyConfiguration) WithClaims(values ...*ResourceClaimApplyConfiguration) *ResourceRequirementsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/resourcerequirements.go","code":"// WithClaims adds the given value to the Claims field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Claims field.\nfunc (b *ResourceRequirementsApplyConfiguration) WithClaims(values ...*ResourceClaimApplyConfiguration) *ResourceRequirementsApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithClaims\")\n\t\t}\n\t\tb.Claims = append(b.Claims, *values[i])\n\t}\n\treturn b\n}","line":{"from":55,"to":66}} {"id":100022254,"name":"ScaleIOPersistentVolumeSource","signature":"func ScaleIOPersistentVolumeSource() *ScaleIOPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scaleiopersistentvolumesource.go","code":"// ScaleIOPersistentVolumeSourceApplyConfiguration constructs an declarative configuration of the ScaleIOPersistentVolumeSource type for use with\n// apply.\nfunc ScaleIOPersistentVolumeSource() *ScaleIOPersistentVolumeSourceApplyConfiguration {\n\treturn \u0026ScaleIOPersistentVolumeSourceApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100022255,"name":"WithGateway","signature":"func (b *ScaleIOPersistentVolumeSourceApplyConfiguration) WithGateway(value string) *ScaleIOPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scaleiopersistentvolumesource.go","code":"// WithGateway sets the Gateway field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Gateway field is set to the value of the last call.\nfunc (b *ScaleIOPersistentVolumeSourceApplyConfiguration) WithGateway(value string) *ScaleIOPersistentVolumeSourceApplyConfiguration {\n\tb.Gateway = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100022256,"name":"WithSystem","signature":"func (b *ScaleIOPersistentVolumeSourceApplyConfiguration) WithSystem(value string) *ScaleIOPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scaleiopersistentvolumesource.go","code":"// WithSystem sets the System field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the System field is set to the value of the last call.\nfunc (b *ScaleIOPersistentVolumeSourceApplyConfiguration) WithSystem(value string) *ScaleIOPersistentVolumeSourceApplyConfiguration {\n\tb.System = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100022257,"name":"WithSecretRef","signature":"func (b *ScaleIOPersistentVolumeSourceApplyConfiguration) WithSecretRef(value *SecretReferenceApplyConfiguration) *ScaleIOPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scaleiopersistentvolumesource.go","code":"// WithSecretRef sets the SecretRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecretRef field is set to the value of the last call.\nfunc (b *ScaleIOPersistentVolumeSourceApplyConfiguration) WithSecretRef(value *SecretReferenceApplyConfiguration) *ScaleIOPersistentVolumeSourceApplyConfiguration {\n\tb.SecretRef = value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100022258,"name":"WithSSLEnabled","signature":"func (b *ScaleIOPersistentVolumeSourceApplyConfiguration) WithSSLEnabled(value bool) *ScaleIOPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scaleiopersistentvolumesource.go","code":"// WithSSLEnabled sets the SSLEnabled field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SSLEnabled field is set to the value of the last call.\nfunc (b *ScaleIOPersistentVolumeSourceApplyConfiguration) WithSSLEnabled(value bool) *ScaleIOPersistentVolumeSourceApplyConfiguration {\n\tb.SSLEnabled = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100022259,"name":"WithProtectionDomain","signature":"func (b *ScaleIOPersistentVolumeSourceApplyConfiguration) WithProtectionDomain(value string) *ScaleIOPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scaleiopersistentvolumesource.go","code":"// WithProtectionDomain sets the ProtectionDomain field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ProtectionDomain field is set to the value of the last call.\nfunc (b *ScaleIOPersistentVolumeSourceApplyConfiguration) WithProtectionDomain(value string) *ScaleIOPersistentVolumeSourceApplyConfiguration {\n\tb.ProtectionDomain = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100022260,"name":"WithStoragePool","signature":"func (b *ScaleIOPersistentVolumeSourceApplyConfiguration) WithStoragePool(value string) *ScaleIOPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scaleiopersistentvolumesource.go","code":"// WithStoragePool sets the StoragePool field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StoragePool field is set to the value of the last call.\nfunc (b *ScaleIOPersistentVolumeSourceApplyConfiguration) WithStoragePool(value string) *ScaleIOPersistentVolumeSourceApplyConfiguration {\n\tb.StoragePool = \u0026value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100022261,"name":"WithStorageMode","signature":"func (b *ScaleIOPersistentVolumeSourceApplyConfiguration) WithStorageMode(value string) *ScaleIOPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scaleiopersistentvolumesource.go","code":"// WithStorageMode sets the StorageMode field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StorageMode field is set to the value of the last call.\nfunc (b *ScaleIOPersistentVolumeSourceApplyConfiguration) WithStorageMode(value string) *ScaleIOPersistentVolumeSourceApplyConfiguration {\n\tb.StorageMode = \u0026value\n\treturn b\n}","line":{"from":90,"to":96}} {"id":100022262,"name":"WithVolumeName","signature":"func (b *ScaleIOPersistentVolumeSourceApplyConfiguration) WithVolumeName(value string) *ScaleIOPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scaleiopersistentvolumesource.go","code":"// WithVolumeName sets the VolumeName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the VolumeName field is set to the value of the last call.\nfunc (b *ScaleIOPersistentVolumeSourceApplyConfiguration) WithVolumeName(value string) *ScaleIOPersistentVolumeSourceApplyConfiguration {\n\tb.VolumeName = \u0026value\n\treturn b\n}","line":{"from":98,"to":104}} {"id":100022263,"name":"WithFSType","signature":"func (b *ScaleIOPersistentVolumeSourceApplyConfiguration) WithFSType(value string) *ScaleIOPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scaleiopersistentvolumesource.go","code":"// WithFSType sets the FSType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSType field is set to the value of the last call.\nfunc (b *ScaleIOPersistentVolumeSourceApplyConfiguration) WithFSType(value string) *ScaleIOPersistentVolumeSourceApplyConfiguration {\n\tb.FSType = \u0026value\n\treturn b\n}","line":{"from":106,"to":112}} {"id":100022264,"name":"WithReadOnly","signature":"func (b *ScaleIOPersistentVolumeSourceApplyConfiguration) WithReadOnly(value bool) *ScaleIOPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scaleiopersistentvolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *ScaleIOPersistentVolumeSourceApplyConfiguration) WithReadOnly(value bool) *ScaleIOPersistentVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":114,"to":120}} {"id":100022265,"name":"ScaleIOVolumeSource","signature":"func ScaleIOVolumeSource() *ScaleIOVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scaleiovolumesource.go","code":"// ScaleIOVolumeSourceApplyConfiguration constructs an declarative configuration of the ScaleIOVolumeSource type for use with\n// apply.\nfunc ScaleIOVolumeSource() *ScaleIOVolumeSourceApplyConfiguration {\n\treturn \u0026ScaleIOVolumeSourceApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100022266,"name":"WithGateway","signature":"func (b *ScaleIOVolumeSourceApplyConfiguration) WithGateway(value string) *ScaleIOVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scaleiovolumesource.go","code":"// WithGateway sets the Gateway field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Gateway field is set to the value of the last call.\nfunc (b *ScaleIOVolumeSourceApplyConfiguration) WithGateway(value string) *ScaleIOVolumeSourceApplyConfiguration {\n\tb.Gateway = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100022267,"name":"WithSystem","signature":"func (b *ScaleIOVolumeSourceApplyConfiguration) WithSystem(value string) *ScaleIOVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scaleiovolumesource.go","code":"// WithSystem sets the System field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the System field is set to the value of the last call.\nfunc (b *ScaleIOVolumeSourceApplyConfiguration) WithSystem(value string) *ScaleIOVolumeSourceApplyConfiguration {\n\tb.System = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100022268,"name":"WithSecretRef","signature":"func (b *ScaleIOVolumeSourceApplyConfiguration) WithSecretRef(value *LocalObjectReferenceApplyConfiguration) *ScaleIOVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scaleiovolumesource.go","code":"// WithSecretRef sets the SecretRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecretRef field is set to the value of the last call.\nfunc (b *ScaleIOVolumeSourceApplyConfiguration) WithSecretRef(value *LocalObjectReferenceApplyConfiguration) *ScaleIOVolumeSourceApplyConfiguration {\n\tb.SecretRef = value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100022269,"name":"WithSSLEnabled","signature":"func (b *ScaleIOVolumeSourceApplyConfiguration) WithSSLEnabled(value bool) *ScaleIOVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scaleiovolumesource.go","code":"// WithSSLEnabled sets the SSLEnabled field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SSLEnabled field is set to the value of the last call.\nfunc (b *ScaleIOVolumeSourceApplyConfiguration) WithSSLEnabled(value bool) *ScaleIOVolumeSourceApplyConfiguration {\n\tb.SSLEnabled = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100022270,"name":"WithProtectionDomain","signature":"func (b *ScaleIOVolumeSourceApplyConfiguration) WithProtectionDomain(value string) *ScaleIOVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scaleiovolumesource.go","code":"// WithProtectionDomain sets the ProtectionDomain field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ProtectionDomain field is set to the value of the last call.\nfunc (b *ScaleIOVolumeSourceApplyConfiguration) WithProtectionDomain(value string) *ScaleIOVolumeSourceApplyConfiguration {\n\tb.ProtectionDomain = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100022271,"name":"WithStoragePool","signature":"func (b *ScaleIOVolumeSourceApplyConfiguration) WithStoragePool(value string) *ScaleIOVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scaleiovolumesource.go","code":"// WithStoragePool sets the StoragePool field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StoragePool field is set to the value of the last call.\nfunc (b *ScaleIOVolumeSourceApplyConfiguration) WithStoragePool(value string) *ScaleIOVolumeSourceApplyConfiguration {\n\tb.StoragePool = \u0026value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100022272,"name":"WithStorageMode","signature":"func (b *ScaleIOVolumeSourceApplyConfiguration) WithStorageMode(value string) *ScaleIOVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scaleiovolumesource.go","code":"// WithStorageMode sets the StorageMode field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StorageMode field is set to the value of the last call.\nfunc (b *ScaleIOVolumeSourceApplyConfiguration) WithStorageMode(value string) *ScaleIOVolumeSourceApplyConfiguration {\n\tb.StorageMode = \u0026value\n\treturn b\n}","line":{"from":90,"to":96}} {"id":100022273,"name":"WithVolumeName","signature":"func (b *ScaleIOVolumeSourceApplyConfiguration) WithVolumeName(value string) *ScaleIOVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scaleiovolumesource.go","code":"// WithVolumeName sets the VolumeName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the VolumeName field is set to the value of the last call.\nfunc (b *ScaleIOVolumeSourceApplyConfiguration) WithVolumeName(value string) *ScaleIOVolumeSourceApplyConfiguration {\n\tb.VolumeName = \u0026value\n\treturn b\n}","line":{"from":98,"to":104}} {"id":100022274,"name":"WithFSType","signature":"func (b *ScaleIOVolumeSourceApplyConfiguration) WithFSType(value string) *ScaleIOVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scaleiovolumesource.go","code":"// WithFSType sets the FSType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSType field is set to the value of the last call.\nfunc (b *ScaleIOVolumeSourceApplyConfiguration) WithFSType(value string) *ScaleIOVolumeSourceApplyConfiguration {\n\tb.FSType = \u0026value\n\treturn b\n}","line":{"from":106,"to":112}} {"id":100022275,"name":"WithReadOnly","signature":"func (b *ScaleIOVolumeSourceApplyConfiguration) WithReadOnly(value bool) *ScaleIOVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scaleiovolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *ScaleIOVolumeSourceApplyConfiguration) WithReadOnly(value bool) *ScaleIOVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":114,"to":120}} {"id":100022276,"name":"ScopedResourceSelectorRequirement","signature":"func ScopedResourceSelectorRequirement() *ScopedResourceSelectorRequirementApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scopedresourceselectorrequirement.go","code":"// ScopedResourceSelectorRequirementApplyConfiguration constructs an declarative configuration of the ScopedResourceSelectorRequirement type for use with\n// apply.\nfunc ScopedResourceSelectorRequirement() *ScopedResourceSelectorRequirementApplyConfiguration {\n\treturn \u0026ScopedResourceSelectorRequirementApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100022277,"name":"WithScopeName","signature":"func (b *ScopedResourceSelectorRequirementApplyConfiguration) WithScopeName(value v1.ResourceQuotaScope) *ScopedResourceSelectorRequirementApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scopedresourceselectorrequirement.go","code":"// WithScopeName sets the ScopeName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ScopeName field is set to the value of the last call.\nfunc (b *ScopedResourceSelectorRequirementApplyConfiguration) WithScopeName(value v1.ResourceQuotaScope) *ScopedResourceSelectorRequirementApplyConfiguration {\n\tb.ScopeName = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100022278,"name":"WithOperator","signature":"func (b *ScopedResourceSelectorRequirementApplyConfiguration) WithOperator(value v1.ScopeSelectorOperator) *ScopedResourceSelectorRequirementApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scopedresourceselectorrequirement.go","code":"// WithOperator sets the Operator field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Operator field is set to the value of the last call.\nfunc (b *ScopedResourceSelectorRequirementApplyConfiguration) WithOperator(value v1.ScopeSelectorOperator) *ScopedResourceSelectorRequirementApplyConfiguration {\n\tb.Operator = \u0026value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100022279,"name":"WithValues","signature":"func (b *ScopedResourceSelectorRequirementApplyConfiguration) WithValues(values ...string) *ScopedResourceSelectorRequirementApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scopedresourceselectorrequirement.go","code":"// WithValues adds the given value to the Values field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Values field.\nfunc (b *ScopedResourceSelectorRequirementApplyConfiguration) WithValues(values ...string) *ScopedResourceSelectorRequirementApplyConfiguration {\n\tfor i := range values {\n\t\tb.Values = append(b.Values, values[i])\n\t}\n\treturn b\n}","line":{"from":55,"to":63}} {"id":100022280,"name":"ScopeSelector","signature":"func ScopeSelector() *ScopeSelectorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scopeselector.go","code":"// ScopeSelectorApplyConfiguration constructs an declarative configuration of the ScopeSelector type for use with\n// apply.\nfunc ScopeSelector() *ScopeSelectorApplyConfiguration {\n\treturn \u0026ScopeSelectorApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100022281,"name":"WithMatchExpressions","signature":"func (b *ScopeSelectorApplyConfiguration) WithMatchExpressions(values ...*ScopedResourceSelectorRequirementApplyConfiguration) *ScopeSelectorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/scopeselector.go","code":"// WithMatchExpressions adds the given value to the MatchExpressions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the MatchExpressions field.\nfunc (b *ScopeSelectorApplyConfiguration) WithMatchExpressions(values ...*ScopedResourceSelectorRequirementApplyConfiguration) *ScopeSelectorApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithMatchExpressions\")\n\t\t}\n\t\tb.MatchExpressions = append(b.MatchExpressions, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100022282,"name":"SeccompProfile","signature":"func SeccompProfile() *SeccompProfileApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/seccompprofile.go","code":"// SeccompProfileApplyConfiguration constructs an declarative configuration of the SeccompProfile type for use with\n// apply.\nfunc SeccompProfile() *SeccompProfileApplyConfiguration {\n\treturn \u0026SeccompProfileApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100022283,"name":"WithType","signature":"func (b *SeccompProfileApplyConfiguration) WithType(value v1.SeccompProfileType) *SeccompProfileApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/seccompprofile.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *SeccompProfileApplyConfiguration) WithType(value v1.SeccompProfileType) *SeccompProfileApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100022284,"name":"WithLocalhostProfile","signature":"func (b *SeccompProfileApplyConfiguration) WithLocalhostProfile(value string) *SeccompProfileApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/seccompprofile.go","code":"// WithLocalhostProfile sets the LocalhostProfile field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LocalhostProfile field is set to the value of the last call.\nfunc (b *SeccompProfileApplyConfiguration) WithLocalhostProfile(value string) *SeccompProfileApplyConfiguration {\n\tb.LocalhostProfile = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100022285,"name":"Secret","signature":"func Secret(name, namespace string) *SecretApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secret.go","code":"// Secret constructs an declarative configuration of the Secret type for use with\n// apply.\nfunc Secret(name, namespace string) *SecretApplyConfiguration {\n\tb := \u0026SecretApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"Secret\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b\n}","line":{"from":41,"to":50}} {"id":100022286,"name":"ExtractSecret","signature":"func ExtractSecret(secret *corev1.Secret, fieldManager string) (*SecretApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secret.go","code":"// ExtractSecret extracts the applied configuration owned by fieldManager from\n// secret. If no managedFields are found in secret for fieldManager, a\n// SecretApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// secret must be a unmodified Secret API object that was retrieved from the Kubernetes API.\n// ExtractSecret provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractSecret(secret *corev1.Secret, fieldManager string) (*SecretApplyConfiguration, error) {\n\treturn extractSecret(secret, fieldManager, \"\")\n}","line":{"from":52,"to":65}} {"id":100022287,"name":"ExtractSecretStatus","signature":"func ExtractSecretStatus(secret *corev1.Secret, fieldManager string) (*SecretApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secret.go","code":"// ExtractSecretStatus is the same as ExtractSecret except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractSecretStatus(secret *corev1.Secret, fieldManager string) (*SecretApplyConfiguration, error) {\n\treturn extractSecret(secret, fieldManager, \"status\")\n}","line":{"from":67,"to":72}} {"id":100022288,"name":"extractSecret","signature":"func extractSecret(secret *corev1.Secret, fieldManager string, subresource string) (*SecretApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secret.go","code":"func extractSecret(secret *corev1.Secret, fieldManager string, subresource string) (*SecretApplyConfiguration, error) {\n\tb := \u0026SecretApplyConfiguration{}\n\terr := managedfields.ExtractInto(secret, internal.Parser().Type(\"io.k8s.api.core.v1.Secret\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(secret.Name)\n\tb.WithNamespace(secret.Namespace)\n\n\tb.WithKind(\"Secret\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b, nil\n}","line":{"from":74,"to":86}} {"id":100022289,"name":"WithKind","signature":"func (b *SecretApplyConfiguration) WithKind(value string) *SecretApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secret.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *SecretApplyConfiguration) WithKind(value string) *SecretApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":88,"to":94}} {"id":100022290,"name":"WithAPIVersion","signature":"func (b *SecretApplyConfiguration) WithAPIVersion(value string) *SecretApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secret.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *SecretApplyConfiguration) WithAPIVersion(value string) *SecretApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":96,"to":102}} {"id":100022291,"name":"WithName","signature":"func (b *SecretApplyConfiguration) WithName(value string) *SecretApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secret.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *SecretApplyConfiguration) WithName(value string) *SecretApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":104,"to":111}} {"id":100022292,"name":"WithGenerateName","signature":"func (b *SecretApplyConfiguration) WithGenerateName(value string) *SecretApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secret.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *SecretApplyConfiguration) WithGenerateName(value string) *SecretApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":113,"to":120}} {"id":100022293,"name":"WithNamespace","signature":"func (b *SecretApplyConfiguration) WithNamespace(value string) *SecretApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secret.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *SecretApplyConfiguration) WithNamespace(value string) *SecretApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":122,"to":129}} {"id":100022294,"name":"WithUID","signature":"func (b *SecretApplyConfiguration) WithUID(value types.UID) *SecretApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secret.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *SecretApplyConfiguration) WithUID(value types.UID) *SecretApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":131,"to":138}} {"id":100022295,"name":"WithResourceVersion","signature":"func (b *SecretApplyConfiguration) WithResourceVersion(value string) *SecretApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secret.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *SecretApplyConfiguration) WithResourceVersion(value string) *SecretApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":140,"to":147}} {"id":100022296,"name":"WithGeneration","signature":"func (b *SecretApplyConfiguration) WithGeneration(value int64) *SecretApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secret.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *SecretApplyConfiguration) WithGeneration(value int64) *SecretApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":149,"to":156}} {"id":100022297,"name":"WithCreationTimestamp","signature":"func (b *SecretApplyConfiguration) WithCreationTimestamp(value metav1.Time) *SecretApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secret.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *SecretApplyConfiguration) WithCreationTimestamp(value metav1.Time) *SecretApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":158,"to":165}} {"id":100022298,"name":"WithDeletionTimestamp","signature":"func (b *SecretApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *SecretApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secret.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *SecretApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *SecretApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":167,"to":174}} {"id":100022299,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *SecretApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *SecretApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secret.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *SecretApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *SecretApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":176,"to":183}} {"id":100022300,"name":"WithLabels","signature":"func (b *SecretApplyConfiguration) WithLabels(entries map[string]string) *SecretApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secret.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *SecretApplyConfiguration) WithLabels(entries map[string]string) *SecretApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":185,"to":198}} {"id":100022301,"name":"WithAnnotations","signature":"func (b *SecretApplyConfiguration) WithAnnotations(entries map[string]string) *SecretApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secret.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *SecretApplyConfiguration) WithAnnotations(entries map[string]string) *SecretApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":200,"to":213}} {"id":100022302,"name":"WithOwnerReferences","signature":"func (b *SecretApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *SecretApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secret.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *SecretApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *SecretApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":215,"to":227}} {"id":100022303,"name":"WithFinalizers","signature":"func (b *SecretApplyConfiguration) WithFinalizers(values ...string) *SecretApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secret.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *SecretApplyConfiguration) WithFinalizers(values ...string) *SecretApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":229,"to":238}} {"id":100022304,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *SecretApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secret.go","code":"func (b *SecretApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":240,"to":244}} {"id":100022305,"name":"WithImmutable","signature":"func (b *SecretApplyConfiguration) WithImmutable(value bool) *SecretApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secret.go","code":"// WithImmutable sets the Immutable field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Immutable field is set to the value of the last call.\nfunc (b *SecretApplyConfiguration) WithImmutable(value bool) *SecretApplyConfiguration {\n\tb.Immutable = \u0026value\n\treturn b\n}","line":{"from":246,"to":252}} {"id":100022306,"name":"WithData","signature":"func (b *SecretApplyConfiguration) WithData(entries map[string][]byte) *SecretApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secret.go","code":"// WithData puts the entries into the Data field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Data field,\n// overwriting an existing map entries in Data field with the same key.\nfunc (b *SecretApplyConfiguration) WithData(entries map[string][]byte) *SecretApplyConfiguration {\n\tif b.Data == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Data = make(map[string][]byte, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Data[k] = v\n\t}\n\treturn b\n}","line":{"from":254,"to":266}} {"id":100022307,"name":"WithStringData","signature":"func (b *SecretApplyConfiguration) WithStringData(entries map[string]string) *SecretApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secret.go","code":"// WithStringData puts the entries into the StringData field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the StringData field,\n// overwriting an existing map entries in StringData field with the same key.\nfunc (b *SecretApplyConfiguration) WithStringData(entries map[string]string) *SecretApplyConfiguration {\n\tif b.StringData == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.StringData = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.StringData[k] = v\n\t}\n\treturn b\n}","line":{"from":268,"to":280}} {"id":100022308,"name":"WithType","signature":"func (b *SecretApplyConfiguration) WithType(value corev1.SecretType) *SecretApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secret.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *SecretApplyConfiguration) WithType(value corev1.SecretType) *SecretApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":282,"to":288}} {"id":100022309,"name":"SecretEnvSource","signature":"func SecretEnvSource() *SecretEnvSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secretenvsource.go","code":"// SecretEnvSourceApplyConfiguration constructs an declarative configuration of the SecretEnvSource type for use with\n// apply.\nfunc SecretEnvSource() *SecretEnvSourceApplyConfiguration {\n\treturn \u0026SecretEnvSourceApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100022310,"name":"WithName","signature":"func (b *SecretEnvSourceApplyConfiguration) WithName(value string) *SecretEnvSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secretenvsource.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *SecretEnvSourceApplyConfiguration) WithName(value string) *SecretEnvSourceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100022311,"name":"WithOptional","signature":"func (b *SecretEnvSourceApplyConfiguration) WithOptional(value bool) *SecretEnvSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secretenvsource.go","code":"// WithOptional sets the Optional field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Optional field is set to the value of the last call.\nfunc (b *SecretEnvSourceApplyConfiguration) WithOptional(value bool) *SecretEnvSourceApplyConfiguration {\n\tb.Optional = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100022312,"name":"SecretKeySelector","signature":"func SecretKeySelector() *SecretKeySelectorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secretkeyselector.go","code":"// SecretKeySelectorApplyConfiguration constructs an declarative configuration of the SecretKeySelector type for use with\n// apply.\nfunc SecretKeySelector() *SecretKeySelectorApplyConfiguration {\n\treturn \u0026SecretKeySelectorApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100022313,"name":"WithName","signature":"func (b *SecretKeySelectorApplyConfiguration) WithName(value string) *SecretKeySelectorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secretkeyselector.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *SecretKeySelectorApplyConfiguration) WithName(value string) *SecretKeySelectorApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100022314,"name":"WithKey","signature":"func (b *SecretKeySelectorApplyConfiguration) WithKey(value string) *SecretKeySelectorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secretkeyselector.go","code":"// WithKey sets the Key field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Key field is set to the value of the last call.\nfunc (b *SecretKeySelectorApplyConfiguration) WithKey(value string) *SecretKeySelectorApplyConfiguration {\n\tb.Key = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100022315,"name":"WithOptional","signature":"func (b *SecretKeySelectorApplyConfiguration) WithOptional(value bool) *SecretKeySelectorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secretkeyselector.go","code":"// WithOptional sets the Optional field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Optional field is set to the value of the last call.\nfunc (b *SecretKeySelectorApplyConfiguration) WithOptional(value bool) *SecretKeySelectorApplyConfiguration {\n\tb.Optional = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100022316,"name":"SecretProjection","signature":"func SecretProjection() *SecretProjectionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secretprojection.go","code":"// SecretProjectionApplyConfiguration constructs an declarative configuration of the SecretProjection type for use with\n// apply.\nfunc SecretProjection() *SecretProjectionApplyConfiguration {\n\treturn \u0026SecretProjectionApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100022317,"name":"WithName","signature":"func (b *SecretProjectionApplyConfiguration) WithName(value string) *SecretProjectionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secretprojection.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *SecretProjectionApplyConfiguration) WithName(value string) *SecretProjectionApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100022318,"name":"WithItems","signature":"func (b *SecretProjectionApplyConfiguration) WithItems(values ...*KeyToPathApplyConfiguration) *SecretProjectionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secretprojection.go","code":"// WithItems adds the given value to the Items field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Items field.\nfunc (b *SecretProjectionApplyConfiguration) WithItems(values ...*KeyToPathApplyConfiguration) *SecretProjectionApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithItems\")\n\t\t}\n\t\tb.Items = append(b.Items, *values[i])\n\t}\n\treturn b\n}","line":{"from":43,"to":54}} {"id":100022319,"name":"WithOptional","signature":"func (b *SecretProjectionApplyConfiguration) WithOptional(value bool) *SecretProjectionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secretprojection.go","code":"// WithOptional sets the Optional field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Optional field is set to the value of the last call.\nfunc (b *SecretProjectionApplyConfiguration) WithOptional(value bool) *SecretProjectionApplyConfiguration {\n\tb.Optional = \u0026value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100022320,"name":"SecretReference","signature":"func SecretReference() *SecretReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secretreference.go","code":"// SecretReferenceApplyConfiguration constructs an declarative configuration of the SecretReference type for use with\n// apply.\nfunc SecretReference() *SecretReferenceApplyConfiguration {\n\treturn \u0026SecretReferenceApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100022321,"name":"WithName","signature":"func (b *SecretReferenceApplyConfiguration) WithName(value string) *SecretReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secretreference.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *SecretReferenceApplyConfiguration) WithName(value string) *SecretReferenceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100022322,"name":"WithNamespace","signature":"func (b *SecretReferenceApplyConfiguration) WithNamespace(value string) *SecretReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secretreference.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *SecretReferenceApplyConfiguration) WithNamespace(value string) *SecretReferenceApplyConfiguration {\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100022323,"name":"SecretVolumeSource","signature":"func SecretVolumeSource() *SecretVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secretvolumesource.go","code":"// SecretVolumeSourceApplyConfiguration constructs an declarative configuration of the SecretVolumeSource type for use with\n// apply.\nfunc SecretVolumeSource() *SecretVolumeSourceApplyConfiguration {\n\treturn \u0026SecretVolumeSourceApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100022324,"name":"WithSecretName","signature":"func (b *SecretVolumeSourceApplyConfiguration) WithSecretName(value string) *SecretVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secretvolumesource.go","code":"// WithSecretName sets the SecretName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecretName field is set to the value of the last call.\nfunc (b *SecretVolumeSourceApplyConfiguration) WithSecretName(value string) *SecretVolumeSourceApplyConfiguration {\n\tb.SecretName = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100022325,"name":"WithItems","signature":"func (b *SecretVolumeSourceApplyConfiguration) WithItems(values ...*KeyToPathApplyConfiguration) *SecretVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secretvolumesource.go","code":"// WithItems adds the given value to the Items field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Items field.\nfunc (b *SecretVolumeSourceApplyConfiguration) WithItems(values ...*KeyToPathApplyConfiguration) *SecretVolumeSourceApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithItems\")\n\t\t}\n\t\tb.Items = append(b.Items, *values[i])\n\t}\n\treturn b\n}","line":{"from":44,"to":55}} {"id":100022326,"name":"WithDefaultMode","signature":"func (b *SecretVolumeSourceApplyConfiguration) WithDefaultMode(value int32) *SecretVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secretvolumesource.go","code":"// WithDefaultMode sets the DefaultMode field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DefaultMode field is set to the value of the last call.\nfunc (b *SecretVolumeSourceApplyConfiguration) WithDefaultMode(value int32) *SecretVolumeSourceApplyConfiguration {\n\tb.DefaultMode = \u0026value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100022327,"name":"WithOptional","signature":"func (b *SecretVolumeSourceApplyConfiguration) WithOptional(value bool) *SecretVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/secretvolumesource.go","code":"// WithOptional sets the Optional field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Optional field is set to the value of the last call.\nfunc (b *SecretVolumeSourceApplyConfiguration) WithOptional(value bool) *SecretVolumeSourceApplyConfiguration {\n\tb.Optional = \u0026value\n\treturn b\n}","line":{"from":65,"to":71}} {"id":100022328,"name":"SecurityContext","signature":"func SecurityContext() *SecurityContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/securitycontext.go","code":"// SecurityContextApplyConfiguration constructs an declarative configuration of the SecurityContext type for use with\n// apply.\nfunc SecurityContext() *SecurityContextApplyConfiguration {\n\treturn \u0026SecurityContextApplyConfiguration{}\n}","line":{"from":41,"to":45}} {"id":100022329,"name":"WithCapabilities","signature":"func (b *SecurityContextApplyConfiguration) WithCapabilities(value *CapabilitiesApplyConfiguration) *SecurityContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/securitycontext.go","code":"// WithCapabilities sets the Capabilities field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Capabilities field is set to the value of the last call.\nfunc (b *SecurityContextApplyConfiguration) WithCapabilities(value *CapabilitiesApplyConfiguration) *SecurityContextApplyConfiguration {\n\tb.Capabilities = value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100022330,"name":"WithPrivileged","signature":"func (b *SecurityContextApplyConfiguration) WithPrivileged(value bool) *SecurityContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/securitycontext.go","code":"// WithPrivileged sets the Privileged field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Privileged field is set to the value of the last call.\nfunc (b *SecurityContextApplyConfiguration) WithPrivileged(value bool) *SecurityContextApplyConfiguration {\n\tb.Privileged = \u0026value\n\treturn b\n}","line":{"from":55,"to":61}} {"id":100022331,"name":"WithSELinuxOptions","signature":"func (b *SecurityContextApplyConfiguration) WithSELinuxOptions(value *SELinuxOptionsApplyConfiguration) *SecurityContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/securitycontext.go","code":"// WithSELinuxOptions sets the SELinuxOptions field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SELinuxOptions field is set to the value of the last call.\nfunc (b *SecurityContextApplyConfiguration) WithSELinuxOptions(value *SELinuxOptionsApplyConfiguration) *SecurityContextApplyConfiguration {\n\tb.SELinuxOptions = value\n\treturn b\n}","line":{"from":63,"to":69}} {"id":100022332,"name":"WithWindowsOptions","signature":"func (b *SecurityContextApplyConfiguration) WithWindowsOptions(value *WindowsSecurityContextOptionsApplyConfiguration) *SecurityContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/securitycontext.go","code":"// WithWindowsOptions sets the WindowsOptions field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the WindowsOptions field is set to the value of the last call.\nfunc (b *SecurityContextApplyConfiguration) WithWindowsOptions(value *WindowsSecurityContextOptionsApplyConfiguration) *SecurityContextApplyConfiguration {\n\tb.WindowsOptions = value\n\treturn b\n}","line":{"from":71,"to":77}} {"id":100022333,"name":"WithRunAsUser","signature":"func (b *SecurityContextApplyConfiguration) WithRunAsUser(value int64) *SecurityContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/securitycontext.go","code":"// WithRunAsUser sets the RunAsUser field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RunAsUser field is set to the value of the last call.\nfunc (b *SecurityContextApplyConfiguration) WithRunAsUser(value int64) *SecurityContextApplyConfiguration {\n\tb.RunAsUser = \u0026value\n\treturn b\n}","line":{"from":79,"to":85}} {"id":100022334,"name":"WithRunAsGroup","signature":"func (b *SecurityContextApplyConfiguration) WithRunAsGroup(value int64) *SecurityContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/securitycontext.go","code":"// WithRunAsGroup sets the RunAsGroup field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RunAsGroup field is set to the value of the last call.\nfunc (b *SecurityContextApplyConfiguration) WithRunAsGroup(value int64) *SecurityContextApplyConfiguration {\n\tb.RunAsGroup = \u0026value\n\treturn b\n}","line":{"from":87,"to":93}} {"id":100022335,"name":"WithRunAsNonRoot","signature":"func (b *SecurityContextApplyConfiguration) WithRunAsNonRoot(value bool) *SecurityContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/securitycontext.go","code":"// WithRunAsNonRoot sets the RunAsNonRoot field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RunAsNonRoot field is set to the value of the last call.\nfunc (b *SecurityContextApplyConfiguration) WithRunAsNonRoot(value bool) *SecurityContextApplyConfiguration {\n\tb.RunAsNonRoot = \u0026value\n\treturn b\n}","line":{"from":95,"to":101}} {"id":100022336,"name":"WithReadOnlyRootFilesystem","signature":"func (b *SecurityContextApplyConfiguration) WithReadOnlyRootFilesystem(value bool) *SecurityContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/securitycontext.go","code":"// WithReadOnlyRootFilesystem sets the ReadOnlyRootFilesystem field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnlyRootFilesystem field is set to the value of the last call.\nfunc (b *SecurityContextApplyConfiguration) WithReadOnlyRootFilesystem(value bool) *SecurityContextApplyConfiguration {\n\tb.ReadOnlyRootFilesystem = \u0026value\n\treturn b\n}","line":{"from":103,"to":109}} {"id":100022337,"name":"WithAllowPrivilegeEscalation","signature":"func (b *SecurityContextApplyConfiguration) WithAllowPrivilegeEscalation(value bool) *SecurityContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/securitycontext.go","code":"// WithAllowPrivilegeEscalation sets the AllowPrivilegeEscalation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AllowPrivilegeEscalation field is set to the value of the last call.\nfunc (b *SecurityContextApplyConfiguration) WithAllowPrivilegeEscalation(value bool) *SecurityContextApplyConfiguration {\n\tb.AllowPrivilegeEscalation = \u0026value\n\treturn b\n}","line":{"from":111,"to":117}} {"id":100022338,"name":"WithProcMount","signature":"func (b *SecurityContextApplyConfiguration) WithProcMount(value corev1.ProcMountType) *SecurityContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/securitycontext.go","code":"// WithProcMount sets the ProcMount field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ProcMount field is set to the value of the last call.\nfunc (b *SecurityContextApplyConfiguration) WithProcMount(value corev1.ProcMountType) *SecurityContextApplyConfiguration {\n\tb.ProcMount = \u0026value\n\treturn b\n}","line":{"from":119,"to":125}} {"id":100022339,"name":"WithSeccompProfile","signature":"func (b *SecurityContextApplyConfiguration) WithSeccompProfile(value *SeccompProfileApplyConfiguration) *SecurityContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/securitycontext.go","code":"// WithSeccompProfile sets the SeccompProfile field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SeccompProfile field is set to the value of the last call.\nfunc (b *SecurityContextApplyConfiguration) WithSeccompProfile(value *SeccompProfileApplyConfiguration) *SecurityContextApplyConfiguration {\n\tb.SeccompProfile = value\n\treturn b\n}","line":{"from":127,"to":133}} {"id":100022340,"name":"SELinuxOptions","signature":"func SELinuxOptions() *SELinuxOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/selinuxoptions.go","code":"// SELinuxOptionsApplyConfiguration constructs an declarative configuration of the SELinuxOptions type for use with\n// apply.\nfunc SELinuxOptions() *SELinuxOptionsApplyConfiguration {\n\treturn \u0026SELinuxOptionsApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100022341,"name":"WithUser","signature":"func (b *SELinuxOptionsApplyConfiguration) WithUser(value string) *SELinuxOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/selinuxoptions.go","code":"// WithUser sets the User field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the User field is set to the value of the last call.\nfunc (b *SELinuxOptionsApplyConfiguration) WithUser(value string) *SELinuxOptionsApplyConfiguration {\n\tb.User = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100022342,"name":"WithRole","signature":"func (b *SELinuxOptionsApplyConfiguration) WithRole(value string) *SELinuxOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/selinuxoptions.go","code":"// WithRole sets the Role field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Role field is set to the value of the last call.\nfunc (b *SELinuxOptionsApplyConfiguration) WithRole(value string) *SELinuxOptionsApplyConfiguration {\n\tb.Role = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100022343,"name":"WithType","signature":"func (b *SELinuxOptionsApplyConfiguration) WithType(value string) *SELinuxOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/selinuxoptions.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *SELinuxOptionsApplyConfiguration) WithType(value string) *SELinuxOptionsApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100022344,"name":"WithLevel","signature":"func (b *SELinuxOptionsApplyConfiguration) WithLevel(value string) *SELinuxOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/selinuxoptions.go","code":"// WithLevel sets the Level field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Level field is set to the value of the last call.\nfunc (b *SELinuxOptionsApplyConfiguration) WithLevel(value string) *SELinuxOptionsApplyConfiguration {\n\tb.Level = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100022345,"name":"Service","signature":"func Service(name, namespace string) *ServiceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/service.go","code":"// Service constructs an declarative configuration of the Service type for use with\n// apply.\nfunc Service(name, namespace string) *ServiceApplyConfiguration {\n\tb := \u0026ServiceApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"Service\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100022346,"name":"ExtractService","signature":"func ExtractService(service *apicorev1.Service, fieldManager string) (*ServiceApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/service.go","code":"// ExtractService extracts the applied configuration owned by fieldManager from\n// service. If no managedFields are found in service for fieldManager, a\n// ServiceApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// service must be a unmodified Service API object that was retrieved from the Kubernetes API.\n// ExtractService provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractService(service *apicorev1.Service, fieldManager string) (*ServiceApplyConfiguration, error) {\n\treturn extractService(service, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100022347,"name":"ExtractServiceStatus","signature":"func ExtractServiceStatus(service *apicorev1.Service, fieldManager string) (*ServiceApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/service.go","code":"// ExtractServiceStatus is the same as ExtractService except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractServiceStatus(service *apicorev1.Service, fieldManager string) (*ServiceApplyConfiguration, error) {\n\treturn extractService(service, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100022348,"name":"extractService","signature":"func extractService(service *apicorev1.Service, fieldManager string, subresource string) (*ServiceApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/service.go","code":"func extractService(service *apicorev1.Service, fieldManager string, subresource string) (*ServiceApplyConfiguration, error) {\n\tb := \u0026ServiceApplyConfiguration{}\n\terr := managedfields.ExtractInto(service, internal.Parser().Type(\"io.k8s.api.core.v1.Service\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(service.Name)\n\tb.WithNamespace(service.Namespace)\n\n\tb.WithKind(\"Service\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100022349,"name":"WithKind","signature":"func (b *ServiceApplyConfiguration) WithKind(value string) *ServiceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/service.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ServiceApplyConfiguration) WithKind(value string) *ServiceApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100022350,"name":"WithAPIVersion","signature":"func (b *ServiceApplyConfiguration) WithAPIVersion(value string) *ServiceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/service.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ServiceApplyConfiguration) WithAPIVersion(value string) *ServiceApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100022351,"name":"WithName","signature":"func (b *ServiceApplyConfiguration) WithName(value string) *ServiceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/service.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ServiceApplyConfiguration) WithName(value string) *ServiceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100022352,"name":"WithGenerateName","signature":"func (b *ServiceApplyConfiguration) WithGenerateName(value string) *ServiceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/service.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ServiceApplyConfiguration) WithGenerateName(value string) *ServiceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100022353,"name":"WithNamespace","signature":"func (b *ServiceApplyConfiguration) WithNamespace(value string) *ServiceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/service.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ServiceApplyConfiguration) WithNamespace(value string) *ServiceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100022354,"name":"WithUID","signature":"func (b *ServiceApplyConfiguration) WithUID(value types.UID) *ServiceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/service.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ServiceApplyConfiguration) WithUID(value types.UID) *ServiceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100022355,"name":"WithResourceVersion","signature":"func (b *ServiceApplyConfiguration) WithResourceVersion(value string) *ServiceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/service.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ServiceApplyConfiguration) WithResourceVersion(value string) *ServiceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100022356,"name":"WithGeneration","signature":"func (b *ServiceApplyConfiguration) WithGeneration(value int64) *ServiceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/service.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ServiceApplyConfiguration) WithGeneration(value int64) *ServiceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100022357,"name":"WithCreationTimestamp","signature":"func (b *ServiceApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ServiceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/service.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ServiceApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ServiceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100022358,"name":"WithDeletionTimestamp","signature":"func (b *ServiceApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ServiceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/service.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ServiceApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ServiceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100022359,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ServiceApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ServiceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/service.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ServiceApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ServiceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100022360,"name":"WithLabels","signature":"func (b *ServiceApplyConfiguration) WithLabels(entries map[string]string) *ServiceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/service.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ServiceApplyConfiguration) WithLabels(entries map[string]string) *ServiceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100022361,"name":"WithAnnotations","signature":"func (b *ServiceApplyConfiguration) WithAnnotations(entries map[string]string) *ServiceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/service.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ServiceApplyConfiguration) WithAnnotations(entries map[string]string) *ServiceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100022362,"name":"WithOwnerReferences","signature":"func (b *ServiceApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ServiceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/service.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ServiceApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ServiceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100022363,"name":"WithFinalizers","signature":"func (b *ServiceApplyConfiguration) WithFinalizers(values ...string) *ServiceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/service.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ServiceApplyConfiguration) WithFinalizers(values ...string) *ServiceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100022364,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ServiceApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/service.go","code":"func (b *ServiceApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100022365,"name":"WithSpec","signature":"func (b *ServiceApplyConfiguration) WithSpec(value *ServiceSpecApplyConfiguration) *ServiceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/service.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *ServiceApplyConfiguration) WithSpec(value *ServiceSpecApplyConfiguration) *ServiceApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100022366,"name":"WithStatus","signature":"func (b *ServiceApplyConfiguration) WithStatus(value *ServiceStatusApplyConfiguration) *ServiceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/service.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *ServiceApplyConfiguration) WithStatus(value *ServiceStatusApplyConfiguration) *ServiceApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100022367,"name":"ServiceAccount","signature":"func ServiceAccount(name, namespace string) *ServiceAccountApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go","code":"// ServiceAccount constructs an declarative configuration of the ServiceAccount type for use with\n// apply.\nfunc ServiceAccount(name, namespace string) *ServiceAccountApplyConfiguration {\n\tb := \u0026ServiceAccountApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"ServiceAccount\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b\n}","line":{"from":40,"to":49}} {"id":100022368,"name":"ExtractServiceAccount","signature":"func ExtractServiceAccount(serviceAccount *apicorev1.ServiceAccount, fieldManager string) (*ServiceAccountApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go","code":"// ExtractServiceAccount extracts the applied configuration owned by fieldManager from\n// serviceAccount. If no managedFields are found in serviceAccount for fieldManager, a\n// ServiceAccountApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// serviceAccount must be a unmodified ServiceAccount API object that was retrieved from the Kubernetes API.\n// ExtractServiceAccount provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractServiceAccount(serviceAccount *apicorev1.ServiceAccount, fieldManager string) (*ServiceAccountApplyConfiguration, error) {\n\treturn extractServiceAccount(serviceAccount, fieldManager, \"\")\n}","line":{"from":51,"to":64}} {"id":100022369,"name":"ExtractServiceAccountStatus","signature":"func ExtractServiceAccountStatus(serviceAccount *apicorev1.ServiceAccount, fieldManager string) (*ServiceAccountApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go","code":"// ExtractServiceAccountStatus is the same as ExtractServiceAccount except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractServiceAccountStatus(serviceAccount *apicorev1.ServiceAccount, fieldManager string) (*ServiceAccountApplyConfiguration, error) {\n\treturn extractServiceAccount(serviceAccount, fieldManager, \"status\")\n}","line":{"from":66,"to":71}} {"id":100022370,"name":"extractServiceAccount","signature":"func extractServiceAccount(serviceAccount *apicorev1.ServiceAccount, fieldManager string, subresource string) (*ServiceAccountApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go","code":"func extractServiceAccount(serviceAccount *apicorev1.ServiceAccount, fieldManager string, subresource string) (*ServiceAccountApplyConfiguration, error) {\n\tb := \u0026ServiceAccountApplyConfiguration{}\n\terr := managedfields.ExtractInto(serviceAccount, internal.Parser().Type(\"io.k8s.api.core.v1.ServiceAccount\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(serviceAccount.Name)\n\tb.WithNamespace(serviceAccount.Namespace)\n\n\tb.WithKind(\"ServiceAccount\")\n\tb.WithAPIVersion(\"v1\")\n\treturn b, nil\n}","line":{"from":73,"to":85}} {"id":100022371,"name":"WithKind","signature":"func (b *ServiceAccountApplyConfiguration) WithKind(value string) *ServiceAccountApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ServiceAccountApplyConfiguration) WithKind(value string) *ServiceAccountApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":87,"to":93}} {"id":100022372,"name":"WithAPIVersion","signature":"func (b *ServiceAccountApplyConfiguration) WithAPIVersion(value string) *ServiceAccountApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ServiceAccountApplyConfiguration) WithAPIVersion(value string) *ServiceAccountApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":95,"to":101}} {"id":100022373,"name":"WithName","signature":"func (b *ServiceAccountApplyConfiguration) WithName(value string) *ServiceAccountApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ServiceAccountApplyConfiguration) WithName(value string) *ServiceAccountApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":103,"to":110}} {"id":100022374,"name":"WithGenerateName","signature":"func (b *ServiceAccountApplyConfiguration) WithGenerateName(value string) *ServiceAccountApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ServiceAccountApplyConfiguration) WithGenerateName(value string) *ServiceAccountApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":112,"to":119}} {"id":100022375,"name":"WithNamespace","signature":"func (b *ServiceAccountApplyConfiguration) WithNamespace(value string) *ServiceAccountApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ServiceAccountApplyConfiguration) WithNamespace(value string) *ServiceAccountApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":121,"to":128}} {"id":100022376,"name":"WithUID","signature":"func (b *ServiceAccountApplyConfiguration) WithUID(value types.UID) *ServiceAccountApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ServiceAccountApplyConfiguration) WithUID(value types.UID) *ServiceAccountApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":130,"to":137}} {"id":100022377,"name":"WithResourceVersion","signature":"func (b *ServiceAccountApplyConfiguration) WithResourceVersion(value string) *ServiceAccountApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ServiceAccountApplyConfiguration) WithResourceVersion(value string) *ServiceAccountApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":139,"to":146}} {"id":100022378,"name":"WithGeneration","signature":"func (b *ServiceAccountApplyConfiguration) WithGeneration(value int64) *ServiceAccountApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ServiceAccountApplyConfiguration) WithGeneration(value int64) *ServiceAccountApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":148,"to":155}} {"id":100022379,"name":"WithCreationTimestamp","signature":"func (b *ServiceAccountApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ServiceAccountApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ServiceAccountApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ServiceAccountApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":157,"to":164}} {"id":100022380,"name":"WithDeletionTimestamp","signature":"func (b *ServiceAccountApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ServiceAccountApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ServiceAccountApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ServiceAccountApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":166,"to":173}} {"id":100022381,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ServiceAccountApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ServiceAccountApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ServiceAccountApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ServiceAccountApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":175,"to":182}} {"id":100022382,"name":"WithLabels","signature":"func (b *ServiceAccountApplyConfiguration) WithLabels(entries map[string]string) *ServiceAccountApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ServiceAccountApplyConfiguration) WithLabels(entries map[string]string) *ServiceAccountApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":184,"to":197}} {"id":100022383,"name":"WithAnnotations","signature":"func (b *ServiceAccountApplyConfiguration) WithAnnotations(entries map[string]string) *ServiceAccountApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ServiceAccountApplyConfiguration) WithAnnotations(entries map[string]string) *ServiceAccountApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":199,"to":212}} {"id":100022384,"name":"WithOwnerReferences","signature":"func (b *ServiceAccountApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ServiceAccountApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ServiceAccountApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ServiceAccountApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":214,"to":226}} {"id":100022385,"name":"WithFinalizers","signature":"func (b *ServiceAccountApplyConfiguration) WithFinalizers(values ...string) *ServiceAccountApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ServiceAccountApplyConfiguration) WithFinalizers(values ...string) *ServiceAccountApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":228,"to":237}} {"id":100022386,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ServiceAccountApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go","code":"func (b *ServiceAccountApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":239,"to":243}} {"id":100022387,"name":"WithSecrets","signature":"func (b *ServiceAccountApplyConfiguration) WithSecrets(values ...*ObjectReferenceApplyConfiguration) *ServiceAccountApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go","code":"// WithSecrets adds the given value to the Secrets field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Secrets field.\nfunc (b *ServiceAccountApplyConfiguration) WithSecrets(values ...*ObjectReferenceApplyConfiguration) *ServiceAccountApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithSecrets\")\n\t\t}\n\t\tb.Secrets = append(b.Secrets, *values[i])\n\t}\n\treturn b\n}","line":{"from":245,"to":256}} {"id":100022388,"name":"WithImagePullSecrets","signature":"func (b *ServiceAccountApplyConfiguration) WithImagePullSecrets(values ...*LocalObjectReferenceApplyConfiguration) *ServiceAccountApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go","code":"// WithImagePullSecrets adds the given value to the ImagePullSecrets field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ImagePullSecrets field.\nfunc (b *ServiceAccountApplyConfiguration) WithImagePullSecrets(values ...*LocalObjectReferenceApplyConfiguration) *ServiceAccountApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithImagePullSecrets\")\n\t\t}\n\t\tb.ImagePullSecrets = append(b.ImagePullSecrets, *values[i])\n\t}\n\treturn b\n}","line":{"from":258,"to":269}} {"id":100022389,"name":"WithAutomountServiceAccountToken","signature":"func (b *ServiceAccountApplyConfiguration) WithAutomountServiceAccountToken(value bool) *ServiceAccountApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccount.go","code":"// WithAutomountServiceAccountToken sets the AutomountServiceAccountToken field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AutomountServiceAccountToken field is set to the value of the last call.\nfunc (b *ServiceAccountApplyConfiguration) WithAutomountServiceAccountToken(value bool) *ServiceAccountApplyConfiguration {\n\tb.AutomountServiceAccountToken = \u0026value\n\treturn b\n}","line":{"from":271,"to":277}} {"id":100022390,"name":"ServiceAccountTokenProjection","signature":"func ServiceAccountTokenProjection() *ServiceAccountTokenProjectionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccounttokenprojection.go","code":"// ServiceAccountTokenProjectionApplyConfiguration constructs an declarative configuration of the ServiceAccountTokenProjection type for use with\n// apply.\nfunc ServiceAccountTokenProjection() *ServiceAccountTokenProjectionApplyConfiguration {\n\treturn \u0026ServiceAccountTokenProjectionApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100022391,"name":"WithAudience","signature":"func (b *ServiceAccountTokenProjectionApplyConfiguration) WithAudience(value string) *ServiceAccountTokenProjectionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccounttokenprojection.go","code":"// WithAudience sets the Audience field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Audience field is set to the value of the last call.\nfunc (b *ServiceAccountTokenProjectionApplyConfiguration) WithAudience(value string) *ServiceAccountTokenProjectionApplyConfiguration {\n\tb.Audience = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100022392,"name":"WithExpirationSeconds","signature":"func (b *ServiceAccountTokenProjectionApplyConfiguration) WithExpirationSeconds(value int64) *ServiceAccountTokenProjectionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccounttokenprojection.go","code":"// WithExpirationSeconds sets the ExpirationSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ExpirationSeconds field is set to the value of the last call.\nfunc (b *ServiceAccountTokenProjectionApplyConfiguration) WithExpirationSeconds(value int64) *ServiceAccountTokenProjectionApplyConfiguration {\n\tb.ExpirationSeconds = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100022393,"name":"WithPath","signature":"func (b *ServiceAccountTokenProjectionApplyConfiguration) WithPath(value string) *ServiceAccountTokenProjectionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceaccounttokenprojection.go","code":"// WithPath sets the Path field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Path field is set to the value of the last call.\nfunc (b *ServiceAccountTokenProjectionApplyConfiguration) WithPath(value string) *ServiceAccountTokenProjectionApplyConfiguration {\n\tb.Path = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100022394,"name":"ServicePort","signature":"func ServicePort() *ServicePortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceport.go","code":"// ServicePortApplyConfiguration constructs an declarative configuration of the ServicePort type for use with\n// apply.\nfunc ServicePort() *ServicePortApplyConfiguration {\n\treturn \u0026ServicePortApplyConfiguration{}\n}","line":{"from":37,"to":41}} {"id":100022395,"name":"WithName","signature":"func (b *ServicePortApplyConfiguration) WithName(value string) *ServicePortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceport.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ServicePortApplyConfiguration) WithName(value string) *ServicePortApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100022396,"name":"WithProtocol","signature":"func (b *ServicePortApplyConfiguration) WithProtocol(value v1.Protocol) *ServicePortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceport.go","code":"// WithProtocol sets the Protocol field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Protocol field is set to the value of the last call.\nfunc (b *ServicePortApplyConfiguration) WithProtocol(value v1.Protocol) *ServicePortApplyConfiguration {\n\tb.Protocol = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100022397,"name":"WithAppProtocol","signature":"func (b *ServicePortApplyConfiguration) WithAppProtocol(value string) *ServicePortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceport.go","code":"// WithAppProtocol sets the AppProtocol field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AppProtocol field is set to the value of the last call.\nfunc (b *ServicePortApplyConfiguration) WithAppProtocol(value string) *ServicePortApplyConfiguration {\n\tb.AppProtocol = \u0026value\n\treturn b\n}","line":{"from":59,"to":65}} {"id":100022398,"name":"WithPort","signature":"func (b *ServicePortApplyConfiguration) WithPort(value int32) *ServicePortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceport.go","code":"// WithPort sets the Port field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Port field is set to the value of the last call.\nfunc (b *ServicePortApplyConfiguration) WithPort(value int32) *ServicePortApplyConfiguration {\n\tb.Port = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100022399,"name":"WithTargetPort","signature":"func (b *ServicePortApplyConfiguration) WithTargetPort(value intstr.IntOrString) *ServicePortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceport.go","code":"// WithTargetPort sets the TargetPort field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TargetPort field is set to the value of the last call.\nfunc (b *ServicePortApplyConfiguration) WithTargetPort(value intstr.IntOrString) *ServicePortApplyConfiguration {\n\tb.TargetPort = \u0026value\n\treturn b\n}","line":{"from":75,"to":81}} {"id":100022400,"name":"WithNodePort","signature":"func (b *ServicePortApplyConfiguration) WithNodePort(value int32) *ServicePortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/serviceport.go","code":"// WithNodePort sets the NodePort field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NodePort field is set to the value of the last call.\nfunc (b *ServicePortApplyConfiguration) WithNodePort(value int32) *ServicePortApplyConfiguration {\n\tb.NodePort = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100022401,"name":"ServiceSpec","signature":"func ServiceSpec() *ServiceSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/servicespec.go","code":"// ServiceSpecApplyConfiguration constructs an declarative configuration of the ServiceSpec type for use with\n// apply.\nfunc ServiceSpec() *ServiceSpecApplyConfiguration {\n\treturn \u0026ServiceSpecApplyConfiguration{}\n}","line":{"from":49,"to":53}} {"id":100022402,"name":"WithPorts","signature":"func (b *ServiceSpecApplyConfiguration) WithPorts(values ...*ServicePortApplyConfiguration) *ServiceSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/servicespec.go","code":"// WithPorts adds the given value to the Ports field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Ports field.\nfunc (b *ServiceSpecApplyConfiguration) WithPorts(values ...*ServicePortApplyConfiguration) *ServiceSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPorts\")\n\t\t}\n\t\tb.Ports = append(b.Ports, *values[i])\n\t}\n\treturn b\n}","line":{"from":55,"to":66}} {"id":100022403,"name":"WithSelector","signature":"func (b *ServiceSpecApplyConfiguration) WithSelector(entries map[string]string) *ServiceSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/servicespec.go","code":"// WithSelector puts the entries into the Selector field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Selector field,\n// overwriting an existing map entries in Selector field with the same key.\nfunc (b *ServiceSpecApplyConfiguration) WithSelector(entries map[string]string) *ServiceSpecApplyConfiguration {\n\tif b.Selector == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Selector = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Selector[k] = v\n\t}\n\treturn b\n}","line":{"from":68,"to":80}} {"id":100022404,"name":"WithClusterIP","signature":"func (b *ServiceSpecApplyConfiguration) WithClusterIP(value string) *ServiceSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/servicespec.go","code":"// WithClusterIP sets the ClusterIP field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ClusterIP field is set to the value of the last call.\nfunc (b *ServiceSpecApplyConfiguration) WithClusterIP(value string) *ServiceSpecApplyConfiguration {\n\tb.ClusterIP = \u0026value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100022405,"name":"WithClusterIPs","signature":"func (b *ServiceSpecApplyConfiguration) WithClusterIPs(values ...string) *ServiceSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/servicespec.go","code":"// WithClusterIPs adds the given value to the ClusterIPs field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ClusterIPs field.\nfunc (b *ServiceSpecApplyConfiguration) WithClusterIPs(values ...string) *ServiceSpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.ClusterIPs = append(b.ClusterIPs, values[i])\n\t}\n\treturn b\n}","line":{"from":90,"to":98}} {"id":100022406,"name":"WithType","signature":"func (b *ServiceSpecApplyConfiguration) WithType(value corev1.ServiceType) *ServiceSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/servicespec.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *ServiceSpecApplyConfiguration) WithType(value corev1.ServiceType) *ServiceSpecApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":100,"to":106}} {"id":100022407,"name":"WithExternalIPs","signature":"func (b *ServiceSpecApplyConfiguration) WithExternalIPs(values ...string) *ServiceSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/servicespec.go","code":"// WithExternalIPs adds the given value to the ExternalIPs field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ExternalIPs field.\nfunc (b *ServiceSpecApplyConfiguration) WithExternalIPs(values ...string) *ServiceSpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.ExternalIPs = append(b.ExternalIPs, values[i])\n\t}\n\treturn b\n}","line":{"from":108,"to":116}} {"id":100022408,"name":"WithSessionAffinity","signature":"func (b *ServiceSpecApplyConfiguration) WithSessionAffinity(value corev1.ServiceAffinity) *ServiceSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/servicespec.go","code":"// WithSessionAffinity sets the SessionAffinity field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SessionAffinity field is set to the value of the last call.\nfunc (b *ServiceSpecApplyConfiguration) WithSessionAffinity(value corev1.ServiceAffinity) *ServiceSpecApplyConfiguration {\n\tb.SessionAffinity = \u0026value\n\treturn b\n}","line":{"from":118,"to":124}} {"id":100022409,"name":"WithLoadBalancerIP","signature":"func (b *ServiceSpecApplyConfiguration) WithLoadBalancerIP(value string) *ServiceSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/servicespec.go","code":"// WithLoadBalancerIP sets the LoadBalancerIP field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LoadBalancerIP field is set to the value of the last call.\nfunc (b *ServiceSpecApplyConfiguration) WithLoadBalancerIP(value string) *ServiceSpecApplyConfiguration {\n\tb.LoadBalancerIP = \u0026value\n\treturn b\n}","line":{"from":126,"to":132}} {"id":100022410,"name":"WithLoadBalancerSourceRanges","signature":"func (b *ServiceSpecApplyConfiguration) WithLoadBalancerSourceRanges(values ...string) *ServiceSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/servicespec.go","code":"// WithLoadBalancerSourceRanges adds the given value to the LoadBalancerSourceRanges field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the LoadBalancerSourceRanges field.\nfunc (b *ServiceSpecApplyConfiguration) WithLoadBalancerSourceRanges(values ...string) *ServiceSpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.LoadBalancerSourceRanges = append(b.LoadBalancerSourceRanges, values[i])\n\t}\n\treturn b\n}","line":{"from":134,"to":142}} {"id":100022411,"name":"WithExternalName","signature":"func (b *ServiceSpecApplyConfiguration) WithExternalName(value string) *ServiceSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/servicespec.go","code":"// WithExternalName sets the ExternalName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ExternalName field is set to the value of the last call.\nfunc (b *ServiceSpecApplyConfiguration) WithExternalName(value string) *ServiceSpecApplyConfiguration {\n\tb.ExternalName = \u0026value\n\treturn b\n}","line":{"from":144,"to":150}} {"id":100022412,"name":"WithExternalTrafficPolicy","signature":"func (b *ServiceSpecApplyConfiguration) WithExternalTrafficPolicy(value corev1.ServiceExternalTrafficPolicy) *ServiceSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/servicespec.go","code":"// WithExternalTrafficPolicy sets the ExternalTrafficPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ExternalTrafficPolicy field is set to the value of the last call.\nfunc (b *ServiceSpecApplyConfiguration) WithExternalTrafficPolicy(value corev1.ServiceExternalTrafficPolicy) *ServiceSpecApplyConfiguration {\n\tb.ExternalTrafficPolicy = \u0026value\n\treturn b\n}","line":{"from":152,"to":158}} {"id":100022413,"name":"WithHealthCheckNodePort","signature":"func (b *ServiceSpecApplyConfiguration) WithHealthCheckNodePort(value int32) *ServiceSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/servicespec.go","code":"// WithHealthCheckNodePort sets the HealthCheckNodePort field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HealthCheckNodePort field is set to the value of the last call.\nfunc (b *ServiceSpecApplyConfiguration) WithHealthCheckNodePort(value int32) *ServiceSpecApplyConfiguration {\n\tb.HealthCheckNodePort = \u0026value\n\treturn b\n}","line":{"from":160,"to":166}} {"id":100022414,"name":"WithPublishNotReadyAddresses","signature":"func (b *ServiceSpecApplyConfiguration) WithPublishNotReadyAddresses(value bool) *ServiceSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/servicespec.go","code":"// WithPublishNotReadyAddresses sets the PublishNotReadyAddresses field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PublishNotReadyAddresses field is set to the value of the last call.\nfunc (b *ServiceSpecApplyConfiguration) WithPublishNotReadyAddresses(value bool) *ServiceSpecApplyConfiguration {\n\tb.PublishNotReadyAddresses = \u0026value\n\treturn b\n}","line":{"from":168,"to":174}} {"id":100022415,"name":"WithSessionAffinityConfig","signature":"func (b *ServiceSpecApplyConfiguration) WithSessionAffinityConfig(value *SessionAffinityConfigApplyConfiguration) *ServiceSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/servicespec.go","code":"// WithSessionAffinityConfig sets the SessionAffinityConfig field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SessionAffinityConfig field is set to the value of the last call.\nfunc (b *ServiceSpecApplyConfiguration) WithSessionAffinityConfig(value *SessionAffinityConfigApplyConfiguration) *ServiceSpecApplyConfiguration {\n\tb.SessionAffinityConfig = value\n\treturn b\n}","line":{"from":176,"to":182}} {"id":100022416,"name":"WithIPFamilies","signature":"func (b *ServiceSpecApplyConfiguration) WithIPFamilies(values ...corev1.IPFamily) *ServiceSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/servicespec.go","code":"// WithIPFamilies adds the given value to the IPFamilies field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the IPFamilies field.\nfunc (b *ServiceSpecApplyConfiguration) WithIPFamilies(values ...corev1.IPFamily) *ServiceSpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.IPFamilies = append(b.IPFamilies, values[i])\n\t}\n\treturn b\n}","line":{"from":184,"to":192}} {"id":100022417,"name":"WithIPFamilyPolicy","signature":"func (b *ServiceSpecApplyConfiguration) WithIPFamilyPolicy(value corev1.IPFamilyPolicy) *ServiceSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/servicespec.go","code":"// WithIPFamilyPolicy sets the IPFamilyPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the IPFamilyPolicy field is set to the value of the last call.\nfunc (b *ServiceSpecApplyConfiguration) WithIPFamilyPolicy(value corev1.IPFamilyPolicy) *ServiceSpecApplyConfiguration {\n\tb.IPFamilyPolicy = \u0026value\n\treturn b\n}","line":{"from":194,"to":200}} {"id":100022418,"name":"WithAllocateLoadBalancerNodePorts","signature":"func (b *ServiceSpecApplyConfiguration) WithAllocateLoadBalancerNodePorts(value bool) *ServiceSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/servicespec.go","code":"// WithAllocateLoadBalancerNodePorts sets the AllocateLoadBalancerNodePorts field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AllocateLoadBalancerNodePorts field is set to the value of the last call.\nfunc (b *ServiceSpecApplyConfiguration) WithAllocateLoadBalancerNodePorts(value bool) *ServiceSpecApplyConfiguration {\n\tb.AllocateLoadBalancerNodePorts = \u0026value\n\treturn b\n}","line":{"from":202,"to":208}} {"id":100022419,"name":"WithLoadBalancerClass","signature":"func (b *ServiceSpecApplyConfiguration) WithLoadBalancerClass(value string) *ServiceSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/servicespec.go","code":"// WithLoadBalancerClass sets the LoadBalancerClass field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LoadBalancerClass field is set to the value of the last call.\nfunc (b *ServiceSpecApplyConfiguration) WithLoadBalancerClass(value string) *ServiceSpecApplyConfiguration {\n\tb.LoadBalancerClass = \u0026value\n\treturn b\n}","line":{"from":210,"to":216}} {"id":100022420,"name":"WithInternalTrafficPolicy","signature":"func (b *ServiceSpecApplyConfiguration) WithInternalTrafficPolicy(value corev1.ServiceInternalTrafficPolicy) *ServiceSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/servicespec.go","code":"// WithInternalTrafficPolicy sets the InternalTrafficPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the InternalTrafficPolicy field is set to the value of the last call.\nfunc (b *ServiceSpecApplyConfiguration) WithInternalTrafficPolicy(value corev1.ServiceInternalTrafficPolicy) *ServiceSpecApplyConfiguration {\n\tb.InternalTrafficPolicy = \u0026value\n\treturn b\n}","line":{"from":218,"to":224}} {"id":100022421,"name":"ServiceStatus","signature":"func ServiceStatus() *ServiceStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/servicestatus.go","code":"// ServiceStatusApplyConfiguration constructs an declarative configuration of the ServiceStatus type for use with\n// apply.\nfunc ServiceStatus() *ServiceStatusApplyConfiguration {\n\treturn \u0026ServiceStatusApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100022422,"name":"WithLoadBalancer","signature":"func (b *ServiceStatusApplyConfiguration) WithLoadBalancer(value *LoadBalancerStatusApplyConfiguration) *ServiceStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/servicestatus.go","code":"// WithLoadBalancer sets the LoadBalancer field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LoadBalancer field is set to the value of the last call.\nfunc (b *ServiceStatusApplyConfiguration) WithLoadBalancer(value *LoadBalancerStatusApplyConfiguration) *ServiceStatusApplyConfiguration {\n\tb.LoadBalancer = value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100022423,"name":"WithConditions","signature":"func (b *ServiceStatusApplyConfiguration) WithConditions(values ...*metav1.ConditionApplyConfiguration) *ServiceStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/servicestatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *ServiceStatusApplyConfiguration) WithConditions(values ...*metav1.ConditionApplyConfiguration) *ServiceStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":46,"to":57}} {"id":100022424,"name":"SessionAffinityConfig","signature":"func SessionAffinityConfig() *SessionAffinityConfigApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/sessionaffinityconfig.go","code":"// SessionAffinityConfigApplyConfiguration constructs an declarative configuration of the SessionAffinityConfig type for use with\n// apply.\nfunc SessionAffinityConfig() *SessionAffinityConfigApplyConfiguration {\n\treturn \u0026SessionAffinityConfigApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100022425,"name":"WithClientIP","signature":"func (b *SessionAffinityConfigApplyConfiguration) WithClientIP(value *ClientIPConfigApplyConfiguration) *SessionAffinityConfigApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/sessionaffinityconfig.go","code":"// WithClientIP sets the ClientIP field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ClientIP field is set to the value of the last call.\nfunc (b *SessionAffinityConfigApplyConfiguration) WithClientIP(value *ClientIPConfigApplyConfiguration) *SessionAffinityConfigApplyConfiguration {\n\tb.ClientIP = value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100022426,"name":"StorageOSPersistentVolumeSource","signature":"func StorageOSPersistentVolumeSource() *StorageOSPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/storageospersistentvolumesource.go","code":"// StorageOSPersistentVolumeSourceApplyConfiguration constructs an declarative configuration of the StorageOSPersistentVolumeSource type for use with\n// apply.\nfunc StorageOSPersistentVolumeSource() *StorageOSPersistentVolumeSourceApplyConfiguration {\n\treturn \u0026StorageOSPersistentVolumeSourceApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100022427,"name":"WithVolumeName","signature":"func (b *StorageOSPersistentVolumeSourceApplyConfiguration) WithVolumeName(value string) *StorageOSPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/storageospersistentvolumesource.go","code":"// WithVolumeName sets the VolumeName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the VolumeName field is set to the value of the last call.\nfunc (b *StorageOSPersistentVolumeSourceApplyConfiguration) WithVolumeName(value string) *StorageOSPersistentVolumeSourceApplyConfiguration {\n\tb.VolumeName = \u0026value\n\treturn b\n}","line":{"from":37,"to":43}} {"id":100022428,"name":"WithVolumeNamespace","signature":"func (b *StorageOSPersistentVolumeSourceApplyConfiguration) WithVolumeNamespace(value string) *StorageOSPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/storageospersistentvolumesource.go","code":"// WithVolumeNamespace sets the VolumeNamespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the VolumeNamespace field is set to the value of the last call.\nfunc (b *StorageOSPersistentVolumeSourceApplyConfiguration) WithVolumeNamespace(value string) *StorageOSPersistentVolumeSourceApplyConfiguration {\n\tb.VolumeNamespace = \u0026value\n\treturn b\n}","line":{"from":45,"to":51}} {"id":100022429,"name":"WithFSType","signature":"func (b *StorageOSPersistentVolumeSourceApplyConfiguration) WithFSType(value string) *StorageOSPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/storageospersistentvolumesource.go","code":"// WithFSType sets the FSType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSType field is set to the value of the last call.\nfunc (b *StorageOSPersistentVolumeSourceApplyConfiguration) WithFSType(value string) *StorageOSPersistentVolumeSourceApplyConfiguration {\n\tb.FSType = \u0026value\n\treturn b\n}","line":{"from":53,"to":59}} {"id":100022430,"name":"WithReadOnly","signature":"func (b *StorageOSPersistentVolumeSourceApplyConfiguration) WithReadOnly(value bool) *StorageOSPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/storageospersistentvolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *StorageOSPersistentVolumeSourceApplyConfiguration) WithReadOnly(value bool) *StorageOSPersistentVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":61,"to":67}} {"id":100022431,"name":"WithSecretRef","signature":"func (b *StorageOSPersistentVolumeSourceApplyConfiguration) WithSecretRef(value *ObjectReferenceApplyConfiguration) *StorageOSPersistentVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/storageospersistentvolumesource.go","code":"// WithSecretRef sets the SecretRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecretRef field is set to the value of the last call.\nfunc (b *StorageOSPersistentVolumeSourceApplyConfiguration) WithSecretRef(value *ObjectReferenceApplyConfiguration) *StorageOSPersistentVolumeSourceApplyConfiguration {\n\tb.SecretRef = value\n\treturn b\n}","line":{"from":69,"to":75}} {"id":100022432,"name":"StorageOSVolumeSource","signature":"func StorageOSVolumeSource() *StorageOSVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/storageosvolumesource.go","code":"// StorageOSVolumeSourceApplyConfiguration constructs an declarative configuration of the StorageOSVolumeSource type for use with\n// apply.\nfunc StorageOSVolumeSource() *StorageOSVolumeSourceApplyConfiguration {\n\treturn \u0026StorageOSVolumeSourceApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100022433,"name":"WithVolumeName","signature":"func (b *StorageOSVolumeSourceApplyConfiguration) WithVolumeName(value string) *StorageOSVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/storageosvolumesource.go","code":"// WithVolumeName sets the VolumeName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the VolumeName field is set to the value of the last call.\nfunc (b *StorageOSVolumeSourceApplyConfiguration) WithVolumeName(value string) *StorageOSVolumeSourceApplyConfiguration {\n\tb.VolumeName = \u0026value\n\treturn b\n}","line":{"from":37,"to":43}} {"id":100022434,"name":"WithVolumeNamespace","signature":"func (b *StorageOSVolumeSourceApplyConfiguration) WithVolumeNamespace(value string) *StorageOSVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/storageosvolumesource.go","code":"// WithVolumeNamespace sets the VolumeNamespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the VolumeNamespace field is set to the value of the last call.\nfunc (b *StorageOSVolumeSourceApplyConfiguration) WithVolumeNamespace(value string) *StorageOSVolumeSourceApplyConfiguration {\n\tb.VolumeNamespace = \u0026value\n\treturn b\n}","line":{"from":45,"to":51}} {"id":100022435,"name":"WithFSType","signature":"func (b *StorageOSVolumeSourceApplyConfiguration) WithFSType(value string) *StorageOSVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/storageosvolumesource.go","code":"// WithFSType sets the FSType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSType field is set to the value of the last call.\nfunc (b *StorageOSVolumeSourceApplyConfiguration) WithFSType(value string) *StorageOSVolumeSourceApplyConfiguration {\n\tb.FSType = \u0026value\n\treturn b\n}","line":{"from":53,"to":59}} {"id":100022436,"name":"WithReadOnly","signature":"func (b *StorageOSVolumeSourceApplyConfiguration) WithReadOnly(value bool) *StorageOSVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/storageosvolumesource.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *StorageOSVolumeSourceApplyConfiguration) WithReadOnly(value bool) *StorageOSVolumeSourceApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":61,"to":67}} {"id":100022437,"name":"WithSecretRef","signature":"func (b *StorageOSVolumeSourceApplyConfiguration) WithSecretRef(value *LocalObjectReferenceApplyConfiguration) *StorageOSVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/storageosvolumesource.go","code":"// WithSecretRef sets the SecretRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecretRef field is set to the value of the last call.\nfunc (b *StorageOSVolumeSourceApplyConfiguration) WithSecretRef(value *LocalObjectReferenceApplyConfiguration) *StorageOSVolumeSourceApplyConfiguration {\n\tb.SecretRef = value\n\treturn b\n}","line":{"from":69,"to":75}} {"id":100022438,"name":"Sysctl","signature":"func Sysctl() *SysctlApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/sysctl.go","code":"// SysctlApplyConfiguration constructs an declarative configuration of the Sysctl type for use with\n// apply.\nfunc Sysctl() *SysctlApplyConfiguration {\n\treturn \u0026SysctlApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100022439,"name":"WithName","signature":"func (b *SysctlApplyConfiguration) WithName(value string) *SysctlApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/sysctl.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *SysctlApplyConfiguration) WithName(value string) *SysctlApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100022440,"name":"WithValue","signature":"func (b *SysctlApplyConfiguration) WithValue(value string) *SysctlApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/sysctl.go","code":"// WithValue sets the Value field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Value field is set to the value of the last call.\nfunc (b *SysctlApplyConfiguration) WithValue(value string) *SysctlApplyConfiguration {\n\tb.Value = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100022441,"name":"Taint","signature":"func Taint() *TaintApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/taint.go","code":"// TaintApplyConfiguration constructs an declarative configuration of the Taint type for use with\n// apply.\nfunc Taint() *TaintApplyConfiguration {\n\treturn \u0026TaintApplyConfiguration{}\n}","line":{"from":35,"to":39}} {"id":100022442,"name":"WithKey","signature":"func (b *TaintApplyConfiguration) WithKey(value string) *TaintApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/taint.go","code":"// WithKey sets the Key field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Key field is set to the value of the last call.\nfunc (b *TaintApplyConfiguration) WithKey(value string) *TaintApplyConfiguration {\n\tb.Key = \u0026value\n\treturn b\n}","line":{"from":41,"to":47}} {"id":100022443,"name":"WithValue","signature":"func (b *TaintApplyConfiguration) WithValue(value string) *TaintApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/taint.go","code":"// WithValue sets the Value field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Value field is set to the value of the last call.\nfunc (b *TaintApplyConfiguration) WithValue(value string) *TaintApplyConfiguration {\n\tb.Value = \u0026value\n\treturn b\n}","line":{"from":49,"to":55}} {"id":100022444,"name":"WithEffect","signature":"func (b *TaintApplyConfiguration) WithEffect(value v1.TaintEffect) *TaintApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/taint.go","code":"// WithEffect sets the Effect field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Effect field is set to the value of the last call.\nfunc (b *TaintApplyConfiguration) WithEffect(value v1.TaintEffect) *TaintApplyConfiguration {\n\tb.Effect = \u0026value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100022445,"name":"WithTimeAdded","signature":"func (b *TaintApplyConfiguration) WithTimeAdded(value metav1.Time) *TaintApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/taint.go","code":"// WithTimeAdded sets the TimeAdded field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TimeAdded field is set to the value of the last call.\nfunc (b *TaintApplyConfiguration) WithTimeAdded(value metav1.Time) *TaintApplyConfiguration {\n\tb.TimeAdded = \u0026value\n\treturn b\n}","line":{"from":65,"to":71}} {"id":100022446,"name":"TCPSocketAction","signature":"func TCPSocketAction() *TCPSocketActionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/tcpsocketaction.go","code":"// TCPSocketActionApplyConfiguration constructs an declarative configuration of the TCPSocketAction type for use with\n// apply.\nfunc TCPSocketAction() *TCPSocketActionApplyConfiguration {\n\treturn \u0026TCPSocketActionApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100022447,"name":"WithPort","signature":"func (b *TCPSocketActionApplyConfiguration) WithPort(value intstr.IntOrString) *TCPSocketActionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/tcpsocketaction.go","code":"// WithPort sets the Port field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Port field is set to the value of the last call.\nfunc (b *TCPSocketActionApplyConfiguration) WithPort(value intstr.IntOrString) *TCPSocketActionApplyConfiguration {\n\tb.Port = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100022448,"name":"WithHost","signature":"func (b *TCPSocketActionApplyConfiguration) WithHost(value string) *TCPSocketActionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/tcpsocketaction.go","code":"// WithHost sets the Host field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Host field is set to the value of the last call.\nfunc (b *TCPSocketActionApplyConfiguration) WithHost(value string) *TCPSocketActionApplyConfiguration {\n\tb.Host = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100022449,"name":"Toleration","signature":"func Toleration() *TolerationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/toleration.go","code":"// TolerationApplyConfiguration constructs an declarative configuration of the Toleration type for use with\n// apply.\nfunc Toleration() *TolerationApplyConfiguration {\n\treturn \u0026TolerationApplyConfiguration{}\n}","line":{"from":35,"to":39}} {"id":100022450,"name":"WithKey","signature":"func (b *TolerationApplyConfiguration) WithKey(value string) *TolerationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/toleration.go","code":"// WithKey sets the Key field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Key field is set to the value of the last call.\nfunc (b *TolerationApplyConfiguration) WithKey(value string) *TolerationApplyConfiguration {\n\tb.Key = \u0026value\n\treturn b\n}","line":{"from":41,"to":47}} {"id":100022451,"name":"WithOperator","signature":"func (b *TolerationApplyConfiguration) WithOperator(value v1.TolerationOperator) *TolerationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/toleration.go","code":"// WithOperator sets the Operator field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Operator field is set to the value of the last call.\nfunc (b *TolerationApplyConfiguration) WithOperator(value v1.TolerationOperator) *TolerationApplyConfiguration {\n\tb.Operator = \u0026value\n\treturn b\n}","line":{"from":49,"to":55}} {"id":100022452,"name":"WithValue","signature":"func (b *TolerationApplyConfiguration) WithValue(value string) *TolerationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/toleration.go","code":"// WithValue sets the Value field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Value field is set to the value of the last call.\nfunc (b *TolerationApplyConfiguration) WithValue(value string) *TolerationApplyConfiguration {\n\tb.Value = \u0026value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100022453,"name":"WithEffect","signature":"func (b *TolerationApplyConfiguration) WithEffect(value v1.TaintEffect) *TolerationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/toleration.go","code":"// WithEffect sets the Effect field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Effect field is set to the value of the last call.\nfunc (b *TolerationApplyConfiguration) WithEffect(value v1.TaintEffect) *TolerationApplyConfiguration {\n\tb.Effect = \u0026value\n\treturn b\n}","line":{"from":65,"to":71}} {"id":100022454,"name":"WithTolerationSeconds","signature":"func (b *TolerationApplyConfiguration) WithTolerationSeconds(value int64) *TolerationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/toleration.go","code":"// WithTolerationSeconds sets the TolerationSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TolerationSeconds field is set to the value of the last call.\nfunc (b *TolerationApplyConfiguration) WithTolerationSeconds(value int64) *TolerationApplyConfiguration {\n\tb.TolerationSeconds = \u0026value\n\treturn b\n}","line":{"from":73,"to":79}} {"id":100022455,"name":"TopologySelectorLabelRequirement","signature":"func TopologySelectorLabelRequirement() *TopologySelectorLabelRequirementApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/topologyselectorlabelrequirement.go","code":"// TopologySelectorLabelRequirementApplyConfiguration constructs an declarative configuration of the TopologySelectorLabelRequirement type for use with\n// apply.\nfunc TopologySelectorLabelRequirement() *TopologySelectorLabelRequirementApplyConfiguration {\n\treturn \u0026TopologySelectorLabelRequirementApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100022456,"name":"WithKey","signature":"func (b *TopologySelectorLabelRequirementApplyConfiguration) WithKey(value string) *TopologySelectorLabelRequirementApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/topologyselectorlabelrequirement.go","code":"// WithKey sets the Key field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Key field is set to the value of the last call.\nfunc (b *TopologySelectorLabelRequirementApplyConfiguration) WithKey(value string) *TopologySelectorLabelRequirementApplyConfiguration {\n\tb.Key = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100022457,"name":"WithValues","signature":"func (b *TopologySelectorLabelRequirementApplyConfiguration) WithValues(values ...string) *TopologySelectorLabelRequirementApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/topologyselectorlabelrequirement.go","code":"// WithValues adds the given value to the Values field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Values field.\nfunc (b *TopologySelectorLabelRequirementApplyConfiguration) WithValues(values ...string) *TopologySelectorLabelRequirementApplyConfiguration {\n\tfor i := range values {\n\t\tb.Values = append(b.Values, values[i])\n\t}\n\treturn b\n}","line":{"from":42,"to":50}} {"id":100022458,"name":"TopologySelectorTerm","signature":"func TopologySelectorTerm() *TopologySelectorTermApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/topologyselectorterm.go","code":"// TopologySelectorTermApplyConfiguration constructs an declarative configuration of the TopologySelectorTerm type for use with\n// apply.\nfunc TopologySelectorTerm() *TopologySelectorTermApplyConfiguration {\n\treturn \u0026TopologySelectorTermApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100022459,"name":"WithMatchLabelExpressions","signature":"func (b *TopologySelectorTermApplyConfiguration) WithMatchLabelExpressions(values ...*TopologySelectorLabelRequirementApplyConfiguration) *TopologySelectorTermApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/topologyselectorterm.go","code":"// WithMatchLabelExpressions adds the given value to the MatchLabelExpressions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the MatchLabelExpressions field.\nfunc (b *TopologySelectorTermApplyConfiguration) WithMatchLabelExpressions(values ...*TopologySelectorLabelRequirementApplyConfiguration) *TopologySelectorTermApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithMatchLabelExpressions\")\n\t\t}\n\t\tb.MatchLabelExpressions = append(b.MatchLabelExpressions, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100022460,"name":"TopologySpreadConstraint","signature":"func TopologySpreadConstraint() *TopologySpreadConstraintApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/topologyspreadconstraint.go","code":"// TopologySpreadConstraintApplyConfiguration constructs an declarative configuration of the TopologySpreadConstraint type for use with\n// apply.\nfunc TopologySpreadConstraint() *TopologySpreadConstraintApplyConfiguration {\n\treturn \u0026TopologySpreadConstraintApplyConfiguration{}\n}","line":{"from":39,"to":43}} {"id":100022461,"name":"WithMaxSkew","signature":"func (b *TopologySpreadConstraintApplyConfiguration) WithMaxSkew(value int32) *TopologySpreadConstraintApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/topologyspreadconstraint.go","code":"// WithMaxSkew sets the MaxSkew field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MaxSkew field is set to the value of the last call.\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithMaxSkew(value int32) *TopologySpreadConstraintApplyConfiguration {\n\tb.MaxSkew = \u0026value\n\treturn b\n}","line":{"from":45,"to":51}} {"id":100022462,"name":"WithTopologyKey","signature":"func (b *TopologySpreadConstraintApplyConfiguration) WithTopologyKey(value string) *TopologySpreadConstraintApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/topologyspreadconstraint.go","code":"// WithTopologyKey sets the TopologyKey field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TopologyKey field is set to the value of the last call.\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithTopologyKey(value string) *TopologySpreadConstraintApplyConfiguration {\n\tb.TopologyKey = \u0026value\n\treturn b\n}","line":{"from":53,"to":59}} {"id":100022463,"name":"WithWhenUnsatisfiable","signature":"func (b *TopologySpreadConstraintApplyConfiguration) WithWhenUnsatisfiable(value v1.UnsatisfiableConstraintAction) *TopologySpreadConstraintApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/topologyspreadconstraint.go","code":"// WithWhenUnsatisfiable sets the WhenUnsatisfiable field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the WhenUnsatisfiable field is set to the value of the last call.\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithWhenUnsatisfiable(value v1.UnsatisfiableConstraintAction) *TopologySpreadConstraintApplyConfiguration {\n\tb.WhenUnsatisfiable = \u0026value\n\treturn b\n}","line":{"from":61,"to":67}} {"id":100022464,"name":"WithLabelSelector","signature":"func (b *TopologySpreadConstraintApplyConfiguration) WithLabelSelector(value *metav1.LabelSelectorApplyConfiguration) *TopologySpreadConstraintApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/topologyspreadconstraint.go","code":"// WithLabelSelector sets the LabelSelector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LabelSelector field is set to the value of the last call.\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithLabelSelector(value *metav1.LabelSelectorApplyConfiguration) *TopologySpreadConstraintApplyConfiguration {\n\tb.LabelSelector = value\n\treturn b\n}","line":{"from":69,"to":75}} {"id":100022465,"name":"WithMinDomains","signature":"func (b *TopologySpreadConstraintApplyConfiguration) WithMinDomains(value int32) *TopologySpreadConstraintApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/topologyspreadconstraint.go","code":"// WithMinDomains sets the MinDomains field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MinDomains field is set to the value of the last call.\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithMinDomains(value int32) *TopologySpreadConstraintApplyConfiguration {\n\tb.MinDomains = \u0026value\n\treturn b\n}","line":{"from":77,"to":83}} {"id":100022466,"name":"WithNodeAffinityPolicy","signature":"func (b *TopologySpreadConstraintApplyConfiguration) WithNodeAffinityPolicy(value v1.NodeInclusionPolicy) *TopologySpreadConstraintApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/topologyspreadconstraint.go","code":"// WithNodeAffinityPolicy sets the NodeAffinityPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NodeAffinityPolicy field is set to the value of the last call.\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithNodeAffinityPolicy(value v1.NodeInclusionPolicy) *TopologySpreadConstraintApplyConfiguration {\n\tb.NodeAffinityPolicy = \u0026value\n\treturn b\n}","line":{"from":85,"to":91}} {"id":100022467,"name":"WithNodeTaintsPolicy","signature":"func (b *TopologySpreadConstraintApplyConfiguration) WithNodeTaintsPolicy(value v1.NodeInclusionPolicy) *TopologySpreadConstraintApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/topologyspreadconstraint.go","code":"// WithNodeTaintsPolicy sets the NodeTaintsPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NodeTaintsPolicy field is set to the value of the last call.\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithNodeTaintsPolicy(value v1.NodeInclusionPolicy) *TopologySpreadConstraintApplyConfiguration {\n\tb.NodeTaintsPolicy = \u0026value\n\treturn b\n}","line":{"from":93,"to":99}} {"id":100022468,"name":"WithMatchLabelKeys","signature":"func (b *TopologySpreadConstraintApplyConfiguration) WithMatchLabelKeys(values ...string) *TopologySpreadConstraintApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/topologyspreadconstraint.go","code":"// WithMatchLabelKeys adds the given value to the MatchLabelKeys field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the MatchLabelKeys field.\nfunc (b *TopologySpreadConstraintApplyConfiguration) WithMatchLabelKeys(values ...string) *TopologySpreadConstraintApplyConfiguration {\n\tfor i := range values {\n\t\tb.MatchLabelKeys = append(b.MatchLabelKeys, values[i])\n\t}\n\treturn b\n}","line":{"from":101,"to":109}} {"id":100022469,"name":"TypedLocalObjectReference","signature":"func TypedLocalObjectReference() *TypedLocalObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/typedlocalobjectreference.go","code":"// TypedLocalObjectReferenceApplyConfiguration constructs an declarative configuration of the TypedLocalObjectReference type for use with\n// apply.\nfunc TypedLocalObjectReference() *TypedLocalObjectReferenceApplyConfiguration {\n\treturn \u0026TypedLocalObjectReferenceApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100022470,"name":"WithAPIGroup","signature":"func (b *TypedLocalObjectReferenceApplyConfiguration) WithAPIGroup(value string) *TypedLocalObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/typedlocalobjectreference.go","code":"// WithAPIGroup sets the APIGroup field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIGroup field is set to the value of the last call.\nfunc (b *TypedLocalObjectReferenceApplyConfiguration) WithAPIGroup(value string) *TypedLocalObjectReferenceApplyConfiguration {\n\tb.APIGroup = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100022471,"name":"WithKind","signature":"func (b *TypedLocalObjectReferenceApplyConfiguration) WithKind(value string) *TypedLocalObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/typedlocalobjectreference.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *TypedLocalObjectReferenceApplyConfiguration) WithKind(value string) *TypedLocalObjectReferenceApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100022472,"name":"WithName","signature":"func (b *TypedLocalObjectReferenceApplyConfiguration) WithName(value string) *TypedLocalObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/typedlocalobjectreference.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *TypedLocalObjectReferenceApplyConfiguration) WithName(value string) *TypedLocalObjectReferenceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100022473,"name":"TypedObjectReference","signature":"func TypedObjectReference() *TypedObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/typedobjectreference.go","code":"// TypedObjectReferenceApplyConfiguration constructs an declarative configuration of the TypedObjectReference type for use with\n// apply.\nfunc TypedObjectReference() *TypedObjectReferenceApplyConfiguration {\n\treturn \u0026TypedObjectReferenceApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100022474,"name":"WithAPIGroup","signature":"func (b *TypedObjectReferenceApplyConfiguration) WithAPIGroup(value string) *TypedObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/typedobjectreference.go","code":"// WithAPIGroup sets the APIGroup field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIGroup field is set to the value of the last call.\nfunc (b *TypedObjectReferenceApplyConfiguration) WithAPIGroup(value string) *TypedObjectReferenceApplyConfiguration {\n\tb.APIGroup = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100022475,"name":"WithKind","signature":"func (b *TypedObjectReferenceApplyConfiguration) WithKind(value string) *TypedObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/typedobjectreference.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *TypedObjectReferenceApplyConfiguration) WithKind(value string) *TypedObjectReferenceApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100022476,"name":"WithName","signature":"func (b *TypedObjectReferenceApplyConfiguration) WithName(value string) *TypedObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/typedobjectreference.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *TypedObjectReferenceApplyConfiguration) WithName(value string) *TypedObjectReferenceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100022477,"name":"WithNamespace","signature":"func (b *TypedObjectReferenceApplyConfiguration) WithNamespace(value string) *TypedObjectReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/typedobjectreference.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *TypedObjectReferenceApplyConfiguration) WithNamespace(value string) *TypedObjectReferenceApplyConfiguration {\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100022478,"name":"Volume","signature":"func Volume() *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// VolumeApplyConfiguration constructs an declarative configuration of the Volume type for use with\n// apply.\nfunc Volume() *VolumeApplyConfiguration {\n\treturn \u0026VolumeApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100022479,"name":"WithName","signature":"func (b *VolumeApplyConfiguration) WithName(value string) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithName(value string) *VolumeApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100022480,"name":"WithHostPath","signature":"func (b *VolumeApplyConfiguration) WithHostPath(value *HostPathVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithHostPath sets the HostPath field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HostPath field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithHostPath(value *HostPathVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.HostPath = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100022481,"name":"WithEmptyDir","signature":"func (b *VolumeApplyConfiguration) WithEmptyDir(value *EmptyDirVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithEmptyDir sets the EmptyDir field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the EmptyDir field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithEmptyDir(value *EmptyDirVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.EmptyDir = value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100022482,"name":"WithGCEPersistentDisk","signature":"func (b *VolumeApplyConfiguration) WithGCEPersistentDisk(value *GCEPersistentDiskVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithGCEPersistentDisk sets the GCEPersistentDisk field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GCEPersistentDisk field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithGCEPersistentDisk(value *GCEPersistentDiskVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.GCEPersistentDisk = value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100022483,"name":"WithAWSElasticBlockStore","signature":"func (b *VolumeApplyConfiguration) WithAWSElasticBlockStore(value *AWSElasticBlockStoreVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithAWSElasticBlockStore sets the AWSElasticBlockStore field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AWSElasticBlockStore field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithAWSElasticBlockStore(value *AWSElasticBlockStoreVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.AWSElasticBlockStore = value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100022484,"name":"WithGitRepo","signature":"func (b *VolumeApplyConfiguration) WithGitRepo(value *GitRepoVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithGitRepo sets the GitRepo field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GitRepo field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithGitRepo(value *GitRepoVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.GitRepo = value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100022485,"name":"WithSecret","signature":"func (b *VolumeApplyConfiguration) WithSecret(value *SecretVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithSecret sets the Secret field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Secret field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithSecret(value *SecretVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.Secret = value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100022486,"name":"WithNFS","signature":"func (b *VolumeApplyConfiguration) WithNFS(value *NFSVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithNFS sets the NFS field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NFS field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithNFS(value *NFSVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.NFS = value\n\treturn b\n}","line":{"from":90,"to":96}} {"id":100022487,"name":"WithISCSI","signature":"func (b *VolumeApplyConfiguration) WithISCSI(value *ISCSIVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithISCSI sets the ISCSI field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ISCSI field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithISCSI(value *ISCSIVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.ISCSI = value\n\treturn b\n}","line":{"from":98,"to":104}} {"id":100022488,"name":"WithGlusterfs","signature":"func (b *VolumeApplyConfiguration) WithGlusterfs(value *GlusterfsVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithGlusterfs sets the Glusterfs field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Glusterfs field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithGlusterfs(value *GlusterfsVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.Glusterfs = value\n\treturn b\n}","line":{"from":106,"to":112}} {"id":100022489,"name":"WithPersistentVolumeClaim","signature":"func (b *VolumeApplyConfiguration) WithPersistentVolumeClaim(value *PersistentVolumeClaimVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithPersistentVolumeClaim sets the PersistentVolumeClaim field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PersistentVolumeClaim field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithPersistentVolumeClaim(value *PersistentVolumeClaimVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.PersistentVolumeClaim = value\n\treturn b\n}","line":{"from":114,"to":120}} {"id":100022490,"name":"WithRBD","signature":"func (b *VolumeApplyConfiguration) WithRBD(value *RBDVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithRBD sets the RBD field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RBD field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithRBD(value *RBDVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.RBD = value\n\treturn b\n}","line":{"from":122,"to":128}} {"id":100022491,"name":"WithFlexVolume","signature":"func (b *VolumeApplyConfiguration) WithFlexVolume(value *FlexVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithFlexVolume sets the FlexVolume field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FlexVolume field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithFlexVolume(value *FlexVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.FlexVolume = value\n\treturn b\n}","line":{"from":130,"to":136}} {"id":100022492,"name":"WithCinder","signature":"func (b *VolumeApplyConfiguration) WithCinder(value *CinderVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithCinder sets the Cinder field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Cinder field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithCinder(value *CinderVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.Cinder = value\n\treturn b\n}","line":{"from":138,"to":144}} {"id":100022493,"name":"WithCephFS","signature":"func (b *VolumeApplyConfiguration) WithCephFS(value *CephFSVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithCephFS sets the CephFS field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CephFS field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithCephFS(value *CephFSVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.CephFS = value\n\treturn b\n}","line":{"from":146,"to":152}} {"id":100022494,"name":"WithFlocker","signature":"func (b *VolumeApplyConfiguration) WithFlocker(value *FlockerVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithFlocker sets the Flocker field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Flocker field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithFlocker(value *FlockerVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.Flocker = value\n\treturn b\n}","line":{"from":154,"to":160}} {"id":100022495,"name":"WithDownwardAPI","signature":"func (b *VolumeApplyConfiguration) WithDownwardAPI(value *DownwardAPIVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithDownwardAPI sets the DownwardAPI field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DownwardAPI field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithDownwardAPI(value *DownwardAPIVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.DownwardAPI = value\n\treturn b\n}","line":{"from":162,"to":168}} {"id":100022496,"name":"WithFC","signature":"func (b *VolumeApplyConfiguration) WithFC(value *FCVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithFC sets the FC field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FC field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithFC(value *FCVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.FC = value\n\treturn b\n}","line":{"from":170,"to":176}} {"id":100022497,"name":"WithAzureFile","signature":"func (b *VolumeApplyConfiguration) WithAzureFile(value *AzureFileVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithAzureFile sets the AzureFile field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AzureFile field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithAzureFile(value *AzureFileVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.AzureFile = value\n\treturn b\n}","line":{"from":178,"to":184}} {"id":100022498,"name":"WithConfigMap","signature":"func (b *VolumeApplyConfiguration) WithConfigMap(value *ConfigMapVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithConfigMap sets the ConfigMap field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ConfigMap field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithConfigMap(value *ConfigMapVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.ConfigMap = value\n\treturn b\n}","line":{"from":186,"to":192}} {"id":100022499,"name":"WithVsphereVolume","signature":"func (b *VolumeApplyConfiguration) WithVsphereVolume(value *VsphereVirtualDiskVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithVsphereVolume sets the VsphereVolume field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the VsphereVolume field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithVsphereVolume(value *VsphereVirtualDiskVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.VsphereVolume = value\n\treturn b\n}","line":{"from":194,"to":200}} {"id":100022500,"name":"WithQuobyte","signature":"func (b *VolumeApplyConfiguration) WithQuobyte(value *QuobyteVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithQuobyte sets the Quobyte field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Quobyte field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithQuobyte(value *QuobyteVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.Quobyte = value\n\treturn b\n}","line":{"from":202,"to":208}} {"id":100022501,"name":"WithAzureDisk","signature":"func (b *VolumeApplyConfiguration) WithAzureDisk(value *AzureDiskVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithAzureDisk sets the AzureDisk field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AzureDisk field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithAzureDisk(value *AzureDiskVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.AzureDisk = value\n\treturn b\n}","line":{"from":210,"to":216}} {"id":100022502,"name":"WithPhotonPersistentDisk","signature":"func (b *VolumeApplyConfiguration) WithPhotonPersistentDisk(value *PhotonPersistentDiskVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithPhotonPersistentDisk sets the PhotonPersistentDisk field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PhotonPersistentDisk field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithPhotonPersistentDisk(value *PhotonPersistentDiskVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.PhotonPersistentDisk = value\n\treturn b\n}","line":{"from":218,"to":224}} {"id":100022503,"name":"WithProjected","signature":"func (b *VolumeApplyConfiguration) WithProjected(value *ProjectedVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithProjected sets the Projected field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Projected field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithProjected(value *ProjectedVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.Projected = value\n\treturn b\n}","line":{"from":226,"to":232}} {"id":100022504,"name":"WithPortworxVolume","signature":"func (b *VolumeApplyConfiguration) WithPortworxVolume(value *PortworxVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithPortworxVolume sets the PortworxVolume field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PortworxVolume field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithPortworxVolume(value *PortworxVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.PortworxVolume = value\n\treturn b\n}","line":{"from":234,"to":240}} {"id":100022505,"name":"WithScaleIO","signature":"func (b *VolumeApplyConfiguration) WithScaleIO(value *ScaleIOVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithScaleIO sets the ScaleIO field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ScaleIO field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithScaleIO(value *ScaleIOVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.ScaleIO = value\n\treturn b\n}","line":{"from":242,"to":248}} {"id":100022506,"name":"WithStorageOS","signature":"func (b *VolumeApplyConfiguration) WithStorageOS(value *StorageOSVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithStorageOS sets the StorageOS field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StorageOS field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithStorageOS(value *StorageOSVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.StorageOS = value\n\treturn b\n}","line":{"from":250,"to":256}} {"id":100022507,"name":"WithCSI","signature":"func (b *VolumeApplyConfiguration) WithCSI(value *CSIVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithCSI sets the CSI field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CSI field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithCSI(value *CSIVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.CSI = value\n\treturn b\n}","line":{"from":258,"to":264}} {"id":100022508,"name":"WithEphemeral","signature":"func (b *VolumeApplyConfiguration) WithEphemeral(value *EphemeralVolumeSourceApplyConfiguration) *VolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volume.go","code":"// WithEphemeral sets the Ephemeral field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Ephemeral field is set to the value of the last call.\nfunc (b *VolumeApplyConfiguration) WithEphemeral(value *EphemeralVolumeSourceApplyConfiguration) *VolumeApplyConfiguration {\n\tb.Ephemeral = value\n\treturn b\n}","line":{"from":266,"to":272}} {"id":100022509,"name":"VolumeDevice","signature":"func VolumeDevice() *VolumeDeviceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumedevice.go","code":"// VolumeDeviceApplyConfiguration constructs an declarative configuration of the VolumeDevice type for use with\n// apply.\nfunc VolumeDevice() *VolumeDeviceApplyConfiguration {\n\treturn \u0026VolumeDeviceApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100022510,"name":"WithName","signature":"func (b *VolumeDeviceApplyConfiguration) WithName(value string) *VolumeDeviceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumedevice.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *VolumeDeviceApplyConfiguration) WithName(value string) *VolumeDeviceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100022511,"name":"WithDevicePath","signature":"func (b *VolumeDeviceApplyConfiguration) WithDevicePath(value string) *VolumeDeviceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumedevice.go","code":"// WithDevicePath sets the DevicePath field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DevicePath field is set to the value of the last call.\nfunc (b *VolumeDeviceApplyConfiguration) WithDevicePath(value string) *VolumeDeviceApplyConfiguration {\n\tb.DevicePath = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100022512,"name":"VolumeMount","signature":"func VolumeMount() *VolumeMountApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumemount.go","code":"// VolumeMountApplyConfiguration constructs an declarative configuration of the VolumeMount type for use with\n// apply.\nfunc VolumeMount() *VolumeMountApplyConfiguration {\n\treturn \u0026VolumeMountApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100022513,"name":"WithName","signature":"func (b *VolumeMountApplyConfiguration) WithName(value string) *VolumeMountApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumemount.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *VolumeMountApplyConfiguration) WithName(value string) *VolumeMountApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100022514,"name":"WithReadOnly","signature":"func (b *VolumeMountApplyConfiguration) WithReadOnly(value bool) *VolumeMountApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumemount.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *VolumeMountApplyConfiguration) WithReadOnly(value bool) *VolumeMountApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100022515,"name":"WithMountPath","signature":"func (b *VolumeMountApplyConfiguration) WithMountPath(value string) *VolumeMountApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumemount.go","code":"// WithMountPath sets the MountPath field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MountPath field is set to the value of the last call.\nfunc (b *VolumeMountApplyConfiguration) WithMountPath(value string) *VolumeMountApplyConfiguration {\n\tb.MountPath = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100022516,"name":"WithSubPath","signature":"func (b *VolumeMountApplyConfiguration) WithSubPath(value string) *VolumeMountApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumemount.go","code":"// WithSubPath sets the SubPath field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SubPath field is set to the value of the last call.\nfunc (b *VolumeMountApplyConfiguration) WithSubPath(value string) *VolumeMountApplyConfiguration {\n\tb.SubPath = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100022517,"name":"WithMountPropagation","signature":"func (b *VolumeMountApplyConfiguration) WithMountPropagation(value v1.MountPropagationMode) *VolumeMountApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumemount.go","code":"// WithMountPropagation sets the MountPropagation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MountPropagation field is set to the value of the last call.\nfunc (b *VolumeMountApplyConfiguration) WithMountPropagation(value v1.MountPropagationMode) *VolumeMountApplyConfiguration {\n\tb.MountPropagation = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100022518,"name":"WithSubPathExpr","signature":"func (b *VolumeMountApplyConfiguration) WithSubPathExpr(value string) *VolumeMountApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumemount.go","code":"// WithSubPathExpr sets the SubPathExpr field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SubPathExpr field is set to the value of the last call.\nfunc (b *VolumeMountApplyConfiguration) WithSubPathExpr(value string) *VolumeMountApplyConfiguration {\n\tb.SubPathExpr = \u0026value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100022519,"name":"VolumeNodeAffinity","signature":"func VolumeNodeAffinity() *VolumeNodeAffinityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumenodeaffinity.go","code":"// VolumeNodeAffinityApplyConfiguration constructs an declarative configuration of the VolumeNodeAffinity type for use with\n// apply.\nfunc VolumeNodeAffinity() *VolumeNodeAffinityApplyConfiguration {\n\treturn \u0026VolumeNodeAffinityApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100022520,"name":"WithRequired","signature":"func (b *VolumeNodeAffinityApplyConfiguration) WithRequired(value *NodeSelectorApplyConfiguration) *VolumeNodeAffinityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumenodeaffinity.go","code":"// WithRequired sets the Required field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Required field is set to the value of the last call.\nfunc (b *VolumeNodeAffinityApplyConfiguration) WithRequired(value *NodeSelectorApplyConfiguration) *VolumeNodeAffinityApplyConfiguration {\n\tb.Required = value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100022521,"name":"VolumeProjection","signature":"func VolumeProjection() *VolumeProjectionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumeprojection.go","code":"// VolumeProjectionApplyConfiguration constructs an declarative configuration of the VolumeProjection type for use with\n// apply.\nfunc VolumeProjection() *VolumeProjectionApplyConfiguration {\n\treturn \u0026VolumeProjectionApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100022522,"name":"WithSecret","signature":"func (b *VolumeProjectionApplyConfiguration) WithSecret(value *SecretProjectionApplyConfiguration) *VolumeProjectionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumeprojection.go","code":"// WithSecret sets the Secret field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Secret field is set to the value of the last call.\nfunc (b *VolumeProjectionApplyConfiguration) WithSecret(value *SecretProjectionApplyConfiguration) *VolumeProjectionApplyConfiguration {\n\tb.Secret = value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100022523,"name":"WithDownwardAPI","signature":"func (b *VolumeProjectionApplyConfiguration) WithDownwardAPI(value *DownwardAPIProjectionApplyConfiguration) *VolumeProjectionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumeprojection.go","code":"// WithDownwardAPI sets the DownwardAPI field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DownwardAPI field is set to the value of the last call.\nfunc (b *VolumeProjectionApplyConfiguration) WithDownwardAPI(value *DownwardAPIProjectionApplyConfiguration) *VolumeProjectionApplyConfiguration {\n\tb.DownwardAPI = value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100022524,"name":"WithConfigMap","signature":"func (b *VolumeProjectionApplyConfiguration) WithConfigMap(value *ConfigMapProjectionApplyConfiguration) *VolumeProjectionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumeprojection.go","code":"// WithConfigMap sets the ConfigMap field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ConfigMap field is set to the value of the last call.\nfunc (b *VolumeProjectionApplyConfiguration) WithConfigMap(value *ConfigMapProjectionApplyConfiguration) *VolumeProjectionApplyConfiguration {\n\tb.ConfigMap = value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100022525,"name":"WithServiceAccountToken","signature":"func (b *VolumeProjectionApplyConfiguration) WithServiceAccountToken(value *ServiceAccountTokenProjectionApplyConfiguration) *VolumeProjectionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumeprojection.go","code":"// WithServiceAccountToken sets the ServiceAccountToken field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ServiceAccountToken field is set to the value of the last call.\nfunc (b *VolumeProjectionApplyConfiguration) WithServiceAccountToken(value *ServiceAccountTokenProjectionApplyConfiguration) *VolumeProjectionApplyConfiguration {\n\tb.ServiceAccountToken = value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100022526,"name":"VolumeSource","signature":"func VolumeSource() *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// VolumeSourceApplyConfiguration constructs an declarative configuration of the VolumeSource type for use with\n// apply.\nfunc VolumeSource() *VolumeSourceApplyConfiguration {\n\treturn \u0026VolumeSourceApplyConfiguration{}\n}","line":{"from":55,"to":59}} {"id":100022527,"name":"WithHostPath","signature":"func (b *VolumeSourceApplyConfiguration) WithHostPath(value *HostPathVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithHostPath sets the HostPath field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HostPath field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithHostPath(value *HostPathVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.HostPath = value\n\treturn b\n}","line":{"from":61,"to":67}} {"id":100022528,"name":"WithEmptyDir","signature":"func (b *VolumeSourceApplyConfiguration) WithEmptyDir(value *EmptyDirVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithEmptyDir sets the EmptyDir field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the EmptyDir field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithEmptyDir(value *EmptyDirVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.EmptyDir = value\n\treturn b\n}","line":{"from":69,"to":75}} {"id":100022529,"name":"WithGCEPersistentDisk","signature":"func (b *VolumeSourceApplyConfiguration) WithGCEPersistentDisk(value *GCEPersistentDiskVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithGCEPersistentDisk sets the GCEPersistentDisk field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GCEPersistentDisk field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithGCEPersistentDisk(value *GCEPersistentDiskVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.GCEPersistentDisk = value\n\treturn b\n}","line":{"from":77,"to":83}} {"id":100022530,"name":"WithAWSElasticBlockStore","signature":"func (b *VolumeSourceApplyConfiguration) WithAWSElasticBlockStore(value *AWSElasticBlockStoreVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithAWSElasticBlockStore sets the AWSElasticBlockStore field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AWSElasticBlockStore field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithAWSElasticBlockStore(value *AWSElasticBlockStoreVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.AWSElasticBlockStore = value\n\treturn b\n}","line":{"from":85,"to":91}} {"id":100022531,"name":"WithGitRepo","signature":"func (b *VolumeSourceApplyConfiguration) WithGitRepo(value *GitRepoVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithGitRepo sets the GitRepo field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GitRepo field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithGitRepo(value *GitRepoVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.GitRepo = value\n\treturn b\n}","line":{"from":93,"to":99}} {"id":100022532,"name":"WithSecret","signature":"func (b *VolumeSourceApplyConfiguration) WithSecret(value *SecretVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithSecret sets the Secret field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Secret field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithSecret(value *SecretVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.Secret = value\n\treturn b\n}","line":{"from":101,"to":107}} {"id":100022533,"name":"WithNFS","signature":"func (b *VolumeSourceApplyConfiguration) WithNFS(value *NFSVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithNFS sets the NFS field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NFS field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithNFS(value *NFSVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.NFS = value\n\treturn b\n}","line":{"from":109,"to":115}} {"id":100022534,"name":"WithISCSI","signature":"func (b *VolumeSourceApplyConfiguration) WithISCSI(value *ISCSIVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithISCSI sets the ISCSI field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ISCSI field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithISCSI(value *ISCSIVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.ISCSI = value\n\treturn b\n}","line":{"from":117,"to":123}} {"id":100022535,"name":"WithGlusterfs","signature":"func (b *VolumeSourceApplyConfiguration) WithGlusterfs(value *GlusterfsVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithGlusterfs sets the Glusterfs field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Glusterfs field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithGlusterfs(value *GlusterfsVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.Glusterfs = value\n\treturn b\n}","line":{"from":125,"to":131}} {"id":100022536,"name":"WithPersistentVolumeClaim","signature":"func (b *VolumeSourceApplyConfiguration) WithPersistentVolumeClaim(value *PersistentVolumeClaimVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithPersistentVolumeClaim sets the PersistentVolumeClaim field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PersistentVolumeClaim field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithPersistentVolumeClaim(value *PersistentVolumeClaimVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.PersistentVolumeClaim = value\n\treturn b\n}","line":{"from":133,"to":139}} {"id":100022537,"name":"WithRBD","signature":"func (b *VolumeSourceApplyConfiguration) WithRBD(value *RBDVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithRBD sets the RBD field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RBD field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithRBD(value *RBDVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.RBD = value\n\treturn b\n}","line":{"from":141,"to":147}} {"id":100022538,"name":"WithFlexVolume","signature":"func (b *VolumeSourceApplyConfiguration) WithFlexVolume(value *FlexVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithFlexVolume sets the FlexVolume field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FlexVolume field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithFlexVolume(value *FlexVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.FlexVolume = value\n\treturn b\n}","line":{"from":149,"to":155}} {"id":100022539,"name":"WithCinder","signature":"func (b *VolumeSourceApplyConfiguration) WithCinder(value *CinderVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithCinder sets the Cinder field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Cinder field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithCinder(value *CinderVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.Cinder = value\n\treturn b\n}","line":{"from":157,"to":163}} {"id":100022540,"name":"WithCephFS","signature":"func (b *VolumeSourceApplyConfiguration) WithCephFS(value *CephFSVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithCephFS sets the CephFS field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CephFS field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithCephFS(value *CephFSVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.CephFS = value\n\treturn b\n}","line":{"from":165,"to":171}} {"id":100022541,"name":"WithFlocker","signature":"func (b *VolumeSourceApplyConfiguration) WithFlocker(value *FlockerVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithFlocker sets the Flocker field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Flocker field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithFlocker(value *FlockerVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.Flocker = value\n\treturn b\n}","line":{"from":173,"to":179}} {"id":100022542,"name":"WithDownwardAPI","signature":"func (b *VolumeSourceApplyConfiguration) WithDownwardAPI(value *DownwardAPIVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithDownwardAPI sets the DownwardAPI field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DownwardAPI field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithDownwardAPI(value *DownwardAPIVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.DownwardAPI = value\n\treturn b\n}","line":{"from":181,"to":187}} {"id":100022543,"name":"WithFC","signature":"func (b *VolumeSourceApplyConfiguration) WithFC(value *FCVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithFC sets the FC field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FC field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithFC(value *FCVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.FC = value\n\treturn b\n}","line":{"from":189,"to":195}} {"id":100022544,"name":"WithAzureFile","signature":"func (b *VolumeSourceApplyConfiguration) WithAzureFile(value *AzureFileVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithAzureFile sets the AzureFile field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AzureFile field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithAzureFile(value *AzureFileVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.AzureFile = value\n\treturn b\n}","line":{"from":197,"to":203}} {"id":100022545,"name":"WithConfigMap","signature":"func (b *VolumeSourceApplyConfiguration) WithConfigMap(value *ConfigMapVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithConfigMap sets the ConfigMap field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ConfigMap field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithConfigMap(value *ConfigMapVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.ConfigMap = value\n\treturn b\n}","line":{"from":205,"to":211}} {"id":100022546,"name":"WithVsphereVolume","signature":"func (b *VolumeSourceApplyConfiguration) WithVsphereVolume(value *VsphereVirtualDiskVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithVsphereVolume sets the VsphereVolume field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the VsphereVolume field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithVsphereVolume(value *VsphereVirtualDiskVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.VsphereVolume = value\n\treturn b\n}","line":{"from":213,"to":219}} {"id":100022547,"name":"WithQuobyte","signature":"func (b *VolumeSourceApplyConfiguration) WithQuobyte(value *QuobyteVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithQuobyte sets the Quobyte field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Quobyte field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithQuobyte(value *QuobyteVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.Quobyte = value\n\treturn b\n}","line":{"from":221,"to":227}} {"id":100022548,"name":"WithAzureDisk","signature":"func (b *VolumeSourceApplyConfiguration) WithAzureDisk(value *AzureDiskVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithAzureDisk sets the AzureDisk field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AzureDisk field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithAzureDisk(value *AzureDiskVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.AzureDisk = value\n\treturn b\n}","line":{"from":229,"to":235}} {"id":100022549,"name":"WithPhotonPersistentDisk","signature":"func (b *VolumeSourceApplyConfiguration) WithPhotonPersistentDisk(value *PhotonPersistentDiskVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithPhotonPersistentDisk sets the PhotonPersistentDisk field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PhotonPersistentDisk field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithPhotonPersistentDisk(value *PhotonPersistentDiskVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.PhotonPersistentDisk = value\n\treturn b\n}","line":{"from":237,"to":243}} {"id":100022550,"name":"WithProjected","signature":"func (b *VolumeSourceApplyConfiguration) WithProjected(value *ProjectedVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithProjected sets the Projected field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Projected field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithProjected(value *ProjectedVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.Projected = value\n\treturn b\n}","line":{"from":245,"to":251}} {"id":100022551,"name":"WithPortworxVolume","signature":"func (b *VolumeSourceApplyConfiguration) WithPortworxVolume(value *PortworxVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithPortworxVolume sets the PortworxVolume field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PortworxVolume field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithPortworxVolume(value *PortworxVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.PortworxVolume = value\n\treturn b\n}","line":{"from":253,"to":259}} {"id":100022552,"name":"WithScaleIO","signature":"func (b *VolumeSourceApplyConfiguration) WithScaleIO(value *ScaleIOVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithScaleIO sets the ScaleIO field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ScaleIO field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithScaleIO(value *ScaleIOVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.ScaleIO = value\n\treturn b\n}","line":{"from":261,"to":267}} {"id":100022553,"name":"WithStorageOS","signature":"func (b *VolumeSourceApplyConfiguration) WithStorageOS(value *StorageOSVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithStorageOS sets the StorageOS field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StorageOS field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithStorageOS(value *StorageOSVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.StorageOS = value\n\treturn b\n}","line":{"from":269,"to":275}} {"id":100022554,"name":"WithCSI","signature":"func (b *VolumeSourceApplyConfiguration) WithCSI(value *CSIVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithCSI sets the CSI field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CSI field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithCSI(value *CSIVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.CSI = value\n\treturn b\n}","line":{"from":277,"to":283}} {"id":100022555,"name":"WithEphemeral","signature":"func (b *VolumeSourceApplyConfiguration) WithEphemeral(value *EphemeralVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/volumesource.go","code":"// WithEphemeral sets the Ephemeral field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Ephemeral field is set to the value of the last call.\nfunc (b *VolumeSourceApplyConfiguration) WithEphemeral(value *EphemeralVolumeSourceApplyConfiguration) *VolumeSourceApplyConfiguration {\n\tb.Ephemeral = value\n\treturn b\n}","line":{"from":285,"to":291}} {"id":100022556,"name":"VsphereVirtualDiskVolumeSource","signature":"func VsphereVirtualDiskVolumeSource() *VsphereVirtualDiskVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/vspherevirtualdiskvolumesource.go","code":"// VsphereVirtualDiskVolumeSourceApplyConfiguration constructs an declarative configuration of the VsphereVirtualDiskVolumeSource type for use with\n// apply.\nfunc VsphereVirtualDiskVolumeSource() *VsphereVirtualDiskVolumeSourceApplyConfiguration {\n\treturn \u0026VsphereVirtualDiskVolumeSourceApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100022557,"name":"WithVolumePath","signature":"func (b *VsphereVirtualDiskVolumeSourceApplyConfiguration) WithVolumePath(value string) *VsphereVirtualDiskVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/vspherevirtualdiskvolumesource.go","code":"// WithVolumePath sets the VolumePath field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the VolumePath field is set to the value of the last call.\nfunc (b *VsphereVirtualDiskVolumeSourceApplyConfiguration) WithVolumePath(value string) *VsphereVirtualDiskVolumeSourceApplyConfiguration {\n\tb.VolumePath = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100022558,"name":"WithFSType","signature":"func (b *VsphereVirtualDiskVolumeSourceApplyConfiguration) WithFSType(value string) *VsphereVirtualDiskVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/vspherevirtualdiskvolumesource.go","code":"// WithFSType sets the FSType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSType field is set to the value of the last call.\nfunc (b *VsphereVirtualDiskVolumeSourceApplyConfiguration) WithFSType(value string) *VsphereVirtualDiskVolumeSourceApplyConfiguration {\n\tb.FSType = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100022559,"name":"WithStoragePolicyName","signature":"func (b *VsphereVirtualDiskVolumeSourceApplyConfiguration) WithStoragePolicyName(value string) *VsphereVirtualDiskVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/vspherevirtualdiskvolumesource.go","code":"// WithStoragePolicyName sets the StoragePolicyName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StoragePolicyName field is set to the value of the last call.\nfunc (b *VsphereVirtualDiskVolumeSourceApplyConfiguration) WithStoragePolicyName(value string) *VsphereVirtualDiskVolumeSourceApplyConfiguration {\n\tb.StoragePolicyName = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100022560,"name":"WithStoragePolicyID","signature":"func (b *VsphereVirtualDiskVolumeSourceApplyConfiguration) WithStoragePolicyID(value string) *VsphereVirtualDiskVolumeSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/vspherevirtualdiskvolumesource.go","code":"// WithStoragePolicyID sets the StoragePolicyID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StoragePolicyID field is set to the value of the last call.\nfunc (b *VsphereVirtualDiskVolumeSourceApplyConfiguration) WithStoragePolicyID(value string) *VsphereVirtualDiskVolumeSourceApplyConfiguration {\n\tb.StoragePolicyID = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100022561,"name":"WeightedPodAffinityTerm","signature":"func WeightedPodAffinityTerm() *WeightedPodAffinityTermApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/weightedpodaffinityterm.go","code":"// WeightedPodAffinityTermApplyConfiguration constructs an declarative configuration of the WeightedPodAffinityTerm type for use with\n// apply.\nfunc WeightedPodAffinityTerm() *WeightedPodAffinityTermApplyConfiguration {\n\treturn \u0026WeightedPodAffinityTermApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100022562,"name":"WithWeight","signature":"func (b *WeightedPodAffinityTermApplyConfiguration) WithWeight(value int32) *WeightedPodAffinityTermApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/weightedpodaffinityterm.go","code":"// WithWeight sets the Weight field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Weight field is set to the value of the last call.\nfunc (b *WeightedPodAffinityTermApplyConfiguration) WithWeight(value int32) *WeightedPodAffinityTermApplyConfiguration {\n\tb.Weight = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100022563,"name":"WithPodAffinityTerm","signature":"func (b *WeightedPodAffinityTermApplyConfiguration) WithPodAffinityTerm(value *PodAffinityTermApplyConfiguration) *WeightedPodAffinityTermApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/weightedpodaffinityterm.go","code":"// WithPodAffinityTerm sets the PodAffinityTerm field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PodAffinityTerm field is set to the value of the last call.\nfunc (b *WeightedPodAffinityTermApplyConfiguration) WithPodAffinityTerm(value *PodAffinityTermApplyConfiguration) *WeightedPodAffinityTermApplyConfiguration {\n\tb.PodAffinityTerm = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100022564,"name":"WindowsSecurityContextOptions","signature":"func WindowsSecurityContextOptions() *WindowsSecurityContextOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/windowssecuritycontextoptions.go","code":"// WindowsSecurityContextOptionsApplyConfiguration constructs an declarative configuration of the WindowsSecurityContextOptions type for use with\n// apply.\nfunc WindowsSecurityContextOptions() *WindowsSecurityContextOptionsApplyConfiguration {\n\treturn \u0026WindowsSecurityContextOptionsApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100022565,"name":"WithGMSACredentialSpecName","signature":"func (b *WindowsSecurityContextOptionsApplyConfiguration) WithGMSACredentialSpecName(value string) *WindowsSecurityContextOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/windowssecuritycontextoptions.go","code":"// WithGMSACredentialSpecName sets the GMSACredentialSpecName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GMSACredentialSpecName field is set to the value of the last call.\nfunc (b *WindowsSecurityContextOptionsApplyConfiguration) WithGMSACredentialSpecName(value string) *WindowsSecurityContextOptionsApplyConfiguration {\n\tb.GMSACredentialSpecName = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100022566,"name":"WithGMSACredentialSpec","signature":"func (b *WindowsSecurityContextOptionsApplyConfiguration) WithGMSACredentialSpec(value string) *WindowsSecurityContextOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/windowssecuritycontextoptions.go","code":"// WithGMSACredentialSpec sets the GMSACredentialSpec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GMSACredentialSpec field is set to the value of the last call.\nfunc (b *WindowsSecurityContextOptionsApplyConfiguration) WithGMSACredentialSpec(value string) *WindowsSecurityContextOptionsApplyConfiguration {\n\tb.GMSACredentialSpec = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100022567,"name":"WithRunAsUserName","signature":"func (b *WindowsSecurityContextOptionsApplyConfiguration) WithRunAsUserName(value string) *WindowsSecurityContextOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/windowssecuritycontextoptions.go","code":"// WithRunAsUserName sets the RunAsUserName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RunAsUserName field is set to the value of the last call.\nfunc (b *WindowsSecurityContextOptionsApplyConfiguration) WithRunAsUserName(value string) *WindowsSecurityContextOptionsApplyConfiguration {\n\tb.RunAsUserName = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100022568,"name":"WithHostProcess","signature":"func (b *WindowsSecurityContextOptionsApplyConfiguration) WithHostProcess(value bool) *WindowsSecurityContextOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/core/v1/windowssecuritycontextoptions.go","code":"// WithHostProcess sets the HostProcess field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HostProcess field is set to the value of the last call.\nfunc (b *WindowsSecurityContextOptionsApplyConfiguration) WithHostProcess(value bool) *WindowsSecurityContextOptionsApplyConfiguration {\n\tb.HostProcess = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100022569,"name":"Endpoint","signature":"func Endpoint() *EndpointApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpoint.go","code":"// EndpointApplyConfiguration constructs an declarative configuration of the Endpoint type for use with\n// apply.\nfunc Endpoint() *EndpointApplyConfiguration {\n\treturn \u0026EndpointApplyConfiguration{}\n}","line":{"from":38,"to":42}} {"id":100022570,"name":"WithAddresses","signature":"func (b *EndpointApplyConfiguration) WithAddresses(values ...string) *EndpointApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpoint.go","code":"// WithAddresses adds the given value to the Addresses field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Addresses field.\nfunc (b *EndpointApplyConfiguration) WithAddresses(values ...string) *EndpointApplyConfiguration {\n\tfor i := range values {\n\t\tb.Addresses = append(b.Addresses, values[i])\n\t}\n\treturn b\n}","line":{"from":44,"to":52}} {"id":100022571,"name":"WithConditions","signature":"func (b *EndpointApplyConfiguration) WithConditions(value *EndpointConditionsApplyConfiguration) *EndpointApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpoint.go","code":"// WithConditions sets the Conditions field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Conditions field is set to the value of the last call.\nfunc (b *EndpointApplyConfiguration) WithConditions(value *EndpointConditionsApplyConfiguration) *EndpointApplyConfiguration {\n\tb.Conditions = value\n\treturn b\n}","line":{"from":54,"to":60}} {"id":100022572,"name":"WithHostname","signature":"func (b *EndpointApplyConfiguration) WithHostname(value string) *EndpointApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpoint.go","code":"// WithHostname sets the Hostname field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Hostname field is set to the value of the last call.\nfunc (b *EndpointApplyConfiguration) WithHostname(value string) *EndpointApplyConfiguration {\n\tb.Hostname = \u0026value\n\treturn b\n}","line":{"from":62,"to":68}} {"id":100022573,"name":"WithTargetRef","signature":"func (b *EndpointApplyConfiguration) WithTargetRef(value *corev1.ObjectReferenceApplyConfiguration) *EndpointApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpoint.go","code":"// WithTargetRef sets the TargetRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TargetRef field is set to the value of the last call.\nfunc (b *EndpointApplyConfiguration) WithTargetRef(value *corev1.ObjectReferenceApplyConfiguration) *EndpointApplyConfiguration {\n\tb.TargetRef = value\n\treturn b\n}","line":{"from":70,"to":76}} {"id":100022574,"name":"WithDeprecatedTopology","signature":"func (b *EndpointApplyConfiguration) WithDeprecatedTopology(entries map[string]string) *EndpointApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpoint.go","code":"// WithDeprecatedTopology puts the entries into the DeprecatedTopology field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the DeprecatedTopology field,\n// overwriting an existing map entries in DeprecatedTopology field with the same key.\nfunc (b *EndpointApplyConfiguration) WithDeprecatedTopology(entries map[string]string) *EndpointApplyConfiguration {\n\tif b.DeprecatedTopology == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.DeprecatedTopology = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.DeprecatedTopology[k] = v\n\t}\n\treturn b\n}","line":{"from":78,"to":90}} {"id":100022575,"name":"WithNodeName","signature":"func (b *EndpointApplyConfiguration) WithNodeName(value string) *EndpointApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpoint.go","code":"// WithNodeName sets the NodeName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NodeName field is set to the value of the last call.\nfunc (b *EndpointApplyConfiguration) WithNodeName(value string) *EndpointApplyConfiguration {\n\tb.NodeName = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100022576,"name":"WithZone","signature":"func (b *EndpointApplyConfiguration) WithZone(value string) *EndpointApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpoint.go","code":"// WithZone sets the Zone field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Zone field is set to the value of the last call.\nfunc (b *EndpointApplyConfiguration) WithZone(value string) *EndpointApplyConfiguration {\n\tb.Zone = \u0026value\n\treturn b\n}","line":{"from":100,"to":106}} {"id":100022577,"name":"WithHints","signature":"func (b *EndpointApplyConfiguration) WithHints(value *EndpointHintsApplyConfiguration) *EndpointApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpoint.go","code":"// WithHints sets the Hints field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Hints field is set to the value of the last call.\nfunc (b *EndpointApplyConfiguration) WithHints(value *EndpointHintsApplyConfiguration) *EndpointApplyConfiguration {\n\tb.Hints = value\n\treturn b\n}","line":{"from":108,"to":114}} {"id":100022578,"name":"EndpointConditions","signature":"func EndpointConditions() *EndpointConditionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointconditions.go","code":"// EndpointConditionsApplyConfiguration constructs an declarative configuration of the EndpointConditions type for use with\n// apply.\nfunc EndpointConditions() *EndpointConditionsApplyConfiguration {\n\treturn \u0026EndpointConditionsApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100022579,"name":"WithReady","signature":"func (b *EndpointConditionsApplyConfiguration) WithReady(value bool) *EndpointConditionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointconditions.go","code":"// WithReady sets the Ready field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Ready field is set to the value of the last call.\nfunc (b *EndpointConditionsApplyConfiguration) WithReady(value bool) *EndpointConditionsApplyConfiguration {\n\tb.Ready = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100022580,"name":"WithServing","signature":"func (b *EndpointConditionsApplyConfiguration) WithServing(value bool) *EndpointConditionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointconditions.go","code":"// WithServing sets the Serving field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Serving field is set to the value of the last call.\nfunc (b *EndpointConditionsApplyConfiguration) WithServing(value bool) *EndpointConditionsApplyConfiguration {\n\tb.Serving = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100022581,"name":"WithTerminating","signature":"func (b *EndpointConditionsApplyConfiguration) WithTerminating(value bool) *EndpointConditionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointconditions.go","code":"// WithTerminating sets the Terminating field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Terminating field is set to the value of the last call.\nfunc (b *EndpointConditionsApplyConfiguration) WithTerminating(value bool) *EndpointConditionsApplyConfiguration {\n\tb.Terminating = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100022582,"name":"EndpointHints","signature":"func EndpointHints() *EndpointHintsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointhints.go","code":"// EndpointHintsApplyConfiguration constructs an declarative configuration of the EndpointHints type for use with\n// apply.\nfunc EndpointHints() *EndpointHintsApplyConfiguration {\n\treturn \u0026EndpointHintsApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100022583,"name":"WithForZones","signature":"func (b *EndpointHintsApplyConfiguration) WithForZones(values ...*ForZoneApplyConfiguration) *EndpointHintsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointhints.go","code":"// WithForZones adds the given value to the ForZones field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ForZones field.\nfunc (b *EndpointHintsApplyConfiguration) WithForZones(values ...*ForZoneApplyConfiguration) *EndpointHintsApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithForZones\")\n\t\t}\n\t\tb.ForZones = append(b.ForZones, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100022584,"name":"EndpointPort","signature":"func EndpointPort() *EndpointPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointport.go","code":"// EndpointPortApplyConfiguration constructs an declarative configuration of the EndpointPort type for use with\n// apply.\nfunc EndpointPort() *EndpointPortApplyConfiguration {\n\treturn \u0026EndpointPortApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100022585,"name":"WithName","signature":"func (b *EndpointPortApplyConfiguration) WithName(value string) *EndpointPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointport.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *EndpointPortApplyConfiguration) WithName(value string) *EndpointPortApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":40,"to":46}} {"id":100022586,"name":"WithProtocol","signature":"func (b *EndpointPortApplyConfiguration) WithProtocol(value v1.Protocol) *EndpointPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointport.go","code":"// WithProtocol sets the Protocol field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Protocol field is set to the value of the last call.\nfunc (b *EndpointPortApplyConfiguration) WithProtocol(value v1.Protocol) *EndpointPortApplyConfiguration {\n\tb.Protocol = \u0026value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100022587,"name":"WithPort","signature":"func (b *EndpointPortApplyConfiguration) WithPort(value int32) *EndpointPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointport.go","code":"// WithPort sets the Port field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Port field is set to the value of the last call.\nfunc (b *EndpointPortApplyConfiguration) WithPort(value int32) *EndpointPortApplyConfiguration {\n\tb.Port = \u0026value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100022588,"name":"WithAppProtocol","signature":"func (b *EndpointPortApplyConfiguration) WithAppProtocol(value string) *EndpointPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointport.go","code":"// WithAppProtocol sets the AppProtocol field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AppProtocol field is set to the value of the last call.\nfunc (b *EndpointPortApplyConfiguration) WithAppProtocol(value string) *EndpointPortApplyConfiguration {\n\tb.AppProtocol = \u0026value\n\treturn b\n}","line":{"from":64,"to":70}} {"id":100022589,"name":"EndpointSlice","signature":"func EndpointSlice(name, namespace string) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go","code":"// EndpointSlice constructs an declarative configuration of the EndpointSlice type for use with\n// apply.\nfunc EndpointSlice(name, namespace string) *EndpointSliceApplyConfiguration {\n\tb := \u0026EndpointSliceApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"EndpointSlice\")\n\tb.WithAPIVersion(\"discovery.k8s.io/v1\")\n\treturn b\n}","line":{"from":40,"to":49}} {"id":100022590,"name":"ExtractEndpointSlice","signature":"func ExtractEndpointSlice(endpointSlice *discoveryv1.EndpointSlice, fieldManager string) (*EndpointSliceApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go","code":"// ExtractEndpointSlice extracts the applied configuration owned by fieldManager from\n// endpointSlice. If no managedFields are found in endpointSlice for fieldManager, a\n// EndpointSliceApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// endpointSlice must be a unmodified EndpointSlice API object that was retrieved from the Kubernetes API.\n// ExtractEndpointSlice provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractEndpointSlice(endpointSlice *discoveryv1.EndpointSlice, fieldManager string) (*EndpointSliceApplyConfiguration, error) {\n\treturn extractEndpointSlice(endpointSlice, fieldManager, \"\")\n}","line":{"from":51,"to":64}} {"id":100022591,"name":"ExtractEndpointSliceStatus","signature":"func ExtractEndpointSliceStatus(endpointSlice *discoveryv1.EndpointSlice, fieldManager string) (*EndpointSliceApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go","code":"// ExtractEndpointSliceStatus is the same as ExtractEndpointSlice except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractEndpointSliceStatus(endpointSlice *discoveryv1.EndpointSlice, fieldManager string) (*EndpointSliceApplyConfiguration, error) {\n\treturn extractEndpointSlice(endpointSlice, fieldManager, \"status\")\n}","line":{"from":66,"to":71}} {"id":100022592,"name":"extractEndpointSlice","signature":"func extractEndpointSlice(endpointSlice *discoveryv1.EndpointSlice, fieldManager string, subresource string) (*EndpointSliceApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go","code":"func extractEndpointSlice(endpointSlice *discoveryv1.EndpointSlice, fieldManager string, subresource string) (*EndpointSliceApplyConfiguration, error) {\n\tb := \u0026EndpointSliceApplyConfiguration{}\n\terr := managedfields.ExtractInto(endpointSlice, internal.Parser().Type(\"io.k8s.api.discovery.v1.EndpointSlice\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(endpointSlice.Name)\n\tb.WithNamespace(endpointSlice.Namespace)\n\n\tb.WithKind(\"EndpointSlice\")\n\tb.WithAPIVersion(\"discovery.k8s.io/v1\")\n\treturn b, nil\n}","line":{"from":73,"to":85}} {"id":100022593,"name":"WithKind","signature":"func (b *EndpointSliceApplyConfiguration) WithKind(value string) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *EndpointSliceApplyConfiguration) WithKind(value string) *EndpointSliceApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":87,"to":93}} {"id":100022594,"name":"WithAPIVersion","signature":"func (b *EndpointSliceApplyConfiguration) WithAPIVersion(value string) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *EndpointSliceApplyConfiguration) WithAPIVersion(value string) *EndpointSliceApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":95,"to":101}} {"id":100022595,"name":"WithName","signature":"func (b *EndpointSliceApplyConfiguration) WithName(value string) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *EndpointSliceApplyConfiguration) WithName(value string) *EndpointSliceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":103,"to":110}} {"id":100022596,"name":"WithGenerateName","signature":"func (b *EndpointSliceApplyConfiguration) WithGenerateName(value string) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *EndpointSliceApplyConfiguration) WithGenerateName(value string) *EndpointSliceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":112,"to":119}} {"id":100022597,"name":"WithNamespace","signature":"func (b *EndpointSliceApplyConfiguration) WithNamespace(value string) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *EndpointSliceApplyConfiguration) WithNamespace(value string) *EndpointSliceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":121,"to":128}} {"id":100022598,"name":"WithUID","signature":"func (b *EndpointSliceApplyConfiguration) WithUID(value types.UID) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *EndpointSliceApplyConfiguration) WithUID(value types.UID) *EndpointSliceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":130,"to":137}} {"id":100022599,"name":"WithResourceVersion","signature":"func (b *EndpointSliceApplyConfiguration) WithResourceVersion(value string) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *EndpointSliceApplyConfiguration) WithResourceVersion(value string) *EndpointSliceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":139,"to":146}} {"id":100022600,"name":"WithGeneration","signature":"func (b *EndpointSliceApplyConfiguration) WithGeneration(value int64) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *EndpointSliceApplyConfiguration) WithGeneration(value int64) *EndpointSliceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":148,"to":155}} {"id":100022601,"name":"WithCreationTimestamp","signature":"func (b *EndpointSliceApplyConfiguration) WithCreationTimestamp(value metav1.Time) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *EndpointSliceApplyConfiguration) WithCreationTimestamp(value metav1.Time) *EndpointSliceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":157,"to":164}} {"id":100022602,"name":"WithDeletionTimestamp","signature":"func (b *EndpointSliceApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *EndpointSliceApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *EndpointSliceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":166,"to":173}} {"id":100022603,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *EndpointSliceApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *EndpointSliceApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *EndpointSliceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":175,"to":182}} {"id":100022604,"name":"WithLabels","signature":"func (b *EndpointSliceApplyConfiguration) WithLabels(entries map[string]string) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *EndpointSliceApplyConfiguration) WithLabels(entries map[string]string) *EndpointSliceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":184,"to":197}} {"id":100022605,"name":"WithAnnotations","signature":"func (b *EndpointSliceApplyConfiguration) WithAnnotations(entries map[string]string) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *EndpointSliceApplyConfiguration) WithAnnotations(entries map[string]string) *EndpointSliceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":199,"to":212}} {"id":100022606,"name":"WithOwnerReferences","signature":"func (b *EndpointSliceApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *EndpointSliceApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *EndpointSliceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":214,"to":226}} {"id":100022607,"name":"WithFinalizers","signature":"func (b *EndpointSliceApplyConfiguration) WithFinalizers(values ...string) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *EndpointSliceApplyConfiguration) WithFinalizers(values ...string) *EndpointSliceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":228,"to":237}} {"id":100022608,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *EndpointSliceApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go","code":"func (b *EndpointSliceApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":239,"to":243}} {"id":100022609,"name":"WithAddressType","signature":"func (b *EndpointSliceApplyConfiguration) WithAddressType(value discoveryv1.AddressType) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go","code":"// WithAddressType sets the AddressType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AddressType field is set to the value of the last call.\nfunc (b *EndpointSliceApplyConfiguration) WithAddressType(value discoveryv1.AddressType) *EndpointSliceApplyConfiguration {\n\tb.AddressType = \u0026value\n\treturn b\n}","line":{"from":245,"to":251}} {"id":100022610,"name":"WithEndpoints","signature":"func (b *EndpointSliceApplyConfiguration) WithEndpoints(values ...*EndpointApplyConfiguration) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go","code":"// WithEndpoints adds the given value to the Endpoints field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Endpoints field.\nfunc (b *EndpointSliceApplyConfiguration) WithEndpoints(values ...*EndpointApplyConfiguration) *EndpointSliceApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithEndpoints\")\n\t\t}\n\t\tb.Endpoints = append(b.Endpoints, *values[i])\n\t}\n\treturn b\n}","line":{"from":253,"to":264}} {"id":100022611,"name":"WithPorts","signature":"func (b *EndpointSliceApplyConfiguration) WithPorts(values ...*EndpointPortApplyConfiguration) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/endpointslice.go","code":"// WithPorts adds the given value to the Ports field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Ports field.\nfunc (b *EndpointSliceApplyConfiguration) WithPorts(values ...*EndpointPortApplyConfiguration) *EndpointSliceApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPorts\")\n\t\t}\n\t\tb.Ports = append(b.Ports, *values[i])\n\t}\n\treturn b\n}","line":{"from":266,"to":277}} {"id":100022612,"name":"ForZone","signature":"func ForZone() *ForZoneApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/forzone.go","code":"// ForZoneApplyConfiguration constructs an declarative configuration of the ForZone type for use with\n// apply.\nfunc ForZone() *ForZoneApplyConfiguration {\n\treturn \u0026ForZoneApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100022613,"name":"WithName","signature":"func (b *ForZoneApplyConfiguration) WithName(value string) *ForZoneApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1/forzone.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ForZoneApplyConfiguration) WithName(value string) *ForZoneApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100022614,"name":"Endpoint","signature":"func Endpoint() *EndpointApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpoint.go","code":"// EndpointApplyConfiguration constructs an declarative configuration of the Endpoint type for use with\n// apply.\nfunc Endpoint() *EndpointApplyConfiguration {\n\treturn \u0026EndpointApplyConfiguration{}\n}","line":{"from":37,"to":41}} {"id":100022615,"name":"WithAddresses","signature":"func (b *EndpointApplyConfiguration) WithAddresses(values ...string) *EndpointApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpoint.go","code":"// WithAddresses adds the given value to the Addresses field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Addresses field.\nfunc (b *EndpointApplyConfiguration) WithAddresses(values ...string) *EndpointApplyConfiguration {\n\tfor i := range values {\n\t\tb.Addresses = append(b.Addresses, values[i])\n\t}\n\treturn b\n}","line":{"from":43,"to":51}} {"id":100022616,"name":"WithConditions","signature":"func (b *EndpointApplyConfiguration) WithConditions(value *EndpointConditionsApplyConfiguration) *EndpointApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpoint.go","code":"// WithConditions sets the Conditions field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Conditions field is set to the value of the last call.\nfunc (b *EndpointApplyConfiguration) WithConditions(value *EndpointConditionsApplyConfiguration) *EndpointApplyConfiguration {\n\tb.Conditions = value\n\treturn b\n}","line":{"from":53,"to":59}} {"id":100022617,"name":"WithHostname","signature":"func (b *EndpointApplyConfiguration) WithHostname(value string) *EndpointApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpoint.go","code":"// WithHostname sets the Hostname field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Hostname field is set to the value of the last call.\nfunc (b *EndpointApplyConfiguration) WithHostname(value string) *EndpointApplyConfiguration {\n\tb.Hostname = \u0026value\n\treturn b\n}","line":{"from":61,"to":67}} {"id":100022618,"name":"WithTargetRef","signature":"func (b *EndpointApplyConfiguration) WithTargetRef(value *v1.ObjectReferenceApplyConfiguration) *EndpointApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpoint.go","code":"// WithTargetRef sets the TargetRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TargetRef field is set to the value of the last call.\nfunc (b *EndpointApplyConfiguration) WithTargetRef(value *v1.ObjectReferenceApplyConfiguration) *EndpointApplyConfiguration {\n\tb.TargetRef = value\n\treturn b\n}","line":{"from":69,"to":75}} {"id":100022619,"name":"WithTopology","signature":"func (b *EndpointApplyConfiguration) WithTopology(entries map[string]string) *EndpointApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpoint.go","code":"// WithTopology puts the entries into the Topology field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Topology field,\n// overwriting an existing map entries in Topology field with the same key.\nfunc (b *EndpointApplyConfiguration) WithTopology(entries map[string]string) *EndpointApplyConfiguration {\n\tif b.Topology == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Topology = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Topology[k] = v\n\t}\n\treturn b\n}","line":{"from":77,"to":89}} {"id":100022620,"name":"WithNodeName","signature":"func (b *EndpointApplyConfiguration) WithNodeName(value string) *EndpointApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpoint.go","code":"// WithNodeName sets the NodeName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NodeName field is set to the value of the last call.\nfunc (b *EndpointApplyConfiguration) WithNodeName(value string) *EndpointApplyConfiguration {\n\tb.NodeName = \u0026value\n\treturn b\n}","line":{"from":91,"to":97}} {"id":100022621,"name":"WithHints","signature":"func (b *EndpointApplyConfiguration) WithHints(value *EndpointHintsApplyConfiguration) *EndpointApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpoint.go","code":"// WithHints sets the Hints field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Hints field is set to the value of the last call.\nfunc (b *EndpointApplyConfiguration) WithHints(value *EndpointHintsApplyConfiguration) *EndpointApplyConfiguration {\n\tb.Hints = value\n\treturn b\n}","line":{"from":99,"to":105}} {"id":100022622,"name":"EndpointConditions","signature":"func EndpointConditions() *EndpointConditionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointconditions.go","code":"// EndpointConditionsApplyConfiguration constructs an declarative configuration of the EndpointConditions type for use with\n// apply.\nfunc EndpointConditions() *EndpointConditionsApplyConfiguration {\n\treturn \u0026EndpointConditionsApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100022623,"name":"WithReady","signature":"func (b *EndpointConditionsApplyConfiguration) WithReady(value bool) *EndpointConditionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointconditions.go","code":"// WithReady sets the Ready field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Ready field is set to the value of the last call.\nfunc (b *EndpointConditionsApplyConfiguration) WithReady(value bool) *EndpointConditionsApplyConfiguration {\n\tb.Ready = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100022624,"name":"WithServing","signature":"func (b *EndpointConditionsApplyConfiguration) WithServing(value bool) *EndpointConditionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointconditions.go","code":"// WithServing sets the Serving field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Serving field is set to the value of the last call.\nfunc (b *EndpointConditionsApplyConfiguration) WithServing(value bool) *EndpointConditionsApplyConfiguration {\n\tb.Serving = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100022625,"name":"WithTerminating","signature":"func (b *EndpointConditionsApplyConfiguration) WithTerminating(value bool) *EndpointConditionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointconditions.go","code":"// WithTerminating sets the Terminating field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Terminating field is set to the value of the last call.\nfunc (b *EndpointConditionsApplyConfiguration) WithTerminating(value bool) *EndpointConditionsApplyConfiguration {\n\tb.Terminating = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100022626,"name":"EndpointHints","signature":"func EndpointHints() *EndpointHintsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointhints.go","code":"// EndpointHintsApplyConfiguration constructs an declarative configuration of the EndpointHints type for use with\n// apply.\nfunc EndpointHints() *EndpointHintsApplyConfiguration {\n\treturn \u0026EndpointHintsApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100022627,"name":"WithForZones","signature":"func (b *EndpointHintsApplyConfiguration) WithForZones(values ...*ForZoneApplyConfiguration) *EndpointHintsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointhints.go","code":"// WithForZones adds the given value to the ForZones field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ForZones field.\nfunc (b *EndpointHintsApplyConfiguration) WithForZones(values ...*ForZoneApplyConfiguration) *EndpointHintsApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithForZones\")\n\t\t}\n\t\tb.ForZones = append(b.ForZones, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100022628,"name":"EndpointPort","signature":"func EndpointPort() *EndpointPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointport.go","code":"// EndpointPortApplyConfiguration constructs an declarative configuration of the EndpointPort type for use with\n// apply.\nfunc EndpointPort() *EndpointPortApplyConfiguration {\n\treturn \u0026EndpointPortApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100022629,"name":"WithName","signature":"func (b *EndpointPortApplyConfiguration) WithName(value string) *EndpointPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointport.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *EndpointPortApplyConfiguration) WithName(value string) *EndpointPortApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":40,"to":46}} {"id":100022630,"name":"WithProtocol","signature":"func (b *EndpointPortApplyConfiguration) WithProtocol(value v1.Protocol) *EndpointPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointport.go","code":"// WithProtocol sets the Protocol field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Protocol field is set to the value of the last call.\nfunc (b *EndpointPortApplyConfiguration) WithProtocol(value v1.Protocol) *EndpointPortApplyConfiguration {\n\tb.Protocol = \u0026value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100022631,"name":"WithPort","signature":"func (b *EndpointPortApplyConfiguration) WithPort(value int32) *EndpointPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointport.go","code":"// WithPort sets the Port field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Port field is set to the value of the last call.\nfunc (b *EndpointPortApplyConfiguration) WithPort(value int32) *EndpointPortApplyConfiguration {\n\tb.Port = \u0026value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100022632,"name":"WithAppProtocol","signature":"func (b *EndpointPortApplyConfiguration) WithAppProtocol(value string) *EndpointPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointport.go","code":"// WithAppProtocol sets the AppProtocol field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AppProtocol field is set to the value of the last call.\nfunc (b *EndpointPortApplyConfiguration) WithAppProtocol(value string) *EndpointPortApplyConfiguration {\n\tb.AppProtocol = \u0026value\n\treturn b\n}","line":{"from":64,"to":70}} {"id":100022633,"name":"EndpointSlice","signature":"func EndpointSlice(name, namespace string) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go","code":"// EndpointSlice constructs an declarative configuration of the EndpointSlice type for use with\n// apply.\nfunc EndpointSlice(name, namespace string) *EndpointSliceApplyConfiguration {\n\tb := \u0026EndpointSliceApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"EndpointSlice\")\n\tb.WithAPIVersion(\"discovery.k8s.io/v1beta1\")\n\treturn b\n}","line":{"from":40,"to":49}} {"id":100022634,"name":"ExtractEndpointSlice","signature":"func ExtractEndpointSlice(endpointSlice *v1beta1.EndpointSlice, fieldManager string) (*EndpointSliceApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go","code":"// ExtractEndpointSlice extracts the applied configuration owned by fieldManager from\n// endpointSlice. If no managedFields are found in endpointSlice for fieldManager, a\n// EndpointSliceApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// endpointSlice must be a unmodified EndpointSlice API object that was retrieved from the Kubernetes API.\n// ExtractEndpointSlice provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractEndpointSlice(endpointSlice *v1beta1.EndpointSlice, fieldManager string) (*EndpointSliceApplyConfiguration, error) {\n\treturn extractEndpointSlice(endpointSlice, fieldManager, \"\")\n}","line":{"from":51,"to":64}} {"id":100022635,"name":"ExtractEndpointSliceStatus","signature":"func ExtractEndpointSliceStatus(endpointSlice *v1beta1.EndpointSlice, fieldManager string) (*EndpointSliceApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go","code":"// ExtractEndpointSliceStatus is the same as ExtractEndpointSlice except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractEndpointSliceStatus(endpointSlice *v1beta1.EndpointSlice, fieldManager string) (*EndpointSliceApplyConfiguration, error) {\n\treturn extractEndpointSlice(endpointSlice, fieldManager, \"status\")\n}","line":{"from":66,"to":71}} {"id":100022636,"name":"extractEndpointSlice","signature":"func extractEndpointSlice(endpointSlice *v1beta1.EndpointSlice, fieldManager string, subresource string) (*EndpointSliceApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go","code":"func extractEndpointSlice(endpointSlice *v1beta1.EndpointSlice, fieldManager string, subresource string) (*EndpointSliceApplyConfiguration, error) {\n\tb := \u0026EndpointSliceApplyConfiguration{}\n\terr := managedfields.ExtractInto(endpointSlice, internal.Parser().Type(\"io.k8s.api.discovery.v1beta1.EndpointSlice\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(endpointSlice.Name)\n\tb.WithNamespace(endpointSlice.Namespace)\n\n\tb.WithKind(\"EndpointSlice\")\n\tb.WithAPIVersion(\"discovery.k8s.io/v1beta1\")\n\treturn b, nil\n}","line":{"from":73,"to":85}} {"id":100022637,"name":"WithKind","signature":"func (b *EndpointSliceApplyConfiguration) WithKind(value string) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *EndpointSliceApplyConfiguration) WithKind(value string) *EndpointSliceApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":87,"to":93}} {"id":100022638,"name":"WithAPIVersion","signature":"func (b *EndpointSliceApplyConfiguration) WithAPIVersion(value string) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *EndpointSliceApplyConfiguration) WithAPIVersion(value string) *EndpointSliceApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":95,"to":101}} {"id":100022639,"name":"WithName","signature":"func (b *EndpointSliceApplyConfiguration) WithName(value string) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *EndpointSliceApplyConfiguration) WithName(value string) *EndpointSliceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":103,"to":110}} {"id":100022640,"name":"WithGenerateName","signature":"func (b *EndpointSliceApplyConfiguration) WithGenerateName(value string) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *EndpointSliceApplyConfiguration) WithGenerateName(value string) *EndpointSliceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":112,"to":119}} {"id":100022641,"name":"WithNamespace","signature":"func (b *EndpointSliceApplyConfiguration) WithNamespace(value string) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *EndpointSliceApplyConfiguration) WithNamespace(value string) *EndpointSliceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":121,"to":128}} {"id":100022642,"name":"WithUID","signature":"func (b *EndpointSliceApplyConfiguration) WithUID(value types.UID) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *EndpointSliceApplyConfiguration) WithUID(value types.UID) *EndpointSliceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":130,"to":137}} {"id":100022643,"name":"WithResourceVersion","signature":"func (b *EndpointSliceApplyConfiguration) WithResourceVersion(value string) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *EndpointSliceApplyConfiguration) WithResourceVersion(value string) *EndpointSliceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":139,"to":146}} {"id":100022644,"name":"WithGeneration","signature":"func (b *EndpointSliceApplyConfiguration) WithGeneration(value int64) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *EndpointSliceApplyConfiguration) WithGeneration(value int64) *EndpointSliceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":148,"to":155}} {"id":100022645,"name":"WithCreationTimestamp","signature":"func (b *EndpointSliceApplyConfiguration) WithCreationTimestamp(value metav1.Time) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *EndpointSliceApplyConfiguration) WithCreationTimestamp(value metav1.Time) *EndpointSliceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":157,"to":164}} {"id":100022646,"name":"WithDeletionTimestamp","signature":"func (b *EndpointSliceApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *EndpointSliceApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *EndpointSliceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":166,"to":173}} {"id":100022647,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *EndpointSliceApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *EndpointSliceApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *EndpointSliceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":175,"to":182}} {"id":100022648,"name":"WithLabels","signature":"func (b *EndpointSliceApplyConfiguration) WithLabels(entries map[string]string) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *EndpointSliceApplyConfiguration) WithLabels(entries map[string]string) *EndpointSliceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":184,"to":197}} {"id":100022649,"name":"WithAnnotations","signature":"func (b *EndpointSliceApplyConfiguration) WithAnnotations(entries map[string]string) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *EndpointSliceApplyConfiguration) WithAnnotations(entries map[string]string) *EndpointSliceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":199,"to":212}} {"id":100022650,"name":"WithOwnerReferences","signature":"func (b *EndpointSliceApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *EndpointSliceApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *EndpointSliceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":214,"to":226}} {"id":100022651,"name":"WithFinalizers","signature":"func (b *EndpointSliceApplyConfiguration) WithFinalizers(values ...string) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *EndpointSliceApplyConfiguration) WithFinalizers(values ...string) *EndpointSliceApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":228,"to":237}} {"id":100022652,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *EndpointSliceApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go","code":"func (b *EndpointSliceApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":239,"to":243}} {"id":100022653,"name":"WithAddressType","signature":"func (b *EndpointSliceApplyConfiguration) WithAddressType(value v1beta1.AddressType) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go","code":"// WithAddressType sets the AddressType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AddressType field is set to the value of the last call.\nfunc (b *EndpointSliceApplyConfiguration) WithAddressType(value v1beta1.AddressType) *EndpointSliceApplyConfiguration {\n\tb.AddressType = \u0026value\n\treturn b\n}","line":{"from":245,"to":251}} {"id":100022654,"name":"WithEndpoints","signature":"func (b *EndpointSliceApplyConfiguration) WithEndpoints(values ...*EndpointApplyConfiguration) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go","code":"// WithEndpoints adds the given value to the Endpoints field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Endpoints field.\nfunc (b *EndpointSliceApplyConfiguration) WithEndpoints(values ...*EndpointApplyConfiguration) *EndpointSliceApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithEndpoints\")\n\t\t}\n\t\tb.Endpoints = append(b.Endpoints, *values[i])\n\t}\n\treturn b\n}","line":{"from":253,"to":264}} {"id":100022655,"name":"WithPorts","signature":"func (b *EndpointSliceApplyConfiguration) WithPorts(values ...*EndpointPortApplyConfiguration) *EndpointSliceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/endpointslice.go","code":"// WithPorts adds the given value to the Ports field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Ports field.\nfunc (b *EndpointSliceApplyConfiguration) WithPorts(values ...*EndpointPortApplyConfiguration) *EndpointSliceApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPorts\")\n\t\t}\n\t\tb.Ports = append(b.Ports, *values[i])\n\t}\n\treturn b\n}","line":{"from":266,"to":277}} {"id":100022656,"name":"ForZone","signature":"func ForZone() *ForZoneApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/forzone.go","code":"// ForZoneApplyConfiguration constructs an declarative configuration of the ForZone type for use with\n// apply.\nfunc ForZone() *ForZoneApplyConfiguration {\n\treturn \u0026ForZoneApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100022657,"name":"WithName","signature":"func (b *ForZoneApplyConfiguration) WithName(value string) *ForZoneApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/discovery/v1beta1/forzone.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ForZoneApplyConfiguration) WithName(value string) *ForZoneApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100022658,"name":"Event","signature":"func Event(name, namespace string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// Event constructs an declarative configuration of the Event type for use with\n// apply.\nfunc Event(name, namespace string) *EventApplyConfiguration {\n\tb := \u0026EventApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"Event\")\n\tb.WithAPIVersion(\"events.k8s.io/v1\")\n\treturn b\n}","line":{"from":52,"to":61}} {"id":100022659,"name":"ExtractEvent","signature":"func ExtractEvent(event *apieventsv1.Event, fieldManager string) (*EventApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// ExtractEvent extracts the applied configuration owned by fieldManager from\n// event. If no managedFields are found in event for fieldManager, a\n// EventApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// event must be a unmodified Event API object that was retrieved from the Kubernetes API.\n// ExtractEvent provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractEvent(event *apieventsv1.Event, fieldManager string) (*EventApplyConfiguration, error) {\n\treturn extractEvent(event, fieldManager, \"\")\n}","line":{"from":63,"to":76}} {"id":100022660,"name":"ExtractEventStatus","signature":"func ExtractEventStatus(event *apieventsv1.Event, fieldManager string) (*EventApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// ExtractEventStatus is the same as ExtractEvent except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractEventStatus(event *apieventsv1.Event, fieldManager string) (*EventApplyConfiguration, error) {\n\treturn extractEvent(event, fieldManager, \"status\")\n}","line":{"from":78,"to":83}} {"id":100022661,"name":"extractEvent","signature":"func extractEvent(event *apieventsv1.Event, fieldManager string, subresource string) (*EventApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"func extractEvent(event *apieventsv1.Event, fieldManager string, subresource string) (*EventApplyConfiguration, error) {\n\tb := \u0026EventApplyConfiguration{}\n\terr := managedfields.ExtractInto(event, internal.Parser().Type(\"io.k8s.api.events.v1.Event\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(event.Name)\n\tb.WithNamespace(event.Namespace)\n\n\tb.WithKind(\"Event\")\n\tb.WithAPIVersion(\"events.k8s.io/v1\")\n\treturn b, nil\n}","line":{"from":85,"to":97}} {"id":100022662,"name":"WithKind","signature":"func (b *EventApplyConfiguration) WithKind(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithKind(value string) *EventApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":99,"to":105}} {"id":100022663,"name":"WithAPIVersion","signature":"func (b *EventApplyConfiguration) WithAPIVersion(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithAPIVersion(value string) *EventApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":107,"to":113}} {"id":100022664,"name":"WithName","signature":"func (b *EventApplyConfiguration) WithName(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithName(value string) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":115,"to":122}} {"id":100022665,"name":"WithGenerateName","signature":"func (b *EventApplyConfiguration) WithGenerateName(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithGenerateName(value string) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":124,"to":131}} {"id":100022666,"name":"WithNamespace","signature":"func (b *EventApplyConfiguration) WithNamespace(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithNamespace(value string) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":133,"to":140}} {"id":100022667,"name":"WithUID","signature":"func (b *EventApplyConfiguration) WithUID(value types.UID) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithUID(value types.UID) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":142,"to":149}} {"id":100022668,"name":"WithResourceVersion","signature":"func (b *EventApplyConfiguration) WithResourceVersion(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithResourceVersion(value string) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":151,"to":158}} {"id":100022669,"name":"WithGeneration","signature":"func (b *EventApplyConfiguration) WithGeneration(value int64) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithGeneration(value int64) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":160,"to":167}} {"id":100022670,"name":"WithCreationTimestamp","signature":"func (b *EventApplyConfiguration) WithCreationTimestamp(value metav1.Time) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithCreationTimestamp(value metav1.Time) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":169,"to":176}} {"id":100022671,"name":"WithDeletionTimestamp","signature":"func (b *EventApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":178,"to":185}} {"id":100022672,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *EventApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":187,"to":194}} {"id":100022673,"name":"WithLabels","signature":"func (b *EventApplyConfiguration) WithLabels(entries map[string]string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *EventApplyConfiguration) WithLabels(entries map[string]string) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100022674,"name":"WithAnnotations","signature":"func (b *EventApplyConfiguration) WithAnnotations(entries map[string]string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *EventApplyConfiguration) WithAnnotations(entries map[string]string) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":211,"to":224}} {"id":100022675,"name":"WithOwnerReferences","signature":"func (b *EventApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *EventApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":226,"to":238}} {"id":100022676,"name":"WithFinalizers","signature":"func (b *EventApplyConfiguration) WithFinalizers(values ...string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *EventApplyConfiguration) WithFinalizers(values ...string) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":240,"to":249}} {"id":100022677,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *EventApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"func (b *EventApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":251,"to":255}} {"id":100022678,"name":"WithEventTime","signature":"func (b *EventApplyConfiguration) WithEventTime(value metav1.MicroTime) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithEventTime sets the EventTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the EventTime field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithEventTime(value metav1.MicroTime) *EventApplyConfiguration {\n\tb.EventTime = \u0026value\n\treturn b\n}","line":{"from":257,"to":263}} {"id":100022679,"name":"WithSeries","signature":"func (b *EventApplyConfiguration) WithSeries(value *EventSeriesApplyConfiguration) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithSeries sets the Series field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Series field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithSeries(value *EventSeriesApplyConfiguration) *EventApplyConfiguration {\n\tb.Series = value\n\treturn b\n}","line":{"from":265,"to":271}} {"id":100022680,"name":"WithReportingController","signature":"func (b *EventApplyConfiguration) WithReportingController(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithReportingController sets the ReportingController field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReportingController field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithReportingController(value string) *EventApplyConfiguration {\n\tb.ReportingController = \u0026value\n\treturn b\n}","line":{"from":273,"to":279}} {"id":100022681,"name":"WithReportingInstance","signature":"func (b *EventApplyConfiguration) WithReportingInstance(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithReportingInstance sets the ReportingInstance field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReportingInstance field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithReportingInstance(value string) *EventApplyConfiguration {\n\tb.ReportingInstance = \u0026value\n\treturn b\n}","line":{"from":281,"to":287}} {"id":100022682,"name":"WithAction","signature":"func (b *EventApplyConfiguration) WithAction(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithAction sets the Action field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Action field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithAction(value string) *EventApplyConfiguration {\n\tb.Action = \u0026value\n\treturn b\n}","line":{"from":289,"to":295}} {"id":100022683,"name":"WithReason","signature":"func (b *EventApplyConfiguration) WithReason(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithReason(value string) *EventApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":297,"to":303}} {"id":100022684,"name":"WithRegarding","signature":"func (b *EventApplyConfiguration) WithRegarding(value *corev1.ObjectReferenceApplyConfiguration) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithRegarding sets the Regarding field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Regarding field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithRegarding(value *corev1.ObjectReferenceApplyConfiguration) *EventApplyConfiguration {\n\tb.Regarding = value\n\treturn b\n}","line":{"from":305,"to":311}} {"id":100022685,"name":"WithRelated","signature":"func (b *EventApplyConfiguration) WithRelated(value *corev1.ObjectReferenceApplyConfiguration) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithRelated sets the Related field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Related field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithRelated(value *corev1.ObjectReferenceApplyConfiguration) *EventApplyConfiguration {\n\tb.Related = value\n\treturn b\n}","line":{"from":313,"to":319}} {"id":100022686,"name":"WithNote","signature":"func (b *EventApplyConfiguration) WithNote(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithNote sets the Note field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Note field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithNote(value string) *EventApplyConfiguration {\n\tb.Note = \u0026value\n\treturn b\n}","line":{"from":321,"to":327}} {"id":100022687,"name":"WithType","signature":"func (b *EventApplyConfiguration) WithType(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithType(value string) *EventApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":329,"to":335}} {"id":100022688,"name":"WithDeprecatedSource","signature":"func (b *EventApplyConfiguration) WithDeprecatedSource(value *corev1.EventSourceApplyConfiguration) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithDeprecatedSource sets the DeprecatedSource field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeprecatedSource field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithDeprecatedSource(value *corev1.EventSourceApplyConfiguration) *EventApplyConfiguration {\n\tb.DeprecatedSource = value\n\treturn b\n}","line":{"from":337,"to":343}} {"id":100022689,"name":"WithDeprecatedFirstTimestamp","signature":"func (b *EventApplyConfiguration) WithDeprecatedFirstTimestamp(value metav1.Time) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithDeprecatedFirstTimestamp sets the DeprecatedFirstTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeprecatedFirstTimestamp field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithDeprecatedFirstTimestamp(value metav1.Time) *EventApplyConfiguration {\n\tb.DeprecatedFirstTimestamp = \u0026value\n\treturn b\n}","line":{"from":345,"to":351}} {"id":100022690,"name":"WithDeprecatedLastTimestamp","signature":"func (b *EventApplyConfiguration) WithDeprecatedLastTimestamp(value metav1.Time) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithDeprecatedLastTimestamp sets the DeprecatedLastTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeprecatedLastTimestamp field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithDeprecatedLastTimestamp(value metav1.Time) *EventApplyConfiguration {\n\tb.DeprecatedLastTimestamp = \u0026value\n\treturn b\n}","line":{"from":353,"to":359}} {"id":100022691,"name":"WithDeprecatedCount","signature":"func (b *EventApplyConfiguration) WithDeprecatedCount(value int32) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/event.go","code":"// WithDeprecatedCount sets the DeprecatedCount field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeprecatedCount field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithDeprecatedCount(value int32) *EventApplyConfiguration {\n\tb.DeprecatedCount = \u0026value\n\treturn b\n}","line":{"from":361,"to":367}} {"id":100022692,"name":"EventSeries","signature":"func EventSeries() *EventSeriesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/eventseries.go","code":"// EventSeriesApplyConfiguration constructs an declarative configuration of the EventSeries type for use with\n// apply.\nfunc EventSeries() *EventSeriesApplyConfiguration {\n\treturn \u0026EventSeriesApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100022693,"name":"WithCount","signature":"func (b *EventSeriesApplyConfiguration) WithCount(value int32) *EventSeriesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/eventseries.go","code":"// WithCount sets the Count field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Count field is set to the value of the last call.\nfunc (b *EventSeriesApplyConfiguration) WithCount(value int32) *EventSeriesApplyConfiguration {\n\tb.Count = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100022694,"name":"WithLastObservedTime","signature":"func (b *EventSeriesApplyConfiguration) WithLastObservedTime(value v1.MicroTime) *EventSeriesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1/eventseries.go","code":"// WithLastObservedTime sets the LastObservedTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastObservedTime field is set to the value of the last call.\nfunc (b *EventSeriesApplyConfiguration) WithLastObservedTime(value v1.MicroTime) *EventSeriesApplyConfiguration {\n\tb.LastObservedTime = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100022695,"name":"Event","signature":"func Event(name, namespace string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// Event constructs an declarative configuration of the Event type for use with\n// apply.\nfunc Event(name, namespace string) *EventApplyConfiguration {\n\tb := \u0026EventApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"Event\")\n\tb.WithAPIVersion(\"events.k8s.io/v1beta1\")\n\treturn b\n}","line":{"from":52,"to":61}} {"id":100022696,"name":"ExtractEvent","signature":"func ExtractEvent(event *eventsv1beta1.Event, fieldManager string) (*EventApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// ExtractEvent extracts the applied configuration owned by fieldManager from\n// event. If no managedFields are found in event for fieldManager, a\n// EventApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// event must be a unmodified Event API object that was retrieved from the Kubernetes API.\n// ExtractEvent provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractEvent(event *eventsv1beta1.Event, fieldManager string) (*EventApplyConfiguration, error) {\n\treturn extractEvent(event, fieldManager, \"\")\n}","line":{"from":63,"to":76}} {"id":100022697,"name":"ExtractEventStatus","signature":"func ExtractEventStatus(event *eventsv1beta1.Event, fieldManager string) (*EventApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// ExtractEventStatus is the same as ExtractEvent except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractEventStatus(event *eventsv1beta1.Event, fieldManager string) (*EventApplyConfiguration, error) {\n\treturn extractEvent(event, fieldManager, \"status\")\n}","line":{"from":78,"to":83}} {"id":100022698,"name":"extractEvent","signature":"func extractEvent(event *eventsv1beta1.Event, fieldManager string, subresource string) (*EventApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"func extractEvent(event *eventsv1beta1.Event, fieldManager string, subresource string) (*EventApplyConfiguration, error) {\n\tb := \u0026EventApplyConfiguration{}\n\terr := managedfields.ExtractInto(event, internal.Parser().Type(\"io.k8s.api.events.v1beta1.Event\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(event.Name)\n\tb.WithNamespace(event.Namespace)\n\n\tb.WithKind(\"Event\")\n\tb.WithAPIVersion(\"events.k8s.io/v1beta1\")\n\treturn b, nil\n}","line":{"from":85,"to":97}} {"id":100022699,"name":"WithKind","signature":"func (b *EventApplyConfiguration) WithKind(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithKind(value string) *EventApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":99,"to":105}} {"id":100022700,"name":"WithAPIVersion","signature":"func (b *EventApplyConfiguration) WithAPIVersion(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithAPIVersion(value string) *EventApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":107,"to":113}} {"id":100022701,"name":"WithName","signature":"func (b *EventApplyConfiguration) WithName(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithName(value string) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":115,"to":122}} {"id":100022702,"name":"WithGenerateName","signature":"func (b *EventApplyConfiguration) WithGenerateName(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithGenerateName(value string) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":124,"to":131}} {"id":100022703,"name":"WithNamespace","signature":"func (b *EventApplyConfiguration) WithNamespace(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithNamespace(value string) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":133,"to":140}} {"id":100022704,"name":"WithUID","signature":"func (b *EventApplyConfiguration) WithUID(value types.UID) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithUID(value types.UID) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":142,"to":149}} {"id":100022705,"name":"WithResourceVersion","signature":"func (b *EventApplyConfiguration) WithResourceVersion(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithResourceVersion(value string) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":151,"to":158}} {"id":100022706,"name":"WithGeneration","signature":"func (b *EventApplyConfiguration) WithGeneration(value int64) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithGeneration(value int64) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":160,"to":167}} {"id":100022707,"name":"WithCreationTimestamp","signature":"func (b *EventApplyConfiguration) WithCreationTimestamp(value metav1.Time) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithCreationTimestamp(value metav1.Time) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":169,"to":176}} {"id":100022708,"name":"WithDeletionTimestamp","signature":"func (b *EventApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":178,"to":185}} {"id":100022709,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *EventApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":187,"to":194}} {"id":100022710,"name":"WithLabels","signature":"func (b *EventApplyConfiguration) WithLabels(entries map[string]string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *EventApplyConfiguration) WithLabels(entries map[string]string) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100022711,"name":"WithAnnotations","signature":"func (b *EventApplyConfiguration) WithAnnotations(entries map[string]string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *EventApplyConfiguration) WithAnnotations(entries map[string]string) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":211,"to":224}} {"id":100022712,"name":"WithOwnerReferences","signature":"func (b *EventApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *EventApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":226,"to":238}} {"id":100022713,"name":"WithFinalizers","signature":"func (b *EventApplyConfiguration) WithFinalizers(values ...string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *EventApplyConfiguration) WithFinalizers(values ...string) *EventApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":240,"to":249}} {"id":100022714,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *EventApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"func (b *EventApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":251,"to":255}} {"id":100022715,"name":"WithEventTime","signature":"func (b *EventApplyConfiguration) WithEventTime(value metav1.MicroTime) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithEventTime sets the EventTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the EventTime field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithEventTime(value metav1.MicroTime) *EventApplyConfiguration {\n\tb.EventTime = \u0026value\n\treturn b\n}","line":{"from":257,"to":263}} {"id":100022716,"name":"WithSeries","signature":"func (b *EventApplyConfiguration) WithSeries(value *EventSeriesApplyConfiguration) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithSeries sets the Series field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Series field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithSeries(value *EventSeriesApplyConfiguration) *EventApplyConfiguration {\n\tb.Series = value\n\treturn b\n}","line":{"from":265,"to":271}} {"id":100022717,"name":"WithReportingController","signature":"func (b *EventApplyConfiguration) WithReportingController(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithReportingController sets the ReportingController field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReportingController field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithReportingController(value string) *EventApplyConfiguration {\n\tb.ReportingController = \u0026value\n\treturn b\n}","line":{"from":273,"to":279}} {"id":100022718,"name":"WithReportingInstance","signature":"func (b *EventApplyConfiguration) WithReportingInstance(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithReportingInstance sets the ReportingInstance field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReportingInstance field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithReportingInstance(value string) *EventApplyConfiguration {\n\tb.ReportingInstance = \u0026value\n\treturn b\n}","line":{"from":281,"to":287}} {"id":100022719,"name":"WithAction","signature":"func (b *EventApplyConfiguration) WithAction(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithAction sets the Action field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Action field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithAction(value string) *EventApplyConfiguration {\n\tb.Action = \u0026value\n\treturn b\n}","line":{"from":289,"to":295}} {"id":100022720,"name":"WithReason","signature":"func (b *EventApplyConfiguration) WithReason(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithReason(value string) *EventApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":297,"to":303}} {"id":100022721,"name":"WithRegarding","signature":"func (b *EventApplyConfiguration) WithRegarding(value *corev1.ObjectReferenceApplyConfiguration) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithRegarding sets the Regarding field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Regarding field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithRegarding(value *corev1.ObjectReferenceApplyConfiguration) *EventApplyConfiguration {\n\tb.Regarding = value\n\treturn b\n}","line":{"from":305,"to":311}} {"id":100022722,"name":"WithRelated","signature":"func (b *EventApplyConfiguration) WithRelated(value *corev1.ObjectReferenceApplyConfiguration) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithRelated sets the Related field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Related field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithRelated(value *corev1.ObjectReferenceApplyConfiguration) *EventApplyConfiguration {\n\tb.Related = value\n\treturn b\n}","line":{"from":313,"to":319}} {"id":100022723,"name":"WithNote","signature":"func (b *EventApplyConfiguration) WithNote(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithNote sets the Note field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Note field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithNote(value string) *EventApplyConfiguration {\n\tb.Note = \u0026value\n\treturn b\n}","line":{"from":321,"to":327}} {"id":100022724,"name":"WithType","signature":"func (b *EventApplyConfiguration) WithType(value string) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithType(value string) *EventApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":329,"to":335}} {"id":100022725,"name":"WithDeprecatedSource","signature":"func (b *EventApplyConfiguration) WithDeprecatedSource(value *corev1.EventSourceApplyConfiguration) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithDeprecatedSource sets the DeprecatedSource field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeprecatedSource field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithDeprecatedSource(value *corev1.EventSourceApplyConfiguration) *EventApplyConfiguration {\n\tb.DeprecatedSource = value\n\treturn b\n}","line":{"from":337,"to":343}} {"id":100022726,"name":"WithDeprecatedFirstTimestamp","signature":"func (b *EventApplyConfiguration) WithDeprecatedFirstTimestamp(value metav1.Time) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithDeprecatedFirstTimestamp sets the DeprecatedFirstTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeprecatedFirstTimestamp field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithDeprecatedFirstTimestamp(value metav1.Time) *EventApplyConfiguration {\n\tb.DeprecatedFirstTimestamp = \u0026value\n\treturn b\n}","line":{"from":345,"to":351}} {"id":100022727,"name":"WithDeprecatedLastTimestamp","signature":"func (b *EventApplyConfiguration) WithDeprecatedLastTimestamp(value metav1.Time) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithDeprecatedLastTimestamp sets the DeprecatedLastTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeprecatedLastTimestamp field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithDeprecatedLastTimestamp(value metav1.Time) *EventApplyConfiguration {\n\tb.DeprecatedLastTimestamp = \u0026value\n\treturn b\n}","line":{"from":353,"to":359}} {"id":100022728,"name":"WithDeprecatedCount","signature":"func (b *EventApplyConfiguration) WithDeprecatedCount(value int32) *EventApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/event.go","code":"// WithDeprecatedCount sets the DeprecatedCount field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeprecatedCount field is set to the value of the last call.\nfunc (b *EventApplyConfiguration) WithDeprecatedCount(value int32) *EventApplyConfiguration {\n\tb.DeprecatedCount = \u0026value\n\treturn b\n}","line":{"from":361,"to":367}} {"id":100022729,"name":"EventSeries","signature":"func EventSeries() *EventSeriesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/eventseries.go","code":"// EventSeriesApplyConfiguration constructs an declarative configuration of the EventSeries type for use with\n// apply.\nfunc EventSeries() *EventSeriesApplyConfiguration {\n\treturn \u0026EventSeriesApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100022730,"name":"WithCount","signature":"func (b *EventSeriesApplyConfiguration) WithCount(value int32) *EventSeriesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/eventseries.go","code":"// WithCount sets the Count field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Count field is set to the value of the last call.\nfunc (b *EventSeriesApplyConfiguration) WithCount(value int32) *EventSeriesApplyConfiguration {\n\tb.Count = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100022731,"name":"WithLastObservedTime","signature":"func (b *EventSeriesApplyConfiguration) WithLastObservedTime(value v1.MicroTime) *EventSeriesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/events/v1beta1/eventseries.go","code":"// WithLastObservedTime sets the LastObservedTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastObservedTime field is set to the value of the last call.\nfunc (b *EventSeriesApplyConfiguration) WithLastObservedTime(value v1.MicroTime) *EventSeriesApplyConfiguration {\n\tb.LastObservedTime = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100022732,"name":"DaemonSet","signature":"func DaemonSet(name, namespace string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonset.go","code":"// DaemonSet constructs an declarative configuration of the DaemonSet type for use with\n// apply.\nfunc DaemonSet(name, namespace string) *DaemonSetApplyConfiguration {\n\tb := \u0026DaemonSetApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"DaemonSet\")\n\tb.WithAPIVersion(\"extensions/v1beta1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100022733,"name":"ExtractDaemonSet","signature":"func ExtractDaemonSet(daemonSet *extensionsv1beta1.DaemonSet, fieldManager string) (*DaemonSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonset.go","code":"// ExtractDaemonSet extracts the applied configuration owned by fieldManager from\n// daemonSet. If no managedFields are found in daemonSet for fieldManager, a\n// DaemonSetApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// daemonSet must be a unmodified DaemonSet API object that was retrieved from the Kubernetes API.\n// ExtractDaemonSet provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractDaemonSet(daemonSet *extensionsv1beta1.DaemonSet, fieldManager string) (*DaemonSetApplyConfiguration, error) {\n\treturn extractDaemonSet(daemonSet, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100022734,"name":"ExtractDaemonSetStatus","signature":"func ExtractDaemonSetStatus(daemonSet *extensionsv1beta1.DaemonSet, fieldManager string) (*DaemonSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonset.go","code":"// ExtractDaemonSetStatus is the same as ExtractDaemonSet except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractDaemonSetStatus(daemonSet *extensionsv1beta1.DaemonSet, fieldManager string) (*DaemonSetApplyConfiguration, error) {\n\treturn extractDaemonSet(daemonSet, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100022735,"name":"extractDaemonSet","signature":"func extractDaemonSet(daemonSet *extensionsv1beta1.DaemonSet, fieldManager string, subresource string) (*DaemonSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonset.go","code":"func extractDaemonSet(daemonSet *extensionsv1beta1.DaemonSet, fieldManager string, subresource string) (*DaemonSetApplyConfiguration, error) {\n\tb := \u0026DaemonSetApplyConfiguration{}\n\terr := managedfields.ExtractInto(daemonSet, internal.Parser().Type(\"io.k8s.api.extensions.v1beta1.DaemonSet\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(daemonSet.Name)\n\tb.WithNamespace(daemonSet.Namespace)\n\n\tb.WithKind(\"DaemonSet\")\n\tb.WithAPIVersion(\"extensions/v1beta1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100022736,"name":"WithKind","signature":"func (b *DaemonSetApplyConfiguration) WithKind(value string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonset.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithKind(value string) *DaemonSetApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100022737,"name":"WithAPIVersion","signature":"func (b *DaemonSetApplyConfiguration) WithAPIVersion(value string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonset.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithAPIVersion(value string) *DaemonSetApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100022738,"name":"WithName","signature":"func (b *DaemonSetApplyConfiguration) WithName(value string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonset.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithName(value string) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100022739,"name":"WithGenerateName","signature":"func (b *DaemonSetApplyConfiguration) WithGenerateName(value string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonset.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithGenerateName(value string) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100022740,"name":"WithNamespace","signature":"func (b *DaemonSetApplyConfiguration) WithNamespace(value string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonset.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithNamespace(value string) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100022741,"name":"WithUID","signature":"func (b *DaemonSetApplyConfiguration) WithUID(value types.UID) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonset.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithUID(value types.UID) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100022742,"name":"WithResourceVersion","signature":"func (b *DaemonSetApplyConfiguration) WithResourceVersion(value string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonset.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithResourceVersion(value string) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100022743,"name":"WithGeneration","signature":"func (b *DaemonSetApplyConfiguration) WithGeneration(value int64) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonset.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithGeneration(value int64) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100022744,"name":"WithCreationTimestamp","signature":"func (b *DaemonSetApplyConfiguration) WithCreationTimestamp(value metav1.Time) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonset.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithCreationTimestamp(value metav1.Time) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100022745,"name":"WithDeletionTimestamp","signature":"func (b *DaemonSetApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonset.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100022746,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *DaemonSetApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonset.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100022747,"name":"WithLabels","signature":"func (b *DaemonSetApplyConfiguration) WithLabels(entries map[string]string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonset.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *DaemonSetApplyConfiguration) WithLabels(entries map[string]string) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100022748,"name":"WithAnnotations","signature":"func (b *DaemonSetApplyConfiguration) WithAnnotations(entries map[string]string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonset.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *DaemonSetApplyConfiguration) WithAnnotations(entries map[string]string) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100022749,"name":"WithOwnerReferences","signature":"func (b *DaemonSetApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonset.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *DaemonSetApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100022750,"name":"WithFinalizers","signature":"func (b *DaemonSetApplyConfiguration) WithFinalizers(values ...string) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonset.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *DaemonSetApplyConfiguration) WithFinalizers(values ...string) *DaemonSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100022751,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *DaemonSetApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonset.go","code":"func (b *DaemonSetApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100022752,"name":"WithSpec","signature":"func (b *DaemonSetApplyConfiguration) WithSpec(value *DaemonSetSpecApplyConfiguration) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonset.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithSpec(value *DaemonSetSpecApplyConfiguration) *DaemonSetApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100022753,"name":"WithStatus","signature":"func (b *DaemonSetApplyConfiguration) WithStatus(value *DaemonSetStatusApplyConfiguration) *DaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonset.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *DaemonSetApplyConfiguration) WithStatus(value *DaemonSetStatusApplyConfiguration) *DaemonSetApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100022754,"name":"DaemonSetCondition","signature":"func DaemonSetCondition() *DaemonSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonsetcondition.go","code":"// DaemonSetConditionApplyConfiguration constructs an declarative configuration of the DaemonSetCondition type for use with\n// apply.\nfunc DaemonSetCondition() *DaemonSetConditionApplyConfiguration {\n\treturn \u0026DaemonSetConditionApplyConfiguration{}\n}","line":{"from":37,"to":41}} {"id":100022755,"name":"WithType","signature":"func (b *DaemonSetConditionApplyConfiguration) WithType(value v1beta1.DaemonSetConditionType) *DaemonSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonsetcondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *DaemonSetConditionApplyConfiguration) WithType(value v1beta1.DaemonSetConditionType) *DaemonSetConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100022756,"name":"WithStatus","signature":"func (b *DaemonSetConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *DaemonSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonsetcondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *DaemonSetConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *DaemonSetConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100022757,"name":"WithLastTransitionTime","signature":"func (b *DaemonSetConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *DaemonSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonsetcondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *DaemonSetConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *DaemonSetConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":59,"to":65}} {"id":100022758,"name":"WithReason","signature":"func (b *DaemonSetConditionApplyConfiguration) WithReason(value string) *DaemonSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonsetcondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *DaemonSetConditionApplyConfiguration) WithReason(value string) *DaemonSetConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100022759,"name":"WithMessage","signature":"func (b *DaemonSetConditionApplyConfiguration) WithMessage(value string) *DaemonSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonsetcondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *DaemonSetConditionApplyConfiguration) WithMessage(value string) *DaemonSetConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":75,"to":81}} {"id":100022760,"name":"DaemonSetSpec","signature":"func DaemonSetSpec() *DaemonSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonsetspec.go","code":"// DaemonSetSpecApplyConfiguration constructs an declarative configuration of the DaemonSetSpec type for use with\n// apply.\nfunc DaemonSetSpec() *DaemonSetSpecApplyConfiguration {\n\treturn \u0026DaemonSetSpecApplyConfiguration{}\n}","line":{"from":37,"to":41}} {"id":100022761,"name":"WithSelector","signature":"func (b *DaemonSetSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *DaemonSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonsetspec.go","code":"// WithSelector sets the Selector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Selector field is set to the value of the last call.\nfunc (b *DaemonSetSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *DaemonSetSpecApplyConfiguration {\n\tb.Selector = value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100022762,"name":"WithTemplate","signature":"func (b *DaemonSetSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *DaemonSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonsetspec.go","code":"// WithTemplate sets the Template field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Template field is set to the value of the last call.\nfunc (b *DaemonSetSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *DaemonSetSpecApplyConfiguration {\n\tb.Template = value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100022763,"name":"WithUpdateStrategy","signature":"func (b *DaemonSetSpecApplyConfiguration) WithUpdateStrategy(value *DaemonSetUpdateStrategyApplyConfiguration) *DaemonSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonsetspec.go","code":"// WithUpdateStrategy sets the UpdateStrategy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UpdateStrategy field is set to the value of the last call.\nfunc (b *DaemonSetSpecApplyConfiguration) WithUpdateStrategy(value *DaemonSetUpdateStrategyApplyConfiguration) *DaemonSetSpecApplyConfiguration {\n\tb.UpdateStrategy = value\n\treturn b\n}","line":{"from":59,"to":65}} {"id":100022764,"name":"WithMinReadySeconds","signature":"func (b *DaemonSetSpecApplyConfiguration) WithMinReadySeconds(value int32) *DaemonSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonsetspec.go","code":"// WithMinReadySeconds sets the MinReadySeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MinReadySeconds field is set to the value of the last call.\nfunc (b *DaemonSetSpecApplyConfiguration) WithMinReadySeconds(value int32) *DaemonSetSpecApplyConfiguration {\n\tb.MinReadySeconds = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100022765,"name":"WithTemplateGeneration","signature":"func (b *DaemonSetSpecApplyConfiguration) WithTemplateGeneration(value int64) *DaemonSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonsetspec.go","code":"// WithTemplateGeneration sets the TemplateGeneration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the TemplateGeneration field is set to the value of the last call.\nfunc (b *DaemonSetSpecApplyConfiguration) WithTemplateGeneration(value int64) *DaemonSetSpecApplyConfiguration {\n\tb.TemplateGeneration = \u0026value\n\treturn b\n}","line":{"from":75,"to":81}} {"id":100022766,"name":"WithRevisionHistoryLimit","signature":"func (b *DaemonSetSpecApplyConfiguration) WithRevisionHistoryLimit(value int32) *DaemonSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonsetspec.go","code":"// WithRevisionHistoryLimit sets the RevisionHistoryLimit field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RevisionHistoryLimit field is set to the value of the last call.\nfunc (b *DaemonSetSpecApplyConfiguration) WithRevisionHistoryLimit(value int32) *DaemonSetSpecApplyConfiguration {\n\tb.RevisionHistoryLimit = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100022767,"name":"DaemonSetStatus","signature":"func DaemonSetStatus() *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonsetstatus.go","code":"// DaemonSetStatusApplyConfiguration constructs an declarative configuration of the DaemonSetStatus type for use with\n// apply.\nfunc DaemonSetStatus() *DaemonSetStatusApplyConfiguration {\n\treturn \u0026DaemonSetStatusApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100022768,"name":"WithCurrentNumberScheduled","signature":"func (b *DaemonSetStatusApplyConfiguration) WithCurrentNumberScheduled(value int32) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonsetstatus.go","code":"// WithCurrentNumberScheduled sets the CurrentNumberScheduled field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CurrentNumberScheduled field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithCurrentNumberScheduled(value int32) *DaemonSetStatusApplyConfiguration {\n\tb.CurrentNumberScheduled = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100022769,"name":"WithNumberMisscheduled","signature":"func (b *DaemonSetStatusApplyConfiguration) WithNumberMisscheduled(value int32) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonsetstatus.go","code":"// WithNumberMisscheduled sets the NumberMisscheduled field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NumberMisscheduled field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithNumberMisscheduled(value int32) *DaemonSetStatusApplyConfiguration {\n\tb.NumberMisscheduled = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100022770,"name":"WithDesiredNumberScheduled","signature":"func (b *DaemonSetStatusApplyConfiguration) WithDesiredNumberScheduled(value int32) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonsetstatus.go","code":"// WithDesiredNumberScheduled sets the DesiredNumberScheduled field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DesiredNumberScheduled field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithDesiredNumberScheduled(value int32) *DaemonSetStatusApplyConfiguration {\n\tb.DesiredNumberScheduled = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100022771,"name":"WithNumberReady","signature":"func (b *DaemonSetStatusApplyConfiguration) WithNumberReady(value int32) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonsetstatus.go","code":"// WithNumberReady sets the NumberReady field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NumberReady field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithNumberReady(value int32) *DaemonSetStatusApplyConfiguration {\n\tb.NumberReady = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100022772,"name":"WithObservedGeneration","signature":"func (b *DaemonSetStatusApplyConfiguration) WithObservedGeneration(value int64) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonsetstatus.go","code":"// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObservedGeneration field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithObservedGeneration(value int64) *DaemonSetStatusApplyConfiguration {\n\tb.ObservedGeneration = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100022773,"name":"WithUpdatedNumberScheduled","signature":"func (b *DaemonSetStatusApplyConfiguration) WithUpdatedNumberScheduled(value int32) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonsetstatus.go","code":"// WithUpdatedNumberScheduled sets the UpdatedNumberScheduled field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UpdatedNumberScheduled field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithUpdatedNumberScheduled(value int32) *DaemonSetStatusApplyConfiguration {\n\tb.UpdatedNumberScheduled = \u0026value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100022774,"name":"WithNumberAvailable","signature":"func (b *DaemonSetStatusApplyConfiguration) WithNumberAvailable(value int32) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonsetstatus.go","code":"// WithNumberAvailable sets the NumberAvailable field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NumberAvailable field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithNumberAvailable(value int32) *DaemonSetStatusApplyConfiguration {\n\tb.NumberAvailable = \u0026value\n\treturn b\n}","line":{"from":90,"to":96}} {"id":100022775,"name":"WithNumberUnavailable","signature":"func (b *DaemonSetStatusApplyConfiguration) WithNumberUnavailable(value int32) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonsetstatus.go","code":"// WithNumberUnavailable sets the NumberUnavailable field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NumberUnavailable field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithNumberUnavailable(value int32) *DaemonSetStatusApplyConfiguration {\n\tb.NumberUnavailable = \u0026value\n\treturn b\n}","line":{"from":98,"to":104}} {"id":100022776,"name":"WithCollisionCount","signature":"func (b *DaemonSetStatusApplyConfiguration) WithCollisionCount(value int32) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonsetstatus.go","code":"// WithCollisionCount sets the CollisionCount field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CollisionCount field is set to the value of the last call.\nfunc (b *DaemonSetStatusApplyConfiguration) WithCollisionCount(value int32) *DaemonSetStatusApplyConfiguration {\n\tb.CollisionCount = \u0026value\n\treturn b\n}","line":{"from":106,"to":112}} {"id":100022777,"name":"WithConditions","signature":"func (b *DaemonSetStatusApplyConfiguration) WithConditions(values ...*DaemonSetConditionApplyConfiguration) *DaemonSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/daemonsetstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *DaemonSetStatusApplyConfiguration) WithConditions(values ...*DaemonSetConditionApplyConfiguration) *DaemonSetStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":114,"to":125}} {"id":100022778,"name":"Deployment","signature":"func Deployment(name, namespace string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deployment.go","code":"// Deployment constructs an declarative configuration of the Deployment type for use with\n// apply.\nfunc Deployment(name, namespace string) *DeploymentApplyConfiguration {\n\tb := \u0026DeploymentApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"Deployment\")\n\tb.WithAPIVersion(\"extensions/v1beta1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100022779,"name":"ExtractDeployment","signature":"func ExtractDeployment(deployment *extensionsv1beta1.Deployment, fieldManager string) (*DeploymentApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deployment.go","code":"// ExtractDeployment extracts the applied configuration owned by fieldManager from\n// deployment. If no managedFields are found in deployment for fieldManager, a\n// DeploymentApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// deployment must be a unmodified Deployment API object that was retrieved from the Kubernetes API.\n// ExtractDeployment provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractDeployment(deployment *extensionsv1beta1.Deployment, fieldManager string) (*DeploymentApplyConfiguration, error) {\n\treturn extractDeployment(deployment, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100022780,"name":"ExtractDeploymentStatus","signature":"func ExtractDeploymentStatus(deployment *extensionsv1beta1.Deployment, fieldManager string) (*DeploymentApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deployment.go","code":"// ExtractDeploymentStatus is the same as ExtractDeployment except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractDeploymentStatus(deployment *extensionsv1beta1.Deployment, fieldManager string) (*DeploymentApplyConfiguration, error) {\n\treturn extractDeployment(deployment, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100022781,"name":"extractDeployment","signature":"func extractDeployment(deployment *extensionsv1beta1.Deployment, fieldManager string, subresource string) (*DeploymentApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deployment.go","code":"func extractDeployment(deployment *extensionsv1beta1.Deployment, fieldManager string, subresource string) (*DeploymentApplyConfiguration, error) {\n\tb := \u0026DeploymentApplyConfiguration{}\n\terr := managedfields.ExtractInto(deployment, internal.Parser().Type(\"io.k8s.api.extensions.v1beta1.Deployment\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(deployment.Name)\n\tb.WithNamespace(deployment.Namespace)\n\n\tb.WithKind(\"Deployment\")\n\tb.WithAPIVersion(\"extensions/v1beta1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100022782,"name":"WithKind","signature":"func (b *DeploymentApplyConfiguration) WithKind(value string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deployment.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithKind(value string) *DeploymentApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100022783,"name":"WithAPIVersion","signature":"func (b *DeploymentApplyConfiguration) WithAPIVersion(value string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deployment.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithAPIVersion(value string) *DeploymentApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100022784,"name":"WithName","signature":"func (b *DeploymentApplyConfiguration) WithName(value string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deployment.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithName(value string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100022785,"name":"WithGenerateName","signature":"func (b *DeploymentApplyConfiguration) WithGenerateName(value string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deployment.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithGenerateName(value string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100022786,"name":"WithNamespace","signature":"func (b *DeploymentApplyConfiguration) WithNamespace(value string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deployment.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithNamespace(value string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100022787,"name":"WithUID","signature":"func (b *DeploymentApplyConfiguration) WithUID(value types.UID) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deployment.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithUID(value types.UID) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100022788,"name":"WithResourceVersion","signature":"func (b *DeploymentApplyConfiguration) WithResourceVersion(value string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deployment.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithResourceVersion(value string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100022789,"name":"WithGeneration","signature":"func (b *DeploymentApplyConfiguration) WithGeneration(value int64) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deployment.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithGeneration(value int64) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100022790,"name":"WithCreationTimestamp","signature":"func (b *DeploymentApplyConfiguration) WithCreationTimestamp(value metav1.Time) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deployment.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithCreationTimestamp(value metav1.Time) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100022791,"name":"WithDeletionTimestamp","signature":"func (b *DeploymentApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deployment.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100022792,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *DeploymentApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deployment.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100022793,"name":"WithLabels","signature":"func (b *DeploymentApplyConfiguration) WithLabels(entries map[string]string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deployment.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *DeploymentApplyConfiguration) WithLabels(entries map[string]string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100022794,"name":"WithAnnotations","signature":"func (b *DeploymentApplyConfiguration) WithAnnotations(entries map[string]string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deployment.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *DeploymentApplyConfiguration) WithAnnotations(entries map[string]string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100022795,"name":"WithOwnerReferences","signature":"func (b *DeploymentApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deployment.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *DeploymentApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100022796,"name":"WithFinalizers","signature":"func (b *DeploymentApplyConfiguration) WithFinalizers(values ...string) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deployment.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *DeploymentApplyConfiguration) WithFinalizers(values ...string) *DeploymentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100022797,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *DeploymentApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deployment.go","code":"func (b *DeploymentApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100022798,"name":"WithSpec","signature":"func (b *DeploymentApplyConfiguration) WithSpec(value *DeploymentSpecApplyConfiguration) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deployment.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithSpec(value *DeploymentSpecApplyConfiguration) *DeploymentApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100022799,"name":"WithStatus","signature":"func (b *DeploymentApplyConfiguration) WithStatus(value *DeploymentStatusApplyConfiguration) *DeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deployment.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *DeploymentApplyConfiguration) WithStatus(value *DeploymentStatusApplyConfiguration) *DeploymentApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100022800,"name":"DeploymentCondition","signature":"func DeploymentCondition() *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentcondition.go","code":"// DeploymentConditionApplyConfiguration constructs an declarative configuration of the DeploymentCondition type for use with\n// apply.\nfunc DeploymentCondition() *DeploymentConditionApplyConfiguration {\n\treturn \u0026DeploymentConditionApplyConfiguration{}\n}","line":{"from":38,"to":42}} {"id":100022801,"name":"WithType","signature":"func (b *DeploymentConditionApplyConfiguration) WithType(value v1beta1.DeploymentConditionType) *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentcondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *DeploymentConditionApplyConfiguration) WithType(value v1beta1.DeploymentConditionType) *DeploymentConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100022802,"name":"WithStatus","signature":"func (b *DeploymentConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentcondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *DeploymentConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *DeploymentConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100022803,"name":"WithLastUpdateTime","signature":"func (b *DeploymentConditionApplyConfiguration) WithLastUpdateTime(value metav1.Time) *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentcondition.go","code":"// WithLastUpdateTime sets the LastUpdateTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastUpdateTime field is set to the value of the last call.\nfunc (b *DeploymentConditionApplyConfiguration) WithLastUpdateTime(value metav1.Time) *DeploymentConditionApplyConfiguration {\n\tb.LastUpdateTime = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100022804,"name":"WithLastTransitionTime","signature":"func (b *DeploymentConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentcondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *DeploymentConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *DeploymentConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":68,"to":74}} {"id":100022805,"name":"WithReason","signature":"func (b *DeploymentConditionApplyConfiguration) WithReason(value string) *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentcondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *DeploymentConditionApplyConfiguration) WithReason(value string) *DeploymentConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":76,"to":82}} {"id":100022806,"name":"WithMessage","signature":"func (b *DeploymentConditionApplyConfiguration) WithMessage(value string) *DeploymentConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentcondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *DeploymentConditionApplyConfiguration) WithMessage(value string) *DeploymentConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100022807,"name":"DeploymentSpec","signature":"func DeploymentSpec() *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentspec.go","code":"// DeploymentSpecApplyConfiguration constructs an declarative configuration of the DeploymentSpec type for use with\n// apply.\nfunc DeploymentSpec() *DeploymentSpecApplyConfiguration {\n\treturn \u0026DeploymentSpecApplyConfiguration{}\n}","line":{"from":40,"to":44}} {"id":100022808,"name":"WithReplicas","signature":"func (b *DeploymentSpecApplyConfiguration) WithReplicas(value int32) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentspec.go","code":"// WithReplicas sets the Replicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Replicas field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithReplicas(value int32) *DeploymentSpecApplyConfiguration {\n\tb.Replicas = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100022809,"name":"WithSelector","signature":"func (b *DeploymentSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentspec.go","code":"// WithSelector sets the Selector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Selector field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *DeploymentSpecApplyConfiguration {\n\tb.Selector = value\n\treturn b\n}","line":{"from":54,"to":60}} {"id":100022810,"name":"WithTemplate","signature":"func (b *DeploymentSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentspec.go","code":"// WithTemplate sets the Template field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Template field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *DeploymentSpecApplyConfiguration {\n\tb.Template = value\n\treturn b\n}","line":{"from":62,"to":68}} {"id":100022811,"name":"WithStrategy","signature":"func (b *DeploymentSpecApplyConfiguration) WithStrategy(value *DeploymentStrategyApplyConfiguration) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentspec.go","code":"// WithStrategy sets the Strategy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Strategy field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithStrategy(value *DeploymentStrategyApplyConfiguration) *DeploymentSpecApplyConfiguration {\n\tb.Strategy = value\n\treturn b\n}","line":{"from":70,"to":76}} {"id":100022812,"name":"WithMinReadySeconds","signature":"func (b *DeploymentSpecApplyConfiguration) WithMinReadySeconds(value int32) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentspec.go","code":"// WithMinReadySeconds sets the MinReadySeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MinReadySeconds field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithMinReadySeconds(value int32) *DeploymentSpecApplyConfiguration {\n\tb.MinReadySeconds = \u0026value\n\treturn b\n}","line":{"from":78,"to":84}} {"id":100022813,"name":"WithRevisionHistoryLimit","signature":"func (b *DeploymentSpecApplyConfiguration) WithRevisionHistoryLimit(value int32) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentspec.go","code":"// WithRevisionHistoryLimit sets the RevisionHistoryLimit field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RevisionHistoryLimit field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithRevisionHistoryLimit(value int32) *DeploymentSpecApplyConfiguration {\n\tb.RevisionHistoryLimit = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100022814,"name":"WithPaused","signature":"func (b *DeploymentSpecApplyConfiguration) WithPaused(value bool) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentspec.go","code":"// WithPaused sets the Paused field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Paused field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithPaused(value bool) *DeploymentSpecApplyConfiguration {\n\tb.Paused = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100022815,"name":"WithRollbackTo","signature":"func (b *DeploymentSpecApplyConfiguration) WithRollbackTo(value *RollbackConfigApplyConfiguration) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentspec.go","code":"// WithRollbackTo sets the RollbackTo field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RollbackTo field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithRollbackTo(value *RollbackConfigApplyConfiguration) *DeploymentSpecApplyConfiguration {\n\tb.RollbackTo = value\n\treturn b\n}","line":{"from":102,"to":108}} {"id":100022816,"name":"WithProgressDeadlineSeconds","signature":"func (b *DeploymentSpecApplyConfiguration) WithProgressDeadlineSeconds(value int32) *DeploymentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentspec.go","code":"// WithProgressDeadlineSeconds sets the ProgressDeadlineSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ProgressDeadlineSeconds field is set to the value of the last call.\nfunc (b *DeploymentSpecApplyConfiguration) WithProgressDeadlineSeconds(value int32) *DeploymentSpecApplyConfiguration {\n\tb.ProgressDeadlineSeconds = \u0026value\n\treturn b\n}","line":{"from":110,"to":116}} {"id":100022817,"name":"DeploymentStatus","signature":"func DeploymentStatus() *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentstatus.go","code":"// DeploymentStatusApplyConfiguration constructs an declarative configuration of the DeploymentStatus type for use with\n// apply.\nfunc DeploymentStatus() *DeploymentStatusApplyConfiguration {\n\treturn \u0026DeploymentStatusApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100022818,"name":"WithObservedGeneration","signature":"func (b *DeploymentStatusApplyConfiguration) WithObservedGeneration(value int64) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentstatus.go","code":"// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObservedGeneration field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithObservedGeneration(value int64) *DeploymentStatusApplyConfiguration {\n\tb.ObservedGeneration = \u0026value\n\treturn b\n}","line":{"from":40,"to":46}} {"id":100022819,"name":"WithReplicas","signature":"func (b *DeploymentStatusApplyConfiguration) WithReplicas(value int32) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentstatus.go","code":"// WithReplicas sets the Replicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Replicas field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithReplicas(value int32) *DeploymentStatusApplyConfiguration {\n\tb.Replicas = \u0026value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100022820,"name":"WithUpdatedReplicas","signature":"func (b *DeploymentStatusApplyConfiguration) WithUpdatedReplicas(value int32) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentstatus.go","code":"// WithUpdatedReplicas sets the UpdatedReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UpdatedReplicas field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithUpdatedReplicas(value int32) *DeploymentStatusApplyConfiguration {\n\tb.UpdatedReplicas = \u0026value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100022821,"name":"WithReadyReplicas","signature":"func (b *DeploymentStatusApplyConfiguration) WithReadyReplicas(value int32) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentstatus.go","code":"// WithReadyReplicas sets the ReadyReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadyReplicas field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithReadyReplicas(value int32) *DeploymentStatusApplyConfiguration {\n\tb.ReadyReplicas = \u0026value\n\treturn b\n}","line":{"from":64,"to":70}} {"id":100022822,"name":"WithAvailableReplicas","signature":"func (b *DeploymentStatusApplyConfiguration) WithAvailableReplicas(value int32) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentstatus.go","code":"// WithAvailableReplicas sets the AvailableReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AvailableReplicas field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithAvailableReplicas(value int32) *DeploymentStatusApplyConfiguration {\n\tb.AvailableReplicas = \u0026value\n\treturn b\n}","line":{"from":72,"to":78}} {"id":100022823,"name":"WithUnavailableReplicas","signature":"func (b *DeploymentStatusApplyConfiguration) WithUnavailableReplicas(value int32) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentstatus.go","code":"// WithUnavailableReplicas sets the UnavailableReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UnavailableReplicas field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithUnavailableReplicas(value int32) *DeploymentStatusApplyConfiguration {\n\tb.UnavailableReplicas = \u0026value\n\treturn b\n}","line":{"from":80,"to":86}} {"id":100022824,"name":"WithConditions","signature":"func (b *DeploymentStatusApplyConfiguration) WithConditions(values ...*DeploymentConditionApplyConfiguration) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *DeploymentStatusApplyConfiguration) WithConditions(values ...*DeploymentConditionApplyConfiguration) *DeploymentStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":88,"to":99}} {"id":100022825,"name":"WithCollisionCount","signature":"func (b *DeploymentStatusApplyConfiguration) WithCollisionCount(value int32) *DeploymentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentstatus.go","code":"// WithCollisionCount sets the CollisionCount field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CollisionCount field is set to the value of the last call.\nfunc (b *DeploymentStatusApplyConfiguration) WithCollisionCount(value int32) *DeploymentStatusApplyConfiguration {\n\tb.CollisionCount = \u0026value\n\treturn b\n}","line":{"from":101,"to":107}} {"id":100022826,"name":"DeploymentStrategy","signature":"func DeploymentStrategy() *DeploymentStrategyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentstrategy.go","code":"// DeploymentStrategyApplyConfiguration constructs an declarative configuration of the DeploymentStrategy type for use with\n// apply.\nfunc DeploymentStrategy() *DeploymentStrategyApplyConfiguration {\n\treturn \u0026DeploymentStrategyApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100022827,"name":"WithType","signature":"func (b *DeploymentStrategyApplyConfiguration) WithType(value v1beta1.DeploymentStrategyType) *DeploymentStrategyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentstrategy.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *DeploymentStrategyApplyConfiguration) WithType(value v1beta1.DeploymentStrategyType) *DeploymentStrategyApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100022828,"name":"WithRollingUpdate","signature":"func (b *DeploymentStrategyApplyConfiguration) WithRollingUpdate(value *RollingUpdateDeploymentApplyConfiguration) *DeploymentStrategyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/deploymentstrategy.go","code":"// WithRollingUpdate sets the RollingUpdate field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RollingUpdate field is set to the value of the last call.\nfunc (b *DeploymentStrategyApplyConfiguration) WithRollingUpdate(value *RollingUpdateDeploymentApplyConfiguration) *DeploymentStrategyApplyConfiguration {\n\tb.RollingUpdate = value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100022829,"name":"HTTPIngressPath","signature":"func HTTPIngressPath() *HTTPIngressPathApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/httpingresspath.go","code":"// HTTPIngressPathApplyConfiguration constructs an declarative configuration of the HTTPIngressPath type for use with\n// apply.\nfunc HTTPIngressPath() *HTTPIngressPathApplyConfiguration {\n\treturn \u0026HTTPIngressPathApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100022830,"name":"WithPath","signature":"func (b *HTTPIngressPathApplyConfiguration) WithPath(value string) *HTTPIngressPathApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/httpingresspath.go","code":"// WithPath sets the Path field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Path field is set to the value of the last call.\nfunc (b *HTTPIngressPathApplyConfiguration) WithPath(value string) *HTTPIngressPathApplyConfiguration {\n\tb.Path = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100022831,"name":"WithPathType","signature":"func (b *HTTPIngressPathApplyConfiguration) WithPathType(value v1beta1.PathType) *HTTPIngressPathApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/httpingresspath.go","code":"// WithPathType sets the PathType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PathType field is set to the value of the last call.\nfunc (b *HTTPIngressPathApplyConfiguration) WithPathType(value v1beta1.PathType) *HTTPIngressPathApplyConfiguration {\n\tb.PathType = \u0026value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100022832,"name":"WithBackend","signature":"func (b *HTTPIngressPathApplyConfiguration) WithBackend(value *IngressBackendApplyConfiguration) *HTTPIngressPathApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/httpingresspath.go","code":"// WithBackend sets the Backend field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Backend field is set to the value of the last call.\nfunc (b *HTTPIngressPathApplyConfiguration) WithBackend(value *IngressBackendApplyConfiguration) *HTTPIngressPathApplyConfiguration {\n\tb.Backend = value\n\treturn b\n}","line":{"from":55,"to":61}} {"id":100022833,"name":"HTTPIngressRuleValue","signature":"func HTTPIngressRuleValue() *HTTPIngressRuleValueApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/httpingressrulevalue.go","code":"// HTTPIngressRuleValueApplyConfiguration constructs an declarative configuration of the HTTPIngressRuleValue type for use with\n// apply.\nfunc HTTPIngressRuleValue() *HTTPIngressRuleValueApplyConfiguration {\n\treturn \u0026HTTPIngressRuleValueApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100022834,"name":"WithPaths","signature":"func (b *HTTPIngressRuleValueApplyConfiguration) WithPaths(values ...*HTTPIngressPathApplyConfiguration) *HTTPIngressRuleValueApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/httpingressrulevalue.go","code":"// WithPaths adds the given value to the Paths field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Paths field.\nfunc (b *HTTPIngressRuleValueApplyConfiguration) WithPaths(values ...*HTTPIngressPathApplyConfiguration) *HTTPIngressRuleValueApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPaths\")\n\t\t}\n\t\tb.Paths = append(b.Paths, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100022835,"name":"Ingress","signature":"func Ingress(name, namespace string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingress.go","code":"// Ingress constructs an declarative configuration of the Ingress type for use with\n// apply.\nfunc Ingress(name, namespace string) *IngressApplyConfiguration {\n\tb := \u0026IngressApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"Ingress\")\n\tb.WithAPIVersion(\"extensions/v1beta1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100022836,"name":"ExtractIngress","signature":"func ExtractIngress(ingress *extensionsv1beta1.Ingress, fieldManager string) (*IngressApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingress.go","code":"// ExtractIngress extracts the applied configuration owned by fieldManager from\n// ingress. If no managedFields are found in ingress for fieldManager, a\n// IngressApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// ingress must be a unmodified Ingress API object that was retrieved from the Kubernetes API.\n// ExtractIngress provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractIngress(ingress *extensionsv1beta1.Ingress, fieldManager string) (*IngressApplyConfiguration, error) {\n\treturn extractIngress(ingress, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100022837,"name":"ExtractIngressStatus","signature":"func ExtractIngressStatus(ingress *extensionsv1beta1.Ingress, fieldManager string) (*IngressApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingress.go","code":"// ExtractIngressStatus is the same as ExtractIngress except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractIngressStatus(ingress *extensionsv1beta1.Ingress, fieldManager string) (*IngressApplyConfiguration, error) {\n\treturn extractIngress(ingress, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100022838,"name":"extractIngress","signature":"func extractIngress(ingress *extensionsv1beta1.Ingress, fieldManager string, subresource string) (*IngressApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingress.go","code":"func extractIngress(ingress *extensionsv1beta1.Ingress, fieldManager string, subresource string) (*IngressApplyConfiguration, error) {\n\tb := \u0026IngressApplyConfiguration{}\n\terr := managedfields.ExtractInto(ingress, internal.Parser().Type(\"io.k8s.api.extensions.v1beta1.Ingress\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(ingress.Name)\n\tb.WithNamespace(ingress.Namespace)\n\n\tb.WithKind(\"Ingress\")\n\tb.WithAPIVersion(\"extensions/v1beta1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100022839,"name":"WithKind","signature":"func (b *IngressApplyConfiguration) WithKind(value string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingress.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithKind(value string) *IngressApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100022840,"name":"WithAPIVersion","signature":"func (b *IngressApplyConfiguration) WithAPIVersion(value string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingress.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithAPIVersion(value string) *IngressApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100022841,"name":"WithName","signature":"func (b *IngressApplyConfiguration) WithName(value string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingress.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithName(value string) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100022842,"name":"WithGenerateName","signature":"func (b *IngressApplyConfiguration) WithGenerateName(value string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingress.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithGenerateName(value string) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100022843,"name":"WithNamespace","signature":"func (b *IngressApplyConfiguration) WithNamespace(value string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingress.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithNamespace(value string) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100022844,"name":"WithUID","signature":"func (b *IngressApplyConfiguration) WithUID(value types.UID) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingress.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithUID(value types.UID) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100022845,"name":"WithResourceVersion","signature":"func (b *IngressApplyConfiguration) WithResourceVersion(value string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingress.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithResourceVersion(value string) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100022846,"name":"WithGeneration","signature":"func (b *IngressApplyConfiguration) WithGeneration(value int64) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingress.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithGeneration(value int64) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100022847,"name":"WithCreationTimestamp","signature":"func (b *IngressApplyConfiguration) WithCreationTimestamp(value metav1.Time) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingress.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithCreationTimestamp(value metav1.Time) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100022848,"name":"WithDeletionTimestamp","signature":"func (b *IngressApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingress.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100022849,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *IngressApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingress.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100022850,"name":"WithLabels","signature":"func (b *IngressApplyConfiguration) WithLabels(entries map[string]string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingress.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *IngressApplyConfiguration) WithLabels(entries map[string]string) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100022851,"name":"WithAnnotations","signature":"func (b *IngressApplyConfiguration) WithAnnotations(entries map[string]string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingress.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *IngressApplyConfiguration) WithAnnotations(entries map[string]string) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100022852,"name":"WithOwnerReferences","signature":"func (b *IngressApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingress.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *IngressApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100022853,"name":"WithFinalizers","signature":"func (b *IngressApplyConfiguration) WithFinalizers(values ...string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingress.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *IngressApplyConfiguration) WithFinalizers(values ...string) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100022854,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *IngressApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingress.go","code":"func (b *IngressApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100022855,"name":"WithSpec","signature":"func (b *IngressApplyConfiguration) WithSpec(value *IngressSpecApplyConfiguration) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingress.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithSpec(value *IngressSpecApplyConfiguration) *IngressApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100022856,"name":"WithStatus","signature":"func (b *IngressApplyConfiguration) WithStatus(value *IngressStatusApplyConfiguration) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingress.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithStatus(value *IngressStatusApplyConfiguration) *IngressApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100022857,"name":"IngressBackend","signature":"func IngressBackend() *IngressBackendApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressbackend.go","code":"// IngressBackendApplyConfiguration constructs an declarative configuration of the IngressBackend type for use with\n// apply.\nfunc IngressBackend() *IngressBackendApplyConfiguration {\n\treturn \u0026IngressBackendApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100022858,"name":"WithServiceName","signature":"func (b *IngressBackendApplyConfiguration) WithServiceName(value string) *IngressBackendApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressbackend.go","code":"// WithServiceName sets the ServiceName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ServiceName field is set to the value of the last call.\nfunc (b *IngressBackendApplyConfiguration) WithServiceName(value string) *IngressBackendApplyConfiguration {\n\tb.ServiceName = \u0026value\n\treturn b\n}","line":{"from":40,"to":46}} {"id":100022859,"name":"WithServicePort","signature":"func (b *IngressBackendApplyConfiguration) WithServicePort(value intstr.IntOrString) *IngressBackendApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressbackend.go","code":"// WithServicePort sets the ServicePort field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ServicePort field is set to the value of the last call.\nfunc (b *IngressBackendApplyConfiguration) WithServicePort(value intstr.IntOrString) *IngressBackendApplyConfiguration {\n\tb.ServicePort = \u0026value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100022860,"name":"WithResource","signature":"func (b *IngressBackendApplyConfiguration) WithResource(value *v1.TypedLocalObjectReferenceApplyConfiguration) *IngressBackendApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressbackend.go","code":"// WithResource sets the Resource field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Resource field is set to the value of the last call.\nfunc (b *IngressBackendApplyConfiguration) WithResource(value *v1.TypedLocalObjectReferenceApplyConfiguration) *IngressBackendApplyConfiguration {\n\tb.Resource = value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100022861,"name":"IngressLoadBalancerIngress","signature":"func IngressLoadBalancerIngress() *IngressLoadBalancerIngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressloadbalanceringress.go","code":"// IngressLoadBalancerIngressApplyConfiguration constructs an declarative configuration of the IngressLoadBalancerIngress type for use with\n// apply.\nfunc IngressLoadBalancerIngress() *IngressLoadBalancerIngressApplyConfiguration {\n\treturn \u0026IngressLoadBalancerIngressApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100022862,"name":"WithIP","signature":"func (b *IngressLoadBalancerIngressApplyConfiguration) WithIP(value string) *IngressLoadBalancerIngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressloadbalanceringress.go","code":"// WithIP sets the IP field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the IP field is set to the value of the last call.\nfunc (b *IngressLoadBalancerIngressApplyConfiguration) WithIP(value string) *IngressLoadBalancerIngressApplyConfiguration {\n\tb.IP = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100022863,"name":"WithHostname","signature":"func (b *IngressLoadBalancerIngressApplyConfiguration) WithHostname(value string) *IngressLoadBalancerIngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressloadbalanceringress.go","code":"// WithHostname sets the Hostname field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Hostname field is set to the value of the last call.\nfunc (b *IngressLoadBalancerIngressApplyConfiguration) WithHostname(value string) *IngressLoadBalancerIngressApplyConfiguration {\n\tb.Hostname = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100022864,"name":"WithPorts","signature":"func (b *IngressLoadBalancerIngressApplyConfiguration) WithPorts(values ...*IngressPortStatusApplyConfiguration) *IngressLoadBalancerIngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressloadbalanceringress.go","code":"// WithPorts adds the given value to the Ports field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Ports field.\nfunc (b *IngressLoadBalancerIngressApplyConfiguration) WithPorts(values ...*IngressPortStatusApplyConfiguration) *IngressLoadBalancerIngressApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPorts\")\n\t\t}\n\t\tb.Ports = append(b.Ports, *values[i])\n\t}\n\treturn b\n}","line":{"from":51,"to":62}} {"id":100022865,"name":"IngressLoadBalancerStatus","signature":"func IngressLoadBalancerStatus() *IngressLoadBalancerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressloadbalancerstatus.go","code":"// IngressLoadBalancerStatusApplyConfiguration constructs an declarative configuration of the IngressLoadBalancerStatus type for use with\n// apply.\nfunc IngressLoadBalancerStatus() *IngressLoadBalancerStatusApplyConfiguration {\n\treturn \u0026IngressLoadBalancerStatusApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100022866,"name":"WithIngress","signature":"func (b *IngressLoadBalancerStatusApplyConfiguration) WithIngress(values ...*IngressLoadBalancerIngressApplyConfiguration) *IngressLoadBalancerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressloadbalancerstatus.go","code":"// WithIngress adds the given value to the Ingress field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Ingress field.\nfunc (b *IngressLoadBalancerStatusApplyConfiguration) WithIngress(values ...*IngressLoadBalancerIngressApplyConfiguration) *IngressLoadBalancerStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithIngress\")\n\t\t}\n\t\tb.Ingress = append(b.Ingress, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100022867,"name":"IngressPortStatus","signature":"func IngressPortStatus() *IngressPortStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressportstatus.go","code":"// IngressPortStatusApplyConfiguration constructs an declarative configuration of the IngressPortStatus type for use with\n// apply.\nfunc IngressPortStatus() *IngressPortStatusApplyConfiguration {\n\treturn \u0026IngressPortStatusApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100022868,"name":"WithPort","signature":"func (b *IngressPortStatusApplyConfiguration) WithPort(value int32) *IngressPortStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressportstatus.go","code":"// WithPort sets the Port field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Port field is set to the value of the last call.\nfunc (b *IngressPortStatusApplyConfiguration) WithPort(value int32) *IngressPortStatusApplyConfiguration {\n\tb.Port = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100022869,"name":"WithProtocol","signature":"func (b *IngressPortStatusApplyConfiguration) WithProtocol(value v1.Protocol) *IngressPortStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressportstatus.go","code":"// WithProtocol sets the Protocol field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Protocol field is set to the value of the last call.\nfunc (b *IngressPortStatusApplyConfiguration) WithProtocol(value v1.Protocol) *IngressPortStatusApplyConfiguration {\n\tb.Protocol = \u0026value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100022870,"name":"WithError","signature":"func (b *IngressPortStatusApplyConfiguration) WithError(value string) *IngressPortStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressportstatus.go","code":"// WithError sets the Error field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Error field is set to the value of the last call.\nfunc (b *IngressPortStatusApplyConfiguration) WithError(value string) *IngressPortStatusApplyConfiguration {\n\tb.Error = \u0026value\n\treturn b\n}","line":{"from":55,"to":61}} {"id":100022871,"name":"IngressRule","signature":"func IngressRule() *IngressRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressrule.go","code":"// IngressRuleApplyConfiguration constructs an declarative configuration of the IngressRule type for use with\n// apply.\nfunc IngressRule() *IngressRuleApplyConfiguration {\n\treturn \u0026IngressRuleApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100022872,"name":"WithHost","signature":"func (b *IngressRuleApplyConfiguration) WithHost(value string) *IngressRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressrule.go","code":"// WithHost sets the Host field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Host field is set to the value of the last call.\nfunc (b *IngressRuleApplyConfiguration) WithHost(value string) *IngressRuleApplyConfiguration {\n\tb.Host = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100022873,"name":"WithHTTP","signature":"func (b *IngressRuleApplyConfiguration) WithHTTP(value *HTTPIngressRuleValueApplyConfiguration) *IngressRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressrule.go","code":"// WithHTTP sets the HTTP field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HTTP field is set to the value of the last call.\nfunc (b *IngressRuleApplyConfiguration) WithHTTP(value *HTTPIngressRuleValueApplyConfiguration) *IngressRuleApplyConfiguration {\n\tb.HTTP = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100022874,"name":"IngressRuleValue","signature":"func IngressRuleValue() *IngressRuleValueApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressrulevalue.go","code":"// IngressRuleValueApplyConfiguration constructs an declarative configuration of the IngressRuleValue type for use with\n// apply.\nfunc IngressRuleValue() *IngressRuleValueApplyConfiguration {\n\treturn \u0026IngressRuleValueApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100022875,"name":"WithHTTP","signature":"func (b *IngressRuleValueApplyConfiguration) WithHTTP(value *HTTPIngressRuleValueApplyConfiguration) *IngressRuleValueApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressrulevalue.go","code":"// WithHTTP sets the HTTP field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HTTP field is set to the value of the last call.\nfunc (b *IngressRuleValueApplyConfiguration) WithHTTP(value *HTTPIngressRuleValueApplyConfiguration) *IngressRuleValueApplyConfiguration {\n\tb.HTTP = value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100022876,"name":"IngressSpec","signature":"func IngressSpec() *IngressSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressspec.go","code":"// IngressSpecApplyConfiguration constructs an declarative configuration of the IngressSpec type for use with\n// apply.\nfunc IngressSpec() *IngressSpecApplyConfiguration {\n\treturn \u0026IngressSpecApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100022877,"name":"WithIngressClassName","signature":"func (b *IngressSpecApplyConfiguration) WithIngressClassName(value string) *IngressSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressspec.go","code":"// WithIngressClassName sets the IngressClassName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the IngressClassName field is set to the value of the last call.\nfunc (b *IngressSpecApplyConfiguration) WithIngressClassName(value string) *IngressSpecApplyConfiguration {\n\tb.IngressClassName = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100022878,"name":"WithBackend","signature":"func (b *IngressSpecApplyConfiguration) WithBackend(value *IngressBackendApplyConfiguration) *IngressSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressspec.go","code":"// WithBackend sets the Backend field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Backend field is set to the value of the last call.\nfunc (b *IngressSpecApplyConfiguration) WithBackend(value *IngressBackendApplyConfiguration) *IngressSpecApplyConfiguration {\n\tb.Backend = value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100022879,"name":"WithTLS","signature":"func (b *IngressSpecApplyConfiguration) WithTLS(values ...*IngressTLSApplyConfiguration) *IngressSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressspec.go","code":"// WithTLS adds the given value to the TLS field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the TLS field.\nfunc (b *IngressSpecApplyConfiguration) WithTLS(values ...*IngressTLSApplyConfiguration) *IngressSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithTLS\")\n\t\t}\n\t\tb.TLS = append(b.TLS, *values[i])\n\t}\n\treturn b\n}","line":{"from":52,"to":63}} {"id":100022880,"name":"WithRules","signature":"func (b *IngressSpecApplyConfiguration) WithRules(values ...*IngressRuleApplyConfiguration) *IngressSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressspec.go","code":"// WithRules adds the given value to the Rules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Rules field.\nfunc (b *IngressSpecApplyConfiguration) WithRules(values ...*IngressRuleApplyConfiguration) *IngressSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRules\")\n\t\t}\n\t\tb.Rules = append(b.Rules, *values[i])\n\t}\n\treturn b\n}","line":{"from":65,"to":76}} {"id":100022881,"name":"IngressStatus","signature":"func IngressStatus() *IngressStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressstatus.go","code":"// IngressStatusApplyConfiguration constructs an declarative configuration of the IngressStatus type for use with\n// apply.\nfunc IngressStatus() *IngressStatusApplyConfiguration {\n\treturn \u0026IngressStatusApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100022882,"name":"WithLoadBalancer","signature":"func (b *IngressStatusApplyConfiguration) WithLoadBalancer(value *IngressLoadBalancerStatusApplyConfiguration) *IngressStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingressstatus.go","code":"// WithLoadBalancer sets the LoadBalancer field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LoadBalancer field is set to the value of the last call.\nfunc (b *IngressStatusApplyConfiguration) WithLoadBalancer(value *IngressLoadBalancerStatusApplyConfiguration) *IngressStatusApplyConfiguration {\n\tb.LoadBalancer = value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100022883,"name":"IngressTLS","signature":"func IngressTLS() *IngressTLSApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingresstls.go","code":"// IngressTLSApplyConfiguration constructs an declarative configuration of the IngressTLS type for use with\n// apply.\nfunc IngressTLS() *IngressTLSApplyConfiguration {\n\treturn \u0026IngressTLSApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100022884,"name":"WithHosts","signature":"func (b *IngressTLSApplyConfiguration) WithHosts(values ...string) *IngressTLSApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingresstls.go","code":"// WithHosts adds the given value to the Hosts field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Hosts field.\nfunc (b *IngressTLSApplyConfiguration) WithHosts(values ...string) *IngressTLSApplyConfiguration {\n\tfor i := range values {\n\t\tb.Hosts = append(b.Hosts, values[i])\n\t}\n\treturn b\n}","line":{"from":34,"to":42}} {"id":100022885,"name":"WithSecretName","signature":"func (b *IngressTLSApplyConfiguration) WithSecretName(value string) *IngressTLSApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ingresstls.go","code":"// WithSecretName sets the SecretName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecretName field is set to the value of the last call.\nfunc (b *IngressTLSApplyConfiguration) WithSecretName(value string) *IngressTLSApplyConfiguration {\n\tb.SecretName = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100022886,"name":"IPBlock","signature":"func IPBlock() *IPBlockApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ipblock.go","code":"// IPBlockApplyConfiguration constructs an declarative configuration of the IPBlock type for use with\n// apply.\nfunc IPBlock() *IPBlockApplyConfiguration {\n\treturn \u0026IPBlockApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100022887,"name":"WithCIDR","signature":"func (b *IPBlockApplyConfiguration) WithCIDR(value string) *IPBlockApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ipblock.go","code":"// WithCIDR sets the CIDR field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CIDR field is set to the value of the last call.\nfunc (b *IPBlockApplyConfiguration) WithCIDR(value string) *IPBlockApplyConfiguration {\n\tb.CIDR = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100022888,"name":"WithExcept","signature":"func (b *IPBlockApplyConfiguration) WithExcept(values ...string) *IPBlockApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/ipblock.go","code":"// WithExcept adds the given value to the Except field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Except field.\nfunc (b *IPBlockApplyConfiguration) WithExcept(values ...string) *IPBlockApplyConfiguration {\n\tfor i := range values {\n\t\tb.Except = append(b.Except, values[i])\n\t}\n\treturn b\n}","line":{"from":42,"to":50}} {"id":100022889,"name":"NetworkPolicy","signature":"func NetworkPolicy(name, namespace string) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicy.go","code":"// NetworkPolicy constructs an declarative configuration of the NetworkPolicy type for use with\n// apply.\nfunc NetworkPolicy(name, namespace string) *NetworkPolicyApplyConfiguration {\n\tb := \u0026NetworkPolicyApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"NetworkPolicy\")\n\tb.WithAPIVersion(\"extensions/v1beta1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100022890,"name":"ExtractNetworkPolicy","signature":"func ExtractNetworkPolicy(networkPolicy *extensionsv1beta1.NetworkPolicy, fieldManager string) (*NetworkPolicyApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicy.go","code":"// ExtractNetworkPolicy extracts the applied configuration owned by fieldManager from\n// networkPolicy. If no managedFields are found in networkPolicy for fieldManager, a\n// NetworkPolicyApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// networkPolicy must be a unmodified NetworkPolicy API object that was retrieved from the Kubernetes API.\n// ExtractNetworkPolicy provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractNetworkPolicy(networkPolicy *extensionsv1beta1.NetworkPolicy, fieldManager string) (*NetworkPolicyApplyConfiguration, error) {\n\treturn extractNetworkPolicy(networkPolicy, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100022891,"name":"ExtractNetworkPolicyStatus","signature":"func ExtractNetworkPolicyStatus(networkPolicy *extensionsv1beta1.NetworkPolicy, fieldManager string) (*NetworkPolicyApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicy.go","code":"// ExtractNetworkPolicyStatus is the same as ExtractNetworkPolicy except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractNetworkPolicyStatus(networkPolicy *extensionsv1beta1.NetworkPolicy, fieldManager string) (*NetworkPolicyApplyConfiguration, error) {\n\treturn extractNetworkPolicy(networkPolicy, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100022892,"name":"extractNetworkPolicy","signature":"func extractNetworkPolicy(networkPolicy *extensionsv1beta1.NetworkPolicy, fieldManager string, subresource string) (*NetworkPolicyApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicy.go","code":"func extractNetworkPolicy(networkPolicy *extensionsv1beta1.NetworkPolicy, fieldManager string, subresource string) (*NetworkPolicyApplyConfiguration, error) {\n\tb := \u0026NetworkPolicyApplyConfiguration{}\n\terr := managedfields.ExtractInto(networkPolicy, internal.Parser().Type(\"io.k8s.api.extensions.v1beta1.NetworkPolicy\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(networkPolicy.Name)\n\tb.WithNamespace(networkPolicy.Namespace)\n\n\tb.WithKind(\"NetworkPolicy\")\n\tb.WithAPIVersion(\"extensions/v1beta1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100022893,"name":"WithKind","signature":"func (b *NetworkPolicyApplyConfiguration) WithKind(value string) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicy.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *NetworkPolicyApplyConfiguration) WithKind(value string) *NetworkPolicyApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100022894,"name":"WithAPIVersion","signature":"func (b *NetworkPolicyApplyConfiguration) WithAPIVersion(value string) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicy.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *NetworkPolicyApplyConfiguration) WithAPIVersion(value string) *NetworkPolicyApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100022895,"name":"WithName","signature":"func (b *NetworkPolicyApplyConfiguration) WithName(value string) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicy.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *NetworkPolicyApplyConfiguration) WithName(value string) *NetworkPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100022896,"name":"WithGenerateName","signature":"func (b *NetworkPolicyApplyConfiguration) WithGenerateName(value string) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicy.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *NetworkPolicyApplyConfiguration) WithGenerateName(value string) *NetworkPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100022897,"name":"WithNamespace","signature":"func (b *NetworkPolicyApplyConfiguration) WithNamespace(value string) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicy.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *NetworkPolicyApplyConfiguration) WithNamespace(value string) *NetworkPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100022898,"name":"WithUID","signature":"func (b *NetworkPolicyApplyConfiguration) WithUID(value types.UID) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicy.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *NetworkPolicyApplyConfiguration) WithUID(value types.UID) *NetworkPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100022899,"name":"WithResourceVersion","signature":"func (b *NetworkPolicyApplyConfiguration) WithResourceVersion(value string) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicy.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *NetworkPolicyApplyConfiguration) WithResourceVersion(value string) *NetworkPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100022900,"name":"WithGeneration","signature":"func (b *NetworkPolicyApplyConfiguration) WithGeneration(value int64) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicy.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *NetworkPolicyApplyConfiguration) WithGeneration(value int64) *NetworkPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100022901,"name":"WithCreationTimestamp","signature":"func (b *NetworkPolicyApplyConfiguration) WithCreationTimestamp(value metav1.Time) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicy.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *NetworkPolicyApplyConfiguration) WithCreationTimestamp(value metav1.Time) *NetworkPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100022902,"name":"WithDeletionTimestamp","signature":"func (b *NetworkPolicyApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicy.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *NetworkPolicyApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *NetworkPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100022903,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *NetworkPolicyApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicy.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *NetworkPolicyApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *NetworkPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100022904,"name":"WithLabels","signature":"func (b *NetworkPolicyApplyConfiguration) WithLabels(entries map[string]string) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicy.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *NetworkPolicyApplyConfiguration) WithLabels(entries map[string]string) *NetworkPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100022905,"name":"WithAnnotations","signature":"func (b *NetworkPolicyApplyConfiguration) WithAnnotations(entries map[string]string) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicy.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *NetworkPolicyApplyConfiguration) WithAnnotations(entries map[string]string) *NetworkPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100022906,"name":"WithOwnerReferences","signature":"func (b *NetworkPolicyApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicy.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *NetworkPolicyApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *NetworkPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100022907,"name":"WithFinalizers","signature":"func (b *NetworkPolicyApplyConfiguration) WithFinalizers(values ...string) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicy.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *NetworkPolicyApplyConfiguration) WithFinalizers(values ...string) *NetworkPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100022908,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *NetworkPolicyApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicy.go","code":"func (b *NetworkPolicyApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100022909,"name":"WithSpec","signature":"func (b *NetworkPolicyApplyConfiguration) WithSpec(value *NetworkPolicySpecApplyConfiguration) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicy.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *NetworkPolicyApplyConfiguration) WithSpec(value *NetworkPolicySpecApplyConfiguration) *NetworkPolicyApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100022910,"name":"WithStatus","signature":"func (b *NetworkPolicyApplyConfiguration) WithStatus(value *NetworkPolicyStatusApplyConfiguration) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicy.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *NetworkPolicyApplyConfiguration) WithStatus(value *NetworkPolicyStatusApplyConfiguration) *NetworkPolicyApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100022911,"name":"NetworkPolicyEgressRule","signature":"func NetworkPolicyEgressRule() *NetworkPolicyEgressRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicyegressrule.go","code":"// NetworkPolicyEgressRuleApplyConfiguration constructs an declarative configuration of the NetworkPolicyEgressRule type for use with\n// apply.\nfunc NetworkPolicyEgressRule() *NetworkPolicyEgressRuleApplyConfiguration {\n\treturn \u0026NetworkPolicyEgressRuleApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100022912,"name":"WithPorts","signature":"func (b *NetworkPolicyEgressRuleApplyConfiguration) WithPorts(values ...*NetworkPolicyPortApplyConfiguration) *NetworkPolicyEgressRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicyegressrule.go","code":"// WithPorts adds the given value to the Ports field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Ports field.\nfunc (b *NetworkPolicyEgressRuleApplyConfiguration) WithPorts(values ...*NetworkPolicyPortApplyConfiguration) *NetworkPolicyEgressRuleApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPorts\")\n\t\t}\n\t\tb.Ports = append(b.Ports, *values[i])\n\t}\n\treturn b\n}","line":{"from":34,"to":45}} {"id":100022913,"name":"WithTo","signature":"func (b *NetworkPolicyEgressRuleApplyConfiguration) WithTo(values ...*NetworkPolicyPeerApplyConfiguration) *NetworkPolicyEgressRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicyegressrule.go","code":"// WithTo adds the given value to the To field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the To field.\nfunc (b *NetworkPolicyEgressRuleApplyConfiguration) WithTo(values ...*NetworkPolicyPeerApplyConfiguration) *NetworkPolicyEgressRuleApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithTo\")\n\t\t}\n\t\tb.To = append(b.To, *values[i])\n\t}\n\treturn b\n}","line":{"from":47,"to":58}} {"id":100022914,"name":"NetworkPolicyIngressRule","signature":"func NetworkPolicyIngressRule() *NetworkPolicyIngressRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicyingressrule.go","code":"// NetworkPolicyIngressRuleApplyConfiguration constructs an declarative configuration of the NetworkPolicyIngressRule type for use with\n// apply.\nfunc NetworkPolicyIngressRule() *NetworkPolicyIngressRuleApplyConfiguration {\n\treturn \u0026NetworkPolicyIngressRuleApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100022915,"name":"WithPorts","signature":"func (b *NetworkPolicyIngressRuleApplyConfiguration) WithPorts(values ...*NetworkPolicyPortApplyConfiguration) *NetworkPolicyIngressRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicyingressrule.go","code":"// WithPorts adds the given value to the Ports field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Ports field.\nfunc (b *NetworkPolicyIngressRuleApplyConfiguration) WithPorts(values ...*NetworkPolicyPortApplyConfiguration) *NetworkPolicyIngressRuleApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPorts\")\n\t\t}\n\t\tb.Ports = append(b.Ports, *values[i])\n\t}\n\treturn b\n}","line":{"from":34,"to":45}} {"id":100022916,"name":"WithFrom","signature":"func (b *NetworkPolicyIngressRuleApplyConfiguration) WithFrom(values ...*NetworkPolicyPeerApplyConfiguration) *NetworkPolicyIngressRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicyingressrule.go","code":"// WithFrom adds the given value to the From field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the From field.\nfunc (b *NetworkPolicyIngressRuleApplyConfiguration) WithFrom(values ...*NetworkPolicyPeerApplyConfiguration) *NetworkPolicyIngressRuleApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithFrom\")\n\t\t}\n\t\tb.From = append(b.From, *values[i])\n\t}\n\treturn b\n}","line":{"from":47,"to":58}} {"id":100022917,"name":"NetworkPolicyPeer","signature":"func NetworkPolicyPeer() *NetworkPolicyPeerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicypeer.go","code":"// NetworkPolicyPeerApplyConfiguration constructs an declarative configuration of the NetworkPolicyPeer type for use with\n// apply.\nfunc NetworkPolicyPeer() *NetworkPolicyPeerApplyConfiguration {\n\treturn \u0026NetworkPolicyPeerApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100022918,"name":"WithPodSelector","signature":"func (b *NetworkPolicyPeerApplyConfiguration) WithPodSelector(value *v1.LabelSelectorApplyConfiguration) *NetworkPolicyPeerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicypeer.go","code":"// WithPodSelector sets the PodSelector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PodSelector field is set to the value of the last call.\nfunc (b *NetworkPolicyPeerApplyConfiguration) WithPodSelector(value *v1.LabelSelectorApplyConfiguration) *NetworkPolicyPeerApplyConfiguration {\n\tb.PodSelector = value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100022919,"name":"WithNamespaceSelector","signature":"func (b *NetworkPolicyPeerApplyConfiguration) WithNamespaceSelector(value *v1.LabelSelectorApplyConfiguration) *NetworkPolicyPeerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicypeer.go","code":"// WithNamespaceSelector sets the NamespaceSelector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NamespaceSelector field is set to the value of the last call.\nfunc (b *NetworkPolicyPeerApplyConfiguration) WithNamespaceSelector(value *v1.LabelSelectorApplyConfiguration) *NetworkPolicyPeerApplyConfiguration {\n\tb.NamespaceSelector = value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100022920,"name":"WithIPBlock","signature":"func (b *NetworkPolicyPeerApplyConfiguration) WithIPBlock(value *IPBlockApplyConfiguration) *NetworkPolicyPeerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicypeer.go","code":"// WithIPBlock sets the IPBlock field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the IPBlock field is set to the value of the last call.\nfunc (b *NetworkPolicyPeerApplyConfiguration) WithIPBlock(value *IPBlockApplyConfiguration) *NetworkPolicyPeerApplyConfiguration {\n\tb.IPBlock = value\n\treturn b\n}","line":{"from":55,"to":61}} {"id":100022921,"name":"NetworkPolicyPort","signature":"func NetworkPolicyPort() *NetworkPolicyPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicyport.go","code":"// NetworkPolicyPortApplyConfiguration constructs an declarative configuration of the NetworkPolicyPort type for use with\n// apply.\nfunc NetworkPolicyPort() *NetworkPolicyPortApplyConfiguration {\n\treturn \u0026NetworkPolicyPortApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100022922,"name":"WithProtocol","signature":"func (b *NetworkPolicyPortApplyConfiguration) WithProtocol(value v1.Protocol) *NetworkPolicyPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicyport.go","code":"// WithProtocol sets the Protocol field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Protocol field is set to the value of the last call.\nfunc (b *NetworkPolicyPortApplyConfiguration) WithProtocol(value v1.Protocol) *NetworkPolicyPortApplyConfiguration {\n\tb.Protocol = \u0026value\n\treturn b\n}","line":{"from":40,"to":46}} {"id":100022923,"name":"WithPort","signature":"func (b *NetworkPolicyPortApplyConfiguration) WithPort(value intstr.IntOrString) *NetworkPolicyPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicyport.go","code":"// WithPort sets the Port field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Port field is set to the value of the last call.\nfunc (b *NetworkPolicyPortApplyConfiguration) WithPort(value intstr.IntOrString) *NetworkPolicyPortApplyConfiguration {\n\tb.Port = \u0026value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100022924,"name":"WithEndPort","signature":"func (b *NetworkPolicyPortApplyConfiguration) WithEndPort(value int32) *NetworkPolicyPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicyport.go","code":"// WithEndPort sets the EndPort field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the EndPort field is set to the value of the last call.\nfunc (b *NetworkPolicyPortApplyConfiguration) WithEndPort(value int32) *NetworkPolicyPortApplyConfiguration {\n\tb.EndPort = \u0026value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100022925,"name":"NetworkPolicySpec","signature":"func NetworkPolicySpec() *NetworkPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicyspec.go","code":"// NetworkPolicySpecApplyConfiguration constructs an declarative configuration of the NetworkPolicySpec type for use with\n// apply.\nfunc NetworkPolicySpec() *NetworkPolicySpecApplyConfiguration {\n\treturn \u0026NetworkPolicySpecApplyConfiguration{}\n}","line":{"from":35,"to":39}} {"id":100022926,"name":"WithPodSelector","signature":"func (b *NetworkPolicySpecApplyConfiguration) WithPodSelector(value *v1.LabelSelectorApplyConfiguration) *NetworkPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicyspec.go","code":"// WithPodSelector sets the PodSelector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PodSelector field is set to the value of the last call.\nfunc (b *NetworkPolicySpecApplyConfiguration) WithPodSelector(value *v1.LabelSelectorApplyConfiguration) *NetworkPolicySpecApplyConfiguration {\n\tb.PodSelector = value\n\treturn b\n}","line":{"from":41,"to":47}} {"id":100022927,"name":"WithIngress","signature":"func (b *NetworkPolicySpecApplyConfiguration) WithIngress(values ...*NetworkPolicyIngressRuleApplyConfiguration) *NetworkPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicyspec.go","code":"// WithIngress adds the given value to the Ingress field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Ingress field.\nfunc (b *NetworkPolicySpecApplyConfiguration) WithIngress(values ...*NetworkPolicyIngressRuleApplyConfiguration) *NetworkPolicySpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithIngress\")\n\t\t}\n\t\tb.Ingress = append(b.Ingress, *values[i])\n\t}\n\treturn b\n}","line":{"from":49,"to":60}} {"id":100022928,"name":"WithEgress","signature":"func (b *NetworkPolicySpecApplyConfiguration) WithEgress(values ...*NetworkPolicyEgressRuleApplyConfiguration) *NetworkPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicyspec.go","code":"// WithEgress adds the given value to the Egress field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Egress field.\nfunc (b *NetworkPolicySpecApplyConfiguration) WithEgress(values ...*NetworkPolicyEgressRuleApplyConfiguration) *NetworkPolicySpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithEgress\")\n\t\t}\n\t\tb.Egress = append(b.Egress, *values[i])\n\t}\n\treturn b\n}","line":{"from":62,"to":73}} {"id":100022929,"name":"WithPolicyTypes","signature":"func (b *NetworkPolicySpecApplyConfiguration) WithPolicyTypes(values ...extensionsv1beta1.PolicyType) *NetworkPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicyspec.go","code":"// WithPolicyTypes adds the given value to the PolicyTypes field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the PolicyTypes field.\nfunc (b *NetworkPolicySpecApplyConfiguration) WithPolicyTypes(values ...extensionsv1beta1.PolicyType) *NetworkPolicySpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.PolicyTypes = append(b.PolicyTypes, values[i])\n\t}\n\treturn b\n}","line":{"from":75,"to":83}} {"id":100022930,"name":"NetworkPolicyStatus","signature":"func NetworkPolicyStatus() *NetworkPolicyStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicystatus.go","code":"// NetworkPolicyStatusApplyConfiguration constructs an declarative configuration of the NetworkPolicyStatus type for use with\n// apply.\nfunc NetworkPolicyStatus() *NetworkPolicyStatusApplyConfiguration {\n\treturn \u0026NetworkPolicyStatusApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100022931,"name":"WithConditions","signature":"func (b *NetworkPolicyStatusApplyConfiguration) WithConditions(values ...*v1.ConditionApplyConfiguration) *NetworkPolicyStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/networkpolicystatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *NetworkPolicyStatusApplyConfiguration) WithConditions(values ...*v1.ConditionApplyConfiguration) *NetworkPolicyStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":37,"to":48}} {"id":100022932,"name":"ReplicaSet","signature":"func ReplicaSet(name, namespace string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicaset.go","code":"// ReplicaSet constructs an declarative configuration of the ReplicaSet type for use with\n// apply.\nfunc ReplicaSet(name, namespace string) *ReplicaSetApplyConfiguration {\n\tb := \u0026ReplicaSetApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"ReplicaSet\")\n\tb.WithAPIVersion(\"extensions/v1beta1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100022933,"name":"ExtractReplicaSet","signature":"func ExtractReplicaSet(replicaSet *extensionsv1beta1.ReplicaSet, fieldManager string) (*ReplicaSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicaset.go","code":"// ExtractReplicaSet extracts the applied configuration owned by fieldManager from\n// replicaSet. If no managedFields are found in replicaSet for fieldManager, a\n// ReplicaSetApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// replicaSet must be a unmodified ReplicaSet API object that was retrieved from the Kubernetes API.\n// ExtractReplicaSet provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractReplicaSet(replicaSet *extensionsv1beta1.ReplicaSet, fieldManager string) (*ReplicaSetApplyConfiguration, error) {\n\treturn extractReplicaSet(replicaSet, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100022934,"name":"ExtractReplicaSetStatus","signature":"func ExtractReplicaSetStatus(replicaSet *extensionsv1beta1.ReplicaSet, fieldManager string) (*ReplicaSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicaset.go","code":"// ExtractReplicaSetStatus is the same as ExtractReplicaSet except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractReplicaSetStatus(replicaSet *extensionsv1beta1.ReplicaSet, fieldManager string) (*ReplicaSetApplyConfiguration, error) {\n\treturn extractReplicaSet(replicaSet, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100022935,"name":"extractReplicaSet","signature":"func extractReplicaSet(replicaSet *extensionsv1beta1.ReplicaSet, fieldManager string, subresource string) (*ReplicaSetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicaset.go","code":"func extractReplicaSet(replicaSet *extensionsv1beta1.ReplicaSet, fieldManager string, subresource string) (*ReplicaSetApplyConfiguration, error) {\n\tb := \u0026ReplicaSetApplyConfiguration{}\n\terr := managedfields.ExtractInto(replicaSet, internal.Parser().Type(\"io.k8s.api.extensions.v1beta1.ReplicaSet\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(replicaSet.Name)\n\tb.WithNamespace(replicaSet.Namespace)\n\n\tb.WithKind(\"ReplicaSet\")\n\tb.WithAPIVersion(\"extensions/v1beta1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100022936,"name":"WithKind","signature":"func (b *ReplicaSetApplyConfiguration) WithKind(value string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicaset.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithKind(value string) *ReplicaSetApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100022937,"name":"WithAPIVersion","signature":"func (b *ReplicaSetApplyConfiguration) WithAPIVersion(value string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicaset.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithAPIVersion(value string) *ReplicaSetApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100022938,"name":"WithName","signature":"func (b *ReplicaSetApplyConfiguration) WithName(value string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicaset.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithName(value string) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100022939,"name":"WithGenerateName","signature":"func (b *ReplicaSetApplyConfiguration) WithGenerateName(value string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicaset.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithGenerateName(value string) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100022940,"name":"WithNamespace","signature":"func (b *ReplicaSetApplyConfiguration) WithNamespace(value string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicaset.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithNamespace(value string) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100022941,"name":"WithUID","signature":"func (b *ReplicaSetApplyConfiguration) WithUID(value types.UID) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicaset.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithUID(value types.UID) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100022942,"name":"WithResourceVersion","signature":"func (b *ReplicaSetApplyConfiguration) WithResourceVersion(value string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicaset.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithResourceVersion(value string) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100022943,"name":"WithGeneration","signature":"func (b *ReplicaSetApplyConfiguration) WithGeneration(value int64) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicaset.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithGeneration(value int64) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100022944,"name":"WithCreationTimestamp","signature":"func (b *ReplicaSetApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicaset.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100022945,"name":"WithDeletionTimestamp","signature":"func (b *ReplicaSetApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicaset.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100022946,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ReplicaSetApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicaset.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100022947,"name":"WithLabels","signature":"func (b *ReplicaSetApplyConfiguration) WithLabels(entries map[string]string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicaset.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ReplicaSetApplyConfiguration) WithLabels(entries map[string]string) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100022948,"name":"WithAnnotations","signature":"func (b *ReplicaSetApplyConfiguration) WithAnnotations(entries map[string]string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicaset.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ReplicaSetApplyConfiguration) WithAnnotations(entries map[string]string) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100022949,"name":"WithOwnerReferences","signature":"func (b *ReplicaSetApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicaset.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ReplicaSetApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100022950,"name":"WithFinalizers","signature":"func (b *ReplicaSetApplyConfiguration) WithFinalizers(values ...string) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicaset.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ReplicaSetApplyConfiguration) WithFinalizers(values ...string) *ReplicaSetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100022951,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ReplicaSetApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicaset.go","code":"func (b *ReplicaSetApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100022952,"name":"WithSpec","signature":"func (b *ReplicaSetApplyConfiguration) WithSpec(value *ReplicaSetSpecApplyConfiguration) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicaset.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithSpec(value *ReplicaSetSpecApplyConfiguration) *ReplicaSetApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100022953,"name":"WithStatus","signature":"func (b *ReplicaSetApplyConfiguration) WithStatus(value *ReplicaSetStatusApplyConfiguration) *ReplicaSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicaset.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *ReplicaSetApplyConfiguration) WithStatus(value *ReplicaSetStatusApplyConfiguration) *ReplicaSetApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100022954,"name":"ReplicaSetCondition","signature":"func ReplicaSetCondition() *ReplicaSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicasetcondition.go","code":"// ReplicaSetConditionApplyConfiguration constructs an declarative configuration of the ReplicaSetCondition type for use with\n// apply.\nfunc ReplicaSetCondition() *ReplicaSetConditionApplyConfiguration {\n\treturn \u0026ReplicaSetConditionApplyConfiguration{}\n}","line":{"from":37,"to":41}} {"id":100022955,"name":"WithType","signature":"func (b *ReplicaSetConditionApplyConfiguration) WithType(value v1beta1.ReplicaSetConditionType) *ReplicaSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicasetcondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *ReplicaSetConditionApplyConfiguration) WithType(value v1beta1.ReplicaSetConditionType) *ReplicaSetConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100022956,"name":"WithStatus","signature":"func (b *ReplicaSetConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *ReplicaSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicasetcondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *ReplicaSetConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *ReplicaSetConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100022957,"name":"WithLastTransitionTime","signature":"func (b *ReplicaSetConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *ReplicaSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicasetcondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *ReplicaSetConditionApplyConfiguration) WithLastTransitionTime(value metav1.Time) *ReplicaSetConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":59,"to":65}} {"id":100022958,"name":"WithReason","signature":"func (b *ReplicaSetConditionApplyConfiguration) WithReason(value string) *ReplicaSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicasetcondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *ReplicaSetConditionApplyConfiguration) WithReason(value string) *ReplicaSetConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100022959,"name":"WithMessage","signature":"func (b *ReplicaSetConditionApplyConfiguration) WithMessage(value string) *ReplicaSetConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicasetcondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *ReplicaSetConditionApplyConfiguration) WithMessage(value string) *ReplicaSetConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":75,"to":81}} {"id":100022960,"name":"ReplicaSetSpec","signature":"func ReplicaSetSpec() *ReplicaSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicasetspec.go","code":"// ReplicaSetSpecApplyConfiguration constructs an declarative configuration of the ReplicaSetSpec type for use with\n// apply.\nfunc ReplicaSetSpec() *ReplicaSetSpecApplyConfiguration {\n\treturn \u0026ReplicaSetSpecApplyConfiguration{}\n}","line":{"from":35,"to":39}} {"id":100022961,"name":"WithReplicas","signature":"func (b *ReplicaSetSpecApplyConfiguration) WithReplicas(value int32) *ReplicaSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicasetspec.go","code":"// WithReplicas sets the Replicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Replicas field is set to the value of the last call.\nfunc (b *ReplicaSetSpecApplyConfiguration) WithReplicas(value int32) *ReplicaSetSpecApplyConfiguration {\n\tb.Replicas = \u0026value\n\treturn b\n}","line":{"from":41,"to":47}} {"id":100022962,"name":"WithMinReadySeconds","signature":"func (b *ReplicaSetSpecApplyConfiguration) WithMinReadySeconds(value int32) *ReplicaSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicasetspec.go","code":"// WithMinReadySeconds sets the MinReadySeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MinReadySeconds field is set to the value of the last call.\nfunc (b *ReplicaSetSpecApplyConfiguration) WithMinReadySeconds(value int32) *ReplicaSetSpecApplyConfiguration {\n\tb.MinReadySeconds = \u0026value\n\treturn b\n}","line":{"from":49,"to":55}} {"id":100022963,"name":"WithSelector","signature":"func (b *ReplicaSetSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *ReplicaSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicasetspec.go","code":"// WithSelector sets the Selector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Selector field is set to the value of the last call.\nfunc (b *ReplicaSetSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *ReplicaSetSpecApplyConfiguration {\n\tb.Selector = value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100022964,"name":"WithTemplate","signature":"func (b *ReplicaSetSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *ReplicaSetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicasetspec.go","code":"// WithTemplate sets the Template field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Template field is set to the value of the last call.\nfunc (b *ReplicaSetSpecApplyConfiguration) WithTemplate(value *corev1.PodTemplateSpecApplyConfiguration) *ReplicaSetSpecApplyConfiguration {\n\tb.Template = value\n\treturn b\n}","line":{"from":65,"to":71}} {"id":100022965,"name":"ReplicaSetStatus","signature":"func ReplicaSetStatus() *ReplicaSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicasetstatus.go","code":"// ReplicaSetStatusApplyConfiguration constructs an declarative configuration of the ReplicaSetStatus type for use with\n// apply.\nfunc ReplicaSetStatus() *ReplicaSetStatusApplyConfiguration {\n\treturn \u0026ReplicaSetStatusApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100022966,"name":"WithReplicas","signature":"func (b *ReplicaSetStatusApplyConfiguration) WithReplicas(value int32) *ReplicaSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicasetstatus.go","code":"// WithReplicas sets the Replicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Replicas field is set to the value of the last call.\nfunc (b *ReplicaSetStatusApplyConfiguration) WithReplicas(value int32) *ReplicaSetStatusApplyConfiguration {\n\tb.Replicas = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100022967,"name":"WithFullyLabeledReplicas","signature":"func (b *ReplicaSetStatusApplyConfiguration) WithFullyLabeledReplicas(value int32) *ReplicaSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicasetstatus.go","code":"// WithFullyLabeledReplicas sets the FullyLabeledReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FullyLabeledReplicas field is set to the value of the last call.\nfunc (b *ReplicaSetStatusApplyConfiguration) WithFullyLabeledReplicas(value int32) *ReplicaSetStatusApplyConfiguration {\n\tb.FullyLabeledReplicas = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100022968,"name":"WithReadyReplicas","signature":"func (b *ReplicaSetStatusApplyConfiguration) WithReadyReplicas(value int32) *ReplicaSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicasetstatus.go","code":"// WithReadyReplicas sets the ReadyReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadyReplicas field is set to the value of the last call.\nfunc (b *ReplicaSetStatusApplyConfiguration) WithReadyReplicas(value int32) *ReplicaSetStatusApplyConfiguration {\n\tb.ReadyReplicas = \u0026value\n\treturn b\n}","line":{"from":54,"to":60}} {"id":100022969,"name":"WithAvailableReplicas","signature":"func (b *ReplicaSetStatusApplyConfiguration) WithAvailableReplicas(value int32) *ReplicaSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicasetstatus.go","code":"// WithAvailableReplicas sets the AvailableReplicas field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AvailableReplicas field is set to the value of the last call.\nfunc (b *ReplicaSetStatusApplyConfiguration) WithAvailableReplicas(value int32) *ReplicaSetStatusApplyConfiguration {\n\tb.AvailableReplicas = \u0026value\n\treturn b\n}","line":{"from":62,"to":68}} {"id":100022970,"name":"WithObservedGeneration","signature":"func (b *ReplicaSetStatusApplyConfiguration) WithObservedGeneration(value int64) *ReplicaSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicasetstatus.go","code":"// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObservedGeneration field is set to the value of the last call.\nfunc (b *ReplicaSetStatusApplyConfiguration) WithObservedGeneration(value int64) *ReplicaSetStatusApplyConfiguration {\n\tb.ObservedGeneration = \u0026value\n\treturn b\n}","line":{"from":70,"to":76}} {"id":100022971,"name":"WithConditions","signature":"func (b *ReplicaSetStatusApplyConfiguration) WithConditions(values ...*ReplicaSetConditionApplyConfiguration) *ReplicaSetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/replicasetstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *ReplicaSetStatusApplyConfiguration) WithConditions(values ...*ReplicaSetConditionApplyConfiguration) *ReplicaSetStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":78,"to":89}} {"id":100022972,"name":"RollbackConfig","signature":"func RollbackConfig() *RollbackConfigApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/rollbackconfig.go","code":"// RollbackConfigApplyConfiguration constructs an declarative configuration of the RollbackConfig type for use with\n// apply.\nfunc RollbackConfig() *RollbackConfigApplyConfiguration {\n\treturn \u0026RollbackConfigApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100022973,"name":"WithRevision","signature":"func (b *RollbackConfigApplyConfiguration) WithRevision(value int64) *RollbackConfigApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/rollbackconfig.go","code":"// WithRevision sets the Revision field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Revision field is set to the value of the last call.\nfunc (b *RollbackConfigApplyConfiguration) WithRevision(value int64) *RollbackConfigApplyConfiguration {\n\tb.Revision = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100022974,"name":"RollingUpdateDaemonSet","signature":"func RollingUpdateDaemonSet() *RollingUpdateDaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/rollingupdatedaemonset.go","code":"// RollingUpdateDaemonSetApplyConfiguration constructs an declarative configuration of the RollingUpdateDaemonSet type for use with\n// apply.\nfunc RollingUpdateDaemonSet() *RollingUpdateDaemonSetApplyConfiguration {\n\treturn \u0026RollingUpdateDaemonSetApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100022975,"name":"WithMaxUnavailable","signature":"func (b *RollingUpdateDaemonSetApplyConfiguration) WithMaxUnavailable(value intstr.IntOrString) *RollingUpdateDaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/rollingupdatedaemonset.go","code":"// WithMaxUnavailable sets the MaxUnavailable field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MaxUnavailable field is set to the value of the last call.\nfunc (b *RollingUpdateDaemonSetApplyConfiguration) WithMaxUnavailable(value intstr.IntOrString) *RollingUpdateDaemonSetApplyConfiguration {\n\tb.MaxUnavailable = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100022976,"name":"WithMaxSurge","signature":"func (b *RollingUpdateDaemonSetApplyConfiguration) WithMaxSurge(value intstr.IntOrString) *RollingUpdateDaemonSetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/rollingupdatedaemonset.go","code":"// WithMaxSurge sets the MaxSurge field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MaxSurge field is set to the value of the last call.\nfunc (b *RollingUpdateDaemonSetApplyConfiguration) WithMaxSurge(value intstr.IntOrString) *RollingUpdateDaemonSetApplyConfiguration {\n\tb.MaxSurge = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100022977,"name":"RollingUpdateDeployment","signature":"func RollingUpdateDeployment() *RollingUpdateDeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/rollingupdatedeployment.go","code":"// RollingUpdateDeploymentApplyConfiguration constructs an declarative configuration of the RollingUpdateDeployment type for use with\n// apply.\nfunc RollingUpdateDeployment() *RollingUpdateDeploymentApplyConfiguration {\n\treturn \u0026RollingUpdateDeploymentApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100022978,"name":"WithMaxUnavailable","signature":"func (b *RollingUpdateDeploymentApplyConfiguration) WithMaxUnavailable(value intstr.IntOrString) *RollingUpdateDeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/rollingupdatedeployment.go","code":"// WithMaxUnavailable sets the MaxUnavailable field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MaxUnavailable field is set to the value of the last call.\nfunc (b *RollingUpdateDeploymentApplyConfiguration) WithMaxUnavailable(value intstr.IntOrString) *RollingUpdateDeploymentApplyConfiguration {\n\tb.MaxUnavailable = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100022979,"name":"WithMaxSurge","signature":"func (b *RollingUpdateDeploymentApplyConfiguration) WithMaxSurge(value intstr.IntOrString) *RollingUpdateDeploymentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/rollingupdatedeployment.go","code":"// WithMaxSurge sets the MaxSurge field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MaxSurge field is set to the value of the last call.\nfunc (b *RollingUpdateDeploymentApplyConfiguration) WithMaxSurge(value intstr.IntOrString) *RollingUpdateDeploymentApplyConfiguration {\n\tb.MaxSurge = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100022980,"name":"Scale","signature":"func Scale() *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/scale.go","code":"// ScaleApplyConfiguration constructs an declarative configuration of the Scale type for use with\n// apply.\nfunc Scale() *ScaleApplyConfiguration {\n\tb := \u0026ScaleApplyConfiguration{}\n\tb.WithKind(\"Scale\")\n\tb.WithAPIVersion(\"extensions/v1beta1\")\n\treturn b\n}","line":{"from":37,"to":44}} {"id":100022981,"name":"WithKind","signature":"func (b *ScaleApplyConfiguration) WithKind(value string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/scale.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithKind(value string) *ScaleApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100022982,"name":"WithAPIVersion","signature":"func (b *ScaleApplyConfiguration) WithAPIVersion(value string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/scale.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithAPIVersion(value string) *ScaleApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":54,"to":60}} {"id":100022983,"name":"WithName","signature":"func (b *ScaleApplyConfiguration) WithName(value string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/scale.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithName(value string) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":62,"to":69}} {"id":100022984,"name":"WithGenerateName","signature":"func (b *ScaleApplyConfiguration) WithGenerateName(value string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/scale.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithGenerateName(value string) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":71,"to":78}} {"id":100022985,"name":"WithNamespace","signature":"func (b *ScaleApplyConfiguration) WithNamespace(value string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/scale.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithNamespace(value string) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":80,"to":87}} {"id":100022986,"name":"WithUID","signature":"func (b *ScaleApplyConfiguration) WithUID(value types.UID) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/scale.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithUID(value types.UID) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":89,"to":96}} {"id":100022987,"name":"WithResourceVersion","signature":"func (b *ScaleApplyConfiguration) WithResourceVersion(value string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/scale.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithResourceVersion(value string) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":98,"to":105}} {"id":100022988,"name":"WithGeneration","signature":"func (b *ScaleApplyConfiguration) WithGeneration(value int64) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/scale.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithGeneration(value int64) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":107,"to":114}} {"id":100022989,"name":"WithCreationTimestamp","signature":"func (b *ScaleApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/scale.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":116,"to":123}} {"id":100022990,"name":"WithDeletionTimestamp","signature":"func (b *ScaleApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/scale.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":125,"to":132}} {"id":100022991,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ScaleApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/scale.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":134,"to":141}} {"id":100022992,"name":"WithLabels","signature":"func (b *ScaleApplyConfiguration) WithLabels(entries map[string]string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/scale.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ScaleApplyConfiguration) WithLabels(entries map[string]string) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":143,"to":156}} {"id":100022993,"name":"WithAnnotations","signature":"func (b *ScaleApplyConfiguration) WithAnnotations(entries map[string]string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/scale.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ScaleApplyConfiguration) WithAnnotations(entries map[string]string) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":158,"to":171}} {"id":100022994,"name":"WithOwnerReferences","signature":"func (b *ScaleApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/scale.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ScaleApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":173,"to":185}} {"id":100022995,"name":"WithFinalizers","signature":"func (b *ScaleApplyConfiguration) WithFinalizers(values ...string) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/scale.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ScaleApplyConfiguration) WithFinalizers(values ...string) *ScaleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":187,"to":196}} {"id":100022996,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ScaleApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/scale.go","code":"func (b *ScaleApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":198,"to":202}} {"id":100022997,"name":"WithSpec","signature":"func (b *ScaleApplyConfiguration) WithSpec(value v1beta1.ScaleSpec) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/scale.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithSpec(value v1beta1.ScaleSpec) *ScaleApplyConfiguration {\n\tb.Spec = \u0026value\n\treturn b\n}","line":{"from":204,"to":210}} {"id":100022998,"name":"WithStatus","signature":"func (b *ScaleApplyConfiguration) WithStatus(value v1beta1.ScaleStatus) *ScaleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/extensions/v1beta1/scale.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *ScaleApplyConfiguration) WithStatus(value v1beta1.ScaleStatus) *ScaleApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":212,"to":218}} {"id":100022999,"name":"FlowDistinguisherMethod","signature":"func FlowDistinguisherMethod() *FlowDistinguisherMethodApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowdistinguishermethod.go","code":"// FlowDistinguisherMethodApplyConfiguration constructs an declarative configuration of the FlowDistinguisherMethod type for use with\n// apply.\nfunc FlowDistinguisherMethod() *FlowDistinguisherMethodApplyConfiguration {\n\treturn \u0026FlowDistinguisherMethodApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100023000,"name":"WithType","signature":"func (b *FlowDistinguisherMethodApplyConfiguration) WithType(value v1alpha1.FlowDistinguisherMethodType) *FlowDistinguisherMethodApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowdistinguishermethod.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *FlowDistinguisherMethodApplyConfiguration) WithType(value v1alpha1.FlowDistinguisherMethodType) *FlowDistinguisherMethodApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":37,"to":43}} {"id":100023001,"name":"FlowSchema","signature":"func FlowSchema(name string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschema.go","code":"// FlowSchema constructs an declarative configuration of the FlowSchema type for use with\n// apply.\nfunc FlowSchema(name string) *FlowSchemaApplyConfiguration {\n\tb := \u0026FlowSchemaApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"FlowSchema\")\n\tb.WithAPIVersion(\"flowcontrol.apiserver.k8s.io/v1alpha1\")\n\treturn b\n}","line":{"from":39,"to":47}} {"id":100023002,"name":"ExtractFlowSchema","signature":"func ExtractFlowSchema(flowSchema *flowcontrolv1alpha1.FlowSchema, fieldManager string) (*FlowSchemaApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschema.go","code":"// ExtractFlowSchema extracts the applied configuration owned by fieldManager from\n// flowSchema. If no managedFields are found in flowSchema for fieldManager, a\n// FlowSchemaApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// flowSchema must be a unmodified FlowSchema API object that was retrieved from the Kubernetes API.\n// ExtractFlowSchema provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractFlowSchema(flowSchema *flowcontrolv1alpha1.FlowSchema, fieldManager string) (*FlowSchemaApplyConfiguration, error) {\n\treturn extractFlowSchema(flowSchema, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100023003,"name":"ExtractFlowSchemaStatus","signature":"func ExtractFlowSchemaStatus(flowSchema *flowcontrolv1alpha1.FlowSchema, fieldManager string) (*FlowSchemaApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschema.go","code":"// ExtractFlowSchemaStatus is the same as ExtractFlowSchema except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractFlowSchemaStatus(flowSchema *flowcontrolv1alpha1.FlowSchema, fieldManager string) (*FlowSchemaApplyConfiguration, error) {\n\treturn extractFlowSchema(flowSchema, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100023004,"name":"extractFlowSchema","signature":"func extractFlowSchema(flowSchema *flowcontrolv1alpha1.FlowSchema, fieldManager string, subresource string) (*FlowSchemaApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschema.go","code":"func extractFlowSchema(flowSchema *flowcontrolv1alpha1.FlowSchema, fieldManager string, subresource string) (*FlowSchemaApplyConfiguration, error) {\n\tb := \u0026FlowSchemaApplyConfiguration{}\n\terr := managedfields.ExtractInto(flowSchema, internal.Parser().Type(\"io.k8s.api.flowcontrol.v1alpha1.FlowSchema\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(flowSchema.Name)\n\n\tb.WithKind(\"FlowSchema\")\n\tb.WithAPIVersion(\"flowcontrol.apiserver.k8s.io/v1alpha1\")\n\treturn b, nil\n}","line":{"from":71,"to":82}} {"id":100023005,"name":"WithKind","signature":"func (b *FlowSchemaApplyConfiguration) WithKind(value string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschema.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithKind(value string) *FlowSchemaApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100023006,"name":"WithAPIVersion","signature":"func (b *FlowSchemaApplyConfiguration) WithAPIVersion(value string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschema.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithAPIVersion(value string) *FlowSchemaApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100023007,"name":"WithName","signature":"func (b *FlowSchemaApplyConfiguration) WithName(value string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschema.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithName(value string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":100,"to":107}} {"id":100023008,"name":"WithGenerateName","signature":"func (b *FlowSchemaApplyConfiguration) WithGenerateName(value string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschema.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithGenerateName(value string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":109,"to":116}} {"id":100023009,"name":"WithNamespace","signature":"func (b *FlowSchemaApplyConfiguration) WithNamespace(value string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschema.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithNamespace(value string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":118,"to":125}} {"id":100023010,"name":"WithUID","signature":"func (b *FlowSchemaApplyConfiguration) WithUID(value types.UID) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschema.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithUID(value types.UID) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":127,"to":134}} {"id":100023011,"name":"WithResourceVersion","signature":"func (b *FlowSchemaApplyConfiguration) WithResourceVersion(value string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschema.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithResourceVersion(value string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":136,"to":143}} {"id":100023012,"name":"WithGeneration","signature":"func (b *FlowSchemaApplyConfiguration) WithGeneration(value int64) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschema.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithGeneration(value int64) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":145,"to":152}} {"id":100023013,"name":"WithCreationTimestamp","signature":"func (b *FlowSchemaApplyConfiguration) WithCreationTimestamp(value metav1.Time) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschema.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithCreationTimestamp(value metav1.Time) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":154,"to":161}} {"id":100023014,"name":"WithDeletionTimestamp","signature":"func (b *FlowSchemaApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschema.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":163,"to":170}} {"id":100023015,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *FlowSchemaApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschema.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":172,"to":179}} {"id":100023016,"name":"WithLabels","signature":"func (b *FlowSchemaApplyConfiguration) WithLabels(entries map[string]string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschema.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *FlowSchemaApplyConfiguration) WithLabels(entries map[string]string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":181,"to":194}} {"id":100023017,"name":"WithAnnotations","signature":"func (b *FlowSchemaApplyConfiguration) WithAnnotations(entries map[string]string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschema.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *FlowSchemaApplyConfiguration) WithAnnotations(entries map[string]string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100023018,"name":"WithOwnerReferences","signature":"func (b *FlowSchemaApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschema.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *FlowSchemaApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":211,"to":223}} {"id":100023019,"name":"WithFinalizers","signature":"func (b *FlowSchemaApplyConfiguration) WithFinalizers(values ...string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschema.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *FlowSchemaApplyConfiguration) WithFinalizers(values ...string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":225,"to":234}} {"id":100023020,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *FlowSchemaApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschema.go","code":"func (b *FlowSchemaApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":236,"to":240}} {"id":100023021,"name":"WithSpec","signature":"func (b *FlowSchemaApplyConfiguration) WithSpec(value *FlowSchemaSpecApplyConfiguration) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschema.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithSpec(value *FlowSchemaSpecApplyConfiguration) *FlowSchemaApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":242,"to":248}} {"id":100023022,"name":"WithStatus","signature":"func (b *FlowSchemaApplyConfiguration) WithStatus(value *FlowSchemaStatusApplyConfiguration) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschema.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithStatus(value *FlowSchemaStatusApplyConfiguration) *FlowSchemaApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":250,"to":256}} {"id":100023023,"name":"FlowSchemaCondition","signature":"func FlowSchemaCondition() *FlowSchemaConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschemacondition.go","code":"// FlowSchemaConditionApplyConfiguration constructs an declarative configuration of the FlowSchemaCondition type for use with\n// apply.\nfunc FlowSchemaCondition() *FlowSchemaConditionApplyConfiguration {\n\treturn \u0026FlowSchemaConditionApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100023024,"name":"WithType","signature":"func (b *FlowSchemaConditionApplyConfiguration) WithType(value v1alpha1.FlowSchemaConditionType) *FlowSchemaConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschemacondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *FlowSchemaConditionApplyConfiguration) WithType(value v1alpha1.FlowSchemaConditionType) *FlowSchemaConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100023025,"name":"WithStatus","signature":"func (b *FlowSchemaConditionApplyConfiguration) WithStatus(value v1alpha1.ConditionStatus) *FlowSchemaConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschemacondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *FlowSchemaConditionApplyConfiguration) WithStatus(value v1alpha1.ConditionStatus) *FlowSchemaConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100023026,"name":"WithLastTransitionTime","signature":"func (b *FlowSchemaConditionApplyConfiguration) WithLastTransitionTime(value v1.Time) *FlowSchemaConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschemacondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *FlowSchemaConditionApplyConfiguration) WithLastTransitionTime(value v1.Time) *FlowSchemaConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100023027,"name":"WithReason","signature":"func (b *FlowSchemaConditionApplyConfiguration) WithReason(value string) *FlowSchemaConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschemacondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *FlowSchemaConditionApplyConfiguration) WithReason(value string) *FlowSchemaConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100023028,"name":"WithMessage","signature":"func (b *FlowSchemaConditionApplyConfiguration) WithMessage(value string) *FlowSchemaConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschemacondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *FlowSchemaConditionApplyConfiguration) WithMessage(value string) *FlowSchemaConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100023029,"name":"FlowSchemaSpec","signature":"func FlowSchemaSpec() *FlowSchemaSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschemaspec.go","code":"// FlowSchemaSpecApplyConfiguration constructs an declarative configuration of the FlowSchemaSpec type for use with\n// apply.\nfunc FlowSchemaSpec() *FlowSchemaSpecApplyConfiguration {\n\treturn \u0026FlowSchemaSpecApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100023030,"name":"WithPriorityLevelConfiguration","signature":"func (b *FlowSchemaSpecApplyConfiguration) WithPriorityLevelConfiguration(value *PriorityLevelConfigurationReferenceApplyConfiguration) *FlowSchemaSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschemaspec.go","code":"// WithPriorityLevelConfiguration sets the PriorityLevelConfiguration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PriorityLevelConfiguration field is set to the value of the last call.\nfunc (b *FlowSchemaSpecApplyConfiguration) WithPriorityLevelConfiguration(value *PriorityLevelConfigurationReferenceApplyConfiguration) *FlowSchemaSpecApplyConfiguration {\n\tb.PriorityLevelConfiguration = value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100023031,"name":"WithMatchingPrecedence","signature":"func (b *FlowSchemaSpecApplyConfiguration) WithMatchingPrecedence(value int32) *FlowSchemaSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschemaspec.go","code":"// WithMatchingPrecedence sets the MatchingPrecedence field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MatchingPrecedence field is set to the value of the last call.\nfunc (b *FlowSchemaSpecApplyConfiguration) WithMatchingPrecedence(value int32) *FlowSchemaSpecApplyConfiguration {\n\tb.MatchingPrecedence = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100023032,"name":"WithDistinguisherMethod","signature":"func (b *FlowSchemaSpecApplyConfiguration) WithDistinguisherMethod(value *FlowDistinguisherMethodApplyConfiguration) *FlowSchemaSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschemaspec.go","code":"// WithDistinguisherMethod sets the DistinguisherMethod field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DistinguisherMethod field is set to the value of the last call.\nfunc (b *FlowSchemaSpecApplyConfiguration) WithDistinguisherMethod(value *FlowDistinguisherMethodApplyConfiguration) *FlowSchemaSpecApplyConfiguration {\n\tb.DistinguisherMethod = value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100023033,"name":"WithRules","signature":"func (b *FlowSchemaSpecApplyConfiguration) WithRules(values ...*PolicyRulesWithSubjectsApplyConfiguration) *FlowSchemaSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschemaspec.go","code":"// WithRules adds the given value to the Rules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Rules field.\nfunc (b *FlowSchemaSpecApplyConfiguration) WithRules(values ...*PolicyRulesWithSubjectsApplyConfiguration) *FlowSchemaSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRules\")\n\t\t}\n\t\tb.Rules = append(b.Rules, *values[i])\n\t}\n\treturn b\n}","line":{"from":60,"to":71}} {"id":100023034,"name":"FlowSchemaStatus","signature":"func FlowSchemaStatus() *FlowSchemaStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschemastatus.go","code":"// FlowSchemaStatusApplyConfiguration constructs an declarative configuration of the FlowSchemaStatus type for use with\n// apply.\nfunc FlowSchemaStatus() *FlowSchemaStatusApplyConfiguration {\n\treturn \u0026FlowSchemaStatusApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023035,"name":"WithConditions","signature":"func (b *FlowSchemaStatusApplyConfiguration) WithConditions(values ...*FlowSchemaConditionApplyConfiguration) *FlowSchemaStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/flowschemastatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *FlowSchemaStatusApplyConfiguration) WithConditions(values ...*FlowSchemaConditionApplyConfiguration) *FlowSchemaStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100023036,"name":"GroupSubject","signature":"func GroupSubject() *GroupSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/groupsubject.go","code":"// GroupSubjectApplyConfiguration constructs an declarative configuration of the GroupSubject type for use with\n// apply.\nfunc GroupSubject() *GroupSubjectApplyConfiguration {\n\treturn \u0026GroupSubjectApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023037,"name":"WithName","signature":"func (b *GroupSubjectApplyConfiguration) WithName(value string) *GroupSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/groupsubject.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *GroupSubjectApplyConfiguration) WithName(value string) *GroupSubjectApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100023038,"name":"LimitedPriorityLevelConfiguration","signature":"func LimitedPriorityLevelConfiguration() *LimitedPriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/limitedprioritylevelconfiguration.go","code":"// LimitedPriorityLevelConfigurationApplyConfiguration constructs an declarative configuration of the LimitedPriorityLevelConfiguration type for use with\n// apply.\nfunc LimitedPriorityLevelConfiguration() *LimitedPriorityLevelConfigurationApplyConfiguration {\n\treturn \u0026LimitedPriorityLevelConfigurationApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100023039,"name":"WithAssuredConcurrencyShares","signature":"func (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithAssuredConcurrencyShares(value int32) *LimitedPriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/limitedprioritylevelconfiguration.go","code":"// WithAssuredConcurrencyShares sets the AssuredConcurrencyShares field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AssuredConcurrencyShares field is set to the value of the last call.\nfunc (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithAssuredConcurrencyShares(value int32) *LimitedPriorityLevelConfigurationApplyConfiguration {\n\tb.AssuredConcurrencyShares = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100023040,"name":"WithLimitResponse","signature":"func (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithLimitResponse(value *LimitResponseApplyConfiguration) *LimitedPriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/limitedprioritylevelconfiguration.go","code":"// WithLimitResponse sets the LimitResponse field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LimitResponse field is set to the value of the last call.\nfunc (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithLimitResponse(value *LimitResponseApplyConfiguration) *LimitedPriorityLevelConfigurationApplyConfiguration {\n\tb.LimitResponse = value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100023041,"name":"WithLendablePercent","signature":"func (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithLendablePercent(value int32) *LimitedPriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/limitedprioritylevelconfiguration.go","code":"// WithLendablePercent sets the LendablePercent field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LendablePercent field is set to the value of the last call.\nfunc (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithLendablePercent(value int32) *LimitedPriorityLevelConfigurationApplyConfiguration {\n\tb.LendablePercent = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100023042,"name":"WithBorrowingLimitPercent","signature":"func (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithBorrowingLimitPercent(value int32) *LimitedPriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/limitedprioritylevelconfiguration.go","code":"// WithBorrowingLimitPercent sets the BorrowingLimitPercent field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the BorrowingLimitPercent field is set to the value of the last call.\nfunc (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithBorrowingLimitPercent(value int32) *LimitedPriorityLevelConfigurationApplyConfiguration {\n\tb.BorrowingLimitPercent = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100023043,"name":"LimitResponse","signature":"func LimitResponse() *LimitResponseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/limitresponse.go","code":"// LimitResponseApplyConfiguration constructs an declarative configuration of the LimitResponse type for use with\n// apply.\nfunc LimitResponse() *LimitResponseApplyConfiguration {\n\treturn \u0026LimitResponseApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100023044,"name":"WithType","signature":"func (b *LimitResponseApplyConfiguration) WithType(value v1alpha1.LimitResponseType) *LimitResponseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/limitresponse.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *LimitResponseApplyConfiguration) WithType(value v1alpha1.LimitResponseType) *LimitResponseApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100023045,"name":"WithQueuing","signature":"func (b *LimitResponseApplyConfiguration) WithQueuing(value *QueuingConfigurationApplyConfiguration) *LimitResponseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/limitresponse.go","code":"// WithQueuing sets the Queuing field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Queuing field is set to the value of the last call.\nfunc (b *LimitResponseApplyConfiguration) WithQueuing(value *QueuingConfigurationApplyConfiguration) *LimitResponseApplyConfiguration {\n\tb.Queuing = value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100023046,"name":"NonResourcePolicyRule","signature":"func NonResourcePolicyRule() *NonResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/nonresourcepolicyrule.go","code":"// NonResourcePolicyRuleApplyConfiguration constructs an declarative configuration of the NonResourcePolicyRule type for use with\n// apply.\nfunc NonResourcePolicyRule() *NonResourcePolicyRuleApplyConfiguration {\n\treturn \u0026NonResourcePolicyRuleApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100023047,"name":"WithVerbs","signature":"func (b *NonResourcePolicyRuleApplyConfiguration) WithVerbs(values ...string) *NonResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/nonresourcepolicyrule.go","code":"// WithVerbs adds the given value to the Verbs field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Verbs field.\nfunc (b *NonResourcePolicyRuleApplyConfiguration) WithVerbs(values ...string) *NonResourcePolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.Verbs = append(b.Verbs, values[i])\n\t}\n\treturn b\n}","line":{"from":34,"to":42}} {"id":100023048,"name":"WithNonResourceURLs","signature":"func (b *NonResourcePolicyRuleApplyConfiguration) WithNonResourceURLs(values ...string) *NonResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/nonresourcepolicyrule.go","code":"// WithNonResourceURLs adds the given value to the NonResourceURLs field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the NonResourceURLs field.\nfunc (b *NonResourcePolicyRuleApplyConfiguration) WithNonResourceURLs(values ...string) *NonResourcePolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.NonResourceURLs = append(b.NonResourceURLs, values[i])\n\t}\n\treturn b\n}","line":{"from":44,"to":52}} {"id":100023049,"name":"PolicyRulesWithSubjects","signature":"func PolicyRulesWithSubjects() *PolicyRulesWithSubjectsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/policyruleswithsubjects.go","code":"// PolicyRulesWithSubjectsApplyConfiguration constructs an declarative configuration of the PolicyRulesWithSubjects type for use with\n// apply.\nfunc PolicyRulesWithSubjects() *PolicyRulesWithSubjectsApplyConfiguration {\n\treturn \u0026PolicyRulesWithSubjectsApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100023050,"name":"WithSubjects","signature":"func (b *PolicyRulesWithSubjectsApplyConfiguration) WithSubjects(values ...*SubjectApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/policyruleswithsubjects.go","code":"// WithSubjects adds the given value to the Subjects field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Subjects field.\nfunc (b *PolicyRulesWithSubjectsApplyConfiguration) WithSubjects(values ...*SubjectApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithSubjects\")\n\t\t}\n\t\tb.Subjects = append(b.Subjects, *values[i])\n\t}\n\treturn b\n}","line":{"from":35,"to":46}} {"id":100023051,"name":"WithResourceRules","signature":"func (b *PolicyRulesWithSubjectsApplyConfiguration) WithResourceRules(values ...*ResourcePolicyRuleApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/policyruleswithsubjects.go","code":"// WithResourceRules adds the given value to the ResourceRules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ResourceRules field.\nfunc (b *PolicyRulesWithSubjectsApplyConfiguration) WithResourceRules(values ...*ResourcePolicyRuleApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithResourceRules\")\n\t\t}\n\t\tb.ResourceRules = append(b.ResourceRules, *values[i])\n\t}\n\treturn b\n}","line":{"from":48,"to":59}} {"id":100023052,"name":"WithNonResourceRules","signature":"func (b *PolicyRulesWithSubjectsApplyConfiguration) WithNonResourceRules(values ...*NonResourcePolicyRuleApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/policyruleswithsubjects.go","code":"// WithNonResourceRules adds the given value to the NonResourceRules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the NonResourceRules field.\nfunc (b *PolicyRulesWithSubjectsApplyConfiguration) WithNonResourceRules(values ...*NonResourcePolicyRuleApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithNonResourceRules\")\n\t\t}\n\t\tb.NonResourceRules = append(b.NonResourceRules, *values[i])\n\t}\n\treturn b\n}","line":{"from":61,"to":72}} {"id":100023053,"name":"PriorityLevelConfiguration","signature":"func PriorityLevelConfiguration(name string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// PriorityLevelConfiguration constructs an declarative configuration of the PriorityLevelConfiguration type for use with\n// apply.\nfunc PriorityLevelConfiguration(name string) *PriorityLevelConfigurationApplyConfiguration {\n\tb := \u0026PriorityLevelConfigurationApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"PriorityLevelConfiguration\")\n\tb.WithAPIVersion(\"flowcontrol.apiserver.k8s.io/v1alpha1\")\n\treturn b\n}","line":{"from":39,"to":47}} {"id":100023054,"name":"ExtractPriorityLevelConfiguration","signature":"func ExtractPriorityLevelConfiguration(priorityLevelConfiguration *flowcontrolv1alpha1.PriorityLevelConfiguration, fieldManager string) (*PriorityLevelConfigurationApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// ExtractPriorityLevelConfiguration extracts the applied configuration owned by fieldManager from\n// priorityLevelConfiguration. If no managedFields are found in priorityLevelConfiguration for fieldManager, a\n// PriorityLevelConfigurationApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// priorityLevelConfiguration must be a unmodified PriorityLevelConfiguration API object that was retrieved from the Kubernetes API.\n// ExtractPriorityLevelConfiguration provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractPriorityLevelConfiguration(priorityLevelConfiguration *flowcontrolv1alpha1.PriorityLevelConfiguration, fieldManager string) (*PriorityLevelConfigurationApplyConfiguration, error) {\n\treturn extractPriorityLevelConfiguration(priorityLevelConfiguration, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100023055,"name":"ExtractPriorityLevelConfigurationStatus","signature":"func ExtractPriorityLevelConfigurationStatus(priorityLevelConfiguration *flowcontrolv1alpha1.PriorityLevelConfiguration, fieldManager string) (*PriorityLevelConfigurationApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// ExtractPriorityLevelConfigurationStatus is the same as ExtractPriorityLevelConfiguration except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractPriorityLevelConfigurationStatus(priorityLevelConfiguration *flowcontrolv1alpha1.PriorityLevelConfiguration, fieldManager string) (*PriorityLevelConfigurationApplyConfiguration, error) {\n\treturn extractPriorityLevelConfiguration(priorityLevelConfiguration, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100023056,"name":"extractPriorityLevelConfiguration","signature":"func extractPriorityLevelConfiguration(priorityLevelConfiguration *flowcontrolv1alpha1.PriorityLevelConfiguration, fieldManager string, subresource string) (*PriorityLevelConfigurationApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"func extractPriorityLevelConfiguration(priorityLevelConfiguration *flowcontrolv1alpha1.PriorityLevelConfiguration, fieldManager string, subresource string) (*PriorityLevelConfigurationApplyConfiguration, error) {\n\tb := \u0026PriorityLevelConfigurationApplyConfiguration{}\n\terr := managedfields.ExtractInto(priorityLevelConfiguration, internal.Parser().Type(\"io.k8s.api.flowcontrol.v1alpha1.PriorityLevelConfiguration\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(priorityLevelConfiguration.Name)\n\n\tb.WithKind(\"PriorityLevelConfiguration\")\n\tb.WithAPIVersion(\"flowcontrol.apiserver.k8s.io/v1alpha1\")\n\treturn b, nil\n}","line":{"from":71,"to":82}} {"id":100023057,"name":"WithKind","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithKind(value string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithKind(value string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100023058,"name":"WithAPIVersion","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithAPIVersion(value string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithAPIVersion(value string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100023059,"name":"WithName","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithName(value string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithName(value string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":100,"to":107}} {"id":100023060,"name":"WithGenerateName","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithGenerateName(value string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithGenerateName(value string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":109,"to":116}} {"id":100023061,"name":"WithNamespace","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithNamespace(value string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithNamespace(value string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":118,"to":125}} {"id":100023062,"name":"WithUID","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithUID(value types.UID) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithUID(value types.UID) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":127,"to":134}} {"id":100023063,"name":"WithResourceVersion","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithResourceVersion(value string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithResourceVersion(value string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":136,"to":143}} {"id":100023064,"name":"WithGeneration","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithGeneration(value int64) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithGeneration(value int64) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":145,"to":152}} {"id":100023065,"name":"WithCreationTimestamp","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":154,"to":161}} {"id":100023066,"name":"WithDeletionTimestamp","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":163,"to":170}} {"id":100023067,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":172,"to":179}} {"id":100023068,"name":"WithLabels","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithLabels(entries map[string]string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithLabels(entries map[string]string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":181,"to":194}} {"id":100023069,"name":"WithAnnotations","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithAnnotations(entries map[string]string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithAnnotations(entries map[string]string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100023070,"name":"WithOwnerReferences","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":211,"to":223}} {"id":100023071,"name":"WithFinalizers","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithFinalizers(values ...string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithFinalizers(values ...string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":225,"to":234}} {"id":100023072,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"func (b *PriorityLevelConfigurationApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":236,"to":240}} {"id":100023073,"name":"WithSpec","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithSpec(value *PriorityLevelConfigurationSpecApplyConfiguration) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithSpec(value *PriorityLevelConfigurationSpecApplyConfiguration) *PriorityLevelConfigurationApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":242,"to":248}} {"id":100023074,"name":"WithStatus","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithStatus(value *PriorityLevelConfigurationStatusApplyConfiguration) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithStatus(value *PriorityLevelConfigurationStatusApplyConfiguration) *PriorityLevelConfigurationApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":250,"to":256}} {"id":100023075,"name":"PriorityLevelConfigurationCondition","signature":"func PriorityLevelConfigurationCondition() *PriorityLevelConfigurationConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfigurationcondition.go","code":"// PriorityLevelConfigurationConditionApplyConfiguration constructs an declarative configuration of the PriorityLevelConfigurationCondition type for use with\n// apply.\nfunc PriorityLevelConfigurationCondition() *PriorityLevelConfigurationConditionApplyConfiguration {\n\treturn \u0026PriorityLevelConfigurationConditionApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100023076,"name":"WithType","signature":"func (b *PriorityLevelConfigurationConditionApplyConfiguration) WithType(value v1alpha1.PriorityLevelConfigurationConditionType) *PriorityLevelConfigurationConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfigurationcondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationConditionApplyConfiguration) WithType(value v1alpha1.PriorityLevelConfigurationConditionType) *PriorityLevelConfigurationConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100023077,"name":"WithStatus","signature":"func (b *PriorityLevelConfigurationConditionApplyConfiguration) WithStatus(value v1alpha1.ConditionStatus) *PriorityLevelConfigurationConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfigurationcondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationConditionApplyConfiguration) WithStatus(value v1alpha1.ConditionStatus) *PriorityLevelConfigurationConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100023078,"name":"WithLastTransitionTime","signature":"func (b *PriorityLevelConfigurationConditionApplyConfiguration) WithLastTransitionTime(value v1.Time) *PriorityLevelConfigurationConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfigurationcondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationConditionApplyConfiguration) WithLastTransitionTime(value v1.Time) *PriorityLevelConfigurationConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100023079,"name":"WithReason","signature":"func (b *PriorityLevelConfigurationConditionApplyConfiguration) WithReason(value string) *PriorityLevelConfigurationConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfigurationcondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationConditionApplyConfiguration) WithReason(value string) *PriorityLevelConfigurationConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100023080,"name":"WithMessage","signature":"func (b *PriorityLevelConfigurationConditionApplyConfiguration) WithMessage(value string) *PriorityLevelConfigurationConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfigurationcondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationConditionApplyConfiguration) WithMessage(value string) *PriorityLevelConfigurationConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100023081,"name":"PriorityLevelConfigurationReference","signature":"func PriorityLevelConfigurationReference() *PriorityLevelConfigurationReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfigurationreference.go","code":"// PriorityLevelConfigurationReferenceApplyConfiguration constructs an declarative configuration of the PriorityLevelConfigurationReference type for use with\n// apply.\nfunc PriorityLevelConfigurationReference() *PriorityLevelConfigurationReferenceApplyConfiguration {\n\treturn \u0026PriorityLevelConfigurationReferenceApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023082,"name":"WithName","signature":"func (b *PriorityLevelConfigurationReferenceApplyConfiguration) WithName(value string) *PriorityLevelConfigurationReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfigurationreference.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationReferenceApplyConfiguration) WithName(value string) *PriorityLevelConfigurationReferenceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100023083,"name":"PriorityLevelConfigurationSpec","signature":"func PriorityLevelConfigurationSpec() *PriorityLevelConfigurationSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfigurationspec.go","code":"// PriorityLevelConfigurationSpecApplyConfiguration constructs an declarative configuration of the PriorityLevelConfigurationSpec type for use with\n// apply.\nfunc PriorityLevelConfigurationSpec() *PriorityLevelConfigurationSpecApplyConfiguration {\n\treturn \u0026PriorityLevelConfigurationSpecApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100023084,"name":"WithType","signature":"func (b *PriorityLevelConfigurationSpecApplyConfiguration) WithType(value v1alpha1.PriorityLevelEnablement) *PriorityLevelConfigurationSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfigurationspec.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationSpecApplyConfiguration) WithType(value v1alpha1.PriorityLevelEnablement) *PriorityLevelConfigurationSpecApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100023085,"name":"WithLimited","signature":"func (b *PriorityLevelConfigurationSpecApplyConfiguration) WithLimited(value *LimitedPriorityLevelConfigurationApplyConfiguration) *PriorityLevelConfigurationSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfigurationspec.go","code":"// WithLimited sets the Limited field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Limited field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationSpecApplyConfiguration) WithLimited(value *LimitedPriorityLevelConfigurationApplyConfiguration) *PriorityLevelConfigurationSpecApplyConfiguration {\n\tb.Limited = value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100023086,"name":"PriorityLevelConfigurationStatus","signature":"func PriorityLevelConfigurationStatus() *PriorityLevelConfigurationStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfigurationstatus.go","code":"// PriorityLevelConfigurationStatusApplyConfiguration constructs an declarative configuration of the PriorityLevelConfigurationStatus type for use with\n// apply.\nfunc PriorityLevelConfigurationStatus() *PriorityLevelConfigurationStatusApplyConfiguration {\n\treturn \u0026PriorityLevelConfigurationStatusApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023087,"name":"WithConditions","signature":"func (b *PriorityLevelConfigurationStatusApplyConfiguration) WithConditions(values ...*PriorityLevelConfigurationConditionApplyConfiguration) *PriorityLevelConfigurationStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/prioritylevelconfigurationstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *PriorityLevelConfigurationStatusApplyConfiguration) WithConditions(values ...*PriorityLevelConfigurationConditionApplyConfiguration) *PriorityLevelConfigurationStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100023088,"name":"QueuingConfiguration","signature":"func QueuingConfiguration() *QueuingConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/queuingconfiguration.go","code":"// QueuingConfigurationApplyConfiguration constructs an declarative configuration of the QueuingConfiguration type for use with\n// apply.\nfunc QueuingConfiguration() *QueuingConfigurationApplyConfiguration {\n\treturn \u0026QueuingConfigurationApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100023089,"name":"WithQueues","signature":"func (b *QueuingConfigurationApplyConfiguration) WithQueues(value int32) *QueuingConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/queuingconfiguration.go","code":"// WithQueues sets the Queues field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Queues field is set to the value of the last call.\nfunc (b *QueuingConfigurationApplyConfiguration) WithQueues(value int32) *QueuingConfigurationApplyConfiguration {\n\tb.Queues = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100023090,"name":"WithHandSize","signature":"func (b *QueuingConfigurationApplyConfiguration) WithHandSize(value int32) *QueuingConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/queuingconfiguration.go","code":"// WithHandSize sets the HandSize field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HandSize field is set to the value of the last call.\nfunc (b *QueuingConfigurationApplyConfiguration) WithHandSize(value int32) *QueuingConfigurationApplyConfiguration {\n\tb.HandSize = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100023091,"name":"WithQueueLengthLimit","signature":"func (b *QueuingConfigurationApplyConfiguration) WithQueueLengthLimit(value int32) *QueuingConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/queuingconfiguration.go","code":"// WithQueueLengthLimit sets the QueueLengthLimit field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the QueueLengthLimit field is set to the value of the last call.\nfunc (b *QueuingConfigurationApplyConfiguration) WithQueueLengthLimit(value int32) *QueuingConfigurationApplyConfiguration {\n\tb.QueueLengthLimit = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100023092,"name":"ResourcePolicyRule","signature":"func ResourcePolicyRule() *ResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/resourcepolicyrule.go","code":"// ResourcePolicyRuleApplyConfiguration constructs an declarative configuration of the ResourcePolicyRule type for use with\n// apply.\nfunc ResourcePolicyRule() *ResourcePolicyRuleApplyConfiguration {\n\treturn \u0026ResourcePolicyRuleApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100023093,"name":"WithVerbs","signature":"func (b *ResourcePolicyRuleApplyConfiguration) WithVerbs(values ...string) *ResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/resourcepolicyrule.go","code":"// WithVerbs adds the given value to the Verbs field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Verbs field.\nfunc (b *ResourcePolicyRuleApplyConfiguration) WithVerbs(values ...string) *ResourcePolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.Verbs = append(b.Verbs, values[i])\n\t}\n\treturn b\n}","line":{"from":37,"to":45}} {"id":100023094,"name":"WithAPIGroups","signature":"func (b *ResourcePolicyRuleApplyConfiguration) WithAPIGroups(values ...string) *ResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/resourcepolicyrule.go","code":"// WithAPIGroups adds the given value to the APIGroups field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the APIGroups field.\nfunc (b *ResourcePolicyRuleApplyConfiguration) WithAPIGroups(values ...string) *ResourcePolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.APIGroups = append(b.APIGroups, values[i])\n\t}\n\treturn b\n}","line":{"from":47,"to":55}} {"id":100023095,"name":"WithResources","signature":"func (b *ResourcePolicyRuleApplyConfiguration) WithResources(values ...string) *ResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/resourcepolicyrule.go","code":"// WithResources adds the given value to the Resources field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Resources field.\nfunc (b *ResourcePolicyRuleApplyConfiguration) WithResources(values ...string) *ResourcePolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.Resources = append(b.Resources, values[i])\n\t}\n\treturn b\n}","line":{"from":57,"to":65}} {"id":100023096,"name":"WithClusterScope","signature":"func (b *ResourcePolicyRuleApplyConfiguration) WithClusterScope(value bool) *ResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/resourcepolicyrule.go","code":"// WithClusterScope sets the ClusterScope field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ClusterScope field is set to the value of the last call.\nfunc (b *ResourcePolicyRuleApplyConfiguration) WithClusterScope(value bool) *ResourcePolicyRuleApplyConfiguration {\n\tb.ClusterScope = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100023097,"name":"WithNamespaces","signature":"func (b *ResourcePolicyRuleApplyConfiguration) WithNamespaces(values ...string) *ResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/resourcepolicyrule.go","code":"// WithNamespaces adds the given value to the Namespaces field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Namespaces field.\nfunc (b *ResourcePolicyRuleApplyConfiguration) WithNamespaces(values ...string) *ResourcePolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.Namespaces = append(b.Namespaces, values[i])\n\t}\n\treturn b\n}","line":{"from":75,"to":83}} {"id":100023098,"name":"ServiceAccountSubject","signature":"func ServiceAccountSubject() *ServiceAccountSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/serviceaccountsubject.go","code":"// ServiceAccountSubjectApplyConfiguration constructs an declarative configuration of the ServiceAccountSubject type for use with\n// apply.\nfunc ServiceAccountSubject() *ServiceAccountSubjectApplyConfiguration {\n\treturn \u0026ServiceAccountSubjectApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100023099,"name":"WithNamespace","signature":"func (b *ServiceAccountSubjectApplyConfiguration) WithNamespace(value string) *ServiceAccountSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/serviceaccountsubject.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ServiceAccountSubjectApplyConfiguration) WithNamespace(value string) *ServiceAccountSubjectApplyConfiguration {\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100023100,"name":"WithName","signature":"func (b *ServiceAccountSubjectApplyConfiguration) WithName(value string) *ServiceAccountSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/serviceaccountsubject.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ServiceAccountSubjectApplyConfiguration) WithName(value string) *ServiceAccountSubjectApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100023101,"name":"Subject","signature":"func Subject() *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/subject.go","code":"// SubjectApplyConfiguration constructs an declarative configuration of the Subject type for use with\n// apply.\nfunc Subject() *SubjectApplyConfiguration {\n\treturn \u0026SubjectApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100023102,"name":"WithKind","signature":"func (b *SubjectApplyConfiguration) WithKind(value v1alpha1.SubjectKind) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/subject.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithKind(value v1alpha1.SubjectKind) *SubjectApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":40,"to":46}} {"id":100023103,"name":"WithUser","signature":"func (b *SubjectApplyConfiguration) WithUser(value *UserSubjectApplyConfiguration) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/subject.go","code":"// WithUser sets the User field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the User field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithUser(value *UserSubjectApplyConfiguration) *SubjectApplyConfiguration {\n\tb.User = value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100023104,"name":"WithGroup","signature":"func (b *SubjectApplyConfiguration) WithGroup(value *GroupSubjectApplyConfiguration) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/subject.go","code":"// WithGroup sets the Group field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Group field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithGroup(value *GroupSubjectApplyConfiguration) *SubjectApplyConfiguration {\n\tb.Group = value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100023105,"name":"WithServiceAccount","signature":"func (b *SubjectApplyConfiguration) WithServiceAccount(value *ServiceAccountSubjectApplyConfiguration) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/subject.go","code":"// WithServiceAccount sets the ServiceAccount field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ServiceAccount field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithServiceAccount(value *ServiceAccountSubjectApplyConfiguration) *SubjectApplyConfiguration {\n\tb.ServiceAccount = value\n\treturn b\n}","line":{"from":64,"to":70}} {"id":100023106,"name":"UserSubject","signature":"func UserSubject() *UserSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/usersubject.go","code":"// UserSubjectApplyConfiguration constructs an declarative configuration of the UserSubject type for use with\n// apply.\nfunc UserSubject() *UserSubjectApplyConfiguration {\n\treturn \u0026UserSubjectApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023107,"name":"WithName","signature":"func (b *UserSubjectApplyConfiguration) WithName(value string) *UserSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1alpha1/usersubject.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *UserSubjectApplyConfiguration) WithName(value string) *UserSubjectApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100023108,"name":"FlowDistinguisherMethod","signature":"func FlowDistinguisherMethod() *FlowDistinguisherMethodApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowdistinguishermethod.go","code":"// FlowDistinguisherMethodApplyConfiguration constructs an declarative configuration of the FlowDistinguisherMethod type for use with\n// apply.\nfunc FlowDistinguisherMethod() *FlowDistinguisherMethodApplyConfiguration {\n\treturn \u0026FlowDistinguisherMethodApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100023109,"name":"WithType","signature":"func (b *FlowDistinguisherMethodApplyConfiguration) WithType(value v1beta1.FlowDistinguisherMethodType) *FlowDistinguisherMethodApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowdistinguishermethod.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *FlowDistinguisherMethodApplyConfiguration) WithType(value v1beta1.FlowDistinguisherMethodType) *FlowDistinguisherMethodApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":37,"to":43}} {"id":100023110,"name":"FlowSchema","signature":"func FlowSchema(name string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschema.go","code":"// FlowSchema constructs an declarative configuration of the FlowSchema type for use with\n// apply.\nfunc FlowSchema(name string) *FlowSchemaApplyConfiguration {\n\tb := \u0026FlowSchemaApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"FlowSchema\")\n\tb.WithAPIVersion(\"flowcontrol.apiserver.k8s.io/v1beta1\")\n\treturn b\n}","line":{"from":39,"to":47}} {"id":100023111,"name":"ExtractFlowSchema","signature":"func ExtractFlowSchema(flowSchema *flowcontrolv1beta1.FlowSchema, fieldManager string) (*FlowSchemaApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschema.go","code":"// ExtractFlowSchema extracts the applied configuration owned by fieldManager from\n// flowSchema. If no managedFields are found in flowSchema for fieldManager, a\n// FlowSchemaApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// flowSchema must be a unmodified FlowSchema API object that was retrieved from the Kubernetes API.\n// ExtractFlowSchema provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractFlowSchema(flowSchema *flowcontrolv1beta1.FlowSchema, fieldManager string) (*FlowSchemaApplyConfiguration, error) {\n\treturn extractFlowSchema(flowSchema, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100023112,"name":"ExtractFlowSchemaStatus","signature":"func ExtractFlowSchemaStatus(flowSchema *flowcontrolv1beta1.FlowSchema, fieldManager string) (*FlowSchemaApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschema.go","code":"// ExtractFlowSchemaStatus is the same as ExtractFlowSchema except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractFlowSchemaStatus(flowSchema *flowcontrolv1beta1.FlowSchema, fieldManager string) (*FlowSchemaApplyConfiguration, error) {\n\treturn extractFlowSchema(flowSchema, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100023113,"name":"extractFlowSchema","signature":"func extractFlowSchema(flowSchema *flowcontrolv1beta1.FlowSchema, fieldManager string, subresource string) (*FlowSchemaApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschema.go","code":"func extractFlowSchema(flowSchema *flowcontrolv1beta1.FlowSchema, fieldManager string, subresource string) (*FlowSchemaApplyConfiguration, error) {\n\tb := \u0026FlowSchemaApplyConfiguration{}\n\terr := managedfields.ExtractInto(flowSchema, internal.Parser().Type(\"io.k8s.api.flowcontrol.v1beta1.FlowSchema\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(flowSchema.Name)\n\n\tb.WithKind(\"FlowSchema\")\n\tb.WithAPIVersion(\"flowcontrol.apiserver.k8s.io/v1beta1\")\n\treturn b, nil\n}","line":{"from":71,"to":82}} {"id":100023114,"name":"WithKind","signature":"func (b *FlowSchemaApplyConfiguration) WithKind(value string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschema.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithKind(value string) *FlowSchemaApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100023115,"name":"WithAPIVersion","signature":"func (b *FlowSchemaApplyConfiguration) WithAPIVersion(value string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschema.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithAPIVersion(value string) *FlowSchemaApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100023116,"name":"WithName","signature":"func (b *FlowSchemaApplyConfiguration) WithName(value string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschema.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithName(value string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":100,"to":107}} {"id":100023117,"name":"WithGenerateName","signature":"func (b *FlowSchemaApplyConfiguration) WithGenerateName(value string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschema.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithGenerateName(value string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":109,"to":116}} {"id":100023118,"name":"WithNamespace","signature":"func (b *FlowSchemaApplyConfiguration) WithNamespace(value string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschema.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithNamespace(value string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":118,"to":125}} {"id":100023119,"name":"WithUID","signature":"func (b *FlowSchemaApplyConfiguration) WithUID(value types.UID) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschema.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithUID(value types.UID) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":127,"to":134}} {"id":100023120,"name":"WithResourceVersion","signature":"func (b *FlowSchemaApplyConfiguration) WithResourceVersion(value string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschema.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithResourceVersion(value string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":136,"to":143}} {"id":100023121,"name":"WithGeneration","signature":"func (b *FlowSchemaApplyConfiguration) WithGeneration(value int64) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschema.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithGeneration(value int64) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":145,"to":152}} {"id":100023122,"name":"WithCreationTimestamp","signature":"func (b *FlowSchemaApplyConfiguration) WithCreationTimestamp(value metav1.Time) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschema.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithCreationTimestamp(value metav1.Time) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":154,"to":161}} {"id":100023123,"name":"WithDeletionTimestamp","signature":"func (b *FlowSchemaApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschema.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":163,"to":170}} {"id":100023124,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *FlowSchemaApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschema.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":172,"to":179}} {"id":100023125,"name":"WithLabels","signature":"func (b *FlowSchemaApplyConfiguration) WithLabels(entries map[string]string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschema.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *FlowSchemaApplyConfiguration) WithLabels(entries map[string]string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":181,"to":194}} {"id":100023126,"name":"WithAnnotations","signature":"func (b *FlowSchemaApplyConfiguration) WithAnnotations(entries map[string]string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschema.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *FlowSchemaApplyConfiguration) WithAnnotations(entries map[string]string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100023127,"name":"WithOwnerReferences","signature":"func (b *FlowSchemaApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschema.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *FlowSchemaApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":211,"to":223}} {"id":100023128,"name":"WithFinalizers","signature":"func (b *FlowSchemaApplyConfiguration) WithFinalizers(values ...string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschema.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *FlowSchemaApplyConfiguration) WithFinalizers(values ...string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":225,"to":234}} {"id":100023129,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *FlowSchemaApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschema.go","code":"func (b *FlowSchemaApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":236,"to":240}} {"id":100023130,"name":"WithSpec","signature":"func (b *FlowSchemaApplyConfiguration) WithSpec(value *FlowSchemaSpecApplyConfiguration) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschema.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithSpec(value *FlowSchemaSpecApplyConfiguration) *FlowSchemaApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":242,"to":248}} {"id":100023131,"name":"WithStatus","signature":"func (b *FlowSchemaApplyConfiguration) WithStatus(value *FlowSchemaStatusApplyConfiguration) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschema.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithStatus(value *FlowSchemaStatusApplyConfiguration) *FlowSchemaApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":250,"to":256}} {"id":100023132,"name":"FlowSchemaCondition","signature":"func FlowSchemaCondition() *FlowSchemaConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschemacondition.go","code":"// FlowSchemaConditionApplyConfiguration constructs an declarative configuration of the FlowSchemaCondition type for use with\n// apply.\nfunc FlowSchemaCondition() *FlowSchemaConditionApplyConfiguration {\n\treturn \u0026FlowSchemaConditionApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100023133,"name":"WithType","signature":"func (b *FlowSchemaConditionApplyConfiguration) WithType(value v1beta1.FlowSchemaConditionType) *FlowSchemaConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschemacondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *FlowSchemaConditionApplyConfiguration) WithType(value v1beta1.FlowSchemaConditionType) *FlowSchemaConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100023134,"name":"WithStatus","signature":"func (b *FlowSchemaConditionApplyConfiguration) WithStatus(value v1beta1.ConditionStatus) *FlowSchemaConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschemacondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *FlowSchemaConditionApplyConfiguration) WithStatus(value v1beta1.ConditionStatus) *FlowSchemaConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100023135,"name":"WithLastTransitionTime","signature":"func (b *FlowSchemaConditionApplyConfiguration) WithLastTransitionTime(value v1.Time) *FlowSchemaConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschemacondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *FlowSchemaConditionApplyConfiguration) WithLastTransitionTime(value v1.Time) *FlowSchemaConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100023136,"name":"WithReason","signature":"func (b *FlowSchemaConditionApplyConfiguration) WithReason(value string) *FlowSchemaConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschemacondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *FlowSchemaConditionApplyConfiguration) WithReason(value string) *FlowSchemaConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100023137,"name":"WithMessage","signature":"func (b *FlowSchemaConditionApplyConfiguration) WithMessage(value string) *FlowSchemaConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschemacondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *FlowSchemaConditionApplyConfiguration) WithMessage(value string) *FlowSchemaConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100023138,"name":"FlowSchemaSpec","signature":"func FlowSchemaSpec() *FlowSchemaSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschemaspec.go","code":"// FlowSchemaSpecApplyConfiguration constructs an declarative configuration of the FlowSchemaSpec type for use with\n// apply.\nfunc FlowSchemaSpec() *FlowSchemaSpecApplyConfiguration {\n\treturn \u0026FlowSchemaSpecApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100023139,"name":"WithPriorityLevelConfiguration","signature":"func (b *FlowSchemaSpecApplyConfiguration) WithPriorityLevelConfiguration(value *PriorityLevelConfigurationReferenceApplyConfiguration) *FlowSchemaSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschemaspec.go","code":"// WithPriorityLevelConfiguration sets the PriorityLevelConfiguration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PriorityLevelConfiguration field is set to the value of the last call.\nfunc (b *FlowSchemaSpecApplyConfiguration) WithPriorityLevelConfiguration(value *PriorityLevelConfigurationReferenceApplyConfiguration) *FlowSchemaSpecApplyConfiguration {\n\tb.PriorityLevelConfiguration = value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100023140,"name":"WithMatchingPrecedence","signature":"func (b *FlowSchemaSpecApplyConfiguration) WithMatchingPrecedence(value int32) *FlowSchemaSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschemaspec.go","code":"// WithMatchingPrecedence sets the MatchingPrecedence field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MatchingPrecedence field is set to the value of the last call.\nfunc (b *FlowSchemaSpecApplyConfiguration) WithMatchingPrecedence(value int32) *FlowSchemaSpecApplyConfiguration {\n\tb.MatchingPrecedence = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100023141,"name":"WithDistinguisherMethod","signature":"func (b *FlowSchemaSpecApplyConfiguration) WithDistinguisherMethod(value *FlowDistinguisherMethodApplyConfiguration) *FlowSchemaSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschemaspec.go","code":"// WithDistinguisherMethod sets the DistinguisherMethod field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DistinguisherMethod field is set to the value of the last call.\nfunc (b *FlowSchemaSpecApplyConfiguration) WithDistinguisherMethod(value *FlowDistinguisherMethodApplyConfiguration) *FlowSchemaSpecApplyConfiguration {\n\tb.DistinguisherMethod = value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100023142,"name":"WithRules","signature":"func (b *FlowSchemaSpecApplyConfiguration) WithRules(values ...*PolicyRulesWithSubjectsApplyConfiguration) *FlowSchemaSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschemaspec.go","code":"// WithRules adds the given value to the Rules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Rules field.\nfunc (b *FlowSchemaSpecApplyConfiguration) WithRules(values ...*PolicyRulesWithSubjectsApplyConfiguration) *FlowSchemaSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRules\")\n\t\t}\n\t\tb.Rules = append(b.Rules, *values[i])\n\t}\n\treturn b\n}","line":{"from":60,"to":71}} {"id":100023143,"name":"FlowSchemaStatus","signature":"func FlowSchemaStatus() *FlowSchemaStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschemastatus.go","code":"// FlowSchemaStatusApplyConfiguration constructs an declarative configuration of the FlowSchemaStatus type for use with\n// apply.\nfunc FlowSchemaStatus() *FlowSchemaStatusApplyConfiguration {\n\treturn \u0026FlowSchemaStatusApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023144,"name":"WithConditions","signature":"func (b *FlowSchemaStatusApplyConfiguration) WithConditions(values ...*FlowSchemaConditionApplyConfiguration) *FlowSchemaStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/flowschemastatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *FlowSchemaStatusApplyConfiguration) WithConditions(values ...*FlowSchemaConditionApplyConfiguration) *FlowSchemaStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100023145,"name":"GroupSubject","signature":"func GroupSubject() *GroupSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/groupsubject.go","code":"// GroupSubjectApplyConfiguration constructs an declarative configuration of the GroupSubject type for use with\n// apply.\nfunc GroupSubject() *GroupSubjectApplyConfiguration {\n\treturn \u0026GroupSubjectApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023146,"name":"WithName","signature":"func (b *GroupSubjectApplyConfiguration) WithName(value string) *GroupSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/groupsubject.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *GroupSubjectApplyConfiguration) WithName(value string) *GroupSubjectApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100023147,"name":"LimitedPriorityLevelConfiguration","signature":"func LimitedPriorityLevelConfiguration() *LimitedPriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/limitedprioritylevelconfiguration.go","code":"// LimitedPriorityLevelConfigurationApplyConfiguration constructs an declarative configuration of the LimitedPriorityLevelConfiguration type for use with\n// apply.\nfunc LimitedPriorityLevelConfiguration() *LimitedPriorityLevelConfigurationApplyConfiguration {\n\treturn \u0026LimitedPriorityLevelConfigurationApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100023148,"name":"WithAssuredConcurrencyShares","signature":"func (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithAssuredConcurrencyShares(value int32) *LimitedPriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/limitedprioritylevelconfiguration.go","code":"// WithAssuredConcurrencyShares sets the AssuredConcurrencyShares field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AssuredConcurrencyShares field is set to the value of the last call.\nfunc (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithAssuredConcurrencyShares(value int32) *LimitedPriorityLevelConfigurationApplyConfiguration {\n\tb.AssuredConcurrencyShares = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100023149,"name":"WithLimitResponse","signature":"func (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithLimitResponse(value *LimitResponseApplyConfiguration) *LimitedPriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/limitedprioritylevelconfiguration.go","code":"// WithLimitResponse sets the LimitResponse field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LimitResponse field is set to the value of the last call.\nfunc (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithLimitResponse(value *LimitResponseApplyConfiguration) *LimitedPriorityLevelConfigurationApplyConfiguration {\n\tb.LimitResponse = value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100023150,"name":"WithLendablePercent","signature":"func (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithLendablePercent(value int32) *LimitedPriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/limitedprioritylevelconfiguration.go","code":"// WithLendablePercent sets the LendablePercent field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LendablePercent field is set to the value of the last call.\nfunc (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithLendablePercent(value int32) *LimitedPriorityLevelConfigurationApplyConfiguration {\n\tb.LendablePercent = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100023151,"name":"WithBorrowingLimitPercent","signature":"func (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithBorrowingLimitPercent(value int32) *LimitedPriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/limitedprioritylevelconfiguration.go","code":"// WithBorrowingLimitPercent sets the BorrowingLimitPercent field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the BorrowingLimitPercent field is set to the value of the last call.\nfunc (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithBorrowingLimitPercent(value int32) *LimitedPriorityLevelConfigurationApplyConfiguration {\n\tb.BorrowingLimitPercent = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100023152,"name":"LimitResponse","signature":"func LimitResponse() *LimitResponseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/limitresponse.go","code":"// LimitResponseApplyConfiguration constructs an declarative configuration of the LimitResponse type for use with\n// apply.\nfunc LimitResponse() *LimitResponseApplyConfiguration {\n\treturn \u0026LimitResponseApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100023153,"name":"WithType","signature":"func (b *LimitResponseApplyConfiguration) WithType(value v1beta1.LimitResponseType) *LimitResponseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/limitresponse.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *LimitResponseApplyConfiguration) WithType(value v1beta1.LimitResponseType) *LimitResponseApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100023154,"name":"WithQueuing","signature":"func (b *LimitResponseApplyConfiguration) WithQueuing(value *QueuingConfigurationApplyConfiguration) *LimitResponseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/limitresponse.go","code":"// WithQueuing sets the Queuing field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Queuing field is set to the value of the last call.\nfunc (b *LimitResponseApplyConfiguration) WithQueuing(value *QueuingConfigurationApplyConfiguration) *LimitResponseApplyConfiguration {\n\tb.Queuing = value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100023155,"name":"NonResourcePolicyRule","signature":"func NonResourcePolicyRule() *NonResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/nonresourcepolicyrule.go","code":"// NonResourcePolicyRuleApplyConfiguration constructs an declarative configuration of the NonResourcePolicyRule type for use with\n// apply.\nfunc NonResourcePolicyRule() *NonResourcePolicyRuleApplyConfiguration {\n\treturn \u0026NonResourcePolicyRuleApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100023156,"name":"WithVerbs","signature":"func (b *NonResourcePolicyRuleApplyConfiguration) WithVerbs(values ...string) *NonResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/nonresourcepolicyrule.go","code":"// WithVerbs adds the given value to the Verbs field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Verbs field.\nfunc (b *NonResourcePolicyRuleApplyConfiguration) WithVerbs(values ...string) *NonResourcePolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.Verbs = append(b.Verbs, values[i])\n\t}\n\treturn b\n}","line":{"from":34,"to":42}} {"id":100023157,"name":"WithNonResourceURLs","signature":"func (b *NonResourcePolicyRuleApplyConfiguration) WithNonResourceURLs(values ...string) *NonResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/nonresourcepolicyrule.go","code":"// WithNonResourceURLs adds the given value to the NonResourceURLs field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the NonResourceURLs field.\nfunc (b *NonResourcePolicyRuleApplyConfiguration) WithNonResourceURLs(values ...string) *NonResourcePolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.NonResourceURLs = append(b.NonResourceURLs, values[i])\n\t}\n\treturn b\n}","line":{"from":44,"to":52}} {"id":100023158,"name":"PolicyRulesWithSubjects","signature":"func PolicyRulesWithSubjects() *PolicyRulesWithSubjectsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/policyruleswithsubjects.go","code":"// PolicyRulesWithSubjectsApplyConfiguration constructs an declarative configuration of the PolicyRulesWithSubjects type for use with\n// apply.\nfunc PolicyRulesWithSubjects() *PolicyRulesWithSubjectsApplyConfiguration {\n\treturn \u0026PolicyRulesWithSubjectsApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100023159,"name":"WithSubjects","signature":"func (b *PolicyRulesWithSubjectsApplyConfiguration) WithSubjects(values ...*SubjectApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/policyruleswithsubjects.go","code":"// WithSubjects adds the given value to the Subjects field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Subjects field.\nfunc (b *PolicyRulesWithSubjectsApplyConfiguration) WithSubjects(values ...*SubjectApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithSubjects\")\n\t\t}\n\t\tb.Subjects = append(b.Subjects, *values[i])\n\t}\n\treturn b\n}","line":{"from":35,"to":46}} {"id":100023160,"name":"WithResourceRules","signature":"func (b *PolicyRulesWithSubjectsApplyConfiguration) WithResourceRules(values ...*ResourcePolicyRuleApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/policyruleswithsubjects.go","code":"// WithResourceRules adds the given value to the ResourceRules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ResourceRules field.\nfunc (b *PolicyRulesWithSubjectsApplyConfiguration) WithResourceRules(values ...*ResourcePolicyRuleApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithResourceRules\")\n\t\t}\n\t\tb.ResourceRules = append(b.ResourceRules, *values[i])\n\t}\n\treturn b\n}","line":{"from":48,"to":59}} {"id":100023161,"name":"WithNonResourceRules","signature":"func (b *PolicyRulesWithSubjectsApplyConfiguration) WithNonResourceRules(values ...*NonResourcePolicyRuleApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/policyruleswithsubjects.go","code":"// WithNonResourceRules adds the given value to the NonResourceRules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the NonResourceRules field.\nfunc (b *PolicyRulesWithSubjectsApplyConfiguration) WithNonResourceRules(values ...*NonResourcePolicyRuleApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithNonResourceRules\")\n\t\t}\n\t\tb.NonResourceRules = append(b.NonResourceRules, *values[i])\n\t}\n\treturn b\n}","line":{"from":61,"to":72}} {"id":100023162,"name":"PriorityLevelConfiguration","signature":"func PriorityLevelConfiguration(name string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// PriorityLevelConfiguration constructs an declarative configuration of the PriorityLevelConfiguration type for use with\n// apply.\nfunc PriorityLevelConfiguration(name string) *PriorityLevelConfigurationApplyConfiguration {\n\tb := \u0026PriorityLevelConfigurationApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"PriorityLevelConfiguration\")\n\tb.WithAPIVersion(\"flowcontrol.apiserver.k8s.io/v1beta1\")\n\treturn b\n}","line":{"from":39,"to":47}} {"id":100023163,"name":"ExtractPriorityLevelConfiguration","signature":"func ExtractPriorityLevelConfiguration(priorityLevelConfiguration *flowcontrolv1beta1.PriorityLevelConfiguration, fieldManager string) (*PriorityLevelConfigurationApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// ExtractPriorityLevelConfiguration extracts the applied configuration owned by fieldManager from\n// priorityLevelConfiguration. If no managedFields are found in priorityLevelConfiguration for fieldManager, a\n// PriorityLevelConfigurationApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// priorityLevelConfiguration must be a unmodified PriorityLevelConfiguration API object that was retrieved from the Kubernetes API.\n// ExtractPriorityLevelConfiguration provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractPriorityLevelConfiguration(priorityLevelConfiguration *flowcontrolv1beta1.PriorityLevelConfiguration, fieldManager string) (*PriorityLevelConfigurationApplyConfiguration, error) {\n\treturn extractPriorityLevelConfiguration(priorityLevelConfiguration, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100023164,"name":"ExtractPriorityLevelConfigurationStatus","signature":"func ExtractPriorityLevelConfigurationStatus(priorityLevelConfiguration *flowcontrolv1beta1.PriorityLevelConfiguration, fieldManager string) (*PriorityLevelConfigurationApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// ExtractPriorityLevelConfigurationStatus is the same as ExtractPriorityLevelConfiguration except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractPriorityLevelConfigurationStatus(priorityLevelConfiguration *flowcontrolv1beta1.PriorityLevelConfiguration, fieldManager string) (*PriorityLevelConfigurationApplyConfiguration, error) {\n\treturn extractPriorityLevelConfiguration(priorityLevelConfiguration, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100023165,"name":"extractPriorityLevelConfiguration","signature":"func extractPriorityLevelConfiguration(priorityLevelConfiguration *flowcontrolv1beta1.PriorityLevelConfiguration, fieldManager string, subresource string) (*PriorityLevelConfigurationApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"func extractPriorityLevelConfiguration(priorityLevelConfiguration *flowcontrolv1beta1.PriorityLevelConfiguration, fieldManager string, subresource string) (*PriorityLevelConfigurationApplyConfiguration, error) {\n\tb := \u0026PriorityLevelConfigurationApplyConfiguration{}\n\terr := managedfields.ExtractInto(priorityLevelConfiguration, internal.Parser().Type(\"io.k8s.api.flowcontrol.v1beta1.PriorityLevelConfiguration\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(priorityLevelConfiguration.Name)\n\n\tb.WithKind(\"PriorityLevelConfiguration\")\n\tb.WithAPIVersion(\"flowcontrol.apiserver.k8s.io/v1beta1\")\n\treturn b, nil\n}","line":{"from":71,"to":82}} {"id":100023166,"name":"WithKind","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithKind(value string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithKind(value string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100023167,"name":"WithAPIVersion","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithAPIVersion(value string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithAPIVersion(value string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100023168,"name":"WithName","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithName(value string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithName(value string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":100,"to":107}} {"id":100023169,"name":"WithGenerateName","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithGenerateName(value string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithGenerateName(value string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":109,"to":116}} {"id":100023170,"name":"WithNamespace","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithNamespace(value string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithNamespace(value string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":118,"to":125}} {"id":100023171,"name":"WithUID","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithUID(value types.UID) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithUID(value types.UID) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":127,"to":134}} {"id":100023172,"name":"WithResourceVersion","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithResourceVersion(value string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithResourceVersion(value string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":136,"to":143}} {"id":100023173,"name":"WithGeneration","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithGeneration(value int64) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithGeneration(value int64) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":145,"to":152}} {"id":100023174,"name":"WithCreationTimestamp","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":154,"to":161}} {"id":100023175,"name":"WithDeletionTimestamp","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":163,"to":170}} {"id":100023176,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":172,"to":179}} {"id":100023177,"name":"WithLabels","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithLabels(entries map[string]string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithLabels(entries map[string]string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":181,"to":194}} {"id":100023178,"name":"WithAnnotations","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithAnnotations(entries map[string]string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithAnnotations(entries map[string]string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100023179,"name":"WithOwnerReferences","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":211,"to":223}} {"id":100023180,"name":"WithFinalizers","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithFinalizers(values ...string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithFinalizers(values ...string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":225,"to":234}} {"id":100023181,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"func (b *PriorityLevelConfigurationApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":236,"to":240}} {"id":100023182,"name":"WithSpec","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithSpec(value *PriorityLevelConfigurationSpecApplyConfiguration) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithSpec(value *PriorityLevelConfigurationSpecApplyConfiguration) *PriorityLevelConfigurationApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":242,"to":248}} {"id":100023183,"name":"WithStatus","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithStatus(value *PriorityLevelConfigurationStatusApplyConfiguration) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithStatus(value *PriorityLevelConfigurationStatusApplyConfiguration) *PriorityLevelConfigurationApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":250,"to":256}} {"id":100023184,"name":"PriorityLevelConfigurationCondition","signature":"func PriorityLevelConfigurationCondition() *PriorityLevelConfigurationConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfigurationcondition.go","code":"// PriorityLevelConfigurationConditionApplyConfiguration constructs an declarative configuration of the PriorityLevelConfigurationCondition type for use with\n// apply.\nfunc PriorityLevelConfigurationCondition() *PriorityLevelConfigurationConditionApplyConfiguration {\n\treturn \u0026PriorityLevelConfigurationConditionApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100023185,"name":"WithType","signature":"func (b *PriorityLevelConfigurationConditionApplyConfiguration) WithType(value v1beta1.PriorityLevelConfigurationConditionType) *PriorityLevelConfigurationConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfigurationcondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationConditionApplyConfiguration) WithType(value v1beta1.PriorityLevelConfigurationConditionType) *PriorityLevelConfigurationConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100023186,"name":"WithStatus","signature":"func (b *PriorityLevelConfigurationConditionApplyConfiguration) WithStatus(value v1beta1.ConditionStatus) *PriorityLevelConfigurationConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfigurationcondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationConditionApplyConfiguration) WithStatus(value v1beta1.ConditionStatus) *PriorityLevelConfigurationConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100023187,"name":"WithLastTransitionTime","signature":"func (b *PriorityLevelConfigurationConditionApplyConfiguration) WithLastTransitionTime(value v1.Time) *PriorityLevelConfigurationConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfigurationcondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationConditionApplyConfiguration) WithLastTransitionTime(value v1.Time) *PriorityLevelConfigurationConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100023188,"name":"WithReason","signature":"func (b *PriorityLevelConfigurationConditionApplyConfiguration) WithReason(value string) *PriorityLevelConfigurationConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfigurationcondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationConditionApplyConfiguration) WithReason(value string) *PriorityLevelConfigurationConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100023189,"name":"WithMessage","signature":"func (b *PriorityLevelConfigurationConditionApplyConfiguration) WithMessage(value string) *PriorityLevelConfigurationConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfigurationcondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationConditionApplyConfiguration) WithMessage(value string) *PriorityLevelConfigurationConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100023190,"name":"PriorityLevelConfigurationReference","signature":"func PriorityLevelConfigurationReference() *PriorityLevelConfigurationReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfigurationreference.go","code":"// PriorityLevelConfigurationReferenceApplyConfiguration constructs an declarative configuration of the PriorityLevelConfigurationReference type for use with\n// apply.\nfunc PriorityLevelConfigurationReference() *PriorityLevelConfigurationReferenceApplyConfiguration {\n\treturn \u0026PriorityLevelConfigurationReferenceApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023191,"name":"WithName","signature":"func (b *PriorityLevelConfigurationReferenceApplyConfiguration) WithName(value string) *PriorityLevelConfigurationReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfigurationreference.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationReferenceApplyConfiguration) WithName(value string) *PriorityLevelConfigurationReferenceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100023192,"name":"PriorityLevelConfigurationSpec","signature":"func PriorityLevelConfigurationSpec() *PriorityLevelConfigurationSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfigurationspec.go","code":"// PriorityLevelConfigurationSpecApplyConfiguration constructs an declarative configuration of the PriorityLevelConfigurationSpec type for use with\n// apply.\nfunc PriorityLevelConfigurationSpec() *PriorityLevelConfigurationSpecApplyConfiguration {\n\treturn \u0026PriorityLevelConfigurationSpecApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100023193,"name":"WithType","signature":"func (b *PriorityLevelConfigurationSpecApplyConfiguration) WithType(value v1beta1.PriorityLevelEnablement) *PriorityLevelConfigurationSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfigurationspec.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationSpecApplyConfiguration) WithType(value v1beta1.PriorityLevelEnablement) *PriorityLevelConfigurationSpecApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100023194,"name":"WithLimited","signature":"func (b *PriorityLevelConfigurationSpecApplyConfiguration) WithLimited(value *LimitedPriorityLevelConfigurationApplyConfiguration) *PriorityLevelConfigurationSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfigurationspec.go","code":"// WithLimited sets the Limited field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Limited field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationSpecApplyConfiguration) WithLimited(value *LimitedPriorityLevelConfigurationApplyConfiguration) *PriorityLevelConfigurationSpecApplyConfiguration {\n\tb.Limited = value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100023195,"name":"PriorityLevelConfigurationStatus","signature":"func PriorityLevelConfigurationStatus() *PriorityLevelConfigurationStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfigurationstatus.go","code":"// PriorityLevelConfigurationStatusApplyConfiguration constructs an declarative configuration of the PriorityLevelConfigurationStatus type for use with\n// apply.\nfunc PriorityLevelConfigurationStatus() *PriorityLevelConfigurationStatusApplyConfiguration {\n\treturn \u0026PriorityLevelConfigurationStatusApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023196,"name":"WithConditions","signature":"func (b *PriorityLevelConfigurationStatusApplyConfiguration) WithConditions(values ...*PriorityLevelConfigurationConditionApplyConfiguration) *PriorityLevelConfigurationStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/prioritylevelconfigurationstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *PriorityLevelConfigurationStatusApplyConfiguration) WithConditions(values ...*PriorityLevelConfigurationConditionApplyConfiguration) *PriorityLevelConfigurationStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100023197,"name":"QueuingConfiguration","signature":"func QueuingConfiguration() *QueuingConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/queuingconfiguration.go","code":"// QueuingConfigurationApplyConfiguration constructs an declarative configuration of the QueuingConfiguration type for use with\n// apply.\nfunc QueuingConfiguration() *QueuingConfigurationApplyConfiguration {\n\treturn \u0026QueuingConfigurationApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100023198,"name":"WithQueues","signature":"func (b *QueuingConfigurationApplyConfiguration) WithQueues(value int32) *QueuingConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/queuingconfiguration.go","code":"// WithQueues sets the Queues field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Queues field is set to the value of the last call.\nfunc (b *QueuingConfigurationApplyConfiguration) WithQueues(value int32) *QueuingConfigurationApplyConfiguration {\n\tb.Queues = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100023199,"name":"WithHandSize","signature":"func (b *QueuingConfigurationApplyConfiguration) WithHandSize(value int32) *QueuingConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/queuingconfiguration.go","code":"// WithHandSize sets the HandSize field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HandSize field is set to the value of the last call.\nfunc (b *QueuingConfigurationApplyConfiguration) WithHandSize(value int32) *QueuingConfigurationApplyConfiguration {\n\tb.HandSize = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100023200,"name":"WithQueueLengthLimit","signature":"func (b *QueuingConfigurationApplyConfiguration) WithQueueLengthLimit(value int32) *QueuingConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/queuingconfiguration.go","code":"// WithQueueLengthLimit sets the QueueLengthLimit field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the QueueLengthLimit field is set to the value of the last call.\nfunc (b *QueuingConfigurationApplyConfiguration) WithQueueLengthLimit(value int32) *QueuingConfigurationApplyConfiguration {\n\tb.QueueLengthLimit = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100023201,"name":"ResourcePolicyRule","signature":"func ResourcePolicyRule() *ResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/resourcepolicyrule.go","code":"// ResourcePolicyRuleApplyConfiguration constructs an declarative configuration of the ResourcePolicyRule type for use with\n// apply.\nfunc ResourcePolicyRule() *ResourcePolicyRuleApplyConfiguration {\n\treturn \u0026ResourcePolicyRuleApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100023202,"name":"WithVerbs","signature":"func (b *ResourcePolicyRuleApplyConfiguration) WithVerbs(values ...string) *ResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/resourcepolicyrule.go","code":"// WithVerbs adds the given value to the Verbs field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Verbs field.\nfunc (b *ResourcePolicyRuleApplyConfiguration) WithVerbs(values ...string) *ResourcePolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.Verbs = append(b.Verbs, values[i])\n\t}\n\treturn b\n}","line":{"from":37,"to":45}} {"id":100023203,"name":"WithAPIGroups","signature":"func (b *ResourcePolicyRuleApplyConfiguration) WithAPIGroups(values ...string) *ResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/resourcepolicyrule.go","code":"// WithAPIGroups adds the given value to the APIGroups field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the APIGroups field.\nfunc (b *ResourcePolicyRuleApplyConfiguration) WithAPIGroups(values ...string) *ResourcePolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.APIGroups = append(b.APIGroups, values[i])\n\t}\n\treturn b\n}","line":{"from":47,"to":55}} {"id":100023204,"name":"WithResources","signature":"func (b *ResourcePolicyRuleApplyConfiguration) WithResources(values ...string) *ResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/resourcepolicyrule.go","code":"// WithResources adds the given value to the Resources field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Resources field.\nfunc (b *ResourcePolicyRuleApplyConfiguration) WithResources(values ...string) *ResourcePolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.Resources = append(b.Resources, values[i])\n\t}\n\treturn b\n}","line":{"from":57,"to":65}} {"id":100023205,"name":"WithClusterScope","signature":"func (b *ResourcePolicyRuleApplyConfiguration) WithClusterScope(value bool) *ResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/resourcepolicyrule.go","code":"// WithClusterScope sets the ClusterScope field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ClusterScope field is set to the value of the last call.\nfunc (b *ResourcePolicyRuleApplyConfiguration) WithClusterScope(value bool) *ResourcePolicyRuleApplyConfiguration {\n\tb.ClusterScope = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100023206,"name":"WithNamespaces","signature":"func (b *ResourcePolicyRuleApplyConfiguration) WithNamespaces(values ...string) *ResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/resourcepolicyrule.go","code":"// WithNamespaces adds the given value to the Namespaces field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Namespaces field.\nfunc (b *ResourcePolicyRuleApplyConfiguration) WithNamespaces(values ...string) *ResourcePolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.Namespaces = append(b.Namespaces, values[i])\n\t}\n\treturn b\n}","line":{"from":75,"to":83}} {"id":100023207,"name":"ServiceAccountSubject","signature":"func ServiceAccountSubject() *ServiceAccountSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/serviceaccountsubject.go","code":"// ServiceAccountSubjectApplyConfiguration constructs an declarative configuration of the ServiceAccountSubject type for use with\n// apply.\nfunc ServiceAccountSubject() *ServiceAccountSubjectApplyConfiguration {\n\treturn \u0026ServiceAccountSubjectApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100023208,"name":"WithNamespace","signature":"func (b *ServiceAccountSubjectApplyConfiguration) WithNamespace(value string) *ServiceAccountSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/serviceaccountsubject.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ServiceAccountSubjectApplyConfiguration) WithNamespace(value string) *ServiceAccountSubjectApplyConfiguration {\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100023209,"name":"WithName","signature":"func (b *ServiceAccountSubjectApplyConfiguration) WithName(value string) *ServiceAccountSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/serviceaccountsubject.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ServiceAccountSubjectApplyConfiguration) WithName(value string) *ServiceAccountSubjectApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100023210,"name":"Subject","signature":"func Subject() *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/subject.go","code":"// SubjectApplyConfiguration constructs an declarative configuration of the Subject type for use with\n// apply.\nfunc Subject() *SubjectApplyConfiguration {\n\treturn \u0026SubjectApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100023211,"name":"WithKind","signature":"func (b *SubjectApplyConfiguration) WithKind(value v1beta1.SubjectKind) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/subject.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithKind(value v1beta1.SubjectKind) *SubjectApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":40,"to":46}} {"id":100023212,"name":"WithUser","signature":"func (b *SubjectApplyConfiguration) WithUser(value *UserSubjectApplyConfiguration) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/subject.go","code":"// WithUser sets the User field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the User field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithUser(value *UserSubjectApplyConfiguration) *SubjectApplyConfiguration {\n\tb.User = value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100023213,"name":"WithGroup","signature":"func (b *SubjectApplyConfiguration) WithGroup(value *GroupSubjectApplyConfiguration) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/subject.go","code":"// WithGroup sets the Group field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Group field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithGroup(value *GroupSubjectApplyConfiguration) *SubjectApplyConfiguration {\n\tb.Group = value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100023214,"name":"WithServiceAccount","signature":"func (b *SubjectApplyConfiguration) WithServiceAccount(value *ServiceAccountSubjectApplyConfiguration) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/subject.go","code":"// WithServiceAccount sets the ServiceAccount field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ServiceAccount field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithServiceAccount(value *ServiceAccountSubjectApplyConfiguration) *SubjectApplyConfiguration {\n\tb.ServiceAccount = value\n\treturn b\n}","line":{"from":64,"to":70}} {"id":100023215,"name":"UserSubject","signature":"func UserSubject() *UserSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/usersubject.go","code":"// UserSubjectApplyConfiguration constructs an declarative configuration of the UserSubject type for use with\n// apply.\nfunc UserSubject() *UserSubjectApplyConfiguration {\n\treturn \u0026UserSubjectApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023216,"name":"WithName","signature":"func (b *UserSubjectApplyConfiguration) WithName(value string) *UserSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta1/usersubject.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *UserSubjectApplyConfiguration) WithName(value string) *UserSubjectApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100023217,"name":"FlowDistinguisherMethod","signature":"func FlowDistinguisherMethod() *FlowDistinguisherMethodApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowdistinguishermethod.go","code":"// FlowDistinguisherMethodApplyConfiguration constructs an declarative configuration of the FlowDistinguisherMethod type for use with\n// apply.\nfunc FlowDistinguisherMethod() *FlowDistinguisherMethodApplyConfiguration {\n\treturn \u0026FlowDistinguisherMethodApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100023218,"name":"WithType","signature":"func (b *FlowDistinguisherMethodApplyConfiguration) WithType(value v1beta2.FlowDistinguisherMethodType) *FlowDistinguisherMethodApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowdistinguishermethod.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *FlowDistinguisherMethodApplyConfiguration) WithType(value v1beta2.FlowDistinguisherMethodType) *FlowDistinguisherMethodApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":37,"to":43}} {"id":100023219,"name":"FlowSchema","signature":"func FlowSchema(name string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschema.go","code":"// FlowSchema constructs an declarative configuration of the FlowSchema type for use with\n// apply.\nfunc FlowSchema(name string) *FlowSchemaApplyConfiguration {\n\tb := \u0026FlowSchemaApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"FlowSchema\")\n\tb.WithAPIVersion(\"flowcontrol.apiserver.k8s.io/v1beta2\")\n\treturn b\n}","line":{"from":39,"to":47}} {"id":100023220,"name":"ExtractFlowSchema","signature":"func ExtractFlowSchema(flowSchema *flowcontrolv1beta2.FlowSchema, fieldManager string) (*FlowSchemaApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschema.go","code":"// ExtractFlowSchema extracts the applied configuration owned by fieldManager from\n// flowSchema. If no managedFields are found in flowSchema for fieldManager, a\n// FlowSchemaApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// flowSchema must be a unmodified FlowSchema API object that was retrieved from the Kubernetes API.\n// ExtractFlowSchema provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractFlowSchema(flowSchema *flowcontrolv1beta2.FlowSchema, fieldManager string) (*FlowSchemaApplyConfiguration, error) {\n\treturn extractFlowSchema(flowSchema, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100023221,"name":"ExtractFlowSchemaStatus","signature":"func ExtractFlowSchemaStatus(flowSchema *flowcontrolv1beta2.FlowSchema, fieldManager string) (*FlowSchemaApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschema.go","code":"// ExtractFlowSchemaStatus is the same as ExtractFlowSchema except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractFlowSchemaStatus(flowSchema *flowcontrolv1beta2.FlowSchema, fieldManager string) (*FlowSchemaApplyConfiguration, error) {\n\treturn extractFlowSchema(flowSchema, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100023222,"name":"extractFlowSchema","signature":"func extractFlowSchema(flowSchema *flowcontrolv1beta2.FlowSchema, fieldManager string, subresource string) (*FlowSchemaApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschema.go","code":"func extractFlowSchema(flowSchema *flowcontrolv1beta2.FlowSchema, fieldManager string, subresource string) (*FlowSchemaApplyConfiguration, error) {\n\tb := \u0026FlowSchemaApplyConfiguration{}\n\terr := managedfields.ExtractInto(flowSchema, internal.Parser().Type(\"io.k8s.api.flowcontrol.v1beta2.FlowSchema\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(flowSchema.Name)\n\n\tb.WithKind(\"FlowSchema\")\n\tb.WithAPIVersion(\"flowcontrol.apiserver.k8s.io/v1beta2\")\n\treturn b, nil\n}","line":{"from":71,"to":82}} {"id":100023223,"name":"WithKind","signature":"func (b *FlowSchemaApplyConfiguration) WithKind(value string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschema.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithKind(value string) *FlowSchemaApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100023224,"name":"WithAPIVersion","signature":"func (b *FlowSchemaApplyConfiguration) WithAPIVersion(value string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschema.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithAPIVersion(value string) *FlowSchemaApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100023225,"name":"WithName","signature":"func (b *FlowSchemaApplyConfiguration) WithName(value string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschema.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithName(value string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":100,"to":107}} {"id":100023226,"name":"WithGenerateName","signature":"func (b *FlowSchemaApplyConfiguration) WithGenerateName(value string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschema.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithGenerateName(value string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":109,"to":116}} {"id":100023227,"name":"WithNamespace","signature":"func (b *FlowSchemaApplyConfiguration) WithNamespace(value string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschema.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithNamespace(value string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":118,"to":125}} {"id":100023228,"name":"WithUID","signature":"func (b *FlowSchemaApplyConfiguration) WithUID(value types.UID) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschema.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithUID(value types.UID) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":127,"to":134}} {"id":100023229,"name":"WithResourceVersion","signature":"func (b *FlowSchemaApplyConfiguration) WithResourceVersion(value string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschema.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithResourceVersion(value string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":136,"to":143}} {"id":100023230,"name":"WithGeneration","signature":"func (b *FlowSchemaApplyConfiguration) WithGeneration(value int64) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschema.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithGeneration(value int64) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":145,"to":152}} {"id":100023231,"name":"WithCreationTimestamp","signature":"func (b *FlowSchemaApplyConfiguration) WithCreationTimestamp(value metav1.Time) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschema.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithCreationTimestamp(value metav1.Time) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":154,"to":161}} {"id":100023232,"name":"WithDeletionTimestamp","signature":"func (b *FlowSchemaApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschema.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":163,"to":170}} {"id":100023233,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *FlowSchemaApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschema.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":172,"to":179}} {"id":100023234,"name":"WithLabels","signature":"func (b *FlowSchemaApplyConfiguration) WithLabels(entries map[string]string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschema.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *FlowSchemaApplyConfiguration) WithLabels(entries map[string]string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":181,"to":194}} {"id":100023235,"name":"WithAnnotations","signature":"func (b *FlowSchemaApplyConfiguration) WithAnnotations(entries map[string]string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschema.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *FlowSchemaApplyConfiguration) WithAnnotations(entries map[string]string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100023236,"name":"WithOwnerReferences","signature":"func (b *FlowSchemaApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschema.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *FlowSchemaApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":211,"to":223}} {"id":100023237,"name":"WithFinalizers","signature":"func (b *FlowSchemaApplyConfiguration) WithFinalizers(values ...string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschema.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *FlowSchemaApplyConfiguration) WithFinalizers(values ...string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":225,"to":234}} {"id":100023238,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *FlowSchemaApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschema.go","code":"func (b *FlowSchemaApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":236,"to":240}} {"id":100023239,"name":"WithSpec","signature":"func (b *FlowSchemaApplyConfiguration) WithSpec(value *FlowSchemaSpecApplyConfiguration) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschema.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithSpec(value *FlowSchemaSpecApplyConfiguration) *FlowSchemaApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":242,"to":248}} {"id":100023240,"name":"WithStatus","signature":"func (b *FlowSchemaApplyConfiguration) WithStatus(value *FlowSchemaStatusApplyConfiguration) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschema.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithStatus(value *FlowSchemaStatusApplyConfiguration) *FlowSchemaApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":250,"to":256}} {"id":100023241,"name":"FlowSchemaCondition","signature":"func FlowSchemaCondition() *FlowSchemaConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschemacondition.go","code":"// FlowSchemaConditionApplyConfiguration constructs an declarative configuration of the FlowSchemaCondition type for use with\n// apply.\nfunc FlowSchemaCondition() *FlowSchemaConditionApplyConfiguration {\n\treturn \u0026FlowSchemaConditionApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100023242,"name":"WithType","signature":"func (b *FlowSchemaConditionApplyConfiguration) WithType(value v1beta2.FlowSchemaConditionType) *FlowSchemaConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschemacondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *FlowSchemaConditionApplyConfiguration) WithType(value v1beta2.FlowSchemaConditionType) *FlowSchemaConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100023243,"name":"WithStatus","signature":"func (b *FlowSchemaConditionApplyConfiguration) WithStatus(value v1beta2.ConditionStatus) *FlowSchemaConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschemacondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *FlowSchemaConditionApplyConfiguration) WithStatus(value v1beta2.ConditionStatus) *FlowSchemaConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100023244,"name":"WithLastTransitionTime","signature":"func (b *FlowSchemaConditionApplyConfiguration) WithLastTransitionTime(value v1.Time) *FlowSchemaConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschemacondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *FlowSchemaConditionApplyConfiguration) WithLastTransitionTime(value v1.Time) *FlowSchemaConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100023245,"name":"WithReason","signature":"func (b *FlowSchemaConditionApplyConfiguration) WithReason(value string) *FlowSchemaConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschemacondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *FlowSchemaConditionApplyConfiguration) WithReason(value string) *FlowSchemaConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100023246,"name":"WithMessage","signature":"func (b *FlowSchemaConditionApplyConfiguration) WithMessage(value string) *FlowSchemaConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschemacondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *FlowSchemaConditionApplyConfiguration) WithMessage(value string) *FlowSchemaConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100023247,"name":"FlowSchemaSpec","signature":"func FlowSchemaSpec() *FlowSchemaSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschemaspec.go","code":"// FlowSchemaSpecApplyConfiguration constructs an declarative configuration of the FlowSchemaSpec type for use with\n// apply.\nfunc FlowSchemaSpec() *FlowSchemaSpecApplyConfiguration {\n\treturn \u0026FlowSchemaSpecApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100023248,"name":"WithPriorityLevelConfiguration","signature":"func (b *FlowSchemaSpecApplyConfiguration) WithPriorityLevelConfiguration(value *PriorityLevelConfigurationReferenceApplyConfiguration) *FlowSchemaSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschemaspec.go","code":"// WithPriorityLevelConfiguration sets the PriorityLevelConfiguration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PriorityLevelConfiguration field is set to the value of the last call.\nfunc (b *FlowSchemaSpecApplyConfiguration) WithPriorityLevelConfiguration(value *PriorityLevelConfigurationReferenceApplyConfiguration) *FlowSchemaSpecApplyConfiguration {\n\tb.PriorityLevelConfiguration = value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100023249,"name":"WithMatchingPrecedence","signature":"func (b *FlowSchemaSpecApplyConfiguration) WithMatchingPrecedence(value int32) *FlowSchemaSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschemaspec.go","code":"// WithMatchingPrecedence sets the MatchingPrecedence field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MatchingPrecedence field is set to the value of the last call.\nfunc (b *FlowSchemaSpecApplyConfiguration) WithMatchingPrecedence(value int32) *FlowSchemaSpecApplyConfiguration {\n\tb.MatchingPrecedence = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100023250,"name":"WithDistinguisherMethod","signature":"func (b *FlowSchemaSpecApplyConfiguration) WithDistinguisherMethod(value *FlowDistinguisherMethodApplyConfiguration) *FlowSchemaSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschemaspec.go","code":"// WithDistinguisherMethod sets the DistinguisherMethod field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DistinguisherMethod field is set to the value of the last call.\nfunc (b *FlowSchemaSpecApplyConfiguration) WithDistinguisherMethod(value *FlowDistinguisherMethodApplyConfiguration) *FlowSchemaSpecApplyConfiguration {\n\tb.DistinguisherMethod = value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100023251,"name":"WithRules","signature":"func (b *FlowSchemaSpecApplyConfiguration) WithRules(values ...*PolicyRulesWithSubjectsApplyConfiguration) *FlowSchemaSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschemaspec.go","code":"// WithRules adds the given value to the Rules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Rules field.\nfunc (b *FlowSchemaSpecApplyConfiguration) WithRules(values ...*PolicyRulesWithSubjectsApplyConfiguration) *FlowSchemaSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRules\")\n\t\t}\n\t\tb.Rules = append(b.Rules, *values[i])\n\t}\n\treturn b\n}","line":{"from":60,"to":71}} {"id":100023252,"name":"FlowSchemaStatus","signature":"func FlowSchemaStatus() *FlowSchemaStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschemastatus.go","code":"// FlowSchemaStatusApplyConfiguration constructs an declarative configuration of the FlowSchemaStatus type for use with\n// apply.\nfunc FlowSchemaStatus() *FlowSchemaStatusApplyConfiguration {\n\treturn \u0026FlowSchemaStatusApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023253,"name":"WithConditions","signature":"func (b *FlowSchemaStatusApplyConfiguration) WithConditions(values ...*FlowSchemaConditionApplyConfiguration) *FlowSchemaStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/flowschemastatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *FlowSchemaStatusApplyConfiguration) WithConditions(values ...*FlowSchemaConditionApplyConfiguration) *FlowSchemaStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100023254,"name":"GroupSubject","signature":"func GroupSubject() *GroupSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/groupsubject.go","code":"// GroupSubjectApplyConfiguration constructs an declarative configuration of the GroupSubject type for use with\n// apply.\nfunc GroupSubject() *GroupSubjectApplyConfiguration {\n\treturn \u0026GroupSubjectApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023255,"name":"WithName","signature":"func (b *GroupSubjectApplyConfiguration) WithName(value string) *GroupSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/groupsubject.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *GroupSubjectApplyConfiguration) WithName(value string) *GroupSubjectApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100023256,"name":"LimitedPriorityLevelConfiguration","signature":"func LimitedPriorityLevelConfiguration() *LimitedPriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/limitedprioritylevelconfiguration.go","code":"// LimitedPriorityLevelConfigurationApplyConfiguration constructs an declarative configuration of the LimitedPriorityLevelConfiguration type for use with\n// apply.\nfunc LimitedPriorityLevelConfiguration() *LimitedPriorityLevelConfigurationApplyConfiguration {\n\treturn \u0026LimitedPriorityLevelConfigurationApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100023257,"name":"WithAssuredConcurrencyShares","signature":"func (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithAssuredConcurrencyShares(value int32) *LimitedPriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/limitedprioritylevelconfiguration.go","code":"// WithAssuredConcurrencyShares sets the AssuredConcurrencyShares field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AssuredConcurrencyShares field is set to the value of the last call.\nfunc (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithAssuredConcurrencyShares(value int32) *LimitedPriorityLevelConfigurationApplyConfiguration {\n\tb.AssuredConcurrencyShares = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100023258,"name":"WithLimitResponse","signature":"func (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithLimitResponse(value *LimitResponseApplyConfiguration) *LimitedPriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/limitedprioritylevelconfiguration.go","code":"// WithLimitResponse sets the LimitResponse field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LimitResponse field is set to the value of the last call.\nfunc (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithLimitResponse(value *LimitResponseApplyConfiguration) *LimitedPriorityLevelConfigurationApplyConfiguration {\n\tb.LimitResponse = value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100023259,"name":"WithLendablePercent","signature":"func (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithLendablePercent(value int32) *LimitedPriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/limitedprioritylevelconfiguration.go","code":"// WithLendablePercent sets the LendablePercent field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LendablePercent field is set to the value of the last call.\nfunc (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithLendablePercent(value int32) *LimitedPriorityLevelConfigurationApplyConfiguration {\n\tb.LendablePercent = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100023260,"name":"WithBorrowingLimitPercent","signature":"func (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithBorrowingLimitPercent(value int32) *LimitedPriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/limitedprioritylevelconfiguration.go","code":"// WithBorrowingLimitPercent sets the BorrowingLimitPercent field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the BorrowingLimitPercent field is set to the value of the last call.\nfunc (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithBorrowingLimitPercent(value int32) *LimitedPriorityLevelConfigurationApplyConfiguration {\n\tb.BorrowingLimitPercent = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100023261,"name":"LimitResponse","signature":"func LimitResponse() *LimitResponseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/limitresponse.go","code":"// LimitResponseApplyConfiguration constructs an declarative configuration of the LimitResponse type for use with\n// apply.\nfunc LimitResponse() *LimitResponseApplyConfiguration {\n\treturn \u0026LimitResponseApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100023262,"name":"WithType","signature":"func (b *LimitResponseApplyConfiguration) WithType(value v1beta2.LimitResponseType) *LimitResponseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/limitresponse.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *LimitResponseApplyConfiguration) WithType(value v1beta2.LimitResponseType) *LimitResponseApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100023263,"name":"WithQueuing","signature":"func (b *LimitResponseApplyConfiguration) WithQueuing(value *QueuingConfigurationApplyConfiguration) *LimitResponseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/limitresponse.go","code":"// WithQueuing sets the Queuing field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Queuing field is set to the value of the last call.\nfunc (b *LimitResponseApplyConfiguration) WithQueuing(value *QueuingConfigurationApplyConfiguration) *LimitResponseApplyConfiguration {\n\tb.Queuing = value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100023264,"name":"NonResourcePolicyRule","signature":"func NonResourcePolicyRule() *NonResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/nonresourcepolicyrule.go","code":"// NonResourcePolicyRuleApplyConfiguration constructs an declarative configuration of the NonResourcePolicyRule type for use with\n// apply.\nfunc NonResourcePolicyRule() *NonResourcePolicyRuleApplyConfiguration {\n\treturn \u0026NonResourcePolicyRuleApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100023265,"name":"WithVerbs","signature":"func (b *NonResourcePolicyRuleApplyConfiguration) WithVerbs(values ...string) *NonResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/nonresourcepolicyrule.go","code":"// WithVerbs adds the given value to the Verbs field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Verbs field.\nfunc (b *NonResourcePolicyRuleApplyConfiguration) WithVerbs(values ...string) *NonResourcePolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.Verbs = append(b.Verbs, values[i])\n\t}\n\treturn b\n}","line":{"from":34,"to":42}} {"id":100023266,"name":"WithNonResourceURLs","signature":"func (b *NonResourcePolicyRuleApplyConfiguration) WithNonResourceURLs(values ...string) *NonResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/nonresourcepolicyrule.go","code":"// WithNonResourceURLs adds the given value to the NonResourceURLs field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the NonResourceURLs field.\nfunc (b *NonResourcePolicyRuleApplyConfiguration) WithNonResourceURLs(values ...string) *NonResourcePolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.NonResourceURLs = append(b.NonResourceURLs, values[i])\n\t}\n\treturn b\n}","line":{"from":44,"to":52}} {"id":100023267,"name":"PolicyRulesWithSubjects","signature":"func PolicyRulesWithSubjects() *PolicyRulesWithSubjectsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/policyruleswithsubjects.go","code":"// PolicyRulesWithSubjectsApplyConfiguration constructs an declarative configuration of the PolicyRulesWithSubjects type for use with\n// apply.\nfunc PolicyRulesWithSubjects() *PolicyRulesWithSubjectsApplyConfiguration {\n\treturn \u0026PolicyRulesWithSubjectsApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100023268,"name":"WithSubjects","signature":"func (b *PolicyRulesWithSubjectsApplyConfiguration) WithSubjects(values ...*SubjectApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/policyruleswithsubjects.go","code":"// WithSubjects adds the given value to the Subjects field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Subjects field.\nfunc (b *PolicyRulesWithSubjectsApplyConfiguration) WithSubjects(values ...*SubjectApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithSubjects\")\n\t\t}\n\t\tb.Subjects = append(b.Subjects, *values[i])\n\t}\n\treturn b\n}","line":{"from":35,"to":46}} {"id":100023269,"name":"WithResourceRules","signature":"func (b *PolicyRulesWithSubjectsApplyConfiguration) WithResourceRules(values ...*ResourcePolicyRuleApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/policyruleswithsubjects.go","code":"// WithResourceRules adds the given value to the ResourceRules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ResourceRules field.\nfunc (b *PolicyRulesWithSubjectsApplyConfiguration) WithResourceRules(values ...*ResourcePolicyRuleApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithResourceRules\")\n\t\t}\n\t\tb.ResourceRules = append(b.ResourceRules, *values[i])\n\t}\n\treturn b\n}","line":{"from":48,"to":59}} {"id":100023270,"name":"WithNonResourceRules","signature":"func (b *PolicyRulesWithSubjectsApplyConfiguration) WithNonResourceRules(values ...*NonResourcePolicyRuleApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/policyruleswithsubjects.go","code":"// WithNonResourceRules adds the given value to the NonResourceRules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the NonResourceRules field.\nfunc (b *PolicyRulesWithSubjectsApplyConfiguration) WithNonResourceRules(values ...*NonResourcePolicyRuleApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithNonResourceRules\")\n\t\t}\n\t\tb.NonResourceRules = append(b.NonResourceRules, *values[i])\n\t}\n\treturn b\n}","line":{"from":61,"to":72}} {"id":100023271,"name":"PriorityLevelConfiguration","signature":"func PriorityLevelConfiguration(name string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// PriorityLevelConfiguration constructs an declarative configuration of the PriorityLevelConfiguration type for use with\n// apply.\nfunc PriorityLevelConfiguration(name string) *PriorityLevelConfigurationApplyConfiguration {\n\tb := \u0026PriorityLevelConfigurationApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"PriorityLevelConfiguration\")\n\tb.WithAPIVersion(\"flowcontrol.apiserver.k8s.io/v1beta2\")\n\treturn b\n}","line":{"from":39,"to":47}} {"id":100023272,"name":"ExtractPriorityLevelConfiguration","signature":"func ExtractPriorityLevelConfiguration(priorityLevelConfiguration *flowcontrolv1beta2.PriorityLevelConfiguration, fieldManager string) (*PriorityLevelConfigurationApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// ExtractPriorityLevelConfiguration extracts the applied configuration owned by fieldManager from\n// priorityLevelConfiguration. If no managedFields are found in priorityLevelConfiguration for fieldManager, a\n// PriorityLevelConfigurationApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// priorityLevelConfiguration must be a unmodified PriorityLevelConfiguration API object that was retrieved from the Kubernetes API.\n// ExtractPriorityLevelConfiguration provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractPriorityLevelConfiguration(priorityLevelConfiguration *flowcontrolv1beta2.PriorityLevelConfiguration, fieldManager string) (*PriorityLevelConfigurationApplyConfiguration, error) {\n\treturn extractPriorityLevelConfiguration(priorityLevelConfiguration, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100023273,"name":"ExtractPriorityLevelConfigurationStatus","signature":"func ExtractPriorityLevelConfigurationStatus(priorityLevelConfiguration *flowcontrolv1beta2.PriorityLevelConfiguration, fieldManager string) (*PriorityLevelConfigurationApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// ExtractPriorityLevelConfigurationStatus is the same as ExtractPriorityLevelConfiguration except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractPriorityLevelConfigurationStatus(priorityLevelConfiguration *flowcontrolv1beta2.PriorityLevelConfiguration, fieldManager string) (*PriorityLevelConfigurationApplyConfiguration, error) {\n\treturn extractPriorityLevelConfiguration(priorityLevelConfiguration, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100023274,"name":"extractPriorityLevelConfiguration","signature":"func extractPriorityLevelConfiguration(priorityLevelConfiguration *flowcontrolv1beta2.PriorityLevelConfiguration, fieldManager string, subresource string) (*PriorityLevelConfigurationApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"func extractPriorityLevelConfiguration(priorityLevelConfiguration *flowcontrolv1beta2.PriorityLevelConfiguration, fieldManager string, subresource string) (*PriorityLevelConfigurationApplyConfiguration, error) {\n\tb := \u0026PriorityLevelConfigurationApplyConfiguration{}\n\terr := managedfields.ExtractInto(priorityLevelConfiguration, internal.Parser().Type(\"io.k8s.api.flowcontrol.v1beta2.PriorityLevelConfiguration\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(priorityLevelConfiguration.Name)\n\n\tb.WithKind(\"PriorityLevelConfiguration\")\n\tb.WithAPIVersion(\"flowcontrol.apiserver.k8s.io/v1beta2\")\n\treturn b, nil\n}","line":{"from":71,"to":82}} {"id":100023275,"name":"WithKind","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithKind(value string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithKind(value string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100023276,"name":"WithAPIVersion","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithAPIVersion(value string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithAPIVersion(value string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100023277,"name":"WithName","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithName(value string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithName(value string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":100,"to":107}} {"id":100023278,"name":"WithGenerateName","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithGenerateName(value string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithGenerateName(value string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":109,"to":116}} {"id":100023279,"name":"WithNamespace","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithNamespace(value string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithNamespace(value string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":118,"to":125}} {"id":100023280,"name":"WithUID","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithUID(value types.UID) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithUID(value types.UID) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":127,"to":134}} {"id":100023281,"name":"WithResourceVersion","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithResourceVersion(value string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithResourceVersion(value string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":136,"to":143}} {"id":100023282,"name":"WithGeneration","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithGeneration(value int64) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithGeneration(value int64) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":145,"to":152}} {"id":100023283,"name":"WithCreationTimestamp","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":154,"to":161}} {"id":100023284,"name":"WithDeletionTimestamp","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":163,"to":170}} {"id":100023285,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":172,"to":179}} {"id":100023286,"name":"WithLabels","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithLabels(entries map[string]string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithLabels(entries map[string]string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":181,"to":194}} {"id":100023287,"name":"WithAnnotations","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithAnnotations(entries map[string]string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithAnnotations(entries map[string]string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100023288,"name":"WithOwnerReferences","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":211,"to":223}} {"id":100023289,"name":"WithFinalizers","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithFinalizers(values ...string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithFinalizers(values ...string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":225,"to":234}} {"id":100023290,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"func (b *PriorityLevelConfigurationApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":236,"to":240}} {"id":100023291,"name":"WithSpec","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithSpec(value *PriorityLevelConfigurationSpecApplyConfiguration) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithSpec(value *PriorityLevelConfigurationSpecApplyConfiguration) *PriorityLevelConfigurationApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":242,"to":248}} {"id":100023292,"name":"WithStatus","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithStatus(value *PriorityLevelConfigurationStatusApplyConfiguration) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithStatus(value *PriorityLevelConfigurationStatusApplyConfiguration) *PriorityLevelConfigurationApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":250,"to":256}} {"id":100023293,"name":"PriorityLevelConfigurationCondition","signature":"func PriorityLevelConfigurationCondition() *PriorityLevelConfigurationConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfigurationcondition.go","code":"// PriorityLevelConfigurationConditionApplyConfiguration constructs an declarative configuration of the PriorityLevelConfigurationCondition type for use with\n// apply.\nfunc PriorityLevelConfigurationCondition() *PriorityLevelConfigurationConditionApplyConfiguration {\n\treturn \u0026PriorityLevelConfigurationConditionApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100023294,"name":"WithType","signature":"func (b *PriorityLevelConfigurationConditionApplyConfiguration) WithType(value v1beta2.PriorityLevelConfigurationConditionType) *PriorityLevelConfigurationConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfigurationcondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationConditionApplyConfiguration) WithType(value v1beta2.PriorityLevelConfigurationConditionType) *PriorityLevelConfigurationConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100023295,"name":"WithStatus","signature":"func (b *PriorityLevelConfigurationConditionApplyConfiguration) WithStatus(value v1beta2.ConditionStatus) *PriorityLevelConfigurationConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfigurationcondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationConditionApplyConfiguration) WithStatus(value v1beta2.ConditionStatus) *PriorityLevelConfigurationConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100023296,"name":"WithLastTransitionTime","signature":"func (b *PriorityLevelConfigurationConditionApplyConfiguration) WithLastTransitionTime(value v1.Time) *PriorityLevelConfigurationConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfigurationcondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationConditionApplyConfiguration) WithLastTransitionTime(value v1.Time) *PriorityLevelConfigurationConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100023297,"name":"WithReason","signature":"func (b *PriorityLevelConfigurationConditionApplyConfiguration) WithReason(value string) *PriorityLevelConfigurationConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfigurationcondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationConditionApplyConfiguration) WithReason(value string) *PriorityLevelConfigurationConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100023298,"name":"WithMessage","signature":"func (b *PriorityLevelConfigurationConditionApplyConfiguration) WithMessage(value string) *PriorityLevelConfigurationConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfigurationcondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationConditionApplyConfiguration) WithMessage(value string) *PriorityLevelConfigurationConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100023299,"name":"PriorityLevelConfigurationReference","signature":"func PriorityLevelConfigurationReference() *PriorityLevelConfigurationReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfigurationreference.go","code":"// PriorityLevelConfigurationReferenceApplyConfiguration constructs an declarative configuration of the PriorityLevelConfigurationReference type for use with\n// apply.\nfunc PriorityLevelConfigurationReference() *PriorityLevelConfigurationReferenceApplyConfiguration {\n\treturn \u0026PriorityLevelConfigurationReferenceApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023300,"name":"WithName","signature":"func (b *PriorityLevelConfigurationReferenceApplyConfiguration) WithName(value string) *PriorityLevelConfigurationReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfigurationreference.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationReferenceApplyConfiguration) WithName(value string) *PriorityLevelConfigurationReferenceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100023301,"name":"PriorityLevelConfigurationSpec","signature":"func PriorityLevelConfigurationSpec() *PriorityLevelConfigurationSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfigurationspec.go","code":"// PriorityLevelConfigurationSpecApplyConfiguration constructs an declarative configuration of the PriorityLevelConfigurationSpec type for use with\n// apply.\nfunc PriorityLevelConfigurationSpec() *PriorityLevelConfigurationSpecApplyConfiguration {\n\treturn \u0026PriorityLevelConfigurationSpecApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100023302,"name":"WithType","signature":"func (b *PriorityLevelConfigurationSpecApplyConfiguration) WithType(value v1beta2.PriorityLevelEnablement) *PriorityLevelConfigurationSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfigurationspec.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationSpecApplyConfiguration) WithType(value v1beta2.PriorityLevelEnablement) *PriorityLevelConfigurationSpecApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100023303,"name":"WithLimited","signature":"func (b *PriorityLevelConfigurationSpecApplyConfiguration) WithLimited(value *LimitedPriorityLevelConfigurationApplyConfiguration) *PriorityLevelConfigurationSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfigurationspec.go","code":"// WithLimited sets the Limited field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Limited field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationSpecApplyConfiguration) WithLimited(value *LimitedPriorityLevelConfigurationApplyConfiguration) *PriorityLevelConfigurationSpecApplyConfiguration {\n\tb.Limited = value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100023304,"name":"PriorityLevelConfigurationStatus","signature":"func PriorityLevelConfigurationStatus() *PriorityLevelConfigurationStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfigurationstatus.go","code":"// PriorityLevelConfigurationStatusApplyConfiguration constructs an declarative configuration of the PriorityLevelConfigurationStatus type for use with\n// apply.\nfunc PriorityLevelConfigurationStatus() *PriorityLevelConfigurationStatusApplyConfiguration {\n\treturn \u0026PriorityLevelConfigurationStatusApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023305,"name":"WithConditions","signature":"func (b *PriorityLevelConfigurationStatusApplyConfiguration) WithConditions(values ...*PriorityLevelConfigurationConditionApplyConfiguration) *PriorityLevelConfigurationStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/prioritylevelconfigurationstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *PriorityLevelConfigurationStatusApplyConfiguration) WithConditions(values ...*PriorityLevelConfigurationConditionApplyConfiguration) *PriorityLevelConfigurationStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100023306,"name":"QueuingConfiguration","signature":"func QueuingConfiguration() *QueuingConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/queuingconfiguration.go","code":"// QueuingConfigurationApplyConfiguration constructs an declarative configuration of the QueuingConfiguration type for use with\n// apply.\nfunc QueuingConfiguration() *QueuingConfigurationApplyConfiguration {\n\treturn \u0026QueuingConfigurationApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100023307,"name":"WithQueues","signature":"func (b *QueuingConfigurationApplyConfiguration) WithQueues(value int32) *QueuingConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/queuingconfiguration.go","code":"// WithQueues sets the Queues field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Queues field is set to the value of the last call.\nfunc (b *QueuingConfigurationApplyConfiguration) WithQueues(value int32) *QueuingConfigurationApplyConfiguration {\n\tb.Queues = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100023308,"name":"WithHandSize","signature":"func (b *QueuingConfigurationApplyConfiguration) WithHandSize(value int32) *QueuingConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/queuingconfiguration.go","code":"// WithHandSize sets the HandSize field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HandSize field is set to the value of the last call.\nfunc (b *QueuingConfigurationApplyConfiguration) WithHandSize(value int32) *QueuingConfigurationApplyConfiguration {\n\tb.HandSize = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100023309,"name":"WithQueueLengthLimit","signature":"func (b *QueuingConfigurationApplyConfiguration) WithQueueLengthLimit(value int32) *QueuingConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/queuingconfiguration.go","code":"// WithQueueLengthLimit sets the QueueLengthLimit field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the QueueLengthLimit field is set to the value of the last call.\nfunc (b *QueuingConfigurationApplyConfiguration) WithQueueLengthLimit(value int32) *QueuingConfigurationApplyConfiguration {\n\tb.QueueLengthLimit = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100023310,"name":"ResourcePolicyRule","signature":"func ResourcePolicyRule() *ResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/resourcepolicyrule.go","code":"// ResourcePolicyRuleApplyConfiguration constructs an declarative configuration of the ResourcePolicyRule type for use with\n// apply.\nfunc ResourcePolicyRule() *ResourcePolicyRuleApplyConfiguration {\n\treturn \u0026ResourcePolicyRuleApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100023311,"name":"WithVerbs","signature":"func (b *ResourcePolicyRuleApplyConfiguration) WithVerbs(values ...string) *ResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/resourcepolicyrule.go","code":"// WithVerbs adds the given value to the Verbs field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Verbs field.\nfunc (b *ResourcePolicyRuleApplyConfiguration) WithVerbs(values ...string) *ResourcePolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.Verbs = append(b.Verbs, values[i])\n\t}\n\treturn b\n}","line":{"from":37,"to":45}} {"id":100023312,"name":"WithAPIGroups","signature":"func (b *ResourcePolicyRuleApplyConfiguration) WithAPIGroups(values ...string) *ResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/resourcepolicyrule.go","code":"// WithAPIGroups adds the given value to the APIGroups field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the APIGroups field.\nfunc (b *ResourcePolicyRuleApplyConfiguration) WithAPIGroups(values ...string) *ResourcePolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.APIGroups = append(b.APIGroups, values[i])\n\t}\n\treturn b\n}","line":{"from":47,"to":55}} {"id":100023313,"name":"WithResources","signature":"func (b *ResourcePolicyRuleApplyConfiguration) WithResources(values ...string) *ResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/resourcepolicyrule.go","code":"// WithResources adds the given value to the Resources field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Resources field.\nfunc (b *ResourcePolicyRuleApplyConfiguration) WithResources(values ...string) *ResourcePolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.Resources = append(b.Resources, values[i])\n\t}\n\treturn b\n}","line":{"from":57,"to":65}} {"id":100023314,"name":"WithClusterScope","signature":"func (b *ResourcePolicyRuleApplyConfiguration) WithClusterScope(value bool) *ResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/resourcepolicyrule.go","code":"// WithClusterScope sets the ClusterScope field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ClusterScope field is set to the value of the last call.\nfunc (b *ResourcePolicyRuleApplyConfiguration) WithClusterScope(value bool) *ResourcePolicyRuleApplyConfiguration {\n\tb.ClusterScope = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100023315,"name":"WithNamespaces","signature":"func (b *ResourcePolicyRuleApplyConfiguration) WithNamespaces(values ...string) *ResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/resourcepolicyrule.go","code":"// WithNamespaces adds the given value to the Namespaces field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Namespaces field.\nfunc (b *ResourcePolicyRuleApplyConfiguration) WithNamespaces(values ...string) *ResourcePolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.Namespaces = append(b.Namespaces, values[i])\n\t}\n\treturn b\n}","line":{"from":75,"to":83}} {"id":100023316,"name":"ServiceAccountSubject","signature":"func ServiceAccountSubject() *ServiceAccountSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/serviceaccountsubject.go","code":"// ServiceAccountSubjectApplyConfiguration constructs an declarative configuration of the ServiceAccountSubject type for use with\n// apply.\nfunc ServiceAccountSubject() *ServiceAccountSubjectApplyConfiguration {\n\treturn \u0026ServiceAccountSubjectApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100023317,"name":"WithNamespace","signature":"func (b *ServiceAccountSubjectApplyConfiguration) WithNamespace(value string) *ServiceAccountSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/serviceaccountsubject.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ServiceAccountSubjectApplyConfiguration) WithNamespace(value string) *ServiceAccountSubjectApplyConfiguration {\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100023318,"name":"WithName","signature":"func (b *ServiceAccountSubjectApplyConfiguration) WithName(value string) *ServiceAccountSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/serviceaccountsubject.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ServiceAccountSubjectApplyConfiguration) WithName(value string) *ServiceAccountSubjectApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100023319,"name":"Subject","signature":"func Subject() *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/subject.go","code":"// SubjectApplyConfiguration constructs an declarative configuration of the Subject type for use with\n// apply.\nfunc Subject() *SubjectApplyConfiguration {\n\treturn \u0026SubjectApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100023320,"name":"WithKind","signature":"func (b *SubjectApplyConfiguration) WithKind(value v1beta2.SubjectKind) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/subject.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithKind(value v1beta2.SubjectKind) *SubjectApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":40,"to":46}} {"id":100023321,"name":"WithUser","signature":"func (b *SubjectApplyConfiguration) WithUser(value *UserSubjectApplyConfiguration) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/subject.go","code":"// WithUser sets the User field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the User field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithUser(value *UserSubjectApplyConfiguration) *SubjectApplyConfiguration {\n\tb.User = value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100023322,"name":"WithGroup","signature":"func (b *SubjectApplyConfiguration) WithGroup(value *GroupSubjectApplyConfiguration) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/subject.go","code":"// WithGroup sets the Group field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Group field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithGroup(value *GroupSubjectApplyConfiguration) *SubjectApplyConfiguration {\n\tb.Group = value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100023323,"name":"WithServiceAccount","signature":"func (b *SubjectApplyConfiguration) WithServiceAccount(value *ServiceAccountSubjectApplyConfiguration) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/subject.go","code":"// WithServiceAccount sets the ServiceAccount field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ServiceAccount field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithServiceAccount(value *ServiceAccountSubjectApplyConfiguration) *SubjectApplyConfiguration {\n\tb.ServiceAccount = value\n\treturn b\n}","line":{"from":64,"to":70}} {"id":100023324,"name":"UserSubject","signature":"func UserSubject() *UserSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/usersubject.go","code":"// UserSubjectApplyConfiguration constructs an declarative configuration of the UserSubject type for use with\n// apply.\nfunc UserSubject() *UserSubjectApplyConfiguration {\n\treturn \u0026UserSubjectApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023325,"name":"WithName","signature":"func (b *UserSubjectApplyConfiguration) WithName(value string) *UserSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2/usersubject.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *UserSubjectApplyConfiguration) WithName(value string) *UserSubjectApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100023326,"name":"FlowDistinguisherMethod","signature":"func FlowDistinguisherMethod() *FlowDistinguisherMethodApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowdistinguishermethod.go","code":"// FlowDistinguisherMethodApplyConfiguration constructs an declarative configuration of the FlowDistinguisherMethod type for use with\n// apply.\nfunc FlowDistinguisherMethod() *FlowDistinguisherMethodApplyConfiguration {\n\treturn \u0026FlowDistinguisherMethodApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100023327,"name":"WithType","signature":"func (b *FlowDistinguisherMethodApplyConfiguration) WithType(value v1beta3.FlowDistinguisherMethodType) *FlowDistinguisherMethodApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowdistinguishermethod.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *FlowDistinguisherMethodApplyConfiguration) WithType(value v1beta3.FlowDistinguisherMethodType) *FlowDistinguisherMethodApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":37,"to":43}} {"id":100023328,"name":"FlowSchema","signature":"func FlowSchema(name string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschema.go","code":"// FlowSchema constructs an declarative configuration of the FlowSchema type for use with\n// apply.\nfunc FlowSchema(name string) *FlowSchemaApplyConfiguration {\n\tb := \u0026FlowSchemaApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"FlowSchema\")\n\tb.WithAPIVersion(\"flowcontrol.apiserver.k8s.io/v1beta3\")\n\treturn b\n}","line":{"from":39,"to":47}} {"id":100023329,"name":"ExtractFlowSchema","signature":"func ExtractFlowSchema(flowSchema *flowcontrolv1beta3.FlowSchema, fieldManager string) (*FlowSchemaApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschema.go","code":"// ExtractFlowSchema extracts the applied configuration owned by fieldManager from\n// flowSchema. If no managedFields are found in flowSchema for fieldManager, a\n// FlowSchemaApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// flowSchema must be a unmodified FlowSchema API object that was retrieved from the Kubernetes API.\n// ExtractFlowSchema provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractFlowSchema(flowSchema *flowcontrolv1beta3.FlowSchema, fieldManager string) (*FlowSchemaApplyConfiguration, error) {\n\treturn extractFlowSchema(flowSchema, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100023330,"name":"ExtractFlowSchemaStatus","signature":"func ExtractFlowSchemaStatus(flowSchema *flowcontrolv1beta3.FlowSchema, fieldManager string) (*FlowSchemaApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschema.go","code":"// ExtractFlowSchemaStatus is the same as ExtractFlowSchema except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractFlowSchemaStatus(flowSchema *flowcontrolv1beta3.FlowSchema, fieldManager string) (*FlowSchemaApplyConfiguration, error) {\n\treturn extractFlowSchema(flowSchema, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100023331,"name":"extractFlowSchema","signature":"func extractFlowSchema(flowSchema *flowcontrolv1beta3.FlowSchema, fieldManager string, subresource string) (*FlowSchemaApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschema.go","code":"func extractFlowSchema(flowSchema *flowcontrolv1beta3.FlowSchema, fieldManager string, subresource string) (*FlowSchemaApplyConfiguration, error) {\n\tb := \u0026FlowSchemaApplyConfiguration{}\n\terr := managedfields.ExtractInto(flowSchema, internal.Parser().Type(\"io.k8s.api.flowcontrol.v1beta3.FlowSchema\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(flowSchema.Name)\n\n\tb.WithKind(\"FlowSchema\")\n\tb.WithAPIVersion(\"flowcontrol.apiserver.k8s.io/v1beta3\")\n\treturn b, nil\n}","line":{"from":71,"to":82}} {"id":100023332,"name":"WithKind","signature":"func (b *FlowSchemaApplyConfiguration) WithKind(value string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschema.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithKind(value string) *FlowSchemaApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100023333,"name":"WithAPIVersion","signature":"func (b *FlowSchemaApplyConfiguration) WithAPIVersion(value string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschema.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithAPIVersion(value string) *FlowSchemaApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100023334,"name":"WithName","signature":"func (b *FlowSchemaApplyConfiguration) WithName(value string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschema.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithName(value string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":100,"to":107}} {"id":100023335,"name":"WithGenerateName","signature":"func (b *FlowSchemaApplyConfiguration) WithGenerateName(value string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschema.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithGenerateName(value string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":109,"to":116}} {"id":100023336,"name":"WithNamespace","signature":"func (b *FlowSchemaApplyConfiguration) WithNamespace(value string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschema.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithNamespace(value string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":118,"to":125}} {"id":100023337,"name":"WithUID","signature":"func (b *FlowSchemaApplyConfiguration) WithUID(value types.UID) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschema.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithUID(value types.UID) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":127,"to":134}} {"id":100023338,"name":"WithResourceVersion","signature":"func (b *FlowSchemaApplyConfiguration) WithResourceVersion(value string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschema.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithResourceVersion(value string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":136,"to":143}} {"id":100023339,"name":"WithGeneration","signature":"func (b *FlowSchemaApplyConfiguration) WithGeneration(value int64) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschema.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithGeneration(value int64) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":145,"to":152}} {"id":100023340,"name":"WithCreationTimestamp","signature":"func (b *FlowSchemaApplyConfiguration) WithCreationTimestamp(value metav1.Time) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschema.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithCreationTimestamp(value metav1.Time) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":154,"to":161}} {"id":100023341,"name":"WithDeletionTimestamp","signature":"func (b *FlowSchemaApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschema.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":163,"to":170}} {"id":100023342,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *FlowSchemaApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschema.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":172,"to":179}} {"id":100023343,"name":"WithLabels","signature":"func (b *FlowSchemaApplyConfiguration) WithLabels(entries map[string]string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschema.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *FlowSchemaApplyConfiguration) WithLabels(entries map[string]string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":181,"to":194}} {"id":100023344,"name":"WithAnnotations","signature":"func (b *FlowSchemaApplyConfiguration) WithAnnotations(entries map[string]string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschema.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *FlowSchemaApplyConfiguration) WithAnnotations(entries map[string]string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100023345,"name":"WithOwnerReferences","signature":"func (b *FlowSchemaApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschema.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *FlowSchemaApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":211,"to":223}} {"id":100023346,"name":"WithFinalizers","signature":"func (b *FlowSchemaApplyConfiguration) WithFinalizers(values ...string) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschema.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *FlowSchemaApplyConfiguration) WithFinalizers(values ...string) *FlowSchemaApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":225,"to":234}} {"id":100023347,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *FlowSchemaApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschema.go","code":"func (b *FlowSchemaApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":236,"to":240}} {"id":100023348,"name":"WithSpec","signature":"func (b *FlowSchemaApplyConfiguration) WithSpec(value *FlowSchemaSpecApplyConfiguration) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschema.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithSpec(value *FlowSchemaSpecApplyConfiguration) *FlowSchemaApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":242,"to":248}} {"id":100023349,"name":"WithStatus","signature":"func (b *FlowSchemaApplyConfiguration) WithStatus(value *FlowSchemaStatusApplyConfiguration) *FlowSchemaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschema.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *FlowSchemaApplyConfiguration) WithStatus(value *FlowSchemaStatusApplyConfiguration) *FlowSchemaApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":250,"to":256}} {"id":100023350,"name":"FlowSchemaCondition","signature":"func FlowSchemaCondition() *FlowSchemaConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschemacondition.go","code":"// FlowSchemaConditionApplyConfiguration constructs an declarative configuration of the FlowSchemaCondition type for use with\n// apply.\nfunc FlowSchemaCondition() *FlowSchemaConditionApplyConfiguration {\n\treturn \u0026FlowSchemaConditionApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100023351,"name":"WithType","signature":"func (b *FlowSchemaConditionApplyConfiguration) WithType(value v1beta3.FlowSchemaConditionType) *FlowSchemaConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschemacondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *FlowSchemaConditionApplyConfiguration) WithType(value v1beta3.FlowSchemaConditionType) *FlowSchemaConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100023352,"name":"WithStatus","signature":"func (b *FlowSchemaConditionApplyConfiguration) WithStatus(value v1beta3.ConditionStatus) *FlowSchemaConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschemacondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *FlowSchemaConditionApplyConfiguration) WithStatus(value v1beta3.ConditionStatus) *FlowSchemaConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100023353,"name":"WithLastTransitionTime","signature":"func (b *FlowSchemaConditionApplyConfiguration) WithLastTransitionTime(value v1.Time) *FlowSchemaConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschemacondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *FlowSchemaConditionApplyConfiguration) WithLastTransitionTime(value v1.Time) *FlowSchemaConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100023354,"name":"WithReason","signature":"func (b *FlowSchemaConditionApplyConfiguration) WithReason(value string) *FlowSchemaConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschemacondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *FlowSchemaConditionApplyConfiguration) WithReason(value string) *FlowSchemaConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100023355,"name":"WithMessage","signature":"func (b *FlowSchemaConditionApplyConfiguration) WithMessage(value string) *FlowSchemaConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschemacondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *FlowSchemaConditionApplyConfiguration) WithMessage(value string) *FlowSchemaConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100023356,"name":"FlowSchemaSpec","signature":"func FlowSchemaSpec() *FlowSchemaSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschemaspec.go","code":"// FlowSchemaSpecApplyConfiguration constructs an declarative configuration of the FlowSchemaSpec type for use with\n// apply.\nfunc FlowSchemaSpec() *FlowSchemaSpecApplyConfiguration {\n\treturn \u0026FlowSchemaSpecApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100023357,"name":"WithPriorityLevelConfiguration","signature":"func (b *FlowSchemaSpecApplyConfiguration) WithPriorityLevelConfiguration(value *PriorityLevelConfigurationReferenceApplyConfiguration) *FlowSchemaSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschemaspec.go","code":"// WithPriorityLevelConfiguration sets the PriorityLevelConfiguration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PriorityLevelConfiguration field is set to the value of the last call.\nfunc (b *FlowSchemaSpecApplyConfiguration) WithPriorityLevelConfiguration(value *PriorityLevelConfigurationReferenceApplyConfiguration) *FlowSchemaSpecApplyConfiguration {\n\tb.PriorityLevelConfiguration = value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100023358,"name":"WithMatchingPrecedence","signature":"func (b *FlowSchemaSpecApplyConfiguration) WithMatchingPrecedence(value int32) *FlowSchemaSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschemaspec.go","code":"// WithMatchingPrecedence sets the MatchingPrecedence field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MatchingPrecedence field is set to the value of the last call.\nfunc (b *FlowSchemaSpecApplyConfiguration) WithMatchingPrecedence(value int32) *FlowSchemaSpecApplyConfiguration {\n\tb.MatchingPrecedence = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100023359,"name":"WithDistinguisherMethod","signature":"func (b *FlowSchemaSpecApplyConfiguration) WithDistinguisherMethod(value *FlowDistinguisherMethodApplyConfiguration) *FlowSchemaSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschemaspec.go","code":"// WithDistinguisherMethod sets the DistinguisherMethod field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DistinguisherMethod field is set to the value of the last call.\nfunc (b *FlowSchemaSpecApplyConfiguration) WithDistinguisherMethod(value *FlowDistinguisherMethodApplyConfiguration) *FlowSchemaSpecApplyConfiguration {\n\tb.DistinguisherMethod = value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100023360,"name":"WithRules","signature":"func (b *FlowSchemaSpecApplyConfiguration) WithRules(values ...*PolicyRulesWithSubjectsApplyConfiguration) *FlowSchemaSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschemaspec.go","code":"// WithRules adds the given value to the Rules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Rules field.\nfunc (b *FlowSchemaSpecApplyConfiguration) WithRules(values ...*PolicyRulesWithSubjectsApplyConfiguration) *FlowSchemaSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRules\")\n\t\t}\n\t\tb.Rules = append(b.Rules, *values[i])\n\t}\n\treturn b\n}","line":{"from":60,"to":71}} {"id":100023361,"name":"FlowSchemaStatus","signature":"func FlowSchemaStatus() *FlowSchemaStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschemastatus.go","code":"// FlowSchemaStatusApplyConfiguration constructs an declarative configuration of the FlowSchemaStatus type for use with\n// apply.\nfunc FlowSchemaStatus() *FlowSchemaStatusApplyConfiguration {\n\treturn \u0026FlowSchemaStatusApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023362,"name":"WithConditions","signature":"func (b *FlowSchemaStatusApplyConfiguration) WithConditions(values ...*FlowSchemaConditionApplyConfiguration) *FlowSchemaStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/flowschemastatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *FlowSchemaStatusApplyConfiguration) WithConditions(values ...*FlowSchemaConditionApplyConfiguration) *FlowSchemaStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100023363,"name":"GroupSubject","signature":"func GroupSubject() *GroupSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/groupsubject.go","code":"// GroupSubjectApplyConfiguration constructs an declarative configuration of the GroupSubject type for use with\n// apply.\nfunc GroupSubject() *GroupSubjectApplyConfiguration {\n\treturn \u0026GroupSubjectApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023364,"name":"WithName","signature":"func (b *GroupSubjectApplyConfiguration) WithName(value string) *GroupSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/groupsubject.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *GroupSubjectApplyConfiguration) WithName(value string) *GroupSubjectApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100023365,"name":"LimitedPriorityLevelConfiguration","signature":"func LimitedPriorityLevelConfiguration() *LimitedPriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/limitedprioritylevelconfiguration.go","code":"// LimitedPriorityLevelConfigurationApplyConfiguration constructs an declarative configuration of the LimitedPriorityLevelConfiguration type for use with\n// apply.\nfunc LimitedPriorityLevelConfiguration() *LimitedPriorityLevelConfigurationApplyConfiguration {\n\treturn \u0026LimitedPriorityLevelConfigurationApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100023366,"name":"WithNominalConcurrencyShares","signature":"func (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithNominalConcurrencyShares(value int32) *LimitedPriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/limitedprioritylevelconfiguration.go","code":"// WithNominalConcurrencyShares sets the NominalConcurrencyShares field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NominalConcurrencyShares field is set to the value of the last call.\nfunc (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithNominalConcurrencyShares(value int32) *LimitedPriorityLevelConfigurationApplyConfiguration {\n\tb.NominalConcurrencyShares = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100023367,"name":"WithLimitResponse","signature":"func (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithLimitResponse(value *LimitResponseApplyConfiguration) *LimitedPriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/limitedprioritylevelconfiguration.go","code":"// WithLimitResponse sets the LimitResponse field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LimitResponse field is set to the value of the last call.\nfunc (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithLimitResponse(value *LimitResponseApplyConfiguration) *LimitedPriorityLevelConfigurationApplyConfiguration {\n\tb.LimitResponse = value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100023368,"name":"WithLendablePercent","signature":"func (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithLendablePercent(value int32) *LimitedPriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/limitedprioritylevelconfiguration.go","code":"// WithLendablePercent sets the LendablePercent field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LendablePercent field is set to the value of the last call.\nfunc (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithLendablePercent(value int32) *LimitedPriorityLevelConfigurationApplyConfiguration {\n\tb.LendablePercent = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100023369,"name":"WithBorrowingLimitPercent","signature":"func (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithBorrowingLimitPercent(value int32) *LimitedPriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/limitedprioritylevelconfiguration.go","code":"// WithBorrowingLimitPercent sets the BorrowingLimitPercent field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the BorrowingLimitPercent field is set to the value of the last call.\nfunc (b *LimitedPriorityLevelConfigurationApplyConfiguration) WithBorrowingLimitPercent(value int32) *LimitedPriorityLevelConfigurationApplyConfiguration {\n\tb.BorrowingLimitPercent = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100023370,"name":"LimitResponse","signature":"func LimitResponse() *LimitResponseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/limitresponse.go","code":"// LimitResponseApplyConfiguration constructs an declarative configuration of the LimitResponse type for use with\n// apply.\nfunc LimitResponse() *LimitResponseApplyConfiguration {\n\treturn \u0026LimitResponseApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100023371,"name":"WithType","signature":"func (b *LimitResponseApplyConfiguration) WithType(value v1beta3.LimitResponseType) *LimitResponseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/limitresponse.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *LimitResponseApplyConfiguration) WithType(value v1beta3.LimitResponseType) *LimitResponseApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100023372,"name":"WithQueuing","signature":"func (b *LimitResponseApplyConfiguration) WithQueuing(value *QueuingConfigurationApplyConfiguration) *LimitResponseApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/limitresponse.go","code":"// WithQueuing sets the Queuing field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Queuing field is set to the value of the last call.\nfunc (b *LimitResponseApplyConfiguration) WithQueuing(value *QueuingConfigurationApplyConfiguration) *LimitResponseApplyConfiguration {\n\tb.Queuing = value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100023373,"name":"NonResourcePolicyRule","signature":"func NonResourcePolicyRule() *NonResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/nonresourcepolicyrule.go","code":"// NonResourcePolicyRuleApplyConfiguration constructs an declarative configuration of the NonResourcePolicyRule type for use with\n// apply.\nfunc NonResourcePolicyRule() *NonResourcePolicyRuleApplyConfiguration {\n\treturn \u0026NonResourcePolicyRuleApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100023374,"name":"WithVerbs","signature":"func (b *NonResourcePolicyRuleApplyConfiguration) WithVerbs(values ...string) *NonResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/nonresourcepolicyrule.go","code":"// WithVerbs adds the given value to the Verbs field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Verbs field.\nfunc (b *NonResourcePolicyRuleApplyConfiguration) WithVerbs(values ...string) *NonResourcePolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.Verbs = append(b.Verbs, values[i])\n\t}\n\treturn b\n}","line":{"from":34,"to":42}} {"id":100023375,"name":"WithNonResourceURLs","signature":"func (b *NonResourcePolicyRuleApplyConfiguration) WithNonResourceURLs(values ...string) *NonResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/nonresourcepolicyrule.go","code":"// WithNonResourceURLs adds the given value to the NonResourceURLs field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the NonResourceURLs field.\nfunc (b *NonResourcePolicyRuleApplyConfiguration) WithNonResourceURLs(values ...string) *NonResourcePolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.NonResourceURLs = append(b.NonResourceURLs, values[i])\n\t}\n\treturn b\n}","line":{"from":44,"to":52}} {"id":100023376,"name":"PolicyRulesWithSubjects","signature":"func PolicyRulesWithSubjects() *PolicyRulesWithSubjectsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/policyruleswithsubjects.go","code":"// PolicyRulesWithSubjectsApplyConfiguration constructs an declarative configuration of the PolicyRulesWithSubjects type for use with\n// apply.\nfunc PolicyRulesWithSubjects() *PolicyRulesWithSubjectsApplyConfiguration {\n\treturn \u0026PolicyRulesWithSubjectsApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100023377,"name":"WithSubjects","signature":"func (b *PolicyRulesWithSubjectsApplyConfiguration) WithSubjects(values ...*SubjectApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/policyruleswithsubjects.go","code":"// WithSubjects adds the given value to the Subjects field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Subjects field.\nfunc (b *PolicyRulesWithSubjectsApplyConfiguration) WithSubjects(values ...*SubjectApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithSubjects\")\n\t\t}\n\t\tb.Subjects = append(b.Subjects, *values[i])\n\t}\n\treturn b\n}","line":{"from":35,"to":46}} {"id":100023378,"name":"WithResourceRules","signature":"func (b *PolicyRulesWithSubjectsApplyConfiguration) WithResourceRules(values ...*ResourcePolicyRuleApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/policyruleswithsubjects.go","code":"// WithResourceRules adds the given value to the ResourceRules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ResourceRules field.\nfunc (b *PolicyRulesWithSubjectsApplyConfiguration) WithResourceRules(values ...*ResourcePolicyRuleApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithResourceRules\")\n\t\t}\n\t\tb.ResourceRules = append(b.ResourceRules, *values[i])\n\t}\n\treturn b\n}","line":{"from":48,"to":59}} {"id":100023379,"name":"WithNonResourceRules","signature":"func (b *PolicyRulesWithSubjectsApplyConfiguration) WithNonResourceRules(values ...*NonResourcePolicyRuleApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/policyruleswithsubjects.go","code":"// WithNonResourceRules adds the given value to the NonResourceRules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the NonResourceRules field.\nfunc (b *PolicyRulesWithSubjectsApplyConfiguration) WithNonResourceRules(values ...*NonResourcePolicyRuleApplyConfiguration) *PolicyRulesWithSubjectsApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithNonResourceRules\")\n\t\t}\n\t\tb.NonResourceRules = append(b.NonResourceRules, *values[i])\n\t}\n\treturn b\n}","line":{"from":61,"to":72}} {"id":100023380,"name":"PriorityLevelConfiguration","signature":"func PriorityLevelConfiguration(name string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// PriorityLevelConfiguration constructs an declarative configuration of the PriorityLevelConfiguration type for use with\n// apply.\nfunc PriorityLevelConfiguration(name string) *PriorityLevelConfigurationApplyConfiguration {\n\tb := \u0026PriorityLevelConfigurationApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"PriorityLevelConfiguration\")\n\tb.WithAPIVersion(\"flowcontrol.apiserver.k8s.io/v1beta3\")\n\treturn b\n}","line":{"from":39,"to":47}} {"id":100023381,"name":"ExtractPriorityLevelConfiguration","signature":"func ExtractPriorityLevelConfiguration(priorityLevelConfiguration *flowcontrolv1beta3.PriorityLevelConfiguration, fieldManager string) (*PriorityLevelConfigurationApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// ExtractPriorityLevelConfiguration extracts the applied configuration owned by fieldManager from\n// priorityLevelConfiguration. If no managedFields are found in priorityLevelConfiguration for fieldManager, a\n// PriorityLevelConfigurationApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// priorityLevelConfiguration must be a unmodified PriorityLevelConfiguration API object that was retrieved from the Kubernetes API.\n// ExtractPriorityLevelConfiguration provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractPriorityLevelConfiguration(priorityLevelConfiguration *flowcontrolv1beta3.PriorityLevelConfiguration, fieldManager string) (*PriorityLevelConfigurationApplyConfiguration, error) {\n\treturn extractPriorityLevelConfiguration(priorityLevelConfiguration, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100023382,"name":"ExtractPriorityLevelConfigurationStatus","signature":"func ExtractPriorityLevelConfigurationStatus(priorityLevelConfiguration *flowcontrolv1beta3.PriorityLevelConfiguration, fieldManager string) (*PriorityLevelConfigurationApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// ExtractPriorityLevelConfigurationStatus is the same as ExtractPriorityLevelConfiguration except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractPriorityLevelConfigurationStatus(priorityLevelConfiguration *flowcontrolv1beta3.PriorityLevelConfiguration, fieldManager string) (*PriorityLevelConfigurationApplyConfiguration, error) {\n\treturn extractPriorityLevelConfiguration(priorityLevelConfiguration, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100023383,"name":"extractPriorityLevelConfiguration","signature":"func extractPriorityLevelConfiguration(priorityLevelConfiguration *flowcontrolv1beta3.PriorityLevelConfiguration, fieldManager string, subresource string) (*PriorityLevelConfigurationApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"func extractPriorityLevelConfiguration(priorityLevelConfiguration *flowcontrolv1beta3.PriorityLevelConfiguration, fieldManager string, subresource string) (*PriorityLevelConfigurationApplyConfiguration, error) {\n\tb := \u0026PriorityLevelConfigurationApplyConfiguration{}\n\terr := managedfields.ExtractInto(priorityLevelConfiguration, internal.Parser().Type(\"io.k8s.api.flowcontrol.v1beta3.PriorityLevelConfiguration\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(priorityLevelConfiguration.Name)\n\n\tb.WithKind(\"PriorityLevelConfiguration\")\n\tb.WithAPIVersion(\"flowcontrol.apiserver.k8s.io/v1beta3\")\n\treturn b, nil\n}","line":{"from":71,"to":82}} {"id":100023384,"name":"WithKind","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithKind(value string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithKind(value string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100023385,"name":"WithAPIVersion","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithAPIVersion(value string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithAPIVersion(value string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100023386,"name":"WithName","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithName(value string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithName(value string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":100,"to":107}} {"id":100023387,"name":"WithGenerateName","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithGenerateName(value string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithGenerateName(value string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":109,"to":116}} {"id":100023388,"name":"WithNamespace","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithNamespace(value string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithNamespace(value string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":118,"to":125}} {"id":100023389,"name":"WithUID","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithUID(value types.UID) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithUID(value types.UID) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":127,"to":134}} {"id":100023390,"name":"WithResourceVersion","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithResourceVersion(value string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithResourceVersion(value string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":136,"to":143}} {"id":100023391,"name":"WithGeneration","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithGeneration(value int64) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithGeneration(value int64) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":145,"to":152}} {"id":100023392,"name":"WithCreationTimestamp","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":154,"to":161}} {"id":100023393,"name":"WithDeletionTimestamp","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":163,"to":170}} {"id":100023394,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":172,"to":179}} {"id":100023395,"name":"WithLabels","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithLabels(entries map[string]string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithLabels(entries map[string]string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":181,"to":194}} {"id":100023396,"name":"WithAnnotations","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithAnnotations(entries map[string]string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithAnnotations(entries map[string]string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100023397,"name":"WithOwnerReferences","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":211,"to":223}} {"id":100023398,"name":"WithFinalizers","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithFinalizers(values ...string) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithFinalizers(values ...string) *PriorityLevelConfigurationApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":225,"to":234}} {"id":100023399,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"func (b *PriorityLevelConfigurationApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":236,"to":240}} {"id":100023400,"name":"WithSpec","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithSpec(value *PriorityLevelConfigurationSpecApplyConfiguration) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithSpec(value *PriorityLevelConfigurationSpecApplyConfiguration) *PriorityLevelConfigurationApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":242,"to":248}} {"id":100023401,"name":"WithStatus","signature":"func (b *PriorityLevelConfigurationApplyConfiguration) WithStatus(value *PriorityLevelConfigurationStatusApplyConfiguration) *PriorityLevelConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationApplyConfiguration) WithStatus(value *PriorityLevelConfigurationStatusApplyConfiguration) *PriorityLevelConfigurationApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":250,"to":256}} {"id":100023402,"name":"PriorityLevelConfigurationCondition","signature":"func PriorityLevelConfigurationCondition() *PriorityLevelConfigurationConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfigurationcondition.go","code":"// PriorityLevelConfigurationConditionApplyConfiguration constructs an declarative configuration of the PriorityLevelConfigurationCondition type for use with\n// apply.\nfunc PriorityLevelConfigurationCondition() *PriorityLevelConfigurationConditionApplyConfiguration {\n\treturn \u0026PriorityLevelConfigurationConditionApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100023403,"name":"WithType","signature":"func (b *PriorityLevelConfigurationConditionApplyConfiguration) WithType(value v1beta3.PriorityLevelConfigurationConditionType) *PriorityLevelConfigurationConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfigurationcondition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationConditionApplyConfiguration) WithType(value v1beta3.PriorityLevelConfigurationConditionType) *PriorityLevelConfigurationConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100023404,"name":"WithStatus","signature":"func (b *PriorityLevelConfigurationConditionApplyConfiguration) WithStatus(value v1beta3.ConditionStatus) *PriorityLevelConfigurationConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfigurationcondition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationConditionApplyConfiguration) WithStatus(value v1beta3.ConditionStatus) *PriorityLevelConfigurationConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100023405,"name":"WithLastTransitionTime","signature":"func (b *PriorityLevelConfigurationConditionApplyConfiguration) WithLastTransitionTime(value v1.Time) *PriorityLevelConfigurationConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfigurationcondition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationConditionApplyConfiguration) WithLastTransitionTime(value v1.Time) *PriorityLevelConfigurationConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100023406,"name":"WithReason","signature":"func (b *PriorityLevelConfigurationConditionApplyConfiguration) WithReason(value string) *PriorityLevelConfigurationConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfigurationcondition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationConditionApplyConfiguration) WithReason(value string) *PriorityLevelConfigurationConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100023407,"name":"WithMessage","signature":"func (b *PriorityLevelConfigurationConditionApplyConfiguration) WithMessage(value string) *PriorityLevelConfigurationConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfigurationcondition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationConditionApplyConfiguration) WithMessage(value string) *PriorityLevelConfigurationConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100023408,"name":"PriorityLevelConfigurationReference","signature":"func PriorityLevelConfigurationReference() *PriorityLevelConfigurationReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfigurationreference.go","code":"// PriorityLevelConfigurationReferenceApplyConfiguration constructs an declarative configuration of the PriorityLevelConfigurationReference type for use with\n// apply.\nfunc PriorityLevelConfigurationReference() *PriorityLevelConfigurationReferenceApplyConfiguration {\n\treturn \u0026PriorityLevelConfigurationReferenceApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023409,"name":"WithName","signature":"func (b *PriorityLevelConfigurationReferenceApplyConfiguration) WithName(value string) *PriorityLevelConfigurationReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfigurationreference.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationReferenceApplyConfiguration) WithName(value string) *PriorityLevelConfigurationReferenceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100023410,"name":"PriorityLevelConfigurationSpec","signature":"func PriorityLevelConfigurationSpec() *PriorityLevelConfigurationSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfigurationspec.go","code":"// PriorityLevelConfigurationSpecApplyConfiguration constructs an declarative configuration of the PriorityLevelConfigurationSpec type for use with\n// apply.\nfunc PriorityLevelConfigurationSpec() *PriorityLevelConfigurationSpecApplyConfiguration {\n\treturn \u0026PriorityLevelConfigurationSpecApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100023411,"name":"WithType","signature":"func (b *PriorityLevelConfigurationSpecApplyConfiguration) WithType(value v1beta3.PriorityLevelEnablement) *PriorityLevelConfigurationSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfigurationspec.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationSpecApplyConfiguration) WithType(value v1beta3.PriorityLevelEnablement) *PriorityLevelConfigurationSpecApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100023412,"name":"WithLimited","signature":"func (b *PriorityLevelConfigurationSpecApplyConfiguration) WithLimited(value *LimitedPriorityLevelConfigurationApplyConfiguration) *PriorityLevelConfigurationSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfigurationspec.go","code":"// WithLimited sets the Limited field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Limited field is set to the value of the last call.\nfunc (b *PriorityLevelConfigurationSpecApplyConfiguration) WithLimited(value *LimitedPriorityLevelConfigurationApplyConfiguration) *PriorityLevelConfigurationSpecApplyConfiguration {\n\tb.Limited = value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100023413,"name":"PriorityLevelConfigurationStatus","signature":"func PriorityLevelConfigurationStatus() *PriorityLevelConfigurationStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfigurationstatus.go","code":"// PriorityLevelConfigurationStatusApplyConfiguration constructs an declarative configuration of the PriorityLevelConfigurationStatus type for use with\n// apply.\nfunc PriorityLevelConfigurationStatus() *PriorityLevelConfigurationStatusApplyConfiguration {\n\treturn \u0026PriorityLevelConfigurationStatusApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023414,"name":"WithConditions","signature":"func (b *PriorityLevelConfigurationStatusApplyConfiguration) WithConditions(values ...*PriorityLevelConfigurationConditionApplyConfiguration) *PriorityLevelConfigurationStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/prioritylevelconfigurationstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *PriorityLevelConfigurationStatusApplyConfiguration) WithConditions(values ...*PriorityLevelConfigurationConditionApplyConfiguration) *PriorityLevelConfigurationStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100023415,"name":"QueuingConfiguration","signature":"func QueuingConfiguration() *QueuingConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/queuingconfiguration.go","code":"// QueuingConfigurationApplyConfiguration constructs an declarative configuration of the QueuingConfiguration type for use with\n// apply.\nfunc QueuingConfiguration() *QueuingConfigurationApplyConfiguration {\n\treturn \u0026QueuingConfigurationApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100023416,"name":"WithQueues","signature":"func (b *QueuingConfigurationApplyConfiguration) WithQueues(value int32) *QueuingConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/queuingconfiguration.go","code":"// WithQueues sets the Queues field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Queues field is set to the value of the last call.\nfunc (b *QueuingConfigurationApplyConfiguration) WithQueues(value int32) *QueuingConfigurationApplyConfiguration {\n\tb.Queues = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100023417,"name":"WithHandSize","signature":"func (b *QueuingConfigurationApplyConfiguration) WithHandSize(value int32) *QueuingConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/queuingconfiguration.go","code":"// WithHandSize sets the HandSize field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HandSize field is set to the value of the last call.\nfunc (b *QueuingConfigurationApplyConfiguration) WithHandSize(value int32) *QueuingConfigurationApplyConfiguration {\n\tb.HandSize = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100023418,"name":"WithQueueLengthLimit","signature":"func (b *QueuingConfigurationApplyConfiguration) WithQueueLengthLimit(value int32) *QueuingConfigurationApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/queuingconfiguration.go","code":"// WithQueueLengthLimit sets the QueueLengthLimit field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the QueueLengthLimit field is set to the value of the last call.\nfunc (b *QueuingConfigurationApplyConfiguration) WithQueueLengthLimit(value int32) *QueuingConfigurationApplyConfiguration {\n\tb.QueueLengthLimit = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100023419,"name":"ResourcePolicyRule","signature":"func ResourcePolicyRule() *ResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/resourcepolicyrule.go","code":"// ResourcePolicyRuleApplyConfiguration constructs an declarative configuration of the ResourcePolicyRule type for use with\n// apply.\nfunc ResourcePolicyRule() *ResourcePolicyRuleApplyConfiguration {\n\treturn \u0026ResourcePolicyRuleApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100023420,"name":"WithVerbs","signature":"func (b *ResourcePolicyRuleApplyConfiguration) WithVerbs(values ...string) *ResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/resourcepolicyrule.go","code":"// WithVerbs adds the given value to the Verbs field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Verbs field.\nfunc (b *ResourcePolicyRuleApplyConfiguration) WithVerbs(values ...string) *ResourcePolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.Verbs = append(b.Verbs, values[i])\n\t}\n\treturn b\n}","line":{"from":37,"to":45}} {"id":100023421,"name":"WithAPIGroups","signature":"func (b *ResourcePolicyRuleApplyConfiguration) WithAPIGroups(values ...string) *ResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/resourcepolicyrule.go","code":"// WithAPIGroups adds the given value to the APIGroups field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the APIGroups field.\nfunc (b *ResourcePolicyRuleApplyConfiguration) WithAPIGroups(values ...string) *ResourcePolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.APIGroups = append(b.APIGroups, values[i])\n\t}\n\treturn b\n}","line":{"from":47,"to":55}} {"id":100023422,"name":"WithResources","signature":"func (b *ResourcePolicyRuleApplyConfiguration) WithResources(values ...string) *ResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/resourcepolicyrule.go","code":"// WithResources adds the given value to the Resources field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Resources field.\nfunc (b *ResourcePolicyRuleApplyConfiguration) WithResources(values ...string) *ResourcePolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.Resources = append(b.Resources, values[i])\n\t}\n\treturn b\n}","line":{"from":57,"to":65}} {"id":100023423,"name":"WithClusterScope","signature":"func (b *ResourcePolicyRuleApplyConfiguration) WithClusterScope(value bool) *ResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/resourcepolicyrule.go","code":"// WithClusterScope sets the ClusterScope field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ClusterScope field is set to the value of the last call.\nfunc (b *ResourcePolicyRuleApplyConfiguration) WithClusterScope(value bool) *ResourcePolicyRuleApplyConfiguration {\n\tb.ClusterScope = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100023424,"name":"WithNamespaces","signature":"func (b *ResourcePolicyRuleApplyConfiguration) WithNamespaces(values ...string) *ResourcePolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/resourcepolicyrule.go","code":"// WithNamespaces adds the given value to the Namespaces field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Namespaces field.\nfunc (b *ResourcePolicyRuleApplyConfiguration) WithNamespaces(values ...string) *ResourcePolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.Namespaces = append(b.Namespaces, values[i])\n\t}\n\treturn b\n}","line":{"from":75,"to":83}} {"id":100023425,"name":"ServiceAccountSubject","signature":"func ServiceAccountSubject() *ServiceAccountSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/serviceaccountsubject.go","code":"// ServiceAccountSubjectApplyConfiguration constructs an declarative configuration of the ServiceAccountSubject type for use with\n// apply.\nfunc ServiceAccountSubject() *ServiceAccountSubjectApplyConfiguration {\n\treturn \u0026ServiceAccountSubjectApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100023426,"name":"WithNamespace","signature":"func (b *ServiceAccountSubjectApplyConfiguration) WithNamespace(value string) *ServiceAccountSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/serviceaccountsubject.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ServiceAccountSubjectApplyConfiguration) WithNamespace(value string) *ServiceAccountSubjectApplyConfiguration {\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100023427,"name":"WithName","signature":"func (b *ServiceAccountSubjectApplyConfiguration) WithName(value string) *ServiceAccountSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/serviceaccountsubject.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ServiceAccountSubjectApplyConfiguration) WithName(value string) *ServiceAccountSubjectApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100023428,"name":"Subject","signature":"func Subject() *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/subject.go","code":"// SubjectApplyConfiguration constructs an declarative configuration of the Subject type for use with\n// apply.\nfunc Subject() *SubjectApplyConfiguration {\n\treturn \u0026SubjectApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100023429,"name":"WithKind","signature":"func (b *SubjectApplyConfiguration) WithKind(value v1beta3.SubjectKind) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/subject.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithKind(value v1beta3.SubjectKind) *SubjectApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":40,"to":46}} {"id":100023430,"name":"WithUser","signature":"func (b *SubjectApplyConfiguration) WithUser(value *UserSubjectApplyConfiguration) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/subject.go","code":"// WithUser sets the User field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the User field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithUser(value *UserSubjectApplyConfiguration) *SubjectApplyConfiguration {\n\tb.User = value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100023431,"name":"WithGroup","signature":"func (b *SubjectApplyConfiguration) WithGroup(value *GroupSubjectApplyConfiguration) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/subject.go","code":"// WithGroup sets the Group field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Group field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithGroup(value *GroupSubjectApplyConfiguration) *SubjectApplyConfiguration {\n\tb.Group = value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100023432,"name":"WithServiceAccount","signature":"func (b *SubjectApplyConfiguration) WithServiceAccount(value *ServiceAccountSubjectApplyConfiguration) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/subject.go","code":"// WithServiceAccount sets the ServiceAccount field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ServiceAccount field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithServiceAccount(value *ServiceAccountSubjectApplyConfiguration) *SubjectApplyConfiguration {\n\tb.ServiceAccount = value\n\treturn b\n}","line":{"from":64,"to":70}} {"id":100023433,"name":"UserSubject","signature":"func UserSubject() *UserSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/usersubject.go","code":"// UserSubjectApplyConfiguration constructs an declarative configuration of the UserSubject type for use with\n// apply.\nfunc UserSubject() *UserSubjectApplyConfiguration {\n\treturn \u0026UserSubjectApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023434,"name":"WithName","signature":"func (b *UserSubjectApplyConfiguration) WithName(value string) *UserSubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/flowcontrol/v1beta3/usersubject.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *UserSubjectApplyConfiguration) WithName(value string) *UserSubjectApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100023435,"name":"ImageReview","signature":"func ImageReview(name string) *ImageReviewApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereview.go","code":"// ImageReview constructs an declarative configuration of the ImageReview type for use with\n// apply.\nfunc ImageReview(name string) *ImageReviewApplyConfiguration {\n\tb := \u0026ImageReviewApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"ImageReview\")\n\tb.WithAPIVersion(\"imagepolicy.k8s.io/v1alpha1\")\n\treturn b\n}","line":{"from":39,"to":47}} {"id":100023436,"name":"ExtractImageReview","signature":"func ExtractImageReview(imageReview *imagepolicyv1alpha1.ImageReview, fieldManager string) (*ImageReviewApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereview.go","code":"// ExtractImageReview extracts the applied configuration owned by fieldManager from\n// imageReview. If no managedFields are found in imageReview for fieldManager, a\n// ImageReviewApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// imageReview must be a unmodified ImageReview API object that was retrieved from the Kubernetes API.\n// ExtractImageReview provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractImageReview(imageReview *imagepolicyv1alpha1.ImageReview, fieldManager string) (*ImageReviewApplyConfiguration, error) {\n\treturn extractImageReview(imageReview, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100023437,"name":"ExtractImageReviewStatus","signature":"func ExtractImageReviewStatus(imageReview *imagepolicyv1alpha1.ImageReview, fieldManager string) (*ImageReviewApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereview.go","code":"// ExtractImageReviewStatus is the same as ExtractImageReview except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractImageReviewStatus(imageReview *imagepolicyv1alpha1.ImageReview, fieldManager string) (*ImageReviewApplyConfiguration, error) {\n\treturn extractImageReview(imageReview, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100023438,"name":"extractImageReview","signature":"func extractImageReview(imageReview *imagepolicyv1alpha1.ImageReview, fieldManager string, subresource string) (*ImageReviewApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereview.go","code":"func extractImageReview(imageReview *imagepolicyv1alpha1.ImageReview, fieldManager string, subresource string) (*ImageReviewApplyConfiguration, error) {\n\tb := \u0026ImageReviewApplyConfiguration{}\n\terr := managedfields.ExtractInto(imageReview, internal.Parser().Type(\"io.k8s.api.imagepolicy.v1alpha1.ImageReview\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(imageReview.Name)\n\n\tb.WithKind(\"ImageReview\")\n\tb.WithAPIVersion(\"imagepolicy.k8s.io/v1alpha1\")\n\treturn b, nil\n}","line":{"from":71,"to":82}} {"id":100023439,"name":"WithKind","signature":"func (b *ImageReviewApplyConfiguration) WithKind(value string) *ImageReviewApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereview.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ImageReviewApplyConfiguration) WithKind(value string) *ImageReviewApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100023440,"name":"WithAPIVersion","signature":"func (b *ImageReviewApplyConfiguration) WithAPIVersion(value string) *ImageReviewApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereview.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ImageReviewApplyConfiguration) WithAPIVersion(value string) *ImageReviewApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100023441,"name":"WithName","signature":"func (b *ImageReviewApplyConfiguration) WithName(value string) *ImageReviewApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereview.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ImageReviewApplyConfiguration) WithName(value string) *ImageReviewApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":100,"to":107}} {"id":100023442,"name":"WithGenerateName","signature":"func (b *ImageReviewApplyConfiguration) WithGenerateName(value string) *ImageReviewApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereview.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ImageReviewApplyConfiguration) WithGenerateName(value string) *ImageReviewApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":109,"to":116}} {"id":100023443,"name":"WithNamespace","signature":"func (b *ImageReviewApplyConfiguration) WithNamespace(value string) *ImageReviewApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereview.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ImageReviewApplyConfiguration) WithNamespace(value string) *ImageReviewApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":118,"to":125}} {"id":100023444,"name":"WithUID","signature":"func (b *ImageReviewApplyConfiguration) WithUID(value types.UID) *ImageReviewApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereview.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ImageReviewApplyConfiguration) WithUID(value types.UID) *ImageReviewApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":127,"to":134}} {"id":100023445,"name":"WithResourceVersion","signature":"func (b *ImageReviewApplyConfiguration) WithResourceVersion(value string) *ImageReviewApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereview.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ImageReviewApplyConfiguration) WithResourceVersion(value string) *ImageReviewApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":136,"to":143}} {"id":100023446,"name":"WithGeneration","signature":"func (b *ImageReviewApplyConfiguration) WithGeneration(value int64) *ImageReviewApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereview.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ImageReviewApplyConfiguration) WithGeneration(value int64) *ImageReviewApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":145,"to":152}} {"id":100023447,"name":"WithCreationTimestamp","signature":"func (b *ImageReviewApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ImageReviewApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereview.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ImageReviewApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ImageReviewApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":154,"to":161}} {"id":100023448,"name":"WithDeletionTimestamp","signature":"func (b *ImageReviewApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ImageReviewApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereview.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ImageReviewApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ImageReviewApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":163,"to":170}} {"id":100023449,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ImageReviewApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ImageReviewApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereview.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ImageReviewApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ImageReviewApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":172,"to":179}} {"id":100023450,"name":"WithLabels","signature":"func (b *ImageReviewApplyConfiguration) WithLabels(entries map[string]string) *ImageReviewApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereview.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ImageReviewApplyConfiguration) WithLabels(entries map[string]string) *ImageReviewApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":181,"to":194}} {"id":100023451,"name":"WithAnnotations","signature":"func (b *ImageReviewApplyConfiguration) WithAnnotations(entries map[string]string) *ImageReviewApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereview.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ImageReviewApplyConfiguration) WithAnnotations(entries map[string]string) *ImageReviewApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100023452,"name":"WithOwnerReferences","signature":"func (b *ImageReviewApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ImageReviewApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereview.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ImageReviewApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ImageReviewApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":211,"to":223}} {"id":100023453,"name":"WithFinalizers","signature":"func (b *ImageReviewApplyConfiguration) WithFinalizers(values ...string) *ImageReviewApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereview.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ImageReviewApplyConfiguration) WithFinalizers(values ...string) *ImageReviewApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":225,"to":234}} {"id":100023454,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ImageReviewApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereview.go","code":"func (b *ImageReviewApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":236,"to":240}} {"id":100023455,"name":"WithSpec","signature":"func (b *ImageReviewApplyConfiguration) WithSpec(value *ImageReviewSpecApplyConfiguration) *ImageReviewApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereview.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *ImageReviewApplyConfiguration) WithSpec(value *ImageReviewSpecApplyConfiguration) *ImageReviewApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":242,"to":248}} {"id":100023456,"name":"WithStatus","signature":"func (b *ImageReviewApplyConfiguration) WithStatus(value *ImageReviewStatusApplyConfiguration) *ImageReviewApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereview.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *ImageReviewApplyConfiguration) WithStatus(value *ImageReviewStatusApplyConfiguration) *ImageReviewApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":250,"to":256}} {"id":100023457,"name":"ImageReviewContainerSpec","signature":"func ImageReviewContainerSpec() *ImageReviewContainerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereviewcontainerspec.go","code":"// ImageReviewContainerSpecApplyConfiguration constructs an declarative configuration of the ImageReviewContainerSpec type for use with\n// apply.\nfunc ImageReviewContainerSpec() *ImageReviewContainerSpecApplyConfiguration {\n\treturn \u0026ImageReviewContainerSpecApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023458,"name":"WithImage","signature":"func (b *ImageReviewContainerSpecApplyConfiguration) WithImage(value string) *ImageReviewContainerSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereviewcontainerspec.go","code":"// WithImage sets the Image field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Image field is set to the value of the last call.\nfunc (b *ImageReviewContainerSpecApplyConfiguration) WithImage(value string) *ImageReviewContainerSpecApplyConfiguration {\n\tb.Image = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100023459,"name":"ImageReviewSpec","signature":"func ImageReviewSpec() *ImageReviewSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereviewspec.go","code":"// ImageReviewSpecApplyConfiguration constructs an declarative configuration of the ImageReviewSpec type for use with\n// apply.\nfunc ImageReviewSpec() *ImageReviewSpecApplyConfiguration {\n\treturn \u0026ImageReviewSpecApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100023460,"name":"WithContainers","signature":"func (b *ImageReviewSpecApplyConfiguration) WithContainers(values ...*ImageReviewContainerSpecApplyConfiguration) *ImageReviewSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereviewspec.go","code":"// WithContainers adds the given value to the Containers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Containers field.\nfunc (b *ImageReviewSpecApplyConfiguration) WithContainers(values ...*ImageReviewContainerSpecApplyConfiguration) *ImageReviewSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithContainers\")\n\t\t}\n\t\tb.Containers = append(b.Containers, *values[i])\n\t}\n\treturn b\n}","line":{"from":35,"to":46}} {"id":100023461,"name":"WithAnnotations","signature":"func (b *ImageReviewSpecApplyConfiguration) WithAnnotations(entries map[string]string) *ImageReviewSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereviewspec.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ImageReviewSpecApplyConfiguration) WithAnnotations(entries map[string]string) *ImageReviewSpecApplyConfiguration {\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":48,"to":60}} {"id":100023462,"name":"WithNamespace","signature":"func (b *ImageReviewSpecApplyConfiguration) WithNamespace(value string) *ImageReviewSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereviewspec.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ImageReviewSpecApplyConfiguration) WithNamespace(value string) *ImageReviewSpecApplyConfiguration {\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":62,"to":68}} {"id":100023463,"name":"ImageReviewStatus","signature":"func ImageReviewStatus() *ImageReviewStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereviewstatus.go","code":"// ImageReviewStatusApplyConfiguration constructs an declarative configuration of the ImageReviewStatus type for use with\n// apply.\nfunc ImageReviewStatus() *ImageReviewStatusApplyConfiguration {\n\treturn \u0026ImageReviewStatusApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100023464,"name":"WithAllowed","signature":"func (b *ImageReviewStatusApplyConfiguration) WithAllowed(value bool) *ImageReviewStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereviewstatus.go","code":"// WithAllowed sets the Allowed field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Allowed field is set to the value of the last call.\nfunc (b *ImageReviewStatusApplyConfiguration) WithAllowed(value bool) *ImageReviewStatusApplyConfiguration {\n\tb.Allowed = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100023465,"name":"WithReason","signature":"func (b *ImageReviewStatusApplyConfiguration) WithReason(value string) *ImageReviewStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereviewstatus.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *ImageReviewStatusApplyConfiguration) WithReason(value string) *ImageReviewStatusApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100023466,"name":"WithAuditAnnotations","signature":"func (b *ImageReviewStatusApplyConfiguration) WithAuditAnnotations(entries map[string]string) *ImageReviewStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/imagepolicy/v1alpha1/imagereviewstatus.go","code":"// WithAuditAnnotations puts the entries into the AuditAnnotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the AuditAnnotations field,\n// overwriting an existing map entries in AuditAnnotations field with the same key.\nfunc (b *ImageReviewStatusApplyConfiguration) WithAuditAnnotations(entries map[string]string) *ImageReviewStatusApplyConfiguration {\n\tif b.AuditAnnotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.AuditAnnotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.AuditAnnotations[k] = v\n\t}\n\treturn b\n}","line":{"from":51,"to":63}} {"id":100023467,"name":"Parser","signature":"func Parser() *typed.Parser","file":"staging/src/k8s.io/client-go/applyconfigurations/internal/internal.go","code":"func Parser() *typed.Parser {\n\tparserOnce.Do(func() {\n\t\tvar err error\n\t\tparser, err = typed.NewParser(schemaYAML)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Failed to parse schema: %v\", err))\n\t\t}\n\t})\n\treturn parser\n}","line":{"from":28,"to":37}} {"id":100023468,"name":"Condition","signature":"func Condition() *ConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/condition.go","code":"// ConditionApplyConfiguration constructs an declarative configuration of the Condition type for use with\n// apply.\nfunc Condition() *ConditionApplyConfiguration {\n\treturn \u0026ConditionApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100023469,"name":"WithType","signature":"func (b *ConditionApplyConfiguration) WithType(value string) *ConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/condition.go","code":"// WithType sets the Type field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Type field is set to the value of the last call.\nfunc (b *ConditionApplyConfiguration) WithType(value string) *ConditionApplyConfiguration {\n\tb.Type = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100023470,"name":"WithStatus","signature":"func (b *ConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *ConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/condition.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *ConditionApplyConfiguration) WithStatus(value v1.ConditionStatus) *ConditionApplyConfiguration {\n\tb.Status = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100023471,"name":"WithObservedGeneration","signature":"func (b *ConditionApplyConfiguration) WithObservedGeneration(value int64) *ConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/condition.go","code":"// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObservedGeneration field is set to the value of the last call.\nfunc (b *ConditionApplyConfiguration) WithObservedGeneration(value int64) *ConditionApplyConfiguration {\n\tb.ObservedGeneration = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100023472,"name":"WithLastTransitionTime","signature":"func (b *ConditionApplyConfiguration) WithLastTransitionTime(value v1.Time) *ConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/condition.go","code":"// WithLastTransitionTime sets the LastTransitionTime field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LastTransitionTime field is set to the value of the last call.\nfunc (b *ConditionApplyConfiguration) WithLastTransitionTime(value v1.Time) *ConditionApplyConfiguration {\n\tb.LastTransitionTime = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100023473,"name":"WithReason","signature":"func (b *ConditionApplyConfiguration) WithReason(value string) *ConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/condition.go","code":"// WithReason sets the Reason field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Reason field is set to the value of the last call.\nfunc (b *ConditionApplyConfiguration) WithReason(value string) *ConditionApplyConfiguration {\n\tb.Reason = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100023474,"name":"WithMessage","signature":"func (b *ConditionApplyConfiguration) WithMessage(value string) *ConditionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/condition.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *ConditionApplyConfiguration) WithMessage(value string) *ConditionApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100023475,"name":"DeleteOptions","signature":"func DeleteOptions() *DeleteOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/deleteoptions.go","code":"// DeleteOptionsApplyConfiguration constructs an declarative configuration of the DeleteOptions type for use with\n// apply.\nfunc DeleteOptions() *DeleteOptionsApplyConfiguration {\n\tb := \u0026DeleteOptionsApplyConfiguration{}\n\tb.WithKind(\"DeleteOptions\")\n\tb.WithAPIVersion(\"meta.k8s.io/v1\")\n\treturn b\n}","line":{"from":36,"to":43}} {"id":100023476,"name":"WithKind","signature":"func (b *DeleteOptionsApplyConfiguration) WithKind(value string) *DeleteOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/deleteoptions.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *DeleteOptionsApplyConfiguration) WithKind(value string) *DeleteOptionsApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":45,"to":51}} {"id":100023477,"name":"WithAPIVersion","signature":"func (b *DeleteOptionsApplyConfiguration) WithAPIVersion(value string) *DeleteOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/deleteoptions.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *DeleteOptionsApplyConfiguration) WithAPIVersion(value string) *DeleteOptionsApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":53,"to":59}} {"id":100023478,"name":"WithGracePeriodSeconds","signature":"func (b *DeleteOptionsApplyConfiguration) WithGracePeriodSeconds(value int64) *DeleteOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/deleteoptions.go","code":"// WithGracePeriodSeconds sets the GracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GracePeriodSeconds field is set to the value of the last call.\nfunc (b *DeleteOptionsApplyConfiguration) WithGracePeriodSeconds(value int64) *DeleteOptionsApplyConfiguration {\n\tb.GracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":61,"to":67}} {"id":100023479,"name":"WithPreconditions","signature":"func (b *DeleteOptionsApplyConfiguration) WithPreconditions(value *PreconditionsApplyConfiguration) *DeleteOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/deleteoptions.go","code":"// WithPreconditions sets the Preconditions field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Preconditions field is set to the value of the last call.\nfunc (b *DeleteOptionsApplyConfiguration) WithPreconditions(value *PreconditionsApplyConfiguration) *DeleteOptionsApplyConfiguration {\n\tb.Preconditions = value\n\treturn b\n}","line":{"from":69,"to":75}} {"id":100023480,"name":"WithOrphanDependents","signature":"func (b *DeleteOptionsApplyConfiguration) WithOrphanDependents(value bool) *DeleteOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/deleteoptions.go","code":"// WithOrphanDependents sets the OrphanDependents field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the OrphanDependents field is set to the value of the last call.\nfunc (b *DeleteOptionsApplyConfiguration) WithOrphanDependents(value bool) *DeleteOptionsApplyConfiguration {\n\tb.OrphanDependents = \u0026value\n\treturn b\n}","line":{"from":77,"to":83}} {"id":100023481,"name":"WithPropagationPolicy","signature":"func (b *DeleteOptionsApplyConfiguration) WithPropagationPolicy(value metav1.DeletionPropagation) *DeleteOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/deleteoptions.go","code":"// WithPropagationPolicy sets the PropagationPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PropagationPolicy field is set to the value of the last call.\nfunc (b *DeleteOptionsApplyConfiguration) WithPropagationPolicy(value metav1.DeletionPropagation) *DeleteOptionsApplyConfiguration {\n\tb.PropagationPolicy = \u0026value\n\treturn b\n}","line":{"from":85,"to":91}} {"id":100023482,"name":"WithDryRun","signature":"func (b *DeleteOptionsApplyConfiguration) WithDryRun(values ...string) *DeleteOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/deleteoptions.go","code":"// WithDryRun adds the given value to the DryRun field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the DryRun field.\nfunc (b *DeleteOptionsApplyConfiguration) WithDryRun(values ...string) *DeleteOptionsApplyConfiguration {\n\tfor i := range values {\n\t\tb.DryRun = append(b.DryRun, values[i])\n\t}\n\treturn b\n}","line":{"from":93,"to":101}} {"id":100023483,"name":"LabelSelector","signature":"func LabelSelector() *LabelSelectorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/labelselector.go","code":"// LabelSelectorApplyConfiguration constructs an declarative configuration of the LabelSelector type for use with\n// apply.\nfunc LabelSelector() *LabelSelectorApplyConfiguration {\n\treturn \u0026LabelSelectorApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100023484,"name":"WithMatchLabels","signature":"func (b *LabelSelectorApplyConfiguration) WithMatchLabels(entries map[string]string) *LabelSelectorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/labelselector.go","code":"// WithMatchLabels puts the entries into the MatchLabels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the MatchLabels field,\n// overwriting an existing map entries in MatchLabels field with the same key.\nfunc (b *LabelSelectorApplyConfiguration) WithMatchLabels(entries map[string]string) *LabelSelectorApplyConfiguration {\n\tif b.MatchLabels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.MatchLabels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.MatchLabels[k] = v\n\t}\n\treturn b\n}","line":{"from":34,"to":46}} {"id":100023485,"name":"WithMatchExpressions","signature":"func (b *LabelSelectorApplyConfiguration) WithMatchExpressions(values ...*LabelSelectorRequirementApplyConfiguration) *LabelSelectorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/labelselector.go","code":"// WithMatchExpressions adds the given value to the MatchExpressions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the MatchExpressions field.\nfunc (b *LabelSelectorApplyConfiguration) WithMatchExpressions(values ...*LabelSelectorRequirementApplyConfiguration) *LabelSelectorApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithMatchExpressions\")\n\t\t}\n\t\tb.MatchExpressions = append(b.MatchExpressions, *values[i])\n\t}\n\treturn b\n}","line":{"from":48,"to":59}} {"id":100023486,"name":"LabelSelectorRequirement","signature":"func LabelSelectorRequirement() *LabelSelectorRequirementApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/labelselectorrequirement.go","code":"// LabelSelectorRequirementApplyConfiguration constructs an declarative configuration of the LabelSelectorRequirement type for use with\n// apply.\nfunc LabelSelectorRequirement() *LabelSelectorRequirementApplyConfiguration {\n\treturn \u0026LabelSelectorRequirementApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100023487,"name":"WithKey","signature":"func (b *LabelSelectorRequirementApplyConfiguration) WithKey(value string) *LabelSelectorRequirementApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/labelselectorrequirement.go","code":"// WithKey sets the Key field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Key field is set to the value of the last call.\nfunc (b *LabelSelectorRequirementApplyConfiguration) WithKey(value string) *LabelSelectorRequirementApplyConfiguration {\n\tb.Key = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100023488,"name":"WithOperator","signature":"func (b *LabelSelectorRequirementApplyConfiguration) WithOperator(value v1.LabelSelectorOperator) *LabelSelectorRequirementApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/labelselectorrequirement.go","code":"// WithOperator sets the Operator field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Operator field is set to the value of the last call.\nfunc (b *LabelSelectorRequirementApplyConfiguration) WithOperator(value v1.LabelSelectorOperator) *LabelSelectorRequirementApplyConfiguration {\n\tb.Operator = \u0026value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100023489,"name":"WithValues","signature":"func (b *LabelSelectorRequirementApplyConfiguration) WithValues(values ...string) *LabelSelectorRequirementApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/labelselectorrequirement.go","code":"// WithValues adds the given value to the Values field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Values field.\nfunc (b *LabelSelectorRequirementApplyConfiguration) WithValues(values ...string) *LabelSelectorRequirementApplyConfiguration {\n\tfor i := range values {\n\t\tb.Values = append(b.Values, values[i])\n\t}\n\treturn b\n}","line":{"from":55,"to":63}} {"id":100023490,"name":"ManagedFieldsEntry","signature":"func ManagedFieldsEntry() *ManagedFieldsEntryApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/managedfieldsentry.go","code":"// ManagedFieldsEntryApplyConfiguration constructs an declarative configuration of the ManagedFieldsEntry type for use with\n// apply.\nfunc ManagedFieldsEntry() *ManagedFieldsEntryApplyConfiguration {\n\treturn \u0026ManagedFieldsEntryApplyConfiguration{}\n}","line":{"from":37,"to":41}} {"id":100023491,"name":"WithManager","signature":"func (b *ManagedFieldsEntryApplyConfiguration) WithManager(value string) *ManagedFieldsEntryApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/managedfieldsentry.go","code":"// WithManager sets the Manager field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Manager field is set to the value of the last call.\nfunc (b *ManagedFieldsEntryApplyConfiguration) WithManager(value string) *ManagedFieldsEntryApplyConfiguration {\n\tb.Manager = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100023492,"name":"WithOperation","signature":"func (b *ManagedFieldsEntryApplyConfiguration) WithOperation(value v1.ManagedFieldsOperationType) *ManagedFieldsEntryApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/managedfieldsentry.go","code":"// WithOperation sets the Operation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Operation field is set to the value of the last call.\nfunc (b *ManagedFieldsEntryApplyConfiguration) WithOperation(value v1.ManagedFieldsOperationType) *ManagedFieldsEntryApplyConfiguration {\n\tb.Operation = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100023493,"name":"WithAPIVersion","signature":"func (b *ManagedFieldsEntryApplyConfiguration) WithAPIVersion(value string) *ManagedFieldsEntryApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/managedfieldsentry.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ManagedFieldsEntryApplyConfiguration) WithAPIVersion(value string) *ManagedFieldsEntryApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":59,"to":65}} {"id":100023494,"name":"WithTime","signature":"func (b *ManagedFieldsEntryApplyConfiguration) WithTime(value v1.Time) *ManagedFieldsEntryApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/managedfieldsentry.go","code":"// WithTime sets the Time field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Time field is set to the value of the last call.\nfunc (b *ManagedFieldsEntryApplyConfiguration) WithTime(value v1.Time) *ManagedFieldsEntryApplyConfiguration {\n\tb.Time = \u0026value\n\treturn b\n}","line":{"from":67,"to":73}} {"id":100023495,"name":"WithFieldsType","signature":"func (b *ManagedFieldsEntryApplyConfiguration) WithFieldsType(value string) *ManagedFieldsEntryApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/managedfieldsentry.go","code":"// WithFieldsType sets the FieldsType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FieldsType field is set to the value of the last call.\nfunc (b *ManagedFieldsEntryApplyConfiguration) WithFieldsType(value string) *ManagedFieldsEntryApplyConfiguration {\n\tb.FieldsType = \u0026value\n\treturn b\n}","line":{"from":75,"to":81}} {"id":100023496,"name":"WithFieldsV1","signature":"func (b *ManagedFieldsEntryApplyConfiguration) WithFieldsV1(value v1.FieldsV1) *ManagedFieldsEntryApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/managedfieldsentry.go","code":"// WithFieldsV1 sets the FieldsV1 field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FieldsV1 field is set to the value of the last call.\nfunc (b *ManagedFieldsEntryApplyConfiguration) WithFieldsV1(value v1.FieldsV1) *ManagedFieldsEntryApplyConfiguration {\n\tb.FieldsV1 = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100023497,"name":"WithSubresource","signature":"func (b *ManagedFieldsEntryApplyConfiguration) WithSubresource(value string) *ManagedFieldsEntryApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/managedfieldsentry.go","code":"// WithSubresource sets the Subresource field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Subresource field is set to the value of the last call.\nfunc (b *ManagedFieldsEntryApplyConfiguration) WithSubresource(value string) *ManagedFieldsEntryApplyConfiguration {\n\tb.Subresource = \u0026value\n\treturn b\n}","line":{"from":91,"to":97}} {"id":100023498,"name":"ObjectMeta","signature":"func ObjectMeta() *ObjectMetaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/objectmeta.go","code":"// ObjectMetaApplyConfiguration constructs an declarative configuration of the ObjectMeta type for use with\n// apply.\nfunc ObjectMeta() *ObjectMetaApplyConfiguration {\n\treturn \u0026ObjectMetaApplyConfiguration{}\n}","line":{"from":44,"to":48}} {"id":100023499,"name":"WithName","signature":"func (b *ObjectMetaApplyConfiguration) WithName(value string) *ObjectMetaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/objectmeta.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ObjectMetaApplyConfiguration) WithName(value string) *ObjectMetaApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100023500,"name":"WithGenerateName","signature":"func (b *ObjectMetaApplyConfiguration) WithGenerateName(value string) *ObjectMetaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/objectmeta.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ObjectMetaApplyConfiguration) WithGenerateName(value string) *ObjectMetaApplyConfiguration {\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100023501,"name":"WithNamespace","signature":"func (b *ObjectMetaApplyConfiguration) WithNamespace(value string) *ObjectMetaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/objectmeta.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ObjectMetaApplyConfiguration) WithNamespace(value string) *ObjectMetaApplyConfiguration {\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100023502,"name":"WithUID","signature":"func (b *ObjectMetaApplyConfiguration) WithUID(value types.UID) *ObjectMetaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/objectmeta.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ObjectMetaApplyConfiguration) WithUID(value types.UID) *ObjectMetaApplyConfiguration {\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100023503,"name":"WithResourceVersion","signature":"func (b *ObjectMetaApplyConfiguration) WithResourceVersion(value string) *ObjectMetaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/objectmeta.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ObjectMetaApplyConfiguration) WithResourceVersion(value string) *ObjectMetaApplyConfiguration {\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100023504,"name":"WithGeneration","signature":"func (b *ObjectMetaApplyConfiguration) WithGeneration(value int64) *ObjectMetaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/objectmeta.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ObjectMetaApplyConfiguration) WithGeneration(value int64) *ObjectMetaApplyConfiguration {\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":90,"to":96}} {"id":100023505,"name":"WithCreationTimestamp","signature":"func (b *ObjectMetaApplyConfiguration) WithCreationTimestamp(value v1.Time) *ObjectMetaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/objectmeta.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ObjectMetaApplyConfiguration) WithCreationTimestamp(value v1.Time) *ObjectMetaApplyConfiguration {\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":98,"to":104}} {"id":100023506,"name":"WithDeletionTimestamp","signature":"func (b *ObjectMetaApplyConfiguration) WithDeletionTimestamp(value v1.Time) *ObjectMetaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/objectmeta.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ObjectMetaApplyConfiguration) WithDeletionTimestamp(value v1.Time) *ObjectMetaApplyConfiguration {\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":106,"to":112}} {"id":100023507,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ObjectMetaApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ObjectMetaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/objectmeta.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ObjectMetaApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ObjectMetaApplyConfiguration {\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":114,"to":120}} {"id":100023508,"name":"WithLabels","signature":"func (b *ObjectMetaApplyConfiguration) WithLabels(entries map[string]string) *ObjectMetaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/objectmeta.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ObjectMetaApplyConfiguration) WithLabels(entries map[string]string) *ObjectMetaApplyConfiguration {\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":122,"to":134}} {"id":100023509,"name":"WithAnnotations","signature":"func (b *ObjectMetaApplyConfiguration) WithAnnotations(entries map[string]string) *ObjectMetaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/objectmeta.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ObjectMetaApplyConfiguration) WithAnnotations(entries map[string]string) *ObjectMetaApplyConfiguration {\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":136,"to":148}} {"id":100023510,"name":"WithOwnerReferences","signature":"func (b *ObjectMetaApplyConfiguration) WithOwnerReferences(values ...*OwnerReferenceApplyConfiguration) *ObjectMetaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/objectmeta.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ObjectMetaApplyConfiguration) WithOwnerReferences(values ...*OwnerReferenceApplyConfiguration) *ObjectMetaApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":150,"to":161}} {"id":100023511,"name":"WithFinalizers","signature":"func (b *ObjectMetaApplyConfiguration) WithFinalizers(values ...string) *ObjectMetaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/objectmeta.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ObjectMetaApplyConfiguration) WithFinalizers(values ...string) *ObjectMetaApplyConfiguration {\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":163,"to":171}} {"id":100023512,"name":"OwnerReference","signature":"func OwnerReference() *OwnerReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/ownerreference.go","code":"// OwnerReferenceApplyConfiguration constructs an declarative configuration of the OwnerReference type for use with\n// apply.\nfunc OwnerReference() *OwnerReferenceApplyConfiguration {\n\treturn \u0026OwnerReferenceApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100023513,"name":"WithAPIVersion","signature":"func (b *OwnerReferenceApplyConfiguration) WithAPIVersion(value string) *OwnerReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/ownerreference.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *OwnerReferenceApplyConfiguration) WithAPIVersion(value string) *OwnerReferenceApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100023514,"name":"WithKind","signature":"func (b *OwnerReferenceApplyConfiguration) WithKind(value string) *OwnerReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/ownerreference.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *OwnerReferenceApplyConfiguration) WithKind(value string) *OwnerReferenceApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100023515,"name":"WithName","signature":"func (b *OwnerReferenceApplyConfiguration) WithName(value string) *OwnerReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/ownerreference.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *OwnerReferenceApplyConfiguration) WithName(value string) *OwnerReferenceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100023516,"name":"WithUID","signature":"func (b *OwnerReferenceApplyConfiguration) WithUID(value types.UID) *OwnerReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/ownerreference.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *OwnerReferenceApplyConfiguration) WithUID(value types.UID) *OwnerReferenceApplyConfiguration {\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100023517,"name":"WithController","signature":"func (b *OwnerReferenceApplyConfiguration) WithController(value bool) *OwnerReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/ownerreference.go","code":"// WithController sets the Controller field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Controller field is set to the value of the last call.\nfunc (b *OwnerReferenceApplyConfiguration) WithController(value bool) *OwnerReferenceApplyConfiguration {\n\tb.Controller = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100023518,"name":"WithBlockOwnerDeletion","signature":"func (b *OwnerReferenceApplyConfiguration) WithBlockOwnerDeletion(value bool) *OwnerReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/ownerreference.go","code":"// WithBlockOwnerDeletion sets the BlockOwnerDeletion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the BlockOwnerDeletion field is set to the value of the last call.\nfunc (b *OwnerReferenceApplyConfiguration) WithBlockOwnerDeletion(value bool) *OwnerReferenceApplyConfiguration {\n\tb.BlockOwnerDeletion = \u0026value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100023519,"name":"Preconditions","signature":"func Preconditions() *PreconditionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/preconditions.go","code":"// PreconditionsApplyConfiguration constructs an declarative configuration of the Preconditions type for use with\n// apply.\nfunc Preconditions() *PreconditionsApplyConfiguration {\n\treturn \u0026PreconditionsApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100023520,"name":"WithUID","signature":"func (b *PreconditionsApplyConfiguration) WithUID(value types.UID) *PreconditionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/preconditions.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *PreconditionsApplyConfiguration) WithUID(value types.UID) *PreconditionsApplyConfiguration {\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100023521,"name":"WithResourceVersion","signature":"func (b *PreconditionsApplyConfiguration) WithResourceVersion(value string) *PreconditionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/preconditions.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *PreconditionsApplyConfiguration) WithResourceVersion(value string) *PreconditionsApplyConfiguration {\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100023522,"name":"TypeMeta","signature":"func TypeMeta() *TypeMetaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/typemeta.go","code":"// TypeMetaApplyConfiguration constructs an declarative configuration of the TypeMeta type for use with\n// apply.\nfunc TypeMeta() *TypeMetaApplyConfiguration {\n\treturn \u0026TypeMetaApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100023523,"name":"WithKind","signature":"func (b *TypeMetaApplyConfiguration) WithKind(value string) *TypeMetaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/typemeta.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *TypeMetaApplyConfiguration) WithKind(value string) *TypeMetaApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100023524,"name":"WithAPIVersion","signature":"func (b *TypeMetaApplyConfiguration) WithAPIVersion(value string) *TypeMetaApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/typemeta.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *TypeMetaApplyConfiguration) WithAPIVersion(value string) *TypeMetaApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100023525,"name":"regenerateGVKParser","signature":"func regenerateGVKParser(dc discovery.DiscoveryInterface) (*managedfields.GvkParser, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/unstructured.go","code":"// regenerateGVKParser builds the parser from the raw OpenAPI schema.\nfunc regenerateGVKParser(dc discovery.DiscoveryInterface) (*managedfields.GvkParser, error) {\n\tdoc, err := dc.OpenAPISchema()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmodels, err := proto.NewOpenAPIData(doc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn managedfields.NewGVKParser(models, false)\n}","line":{"from":57,"to":70}} {"id":100023526,"name":"objectTypeForGVK","signature":"func (c *gvkParserCache) objectTypeForGVK(gvk schema.GroupVersionKind) (*typed.ParseableType, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/unstructured.go","code":"// objectTypeForGVK retrieves the typed.ParseableType for a given gvk from the cache\nfunc (c *gvkParserCache) objectTypeForGVK(gvk schema.GroupVersionKind) (*typed.ParseableType, error) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\t// if the ttl on the openAPISchema has expired,\n\t// regenerate the gvk parser\n\tif time.Since(c.lastChecked) \u003e openAPISchemaTTL {\n\t\tc.lastChecked = time.Now()\n\t\tparser, err := regenerateGVKParser(c.discoveryClient)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tc.gvkParser = parser\n\t}\n\treturn c.gvkParser.Type(gvk), nil\n}","line":{"from":72,"to":87}} {"id":100023527,"name":"NewUnstructuredExtractor","signature":"func NewUnstructuredExtractor(dc discovery.DiscoveryInterface) (UnstructuredExtractor, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/unstructured.go","code":"// NewUnstructuredExtractor creates the extractor with which you can extract the applied configuration\n// for a given manager from an unstructured object.\nfunc NewUnstructuredExtractor(dc discovery.DiscoveryInterface) (UnstructuredExtractor, error) {\n\tparser, err := regenerateGVKParser(dc)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed generating initial GVK Parser: %v\", err)\n\t}\n\treturn \u0026extractor{\n\t\tcache: \u0026gvkParserCache{\n\t\t\tgvkParser: parser,\n\t\t\tdiscoveryClient: dc,\n\t\t},\n\t}, nil\n}","line":{"from":93,"to":106}} {"id":100023528,"name":"Extract","signature":"func (e *extractor) Extract(object *unstructured.Unstructured, fieldManager string) (*unstructured.Unstructured, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/unstructured.go","code":"// Extract extracts the applied configuration owned by fieldManager from an unstructured object.\n// Note that the apply configuration itself is also an unstructured object.\nfunc (e *extractor) Extract(object *unstructured.Unstructured, fieldManager string) (*unstructured.Unstructured, error) {\n\treturn e.extractUnstructured(object, fieldManager, \"\")\n}","line":{"from":108,"to":112}} {"id":100023529,"name":"ExtractStatus","signature":"func (e *extractor) ExtractStatus(object *unstructured.Unstructured, fieldManager string) (*unstructured.Unstructured, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/unstructured.go","code":"// ExtractStatus is the same as ExtractUnstructured except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc (e *extractor) ExtractStatus(object *unstructured.Unstructured, fieldManager string) (*unstructured.Unstructured, error) {\n\treturn e.extractUnstructured(object, fieldManager, \"status\")\n}","line":{"from":114,"to":119}} {"id":100023530,"name":"extractUnstructured","signature":"func (e *extractor) extractUnstructured(object *unstructured.Unstructured, fieldManager string, subresource string) (*unstructured.Unstructured, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/meta/v1/unstructured.go","code":"func (e *extractor) extractUnstructured(object *unstructured.Unstructured, fieldManager string, subresource string) (*unstructured.Unstructured, error) {\n\tgvk := object.GetObjectKind().GroupVersionKind()\n\tobjectType, err := e.cache.objectTypeForGVK(gvk)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to fetch the objectType: %v\", err)\n\t}\n\tresult := \u0026unstructured.Unstructured{}\n\terr = managedfields.ExtractInto(object, *objectType, fieldManager, result, subresource)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed calling ExtractInto for unstructured: %v\", err)\n\t}\n\tresult.SetName(object.GetName())\n\tresult.SetNamespace(object.GetNamespace())\n\tresult.SetKind(object.GetKind())\n\tresult.SetAPIVersion(object.GetAPIVersion())\n\treturn result, nil\n}","line":{"from":121,"to":137}} {"id":100023531,"name":"HTTPIngressPath","signature":"func HTTPIngressPath() *HTTPIngressPathApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/httpingresspath.go","code":"// HTTPIngressPathApplyConfiguration constructs an declarative configuration of the HTTPIngressPath type for use with\n// apply.\nfunc HTTPIngressPath() *HTTPIngressPathApplyConfiguration {\n\treturn \u0026HTTPIngressPathApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100023532,"name":"WithPath","signature":"func (b *HTTPIngressPathApplyConfiguration) WithPath(value string) *HTTPIngressPathApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/httpingresspath.go","code":"// WithPath sets the Path field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Path field is set to the value of the last call.\nfunc (b *HTTPIngressPathApplyConfiguration) WithPath(value string) *HTTPIngressPathApplyConfiguration {\n\tb.Path = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100023533,"name":"WithPathType","signature":"func (b *HTTPIngressPathApplyConfiguration) WithPathType(value v1.PathType) *HTTPIngressPathApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/httpingresspath.go","code":"// WithPathType sets the PathType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PathType field is set to the value of the last call.\nfunc (b *HTTPIngressPathApplyConfiguration) WithPathType(value v1.PathType) *HTTPIngressPathApplyConfiguration {\n\tb.PathType = \u0026value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100023534,"name":"WithBackend","signature":"func (b *HTTPIngressPathApplyConfiguration) WithBackend(value *IngressBackendApplyConfiguration) *HTTPIngressPathApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/httpingresspath.go","code":"// WithBackend sets the Backend field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Backend field is set to the value of the last call.\nfunc (b *HTTPIngressPathApplyConfiguration) WithBackend(value *IngressBackendApplyConfiguration) *HTTPIngressPathApplyConfiguration {\n\tb.Backend = value\n\treturn b\n}","line":{"from":55,"to":61}} {"id":100023535,"name":"HTTPIngressRuleValue","signature":"func HTTPIngressRuleValue() *HTTPIngressRuleValueApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/httpingressrulevalue.go","code":"// HTTPIngressRuleValueApplyConfiguration constructs an declarative configuration of the HTTPIngressRuleValue type for use with\n// apply.\nfunc HTTPIngressRuleValue() *HTTPIngressRuleValueApplyConfiguration {\n\treturn \u0026HTTPIngressRuleValueApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023536,"name":"WithPaths","signature":"func (b *HTTPIngressRuleValueApplyConfiguration) WithPaths(values ...*HTTPIngressPathApplyConfiguration) *HTTPIngressRuleValueApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/httpingressrulevalue.go","code":"// WithPaths adds the given value to the Paths field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Paths field.\nfunc (b *HTTPIngressRuleValueApplyConfiguration) WithPaths(values ...*HTTPIngressPathApplyConfiguration) *HTTPIngressRuleValueApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPaths\")\n\t\t}\n\t\tb.Paths = append(b.Paths, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100023537,"name":"Ingress","signature":"func Ingress(name, namespace string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingress.go","code":"// Ingress constructs an declarative configuration of the Ingress type for use with\n// apply.\nfunc Ingress(name, namespace string) *IngressApplyConfiguration {\n\tb := \u0026IngressApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"Ingress\")\n\tb.WithAPIVersion(\"networking.k8s.io/v1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100023538,"name":"ExtractIngress","signature":"func ExtractIngress(ingress *apinetworkingv1.Ingress, fieldManager string) (*IngressApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingress.go","code":"// ExtractIngress extracts the applied configuration owned by fieldManager from\n// ingress. If no managedFields are found in ingress for fieldManager, a\n// IngressApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// ingress must be a unmodified Ingress API object that was retrieved from the Kubernetes API.\n// ExtractIngress provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractIngress(ingress *apinetworkingv1.Ingress, fieldManager string) (*IngressApplyConfiguration, error) {\n\treturn extractIngress(ingress, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100023539,"name":"ExtractIngressStatus","signature":"func ExtractIngressStatus(ingress *apinetworkingv1.Ingress, fieldManager string) (*IngressApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingress.go","code":"// ExtractIngressStatus is the same as ExtractIngress except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractIngressStatus(ingress *apinetworkingv1.Ingress, fieldManager string) (*IngressApplyConfiguration, error) {\n\treturn extractIngress(ingress, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100023540,"name":"extractIngress","signature":"func extractIngress(ingress *apinetworkingv1.Ingress, fieldManager string, subresource string) (*IngressApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingress.go","code":"func extractIngress(ingress *apinetworkingv1.Ingress, fieldManager string, subresource string) (*IngressApplyConfiguration, error) {\n\tb := \u0026IngressApplyConfiguration{}\n\terr := managedfields.ExtractInto(ingress, internal.Parser().Type(\"io.k8s.api.networking.v1.Ingress\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(ingress.Name)\n\tb.WithNamespace(ingress.Namespace)\n\n\tb.WithKind(\"Ingress\")\n\tb.WithAPIVersion(\"networking.k8s.io/v1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100023541,"name":"WithKind","signature":"func (b *IngressApplyConfiguration) WithKind(value string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingress.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithKind(value string) *IngressApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100023542,"name":"WithAPIVersion","signature":"func (b *IngressApplyConfiguration) WithAPIVersion(value string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingress.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithAPIVersion(value string) *IngressApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100023543,"name":"WithName","signature":"func (b *IngressApplyConfiguration) WithName(value string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingress.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithName(value string) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100023544,"name":"WithGenerateName","signature":"func (b *IngressApplyConfiguration) WithGenerateName(value string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingress.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithGenerateName(value string) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100023545,"name":"WithNamespace","signature":"func (b *IngressApplyConfiguration) WithNamespace(value string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingress.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithNamespace(value string) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100023546,"name":"WithUID","signature":"func (b *IngressApplyConfiguration) WithUID(value types.UID) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingress.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithUID(value types.UID) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100023547,"name":"WithResourceVersion","signature":"func (b *IngressApplyConfiguration) WithResourceVersion(value string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingress.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithResourceVersion(value string) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100023548,"name":"WithGeneration","signature":"func (b *IngressApplyConfiguration) WithGeneration(value int64) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingress.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithGeneration(value int64) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100023549,"name":"WithCreationTimestamp","signature":"func (b *IngressApplyConfiguration) WithCreationTimestamp(value metav1.Time) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingress.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithCreationTimestamp(value metav1.Time) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100023550,"name":"WithDeletionTimestamp","signature":"func (b *IngressApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingress.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100023551,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *IngressApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingress.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100023552,"name":"WithLabels","signature":"func (b *IngressApplyConfiguration) WithLabels(entries map[string]string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingress.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *IngressApplyConfiguration) WithLabels(entries map[string]string) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100023553,"name":"WithAnnotations","signature":"func (b *IngressApplyConfiguration) WithAnnotations(entries map[string]string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingress.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *IngressApplyConfiguration) WithAnnotations(entries map[string]string) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100023554,"name":"WithOwnerReferences","signature":"func (b *IngressApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingress.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *IngressApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100023555,"name":"WithFinalizers","signature":"func (b *IngressApplyConfiguration) WithFinalizers(values ...string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingress.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *IngressApplyConfiguration) WithFinalizers(values ...string) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100023556,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *IngressApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingress.go","code":"func (b *IngressApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100023557,"name":"WithSpec","signature":"func (b *IngressApplyConfiguration) WithSpec(value *IngressSpecApplyConfiguration) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingress.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithSpec(value *IngressSpecApplyConfiguration) *IngressApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100023558,"name":"WithStatus","signature":"func (b *IngressApplyConfiguration) WithStatus(value *IngressStatusApplyConfiguration) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingress.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithStatus(value *IngressStatusApplyConfiguration) *IngressApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100023559,"name":"IngressBackend","signature":"func IngressBackend() *IngressBackendApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressbackend.go","code":"// IngressBackendApplyConfiguration constructs an declarative configuration of the IngressBackend type for use with\n// apply.\nfunc IngressBackend() *IngressBackendApplyConfiguration {\n\treturn \u0026IngressBackendApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100023560,"name":"WithService","signature":"func (b *IngressBackendApplyConfiguration) WithService(value *IngressServiceBackendApplyConfiguration) *IngressBackendApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressbackend.go","code":"// WithService sets the Service field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Service field is set to the value of the last call.\nfunc (b *IngressBackendApplyConfiguration) WithService(value *IngressServiceBackendApplyConfiguration) *IngressBackendApplyConfiguration {\n\tb.Service = value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100023561,"name":"WithResource","signature":"func (b *IngressBackendApplyConfiguration) WithResource(value *corev1.TypedLocalObjectReferenceApplyConfiguration) *IngressBackendApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressbackend.go","code":"// WithResource sets the Resource field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Resource field is set to the value of the last call.\nfunc (b *IngressBackendApplyConfiguration) WithResource(value *corev1.TypedLocalObjectReferenceApplyConfiguration) *IngressBackendApplyConfiguration {\n\tb.Resource = value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100023562,"name":"IngressClass","signature":"func IngressClass(name string) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclass.go","code":"// IngressClass constructs an declarative configuration of the IngressClass type for use with\n// apply.\nfunc IngressClass(name string) *IngressClassApplyConfiguration {\n\tb := \u0026IngressClassApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"IngressClass\")\n\tb.WithAPIVersion(\"networking.k8s.io/v1\")\n\treturn b\n}","line":{"from":38,"to":46}} {"id":100023563,"name":"ExtractIngressClass","signature":"func ExtractIngressClass(ingressClass *apinetworkingv1.IngressClass, fieldManager string) (*IngressClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclass.go","code":"// ExtractIngressClass extracts the applied configuration owned by fieldManager from\n// ingressClass. If no managedFields are found in ingressClass for fieldManager, a\n// IngressClassApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// ingressClass must be a unmodified IngressClass API object that was retrieved from the Kubernetes API.\n// ExtractIngressClass provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractIngressClass(ingressClass *apinetworkingv1.IngressClass, fieldManager string) (*IngressClassApplyConfiguration, error) {\n\treturn extractIngressClass(ingressClass, fieldManager, \"\")\n}","line":{"from":48,"to":61}} {"id":100023564,"name":"ExtractIngressClassStatus","signature":"func ExtractIngressClassStatus(ingressClass *apinetworkingv1.IngressClass, fieldManager string) (*IngressClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclass.go","code":"// ExtractIngressClassStatus is the same as ExtractIngressClass except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractIngressClassStatus(ingressClass *apinetworkingv1.IngressClass, fieldManager string) (*IngressClassApplyConfiguration, error) {\n\treturn extractIngressClass(ingressClass, fieldManager, \"status\")\n}","line":{"from":63,"to":68}} {"id":100023565,"name":"extractIngressClass","signature":"func extractIngressClass(ingressClass *apinetworkingv1.IngressClass, fieldManager string, subresource string) (*IngressClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclass.go","code":"func extractIngressClass(ingressClass *apinetworkingv1.IngressClass, fieldManager string, subresource string) (*IngressClassApplyConfiguration, error) {\n\tb := \u0026IngressClassApplyConfiguration{}\n\terr := managedfields.ExtractInto(ingressClass, internal.Parser().Type(\"io.k8s.api.networking.v1.IngressClass\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(ingressClass.Name)\n\n\tb.WithKind(\"IngressClass\")\n\tb.WithAPIVersion(\"networking.k8s.io/v1\")\n\treturn b, nil\n}","line":{"from":70,"to":81}} {"id":100023566,"name":"WithKind","signature":"func (b *IngressClassApplyConfiguration) WithKind(value string) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclass.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *IngressClassApplyConfiguration) WithKind(value string) *IngressClassApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100023567,"name":"WithAPIVersion","signature":"func (b *IngressClassApplyConfiguration) WithAPIVersion(value string) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclass.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *IngressClassApplyConfiguration) WithAPIVersion(value string) *IngressClassApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":91,"to":97}} {"id":100023568,"name":"WithName","signature":"func (b *IngressClassApplyConfiguration) WithName(value string) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclass.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *IngressClassApplyConfiguration) WithName(value string) *IngressClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":99,"to":106}} {"id":100023569,"name":"WithGenerateName","signature":"func (b *IngressClassApplyConfiguration) WithGenerateName(value string) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclass.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *IngressClassApplyConfiguration) WithGenerateName(value string) *IngressClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":108,"to":115}} {"id":100023570,"name":"WithNamespace","signature":"func (b *IngressClassApplyConfiguration) WithNamespace(value string) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclass.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *IngressClassApplyConfiguration) WithNamespace(value string) *IngressClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":117,"to":124}} {"id":100023571,"name":"WithUID","signature":"func (b *IngressClassApplyConfiguration) WithUID(value types.UID) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclass.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *IngressClassApplyConfiguration) WithUID(value types.UID) *IngressClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":126,"to":133}} {"id":100023572,"name":"WithResourceVersion","signature":"func (b *IngressClassApplyConfiguration) WithResourceVersion(value string) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclass.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *IngressClassApplyConfiguration) WithResourceVersion(value string) *IngressClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":135,"to":142}} {"id":100023573,"name":"WithGeneration","signature":"func (b *IngressClassApplyConfiguration) WithGeneration(value int64) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclass.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *IngressClassApplyConfiguration) WithGeneration(value int64) *IngressClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":144,"to":151}} {"id":100023574,"name":"WithCreationTimestamp","signature":"func (b *IngressClassApplyConfiguration) WithCreationTimestamp(value metav1.Time) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclass.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *IngressClassApplyConfiguration) WithCreationTimestamp(value metav1.Time) *IngressClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":153,"to":160}} {"id":100023575,"name":"WithDeletionTimestamp","signature":"func (b *IngressClassApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclass.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *IngressClassApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *IngressClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":162,"to":169}} {"id":100023576,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *IngressClassApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclass.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *IngressClassApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *IngressClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":171,"to":178}} {"id":100023577,"name":"WithLabels","signature":"func (b *IngressClassApplyConfiguration) WithLabels(entries map[string]string) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclass.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *IngressClassApplyConfiguration) WithLabels(entries map[string]string) *IngressClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":180,"to":193}} {"id":100023578,"name":"WithAnnotations","signature":"func (b *IngressClassApplyConfiguration) WithAnnotations(entries map[string]string) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclass.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *IngressClassApplyConfiguration) WithAnnotations(entries map[string]string) *IngressClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":195,"to":208}} {"id":100023579,"name":"WithOwnerReferences","signature":"func (b *IngressClassApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclass.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *IngressClassApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *IngressClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":210,"to":222}} {"id":100023580,"name":"WithFinalizers","signature":"func (b *IngressClassApplyConfiguration) WithFinalizers(values ...string) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclass.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *IngressClassApplyConfiguration) WithFinalizers(values ...string) *IngressClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":224,"to":233}} {"id":100023581,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *IngressClassApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclass.go","code":"func (b *IngressClassApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":235,"to":239}} {"id":100023582,"name":"WithSpec","signature":"func (b *IngressClassApplyConfiguration) WithSpec(value *IngressClassSpecApplyConfiguration) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclass.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *IngressClassApplyConfiguration) WithSpec(value *IngressClassSpecApplyConfiguration) *IngressClassApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":241,"to":247}} {"id":100023583,"name":"IngressClassParametersReference","signature":"func IngressClassParametersReference() *IngressClassParametersReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclassparametersreference.go","code":"// IngressClassParametersReferenceApplyConfiguration constructs an declarative configuration of the IngressClassParametersReference type for use with\n// apply.\nfunc IngressClassParametersReference() *IngressClassParametersReferenceApplyConfiguration {\n\treturn \u0026IngressClassParametersReferenceApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100023584,"name":"WithAPIGroup","signature":"func (b *IngressClassParametersReferenceApplyConfiguration) WithAPIGroup(value string) *IngressClassParametersReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclassparametersreference.go","code":"// WithAPIGroup sets the APIGroup field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIGroup field is set to the value of the last call.\nfunc (b *IngressClassParametersReferenceApplyConfiguration) WithAPIGroup(value string) *IngressClassParametersReferenceApplyConfiguration {\n\tb.APIGroup = \u0026value\n\treturn b\n}","line":{"from":37,"to":43}} {"id":100023585,"name":"WithKind","signature":"func (b *IngressClassParametersReferenceApplyConfiguration) WithKind(value string) *IngressClassParametersReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclassparametersreference.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *IngressClassParametersReferenceApplyConfiguration) WithKind(value string) *IngressClassParametersReferenceApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":45,"to":51}} {"id":100023586,"name":"WithName","signature":"func (b *IngressClassParametersReferenceApplyConfiguration) WithName(value string) *IngressClassParametersReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclassparametersreference.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *IngressClassParametersReferenceApplyConfiguration) WithName(value string) *IngressClassParametersReferenceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":53,"to":59}} {"id":100023587,"name":"WithScope","signature":"func (b *IngressClassParametersReferenceApplyConfiguration) WithScope(value string) *IngressClassParametersReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclassparametersreference.go","code":"// WithScope sets the Scope field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Scope field is set to the value of the last call.\nfunc (b *IngressClassParametersReferenceApplyConfiguration) WithScope(value string) *IngressClassParametersReferenceApplyConfiguration {\n\tb.Scope = \u0026value\n\treturn b\n}","line":{"from":61,"to":67}} {"id":100023588,"name":"WithNamespace","signature":"func (b *IngressClassParametersReferenceApplyConfiguration) WithNamespace(value string) *IngressClassParametersReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclassparametersreference.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *IngressClassParametersReferenceApplyConfiguration) WithNamespace(value string) *IngressClassParametersReferenceApplyConfiguration {\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":69,"to":75}} {"id":100023589,"name":"IngressClassSpec","signature":"func IngressClassSpec() *IngressClassSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclassspec.go","code":"// IngressClassSpecApplyConfiguration constructs an declarative configuration of the IngressClassSpec type for use with\n// apply.\nfunc IngressClassSpec() *IngressClassSpecApplyConfiguration {\n\treturn \u0026IngressClassSpecApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100023590,"name":"WithController","signature":"func (b *IngressClassSpecApplyConfiguration) WithController(value string) *IngressClassSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclassspec.go","code":"// WithController sets the Controller field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Controller field is set to the value of the last call.\nfunc (b *IngressClassSpecApplyConfiguration) WithController(value string) *IngressClassSpecApplyConfiguration {\n\tb.Controller = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100023591,"name":"WithParameters","signature":"func (b *IngressClassSpecApplyConfiguration) WithParameters(value *IngressClassParametersReferenceApplyConfiguration) *IngressClassSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressclassspec.go","code":"// WithParameters sets the Parameters field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Parameters field is set to the value of the last call.\nfunc (b *IngressClassSpecApplyConfiguration) WithParameters(value *IngressClassParametersReferenceApplyConfiguration) *IngressClassSpecApplyConfiguration {\n\tb.Parameters = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100023592,"name":"IngressLoadBalancerIngress","signature":"func IngressLoadBalancerIngress() *IngressLoadBalancerIngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressloadbalanceringress.go","code":"// IngressLoadBalancerIngressApplyConfiguration constructs an declarative configuration of the IngressLoadBalancerIngress type for use with\n// apply.\nfunc IngressLoadBalancerIngress() *IngressLoadBalancerIngressApplyConfiguration {\n\treturn \u0026IngressLoadBalancerIngressApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100023593,"name":"WithIP","signature":"func (b *IngressLoadBalancerIngressApplyConfiguration) WithIP(value string) *IngressLoadBalancerIngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressloadbalanceringress.go","code":"// WithIP sets the IP field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the IP field is set to the value of the last call.\nfunc (b *IngressLoadBalancerIngressApplyConfiguration) WithIP(value string) *IngressLoadBalancerIngressApplyConfiguration {\n\tb.IP = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100023594,"name":"WithHostname","signature":"func (b *IngressLoadBalancerIngressApplyConfiguration) WithHostname(value string) *IngressLoadBalancerIngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressloadbalanceringress.go","code":"// WithHostname sets the Hostname field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Hostname field is set to the value of the last call.\nfunc (b *IngressLoadBalancerIngressApplyConfiguration) WithHostname(value string) *IngressLoadBalancerIngressApplyConfiguration {\n\tb.Hostname = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100023595,"name":"WithPorts","signature":"func (b *IngressLoadBalancerIngressApplyConfiguration) WithPorts(values ...*IngressPortStatusApplyConfiguration) *IngressLoadBalancerIngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressloadbalanceringress.go","code":"// WithPorts adds the given value to the Ports field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Ports field.\nfunc (b *IngressLoadBalancerIngressApplyConfiguration) WithPorts(values ...*IngressPortStatusApplyConfiguration) *IngressLoadBalancerIngressApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPorts\")\n\t\t}\n\t\tb.Ports = append(b.Ports, *values[i])\n\t}\n\treturn b\n}","line":{"from":51,"to":62}} {"id":100023596,"name":"IngressLoadBalancerStatus","signature":"func IngressLoadBalancerStatus() *IngressLoadBalancerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressloadbalancerstatus.go","code":"// IngressLoadBalancerStatusApplyConfiguration constructs an declarative configuration of the IngressLoadBalancerStatus type for use with\n// apply.\nfunc IngressLoadBalancerStatus() *IngressLoadBalancerStatusApplyConfiguration {\n\treturn \u0026IngressLoadBalancerStatusApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023597,"name":"WithIngress","signature":"func (b *IngressLoadBalancerStatusApplyConfiguration) WithIngress(values ...*IngressLoadBalancerIngressApplyConfiguration) *IngressLoadBalancerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressloadbalancerstatus.go","code":"// WithIngress adds the given value to the Ingress field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Ingress field.\nfunc (b *IngressLoadBalancerStatusApplyConfiguration) WithIngress(values ...*IngressLoadBalancerIngressApplyConfiguration) *IngressLoadBalancerStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithIngress\")\n\t\t}\n\t\tb.Ingress = append(b.Ingress, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100023598,"name":"IngressPortStatus","signature":"func IngressPortStatus() *IngressPortStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressportstatus.go","code":"// IngressPortStatusApplyConfiguration constructs an declarative configuration of the IngressPortStatus type for use with\n// apply.\nfunc IngressPortStatus() *IngressPortStatusApplyConfiguration {\n\treturn \u0026IngressPortStatusApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100023599,"name":"WithPort","signature":"func (b *IngressPortStatusApplyConfiguration) WithPort(value int32) *IngressPortStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressportstatus.go","code":"// WithPort sets the Port field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Port field is set to the value of the last call.\nfunc (b *IngressPortStatusApplyConfiguration) WithPort(value int32) *IngressPortStatusApplyConfiguration {\n\tb.Port = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100023600,"name":"WithProtocol","signature":"func (b *IngressPortStatusApplyConfiguration) WithProtocol(value v1.Protocol) *IngressPortStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressportstatus.go","code":"// WithProtocol sets the Protocol field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Protocol field is set to the value of the last call.\nfunc (b *IngressPortStatusApplyConfiguration) WithProtocol(value v1.Protocol) *IngressPortStatusApplyConfiguration {\n\tb.Protocol = \u0026value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100023601,"name":"WithError","signature":"func (b *IngressPortStatusApplyConfiguration) WithError(value string) *IngressPortStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressportstatus.go","code":"// WithError sets the Error field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Error field is set to the value of the last call.\nfunc (b *IngressPortStatusApplyConfiguration) WithError(value string) *IngressPortStatusApplyConfiguration {\n\tb.Error = \u0026value\n\treturn b\n}","line":{"from":55,"to":61}} {"id":100023602,"name":"IngressRule","signature":"func IngressRule() *IngressRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressrule.go","code":"// IngressRuleApplyConfiguration constructs an declarative configuration of the IngressRule type for use with\n// apply.\nfunc IngressRule() *IngressRuleApplyConfiguration {\n\treturn \u0026IngressRuleApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100023603,"name":"WithHost","signature":"func (b *IngressRuleApplyConfiguration) WithHost(value string) *IngressRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressrule.go","code":"// WithHost sets the Host field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Host field is set to the value of the last call.\nfunc (b *IngressRuleApplyConfiguration) WithHost(value string) *IngressRuleApplyConfiguration {\n\tb.Host = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100023604,"name":"WithHTTP","signature":"func (b *IngressRuleApplyConfiguration) WithHTTP(value *HTTPIngressRuleValueApplyConfiguration) *IngressRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressrule.go","code":"// WithHTTP sets the HTTP field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HTTP field is set to the value of the last call.\nfunc (b *IngressRuleApplyConfiguration) WithHTTP(value *HTTPIngressRuleValueApplyConfiguration) *IngressRuleApplyConfiguration {\n\tb.HTTP = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100023605,"name":"IngressRuleValue","signature":"func IngressRuleValue() *IngressRuleValueApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressrulevalue.go","code":"// IngressRuleValueApplyConfiguration constructs an declarative configuration of the IngressRuleValue type for use with\n// apply.\nfunc IngressRuleValue() *IngressRuleValueApplyConfiguration {\n\treturn \u0026IngressRuleValueApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023606,"name":"WithHTTP","signature":"func (b *IngressRuleValueApplyConfiguration) WithHTTP(value *HTTPIngressRuleValueApplyConfiguration) *IngressRuleValueApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressrulevalue.go","code":"// WithHTTP sets the HTTP field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HTTP field is set to the value of the last call.\nfunc (b *IngressRuleValueApplyConfiguration) WithHTTP(value *HTTPIngressRuleValueApplyConfiguration) *IngressRuleValueApplyConfiguration {\n\tb.HTTP = value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100023607,"name":"IngressServiceBackend","signature":"func IngressServiceBackend() *IngressServiceBackendApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressservicebackend.go","code":"// IngressServiceBackendApplyConfiguration constructs an declarative configuration of the IngressServiceBackend type for use with\n// apply.\nfunc IngressServiceBackend() *IngressServiceBackendApplyConfiguration {\n\treturn \u0026IngressServiceBackendApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100023608,"name":"WithName","signature":"func (b *IngressServiceBackendApplyConfiguration) WithName(value string) *IngressServiceBackendApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressservicebackend.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *IngressServiceBackendApplyConfiguration) WithName(value string) *IngressServiceBackendApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100023609,"name":"WithPort","signature":"func (b *IngressServiceBackendApplyConfiguration) WithPort(value *ServiceBackendPortApplyConfiguration) *IngressServiceBackendApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressservicebackend.go","code":"// WithPort sets the Port field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Port field is set to the value of the last call.\nfunc (b *IngressServiceBackendApplyConfiguration) WithPort(value *ServiceBackendPortApplyConfiguration) *IngressServiceBackendApplyConfiguration {\n\tb.Port = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100023610,"name":"IngressSpec","signature":"func IngressSpec() *IngressSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressspec.go","code":"// IngressSpecApplyConfiguration constructs an declarative configuration of the IngressSpec type for use with\n// apply.\nfunc IngressSpec() *IngressSpecApplyConfiguration {\n\treturn \u0026IngressSpecApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100023611,"name":"WithIngressClassName","signature":"func (b *IngressSpecApplyConfiguration) WithIngressClassName(value string) *IngressSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressspec.go","code":"// WithIngressClassName sets the IngressClassName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the IngressClassName field is set to the value of the last call.\nfunc (b *IngressSpecApplyConfiguration) WithIngressClassName(value string) *IngressSpecApplyConfiguration {\n\tb.IngressClassName = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100023612,"name":"WithDefaultBackend","signature":"func (b *IngressSpecApplyConfiguration) WithDefaultBackend(value *IngressBackendApplyConfiguration) *IngressSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressspec.go","code":"// WithDefaultBackend sets the DefaultBackend field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DefaultBackend field is set to the value of the last call.\nfunc (b *IngressSpecApplyConfiguration) WithDefaultBackend(value *IngressBackendApplyConfiguration) *IngressSpecApplyConfiguration {\n\tb.DefaultBackend = value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100023613,"name":"WithTLS","signature":"func (b *IngressSpecApplyConfiguration) WithTLS(values ...*IngressTLSApplyConfiguration) *IngressSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressspec.go","code":"// WithTLS adds the given value to the TLS field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the TLS field.\nfunc (b *IngressSpecApplyConfiguration) WithTLS(values ...*IngressTLSApplyConfiguration) *IngressSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithTLS\")\n\t\t}\n\t\tb.TLS = append(b.TLS, *values[i])\n\t}\n\treturn b\n}","line":{"from":52,"to":63}} {"id":100023614,"name":"WithRules","signature":"func (b *IngressSpecApplyConfiguration) WithRules(values ...*IngressRuleApplyConfiguration) *IngressSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressspec.go","code":"// WithRules adds the given value to the Rules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Rules field.\nfunc (b *IngressSpecApplyConfiguration) WithRules(values ...*IngressRuleApplyConfiguration) *IngressSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRules\")\n\t\t}\n\t\tb.Rules = append(b.Rules, *values[i])\n\t}\n\treturn b\n}","line":{"from":65,"to":76}} {"id":100023615,"name":"IngressStatus","signature":"func IngressStatus() *IngressStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressstatus.go","code":"// IngressStatusApplyConfiguration constructs an declarative configuration of the IngressStatus type for use with\n// apply.\nfunc IngressStatus() *IngressStatusApplyConfiguration {\n\treturn \u0026IngressStatusApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023616,"name":"WithLoadBalancer","signature":"func (b *IngressStatusApplyConfiguration) WithLoadBalancer(value *IngressLoadBalancerStatusApplyConfiguration) *IngressStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingressstatus.go","code":"// WithLoadBalancer sets the LoadBalancer field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LoadBalancer field is set to the value of the last call.\nfunc (b *IngressStatusApplyConfiguration) WithLoadBalancer(value *IngressLoadBalancerStatusApplyConfiguration) *IngressStatusApplyConfiguration {\n\tb.LoadBalancer = value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100023617,"name":"IngressTLS","signature":"func IngressTLS() *IngressTLSApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingresstls.go","code":"// IngressTLSApplyConfiguration constructs an declarative configuration of the IngressTLS type for use with\n// apply.\nfunc IngressTLS() *IngressTLSApplyConfiguration {\n\treturn \u0026IngressTLSApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100023618,"name":"WithHosts","signature":"func (b *IngressTLSApplyConfiguration) WithHosts(values ...string) *IngressTLSApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingresstls.go","code":"// WithHosts adds the given value to the Hosts field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Hosts field.\nfunc (b *IngressTLSApplyConfiguration) WithHosts(values ...string) *IngressTLSApplyConfiguration {\n\tfor i := range values {\n\t\tb.Hosts = append(b.Hosts, values[i])\n\t}\n\treturn b\n}","line":{"from":34,"to":42}} {"id":100023619,"name":"WithSecretName","signature":"func (b *IngressTLSApplyConfiguration) WithSecretName(value string) *IngressTLSApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ingresstls.go","code":"// WithSecretName sets the SecretName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecretName field is set to the value of the last call.\nfunc (b *IngressTLSApplyConfiguration) WithSecretName(value string) *IngressTLSApplyConfiguration {\n\tb.SecretName = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100023620,"name":"IPBlock","signature":"func IPBlock() *IPBlockApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ipblock.go","code":"// IPBlockApplyConfiguration constructs an declarative configuration of the IPBlock type for use with\n// apply.\nfunc IPBlock() *IPBlockApplyConfiguration {\n\treturn \u0026IPBlockApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100023621,"name":"WithCIDR","signature":"func (b *IPBlockApplyConfiguration) WithCIDR(value string) *IPBlockApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ipblock.go","code":"// WithCIDR sets the CIDR field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CIDR field is set to the value of the last call.\nfunc (b *IPBlockApplyConfiguration) WithCIDR(value string) *IPBlockApplyConfiguration {\n\tb.CIDR = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100023622,"name":"WithExcept","signature":"func (b *IPBlockApplyConfiguration) WithExcept(values ...string) *IPBlockApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/ipblock.go","code":"// WithExcept adds the given value to the Except field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Except field.\nfunc (b *IPBlockApplyConfiguration) WithExcept(values ...string) *IPBlockApplyConfiguration {\n\tfor i := range values {\n\t\tb.Except = append(b.Except, values[i])\n\t}\n\treturn b\n}","line":{"from":42,"to":50}} {"id":100023623,"name":"NetworkPolicy","signature":"func NetworkPolicy(name, namespace string) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicy.go","code":"// NetworkPolicy constructs an declarative configuration of the NetworkPolicy type for use with\n// apply.\nfunc NetworkPolicy(name, namespace string) *NetworkPolicyApplyConfiguration {\n\tb := \u0026NetworkPolicyApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"NetworkPolicy\")\n\tb.WithAPIVersion(\"networking.k8s.io/v1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100023624,"name":"ExtractNetworkPolicy","signature":"func ExtractNetworkPolicy(networkPolicy *apinetworkingv1.NetworkPolicy, fieldManager string) (*NetworkPolicyApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicy.go","code":"// ExtractNetworkPolicy extracts the applied configuration owned by fieldManager from\n// networkPolicy. If no managedFields are found in networkPolicy for fieldManager, a\n// NetworkPolicyApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// networkPolicy must be a unmodified NetworkPolicy API object that was retrieved from the Kubernetes API.\n// ExtractNetworkPolicy provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractNetworkPolicy(networkPolicy *apinetworkingv1.NetworkPolicy, fieldManager string) (*NetworkPolicyApplyConfiguration, error) {\n\treturn extractNetworkPolicy(networkPolicy, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100023625,"name":"ExtractNetworkPolicyStatus","signature":"func ExtractNetworkPolicyStatus(networkPolicy *apinetworkingv1.NetworkPolicy, fieldManager string) (*NetworkPolicyApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicy.go","code":"// ExtractNetworkPolicyStatus is the same as ExtractNetworkPolicy except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractNetworkPolicyStatus(networkPolicy *apinetworkingv1.NetworkPolicy, fieldManager string) (*NetworkPolicyApplyConfiguration, error) {\n\treturn extractNetworkPolicy(networkPolicy, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100023626,"name":"extractNetworkPolicy","signature":"func extractNetworkPolicy(networkPolicy *apinetworkingv1.NetworkPolicy, fieldManager string, subresource string) (*NetworkPolicyApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicy.go","code":"func extractNetworkPolicy(networkPolicy *apinetworkingv1.NetworkPolicy, fieldManager string, subresource string) (*NetworkPolicyApplyConfiguration, error) {\n\tb := \u0026NetworkPolicyApplyConfiguration{}\n\terr := managedfields.ExtractInto(networkPolicy, internal.Parser().Type(\"io.k8s.api.networking.v1.NetworkPolicy\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(networkPolicy.Name)\n\tb.WithNamespace(networkPolicy.Namespace)\n\n\tb.WithKind(\"NetworkPolicy\")\n\tb.WithAPIVersion(\"networking.k8s.io/v1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100023627,"name":"WithKind","signature":"func (b *NetworkPolicyApplyConfiguration) WithKind(value string) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicy.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *NetworkPolicyApplyConfiguration) WithKind(value string) *NetworkPolicyApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100023628,"name":"WithAPIVersion","signature":"func (b *NetworkPolicyApplyConfiguration) WithAPIVersion(value string) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicy.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *NetworkPolicyApplyConfiguration) WithAPIVersion(value string) *NetworkPolicyApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100023629,"name":"WithName","signature":"func (b *NetworkPolicyApplyConfiguration) WithName(value string) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicy.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *NetworkPolicyApplyConfiguration) WithName(value string) *NetworkPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100023630,"name":"WithGenerateName","signature":"func (b *NetworkPolicyApplyConfiguration) WithGenerateName(value string) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicy.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *NetworkPolicyApplyConfiguration) WithGenerateName(value string) *NetworkPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100023631,"name":"WithNamespace","signature":"func (b *NetworkPolicyApplyConfiguration) WithNamespace(value string) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicy.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *NetworkPolicyApplyConfiguration) WithNamespace(value string) *NetworkPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100023632,"name":"WithUID","signature":"func (b *NetworkPolicyApplyConfiguration) WithUID(value types.UID) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicy.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *NetworkPolicyApplyConfiguration) WithUID(value types.UID) *NetworkPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100023633,"name":"WithResourceVersion","signature":"func (b *NetworkPolicyApplyConfiguration) WithResourceVersion(value string) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicy.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *NetworkPolicyApplyConfiguration) WithResourceVersion(value string) *NetworkPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100023634,"name":"WithGeneration","signature":"func (b *NetworkPolicyApplyConfiguration) WithGeneration(value int64) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicy.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *NetworkPolicyApplyConfiguration) WithGeneration(value int64) *NetworkPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100023635,"name":"WithCreationTimestamp","signature":"func (b *NetworkPolicyApplyConfiguration) WithCreationTimestamp(value metav1.Time) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicy.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *NetworkPolicyApplyConfiguration) WithCreationTimestamp(value metav1.Time) *NetworkPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100023636,"name":"WithDeletionTimestamp","signature":"func (b *NetworkPolicyApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicy.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *NetworkPolicyApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *NetworkPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100023637,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *NetworkPolicyApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicy.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *NetworkPolicyApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *NetworkPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100023638,"name":"WithLabels","signature":"func (b *NetworkPolicyApplyConfiguration) WithLabels(entries map[string]string) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicy.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *NetworkPolicyApplyConfiguration) WithLabels(entries map[string]string) *NetworkPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100023639,"name":"WithAnnotations","signature":"func (b *NetworkPolicyApplyConfiguration) WithAnnotations(entries map[string]string) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicy.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *NetworkPolicyApplyConfiguration) WithAnnotations(entries map[string]string) *NetworkPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100023640,"name":"WithOwnerReferences","signature":"func (b *NetworkPolicyApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicy.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *NetworkPolicyApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *NetworkPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100023641,"name":"WithFinalizers","signature":"func (b *NetworkPolicyApplyConfiguration) WithFinalizers(values ...string) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicy.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *NetworkPolicyApplyConfiguration) WithFinalizers(values ...string) *NetworkPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100023642,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *NetworkPolicyApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicy.go","code":"func (b *NetworkPolicyApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100023643,"name":"WithSpec","signature":"func (b *NetworkPolicyApplyConfiguration) WithSpec(value *NetworkPolicySpecApplyConfiguration) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicy.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *NetworkPolicyApplyConfiguration) WithSpec(value *NetworkPolicySpecApplyConfiguration) *NetworkPolicyApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100023644,"name":"WithStatus","signature":"func (b *NetworkPolicyApplyConfiguration) WithStatus(value *NetworkPolicyStatusApplyConfiguration) *NetworkPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicy.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *NetworkPolicyApplyConfiguration) WithStatus(value *NetworkPolicyStatusApplyConfiguration) *NetworkPolicyApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100023645,"name":"NetworkPolicyEgressRule","signature":"func NetworkPolicyEgressRule() *NetworkPolicyEgressRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicyegressrule.go","code":"// NetworkPolicyEgressRuleApplyConfiguration constructs an declarative configuration of the NetworkPolicyEgressRule type for use with\n// apply.\nfunc NetworkPolicyEgressRule() *NetworkPolicyEgressRuleApplyConfiguration {\n\treturn \u0026NetworkPolicyEgressRuleApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100023646,"name":"WithPorts","signature":"func (b *NetworkPolicyEgressRuleApplyConfiguration) WithPorts(values ...*NetworkPolicyPortApplyConfiguration) *NetworkPolicyEgressRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicyegressrule.go","code":"// WithPorts adds the given value to the Ports field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Ports field.\nfunc (b *NetworkPolicyEgressRuleApplyConfiguration) WithPorts(values ...*NetworkPolicyPortApplyConfiguration) *NetworkPolicyEgressRuleApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPorts\")\n\t\t}\n\t\tb.Ports = append(b.Ports, *values[i])\n\t}\n\treturn b\n}","line":{"from":34,"to":45}} {"id":100023647,"name":"WithTo","signature":"func (b *NetworkPolicyEgressRuleApplyConfiguration) WithTo(values ...*NetworkPolicyPeerApplyConfiguration) *NetworkPolicyEgressRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicyegressrule.go","code":"// WithTo adds the given value to the To field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the To field.\nfunc (b *NetworkPolicyEgressRuleApplyConfiguration) WithTo(values ...*NetworkPolicyPeerApplyConfiguration) *NetworkPolicyEgressRuleApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithTo\")\n\t\t}\n\t\tb.To = append(b.To, *values[i])\n\t}\n\treturn b\n}","line":{"from":47,"to":58}} {"id":100023648,"name":"NetworkPolicyIngressRule","signature":"func NetworkPolicyIngressRule() *NetworkPolicyIngressRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicyingressrule.go","code":"// NetworkPolicyIngressRuleApplyConfiguration constructs an declarative configuration of the NetworkPolicyIngressRule type for use with\n// apply.\nfunc NetworkPolicyIngressRule() *NetworkPolicyIngressRuleApplyConfiguration {\n\treturn \u0026NetworkPolicyIngressRuleApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100023649,"name":"WithPorts","signature":"func (b *NetworkPolicyIngressRuleApplyConfiguration) WithPorts(values ...*NetworkPolicyPortApplyConfiguration) *NetworkPolicyIngressRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicyingressrule.go","code":"// WithPorts adds the given value to the Ports field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Ports field.\nfunc (b *NetworkPolicyIngressRuleApplyConfiguration) WithPorts(values ...*NetworkPolicyPortApplyConfiguration) *NetworkPolicyIngressRuleApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPorts\")\n\t\t}\n\t\tb.Ports = append(b.Ports, *values[i])\n\t}\n\treturn b\n}","line":{"from":34,"to":45}} {"id":100023650,"name":"WithFrom","signature":"func (b *NetworkPolicyIngressRuleApplyConfiguration) WithFrom(values ...*NetworkPolicyPeerApplyConfiguration) *NetworkPolicyIngressRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicyingressrule.go","code":"// WithFrom adds the given value to the From field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the From field.\nfunc (b *NetworkPolicyIngressRuleApplyConfiguration) WithFrom(values ...*NetworkPolicyPeerApplyConfiguration) *NetworkPolicyIngressRuleApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithFrom\")\n\t\t}\n\t\tb.From = append(b.From, *values[i])\n\t}\n\treturn b\n}","line":{"from":47,"to":58}} {"id":100023651,"name":"NetworkPolicyPeer","signature":"func NetworkPolicyPeer() *NetworkPolicyPeerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicypeer.go","code":"// NetworkPolicyPeerApplyConfiguration constructs an declarative configuration of the NetworkPolicyPeer type for use with\n// apply.\nfunc NetworkPolicyPeer() *NetworkPolicyPeerApplyConfiguration {\n\treturn \u0026NetworkPolicyPeerApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100023652,"name":"WithPodSelector","signature":"func (b *NetworkPolicyPeerApplyConfiguration) WithPodSelector(value *v1.LabelSelectorApplyConfiguration) *NetworkPolicyPeerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicypeer.go","code":"// WithPodSelector sets the PodSelector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PodSelector field is set to the value of the last call.\nfunc (b *NetworkPolicyPeerApplyConfiguration) WithPodSelector(value *v1.LabelSelectorApplyConfiguration) *NetworkPolicyPeerApplyConfiguration {\n\tb.PodSelector = value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100023653,"name":"WithNamespaceSelector","signature":"func (b *NetworkPolicyPeerApplyConfiguration) WithNamespaceSelector(value *v1.LabelSelectorApplyConfiguration) *NetworkPolicyPeerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicypeer.go","code":"// WithNamespaceSelector sets the NamespaceSelector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NamespaceSelector field is set to the value of the last call.\nfunc (b *NetworkPolicyPeerApplyConfiguration) WithNamespaceSelector(value *v1.LabelSelectorApplyConfiguration) *NetworkPolicyPeerApplyConfiguration {\n\tb.NamespaceSelector = value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100023654,"name":"WithIPBlock","signature":"func (b *NetworkPolicyPeerApplyConfiguration) WithIPBlock(value *IPBlockApplyConfiguration) *NetworkPolicyPeerApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicypeer.go","code":"// WithIPBlock sets the IPBlock field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the IPBlock field is set to the value of the last call.\nfunc (b *NetworkPolicyPeerApplyConfiguration) WithIPBlock(value *IPBlockApplyConfiguration) *NetworkPolicyPeerApplyConfiguration {\n\tb.IPBlock = value\n\treturn b\n}","line":{"from":55,"to":61}} {"id":100023655,"name":"NetworkPolicyPort","signature":"func NetworkPolicyPort() *NetworkPolicyPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicyport.go","code":"// NetworkPolicyPortApplyConfiguration constructs an declarative configuration of the NetworkPolicyPort type for use with\n// apply.\nfunc NetworkPolicyPort() *NetworkPolicyPortApplyConfiguration {\n\treturn \u0026NetworkPolicyPortApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100023656,"name":"WithProtocol","signature":"func (b *NetworkPolicyPortApplyConfiguration) WithProtocol(value v1.Protocol) *NetworkPolicyPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicyport.go","code":"// WithProtocol sets the Protocol field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Protocol field is set to the value of the last call.\nfunc (b *NetworkPolicyPortApplyConfiguration) WithProtocol(value v1.Protocol) *NetworkPolicyPortApplyConfiguration {\n\tb.Protocol = \u0026value\n\treturn b\n}","line":{"from":40,"to":46}} {"id":100023657,"name":"WithPort","signature":"func (b *NetworkPolicyPortApplyConfiguration) WithPort(value intstr.IntOrString) *NetworkPolicyPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicyport.go","code":"// WithPort sets the Port field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Port field is set to the value of the last call.\nfunc (b *NetworkPolicyPortApplyConfiguration) WithPort(value intstr.IntOrString) *NetworkPolicyPortApplyConfiguration {\n\tb.Port = \u0026value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100023658,"name":"WithEndPort","signature":"func (b *NetworkPolicyPortApplyConfiguration) WithEndPort(value int32) *NetworkPolicyPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicyport.go","code":"// WithEndPort sets the EndPort field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the EndPort field is set to the value of the last call.\nfunc (b *NetworkPolicyPortApplyConfiguration) WithEndPort(value int32) *NetworkPolicyPortApplyConfiguration {\n\tb.EndPort = \u0026value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100023659,"name":"NetworkPolicySpec","signature":"func NetworkPolicySpec() *NetworkPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicyspec.go","code":"// NetworkPolicySpecApplyConfiguration constructs an declarative configuration of the NetworkPolicySpec type for use with\n// apply.\nfunc NetworkPolicySpec() *NetworkPolicySpecApplyConfiguration {\n\treturn \u0026NetworkPolicySpecApplyConfiguration{}\n}","line":{"from":35,"to":39}} {"id":100023660,"name":"WithPodSelector","signature":"func (b *NetworkPolicySpecApplyConfiguration) WithPodSelector(value *v1.LabelSelectorApplyConfiguration) *NetworkPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicyspec.go","code":"// WithPodSelector sets the PodSelector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PodSelector field is set to the value of the last call.\nfunc (b *NetworkPolicySpecApplyConfiguration) WithPodSelector(value *v1.LabelSelectorApplyConfiguration) *NetworkPolicySpecApplyConfiguration {\n\tb.PodSelector = value\n\treturn b\n}","line":{"from":41,"to":47}} {"id":100023661,"name":"WithIngress","signature":"func (b *NetworkPolicySpecApplyConfiguration) WithIngress(values ...*NetworkPolicyIngressRuleApplyConfiguration) *NetworkPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicyspec.go","code":"// WithIngress adds the given value to the Ingress field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Ingress field.\nfunc (b *NetworkPolicySpecApplyConfiguration) WithIngress(values ...*NetworkPolicyIngressRuleApplyConfiguration) *NetworkPolicySpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithIngress\")\n\t\t}\n\t\tb.Ingress = append(b.Ingress, *values[i])\n\t}\n\treturn b\n}","line":{"from":49,"to":60}} {"id":100023662,"name":"WithEgress","signature":"func (b *NetworkPolicySpecApplyConfiguration) WithEgress(values ...*NetworkPolicyEgressRuleApplyConfiguration) *NetworkPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicyspec.go","code":"// WithEgress adds the given value to the Egress field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Egress field.\nfunc (b *NetworkPolicySpecApplyConfiguration) WithEgress(values ...*NetworkPolicyEgressRuleApplyConfiguration) *NetworkPolicySpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithEgress\")\n\t\t}\n\t\tb.Egress = append(b.Egress, *values[i])\n\t}\n\treturn b\n}","line":{"from":62,"to":73}} {"id":100023663,"name":"WithPolicyTypes","signature":"func (b *NetworkPolicySpecApplyConfiguration) WithPolicyTypes(values ...apinetworkingv1.PolicyType) *NetworkPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicyspec.go","code":"// WithPolicyTypes adds the given value to the PolicyTypes field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the PolicyTypes field.\nfunc (b *NetworkPolicySpecApplyConfiguration) WithPolicyTypes(values ...apinetworkingv1.PolicyType) *NetworkPolicySpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.PolicyTypes = append(b.PolicyTypes, values[i])\n\t}\n\treturn b\n}","line":{"from":75,"to":83}} {"id":100023664,"name":"NetworkPolicyStatus","signature":"func NetworkPolicyStatus() *NetworkPolicyStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicystatus.go","code":"// NetworkPolicyStatusApplyConfiguration constructs an declarative configuration of the NetworkPolicyStatus type for use with\n// apply.\nfunc NetworkPolicyStatus() *NetworkPolicyStatusApplyConfiguration {\n\treturn \u0026NetworkPolicyStatusApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100023665,"name":"WithConditions","signature":"func (b *NetworkPolicyStatusApplyConfiguration) WithConditions(values ...*v1.ConditionApplyConfiguration) *NetworkPolicyStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/networkpolicystatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *NetworkPolicyStatusApplyConfiguration) WithConditions(values ...*v1.ConditionApplyConfiguration) *NetworkPolicyStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":37,"to":48}} {"id":100023666,"name":"ServiceBackendPort","signature":"func ServiceBackendPort() *ServiceBackendPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/servicebackendport.go","code":"// ServiceBackendPortApplyConfiguration constructs an declarative configuration of the ServiceBackendPort type for use with\n// apply.\nfunc ServiceBackendPort() *ServiceBackendPortApplyConfiguration {\n\treturn \u0026ServiceBackendPortApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100023667,"name":"WithName","signature":"func (b *ServiceBackendPortApplyConfiguration) WithName(value string) *ServiceBackendPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/servicebackendport.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ServiceBackendPortApplyConfiguration) WithName(value string) *ServiceBackendPortApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100023668,"name":"WithNumber","signature":"func (b *ServiceBackendPortApplyConfiguration) WithNumber(value int32) *ServiceBackendPortApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1/servicebackendport.go","code":"// WithNumber sets the Number field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Number field is set to the value of the last call.\nfunc (b *ServiceBackendPortApplyConfiguration) WithNumber(value int32) *ServiceBackendPortApplyConfiguration {\n\tb.Number = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100023669,"name":"ClusterCIDR","signature":"func ClusterCIDR(name string) *ClusterCIDRApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/clustercidr.go","code":"// ClusterCIDR constructs an declarative configuration of the ClusterCIDR type for use with\n// apply.\nfunc ClusterCIDR(name string) *ClusterCIDRApplyConfiguration {\n\tb := \u0026ClusterCIDRApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"ClusterCIDR\")\n\tb.WithAPIVersion(\"networking.k8s.io/v1alpha1\")\n\treturn b\n}","line":{"from":38,"to":46}} {"id":100023670,"name":"ExtractClusterCIDR","signature":"func ExtractClusterCIDR(clusterCIDR *networkingv1alpha1.ClusterCIDR, fieldManager string) (*ClusterCIDRApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/clustercidr.go","code":"// ExtractClusterCIDR extracts the applied configuration owned by fieldManager from\n// clusterCIDR. If no managedFields are found in clusterCIDR for fieldManager, a\n// ClusterCIDRApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// clusterCIDR must be a unmodified ClusterCIDR API object that was retrieved from the Kubernetes API.\n// ExtractClusterCIDR provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractClusterCIDR(clusterCIDR *networkingv1alpha1.ClusterCIDR, fieldManager string) (*ClusterCIDRApplyConfiguration, error) {\n\treturn extractClusterCIDR(clusterCIDR, fieldManager, \"\")\n}","line":{"from":48,"to":61}} {"id":100023671,"name":"ExtractClusterCIDRStatus","signature":"func ExtractClusterCIDRStatus(clusterCIDR *networkingv1alpha1.ClusterCIDR, fieldManager string) (*ClusterCIDRApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/clustercidr.go","code":"// ExtractClusterCIDRStatus is the same as ExtractClusterCIDR except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractClusterCIDRStatus(clusterCIDR *networkingv1alpha1.ClusterCIDR, fieldManager string) (*ClusterCIDRApplyConfiguration, error) {\n\treturn extractClusterCIDR(clusterCIDR, fieldManager, \"status\")\n}","line":{"from":63,"to":68}} {"id":100023672,"name":"extractClusterCIDR","signature":"func extractClusterCIDR(clusterCIDR *networkingv1alpha1.ClusterCIDR, fieldManager string, subresource string) (*ClusterCIDRApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/clustercidr.go","code":"func extractClusterCIDR(clusterCIDR *networkingv1alpha1.ClusterCIDR, fieldManager string, subresource string) (*ClusterCIDRApplyConfiguration, error) {\n\tb := \u0026ClusterCIDRApplyConfiguration{}\n\terr := managedfields.ExtractInto(clusterCIDR, internal.Parser().Type(\"io.k8s.api.networking.v1alpha1.ClusterCIDR\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(clusterCIDR.Name)\n\n\tb.WithKind(\"ClusterCIDR\")\n\tb.WithAPIVersion(\"networking.k8s.io/v1alpha1\")\n\treturn b, nil\n}","line":{"from":70,"to":81}} {"id":100023673,"name":"WithKind","signature":"func (b *ClusterCIDRApplyConfiguration) WithKind(value string) *ClusterCIDRApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/clustercidr.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ClusterCIDRApplyConfiguration) WithKind(value string) *ClusterCIDRApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100023674,"name":"WithAPIVersion","signature":"func (b *ClusterCIDRApplyConfiguration) WithAPIVersion(value string) *ClusterCIDRApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/clustercidr.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ClusterCIDRApplyConfiguration) WithAPIVersion(value string) *ClusterCIDRApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":91,"to":97}} {"id":100023675,"name":"WithName","signature":"func (b *ClusterCIDRApplyConfiguration) WithName(value string) *ClusterCIDRApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/clustercidr.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ClusterCIDRApplyConfiguration) WithName(value string) *ClusterCIDRApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":99,"to":106}} {"id":100023676,"name":"WithGenerateName","signature":"func (b *ClusterCIDRApplyConfiguration) WithGenerateName(value string) *ClusterCIDRApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/clustercidr.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ClusterCIDRApplyConfiguration) WithGenerateName(value string) *ClusterCIDRApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":108,"to":115}} {"id":100023677,"name":"WithNamespace","signature":"func (b *ClusterCIDRApplyConfiguration) WithNamespace(value string) *ClusterCIDRApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/clustercidr.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ClusterCIDRApplyConfiguration) WithNamespace(value string) *ClusterCIDRApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":117,"to":124}} {"id":100023678,"name":"WithUID","signature":"func (b *ClusterCIDRApplyConfiguration) WithUID(value types.UID) *ClusterCIDRApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/clustercidr.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ClusterCIDRApplyConfiguration) WithUID(value types.UID) *ClusterCIDRApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":126,"to":133}} {"id":100023679,"name":"WithResourceVersion","signature":"func (b *ClusterCIDRApplyConfiguration) WithResourceVersion(value string) *ClusterCIDRApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/clustercidr.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ClusterCIDRApplyConfiguration) WithResourceVersion(value string) *ClusterCIDRApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":135,"to":142}} {"id":100023680,"name":"WithGeneration","signature":"func (b *ClusterCIDRApplyConfiguration) WithGeneration(value int64) *ClusterCIDRApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/clustercidr.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ClusterCIDRApplyConfiguration) WithGeneration(value int64) *ClusterCIDRApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":144,"to":151}} {"id":100023681,"name":"WithCreationTimestamp","signature":"func (b *ClusterCIDRApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ClusterCIDRApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/clustercidr.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ClusterCIDRApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ClusterCIDRApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":153,"to":160}} {"id":100023682,"name":"WithDeletionTimestamp","signature":"func (b *ClusterCIDRApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ClusterCIDRApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/clustercidr.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ClusterCIDRApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ClusterCIDRApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":162,"to":169}} {"id":100023683,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ClusterCIDRApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ClusterCIDRApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/clustercidr.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ClusterCIDRApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ClusterCIDRApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":171,"to":178}} {"id":100023684,"name":"WithLabels","signature":"func (b *ClusterCIDRApplyConfiguration) WithLabels(entries map[string]string) *ClusterCIDRApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/clustercidr.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ClusterCIDRApplyConfiguration) WithLabels(entries map[string]string) *ClusterCIDRApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":180,"to":193}} {"id":100023685,"name":"WithAnnotations","signature":"func (b *ClusterCIDRApplyConfiguration) WithAnnotations(entries map[string]string) *ClusterCIDRApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/clustercidr.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ClusterCIDRApplyConfiguration) WithAnnotations(entries map[string]string) *ClusterCIDRApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":195,"to":208}} {"id":100023686,"name":"WithOwnerReferences","signature":"func (b *ClusterCIDRApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ClusterCIDRApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/clustercidr.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ClusterCIDRApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ClusterCIDRApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":210,"to":222}} {"id":100023687,"name":"WithFinalizers","signature":"func (b *ClusterCIDRApplyConfiguration) WithFinalizers(values ...string) *ClusterCIDRApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/clustercidr.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ClusterCIDRApplyConfiguration) WithFinalizers(values ...string) *ClusterCIDRApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":224,"to":233}} {"id":100023688,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ClusterCIDRApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/clustercidr.go","code":"func (b *ClusterCIDRApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":235,"to":239}} {"id":100023689,"name":"WithSpec","signature":"func (b *ClusterCIDRApplyConfiguration) WithSpec(value *ClusterCIDRSpecApplyConfiguration) *ClusterCIDRApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/clustercidr.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *ClusterCIDRApplyConfiguration) WithSpec(value *ClusterCIDRSpecApplyConfiguration) *ClusterCIDRApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":241,"to":247}} {"id":100023690,"name":"ClusterCIDRSpec","signature":"func ClusterCIDRSpec() *ClusterCIDRSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/clustercidrspec.go","code":"// ClusterCIDRSpecApplyConfiguration constructs an declarative configuration of the ClusterCIDRSpec type for use with\n// apply.\nfunc ClusterCIDRSpec() *ClusterCIDRSpecApplyConfiguration {\n\treturn \u0026ClusterCIDRSpecApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100023691,"name":"WithNodeSelector","signature":"func (b *ClusterCIDRSpecApplyConfiguration) WithNodeSelector(value *v1.NodeSelectorApplyConfiguration) *ClusterCIDRSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/clustercidrspec.go","code":"// WithNodeSelector sets the NodeSelector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NodeSelector field is set to the value of the last call.\nfunc (b *ClusterCIDRSpecApplyConfiguration) WithNodeSelector(value *v1.NodeSelectorApplyConfiguration) *ClusterCIDRSpecApplyConfiguration {\n\tb.NodeSelector = value\n\treturn b\n}","line":{"from":40,"to":46}} {"id":100023692,"name":"WithPerNodeHostBits","signature":"func (b *ClusterCIDRSpecApplyConfiguration) WithPerNodeHostBits(value int32) *ClusterCIDRSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/clustercidrspec.go","code":"// WithPerNodeHostBits sets the PerNodeHostBits field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PerNodeHostBits field is set to the value of the last call.\nfunc (b *ClusterCIDRSpecApplyConfiguration) WithPerNodeHostBits(value int32) *ClusterCIDRSpecApplyConfiguration {\n\tb.PerNodeHostBits = \u0026value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100023693,"name":"WithIPv4","signature":"func (b *ClusterCIDRSpecApplyConfiguration) WithIPv4(value string) *ClusterCIDRSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/clustercidrspec.go","code":"// WithIPv4 sets the IPv4 field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the IPv4 field is set to the value of the last call.\nfunc (b *ClusterCIDRSpecApplyConfiguration) WithIPv4(value string) *ClusterCIDRSpecApplyConfiguration {\n\tb.IPv4 = \u0026value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100023694,"name":"WithIPv6","signature":"func (b *ClusterCIDRSpecApplyConfiguration) WithIPv6(value string) *ClusterCIDRSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/clustercidrspec.go","code":"// WithIPv6 sets the IPv6 field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the IPv6 field is set to the value of the last call.\nfunc (b *ClusterCIDRSpecApplyConfiguration) WithIPv6(value string) *ClusterCIDRSpecApplyConfiguration {\n\tb.IPv6 = \u0026value\n\treturn b\n}","line":{"from":64,"to":70}} {"id":100023695,"name":"IPAddress","signature":"func IPAddress(name string) *IPAddressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/ipaddress.go","code":"// IPAddress constructs an declarative configuration of the IPAddress type for use with\n// apply.\nfunc IPAddress(name string) *IPAddressApplyConfiguration {\n\tb := \u0026IPAddressApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"IPAddress\")\n\tb.WithAPIVersion(\"networking.k8s.io/v1alpha1\")\n\treturn b\n}","line":{"from":38,"to":46}} {"id":100023696,"name":"ExtractIPAddress","signature":"func ExtractIPAddress(iPAddress *networkingv1alpha1.IPAddress, fieldManager string) (*IPAddressApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/ipaddress.go","code":"// ExtractIPAddress extracts the applied configuration owned by fieldManager from\n// iPAddress. If no managedFields are found in iPAddress for fieldManager, a\n// IPAddressApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// iPAddress must be a unmodified IPAddress API object that was retrieved from the Kubernetes API.\n// ExtractIPAddress provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractIPAddress(iPAddress *networkingv1alpha1.IPAddress, fieldManager string) (*IPAddressApplyConfiguration, error) {\n\treturn extractIPAddress(iPAddress, fieldManager, \"\")\n}","line":{"from":48,"to":61}} {"id":100023697,"name":"ExtractIPAddressStatus","signature":"func ExtractIPAddressStatus(iPAddress *networkingv1alpha1.IPAddress, fieldManager string) (*IPAddressApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/ipaddress.go","code":"// ExtractIPAddressStatus is the same as ExtractIPAddress except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractIPAddressStatus(iPAddress *networkingv1alpha1.IPAddress, fieldManager string) (*IPAddressApplyConfiguration, error) {\n\treturn extractIPAddress(iPAddress, fieldManager, \"status\")\n}","line":{"from":63,"to":68}} {"id":100023698,"name":"extractIPAddress","signature":"func extractIPAddress(iPAddress *networkingv1alpha1.IPAddress, fieldManager string, subresource string) (*IPAddressApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/ipaddress.go","code":"func extractIPAddress(iPAddress *networkingv1alpha1.IPAddress, fieldManager string, subresource string) (*IPAddressApplyConfiguration, error) {\n\tb := \u0026IPAddressApplyConfiguration{}\n\terr := managedfields.ExtractInto(iPAddress, internal.Parser().Type(\"io.k8s.api.networking.v1alpha1.IPAddress\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(iPAddress.Name)\n\n\tb.WithKind(\"IPAddress\")\n\tb.WithAPIVersion(\"networking.k8s.io/v1alpha1\")\n\treturn b, nil\n}","line":{"from":70,"to":81}} {"id":100023699,"name":"WithKind","signature":"func (b *IPAddressApplyConfiguration) WithKind(value string) *IPAddressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/ipaddress.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *IPAddressApplyConfiguration) WithKind(value string) *IPAddressApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100023700,"name":"WithAPIVersion","signature":"func (b *IPAddressApplyConfiguration) WithAPIVersion(value string) *IPAddressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/ipaddress.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *IPAddressApplyConfiguration) WithAPIVersion(value string) *IPAddressApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":91,"to":97}} {"id":100023701,"name":"WithName","signature":"func (b *IPAddressApplyConfiguration) WithName(value string) *IPAddressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/ipaddress.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *IPAddressApplyConfiguration) WithName(value string) *IPAddressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":99,"to":106}} {"id":100023702,"name":"WithGenerateName","signature":"func (b *IPAddressApplyConfiguration) WithGenerateName(value string) *IPAddressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/ipaddress.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *IPAddressApplyConfiguration) WithGenerateName(value string) *IPAddressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":108,"to":115}} {"id":100023703,"name":"WithNamespace","signature":"func (b *IPAddressApplyConfiguration) WithNamespace(value string) *IPAddressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/ipaddress.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *IPAddressApplyConfiguration) WithNamespace(value string) *IPAddressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":117,"to":124}} {"id":100023704,"name":"WithUID","signature":"func (b *IPAddressApplyConfiguration) WithUID(value types.UID) *IPAddressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/ipaddress.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *IPAddressApplyConfiguration) WithUID(value types.UID) *IPAddressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":126,"to":133}} {"id":100023705,"name":"WithResourceVersion","signature":"func (b *IPAddressApplyConfiguration) WithResourceVersion(value string) *IPAddressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/ipaddress.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *IPAddressApplyConfiguration) WithResourceVersion(value string) *IPAddressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":135,"to":142}} {"id":100023706,"name":"WithGeneration","signature":"func (b *IPAddressApplyConfiguration) WithGeneration(value int64) *IPAddressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/ipaddress.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *IPAddressApplyConfiguration) WithGeneration(value int64) *IPAddressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":144,"to":151}} {"id":100023707,"name":"WithCreationTimestamp","signature":"func (b *IPAddressApplyConfiguration) WithCreationTimestamp(value metav1.Time) *IPAddressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/ipaddress.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *IPAddressApplyConfiguration) WithCreationTimestamp(value metav1.Time) *IPAddressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":153,"to":160}} {"id":100023708,"name":"WithDeletionTimestamp","signature":"func (b *IPAddressApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *IPAddressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/ipaddress.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *IPAddressApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *IPAddressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":162,"to":169}} {"id":100023709,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *IPAddressApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *IPAddressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/ipaddress.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *IPAddressApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *IPAddressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":171,"to":178}} {"id":100023710,"name":"WithLabels","signature":"func (b *IPAddressApplyConfiguration) WithLabels(entries map[string]string) *IPAddressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/ipaddress.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *IPAddressApplyConfiguration) WithLabels(entries map[string]string) *IPAddressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":180,"to":193}} {"id":100023711,"name":"WithAnnotations","signature":"func (b *IPAddressApplyConfiguration) WithAnnotations(entries map[string]string) *IPAddressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/ipaddress.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *IPAddressApplyConfiguration) WithAnnotations(entries map[string]string) *IPAddressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":195,"to":208}} {"id":100023712,"name":"WithOwnerReferences","signature":"func (b *IPAddressApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *IPAddressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/ipaddress.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *IPAddressApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *IPAddressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":210,"to":222}} {"id":100023713,"name":"WithFinalizers","signature":"func (b *IPAddressApplyConfiguration) WithFinalizers(values ...string) *IPAddressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/ipaddress.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *IPAddressApplyConfiguration) WithFinalizers(values ...string) *IPAddressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":224,"to":233}} {"id":100023714,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *IPAddressApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/ipaddress.go","code":"func (b *IPAddressApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":235,"to":239}} {"id":100023715,"name":"WithSpec","signature":"func (b *IPAddressApplyConfiguration) WithSpec(value *IPAddressSpecApplyConfiguration) *IPAddressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/ipaddress.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *IPAddressApplyConfiguration) WithSpec(value *IPAddressSpecApplyConfiguration) *IPAddressApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":241,"to":247}} {"id":100023716,"name":"IPAddressSpec","signature":"func IPAddressSpec() *IPAddressSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/ipaddressspec.go","code":"// IPAddressSpecApplyConfiguration constructs an declarative configuration of the IPAddressSpec type for use with\n// apply.\nfunc IPAddressSpec() *IPAddressSpecApplyConfiguration {\n\treturn \u0026IPAddressSpecApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023717,"name":"WithParentRef","signature":"func (b *IPAddressSpecApplyConfiguration) WithParentRef(value *ParentReferenceApplyConfiguration) *IPAddressSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/ipaddressspec.go","code":"// WithParentRef sets the ParentRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ParentRef field is set to the value of the last call.\nfunc (b *IPAddressSpecApplyConfiguration) WithParentRef(value *ParentReferenceApplyConfiguration) *IPAddressSpecApplyConfiguration {\n\tb.ParentRef = value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100023718,"name":"ParentReference","signature":"func ParentReference() *ParentReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/parentreference.go","code":"// ParentReferenceApplyConfiguration constructs an declarative configuration of the ParentReference type for use with\n// apply.\nfunc ParentReference() *ParentReferenceApplyConfiguration {\n\treturn \u0026ParentReferenceApplyConfiguration{}\n}","line":{"from":35,"to":39}} {"id":100023719,"name":"WithGroup","signature":"func (b *ParentReferenceApplyConfiguration) WithGroup(value string) *ParentReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/parentreference.go","code":"// WithGroup sets the Group field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Group field is set to the value of the last call.\nfunc (b *ParentReferenceApplyConfiguration) WithGroup(value string) *ParentReferenceApplyConfiguration {\n\tb.Group = \u0026value\n\treturn b\n}","line":{"from":41,"to":47}} {"id":100023720,"name":"WithResource","signature":"func (b *ParentReferenceApplyConfiguration) WithResource(value string) *ParentReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/parentreference.go","code":"// WithResource sets the Resource field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Resource field is set to the value of the last call.\nfunc (b *ParentReferenceApplyConfiguration) WithResource(value string) *ParentReferenceApplyConfiguration {\n\tb.Resource = \u0026value\n\treturn b\n}","line":{"from":49,"to":55}} {"id":100023721,"name":"WithNamespace","signature":"func (b *ParentReferenceApplyConfiguration) WithNamespace(value string) *ParentReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/parentreference.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ParentReferenceApplyConfiguration) WithNamespace(value string) *ParentReferenceApplyConfiguration {\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":57,"to":63}} {"id":100023722,"name":"WithName","signature":"func (b *ParentReferenceApplyConfiguration) WithName(value string) *ParentReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/parentreference.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ParentReferenceApplyConfiguration) WithName(value string) *ParentReferenceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":65,"to":71}} {"id":100023723,"name":"WithUID","signature":"func (b *ParentReferenceApplyConfiguration) WithUID(value types.UID) *ParentReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1alpha1/parentreference.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ParentReferenceApplyConfiguration) WithUID(value types.UID) *ParentReferenceApplyConfiguration {\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":73,"to":79}} {"id":100023724,"name":"HTTPIngressPath","signature":"func HTTPIngressPath() *HTTPIngressPathApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/httpingresspath.go","code":"// HTTPIngressPathApplyConfiguration constructs an declarative configuration of the HTTPIngressPath type for use with\n// apply.\nfunc HTTPIngressPath() *HTTPIngressPathApplyConfiguration {\n\treturn \u0026HTTPIngressPathApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100023725,"name":"WithPath","signature":"func (b *HTTPIngressPathApplyConfiguration) WithPath(value string) *HTTPIngressPathApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/httpingresspath.go","code":"// WithPath sets the Path field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Path field is set to the value of the last call.\nfunc (b *HTTPIngressPathApplyConfiguration) WithPath(value string) *HTTPIngressPathApplyConfiguration {\n\tb.Path = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100023726,"name":"WithPathType","signature":"func (b *HTTPIngressPathApplyConfiguration) WithPathType(value v1beta1.PathType) *HTTPIngressPathApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/httpingresspath.go","code":"// WithPathType sets the PathType field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PathType field is set to the value of the last call.\nfunc (b *HTTPIngressPathApplyConfiguration) WithPathType(value v1beta1.PathType) *HTTPIngressPathApplyConfiguration {\n\tb.PathType = \u0026value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100023727,"name":"WithBackend","signature":"func (b *HTTPIngressPathApplyConfiguration) WithBackend(value *IngressBackendApplyConfiguration) *HTTPIngressPathApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/httpingresspath.go","code":"// WithBackend sets the Backend field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Backend field is set to the value of the last call.\nfunc (b *HTTPIngressPathApplyConfiguration) WithBackend(value *IngressBackendApplyConfiguration) *HTTPIngressPathApplyConfiguration {\n\tb.Backend = value\n\treturn b\n}","line":{"from":55,"to":61}} {"id":100023728,"name":"HTTPIngressRuleValue","signature":"func HTTPIngressRuleValue() *HTTPIngressRuleValueApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/httpingressrulevalue.go","code":"// HTTPIngressRuleValueApplyConfiguration constructs an declarative configuration of the HTTPIngressRuleValue type for use with\n// apply.\nfunc HTTPIngressRuleValue() *HTTPIngressRuleValueApplyConfiguration {\n\treturn \u0026HTTPIngressRuleValueApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023729,"name":"WithPaths","signature":"func (b *HTTPIngressRuleValueApplyConfiguration) WithPaths(values ...*HTTPIngressPathApplyConfiguration) *HTTPIngressRuleValueApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/httpingressrulevalue.go","code":"// WithPaths adds the given value to the Paths field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Paths field.\nfunc (b *HTTPIngressRuleValueApplyConfiguration) WithPaths(values ...*HTTPIngressPathApplyConfiguration) *HTTPIngressRuleValueApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPaths\")\n\t\t}\n\t\tb.Paths = append(b.Paths, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100023730,"name":"Ingress","signature":"func Ingress(name, namespace string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingress.go","code":"// Ingress constructs an declarative configuration of the Ingress type for use with\n// apply.\nfunc Ingress(name, namespace string) *IngressApplyConfiguration {\n\tb := \u0026IngressApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"Ingress\")\n\tb.WithAPIVersion(\"networking.k8s.io/v1beta1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100023731,"name":"ExtractIngress","signature":"func ExtractIngress(ingress *networkingv1beta1.Ingress, fieldManager string) (*IngressApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingress.go","code":"// ExtractIngress extracts the applied configuration owned by fieldManager from\n// ingress. If no managedFields are found in ingress for fieldManager, a\n// IngressApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// ingress must be a unmodified Ingress API object that was retrieved from the Kubernetes API.\n// ExtractIngress provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractIngress(ingress *networkingv1beta1.Ingress, fieldManager string) (*IngressApplyConfiguration, error) {\n\treturn extractIngress(ingress, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100023732,"name":"ExtractIngressStatus","signature":"func ExtractIngressStatus(ingress *networkingv1beta1.Ingress, fieldManager string) (*IngressApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingress.go","code":"// ExtractIngressStatus is the same as ExtractIngress except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractIngressStatus(ingress *networkingv1beta1.Ingress, fieldManager string) (*IngressApplyConfiguration, error) {\n\treturn extractIngress(ingress, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100023733,"name":"extractIngress","signature":"func extractIngress(ingress *networkingv1beta1.Ingress, fieldManager string, subresource string) (*IngressApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingress.go","code":"func extractIngress(ingress *networkingv1beta1.Ingress, fieldManager string, subresource string) (*IngressApplyConfiguration, error) {\n\tb := \u0026IngressApplyConfiguration{}\n\terr := managedfields.ExtractInto(ingress, internal.Parser().Type(\"io.k8s.api.networking.v1beta1.Ingress\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(ingress.Name)\n\tb.WithNamespace(ingress.Namespace)\n\n\tb.WithKind(\"Ingress\")\n\tb.WithAPIVersion(\"networking.k8s.io/v1beta1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100023734,"name":"WithKind","signature":"func (b *IngressApplyConfiguration) WithKind(value string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingress.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithKind(value string) *IngressApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100023735,"name":"WithAPIVersion","signature":"func (b *IngressApplyConfiguration) WithAPIVersion(value string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingress.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithAPIVersion(value string) *IngressApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100023736,"name":"WithName","signature":"func (b *IngressApplyConfiguration) WithName(value string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingress.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithName(value string) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100023737,"name":"WithGenerateName","signature":"func (b *IngressApplyConfiguration) WithGenerateName(value string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingress.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithGenerateName(value string) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100023738,"name":"WithNamespace","signature":"func (b *IngressApplyConfiguration) WithNamespace(value string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingress.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithNamespace(value string) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100023739,"name":"WithUID","signature":"func (b *IngressApplyConfiguration) WithUID(value types.UID) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingress.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithUID(value types.UID) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100023740,"name":"WithResourceVersion","signature":"func (b *IngressApplyConfiguration) WithResourceVersion(value string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingress.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithResourceVersion(value string) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100023741,"name":"WithGeneration","signature":"func (b *IngressApplyConfiguration) WithGeneration(value int64) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingress.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithGeneration(value int64) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100023742,"name":"WithCreationTimestamp","signature":"func (b *IngressApplyConfiguration) WithCreationTimestamp(value metav1.Time) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingress.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithCreationTimestamp(value metav1.Time) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100023743,"name":"WithDeletionTimestamp","signature":"func (b *IngressApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingress.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100023744,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *IngressApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingress.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100023745,"name":"WithLabels","signature":"func (b *IngressApplyConfiguration) WithLabels(entries map[string]string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingress.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *IngressApplyConfiguration) WithLabels(entries map[string]string) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100023746,"name":"WithAnnotations","signature":"func (b *IngressApplyConfiguration) WithAnnotations(entries map[string]string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingress.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *IngressApplyConfiguration) WithAnnotations(entries map[string]string) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100023747,"name":"WithOwnerReferences","signature":"func (b *IngressApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingress.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *IngressApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100023748,"name":"WithFinalizers","signature":"func (b *IngressApplyConfiguration) WithFinalizers(values ...string) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingress.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *IngressApplyConfiguration) WithFinalizers(values ...string) *IngressApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100023749,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *IngressApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingress.go","code":"func (b *IngressApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100023750,"name":"WithSpec","signature":"func (b *IngressApplyConfiguration) WithSpec(value *IngressSpecApplyConfiguration) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingress.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithSpec(value *IngressSpecApplyConfiguration) *IngressApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100023751,"name":"WithStatus","signature":"func (b *IngressApplyConfiguration) WithStatus(value *IngressStatusApplyConfiguration) *IngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingress.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *IngressApplyConfiguration) WithStatus(value *IngressStatusApplyConfiguration) *IngressApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100023752,"name":"IngressBackend","signature":"func IngressBackend() *IngressBackendApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressbackend.go","code":"// IngressBackendApplyConfiguration constructs an declarative configuration of the IngressBackend type for use with\n// apply.\nfunc IngressBackend() *IngressBackendApplyConfiguration {\n\treturn \u0026IngressBackendApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100023753,"name":"WithServiceName","signature":"func (b *IngressBackendApplyConfiguration) WithServiceName(value string) *IngressBackendApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressbackend.go","code":"// WithServiceName sets the ServiceName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ServiceName field is set to the value of the last call.\nfunc (b *IngressBackendApplyConfiguration) WithServiceName(value string) *IngressBackendApplyConfiguration {\n\tb.ServiceName = \u0026value\n\treturn b\n}","line":{"from":40,"to":46}} {"id":100023754,"name":"WithServicePort","signature":"func (b *IngressBackendApplyConfiguration) WithServicePort(value intstr.IntOrString) *IngressBackendApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressbackend.go","code":"// WithServicePort sets the ServicePort field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ServicePort field is set to the value of the last call.\nfunc (b *IngressBackendApplyConfiguration) WithServicePort(value intstr.IntOrString) *IngressBackendApplyConfiguration {\n\tb.ServicePort = \u0026value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100023755,"name":"WithResource","signature":"func (b *IngressBackendApplyConfiguration) WithResource(value *v1.TypedLocalObjectReferenceApplyConfiguration) *IngressBackendApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressbackend.go","code":"// WithResource sets the Resource field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Resource field is set to the value of the last call.\nfunc (b *IngressBackendApplyConfiguration) WithResource(value *v1.TypedLocalObjectReferenceApplyConfiguration) *IngressBackendApplyConfiguration {\n\tb.Resource = value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100023756,"name":"IngressClass","signature":"func IngressClass(name string) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclass.go","code":"// IngressClass constructs an declarative configuration of the IngressClass type for use with\n// apply.\nfunc IngressClass(name string) *IngressClassApplyConfiguration {\n\tb := \u0026IngressClassApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"IngressClass\")\n\tb.WithAPIVersion(\"networking.k8s.io/v1beta1\")\n\treturn b\n}","line":{"from":38,"to":46}} {"id":100023757,"name":"ExtractIngressClass","signature":"func ExtractIngressClass(ingressClass *networkingv1beta1.IngressClass, fieldManager string) (*IngressClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclass.go","code":"// ExtractIngressClass extracts the applied configuration owned by fieldManager from\n// ingressClass. If no managedFields are found in ingressClass for fieldManager, a\n// IngressClassApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// ingressClass must be a unmodified IngressClass API object that was retrieved from the Kubernetes API.\n// ExtractIngressClass provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractIngressClass(ingressClass *networkingv1beta1.IngressClass, fieldManager string) (*IngressClassApplyConfiguration, error) {\n\treturn extractIngressClass(ingressClass, fieldManager, \"\")\n}","line":{"from":48,"to":61}} {"id":100023758,"name":"ExtractIngressClassStatus","signature":"func ExtractIngressClassStatus(ingressClass *networkingv1beta1.IngressClass, fieldManager string) (*IngressClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclass.go","code":"// ExtractIngressClassStatus is the same as ExtractIngressClass except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractIngressClassStatus(ingressClass *networkingv1beta1.IngressClass, fieldManager string) (*IngressClassApplyConfiguration, error) {\n\treturn extractIngressClass(ingressClass, fieldManager, \"status\")\n}","line":{"from":63,"to":68}} {"id":100023759,"name":"extractIngressClass","signature":"func extractIngressClass(ingressClass *networkingv1beta1.IngressClass, fieldManager string, subresource string) (*IngressClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclass.go","code":"func extractIngressClass(ingressClass *networkingv1beta1.IngressClass, fieldManager string, subresource string) (*IngressClassApplyConfiguration, error) {\n\tb := \u0026IngressClassApplyConfiguration{}\n\terr := managedfields.ExtractInto(ingressClass, internal.Parser().Type(\"io.k8s.api.networking.v1beta1.IngressClass\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(ingressClass.Name)\n\n\tb.WithKind(\"IngressClass\")\n\tb.WithAPIVersion(\"networking.k8s.io/v1beta1\")\n\treturn b, nil\n}","line":{"from":70,"to":81}} {"id":100023760,"name":"WithKind","signature":"func (b *IngressClassApplyConfiguration) WithKind(value string) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclass.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *IngressClassApplyConfiguration) WithKind(value string) *IngressClassApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100023761,"name":"WithAPIVersion","signature":"func (b *IngressClassApplyConfiguration) WithAPIVersion(value string) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclass.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *IngressClassApplyConfiguration) WithAPIVersion(value string) *IngressClassApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":91,"to":97}} {"id":100023762,"name":"WithName","signature":"func (b *IngressClassApplyConfiguration) WithName(value string) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclass.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *IngressClassApplyConfiguration) WithName(value string) *IngressClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":99,"to":106}} {"id":100023763,"name":"WithGenerateName","signature":"func (b *IngressClassApplyConfiguration) WithGenerateName(value string) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclass.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *IngressClassApplyConfiguration) WithGenerateName(value string) *IngressClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":108,"to":115}} {"id":100023764,"name":"WithNamespace","signature":"func (b *IngressClassApplyConfiguration) WithNamespace(value string) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclass.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *IngressClassApplyConfiguration) WithNamespace(value string) *IngressClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":117,"to":124}} {"id":100023765,"name":"WithUID","signature":"func (b *IngressClassApplyConfiguration) WithUID(value types.UID) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclass.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *IngressClassApplyConfiguration) WithUID(value types.UID) *IngressClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":126,"to":133}} {"id":100023766,"name":"WithResourceVersion","signature":"func (b *IngressClassApplyConfiguration) WithResourceVersion(value string) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclass.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *IngressClassApplyConfiguration) WithResourceVersion(value string) *IngressClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":135,"to":142}} {"id":100023767,"name":"WithGeneration","signature":"func (b *IngressClassApplyConfiguration) WithGeneration(value int64) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclass.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *IngressClassApplyConfiguration) WithGeneration(value int64) *IngressClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":144,"to":151}} {"id":100023768,"name":"WithCreationTimestamp","signature":"func (b *IngressClassApplyConfiguration) WithCreationTimestamp(value metav1.Time) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclass.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *IngressClassApplyConfiguration) WithCreationTimestamp(value metav1.Time) *IngressClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":153,"to":160}} {"id":100023769,"name":"WithDeletionTimestamp","signature":"func (b *IngressClassApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclass.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *IngressClassApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *IngressClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":162,"to":169}} {"id":100023770,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *IngressClassApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclass.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *IngressClassApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *IngressClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":171,"to":178}} {"id":100023771,"name":"WithLabels","signature":"func (b *IngressClassApplyConfiguration) WithLabels(entries map[string]string) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclass.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *IngressClassApplyConfiguration) WithLabels(entries map[string]string) *IngressClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":180,"to":193}} {"id":100023772,"name":"WithAnnotations","signature":"func (b *IngressClassApplyConfiguration) WithAnnotations(entries map[string]string) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclass.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *IngressClassApplyConfiguration) WithAnnotations(entries map[string]string) *IngressClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":195,"to":208}} {"id":100023773,"name":"WithOwnerReferences","signature":"func (b *IngressClassApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclass.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *IngressClassApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *IngressClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":210,"to":222}} {"id":100023774,"name":"WithFinalizers","signature":"func (b *IngressClassApplyConfiguration) WithFinalizers(values ...string) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclass.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *IngressClassApplyConfiguration) WithFinalizers(values ...string) *IngressClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":224,"to":233}} {"id":100023775,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *IngressClassApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclass.go","code":"func (b *IngressClassApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":235,"to":239}} {"id":100023776,"name":"WithSpec","signature":"func (b *IngressClassApplyConfiguration) WithSpec(value *IngressClassSpecApplyConfiguration) *IngressClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclass.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *IngressClassApplyConfiguration) WithSpec(value *IngressClassSpecApplyConfiguration) *IngressClassApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":241,"to":247}} {"id":100023777,"name":"IngressClassParametersReference","signature":"func IngressClassParametersReference() *IngressClassParametersReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclassparametersreference.go","code":"// IngressClassParametersReferenceApplyConfiguration constructs an declarative configuration of the IngressClassParametersReference type for use with\n// apply.\nfunc IngressClassParametersReference() *IngressClassParametersReferenceApplyConfiguration {\n\treturn \u0026IngressClassParametersReferenceApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100023778,"name":"WithAPIGroup","signature":"func (b *IngressClassParametersReferenceApplyConfiguration) WithAPIGroup(value string) *IngressClassParametersReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclassparametersreference.go","code":"// WithAPIGroup sets the APIGroup field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIGroup field is set to the value of the last call.\nfunc (b *IngressClassParametersReferenceApplyConfiguration) WithAPIGroup(value string) *IngressClassParametersReferenceApplyConfiguration {\n\tb.APIGroup = \u0026value\n\treturn b\n}","line":{"from":37,"to":43}} {"id":100023779,"name":"WithKind","signature":"func (b *IngressClassParametersReferenceApplyConfiguration) WithKind(value string) *IngressClassParametersReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclassparametersreference.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *IngressClassParametersReferenceApplyConfiguration) WithKind(value string) *IngressClassParametersReferenceApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":45,"to":51}} {"id":100023780,"name":"WithName","signature":"func (b *IngressClassParametersReferenceApplyConfiguration) WithName(value string) *IngressClassParametersReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclassparametersreference.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *IngressClassParametersReferenceApplyConfiguration) WithName(value string) *IngressClassParametersReferenceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":53,"to":59}} {"id":100023781,"name":"WithScope","signature":"func (b *IngressClassParametersReferenceApplyConfiguration) WithScope(value string) *IngressClassParametersReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclassparametersreference.go","code":"// WithScope sets the Scope field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Scope field is set to the value of the last call.\nfunc (b *IngressClassParametersReferenceApplyConfiguration) WithScope(value string) *IngressClassParametersReferenceApplyConfiguration {\n\tb.Scope = \u0026value\n\treturn b\n}","line":{"from":61,"to":67}} {"id":100023782,"name":"WithNamespace","signature":"func (b *IngressClassParametersReferenceApplyConfiguration) WithNamespace(value string) *IngressClassParametersReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclassparametersreference.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *IngressClassParametersReferenceApplyConfiguration) WithNamespace(value string) *IngressClassParametersReferenceApplyConfiguration {\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":69,"to":75}} {"id":100023783,"name":"IngressClassSpec","signature":"func IngressClassSpec() *IngressClassSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclassspec.go","code":"// IngressClassSpecApplyConfiguration constructs an declarative configuration of the IngressClassSpec type for use with\n// apply.\nfunc IngressClassSpec() *IngressClassSpecApplyConfiguration {\n\treturn \u0026IngressClassSpecApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100023784,"name":"WithController","signature":"func (b *IngressClassSpecApplyConfiguration) WithController(value string) *IngressClassSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclassspec.go","code":"// WithController sets the Controller field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Controller field is set to the value of the last call.\nfunc (b *IngressClassSpecApplyConfiguration) WithController(value string) *IngressClassSpecApplyConfiguration {\n\tb.Controller = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100023785,"name":"WithParameters","signature":"func (b *IngressClassSpecApplyConfiguration) WithParameters(value *IngressClassParametersReferenceApplyConfiguration) *IngressClassSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressclassspec.go","code":"// WithParameters sets the Parameters field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Parameters field is set to the value of the last call.\nfunc (b *IngressClassSpecApplyConfiguration) WithParameters(value *IngressClassParametersReferenceApplyConfiguration) *IngressClassSpecApplyConfiguration {\n\tb.Parameters = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100023786,"name":"IngressLoadBalancerIngress","signature":"func IngressLoadBalancerIngress() *IngressLoadBalancerIngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressloadbalanceringress.go","code":"// IngressLoadBalancerIngressApplyConfiguration constructs an declarative configuration of the IngressLoadBalancerIngress type for use with\n// apply.\nfunc IngressLoadBalancerIngress() *IngressLoadBalancerIngressApplyConfiguration {\n\treturn \u0026IngressLoadBalancerIngressApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100023787,"name":"WithIP","signature":"func (b *IngressLoadBalancerIngressApplyConfiguration) WithIP(value string) *IngressLoadBalancerIngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressloadbalanceringress.go","code":"// WithIP sets the IP field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the IP field is set to the value of the last call.\nfunc (b *IngressLoadBalancerIngressApplyConfiguration) WithIP(value string) *IngressLoadBalancerIngressApplyConfiguration {\n\tb.IP = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100023788,"name":"WithHostname","signature":"func (b *IngressLoadBalancerIngressApplyConfiguration) WithHostname(value string) *IngressLoadBalancerIngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressloadbalanceringress.go","code":"// WithHostname sets the Hostname field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Hostname field is set to the value of the last call.\nfunc (b *IngressLoadBalancerIngressApplyConfiguration) WithHostname(value string) *IngressLoadBalancerIngressApplyConfiguration {\n\tb.Hostname = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100023789,"name":"WithPorts","signature":"func (b *IngressLoadBalancerIngressApplyConfiguration) WithPorts(values ...*IngressPortStatusApplyConfiguration) *IngressLoadBalancerIngressApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressloadbalanceringress.go","code":"// WithPorts adds the given value to the Ports field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Ports field.\nfunc (b *IngressLoadBalancerIngressApplyConfiguration) WithPorts(values ...*IngressPortStatusApplyConfiguration) *IngressLoadBalancerIngressApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithPorts\")\n\t\t}\n\t\tb.Ports = append(b.Ports, *values[i])\n\t}\n\treturn b\n}","line":{"from":51,"to":62}} {"id":100023790,"name":"IngressLoadBalancerStatus","signature":"func IngressLoadBalancerStatus() *IngressLoadBalancerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressloadbalancerstatus.go","code":"// IngressLoadBalancerStatusApplyConfiguration constructs an declarative configuration of the IngressLoadBalancerStatus type for use with\n// apply.\nfunc IngressLoadBalancerStatus() *IngressLoadBalancerStatusApplyConfiguration {\n\treturn \u0026IngressLoadBalancerStatusApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023791,"name":"WithIngress","signature":"func (b *IngressLoadBalancerStatusApplyConfiguration) WithIngress(values ...*IngressLoadBalancerIngressApplyConfiguration) *IngressLoadBalancerStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressloadbalancerstatus.go","code":"// WithIngress adds the given value to the Ingress field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Ingress field.\nfunc (b *IngressLoadBalancerStatusApplyConfiguration) WithIngress(values ...*IngressLoadBalancerIngressApplyConfiguration) *IngressLoadBalancerStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithIngress\")\n\t\t}\n\t\tb.Ingress = append(b.Ingress, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100023792,"name":"IngressPortStatus","signature":"func IngressPortStatus() *IngressPortStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressportstatus.go","code":"// IngressPortStatusApplyConfiguration constructs an declarative configuration of the IngressPortStatus type for use with\n// apply.\nfunc IngressPortStatus() *IngressPortStatusApplyConfiguration {\n\treturn \u0026IngressPortStatusApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100023793,"name":"WithPort","signature":"func (b *IngressPortStatusApplyConfiguration) WithPort(value int32) *IngressPortStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressportstatus.go","code":"// WithPort sets the Port field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Port field is set to the value of the last call.\nfunc (b *IngressPortStatusApplyConfiguration) WithPort(value int32) *IngressPortStatusApplyConfiguration {\n\tb.Port = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100023794,"name":"WithProtocol","signature":"func (b *IngressPortStatusApplyConfiguration) WithProtocol(value v1.Protocol) *IngressPortStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressportstatus.go","code":"// WithProtocol sets the Protocol field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Protocol field is set to the value of the last call.\nfunc (b *IngressPortStatusApplyConfiguration) WithProtocol(value v1.Protocol) *IngressPortStatusApplyConfiguration {\n\tb.Protocol = \u0026value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100023795,"name":"WithError","signature":"func (b *IngressPortStatusApplyConfiguration) WithError(value string) *IngressPortStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressportstatus.go","code":"// WithError sets the Error field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Error field is set to the value of the last call.\nfunc (b *IngressPortStatusApplyConfiguration) WithError(value string) *IngressPortStatusApplyConfiguration {\n\tb.Error = \u0026value\n\treturn b\n}","line":{"from":55,"to":61}} {"id":100023796,"name":"IngressRule","signature":"func IngressRule() *IngressRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressrule.go","code":"// IngressRuleApplyConfiguration constructs an declarative configuration of the IngressRule type for use with\n// apply.\nfunc IngressRule() *IngressRuleApplyConfiguration {\n\treturn \u0026IngressRuleApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100023797,"name":"WithHost","signature":"func (b *IngressRuleApplyConfiguration) WithHost(value string) *IngressRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressrule.go","code":"// WithHost sets the Host field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Host field is set to the value of the last call.\nfunc (b *IngressRuleApplyConfiguration) WithHost(value string) *IngressRuleApplyConfiguration {\n\tb.Host = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100023798,"name":"WithHTTP","signature":"func (b *IngressRuleApplyConfiguration) WithHTTP(value *HTTPIngressRuleValueApplyConfiguration) *IngressRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressrule.go","code":"// WithHTTP sets the HTTP field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HTTP field is set to the value of the last call.\nfunc (b *IngressRuleApplyConfiguration) WithHTTP(value *HTTPIngressRuleValueApplyConfiguration) *IngressRuleApplyConfiguration {\n\tb.HTTP = value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100023799,"name":"IngressRuleValue","signature":"func IngressRuleValue() *IngressRuleValueApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressrulevalue.go","code":"// IngressRuleValueApplyConfiguration constructs an declarative configuration of the IngressRuleValue type for use with\n// apply.\nfunc IngressRuleValue() *IngressRuleValueApplyConfiguration {\n\treturn \u0026IngressRuleValueApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023800,"name":"WithHTTP","signature":"func (b *IngressRuleValueApplyConfiguration) WithHTTP(value *HTTPIngressRuleValueApplyConfiguration) *IngressRuleValueApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressrulevalue.go","code":"// WithHTTP sets the HTTP field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HTTP field is set to the value of the last call.\nfunc (b *IngressRuleValueApplyConfiguration) WithHTTP(value *HTTPIngressRuleValueApplyConfiguration) *IngressRuleValueApplyConfiguration {\n\tb.HTTP = value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100023801,"name":"IngressSpec","signature":"func IngressSpec() *IngressSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressspec.go","code":"// IngressSpecApplyConfiguration constructs an declarative configuration of the IngressSpec type for use with\n// apply.\nfunc IngressSpec() *IngressSpecApplyConfiguration {\n\treturn \u0026IngressSpecApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100023802,"name":"WithIngressClassName","signature":"func (b *IngressSpecApplyConfiguration) WithIngressClassName(value string) *IngressSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressspec.go","code":"// WithIngressClassName sets the IngressClassName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the IngressClassName field is set to the value of the last call.\nfunc (b *IngressSpecApplyConfiguration) WithIngressClassName(value string) *IngressSpecApplyConfiguration {\n\tb.IngressClassName = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100023803,"name":"WithBackend","signature":"func (b *IngressSpecApplyConfiguration) WithBackend(value *IngressBackendApplyConfiguration) *IngressSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressspec.go","code":"// WithBackend sets the Backend field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Backend field is set to the value of the last call.\nfunc (b *IngressSpecApplyConfiguration) WithBackend(value *IngressBackendApplyConfiguration) *IngressSpecApplyConfiguration {\n\tb.Backend = value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100023804,"name":"WithTLS","signature":"func (b *IngressSpecApplyConfiguration) WithTLS(values ...*IngressTLSApplyConfiguration) *IngressSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressspec.go","code":"// WithTLS adds the given value to the TLS field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the TLS field.\nfunc (b *IngressSpecApplyConfiguration) WithTLS(values ...*IngressTLSApplyConfiguration) *IngressSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithTLS\")\n\t\t}\n\t\tb.TLS = append(b.TLS, *values[i])\n\t}\n\treturn b\n}","line":{"from":52,"to":63}} {"id":100023805,"name":"WithRules","signature":"func (b *IngressSpecApplyConfiguration) WithRules(values ...*IngressRuleApplyConfiguration) *IngressSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressspec.go","code":"// WithRules adds the given value to the Rules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Rules field.\nfunc (b *IngressSpecApplyConfiguration) WithRules(values ...*IngressRuleApplyConfiguration) *IngressSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRules\")\n\t\t}\n\t\tb.Rules = append(b.Rules, *values[i])\n\t}\n\treturn b\n}","line":{"from":65,"to":76}} {"id":100023806,"name":"IngressStatus","signature":"func IngressStatus() *IngressStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressstatus.go","code":"// IngressStatusApplyConfiguration constructs an declarative configuration of the IngressStatus type for use with\n// apply.\nfunc IngressStatus() *IngressStatusApplyConfiguration {\n\treturn \u0026IngressStatusApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023807,"name":"WithLoadBalancer","signature":"func (b *IngressStatusApplyConfiguration) WithLoadBalancer(value *IngressLoadBalancerStatusApplyConfiguration) *IngressStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingressstatus.go","code":"// WithLoadBalancer sets the LoadBalancer field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the LoadBalancer field is set to the value of the last call.\nfunc (b *IngressStatusApplyConfiguration) WithLoadBalancer(value *IngressLoadBalancerStatusApplyConfiguration) *IngressStatusApplyConfiguration {\n\tb.LoadBalancer = value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100023808,"name":"IngressTLS","signature":"func IngressTLS() *IngressTLSApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingresstls.go","code":"// IngressTLSApplyConfiguration constructs an declarative configuration of the IngressTLS type for use with\n// apply.\nfunc IngressTLS() *IngressTLSApplyConfiguration {\n\treturn \u0026IngressTLSApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100023809,"name":"WithHosts","signature":"func (b *IngressTLSApplyConfiguration) WithHosts(values ...string) *IngressTLSApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingresstls.go","code":"// WithHosts adds the given value to the Hosts field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Hosts field.\nfunc (b *IngressTLSApplyConfiguration) WithHosts(values ...string) *IngressTLSApplyConfiguration {\n\tfor i := range values {\n\t\tb.Hosts = append(b.Hosts, values[i])\n\t}\n\treturn b\n}","line":{"from":34,"to":42}} {"id":100023810,"name":"WithSecretName","signature":"func (b *IngressTLSApplyConfiguration) WithSecretName(value string) *IngressTLSApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/networking/v1beta1/ingresstls.go","code":"// WithSecretName sets the SecretName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SecretName field is set to the value of the last call.\nfunc (b *IngressTLSApplyConfiguration) WithSecretName(value string) *IngressTLSApplyConfiguration {\n\tb.SecretName = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100023811,"name":"Overhead","signature":"func Overhead() *OverheadApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/overhead.go","code":"// OverheadApplyConfiguration constructs an declarative configuration of the Overhead type for use with\n// apply.\nfunc Overhead() *OverheadApplyConfiguration {\n\treturn \u0026OverheadApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100023812,"name":"WithPodFixed","signature":"func (b *OverheadApplyConfiguration) WithPodFixed(value v1.ResourceList) *OverheadApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/overhead.go","code":"// WithPodFixed sets the PodFixed field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PodFixed field is set to the value of the last call.\nfunc (b *OverheadApplyConfiguration) WithPodFixed(value v1.ResourceList) *OverheadApplyConfiguration {\n\tb.PodFixed = \u0026value\n\treturn b\n}","line":{"from":37,"to":43}} {"id":100023813,"name":"RuntimeClass","signature":"func RuntimeClass(name string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go","code":"// RuntimeClass constructs an declarative configuration of the RuntimeClass type for use with\n// apply.\nfunc RuntimeClass(name string) *RuntimeClassApplyConfiguration {\n\tb := \u0026RuntimeClassApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"RuntimeClass\")\n\tb.WithAPIVersion(\"node.k8s.io/v1\")\n\treturn b\n}","line":{"from":40,"to":48}} {"id":100023814,"name":"ExtractRuntimeClass","signature":"func ExtractRuntimeClass(runtimeClass *apinodev1.RuntimeClass, fieldManager string) (*RuntimeClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go","code":"// ExtractRuntimeClass extracts the applied configuration owned by fieldManager from\n// runtimeClass. If no managedFields are found in runtimeClass for fieldManager, a\n// RuntimeClassApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// runtimeClass must be a unmodified RuntimeClass API object that was retrieved from the Kubernetes API.\n// ExtractRuntimeClass provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractRuntimeClass(runtimeClass *apinodev1.RuntimeClass, fieldManager string) (*RuntimeClassApplyConfiguration, error) {\n\treturn extractRuntimeClass(runtimeClass, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100023815,"name":"ExtractRuntimeClassStatus","signature":"func ExtractRuntimeClassStatus(runtimeClass *apinodev1.RuntimeClass, fieldManager string) (*RuntimeClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go","code":"// ExtractRuntimeClassStatus is the same as ExtractRuntimeClass except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractRuntimeClassStatus(runtimeClass *apinodev1.RuntimeClass, fieldManager string) (*RuntimeClassApplyConfiguration, error) {\n\treturn extractRuntimeClass(runtimeClass, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100023816,"name":"extractRuntimeClass","signature":"func extractRuntimeClass(runtimeClass *apinodev1.RuntimeClass, fieldManager string, subresource string) (*RuntimeClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go","code":"func extractRuntimeClass(runtimeClass *apinodev1.RuntimeClass, fieldManager string, subresource string) (*RuntimeClassApplyConfiguration, error) {\n\tb := \u0026RuntimeClassApplyConfiguration{}\n\terr := managedfields.ExtractInto(runtimeClass, internal.Parser().Type(\"io.k8s.api.node.v1.RuntimeClass\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(runtimeClass.Name)\n\n\tb.WithKind(\"RuntimeClass\")\n\tb.WithAPIVersion(\"node.k8s.io/v1\")\n\treturn b, nil\n}","line":{"from":72,"to":83}} {"id":100023817,"name":"WithKind","signature":"func (b *RuntimeClassApplyConfiguration) WithKind(value string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithKind(value string) *RuntimeClassApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":85,"to":91}} {"id":100023818,"name":"WithAPIVersion","signature":"func (b *RuntimeClassApplyConfiguration) WithAPIVersion(value string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithAPIVersion(value string) *RuntimeClassApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":93,"to":99}} {"id":100023819,"name":"WithName","signature":"func (b *RuntimeClassApplyConfiguration) WithName(value string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithName(value string) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":101,"to":108}} {"id":100023820,"name":"WithGenerateName","signature":"func (b *RuntimeClassApplyConfiguration) WithGenerateName(value string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithGenerateName(value string) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":110,"to":117}} {"id":100023821,"name":"WithNamespace","signature":"func (b *RuntimeClassApplyConfiguration) WithNamespace(value string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithNamespace(value string) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":119,"to":126}} {"id":100023822,"name":"WithUID","signature":"func (b *RuntimeClassApplyConfiguration) WithUID(value types.UID) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithUID(value types.UID) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":128,"to":135}} {"id":100023823,"name":"WithResourceVersion","signature":"func (b *RuntimeClassApplyConfiguration) WithResourceVersion(value string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithResourceVersion(value string) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":137,"to":144}} {"id":100023824,"name":"WithGeneration","signature":"func (b *RuntimeClassApplyConfiguration) WithGeneration(value int64) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithGeneration(value int64) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":146,"to":153}} {"id":100023825,"name":"WithCreationTimestamp","signature":"func (b *RuntimeClassApplyConfiguration) WithCreationTimestamp(value metav1.Time) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithCreationTimestamp(value metav1.Time) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":155,"to":162}} {"id":100023826,"name":"WithDeletionTimestamp","signature":"func (b *RuntimeClassApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":164,"to":171}} {"id":100023827,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *RuntimeClassApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":173,"to":180}} {"id":100023828,"name":"WithLabels","signature":"func (b *RuntimeClassApplyConfiguration) WithLabels(entries map[string]string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *RuntimeClassApplyConfiguration) WithLabels(entries map[string]string) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":182,"to":195}} {"id":100023829,"name":"WithAnnotations","signature":"func (b *RuntimeClassApplyConfiguration) WithAnnotations(entries map[string]string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *RuntimeClassApplyConfiguration) WithAnnotations(entries map[string]string) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":197,"to":210}} {"id":100023830,"name":"WithOwnerReferences","signature":"func (b *RuntimeClassApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *RuntimeClassApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":212,"to":224}} {"id":100023831,"name":"WithFinalizers","signature":"func (b *RuntimeClassApplyConfiguration) WithFinalizers(values ...string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *RuntimeClassApplyConfiguration) WithFinalizers(values ...string) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":226,"to":235}} {"id":100023832,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *RuntimeClassApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go","code":"func (b *RuntimeClassApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":237,"to":241}} {"id":100023833,"name":"WithHandler","signature":"func (b *RuntimeClassApplyConfiguration) WithHandler(value string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go","code":"// WithHandler sets the Handler field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Handler field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithHandler(value string) *RuntimeClassApplyConfiguration {\n\tb.Handler = \u0026value\n\treturn b\n}","line":{"from":243,"to":249}} {"id":100023834,"name":"WithOverhead","signature":"func (b *RuntimeClassApplyConfiguration) WithOverhead(value *OverheadApplyConfiguration) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go","code":"// WithOverhead sets the Overhead field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Overhead field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithOverhead(value *OverheadApplyConfiguration) *RuntimeClassApplyConfiguration {\n\tb.Overhead = value\n\treturn b\n}","line":{"from":251,"to":257}} {"id":100023835,"name":"WithScheduling","signature":"func (b *RuntimeClassApplyConfiguration) WithScheduling(value *SchedulingApplyConfiguration) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/runtimeclass.go","code":"// WithScheduling sets the Scheduling field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Scheduling field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithScheduling(value *SchedulingApplyConfiguration) *RuntimeClassApplyConfiguration {\n\tb.Scheduling = value\n\treturn b\n}","line":{"from":259,"to":265}} {"id":100023836,"name":"Scheduling","signature":"func Scheduling() *SchedulingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/scheduling.go","code":"// SchedulingApplyConfiguration constructs an declarative configuration of the Scheduling type for use with\n// apply.\nfunc Scheduling() *SchedulingApplyConfiguration {\n\treturn \u0026SchedulingApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100023837,"name":"WithNodeSelector","signature":"func (b *SchedulingApplyConfiguration) WithNodeSelector(entries map[string]string) *SchedulingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/scheduling.go","code":"// WithNodeSelector puts the entries into the NodeSelector field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the NodeSelector field,\n// overwriting an existing map entries in NodeSelector field with the same key.\nfunc (b *SchedulingApplyConfiguration) WithNodeSelector(entries map[string]string) *SchedulingApplyConfiguration {\n\tif b.NodeSelector == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.NodeSelector = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.NodeSelector[k] = v\n\t}\n\treturn b\n}","line":{"from":38,"to":50}} {"id":100023838,"name":"WithTolerations","signature":"func (b *SchedulingApplyConfiguration) WithTolerations(values ...*v1.TolerationApplyConfiguration) *SchedulingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1/scheduling.go","code":"// WithTolerations adds the given value to the Tolerations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Tolerations field.\nfunc (b *SchedulingApplyConfiguration) WithTolerations(values ...*v1.TolerationApplyConfiguration) *SchedulingApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithTolerations\")\n\t\t}\n\t\tb.Tolerations = append(b.Tolerations, *values[i])\n\t}\n\treturn b\n}","line":{"from":52,"to":63}} {"id":100023839,"name":"Overhead","signature":"func Overhead() *OverheadApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/overhead.go","code":"// OverheadApplyConfiguration constructs an declarative configuration of the Overhead type for use with\n// apply.\nfunc Overhead() *OverheadApplyConfiguration {\n\treturn \u0026OverheadApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100023840,"name":"WithPodFixed","signature":"func (b *OverheadApplyConfiguration) WithPodFixed(value v1.ResourceList) *OverheadApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/overhead.go","code":"// WithPodFixed sets the PodFixed field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PodFixed field is set to the value of the last call.\nfunc (b *OverheadApplyConfiguration) WithPodFixed(value v1.ResourceList) *OverheadApplyConfiguration {\n\tb.PodFixed = \u0026value\n\treturn b\n}","line":{"from":37,"to":43}} {"id":100023841,"name":"RuntimeClass","signature":"func RuntimeClass(name string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclass.go","code":"// RuntimeClass constructs an declarative configuration of the RuntimeClass type for use with\n// apply.\nfunc RuntimeClass(name string) *RuntimeClassApplyConfiguration {\n\tb := \u0026RuntimeClassApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"RuntimeClass\")\n\tb.WithAPIVersion(\"node.k8s.io/v1alpha1\")\n\treturn b\n}","line":{"from":38,"to":46}} {"id":100023842,"name":"ExtractRuntimeClass","signature":"func ExtractRuntimeClass(runtimeClass *nodev1alpha1.RuntimeClass, fieldManager string) (*RuntimeClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclass.go","code":"// ExtractRuntimeClass extracts the applied configuration owned by fieldManager from\n// runtimeClass. If no managedFields are found in runtimeClass for fieldManager, a\n// RuntimeClassApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// runtimeClass must be a unmodified RuntimeClass API object that was retrieved from the Kubernetes API.\n// ExtractRuntimeClass provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractRuntimeClass(runtimeClass *nodev1alpha1.RuntimeClass, fieldManager string) (*RuntimeClassApplyConfiguration, error) {\n\treturn extractRuntimeClass(runtimeClass, fieldManager, \"\")\n}","line":{"from":48,"to":61}} {"id":100023843,"name":"ExtractRuntimeClassStatus","signature":"func ExtractRuntimeClassStatus(runtimeClass *nodev1alpha1.RuntimeClass, fieldManager string) (*RuntimeClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclass.go","code":"// ExtractRuntimeClassStatus is the same as ExtractRuntimeClass except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractRuntimeClassStatus(runtimeClass *nodev1alpha1.RuntimeClass, fieldManager string) (*RuntimeClassApplyConfiguration, error) {\n\treturn extractRuntimeClass(runtimeClass, fieldManager, \"status\")\n}","line":{"from":63,"to":68}} {"id":100023844,"name":"extractRuntimeClass","signature":"func extractRuntimeClass(runtimeClass *nodev1alpha1.RuntimeClass, fieldManager string, subresource string) (*RuntimeClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclass.go","code":"func extractRuntimeClass(runtimeClass *nodev1alpha1.RuntimeClass, fieldManager string, subresource string) (*RuntimeClassApplyConfiguration, error) {\n\tb := \u0026RuntimeClassApplyConfiguration{}\n\terr := managedfields.ExtractInto(runtimeClass, internal.Parser().Type(\"io.k8s.api.node.v1alpha1.RuntimeClass\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(runtimeClass.Name)\n\n\tb.WithKind(\"RuntimeClass\")\n\tb.WithAPIVersion(\"node.k8s.io/v1alpha1\")\n\treturn b, nil\n}","line":{"from":70,"to":81}} {"id":100023845,"name":"WithKind","signature":"func (b *RuntimeClassApplyConfiguration) WithKind(value string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclass.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithKind(value string) *RuntimeClassApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100023846,"name":"WithAPIVersion","signature":"func (b *RuntimeClassApplyConfiguration) WithAPIVersion(value string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclass.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithAPIVersion(value string) *RuntimeClassApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":91,"to":97}} {"id":100023847,"name":"WithName","signature":"func (b *RuntimeClassApplyConfiguration) WithName(value string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclass.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithName(value string) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":99,"to":106}} {"id":100023848,"name":"WithGenerateName","signature":"func (b *RuntimeClassApplyConfiguration) WithGenerateName(value string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclass.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithGenerateName(value string) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":108,"to":115}} {"id":100023849,"name":"WithNamespace","signature":"func (b *RuntimeClassApplyConfiguration) WithNamespace(value string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclass.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithNamespace(value string) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":117,"to":124}} {"id":100023850,"name":"WithUID","signature":"func (b *RuntimeClassApplyConfiguration) WithUID(value types.UID) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclass.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithUID(value types.UID) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":126,"to":133}} {"id":100023851,"name":"WithResourceVersion","signature":"func (b *RuntimeClassApplyConfiguration) WithResourceVersion(value string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclass.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithResourceVersion(value string) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":135,"to":142}} {"id":100023852,"name":"WithGeneration","signature":"func (b *RuntimeClassApplyConfiguration) WithGeneration(value int64) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclass.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithGeneration(value int64) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":144,"to":151}} {"id":100023853,"name":"WithCreationTimestamp","signature":"func (b *RuntimeClassApplyConfiguration) WithCreationTimestamp(value metav1.Time) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclass.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithCreationTimestamp(value metav1.Time) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":153,"to":160}} {"id":100023854,"name":"WithDeletionTimestamp","signature":"func (b *RuntimeClassApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclass.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":162,"to":169}} {"id":100023855,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *RuntimeClassApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclass.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":171,"to":178}} {"id":100023856,"name":"WithLabels","signature":"func (b *RuntimeClassApplyConfiguration) WithLabels(entries map[string]string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclass.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *RuntimeClassApplyConfiguration) WithLabels(entries map[string]string) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":180,"to":193}} {"id":100023857,"name":"WithAnnotations","signature":"func (b *RuntimeClassApplyConfiguration) WithAnnotations(entries map[string]string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclass.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *RuntimeClassApplyConfiguration) WithAnnotations(entries map[string]string) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":195,"to":208}} {"id":100023858,"name":"WithOwnerReferences","signature":"func (b *RuntimeClassApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclass.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *RuntimeClassApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":210,"to":222}} {"id":100023859,"name":"WithFinalizers","signature":"func (b *RuntimeClassApplyConfiguration) WithFinalizers(values ...string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclass.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *RuntimeClassApplyConfiguration) WithFinalizers(values ...string) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":224,"to":233}} {"id":100023860,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *RuntimeClassApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclass.go","code":"func (b *RuntimeClassApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":235,"to":239}} {"id":100023861,"name":"WithSpec","signature":"func (b *RuntimeClassApplyConfiguration) WithSpec(value *RuntimeClassSpecApplyConfiguration) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclass.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithSpec(value *RuntimeClassSpecApplyConfiguration) *RuntimeClassApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":241,"to":247}} {"id":100023862,"name":"RuntimeClassSpec","signature":"func RuntimeClassSpec() *RuntimeClassSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclassspec.go","code":"// RuntimeClassSpecApplyConfiguration constructs an declarative configuration of the RuntimeClassSpec type for use with\n// apply.\nfunc RuntimeClassSpec() *RuntimeClassSpecApplyConfiguration {\n\treturn \u0026RuntimeClassSpecApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100023863,"name":"WithRuntimeHandler","signature":"func (b *RuntimeClassSpecApplyConfiguration) WithRuntimeHandler(value string) *RuntimeClassSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclassspec.go","code":"// WithRuntimeHandler sets the RuntimeHandler field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RuntimeHandler field is set to the value of the last call.\nfunc (b *RuntimeClassSpecApplyConfiguration) WithRuntimeHandler(value string) *RuntimeClassSpecApplyConfiguration {\n\tb.RuntimeHandler = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100023864,"name":"WithOverhead","signature":"func (b *RuntimeClassSpecApplyConfiguration) WithOverhead(value *OverheadApplyConfiguration) *RuntimeClassSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclassspec.go","code":"// WithOverhead sets the Overhead field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Overhead field is set to the value of the last call.\nfunc (b *RuntimeClassSpecApplyConfiguration) WithOverhead(value *OverheadApplyConfiguration) *RuntimeClassSpecApplyConfiguration {\n\tb.Overhead = value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100023865,"name":"WithScheduling","signature":"func (b *RuntimeClassSpecApplyConfiguration) WithScheduling(value *SchedulingApplyConfiguration) *RuntimeClassSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/runtimeclassspec.go","code":"// WithScheduling sets the Scheduling field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Scheduling field is set to the value of the last call.\nfunc (b *RuntimeClassSpecApplyConfiguration) WithScheduling(value *SchedulingApplyConfiguration) *RuntimeClassSpecApplyConfiguration {\n\tb.Scheduling = value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100023866,"name":"Scheduling","signature":"func Scheduling() *SchedulingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/scheduling.go","code":"// SchedulingApplyConfiguration constructs an declarative configuration of the Scheduling type for use with\n// apply.\nfunc Scheduling() *SchedulingApplyConfiguration {\n\treturn \u0026SchedulingApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100023867,"name":"WithNodeSelector","signature":"func (b *SchedulingApplyConfiguration) WithNodeSelector(entries map[string]string) *SchedulingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/scheduling.go","code":"// WithNodeSelector puts the entries into the NodeSelector field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the NodeSelector field,\n// overwriting an existing map entries in NodeSelector field with the same key.\nfunc (b *SchedulingApplyConfiguration) WithNodeSelector(entries map[string]string) *SchedulingApplyConfiguration {\n\tif b.NodeSelector == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.NodeSelector = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.NodeSelector[k] = v\n\t}\n\treturn b\n}","line":{"from":38,"to":50}} {"id":100023868,"name":"WithTolerations","signature":"func (b *SchedulingApplyConfiguration) WithTolerations(values ...*v1.TolerationApplyConfiguration) *SchedulingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1alpha1/scheduling.go","code":"// WithTolerations adds the given value to the Tolerations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Tolerations field.\nfunc (b *SchedulingApplyConfiguration) WithTolerations(values ...*v1.TolerationApplyConfiguration) *SchedulingApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithTolerations\")\n\t\t}\n\t\tb.Tolerations = append(b.Tolerations, *values[i])\n\t}\n\treturn b\n}","line":{"from":52,"to":63}} {"id":100023869,"name":"Overhead","signature":"func Overhead() *OverheadApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/overhead.go","code":"// OverheadApplyConfiguration constructs an declarative configuration of the Overhead type for use with\n// apply.\nfunc Overhead() *OverheadApplyConfiguration {\n\treturn \u0026OverheadApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100023870,"name":"WithPodFixed","signature":"func (b *OverheadApplyConfiguration) WithPodFixed(value v1.ResourceList) *OverheadApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/overhead.go","code":"// WithPodFixed sets the PodFixed field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PodFixed field is set to the value of the last call.\nfunc (b *OverheadApplyConfiguration) WithPodFixed(value v1.ResourceList) *OverheadApplyConfiguration {\n\tb.PodFixed = \u0026value\n\treturn b\n}","line":{"from":37,"to":43}} {"id":100023871,"name":"RuntimeClass","signature":"func RuntimeClass(name string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go","code":"// RuntimeClass constructs an declarative configuration of the RuntimeClass type for use with\n// apply.\nfunc RuntimeClass(name string) *RuntimeClassApplyConfiguration {\n\tb := \u0026RuntimeClassApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"RuntimeClass\")\n\tb.WithAPIVersion(\"node.k8s.io/v1beta1\")\n\treturn b\n}","line":{"from":40,"to":48}} {"id":100023872,"name":"ExtractRuntimeClass","signature":"func ExtractRuntimeClass(runtimeClass *nodev1beta1.RuntimeClass, fieldManager string) (*RuntimeClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go","code":"// ExtractRuntimeClass extracts the applied configuration owned by fieldManager from\n// runtimeClass. If no managedFields are found in runtimeClass for fieldManager, a\n// RuntimeClassApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// runtimeClass must be a unmodified RuntimeClass API object that was retrieved from the Kubernetes API.\n// ExtractRuntimeClass provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractRuntimeClass(runtimeClass *nodev1beta1.RuntimeClass, fieldManager string) (*RuntimeClassApplyConfiguration, error) {\n\treturn extractRuntimeClass(runtimeClass, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100023873,"name":"ExtractRuntimeClassStatus","signature":"func ExtractRuntimeClassStatus(runtimeClass *nodev1beta1.RuntimeClass, fieldManager string) (*RuntimeClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go","code":"// ExtractRuntimeClassStatus is the same as ExtractRuntimeClass except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractRuntimeClassStatus(runtimeClass *nodev1beta1.RuntimeClass, fieldManager string) (*RuntimeClassApplyConfiguration, error) {\n\treturn extractRuntimeClass(runtimeClass, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100023874,"name":"extractRuntimeClass","signature":"func extractRuntimeClass(runtimeClass *nodev1beta1.RuntimeClass, fieldManager string, subresource string) (*RuntimeClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go","code":"func extractRuntimeClass(runtimeClass *nodev1beta1.RuntimeClass, fieldManager string, subresource string) (*RuntimeClassApplyConfiguration, error) {\n\tb := \u0026RuntimeClassApplyConfiguration{}\n\terr := managedfields.ExtractInto(runtimeClass, internal.Parser().Type(\"io.k8s.api.node.v1beta1.RuntimeClass\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(runtimeClass.Name)\n\n\tb.WithKind(\"RuntimeClass\")\n\tb.WithAPIVersion(\"node.k8s.io/v1beta1\")\n\treturn b, nil\n}","line":{"from":72,"to":83}} {"id":100023875,"name":"WithKind","signature":"func (b *RuntimeClassApplyConfiguration) WithKind(value string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithKind(value string) *RuntimeClassApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":85,"to":91}} {"id":100023876,"name":"WithAPIVersion","signature":"func (b *RuntimeClassApplyConfiguration) WithAPIVersion(value string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithAPIVersion(value string) *RuntimeClassApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":93,"to":99}} {"id":100023877,"name":"WithName","signature":"func (b *RuntimeClassApplyConfiguration) WithName(value string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithName(value string) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":101,"to":108}} {"id":100023878,"name":"WithGenerateName","signature":"func (b *RuntimeClassApplyConfiguration) WithGenerateName(value string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithGenerateName(value string) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":110,"to":117}} {"id":100023879,"name":"WithNamespace","signature":"func (b *RuntimeClassApplyConfiguration) WithNamespace(value string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithNamespace(value string) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":119,"to":126}} {"id":100023880,"name":"WithUID","signature":"func (b *RuntimeClassApplyConfiguration) WithUID(value types.UID) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithUID(value types.UID) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":128,"to":135}} {"id":100023881,"name":"WithResourceVersion","signature":"func (b *RuntimeClassApplyConfiguration) WithResourceVersion(value string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithResourceVersion(value string) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":137,"to":144}} {"id":100023882,"name":"WithGeneration","signature":"func (b *RuntimeClassApplyConfiguration) WithGeneration(value int64) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithGeneration(value int64) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":146,"to":153}} {"id":100023883,"name":"WithCreationTimestamp","signature":"func (b *RuntimeClassApplyConfiguration) WithCreationTimestamp(value metav1.Time) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithCreationTimestamp(value metav1.Time) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":155,"to":162}} {"id":100023884,"name":"WithDeletionTimestamp","signature":"func (b *RuntimeClassApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":164,"to":171}} {"id":100023885,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *RuntimeClassApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":173,"to":180}} {"id":100023886,"name":"WithLabels","signature":"func (b *RuntimeClassApplyConfiguration) WithLabels(entries map[string]string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *RuntimeClassApplyConfiguration) WithLabels(entries map[string]string) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":182,"to":195}} {"id":100023887,"name":"WithAnnotations","signature":"func (b *RuntimeClassApplyConfiguration) WithAnnotations(entries map[string]string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *RuntimeClassApplyConfiguration) WithAnnotations(entries map[string]string) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":197,"to":210}} {"id":100023888,"name":"WithOwnerReferences","signature":"func (b *RuntimeClassApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *RuntimeClassApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":212,"to":224}} {"id":100023889,"name":"WithFinalizers","signature":"func (b *RuntimeClassApplyConfiguration) WithFinalizers(values ...string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *RuntimeClassApplyConfiguration) WithFinalizers(values ...string) *RuntimeClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":226,"to":235}} {"id":100023890,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *RuntimeClassApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go","code":"func (b *RuntimeClassApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":237,"to":241}} {"id":100023891,"name":"WithHandler","signature":"func (b *RuntimeClassApplyConfiguration) WithHandler(value string) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go","code":"// WithHandler sets the Handler field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Handler field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithHandler(value string) *RuntimeClassApplyConfiguration {\n\tb.Handler = \u0026value\n\treturn b\n}","line":{"from":243,"to":249}} {"id":100023892,"name":"WithOverhead","signature":"func (b *RuntimeClassApplyConfiguration) WithOverhead(value *OverheadApplyConfiguration) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go","code":"// WithOverhead sets the Overhead field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Overhead field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithOverhead(value *OverheadApplyConfiguration) *RuntimeClassApplyConfiguration {\n\tb.Overhead = value\n\treturn b\n}","line":{"from":251,"to":257}} {"id":100023893,"name":"WithScheduling","signature":"func (b *RuntimeClassApplyConfiguration) WithScheduling(value *SchedulingApplyConfiguration) *RuntimeClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/runtimeclass.go","code":"// WithScheduling sets the Scheduling field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Scheduling field is set to the value of the last call.\nfunc (b *RuntimeClassApplyConfiguration) WithScheduling(value *SchedulingApplyConfiguration) *RuntimeClassApplyConfiguration {\n\tb.Scheduling = value\n\treturn b\n}","line":{"from":259,"to":265}} {"id":100023894,"name":"Scheduling","signature":"func Scheduling() *SchedulingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/scheduling.go","code":"// SchedulingApplyConfiguration constructs an declarative configuration of the Scheduling type for use with\n// apply.\nfunc Scheduling() *SchedulingApplyConfiguration {\n\treturn \u0026SchedulingApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100023895,"name":"WithNodeSelector","signature":"func (b *SchedulingApplyConfiguration) WithNodeSelector(entries map[string]string) *SchedulingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/scheduling.go","code":"// WithNodeSelector puts the entries into the NodeSelector field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the NodeSelector field,\n// overwriting an existing map entries in NodeSelector field with the same key.\nfunc (b *SchedulingApplyConfiguration) WithNodeSelector(entries map[string]string) *SchedulingApplyConfiguration {\n\tif b.NodeSelector == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.NodeSelector = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.NodeSelector[k] = v\n\t}\n\treturn b\n}","line":{"from":38,"to":50}} {"id":100023896,"name":"WithTolerations","signature":"func (b *SchedulingApplyConfiguration) WithTolerations(values ...*v1.TolerationApplyConfiguration) *SchedulingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/node/v1beta1/scheduling.go","code":"// WithTolerations adds the given value to the Tolerations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Tolerations field.\nfunc (b *SchedulingApplyConfiguration) WithTolerations(values ...*v1.TolerationApplyConfiguration) *SchedulingApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithTolerations\")\n\t\t}\n\t\tb.Tolerations = append(b.Tolerations, *values[i])\n\t}\n\treturn b\n}","line":{"from":52,"to":63}} {"id":100023897,"name":"Eviction","signature":"func Eviction(name, namespace string) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/eviction.go","code":"// Eviction constructs an declarative configuration of the Eviction type for use with\n// apply.\nfunc Eviction(name, namespace string) *EvictionApplyConfiguration {\n\tb := \u0026EvictionApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"Eviction\")\n\tb.WithAPIVersion(\"policy/v1\")\n\treturn b\n}","line":{"from":38,"to":47}} {"id":100023898,"name":"ExtractEviction","signature":"func ExtractEviction(eviction *policyv1.Eviction, fieldManager string) (*EvictionApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/eviction.go","code":"// ExtractEviction extracts the applied configuration owned by fieldManager from\n// eviction. If no managedFields are found in eviction for fieldManager, a\n// EvictionApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// eviction must be a unmodified Eviction API object that was retrieved from the Kubernetes API.\n// ExtractEviction provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractEviction(eviction *policyv1.Eviction, fieldManager string) (*EvictionApplyConfiguration, error) {\n\treturn extractEviction(eviction, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100023899,"name":"ExtractEvictionStatus","signature":"func ExtractEvictionStatus(eviction *policyv1.Eviction, fieldManager string) (*EvictionApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/eviction.go","code":"// ExtractEvictionStatus is the same as ExtractEviction except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractEvictionStatus(eviction *policyv1.Eviction, fieldManager string) (*EvictionApplyConfiguration, error) {\n\treturn extractEviction(eviction, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100023900,"name":"extractEviction","signature":"func extractEviction(eviction *policyv1.Eviction, fieldManager string, subresource string) (*EvictionApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/eviction.go","code":"func extractEviction(eviction *policyv1.Eviction, fieldManager string, subresource string) (*EvictionApplyConfiguration, error) {\n\tb := \u0026EvictionApplyConfiguration{}\n\terr := managedfields.ExtractInto(eviction, internal.Parser().Type(\"io.k8s.api.policy.v1.Eviction\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(eviction.Name)\n\tb.WithNamespace(eviction.Namespace)\n\n\tb.WithKind(\"Eviction\")\n\tb.WithAPIVersion(\"policy/v1\")\n\treturn b, nil\n}","line":{"from":71,"to":83}} {"id":100023901,"name":"WithKind","signature":"func (b *EvictionApplyConfiguration) WithKind(value string) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/eviction.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *EvictionApplyConfiguration) WithKind(value string) *EvictionApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":85,"to":91}} {"id":100023902,"name":"WithAPIVersion","signature":"func (b *EvictionApplyConfiguration) WithAPIVersion(value string) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/eviction.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *EvictionApplyConfiguration) WithAPIVersion(value string) *EvictionApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":93,"to":99}} {"id":100023903,"name":"WithName","signature":"func (b *EvictionApplyConfiguration) WithName(value string) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/eviction.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *EvictionApplyConfiguration) WithName(value string) *EvictionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":101,"to":108}} {"id":100023904,"name":"WithGenerateName","signature":"func (b *EvictionApplyConfiguration) WithGenerateName(value string) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/eviction.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *EvictionApplyConfiguration) WithGenerateName(value string) *EvictionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":110,"to":117}} {"id":100023905,"name":"WithNamespace","signature":"func (b *EvictionApplyConfiguration) WithNamespace(value string) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/eviction.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *EvictionApplyConfiguration) WithNamespace(value string) *EvictionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":119,"to":126}} {"id":100023906,"name":"WithUID","signature":"func (b *EvictionApplyConfiguration) WithUID(value types.UID) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/eviction.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *EvictionApplyConfiguration) WithUID(value types.UID) *EvictionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":128,"to":135}} {"id":100023907,"name":"WithResourceVersion","signature":"func (b *EvictionApplyConfiguration) WithResourceVersion(value string) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/eviction.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *EvictionApplyConfiguration) WithResourceVersion(value string) *EvictionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":137,"to":144}} {"id":100023908,"name":"WithGeneration","signature":"func (b *EvictionApplyConfiguration) WithGeneration(value int64) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/eviction.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *EvictionApplyConfiguration) WithGeneration(value int64) *EvictionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":146,"to":153}} {"id":100023909,"name":"WithCreationTimestamp","signature":"func (b *EvictionApplyConfiguration) WithCreationTimestamp(value metav1.Time) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/eviction.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *EvictionApplyConfiguration) WithCreationTimestamp(value metav1.Time) *EvictionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":155,"to":162}} {"id":100023910,"name":"WithDeletionTimestamp","signature":"func (b *EvictionApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/eviction.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *EvictionApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *EvictionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":164,"to":171}} {"id":100023911,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *EvictionApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/eviction.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *EvictionApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *EvictionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":173,"to":180}} {"id":100023912,"name":"WithLabels","signature":"func (b *EvictionApplyConfiguration) WithLabels(entries map[string]string) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/eviction.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *EvictionApplyConfiguration) WithLabels(entries map[string]string) *EvictionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":182,"to":195}} {"id":100023913,"name":"WithAnnotations","signature":"func (b *EvictionApplyConfiguration) WithAnnotations(entries map[string]string) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/eviction.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *EvictionApplyConfiguration) WithAnnotations(entries map[string]string) *EvictionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":197,"to":210}} {"id":100023914,"name":"WithOwnerReferences","signature":"func (b *EvictionApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/eviction.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *EvictionApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *EvictionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":212,"to":224}} {"id":100023915,"name":"WithFinalizers","signature":"func (b *EvictionApplyConfiguration) WithFinalizers(values ...string) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/eviction.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *EvictionApplyConfiguration) WithFinalizers(values ...string) *EvictionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":226,"to":235}} {"id":100023916,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *EvictionApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/eviction.go","code":"func (b *EvictionApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":237,"to":241}} {"id":100023917,"name":"WithDeleteOptions","signature":"func (b *EvictionApplyConfiguration) WithDeleteOptions(value *v1.DeleteOptionsApplyConfiguration) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/eviction.go","code":"// WithDeleteOptions sets the DeleteOptions field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeleteOptions field is set to the value of the last call.\nfunc (b *EvictionApplyConfiguration) WithDeleteOptions(value *v1.DeleteOptionsApplyConfiguration) *EvictionApplyConfiguration {\n\tb.DeleteOptions = value\n\treturn b\n}","line":{"from":243,"to":249}} {"id":100023918,"name":"PodDisruptionBudget","signature":"func PodDisruptionBudget(name, namespace string) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudget.go","code":"// PodDisruptionBudget constructs an declarative configuration of the PodDisruptionBudget type for use with\n// apply.\nfunc PodDisruptionBudget(name, namespace string) *PodDisruptionBudgetApplyConfiguration {\n\tb := \u0026PodDisruptionBudgetApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"PodDisruptionBudget\")\n\tb.WithAPIVersion(\"policy/v1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100023919,"name":"ExtractPodDisruptionBudget","signature":"func ExtractPodDisruptionBudget(podDisruptionBudget *apipolicyv1.PodDisruptionBudget, fieldManager string) (*PodDisruptionBudgetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudget.go","code":"// ExtractPodDisruptionBudget extracts the applied configuration owned by fieldManager from\n// podDisruptionBudget. If no managedFields are found in podDisruptionBudget for fieldManager, a\n// PodDisruptionBudgetApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// podDisruptionBudget must be a unmodified PodDisruptionBudget API object that was retrieved from the Kubernetes API.\n// ExtractPodDisruptionBudget provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractPodDisruptionBudget(podDisruptionBudget *apipolicyv1.PodDisruptionBudget, fieldManager string) (*PodDisruptionBudgetApplyConfiguration, error) {\n\treturn extractPodDisruptionBudget(podDisruptionBudget, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100023920,"name":"ExtractPodDisruptionBudgetStatus","signature":"func ExtractPodDisruptionBudgetStatus(podDisruptionBudget *apipolicyv1.PodDisruptionBudget, fieldManager string) (*PodDisruptionBudgetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudget.go","code":"// ExtractPodDisruptionBudgetStatus is the same as ExtractPodDisruptionBudget except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractPodDisruptionBudgetStatus(podDisruptionBudget *apipolicyv1.PodDisruptionBudget, fieldManager string) (*PodDisruptionBudgetApplyConfiguration, error) {\n\treturn extractPodDisruptionBudget(podDisruptionBudget, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100023921,"name":"extractPodDisruptionBudget","signature":"func extractPodDisruptionBudget(podDisruptionBudget *apipolicyv1.PodDisruptionBudget, fieldManager string, subresource string) (*PodDisruptionBudgetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudget.go","code":"func extractPodDisruptionBudget(podDisruptionBudget *apipolicyv1.PodDisruptionBudget, fieldManager string, subresource string) (*PodDisruptionBudgetApplyConfiguration, error) {\n\tb := \u0026PodDisruptionBudgetApplyConfiguration{}\n\terr := managedfields.ExtractInto(podDisruptionBudget, internal.Parser().Type(\"io.k8s.api.policy.v1.PodDisruptionBudget\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(podDisruptionBudget.Name)\n\tb.WithNamespace(podDisruptionBudget.Namespace)\n\n\tb.WithKind(\"PodDisruptionBudget\")\n\tb.WithAPIVersion(\"policy/v1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100023922,"name":"WithKind","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithKind(value string) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudget.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithKind(value string) *PodDisruptionBudgetApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100023923,"name":"WithAPIVersion","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithAPIVersion(value string) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudget.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithAPIVersion(value string) *PodDisruptionBudgetApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100023924,"name":"WithName","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithName(value string) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudget.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithName(value string) *PodDisruptionBudgetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100023925,"name":"WithGenerateName","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithGenerateName(value string) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudget.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithGenerateName(value string) *PodDisruptionBudgetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100023926,"name":"WithNamespace","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithNamespace(value string) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudget.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithNamespace(value string) *PodDisruptionBudgetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100023927,"name":"WithUID","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithUID(value types.UID) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudget.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithUID(value types.UID) *PodDisruptionBudgetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100023928,"name":"WithResourceVersion","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithResourceVersion(value string) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudget.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithResourceVersion(value string) *PodDisruptionBudgetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100023929,"name":"WithGeneration","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithGeneration(value int64) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudget.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithGeneration(value int64) *PodDisruptionBudgetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100023930,"name":"WithCreationTimestamp","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudget.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PodDisruptionBudgetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100023931,"name":"WithDeletionTimestamp","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudget.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PodDisruptionBudgetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100023932,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudget.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PodDisruptionBudgetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100023933,"name":"WithLabels","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithLabels(entries map[string]string) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudget.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithLabels(entries map[string]string) *PodDisruptionBudgetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100023934,"name":"WithAnnotations","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithAnnotations(entries map[string]string) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudget.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithAnnotations(entries map[string]string) *PodDisruptionBudgetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100023935,"name":"WithOwnerReferences","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudget.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PodDisruptionBudgetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100023936,"name":"WithFinalizers","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithFinalizers(values ...string) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudget.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithFinalizers(values ...string) *PodDisruptionBudgetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100023937,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *PodDisruptionBudgetApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudget.go","code":"func (b *PodDisruptionBudgetApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100023938,"name":"WithSpec","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithSpec(value *PodDisruptionBudgetSpecApplyConfiguration) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudget.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithSpec(value *PodDisruptionBudgetSpecApplyConfiguration) *PodDisruptionBudgetApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100023939,"name":"WithStatus","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithStatus(value *PodDisruptionBudgetStatusApplyConfiguration) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudget.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithStatus(value *PodDisruptionBudgetStatusApplyConfiguration) *PodDisruptionBudgetApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100023940,"name":"PodDisruptionBudgetSpec","signature":"func PodDisruptionBudgetSpec() *PodDisruptionBudgetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudgetspec.go","code":"// PodDisruptionBudgetSpecApplyConfiguration constructs an declarative configuration of the PodDisruptionBudgetSpec type for use with\n// apply.\nfunc PodDisruptionBudgetSpec() *PodDisruptionBudgetSpecApplyConfiguration {\n\treturn \u0026PodDisruptionBudgetSpecApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100023941,"name":"WithMinAvailable","signature":"func (b *PodDisruptionBudgetSpecApplyConfiguration) WithMinAvailable(value intstr.IntOrString) *PodDisruptionBudgetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudgetspec.go","code":"// WithMinAvailable sets the MinAvailable field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MinAvailable field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetSpecApplyConfiguration) WithMinAvailable(value intstr.IntOrString) *PodDisruptionBudgetSpecApplyConfiguration {\n\tb.MinAvailable = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100023942,"name":"WithSelector","signature":"func (b *PodDisruptionBudgetSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *PodDisruptionBudgetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudgetspec.go","code":"// WithSelector sets the Selector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Selector field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *PodDisruptionBudgetSpecApplyConfiguration {\n\tb.Selector = value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100023943,"name":"WithMaxUnavailable","signature":"func (b *PodDisruptionBudgetSpecApplyConfiguration) WithMaxUnavailable(value intstr.IntOrString) *PodDisruptionBudgetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudgetspec.go","code":"// WithMaxUnavailable sets the MaxUnavailable field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MaxUnavailable field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetSpecApplyConfiguration) WithMaxUnavailable(value intstr.IntOrString) *PodDisruptionBudgetSpecApplyConfiguration {\n\tb.MaxUnavailable = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100023944,"name":"WithUnhealthyPodEvictionPolicy","signature":"func (b *PodDisruptionBudgetSpecApplyConfiguration) WithUnhealthyPodEvictionPolicy(value policyv1.UnhealthyPodEvictionPolicyType) *PodDisruptionBudgetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudgetspec.go","code":"// WithUnhealthyPodEvictionPolicy sets the UnhealthyPodEvictionPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UnhealthyPodEvictionPolicy field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetSpecApplyConfiguration) WithUnhealthyPodEvictionPolicy(value policyv1.UnhealthyPodEvictionPolicyType) *PodDisruptionBudgetSpecApplyConfiguration {\n\tb.UnhealthyPodEvictionPolicy = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100023945,"name":"PodDisruptionBudgetStatus","signature":"func PodDisruptionBudgetStatus() *PodDisruptionBudgetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudgetstatus.go","code":"// PodDisruptionBudgetStatusApplyConfiguration constructs an declarative configuration of the PodDisruptionBudgetStatus type for use with\n// apply.\nfunc PodDisruptionBudgetStatus() *PodDisruptionBudgetStatusApplyConfiguration {\n\treturn \u0026PodDisruptionBudgetStatusApplyConfiguration{}\n}","line":{"from":38,"to":42}} {"id":100023946,"name":"WithObservedGeneration","signature":"func (b *PodDisruptionBudgetStatusApplyConfiguration) WithObservedGeneration(value int64) *PodDisruptionBudgetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudgetstatus.go","code":"// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObservedGeneration field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetStatusApplyConfiguration) WithObservedGeneration(value int64) *PodDisruptionBudgetStatusApplyConfiguration {\n\tb.ObservedGeneration = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100023947,"name":"WithDisruptedPods","signature":"func (b *PodDisruptionBudgetStatusApplyConfiguration) WithDisruptedPods(entries map[string]v1.Time) *PodDisruptionBudgetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudgetstatus.go","code":"// WithDisruptedPods puts the entries into the DisruptedPods field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the DisruptedPods field,\n// overwriting an existing map entries in DisruptedPods field with the same key.\nfunc (b *PodDisruptionBudgetStatusApplyConfiguration) WithDisruptedPods(entries map[string]v1.Time) *PodDisruptionBudgetStatusApplyConfiguration {\n\tif b.DisruptedPods == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.DisruptedPods = make(map[string]v1.Time, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.DisruptedPods[k] = v\n\t}\n\treturn b\n}","line":{"from":52,"to":64}} {"id":100023948,"name":"WithDisruptionsAllowed","signature":"func (b *PodDisruptionBudgetStatusApplyConfiguration) WithDisruptionsAllowed(value int32) *PodDisruptionBudgetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudgetstatus.go","code":"// WithDisruptionsAllowed sets the DisruptionsAllowed field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DisruptionsAllowed field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetStatusApplyConfiguration) WithDisruptionsAllowed(value int32) *PodDisruptionBudgetStatusApplyConfiguration {\n\tb.DisruptionsAllowed = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100023949,"name":"WithCurrentHealthy","signature":"func (b *PodDisruptionBudgetStatusApplyConfiguration) WithCurrentHealthy(value int32) *PodDisruptionBudgetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudgetstatus.go","code":"// WithCurrentHealthy sets the CurrentHealthy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CurrentHealthy field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetStatusApplyConfiguration) WithCurrentHealthy(value int32) *PodDisruptionBudgetStatusApplyConfiguration {\n\tb.CurrentHealthy = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100023950,"name":"WithDesiredHealthy","signature":"func (b *PodDisruptionBudgetStatusApplyConfiguration) WithDesiredHealthy(value int32) *PodDisruptionBudgetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudgetstatus.go","code":"// WithDesiredHealthy sets the DesiredHealthy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DesiredHealthy field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetStatusApplyConfiguration) WithDesiredHealthy(value int32) *PodDisruptionBudgetStatusApplyConfiguration {\n\tb.DesiredHealthy = \u0026value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100023951,"name":"WithExpectedPods","signature":"func (b *PodDisruptionBudgetStatusApplyConfiguration) WithExpectedPods(value int32) *PodDisruptionBudgetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudgetstatus.go","code":"// WithExpectedPods sets the ExpectedPods field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ExpectedPods field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetStatusApplyConfiguration) WithExpectedPods(value int32) *PodDisruptionBudgetStatusApplyConfiguration {\n\tb.ExpectedPods = \u0026value\n\treturn b\n}","line":{"from":90,"to":96}} {"id":100023952,"name":"WithConditions","signature":"func (b *PodDisruptionBudgetStatusApplyConfiguration) WithConditions(values ...*metav1.ConditionApplyConfiguration) *PodDisruptionBudgetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1/poddisruptionbudgetstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *PodDisruptionBudgetStatusApplyConfiguration) WithConditions(values ...*metav1.ConditionApplyConfiguration) *PodDisruptionBudgetStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":98,"to":109}} {"id":100023953,"name":"AllowedCSIDriver","signature":"func AllowedCSIDriver() *AllowedCSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/allowedcsidriver.go","code":"// AllowedCSIDriverApplyConfiguration constructs an declarative configuration of the AllowedCSIDriver type for use with\n// apply.\nfunc AllowedCSIDriver() *AllowedCSIDriverApplyConfiguration {\n\treturn \u0026AllowedCSIDriverApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023954,"name":"WithName","signature":"func (b *AllowedCSIDriverApplyConfiguration) WithName(value string) *AllowedCSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/allowedcsidriver.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *AllowedCSIDriverApplyConfiguration) WithName(value string) *AllowedCSIDriverApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100023955,"name":"AllowedFlexVolume","signature":"func AllowedFlexVolume() *AllowedFlexVolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/allowedflexvolume.go","code":"// AllowedFlexVolumeApplyConfiguration constructs an declarative configuration of the AllowedFlexVolume type for use with\n// apply.\nfunc AllowedFlexVolume() *AllowedFlexVolumeApplyConfiguration {\n\treturn \u0026AllowedFlexVolumeApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100023956,"name":"WithDriver","signature":"func (b *AllowedFlexVolumeApplyConfiguration) WithDriver(value string) *AllowedFlexVolumeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/allowedflexvolume.go","code":"// WithDriver sets the Driver field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Driver field is set to the value of the last call.\nfunc (b *AllowedFlexVolumeApplyConfiguration) WithDriver(value string) *AllowedFlexVolumeApplyConfiguration {\n\tb.Driver = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100023957,"name":"AllowedHostPath","signature":"func AllowedHostPath() *AllowedHostPathApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/allowedhostpath.go","code":"// AllowedHostPathApplyConfiguration constructs an declarative configuration of the AllowedHostPath type for use with\n// apply.\nfunc AllowedHostPath() *AllowedHostPathApplyConfiguration {\n\treturn \u0026AllowedHostPathApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100023958,"name":"WithPathPrefix","signature":"func (b *AllowedHostPathApplyConfiguration) WithPathPrefix(value string) *AllowedHostPathApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/allowedhostpath.go","code":"// WithPathPrefix sets the PathPrefix field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PathPrefix field is set to the value of the last call.\nfunc (b *AllowedHostPathApplyConfiguration) WithPathPrefix(value string) *AllowedHostPathApplyConfiguration {\n\tb.PathPrefix = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100023959,"name":"WithReadOnly","signature":"func (b *AllowedHostPathApplyConfiguration) WithReadOnly(value bool) *AllowedHostPathApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/allowedhostpath.go","code":"// WithReadOnly sets the ReadOnly field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnly field is set to the value of the last call.\nfunc (b *AllowedHostPathApplyConfiguration) WithReadOnly(value bool) *AllowedHostPathApplyConfiguration {\n\tb.ReadOnly = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100023960,"name":"Eviction","signature":"func Eviction(name, namespace string) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/eviction.go","code":"// Eviction constructs an declarative configuration of the Eviction type for use with\n// apply.\nfunc Eviction(name, namespace string) *EvictionApplyConfiguration {\n\tb := \u0026EvictionApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"Eviction\")\n\tb.WithAPIVersion(\"policy/v1beta1\")\n\treturn b\n}","line":{"from":38,"to":47}} {"id":100023961,"name":"ExtractEviction","signature":"func ExtractEviction(eviction *v1beta1.Eviction, fieldManager string) (*EvictionApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/eviction.go","code":"// ExtractEviction extracts the applied configuration owned by fieldManager from\n// eviction. If no managedFields are found in eviction for fieldManager, a\n// EvictionApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// eviction must be a unmodified Eviction API object that was retrieved from the Kubernetes API.\n// ExtractEviction provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractEviction(eviction *v1beta1.Eviction, fieldManager string) (*EvictionApplyConfiguration, error) {\n\treturn extractEviction(eviction, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100023962,"name":"ExtractEvictionStatus","signature":"func ExtractEvictionStatus(eviction *v1beta1.Eviction, fieldManager string) (*EvictionApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/eviction.go","code":"// ExtractEvictionStatus is the same as ExtractEviction except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractEvictionStatus(eviction *v1beta1.Eviction, fieldManager string) (*EvictionApplyConfiguration, error) {\n\treturn extractEviction(eviction, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100023963,"name":"extractEviction","signature":"func extractEviction(eviction *v1beta1.Eviction, fieldManager string, subresource string) (*EvictionApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/eviction.go","code":"func extractEviction(eviction *v1beta1.Eviction, fieldManager string, subresource string) (*EvictionApplyConfiguration, error) {\n\tb := \u0026EvictionApplyConfiguration{}\n\terr := managedfields.ExtractInto(eviction, internal.Parser().Type(\"io.k8s.api.policy.v1beta1.Eviction\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(eviction.Name)\n\tb.WithNamespace(eviction.Namespace)\n\n\tb.WithKind(\"Eviction\")\n\tb.WithAPIVersion(\"policy/v1beta1\")\n\treturn b, nil\n}","line":{"from":71,"to":83}} {"id":100023964,"name":"WithKind","signature":"func (b *EvictionApplyConfiguration) WithKind(value string) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/eviction.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *EvictionApplyConfiguration) WithKind(value string) *EvictionApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":85,"to":91}} {"id":100023965,"name":"WithAPIVersion","signature":"func (b *EvictionApplyConfiguration) WithAPIVersion(value string) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/eviction.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *EvictionApplyConfiguration) WithAPIVersion(value string) *EvictionApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":93,"to":99}} {"id":100023966,"name":"WithName","signature":"func (b *EvictionApplyConfiguration) WithName(value string) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/eviction.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *EvictionApplyConfiguration) WithName(value string) *EvictionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":101,"to":108}} {"id":100023967,"name":"WithGenerateName","signature":"func (b *EvictionApplyConfiguration) WithGenerateName(value string) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/eviction.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *EvictionApplyConfiguration) WithGenerateName(value string) *EvictionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":110,"to":117}} {"id":100023968,"name":"WithNamespace","signature":"func (b *EvictionApplyConfiguration) WithNamespace(value string) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/eviction.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *EvictionApplyConfiguration) WithNamespace(value string) *EvictionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":119,"to":126}} {"id":100023969,"name":"WithUID","signature":"func (b *EvictionApplyConfiguration) WithUID(value types.UID) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/eviction.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *EvictionApplyConfiguration) WithUID(value types.UID) *EvictionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":128,"to":135}} {"id":100023970,"name":"WithResourceVersion","signature":"func (b *EvictionApplyConfiguration) WithResourceVersion(value string) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/eviction.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *EvictionApplyConfiguration) WithResourceVersion(value string) *EvictionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":137,"to":144}} {"id":100023971,"name":"WithGeneration","signature":"func (b *EvictionApplyConfiguration) WithGeneration(value int64) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/eviction.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *EvictionApplyConfiguration) WithGeneration(value int64) *EvictionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":146,"to":153}} {"id":100023972,"name":"WithCreationTimestamp","signature":"func (b *EvictionApplyConfiguration) WithCreationTimestamp(value metav1.Time) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/eviction.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *EvictionApplyConfiguration) WithCreationTimestamp(value metav1.Time) *EvictionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":155,"to":162}} {"id":100023973,"name":"WithDeletionTimestamp","signature":"func (b *EvictionApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/eviction.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *EvictionApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *EvictionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":164,"to":171}} {"id":100023974,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *EvictionApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/eviction.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *EvictionApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *EvictionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":173,"to":180}} {"id":100023975,"name":"WithLabels","signature":"func (b *EvictionApplyConfiguration) WithLabels(entries map[string]string) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/eviction.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *EvictionApplyConfiguration) WithLabels(entries map[string]string) *EvictionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":182,"to":195}} {"id":100023976,"name":"WithAnnotations","signature":"func (b *EvictionApplyConfiguration) WithAnnotations(entries map[string]string) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/eviction.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *EvictionApplyConfiguration) WithAnnotations(entries map[string]string) *EvictionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":197,"to":210}} {"id":100023977,"name":"WithOwnerReferences","signature":"func (b *EvictionApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/eviction.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *EvictionApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *EvictionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":212,"to":224}} {"id":100023978,"name":"WithFinalizers","signature":"func (b *EvictionApplyConfiguration) WithFinalizers(values ...string) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/eviction.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *EvictionApplyConfiguration) WithFinalizers(values ...string) *EvictionApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":226,"to":235}} {"id":100023979,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *EvictionApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/eviction.go","code":"func (b *EvictionApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":237,"to":241}} {"id":100023980,"name":"WithDeleteOptions","signature":"func (b *EvictionApplyConfiguration) WithDeleteOptions(value *v1.DeleteOptionsApplyConfiguration) *EvictionApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/eviction.go","code":"// WithDeleteOptions sets the DeleteOptions field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeleteOptions field is set to the value of the last call.\nfunc (b *EvictionApplyConfiguration) WithDeleteOptions(value *v1.DeleteOptionsApplyConfiguration) *EvictionApplyConfiguration {\n\tb.DeleteOptions = value\n\treturn b\n}","line":{"from":243,"to":249}} {"id":100023981,"name":"FSGroupStrategyOptions","signature":"func FSGroupStrategyOptions() *FSGroupStrategyOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/fsgroupstrategyoptions.go","code":"// FSGroupStrategyOptionsApplyConfiguration constructs an declarative configuration of the FSGroupStrategyOptions type for use with\n// apply.\nfunc FSGroupStrategyOptions() *FSGroupStrategyOptionsApplyConfiguration {\n\treturn \u0026FSGroupStrategyOptionsApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100023982,"name":"WithRule","signature":"func (b *FSGroupStrategyOptionsApplyConfiguration) WithRule(value v1beta1.FSGroupStrategyType) *FSGroupStrategyOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/fsgroupstrategyoptions.go","code":"// WithRule sets the Rule field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Rule field is set to the value of the last call.\nfunc (b *FSGroupStrategyOptionsApplyConfiguration) WithRule(value v1beta1.FSGroupStrategyType) *FSGroupStrategyOptionsApplyConfiguration {\n\tb.Rule = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100023983,"name":"WithRanges","signature":"func (b *FSGroupStrategyOptionsApplyConfiguration) WithRanges(values ...*IDRangeApplyConfiguration) *FSGroupStrategyOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/fsgroupstrategyoptions.go","code":"// WithRanges adds the given value to the Ranges field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Ranges field.\nfunc (b *FSGroupStrategyOptionsApplyConfiguration) WithRanges(values ...*IDRangeApplyConfiguration) *FSGroupStrategyOptionsApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRanges\")\n\t\t}\n\t\tb.Ranges = append(b.Ranges, *values[i])\n\t}\n\treturn b\n}","line":{"from":46,"to":57}} {"id":100023984,"name":"HostPortRange","signature":"func HostPortRange() *HostPortRangeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/hostportrange.go","code":"// HostPortRangeApplyConfiguration constructs an declarative configuration of the HostPortRange type for use with\n// apply.\nfunc HostPortRange() *HostPortRangeApplyConfiguration {\n\treturn \u0026HostPortRangeApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100023985,"name":"WithMin","signature":"func (b *HostPortRangeApplyConfiguration) WithMin(value int32) *HostPortRangeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/hostportrange.go","code":"// WithMin sets the Min field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Min field is set to the value of the last call.\nfunc (b *HostPortRangeApplyConfiguration) WithMin(value int32) *HostPortRangeApplyConfiguration {\n\tb.Min = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100023986,"name":"WithMax","signature":"func (b *HostPortRangeApplyConfiguration) WithMax(value int32) *HostPortRangeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/hostportrange.go","code":"// WithMax sets the Max field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Max field is set to the value of the last call.\nfunc (b *HostPortRangeApplyConfiguration) WithMax(value int32) *HostPortRangeApplyConfiguration {\n\tb.Max = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100023987,"name":"IDRange","signature":"func IDRange() *IDRangeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/idrange.go","code":"// IDRangeApplyConfiguration constructs an declarative configuration of the IDRange type for use with\n// apply.\nfunc IDRange() *IDRangeApplyConfiguration {\n\treturn \u0026IDRangeApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100023988,"name":"WithMin","signature":"func (b *IDRangeApplyConfiguration) WithMin(value int64) *IDRangeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/idrange.go","code":"// WithMin sets the Min field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Min field is set to the value of the last call.\nfunc (b *IDRangeApplyConfiguration) WithMin(value int64) *IDRangeApplyConfiguration {\n\tb.Min = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100023989,"name":"WithMax","signature":"func (b *IDRangeApplyConfiguration) WithMax(value int64) *IDRangeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/idrange.go","code":"// WithMax sets the Max field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Max field is set to the value of the last call.\nfunc (b *IDRangeApplyConfiguration) WithMax(value int64) *IDRangeApplyConfiguration {\n\tb.Max = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100023990,"name":"PodDisruptionBudget","signature":"func PodDisruptionBudget(name, namespace string) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudget.go","code":"// PodDisruptionBudget constructs an declarative configuration of the PodDisruptionBudget type for use with\n// apply.\nfunc PodDisruptionBudget(name, namespace string) *PodDisruptionBudgetApplyConfiguration {\n\tb := \u0026PodDisruptionBudgetApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"PodDisruptionBudget\")\n\tb.WithAPIVersion(\"policy/v1beta1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100023991,"name":"ExtractPodDisruptionBudget","signature":"func ExtractPodDisruptionBudget(podDisruptionBudget *policyv1beta1.PodDisruptionBudget, fieldManager string) (*PodDisruptionBudgetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudget.go","code":"// ExtractPodDisruptionBudget extracts the applied configuration owned by fieldManager from\n// podDisruptionBudget. If no managedFields are found in podDisruptionBudget for fieldManager, a\n// PodDisruptionBudgetApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// podDisruptionBudget must be a unmodified PodDisruptionBudget API object that was retrieved from the Kubernetes API.\n// ExtractPodDisruptionBudget provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractPodDisruptionBudget(podDisruptionBudget *policyv1beta1.PodDisruptionBudget, fieldManager string) (*PodDisruptionBudgetApplyConfiguration, error) {\n\treturn extractPodDisruptionBudget(podDisruptionBudget, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100023992,"name":"ExtractPodDisruptionBudgetStatus","signature":"func ExtractPodDisruptionBudgetStatus(podDisruptionBudget *policyv1beta1.PodDisruptionBudget, fieldManager string) (*PodDisruptionBudgetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudget.go","code":"// ExtractPodDisruptionBudgetStatus is the same as ExtractPodDisruptionBudget except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractPodDisruptionBudgetStatus(podDisruptionBudget *policyv1beta1.PodDisruptionBudget, fieldManager string) (*PodDisruptionBudgetApplyConfiguration, error) {\n\treturn extractPodDisruptionBudget(podDisruptionBudget, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100023993,"name":"extractPodDisruptionBudget","signature":"func extractPodDisruptionBudget(podDisruptionBudget *policyv1beta1.PodDisruptionBudget, fieldManager string, subresource string) (*PodDisruptionBudgetApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudget.go","code":"func extractPodDisruptionBudget(podDisruptionBudget *policyv1beta1.PodDisruptionBudget, fieldManager string, subresource string) (*PodDisruptionBudgetApplyConfiguration, error) {\n\tb := \u0026PodDisruptionBudgetApplyConfiguration{}\n\terr := managedfields.ExtractInto(podDisruptionBudget, internal.Parser().Type(\"io.k8s.api.policy.v1beta1.PodDisruptionBudget\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(podDisruptionBudget.Name)\n\tb.WithNamespace(podDisruptionBudget.Namespace)\n\n\tb.WithKind(\"PodDisruptionBudget\")\n\tb.WithAPIVersion(\"policy/v1beta1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100023994,"name":"WithKind","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithKind(value string) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudget.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithKind(value string) *PodDisruptionBudgetApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100023995,"name":"WithAPIVersion","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithAPIVersion(value string) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudget.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithAPIVersion(value string) *PodDisruptionBudgetApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100023996,"name":"WithName","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithName(value string) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudget.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithName(value string) *PodDisruptionBudgetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100023997,"name":"WithGenerateName","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithGenerateName(value string) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudget.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithGenerateName(value string) *PodDisruptionBudgetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100023998,"name":"WithNamespace","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithNamespace(value string) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudget.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithNamespace(value string) *PodDisruptionBudgetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100023999,"name":"WithUID","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithUID(value types.UID) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudget.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithUID(value types.UID) *PodDisruptionBudgetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100024000,"name":"WithResourceVersion","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithResourceVersion(value string) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudget.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithResourceVersion(value string) *PodDisruptionBudgetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100024001,"name":"WithGeneration","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithGeneration(value int64) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudget.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithGeneration(value int64) *PodDisruptionBudgetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100024002,"name":"WithCreationTimestamp","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudget.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PodDisruptionBudgetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100024003,"name":"WithDeletionTimestamp","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudget.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PodDisruptionBudgetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100024004,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudget.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PodDisruptionBudgetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100024005,"name":"WithLabels","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithLabels(entries map[string]string) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudget.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithLabels(entries map[string]string) *PodDisruptionBudgetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100024006,"name":"WithAnnotations","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithAnnotations(entries map[string]string) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudget.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithAnnotations(entries map[string]string) *PodDisruptionBudgetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100024007,"name":"WithOwnerReferences","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudget.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PodDisruptionBudgetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100024008,"name":"WithFinalizers","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithFinalizers(values ...string) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudget.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithFinalizers(values ...string) *PodDisruptionBudgetApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100024009,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *PodDisruptionBudgetApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudget.go","code":"func (b *PodDisruptionBudgetApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100024010,"name":"WithSpec","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithSpec(value *PodDisruptionBudgetSpecApplyConfiguration) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudget.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithSpec(value *PodDisruptionBudgetSpecApplyConfiguration) *PodDisruptionBudgetApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100024011,"name":"WithStatus","signature":"func (b *PodDisruptionBudgetApplyConfiguration) WithStatus(value *PodDisruptionBudgetStatusApplyConfiguration) *PodDisruptionBudgetApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudget.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetApplyConfiguration) WithStatus(value *PodDisruptionBudgetStatusApplyConfiguration) *PodDisruptionBudgetApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100024012,"name":"PodDisruptionBudgetSpec","signature":"func PodDisruptionBudgetSpec() *PodDisruptionBudgetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudgetspec.go","code":"// PodDisruptionBudgetSpecApplyConfiguration constructs an declarative configuration of the PodDisruptionBudgetSpec type for use with\n// apply.\nfunc PodDisruptionBudgetSpec() *PodDisruptionBudgetSpecApplyConfiguration {\n\treturn \u0026PodDisruptionBudgetSpecApplyConfiguration{}\n}","line":{"from":36,"to":40}} {"id":100024013,"name":"WithMinAvailable","signature":"func (b *PodDisruptionBudgetSpecApplyConfiguration) WithMinAvailable(value intstr.IntOrString) *PodDisruptionBudgetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudgetspec.go","code":"// WithMinAvailable sets the MinAvailable field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MinAvailable field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetSpecApplyConfiguration) WithMinAvailable(value intstr.IntOrString) *PodDisruptionBudgetSpecApplyConfiguration {\n\tb.MinAvailable = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100024014,"name":"WithSelector","signature":"func (b *PodDisruptionBudgetSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *PodDisruptionBudgetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudgetspec.go","code":"// WithSelector sets the Selector field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Selector field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetSpecApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *PodDisruptionBudgetSpecApplyConfiguration {\n\tb.Selector = value\n\treturn b\n}","line":{"from":50,"to":56}} {"id":100024015,"name":"WithMaxUnavailable","signature":"func (b *PodDisruptionBudgetSpecApplyConfiguration) WithMaxUnavailable(value intstr.IntOrString) *PodDisruptionBudgetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudgetspec.go","code":"// WithMaxUnavailable sets the MaxUnavailable field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MaxUnavailable field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetSpecApplyConfiguration) WithMaxUnavailable(value intstr.IntOrString) *PodDisruptionBudgetSpecApplyConfiguration {\n\tb.MaxUnavailable = \u0026value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100024016,"name":"WithUnhealthyPodEvictionPolicy","signature":"func (b *PodDisruptionBudgetSpecApplyConfiguration) WithUnhealthyPodEvictionPolicy(value v1beta1.UnhealthyPodEvictionPolicyType) *PodDisruptionBudgetSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudgetspec.go","code":"// WithUnhealthyPodEvictionPolicy sets the UnhealthyPodEvictionPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UnhealthyPodEvictionPolicy field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetSpecApplyConfiguration) WithUnhealthyPodEvictionPolicy(value v1beta1.UnhealthyPodEvictionPolicyType) *PodDisruptionBudgetSpecApplyConfiguration {\n\tb.UnhealthyPodEvictionPolicy = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100024017,"name":"PodDisruptionBudgetStatus","signature":"func PodDisruptionBudgetStatus() *PodDisruptionBudgetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudgetstatus.go","code":"// PodDisruptionBudgetStatusApplyConfiguration constructs an declarative configuration of the PodDisruptionBudgetStatus type for use with\n// apply.\nfunc PodDisruptionBudgetStatus() *PodDisruptionBudgetStatusApplyConfiguration {\n\treturn \u0026PodDisruptionBudgetStatusApplyConfiguration{}\n}","line":{"from":38,"to":42}} {"id":100024018,"name":"WithObservedGeneration","signature":"func (b *PodDisruptionBudgetStatusApplyConfiguration) WithObservedGeneration(value int64) *PodDisruptionBudgetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudgetstatus.go","code":"// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ObservedGeneration field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetStatusApplyConfiguration) WithObservedGeneration(value int64) *PodDisruptionBudgetStatusApplyConfiguration {\n\tb.ObservedGeneration = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100024019,"name":"WithDisruptedPods","signature":"func (b *PodDisruptionBudgetStatusApplyConfiguration) WithDisruptedPods(entries map[string]v1.Time) *PodDisruptionBudgetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudgetstatus.go","code":"// WithDisruptedPods puts the entries into the DisruptedPods field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the DisruptedPods field,\n// overwriting an existing map entries in DisruptedPods field with the same key.\nfunc (b *PodDisruptionBudgetStatusApplyConfiguration) WithDisruptedPods(entries map[string]v1.Time) *PodDisruptionBudgetStatusApplyConfiguration {\n\tif b.DisruptedPods == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.DisruptedPods = make(map[string]v1.Time, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.DisruptedPods[k] = v\n\t}\n\treturn b\n}","line":{"from":52,"to":64}} {"id":100024020,"name":"WithDisruptionsAllowed","signature":"func (b *PodDisruptionBudgetStatusApplyConfiguration) WithDisruptionsAllowed(value int32) *PodDisruptionBudgetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudgetstatus.go","code":"// WithDisruptionsAllowed sets the DisruptionsAllowed field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DisruptionsAllowed field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetStatusApplyConfiguration) WithDisruptionsAllowed(value int32) *PodDisruptionBudgetStatusApplyConfiguration {\n\tb.DisruptionsAllowed = \u0026value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100024021,"name":"WithCurrentHealthy","signature":"func (b *PodDisruptionBudgetStatusApplyConfiguration) WithCurrentHealthy(value int32) *PodDisruptionBudgetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudgetstatus.go","code":"// WithCurrentHealthy sets the CurrentHealthy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CurrentHealthy field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetStatusApplyConfiguration) WithCurrentHealthy(value int32) *PodDisruptionBudgetStatusApplyConfiguration {\n\tb.CurrentHealthy = \u0026value\n\treturn b\n}","line":{"from":74,"to":80}} {"id":100024022,"name":"WithDesiredHealthy","signature":"func (b *PodDisruptionBudgetStatusApplyConfiguration) WithDesiredHealthy(value int32) *PodDisruptionBudgetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudgetstatus.go","code":"// WithDesiredHealthy sets the DesiredHealthy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DesiredHealthy field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetStatusApplyConfiguration) WithDesiredHealthy(value int32) *PodDisruptionBudgetStatusApplyConfiguration {\n\tb.DesiredHealthy = \u0026value\n\treturn b\n}","line":{"from":82,"to":88}} {"id":100024023,"name":"WithExpectedPods","signature":"func (b *PodDisruptionBudgetStatusApplyConfiguration) WithExpectedPods(value int32) *PodDisruptionBudgetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudgetstatus.go","code":"// WithExpectedPods sets the ExpectedPods field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ExpectedPods field is set to the value of the last call.\nfunc (b *PodDisruptionBudgetStatusApplyConfiguration) WithExpectedPods(value int32) *PodDisruptionBudgetStatusApplyConfiguration {\n\tb.ExpectedPods = \u0026value\n\treturn b\n}","line":{"from":90,"to":96}} {"id":100024024,"name":"WithConditions","signature":"func (b *PodDisruptionBudgetStatusApplyConfiguration) WithConditions(values ...*metav1.ConditionApplyConfiguration) *PodDisruptionBudgetStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/poddisruptionbudgetstatus.go","code":"// WithConditions adds the given value to the Conditions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Conditions field.\nfunc (b *PodDisruptionBudgetStatusApplyConfiguration) WithConditions(values ...*metav1.ConditionApplyConfiguration) *PodDisruptionBudgetStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithConditions\")\n\t\t}\n\t\tb.Conditions = append(b.Conditions, *values[i])\n\t}\n\treturn b\n}","line":{"from":98,"to":109}} {"id":100024025,"name":"PodSecurityPolicy","signature":"func PodSecurityPolicy(name string) *PodSecurityPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicy.go","code":"// PodSecurityPolicy constructs an declarative configuration of the PodSecurityPolicy type for use with\n// apply.\nfunc PodSecurityPolicy(name string) *PodSecurityPolicyApplyConfiguration {\n\tb := \u0026PodSecurityPolicyApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"PodSecurityPolicy\")\n\tb.WithAPIVersion(\"policy/v1beta1\")\n\treturn b\n}","line":{"from":38,"to":46}} {"id":100024026,"name":"ExtractPodSecurityPolicy","signature":"func ExtractPodSecurityPolicy(podSecurityPolicy *policyv1beta1.PodSecurityPolicy, fieldManager string) (*PodSecurityPolicyApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicy.go","code":"// ExtractPodSecurityPolicy extracts the applied configuration owned by fieldManager from\n// podSecurityPolicy. If no managedFields are found in podSecurityPolicy for fieldManager, a\n// PodSecurityPolicyApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// podSecurityPolicy must be a unmodified PodSecurityPolicy API object that was retrieved from the Kubernetes API.\n// ExtractPodSecurityPolicy provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractPodSecurityPolicy(podSecurityPolicy *policyv1beta1.PodSecurityPolicy, fieldManager string) (*PodSecurityPolicyApplyConfiguration, error) {\n\treturn extractPodSecurityPolicy(podSecurityPolicy, fieldManager, \"\")\n}","line":{"from":48,"to":61}} {"id":100024027,"name":"ExtractPodSecurityPolicyStatus","signature":"func ExtractPodSecurityPolicyStatus(podSecurityPolicy *policyv1beta1.PodSecurityPolicy, fieldManager string) (*PodSecurityPolicyApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicy.go","code":"// ExtractPodSecurityPolicyStatus is the same as ExtractPodSecurityPolicy except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractPodSecurityPolicyStatus(podSecurityPolicy *policyv1beta1.PodSecurityPolicy, fieldManager string) (*PodSecurityPolicyApplyConfiguration, error) {\n\treturn extractPodSecurityPolicy(podSecurityPolicy, fieldManager, \"status\")\n}","line":{"from":63,"to":68}} {"id":100024028,"name":"extractPodSecurityPolicy","signature":"func extractPodSecurityPolicy(podSecurityPolicy *policyv1beta1.PodSecurityPolicy, fieldManager string, subresource string) (*PodSecurityPolicyApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicy.go","code":"func extractPodSecurityPolicy(podSecurityPolicy *policyv1beta1.PodSecurityPolicy, fieldManager string, subresource string) (*PodSecurityPolicyApplyConfiguration, error) {\n\tb := \u0026PodSecurityPolicyApplyConfiguration{}\n\terr := managedfields.ExtractInto(podSecurityPolicy, internal.Parser().Type(\"io.k8s.api.policy.v1beta1.PodSecurityPolicy\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(podSecurityPolicy.Name)\n\n\tb.WithKind(\"PodSecurityPolicy\")\n\tb.WithAPIVersion(\"policy/v1beta1\")\n\treturn b, nil\n}","line":{"from":70,"to":81}} {"id":100024029,"name":"WithKind","signature":"func (b *PodSecurityPolicyApplyConfiguration) WithKind(value string) *PodSecurityPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicy.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *PodSecurityPolicyApplyConfiguration) WithKind(value string) *PodSecurityPolicyApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100024030,"name":"WithAPIVersion","signature":"func (b *PodSecurityPolicyApplyConfiguration) WithAPIVersion(value string) *PodSecurityPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicy.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *PodSecurityPolicyApplyConfiguration) WithAPIVersion(value string) *PodSecurityPolicyApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":91,"to":97}} {"id":100024031,"name":"WithName","signature":"func (b *PodSecurityPolicyApplyConfiguration) WithName(value string) *PodSecurityPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicy.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *PodSecurityPolicyApplyConfiguration) WithName(value string) *PodSecurityPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":99,"to":106}} {"id":100024032,"name":"WithGenerateName","signature":"func (b *PodSecurityPolicyApplyConfiguration) WithGenerateName(value string) *PodSecurityPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicy.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *PodSecurityPolicyApplyConfiguration) WithGenerateName(value string) *PodSecurityPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":108,"to":115}} {"id":100024033,"name":"WithNamespace","signature":"func (b *PodSecurityPolicyApplyConfiguration) WithNamespace(value string) *PodSecurityPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicy.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *PodSecurityPolicyApplyConfiguration) WithNamespace(value string) *PodSecurityPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":117,"to":124}} {"id":100024034,"name":"WithUID","signature":"func (b *PodSecurityPolicyApplyConfiguration) WithUID(value types.UID) *PodSecurityPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicy.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *PodSecurityPolicyApplyConfiguration) WithUID(value types.UID) *PodSecurityPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":126,"to":133}} {"id":100024035,"name":"WithResourceVersion","signature":"func (b *PodSecurityPolicyApplyConfiguration) WithResourceVersion(value string) *PodSecurityPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicy.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *PodSecurityPolicyApplyConfiguration) WithResourceVersion(value string) *PodSecurityPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":135,"to":142}} {"id":100024036,"name":"WithGeneration","signature":"func (b *PodSecurityPolicyApplyConfiguration) WithGeneration(value int64) *PodSecurityPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicy.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *PodSecurityPolicyApplyConfiguration) WithGeneration(value int64) *PodSecurityPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":144,"to":151}} {"id":100024037,"name":"WithCreationTimestamp","signature":"func (b *PodSecurityPolicyApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PodSecurityPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicy.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *PodSecurityPolicyApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PodSecurityPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":153,"to":160}} {"id":100024038,"name":"WithDeletionTimestamp","signature":"func (b *PodSecurityPolicyApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PodSecurityPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicy.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *PodSecurityPolicyApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PodSecurityPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":162,"to":169}} {"id":100024039,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *PodSecurityPolicyApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PodSecurityPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicy.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *PodSecurityPolicyApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PodSecurityPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":171,"to":178}} {"id":100024040,"name":"WithLabels","signature":"func (b *PodSecurityPolicyApplyConfiguration) WithLabels(entries map[string]string) *PodSecurityPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicy.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *PodSecurityPolicyApplyConfiguration) WithLabels(entries map[string]string) *PodSecurityPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":180,"to":193}} {"id":100024041,"name":"WithAnnotations","signature":"func (b *PodSecurityPolicyApplyConfiguration) WithAnnotations(entries map[string]string) *PodSecurityPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicy.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *PodSecurityPolicyApplyConfiguration) WithAnnotations(entries map[string]string) *PodSecurityPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":195,"to":208}} {"id":100024042,"name":"WithOwnerReferences","signature":"func (b *PodSecurityPolicyApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PodSecurityPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicy.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *PodSecurityPolicyApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PodSecurityPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":210,"to":222}} {"id":100024043,"name":"WithFinalizers","signature":"func (b *PodSecurityPolicyApplyConfiguration) WithFinalizers(values ...string) *PodSecurityPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicy.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *PodSecurityPolicyApplyConfiguration) WithFinalizers(values ...string) *PodSecurityPolicyApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":224,"to":233}} {"id":100024044,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *PodSecurityPolicyApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicy.go","code":"func (b *PodSecurityPolicyApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":235,"to":239}} {"id":100024045,"name":"WithSpec","signature":"func (b *PodSecurityPolicyApplyConfiguration) WithSpec(value *PodSecurityPolicySpecApplyConfiguration) *PodSecurityPolicyApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicy.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *PodSecurityPolicyApplyConfiguration) WithSpec(value *PodSecurityPolicySpecApplyConfiguration) *PodSecurityPolicyApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":241,"to":247}} {"id":100024046,"name":"PodSecurityPolicySpec","signature":"func PodSecurityPolicySpec() *PodSecurityPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicyspec.go","code":"// PodSecurityPolicySpecApplyConfiguration constructs an declarative configuration of the PodSecurityPolicySpec type for use with\n// apply.\nfunc PodSecurityPolicySpec() *PodSecurityPolicySpecApplyConfiguration {\n\treturn \u0026PodSecurityPolicySpecApplyConfiguration{}\n}","line":{"from":55,"to":59}} {"id":100024047,"name":"WithPrivileged","signature":"func (b *PodSecurityPolicySpecApplyConfiguration) WithPrivileged(value bool) *PodSecurityPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicyspec.go","code":"// WithPrivileged sets the Privileged field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Privileged field is set to the value of the last call.\nfunc (b *PodSecurityPolicySpecApplyConfiguration) WithPrivileged(value bool) *PodSecurityPolicySpecApplyConfiguration {\n\tb.Privileged = \u0026value\n\treturn b\n}","line":{"from":61,"to":67}} {"id":100024048,"name":"WithDefaultAddCapabilities","signature":"func (b *PodSecurityPolicySpecApplyConfiguration) WithDefaultAddCapabilities(values ...v1.Capability) *PodSecurityPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicyspec.go","code":"// WithDefaultAddCapabilities adds the given value to the DefaultAddCapabilities field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the DefaultAddCapabilities field.\nfunc (b *PodSecurityPolicySpecApplyConfiguration) WithDefaultAddCapabilities(values ...v1.Capability) *PodSecurityPolicySpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.DefaultAddCapabilities = append(b.DefaultAddCapabilities, values[i])\n\t}\n\treturn b\n}","line":{"from":69,"to":77}} {"id":100024049,"name":"WithRequiredDropCapabilities","signature":"func (b *PodSecurityPolicySpecApplyConfiguration) WithRequiredDropCapabilities(values ...v1.Capability) *PodSecurityPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicyspec.go","code":"// WithRequiredDropCapabilities adds the given value to the RequiredDropCapabilities field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the RequiredDropCapabilities field.\nfunc (b *PodSecurityPolicySpecApplyConfiguration) WithRequiredDropCapabilities(values ...v1.Capability) *PodSecurityPolicySpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.RequiredDropCapabilities = append(b.RequiredDropCapabilities, values[i])\n\t}\n\treturn b\n}","line":{"from":79,"to":87}} {"id":100024050,"name":"WithAllowedCapabilities","signature":"func (b *PodSecurityPolicySpecApplyConfiguration) WithAllowedCapabilities(values ...v1.Capability) *PodSecurityPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicyspec.go","code":"// WithAllowedCapabilities adds the given value to the AllowedCapabilities field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the AllowedCapabilities field.\nfunc (b *PodSecurityPolicySpecApplyConfiguration) WithAllowedCapabilities(values ...v1.Capability) *PodSecurityPolicySpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.AllowedCapabilities = append(b.AllowedCapabilities, values[i])\n\t}\n\treturn b\n}","line":{"from":89,"to":97}} {"id":100024051,"name":"WithVolumes","signature":"func (b *PodSecurityPolicySpecApplyConfiguration) WithVolumes(values ...v1beta1.FSType) *PodSecurityPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicyspec.go","code":"// WithVolumes adds the given value to the Volumes field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Volumes field.\nfunc (b *PodSecurityPolicySpecApplyConfiguration) WithVolumes(values ...v1beta1.FSType) *PodSecurityPolicySpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.Volumes = append(b.Volumes, values[i])\n\t}\n\treturn b\n}","line":{"from":99,"to":107}} {"id":100024052,"name":"WithHostNetwork","signature":"func (b *PodSecurityPolicySpecApplyConfiguration) WithHostNetwork(value bool) *PodSecurityPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicyspec.go","code":"// WithHostNetwork sets the HostNetwork field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HostNetwork field is set to the value of the last call.\nfunc (b *PodSecurityPolicySpecApplyConfiguration) WithHostNetwork(value bool) *PodSecurityPolicySpecApplyConfiguration {\n\tb.HostNetwork = \u0026value\n\treturn b\n}","line":{"from":109,"to":115}} {"id":100024053,"name":"WithHostPorts","signature":"func (b *PodSecurityPolicySpecApplyConfiguration) WithHostPorts(values ...*HostPortRangeApplyConfiguration) *PodSecurityPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicyspec.go","code":"// WithHostPorts adds the given value to the HostPorts field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the HostPorts field.\nfunc (b *PodSecurityPolicySpecApplyConfiguration) WithHostPorts(values ...*HostPortRangeApplyConfiguration) *PodSecurityPolicySpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithHostPorts\")\n\t\t}\n\t\tb.HostPorts = append(b.HostPorts, *values[i])\n\t}\n\treturn b\n}","line":{"from":117,"to":128}} {"id":100024054,"name":"WithHostPID","signature":"func (b *PodSecurityPolicySpecApplyConfiguration) WithHostPID(value bool) *PodSecurityPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicyspec.go","code":"// WithHostPID sets the HostPID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HostPID field is set to the value of the last call.\nfunc (b *PodSecurityPolicySpecApplyConfiguration) WithHostPID(value bool) *PodSecurityPolicySpecApplyConfiguration {\n\tb.HostPID = \u0026value\n\treturn b\n}","line":{"from":130,"to":136}} {"id":100024055,"name":"WithHostIPC","signature":"func (b *PodSecurityPolicySpecApplyConfiguration) WithHostIPC(value bool) *PodSecurityPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicyspec.go","code":"// WithHostIPC sets the HostIPC field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the HostIPC field is set to the value of the last call.\nfunc (b *PodSecurityPolicySpecApplyConfiguration) WithHostIPC(value bool) *PodSecurityPolicySpecApplyConfiguration {\n\tb.HostIPC = \u0026value\n\treturn b\n}","line":{"from":138,"to":144}} {"id":100024056,"name":"WithSELinux","signature":"func (b *PodSecurityPolicySpecApplyConfiguration) WithSELinux(value *SELinuxStrategyOptionsApplyConfiguration) *PodSecurityPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicyspec.go","code":"// WithSELinux sets the SELinux field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SELinux field is set to the value of the last call.\nfunc (b *PodSecurityPolicySpecApplyConfiguration) WithSELinux(value *SELinuxStrategyOptionsApplyConfiguration) *PodSecurityPolicySpecApplyConfiguration {\n\tb.SELinux = value\n\treturn b\n}","line":{"from":146,"to":152}} {"id":100024057,"name":"WithRunAsUser","signature":"func (b *PodSecurityPolicySpecApplyConfiguration) WithRunAsUser(value *RunAsUserStrategyOptionsApplyConfiguration) *PodSecurityPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicyspec.go","code":"// WithRunAsUser sets the RunAsUser field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RunAsUser field is set to the value of the last call.\nfunc (b *PodSecurityPolicySpecApplyConfiguration) WithRunAsUser(value *RunAsUserStrategyOptionsApplyConfiguration) *PodSecurityPolicySpecApplyConfiguration {\n\tb.RunAsUser = value\n\treturn b\n}","line":{"from":154,"to":160}} {"id":100024058,"name":"WithRunAsGroup","signature":"func (b *PodSecurityPolicySpecApplyConfiguration) WithRunAsGroup(value *RunAsGroupStrategyOptionsApplyConfiguration) *PodSecurityPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicyspec.go","code":"// WithRunAsGroup sets the RunAsGroup field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RunAsGroup field is set to the value of the last call.\nfunc (b *PodSecurityPolicySpecApplyConfiguration) WithRunAsGroup(value *RunAsGroupStrategyOptionsApplyConfiguration) *PodSecurityPolicySpecApplyConfiguration {\n\tb.RunAsGroup = value\n\treturn b\n}","line":{"from":162,"to":168}} {"id":100024059,"name":"WithSupplementalGroups","signature":"func (b *PodSecurityPolicySpecApplyConfiguration) WithSupplementalGroups(value *SupplementalGroupsStrategyOptionsApplyConfiguration) *PodSecurityPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicyspec.go","code":"// WithSupplementalGroups sets the SupplementalGroups field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SupplementalGroups field is set to the value of the last call.\nfunc (b *PodSecurityPolicySpecApplyConfiguration) WithSupplementalGroups(value *SupplementalGroupsStrategyOptionsApplyConfiguration) *PodSecurityPolicySpecApplyConfiguration {\n\tb.SupplementalGroups = value\n\treturn b\n}","line":{"from":170,"to":176}} {"id":100024060,"name":"WithFSGroup","signature":"func (b *PodSecurityPolicySpecApplyConfiguration) WithFSGroup(value *FSGroupStrategyOptionsApplyConfiguration) *PodSecurityPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicyspec.go","code":"// WithFSGroup sets the FSGroup field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSGroup field is set to the value of the last call.\nfunc (b *PodSecurityPolicySpecApplyConfiguration) WithFSGroup(value *FSGroupStrategyOptionsApplyConfiguration) *PodSecurityPolicySpecApplyConfiguration {\n\tb.FSGroup = value\n\treturn b\n}","line":{"from":178,"to":184}} {"id":100024061,"name":"WithReadOnlyRootFilesystem","signature":"func (b *PodSecurityPolicySpecApplyConfiguration) WithReadOnlyRootFilesystem(value bool) *PodSecurityPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicyspec.go","code":"// WithReadOnlyRootFilesystem sets the ReadOnlyRootFilesystem field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReadOnlyRootFilesystem field is set to the value of the last call.\nfunc (b *PodSecurityPolicySpecApplyConfiguration) WithReadOnlyRootFilesystem(value bool) *PodSecurityPolicySpecApplyConfiguration {\n\tb.ReadOnlyRootFilesystem = \u0026value\n\treturn b\n}","line":{"from":186,"to":192}} {"id":100024062,"name":"WithDefaultAllowPrivilegeEscalation","signature":"func (b *PodSecurityPolicySpecApplyConfiguration) WithDefaultAllowPrivilegeEscalation(value bool) *PodSecurityPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicyspec.go","code":"// WithDefaultAllowPrivilegeEscalation sets the DefaultAllowPrivilegeEscalation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DefaultAllowPrivilegeEscalation field is set to the value of the last call.\nfunc (b *PodSecurityPolicySpecApplyConfiguration) WithDefaultAllowPrivilegeEscalation(value bool) *PodSecurityPolicySpecApplyConfiguration {\n\tb.DefaultAllowPrivilegeEscalation = \u0026value\n\treturn b\n}","line":{"from":194,"to":200}} {"id":100024063,"name":"WithAllowPrivilegeEscalation","signature":"func (b *PodSecurityPolicySpecApplyConfiguration) WithAllowPrivilegeEscalation(value bool) *PodSecurityPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicyspec.go","code":"// WithAllowPrivilegeEscalation sets the AllowPrivilegeEscalation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AllowPrivilegeEscalation field is set to the value of the last call.\nfunc (b *PodSecurityPolicySpecApplyConfiguration) WithAllowPrivilegeEscalation(value bool) *PodSecurityPolicySpecApplyConfiguration {\n\tb.AllowPrivilegeEscalation = \u0026value\n\treturn b\n}","line":{"from":202,"to":208}} {"id":100024064,"name":"WithAllowedHostPaths","signature":"func (b *PodSecurityPolicySpecApplyConfiguration) WithAllowedHostPaths(values ...*AllowedHostPathApplyConfiguration) *PodSecurityPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicyspec.go","code":"// WithAllowedHostPaths adds the given value to the AllowedHostPaths field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the AllowedHostPaths field.\nfunc (b *PodSecurityPolicySpecApplyConfiguration) WithAllowedHostPaths(values ...*AllowedHostPathApplyConfiguration) *PodSecurityPolicySpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithAllowedHostPaths\")\n\t\t}\n\t\tb.AllowedHostPaths = append(b.AllowedHostPaths, *values[i])\n\t}\n\treturn b\n}","line":{"from":210,"to":221}} {"id":100024065,"name":"WithAllowedFlexVolumes","signature":"func (b *PodSecurityPolicySpecApplyConfiguration) WithAllowedFlexVolumes(values ...*AllowedFlexVolumeApplyConfiguration) *PodSecurityPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicyspec.go","code":"// WithAllowedFlexVolumes adds the given value to the AllowedFlexVolumes field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the AllowedFlexVolumes field.\nfunc (b *PodSecurityPolicySpecApplyConfiguration) WithAllowedFlexVolumes(values ...*AllowedFlexVolumeApplyConfiguration) *PodSecurityPolicySpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithAllowedFlexVolumes\")\n\t\t}\n\t\tb.AllowedFlexVolumes = append(b.AllowedFlexVolumes, *values[i])\n\t}\n\treturn b\n}","line":{"from":223,"to":234}} {"id":100024066,"name":"WithAllowedCSIDrivers","signature":"func (b *PodSecurityPolicySpecApplyConfiguration) WithAllowedCSIDrivers(values ...*AllowedCSIDriverApplyConfiguration) *PodSecurityPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicyspec.go","code":"// WithAllowedCSIDrivers adds the given value to the AllowedCSIDrivers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the AllowedCSIDrivers field.\nfunc (b *PodSecurityPolicySpecApplyConfiguration) WithAllowedCSIDrivers(values ...*AllowedCSIDriverApplyConfiguration) *PodSecurityPolicySpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithAllowedCSIDrivers\")\n\t\t}\n\t\tb.AllowedCSIDrivers = append(b.AllowedCSIDrivers, *values[i])\n\t}\n\treturn b\n}","line":{"from":236,"to":247}} {"id":100024067,"name":"WithAllowedUnsafeSysctls","signature":"func (b *PodSecurityPolicySpecApplyConfiguration) WithAllowedUnsafeSysctls(values ...string) *PodSecurityPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicyspec.go","code":"// WithAllowedUnsafeSysctls adds the given value to the AllowedUnsafeSysctls field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the AllowedUnsafeSysctls field.\nfunc (b *PodSecurityPolicySpecApplyConfiguration) WithAllowedUnsafeSysctls(values ...string) *PodSecurityPolicySpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.AllowedUnsafeSysctls = append(b.AllowedUnsafeSysctls, values[i])\n\t}\n\treturn b\n}","line":{"from":249,"to":257}} {"id":100024068,"name":"WithForbiddenSysctls","signature":"func (b *PodSecurityPolicySpecApplyConfiguration) WithForbiddenSysctls(values ...string) *PodSecurityPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicyspec.go","code":"// WithForbiddenSysctls adds the given value to the ForbiddenSysctls field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ForbiddenSysctls field.\nfunc (b *PodSecurityPolicySpecApplyConfiguration) WithForbiddenSysctls(values ...string) *PodSecurityPolicySpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.ForbiddenSysctls = append(b.ForbiddenSysctls, values[i])\n\t}\n\treturn b\n}","line":{"from":259,"to":267}} {"id":100024069,"name":"WithAllowedProcMountTypes","signature":"func (b *PodSecurityPolicySpecApplyConfiguration) WithAllowedProcMountTypes(values ...v1.ProcMountType) *PodSecurityPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicyspec.go","code":"// WithAllowedProcMountTypes adds the given value to the AllowedProcMountTypes field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the AllowedProcMountTypes field.\nfunc (b *PodSecurityPolicySpecApplyConfiguration) WithAllowedProcMountTypes(values ...v1.ProcMountType) *PodSecurityPolicySpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.AllowedProcMountTypes = append(b.AllowedProcMountTypes, values[i])\n\t}\n\treturn b\n}","line":{"from":269,"to":277}} {"id":100024070,"name":"WithRuntimeClass","signature":"func (b *PodSecurityPolicySpecApplyConfiguration) WithRuntimeClass(value *RuntimeClassStrategyOptionsApplyConfiguration) *PodSecurityPolicySpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/podsecuritypolicyspec.go","code":"// WithRuntimeClass sets the RuntimeClass field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RuntimeClass field is set to the value of the last call.\nfunc (b *PodSecurityPolicySpecApplyConfiguration) WithRuntimeClass(value *RuntimeClassStrategyOptionsApplyConfiguration) *PodSecurityPolicySpecApplyConfiguration {\n\tb.RuntimeClass = value\n\treturn b\n}","line":{"from":279,"to":285}} {"id":100024071,"name":"RunAsGroupStrategyOptions","signature":"func RunAsGroupStrategyOptions() *RunAsGroupStrategyOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/runasgroupstrategyoptions.go","code":"// RunAsGroupStrategyOptionsApplyConfiguration constructs an declarative configuration of the RunAsGroupStrategyOptions type for use with\n// apply.\nfunc RunAsGroupStrategyOptions() *RunAsGroupStrategyOptionsApplyConfiguration {\n\treturn \u0026RunAsGroupStrategyOptionsApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100024072,"name":"WithRule","signature":"func (b *RunAsGroupStrategyOptionsApplyConfiguration) WithRule(value v1beta1.RunAsGroupStrategy) *RunAsGroupStrategyOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/runasgroupstrategyoptions.go","code":"// WithRule sets the Rule field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Rule field is set to the value of the last call.\nfunc (b *RunAsGroupStrategyOptionsApplyConfiguration) WithRule(value v1beta1.RunAsGroupStrategy) *RunAsGroupStrategyOptionsApplyConfiguration {\n\tb.Rule = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100024073,"name":"WithRanges","signature":"func (b *RunAsGroupStrategyOptionsApplyConfiguration) WithRanges(values ...*IDRangeApplyConfiguration) *RunAsGroupStrategyOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/runasgroupstrategyoptions.go","code":"// WithRanges adds the given value to the Ranges field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Ranges field.\nfunc (b *RunAsGroupStrategyOptionsApplyConfiguration) WithRanges(values ...*IDRangeApplyConfiguration) *RunAsGroupStrategyOptionsApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRanges\")\n\t\t}\n\t\tb.Ranges = append(b.Ranges, *values[i])\n\t}\n\treturn b\n}","line":{"from":46,"to":57}} {"id":100024074,"name":"RunAsUserStrategyOptions","signature":"func RunAsUserStrategyOptions() *RunAsUserStrategyOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/runasuserstrategyoptions.go","code":"// RunAsUserStrategyOptionsApplyConfiguration constructs an declarative configuration of the RunAsUserStrategyOptions type for use with\n// apply.\nfunc RunAsUserStrategyOptions() *RunAsUserStrategyOptionsApplyConfiguration {\n\treturn \u0026RunAsUserStrategyOptionsApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100024075,"name":"WithRule","signature":"func (b *RunAsUserStrategyOptionsApplyConfiguration) WithRule(value v1beta1.RunAsUserStrategy) *RunAsUserStrategyOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/runasuserstrategyoptions.go","code":"// WithRule sets the Rule field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Rule field is set to the value of the last call.\nfunc (b *RunAsUserStrategyOptionsApplyConfiguration) WithRule(value v1beta1.RunAsUserStrategy) *RunAsUserStrategyOptionsApplyConfiguration {\n\tb.Rule = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100024076,"name":"WithRanges","signature":"func (b *RunAsUserStrategyOptionsApplyConfiguration) WithRanges(values ...*IDRangeApplyConfiguration) *RunAsUserStrategyOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/runasuserstrategyoptions.go","code":"// WithRanges adds the given value to the Ranges field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Ranges field.\nfunc (b *RunAsUserStrategyOptionsApplyConfiguration) WithRanges(values ...*IDRangeApplyConfiguration) *RunAsUserStrategyOptionsApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRanges\")\n\t\t}\n\t\tb.Ranges = append(b.Ranges, *values[i])\n\t}\n\treturn b\n}","line":{"from":46,"to":57}} {"id":100024077,"name":"RuntimeClassStrategyOptions","signature":"func RuntimeClassStrategyOptions() *RuntimeClassStrategyOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/runtimeclassstrategyoptions.go","code":"// RuntimeClassStrategyOptionsApplyConfiguration constructs an declarative configuration of the RuntimeClassStrategyOptions type for use with\n// apply.\nfunc RuntimeClassStrategyOptions() *RuntimeClassStrategyOptionsApplyConfiguration {\n\treturn \u0026RuntimeClassStrategyOptionsApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100024078,"name":"WithAllowedRuntimeClassNames","signature":"func (b *RuntimeClassStrategyOptionsApplyConfiguration) WithAllowedRuntimeClassNames(values ...string) *RuntimeClassStrategyOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/runtimeclassstrategyoptions.go","code":"// WithAllowedRuntimeClassNames adds the given value to the AllowedRuntimeClassNames field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the AllowedRuntimeClassNames field.\nfunc (b *RuntimeClassStrategyOptionsApplyConfiguration) WithAllowedRuntimeClassNames(values ...string) *RuntimeClassStrategyOptionsApplyConfiguration {\n\tfor i := range values {\n\t\tb.AllowedRuntimeClassNames = append(b.AllowedRuntimeClassNames, values[i])\n\t}\n\treturn b\n}","line":{"from":34,"to":42}} {"id":100024079,"name":"WithDefaultRuntimeClassName","signature":"func (b *RuntimeClassStrategyOptionsApplyConfiguration) WithDefaultRuntimeClassName(value string) *RuntimeClassStrategyOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/runtimeclassstrategyoptions.go","code":"// WithDefaultRuntimeClassName sets the DefaultRuntimeClassName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DefaultRuntimeClassName field is set to the value of the last call.\nfunc (b *RuntimeClassStrategyOptionsApplyConfiguration) WithDefaultRuntimeClassName(value string) *RuntimeClassStrategyOptionsApplyConfiguration {\n\tb.DefaultRuntimeClassName = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100024080,"name":"SELinuxStrategyOptions","signature":"func SELinuxStrategyOptions() *SELinuxStrategyOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/selinuxstrategyoptions.go","code":"// SELinuxStrategyOptionsApplyConfiguration constructs an declarative configuration of the SELinuxStrategyOptions type for use with\n// apply.\nfunc SELinuxStrategyOptions() *SELinuxStrategyOptionsApplyConfiguration {\n\treturn \u0026SELinuxStrategyOptionsApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100024081,"name":"WithRule","signature":"func (b *SELinuxStrategyOptionsApplyConfiguration) WithRule(value v1beta1.SELinuxStrategy) *SELinuxStrategyOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/selinuxstrategyoptions.go","code":"// WithRule sets the Rule field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Rule field is set to the value of the last call.\nfunc (b *SELinuxStrategyOptionsApplyConfiguration) WithRule(value v1beta1.SELinuxStrategy) *SELinuxStrategyOptionsApplyConfiguration {\n\tb.Rule = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100024082,"name":"WithSELinuxOptions","signature":"func (b *SELinuxStrategyOptionsApplyConfiguration) WithSELinuxOptions(value *v1.SELinuxOptionsApplyConfiguration) *SELinuxStrategyOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/selinuxstrategyoptions.go","code":"// WithSELinuxOptions sets the SELinuxOptions field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SELinuxOptions field is set to the value of the last call.\nfunc (b *SELinuxStrategyOptionsApplyConfiguration) WithSELinuxOptions(value *v1.SELinuxOptionsApplyConfiguration) *SELinuxStrategyOptionsApplyConfiguration {\n\tb.SELinuxOptions = value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100024083,"name":"SupplementalGroupsStrategyOptions","signature":"func SupplementalGroupsStrategyOptions() *SupplementalGroupsStrategyOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/supplementalgroupsstrategyoptions.go","code":"// SupplementalGroupsStrategyOptionsApplyConfiguration constructs an declarative configuration of the SupplementalGroupsStrategyOptions type for use with\n// apply.\nfunc SupplementalGroupsStrategyOptions() *SupplementalGroupsStrategyOptionsApplyConfiguration {\n\treturn \u0026SupplementalGroupsStrategyOptionsApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100024084,"name":"WithRule","signature":"func (b *SupplementalGroupsStrategyOptionsApplyConfiguration) WithRule(value v1beta1.SupplementalGroupsStrategyType) *SupplementalGroupsStrategyOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/supplementalgroupsstrategyoptions.go","code":"// WithRule sets the Rule field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Rule field is set to the value of the last call.\nfunc (b *SupplementalGroupsStrategyOptionsApplyConfiguration) WithRule(value v1beta1.SupplementalGroupsStrategyType) *SupplementalGroupsStrategyOptionsApplyConfiguration {\n\tb.Rule = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100024085,"name":"WithRanges","signature":"func (b *SupplementalGroupsStrategyOptionsApplyConfiguration) WithRanges(values ...*IDRangeApplyConfiguration) *SupplementalGroupsStrategyOptionsApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/policy/v1beta1/supplementalgroupsstrategyoptions.go","code":"// WithRanges adds the given value to the Ranges field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Ranges field.\nfunc (b *SupplementalGroupsStrategyOptionsApplyConfiguration) WithRanges(values ...*IDRangeApplyConfiguration) *SupplementalGroupsStrategyOptionsApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRanges\")\n\t\t}\n\t\tb.Ranges = append(b.Ranges, *values[i])\n\t}\n\treturn b\n}","line":{"from":46,"to":57}} {"id":100024086,"name":"AggregationRule","signature":"func AggregationRule() *AggregationRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/aggregationrule.go","code":"// AggregationRuleApplyConfiguration constructs an declarative configuration of the AggregationRule type for use with\n// apply.\nfunc AggregationRule() *AggregationRuleApplyConfiguration {\n\treturn \u0026AggregationRuleApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100024087,"name":"WithClusterRoleSelectors","signature":"func (b *AggregationRuleApplyConfiguration) WithClusterRoleSelectors(values ...*v1.LabelSelectorApplyConfiguration) *AggregationRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/aggregationrule.go","code":"// WithClusterRoleSelectors adds the given value to the ClusterRoleSelectors field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ClusterRoleSelectors field.\nfunc (b *AggregationRuleApplyConfiguration) WithClusterRoleSelectors(values ...*v1.LabelSelectorApplyConfiguration) *AggregationRuleApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithClusterRoleSelectors\")\n\t\t}\n\t\tb.ClusterRoleSelectors = append(b.ClusterRoleSelectors, *values[i])\n\t}\n\treturn b\n}","line":{"from":37,"to":48}} {"id":100024088,"name":"ClusterRole","signature":"func ClusterRole(name string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrole.go","code":"// ClusterRole constructs an declarative configuration of the ClusterRole type for use with\n// apply.\nfunc ClusterRole(name string) *ClusterRoleApplyConfiguration {\n\tb := \u0026ClusterRoleApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"ClusterRole\")\n\tb.WithAPIVersion(\"rbac.authorization.k8s.io/v1\")\n\treturn b\n}","line":{"from":39,"to":47}} {"id":100024089,"name":"ExtractClusterRole","signature":"func ExtractClusterRole(clusterRole *apirbacv1.ClusterRole, fieldManager string) (*ClusterRoleApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrole.go","code":"// ExtractClusterRole extracts the applied configuration owned by fieldManager from\n// clusterRole. If no managedFields are found in clusterRole for fieldManager, a\n// ClusterRoleApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// clusterRole must be a unmodified ClusterRole API object that was retrieved from the Kubernetes API.\n// ExtractClusterRole provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractClusterRole(clusterRole *apirbacv1.ClusterRole, fieldManager string) (*ClusterRoleApplyConfiguration, error) {\n\treturn extractClusterRole(clusterRole, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100024090,"name":"ExtractClusterRoleStatus","signature":"func ExtractClusterRoleStatus(clusterRole *apirbacv1.ClusterRole, fieldManager string) (*ClusterRoleApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrole.go","code":"// ExtractClusterRoleStatus is the same as ExtractClusterRole except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractClusterRoleStatus(clusterRole *apirbacv1.ClusterRole, fieldManager string) (*ClusterRoleApplyConfiguration, error) {\n\treturn extractClusterRole(clusterRole, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100024091,"name":"extractClusterRole","signature":"func extractClusterRole(clusterRole *apirbacv1.ClusterRole, fieldManager string, subresource string) (*ClusterRoleApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrole.go","code":"func extractClusterRole(clusterRole *apirbacv1.ClusterRole, fieldManager string, subresource string) (*ClusterRoleApplyConfiguration, error) {\n\tb := \u0026ClusterRoleApplyConfiguration{}\n\terr := managedfields.ExtractInto(clusterRole, internal.Parser().Type(\"io.k8s.api.rbac.v1.ClusterRole\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(clusterRole.Name)\n\n\tb.WithKind(\"ClusterRole\")\n\tb.WithAPIVersion(\"rbac.authorization.k8s.io/v1\")\n\treturn b, nil\n}","line":{"from":71,"to":82}} {"id":100024092,"name":"WithKind","signature":"func (b *ClusterRoleApplyConfiguration) WithKind(value string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrole.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithKind(value string) *ClusterRoleApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100024093,"name":"WithAPIVersion","signature":"func (b *ClusterRoleApplyConfiguration) WithAPIVersion(value string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrole.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithAPIVersion(value string) *ClusterRoleApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100024094,"name":"WithName","signature":"func (b *ClusterRoleApplyConfiguration) WithName(value string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrole.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithName(value string) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":100,"to":107}} {"id":100024095,"name":"WithGenerateName","signature":"func (b *ClusterRoleApplyConfiguration) WithGenerateName(value string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrole.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithGenerateName(value string) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":109,"to":116}} {"id":100024096,"name":"WithNamespace","signature":"func (b *ClusterRoleApplyConfiguration) WithNamespace(value string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrole.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithNamespace(value string) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":118,"to":125}} {"id":100024097,"name":"WithUID","signature":"func (b *ClusterRoleApplyConfiguration) WithUID(value types.UID) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrole.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithUID(value types.UID) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":127,"to":134}} {"id":100024098,"name":"WithResourceVersion","signature":"func (b *ClusterRoleApplyConfiguration) WithResourceVersion(value string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrole.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithResourceVersion(value string) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":136,"to":143}} {"id":100024099,"name":"WithGeneration","signature":"func (b *ClusterRoleApplyConfiguration) WithGeneration(value int64) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrole.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithGeneration(value int64) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":145,"to":152}} {"id":100024100,"name":"WithCreationTimestamp","signature":"func (b *ClusterRoleApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrole.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":154,"to":161}} {"id":100024101,"name":"WithDeletionTimestamp","signature":"func (b *ClusterRoleApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrole.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":163,"to":170}} {"id":100024102,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ClusterRoleApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrole.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":172,"to":179}} {"id":100024103,"name":"WithLabels","signature":"func (b *ClusterRoleApplyConfiguration) WithLabels(entries map[string]string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrole.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ClusterRoleApplyConfiguration) WithLabels(entries map[string]string) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":181,"to":194}} {"id":100024104,"name":"WithAnnotations","signature":"func (b *ClusterRoleApplyConfiguration) WithAnnotations(entries map[string]string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrole.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ClusterRoleApplyConfiguration) WithAnnotations(entries map[string]string) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100024105,"name":"WithOwnerReferences","signature":"func (b *ClusterRoleApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrole.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ClusterRoleApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":211,"to":223}} {"id":100024106,"name":"WithFinalizers","signature":"func (b *ClusterRoleApplyConfiguration) WithFinalizers(values ...string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrole.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ClusterRoleApplyConfiguration) WithFinalizers(values ...string) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":225,"to":234}} {"id":100024107,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ClusterRoleApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrole.go","code":"func (b *ClusterRoleApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":236,"to":240}} {"id":100024108,"name":"WithRules","signature":"func (b *ClusterRoleApplyConfiguration) WithRules(values ...*PolicyRuleApplyConfiguration) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrole.go","code":"// WithRules adds the given value to the Rules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Rules field.\nfunc (b *ClusterRoleApplyConfiguration) WithRules(values ...*PolicyRuleApplyConfiguration) *ClusterRoleApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRules\")\n\t\t}\n\t\tb.Rules = append(b.Rules, *values[i])\n\t}\n\treturn b\n}","line":{"from":242,"to":253}} {"id":100024109,"name":"WithAggregationRule","signature":"func (b *ClusterRoleApplyConfiguration) WithAggregationRule(value *AggregationRuleApplyConfiguration) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrole.go","code":"// WithAggregationRule sets the AggregationRule field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AggregationRule field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithAggregationRule(value *AggregationRuleApplyConfiguration) *ClusterRoleApplyConfiguration {\n\tb.AggregationRule = value\n\treturn b\n}","line":{"from":255,"to":261}} {"id":100024110,"name":"ClusterRoleBinding","signature":"func ClusterRoleBinding(name string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrolebinding.go","code":"// ClusterRoleBinding constructs an declarative configuration of the ClusterRoleBinding type for use with\n// apply.\nfunc ClusterRoleBinding(name string) *ClusterRoleBindingApplyConfiguration {\n\tb := \u0026ClusterRoleBindingApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"ClusterRoleBinding\")\n\tb.WithAPIVersion(\"rbac.authorization.k8s.io/v1\")\n\treturn b\n}","line":{"from":39,"to":47}} {"id":100024111,"name":"ExtractClusterRoleBinding","signature":"func ExtractClusterRoleBinding(clusterRoleBinding *apirbacv1.ClusterRoleBinding, fieldManager string) (*ClusterRoleBindingApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrolebinding.go","code":"// ExtractClusterRoleBinding extracts the applied configuration owned by fieldManager from\n// clusterRoleBinding. If no managedFields are found in clusterRoleBinding for fieldManager, a\n// ClusterRoleBindingApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// clusterRoleBinding must be a unmodified ClusterRoleBinding API object that was retrieved from the Kubernetes API.\n// ExtractClusterRoleBinding provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractClusterRoleBinding(clusterRoleBinding *apirbacv1.ClusterRoleBinding, fieldManager string) (*ClusterRoleBindingApplyConfiguration, error) {\n\treturn extractClusterRoleBinding(clusterRoleBinding, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100024112,"name":"ExtractClusterRoleBindingStatus","signature":"func ExtractClusterRoleBindingStatus(clusterRoleBinding *apirbacv1.ClusterRoleBinding, fieldManager string) (*ClusterRoleBindingApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrolebinding.go","code":"// ExtractClusterRoleBindingStatus is the same as ExtractClusterRoleBinding except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractClusterRoleBindingStatus(clusterRoleBinding *apirbacv1.ClusterRoleBinding, fieldManager string) (*ClusterRoleBindingApplyConfiguration, error) {\n\treturn extractClusterRoleBinding(clusterRoleBinding, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100024113,"name":"extractClusterRoleBinding","signature":"func extractClusterRoleBinding(clusterRoleBinding *apirbacv1.ClusterRoleBinding, fieldManager string, subresource string) (*ClusterRoleBindingApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrolebinding.go","code":"func extractClusterRoleBinding(clusterRoleBinding *apirbacv1.ClusterRoleBinding, fieldManager string, subresource string) (*ClusterRoleBindingApplyConfiguration, error) {\n\tb := \u0026ClusterRoleBindingApplyConfiguration{}\n\terr := managedfields.ExtractInto(clusterRoleBinding, internal.Parser().Type(\"io.k8s.api.rbac.v1.ClusterRoleBinding\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(clusterRoleBinding.Name)\n\n\tb.WithKind(\"ClusterRoleBinding\")\n\tb.WithAPIVersion(\"rbac.authorization.k8s.io/v1\")\n\treturn b, nil\n}","line":{"from":71,"to":82}} {"id":100024114,"name":"WithKind","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithKind(value string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrolebinding.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithKind(value string) *ClusterRoleBindingApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100024115,"name":"WithAPIVersion","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithAPIVersion(value string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrolebinding.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithAPIVersion(value string) *ClusterRoleBindingApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100024116,"name":"WithName","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithName(value string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrolebinding.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithName(value string) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":100,"to":107}} {"id":100024117,"name":"WithGenerateName","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithGenerateName(value string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrolebinding.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithGenerateName(value string) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":109,"to":116}} {"id":100024118,"name":"WithNamespace","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithNamespace(value string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrolebinding.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithNamespace(value string) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":118,"to":125}} {"id":100024119,"name":"WithUID","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithUID(value types.UID) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrolebinding.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithUID(value types.UID) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":127,"to":134}} {"id":100024120,"name":"WithResourceVersion","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithResourceVersion(value string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrolebinding.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithResourceVersion(value string) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":136,"to":143}} {"id":100024121,"name":"WithGeneration","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithGeneration(value int64) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrolebinding.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithGeneration(value int64) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":145,"to":152}} {"id":100024122,"name":"WithCreationTimestamp","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrolebinding.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":154,"to":161}} {"id":100024123,"name":"WithDeletionTimestamp","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrolebinding.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":163,"to":170}} {"id":100024124,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrolebinding.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":172,"to":179}} {"id":100024125,"name":"WithLabels","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithLabels(entries map[string]string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrolebinding.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithLabels(entries map[string]string) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":181,"to":194}} {"id":100024126,"name":"WithAnnotations","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithAnnotations(entries map[string]string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrolebinding.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithAnnotations(entries map[string]string) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100024127,"name":"WithOwnerReferences","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrolebinding.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":211,"to":223}} {"id":100024128,"name":"WithFinalizers","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithFinalizers(values ...string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrolebinding.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithFinalizers(values ...string) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":225,"to":234}} {"id":100024129,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ClusterRoleBindingApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrolebinding.go","code":"func (b *ClusterRoleBindingApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":236,"to":240}} {"id":100024130,"name":"WithSubjects","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithSubjects(values ...*SubjectApplyConfiguration) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrolebinding.go","code":"// WithSubjects adds the given value to the Subjects field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Subjects field.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithSubjects(values ...*SubjectApplyConfiguration) *ClusterRoleBindingApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithSubjects\")\n\t\t}\n\t\tb.Subjects = append(b.Subjects, *values[i])\n\t}\n\treturn b\n}","line":{"from":242,"to":253}} {"id":100024131,"name":"WithRoleRef","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithRoleRef(value *RoleRefApplyConfiguration) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/clusterrolebinding.go","code":"// WithRoleRef sets the RoleRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RoleRef field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithRoleRef(value *RoleRefApplyConfiguration) *ClusterRoleBindingApplyConfiguration {\n\tb.RoleRef = value\n\treturn b\n}","line":{"from":255,"to":261}} {"id":100024132,"name":"PolicyRule","signature":"func PolicyRule() *PolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/policyrule.go","code":"// PolicyRuleApplyConfiguration constructs an declarative configuration of the PolicyRule type for use with\n// apply.\nfunc PolicyRule() *PolicyRuleApplyConfiguration {\n\treturn \u0026PolicyRuleApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100024133,"name":"WithVerbs","signature":"func (b *PolicyRuleApplyConfiguration) WithVerbs(values ...string) *PolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/policyrule.go","code":"// WithVerbs adds the given value to the Verbs field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Verbs field.\nfunc (b *PolicyRuleApplyConfiguration) WithVerbs(values ...string) *PolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.Verbs = append(b.Verbs, values[i])\n\t}\n\treturn b\n}","line":{"from":37,"to":45}} {"id":100024134,"name":"WithAPIGroups","signature":"func (b *PolicyRuleApplyConfiguration) WithAPIGroups(values ...string) *PolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/policyrule.go","code":"// WithAPIGroups adds the given value to the APIGroups field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the APIGroups field.\nfunc (b *PolicyRuleApplyConfiguration) WithAPIGroups(values ...string) *PolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.APIGroups = append(b.APIGroups, values[i])\n\t}\n\treturn b\n}","line":{"from":47,"to":55}} {"id":100024135,"name":"WithResources","signature":"func (b *PolicyRuleApplyConfiguration) WithResources(values ...string) *PolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/policyrule.go","code":"// WithResources adds the given value to the Resources field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Resources field.\nfunc (b *PolicyRuleApplyConfiguration) WithResources(values ...string) *PolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.Resources = append(b.Resources, values[i])\n\t}\n\treturn b\n}","line":{"from":57,"to":65}} {"id":100024136,"name":"WithResourceNames","signature":"func (b *PolicyRuleApplyConfiguration) WithResourceNames(values ...string) *PolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/policyrule.go","code":"// WithResourceNames adds the given value to the ResourceNames field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ResourceNames field.\nfunc (b *PolicyRuleApplyConfiguration) WithResourceNames(values ...string) *PolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.ResourceNames = append(b.ResourceNames, values[i])\n\t}\n\treturn b\n}","line":{"from":67,"to":75}} {"id":100024137,"name":"WithNonResourceURLs","signature":"func (b *PolicyRuleApplyConfiguration) WithNonResourceURLs(values ...string) *PolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/policyrule.go","code":"// WithNonResourceURLs adds the given value to the NonResourceURLs field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the NonResourceURLs field.\nfunc (b *PolicyRuleApplyConfiguration) WithNonResourceURLs(values ...string) *PolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.NonResourceURLs = append(b.NonResourceURLs, values[i])\n\t}\n\treturn b\n}","line":{"from":77,"to":85}} {"id":100024138,"name":"Role","signature":"func Role(name, namespace string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/role.go","code":"// Role constructs an declarative configuration of the Role type for use with\n// apply.\nfunc Role(name, namespace string) *RoleApplyConfiguration {\n\tb := \u0026RoleApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"Role\")\n\tb.WithAPIVersion(\"rbac.authorization.k8s.io/v1\")\n\treturn b\n}","line":{"from":38,"to":47}} {"id":100024139,"name":"ExtractRole","signature":"func ExtractRole(role *apirbacv1.Role, fieldManager string) (*RoleApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/role.go","code":"// ExtractRole extracts the applied configuration owned by fieldManager from\n// role. If no managedFields are found in role for fieldManager, a\n// RoleApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// role must be a unmodified Role API object that was retrieved from the Kubernetes API.\n// ExtractRole provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractRole(role *apirbacv1.Role, fieldManager string) (*RoleApplyConfiguration, error) {\n\treturn extractRole(role, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100024140,"name":"ExtractRoleStatus","signature":"func ExtractRoleStatus(role *apirbacv1.Role, fieldManager string) (*RoleApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/role.go","code":"// ExtractRoleStatus is the same as ExtractRole except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractRoleStatus(role *apirbacv1.Role, fieldManager string) (*RoleApplyConfiguration, error) {\n\treturn extractRole(role, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100024141,"name":"extractRole","signature":"func extractRole(role *apirbacv1.Role, fieldManager string, subresource string) (*RoleApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/role.go","code":"func extractRole(role *apirbacv1.Role, fieldManager string, subresource string) (*RoleApplyConfiguration, error) {\n\tb := \u0026RoleApplyConfiguration{}\n\terr := managedfields.ExtractInto(role, internal.Parser().Type(\"io.k8s.api.rbac.v1.Role\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(role.Name)\n\tb.WithNamespace(role.Namespace)\n\n\tb.WithKind(\"Role\")\n\tb.WithAPIVersion(\"rbac.authorization.k8s.io/v1\")\n\treturn b, nil\n}","line":{"from":71,"to":83}} {"id":100024142,"name":"WithKind","signature":"func (b *RoleApplyConfiguration) WithKind(value string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/role.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithKind(value string) *RoleApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":85,"to":91}} {"id":100024143,"name":"WithAPIVersion","signature":"func (b *RoleApplyConfiguration) WithAPIVersion(value string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/role.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithAPIVersion(value string) *RoleApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":93,"to":99}} {"id":100024144,"name":"WithName","signature":"func (b *RoleApplyConfiguration) WithName(value string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/role.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithName(value string) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":101,"to":108}} {"id":100024145,"name":"WithGenerateName","signature":"func (b *RoleApplyConfiguration) WithGenerateName(value string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/role.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithGenerateName(value string) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":110,"to":117}} {"id":100024146,"name":"WithNamespace","signature":"func (b *RoleApplyConfiguration) WithNamespace(value string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/role.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithNamespace(value string) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":119,"to":126}} {"id":100024147,"name":"WithUID","signature":"func (b *RoleApplyConfiguration) WithUID(value types.UID) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/role.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithUID(value types.UID) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":128,"to":135}} {"id":100024148,"name":"WithResourceVersion","signature":"func (b *RoleApplyConfiguration) WithResourceVersion(value string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/role.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithResourceVersion(value string) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":137,"to":144}} {"id":100024149,"name":"WithGeneration","signature":"func (b *RoleApplyConfiguration) WithGeneration(value int64) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/role.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithGeneration(value int64) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":146,"to":153}} {"id":100024150,"name":"WithCreationTimestamp","signature":"func (b *RoleApplyConfiguration) WithCreationTimestamp(value metav1.Time) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/role.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithCreationTimestamp(value metav1.Time) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":155,"to":162}} {"id":100024151,"name":"WithDeletionTimestamp","signature":"func (b *RoleApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/role.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":164,"to":171}} {"id":100024152,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *RoleApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/role.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":173,"to":180}} {"id":100024153,"name":"WithLabels","signature":"func (b *RoleApplyConfiguration) WithLabels(entries map[string]string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/role.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *RoleApplyConfiguration) WithLabels(entries map[string]string) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":182,"to":195}} {"id":100024154,"name":"WithAnnotations","signature":"func (b *RoleApplyConfiguration) WithAnnotations(entries map[string]string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/role.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *RoleApplyConfiguration) WithAnnotations(entries map[string]string) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":197,"to":210}} {"id":100024155,"name":"WithOwnerReferences","signature":"func (b *RoleApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/role.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *RoleApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":212,"to":224}} {"id":100024156,"name":"WithFinalizers","signature":"func (b *RoleApplyConfiguration) WithFinalizers(values ...string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/role.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *RoleApplyConfiguration) WithFinalizers(values ...string) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":226,"to":235}} {"id":100024157,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *RoleApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/role.go","code":"func (b *RoleApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":237,"to":241}} {"id":100024158,"name":"WithRules","signature":"func (b *RoleApplyConfiguration) WithRules(values ...*PolicyRuleApplyConfiguration) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/role.go","code":"// WithRules adds the given value to the Rules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Rules field.\nfunc (b *RoleApplyConfiguration) WithRules(values ...*PolicyRuleApplyConfiguration) *RoleApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRules\")\n\t\t}\n\t\tb.Rules = append(b.Rules, *values[i])\n\t}\n\treturn b\n}","line":{"from":243,"to":254}} {"id":100024159,"name":"RoleBinding","signature":"func RoleBinding(name, namespace string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/rolebinding.go","code":"// RoleBinding constructs an declarative configuration of the RoleBinding type for use with\n// apply.\nfunc RoleBinding(name, namespace string) *RoleBindingApplyConfiguration {\n\tb := \u0026RoleBindingApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"RoleBinding\")\n\tb.WithAPIVersion(\"rbac.authorization.k8s.io/v1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100024160,"name":"ExtractRoleBinding","signature":"func ExtractRoleBinding(roleBinding *apirbacv1.RoleBinding, fieldManager string) (*RoleBindingApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/rolebinding.go","code":"// ExtractRoleBinding extracts the applied configuration owned by fieldManager from\n// roleBinding. If no managedFields are found in roleBinding for fieldManager, a\n// RoleBindingApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// roleBinding must be a unmodified RoleBinding API object that was retrieved from the Kubernetes API.\n// ExtractRoleBinding provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractRoleBinding(roleBinding *apirbacv1.RoleBinding, fieldManager string) (*RoleBindingApplyConfiguration, error) {\n\treturn extractRoleBinding(roleBinding, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100024161,"name":"ExtractRoleBindingStatus","signature":"func ExtractRoleBindingStatus(roleBinding *apirbacv1.RoleBinding, fieldManager string) (*RoleBindingApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/rolebinding.go","code":"// ExtractRoleBindingStatus is the same as ExtractRoleBinding except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractRoleBindingStatus(roleBinding *apirbacv1.RoleBinding, fieldManager string) (*RoleBindingApplyConfiguration, error) {\n\treturn extractRoleBinding(roleBinding, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100024162,"name":"extractRoleBinding","signature":"func extractRoleBinding(roleBinding *apirbacv1.RoleBinding, fieldManager string, subresource string) (*RoleBindingApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/rolebinding.go","code":"func extractRoleBinding(roleBinding *apirbacv1.RoleBinding, fieldManager string, subresource string) (*RoleBindingApplyConfiguration, error) {\n\tb := \u0026RoleBindingApplyConfiguration{}\n\terr := managedfields.ExtractInto(roleBinding, internal.Parser().Type(\"io.k8s.api.rbac.v1.RoleBinding\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(roleBinding.Name)\n\tb.WithNamespace(roleBinding.Namespace)\n\n\tb.WithKind(\"RoleBinding\")\n\tb.WithAPIVersion(\"rbac.authorization.k8s.io/v1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100024163,"name":"WithKind","signature":"func (b *RoleBindingApplyConfiguration) WithKind(value string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/rolebinding.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithKind(value string) *RoleBindingApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100024164,"name":"WithAPIVersion","signature":"func (b *RoleBindingApplyConfiguration) WithAPIVersion(value string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/rolebinding.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithAPIVersion(value string) *RoleBindingApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100024165,"name":"WithName","signature":"func (b *RoleBindingApplyConfiguration) WithName(value string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/rolebinding.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithName(value string) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100024166,"name":"WithGenerateName","signature":"func (b *RoleBindingApplyConfiguration) WithGenerateName(value string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/rolebinding.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithGenerateName(value string) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100024167,"name":"WithNamespace","signature":"func (b *RoleBindingApplyConfiguration) WithNamespace(value string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/rolebinding.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithNamespace(value string) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100024168,"name":"WithUID","signature":"func (b *RoleBindingApplyConfiguration) WithUID(value types.UID) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/rolebinding.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithUID(value types.UID) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100024169,"name":"WithResourceVersion","signature":"func (b *RoleBindingApplyConfiguration) WithResourceVersion(value string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/rolebinding.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithResourceVersion(value string) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100024170,"name":"WithGeneration","signature":"func (b *RoleBindingApplyConfiguration) WithGeneration(value int64) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/rolebinding.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithGeneration(value int64) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100024171,"name":"WithCreationTimestamp","signature":"func (b *RoleBindingApplyConfiguration) WithCreationTimestamp(value metav1.Time) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/rolebinding.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithCreationTimestamp(value metav1.Time) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100024172,"name":"WithDeletionTimestamp","signature":"func (b *RoleBindingApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/rolebinding.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100024173,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *RoleBindingApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/rolebinding.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100024174,"name":"WithLabels","signature":"func (b *RoleBindingApplyConfiguration) WithLabels(entries map[string]string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/rolebinding.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *RoleBindingApplyConfiguration) WithLabels(entries map[string]string) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100024175,"name":"WithAnnotations","signature":"func (b *RoleBindingApplyConfiguration) WithAnnotations(entries map[string]string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/rolebinding.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *RoleBindingApplyConfiguration) WithAnnotations(entries map[string]string) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100024176,"name":"WithOwnerReferences","signature":"func (b *RoleBindingApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/rolebinding.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *RoleBindingApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100024177,"name":"WithFinalizers","signature":"func (b *RoleBindingApplyConfiguration) WithFinalizers(values ...string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/rolebinding.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *RoleBindingApplyConfiguration) WithFinalizers(values ...string) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100024178,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *RoleBindingApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/rolebinding.go","code":"func (b *RoleBindingApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100024179,"name":"WithSubjects","signature":"func (b *RoleBindingApplyConfiguration) WithSubjects(values ...*SubjectApplyConfiguration) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/rolebinding.go","code":"// WithSubjects adds the given value to the Subjects field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Subjects field.\nfunc (b *RoleBindingApplyConfiguration) WithSubjects(values ...*SubjectApplyConfiguration) *RoleBindingApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithSubjects\")\n\t\t}\n\t\tb.Subjects = append(b.Subjects, *values[i])\n\t}\n\treturn b\n}","line":{"from":244,"to":255}} {"id":100024180,"name":"WithRoleRef","signature":"func (b *RoleBindingApplyConfiguration) WithRoleRef(value *RoleRefApplyConfiguration) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/rolebinding.go","code":"// WithRoleRef sets the RoleRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RoleRef field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithRoleRef(value *RoleRefApplyConfiguration) *RoleBindingApplyConfiguration {\n\tb.RoleRef = value\n\treturn b\n}","line":{"from":257,"to":263}} {"id":100024181,"name":"RoleRef","signature":"func RoleRef() *RoleRefApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/roleref.go","code":"// RoleRefApplyConfiguration constructs an declarative configuration of the RoleRef type for use with\n// apply.\nfunc RoleRef() *RoleRefApplyConfiguration {\n\treturn \u0026RoleRefApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100024182,"name":"WithAPIGroup","signature":"func (b *RoleRefApplyConfiguration) WithAPIGroup(value string) *RoleRefApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/roleref.go","code":"// WithAPIGroup sets the APIGroup field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIGroup field is set to the value of the last call.\nfunc (b *RoleRefApplyConfiguration) WithAPIGroup(value string) *RoleRefApplyConfiguration {\n\tb.APIGroup = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100024183,"name":"WithKind","signature":"func (b *RoleRefApplyConfiguration) WithKind(value string) *RoleRefApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/roleref.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *RoleRefApplyConfiguration) WithKind(value string) *RoleRefApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100024184,"name":"WithName","signature":"func (b *RoleRefApplyConfiguration) WithName(value string) *RoleRefApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/roleref.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *RoleRefApplyConfiguration) WithName(value string) *RoleRefApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100024185,"name":"Subject","signature":"func Subject() *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/subject.go","code":"// SubjectApplyConfiguration constructs an declarative configuration of the Subject type for use with\n// apply.\nfunc Subject() *SubjectApplyConfiguration {\n\treturn \u0026SubjectApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100024186,"name":"WithKind","signature":"func (b *SubjectApplyConfiguration) WithKind(value string) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/subject.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithKind(value string) *SubjectApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100024187,"name":"WithAPIGroup","signature":"func (b *SubjectApplyConfiguration) WithAPIGroup(value string) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/subject.go","code":"// WithAPIGroup sets the APIGroup field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIGroup field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithAPIGroup(value string) *SubjectApplyConfiguration {\n\tb.APIGroup = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100024188,"name":"WithName","signature":"func (b *SubjectApplyConfiguration) WithName(value string) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/subject.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithName(value string) *SubjectApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100024189,"name":"WithNamespace","signature":"func (b *SubjectApplyConfiguration) WithNamespace(value string) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1/subject.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithNamespace(value string) *SubjectApplyConfiguration {\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100024190,"name":"AggregationRule","signature":"func AggregationRule() *AggregationRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/aggregationrule.go","code":"// AggregationRuleApplyConfiguration constructs an declarative configuration of the AggregationRule type for use with\n// apply.\nfunc AggregationRule() *AggregationRuleApplyConfiguration {\n\treturn \u0026AggregationRuleApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100024191,"name":"WithClusterRoleSelectors","signature":"func (b *AggregationRuleApplyConfiguration) WithClusterRoleSelectors(values ...*v1.LabelSelectorApplyConfiguration) *AggregationRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/aggregationrule.go","code":"// WithClusterRoleSelectors adds the given value to the ClusterRoleSelectors field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ClusterRoleSelectors field.\nfunc (b *AggregationRuleApplyConfiguration) WithClusterRoleSelectors(values ...*v1.LabelSelectorApplyConfiguration) *AggregationRuleApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithClusterRoleSelectors\")\n\t\t}\n\t\tb.ClusterRoleSelectors = append(b.ClusterRoleSelectors, *values[i])\n\t}\n\treturn b\n}","line":{"from":37,"to":48}} {"id":100024192,"name":"ClusterRole","signature":"func ClusterRole(name string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrole.go","code":"// ClusterRole constructs an declarative configuration of the ClusterRole type for use with\n// apply.\nfunc ClusterRole(name string) *ClusterRoleApplyConfiguration {\n\tb := \u0026ClusterRoleApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"ClusterRole\")\n\tb.WithAPIVersion(\"rbac.authorization.k8s.io/v1alpha1\")\n\treturn b\n}","line":{"from":39,"to":47}} {"id":100024193,"name":"ExtractClusterRole","signature":"func ExtractClusterRole(clusterRole *rbacv1alpha1.ClusterRole, fieldManager string) (*ClusterRoleApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrole.go","code":"// ExtractClusterRole extracts the applied configuration owned by fieldManager from\n// clusterRole. If no managedFields are found in clusterRole for fieldManager, a\n// ClusterRoleApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// clusterRole must be a unmodified ClusterRole API object that was retrieved from the Kubernetes API.\n// ExtractClusterRole provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractClusterRole(clusterRole *rbacv1alpha1.ClusterRole, fieldManager string) (*ClusterRoleApplyConfiguration, error) {\n\treturn extractClusterRole(clusterRole, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100024194,"name":"ExtractClusterRoleStatus","signature":"func ExtractClusterRoleStatus(clusterRole *rbacv1alpha1.ClusterRole, fieldManager string) (*ClusterRoleApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrole.go","code":"// ExtractClusterRoleStatus is the same as ExtractClusterRole except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractClusterRoleStatus(clusterRole *rbacv1alpha1.ClusterRole, fieldManager string) (*ClusterRoleApplyConfiguration, error) {\n\treturn extractClusterRole(clusterRole, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100024195,"name":"extractClusterRole","signature":"func extractClusterRole(clusterRole *rbacv1alpha1.ClusterRole, fieldManager string, subresource string) (*ClusterRoleApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrole.go","code":"func extractClusterRole(clusterRole *rbacv1alpha1.ClusterRole, fieldManager string, subresource string) (*ClusterRoleApplyConfiguration, error) {\n\tb := \u0026ClusterRoleApplyConfiguration{}\n\terr := managedfields.ExtractInto(clusterRole, internal.Parser().Type(\"io.k8s.api.rbac.v1alpha1.ClusterRole\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(clusterRole.Name)\n\n\tb.WithKind(\"ClusterRole\")\n\tb.WithAPIVersion(\"rbac.authorization.k8s.io/v1alpha1\")\n\treturn b, nil\n}","line":{"from":71,"to":82}} {"id":100024196,"name":"WithKind","signature":"func (b *ClusterRoleApplyConfiguration) WithKind(value string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrole.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithKind(value string) *ClusterRoleApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100024197,"name":"WithAPIVersion","signature":"func (b *ClusterRoleApplyConfiguration) WithAPIVersion(value string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrole.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithAPIVersion(value string) *ClusterRoleApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100024198,"name":"WithName","signature":"func (b *ClusterRoleApplyConfiguration) WithName(value string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrole.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithName(value string) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":100,"to":107}} {"id":100024199,"name":"WithGenerateName","signature":"func (b *ClusterRoleApplyConfiguration) WithGenerateName(value string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrole.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithGenerateName(value string) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":109,"to":116}} {"id":100024200,"name":"WithNamespace","signature":"func (b *ClusterRoleApplyConfiguration) WithNamespace(value string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrole.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithNamespace(value string) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":118,"to":125}} {"id":100024201,"name":"WithUID","signature":"func (b *ClusterRoleApplyConfiguration) WithUID(value types.UID) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrole.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithUID(value types.UID) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":127,"to":134}} {"id":100024202,"name":"WithResourceVersion","signature":"func (b *ClusterRoleApplyConfiguration) WithResourceVersion(value string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrole.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithResourceVersion(value string) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":136,"to":143}} {"id":100024203,"name":"WithGeneration","signature":"func (b *ClusterRoleApplyConfiguration) WithGeneration(value int64) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrole.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithGeneration(value int64) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":145,"to":152}} {"id":100024204,"name":"WithCreationTimestamp","signature":"func (b *ClusterRoleApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrole.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":154,"to":161}} {"id":100024205,"name":"WithDeletionTimestamp","signature":"func (b *ClusterRoleApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrole.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":163,"to":170}} {"id":100024206,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ClusterRoleApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrole.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":172,"to":179}} {"id":100024207,"name":"WithLabels","signature":"func (b *ClusterRoleApplyConfiguration) WithLabels(entries map[string]string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrole.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ClusterRoleApplyConfiguration) WithLabels(entries map[string]string) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":181,"to":194}} {"id":100024208,"name":"WithAnnotations","signature":"func (b *ClusterRoleApplyConfiguration) WithAnnotations(entries map[string]string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrole.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ClusterRoleApplyConfiguration) WithAnnotations(entries map[string]string) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100024209,"name":"WithOwnerReferences","signature":"func (b *ClusterRoleApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrole.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ClusterRoleApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":211,"to":223}} {"id":100024210,"name":"WithFinalizers","signature":"func (b *ClusterRoleApplyConfiguration) WithFinalizers(values ...string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrole.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ClusterRoleApplyConfiguration) WithFinalizers(values ...string) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":225,"to":234}} {"id":100024211,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ClusterRoleApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrole.go","code":"func (b *ClusterRoleApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":236,"to":240}} {"id":100024212,"name":"WithRules","signature":"func (b *ClusterRoleApplyConfiguration) WithRules(values ...*PolicyRuleApplyConfiguration) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrole.go","code":"// WithRules adds the given value to the Rules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Rules field.\nfunc (b *ClusterRoleApplyConfiguration) WithRules(values ...*PolicyRuleApplyConfiguration) *ClusterRoleApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRules\")\n\t\t}\n\t\tb.Rules = append(b.Rules, *values[i])\n\t}\n\treturn b\n}","line":{"from":242,"to":253}} {"id":100024213,"name":"WithAggregationRule","signature":"func (b *ClusterRoleApplyConfiguration) WithAggregationRule(value *AggregationRuleApplyConfiguration) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrole.go","code":"// WithAggregationRule sets the AggregationRule field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AggregationRule field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithAggregationRule(value *AggregationRuleApplyConfiguration) *ClusterRoleApplyConfiguration {\n\tb.AggregationRule = value\n\treturn b\n}","line":{"from":255,"to":261}} {"id":100024214,"name":"ClusterRoleBinding","signature":"func ClusterRoleBinding(name string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrolebinding.go","code":"// ClusterRoleBinding constructs an declarative configuration of the ClusterRoleBinding type for use with\n// apply.\nfunc ClusterRoleBinding(name string) *ClusterRoleBindingApplyConfiguration {\n\tb := \u0026ClusterRoleBindingApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"ClusterRoleBinding\")\n\tb.WithAPIVersion(\"rbac.authorization.k8s.io/v1alpha1\")\n\treturn b\n}","line":{"from":39,"to":47}} {"id":100024215,"name":"ExtractClusterRoleBinding","signature":"func ExtractClusterRoleBinding(clusterRoleBinding *rbacv1alpha1.ClusterRoleBinding, fieldManager string) (*ClusterRoleBindingApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrolebinding.go","code":"// ExtractClusterRoleBinding extracts the applied configuration owned by fieldManager from\n// clusterRoleBinding. If no managedFields are found in clusterRoleBinding for fieldManager, a\n// ClusterRoleBindingApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// clusterRoleBinding must be a unmodified ClusterRoleBinding API object that was retrieved from the Kubernetes API.\n// ExtractClusterRoleBinding provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractClusterRoleBinding(clusterRoleBinding *rbacv1alpha1.ClusterRoleBinding, fieldManager string) (*ClusterRoleBindingApplyConfiguration, error) {\n\treturn extractClusterRoleBinding(clusterRoleBinding, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100024216,"name":"ExtractClusterRoleBindingStatus","signature":"func ExtractClusterRoleBindingStatus(clusterRoleBinding *rbacv1alpha1.ClusterRoleBinding, fieldManager string) (*ClusterRoleBindingApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrolebinding.go","code":"// ExtractClusterRoleBindingStatus is the same as ExtractClusterRoleBinding except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractClusterRoleBindingStatus(clusterRoleBinding *rbacv1alpha1.ClusterRoleBinding, fieldManager string) (*ClusterRoleBindingApplyConfiguration, error) {\n\treturn extractClusterRoleBinding(clusterRoleBinding, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100024217,"name":"extractClusterRoleBinding","signature":"func extractClusterRoleBinding(clusterRoleBinding *rbacv1alpha1.ClusterRoleBinding, fieldManager string, subresource string) (*ClusterRoleBindingApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrolebinding.go","code":"func extractClusterRoleBinding(clusterRoleBinding *rbacv1alpha1.ClusterRoleBinding, fieldManager string, subresource string) (*ClusterRoleBindingApplyConfiguration, error) {\n\tb := \u0026ClusterRoleBindingApplyConfiguration{}\n\terr := managedfields.ExtractInto(clusterRoleBinding, internal.Parser().Type(\"io.k8s.api.rbac.v1alpha1.ClusterRoleBinding\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(clusterRoleBinding.Name)\n\n\tb.WithKind(\"ClusterRoleBinding\")\n\tb.WithAPIVersion(\"rbac.authorization.k8s.io/v1alpha1\")\n\treturn b, nil\n}","line":{"from":71,"to":82}} {"id":100024218,"name":"WithKind","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithKind(value string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrolebinding.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithKind(value string) *ClusterRoleBindingApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100024219,"name":"WithAPIVersion","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithAPIVersion(value string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrolebinding.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithAPIVersion(value string) *ClusterRoleBindingApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100024220,"name":"WithName","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithName(value string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrolebinding.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithName(value string) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":100,"to":107}} {"id":100024221,"name":"WithGenerateName","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithGenerateName(value string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrolebinding.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithGenerateName(value string) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":109,"to":116}} {"id":100024222,"name":"WithNamespace","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithNamespace(value string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrolebinding.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithNamespace(value string) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":118,"to":125}} {"id":100024223,"name":"WithUID","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithUID(value types.UID) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrolebinding.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithUID(value types.UID) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":127,"to":134}} {"id":100024224,"name":"WithResourceVersion","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithResourceVersion(value string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrolebinding.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithResourceVersion(value string) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":136,"to":143}} {"id":100024225,"name":"WithGeneration","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithGeneration(value int64) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrolebinding.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithGeneration(value int64) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":145,"to":152}} {"id":100024226,"name":"WithCreationTimestamp","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrolebinding.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":154,"to":161}} {"id":100024227,"name":"WithDeletionTimestamp","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrolebinding.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":163,"to":170}} {"id":100024228,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrolebinding.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":172,"to":179}} {"id":100024229,"name":"WithLabels","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithLabels(entries map[string]string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrolebinding.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithLabels(entries map[string]string) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":181,"to":194}} {"id":100024230,"name":"WithAnnotations","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithAnnotations(entries map[string]string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrolebinding.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithAnnotations(entries map[string]string) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100024231,"name":"WithOwnerReferences","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrolebinding.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":211,"to":223}} {"id":100024232,"name":"WithFinalizers","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithFinalizers(values ...string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrolebinding.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithFinalizers(values ...string) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":225,"to":234}} {"id":100024233,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ClusterRoleBindingApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrolebinding.go","code":"func (b *ClusterRoleBindingApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":236,"to":240}} {"id":100024234,"name":"WithSubjects","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithSubjects(values ...*SubjectApplyConfiguration) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrolebinding.go","code":"// WithSubjects adds the given value to the Subjects field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Subjects field.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithSubjects(values ...*SubjectApplyConfiguration) *ClusterRoleBindingApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithSubjects\")\n\t\t}\n\t\tb.Subjects = append(b.Subjects, *values[i])\n\t}\n\treturn b\n}","line":{"from":242,"to":253}} {"id":100024235,"name":"WithRoleRef","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithRoleRef(value *RoleRefApplyConfiguration) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/clusterrolebinding.go","code":"// WithRoleRef sets the RoleRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RoleRef field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithRoleRef(value *RoleRefApplyConfiguration) *ClusterRoleBindingApplyConfiguration {\n\tb.RoleRef = value\n\treturn b\n}","line":{"from":255,"to":261}} {"id":100024236,"name":"PolicyRule","signature":"func PolicyRule() *PolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/policyrule.go","code":"// PolicyRuleApplyConfiguration constructs an declarative configuration of the PolicyRule type for use with\n// apply.\nfunc PolicyRule() *PolicyRuleApplyConfiguration {\n\treturn \u0026PolicyRuleApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100024237,"name":"WithVerbs","signature":"func (b *PolicyRuleApplyConfiguration) WithVerbs(values ...string) *PolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/policyrule.go","code":"// WithVerbs adds the given value to the Verbs field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Verbs field.\nfunc (b *PolicyRuleApplyConfiguration) WithVerbs(values ...string) *PolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.Verbs = append(b.Verbs, values[i])\n\t}\n\treturn b\n}","line":{"from":37,"to":45}} {"id":100024238,"name":"WithAPIGroups","signature":"func (b *PolicyRuleApplyConfiguration) WithAPIGroups(values ...string) *PolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/policyrule.go","code":"// WithAPIGroups adds the given value to the APIGroups field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the APIGroups field.\nfunc (b *PolicyRuleApplyConfiguration) WithAPIGroups(values ...string) *PolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.APIGroups = append(b.APIGroups, values[i])\n\t}\n\treturn b\n}","line":{"from":47,"to":55}} {"id":100024239,"name":"WithResources","signature":"func (b *PolicyRuleApplyConfiguration) WithResources(values ...string) *PolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/policyrule.go","code":"// WithResources adds the given value to the Resources field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Resources field.\nfunc (b *PolicyRuleApplyConfiguration) WithResources(values ...string) *PolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.Resources = append(b.Resources, values[i])\n\t}\n\treturn b\n}","line":{"from":57,"to":65}} {"id":100024240,"name":"WithResourceNames","signature":"func (b *PolicyRuleApplyConfiguration) WithResourceNames(values ...string) *PolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/policyrule.go","code":"// WithResourceNames adds the given value to the ResourceNames field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ResourceNames field.\nfunc (b *PolicyRuleApplyConfiguration) WithResourceNames(values ...string) *PolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.ResourceNames = append(b.ResourceNames, values[i])\n\t}\n\treturn b\n}","line":{"from":67,"to":75}} {"id":100024241,"name":"WithNonResourceURLs","signature":"func (b *PolicyRuleApplyConfiguration) WithNonResourceURLs(values ...string) *PolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/policyrule.go","code":"// WithNonResourceURLs adds the given value to the NonResourceURLs field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the NonResourceURLs field.\nfunc (b *PolicyRuleApplyConfiguration) WithNonResourceURLs(values ...string) *PolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.NonResourceURLs = append(b.NonResourceURLs, values[i])\n\t}\n\treturn b\n}","line":{"from":77,"to":85}} {"id":100024242,"name":"Role","signature":"func Role(name, namespace string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/role.go","code":"// Role constructs an declarative configuration of the Role type for use with\n// apply.\nfunc Role(name, namespace string) *RoleApplyConfiguration {\n\tb := \u0026RoleApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"Role\")\n\tb.WithAPIVersion(\"rbac.authorization.k8s.io/v1alpha1\")\n\treturn b\n}","line":{"from":38,"to":47}} {"id":100024243,"name":"ExtractRole","signature":"func ExtractRole(role *rbacv1alpha1.Role, fieldManager string) (*RoleApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/role.go","code":"// ExtractRole extracts the applied configuration owned by fieldManager from\n// role. If no managedFields are found in role for fieldManager, a\n// RoleApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// role must be a unmodified Role API object that was retrieved from the Kubernetes API.\n// ExtractRole provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractRole(role *rbacv1alpha1.Role, fieldManager string) (*RoleApplyConfiguration, error) {\n\treturn extractRole(role, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100024244,"name":"ExtractRoleStatus","signature":"func ExtractRoleStatus(role *rbacv1alpha1.Role, fieldManager string) (*RoleApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/role.go","code":"// ExtractRoleStatus is the same as ExtractRole except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractRoleStatus(role *rbacv1alpha1.Role, fieldManager string) (*RoleApplyConfiguration, error) {\n\treturn extractRole(role, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100024245,"name":"extractRole","signature":"func extractRole(role *rbacv1alpha1.Role, fieldManager string, subresource string) (*RoleApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/role.go","code":"func extractRole(role *rbacv1alpha1.Role, fieldManager string, subresource string) (*RoleApplyConfiguration, error) {\n\tb := \u0026RoleApplyConfiguration{}\n\terr := managedfields.ExtractInto(role, internal.Parser().Type(\"io.k8s.api.rbac.v1alpha1.Role\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(role.Name)\n\tb.WithNamespace(role.Namespace)\n\n\tb.WithKind(\"Role\")\n\tb.WithAPIVersion(\"rbac.authorization.k8s.io/v1alpha1\")\n\treturn b, nil\n}","line":{"from":71,"to":83}} {"id":100024246,"name":"WithKind","signature":"func (b *RoleApplyConfiguration) WithKind(value string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/role.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithKind(value string) *RoleApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":85,"to":91}} {"id":100024247,"name":"WithAPIVersion","signature":"func (b *RoleApplyConfiguration) WithAPIVersion(value string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/role.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithAPIVersion(value string) *RoleApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":93,"to":99}} {"id":100024248,"name":"WithName","signature":"func (b *RoleApplyConfiguration) WithName(value string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/role.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithName(value string) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":101,"to":108}} {"id":100024249,"name":"WithGenerateName","signature":"func (b *RoleApplyConfiguration) WithGenerateName(value string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/role.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithGenerateName(value string) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":110,"to":117}} {"id":100024250,"name":"WithNamespace","signature":"func (b *RoleApplyConfiguration) WithNamespace(value string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/role.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithNamespace(value string) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":119,"to":126}} {"id":100024251,"name":"WithUID","signature":"func (b *RoleApplyConfiguration) WithUID(value types.UID) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/role.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithUID(value types.UID) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":128,"to":135}} {"id":100024252,"name":"WithResourceVersion","signature":"func (b *RoleApplyConfiguration) WithResourceVersion(value string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/role.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithResourceVersion(value string) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":137,"to":144}} {"id":100024253,"name":"WithGeneration","signature":"func (b *RoleApplyConfiguration) WithGeneration(value int64) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/role.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithGeneration(value int64) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":146,"to":153}} {"id":100024254,"name":"WithCreationTimestamp","signature":"func (b *RoleApplyConfiguration) WithCreationTimestamp(value metav1.Time) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/role.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithCreationTimestamp(value metav1.Time) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":155,"to":162}} {"id":100024255,"name":"WithDeletionTimestamp","signature":"func (b *RoleApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/role.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":164,"to":171}} {"id":100024256,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *RoleApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/role.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":173,"to":180}} {"id":100024257,"name":"WithLabels","signature":"func (b *RoleApplyConfiguration) WithLabels(entries map[string]string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/role.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *RoleApplyConfiguration) WithLabels(entries map[string]string) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":182,"to":195}} {"id":100024258,"name":"WithAnnotations","signature":"func (b *RoleApplyConfiguration) WithAnnotations(entries map[string]string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/role.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *RoleApplyConfiguration) WithAnnotations(entries map[string]string) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":197,"to":210}} {"id":100024259,"name":"WithOwnerReferences","signature":"func (b *RoleApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/role.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *RoleApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":212,"to":224}} {"id":100024260,"name":"WithFinalizers","signature":"func (b *RoleApplyConfiguration) WithFinalizers(values ...string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/role.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *RoleApplyConfiguration) WithFinalizers(values ...string) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":226,"to":235}} {"id":100024261,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *RoleApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/role.go","code":"func (b *RoleApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":237,"to":241}} {"id":100024262,"name":"WithRules","signature":"func (b *RoleApplyConfiguration) WithRules(values ...*PolicyRuleApplyConfiguration) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/role.go","code":"// WithRules adds the given value to the Rules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Rules field.\nfunc (b *RoleApplyConfiguration) WithRules(values ...*PolicyRuleApplyConfiguration) *RoleApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRules\")\n\t\t}\n\t\tb.Rules = append(b.Rules, *values[i])\n\t}\n\treturn b\n}","line":{"from":243,"to":254}} {"id":100024263,"name":"RoleBinding","signature":"func RoleBinding(name, namespace string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/rolebinding.go","code":"// RoleBinding constructs an declarative configuration of the RoleBinding type for use with\n// apply.\nfunc RoleBinding(name, namespace string) *RoleBindingApplyConfiguration {\n\tb := \u0026RoleBindingApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"RoleBinding\")\n\tb.WithAPIVersion(\"rbac.authorization.k8s.io/v1alpha1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100024264,"name":"ExtractRoleBinding","signature":"func ExtractRoleBinding(roleBinding *rbacv1alpha1.RoleBinding, fieldManager string) (*RoleBindingApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/rolebinding.go","code":"// ExtractRoleBinding extracts the applied configuration owned by fieldManager from\n// roleBinding. If no managedFields are found in roleBinding for fieldManager, a\n// RoleBindingApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// roleBinding must be a unmodified RoleBinding API object that was retrieved from the Kubernetes API.\n// ExtractRoleBinding provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractRoleBinding(roleBinding *rbacv1alpha1.RoleBinding, fieldManager string) (*RoleBindingApplyConfiguration, error) {\n\treturn extractRoleBinding(roleBinding, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100024265,"name":"ExtractRoleBindingStatus","signature":"func ExtractRoleBindingStatus(roleBinding *rbacv1alpha1.RoleBinding, fieldManager string) (*RoleBindingApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/rolebinding.go","code":"// ExtractRoleBindingStatus is the same as ExtractRoleBinding except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractRoleBindingStatus(roleBinding *rbacv1alpha1.RoleBinding, fieldManager string) (*RoleBindingApplyConfiguration, error) {\n\treturn extractRoleBinding(roleBinding, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100024266,"name":"extractRoleBinding","signature":"func extractRoleBinding(roleBinding *rbacv1alpha1.RoleBinding, fieldManager string, subresource string) (*RoleBindingApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/rolebinding.go","code":"func extractRoleBinding(roleBinding *rbacv1alpha1.RoleBinding, fieldManager string, subresource string) (*RoleBindingApplyConfiguration, error) {\n\tb := \u0026RoleBindingApplyConfiguration{}\n\terr := managedfields.ExtractInto(roleBinding, internal.Parser().Type(\"io.k8s.api.rbac.v1alpha1.RoleBinding\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(roleBinding.Name)\n\tb.WithNamespace(roleBinding.Namespace)\n\n\tb.WithKind(\"RoleBinding\")\n\tb.WithAPIVersion(\"rbac.authorization.k8s.io/v1alpha1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100024267,"name":"WithKind","signature":"func (b *RoleBindingApplyConfiguration) WithKind(value string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/rolebinding.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithKind(value string) *RoleBindingApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100024268,"name":"WithAPIVersion","signature":"func (b *RoleBindingApplyConfiguration) WithAPIVersion(value string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/rolebinding.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithAPIVersion(value string) *RoleBindingApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100024269,"name":"WithName","signature":"func (b *RoleBindingApplyConfiguration) WithName(value string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/rolebinding.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithName(value string) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100024270,"name":"WithGenerateName","signature":"func (b *RoleBindingApplyConfiguration) WithGenerateName(value string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/rolebinding.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithGenerateName(value string) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100024271,"name":"WithNamespace","signature":"func (b *RoleBindingApplyConfiguration) WithNamespace(value string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/rolebinding.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithNamespace(value string) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100024272,"name":"WithUID","signature":"func (b *RoleBindingApplyConfiguration) WithUID(value types.UID) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/rolebinding.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithUID(value types.UID) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100024273,"name":"WithResourceVersion","signature":"func (b *RoleBindingApplyConfiguration) WithResourceVersion(value string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/rolebinding.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithResourceVersion(value string) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100024274,"name":"WithGeneration","signature":"func (b *RoleBindingApplyConfiguration) WithGeneration(value int64) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/rolebinding.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithGeneration(value int64) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100024275,"name":"WithCreationTimestamp","signature":"func (b *RoleBindingApplyConfiguration) WithCreationTimestamp(value metav1.Time) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/rolebinding.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithCreationTimestamp(value metav1.Time) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100024276,"name":"WithDeletionTimestamp","signature":"func (b *RoleBindingApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/rolebinding.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100024277,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *RoleBindingApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/rolebinding.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100024278,"name":"WithLabels","signature":"func (b *RoleBindingApplyConfiguration) WithLabels(entries map[string]string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/rolebinding.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *RoleBindingApplyConfiguration) WithLabels(entries map[string]string) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100024279,"name":"WithAnnotations","signature":"func (b *RoleBindingApplyConfiguration) WithAnnotations(entries map[string]string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/rolebinding.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *RoleBindingApplyConfiguration) WithAnnotations(entries map[string]string) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100024280,"name":"WithOwnerReferences","signature":"func (b *RoleBindingApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/rolebinding.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *RoleBindingApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100024281,"name":"WithFinalizers","signature":"func (b *RoleBindingApplyConfiguration) WithFinalizers(values ...string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/rolebinding.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *RoleBindingApplyConfiguration) WithFinalizers(values ...string) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100024282,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *RoleBindingApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/rolebinding.go","code":"func (b *RoleBindingApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100024283,"name":"WithSubjects","signature":"func (b *RoleBindingApplyConfiguration) WithSubjects(values ...*SubjectApplyConfiguration) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/rolebinding.go","code":"// WithSubjects adds the given value to the Subjects field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Subjects field.\nfunc (b *RoleBindingApplyConfiguration) WithSubjects(values ...*SubjectApplyConfiguration) *RoleBindingApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithSubjects\")\n\t\t}\n\t\tb.Subjects = append(b.Subjects, *values[i])\n\t}\n\treturn b\n}","line":{"from":244,"to":255}} {"id":100024284,"name":"WithRoleRef","signature":"func (b *RoleBindingApplyConfiguration) WithRoleRef(value *RoleRefApplyConfiguration) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/rolebinding.go","code":"// WithRoleRef sets the RoleRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RoleRef field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithRoleRef(value *RoleRefApplyConfiguration) *RoleBindingApplyConfiguration {\n\tb.RoleRef = value\n\treturn b\n}","line":{"from":257,"to":263}} {"id":100024285,"name":"RoleRef","signature":"func RoleRef() *RoleRefApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/roleref.go","code":"// RoleRefApplyConfiguration constructs an declarative configuration of the RoleRef type for use with\n// apply.\nfunc RoleRef() *RoleRefApplyConfiguration {\n\treturn \u0026RoleRefApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100024286,"name":"WithAPIGroup","signature":"func (b *RoleRefApplyConfiguration) WithAPIGroup(value string) *RoleRefApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/roleref.go","code":"// WithAPIGroup sets the APIGroup field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIGroup field is set to the value of the last call.\nfunc (b *RoleRefApplyConfiguration) WithAPIGroup(value string) *RoleRefApplyConfiguration {\n\tb.APIGroup = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100024287,"name":"WithKind","signature":"func (b *RoleRefApplyConfiguration) WithKind(value string) *RoleRefApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/roleref.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *RoleRefApplyConfiguration) WithKind(value string) *RoleRefApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100024288,"name":"WithName","signature":"func (b *RoleRefApplyConfiguration) WithName(value string) *RoleRefApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/roleref.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *RoleRefApplyConfiguration) WithName(value string) *RoleRefApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100024289,"name":"Subject","signature":"func Subject() *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/subject.go","code":"// SubjectApplyConfiguration constructs an declarative configuration of the Subject type for use with\n// apply.\nfunc Subject() *SubjectApplyConfiguration {\n\treturn \u0026SubjectApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100024290,"name":"WithKind","signature":"func (b *SubjectApplyConfiguration) WithKind(value string) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/subject.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithKind(value string) *SubjectApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100024291,"name":"WithAPIVersion","signature":"func (b *SubjectApplyConfiguration) WithAPIVersion(value string) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/subject.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithAPIVersion(value string) *SubjectApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100024292,"name":"WithName","signature":"func (b *SubjectApplyConfiguration) WithName(value string) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/subject.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithName(value string) *SubjectApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100024293,"name":"WithNamespace","signature":"func (b *SubjectApplyConfiguration) WithNamespace(value string) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1alpha1/subject.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithNamespace(value string) *SubjectApplyConfiguration {\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100024294,"name":"AggregationRule","signature":"func AggregationRule() *AggregationRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/aggregationrule.go","code":"// AggregationRuleApplyConfiguration constructs an declarative configuration of the AggregationRule type for use with\n// apply.\nfunc AggregationRule() *AggregationRuleApplyConfiguration {\n\treturn \u0026AggregationRuleApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100024295,"name":"WithClusterRoleSelectors","signature":"func (b *AggregationRuleApplyConfiguration) WithClusterRoleSelectors(values ...*v1.LabelSelectorApplyConfiguration) *AggregationRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/aggregationrule.go","code":"// WithClusterRoleSelectors adds the given value to the ClusterRoleSelectors field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ClusterRoleSelectors field.\nfunc (b *AggregationRuleApplyConfiguration) WithClusterRoleSelectors(values ...*v1.LabelSelectorApplyConfiguration) *AggregationRuleApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithClusterRoleSelectors\")\n\t\t}\n\t\tb.ClusterRoleSelectors = append(b.ClusterRoleSelectors, *values[i])\n\t}\n\treturn b\n}","line":{"from":37,"to":48}} {"id":100024296,"name":"ClusterRole","signature":"func ClusterRole(name string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrole.go","code":"// ClusterRole constructs an declarative configuration of the ClusterRole type for use with\n// apply.\nfunc ClusterRole(name string) *ClusterRoleApplyConfiguration {\n\tb := \u0026ClusterRoleApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"ClusterRole\")\n\tb.WithAPIVersion(\"rbac.authorization.k8s.io/v1beta1\")\n\treturn b\n}","line":{"from":39,"to":47}} {"id":100024297,"name":"ExtractClusterRole","signature":"func ExtractClusterRole(clusterRole *rbacv1beta1.ClusterRole, fieldManager string) (*ClusterRoleApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrole.go","code":"// ExtractClusterRole extracts the applied configuration owned by fieldManager from\n// clusterRole. If no managedFields are found in clusterRole for fieldManager, a\n// ClusterRoleApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// clusterRole must be a unmodified ClusterRole API object that was retrieved from the Kubernetes API.\n// ExtractClusterRole provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractClusterRole(clusterRole *rbacv1beta1.ClusterRole, fieldManager string) (*ClusterRoleApplyConfiguration, error) {\n\treturn extractClusterRole(clusterRole, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100024298,"name":"ExtractClusterRoleStatus","signature":"func ExtractClusterRoleStatus(clusterRole *rbacv1beta1.ClusterRole, fieldManager string) (*ClusterRoleApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrole.go","code":"// ExtractClusterRoleStatus is the same as ExtractClusterRole except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractClusterRoleStatus(clusterRole *rbacv1beta1.ClusterRole, fieldManager string) (*ClusterRoleApplyConfiguration, error) {\n\treturn extractClusterRole(clusterRole, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100024299,"name":"extractClusterRole","signature":"func extractClusterRole(clusterRole *rbacv1beta1.ClusterRole, fieldManager string, subresource string) (*ClusterRoleApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrole.go","code":"func extractClusterRole(clusterRole *rbacv1beta1.ClusterRole, fieldManager string, subresource string) (*ClusterRoleApplyConfiguration, error) {\n\tb := \u0026ClusterRoleApplyConfiguration{}\n\terr := managedfields.ExtractInto(clusterRole, internal.Parser().Type(\"io.k8s.api.rbac.v1beta1.ClusterRole\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(clusterRole.Name)\n\n\tb.WithKind(\"ClusterRole\")\n\tb.WithAPIVersion(\"rbac.authorization.k8s.io/v1beta1\")\n\treturn b, nil\n}","line":{"from":71,"to":82}} {"id":100024300,"name":"WithKind","signature":"func (b *ClusterRoleApplyConfiguration) WithKind(value string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrole.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithKind(value string) *ClusterRoleApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100024301,"name":"WithAPIVersion","signature":"func (b *ClusterRoleApplyConfiguration) WithAPIVersion(value string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrole.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithAPIVersion(value string) *ClusterRoleApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100024302,"name":"WithName","signature":"func (b *ClusterRoleApplyConfiguration) WithName(value string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrole.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithName(value string) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":100,"to":107}} {"id":100024303,"name":"WithGenerateName","signature":"func (b *ClusterRoleApplyConfiguration) WithGenerateName(value string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrole.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithGenerateName(value string) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":109,"to":116}} {"id":100024304,"name":"WithNamespace","signature":"func (b *ClusterRoleApplyConfiguration) WithNamespace(value string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrole.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithNamespace(value string) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":118,"to":125}} {"id":100024305,"name":"WithUID","signature":"func (b *ClusterRoleApplyConfiguration) WithUID(value types.UID) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrole.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithUID(value types.UID) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":127,"to":134}} {"id":100024306,"name":"WithResourceVersion","signature":"func (b *ClusterRoleApplyConfiguration) WithResourceVersion(value string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrole.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithResourceVersion(value string) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":136,"to":143}} {"id":100024307,"name":"WithGeneration","signature":"func (b *ClusterRoleApplyConfiguration) WithGeneration(value int64) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrole.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithGeneration(value int64) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":145,"to":152}} {"id":100024308,"name":"WithCreationTimestamp","signature":"func (b *ClusterRoleApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrole.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":154,"to":161}} {"id":100024309,"name":"WithDeletionTimestamp","signature":"func (b *ClusterRoleApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrole.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":163,"to":170}} {"id":100024310,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ClusterRoleApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrole.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":172,"to":179}} {"id":100024311,"name":"WithLabels","signature":"func (b *ClusterRoleApplyConfiguration) WithLabels(entries map[string]string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrole.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ClusterRoleApplyConfiguration) WithLabels(entries map[string]string) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":181,"to":194}} {"id":100024312,"name":"WithAnnotations","signature":"func (b *ClusterRoleApplyConfiguration) WithAnnotations(entries map[string]string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrole.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ClusterRoleApplyConfiguration) WithAnnotations(entries map[string]string) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100024313,"name":"WithOwnerReferences","signature":"func (b *ClusterRoleApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrole.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ClusterRoleApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":211,"to":223}} {"id":100024314,"name":"WithFinalizers","signature":"func (b *ClusterRoleApplyConfiguration) WithFinalizers(values ...string) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrole.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ClusterRoleApplyConfiguration) WithFinalizers(values ...string) *ClusterRoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":225,"to":234}} {"id":100024315,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ClusterRoleApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrole.go","code":"func (b *ClusterRoleApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":236,"to":240}} {"id":100024316,"name":"WithRules","signature":"func (b *ClusterRoleApplyConfiguration) WithRules(values ...*PolicyRuleApplyConfiguration) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrole.go","code":"// WithRules adds the given value to the Rules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Rules field.\nfunc (b *ClusterRoleApplyConfiguration) WithRules(values ...*PolicyRuleApplyConfiguration) *ClusterRoleApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRules\")\n\t\t}\n\t\tb.Rules = append(b.Rules, *values[i])\n\t}\n\treturn b\n}","line":{"from":242,"to":253}} {"id":100024317,"name":"WithAggregationRule","signature":"func (b *ClusterRoleApplyConfiguration) WithAggregationRule(value *AggregationRuleApplyConfiguration) *ClusterRoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrole.go","code":"// WithAggregationRule sets the AggregationRule field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AggregationRule field is set to the value of the last call.\nfunc (b *ClusterRoleApplyConfiguration) WithAggregationRule(value *AggregationRuleApplyConfiguration) *ClusterRoleApplyConfiguration {\n\tb.AggregationRule = value\n\treturn b\n}","line":{"from":255,"to":261}} {"id":100024318,"name":"ClusterRoleBinding","signature":"func ClusterRoleBinding(name string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrolebinding.go","code":"// ClusterRoleBinding constructs an declarative configuration of the ClusterRoleBinding type for use with\n// apply.\nfunc ClusterRoleBinding(name string) *ClusterRoleBindingApplyConfiguration {\n\tb := \u0026ClusterRoleBindingApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"ClusterRoleBinding\")\n\tb.WithAPIVersion(\"rbac.authorization.k8s.io/v1beta1\")\n\treturn b\n}","line":{"from":39,"to":47}} {"id":100024319,"name":"ExtractClusterRoleBinding","signature":"func ExtractClusterRoleBinding(clusterRoleBinding *rbacv1beta1.ClusterRoleBinding, fieldManager string) (*ClusterRoleBindingApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrolebinding.go","code":"// ExtractClusterRoleBinding extracts the applied configuration owned by fieldManager from\n// clusterRoleBinding. If no managedFields are found in clusterRoleBinding for fieldManager, a\n// ClusterRoleBindingApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// clusterRoleBinding must be a unmodified ClusterRoleBinding API object that was retrieved from the Kubernetes API.\n// ExtractClusterRoleBinding provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractClusterRoleBinding(clusterRoleBinding *rbacv1beta1.ClusterRoleBinding, fieldManager string) (*ClusterRoleBindingApplyConfiguration, error) {\n\treturn extractClusterRoleBinding(clusterRoleBinding, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100024320,"name":"ExtractClusterRoleBindingStatus","signature":"func ExtractClusterRoleBindingStatus(clusterRoleBinding *rbacv1beta1.ClusterRoleBinding, fieldManager string) (*ClusterRoleBindingApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrolebinding.go","code":"// ExtractClusterRoleBindingStatus is the same as ExtractClusterRoleBinding except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractClusterRoleBindingStatus(clusterRoleBinding *rbacv1beta1.ClusterRoleBinding, fieldManager string) (*ClusterRoleBindingApplyConfiguration, error) {\n\treturn extractClusterRoleBinding(clusterRoleBinding, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100024321,"name":"extractClusterRoleBinding","signature":"func extractClusterRoleBinding(clusterRoleBinding *rbacv1beta1.ClusterRoleBinding, fieldManager string, subresource string) (*ClusterRoleBindingApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrolebinding.go","code":"func extractClusterRoleBinding(clusterRoleBinding *rbacv1beta1.ClusterRoleBinding, fieldManager string, subresource string) (*ClusterRoleBindingApplyConfiguration, error) {\n\tb := \u0026ClusterRoleBindingApplyConfiguration{}\n\terr := managedfields.ExtractInto(clusterRoleBinding, internal.Parser().Type(\"io.k8s.api.rbac.v1beta1.ClusterRoleBinding\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(clusterRoleBinding.Name)\n\n\tb.WithKind(\"ClusterRoleBinding\")\n\tb.WithAPIVersion(\"rbac.authorization.k8s.io/v1beta1\")\n\treturn b, nil\n}","line":{"from":71,"to":82}} {"id":100024322,"name":"WithKind","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithKind(value string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrolebinding.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithKind(value string) *ClusterRoleBindingApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100024323,"name":"WithAPIVersion","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithAPIVersion(value string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrolebinding.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithAPIVersion(value string) *ClusterRoleBindingApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100024324,"name":"WithName","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithName(value string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrolebinding.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithName(value string) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":100,"to":107}} {"id":100024325,"name":"WithGenerateName","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithGenerateName(value string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrolebinding.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithGenerateName(value string) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":109,"to":116}} {"id":100024326,"name":"WithNamespace","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithNamespace(value string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrolebinding.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithNamespace(value string) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":118,"to":125}} {"id":100024327,"name":"WithUID","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithUID(value types.UID) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrolebinding.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithUID(value types.UID) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":127,"to":134}} {"id":100024328,"name":"WithResourceVersion","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithResourceVersion(value string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrolebinding.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithResourceVersion(value string) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":136,"to":143}} {"id":100024329,"name":"WithGeneration","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithGeneration(value int64) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrolebinding.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithGeneration(value int64) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":145,"to":152}} {"id":100024330,"name":"WithCreationTimestamp","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrolebinding.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":154,"to":161}} {"id":100024331,"name":"WithDeletionTimestamp","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrolebinding.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":163,"to":170}} {"id":100024332,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrolebinding.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":172,"to":179}} {"id":100024333,"name":"WithLabels","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithLabels(entries map[string]string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrolebinding.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithLabels(entries map[string]string) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":181,"to":194}} {"id":100024334,"name":"WithAnnotations","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithAnnotations(entries map[string]string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrolebinding.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithAnnotations(entries map[string]string) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100024335,"name":"WithOwnerReferences","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrolebinding.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":211,"to":223}} {"id":100024336,"name":"WithFinalizers","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithFinalizers(values ...string) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrolebinding.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithFinalizers(values ...string) *ClusterRoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":225,"to":234}} {"id":100024337,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ClusterRoleBindingApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrolebinding.go","code":"func (b *ClusterRoleBindingApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":236,"to":240}} {"id":100024338,"name":"WithSubjects","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithSubjects(values ...*SubjectApplyConfiguration) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrolebinding.go","code":"// WithSubjects adds the given value to the Subjects field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Subjects field.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithSubjects(values ...*SubjectApplyConfiguration) *ClusterRoleBindingApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithSubjects\")\n\t\t}\n\t\tb.Subjects = append(b.Subjects, *values[i])\n\t}\n\treturn b\n}","line":{"from":242,"to":253}} {"id":100024339,"name":"WithRoleRef","signature":"func (b *ClusterRoleBindingApplyConfiguration) WithRoleRef(value *RoleRefApplyConfiguration) *ClusterRoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/clusterrolebinding.go","code":"// WithRoleRef sets the RoleRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RoleRef field is set to the value of the last call.\nfunc (b *ClusterRoleBindingApplyConfiguration) WithRoleRef(value *RoleRefApplyConfiguration) *ClusterRoleBindingApplyConfiguration {\n\tb.RoleRef = value\n\treturn b\n}","line":{"from":255,"to":261}} {"id":100024340,"name":"PolicyRule","signature":"func PolicyRule() *PolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/policyrule.go","code":"// PolicyRuleApplyConfiguration constructs an declarative configuration of the PolicyRule type for use with\n// apply.\nfunc PolicyRule() *PolicyRuleApplyConfiguration {\n\treturn \u0026PolicyRuleApplyConfiguration{}\n}","line":{"from":31,"to":35}} {"id":100024341,"name":"WithVerbs","signature":"func (b *PolicyRuleApplyConfiguration) WithVerbs(values ...string) *PolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/policyrule.go","code":"// WithVerbs adds the given value to the Verbs field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Verbs field.\nfunc (b *PolicyRuleApplyConfiguration) WithVerbs(values ...string) *PolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.Verbs = append(b.Verbs, values[i])\n\t}\n\treturn b\n}","line":{"from":37,"to":45}} {"id":100024342,"name":"WithAPIGroups","signature":"func (b *PolicyRuleApplyConfiguration) WithAPIGroups(values ...string) *PolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/policyrule.go","code":"// WithAPIGroups adds the given value to the APIGroups field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the APIGroups field.\nfunc (b *PolicyRuleApplyConfiguration) WithAPIGroups(values ...string) *PolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.APIGroups = append(b.APIGroups, values[i])\n\t}\n\treturn b\n}","line":{"from":47,"to":55}} {"id":100024343,"name":"WithResources","signature":"func (b *PolicyRuleApplyConfiguration) WithResources(values ...string) *PolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/policyrule.go","code":"// WithResources adds the given value to the Resources field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Resources field.\nfunc (b *PolicyRuleApplyConfiguration) WithResources(values ...string) *PolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.Resources = append(b.Resources, values[i])\n\t}\n\treturn b\n}","line":{"from":57,"to":65}} {"id":100024344,"name":"WithResourceNames","signature":"func (b *PolicyRuleApplyConfiguration) WithResourceNames(values ...string) *PolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/policyrule.go","code":"// WithResourceNames adds the given value to the ResourceNames field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ResourceNames field.\nfunc (b *PolicyRuleApplyConfiguration) WithResourceNames(values ...string) *PolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.ResourceNames = append(b.ResourceNames, values[i])\n\t}\n\treturn b\n}","line":{"from":67,"to":75}} {"id":100024345,"name":"WithNonResourceURLs","signature":"func (b *PolicyRuleApplyConfiguration) WithNonResourceURLs(values ...string) *PolicyRuleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/policyrule.go","code":"// WithNonResourceURLs adds the given value to the NonResourceURLs field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the NonResourceURLs field.\nfunc (b *PolicyRuleApplyConfiguration) WithNonResourceURLs(values ...string) *PolicyRuleApplyConfiguration {\n\tfor i := range values {\n\t\tb.NonResourceURLs = append(b.NonResourceURLs, values[i])\n\t}\n\treturn b\n}","line":{"from":77,"to":85}} {"id":100024346,"name":"Role","signature":"func Role(name, namespace string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/role.go","code":"// Role constructs an declarative configuration of the Role type for use with\n// apply.\nfunc Role(name, namespace string) *RoleApplyConfiguration {\n\tb := \u0026RoleApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"Role\")\n\tb.WithAPIVersion(\"rbac.authorization.k8s.io/v1beta1\")\n\treturn b\n}","line":{"from":38,"to":47}} {"id":100024347,"name":"ExtractRole","signature":"func ExtractRole(role *rbacv1beta1.Role, fieldManager string) (*RoleApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/role.go","code":"// ExtractRole extracts the applied configuration owned by fieldManager from\n// role. If no managedFields are found in role for fieldManager, a\n// RoleApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// role must be a unmodified Role API object that was retrieved from the Kubernetes API.\n// ExtractRole provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractRole(role *rbacv1beta1.Role, fieldManager string) (*RoleApplyConfiguration, error) {\n\treturn extractRole(role, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100024348,"name":"ExtractRoleStatus","signature":"func ExtractRoleStatus(role *rbacv1beta1.Role, fieldManager string) (*RoleApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/role.go","code":"// ExtractRoleStatus is the same as ExtractRole except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractRoleStatus(role *rbacv1beta1.Role, fieldManager string) (*RoleApplyConfiguration, error) {\n\treturn extractRole(role, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100024349,"name":"extractRole","signature":"func extractRole(role *rbacv1beta1.Role, fieldManager string, subresource string) (*RoleApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/role.go","code":"func extractRole(role *rbacv1beta1.Role, fieldManager string, subresource string) (*RoleApplyConfiguration, error) {\n\tb := \u0026RoleApplyConfiguration{}\n\terr := managedfields.ExtractInto(role, internal.Parser().Type(\"io.k8s.api.rbac.v1beta1.Role\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(role.Name)\n\tb.WithNamespace(role.Namespace)\n\n\tb.WithKind(\"Role\")\n\tb.WithAPIVersion(\"rbac.authorization.k8s.io/v1beta1\")\n\treturn b, nil\n}","line":{"from":71,"to":83}} {"id":100024350,"name":"WithKind","signature":"func (b *RoleApplyConfiguration) WithKind(value string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/role.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithKind(value string) *RoleApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":85,"to":91}} {"id":100024351,"name":"WithAPIVersion","signature":"func (b *RoleApplyConfiguration) WithAPIVersion(value string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/role.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithAPIVersion(value string) *RoleApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":93,"to":99}} {"id":100024352,"name":"WithName","signature":"func (b *RoleApplyConfiguration) WithName(value string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/role.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithName(value string) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":101,"to":108}} {"id":100024353,"name":"WithGenerateName","signature":"func (b *RoleApplyConfiguration) WithGenerateName(value string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/role.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithGenerateName(value string) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":110,"to":117}} {"id":100024354,"name":"WithNamespace","signature":"func (b *RoleApplyConfiguration) WithNamespace(value string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/role.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithNamespace(value string) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":119,"to":126}} {"id":100024355,"name":"WithUID","signature":"func (b *RoleApplyConfiguration) WithUID(value types.UID) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/role.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithUID(value types.UID) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":128,"to":135}} {"id":100024356,"name":"WithResourceVersion","signature":"func (b *RoleApplyConfiguration) WithResourceVersion(value string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/role.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithResourceVersion(value string) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":137,"to":144}} {"id":100024357,"name":"WithGeneration","signature":"func (b *RoleApplyConfiguration) WithGeneration(value int64) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/role.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithGeneration(value int64) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":146,"to":153}} {"id":100024358,"name":"WithCreationTimestamp","signature":"func (b *RoleApplyConfiguration) WithCreationTimestamp(value metav1.Time) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/role.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithCreationTimestamp(value metav1.Time) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":155,"to":162}} {"id":100024359,"name":"WithDeletionTimestamp","signature":"func (b *RoleApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/role.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":164,"to":171}} {"id":100024360,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *RoleApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/role.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *RoleApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":173,"to":180}} {"id":100024361,"name":"WithLabels","signature":"func (b *RoleApplyConfiguration) WithLabels(entries map[string]string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/role.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *RoleApplyConfiguration) WithLabels(entries map[string]string) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":182,"to":195}} {"id":100024362,"name":"WithAnnotations","signature":"func (b *RoleApplyConfiguration) WithAnnotations(entries map[string]string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/role.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *RoleApplyConfiguration) WithAnnotations(entries map[string]string) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":197,"to":210}} {"id":100024363,"name":"WithOwnerReferences","signature":"func (b *RoleApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/role.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *RoleApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":212,"to":224}} {"id":100024364,"name":"WithFinalizers","signature":"func (b *RoleApplyConfiguration) WithFinalizers(values ...string) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/role.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *RoleApplyConfiguration) WithFinalizers(values ...string) *RoleApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":226,"to":235}} {"id":100024365,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *RoleApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/role.go","code":"func (b *RoleApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":237,"to":241}} {"id":100024366,"name":"WithRules","signature":"func (b *RoleApplyConfiguration) WithRules(values ...*PolicyRuleApplyConfiguration) *RoleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/role.go","code":"// WithRules adds the given value to the Rules field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Rules field.\nfunc (b *RoleApplyConfiguration) WithRules(values ...*PolicyRuleApplyConfiguration) *RoleApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithRules\")\n\t\t}\n\t\tb.Rules = append(b.Rules, *values[i])\n\t}\n\treturn b\n}","line":{"from":243,"to":254}} {"id":100024367,"name":"RoleBinding","signature":"func RoleBinding(name, namespace string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/rolebinding.go","code":"// RoleBinding constructs an declarative configuration of the RoleBinding type for use with\n// apply.\nfunc RoleBinding(name, namespace string) *RoleBindingApplyConfiguration {\n\tb := \u0026RoleBindingApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"RoleBinding\")\n\tb.WithAPIVersion(\"rbac.authorization.k8s.io/v1beta1\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100024368,"name":"ExtractRoleBinding","signature":"func ExtractRoleBinding(roleBinding *rbacv1beta1.RoleBinding, fieldManager string) (*RoleBindingApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/rolebinding.go","code":"// ExtractRoleBinding extracts the applied configuration owned by fieldManager from\n// roleBinding. If no managedFields are found in roleBinding for fieldManager, a\n// RoleBindingApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// roleBinding must be a unmodified RoleBinding API object that was retrieved from the Kubernetes API.\n// ExtractRoleBinding provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractRoleBinding(roleBinding *rbacv1beta1.RoleBinding, fieldManager string) (*RoleBindingApplyConfiguration, error) {\n\treturn extractRoleBinding(roleBinding, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100024369,"name":"ExtractRoleBindingStatus","signature":"func ExtractRoleBindingStatus(roleBinding *rbacv1beta1.RoleBinding, fieldManager string) (*RoleBindingApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/rolebinding.go","code":"// ExtractRoleBindingStatus is the same as ExtractRoleBinding except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractRoleBindingStatus(roleBinding *rbacv1beta1.RoleBinding, fieldManager string) (*RoleBindingApplyConfiguration, error) {\n\treturn extractRoleBinding(roleBinding, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100024370,"name":"extractRoleBinding","signature":"func extractRoleBinding(roleBinding *rbacv1beta1.RoleBinding, fieldManager string, subresource string) (*RoleBindingApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/rolebinding.go","code":"func extractRoleBinding(roleBinding *rbacv1beta1.RoleBinding, fieldManager string, subresource string) (*RoleBindingApplyConfiguration, error) {\n\tb := \u0026RoleBindingApplyConfiguration{}\n\terr := managedfields.ExtractInto(roleBinding, internal.Parser().Type(\"io.k8s.api.rbac.v1beta1.RoleBinding\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(roleBinding.Name)\n\tb.WithNamespace(roleBinding.Namespace)\n\n\tb.WithKind(\"RoleBinding\")\n\tb.WithAPIVersion(\"rbac.authorization.k8s.io/v1beta1\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100024371,"name":"WithKind","signature":"func (b *RoleBindingApplyConfiguration) WithKind(value string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/rolebinding.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithKind(value string) *RoleBindingApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100024372,"name":"WithAPIVersion","signature":"func (b *RoleBindingApplyConfiguration) WithAPIVersion(value string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/rolebinding.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithAPIVersion(value string) *RoleBindingApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100024373,"name":"WithName","signature":"func (b *RoleBindingApplyConfiguration) WithName(value string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/rolebinding.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithName(value string) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100024374,"name":"WithGenerateName","signature":"func (b *RoleBindingApplyConfiguration) WithGenerateName(value string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/rolebinding.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithGenerateName(value string) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100024375,"name":"WithNamespace","signature":"func (b *RoleBindingApplyConfiguration) WithNamespace(value string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/rolebinding.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithNamespace(value string) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100024376,"name":"WithUID","signature":"func (b *RoleBindingApplyConfiguration) WithUID(value types.UID) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/rolebinding.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithUID(value types.UID) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100024377,"name":"WithResourceVersion","signature":"func (b *RoleBindingApplyConfiguration) WithResourceVersion(value string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/rolebinding.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithResourceVersion(value string) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100024378,"name":"WithGeneration","signature":"func (b *RoleBindingApplyConfiguration) WithGeneration(value int64) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/rolebinding.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithGeneration(value int64) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100024379,"name":"WithCreationTimestamp","signature":"func (b *RoleBindingApplyConfiguration) WithCreationTimestamp(value metav1.Time) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/rolebinding.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithCreationTimestamp(value metav1.Time) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100024380,"name":"WithDeletionTimestamp","signature":"func (b *RoleBindingApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/rolebinding.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100024381,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *RoleBindingApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/rolebinding.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100024382,"name":"WithLabels","signature":"func (b *RoleBindingApplyConfiguration) WithLabels(entries map[string]string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/rolebinding.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *RoleBindingApplyConfiguration) WithLabels(entries map[string]string) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100024383,"name":"WithAnnotations","signature":"func (b *RoleBindingApplyConfiguration) WithAnnotations(entries map[string]string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/rolebinding.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *RoleBindingApplyConfiguration) WithAnnotations(entries map[string]string) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100024384,"name":"WithOwnerReferences","signature":"func (b *RoleBindingApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/rolebinding.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *RoleBindingApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100024385,"name":"WithFinalizers","signature":"func (b *RoleBindingApplyConfiguration) WithFinalizers(values ...string) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/rolebinding.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *RoleBindingApplyConfiguration) WithFinalizers(values ...string) *RoleBindingApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100024386,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *RoleBindingApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/rolebinding.go","code":"func (b *RoleBindingApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100024387,"name":"WithSubjects","signature":"func (b *RoleBindingApplyConfiguration) WithSubjects(values ...*SubjectApplyConfiguration) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/rolebinding.go","code":"// WithSubjects adds the given value to the Subjects field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Subjects field.\nfunc (b *RoleBindingApplyConfiguration) WithSubjects(values ...*SubjectApplyConfiguration) *RoleBindingApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithSubjects\")\n\t\t}\n\t\tb.Subjects = append(b.Subjects, *values[i])\n\t}\n\treturn b\n}","line":{"from":244,"to":255}} {"id":100024388,"name":"WithRoleRef","signature":"func (b *RoleBindingApplyConfiguration) WithRoleRef(value *RoleRefApplyConfiguration) *RoleBindingApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/rolebinding.go","code":"// WithRoleRef sets the RoleRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RoleRef field is set to the value of the last call.\nfunc (b *RoleBindingApplyConfiguration) WithRoleRef(value *RoleRefApplyConfiguration) *RoleBindingApplyConfiguration {\n\tb.RoleRef = value\n\treturn b\n}","line":{"from":257,"to":263}} {"id":100024389,"name":"RoleRef","signature":"func RoleRef() *RoleRefApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/roleref.go","code":"// RoleRefApplyConfiguration constructs an declarative configuration of the RoleRef type for use with\n// apply.\nfunc RoleRef() *RoleRefApplyConfiguration {\n\treturn \u0026RoleRefApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100024390,"name":"WithAPIGroup","signature":"func (b *RoleRefApplyConfiguration) WithAPIGroup(value string) *RoleRefApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/roleref.go","code":"// WithAPIGroup sets the APIGroup field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIGroup field is set to the value of the last call.\nfunc (b *RoleRefApplyConfiguration) WithAPIGroup(value string) *RoleRefApplyConfiguration {\n\tb.APIGroup = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100024391,"name":"WithKind","signature":"func (b *RoleRefApplyConfiguration) WithKind(value string) *RoleRefApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/roleref.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *RoleRefApplyConfiguration) WithKind(value string) *RoleRefApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100024392,"name":"WithName","signature":"func (b *RoleRefApplyConfiguration) WithName(value string) *RoleRefApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/roleref.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *RoleRefApplyConfiguration) WithName(value string) *RoleRefApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100024393,"name":"Subject","signature":"func Subject() *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/subject.go","code":"// SubjectApplyConfiguration constructs an declarative configuration of the Subject type for use with\n// apply.\nfunc Subject() *SubjectApplyConfiguration {\n\treturn \u0026SubjectApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100024394,"name":"WithKind","signature":"func (b *SubjectApplyConfiguration) WithKind(value string) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/subject.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithKind(value string) *SubjectApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100024395,"name":"WithAPIGroup","signature":"func (b *SubjectApplyConfiguration) WithAPIGroup(value string) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/subject.go","code":"// WithAPIGroup sets the APIGroup field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIGroup field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithAPIGroup(value string) *SubjectApplyConfiguration {\n\tb.APIGroup = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100024396,"name":"WithName","signature":"func (b *SubjectApplyConfiguration) WithName(value string) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/subject.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithName(value string) *SubjectApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100024397,"name":"WithNamespace","signature":"func (b *SubjectApplyConfiguration) WithNamespace(value string) *SubjectApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/rbac/v1beta1/subject.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *SubjectApplyConfiguration) WithNamespace(value string) *SubjectApplyConfiguration {\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100024398,"name":"AllocationResult","signature":"func AllocationResult() *AllocationResultApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/allocationresult.go","code":"// AllocationResultApplyConfiguration constructs an declarative configuration of the AllocationResult type for use with\n// apply.\nfunc AllocationResult() *AllocationResultApplyConfiguration {\n\treturn \u0026AllocationResultApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100024399,"name":"WithResourceHandles","signature":"func (b *AllocationResultApplyConfiguration) WithResourceHandles(values ...*ResourceHandleApplyConfiguration) *AllocationResultApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/allocationresult.go","code":"// WithResourceHandles adds the given value to the ResourceHandles field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ResourceHandles field.\nfunc (b *AllocationResultApplyConfiguration) WithResourceHandles(values ...*ResourceHandleApplyConfiguration) *AllocationResultApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithResourceHandles\")\n\t\t}\n\t\tb.ResourceHandles = append(b.ResourceHandles, *values[i])\n\t}\n\treturn b\n}","line":{"from":39,"to":50}} {"id":100024400,"name":"WithAvailableOnNodes","signature":"func (b *AllocationResultApplyConfiguration) WithAvailableOnNodes(value *v1.NodeSelectorApplyConfiguration) *AllocationResultApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/allocationresult.go","code":"// WithAvailableOnNodes sets the AvailableOnNodes field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AvailableOnNodes field is set to the value of the last call.\nfunc (b *AllocationResultApplyConfiguration) WithAvailableOnNodes(value *v1.NodeSelectorApplyConfiguration) *AllocationResultApplyConfiguration {\n\tb.AvailableOnNodes = value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100024401,"name":"WithShareable","signature":"func (b *AllocationResultApplyConfiguration) WithShareable(value bool) *AllocationResultApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/allocationresult.go","code":"// WithShareable sets the Shareable field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Shareable field is set to the value of the last call.\nfunc (b *AllocationResultApplyConfiguration) WithShareable(value bool) *AllocationResultApplyConfiguration {\n\tb.Shareable = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100024402,"name":"PodSchedulingContext","signature":"func PodSchedulingContext(name, namespace string) *PodSchedulingContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontext.go","code":"// PodSchedulingContext constructs an declarative configuration of the PodSchedulingContext type for use with\n// apply.\nfunc PodSchedulingContext(name, namespace string) *PodSchedulingContextApplyConfiguration {\n\tb := \u0026PodSchedulingContextApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"PodSchedulingContext\")\n\tb.WithAPIVersion(\"resource.k8s.io/v1alpha2\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100024403,"name":"ExtractPodSchedulingContext","signature":"func ExtractPodSchedulingContext(podSchedulingContext *resourcev1alpha2.PodSchedulingContext, fieldManager string) (*PodSchedulingContextApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontext.go","code":"// ExtractPodSchedulingContext extracts the applied configuration owned by fieldManager from\n// podSchedulingContext. If no managedFields are found in podSchedulingContext for fieldManager, a\n// PodSchedulingContextApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// podSchedulingContext must be a unmodified PodSchedulingContext API object that was retrieved from the Kubernetes API.\n// ExtractPodSchedulingContext provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractPodSchedulingContext(podSchedulingContext *resourcev1alpha2.PodSchedulingContext, fieldManager string) (*PodSchedulingContextApplyConfiguration, error) {\n\treturn extractPodSchedulingContext(podSchedulingContext, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100024404,"name":"ExtractPodSchedulingContextStatus","signature":"func ExtractPodSchedulingContextStatus(podSchedulingContext *resourcev1alpha2.PodSchedulingContext, fieldManager string) (*PodSchedulingContextApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontext.go","code":"// ExtractPodSchedulingContextStatus is the same as ExtractPodSchedulingContext except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractPodSchedulingContextStatus(podSchedulingContext *resourcev1alpha2.PodSchedulingContext, fieldManager string) (*PodSchedulingContextApplyConfiguration, error) {\n\treturn extractPodSchedulingContext(podSchedulingContext, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100024405,"name":"extractPodSchedulingContext","signature":"func extractPodSchedulingContext(podSchedulingContext *resourcev1alpha2.PodSchedulingContext, fieldManager string, subresource string) (*PodSchedulingContextApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontext.go","code":"func extractPodSchedulingContext(podSchedulingContext *resourcev1alpha2.PodSchedulingContext, fieldManager string, subresource string) (*PodSchedulingContextApplyConfiguration, error) {\n\tb := \u0026PodSchedulingContextApplyConfiguration{}\n\terr := managedfields.ExtractInto(podSchedulingContext, internal.Parser().Type(\"io.k8s.api.resource.v1alpha2.PodSchedulingContext\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(podSchedulingContext.Name)\n\tb.WithNamespace(podSchedulingContext.Namespace)\n\n\tb.WithKind(\"PodSchedulingContext\")\n\tb.WithAPIVersion(\"resource.k8s.io/v1alpha2\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100024406,"name":"WithKind","signature":"func (b *PodSchedulingContextApplyConfiguration) WithKind(value string) *PodSchedulingContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontext.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *PodSchedulingContextApplyConfiguration) WithKind(value string) *PodSchedulingContextApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100024407,"name":"WithAPIVersion","signature":"func (b *PodSchedulingContextApplyConfiguration) WithAPIVersion(value string) *PodSchedulingContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontext.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *PodSchedulingContextApplyConfiguration) WithAPIVersion(value string) *PodSchedulingContextApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100024408,"name":"WithName","signature":"func (b *PodSchedulingContextApplyConfiguration) WithName(value string) *PodSchedulingContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontext.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *PodSchedulingContextApplyConfiguration) WithName(value string) *PodSchedulingContextApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100024409,"name":"WithGenerateName","signature":"func (b *PodSchedulingContextApplyConfiguration) WithGenerateName(value string) *PodSchedulingContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontext.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *PodSchedulingContextApplyConfiguration) WithGenerateName(value string) *PodSchedulingContextApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100024410,"name":"WithNamespace","signature":"func (b *PodSchedulingContextApplyConfiguration) WithNamespace(value string) *PodSchedulingContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontext.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *PodSchedulingContextApplyConfiguration) WithNamespace(value string) *PodSchedulingContextApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100024411,"name":"WithUID","signature":"func (b *PodSchedulingContextApplyConfiguration) WithUID(value types.UID) *PodSchedulingContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontext.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *PodSchedulingContextApplyConfiguration) WithUID(value types.UID) *PodSchedulingContextApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100024412,"name":"WithResourceVersion","signature":"func (b *PodSchedulingContextApplyConfiguration) WithResourceVersion(value string) *PodSchedulingContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontext.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *PodSchedulingContextApplyConfiguration) WithResourceVersion(value string) *PodSchedulingContextApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100024413,"name":"WithGeneration","signature":"func (b *PodSchedulingContextApplyConfiguration) WithGeneration(value int64) *PodSchedulingContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontext.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *PodSchedulingContextApplyConfiguration) WithGeneration(value int64) *PodSchedulingContextApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100024414,"name":"WithCreationTimestamp","signature":"func (b *PodSchedulingContextApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PodSchedulingContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontext.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *PodSchedulingContextApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PodSchedulingContextApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100024415,"name":"WithDeletionTimestamp","signature":"func (b *PodSchedulingContextApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PodSchedulingContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontext.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *PodSchedulingContextApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PodSchedulingContextApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100024416,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *PodSchedulingContextApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PodSchedulingContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontext.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *PodSchedulingContextApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PodSchedulingContextApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100024417,"name":"WithLabels","signature":"func (b *PodSchedulingContextApplyConfiguration) WithLabels(entries map[string]string) *PodSchedulingContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontext.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *PodSchedulingContextApplyConfiguration) WithLabels(entries map[string]string) *PodSchedulingContextApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100024418,"name":"WithAnnotations","signature":"func (b *PodSchedulingContextApplyConfiguration) WithAnnotations(entries map[string]string) *PodSchedulingContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontext.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *PodSchedulingContextApplyConfiguration) WithAnnotations(entries map[string]string) *PodSchedulingContextApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100024419,"name":"WithOwnerReferences","signature":"func (b *PodSchedulingContextApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PodSchedulingContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontext.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *PodSchedulingContextApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PodSchedulingContextApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100024420,"name":"WithFinalizers","signature":"func (b *PodSchedulingContextApplyConfiguration) WithFinalizers(values ...string) *PodSchedulingContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontext.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *PodSchedulingContextApplyConfiguration) WithFinalizers(values ...string) *PodSchedulingContextApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100024421,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *PodSchedulingContextApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontext.go","code":"func (b *PodSchedulingContextApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100024422,"name":"WithSpec","signature":"func (b *PodSchedulingContextApplyConfiguration) WithSpec(value *PodSchedulingContextSpecApplyConfiguration) *PodSchedulingContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontext.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *PodSchedulingContextApplyConfiguration) WithSpec(value *PodSchedulingContextSpecApplyConfiguration) *PodSchedulingContextApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100024423,"name":"WithStatus","signature":"func (b *PodSchedulingContextApplyConfiguration) WithStatus(value *PodSchedulingContextStatusApplyConfiguration) *PodSchedulingContextApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontext.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *PodSchedulingContextApplyConfiguration) WithStatus(value *PodSchedulingContextStatusApplyConfiguration) *PodSchedulingContextApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100024424,"name":"PodSchedulingContextSpec","signature":"func PodSchedulingContextSpec() *PodSchedulingContextSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontextspec.go","code":"// PodSchedulingContextSpecApplyConfiguration constructs an declarative configuration of the PodSchedulingContextSpec type for use with\n// apply.\nfunc PodSchedulingContextSpec() *PodSchedulingContextSpecApplyConfiguration {\n\treturn \u0026PodSchedulingContextSpecApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100024425,"name":"WithSelectedNode","signature":"func (b *PodSchedulingContextSpecApplyConfiguration) WithSelectedNode(value string) *PodSchedulingContextSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontextspec.go","code":"// WithSelectedNode sets the SelectedNode field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SelectedNode field is set to the value of the last call.\nfunc (b *PodSchedulingContextSpecApplyConfiguration) WithSelectedNode(value string) *PodSchedulingContextSpecApplyConfiguration {\n\tb.SelectedNode = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100024426,"name":"WithPotentialNodes","signature":"func (b *PodSchedulingContextSpecApplyConfiguration) WithPotentialNodes(values ...string) *PodSchedulingContextSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontextspec.go","code":"// WithPotentialNodes adds the given value to the PotentialNodes field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the PotentialNodes field.\nfunc (b *PodSchedulingContextSpecApplyConfiguration) WithPotentialNodes(values ...string) *PodSchedulingContextSpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.PotentialNodes = append(b.PotentialNodes, values[i])\n\t}\n\treturn b\n}","line":{"from":42,"to":50}} {"id":100024427,"name":"PodSchedulingContextStatus","signature":"func PodSchedulingContextStatus() *PodSchedulingContextStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontextstatus.go","code":"// PodSchedulingContextStatusApplyConfiguration constructs an declarative configuration of the PodSchedulingContextStatus type for use with\n// apply.\nfunc PodSchedulingContextStatus() *PodSchedulingContextStatusApplyConfiguration {\n\treturn \u0026PodSchedulingContextStatusApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100024428,"name":"WithResourceClaims","signature":"func (b *PodSchedulingContextStatusApplyConfiguration) WithResourceClaims(values ...*ResourceClaimSchedulingStatusApplyConfiguration) *PodSchedulingContextStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/podschedulingcontextstatus.go","code":"// WithResourceClaims adds the given value to the ResourceClaims field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ResourceClaims field.\nfunc (b *PodSchedulingContextStatusApplyConfiguration) WithResourceClaims(values ...*ResourceClaimSchedulingStatusApplyConfiguration) *PodSchedulingContextStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithResourceClaims\")\n\t\t}\n\t\tb.ResourceClaims = append(b.ResourceClaims, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100024429,"name":"ResourceClaim","signature":"func ResourceClaim(name, namespace string) *ResourceClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaim.go","code":"// ResourceClaim constructs an declarative configuration of the ResourceClaim type for use with\n// apply.\nfunc ResourceClaim(name, namespace string) *ResourceClaimApplyConfiguration {\n\tb := \u0026ResourceClaimApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"ResourceClaim\")\n\tb.WithAPIVersion(\"resource.k8s.io/v1alpha2\")\n\treturn b\n}","line":{"from":39,"to":48}} {"id":100024430,"name":"ExtractResourceClaim","signature":"func ExtractResourceClaim(resourceClaim *resourcev1alpha2.ResourceClaim, fieldManager string) (*ResourceClaimApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaim.go","code":"// ExtractResourceClaim extracts the applied configuration owned by fieldManager from\n// resourceClaim. If no managedFields are found in resourceClaim for fieldManager, a\n// ResourceClaimApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// resourceClaim must be a unmodified ResourceClaim API object that was retrieved from the Kubernetes API.\n// ExtractResourceClaim provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractResourceClaim(resourceClaim *resourcev1alpha2.ResourceClaim, fieldManager string) (*ResourceClaimApplyConfiguration, error) {\n\treturn extractResourceClaim(resourceClaim, fieldManager, \"\")\n}","line":{"from":50,"to":63}} {"id":100024431,"name":"ExtractResourceClaimStatus","signature":"func ExtractResourceClaimStatus(resourceClaim *resourcev1alpha2.ResourceClaim, fieldManager string) (*ResourceClaimApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaim.go","code":"// ExtractResourceClaimStatus is the same as ExtractResourceClaim except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractResourceClaimStatus(resourceClaim *resourcev1alpha2.ResourceClaim, fieldManager string) (*ResourceClaimApplyConfiguration, error) {\n\treturn extractResourceClaim(resourceClaim, fieldManager, \"status\")\n}","line":{"from":65,"to":70}} {"id":100024432,"name":"extractResourceClaim","signature":"func extractResourceClaim(resourceClaim *resourcev1alpha2.ResourceClaim, fieldManager string, subresource string) (*ResourceClaimApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaim.go","code":"func extractResourceClaim(resourceClaim *resourcev1alpha2.ResourceClaim, fieldManager string, subresource string) (*ResourceClaimApplyConfiguration, error) {\n\tb := \u0026ResourceClaimApplyConfiguration{}\n\terr := managedfields.ExtractInto(resourceClaim, internal.Parser().Type(\"io.k8s.api.resource.v1alpha2.ResourceClaim\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(resourceClaim.Name)\n\tb.WithNamespace(resourceClaim.Namespace)\n\n\tb.WithKind(\"ResourceClaim\")\n\tb.WithAPIVersion(\"resource.k8s.io/v1alpha2\")\n\treturn b, nil\n}","line":{"from":72,"to":84}} {"id":100024433,"name":"WithKind","signature":"func (b *ResourceClaimApplyConfiguration) WithKind(value string) *ResourceClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaim.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ResourceClaimApplyConfiguration) WithKind(value string) *ResourceClaimApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100024434,"name":"WithAPIVersion","signature":"func (b *ResourceClaimApplyConfiguration) WithAPIVersion(value string) *ResourceClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaim.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ResourceClaimApplyConfiguration) WithAPIVersion(value string) *ResourceClaimApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100024435,"name":"WithName","signature":"func (b *ResourceClaimApplyConfiguration) WithName(value string) *ResourceClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaim.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ResourceClaimApplyConfiguration) WithName(value string) *ResourceClaimApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100024436,"name":"WithGenerateName","signature":"func (b *ResourceClaimApplyConfiguration) WithGenerateName(value string) *ResourceClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaim.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ResourceClaimApplyConfiguration) WithGenerateName(value string) *ResourceClaimApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100024437,"name":"WithNamespace","signature":"func (b *ResourceClaimApplyConfiguration) WithNamespace(value string) *ResourceClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaim.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ResourceClaimApplyConfiguration) WithNamespace(value string) *ResourceClaimApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100024438,"name":"WithUID","signature":"func (b *ResourceClaimApplyConfiguration) WithUID(value types.UID) *ResourceClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaim.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ResourceClaimApplyConfiguration) WithUID(value types.UID) *ResourceClaimApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100024439,"name":"WithResourceVersion","signature":"func (b *ResourceClaimApplyConfiguration) WithResourceVersion(value string) *ResourceClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaim.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ResourceClaimApplyConfiguration) WithResourceVersion(value string) *ResourceClaimApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100024440,"name":"WithGeneration","signature":"func (b *ResourceClaimApplyConfiguration) WithGeneration(value int64) *ResourceClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaim.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ResourceClaimApplyConfiguration) WithGeneration(value int64) *ResourceClaimApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100024441,"name":"WithCreationTimestamp","signature":"func (b *ResourceClaimApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ResourceClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaim.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ResourceClaimApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ResourceClaimApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100024442,"name":"WithDeletionTimestamp","signature":"func (b *ResourceClaimApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ResourceClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaim.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ResourceClaimApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ResourceClaimApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100024443,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ResourceClaimApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ResourceClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaim.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ResourceClaimApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ResourceClaimApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100024444,"name":"WithLabels","signature":"func (b *ResourceClaimApplyConfiguration) WithLabels(entries map[string]string) *ResourceClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaim.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ResourceClaimApplyConfiguration) WithLabels(entries map[string]string) *ResourceClaimApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100024445,"name":"WithAnnotations","signature":"func (b *ResourceClaimApplyConfiguration) WithAnnotations(entries map[string]string) *ResourceClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaim.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ResourceClaimApplyConfiguration) WithAnnotations(entries map[string]string) *ResourceClaimApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100024446,"name":"WithOwnerReferences","signature":"func (b *ResourceClaimApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ResourceClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaim.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ResourceClaimApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ResourceClaimApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100024447,"name":"WithFinalizers","signature":"func (b *ResourceClaimApplyConfiguration) WithFinalizers(values ...string) *ResourceClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaim.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ResourceClaimApplyConfiguration) WithFinalizers(values ...string) *ResourceClaimApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100024448,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ResourceClaimApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaim.go","code":"func (b *ResourceClaimApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100024449,"name":"WithSpec","signature":"func (b *ResourceClaimApplyConfiguration) WithSpec(value *ResourceClaimSpecApplyConfiguration) *ResourceClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaim.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *ResourceClaimApplyConfiguration) WithSpec(value *ResourceClaimSpecApplyConfiguration) *ResourceClaimApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100024450,"name":"WithStatus","signature":"func (b *ResourceClaimApplyConfiguration) WithStatus(value *ResourceClaimStatusApplyConfiguration) *ResourceClaimApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaim.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *ResourceClaimApplyConfiguration) WithStatus(value *ResourceClaimStatusApplyConfiguration) *ResourceClaimApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100024451,"name":"ResourceClaimConsumerReference","signature":"func ResourceClaimConsumerReference() *ResourceClaimConsumerReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimconsumerreference.go","code":"// ResourceClaimConsumerReferenceApplyConfiguration constructs an declarative configuration of the ResourceClaimConsumerReference type for use with\n// apply.\nfunc ResourceClaimConsumerReference() *ResourceClaimConsumerReferenceApplyConfiguration {\n\treturn \u0026ResourceClaimConsumerReferenceApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100024452,"name":"WithAPIGroup","signature":"func (b *ResourceClaimConsumerReferenceApplyConfiguration) WithAPIGroup(value string) *ResourceClaimConsumerReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimconsumerreference.go","code":"// WithAPIGroup sets the APIGroup field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIGroup field is set to the value of the last call.\nfunc (b *ResourceClaimConsumerReferenceApplyConfiguration) WithAPIGroup(value string) *ResourceClaimConsumerReferenceApplyConfiguration {\n\tb.APIGroup = \u0026value\n\treturn b\n}","line":{"from":40,"to":46}} {"id":100024453,"name":"WithResource","signature":"func (b *ResourceClaimConsumerReferenceApplyConfiguration) WithResource(value string) *ResourceClaimConsumerReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimconsumerreference.go","code":"// WithResource sets the Resource field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Resource field is set to the value of the last call.\nfunc (b *ResourceClaimConsumerReferenceApplyConfiguration) WithResource(value string) *ResourceClaimConsumerReferenceApplyConfiguration {\n\tb.Resource = \u0026value\n\treturn b\n}","line":{"from":48,"to":54}} {"id":100024454,"name":"WithName","signature":"func (b *ResourceClaimConsumerReferenceApplyConfiguration) WithName(value string) *ResourceClaimConsumerReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimconsumerreference.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ResourceClaimConsumerReferenceApplyConfiguration) WithName(value string) *ResourceClaimConsumerReferenceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":56,"to":62}} {"id":100024455,"name":"WithUID","signature":"func (b *ResourceClaimConsumerReferenceApplyConfiguration) WithUID(value types.UID) *ResourceClaimConsumerReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimconsumerreference.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ResourceClaimConsumerReferenceApplyConfiguration) WithUID(value types.UID) *ResourceClaimConsumerReferenceApplyConfiguration {\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":64,"to":70}} {"id":100024456,"name":"ResourceClaimParametersReference","signature":"func ResourceClaimParametersReference() *ResourceClaimParametersReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimparametersreference.go","code":"// ResourceClaimParametersReferenceApplyConfiguration constructs an declarative configuration of the ResourceClaimParametersReference type for use with\n// apply.\nfunc ResourceClaimParametersReference() *ResourceClaimParametersReferenceApplyConfiguration {\n\treturn \u0026ResourceClaimParametersReferenceApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100024457,"name":"WithAPIGroup","signature":"func (b *ResourceClaimParametersReferenceApplyConfiguration) WithAPIGroup(value string) *ResourceClaimParametersReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimparametersreference.go","code":"// WithAPIGroup sets the APIGroup field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIGroup field is set to the value of the last call.\nfunc (b *ResourceClaimParametersReferenceApplyConfiguration) WithAPIGroup(value string) *ResourceClaimParametersReferenceApplyConfiguration {\n\tb.APIGroup = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100024458,"name":"WithKind","signature":"func (b *ResourceClaimParametersReferenceApplyConfiguration) WithKind(value string) *ResourceClaimParametersReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimparametersreference.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ResourceClaimParametersReferenceApplyConfiguration) WithKind(value string) *ResourceClaimParametersReferenceApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100024459,"name":"WithName","signature":"func (b *ResourceClaimParametersReferenceApplyConfiguration) WithName(value string) *ResourceClaimParametersReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimparametersreference.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ResourceClaimParametersReferenceApplyConfiguration) WithName(value string) *ResourceClaimParametersReferenceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100024460,"name":"ResourceClaimSchedulingStatus","signature":"func ResourceClaimSchedulingStatus() *ResourceClaimSchedulingStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimschedulingstatus.go","code":"// ResourceClaimSchedulingStatusApplyConfiguration constructs an declarative configuration of the ResourceClaimSchedulingStatus type for use with\n// apply.\nfunc ResourceClaimSchedulingStatus() *ResourceClaimSchedulingStatusApplyConfiguration {\n\treturn \u0026ResourceClaimSchedulingStatusApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100024461,"name":"WithName","signature":"func (b *ResourceClaimSchedulingStatusApplyConfiguration) WithName(value string) *ResourceClaimSchedulingStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimschedulingstatus.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ResourceClaimSchedulingStatusApplyConfiguration) WithName(value string) *ResourceClaimSchedulingStatusApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100024462,"name":"WithUnsuitableNodes","signature":"func (b *ResourceClaimSchedulingStatusApplyConfiguration) WithUnsuitableNodes(values ...string) *ResourceClaimSchedulingStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimschedulingstatus.go","code":"// WithUnsuitableNodes adds the given value to the UnsuitableNodes field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the UnsuitableNodes field.\nfunc (b *ResourceClaimSchedulingStatusApplyConfiguration) WithUnsuitableNodes(values ...string) *ResourceClaimSchedulingStatusApplyConfiguration {\n\tfor i := range values {\n\t\tb.UnsuitableNodes = append(b.UnsuitableNodes, values[i])\n\t}\n\treturn b\n}","line":{"from":42,"to":50}} {"id":100024463,"name":"ResourceClaimSpec","signature":"func ResourceClaimSpec() *ResourceClaimSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimspec.go","code":"// ResourceClaimSpecApplyConfiguration constructs an declarative configuration of the ResourceClaimSpec type for use with\n// apply.\nfunc ResourceClaimSpec() *ResourceClaimSpecApplyConfiguration {\n\treturn \u0026ResourceClaimSpecApplyConfiguration{}\n}","line":{"from":33,"to":37}} {"id":100024464,"name":"WithResourceClassName","signature":"func (b *ResourceClaimSpecApplyConfiguration) WithResourceClassName(value string) *ResourceClaimSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimspec.go","code":"// WithResourceClassName sets the ResourceClassName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceClassName field is set to the value of the last call.\nfunc (b *ResourceClaimSpecApplyConfiguration) WithResourceClassName(value string) *ResourceClaimSpecApplyConfiguration {\n\tb.ResourceClassName = \u0026value\n\treturn b\n}","line":{"from":39,"to":45}} {"id":100024465,"name":"WithParametersRef","signature":"func (b *ResourceClaimSpecApplyConfiguration) WithParametersRef(value *ResourceClaimParametersReferenceApplyConfiguration) *ResourceClaimSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimspec.go","code":"// WithParametersRef sets the ParametersRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ParametersRef field is set to the value of the last call.\nfunc (b *ResourceClaimSpecApplyConfiguration) WithParametersRef(value *ResourceClaimParametersReferenceApplyConfiguration) *ResourceClaimSpecApplyConfiguration {\n\tb.ParametersRef = value\n\treturn b\n}","line":{"from":47,"to":53}} {"id":100024466,"name":"WithAllocationMode","signature":"func (b *ResourceClaimSpecApplyConfiguration) WithAllocationMode(value resourcev1alpha2.AllocationMode) *ResourceClaimSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimspec.go","code":"// WithAllocationMode sets the AllocationMode field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AllocationMode field is set to the value of the last call.\nfunc (b *ResourceClaimSpecApplyConfiguration) WithAllocationMode(value resourcev1alpha2.AllocationMode) *ResourceClaimSpecApplyConfiguration {\n\tb.AllocationMode = \u0026value\n\treturn b\n}","line":{"from":55,"to":61}} {"id":100024467,"name":"ResourceClaimStatus","signature":"func ResourceClaimStatus() *ResourceClaimStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimstatus.go","code":"// ResourceClaimStatusApplyConfiguration constructs an declarative configuration of the ResourceClaimStatus type for use with\n// apply.\nfunc ResourceClaimStatus() *ResourceClaimStatusApplyConfiguration {\n\treturn \u0026ResourceClaimStatusApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100024468,"name":"WithDriverName","signature":"func (b *ResourceClaimStatusApplyConfiguration) WithDriverName(value string) *ResourceClaimStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimstatus.go","code":"// WithDriverName sets the DriverName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DriverName field is set to the value of the last call.\nfunc (b *ResourceClaimStatusApplyConfiguration) WithDriverName(value string) *ResourceClaimStatusApplyConfiguration {\n\tb.DriverName = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100024469,"name":"WithAllocation","signature":"func (b *ResourceClaimStatusApplyConfiguration) WithAllocation(value *AllocationResultApplyConfiguration) *ResourceClaimStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimstatus.go","code":"// WithAllocation sets the Allocation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Allocation field is set to the value of the last call.\nfunc (b *ResourceClaimStatusApplyConfiguration) WithAllocation(value *AllocationResultApplyConfiguration) *ResourceClaimStatusApplyConfiguration {\n\tb.Allocation = value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100024470,"name":"WithReservedFor","signature":"func (b *ResourceClaimStatusApplyConfiguration) WithReservedFor(values ...*ResourceClaimConsumerReferenceApplyConfiguration) *ResourceClaimStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimstatus.go","code":"// WithReservedFor adds the given value to the ReservedFor field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the ReservedFor field.\nfunc (b *ResourceClaimStatusApplyConfiguration) WithReservedFor(values ...*ResourceClaimConsumerReferenceApplyConfiguration) *ResourceClaimStatusApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithReservedFor\")\n\t\t}\n\t\tb.ReservedFor = append(b.ReservedFor, *values[i])\n\t}\n\treturn b\n}","line":{"from":52,"to":63}} {"id":100024471,"name":"WithDeallocationRequested","signature":"func (b *ResourceClaimStatusApplyConfiguration) WithDeallocationRequested(value bool) *ResourceClaimStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimstatus.go","code":"// WithDeallocationRequested sets the DeallocationRequested field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeallocationRequested field is set to the value of the last call.\nfunc (b *ResourceClaimStatusApplyConfiguration) WithDeallocationRequested(value bool) *ResourceClaimStatusApplyConfiguration {\n\tb.DeallocationRequested = \u0026value\n\treturn b\n}","line":{"from":65,"to":71}} {"id":100024472,"name":"ResourceClaimTemplate","signature":"func ResourceClaimTemplate(name, namespace string) *ResourceClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplate.go","code":"// ResourceClaimTemplate constructs an declarative configuration of the ResourceClaimTemplate type for use with\n// apply.\nfunc ResourceClaimTemplate(name, namespace string) *ResourceClaimTemplateApplyConfiguration {\n\tb := \u0026ResourceClaimTemplateApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"ResourceClaimTemplate\")\n\tb.WithAPIVersion(\"resource.k8s.io/v1alpha2\")\n\treturn b\n}","line":{"from":38,"to":47}} {"id":100024473,"name":"ExtractResourceClaimTemplate","signature":"func ExtractResourceClaimTemplate(resourceClaimTemplate *resourcev1alpha2.ResourceClaimTemplate, fieldManager string) (*ResourceClaimTemplateApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplate.go","code":"// ExtractResourceClaimTemplate extracts the applied configuration owned by fieldManager from\n// resourceClaimTemplate. If no managedFields are found in resourceClaimTemplate for fieldManager, a\n// ResourceClaimTemplateApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// resourceClaimTemplate must be a unmodified ResourceClaimTemplate API object that was retrieved from the Kubernetes API.\n// ExtractResourceClaimTemplate provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractResourceClaimTemplate(resourceClaimTemplate *resourcev1alpha2.ResourceClaimTemplate, fieldManager string) (*ResourceClaimTemplateApplyConfiguration, error) {\n\treturn extractResourceClaimTemplate(resourceClaimTemplate, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100024474,"name":"ExtractResourceClaimTemplateStatus","signature":"func ExtractResourceClaimTemplateStatus(resourceClaimTemplate *resourcev1alpha2.ResourceClaimTemplate, fieldManager string) (*ResourceClaimTemplateApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplate.go","code":"// ExtractResourceClaimTemplateStatus is the same as ExtractResourceClaimTemplate except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractResourceClaimTemplateStatus(resourceClaimTemplate *resourcev1alpha2.ResourceClaimTemplate, fieldManager string) (*ResourceClaimTemplateApplyConfiguration, error) {\n\treturn extractResourceClaimTemplate(resourceClaimTemplate, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100024475,"name":"extractResourceClaimTemplate","signature":"func extractResourceClaimTemplate(resourceClaimTemplate *resourcev1alpha2.ResourceClaimTemplate, fieldManager string, subresource string) (*ResourceClaimTemplateApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplate.go","code":"func extractResourceClaimTemplate(resourceClaimTemplate *resourcev1alpha2.ResourceClaimTemplate, fieldManager string, subresource string) (*ResourceClaimTemplateApplyConfiguration, error) {\n\tb := \u0026ResourceClaimTemplateApplyConfiguration{}\n\terr := managedfields.ExtractInto(resourceClaimTemplate, internal.Parser().Type(\"io.k8s.api.resource.v1alpha2.ResourceClaimTemplate\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(resourceClaimTemplate.Name)\n\tb.WithNamespace(resourceClaimTemplate.Namespace)\n\n\tb.WithKind(\"ResourceClaimTemplate\")\n\tb.WithAPIVersion(\"resource.k8s.io/v1alpha2\")\n\treturn b, nil\n}","line":{"from":71,"to":83}} {"id":100024476,"name":"WithKind","signature":"func (b *ResourceClaimTemplateApplyConfiguration) WithKind(value string) *ResourceClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplate.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ResourceClaimTemplateApplyConfiguration) WithKind(value string) *ResourceClaimTemplateApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":85,"to":91}} {"id":100024477,"name":"WithAPIVersion","signature":"func (b *ResourceClaimTemplateApplyConfiguration) WithAPIVersion(value string) *ResourceClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplate.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ResourceClaimTemplateApplyConfiguration) WithAPIVersion(value string) *ResourceClaimTemplateApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":93,"to":99}} {"id":100024478,"name":"WithName","signature":"func (b *ResourceClaimTemplateApplyConfiguration) WithName(value string) *ResourceClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplate.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ResourceClaimTemplateApplyConfiguration) WithName(value string) *ResourceClaimTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":101,"to":108}} {"id":100024479,"name":"WithGenerateName","signature":"func (b *ResourceClaimTemplateApplyConfiguration) WithGenerateName(value string) *ResourceClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplate.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ResourceClaimTemplateApplyConfiguration) WithGenerateName(value string) *ResourceClaimTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":110,"to":117}} {"id":100024480,"name":"WithNamespace","signature":"func (b *ResourceClaimTemplateApplyConfiguration) WithNamespace(value string) *ResourceClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplate.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ResourceClaimTemplateApplyConfiguration) WithNamespace(value string) *ResourceClaimTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":119,"to":126}} {"id":100024481,"name":"WithUID","signature":"func (b *ResourceClaimTemplateApplyConfiguration) WithUID(value types.UID) *ResourceClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplate.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ResourceClaimTemplateApplyConfiguration) WithUID(value types.UID) *ResourceClaimTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":128,"to":135}} {"id":100024482,"name":"WithResourceVersion","signature":"func (b *ResourceClaimTemplateApplyConfiguration) WithResourceVersion(value string) *ResourceClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplate.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ResourceClaimTemplateApplyConfiguration) WithResourceVersion(value string) *ResourceClaimTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":137,"to":144}} {"id":100024483,"name":"WithGeneration","signature":"func (b *ResourceClaimTemplateApplyConfiguration) WithGeneration(value int64) *ResourceClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplate.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ResourceClaimTemplateApplyConfiguration) WithGeneration(value int64) *ResourceClaimTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":146,"to":153}} {"id":100024484,"name":"WithCreationTimestamp","signature":"func (b *ResourceClaimTemplateApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ResourceClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplate.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ResourceClaimTemplateApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ResourceClaimTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":155,"to":162}} {"id":100024485,"name":"WithDeletionTimestamp","signature":"func (b *ResourceClaimTemplateApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ResourceClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplate.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ResourceClaimTemplateApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ResourceClaimTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":164,"to":171}} {"id":100024486,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ResourceClaimTemplateApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ResourceClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplate.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ResourceClaimTemplateApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ResourceClaimTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":173,"to":180}} {"id":100024487,"name":"WithLabels","signature":"func (b *ResourceClaimTemplateApplyConfiguration) WithLabels(entries map[string]string) *ResourceClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplate.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ResourceClaimTemplateApplyConfiguration) WithLabels(entries map[string]string) *ResourceClaimTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":182,"to":195}} {"id":100024488,"name":"WithAnnotations","signature":"func (b *ResourceClaimTemplateApplyConfiguration) WithAnnotations(entries map[string]string) *ResourceClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplate.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ResourceClaimTemplateApplyConfiguration) WithAnnotations(entries map[string]string) *ResourceClaimTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":197,"to":210}} {"id":100024489,"name":"WithOwnerReferences","signature":"func (b *ResourceClaimTemplateApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ResourceClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplate.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ResourceClaimTemplateApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ResourceClaimTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":212,"to":224}} {"id":100024490,"name":"WithFinalizers","signature":"func (b *ResourceClaimTemplateApplyConfiguration) WithFinalizers(values ...string) *ResourceClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplate.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ResourceClaimTemplateApplyConfiguration) WithFinalizers(values ...string) *ResourceClaimTemplateApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":226,"to":235}} {"id":100024491,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ResourceClaimTemplateApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplate.go","code":"func (b *ResourceClaimTemplateApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":237,"to":241}} {"id":100024492,"name":"WithSpec","signature":"func (b *ResourceClaimTemplateApplyConfiguration) WithSpec(value *ResourceClaimTemplateSpecApplyConfiguration) *ResourceClaimTemplateApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplate.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *ResourceClaimTemplateApplyConfiguration) WithSpec(value *ResourceClaimTemplateSpecApplyConfiguration) *ResourceClaimTemplateApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":243,"to":249}} {"id":100024493,"name":"ResourceClaimTemplateSpec","signature":"func ResourceClaimTemplateSpec() *ResourceClaimTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplatespec.go","code":"// ResourceClaimTemplateSpecApplyConfiguration constructs an declarative configuration of the ResourceClaimTemplateSpec type for use with\n// apply.\nfunc ResourceClaimTemplateSpec() *ResourceClaimTemplateSpecApplyConfiguration {\n\treturn \u0026ResourceClaimTemplateSpecApplyConfiguration{}\n}","line":{"from":34,"to":38}} {"id":100024494,"name":"WithName","signature":"func (b *ResourceClaimTemplateSpecApplyConfiguration) WithName(value string) *ResourceClaimTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplatespec.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ResourceClaimTemplateSpecApplyConfiguration) WithName(value string) *ResourceClaimTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":40,"to":47}} {"id":100024495,"name":"WithGenerateName","signature":"func (b *ResourceClaimTemplateSpecApplyConfiguration) WithGenerateName(value string) *ResourceClaimTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplatespec.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ResourceClaimTemplateSpecApplyConfiguration) WithGenerateName(value string) *ResourceClaimTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":49,"to":56}} {"id":100024496,"name":"WithNamespace","signature":"func (b *ResourceClaimTemplateSpecApplyConfiguration) WithNamespace(value string) *ResourceClaimTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplatespec.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ResourceClaimTemplateSpecApplyConfiguration) WithNamespace(value string) *ResourceClaimTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":58,"to":65}} {"id":100024497,"name":"WithUID","signature":"func (b *ResourceClaimTemplateSpecApplyConfiguration) WithUID(value types.UID) *ResourceClaimTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplatespec.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ResourceClaimTemplateSpecApplyConfiguration) WithUID(value types.UID) *ResourceClaimTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":67,"to":74}} {"id":100024498,"name":"WithResourceVersion","signature":"func (b *ResourceClaimTemplateSpecApplyConfiguration) WithResourceVersion(value string) *ResourceClaimTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplatespec.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ResourceClaimTemplateSpecApplyConfiguration) WithResourceVersion(value string) *ResourceClaimTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":76,"to":83}} {"id":100024499,"name":"WithGeneration","signature":"func (b *ResourceClaimTemplateSpecApplyConfiguration) WithGeneration(value int64) *ResourceClaimTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplatespec.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ResourceClaimTemplateSpecApplyConfiguration) WithGeneration(value int64) *ResourceClaimTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":85,"to":92}} {"id":100024500,"name":"WithCreationTimestamp","signature":"func (b *ResourceClaimTemplateSpecApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ResourceClaimTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplatespec.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ResourceClaimTemplateSpecApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ResourceClaimTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":94,"to":101}} {"id":100024501,"name":"WithDeletionTimestamp","signature":"func (b *ResourceClaimTemplateSpecApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ResourceClaimTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplatespec.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ResourceClaimTemplateSpecApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ResourceClaimTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":103,"to":110}} {"id":100024502,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ResourceClaimTemplateSpecApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ResourceClaimTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplatespec.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ResourceClaimTemplateSpecApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ResourceClaimTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":112,"to":119}} {"id":100024503,"name":"WithLabels","signature":"func (b *ResourceClaimTemplateSpecApplyConfiguration) WithLabels(entries map[string]string) *ResourceClaimTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplatespec.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ResourceClaimTemplateSpecApplyConfiguration) WithLabels(entries map[string]string) *ResourceClaimTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":121,"to":134}} {"id":100024504,"name":"WithAnnotations","signature":"func (b *ResourceClaimTemplateSpecApplyConfiguration) WithAnnotations(entries map[string]string) *ResourceClaimTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplatespec.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ResourceClaimTemplateSpecApplyConfiguration) WithAnnotations(entries map[string]string) *ResourceClaimTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":136,"to":149}} {"id":100024505,"name":"WithOwnerReferences","signature":"func (b *ResourceClaimTemplateSpecApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ResourceClaimTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplatespec.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ResourceClaimTemplateSpecApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ResourceClaimTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":151,"to":163}} {"id":100024506,"name":"WithFinalizers","signature":"func (b *ResourceClaimTemplateSpecApplyConfiguration) WithFinalizers(values ...string) *ResourceClaimTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplatespec.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ResourceClaimTemplateSpecApplyConfiguration) WithFinalizers(values ...string) *ResourceClaimTemplateSpecApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":165,"to":174}} {"id":100024507,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ResourceClaimTemplateSpecApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplatespec.go","code":"func (b *ResourceClaimTemplateSpecApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":176,"to":180}} {"id":100024508,"name":"WithSpec","signature":"func (b *ResourceClaimTemplateSpecApplyConfiguration) WithSpec(value *ResourceClaimSpecApplyConfiguration) *ResourceClaimTemplateSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclaimtemplatespec.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *ResourceClaimTemplateSpecApplyConfiguration) WithSpec(value *ResourceClaimSpecApplyConfiguration) *ResourceClaimTemplateSpecApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":182,"to":188}} {"id":100024509,"name":"ResourceClass","signature":"func ResourceClass(name string) *ResourceClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclass.go","code":"// ResourceClass constructs an declarative configuration of the ResourceClass type for use with\n// apply.\nfunc ResourceClass(name string) *ResourceClassApplyConfiguration {\n\tb := \u0026ResourceClassApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"ResourceClass\")\n\tb.WithAPIVersion(\"resource.k8s.io/v1alpha2\")\n\treturn b\n}","line":{"from":41,"to":49}} {"id":100024510,"name":"ExtractResourceClass","signature":"func ExtractResourceClass(resourceClass *resourcev1alpha2.ResourceClass, fieldManager string) (*ResourceClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclass.go","code":"// ExtractResourceClass extracts the applied configuration owned by fieldManager from\n// resourceClass. If no managedFields are found in resourceClass for fieldManager, a\n// ResourceClassApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// resourceClass must be a unmodified ResourceClass API object that was retrieved from the Kubernetes API.\n// ExtractResourceClass provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractResourceClass(resourceClass *resourcev1alpha2.ResourceClass, fieldManager string) (*ResourceClassApplyConfiguration, error) {\n\treturn extractResourceClass(resourceClass, fieldManager, \"\")\n}","line":{"from":51,"to":64}} {"id":100024511,"name":"ExtractResourceClassStatus","signature":"func ExtractResourceClassStatus(resourceClass *resourcev1alpha2.ResourceClass, fieldManager string) (*ResourceClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclass.go","code":"// ExtractResourceClassStatus is the same as ExtractResourceClass except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractResourceClassStatus(resourceClass *resourcev1alpha2.ResourceClass, fieldManager string) (*ResourceClassApplyConfiguration, error) {\n\treturn extractResourceClass(resourceClass, fieldManager, \"status\")\n}","line":{"from":66,"to":71}} {"id":100024512,"name":"extractResourceClass","signature":"func extractResourceClass(resourceClass *resourcev1alpha2.ResourceClass, fieldManager string, subresource string) (*ResourceClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclass.go","code":"func extractResourceClass(resourceClass *resourcev1alpha2.ResourceClass, fieldManager string, subresource string) (*ResourceClassApplyConfiguration, error) {\n\tb := \u0026ResourceClassApplyConfiguration{}\n\terr := managedfields.ExtractInto(resourceClass, internal.Parser().Type(\"io.k8s.api.resource.v1alpha2.ResourceClass\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(resourceClass.Name)\n\n\tb.WithKind(\"ResourceClass\")\n\tb.WithAPIVersion(\"resource.k8s.io/v1alpha2\")\n\treturn b, nil\n}","line":{"from":73,"to":84}} {"id":100024513,"name":"WithKind","signature":"func (b *ResourceClassApplyConfiguration) WithKind(value string) *ResourceClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclass.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ResourceClassApplyConfiguration) WithKind(value string) *ResourceClassApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":86,"to":92}} {"id":100024514,"name":"WithAPIVersion","signature":"func (b *ResourceClassApplyConfiguration) WithAPIVersion(value string) *ResourceClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclass.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *ResourceClassApplyConfiguration) WithAPIVersion(value string) *ResourceClassApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":94,"to":100}} {"id":100024515,"name":"WithName","signature":"func (b *ResourceClassApplyConfiguration) WithName(value string) *ResourceClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclass.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ResourceClassApplyConfiguration) WithName(value string) *ResourceClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":102,"to":109}} {"id":100024516,"name":"WithGenerateName","signature":"func (b *ResourceClassApplyConfiguration) WithGenerateName(value string) *ResourceClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclass.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *ResourceClassApplyConfiguration) WithGenerateName(value string) *ResourceClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":111,"to":118}} {"id":100024517,"name":"WithNamespace","signature":"func (b *ResourceClassApplyConfiguration) WithNamespace(value string) *ResourceClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclass.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ResourceClassApplyConfiguration) WithNamespace(value string) *ResourceClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":120,"to":127}} {"id":100024518,"name":"WithUID","signature":"func (b *ResourceClassApplyConfiguration) WithUID(value types.UID) *ResourceClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclass.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *ResourceClassApplyConfiguration) WithUID(value types.UID) *ResourceClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":129,"to":136}} {"id":100024519,"name":"WithResourceVersion","signature":"func (b *ResourceClassApplyConfiguration) WithResourceVersion(value string) *ResourceClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclass.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *ResourceClassApplyConfiguration) WithResourceVersion(value string) *ResourceClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":138,"to":145}} {"id":100024520,"name":"WithGeneration","signature":"func (b *ResourceClassApplyConfiguration) WithGeneration(value int64) *ResourceClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclass.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *ResourceClassApplyConfiguration) WithGeneration(value int64) *ResourceClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":147,"to":154}} {"id":100024521,"name":"WithCreationTimestamp","signature":"func (b *ResourceClassApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ResourceClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclass.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *ResourceClassApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ResourceClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":156,"to":163}} {"id":100024522,"name":"WithDeletionTimestamp","signature":"func (b *ResourceClassApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ResourceClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclass.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *ResourceClassApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ResourceClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":165,"to":172}} {"id":100024523,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *ResourceClassApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ResourceClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclass.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *ResourceClassApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ResourceClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":174,"to":181}} {"id":100024524,"name":"WithLabels","signature":"func (b *ResourceClassApplyConfiguration) WithLabels(entries map[string]string) *ResourceClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclass.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *ResourceClassApplyConfiguration) WithLabels(entries map[string]string) *ResourceClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":183,"to":196}} {"id":100024525,"name":"WithAnnotations","signature":"func (b *ResourceClassApplyConfiguration) WithAnnotations(entries map[string]string) *ResourceClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclass.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *ResourceClassApplyConfiguration) WithAnnotations(entries map[string]string) *ResourceClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":198,"to":211}} {"id":100024526,"name":"WithOwnerReferences","signature":"func (b *ResourceClassApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ResourceClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclass.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *ResourceClassApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ResourceClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":213,"to":225}} {"id":100024527,"name":"WithFinalizers","signature":"func (b *ResourceClassApplyConfiguration) WithFinalizers(values ...string) *ResourceClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclass.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *ResourceClassApplyConfiguration) WithFinalizers(values ...string) *ResourceClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":227,"to":236}} {"id":100024528,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *ResourceClassApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclass.go","code":"func (b *ResourceClassApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":238,"to":242}} {"id":100024529,"name":"WithDriverName","signature":"func (b *ResourceClassApplyConfiguration) WithDriverName(value string) *ResourceClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclass.go","code":"// WithDriverName sets the DriverName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DriverName field is set to the value of the last call.\nfunc (b *ResourceClassApplyConfiguration) WithDriverName(value string) *ResourceClassApplyConfiguration {\n\tb.DriverName = \u0026value\n\treturn b\n}","line":{"from":244,"to":250}} {"id":100024530,"name":"WithParametersRef","signature":"func (b *ResourceClassApplyConfiguration) WithParametersRef(value *ResourceClassParametersReferenceApplyConfiguration) *ResourceClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclass.go","code":"// WithParametersRef sets the ParametersRef field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ParametersRef field is set to the value of the last call.\nfunc (b *ResourceClassApplyConfiguration) WithParametersRef(value *ResourceClassParametersReferenceApplyConfiguration) *ResourceClassApplyConfiguration {\n\tb.ParametersRef = value\n\treturn b\n}","line":{"from":252,"to":258}} {"id":100024531,"name":"WithSuitableNodes","signature":"func (b *ResourceClassApplyConfiguration) WithSuitableNodes(value *corev1.NodeSelectorApplyConfiguration) *ResourceClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclass.go","code":"// WithSuitableNodes sets the SuitableNodes field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SuitableNodes field is set to the value of the last call.\nfunc (b *ResourceClassApplyConfiguration) WithSuitableNodes(value *corev1.NodeSelectorApplyConfiguration) *ResourceClassApplyConfiguration {\n\tb.SuitableNodes = value\n\treturn b\n}","line":{"from":260,"to":266}} {"id":100024532,"name":"ResourceClassParametersReference","signature":"func ResourceClassParametersReference() *ResourceClassParametersReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclassparametersreference.go","code":"// ResourceClassParametersReferenceApplyConfiguration constructs an declarative configuration of the ResourceClassParametersReference type for use with\n// apply.\nfunc ResourceClassParametersReference() *ResourceClassParametersReferenceApplyConfiguration {\n\treturn \u0026ResourceClassParametersReferenceApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100024533,"name":"WithAPIGroup","signature":"func (b *ResourceClassParametersReferenceApplyConfiguration) WithAPIGroup(value string) *ResourceClassParametersReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclassparametersreference.go","code":"// WithAPIGroup sets the APIGroup field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIGroup field is set to the value of the last call.\nfunc (b *ResourceClassParametersReferenceApplyConfiguration) WithAPIGroup(value string) *ResourceClassParametersReferenceApplyConfiguration {\n\tb.APIGroup = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100024534,"name":"WithKind","signature":"func (b *ResourceClassParametersReferenceApplyConfiguration) WithKind(value string) *ResourceClassParametersReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclassparametersreference.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *ResourceClassParametersReferenceApplyConfiguration) WithKind(value string) *ResourceClassParametersReferenceApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100024535,"name":"WithName","signature":"func (b *ResourceClassParametersReferenceApplyConfiguration) WithName(value string) *ResourceClassParametersReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclassparametersreference.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *ResourceClassParametersReferenceApplyConfiguration) WithName(value string) *ResourceClassParametersReferenceApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100024536,"name":"WithNamespace","signature":"func (b *ResourceClassParametersReferenceApplyConfiguration) WithNamespace(value string) *ResourceClassParametersReferenceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourceclassparametersreference.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *ResourceClassParametersReferenceApplyConfiguration) WithNamespace(value string) *ResourceClassParametersReferenceApplyConfiguration {\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":60,"to":66}} {"id":100024537,"name":"ResourceHandle","signature":"func ResourceHandle() *ResourceHandleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourcehandle.go","code":"// ResourceHandleApplyConfiguration constructs an declarative configuration of the ResourceHandle type for use with\n// apply.\nfunc ResourceHandle() *ResourceHandleApplyConfiguration {\n\treturn \u0026ResourceHandleApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100024538,"name":"WithDriverName","signature":"func (b *ResourceHandleApplyConfiguration) WithDriverName(value string) *ResourceHandleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourcehandle.go","code":"// WithDriverName sets the DriverName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DriverName field is set to the value of the last call.\nfunc (b *ResourceHandleApplyConfiguration) WithDriverName(value string) *ResourceHandleApplyConfiguration {\n\tb.DriverName = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100024539,"name":"WithData","signature":"func (b *ResourceHandleApplyConfiguration) WithData(value string) *ResourceHandleApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/resource/v1alpha2/resourcehandle.go","code":"// WithData sets the Data field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Data field is set to the value of the last call.\nfunc (b *ResourceHandleApplyConfiguration) WithData(value string) *ResourceHandleApplyConfiguration {\n\tb.Data = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100024540,"name":"PriorityClass","signature":"func PriorityClass(name string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go","code":"// PriorityClass constructs an declarative configuration of the PriorityClass type for use with\n// apply.\nfunc PriorityClass(name string) *PriorityClassApplyConfiguration {\n\tb := \u0026PriorityClassApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"PriorityClass\")\n\tb.WithAPIVersion(\"scheduling.k8s.io/v1\")\n\treturn b\n}","line":{"from":42,"to":50}} {"id":100024541,"name":"ExtractPriorityClass","signature":"func ExtractPriorityClass(priorityClass *schedulingv1.PriorityClass, fieldManager string) (*PriorityClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go","code":"// ExtractPriorityClass extracts the applied configuration owned by fieldManager from\n// priorityClass. If no managedFields are found in priorityClass for fieldManager, a\n// PriorityClassApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// priorityClass must be a unmodified PriorityClass API object that was retrieved from the Kubernetes API.\n// ExtractPriorityClass provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractPriorityClass(priorityClass *schedulingv1.PriorityClass, fieldManager string) (*PriorityClassApplyConfiguration, error) {\n\treturn extractPriorityClass(priorityClass, fieldManager, \"\")\n}","line":{"from":52,"to":65}} {"id":100024542,"name":"ExtractPriorityClassStatus","signature":"func ExtractPriorityClassStatus(priorityClass *schedulingv1.PriorityClass, fieldManager string) (*PriorityClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go","code":"// ExtractPriorityClassStatus is the same as ExtractPriorityClass except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractPriorityClassStatus(priorityClass *schedulingv1.PriorityClass, fieldManager string) (*PriorityClassApplyConfiguration, error) {\n\treturn extractPriorityClass(priorityClass, fieldManager, \"status\")\n}","line":{"from":67,"to":72}} {"id":100024543,"name":"extractPriorityClass","signature":"func extractPriorityClass(priorityClass *schedulingv1.PriorityClass, fieldManager string, subresource string) (*PriorityClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go","code":"func extractPriorityClass(priorityClass *schedulingv1.PriorityClass, fieldManager string, subresource string) (*PriorityClassApplyConfiguration, error) {\n\tb := \u0026PriorityClassApplyConfiguration{}\n\terr := managedfields.ExtractInto(priorityClass, internal.Parser().Type(\"io.k8s.api.scheduling.v1.PriorityClass\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(priorityClass.Name)\n\n\tb.WithKind(\"PriorityClass\")\n\tb.WithAPIVersion(\"scheduling.k8s.io/v1\")\n\treturn b, nil\n}","line":{"from":74,"to":85}} {"id":100024544,"name":"WithKind","signature":"func (b *PriorityClassApplyConfiguration) WithKind(value string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithKind(value string) *PriorityClassApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":87,"to":93}} {"id":100024545,"name":"WithAPIVersion","signature":"func (b *PriorityClassApplyConfiguration) WithAPIVersion(value string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithAPIVersion(value string) *PriorityClassApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":95,"to":101}} {"id":100024546,"name":"WithName","signature":"func (b *PriorityClassApplyConfiguration) WithName(value string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithName(value string) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":103,"to":110}} {"id":100024547,"name":"WithGenerateName","signature":"func (b *PriorityClassApplyConfiguration) WithGenerateName(value string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithGenerateName(value string) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":112,"to":119}} {"id":100024548,"name":"WithNamespace","signature":"func (b *PriorityClassApplyConfiguration) WithNamespace(value string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithNamespace(value string) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":121,"to":128}} {"id":100024549,"name":"WithUID","signature":"func (b *PriorityClassApplyConfiguration) WithUID(value types.UID) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithUID(value types.UID) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":130,"to":137}} {"id":100024550,"name":"WithResourceVersion","signature":"func (b *PriorityClassApplyConfiguration) WithResourceVersion(value string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithResourceVersion(value string) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":139,"to":146}} {"id":100024551,"name":"WithGeneration","signature":"func (b *PriorityClassApplyConfiguration) WithGeneration(value int64) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithGeneration(value int64) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":148,"to":155}} {"id":100024552,"name":"WithCreationTimestamp","signature":"func (b *PriorityClassApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":157,"to":164}} {"id":100024553,"name":"WithDeletionTimestamp","signature":"func (b *PriorityClassApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":166,"to":173}} {"id":100024554,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *PriorityClassApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":175,"to":182}} {"id":100024555,"name":"WithLabels","signature":"func (b *PriorityClassApplyConfiguration) WithLabels(entries map[string]string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *PriorityClassApplyConfiguration) WithLabels(entries map[string]string) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":184,"to":197}} {"id":100024556,"name":"WithAnnotations","signature":"func (b *PriorityClassApplyConfiguration) WithAnnotations(entries map[string]string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *PriorityClassApplyConfiguration) WithAnnotations(entries map[string]string) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":199,"to":212}} {"id":100024557,"name":"WithOwnerReferences","signature":"func (b *PriorityClassApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *PriorityClassApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":214,"to":226}} {"id":100024558,"name":"WithFinalizers","signature":"func (b *PriorityClassApplyConfiguration) WithFinalizers(values ...string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *PriorityClassApplyConfiguration) WithFinalizers(values ...string) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":228,"to":237}} {"id":100024559,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *PriorityClassApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go","code":"func (b *PriorityClassApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":239,"to":243}} {"id":100024560,"name":"WithValue","signature":"func (b *PriorityClassApplyConfiguration) WithValue(value int32) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go","code":"// WithValue sets the Value field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Value field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithValue(value int32) *PriorityClassApplyConfiguration {\n\tb.Value = \u0026value\n\treturn b\n}","line":{"from":245,"to":251}} {"id":100024561,"name":"WithGlobalDefault","signature":"func (b *PriorityClassApplyConfiguration) WithGlobalDefault(value bool) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go","code":"// WithGlobalDefault sets the GlobalDefault field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GlobalDefault field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithGlobalDefault(value bool) *PriorityClassApplyConfiguration {\n\tb.GlobalDefault = \u0026value\n\treturn b\n}","line":{"from":253,"to":259}} {"id":100024562,"name":"WithDescription","signature":"func (b *PriorityClassApplyConfiguration) WithDescription(value string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go","code":"// WithDescription sets the Description field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Description field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithDescription(value string) *PriorityClassApplyConfiguration {\n\tb.Description = \u0026value\n\treturn b\n}","line":{"from":261,"to":267}} {"id":100024563,"name":"WithPreemptionPolicy","signature":"func (b *PriorityClassApplyConfiguration) WithPreemptionPolicy(value corev1.PreemptionPolicy) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1/priorityclass.go","code":"// WithPreemptionPolicy sets the PreemptionPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PreemptionPolicy field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithPreemptionPolicy(value corev1.PreemptionPolicy) *PriorityClassApplyConfiguration {\n\tb.PreemptionPolicy = \u0026value\n\treturn b\n}","line":{"from":269,"to":275}} {"id":100024564,"name":"PriorityClass","signature":"func PriorityClass(name string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1alpha1/priorityclass.go","code":"// PriorityClass constructs an declarative configuration of the PriorityClass type for use with\n// apply.\nfunc PriorityClass(name string) *PriorityClassApplyConfiguration {\n\tb := \u0026PriorityClassApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"PriorityClass\")\n\tb.WithAPIVersion(\"scheduling.k8s.io/v1alpha1\")\n\treturn b\n}","line":{"from":42,"to":50}} {"id":100024565,"name":"ExtractPriorityClass","signature":"func ExtractPriorityClass(priorityClass *v1alpha1.PriorityClass, fieldManager string) (*PriorityClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1alpha1/priorityclass.go","code":"// ExtractPriorityClass extracts the applied configuration owned by fieldManager from\n// priorityClass. If no managedFields are found in priorityClass for fieldManager, a\n// PriorityClassApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// priorityClass must be a unmodified PriorityClass API object that was retrieved from the Kubernetes API.\n// ExtractPriorityClass provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractPriorityClass(priorityClass *v1alpha1.PriorityClass, fieldManager string) (*PriorityClassApplyConfiguration, error) {\n\treturn extractPriorityClass(priorityClass, fieldManager, \"\")\n}","line":{"from":52,"to":65}} {"id":100024566,"name":"ExtractPriorityClassStatus","signature":"func ExtractPriorityClassStatus(priorityClass *v1alpha1.PriorityClass, fieldManager string) (*PriorityClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1alpha1/priorityclass.go","code":"// ExtractPriorityClassStatus is the same as ExtractPriorityClass except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractPriorityClassStatus(priorityClass *v1alpha1.PriorityClass, fieldManager string) (*PriorityClassApplyConfiguration, error) {\n\treturn extractPriorityClass(priorityClass, fieldManager, \"status\")\n}","line":{"from":67,"to":72}} {"id":100024567,"name":"extractPriorityClass","signature":"func extractPriorityClass(priorityClass *v1alpha1.PriorityClass, fieldManager string, subresource string) (*PriorityClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1alpha1/priorityclass.go","code":"func extractPriorityClass(priorityClass *v1alpha1.PriorityClass, fieldManager string, subresource string) (*PriorityClassApplyConfiguration, error) {\n\tb := \u0026PriorityClassApplyConfiguration{}\n\terr := managedfields.ExtractInto(priorityClass, internal.Parser().Type(\"io.k8s.api.scheduling.v1alpha1.PriorityClass\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(priorityClass.Name)\n\n\tb.WithKind(\"PriorityClass\")\n\tb.WithAPIVersion(\"scheduling.k8s.io/v1alpha1\")\n\treturn b, nil\n}","line":{"from":74,"to":85}} {"id":100024568,"name":"WithKind","signature":"func (b *PriorityClassApplyConfiguration) WithKind(value string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1alpha1/priorityclass.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithKind(value string) *PriorityClassApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":87,"to":93}} {"id":100024569,"name":"WithAPIVersion","signature":"func (b *PriorityClassApplyConfiguration) WithAPIVersion(value string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1alpha1/priorityclass.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithAPIVersion(value string) *PriorityClassApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":95,"to":101}} {"id":100024570,"name":"WithName","signature":"func (b *PriorityClassApplyConfiguration) WithName(value string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1alpha1/priorityclass.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithName(value string) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":103,"to":110}} {"id":100024571,"name":"WithGenerateName","signature":"func (b *PriorityClassApplyConfiguration) WithGenerateName(value string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1alpha1/priorityclass.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithGenerateName(value string) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":112,"to":119}} {"id":100024572,"name":"WithNamespace","signature":"func (b *PriorityClassApplyConfiguration) WithNamespace(value string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1alpha1/priorityclass.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithNamespace(value string) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":121,"to":128}} {"id":100024573,"name":"WithUID","signature":"func (b *PriorityClassApplyConfiguration) WithUID(value types.UID) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1alpha1/priorityclass.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithUID(value types.UID) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":130,"to":137}} {"id":100024574,"name":"WithResourceVersion","signature":"func (b *PriorityClassApplyConfiguration) WithResourceVersion(value string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1alpha1/priorityclass.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithResourceVersion(value string) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":139,"to":146}} {"id":100024575,"name":"WithGeneration","signature":"func (b *PriorityClassApplyConfiguration) WithGeneration(value int64) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1alpha1/priorityclass.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithGeneration(value int64) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":148,"to":155}} {"id":100024576,"name":"WithCreationTimestamp","signature":"func (b *PriorityClassApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1alpha1/priorityclass.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":157,"to":164}} {"id":100024577,"name":"WithDeletionTimestamp","signature":"func (b *PriorityClassApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1alpha1/priorityclass.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":166,"to":173}} {"id":100024578,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *PriorityClassApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1alpha1/priorityclass.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":175,"to":182}} {"id":100024579,"name":"WithLabels","signature":"func (b *PriorityClassApplyConfiguration) WithLabels(entries map[string]string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1alpha1/priorityclass.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *PriorityClassApplyConfiguration) WithLabels(entries map[string]string) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":184,"to":197}} {"id":100024580,"name":"WithAnnotations","signature":"func (b *PriorityClassApplyConfiguration) WithAnnotations(entries map[string]string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1alpha1/priorityclass.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *PriorityClassApplyConfiguration) WithAnnotations(entries map[string]string) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":199,"to":212}} {"id":100024581,"name":"WithOwnerReferences","signature":"func (b *PriorityClassApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1alpha1/priorityclass.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *PriorityClassApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":214,"to":226}} {"id":100024582,"name":"WithFinalizers","signature":"func (b *PriorityClassApplyConfiguration) WithFinalizers(values ...string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1alpha1/priorityclass.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *PriorityClassApplyConfiguration) WithFinalizers(values ...string) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":228,"to":237}} {"id":100024583,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *PriorityClassApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1alpha1/priorityclass.go","code":"func (b *PriorityClassApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":239,"to":243}} {"id":100024584,"name":"WithValue","signature":"func (b *PriorityClassApplyConfiguration) WithValue(value int32) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1alpha1/priorityclass.go","code":"// WithValue sets the Value field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Value field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithValue(value int32) *PriorityClassApplyConfiguration {\n\tb.Value = \u0026value\n\treturn b\n}","line":{"from":245,"to":251}} {"id":100024585,"name":"WithGlobalDefault","signature":"func (b *PriorityClassApplyConfiguration) WithGlobalDefault(value bool) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1alpha1/priorityclass.go","code":"// WithGlobalDefault sets the GlobalDefault field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GlobalDefault field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithGlobalDefault(value bool) *PriorityClassApplyConfiguration {\n\tb.GlobalDefault = \u0026value\n\treturn b\n}","line":{"from":253,"to":259}} {"id":100024586,"name":"WithDescription","signature":"func (b *PriorityClassApplyConfiguration) WithDescription(value string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1alpha1/priorityclass.go","code":"// WithDescription sets the Description field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Description field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithDescription(value string) *PriorityClassApplyConfiguration {\n\tb.Description = \u0026value\n\treturn b\n}","line":{"from":261,"to":267}} {"id":100024587,"name":"WithPreemptionPolicy","signature":"func (b *PriorityClassApplyConfiguration) WithPreemptionPolicy(value corev1.PreemptionPolicy) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1alpha1/priorityclass.go","code":"// WithPreemptionPolicy sets the PreemptionPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PreemptionPolicy field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithPreemptionPolicy(value corev1.PreemptionPolicy) *PriorityClassApplyConfiguration {\n\tb.PreemptionPolicy = \u0026value\n\treturn b\n}","line":{"from":269,"to":275}} {"id":100024588,"name":"PriorityClass","signature":"func PriorityClass(name string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go","code":"// PriorityClass constructs an declarative configuration of the PriorityClass type for use with\n// apply.\nfunc PriorityClass(name string) *PriorityClassApplyConfiguration {\n\tb := \u0026PriorityClassApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"PriorityClass\")\n\tb.WithAPIVersion(\"scheduling.k8s.io/v1beta1\")\n\treturn b\n}","line":{"from":42,"to":50}} {"id":100024589,"name":"ExtractPriorityClass","signature":"func ExtractPriorityClass(priorityClass *v1beta1.PriorityClass, fieldManager string) (*PriorityClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go","code":"// ExtractPriorityClass extracts the applied configuration owned by fieldManager from\n// priorityClass. If no managedFields are found in priorityClass for fieldManager, a\n// PriorityClassApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// priorityClass must be a unmodified PriorityClass API object that was retrieved from the Kubernetes API.\n// ExtractPriorityClass provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractPriorityClass(priorityClass *v1beta1.PriorityClass, fieldManager string) (*PriorityClassApplyConfiguration, error) {\n\treturn extractPriorityClass(priorityClass, fieldManager, \"\")\n}","line":{"from":52,"to":65}} {"id":100024590,"name":"ExtractPriorityClassStatus","signature":"func ExtractPriorityClassStatus(priorityClass *v1beta1.PriorityClass, fieldManager string) (*PriorityClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go","code":"// ExtractPriorityClassStatus is the same as ExtractPriorityClass except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractPriorityClassStatus(priorityClass *v1beta1.PriorityClass, fieldManager string) (*PriorityClassApplyConfiguration, error) {\n\treturn extractPriorityClass(priorityClass, fieldManager, \"status\")\n}","line":{"from":67,"to":72}} {"id":100024591,"name":"extractPriorityClass","signature":"func extractPriorityClass(priorityClass *v1beta1.PriorityClass, fieldManager string, subresource string) (*PriorityClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go","code":"func extractPriorityClass(priorityClass *v1beta1.PriorityClass, fieldManager string, subresource string) (*PriorityClassApplyConfiguration, error) {\n\tb := \u0026PriorityClassApplyConfiguration{}\n\terr := managedfields.ExtractInto(priorityClass, internal.Parser().Type(\"io.k8s.api.scheduling.v1beta1.PriorityClass\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(priorityClass.Name)\n\n\tb.WithKind(\"PriorityClass\")\n\tb.WithAPIVersion(\"scheduling.k8s.io/v1beta1\")\n\treturn b, nil\n}","line":{"from":74,"to":85}} {"id":100024592,"name":"WithKind","signature":"func (b *PriorityClassApplyConfiguration) WithKind(value string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithKind(value string) *PriorityClassApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":87,"to":93}} {"id":100024593,"name":"WithAPIVersion","signature":"func (b *PriorityClassApplyConfiguration) WithAPIVersion(value string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithAPIVersion(value string) *PriorityClassApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":95,"to":101}} {"id":100024594,"name":"WithName","signature":"func (b *PriorityClassApplyConfiguration) WithName(value string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithName(value string) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":103,"to":110}} {"id":100024595,"name":"WithGenerateName","signature":"func (b *PriorityClassApplyConfiguration) WithGenerateName(value string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithGenerateName(value string) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":112,"to":119}} {"id":100024596,"name":"WithNamespace","signature":"func (b *PriorityClassApplyConfiguration) WithNamespace(value string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithNamespace(value string) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":121,"to":128}} {"id":100024597,"name":"WithUID","signature":"func (b *PriorityClassApplyConfiguration) WithUID(value types.UID) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithUID(value types.UID) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":130,"to":137}} {"id":100024598,"name":"WithResourceVersion","signature":"func (b *PriorityClassApplyConfiguration) WithResourceVersion(value string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithResourceVersion(value string) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":139,"to":146}} {"id":100024599,"name":"WithGeneration","signature":"func (b *PriorityClassApplyConfiguration) WithGeneration(value int64) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithGeneration(value int64) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":148,"to":155}} {"id":100024600,"name":"WithCreationTimestamp","signature":"func (b *PriorityClassApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithCreationTimestamp(value metav1.Time) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":157,"to":164}} {"id":100024601,"name":"WithDeletionTimestamp","signature":"func (b *PriorityClassApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":166,"to":173}} {"id":100024602,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *PriorityClassApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":175,"to":182}} {"id":100024603,"name":"WithLabels","signature":"func (b *PriorityClassApplyConfiguration) WithLabels(entries map[string]string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *PriorityClassApplyConfiguration) WithLabels(entries map[string]string) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":184,"to":197}} {"id":100024604,"name":"WithAnnotations","signature":"func (b *PriorityClassApplyConfiguration) WithAnnotations(entries map[string]string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *PriorityClassApplyConfiguration) WithAnnotations(entries map[string]string) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":199,"to":212}} {"id":100024605,"name":"WithOwnerReferences","signature":"func (b *PriorityClassApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *PriorityClassApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":214,"to":226}} {"id":100024606,"name":"WithFinalizers","signature":"func (b *PriorityClassApplyConfiguration) WithFinalizers(values ...string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *PriorityClassApplyConfiguration) WithFinalizers(values ...string) *PriorityClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":228,"to":237}} {"id":100024607,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *PriorityClassApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go","code":"func (b *PriorityClassApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":239,"to":243}} {"id":100024608,"name":"WithValue","signature":"func (b *PriorityClassApplyConfiguration) WithValue(value int32) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go","code":"// WithValue sets the Value field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Value field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithValue(value int32) *PriorityClassApplyConfiguration {\n\tb.Value = \u0026value\n\treturn b\n}","line":{"from":245,"to":251}} {"id":100024609,"name":"WithGlobalDefault","signature":"func (b *PriorityClassApplyConfiguration) WithGlobalDefault(value bool) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go","code":"// WithGlobalDefault sets the GlobalDefault field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GlobalDefault field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithGlobalDefault(value bool) *PriorityClassApplyConfiguration {\n\tb.GlobalDefault = \u0026value\n\treturn b\n}","line":{"from":253,"to":259}} {"id":100024610,"name":"WithDescription","signature":"func (b *PriorityClassApplyConfiguration) WithDescription(value string) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go","code":"// WithDescription sets the Description field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Description field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithDescription(value string) *PriorityClassApplyConfiguration {\n\tb.Description = \u0026value\n\treturn b\n}","line":{"from":261,"to":267}} {"id":100024611,"name":"WithPreemptionPolicy","signature":"func (b *PriorityClassApplyConfiguration) WithPreemptionPolicy(value corev1.PreemptionPolicy) *PriorityClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/scheduling/v1beta1/priorityclass.go","code":"// WithPreemptionPolicy sets the PreemptionPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PreemptionPolicy field is set to the value of the last call.\nfunc (b *PriorityClassApplyConfiguration) WithPreemptionPolicy(value corev1.PreemptionPolicy) *PriorityClassApplyConfiguration {\n\tb.PreemptionPolicy = \u0026value\n\treturn b\n}","line":{"from":269,"to":275}} {"id":100024612,"name":"CSIDriver","signature":"func CSIDriver(name string) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriver.go","code":"// CSIDriver constructs an declarative configuration of the CSIDriver type for use with\n// apply.\nfunc CSIDriver(name string) *CSIDriverApplyConfiguration {\n\tb := \u0026CSIDriverApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"CSIDriver\")\n\tb.WithAPIVersion(\"storage.k8s.io/v1\")\n\treturn b\n}","line":{"from":38,"to":46}} {"id":100024613,"name":"ExtractCSIDriver","signature":"func ExtractCSIDriver(cSIDriver *apistoragev1.CSIDriver, fieldManager string) (*CSIDriverApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriver.go","code":"// ExtractCSIDriver extracts the applied configuration owned by fieldManager from\n// cSIDriver. If no managedFields are found in cSIDriver for fieldManager, a\n// CSIDriverApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// cSIDriver must be a unmodified CSIDriver API object that was retrieved from the Kubernetes API.\n// ExtractCSIDriver provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractCSIDriver(cSIDriver *apistoragev1.CSIDriver, fieldManager string) (*CSIDriverApplyConfiguration, error) {\n\treturn extractCSIDriver(cSIDriver, fieldManager, \"\")\n}","line":{"from":48,"to":61}} {"id":100024614,"name":"ExtractCSIDriverStatus","signature":"func ExtractCSIDriverStatus(cSIDriver *apistoragev1.CSIDriver, fieldManager string) (*CSIDriverApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriver.go","code":"// ExtractCSIDriverStatus is the same as ExtractCSIDriver except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractCSIDriverStatus(cSIDriver *apistoragev1.CSIDriver, fieldManager string) (*CSIDriverApplyConfiguration, error) {\n\treturn extractCSIDriver(cSIDriver, fieldManager, \"status\")\n}","line":{"from":63,"to":68}} {"id":100024615,"name":"extractCSIDriver","signature":"func extractCSIDriver(cSIDriver *apistoragev1.CSIDriver, fieldManager string, subresource string) (*CSIDriverApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriver.go","code":"func extractCSIDriver(cSIDriver *apistoragev1.CSIDriver, fieldManager string, subresource string) (*CSIDriverApplyConfiguration, error) {\n\tb := \u0026CSIDriverApplyConfiguration{}\n\terr := managedfields.ExtractInto(cSIDriver, internal.Parser().Type(\"io.k8s.api.storage.v1.CSIDriver\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(cSIDriver.Name)\n\n\tb.WithKind(\"CSIDriver\")\n\tb.WithAPIVersion(\"storage.k8s.io/v1\")\n\treturn b, nil\n}","line":{"from":70,"to":81}} {"id":100024616,"name":"WithKind","signature":"func (b *CSIDriverApplyConfiguration) WithKind(value string) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriver.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *CSIDriverApplyConfiguration) WithKind(value string) *CSIDriverApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100024617,"name":"WithAPIVersion","signature":"func (b *CSIDriverApplyConfiguration) WithAPIVersion(value string) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriver.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *CSIDriverApplyConfiguration) WithAPIVersion(value string) *CSIDriverApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":91,"to":97}} {"id":100024618,"name":"WithName","signature":"func (b *CSIDriverApplyConfiguration) WithName(value string) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriver.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *CSIDriverApplyConfiguration) WithName(value string) *CSIDriverApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":99,"to":106}} {"id":100024619,"name":"WithGenerateName","signature":"func (b *CSIDriverApplyConfiguration) WithGenerateName(value string) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriver.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *CSIDriverApplyConfiguration) WithGenerateName(value string) *CSIDriverApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":108,"to":115}} {"id":100024620,"name":"WithNamespace","signature":"func (b *CSIDriverApplyConfiguration) WithNamespace(value string) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriver.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *CSIDriverApplyConfiguration) WithNamespace(value string) *CSIDriverApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":117,"to":124}} {"id":100024621,"name":"WithUID","signature":"func (b *CSIDriverApplyConfiguration) WithUID(value types.UID) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriver.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *CSIDriverApplyConfiguration) WithUID(value types.UID) *CSIDriverApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":126,"to":133}} {"id":100024622,"name":"WithResourceVersion","signature":"func (b *CSIDriverApplyConfiguration) WithResourceVersion(value string) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriver.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *CSIDriverApplyConfiguration) WithResourceVersion(value string) *CSIDriverApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":135,"to":142}} {"id":100024623,"name":"WithGeneration","signature":"func (b *CSIDriverApplyConfiguration) WithGeneration(value int64) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriver.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *CSIDriverApplyConfiguration) WithGeneration(value int64) *CSIDriverApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":144,"to":151}} {"id":100024624,"name":"WithCreationTimestamp","signature":"func (b *CSIDriverApplyConfiguration) WithCreationTimestamp(value metav1.Time) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriver.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *CSIDriverApplyConfiguration) WithCreationTimestamp(value metav1.Time) *CSIDriverApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":153,"to":160}} {"id":100024625,"name":"WithDeletionTimestamp","signature":"func (b *CSIDriverApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriver.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *CSIDriverApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *CSIDriverApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":162,"to":169}} {"id":100024626,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *CSIDriverApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriver.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *CSIDriverApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *CSIDriverApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":171,"to":178}} {"id":100024627,"name":"WithLabels","signature":"func (b *CSIDriverApplyConfiguration) WithLabels(entries map[string]string) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriver.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *CSIDriverApplyConfiguration) WithLabels(entries map[string]string) *CSIDriverApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":180,"to":193}} {"id":100024628,"name":"WithAnnotations","signature":"func (b *CSIDriverApplyConfiguration) WithAnnotations(entries map[string]string) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriver.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *CSIDriverApplyConfiguration) WithAnnotations(entries map[string]string) *CSIDriverApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":195,"to":208}} {"id":100024629,"name":"WithOwnerReferences","signature":"func (b *CSIDriverApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriver.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *CSIDriverApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *CSIDriverApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":210,"to":222}} {"id":100024630,"name":"WithFinalizers","signature":"func (b *CSIDriverApplyConfiguration) WithFinalizers(values ...string) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriver.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *CSIDriverApplyConfiguration) WithFinalizers(values ...string) *CSIDriverApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":224,"to":233}} {"id":100024631,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *CSIDriverApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriver.go","code":"func (b *CSIDriverApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":235,"to":239}} {"id":100024632,"name":"WithSpec","signature":"func (b *CSIDriverApplyConfiguration) WithSpec(value *CSIDriverSpecApplyConfiguration) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriver.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *CSIDriverApplyConfiguration) WithSpec(value *CSIDriverSpecApplyConfiguration) *CSIDriverApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":241,"to":247}} {"id":100024633,"name":"CSIDriverSpec","signature":"func CSIDriverSpec() *CSIDriverSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriverspec.go","code":"// CSIDriverSpecApplyConfiguration constructs an declarative configuration of the CSIDriverSpec type for use with\n// apply.\nfunc CSIDriverSpec() *CSIDriverSpecApplyConfiguration {\n\treturn \u0026CSIDriverSpecApplyConfiguration{}\n}","line":{"from":38,"to":42}} {"id":100024634,"name":"WithAttachRequired","signature":"func (b *CSIDriverSpecApplyConfiguration) WithAttachRequired(value bool) *CSIDriverSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriverspec.go","code":"// WithAttachRequired sets the AttachRequired field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AttachRequired field is set to the value of the last call.\nfunc (b *CSIDriverSpecApplyConfiguration) WithAttachRequired(value bool) *CSIDriverSpecApplyConfiguration {\n\tb.AttachRequired = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100024635,"name":"WithPodInfoOnMount","signature":"func (b *CSIDriverSpecApplyConfiguration) WithPodInfoOnMount(value bool) *CSIDriverSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriverspec.go","code":"// WithPodInfoOnMount sets the PodInfoOnMount field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PodInfoOnMount field is set to the value of the last call.\nfunc (b *CSIDriverSpecApplyConfiguration) WithPodInfoOnMount(value bool) *CSIDriverSpecApplyConfiguration {\n\tb.PodInfoOnMount = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100024636,"name":"WithVolumeLifecycleModes","signature":"func (b *CSIDriverSpecApplyConfiguration) WithVolumeLifecycleModes(values ...v1.VolumeLifecycleMode) *CSIDriverSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriverspec.go","code":"// WithVolumeLifecycleModes adds the given value to the VolumeLifecycleModes field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the VolumeLifecycleModes field.\nfunc (b *CSIDriverSpecApplyConfiguration) WithVolumeLifecycleModes(values ...v1.VolumeLifecycleMode) *CSIDriverSpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.VolumeLifecycleModes = append(b.VolumeLifecycleModes, values[i])\n\t}\n\treturn b\n}","line":{"from":60,"to":68}} {"id":100024637,"name":"WithStorageCapacity","signature":"func (b *CSIDriverSpecApplyConfiguration) WithStorageCapacity(value bool) *CSIDriverSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriverspec.go","code":"// WithStorageCapacity sets the StorageCapacity field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StorageCapacity field is set to the value of the last call.\nfunc (b *CSIDriverSpecApplyConfiguration) WithStorageCapacity(value bool) *CSIDriverSpecApplyConfiguration {\n\tb.StorageCapacity = \u0026value\n\treturn b\n}","line":{"from":70,"to":76}} {"id":100024638,"name":"WithFSGroupPolicy","signature":"func (b *CSIDriverSpecApplyConfiguration) WithFSGroupPolicy(value v1.FSGroupPolicy) *CSIDriverSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriverspec.go","code":"// WithFSGroupPolicy sets the FSGroupPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSGroupPolicy field is set to the value of the last call.\nfunc (b *CSIDriverSpecApplyConfiguration) WithFSGroupPolicy(value v1.FSGroupPolicy) *CSIDriverSpecApplyConfiguration {\n\tb.FSGroupPolicy = \u0026value\n\treturn b\n}","line":{"from":78,"to":84}} {"id":100024639,"name":"WithTokenRequests","signature":"func (b *CSIDriverSpecApplyConfiguration) WithTokenRequests(values ...*TokenRequestApplyConfiguration) *CSIDriverSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriverspec.go","code":"// WithTokenRequests adds the given value to the TokenRequests field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the TokenRequests field.\nfunc (b *CSIDriverSpecApplyConfiguration) WithTokenRequests(values ...*TokenRequestApplyConfiguration) *CSIDriverSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithTokenRequests\")\n\t\t}\n\t\tb.TokenRequests = append(b.TokenRequests, *values[i])\n\t}\n\treturn b\n}","line":{"from":86,"to":97}} {"id":100024640,"name":"WithRequiresRepublish","signature":"func (b *CSIDriverSpecApplyConfiguration) WithRequiresRepublish(value bool) *CSIDriverSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriverspec.go","code":"// WithRequiresRepublish sets the RequiresRepublish field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RequiresRepublish field is set to the value of the last call.\nfunc (b *CSIDriverSpecApplyConfiguration) WithRequiresRepublish(value bool) *CSIDriverSpecApplyConfiguration {\n\tb.RequiresRepublish = \u0026value\n\treturn b\n}","line":{"from":99,"to":105}} {"id":100024641,"name":"WithSELinuxMount","signature":"func (b *CSIDriverSpecApplyConfiguration) WithSELinuxMount(value bool) *CSIDriverSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csidriverspec.go","code":"// WithSELinuxMount sets the SELinuxMount field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SELinuxMount field is set to the value of the last call.\nfunc (b *CSIDriverSpecApplyConfiguration) WithSELinuxMount(value bool) *CSIDriverSpecApplyConfiguration {\n\tb.SELinuxMount = \u0026value\n\treturn b\n}","line":{"from":107,"to":113}} {"id":100024642,"name":"CSINode","signature":"func CSINode(name string) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinode.go","code":"// CSINode constructs an declarative configuration of the CSINode type for use with\n// apply.\nfunc CSINode(name string) *CSINodeApplyConfiguration {\n\tb := \u0026CSINodeApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"CSINode\")\n\tb.WithAPIVersion(\"storage.k8s.io/v1\")\n\treturn b\n}","line":{"from":38,"to":46}} {"id":100024643,"name":"ExtractCSINode","signature":"func ExtractCSINode(cSINode *apistoragev1.CSINode, fieldManager string) (*CSINodeApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinode.go","code":"// ExtractCSINode extracts the applied configuration owned by fieldManager from\n// cSINode. If no managedFields are found in cSINode for fieldManager, a\n// CSINodeApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// cSINode must be a unmodified CSINode API object that was retrieved from the Kubernetes API.\n// ExtractCSINode provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractCSINode(cSINode *apistoragev1.CSINode, fieldManager string) (*CSINodeApplyConfiguration, error) {\n\treturn extractCSINode(cSINode, fieldManager, \"\")\n}","line":{"from":48,"to":61}} {"id":100024644,"name":"ExtractCSINodeStatus","signature":"func ExtractCSINodeStatus(cSINode *apistoragev1.CSINode, fieldManager string) (*CSINodeApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinode.go","code":"// ExtractCSINodeStatus is the same as ExtractCSINode except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractCSINodeStatus(cSINode *apistoragev1.CSINode, fieldManager string) (*CSINodeApplyConfiguration, error) {\n\treturn extractCSINode(cSINode, fieldManager, \"status\")\n}","line":{"from":63,"to":68}} {"id":100024645,"name":"extractCSINode","signature":"func extractCSINode(cSINode *apistoragev1.CSINode, fieldManager string, subresource string) (*CSINodeApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinode.go","code":"func extractCSINode(cSINode *apistoragev1.CSINode, fieldManager string, subresource string) (*CSINodeApplyConfiguration, error) {\n\tb := \u0026CSINodeApplyConfiguration{}\n\terr := managedfields.ExtractInto(cSINode, internal.Parser().Type(\"io.k8s.api.storage.v1.CSINode\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(cSINode.Name)\n\n\tb.WithKind(\"CSINode\")\n\tb.WithAPIVersion(\"storage.k8s.io/v1\")\n\treturn b, nil\n}","line":{"from":70,"to":81}} {"id":100024646,"name":"WithKind","signature":"func (b *CSINodeApplyConfiguration) WithKind(value string) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinode.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *CSINodeApplyConfiguration) WithKind(value string) *CSINodeApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100024647,"name":"WithAPIVersion","signature":"func (b *CSINodeApplyConfiguration) WithAPIVersion(value string) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinode.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *CSINodeApplyConfiguration) WithAPIVersion(value string) *CSINodeApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":91,"to":97}} {"id":100024648,"name":"WithName","signature":"func (b *CSINodeApplyConfiguration) WithName(value string) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinode.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *CSINodeApplyConfiguration) WithName(value string) *CSINodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":99,"to":106}} {"id":100024649,"name":"WithGenerateName","signature":"func (b *CSINodeApplyConfiguration) WithGenerateName(value string) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinode.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *CSINodeApplyConfiguration) WithGenerateName(value string) *CSINodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":108,"to":115}} {"id":100024650,"name":"WithNamespace","signature":"func (b *CSINodeApplyConfiguration) WithNamespace(value string) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinode.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *CSINodeApplyConfiguration) WithNamespace(value string) *CSINodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":117,"to":124}} {"id":100024651,"name":"WithUID","signature":"func (b *CSINodeApplyConfiguration) WithUID(value types.UID) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinode.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *CSINodeApplyConfiguration) WithUID(value types.UID) *CSINodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":126,"to":133}} {"id":100024652,"name":"WithResourceVersion","signature":"func (b *CSINodeApplyConfiguration) WithResourceVersion(value string) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinode.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *CSINodeApplyConfiguration) WithResourceVersion(value string) *CSINodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":135,"to":142}} {"id":100024653,"name":"WithGeneration","signature":"func (b *CSINodeApplyConfiguration) WithGeneration(value int64) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinode.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *CSINodeApplyConfiguration) WithGeneration(value int64) *CSINodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":144,"to":151}} {"id":100024654,"name":"WithCreationTimestamp","signature":"func (b *CSINodeApplyConfiguration) WithCreationTimestamp(value metav1.Time) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinode.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *CSINodeApplyConfiguration) WithCreationTimestamp(value metav1.Time) *CSINodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":153,"to":160}} {"id":100024655,"name":"WithDeletionTimestamp","signature":"func (b *CSINodeApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinode.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *CSINodeApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *CSINodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":162,"to":169}} {"id":100024656,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *CSINodeApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinode.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *CSINodeApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *CSINodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":171,"to":178}} {"id":100024657,"name":"WithLabels","signature":"func (b *CSINodeApplyConfiguration) WithLabels(entries map[string]string) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinode.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *CSINodeApplyConfiguration) WithLabels(entries map[string]string) *CSINodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":180,"to":193}} {"id":100024658,"name":"WithAnnotations","signature":"func (b *CSINodeApplyConfiguration) WithAnnotations(entries map[string]string) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinode.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *CSINodeApplyConfiguration) WithAnnotations(entries map[string]string) *CSINodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":195,"to":208}} {"id":100024659,"name":"WithOwnerReferences","signature":"func (b *CSINodeApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinode.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *CSINodeApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *CSINodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":210,"to":222}} {"id":100024660,"name":"WithFinalizers","signature":"func (b *CSINodeApplyConfiguration) WithFinalizers(values ...string) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinode.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *CSINodeApplyConfiguration) WithFinalizers(values ...string) *CSINodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":224,"to":233}} {"id":100024661,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *CSINodeApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinode.go","code":"func (b *CSINodeApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":235,"to":239}} {"id":100024662,"name":"WithSpec","signature":"func (b *CSINodeApplyConfiguration) WithSpec(value *CSINodeSpecApplyConfiguration) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinode.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *CSINodeApplyConfiguration) WithSpec(value *CSINodeSpecApplyConfiguration) *CSINodeApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":241,"to":247}} {"id":100024663,"name":"CSINodeDriver","signature":"func CSINodeDriver() *CSINodeDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinodedriver.go","code":"// CSINodeDriverApplyConfiguration constructs an declarative configuration of the CSINodeDriver type for use with\n// apply.\nfunc CSINodeDriver() *CSINodeDriverApplyConfiguration {\n\treturn \u0026CSINodeDriverApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100024664,"name":"WithName","signature":"func (b *CSINodeDriverApplyConfiguration) WithName(value string) *CSINodeDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinodedriver.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *CSINodeDriverApplyConfiguration) WithName(value string) *CSINodeDriverApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100024665,"name":"WithNodeID","signature":"func (b *CSINodeDriverApplyConfiguration) WithNodeID(value string) *CSINodeDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinodedriver.go","code":"// WithNodeID sets the NodeID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NodeID field is set to the value of the last call.\nfunc (b *CSINodeDriverApplyConfiguration) WithNodeID(value string) *CSINodeDriverApplyConfiguration {\n\tb.NodeID = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100024666,"name":"WithTopologyKeys","signature":"func (b *CSINodeDriverApplyConfiguration) WithTopologyKeys(values ...string) *CSINodeDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinodedriver.go","code":"// WithTopologyKeys adds the given value to the TopologyKeys field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the TopologyKeys field.\nfunc (b *CSINodeDriverApplyConfiguration) WithTopologyKeys(values ...string) *CSINodeDriverApplyConfiguration {\n\tfor i := range values {\n\t\tb.TopologyKeys = append(b.TopologyKeys, values[i])\n\t}\n\treturn b\n}","line":{"from":52,"to":60}} {"id":100024667,"name":"WithAllocatable","signature":"func (b *CSINodeDriverApplyConfiguration) WithAllocatable(value *VolumeNodeResourcesApplyConfiguration) *CSINodeDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinodedriver.go","code":"// WithAllocatable sets the Allocatable field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Allocatable field is set to the value of the last call.\nfunc (b *CSINodeDriverApplyConfiguration) WithAllocatable(value *VolumeNodeResourcesApplyConfiguration) *CSINodeDriverApplyConfiguration {\n\tb.Allocatable = value\n\treturn b\n}","line":{"from":62,"to":68}} {"id":100024668,"name":"CSINodeSpec","signature":"func CSINodeSpec() *CSINodeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinodespec.go","code":"// CSINodeSpecApplyConfiguration constructs an declarative configuration of the CSINodeSpec type for use with\n// apply.\nfunc CSINodeSpec() *CSINodeSpecApplyConfiguration {\n\treturn \u0026CSINodeSpecApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100024669,"name":"WithDrivers","signature":"func (b *CSINodeSpecApplyConfiguration) WithDrivers(values ...*CSINodeDriverApplyConfiguration) *CSINodeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csinodespec.go","code":"// WithDrivers adds the given value to the Drivers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Drivers field.\nfunc (b *CSINodeSpecApplyConfiguration) WithDrivers(values ...*CSINodeDriverApplyConfiguration) *CSINodeSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithDrivers\")\n\t\t}\n\t\tb.Drivers = append(b.Drivers, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100024670,"name":"CSIStorageCapacity","signature":"func CSIStorageCapacity(name, namespace string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go","code":"// CSIStorageCapacity constructs an declarative configuration of the CSIStorageCapacity type for use with\n// apply.\nfunc CSIStorageCapacity(name, namespace string) *CSIStorageCapacityApplyConfiguration {\n\tb := \u0026CSIStorageCapacityApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"CSIStorageCapacity\")\n\tb.WithAPIVersion(\"storage.k8s.io/v1\")\n\treturn b\n}","line":{"from":42,"to":51}} {"id":100024671,"name":"ExtractCSIStorageCapacity","signature":"func ExtractCSIStorageCapacity(cSIStorageCapacity *storagev1.CSIStorageCapacity, fieldManager string) (*CSIStorageCapacityApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go","code":"// ExtractCSIStorageCapacity extracts the applied configuration owned by fieldManager from\n// cSIStorageCapacity. If no managedFields are found in cSIStorageCapacity for fieldManager, a\n// CSIStorageCapacityApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// cSIStorageCapacity must be a unmodified CSIStorageCapacity API object that was retrieved from the Kubernetes API.\n// ExtractCSIStorageCapacity provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractCSIStorageCapacity(cSIStorageCapacity *storagev1.CSIStorageCapacity, fieldManager string) (*CSIStorageCapacityApplyConfiguration, error) {\n\treturn extractCSIStorageCapacity(cSIStorageCapacity, fieldManager, \"\")\n}","line":{"from":53,"to":66}} {"id":100024672,"name":"ExtractCSIStorageCapacityStatus","signature":"func ExtractCSIStorageCapacityStatus(cSIStorageCapacity *storagev1.CSIStorageCapacity, fieldManager string) (*CSIStorageCapacityApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go","code":"// ExtractCSIStorageCapacityStatus is the same as ExtractCSIStorageCapacity except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractCSIStorageCapacityStatus(cSIStorageCapacity *storagev1.CSIStorageCapacity, fieldManager string) (*CSIStorageCapacityApplyConfiguration, error) {\n\treturn extractCSIStorageCapacity(cSIStorageCapacity, fieldManager, \"status\")\n}","line":{"from":68,"to":73}} {"id":100024673,"name":"extractCSIStorageCapacity","signature":"func extractCSIStorageCapacity(cSIStorageCapacity *storagev1.CSIStorageCapacity, fieldManager string, subresource string) (*CSIStorageCapacityApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go","code":"func extractCSIStorageCapacity(cSIStorageCapacity *storagev1.CSIStorageCapacity, fieldManager string, subresource string) (*CSIStorageCapacityApplyConfiguration, error) {\n\tb := \u0026CSIStorageCapacityApplyConfiguration{}\n\terr := managedfields.ExtractInto(cSIStorageCapacity, internal.Parser().Type(\"io.k8s.api.storage.v1.CSIStorageCapacity\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(cSIStorageCapacity.Name)\n\tb.WithNamespace(cSIStorageCapacity.Namespace)\n\n\tb.WithKind(\"CSIStorageCapacity\")\n\tb.WithAPIVersion(\"storage.k8s.io/v1\")\n\treturn b, nil\n}","line":{"from":75,"to":87}} {"id":100024674,"name":"WithKind","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithKind(value string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithKind(value string) *CSIStorageCapacityApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":89,"to":95}} {"id":100024675,"name":"WithAPIVersion","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithAPIVersion(value string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithAPIVersion(value string) *CSIStorageCapacityApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":97,"to":103}} {"id":100024676,"name":"WithName","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithName(value string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithName(value string) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":105,"to":112}} {"id":100024677,"name":"WithGenerateName","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithGenerateName(value string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithGenerateName(value string) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":114,"to":121}} {"id":100024678,"name":"WithNamespace","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithNamespace(value string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithNamespace(value string) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":123,"to":130}} {"id":100024679,"name":"WithUID","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithUID(value types.UID) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithUID(value types.UID) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":132,"to":139}} {"id":100024680,"name":"WithResourceVersion","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithResourceVersion(value string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithResourceVersion(value string) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":141,"to":148}} {"id":100024681,"name":"WithGeneration","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithGeneration(value int64) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithGeneration(value int64) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":150,"to":157}} {"id":100024682,"name":"WithCreationTimestamp","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithCreationTimestamp(value metav1.Time) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithCreationTimestamp(value metav1.Time) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":159,"to":166}} {"id":100024683,"name":"WithDeletionTimestamp","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":168,"to":175}} {"id":100024684,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":177,"to":184}} {"id":100024685,"name":"WithLabels","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithLabels(entries map[string]string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithLabels(entries map[string]string) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":186,"to":199}} {"id":100024686,"name":"WithAnnotations","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithAnnotations(entries map[string]string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithAnnotations(entries map[string]string) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":201,"to":214}} {"id":100024687,"name":"WithOwnerReferences","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":216,"to":228}} {"id":100024688,"name":"WithFinalizers","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithFinalizers(values ...string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithFinalizers(values ...string) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":230,"to":239}} {"id":100024689,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *CSIStorageCapacityApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go","code":"func (b *CSIStorageCapacityApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":241,"to":245}} {"id":100024690,"name":"WithNodeTopology","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithNodeTopology(value *v1.LabelSelectorApplyConfiguration) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go","code":"// WithNodeTopology sets the NodeTopology field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NodeTopology field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithNodeTopology(value *v1.LabelSelectorApplyConfiguration) *CSIStorageCapacityApplyConfiguration {\n\tb.NodeTopology = value\n\treturn b\n}","line":{"from":247,"to":253}} {"id":100024691,"name":"WithStorageClassName","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithStorageClassName(value string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go","code":"// WithStorageClassName sets the StorageClassName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StorageClassName field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithStorageClassName(value string) *CSIStorageCapacityApplyConfiguration {\n\tb.StorageClassName = \u0026value\n\treturn b\n}","line":{"from":255,"to":261}} {"id":100024692,"name":"WithCapacity","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithCapacity(value resource.Quantity) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go","code":"// WithCapacity sets the Capacity field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Capacity field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithCapacity(value resource.Quantity) *CSIStorageCapacityApplyConfiguration {\n\tb.Capacity = \u0026value\n\treturn b\n}","line":{"from":263,"to":269}} {"id":100024693,"name":"WithMaximumVolumeSize","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithMaximumVolumeSize(value resource.Quantity) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/csistoragecapacity.go","code":"// WithMaximumVolumeSize sets the MaximumVolumeSize field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MaximumVolumeSize field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithMaximumVolumeSize(value resource.Quantity) *CSIStorageCapacityApplyConfiguration {\n\tb.MaximumVolumeSize = \u0026value\n\treturn b\n}","line":{"from":271,"to":277}} {"id":100024694,"name":"StorageClass","signature":"func StorageClass(name string) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"// StorageClass constructs an declarative configuration of the StorageClass type for use with\n// apply.\nfunc StorageClass(name string) *StorageClassApplyConfiguration {\n\tb := \u0026StorageClassApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"StorageClass\")\n\tb.WithAPIVersion(\"storage.k8s.io/v1\")\n\treturn b\n}","line":{"from":46,"to":54}} {"id":100024695,"name":"ExtractStorageClass","signature":"func ExtractStorageClass(storageClass *storagev1.StorageClass, fieldManager string) (*StorageClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"// ExtractStorageClass extracts the applied configuration owned by fieldManager from\n// storageClass. If no managedFields are found in storageClass for fieldManager, a\n// StorageClassApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// storageClass must be a unmodified StorageClass API object that was retrieved from the Kubernetes API.\n// ExtractStorageClass provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractStorageClass(storageClass *storagev1.StorageClass, fieldManager string) (*StorageClassApplyConfiguration, error) {\n\treturn extractStorageClass(storageClass, fieldManager, \"\")\n}","line":{"from":56,"to":69}} {"id":100024696,"name":"ExtractStorageClassStatus","signature":"func ExtractStorageClassStatus(storageClass *storagev1.StorageClass, fieldManager string) (*StorageClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"// ExtractStorageClassStatus is the same as ExtractStorageClass except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractStorageClassStatus(storageClass *storagev1.StorageClass, fieldManager string) (*StorageClassApplyConfiguration, error) {\n\treturn extractStorageClass(storageClass, fieldManager, \"status\")\n}","line":{"from":71,"to":76}} {"id":100024697,"name":"extractStorageClass","signature":"func extractStorageClass(storageClass *storagev1.StorageClass, fieldManager string, subresource string) (*StorageClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"func extractStorageClass(storageClass *storagev1.StorageClass, fieldManager string, subresource string) (*StorageClassApplyConfiguration, error) {\n\tb := \u0026StorageClassApplyConfiguration{}\n\terr := managedfields.ExtractInto(storageClass, internal.Parser().Type(\"io.k8s.api.storage.v1.StorageClass\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(storageClass.Name)\n\n\tb.WithKind(\"StorageClass\")\n\tb.WithAPIVersion(\"storage.k8s.io/v1\")\n\treturn b, nil\n}","line":{"from":78,"to":89}} {"id":100024698,"name":"WithKind","signature":"func (b *StorageClassApplyConfiguration) WithKind(value string) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithKind(value string) *StorageClassApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":91,"to":97}} {"id":100024699,"name":"WithAPIVersion","signature":"func (b *StorageClassApplyConfiguration) WithAPIVersion(value string) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithAPIVersion(value string) *StorageClassApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":99,"to":105}} {"id":100024700,"name":"WithName","signature":"func (b *StorageClassApplyConfiguration) WithName(value string) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithName(value string) *StorageClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":107,"to":114}} {"id":100024701,"name":"WithGenerateName","signature":"func (b *StorageClassApplyConfiguration) WithGenerateName(value string) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithGenerateName(value string) *StorageClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":116,"to":123}} {"id":100024702,"name":"WithNamespace","signature":"func (b *StorageClassApplyConfiguration) WithNamespace(value string) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithNamespace(value string) *StorageClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":125,"to":132}} {"id":100024703,"name":"WithUID","signature":"func (b *StorageClassApplyConfiguration) WithUID(value types.UID) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithUID(value types.UID) *StorageClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":134,"to":141}} {"id":100024704,"name":"WithResourceVersion","signature":"func (b *StorageClassApplyConfiguration) WithResourceVersion(value string) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithResourceVersion(value string) *StorageClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":143,"to":150}} {"id":100024705,"name":"WithGeneration","signature":"func (b *StorageClassApplyConfiguration) WithGeneration(value int64) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithGeneration(value int64) *StorageClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":152,"to":159}} {"id":100024706,"name":"WithCreationTimestamp","signature":"func (b *StorageClassApplyConfiguration) WithCreationTimestamp(value metav1.Time) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithCreationTimestamp(value metav1.Time) *StorageClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":161,"to":168}} {"id":100024707,"name":"WithDeletionTimestamp","signature":"func (b *StorageClassApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *StorageClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":170,"to":177}} {"id":100024708,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *StorageClassApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *StorageClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":179,"to":186}} {"id":100024709,"name":"WithLabels","signature":"func (b *StorageClassApplyConfiguration) WithLabels(entries map[string]string) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *StorageClassApplyConfiguration) WithLabels(entries map[string]string) *StorageClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":188,"to":201}} {"id":100024710,"name":"WithAnnotations","signature":"func (b *StorageClassApplyConfiguration) WithAnnotations(entries map[string]string) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *StorageClassApplyConfiguration) WithAnnotations(entries map[string]string) *StorageClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":203,"to":216}} {"id":100024711,"name":"WithOwnerReferences","signature":"func (b *StorageClassApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *StorageClassApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *StorageClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":218,"to":230}} {"id":100024712,"name":"WithFinalizers","signature":"func (b *StorageClassApplyConfiguration) WithFinalizers(values ...string) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *StorageClassApplyConfiguration) WithFinalizers(values ...string) *StorageClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":232,"to":241}} {"id":100024713,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *StorageClassApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"func (b *StorageClassApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":243,"to":247}} {"id":100024714,"name":"WithProvisioner","signature":"func (b *StorageClassApplyConfiguration) WithProvisioner(value string) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"// WithProvisioner sets the Provisioner field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Provisioner field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithProvisioner(value string) *StorageClassApplyConfiguration {\n\tb.Provisioner = \u0026value\n\treturn b\n}","line":{"from":249,"to":255}} {"id":100024715,"name":"WithParameters","signature":"func (b *StorageClassApplyConfiguration) WithParameters(entries map[string]string) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"// WithParameters puts the entries into the Parameters field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Parameters field,\n// overwriting an existing map entries in Parameters field with the same key.\nfunc (b *StorageClassApplyConfiguration) WithParameters(entries map[string]string) *StorageClassApplyConfiguration {\n\tif b.Parameters == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Parameters = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Parameters[k] = v\n\t}\n\treturn b\n}","line":{"from":257,"to":269}} {"id":100024716,"name":"WithReclaimPolicy","signature":"func (b *StorageClassApplyConfiguration) WithReclaimPolicy(value corev1.PersistentVolumeReclaimPolicy) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"// WithReclaimPolicy sets the ReclaimPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReclaimPolicy field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithReclaimPolicy(value corev1.PersistentVolumeReclaimPolicy) *StorageClassApplyConfiguration {\n\tb.ReclaimPolicy = \u0026value\n\treturn b\n}","line":{"from":271,"to":277}} {"id":100024717,"name":"WithMountOptions","signature":"func (b *StorageClassApplyConfiguration) WithMountOptions(values ...string) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"// WithMountOptions adds the given value to the MountOptions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the MountOptions field.\nfunc (b *StorageClassApplyConfiguration) WithMountOptions(values ...string) *StorageClassApplyConfiguration {\n\tfor i := range values {\n\t\tb.MountOptions = append(b.MountOptions, values[i])\n\t}\n\treturn b\n}","line":{"from":279,"to":287}} {"id":100024718,"name":"WithAllowVolumeExpansion","signature":"func (b *StorageClassApplyConfiguration) WithAllowVolumeExpansion(value bool) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"// WithAllowVolumeExpansion sets the AllowVolumeExpansion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AllowVolumeExpansion field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithAllowVolumeExpansion(value bool) *StorageClassApplyConfiguration {\n\tb.AllowVolumeExpansion = \u0026value\n\treturn b\n}","line":{"from":289,"to":295}} {"id":100024719,"name":"WithVolumeBindingMode","signature":"func (b *StorageClassApplyConfiguration) WithVolumeBindingMode(value storagev1.VolumeBindingMode) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"// WithVolumeBindingMode sets the VolumeBindingMode field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the VolumeBindingMode field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithVolumeBindingMode(value storagev1.VolumeBindingMode) *StorageClassApplyConfiguration {\n\tb.VolumeBindingMode = \u0026value\n\treturn b\n}","line":{"from":297,"to":303}} {"id":100024720,"name":"WithAllowedTopologies","signature":"func (b *StorageClassApplyConfiguration) WithAllowedTopologies(values ...*applyconfigurationscorev1.TopologySelectorTermApplyConfiguration) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/storageclass.go","code":"// WithAllowedTopologies adds the given value to the AllowedTopologies field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the AllowedTopologies field.\nfunc (b *StorageClassApplyConfiguration) WithAllowedTopologies(values ...*applyconfigurationscorev1.TopologySelectorTermApplyConfiguration) *StorageClassApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithAllowedTopologies\")\n\t\t}\n\t\tb.AllowedTopologies = append(b.AllowedTopologies, *values[i])\n\t}\n\treturn b\n}","line":{"from":305,"to":316}} {"id":100024721,"name":"TokenRequest","signature":"func TokenRequest() *TokenRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/tokenrequest.go","code":"// TokenRequestApplyConfiguration constructs an declarative configuration of the TokenRequest type for use with\n// apply.\nfunc TokenRequest() *TokenRequestApplyConfiguration {\n\treturn \u0026TokenRequestApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100024722,"name":"WithAudience","signature":"func (b *TokenRequestApplyConfiguration) WithAudience(value string) *TokenRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/tokenrequest.go","code":"// WithAudience sets the Audience field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Audience field is set to the value of the last call.\nfunc (b *TokenRequestApplyConfiguration) WithAudience(value string) *TokenRequestApplyConfiguration {\n\tb.Audience = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100024723,"name":"WithExpirationSeconds","signature":"func (b *TokenRequestApplyConfiguration) WithExpirationSeconds(value int64) *TokenRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/tokenrequest.go","code":"// WithExpirationSeconds sets the ExpirationSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ExpirationSeconds field is set to the value of the last call.\nfunc (b *TokenRequestApplyConfiguration) WithExpirationSeconds(value int64) *TokenRequestApplyConfiguration {\n\tb.ExpirationSeconds = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100024724,"name":"VolumeAttachment","signature":"func VolumeAttachment(name string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachment.go","code":"// VolumeAttachment constructs an declarative configuration of the VolumeAttachment type for use with\n// apply.\nfunc VolumeAttachment(name string) *VolumeAttachmentApplyConfiguration {\n\tb := \u0026VolumeAttachmentApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"VolumeAttachment\")\n\tb.WithAPIVersion(\"storage.k8s.io/v1\")\n\treturn b\n}","line":{"from":39,"to":47}} {"id":100024725,"name":"ExtractVolumeAttachment","signature":"func ExtractVolumeAttachment(volumeAttachment *apistoragev1.VolumeAttachment, fieldManager string) (*VolumeAttachmentApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachment.go","code":"// ExtractVolumeAttachment extracts the applied configuration owned by fieldManager from\n// volumeAttachment. If no managedFields are found in volumeAttachment for fieldManager, a\n// VolumeAttachmentApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// volumeAttachment must be a unmodified VolumeAttachment API object that was retrieved from the Kubernetes API.\n// ExtractVolumeAttachment provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractVolumeAttachment(volumeAttachment *apistoragev1.VolumeAttachment, fieldManager string) (*VolumeAttachmentApplyConfiguration, error) {\n\treturn extractVolumeAttachment(volumeAttachment, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100024726,"name":"ExtractVolumeAttachmentStatus","signature":"func ExtractVolumeAttachmentStatus(volumeAttachment *apistoragev1.VolumeAttachment, fieldManager string) (*VolumeAttachmentApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachment.go","code":"// ExtractVolumeAttachmentStatus is the same as ExtractVolumeAttachment except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractVolumeAttachmentStatus(volumeAttachment *apistoragev1.VolumeAttachment, fieldManager string) (*VolumeAttachmentApplyConfiguration, error) {\n\treturn extractVolumeAttachment(volumeAttachment, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100024727,"name":"extractVolumeAttachment","signature":"func extractVolumeAttachment(volumeAttachment *apistoragev1.VolumeAttachment, fieldManager string, subresource string) (*VolumeAttachmentApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachment.go","code":"func extractVolumeAttachment(volumeAttachment *apistoragev1.VolumeAttachment, fieldManager string, subresource string) (*VolumeAttachmentApplyConfiguration, error) {\n\tb := \u0026VolumeAttachmentApplyConfiguration{}\n\terr := managedfields.ExtractInto(volumeAttachment, internal.Parser().Type(\"io.k8s.api.storage.v1.VolumeAttachment\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(volumeAttachment.Name)\n\n\tb.WithKind(\"VolumeAttachment\")\n\tb.WithAPIVersion(\"storage.k8s.io/v1\")\n\treturn b, nil\n}","line":{"from":71,"to":82}} {"id":100024728,"name":"WithKind","signature":"func (b *VolumeAttachmentApplyConfiguration) WithKind(value string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachment.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithKind(value string) *VolumeAttachmentApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100024729,"name":"WithAPIVersion","signature":"func (b *VolumeAttachmentApplyConfiguration) WithAPIVersion(value string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachment.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithAPIVersion(value string) *VolumeAttachmentApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100024730,"name":"WithName","signature":"func (b *VolumeAttachmentApplyConfiguration) WithName(value string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachment.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithName(value string) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":100,"to":107}} {"id":100024731,"name":"WithGenerateName","signature":"func (b *VolumeAttachmentApplyConfiguration) WithGenerateName(value string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachment.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithGenerateName(value string) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":109,"to":116}} {"id":100024732,"name":"WithNamespace","signature":"func (b *VolumeAttachmentApplyConfiguration) WithNamespace(value string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachment.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithNamespace(value string) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":118,"to":125}} {"id":100024733,"name":"WithUID","signature":"func (b *VolumeAttachmentApplyConfiguration) WithUID(value types.UID) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachment.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithUID(value types.UID) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":127,"to":134}} {"id":100024734,"name":"WithResourceVersion","signature":"func (b *VolumeAttachmentApplyConfiguration) WithResourceVersion(value string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachment.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithResourceVersion(value string) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":136,"to":143}} {"id":100024735,"name":"WithGeneration","signature":"func (b *VolumeAttachmentApplyConfiguration) WithGeneration(value int64) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachment.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithGeneration(value int64) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":145,"to":152}} {"id":100024736,"name":"WithCreationTimestamp","signature":"func (b *VolumeAttachmentApplyConfiguration) WithCreationTimestamp(value metav1.Time) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachment.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithCreationTimestamp(value metav1.Time) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":154,"to":161}} {"id":100024737,"name":"WithDeletionTimestamp","signature":"func (b *VolumeAttachmentApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachment.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":163,"to":170}} {"id":100024738,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *VolumeAttachmentApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachment.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":172,"to":179}} {"id":100024739,"name":"WithLabels","signature":"func (b *VolumeAttachmentApplyConfiguration) WithLabels(entries map[string]string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachment.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *VolumeAttachmentApplyConfiguration) WithLabels(entries map[string]string) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":181,"to":194}} {"id":100024740,"name":"WithAnnotations","signature":"func (b *VolumeAttachmentApplyConfiguration) WithAnnotations(entries map[string]string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachment.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *VolumeAttachmentApplyConfiguration) WithAnnotations(entries map[string]string) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100024741,"name":"WithOwnerReferences","signature":"func (b *VolumeAttachmentApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachment.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *VolumeAttachmentApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":211,"to":223}} {"id":100024742,"name":"WithFinalizers","signature":"func (b *VolumeAttachmentApplyConfiguration) WithFinalizers(values ...string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachment.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *VolumeAttachmentApplyConfiguration) WithFinalizers(values ...string) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":225,"to":234}} {"id":100024743,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *VolumeAttachmentApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachment.go","code":"func (b *VolumeAttachmentApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":236,"to":240}} {"id":100024744,"name":"WithSpec","signature":"func (b *VolumeAttachmentApplyConfiguration) WithSpec(value *VolumeAttachmentSpecApplyConfiguration) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachment.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithSpec(value *VolumeAttachmentSpecApplyConfiguration) *VolumeAttachmentApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":242,"to":248}} {"id":100024745,"name":"WithStatus","signature":"func (b *VolumeAttachmentApplyConfiguration) WithStatus(value *VolumeAttachmentStatusApplyConfiguration) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachment.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithStatus(value *VolumeAttachmentStatusApplyConfiguration) *VolumeAttachmentApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":250,"to":256}} {"id":100024746,"name":"VolumeAttachmentSource","signature":"func VolumeAttachmentSource() *VolumeAttachmentSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachmentsource.go","code":"// VolumeAttachmentSourceApplyConfiguration constructs an declarative configuration of the VolumeAttachmentSource type for use with\n// apply.\nfunc VolumeAttachmentSource() *VolumeAttachmentSourceApplyConfiguration {\n\treturn \u0026VolumeAttachmentSourceApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100024747,"name":"WithPersistentVolumeName","signature":"func (b *VolumeAttachmentSourceApplyConfiguration) WithPersistentVolumeName(value string) *VolumeAttachmentSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachmentsource.go","code":"// WithPersistentVolumeName sets the PersistentVolumeName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PersistentVolumeName field is set to the value of the last call.\nfunc (b *VolumeAttachmentSourceApplyConfiguration) WithPersistentVolumeName(value string) *VolumeAttachmentSourceApplyConfiguration {\n\tb.PersistentVolumeName = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100024748,"name":"WithInlineVolumeSpec","signature":"func (b *VolumeAttachmentSourceApplyConfiguration) WithInlineVolumeSpec(value *v1.PersistentVolumeSpecApplyConfiguration) *VolumeAttachmentSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachmentsource.go","code":"// WithInlineVolumeSpec sets the InlineVolumeSpec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the InlineVolumeSpec field is set to the value of the last call.\nfunc (b *VolumeAttachmentSourceApplyConfiguration) WithInlineVolumeSpec(value *v1.PersistentVolumeSpecApplyConfiguration) *VolumeAttachmentSourceApplyConfiguration {\n\tb.InlineVolumeSpec = value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100024749,"name":"VolumeAttachmentSpec","signature":"func VolumeAttachmentSpec() *VolumeAttachmentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachmentspec.go","code":"// VolumeAttachmentSpecApplyConfiguration constructs an declarative configuration of the VolumeAttachmentSpec type for use with\n// apply.\nfunc VolumeAttachmentSpec() *VolumeAttachmentSpecApplyConfiguration {\n\treturn \u0026VolumeAttachmentSpecApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100024750,"name":"WithAttacher","signature":"func (b *VolumeAttachmentSpecApplyConfiguration) WithAttacher(value string) *VolumeAttachmentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachmentspec.go","code":"// WithAttacher sets the Attacher field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Attacher field is set to the value of the last call.\nfunc (b *VolumeAttachmentSpecApplyConfiguration) WithAttacher(value string) *VolumeAttachmentSpecApplyConfiguration {\n\tb.Attacher = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100024751,"name":"WithSource","signature":"func (b *VolumeAttachmentSpecApplyConfiguration) WithSource(value *VolumeAttachmentSourceApplyConfiguration) *VolumeAttachmentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachmentspec.go","code":"// WithSource sets the Source field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Source field is set to the value of the last call.\nfunc (b *VolumeAttachmentSpecApplyConfiguration) WithSource(value *VolumeAttachmentSourceApplyConfiguration) *VolumeAttachmentSpecApplyConfiguration {\n\tb.Source = value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100024752,"name":"WithNodeName","signature":"func (b *VolumeAttachmentSpecApplyConfiguration) WithNodeName(value string) *VolumeAttachmentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachmentspec.go","code":"// WithNodeName sets the NodeName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NodeName field is set to the value of the last call.\nfunc (b *VolumeAttachmentSpecApplyConfiguration) WithNodeName(value string) *VolumeAttachmentSpecApplyConfiguration {\n\tb.NodeName = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100024753,"name":"VolumeAttachmentStatus","signature":"func VolumeAttachmentStatus() *VolumeAttachmentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachmentstatus.go","code":"// VolumeAttachmentStatusApplyConfiguration constructs an declarative configuration of the VolumeAttachmentStatus type for use with\n// apply.\nfunc VolumeAttachmentStatus() *VolumeAttachmentStatusApplyConfiguration {\n\treturn \u0026VolumeAttachmentStatusApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100024754,"name":"WithAttached","signature":"func (b *VolumeAttachmentStatusApplyConfiguration) WithAttached(value bool) *VolumeAttachmentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachmentstatus.go","code":"// WithAttached sets the Attached field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Attached field is set to the value of the last call.\nfunc (b *VolumeAttachmentStatusApplyConfiguration) WithAttached(value bool) *VolumeAttachmentStatusApplyConfiguration {\n\tb.Attached = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100024755,"name":"WithAttachmentMetadata","signature":"func (b *VolumeAttachmentStatusApplyConfiguration) WithAttachmentMetadata(entries map[string]string) *VolumeAttachmentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachmentstatus.go","code":"// WithAttachmentMetadata puts the entries into the AttachmentMetadata field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the AttachmentMetadata field,\n// overwriting an existing map entries in AttachmentMetadata field with the same key.\nfunc (b *VolumeAttachmentStatusApplyConfiguration) WithAttachmentMetadata(entries map[string]string) *VolumeAttachmentStatusApplyConfiguration {\n\tif b.AttachmentMetadata == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.AttachmentMetadata = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.AttachmentMetadata[k] = v\n\t}\n\treturn b\n}","line":{"from":44,"to":56}} {"id":100024756,"name":"WithAttachError","signature":"func (b *VolumeAttachmentStatusApplyConfiguration) WithAttachError(value *VolumeErrorApplyConfiguration) *VolumeAttachmentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachmentstatus.go","code":"// WithAttachError sets the AttachError field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AttachError field is set to the value of the last call.\nfunc (b *VolumeAttachmentStatusApplyConfiguration) WithAttachError(value *VolumeErrorApplyConfiguration) *VolumeAttachmentStatusApplyConfiguration {\n\tb.AttachError = value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100024757,"name":"WithDetachError","signature":"func (b *VolumeAttachmentStatusApplyConfiguration) WithDetachError(value *VolumeErrorApplyConfiguration) *VolumeAttachmentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeattachmentstatus.go","code":"// WithDetachError sets the DetachError field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DetachError field is set to the value of the last call.\nfunc (b *VolumeAttachmentStatusApplyConfiguration) WithDetachError(value *VolumeErrorApplyConfiguration) *VolumeAttachmentStatusApplyConfiguration {\n\tb.DetachError = value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100024758,"name":"VolumeError","signature":"func VolumeError() *VolumeErrorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeerror.go","code":"// VolumeErrorApplyConfiguration constructs an declarative configuration of the VolumeError type for use with\n// apply.\nfunc VolumeError() *VolumeErrorApplyConfiguration {\n\treturn \u0026VolumeErrorApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100024759,"name":"WithTime","signature":"func (b *VolumeErrorApplyConfiguration) WithTime(value v1.Time) *VolumeErrorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeerror.go","code":"// WithTime sets the Time field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Time field is set to the value of the last call.\nfunc (b *VolumeErrorApplyConfiguration) WithTime(value v1.Time) *VolumeErrorApplyConfiguration {\n\tb.Time = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100024760,"name":"WithMessage","signature":"func (b *VolumeErrorApplyConfiguration) WithMessage(value string) *VolumeErrorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumeerror.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *VolumeErrorApplyConfiguration) WithMessage(value string) *VolumeErrorApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100024761,"name":"VolumeNodeResources","signature":"func VolumeNodeResources() *VolumeNodeResourcesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumenoderesources.go","code":"// VolumeNodeResourcesApplyConfiguration constructs an declarative configuration of the VolumeNodeResources type for use with\n// apply.\nfunc VolumeNodeResources() *VolumeNodeResourcesApplyConfiguration {\n\treturn \u0026VolumeNodeResourcesApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100024762,"name":"WithCount","signature":"func (b *VolumeNodeResourcesApplyConfiguration) WithCount(value int32) *VolumeNodeResourcesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1/volumenoderesources.go","code":"// WithCount sets the Count field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Count field is set to the value of the last call.\nfunc (b *VolumeNodeResourcesApplyConfiguration) WithCount(value int32) *VolumeNodeResourcesApplyConfiguration {\n\tb.Count = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100024763,"name":"CSIStorageCapacity","signature":"func CSIStorageCapacity(name, namespace string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go","code":"// CSIStorageCapacity constructs an declarative configuration of the CSIStorageCapacity type for use with\n// apply.\nfunc CSIStorageCapacity(name, namespace string) *CSIStorageCapacityApplyConfiguration {\n\tb := \u0026CSIStorageCapacityApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"CSIStorageCapacity\")\n\tb.WithAPIVersion(\"storage.k8s.io/v1alpha1\")\n\treturn b\n}","line":{"from":42,"to":51}} {"id":100024764,"name":"ExtractCSIStorageCapacity","signature":"func ExtractCSIStorageCapacity(cSIStorageCapacity *v1alpha1.CSIStorageCapacity, fieldManager string) (*CSIStorageCapacityApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go","code":"// ExtractCSIStorageCapacity extracts the applied configuration owned by fieldManager from\n// cSIStorageCapacity. If no managedFields are found in cSIStorageCapacity for fieldManager, a\n// CSIStorageCapacityApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// cSIStorageCapacity must be a unmodified CSIStorageCapacity API object that was retrieved from the Kubernetes API.\n// ExtractCSIStorageCapacity provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractCSIStorageCapacity(cSIStorageCapacity *v1alpha1.CSIStorageCapacity, fieldManager string) (*CSIStorageCapacityApplyConfiguration, error) {\n\treturn extractCSIStorageCapacity(cSIStorageCapacity, fieldManager, \"\")\n}","line":{"from":53,"to":66}} {"id":100024765,"name":"ExtractCSIStorageCapacityStatus","signature":"func ExtractCSIStorageCapacityStatus(cSIStorageCapacity *v1alpha1.CSIStorageCapacity, fieldManager string) (*CSIStorageCapacityApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go","code":"// ExtractCSIStorageCapacityStatus is the same as ExtractCSIStorageCapacity except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractCSIStorageCapacityStatus(cSIStorageCapacity *v1alpha1.CSIStorageCapacity, fieldManager string) (*CSIStorageCapacityApplyConfiguration, error) {\n\treturn extractCSIStorageCapacity(cSIStorageCapacity, fieldManager, \"status\")\n}","line":{"from":68,"to":73}} {"id":100024766,"name":"extractCSIStorageCapacity","signature":"func extractCSIStorageCapacity(cSIStorageCapacity *v1alpha1.CSIStorageCapacity, fieldManager string, subresource string) (*CSIStorageCapacityApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go","code":"func extractCSIStorageCapacity(cSIStorageCapacity *v1alpha1.CSIStorageCapacity, fieldManager string, subresource string) (*CSIStorageCapacityApplyConfiguration, error) {\n\tb := \u0026CSIStorageCapacityApplyConfiguration{}\n\terr := managedfields.ExtractInto(cSIStorageCapacity, internal.Parser().Type(\"io.k8s.api.storage.v1alpha1.CSIStorageCapacity\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(cSIStorageCapacity.Name)\n\tb.WithNamespace(cSIStorageCapacity.Namespace)\n\n\tb.WithKind(\"CSIStorageCapacity\")\n\tb.WithAPIVersion(\"storage.k8s.io/v1alpha1\")\n\treturn b, nil\n}","line":{"from":75,"to":87}} {"id":100024767,"name":"WithKind","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithKind(value string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithKind(value string) *CSIStorageCapacityApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":89,"to":95}} {"id":100024768,"name":"WithAPIVersion","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithAPIVersion(value string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithAPIVersion(value string) *CSIStorageCapacityApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":97,"to":103}} {"id":100024769,"name":"WithName","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithName(value string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithName(value string) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":105,"to":112}} {"id":100024770,"name":"WithGenerateName","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithGenerateName(value string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithGenerateName(value string) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":114,"to":121}} {"id":100024771,"name":"WithNamespace","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithNamespace(value string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithNamespace(value string) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":123,"to":130}} {"id":100024772,"name":"WithUID","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithUID(value types.UID) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithUID(value types.UID) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":132,"to":139}} {"id":100024773,"name":"WithResourceVersion","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithResourceVersion(value string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithResourceVersion(value string) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":141,"to":148}} {"id":100024774,"name":"WithGeneration","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithGeneration(value int64) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithGeneration(value int64) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":150,"to":157}} {"id":100024775,"name":"WithCreationTimestamp","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithCreationTimestamp(value metav1.Time) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithCreationTimestamp(value metav1.Time) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":159,"to":166}} {"id":100024776,"name":"WithDeletionTimestamp","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":168,"to":175}} {"id":100024777,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":177,"to":184}} {"id":100024778,"name":"WithLabels","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithLabels(entries map[string]string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithLabels(entries map[string]string) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":186,"to":199}} {"id":100024779,"name":"WithAnnotations","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithAnnotations(entries map[string]string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithAnnotations(entries map[string]string) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":201,"to":214}} {"id":100024780,"name":"WithOwnerReferences","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":216,"to":228}} {"id":100024781,"name":"WithFinalizers","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithFinalizers(values ...string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithFinalizers(values ...string) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":230,"to":239}} {"id":100024782,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *CSIStorageCapacityApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go","code":"func (b *CSIStorageCapacityApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":241,"to":245}} {"id":100024783,"name":"WithNodeTopology","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithNodeTopology(value *v1.LabelSelectorApplyConfiguration) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go","code":"// WithNodeTopology sets the NodeTopology field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NodeTopology field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithNodeTopology(value *v1.LabelSelectorApplyConfiguration) *CSIStorageCapacityApplyConfiguration {\n\tb.NodeTopology = value\n\treturn b\n}","line":{"from":247,"to":253}} {"id":100024784,"name":"WithStorageClassName","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithStorageClassName(value string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go","code":"// WithStorageClassName sets the StorageClassName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StorageClassName field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithStorageClassName(value string) *CSIStorageCapacityApplyConfiguration {\n\tb.StorageClassName = \u0026value\n\treturn b\n}","line":{"from":255,"to":261}} {"id":100024785,"name":"WithCapacity","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithCapacity(value resource.Quantity) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go","code":"// WithCapacity sets the Capacity field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Capacity field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithCapacity(value resource.Quantity) *CSIStorageCapacityApplyConfiguration {\n\tb.Capacity = \u0026value\n\treturn b\n}","line":{"from":263,"to":269}} {"id":100024786,"name":"WithMaximumVolumeSize","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithMaximumVolumeSize(value resource.Quantity) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/csistoragecapacity.go","code":"// WithMaximumVolumeSize sets the MaximumVolumeSize field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MaximumVolumeSize field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithMaximumVolumeSize(value resource.Quantity) *CSIStorageCapacityApplyConfiguration {\n\tb.MaximumVolumeSize = \u0026value\n\treturn b\n}","line":{"from":271,"to":277}} {"id":100024787,"name":"VolumeAttachment","signature":"func VolumeAttachment(name string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachment.go","code":"// VolumeAttachment constructs an declarative configuration of the VolumeAttachment type for use with\n// apply.\nfunc VolumeAttachment(name string) *VolumeAttachmentApplyConfiguration {\n\tb := \u0026VolumeAttachmentApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"VolumeAttachment\")\n\tb.WithAPIVersion(\"storage.k8s.io/v1alpha1\")\n\treturn b\n}","line":{"from":39,"to":47}} {"id":100024788,"name":"ExtractVolumeAttachment","signature":"func ExtractVolumeAttachment(volumeAttachment *storagev1alpha1.VolumeAttachment, fieldManager string) (*VolumeAttachmentApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachment.go","code":"// ExtractVolumeAttachment extracts the applied configuration owned by fieldManager from\n// volumeAttachment. If no managedFields are found in volumeAttachment for fieldManager, a\n// VolumeAttachmentApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// volumeAttachment must be a unmodified VolumeAttachment API object that was retrieved from the Kubernetes API.\n// ExtractVolumeAttachment provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractVolumeAttachment(volumeAttachment *storagev1alpha1.VolumeAttachment, fieldManager string) (*VolumeAttachmentApplyConfiguration, error) {\n\treturn extractVolumeAttachment(volumeAttachment, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100024789,"name":"ExtractVolumeAttachmentStatus","signature":"func ExtractVolumeAttachmentStatus(volumeAttachment *storagev1alpha1.VolumeAttachment, fieldManager string) (*VolumeAttachmentApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachment.go","code":"// ExtractVolumeAttachmentStatus is the same as ExtractVolumeAttachment except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractVolumeAttachmentStatus(volumeAttachment *storagev1alpha1.VolumeAttachment, fieldManager string) (*VolumeAttachmentApplyConfiguration, error) {\n\treturn extractVolumeAttachment(volumeAttachment, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100024790,"name":"extractVolumeAttachment","signature":"func extractVolumeAttachment(volumeAttachment *storagev1alpha1.VolumeAttachment, fieldManager string, subresource string) (*VolumeAttachmentApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachment.go","code":"func extractVolumeAttachment(volumeAttachment *storagev1alpha1.VolumeAttachment, fieldManager string, subresource string) (*VolumeAttachmentApplyConfiguration, error) {\n\tb := \u0026VolumeAttachmentApplyConfiguration{}\n\terr := managedfields.ExtractInto(volumeAttachment, internal.Parser().Type(\"io.k8s.api.storage.v1alpha1.VolumeAttachment\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(volumeAttachment.Name)\n\n\tb.WithKind(\"VolumeAttachment\")\n\tb.WithAPIVersion(\"storage.k8s.io/v1alpha1\")\n\treturn b, nil\n}","line":{"from":71,"to":82}} {"id":100024791,"name":"WithKind","signature":"func (b *VolumeAttachmentApplyConfiguration) WithKind(value string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachment.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithKind(value string) *VolumeAttachmentApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100024792,"name":"WithAPIVersion","signature":"func (b *VolumeAttachmentApplyConfiguration) WithAPIVersion(value string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachment.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithAPIVersion(value string) *VolumeAttachmentApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100024793,"name":"WithName","signature":"func (b *VolumeAttachmentApplyConfiguration) WithName(value string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachment.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithName(value string) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":100,"to":107}} {"id":100024794,"name":"WithGenerateName","signature":"func (b *VolumeAttachmentApplyConfiguration) WithGenerateName(value string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachment.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithGenerateName(value string) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":109,"to":116}} {"id":100024795,"name":"WithNamespace","signature":"func (b *VolumeAttachmentApplyConfiguration) WithNamespace(value string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachment.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithNamespace(value string) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":118,"to":125}} {"id":100024796,"name":"WithUID","signature":"func (b *VolumeAttachmentApplyConfiguration) WithUID(value types.UID) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachment.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithUID(value types.UID) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":127,"to":134}} {"id":100024797,"name":"WithResourceVersion","signature":"func (b *VolumeAttachmentApplyConfiguration) WithResourceVersion(value string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachment.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithResourceVersion(value string) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":136,"to":143}} {"id":100024798,"name":"WithGeneration","signature":"func (b *VolumeAttachmentApplyConfiguration) WithGeneration(value int64) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachment.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithGeneration(value int64) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":145,"to":152}} {"id":100024799,"name":"WithCreationTimestamp","signature":"func (b *VolumeAttachmentApplyConfiguration) WithCreationTimestamp(value metav1.Time) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachment.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithCreationTimestamp(value metav1.Time) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":154,"to":161}} {"id":100024800,"name":"WithDeletionTimestamp","signature":"func (b *VolumeAttachmentApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachment.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":163,"to":170}} {"id":100024801,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *VolumeAttachmentApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachment.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":172,"to":179}} {"id":100024802,"name":"WithLabels","signature":"func (b *VolumeAttachmentApplyConfiguration) WithLabels(entries map[string]string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachment.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *VolumeAttachmentApplyConfiguration) WithLabels(entries map[string]string) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":181,"to":194}} {"id":100024803,"name":"WithAnnotations","signature":"func (b *VolumeAttachmentApplyConfiguration) WithAnnotations(entries map[string]string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachment.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *VolumeAttachmentApplyConfiguration) WithAnnotations(entries map[string]string) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100024804,"name":"WithOwnerReferences","signature":"func (b *VolumeAttachmentApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachment.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *VolumeAttachmentApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":211,"to":223}} {"id":100024805,"name":"WithFinalizers","signature":"func (b *VolumeAttachmentApplyConfiguration) WithFinalizers(values ...string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachment.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *VolumeAttachmentApplyConfiguration) WithFinalizers(values ...string) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":225,"to":234}} {"id":100024806,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *VolumeAttachmentApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachment.go","code":"func (b *VolumeAttachmentApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":236,"to":240}} {"id":100024807,"name":"WithSpec","signature":"func (b *VolumeAttachmentApplyConfiguration) WithSpec(value *VolumeAttachmentSpecApplyConfiguration) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachment.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithSpec(value *VolumeAttachmentSpecApplyConfiguration) *VolumeAttachmentApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":242,"to":248}} {"id":100024808,"name":"WithStatus","signature":"func (b *VolumeAttachmentApplyConfiguration) WithStatus(value *VolumeAttachmentStatusApplyConfiguration) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachment.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithStatus(value *VolumeAttachmentStatusApplyConfiguration) *VolumeAttachmentApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":250,"to":256}} {"id":100024809,"name":"VolumeAttachmentSource","signature":"func VolumeAttachmentSource() *VolumeAttachmentSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachmentsource.go","code":"// VolumeAttachmentSourceApplyConfiguration constructs an declarative configuration of the VolumeAttachmentSource type for use with\n// apply.\nfunc VolumeAttachmentSource() *VolumeAttachmentSourceApplyConfiguration {\n\treturn \u0026VolumeAttachmentSourceApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100024810,"name":"WithPersistentVolumeName","signature":"func (b *VolumeAttachmentSourceApplyConfiguration) WithPersistentVolumeName(value string) *VolumeAttachmentSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachmentsource.go","code":"// WithPersistentVolumeName sets the PersistentVolumeName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PersistentVolumeName field is set to the value of the last call.\nfunc (b *VolumeAttachmentSourceApplyConfiguration) WithPersistentVolumeName(value string) *VolumeAttachmentSourceApplyConfiguration {\n\tb.PersistentVolumeName = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100024811,"name":"WithInlineVolumeSpec","signature":"func (b *VolumeAttachmentSourceApplyConfiguration) WithInlineVolumeSpec(value *v1.PersistentVolumeSpecApplyConfiguration) *VolumeAttachmentSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachmentsource.go","code":"// WithInlineVolumeSpec sets the InlineVolumeSpec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the InlineVolumeSpec field is set to the value of the last call.\nfunc (b *VolumeAttachmentSourceApplyConfiguration) WithInlineVolumeSpec(value *v1.PersistentVolumeSpecApplyConfiguration) *VolumeAttachmentSourceApplyConfiguration {\n\tb.InlineVolumeSpec = value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100024812,"name":"VolumeAttachmentSpec","signature":"func VolumeAttachmentSpec() *VolumeAttachmentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachmentspec.go","code":"// VolumeAttachmentSpecApplyConfiguration constructs an declarative configuration of the VolumeAttachmentSpec type for use with\n// apply.\nfunc VolumeAttachmentSpec() *VolumeAttachmentSpecApplyConfiguration {\n\treturn \u0026VolumeAttachmentSpecApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100024813,"name":"WithAttacher","signature":"func (b *VolumeAttachmentSpecApplyConfiguration) WithAttacher(value string) *VolumeAttachmentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachmentspec.go","code":"// WithAttacher sets the Attacher field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Attacher field is set to the value of the last call.\nfunc (b *VolumeAttachmentSpecApplyConfiguration) WithAttacher(value string) *VolumeAttachmentSpecApplyConfiguration {\n\tb.Attacher = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100024814,"name":"WithSource","signature":"func (b *VolumeAttachmentSpecApplyConfiguration) WithSource(value *VolumeAttachmentSourceApplyConfiguration) *VolumeAttachmentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachmentspec.go","code":"// WithSource sets the Source field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Source field is set to the value of the last call.\nfunc (b *VolumeAttachmentSpecApplyConfiguration) WithSource(value *VolumeAttachmentSourceApplyConfiguration) *VolumeAttachmentSpecApplyConfiguration {\n\tb.Source = value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100024815,"name":"WithNodeName","signature":"func (b *VolumeAttachmentSpecApplyConfiguration) WithNodeName(value string) *VolumeAttachmentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachmentspec.go","code":"// WithNodeName sets the NodeName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NodeName field is set to the value of the last call.\nfunc (b *VolumeAttachmentSpecApplyConfiguration) WithNodeName(value string) *VolumeAttachmentSpecApplyConfiguration {\n\tb.NodeName = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100024816,"name":"VolumeAttachmentStatus","signature":"func VolumeAttachmentStatus() *VolumeAttachmentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachmentstatus.go","code":"// VolumeAttachmentStatusApplyConfiguration constructs an declarative configuration of the VolumeAttachmentStatus type for use with\n// apply.\nfunc VolumeAttachmentStatus() *VolumeAttachmentStatusApplyConfiguration {\n\treturn \u0026VolumeAttachmentStatusApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100024817,"name":"WithAttached","signature":"func (b *VolumeAttachmentStatusApplyConfiguration) WithAttached(value bool) *VolumeAttachmentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachmentstatus.go","code":"// WithAttached sets the Attached field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Attached field is set to the value of the last call.\nfunc (b *VolumeAttachmentStatusApplyConfiguration) WithAttached(value bool) *VolumeAttachmentStatusApplyConfiguration {\n\tb.Attached = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100024818,"name":"WithAttachmentMetadata","signature":"func (b *VolumeAttachmentStatusApplyConfiguration) WithAttachmentMetadata(entries map[string]string) *VolumeAttachmentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachmentstatus.go","code":"// WithAttachmentMetadata puts the entries into the AttachmentMetadata field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the AttachmentMetadata field,\n// overwriting an existing map entries in AttachmentMetadata field with the same key.\nfunc (b *VolumeAttachmentStatusApplyConfiguration) WithAttachmentMetadata(entries map[string]string) *VolumeAttachmentStatusApplyConfiguration {\n\tif b.AttachmentMetadata == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.AttachmentMetadata = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.AttachmentMetadata[k] = v\n\t}\n\treturn b\n}","line":{"from":44,"to":56}} {"id":100024819,"name":"WithAttachError","signature":"func (b *VolumeAttachmentStatusApplyConfiguration) WithAttachError(value *VolumeErrorApplyConfiguration) *VolumeAttachmentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachmentstatus.go","code":"// WithAttachError sets the AttachError field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AttachError field is set to the value of the last call.\nfunc (b *VolumeAttachmentStatusApplyConfiguration) WithAttachError(value *VolumeErrorApplyConfiguration) *VolumeAttachmentStatusApplyConfiguration {\n\tb.AttachError = value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100024820,"name":"WithDetachError","signature":"func (b *VolumeAttachmentStatusApplyConfiguration) WithDetachError(value *VolumeErrorApplyConfiguration) *VolumeAttachmentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeattachmentstatus.go","code":"// WithDetachError sets the DetachError field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DetachError field is set to the value of the last call.\nfunc (b *VolumeAttachmentStatusApplyConfiguration) WithDetachError(value *VolumeErrorApplyConfiguration) *VolumeAttachmentStatusApplyConfiguration {\n\tb.DetachError = value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100024821,"name":"VolumeError","signature":"func VolumeError() *VolumeErrorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeerror.go","code":"// VolumeErrorApplyConfiguration constructs an declarative configuration of the VolumeError type for use with\n// apply.\nfunc VolumeError() *VolumeErrorApplyConfiguration {\n\treturn \u0026VolumeErrorApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100024822,"name":"WithTime","signature":"func (b *VolumeErrorApplyConfiguration) WithTime(value v1.Time) *VolumeErrorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeerror.go","code":"// WithTime sets the Time field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Time field is set to the value of the last call.\nfunc (b *VolumeErrorApplyConfiguration) WithTime(value v1.Time) *VolumeErrorApplyConfiguration {\n\tb.Time = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100024823,"name":"WithMessage","signature":"func (b *VolumeErrorApplyConfiguration) WithMessage(value string) *VolumeErrorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1alpha1/volumeerror.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *VolumeErrorApplyConfiguration) WithMessage(value string) *VolumeErrorApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100024824,"name":"CSIDriver","signature":"func CSIDriver(name string) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriver.go","code":"// CSIDriver constructs an declarative configuration of the CSIDriver type for use with\n// apply.\nfunc CSIDriver(name string) *CSIDriverApplyConfiguration {\n\tb := \u0026CSIDriverApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"CSIDriver\")\n\tb.WithAPIVersion(\"storage.k8s.io/v1beta1\")\n\treturn b\n}","line":{"from":38,"to":46}} {"id":100024825,"name":"ExtractCSIDriver","signature":"func ExtractCSIDriver(cSIDriver *storagev1beta1.CSIDriver, fieldManager string) (*CSIDriverApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriver.go","code":"// ExtractCSIDriver extracts the applied configuration owned by fieldManager from\n// cSIDriver. If no managedFields are found in cSIDriver for fieldManager, a\n// CSIDriverApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// cSIDriver must be a unmodified CSIDriver API object that was retrieved from the Kubernetes API.\n// ExtractCSIDriver provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractCSIDriver(cSIDriver *storagev1beta1.CSIDriver, fieldManager string) (*CSIDriverApplyConfiguration, error) {\n\treturn extractCSIDriver(cSIDriver, fieldManager, \"\")\n}","line":{"from":48,"to":61}} {"id":100024826,"name":"ExtractCSIDriverStatus","signature":"func ExtractCSIDriverStatus(cSIDriver *storagev1beta1.CSIDriver, fieldManager string) (*CSIDriverApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriver.go","code":"// ExtractCSIDriverStatus is the same as ExtractCSIDriver except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractCSIDriverStatus(cSIDriver *storagev1beta1.CSIDriver, fieldManager string) (*CSIDriverApplyConfiguration, error) {\n\treturn extractCSIDriver(cSIDriver, fieldManager, \"status\")\n}","line":{"from":63,"to":68}} {"id":100024827,"name":"extractCSIDriver","signature":"func extractCSIDriver(cSIDriver *storagev1beta1.CSIDriver, fieldManager string, subresource string) (*CSIDriverApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriver.go","code":"func extractCSIDriver(cSIDriver *storagev1beta1.CSIDriver, fieldManager string, subresource string) (*CSIDriverApplyConfiguration, error) {\n\tb := \u0026CSIDriverApplyConfiguration{}\n\terr := managedfields.ExtractInto(cSIDriver, internal.Parser().Type(\"io.k8s.api.storage.v1beta1.CSIDriver\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(cSIDriver.Name)\n\n\tb.WithKind(\"CSIDriver\")\n\tb.WithAPIVersion(\"storage.k8s.io/v1beta1\")\n\treturn b, nil\n}","line":{"from":70,"to":81}} {"id":100024828,"name":"WithKind","signature":"func (b *CSIDriverApplyConfiguration) WithKind(value string) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriver.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *CSIDriverApplyConfiguration) WithKind(value string) *CSIDriverApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100024829,"name":"WithAPIVersion","signature":"func (b *CSIDriverApplyConfiguration) WithAPIVersion(value string) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriver.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *CSIDriverApplyConfiguration) WithAPIVersion(value string) *CSIDriverApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":91,"to":97}} {"id":100024830,"name":"WithName","signature":"func (b *CSIDriverApplyConfiguration) WithName(value string) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriver.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *CSIDriverApplyConfiguration) WithName(value string) *CSIDriverApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":99,"to":106}} {"id":100024831,"name":"WithGenerateName","signature":"func (b *CSIDriverApplyConfiguration) WithGenerateName(value string) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriver.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *CSIDriverApplyConfiguration) WithGenerateName(value string) *CSIDriverApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":108,"to":115}} {"id":100024832,"name":"WithNamespace","signature":"func (b *CSIDriverApplyConfiguration) WithNamespace(value string) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriver.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *CSIDriverApplyConfiguration) WithNamespace(value string) *CSIDriverApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":117,"to":124}} {"id":100024833,"name":"WithUID","signature":"func (b *CSIDriverApplyConfiguration) WithUID(value types.UID) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriver.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *CSIDriverApplyConfiguration) WithUID(value types.UID) *CSIDriverApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":126,"to":133}} {"id":100024834,"name":"WithResourceVersion","signature":"func (b *CSIDriverApplyConfiguration) WithResourceVersion(value string) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriver.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *CSIDriverApplyConfiguration) WithResourceVersion(value string) *CSIDriverApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":135,"to":142}} {"id":100024835,"name":"WithGeneration","signature":"func (b *CSIDriverApplyConfiguration) WithGeneration(value int64) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriver.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *CSIDriverApplyConfiguration) WithGeneration(value int64) *CSIDriverApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":144,"to":151}} {"id":100024836,"name":"WithCreationTimestamp","signature":"func (b *CSIDriverApplyConfiguration) WithCreationTimestamp(value metav1.Time) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriver.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *CSIDriverApplyConfiguration) WithCreationTimestamp(value metav1.Time) *CSIDriverApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":153,"to":160}} {"id":100024837,"name":"WithDeletionTimestamp","signature":"func (b *CSIDriverApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriver.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *CSIDriverApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *CSIDriverApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":162,"to":169}} {"id":100024838,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *CSIDriverApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriver.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *CSIDriverApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *CSIDriverApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":171,"to":178}} {"id":100024839,"name":"WithLabels","signature":"func (b *CSIDriverApplyConfiguration) WithLabels(entries map[string]string) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriver.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *CSIDriverApplyConfiguration) WithLabels(entries map[string]string) *CSIDriverApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":180,"to":193}} {"id":100024840,"name":"WithAnnotations","signature":"func (b *CSIDriverApplyConfiguration) WithAnnotations(entries map[string]string) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriver.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *CSIDriverApplyConfiguration) WithAnnotations(entries map[string]string) *CSIDriverApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":195,"to":208}} {"id":100024841,"name":"WithOwnerReferences","signature":"func (b *CSIDriverApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriver.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *CSIDriverApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *CSIDriverApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":210,"to":222}} {"id":100024842,"name":"WithFinalizers","signature":"func (b *CSIDriverApplyConfiguration) WithFinalizers(values ...string) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriver.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *CSIDriverApplyConfiguration) WithFinalizers(values ...string) *CSIDriverApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":224,"to":233}} {"id":100024843,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *CSIDriverApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriver.go","code":"func (b *CSIDriverApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":235,"to":239}} {"id":100024844,"name":"WithSpec","signature":"func (b *CSIDriverApplyConfiguration) WithSpec(value *CSIDriverSpecApplyConfiguration) *CSIDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriver.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *CSIDriverApplyConfiguration) WithSpec(value *CSIDriverSpecApplyConfiguration) *CSIDriverApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":241,"to":247}} {"id":100024845,"name":"CSIDriverSpec","signature":"func CSIDriverSpec() *CSIDriverSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriverspec.go","code":"// CSIDriverSpecApplyConfiguration constructs an declarative configuration of the CSIDriverSpec type for use with\n// apply.\nfunc CSIDriverSpec() *CSIDriverSpecApplyConfiguration {\n\treturn \u0026CSIDriverSpecApplyConfiguration{}\n}","line":{"from":38,"to":42}} {"id":100024846,"name":"WithAttachRequired","signature":"func (b *CSIDriverSpecApplyConfiguration) WithAttachRequired(value bool) *CSIDriverSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriverspec.go","code":"// WithAttachRequired sets the AttachRequired field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AttachRequired field is set to the value of the last call.\nfunc (b *CSIDriverSpecApplyConfiguration) WithAttachRequired(value bool) *CSIDriverSpecApplyConfiguration {\n\tb.AttachRequired = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100024847,"name":"WithPodInfoOnMount","signature":"func (b *CSIDriverSpecApplyConfiguration) WithPodInfoOnMount(value bool) *CSIDriverSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriverspec.go","code":"// WithPodInfoOnMount sets the PodInfoOnMount field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PodInfoOnMount field is set to the value of the last call.\nfunc (b *CSIDriverSpecApplyConfiguration) WithPodInfoOnMount(value bool) *CSIDriverSpecApplyConfiguration {\n\tb.PodInfoOnMount = \u0026value\n\treturn b\n}","line":{"from":52,"to":58}} {"id":100024848,"name":"WithVolumeLifecycleModes","signature":"func (b *CSIDriverSpecApplyConfiguration) WithVolumeLifecycleModes(values ...v1beta1.VolumeLifecycleMode) *CSIDriverSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriverspec.go","code":"// WithVolumeLifecycleModes adds the given value to the VolumeLifecycleModes field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the VolumeLifecycleModes field.\nfunc (b *CSIDriverSpecApplyConfiguration) WithVolumeLifecycleModes(values ...v1beta1.VolumeLifecycleMode) *CSIDriverSpecApplyConfiguration {\n\tfor i := range values {\n\t\tb.VolumeLifecycleModes = append(b.VolumeLifecycleModes, values[i])\n\t}\n\treturn b\n}","line":{"from":60,"to":68}} {"id":100024849,"name":"WithStorageCapacity","signature":"func (b *CSIDriverSpecApplyConfiguration) WithStorageCapacity(value bool) *CSIDriverSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriverspec.go","code":"// WithStorageCapacity sets the StorageCapacity field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StorageCapacity field is set to the value of the last call.\nfunc (b *CSIDriverSpecApplyConfiguration) WithStorageCapacity(value bool) *CSIDriverSpecApplyConfiguration {\n\tb.StorageCapacity = \u0026value\n\treturn b\n}","line":{"from":70,"to":76}} {"id":100024850,"name":"WithFSGroupPolicy","signature":"func (b *CSIDriverSpecApplyConfiguration) WithFSGroupPolicy(value v1beta1.FSGroupPolicy) *CSIDriverSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriverspec.go","code":"// WithFSGroupPolicy sets the FSGroupPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the FSGroupPolicy field is set to the value of the last call.\nfunc (b *CSIDriverSpecApplyConfiguration) WithFSGroupPolicy(value v1beta1.FSGroupPolicy) *CSIDriverSpecApplyConfiguration {\n\tb.FSGroupPolicy = \u0026value\n\treturn b\n}","line":{"from":78,"to":84}} {"id":100024851,"name":"WithTokenRequests","signature":"func (b *CSIDriverSpecApplyConfiguration) WithTokenRequests(values ...*TokenRequestApplyConfiguration) *CSIDriverSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriverspec.go","code":"// WithTokenRequests adds the given value to the TokenRequests field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the TokenRequests field.\nfunc (b *CSIDriverSpecApplyConfiguration) WithTokenRequests(values ...*TokenRequestApplyConfiguration) *CSIDriverSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithTokenRequests\")\n\t\t}\n\t\tb.TokenRequests = append(b.TokenRequests, *values[i])\n\t}\n\treturn b\n}","line":{"from":86,"to":97}} {"id":100024852,"name":"WithRequiresRepublish","signature":"func (b *CSIDriverSpecApplyConfiguration) WithRequiresRepublish(value bool) *CSIDriverSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriverspec.go","code":"// WithRequiresRepublish sets the RequiresRepublish field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the RequiresRepublish field is set to the value of the last call.\nfunc (b *CSIDriverSpecApplyConfiguration) WithRequiresRepublish(value bool) *CSIDriverSpecApplyConfiguration {\n\tb.RequiresRepublish = \u0026value\n\treturn b\n}","line":{"from":99,"to":105}} {"id":100024853,"name":"WithSELinuxMount","signature":"func (b *CSIDriverSpecApplyConfiguration) WithSELinuxMount(value bool) *CSIDriverSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csidriverspec.go","code":"// WithSELinuxMount sets the SELinuxMount field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the SELinuxMount field is set to the value of the last call.\nfunc (b *CSIDriverSpecApplyConfiguration) WithSELinuxMount(value bool) *CSIDriverSpecApplyConfiguration {\n\tb.SELinuxMount = \u0026value\n\treturn b\n}","line":{"from":107,"to":113}} {"id":100024854,"name":"CSINode","signature":"func CSINode(name string) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinode.go","code":"// CSINode constructs an declarative configuration of the CSINode type for use with\n// apply.\nfunc CSINode(name string) *CSINodeApplyConfiguration {\n\tb := \u0026CSINodeApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"CSINode\")\n\tb.WithAPIVersion(\"storage.k8s.io/v1beta1\")\n\treturn b\n}","line":{"from":38,"to":46}} {"id":100024855,"name":"ExtractCSINode","signature":"func ExtractCSINode(cSINode *storagev1beta1.CSINode, fieldManager string) (*CSINodeApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinode.go","code":"// ExtractCSINode extracts the applied configuration owned by fieldManager from\n// cSINode. If no managedFields are found in cSINode for fieldManager, a\n// CSINodeApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// cSINode must be a unmodified CSINode API object that was retrieved from the Kubernetes API.\n// ExtractCSINode provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractCSINode(cSINode *storagev1beta1.CSINode, fieldManager string) (*CSINodeApplyConfiguration, error) {\n\treturn extractCSINode(cSINode, fieldManager, \"\")\n}","line":{"from":48,"to":61}} {"id":100024856,"name":"ExtractCSINodeStatus","signature":"func ExtractCSINodeStatus(cSINode *storagev1beta1.CSINode, fieldManager string) (*CSINodeApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinode.go","code":"// ExtractCSINodeStatus is the same as ExtractCSINode except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractCSINodeStatus(cSINode *storagev1beta1.CSINode, fieldManager string) (*CSINodeApplyConfiguration, error) {\n\treturn extractCSINode(cSINode, fieldManager, \"status\")\n}","line":{"from":63,"to":68}} {"id":100024857,"name":"extractCSINode","signature":"func extractCSINode(cSINode *storagev1beta1.CSINode, fieldManager string, subresource string) (*CSINodeApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinode.go","code":"func extractCSINode(cSINode *storagev1beta1.CSINode, fieldManager string, subresource string) (*CSINodeApplyConfiguration, error) {\n\tb := \u0026CSINodeApplyConfiguration{}\n\terr := managedfields.ExtractInto(cSINode, internal.Parser().Type(\"io.k8s.api.storage.v1beta1.CSINode\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(cSINode.Name)\n\n\tb.WithKind(\"CSINode\")\n\tb.WithAPIVersion(\"storage.k8s.io/v1beta1\")\n\treturn b, nil\n}","line":{"from":70,"to":81}} {"id":100024858,"name":"WithKind","signature":"func (b *CSINodeApplyConfiguration) WithKind(value string) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinode.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *CSINodeApplyConfiguration) WithKind(value string) *CSINodeApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":83,"to":89}} {"id":100024859,"name":"WithAPIVersion","signature":"func (b *CSINodeApplyConfiguration) WithAPIVersion(value string) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinode.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *CSINodeApplyConfiguration) WithAPIVersion(value string) *CSINodeApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":91,"to":97}} {"id":100024860,"name":"WithName","signature":"func (b *CSINodeApplyConfiguration) WithName(value string) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinode.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *CSINodeApplyConfiguration) WithName(value string) *CSINodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":99,"to":106}} {"id":100024861,"name":"WithGenerateName","signature":"func (b *CSINodeApplyConfiguration) WithGenerateName(value string) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinode.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *CSINodeApplyConfiguration) WithGenerateName(value string) *CSINodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":108,"to":115}} {"id":100024862,"name":"WithNamespace","signature":"func (b *CSINodeApplyConfiguration) WithNamespace(value string) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinode.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *CSINodeApplyConfiguration) WithNamespace(value string) *CSINodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":117,"to":124}} {"id":100024863,"name":"WithUID","signature":"func (b *CSINodeApplyConfiguration) WithUID(value types.UID) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinode.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *CSINodeApplyConfiguration) WithUID(value types.UID) *CSINodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":126,"to":133}} {"id":100024864,"name":"WithResourceVersion","signature":"func (b *CSINodeApplyConfiguration) WithResourceVersion(value string) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinode.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *CSINodeApplyConfiguration) WithResourceVersion(value string) *CSINodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":135,"to":142}} {"id":100024865,"name":"WithGeneration","signature":"func (b *CSINodeApplyConfiguration) WithGeneration(value int64) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinode.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *CSINodeApplyConfiguration) WithGeneration(value int64) *CSINodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":144,"to":151}} {"id":100024866,"name":"WithCreationTimestamp","signature":"func (b *CSINodeApplyConfiguration) WithCreationTimestamp(value metav1.Time) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinode.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *CSINodeApplyConfiguration) WithCreationTimestamp(value metav1.Time) *CSINodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":153,"to":160}} {"id":100024867,"name":"WithDeletionTimestamp","signature":"func (b *CSINodeApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinode.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *CSINodeApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *CSINodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":162,"to":169}} {"id":100024868,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *CSINodeApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinode.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *CSINodeApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *CSINodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":171,"to":178}} {"id":100024869,"name":"WithLabels","signature":"func (b *CSINodeApplyConfiguration) WithLabels(entries map[string]string) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinode.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *CSINodeApplyConfiguration) WithLabels(entries map[string]string) *CSINodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":180,"to":193}} {"id":100024870,"name":"WithAnnotations","signature":"func (b *CSINodeApplyConfiguration) WithAnnotations(entries map[string]string) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinode.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *CSINodeApplyConfiguration) WithAnnotations(entries map[string]string) *CSINodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":195,"to":208}} {"id":100024871,"name":"WithOwnerReferences","signature":"func (b *CSINodeApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinode.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *CSINodeApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *CSINodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":210,"to":222}} {"id":100024872,"name":"WithFinalizers","signature":"func (b *CSINodeApplyConfiguration) WithFinalizers(values ...string) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinode.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *CSINodeApplyConfiguration) WithFinalizers(values ...string) *CSINodeApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":224,"to":233}} {"id":100024873,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *CSINodeApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinode.go","code":"func (b *CSINodeApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":235,"to":239}} {"id":100024874,"name":"WithSpec","signature":"func (b *CSINodeApplyConfiguration) WithSpec(value *CSINodeSpecApplyConfiguration) *CSINodeApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinode.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *CSINodeApplyConfiguration) WithSpec(value *CSINodeSpecApplyConfiguration) *CSINodeApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":241,"to":247}} {"id":100024875,"name":"CSINodeDriver","signature":"func CSINodeDriver() *CSINodeDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinodedriver.go","code":"// CSINodeDriverApplyConfiguration constructs an declarative configuration of the CSINodeDriver type for use with\n// apply.\nfunc CSINodeDriver() *CSINodeDriverApplyConfiguration {\n\treturn \u0026CSINodeDriverApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100024876,"name":"WithName","signature":"func (b *CSINodeDriverApplyConfiguration) WithName(value string) *CSINodeDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinodedriver.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *CSINodeDriverApplyConfiguration) WithName(value string) *CSINodeDriverApplyConfiguration {\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100024877,"name":"WithNodeID","signature":"func (b *CSINodeDriverApplyConfiguration) WithNodeID(value string) *CSINodeDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinodedriver.go","code":"// WithNodeID sets the NodeID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NodeID field is set to the value of the last call.\nfunc (b *CSINodeDriverApplyConfiguration) WithNodeID(value string) *CSINodeDriverApplyConfiguration {\n\tb.NodeID = \u0026value\n\treturn b\n}","line":{"from":44,"to":50}} {"id":100024878,"name":"WithTopologyKeys","signature":"func (b *CSINodeDriverApplyConfiguration) WithTopologyKeys(values ...string) *CSINodeDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinodedriver.go","code":"// WithTopologyKeys adds the given value to the TopologyKeys field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the TopologyKeys field.\nfunc (b *CSINodeDriverApplyConfiguration) WithTopologyKeys(values ...string) *CSINodeDriverApplyConfiguration {\n\tfor i := range values {\n\t\tb.TopologyKeys = append(b.TopologyKeys, values[i])\n\t}\n\treturn b\n}","line":{"from":52,"to":60}} {"id":100024879,"name":"WithAllocatable","signature":"func (b *CSINodeDriverApplyConfiguration) WithAllocatable(value *VolumeNodeResourcesApplyConfiguration) *CSINodeDriverApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinodedriver.go","code":"// WithAllocatable sets the Allocatable field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Allocatable field is set to the value of the last call.\nfunc (b *CSINodeDriverApplyConfiguration) WithAllocatable(value *VolumeNodeResourcesApplyConfiguration) *CSINodeDriverApplyConfiguration {\n\tb.Allocatable = value\n\treturn b\n}","line":{"from":62,"to":68}} {"id":100024880,"name":"CSINodeSpec","signature":"func CSINodeSpec() *CSINodeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinodespec.go","code":"// CSINodeSpecApplyConfiguration constructs an declarative configuration of the CSINodeSpec type for use with\n// apply.\nfunc CSINodeSpec() *CSINodeSpecApplyConfiguration {\n\treturn \u0026CSINodeSpecApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100024881,"name":"WithDrivers","signature":"func (b *CSINodeSpecApplyConfiguration) WithDrivers(values ...*CSINodeDriverApplyConfiguration) *CSINodeSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csinodespec.go","code":"// WithDrivers adds the given value to the Drivers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Drivers field.\nfunc (b *CSINodeSpecApplyConfiguration) WithDrivers(values ...*CSINodeDriverApplyConfiguration) *CSINodeSpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithDrivers\")\n\t\t}\n\t\tb.Drivers = append(b.Drivers, *values[i])\n\t}\n\treturn b\n}","line":{"from":33,"to":44}} {"id":100024882,"name":"CSIStorageCapacity","signature":"func CSIStorageCapacity(name, namespace string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go","code":"// CSIStorageCapacity constructs an declarative configuration of the CSIStorageCapacity type for use with\n// apply.\nfunc CSIStorageCapacity(name, namespace string) *CSIStorageCapacityApplyConfiguration {\n\tb := \u0026CSIStorageCapacityApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithNamespace(namespace)\n\tb.WithKind(\"CSIStorageCapacity\")\n\tb.WithAPIVersion(\"storage.k8s.io/v1beta1\")\n\treturn b\n}","line":{"from":42,"to":51}} {"id":100024883,"name":"ExtractCSIStorageCapacity","signature":"func ExtractCSIStorageCapacity(cSIStorageCapacity *v1beta1.CSIStorageCapacity, fieldManager string) (*CSIStorageCapacityApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go","code":"// ExtractCSIStorageCapacity extracts the applied configuration owned by fieldManager from\n// cSIStorageCapacity. If no managedFields are found in cSIStorageCapacity for fieldManager, a\n// CSIStorageCapacityApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// cSIStorageCapacity must be a unmodified CSIStorageCapacity API object that was retrieved from the Kubernetes API.\n// ExtractCSIStorageCapacity provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractCSIStorageCapacity(cSIStorageCapacity *v1beta1.CSIStorageCapacity, fieldManager string) (*CSIStorageCapacityApplyConfiguration, error) {\n\treturn extractCSIStorageCapacity(cSIStorageCapacity, fieldManager, \"\")\n}","line":{"from":53,"to":66}} {"id":100024884,"name":"ExtractCSIStorageCapacityStatus","signature":"func ExtractCSIStorageCapacityStatus(cSIStorageCapacity *v1beta1.CSIStorageCapacity, fieldManager string) (*CSIStorageCapacityApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go","code":"// ExtractCSIStorageCapacityStatus is the same as ExtractCSIStorageCapacity except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractCSIStorageCapacityStatus(cSIStorageCapacity *v1beta1.CSIStorageCapacity, fieldManager string) (*CSIStorageCapacityApplyConfiguration, error) {\n\treturn extractCSIStorageCapacity(cSIStorageCapacity, fieldManager, \"status\")\n}","line":{"from":68,"to":73}} {"id":100024885,"name":"extractCSIStorageCapacity","signature":"func extractCSIStorageCapacity(cSIStorageCapacity *v1beta1.CSIStorageCapacity, fieldManager string, subresource string) (*CSIStorageCapacityApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go","code":"func extractCSIStorageCapacity(cSIStorageCapacity *v1beta1.CSIStorageCapacity, fieldManager string, subresource string) (*CSIStorageCapacityApplyConfiguration, error) {\n\tb := \u0026CSIStorageCapacityApplyConfiguration{}\n\terr := managedfields.ExtractInto(cSIStorageCapacity, internal.Parser().Type(\"io.k8s.api.storage.v1beta1.CSIStorageCapacity\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(cSIStorageCapacity.Name)\n\tb.WithNamespace(cSIStorageCapacity.Namespace)\n\n\tb.WithKind(\"CSIStorageCapacity\")\n\tb.WithAPIVersion(\"storage.k8s.io/v1beta1\")\n\treturn b, nil\n}","line":{"from":75,"to":87}} {"id":100024886,"name":"WithKind","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithKind(value string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithKind(value string) *CSIStorageCapacityApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":89,"to":95}} {"id":100024887,"name":"WithAPIVersion","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithAPIVersion(value string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithAPIVersion(value string) *CSIStorageCapacityApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":97,"to":103}} {"id":100024888,"name":"WithName","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithName(value string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithName(value string) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":105,"to":112}} {"id":100024889,"name":"WithGenerateName","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithGenerateName(value string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithGenerateName(value string) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":114,"to":121}} {"id":100024890,"name":"WithNamespace","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithNamespace(value string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithNamespace(value string) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":123,"to":130}} {"id":100024891,"name":"WithUID","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithUID(value types.UID) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithUID(value types.UID) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":132,"to":139}} {"id":100024892,"name":"WithResourceVersion","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithResourceVersion(value string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithResourceVersion(value string) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":141,"to":148}} {"id":100024893,"name":"WithGeneration","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithGeneration(value int64) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithGeneration(value int64) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":150,"to":157}} {"id":100024894,"name":"WithCreationTimestamp","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithCreationTimestamp(value metav1.Time) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithCreationTimestamp(value metav1.Time) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":159,"to":166}} {"id":100024895,"name":"WithDeletionTimestamp","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":168,"to":175}} {"id":100024896,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":177,"to":184}} {"id":100024897,"name":"WithLabels","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithLabels(entries map[string]string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithLabels(entries map[string]string) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":186,"to":199}} {"id":100024898,"name":"WithAnnotations","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithAnnotations(entries map[string]string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithAnnotations(entries map[string]string) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":201,"to":214}} {"id":100024899,"name":"WithOwnerReferences","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":216,"to":228}} {"id":100024900,"name":"WithFinalizers","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithFinalizers(values ...string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithFinalizers(values ...string) *CSIStorageCapacityApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":230,"to":239}} {"id":100024901,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *CSIStorageCapacityApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go","code":"func (b *CSIStorageCapacityApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":241,"to":245}} {"id":100024902,"name":"WithNodeTopology","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithNodeTopology(value *v1.LabelSelectorApplyConfiguration) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go","code":"// WithNodeTopology sets the NodeTopology field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NodeTopology field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithNodeTopology(value *v1.LabelSelectorApplyConfiguration) *CSIStorageCapacityApplyConfiguration {\n\tb.NodeTopology = value\n\treturn b\n}","line":{"from":247,"to":253}} {"id":100024903,"name":"WithStorageClassName","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithStorageClassName(value string) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go","code":"// WithStorageClassName sets the StorageClassName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the StorageClassName field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithStorageClassName(value string) *CSIStorageCapacityApplyConfiguration {\n\tb.StorageClassName = \u0026value\n\treturn b\n}","line":{"from":255,"to":261}} {"id":100024904,"name":"WithCapacity","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithCapacity(value resource.Quantity) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go","code":"// WithCapacity sets the Capacity field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Capacity field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithCapacity(value resource.Quantity) *CSIStorageCapacityApplyConfiguration {\n\tb.Capacity = \u0026value\n\treturn b\n}","line":{"from":263,"to":269}} {"id":100024905,"name":"WithMaximumVolumeSize","signature":"func (b *CSIStorageCapacityApplyConfiguration) WithMaximumVolumeSize(value resource.Quantity) *CSIStorageCapacityApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/csistoragecapacity.go","code":"// WithMaximumVolumeSize sets the MaximumVolumeSize field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the MaximumVolumeSize field is set to the value of the last call.\nfunc (b *CSIStorageCapacityApplyConfiguration) WithMaximumVolumeSize(value resource.Quantity) *CSIStorageCapacityApplyConfiguration {\n\tb.MaximumVolumeSize = \u0026value\n\treturn b\n}","line":{"from":271,"to":277}} {"id":100024906,"name":"StorageClass","signature":"func StorageClass(name string) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"// StorageClass constructs an declarative configuration of the StorageClass type for use with\n// apply.\nfunc StorageClass(name string) *StorageClassApplyConfiguration {\n\tb := \u0026StorageClassApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"StorageClass\")\n\tb.WithAPIVersion(\"storage.k8s.io/v1beta1\")\n\treturn b\n}","line":{"from":46,"to":54}} {"id":100024907,"name":"ExtractStorageClass","signature":"func ExtractStorageClass(storageClass *v1beta1.StorageClass, fieldManager string) (*StorageClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"// ExtractStorageClass extracts the applied configuration owned by fieldManager from\n// storageClass. If no managedFields are found in storageClass for fieldManager, a\n// StorageClassApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// storageClass must be a unmodified StorageClass API object that was retrieved from the Kubernetes API.\n// ExtractStorageClass provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractStorageClass(storageClass *v1beta1.StorageClass, fieldManager string) (*StorageClassApplyConfiguration, error) {\n\treturn extractStorageClass(storageClass, fieldManager, \"\")\n}","line":{"from":56,"to":69}} {"id":100024908,"name":"ExtractStorageClassStatus","signature":"func ExtractStorageClassStatus(storageClass *v1beta1.StorageClass, fieldManager string) (*StorageClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"// ExtractStorageClassStatus is the same as ExtractStorageClass except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractStorageClassStatus(storageClass *v1beta1.StorageClass, fieldManager string) (*StorageClassApplyConfiguration, error) {\n\treturn extractStorageClass(storageClass, fieldManager, \"status\")\n}","line":{"from":71,"to":76}} {"id":100024909,"name":"extractStorageClass","signature":"func extractStorageClass(storageClass *v1beta1.StorageClass, fieldManager string, subresource string) (*StorageClassApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"func extractStorageClass(storageClass *v1beta1.StorageClass, fieldManager string, subresource string) (*StorageClassApplyConfiguration, error) {\n\tb := \u0026StorageClassApplyConfiguration{}\n\terr := managedfields.ExtractInto(storageClass, internal.Parser().Type(\"io.k8s.api.storage.v1beta1.StorageClass\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(storageClass.Name)\n\n\tb.WithKind(\"StorageClass\")\n\tb.WithAPIVersion(\"storage.k8s.io/v1beta1\")\n\treturn b, nil\n}","line":{"from":78,"to":89}} {"id":100024910,"name":"WithKind","signature":"func (b *StorageClassApplyConfiguration) WithKind(value string) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithKind(value string) *StorageClassApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":91,"to":97}} {"id":100024911,"name":"WithAPIVersion","signature":"func (b *StorageClassApplyConfiguration) WithAPIVersion(value string) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithAPIVersion(value string) *StorageClassApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":99,"to":105}} {"id":100024912,"name":"WithName","signature":"func (b *StorageClassApplyConfiguration) WithName(value string) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithName(value string) *StorageClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":107,"to":114}} {"id":100024913,"name":"WithGenerateName","signature":"func (b *StorageClassApplyConfiguration) WithGenerateName(value string) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithGenerateName(value string) *StorageClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":116,"to":123}} {"id":100024914,"name":"WithNamespace","signature":"func (b *StorageClassApplyConfiguration) WithNamespace(value string) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithNamespace(value string) *StorageClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":125,"to":132}} {"id":100024915,"name":"WithUID","signature":"func (b *StorageClassApplyConfiguration) WithUID(value types.UID) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithUID(value types.UID) *StorageClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":134,"to":141}} {"id":100024916,"name":"WithResourceVersion","signature":"func (b *StorageClassApplyConfiguration) WithResourceVersion(value string) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithResourceVersion(value string) *StorageClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":143,"to":150}} {"id":100024917,"name":"WithGeneration","signature":"func (b *StorageClassApplyConfiguration) WithGeneration(value int64) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithGeneration(value int64) *StorageClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":152,"to":159}} {"id":100024918,"name":"WithCreationTimestamp","signature":"func (b *StorageClassApplyConfiguration) WithCreationTimestamp(value metav1.Time) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithCreationTimestamp(value metav1.Time) *StorageClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":161,"to":168}} {"id":100024919,"name":"WithDeletionTimestamp","signature":"func (b *StorageClassApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *StorageClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":170,"to":177}} {"id":100024920,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *StorageClassApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *StorageClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":179,"to":186}} {"id":100024921,"name":"WithLabels","signature":"func (b *StorageClassApplyConfiguration) WithLabels(entries map[string]string) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *StorageClassApplyConfiguration) WithLabels(entries map[string]string) *StorageClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":188,"to":201}} {"id":100024922,"name":"WithAnnotations","signature":"func (b *StorageClassApplyConfiguration) WithAnnotations(entries map[string]string) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *StorageClassApplyConfiguration) WithAnnotations(entries map[string]string) *StorageClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":203,"to":216}} {"id":100024923,"name":"WithOwnerReferences","signature":"func (b *StorageClassApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *StorageClassApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *StorageClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":218,"to":230}} {"id":100024924,"name":"WithFinalizers","signature":"func (b *StorageClassApplyConfiguration) WithFinalizers(values ...string) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *StorageClassApplyConfiguration) WithFinalizers(values ...string) *StorageClassApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":232,"to":241}} {"id":100024925,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *StorageClassApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"func (b *StorageClassApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":243,"to":247}} {"id":100024926,"name":"WithProvisioner","signature":"func (b *StorageClassApplyConfiguration) WithProvisioner(value string) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"// WithProvisioner sets the Provisioner field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Provisioner field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithProvisioner(value string) *StorageClassApplyConfiguration {\n\tb.Provisioner = \u0026value\n\treturn b\n}","line":{"from":249,"to":255}} {"id":100024927,"name":"WithParameters","signature":"func (b *StorageClassApplyConfiguration) WithParameters(entries map[string]string) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"// WithParameters puts the entries into the Parameters field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Parameters field,\n// overwriting an existing map entries in Parameters field with the same key.\nfunc (b *StorageClassApplyConfiguration) WithParameters(entries map[string]string) *StorageClassApplyConfiguration {\n\tif b.Parameters == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Parameters = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Parameters[k] = v\n\t}\n\treturn b\n}","line":{"from":257,"to":269}} {"id":100024928,"name":"WithReclaimPolicy","signature":"func (b *StorageClassApplyConfiguration) WithReclaimPolicy(value corev1.PersistentVolumeReclaimPolicy) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"// WithReclaimPolicy sets the ReclaimPolicy field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ReclaimPolicy field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithReclaimPolicy(value corev1.PersistentVolumeReclaimPolicy) *StorageClassApplyConfiguration {\n\tb.ReclaimPolicy = \u0026value\n\treturn b\n}","line":{"from":271,"to":277}} {"id":100024929,"name":"WithMountOptions","signature":"func (b *StorageClassApplyConfiguration) WithMountOptions(values ...string) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"// WithMountOptions adds the given value to the MountOptions field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the MountOptions field.\nfunc (b *StorageClassApplyConfiguration) WithMountOptions(values ...string) *StorageClassApplyConfiguration {\n\tfor i := range values {\n\t\tb.MountOptions = append(b.MountOptions, values[i])\n\t}\n\treturn b\n}","line":{"from":279,"to":287}} {"id":100024930,"name":"WithAllowVolumeExpansion","signature":"func (b *StorageClassApplyConfiguration) WithAllowVolumeExpansion(value bool) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"// WithAllowVolumeExpansion sets the AllowVolumeExpansion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AllowVolumeExpansion field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithAllowVolumeExpansion(value bool) *StorageClassApplyConfiguration {\n\tb.AllowVolumeExpansion = \u0026value\n\treturn b\n}","line":{"from":289,"to":295}} {"id":100024931,"name":"WithVolumeBindingMode","signature":"func (b *StorageClassApplyConfiguration) WithVolumeBindingMode(value v1beta1.VolumeBindingMode) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"// WithVolumeBindingMode sets the VolumeBindingMode field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the VolumeBindingMode field is set to the value of the last call.\nfunc (b *StorageClassApplyConfiguration) WithVolumeBindingMode(value v1beta1.VolumeBindingMode) *StorageClassApplyConfiguration {\n\tb.VolumeBindingMode = \u0026value\n\treturn b\n}","line":{"from":297,"to":303}} {"id":100024932,"name":"WithAllowedTopologies","signature":"func (b *StorageClassApplyConfiguration) WithAllowedTopologies(values ...*applyconfigurationscorev1.TopologySelectorTermApplyConfiguration) *StorageClassApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/storageclass.go","code":"// WithAllowedTopologies adds the given value to the AllowedTopologies field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the AllowedTopologies field.\nfunc (b *StorageClassApplyConfiguration) WithAllowedTopologies(values ...*applyconfigurationscorev1.TopologySelectorTermApplyConfiguration) *StorageClassApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithAllowedTopologies\")\n\t\t}\n\t\tb.AllowedTopologies = append(b.AllowedTopologies, *values[i])\n\t}\n\treturn b\n}","line":{"from":305,"to":316}} {"id":100024933,"name":"TokenRequest","signature":"func TokenRequest() *TokenRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/tokenrequest.go","code":"// TokenRequestApplyConfiguration constructs an declarative configuration of the TokenRequest type for use with\n// apply.\nfunc TokenRequest() *TokenRequestApplyConfiguration {\n\treturn \u0026TokenRequestApplyConfiguration{}\n}","line":{"from":28,"to":32}} {"id":100024934,"name":"WithAudience","signature":"func (b *TokenRequestApplyConfiguration) WithAudience(value string) *TokenRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/tokenrequest.go","code":"// WithAudience sets the Audience field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Audience field is set to the value of the last call.\nfunc (b *TokenRequestApplyConfiguration) WithAudience(value string) *TokenRequestApplyConfiguration {\n\tb.Audience = \u0026value\n\treturn b\n}","line":{"from":34,"to":40}} {"id":100024935,"name":"WithExpirationSeconds","signature":"func (b *TokenRequestApplyConfiguration) WithExpirationSeconds(value int64) *TokenRequestApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/tokenrequest.go","code":"// WithExpirationSeconds sets the ExpirationSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ExpirationSeconds field is set to the value of the last call.\nfunc (b *TokenRequestApplyConfiguration) WithExpirationSeconds(value int64) *TokenRequestApplyConfiguration {\n\tb.ExpirationSeconds = \u0026value\n\treturn b\n}","line":{"from":42,"to":48}} {"id":100024936,"name":"VolumeAttachment","signature":"func VolumeAttachment(name string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachment.go","code":"// VolumeAttachment constructs an declarative configuration of the VolumeAttachment type for use with\n// apply.\nfunc VolumeAttachment(name string) *VolumeAttachmentApplyConfiguration {\n\tb := \u0026VolumeAttachmentApplyConfiguration{}\n\tb.WithName(name)\n\tb.WithKind(\"VolumeAttachment\")\n\tb.WithAPIVersion(\"storage.k8s.io/v1beta1\")\n\treturn b\n}","line":{"from":39,"to":47}} {"id":100024937,"name":"ExtractVolumeAttachment","signature":"func ExtractVolumeAttachment(volumeAttachment *storagev1beta1.VolumeAttachment, fieldManager string) (*VolumeAttachmentApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachment.go","code":"// ExtractVolumeAttachment extracts the applied configuration owned by fieldManager from\n// volumeAttachment. If no managedFields are found in volumeAttachment for fieldManager, a\n// VolumeAttachmentApplyConfiguration is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// volumeAttachment must be a unmodified VolumeAttachment API object that was retrieved from the Kubernetes API.\n// ExtractVolumeAttachment provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc ExtractVolumeAttachment(volumeAttachment *storagev1beta1.VolumeAttachment, fieldManager string) (*VolumeAttachmentApplyConfiguration, error) {\n\treturn extractVolumeAttachment(volumeAttachment, fieldManager, \"\")\n}","line":{"from":49,"to":62}} {"id":100024938,"name":"ExtractVolumeAttachmentStatus","signature":"func ExtractVolumeAttachmentStatus(volumeAttachment *storagev1beta1.VolumeAttachment, fieldManager string) (*VolumeAttachmentApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachment.go","code":"// ExtractVolumeAttachmentStatus is the same as ExtractVolumeAttachment except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc ExtractVolumeAttachmentStatus(volumeAttachment *storagev1beta1.VolumeAttachment, fieldManager string) (*VolumeAttachmentApplyConfiguration, error) {\n\treturn extractVolumeAttachment(volumeAttachment, fieldManager, \"status\")\n}","line":{"from":64,"to":69}} {"id":100024939,"name":"extractVolumeAttachment","signature":"func extractVolumeAttachment(volumeAttachment *storagev1beta1.VolumeAttachment, fieldManager string, subresource string) (*VolumeAttachmentApplyConfiguration, error)","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachment.go","code":"func extractVolumeAttachment(volumeAttachment *storagev1beta1.VolumeAttachment, fieldManager string, subresource string) (*VolumeAttachmentApplyConfiguration, error) {\n\tb := \u0026VolumeAttachmentApplyConfiguration{}\n\terr := managedfields.ExtractInto(volumeAttachment, internal.Parser().Type(\"io.k8s.api.storage.v1beta1.VolumeAttachment\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName(volumeAttachment.Name)\n\n\tb.WithKind(\"VolumeAttachment\")\n\tb.WithAPIVersion(\"storage.k8s.io/v1beta1\")\n\treturn b, nil\n}","line":{"from":71,"to":82}} {"id":100024940,"name":"WithKind","signature":"func (b *VolumeAttachmentApplyConfiguration) WithKind(value string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachment.go","code":"// WithKind sets the Kind field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Kind field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithKind(value string) *VolumeAttachmentApplyConfiguration {\n\tb.Kind = \u0026value\n\treturn b\n}","line":{"from":84,"to":90}} {"id":100024941,"name":"WithAPIVersion","signature":"func (b *VolumeAttachmentApplyConfiguration) WithAPIVersion(value string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachment.go","code":"// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the APIVersion field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithAPIVersion(value string) *VolumeAttachmentApplyConfiguration {\n\tb.APIVersion = \u0026value\n\treturn b\n}","line":{"from":92,"to":98}} {"id":100024942,"name":"WithName","signature":"func (b *VolumeAttachmentApplyConfiguration) WithName(value string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachment.go","code":"// WithName sets the Name field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Name field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithName(value string) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Name = \u0026value\n\treturn b\n}","line":{"from":100,"to":107}} {"id":100024943,"name":"WithGenerateName","signature":"func (b *VolumeAttachmentApplyConfiguration) WithGenerateName(value string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachment.go","code":"// WithGenerateName sets the GenerateName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the GenerateName field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithGenerateName(value string) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.GenerateName = \u0026value\n\treturn b\n}","line":{"from":109,"to":116}} {"id":100024944,"name":"WithNamespace","signature":"func (b *VolumeAttachmentApplyConfiguration) WithNamespace(value string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachment.go","code":"// WithNamespace sets the Namespace field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Namespace field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithNamespace(value string) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Namespace = \u0026value\n\treturn b\n}","line":{"from":118,"to":125}} {"id":100024945,"name":"WithUID","signature":"func (b *VolumeAttachmentApplyConfiguration) WithUID(value types.UID) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachment.go","code":"// WithUID sets the UID field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the UID field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithUID(value types.UID) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.UID = \u0026value\n\treturn b\n}","line":{"from":127,"to":134}} {"id":100024946,"name":"WithResourceVersion","signature":"func (b *VolumeAttachmentApplyConfiguration) WithResourceVersion(value string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachment.go","code":"// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the ResourceVersion field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithResourceVersion(value string) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.ResourceVersion = \u0026value\n\treturn b\n}","line":{"from":136,"to":143}} {"id":100024947,"name":"WithGeneration","signature":"func (b *VolumeAttachmentApplyConfiguration) WithGeneration(value int64) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachment.go","code":"// WithGeneration sets the Generation field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Generation field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithGeneration(value int64) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.Generation = \u0026value\n\treturn b\n}","line":{"from":145,"to":152}} {"id":100024948,"name":"WithCreationTimestamp","signature":"func (b *VolumeAttachmentApplyConfiguration) WithCreationTimestamp(value metav1.Time) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachment.go","code":"// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the CreationTimestamp field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithCreationTimestamp(value metav1.Time) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.CreationTimestamp = \u0026value\n\treturn b\n}","line":{"from":154,"to":161}} {"id":100024949,"name":"WithDeletionTimestamp","signature":"func (b *VolumeAttachmentApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachment.go","code":"// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionTimestamp field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionTimestamp = \u0026value\n\treturn b\n}","line":{"from":163,"to":170}} {"id":100024950,"name":"WithDeletionGracePeriodSeconds","signature":"func (b *VolumeAttachmentApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachment.go","code":"// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tb.DeletionGracePeriodSeconds = \u0026value\n\treturn b\n}","line":{"from":172,"to":179}} {"id":100024951,"name":"WithLabels","signature":"func (b *VolumeAttachmentApplyConfiguration) WithLabels(entries map[string]string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachment.go","code":"// WithLabels puts the entries into the Labels field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Labels field,\n// overwriting an existing map entries in Labels field with the same key.\nfunc (b *VolumeAttachmentApplyConfiguration) WithLabels(entries map[string]string) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Labels == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Labels = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Labels[k] = v\n\t}\n\treturn b\n}","line":{"from":181,"to":194}} {"id":100024952,"name":"WithAnnotations","signature":"func (b *VolumeAttachmentApplyConfiguration) WithAnnotations(entries map[string]string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachment.go","code":"// WithAnnotations puts the entries into the Annotations field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the Annotations field,\n// overwriting an existing map entries in Annotations field with the same key.\nfunc (b *VolumeAttachmentApplyConfiguration) WithAnnotations(entries map[string]string) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tif b.Annotations == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.Annotations = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.Annotations[k] = v\n\t}\n\treturn b\n}","line":{"from":196,"to":209}} {"id":100024953,"name":"WithOwnerReferences","signature":"func (b *VolumeAttachmentApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachment.go","code":"// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the OwnerReferences field.\nfunc (b *VolumeAttachmentApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithOwnerReferences\")\n\t\t}\n\t\tb.OwnerReferences = append(b.OwnerReferences, *values[i])\n\t}\n\treturn b\n}","line":{"from":211,"to":223}} {"id":100024954,"name":"WithFinalizers","signature":"func (b *VolumeAttachmentApplyConfiguration) WithFinalizers(values ...string) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachment.go","code":"// WithFinalizers adds the given value to the Finalizers field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, values provided by each call will be appended to the Finalizers field.\nfunc (b *VolumeAttachmentApplyConfiguration) WithFinalizers(values ...string) *VolumeAttachmentApplyConfiguration {\n\tb.ensureObjectMetaApplyConfigurationExists()\n\tfor i := range values {\n\t\tb.Finalizers = append(b.Finalizers, values[i])\n\t}\n\treturn b\n}","line":{"from":225,"to":234}} {"id":100024955,"name":"ensureObjectMetaApplyConfigurationExists","signature":"func (b *VolumeAttachmentApplyConfiguration) ensureObjectMetaApplyConfigurationExists()","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachment.go","code":"func (b *VolumeAttachmentApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {\n\tif b.ObjectMetaApplyConfiguration == nil {\n\t\tb.ObjectMetaApplyConfiguration = \u0026v1.ObjectMetaApplyConfiguration{}\n\t}\n}","line":{"from":236,"to":240}} {"id":100024956,"name":"WithSpec","signature":"func (b *VolumeAttachmentApplyConfiguration) WithSpec(value *VolumeAttachmentSpecApplyConfiguration) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachment.go","code":"// WithSpec sets the Spec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Spec field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithSpec(value *VolumeAttachmentSpecApplyConfiguration) *VolumeAttachmentApplyConfiguration {\n\tb.Spec = value\n\treturn b\n}","line":{"from":242,"to":248}} {"id":100024957,"name":"WithStatus","signature":"func (b *VolumeAttachmentApplyConfiguration) WithStatus(value *VolumeAttachmentStatusApplyConfiguration) *VolumeAttachmentApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachment.go","code":"// WithStatus sets the Status field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Status field is set to the value of the last call.\nfunc (b *VolumeAttachmentApplyConfiguration) WithStatus(value *VolumeAttachmentStatusApplyConfiguration) *VolumeAttachmentApplyConfiguration {\n\tb.Status = value\n\treturn b\n}","line":{"from":250,"to":256}} {"id":100024958,"name":"VolumeAttachmentSource","signature":"func VolumeAttachmentSource() *VolumeAttachmentSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachmentsource.go","code":"// VolumeAttachmentSourceApplyConfiguration constructs an declarative configuration of the VolumeAttachmentSource type for use with\n// apply.\nfunc VolumeAttachmentSource() *VolumeAttachmentSourceApplyConfiguration {\n\treturn \u0026VolumeAttachmentSourceApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100024959,"name":"WithPersistentVolumeName","signature":"func (b *VolumeAttachmentSourceApplyConfiguration) WithPersistentVolumeName(value string) *VolumeAttachmentSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachmentsource.go","code":"// WithPersistentVolumeName sets the PersistentVolumeName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the PersistentVolumeName field is set to the value of the last call.\nfunc (b *VolumeAttachmentSourceApplyConfiguration) WithPersistentVolumeName(value string) *VolumeAttachmentSourceApplyConfiguration {\n\tb.PersistentVolumeName = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100024960,"name":"WithInlineVolumeSpec","signature":"func (b *VolumeAttachmentSourceApplyConfiguration) WithInlineVolumeSpec(value *v1.PersistentVolumeSpecApplyConfiguration) *VolumeAttachmentSourceApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachmentsource.go","code":"// WithInlineVolumeSpec sets the InlineVolumeSpec field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the InlineVolumeSpec field is set to the value of the last call.\nfunc (b *VolumeAttachmentSourceApplyConfiguration) WithInlineVolumeSpec(value *v1.PersistentVolumeSpecApplyConfiguration) *VolumeAttachmentSourceApplyConfiguration {\n\tb.InlineVolumeSpec = value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100024961,"name":"VolumeAttachmentSpec","signature":"func VolumeAttachmentSpec() *VolumeAttachmentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachmentspec.go","code":"// VolumeAttachmentSpecApplyConfiguration constructs an declarative configuration of the VolumeAttachmentSpec type for use with\n// apply.\nfunc VolumeAttachmentSpec() *VolumeAttachmentSpecApplyConfiguration {\n\treturn \u0026VolumeAttachmentSpecApplyConfiguration{}\n}","line":{"from":29,"to":33}} {"id":100024962,"name":"WithAttacher","signature":"func (b *VolumeAttachmentSpecApplyConfiguration) WithAttacher(value string) *VolumeAttachmentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachmentspec.go","code":"// WithAttacher sets the Attacher field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Attacher field is set to the value of the last call.\nfunc (b *VolumeAttachmentSpecApplyConfiguration) WithAttacher(value string) *VolumeAttachmentSpecApplyConfiguration {\n\tb.Attacher = \u0026value\n\treturn b\n}","line":{"from":35,"to":41}} {"id":100024963,"name":"WithSource","signature":"func (b *VolumeAttachmentSpecApplyConfiguration) WithSource(value *VolumeAttachmentSourceApplyConfiguration) *VolumeAttachmentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachmentspec.go","code":"// WithSource sets the Source field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Source field is set to the value of the last call.\nfunc (b *VolumeAttachmentSpecApplyConfiguration) WithSource(value *VolumeAttachmentSourceApplyConfiguration) *VolumeAttachmentSpecApplyConfiguration {\n\tb.Source = value\n\treturn b\n}","line":{"from":43,"to":49}} {"id":100024964,"name":"WithNodeName","signature":"func (b *VolumeAttachmentSpecApplyConfiguration) WithNodeName(value string) *VolumeAttachmentSpecApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachmentspec.go","code":"// WithNodeName sets the NodeName field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the NodeName field is set to the value of the last call.\nfunc (b *VolumeAttachmentSpecApplyConfiguration) WithNodeName(value string) *VolumeAttachmentSpecApplyConfiguration {\n\tb.NodeName = \u0026value\n\treturn b\n}","line":{"from":51,"to":57}} {"id":100024965,"name":"VolumeAttachmentStatus","signature":"func VolumeAttachmentStatus() *VolumeAttachmentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachmentstatus.go","code":"// VolumeAttachmentStatusApplyConfiguration constructs an declarative configuration of the VolumeAttachmentStatus type for use with\n// apply.\nfunc VolumeAttachmentStatus() *VolumeAttachmentStatusApplyConfiguration {\n\treturn \u0026VolumeAttachmentStatusApplyConfiguration{}\n}","line":{"from":30,"to":34}} {"id":100024966,"name":"WithAttached","signature":"func (b *VolumeAttachmentStatusApplyConfiguration) WithAttached(value bool) *VolumeAttachmentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachmentstatus.go","code":"// WithAttached sets the Attached field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Attached field is set to the value of the last call.\nfunc (b *VolumeAttachmentStatusApplyConfiguration) WithAttached(value bool) *VolumeAttachmentStatusApplyConfiguration {\n\tb.Attached = \u0026value\n\treturn b\n}","line":{"from":36,"to":42}} {"id":100024967,"name":"WithAttachmentMetadata","signature":"func (b *VolumeAttachmentStatusApplyConfiguration) WithAttachmentMetadata(entries map[string]string) *VolumeAttachmentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachmentstatus.go","code":"// WithAttachmentMetadata puts the entries into the AttachmentMetadata field in the declarative configuration\n// and returns the receiver, so that objects can be build by chaining \"With\" function invocations.\n// If called multiple times, the entries provided by each call will be put on the AttachmentMetadata field,\n// overwriting an existing map entries in AttachmentMetadata field with the same key.\nfunc (b *VolumeAttachmentStatusApplyConfiguration) WithAttachmentMetadata(entries map[string]string) *VolumeAttachmentStatusApplyConfiguration {\n\tif b.AttachmentMetadata == nil \u0026\u0026 len(entries) \u003e 0 {\n\t\tb.AttachmentMetadata = make(map[string]string, len(entries))\n\t}\n\tfor k, v := range entries {\n\t\tb.AttachmentMetadata[k] = v\n\t}\n\treturn b\n}","line":{"from":44,"to":56}} {"id":100024968,"name":"WithAttachError","signature":"func (b *VolumeAttachmentStatusApplyConfiguration) WithAttachError(value *VolumeErrorApplyConfiguration) *VolumeAttachmentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachmentstatus.go","code":"// WithAttachError sets the AttachError field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the AttachError field is set to the value of the last call.\nfunc (b *VolumeAttachmentStatusApplyConfiguration) WithAttachError(value *VolumeErrorApplyConfiguration) *VolumeAttachmentStatusApplyConfiguration {\n\tb.AttachError = value\n\treturn b\n}","line":{"from":58,"to":64}} {"id":100024969,"name":"WithDetachError","signature":"func (b *VolumeAttachmentStatusApplyConfiguration) WithDetachError(value *VolumeErrorApplyConfiguration) *VolumeAttachmentStatusApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeattachmentstatus.go","code":"// WithDetachError sets the DetachError field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the DetachError field is set to the value of the last call.\nfunc (b *VolumeAttachmentStatusApplyConfiguration) WithDetachError(value *VolumeErrorApplyConfiguration) *VolumeAttachmentStatusApplyConfiguration {\n\tb.DetachError = value\n\treturn b\n}","line":{"from":66,"to":72}} {"id":100024970,"name":"VolumeError","signature":"func VolumeError() *VolumeErrorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeerror.go","code":"// VolumeErrorApplyConfiguration constructs an declarative configuration of the VolumeError type for use with\n// apply.\nfunc VolumeError() *VolumeErrorApplyConfiguration {\n\treturn \u0026VolumeErrorApplyConfiguration{}\n}","line":{"from":32,"to":36}} {"id":100024971,"name":"WithTime","signature":"func (b *VolumeErrorApplyConfiguration) WithTime(value v1.Time) *VolumeErrorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeerror.go","code":"// WithTime sets the Time field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Time field is set to the value of the last call.\nfunc (b *VolumeErrorApplyConfiguration) WithTime(value v1.Time) *VolumeErrorApplyConfiguration {\n\tb.Time = \u0026value\n\treturn b\n}","line":{"from":38,"to":44}} {"id":100024972,"name":"WithMessage","signature":"func (b *VolumeErrorApplyConfiguration) WithMessage(value string) *VolumeErrorApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumeerror.go","code":"// WithMessage sets the Message field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Message field is set to the value of the last call.\nfunc (b *VolumeErrorApplyConfiguration) WithMessage(value string) *VolumeErrorApplyConfiguration {\n\tb.Message = \u0026value\n\treturn b\n}","line":{"from":46,"to":52}} {"id":100024973,"name":"VolumeNodeResources","signature":"func VolumeNodeResources() *VolumeNodeResourcesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumenoderesources.go","code":"// VolumeNodeResourcesApplyConfiguration constructs an declarative configuration of the VolumeNodeResources type for use with\n// apply.\nfunc VolumeNodeResources() *VolumeNodeResourcesApplyConfiguration {\n\treturn \u0026VolumeNodeResourcesApplyConfiguration{}\n}","line":{"from":27,"to":31}} {"id":100024974,"name":"WithCount","signature":"func (b *VolumeNodeResourcesApplyConfiguration) WithCount(value int32) *VolumeNodeResourcesApplyConfiguration","file":"staging/src/k8s.io/client-go/applyconfigurations/storage/v1beta1/volumenoderesources.go","code":"// WithCount sets the Count field in the declarative configuration to the given value\n// and returns the receiver, so that objects can be built by chaining \"With\" function invocations.\n// If called multiple times, the Count field is set to the value of the last call.\nfunc (b *VolumeNodeResourcesApplyConfiguration) WithCount(value int32) *VolumeNodeResourcesApplyConfiguration {\n\tb.Count = \u0026value\n\treturn b\n}","line":{"from":33,"to":39}} {"id":100024975,"name":"ForKind","signature":"func ForKind(kind schema.GroupVersionKind) interface{}","file":"staging/src/k8s.io/client-go/applyconfigurations/utils.go","code":"// ForKind returns an apply configuration type for the given GroupVersionKind, or nil if no\n// apply configuration type exists for the given GroupVersionKind.\nfunc ForKind(kind schema.GroupVersionKind) interface{} {\n\tswitch kind {\n\t// Group=admissionregistration.k8s.io, Version=v1\n\tcase v1.SchemeGroupVersion.WithKind(\"MatchCondition\"):\n\t\treturn \u0026admissionregistrationv1.MatchConditionApplyConfiguration{}\n\tcase v1.SchemeGroupVersion.WithKind(\"MutatingWebhook\"):\n\t\treturn \u0026admissionregistrationv1.MutatingWebhookApplyConfiguration{}\n\tcase v1.SchemeGroupVersion.WithKind(\"MutatingWebhookConfiguration\"):\n\t\treturn \u0026admissionregistrationv1.MutatingWebhookConfigurationApplyConfiguration{}\n\tcase v1.SchemeGroupVersion.WithKind(\"Rule\"):\n\t\treturn \u0026admissionregistrationv1.RuleApplyConfiguration{}\n\tcase v1.SchemeGroupVersion.WithKind(\"RuleWithOperations\"):\n\t\treturn \u0026admissionregistrationv1.RuleWithOperationsApplyConfiguration{}\n\tcase v1.SchemeGroupVersion.WithKind(\"ServiceReference\"):\n\t\treturn \u0026admissionregistrationv1.ServiceReferenceApplyConfiguration{}\n\tcase v1.SchemeGroupVersion.WithKind(\"ValidatingWebhook\"):\n\t\treturn \u0026admissionregistrationv1.ValidatingWebhookApplyConfiguration{}\n\tcase v1.SchemeGroupVersion.WithKind(\"ValidatingWebhookConfiguration\"):\n\t\treturn \u0026admissionregistrationv1.ValidatingWebhookConfigurationApplyConfiguration{}\n\tcase v1.SchemeGroupVersion.WithKind(\"WebhookClientConfig\"):\n\t\treturn \u0026admissionregistrationv1.WebhookClientConfigApplyConfiguration{}\n\n\t\t// Group=admissionregistration.k8s.io, Version=v1alpha1\n\tcase v1alpha1.SchemeGroupVersion.WithKind(\"AuditAnnotation\"):\n\t\treturn \u0026admissionregistrationv1alpha1.AuditAnnotationApplyConfiguration{}\n\tcase v1alpha1.SchemeGroupVersion.WithKind(\"ExpressionWarning\"):\n\t\treturn \u0026admissionregistrationv1alpha1.ExpressionWarningApplyConfiguration{}\n\tcase v1alpha1.SchemeGroupVersion.WithKind(\"MatchCondition\"):\n\t\treturn \u0026admissionregistrationv1alpha1.MatchConditionApplyConfiguration{}\n\tcase v1alpha1.SchemeGroupVersion.WithKind(\"MatchResources\"):\n\t\treturn \u0026admissionregistrationv1alpha1.MatchResourcesApplyConfiguration{}\n\tcase v1alpha1.SchemeGroupVersion.WithKind(\"NamedRuleWithOperations\"):\n\t\treturn \u0026admissionregistrationv1alpha1.NamedRuleWithOperationsApplyConfiguration{}\n\tcase v1alpha1.SchemeGroupVersion.WithKind(\"ParamKind\"):\n\t\treturn \u0026admissionregistrationv1alpha1.ParamKindApplyConfiguration{}\n\tcase v1alpha1.SchemeGroupVersion.WithKind(\"ParamRef\"):\n\t\treturn \u0026admissionregistrationv1alpha1.ParamRefApplyConfiguration{}\n\tcase v1alpha1.SchemeGroupVersion.WithKind(\"TypeChecking\"):\n\t\treturn \u0026admissionregistrationv1alpha1.TypeCheckingApplyConfiguration{}\n\tcase v1alpha1.SchemeGroupVersion.WithKind(\"ValidatingAdmissionPolicy\"):\n\t\treturn \u0026admissionregistrationv1alpha1.ValidatingAdmissionPolicyApplyConfiguration{}\n\tcase v1alpha1.SchemeGroupVersion.WithKind(\"ValidatingAdmissionPolicyBinding\"):\n\t\treturn \u0026admissionregistrationv1alpha1.ValidatingAdmissionPolicyBindingApplyConfiguration{}\n\tcase v1alpha1.SchemeGroupVersion.WithKind(\"ValidatingAdmissionPolicyBindingSpec\"):\n\t\treturn \u0026admissionregistrationv1alpha1.ValidatingAdmissionPolicyBindingSpecApplyConfiguration{}\n\tcase v1alpha1.SchemeGroupVersion.WithKind(\"ValidatingAdmissionPolicySpec\"):\n\t\treturn \u0026admissionregistrationv1alpha1.ValidatingAdmissionPolicySpecApplyConfiguration{}\n\tcase v1alpha1.SchemeGroupVersion.WithKind(\"ValidatingAdmissionPolicyStatus\"):\n\t\treturn \u0026admissionregistrationv1alpha1.ValidatingAdmissionPolicyStatusApplyConfiguration{}\n\tcase v1alpha1.SchemeGroupVersion.WithKind(\"Validation\"):\n\t\treturn \u0026admissionregistrationv1alpha1.ValidationApplyConfiguration{}\n\n\t\t// Group=admissionregistration.k8s.io, Version=v1beta1\n\tcase v1beta1.SchemeGroupVersion.WithKind(\"MatchCondition\"):\n\t\treturn \u0026admissionregistrationv1beta1.MatchConditionApplyConfiguration{}\n\tcase v1beta1.SchemeGroupVersion.WithKind(\"MutatingWebhook\"):\n\t\treturn \u0026admissionregistrationv1beta1.MutatingWebhookApplyConfiguration{}\n\tcase v1beta1.SchemeGroupVersion.WithKind(\"MutatingWebhookConfiguration\"):\n\t\treturn \u0026admissionregistrationv1beta1.MutatingWebhookConfigurationApplyConfiguration{}\n\tcase v1beta1.SchemeGroupVersion.WithKind(\"ServiceReference\"):\n\t\treturn \u0026admissionregistrationv1beta1.ServiceReferenceApplyConfiguration{}\n\tcase v1beta1.SchemeGroupVersion.WithKind(\"ValidatingWebhook\"):\n\t\treturn \u0026admissionregistrationv1beta1.ValidatingWebhookApplyConfiguration{}\n\tcase v1beta1.SchemeGroupVersion.WithKind(\"ValidatingWebhookConfiguration\"):\n\t\treturn \u0026admissionregistrationv1beta1.ValidatingWebhookConfigurationApplyConfiguration{}\n\tcase v1beta1.SchemeGroupVersion.WithKind(\"WebhookClientConfig\"):\n\t\treturn \u0026admissionregistrationv1beta1.WebhookClientConfigApplyConfiguration{}\n\n\t\t// Group=apps, Version=v1\n\tcase appsv1.SchemeGroupVersion.WithKind(\"ControllerRevision\"):\n\t\treturn \u0026applyconfigurationsappsv1.ControllerRevisionApplyConfiguration{}\n\tcase appsv1.SchemeGroupVersion.WithKind(\"DaemonSet\"):\n\t\treturn \u0026applyconfigurationsappsv1.DaemonSetApplyConfiguration{}\n\tcase appsv1.SchemeGroupVersion.WithKind(\"DaemonSetCondition\"):\n\t\treturn \u0026applyconfigurationsappsv1.DaemonSetConditionApplyConfiguration{}\n\tcase appsv1.SchemeGroupVersion.WithKind(\"DaemonSetSpec\"):\n\t\treturn \u0026applyconfigurationsappsv1.DaemonSetSpecApplyConfiguration{}\n\tcase appsv1.SchemeGroupVersion.WithKind(\"DaemonSetStatus\"):\n\t\treturn \u0026applyconfigurationsappsv1.DaemonSetStatusApplyConfiguration{}\n\tcase appsv1.SchemeGroupVersion.WithKind(\"DaemonSetUpdateStrategy\"):\n\t\treturn \u0026applyconfigurationsappsv1.DaemonSetUpdateStrategyApplyConfiguration{}\n\tcase appsv1.SchemeGroupVersion.WithKind(\"Deployment\"):\n\t\treturn \u0026applyconfigurationsappsv1.DeploymentApplyConfiguration{}\n\tcase appsv1.SchemeGroupVersion.WithKind(\"DeploymentCondition\"):\n\t\treturn \u0026applyconfigurationsappsv1.DeploymentConditionApplyConfiguration{}\n\tcase appsv1.SchemeGroupVersion.WithKind(\"DeploymentSpec\"):\n\t\treturn \u0026applyconfigurationsappsv1.DeploymentSpecApplyConfiguration{}\n\tcase appsv1.SchemeGroupVersion.WithKind(\"DeploymentStatus\"):\n\t\treturn \u0026applyconfigurationsappsv1.DeploymentStatusApplyConfiguration{}\n\tcase appsv1.SchemeGroupVersion.WithKind(\"DeploymentStrategy\"):\n\t\treturn \u0026applyconfigurationsappsv1.DeploymentStrategyApplyConfiguration{}\n\tcase appsv1.SchemeGroupVersion.WithKind(\"ReplicaSet\"):\n\t\treturn \u0026applyconfigurationsappsv1.ReplicaSetApplyConfiguration{}\n\tcase appsv1.SchemeGroupVersion.WithKind(\"ReplicaSetCondition\"):\n\t\treturn \u0026applyconfigurationsappsv1.ReplicaSetConditionApplyConfiguration{}\n\tcase appsv1.SchemeGroupVersion.WithKind(\"ReplicaSetSpec\"):\n\t\treturn \u0026applyconfigurationsappsv1.ReplicaSetSpecApplyConfiguration{}\n\tcase appsv1.SchemeGroupVersion.WithKind(\"ReplicaSetStatus\"):\n\t\treturn \u0026applyconfigurationsappsv1.ReplicaSetStatusApplyConfiguration{}\n\tcase appsv1.SchemeGroupVersion.WithKind(\"RollingUpdateDaemonSet\"):\n\t\treturn \u0026applyconfigurationsappsv1.RollingUpdateDaemonSetApplyConfiguration{}\n\tcase appsv1.SchemeGroupVersion.WithKind(\"RollingUpdateDeployment\"):\n\t\treturn \u0026applyconfigurationsappsv1.RollingUpdateDeploymentApplyConfiguration{}\n\tcase appsv1.SchemeGroupVersion.WithKind(\"RollingUpdateStatefulSetStrategy\"):\n\t\treturn \u0026applyconfigurationsappsv1.RollingUpdateStatefulSetStrategyApplyConfiguration{}\n\tcase appsv1.SchemeGroupVersion.WithKind(\"StatefulSet\"):\n\t\treturn \u0026applyconfigurationsappsv1.StatefulSetApplyConfiguration{}\n\tcase appsv1.SchemeGroupVersion.WithKind(\"StatefulSetCondition\"):\n\t\treturn \u0026applyconfigurationsappsv1.StatefulSetConditionApplyConfiguration{}\n\tcase appsv1.SchemeGroupVersion.WithKind(\"StatefulSetOrdinals\"):\n\t\treturn \u0026applyconfigurationsappsv1.StatefulSetOrdinalsApplyConfiguration{}\n\tcase appsv1.SchemeGroupVersion.WithKind(\"StatefulSetPersistentVolumeClaimRetentionPolicy\"):\n\t\treturn \u0026applyconfigurationsappsv1.StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration{}\n\tcase appsv1.SchemeGroupVersion.WithKind(\"StatefulSetSpec\"):\n\t\treturn \u0026applyconfigurationsappsv1.StatefulSetSpecApplyConfiguration{}\n\tcase appsv1.SchemeGroupVersion.WithKind(\"StatefulSetStatus\"):\n\t\treturn \u0026applyconfigurationsappsv1.StatefulSetStatusApplyConfiguration{}\n\tcase appsv1.SchemeGroupVersion.WithKind(\"StatefulSetUpdateStrategy\"):\n\t\treturn \u0026applyconfigurationsappsv1.StatefulSetUpdateStrategyApplyConfiguration{}\n\n\t\t// Group=apps, Version=v1beta1\n\tcase appsv1beta1.SchemeGroupVersion.WithKind(\"ControllerRevision\"):\n\t\treturn \u0026applyconfigurationsappsv1beta1.ControllerRevisionApplyConfiguration{}\n\tcase appsv1beta1.SchemeGroupVersion.WithKind(\"Deployment\"):\n\t\treturn \u0026applyconfigurationsappsv1beta1.DeploymentApplyConfiguration{}\n\tcase appsv1beta1.SchemeGroupVersion.WithKind(\"DeploymentCondition\"):\n\t\treturn \u0026applyconfigurationsappsv1beta1.DeploymentConditionApplyConfiguration{}\n\tcase appsv1beta1.SchemeGroupVersion.WithKind(\"DeploymentSpec\"):\n\t\treturn \u0026applyconfigurationsappsv1beta1.DeploymentSpecApplyConfiguration{}\n\tcase appsv1beta1.SchemeGroupVersion.WithKind(\"DeploymentStatus\"):\n\t\treturn \u0026applyconfigurationsappsv1beta1.DeploymentStatusApplyConfiguration{}\n\tcase appsv1beta1.SchemeGroupVersion.WithKind(\"DeploymentStrategy\"):\n\t\treturn \u0026applyconfigurationsappsv1beta1.DeploymentStrategyApplyConfiguration{}\n\tcase appsv1beta1.SchemeGroupVersion.WithKind(\"RollbackConfig\"):\n\t\treturn \u0026applyconfigurationsappsv1beta1.RollbackConfigApplyConfiguration{}\n\tcase appsv1beta1.SchemeGroupVersion.WithKind(\"RollingUpdateDeployment\"):\n\t\treturn \u0026applyconfigurationsappsv1beta1.RollingUpdateDeploymentApplyConfiguration{}\n\tcase appsv1beta1.SchemeGroupVersion.WithKind(\"RollingUpdateStatefulSetStrategy\"):\n\t\treturn \u0026applyconfigurationsappsv1beta1.RollingUpdateStatefulSetStrategyApplyConfiguration{}\n\tcase appsv1beta1.SchemeGroupVersion.WithKind(\"StatefulSet\"):\n\t\treturn \u0026applyconfigurationsappsv1beta1.StatefulSetApplyConfiguration{}\n\tcase appsv1beta1.SchemeGroupVersion.WithKind(\"StatefulSetCondition\"):\n\t\treturn \u0026applyconfigurationsappsv1beta1.StatefulSetConditionApplyConfiguration{}\n\tcase appsv1beta1.SchemeGroupVersion.WithKind(\"StatefulSetOrdinals\"):\n\t\treturn \u0026applyconfigurationsappsv1beta1.StatefulSetOrdinalsApplyConfiguration{}\n\tcase appsv1beta1.SchemeGroupVersion.WithKind(\"StatefulSetPersistentVolumeClaimRetentionPolicy\"):\n\t\treturn \u0026applyconfigurationsappsv1beta1.StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration{}\n\tcase appsv1beta1.SchemeGroupVersion.WithKind(\"StatefulSetSpec\"):\n\t\treturn \u0026applyconfigurationsappsv1beta1.StatefulSetSpecApplyConfiguration{}\n\tcase appsv1beta1.SchemeGroupVersion.WithKind(\"StatefulSetStatus\"):\n\t\treturn \u0026applyconfigurationsappsv1beta1.StatefulSetStatusApplyConfiguration{}\n\tcase appsv1beta1.SchemeGroupVersion.WithKind(\"StatefulSetUpdateStrategy\"):\n\t\treturn \u0026applyconfigurationsappsv1beta1.StatefulSetUpdateStrategyApplyConfiguration{}\n\n\t\t// Group=apps, Version=v1beta2\n\tcase v1beta2.SchemeGroupVersion.WithKind(\"ControllerRevision\"):\n\t\treturn \u0026appsv1beta2.ControllerRevisionApplyConfiguration{}\n\tcase v1beta2.SchemeGroupVersion.WithKind(\"DaemonSet\"):\n\t\treturn \u0026appsv1beta2.DaemonSetApplyConfiguration{}\n\tcase v1beta2.SchemeGroupVersion.WithKind(\"DaemonSetCondition\"):\n\t\treturn \u0026appsv1beta2.DaemonSetConditionApplyConfiguration{}\n\tcase v1beta2.SchemeGroupVersion.WithKind(\"DaemonSetSpec\"):\n\t\treturn \u0026appsv1beta2.DaemonSetSpecApplyConfiguration{}\n\tcase v1beta2.SchemeGroupVersion.WithKind(\"DaemonSetStatus\"):\n\t\treturn \u0026appsv1beta2.DaemonSetStatusApplyConfiguration{}\n\tcase v1beta2.SchemeGroupVersion.WithKind(\"DaemonSetUpdateStrategy\"):\n\t\treturn \u0026appsv1beta2.DaemonSetUpdateStrategyApplyConfiguration{}\n\tcase v1beta2.SchemeGroupVersion.WithKind(\"Deployment\"):\n\t\treturn \u0026appsv1beta2.DeploymentApplyConfiguration{}\n\tcase v1beta2.SchemeGroupVersion.WithKind(\"DeploymentCondition\"):\n\t\treturn \u0026appsv1beta2.DeploymentConditionApplyConfiguration{}\n\tcase v1beta2.SchemeGroupVersion.WithKind(\"DeploymentSpec\"):\n\t\treturn \u0026appsv1beta2.DeploymentSpecApplyConfiguration{}\n\tcase v1beta2.SchemeGroupVersion.WithKind(\"DeploymentStatus\"):\n\t\treturn \u0026appsv1beta2.DeploymentStatusApplyConfiguration{}\n\tcase v1beta2.SchemeGroupVersion.WithKind(\"DeploymentStrategy\"):\n\t\treturn \u0026appsv1beta2.DeploymentStrategyApplyConfiguration{}\n\tcase v1beta2.SchemeGroupVersion.WithKind(\"ReplicaSet\"):\n\t\treturn \u0026appsv1beta2.ReplicaSetApplyConfiguration{}\n\tcase v1beta2.SchemeGroupVersion.WithKind(\"ReplicaSetCondition\"):\n\t\treturn \u0026appsv1beta2.ReplicaSetConditionApplyConfiguration{}\n\tcase v1beta2.SchemeGroupVersion.WithKind(\"ReplicaSetSpec\"):\n\t\treturn \u0026appsv1beta2.ReplicaSetSpecApplyConfiguration{}\n\tcase v1beta2.SchemeGroupVersion.WithKind(\"ReplicaSetStatus\"):\n\t\treturn \u0026appsv1beta2.ReplicaSetStatusApplyConfiguration{}\n\tcase v1beta2.SchemeGroupVersion.WithKind(\"RollingUpdateDaemonSet\"):\n\t\treturn \u0026appsv1beta2.RollingUpdateDaemonSetApplyConfiguration{}\n\tcase v1beta2.SchemeGroupVersion.WithKind(\"RollingUpdateDeployment\"):\n\t\treturn \u0026appsv1beta2.RollingUpdateDeploymentApplyConfiguration{}\n\tcase v1beta2.SchemeGroupVersion.WithKind(\"RollingUpdateStatefulSetStrategy\"):\n\t\treturn \u0026appsv1beta2.RollingUpdateStatefulSetStrategyApplyConfiguration{}\n\tcase v1beta2.SchemeGroupVersion.WithKind(\"Scale\"):\n\t\treturn \u0026appsv1beta2.ScaleApplyConfiguration{}\n\tcase v1beta2.SchemeGroupVersion.WithKind(\"StatefulSet\"):\n\t\treturn \u0026appsv1beta2.StatefulSetApplyConfiguration{}\n\tcase v1beta2.SchemeGroupVersion.WithKind(\"StatefulSetCondition\"):\n\t\treturn \u0026appsv1beta2.StatefulSetConditionApplyConfiguration{}\n\tcase v1beta2.SchemeGroupVersion.WithKind(\"StatefulSetOrdinals\"):\n\t\treturn \u0026appsv1beta2.StatefulSetOrdinalsApplyConfiguration{}\n\tcase v1beta2.SchemeGroupVersion.WithKind(\"StatefulSetPersistentVolumeClaimRetentionPolicy\"):\n\t\treturn \u0026appsv1beta2.StatefulSetPersistentVolumeClaimRetentionPolicyApplyConfiguration{}\n\tcase v1beta2.SchemeGroupVersion.WithKind(\"StatefulSetSpec\"):\n\t\treturn \u0026appsv1beta2.StatefulSetSpecApplyConfiguration{}\n\tcase v1beta2.SchemeGroupVersion.WithKind(\"StatefulSetStatus\"):\n\t\treturn \u0026appsv1beta2.StatefulSetStatusApplyConfiguration{}\n\tcase v1beta2.SchemeGroupVersion.WithKind(\"StatefulSetUpdateStrategy\"):\n\t\treturn \u0026appsv1beta2.StatefulSetUpdateStrategyApplyConfiguration{}\n\n\t\t// Group=autoscaling, Version=v1\n\tcase autoscalingv1.SchemeGroupVersion.WithKind(\"CrossVersionObjectReference\"):\n\t\treturn \u0026applyconfigurationsautoscalingv1.CrossVersionObjectReferenceApplyConfiguration{}\n\tcase autoscalingv1.SchemeGroupVersion.WithKind(\"HorizontalPodAutoscaler\"):\n\t\treturn \u0026applyconfigurationsautoscalingv1.HorizontalPodAutoscalerApplyConfiguration{}\n\tcase autoscalingv1.SchemeGroupVersion.WithKind(\"HorizontalPodAutoscalerSpec\"):\n\t\treturn \u0026applyconfigurationsautoscalingv1.HorizontalPodAutoscalerSpecApplyConfiguration{}\n\tcase autoscalingv1.SchemeGroupVersion.WithKind(\"HorizontalPodAutoscalerStatus\"):\n\t\treturn \u0026applyconfigurationsautoscalingv1.HorizontalPodAutoscalerStatusApplyConfiguration{}\n\tcase autoscalingv1.SchemeGroupVersion.WithKind(\"Scale\"):\n\t\treturn \u0026applyconfigurationsautoscalingv1.ScaleApplyConfiguration{}\n\tcase autoscalingv1.SchemeGroupVersion.WithKind(\"ScaleSpec\"):\n\t\treturn \u0026applyconfigurationsautoscalingv1.ScaleSpecApplyConfiguration{}\n\tcase autoscalingv1.SchemeGroupVersion.WithKind(\"ScaleStatus\"):\n\t\treturn \u0026applyconfigurationsautoscalingv1.ScaleStatusApplyConfiguration{}\n\n\t\t// Group=autoscaling, Version=v2\n\tcase v2.SchemeGroupVersion.WithKind(\"ContainerResourceMetricSource\"):\n\t\treturn \u0026autoscalingv2.ContainerResourceMetricSourceApplyConfiguration{}\n\tcase v2.SchemeGroupVersion.WithKind(\"ContainerResourceMetricStatus\"):\n\t\treturn \u0026autoscalingv2.ContainerResourceMetricStatusApplyConfiguration{}\n\tcase v2.SchemeGroupVersion.WithKind(\"CrossVersionObjectReference\"):\n\t\treturn \u0026autoscalingv2.CrossVersionObjectReferenceApplyConfiguration{}\n\tcase v2.SchemeGroupVersion.WithKind(\"ExternalMetricSource\"):\n\t\treturn \u0026autoscalingv2.ExternalMetricSourceApplyConfiguration{}\n\tcase v2.SchemeGroupVersion.WithKind(\"ExternalMetricStatus\"):\n\t\treturn \u0026autoscalingv2.ExternalMetricStatusApplyConfiguration{}\n\tcase v2.SchemeGroupVersion.WithKind(\"HorizontalPodAutoscaler\"):\n\t\treturn \u0026autoscalingv2.HorizontalPodAutoscalerApplyConfiguration{}\n\tcase v2.SchemeGroupVersion.WithKind(\"HorizontalPodAutoscalerBehavior\"):\n\t\treturn \u0026autoscalingv2.HorizontalPodAutoscalerBehaviorApplyConfiguration{}\n\tcase v2.SchemeGroupVersion.WithKind(\"HorizontalPodAutoscalerCondition\"):\n\t\treturn \u0026autoscalingv2.HorizontalPodAutoscalerConditionApplyConfiguration{}\n\tcase v2.SchemeGroupVersion.WithKind(\"HorizontalPodAutoscalerSpec\"):\n\t\treturn \u0026autoscalingv2.HorizontalPodAutoscalerSpecApplyConfiguration{}\n\tcase v2.SchemeGroupVersion.WithKind(\"HorizontalPodAutoscalerStatus\"):\n\t\treturn \u0026autoscalingv2.HorizontalPodAutoscalerStatusApplyConfiguration{}\n\tcase v2.SchemeGroupVersion.WithKind(\"HPAScalingPolicy\"):\n\t\treturn \u0026autoscalingv2.HPAScalingPolicyApplyConfiguration{}\n\tcase v2.SchemeGroupVersion.WithKind(\"HPAScalingRules\"):\n\t\treturn \u0026autoscalingv2.HPAScalingRulesApplyConfiguration{}\n\tcase v2.SchemeGroupVersion.WithKind(\"MetricIdentifier\"):\n\t\treturn \u0026autoscalingv2.MetricIdentifierApplyConfiguration{}\n\tcase v2.SchemeGroupVersion.WithKind(\"MetricSpec\"):\n\t\treturn \u0026autoscalingv2.MetricSpecApplyConfiguration{}\n\tcase v2.SchemeGroupVersion.WithKind(\"MetricStatus\"):\n\t\treturn \u0026autoscalingv2.MetricStatusApplyConfiguration{}\n\tcase v2.SchemeGroupVersion.WithKind(\"MetricTarget\"):\n\t\treturn \u0026autoscalingv2.MetricTargetApplyConfiguration{}\n\tcase v2.SchemeGroupVersion.WithKind(\"MetricValueStatus\"):\n\t\treturn \u0026autoscalingv2.MetricValueStatusApplyConfiguration{}\n\tcase v2.SchemeGroupVersion.WithKind(\"ObjectMetricSource\"):\n\t\treturn \u0026autoscalingv2.ObjectMetricSourceApplyConfiguration{}\n\tcase v2.SchemeGroupVersion.WithKind(\"ObjectMetricStatus\"):\n\t\treturn \u0026autoscalingv2.ObjectMetricStatusApplyConfiguration{}\n\tcase v2.SchemeGroupVersion.WithKind(\"PodsMetricSource\"):\n\t\treturn \u0026autoscalingv2.PodsMetricSourceApplyConfiguration{}\n\tcase v2.SchemeGroupVersion.WithKind(\"PodsMetricStatus\"):\n\t\treturn \u0026autoscalingv2.PodsMetricStatusApplyConfiguration{}\n\tcase v2.SchemeGroupVersion.WithKind(\"ResourceMetricSource\"):\n\t\treturn \u0026autoscalingv2.ResourceMetricSourceApplyConfiguration{}\n\tcase v2.SchemeGroupVersion.WithKind(\"ResourceMetricStatus\"):\n\t\treturn \u0026autoscalingv2.ResourceMetricStatusApplyConfiguration{}\n\n\t\t// Group=autoscaling, Version=v2beta1\n\tcase v2beta1.SchemeGroupVersion.WithKind(\"ContainerResourceMetricSource\"):\n\t\treturn \u0026autoscalingv2beta1.ContainerResourceMetricSourceApplyConfiguration{}\n\tcase v2beta1.SchemeGroupVersion.WithKind(\"ContainerResourceMetricStatus\"):\n\t\treturn \u0026autoscalingv2beta1.ContainerResourceMetricStatusApplyConfiguration{}\n\tcase v2beta1.SchemeGroupVersion.WithKind(\"CrossVersionObjectReference\"):\n\t\treturn \u0026autoscalingv2beta1.CrossVersionObjectReferenceApplyConfiguration{}\n\tcase v2beta1.SchemeGroupVersion.WithKind(\"ExternalMetricSource\"):\n\t\treturn \u0026autoscalingv2beta1.ExternalMetricSourceApplyConfiguration{}\n\tcase v2beta1.SchemeGroupVersion.WithKind(\"ExternalMetricStatus\"):\n\t\treturn \u0026autoscalingv2beta1.ExternalMetricStatusApplyConfiguration{}\n\tcase v2beta1.SchemeGroupVersion.WithKind(\"HorizontalPodAutoscaler\"):\n\t\treturn \u0026autoscalingv2beta1.HorizontalPodAutoscalerApplyConfiguration{}\n\tcase v2beta1.SchemeGroupVersion.WithKind(\"HorizontalPodAutoscalerCondition\"):\n\t\treturn \u0026autoscalingv2beta1.HorizontalPodAutoscalerConditionApplyConfiguration{}\n\tcase v2beta1.SchemeGroupVersion.WithKind(\"HorizontalPodAutoscalerSpec\"):\n\t\treturn \u0026autoscalingv2beta1.HorizontalPodAutoscalerSpecApplyConfiguration{}\n\tcase v2beta1.SchemeGroupVersion.WithKind(\"HorizontalPodAutoscalerStatus\"):\n\t\treturn \u0026autoscalingv2beta1.HorizontalPodAutoscalerStatusApplyConfiguration{}\n\tcase v2beta1.SchemeGroupVersion.WithKind(\"MetricSpec\"):\n\t\treturn \u0026autoscalingv2beta1.MetricSpecApplyConfiguration{}\n\tcase v2beta1.SchemeGroupVersion.WithKind(\"MetricStatus\"):\n\t\treturn \u0026autoscalingv2beta1.MetricStatusApplyConfiguration{}\n\tcase v2beta1.SchemeGroupVersion.WithKind(\"ObjectMetricSource\"):\n\t\treturn \u0026autoscalingv2beta1.ObjectMetricSourceApplyConfiguration{}\n\tcase v2beta1.SchemeGroupVersion.WithKind(\"ObjectMetricStatus\"):\n\t\treturn \u0026autoscalingv2beta1.ObjectMetricStatusApplyConfiguration{}\n\tcase v2beta1.SchemeGroupVersion.WithKind(\"PodsMetricSource\"):\n\t\treturn \u0026autoscalingv2beta1.PodsMetricSourceApplyConfiguration{}\n\tcase v2beta1.SchemeGroupVersion.WithKind(\"PodsMetricStatus\"):\n\t\treturn \u0026autoscalingv2beta1.PodsMetricStatusApplyConfiguration{}\n\tcase v2beta1.SchemeGroupVersion.WithKind(\"ResourceMetricSource\"):\n\t\treturn \u0026autoscalingv2beta1.ResourceMetricSourceApplyConfiguration{}\n\tcase v2beta1.SchemeGroupVersion.WithKind(\"ResourceMetricStatus\"):\n\t\treturn \u0026autoscalingv2beta1.ResourceMetricStatusApplyConfiguration{}\n\n\t\t// Group=autoscaling, Version=v2beta2\n\tcase v2beta2.SchemeGroupVersion.WithKind(\"ContainerResourceMetricSource\"):\n\t\treturn \u0026autoscalingv2beta2.ContainerResourceMetricSourceApplyConfiguration{}\n\tcase v2beta2.SchemeGroupVersion.WithKind(\"ContainerResourceMetricStatus\"):\n\t\treturn \u0026autoscalingv2beta2.ContainerResourceMetricStatusApplyConfiguration{}\n\tcase v2beta2.SchemeGroupVersion.WithKind(\"CrossVersionObjectReference\"):\n\t\treturn \u0026autoscalingv2beta2.CrossVersionObjectReferenceApplyConfiguration{}\n\tcase v2beta2.SchemeGroupVersion.WithKind(\"ExternalMetricSource\"):\n\t\treturn \u0026autoscalingv2beta2.ExternalMetricSourceApplyConfiguration{}\n\tcase v2beta2.SchemeGroupVersion.WithKind(\"ExternalMetricStatus\"):\n\t\treturn \u0026autoscalingv2beta2.ExternalMetricStatusApplyConfiguration{}\n\tcase v2beta2.SchemeGroupVersion.WithKind(\"HorizontalPodAutoscaler\"):\n\t\treturn \u0026autoscalingv2beta2.HorizontalPodAutoscalerApplyConfiguration{}\n\tcase v2beta2.SchemeGroupVersion.WithKind(\"HorizontalPodAutoscalerBehavior\"):\n\t\treturn \u0026autoscalingv2beta2.HorizontalPodAutoscalerBehaviorApplyConfiguration{}\n\tcase v2beta2.SchemeGroupVersion.WithKind(\"HorizontalPodAutoscalerCondition\"):\n\t\treturn \u0026autoscalingv2beta2.HorizontalPodAutoscalerConditionApplyConfiguration{}\n\tcase v2beta2.SchemeGroupVersion.WithKind(\"HorizontalPodAutoscalerSpec\"):\n\t\treturn \u0026autoscalingv2beta2.HorizontalPodAutoscalerSpecApplyConfiguration{}\n\tcase v2beta2.SchemeGroupVersion.WithKind(\"HorizontalPodAutoscalerStatus\"):\n\t\treturn \u0026autoscalingv2beta2.HorizontalPodAutoscalerStatusApplyConfiguration{}\n\tcase v2beta2.SchemeGroupVersion.WithKind(\"HPAScalingPolicy\"):\n\t\treturn \u0026autoscalingv2beta2.HPAScalingPolicyApplyConfiguration{}\n\tcase v2beta2.SchemeGroupVersion.WithKind(\"HPAScalingRules\"):\n\t\treturn \u0026autoscalingv2beta2.HPAScalingRulesApplyConfiguration{}\n\tcase v2beta2.SchemeGroupVersion.WithKind(\"MetricIdentifier\"):\n\t\treturn \u0026autoscalingv2beta2.MetricIdentifierApplyConfiguration{}\n\tcase v2beta2.SchemeGroupVersion.WithKind(\"MetricSpec\"):\n\t\treturn \u0026autoscalingv2beta2.MetricSpecApplyConfiguration{}\n\tcase v2beta2.SchemeGroupVersion.WithKind(\"MetricStatus\"):\n\t\treturn \u0026autoscalingv2beta2.MetricStatusApplyConfiguration{}\n\tcase v2beta2.SchemeGroupVersion.WithKind(\"MetricTarget\"):\n\t\treturn \u0026autoscalingv2beta2.MetricTargetApplyConfiguration{}\n\tcase v2beta2.SchemeGroupVersion.WithKind(\"MetricValueStatus\"):\n\t\treturn \u0026autoscalingv2beta2.MetricValueStatusApplyConfiguration{}\n\tcase v2beta2.SchemeGroupVersion.WithKind(\"ObjectMetricSource\"):\n\t\treturn \u0026autoscalingv2beta2.ObjectMetricSourceApplyConfiguration{}\n\tcase v2beta2.SchemeGroupVersion.WithKind(\"ObjectMetricStatus\"):\n\t\treturn \u0026autoscalingv2beta2.ObjectMetricStatusApplyConfiguration{}\n\tcase v2beta2.SchemeGroupVersion.WithKind(\"PodsMetricSource\"):\n\t\treturn \u0026autoscalingv2beta2.PodsMetricSourceApplyConfiguration{}\n\tcase v2beta2.SchemeGroupVersion.WithKind(\"PodsMetricStatus\"):\n\t\treturn \u0026autoscalingv2beta2.PodsMetricStatusApplyConfiguration{}\n\tcase v2beta2.SchemeGroupVersion.WithKind(\"ResourceMetricSource\"):\n\t\treturn \u0026autoscalingv2beta2.ResourceMetricSourceApplyConfiguration{}\n\tcase v2beta2.SchemeGroupVersion.WithKind(\"ResourceMetricStatus\"):\n\t\treturn \u0026autoscalingv2beta2.ResourceMetricStatusApplyConfiguration{}\n\n\t\t// Group=batch, Version=v1\n\tcase batchv1.SchemeGroupVersion.WithKind(\"CronJob\"):\n\t\treturn \u0026applyconfigurationsbatchv1.CronJobApplyConfiguration{}\n\tcase batchv1.SchemeGroupVersion.WithKind(\"CronJobSpec\"):\n\t\treturn \u0026applyconfigurationsbatchv1.CronJobSpecApplyConfiguration{}\n\tcase batchv1.SchemeGroupVersion.WithKind(\"CronJobStatus\"):\n\t\treturn \u0026applyconfigurationsbatchv1.CronJobStatusApplyConfiguration{}\n\tcase batchv1.SchemeGroupVersion.WithKind(\"Job\"):\n\t\treturn \u0026applyconfigurationsbatchv1.JobApplyConfiguration{}\n\tcase batchv1.SchemeGroupVersion.WithKind(\"JobCondition\"):\n\t\treturn \u0026applyconfigurationsbatchv1.JobConditionApplyConfiguration{}\n\tcase batchv1.SchemeGroupVersion.WithKind(\"JobSpec\"):\n\t\treturn \u0026applyconfigurationsbatchv1.JobSpecApplyConfiguration{}\n\tcase batchv1.SchemeGroupVersion.WithKind(\"JobStatus\"):\n\t\treturn \u0026applyconfigurationsbatchv1.JobStatusApplyConfiguration{}\n\tcase batchv1.SchemeGroupVersion.WithKind(\"JobTemplateSpec\"):\n\t\treturn \u0026applyconfigurationsbatchv1.JobTemplateSpecApplyConfiguration{}\n\tcase batchv1.SchemeGroupVersion.WithKind(\"PodFailurePolicy\"):\n\t\treturn \u0026applyconfigurationsbatchv1.PodFailurePolicyApplyConfiguration{}\n\tcase batchv1.SchemeGroupVersion.WithKind(\"PodFailurePolicyOnExitCodesRequirement\"):\n\t\treturn \u0026applyconfigurationsbatchv1.PodFailurePolicyOnExitCodesRequirementApplyConfiguration{}\n\tcase batchv1.SchemeGroupVersion.WithKind(\"PodFailurePolicyOnPodConditionsPattern\"):\n\t\treturn \u0026applyconfigurationsbatchv1.PodFailurePolicyOnPodConditionsPatternApplyConfiguration{}\n\tcase batchv1.SchemeGroupVersion.WithKind(\"PodFailurePolicyRule\"):\n\t\treturn \u0026applyconfigurationsbatchv1.PodFailurePolicyRuleApplyConfiguration{}\n\tcase batchv1.SchemeGroupVersion.WithKind(\"UncountedTerminatedPods\"):\n\t\treturn \u0026applyconfigurationsbatchv1.UncountedTerminatedPodsApplyConfiguration{}\n\n\t\t// Group=batch, Version=v1beta1\n\tcase batchv1beta1.SchemeGroupVersion.WithKind(\"CronJob\"):\n\t\treturn \u0026applyconfigurationsbatchv1beta1.CronJobApplyConfiguration{}\n\tcase batchv1beta1.SchemeGroupVersion.WithKind(\"CronJobSpec\"):\n\t\treturn \u0026applyconfigurationsbatchv1beta1.CronJobSpecApplyConfiguration{}\n\tcase batchv1beta1.SchemeGroupVersion.WithKind(\"CronJobStatus\"):\n\t\treturn \u0026applyconfigurationsbatchv1beta1.CronJobStatusApplyConfiguration{}\n\tcase batchv1beta1.SchemeGroupVersion.WithKind(\"JobTemplateSpec\"):\n\t\treturn \u0026applyconfigurationsbatchv1beta1.JobTemplateSpecApplyConfiguration{}\n\n\t\t// Group=certificates.k8s.io, Version=v1\n\tcase certificatesv1.SchemeGroupVersion.WithKind(\"CertificateSigningRequest\"):\n\t\treturn \u0026applyconfigurationscertificatesv1.CertificateSigningRequestApplyConfiguration{}\n\tcase certificatesv1.SchemeGroupVersion.WithKind(\"CertificateSigningRequestCondition\"):\n\t\treturn \u0026applyconfigurationscertificatesv1.CertificateSigningRequestConditionApplyConfiguration{}\n\tcase certificatesv1.SchemeGroupVersion.WithKind(\"CertificateSigningRequestSpec\"):\n\t\treturn \u0026applyconfigurationscertificatesv1.CertificateSigningRequestSpecApplyConfiguration{}\n\tcase certificatesv1.SchemeGroupVersion.WithKind(\"CertificateSigningRequestStatus\"):\n\t\treturn \u0026applyconfigurationscertificatesv1.CertificateSigningRequestStatusApplyConfiguration{}\n\n\t\t// Group=certificates.k8s.io, Version=v1alpha1\n\tcase certificatesv1alpha1.SchemeGroupVersion.WithKind(\"ClusterTrustBundle\"):\n\t\treturn \u0026applyconfigurationscertificatesv1alpha1.ClusterTrustBundleApplyConfiguration{}\n\tcase certificatesv1alpha1.SchemeGroupVersion.WithKind(\"ClusterTrustBundleSpec\"):\n\t\treturn \u0026applyconfigurationscertificatesv1alpha1.ClusterTrustBundleSpecApplyConfiguration{}\n\n\t\t// Group=certificates.k8s.io, Version=v1beta1\n\tcase certificatesv1beta1.SchemeGroupVersion.WithKind(\"CertificateSigningRequest\"):\n\t\treturn \u0026applyconfigurationscertificatesv1beta1.CertificateSigningRequestApplyConfiguration{}\n\tcase certificatesv1beta1.SchemeGroupVersion.WithKind(\"CertificateSigningRequestCondition\"):\n\t\treturn \u0026applyconfigurationscertificatesv1beta1.CertificateSigningRequestConditionApplyConfiguration{}\n\tcase certificatesv1beta1.SchemeGroupVersion.WithKind(\"CertificateSigningRequestSpec\"):\n\t\treturn \u0026applyconfigurationscertificatesv1beta1.CertificateSigningRequestSpecApplyConfiguration{}\n\tcase certificatesv1beta1.SchemeGroupVersion.WithKind(\"CertificateSigningRequestStatus\"):\n\t\treturn \u0026applyconfigurationscertificatesv1beta1.CertificateSigningRequestStatusApplyConfiguration{}\n\n\t\t// Group=coordination.k8s.io, Version=v1\n\tcase coordinationv1.SchemeGroupVersion.WithKind(\"Lease\"):\n\t\treturn \u0026applyconfigurationscoordinationv1.LeaseApplyConfiguration{}\n\tcase coordinationv1.SchemeGroupVersion.WithKind(\"LeaseSpec\"):\n\t\treturn \u0026applyconfigurationscoordinationv1.LeaseSpecApplyConfiguration{}\n\n\t\t// Group=coordination.k8s.io, Version=v1beta1\n\tcase coordinationv1beta1.SchemeGroupVersion.WithKind(\"Lease\"):\n\t\treturn \u0026applyconfigurationscoordinationv1beta1.LeaseApplyConfiguration{}\n\tcase coordinationv1beta1.SchemeGroupVersion.WithKind(\"LeaseSpec\"):\n\t\treturn \u0026applyconfigurationscoordinationv1beta1.LeaseSpecApplyConfiguration{}\n\n\t\t// Group=core, Version=v1\n\tcase corev1.SchemeGroupVersion.WithKind(\"Affinity\"):\n\t\treturn \u0026applyconfigurationscorev1.AffinityApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"AttachedVolume\"):\n\t\treturn \u0026applyconfigurationscorev1.AttachedVolumeApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"AWSElasticBlockStoreVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.AWSElasticBlockStoreVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"AzureDiskVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.AzureDiskVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"AzureFilePersistentVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.AzureFilePersistentVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"AzureFileVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.AzureFileVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"Capabilities\"):\n\t\treturn \u0026applyconfigurationscorev1.CapabilitiesApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"CephFSPersistentVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.CephFSPersistentVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"CephFSVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.CephFSVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"CinderPersistentVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.CinderPersistentVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"CinderVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.CinderVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ClaimSource\"):\n\t\treturn \u0026applyconfigurationscorev1.ClaimSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ClientIPConfig\"):\n\t\treturn \u0026applyconfigurationscorev1.ClientIPConfigApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ComponentCondition\"):\n\t\treturn \u0026applyconfigurationscorev1.ComponentConditionApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ComponentStatus\"):\n\t\treturn \u0026applyconfigurationscorev1.ComponentStatusApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ConfigMap\"):\n\t\treturn \u0026applyconfigurationscorev1.ConfigMapApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ConfigMapEnvSource\"):\n\t\treturn \u0026applyconfigurationscorev1.ConfigMapEnvSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ConfigMapKeySelector\"):\n\t\treturn \u0026applyconfigurationscorev1.ConfigMapKeySelectorApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ConfigMapNodeConfigSource\"):\n\t\treturn \u0026applyconfigurationscorev1.ConfigMapNodeConfigSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ConfigMapProjection\"):\n\t\treturn \u0026applyconfigurationscorev1.ConfigMapProjectionApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ConfigMapVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.ConfigMapVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"Container\"):\n\t\treturn \u0026applyconfigurationscorev1.ContainerApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ContainerImage\"):\n\t\treturn \u0026applyconfigurationscorev1.ContainerImageApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ContainerPort\"):\n\t\treturn \u0026applyconfigurationscorev1.ContainerPortApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ContainerResizePolicy\"):\n\t\treturn \u0026applyconfigurationscorev1.ContainerResizePolicyApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ContainerState\"):\n\t\treturn \u0026applyconfigurationscorev1.ContainerStateApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ContainerStateRunning\"):\n\t\treturn \u0026applyconfigurationscorev1.ContainerStateRunningApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ContainerStateTerminated\"):\n\t\treturn \u0026applyconfigurationscorev1.ContainerStateTerminatedApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ContainerStateWaiting\"):\n\t\treturn \u0026applyconfigurationscorev1.ContainerStateWaitingApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ContainerStatus\"):\n\t\treturn \u0026applyconfigurationscorev1.ContainerStatusApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"CSIPersistentVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.CSIPersistentVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"CSIVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.CSIVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"DaemonEndpoint\"):\n\t\treturn \u0026applyconfigurationscorev1.DaemonEndpointApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"DownwardAPIProjection\"):\n\t\treturn \u0026applyconfigurationscorev1.DownwardAPIProjectionApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"DownwardAPIVolumeFile\"):\n\t\treturn \u0026applyconfigurationscorev1.DownwardAPIVolumeFileApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"DownwardAPIVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.DownwardAPIVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"EmptyDirVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.EmptyDirVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"EndpointAddress\"):\n\t\treturn \u0026applyconfigurationscorev1.EndpointAddressApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"EndpointPort\"):\n\t\treturn \u0026applyconfigurationscorev1.EndpointPortApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"Endpoints\"):\n\t\treturn \u0026applyconfigurationscorev1.EndpointsApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"EndpointSubset\"):\n\t\treturn \u0026applyconfigurationscorev1.EndpointSubsetApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"EnvFromSource\"):\n\t\treturn \u0026applyconfigurationscorev1.EnvFromSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"EnvVar\"):\n\t\treturn \u0026applyconfigurationscorev1.EnvVarApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"EnvVarSource\"):\n\t\treturn \u0026applyconfigurationscorev1.EnvVarSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"EphemeralContainer\"):\n\t\treturn \u0026applyconfigurationscorev1.EphemeralContainerApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"EphemeralContainerCommon\"):\n\t\treturn \u0026applyconfigurationscorev1.EphemeralContainerCommonApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"EphemeralVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.EphemeralVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"Event\"):\n\t\treturn \u0026applyconfigurationscorev1.EventApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"EventSeries\"):\n\t\treturn \u0026applyconfigurationscorev1.EventSeriesApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"EventSource\"):\n\t\treturn \u0026applyconfigurationscorev1.EventSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ExecAction\"):\n\t\treturn \u0026applyconfigurationscorev1.ExecActionApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"FCVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.FCVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"FlexPersistentVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.FlexPersistentVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"FlexVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.FlexVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"FlockerVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.FlockerVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"GCEPersistentDiskVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.GCEPersistentDiskVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"GitRepoVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.GitRepoVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"GlusterfsPersistentVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.GlusterfsPersistentVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"GlusterfsVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.GlusterfsVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"GRPCAction\"):\n\t\treturn \u0026applyconfigurationscorev1.GRPCActionApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"HostAlias\"):\n\t\treturn \u0026applyconfigurationscorev1.HostAliasApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"HostPathVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.HostPathVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"HTTPGetAction\"):\n\t\treturn \u0026applyconfigurationscorev1.HTTPGetActionApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"HTTPHeader\"):\n\t\treturn \u0026applyconfigurationscorev1.HTTPHeaderApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ISCSIPersistentVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.ISCSIPersistentVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ISCSIVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.ISCSIVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"KeyToPath\"):\n\t\treturn \u0026applyconfigurationscorev1.KeyToPathApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"Lifecycle\"):\n\t\treturn \u0026applyconfigurationscorev1.LifecycleApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"LifecycleHandler\"):\n\t\treturn \u0026applyconfigurationscorev1.LifecycleHandlerApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"LimitRange\"):\n\t\treturn \u0026applyconfigurationscorev1.LimitRangeApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"LimitRangeItem\"):\n\t\treturn \u0026applyconfigurationscorev1.LimitRangeItemApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"LimitRangeSpec\"):\n\t\treturn \u0026applyconfigurationscorev1.LimitRangeSpecApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"LoadBalancerIngress\"):\n\t\treturn \u0026applyconfigurationscorev1.LoadBalancerIngressApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"LoadBalancerStatus\"):\n\t\treturn \u0026applyconfigurationscorev1.LoadBalancerStatusApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"LocalObjectReference\"):\n\t\treturn \u0026applyconfigurationscorev1.LocalObjectReferenceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"LocalVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.LocalVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"Namespace\"):\n\t\treturn \u0026applyconfigurationscorev1.NamespaceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"NamespaceCondition\"):\n\t\treturn \u0026applyconfigurationscorev1.NamespaceConditionApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"NamespaceSpec\"):\n\t\treturn \u0026applyconfigurationscorev1.NamespaceSpecApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"NamespaceStatus\"):\n\t\treturn \u0026applyconfigurationscorev1.NamespaceStatusApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"NFSVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.NFSVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"Node\"):\n\t\treturn \u0026applyconfigurationscorev1.NodeApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"NodeAddress\"):\n\t\treturn \u0026applyconfigurationscorev1.NodeAddressApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"NodeAffinity\"):\n\t\treturn \u0026applyconfigurationscorev1.NodeAffinityApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"NodeCondition\"):\n\t\treturn \u0026applyconfigurationscorev1.NodeConditionApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"NodeConfigSource\"):\n\t\treturn \u0026applyconfigurationscorev1.NodeConfigSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"NodeConfigStatus\"):\n\t\treturn \u0026applyconfigurationscorev1.NodeConfigStatusApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"NodeDaemonEndpoints\"):\n\t\treturn \u0026applyconfigurationscorev1.NodeDaemonEndpointsApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"NodeSelector\"):\n\t\treturn \u0026applyconfigurationscorev1.NodeSelectorApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"NodeSelectorRequirement\"):\n\t\treturn \u0026applyconfigurationscorev1.NodeSelectorRequirementApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"NodeSelectorTerm\"):\n\t\treturn \u0026applyconfigurationscorev1.NodeSelectorTermApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"NodeSpec\"):\n\t\treturn \u0026applyconfigurationscorev1.NodeSpecApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"NodeStatus\"):\n\t\treturn \u0026applyconfigurationscorev1.NodeStatusApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"NodeSystemInfo\"):\n\t\treturn \u0026applyconfigurationscorev1.NodeSystemInfoApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ObjectFieldSelector\"):\n\t\treturn \u0026applyconfigurationscorev1.ObjectFieldSelectorApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ObjectReference\"):\n\t\treturn \u0026applyconfigurationscorev1.ObjectReferenceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PersistentVolume\"):\n\t\treturn \u0026applyconfigurationscorev1.PersistentVolumeApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PersistentVolumeClaim\"):\n\t\treturn \u0026applyconfigurationscorev1.PersistentVolumeClaimApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PersistentVolumeClaimCondition\"):\n\t\treturn \u0026applyconfigurationscorev1.PersistentVolumeClaimConditionApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PersistentVolumeClaimSpec\"):\n\t\treturn \u0026applyconfigurationscorev1.PersistentVolumeClaimSpecApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PersistentVolumeClaimStatus\"):\n\t\treturn \u0026applyconfigurationscorev1.PersistentVolumeClaimStatusApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PersistentVolumeClaimTemplate\"):\n\t\treturn \u0026applyconfigurationscorev1.PersistentVolumeClaimTemplateApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PersistentVolumeClaimVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.PersistentVolumeClaimVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PersistentVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.PersistentVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PersistentVolumeSpec\"):\n\t\treturn \u0026applyconfigurationscorev1.PersistentVolumeSpecApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PersistentVolumeStatus\"):\n\t\treturn \u0026applyconfigurationscorev1.PersistentVolumeStatusApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PhotonPersistentDiskVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.PhotonPersistentDiskVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"Pod\"):\n\t\treturn \u0026applyconfigurationscorev1.PodApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PodAffinity\"):\n\t\treturn \u0026applyconfigurationscorev1.PodAffinityApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PodAffinityTerm\"):\n\t\treturn \u0026applyconfigurationscorev1.PodAffinityTermApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PodAntiAffinity\"):\n\t\treturn \u0026applyconfigurationscorev1.PodAntiAffinityApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PodCondition\"):\n\t\treturn \u0026applyconfigurationscorev1.PodConditionApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PodDNSConfig\"):\n\t\treturn \u0026applyconfigurationscorev1.PodDNSConfigApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PodDNSConfigOption\"):\n\t\treturn \u0026applyconfigurationscorev1.PodDNSConfigOptionApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PodIP\"):\n\t\treturn \u0026applyconfigurationscorev1.PodIPApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PodOS\"):\n\t\treturn \u0026applyconfigurationscorev1.PodOSApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PodReadinessGate\"):\n\t\treturn \u0026applyconfigurationscorev1.PodReadinessGateApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PodResourceClaim\"):\n\t\treturn \u0026applyconfigurationscorev1.PodResourceClaimApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PodSchedulingGate\"):\n\t\treturn \u0026applyconfigurationscorev1.PodSchedulingGateApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PodSecurityContext\"):\n\t\treturn \u0026applyconfigurationscorev1.PodSecurityContextApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PodSpec\"):\n\t\treturn \u0026applyconfigurationscorev1.PodSpecApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PodStatus\"):\n\t\treturn \u0026applyconfigurationscorev1.PodStatusApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PodTemplate\"):\n\t\treturn \u0026applyconfigurationscorev1.PodTemplateApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PodTemplateSpec\"):\n\t\treturn \u0026applyconfigurationscorev1.PodTemplateSpecApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PortStatus\"):\n\t\treturn \u0026applyconfigurationscorev1.PortStatusApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PortworxVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.PortworxVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"PreferredSchedulingTerm\"):\n\t\treturn \u0026applyconfigurationscorev1.PreferredSchedulingTermApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"Probe\"):\n\t\treturn \u0026applyconfigurationscorev1.ProbeApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ProbeHandler\"):\n\t\treturn \u0026applyconfigurationscorev1.ProbeHandlerApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ProjectedVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.ProjectedVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"QuobyteVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.QuobyteVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"RBDPersistentVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.RBDPersistentVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"RBDVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.RBDVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ReplicationController\"):\n\t\treturn \u0026applyconfigurationscorev1.ReplicationControllerApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ReplicationControllerCondition\"):\n\t\treturn \u0026applyconfigurationscorev1.ReplicationControllerConditionApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ReplicationControllerSpec\"):\n\t\treturn \u0026applyconfigurationscorev1.ReplicationControllerSpecApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ReplicationControllerStatus\"):\n\t\treturn \u0026applyconfigurationscorev1.ReplicationControllerStatusApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ResourceClaim\"):\n\t\treturn \u0026applyconfigurationscorev1.ResourceClaimApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ResourceFieldSelector\"):\n\t\treturn \u0026applyconfigurationscorev1.ResourceFieldSelectorApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ResourceQuota\"):\n\t\treturn \u0026applyconfigurationscorev1.ResourceQuotaApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ResourceQuotaSpec\"):\n\t\treturn \u0026applyconfigurationscorev1.ResourceQuotaSpecApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ResourceQuotaStatus\"):\n\t\treturn \u0026applyconfigurationscorev1.ResourceQuotaStatusApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ResourceRequirements\"):\n\t\treturn \u0026applyconfigurationscorev1.ResourceRequirementsApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ScaleIOPersistentVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.ScaleIOPersistentVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ScaleIOVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.ScaleIOVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ScopedResourceSelectorRequirement\"):\n\t\treturn \u0026applyconfigurationscorev1.ScopedResourceSelectorRequirementApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ScopeSelector\"):\n\t\treturn \u0026applyconfigurationscorev1.ScopeSelectorApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"SeccompProfile\"):\n\t\treturn \u0026applyconfigurationscorev1.SeccompProfileApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"Secret\"):\n\t\treturn \u0026applyconfigurationscorev1.SecretApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"SecretEnvSource\"):\n\t\treturn \u0026applyconfigurationscorev1.SecretEnvSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"SecretKeySelector\"):\n\t\treturn \u0026applyconfigurationscorev1.SecretKeySelectorApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"SecretProjection\"):\n\t\treturn \u0026applyconfigurationscorev1.SecretProjectionApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"SecretReference\"):\n\t\treturn \u0026applyconfigurationscorev1.SecretReferenceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"SecretVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.SecretVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"SecurityContext\"):\n\t\treturn \u0026applyconfigurationscorev1.SecurityContextApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"SELinuxOptions\"):\n\t\treturn \u0026applyconfigurationscorev1.SELinuxOptionsApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"Service\"):\n\t\treturn \u0026applyconfigurationscorev1.ServiceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ServiceAccount\"):\n\t\treturn \u0026applyconfigurationscorev1.ServiceAccountApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ServiceAccountTokenProjection\"):\n\t\treturn \u0026applyconfigurationscorev1.ServiceAccountTokenProjectionApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ServicePort\"):\n\t\treturn \u0026applyconfigurationscorev1.ServicePortApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ServiceSpec\"):\n\t\treturn \u0026applyconfigurationscorev1.ServiceSpecApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"ServiceStatus\"):\n\t\treturn \u0026applyconfigurationscorev1.ServiceStatusApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"SessionAffinityConfig\"):\n\t\treturn \u0026applyconfigurationscorev1.SessionAffinityConfigApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"StorageOSPersistentVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.StorageOSPersistentVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"StorageOSVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.StorageOSVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"Sysctl\"):\n\t\treturn \u0026applyconfigurationscorev1.SysctlApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"Taint\"):\n\t\treturn \u0026applyconfigurationscorev1.TaintApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"TCPSocketAction\"):\n\t\treturn \u0026applyconfigurationscorev1.TCPSocketActionApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"Toleration\"):\n\t\treturn \u0026applyconfigurationscorev1.TolerationApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"TopologySelectorLabelRequirement\"):\n\t\treturn \u0026applyconfigurationscorev1.TopologySelectorLabelRequirementApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"TopologySelectorTerm\"):\n\t\treturn \u0026applyconfigurationscorev1.TopologySelectorTermApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"TopologySpreadConstraint\"):\n\t\treturn \u0026applyconfigurationscorev1.TopologySpreadConstraintApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"TypedLocalObjectReference\"):\n\t\treturn \u0026applyconfigurationscorev1.TypedLocalObjectReferenceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"TypedObjectReference\"):\n\t\treturn \u0026applyconfigurationscorev1.TypedObjectReferenceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"Volume\"):\n\t\treturn \u0026applyconfigurationscorev1.VolumeApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"VolumeDevice\"):\n\t\treturn \u0026applyconfigurationscorev1.VolumeDeviceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"VolumeMount\"):\n\t\treturn \u0026applyconfigurationscorev1.VolumeMountApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"VolumeNodeAffinity\"):\n\t\treturn \u0026applyconfigurationscorev1.VolumeNodeAffinityApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"VolumeProjection\"):\n\t\treturn \u0026applyconfigurationscorev1.VolumeProjectionApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"VolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.VolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"VsphereVirtualDiskVolumeSource\"):\n\t\treturn \u0026applyconfigurationscorev1.VsphereVirtualDiskVolumeSourceApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"WeightedPodAffinityTerm\"):\n\t\treturn \u0026applyconfigurationscorev1.WeightedPodAffinityTermApplyConfiguration{}\n\tcase corev1.SchemeGroupVersion.WithKind(\"WindowsSecurityContextOptions\"):\n\t\treturn \u0026applyconfigurationscorev1.WindowsSecurityContextOptionsApplyConfiguration{}\n\n\t\t// Group=discovery.k8s.io, Version=v1\n\tcase discoveryv1.SchemeGroupVersion.WithKind(\"Endpoint\"):\n\t\treturn \u0026applyconfigurationsdiscoveryv1.EndpointApplyConfiguration{}\n\tcase discoveryv1.SchemeGroupVersion.WithKind(\"EndpointConditions\"):\n\t\treturn \u0026applyconfigurationsdiscoveryv1.EndpointConditionsApplyConfiguration{}\n\tcase discoveryv1.SchemeGroupVersion.WithKind(\"EndpointHints\"):\n\t\treturn \u0026applyconfigurationsdiscoveryv1.EndpointHintsApplyConfiguration{}\n\tcase discoveryv1.SchemeGroupVersion.WithKind(\"EndpointPort\"):\n\t\treturn \u0026applyconfigurationsdiscoveryv1.EndpointPortApplyConfiguration{}\n\tcase discoveryv1.SchemeGroupVersion.WithKind(\"EndpointSlice\"):\n\t\treturn \u0026applyconfigurationsdiscoveryv1.EndpointSliceApplyConfiguration{}\n\tcase discoveryv1.SchemeGroupVersion.WithKind(\"ForZone\"):\n\t\treturn \u0026applyconfigurationsdiscoveryv1.ForZoneApplyConfiguration{}\n\n\t\t// Group=discovery.k8s.io, Version=v1beta1\n\tcase discoveryv1beta1.SchemeGroupVersion.WithKind(\"Endpoint\"):\n\t\treturn \u0026applyconfigurationsdiscoveryv1beta1.EndpointApplyConfiguration{}\n\tcase discoveryv1beta1.SchemeGroupVersion.WithKind(\"EndpointConditions\"):\n\t\treturn \u0026applyconfigurationsdiscoveryv1beta1.EndpointConditionsApplyConfiguration{}\n\tcase discoveryv1beta1.SchemeGroupVersion.WithKind(\"EndpointHints\"):\n\t\treturn \u0026applyconfigurationsdiscoveryv1beta1.EndpointHintsApplyConfiguration{}\n\tcase discoveryv1beta1.SchemeGroupVersion.WithKind(\"EndpointPort\"):\n\t\treturn \u0026applyconfigurationsdiscoveryv1beta1.EndpointPortApplyConfiguration{}\n\tcase discoveryv1beta1.SchemeGroupVersion.WithKind(\"EndpointSlice\"):\n\t\treturn \u0026applyconfigurationsdiscoveryv1beta1.EndpointSliceApplyConfiguration{}\n\tcase discoveryv1beta1.SchemeGroupVersion.WithKind(\"ForZone\"):\n\t\treturn \u0026applyconfigurationsdiscoveryv1beta1.ForZoneApplyConfiguration{}\n\n\t\t// Group=events.k8s.io, Version=v1\n\tcase eventsv1.SchemeGroupVersion.WithKind(\"Event\"):\n\t\treturn \u0026applyconfigurationseventsv1.EventApplyConfiguration{}\n\tcase eventsv1.SchemeGroupVersion.WithKind(\"EventSeries\"):\n\t\treturn \u0026applyconfigurationseventsv1.EventSeriesApplyConfiguration{}\n\n\t\t// Group=events.k8s.io, Version=v1beta1\n\tcase eventsv1beta1.SchemeGroupVersion.WithKind(\"Event\"):\n\t\treturn \u0026applyconfigurationseventsv1beta1.EventApplyConfiguration{}\n\tcase eventsv1beta1.SchemeGroupVersion.WithKind(\"EventSeries\"):\n\t\treturn \u0026applyconfigurationseventsv1beta1.EventSeriesApplyConfiguration{}\n\n\t\t// Group=extensions, Version=v1beta1\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"DaemonSet\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.DaemonSetApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"DaemonSetCondition\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.DaemonSetConditionApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"DaemonSetSpec\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.DaemonSetSpecApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"DaemonSetStatus\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.DaemonSetStatusApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"DaemonSetUpdateStrategy\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.DaemonSetUpdateStrategyApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"Deployment\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.DeploymentApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"DeploymentCondition\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.DeploymentConditionApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"DeploymentSpec\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.DeploymentSpecApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"DeploymentStatus\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.DeploymentStatusApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"DeploymentStrategy\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.DeploymentStrategyApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"HTTPIngressPath\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.HTTPIngressPathApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"HTTPIngressRuleValue\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.HTTPIngressRuleValueApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"Ingress\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.IngressApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"IngressBackend\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.IngressBackendApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"IngressLoadBalancerIngress\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.IngressLoadBalancerIngressApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"IngressLoadBalancerStatus\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.IngressLoadBalancerStatusApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"IngressPortStatus\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.IngressPortStatusApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"IngressRule\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.IngressRuleApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"IngressRuleValue\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.IngressRuleValueApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"IngressSpec\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.IngressSpecApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"IngressStatus\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.IngressStatusApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"IngressTLS\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.IngressTLSApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"IPBlock\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.IPBlockApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"NetworkPolicy\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.NetworkPolicyApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"NetworkPolicyEgressRule\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.NetworkPolicyEgressRuleApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"NetworkPolicyIngressRule\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.NetworkPolicyIngressRuleApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"NetworkPolicyPeer\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.NetworkPolicyPeerApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"NetworkPolicyPort\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.NetworkPolicyPortApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"NetworkPolicySpec\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.NetworkPolicySpecApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"NetworkPolicyStatus\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.NetworkPolicyStatusApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"ReplicaSet\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.ReplicaSetApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"ReplicaSetCondition\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.ReplicaSetConditionApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"ReplicaSetSpec\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.ReplicaSetSpecApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"ReplicaSetStatus\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.ReplicaSetStatusApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"RollbackConfig\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.RollbackConfigApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"RollingUpdateDaemonSet\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.RollingUpdateDaemonSetApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"RollingUpdateDeployment\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.RollingUpdateDeploymentApplyConfiguration{}\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"Scale\"):\n\t\treturn \u0026applyconfigurationsextensionsv1beta1.ScaleApplyConfiguration{}\n\n\t\t// Group=flowcontrol.apiserver.k8s.io, Version=v1alpha1\n\tcase flowcontrolv1alpha1.SchemeGroupVersion.WithKind(\"FlowDistinguisherMethod\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1alpha1.FlowDistinguisherMethodApplyConfiguration{}\n\tcase flowcontrolv1alpha1.SchemeGroupVersion.WithKind(\"FlowSchema\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1alpha1.FlowSchemaApplyConfiguration{}\n\tcase flowcontrolv1alpha1.SchemeGroupVersion.WithKind(\"FlowSchemaCondition\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1alpha1.FlowSchemaConditionApplyConfiguration{}\n\tcase flowcontrolv1alpha1.SchemeGroupVersion.WithKind(\"FlowSchemaSpec\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1alpha1.FlowSchemaSpecApplyConfiguration{}\n\tcase flowcontrolv1alpha1.SchemeGroupVersion.WithKind(\"FlowSchemaStatus\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1alpha1.FlowSchemaStatusApplyConfiguration{}\n\tcase flowcontrolv1alpha1.SchemeGroupVersion.WithKind(\"GroupSubject\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1alpha1.GroupSubjectApplyConfiguration{}\n\tcase flowcontrolv1alpha1.SchemeGroupVersion.WithKind(\"LimitedPriorityLevelConfiguration\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1alpha1.LimitedPriorityLevelConfigurationApplyConfiguration{}\n\tcase flowcontrolv1alpha1.SchemeGroupVersion.WithKind(\"LimitResponse\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1alpha1.LimitResponseApplyConfiguration{}\n\tcase flowcontrolv1alpha1.SchemeGroupVersion.WithKind(\"NonResourcePolicyRule\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1alpha1.NonResourcePolicyRuleApplyConfiguration{}\n\tcase flowcontrolv1alpha1.SchemeGroupVersion.WithKind(\"PolicyRulesWithSubjects\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1alpha1.PolicyRulesWithSubjectsApplyConfiguration{}\n\tcase flowcontrolv1alpha1.SchemeGroupVersion.WithKind(\"PriorityLevelConfiguration\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1alpha1.PriorityLevelConfigurationApplyConfiguration{}\n\tcase flowcontrolv1alpha1.SchemeGroupVersion.WithKind(\"PriorityLevelConfigurationCondition\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1alpha1.PriorityLevelConfigurationConditionApplyConfiguration{}\n\tcase flowcontrolv1alpha1.SchemeGroupVersion.WithKind(\"PriorityLevelConfigurationReference\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1alpha1.PriorityLevelConfigurationReferenceApplyConfiguration{}\n\tcase flowcontrolv1alpha1.SchemeGroupVersion.WithKind(\"PriorityLevelConfigurationSpec\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1alpha1.PriorityLevelConfigurationSpecApplyConfiguration{}\n\tcase flowcontrolv1alpha1.SchemeGroupVersion.WithKind(\"PriorityLevelConfigurationStatus\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1alpha1.PriorityLevelConfigurationStatusApplyConfiguration{}\n\tcase flowcontrolv1alpha1.SchemeGroupVersion.WithKind(\"QueuingConfiguration\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1alpha1.QueuingConfigurationApplyConfiguration{}\n\tcase flowcontrolv1alpha1.SchemeGroupVersion.WithKind(\"ResourcePolicyRule\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1alpha1.ResourcePolicyRuleApplyConfiguration{}\n\tcase flowcontrolv1alpha1.SchemeGroupVersion.WithKind(\"ServiceAccountSubject\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1alpha1.ServiceAccountSubjectApplyConfiguration{}\n\tcase flowcontrolv1alpha1.SchemeGroupVersion.WithKind(\"Subject\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1alpha1.SubjectApplyConfiguration{}\n\tcase flowcontrolv1alpha1.SchemeGroupVersion.WithKind(\"UserSubject\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1alpha1.UserSubjectApplyConfiguration{}\n\n\t\t// Group=flowcontrol.apiserver.k8s.io, Version=v1beta1\n\tcase flowcontrolv1beta1.SchemeGroupVersion.WithKind(\"FlowDistinguisherMethod\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta1.FlowDistinguisherMethodApplyConfiguration{}\n\tcase flowcontrolv1beta1.SchemeGroupVersion.WithKind(\"FlowSchema\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta1.FlowSchemaApplyConfiguration{}\n\tcase flowcontrolv1beta1.SchemeGroupVersion.WithKind(\"FlowSchemaCondition\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta1.FlowSchemaConditionApplyConfiguration{}\n\tcase flowcontrolv1beta1.SchemeGroupVersion.WithKind(\"FlowSchemaSpec\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta1.FlowSchemaSpecApplyConfiguration{}\n\tcase flowcontrolv1beta1.SchemeGroupVersion.WithKind(\"FlowSchemaStatus\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta1.FlowSchemaStatusApplyConfiguration{}\n\tcase flowcontrolv1beta1.SchemeGroupVersion.WithKind(\"GroupSubject\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta1.GroupSubjectApplyConfiguration{}\n\tcase flowcontrolv1beta1.SchemeGroupVersion.WithKind(\"LimitedPriorityLevelConfiguration\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta1.LimitedPriorityLevelConfigurationApplyConfiguration{}\n\tcase flowcontrolv1beta1.SchemeGroupVersion.WithKind(\"LimitResponse\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta1.LimitResponseApplyConfiguration{}\n\tcase flowcontrolv1beta1.SchemeGroupVersion.WithKind(\"NonResourcePolicyRule\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta1.NonResourcePolicyRuleApplyConfiguration{}\n\tcase flowcontrolv1beta1.SchemeGroupVersion.WithKind(\"PolicyRulesWithSubjects\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta1.PolicyRulesWithSubjectsApplyConfiguration{}\n\tcase flowcontrolv1beta1.SchemeGroupVersion.WithKind(\"PriorityLevelConfiguration\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta1.PriorityLevelConfigurationApplyConfiguration{}\n\tcase flowcontrolv1beta1.SchemeGroupVersion.WithKind(\"PriorityLevelConfigurationCondition\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta1.PriorityLevelConfigurationConditionApplyConfiguration{}\n\tcase flowcontrolv1beta1.SchemeGroupVersion.WithKind(\"PriorityLevelConfigurationReference\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta1.PriorityLevelConfigurationReferenceApplyConfiguration{}\n\tcase flowcontrolv1beta1.SchemeGroupVersion.WithKind(\"PriorityLevelConfigurationSpec\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta1.PriorityLevelConfigurationSpecApplyConfiguration{}\n\tcase flowcontrolv1beta1.SchemeGroupVersion.WithKind(\"PriorityLevelConfigurationStatus\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta1.PriorityLevelConfigurationStatusApplyConfiguration{}\n\tcase flowcontrolv1beta1.SchemeGroupVersion.WithKind(\"QueuingConfiguration\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta1.QueuingConfigurationApplyConfiguration{}\n\tcase flowcontrolv1beta1.SchemeGroupVersion.WithKind(\"ResourcePolicyRule\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta1.ResourcePolicyRuleApplyConfiguration{}\n\tcase flowcontrolv1beta1.SchemeGroupVersion.WithKind(\"ServiceAccountSubject\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta1.ServiceAccountSubjectApplyConfiguration{}\n\tcase flowcontrolv1beta1.SchemeGroupVersion.WithKind(\"Subject\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta1.SubjectApplyConfiguration{}\n\tcase flowcontrolv1beta1.SchemeGroupVersion.WithKind(\"UserSubject\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta1.UserSubjectApplyConfiguration{}\n\n\t\t// Group=flowcontrol.apiserver.k8s.io, Version=v1beta2\n\tcase flowcontrolv1beta2.SchemeGroupVersion.WithKind(\"FlowDistinguisherMethod\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta2.FlowDistinguisherMethodApplyConfiguration{}\n\tcase flowcontrolv1beta2.SchemeGroupVersion.WithKind(\"FlowSchema\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta2.FlowSchemaApplyConfiguration{}\n\tcase flowcontrolv1beta2.SchemeGroupVersion.WithKind(\"FlowSchemaCondition\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta2.FlowSchemaConditionApplyConfiguration{}\n\tcase flowcontrolv1beta2.SchemeGroupVersion.WithKind(\"FlowSchemaSpec\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta2.FlowSchemaSpecApplyConfiguration{}\n\tcase flowcontrolv1beta2.SchemeGroupVersion.WithKind(\"FlowSchemaStatus\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta2.FlowSchemaStatusApplyConfiguration{}\n\tcase flowcontrolv1beta2.SchemeGroupVersion.WithKind(\"GroupSubject\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta2.GroupSubjectApplyConfiguration{}\n\tcase flowcontrolv1beta2.SchemeGroupVersion.WithKind(\"LimitedPriorityLevelConfiguration\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta2.LimitedPriorityLevelConfigurationApplyConfiguration{}\n\tcase flowcontrolv1beta2.SchemeGroupVersion.WithKind(\"LimitResponse\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta2.LimitResponseApplyConfiguration{}\n\tcase flowcontrolv1beta2.SchemeGroupVersion.WithKind(\"NonResourcePolicyRule\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta2.NonResourcePolicyRuleApplyConfiguration{}\n\tcase flowcontrolv1beta2.SchemeGroupVersion.WithKind(\"PolicyRulesWithSubjects\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta2.PolicyRulesWithSubjectsApplyConfiguration{}\n\tcase flowcontrolv1beta2.SchemeGroupVersion.WithKind(\"PriorityLevelConfiguration\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta2.PriorityLevelConfigurationApplyConfiguration{}\n\tcase flowcontrolv1beta2.SchemeGroupVersion.WithKind(\"PriorityLevelConfigurationCondition\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta2.PriorityLevelConfigurationConditionApplyConfiguration{}\n\tcase flowcontrolv1beta2.SchemeGroupVersion.WithKind(\"PriorityLevelConfigurationReference\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta2.PriorityLevelConfigurationReferenceApplyConfiguration{}\n\tcase flowcontrolv1beta2.SchemeGroupVersion.WithKind(\"PriorityLevelConfigurationSpec\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta2.PriorityLevelConfigurationSpecApplyConfiguration{}\n\tcase flowcontrolv1beta2.SchemeGroupVersion.WithKind(\"PriorityLevelConfigurationStatus\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta2.PriorityLevelConfigurationStatusApplyConfiguration{}\n\tcase flowcontrolv1beta2.SchemeGroupVersion.WithKind(\"QueuingConfiguration\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta2.QueuingConfigurationApplyConfiguration{}\n\tcase flowcontrolv1beta2.SchemeGroupVersion.WithKind(\"ResourcePolicyRule\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta2.ResourcePolicyRuleApplyConfiguration{}\n\tcase flowcontrolv1beta2.SchemeGroupVersion.WithKind(\"ServiceAccountSubject\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta2.ServiceAccountSubjectApplyConfiguration{}\n\tcase flowcontrolv1beta2.SchemeGroupVersion.WithKind(\"Subject\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta2.SubjectApplyConfiguration{}\n\tcase flowcontrolv1beta2.SchemeGroupVersion.WithKind(\"UserSubject\"):\n\t\treturn \u0026applyconfigurationsflowcontrolv1beta2.UserSubjectApplyConfiguration{}\n\n\t\t// Group=flowcontrol.apiserver.k8s.io, Version=v1beta3\n\tcase v1beta3.SchemeGroupVersion.WithKind(\"FlowDistinguisherMethod\"):\n\t\treturn \u0026flowcontrolv1beta3.FlowDistinguisherMethodApplyConfiguration{}\n\tcase v1beta3.SchemeGroupVersion.WithKind(\"FlowSchema\"):\n\t\treturn \u0026flowcontrolv1beta3.FlowSchemaApplyConfiguration{}\n\tcase v1beta3.SchemeGroupVersion.WithKind(\"FlowSchemaCondition\"):\n\t\treturn \u0026flowcontrolv1beta3.FlowSchemaConditionApplyConfiguration{}\n\tcase v1beta3.SchemeGroupVersion.WithKind(\"FlowSchemaSpec\"):\n\t\treturn \u0026flowcontrolv1beta3.FlowSchemaSpecApplyConfiguration{}\n\tcase v1beta3.SchemeGroupVersion.WithKind(\"FlowSchemaStatus\"):\n\t\treturn \u0026flowcontrolv1beta3.FlowSchemaStatusApplyConfiguration{}\n\tcase v1beta3.SchemeGroupVersion.WithKind(\"GroupSubject\"):\n\t\treturn \u0026flowcontrolv1beta3.GroupSubjectApplyConfiguration{}\n\tcase v1beta3.SchemeGroupVersion.WithKind(\"LimitedPriorityLevelConfiguration\"):\n\t\treturn \u0026flowcontrolv1beta3.LimitedPriorityLevelConfigurationApplyConfiguration{}\n\tcase v1beta3.SchemeGroupVersion.WithKind(\"LimitResponse\"):\n\t\treturn \u0026flowcontrolv1beta3.LimitResponseApplyConfiguration{}\n\tcase v1beta3.SchemeGroupVersion.WithKind(\"NonResourcePolicyRule\"):\n\t\treturn \u0026flowcontrolv1beta3.NonResourcePolicyRuleApplyConfiguration{}\n\tcase v1beta3.SchemeGroupVersion.WithKind(\"PolicyRulesWithSubjects\"):\n\t\treturn \u0026flowcontrolv1beta3.PolicyRulesWithSubjectsApplyConfiguration{}\n\tcase v1beta3.SchemeGroupVersion.WithKind(\"PriorityLevelConfiguration\"):\n\t\treturn \u0026flowcontrolv1beta3.PriorityLevelConfigurationApplyConfiguration{}\n\tcase v1beta3.SchemeGroupVersion.WithKind(\"PriorityLevelConfigurationCondition\"):\n\t\treturn \u0026flowcontrolv1beta3.PriorityLevelConfigurationConditionApplyConfiguration{}\n\tcase v1beta3.SchemeGroupVersion.WithKind(\"PriorityLevelConfigurationReference\"):\n\t\treturn \u0026flowcontrolv1beta3.PriorityLevelConfigurationReferenceApplyConfiguration{}\n\tcase v1beta3.SchemeGroupVersion.WithKind(\"PriorityLevelConfigurationSpec\"):\n\t\treturn \u0026flowcontrolv1beta3.PriorityLevelConfigurationSpecApplyConfiguration{}\n\tcase v1beta3.SchemeGroupVersion.WithKind(\"PriorityLevelConfigurationStatus\"):\n\t\treturn \u0026flowcontrolv1beta3.PriorityLevelConfigurationStatusApplyConfiguration{}\n\tcase v1beta3.SchemeGroupVersion.WithKind(\"QueuingConfiguration\"):\n\t\treturn \u0026flowcontrolv1beta3.QueuingConfigurationApplyConfiguration{}\n\tcase v1beta3.SchemeGroupVersion.WithKind(\"ResourcePolicyRule\"):\n\t\treturn \u0026flowcontrolv1beta3.ResourcePolicyRuleApplyConfiguration{}\n\tcase v1beta3.SchemeGroupVersion.WithKind(\"ServiceAccountSubject\"):\n\t\treturn \u0026flowcontrolv1beta3.ServiceAccountSubjectApplyConfiguration{}\n\tcase v1beta3.SchemeGroupVersion.WithKind(\"Subject\"):\n\t\treturn \u0026flowcontrolv1beta3.SubjectApplyConfiguration{}\n\tcase v1beta3.SchemeGroupVersion.WithKind(\"UserSubject\"):\n\t\treturn \u0026flowcontrolv1beta3.UserSubjectApplyConfiguration{}\n\n\t\t// Group=imagepolicy.k8s.io, Version=v1alpha1\n\tcase imagepolicyv1alpha1.SchemeGroupVersion.WithKind(\"ImageReview\"):\n\t\treturn \u0026applyconfigurationsimagepolicyv1alpha1.ImageReviewApplyConfiguration{}\n\tcase imagepolicyv1alpha1.SchemeGroupVersion.WithKind(\"ImageReviewContainerSpec\"):\n\t\treturn \u0026applyconfigurationsimagepolicyv1alpha1.ImageReviewContainerSpecApplyConfiguration{}\n\tcase imagepolicyv1alpha1.SchemeGroupVersion.WithKind(\"ImageReviewSpec\"):\n\t\treturn \u0026applyconfigurationsimagepolicyv1alpha1.ImageReviewSpecApplyConfiguration{}\n\tcase imagepolicyv1alpha1.SchemeGroupVersion.WithKind(\"ImageReviewStatus\"):\n\t\treturn \u0026applyconfigurationsimagepolicyv1alpha1.ImageReviewStatusApplyConfiguration{}\n\n\t\t// Group=internal.apiserver.k8s.io, Version=v1alpha1\n\tcase apiserverinternalv1alpha1.SchemeGroupVersion.WithKind(\"ServerStorageVersion\"):\n\t\treturn \u0026applyconfigurationsapiserverinternalv1alpha1.ServerStorageVersionApplyConfiguration{}\n\tcase apiserverinternalv1alpha1.SchemeGroupVersion.WithKind(\"StorageVersion\"):\n\t\treturn \u0026applyconfigurationsapiserverinternalv1alpha1.StorageVersionApplyConfiguration{}\n\tcase apiserverinternalv1alpha1.SchemeGroupVersion.WithKind(\"StorageVersionCondition\"):\n\t\treturn \u0026applyconfigurationsapiserverinternalv1alpha1.StorageVersionConditionApplyConfiguration{}\n\tcase apiserverinternalv1alpha1.SchemeGroupVersion.WithKind(\"StorageVersionStatus\"):\n\t\treturn \u0026applyconfigurationsapiserverinternalv1alpha1.StorageVersionStatusApplyConfiguration{}\n\n\t\t// Group=meta.k8s.io, Version=v1\n\tcase metav1.SchemeGroupVersion.WithKind(\"Condition\"):\n\t\treturn \u0026applyconfigurationsmetav1.ConditionApplyConfiguration{}\n\tcase metav1.SchemeGroupVersion.WithKind(\"DeleteOptions\"):\n\t\treturn \u0026applyconfigurationsmetav1.DeleteOptionsApplyConfiguration{}\n\tcase metav1.SchemeGroupVersion.WithKind(\"LabelSelector\"):\n\t\treturn \u0026applyconfigurationsmetav1.LabelSelectorApplyConfiguration{}\n\tcase metav1.SchemeGroupVersion.WithKind(\"LabelSelectorRequirement\"):\n\t\treturn \u0026applyconfigurationsmetav1.LabelSelectorRequirementApplyConfiguration{}\n\tcase metav1.SchemeGroupVersion.WithKind(\"ManagedFieldsEntry\"):\n\t\treturn \u0026applyconfigurationsmetav1.ManagedFieldsEntryApplyConfiguration{}\n\tcase metav1.SchemeGroupVersion.WithKind(\"ObjectMeta\"):\n\t\treturn \u0026applyconfigurationsmetav1.ObjectMetaApplyConfiguration{}\n\tcase metav1.SchemeGroupVersion.WithKind(\"OwnerReference\"):\n\t\treturn \u0026applyconfigurationsmetav1.OwnerReferenceApplyConfiguration{}\n\tcase metav1.SchemeGroupVersion.WithKind(\"Preconditions\"):\n\t\treturn \u0026applyconfigurationsmetav1.PreconditionsApplyConfiguration{}\n\tcase metav1.SchemeGroupVersion.WithKind(\"TypeMeta\"):\n\t\treturn \u0026applyconfigurationsmetav1.TypeMetaApplyConfiguration{}\n\n\t\t// Group=networking.k8s.io, Version=v1\n\tcase networkingv1.SchemeGroupVersion.WithKind(\"HTTPIngressPath\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1.HTTPIngressPathApplyConfiguration{}\n\tcase networkingv1.SchemeGroupVersion.WithKind(\"HTTPIngressRuleValue\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1.HTTPIngressRuleValueApplyConfiguration{}\n\tcase networkingv1.SchemeGroupVersion.WithKind(\"Ingress\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1.IngressApplyConfiguration{}\n\tcase networkingv1.SchemeGroupVersion.WithKind(\"IngressBackend\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1.IngressBackendApplyConfiguration{}\n\tcase networkingv1.SchemeGroupVersion.WithKind(\"IngressClass\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1.IngressClassApplyConfiguration{}\n\tcase networkingv1.SchemeGroupVersion.WithKind(\"IngressClassParametersReference\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1.IngressClassParametersReferenceApplyConfiguration{}\n\tcase networkingv1.SchemeGroupVersion.WithKind(\"IngressClassSpec\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1.IngressClassSpecApplyConfiguration{}\n\tcase networkingv1.SchemeGroupVersion.WithKind(\"IngressLoadBalancerIngress\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1.IngressLoadBalancerIngressApplyConfiguration{}\n\tcase networkingv1.SchemeGroupVersion.WithKind(\"IngressLoadBalancerStatus\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1.IngressLoadBalancerStatusApplyConfiguration{}\n\tcase networkingv1.SchemeGroupVersion.WithKind(\"IngressPortStatus\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1.IngressPortStatusApplyConfiguration{}\n\tcase networkingv1.SchemeGroupVersion.WithKind(\"IngressRule\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1.IngressRuleApplyConfiguration{}\n\tcase networkingv1.SchemeGroupVersion.WithKind(\"IngressRuleValue\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1.IngressRuleValueApplyConfiguration{}\n\tcase networkingv1.SchemeGroupVersion.WithKind(\"IngressServiceBackend\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1.IngressServiceBackendApplyConfiguration{}\n\tcase networkingv1.SchemeGroupVersion.WithKind(\"IngressSpec\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1.IngressSpecApplyConfiguration{}\n\tcase networkingv1.SchemeGroupVersion.WithKind(\"IngressStatus\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1.IngressStatusApplyConfiguration{}\n\tcase networkingv1.SchemeGroupVersion.WithKind(\"IngressTLS\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1.IngressTLSApplyConfiguration{}\n\tcase networkingv1.SchemeGroupVersion.WithKind(\"IPBlock\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1.IPBlockApplyConfiguration{}\n\tcase networkingv1.SchemeGroupVersion.WithKind(\"NetworkPolicy\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1.NetworkPolicyApplyConfiguration{}\n\tcase networkingv1.SchemeGroupVersion.WithKind(\"NetworkPolicyEgressRule\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1.NetworkPolicyEgressRuleApplyConfiguration{}\n\tcase networkingv1.SchemeGroupVersion.WithKind(\"NetworkPolicyIngressRule\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1.NetworkPolicyIngressRuleApplyConfiguration{}\n\tcase networkingv1.SchemeGroupVersion.WithKind(\"NetworkPolicyPeer\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1.NetworkPolicyPeerApplyConfiguration{}\n\tcase networkingv1.SchemeGroupVersion.WithKind(\"NetworkPolicyPort\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1.NetworkPolicyPortApplyConfiguration{}\n\tcase networkingv1.SchemeGroupVersion.WithKind(\"NetworkPolicySpec\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1.NetworkPolicySpecApplyConfiguration{}\n\tcase networkingv1.SchemeGroupVersion.WithKind(\"NetworkPolicyStatus\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1.NetworkPolicyStatusApplyConfiguration{}\n\tcase networkingv1.SchemeGroupVersion.WithKind(\"ServiceBackendPort\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1.ServiceBackendPortApplyConfiguration{}\n\n\t\t// Group=networking.k8s.io, Version=v1alpha1\n\tcase networkingv1alpha1.SchemeGroupVersion.WithKind(\"ClusterCIDR\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1alpha1.ClusterCIDRApplyConfiguration{}\n\tcase networkingv1alpha1.SchemeGroupVersion.WithKind(\"ClusterCIDRSpec\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1alpha1.ClusterCIDRSpecApplyConfiguration{}\n\tcase networkingv1alpha1.SchemeGroupVersion.WithKind(\"IPAddress\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1alpha1.IPAddressApplyConfiguration{}\n\tcase networkingv1alpha1.SchemeGroupVersion.WithKind(\"IPAddressSpec\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1alpha1.IPAddressSpecApplyConfiguration{}\n\tcase networkingv1alpha1.SchemeGroupVersion.WithKind(\"ParentReference\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1alpha1.ParentReferenceApplyConfiguration{}\n\n\t\t// Group=networking.k8s.io, Version=v1beta1\n\tcase networkingv1beta1.SchemeGroupVersion.WithKind(\"HTTPIngressPath\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1beta1.HTTPIngressPathApplyConfiguration{}\n\tcase networkingv1beta1.SchemeGroupVersion.WithKind(\"HTTPIngressRuleValue\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1beta1.HTTPIngressRuleValueApplyConfiguration{}\n\tcase networkingv1beta1.SchemeGroupVersion.WithKind(\"Ingress\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1beta1.IngressApplyConfiguration{}\n\tcase networkingv1beta1.SchemeGroupVersion.WithKind(\"IngressBackend\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1beta1.IngressBackendApplyConfiguration{}\n\tcase networkingv1beta1.SchemeGroupVersion.WithKind(\"IngressClass\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1beta1.IngressClassApplyConfiguration{}\n\tcase networkingv1beta1.SchemeGroupVersion.WithKind(\"IngressClassParametersReference\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1beta1.IngressClassParametersReferenceApplyConfiguration{}\n\tcase networkingv1beta1.SchemeGroupVersion.WithKind(\"IngressClassSpec\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1beta1.IngressClassSpecApplyConfiguration{}\n\tcase networkingv1beta1.SchemeGroupVersion.WithKind(\"IngressLoadBalancerIngress\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1beta1.IngressLoadBalancerIngressApplyConfiguration{}\n\tcase networkingv1beta1.SchemeGroupVersion.WithKind(\"IngressLoadBalancerStatus\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1beta1.IngressLoadBalancerStatusApplyConfiguration{}\n\tcase networkingv1beta1.SchemeGroupVersion.WithKind(\"IngressPortStatus\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1beta1.IngressPortStatusApplyConfiguration{}\n\tcase networkingv1beta1.SchemeGroupVersion.WithKind(\"IngressRule\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1beta1.IngressRuleApplyConfiguration{}\n\tcase networkingv1beta1.SchemeGroupVersion.WithKind(\"IngressRuleValue\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1beta1.IngressRuleValueApplyConfiguration{}\n\tcase networkingv1beta1.SchemeGroupVersion.WithKind(\"IngressSpec\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1beta1.IngressSpecApplyConfiguration{}\n\tcase networkingv1beta1.SchemeGroupVersion.WithKind(\"IngressStatus\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1beta1.IngressStatusApplyConfiguration{}\n\tcase networkingv1beta1.SchemeGroupVersion.WithKind(\"IngressTLS\"):\n\t\treturn \u0026applyconfigurationsnetworkingv1beta1.IngressTLSApplyConfiguration{}\n\n\t\t// Group=node.k8s.io, Version=v1\n\tcase nodev1.SchemeGroupVersion.WithKind(\"Overhead\"):\n\t\treturn \u0026applyconfigurationsnodev1.OverheadApplyConfiguration{}\n\tcase nodev1.SchemeGroupVersion.WithKind(\"RuntimeClass\"):\n\t\treturn \u0026applyconfigurationsnodev1.RuntimeClassApplyConfiguration{}\n\tcase nodev1.SchemeGroupVersion.WithKind(\"Scheduling\"):\n\t\treturn \u0026applyconfigurationsnodev1.SchedulingApplyConfiguration{}\n\n\t\t// Group=node.k8s.io, Version=v1alpha1\n\tcase nodev1alpha1.SchemeGroupVersion.WithKind(\"Overhead\"):\n\t\treturn \u0026applyconfigurationsnodev1alpha1.OverheadApplyConfiguration{}\n\tcase nodev1alpha1.SchemeGroupVersion.WithKind(\"RuntimeClass\"):\n\t\treturn \u0026applyconfigurationsnodev1alpha1.RuntimeClassApplyConfiguration{}\n\tcase nodev1alpha1.SchemeGroupVersion.WithKind(\"RuntimeClassSpec\"):\n\t\treturn \u0026applyconfigurationsnodev1alpha1.RuntimeClassSpecApplyConfiguration{}\n\tcase nodev1alpha1.SchemeGroupVersion.WithKind(\"Scheduling\"):\n\t\treturn \u0026applyconfigurationsnodev1alpha1.SchedulingApplyConfiguration{}\n\n\t\t// Group=node.k8s.io, Version=v1beta1\n\tcase nodev1beta1.SchemeGroupVersion.WithKind(\"Overhead\"):\n\t\treturn \u0026applyconfigurationsnodev1beta1.OverheadApplyConfiguration{}\n\tcase nodev1beta1.SchemeGroupVersion.WithKind(\"RuntimeClass\"):\n\t\treturn \u0026applyconfigurationsnodev1beta1.RuntimeClassApplyConfiguration{}\n\tcase nodev1beta1.SchemeGroupVersion.WithKind(\"Scheduling\"):\n\t\treturn \u0026applyconfigurationsnodev1beta1.SchedulingApplyConfiguration{}\n\n\t\t// Group=policy, Version=v1\n\tcase policyv1.SchemeGroupVersion.WithKind(\"Eviction\"):\n\t\treturn \u0026applyconfigurationspolicyv1.EvictionApplyConfiguration{}\n\tcase policyv1.SchemeGroupVersion.WithKind(\"PodDisruptionBudget\"):\n\t\treturn \u0026applyconfigurationspolicyv1.PodDisruptionBudgetApplyConfiguration{}\n\tcase policyv1.SchemeGroupVersion.WithKind(\"PodDisruptionBudgetSpec\"):\n\t\treturn \u0026applyconfigurationspolicyv1.PodDisruptionBudgetSpecApplyConfiguration{}\n\tcase policyv1.SchemeGroupVersion.WithKind(\"PodDisruptionBudgetStatus\"):\n\t\treturn \u0026applyconfigurationspolicyv1.PodDisruptionBudgetStatusApplyConfiguration{}\n\n\t\t// Group=policy, Version=v1beta1\n\tcase policyv1beta1.SchemeGroupVersion.WithKind(\"AllowedCSIDriver\"):\n\t\treturn \u0026applyconfigurationspolicyv1beta1.AllowedCSIDriverApplyConfiguration{}\n\tcase policyv1beta1.SchemeGroupVersion.WithKind(\"AllowedFlexVolume\"):\n\t\treturn \u0026applyconfigurationspolicyv1beta1.AllowedFlexVolumeApplyConfiguration{}\n\tcase policyv1beta1.SchemeGroupVersion.WithKind(\"AllowedHostPath\"):\n\t\treturn \u0026applyconfigurationspolicyv1beta1.AllowedHostPathApplyConfiguration{}\n\tcase policyv1beta1.SchemeGroupVersion.WithKind(\"Eviction\"):\n\t\treturn \u0026applyconfigurationspolicyv1beta1.EvictionApplyConfiguration{}\n\tcase policyv1beta1.SchemeGroupVersion.WithKind(\"FSGroupStrategyOptions\"):\n\t\treturn \u0026applyconfigurationspolicyv1beta1.FSGroupStrategyOptionsApplyConfiguration{}\n\tcase policyv1beta1.SchemeGroupVersion.WithKind(\"HostPortRange\"):\n\t\treturn \u0026applyconfigurationspolicyv1beta1.HostPortRangeApplyConfiguration{}\n\tcase policyv1beta1.SchemeGroupVersion.WithKind(\"IDRange\"):\n\t\treturn \u0026applyconfigurationspolicyv1beta1.IDRangeApplyConfiguration{}\n\tcase policyv1beta1.SchemeGroupVersion.WithKind(\"PodDisruptionBudget\"):\n\t\treturn \u0026applyconfigurationspolicyv1beta1.PodDisruptionBudgetApplyConfiguration{}\n\tcase policyv1beta1.SchemeGroupVersion.WithKind(\"PodDisruptionBudgetSpec\"):\n\t\treturn \u0026applyconfigurationspolicyv1beta1.PodDisruptionBudgetSpecApplyConfiguration{}\n\tcase policyv1beta1.SchemeGroupVersion.WithKind(\"PodDisruptionBudgetStatus\"):\n\t\treturn \u0026applyconfigurationspolicyv1beta1.PodDisruptionBudgetStatusApplyConfiguration{}\n\tcase policyv1beta1.SchemeGroupVersion.WithKind(\"PodSecurityPolicy\"):\n\t\treturn \u0026applyconfigurationspolicyv1beta1.PodSecurityPolicyApplyConfiguration{}\n\tcase policyv1beta1.SchemeGroupVersion.WithKind(\"PodSecurityPolicySpec\"):\n\t\treturn \u0026applyconfigurationspolicyv1beta1.PodSecurityPolicySpecApplyConfiguration{}\n\tcase policyv1beta1.SchemeGroupVersion.WithKind(\"RunAsGroupStrategyOptions\"):\n\t\treturn \u0026applyconfigurationspolicyv1beta1.RunAsGroupStrategyOptionsApplyConfiguration{}\n\tcase policyv1beta1.SchemeGroupVersion.WithKind(\"RunAsUserStrategyOptions\"):\n\t\treturn \u0026applyconfigurationspolicyv1beta1.RunAsUserStrategyOptionsApplyConfiguration{}\n\tcase policyv1beta1.SchemeGroupVersion.WithKind(\"RuntimeClassStrategyOptions\"):\n\t\treturn \u0026applyconfigurationspolicyv1beta1.RuntimeClassStrategyOptionsApplyConfiguration{}\n\tcase policyv1beta1.SchemeGroupVersion.WithKind(\"SELinuxStrategyOptions\"):\n\t\treturn \u0026applyconfigurationspolicyv1beta1.SELinuxStrategyOptionsApplyConfiguration{}\n\tcase policyv1beta1.SchemeGroupVersion.WithKind(\"SupplementalGroupsStrategyOptions\"):\n\t\treturn \u0026applyconfigurationspolicyv1beta1.SupplementalGroupsStrategyOptionsApplyConfiguration{}\n\n\t\t// Group=rbac.authorization.k8s.io, Version=v1\n\tcase rbacv1.SchemeGroupVersion.WithKind(\"AggregationRule\"):\n\t\treturn \u0026applyconfigurationsrbacv1.AggregationRuleApplyConfiguration{}\n\tcase rbacv1.SchemeGroupVersion.WithKind(\"ClusterRole\"):\n\t\treturn \u0026applyconfigurationsrbacv1.ClusterRoleApplyConfiguration{}\n\tcase rbacv1.SchemeGroupVersion.WithKind(\"ClusterRoleBinding\"):\n\t\treturn \u0026applyconfigurationsrbacv1.ClusterRoleBindingApplyConfiguration{}\n\tcase rbacv1.SchemeGroupVersion.WithKind(\"PolicyRule\"):\n\t\treturn \u0026applyconfigurationsrbacv1.PolicyRuleApplyConfiguration{}\n\tcase rbacv1.SchemeGroupVersion.WithKind(\"Role\"):\n\t\treturn \u0026applyconfigurationsrbacv1.RoleApplyConfiguration{}\n\tcase rbacv1.SchemeGroupVersion.WithKind(\"RoleBinding\"):\n\t\treturn \u0026applyconfigurationsrbacv1.RoleBindingApplyConfiguration{}\n\tcase rbacv1.SchemeGroupVersion.WithKind(\"RoleRef\"):\n\t\treturn \u0026applyconfigurationsrbacv1.RoleRefApplyConfiguration{}\n\tcase rbacv1.SchemeGroupVersion.WithKind(\"Subject\"):\n\t\treturn \u0026applyconfigurationsrbacv1.SubjectApplyConfiguration{}\n\n\t\t// Group=rbac.authorization.k8s.io, Version=v1alpha1\n\tcase rbacv1alpha1.SchemeGroupVersion.WithKind(\"AggregationRule\"):\n\t\treturn \u0026applyconfigurationsrbacv1alpha1.AggregationRuleApplyConfiguration{}\n\tcase rbacv1alpha1.SchemeGroupVersion.WithKind(\"ClusterRole\"):\n\t\treturn \u0026applyconfigurationsrbacv1alpha1.ClusterRoleApplyConfiguration{}\n\tcase rbacv1alpha1.SchemeGroupVersion.WithKind(\"ClusterRoleBinding\"):\n\t\treturn \u0026applyconfigurationsrbacv1alpha1.ClusterRoleBindingApplyConfiguration{}\n\tcase rbacv1alpha1.SchemeGroupVersion.WithKind(\"PolicyRule\"):\n\t\treturn \u0026applyconfigurationsrbacv1alpha1.PolicyRuleApplyConfiguration{}\n\tcase rbacv1alpha1.SchemeGroupVersion.WithKind(\"Role\"):\n\t\treturn \u0026applyconfigurationsrbacv1alpha1.RoleApplyConfiguration{}\n\tcase rbacv1alpha1.SchemeGroupVersion.WithKind(\"RoleBinding\"):\n\t\treturn \u0026applyconfigurationsrbacv1alpha1.RoleBindingApplyConfiguration{}\n\tcase rbacv1alpha1.SchemeGroupVersion.WithKind(\"RoleRef\"):\n\t\treturn \u0026applyconfigurationsrbacv1alpha1.RoleRefApplyConfiguration{}\n\tcase rbacv1alpha1.SchemeGroupVersion.WithKind(\"Subject\"):\n\t\treturn \u0026applyconfigurationsrbacv1alpha1.SubjectApplyConfiguration{}\n\n\t\t// Group=rbac.authorization.k8s.io, Version=v1beta1\n\tcase rbacv1beta1.SchemeGroupVersion.WithKind(\"AggregationRule\"):\n\t\treturn \u0026applyconfigurationsrbacv1beta1.AggregationRuleApplyConfiguration{}\n\tcase rbacv1beta1.SchemeGroupVersion.WithKind(\"ClusterRole\"):\n\t\treturn \u0026applyconfigurationsrbacv1beta1.ClusterRoleApplyConfiguration{}\n\tcase rbacv1beta1.SchemeGroupVersion.WithKind(\"ClusterRoleBinding\"):\n\t\treturn \u0026applyconfigurationsrbacv1beta1.ClusterRoleBindingApplyConfiguration{}\n\tcase rbacv1beta1.SchemeGroupVersion.WithKind(\"PolicyRule\"):\n\t\treturn \u0026applyconfigurationsrbacv1beta1.PolicyRuleApplyConfiguration{}\n\tcase rbacv1beta1.SchemeGroupVersion.WithKind(\"Role\"):\n\t\treturn \u0026applyconfigurationsrbacv1beta1.RoleApplyConfiguration{}\n\tcase rbacv1beta1.SchemeGroupVersion.WithKind(\"RoleBinding\"):\n\t\treturn \u0026applyconfigurationsrbacv1beta1.RoleBindingApplyConfiguration{}\n\tcase rbacv1beta1.SchemeGroupVersion.WithKind(\"RoleRef\"):\n\t\treturn \u0026applyconfigurationsrbacv1beta1.RoleRefApplyConfiguration{}\n\tcase rbacv1beta1.SchemeGroupVersion.WithKind(\"Subject\"):\n\t\treturn \u0026applyconfigurationsrbacv1beta1.SubjectApplyConfiguration{}\n\n\t\t// Group=resource.k8s.io, Version=v1alpha2\n\tcase v1alpha2.SchemeGroupVersion.WithKind(\"AllocationResult\"):\n\t\treturn \u0026resourcev1alpha2.AllocationResultApplyConfiguration{}\n\tcase v1alpha2.SchemeGroupVersion.WithKind(\"PodSchedulingContext\"):\n\t\treturn \u0026resourcev1alpha2.PodSchedulingContextApplyConfiguration{}\n\tcase v1alpha2.SchemeGroupVersion.WithKind(\"PodSchedulingContextSpec\"):\n\t\treturn \u0026resourcev1alpha2.PodSchedulingContextSpecApplyConfiguration{}\n\tcase v1alpha2.SchemeGroupVersion.WithKind(\"PodSchedulingContextStatus\"):\n\t\treturn \u0026resourcev1alpha2.PodSchedulingContextStatusApplyConfiguration{}\n\tcase v1alpha2.SchemeGroupVersion.WithKind(\"ResourceClaim\"):\n\t\treturn \u0026resourcev1alpha2.ResourceClaimApplyConfiguration{}\n\tcase v1alpha2.SchemeGroupVersion.WithKind(\"ResourceClaimConsumerReference\"):\n\t\treturn \u0026resourcev1alpha2.ResourceClaimConsumerReferenceApplyConfiguration{}\n\tcase v1alpha2.SchemeGroupVersion.WithKind(\"ResourceClaimParametersReference\"):\n\t\treturn \u0026resourcev1alpha2.ResourceClaimParametersReferenceApplyConfiguration{}\n\tcase v1alpha2.SchemeGroupVersion.WithKind(\"ResourceClaimSchedulingStatus\"):\n\t\treturn \u0026resourcev1alpha2.ResourceClaimSchedulingStatusApplyConfiguration{}\n\tcase v1alpha2.SchemeGroupVersion.WithKind(\"ResourceClaimSpec\"):\n\t\treturn \u0026resourcev1alpha2.ResourceClaimSpecApplyConfiguration{}\n\tcase v1alpha2.SchemeGroupVersion.WithKind(\"ResourceClaimStatus\"):\n\t\treturn \u0026resourcev1alpha2.ResourceClaimStatusApplyConfiguration{}\n\tcase v1alpha2.SchemeGroupVersion.WithKind(\"ResourceClaimTemplate\"):\n\t\treturn \u0026resourcev1alpha2.ResourceClaimTemplateApplyConfiguration{}\n\tcase v1alpha2.SchemeGroupVersion.WithKind(\"ResourceClaimTemplateSpec\"):\n\t\treturn \u0026resourcev1alpha2.ResourceClaimTemplateSpecApplyConfiguration{}\n\tcase v1alpha2.SchemeGroupVersion.WithKind(\"ResourceClass\"):\n\t\treturn \u0026resourcev1alpha2.ResourceClassApplyConfiguration{}\n\tcase v1alpha2.SchemeGroupVersion.WithKind(\"ResourceClassParametersReference\"):\n\t\treturn \u0026resourcev1alpha2.ResourceClassParametersReferenceApplyConfiguration{}\n\tcase v1alpha2.SchemeGroupVersion.WithKind(\"ResourceHandle\"):\n\t\treturn \u0026resourcev1alpha2.ResourceHandleApplyConfiguration{}\n\n\t\t// Group=scheduling.k8s.io, Version=v1\n\tcase schedulingv1.SchemeGroupVersion.WithKind(\"PriorityClass\"):\n\t\treturn \u0026applyconfigurationsschedulingv1.PriorityClassApplyConfiguration{}\n\n\t\t// Group=scheduling.k8s.io, Version=v1alpha1\n\tcase schedulingv1alpha1.SchemeGroupVersion.WithKind(\"PriorityClass\"):\n\t\treturn \u0026applyconfigurationsschedulingv1alpha1.PriorityClassApplyConfiguration{}\n\n\t\t// Group=scheduling.k8s.io, Version=v1beta1\n\tcase schedulingv1beta1.SchemeGroupVersion.WithKind(\"PriorityClass\"):\n\t\treturn \u0026applyconfigurationsschedulingv1beta1.PriorityClassApplyConfiguration{}\n\n\t\t// Group=storage.k8s.io, Version=v1\n\tcase storagev1.SchemeGroupVersion.WithKind(\"CSIDriver\"):\n\t\treturn \u0026applyconfigurationsstoragev1.CSIDriverApplyConfiguration{}\n\tcase storagev1.SchemeGroupVersion.WithKind(\"CSIDriverSpec\"):\n\t\treturn \u0026applyconfigurationsstoragev1.CSIDriverSpecApplyConfiguration{}\n\tcase storagev1.SchemeGroupVersion.WithKind(\"CSINode\"):\n\t\treturn \u0026applyconfigurationsstoragev1.CSINodeApplyConfiguration{}\n\tcase storagev1.SchemeGroupVersion.WithKind(\"CSINodeDriver\"):\n\t\treturn \u0026applyconfigurationsstoragev1.CSINodeDriverApplyConfiguration{}\n\tcase storagev1.SchemeGroupVersion.WithKind(\"CSINodeSpec\"):\n\t\treturn \u0026applyconfigurationsstoragev1.CSINodeSpecApplyConfiguration{}\n\tcase storagev1.SchemeGroupVersion.WithKind(\"CSIStorageCapacity\"):\n\t\treturn \u0026applyconfigurationsstoragev1.CSIStorageCapacityApplyConfiguration{}\n\tcase storagev1.SchemeGroupVersion.WithKind(\"StorageClass\"):\n\t\treturn \u0026applyconfigurationsstoragev1.StorageClassApplyConfiguration{}\n\tcase storagev1.SchemeGroupVersion.WithKind(\"TokenRequest\"):\n\t\treturn \u0026applyconfigurationsstoragev1.TokenRequestApplyConfiguration{}\n\tcase storagev1.SchemeGroupVersion.WithKind(\"VolumeAttachment\"):\n\t\treturn \u0026applyconfigurationsstoragev1.VolumeAttachmentApplyConfiguration{}\n\tcase storagev1.SchemeGroupVersion.WithKind(\"VolumeAttachmentSource\"):\n\t\treturn \u0026applyconfigurationsstoragev1.VolumeAttachmentSourceApplyConfiguration{}\n\tcase storagev1.SchemeGroupVersion.WithKind(\"VolumeAttachmentSpec\"):\n\t\treturn \u0026applyconfigurationsstoragev1.VolumeAttachmentSpecApplyConfiguration{}\n\tcase storagev1.SchemeGroupVersion.WithKind(\"VolumeAttachmentStatus\"):\n\t\treturn \u0026applyconfigurationsstoragev1.VolumeAttachmentStatusApplyConfiguration{}\n\tcase storagev1.SchemeGroupVersion.WithKind(\"VolumeError\"):\n\t\treturn \u0026applyconfigurationsstoragev1.VolumeErrorApplyConfiguration{}\n\tcase storagev1.SchemeGroupVersion.WithKind(\"VolumeNodeResources\"):\n\t\treturn \u0026applyconfigurationsstoragev1.VolumeNodeResourcesApplyConfiguration{}\n\n\t\t// Group=storage.k8s.io, Version=v1alpha1\n\tcase storagev1alpha1.SchemeGroupVersion.WithKind(\"CSIStorageCapacity\"):\n\t\treturn \u0026applyconfigurationsstoragev1alpha1.CSIStorageCapacityApplyConfiguration{}\n\tcase storagev1alpha1.SchemeGroupVersion.WithKind(\"VolumeAttachment\"):\n\t\treturn \u0026applyconfigurationsstoragev1alpha1.VolumeAttachmentApplyConfiguration{}\n\tcase storagev1alpha1.SchemeGroupVersion.WithKind(\"VolumeAttachmentSource\"):\n\t\treturn \u0026applyconfigurationsstoragev1alpha1.VolumeAttachmentSourceApplyConfiguration{}\n\tcase storagev1alpha1.SchemeGroupVersion.WithKind(\"VolumeAttachmentSpec\"):\n\t\treturn \u0026applyconfigurationsstoragev1alpha1.VolumeAttachmentSpecApplyConfiguration{}\n\tcase storagev1alpha1.SchemeGroupVersion.WithKind(\"VolumeAttachmentStatus\"):\n\t\treturn \u0026applyconfigurationsstoragev1alpha1.VolumeAttachmentStatusApplyConfiguration{}\n\tcase storagev1alpha1.SchemeGroupVersion.WithKind(\"VolumeError\"):\n\t\treturn \u0026applyconfigurationsstoragev1alpha1.VolumeErrorApplyConfiguration{}\n\n\t\t// Group=storage.k8s.io, Version=v1beta1\n\tcase storagev1beta1.SchemeGroupVersion.WithKind(\"CSIDriver\"):\n\t\treturn \u0026applyconfigurationsstoragev1beta1.CSIDriverApplyConfiguration{}\n\tcase storagev1beta1.SchemeGroupVersion.WithKind(\"CSIDriverSpec\"):\n\t\treturn \u0026applyconfigurationsstoragev1beta1.CSIDriverSpecApplyConfiguration{}\n\tcase storagev1beta1.SchemeGroupVersion.WithKind(\"CSINode\"):\n\t\treturn \u0026applyconfigurationsstoragev1beta1.CSINodeApplyConfiguration{}\n\tcase storagev1beta1.SchemeGroupVersion.WithKind(\"CSINodeDriver\"):\n\t\treturn \u0026applyconfigurationsstoragev1beta1.CSINodeDriverApplyConfiguration{}\n\tcase storagev1beta1.SchemeGroupVersion.WithKind(\"CSINodeSpec\"):\n\t\treturn \u0026applyconfigurationsstoragev1beta1.CSINodeSpecApplyConfiguration{}\n\tcase storagev1beta1.SchemeGroupVersion.WithKind(\"CSIStorageCapacity\"):\n\t\treturn \u0026applyconfigurationsstoragev1beta1.CSIStorageCapacityApplyConfiguration{}\n\tcase storagev1beta1.SchemeGroupVersion.WithKind(\"StorageClass\"):\n\t\treturn \u0026applyconfigurationsstoragev1beta1.StorageClassApplyConfiguration{}\n\tcase storagev1beta1.SchemeGroupVersion.WithKind(\"TokenRequest\"):\n\t\treturn \u0026applyconfigurationsstoragev1beta1.TokenRequestApplyConfiguration{}\n\tcase storagev1beta1.SchemeGroupVersion.WithKind(\"VolumeAttachment\"):\n\t\treturn \u0026applyconfigurationsstoragev1beta1.VolumeAttachmentApplyConfiguration{}\n\tcase storagev1beta1.SchemeGroupVersion.WithKind(\"VolumeAttachmentSource\"):\n\t\treturn \u0026applyconfigurationsstoragev1beta1.VolumeAttachmentSourceApplyConfiguration{}\n\tcase storagev1beta1.SchemeGroupVersion.WithKind(\"VolumeAttachmentSpec\"):\n\t\treturn \u0026applyconfigurationsstoragev1beta1.VolumeAttachmentSpecApplyConfiguration{}\n\tcase storagev1beta1.SchemeGroupVersion.WithKind(\"VolumeAttachmentStatus\"):\n\t\treturn \u0026applyconfigurationsstoragev1beta1.VolumeAttachmentStatusApplyConfiguration{}\n\tcase storagev1beta1.SchemeGroupVersion.WithKind(\"VolumeError\"):\n\t\treturn \u0026applyconfigurationsstoragev1beta1.VolumeErrorApplyConfiguration{}\n\tcase storagev1beta1.SchemeGroupVersion.WithKind(\"VolumeNodeResources\"):\n\t\treturn \u0026applyconfigurationsstoragev1beta1.VolumeNodeResourcesApplyConfiguration{}\n\n\t}\n\treturn nil\n}","line":{"from":121,"to":1591}} {"id":100024976,"name":"Error","signature":"func (s StaleGroupVersionError) Error() string","file":"staging/src/k8s.io/client-go/discovery/aggregated_discovery.go","code":"func (s StaleGroupVersionError) Error() string {\n\treturn fmt.Sprintf(\"stale GroupVersion discovery: %v\", s.gv)\n}","line":{"from":33,"to":35}} {"id":100024977,"name":"SplitGroupsAndResources","signature":"func SplitGroupsAndResources(aggregatedGroups apidiscovery.APIGroupDiscoveryList) (","file":"staging/src/k8s.io/client-go/discovery/aggregated_discovery.go","code":"// SplitGroupsAndResources transforms \"aggregated\" discovery top-level structure into\n// the previous \"unaggregated\" discovery groups and resources.\nfunc SplitGroupsAndResources(aggregatedGroups apidiscovery.APIGroupDiscoveryList) (\n\t*metav1.APIGroupList,\n\tmap[schema.GroupVersion]*metav1.APIResourceList,\n\tmap[schema.GroupVersion]error) {\n\t// Aggregated group list will contain the entirety of discovery, including\n\t// groups, versions, and resources. GroupVersions marked \"stale\" are failed.\n\tgroups := []*metav1.APIGroup{}\n\tfailedGVs := map[schema.GroupVersion]error{}\n\tresourcesByGV := map[schema.GroupVersion]*metav1.APIResourceList{}\n\tfor _, aggGroup := range aggregatedGroups.Items {\n\t\tgroup, resources, failed := convertAPIGroup(aggGroup)\n\t\tgroups = append(groups, group)\n\t\tfor gv, resourceList := range resources {\n\t\t\tresourcesByGV[gv] = resourceList\n\t\t}\n\t\tfor gv, err := range failed {\n\t\t\tfailedGVs[gv] = err\n\t\t}\n\t}\n\t// Transform slice of groups to group list before returning.\n\tgroupList := \u0026metav1.APIGroupList{}\n\tgroupList.Groups = make([]metav1.APIGroup, 0, len(groups))\n\tfor _, group := range groups {\n\t\tgroupList.Groups = append(groupList.Groups, *group)\n\t}\n\treturn groupList, resourcesByGV, failedGVs\n}","line":{"from":37,"to":65}} {"id":100024978,"name":"convertAPIGroup","signature":"func convertAPIGroup(g apidiscovery.APIGroupDiscovery) (","file":"staging/src/k8s.io/client-go/discovery/aggregated_discovery.go","code":"// convertAPIGroup tranforms an \"aggregated\" APIGroupDiscovery to an \"legacy\" APIGroup,\n// also returning the map of APIResourceList for resources within GroupVersions.\nfunc convertAPIGroup(g apidiscovery.APIGroupDiscovery) (\n\t*metav1.APIGroup,\n\tmap[schema.GroupVersion]*metav1.APIResourceList,\n\tmap[schema.GroupVersion]error) {\n\t// Iterate through versions to convert to group and resources.\n\tgroup := \u0026metav1.APIGroup{}\n\tgvResources := map[schema.GroupVersion]*metav1.APIResourceList{}\n\tfailedGVs := map[schema.GroupVersion]error{}\n\tgroup.Name = g.ObjectMeta.Name\n\tfor _, v := range g.Versions {\n\t\tgv := schema.GroupVersion{Group: g.Name, Version: v.Version}\n\t\tif v.Freshness == apidiscovery.DiscoveryFreshnessStale {\n\t\t\tfailedGVs[gv] = StaleGroupVersionError{gv: gv}\n\t\t\tcontinue\n\t\t}\n\t\tversion := metav1.GroupVersionForDiscovery{}\n\t\tversion.GroupVersion = gv.String()\n\t\tversion.Version = v.Version\n\t\tgroup.Versions = append(group.Versions, version)\n\t\t// PreferredVersion is first non-stale Version\n\t\tif group.PreferredVersion == (metav1.GroupVersionForDiscovery{}) {\n\t\t\tgroup.PreferredVersion = version\n\t\t}\n\t\tresourceList := \u0026metav1.APIResourceList{}\n\t\tresourceList.GroupVersion = gv.String()\n\t\tfor _, r := range v.Resources {\n\t\t\tresource, err := convertAPIResource(r)\n\t\t\tif err == nil {\n\t\t\t\tresourceList.APIResources = append(resourceList.APIResources, resource)\n\t\t\t}\n\t\t\t// Subresources field in new format get transformed into full APIResources.\n\t\t\t// It is possible a partial result with an error was returned to be used\n\t\t\t// as the parent resource for the subresource.\n\t\t\tfor _, subresource := range r.Subresources {\n\t\t\t\tsr, err := convertAPISubresource(resource, subresource)\n\t\t\t\tif err == nil {\n\t\t\t\t\tresourceList.APIResources = append(resourceList.APIResources, sr)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tgvResources[gv] = resourceList\n\t}\n\treturn group, gvResources, failedGVs\n}","line":{"from":67,"to":112}} {"id":100024979,"name":"convertAPIResource","signature":"func convertAPIResource(in apidiscovery.APIResourceDiscovery) (metav1.APIResource, error)","file":"staging/src/k8s.io/client-go/discovery/aggregated_discovery.go","code":"// convertAPIResource tranforms a APIResourceDiscovery to an APIResource. We are\n// resilient to missing GVK, since this resource might be the parent resource\n// for a subresource. If the parent is missing a GVK, it is not returned in\n// discovery, and the subresource MUST have the GVK.\nfunc convertAPIResource(in apidiscovery.APIResourceDiscovery) (metav1.APIResource, error) {\n\tresult := metav1.APIResource{\n\t\tName: in.Resource,\n\t\tSingularName: in.SingularResource,\n\t\tNamespaced: in.Scope == apidiscovery.ScopeNamespace,\n\t\tVerbs: in.Verbs,\n\t\tShortNames: in.ShortNames,\n\t\tCategories: in.Categories,\n\t}\n\tvar err error\n\tif in.ResponseKind != nil {\n\t\tresult.Group = in.ResponseKind.Group\n\t\tresult.Version = in.ResponseKind.Version\n\t\tresult.Kind = in.ResponseKind.Kind\n\t} else {\n\t\terr = fmt.Errorf(\"discovery resource %s missing GVK\", in.Resource)\n\t}\n\t// Can return partial result with error, which can be the parent for a\n\t// subresource. Do not add this result to the returned discovery resources.\n\treturn result, err\n}","line":{"from":114,"to":138}} {"id":100024980,"name":"convertAPISubresource","signature":"func convertAPISubresource(parent metav1.APIResource, in apidiscovery.APISubresourceDiscovery) (metav1.APIResource, error)","file":"staging/src/k8s.io/client-go/discovery/aggregated_discovery.go","code":"// convertAPISubresource tranforms a APISubresourceDiscovery to an APIResource.\nfunc convertAPISubresource(parent metav1.APIResource, in apidiscovery.APISubresourceDiscovery) (metav1.APIResource, error) {\n\tresult := metav1.APIResource{}\n\tif in.ResponseKind == nil {\n\t\treturn result, fmt.Errorf(\"subresource %s/%s missing GVK\", parent.Name, in.Subresource)\n\t}\n\tresult.Name = fmt.Sprintf(\"%s/%s\", parent.Name, in.Subresource)\n\tresult.SingularName = parent.SingularName\n\tresult.Namespaced = parent.Namespaced\n\tresult.Group = in.ResponseKind.Group\n\tresult.Version = in.ResponseKind.Version\n\tresult.Kind = in.ResponseKind.Kind\n\tresult.Verbs = in.Verbs\n\treturn result, nil\n}","line":{"from":140,"to":154}} {"id":100024981,"name":"ServerResourcesForGroupVersion","signature":"func (d *CachedDiscoveryClient) ServerResourcesForGroupVersion(groupVersion string) (*metav1.APIResourceList, error)","file":"staging/src/k8s.io/client-go/discovery/cached/disk/cached_discovery.go","code":"// ServerResourcesForGroupVersion returns the supported resources for a group and version.\nfunc (d *CachedDiscoveryClient) ServerResourcesForGroupVersion(groupVersion string) (*metav1.APIResourceList, error) {\n\tfilename := filepath.Join(d.cacheDirectory, groupVersion, \"serverresources.json\")\n\tcachedBytes, err := d.getCachedFile(filename)\n\t// don't fail on errors, we either don't have a file or won't be able to run the cached check. Either way we can fallback.\n\tif err == nil {\n\t\tcachedResources := \u0026metav1.APIResourceList{}\n\t\tif err := runtime.DecodeInto(scheme.Codecs.UniversalDecoder(), cachedBytes, cachedResources); err == nil {\n\t\t\tklog.V(10).Infof(\"returning cached discovery info from %v\", filename)\n\t\t\treturn cachedResources, nil\n\t\t}\n\t}\n\n\tliveResources, err := d.delegate.ServerResourcesForGroupVersion(groupVersion)\n\tif err != nil {\n\t\tklog.V(3).Infof(\"skipped caching discovery info due to %v\", err)\n\t\treturn liveResources, err\n\t}\n\tif liveResources == nil || len(liveResources.APIResources) == 0 {\n\t\tklog.V(3).Infof(\"skipped caching discovery info, no resources found\")\n\t\treturn liveResources, err\n\t}\n\n\tif err := d.writeCachedFile(filename, liveResources); err != nil {\n\t\tklog.V(1).Infof(\"failed to write cache to %v due to %v\", filename, err)\n\t}\n\n\treturn liveResources, nil\n}","line":{"from":69,"to":97}} {"id":100024982,"name":"ServerGroupsAndResources","signature":"func (d *CachedDiscoveryClient) ServerGroupsAndResources() ([]*metav1.APIGroup, []*metav1.APIResourceList, error)","file":"staging/src/k8s.io/client-go/discovery/cached/disk/cached_discovery.go","code":"// ServerGroupsAndResources returns the supported groups and resources for all groups and versions.\nfunc (d *CachedDiscoveryClient) ServerGroupsAndResources() ([]*metav1.APIGroup, []*metav1.APIResourceList, error) {\n\treturn discovery.ServerGroupsAndResources(d)\n}","line":{"from":99,"to":102}} {"id":100024983,"name":"ServerGroups","signature":"func (d *CachedDiscoveryClient) ServerGroups() (*metav1.APIGroupList, error)","file":"staging/src/k8s.io/client-go/discovery/cached/disk/cached_discovery.go","code":"// ServerGroups returns the supported groups, with information like supported versions and the\n// preferred version.\nfunc (d *CachedDiscoveryClient) ServerGroups() (*metav1.APIGroupList, error) {\n\tfilename := filepath.Join(d.cacheDirectory, \"servergroups.json\")\n\tcachedBytes, err := d.getCachedFile(filename)\n\t// don't fail on errors, we either don't have a file or won't be able to run the cached check. Either way we can fallback.\n\tif err == nil {\n\t\tcachedGroups := \u0026metav1.APIGroupList{}\n\t\tif err := runtime.DecodeInto(scheme.Codecs.UniversalDecoder(), cachedBytes, cachedGroups); err == nil {\n\t\t\tklog.V(10).Infof(\"returning cached discovery info from %v\", filename)\n\t\t\treturn cachedGroups, nil\n\t\t}\n\t}\n\n\tliveGroups, err := d.delegate.ServerGroups()\n\tif err != nil {\n\t\tklog.V(3).Infof(\"skipped caching discovery info due to %v\", err)\n\t\treturn liveGroups, err\n\t}\n\tif liveGroups == nil || len(liveGroups.Groups) == 0 {\n\t\tklog.V(3).Infof(\"skipped caching discovery info, no groups found\")\n\t\treturn liveGroups, err\n\t}\n\n\tif err := d.writeCachedFile(filename, liveGroups); err != nil {\n\t\tklog.V(1).Infof(\"failed to write cache to %v due to %v\", filename, err)\n\t}\n\n\treturn liveGroups, nil\n}","line":{"from":104,"to":133}} {"id":100024984,"name":"getCachedFile","signature":"func (d *CachedDiscoveryClient) getCachedFile(filename string) ([]byte, error)","file":"staging/src/k8s.io/client-go/discovery/cached/disk/cached_discovery.go","code":"func (d *CachedDiscoveryClient) getCachedFile(filename string) ([]byte, error) {\n\t// after invalidation ignore cache files not created by this process\n\td.mutex.Lock()\n\t_, ourFile := d.ourFiles[filename]\n\tif d.invalidated \u0026\u0026 !ourFile {\n\t\td.mutex.Unlock()\n\t\treturn nil, errors.New(\"cache invalidated\")\n\t}\n\td.mutex.Unlock()\n\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\n\tfileInfo, err := file.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif time.Now().After(fileInfo.ModTime().Add(d.ttl)) {\n\t\treturn nil, errors.New(\"cache expired\")\n\t}\n\n\t// the cache is present and its valid. Try to read and use it.\n\tcachedBytes, err := io.ReadAll(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\td.mutex.Lock()\n\tdefer d.mutex.Unlock()\n\td.fresh = d.fresh \u0026\u0026 ourFile\n\n\treturn cachedBytes, nil\n}","line":{"from":135,"to":171}} {"id":100024985,"name":"writeCachedFile","signature":"func (d *CachedDiscoveryClient) writeCachedFile(filename string, obj runtime.Object) error","file":"staging/src/k8s.io/client-go/discovery/cached/disk/cached_discovery.go","code":"func (d *CachedDiscoveryClient) writeCachedFile(filename string, obj runtime.Object) error {\n\tif err := os.MkdirAll(filepath.Dir(filename), 0750); err != nil {\n\t\treturn err\n\t}\n\n\tbytes, err := runtime.Encode(scheme.Codecs.LegacyCodec(), obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf, err := os.CreateTemp(filepath.Dir(filename), filepath.Base(filename)+\".\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer os.Remove(f.Name())\n\t_, err = f.Write(bytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.Chmod(f.Name(), 0660)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tname := f.Name()\n\terr = f.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// atomic rename\n\td.mutex.Lock()\n\tdefer d.mutex.Unlock()\n\terr = os.Rename(name, filename)\n\tif err == nil {\n\t\td.ourFiles[filename] = struct{}{}\n\t}\n\treturn err\n}","line":{"from":173,"to":212}} {"id":100024986,"name":"RESTClient","signature":"func (d *CachedDiscoveryClient) RESTClient() restclient.Interface","file":"staging/src/k8s.io/client-go/discovery/cached/disk/cached_discovery.go","code":"// RESTClient returns a RESTClient that is used to communicate with API server\n// by this client implementation.\nfunc (d *CachedDiscoveryClient) RESTClient() restclient.Interface {\n\treturn d.delegate.RESTClient()\n}","line":{"from":214,"to":218}} {"id":100024987,"name":"ServerPreferredResources","signature":"func (d *CachedDiscoveryClient) ServerPreferredResources() ([]*metav1.APIResourceList, error)","file":"staging/src/k8s.io/client-go/discovery/cached/disk/cached_discovery.go","code":"// ServerPreferredResources returns the supported resources with the version preferred by the\n// server.\nfunc (d *CachedDiscoveryClient) ServerPreferredResources() ([]*metav1.APIResourceList, error) {\n\treturn discovery.ServerPreferredResources(d)\n}","line":{"from":220,"to":224}} {"id":100024988,"name":"ServerPreferredNamespacedResources","signature":"func (d *CachedDiscoveryClient) ServerPreferredNamespacedResources() ([]*metav1.APIResourceList, error)","file":"staging/src/k8s.io/client-go/discovery/cached/disk/cached_discovery.go","code":"// ServerPreferredNamespacedResources returns the supported namespaced resources with the\n// version preferred by the server.\nfunc (d *CachedDiscoveryClient) ServerPreferredNamespacedResources() ([]*metav1.APIResourceList, error) {\n\treturn discovery.ServerPreferredNamespacedResources(d)\n}","line":{"from":226,"to":230}} {"id":100024989,"name":"ServerVersion","signature":"func (d *CachedDiscoveryClient) ServerVersion() (*version.Info, error)","file":"staging/src/k8s.io/client-go/discovery/cached/disk/cached_discovery.go","code":"// ServerVersion retrieves and parses the server's version (git version).\nfunc (d *CachedDiscoveryClient) ServerVersion() (*version.Info, error) {\n\treturn d.delegate.ServerVersion()\n}","line":{"from":232,"to":235}} {"id":100024990,"name":"OpenAPISchema","signature":"func (d *CachedDiscoveryClient) OpenAPISchema() (*openapi_v2.Document, error)","file":"staging/src/k8s.io/client-go/discovery/cached/disk/cached_discovery.go","code":"// OpenAPISchema retrieves and parses the swagger API schema the server supports.\nfunc (d *CachedDiscoveryClient) OpenAPISchema() (*openapi_v2.Document, error) {\n\treturn d.delegate.OpenAPISchema()\n}","line":{"from":237,"to":240}} {"id":100024991,"name":"OpenAPIV3","signature":"func (d *CachedDiscoveryClient) OpenAPIV3() openapi.Client","file":"staging/src/k8s.io/client-go/discovery/cached/disk/cached_discovery.go","code":"// OpenAPIV3 retrieves and parses the OpenAPIV3 specs exposed by the server\nfunc (d *CachedDiscoveryClient) OpenAPIV3() openapi.Client {\n\t// Must take lock since Invalidate call may modify openapiClient\n\td.mutex.Lock()\n\tdefer d.mutex.Unlock()\n\n\tif d.openapiClient == nil {\n\t\t// Delegate is discovery client created with special HTTP client which\n\t\t// respects E-Tag cache responses to serve cache from disk.\n\t\td.openapiClient = cachedopenapi.NewClient(d.delegate.OpenAPIV3())\n\t}\n\n\treturn d.openapiClient\n}","line":{"from":242,"to":255}} {"id":100024992,"name":"Fresh","signature":"func (d *CachedDiscoveryClient) Fresh() bool","file":"staging/src/k8s.io/client-go/discovery/cached/disk/cached_discovery.go","code":"// Fresh is supposed to tell the caller whether or not to retry if the cache\n// fails to find something (false = retry, true = no need to retry).\nfunc (d *CachedDiscoveryClient) Fresh() bool {\n\td.mutex.Lock()\n\tdefer d.mutex.Unlock()\n\n\treturn d.fresh\n}","line":{"from":257,"to":264}} {"id":100024993,"name":"Invalidate","signature":"func (d *CachedDiscoveryClient) Invalidate()","file":"staging/src/k8s.io/client-go/discovery/cached/disk/cached_discovery.go","code":"// Invalidate enforces that no cached data is used in the future that is older than the current time.\nfunc (d *CachedDiscoveryClient) Invalidate() {\n\td.mutex.Lock()\n\tdefer d.mutex.Unlock()\n\n\td.ourFiles = map[string]struct{}{}\n\td.fresh = true\n\td.invalidated = true\n\td.openapiClient = nil\n\tif ad, ok := d.delegate.(discovery.CachedDiscoveryInterface); ok {\n\t\tad.Invalidate()\n\t}\n}","line":{"from":266,"to":278}} {"id":100024994,"name":"WithLegacy","signature":"func (d *CachedDiscoveryClient) WithLegacy() discovery.DiscoveryInterface","file":"staging/src/k8s.io/client-go/discovery/cached/disk/cached_discovery.go","code":"// WithLegacy returns current cached discovery client;\n// current client does not support legacy-only discovery.\nfunc (d *CachedDiscoveryClient) WithLegacy() discovery.DiscoveryInterface {\n\treturn d\n}","line":{"from":280,"to":284}} {"id":100024995,"name":"NewCachedDiscoveryClientForConfig","signature":"func NewCachedDiscoveryClientForConfig(config *restclient.Config, discoveryCacheDir, httpCacheDir string, ttl time.Duration) (*CachedDiscoveryClient, error)","file":"staging/src/k8s.io/client-go/discovery/cached/disk/cached_discovery.go","code":"// NewCachedDiscoveryClientForConfig creates a new DiscoveryClient for the given config, and wraps\n// the created client in a CachedDiscoveryClient. The provided configuration is updated with a\n// custom transport that understands cache responses.\n// We receive two distinct cache directories for now, in order to preserve old behavior\n// which makes use of the --cache-dir flag value for storing cache data from the CacheRoundTripper,\n// and makes use of the hardcoded destination (~/.kube/cache/discovery/...) for storing\n// CachedDiscoveryClient cache data. If httpCacheDir is empty, the restconfig's transport will not\n// be updated with a roundtripper that understands cache responses.\n// If discoveryCacheDir is empty, cached server resource data will be looked up in the current directory.\nfunc NewCachedDiscoveryClientForConfig(config *restclient.Config, discoveryCacheDir, httpCacheDir string, ttl time.Duration) (*CachedDiscoveryClient, error) {\n\tif len(httpCacheDir) \u003e 0 {\n\t\t// update the given restconfig with a custom roundtripper that\n\t\t// understands how to handle cache responses.\n\t\tconfig = restclient.CopyConfig(config)\n\t\tconfig.Wrap(func(rt http.RoundTripper) http.RoundTripper {\n\t\t\treturn newCacheRoundTripper(httpCacheDir, rt)\n\t\t})\n\t}\n\n\tdiscoveryClient, err := discovery.NewDiscoveryClientForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// The delegate caches the discovery groups and resources (memcache). \"ServerGroups\",\n\t// which usually only returns (and caches) the groups, can now store the resources as\n\t// well if the server supports the newer aggregated discovery format.\n\treturn newCachedDiscoveryClient(memory.NewMemCacheClient(discoveryClient), discoveryCacheDir, ttl), nil\n}","line":{"from":286,"to":314}} {"id":100024996,"name":"newCachedDiscoveryClient","signature":"func newCachedDiscoveryClient(delegate discovery.DiscoveryInterface, cacheDirectory string, ttl time.Duration) *CachedDiscoveryClient","file":"staging/src/k8s.io/client-go/discovery/cached/disk/cached_discovery.go","code":"// NewCachedDiscoveryClient creates a new DiscoveryClient. cacheDirectory is the directory where discovery docs are held. It must be unique per host:port combination to work well.\nfunc newCachedDiscoveryClient(delegate discovery.DiscoveryInterface, cacheDirectory string, ttl time.Duration) *CachedDiscoveryClient {\n\treturn \u0026CachedDiscoveryClient{\n\t\tdelegate: delegate,\n\t\tcacheDirectory: cacheDirectory,\n\t\tttl: ttl,\n\t\tourFiles: map[string]struct{}{},\n\t\tfresh: true,\n\t}\n}","line":{"from":316,"to":325}} {"id":100024997,"name":"newCacheRoundTripper","signature":"func newCacheRoundTripper(cacheDir string, rt http.RoundTripper) http.RoundTripper","file":"staging/src/k8s.io/client-go/discovery/cached/disk/round_tripper.go","code":"// newCacheRoundTripper creates a roundtripper that reads the ETag on\n// response headers and send the If-None-Match header on subsequent\n// corresponding requests.\nfunc newCacheRoundTripper(cacheDir string, rt http.RoundTripper) http.RoundTripper {\n\td := diskv.New(diskv.Options{\n\t\tPathPerm: os.FileMode(0750),\n\t\tFilePerm: os.FileMode(0660),\n\t\tBasePath: cacheDir,\n\t\tTempDir: filepath.Join(cacheDir, \".diskv-temp\"),\n\t})\n\tt := httpcache.NewTransport(\u0026sumDiskCache{disk: d})\n\tt.Transport = rt\n\n\treturn \u0026cacheRoundTripper{rt: t}\n}","line":{"from":36,"to":50}} {"id":100024998,"name":"RoundTrip","signature":"func (rt *cacheRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)","file":"staging/src/k8s.io/client-go/discovery/cached/disk/round_tripper.go","code":"func (rt *cacheRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {\n\treturn rt.rt.RoundTrip(req)\n}","line":{"from":52,"to":54}} {"id":100024999,"name":"CancelRequest","signature":"func (rt *cacheRoundTripper) CancelRequest(req *http.Request)","file":"staging/src/k8s.io/client-go/discovery/cached/disk/round_tripper.go","code":"func (rt *cacheRoundTripper) CancelRequest(req *http.Request) {\n\ttype canceler interface {\n\t\tCancelRequest(*http.Request)\n\t}\n\tif cr, ok := rt.rt.Transport.(canceler); ok {\n\t\tcr.CancelRequest(req)\n\t} else {\n\t\tklog.Errorf(\"CancelRequest not implemented by %T\", rt.rt.Transport)\n\t}\n}","line":{"from":56,"to":65}} {"id":100025000,"name":"WrappedRoundTripper","signature":"func (rt *cacheRoundTripper) WrappedRoundTripper() http.RoundTripper { return rt.rt.Transport }","file":"staging/src/k8s.io/client-go/discovery/cached/disk/round_tripper.go","code":"func (rt *cacheRoundTripper) WrappedRoundTripper() http.RoundTripper { return rt.rt.Transport }","line":{"from":67,"to":67}} {"id":100025001,"name":"Get","signature":"func (c *sumDiskCache) Get(key string) ([]byte, bool)","file":"staging/src/k8s.io/client-go/discovery/cached/disk/round_tripper.go","code":"// Get the requested key from the cache on disk. If Get encounters an error, or\n// the returned value is not a SHA256 sum followed by bytes with a matching\n// checksum it will return false to indicate a cache miss.\nfunc (c *sumDiskCache) Get(key string) ([]byte, bool) {\n\tb, err := c.disk.Read(sanitize(key))\n\tif err != nil || len(b) \u003c sha256.Size {\n\t\treturn []byte{}, false\n\t}\n\n\tresponse := b[sha256.Size:]\n\twant := b[:sha256.Size] // The first 32 bytes of the file should be the SHA256 sum.\n\tgot := sha256.Sum256(response)\n\tif !bytes.Equal(want, got[:]) {\n\t\treturn []byte{}, false\n\t}\n\n\treturn response, true\n}","line":{"from":80,"to":97}} {"id":100025002,"name":"Set","signature":"func (c *sumDiskCache) Set(key string, response []byte)","file":"staging/src/k8s.io/client-go/discovery/cached/disk/round_tripper.go","code":"// Set writes the response to a file on disk. The filename will be the SHA256\n// sum of the key. The file will contain a SHA256 sum of the response bytes,\n// followed by said response bytes.\nfunc (c *sumDiskCache) Set(key string, response []byte) {\n\ts := sha256.Sum256(response)\n\t_ = c.disk.Write(sanitize(key), append(s[:], response...)) // Nothing we can do with this error.\n}","line":{"from":99,"to":105}} {"id":100025003,"name":"Delete","signature":"func (c *sumDiskCache) Delete(key string)","file":"staging/src/k8s.io/client-go/discovery/cached/disk/round_tripper.go","code":"func (c *sumDiskCache) Delete(key string) {\n\t_ = c.disk.Erase(sanitize(key)) // Nothing we can do with this error.\n}","line":{"from":107,"to":109}} {"id":100025004,"name":"sanitize","signature":"func sanitize(key string) string","file":"staging/src/k8s.io/client-go/discovery/cached/disk/round_tripper.go","code":"// Sanitize an httpcache key such that it can be used as a diskv key, which must\n// be a valid filename. The httpcache key will either be the requested URL (if\n// the request method was GET) or \"\u003cmethod\u003e \u003curl\u003e\" for other methods, per the\n// httpcache.cacheKey function.\nfunc sanitize(key string) string {\n\t// These keys are not sensitive. We use sha256 to avoid a (potentially\n\t// malicious) collision causing the wrong cache data to be written or\n\t// accessed.\n\treturn fmt.Sprintf(\"%x\", sha256.Sum256([]byte(key)))\n}","line":{"from":111,"to":120}} {"id":100025005,"name":"NewMemCacheClient","signature":"func NewMemCacheClient(delegate discovery.DiscoveryInterface) discovery.CachedDiscoveryInterface","file":"staging/src/k8s.io/client-go/discovery/cached/legacy.go","code":"// NewMemCacheClient is DEPRECATED. Use memory.NewMemCacheClient directly.\nfunc NewMemCacheClient(delegate discovery.DiscoveryInterface) discovery.CachedDiscoveryInterface {\n\treturn memory.NewMemCacheClient(delegate)\n}","line":{"from":24,"to":27}} {"id":100025006,"name":"Error","signature":"func (e *emptyResponseError) Error() string","file":"staging/src/k8s.io/client-go/discovery/cached/memory/memcache.go","code":"func (e *emptyResponseError) Error() string {\n\treturn fmt.Sprintf(\"received empty response for: %s\", e.gv)\n}","line":{"from":70,"to":72}} {"id":100025007,"name":"isTransientConnectionError","signature":"func isTransientConnectionError(err error) bool","file":"staging/src/k8s.io/client-go/discovery/cached/memory/memcache.go","code":"// isTransientConnectionError checks whether given error is \"Connection refused\" or\n// \"Connection reset\" error which usually means that apiserver is temporarily\n// unavailable.\nfunc isTransientConnectionError(err error) bool {\n\tvar errno syscall.Errno\n\tif errors.As(err, \u0026errno) {\n\t\treturn errno == syscall.ECONNREFUSED || errno == syscall.ECONNRESET\n\t}\n\treturn false\n}","line":{"from":76,"to":85}} {"id":100025008,"name":"isTransientError","signature":"func isTransientError(err error) bool","file":"staging/src/k8s.io/client-go/discovery/cached/memory/memcache.go","code":"func isTransientError(err error) bool {\n\tif isTransientConnectionError(err) {\n\t\treturn true\n\t}\n\n\tif t, ok := err.(errorsutil.APIStatus); ok \u0026\u0026 t.Status().Code \u003e= 500 {\n\t\treturn true\n\t}\n\n\treturn errorsutil.IsTooManyRequests(err)\n}","line":{"from":87,"to":97}} {"id":100025009,"name":"ServerResourcesForGroupVersion","signature":"func (d *memCacheClient) ServerResourcesForGroupVersion(groupVersion string) (*metav1.APIResourceList, error)","file":"staging/src/k8s.io/client-go/discovery/cached/memory/memcache.go","code":"// ServerResourcesForGroupVersion returns the supported resources for a group and version.\nfunc (d *memCacheClient) ServerResourcesForGroupVersion(groupVersion string) (*metav1.APIResourceList, error) {\n\td.lock.Lock()\n\tdefer d.lock.Unlock()\n\tif !d.cacheValid {\n\t\tif err := d.refreshLocked(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tcachedVal, ok := d.groupToServerResources[groupVersion]\n\tif !ok {\n\t\treturn nil, ErrCacheNotFound\n\t}\n\n\tif cachedVal.err != nil \u0026\u0026 isTransientError(cachedVal.err) {\n\t\tr, err := d.serverResourcesForGroupVersion(groupVersion)\n\t\tif err != nil {\n\t\t\t// Don't log \"empty response\" as an error; it is a common response for metrics.\n\t\t\tif _, emptyErr := err.(*emptyResponseError); emptyErr {\n\t\t\t\t// Log at same verbosity as disk cache.\n\t\t\t\tklog.V(3).Infof(\"%v\", err)\n\t\t\t} else {\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get resource list for %v: %v\", groupVersion, err))\n\t\t\t}\n\t\t}\n\t\tcachedVal = \u0026cacheEntry{r, err}\n\t\td.groupToServerResources[groupVersion] = cachedVal\n\t}\n\n\treturn cachedVal.resourceList, cachedVal.err\n}","line":{"from":99,"to":129}} {"id":100025010,"name":"ServerGroupsAndResources","signature":"func (d *memCacheClient) ServerGroupsAndResources() ([]*metav1.APIGroup, []*metav1.APIResourceList, error)","file":"staging/src/k8s.io/client-go/discovery/cached/memory/memcache.go","code":"// ServerGroupsAndResources returns the groups and supported resources for all groups and versions.\nfunc (d *memCacheClient) ServerGroupsAndResources() ([]*metav1.APIGroup, []*metav1.APIResourceList, error) {\n\treturn discovery.ServerGroupsAndResources(d)\n}","line":{"from":131,"to":134}} {"id":100025011,"name":"GroupsAndMaybeResources","signature":"func (d *memCacheClient) GroupsAndMaybeResources() (*metav1.APIGroupList, map[schema.GroupVersion]*metav1.APIResourceList, map[schema.GroupVersion]error, error)","file":"staging/src/k8s.io/client-go/discovery/cached/memory/memcache.go","code":"// GroupsAndMaybeResources returns the list of APIGroups, and possibly the map of group/version\n// to resources. The returned groups will never be nil, but the resources map can be nil\n// if there are no cached resources.\nfunc (d *memCacheClient) GroupsAndMaybeResources() (*metav1.APIGroupList, map[schema.GroupVersion]*metav1.APIResourceList, map[schema.GroupVersion]error, error) {\n\td.lock.Lock()\n\tdefer d.lock.Unlock()\n\n\tif !d.cacheValid {\n\t\tif err := d.refreshLocked(); err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t}\n\t// Build the resourceList from the cache?\n\tvar resourcesMap map[schema.GroupVersion]*metav1.APIResourceList\n\tvar failedGVs map[schema.GroupVersion]error\n\tif d.receivedAggregatedDiscovery \u0026\u0026 len(d.groupToServerResources) \u003e 0 {\n\t\tresourcesMap = map[schema.GroupVersion]*metav1.APIResourceList{}\n\t\tfailedGVs = map[schema.GroupVersion]error{}\n\t\tfor gv, cacheEntry := range d.groupToServerResources {\n\t\t\tgroupVersion, err := schema.ParseGroupVersion(gv)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, nil, fmt.Errorf(\"failed to parse group version (%v): %v\", gv, err)\n\t\t\t}\n\t\t\tif cacheEntry.err != nil {\n\t\t\t\tfailedGVs[groupVersion] = cacheEntry.err\n\t\t\t} else {\n\t\t\t\tresourcesMap[groupVersion] = cacheEntry.resourceList\n\t\t\t}\n\t\t}\n\t}\n\treturn d.groupList, resourcesMap, failedGVs, nil\n}","line":{"from":136,"to":167}} {"id":100025012,"name":"ServerGroups","signature":"func (d *memCacheClient) ServerGroups() (*metav1.APIGroupList, error)","file":"staging/src/k8s.io/client-go/discovery/cached/memory/memcache.go","code":"func (d *memCacheClient) ServerGroups() (*metav1.APIGroupList, error) {\n\tgroups, _, _, err := d.GroupsAndMaybeResources()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn groups, nil\n}","line":{"from":169,"to":175}} {"id":100025013,"name":"RESTClient","signature":"func (d *memCacheClient) RESTClient() restclient.Interface","file":"staging/src/k8s.io/client-go/discovery/cached/memory/memcache.go","code":"func (d *memCacheClient) RESTClient() restclient.Interface {\n\treturn d.delegate.RESTClient()\n}","line":{"from":177,"to":179}} {"id":100025014,"name":"ServerPreferredResources","signature":"func (d *memCacheClient) ServerPreferredResources() ([]*metav1.APIResourceList, error)","file":"staging/src/k8s.io/client-go/discovery/cached/memory/memcache.go","code":"func (d *memCacheClient) ServerPreferredResources() ([]*metav1.APIResourceList, error) {\n\treturn discovery.ServerPreferredResources(d)\n}","line":{"from":181,"to":183}} {"id":100025015,"name":"ServerPreferredNamespacedResources","signature":"func (d *memCacheClient) ServerPreferredNamespacedResources() ([]*metav1.APIResourceList, error)","file":"staging/src/k8s.io/client-go/discovery/cached/memory/memcache.go","code":"func (d *memCacheClient) ServerPreferredNamespacedResources() ([]*metav1.APIResourceList, error) {\n\treturn discovery.ServerPreferredNamespacedResources(d)\n}","line":{"from":185,"to":187}} {"id":100025016,"name":"ServerVersion","signature":"func (d *memCacheClient) ServerVersion() (*version.Info, error)","file":"staging/src/k8s.io/client-go/discovery/cached/memory/memcache.go","code":"func (d *memCacheClient) ServerVersion() (*version.Info, error) {\n\treturn d.delegate.ServerVersion()\n}","line":{"from":189,"to":191}} {"id":100025017,"name":"OpenAPISchema","signature":"func (d *memCacheClient) OpenAPISchema() (*openapi_v2.Document, error)","file":"staging/src/k8s.io/client-go/discovery/cached/memory/memcache.go","code":"func (d *memCacheClient) OpenAPISchema() (*openapi_v2.Document, error) {\n\treturn d.delegate.OpenAPISchema()\n}","line":{"from":193,"to":195}} {"id":100025018,"name":"OpenAPIV3","signature":"func (d *memCacheClient) OpenAPIV3() openapi.Client","file":"staging/src/k8s.io/client-go/discovery/cached/memory/memcache.go","code":"func (d *memCacheClient) OpenAPIV3() openapi.Client {\n\t// Must take lock since Invalidate call may modify openapiClient\n\td.lock.Lock()\n\tdefer d.lock.Unlock()\n\n\tif d.openapiClient == nil {\n\t\td.openapiClient = cachedopenapi.NewClient(d.delegate.OpenAPIV3())\n\t}\n\n\treturn d.openapiClient\n}","line":{"from":197,"to":207}} {"id":100025019,"name":"Fresh","signature":"func (d *memCacheClient) Fresh() bool","file":"staging/src/k8s.io/client-go/discovery/cached/memory/memcache.go","code":"func (d *memCacheClient) Fresh() bool {\n\td.lock.RLock()\n\tdefer d.lock.RUnlock()\n\t// Return whether the cache is populated at all. It is still possible that\n\t// a single entry is missing due to transient errors and the attempt to read\n\t// that entry will trigger retry.\n\treturn d.cacheValid\n}","line":{"from":209,"to":216}} {"id":100025020,"name":"Invalidate","signature":"func (d *memCacheClient) Invalidate()","file":"staging/src/k8s.io/client-go/discovery/cached/memory/memcache.go","code":"// Invalidate enforces that no cached data that is older than the current time\n// is used.\nfunc (d *memCacheClient) Invalidate() {\n\td.lock.Lock()\n\tdefer d.lock.Unlock()\n\td.cacheValid = false\n\td.groupToServerResources = nil\n\td.groupList = nil\n\td.openapiClient = nil\n\td.receivedAggregatedDiscovery = false\n\tif ad, ok := d.delegate.(discovery.CachedDiscoveryInterface); ok {\n\t\tad.Invalidate()\n\t}\n}","line":{"from":218,"to":231}} {"id":100025021,"name":"refreshLocked","signature":"func (d *memCacheClient) refreshLocked() error","file":"staging/src/k8s.io/client-go/discovery/cached/memory/memcache.go","code":"// refreshLocked refreshes the state of cache. The caller must hold d.lock for\n// writing.\nfunc (d *memCacheClient) refreshLocked() error {\n\t// TODO: Could this multiplicative set of calls be replaced by a single call\n\t// to ServerResources? If it's possible for more than one resulting\n\t// APIResourceList to have the same GroupVersion, the lists would need merged.\n\tvar gl *metav1.APIGroupList\n\tvar err error\n\n\tif ad, ok := d.delegate.(discovery.AggregatedDiscoveryInterface); ok {\n\t\tvar resources map[schema.GroupVersion]*metav1.APIResourceList\n\t\tvar failedGVs map[schema.GroupVersion]error\n\t\tgl, resources, failedGVs, err = ad.GroupsAndMaybeResources()\n\t\tif resources != nil \u0026\u0026 err == nil {\n\t\t\t// Cache the resources.\n\t\t\td.groupToServerResources = map[string]*cacheEntry{}\n\t\t\td.groupList = gl\n\t\t\tfor gv, resources := range resources {\n\t\t\t\td.groupToServerResources[gv.String()] = \u0026cacheEntry{resources, nil}\n\t\t\t}\n\t\t\t// Cache GroupVersion discovery errors\n\t\t\tfor gv, err := range failedGVs {\n\t\t\t\td.groupToServerResources[gv.String()] = \u0026cacheEntry{nil, err}\n\t\t\t}\n\t\t\td.receivedAggregatedDiscovery = true\n\t\t\td.cacheValid = true\n\t\t\treturn nil\n\t\t}\n\t} else {\n\t\tgl, err = d.delegate.ServerGroups()\n\t}\n\tif err != nil || len(gl.Groups) == 0 {\n\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get current server API group list: %v\", err))\n\t\treturn err\n\t}\n\n\twg := \u0026sync.WaitGroup{}\n\tresultLock := \u0026sync.Mutex{}\n\trl := map[string]*cacheEntry{}\n\tfor _, g := range gl.Groups {\n\t\tfor _, v := range g.Versions {\n\t\t\tgv := v.GroupVersion\n\t\t\twg.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tdefer utilruntime.HandleCrash()\n\n\t\t\t\tr, err := d.serverResourcesForGroupVersion(gv)\n\t\t\t\tif err != nil {\n\t\t\t\t\t// Don't log \"empty response\" as an error; it is a common response for metrics.\n\t\t\t\t\tif _, emptyErr := err.(*emptyResponseError); emptyErr {\n\t\t\t\t\t\t// Log at same verbosity as disk cache.\n\t\t\t\t\t\tklog.V(3).Infof(\"%v\", err)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"couldn't get resource list for %v: %v\", gv, err))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tresultLock.Lock()\n\t\t\t\tdefer resultLock.Unlock()\n\t\t\t\trl[gv] = \u0026cacheEntry{r, err}\n\t\t\t}()\n\t\t}\n\t}\n\twg.Wait()\n\n\td.groupToServerResources, d.groupList = rl, gl\n\td.cacheValid = true\n\treturn nil\n}","line":{"from":233,"to":302}} {"id":100025022,"name":"serverResourcesForGroupVersion","signature":"func (d *memCacheClient) serverResourcesForGroupVersion(groupVersion string) (*metav1.APIResourceList, error)","file":"staging/src/k8s.io/client-go/discovery/cached/memory/memcache.go","code":"func (d *memCacheClient) serverResourcesForGroupVersion(groupVersion string) (*metav1.APIResourceList, error) {\n\tr, err := d.delegate.ServerResourcesForGroupVersion(groupVersion)\n\tif err != nil {\n\t\treturn r, err\n\t}\n\tif len(r.APIResources) == 0 {\n\t\treturn r, \u0026emptyResponseError{gv: groupVersion}\n\t}\n\treturn r, nil\n}","line":{"from":304,"to":313}} {"id":100025023,"name":"WithLegacy","signature":"func (d *memCacheClient) WithLegacy() discovery.DiscoveryInterface","file":"staging/src/k8s.io/client-go/discovery/cached/memory/memcache.go","code":"// WithLegacy returns current memory-cached discovery client;\n// current client does not support legacy-only discovery.\nfunc (d *memCacheClient) WithLegacy() discovery.DiscoveryInterface {\n\treturn d\n}","line":{"from":315,"to":319}} {"id":100025024,"name":"NewMemCacheClient","signature":"func NewMemCacheClient(delegate discovery.DiscoveryInterface) discovery.CachedDiscoveryInterface","file":"staging/src/k8s.io/client-go/discovery/cached/memory/memcache.go","code":"// NewMemCacheClient creates a new CachedDiscoveryInterface which caches\n// discovery information in memory and will stay up-to-date if Invalidate is\n// called with regularity.\n//\n// NOTE: The client will NOT resort to live lookups on cache misses.\nfunc NewMemCacheClient(delegate discovery.DiscoveryInterface) discovery.CachedDiscoveryInterface {\n\treturn \u0026memCacheClient{\n\t\tdelegate: delegate,\n\t\tgroupToServerResources: map[string]*cacheEntry{},\n\t\treceivedAggregatedDiscovery: false,\n\t}\n}","line":{"from":321,"to":332}} {"id":100025025,"name":"apiVersionsToAPIGroup","signature":"func apiVersionsToAPIGroup(apiVersions *metav1.APIVersions) (apiGroup metav1.APIGroup)","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"// Convert metav1.APIVersions to metav1.APIGroup. APIVersions is used by legacy v1, so\n// group would be \"\".\nfunc apiVersionsToAPIGroup(apiVersions *metav1.APIVersions) (apiGroup metav1.APIGroup) {\n\tgroupVersions := []metav1.GroupVersionForDiscovery{}\n\tfor _, version := range apiVersions.Versions {\n\t\tgroupVersion := metav1.GroupVersionForDiscovery{\n\t\t\tGroupVersion: version,\n\t\t\tVersion: version,\n\t\t}\n\t\tgroupVersions = append(groupVersions, groupVersion)\n\t}\n\tapiGroup.Versions = groupVersions\n\t// There should be only one groupVersion returned at /api\n\tapiGroup.PreferredVersion = groupVersions[0]\n\treturn\n}","line":{"from":169,"to":184}} {"id":100025026,"name":"GroupsAndMaybeResources","signature":"func (d *DiscoveryClient) GroupsAndMaybeResources() (","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"// GroupsAndMaybeResources returns the discovery groups, and (if new aggregated\n// discovery format) the resources keyed by group/version. Merges discovery groups\n// and resources from /api and /apis (either aggregated or not). Legacy groups\n// must be ordered first. The server will either return both endpoints (/api, /apis)\n// as aggregated discovery format or legacy format. For safety, resources will only\n// be returned if both endpoints returned resources. Returned \"failedGVs\" can be\n// empty, but will only be nil in the case an error is returned.\nfunc (d *DiscoveryClient) GroupsAndMaybeResources() (\n\t*metav1.APIGroupList,\n\tmap[schema.GroupVersion]*metav1.APIResourceList,\n\tmap[schema.GroupVersion]error,\n\terror) {\n\t// Legacy group ordered first (there is only one -- core/v1 group). Returned groups must\n\t// be non-nil, but it could be empty. Returned resources, apiResources map could be nil.\n\tgroups, resources, failedGVs, err := d.downloadLegacy()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\t// Discovery groups and (possibly) resources downloaded from /apis.\n\tapiGroups, apiResources, failedApisGVs, aerr := d.downloadAPIs()\n\tif aerr != nil {\n\t\treturn nil, nil, nil, aerr\n\t}\n\t// Merge apis groups into the legacy groups.\n\tfor _, group := range apiGroups.Groups {\n\t\tgroups.Groups = append(groups.Groups, group)\n\t}\n\t// For safety, only return resources if both endpoints returned resources.\n\tif resources != nil \u0026\u0026 apiResources != nil {\n\t\tfor gv, resourceList := range apiResources {\n\t\t\tresources[gv] = resourceList\n\t\t}\n\t} else if resources != nil {\n\t\tresources = nil\n\t}\n\t// Merge failed GroupVersions from /api and /apis\n\tfor gv, err := range failedApisGVs {\n\t\tfailedGVs[gv] = err\n\t}\n\treturn groups, resources, failedGVs, err\n}","line":{"from":186,"to":226}} {"id":100025027,"name":"downloadLegacy","signature":"func (d *DiscoveryClient) downloadLegacy() (","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"// downloadLegacy returns the discovery groups and possibly resources\n// for the legacy v1 GVR at /api, or an error if one occurred. It is\n// possible for the resource map to be nil if the server returned\n// the unaggregated discovery. Returned \"failedGVs\" can be empty, but\n// will only be nil in the case of a returned error.\nfunc (d *DiscoveryClient) downloadLegacy() (\n\t*metav1.APIGroupList,\n\tmap[schema.GroupVersion]*metav1.APIResourceList,\n\tmap[schema.GroupVersion]error,\n\terror) {\n\taccept := acceptDiscoveryFormats\n\tif d.UseLegacyDiscovery {\n\t\taccept = AcceptV1\n\t}\n\tvar responseContentType string\n\tbody, err := d.restClient.Get().\n\t\tAbsPath(\"/api\").\n\t\tSetHeader(\"Accept\", accept).\n\t\tDo(context.TODO()).\n\t\tContentType(\u0026responseContentType).\n\t\tRaw()\n\tapiGroupList := \u0026metav1.APIGroupList{}\n\tfailedGVs := map[schema.GroupVersion]error{}\n\tif err != nil {\n\t\t// Tolerate 404, since aggregated api servers can return it.\n\t\tif errors.IsNotFound(err) {\n\t\t\t// Return empty structures and no error.\n\t\t\temptyGVMap := map[schema.GroupVersion]*metav1.APIResourceList{}\n\t\t\treturn apiGroupList, emptyGVMap, failedGVs, nil\n\t\t} else {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t}\n\n\tvar resourcesByGV map[schema.GroupVersion]*metav1.APIResourceList\n\t// Switch on content-type server responded with: aggregated or unaggregated.\n\tswitch {\n\tcase isV2Beta1ContentType(responseContentType):\n\t\tvar aggregatedDiscovery apidiscovery.APIGroupDiscoveryList\n\t\terr = json.Unmarshal(body, \u0026aggregatedDiscovery)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t\tapiGroupList, resourcesByGV, failedGVs = SplitGroupsAndResources(aggregatedDiscovery)\n\tdefault:\n\t\t// Default is unaggregated discovery v1.\n\t\tvar v metav1.APIVersions\n\t\terr = json.Unmarshal(body, \u0026v)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t\tapiGroup := metav1.APIGroup{}\n\t\tif len(v.Versions) != 0 {\n\t\t\tapiGroup = apiVersionsToAPIGroup(\u0026v)\n\t\t}\n\t\tapiGroupList.Groups = []metav1.APIGroup{apiGroup}\n\t}\n\n\treturn apiGroupList, resourcesByGV, failedGVs, nil\n}","line":{"from":228,"to":287}} {"id":100025028,"name":"downloadAPIs","signature":"func (d *DiscoveryClient) downloadAPIs() (","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"// downloadAPIs returns the discovery groups and (if aggregated format) the\n// discovery resources. The returned groups will always exist, but the\n// resources map may be nil. Returned \"failedGVs\" can be empty, but will\n// only be nil in the case of a returned error.\nfunc (d *DiscoveryClient) downloadAPIs() (\n\t*metav1.APIGroupList,\n\tmap[schema.GroupVersion]*metav1.APIResourceList,\n\tmap[schema.GroupVersion]error,\n\terror) {\n\taccept := acceptDiscoveryFormats\n\tif d.UseLegacyDiscovery {\n\t\taccept = AcceptV1\n\t}\n\tvar responseContentType string\n\tbody, err := d.restClient.Get().\n\t\tAbsPath(\"/apis\").\n\t\tSetHeader(\"Accept\", accept).\n\t\tDo(context.TODO()).\n\t\tContentType(\u0026responseContentType).\n\t\tRaw()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tapiGroupList := \u0026metav1.APIGroupList{}\n\tfailedGVs := map[schema.GroupVersion]error{}\n\tvar resourcesByGV map[schema.GroupVersion]*metav1.APIResourceList\n\t// Switch on content-type server responded with: aggregated or unaggregated.\n\tswitch {\n\tcase isV2Beta1ContentType(responseContentType):\n\t\tvar aggregatedDiscovery apidiscovery.APIGroupDiscoveryList\n\t\terr = json.Unmarshal(body, \u0026aggregatedDiscovery)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t\tapiGroupList, resourcesByGV, failedGVs = SplitGroupsAndResources(aggregatedDiscovery)\n\tdefault:\n\t\t// Default is unaggregated discovery v1.\n\t\terr = json.Unmarshal(body, apiGroupList)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t}\n\n\treturn apiGroupList, resourcesByGV, failedGVs, nil\n}","line":{"from":289,"to":334}} {"id":100025029,"name":"isV2Beta1ContentType","signature":"func isV2Beta1ContentType(contentType string) bool","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"// isV2Beta1ContentType checks of the content-type string is both\n// \"application/json\" and contains the v2beta1 content-type params.\n// NOTE: This function is resilient to the ordering of the\n// content-type parameters, as well as parameters added by\n// intermediaries such as proxies or gateways. Examples:\n//\n//\t\"application/json; g=apidiscovery.k8s.io;v=v2beta1;as=APIGroupDiscoveryList\" = true\n//\t\"application/json; as=APIGroupDiscoveryList;v=v2beta1;g=apidiscovery.k8s.io\" = true\n//\t\"application/json; as=APIGroupDiscoveryList;v=v2beta1;g=apidiscovery.k8s.io;charset=utf-8\" = true\n//\t\"application/json\" = false\n//\t\"application/json; charset=UTF-8\" = false\nfunc isV2Beta1ContentType(contentType string) bool {\n\tbase, params, err := mime.ParseMediaType(contentType)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn runtime.ContentTypeJSON == base \u0026\u0026\n\t\tparams[\"g\"] == \"apidiscovery.k8s.io\" \u0026\u0026\n\t\tparams[\"v\"] == \"v2beta1\" \u0026\u0026\n\t\tparams[\"as\"] == \"APIGroupDiscoveryList\"\n}","line":{"from":336,"to":356}} {"id":100025030,"name":"ServerGroups","signature":"func (d *DiscoveryClient) ServerGroups() (*metav1.APIGroupList, error)","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"// ServerGroups returns the supported groups, with information like supported versions and the\n// preferred version.\nfunc (d *DiscoveryClient) ServerGroups() (*metav1.APIGroupList, error) {\n\tgroups, _, _, err := d.GroupsAndMaybeResources()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn groups, nil\n}","line":{"from":358,"to":366}} {"id":100025031,"name":"ServerResourcesForGroupVersion","signature":"func (d *DiscoveryClient) ServerResourcesForGroupVersion(groupVersion string) (resources *metav1.APIResourceList, err error)","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"// ServerResourcesForGroupVersion returns the supported resources for a group and version.\nfunc (d *DiscoveryClient) ServerResourcesForGroupVersion(groupVersion string) (resources *metav1.APIResourceList, err error) {\n\turl := url.URL{}\n\tif len(groupVersion) == 0 {\n\t\treturn nil, fmt.Errorf(\"groupVersion shouldn't be empty\")\n\t}\n\tif len(d.LegacyPrefix) \u003e 0 \u0026\u0026 groupVersion == \"v1\" {\n\t\turl.Path = d.LegacyPrefix + \"/\" + groupVersion\n\t} else {\n\t\turl.Path = \"/apis/\" + groupVersion\n\t}\n\tresources = \u0026metav1.APIResourceList{\n\t\tGroupVersion: groupVersion,\n\t}\n\terr = d.restClient.Get().AbsPath(url.String()).Do(context.TODO()).Into(resources)\n\tif err != nil {\n\t\t// Tolerate core/v1 not found response by returning empty resource list;\n\t\t// this probably should not happen. But we should verify all callers are\n\t\t// not depending on this toleration before removal.\n\t\tif groupVersion == \"v1\" \u0026\u0026 errors.IsNotFound(err) {\n\t\t\treturn resources, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn resources, nil\n}","line":{"from":368,"to":393}} {"id":100025032,"name":"ServerGroupsAndResources","signature":"func (d *DiscoveryClient) ServerGroupsAndResources() ([]*metav1.APIGroup, []*metav1.APIResourceList, error)","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"// ServerGroupsAndResources returns the supported resources for all groups and versions.\nfunc (d *DiscoveryClient) ServerGroupsAndResources() ([]*metav1.APIGroup, []*metav1.APIResourceList, error) {\n\treturn withRetries(defaultRetries, func() ([]*metav1.APIGroup, []*metav1.APIResourceList, error) {\n\t\treturn ServerGroupsAndResources(d)\n\t})\n}","line":{"from":395,"to":400}} {"id":100025033,"name":"Error","signature":"func (e *ErrGroupDiscoveryFailed) Error() string","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"// Error implements the error interface\nfunc (e *ErrGroupDiscoveryFailed) Error() string {\n\tvar groups []string\n\tfor k, v := range e.Groups {\n\t\tgroups = append(groups, fmt.Sprintf(\"%s: %v\", k, v))\n\t}\n\tsort.Strings(groups)\n\treturn fmt.Sprintf(\"unable to retrieve the complete list of server APIs: %s\", strings.Join(groups, \", \"))\n}","line":{"from":408,"to":416}} {"id":100025034,"name":"IsGroupDiscoveryFailedError","signature":"func IsGroupDiscoveryFailedError(err error) bool","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"// IsGroupDiscoveryFailedError returns true if the provided error indicates the server was unable to discover\n// a complete list of APIs for the client to use.\nfunc IsGroupDiscoveryFailedError(err error) bool {\n\t_, ok := err.(*ErrGroupDiscoveryFailed)\n\treturn err != nil \u0026\u0026 ok\n}","line":{"from":418,"to":423}} {"id":100025035,"name":"ServerGroupsAndResources","signature":"func ServerGroupsAndResources(d DiscoveryInterface) ([]*metav1.APIGroup, []*metav1.APIResourceList, error)","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"func ServerGroupsAndResources(d DiscoveryInterface) ([]*metav1.APIGroup, []*metav1.APIResourceList, error) {\n\tvar sgs *metav1.APIGroupList\n\tvar resources []*metav1.APIResourceList\n\tvar failedGVs map[schema.GroupVersion]error\n\tvar err error\n\n\t// If the passed discovery object implements the wider AggregatedDiscoveryInterface,\n\t// then attempt to retrieve aggregated discovery with both groups and the resources.\n\tif ad, ok := d.(AggregatedDiscoveryInterface); ok {\n\t\tvar resourcesByGV map[schema.GroupVersion]*metav1.APIResourceList\n\t\tsgs, resourcesByGV, failedGVs, err = ad.GroupsAndMaybeResources()\n\t\tfor _, resourceList := range resourcesByGV {\n\t\t\tresources = append(resources, resourceList)\n\t\t}\n\t} else {\n\t\tsgs, err = d.ServerGroups()\n\t}\n\n\tif sgs == nil {\n\t\treturn nil, nil, err\n\t}\n\tresultGroups := []*metav1.APIGroup{}\n\tfor i := range sgs.Groups {\n\t\tresultGroups = append(resultGroups, \u0026sgs.Groups[i])\n\t}\n\t// resources is non-nil if aggregated discovery succeeded.\n\tif resources != nil {\n\t\t// Any stale Group/Versions returned by aggregated discovery\n\t\t// must be surfaced to the caller as failed Group/Versions.\n\t\tvar ferr error\n\t\tif len(failedGVs) \u003e 0 {\n\t\t\tferr = \u0026ErrGroupDiscoveryFailed{Groups: failedGVs}\n\t\t}\n\t\treturn resultGroups, resources, ferr\n\t}\n\n\tgroupVersionResources, failedGroups := fetchGroupVersionResources(d, sgs)\n\n\t// order results by group/version discovery order\n\tresult := []*metav1.APIResourceList{}\n\tfor _, apiGroup := range sgs.Groups {\n\t\tfor _, version := range apiGroup.Versions {\n\t\t\tgv := schema.GroupVersion{Group: apiGroup.Name, Version: version.Version}\n\t\t\tif resources, ok := groupVersionResources[gv]; ok {\n\t\t\t\tresult = append(result, resources)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(failedGroups) == 0 {\n\t\treturn resultGroups, result, nil\n\t}\n\n\treturn resultGroups, result, \u0026ErrGroupDiscoveryFailed{Groups: failedGroups}\n}","line":{"from":425,"to":479}} {"id":100025036,"name":"ServerPreferredResources","signature":"func ServerPreferredResources(d DiscoveryInterface) ([]*metav1.APIResourceList, error)","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"// ServerPreferredResources uses the provided discovery interface to look up preferred resources\nfunc ServerPreferredResources(d DiscoveryInterface) ([]*metav1.APIResourceList, error) {\n\tvar serverGroupList *metav1.APIGroupList\n\tvar failedGroups map[schema.GroupVersion]error\n\tvar groupVersionResources map[schema.GroupVersion]*metav1.APIResourceList\n\tvar err error\n\n\t// If the passed discovery object implements the wider AggregatedDiscoveryInterface,\n\t// then it is attempt to retrieve both the groups and the resources. \"failedGroups\"\n\t// are Group/Versions returned as stale in AggregatedDiscovery format.\n\tad, ok := d.(AggregatedDiscoveryInterface)\n\tif ok {\n\t\tserverGroupList, groupVersionResources, failedGroups, err = ad.GroupsAndMaybeResources()\n\t} else {\n\t\tserverGroupList, err = d.ServerGroups()\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Non-aggregated discovery must fetch resources from Groups.\n\tif groupVersionResources == nil {\n\t\tgroupVersionResources, failedGroups = fetchGroupVersionResources(d, serverGroupList)\n\t}\n\n\tresult := []*metav1.APIResourceList{}\n\tgrVersions := map[schema.GroupResource]string{} // selected version of a GroupResource\n\tgrAPIResources := map[schema.GroupResource]*metav1.APIResource{} // selected APIResource for a GroupResource\n\tgvAPIResourceLists := map[schema.GroupVersion]*metav1.APIResourceList{} // blueprint for a APIResourceList for later grouping\n\n\tfor _, apiGroup := range serverGroupList.Groups {\n\t\tfor _, version := range apiGroup.Versions {\n\t\t\tgroupVersion := schema.GroupVersion{Group: apiGroup.Name, Version: version.Version}\n\n\t\t\tapiResourceList, ok := groupVersionResources[groupVersion]\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// create empty list which is filled later in another loop\n\t\t\temptyAPIResourceList := metav1.APIResourceList{\n\t\t\t\tGroupVersion: version.GroupVersion,\n\t\t\t}\n\t\t\tgvAPIResourceLists[groupVersion] = \u0026emptyAPIResourceList\n\t\t\tresult = append(result, \u0026emptyAPIResourceList)\n\n\t\t\tfor i := range apiResourceList.APIResources {\n\t\t\t\tapiResource := \u0026apiResourceList.APIResources[i]\n\t\t\t\tif strings.Contains(apiResource.Name, \"/\") {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tgv := schema.GroupResource{Group: apiGroup.Name, Resource: apiResource.Name}\n\t\t\t\tif _, ok := grAPIResources[gv]; ok \u0026\u0026 version.Version != apiGroup.PreferredVersion.Version {\n\t\t\t\t\t// only override with preferred version\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tgrVersions[gv] = version.Version\n\t\t\t\tgrAPIResources[gv] = apiResource\n\t\t\t}\n\t\t}\n\t}\n\n\t// group selected APIResources according to GroupVersion into APIResourceLists\n\tfor groupResource, apiResource := range grAPIResources {\n\t\tversion := grVersions[groupResource]\n\t\tgroupVersion := schema.GroupVersion{Group: groupResource.Group, Version: version}\n\t\tapiResourceList := gvAPIResourceLists[groupVersion]\n\t\tapiResourceList.APIResources = append(apiResourceList.APIResources, *apiResource)\n\t}\n\n\tif len(failedGroups) == 0 {\n\t\treturn result, nil\n\t}\n\n\treturn result, \u0026ErrGroupDiscoveryFailed{Groups: failedGroups}\n}","line":{"from":481,"to":555}} {"id":100025037,"name":"fetchGroupVersionResources","signature":"func fetchGroupVersionResources(d DiscoveryInterface, apiGroups *metav1.APIGroupList) (map[schema.GroupVersion]*metav1.APIResourceList, map[schema.GroupVersion]error)","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"// fetchServerResourcesForGroupVersions uses the discovery client to fetch the resources for the specified groups in parallel.\nfunc fetchGroupVersionResources(d DiscoveryInterface, apiGroups *metav1.APIGroupList) (map[schema.GroupVersion]*metav1.APIResourceList, map[schema.GroupVersion]error) {\n\tgroupVersionResources := make(map[schema.GroupVersion]*metav1.APIResourceList)\n\tfailedGroups := make(map[schema.GroupVersion]error)\n\n\twg := \u0026sync.WaitGroup{}\n\tresultLock := \u0026sync.Mutex{}\n\tfor _, apiGroup := range apiGroups.Groups {\n\t\tfor _, version := range apiGroup.Versions {\n\t\t\tgroupVersion := schema.GroupVersion{Group: apiGroup.Name, Version: version.Version}\n\t\t\twg.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tdefer utilruntime.HandleCrash()\n\n\t\t\t\tapiResourceList, err := d.ServerResourcesForGroupVersion(groupVersion.String())\n\n\t\t\t\t// lock to record results\n\t\t\t\tresultLock.Lock()\n\t\t\t\tdefer resultLock.Unlock()\n\n\t\t\t\tif err != nil {\n\t\t\t\t\t// TODO: maybe restrict this to NotFound errors\n\t\t\t\t\tfailedGroups[groupVersion] = err\n\t\t\t\t}\n\t\t\t\tif apiResourceList != nil {\n\t\t\t\t\t// even in case of error, some fallback might have been returned\n\t\t\t\t\tgroupVersionResources[groupVersion] = apiResourceList\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t}\n\twg.Wait()\n\n\treturn groupVersionResources, failedGroups\n}","line":{"from":557,"to":592}} {"id":100025038,"name":"ServerPreferredResources","signature":"func (d *DiscoveryClient) ServerPreferredResources() ([]*metav1.APIResourceList, error)","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"// ServerPreferredResources returns the supported resources with the version preferred by the\n// server.\nfunc (d *DiscoveryClient) ServerPreferredResources() ([]*metav1.APIResourceList, error) {\n\t_, rs, err := withRetries(defaultRetries, func() ([]*metav1.APIGroup, []*metav1.APIResourceList, error) {\n\t\trs, err := ServerPreferredResources(d)\n\t\treturn nil, rs, err\n\t})\n\treturn rs, err\n}","line":{"from":594,"to":602}} {"id":100025039,"name":"ServerPreferredNamespacedResources","signature":"func (d *DiscoveryClient) ServerPreferredNamespacedResources() ([]*metav1.APIResourceList, error)","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"// ServerPreferredNamespacedResources returns the supported namespaced resources with the\n// version preferred by the server.\nfunc (d *DiscoveryClient) ServerPreferredNamespacedResources() ([]*metav1.APIResourceList, error) {\n\treturn ServerPreferredNamespacedResources(d)\n}","line":{"from":604,"to":608}} {"id":100025040,"name":"ServerPreferredNamespacedResources","signature":"func ServerPreferredNamespacedResources(d DiscoveryInterface) ([]*metav1.APIResourceList, error)","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"// ServerPreferredNamespacedResources uses the provided discovery interface to look up preferred namespaced resources\nfunc ServerPreferredNamespacedResources(d DiscoveryInterface) ([]*metav1.APIResourceList, error) {\n\tall, err := ServerPreferredResources(d)\n\treturn FilteredBy(ResourcePredicateFunc(func(groupVersion string, r *metav1.APIResource) bool {\n\t\treturn r.Namespaced\n\t}), all), err\n}","line":{"from":610,"to":616}} {"id":100025041,"name":"ServerVersion","signature":"func (d *DiscoveryClient) ServerVersion() (*version.Info, error)","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"// ServerVersion retrieves and parses the server's version (git version).\nfunc (d *DiscoveryClient) ServerVersion() (*version.Info, error) {\n\tbody, err := d.restClient.Get().AbsPath(\"/version\").Do(context.TODO()).Raw()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar info version.Info\n\terr = json.Unmarshal(body, \u0026info)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to parse the server version: %v\", err)\n\t}\n\treturn \u0026info, nil\n}","line":{"from":618,"to":630}} {"id":100025042,"name":"OpenAPISchema","signature":"func (d *DiscoveryClient) OpenAPISchema() (*openapi_v2.Document, error)","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"// OpenAPISchema fetches the open api v2 schema using a rest client and parses the proto.\nfunc (d *DiscoveryClient) OpenAPISchema() (*openapi_v2.Document, error) {\n\tdata, err := d.restClient.Get().AbsPath(\"/openapi/v2\").SetHeader(\"Accept\", openAPIV2mimePb).Do(context.TODO()).Raw()\n\tif err != nil {\n\t\tif errors.IsForbidden(err) || errors.IsNotFound(err) || errors.IsNotAcceptable(err) {\n\t\t\t// single endpoint not found/registered in old server, try to fetch old endpoint\n\t\t\t// TODO: remove this when kubectl/client-go don't work with 1.9 server\n\t\t\tdata, err = d.restClient.Get().AbsPath(\"/swagger-2.0.0.pb-v1\").Do(context.TODO()).Raw()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tdocument := \u0026openapi_v2.Document{}\n\terr = proto.Unmarshal(data, document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn document, nil\n}","line":{"from":632,"to":653}} {"id":100025043,"name":"OpenAPIV3","signature":"func (d *DiscoveryClient) OpenAPIV3() openapi.Client","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"func (d *DiscoveryClient) OpenAPIV3() openapi.Client {\n\treturn openapi.NewClient(d.restClient)\n}","line":{"from":655,"to":657}} {"id":100025044,"name":"WithLegacy","signature":"func (d *DiscoveryClient) WithLegacy() DiscoveryInterface","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"// WithLegacy returns copy of current discovery client that will only\n// receive the legacy discovery format.\nfunc (d *DiscoveryClient) WithLegacy() DiscoveryInterface {\n\tclient := *d\n\tclient.UseLegacyDiscovery = true\n\treturn \u0026client\n}","line":{"from":659,"to":665}} {"id":100025045,"name":"withRetries","signature":"func withRetries(maxRetries int, f func() ([]*metav1.APIGroup, []*metav1.APIResourceList, error)) ([]*metav1.APIGroup, []*metav1.APIResourceList, error)","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"// withRetries retries the given recovery function in case the groups supported by the server change after ServerGroup() returns.\nfunc withRetries(maxRetries int, f func() ([]*metav1.APIGroup, []*metav1.APIResourceList, error)) ([]*metav1.APIGroup, []*metav1.APIResourceList, error) {\n\tvar result []*metav1.APIResourceList\n\tvar resultGroups []*metav1.APIGroup\n\tvar err error\n\tfor i := 0; i \u003c maxRetries; i++ {\n\t\tresultGroups, result, err = f()\n\t\tif err == nil {\n\t\t\treturn resultGroups, result, nil\n\t\t}\n\t\tif _, ok := err.(*ErrGroupDiscoveryFailed); !ok {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\treturn resultGroups, result, err\n}","line":{"from":667,"to":682}} {"id":100025046,"name":"setDiscoveryDefaults","signature":"func setDiscoveryDefaults(config *restclient.Config) error","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"func setDiscoveryDefaults(config *restclient.Config) error {\n\tconfig.APIPath = \"\"\n\tconfig.GroupVersion = nil\n\tif config.Timeout == 0 {\n\t\tconfig.Timeout = defaultTimeout\n\t}\n\t// if a burst limit is not already configured\n\tif config.Burst == 0 {\n\t\t// discovery is expected to be bursty, increase the default burst\n\t\t// to accommodate looking up resource info for many API groups.\n\t\t// matches burst set by ConfigFlags#ToDiscoveryClient().\n\t\t// see https://issue.k8s.io/86149\n\t\tconfig.Burst = defaultBurst\n\t}\n\tcodec := runtime.NoopEncoder{Decoder: scheme.Codecs.UniversalDecoder()}\n\tconfig.NegotiatedSerializer = serializer.NegotiatedSerializerWrapper(runtime.SerializerInfo{Serializer: codec})\n\tif len(config.UserAgent) == 0 {\n\t\tconfig.UserAgent = restclient.DefaultKubernetesUserAgent()\n\t}\n\treturn nil\n}","line":{"from":684,"to":704}} {"id":100025047,"name":"NewDiscoveryClientForConfig","signature":"func NewDiscoveryClientForConfig(c *restclient.Config) (*DiscoveryClient, error)","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"// NewDiscoveryClientForConfig creates a new DiscoveryClient for the given config. This client\n// can be used to discover supported resources in the API server.\n// NewDiscoveryClientForConfig is equivalent to NewDiscoveryClientForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewDiscoveryClientForConfig(c *restclient.Config) (*DiscoveryClient, error) {\n\tconfig := *c\n\tif err := setDiscoveryDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := restclient.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewDiscoveryClientForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":706,"to":720}} {"id":100025048,"name":"NewDiscoveryClientForConfigAndClient","signature":"func NewDiscoveryClientForConfigAndClient(c *restclient.Config, httpClient *http.Client) (*DiscoveryClient, error)","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"// NewDiscoveryClientForConfigAndClient creates a new DiscoveryClient for the given config. This client\n// can be used to discover supported resources in the API server.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewDiscoveryClientForConfigAndClient(c *restclient.Config, httpClient *http.Client) (*DiscoveryClient, error) {\n\tconfig := *c\n\tif err := setDiscoveryDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := restclient.UnversionedRESTClientForConfigAndClient(\u0026config, httpClient)\n\treturn \u0026DiscoveryClient{restClient: client, LegacyPrefix: \"/api\", UseLegacyDiscovery: false}, err\n}","line":{"from":722,"to":732}} {"id":100025049,"name":"NewDiscoveryClientForConfigOrDie","signature":"func NewDiscoveryClientForConfigOrDie(c *restclient.Config) *DiscoveryClient","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"// NewDiscoveryClientForConfigOrDie creates a new DiscoveryClient for the given config. If\n// there is an error, it panics.\nfunc NewDiscoveryClientForConfigOrDie(c *restclient.Config) *DiscoveryClient {\n\tclient, err := NewDiscoveryClientForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n\n}","line":{"from":734,"to":743}} {"id":100025050,"name":"NewDiscoveryClient","signature":"func NewDiscoveryClient(c restclient.Interface) *DiscoveryClient","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"// NewDiscoveryClient returns a new DiscoveryClient for the given RESTClient.\nfunc NewDiscoveryClient(c restclient.Interface) *DiscoveryClient {\n\treturn \u0026DiscoveryClient{restClient: c, LegacyPrefix: \"/api\", UseLegacyDiscovery: false}\n}","line":{"from":745,"to":748}} {"id":100025051,"name":"RESTClient","signature":"func (d *DiscoveryClient) RESTClient() restclient.Interface","file":"staging/src/k8s.io/client-go/discovery/discovery_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (d *DiscoveryClient) RESTClient() restclient.Interface {\n\tif d == nil {\n\t\treturn nil\n\t}\n\treturn d.restClient\n}","line":{"from":750,"to":757}} {"id":100025052,"name":"IsResourceEnabled","signature":"func IsResourceEnabled(client DiscoveryInterface, resourceToCheck schema.GroupVersionResource) (bool, error)","file":"staging/src/k8s.io/client-go/discovery/helper.go","code":"// IsResourceEnabled queries the server to determine if the resource specified is present on the server.\n// This is particularly helpful when writing a controller or an e2e test that requires a particular resource to function.\nfunc IsResourceEnabled(client DiscoveryInterface, resourceToCheck schema.GroupVersionResource) (bool, error) {\n\t// this is a single request. The ServerResourcesForGroupVersion handles the core v1 group as legacy.\n\tresourceList, err := client.ServerResourcesForGroupVersion(resourceToCheck.GroupVersion().String())\n\tif apierrors.IsNotFound(err) { // if the discovery endpoint isn't present, then the resource isn't present.\n\t\treturn false, nil\n\t}\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tfor _, actualResource := range resourceList.APIResources {\n\t\tif actualResource.Name == resourceToCheck.Resource {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, nil\n}","line":{"from":29,"to":47}} {"id":100025053,"name":"MatchesServerVersion","signature":"func MatchesServerVersion(clientVersion apimachineryversion.Info, client DiscoveryInterface) error","file":"staging/src/k8s.io/client-go/discovery/helper.go","code":"// MatchesServerVersion queries the server to compares the build version\n// (git hash) of the client with the server's build version. It returns an error\n// if it failed to contact the server or if the versions are not an exact match.\nfunc MatchesServerVersion(clientVersion apimachineryversion.Info, client DiscoveryInterface) error {\n\tsVer, err := client.ServerVersion()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't read version from server: %v\", err)\n\t}\n\t// GitVersion includes GitCommit and GitTreeState, but best to be safe?\n\tif clientVersion.GitVersion != sVer.GitVersion || clientVersion.GitCommit != sVer.GitCommit || clientVersion.GitTreeState != sVer.GitTreeState {\n\t\treturn fmt.Errorf(\"server version (%#v) differs from client version (%#v)\", sVer, clientVersion)\n\t}\n\n\treturn nil\n}","line":{"from":49,"to":63}} {"id":100025054,"name":"ServerSupportsVersion","signature":"func ServerSupportsVersion(client DiscoveryInterface, requiredGV schema.GroupVersion) error","file":"staging/src/k8s.io/client-go/discovery/helper.go","code":"// ServerSupportsVersion returns an error if the server doesn't have the required version\nfunc ServerSupportsVersion(client DiscoveryInterface, requiredGV schema.GroupVersion) error {\n\tgroups, err := client.ServerGroups()\n\tif err != nil {\n\t\t// This is almost always a connection error, and higher level code should treat this as a generic error,\n\t\t// not a negotiation specific error.\n\t\treturn err\n\t}\n\tversions := metav1.ExtractGroupVersions(groups)\n\tserverVersions := sets.String{}\n\tfor _, v := range versions {\n\t\tserverVersions.Insert(v)\n\t}\n\n\tif serverVersions.Has(requiredGV.String()) {\n\t\treturn nil\n\t}\n\n\t// If the server supports no versions, then we should pretend it has the version because of old servers.\n\t// This can happen because discovery fails due to 403 Forbidden errors\n\tif len(serverVersions) == 0 {\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"server does not support API version %q\", requiredGV)\n}","line":{"from":65,"to":90}} {"id":100025055,"name":"GroupVersionResources","signature":"func GroupVersionResources(rls []*metav1.APIResourceList) (map[schema.GroupVersionResource]struct{}, error)","file":"staging/src/k8s.io/client-go/discovery/helper.go","code":"// GroupVersionResources converts APIResourceLists to the GroupVersionResources.\nfunc GroupVersionResources(rls []*metav1.APIResourceList) (map[schema.GroupVersionResource]struct{}, error) {\n\tgvrs := map[schema.GroupVersionResource]struct{}{}\n\tfor _, rl := range rls {\n\t\tgv, err := schema.ParseGroupVersion(rl.GroupVersion)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor i := range rl.APIResources {\n\t\t\tgvrs[schema.GroupVersionResource{Group: gv.Group, Version: gv.Version, Resource: rl.APIResources[i].Name}] = struct{}{}\n\t\t}\n\t}\n\treturn gvrs, nil\n}","line":{"from":92,"to":105}} {"id":100025056,"name":"FilteredBy","signature":"func FilteredBy(pred ResourcePredicate, rls []*metav1.APIResourceList) []*metav1.APIResourceList","file":"staging/src/k8s.io/client-go/discovery/helper.go","code":"// FilteredBy filters by the given predicate. Empty APIResourceLists are dropped.\nfunc FilteredBy(pred ResourcePredicate, rls []*metav1.APIResourceList) []*metav1.APIResourceList {\n\tresult := []*metav1.APIResourceList{}\n\tfor _, rl := range rls {\n\t\tfiltered := *rl\n\t\tfiltered.APIResources = nil\n\t\tfor i := range rl.APIResources {\n\t\t\tif pred.Match(rl.GroupVersion, \u0026rl.APIResources[i]) {\n\t\t\t\tfiltered.APIResources = append(filtered.APIResources, rl.APIResources[i])\n\t\t\t}\n\t\t}\n\t\tif filtered.APIResources != nil {\n\t\t\tresult = append(result, \u0026filtered)\n\t\t}\n\t}\n\treturn result\n}","line":{"from":107,"to":123}} {"id":100025057,"name":"Match","signature":"func (fn ResourcePredicateFunc) Match(groupVersion string, r *metav1.APIResource) bool","file":"staging/src/k8s.io/client-go/discovery/helper.go","code":"// Match is a wrapper around ResourcePredicateFunc.\nfunc (fn ResourcePredicateFunc) Match(groupVersion string, r *metav1.APIResource) bool {\n\treturn fn(groupVersion, r)\n}","line":{"from":133,"to":136}} {"id":100025058,"name":"Match","signature":"func (p SupportsAllVerbs) Match(groupVersion string, r *metav1.APIResource) bool","file":"staging/src/k8s.io/client-go/discovery/helper.go","code":"// Match checks if a resource contains all the given verbs.\nfunc (p SupportsAllVerbs) Match(groupVersion string, r *metav1.APIResource) bool {\n\treturn sets.NewString([]string(r.Verbs)...).HasAll(p.Verbs...)\n}","line":{"from":143,"to":146}} {"id":100025059,"name":"NewDynamicSharedInformerFactory","signature":"func NewDynamicSharedInformerFactory(client dynamic.Interface, defaultResync time.Duration) DynamicSharedInformerFactory","file":"staging/src/k8s.io/client-go/dynamic/dynamicinformer/informer.go","code":"// NewDynamicSharedInformerFactory constructs a new instance of dynamicSharedInformerFactory for all namespaces.\nfunc NewDynamicSharedInformerFactory(client dynamic.Interface, defaultResync time.Duration) DynamicSharedInformerFactory {\n\treturn NewFilteredDynamicSharedInformerFactory(client, defaultResync, metav1.NamespaceAll, nil)\n}","line":{"from":35,"to":38}} {"id":100025060,"name":"NewFilteredDynamicSharedInformerFactory","signature":"func NewFilteredDynamicSharedInformerFactory(client dynamic.Interface, defaultResync time.Duration, namespace string, tweakListOptions TweakListOptionsFunc) DynamicSharedInformerFactory","file":"staging/src/k8s.io/client-go/dynamic/dynamicinformer/informer.go","code":"// NewFilteredDynamicSharedInformerFactory constructs a new instance of dynamicSharedInformerFactory.\n// Listers obtained via this factory will be subject to the same filters as specified here.\nfunc NewFilteredDynamicSharedInformerFactory(client dynamic.Interface, defaultResync time.Duration, namespace string, tweakListOptions TweakListOptionsFunc) DynamicSharedInformerFactory {\n\treturn \u0026dynamicSharedInformerFactory{\n\t\tclient: client,\n\t\tdefaultResync: defaultResync,\n\t\tnamespace: namespace,\n\t\tinformers: map[schema.GroupVersionResource]informers.GenericInformer{},\n\t\tstartedInformers: make(map[schema.GroupVersionResource]bool),\n\t\ttweakListOptions: tweakListOptions,\n\t}\n}","line":{"from":40,"to":51}} {"id":100025061,"name":"ForResource","signature":"func (f *dynamicSharedInformerFactory) ForResource(gvr schema.GroupVersionResource) informers.GenericInformer","file":"staging/src/k8s.io/client-go/dynamic/dynamicinformer/informer.go","code":"func (f *dynamicSharedInformerFactory) ForResource(gvr schema.GroupVersionResource) informers.GenericInformer {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\n\tkey := gvr\n\tinformer, exists := f.informers[key]\n\tif exists {\n\t\treturn informer\n\t}\n\n\tinformer = NewFilteredDynamicInformer(f.client, gvr, f.namespace, f.defaultResync, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n\tf.informers[key] = informer\n\n\treturn informer\n}","line":{"from":74,"to":88}} {"id":100025062,"name":"Start","signature":"func (f *dynamicSharedInformerFactory) Start(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/client-go/dynamic/dynamicinformer/informer.go","code":"// Start initializes all requested informers.\nfunc (f *dynamicSharedInformerFactory) Start(stopCh \u003c-chan struct{}) {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\n\tif f.shuttingDown {\n\t\treturn\n\t}\n\n\tfor informerType, informer := range f.informers {\n\t\tif !f.startedInformers[informerType] {\n\t\t\tf.wg.Add(1)\n\t\t\t// We need a new variable in each loop iteration,\n\t\t\t// otherwise the goroutine would use the loop variable\n\t\t\t// and that keeps changing.\n\t\t\tinformer := informer.Informer()\n\t\t\tgo func() {\n\t\t\t\tdefer f.wg.Done()\n\t\t\t\tinformer.Run(stopCh)\n\t\t\t}()\n\t\t\tf.startedInformers[informerType] = true\n\t\t}\n\t}\n}","line":{"from":90,"to":113}} {"id":100025063,"name":"WaitForCacheSync","signature":"func (f *dynamicSharedInformerFactory) WaitForCacheSync(stopCh \u003c-chan struct{}) map[schema.GroupVersionResource]bool","file":"staging/src/k8s.io/client-go/dynamic/dynamicinformer/informer.go","code":"// WaitForCacheSync waits for all started informers' cache were synced.\nfunc (f *dynamicSharedInformerFactory) WaitForCacheSync(stopCh \u003c-chan struct{}) map[schema.GroupVersionResource]bool {\n\tinformers := func() map[schema.GroupVersionResource]cache.SharedIndexInformer {\n\t\tf.lock.Lock()\n\t\tdefer f.lock.Unlock()\n\n\t\tinformers := map[schema.GroupVersionResource]cache.SharedIndexInformer{}\n\t\tfor informerType, informer := range f.informers {\n\t\t\tif f.startedInformers[informerType] {\n\t\t\t\tinformers[informerType] = informer.Informer()\n\t\t\t}\n\t\t}\n\t\treturn informers\n\t}()\n\n\tres := map[schema.GroupVersionResource]bool{}\n\tfor informType, informer := range informers {\n\t\tres[informType] = cache.WaitForCacheSync(stopCh, informer.HasSynced)\n\t}\n\treturn res\n}","line":{"from":115,"to":135}} {"id":100025064,"name":"Shutdown","signature":"func (f *dynamicSharedInformerFactory) Shutdown()","file":"staging/src/k8s.io/client-go/dynamic/dynamicinformer/informer.go","code":"func (f *dynamicSharedInformerFactory) Shutdown() {\n\t// Will return immediately if there is nothing to wait for.\n\tdefer f.wg.Wait()\n\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\tf.shuttingDown = true\n}","line":{"from":137,"to":144}} {"id":100025065,"name":"NewFilteredDynamicInformer","signature":"func NewFilteredDynamicInformer(client dynamic.Interface, gvr schema.GroupVersionResource, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions TweakListOptionsFunc) informers.GenericInformer","file":"staging/src/k8s.io/client-go/dynamic/dynamicinformer/informer.go","code":"// NewFilteredDynamicInformer constructs a new informer for a dynamic type.\nfunc NewFilteredDynamicInformer(client dynamic.Interface, gvr schema.GroupVersionResource, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions TweakListOptionsFunc) informers.GenericInformer {\n\treturn \u0026dynamicInformer{\n\t\tgvr: gvr,\n\t\tinformer: cache.NewSharedIndexInformerWithOptions(\n\t\t\t\u0026cache.ListWatch{\n\t\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t\t}\n\t\t\t\t\treturn client.Resource(gvr).Namespace(namespace).List(context.TODO(), options)\n\t\t\t\t},\n\t\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t\t}\n\t\t\t\t\treturn client.Resource(gvr).Namespace(namespace).Watch(context.TODO(), options)\n\t\t\t\t},\n\t\t\t},\n\t\t\t\u0026unstructured.Unstructured{},\n\t\t\tcache.SharedIndexInformerOptions{\n\t\t\t\tResyncPeriod: resyncPeriod,\n\t\t\t\tIndexers: indexers,\n\t\t\t\tObjectDescription: gvr.String(),\n\t\t\t},\n\t\t),\n\t}\n}","line":{"from":146,"to":173}} {"id":100025066,"name":"Informer","signature":"func (d *dynamicInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/dynamic/dynamicinformer/informer.go","code":"func (d *dynamicInformer) Informer() cache.SharedIndexInformer {\n\treturn d.informer\n}","line":{"from":182,"to":184}} {"id":100025067,"name":"Lister","signature":"func (d *dynamicInformer) Lister() cache.GenericLister","file":"staging/src/k8s.io/client-go/dynamic/dynamicinformer/informer.go","code":"func (d *dynamicInformer) Lister() cache.GenericLister {\n\treturn dynamiclister.NewRuntimeObjectShim(dynamiclister.New(d.informer.GetIndexer(), d.gvr))\n}","line":{"from":186,"to":188}} {"id":100025068,"name":"New","signature":"func New(indexer cache.Indexer, gvr schema.GroupVersionResource) Lister","file":"staging/src/k8s.io/client-go/dynamic/dynamiclister/lister.go","code":"// New returns a new Lister.\nfunc New(indexer cache.Indexer, gvr schema.GroupVersionResource) Lister {\n\treturn \u0026dynamicLister{indexer: indexer, gvr: gvr}\n}","line":{"from":36,"to":39}} {"id":100025069,"name":"List","signature":"func (l *dynamicLister) List(selector labels.Selector) (ret []*unstructured.Unstructured, err error)","file":"staging/src/k8s.io/client-go/dynamic/dynamiclister/lister.go","code":"// List lists all resources in the indexer.\nfunc (l *dynamicLister) List(selector labels.Selector) (ret []*unstructured.Unstructured, err error) {\n\terr = cache.ListAll(l.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*unstructured.Unstructured))\n\t})\n\treturn ret, err\n}","line":{"from":41,"to":47}} {"id":100025070,"name":"Get","signature":"func (l *dynamicLister) Get(name string) (*unstructured.Unstructured, error)","file":"staging/src/k8s.io/client-go/dynamic/dynamiclister/lister.go","code":"// Get retrieves a resource from the indexer with the given name\nfunc (l *dynamicLister) Get(name string) (*unstructured.Unstructured, error) {\n\tobj, exists, err := l.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(l.gvr.GroupResource(), name)\n\t}\n\treturn obj.(*unstructured.Unstructured), nil\n}","line":{"from":49,"to":59}} {"id":100025071,"name":"Namespace","signature":"func (l *dynamicLister) Namespace(namespace string) NamespaceLister","file":"staging/src/k8s.io/client-go/dynamic/dynamiclister/lister.go","code":"// Namespace returns an object that can list and get resources from a given namespace.\nfunc (l *dynamicLister) Namespace(namespace string) NamespaceLister {\n\treturn \u0026dynamicNamespaceLister{indexer: l.indexer, namespace: namespace, gvr: l.gvr}\n}","line":{"from":61,"to":64}} {"id":100025072,"name":"List","signature":"func (l *dynamicNamespaceLister) List(selector labels.Selector) (ret []*unstructured.Unstructured, err error)","file":"staging/src/k8s.io/client-go/dynamic/dynamiclister/lister.go","code":"// List lists all resources in the indexer for a given namespace.\nfunc (l *dynamicNamespaceLister) List(selector labels.Selector) (ret []*unstructured.Unstructured, err error) {\n\terr = cache.ListAllByNamespace(l.indexer, l.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*unstructured.Unstructured))\n\t})\n\treturn ret, err\n}","line":{"from":73,"to":79}} {"id":100025073,"name":"Get","signature":"func (l *dynamicNamespaceLister) Get(name string) (*unstructured.Unstructured, error)","file":"staging/src/k8s.io/client-go/dynamic/dynamiclister/lister.go","code":"// Get retrieves a resource from the indexer for a given namespace and name.\nfunc (l *dynamicNamespaceLister) Get(name string) (*unstructured.Unstructured, error) {\n\tobj, exists, err := l.indexer.GetByKey(l.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(l.gvr.GroupResource(), name)\n\t}\n\treturn obj.(*unstructured.Unstructured), nil\n}","line":{"from":81,"to":91}} {"id":100025074,"name":"NewRuntimeObjectShim","signature":"func NewRuntimeObjectShim(lister Lister) cache.GenericLister","file":"staging/src/k8s.io/client-go/dynamic/dynamiclister/shim.go","code":"// NewRuntimeObjectShim returns a new shim for Lister.\n// It wraps Lister so that it implements cache.GenericLister interface\nfunc NewRuntimeObjectShim(lister Lister) cache.GenericLister {\n\treturn \u0026dynamicListerShim{lister: lister}\n}","line":{"from":33,"to":37}} {"id":100025075,"name":"List","signature":"func (s *dynamicListerShim) List(selector labels.Selector) (ret []runtime.Object, err error)","file":"staging/src/k8s.io/client-go/dynamic/dynamiclister/shim.go","code":"// List will return all objects across namespaces\nfunc (s *dynamicListerShim) List(selector labels.Selector) (ret []runtime.Object, err error) {\n\tobjs, err := s.lister.List(selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret = make([]runtime.Object, len(objs))\n\tfor index, obj := range objs {\n\t\tret[index] = obj\n\t}\n\treturn ret, err\n}","line":{"from":39,"to":51}} {"id":100025076,"name":"Get","signature":"func (s *dynamicListerShim) Get(name string) (runtime.Object, error)","file":"staging/src/k8s.io/client-go/dynamic/dynamiclister/shim.go","code":"// Get will attempt to retrieve assuming that name==key\nfunc (s *dynamicListerShim) Get(name string) (runtime.Object, error) {\n\treturn s.lister.Get(name)\n}","line":{"from":53,"to":56}} {"id":100025077,"name":"ByNamespace","signature":"func (s *dynamicListerShim) ByNamespace(namespace string) cache.GenericNamespaceLister","file":"staging/src/k8s.io/client-go/dynamic/dynamiclister/shim.go","code":"func (s *dynamicListerShim) ByNamespace(namespace string) cache.GenericNamespaceLister {\n\treturn \u0026dynamicNamespaceListerShim{\n\t\tnamespaceLister: s.lister.Namespace(namespace),\n\t}\n}","line":{"from":58,"to":62}} {"id":100025078,"name":"List","signature":"func (ns *dynamicNamespaceListerShim) List(selector labels.Selector) (ret []runtime.Object, err error)","file":"staging/src/k8s.io/client-go/dynamic/dynamiclister/shim.go","code":"// List will return all objects in this namespace\nfunc (ns *dynamicNamespaceListerShim) List(selector labels.Selector) (ret []runtime.Object, err error) {\n\tobjs, err := ns.namespaceLister.List(selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret = make([]runtime.Object, len(objs))\n\tfor index, obj := range objs {\n\t\tret[index] = obj\n\t}\n\treturn ret, err\n}","line":{"from":70,"to":82}} {"id":100025079,"name":"Get","signature":"func (ns *dynamicNamespaceListerShim) Get(name string) (runtime.Object, error)","file":"staging/src/k8s.io/client-go/dynamic/dynamiclister/shim.go","code":"// Get will attempt to retrieve by namespace and name\nfunc (ns *dynamicNamespaceListerShim) Get(name string) (runtime.Object, error) {\n\treturn ns.namespaceLister.Get(name)\n}","line":{"from":84,"to":87}} {"id":100025080,"name":"LegacyAPIPathResolverFunc","signature":"func LegacyAPIPathResolverFunc(kind schema.GroupVersionKind) string","file":"staging/src/k8s.io/client-go/dynamic/interface.go","code":"// LegacyAPIPathResolverFunc can resolve paths properly with the legacy API.\n// TODO find a better place to move this for existing callers\nfunc LegacyAPIPathResolverFunc(kind schema.GroupVersionKind) string {\n\tif len(kind.Group) == 0 {\n\t\treturn \"/api\"\n\t}\n\treturn \"/apis\"\n}","line":{"from":56,"to":63}} {"id":100025081,"name":"init","signature":"func init()","file":"staging/src/k8s.io/client-go/dynamic/scheme.go","code":"func init() {\n\tmetav1.AddToGroupVersion(watchScheme, versionV1)\n\tmetav1.AddToGroupVersion(basicScheme, versionV1)\n\tmetav1.AddToGroupVersion(parameterScheme, versionV1)\n\tmetav1.AddToGroupVersion(deleteScheme, versionV1)\n}","line":{"from":37,"to":42}} {"id":100025082,"name":"SupportedMediaTypes","signature":"func (s basicNegotiatedSerializer) SupportedMediaTypes() []runtime.SerializerInfo","file":"staging/src/k8s.io/client-go/dynamic/scheme.go","code":"func (s basicNegotiatedSerializer) SupportedMediaTypes() []runtime.SerializerInfo {\n\treturn []runtime.SerializerInfo{\n\t\t{\n\t\t\tMediaType: \"application/json\",\n\t\t\tMediaTypeType: \"application\",\n\t\t\tMediaTypeSubType: \"json\",\n\t\t\tEncodesAsText: true,\n\t\t\tSerializer: json.NewSerializer(json.DefaultMetaFactory, unstructuredCreater{basicScheme}, unstructuredTyper{basicScheme}, false),\n\t\t\tPrettySerializer: json.NewSerializer(json.DefaultMetaFactory, unstructuredCreater{basicScheme}, unstructuredTyper{basicScheme}, true),\n\t\t\tStreamSerializer: \u0026runtime.StreamSerializerInfo{\n\t\t\t\tEncodesAsText: true,\n\t\t\t\tSerializer: json.NewSerializer(json.DefaultMetaFactory, basicScheme, basicScheme, false),\n\t\t\t\tFramer: json.Framer,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":47,"to":63}} {"id":100025083,"name":"EncoderForVersion","signature":"func (s basicNegotiatedSerializer) EncoderForVersion(encoder runtime.Encoder, gv runtime.GroupVersioner) runtime.Encoder","file":"staging/src/k8s.io/client-go/dynamic/scheme.go","code":"func (s basicNegotiatedSerializer) EncoderForVersion(encoder runtime.Encoder, gv runtime.GroupVersioner) runtime.Encoder {\n\treturn runtime.WithVersionEncoder{\n\t\tVersion: gv,\n\t\tEncoder: encoder,\n\t\tObjectTyper: unstructuredTyper{basicScheme},\n\t}\n}","line":{"from":65,"to":71}} {"id":100025084,"name":"DecoderToVersion","signature":"func (s basicNegotiatedSerializer) DecoderToVersion(decoder runtime.Decoder, gv runtime.GroupVersioner) runtime.Decoder","file":"staging/src/k8s.io/client-go/dynamic/scheme.go","code":"func (s basicNegotiatedSerializer) DecoderToVersion(decoder runtime.Decoder, gv runtime.GroupVersioner) runtime.Decoder {\n\treturn decoder\n}","line":{"from":73,"to":75}} {"id":100025085,"name":"New","signature":"func (c unstructuredCreater) New(kind schema.GroupVersionKind) (runtime.Object, error)","file":"staging/src/k8s.io/client-go/dynamic/scheme.go","code":"func (c unstructuredCreater) New(kind schema.GroupVersionKind) (runtime.Object, error) {\n\tout, err := c.nested.New(kind)\n\tif err == nil {\n\t\treturn out, nil\n\t}\n\tout = \u0026unstructured.Unstructured{}\n\tout.GetObjectKind().SetGroupVersionKind(kind)\n\treturn out, nil\n}","line":{"from":81,"to":89}} {"id":100025086,"name":"ObjectKinds","signature":"func (t unstructuredTyper) ObjectKinds(obj runtime.Object) ([]schema.GroupVersionKind, bool, error)","file":"staging/src/k8s.io/client-go/dynamic/scheme.go","code":"func (t unstructuredTyper) ObjectKinds(obj runtime.Object) ([]schema.GroupVersionKind, bool, error) {\n\tkinds, unversioned, err := t.nested.ObjectKinds(obj)\n\tif err == nil {\n\t\treturn kinds, unversioned, nil\n\t}\n\tif _, ok := obj.(runtime.Unstructured); ok \u0026\u0026 !obj.GetObjectKind().GroupVersionKind().Empty() {\n\t\treturn []schema.GroupVersionKind{obj.GetObjectKind().GroupVersionKind()}, false, nil\n\t}\n\treturn nil, false, err\n}","line":{"from":95,"to":104}} {"id":100025087,"name":"Recognizes","signature":"func (t unstructuredTyper) Recognizes(gvk schema.GroupVersionKind) bool","file":"staging/src/k8s.io/client-go/dynamic/scheme.go","code":"func (t unstructuredTyper) Recognizes(gvk schema.GroupVersionKind) bool {\n\treturn true\n}","line":{"from":106,"to":108}} {"id":100025088,"name":"ConfigFor","signature":"func ConfigFor(inConfig *rest.Config) *rest.Config","file":"staging/src/k8s.io/client-go/dynamic/simple.go","code":"// ConfigFor returns a copy of the provided config with the\n// appropriate dynamic client defaults set.\nfunc ConfigFor(inConfig *rest.Config) *rest.Config {\n\tconfig := rest.CopyConfig(inConfig)\n\tconfig.AcceptContentTypes = \"application/json\"\n\tconfig.ContentType = \"application/json\"\n\tconfig.NegotiatedSerializer = basicNegotiatedSerializer{} // this gets used for discovery and error handling types\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\treturn config\n}","line":{"from":40,"to":51}} {"id":100025089,"name":"New","signature":"func New(c rest.Interface) *DynamicClient","file":"staging/src/k8s.io/client-go/dynamic/simple.go","code":"// New creates a new DynamicClient for the given RESTClient.\nfunc New(c rest.Interface) *DynamicClient {\n\treturn \u0026DynamicClient{client: c}\n}","line":{"from":53,"to":56}} {"id":100025090,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *DynamicClient","file":"staging/src/k8s.io/client-go/dynamic/simple.go","code":"// NewForConfigOrDie creates a new DynamicClient for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *DynamicClient {\n\tret, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ret\n}","line":{"from":58,"to":66}} {"id":100025091,"name":"NewForConfig","signature":"func NewForConfig(inConfig *rest.Config) (*DynamicClient, error)","file":"staging/src/k8s.io/client-go/dynamic/simple.go","code":"// NewForConfig creates a new dynamic client or returns an error.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(inConfig *rest.Config) (*DynamicClient, error) {\n\tconfig := ConfigFor(inConfig)\n\n\thttpClient, err := rest.HTTPClientFor(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(config, httpClient)\n}","line":{"from":68,"to":79}} {"id":100025092,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(inConfig *rest.Config, h *http.Client) (*DynamicClient, error)","file":"staging/src/k8s.io/client-go/dynamic/simple.go","code":"// NewForConfigAndClient creates a new dynamic client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(inConfig *rest.Config, h *http.Client) (*DynamicClient, error) {\n\tconfig := ConfigFor(inConfig)\n\t// for serializing the options\n\tconfig.GroupVersion = \u0026schema.GroupVersion{}\n\tconfig.APIPath = \"/if-you-see-this-search-for-the-break\"\n\n\trestClient, err := rest.RESTClientForConfigAndClient(config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026DynamicClient{client: restClient}, nil\n}","line":{"from":81,"to":94}} {"id":100025093,"name":"Resource","signature":"func (c *DynamicClient) Resource(resource schema.GroupVersionResource) NamespaceableResourceInterface","file":"staging/src/k8s.io/client-go/dynamic/simple.go","code":"func (c *DynamicClient) Resource(resource schema.GroupVersionResource) NamespaceableResourceInterface {\n\treturn \u0026dynamicResourceClient{client: c, resource: resource}\n}","line":{"from":102,"to":104}} {"id":100025094,"name":"Namespace","signature":"func (c *dynamicResourceClient) Namespace(ns string) ResourceInterface","file":"staging/src/k8s.io/client-go/dynamic/simple.go","code":"func (c *dynamicResourceClient) Namespace(ns string) ResourceInterface {\n\tret := *c\n\tret.namespace = ns\n\treturn \u0026ret\n}","line":{"from":106,"to":110}} {"id":100025095,"name":"Create","signature":"func (c *dynamicResourceClient) Create(ctx context.Context, obj *unstructured.Unstructured, opts metav1.CreateOptions, subresources ...string) (*unstructured.Unstructured, error)","file":"staging/src/k8s.io/client-go/dynamic/simple.go","code":"func (c *dynamicResourceClient) Create(ctx context.Context, obj *unstructured.Unstructured, opts metav1.CreateOptions, subresources ...string) (*unstructured.Unstructured, error) {\n\toutBytes, err := runtime.Encode(unstructured.UnstructuredJSONScheme, obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := \"\"\n\tif len(subresources) \u003e 0 {\n\t\taccessor, err := meta.Accessor(obj)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tname = accessor.GetName()\n\t\tif len(name) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"name is required\")\n\t\t}\n\t}\n\tif err := validateNamespaceWithOptionalName(c.namespace, name); err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := c.client.client.\n\t\tPost().\n\t\tAbsPath(append(c.makeURLSegments(name), subresources...)...).\n\t\tSetHeader(\"Content-Type\", runtime.ContentTypeJSON).\n\t\tBody(outBytes).\n\t\tSpecificallyVersionedParams(\u0026opts, dynamicParameterCodec, versionV1).\n\t\tDo(ctx)\n\tif err := result.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tretBytes, err := result.Raw()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn uncastObj.(*unstructured.Unstructured), nil\n}","line":{"from":112,"to":152}} {"id":100025096,"name":"Update","signature":"func (c *dynamicResourceClient) Update(ctx context.Context, obj *unstructured.Unstructured, opts metav1.UpdateOptions, subresources ...string) (*unstructured.Unstructured, error)","file":"staging/src/k8s.io/client-go/dynamic/simple.go","code":"func (c *dynamicResourceClient) Update(ctx context.Context, obj *unstructured.Unstructured, opts metav1.UpdateOptions, subresources ...string) (*unstructured.Unstructured, error) {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := accessor.GetName()\n\tif len(name) == 0 {\n\t\treturn nil, fmt.Errorf(\"name is required\")\n\t}\n\tif err := validateNamespaceWithOptionalName(c.namespace, name); err != nil {\n\t\treturn nil, err\n\t}\n\toutBytes, err := runtime.Encode(unstructured.UnstructuredJSONScheme, obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := c.client.client.\n\t\tPut().\n\t\tAbsPath(append(c.makeURLSegments(name), subresources...)...).\n\t\tSetHeader(\"Content-Type\", runtime.ContentTypeJSON).\n\t\tBody(outBytes).\n\t\tSpecificallyVersionedParams(\u0026opts, dynamicParameterCodec, versionV1).\n\t\tDo(ctx)\n\tif err := result.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tretBytes, err := result.Raw()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn uncastObj.(*unstructured.Unstructured), nil\n}","line":{"from":154,"to":191}} {"id":100025097,"name":"UpdateStatus","signature":"func (c *dynamicResourceClient) UpdateStatus(ctx context.Context, obj *unstructured.Unstructured, opts metav1.UpdateOptions) (*unstructured.Unstructured, error)","file":"staging/src/k8s.io/client-go/dynamic/simple.go","code":"func (c *dynamicResourceClient) UpdateStatus(ctx context.Context, obj *unstructured.Unstructured, opts metav1.UpdateOptions) (*unstructured.Unstructured, error) {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := accessor.GetName()\n\tif len(name) == 0 {\n\t\treturn nil, fmt.Errorf(\"name is required\")\n\t}\n\tif err := validateNamespaceWithOptionalName(c.namespace, name); err != nil {\n\t\treturn nil, err\n\t}\n\toutBytes, err := runtime.Encode(unstructured.UnstructuredJSONScheme, obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := c.client.client.\n\t\tPut().\n\t\tAbsPath(append(c.makeURLSegments(name), \"status\")...).\n\t\tSetHeader(\"Content-Type\", runtime.ContentTypeJSON).\n\t\tBody(outBytes).\n\t\tSpecificallyVersionedParams(\u0026opts, dynamicParameterCodec, versionV1).\n\t\tDo(ctx)\n\tif err := result.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tretBytes, err := result.Raw()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn uncastObj.(*unstructured.Unstructured), nil\n}","line":{"from":193,"to":230}} {"id":100025098,"name":"Delete","signature":"func (c *dynamicResourceClient) Delete(ctx context.Context, name string, opts metav1.DeleteOptions, subresources ...string) error","file":"staging/src/k8s.io/client-go/dynamic/simple.go","code":"func (c *dynamicResourceClient) Delete(ctx context.Context, name string, opts metav1.DeleteOptions, subresources ...string) error {\n\tif len(name) == 0 {\n\t\treturn fmt.Errorf(\"name is required\")\n\t}\n\tif err := validateNamespaceWithOptionalName(c.namespace, name); err != nil {\n\t\treturn err\n\t}\n\tdeleteOptionsByte, err := runtime.Encode(deleteOptionsCodec.LegacyCodec(schema.GroupVersion{Version: \"v1\"}), \u0026opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresult := c.client.client.\n\t\tDelete().\n\t\tAbsPath(append(c.makeURLSegments(name), subresources...)...).\n\t\tSetHeader(\"Content-Type\", runtime.ContentTypeJSON).\n\t\tBody(deleteOptionsByte).\n\t\tDo(ctx)\n\treturn result.Error()\n}","line":{"from":232,"to":251}} {"id":100025099,"name":"DeleteCollection","signature":"func (c *dynamicResourceClient) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOptions metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/dynamic/simple.go","code":"func (c *dynamicResourceClient) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOptions metav1.ListOptions) error {\n\tif err := validateNamespaceWithOptionalName(c.namespace); err != nil {\n\t\treturn err\n\t}\n\n\tdeleteOptionsByte, err := runtime.Encode(deleteOptionsCodec.LegacyCodec(schema.GroupVersion{Version: \"v1\"}), \u0026opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresult := c.client.client.\n\t\tDelete().\n\t\tAbsPath(c.makeURLSegments(\"\")...).\n\t\tSetHeader(\"Content-Type\", runtime.ContentTypeJSON).\n\t\tBody(deleteOptionsByte).\n\t\tSpecificallyVersionedParams(\u0026listOptions, dynamicParameterCodec, versionV1).\n\t\tDo(ctx)\n\treturn result.Error()\n}","line":{"from":253,"to":271}} {"id":100025100,"name":"Get","signature":"func (c *dynamicResourceClient) Get(ctx context.Context, name string, opts metav1.GetOptions, subresources ...string) (*unstructured.Unstructured, error)","file":"staging/src/k8s.io/client-go/dynamic/simple.go","code":"func (c *dynamicResourceClient) Get(ctx context.Context, name string, opts metav1.GetOptions, subresources ...string) (*unstructured.Unstructured, error) {\n\tif len(name) == 0 {\n\t\treturn nil, fmt.Errorf(\"name is required\")\n\t}\n\tif err := validateNamespaceWithOptionalName(c.namespace, name); err != nil {\n\t\treturn nil, err\n\t}\n\tresult := c.client.client.Get().AbsPath(append(c.makeURLSegments(name), subresources...)...).SpecificallyVersionedParams(\u0026opts, dynamicParameterCodec, versionV1).Do(ctx)\n\tif err := result.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\tretBytes, err := result.Raw()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn uncastObj.(*unstructured.Unstructured), nil\n}","line":{"from":273,"to":293}} {"id":100025101,"name":"List","signature":"func (c *dynamicResourceClient) List(ctx context.Context, opts metav1.ListOptions) (*unstructured.UnstructuredList, error)","file":"staging/src/k8s.io/client-go/dynamic/simple.go","code":"func (c *dynamicResourceClient) List(ctx context.Context, opts metav1.ListOptions) (*unstructured.UnstructuredList, error) {\n\tif err := validateNamespaceWithOptionalName(c.namespace); err != nil {\n\t\treturn nil, err\n\t}\n\tresult := c.client.client.Get().AbsPath(c.makeURLSegments(\"\")...).SpecificallyVersionedParams(\u0026opts, dynamicParameterCodec, versionV1).Do(ctx)\n\tif err := result.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\tretBytes, err := result.Raw()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif list, ok := uncastObj.(*unstructured.UnstructuredList); ok {\n\t\treturn list, nil\n\t}\n\n\tlist, err := uncastObj.(*unstructured.Unstructured).ToList()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn list, nil\n}","line":{"from":295,"to":320}} {"id":100025102,"name":"Watch","signature":"func (c *dynamicResourceClient) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/dynamic/simple.go","code":"func (c *dynamicResourceClient) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\topts.Watch = true\n\tif err := validateNamespaceWithOptionalName(c.namespace); err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.client.client.Get().AbsPath(c.makeURLSegments(\"\")...).\n\t\tSpecificallyVersionedParams(\u0026opts, dynamicParameterCodec, versionV1).\n\t\tWatch(ctx)\n}","line":{"from":322,"to":330}} {"id":100025103,"name":"Patch","signature":"func (c *dynamicResourceClient) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (*unstructured.Unstructured, error)","file":"staging/src/k8s.io/client-go/dynamic/simple.go","code":"func (c *dynamicResourceClient) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (*unstructured.Unstructured, error) {\n\tif len(name) == 0 {\n\t\treturn nil, fmt.Errorf(\"name is required\")\n\t}\n\tif err := validateNamespaceWithOptionalName(c.namespace, name); err != nil {\n\t\treturn nil, err\n\t}\n\tresult := c.client.client.\n\t\tPatch(pt).\n\t\tAbsPath(append(c.makeURLSegments(name), subresources...)...).\n\t\tBody(data).\n\t\tSpecificallyVersionedParams(\u0026opts, dynamicParameterCodec, versionV1).\n\t\tDo(ctx)\n\tif err := result.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\tretBytes, err := result.Raw()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn uncastObj.(*unstructured.Unstructured), nil\n}","line":{"from":332,"to":357}} {"id":100025104,"name":"Apply","signature":"func (c *dynamicResourceClient) Apply(ctx context.Context, name string, obj *unstructured.Unstructured, opts metav1.ApplyOptions, subresources ...string) (*unstructured.Unstructured, error)","file":"staging/src/k8s.io/client-go/dynamic/simple.go","code":"func (c *dynamicResourceClient) Apply(ctx context.Context, name string, obj *unstructured.Unstructured, opts metav1.ApplyOptions, subresources ...string) (*unstructured.Unstructured, error) {\n\tif len(name) == 0 {\n\t\treturn nil, fmt.Errorf(\"name is required\")\n\t}\n\tif err := validateNamespaceWithOptionalName(c.namespace, name); err != nil {\n\t\treturn nil, err\n\t}\n\toutBytes, err := runtime.Encode(unstructured.UnstructuredJSONScheme, obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmanagedFields := accessor.GetManagedFields()\n\tif len(managedFields) \u003e 0 {\n\t\treturn nil, fmt.Errorf(`cannot apply an object with managed fields already set.\n\t\tUse the client-go/applyconfigurations \"UnstructructuredExtractor\" to obtain the unstructured ApplyConfiguration for the given field manager that you can use/modify here to apply`)\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\n\tresult := c.client.client.\n\t\tPatch(types.ApplyPatchType).\n\t\tAbsPath(append(c.makeURLSegments(name), subresources...)...).\n\t\tBody(outBytes).\n\t\tSpecificallyVersionedParams(\u0026patchOpts, dynamicParameterCodec, versionV1).\n\t\tDo(ctx)\n\tif err := result.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\tretBytes, err := result.Raw()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn uncastObj.(*unstructured.Unstructured), nil\n}","line":{"from":359,"to":399}} {"id":100025105,"name":"ApplyStatus","signature":"func (c *dynamicResourceClient) ApplyStatus(ctx context.Context, name string, obj *unstructured.Unstructured, opts metav1.ApplyOptions) (*unstructured.Unstructured, error)","file":"staging/src/k8s.io/client-go/dynamic/simple.go","code":"func (c *dynamicResourceClient) ApplyStatus(ctx context.Context, name string, obj *unstructured.Unstructured, opts metav1.ApplyOptions) (*unstructured.Unstructured, error) {\n\treturn c.Apply(ctx, name, obj, opts, \"status\")\n}","line":{"from":400,"to":402}} {"id":100025106,"name":"validateNamespaceWithOptionalName","signature":"func validateNamespaceWithOptionalName(namespace string, name ...string) error","file":"staging/src/k8s.io/client-go/dynamic/simple.go","code":"func validateNamespaceWithOptionalName(namespace string, name ...string) error {\n\tif msgs := rest.IsValidPathSegmentName(namespace); len(msgs) != 0 {\n\t\treturn fmt.Errorf(\"invalid namespace %q: %v\", namespace, msgs)\n\t}\n\tif len(name) \u003e 1 {\n\t\tpanic(\"Invalid number of names\")\n\t} else if len(name) == 1 {\n\t\tif msgs := rest.IsValidPathSegmentName(name[0]); len(msgs) != 0 {\n\t\t\treturn fmt.Errorf(\"invalid resource name %q: %v\", name[0], msgs)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":404,"to":416}} {"id":100025107,"name":"makeURLSegments","signature":"func (c *dynamicResourceClient) makeURLSegments(name string) []string","file":"staging/src/k8s.io/client-go/dynamic/simple.go","code":"func (c *dynamicResourceClient) makeURLSegments(name string) []string {\n\turl := []string{}\n\tif len(c.resource.Group) == 0 {\n\t\turl = append(url, \"api\")\n\t} else {\n\t\turl = append(url, \"apis\", c.resource.Group)\n\t}\n\turl = append(url, c.resource.Version)\n\n\tif len(c.namespace) \u003e 0 {\n\t\turl = append(url, \"namespaces\", c.namespace)\n\t}\n\turl = append(url, c.resource.Resource)\n\n\tif len(name) \u003e 0 {\n\t\turl = append(url, name)\n\t}\n\n\treturn url\n}","line":{"from":418,"to":437}} {"id":100025108,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/admissionregistration/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":44,"to":47}} {"id":100025109,"name":"V1","signature":"func (g *group) V1() v1.Interface","file":"staging/src/k8s.io/client-go/informers/admissionregistration/interface.go","code":"// V1 returns a new v1.Interface.\nfunc (g *group) V1() v1.Interface {\n\treturn v1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":49,"to":52}} {"id":100025110,"name":"V1alpha1","signature":"func (g *group) V1alpha1() v1alpha1.Interface","file":"staging/src/k8s.io/client-go/informers/admissionregistration/interface.go","code":"// V1alpha1 returns a new v1alpha1.Interface.\nfunc (g *group) V1alpha1() v1alpha1.Interface {\n\treturn v1alpha1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":54,"to":57}} {"id":100025111,"name":"V1beta1","signature":"func (g *group) V1beta1() v1beta1.Interface","file":"staging/src/k8s.io/client-go/informers/admissionregistration/interface.go","code":"// V1beta1 returns a new v1beta1.Interface.\nfunc (g *group) V1beta1() v1beta1.Interface {\n\treturn v1beta1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":59,"to":62}} {"id":100025112,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":39,"to":42}} {"id":100025113,"name":"MutatingWebhookConfigurations","signature":"func (v *version) MutatingWebhookConfigurations() MutatingWebhookConfigurationInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1/interface.go","code":"// MutatingWebhookConfigurations returns a MutatingWebhookConfigurationInformer.\nfunc (v *version) MutatingWebhookConfigurations() MutatingWebhookConfigurationInformer {\n\treturn \u0026mutatingWebhookConfigurationInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":44,"to":47}} {"id":100025114,"name":"ValidatingWebhookConfigurations","signature":"func (v *version) ValidatingWebhookConfigurations() ValidatingWebhookConfigurationInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1/interface.go","code":"// ValidatingWebhookConfigurations returns a ValidatingWebhookConfigurationInformer.\nfunc (v *version) ValidatingWebhookConfigurations() ValidatingWebhookConfigurationInformer {\n\treturn \u0026validatingWebhookConfigurationInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":49,"to":52}} {"id":100025115,"name":"NewMutatingWebhookConfigurationInformer","signature":"func NewMutatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// NewMutatingWebhookConfigurationInformer constructs a new informer for MutatingWebhookConfiguration type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewMutatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredMutatingWebhookConfigurationInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025116,"name":"NewFilteredMutatingWebhookConfigurationInformer","signature":"func NewFilteredMutatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// NewFilteredMutatingWebhookConfigurationInformer constructs a new informer for MutatingWebhookConfiguration type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredMutatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AdmissionregistrationV1().MutatingWebhookConfigurations().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AdmissionregistrationV1().MutatingWebhookConfigurations().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026admissionregistrationv1.MutatingWebhookConfiguration{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025117,"name":"defaultInformer","signature":"func (f *mutatingWebhookConfigurationInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"func (f *mutatingWebhookConfigurationInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredMutatingWebhookConfigurationInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025118,"name":"Informer","signature":"func (f *mutatingWebhookConfigurationInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"func (f *mutatingWebhookConfigurationInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026admissionregistrationv1.MutatingWebhookConfiguration{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025119,"name":"Lister","signature":"func (f *mutatingWebhookConfigurationInformer) Lister() v1.MutatingWebhookConfigurationLister","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"func (f *mutatingWebhookConfigurationInformer) Lister() v1.MutatingWebhookConfigurationLister {\n\treturn v1.NewMutatingWebhookConfigurationLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025120,"name":"NewValidatingWebhookConfigurationInformer","signature":"func NewValidatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// NewValidatingWebhookConfigurationInformer constructs a new informer for ValidatingWebhookConfiguration type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewValidatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredValidatingWebhookConfigurationInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025121,"name":"NewFilteredValidatingWebhookConfigurationInformer","signature":"func NewFilteredValidatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// NewFilteredValidatingWebhookConfigurationInformer constructs a new informer for ValidatingWebhookConfiguration type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredValidatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AdmissionregistrationV1().ValidatingWebhookConfigurations().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AdmissionregistrationV1().ValidatingWebhookConfigurations().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026admissionregistrationv1.ValidatingWebhookConfiguration{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025122,"name":"defaultInformer","signature":"func (f *validatingWebhookConfigurationInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1/validatingwebhookconfiguration.go","code":"func (f *validatingWebhookConfigurationInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredValidatingWebhookConfigurationInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025123,"name":"Informer","signature":"func (f *validatingWebhookConfigurationInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1/validatingwebhookconfiguration.go","code":"func (f *validatingWebhookConfigurationInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026admissionregistrationv1.ValidatingWebhookConfiguration{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025124,"name":"Lister","signature":"func (f *validatingWebhookConfigurationInformer) Lister() v1.ValidatingWebhookConfigurationLister","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1/validatingwebhookconfiguration.go","code":"func (f *validatingWebhookConfigurationInformer) Lister() v1.ValidatingWebhookConfigurationLister {\n\treturn v1.NewValidatingWebhookConfigurationLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025125,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1alpha1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":39,"to":42}} {"id":100025126,"name":"ValidatingAdmissionPolicies","signature":"func (v *version) ValidatingAdmissionPolicies() ValidatingAdmissionPolicyInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1alpha1/interface.go","code":"// ValidatingAdmissionPolicies returns a ValidatingAdmissionPolicyInformer.\nfunc (v *version) ValidatingAdmissionPolicies() ValidatingAdmissionPolicyInformer {\n\treturn \u0026validatingAdmissionPolicyInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":44,"to":47}} {"id":100025127,"name":"ValidatingAdmissionPolicyBindings","signature":"func (v *version) ValidatingAdmissionPolicyBindings() ValidatingAdmissionPolicyBindingInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1alpha1/interface.go","code":"// ValidatingAdmissionPolicyBindings returns a ValidatingAdmissionPolicyBindingInformer.\nfunc (v *version) ValidatingAdmissionPolicyBindings() ValidatingAdmissionPolicyBindingInformer {\n\treturn \u0026validatingAdmissionPolicyBindingInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":49,"to":52}} {"id":100025128,"name":"NewValidatingAdmissionPolicyInformer","signature":"func NewValidatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// NewValidatingAdmissionPolicyInformer constructs a new informer for ValidatingAdmissionPolicy type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewValidatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredValidatingAdmissionPolicyInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025129,"name":"NewFilteredValidatingAdmissionPolicyInformer","signature":"func NewFilteredValidatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// NewFilteredValidatingAdmissionPolicyInformer constructs a new informer for ValidatingAdmissionPolicy type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredValidatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AdmissionregistrationV1alpha1().ValidatingAdmissionPolicies().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AdmissionregistrationV1alpha1().ValidatingAdmissionPolicies().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026admissionregistrationv1alpha1.ValidatingAdmissionPolicy{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025130,"name":"defaultInformer","signature":"func (f *validatingAdmissionPolicyInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"func (f *validatingAdmissionPolicyInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredValidatingAdmissionPolicyInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025131,"name":"Informer","signature":"func (f *validatingAdmissionPolicyInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"func (f *validatingAdmissionPolicyInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026admissionregistrationv1alpha1.ValidatingAdmissionPolicy{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025132,"name":"Lister","signature":"func (f *validatingAdmissionPolicyInformer) Lister() v1alpha1.ValidatingAdmissionPolicyLister","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"func (f *validatingAdmissionPolicyInformer) Lister() v1alpha1.ValidatingAdmissionPolicyLister {\n\treturn v1alpha1.NewValidatingAdmissionPolicyLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025133,"name":"NewValidatingAdmissionPolicyBindingInformer","signature":"func NewValidatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// NewValidatingAdmissionPolicyBindingInformer constructs a new informer for ValidatingAdmissionPolicyBinding type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewValidatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredValidatingAdmissionPolicyBindingInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025134,"name":"NewFilteredValidatingAdmissionPolicyBindingInformer","signature":"func NewFilteredValidatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// NewFilteredValidatingAdmissionPolicyBindingInformer constructs a new informer for ValidatingAdmissionPolicyBinding type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredValidatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AdmissionregistrationV1alpha1().ValidatingAdmissionPolicyBindings().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AdmissionregistrationV1alpha1().ValidatingAdmissionPolicyBindings().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026admissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025135,"name":"defaultInformer","signature":"func (f *validatingAdmissionPolicyBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"func (f *validatingAdmissionPolicyBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredValidatingAdmissionPolicyBindingInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025136,"name":"Informer","signature":"func (f *validatingAdmissionPolicyBindingInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"func (f *validatingAdmissionPolicyBindingInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026admissionregistrationv1alpha1.ValidatingAdmissionPolicyBinding{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025137,"name":"Lister","signature":"func (f *validatingAdmissionPolicyBindingInformer) Lister() v1alpha1.ValidatingAdmissionPolicyBindingLister","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"func (f *validatingAdmissionPolicyBindingInformer) Lister() v1alpha1.ValidatingAdmissionPolicyBindingLister {\n\treturn v1alpha1.NewValidatingAdmissionPolicyBindingLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025138,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1beta1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":39,"to":42}} {"id":100025139,"name":"MutatingWebhookConfigurations","signature":"func (v *version) MutatingWebhookConfigurations() MutatingWebhookConfigurationInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1beta1/interface.go","code":"// MutatingWebhookConfigurations returns a MutatingWebhookConfigurationInformer.\nfunc (v *version) MutatingWebhookConfigurations() MutatingWebhookConfigurationInformer {\n\treturn \u0026mutatingWebhookConfigurationInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":44,"to":47}} {"id":100025140,"name":"ValidatingWebhookConfigurations","signature":"func (v *version) ValidatingWebhookConfigurations() ValidatingWebhookConfigurationInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1beta1/interface.go","code":"// ValidatingWebhookConfigurations returns a ValidatingWebhookConfigurationInformer.\nfunc (v *version) ValidatingWebhookConfigurations() ValidatingWebhookConfigurationInformer {\n\treturn \u0026validatingWebhookConfigurationInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":49,"to":52}} {"id":100025141,"name":"NewMutatingWebhookConfigurationInformer","signature":"func NewMutatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// NewMutatingWebhookConfigurationInformer constructs a new informer for MutatingWebhookConfiguration type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewMutatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredMutatingWebhookConfigurationInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025142,"name":"NewFilteredMutatingWebhookConfigurationInformer","signature":"func NewFilteredMutatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// NewFilteredMutatingWebhookConfigurationInformer constructs a new informer for MutatingWebhookConfiguration type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredMutatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AdmissionregistrationV1beta1().MutatingWebhookConfigurations().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AdmissionregistrationV1beta1().MutatingWebhookConfigurations().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026admissionregistrationv1beta1.MutatingWebhookConfiguration{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025143,"name":"defaultInformer","signature":"func (f *mutatingWebhookConfigurationInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"func (f *mutatingWebhookConfigurationInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredMutatingWebhookConfigurationInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025144,"name":"Informer","signature":"func (f *mutatingWebhookConfigurationInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"func (f *mutatingWebhookConfigurationInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026admissionregistrationv1beta1.MutatingWebhookConfiguration{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025145,"name":"Lister","signature":"func (f *mutatingWebhookConfigurationInformer) Lister() v1beta1.MutatingWebhookConfigurationLister","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"func (f *mutatingWebhookConfigurationInformer) Lister() v1beta1.MutatingWebhookConfigurationLister {\n\treturn v1beta1.NewMutatingWebhookConfigurationLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025146,"name":"NewValidatingWebhookConfigurationInformer","signature":"func NewValidatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// NewValidatingWebhookConfigurationInformer constructs a new informer for ValidatingWebhookConfiguration type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewValidatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredValidatingWebhookConfigurationInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025147,"name":"NewFilteredValidatingWebhookConfigurationInformer","signature":"func NewFilteredValidatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// NewFilteredValidatingWebhookConfigurationInformer constructs a new informer for ValidatingWebhookConfiguration type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredValidatingWebhookConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AdmissionregistrationV1beta1().ValidatingWebhookConfigurations().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AdmissionregistrationV1beta1().ValidatingWebhookConfigurations().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026admissionregistrationv1beta1.ValidatingWebhookConfiguration{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025148,"name":"defaultInformer","signature":"func (f *validatingWebhookConfigurationInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"func (f *validatingWebhookConfigurationInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredValidatingWebhookConfigurationInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025149,"name":"Informer","signature":"func (f *validatingWebhookConfigurationInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"func (f *validatingWebhookConfigurationInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026admissionregistrationv1beta1.ValidatingWebhookConfiguration{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025150,"name":"Lister","signature":"func (f *validatingWebhookConfigurationInformer) Lister() v1beta1.ValidatingWebhookConfigurationLister","file":"staging/src/k8s.io/client-go/informers/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"func (f *validatingWebhookConfigurationInformer) Lister() v1beta1.ValidatingWebhookConfigurationLister {\n\treturn v1beta1.NewValidatingWebhookConfigurationLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025151,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/apiserverinternal/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":38,"to":41}} {"id":100025152,"name":"V1alpha1","signature":"func (g *group) V1alpha1() v1alpha1.Interface","file":"staging/src/k8s.io/client-go/informers/apiserverinternal/interface.go","code":"// V1alpha1 returns a new v1alpha1.Interface.\nfunc (g *group) V1alpha1() v1alpha1.Interface {\n\treturn v1alpha1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":43,"to":46}} {"id":100025153,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/apiserverinternal/v1alpha1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":37,"to":40}} {"id":100025154,"name":"StorageVersions","signature":"func (v *version) StorageVersions() StorageVersionInformer","file":"staging/src/k8s.io/client-go/informers/apiserverinternal/v1alpha1/interface.go","code":"// StorageVersions returns a StorageVersionInformer.\nfunc (v *version) StorageVersions() StorageVersionInformer {\n\treturn \u0026storageVersionInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":42,"to":45}} {"id":100025155,"name":"NewStorageVersionInformer","signature":"func NewStorageVersionInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apiserverinternal/v1alpha1/storageversion.go","code":"// NewStorageVersionInformer constructs a new informer for StorageVersion type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewStorageVersionInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredStorageVersionInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025156,"name":"NewFilteredStorageVersionInformer","signature":"func NewFilteredStorageVersionInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apiserverinternal/v1alpha1/storageversion.go","code":"// NewFilteredStorageVersionInformer constructs a new informer for StorageVersion type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredStorageVersionInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.InternalV1alpha1().StorageVersions().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.InternalV1alpha1().StorageVersions().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026apiserverinternalv1alpha1.StorageVersion{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025157,"name":"defaultInformer","signature":"func (f *storageVersionInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apiserverinternal/v1alpha1/storageversion.go","code":"func (f *storageVersionInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredStorageVersionInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025158,"name":"Informer","signature":"func (f *storageVersionInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apiserverinternal/v1alpha1/storageversion.go","code":"func (f *storageVersionInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026apiserverinternalv1alpha1.StorageVersion{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025159,"name":"Lister","signature":"func (f *storageVersionInformer) Lister() v1alpha1.StorageVersionLister","file":"staging/src/k8s.io/client-go/informers/apiserverinternal/v1alpha1/storageversion.go","code":"func (f *storageVersionInformer) Lister() v1alpha1.StorageVersionLister {\n\treturn v1alpha1.NewStorageVersionLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025160,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/apps/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":44,"to":47}} {"id":100025161,"name":"V1","signature":"func (g *group) V1() v1.Interface","file":"staging/src/k8s.io/client-go/informers/apps/interface.go","code":"// V1 returns a new v1.Interface.\nfunc (g *group) V1() v1.Interface {\n\treturn v1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":49,"to":52}} {"id":100025162,"name":"V1beta1","signature":"func (g *group) V1beta1() v1beta1.Interface","file":"staging/src/k8s.io/client-go/informers/apps/interface.go","code":"// V1beta1 returns a new v1beta1.Interface.\nfunc (g *group) V1beta1() v1beta1.Interface {\n\treturn v1beta1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":54,"to":57}} {"id":100025163,"name":"V1beta2","signature":"func (g *group) V1beta2() v1beta2.Interface","file":"staging/src/k8s.io/client-go/informers/apps/interface.go","code":"// V1beta2 returns a new v1beta2.Interface.\nfunc (g *group) V1beta2() v1beta2.Interface {\n\treturn v1beta2.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":59,"to":62}} {"id":100025164,"name":"NewControllerRevisionInformer","signature":"func NewControllerRevisionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1/controllerrevision.go","code":"// NewControllerRevisionInformer constructs a new informer for ControllerRevision type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewControllerRevisionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredControllerRevisionInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025165,"name":"NewFilteredControllerRevisionInformer","signature":"func NewFilteredControllerRevisionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1/controllerrevision.go","code":"// NewFilteredControllerRevisionInformer constructs a new informer for ControllerRevision type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredControllerRevisionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AppsV1().ControllerRevisions(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AppsV1().ControllerRevisions(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026appsv1.ControllerRevision{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025166,"name":"defaultInformer","signature":"func (f *controllerRevisionInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1/controllerrevision.go","code":"func (f *controllerRevisionInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredControllerRevisionInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025167,"name":"Informer","signature":"func (f *controllerRevisionInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1/controllerrevision.go","code":"func (f *controllerRevisionInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026appsv1.ControllerRevision{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025168,"name":"Lister","signature":"func (f *controllerRevisionInformer) Lister() v1.ControllerRevisionLister","file":"staging/src/k8s.io/client-go/informers/apps/v1/controllerrevision.go","code":"func (f *controllerRevisionInformer) Lister() v1.ControllerRevisionLister {\n\treturn v1.NewControllerRevisionLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025169,"name":"NewDaemonSetInformer","signature":"func NewDaemonSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1/daemonset.go","code":"// NewDaemonSetInformer constructs a new informer for DaemonSet type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewDaemonSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredDaemonSetInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025170,"name":"NewFilteredDaemonSetInformer","signature":"func NewFilteredDaemonSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1/daemonset.go","code":"// NewFilteredDaemonSetInformer constructs a new informer for DaemonSet type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredDaemonSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AppsV1().DaemonSets(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AppsV1().DaemonSets(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026appsv1.DaemonSet{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025171,"name":"defaultInformer","signature":"func (f *daemonSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1/daemonset.go","code":"func (f *daemonSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredDaemonSetInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025172,"name":"Informer","signature":"func (f *daemonSetInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1/daemonset.go","code":"func (f *daemonSetInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026appsv1.DaemonSet{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025173,"name":"Lister","signature":"func (f *daemonSetInformer) Lister() v1.DaemonSetLister","file":"staging/src/k8s.io/client-go/informers/apps/v1/daemonset.go","code":"func (f *daemonSetInformer) Lister() v1.DaemonSetLister {\n\treturn v1.NewDaemonSetLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025174,"name":"NewDeploymentInformer","signature":"func NewDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1/deployment.go","code":"// NewDeploymentInformer constructs a new informer for Deployment type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredDeploymentInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025175,"name":"NewFilteredDeploymentInformer","signature":"func NewFilteredDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1/deployment.go","code":"// NewFilteredDeploymentInformer constructs a new informer for Deployment type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AppsV1().Deployments(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AppsV1().Deployments(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026appsv1.Deployment{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025176,"name":"defaultInformer","signature":"func (f *deploymentInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1/deployment.go","code":"func (f *deploymentInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredDeploymentInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025177,"name":"Informer","signature":"func (f *deploymentInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1/deployment.go","code":"func (f *deploymentInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026appsv1.Deployment{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025178,"name":"Lister","signature":"func (f *deploymentInformer) Lister() v1.DeploymentLister","file":"staging/src/k8s.io/client-go/informers/apps/v1/deployment.go","code":"func (f *deploymentInformer) Lister() v1.DeploymentLister {\n\treturn v1.NewDeploymentLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025179,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/apps/v1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":45,"to":48}} {"id":100025180,"name":"ControllerRevisions","signature":"func (v *version) ControllerRevisions() ControllerRevisionInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1/interface.go","code":"// ControllerRevisions returns a ControllerRevisionInformer.\nfunc (v *version) ControllerRevisions() ControllerRevisionInformer {\n\treturn \u0026controllerRevisionInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":50,"to":53}} {"id":100025181,"name":"DaemonSets","signature":"func (v *version) DaemonSets() DaemonSetInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1/interface.go","code":"// DaemonSets returns a DaemonSetInformer.\nfunc (v *version) DaemonSets() DaemonSetInformer {\n\treturn \u0026daemonSetInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":55,"to":58}} {"id":100025182,"name":"Deployments","signature":"func (v *version) Deployments() DeploymentInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1/interface.go","code":"// Deployments returns a DeploymentInformer.\nfunc (v *version) Deployments() DeploymentInformer {\n\treturn \u0026deploymentInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":60,"to":63}} {"id":100025183,"name":"ReplicaSets","signature":"func (v *version) ReplicaSets() ReplicaSetInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1/interface.go","code":"// ReplicaSets returns a ReplicaSetInformer.\nfunc (v *version) ReplicaSets() ReplicaSetInformer {\n\treturn \u0026replicaSetInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":65,"to":68}} {"id":100025184,"name":"StatefulSets","signature":"func (v *version) StatefulSets() StatefulSetInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1/interface.go","code":"// StatefulSets returns a StatefulSetInformer.\nfunc (v *version) StatefulSets() StatefulSetInformer {\n\treturn \u0026statefulSetInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":70,"to":73}} {"id":100025185,"name":"NewReplicaSetInformer","signature":"func NewReplicaSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1/replicaset.go","code":"// NewReplicaSetInformer constructs a new informer for ReplicaSet type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewReplicaSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredReplicaSetInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025186,"name":"NewFilteredReplicaSetInformer","signature":"func NewFilteredReplicaSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1/replicaset.go","code":"// NewFilteredReplicaSetInformer constructs a new informer for ReplicaSet type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredReplicaSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AppsV1().ReplicaSets(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AppsV1().ReplicaSets(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026appsv1.ReplicaSet{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025187,"name":"defaultInformer","signature":"func (f *replicaSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1/replicaset.go","code":"func (f *replicaSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredReplicaSetInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025188,"name":"Informer","signature":"func (f *replicaSetInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1/replicaset.go","code":"func (f *replicaSetInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026appsv1.ReplicaSet{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025189,"name":"Lister","signature":"func (f *replicaSetInformer) Lister() v1.ReplicaSetLister","file":"staging/src/k8s.io/client-go/informers/apps/v1/replicaset.go","code":"func (f *replicaSetInformer) Lister() v1.ReplicaSetLister {\n\treturn v1.NewReplicaSetLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025190,"name":"NewStatefulSetInformer","signature":"func NewStatefulSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1/statefulset.go","code":"// NewStatefulSetInformer constructs a new informer for StatefulSet type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewStatefulSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredStatefulSetInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025191,"name":"NewFilteredStatefulSetInformer","signature":"func NewFilteredStatefulSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1/statefulset.go","code":"// NewFilteredStatefulSetInformer constructs a new informer for StatefulSet type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredStatefulSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AppsV1().StatefulSets(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AppsV1().StatefulSets(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026appsv1.StatefulSet{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025192,"name":"defaultInformer","signature":"func (f *statefulSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1/statefulset.go","code":"func (f *statefulSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredStatefulSetInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025193,"name":"Informer","signature":"func (f *statefulSetInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1/statefulset.go","code":"func (f *statefulSetInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026appsv1.StatefulSet{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025194,"name":"Lister","signature":"func (f *statefulSetInformer) Lister() v1.StatefulSetLister","file":"staging/src/k8s.io/client-go/informers/apps/v1/statefulset.go","code":"func (f *statefulSetInformer) Lister() v1.StatefulSetLister {\n\treturn v1.NewStatefulSetLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025195,"name":"NewControllerRevisionInformer","signature":"func NewControllerRevisionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta1/controllerrevision.go","code":"// NewControllerRevisionInformer constructs a new informer for ControllerRevision type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewControllerRevisionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredControllerRevisionInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025196,"name":"NewFilteredControllerRevisionInformer","signature":"func NewFilteredControllerRevisionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta1/controllerrevision.go","code":"// NewFilteredControllerRevisionInformer constructs a new informer for ControllerRevision type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredControllerRevisionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AppsV1beta1().ControllerRevisions(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AppsV1beta1().ControllerRevisions(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026appsv1beta1.ControllerRevision{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025197,"name":"defaultInformer","signature":"func (f *controllerRevisionInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta1/controllerrevision.go","code":"func (f *controllerRevisionInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredControllerRevisionInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025198,"name":"Informer","signature":"func (f *controllerRevisionInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta1/controllerrevision.go","code":"func (f *controllerRevisionInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026appsv1beta1.ControllerRevision{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025199,"name":"Lister","signature":"func (f *controllerRevisionInformer) Lister() v1beta1.ControllerRevisionLister","file":"staging/src/k8s.io/client-go/informers/apps/v1beta1/controllerrevision.go","code":"func (f *controllerRevisionInformer) Lister() v1beta1.ControllerRevisionLister {\n\treturn v1beta1.NewControllerRevisionLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025200,"name":"NewDeploymentInformer","signature":"func NewDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta1/deployment.go","code":"// NewDeploymentInformer constructs a new informer for Deployment type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredDeploymentInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025201,"name":"NewFilteredDeploymentInformer","signature":"func NewFilteredDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta1/deployment.go","code":"// NewFilteredDeploymentInformer constructs a new informer for Deployment type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AppsV1beta1().Deployments(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AppsV1beta1().Deployments(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026appsv1beta1.Deployment{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025202,"name":"defaultInformer","signature":"func (f *deploymentInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta1/deployment.go","code":"func (f *deploymentInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredDeploymentInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025203,"name":"Informer","signature":"func (f *deploymentInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta1/deployment.go","code":"func (f *deploymentInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026appsv1beta1.Deployment{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025204,"name":"Lister","signature":"func (f *deploymentInformer) Lister() v1beta1.DeploymentLister","file":"staging/src/k8s.io/client-go/informers/apps/v1beta1/deployment.go","code":"func (f *deploymentInformer) Lister() v1beta1.DeploymentLister {\n\treturn v1beta1.NewDeploymentLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025205,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/apps/v1beta1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":41,"to":44}} {"id":100025206,"name":"ControllerRevisions","signature":"func (v *version) ControllerRevisions() ControllerRevisionInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta1/interface.go","code":"// ControllerRevisions returns a ControllerRevisionInformer.\nfunc (v *version) ControllerRevisions() ControllerRevisionInformer {\n\treturn \u0026controllerRevisionInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":46,"to":49}} {"id":100025207,"name":"Deployments","signature":"func (v *version) Deployments() DeploymentInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta1/interface.go","code":"// Deployments returns a DeploymentInformer.\nfunc (v *version) Deployments() DeploymentInformer {\n\treturn \u0026deploymentInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":51,"to":54}} {"id":100025208,"name":"StatefulSets","signature":"func (v *version) StatefulSets() StatefulSetInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta1/interface.go","code":"// StatefulSets returns a StatefulSetInformer.\nfunc (v *version) StatefulSets() StatefulSetInformer {\n\treturn \u0026statefulSetInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":56,"to":59}} {"id":100025209,"name":"NewStatefulSetInformer","signature":"func NewStatefulSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta1/statefulset.go","code":"// NewStatefulSetInformer constructs a new informer for StatefulSet type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewStatefulSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredStatefulSetInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025210,"name":"NewFilteredStatefulSetInformer","signature":"func NewFilteredStatefulSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta1/statefulset.go","code":"// NewFilteredStatefulSetInformer constructs a new informer for StatefulSet type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredStatefulSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AppsV1beta1().StatefulSets(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AppsV1beta1().StatefulSets(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026appsv1beta1.StatefulSet{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025211,"name":"defaultInformer","signature":"func (f *statefulSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta1/statefulset.go","code":"func (f *statefulSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredStatefulSetInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025212,"name":"Informer","signature":"func (f *statefulSetInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta1/statefulset.go","code":"func (f *statefulSetInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026appsv1beta1.StatefulSet{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025213,"name":"Lister","signature":"func (f *statefulSetInformer) Lister() v1beta1.StatefulSetLister","file":"staging/src/k8s.io/client-go/informers/apps/v1beta1/statefulset.go","code":"func (f *statefulSetInformer) Lister() v1beta1.StatefulSetLister {\n\treturn v1beta1.NewStatefulSetLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025214,"name":"NewControllerRevisionInformer","signature":"func NewControllerRevisionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/controllerrevision.go","code":"// NewControllerRevisionInformer constructs a new informer for ControllerRevision type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewControllerRevisionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredControllerRevisionInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025215,"name":"NewFilteredControllerRevisionInformer","signature":"func NewFilteredControllerRevisionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/controllerrevision.go","code":"// NewFilteredControllerRevisionInformer constructs a new informer for ControllerRevision type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredControllerRevisionInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AppsV1beta2().ControllerRevisions(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AppsV1beta2().ControllerRevisions(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026appsv1beta2.ControllerRevision{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025216,"name":"defaultInformer","signature":"func (f *controllerRevisionInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/controllerrevision.go","code":"func (f *controllerRevisionInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredControllerRevisionInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025217,"name":"Informer","signature":"func (f *controllerRevisionInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/controllerrevision.go","code":"func (f *controllerRevisionInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026appsv1beta2.ControllerRevision{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025218,"name":"Lister","signature":"func (f *controllerRevisionInformer) Lister() v1beta2.ControllerRevisionLister","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/controllerrevision.go","code":"func (f *controllerRevisionInformer) Lister() v1beta2.ControllerRevisionLister {\n\treturn v1beta2.NewControllerRevisionLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025219,"name":"NewDaemonSetInformer","signature":"func NewDaemonSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/daemonset.go","code":"// NewDaemonSetInformer constructs a new informer for DaemonSet type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewDaemonSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredDaemonSetInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025220,"name":"NewFilteredDaemonSetInformer","signature":"func NewFilteredDaemonSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/daemonset.go","code":"// NewFilteredDaemonSetInformer constructs a new informer for DaemonSet type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredDaemonSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AppsV1beta2().DaemonSets(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AppsV1beta2().DaemonSets(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026appsv1beta2.DaemonSet{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025221,"name":"defaultInformer","signature":"func (f *daemonSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/daemonset.go","code":"func (f *daemonSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredDaemonSetInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025222,"name":"Informer","signature":"func (f *daemonSetInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/daemonset.go","code":"func (f *daemonSetInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026appsv1beta2.DaemonSet{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025223,"name":"Lister","signature":"func (f *daemonSetInformer) Lister() v1beta2.DaemonSetLister","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/daemonset.go","code":"func (f *daemonSetInformer) Lister() v1beta2.DaemonSetLister {\n\treturn v1beta2.NewDaemonSetLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025224,"name":"NewDeploymentInformer","signature":"func NewDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/deployment.go","code":"// NewDeploymentInformer constructs a new informer for Deployment type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredDeploymentInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025225,"name":"NewFilteredDeploymentInformer","signature":"func NewFilteredDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/deployment.go","code":"// NewFilteredDeploymentInformer constructs a new informer for Deployment type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AppsV1beta2().Deployments(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AppsV1beta2().Deployments(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026appsv1beta2.Deployment{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025226,"name":"defaultInformer","signature":"func (f *deploymentInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/deployment.go","code":"func (f *deploymentInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredDeploymentInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025227,"name":"Informer","signature":"func (f *deploymentInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/deployment.go","code":"func (f *deploymentInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026appsv1beta2.Deployment{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025228,"name":"Lister","signature":"func (f *deploymentInformer) Lister() v1beta2.DeploymentLister","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/deployment.go","code":"func (f *deploymentInformer) Lister() v1beta2.DeploymentLister {\n\treturn v1beta2.NewDeploymentLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025229,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":45,"to":48}} {"id":100025230,"name":"ControllerRevisions","signature":"func (v *version) ControllerRevisions() ControllerRevisionInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/interface.go","code":"// ControllerRevisions returns a ControllerRevisionInformer.\nfunc (v *version) ControllerRevisions() ControllerRevisionInformer {\n\treturn \u0026controllerRevisionInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":50,"to":53}} {"id":100025231,"name":"DaemonSets","signature":"func (v *version) DaemonSets() DaemonSetInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/interface.go","code":"// DaemonSets returns a DaemonSetInformer.\nfunc (v *version) DaemonSets() DaemonSetInformer {\n\treturn \u0026daemonSetInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":55,"to":58}} {"id":100025232,"name":"Deployments","signature":"func (v *version) Deployments() DeploymentInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/interface.go","code":"// Deployments returns a DeploymentInformer.\nfunc (v *version) Deployments() DeploymentInformer {\n\treturn \u0026deploymentInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":60,"to":63}} {"id":100025233,"name":"ReplicaSets","signature":"func (v *version) ReplicaSets() ReplicaSetInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/interface.go","code":"// ReplicaSets returns a ReplicaSetInformer.\nfunc (v *version) ReplicaSets() ReplicaSetInformer {\n\treturn \u0026replicaSetInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":65,"to":68}} {"id":100025234,"name":"StatefulSets","signature":"func (v *version) StatefulSets() StatefulSetInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/interface.go","code":"// StatefulSets returns a StatefulSetInformer.\nfunc (v *version) StatefulSets() StatefulSetInformer {\n\treturn \u0026statefulSetInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":70,"to":73}} {"id":100025235,"name":"NewReplicaSetInformer","signature":"func NewReplicaSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/replicaset.go","code":"// NewReplicaSetInformer constructs a new informer for ReplicaSet type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewReplicaSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredReplicaSetInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025236,"name":"NewFilteredReplicaSetInformer","signature":"func NewFilteredReplicaSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/replicaset.go","code":"// NewFilteredReplicaSetInformer constructs a new informer for ReplicaSet type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredReplicaSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AppsV1beta2().ReplicaSets(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AppsV1beta2().ReplicaSets(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026appsv1beta2.ReplicaSet{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025237,"name":"defaultInformer","signature":"func (f *replicaSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/replicaset.go","code":"func (f *replicaSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredReplicaSetInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025238,"name":"Informer","signature":"func (f *replicaSetInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/replicaset.go","code":"func (f *replicaSetInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026appsv1beta2.ReplicaSet{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025239,"name":"Lister","signature":"func (f *replicaSetInformer) Lister() v1beta2.ReplicaSetLister","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/replicaset.go","code":"func (f *replicaSetInformer) Lister() v1beta2.ReplicaSetLister {\n\treturn v1beta2.NewReplicaSetLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025240,"name":"NewStatefulSetInformer","signature":"func NewStatefulSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/statefulset.go","code":"// NewStatefulSetInformer constructs a new informer for StatefulSet type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewStatefulSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredStatefulSetInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025241,"name":"NewFilteredStatefulSetInformer","signature":"func NewFilteredStatefulSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/statefulset.go","code":"// NewFilteredStatefulSetInformer constructs a new informer for StatefulSet type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredStatefulSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AppsV1beta2().StatefulSets(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AppsV1beta2().StatefulSets(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026appsv1beta2.StatefulSet{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025242,"name":"defaultInformer","signature":"func (f *statefulSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/statefulset.go","code":"func (f *statefulSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredStatefulSetInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025243,"name":"Informer","signature":"func (f *statefulSetInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/statefulset.go","code":"func (f *statefulSetInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026appsv1beta2.StatefulSet{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025244,"name":"Lister","signature":"func (f *statefulSetInformer) Lister() v1beta2.StatefulSetLister","file":"staging/src/k8s.io/client-go/informers/apps/v1beta2/statefulset.go","code":"func (f *statefulSetInformer) Lister() v1beta2.StatefulSetLister {\n\treturn v1beta2.NewStatefulSetLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025245,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/autoscaling/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":47,"to":50}} {"id":100025246,"name":"V1","signature":"func (g *group) V1() v1.Interface","file":"staging/src/k8s.io/client-go/informers/autoscaling/interface.go","code":"// V1 returns a new v1.Interface.\nfunc (g *group) V1() v1.Interface {\n\treturn v1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":52,"to":55}} {"id":100025247,"name":"V2","signature":"func (g *group) V2() v2.Interface","file":"staging/src/k8s.io/client-go/informers/autoscaling/interface.go","code":"// V2 returns a new v2.Interface.\nfunc (g *group) V2() v2.Interface {\n\treturn v2.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":57,"to":60}} {"id":100025248,"name":"V2beta1","signature":"func (g *group) V2beta1() v2beta1.Interface","file":"staging/src/k8s.io/client-go/informers/autoscaling/interface.go","code":"// V2beta1 returns a new v2beta1.Interface.\nfunc (g *group) V2beta1() v2beta1.Interface {\n\treturn v2beta1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":62,"to":65}} {"id":100025249,"name":"V2beta2","signature":"func (g *group) V2beta2() v2beta2.Interface","file":"staging/src/k8s.io/client-go/informers/autoscaling/interface.go","code":"// V2beta2 returns a new v2beta2.Interface.\nfunc (g *group) V2beta2() v2beta2.Interface {\n\treturn v2beta2.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":67,"to":70}} {"id":100025250,"name":"NewHorizontalPodAutoscalerInformer","signature":"func NewHorizontalPodAutoscalerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/autoscaling/v1/horizontalpodautoscaler.go","code":"// NewHorizontalPodAutoscalerInformer constructs a new informer for HorizontalPodAutoscaler type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewHorizontalPodAutoscalerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredHorizontalPodAutoscalerInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025251,"name":"NewFilteredHorizontalPodAutoscalerInformer","signature":"func NewFilteredHorizontalPodAutoscalerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/autoscaling/v1/horizontalpodautoscaler.go","code":"// NewFilteredHorizontalPodAutoscalerInformer constructs a new informer for HorizontalPodAutoscaler type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredHorizontalPodAutoscalerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AutoscalingV1().HorizontalPodAutoscalers(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AutoscalingV1().HorizontalPodAutoscalers(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026autoscalingv1.HorizontalPodAutoscaler{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025252,"name":"defaultInformer","signature":"func (f *horizontalPodAutoscalerInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/autoscaling/v1/horizontalpodautoscaler.go","code":"func (f *horizontalPodAutoscalerInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredHorizontalPodAutoscalerInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025253,"name":"Informer","signature":"func (f *horizontalPodAutoscalerInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/autoscaling/v1/horizontalpodautoscaler.go","code":"func (f *horizontalPodAutoscalerInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026autoscalingv1.HorizontalPodAutoscaler{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025254,"name":"Lister","signature":"func (f *horizontalPodAutoscalerInformer) Lister() v1.HorizontalPodAutoscalerLister","file":"staging/src/k8s.io/client-go/informers/autoscaling/v1/horizontalpodautoscaler.go","code":"func (f *horizontalPodAutoscalerInformer) Lister() v1.HorizontalPodAutoscalerLister {\n\treturn v1.NewHorizontalPodAutoscalerLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025255,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/autoscaling/v1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":37,"to":40}} {"id":100025256,"name":"HorizontalPodAutoscalers","signature":"func (v *version) HorizontalPodAutoscalers() HorizontalPodAutoscalerInformer","file":"staging/src/k8s.io/client-go/informers/autoscaling/v1/interface.go","code":"// HorizontalPodAutoscalers returns a HorizontalPodAutoscalerInformer.\nfunc (v *version) HorizontalPodAutoscalers() HorizontalPodAutoscalerInformer {\n\treturn \u0026horizontalPodAutoscalerInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":42,"to":45}} {"id":100025257,"name":"NewHorizontalPodAutoscalerInformer","signature":"func NewHorizontalPodAutoscalerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/autoscaling/v2/horizontalpodautoscaler.go","code":"// NewHorizontalPodAutoscalerInformer constructs a new informer for HorizontalPodAutoscaler type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewHorizontalPodAutoscalerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredHorizontalPodAutoscalerInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025258,"name":"NewFilteredHorizontalPodAutoscalerInformer","signature":"func NewFilteredHorizontalPodAutoscalerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/autoscaling/v2/horizontalpodautoscaler.go","code":"// NewFilteredHorizontalPodAutoscalerInformer constructs a new informer for HorizontalPodAutoscaler type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredHorizontalPodAutoscalerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AutoscalingV2().HorizontalPodAutoscalers(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AutoscalingV2().HorizontalPodAutoscalers(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026autoscalingv2.HorizontalPodAutoscaler{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025259,"name":"defaultInformer","signature":"func (f *horizontalPodAutoscalerInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/autoscaling/v2/horizontalpodautoscaler.go","code":"func (f *horizontalPodAutoscalerInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredHorizontalPodAutoscalerInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025260,"name":"Informer","signature":"func (f *horizontalPodAutoscalerInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/autoscaling/v2/horizontalpodautoscaler.go","code":"func (f *horizontalPodAutoscalerInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026autoscalingv2.HorizontalPodAutoscaler{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025261,"name":"Lister","signature":"func (f *horizontalPodAutoscalerInformer) Lister() v2.HorizontalPodAutoscalerLister","file":"staging/src/k8s.io/client-go/informers/autoscaling/v2/horizontalpodautoscaler.go","code":"func (f *horizontalPodAutoscalerInformer) Lister() v2.HorizontalPodAutoscalerLister {\n\treturn v2.NewHorizontalPodAutoscalerLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025262,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/autoscaling/v2/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":37,"to":40}} {"id":100025263,"name":"HorizontalPodAutoscalers","signature":"func (v *version) HorizontalPodAutoscalers() HorizontalPodAutoscalerInformer","file":"staging/src/k8s.io/client-go/informers/autoscaling/v2/interface.go","code":"// HorizontalPodAutoscalers returns a HorizontalPodAutoscalerInformer.\nfunc (v *version) HorizontalPodAutoscalers() HorizontalPodAutoscalerInformer {\n\treturn \u0026horizontalPodAutoscalerInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":42,"to":45}} {"id":100025264,"name":"NewHorizontalPodAutoscalerInformer","signature":"func NewHorizontalPodAutoscalerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// NewHorizontalPodAutoscalerInformer constructs a new informer for HorizontalPodAutoscaler type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewHorizontalPodAutoscalerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredHorizontalPodAutoscalerInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025265,"name":"NewFilteredHorizontalPodAutoscalerInformer","signature":"func NewFilteredHorizontalPodAutoscalerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// NewFilteredHorizontalPodAutoscalerInformer constructs a new informer for HorizontalPodAutoscaler type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredHorizontalPodAutoscalerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AutoscalingV2beta1().HorizontalPodAutoscalers(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AutoscalingV2beta1().HorizontalPodAutoscalers(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026autoscalingv2beta1.HorizontalPodAutoscaler{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025266,"name":"defaultInformer","signature":"func (f *horizontalPodAutoscalerInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"func (f *horizontalPodAutoscalerInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredHorizontalPodAutoscalerInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025267,"name":"Informer","signature":"func (f *horizontalPodAutoscalerInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"func (f *horizontalPodAutoscalerInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026autoscalingv2beta1.HorizontalPodAutoscaler{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025268,"name":"Lister","signature":"func (f *horizontalPodAutoscalerInformer) Lister() v2beta1.HorizontalPodAutoscalerLister","file":"staging/src/k8s.io/client-go/informers/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"func (f *horizontalPodAutoscalerInformer) Lister() v2beta1.HorizontalPodAutoscalerLister {\n\treturn v2beta1.NewHorizontalPodAutoscalerLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025269,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/autoscaling/v2beta1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":37,"to":40}} {"id":100025270,"name":"HorizontalPodAutoscalers","signature":"func (v *version) HorizontalPodAutoscalers() HorizontalPodAutoscalerInformer","file":"staging/src/k8s.io/client-go/informers/autoscaling/v2beta1/interface.go","code":"// HorizontalPodAutoscalers returns a HorizontalPodAutoscalerInformer.\nfunc (v *version) HorizontalPodAutoscalers() HorizontalPodAutoscalerInformer {\n\treturn \u0026horizontalPodAutoscalerInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":42,"to":45}} {"id":100025271,"name":"NewHorizontalPodAutoscalerInformer","signature":"func NewHorizontalPodAutoscalerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// NewHorizontalPodAutoscalerInformer constructs a new informer for HorizontalPodAutoscaler type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewHorizontalPodAutoscalerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredHorizontalPodAutoscalerInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025272,"name":"NewFilteredHorizontalPodAutoscalerInformer","signature":"func NewFilteredHorizontalPodAutoscalerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// NewFilteredHorizontalPodAutoscalerInformer constructs a new informer for HorizontalPodAutoscaler type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredHorizontalPodAutoscalerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AutoscalingV2beta2().HorizontalPodAutoscalers(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.AutoscalingV2beta2().HorizontalPodAutoscalers(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026autoscalingv2beta2.HorizontalPodAutoscaler{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025273,"name":"defaultInformer","signature":"func (f *horizontalPodAutoscalerInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"func (f *horizontalPodAutoscalerInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredHorizontalPodAutoscalerInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025274,"name":"Informer","signature":"func (f *horizontalPodAutoscalerInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"func (f *horizontalPodAutoscalerInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026autoscalingv2beta2.HorizontalPodAutoscaler{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025275,"name":"Lister","signature":"func (f *horizontalPodAutoscalerInformer) Lister() v2beta2.HorizontalPodAutoscalerLister","file":"staging/src/k8s.io/client-go/informers/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"func (f *horizontalPodAutoscalerInformer) Lister() v2beta2.HorizontalPodAutoscalerLister {\n\treturn v2beta2.NewHorizontalPodAutoscalerLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025276,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/autoscaling/v2beta2/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":37,"to":40}} {"id":100025277,"name":"HorizontalPodAutoscalers","signature":"func (v *version) HorizontalPodAutoscalers() HorizontalPodAutoscalerInformer","file":"staging/src/k8s.io/client-go/informers/autoscaling/v2beta2/interface.go","code":"// HorizontalPodAutoscalers returns a HorizontalPodAutoscalerInformer.\nfunc (v *version) HorizontalPodAutoscalers() HorizontalPodAutoscalerInformer {\n\treturn \u0026horizontalPodAutoscalerInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":42,"to":45}} {"id":100025278,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/batch/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":41,"to":44}} {"id":100025279,"name":"V1","signature":"func (g *group) V1() v1.Interface","file":"staging/src/k8s.io/client-go/informers/batch/interface.go","code":"// V1 returns a new v1.Interface.\nfunc (g *group) V1() v1.Interface {\n\treturn v1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":46,"to":49}} {"id":100025280,"name":"V1beta1","signature":"func (g *group) V1beta1() v1beta1.Interface","file":"staging/src/k8s.io/client-go/informers/batch/interface.go","code":"// V1beta1 returns a new v1beta1.Interface.\nfunc (g *group) V1beta1() v1beta1.Interface {\n\treturn v1beta1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":51,"to":54}} {"id":100025281,"name":"NewCronJobInformer","signature":"func NewCronJobInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/batch/v1/cronjob.go","code":"// NewCronJobInformer constructs a new informer for CronJob type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewCronJobInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredCronJobInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025282,"name":"NewFilteredCronJobInformer","signature":"func NewFilteredCronJobInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/batch/v1/cronjob.go","code":"// NewFilteredCronJobInformer constructs a new informer for CronJob type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredCronJobInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.BatchV1().CronJobs(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.BatchV1().CronJobs(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026batchv1.CronJob{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025283,"name":"defaultInformer","signature":"func (f *cronJobInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/batch/v1/cronjob.go","code":"func (f *cronJobInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredCronJobInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025284,"name":"Informer","signature":"func (f *cronJobInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/batch/v1/cronjob.go","code":"func (f *cronJobInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026batchv1.CronJob{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025285,"name":"Lister","signature":"func (f *cronJobInformer) Lister() v1.CronJobLister","file":"staging/src/k8s.io/client-go/informers/batch/v1/cronjob.go","code":"func (f *cronJobInformer) Lister() v1.CronJobLister {\n\treturn v1.NewCronJobLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025286,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/batch/v1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":39,"to":42}} {"id":100025287,"name":"CronJobs","signature":"func (v *version) CronJobs() CronJobInformer","file":"staging/src/k8s.io/client-go/informers/batch/v1/interface.go","code":"// CronJobs returns a CronJobInformer.\nfunc (v *version) CronJobs() CronJobInformer {\n\treturn \u0026cronJobInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":44,"to":47}} {"id":100025288,"name":"Jobs","signature":"func (v *version) Jobs() JobInformer","file":"staging/src/k8s.io/client-go/informers/batch/v1/interface.go","code":"// Jobs returns a JobInformer.\nfunc (v *version) Jobs() JobInformer {\n\treturn \u0026jobInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":49,"to":52}} {"id":100025289,"name":"NewJobInformer","signature":"func NewJobInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/batch/v1/job.go","code":"// NewJobInformer constructs a new informer for Job type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewJobInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredJobInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025290,"name":"NewFilteredJobInformer","signature":"func NewFilteredJobInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/batch/v1/job.go","code":"// NewFilteredJobInformer constructs a new informer for Job type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredJobInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.BatchV1().Jobs(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.BatchV1().Jobs(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026batchv1.Job{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025291,"name":"defaultInformer","signature":"func (f *jobInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/batch/v1/job.go","code":"func (f *jobInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredJobInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025292,"name":"Informer","signature":"func (f *jobInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/batch/v1/job.go","code":"func (f *jobInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026batchv1.Job{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025293,"name":"Lister","signature":"func (f *jobInformer) Lister() v1.JobLister","file":"staging/src/k8s.io/client-go/informers/batch/v1/job.go","code":"func (f *jobInformer) Lister() v1.JobLister {\n\treturn v1.NewJobLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025294,"name":"NewCronJobInformer","signature":"func NewCronJobInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/batch/v1beta1/cronjob.go","code":"// NewCronJobInformer constructs a new informer for CronJob type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewCronJobInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredCronJobInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025295,"name":"NewFilteredCronJobInformer","signature":"func NewFilteredCronJobInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/batch/v1beta1/cronjob.go","code":"// NewFilteredCronJobInformer constructs a new informer for CronJob type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredCronJobInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.BatchV1beta1().CronJobs(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.BatchV1beta1().CronJobs(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026batchv1beta1.CronJob{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025296,"name":"defaultInformer","signature":"func (f *cronJobInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/batch/v1beta1/cronjob.go","code":"func (f *cronJobInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredCronJobInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025297,"name":"Informer","signature":"func (f *cronJobInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/batch/v1beta1/cronjob.go","code":"func (f *cronJobInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026batchv1beta1.CronJob{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025298,"name":"Lister","signature":"func (f *cronJobInformer) Lister() v1beta1.CronJobLister","file":"staging/src/k8s.io/client-go/informers/batch/v1beta1/cronjob.go","code":"func (f *cronJobInformer) Lister() v1beta1.CronJobLister {\n\treturn v1beta1.NewCronJobLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025299,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/batch/v1beta1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":37,"to":40}} {"id":100025300,"name":"CronJobs","signature":"func (v *version) CronJobs() CronJobInformer","file":"staging/src/k8s.io/client-go/informers/batch/v1beta1/interface.go","code":"// CronJobs returns a CronJobInformer.\nfunc (v *version) CronJobs() CronJobInformer {\n\treturn \u0026cronJobInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":42,"to":45}} {"id":100025301,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/certificates/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":44,"to":47}} {"id":100025302,"name":"V1","signature":"func (g *group) V1() v1.Interface","file":"staging/src/k8s.io/client-go/informers/certificates/interface.go","code":"// V1 returns a new v1.Interface.\nfunc (g *group) V1() v1.Interface {\n\treturn v1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":49,"to":52}} {"id":100025303,"name":"V1alpha1","signature":"func (g *group) V1alpha1() v1alpha1.Interface","file":"staging/src/k8s.io/client-go/informers/certificates/interface.go","code":"// V1alpha1 returns a new v1alpha1.Interface.\nfunc (g *group) V1alpha1() v1alpha1.Interface {\n\treturn v1alpha1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":54,"to":57}} {"id":100025304,"name":"V1beta1","signature":"func (g *group) V1beta1() v1beta1.Interface","file":"staging/src/k8s.io/client-go/informers/certificates/interface.go","code":"// V1beta1 returns a new v1beta1.Interface.\nfunc (g *group) V1beta1() v1beta1.Interface {\n\treturn v1beta1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":59,"to":62}} {"id":100025305,"name":"NewCertificateSigningRequestInformer","signature":"func NewCertificateSigningRequestInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/certificates/v1/certificatesigningrequest.go","code":"// NewCertificateSigningRequestInformer constructs a new informer for CertificateSigningRequest type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewCertificateSigningRequestInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredCertificateSigningRequestInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025306,"name":"NewFilteredCertificateSigningRequestInformer","signature":"func NewFilteredCertificateSigningRequestInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/certificates/v1/certificatesigningrequest.go","code":"// NewFilteredCertificateSigningRequestInformer constructs a new informer for CertificateSigningRequest type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredCertificateSigningRequestInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CertificatesV1().CertificateSigningRequests().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CertificatesV1().CertificateSigningRequests().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026certificatesv1.CertificateSigningRequest{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025307,"name":"defaultInformer","signature":"func (f *certificateSigningRequestInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/certificates/v1/certificatesigningrequest.go","code":"func (f *certificateSigningRequestInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredCertificateSigningRequestInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025308,"name":"Informer","signature":"func (f *certificateSigningRequestInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/certificates/v1/certificatesigningrequest.go","code":"func (f *certificateSigningRequestInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026certificatesv1.CertificateSigningRequest{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025309,"name":"Lister","signature":"func (f *certificateSigningRequestInformer) Lister() v1.CertificateSigningRequestLister","file":"staging/src/k8s.io/client-go/informers/certificates/v1/certificatesigningrequest.go","code":"func (f *certificateSigningRequestInformer) Lister() v1.CertificateSigningRequestLister {\n\treturn v1.NewCertificateSigningRequestLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025310,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/certificates/v1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":37,"to":40}} {"id":100025311,"name":"CertificateSigningRequests","signature":"func (v *version) CertificateSigningRequests() CertificateSigningRequestInformer","file":"staging/src/k8s.io/client-go/informers/certificates/v1/interface.go","code":"// CertificateSigningRequests returns a CertificateSigningRequestInformer.\nfunc (v *version) CertificateSigningRequests() CertificateSigningRequestInformer {\n\treturn \u0026certificateSigningRequestInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":42,"to":45}} {"id":100025312,"name":"NewClusterTrustBundleInformer","signature":"func NewClusterTrustBundleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/certificates/v1alpha1/clustertrustbundle.go","code":"// NewClusterTrustBundleInformer constructs a new informer for ClusterTrustBundle type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewClusterTrustBundleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredClusterTrustBundleInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025313,"name":"NewFilteredClusterTrustBundleInformer","signature":"func NewFilteredClusterTrustBundleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/certificates/v1alpha1/clustertrustbundle.go","code":"// NewFilteredClusterTrustBundleInformer constructs a new informer for ClusterTrustBundle type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredClusterTrustBundleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CertificatesV1alpha1().ClusterTrustBundles().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CertificatesV1alpha1().ClusterTrustBundles().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026certificatesv1alpha1.ClusterTrustBundle{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025314,"name":"defaultInformer","signature":"func (f *clusterTrustBundleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/certificates/v1alpha1/clustertrustbundle.go","code":"func (f *clusterTrustBundleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredClusterTrustBundleInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025315,"name":"Informer","signature":"func (f *clusterTrustBundleInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/certificates/v1alpha1/clustertrustbundle.go","code":"func (f *clusterTrustBundleInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026certificatesv1alpha1.ClusterTrustBundle{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025316,"name":"Lister","signature":"func (f *clusterTrustBundleInformer) Lister() v1alpha1.ClusterTrustBundleLister","file":"staging/src/k8s.io/client-go/informers/certificates/v1alpha1/clustertrustbundle.go","code":"func (f *clusterTrustBundleInformer) Lister() v1alpha1.ClusterTrustBundleLister {\n\treturn v1alpha1.NewClusterTrustBundleLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025317,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/certificates/v1alpha1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":37,"to":40}} {"id":100025318,"name":"ClusterTrustBundles","signature":"func (v *version) ClusterTrustBundles() ClusterTrustBundleInformer","file":"staging/src/k8s.io/client-go/informers/certificates/v1alpha1/interface.go","code":"// ClusterTrustBundles returns a ClusterTrustBundleInformer.\nfunc (v *version) ClusterTrustBundles() ClusterTrustBundleInformer {\n\treturn \u0026clusterTrustBundleInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":42,"to":45}} {"id":100025319,"name":"NewCertificateSigningRequestInformer","signature":"func NewCertificateSigningRequestInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/certificates/v1beta1/certificatesigningrequest.go","code":"// NewCertificateSigningRequestInformer constructs a new informer for CertificateSigningRequest type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewCertificateSigningRequestInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredCertificateSigningRequestInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025320,"name":"NewFilteredCertificateSigningRequestInformer","signature":"func NewFilteredCertificateSigningRequestInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/certificates/v1beta1/certificatesigningrequest.go","code":"// NewFilteredCertificateSigningRequestInformer constructs a new informer for CertificateSigningRequest type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredCertificateSigningRequestInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CertificatesV1beta1().CertificateSigningRequests().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CertificatesV1beta1().CertificateSigningRequests().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026certificatesv1beta1.CertificateSigningRequest{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025321,"name":"defaultInformer","signature":"func (f *certificateSigningRequestInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/certificates/v1beta1/certificatesigningrequest.go","code":"func (f *certificateSigningRequestInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredCertificateSigningRequestInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025322,"name":"Informer","signature":"func (f *certificateSigningRequestInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/certificates/v1beta1/certificatesigningrequest.go","code":"func (f *certificateSigningRequestInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026certificatesv1beta1.CertificateSigningRequest{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025323,"name":"Lister","signature":"func (f *certificateSigningRequestInformer) Lister() v1beta1.CertificateSigningRequestLister","file":"staging/src/k8s.io/client-go/informers/certificates/v1beta1/certificatesigningrequest.go","code":"func (f *certificateSigningRequestInformer) Lister() v1beta1.CertificateSigningRequestLister {\n\treturn v1beta1.NewCertificateSigningRequestLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025324,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/certificates/v1beta1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":37,"to":40}} {"id":100025325,"name":"CertificateSigningRequests","signature":"func (v *version) CertificateSigningRequests() CertificateSigningRequestInformer","file":"staging/src/k8s.io/client-go/informers/certificates/v1beta1/interface.go","code":"// CertificateSigningRequests returns a CertificateSigningRequestInformer.\nfunc (v *version) CertificateSigningRequests() CertificateSigningRequestInformer {\n\treturn \u0026certificateSigningRequestInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":42,"to":45}} {"id":100025326,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/coordination/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":41,"to":44}} {"id":100025327,"name":"V1","signature":"func (g *group) V1() v1.Interface","file":"staging/src/k8s.io/client-go/informers/coordination/interface.go","code":"// V1 returns a new v1.Interface.\nfunc (g *group) V1() v1.Interface {\n\treturn v1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":46,"to":49}} {"id":100025328,"name":"V1beta1","signature":"func (g *group) V1beta1() v1beta1.Interface","file":"staging/src/k8s.io/client-go/informers/coordination/interface.go","code":"// V1beta1 returns a new v1beta1.Interface.\nfunc (g *group) V1beta1() v1beta1.Interface {\n\treturn v1beta1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":51,"to":54}} {"id":100025329,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/coordination/v1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":37,"to":40}} {"id":100025330,"name":"Leases","signature":"func (v *version) Leases() LeaseInformer","file":"staging/src/k8s.io/client-go/informers/coordination/v1/interface.go","code":"// Leases returns a LeaseInformer.\nfunc (v *version) Leases() LeaseInformer {\n\treturn \u0026leaseInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":42,"to":45}} {"id":100025331,"name":"NewLeaseInformer","signature":"func NewLeaseInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/coordination/v1/lease.go","code":"// NewLeaseInformer constructs a new informer for Lease type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewLeaseInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredLeaseInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025332,"name":"NewFilteredLeaseInformer","signature":"func NewFilteredLeaseInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/coordination/v1/lease.go","code":"// NewFilteredLeaseInformer constructs a new informer for Lease type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredLeaseInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoordinationV1().Leases(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoordinationV1().Leases(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026coordinationv1.Lease{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025333,"name":"defaultInformer","signature":"func (f *leaseInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/coordination/v1/lease.go","code":"func (f *leaseInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredLeaseInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025334,"name":"Informer","signature":"func (f *leaseInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/coordination/v1/lease.go","code":"func (f *leaseInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026coordinationv1.Lease{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025335,"name":"Lister","signature":"func (f *leaseInformer) Lister() v1.LeaseLister","file":"staging/src/k8s.io/client-go/informers/coordination/v1/lease.go","code":"func (f *leaseInformer) Lister() v1.LeaseLister {\n\treturn v1.NewLeaseLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025336,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/coordination/v1beta1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":37,"to":40}} {"id":100025337,"name":"Leases","signature":"func (v *version) Leases() LeaseInformer","file":"staging/src/k8s.io/client-go/informers/coordination/v1beta1/interface.go","code":"// Leases returns a LeaseInformer.\nfunc (v *version) Leases() LeaseInformer {\n\treturn \u0026leaseInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":42,"to":45}} {"id":100025338,"name":"NewLeaseInformer","signature":"func NewLeaseInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/coordination/v1beta1/lease.go","code":"// NewLeaseInformer constructs a new informer for Lease type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewLeaseInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredLeaseInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025339,"name":"NewFilteredLeaseInformer","signature":"func NewFilteredLeaseInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/coordination/v1beta1/lease.go","code":"// NewFilteredLeaseInformer constructs a new informer for Lease type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredLeaseInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoordinationV1beta1().Leases(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoordinationV1beta1().Leases(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026coordinationv1beta1.Lease{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025340,"name":"defaultInformer","signature":"func (f *leaseInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/coordination/v1beta1/lease.go","code":"func (f *leaseInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredLeaseInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025341,"name":"Informer","signature":"func (f *leaseInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/coordination/v1beta1/lease.go","code":"func (f *leaseInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026coordinationv1beta1.Lease{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025342,"name":"Lister","signature":"func (f *leaseInformer) Lister() v1beta1.LeaseLister","file":"staging/src/k8s.io/client-go/informers/coordination/v1beta1/lease.go","code":"func (f *leaseInformer) Lister() v1beta1.LeaseLister {\n\treturn v1beta1.NewLeaseLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025343,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/core/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":38,"to":41}} {"id":100025344,"name":"V1","signature":"func (g *group) V1() v1.Interface","file":"staging/src/k8s.io/client-go/informers/core/interface.go","code":"// V1 returns a new v1.Interface.\nfunc (g *group) V1() v1.Interface {\n\treturn v1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":43,"to":46}} {"id":100025345,"name":"NewComponentStatusInformer","signature":"func NewComponentStatusInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/componentstatus.go","code":"// NewComponentStatusInformer constructs a new informer for ComponentStatus type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewComponentStatusInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredComponentStatusInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025346,"name":"NewFilteredComponentStatusInformer","signature":"func NewFilteredComponentStatusInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/componentstatus.go","code":"// NewFilteredComponentStatusInformer constructs a new informer for ComponentStatus type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredComponentStatusInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().ComponentStatuses().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().ComponentStatuses().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026corev1.ComponentStatus{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025347,"name":"defaultInformer","signature":"func (f *componentStatusInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/componentstatus.go","code":"func (f *componentStatusInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredComponentStatusInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025348,"name":"Informer","signature":"func (f *componentStatusInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/componentstatus.go","code":"func (f *componentStatusInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026corev1.ComponentStatus{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025349,"name":"Lister","signature":"func (f *componentStatusInformer) Lister() v1.ComponentStatusLister","file":"staging/src/k8s.io/client-go/informers/core/v1/componentstatus.go","code":"func (f *componentStatusInformer) Lister() v1.ComponentStatusLister {\n\treturn v1.NewComponentStatusLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025350,"name":"NewConfigMapInformer","signature":"func NewConfigMapInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/configmap.go","code":"// NewConfigMapInformer constructs a new informer for ConfigMap type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewConfigMapInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredConfigMapInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025351,"name":"NewFilteredConfigMapInformer","signature":"func NewFilteredConfigMapInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/configmap.go","code":"// NewFilteredConfigMapInformer constructs a new informer for ConfigMap type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredConfigMapInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().ConfigMaps(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().ConfigMaps(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026corev1.ConfigMap{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025352,"name":"defaultInformer","signature":"func (f *configMapInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/configmap.go","code":"func (f *configMapInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredConfigMapInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025353,"name":"Informer","signature":"func (f *configMapInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/configmap.go","code":"func (f *configMapInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026corev1.ConfigMap{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025354,"name":"Lister","signature":"func (f *configMapInformer) Lister() v1.ConfigMapLister","file":"staging/src/k8s.io/client-go/informers/core/v1/configmap.go","code":"func (f *configMapInformer) Lister() v1.ConfigMapLister {\n\treturn v1.NewConfigMapLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025355,"name":"NewEndpointsInformer","signature":"func NewEndpointsInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/endpoints.go","code":"// NewEndpointsInformer constructs a new informer for Endpoints type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewEndpointsInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredEndpointsInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025356,"name":"NewFilteredEndpointsInformer","signature":"func NewFilteredEndpointsInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/endpoints.go","code":"// NewFilteredEndpointsInformer constructs a new informer for Endpoints type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredEndpointsInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().Endpoints(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().Endpoints(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026corev1.Endpoints{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025357,"name":"defaultInformer","signature":"func (f *endpointsInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/endpoints.go","code":"func (f *endpointsInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredEndpointsInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025358,"name":"Informer","signature":"func (f *endpointsInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/endpoints.go","code":"func (f *endpointsInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026corev1.Endpoints{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025359,"name":"Lister","signature":"func (f *endpointsInformer) Lister() v1.EndpointsLister","file":"staging/src/k8s.io/client-go/informers/core/v1/endpoints.go","code":"func (f *endpointsInformer) Lister() v1.EndpointsLister {\n\treturn v1.NewEndpointsLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025360,"name":"NewEventInformer","signature":"func NewEventInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/event.go","code":"// NewEventInformer constructs a new informer for Event type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewEventInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredEventInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025361,"name":"NewFilteredEventInformer","signature":"func NewFilteredEventInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/event.go","code":"// NewFilteredEventInformer constructs a new informer for Event type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredEventInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().Events(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().Events(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026corev1.Event{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025362,"name":"defaultInformer","signature":"func (f *eventInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/event.go","code":"func (f *eventInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredEventInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025363,"name":"Informer","signature":"func (f *eventInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/event.go","code":"func (f *eventInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026corev1.Event{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025364,"name":"Lister","signature":"func (f *eventInformer) Lister() v1.EventLister","file":"staging/src/k8s.io/client-go/informers/core/v1/event.go","code":"func (f *eventInformer) Lister() v1.EventLister {\n\treturn v1.NewEventLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025365,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/core/v1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":67,"to":70}} {"id":100025366,"name":"ComponentStatuses","signature":"func (v *version) ComponentStatuses() ComponentStatusInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/interface.go","code":"// ComponentStatuses returns a ComponentStatusInformer.\nfunc (v *version) ComponentStatuses() ComponentStatusInformer {\n\treturn \u0026componentStatusInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":72,"to":75}} {"id":100025367,"name":"ConfigMaps","signature":"func (v *version) ConfigMaps() ConfigMapInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/interface.go","code":"// ConfigMaps returns a ConfigMapInformer.\nfunc (v *version) ConfigMaps() ConfigMapInformer {\n\treturn \u0026configMapInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":77,"to":80}} {"id":100025368,"name":"Endpoints","signature":"func (v *version) Endpoints() EndpointsInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/interface.go","code":"// Endpoints returns a EndpointsInformer.\nfunc (v *version) Endpoints() EndpointsInformer {\n\treturn \u0026endpointsInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":82,"to":85}} {"id":100025369,"name":"Events","signature":"func (v *version) Events() EventInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/interface.go","code":"// Events returns a EventInformer.\nfunc (v *version) Events() EventInformer {\n\treturn \u0026eventInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":87,"to":90}} {"id":100025370,"name":"LimitRanges","signature":"func (v *version) LimitRanges() LimitRangeInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/interface.go","code":"// LimitRanges returns a LimitRangeInformer.\nfunc (v *version) LimitRanges() LimitRangeInformer {\n\treturn \u0026limitRangeInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":92,"to":95}} {"id":100025371,"name":"Namespaces","signature":"func (v *version) Namespaces() NamespaceInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/interface.go","code":"// Namespaces returns a NamespaceInformer.\nfunc (v *version) Namespaces() NamespaceInformer {\n\treturn \u0026namespaceInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":97,"to":100}} {"id":100025372,"name":"Nodes","signature":"func (v *version) Nodes() NodeInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/interface.go","code":"// Nodes returns a NodeInformer.\nfunc (v *version) Nodes() NodeInformer {\n\treturn \u0026nodeInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":102,"to":105}} {"id":100025373,"name":"PersistentVolumes","signature":"func (v *version) PersistentVolumes() PersistentVolumeInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/interface.go","code":"// PersistentVolumes returns a PersistentVolumeInformer.\nfunc (v *version) PersistentVolumes() PersistentVolumeInformer {\n\treturn \u0026persistentVolumeInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":107,"to":110}} {"id":100025374,"name":"PersistentVolumeClaims","signature":"func (v *version) PersistentVolumeClaims() PersistentVolumeClaimInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/interface.go","code":"// PersistentVolumeClaims returns a PersistentVolumeClaimInformer.\nfunc (v *version) PersistentVolumeClaims() PersistentVolumeClaimInformer {\n\treturn \u0026persistentVolumeClaimInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":112,"to":115}} {"id":100025375,"name":"Pods","signature":"func (v *version) Pods() PodInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/interface.go","code":"// Pods returns a PodInformer.\nfunc (v *version) Pods() PodInformer {\n\treturn \u0026podInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":117,"to":120}} {"id":100025376,"name":"PodTemplates","signature":"func (v *version) PodTemplates() PodTemplateInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/interface.go","code":"// PodTemplates returns a PodTemplateInformer.\nfunc (v *version) PodTemplates() PodTemplateInformer {\n\treturn \u0026podTemplateInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":122,"to":125}} {"id":100025377,"name":"ReplicationControllers","signature":"func (v *version) ReplicationControllers() ReplicationControllerInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/interface.go","code":"// ReplicationControllers returns a ReplicationControllerInformer.\nfunc (v *version) ReplicationControllers() ReplicationControllerInformer {\n\treturn \u0026replicationControllerInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":127,"to":130}} {"id":100025378,"name":"ResourceQuotas","signature":"func (v *version) ResourceQuotas() ResourceQuotaInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/interface.go","code":"// ResourceQuotas returns a ResourceQuotaInformer.\nfunc (v *version) ResourceQuotas() ResourceQuotaInformer {\n\treturn \u0026resourceQuotaInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":132,"to":135}} {"id":100025379,"name":"Secrets","signature":"func (v *version) Secrets() SecretInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/interface.go","code":"// Secrets returns a SecretInformer.\nfunc (v *version) Secrets() SecretInformer {\n\treturn \u0026secretInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":137,"to":140}} {"id":100025380,"name":"Services","signature":"func (v *version) Services() ServiceInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/interface.go","code":"// Services returns a ServiceInformer.\nfunc (v *version) Services() ServiceInformer {\n\treturn \u0026serviceInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":142,"to":145}} {"id":100025381,"name":"ServiceAccounts","signature":"func (v *version) ServiceAccounts() ServiceAccountInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/interface.go","code":"// ServiceAccounts returns a ServiceAccountInformer.\nfunc (v *version) ServiceAccounts() ServiceAccountInformer {\n\treturn \u0026serviceAccountInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":147,"to":150}} {"id":100025382,"name":"NewLimitRangeInformer","signature":"func NewLimitRangeInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/limitrange.go","code":"// NewLimitRangeInformer constructs a new informer for LimitRange type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewLimitRangeInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredLimitRangeInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025383,"name":"NewFilteredLimitRangeInformer","signature":"func NewFilteredLimitRangeInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/limitrange.go","code":"// NewFilteredLimitRangeInformer constructs a new informer for LimitRange type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredLimitRangeInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().LimitRanges(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().LimitRanges(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026corev1.LimitRange{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025384,"name":"defaultInformer","signature":"func (f *limitRangeInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/limitrange.go","code":"func (f *limitRangeInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredLimitRangeInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025385,"name":"Informer","signature":"func (f *limitRangeInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/limitrange.go","code":"func (f *limitRangeInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026corev1.LimitRange{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025386,"name":"Lister","signature":"func (f *limitRangeInformer) Lister() v1.LimitRangeLister","file":"staging/src/k8s.io/client-go/informers/core/v1/limitrange.go","code":"func (f *limitRangeInformer) Lister() v1.LimitRangeLister {\n\treturn v1.NewLimitRangeLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025387,"name":"NewNamespaceInformer","signature":"func NewNamespaceInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/namespace.go","code":"// NewNamespaceInformer constructs a new informer for Namespace type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewNamespaceInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredNamespaceInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025388,"name":"NewFilteredNamespaceInformer","signature":"func NewFilteredNamespaceInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/namespace.go","code":"// NewFilteredNamespaceInformer constructs a new informer for Namespace type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredNamespaceInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().Namespaces().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().Namespaces().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026corev1.Namespace{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025389,"name":"defaultInformer","signature":"func (f *namespaceInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/namespace.go","code":"func (f *namespaceInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredNamespaceInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025390,"name":"Informer","signature":"func (f *namespaceInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/namespace.go","code":"func (f *namespaceInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026corev1.Namespace{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025391,"name":"Lister","signature":"func (f *namespaceInformer) Lister() v1.NamespaceLister","file":"staging/src/k8s.io/client-go/informers/core/v1/namespace.go","code":"func (f *namespaceInformer) Lister() v1.NamespaceLister {\n\treturn v1.NewNamespaceLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025392,"name":"NewNodeInformer","signature":"func NewNodeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/node.go","code":"// NewNodeInformer constructs a new informer for Node type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewNodeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredNodeInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025393,"name":"NewFilteredNodeInformer","signature":"func NewFilteredNodeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/node.go","code":"// NewFilteredNodeInformer constructs a new informer for Node type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredNodeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().Nodes().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().Nodes().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026corev1.Node{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025394,"name":"defaultInformer","signature":"func (f *nodeInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/node.go","code":"func (f *nodeInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredNodeInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025395,"name":"Informer","signature":"func (f *nodeInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/node.go","code":"func (f *nodeInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026corev1.Node{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025396,"name":"Lister","signature":"func (f *nodeInformer) Lister() v1.NodeLister","file":"staging/src/k8s.io/client-go/informers/core/v1/node.go","code":"func (f *nodeInformer) Lister() v1.NodeLister {\n\treturn v1.NewNodeLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025397,"name":"NewPersistentVolumeInformer","signature":"func NewPersistentVolumeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/persistentvolume.go","code":"// NewPersistentVolumeInformer constructs a new informer for PersistentVolume type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewPersistentVolumeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredPersistentVolumeInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025398,"name":"NewFilteredPersistentVolumeInformer","signature":"func NewFilteredPersistentVolumeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/persistentvolume.go","code":"// NewFilteredPersistentVolumeInformer constructs a new informer for PersistentVolume type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredPersistentVolumeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().PersistentVolumes().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().PersistentVolumes().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026corev1.PersistentVolume{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025399,"name":"defaultInformer","signature":"func (f *persistentVolumeInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/persistentvolume.go","code":"func (f *persistentVolumeInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredPersistentVolumeInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025400,"name":"Informer","signature":"func (f *persistentVolumeInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/persistentvolume.go","code":"func (f *persistentVolumeInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026corev1.PersistentVolume{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025401,"name":"Lister","signature":"func (f *persistentVolumeInformer) Lister() v1.PersistentVolumeLister","file":"staging/src/k8s.io/client-go/informers/core/v1/persistentvolume.go","code":"func (f *persistentVolumeInformer) Lister() v1.PersistentVolumeLister {\n\treturn v1.NewPersistentVolumeLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025402,"name":"NewPersistentVolumeClaimInformer","signature":"func NewPersistentVolumeClaimInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/persistentvolumeclaim.go","code":"// NewPersistentVolumeClaimInformer constructs a new informer for PersistentVolumeClaim type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewPersistentVolumeClaimInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredPersistentVolumeClaimInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025403,"name":"NewFilteredPersistentVolumeClaimInformer","signature":"func NewFilteredPersistentVolumeClaimInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/persistentvolumeclaim.go","code":"// NewFilteredPersistentVolumeClaimInformer constructs a new informer for PersistentVolumeClaim type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredPersistentVolumeClaimInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().PersistentVolumeClaims(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().PersistentVolumeClaims(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026corev1.PersistentVolumeClaim{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025404,"name":"defaultInformer","signature":"func (f *persistentVolumeClaimInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/persistentvolumeclaim.go","code":"func (f *persistentVolumeClaimInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredPersistentVolumeClaimInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025405,"name":"Informer","signature":"func (f *persistentVolumeClaimInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/persistentvolumeclaim.go","code":"func (f *persistentVolumeClaimInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026corev1.PersistentVolumeClaim{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025406,"name":"Lister","signature":"func (f *persistentVolumeClaimInformer) Lister() v1.PersistentVolumeClaimLister","file":"staging/src/k8s.io/client-go/informers/core/v1/persistentvolumeclaim.go","code":"func (f *persistentVolumeClaimInformer) Lister() v1.PersistentVolumeClaimLister {\n\treturn v1.NewPersistentVolumeClaimLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025407,"name":"NewPodInformer","signature":"func NewPodInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/pod.go","code":"// NewPodInformer constructs a new informer for Pod type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewPodInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredPodInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025408,"name":"NewFilteredPodInformer","signature":"func NewFilteredPodInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/pod.go","code":"// NewFilteredPodInformer constructs a new informer for Pod type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredPodInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().Pods(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().Pods(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026corev1.Pod{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025409,"name":"defaultInformer","signature":"func (f *podInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/pod.go","code":"func (f *podInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredPodInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025410,"name":"Informer","signature":"func (f *podInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/pod.go","code":"func (f *podInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026corev1.Pod{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025411,"name":"Lister","signature":"func (f *podInformer) Lister() v1.PodLister","file":"staging/src/k8s.io/client-go/informers/core/v1/pod.go","code":"func (f *podInformer) Lister() v1.PodLister {\n\treturn v1.NewPodLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025412,"name":"NewPodTemplateInformer","signature":"func NewPodTemplateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/podtemplate.go","code":"// NewPodTemplateInformer constructs a new informer for PodTemplate type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewPodTemplateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredPodTemplateInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025413,"name":"NewFilteredPodTemplateInformer","signature":"func NewFilteredPodTemplateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/podtemplate.go","code":"// NewFilteredPodTemplateInformer constructs a new informer for PodTemplate type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredPodTemplateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().PodTemplates(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().PodTemplates(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026corev1.PodTemplate{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025414,"name":"defaultInformer","signature":"func (f *podTemplateInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/podtemplate.go","code":"func (f *podTemplateInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredPodTemplateInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025415,"name":"Informer","signature":"func (f *podTemplateInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/podtemplate.go","code":"func (f *podTemplateInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026corev1.PodTemplate{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025416,"name":"Lister","signature":"func (f *podTemplateInformer) Lister() v1.PodTemplateLister","file":"staging/src/k8s.io/client-go/informers/core/v1/podtemplate.go","code":"func (f *podTemplateInformer) Lister() v1.PodTemplateLister {\n\treturn v1.NewPodTemplateLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025417,"name":"NewReplicationControllerInformer","signature":"func NewReplicationControllerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/replicationcontroller.go","code":"// NewReplicationControllerInformer constructs a new informer for ReplicationController type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewReplicationControllerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredReplicationControllerInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025418,"name":"NewFilteredReplicationControllerInformer","signature":"func NewFilteredReplicationControllerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/replicationcontroller.go","code":"// NewFilteredReplicationControllerInformer constructs a new informer for ReplicationController type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredReplicationControllerInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().ReplicationControllers(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().ReplicationControllers(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026corev1.ReplicationController{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025419,"name":"defaultInformer","signature":"func (f *replicationControllerInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/replicationcontroller.go","code":"func (f *replicationControllerInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredReplicationControllerInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025420,"name":"Informer","signature":"func (f *replicationControllerInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/replicationcontroller.go","code":"func (f *replicationControllerInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026corev1.ReplicationController{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025421,"name":"Lister","signature":"func (f *replicationControllerInformer) Lister() v1.ReplicationControllerLister","file":"staging/src/k8s.io/client-go/informers/core/v1/replicationcontroller.go","code":"func (f *replicationControllerInformer) Lister() v1.ReplicationControllerLister {\n\treturn v1.NewReplicationControllerLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025422,"name":"NewResourceQuotaInformer","signature":"func NewResourceQuotaInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/resourcequota.go","code":"// NewResourceQuotaInformer constructs a new informer for ResourceQuota type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewResourceQuotaInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredResourceQuotaInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025423,"name":"NewFilteredResourceQuotaInformer","signature":"func NewFilteredResourceQuotaInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/resourcequota.go","code":"// NewFilteredResourceQuotaInformer constructs a new informer for ResourceQuota type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredResourceQuotaInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().ResourceQuotas(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().ResourceQuotas(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026corev1.ResourceQuota{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025424,"name":"defaultInformer","signature":"func (f *resourceQuotaInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/resourcequota.go","code":"func (f *resourceQuotaInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredResourceQuotaInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025425,"name":"Informer","signature":"func (f *resourceQuotaInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/resourcequota.go","code":"func (f *resourceQuotaInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026corev1.ResourceQuota{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025426,"name":"Lister","signature":"func (f *resourceQuotaInformer) Lister() v1.ResourceQuotaLister","file":"staging/src/k8s.io/client-go/informers/core/v1/resourcequota.go","code":"func (f *resourceQuotaInformer) Lister() v1.ResourceQuotaLister {\n\treturn v1.NewResourceQuotaLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025427,"name":"NewSecretInformer","signature":"func NewSecretInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/secret.go","code":"// NewSecretInformer constructs a new informer for Secret type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewSecretInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredSecretInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025428,"name":"NewFilteredSecretInformer","signature":"func NewFilteredSecretInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/secret.go","code":"// NewFilteredSecretInformer constructs a new informer for Secret type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredSecretInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().Secrets(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().Secrets(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026corev1.Secret{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025429,"name":"defaultInformer","signature":"func (f *secretInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/secret.go","code":"func (f *secretInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredSecretInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025430,"name":"Informer","signature":"func (f *secretInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/secret.go","code":"func (f *secretInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026corev1.Secret{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025431,"name":"Lister","signature":"func (f *secretInformer) Lister() v1.SecretLister","file":"staging/src/k8s.io/client-go/informers/core/v1/secret.go","code":"func (f *secretInformer) Lister() v1.SecretLister {\n\treturn v1.NewSecretLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025432,"name":"NewServiceInformer","signature":"func NewServiceInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/service.go","code":"// NewServiceInformer constructs a new informer for Service type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewServiceInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredServiceInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025433,"name":"NewFilteredServiceInformer","signature":"func NewFilteredServiceInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/service.go","code":"// NewFilteredServiceInformer constructs a new informer for Service type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredServiceInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().Services(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().Services(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026corev1.Service{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025434,"name":"defaultInformer","signature":"func (f *serviceInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/service.go","code":"func (f *serviceInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredServiceInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025435,"name":"Informer","signature":"func (f *serviceInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/service.go","code":"func (f *serviceInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026corev1.Service{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025436,"name":"Lister","signature":"func (f *serviceInformer) Lister() v1.ServiceLister","file":"staging/src/k8s.io/client-go/informers/core/v1/service.go","code":"func (f *serviceInformer) Lister() v1.ServiceLister {\n\treturn v1.NewServiceLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025437,"name":"NewServiceAccountInformer","signature":"func NewServiceAccountInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/serviceaccount.go","code":"// NewServiceAccountInformer constructs a new informer for ServiceAccount type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewServiceAccountInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredServiceAccountInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025438,"name":"NewFilteredServiceAccountInformer","signature":"func NewFilteredServiceAccountInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/serviceaccount.go","code":"// NewFilteredServiceAccountInformer constructs a new informer for ServiceAccount type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredServiceAccountInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().ServiceAccounts(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.CoreV1().ServiceAccounts(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026corev1.ServiceAccount{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025439,"name":"defaultInformer","signature":"func (f *serviceAccountInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/serviceaccount.go","code":"func (f *serviceAccountInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredServiceAccountInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025440,"name":"Informer","signature":"func (f *serviceAccountInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/core/v1/serviceaccount.go","code":"func (f *serviceAccountInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026corev1.ServiceAccount{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025441,"name":"Lister","signature":"func (f *serviceAccountInformer) Lister() v1.ServiceAccountLister","file":"staging/src/k8s.io/client-go/informers/core/v1/serviceaccount.go","code":"func (f *serviceAccountInformer) Lister() v1.ServiceAccountLister {\n\treturn v1.NewServiceAccountLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025442,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/discovery/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":41,"to":44}} {"id":100025443,"name":"V1","signature":"func (g *group) V1() v1.Interface","file":"staging/src/k8s.io/client-go/informers/discovery/interface.go","code":"// V1 returns a new v1.Interface.\nfunc (g *group) V1() v1.Interface {\n\treturn v1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":46,"to":49}} {"id":100025444,"name":"V1beta1","signature":"func (g *group) V1beta1() v1beta1.Interface","file":"staging/src/k8s.io/client-go/informers/discovery/interface.go","code":"// V1beta1 returns a new v1beta1.Interface.\nfunc (g *group) V1beta1() v1beta1.Interface {\n\treturn v1beta1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":51,"to":54}} {"id":100025445,"name":"NewEndpointSliceInformer","signature":"func NewEndpointSliceInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/discovery/v1/endpointslice.go","code":"// NewEndpointSliceInformer constructs a new informer for EndpointSlice type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewEndpointSliceInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredEndpointSliceInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025446,"name":"NewFilteredEndpointSliceInformer","signature":"func NewFilteredEndpointSliceInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/discovery/v1/endpointslice.go","code":"// NewFilteredEndpointSliceInformer constructs a new informer for EndpointSlice type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredEndpointSliceInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.DiscoveryV1().EndpointSlices(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.DiscoveryV1().EndpointSlices(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026discoveryv1.EndpointSlice{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025447,"name":"defaultInformer","signature":"func (f *endpointSliceInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/discovery/v1/endpointslice.go","code":"func (f *endpointSliceInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredEndpointSliceInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025448,"name":"Informer","signature":"func (f *endpointSliceInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/discovery/v1/endpointslice.go","code":"func (f *endpointSliceInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026discoveryv1.EndpointSlice{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025449,"name":"Lister","signature":"func (f *endpointSliceInformer) Lister() v1.EndpointSliceLister","file":"staging/src/k8s.io/client-go/informers/discovery/v1/endpointslice.go","code":"func (f *endpointSliceInformer) Lister() v1.EndpointSliceLister {\n\treturn v1.NewEndpointSliceLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025450,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/discovery/v1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":37,"to":40}} {"id":100025451,"name":"EndpointSlices","signature":"func (v *version) EndpointSlices() EndpointSliceInformer","file":"staging/src/k8s.io/client-go/informers/discovery/v1/interface.go","code":"// EndpointSlices returns a EndpointSliceInformer.\nfunc (v *version) EndpointSlices() EndpointSliceInformer {\n\treturn \u0026endpointSliceInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":42,"to":45}} {"id":100025452,"name":"NewEndpointSliceInformer","signature":"func NewEndpointSliceInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/discovery/v1beta1/endpointslice.go","code":"// NewEndpointSliceInformer constructs a new informer for EndpointSlice type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewEndpointSliceInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredEndpointSliceInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025453,"name":"NewFilteredEndpointSliceInformer","signature":"func NewFilteredEndpointSliceInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/discovery/v1beta1/endpointslice.go","code":"// NewFilteredEndpointSliceInformer constructs a new informer for EndpointSlice type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredEndpointSliceInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.DiscoveryV1beta1().EndpointSlices(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.DiscoveryV1beta1().EndpointSlices(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026discoveryv1beta1.EndpointSlice{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025454,"name":"defaultInformer","signature":"func (f *endpointSliceInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/discovery/v1beta1/endpointslice.go","code":"func (f *endpointSliceInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredEndpointSliceInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025455,"name":"Informer","signature":"func (f *endpointSliceInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/discovery/v1beta1/endpointslice.go","code":"func (f *endpointSliceInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026discoveryv1beta1.EndpointSlice{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025456,"name":"Lister","signature":"func (f *endpointSliceInformer) Lister() v1beta1.EndpointSliceLister","file":"staging/src/k8s.io/client-go/informers/discovery/v1beta1/endpointslice.go","code":"func (f *endpointSliceInformer) Lister() v1beta1.EndpointSliceLister {\n\treturn v1beta1.NewEndpointSliceLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025457,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/discovery/v1beta1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":37,"to":40}} {"id":100025458,"name":"EndpointSlices","signature":"func (v *version) EndpointSlices() EndpointSliceInformer","file":"staging/src/k8s.io/client-go/informers/discovery/v1beta1/interface.go","code":"// EndpointSlices returns a EndpointSliceInformer.\nfunc (v *version) EndpointSlices() EndpointSliceInformer {\n\treturn \u0026endpointSliceInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":42,"to":45}} {"id":100025459,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/events/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":41,"to":44}} {"id":100025460,"name":"V1","signature":"func (g *group) V1() v1.Interface","file":"staging/src/k8s.io/client-go/informers/events/interface.go","code":"// V1 returns a new v1.Interface.\nfunc (g *group) V1() v1.Interface {\n\treturn v1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":46,"to":49}} {"id":100025461,"name":"V1beta1","signature":"func (g *group) V1beta1() v1beta1.Interface","file":"staging/src/k8s.io/client-go/informers/events/interface.go","code":"// V1beta1 returns a new v1beta1.Interface.\nfunc (g *group) V1beta1() v1beta1.Interface {\n\treturn v1beta1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":51,"to":54}} {"id":100025462,"name":"NewEventInformer","signature":"func NewEventInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/events/v1/event.go","code":"// NewEventInformer constructs a new informer for Event type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewEventInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredEventInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025463,"name":"NewFilteredEventInformer","signature":"func NewFilteredEventInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/events/v1/event.go","code":"// NewFilteredEventInformer constructs a new informer for Event type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredEventInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.EventsV1().Events(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.EventsV1().Events(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026eventsv1.Event{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025464,"name":"defaultInformer","signature":"func (f *eventInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/events/v1/event.go","code":"func (f *eventInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredEventInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025465,"name":"Informer","signature":"func (f *eventInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/events/v1/event.go","code":"func (f *eventInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026eventsv1.Event{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025466,"name":"Lister","signature":"func (f *eventInformer) Lister() v1.EventLister","file":"staging/src/k8s.io/client-go/informers/events/v1/event.go","code":"func (f *eventInformer) Lister() v1.EventLister {\n\treturn v1.NewEventLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025467,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/events/v1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":37,"to":40}} {"id":100025468,"name":"Events","signature":"func (v *version) Events() EventInformer","file":"staging/src/k8s.io/client-go/informers/events/v1/interface.go","code":"// Events returns a EventInformer.\nfunc (v *version) Events() EventInformer {\n\treturn \u0026eventInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":42,"to":45}} {"id":100025469,"name":"NewEventInformer","signature":"func NewEventInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/events/v1beta1/event.go","code":"// NewEventInformer constructs a new informer for Event type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewEventInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredEventInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025470,"name":"NewFilteredEventInformer","signature":"func NewFilteredEventInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/events/v1beta1/event.go","code":"// NewFilteredEventInformer constructs a new informer for Event type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredEventInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.EventsV1beta1().Events(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.EventsV1beta1().Events(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026eventsv1beta1.Event{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025471,"name":"defaultInformer","signature":"func (f *eventInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/events/v1beta1/event.go","code":"func (f *eventInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredEventInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025472,"name":"Informer","signature":"func (f *eventInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/events/v1beta1/event.go","code":"func (f *eventInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026eventsv1beta1.Event{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025473,"name":"Lister","signature":"func (f *eventInformer) Lister() v1beta1.EventLister","file":"staging/src/k8s.io/client-go/informers/events/v1beta1/event.go","code":"func (f *eventInformer) Lister() v1beta1.EventLister {\n\treturn v1beta1.NewEventLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025474,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/events/v1beta1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":37,"to":40}} {"id":100025475,"name":"Events","signature":"func (v *version) Events() EventInformer","file":"staging/src/k8s.io/client-go/informers/events/v1beta1/interface.go","code":"// Events returns a EventInformer.\nfunc (v *version) Events() EventInformer {\n\treturn \u0026eventInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":42,"to":45}} {"id":100025476,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/extensions/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":38,"to":41}} {"id":100025477,"name":"V1beta1","signature":"func (g *group) V1beta1() v1beta1.Interface","file":"staging/src/k8s.io/client-go/informers/extensions/interface.go","code":"// V1beta1 returns a new v1beta1.Interface.\nfunc (g *group) V1beta1() v1beta1.Interface {\n\treturn v1beta1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":43,"to":46}} {"id":100025478,"name":"NewDaemonSetInformer","signature":"func NewDaemonSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/daemonset.go","code":"// NewDaemonSetInformer constructs a new informer for DaemonSet type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewDaemonSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredDaemonSetInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025479,"name":"NewFilteredDaemonSetInformer","signature":"func NewFilteredDaemonSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/daemonset.go","code":"// NewFilteredDaemonSetInformer constructs a new informer for DaemonSet type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredDaemonSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.ExtensionsV1beta1().DaemonSets(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.ExtensionsV1beta1().DaemonSets(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026extensionsv1beta1.DaemonSet{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025480,"name":"defaultInformer","signature":"func (f *daemonSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/daemonset.go","code":"func (f *daemonSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredDaemonSetInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025481,"name":"Informer","signature":"func (f *daemonSetInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/daemonset.go","code":"func (f *daemonSetInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026extensionsv1beta1.DaemonSet{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025482,"name":"Lister","signature":"func (f *daemonSetInformer) Lister() v1beta1.DaemonSetLister","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/daemonset.go","code":"func (f *daemonSetInformer) Lister() v1beta1.DaemonSetLister {\n\treturn v1beta1.NewDaemonSetLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025483,"name":"NewDeploymentInformer","signature":"func NewDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/deployment.go","code":"// NewDeploymentInformer constructs a new informer for Deployment type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredDeploymentInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025484,"name":"NewFilteredDeploymentInformer","signature":"func NewFilteredDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/deployment.go","code":"// NewFilteredDeploymentInformer constructs a new informer for Deployment type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredDeploymentInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.ExtensionsV1beta1().Deployments(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.ExtensionsV1beta1().Deployments(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026extensionsv1beta1.Deployment{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025485,"name":"defaultInformer","signature":"func (f *deploymentInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/deployment.go","code":"func (f *deploymentInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredDeploymentInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025486,"name":"Informer","signature":"func (f *deploymentInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/deployment.go","code":"func (f *deploymentInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026extensionsv1beta1.Deployment{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025487,"name":"Lister","signature":"func (f *deploymentInformer) Lister() v1beta1.DeploymentLister","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/deployment.go","code":"func (f *deploymentInformer) Lister() v1beta1.DeploymentLister {\n\treturn v1beta1.NewDeploymentLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025488,"name":"NewIngressInformer","signature":"func NewIngressInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/ingress.go","code":"// NewIngressInformer constructs a new informer for Ingress type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewIngressInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredIngressInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025489,"name":"NewFilteredIngressInformer","signature":"func NewFilteredIngressInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/ingress.go","code":"// NewFilteredIngressInformer constructs a new informer for Ingress type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredIngressInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.ExtensionsV1beta1().Ingresses(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.ExtensionsV1beta1().Ingresses(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026extensionsv1beta1.Ingress{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025490,"name":"defaultInformer","signature":"func (f *ingressInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/ingress.go","code":"func (f *ingressInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredIngressInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025491,"name":"Informer","signature":"func (f *ingressInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/ingress.go","code":"func (f *ingressInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026extensionsv1beta1.Ingress{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025492,"name":"Lister","signature":"func (f *ingressInformer) Lister() v1beta1.IngressLister","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/ingress.go","code":"func (f *ingressInformer) Lister() v1beta1.IngressLister {\n\treturn v1beta1.NewIngressLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025493,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":45,"to":48}} {"id":100025494,"name":"DaemonSets","signature":"func (v *version) DaemonSets() DaemonSetInformer","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/interface.go","code":"// DaemonSets returns a DaemonSetInformer.\nfunc (v *version) DaemonSets() DaemonSetInformer {\n\treturn \u0026daemonSetInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":50,"to":53}} {"id":100025495,"name":"Deployments","signature":"func (v *version) Deployments() DeploymentInformer","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/interface.go","code":"// Deployments returns a DeploymentInformer.\nfunc (v *version) Deployments() DeploymentInformer {\n\treturn \u0026deploymentInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":55,"to":58}} {"id":100025496,"name":"Ingresses","signature":"func (v *version) Ingresses() IngressInformer","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/interface.go","code":"// Ingresses returns a IngressInformer.\nfunc (v *version) Ingresses() IngressInformer {\n\treturn \u0026ingressInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":60,"to":63}} {"id":100025497,"name":"NetworkPolicies","signature":"func (v *version) NetworkPolicies() NetworkPolicyInformer","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/interface.go","code":"// NetworkPolicies returns a NetworkPolicyInformer.\nfunc (v *version) NetworkPolicies() NetworkPolicyInformer {\n\treturn \u0026networkPolicyInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":65,"to":68}} {"id":100025498,"name":"ReplicaSets","signature":"func (v *version) ReplicaSets() ReplicaSetInformer","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/interface.go","code":"// ReplicaSets returns a ReplicaSetInformer.\nfunc (v *version) ReplicaSets() ReplicaSetInformer {\n\treturn \u0026replicaSetInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":70,"to":73}} {"id":100025499,"name":"NewNetworkPolicyInformer","signature":"func NewNetworkPolicyInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/networkpolicy.go","code":"// NewNetworkPolicyInformer constructs a new informer for NetworkPolicy type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewNetworkPolicyInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredNetworkPolicyInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025500,"name":"NewFilteredNetworkPolicyInformer","signature":"func NewFilteredNetworkPolicyInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/networkpolicy.go","code":"// NewFilteredNetworkPolicyInformer constructs a new informer for NetworkPolicy type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredNetworkPolicyInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.ExtensionsV1beta1().NetworkPolicies(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.ExtensionsV1beta1().NetworkPolicies(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026extensionsv1beta1.NetworkPolicy{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025501,"name":"defaultInformer","signature":"func (f *networkPolicyInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/networkpolicy.go","code":"func (f *networkPolicyInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredNetworkPolicyInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025502,"name":"Informer","signature":"func (f *networkPolicyInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/networkpolicy.go","code":"func (f *networkPolicyInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026extensionsv1beta1.NetworkPolicy{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025503,"name":"Lister","signature":"func (f *networkPolicyInformer) Lister() v1beta1.NetworkPolicyLister","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/networkpolicy.go","code":"func (f *networkPolicyInformer) Lister() v1beta1.NetworkPolicyLister {\n\treturn v1beta1.NewNetworkPolicyLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025504,"name":"NewReplicaSetInformer","signature":"func NewReplicaSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/replicaset.go","code":"// NewReplicaSetInformer constructs a new informer for ReplicaSet type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewReplicaSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredReplicaSetInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025505,"name":"NewFilteredReplicaSetInformer","signature":"func NewFilteredReplicaSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/replicaset.go","code":"// NewFilteredReplicaSetInformer constructs a new informer for ReplicaSet type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredReplicaSetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.ExtensionsV1beta1().ReplicaSets(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.ExtensionsV1beta1().ReplicaSets(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026extensionsv1beta1.ReplicaSet{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025506,"name":"defaultInformer","signature":"func (f *replicaSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/replicaset.go","code":"func (f *replicaSetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredReplicaSetInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025507,"name":"Informer","signature":"func (f *replicaSetInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/replicaset.go","code":"func (f *replicaSetInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026extensionsv1beta1.ReplicaSet{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025508,"name":"Lister","signature":"func (f *replicaSetInformer) Lister() v1beta1.ReplicaSetLister","file":"staging/src/k8s.io/client-go/informers/extensions/v1beta1/replicaset.go","code":"func (f *replicaSetInformer) Lister() v1beta1.ReplicaSetLister {\n\treturn v1beta1.NewReplicaSetLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025509,"name":"WithCustomResyncConfig","signature":"func WithCustomResyncConfig(resyncConfig map[v1.Object]time.Duration) SharedInformerOption","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"// WithCustomResyncConfig sets a custom resync period for the specified informer types.\nfunc WithCustomResyncConfig(resyncConfig map[v1.Object]time.Duration) SharedInformerOption {\n\treturn func(factory *sharedInformerFactory) *sharedInformerFactory {\n\t\tfor k, v := range resyncConfig {\n\t\t\tfactory.customResync[reflect.TypeOf(k)] = v\n\t\t}\n\t\treturn factory\n\t}\n}","line":{"from":75,"to":83}} {"id":100025510,"name":"WithTweakListOptions","signature":"func WithTweakListOptions(tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerOption","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"// WithTweakListOptions sets a custom filter on all listers of the configured SharedInformerFactory.\nfunc WithTweakListOptions(tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerOption {\n\treturn func(factory *sharedInformerFactory) *sharedInformerFactory {\n\t\tfactory.tweakListOptions = tweakListOptions\n\t\treturn factory\n\t}\n}","line":{"from":85,"to":91}} {"id":100025511,"name":"WithNamespace","signature":"func WithNamespace(namespace string) SharedInformerOption","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"// WithNamespace limits the SharedInformerFactory to the specified namespace.\nfunc WithNamespace(namespace string) SharedInformerOption {\n\treturn func(factory *sharedInformerFactory) *sharedInformerFactory {\n\t\tfactory.namespace = namespace\n\t\treturn factory\n\t}\n}","line":{"from":93,"to":99}} {"id":100025512,"name":"NewSharedInformerFactory","signature":"func NewSharedInformerFactory(client kubernetes.Interface, defaultResync time.Duration) SharedInformerFactory","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"// NewSharedInformerFactory constructs a new instance of sharedInformerFactory for all namespaces.\nfunc NewSharedInformerFactory(client kubernetes.Interface, defaultResync time.Duration) SharedInformerFactory {\n\treturn NewSharedInformerFactoryWithOptions(client, defaultResync)\n}","line":{"from":101,"to":104}} {"id":100025513,"name":"NewFilteredSharedInformerFactory","signature":"func NewFilteredSharedInformerFactory(client kubernetes.Interface, defaultResync time.Duration, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerFactory","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"// NewFilteredSharedInformerFactory constructs a new instance of sharedInformerFactory.\n// Listers obtained via this SharedInformerFactory will be subject to the same filters\n// as specified here.\n// Deprecated: Please use NewSharedInformerFactoryWithOptions instead\nfunc NewFilteredSharedInformerFactory(client kubernetes.Interface, defaultResync time.Duration, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerFactory {\n\treturn NewSharedInformerFactoryWithOptions(client, defaultResync, WithNamespace(namespace), WithTweakListOptions(tweakListOptions))\n}","line":{"from":106,"to":112}} {"id":100025514,"name":"NewSharedInformerFactoryWithOptions","signature":"func NewSharedInformerFactoryWithOptions(client kubernetes.Interface, defaultResync time.Duration, options ...SharedInformerOption) SharedInformerFactory","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"// NewSharedInformerFactoryWithOptions constructs a new instance of a SharedInformerFactory with additional options.\nfunc NewSharedInformerFactoryWithOptions(client kubernetes.Interface, defaultResync time.Duration, options ...SharedInformerOption) SharedInformerFactory {\n\tfactory := \u0026sharedInformerFactory{\n\t\tclient: client,\n\t\tnamespace: v1.NamespaceAll,\n\t\tdefaultResync: defaultResync,\n\t\tinformers: make(map[reflect.Type]cache.SharedIndexInformer),\n\t\tstartedInformers: make(map[reflect.Type]bool),\n\t\tcustomResync: make(map[reflect.Type]time.Duration),\n\t}\n\n\t// Apply all options\n\tfor _, opt := range options {\n\t\tfactory = opt(factory)\n\t}\n\n\treturn factory\n}","line":{"from":114,"to":131}} {"id":100025515,"name":"Start","signature":"func (f *sharedInformerFactory) Start(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"func (f *sharedInformerFactory) Start(stopCh \u003c-chan struct{}) {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\n\tif f.shuttingDown {\n\t\treturn\n\t}\n\n\tfor informerType, informer := range f.informers {\n\t\tif !f.startedInformers[informerType] {\n\t\t\tf.wg.Add(1)\n\t\t\t// We need a new variable in each loop iteration,\n\t\t\t// otherwise the goroutine would use the loop variable\n\t\t\t// and that keeps changing.\n\t\t\tinformer := informer\n\t\t\tgo func() {\n\t\t\t\tdefer f.wg.Done()\n\t\t\t\tinformer.Run(stopCh)\n\t\t\t}()\n\t\t\tf.startedInformers[informerType] = true\n\t\t}\n\t}\n}","line":{"from":133,"to":155}} {"id":100025516,"name":"Shutdown","signature":"func (f *sharedInformerFactory) Shutdown()","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"func (f *sharedInformerFactory) Shutdown() {\n\tf.lock.Lock()\n\tf.shuttingDown = true\n\tf.lock.Unlock()\n\n\t// Will return immediately if there is nothing to wait for.\n\tf.wg.Wait()\n}","line":{"from":157,"to":164}} {"id":100025517,"name":"WaitForCacheSync","signature":"func (f *sharedInformerFactory) WaitForCacheSync(stopCh \u003c-chan struct{}) map[reflect.Type]bool","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"func (f *sharedInformerFactory) WaitForCacheSync(stopCh \u003c-chan struct{}) map[reflect.Type]bool {\n\tinformers := func() map[reflect.Type]cache.SharedIndexInformer {\n\t\tf.lock.Lock()\n\t\tdefer f.lock.Unlock()\n\n\t\tinformers := map[reflect.Type]cache.SharedIndexInformer{}\n\t\tfor informerType, informer := range f.informers {\n\t\t\tif f.startedInformers[informerType] {\n\t\t\t\tinformers[informerType] = informer\n\t\t\t}\n\t\t}\n\t\treturn informers\n\t}()\n\n\tres := map[reflect.Type]bool{}\n\tfor informType, informer := range informers {\n\t\tres[informType] = cache.WaitForCacheSync(stopCh, informer.HasSynced)\n\t}\n\treturn res\n}","line":{"from":166,"to":185}} {"id":100025518,"name":"InformerFor","signature":"func (f *sharedInformerFactory) InformerFor(obj runtime.Object, newFunc internalinterfaces.NewInformerFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"// InternalInformerFor returns the SharedIndexInformer for obj using an internal\n// client.\nfunc (f *sharedInformerFactory) InformerFor(obj runtime.Object, newFunc internalinterfaces.NewInformerFunc) cache.SharedIndexInformer {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\n\tinformerType := reflect.TypeOf(obj)\n\tinformer, exists := f.informers[informerType]\n\tif exists {\n\t\treturn informer\n\t}\n\n\tresyncPeriod, exists := f.customResync[informerType]\n\tif !exists {\n\t\tresyncPeriod = f.defaultResync\n\t}\n\n\tinformer = newFunc(f.client, resyncPeriod)\n\tf.informers[informerType] = informer\n\n\treturn informer\n}","line":{"from":187,"to":208}} {"id":100025519,"name":"Admissionregistration","signature":"func (f *sharedInformerFactory) Admissionregistration() admissionregistration.Interface","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"func (f *sharedInformerFactory) Admissionregistration() admissionregistration.Interface {\n\treturn admissionregistration.New(f, f.namespace, f.tweakListOptions)\n}","line":{"from":285,"to":287}} {"id":100025520,"name":"Internal","signature":"func (f *sharedInformerFactory) Internal() apiserverinternal.Interface","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"func (f *sharedInformerFactory) Internal() apiserverinternal.Interface {\n\treturn apiserverinternal.New(f, f.namespace, f.tweakListOptions)\n}","line":{"from":289,"to":291}} {"id":100025521,"name":"Apps","signature":"func (f *sharedInformerFactory) Apps() apps.Interface","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"func (f *sharedInformerFactory) Apps() apps.Interface {\n\treturn apps.New(f, f.namespace, f.tweakListOptions)\n}","line":{"from":293,"to":295}} {"id":100025522,"name":"Autoscaling","signature":"func (f *sharedInformerFactory) Autoscaling() autoscaling.Interface","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"func (f *sharedInformerFactory) Autoscaling() autoscaling.Interface {\n\treturn autoscaling.New(f, f.namespace, f.tweakListOptions)\n}","line":{"from":297,"to":299}} {"id":100025523,"name":"Batch","signature":"func (f *sharedInformerFactory) Batch() batch.Interface","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"func (f *sharedInformerFactory) Batch() batch.Interface {\n\treturn batch.New(f, f.namespace, f.tweakListOptions)\n}","line":{"from":301,"to":303}} {"id":100025524,"name":"Certificates","signature":"func (f *sharedInformerFactory) Certificates() certificates.Interface","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"func (f *sharedInformerFactory) Certificates() certificates.Interface {\n\treturn certificates.New(f, f.namespace, f.tweakListOptions)\n}","line":{"from":305,"to":307}} {"id":100025525,"name":"Coordination","signature":"func (f *sharedInformerFactory) Coordination() coordination.Interface","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"func (f *sharedInformerFactory) Coordination() coordination.Interface {\n\treturn coordination.New(f, f.namespace, f.tweakListOptions)\n}","line":{"from":309,"to":311}} {"id":100025526,"name":"Core","signature":"func (f *sharedInformerFactory) Core() core.Interface","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"func (f *sharedInformerFactory) Core() core.Interface {\n\treturn core.New(f, f.namespace, f.tweakListOptions)\n}","line":{"from":313,"to":315}} {"id":100025527,"name":"Discovery","signature":"func (f *sharedInformerFactory) Discovery() discovery.Interface","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"func (f *sharedInformerFactory) Discovery() discovery.Interface {\n\treturn discovery.New(f, f.namespace, f.tweakListOptions)\n}","line":{"from":317,"to":319}} {"id":100025528,"name":"Events","signature":"func (f *sharedInformerFactory) Events() events.Interface","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"func (f *sharedInformerFactory) Events() events.Interface {\n\treturn events.New(f, f.namespace, f.tweakListOptions)\n}","line":{"from":321,"to":323}} {"id":100025529,"name":"Extensions","signature":"func (f *sharedInformerFactory) Extensions() extensions.Interface","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"func (f *sharedInformerFactory) Extensions() extensions.Interface {\n\treturn extensions.New(f, f.namespace, f.tweakListOptions)\n}","line":{"from":325,"to":327}} {"id":100025530,"name":"Flowcontrol","signature":"func (f *sharedInformerFactory) Flowcontrol() flowcontrol.Interface","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"func (f *sharedInformerFactory) Flowcontrol() flowcontrol.Interface {\n\treturn flowcontrol.New(f, f.namespace, f.tweakListOptions)\n}","line":{"from":329,"to":331}} {"id":100025531,"name":"Networking","signature":"func (f *sharedInformerFactory) Networking() networking.Interface","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"func (f *sharedInformerFactory) Networking() networking.Interface {\n\treturn networking.New(f, f.namespace, f.tweakListOptions)\n}","line":{"from":333,"to":335}} {"id":100025532,"name":"Node","signature":"func (f *sharedInformerFactory) Node() node.Interface","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"func (f *sharedInformerFactory) Node() node.Interface {\n\treturn node.New(f, f.namespace, f.tweakListOptions)\n}","line":{"from":337,"to":339}} {"id":100025533,"name":"Policy","signature":"func (f *sharedInformerFactory) Policy() policy.Interface","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"func (f *sharedInformerFactory) Policy() policy.Interface {\n\treturn policy.New(f, f.namespace, f.tweakListOptions)\n}","line":{"from":341,"to":343}} {"id":100025534,"name":"Rbac","signature":"func (f *sharedInformerFactory) Rbac() rbac.Interface","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"func (f *sharedInformerFactory) Rbac() rbac.Interface {\n\treturn rbac.New(f, f.namespace, f.tweakListOptions)\n}","line":{"from":345,"to":347}} {"id":100025535,"name":"Resource","signature":"func (f *sharedInformerFactory) Resource() resource.Interface","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"func (f *sharedInformerFactory) Resource() resource.Interface {\n\treturn resource.New(f, f.namespace, f.tweakListOptions)\n}","line":{"from":349,"to":351}} {"id":100025536,"name":"Scheduling","signature":"func (f *sharedInformerFactory) Scheduling() scheduling.Interface","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"func (f *sharedInformerFactory) Scheduling() scheduling.Interface {\n\treturn scheduling.New(f, f.namespace, f.tweakListOptions)\n}","line":{"from":353,"to":355}} {"id":100025537,"name":"Storage","signature":"func (f *sharedInformerFactory) Storage() storage.Interface","file":"staging/src/k8s.io/client-go/informers/factory.go","code":"func (f *sharedInformerFactory) Storage() storage.Interface {\n\treturn storage.New(f, f.namespace, f.tweakListOptions)\n}","line":{"from":357,"to":359}} {"id":100025538,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/flowcontrol/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":47,"to":50}} {"id":100025539,"name":"V1alpha1","signature":"func (g *group) V1alpha1() v1alpha1.Interface","file":"staging/src/k8s.io/client-go/informers/flowcontrol/interface.go","code":"// V1alpha1 returns a new v1alpha1.Interface.\nfunc (g *group) V1alpha1() v1alpha1.Interface {\n\treturn v1alpha1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":52,"to":55}} {"id":100025540,"name":"V1beta1","signature":"func (g *group) V1beta1() v1beta1.Interface","file":"staging/src/k8s.io/client-go/informers/flowcontrol/interface.go","code":"// V1beta1 returns a new v1beta1.Interface.\nfunc (g *group) V1beta1() v1beta1.Interface {\n\treturn v1beta1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":57,"to":60}} {"id":100025541,"name":"V1beta2","signature":"func (g *group) V1beta2() v1beta2.Interface","file":"staging/src/k8s.io/client-go/informers/flowcontrol/interface.go","code":"// V1beta2 returns a new v1beta2.Interface.\nfunc (g *group) V1beta2() v1beta2.Interface {\n\treturn v1beta2.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":62,"to":65}} {"id":100025542,"name":"V1beta3","signature":"func (g *group) V1beta3() v1beta3.Interface","file":"staging/src/k8s.io/client-go/informers/flowcontrol/interface.go","code":"// V1beta3 returns a new v1beta3.Interface.\nfunc (g *group) V1beta3() v1beta3.Interface {\n\treturn v1beta3.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":67,"to":70}} {"id":100025543,"name":"NewFlowSchemaInformer","signature":"func NewFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1alpha1/flowschema.go","code":"// NewFlowSchemaInformer constructs a new informer for FlowSchema type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredFlowSchemaInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025544,"name":"NewFilteredFlowSchemaInformer","signature":"func NewFilteredFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1alpha1/flowschema.go","code":"// NewFilteredFlowSchemaInformer constructs a new informer for FlowSchema type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.FlowcontrolV1alpha1().FlowSchemas().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.FlowcontrolV1alpha1().FlowSchemas().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026flowcontrolv1alpha1.FlowSchema{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025545,"name":"defaultInformer","signature":"func (f *flowSchemaInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1alpha1/flowschema.go","code":"func (f *flowSchemaInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredFlowSchemaInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025546,"name":"Informer","signature":"func (f *flowSchemaInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1alpha1/flowschema.go","code":"func (f *flowSchemaInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026flowcontrolv1alpha1.FlowSchema{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025547,"name":"Lister","signature":"func (f *flowSchemaInformer) Lister() v1alpha1.FlowSchemaLister","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1alpha1/flowschema.go","code":"func (f *flowSchemaInformer) Lister() v1alpha1.FlowSchemaLister {\n\treturn v1alpha1.NewFlowSchemaLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025548,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1alpha1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":39,"to":42}} {"id":100025549,"name":"FlowSchemas","signature":"func (v *version) FlowSchemas() FlowSchemaInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1alpha1/interface.go","code":"// FlowSchemas returns a FlowSchemaInformer.\nfunc (v *version) FlowSchemas() FlowSchemaInformer {\n\treturn \u0026flowSchemaInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":44,"to":47}} {"id":100025550,"name":"PriorityLevelConfigurations","signature":"func (v *version) PriorityLevelConfigurations() PriorityLevelConfigurationInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1alpha1/interface.go","code":"// PriorityLevelConfigurations returns a PriorityLevelConfigurationInformer.\nfunc (v *version) PriorityLevelConfigurations() PriorityLevelConfigurationInformer {\n\treturn \u0026priorityLevelConfigurationInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":49,"to":52}} {"id":100025551,"name":"NewPriorityLevelConfigurationInformer","signature":"func NewPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// NewPriorityLevelConfigurationInformer constructs a new informer for PriorityLevelConfiguration type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredPriorityLevelConfigurationInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025552,"name":"NewFilteredPriorityLevelConfigurationInformer","signature":"func NewFilteredPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// NewFilteredPriorityLevelConfigurationInformer constructs a new informer for PriorityLevelConfiguration type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.FlowcontrolV1alpha1().PriorityLevelConfigurations().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.FlowcontrolV1alpha1().PriorityLevelConfigurations().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026flowcontrolv1alpha1.PriorityLevelConfiguration{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025553,"name":"defaultInformer","signature":"func (f *priorityLevelConfigurationInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"func (f *priorityLevelConfigurationInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredPriorityLevelConfigurationInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025554,"name":"Informer","signature":"func (f *priorityLevelConfigurationInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"func (f *priorityLevelConfigurationInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026flowcontrolv1alpha1.PriorityLevelConfiguration{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025555,"name":"Lister","signature":"func (f *priorityLevelConfigurationInformer) Lister() v1alpha1.PriorityLevelConfigurationLister","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"func (f *priorityLevelConfigurationInformer) Lister() v1alpha1.PriorityLevelConfigurationLister {\n\treturn v1alpha1.NewPriorityLevelConfigurationLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025556,"name":"NewFlowSchemaInformer","signature":"func NewFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta1/flowschema.go","code":"// NewFlowSchemaInformer constructs a new informer for FlowSchema type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredFlowSchemaInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025557,"name":"NewFilteredFlowSchemaInformer","signature":"func NewFilteredFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta1/flowschema.go","code":"// NewFilteredFlowSchemaInformer constructs a new informer for FlowSchema type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.FlowcontrolV1beta1().FlowSchemas().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.FlowcontrolV1beta1().FlowSchemas().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026flowcontrolv1beta1.FlowSchema{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025558,"name":"defaultInformer","signature":"func (f *flowSchemaInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta1/flowschema.go","code":"func (f *flowSchemaInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredFlowSchemaInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025559,"name":"Informer","signature":"func (f *flowSchemaInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta1/flowschema.go","code":"func (f *flowSchemaInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026flowcontrolv1beta1.FlowSchema{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025560,"name":"Lister","signature":"func (f *flowSchemaInformer) Lister() v1beta1.FlowSchemaLister","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta1/flowschema.go","code":"func (f *flowSchemaInformer) Lister() v1beta1.FlowSchemaLister {\n\treturn v1beta1.NewFlowSchemaLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025561,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":39,"to":42}} {"id":100025562,"name":"FlowSchemas","signature":"func (v *version) FlowSchemas() FlowSchemaInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta1/interface.go","code":"// FlowSchemas returns a FlowSchemaInformer.\nfunc (v *version) FlowSchemas() FlowSchemaInformer {\n\treturn \u0026flowSchemaInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":44,"to":47}} {"id":100025563,"name":"PriorityLevelConfigurations","signature":"func (v *version) PriorityLevelConfigurations() PriorityLevelConfigurationInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta1/interface.go","code":"// PriorityLevelConfigurations returns a PriorityLevelConfigurationInformer.\nfunc (v *version) PriorityLevelConfigurations() PriorityLevelConfigurationInformer {\n\treturn \u0026priorityLevelConfigurationInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":49,"to":52}} {"id":100025564,"name":"NewPriorityLevelConfigurationInformer","signature":"func NewPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// NewPriorityLevelConfigurationInformer constructs a new informer for PriorityLevelConfiguration type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredPriorityLevelConfigurationInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025565,"name":"NewFilteredPriorityLevelConfigurationInformer","signature":"func NewFilteredPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// NewFilteredPriorityLevelConfigurationInformer constructs a new informer for PriorityLevelConfiguration type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.FlowcontrolV1beta1().PriorityLevelConfigurations().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.FlowcontrolV1beta1().PriorityLevelConfigurations().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026flowcontrolv1beta1.PriorityLevelConfiguration{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025566,"name":"defaultInformer","signature":"func (f *priorityLevelConfigurationInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"func (f *priorityLevelConfigurationInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredPriorityLevelConfigurationInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025567,"name":"Informer","signature":"func (f *priorityLevelConfigurationInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"func (f *priorityLevelConfigurationInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026flowcontrolv1beta1.PriorityLevelConfiguration{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025568,"name":"Lister","signature":"func (f *priorityLevelConfigurationInformer) Lister() v1beta1.PriorityLevelConfigurationLister","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"func (f *priorityLevelConfigurationInformer) Lister() v1beta1.PriorityLevelConfigurationLister {\n\treturn v1beta1.NewPriorityLevelConfigurationLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025569,"name":"NewFlowSchemaInformer","signature":"func NewFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta2/flowschema.go","code":"// NewFlowSchemaInformer constructs a new informer for FlowSchema type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredFlowSchemaInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025570,"name":"NewFilteredFlowSchemaInformer","signature":"func NewFilteredFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta2/flowschema.go","code":"// NewFilteredFlowSchemaInformer constructs a new informer for FlowSchema type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.FlowcontrolV1beta2().FlowSchemas().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.FlowcontrolV1beta2().FlowSchemas().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026flowcontrolv1beta2.FlowSchema{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025571,"name":"defaultInformer","signature":"func (f *flowSchemaInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta2/flowschema.go","code":"func (f *flowSchemaInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredFlowSchemaInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025572,"name":"Informer","signature":"func (f *flowSchemaInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta2/flowschema.go","code":"func (f *flowSchemaInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026flowcontrolv1beta2.FlowSchema{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025573,"name":"Lister","signature":"func (f *flowSchemaInformer) Lister() v1beta2.FlowSchemaLister","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta2/flowschema.go","code":"func (f *flowSchemaInformer) Lister() v1beta2.FlowSchemaLister {\n\treturn v1beta2.NewFlowSchemaLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025574,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta2/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":39,"to":42}} {"id":100025575,"name":"FlowSchemas","signature":"func (v *version) FlowSchemas() FlowSchemaInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta2/interface.go","code":"// FlowSchemas returns a FlowSchemaInformer.\nfunc (v *version) FlowSchemas() FlowSchemaInformer {\n\treturn \u0026flowSchemaInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":44,"to":47}} {"id":100025576,"name":"PriorityLevelConfigurations","signature":"func (v *version) PriorityLevelConfigurations() PriorityLevelConfigurationInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta2/interface.go","code":"// PriorityLevelConfigurations returns a PriorityLevelConfigurationInformer.\nfunc (v *version) PriorityLevelConfigurations() PriorityLevelConfigurationInformer {\n\treturn \u0026priorityLevelConfigurationInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":49,"to":52}} {"id":100025577,"name":"NewPriorityLevelConfigurationInformer","signature":"func NewPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// NewPriorityLevelConfigurationInformer constructs a new informer for PriorityLevelConfiguration type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredPriorityLevelConfigurationInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025578,"name":"NewFilteredPriorityLevelConfigurationInformer","signature":"func NewFilteredPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// NewFilteredPriorityLevelConfigurationInformer constructs a new informer for PriorityLevelConfiguration type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.FlowcontrolV1beta2().PriorityLevelConfigurations().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.FlowcontrolV1beta2().PriorityLevelConfigurations().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026flowcontrolv1beta2.PriorityLevelConfiguration{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025579,"name":"defaultInformer","signature":"func (f *priorityLevelConfigurationInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"func (f *priorityLevelConfigurationInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredPriorityLevelConfigurationInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025580,"name":"Informer","signature":"func (f *priorityLevelConfigurationInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"func (f *priorityLevelConfigurationInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026flowcontrolv1beta2.PriorityLevelConfiguration{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025581,"name":"Lister","signature":"func (f *priorityLevelConfigurationInformer) Lister() v1beta2.PriorityLevelConfigurationLister","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"func (f *priorityLevelConfigurationInformer) Lister() v1beta2.PriorityLevelConfigurationLister {\n\treturn v1beta2.NewPriorityLevelConfigurationLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025582,"name":"NewFlowSchemaInformer","signature":"func NewFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta3/flowschema.go","code":"// NewFlowSchemaInformer constructs a new informer for FlowSchema type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredFlowSchemaInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025583,"name":"NewFilteredFlowSchemaInformer","signature":"func NewFilteredFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta3/flowschema.go","code":"// NewFilteredFlowSchemaInformer constructs a new informer for FlowSchema type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredFlowSchemaInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.FlowcontrolV1beta3().FlowSchemas().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.FlowcontrolV1beta3().FlowSchemas().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026flowcontrolv1beta3.FlowSchema{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025584,"name":"defaultInformer","signature":"func (f *flowSchemaInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta3/flowschema.go","code":"func (f *flowSchemaInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredFlowSchemaInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025585,"name":"Informer","signature":"func (f *flowSchemaInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta3/flowschema.go","code":"func (f *flowSchemaInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026flowcontrolv1beta3.FlowSchema{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025586,"name":"Lister","signature":"func (f *flowSchemaInformer) Lister() v1beta3.FlowSchemaLister","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta3/flowschema.go","code":"func (f *flowSchemaInformer) Lister() v1beta3.FlowSchemaLister {\n\treturn v1beta3.NewFlowSchemaLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025587,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta3/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":39,"to":42}} {"id":100025588,"name":"FlowSchemas","signature":"func (v *version) FlowSchemas() FlowSchemaInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta3/interface.go","code":"// FlowSchemas returns a FlowSchemaInformer.\nfunc (v *version) FlowSchemas() FlowSchemaInformer {\n\treturn \u0026flowSchemaInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":44,"to":47}} {"id":100025589,"name":"PriorityLevelConfigurations","signature":"func (v *version) PriorityLevelConfigurations() PriorityLevelConfigurationInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta3/interface.go","code":"// PriorityLevelConfigurations returns a PriorityLevelConfigurationInformer.\nfunc (v *version) PriorityLevelConfigurations() PriorityLevelConfigurationInformer {\n\treturn \u0026priorityLevelConfigurationInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":49,"to":52}} {"id":100025590,"name":"NewPriorityLevelConfigurationInformer","signature":"func NewPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// NewPriorityLevelConfigurationInformer constructs a new informer for PriorityLevelConfiguration type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredPriorityLevelConfigurationInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025591,"name":"NewFilteredPriorityLevelConfigurationInformer","signature":"func NewFilteredPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// NewFilteredPriorityLevelConfigurationInformer constructs a new informer for PriorityLevelConfiguration type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredPriorityLevelConfigurationInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.FlowcontrolV1beta3().PriorityLevelConfigurations().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.FlowcontrolV1beta3().PriorityLevelConfigurations().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026flowcontrolv1beta3.PriorityLevelConfiguration{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025592,"name":"defaultInformer","signature":"func (f *priorityLevelConfigurationInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"func (f *priorityLevelConfigurationInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredPriorityLevelConfigurationInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025593,"name":"Informer","signature":"func (f *priorityLevelConfigurationInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"func (f *priorityLevelConfigurationInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026flowcontrolv1beta3.PriorityLevelConfiguration{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025594,"name":"Lister","signature":"func (f *priorityLevelConfigurationInformer) Lister() v1beta3.PriorityLevelConfigurationLister","file":"staging/src/k8s.io/client-go/informers/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"func (f *priorityLevelConfigurationInformer) Lister() v1beta3.PriorityLevelConfigurationLister {\n\treturn v1beta3.NewPriorityLevelConfigurationLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025595,"name":"Informer","signature":"func (f *genericInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/generic.go","code":"// Informer returns the SharedIndexInformer.\nfunc (f *genericInformer) Informer() cache.SharedIndexInformer {\n\treturn f.informer\n}","line":{"from":86,"to":89}} {"id":100025596,"name":"Lister","signature":"func (f *genericInformer) Lister() cache.GenericLister","file":"staging/src/k8s.io/client-go/informers/generic.go","code":"// Lister returns the GenericLister.\nfunc (f *genericInformer) Lister() cache.GenericLister {\n\treturn cache.NewGenericLister(f.Informer().GetIndexer(), f.resource)\n}","line":{"from":91,"to":94}} {"id":100025597,"name":"ForResource","signature":"func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error)","file":"staging/src/k8s.io/client-go/informers/generic.go","code":"// ForResource gives generic access to a shared informer of the matching type\n// TODO extend this to unknown resources with a client pool\nfunc (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) {\n\tswitch resource {\n\t// Group=admissionregistration.k8s.io, Version=v1\n\tcase v1.SchemeGroupVersion.WithResource(\"mutatingwebhookconfigurations\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Admissionregistration().V1().MutatingWebhookConfigurations().Informer()}, nil\n\tcase v1.SchemeGroupVersion.WithResource(\"validatingwebhookconfigurations\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Admissionregistration().V1().ValidatingWebhookConfigurations().Informer()}, nil\n\n\t\t// Group=admissionregistration.k8s.io, Version=v1alpha1\n\tcase v1alpha1.SchemeGroupVersion.WithResource(\"validatingadmissionpolicies\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Admissionregistration().V1alpha1().ValidatingAdmissionPolicies().Informer()}, nil\n\tcase v1alpha1.SchemeGroupVersion.WithResource(\"validatingadmissionpolicybindings\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Admissionregistration().V1alpha1().ValidatingAdmissionPolicyBindings().Informer()}, nil\n\n\t\t// Group=admissionregistration.k8s.io, Version=v1beta1\n\tcase v1beta1.SchemeGroupVersion.WithResource(\"mutatingwebhookconfigurations\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Admissionregistration().V1beta1().MutatingWebhookConfigurations().Informer()}, nil\n\tcase v1beta1.SchemeGroupVersion.WithResource(\"validatingwebhookconfigurations\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Admissionregistration().V1beta1().ValidatingWebhookConfigurations().Informer()}, nil\n\n\t\t// Group=apps, Version=v1\n\tcase appsv1.SchemeGroupVersion.WithResource(\"controllerrevisions\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Apps().V1().ControllerRevisions().Informer()}, nil\n\tcase appsv1.SchemeGroupVersion.WithResource(\"daemonsets\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Apps().V1().DaemonSets().Informer()}, nil\n\tcase appsv1.SchemeGroupVersion.WithResource(\"deployments\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Apps().V1().Deployments().Informer()}, nil\n\tcase appsv1.SchemeGroupVersion.WithResource(\"replicasets\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Apps().V1().ReplicaSets().Informer()}, nil\n\tcase appsv1.SchemeGroupVersion.WithResource(\"statefulsets\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Apps().V1().StatefulSets().Informer()}, nil\n\n\t\t// Group=apps, Version=v1beta1\n\tcase appsv1beta1.SchemeGroupVersion.WithResource(\"controllerrevisions\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Apps().V1beta1().ControllerRevisions().Informer()}, nil\n\tcase appsv1beta1.SchemeGroupVersion.WithResource(\"deployments\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Apps().V1beta1().Deployments().Informer()}, nil\n\tcase appsv1beta1.SchemeGroupVersion.WithResource(\"statefulsets\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Apps().V1beta1().StatefulSets().Informer()}, nil\n\n\t\t// Group=apps, Version=v1beta2\n\tcase v1beta2.SchemeGroupVersion.WithResource(\"controllerrevisions\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Apps().V1beta2().ControllerRevisions().Informer()}, nil\n\tcase v1beta2.SchemeGroupVersion.WithResource(\"daemonsets\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Apps().V1beta2().DaemonSets().Informer()}, nil\n\tcase v1beta2.SchemeGroupVersion.WithResource(\"deployments\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Apps().V1beta2().Deployments().Informer()}, nil\n\tcase v1beta2.SchemeGroupVersion.WithResource(\"replicasets\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Apps().V1beta2().ReplicaSets().Informer()}, nil\n\tcase v1beta2.SchemeGroupVersion.WithResource(\"statefulsets\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Apps().V1beta2().StatefulSets().Informer()}, nil\n\n\t\t// Group=autoscaling, Version=v1\n\tcase autoscalingv1.SchemeGroupVersion.WithResource(\"horizontalpodautoscalers\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Autoscaling().V1().HorizontalPodAutoscalers().Informer()}, nil\n\n\t\t// Group=autoscaling, Version=v2\n\tcase v2.SchemeGroupVersion.WithResource(\"horizontalpodautoscalers\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Autoscaling().V2().HorizontalPodAutoscalers().Informer()}, nil\n\n\t\t// Group=autoscaling, Version=v2beta1\n\tcase v2beta1.SchemeGroupVersion.WithResource(\"horizontalpodautoscalers\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Autoscaling().V2beta1().HorizontalPodAutoscalers().Informer()}, nil\n\n\t\t// Group=autoscaling, Version=v2beta2\n\tcase v2beta2.SchemeGroupVersion.WithResource(\"horizontalpodautoscalers\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Autoscaling().V2beta2().HorizontalPodAutoscalers().Informer()}, nil\n\n\t\t// Group=batch, Version=v1\n\tcase batchv1.SchemeGroupVersion.WithResource(\"cronjobs\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Batch().V1().CronJobs().Informer()}, nil\n\tcase batchv1.SchemeGroupVersion.WithResource(\"jobs\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Batch().V1().Jobs().Informer()}, nil\n\n\t\t// Group=batch, Version=v1beta1\n\tcase batchv1beta1.SchemeGroupVersion.WithResource(\"cronjobs\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Batch().V1beta1().CronJobs().Informer()}, nil\n\n\t\t// Group=certificates.k8s.io, Version=v1\n\tcase certificatesv1.SchemeGroupVersion.WithResource(\"certificatesigningrequests\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Certificates().V1().CertificateSigningRequests().Informer()}, nil\n\n\t\t// Group=certificates.k8s.io, Version=v1alpha1\n\tcase certificatesv1alpha1.SchemeGroupVersion.WithResource(\"clustertrustbundles\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Certificates().V1alpha1().ClusterTrustBundles().Informer()}, nil\n\n\t\t// Group=certificates.k8s.io, Version=v1beta1\n\tcase certificatesv1beta1.SchemeGroupVersion.WithResource(\"certificatesigningrequests\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Certificates().V1beta1().CertificateSigningRequests().Informer()}, nil\n\n\t\t// Group=coordination.k8s.io, Version=v1\n\tcase coordinationv1.SchemeGroupVersion.WithResource(\"leases\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Coordination().V1().Leases().Informer()}, nil\n\n\t\t// Group=coordination.k8s.io, Version=v1beta1\n\tcase coordinationv1beta1.SchemeGroupVersion.WithResource(\"leases\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Coordination().V1beta1().Leases().Informer()}, nil\n\n\t\t// Group=core, Version=v1\n\tcase corev1.SchemeGroupVersion.WithResource(\"componentstatuses\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Core().V1().ComponentStatuses().Informer()}, nil\n\tcase corev1.SchemeGroupVersion.WithResource(\"configmaps\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Core().V1().ConfigMaps().Informer()}, nil\n\tcase corev1.SchemeGroupVersion.WithResource(\"endpoints\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Core().V1().Endpoints().Informer()}, nil\n\tcase corev1.SchemeGroupVersion.WithResource(\"events\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Core().V1().Events().Informer()}, nil\n\tcase corev1.SchemeGroupVersion.WithResource(\"limitranges\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Core().V1().LimitRanges().Informer()}, nil\n\tcase corev1.SchemeGroupVersion.WithResource(\"namespaces\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Core().V1().Namespaces().Informer()}, nil\n\tcase corev1.SchemeGroupVersion.WithResource(\"nodes\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Core().V1().Nodes().Informer()}, nil\n\tcase corev1.SchemeGroupVersion.WithResource(\"persistentvolumes\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Core().V1().PersistentVolumes().Informer()}, nil\n\tcase corev1.SchemeGroupVersion.WithResource(\"persistentvolumeclaims\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Core().V1().PersistentVolumeClaims().Informer()}, nil\n\tcase corev1.SchemeGroupVersion.WithResource(\"pods\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Core().V1().Pods().Informer()}, nil\n\tcase corev1.SchemeGroupVersion.WithResource(\"podtemplates\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Core().V1().PodTemplates().Informer()}, nil\n\tcase corev1.SchemeGroupVersion.WithResource(\"replicationcontrollers\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Core().V1().ReplicationControllers().Informer()}, nil\n\tcase corev1.SchemeGroupVersion.WithResource(\"resourcequotas\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Core().V1().ResourceQuotas().Informer()}, nil\n\tcase corev1.SchemeGroupVersion.WithResource(\"secrets\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Core().V1().Secrets().Informer()}, nil\n\tcase corev1.SchemeGroupVersion.WithResource(\"services\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Core().V1().Services().Informer()}, nil\n\tcase corev1.SchemeGroupVersion.WithResource(\"serviceaccounts\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Core().V1().ServiceAccounts().Informer()}, nil\n\n\t\t// Group=discovery.k8s.io, Version=v1\n\tcase discoveryv1.SchemeGroupVersion.WithResource(\"endpointslices\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Discovery().V1().EndpointSlices().Informer()}, nil\n\n\t\t// Group=discovery.k8s.io, Version=v1beta1\n\tcase discoveryv1beta1.SchemeGroupVersion.WithResource(\"endpointslices\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Discovery().V1beta1().EndpointSlices().Informer()}, nil\n\n\t\t// Group=events.k8s.io, Version=v1\n\tcase eventsv1.SchemeGroupVersion.WithResource(\"events\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Events().V1().Events().Informer()}, nil\n\n\t\t// Group=events.k8s.io, Version=v1beta1\n\tcase eventsv1beta1.SchemeGroupVersion.WithResource(\"events\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Events().V1beta1().Events().Informer()}, nil\n\n\t\t// Group=extensions, Version=v1beta1\n\tcase extensionsv1beta1.SchemeGroupVersion.WithResource(\"daemonsets\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Extensions().V1beta1().DaemonSets().Informer()}, nil\n\tcase extensionsv1beta1.SchemeGroupVersion.WithResource(\"deployments\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Extensions().V1beta1().Deployments().Informer()}, nil\n\tcase extensionsv1beta1.SchemeGroupVersion.WithResource(\"ingresses\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Extensions().V1beta1().Ingresses().Informer()}, nil\n\tcase extensionsv1beta1.SchemeGroupVersion.WithResource(\"networkpolicies\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Extensions().V1beta1().NetworkPolicies().Informer()}, nil\n\tcase extensionsv1beta1.SchemeGroupVersion.WithResource(\"replicasets\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Extensions().V1beta1().ReplicaSets().Informer()}, nil\n\n\t\t// Group=flowcontrol.apiserver.k8s.io, Version=v1alpha1\n\tcase flowcontrolv1alpha1.SchemeGroupVersion.WithResource(\"flowschemas\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Flowcontrol().V1alpha1().FlowSchemas().Informer()}, nil\n\tcase flowcontrolv1alpha1.SchemeGroupVersion.WithResource(\"prioritylevelconfigurations\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Flowcontrol().V1alpha1().PriorityLevelConfigurations().Informer()}, nil\n\n\t\t// Group=flowcontrol.apiserver.k8s.io, Version=v1beta1\n\tcase flowcontrolv1beta1.SchemeGroupVersion.WithResource(\"flowschemas\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Flowcontrol().V1beta1().FlowSchemas().Informer()}, nil\n\tcase flowcontrolv1beta1.SchemeGroupVersion.WithResource(\"prioritylevelconfigurations\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Flowcontrol().V1beta1().PriorityLevelConfigurations().Informer()}, nil\n\n\t\t// Group=flowcontrol.apiserver.k8s.io, Version=v1beta2\n\tcase flowcontrolv1beta2.SchemeGroupVersion.WithResource(\"flowschemas\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Flowcontrol().V1beta2().FlowSchemas().Informer()}, nil\n\tcase flowcontrolv1beta2.SchemeGroupVersion.WithResource(\"prioritylevelconfigurations\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Flowcontrol().V1beta2().PriorityLevelConfigurations().Informer()}, nil\n\n\t\t// Group=flowcontrol.apiserver.k8s.io, Version=v1beta3\n\tcase v1beta3.SchemeGroupVersion.WithResource(\"flowschemas\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Flowcontrol().V1beta3().FlowSchemas().Informer()}, nil\n\tcase v1beta3.SchemeGroupVersion.WithResource(\"prioritylevelconfigurations\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Flowcontrol().V1beta3().PriorityLevelConfigurations().Informer()}, nil\n\n\t\t// Group=internal.apiserver.k8s.io, Version=v1alpha1\n\tcase apiserverinternalv1alpha1.SchemeGroupVersion.WithResource(\"storageversions\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Internal().V1alpha1().StorageVersions().Informer()}, nil\n\n\t\t// Group=networking.k8s.io, Version=v1\n\tcase networkingv1.SchemeGroupVersion.WithResource(\"ingresses\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Networking().V1().Ingresses().Informer()}, nil\n\tcase networkingv1.SchemeGroupVersion.WithResource(\"ingressclasses\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Networking().V1().IngressClasses().Informer()}, nil\n\tcase networkingv1.SchemeGroupVersion.WithResource(\"networkpolicies\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Networking().V1().NetworkPolicies().Informer()}, nil\n\n\t\t// Group=networking.k8s.io, Version=v1alpha1\n\tcase networkingv1alpha1.SchemeGroupVersion.WithResource(\"clustercidrs\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Networking().V1alpha1().ClusterCIDRs().Informer()}, nil\n\tcase networkingv1alpha1.SchemeGroupVersion.WithResource(\"ipaddresses\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Networking().V1alpha1().IPAddresses().Informer()}, nil\n\n\t\t// Group=networking.k8s.io, Version=v1beta1\n\tcase networkingv1beta1.SchemeGroupVersion.WithResource(\"ingresses\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Networking().V1beta1().Ingresses().Informer()}, nil\n\tcase networkingv1beta1.SchemeGroupVersion.WithResource(\"ingressclasses\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Networking().V1beta1().IngressClasses().Informer()}, nil\n\n\t\t// Group=node.k8s.io, Version=v1\n\tcase nodev1.SchemeGroupVersion.WithResource(\"runtimeclasses\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Node().V1().RuntimeClasses().Informer()}, nil\n\n\t\t// Group=node.k8s.io, Version=v1alpha1\n\tcase nodev1alpha1.SchemeGroupVersion.WithResource(\"runtimeclasses\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Node().V1alpha1().RuntimeClasses().Informer()}, nil\n\n\t\t// Group=node.k8s.io, Version=v1beta1\n\tcase nodev1beta1.SchemeGroupVersion.WithResource(\"runtimeclasses\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Node().V1beta1().RuntimeClasses().Informer()}, nil\n\n\t\t// Group=policy, Version=v1\n\tcase policyv1.SchemeGroupVersion.WithResource(\"poddisruptionbudgets\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Policy().V1().PodDisruptionBudgets().Informer()}, nil\n\n\t\t// Group=policy, Version=v1beta1\n\tcase policyv1beta1.SchemeGroupVersion.WithResource(\"poddisruptionbudgets\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Policy().V1beta1().PodDisruptionBudgets().Informer()}, nil\n\tcase policyv1beta1.SchemeGroupVersion.WithResource(\"podsecuritypolicies\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Policy().V1beta1().PodSecurityPolicies().Informer()}, nil\n\n\t\t// Group=rbac.authorization.k8s.io, Version=v1\n\tcase rbacv1.SchemeGroupVersion.WithResource(\"clusterroles\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Rbac().V1().ClusterRoles().Informer()}, nil\n\tcase rbacv1.SchemeGroupVersion.WithResource(\"clusterrolebindings\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Rbac().V1().ClusterRoleBindings().Informer()}, nil\n\tcase rbacv1.SchemeGroupVersion.WithResource(\"roles\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Rbac().V1().Roles().Informer()}, nil\n\tcase rbacv1.SchemeGroupVersion.WithResource(\"rolebindings\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Rbac().V1().RoleBindings().Informer()}, nil\n\n\t\t// Group=rbac.authorization.k8s.io, Version=v1alpha1\n\tcase rbacv1alpha1.SchemeGroupVersion.WithResource(\"clusterroles\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Rbac().V1alpha1().ClusterRoles().Informer()}, nil\n\tcase rbacv1alpha1.SchemeGroupVersion.WithResource(\"clusterrolebindings\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Rbac().V1alpha1().ClusterRoleBindings().Informer()}, nil\n\tcase rbacv1alpha1.SchemeGroupVersion.WithResource(\"roles\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Rbac().V1alpha1().Roles().Informer()}, nil\n\tcase rbacv1alpha1.SchemeGroupVersion.WithResource(\"rolebindings\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Rbac().V1alpha1().RoleBindings().Informer()}, nil\n\n\t\t// Group=rbac.authorization.k8s.io, Version=v1beta1\n\tcase rbacv1beta1.SchemeGroupVersion.WithResource(\"clusterroles\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Rbac().V1beta1().ClusterRoles().Informer()}, nil\n\tcase rbacv1beta1.SchemeGroupVersion.WithResource(\"clusterrolebindings\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Rbac().V1beta1().ClusterRoleBindings().Informer()}, nil\n\tcase rbacv1beta1.SchemeGroupVersion.WithResource(\"roles\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Rbac().V1beta1().Roles().Informer()}, nil\n\tcase rbacv1beta1.SchemeGroupVersion.WithResource(\"rolebindings\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Rbac().V1beta1().RoleBindings().Informer()}, nil\n\n\t\t// Group=resource.k8s.io, Version=v1alpha2\n\tcase v1alpha2.SchemeGroupVersion.WithResource(\"podschedulingcontexts\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Resource().V1alpha2().PodSchedulingContexts().Informer()}, nil\n\tcase v1alpha2.SchemeGroupVersion.WithResource(\"resourceclaims\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Resource().V1alpha2().ResourceClaims().Informer()}, nil\n\tcase v1alpha2.SchemeGroupVersion.WithResource(\"resourceclaimtemplates\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Resource().V1alpha2().ResourceClaimTemplates().Informer()}, nil\n\tcase v1alpha2.SchemeGroupVersion.WithResource(\"resourceclasses\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Resource().V1alpha2().ResourceClasses().Informer()}, nil\n\n\t\t// Group=scheduling.k8s.io, Version=v1\n\tcase schedulingv1.SchemeGroupVersion.WithResource(\"priorityclasses\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Scheduling().V1().PriorityClasses().Informer()}, nil\n\n\t\t// Group=scheduling.k8s.io, Version=v1alpha1\n\tcase schedulingv1alpha1.SchemeGroupVersion.WithResource(\"priorityclasses\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Scheduling().V1alpha1().PriorityClasses().Informer()}, nil\n\n\t\t// Group=scheduling.k8s.io, Version=v1beta1\n\tcase schedulingv1beta1.SchemeGroupVersion.WithResource(\"priorityclasses\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Scheduling().V1beta1().PriorityClasses().Informer()}, nil\n\n\t\t// Group=storage.k8s.io, Version=v1\n\tcase storagev1.SchemeGroupVersion.WithResource(\"csidrivers\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Storage().V1().CSIDrivers().Informer()}, nil\n\tcase storagev1.SchemeGroupVersion.WithResource(\"csinodes\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Storage().V1().CSINodes().Informer()}, nil\n\tcase storagev1.SchemeGroupVersion.WithResource(\"csistoragecapacities\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Storage().V1().CSIStorageCapacities().Informer()}, nil\n\tcase storagev1.SchemeGroupVersion.WithResource(\"storageclasses\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Storage().V1().StorageClasses().Informer()}, nil\n\tcase storagev1.SchemeGroupVersion.WithResource(\"volumeattachments\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Storage().V1().VolumeAttachments().Informer()}, nil\n\n\t\t// Group=storage.k8s.io, Version=v1alpha1\n\tcase storagev1alpha1.SchemeGroupVersion.WithResource(\"csistoragecapacities\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Storage().V1alpha1().CSIStorageCapacities().Informer()}, nil\n\tcase storagev1alpha1.SchemeGroupVersion.WithResource(\"volumeattachments\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Storage().V1alpha1().VolumeAttachments().Informer()}, nil\n\n\t\t// Group=storage.k8s.io, Version=v1beta1\n\tcase storagev1beta1.SchemeGroupVersion.WithResource(\"csidrivers\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Storage().V1beta1().CSIDrivers().Informer()}, nil\n\tcase storagev1beta1.SchemeGroupVersion.WithResource(\"csinodes\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Storage().V1beta1().CSINodes().Informer()}, nil\n\tcase storagev1beta1.SchemeGroupVersion.WithResource(\"csistoragecapacities\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Storage().V1beta1().CSIStorageCapacities().Informer()}, nil\n\tcase storagev1beta1.SchemeGroupVersion.WithResource(\"storageclasses\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Storage().V1beta1().StorageClasses().Informer()}, nil\n\tcase storagev1beta1.SchemeGroupVersion.WithResource(\"volumeattachments\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Storage().V1beta1().VolumeAttachments().Informer()}, nil\n\n\t}\n\n\treturn nil, fmt.Errorf(\"no informer found for %v\", resource)\n}","line":{"from":96,"to":413}} {"id":100025598,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/networking/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":44,"to":47}} {"id":100025599,"name":"V1","signature":"func (g *group) V1() v1.Interface","file":"staging/src/k8s.io/client-go/informers/networking/interface.go","code":"// V1 returns a new v1.Interface.\nfunc (g *group) V1() v1.Interface {\n\treturn v1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":49,"to":52}} {"id":100025600,"name":"V1alpha1","signature":"func (g *group) V1alpha1() v1alpha1.Interface","file":"staging/src/k8s.io/client-go/informers/networking/interface.go","code":"// V1alpha1 returns a new v1alpha1.Interface.\nfunc (g *group) V1alpha1() v1alpha1.Interface {\n\treturn v1alpha1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":54,"to":57}} {"id":100025601,"name":"V1beta1","signature":"func (g *group) V1beta1() v1beta1.Interface","file":"staging/src/k8s.io/client-go/informers/networking/interface.go","code":"// V1beta1 returns a new v1beta1.Interface.\nfunc (g *group) V1beta1() v1beta1.Interface {\n\treturn v1beta1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":59,"to":62}} {"id":100025602,"name":"NewIngressInformer","signature":"func NewIngressInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1/ingress.go","code":"// NewIngressInformer constructs a new informer for Ingress type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewIngressInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredIngressInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025603,"name":"NewFilteredIngressInformer","signature":"func NewFilteredIngressInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1/ingress.go","code":"// NewFilteredIngressInformer constructs a new informer for Ingress type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredIngressInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.NetworkingV1().Ingresses(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.NetworkingV1().Ingresses(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026networkingv1.Ingress{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025604,"name":"defaultInformer","signature":"func (f *ingressInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1/ingress.go","code":"func (f *ingressInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredIngressInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025605,"name":"Informer","signature":"func (f *ingressInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1/ingress.go","code":"func (f *ingressInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026networkingv1.Ingress{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025606,"name":"Lister","signature":"func (f *ingressInformer) Lister() v1.IngressLister","file":"staging/src/k8s.io/client-go/informers/networking/v1/ingress.go","code":"func (f *ingressInformer) Lister() v1.IngressLister {\n\treturn v1.NewIngressLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025607,"name":"NewIngressClassInformer","signature":"func NewIngressClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1/ingressclass.go","code":"// NewIngressClassInformer constructs a new informer for IngressClass type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewIngressClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredIngressClassInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025608,"name":"NewFilteredIngressClassInformer","signature":"func NewFilteredIngressClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1/ingressclass.go","code":"// NewFilteredIngressClassInformer constructs a new informer for IngressClass type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredIngressClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.NetworkingV1().IngressClasses().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.NetworkingV1().IngressClasses().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026networkingv1.IngressClass{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025609,"name":"defaultInformer","signature":"func (f *ingressClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1/ingressclass.go","code":"func (f *ingressClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredIngressClassInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025610,"name":"Informer","signature":"func (f *ingressClassInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1/ingressclass.go","code":"func (f *ingressClassInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026networkingv1.IngressClass{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025611,"name":"Lister","signature":"func (f *ingressClassInformer) Lister() v1.IngressClassLister","file":"staging/src/k8s.io/client-go/informers/networking/v1/ingressclass.go","code":"func (f *ingressClassInformer) Lister() v1.IngressClassLister {\n\treturn v1.NewIngressClassLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025612,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/networking/v1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":41,"to":44}} {"id":100025613,"name":"Ingresses","signature":"func (v *version) Ingresses() IngressInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1/interface.go","code":"// Ingresses returns a IngressInformer.\nfunc (v *version) Ingresses() IngressInformer {\n\treturn \u0026ingressInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":46,"to":49}} {"id":100025614,"name":"IngressClasses","signature":"func (v *version) IngressClasses() IngressClassInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1/interface.go","code":"// IngressClasses returns a IngressClassInformer.\nfunc (v *version) IngressClasses() IngressClassInformer {\n\treturn \u0026ingressClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":51,"to":54}} {"id":100025615,"name":"NetworkPolicies","signature":"func (v *version) NetworkPolicies() NetworkPolicyInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1/interface.go","code":"// NetworkPolicies returns a NetworkPolicyInformer.\nfunc (v *version) NetworkPolicies() NetworkPolicyInformer {\n\treturn \u0026networkPolicyInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":56,"to":59}} {"id":100025616,"name":"NewNetworkPolicyInformer","signature":"func NewNetworkPolicyInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1/networkpolicy.go","code":"// NewNetworkPolicyInformer constructs a new informer for NetworkPolicy type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewNetworkPolicyInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredNetworkPolicyInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025617,"name":"NewFilteredNetworkPolicyInformer","signature":"func NewFilteredNetworkPolicyInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1/networkpolicy.go","code":"// NewFilteredNetworkPolicyInformer constructs a new informer for NetworkPolicy type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredNetworkPolicyInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.NetworkingV1().NetworkPolicies(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.NetworkingV1().NetworkPolicies(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026networkingv1.NetworkPolicy{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025618,"name":"defaultInformer","signature":"func (f *networkPolicyInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1/networkpolicy.go","code":"func (f *networkPolicyInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredNetworkPolicyInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025619,"name":"Informer","signature":"func (f *networkPolicyInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1/networkpolicy.go","code":"func (f *networkPolicyInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026networkingv1.NetworkPolicy{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025620,"name":"Lister","signature":"func (f *networkPolicyInformer) Lister() v1.NetworkPolicyLister","file":"staging/src/k8s.io/client-go/informers/networking/v1/networkpolicy.go","code":"func (f *networkPolicyInformer) Lister() v1.NetworkPolicyLister {\n\treturn v1.NewNetworkPolicyLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025621,"name":"NewClusterCIDRInformer","signature":"func NewClusterCIDRInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1alpha1/clustercidr.go","code":"// NewClusterCIDRInformer constructs a new informer for ClusterCIDR type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewClusterCIDRInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredClusterCIDRInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025622,"name":"NewFilteredClusterCIDRInformer","signature":"func NewFilteredClusterCIDRInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1alpha1/clustercidr.go","code":"// NewFilteredClusterCIDRInformer constructs a new informer for ClusterCIDR type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredClusterCIDRInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.NetworkingV1alpha1().ClusterCIDRs().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.NetworkingV1alpha1().ClusterCIDRs().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026networkingv1alpha1.ClusterCIDR{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025623,"name":"defaultInformer","signature":"func (f *clusterCIDRInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1alpha1/clustercidr.go","code":"func (f *clusterCIDRInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredClusterCIDRInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025624,"name":"Informer","signature":"func (f *clusterCIDRInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1alpha1/clustercidr.go","code":"func (f *clusterCIDRInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026networkingv1alpha1.ClusterCIDR{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025625,"name":"Lister","signature":"func (f *clusterCIDRInformer) Lister() v1alpha1.ClusterCIDRLister","file":"staging/src/k8s.io/client-go/informers/networking/v1alpha1/clustercidr.go","code":"func (f *clusterCIDRInformer) Lister() v1alpha1.ClusterCIDRLister {\n\treturn v1alpha1.NewClusterCIDRLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025626,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/networking/v1alpha1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":39,"to":42}} {"id":100025627,"name":"ClusterCIDRs","signature":"func (v *version) ClusterCIDRs() ClusterCIDRInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1alpha1/interface.go","code":"// ClusterCIDRs returns a ClusterCIDRInformer.\nfunc (v *version) ClusterCIDRs() ClusterCIDRInformer {\n\treturn \u0026clusterCIDRInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":44,"to":47}} {"id":100025628,"name":"IPAddresses","signature":"func (v *version) IPAddresses() IPAddressInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1alpha1/interface.go","code":"// IPAddresses returns a IPAddressInformer.\nfunc (v *version) IPAddresses() IPAddressInformer {\n\treturn \u0026iPAddressInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":49,"to":52}} {"id":100025629,"name":"NewIPAddressInformer","signature":"func NewIPAddressInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1alpha1/ipaddress.go","code":"// NewIPAddressInformer constructs a new informer for IPAddress type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewIPAddressInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredIPAddressInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025630,"name":"NewFilteredIPAddressInformer","signature":"func NewFilteredIPAddressInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1alpha1/ipaddress.go","code":"// NewFilteredIPAddressInformer constructs a new informer for IPAddress type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredIPAddressInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.NetworkingV1alpha1().IPAddresses().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.NetworkingV1alpha1().IPAddresses().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026networkingv1alpha1.IPAddress{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025631,"name":"defaultInformer","signature":"func (f *iPAddressInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1alpha1/ipaddress.go","code":"func (f *iPAddressInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredIPAddressInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025632,"name":"Informer","signature":"func (f *iPAddressInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1alpha1/ipaddress.go","code":"func (f *iPAddressInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026networkingv1alpha1.IPAddress{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025633,"name":"Lister","signature":"func (f *iPAddressInformer) Lister() v1alpha1.IPAddressLister","file":"staging/src/k8s.io/client-go/informers/networking/v1alpha1/ipaddress.go","code":"func (f *iPAddressInformer) Lister() v1alpha1.IPAddressLister {\n\treturn v1alpha1.NewIPAddressLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025634,"name":"NewIngressInformer","signature":"func NewIngressInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1beta1/ingress.go","code":"// NewIngressInformer constructs a new informer for Ingress type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewIngressInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredIngressInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025635,"name":"NewFilteredIngressInformer","signature":"func NewFilteredIngressInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1beta1/ingress.go","code":"// NewFilteredIngressInformer constructs a new informer for Ingress type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredIngressInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.NetworkingV1beta1().Ingresses(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.NetworkingV1beta1().Ingresses(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026networkingv1beta1.Ingress{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025636,"name":"defaultInformer","signature":"func (f *ingressInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1beta1/ingress.go","code":"func (f *ingressInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredIngressInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025637,"name":"Informer","signature":"func (f *ingressInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1beta1/ingress.go","code":"func (f *ingressInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026networkingv1beta1.Ingress{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025638,"name":"Lister","signature":"func (f *ingressInformer) Lister() v1beta1.IngressLister","file":"staging/src/k8s.io/client-go/informers/networking/v1beta1/ingress.go","code":"func (f *ingressInformer) Lister() v1beta1.IngressLister {\n\treturn v1beta1.NewIngressLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025639,"name":"NewIngressClassInformer","signature":"func NewIngressClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1beta1/ingressclass.go","code":"// NewIngressClassInformer constructs a new informer for IngressClass type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewIngressClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredIngressClassInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025640,"name":"NewFilteredIngressClassInformer","signature":"func NewFilteredIngressClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1beta1/ingressclass.go","code":"// NewFilteredIngressClassInformer constructs a new informer for IngressClass type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredIngressClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.NetworkingV1beta1().IngressClasses().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.NetworkingV1beta1().IngressClasses().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026networkingv1beta1.IngressClass{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025641,"name":"defaultInformer","signature":"func (f *ingressClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1beta1/ingressclass.go","code":"func (f *ingressClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredIngressClassInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025642,"name":"Informer","signature":"func (f *ingressClassInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1beta1/ingressclass.go","code":"func (f *ingressClassInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026networkingv1beta1.IngressClass{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025643,"name":"Lister","signature":"func (f *ingressClassInformer) Lister() v1beta1.IngressClassLister","file":"staging/src/k8s.io/client-go/informers/networking/v1beta1/ingressclass.go","code":"func (f *ingressClassInformer) Lister() v1beta1.IngressClassLister {\n\treturn v1beta1.NewIngressClassLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025644,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/networking/v1beta1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":39,"to":42}} {"id":100025645,"name":"Ingresses","signature":"func (v *version) Ingresses() IngressInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1beta1/interface.go","code":"// Ingresses returns a IngressInformer.\nfunc (v *version) Ingresses() IngressInformer {\n\treturn \u0026ingressInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":44,"to":47}} {"id":100025646,"name":"IngressClasses","signature":"func (v *version) IngressClasses() IngressClassInformer","file":"staging/src/k8s.io/client-go/informers/networking/v1beta1/interface.go","code":"// IngressClasses returns a IngressClassInformer.\nfunc (v *version) IngressClasses() IngressClassInformer {\n\treturn \u0026ingressClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":49,"to":52}} {"id":100025647,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/node/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":44,"to":47}} {"id":100025648,"name":"V1","signature":"func (g *group) V1() v1.Interface","file":"staging/src/k8s.io/client-go/informers/node/interface.go","code":"// V1 returns a new v1.Interface.\nfunc (g *group) V1() v1.Interface {\n\treturn v1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":49,"to":52}} {"id":100025649,"name":"V1alpha1","signature":"func (g *group) V1alpha1() v1alpha1.Interface","file":"staging/src/k8s.io/client-go/informers/node/interface.go","code":"// V1alpha1 returns a new v1alpha1.Interface.\nfunc (g *group) V1alpha1() v1alpha1.Interface {\n\treturn v1alpha1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":54,"to":57}} {"id":100025650,"name":"V1beta1","signature":"func (g *group) V1beta1() v1beta1.Interface","file":"staging/src/k8s.io/client-go/informers/node/interface.go","code":"// V1beta1 returns a new v1beta1.Interface.\nfunc (g *group) V1beta1() v1beta1.Interface {\n\treturn v1beta1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":59,"to":62}} {"id":100025651,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/node/v1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":37,"to":40}} {"id":100025652,"name":"RuntimeClasses","signature":"func (v *version) RuntimeClasses() RuntimeClassInformer","file":"staging/src/k8s.io/client-go/informers/node/v1/interface.go","code":"// RuntimeClasses returns a RuntimeClassInformer.\nfunc (v *version) RuntimeClasses() RuntimeClassInformer {\n\treturn \u0026runtimeClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":42,"to":45}} {"id":100025653,"name":"NewRuntimeClassInformer","signature":"func NewRuntimeClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/node/v1/runtimeclass.go","code":"// NewRuntimeClassInformer constructs a new informer for RuntimeClass type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewRuntimeClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredRuntimeClassInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025654,"name":"NewFilteredRuntimeClassInformer","signature":"func NewFilteredRuntimeClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/node/v1/runtimeclass.go","code":"// NewFilteredRuntimeClassInformer constructs a new informer for RuntimeClass type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredRuntimeClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.NodeV1().RuntimeClasses().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.NodeV1().RuntimeClasses().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026nodev1.RuntimeClass{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025655,"name":"defaultInformer","signature":"func (f *runtimeClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/node/v1/runtimeclass.go","code":"func (f *runtimeClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredRuntimeClassInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025656,"name":"Informer","signature":"func (f *runtimeClassInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/node/v1/runtimeclass.go","code":"func (f *runtimeClassInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026nodev1.RuntimeClass{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025657,"name":"Lister","signature":"func (f *runtimeClassInformer) Lister() v1.RuntimeClassLister","file":"staging/src/k8s.io/client-go/informers/node/v1/runtimeclass.go","code":"func (f *runtimeClassInformer) Lister() v1.RuntimeClassLister {\n\treturn v1.NewRuntimeClassLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025658,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/node/v1alpha1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":37,"to":40}} {"id":100025659,"name":"RuntimeClasses","signature":"func (v *version) RuntimeClasses() RuntimeClassInformer","file":"staging/src/k8s.io/client-go/informers/node/v1alpha1/interface.go","code":"// RuntimeClasses returns a RuntimeClassInformer.\nfunc (v *version) RuntimeClasses() RuntimeClassInformer {\n\treturn \u0026runtimeClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":42,"to":45}} {"id":100025660,"name":"NewRuntimeClassInformer","signature":"func NewRuntimeClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/node/v1alpha1/runtimeclass.go","code":"// NewRuntimeClassInformer constructs a new informer for RuntimeClass type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewRuntimeClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredRuntimeClassInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025661,"name":"NewFilteredRuntimeClassInformer","signature":"func NewFilteredRuntimeClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/node/v1alpha1/runtimeclass.go","code":"// NewFilteredRuntimeClassInformer constructs a new informer for RuntimeClass type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredRuntimeClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.NodeV1alpha1().RuntimeClasses().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.NodeV1alpha1().RuntimeClasses().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026nodev1alpha1.RuntimeClass{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025662,"name":"defaultInformer","signature":"func (f *runtimeClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/node/v1alpha1/runtimeclass.go","code":"func (f *runtimeClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredRuntimeClassInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025663,"name":"Informer","signature":"func (f *runtimeClassInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/node/v1alpha1/runtimeclass.go","code":"func (f *runtimeClassInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026nodev1alpha1.RuntimeClass{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025664,"name":"Lister","signature":"func (f *runtimeClassInformer) Lister() v1alpha1.RuntimeClassLister","file":"staging/src/k8s.io/client-go/informers/node/v1alpha1/runtimeclass.go","code":"func (f *runtimeClassInformer) Lister() v1alpha1.RuntimeClassLister {\n\treturn v1alpha1.NewRuntimeClassLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025665,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/node/v1beta1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":37,"to":40}} {"id":100025666,"name":"RuntimeClasses","signature":"func (v *version) RuntimeClasses() RuntimeClassInformer","file":"staging/src/k8s.io/client-go/informers/node/v1beta1/interface.go","code":"// RuntimeClasses returns a RuntimeClassInformer.\nfunc (v *version) RuntimeClasses() RuntimeClassInformer {\n\treturn \u0026runtimeClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":42,"to":45}} {"id":100025667,"name":"NewRuntimeClassInformer","signature":"func NewRuntimeClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/node/v1beta1/runtimeclass.go","code":"// NewRuntimeClassInformer constructs a new informer for RuntimeClass type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewRuntimeClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredRuntimeClassInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025668,"name":"NewFilteredRuntimeClassInformer","signature":"func NewFilteredRuntimeClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/node/v1beta1/runtimeclass.go","code":"// NewFilteredRuntimeClassInformer constructs a new informer for RuntimeClass type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredRuntimeClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.NodeV1beta1().RuntimeClasses().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.NodeV1beta1().RuntimeClasses().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026nodev1beta1.RuntimeClass{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025669,"name":"defaultInformer","signature":"func (f *runtimeClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/node/v1beta1/runtimeclass.go","code":"func (f *runtimeClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredRuntimeClassInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025670,"name":"Informer","signature":"func (f *runtimeClassInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/node/v1beta1/runtimeclass.go","code":"func (f *runtimeClassInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026nodev1beta1.RuntimeClass{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025671,"name":"Lister","signature":"func (f *runtimeClassInformer) Lister() v1beta1.RuntimeClassLister","file":"staging/src/k8s.io/client-go/informers/node/v1beta1/runtimeclass.go","code":"func (f *runtimeClassInformer) Lister() v1beta1.RuntimeClassLister {\n\treturn v1beta1.NewRuntimeClassLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025672,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/policy/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":41,"to":44}} {"id":100025673,"name":"V1","signature":"func (g *group) V1() v1.Interface","file":"staging/src/k8s.io/client-go/informers/policy/interface.go","code":"// V1 returns a new v1.Interface.\nfunc (g *group) V1() v1.Interface {\n\treturn v1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":46,"to":49}} {"id":100025674,"name":"V1beta1","signature":"func (g *group) V1beta1() v1beta1.Interface","file":"staging/src/k8s.io/client-go/informers/policy/interface.go","code":"// V1beta1 returns a new v1beta1.Interface.\nfunc (g *group) V1beta1() v1beta1.Interface {\n\treturn v1beta1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":51,"to":54}} {"id":100025675,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/policy/v1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":37,"to":40}} {"id":100025676,"name":"PodDisruptionBudgets","signature":"func (v *version) PodDisruptionBudgets() PodDisruptionBudgetInformer","file":"staging/src/k8s.io/client-go/informers/policy/v1/interface.go","code":"// PodDisruptionBudgets returns a PodDisruptionBudgetInformer.\nfunc (v *version) PodDisruptionBudgets() PodDisruptionBudgetInformer {\n\treturn \u0026podDisruptionBudgetInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":42,"to":45}} {"id":100025677,"name":"NewPodDisruptionBudgetInformer","signature":"func NewPodDisruptionBudgetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/policy/v1/poddisruptionbudget.go","code":"// NewPodDisruptionBudgetInformer constructs a new informer for PodDisruptionBudget type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewPodDisruptionBudgetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredPodDisruptionBudgetInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025678,"name":"NewFilteredPodDisruptionBudgetInformer","signature":"func NewFilteredPodDisruptionBudgetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/policy/v1/poddisruptionbudget.go","code":"// NewFilteredPodDisruptionBudgetInformer constructs a new informer for PodDisruptionBudget type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredPodDisruptionBudgetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.PolicyV1().PodDisruptionBudgets(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.PolicyV1().PodDisruptionBudgets(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026policyv1.PodDisruptionBudget{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025679,"name":"defaultInformer","signature":"func (f *podDisruptionBudgetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/policy/v1/poddisruptionbudget.go","code":"func (f *podDisruptionBudgetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredPodDisruptionBudgetInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025680,"name":"Informer","signature":"func (f *podDisruptionBudgetInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/policy/v1/poddisruptionbudget.go","code":"func (f *podDisruptionBudgetInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026policyv1.PodDisruptionBudget{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025681,"name":"Lister","signature":"func (f *podDisruptionBudgetInformer) Lister() v1.PodDisruptionBudgetLister","file":"staging/src/k8s.io/client-go/informers/policy/v1/poddisruptionbudget.go","code":"func (f *podDisruptionBudgetInformer) Lister() v1.PodDisruptionBudgetLister {\n\treturn v1.NewPodDisruptionBudgetLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025682,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/policy/v1beta1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":39,"to":42}} {"id":100025683,"name":"PodDisruptionBudgets","signature":"func (v *version) PodDisruptionBudgets() PodDisruptionBudgetInformer","file":"staging/src/k8s.io/client-go/informers/policy/v1beta1/interface.go","code":"// PodDisruptionBudgets returns a PodDisruptionBudgetInformer.\nfunc (v *version) PodDisruptionBudgets() PodDisruptionBudgetInformer {\n\treturn \u0026podDisruptionBudgetInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":44,"to":47}} {"id":100025684,"name":"PodSecurityPolicies","signature":"func (v *version) PodSecurityPolicies() PodSecurityPolicyInformer","file":"staging/src/k8s.io/client-go/informers/policy/v1beta1/interface.go","code":"// PodSecurityPolicies returns a PodSecurityPolicyInformer.\nfunc (v *version) PodSecurityPolicies() PodSecurityPolicyInformer {\n\treturn \u0026podSecurityPolicyInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":49,"to":52}} {"id":100025685,"name":"NewPodDisruptionBudgetInformer","signature":"func NewPodDisruptionBudgetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/policy/v1beta1/poddisruptionbudget.go","code":"// NewPodDisruptionBudgetInformer constructs a new informer for PodDisruptionBudget type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewPodDisruptionBudgetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredPodDisruptionBudgetInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025686,"name":"NewFilteredPodDisruptionBudgetInformer","signature":"func NewFilteredPodDisruptionBudgetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/policy/v1beta1/poddisruptionbudget.go","code":"// NewFilteredPodDisruptionBudgetInformer constructs a new informer for PodDisruptionBudget type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredPodDisruptionBudgetInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.PolicyV1beta1().PodDisruptionBudgets(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.PolicyV1beta1().PodDisruptionBudgets(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026policyv1beta1.PodDisruptionBudget{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025687,"name":"defaultInformer","signature":"func (f *podDisruptionBudgetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/policy/v1beta1/poddisruptionbudget.go","code":"func (f *podDisruptionBudgetInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredPodDisruptionBudgetInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025688,"name":"Informer","signature":"func (f *podDisruptionBudgetInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/policy/v1beta1/poddisruptionbudget.go","code":"func (f *podDisruptionBudgetInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026policyv1beta1.PodDisruptionBudget{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025689,"name":"Lister","signature":"func (f *podDisruptionBudgetInformer) Lister() v1beta1.PodDisruptionBudgetLister","file":"staging/src/k8s.io/client-go/informers/policy/v1beta1/poddisruptionbudget.go","code":"func (f *podDisruptionBudgetInformer) Lister() v1beta1.PodDisruptionBudgetLister {\n\treturn v1beta1.NewPodDisruptionBudgetLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025690,"name":"NewPodSecurityPolicyInformer","signature":"func NewPodSecurityPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/policy/v1beta1/podsecuritypolicy.go","code":"// NewPodSecurityPolicyInformer constructs a new informer for PodSecurityPolicy type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewPodSecurityPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredPodSecurityPolicyInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025691,"name":"NewFilteredPodSecurityPolicyInformer","signature":"func NewFilteredPodSecurityPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/policy/v1beta1/podsecuritypolicy.go","code":"// NewFilteredPodSecurityPolicyInformer constructs a new informer for PodSecurityPolicy type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredPodSecurityPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.PolicyV1beta1().PodSecurityPolicies().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.PolicyV1beta1().PodSecurityPolicies().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026policyv1beta1.PodSecurityPolicy{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025692,"name":"defaultInformer","signature":"func (f *podSecurityPolicyInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/policy/v1beta1/podsecuritypolicy.go","code":"func (f *podSecurityPolicyInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredPodSecurityPolicyInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025693,"name":"Informer","signature":"func (f *podSecurityPolicyInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/policy/v1beta1/podsecuritypolicy.go","code":"func (f *podSecurityPolicyInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026policyv1beta1.PodSecurityPolicy{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025694,"name":"Lister","signature":"func (f *podSecurityPolicyInformer) Lister() v1beta1.PodSecurityPolicyLister","file":"staging/src/k8s.io/client-go/informers/policy/v1beta1/podsecuritypolicy.go","code":"func (f *podSecurityPolicyInformer) Lister() v1beta1.PodSecurityPolicyLister {\n\treturn v1beta1.NewPodSecurityPolicyLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025695,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/rbac/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":44,"to":47}} {"id":100025696,"name":"V1","signature":"func (g *group) V1() v1.Interface","file":"staging/src/k8s.io/client-go/informers/rbac/interface.go","code":"// V1 returns a new v1.Interface.\nfunc (g *group) V1() v1.Interface {\n\treturn v1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":49,"to":52}} {"id":100025697,"name":"V1alpha1","signature":"func (g *group) V1alpha1() v1alpha1.Interface","file":"staging/src/k8s.io/client-go/informers/rbac/interface.go","code":"// V1alpha1 returns a new v1alpha1.Interface.\nfunc (g *group) V1alpha1() v1alpha1.Interface {\n\treturn v1alpha1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":54,"to":57}} {"id":100025698,"name":"V1beta1","signature":"func (g *group) V1beta1() v1beta1.Interface","file":"staging/src/k8s.io/client-go/informers/rbac/interface.go","code":"// V1beta1 returns a new v1beta1.Interface.\nfunc (g *group) V1beta1() v1beta1.Interface {\n\treturn v1beta1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":59,"to":62}} {"id":100025699,"name":"NewClusterRoleInformer","signature":"func NewClusterRoleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1/clusterrole.go","code":"// NewClusterRoleInformer constructs a new informer for ClusterRole type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewClusterRoleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredClusterRoleInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025700,"name":"NewFilteredClusterRoleInformer","signature":"func NewFilteredClusterRoleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1/clusterrole.go","code":"// NewFilteredClusterRoleInformer constructs a new informer for ClusterRole type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredClusterRoleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.RbacV1().ClusterRoles().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.RbacV1().ClusterRoles().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026rbacv1.ClusterRole{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025701,"name":"defaultInformer","signature":"func (f *clusterRoleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1/clusterrole.go","code":"func (f *clusterRoleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredClusterRoleInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025702,"name":"Informer","signature":"func (f *clusterRoleInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1/clusterrole.go","code":"func (f *clusterRoleInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026rbacv1.ClusterRole{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025703,"name":"Lister","signature":"func (f *clusterRoleInformer) Lister() v1.ClusterRoleLister","file":"staging/src/k8s.io/client-go/informers/rbac/v1/clusterrole.go","code":"func (f *clusterRoleInformer) Lister() v1.ClusterRoleLister {\n\treturn v1.NewClusterRoleLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025704,"name":"NewClusterRoleBindingInformer","signature":"func NewClusterRoleBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1/clusterrolebinding.go","code":"// NewClusterRoleBindingInformer constructs a new informer for ClusterRoleBinding type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewClusterRoleBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredClusterRoleBindingInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025705,"name":"NewFilteredClusterRoleBindingInformer","signature":"func NewFilteredClusterRoleBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1/clusterrolebinding.go","code":"// NewFilteredClusterRoleBindingInformer constructs a new informer for ClusterRoleBinding type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredClusterRoleBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.RbacV1().ClusterRoleBindings().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.RbacV1().ClusterRoleBindings().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026rbacv1.ClusterRoleBinding{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025706,"name":"defaultInformer","signature":"func (f *clusterRoleBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1/clusterrolebinding.go","code":"func (f *clusterRoleBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredClusterRoleBindingInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025707,"name":"Informer","signature":"func (f *clusterRoleBindingInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1/clusterrolebinding.go","code":"func (f *clusterRoleBindingInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026rbacv1.ClusterRoleBinding{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025708,"name":"Lister","signature":"func (f *clusterRoleBindingInformer) Lister() v1.ClusterRoleBindingLister","file":"staging/src/k8s.io/client-go/informers/rbac/v1/clusterrolebinding.go","code":"func (f *clusterRoleBindingInformer) Lister() v1.ClusterRoleBindingLister {\n\treturn v1.NewClusterRoleBindingLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025709,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/rbac/v1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":43,"to":46}} {"id":100025710,"name":"ClusterRoles","signature":"func (v *version) ClusterRoles() ClusterRoleInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1/interface.go","code":"// ClusterRoles returns a ClusterRoleInformer.\nfunc (v *version) ClusterRoles() ClusterRoleInformer {\n\treturn \u0026clusterRoleInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":48,"to":51}} {"id":100025711,"name":"ClusterRoleBindings","signature":"func (v *version) ClusterRoleBindings() ClusterRoleBindingInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1/interface.go","code":"// ClusterRoleBindings returns a ClusterRoleBindingInformer.\nfunc (v *version) ClusterRoleBindings() ClusterRoleBindingInformer {\n\treturn \u0026clusterRoleBindingInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":53,"to":56}} {"id":100025712,"name":"Roles","signature":"func (v *version) Roles() RoleInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1/interface.go","code":"// Roles returns a RoleInformer.\nfunc (v *version) Roles() RoleInformer {\n\treturn \u0026roleInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":58,"to":61}} {"id":100025713,"name":"RoleBindings","signature":"func (v *version) RoleBindings() RoleBindingInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1/interface.go","code":"// RoleBindings returns a RoleBindingInformer.\nfunc (v *version) RoleBindings() RoleBindingInformer {\n\treturn \u0026roleBindingInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":63,"to":66}} {"id":100025714,"name":"NewRoleInformer","signature":"func NewRoleInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1/role.go","code":"// NewRoleInformer constructs a new informer for Role type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewRoleInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredRoleInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025715,"name":"NewFilteredRoleInformer","signature":"func NewFilteredRoleInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1/role.go","code":"// NewFilteredRoleInformer constructs a new informer for Role type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredRoleInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.RbacV1().Roles(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.RbacV1().Roles(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026rbacv1.Role{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025716,"name":"defaultInformer","signature":"func (f *roleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1/role.go","code":"func (f *roleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredRoleInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025717,"name":"Informer","signature":"func (f *roleInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1/role.go","code":"func (f *roleInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026rbacv1.Role{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025718,"name":"Lister","signature":"func (f *roleInformer) Lister() v1.RoleLister","file":"staging/src/k8s.io/client-go/informers/rbac/v1/role.go","code":"func (f *roleInformer) Lister() v1.RoleLister {\n\treturn v1.NewRoleLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025719,"name":"NewRoleBindingInformer","signature":"func NewRoleBindingInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1/rolebinding.go","code":"// NewRoleBindingInformer constructs a new informer for RoleBinding type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewRoleBindingInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredRoleBindingInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025720,"name":"NewFilteredRoleBindingInformer","signature":"func NewFilteredRoleBindingInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1/rolebinding.go","code":"// NewFilteredRoleBindingInformer constructs a new informer for RoleBinding type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredRoleBindingInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.RbacV1().RoleBindings(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.RbacV1().RoleBindings(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026rbacv1.RoleBinding{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025721,"name":"defaultInformer","signature":"func (f *roleBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1/rolebinding.go","code":"func (f *roleBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredRoleBindingInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025722,"name":"Informer","signature":"func (f *roleBindingInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1/rolebinding.go","code":"func (f *roleBindingInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026rbacv1.RoleBinding{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025723,"name":"Lister","signature":"func (f *roleBindingInformer) Lister() v1.RoleBindingLister","file":"staging/src/k8s.io/client-go/informers/rbac/v1/rolebinding.go","code":"func (f *roleBindingInformer) Lister() v1.RoleBindingLister {\n\treturn v1.NewRoleBindingLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025724,"name":"NewClusterRoleInformer","signature":"func NewClusterRoleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1alpha1/clusterrole.go","code":"// NewClusterRoleInformer constructs a new informer for ClusterRole type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewClusterRoleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredClusterRoleInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025725,"name":"NewFilteredClusterRoleInformer","signature":"func NewFilteredClusterRoleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1alpha1/clusterrole.go","code":"// NewFilteredClusterRoleInformer constructs a new informer for ClusterRole type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredClusterRoleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.RbacV1alpha1().ClusterRoles().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.RbacV1alpha1().ClusterRoles().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026rbacv1alpha1.ClusterRole{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025726,"name":"defaultInformer","signature":"func (f *clusterRoleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1alpha1/clusterrole.go","code":"func (f *clusterRoleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredClusterRoleInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025727,"name":"Informer","signature":"func (f *clusterRoleInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1alpha1/clusterrole.go","code":"func (f *clusterRoleInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026rbacv1alpha1.ClusterRole{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025728,"name":"Lister","signature":"func (f *clusterRoleInformer) Lister() v1alpha1.ClusterRoleLister","file":"staging/src/k8s.io/client-go/informers/rbac/v1alpha1/clusterrole.go","code":"func (f *clusterRoleInformer) Lister() v1alpha1.ClusterRoleLister {\n\treturn v1alpha1.NewClusterRoleLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025729,"name":"NewClusterRoleBindingInformer","signature":"func NewClusterRoleBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1alpha1/clusterrolebinding.go","code":"// NewClusterRoleBindingInformer constructs a new informer for ClusterRoleBinding type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewClusterRoleBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredClusterRoleBindingInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025730,"name":"NewFilteredClusterRoleBindingInformer","signature":"func NewFilteredClusterRoleBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1alpha1/clusterrolebinding.go","code":"// NewFilteredClusterRoleBindingInformer constructs a new informer for ClusterRoleBinding type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredClusterRoleBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.RbacV1alpha1().ClusterRoleBindings().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.RbacV1alpha1().ClusterRoleBindings().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026rbacv1alpha1.ClusterRoleBinding{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025731,"name":"defaultInformer","signature":"func (f *clusterRoleBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1alpha1/clusterrolebinding.go","code":"func (f *clusterRoleBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredClusterRoleBindingInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025732,"name":"Informer","signature":"func (f *clusterRoleBindingInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1alpha1/clusterrolebinding.go","code":"func (f *clusterRoleBindingInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026rbacv1alpha1.ClusterRoleBinding{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025733,"name":"Lister","signature":"func (f *clusterRoleBindingInformer) Lister() v1alpha1.ClusterRoleBindingLister","file":"staging/src/k8s.io/client-go/informers/rbac/v1alpha1/clusterrolebinding.go","code":"func (f *clusterRoleBindingInformer) Lister() v1alpha1.ClusterRoleBindingLister {\n\treturn v1alpha1.NewClusterRoleBindingLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025734,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/rbac/v1alpha1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":43,"to":46}} {"id":100025735,"name":"ClusterRoles","signature":"func (v *version) ClusterRoles() ClusterRoleInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1alpha1/interface.go","code":"// ClusterRoles returns a ClusterRoleInformer.\nfunc (v *version) ClusterRoles() ClusterRoleInformer {\n\treturn \u0026clusterRoleInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":48,"to":51}} {"id":100025736,"name":"ClusterRoleBindings","signature":"func (v *version) ClusterRoleBindings() ClusterRoleBindingInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1alpha1/interface.go","code":"// ClusterRoleBindings returns a ClusterRoleBindingInformer.\nfunc (v *version) ClusterRoleBindings() ClusterRoleBindingInformer {\n\treturn \u0026clusterRoleBindingInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":53,"to":56}} {"id":100025737,"name":"Roles","signature":"func (v *version) Roles() RoleInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1alpha1/interface.go","code":"// Roles returns a RoleInformer.\nfunc (v *version) Roles() RoleInformer {\n\treturn \u0026roleInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":58,"to":61}} {"id":100025738,"name":"RoleBindings","signature":"func (v *version) RoleBindings() RoleBindingInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1alpha1/interface.go","code":"// RoleBindings returns a RoleBindingInformer.\nfunc (v *version) RoleBindings() RoleBindingInformer {\n\treturn \u0026roleBindingInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":63,"to":66}} {"id":100025739,"name":"NewRoleInformer","signature":"func NewRoleInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1alpha1/role.go","code":"// NewRoleInformer constructs a new informer for Role type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewRoleInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredRoleInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025740,"name":"NewFilteredRoleInformer","signature":"func NewFilteredRoleInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1alpha1/role.go","code":"// NewFilteredRoleInformer constructs a new informer for Role type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredRoleInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.RbacV1alpha1().Roles(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.RbacV1alpha1().Roles(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026rbacv1alpha1.Role{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025741,"name":"defaultInformer","signature":"func (f *roleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1alpha1/role.go","code":"func (f *roleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredRoleInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025742,"name":"Informer","signature":"func (f *roleInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1alpha1/role.go","code":"func (f *roleInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026rbacv1alpha1.Role{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025743,"name":"Lister","signature":"func (f *roleInformer) Lister() v1alpha1.RoleLister","file":"staging/src/k8s.io/client-go/informers/rbac/v1alpha1/role.go","code":"func (f *roleInformer) Lister() v1alpha1.RoleLister {\n\treturn v1alpha1.NewRoleLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025744,"name":"NewRoleBindingInformer","signature":"func NewRoleBindingInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1alpha1/rolebinding.go","code":"// NewRoleBindingInformer constructs a new informer for RoleBinding type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewRoleBindingInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredRoleBindingInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025745,"name":"NewFilteredRoleBindingInformer","signature":"func NewFilteredRoleBindingInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1alpha1/rolebinding.go","code":"// NewFilteredRoleBindingInformer constructs a new informer for RoleBinding type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredRoleBindingInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.RbacV1alpha1().RoleBindings(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.RbacV1alpha1().RoleBindings(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026rbacv1alpha1.RoleBinding{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025746,"name":"defaultInformer","signature":"func (f *roleBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1alpha1/rolebinding.go","code":"func (f *roleBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredRoleBindingInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025747,"name":"Informer","signature":"func (f *roleBindingInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1alpha1/rolebinding.go","code":"func (f *roleBindingInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026rbacv1alpha1.RoleBinding{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025748,"name":"Lister","signature":"func (f *roleBindingInformer) Lister() v1alpha1.RoleBindingLister","file":"staging/src/k8s.io/client-go/informers/rbac/v1alpha1/rolebinding.go","code":"func (f *roleBindingInformer) Lister() v1alpha1.RoleBindingLister {\n\treturn v1alpha1.NewRoleBindingLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025749,"name":"NewClusterRoleInformer","signature":"func NewClusterRoleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1beta1/clusterrole.go","code":"// NewClusterRoleInformer constructs a new informer for ClusterRole type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewClusterRoleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredClusterRoleInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025750,"name":"NewFilteredClusterRoleInformer","signature":"func NewFilteredClusterRoleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1beta1/clusterrole.go","code":"// NewFilteredClusterRoleInformer constructs a new informer for ClusterRole type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredClusterRoleInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.RbacV1beta1().ClusterRoles().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.RbacV1beta1().ClusterRoles().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026rbacv1beta1.ClusterRole{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025751,"name":"defaultInformer","signature":"func (f *clusterRoleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1beta1/clusterrole.go","code":"func (f *clusterRoleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredClusterRoleInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025752,"name":"Informer","signature":"func (f *clusterRoleInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1beta1/clusterrole.go","code":"func (f *clusterRoleInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026rbacv1beta1.ClusterRole{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025753,"name":"Lister","signature":"func (f *clusterRoleInformer) Lister() v1beta1.ClusterRoleLister","file":"staging/src/k8s.io/client-go/informers/rbac/v1beta1/clusterrole.go","code":"func (f *clusterRoleInformer) Lister() v1beta1.ClusterRoleLister {\n\treturn v1beta1.NewClusterRoleLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025754,"name":"NewClusterRoleBindingInformer","signature":"func NewClusterRoleBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1beta1/clusterrolebinding.go","code":"// NewClusterRoleBindingInformer constructs a new informer for ClusterRoleBinding type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewClusterRoleBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredClusterRoleBindingInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025755,"name":"NewFilteredClusterRoleBindingInformer","signature":"func NewFilteredClusterRoleBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1beta1/clusterrolebinding.go","code":"// NewFilteredClusterRoleBindingInformer constructs a new informer for ClusterRoleBinding type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredClusterRoleBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.RbacV1beta1().ClusterRoleBindings().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.RbacV1beta1().ClusterRoleBindings().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026rbacv1beta1.ClusterRoleBinding{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025756,"name":"defaultInformer","signature":"func (f *clusterRoleBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1beta1/clusterrolebinding.go","code":"func (f *clusterRoleBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredClusterRoleBindingInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025757,"name":"Informer","signature":"func (f *clusterRoleBindingInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1beta1/clusterrolebinding.go","code":"func (f *clusterRoleBindingInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026rbacv1beta1.ClusterRoleBinding{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025758,"name":"Lister","signature":"func (f *clusterRoleBindingInformer) Lister() v1beta1.ClusterRoleBindingLister","file":"staging/src/k8s.io/client-go/informers/rbac/v1beta1/clusterrolebinding.go","code":"func (f *clusterRoleBindingInformer) Lister() v1beta1.ClusterRoleBindingLister {\n\treturn v1beta1.NewClusterRoleBindingLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025759,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/rbac/v1beta1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":43,"to":46}} {"id":100025760,"name":"ClusterRoles","signature":"func (v *version) ClusterRoles() ClusterRoleInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1beta1/interface.go","code":"// ClusterRoles returns a ClusterRoleInformer.\nfunc (v *version) ClusterRoles() ClusterRoleInformer {\n\treturn \u0026clusterRoleInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":48,"to":51}} {"id":100025761,"name":"ClusterRoleBindings","signature":"func (v *version) ClusterRoleBindings() ClusterRoleBindingInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1beta1/interface.go","code":"// ClusterRoleBindings returns a ClusterRoleBindingInformer.\nfunc (v *version) ClusterRoleBindings() ClusterRoleBindingInformer {\n\treturn \u0026clusterRoleBindingInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":53,"to":56}} {"id":100025762,"name":"Roles","signature":"func (v *version) Roles() RoleInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1beta1/interface.go","code":"// Roles returns a RoleInformer.\nfunc (v *version) Roles() RoleInformer {\n\treturn \u0026roleInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":58,"to":61}} {"id":100025763,"name":"RoleBindings","signature":"func (v *version) RoleBindings() RoleBindingInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1beta1/interface.go","code":"// RoleBindings returns a RoleBindingInformer.\nfunc (v *version) RoleBindings() RoleBindingInformer {\n\treturn \u0026roleBindingInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":63,"to":66}} {"id":100025764,"name":"NewRoleInformer","signature":"func NewRoleInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1beta1/role.go","code":"// NewRoleInformer constructs a new informer for Role type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewRoleInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredRoleInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025765,"name":"NewFilteredRoleInformer","signature":"func NewFilteredRoleInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1beta1/role.go","code":"// NewFilteredRoleInformer constructs a new informer for Role type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredRoleInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.RbacV1beta1().Roles(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.RbacV1beta1().Roles(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026rbacv1beta1.Role{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025766,"name":"defaultInformer","signature":"func (f *roleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1beta1/role.go","code":"func (f *roleInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredRoleInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025767,"name":"Informer","signature":"func (f *roleInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1beta1/role.go","code":"func (f *roleInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026rbacv1beta1.Role{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025768,"name":"Lister","signature":"func (f *roleInformer) Lister() v1beta1.RoleLister","file":"staging/src/k8s.io/client-go/informers/rbac/v1beta1/role.go","code":"func (f *roleInformer) Lister() v1beta1.RoleLister {\n\treturn v1beta1.NewRoleLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025769,"name":"NewRoleBindingInformer","signature":"func NewRoleBindingInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1beta1/rolebinding.go","code":"// NewRoleBindingInformer constructs a new informer for RoleBinding type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewRoleBindingInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredRoleBindingInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025770,"name":"NewFilteredRoleBindingInformer","signature":"func NewFilteredRoleBindingInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1beta1/rolebinding.go","code":"// NewFilteredRoleBindingInformer constructs a new informer for RoleBinding type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredRoleBindingInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.RbacV1beta1().RoleBindings(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.RbacV1beta1().RoleBindings(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026rbacv1beta1.RoleBinding{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025771,"name":"defaultInformer","signature":"func (f *roleBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1beta1/rolebinding.go","code":"func (f *roleBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredRoleBindingInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025772,"name":"Informer","signature":"func (f *roleBindingInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/rbac/v1beta1/rolebinding.go","code":"func (f *roleBindingInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026rbacv1beta1.RoleBinding{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025773,"name":"Lister","signature":"func (f *roleBindingInformer) Lister() v1beta1.RoleBindingLister","file":"staging/src/k8s.io/client-go/informers/rbac/v1beta1/rolebinding.go","code":"func (f *roleBindingInformer) Lister() v1beta1.RoleBindingLister {\n\treturn v1beta1.NewRoleBindingLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025774,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/resource/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":38,"to":41}} {"id":100025775,"name":"V1alpha2","signature":"func (g *group) V1alpha2() v1alpha2.Interface","file":"staging/src/k8s.io/client-go/informers/resource/interface.go","code":"// V1alpha2 returns a new v1alpha2.Interface.\nfunc (g *group) V1alpha2() v1alpha2.Interface {\n\treturn v1alpha2.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":43,"to":46}} {"id":100025776,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/resource/v1alpha2/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":43,"to":46}} {"id":100025777,"name":"PodSchedulingContexts","signature":"func (v *version) PodSchedulingContexts() PodSchedulingContextInformer","file":"staging/src/k8s.io/client-go/informers/resource/v1alpha2/interface.go","code":"// PodSchedulingContexts returns a PodSchedulingContextInformer.\nfunc (v *version) PodSchedulingContexts() PodSchedulingContextInformer {\n\treturn \u0026podSchedulingContextInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":48,"to":51}} {"id":100025778,"name":"ResourceClaims","signature":"func (v *version) ResourceClaims() ResourceClaimInformer","file":"staging/src/k8s.io/client-go/informers/resource/v1alpha2/interface.go","code":"// ResourceClaims returns a ResourceClaimInformer.\nfunc (v *version) ResourceClaims() ResourceClaimInformer {\n\treturn \u0026resourceClaimInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":53,"to":56}} {"id":100025779,"name":"ResourceClaimTemplates","signature":"func (v *version) ResourceClaimTemplates() ResourceClaimTemplateInformer","file":"staging/src/k8s.io/client-go/informers/resource/v1alpha2/interface.go","code":"// ResourceClaimTemplates returns a ResourceClaimTemplateInformer.\nfunc (v *version) ResourceClaimTemplates() ResourceClaimTemplateInformer {\n\treturn \u0026resourceClaimTemplateInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":58,"to":61}} {"id":100025780,"name":"ResourceClasses","signature":"func (v *version) ResourceClasses() ResourceClassInformer","file":"staging/src/k8s.io/client-go/informers/resource/v1alpha2/interface.go","code":"// ResourceClasses returns a ResourceClassInformer.\nfunc (v *version) ResourceClasses() ResourceClassInformer {\n\treturn \u0026resourceClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":63,"to":66}} {"id":100025781,"name":"NewPodSchedulingContextInformer","signature":"func NewPodSchedulingContextInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/resource/v1alpha2/podschedulingcontext.go","code":"// NewPodSchedulingContextInformer constructs a new informer for PodSchedulingContext type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewPodSchedulingContextInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredPodSchedulingContextInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025782,"name":"NewFilteredPodSchedulingContextInformer","signature":"func NewFilteredPodSchedulingContextInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/resource/v1alpha2/podschedulingcontext.go","code":"// NewFilteredPodSchedulingContextInformer constructs a new informer for PodSchedulingContext type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredPodSchedulingContextInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.ResourceV1alpha2().PodSchedulingContexts(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.ResourceV1alpha2().PodSchedulingContexts(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026resourcev1alpha2.PodSchedulingContext{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025783,"name":"defaultInformer","signature":"func (f *podSchedulingContextInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/resource/v1alpha2/podschedulingcontext.go","code":"func (f *podSchedulingContextInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredPodSchedulingContextInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025784,"name":"Informer","signature":"func (f *podSchedulingContextInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/resource/v1alpha2/podschedulingcontext.go","code":"func (f *podSchedulingContextInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026resourcev1alpha2.PodSchedulingContext{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025785,"name":"Lister","signature":"func (f *podSchedulingContextInformer) Lister() v1alpha2.PodSchedulingContextLister","file":"staging/src/k8s.io/client-go/informers/resource/v1alpha2/podschedulingcontext.go","code":"func (f *podSchedulingContextInformer) Lister() v1alpha2.PodSchedulingContextLister {\n\treturn v1alpha2.NewPodSchedulingContextLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025786,"name":"NewResourceClaimInformer","signature":"func NewResourceClaimInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/resource/v1alpha2/resourceclaim.go","code":"// NewResourceClaimInformer constructs a new informer for ResourceClaim type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewResourceClaimInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredResourceClaimInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025787,"name":"NewFilteredResourceClaimInformer","signature":"func NewFilteredResourceClaimInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/resource/v1alpha2/resourceclaim.go","code":"// NewFilteredResourceClaimInformer constructs a new informer for ResourceClaim type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredResourceClaimInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.ResourceV1alpha2().ResourceClaims(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.ResourceV1alpha2().ResourceClaims(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026resourcev1alpha2.ResourceClaim{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025788,"name":"defaultInformer","signature":"func (f *resourceClaimInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/resource/v1alpha2/resourceclaim.go","code":"func (f *resourceClaimInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredResourceClaimInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025789,"name":"Informer","signature":"func (f *resourceClaimInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/resource/v1alpha2/resourceclaim.go","code":"func (f *resourceClaimInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026resourcev1alpha2.ResourceClaim{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025790,"name":"Lister","signature":"func (f *resourceClaimInformer) Lister() v1alpha2.ResourceClaimLister","file":"staging/src/k8s.io/client-go/informers/resource/v1alpha2/resourceclaim.go","code":"func (f *resourceClaimInformer) Lister() v1alpha2.ResourceClaimLister {\n\treturn v1alpha2.NewResourceClaimLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025791,"name":"NewResourceClaimTemplateInformer","signature":"func NewResourceClaimTemplateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/resource/v1alpha2/resourceclaimtemplate.go","code":"// NewResourceClaimTemplateInformer constructs a new informer for ResourceClaimTemplate type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewResourceClaimTemplateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredResourceClaimTemplateInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025792,"name":"NewFilteredResourceClaimTemplateInformer","signature":"func NewFilteredResourceClaimTemplateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/resource/v1alpha2/resourceclaimtemplate.go","code":"// NewFilteredResourceClaimTemplateInformer constructs a new informer for ResourceClaimTemplate type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredResourceClaimTemplateInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.ResourceV1alpha2().ResourceClaimTemplates(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.ResourceV1alpha2().ResourceClaimTemplates(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026resourcev1alpha2.ResourceClaimTemplate{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025793,"name":"defaultInformer","signature":"func (f *resourceClaimTemplateInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/resource/v1alpha2/resourceclaimtemplate.go","code":"func (f *resourceClaimTemplateInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredResourceClaimTemplateInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025794,"name":"Informer","signature":"func (f *resourceClaimTemplateInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/resource/v1alpha2/resourceclaimtemplate.go","code":"func (f *resourceClaimTemplateInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026resourcev1alpha2.ResourceClaimTemplate{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025795,"name":"Lister","signature":"func (f *resourceClaimTemplateInformer) Lister() v1alpha2.ResourceClaimTemplateLister","file":"staging/src/k8s.io/client-go/informers/resource/v1alpha2/resourceclaimtemplate.go","code":"func (f *resourceClaimTemplateInformer) Lister() v1alpha2.ResourceClaimTemplateLister {\n\treturn v1alpha2.NewResourceClaimTemplateLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025796,"name":"NewResourceClassInformer","signature":"func NewResourceClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/resource/v1alpha2/resourceclass.go","code":"// NewResourceClassInformer constructs a new informer for ResourceClass type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewResourceClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredResourceClassInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025797,"name":"NewFilteredResourceClassInformer","signature":"func NewFilteredResourceClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/resource/v1alpha2/resourceclass.go","code":"// NewFilteredResourceClassInformer constructs a new informer for ResourceClass type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredResourceClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.ResourceV1alpha2().ResourceClasses().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.ResourceV1alpha2().ResourceClasses().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026resourcev1alpha2.ResourceClass{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025798,"name":"defaultInformer","signature":"func (f *resourceClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/resource/v1alpha2/resourceclass.go","code":"func (f *resourceClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredResourceClassInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025799,"name":"Informer","signature":"func (f *resourceClassInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/resource/v1alpha2/resourceclass.go","code":"func (f *resourceClassInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026resourcev1alpha2.ResourceClass{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025800,"name":"Lister","signature":"func (f *resourceClassInformer) Lister() v1alpha2.ResourceClassLister","file":"staging/src/k8s.io/client-go/informers/resource/v1alpha2/resourceclass.go","code":"func (f *resourceClassInformer) Lister() v1alpha2.ResourceClassLister {\n\treturn v1alpha2.NewResourceClassLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025801,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/scheduling/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":44,"to":47}} {"id":100025802,"name":"V1","signature":"func (g *group) V1() v1.Interface","file":"staging/src/k8s.io/client-go/informers/scheduling/interface.go","code":"// V1 returns a new v1.Interface.\nfunc (g *group) V1() v1.Interface {\n\treturn v1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":49,"to":52}} {"id":100025803,"name":"V1alpha1","signature":"func (g *group) V1alpha1() v1alpha1.Interface","file":"staging/src/k8s.io/client-go/informers/scheduling/interface.go","code":"// V1alpha1 returns a new v1alpha1.Interface.\nfunc (g *group) V1alpha1() v1alpha1.Interface {\n\treturn v1alpha1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":54,"to":57}} {"id":100025804,"name":"V1beta1","signature":"func (g *group) V1beta1() v1beta1.Interface","file":"staging/src/k8s.io/client-go/informers/scheduling/interface.go","code":"// V1beta1 returns a new v1beta1.Interface.\nfunc (g *group) V1beta1() v1beta1.Interface {\n\treturn v1beta1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":59,"to":62}} {"id":100025805,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/scheduling/v1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":37,"to":40}} {"id":100025806,"name":"PriorityClasses","signature":"func (v *version) PriorityClasses() PriorityClassInformer","file":"staging/src/k8s.io/client-go/informers/scheduling/v1/interface.go","code":"// PriorityClasses returns a PriorityClassInformer.\nfunc (v *version) PriorityClasses() PriorityClassInformer {\n\treturn \u0026priorityClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":42,"to":45}} {"id":100025807,"name":"NewPriorityClassInformer","signature":"func NewPriorityClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/scheduling/v1/priorityclass.go","code":"// NewPriorityClassInformer constructs a new informer for PriorityClass type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewPriorityClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredPriorityClassInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025808,"name":"NewFilteredPriorityClassInformer","signature":"func NewFilteredPriorityClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/scheduling/v1/priorityclass.go","code":"// NewFilteredPriorityClassInformer constructs a new informer for PriorityClass type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredPriorityClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.SchedulingV1().PriorityClasses().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.SchedulingV1().PriorityClasses().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026schedulingv1.PriorityClass{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025809,"name":"defaultInformer","signature":"func (f *priorityClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/scheduling/v1/priorityclass.go","code":"func (f *priorityClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredPriorityClassInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025810,"name":"Informer","signature":"func (f *priorityClassInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/scheduling/v1/priorityclass.go","code":"func (f *priorityClassInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026schedulingv1.PriorityClass{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025811,"name":"Lister","signature":"func (f *priorityClassInformer) Lister() v1.PriorityClassLister","file":"staging/src/k8s.io/client-go/informers/scheduling/v1/priorityclass.go","code":"func (f *priorityClassInformer) Lister() v1.PriorityClassLister {\n\treturn v1.NewPriorityClassLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025812,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/scheduling/v1alpha1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":37,"to":40}} {"id":100025813,"name":"PriorityClasses","signature":"func (v *version) PriorityClasses() PriorityClassInformer","file":"staging/src/k8s.io/client-go/informers/scheduling/v1alpha1/interface.go","code":"// PriorityClasses returns a PriorityClassInformer.\nfunc (v *version) PriorityClasses() PriorityClassInformer {\n\treturn \u0026priorityClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":42,"to":45}} {"id":100025814,"name":"NewPriorityClassInformer","signature":"func NewPriorityClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/scheduling/v1alpha1/priorityclass.go","code":"// NewPriorityClassInformer constructs a new informer for PriorityClass type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewPriorityClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredPriorityClassInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025815,"name":"NewFilteredPriorityClassInformer","signature":"func NewFilteredPriorityClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/scheduling/v1alpha1/priorityclass.go","code":"// NewFilteredPriorityClassInformer constructs a new informer for PriorityClass type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredPriorityClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.SchedulingV1alpha1().PriorityClasses().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.SchedulingV1alpha1().PriorityClasses().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026schedulingv1alpha1.PriorityClass{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025816,"name":"defaultInformer","signature":"func (f *priorityClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/scheduling/v1alpha1/priorityclass.go","code":"func (f *priorityClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredPriorityClassInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025817,"name":"Informer","signature":"func (f *priorityClassInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/scheduling/v1alpha1/priorityclass.go","code":"func (f *priorityClassInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026schedulingv1alpha1.PriorityClass{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025818,"name":"Lister","signature":"func (f *priorityClassInformer) Lister() v1alpha1.PriorityClassLister","file":"staging/src/k8s.io/client-go/informers/scheduling/v1alpha1/priorityclass.go","code":"func (f *priorityClassInformer) Lister() v1alpha1.PriorityClassLister {\n\treturn v1alpha1.NewPriorityClassLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025819,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/scheduling/v1beta1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":37,"to":40}} {"id":100025820,"name":"PriorityClasses","signature":"func (v *version) PriorityClasses() PriorityClassInformer","file":"staging/src/k8s.io/client-go/informers/scheduling/v1beta1/interface.go","code":"// PriorityClasses returns a PriorityClassInformer.\nfunc (v *version) PriorityClasses() PriorityClassInformer {\n\treturn \u0026priorityClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":42,"to":45}} {"id":100025821,"name":"NewPriorityClassInformer","signature":"func NewPriorityClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/scheduling/v1beta1/priorityclass.go","code":"// NewPriorityClassInformer constructs a new informer for PriorityClass type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewPriorityClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredPriorityClassInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025822,"name":"NewFilteredPriorityClassInformer","signature":"func NewFilteredPriorityClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/scheduling/v1beta1/priorityclass.go","code":"// NewFilteredPriorityClassInformer constructs a new informer for PriorityClass type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredPriorityClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.SchedulingV1beta1().PriorityClasses().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.SchedulingV1beta1().PriorityClasses().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026schedulingv1beta1.PriorityClass{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025823,"name":"defaultInformer","signature":"func (f *priorityClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/scheduling/v1beta1/priorityclass.go","code":"func (f *priorityClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredPriorityClassInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025824,"name":"Informer","signature":"func (f *priorityClassInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/scheduling/v1beta1/priorityclass.go","code":"func (f *priorityClassInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026schedulingv1beta1.PriorityClass{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025825,"name":"Lister","signature":"func (f *priorityClassInformer) Lister() v1beta1.PriorityClassLister","file":"staging/src/k8s.io/client-go/informers/scheduling/v1beta1/priorityclass.go","code":"func (f *priorityClassInformer) Lister() v1beta1.PriorityClassLister {\n\treturn v1beta1.NewPriorityClassLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025826,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/storage/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":44,"to":47}} {"id":100025827,"name":"V1","signature":"func (g *group) V1() v1.Interface","file":"staging/src/k8s.io/client-go/informers/storage/interface.go","code":"// V1 returns a new v1.Interface.\nfunc (g *group) V1() v1.Interface {\n\treturn v1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":49,"to":52}} {"id":100025828,"name":"V1alpha1","signature":"func (g *group) V1alpha1() v1alpha1.Interface","file":"staging/src/k8s.io/client-go/informers/storage/interface.go","code":"// V1alpha1 returns a new v1alpha1.Interface.\nfunc (g *group) V1alpha1() v1alpha1.Interface {\n\treturn v1alpha1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":54,"to":57}} {"id":100025829,"name":"V1beta1","signature":"func (g *group) V1beta1() v1beta1.Interface","file":"staging/src/k8s.io/client-go/informers/storage/interface.go","code":"// V1beta1 returns a new v1beta1.Interface.\nfunc (g *group) V1beta1() v1beta1.Interface {\n\treturn v1beta1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":59,"to":62}} {"id":100025830,"name":"NewCSIDriverInformer","signature":"func NewCSIDriverInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1/csidriver.go","code":"// NewCSIDriverInformer constructs a new informer for CSIDriver type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewCSIDriverInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredCSIDriverInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025831,"name":"NewFilteredCSIDriverInformer","signature":"func NewFilteredCSIDriverInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1/csidriver.go","code":"// NewFilteredCSIDriverInformer constructs a new informer for CSIDriver type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredCSIDriverInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.StorageV1().CSIDrivers().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.StorageV1().CSIDrivers().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026storagev1.CSIDriver{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025832,"name":"defaultInformer","signature":"func (f *cSIDriverInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1/csidriver.go","code":"func (f *cSIDriverInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredCSIDriverInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025833,"name":"Informer","signature":"func (f *cSIDriverInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1/csidriver.go","code":"func (f *cSIDriverInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026storagev1.CSIDriver{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025834,"name":"Lister","signature":"func (f *cSIDriverInformer) Lister() v1.CSIDriverLister","file":"staging/src/k8s.io/client-go/informers/storage/v1/csidriver.go","code":"func (f *cSIDriverInformer) Lister() v1.CSIDriverLister {\n\treturn v1.NewCSIDriverLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025835,"name":"NewCSINodeInformer","signature":"func NewCSINodeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1/csinode.go","code":"// NewCSINodeInformer constructs a new informer for CSINode type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewCSINodeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredCSINodeInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025836,"name":"NewFilteredCSINodeInformer","signature":"func NewFilteredCSINodeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1/csinode.go","code":"// NewFilteredCSINodeInformer constructs a new informer for CSINode type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredCSINodeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.StorageV1().CSINodes().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.StorageV1().CSINodes().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026storagev1.CSINode{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025837,"name":"defaultInformer","signature":"func (f *cSINodeInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1/csinode.go","code":"func (f *cSINodeInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredCSINodeInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025838,"name":"Informer","signature":"func (f *cSINodeInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1/csinode.go","code":"func (f *cSINodeInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026storagev1.CSINode{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025839,"name":"Lister","signature":"func (f *cSINodeInformer) Lister() v1.CSINodeLister","file":"staging/src/k8s.io/client-go/informers/storage/v1/csinode.go","code":"func (f *cSINodeInformer) Lister() v1.CSINodeLister {\n\treturn v1.NewCSINodeLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025840,"name":"NewCSIStorageCapacityInformer","signature":"func NewCSIStorageCapacityInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1/csistoragecapacity.go","code":"// NewCSIStorageCapacityInformer constructs a new informer for CSIStorageCapacity type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewCSIStorageCapacityInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredCSIStorageCapacityInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025841,"name":"NewFilteredCSIStorageCapacityInformer","signature":"func NewFilteredCSIStorageCapacityInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1/csistoragecapacity.go","code":"// NewFilteredCSIStorageCapacityInformer constructs a new informer for CSIStorageCapacity type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredCSIStorageCapacityInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.StorageV1().CSIStorageCapacities(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.StorageV1().CSIStorageCapacities(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026storagev1.CSIStorageCapacity{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025842,"name":"defaultInformer","signature":"func (f *cSIStorageCapacityInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1/csistoragecapacity.go","code":"func (f *cSIStorageCapacityInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredCSIStorageCapacityInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025843,"name":"Informer","signature":"func (f *cSIStorageCapacityInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1/csistoragecapacity.go","code":"func (f *cSIStorageCapacityInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026storagev1.CSIStorageCapacity{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025844,"name":"Lister","signature":"func (f *cSIStorageCapacityInformer) Lister() v1.CSIStorageCapacityLister","file":"staging/src/k8s.io/client-go/informers/storage/v1/csistoragecapacity.go","code":"func (f *cSIStorageCapacityInformer) Lister() v1.CSIStorageCapacityLister {\n\treturn v1.NewCSIStorageCapacityLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025845,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/storage/v1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":45,"to":48}} {"id":100025846,"name":"CSIDrivers","signature":"func (v *version) CSIDrivers() CSIDriverInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1/interface.go","code":"// CSIDrivers returns a CSIDriverInformer.\nfunc (v *version) CSIDrivers() CSIDriverInformer {\n\treturn \u0026cSIDriverInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":50,"to":53}} {"id":100025847,"name":"CSINodes","signature":"func (v *version) CSINodes() CSINodeInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1/interface.go","code":"// CSINodes returns a CSINodeInformer.\nfunc (v *version) CSINodes() CSINodeInformer {\n\treturn \u0026cSINodeInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":55,"to":58}} {"id":100025848,"name":"CSIStorageCapacities","signature":"func (v *version) CSIStorageCapacities() CSIStorageCapacityInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1/interface.go","code":"// CSIStorageCapacities returns a CSIStorageCapacityInformer.\nfunc (v *version) CSIStorageCapacities() CSIStorageCapacityInformer {\n\treturn \u0026cSIStorageCapacityInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":60,"to":63}} {"id":100025849,"name":"StorageClasses","signature":"func (v *version) StorageClasses() StorageClassInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1/interface.go","code":"// StorageClasses returns a StorageClassInformer.\nfunc (v *version) StorageClasses() StorageClassInformer {\n\treturn \u0026storageClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":65,"to":68}} {"id":100025850,"name":"VolumeAttachments","signature":"func (v *version) VolumeAttachments() VolumeAttachmentInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1/interface.go","code":"// VolumeAttachments returns a VolumeAttachmentInformer.\nfunc (v *version) VolumeAttachments() VolumeAttachmentInformer {\n\treturn \u0026volumeAttachmentInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":70,"to":73}} {"id":100025851,"name":"NewStorageClassInformer","signature":"func NewStorageClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1/storageclass.go","code":"// NewStorageClassInformer constructs a new informer for StorageClass type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewStorageClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredStorageClassInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025852,"name":"NewFilteredStorageClassInformer","signature":"func NewFilteredStorageClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1/storageclass.go","code":"// NewFilteredStorageClassInformer constructs a new informer for StorageClass type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredStorageClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.StorageV1().StorageClasses().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.StorageV1().StorageClasses().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026storagev1.StorageClass{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025853,"name":"defaultInformer","signature":"func (f *storageClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1/storageclass.go","code":"func (f *storageClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredStorageClassInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025854,"name":"Informer","signature":"func (f *storageClassInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1/storageclass.go","code":"func (f *storageClassInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026storagev1.StorageClass{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025855,"name":"Lister","signature":"func (f *storageClassInformer) Lister() v1.StorageClassLister","file":"staging/src/k8s.io/client-go/informers/storage/v1/storageclass.go","code":"func (f *storageClassInformer) Lister() v1.StorageClassLister {\n\treturn v1.NewStorageClassLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025856,"name":"NewVolumeAttachmentInformer","signature":"func NewVolumeAttachmentInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1/volumeattachment.go","code":"// NewVolumeAttachmentInformer constructs a new informer for VolumeAttachment type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewVolumeAttachmentInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredVolumeAttachmentInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025857,"name":"NewFilteredVolumeAttachmentInformer","signature":"func NewFilteredVolumeAttachmentInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1/volumeattachment.go","code":"// NewFilteredVolumeAttachmentInformer constructs a new informer for VolumeAttachment type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredVolumeAttachmentInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.StorageV1().VolumeAttachments().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.StorageV1().VolumeAttachments().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026storagev1.VolumeAttachment{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025858,"name":"defaultInformer","signature":"func (f *volumeAttachmentInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1/volumeattachment.go","code":"func (f *volumeAttachmentInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredVolumeAttachmentInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025859,"name":"Informer","signature":"func (f *volumeAttachmentInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1/volumeattachment.go","code":"func (f *volumeAttachmentInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026storagev1.VolumeAttachment{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025860,"name":"Lister","signature":"func (f *volumeAttachmentInformer) Lister() v1.VolumeAttachmentLister","file":"staging/src/k8s.io/client-go/informers/storage/v1/volumeattachment.go","code":"func (f *volumeAttachmentInformer) Lister() v1.VolumeAttachmentLister {\n\treturn v1.NewVolumeAttachmentLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025861,"name":"NewCSIStorageCapacityInformer","signature":"func NewCSIStorageCapacityInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1alpha1/csistoragecapacity.go","code":"// NewCSIStorageCapacityInformer constructs a new informer for CSIStorageCapacity type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewCSIStorageCapacityInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredCSIStorageCapacityInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025862,"name":"NewFilteredCSIStorageCapacityInformer","signature":"func NewFilteredCSIStorageCapacityInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1alpha1/csistoragecapacity.go","code":"// NewFilteredCSIStorageCapacityInformer constructs a new informer for CSIStorageCapacity type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredCSIStorageCapacityInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.StorageV1alpha1().CSIStorageCapacities(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.StorageV1alpha1().CSIStorageCapacities(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026storagev1alpha1.CSIStorageCapacity{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025863,"name":"defaultInformer","signature":"func (f *cSIStorageCapacityInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1alpha1/csistoragecapacity.go","code":"func (f *cSIStorageCapacityInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredCSIStorageCapacityInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025864,"name":"Informer","signature":"func (f *cSIStorageCapacityInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1alpha1/csistoragecapacity.go","code":"func (f *cSIStorageCapacityInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026storagev1alpha1.CSIStorageCapacity{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025865,"name":"Lister","signature":"func (f *cSIStorageCapacityInformer) Lister() v1alpha1.CSIStorageCapacityLister","file":"staging/src/k8s.io/client-go/informers/storage/v1alpha1/csistoragecapacity.go","code":"func (f *cSIStorageCapacityInformer) Lister() v1alpha1.CSIStorageCapacityLister {\n\treturn v1alpha1.NewCSIStorageCapacityLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025866,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/storage/v1alpha1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":39,"to":42}} {"id":100025867,"name":"CSIStorageCapacities","signature":"func (v *version) CSIStorageCapacities() CSIStorageCapacityInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1alpha1/interface.go","code":"// CSIStorageCapacities returns a CSIStorageCapacityInformer.\nfunc (v *version) CSIStorageCapacities() CSIStorageCapacityInformer {\n\treturn \u0026cSIStorageCapacityInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":44,"to":47}} {"id":100025868,"name":"VolumeAttachments","signature":"func (v *version) VolumeAttachments() VolumeAttachmentInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1alpha1/interface.go","code":"// VolumeAttachments returns a VolumeAttachmentInformer.\nfunc (v *version) VolumeAttachments() VolumeAttachmentInformer {\n\treturn \u0026volumeAttachmentInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":49,"to":52}} {"id":100025869,"name":"NewVolumeAttachmentInformer","signature":"func NewVolumeAttachmentInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1alpha1/volumeattachment.go","code":"// NewVolumeAttachmentInformer constructs a new informer for VolumeAttachment type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewVolumeAttachmentInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredVolumeAttachmentInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025870,"name":"NewFilteredVolumeAttachmentInformer","signature":"func NewFilteredVolumeAttachmentInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1alpha1/volumeattachment.go","code":"// NewFilteredVolumeAttachmentInformer constructs a new informer for VolumeAttachment type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredVolumeAttachmentInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.StorageV1alpha1().VolumeAttachments().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.StorageV1alpha1().VolumeAttachments().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026storagev1alpha1.VolumeAttachment{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025871,"name":"defaultInformer","signature":"func (f *volumeAttachmentInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1alpha1/volumeattachment.go","code":"func (f *volumeAttachmentInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredVolumeAttachmentInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025872,"name":"Informer","signature":"func (f *volumeAttachmentInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1alpha1/volumeattachment.go","code":"func (f *volumeAttachmentInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026storagev1alpha1.VolumeAttachment{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025873,"name":"Lister","signature":"func (f *volumeAttachmentInformer) Lister() v1alpha1.VolumeAttachmentLister","file":"staging/src/k8s.io/client-go/informers/storage/v1alpha1/volumeattachment.go","code":"func (f *volumeAttachmentInformer) Lister() v1alpha1.VolumeAttachmentLister {\n\treturn v1alpha1.NewVolumeAttachmentLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025874,"name":"NewCSIDriverInformer","signature":"func NewCSIDriverInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/csidriver.go","code":"// NewCSIDriverInformer constructs a new informer for CSIDriver type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewCSIDriverInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredCSIDriverInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025875,"name":"NewFilteredCSIDriverInformer","signature":"func NewFilteredCSIDriverInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/csidriver.go","code":"// NewFilteredCSIDriverInformer constructs a new informer for CSIDriver type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredCSIDriverInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.StorageV1beta1().CSIDrivers().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.StorageV1beta1().CSIDrivers().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026storagev1beta1.CSIDriver{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025876,"name":"defaultInformer","signature":"func (f *cSIDriverInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/csidriver.go","code":"func (f *cSIDriverInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredCSIDriverInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025877,"name":"Informer","signature":"func (f *cSIDriverInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/csidriver.go","code":"func (f *cSIDriverInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026storagev1beta1.CSIDriver{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025878,"name":"Lister","signature":"func (f *cSIDriverInformer) Lister() v1beta1.CSIDriverLister","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/csidriver.go","code":"func (f *cSIDriverInformer) Lister() v1beta1.CSIDriverLister {\n\treturn v1beta1.NewCSIDriverLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025879,"name":"NewCSINodeInformer","signature":"func NewCSINodeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/csinode.go","code":"// NewCSINodeInformer constructs a new informer for CSINode type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewCSINodeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredCSINodeInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025880,"name":"NewFilteredCSINodeInformer","signature":"func NewFilteredCSINodeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/csinode.go","code":"// NewFilteredCSINodeInformer constructs a new informer for CSINode type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredCSINodeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.StorageV1beta1().CSINodes().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.StorageV1beta1().CSINodes().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026storagev1beta1.CSINode{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025881,"name":"defaultInformer","signature":"func (f *cSINodeInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/csinode.go","code":"func (f *cSINodeInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredCSINodeInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025882,"name":"Informer","signature":"func (f *cSINodeInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/csinode.go","code":"func (f *cSINodeInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026storagev1beta1.CSINode{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025883,"name":"Lister","signature":"func (f *cSINodeInformer) Lister() v1beta1.CSINodeLister","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/csinode.go","code":"func (f *cSINodeInformer) Lister() v1beta1.CSINodeLister {\n\treturn v1beta1.NewCSINodeLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025884,"name":"NewCSIStorageCapacityInformer","signature":"func NewCSIStorageCapacityInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/csistoragecapacity.go","code":"// NewCSIStorageCapacityInformer constructs a new informer for CSIStorageCapacity type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewCSIStorageCapacityInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredCSIStorageCapacityInformer(client, namespace, resyncPeriod, indexers, nil)\n}","line":{"from":48,"to":53}} {"id":100025885,"name":"NewFilteredCSIStorageCapacityInformer","signature":"func NewFilteredCSIStorageCapacityInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/csistoragecapacity.go","code":"// NewFilteredCSIStorageCapacityInformer constructs a new informer for CSIStorageCapacity type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredCSIStorageCapacityInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.StorageV1beta1().CSIStorageCapacities(namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.StorageV1beta1().CSIStorageCapacities(namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026storagev1beta1.CSIStorageCapacity{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":55,"to":78}} {"id":100025886,"name":"defaultInformer","signature":"func (f *cSIStorageCapacityInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/csistoragecapacity.go","code":"func (f *cSIStorageCapacityInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredCSIStorageCapacityInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":80,"to":82}} {"id":100025887,"name":"Informer","signature":"func (f *cSIStorageCapacityInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/csistoragecapacity.go","code":"func (f *cSIStorageCapacityInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026storagev1beta1.CSIStorageCapacity{}, f.defaultInformer)\n}","line":{"from":84,"to":86}} {"id":100025888,"name":"Lister","signature":"func (f *cSIStorageCapacityInformer) Lister() v1beta1.CSIStorageCapacityLister","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/csistoragecapacity.go","code":"func (f *cSIStorageCapacityInformer) Lister() v1beta1.CSIStorageCapacityLister {\n\treturn v1beta1.NewCSIStorageCapacityLister(f.Informer().GetIndexer())\n}","line":{"from":88,"to":90}} {"id":100025889,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":45,"to":48}} {"id":100025890,"name":"CSIDrivers","signature":"func (v *version) CSIDrivers() CSIDriverInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/interface.go","code":"// CSIDrivers returns a CSIDriverInformer.\nfunc (v *version) CSIDrivers() CSIDriverInformer {\n\treturn \u0026cSIDriverInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":50,"to":53}} {"id":100025891,"name":"CSINodes","signature":"func (v *version) CSINodes() CSINodeInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/interface.go","code":"// CSINodes returns a CSINodeInformer.\nfunc (v *version) CSINodes() CSINodeInformer {\n\treturn \u0026cSINodeInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":55,"to":58}} {"id":100025892,"name":"CSIStorageCapacities","signature":"func (v *version) CSIStorageCapacities() CSIStorageCapacityInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/interface.go","code":"// CSIStorageCapacities returns a CSIStorageCapacityInformer.\nfunc (v *version) CSIStorageCapacities() CSIStorageCapacityInformer {\n\treturn \u0026cSIStorageCapacityInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}\n}","line":{"from":60,"to":63}} {"id":100025893,"name":"StorageClasses","signature":"func (v *version) StorageClasses() StorageClassInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/interface.go","code":"// StorageClasses returns a StorageClassInformer.\nfunc (v *version) StorageClasses() StorageClassInformer {\n\treturn \u0026storageClassInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":65,"to":68}} {"id":100025894,"name":"VolumeAttachments","signature":"func (v *version) VolumeAttachments() VolumeAttachmentInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/interface.go","code":"// VolumeAttachments returns a VolumeAttachmentInformer.\nfunc (v *version) VolumeAttachments() VolumeAttachmentInformer {\n\treturn \u0026volumeAttachmentInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":70,"to":73}} {"id":100025895,"name":"NewStorageClassInformer","signature":"func NewStorageClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/storageclass.go","code":"// NewStorageClassInformer constructs a new informer for StorageClass type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewStorageClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredStorageClassInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025896,"name":"NewFilteredStorageClassInformer","signature":"func NewFilteredStorageClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/storageclass.go","code":"// NewFilteredStorageClassInformer constructs a new informer for StorageClass type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredStorageClassInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.StorageV1beta1().StorageClasses().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.StorageV1beta1().StorageClasses().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026storagev1beta1.StorageClass{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025897,"name":"defaultInformer","signature":"func (f *storageClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/storageclass.go","code":"func (f *storageClassInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredStorageClassInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025898,"name":"Informer","signature":"func (f *storageClassInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/storageclass.go","code":"func (f *storageClassInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026storagev1beta1.StorageClass{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025899,"name":"Lister","signature":"func (f *storageClassInformer) Lister() v1beta1.StorageClassLister","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/storageclass.go","code":"func (f *storageClassInformer) Lister() v1beta1.StorageClassLister {\n\treturn v1beta1.NewStorageClassLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025900,"name":"NewVolumeAttachmentInformer","signature":"func NewVolumeAttachmentInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/volumeattachment.go","code":"// NewVolumeAttachmentInformer constructs a new informer for VolumeAttachment type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewVolumeAttachmentInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredVolumeAttachmentInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100025901,"name":"NewFilteredVolumeAttachmentInformer","signature":"func NewFilteredVolumeAttachmentInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/volumeattachment.go","code":"// NewFilteredVolumeAttachmentInformer constructs a new informer for VolumeAttachment type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredVolumeAttachmentInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.StorageV1beta1().VolumeAttachments().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.StorageV1beta1().VolumeAttachments().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026storagev1beta1.VolumeAttachment{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100025902,"name":"defaultInformer","signature":"func (f *volumeAttachmentInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/volumeattachment.go","code":"func (f *volumeAttachmentInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredVolumeAttachmentInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100025903,"name":"Informer","signature":"func (f *volumeAttachmentInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/volumeattachment.go","code":"func (f *volumeAttachmentInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026storagev1beta1.VolumeAttachment{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100025904,"name":"Lister","signature":"func (f *volumeAttachmentInformer) Lister() v1beta1.VolumeAttachmentLister","file":"staging/src/k8s.io/client-go/informers/storage/v1beta1/volumeattachment.go","code":"func (f *volumeAttachmentInformer) Lister() v1beta1.VolumeAttachmentLister {\n\treturn v1beta1.NewVolumeAttachmentLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100025905,"name":"AdmissionregistrationV1","signature":"func (c *Clientset) AdmissionregistrationV1() admissionregistrationv1.AdmissionregistrationV1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// AdmissionregistrationV1 retrieves the AdmissionregistrationV1Client\nfunc (c *Clientset) AdmissionregistrationV1() admissionregistrationv1.AdmissionregistrationV1Interface {\n\treturn c.admissionregistrationV1\n}","line":{"from":192,"to":195}} {"id":100025906,"name":"AdmissionregistrationV1alpha1","signature":"func (c *Clientset) AdmissionregistrationV1alpha1() admissionregistrationv1alpha1.AdmissionregistrationV1alpha1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// AdmissionregistrationV1alpha1 retrieves the AdmissionregistrationV1alpha1Client\nfunc (c *Clientset) AdmissionregistrationV1alpha1() admissionregistrationv1alpha1.AdmissionregistrationV1alpha1Interface {\n\treturn c.admissionregistrationV1alpha1\n}","line":{"from":197,"to":200}} {"id":100025907,"name":"AdmissionregistrationV1beta1","signature":"func (c *Clientset) AdmissionregistrationV1beta1() admissionregistrationv1beta1.AdmissionregistrationV1beta1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// AdmissionregistrationV1beta1 retrieves the AdmissionregistrationV1beta1Client\nfunc (c *Clientset) AdmissionregistrationV1beta1() admissionregistrationv1beta1.AdmissionregistrationV1beta1Interface {\n\treturn c.admissionregistrationV1beta1\n}","line":{"from":202,"to":205}} {"id":100025908,"name":"InternalV1alpha1","signature":"func (c *Clientset) InternalV1alpha1() internalv1alpha1.InternalV1alpha1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// InternalV1alpha1 retrieves the InternalV1alpha1Client\nfunc (c *Clientset) InternalV1alpha1() internalv1alpha1.InternalV1alpha1Interface {\n\treturn c.internalV1alpha1\n}","line":{"from":207,"to":210}} {"id":100025909,"name":"AppsV1","signature":"func (c *Clientset) AppsV1() appsv1.AppsV1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// AppsV1 retrieves the AppsV1Client\nfunc (c *Clientset) AppsV1() appsv1.AppsV1Interface {\n\treturn c.appsV1\n}","line":{"from":212,"to":215}} {"id":100025910,"name":"AppsV1beta1","signature":"func (c *Clientset) AppsV1beta1() appsv1beta1.AppsV1beta1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// AppsV1beta1 retrieves the AppsV1beta1Client\nfunc (c *Clientset) AppsV1beta1() appsv1beta1.AppsV1beta1Interface {\n\treturn c.appsV1beta1\n}","line":{"from":217,"to":220}} {"id":100025911,"name":"AppsV1beta2","signature":"func (c *Clientset) AppsV1beta2() appsv1beta2.AppsV1beta2Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// AppsV1beta2 retrieves the AppsV1beta2Client\nfunc (c *Clientset) AppsV1beta2() appsv1beta2.AppsV1beta2Interface {\n\treturn c.appsV1beta2\n}","line":{"from":222,"to":225}} {"id":100025912,"name":"AuthenticationV1","signature":"func (c *Clientset) AuthenticationV1() authenticationv1.AuthenticationV1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// AuthenticationV1 retrieves the AuthenticationV1Client\nfunc (c *Clientset) AuthenticationV1() authenticationv1.AuthenticationV1Interface {\n\treturn c.authenticationV1\n}","line":{"from":227,"to":230}} {"id":100025913,"name":"AuthenticationV1alpha1","signature":"func (c *Clientset) AuthenticationV1alpha1() authenticationv1alpha1.AuthenticationV1alpha1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// AuthenticationV1alpha1 retrieves the AuthenticationV1alpha1Client\nfunc (c *Clientset) AuthenticationV1alpha1() authenticationv1alpha1.AuthenticationV1alpha1Interface {\n\treturn c.authenticationV1alpha1\n}","line":{"from":232,"to":235}} {"id":100025914,"name":"AuthenticationV1beta1","signature":"func (c *Clientset) AuthenticationV1beta1() authenticationv1beta1.AuthenticationV1beta1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// AuthenticationV1beta1 retrieves the AuthenticationV1beta1Client\nfunc (c *Clientset) AuthenticationV1beta1() authenticationv1beta1.AuthenticationV1beta1Interface {\n\treturn c.authenticationV1beta1\n}","line":{"from":237,"to":240}} {"id":100025915,"name":"AuthorizationV1","signature":"func (c *Clientset) AuthorizationV1() authorizationv1.AuthorizationV1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// AuthorizationV1 retrieves the AuthorizationV1Client\nfunc (c *Clientset) AuthorizationV1() authorizationv1.AuthorizationV1Interface {\n\treturn c.authorizationV1\n}","line":{"from":242,"to":245}} {"id":100025916,"name":"AuthorizationV1beta1","signature":"func (c *Clientset) AuthorizationV1beta1() authorizationv1beta1.AuthorizationV1beta1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// AuthorizationV1beta1 retrieves the AuthorizationV1beta1Client\nfunc (c *Clientset) AuthorizationV1beta1() authorizationv1beta1.AuthorizationV1beta1Interface {\n\treturn c.authorizationV1beta1\n}","line":{"from":247,"to":250}} {"id":100025917,"name":"AutoscalingV1","signature":"func (c *Clientset) AutoscalingV1() autoscalingv1.AutoscalingV1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// AutoscalingV1 retrieves the AutoscalingV1Client\nfunc (c *Clientset) AutoscalingV1() autoscalingv1.AutoscalingV1Interface {\n\treturn c.autoscalingV1\n}","line":{"from":252,"to":255}} {"id":100025918,"name":"AutoscalingV2","signature":"func (c *Clientset) AutoscalingV2() autoscalingv2.AutoscalingV2Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// AutoscalingV2 retrieves the AutoscalingV2Client\nfunc (c *Clientset) AutoscalingV2() autoscalingv2.AutoscalingV2Interface {\n\treturn c.autoscalingV2\n}","line":{"from":257,"to":260}} {"id":100025919,"name":"AutoscalingV2beta1","signature":"func (c *Clientset) AutoscalingV2beta1() autoscalingv2beta1.AutoscalingV2beta1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// AutoscalingV2beta1 retrieves the AutoscalingV2beta1Client\nfunc (c *Clientset) AutoscalingV2beta1() autoscalingv2beta1.AutoscalingV2beta1Interface {\n\treturn c.autoscalingV2beta1\n}","line":{"from":262,"to":265}} {"id":100025920,"name":"AutoscalingV2beta2","signature":"func (c *Clientset) AutoscalingV2beta2() autoscalingv2beta2.AutoscalingV2beta2Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// AutoscalingV2beta2 retrieves the AutoscalingV2beta2Client\nfunc (c *Clientset) AutoscalingV2beta2() autoscalingv2beta2.AutoscalingV2beta2Interface {\n\treturn c.autoscalingV2beta2\n}","line":{"from":267,"to":270}} {"id":100025921,"name":"BatchV1","signature":"func (c *Clientset) BatchV1() batchv1.BatchV1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// BatchV1 retrieves the BatchV1Client\nfunc (c *Clientset) BatchV1() batchv1.BatchV1Interface {\n\treturn c.batchV1\n}","line":{"from":272,"to":275}} {"id":100025922,"name":"BatchV1beta1","signature":"func (c *Clientset) BatchV1beta1() batchv1beta1.BatchV1beta1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// BatchV1beta1 retrieves the BatchV1beta1Client\nfunc (c *Clientset) BatchV1beta1() batchv1beta1.BatchV1beta1Interface {\n\treturn c.batchV1beta1\n}","line":{"from":277,"to":280}} {"id":100025923,"name":"CertificatesV1","signature":"func (c *Clientset) CertificatesV1() certificatesv1.CertificatesV1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// CertificatesV1 retrieves the CertificatesV1Client\nfunc (c *Clientset) CertificatesV1() certificatesv1.CertificatesV1Interface {\n\treturn c.certificatesV1\n}","line":{"from":282,"to":285}} {"id":100025924,"name":"CertificatesV1beta1","signature":"func (c *Clientset) CertificatesV1beta1() certificatesv1beta1.CertificatesV1beta1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// CertificatesV1beta1 retrieves the CertificatesV1beta1Client\nfunc (c *Clientset) CertificatesV1beta1() certificatesv1beta1.CertificatesV1beta1Interface {\n\treturn c.certificatesV1beta1\n}","line":{"from":287,"to":290}} {"id":100025925,"name":"CertificatesV1alpha1","signature":"func (c *Clientset) CertificatesV1alpha1() certificatesv1alpha1.CertificatesV1alpha1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// CertificatesV1alpha1 retrieves the CertificatesV1alpha1Client\nfunc (c *Clientset) CertificatesV1alpha1() certificatesv1alpha1.CertificatesV1alpha1Interface {\n\treturn c.certificatesV1alpha1\n}","line":{"from":292,"to":295}} {"id":100025926,"name":"CoordinationV1beta1","signature":"func (c *Clientset) CoordinationV1beta1() coordinationv1beta1.CoordinationV1beta1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// CoordinationV1beta1 retrieves the CoordinationV1beta1Client\nfunc (c *Clientset) CoordinationV1beta1() coordinationv1beta1.CoordinationV1beta1Interface {\n\treturn c.coordinationV1beta1\n}","line":{"from":297,"to":300}} {"id":100025927,"name":"CoordinationV1","signature":"func (c *Clientset) CoordinationV1() coordinationv1.CoordinationV1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// CoordinationV1 retrieves the CoordinationV1Client\nfunc (c *Clientset) CoordinationV1() coordinationv1.CoordinationV1Interface {\n\treturn c.coordinationV1\n}","line":{"from":302,"to":305}} {"id":100025928,"name":"CoreV1","signature":"func (c *Clientset) CoreV1() corev1.CoreV1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// CoreV1 retrieves the CoreV1Client\nfunc (c *Clientset) CoreV1() corev1.CoreV1Interface {\n\treturn c.coreV1\n}","line":{"from":307,"to":310}} {"id":100025929,"name":"DiscoveryV1","signature":"func (c *Clientset) DiscoveryV1() discoveryv1.DiscoveryV1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// DiscoveryV1 retrieves the DiscoveryV1Client\nfunc (c *Clientset) DiscoveryV1() discoveryv1.DiscoveryV1Interface {\n\treturn c.discoveryV1\n}","line":{"from":312,"to":315}} {"id":100025930,"name":"DiscoveryV1beta1","signature":"func (c *Clientset) DiscoveryV1beta1() discoveryv1beta1.DiscoveryV1beta1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// DiscoveryV1beta1 retrieves the DiscoveryV1beta1Client\nfunc (c *Clientset) DiscoveryV1beta1() discoveryv1beta1.DiscoveryV1beta1Interface {\n\treturn c.discoveryV1beta1\n}","line":{"from":317,"to":320}} {"id":100025931,"name":"EventsV1","signature":"func (c *Clientset) EventsV1() eventsv1.EventsV1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// EventsV1 retrieves the EventsV1Client\nfunc (c *Clientset) EventsV1() eventsv1.EventsV1Interface {\n\treturn c.eventsV1\n}","line":{"from":322,"to":325}} {"id":100025932,"name":"EventsV1beta1","signature":"func (c *Clientset) EventsV1beta1() eventsv1beta1.EventsV1beta1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// EventsV1beta1 retrieves the EventsV1beta1Client\nfunc (c *Clientset) EventsV1beta1() eventsv1beta1.EventsV1beta1Interface {\n\treturn c.eventsV1beta1\n}","line":{"from":327,"to":330}} {"id":100025933,"name":"ExtensionsV1beta1","signature":"func (c *Clientset) ExtensionsV1beta1() extensionsv1beta1.ExtensionsV1beta1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// ExtensionsV1beta1 retrieves the ExtensionsV1beta1Client\nfunc (c *Clientset) ExtensionsV1beta1() extensionsv1beta1.ExtensionsV1beta1Interface {\n\treturn c.extensionsV1beta1\n}","line":{"from":332,"to":335}} {"id":100025934,"name":"FlowcontrolV1alpha1","signature":"func (c *Clientset) FlowcontrolV1alpha1() flowcontrolv1alpha1.FlowcontrolV1alpha1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// FlowcontrolV1alpha1 retrieves the FlowcontrolV1alpha1Client\nfunc (c *Clientset) FlowcontrolV1alpha1() flowcontrolv1alpha1.FlowcontrolV1alpha1Interface {\n\treturn c.flowcontrolV1alpha1\n}","line":{"from":337,"to":340}} {"id":100025935,"name":"FlowcontrolV1beta1","signature":"func (c *Clientset) FlowcontrolV1beta1() flowcontrolv1beta1.FlowcontrolV1beta1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// FlowcontrolV1beta1 retrieves the FlowcontrolV1beta1Client\nfunc (c *Clientset) FlowcontrolV1beta1() flowcontrolv1beta1.FlowcontrolV1beta1Interface {\n\treturn c.flowcontrolV1beta1\n}","line":{"from":342,"to":345}} {"id":100025936,"name":"FlowcontrolV1beta2","signature":"func (c *Clientset) FlowcontrolV1beta2() flowcontrolv1beta2.FlowcontrolV1beta2Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// FlowcontrolV1beta2 retrieves the FlowcontrolV1beta2Client\nfunc (c *Clientset) FlowcontrolV1beta2() flowcontrolv1beta2.FlowcontrolV1beta2Interface {\n\treturn c.flowcontrolV1beta2\n}","line":{"from":347,"to":350}} {"id":100025937,"name":"FlowcontrolV1beta3","signature":"func (c *Clientset) FlowcontrolV1beta3() flowcontrolv1beta3.FlowcontrolV1beta3Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// FlowcontrolV1beta3 retrieves the FlowcontrolV1beta3Client\nfunc (c *Clientset) FlowcontrolV1beta3() flowcontrolv1beta3.FlowcontrolV1beta3Interface {\n\treturn c.flowcontrolV1beta3\n}","line":{"from":352,"to":355}} {"id":100025938,"name":"NetworkingV1","signature":"func (c *Clientset) NetworkingV1() networkingv1.NetworkingV1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// NetworkingV1 retrieves the NetworkingV1Client\nfunc (c *Clientset) NetworkingV1() networkingv1.NetworkingV1Interface {\n\treturn c.networkingV1\n}","line":{"from":357,"to":360}} {"id":100025939,"name":"NetworkingV1alpha1","signature":"func (c *Clientset) NetworkingV1alpha1() networkingv1alpha1.NetworkingV1alpha1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// NetworkingV1alpha1 retrieves the NetworkingV1alpha1Client\nfunc (c *Clientset) NetworkingV1alpha1() networkingv1alpha1.NetworkingV1alpha1Interface {\n\treturn c.networkingV1alpha1\n}","line":{"from":362,"to":365}} {"id":100025940,"name":"NetworkingV1beta1","signature":"func (c *Clientset) NetworkingV1beta1() networkingv1beta1.NetworkingV1beta1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// NetworkingV1beta1 retrieves the NetworkingV1beta1Client\nfunc (c *Clientset) NetworkingV1beta1() networkingv1beta1.NetworkingV1beta1Interface {\n\treturn c.networkingV1beta1\n}","line":{"from":367,"to":370}} {"id":100025941,"name":"NodeV1","signature":"func (c *Clientset) NodeV1() nodev1.NodeV1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// NodeV1 retrieves the NodeV1Client\nfunc (c *Clientset) NodeV1() nodev1.NodeV1Interface {\n\treturn c.nodeV1\n}","line":{"from":372,"to":375}} {"id":100025942,"name":"NodeV1alpha1","signature":"func (c *Clientset) NodeV1alpha1() nodev1alpha1.NodeV1alpha1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// NodeV1alpha1 retrieves the NodeV1alpha1Client\nfunc (c *Clientset) NodeV1alpha1() nodev1alpha1.NodeV1alpha1Interface {\n\treturn c.nodeV1alpha1\n}","line":{"from":377,"to":380}} {"id":100025943,"name":"NodeV1beta1","signature":"func (c *Clientset) NodeV1beta1() nodev1beta1.NodeV1beta1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// NodeV1beta1 retrieves the NodeV1beta1Client\nfunc (c *Clientset) NodeV1beta1() nodev1beta1.NodeV1beta1Interface {\n\treturn c.nodeV1beta1\n}","line":{"from":382,"to":385}} {"id":100025944,"name":"PolicyV1","signature":"func (c *Clientset) PolicyV1() policyv1.PolicyV1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// PolicyV1 retrieves the PolicyV1Client\nfunc (c *Clientset) PolicyV1() policyv1.PolicyV1Interface {\n\treturn c.policyV1\n}","line":{"from":387,"to":390}} {"id":100025945,"name":"PolicyV1beta1","signature":"func (c *Clientset) PolicyV1beta1() policyv1beta1.PolicyV1beta1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// PolicyV1beta1 retrieves the PolicyV1beta1Client\nfunc (c *Clientset) PolicyV1beta1() policyv1beta1.PolicyV1beta1Interface {\n\treturn c.policyV1beta1\n}","line":{"from":392,"to":395}} {"id":100025946,"name":"RbacV1","signature":"func (c *Clientset) RbacV1() rbacv1.RbacV1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// RbacV1 retrieves the RbacV1Client\nfunc (c *Clientset) RbacV1() rbacv1.RbacV1Interface {\n\treturn c.rbacV1\n}","line":{"from":397,"to":400}} {"id":100025947,"name":"RbacV1beta1","signature":"func (c *Clientset) RbacV1beta1() rbacv1beta1.RbacV1beta1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// RbacV1beta1 retrieves the RbacV1beta1Client\nfunc (c *Clientset) RbacV1beta1() rbacv1beta1.RbacV1beta1Interface {\n\treturn c.rbacV1beta1\n}","line":{"from":402,"to":405}} {"id":100025948,"name":"RbacV1alpha1","signature":"func (c *Clientset) RbacV1alpha1() rbacv1alpha1.RbacV1alpha1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// RbacV1alpha1 retrieves the RbacV1alpha1Client\nfunc (c *Clientset) RbacV1alpha1() rbacv1alpha1.RbacV1alpha1Interface {\n\treturn c.rbacV1alpha1\n}","line":{"from":407,"to":410}} {"id":100025949,"name":"ResourceV1alpha2","signature":"func (c *Clientset) ResourceV1alpha2() resourcev1alpha2.ResourceV1alpha2Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// ResourceV1alpha2 retrieves the ResourceV1alpha2Client\nfunc (c *Clientset) ResourceV1alpha2() resourcev1alpha2.ResourceV1alpha2Interface {\n\treturn c.resourceV1alpha2\n}","line":{"from":412,"to":415}} {"id":100025950,"name":"SchedulingV1alpha1","signature":"func (c *Clientset) SchedulingV1alpha1() schedulingv1alpha1.SchedulingV1alpha1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// SchedulingV1alpha1 retrieves the SchedulingV1alpha1Client\nfunc (c *Clientset) SchedulingV1alpha1() schedulingv1alpha1.SchedulingV1alpha1Interface {\n\treturn c.schedulingV1alpha1\n}","line":{"from":417,"to":420}} {"id":100025951,"name":"SchedulingV1beta1","signature":"func (c *Clientset) SchedulingV1beta1() schedulingv1beta1.SchedulingV1beta1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// SchedulingV1beta1 retrieves the SchedulingV1beta1Client\nfunc (c *Clientset) SchedulingV1beta1() schedulingv1beta1.SchedulingV1beta1Interface {\n\treturn c.schedulingV1beta1\n}","line":{"from":422,"to":425}} {"id":100025952,"name":"SchedulingV1","signature":"func (c *Clientset) SchedulingV1() schedulingv1.SchedulingV1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// SchedulingV1 retrieves the SchedulingV1Client\nfunc (c *Clientset) SchedulingV1() schedulingv1.SchedulingV1Interface {\n\treturn c.schedulingV1\n}","line":{"from":427,"to":430}} {"id":100025953,"name":"StorageV1beta1","signature":"func (c *Clientset) StorageV1beta1() storagev1beta1.StorageV1beta1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// StorageV1beta1 retrieves the StorageV1beta1Client\nfunc (c *Clientset) StorageV1beta1() storagev1beta1.StorageV1beta1Interface {\n\treturn c.storageV1beta1\n}","line":{"from":432,"to":435}} {"id":100025954,"name":"StorageV1","signature":"func (c *Clientset) StorageV1() storagev1.StorageV1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// StorageV1 retrieves the StorageV1Client\nfunc (c *Clientset) StorageV1() storagev1.StorageV1Interface {\n\treturn c.storageV1\n}","line":{"from":437,"to":440}} {"id":100025955,"name":"StorageV1alpha1","signature":"func (c *Clientset) StorageV1alpha1() storagev1alpha1.StorageV1alpha1Interface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// StorageV1alpha1 retrieves the StorageV1alpha1Client\nfunc (c *Clientset) StorageV1alpha1() storagev1alpha1.StorageV1alpha1Interface {\n\treturn c.storageV1alpha1\n}","line":{"from":442,"to":445}} {"id":100025956,"name":"Discovery","signature":"func (c *Clientset) Discovery() discovery.DiscoveryInterface","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// Discovery retrieves the DiscoveryClient\nfunc (c *Clientset) Discovery() discovery.DiscoveryInterface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.DiscoveryClient\n}","line":{"from":447,"to":453}} {"id":100025957,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*Clientset, error)","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// NewForConfig creates a new Clientset for the given config.\n// If config's RateLimiter is not set and QPS and Burst are acceptable,\n// NewForConfig will generate a rate-limiter in configShallowCopy.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*Clientset, error) {\n\tconfigShallowCopy := *c\n\n\tif configShallowCopy.UserAgent == \"\" {\n\t\tconfigShallowCopy.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\t// share the transport between all clients\n\thttpClient, err := rest.HTTPClientFor(\u0026configShallowCopy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n}","line":{"from":455,"to":474}} {"id":100025958,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, httpClient *http.Client) (*Clientset, error)","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// NewForConfigAndClient creates a new Clientset for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\n// If config's RateLimiter is not set and QPS and Burst are acceptable,\n// NewForConfigAndClient will generate a rate-limiter in configShallowCopy.\nfunc NewForConfigAndClient(c *rest.Config, httpClient *http.Client) (*Clientset, error) {\n\tconfigShallowCopy := *c\n\tif configShallowCopy.RateLimiter == nil \u0026\u0026 configShallowCopy.QPS \u003e 0 {\n\t\tif configShallowCopy.Burst \u003c= 0 {\n\t\t\treturn nil, fmt.Errorf(\"burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0\")\n\t\t}\n\t\tconfigShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst)\n\t}\n\n\tvar cs Clientset\n\tvar err error\n\tcs.admissionregistrationV1, err = admissionregistrationv1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.admissionregistrationV1alpha1, err = admissionregistrationv1alpha1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.admissionregistrationV1beta1, err = admissionregistrationv1beta1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.internalV1alpha1, err = internalv1alpha1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.appsV1, err = appsv1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.appsV1beta1, err = appsv1beta1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.appsV1beta2, err = appsv1beta2.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.authenticationV1, err = authenticationv1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.authenticationV1alpha1, err = authenticationv1alpha1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.authenticationV1beta1, err = authenticationv1beta1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.authorizationV1, err = authorizationv1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.authorizationV1beta1, err = authorizationv1beta1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.autoscalingV1, err = autoscalingv1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.autoscalingV2, err = autoscalingv2.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.autoscalingV2beta1, err = autoscalingv2beta1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.autoscalingV2beta2, err = autoscalingv2beta2.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.batchV1, err = batchv1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.batchV1beta1, err = batchv1beta1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.certificatesV1, err = certificatesv1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.certificatesV1beta1, err = certificatesv1beta1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.certificatesV1alpha1, err = certificatesv1alpha1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.coordinationV1beta1, err = coordinationv1beta1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.coordinationV1, err = coordinationv1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.coreV1, err = corev1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.discoveryV1, err = discoveryv1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.discoveryV1beta1, err = discoveryv1beta1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.eventsV1, err = eventsv1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.eventsV1beta1, err = eventsv1beta1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.extensionsV1beta1, err = extensionsv1beta1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.flowcontrolV1alpha1, err = flowcontrolv1alpha1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.flowcontrolV1beta1, err = flowcontrolv1beta1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.flowcontrolV1beta2, err = flowcontrolv1beta2.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.flowcontrolV1beta3, err = flowcontrolv1beta3.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.networkingV1, err = networkingv1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.networkingV1alpha1, err = networkingv1alpha1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.networkingV1beta1, err = networkingv1beta1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.nodeV1, err = nodev1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.nodeV1alpha1, err = nodev1alpha1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.nodeV1beta1, err = nodev1beta1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.policyV1, err = policyv1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.policyV1beta1, err = policyv1beta1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.rbacV1, err = rbacv1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.rbacV1beta1, err = rbacv1beta1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.rbacV1alpha1, err = rbacv1alpha1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.resourceV1alpha2, err = resourcev1alpha2.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.schedulingV1alpha1, err = schedulingv1alpha1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.schedulingV1beta1, err = schedulingv1beta1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.schedulingV1, err = schedulingv1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.storageV1beta1, err = storagev1beta1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.storageV1, err = storagev1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.storageV1alpha1, err = storagev1alpha1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026cs, nil\n}","line":{"from":476,"to":701}} {"id":100025959,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *Clientset","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// NewForConfigOrDie creates a new Clientset for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *Clientset {\n\tcs, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn cs\n}","line":{"from":703,"to":711}} {"id":100025960,"name":"New","signature":"func New(c rest.Interface) *Clientset","file":"staging/src/k8s.io/client-go/kubernetes/clientset.go","code":"// New creates a new Clientset for the given RESTClient.\nfunc New(c rest.Interface) *Clientset {\n\tvar cs Clientset\n\tcs.admissionregistrationV1 = admissionregistrationv1.New(c)\n\tcs.admissionregistrationV1alpha1 = admissionregistrationv1alpha1.New(c)\n\tcs.admissionregistrationV1beta1 = admissionregistrationv1beta1.New(c)\n\tcs.internalV1alpha1 = internalv1alpha1.New(c)\n\tcs.appsV1 = appsv1.New(c)\n\tcs.appsV1beta1 = appsv1beta1.New(c)\n\tcs.appsV1beta2 = appsv1beta2.New(c)\n\tcs.authenticationV1 = authenticationv1.New(c)\n\tcs.authenticationV1alpha1 = authenticationv1alpha1.New(c)\n\tcs.authenticationV1beta1 = authenticationv1beta1.New(c)\n\tcs.authorizationV1 = authorizationv1.New(c)\n\tcs.authorizationV1beta1 = authorizationv1beta1.New(c)\n\tcs.autoscalingV1 = autoscalingv1.New(c)\n\tcs.autoscalingV2 = autoscalingv2.New(c)\n\tcs.autoscalingV2beta1 = autoscalingv2beta1.New(c)\n\tcs.autoscalingV2beta2 = autoscalingv2beta2.New(c)\n\tcs.batchV1 = batchv1.New(c)\n\tcs.batchV1beta1 = batchv1beta1.New(c)\n\tcs.certificatesV1 = certificatesv1.New(c)\n\tcs.certificatesV1beta1 = certificatesv1beta1.New(c)\n\tcs.certificatesV1alpha1 = certificatesv1alpha1.New(c)\n\tcs.coordinationV1beta1 = coordinationv1beta1.New(c)\n\tcs.coordinationV1 = coordinationv1.New(c)\n\tcs.coreV1 = corev1.New(c)\n\tcs.discoveryV1 = discoveryv1.New(c)\n\tcs.discoveryV1beta1 = discoveryv1beta1.New(c)\n\tcs.eventsV1 = eventsv1.New(c)\n\tcs.eventsV1beta1 = eventsv1beta1.New(c)\n\tcs.extensionsV1beta1 = extensionsv1beta1.New(c)\n\tcs.flowcontrolV1alpha1 = flowcontrolv1alpha1.New(c)\n\tcs.flowcontrolV1beta1 = flowcontrolv1beta1.New(c)\n\tcs.flowcontrolV1beta2 = flowcontrolv1beta2.New(c)\n\tcs.flowcontrolV1beta3 = flowcontrolv1beta3.New(c)\n\tcs.networkingV1 = networkingv1.New(c)\n\tcs.networkingV1alpha1 = networkingv1alpha1.New(c)\n\tcs.networkingV1beta1 = networkingv1beta1.New(c)\n\tcs.nodeV1 = nodev1.New(c)\n\tcs.nodeV1alpha1 = nodev1alpha1.New(c)\n\tcs.nodeV1beta1 = nodev1beta1.New(c)\n\tcs.policyV1 = policyv1.New(c)\n\tcs.policyV1beta1 = policyv1beta1.New(c)\n\tcs.rbacV1 = rbacv1.New(c)\n\tcs.rbacV1beta1 = rbacv1beta1.New(c)\n\tcs.rbacV1alpha1 = rbacv1alpha1.New(c)\n\tcs.resourceV1alpha2 = resourcev1alpha2.New(c)\n\tcs.schedulingV1alpha1 = schedulingv1alpha1.New(c)\n\tcs.schedulingV1beta1 = schedulingv1beta1.New(c)\n\tcs.schedulingV1 = schedulingv1.New(c)\n\tcs.storageV1beta1 = storagev1beta1.New(c)\n\tcs.storageV1 = storagev1.New(c)\n\tcs.storageV1alpha1 = storagev1alpha1.New(c)\n\n\tcs.DiscoveryClient = discovery.NewDiscoveryClient(c)\n\treturn \u0026cs\n}","line":{"from":713,"to":770}} {"id":100025961,"name":"init","signature":"func init()","file":"staging/src/k8s.io/client-go/kubernetes/scheme/register.go","code":"func init() {\n\tv1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: \"v1\"})\n\tutilruntime.Must(AddToScheme(Scheme))\n}","line":{"from":153,"to":156}} {"id":100025962,"name":"MutatingWebhookConfigurations","signature":"func (c *AdmissionregistrationV1Client) MutatingWebhookConfigurations() MutatingWebhookConfigurationInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/admissionregistration_client.go","code":"func (c *AdmissionregistrationV1Client) MutatingWebhookConfigurations() MutatingWebhookConfigurationInterface {\n\treturn newMutatingWebhookConfigurations(c)\n}","line":{"from":40,"to":42}} {"id":100025963,"name":"ValidatingWebhookConfigurations","signature":"func (c *AdmissionregistrationV1Client) ValidatingWebhookConfigurations() ValidatingWebhookConfigurationInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/admissionregistration_client.go","code":"func (c *AdmissionregistrationV1Client) ValidatingWebhookConfigurations() ValidatingWebhookConfigurationInterface {\n\treturn newValidatingWebhookConfigurations(c)\n}","line":{"from":44,"to":46}} {"id":100025964,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*AdmissionregistrationV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/admissionregistration_client.go","code":"// NewForConfig creates a new AdmissionregistrationV1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*AdmissionregistrationV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":48,"to":61}} {"id":100025965,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AdmissionregistrationV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/admissionregistration_client.go","code":"// NewForConfigAndClient creates a new AdmissionregistrationV1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*AdmissionregistrationV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026AdmissionregistrationV1Client{client}, nil\n}","line":{"from":63,"to":75}} {"id":100025966,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *AdmissionregistrationV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/admissionregistration_client.go","code":"// NewForConfigOrDie creates a new AdmissionregistrationV1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *AdmissionregistrationV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":77,"to":85}} {"id":100025967,"name":"New","signature":"func New(c rest.Interface) *AdmissionregistrationV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/admissionregistration_client.go","code":"// New creates a new AdmissionregistrationV1Client for the given RESTClient.\nfunc New(c rest.Interface) *AdmissionregistrationV1Client {\n\treturn \u0026AdmissionregistrationV1Client{c}\n}","line":{"from":87,"to":90}} {"id":100025968,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/admissionregistration_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":92,"to":103}} {"id":100025969,"name":"RESTClient","signature":"func (c *AdmissionregistrationV1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/admissionregistration_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *AdmissionregistrationV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":105,"to":112}} {"id":100025970,"name":"newMutatingWebhookConfigurations","signature":"func newMutatingWebhookConfigurations(c *AdmissionregistrationV1Client) *mutatingWebhookConfigurations","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// newMutatingWebhookConfigurations returns a MutatingWebhookConfigurations\nfunc newMutatingWebhookConfigurations(c *AdmissionregistrationV1Client) *mutatingWebhookConfigurations {\n\treturn \u0026mutatingWebhookConfigurations{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100025971,"name":"Get","signature":"func (c *mutatingWebhookConfigurations) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.MutatingWebhookConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// Get takes name of the mutatingWebhookConfiguration, and returns the corresponding mutatingWebhookConfiguration object, and an error if there is any.\nfunc (c *mutatingWebhookConfigurations) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.MutatingWebhookConfiguration, err error) {\n\tresult = \u0026v1.MutatingWebhookConfiguration{}\n\terr = c.client.Get().\n\t\tResource(\"mutatingwebhookconfigurations\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100025972,"name":"List","signature":"func (c *mutatingWebhookConfigurations) List(ctx context.Context, opts metav1.ListOptions) (result *v1.MutatingWebhookConfigurationList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// List takes label and field selectors, and returns the list of MutatingWebhookConfigurations that match those selectors.\nfunc (c *mutatingWebhookConfigurations) List(ctx context.Context, opts metav1.ListOptions) (result *v1.MutatingWebhookConfigurationList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.MutatingWebhookConfigurationList{}\n\terr = c.client.Get().\n\t\tResource(\"mutatingwebhookconfigurations\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100025973,"name":"Watch","signature":"func (c *mutatingWebhookConfigurations) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// Watch returns a watch.Interface that watches the requested mutatingWebhookConfigurations.\nfunc (c *mutatingWebhookConfigurations) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"mutatingwebhookconfigurations\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100025974,"name":"Create","signature":"func (c *mutatingWebhookConfigurations) Create(ctx context.Context, mutatingWebhookConfiguration *v1.MutatingWebhookConfiguration, opts metav1.CreateOptions) (result *v1.MutatingWebhookConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// Create takes the representation of a mutatingWebhookConfiguration and creates it. Returns the server's representation of the mutatingWebhookConfiguration, and an error, if there is any.\nfunc (c *mutatingWebhookConfigurations) Create(ctx context.Context, mutatingWebhookConfiguration *v1.MutatingWebhookConfiguration, opts metav1.CreateOptions) (result *v1.MutatingWebhookConfiguration, err error) {\n\tresult = \u0026v1.MutatingWebhookConfiguration{}\n\terr = c.client.Post().\n\t\tResource(\"mutatingwebhookconfigurations\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(mutatingWebhookConfiguration).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100025975,"name":"Update","signature":"func (c *mutatingWebhookConfigurations) Update(ctx context.Context, mutatingWebhookConfiguration *v1.MutatingWebhookConfiguration, opts metav1.UpdateOptions) (result *v1.MutatingWebhookConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// Update takes the representation of a mutatingWebhookConfiguration and updates it. Returns the server's representation of the mutatingWebhookConfiguration, and an error, if there is any.\nfunc (c *mutatingWebhookConfigurations) Update(ctx context.Context, mutatingWebhookConfiguration *v1.MutatingWebhookConfiguration, opts metav1.UpdateOptions) (result *v1.MutatingWebhookConfiguration, err error) {\n\tresult = \u0026v1.MutatingWebhookConfiguration{}\n\terr = c.client.Put().\n\t\tResource(\"mutatingwebhookconfigurations\").\n\t\tName(mutatingWebhookConfiguration.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(mutatingWebhookConfiguration).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100025976,"name":"Delete","signature":"func (c *mutatingWebhookConfigurations) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// Delete takes name of the mutatingWebhookConfiguration and deletes it. Returns an error if one occurs.\nfunc (c *mutatingWebhookConfigurations) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"mutatingwebhookconfigurations\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100025977,"name":"DeleteCollection","signature":"func (c *mutatingWebhookConfigurations) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *mutatingWebhookConfigurations) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"mutatingwebhookconfigurations\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100025978,"name":"Patch","signature":"func (c *mutatingWebhookConfigurations) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.MutatingWebhookConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// Patch applies the patch and returns the patched mutatingWebhookConfiguration.\nfunc (c *mutatingWebhookConfigurations) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.MutatingWebhookConfiguration, err error) {\n\tresult = \u0026v1.MutatingWebhookConfiguration{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"mutatingwebhookconfigurations\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100025979,"name":"Apply","signature":"func (c *mutatingWebhookConfigurations) Apply(ctx context.Context, mutatingWebhookConfiguration *admissionregistrationv1.MutatingWebhookConfigurationApplyConfiguration, opts metav1.ApplyOptions) (result *v1.MutatingWebhookConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied mutatingWebhookConfiguration.\nfunc (c *mutatingWebhookConfigurations) Apply(ctx context.Context, mutatingWebhookConfiguration *admissionregistrationv1.MutatingWebhookConfigurationApplyConfiguration, opts metav1.ApplyOptions) (result *v1.MutatingWebhookConfiguration, err error) {\n\tif mutatingWebhookConfiguration == nil {\n\t\treturn nil, fmt.Errorf(\"mutatingWebhookConfiguration provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(mutatingWebhookConfiguration)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := mutatingWebhookConfiguration.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"mutatingWebhookConfiguration.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.MutatingWebhookConfiguration{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"mutatingwebhookconfigurations\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100025980,"name":"newValidatingWebhookConfigurations","signature":"func newValidatingWebhookConfigurations(c *AdmissionregistrationV1Client) *validatingWebhookConfigurations","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// newValidatingWebhookConfigurations returns a ValidatingWebhookConfigurations\nfunc newValidatingWebhookConfigurations(c *AdmissionregistrationV1Client) *validatingWebhookConfigurations {\n\treturn \u0026validatingWebhookConfigurations{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100025981,"name":"Get","signature":"func (c *validatingWebhookConfigurations) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ValidatingWebhookConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// Get takes name of the validatingWebhookConfiguration, and returns the corresponding validatingWebhookConfiguration object, and an error if there is any.\nfunc (c *validatingWebhookConfigurations) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ValidatingWebhookConfiguration, err error) {\n\tresult = \u0026v1.ValidatingWebhookConfiguration{}\n\terr = c.client.Get().\n\t\tResource(\"validatingwebhookconfigurations\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100025982,"name":"List","signature":"func (c *validatingWebhookConfigurations) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ValidatingWebhookConfigurationList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// List takes label and field selectors, and returns the list of ValidatingWebhookConfigurations that match those selectors.\nfunc (c *validatingWebhookConfigurations) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ValidatingWebhookConfigurationList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.ValidatingWebhookConfigurationList{}\n\terr = c.client.Get().\n\t\tResource(\"validatingwebhookconfigurations\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100025983,"name":"Watch","signature":"func (c *validatingWebhookConfigurations) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// Watch returns a watch.Interface that watches the requested validatingWebhookConfigurations.\nfunc (c *validatingWebhookConfigurations) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"validatingwebhookconfigurations\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100025984,"name":"Create","signature":"func (c *validatingWebhookConfigurations) Create(ctx context.Context, validatingWebhookConfiguration *v1.ValidatingWebhookConfiguration, opts metav1.CreateOptions) (result *v1.ValidatingWebhookConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// Create takes the representation of a validatingWebhookConfiguration and creates it. Returns the server's representation of the validatingWebhookConfiguration, and an error, if there is any.\nfunc (c *validatingWebhookConfigurations) Create(ctx context.Context, validatingWebhookConfiguration *v1.ValidatingWebhookConfiguration, opts metav1.CreateOptions) (result *v1.ValidatingWebhookConfiguration, err error) {\n\tresult = \u0026v1.ValidatingWebhookConfiguration{}\n\terr = c.client.Post().\n\t\tResource(\"validatingwebhookconfigurations\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(validatingWebhookConfiguration).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100025985,"name":"Update","signature":"func (c *validatingWebhookConfigurations) Update(ctx context.Context, validatingWebhookConfiguration *v1.ValidatingWebhookConfiguration, opts metav1.UpdateOptions) (result *v1.ValidatingWebhookConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// Update takes the representation of a validatingWebhookConfiguration and updates it. Returns the server's representation of the validatingWebhookConfiguration, and an error, if there is any.\nfunc (c *validatingWebhookConfigurations) Update(ctx context.Context, validatingWebhookConfiguration *v1.ValidatingWebhookConfiguration, opts metav1.UpdateOptions) (result *v1.ValidatingWebhookConfiguration, err error) {\n\tresult = \u0026v1.ValidatingWebhookConfiguration{}\n\terr = c.client.Put().\n\t\tResource(\"validatingwebhookconfigurations\").\n\t\tName(validatingWebhookConfiguration.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(validatingWebhookConfiguration).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100025986,"name":"Delete","signature":"func (c *validatingWebhookConfigurations) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// Delete takes name of the validatingWebhookConfiguration and deletes it. Returns an error if one occurs.\nfunc (c *validatingWebhookConfigurations) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"validatingwebhookconfigurations\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100025987,"name":"DeleteCollection","signature":"func (c *validatingWebhookConfigurations) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *validatingWebhookConfigurations) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"validatingwebhookconfigurations\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100025988,"name":"Patch","signature":"func (c *validatingWebhookConfigurations) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ValidatingWebhookConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// Patch applies the patch and returns the patched validatingWebhookConfiguration.\nfunc (c *validatingWebhookConfigurations) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ValidatingWebhookConfiguration, err error) {\n\tresult = \u0026v1.ValidatingWebhookConfiguration{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"validatingwebhookconfigurations\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100025989,"name":"Apply","signature":"func (c *validatingWebhookConfigurations) Apply(ctx context.Context, validatingWebhookConfiguration *admissionregistrationv1.ValidatingWebhookConfigurationApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ValidatingWebhookConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied validatingWebhookConfiguration.\nfunc (c *validatingWebhookConfigurations) Apply(ctx context.Context, validatingWebhookConfiguration *admissionregistrationv1.ValidatingWebhookConfigurationApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ValidatingWebhookConfiguration, err error) {\n\tif validatingWebhookConfiguration == nil {\n\t\treturn nil, fmt.Errorf(\"validatingWebhookConfiguration provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(validatingWebhookConfiguration)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := validatingWebhookConfiguration.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"validatingWebhookConfiguration.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.ValidatingWebhookConfiguration{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"validatingwebhookconfigurations\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100025990,"name":"ValidatingAdmissionPolicies","signature":"func (c *AdmissionregistrationV1alpha1Client) ValidatingAdmissionPolicies() ValidatingAdmissionPolicyInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/admissionregistration_client.go","code":"func (c *AdmissionregistrationV1alpha1Client) ValidatingAdmissionPolicies() ValidatingAdmissionPolicyInterface {\n\treturn newValidatingAdmissionPolicies(c)\n}","line":{"from":40,"to":42}} {"id":100025991,"name":"ValidatingAdmissionPolicyBindings","signature":"func (c *AdmissionregistrationV1alpha1Client) ValidatingAdmissionPolicyBindings() ValidatingAdmissionPolicyBindingInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/admissionregistration_client.go","code":"func (c *AdmissionregistrationV1alpha1Client) ValidatingAdmissionPolicyBindings() ValidatingAdmissionPolicyBindingInterface {\n\treturn newValidatingAdmissionPolicyBindings(c)\n}","line":{"from":44,"to":46}} {"id":100025992,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*AdmissionregistrationV1alpha1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/admissionregistration_client.go","code":"// NewForConfig creates a new AdmissionregistrationV1alpha1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*AdmissionregistrationV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":48,"to":61}} {"id":100025993,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AdmissionregistrationV1alpha1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/admissionregistration_client.go","code":"// NewForConfigAndClient creates a new AdmissionregistrationV1alpha1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*AdmissionregistrationV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026AdmissionregistrationV1alpha1Client{client}, nil\n}","line":{"from":63,"to":75}} {"id":100025994,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *AdmissionregistrationV1alpha1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/admissionregistration_client.go","code":"// NewForConfigOrDie creates a new AdmissionregistrationV1alpha1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *AdmissionregistrationV1alpha1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":77,"to":85}} {"id":100025995,"name":"New","signature":"func New(c rest.Interface) *AdmissionregistrationV1alpha1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/admissionregistration_client.go","code":"// New creates a new AdmissionregistrationV1alpha1Client for the given RESTClient.\nfunc New(c rest.Interface) *AdmissionregistrationV1alpha1Client {\n\treturn \u0026AdmissionregistrationV1alpha1Client{c}\n}","line":{"from":87,"to":90}} {"id":100025996,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/admissionregistration_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1alpha1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":92,"to":103}} {"id":100025997,"name":"RESTClient","signature":"func (c *AdmissionregistrationV1alpha1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/admissionregistration_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *AdmissionregistrationV1alpha1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":105,"to":112}} {"id":100025998,"name":"newValidatingAdmissionPolicies","signature":"func newValidatingAdmissionPolicies(c *AdmissionregistrationV1alpha1Client) *validatingAdmissionPolicies","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// newValidatingAdmissionPolicies returns a ValidatingAdmissionPolicies\nfunc newValidatingAdmissionPolicies(c *AdmissionregistrationV1alpha1Client) *validatingAdmissionPolicies {\n\treturn \u0026validatingAdmissionPolicies{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":63,"to":68}} {"id":100025999,"name":"Get","signature":"func (c *validatingAdmissionPolicies) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.ValidatingAdmissionPolicy, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// Get takes name of the validatingAdmissionPolicy, and returns the corresponding validatingAdmissionPolicy object, and an error if there is any.\nfunc (c *validatingAdmissionPolicies) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.ValidatingAdmissionPolicy, err error) {\n\tresult = \u0026v1alpha1.ValidatingAdmissionPolicy{}\n\terr = c.client.Get().\n\t\tResource(\"validatingadmissionpolicies\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":80}} {"id":100026000,"name":"List","signature":"func (c *validatingAdmissionPolicies) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.ValidatingAdmissionPolicyList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// List takes label and field selectors, and returns the list of ValidatingAdmissionPolicies that match those selectors.\nfunc (c *validatingAdmissionPolicies) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.ValidatingAdmissionPolicyList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1alpha1.ValidatingAdmissionPolicyList{}\n\terr = c.client.Get().\n\t\tResource(\"validatingadmissionpolicies\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":82,"to":96}} {"id":100026001,"name":"Watch","signature":"func (c *validatingAdmissionPolicies) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// Watch returns a watch.Interface that watches the requested validatingAdmissionPolicies.\nfunc (c *validatingAdmissionPolicies) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"validatingadmissionpolicies\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":98,"to":110}} {"id":100026002,"name":"Create","signature":"func (c *validatingAdmissionPolicies) Create(ctx context.Context, validatingAdmissionPolicy *v1alpha1.ValidatingAdmissionPolicy, opts v1.CreateOptions) (result *v1alpha1.ValidatingAdmissionPolicy, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// Create takes the representation of a validatingAdmissionPolicy and creates it. Returns the server's representation of the validatingAdmissionPolicy, and an error, if there is any.\nfunc (c *validatingAdmissionPolicies) Create(ctx context.Context, validatingAdmissionPolicy *v1alpha1.ValidatingAdmissionPolicy, opts v1.CreateOptions) (result *v1alpha1.ValidatingAdmissionPolicy, err error) {\n\tresult = \u0026v1alpha1.ValidatingAdmissionPolicy{}\n\terr = c.client.Post().\n\t\tResource(\"validatingadmissionpolicies\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(validatingAdmissionPolicy).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":112,"to":122}} {"id":100026003,"name":"Update","signature":"func (c *validatingAdmissionPolicies) Update(ctx context.Context, validatingAdmissionPolicy *v1alpha1.ValidatingAdmissionPolicy, opts v1.UpdateOptions) (result *v1alpha1.ValidatingAdmissionPolicy, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// Update takes the representation of a validatingAdmissionPolicy and updates it. Returns the server's representation of the validatingAdmissionPolicy, and an error, if there is any.\nfunc (c *validatingAdmissionPolicies) Update(ctx context.Context, validatingAdmissionPolicy *v1alpha1.ValidatingAdmissionPolicy, opts v1.UpdateOptions) (result *v1alpha1.ValidatingAdmissionPolicy, err error) {\n\tresult = \u0026v1alpha1.ValidatingAdmissionPolicy{}\n\terr = c.client.Put().\n\t\tResource(\"validatingadmissionpolicies\").\n\t\tName(validatingAdmissionPolicy.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(validatingAdmissionPolicy).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":124,"to":135}} {"id":100026004,"name":"UpdateStatus","signature":"func (c *validatingAdmissionPolicies) UpdateStatus(ctx context.Context, validatingAdmissionPolicy *v1alpha1.ValidatingAdmissionPolicy, opts v1.UpdateOptions) (result *v1alpha1.ValidatingAdmissionPolicy, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *validatingAdmissionPolicies) UpdateStatus(ctx context.Context, validatingAdmissionPolicy *v1alpha1.ValidatingAdmissionPolicy, opts v1.UpdateOptions) (result *v1alpha1.ValidatingAdmissionPolicy, err error) {\n\tresult = \u0026v1alpha1.ValidatingAdmissionPolicy{}\n\terr = c.client.Put().\n\t\tResource(\"validatingadmissionpolicies\").\n\t\tName(validatingAdmissionPolicy.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(validatingAdmissionPolicy).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":137,"to":150}} {"id":100026005,"name":"Delete","signature":"func (c *validatingAdmissionPolicies) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// Delete takes name of the validatingAdmissionPolicy and deletes it. Returns an error if one occurs.\nfunc (c *validatingAdmissionPolicies) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"validatingadmissionpolicies\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":152,"to":160}} {"id":100026006,"name":"DeleteCollection","signature":"func (c *validatingAdmissionPolicies) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *validatingAdmissionPolicies) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"validatingadmissionpolicies\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":162,"to":175}} {"id":100026007,"name":"Patch","signature":"func (c *validatingAdmissionPolicies) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.ValidatingAdmissionPolicy, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// Patch applies the patch and returns the patched validatingAdmissionPolicy.\nfunc (c *validatingAdmissionPolicies) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.ValidatingAdmissionPolicy, err error) {\n\tresult = \u0026v1alpha1.ValidatingAdmissionPolicy{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"validatingadmissionpolicies\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":177,"to":189}} {"id":100026008,"name":"Apply","signature":"func (c *validatingAdmissionPolicies) Apply(ctx context.Context, validatingAdmissionPolicy *admissionregistrationv1alpha1.ValidatingAdmissionPolicyApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.ValidatingAdmissionPolicy, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied validatingAdmissionPolicy.\nfunc (c *validatingAdmissionPolicies) Apply(ctx context.Context, validatingAdmissionPolicy *admissionregistrationv1alpha1.ValidatingAdmissionPolicyApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.ValidatingAdmissionPolicy, err error) {\n\tif validatingAdmissionPolicy == nil {\n\t\treturn nil, fmt.Errorf(\"validatingAdmissionPolicy provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(validatingAdmissionPolicy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := validatingAdmissionPolicy.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"validatingAdmissionPolicy.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1alpha1.ValidatingAdmissionPolicy{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"validatingadmissionpolicies\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":191,"to":214}} {"id":100026009,"name":"ApplyStatus","signature":"func (c *validatingAdmissionPolicies) ApplyStatus(ctx context.Context, validatingAdmissionPolicy *admissionregistrationv1alpha1.ValidatingAdmissionPolicyApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.ValidatingAdmissionPolicy, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *validatingAdmissionPolicies) ApplyStatus(ctx context.Context, validatingAdmissionPolicy *admissionregistrationv1alpha1.ValidatingAdmissionPolicyApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.ValidatingAdmissionPolicy, err error) {\n\tif validatingAdmissionPolicy == nil {\n\t\treturn nil, fmt.Errorf(\"validatingAdmissionPolicy provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(validatingAdmissionPolicy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := validatingAdmissionPolicy.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"validatingAdmissionPolicy.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1alpha1.ValidatingAdmissionPolicy{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"validatingadmissionpolicies\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":216,"to":243}} {"id":100026010,"name":"newValidatingAdmissionPolicyBindings","signature":"func newValidatingAdmissionPolicyBindings(c *AdmissionregistrationV1alpha1Client) *validatingAdmissionPolicyBindings","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// newValidatingAdmissionPolicyBindings returns a ValidatingAdmissionPolicyBindings\nfunc newValidatingAdmissionPolicyBindings(c *AdmissionregistrationV1alpha1Client) *validatingAdmissionPolicyBindings {\n\treturn \u0026validatingAdmissionPolicyBindings{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100026011,"name":"Get","signature":"func (c *validatingAdmissionPolicyBindings) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.ValidatingAdmissionPolicyBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// Get takes name of the validatingAdmissionPolicyBinding, and returns the corresponding validatingAdmissionPolicyBinding object, and an error if there is any.\nfunc (c *validatingAdmissionPolicyBindings) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.ValidatingAdmissionPolicyBinding, err error) {\n\tresult = \u0026v1alpha1.ValidatingAdmissionPolicyBinding{}\n\terr = c.client.Get().\n\t\tResource(\"validatingadmissionpolicybindings\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100026012,"name":"List","signature":"func (c *validatingAdmissionPolicyBindings) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.ValidatingAdmissionPolicyBindingList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// List takes label and field selectors, and returns the list of ValidatingAdmissionPolicyBindings that match those selectors.\nfunc (c *validatingAdmissionPolicyBindings) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.ValidatingAdmissionPolicyBindingList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1alpha1.ValidatingAdmissionPolicyBindingList{}\n\terr = c.client.Get().\n\t\tResource(\"validatingadmissionpolicybindings\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100026013,"name":"Watch","signature":"func (c *validatingAdmissionPolicyBindings) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// Watch returns a watch.Interface that watches the requested validatingAdmissionPolicyBindings.\nfunc (c *validatingAdmissionPolicyBindings) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"validatingadmissionpolicybindings\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100026014,"name":"Create","signature":"func (c *validatingAdmissionPolicyBindings) Create(ctx context.Context, validatingAdmissionPolicyBinding *v1alpha1.ValidatingAdmissionPolicyBinding, opts v1.CreateOptions) (result *v1alpha1.ValidatingAdmissionPolicyBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// Create takes the representation of a validatingAdmissionPolicyBinding and creates it. Returns the server's representation of the validatingAdmissionPolicyBinding, and an error, if there is any.\nfunc (c *validatingAdmissionPolicyBindings) Create(ctx context.Context, validatingAdmissionPolicyBinding *v1alpha1.ValidatingAdmissionPolicyBinding, opts v1.CreateOptions) (result *v1alpha1.ValidatingAdmissionPolicyBinding, err error) {\n\tresult = \u0026v1alpha1.ValidatingAdmissionPolicyBinding{}\n\terr = c.client.Post().\n\t\tResource(\"validatingadmissionpolicybindings\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(validatingAdmissionPolicyBinding).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100026015,"name":"Update","signature":"func (c *validatingAdmissionPolicyBindings) Update(ctx context.Context, validatingAdmissionPolicyBinding *v1alpha1.ValidatingAdmissionPolicyBinding, opts v1.UpdateOptions) (result *v1alpha1.ValidatingAdmissionPolicyBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// Update takes the representation of a validatingAdmissionPolicyBinding and updates it. Returns the server's representation of the validatingAdmissionPolicyBinding, and an error, if there is any.\nfunc (c *validatingAdmissionPolicyBindings) Update(ctx context.Context, validatingAdmissionPolicyBinding *v1alpha1.ValidatingAdmissionPolicyBinding, opts v1.UpdateOptions) (result *v1alpha1.ValidatingAdmissionPolicyBinding, err error) {\n\tresult = \u0026v1alpha1.ValidatingAdmissionPolicyBinding{}\n\terr = c.client.Put().\n\t\tResource(\"validatingadmissionpolicybindings\").\n\t\tName(validatingAdmissionPolicyBinding.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(validatingAdmissionPolicyBinding).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100026016,"name":"Delete","signature":"func (c *validatingAdmissionPolicyBindings) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// Delete takes name of the validatingAdmissionPolicyBinding and deletes it. Returns an error if one occurs.\nfunc (c *validatingAdmissionPolicyBindings) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"validatingadmissionpolicybindings\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100026017,"name":"DeleteCollection","signature":"func (c *validatingAdmissionPolicyBindings) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *validatingAdmissionPolicyBindings) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"validatingadmissionpolicybindings\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100026018,"name":"Patch","signature":"func (c *validatingAdmissionPolicyBindings) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.ValidatingAdmissionPolicyBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// Patch applies the patch and returns the patched validatingAdmissionPolicyBinding.\nfunc (c *validatingAdmissionPolicyBindings) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.ValidatingAdmissionPolicyBinding, err error) {\n\tresult = \u0026v1alpha1.ValidatingAdmissionPolicyBinding{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"validatingadmissionpolicybindings\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100026019,"name":"Apply","signature":"func (c *validatingAdmissionPolicyBindings) Apply(ctx context.Context, validatingAdmissionPolicyBinding *admissionregistrationv1alpha1.ValidatingAdmissionPolicyBindingApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.ValidatingAdmissionPolicyBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied validatingAdmissionPolicyBinding.\nfunc (c *validatingAdmissionPolicyBindings) Apply(ctx context.Context, validatingAdmissionPolicyBinding *admissionregistrationv1alpha1.ValidatingAdmissionPolicyBindingApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.ValidatingAdmissionPolicyBinding, err error) {\n\tif validatingAdmissionPolicyBinding == nil {\n\t\treturn nil, fmt.Errorf(\"validatingAdmissionPolicyBinding provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(validatingAdmissionPolicyBinding)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := validatingAdmissionPolicyBinding.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"validatingAdmissionPolicyBinding.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1alpha1.ValidatingAdmissionPolicyBinding{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"validatingadmissionpolicybindings\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100026020,"name":"MutatingWebhookConfigurations","signature":"func (c *AdmissionregistrationV1beta1Client) MutatingWebhookConfigurations() MutatingWebhookConfigurationInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/admissionregistration_client.go","code":"func (c *AdmissionregistrationV1beta1Client) MutatingWebhookConfigurations() MutatingWebhookConfigurationInterface {\n\treturn newMutatingWebhookConfigurations(c)\n}","line":{"from":40,"to":42}} {"id":100026021,"name":"ValidatingWebhookConfigurations","signature":"func (c *AdmissionregistrationV1beta1Client) ValidatingWebhookConfigurations() ValidatingWebhookConfigurationInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/admissionregistration_client.go","code":"func (c *AdmissionregistrationV1beta1Client) ValidatingWebhookConfigurations() ValidatingWebhookConfigurationInterface {\n\treturn newValidatingWebhookConfigurations(c)\n}","line":{"from":44,"to":46}} {"id":100026022,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*AdmissionregistrationV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/admissionregistration_client.go","code":"// NewForConfig creates a new AdmissionregistrationV1beta1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*AdmissionregistrationV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":48,"to":61}} {"id":100026023,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AdmissionregistrationV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/admissionregistration_client.go","code":"// NewForConfigAndClient creates a new AdmissionregistrationV1beta1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*AdmissionregistrationV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026AdmissionregistrationV1beta1Client{client}, nil\n}","line":{"from":63,"to":75}} {"id":100026024,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *AdmissionregistrationV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/admissionregistration_client.go","code":"// NewForConfigOrDie creates a new AdmissionregistrationV1beta1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *AdmissionregistrationV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":77,"to":85}} {"id":100026025,"name":"New","signature":"func New(c rest.Interface) *AdmissionregistrationV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/admissionregistration_client.go","code":"// New creates a new AdmissionregistrationV1beta1Client for the given RESTClient.\nfunc New(c rest.Interface) *AdmissionregistrationV1beta1Client {\n\treturn \u0026AdmissionregistrationV1beta1Client{c}\n}","line":{"from":87,"to":90}} {"id":100026026,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/admissionregistration_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":92,"to":103}} {"id":100026027,"name":"RESTClient","signature":"func (c *AdmissionregistrationV1beta1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/admissionregistration_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *AdmissionregistrationV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":105,"to":112}} {"id":100026028,"name":"newMutatingWebhookConfigurations","signature":"func newMutatingWebhookConfigurations(c *AdmissionregistrationV1beta1Client) *mutatingWebhookConfigurations","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// newMutatingWebhookConfigurations returns a MutatingWebhookConfigurations\nfunc newMutatingWebhookConfigurations(c *AdmissionregistrationV1beta1Client) *mutatingWebhookConfigurations {\n\treturn \u0026mutatingWebhookConfigurations{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100026029,"name":"Get","signature":"func (c *mutatingWebhookConfigurations) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.MutatingWebhookConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// Get takes name of the mutatingWebhookConfiguration, and returns the corresponding mutatingWebhookConfiguration object, and an error if there is any.\nfunc (c *mutatingWebhookConfigurations) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.MutatingWebhookConfiguration, err error) {\n\tresult = \u0026v1beta1.MutatingWebhookConfiguration{}\n\terr = c.client.Get().\n\t\tResource(\"mutatingwebhookconfigurations\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100026030,"name":"List","signature":"func (c *mutatingWebhookConfigurations) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.MutatingWebhookConfigurationList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// List takes label and field selectors, and returns the list of MutatingWebhookConfigurations that match those selectors.\nfunc (c *mutatingWebhookConfigurations) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.MutatingWebhookConfigurationList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.MutatingWebhookConfigurationList{}\n\terr = c.client.Get().\n\t\tResource(\"mutatingwebhookconfigurations\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100026031,"name":"Watch","signature":"func (c *mutatingWebhookConfigurations) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// Watch returns a watch.Interface that watches the requested mutatingWebhookConfigurations.\nfunc (c *mutatingWebhookConfigurations) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"mutatingwebhookconfigurations\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100026032,"name":"Create","signature":"func (c *mutatingWebhookConfigurations) Create(ctx context.Context, mutatingWebhookConfiguration *v1beta1.MutatingWebhookConfiguration, opts v1.CreateOptions) (result *v1beta1.MutatingWebhookConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// Create takes the representation of a mutatingWebhookConfiguration and creates it. Returns the server's representation of the mutatingWebhookConfiguration, and an error, if there is any.\nfunc (c *mutatingWebhookConfigurations) Create(ctx context.Context, mutatingWebhookConfiguration *v1beta1.MutatingWebhookConfiguration, opts v1.CreateOptions) (result *v1beta1.MutatingWebhookConfiguration, err error) {\n\tresult = \u0026v1beta1.MutatingWebhookConfiguration{}\n\terr = c.client.Post().\n\t\tResource(\"mutatingwebhookconfigurations\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(mutatingWebhookConfiguration).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100026033,"name":"Update","signature":"func (c *mutatingWebhookConfigurations) Update(ctx context.Context, mutatingWebhookConfiguration *v1beta1.MutatingWebhookConfiguration, opts v1.UpdateOptions) (result *v1beta1.MutatingWebhookConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// Update takes the representation of a mutatingWebhookConfiguration and updates it. Returns the server's representation of the mutatingWebhookConfiguration, and an error, if there is any.\nfunc (c *mutatingWebhookConfigurations) Update(ctx context.Context, mutatingWebhookConfiguration *v1beta1.MutatingWebhookConfiguration, opts v1.UpdateOptions) (result *v1beta1.MutatingWebhookConfiguration, err error) {\n\tresult = \u0026v1beta1.MutatingWebhookConfiguration{}\n\terr = c.client.Put().\n\t\tResource(\"mutatingwebhookconfigurations\").\n\t\tName(mutatingWebhookConfiguration.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(mutatingWebhookConfiguration).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100026034,"name":"Delete","signature":"func (c *mutatingWebhookConfigurations) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// Delete takes name of the mutatingWebhookConfiguration and deletes it. Returns an error if one occurs.\nfunc (c *mutatingWebhookConfigurations) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"mutatingwebhookconfigurations\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100026035,"name":"DeleteCollection","signature":"func (c *mutatingWebhookConfigurations) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *mutatingWebhookConfigurations) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"mutatingwebhookconfigurations\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100026036,"name":"Patch","signature":"func (c *mutatingWebhookConfigurations) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.MutatingWebhookConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// Patch applies the patch and returns the patched mutatingWebhookConfiguration.\nfunc (c *mutatingWebhookConfigurations) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.MutatingWebhookConfiguration, err error) {\n\tresult = \u0026v1beta1.MutatingWebhookConfiguration{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"mutatingwebhookconfigurations\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100026037,"name":"Apply","signature":"func (c *mutatingWebhookConfigurations) Apply(ctx context.Context, mutatingWebhookConfiguration *admissionregistrationv1beta1.MutatingWebhookConfigurationApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.MutatingWebhookConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied mutatingWebhookConfiguration.\nfunc (c *mutatingWebhookConfigurations) Apply(ctx context.Context, mutatingWebhookConfiguration *admissionregistrationv1beta1.MutatingWebhookConfigurationApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.MutatingWebhookConfiguration, err error) {\n\tif mutatingWebhookConfiguration == nil {\n\t\treturn nil, fmt.Errorf(\"mutatingWebhookConfiguration provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(mutatingWebhookConfiguration)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := mutatingWebhookConfiguration.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"mutatingWebhookConfiguration.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.MutatingWebhookConfiguration{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"mutatingwebhookconfigurations\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100026038,"name":"newValidatingWebhookConfigurations","signature":"func newValidatingWebhookConfigurations(c *AdmissionregistrationV1beta1Client) *validatingWebhookConfigurations","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// newValidatingWebhookConfigurations returns a ValidatingWebhookConfigurations\nfunc newValidatingWebhookConfigurations(c *AdmissionregistrationV1beta1Client) *validatingWebhookConfigurations {\n\treturn \u0026validatingWebhookConfigurations{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100026039,"name":"Get","signature":"func (c *validatingWebhookConfigurations) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.ValidatingWebhookConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// Get takes name of the validatingWebhookConfiguration, and returns the corresponding validatingWebhookConfiguration object, and an error if there is any.\nfunc (c *validatingWebhookConfigurations) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.ValidatingWebhookConfiguration, err error) {\n\tresult = \u0026v1beta1.ValidatingWebhookConfiguration{}\n\terr = c.client.Get().\n\t\tResource(\"validatingwebhookconfigurations\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100026040,"name":"List","signature":"func (c *validatingWebhookConfigurations) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.ValidatingWebhookConfigurationList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// List takes label and field selectors, and returns the list of ValidatingWebhookConfigurations that match those selectors.\nfunc (c *validatingWebhookConfigurations) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.ValidatingWebhookConfigurationList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.ValidatingWebhookConfigurationList{}\n\terr = c.client.Get().\n\t\tResource(\"validatingwebhookconfigurations\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100026041,"name":"Watch","signature":"func (c *validatingWebhookConfigurations) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// Watch returns a watch.Interface that watches the requested validatingWebhookConfigurations.\nfunc (c *validatingWebhookConfigurations) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"validatingwebhookconfigurations\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100026042,"name":"Create","signature":"func (c *validatingWebhookConfigurations) Create(ctx context.Context, validatingWebhookConfiguration *v1beta1.ValidatingWebhookConfiguration, opts v1.CreateOptions) (result *v1beta1.ValidatingWebhookConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// Create takes the representation of a validatingWebhookConfiguration and creates it. Returns the server's representation of the validatingWebhookConfiguration, and an error, if there is any.\nfunc (c *validatingWebhookConfigurations) Create(ctx context.Context, validatingWebhookConfiguration *v1beta1.ValidatingWebhookConfiguration, opts v1.CreateOptions) (result *v1beta1.ValidatingWebhookConfiguration, err error) {\n\tresult = \u0026v1beta1.ValidatingWebhookConfiguration{}\n\terr = c.client.Post().\n\t\tResource(\"validatingwebhookconfigurations\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(validatingWebhookConfiguration).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100026043,"name":"Update","signature":"func (c *validatingWebhookConfigurations) Update(ctx context.Context, validatingWebhookConfiguration *v1beta1.ValidatingWebhookConfiguration, opts v1.UpdateOptions) (result *v1beta1.ValidatingWebhookConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// Update takes the representation of a validatingWebhookConfiguration and updates it. Returns the server's representation of the validatingWebhookConfiguration, and an error, if there is any.\nfunc (c *validatingWebhookConfigurations) Update(ctx context.Context, validatingWebhookConfiguration *v1beta1.ValidatingWebhookConfiguration, opts v1.UpdateOptions) (result *v1beta1.ValidatingWebhookConfiguration, err error) {\n\tresult = \u0026v1beta1.ValidatingWebhookConfiguration{}\n\terr = c.client.Put().\n\t\tResource(\"validatingwebhookconfigurations\").\n\t\tName(validatingWebhookConfiguration.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(validatingWebhookConfiguration).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100026044,"name":"Delete","signature":"func (c *validatingWebhookConfigurations) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// Delete takes name of the validatingWebhookConfiguration and deletes it. Returns an error if one occurs.\nfunc (c *validatingWebhookConfigurations) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"validatingwebhookconfigurations\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100026045,"name":"DeleteCollection","signature":"func (c *validatingWebhookConfigurations) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *validatingWebhookConfigurations) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"validatingwebhookconfigurations\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100026046,"name":"Patch","signature":"func (c *validatingWebhookConfigurations) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.ValidatingWebhookConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// Patch applies the patch and returns the patched validatingWebhookConfiguration.\nfunc (c *validatingWebhookConfigurations) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.ValidatingWebhookConfiguration, err error) {\n\tresult = \u0026v1beta1.ValidatingWebhookConfiguration{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"validatingwebhookconfigurations\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100026047,"name":"Apply","signature":"func (c *validatingWebhookConfigurations) Apply(ctx context.Context, validatingWebhookConfiguration *admissionregistrationv1beta1.ValidatingWebhookConfigurationApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.ValidatingWebhookConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied validatingWebhookConfiguration.\nfunc (c *validatingWebhookConfigurations) Apply(ctx context.Context, validatingWebhookConfiguration *admissionregistrationv1beta1.ValidatingWebhookConfigurationApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.ValidatingWebhookConfiguration, err error) {\n\tif validatingWebhookConfiguration == nil {\n\t\treturn nil, fmt.Errorf(\"validatingWebhookConfiguration provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(validatingWebhookConfiguration)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := validatingWebhookConfiguration.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"validatingWebhookConfiguration.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.ValidatingWebhookConfiguration{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"validatingwebhookconfigurations\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100026048,"name":"StorageVersions","signature":"func (c *InternalV1alpha1Client) StorageVersions() StorageVersionInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/apiserverinternal/v1alpha1/apiserverinternal_client.go","code":"func (c *InternalV1alpha1Client) StorageVersions() StorageVersionInterface {\n\treturn newStorageVersions(c)\n}","line":{"from":39,"to":41}} {"id":100026049,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*InternalV1alpha1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apiserverinternal/v1alpha1/apiserverinternal_client.go","code":"// NewForConfig creates a new InternalV1alpha1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*InternalV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":43,"to":56}} {"id":100026050,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*InternalV1alpha1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apiserverinternal/v1alpha1/apiserverinternal_client.go","code":"// NewForConfigAndClient creates a new InternalV1alpha1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*InternalV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026InternalV1alpha1Client{client}, nil\n}","line":{"from":58,"to":70}} {"id":100026051,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *InternalV1alpha1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/apiserverinternal/v1alpha1/apiserverinternal_client.go","code":"// NewForConfigOrDie creates a new InternalV1alpha1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *InternalV1alpha1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":72,"to":80}} {"id":100026052,"name":"New","signature":"func New(c rest.Interface) *InternalV1alpha1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/apiserverinternal/v1alpha1/apiserverinternal_client.go","code":"// New creates a new InternalV1alpha1Client for the given RESTClient.\nfunc New(c rest.Interface) *InternalV1alpha1Client {\n\treturn \u0026InternalV1alpha1Client{c}\n}","line":{"from":82,"to":85}} {"id":100026053,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apiserverinternal/v1alpha1/apiserverinternal_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1alpha1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":87,"to":98}} {"id":100026054,"name":"RESTClient","signature":"func (c *InternalV1alpha1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/apiserverinternal/v1alpha1/apiserverinternal_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *InternalV1alpha1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":100,"to":107}} {"id":100026055,"name":"newStorageVersions","signature":"func newStorageVersions(c *InternalV1alpha1Client) *storageVersions","file":"staging/src/k8s.io/client-go/kubernetes/typed/apiserverinternal/v1alpha1/storageversion.go","code":"// newStorageVersions returns a StorageVersions\nfunc newStorageVersions(c *InternalV1alpha1Client) *storageVersions {\n\treturn \u0026storageVersions{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":63,"to":68}} {"id":100026056,"name":"Get","signature":"func (c *storageVersions) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.StorageVersion, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apiserverinternal/v1alpha1/storageversion.go","code":"// Get takes name of the storageVersion, and returns the corresponding storageVersion object, and an error if there is any.\nfunc (c *storageVersions) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.StorageVersion, err error) {\n\tresult = \u0026v1alpha1.StorageVersion{}\n\terr = c.client.Get().\n\t\tResource(\"storageversions\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":80}} {"id":100026057,"name":"List","signature":"func (c *storageVersions) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.StorageVersionList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apiserverinternal/v1alpha1/storageversion.go","code":"// List takes label and field selectors, and returns the list of StorageVersions that match those selectors.\nfunc (c *storageVersions) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.StorageVersionList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1alpha1.StorageVersionList{}\n\terr = c.client.Get().\n\t\tResource(\"storageversions\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":82,"to":96}} {"id":100026058,"name":"Watch","signature":"func (c *storageVersions) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apiserverinternal/v1alpha1/storageversion.go","code":"// Watch returns a watch.Interface that watches the requested storageVersions.\nfunc (c *storageVersions) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"storageversions\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":98,"to":110}} {"id":100026059,"name":"Create","signature":"func (c *storageVersions) Create(ctx context.Context, storageVersion *v1alpha1.StorageVersion, opts v1.CreateOptions) (result *v1alpha1.StorageVersion, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apiserverinternal/v1alpha1/storageversion.go","code":"// Create takes the representation of a storageVersion and creates it. Returns the server's representation of the storageVersion, and an error, if there is any.\nfunc (c *storageVersions) Create(ctx context.Context, storageVersion *v1alpha1.StorageVersion, opts v1.CreateOptions) (result *v1alpha1.StorageVersion, err error) {\n\tresult = \u0026v1alpha1.StorageVersion{}\n\terr = c.client.Post().\n\t\tResource(\"storageversions\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(storageVersion).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":112,"to":122}} {"id":100026060,"name":"Update","signature":"func (c *storageVersions) Update(ctx context.Context, storageVersion *v1alpha1.StorageVersion, opts v1.UpdateOptions) (result *v1alpha1.StorageVersion, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apiserverinternal/v1alpha1/storageversion.go","code":"// Update takes the representation of a storageVersion and updates it. Returns the server's representation of the storageVersion, and an error, if there is any.\nfunc (c *storageVersions) Update(ctx context.Context, storageVersion *v1alpha1.StorageVersion, opts v1.UpdateOptions) (result *v1alpha1.StorageVersion, err error) {\n\tresult = \u0026v1alpha1.StorageVersion{}\n\terr = c.client.Put().\n\t\tResource(\"storageversions\").\n\t\tName(storageVersion.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(storageVersion).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":124,"to":135}} {"id":100026061,"name":"UpdateStatus","signature":"func (c *storageVersions) UpdateStatus(ctx context.Context, storageVersion *v1alpha1.StorageVersion, opts v1.UpdateOptions) (result *v1alpha1.StorageVersion, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apiserverinternal/v1alpha1/storageversion.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *storageVersions) UpdateStatus(ctx context.Context, storageVersion *v1alpha1.StorageVersion, opts v1.UpdateOptions) (result *v1alpha1.StorageVersion, err error) {\n\tresult = \u0026v1alpha1.StorageVersion{}\n\terr = c.client.Put().\n\t\tResource(\"storageversions\").\n\t\tName(storageVersion.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(storageVersion).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":137,"to":150}} {"id":100026062,"name":"Delete","signature":"func (c *storageVersions) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apiserverinternal/v1alpha1/storageversion.go","code":"// Delete takes name of the storageVersion and deletes it. Returns an error if one occurs.\nfunc (c *storageVersions) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"storageversions\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":152,"to":160}} {"id":100026063,"name":"DeleteCollection","signature":"func (c *storageVersions) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apiserverinternal/v1alpha1/storageversion.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *storageVersions) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"storageversions\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":162,"to":175}} {"id":100026064,"name":"Patch","signature":"func (c *storageVersions) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.StorageVersion, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apiserverinternal/v1alpha1/storageversion.go","code":"// Patch applies the patch and returns the patched storageVersion.\nfunc (c *storageVersions) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.StorageVersion, err error) {\n\tresult = \u0026v1alpha1.StorageVersion{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"storageversions\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":177,"to":189}} {"id":100026065,"name":"Apply","signature":"func (c *storageVersions) Apply(ctx context.Context, storageVersion *apiserverinternalv1alpha1.StorageVersionApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.StorageVersion, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apiserverinternal/v1alpha1/storageversion.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied storageVersion.\nfunc (c *storageVersions) Apply(ctx context.Context, storageVersion *apiserverinternalv1alpha1.StorageVersionApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.StorageVersion, err error) {\n\tif storageVersion == nil {\n\t\treturn nil, fmt.Errorf(\"storageVersion provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(storageVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := storageVersion.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"storageVersion.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1alpha1.StorageVersion{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"storageversions\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":191,"to":214}} {"id":100026066,"name":"ApplyStatus","signature":"func (c *storageVersions) ApplyStatus(ctx context.Context, storageVersion *apiserverinternalv1alpha1.StorageVersionApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.StorageVersion, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apiserverinternal/v1alpha1/storageversion.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *storageVersions) ApplyStatus(ctx context.Context, storageVersion *apiserverinternalv1alpha1.StorageVersionApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.StorageVersion, err error) {\n\tif storageVersion == nil {\n\t\treturn nil, fmt.Errorf(\"storageVersion provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(storageVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := storageVersion.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"storageVersion.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1alpha1.StorageVersion{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"storageversions\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":216,"to":243}} {"id":100026067,"name":"ControllerRevisions","signature":"func (c *AppsV1Client) ControllerRevisions(namespace string) ControllerRevisionInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/apps_client.go","code":"func (c *AppsV1Client) ControllerRevisions(namespace string) ControllerRevisionInterface {\n\treturn newControllerRevisions(c, namespace)\n}","line":{"from":43,"to":45}} {"id":100026068,"name":"DaemonSets","signature":"func (c *AppsV1Client) DaemonSets(namespace string) DaemonSetInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/apps_client.go","code":"func (c *AppsV1Client) DaemonSets(namespace string) DaemonSetInterface {\n\treturn newDaemonSets(c, namespace)\n}","line":{"from":47,"to":49}} {"id":100026069,"name":"Deployments","signature":"func (c *AppsV1Client) Deployments(namespace string) DeploymentInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/apps_client.go","code":"func (c *AppsV1Client) Deployments(namespace string) DeploymentInterface {\n\treturn newDeployments(c, namespace)\n}","line":{"from":51,"to":53}} {"id":100026070,"name":"ReplicaSets","signature":"func (c *AppsV1Client) ReplicaSets(namespace string) ReplicaSetInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/apps_client.go","code":"func (c *AppsV1Client) ReplicaSets(namespace string) ReplicaSetInterface {\n\treturn newReplicaSets(c, namespace)\n}","line":{"from":55,"to":57}} {"id":100026071,"name":"StatefulSets","signature":"func (c *AppsV1Client) StatefulSets(namespace string) StatefulSetInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/apps_client.go","code":"func (c *AppsV1Client) StatefulSets(namespace string) StatefulSetInterface {\n\treturn newStatefulSets(c, namespace)\n}","line":{"from":59,"to":61}} {"id":100026072,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*AppsV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/apps_client.go","code":"// NewForConfig creates a new AppsV1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*AppsV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":63,"to":76}} {"id":100026073,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AppsV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/apps_client.go","code":"// NewForConfigAndClient creates a new AppsV1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*AppsV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026AppsV1Client{client}, nil\n}","line":{"from":78,"to":90}} {"id":100026074,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *AppsV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/apps_client.go","code":"// NewForConfigOrDie creates a new AppsV1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *AppsV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":92,"to":100}} {"id":100026075,"name":"New","signature":"func New(c rest.Interface) *AppsV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/apps_client.go","code":"// New creates a new AppsV1Client for the given RESTClient.\nfunc New(c rest.Interface) *AppsV1Client {\n\treturn \u0026AppsV1Client{c}\n}","line":{"from":102,"to":105}} {"id":100026076,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/apps_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":107,"to":118}} {"id":100026077,"name":"RESTClient","signature":"func (c *AppsV1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/apps_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *AppsV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":120,"to":127}} {"id":100026078,"name":"newControllerRevisions","signature":"func newControllerRevisions(c *AppsV1Client, namespace string) *controllerRevisions","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/controllerrevision.go","code":"// newControllerRevisions returns a ControllerRevisions\nfunc newControllerRevisions(c *AppsV1Client, namespace string) *controllerRevisions {\n\treturn \u0026controllerRevisions{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":62,"to":68}} {"id":100026079,"name":"Get","signature":"func (c *controllerRevisions) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ControllerRevision, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/controllerrevision.go","code":"// Get takes name of the controllerRevision, and returns the corresponding controllerRevision object, and an error if there is any.\nfunc (c *controllerRevisions) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ControllerRevision, err error) {\n\tresult = \u0026v1.ControllerRevision{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":81}} {"id":100026080,"name":"List","signature":"func (c *controllerRevisions) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ControllerRevisionList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/controllerrevision.go","code":"// List takes label and field selectors, and returns the list of ControllerRevisions that match those selectors.\nfunc (c *controllerRevisions) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ControllerRevisionList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.ControllerRevisionList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":83,"to":98}} {"id":100026081,"name":"Watch","signature":"func (c *controllerRevisions) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/controllerrevision.go","code":"// Watch returns a watch.Interface that watches the requested controllerRevisions.\nfunc (c *controllerRevisions) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":100,"to":113}} {"id":100026082,"name":"Create","signature":"func (c *controllerRevisions) Create(ctx context.Context, controllerRevision *v1.ControllerRevision, opts metav1.CreateOptions) (result *v1.ControllerRevision, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/controllerrevision.go","code":"// Create takes the representation of a controllerRevision and creates it. Returns the server's representation of the controllerRevision, and an error, if there is any.\nfunc (c *controllerRevisions) Create(ctx context.Context, controllerRevision *v1.ControllerRevision, opts metav1.CreateOptions) (result *v1.ControllerRevision, err error) {\n\tresult = \u0026v1.ControllerRevision{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(controllerRevision).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":115,"to":126}} {"id":100026083,"name":"Update","signature":"func (c *controllerRevisions) Update(ctx context.Context, controllerRevision *v1.ControllerRevision, opts metav1.UpdateOptions) (result *v1.ControllerRevision, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/controllerrevision.go","code":"// Update takes the representation of a controllerRevision and updates it. Returns the server's representation of the controllerRevision, and an error, if there is any.\nfunc (c *controllerRevisions) Update(ctx context.Context, controllerRevision *v1.ControllerRevision, opts metav1.UpdateOptions) (result *v1.ControllerRevision, err error) {\n\tresult = \u0026v1.ControllerRevision{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tName(controllerRevision.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(controllerRevision).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":128,"to":140}} {"id":100026084,"name":"Delete","signature":"func (c *controllerRevisions) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/controllerrevision.go","code":"// Delete takes name of the controllerRevision and deletes it. Returns an error if one occurs.\nfunc (c *controllerRevisions) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":142,"to":151}} {"id":100026085,"name":"DeleteCollection","signature":"func (c *controllerRevisions) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/controllerrevision.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *controllerRevisions) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":153,"to":167}} {"id":100026086,"name":"Patch","signature":"func (c *controllerRevisions) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ControllerRevision, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/controllerrevision.go","code":"// Patch applies the patch and returns the patched controllerRevision.\nfunc (c *controllerRevisions) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ControllerRevision, err error) {\n\tresult = \u0026v1.ControllerRevision{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":169,"to":182}} {"id":100026087,"name":"Apply","signature":"func (c *controllerRevisions) Apply(ctx context.Context, controllerRevision *appsv1.ControllerRevisionApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ControllerRevision, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/controllerrevision.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied controllerRevision.\nfunc (c *controllerRevisions) Apply(ctx context.Context, controllerRevision *appsv1.ControllerRevisionApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ControllerRevision, err error) {\n\tif controllerRevision == nil {\n\t\treturn nil, fmt.Errorf(\"controllerRevision provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(controllerRevision)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := controllerRevision.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"controllerRevision.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.ControllerRevision{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":184,"to":208}} {"id":100026088,"name":"newDaemonSets","signature":"func newDaemonSets(c *AppsV1Client, namespace string) *daemonSets","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/daemonset.go","code":"// newDaemonSets returns a DaemonSets\nfunc newDaemonSets(c *AppsV1Client, namespace string) *daemonSets {\n\treturn \u0026daemonSets{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":64,"to":70}} {"id":100026089,"name":"Get","signature":"func (c *daemonSets) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/daemonset.go","code":"// Get takes name of the daemonSet, and returns the corresponding daemonSet object, and an error if there is any.\nfunc (c *daemonSets) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.DaemonSet, err error) {\n\tresult = \u0026v1.DaemonSet{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":72,"to":83}} {"id":100026090,"name":"List","signature":"func (c *daemonSets) List(ctx context.Context, opts metav1.ListOptions) (result *v1.DaemonSetList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/daemonset.go","code":"// List takes label and field selectors, and returns the list of DaemonSets that match those selectors.\nfunc (c *daemonSets) List(ctx context.Context, opts metav1.ListOptions) (result *v1.DaemonSetList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.DaemonSetList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":85,"to":100}} {"id":100026091,"name":"Watch","signature":"func (c *daemonSets) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/daemonset.go","code":"// Watch returns a watch.Interface that watches the requested daemonSets.\nfunc (c *daemonSets) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":102,"to":115}} {"id":100026092,"name":"Create","signature":"func (c *daemonSets) Create(ctx context.Context, daemonSet *v1.DaemonSet, opts metav1.CreateOptions) (result *v1.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/daemonset.go","code":"// Create takes the representation of a daemonSet and creates it. Returns the server's representation of the daemonSet, and an error, if there is any.\nfunc (c *daemonSets) Create(ctx context.Context, daemonSet *v1.DaemonSet, opts metav1.CreateOptions) (result *v1.DaemonSet, err error) {\n\tresult = \u0026v1.DaemonSet{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(daemonSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":117,"to":128}} {"id":100026093,"name":"Update","signature":"func (c *daemonSets) Update(ctx context.Context, daemonSet *v1.DaemonSet, opts metav1.UpdateOptions) (result *v1.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/daemonset.go","code":"// Update takes the representation of a daemonSet and updates it. Returns the server's representation of the daemonSet, and an error, if there is any.\nfunc (c *daemonSets) Update(ctx context.Context, daemonSet *v1.DaemonSet, opts metav1.UpdateOptions) (result *v1.DaemonSet, err error) {\n\tresult = \u0026v1.DaemonSet{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tName(daemonSet.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(daemonSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":130,"to":142}} {"id":100026094,"name":"UpdateStatus","signature":"func (c *daemonSets) UpdateStatus(ctx context.Context, daemonSet *v1.DaemonSet, opts metav1.UpdateOptions) (result *v1.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/daemonset.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *daemonSets) UpdateStatus(ctx context.Context, daemonSet *v1.DaemonSet, opts metav1.UpdateOptions) (result *v1.DaemonSet, err error) {\n\tresult = \u0026v1.DaemonSet{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tName(daemonSet.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(daemonSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":144,"to":158}} {"id":100026095,"name":"Delete","signature":"func (c *daemonSets) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/daemonset.go","code":"// Delete takes name of the daemonSet and deletes it. Returns an error if one occurs.\nfunc (c *daemonSets) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":160,"to":169}} {"id":100026096,"name":"DeleteCollection","signature":"func (c *daemonSets) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/daemonset.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *daemonSets) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":171,"to":185}} {"id":100026097,"name":"Patch","signature":"func (c *daemonSets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/daemonset.go","code":"// Patch applies the patch and returns the patched daemonSet.\nfunc (c *daemonSets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.DaemonSet, err error) {\n\tresult = \u0026v1.DaemonSet{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":187,"to":200}} {"id":100026098,"name":"Apply","signature":"func (c *daemonSets) Apply(ctx context.Context, daemonSet *appsv1.DaemonSetApplyConfiguration, opts metav1.ApplyOptions) (result *v1.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/daemonset.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied daemonSet.\nfunc (c *daemonSets) Apply(ctx context.Context, daemonSet *appsv1.DaemonSetApplyConfiguration, opts metav1.ApplyOptions) (result *v1.DaemonSet, err error) {\n\tif daemonSet == nil {\n\t\treturn nil, fmt.Errorf(\"daemonSet provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(daemonSet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := daemonSet.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"daemonSet.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.DaemonSet{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":202,"to":226}} {"id":100026099,"name":"ApplyStatus","signature":"func (c *daemonSets) ApplyStatus(ctx context.Context, daemonSet *appsv1.DaemonSetApplyConfiguration, opts metav1.ApplyOptions) (result *v1.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/daemonset.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *daemonSets) ApplyStatus(ctx context.Context, daemonSet *appsv1.DaemonSetApplyConfiguration, opts metav1.ApplyOptions) (result *v1.DaemonSet, err error) {\n\tif daemonSet == nil {\n\t\treturn nil, fmt.Errorf(\"daemonSet provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(daemonSet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := daemonSet.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"daemonSet.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1.DaemonSet{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":228,"to":256}} {"id":100026100,"name":"newDeployments","signature":"func newDeployments(c *AppsV1Client, namespace string) *deployments","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/deployment.go","code":"// newDeployments returns a Deployments\nfunc newDeployments(c *AppsV1Client, namespace string) *deployments {\n\treturn \u0026deployments{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":70,"to":76}} {"id":100026101,"name":"Get","signature":"func (c *deployments) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/deployment.go","code":"// Get takes name of the deployment, and returns the corresponding deployment object, and an error if there is any.\nfunc (c *deployments) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Deployment, err error) {\n\tresult = \u0026v1.Deployment{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":78,"to":89}} {"id":100026102,"name":"List","signature":"func (c *deployments) List(ctx context.Context, opts metav1.ListOptions) (result *v1.DeploymentList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/deployment.go","code":"// List takes label and field selectors, and returns the list of Deployments that match those selectors.\nfunc (c *deployments) List(ctx context.Context, opts metav1.ListOptions) (result *v1.DeploymentList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.DeploymentList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":91,"to":106}} {"id":100026103,"name":"Watch","signature":"func (c *deployments) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/deployment.go","code":"// Watch returns a watch.Interface that watches the requested deployments.\nfunc (c *deployments) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":108,"to":121}} {"id":100026104,"name":"Create","signature":"func (c *deployments) Create(ctx context.Context, deployment *v1.Deployment, opts metav1.CreateOptions) (result *v1.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/deployment.go","code":"// Create takes the representation of a deployment and creates it. Returns the server's representation of the deployment, and an error, if there is any.\nfunc (c *deployments) Create(ctx context.Context, deployment *v1.Deployment, opts metav1.CreateOptions) (result *v1.Deployment, err error) {\n\tresult = \u0026v1.Deployment{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(deployment).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":123,"to":134}} {"id":100026105,"name":"Update","signature":"func (c *deployments) Update(ctx context.Context, deployment *v1.Deployment, opts metav1.UpdateOptions) (result *v1.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/deployment.go","code":"// Update takes the representation of a deployment and updates it. Returns the server's representation of the deployment, and an error, if there is any.\nfunc (c *deployments) Update(ctx context.Context, deployment *v1.Deployment, opts metav1.UpdateOptions) (result *v1.Deployment, err error) {\n\tresult = \u0026v1.Deployment{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(deployment.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(deployment).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":136,"to":148}} {"id":100026106,"name":"UpdateStatus","signature":"func (c *deployments) UpdateStatus(ctx context.Context, deployment *v1.Deployment, opts metav1.UpdateOptions) (result *v1.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/deployment.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *deployments) UpdateStatus(ctx context.Context, deployment *v1.Deployment, opts metav1.UpdateOptions) (result *v1.Deployment, err error) {\n\tresult = \u0026v1.Deployment{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(deployment.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(deployment).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":150,"to":164}} {"id":100026107,"name":"Delete","signature":"func (c *deployments) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/deployment.go","code":"// Delete takes name of the deployment and deletes it. Returns an error if one occurs.\nfunc (c *deployments) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":166,"to":175}} {"id":100026108,"name":"DeleteCollection","signature":"func (c *deployments) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/deployment.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *deployments) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":177,"to":191}} {"id":100026109,"name":"Patch","signature":"func (c *deployments) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/deployment.go","code":"// Patch applies the patch and returns the patched deployment.\nfunc (c *deployments) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Deployment, err error) {\n\tresult = \u0026v1.Deployment{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":193,"to":206}} {"id":100026110,"name":"Apply","signature":"func (c *deployments) Apply(ctx context.Context, deployment *appsv1.DeploymentApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/deployment.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied deployment.\nfunc (c *deployments) Apply(ctx context.Context, deployment *appsv1.DeploymentApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Deployment, err error) {\n\tif deployment == nil {\n\t\treturn nil, fmt.Errorf(\"deployment provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(deployment)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := deployment.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"deployment.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.Deployment{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":208,"to":232}} {"id":100026111,"name":"ApplyStatus","signature":"func (c *deployments) ApplyStatus(ctx context.Context, deployment *appsv1.DeploymentApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/deployment.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *deployments) ApplyStatus(ctx context.Context, deployment *appsv1.DeploymentApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Deployment, err error) {\n\tif deployment == nil {\n\t\treturn nil, fmt.Errorf(\"deployment provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(deployment)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := deployment.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"deployment.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1.Deployment{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":234,"to":262}} {"id":100026112,"name":"GetScale","signature":"func (c *deployments) GetScale(ctx context.Context, deploymentName string, options metav1.GetOptions) (result *autoscalingv1.Scale, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/deployment.go","code":"// GetScale takes name of the deployment, and returns the corresponding autoscalingv1.Scale object, and an error if there is any.\nfunc (c *deployments) GetScale(ctx context.Context, deploymentName string, options metav1.GetOptions) (result *autoscalingv1.Scale, err error) {\n\tresult = \u0026autoscalingv1.Scale{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(deploymentName).\n\t\tSubResource(\"scale\").\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":264,"to":276}} {"id":100026113,"name":"UpdateScale","signature":"func (c *deployments) UpdateScale(ctx context.Context, deploymentName string, scale *autoscalingv1.Scale, opts metav1.UpdateOptions) (result *autoscalingv1.Scale, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/deployment.go","code":"// UpdateScale takes the top resource name and the representation of a scale and updates it. Returns the server's representation of the scale, and an error, if there is any.\nfunc (c *deployments) UpdateScale(ctx context.Context, deploymentName string, scale *autoscalingv1.Scale, opts metav1.UpdateOptions) (result *autoscalingv1.Scale, err error) {\n\tresult = \u0026autoscalingv1.Scale{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(deploymentName).\n\t\tSubResource(\"scale\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(scale).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":278,"to":291}} {"id":100026114,"name":"ApplyScale","signature":"func (c *deployments) ApplyScale(ctx context.Context, deploymentName string, scale *applyconfigurationsautoscalingv1.ScaleApplyConfiguration, opts metav1.ApplyOptions) (result *autoscalingv1.Scale, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/deployment.go","code":"// ApplyScale takes top resource name and the apply declarative configuration for scale,\n// applies it and returns the applied scale, and an error, if there is any.\nfunc (c *deployments) ApplyScale(ctx context.Context, deploymentName string, scale *applyconfigurationsautoscalingv1.ScaleApplyConfiguration, opts metav1.ApplyOptions) (result *autoscalingv1.Scale, err error) {\n\tif scale == nil {\n\t\treturn nil, fmt.Errorf(\"scale provided to ApplyScale must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(scale)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult = \u0026autoscalingv1.Scale{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(deploymentName).\n\t\tSubResource(\"scale\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":293,"to":316}} {"id":100026115,"name":"newReplicaSets","signature":"func newReplicaSets(c *AppsV1Client, namespace string) *replicaSets","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/replicaset.go","code":"// newReplicaSets returns a ReplicaSets\nfunc newReplicaSets(c *AppsV1Client, namespace string) *replicaSets {\n\treturn \u0026replicaSets{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":70,"to":76}} {"id":100026116,"name":"Get","signature":"func (c *replicaSets) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/replicaset.go","code":"// Get takes name of the replicaSet, and returns the corresponding replicaSet object, and an error if there is any.\nfunc (c *replicaSets) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ReplicaSet, err error) {\n\tresult = \u0026v1.ReplicaSet{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":78,"to":89}} {"id":100026117,"name":"List","signature":"func (c *replicaSets) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ReplicaSetList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/replicaset.go","code":"// List takes label and field selectors, and returns the list of ReplicaSets that match those selectors.\nfunc (c *replicaSets) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ReplicaSetList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.ReplicaSetList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":91,"to":106}} {"id":100026118,"name":"Watch","signature":"func (c *replicaSets) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/replicaset.go","code":"// Watch returns a watch.Interface that watches the requested replicaSets.\nfunc (c *replicaSets) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":108,"to":121}} {"id":100026119,"name":"Create","signature":"func (c *replicaSets) Create(ctx context.Context, replicaSet *v1.ReplicaSet, opts metav1.CreateOptions) (result *v1.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/replicaset.go","code":"// Create takes the representation of a replicaSet and creates it. Returns the server's representation of the replicaSet, and an error, if there is any.\nfunc (c *replicaSets) Create(ctx context.Context, replicaSet *v1.ReplicaSet, opts metav1.CreateOptions) (result *v1.ReplicaSet, err error) {\n\tresult = \u0026v1.ReplicaSet{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(replicaSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":123,"to":134}} {"id":100026120,"name":"Update","signature":"func (c *replicaSets) Update(ctx context.Context, replicaSet *v1.ReplicaSet, opts metav1.UpdateOptions) (result *v1.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/replicaset.go","code":"// Update takes the representation of a replicaSet and updates it. Returns the server's representation of the replicaSet, and an error, if there is any.\nfunc (c *replicaSets) Update(ctx context.Context, replicaSet *v1.ReplicaSet, opts metav1.UpdateOptions) (result *v1.ReplicaSet, err error) {\n\tresult = \u0026v1.ReplicaSet{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(replicaSet.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(replicaSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":136,"to":148}} {"id":100026121,"name":"UpdateStatus","signature":"func (c *replicaSets) UpdateStatus(ctx context.Context, replicaSet *v1.ReplicaSet, opts metav1.UpdateOptions) (result *v1.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/replicaset.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *replicaSets) UpdateStatus(ctx context.Context, replicaSet *v1.ReplicaSet, opts metav1.UpdateOptions) (result *v1.ReplicaSet, err error) {\n\tresult = \u0026v1.ReplicaSet{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(replicaSet.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(replicaSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":150,"to":164}} {"id":100026122,"name":"Delete","signature":"func (c *replicaSets) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/replicaset.go","code":"// Delete takes name of the replicaSet and deletes it. Returns an error if one occurs.\nfunc (c *replicaSets) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":166,"to":175}} {"id":100026123,"name":"DeleteCollection","signature":"func (c *replicaSets) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/replicaset.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *replicaSets) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":177,"to":191}} {"id":100026124,"name":"Patch","signature":"func (c *replicaSets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/replicaset.go","code":"// Patch applies the patch and returns the patched replicaSet.\nfunc (c *replicaSets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ReplicaSet, err error) {\n\tresult = \u0026v1.ReplicaSet{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":193,"to":206}} {"id":100026125,"name":"Apply","signature":"func (c *replicaSets) Apply(ctx context.Context, replicaSet *appsv1.ReplicaSetApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/replicaset.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied replicaSet.\nfunc (c *replicaSets) Apply(ctx context.Context, replicaSet *appsv1.ReplicaSetApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ReplicaSet, err error) {\n\tif replicaSet == nil {\n\t\treturn nil, fmt.Errorf(\"replicaSet provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(replicaSet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := replicaSet.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"replicaSet.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.ReplicaSet{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":208,"to":232}} {"id":100026126,"name":"ApplyStatus","signature":"func (c *replicaSets) ApplyStatus(ctx context.Context, replicaSet *appsv1.ReplicaSetApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/replicaset.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *replicaSets) ApplyStatus(ctx context.Context, replicaSet *appsv1.ReplicaSetApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ReplicaSet, err error) {\n\tif replicaSet == nil {\n\t\treturn nil, fmt.Errorf(\"replicaSet provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(replicaSet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := replicaSet.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"replicaSet.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1.ReplicaSet{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":234,"to":262}} {"id":100026127,"name":"GetScale","signature":"func (c *replicaSets) GetScale(ctx context.Context, replicaSetName string, options metav1.GetOptions) (result *autoscalingv1.Scale, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/replicaset.go","code":"// GetScale takes name of the replicaSet, and returns the corresponding autoscalingv1.Scale object, and an error if there is any.\nfunc (c *replicaSets) GetScale(ctx context.Context, replicaSetName string, options metav1.GetOptions) (result *autoscalingv1.Scale, err error) {\n\tresult = \u0026autoscalingv1.Scale{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(replicaSetName).\n\t\tSubResource(\"scale\").\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":264,"to":276}} {"id":100026128,"name":"UpdateScale","signature":"func (c *replicaSets) UpdateScale(ctx context.Context, replicaSetName string, scale *autoscalingv1.Scale, opts metav1.UpdateOptions) (result *autoscalingv1.Scale, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/replicaset.go","code":"// UpdateScale takes the top resource name and the representation of a scale and updates it. Returns the server's representation of the scale, and an error, if there is any.\nfunc (c *replicaSets) UpdateScale(ctx context.Context, replicaSetName string, scale *autoscalingv1.Scale, opts metav1.UpdateOptions) (result *autoscalingv1.Scale, err error) {\n\tresult = \u0026autoscalingv1.Scale{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(replicaSetName).\n\t\tSubResource(\"scale\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(scale).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":278,"to":291}} {"id":100026129,"name":"ApplyScale","signature":"func (c *replicaSets) ApplyScale(ctx context.Context, replicaSetName string, scale *applyconfigurationsautoscalingv1.ScaleApplyConfiguration, opts metav1.ApplyOptions) (result *autoscalingv1.Scale, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/replicaset.go","code":"// ApplyScale takes top resource name and the apply declarative configuration for scale,\n// applies it and returns the applied scale, and an error, if there is any.\nfunc (c *replicaSets) ApplyScale(ctx context.Context, replicaSetName string, scale *applyconfigurationsautoscalingv1.ScaleApplyConfiguration, opts metav1.ApplyOptions) (result *autoscalingv1.Scale, err error) {\n\tif scale == nil {\n\t\treturn nil, fmt.Errorf(\"scale provided to ApplyScale must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(scale)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult = \u0026autoscalingv1.Scale{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(replicaSetName).\n\t\tSubResource(\"scale\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":293,"to":316}} {"id":100026130,"name":"newStatefulSets","signature":"func newStatefulSets(c *AppsV1Client, namespace string) *statefulSets","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/statefulset.go","code":"// newStatefulSets returns a StatefulSets\nfunc newStatefulSets(c *AppsV1Client, namespace string) *statefulSets {\n\treturn \u0026statefulSets{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":70,"to":76}} {"id":100026131,"name":"Get","signature":"func (c *statefulSets) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/statefulset.go","code":"// Get takes name of the statefulSet, and returns the corresponding statefulSet object, and an error if there is any.\nfunc (c *statefulSets) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.StatefulSet, err error) {\n\tresult = \u0026v1.StatefulSet{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":78,"to":89}} {"id":100026132,"name":"List","signature":"func (c *statefulSets) List(ctx context.Context, opts metav1.ListOptions) (result *v1.StatefulSetList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/statefulset.go","code":"// List takes label and field selectors, and returns the list of StatefulSets that match those selectors.\nfunc (c *statefulSets) List(ctx context.Context, opts metav1.ListOptions) (result *v1.StatefulSetList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.StatefulSetList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":91,"to":106}} {"id":100026133,"name":"Watch","signature":"func (c *statefulSets) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/statefulset.go","code":"// Watch returns a watch.Interface that watches the requested statefulSets.\nfunc (c *statefulSets) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":108,"to":121}} {"id":100026134,"name":"Create","signature":"func (c *statefulSets) Create(ctx context.Context, statefulSet *v1.StatefulSet, opts metav1.CreateOptions) (result *v1.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/statefulset.go","code":"// Create takes the representation of a statefulSet and creates it. Returns the server's representation of the statefulSet, and an error, if there is any.\nfunc (c *statefulSets) Create(ctx context.Context, statefulSet *v1.StatefulSet, opts metav1.CreateOptions) (result *v1.StatefulSet, err error) {\n\tresult = \u0026v1.StatefulSet{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(statefulSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":123,"to":134}} {"id":100026135,"name":"Update","signature":"func (c *statefulSets) Update(ctx context.Context, statefulSet *v1.StatefulSet, opts metav1.UpdateOptions) (result *v1.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/statefulset.go","code":"// Update takes the representation of a statefulSet and updates it. Returns the server's representation of the statefulSet, and an error, if there is any.\nfunc (c *statefulSets) Update(ctx context.Context, statefulSet *v1.StatefulSet, opts metav1.UpdateOptions) (result *v1.StatefulSet, err error) {\n\tresult = \u0026v1.StatefulSet{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(statefulSet.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(statefulSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":136,"to":148}} {"id":100026136,"name":"UpdateStatus","signature":"func (c *statefulSets) UpdateStatus(ctx context.Context, statefulSet *v1.StatefulSet, opts metav1.UpdateOptions) (result *v1.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/statefulset.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *statefulSets) UpdateStatus(ctx context.Context, statefulSet *v1.StatefulSet, opts metav1.UpdateOptions) (result *v1.StatefulSet, err error) {\n\tresult = \u0026v1.StatefulSet{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(statefulSet.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(statefulSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":150,"to":164}} {"id":100026137,"name":"Delete","signature":"func (c *statefulSets) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/statefulset.go","code":"// Delete takes name of the statefulSet and deletes it. Returns an error if one occurs.\nfunc (c *statefulSets) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":166,"to":175}} {"id":100026138,"name":"DeleteCollection","signature":"func (c *statefulSets) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/statefulset.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *statefulSets) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":177,"to":191}} {"id":100026139,"name":"Patch","signature":"func (c *statefulSets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/statefulset.go","code":"// Patch applies the patch and returns the patched statefulSet.\nfunc (c *statefulSets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.StatefulSet, err error) {\n\tresult = \u0026v1.StatefulSet{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":193,"to":206}} {"id":100026140,"name":"Apply","signature":"func (c *statefulSets) Apply(ctx context.Context, statefulSet *appsv1.StatefulSetApplyConfiguration, opts metav1.ApplyOptions) (result *v1.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/statefulset.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied statefulSet.\nfunc (c *statefulSets) Apply(ctx context.Context, statefulSet *appsv1.StatefulSetApplyConfiguration, opts metav1.ApplyOptions) (result *v1.StatefulSet, err error) {\n\tif statefulSet == nil {\n\t\treturn nil, fmt.Errorf(\"statefulSet provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(statefulSet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := statefulSet.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"statefulSet.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.StatefulSet{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":208,"to":232}} {"id":100026141,"name":"ApplyStatus","signature":"func (c *statefulSets) ApplyStatus(ctx context.Context, statefulSet *appsv1.StatefulSetApplyConfiguration, opts metav1.ApplyOptions) (result *v1.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/statefulset.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *statefulSets) ApplyStatus(ctx context.Context, statefulSet *appsv1.StatefulSetApplyConfiguration, opts metav1.ApplyOptions) (result *v1.StatefulSet, err error) {\n\tif statefulSet == nil {\n\t\treturn nil, fmt.Errorf(\"statefulSet provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(statefulSet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := statefulSet.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"statefulSet.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1.StatefulSet{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":234,"to":262}} {"id":100026142,"name":"GetScale","signature":"func (c *statefulSets) GetScale(ctx context.Context, statefulSetName string, options metav1.GetOptions) (result *autoscalingv1.Scale, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/statefulset.go","code":"// GetScale takes name of the statefulSet, and returns the corresponding autoscalingv1.Scale object, and an error if there is any.\nfunc (c *statefulSets) GetScale(ctx context.Context, statefulSetName string, options metav1.GetOptions) (result *autoscalingv1.Scale, err error) {\n\tresult = \u0026autoscalingv1.Scale{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(statefulSetName).\n\t\tSubResource(\"scale\").\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":264,"to":276}} {"id":100026143,"name":"UpdateScale","signature":"func (c *statefulSets) UpdateScale(ctx context.Context, statefulSetName string, scale *autoscalingv1.Scale, opts metav1.UpdateOptions) (result *autoscalingv1.Scale, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/statefulset.go","code":"// UpdateScale takes the top resource name and the representation of a scale and updates it. Returns the server's representation of the scale, and an error, if there is any.\nfunc (c *statefulSets) UpdateScale(ctx context.Context, statefulSetName string, scale *autoscalingv1.Scale, opts metav1.UpdateOptions) (result *autoscalingv1.Scale, err error) {\n\tresult = \u0026autoscalingv1.Scale{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(statefulSetName).\n\t\tSubResource(\"scale\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(scale).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":278,"to":291}} {"id":100026144,"name":"ApplyScale","signature":"func (c *statefulSets) ApplyScale(ctx context.Context, statefulSetName string, scale *applyconfigurationsautoscalingv1.ScaleApplyConfiguration, opts metav1.ApplyOptions) (result *autoscalingv1.Scale, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1/statefulset.go","code":"// ApplyScale takes top resource name and the apply declarative configuration for scale,\n// applies it and returns the applied scale, and an error, if there is any.\nfunc (c *statefulSets) ApplyScale(ctx context.Context, statefulSetName string, scale *applyconfigurationsautoscalingv1.ScaleApplyConfiguration, opts metav1.ApplyOptions) (result *autoscalingv1.Scale, err error) {\n\tif scale == nil {\n\t\treturn nil, fmt.Errorf(\"scale provided to ApplyScale must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(scale)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult = \u0026autoscalingv1.Scale{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(statefulSetName).\n\t\tSubResource(\"scale\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":293,"to":316}} {"id":100026145,"name":"ControllerRevisions","signature":"func (c *AppsV1beta1Client) ControllerRevisions(namespace string) ControllerRevisionInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/apps_client.go","code":"func (c *AppsV1beta1Client) ControllerRevisions(namespace string) ControllerRevisionInterface {\n\treturn newControllerRevisions(c, namespace)\n}","line":{"from":41,"to":43}} {"id":100026146,"name":"Deployments","signature":"func (c *AppsV1beta1Client) Deployments(namespace string) DeploymentInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/apps_client.go","code":"func (c *AppsV1beta1Client) Deployments(namespace string) DeploymentInterface {\n\treturn newDeployments(c, namespace)\n}","line":{"from":45,"to":47}} {"id":100026147,"name":"StatefulSets","signature":"func (c *AppsV1beta1Client) StatefulSets(namespace string) StatefulSetInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/apps_client.go","code":"func (c *AppsV1beta1Client) StatefulSets(namespace string) StatefulSetInterface {\n\treturn newStatefulSets(c, namespace)\n}","line":{"from":49,"to":51}} {"id":100026148,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*AppsV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/apps_client.go","code":"// NewForConfig creates a new AppsV1beta1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*AppsV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":53,"to":66}} {"id":100026149,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AppsV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/apps_client.go","code":"// NewForConfigAndClient creates a new AppsV1beta1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*AppsV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026AppsV1beta1Client{client}, nil\n}","line":{"from":68,"to":80}} {"id":100026150,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *AppsV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/apps_client.go","code":"// NewForConfigOrDie creates a new AppsV1beta1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *AppsV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":82,"to":90}} {"id":100026151,"name":"New","signature":"func New(c rest.Interface) *AppsV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/apps_client.go","code":"// New creates a new AppsV1beta1Client for the given RESTClient.\nfunc New(c rest.Interface) *AppsV1beta1Client {\n\treturn \u0026AppsV1beta1Client{c}\n}","line":{"from":92,"to":95}} {"id":100026152,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/apps_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":97,"to":108}} {"id":100026153,"name":"RESTClient","signature":"func (c *AppsV1beta1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/apps_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *AppsV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":110,"to":117}} {"id":100026154,"name":"newControllerRevisions","signature":"func newControllerRevisions(c *AppsV1beta1Client, namespace string) *controllerRevisions","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/controllerrevision.go","code":"// newControllerRevisions returns a ControllerRevisions\nfunc newControllerRevisions(c *AppsV1beta1Client, namespace string) *controllerRevisions {\n\treturn \u0026controllerRevisions{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":62,"to":68}} {"id":100026155,"name":"Get","signature":"func (c *controllerRevisions) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.ControllerRevision, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/controllerrevision.go","code":"// Get takes name of the controllerRevision, and returns the corresponding controllerRevision object, and an error if there is any.\nfunc (c *controllerRevisions) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.ControllerRevision, err error) {\n\tresult = \u0026v1beta1.ControllerRevision{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":81}} {"id":100026156,"name":"List","signature":"func (c *controllerRevisions) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.ControllerRevisionList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/controllerrevision.go","code":"// List takes label and field selectors, and returns the list of ControllerRevisions that match those selectors.\nfunc (c *controllerRevisions) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.ControllerRevisionList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.ControllerRevisionList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":83,"to":98}} {"id":100026157,"name":"Watch","signature":"func (c *controllerRevisions) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/controllerrevision.go","code":"// Watch returns a watch.Interface that watches the requested controllerRevisions.\nfunc (c *controllerRevisions) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":100,"to":113}} {"id":100026158,"name":"Create","signature":"func (c *controllerRevisions) Create(ctx context.Context, controllerRevision *v1beta1.ControllerRevision, opts v1.CreateOptions) (result *v1beta1.ControllerRevision, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/controllerrevision.go","code":"// Create takes the representation of a controllerRevision and creates it. Returns the server's representation of the controllerRevision, and an error, if there is any.\nfunc (c *controllerRevisions) Create(ctx context.Context, controllerRevision *v1beta1.ControllerRevision, opts v1.CreateOptions) (result *v1beta1.ControllerRevision, err error) {\n\tresult = \u0026v1beta1.ControllerRevision{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(controllerRevision).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":115,"to":126}} {"id":100026159,"name":"Update","signature":"func (c *controllerRevisions) Update(ctx context.Context, controllerRevision *v1beta1.ControllerRevision, opts v1.UpdateOptions) (result *v1beta1.ControllerRevision, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/controllerrevision.go","code":"// Update takes the representation of a controllerRevision and updates it. Returns the server's representation of the controllerRevision, and an error, if there is any.\nfunc (c *controllerRevisions) Update(ctx context.Context, controllerRevision *v1beta1.ControllerRevision, opts v1.UpdateOptions) (result *v1beta1.ControllerRevision, err error) {\n\tresult = \u0026v1beta1.ControllerRevision{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tName(controllerRevision.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(controllerRevision).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":128,"to":140}} {"id":100026160,"name":"Delete","signature":"func (c *controllerRevisions) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/controllerrevision.go","code":"// Delete takes name of the controllerRevision and deletes it. Returns an error if one occurs.\nfunc (c *controllerRevisions) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":142,"to":151}} {"id":100026161,"name":"DeleteCollection","signature":"func (c *controllerRevisions) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/controllerrevision.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *controllerRevisions) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":153,"to":167}} {"id":100026162,"name":"Patch","signature":"func (c *controllerRevisions) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.ControllerRevision, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/controllerrevision.go","code":"// Patch applies the patch and returns the patched controllerRevision.\nfunc (c *controllerRevisions) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.ControllerRevision, err error) {\n\tresult = \u0026v1beta1.ControllerRevision{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":169,"to":182}} {"id":100026163,"name":"Apply","signature":"func (c *controllerRevisions) Apply(ctx context.Context, controllerRevision *appsv1beta1.ControllerRevisionApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.ControllerRevision, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/controllerrevision.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied controllerRevision.\nfunc (c *controllerRevisions) Apply(ctx context.Context, controllerRevision *appsv1beta1.ControllerRevisionApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.ControllerRevision, err error) {\n\tif controllerRevision == nil {\n\t\treturn nil, fmt.Errorf(\"controllerRevision provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(controllerRevision)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := controllerRevision.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"controllerRevision.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.ControllerRevision{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":184,"to":208}} {"id":100026164,"name":"newDeployments","signature":"func newDeployments(c *AppsV1beta1Client, namespace string) *deployments","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/deployment.go","code":"// newDeployments returns a Deployments\nfunc newDeployments(c *AppsV1beta1Client, namespace string) *deployments {\n\treturn \u0026deployments{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":64,"to":70}} {"id":100026165,"name":"Get","signature":"func (c *deployments) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/deployment.go","code":"// Get takes name of the deployment, and returns the corresponding deployment object, and an error if there is any.\nfunc (c *deployments) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.Deployment, err error) {\n\tresult = \u0026v1beta1.Deployment{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":72,"to":83}} {"id":100026166,"name":"List","signature":"func (c *deployments) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.DeploymentList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/deployment.go","code":"// List takes label and field selectors, and returns the list of Deployments that match those selectors.\nfunc (c *deployments) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.DeploymentList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.DeploymentList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":85,"to":100}} {"id":100026167,"name":"Watch","signature":"func (c *deployments) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/deployment.go","code":"// Watch returns a watch.Interface that watches the requested deployments.\nfunc (c *deployments) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":102,"to":115}} {"id":100026168,"name":"Create","signature":"func (c *deployments) Create(ctx context.Context, deployment *v1beta1.Deployment, opts v1.CreateOptions) (result *v1beta1.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/deployment.go","code":"// Create takes the representation of a deployment and creates it. Returns the server's representation of the deployment, and an error, if there is any.\nfunc (c *deployments) Create(ctx context.Context, deployment *v1beta1.Deployment, opts v1.CreateOptions) (result *v1beta1.Deployment, err error) {\n\tresult = \u0026v1beta1.Deployment{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(deployment).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":117,"to":128}} {"id":100026169,"name":"Update","signature":"func (c *deployments) Update(ctx context.Context, deployment *v1beta1.Deployment, opts v1.UpdateOptions) (result *v1beta1.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/deployment.go","code":"// Update takes the representation of a deployment and updates it. Returns the server's representation of the deployment, and an error, if there is any.\nfunc (c *deployments) Update(ctx context.Context, deployment *v1beta1.Deployment, opts v1.UpdateOptions) (result *v1beta1.Deployment, err error) {\n\tresult = \u0026v1beta1.Deployment{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(deployment.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(deployment).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":130,"to":142}} {"id":100026170,"name":"UpdateStatus","signature":"func (c *deployments) UpdateStatus(ctx context.Context, deployment *v1beta1.Deployment, opts v1.UpdateOptions) (result *v1beta1.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/deployment.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *deployments) UpdateStatus(ctx context.Context, deployment *v1beta1.Deployment, opts v1.UpdateOptions) (result *v1beta1.Deployment, err error) {\n\tresult = \u0026v1beta1.Deployment{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(deployment.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(deployment).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":144,"to":158}} {"id":100026171,"name":"Delete","signature":"func (c *deployments) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/deployment.go","code":"// Delete takes name of the deployment and deletes it. Returns an error if one occurs.\nfunc (c *deployments) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":160,"to":169}} {"id":100026172,"name":"DeleteCollection","signature":"func (c *deployments) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/deployment.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *deployments) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":171,"to":185}} {"id":100026173,"name":"Patch","signature":"func (c *deployments) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/deployment.go","code":"// Patch applies the patch and returns the patched deployment.\nfunc (c *deployments) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.Deployment, err error) {\n\tresult = \u0026v1beta1.Deployment{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":187,"to":200}} {"id":100026174,"name":"Apply","signature":"func (c *deployments) Apply(ctx context.Context, deployment *appsv1beta1.DeploymentApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/deployment.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied deployment.\nfunc (c *deployments) Apply(ctx context.Context, deployment *appsv1beta1.DeploymentApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Deployment, err error) {\n\tif deployment == nil {\n\t\treturn nil, fmt.Errorf(\"deployment provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(deployment)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := deployment.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"deployment.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.Deployment{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":202,"to":226}} {"id":100026175,"name":"ApplyStatus","signature":"func (c *deployments) ApplyStatus(ctx context.Context, deployment *appsv1beta1.DeploymentApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/deployment.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *deployments) ApplyStatus(ctx context.Context, deployment *appsv1beta1.DeploymentApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Deployment, err error) {\n\tif deployment == nil {\n\t\treturn nil, fmt.Errorf(\"deployment provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(deployment)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := deployment.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"deployment.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1beta1.Deployment{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":228,"to":256}} {"id":100026176,"name":"newStatefulSets","signature":"func newStatefulSets(c *AppsV1beta1Client, namespace string) *statefulSets","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/statefulset.go","code":"// newStatefulSets returns a StatefulSets\nfunc newStatefulSets(c *AppsV1beta1Client, namespace string) *statefulSets {\n\treturn \u0026statefulSets{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":64,"to":70}} {"id":100026177,"name":"Get","signature":"func (c *statefulSets) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/statefulset.go","code":"// Get takes name of the statefulSet, and returns the corresponding statefulSet object, and an error if there is any.\nfunc (c *statefulSets) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.StatefulSet, err error) {\n\tresult = \u0026v1beta1.StatefulSet{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":72,"to":83}} {"id":100026178,"name":"List","signature":"func (c *statefulSets) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.StatefulSetList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/statefulset.go","code":"// List takes label and field selectors, and returns the list of StatefulSets that match those selectors.\nfunc (c *statefulSets) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.StatefulSetList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.StatefulSetList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":85,"to":100}} {"id":100026179,"name":"Watch","signature":"func (c *statefulSets) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/statefulset.go","code":"// Watch returns a watch.Interface that watches the requested statefulSets.\nfunc (c *statefulSets) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":102,"to":115}} {"id":100026180,"name":"Create","signature":"func (c *statefulSets) Create(ctx context.Context, statefulSet *v1beta1.StatefulSet, opts v1.CreateOptions) (result *v1beta1.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/statefulset.go","code":"// Create takes the representation of a statefulSet and creates it. Returns the server's representation of the statefulSet, and an error, if there is any.\nfunc (c *statefulSets) Create(ctx context.Context, statefulSet *v1beta1.StatefulSet, opts v1.CreateOptions) (result *v1beta1.StatefulSet, err error) {\n\tresult = \u0026v1beta1.StatefulSet{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(statefulSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":117,"to":128}} {"id":100026181,"name":"Update","signature":"func (c *statefulSets) Update(ctx context.Context, statefulSet *v1beta1.StatefulSet, opts v1.UpdateOptions) (result *v1beta1.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/statefulset.go","code":"// Update takes the representation of a statefulSet and updates it. Returns the server's representation of the statefulSet, and an error, if there is any.\nfunc (c *statefulSets) Update(ctx context.Context, statefulSet *v1beta1.StatefulSet, opts v1.UpdateOptions) (result *v1beta1.StatefulSet, err error) {\n\tresult = \u0026v1beta1.StatefulSet{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(statefulSet.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(statefulSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":130,"to":142}} {"id":100026182,"name":"UpdateStatus","signature":"func (c *statefulSets) UpdateStatus(ctx context.Context, statefulSet *v1beta1.StatefulSet, opts v1.UpdateOptions) (result *v1beta1.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/statefulset.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *statefulSets) UpdateStatus(ctx context.Context, statefulSet *v1beta1.StatefulSet, opts v1.UpdateOptions) (result *v1beta1.StatefulSet, err error) {\n\tresult = \u0026v1beta1.StatefulSet{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(statefulSet.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(statefulSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":144,"to":158}} {"id":100026183,"name":"Delete","signature":"func (c *statefulSets) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/statefulset.go","code":"// Delete takes name of the statefulSet and deletes it. Returns an error if one occurs.\nfunc (c *statefulSets) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":160,"to":169}} {"id":100026184,"name":"DeleteCollection","signature":"func (c *statefulSets) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/statefulset.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *statefulSets) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":171,"to":185}} {"id":100026185,"name":"Patch","signature":"func (c *statefulSets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/statefulset.go","code":"// Patch applies the patch and returns the patched statefulSet.\nfunc (c *statefulSets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.StatefulSet, err error) {\n\tresult = \u0026v1beta1.StatefulSet{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":187,"to":200}} {"id":100026186,"name":"Apply","signature":"func (c *statefulSets) Apply(ctx context.Context, statefulSet *appsv1beta1.StatefulSetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/statefulset.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied statefulSet.\nfunc (c *statefulSets) Apply(ctx context.Context, statefulSet *appsv1beta1.StatefulSetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.StatefulSet, err error) {\n\tif statefulSet == nil {\n\t\treturn nil, fmt.Errorf(\"statefulSet provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(statefulSet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := statefulSet.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"statefulSet.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.StatefulSet{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":202,"to":226}} {"id":100026187,"name":"ApplyStatus","signature":"func (c *statefulSets) ApplyStatus(ctx context.Context, statefulSet *appsv1beta1.StatefulSetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta1/statefulset.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *statefulSets) ApplyStatus(ctx context.Context, statefulSet *appsv1beta1.StatefulSetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.StatefulSet, err error) {\n\tif statefulSet == nil {\n\t\treturn nil, fmt.Errorf(\"statefulSet provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(statefulSet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := statefulSet.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"statefulSet.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1beta1.StatefulSet{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":228,"to":256}} {"id":100026188,"name":"ControllerRevisions","signature":"func (c *AppsV1beta2Client) ControllerRevisions(namespace string) ControllerRevisionInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/apps_client.go","code":"func (c *AppsV1beta2Client) ControllerRevisions(namespace string) ControllerRevisionInterface {\n\treturn newControllerRevisions(c, namespace)\n}","line":{"from":43,"to":45}} {"id":100026189,"name":"DaemonSets","signature":"func (c *AppsV1beta2Client) DaemonSets(namespace string) DaemonSetInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/apps_client.go","code":"func (c *AppsV1beta2Client) DaemonSets(namespace string) DaemonSetInterface {\n\treturn newDaemonSets(c, namespace)\n}","line":{"from":47,"to":49}} {"id":100026190,"name":"Deployments","signature":"func (c *AppsV1beta2Client) Deployments(namespace string) DeploymentInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/apps_client.go","code":"func (c *AppsV1beta2Client) Deployments(namespace string) DeploymentInterface {\n\treturn newDeployments(c, namespace)\n}","line":{"from":51,"to":53}} {"id":100026191,"name":"ReplicaSets","signature":"func (c *AppsV1beta2Client) ReplicaSets(namespace string) ReplicaSetInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/apps_client.go","code":"func (c *AppsV1beta2Client) ReplicaSets(namespace string) ReplicaSetInterface {\n\treturn newReplicaSets(c, namespace)\n}","line":{"from":55,"to":57}} {"id":100026192,"name":"StatefulSets","signature":"func (c *AppsV1beta2Client) StatefulSets(namespace string) StatefulSetInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/apps_client.go","code":"func (c *AppsV1beta2Client) StatefulSets(namespace string) StatefulSetInterface {\n\treturn newStatefulSets(c, namespace)\n}","line":{"from":59,"to":61}} {"id":100026193,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*AppsV1beta2Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/apps_client.go","code":"// NewForConfig creates a new AppsV1beta2Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*AppsV1beta2Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":63,"to":76}} {"id":100026194,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AppsV1beta2Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/apps_client.go","code":"// NewForConfigAndClient creates a new AppsV1beta2Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*AppsV1beta2Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026AppsV1beta2Client{client}, nil\n}","line":{"from":78,"to":90}} {"id":100026195,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *AppsV1beta2Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/apps_client.go","code":"// NewForConfigOrDie creates a new AppsV1beta2Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *AppsV1beta2Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":92,"to":100}} {"id":100026196,"name":"New","signature":"func New(c rest.Interface) *AppsV1beta2Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/apps_client.go","code":"// New creates a new AppsV1beta2Client for the given RESTClient.\nfunc New(c rest.Interface) *AppsV1beta2Client {\n\treturn \u0026AppsV1beta2Client{c}\n}","line":{"from":102,"to":105}} {"id":100026197,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/apps_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta2.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":107,"to":118}} {"id":100026198,"name":"RESTClient","signature":"func (c *AppsV1beta2Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/apps_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *AppsV1beta2Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":120,"to":127}} {"id":100026199,"name":"newControllerRevisions","signature":"func newControllerRevisions(c *AppsV1beta2Client, namespace string) *controllerRevisions","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/controllerrevision.go","code":"// newControllerRevisions returns a ControllerRevisions\nfunc newControllerRevisions(c *AppsV1beta2Client, namespace string) *controllerRevisions {\n\treturn \u0026controllerRevisions{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":62,"to":68}} {"id":100026200,"name":"Get","signature":"func (c *controllerRevisions) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta2.ControllerRevision, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/controllerrevision.go","code":"// Get takes name of the controllerRevision, and returns the corresponding controllerRevision object, and an error if there is any.\nfunc (c *controllerRevisions) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta2.ControllerRevision, err error) {\n\tresult = \u0026v1beta2.ControllerRevision{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":81}} {"id":100026201,"name":"List","signature":"func (c *controllerRevisions) List(ctx context.Context, opts v1.ListOptions) (result *v1beta2.ControllerRevisionList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/controllerrevision.go","code":"// List takes label and field selectors, and returns the list of ControllerRevisions that match those selectors.\nfunc (c *controllerRevisions) List(ctx context.Context, opts v1.ListOptions) (result *v1beta2.ControllerRevisionList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta2.ControllerRevisionList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":83,"to":98}} {"id":100026202,"name":"Watch","signature":"func (c *controllerRevisions) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/controllerrevision.go","code":"// Watch returns a watch.Interface that watches the requested controllerRevisions.\nfunc (c *controllerRevisions) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":100,"to":113}} {"id":100026203,"name":"Create","signature":"func (c *controllerRevisions) Create(ctx context.Context, controllerRevision *v1beta2.ControllerRevision, opts v1.CreateOptions) (result *v1beta2.ControllerRevision, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/controllerrevision.go","code":"// Create takes the representation of a controllerRevision and creates it. Returns the server's representation of the controllerRevision, and an error, if there is any.\nfunc (c *controllerRevisions) Create(ctx context.Context, controllerRevision *v1beta2.ControllerRevision, opts v1.CreateOptions) (result *v1beta2.ControllerRevision, err error) {\n\tresult = \u0026v1beta2.ControllerRevision{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(controllerRevision).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":115,"to":126}} {"id":100026204,"name":"Update","signature":"func (c *controllerRevisions) Update(ctx context.Context, controllerRevision *v1beta2.ControllerRevision, opts v1.UpdateOptions) (result *v1beta2.ControllerRevision, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/controllerrevision.go","code":"// Update takes the representation of a controllerRevision and updates it. Returns the server's representation of the controllerRevision, and an error, if there is any.\nfunc (c *controllerRevisions) Update(ctx context.Context, controllerRevision *v1beta2.ControllerRevision, opts v1.UpdateOptions) (result *v1beta2.ControllerRevision, err error) {\n\tresult = \u0026v1beta2.ControllerRevision{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tName(controllerRevision.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(controllerRevision).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":128,"to":140}} {"id":100026205,"name":"Delete","signature":"func (c *controllerRevisions) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/controllerrevision.go","code":"// Delete takes name of the controllerRevision and deletes it. Returns an error if one occurs.\nfunc (c *controllerRevisions) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":142,"to":151}} {"id":100026206,"name":"DeleteCollection","signature":"func (c *controllerRevisions) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/controllerrevision.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *controllerRevisions) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":153,"to":167}} {"id":100026207,"name":"Patch","signature":"func (c *controllerRevisions) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta2.ControllerRevision, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/controllerrevision.go","code":"// Patch applies the patch and returns the patched controllerRevision.\nfunc (c *controllerRevisions) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta2.ControllerRevision, err error) {\n\tresult = \u0026v1beta2.ControllerRevision{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":169,"to":182}} {"id":100026208,"name":"Apply","signature":"func (c *controllerRevisions) Apply(ctx context.Context, controllerRevision *appsv1beta2.ControllerRevisionApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.ControllerRevision, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/controllerrevision.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied controllerRevision.\nfunc (c *controllerRevisions) Apply(ctx context.Context, controllerRevision *appsv1beta2.ControllerRevisionApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.ControllerRevision, err error) {\n\tif controllerRevision == nil {\n\t\treturn nil, fmt.Errorf(\"controllerRevision provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(controllerRevision)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := controllerRevision.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"controllerRevision.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta2.ControllerRevision{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"controllerrevisions\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":184,"to":208}} {"id":100026209,"name":"newDaemonSets","signature":"func newDaemonSets(c *AppsV1beta2Client, namespace string) *daemonSets","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/daemonset.go","code":"// newDaemonSets returns a DaemonSets\nfunc newDaemonSets(c *AppsV1beta2Client, namespace string) *daemonSets {\n\treturn \u0026daemonSets{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":64,"to":70}} {"id":100026210,"name":"Get","signature":"func (c *daemonSets) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta2.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/daemonset.go","code":"// Get takes name of the daemonSet, and returns the corresponding daemonSet object, and an error if there is any.\nfunc (c *daemonSets) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta2.DaemonSet, err error) {\n\tresult = \u0026v1beta2.DaemonSet{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":72,"to":83}} {"id":100026211,"name":"List","signature":"func (c *daemonSets) List(ctx context.Context, opts v1.ListOptions) (result *v1beta2.DaemonSetList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/daemonset.go","code":"// List takes label and field selectors, and returns the list of DaemonSets that match those selectors.\nfunc (c *daemonSets) List(ctx context.Context, opts v1.ListOptions) (result *v1beta2.DaemonSetList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta2.DaemonSetList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":85,"to":100}} {"id":100026212,"name":"Watch","signature":"func (c *daemonSets) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/daemonset.go","code":"// Watch returns a watch.Interface that watches the requested daemonSets.\nfunc (c *daemonSets) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":102,"to":115}} {"id":100026213,"name":"Create","signature":"func (c *daemonSets) Create(ctx context.Context, daemonSet *v1beta2.DaemonSet, opts v1.CreateOptions) (result *v1beta2.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/daemonset.go","code":"// Create takes the representation of a daemonSet and creates it. Returns the server's representation of the daemonSet, and an error, if there is any.\nfunc (c *daemonSets) Create(ctx context.Context, daemonSet *v1beta2.DaemonSet, opts v1.CreateOptions) (result *v1beta2.DaemonSet, err error) {\n\tresult = \u0026v1beta2.DaemonSet{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(daemonSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":117,"to":128}} {"id":100026214,"name":"Update","signature":"func (c *daemonSets) Update(ctx context.Context, daemonSet *v1beta2.DaemonSet, opts v1.UpdateOptions) (result *v1beta2.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/daemonset.go","code":"// Update takes the representation of a daemonSet and updates it. Returns the server's representation of the daemonSet, and an error, if there is any.\nfunc (c *daemonSets) Update(ctx context.Context, daemonSet *v1beta2.DaemonSet, opts v1.UpdateOptions) (result *v1beta2.DaemonSet, err error) {\n\tresult = \u0026v1beta2.DaemonSet{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tName(daemonSet.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(daemonSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":130,"to":142}} {"id":100026215,"name":"UpdateStatus","signature":"func (c *daemonSets) UpdateStatus(ctx context.Context, daemonSet *v1beta2.DaemonSet, opts v1.UpdateOptions) (result *v1beta2.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/daemonset.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *daemonSets) UpdateStatus(ctx context.Context, daemonSet *v1beta2.DaemonSet, opts v1.UpdateOptions) (result *v1beta2.DaemonSet, err error) {\n\tresult = \u0026v1beta2.DaemonSet{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tName(daemonSet.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(daemonSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":144,"to":158}} {"id":100026216,"name":"Delete","signature":"func (c *daemonSets) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/daemonset.go","code":"// Delete takes name of the daemonSet and deletes it. Returns an error if one occurs.\nfunc (c *daemonSets) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":160,"to":169}} {"id":100026217,"name":"DeleteCollection","signature":"func (c *daemonSets) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/daemonset.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *daemonSets) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":171,"to":185}} {"id":100026218,"name":"Patch","signature":"func (c *daemonSets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta2.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/daemonset.go","code":"// Patch applies the patch and returns the patched daemonSet.\nfunc (c *daemonSets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta2.DaemonSet, err error) {\n\tresult = \u0026v1beta2.DaemonSet{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":187,"to":200}} {"id":100026219,"name":"Apply","signature":"func (c *daemonSets) Apply(ctx context.Context, daemonSet *appsv1beta2.DaemonSetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/daemonset.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied daemonSet.\nfunc (c *daemonSets) Apply(ctx context.Context, daemonSet *appsv1beta2.DaemonSetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.DaemonSet, err error) {\n\tif daemonSet == nil {\n\t\treturn nil, fmt.Errorf(\"daemonSet provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(daemonSet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := daemonSet.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"daemonSet.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta2.DaemonSet{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":202,"to":226}} {"id":100026220,"name":"ApplyStatus","signature":"func (c *daemonSets) ApplyStatus(ctx context.Context, daemonSet *appsv1beta2.DaemonSetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/daemonset.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *daemonSets) ApplyStatus(ctx context.Context, daemonSet *appsv1beta2.DaemonSetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.DaemonSet, err error) {\n\tif daemonSet == nil {\n\t\treturn nil, fmt.Errorf(\"daemonSet provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(daemonSet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := daemonSet.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"daemonSet.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1beta2.DaemonSet{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":228,"to":256}} {"id":100026221,"name":"newDeployments","signature":"func newDeployments(c *AppsV1beta2Client, namespace string) *deployments","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/deployment.go","code":"// newDeployments returns a Deployments\nfunc newDeployments(c *AppsV1beta2Client, namespace string) *deployments {\n\treturn \u0026deployments{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":64,"to":70}} {"id":100026222,"name":"Get","signature":"func (c *deployments) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta2.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/deployment.go","code":"// Get takes name of the deployment, and returns the corresponding deployment object, and an error if there is any.\nfunc (c *deployments) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta2.Deployment, err error) {\n\tresult = \u0026v1beta2.Deployment{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":72,"to":83}} {"id":100026223,"name":"List","signature":"func (c *deployments) List(ctx context.Context, opts v1.ListOptions) (result *v1beta2.DeploymentList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/deployment.go","code":"// List takes label and field selectors, and returns the list of Deployments that match those selectors.\nfunc (c *deployments) List(ctx context.Context, opts v1.ListOptions) (result *v1beta2.DeploymentList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta2.DeploymentList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":85,"to":100}} {"id":100026224,"name":"Watch","signature":"func (c *deployments) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/deployment.go","code":"// Watch returns a watch.Interface that watches the requested deployments.\nfunc (c *deployments) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":102,"to":115}} {"id":100026225,"name":"Create","signature":"func (c *deployments) Create(ctx context.Context, deployment *v1beta2.Deployment, opts v1.CreateOptions) (result *v1beta2.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/deployment.go","code":"// Create takes the representation of a deployment and creates it. Returns the server's representation of the deployment, and an error, if there is any.\nfunc (c *deployments) Create(ctx context.Context, deployment *v1beta2.Deployment, opts v1.CreateOptions) (result *v1beta2.Deployment, err error) {\n\tresult = \u0026v1beta2.Deployment{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(deployment).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":117,"to":128}} {"id":100026226,"name":"Update","signature":"func (c *deployments) Update(ctx context.Context, deployment *v1beta2.Deployment, opts v1.UpdateOptions) (result *v1beta2.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/deployment.go","code":"// Update takes the representation of a deployment and updates it. Returns the server's representation of the deployment, and an error, if there is any.\nfunc (c *deployments) Update(ctx context.Context, deployment *v1beta2.Deployment, opts v1.UpdateOptions) (result *v1beta2.Deployment, err error) {\n\tresult = \u0026v1beta2.Deployment{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(deployment.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(deployment).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":130,"to":142}} {"id":100026227,"name":"UpdateStatus","signature":"func (c *deployments) UpdateStatus(ctx context.Context, deployment *v1beta2.Deployment, opts v1.UpdateOptions) (result *v1beta2.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/deployment.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *deployments) UpdateStatus(ctx context.Context, deployment *v1beta2.Deployment, opts v1.UpdateOptions) (result *v1beta2.Deployment, err error) {\n\tresult = \u0026v1beta2.Deployment{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(deployment.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(deployment).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":144,"to":158}} {"id":100026228,"name":"Delete","signature":"func (c *deployments) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/deployment.go","code":"// Delete takes name of the deployment and deletes it. Returns an error if one occurs.\nfunc (c *deployments) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":160,"to":169}} {"id":100026229,"name":"DeleteCollection","signature":"func (c *deployments) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/deployment.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *deployments) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":171,"to":185}} {"id":100026230,"name":"Patch","signature":"func (c *deployments) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta2.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/deployment.go","code":"// Patch applies the patch and returns the patched deployment.\nfunc (c *deployments) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta2.Deployment, err error) {\n\tresult = \u0026v1beta2.Deployment{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":187,"to":200}} {"id":100026231,"name":"Apply","signature":"func (c *deployments) Apply(ctx context.Context, deployment *appsv1beta2.DeploymentApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/deployment.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied deployment.\nfunc (c *deployments) Apply(ctx context.Context, deployment *appsv1beta2.DeploymentApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.Deployment, err error) {\n\tif deployment == nil {\n\t\treturn nil, fmt.Errorf(\"deployment provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(deployment)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := deployment.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"deployment.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta2.Deployment{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":202,"to":226}} {"id":100026232,"name":"ApplyStatus","signature":"func (c *deployments) ApplyStatus(ctx context.Context, deployment *appsv1beta2.DeploymentApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/deployment.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *deployments) ApplyStatus(ctx context.Context, deployment *appsv1beta2.DeploymentApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.Deployment, err error) {\n\tif deployment == nil {\n\t\treturn nil, fmt.Errorf(\"deployment provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(deployment)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := deployment.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"deployment.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1beta2.Deployment{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":228,"to":256}} {"id":100026233,"name":"newReplicaSets","signature":"func newReplicaSets(c *AppsV1beta2Client, namespace string) *replicaSets","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/replicaset.go","code":"// newReplicaSets returns a ReplicaSets\nfunc newReplicaSets(c *AppsV1beta2Client, namespace string) *replicaSets {\n\treturn \u0026replicaSets{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":64,"to":70}} {"id":100026234,"name":"Get","signature":"func (c *replicaSets) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta2.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/replicaset.go","code":"// Get takes name of the replicaSet, and returns the corresponding replicaSet object, and an error if there is any.\nfunc (c *replicaSets) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta2.ReplicaSet, err error) {\n\tresult = \u0026v1beta2.ReplicaSet{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":72,"to":83}} {"id":100026235,"name":"List","signature":"func (c *replicaSets) List(ctx context.Context, opts v1.ListOptions) (result *v1beta2.ReplicaSetList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/replicaset.go","code":"// List takes label and field selectors, and returns the list of ReplicaSets that match those selectors.\nfunc (c *replicaSets) List(ctx context.Context, opts v1.ListOptions) (result *v1beta2.ReplicaSetList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta2.ReplicaSetList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":85,"to":100}} {"id":100026236,"name":"Watch","signature":"func (c *replicaSets) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/replicaset.go","code":"// Watch returns a watch.Interface that watches the requested replicaSets.\nfunc (c *replicaSets) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":102,"to":115}} {"id":100026237,"name":"Create","signature":"func (c *replicaSets) Create(ctx context.Context, replicaSet *v1beta2.ReplicaSet, opts v1.CreateOptions) (result *v1beta2.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/replicaset.go","code":"// Create takes the representation of a replicaSet and creates it. Returns the server's representation of the replicaSet, and an error, if there is any.\nfunc (c *replicaSets) Create(ctx context.Context, replicaSet *v1beta2.ReplicaSet, opts v1.CreateOptions) (result *v1beta2.ReplicaSet, err error) {\n\tresult = \u0026v1beta2.ReplicaSet{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(replicaSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":117,"to":128}} {"id":100026238,"name":"Update","signature":"func (c *replicaSets) Update(ctx context.Context, replicaSet *v1beta2.ReplicaSet, opts v1.UpdateOptions) (result *v1beta2.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/replicaset.go","code":"// Update takes the representation of a replicaSet and updates it. Returns the server's representation of the replicaSet, and an error, if there is any.\nfunc (c *replicaSets) Update(ctx context.Context, replicaSet *v1beta2.ReplicaSet, opts v1.UpdateOptions) (result *v1beta2.ReplicaSet, err error) {\n\tresult = \u0026v1beta2.ReplicaSet{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(replicaSet.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(replicaSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":130,"to":142}} {"id":100026239,"name":"UpdateStatus","signature":"func (c *replicaSets) UpdateStatus(ctx context.Context, replicaSet *v1beta2.ReplicaSet, opts v1.UpdateOptions) (result *v1beta2.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/replicaset.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *replicaSets) UpdateStatus(ctx context.Context, replicaSet *v1beta2.ReplicaSet, opts v1.UpdateOptions) (result *v1beta2.ReplicaSet, err error) {\n\tresult = \u0026v1beta2.ReplicaSet{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(replicaSet.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(replicaSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":144,"to":158}} {"id":100026240,"name":"Delete","signature":"func (c *replicaSets) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/replicaset.go","code":"// Delete takes name of the replicaSet and deletes it. Returns an error if one occurs.\nfunc (c *replicaSets) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":160,"to":169}} {"id":100026241,"name":"DeleteCollection","signature":"func (c *replicaSets) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/replicaset.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *replicaSets) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":171,"to":185}} {"id":100026242,"name":"Patch","signature":"func (c *replicaSets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta2.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/replicaset.go","code":"// Patch applies the patch and returns the patched replicaSet.\nfunc (c *replicaSets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta2.ReplicaSet, err error) {\n\tresult = \u0026v1beta2.ReplicaSet{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":187,"to":200}} {"id":100026243,"name":"Apply","signature":"func (c *replicaSets) Apply(ctx context.Context, replicaSet *appsv1beta2.ReplicaSetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/replicaset.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied replicaSet.\nfunc (c *replicaSets) Apply(ctx context.Context, replicaSet *appsv1beta2.ReplicaSetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.ReplicaSet, err error) {\n\tif replicaSet == nil {\n\t\treturn nil, fmt.Errorf(\"replicaSet provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(replicaSet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := replicaSet.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"replicaSet.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta2.ReplicaSet{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":202,"to":226}} {"id":100026244,"name":"ApplyStatus","signature":"func (c *replicaSets) ApplyStatus(ctx context.Context, replicaSet *appsv1beta2.ReplicaSetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/replicaset.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *replicaSets) ApplyStatus(ctx context.Context, replicaSet *appsv1beta2.ReplicaSetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.ReplicaSet, err error) {\n\tif replicaSet == nil {\n\t\treturn nil, fmt.Errorf(\"replicaSet provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(replicaSet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := replicaSet.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"replicaSet.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1beta2.ReplicaSet{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":228,"to":256}} {"id":100026245,"name":"newStatefulSets","signature":"func newStatefulSets(c *AppsV1beta2Client, namespace string) *statefulSets","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/statefulset.go","code":"// newStatefulSets returns a StatefulSets\nfunc newStatefulSets(c *AppsV1beta2Client, namespace string) *statefulSets {\n\treturn \u0026statefulSets{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":68,"to":74}} {"id":100026246,"name":"Get","signature":"func (c *statefulSets) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta2.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/statefulset.go","code":"// Get takes name of the statefulSet, and returns the corresponding statefulSet object, and an error if there is any.\nfunc (c *statefulSets) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta2.StatefulSet, err error) {\n\tresult = \u0026v1beta2.StatefulSet{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":76,"to":87}} {"id":100026247,"name":"List","signature":"func (c *statefulSets) List(ctx context.Context, opts v1.ListOptions) (result *v1beta2.StatefulSetList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/statefulset.go","code":"// List takes label and field selectors, and returns the list of StatefulSets that match those selectors.\nfunc (c *statefulSets) List(ctx context.Context, opts v1.ListOptions) (result *v1beta2.StatefulSetList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta2.StatefulSetList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":89,"to":104}} {"id":100026248,"name":"Watch","signature":"func (c *statefulSets) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/statefulset.go","code":"// Watch returns a watch.Interface that watches the requested statefulSets.\nfunc (c *statefulSets) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":106,"to":119}} {"id":100026249,"name":"Create","signature":"func (c *statefulSets) Create(ctx context.Context, statefulSet *v1beta2.StatefulSet, opts v1.CreateOptions) (result *v1beta2.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/statefulset.go","code":"// Create takes the representation of a statefulSet and creates it. Returns the server's representation of the statefulSet, and an error, if there is any.\nfunc (c *statefulSets) Create(ctx context.Context, statefulSet *v1beta2.StatefulSet, opts v1.CreateOptions) (result *v1beta2.StatefulSet, err error) {\n\tresult = \u0026v1beta2.StatefulSet{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(statefulSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":121,"to":132}} {"id":100026250,"name":"Update","signature":"func (c *statefulSets) Update(ctx context.Context, statefulSet *v1beta2.StatefulSet, opts v1.UpdateOptions) (result *v1beta2.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/statefulset.go","code":"// Update takes the representation of a statefulSet and updates it. Returns the server's representation of the statefulSet, and an error, if there is any.\nfunc (c *statefulSets) Update(ctx context.Context, statefulSet *v1beta2.StatefulSet, opts v1.UpdateOptions) (result *v1beta2.StatefulSet, err error) {\n\tresult = \u0026v1beta2.StatefulSet{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(statefulSet.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(statefulSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":134,"to":146}} {"id":100026251,"name":"UpdateStatus","signature":"func (c *statefulSets) UpdateStatus(ctx context.Context, statefulSet *v1beta2.StatefulSet, opts v1.UpdateOptions) (result *v1beta2.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/statefulset.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *statefulSets) UpdateStatus(ctx context.Context, statefulSet *v1beta2.StatefulSet, opts v1.UpdateOptions) (result *v1beta2.StatefulSet, err error) {\n\tresult = \u0026v1beta2.StatefulSet{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(statefulSet.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(statefulSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":148,"to":162}} {"id":100026252,"name":"Delete","signature":"func (c *statefulSets) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/statefulset.go","code":"// Delete takes name of the statefulSet and deletes it. Returns an error if one occurs.\nfunc (c *statefulSets) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":164,"to":173}} {"id":100026253,"name":"DeleteCollection","signature":"func (c *statefulSets) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/statefulset.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *statefulSets) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":175,"to":189}} {"id":100026254,"name":"Patch","signature":"func (c *statefulSets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta2.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/statefulset.go","code":"// Patch applies the patch and returns the patched statefulSet.\nfunc (c *statefulSets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta2.StatefulSet, err error) {\n\tresult = \u0026v1beta2.StatefulSet{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":191,"to":204}} {"id":100026255,"name":"Apply","signature":"func (c *statefulSets) Apply(ctx context.Context, statefulSet *appsv1beta2.StatefulSetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/statefulset.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied statefulSet.\nfunc (c *statefulSets) Apply(ctx context.Context, statefulSet *appsv1beta2.StatefulSetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.StatefulSet, err error) {\n\tif statefulSet == nil {\n\t\treturn nil, fmt.Errorf(\"statefulSet provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(statefulSet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := statefulSet.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"statefulSet.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta2.StatefulSet{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":206,"to":230}} {"id":100026256,"name":"ApplyStatus","signature":"func (c *statefulSets) ApplyStatus(ctx context.Context, statefulSet *appsv1beta2.StatefulSetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/statefulset.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *statefulSets) ApplyStatus(ctx context.Context, statefulSet *appsv1beta2.StatefulSetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.StatefulSet, err error) {\n\tif statefulSet == nil {\n\t\treturn nil, fmt.Errorf(\"statefulSet provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(statefulSet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := statefulSet.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"statefulSet.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1beta2.StatefulSet{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":232,"to":260}} {"id":100026257,"name":"GetScale","signature":"func (c *statefulSets) GetScale(ctx context.Context, statefulSetName string, options v1.GetOptions) (result *v1beta2.Scale, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/statefulset.go","code":"// GetScale takes name of the statefulSet, and returns the corresponding v1beta2.Scale object, and an error if there is any.\nfunc (c *statefulSets) GetScale(ctx context.Context, statefulSetName string, options v1.GetOptions) (result *v1beta2.Scale, err error) {\n\tresult = \u0026v1beta2.Scale{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(statefulSetName).\n\t\tSubResource(\"scale\").\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":262,"to":274}} {"id":100026258,"name":"UpdateScale","signature":"func (c *statefulSets) UpdateScale(ctx context.Context, statefulSetName string, scale *v1beta2.Scale, opts v1.UpdateOptions) (result *v1beta2.Scale, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/statefulset.go","code":"// UpdateScale takes the top resource name and the representation of a scale and updates it. Returns the server's representation of the scale, and an error, if there is any.\nfunc (c *statefulSets) UpdateScale(ctx context.Context, statefulSetName string, scale *v1beta2.Scale, opts v1.UpdateOptions) (result *v1beta2.Scale, err error) {\n\tresult = \u0026v1beta2.Scale{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(statefulSetName).\n\t\tSubResource(\"scale\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(scale).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":276,"to":289}} {"id":100026259,"name":"ApplyScale","signature":"func (c *statefulSets) ApplyScale(ctx context.Context, statefulSetName string, scale *appsv1beta2.ScaleApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.Scale, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/apps/v1beta2/statefulset.go","code":"// ApplyScale takes top resource name and the apply declarative configuration for scale,\n// applies it and returns the applied scale, and an error, if there is any.\nfunc (c *statefulSets) ApplyScale(ctx context.Context, statefulSetName string, scale *appsv1beta2.ScaleApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.Scale, err error) {\n\tif scale == nil {\n\t\treturn nil, fmt.Errorf(\"scale provided to ApplyScale must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(scale)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult = \u0026v1beta2.Scale{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"statefulsets\").\n\t\tName(statefulSetName).\n\t\tSubResource(\"scale\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":291,"to":314}} {"id":100026260,"name":"TokenReviews","signature":"func (c *AuthenticationV1Client) TokenReviews() TokenReviewInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1/authentication_client.go","code":"func (c *AuthenticationV1Client) TokenReviews() TokenReviewInterface {\n\treturn newTokenReviews(c)\n}","line":{"from":39,"to":41}} {"id":100026261,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*AuthenticationV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1/authentication_client.go","code":"// NewForConfig creates a new AuthenticationV1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*AuthenticationV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":43,"to":56}} {"id":100026262,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AuthenticationV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1/authentication_client.go","code":"// NewForConfigAndClient creates a new AuthenticationV1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*AuthenticationV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026AuthenticationV1Client{client}, nil\n}","line":{"from":58,"to":70}} {"id":100026263,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *AuthenticationV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1/authentication_client.go","code":"// NewForConfigOrDie creates a new AuthenticationV1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *AuthenticationV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":72,"to":80}} {"id":100026264,"name":"New","signature":"func New(c rest.Interface) *AuthenticationV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1/authentication_client.go","code":"// New creates a new AuthenticationV1Client for the given RESTClient.\nfunc New(c rest.Interface) *AuthenticationV1Client {\n\treturn \u0026AuthenticationV1Client{c}\n}","line":{"from":82,"to":85}} {"id":100026265,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1/authentication_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":87,"to":98}} {"id":100026266,"name":"RESTClient","signature":"func (c *AuthenticationV1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1/authentication_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *AuthenticationV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":100,"to":107}} {"id":100026267,"name":"newTokenReviews","signature":"func newTokenReviews(c *AuthenticationV1Client) *tokenReviews","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1/tokenreview.go","code":"// newTokenReviews returns a TokenReviews\nfunc newTokenReviews(c *AuthenticationV1Client) *tokenReviews {\n\treturn \u0026tokenReviews{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":47,"to":52}} {"id":100026268,"name":"Create","signature":"func (c *tokenReviews) Create(ctx context.Context, tokenReview *v1.TokenReview, opts metav1.CreateOptions) (result *v1.TokenReview, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1/tokenreview.go","code":"// Create takes the representation of a tokenReview and creates it. Returns the server's representation of the tokenReview, and an error, if there is any.\nfunc (c *tokenReviews) Create(ctx context.Context, tokenReview *v1.TokenReview, opts metav1.CreateOptions) (result *v1.TokenReview, err error) {\n\tresult = \u0026v1.TokenReview{}\n\terr = c.client.Post().\n\t\tResource(\"tokenreviews\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(tokenReview).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":54,"to":64}} {"id":100026269,"name":"SelfSubjectReviews","signature":"func (c *AuthenticationV1alpha1Client) SelfSubjectReviews() SelfSubjectReviewInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1alpha1/authentication_client.go","code":"func (c *AuthenticationV1alpha1Client) SelfSubjectReviews() SelfSubjectReviewInterface {\n\treturn newSelfSubjectReviews(c)\n}","line":{"from":39,"to":41}} {"id":100026270,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*AuthenticationV1alpha1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1alpha1/authentication_client.go","code":"// NewForConfig creates a new AuthenticationV1alpha1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*AuthenticationV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":43,"to":56}} {"id":100026271,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AuthenticationV1alpha1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1alpha1/authentication_client.go","code":"// NewForConfigAndClient creates a new AuthenticationV1alpha1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*AuthenticationV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026AuthenticationV1alpha1Client{client}, nil\n}","line":{"from":58,"to":70}} {"id":100026272,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *AuthenticationV1alpha1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1alpha1/authentication_client.go","code":"// NewForConfigOrDie creates a new AuthenticationV1alpha1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *AuthenticationV1alpha1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":72,"to":80}} {"id":100026273,"name":"New","signature":"func New(c rest.Interface) *AuthenticationV1alpha1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1alpha1/authentication_client.go","code":"// New creates a new AuthenticationV1alpha1Client for the given RESTClient.\nfunc New(c rest.Interface) *AuthenticationV1alpha1Client {\n\treturn \u0026AuthenticationV1alpha1Client{c}\n}","line":{"from":82,"to":85}} {"id":100026274,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1alpha1/authentication_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1alpha1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":87,"to":98}} {"id":100026275,"name":"RESTClient","signature":"func (c *AuthenticationV1alpha1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1alpha1/authentication_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *AuthenticationV1alpha1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":100,"to":107}} {"id":100026276,"name":"newSelfSubjectReviews","signature":"func newSelfSubjectReviews(c *AuthenticationV1alpha1Client) *selfSubjectReviews","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1alpha1/selfsubjectreview.go","code":"// newSelfSubjectReviews returns a SelfSubjectReviews\nfunc newSelfSubjectReviews(c *AuthenticationV1alpha1Client) *selfSubjectReviews {\n\treturn \u0026selfSubjectReviews{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":47,"to":52}} {"id":100026277,"name":"Create","signature":"func (c *selfSubjectReviews) Create(ctx context.Context, selfSubjectReview *v1alpha1.SelfSubjectReview, opts v1.CreateOptions) (result *v1alpha1.SelfSubjectReview, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1alpha1/selfsubjectreview.go","code":"// Create takes the representation of a selfSubjectReview and creates it. Returns the server's representation of the selfSubjectReview, and an error, if there is any.\nfunc (c *selfSubjectReviews) Create(ctx context.Context, selfSubjectReview *v1alpha1.SelfSubjectReview, opts v1.CreateOptions) (result *v1alpha1.SelfSubjectReview, err error) {\n\tresult = \u0026v1alpha1.SelfSubjectReview{}\n\terr = c.client.Post().\n\t\tResource(\"selfsubjectreviews\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(selfSubjectReview).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":54,"to":64}} {"id":100026278,"name":"SelfSubjectReviews","signature":"func (c *AuthenticationV1beta1Client) SelfSubjectReviews() SelfSubjectReviewInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1beta1/authentication_client.go","code":"func (c *AuthenticationV1beta1Client) SelfSubjectReviews() SelfSubjectReviewInterface {\n\treturn newSelfSubjectReviews(c)\n}","line":{"from":40,"to":42}} {"id":100026279,"name":"TokenReviews","signature":"func (c *AuthenticationV1beta1Client) TokenReviews() TokenReviewInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1beta1/authentication_client.go","code":"func (c *AuthenticationV1beta1Client) TokenReviews() TokenReviewInterface {\n\treturn newTokenReviews(c)\n}","line":{"from":44,"to":46}} {"id":100026280,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*AuthenticationV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1beta1/authentication_client.go","code":"// NewForConfig creates a new AuthenticationV1beta1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*AuthenticationV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":48,"to":61}} {"id":100026281,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AuthenticationV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1beta1/authentication_client.go","code":"// NewForConfigAndClient creates a new AuthenticationV1beta1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*AuthenticationV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026AuthenticationV1beta1Client{client}, nil\n}","line":{"from":63,"to":75}} {"id":100026282,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *AuthenticationV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1beta1/authentication_client.go","code":"// NewForConfigOrDie creates a new AuthenticationV1beta1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *AuthenticationV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":77,"to":85}} {"id":100026283,"name":"New","signature":"func New(c rest.Interface) *AuthenticationV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1beta1/authentication_client.go","code":"// New creates a new AuthenticationV1beta1Client for the given RESTClient.\nfunc New(c rest.Interface) *AuthenticationV1beta1Client {\n\treturn \u0026AuthenticationV1beta1Client{c}\n}","line":{"from":87,"to":90}} {"id":100026284,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1beta1/authentication_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":92,"to":103}} {"id":100026285,"name":"RESTClient","signature":"func (c *AuthenticationV1beta1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1beta1/authentication_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *AuthenticationV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":105,"to":112}} {"id":100026286,"name":"newSelfSubjectReviews","signature":"func newSelfSubjectReviews(c *AuthenticationV1beta1Client) *selfSubjectReviews","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1beta1/selfsubjectreview.go","code":"// newSelfSubjectReviews returns a SelfSubjectReviews\nfunc newSelfSubjectReviews(c *AuthenticationV1beta1Client) *selfSubjectReviews {\n\treturn \u0026selfSubjectReviews{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":47,"to":52}} {"id":100026287,"name":"Create","signature":"func (c *selfSubjectReviews) Create(ctx context.Context, selfSubjectReview *v1beta1.SelfSubjectReview, opts v1.CreateOptions) (result *v1beta1.SelfSubjectReview, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1beta1/selfsubjectreview.go","code":"// Create takes the representation of a selfSubjectReview and creates it. Returns the server's representation of the selfSubjectReview, and an error, if there is any.\nfunc (c *selfSubjectReviews) Create(ctx context.Context, selfSubjectReview *v1beta1.SelfSubjectReview, opts v1.CreateOptions) (result *v1beta1.SelfSubjectReview, err error) {\n\tresult = \u0026v1beta1.SelfSubjectReview{}\n\terr = c.client.Post().\n\t\tResource(\"selfsubjectreviews\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(selfSubjectReview).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":54,"to":64}} {"id":100026288,"name":"newTokenReviews","signature":"func newTokenReviews(c *AuthenticationV1beta1Client) *tokenReviews","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1beta1/tokenreview.go","code":"// newTokenReviews returns a TokenReviews\nfunc newTokenReviews(c *AuthenticationV1beta1Client) *tokenReviews {\n\treturn \u0026tokenReviews{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":47,"to":52}} {"id":100026289,"name":"Create","signature":"func (c *tokenReviews) Create(ctx context.Context, tokenReview *v1beta1.TokenReview, opts v1.CreateOptions) (result *v1beta1.TokenReview, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/authentication/v1beta1/tokenreview.go","code":"// Create takes the representation of a tokenReview and creates it. Returns the server's representation of the tokenReview, and an error, if there is any.\nfunc (c *tokenReviews) Create(ctx context.Context, tokenReview *v1beta1.TokenReview, opts v1.CreateOptions) (result *v1beta1.TokenReview, err error) {\n\tresult = \u0026v1beta1.TokenReview{}\n\terr = c.client.Post().\n\t\tResource(\"tokenreviews\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(tokenReview).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":54,"to":64}} {"id":100026290,"name":"LocalSubjectAccessReviews","signature":"func (c *AuthorizationV1Client) LocalSubjectAccessReviews(namespace string) LocalSubjectAccessReviewInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1/authorization_client.go","code":"func (c *AuthorizationV1Client) LocalSubjectAccessReviews(namespace string) LocalSubjectAccessReviewInterface {\n\treturn newLocalSubjectAccessReviews(c, namespace)\n}","line":{"from":42,"to":44}} {"id":100026291,"name":"SelfSubjectAccessReviews","signature":"func (c *AuthorizationV1Client) SelfSubjectAccessReviews() SelfSubjectAccessReviewInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1/authorization_client.go","code":"func (c *AuthorizationV1Client) SelfSubjectAccessReviews() SelfSubjectAccessReviewInterface {\n\treturn newSelfSubjectAccessReviews(c)\n}","line":{"from":46,"to":48}} {"id":100026292,"name":"SelfSubjectRulesReviews","signature":"func (c *AuthorizationV1Client) SelfSubjectRulesReviews() SelfSubjectRulesReviewInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1/authorization_client.go","code":"func (c *AuthorizationV1Client) SelfSubjectRulesReviews() SelfSubjectRulesReviewInterface {\n\treturn newSelfSubjectRulesReviews(c)\n}","line":{"from":50,"to":52}} {"id":100026293,"name":"SubjectAccessReviews","signature":"func (c *AuthorizationV1Client) SubjectAccessReviews() SubjectAccessReviewInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1/authorization_client.go","code":"func (c *AuthorizationV1Client) SubjectAccessReviews() SubjectAccessReviewInterface {\n\treturn newSubjectAccessReviews(c)\n}","line":{"from":54,"to":56}} {"id":100026294,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*AuthorizationV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1/authorization_client.go","code":"// NewForConfig creates a new AuthorizationV1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*AuthorizationV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":58,"to":71}} {"id":100026295,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AuthorizationV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1/authorization_client.go","code":"// NewForConfigAndClient creates a new AuthorizationV1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*AuthorizationV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026AuthorizationV1Client{client}, nil\n}","line":{"from":73,"to":85}} {"id":100026296,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *AuthorizationV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1/authorization_client.go","code":"// NewForConfigOrDie creates a new AuthorizationV1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *AuthorizationV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":87,"to":95}} {"id":100026297,"name":"New","signature":"func New(c rest.Interface) *AuthorizationV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1/authorization_client.go","code":"// New creates a new AuthorizationV1Client for the given RESTClient.\nfunc New(c rest.Interface) *AuthorizationV1Client {\n\treturn \u0026AuthorizationV1Client{c}\n}","line":{"from":97,"to":100}} {"id":100026298,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1/authorization_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":102,"to":113}} {"id":100026299,"name":"RESTClient","signature":"func (c *AuthorizationV1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1/authorization_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *AuthorizationV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":115,"to":122}} {"id":100026300,"name":"newLocalSubjectAccessReviews","signature":"func newLocalSubjectAccessReviews(c *AuthorizationV1Client, namespace string) *localSubjectAccessReviews","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1/localsubjectaccessreview.go","code":"// newLocalSubjectAccessReviews returns a LocalSubjectAccessReviews\nfunc newLocalSubjectAccessReviews(c *AuthorizationV1Client, namespace string) *localSubjectAccessReviews {\n\treturn \u0026localSubjectAccessReviews{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":48,"to":54}} {"id":100026301,"name":"Create","signature":"func (c *localSubjectAccessReviews) Create(ctx context.Context, localSubjectAccessReview *v1.LocalSubjectAccessReview, opts metav1.CreateOptions) (result *v1.LocalSubjectAccessReview, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1/localsubjectaccessreview.go","code":"// Create takes the representation of a localSubjectAccessReview and creates it. Returns the server's representation of the localSubjectAccessReview, and an error, if there is any.\nfunc (c *localSubjectAccessReviews) Create(ctx context.Context, localSubjectAccessReview *v1.LocalSubjectAccessReview, opts metav1.CreateOptions) (result *v1.LocalSubjectAccessReview, err error) {\n\tresult = \u0026v1.LocalSubjectAccessReview{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"localsubjectaccessreviews\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(localSubjectAccessReview).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":56,"to":67}} {"id":100026302,"name":"newSelfSubjectAccessReviews","signature":"func newSelfSubjectAccessReviews(c *AuthorizationV1Client) *selfSubjectAccessReviews","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1/selfsubjectaccessreview.go","code":"// newSelfSubjectAccessReviews returns a SelfSubjectAccessReviews\nfunc newSelfSubjectAccessReviews(c *AuthorizationV1Client) *selfSubjectAccessReviews {\n\treturn \u0026selfSubjectAccessReviews{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":47,"to":52}} {"id":100026303,"name":"Create","signature":"func (c *selfSubjectAccessReviews) Create(ctx context.Context, selfSubjectAccessReview *v1.SelfSubjectAccessReview, opts metav1.CreateOptions) (result *v1.SelfSubjectAccessReview, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1/selfsubjectaccessreview.go","code":"// Create takes the representation of a selfSubjectAccessReview and creates it. Returns the server's representation of the selfSubjectAccessReview, and an error, if there is any.\nfunc (c *selfSubjectAccessReviews) Create(ctx context.Context, selfSubjectAccessReview *v1.SelfSubjectAccessReview, opts metav1.CreateOptions) (result *v1.SelfSubjectAccessReview, err error) {\n\tresult = \u0026v1.SelfSubjectAccessReview{}\n\terr = c.client.Post().\n\t\tResource(\"selfsubjectaccessreviews\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(selfSubjectAccessReview).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":54,"to":64}} {"id":100026304,"name":"newSelfSubjectRulesReviews","signature":"func newSelfSubjectRulesReviews(c *AuthorizationV1Client) *selfSubjectRulesReviews","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1/selfsubjectrulesreview.go","code":"// newSelfSubjectRulesReviews returns a SelfSubjectRulesReviews\nfunc newSelfSubjectRulesReviews(c *AuthorizationV1Client) *selfSubjectRulesReviews {\n\treturn \u0026selfSubjectRulesReviews{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":47,"to":52}} {"id":100026305,"name":"Create","signature":"func (c *selfSubjectRulesReviews) Create(ctx context.Context, selfSubjectRulesReview *v1.SelfSubjectRulesReview, opts metav1.CreateOptions) (result *v1.SelfSubjectRulesReview, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1/selfsubjectrulesreview.go","code":"// Create takes the representation of a selfSubjectRulesReview and creates it. Returns the server's representation of the selfSubjectRulesReview, and an error, if there is any.\nfunc (c *selfSubjectRulesReviews) Create(ctx context.Context, selfSubjectRulesReview *v1.SelfSubjectRulesReview, opts metav1.CreateOptions) (result *v1.SelfSubjectRulesReview, err error) {\n\tresult = \u0026v1.SelfSubjectRulesReview{}\n\terr = c.client.Post().\n\t\tResource(\"selfsubjectrulesreviews\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(selfSubjectRulesReview).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":54,"to":64}} {"id":100026306,"name":"newSubjectAccessReviews","signature":"func newSubjectAccessReviews(c *AuthorizationV1Client) *subjectAccessReviews","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1/subjectaccessreview.go","code":"// newSubjectAccessReviews returns a SubjectAccessReviews\nfunc newSubjectAccessReviews(c *AuthorizationV1Client) *subjectAccessReviews {\n\treturn \u0026subjectAccessReviews{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":47,"to":52}} {"id":100026307,"name":"Create","signature":"func (c *subjectAccessReviews) Create(ctx context.Context, subjectAccessReview *v1.SubjectAccessReview, opts metav1.CreateOptions) (result *v1.SubjectAccessReview, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1/subjectaccessreview.go","code":"// Create takes the representation of a subjectAccessReview and creates it. Returns the server's representation of the subjectAccessReview, and an error, if there is any.\nfunc (c *subjectAccessReviews) Create(ctx context.Context, subjectAccessReview *v1.SubjectAccessReview, opts metav1.CreateOptions) (result *v1.SubjectAccessReview, err error) {\n\tresult = \u0026v1.SubjectAccessReview{}\n\terr = c.client.Post().\n\t\tResource(\"subjectaccessreviews\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(subjectAccessReview).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":54,"to":64}} {"id":100026308,"name":"LocalSubjectAccessReviews","signature":"func (c *AuthorizationV1beta1Client) LocalSubjectAccessReviews(namespace string) LocalSubjectAccessReviewInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1beta1/authorization_client.go","code":"func (c *AuthorizationV1beta1Client) LocalSubjectAccessReviews(namespace string) LocalSubjectAccessReviewInterface {\n\treturn newLocalSubjectAccessReviews(c, namespace)\n}","line":{"from":42,"to":44}} {"id":100026309,"name":"SelfSubjectAccessReviews","signature":"func (c *AuthorizationV1beta1Client) SelfSubjectAccessReviews() SelfSubjectAccessReviewInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1beta1/authorization_client.go","code":"func (c *AuthorizationV1beta1Client) SelfSubjectAccessReviews() SelfSubjectAccessReviewInterface {\n\treturn newSelfSubjectAccessReviews(c)\n}","line":{"from":46,"to":48}} {"id":100026310,"name":"SelfSubjectRulesReviews","signature":"func (c *AuthorizationV1beta1Client) SelfSubjectRulesReviews() SelfSubjectRulesReviewInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1beta1/authorization_client.go","code":"func (c *AuthorizationV1beta1Client) SelfSubjectRulesReviews() SelfSubjectRulesReviewInterface {\n\treturn newSelfSubjectRulesReviews(c)\n}","line":{"from":50,"to":52}} {"id":100026311,"name":"SubjectAccessReviews","signature":"func (c *AuthorizationV1beta1Client) SubjectAccessReviews() SubjectAccessReviewInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1beta1/authorization_client.go","code":"func (c *AuthorizationV1beta1Client) SubjectAccessReviews() SubjectAccessReviewInterface {\n\treturn newSubjectAccessReviews(c)\n}","line":{"from":54,"to":56}} {"id":100026312,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*AuthorizationV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1beta1/authorization_client.go","code":"// NewForConfig creates a new AuthorizationV1beta1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*AuthorizationV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":58,"to":71}} {"id":100026313,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AuthorizationV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1beta1/authorization_client.go","code":"// NewForConfigAndClient creates a new AuthorizationV1beta1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*AuthorizationV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026AuthorizationV1beta1Client{client}, nil\n}","line":{"from":73,"to":85}} {"id":100026314,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *AuthorizationV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1beta1/authorization_client.go","code":"// NewForConfigOrDie creates a new AuthorizationV1beta1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *AuthorizationV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":87,"to":95}} {"id":100026315,"name":"New","signature":"func New(c rest.Interface) *AuthorizationV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1beta1/authorization_client.go","code":"// New creates a new AuthorizationV1beta1Client for the given RESTClient.\nfunc New(c rest.Interface) *AuthorizationV1beta1Client {\n\treturn \u0026AuthorizationV1beta1Client{c}\n}","line":{"from":97,"to":100}} {"id":100026316,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1beta1/authorization_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":102,"to":113}} {"id":100026317,"name":"RESTClient","signature":"func (c *AuthorizationV1beta1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1beta1/authorization_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *AuthorizationV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":115,"to":122}} {"id":100026318,"name":"newLocalSubjectAccessReviews","signature":"func newLocalSubjectAccessReviews(c *AuthorizationV1beta1Client, namespace string) *localSubjectAccessReviews","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1beta1/localsubjectaccessreview.go","code":"// newLocalSubjectAccessReviews returns a LocalSubjectAccessReviews\nfunc newLocalSubjectAccessReviews(c *AuthorizationV1beta1Client, namespace string) *localSubjectAccessReviews {\n\treturn \u0026localSubjectAccessReviews{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":48,"to":54}} {"id":100026319,"name":"Create","signature":"func (c *localSubjectAccessReviews) Create(ctx context.Context, localSubjectAccessReview *v1beta1.LocalSubjectAccessReview, opts v1.CreateOptions) (result *v1beta1.LocalSubjectAccessReview, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1beta1/localsubjectaccessreview.go","code":"// Create takes the representation of a localSubjectAccessReview and creates it. Returns the server's representation of the localSubjectAccessReview, and an error, if there is any.\nfunc (c *localSubjectAccessReviews) Create(ctx context.Context, localSubjectAccessReview *v1beta1.LocalSubjectAccessReview, opts v1.CreateOptions) (result *v1beta1.LocalSubjectAccessReview, err error) {\n\tresult = \u0026v1beta1.LocalSubjectAccessReview{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"localsubjectaccessreviews\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(localSubjectAccessReview).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":56,"to":67}} {"id":100026320,"name":"newSelfSubjectAccessReviews","signature":"func newSelfSubjectAccessReviews(c *AuthorizationV1beta1Client) *selfSubjectAccessReviews","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1beta1/selfsubjectaccessreview.go","code":"// newSelfSubjectAccessReviews returns a SelfSubjectAccessReviews\nfunc newSelfSubjectAccessReviews(c *AuthorizationV1beta1Client) *selfSubjectAccessReviews {\n\treturn \u0026selfSubjectAccessReviews{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":47,"to":52}} {"id":100026321,"name":"Create","signature":"func (c *selfSubjectAccessReviews) Create(ctx context.Context, selfSubjectAccessReview *v1beta1.SelfSubjectAccessReview, opts v1.CreateOptions) (result *v1beta1.SelfSubjectAccessReview, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1beta1/selfsubjectaccessreview.go","code":"// Create takes the representation of a selfSubjectAccessReview and creates it. Returns the server's representation of the selfSubjectAccessReview, and an error, if there is any.\nfunc (c *selfSubjectAccessReviews) Create(ctx context.Context, selfSubjectAccessReview *v1beta1.SelfSubjectAccessReview, opts v1.CreateOptions) (result *v1beta1.SelfSubjectAccessReview, err error) {\n\tresult = \u0026v1beta1.SelfSubjectAccessReview{}\n\terr = c.client.Post().\n\t\tResource(\"selfsubjectaccessreviews\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(selfSubjectAccessReview).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":54,"to":64}} {"id":100026322,"name":"newSelfSubjectRulesReviews","signature":"func newSelfSubjectRulesReviews(c *AuthorizationV1beta1Client) *selfSubjectRulesReviews","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1beta1/selfsubjectrulesreview.go","code":"// newSelfSubjectRulesReviews returns a SelfSubjectRulesReviews\nfunc newSelfSubjectRulesReviews(c *AuthorizationV1beta1Client) *selfSubjectRulesReviews {\n\treturn \u0026selfSubjectRulesReviews{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":47,"to":52}} {"id":100026323,"name":"Create","signature":"func (c *selfSubjectRulesReviews) Create(ctx context.Context, selfSubjectRulesReview *v1beta1.SelfSubjectRulesReview, opts v1.CreateOptions) (result *v1beta1.SelfSubjectRulesReview, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1beta1/selfsubjectrulesreview.go","code":"// Create takes the representation of a selfSubjectRulesReview and creates it. Returns the server's representation of the selfSubjectRulesReview, and an error, if there is any.\nfunc (c *selfSubjectRulesReviews) Create(ctx context.Context, selfSubjectRulesReview *v1beta1.SelfSubjectRulesReview, opts v1.CreateOptions) (result *v1beta1.SelfSubjectRulesReview, err error) {\n\tresult = \u0026v1beta1.SelfSubjectRulesReview{}\n\terr = c.client.Post().\n\t\tResource(\"selfsubjectrulesreviews\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(selfSubjectRulesReview).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":54,"to":64}} {"id":100026324,"name":"newSubjectAccessReviews","signature":"func newSubjectAccessReviews(c *AuthorizationV1beta1Client) *subjectAccessReviews","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1beta1/subjectaccessreview.go","code":"// newSubjectAccessReviews returns a SubjectAccessReviews\nfunc newSubjectAccessReviews(c *AuthorizationV1beta1Client) *subjectAccessReviews {\n\treturn \u0026subjectAccessReviews{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":47,"to":52}} {"id":100026325,"name":"Create","signature":"func (c *subjectAccessReviews) Create(ctx context.Context, subjectAccessReview *v1beta1.SubjectAccessReview, opts v1.CreateOptions) (result *v1beta1.SubjectAccessReview, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/authorization/v1beta1/subjectaccessreview.go","code":"// Create takes the representation of a subjectAccessReview and creates it. Returns the server's representation of the subjectAccessReview, and an error, if there is any.\nfunc (c *subjectAccessReviews) Create(ctx context.Context, subjectAccessReview *v1beta1.SubjectAccessReview, opts v1.CreateOptions) (result *v1beta1.SubjectAccessReview, err error) {\n\tresult = \u0026v1beta1.SubjectAccessReview{}\n\terr = c.client.Post().\n\t\tResource(\"subjectaccessreviews\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(subjectAccessReview).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":54,"to":64}} {"id":100026326,"name":"HorizontalPodAutoscalers","signature":"func (c *AutoscalingV1Client) HorizontalPodAutoscalers(namespace string) HorizontalPodAutoscalerInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v1/autoscaling_client.go","code":"func (c *AutoscalingV1Client) HorizontalPodAutoscalers(namespace string) HorizontalPodAutoscalerInterface {\n\treturn newHorizontalPodAutoscalers(c, namespace)\n}","line":{"from":39,"to":41}} {"id":100026327,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*AutoscalingV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v1/autoscaling_client.go","code":"// NewForConfig creates a new AutoscalingV1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*AutoscalingV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":43,"to":56}} {"id":100026328,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AutoscalingV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v1/autoscaling_client.go","code":"// NewForConfigAndClient creates a new AutoscalingV1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*AutoscalingV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026AutoscalingV1Client{client}, nil\n}","line":{"from":58,"to":70}} {"id":100026329,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *AutoscalingV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v1/autoscaling_client.go","code":"// NewForConfigOrDie creates a new AutoscalingV1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *AutoscalingV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":72,"to":80}} {"id":100026330,"name":"New","signature":"func New(c rest.Interface) *AutoscalingV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v1/autoscaling_client.go","code":"// New creates a new AutoscalingV1Client for the given RESTClient.\nfunc New(c rest.Interface) *AutoscalingV1Client {\n\treturn \u0026AutoscalingV1Client{c}\n}","line":{"from":82,"to":85}} {"id":100026331,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v1/autoscaling_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":87,"to":98}} {"id":100026332,"name":"RESTClient","signature":"func (c *AutoscalingV1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v1/autoscaling_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *AutoscalingV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":100,"to":107}} {"id":100026333,"name":"newHorizontalPodAutoscalers","signature":"func newHorizontalPodAutoscalers(c *AutoscalingV1Client, namespace string) *horizontalPodAutoscalers","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v1/horizontalpodautoscaler.go","code":"// newHorizontalPodAutoscalers returns a HorizontalPodAutoscalers\nfunc newHorizontalPodAutoscalers(c *AutoscalingV1Client, namespace string) *horizontalPodAutoscalers {\n\treturn \u0026horizontalPodAutoscalers{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":64,"to":70}} {"id":100026334,"name":"Get","signature":"func (c *horizontalPodAutoscalers) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v1/horizontalpodautoscaler.go","code":"// Get takes name of the horizontalPodAutoscaler, and returns the corresponding horizontalPodAutoscaler object, and an error if there is any.\nfunc (c *horizontalPodAutoscalers) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.HorizontalPodAutoscaler, err error) {\n\tresult = \u0026v1.HorizontalPodAutoscaler{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":72,"to":83}} {"id":100026335,"name":"List","signature":"func (c *horizontalPodAutoscalers) List(ctx context.Context, opts metav1.ListOptions) (result *v1.HorizontalPodAutoscalerList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v1/horizontalpodautoscaler.go","code":"// List takes label and field selectors, and returns the list of HorizontalPodAutoscalers that match those selectors.\nfunc (c *horizontalPodAutoscalers) List(ctx context.Context, opts metav1.ListOptions) (result *v1.HorizontalPodAutoscalerList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.HorizontalPodAutoscalerList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":85,"to":100}} {"id":100026336,"name":"Watch","signature":"func (c *horizontalPodAutoscalers) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v1/horizontalpodautoscaler.go","code":"// Watch returns a watch.Interface that watches the requested horizontalPodAutoscalers.\nfunc (c *horizontalPodAutoscalers) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":102,"to":115}} {"id":100026337,"name":"Create","signature":"func (c *horizontalPodAutoscalers) Create(ctx context.Context, horizontalPodAutoscaler *v1.HorizontalPodAutoscaler, opts metav1.CreateOptions) (result *v1.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v1/horizontalpodautoscaler.go","code":"// Create takes the representation of a horizontalPodAutoscaler and creates it. Returns the server's representation of the horizontalPodAutoscaler, and an error, if there is any.\nfunc (c *horizontalPodAutoscalers) Create(ctx context.Context, horizontalPodAutoscaler *v1.HorizontalPodAutoscaler, opts metav1.CreateOptions) (result *v1.HorizontalPodAutoscaler, err error) {\n\tresult = \u0026v1.HorizontalPodAutoscaler{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(horizontalPodAutoscaler).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":117,"to":128}} {"id":100026338,"name":"Update","signature":"func (c *horizontalPodAutoscalers) Update(ctx context.Context, horizontalPodAutoscaler *v1.HorizontalPodAutoscaler, opts metav1.UpdateOptions) (result *v1.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v1/horizontalpodautoscaler.go","code":"// Update takes the representation of a horizontalPodAutoscaler and updates it. Returns the server's representation of the horizontalPodAutoscaler, and an error, if there is any.\nfunc (c *horizontalPodAutoscalers) Update(ctx context.Context, horizontalPodAutoscaler *v1.HorizontalPodAutoscaler, opts metav1.UpdateOptions) (result *v1.HorizontalPodAutoscaler, err error) {\n\tresult = \u0026v1.HorizontalPodAutoscaler{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(horizontalPodAutoscaler.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(horizontalPodAutoscaler).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":130,"to":142}} {"id":100026339,"name":"UpdateStatus","signature":"func (c *horizontalPodAutoscalers) UpdateStatus(ctx context.Context, horizontalPodAutoscaler *v1.HorizontalPodAutoscaler, opts metav1.UpdateOptions) (result *v1.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v1/horizontalpodautoscaler.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *horizontalPodAutoscalers) UpdateStatus(ctx context.Context, horizontalPodAutoscaler *v1.HorizontalPodAutoscaler, opts metav1.UpdateOptions) (result *v1.HorizontalPodAutoscaler, err error) {\n\tresult = \u0026v1.HorizontalPodAutoscaler{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(horizontalPodAutoscaler.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(horizontalPodAutoscaler).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":144,"to":158}} {"id":100026340,"name":"Delete","signature":"func (c *horizontalPodAutoscalers) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v1/horizontalpodautoscaler.go","code":"// Delete takes name of the horizontalPodAutoscaler and deletes it. Returns an error if one occurs.\nfunc (c *horizontalPodAutoscalers) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":160,"to":169}} {"id":100026341,"name":"DeleteCollection","signature":"func (c *horizontalPodAutoscalers) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v1/horizontalpodautoscaler.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *horizontalPodAutoscalers) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":171,"to":185}} {"id":100026342,"name":"Patch","signature":"func (c *horizontalPodAutoscalers) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v1/horizontalpodautoscaler.go","code":"// Patch applies the patch and returns the patched horizontalPodAutoscaler.\nfunc (c *horizontalPodAutoscalers) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.HorizontalPodAutoscaler, err error) {\n\tresult = \u0026v1.HorizontalPodAutoscaler{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":187,"to":200}} {"id":100026343,"name":"Apply","signature":"func (c *horizontalPodAutoscalers) Apply(ctx context.Context, horizontalPodAutoscaler *autoscalingv1.HorizontalPodAutoscalerApplyConfiguration, opts metav1.ApplyOptions) (result *v1.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v1/horizontalpodautoscaler.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied horizontalPodAutoscaler.\nfunc (c *horizontalPodAutoscalers) Apply(ctx context.Context, horizontalPodAutoscaler *autoscalingv1.HorizontalPodAutoscalerApplyConfiguration, opts metav1.ApplyOptions) (result *v1.HorizontalPodAutoscaler, err error) {\n\tif horizontalPodAutoscaler == nil {\n\t\treturn nil, fmt.Errorf(\"horizontalPodAutoscaler provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(horizontalPodAutoscaler)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := horizontalPodAutoscaler.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"horizontalPodAutoscaler.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.HorizontalPodAutoscaler{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":202,"to":226}} {"id":100026344,"name":"ApplyStatus","signature":"func (c *horizontalPodAutoscalers) ApplyStatus(ctx context.Context, horizontalPodAutoscaler *autoscalingv1.HorizontalPodAutoscalerApplyConfiguration, opts metav1.ApplyOptions) (result *v1.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v1/horizontalpodautoscaler.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *horizontalPodAutoscalers) ApplyStatus(ctx context.Context, horizontalPodAutoscaler *autoscalingv1.HorizontalPodAutoscalerApplyConfiguration, opts metav1.ApplyOptions) (result *v1.HorizontalPodAutoscaler, err error) {\n\tif horizontalPodAutoscaler == nil {\n\t\treturn nil, fmt.Errorf(\"horizontalPodAutoscaler provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(horizontalPodAutoscaler)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := horizontalPodAutoscaler.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"horizontalPodAutoscaler.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1.HorizontalPodAutoscaler{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":228,"to":256}} {"id":100026345,"name":"HorizontalPodAutoscalers","signature":"func (c *AutoscalingV2Client) HorizontalPodAutoscalers(namespace string) HorizontalPodAutoscalerInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2/autoscaling_client.go","code":"func (c *AutoscalingV2Client) HorizontalPodAutoscalers(namespace string) HorizontalPodAutoscalerInterface {\n\treturn newHorizontalPodAutoscalers(c, namespace)\n}","line":{"from":39,"to":41}} {"id":100026346,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*AutoscalingV2Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2/autoscaling_client.go","code":"// NewForConfig creates a new AutoscalingV2Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*AutoscalingV2Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":43,"to":56}} {"id":100026347,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AutoscalingV2Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2/autoscaling_client.go","code":"// NewForConfigAndClient creates a new AutoscalingV2Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*AutoscalingV2Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026AutoscalingV2Client{client}, nil\n}","line":{"from":58,"to":70}} {"id":100026348,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *AutoscalingV2Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2/autoscaling_client.go","code":"// NewForConfigOrDie creates a new AutoscalingV2Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *AutoscalingV2Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":72,"to":80}} {"id":100026349,"name":"New","signature":"func New(c rest.Interface) *AutoscalingV2Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2/autoscaling_client.go","code":"// New creates a new AutoscalingV2Client for the given RESTClient.\nfunc New(c rest.Interface) *AutoscalingV2Client {\n\treturn \u0026AutoscalingV2Client{c}\n}","line":{"from":82,"to":85}} {"id":100026350,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2/autoscaling_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v2.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":87,"to":98}} {"id":100026351,"name":"RESTClient","signature":"func (c *AutoscalingV2Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2/autoscaling_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *AutoscalingV2Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":100,"to":107}} {"id":100026352,"name":"newHorizontalPodAutoscalers","signature":"func newHorizontalPodAutoscalers(c *AutoscalingV2Client, namespace string) *horizontalPodAutoscalers","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2/horizontalpodautoscaler.go","code":"// newHorizontalPodAutoscalers returns a HorizontalPodAutoscalers\nfunc newHorizontalPodAutoscalers(c *AutoscalingV2Client, namespace string) *horizontalPodAutoscalers {\n\treturn \u0026horizontalPodAutoscalers{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":64,"to":70}} {"id":100026353,"name":"Get","signature":"func (c *horizontalPodAutoscalers) Get(ctx context.Context, name string, options v1.GetOptions) (result *v2.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2/horizontalpodautoscaler.go","code":"// Get takes name of the horizontalPodAutoscaler, and returns the corresponding horizontalPodAutoscaler object, and an error if there is any.\nfunc (c *horizontalPodAutoscalers) Get(ctx context.Context, name string, options v1.GetOptions) (result *v2.HorizontalPodAutoscaler, err error) {\n\tresult = \u0026v2.HorizontalPodAutoscaler{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":72,"to":83}} {"id":100026354,"name":"List","signature":"func (c *horizontalPodAutoscalers) List(ctx context.Context, opts v1.ListOptions) (result *v2.HorizontalPodAutoscalerList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2/horizontalpodautoscaler.go","code":"// List takes label and field selectors, and returns the list of HorizontalPodAutoscalers that match those selectors.\nfunc (c *horizontalPodAutoscalers) List(ctx context.Context, opts v1.ListOptions) (result *v2.HorizontalPodAutoscalerList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v2.HorizontalPodAutoscalerList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":85,"to":100}} {"id":100026355,"name":"Watch","signature":"func (c *horizontalPodAutoscalers) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2/horizontalpodautoscaler.go","code":"// Watch returns a watch.Interface that watches the requested horizontalPodAutoscalers.\nfunc (c *horizontalPodAutoscalers) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":102,"to":115}} {"id":100026356,"name":"Create","signature":"func (c *horizontalPodAutoscalers) Create(ctx context.Context, horizontalPodAutoscaler *v2.HorizontalPodAutoscaler, opts v1.CreateOptions) (result *v2.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2/horizontalpodautoscaler.go","code":"// Create takes the representation of a horizontalPodAutoscaler and creates it. Returns the server's representation of the horizontalPodAutoscaler, and an error, if there is any.\nfunc (c *horizontalPodAutoscalers) Create(ctx context.Context, horizontalPodAutoscaler *v2.HorizontalPodAutoscaler, opts v1.CreateOptions) (result *v2.HorizontalPodAutoscaler, err error) {\n\tresult = \u0026v2.HorizontalPodAutoscaler{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(horizontalPodAutoscaler).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":117,"to":128}} {"id":100026357,"name":"Update","signature":"func (c *horizontalPodAutoscalers) Update(ctx context.Context, horizontalPodAutoscaler *v2.HorizontalPodAutoscaler, opts v1.UpdateOptions) (result *v2.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2/horizontalpodautoscaler.go","code":"// Update takes the representation of a horizontalPodAutoscaler and updates it. Returns the server's representation of the horizontalPodAutoscaler, and an error, if there is any.\nfunc (c *horizontalPodAutoscalers) Update(ctx context.Context, horizontalPodAutoscaler *v2.HorizontalPodAutoscaler, opts v1.UpdateOptions) (result *v2.HorizontalPodAutoscaler, err error) {\n\tresult = \u0026v2.HorizontalPodAutoscaler{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(horizontalPodAutoscaler.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(horizontalPodAutoscaler).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":130,"to":142}} {"id":100026358,"name":"UpdateStatus","signature":"func (c *horizontalPodAutoscalers) UpdateStatus(ctx context.Context, horizontalPodAutoscaler *v2.HorizontalPodAutoscaler, opts v1.UpdateOptions) (result *v2.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2/horizontalpodautoscaler.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *horizontalPodAutoscalers) UpdateStatus(ctx context.Context, horizontalPodAutoscaler *v2.HorizontalPodAutoscaler, opts v1.UpdateOptions) (result *v2.HorizontalPodAutoscaler, err error) {\n\tresult = \u0026v2.HorizontalPodAutoscaler{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(horizontalPodAutoscaler.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(horizontalPodAutoscaler).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":144,"to":158}} {"id":100026359,"name":"Delete","signature":"func (c *horizontalPodAutoscalers) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2/horizontalpodautoscaler.go","code":"// Delete takes name of the horizontalPodAutoscaler and deletes it. Returns an error if one occurs.\nfunc (c *horizontalPodAutoscalers) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":160,"to":169}} {"id":100026360,"name":"DeleteCollection","signature":"func (c *horizontalPodAutoscalers) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2/horizontalpodautoscaler.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *horizontalPodAutoscalers) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":171,"to":185}} {"id":100026361,"name":"Patch","signature":"func (c *horizontalPodAutoscalers) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v2.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2/horizontalpodautoscaler.go","code":"// Patch applies the patch and returns the patched horizontalPodAutoscaler.\nfunc (c *horizontalPodAutoscalers) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v2.HorizontalPodAutoscaler, err error) {\n\tresult = \u0026v2.HorizontalPodAutoscaler{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":187,"to":200}} {"id":100026362,"name":"Apply","signature":"func (c *horizontalPodAutoscalers) Apply(ctx context.Context, horizontalPodAutoscaler *autoscalingv2.HorizontalPodAutoscalerApplyConfiguration, opts v1.ApplyOptions) (result *v2.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2/horizontalpodautoscaler.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied horizontalPodAutoscaler.\nfunc (c *horizontalPodAutoscalers) Apply(ctx context.Context, horizontalPodAutoscaler *autoscalingv2.HorizontalPodAutoscalerApplyConfiguration, opts v1.ApplyOptions) (result *v2.HorizontalPodAutoscaler, err error) {\n\tif horizontalPodAutoscaler == nil {\n\t\treturn nil, fmt.Errorf(\"horizontalPodAutoscaler provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(horizontalPodAutoscaler)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := horizontalPodAutoscaler.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"horizontalPodAutoscaler.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v2.HorizontalPodAutoscaler{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":202,"to":226}} {"id":100026363,"name":"ApplyStatus","signature":"func (c *horizontalPodAutoscalers) ApplyStatus(ctx context.Context, horizontalPodAutoscaler *autoscalingv2.HorizontalPodAutoscalerApplyConfiguration, opts v1.ApplyOptions) (result *v2.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2/horizontalpodautoscaler.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *horizontalPodAutoscalers) ApplyStatus(ctx context.Context, horizontalPodAutoscaler *autoscalingv2.HorizontalPodAutoscalerApplyConfiguration, opts v1.ApplyOptions) (result *v2.HorizontalPodAutoscaler, err error) {\n\tif horizontalPodAutoscaler == nil {\n\t\treturn nil, fmt.Errorf(\"horizontalPodAutoscaler provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(horizontalPodAutoscaler)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := horizontalPodAutoscaler.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"horizontalPodAutoscaler.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v2.HorizontalPodAutoscaler{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":228,"to":256}} {"id":100026364,"name":"HorizontalPodAutoscalers","signature":"func (c *AutoscalingV2beta1Client) HorizontalPodAutoscalers(namespace string) HorizontalPodAutoscalerInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta1/autoscaling_client.go","code":"func (c *AutoscalingV2beta1Client) HorizontalPodAutoscalers(namespace string) HorizontalPodAutoscalerInterface {\n\treturn newHorizontalPodAutoscalers(c, namespace)\n}","line":{"from":39,"to":41}} {"id":100026365,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*AutoscalingV2beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta1/autoscaling_client.go","code":"// NewForConfig creates a new AutoscalingV2beta1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*AutoscalingV2beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":43,"to":56}} {"id":100026366,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AutoscalingV2beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta1/autoscaling_client.go","code":"// NewForConfigAndClient creates a new AutoscalingV2beta1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*AutoscalingV2beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026AutoscalingV2beta1Client{client}, nil\n}","line":{"from":58,"to":70}} {"id":100026367,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *AutoscalingV2beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta1/autoscaling_client.go","code":"// NewForConfigOrDie creates a new AutoscalingV2beta1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *AutoscalingV2beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":72,"to":80}} {"id":100026368,"name":"New","signature":"func New(c rest.Interface) *AutoscalingV2beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta1/autoscaling_client.go","code":"// New creates a new AutoscalingV2beta1Client for the given RESTClient.\nfunc New(c rest.Interface) *AutoscalingV2beta1Client {\n\treturn \u0026AutoscalingV2beta1Client{c}\n}","line":{"from":82,"to":85}} {"id":100026369,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta1/autoscaling_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v2beta1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":87,"to":98}} {"id":100026370,"name":"RESTClient","signature":"func (c *AutoscalingV2beta1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta1/autoscaling_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *AutoscalingV2beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":100,"to":107}} {"id":100026371,"name":"newHorizontalPodAutoscalers","signature":"func newHorizontalPodAutoscalers(c *AutoscalingV2beta1Client, namespace string) *horizontalPodAutoscalers","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// newHorizontalPodAutoscalers returns a HorizontalPodAutoscalers\nfunc newHorizontalPodAutoscalers(c *AutoscalingV2beta1Client, namespace string) *horizontalPodAutoscalers {\n\treturn \u0026horizontalPodAutoscalers{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":64,"to":70}} {"id":100026372,"name":"Get","signature":"func (c *horizontalPodAutoscalers) Get(ctx context.Context, name string, options v1.GetOptions) (result *v2beta1.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// Get takes name of the horizontalPodAutoscaler, and returns the corresponding horizontalPodAutoscaler object, and an error if there is any.\nfunc (c *horizontalPodAutoscalers) Get(ctx context.Context, name string, options v1.GetOptions) (result *v2beta1.HorizontalPodAutoscaler, err error) {\n\tresult = \u0026v2beta1.HorizontalPodAutoscaler{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":72,"to":83}} {"id":100026373,"name":"List","signature":"func (c *horizontalPodAutoscalers) List(ctx context.Context, opts v1.ListOptions) (result *v2beta1.HorizontalPodAutoscalerList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// List takes label and field selectors, and returns the list of HorizontalPodAutoscalers that match those selectors.\nfunc (c *horizontalPodAutoscalers) List(ctx context.Context, opts v1.ListOptions) (result *v2beta1.HorizontalPodAutoscalerList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v2beta1.HorizontalPodAutoscalerList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":85,"to":100}} {"id":100026374,"name":"Watch","signature":"func (c *horizontalPodAutoscalers) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// Watch returns a watch.Interface that watches the requested horizontalPodAutoscalers.\nfunc (c *horizontalPodAutoscalers) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":102,"to":115}} {"id":100026375,"name":"Create","signature":"func (c *horizontalPodAutoscalers) Create(ctx context.Context, horizontalPodAutoscaler *v2beta1.HorizontalPodAutoscaler, opts v1.CreateOptions) (result *v2beta1.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// Create takes the representation of a horizontalPodAutoscaler and creates it. Returns the server's representation of the horizontalPodAutoscaler, and an error, if there is any.\nfunc (c *horizontalPodAutoscalers) Create(ctx context.Context, horizontalPodAutoscaler *v2beta1.HorizontalPodAutoscaler, opts v1.CreateOptions) (result *v2beta1.HorizontalPodAutoscaler, err error) {\n\tresult = \u0026v2beta1.HorizontalPodAutoscaler{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(horizontalPodAutoscaler).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":117,"to":128}} {"id":100026376,"name":"Update","signature":"func (c *horizontalPodAutoscalers) Update(ctx context.Context, horizontalPodAutoscaler *v2beta1.HorizontalPodAutoscaler, opts v1.UpdateOptions) (result *v2beta1.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// Update takes the representation of a horizontalPodAutoscaler and updates it. Returns the server's representation of the horizontalPodAutoscaler, and an error, if there is any.\nfunc (c *horizontalPodAutoscalers) Update(ctx context.Context, horizontalPodAutoscaler *v2beta1.HorizontalPodAutoscaler, opts v1.UpdateOptions) (result *v2beta1.HorizontalPodAutoscaler, err error) {\n\tresult = \u0026v2beta1.HorizontalPodAutoscaler{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(horizontalPodAutoscaler.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(horizontalPodAutoscaler).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":130,"to":142}} {"id":100026377,"name":"UpdateStatus","signature":"func (c *horizontalPodAutoscalers) UpdateStatus(ctx context.Context, horizontalPodAutoscaler *v2beta1.HorizontalPodAutoscaler, opts v1.UpdateOptions) (result *v2beta1.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *horizontalPodAutoscalers) UpdateStatus(ctx context.Context, horizontalPodAutoscaler *v2beta1.HorizontalPodAutoscaler, opts v1.UpdateOptions) (result *v2beta1.HorizontalPodAutoscaler, err error) {\n\tresult = \u0026v2beta1.HorizontalPodAutoscaler{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(horizontalPodAutoscaler.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(horizontalPodAutoscaler).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":144,"to":158}} {"id":100026378,"name":"Delete","signature":"func (c *horizontalPodAutoscalers) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// Delete takes name of the horizontalPodAutoscaler and deletes it. Returns an error if one occurs.\nfunc (c *horizontalPodAutoscalers) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":160,"to":169}} {"id":100026379,"name":"DeleteCollection","signature":"func (c *horizontalPodAutoscalers) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *horizontalPodAutoscalers) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":171,"to":185}} {"id":100026380,"name":"Patch","signature":"func (c *horizontalPodAutoscalers) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v2beta1.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// Patch applies the patch and returns the patched horizontalPodAutoscaler.\nfunc (c *horizontalPodAutoscalers) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v2beta1.HorizontalPodAutoscaler, err error) {\n\tresult = \u0026v2beta1.HorizontalPodAutoscaler{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":187,"to":200}} {"id":100026381,"name":"Apply","signature":"func (c *horizontalPodAutoscalers) Apply(ctx context.Context, horizontalPodAutoscaler *autoscalingv2beta1.HorizontalPodAutoscalerApplyConfiguration, opts v1.ApplyOptions) (result *v2beta1.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied horizontalPodAutoscaler.\nfunc (c *horizontalPodAutoscalers) Apply(ctx context.Context, horizontalPodAutoscaler *autoscalingv2beta1.HorizontalPodAutoscalerApplyConfiguration, opts v1.ApplyOptions) (result *v2beta1.HorizontalPodAutoscaler, err error) {\n\tif horizontalPodAutoscaler == nil {\n\t\treturn nil, fmt.Errorf(\"horizontalPodAutoscaler provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(horizontalPodAutoscaler)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := horizontalPodAutoscaler.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"horizontalPodAutoscaler.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v2beta1.HorizontalPodAutoscaler{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":202,"to":226}} {"id":100026382,"name":"ApplyStatus","signature":"func (c *horizontalPodAutoscalers) ApplyStatus(ctx context.Context, horizontalPodAutoscaler *autoscalingv2beta1.HorizontalPodAutoscalerApplyConfiguration, opts v1.ApplyOptions) (result *v2beta1.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *horizontalPodAutoscalers) ApplyStatus(ctx context.Context, horizontalPodAutoscaler *autoscalingv2beta1.HorizontalPodAutoscalerApplyConfiguration, opts v1.ApplyOptions) (result *v2beta1.HorizontalPodAutoscaler, err error) {\n\tif horizontalPodAutoscaler == nil {\n\t\treturn nil, fmt.Errorf(\"horizontalPodAutoscaler provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(horizontalPodAutoscaler)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := horizontalPodAutoscaler.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"horizontalPodAutoscaler.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v2beta1.HorizontalPodAutoscaler{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":228,"to":256}} {"id":100026383,"name":"HorizontalPodAutoscalers","signature":"func (c *AutoscalingV2beta2Client) HorizontalPodAutoscalers(namespace string) HorizontalPodAutoscalerInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta2/autoscaling_client.go","code":"func (c *AutoscalingV2beta2Client) HorizontalPodAutoscalers(namespace string) HorizontalPodAutoscalerInterface {\n\treturn newHorizontalPodAutoscalers(c, namespace)\n}","line":{"from":39,"to":41}} {"id":100026384,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*AutoscalingV2beta2Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta2/autoscaling_client.go","code":"// NewForConfig creates a new AutoscalingV2beta2Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*AutoscalingV2beta2Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":43,"to":56}} {"id":100026385,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*AutoscalingV2beta2Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta2/autoscaling_client.go","code":"// NewForConfigAndClient creates a new AutoscalingV2beta2Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*AutoscalingV2beta2Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026AutoscalingV2beta2Client{client}, nil\n}","line":{"from":58,"to":70}} {"id":100026386,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *AutoscalingV2beta2Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta2/autoscaling_client.go","code":"// NewForConfigOrDie creates a new AutoscalingV2beta2Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *AutoscalingV2beta2Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":72,"to":80}} {"id":100026387,"name":"New","signature":"func New(c rest.Interface) *AutoscalingV2beta2Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta2/autoscaling_client.go","code":"// New creates a new AutoscalingV2beta2Client for the given RESTClient.\nfunc New(c rest.Interface) *AutoscalingV2beta2Client {\n\treturn \u0026AutoscalingV2beta2Client{c}\n}","line":{"from":82,"to":85}} {"id":100026388,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta2/autoscaling_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v2beta2.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":87,"to":98}} {"id":100026389,"name":"RESTClient","signature":"func (c *AutoscalingV2beta2Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta2/autoscaling_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *AutoscalingV2beta2Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":100,"to":107}} {"id":100026390,"name":"newHorizontalPodAutoscalers","signature":"func newHorizontalPodAutoscalers(c *AutoscalingV2beta2Client, namespace string) *horizontalPodAutoscalers","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// newHorizontalPodAutoscalers returns a HorizontalPodAutoscalers\nfunc newHorizontalPodAutoscalers(c *AutoscalingV2beta2Client, namespace string) *horizontalPodAutoscalers {\n\treturn \u0026horizontalPodAutoscalers{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":64,"to":70}} {"id":100026391,"name":"Get","signature":"func (c *horizontalPodAutoscalers) Get(ctx context.Context, name string, options v1.GetOptions) (result *v2beta2.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// Get takes name of the horizontalPodAutoscaler, and returns the corresponding horizontalPodAutoscaler object, and an error if there is any.\nfunc (c *horizontalPodAutoscalers) Get(ctx context.Context, name string, options v1.GetOptions) (result *v2beta2.HorizontalPodAutoscaler, err error) {\n\tresult = \u0026v2beta2.HorizontalPodAutoscaler{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":72,"to":83}} {"id":100026392,"name":"List","signature":"func (c *horizontalPodAutoscalers) List(ctx context.Context, opts v1.ListOptions) (result *v2beta2.HorizontalPodAutoscalerList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// List takes label and field selectors, and returns the list of HorizontalPodAutoscalers that match those selectors.\nfunc (c *horizontalPodAutoscalers) List(ctx context.Context, opts v1.ListOptions) (result *v2beta2.HorizontalPodAutoscalerList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v2beta2.HorizontalPodAutoscalerList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":85,"to":100}} {"id":100026393,"name":"Watch","signature":"func (c *horizontalPodAutoscalers) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// Watch returns a watch.Interface that watches the requested horizontalPodAutoscalers.\nfunc (c *horizontalPodAutoscalers) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":102,"to":115}} {"id":100026394,"name":"Create","signature":"func (c *horizontalPodAutoscalers) Create(ctx context.Context, horizontalPodAutoscaler *v2beta2.HorizontalPodAutoscaler, opts v1.CreateOptions) (result *v2beta2.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// Create takes the representation of a horizontalPodAutoscaler and creates it. Returns the server's representation of the horizontalPodAutoscaler, and an error, if there is any.\nfunc (c *horizontalPodAutoscalers) Create(ctx context.Context, horizontalPodAutoscaler *v2beta2.HorizontalPodAutoscaler, opts v1.CreateOptions) (result *v2beta2.HorizontalPodAutoscaler, err error) {\n\tresult = \u0026v2beta2.HorizontalPodAutoscaler{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(horizontalPodAutoscaler).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":117,"to":128}} {"id":100026395,"name":"Update","signature":"func (c *horizontalPodAutoscalers) Update(ctx context.Context, horizontalPodAutoscaler *v2beta2.HorizontalPodAutoscaler, opts v1.UpdateOptions) (result *v2beta2.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// Update takes the representation of a horizontalPodAutoscaler and updates it. Returns the server's representation of the horizontalPodAutoscaler, and an error, if there is any.\nfunc (c *horizontalPodAutoscalers) Update(ctx context.Context, horizontalPodAutoscaler *v2beta2.HorizontalPodAutoscaler, opts v1.UpdateOptions) (result *v2beta2.HorizontalPodAutoscaler, err error) {\n\tresult = \u0026v2beta2.HorizontalPodAutoscaler{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(horizontalPodAutoscaler.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(horizontalPodAutoscaler).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":130,"to":142}} {"id":100026396,"name":"UpdateStatus","signature":"func (c *horizontalPodAutoscalers) UpdateStatus(ctx context.Context, horizontalPodAutoscaler *v2beta2.HorizontalPodAutoscaler, opts v1.UpdateOptions) (result *v2beta2.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *horizontalPodAutoscalers) UpdateStatus(ctx context.Context, horizontalPodAutoscaler *v2beta2.HorizontalPodAutoscaler, opts v1.UpdateOptions) (result *v2beta2.HorizontalPodAutoscaler, err error) {\n\tresult = \u0026v2beta2.HorizontalPodAutoscaler{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(horizontalPodAutoscaler.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(horizontalPodAutoscaler).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":144,"to":158}} {"id":100026397,"name":"Delete","signature":"func (c *horizontalPodAutoscalers) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// Delete takes name of the horizontalPodAutoscaler and deletes it. Returns an error if one occurs.\nfunc (c *horizontalPodAutoscalers) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":160,"to":169}} {"id":100026398,"name":"DeleteCollection","signature":"func (c *horizontalPodAutoscalers) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *horizontalPodAutoscalers) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":171,"to":185}} {"id":100026399,"name":"Patch","signature":"func (c *horizontalPodAutoscalers) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v2beta2.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// Patch applies the patch and returns the patched horizontalPodAutoscaler.\nfunc (c *horizontalPodAutoscalers) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v2beta2.HorizontalPodAutoscaler, err error) {\n\tresult = \u0026v2beta2.HorizontalPodAutoscaler{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":187,"to":200}} {"id":100026400,"name":"Apply","signature":"func (c *horizontalPodAutoscalers) Apply(ctx context.Context, horizontalPodAutoscaler *autoscalingv2beta2.HorizontalPodAutoscalerApplyConfiguration, opts v1.ApplyOptions) (result *v2beta2.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied horizontalPodAutoscaler.\nfunc (c *horizontalPodAutoscalers) Apply(ctx context.Context, horizontalPodAutoscaler *autoscalingv2beta2.HorizontalPodAutoscalerApplyConfiguration, opts v1.ApplyOptions) (result *v2beta2.HorizontalPodAutoscaler, err error) {\n\tif horizontalPodAutoscaler == nil {\n\t\treturn nil, fmt.Errorf(\"horizontalPodAutoscaler provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(horizontalPodAutoscaler)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := horizontalPodAutoscaler.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"horizontalPodAutoscaler.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v2beta2.HorizontalPodAutoscaler{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":202,"to":226}} {"id":100026401,"name":"ApplyStatus","signature":"func (c *horizontalPodAutoscalers) ApplyStatus(ctx context.Context, horizontalPodAutoscaler *autoscalingv2beta2.HorizontalPodAutoscalerApplyConfiguration, opts v1.ApplyOptions) (result *v2beta2.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *horizontalPodAutoscalers) ApplyStatus(ctx context.Context, horizontalPodAutoscaler *autoscalingv2beta2.HorizontalPodAutoscalerApplyConfiguration, opts v1.ApplyOptions) (result *v2beta2.HorizontalPodAutoscaler, err error) {\n\tif horizontalPodAutoscaler == nil {\n\t\treturn nil, fmt.Errorf(\"horizontalPodAutoscaler provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(horizontalPodAutoscaler)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := horizontalPodAutoscaler.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"horizontalPodAutoscaler.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v2beta2.HorizontalPodAutoscaler{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"horizontalpodautoscalers\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":228,"to":256}} {"id":100026402,"name":"CronJobs","signature":"func (c *BatchV1Client) CronJobs(namespace string) CronJobInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/batch_client.go","code":"func (c *BatchV1Client) CronJobs(namespace string) CronJobInterface {\n\treturn newCronJobs(c, namespace)\n}","line":{"from":40,"to":42}} {"id":100026403,"name":"Jobs","signature":"func (c *BatchV1Client) Jobs(namespace string) JobInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/batch_client.go","code":"func (c *BatchV1Client) Jobs(namespace string) JobInterface {\n\treturn newJobs(c, namespace)\n}","line":{"from":44,"to":46}} {"id":100026404,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*BatchV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/batch_client.go","code":"// NewForConfig creates a new BatchV1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*BatchV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":48,"to":61}} {"id":100026405,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*BatchV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/batch_client.go","code":"// NewForConfigAndClient creates a new BatchV1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*BatchV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026BatchV1Client{client}, nil\n}","line":{"from":63,"to":75}} {"id":100026406,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *BatchV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/batch_client.go","code":"// NewForConfigOrDie creates a new BatchV1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *BatchV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":77,"to":85}} {"id":100026407,"name":"New","signature":"func New(c rest.Interface) *BatchV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/batch_client.go","code":"// New creates a new BatchV1Client for the given RESTClient.\nfunc New(c rest.Interface) *BatchV1Client {\n\treturn \u0026BatchV1Client{c}\n}","line":{"from":87,"to":90}} {"id":100026408,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/batch_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":92,"to":103}} {"id":100026409,"name":"RESTClient","signature":"func (c *BatchV1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/batch_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *BatchV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":105,"to":112}} {"id":100026410,"name":"newCronJobs","signature":"func newCronJobs(c *BatchV1Client, namespace string) *cronJobs","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/cronjob.go","code":"// newCronJobs returns a CronJobs\nfunc newCronJobs(c *BatchV1Client, namespace string) *cronJobs {\n\treturn \u0026cronJobs{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":64,"to":70}} {"id":100026411,"name":"Get","signature":"func (c *cronJobs) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.CronJob, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/cronjob.go","code":"// Get takes name of the cronJob, and returns the corresponding cronJob object, and an error if there is any.\nfunc (c *cronJobs) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.CronJob, err error) {\n\tresult = \u0026v1.CronJob{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"cronjobs\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":72,"to":83}} {"id":100026412,"name":"List","signature":"func (c *cronJobs) List(ctx context.Context, opts metav1.ListOptions) (result *v1.CronJobList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/cronjob.go","code":"// List takes label and field selectors, and returns the list of CronJobs that match those selectors.\nfunc (c *cronJobs) List(ctx context.Context, opts metav1.ListOptions) (result *v1.CronJobList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.CronJobList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"cronjobs\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":85,"to":100}} {"id":100026413,"name":"Watch","signature":"func (c *cronJobs) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/cronjob.go","code":"// Watch returns a watch.Interface that watches the requested cronJobs.\nfunc (c *cronJobs) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"cronjobs\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":102,"to":115}} {"id":100026414,"name":"Create","signature":"func (c *cronJobs) Create(ctx context.Context, cronJob *v1.CronJob, opts metav1.CreateOptions) (result *v1.CronJob, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/cronjob.go","code":"// Create takes the representation of a cronJob and creates it. Returns the server's representation of the cronJob, and an error, if there is any.\nfunc (c *cronJobs) Create(ctx context.Context, cronJob *v1.CronJob, opts metav1.CreateOptions) (result *v1.CronJob, err error) {\n\tresult = \u0026v1.CronJob{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"cronjobs\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(cronJob).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":117,"to":128}} {"id":100026415,"name":"Update","signature":"func (c *cronJobs) Update(ctx context.Context, cronJob *v1.CronJob, opts metav1.UpdateOptions) (result *v1.CronJob, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/cronjob.go","code":"// Update takes the representation of a cronJob and updates it. Returns the server's representation of the cronJob, and an error, if there is any.\nfunc (c *cronJobs) Update(ctx context.Context, cronJob *v1.CronJob, opts metav1.UpdateOptions) (result *v1.CronJob, err error) {\n\tresult = \u0026v1.CronJob{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"cronjobs\").\n\t\tName(cronJob.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(cronJob).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":130,"to":142}} {"id":100026416,"name":"UpdateStatus","signature":"func (c *cronJobs) UpdateStatus(ctx context.Context, cronJob *v1.CronJob, opts metav1.UpdateOptions) (result *v1.CronJob, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/cronjob.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *cronJobs) UpdateStatus(ctx context.Context, cronJob *v1.CronJob, opts metav1.UpdateOptions) (result *v1.CronJob, err error) {\n\tresult = \u0026v1.CronJob{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"cronjobs\").\n\t\tName(cronJob.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(cronJob).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":144,"to":158}} {"id":100026417,"name":"Delete","signature":"func (c *cronJobs) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/cronjob.go","code":"// Delete takes name of the cronJob and deletes it. Returns an error if one occurs.\nfunc (c *cronJobs) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"cronjobs\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":160,"to":169}} {"id":100026418,"name":"DeleteCollection","signature":"func (c *cronJobs) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/cronjob.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *cronJobs) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"cronjobs\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":171,"to":185}} {"id":100026419,"name":"Patch","signature":"func (c *cronJobs) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.CronJob, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/cronjob.go","code":"// Patch applies the patch and returns the patched cronJob.\nfunc (c *cronJobs) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.CronJob, err error) {\n\tresult = \u0026v1.CronJob{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"cronjobs\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":187,"to":200}} {"id":100026420,"name":"Apply","signature":"func (c *cronJobs) Apply(ctx context.Context, cronJob *batchv1.CronJobApplyConfiguration, opts metav1.ApplyOptions) (result *v1.CronJob, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/cronjob.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied cronJob.\nfunc (c *cronJobs) Apply(ctx context.Context, cronJob *batchv1.CronJobApplyConfiguration, opts metav1.ApplyOptions) (result *v1.CronJob, err error) {\n\tif cronJob == nil {\n\t\treturn nil, fmt.Errorf(\"cronJob provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(cronJob)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := cronJob.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"cronJob.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.CronJob{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"cronjobs\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":202,"to":226}} {"id":100026421,"name":"ApplyStatus","signature":"func (c *cronJobs) ApplyStatus(ctx context.Context, cronJob *batchv1.CronJobApplyConfiguration, opts metav1.ApplyOptions) (result *v1.CronJob, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/cronjob.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *cronJobs) ApplyStatus(ctx context.Context, cronJob *batchv1.CronJobApplyConfiguration, opts metav1.ApplyOptions) (result *v1.CronJob, err error) {\n\tif cronJob == nil {\n\t\treturn nil, fmt.Errorf(\"cronJob provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(cronJob)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := cronJob.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"cronJob.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1.CronJob{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"cronjobs\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":228,"to":256}} {"id":100026422,"name":"newJobs","signature":"func newJobs(c *BatchV1Client, namespace string) *jobs","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/job.go","code":"// newJobs returns a Jobs\nfunc newJobs(c *BatchV1Client, namespace string) *jobs {\n\treturn \u0026jobs{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":64,"to":70}} {"id":100026423,"name":"Get","signature":"func (c *jobs) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Job, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/job.go","code":"// Get takes name of the job, and returns the corresponding job object, and an error if there is any.\nfunc (c *jobs) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Job, err error) {\n\tresult = \u0026v1.Job{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"jobs\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":72,"to":83}} {"id":100026424,"name":"List","signature":"func (c *jobs) List(ctx context.Context, opts metav1.ListOptions) (result *v1.JobList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/job.go","code":"// List takes label and field selectors, and returns the list of Jobs that match those selectors.\nfunc (c *jobs) List(ctx context.Context, opts metav1.ListOptions) (result *v1.JobList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.JobList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"jobs\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":85,"to":100}} {"id":100026425,"name":"Watch","signature":"func (c *jobs) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/job.go","code":"// Watch returns a watch.Interface that watches the requested jobs.\nfunc (c *jobs) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"jobs\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":102,"to":115}} {"id":100026426,"name":"Create","signature":"func (c *jobs) Create(ctx context.Context, job *v1.Job, opts metav1.CreateOptions) (result *v1.Job, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/job.go","code":"// Create takes the representation of a job and creates it. Returns the server's representation of the job, and an error, if there is any.\nfunc (c *jobs) Create(ctx context.Context, job *v1.Job, opts metav1.CreateOptions) (result *v1.Job, err error) {\n\tresult = \u0026v1.Job{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"jobs\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(job).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":117,"to":128}} {"id":100026427,"name":"Update","signature":"func (c *jobs) Update(ctx context.Context, job *v1.Job, opts metav1.UpdateOptions) (result *v1.Job, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/job.go","code":"// Update takes the representation of a job and updates it. Returns the server's representation of the job, and an error, if there is any.\nfunc (c *jobs) Update(ctx context.Context, job *v1.Job, opts metav1.UpdateOptions) (result *v1.Job, err error) {\n\tresult = \u0026v1.Job{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"jobs\").\n\t\tName(job.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(job).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":130,"to":142}} {"id":100026428,"name":"UpdateStatus","signature":"func (c *jobs) UpdateStatus(ctx context.Context, job *v1.Job, opts metav1.UpdateOptions) (result *v1.Job, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/job.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *jobs) UpdateStatus(ctx context.Context, job *v1.Job, opts metav1.UpdateOptions) (result *v1.Job, err error) {\n\tresult = \u0026v1.Job{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"jobs\").\n\t\tName(job.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(job).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":144,"to":158}} {"id":100026429,"name":"Delete","signature":"func (c *jobs) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/job.go","code":"// Delete takes name of the job and deletes it. Returns an error if one occurs.\nfunc (c *jobs) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"jobs\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":160,"to":169}} {"id":100026430,"name":"DeleteCollection","signature":"func (c *jobs) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/job.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *jobs) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"jobs\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":171,"to":185}} {"id":100026431,"name":"Patch","signature":"func (c *jobs) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Job, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/job.go","code":"// Patch applies the patch and returns the patched job.\nfunc (c *jobs) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Job, err error) {\n\tresult = \u0026v1.Job{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"jobs\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":187,"to":200}} {"id":100026432,"name":"Apply","signature":"func (c *jobs) Apply(ctx context.Context, job *batchv1.JobApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Job, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/job.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied job.\nfunc (c *jobs) Apply(ctx context.Context, job *batchv1.JobApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Job, err error) {\n\tif job == nil {\n\t\treturn nil, fmt.Errorf(\"job provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(job)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := job.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"job.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.Job{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"jobs\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":202,"to":226}} {"id":100026433,"name":"ApplyStatus","signature":"func (c *jobs) ApplyStatus(ctx context.Context, job *batchv1.JobApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Job, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1/job.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *jobs) ApplyStatus(ctx context.Context, job *batchv1.JobApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Job, err error) {\n\tif job == nil {\n\t\treturn nil, fmt.Errorf(\"job provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(job)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := job.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"job.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1.Job{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"jobs\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":228,"to":256}} {"id":100026434,"name":"CronJobs","signature":"func (c *BatchV1beta1Client) CronJobs(namespace string) CronJobInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1beta1/batch_client.go","code":"func (c *BatchV1beta1Client) CronJobs(namespace string) CronJobInterface {\n\treturn newCronJobs(c, namespace)\n}","line":{"from":39,"to":41}} {"id":100026435,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*BatchV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1beta1/batch_client.go","code":"// NewForConfig creates a new BatchV1beta1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*BatchV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":43,"to":56}} {"id":100026436,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*BatchV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1beta1/batch_client.go","code":"// NewForConfigAndClient creates a new BatchV1beta1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*BatchV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026BatchV1beta1Client{client}, nil\n}","line":{"from":58,"to":70}} {"id":100026437,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *BatchV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1beta1/batch_client.go","code":"// NewForConfigOrDie creates a new BatchV1beta1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *BatchV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":72,"to":80}} {"id":100026438,"name":"New","signature":"func New(c rest.Interface) *BatchV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1beta1/batch_client.go","code":"// New creates a new BatchV1beta1Client for the given RESTClient.\nfunc New(c rest.Interface) *BatchV1beta1Client {\n\treturn \u0026BatchV1beta1Client{c}\n}","line":{"from":82,"to":85}} {"id":100026439,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1beta1/batch_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":87,"to":98}} {"id":100026440,"name":"RESTClient","signature":"func (c *BatchV1beta1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1beta1/batch_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *BatchV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":100,"to":107}} {"id":100026441,"name":"newCronJobs","signature":"func newCronJobs(c *BatchV1beta1Client, namespace string) *cronJobs","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1beta1/cronjob.go","code":"// newCronJobs returns a CronJobs\nfunc newCronJobs(c *BatchV1beta1Client, namespace string) *cronJobs {\n\treturn \u0026cronJobs{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":64,"to":70}} {"id":100026442,"name":"Get","signature":"func (c *cronJobs) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.CronJob, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1beta1/cronjob.go","code":"// Get takes name of the cronJob, and returns the corresponding cronJob object, and an error if there is any.\nfunc (c *cronJobs) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.CronJob, err error) {\n\tresult = \u0026v1beta1.CronJob{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"cronjobs\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":72,"to":83}} {"id":100026443,"name":"List","signature":"func (c *cronJobs) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.CronJobList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1beta1/cronjob.go","code":"// List takes label and field selectors, and returns the list of CronJobs that match those selectors.\nfunc (c *cronJobs) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.CronJobList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.CronJobList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"cronjobs\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":85,"to":100}} {"id":100026444,"name":"Watch","signature":"func (c *cronJobs) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1beta1/cronjob.go","code":"// Watch returns a watch.Interface that watches the requested cronJobs.\nfunc (c *cronJobs) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"cronjobs\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":102,"to":115}} {"id":100026445,"name":"Create","signature":"func (c *cronJobs) Create(ctx context.Context, cronJob *v1beta1.CronJob, opts v1.CreateOptions) (result *v1beta1.CronJob, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1beta1/cronjob.go","code":"// Create takes the representation of a cronJob and creates it. Returns the server's representation of the cronJob, and an error, if there is any.\nfunc (c *cronJobs) Create(ctx context.Context, cronJob *v1beta1.CronJob, opts v1.CreateOptions) (result *v1beta1.CronJob, err error) {\n\tresult = \u0026v1beta1.CronJob{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"cronjobs\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(cronJob).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":117,"to":128}} {"id":100026446,"name":"Update","signature":"func (c *cronJobs) Update(ctx context.Context, cronJob *v1beta1.CronJob, opts v1.UpdateOptions) (result *v1beta1.CronJob, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1beta1/cronjob.go","code":"// Update takes the representation of a cronJob and updates it. Returns the server's representation of the cronJob, and an error, if there is any.\nfunc (c *cronJobs) Update(ctx context.Context, cronJob *v1beta1.CronJob, opts v1.UpdateOptions) (result *v1beta1.CronJob, err error) {\n\tresult = \u0026v1beta1.CronJob{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"cronjobs\").\n\t\tName(cronJob.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(cronJob).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":130,"to":142}} {"id":100026447,"name":"UpdateStatus","signature":"func (c *cronJobs) UpdateStatus(ctx context.Context, cronJob *v1beta1.CronJob, opts v1.UpdateOptions) (result *v1beta1.CronJob, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1beta1/cronjob.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *cronJobs) UpdateStatus(ctx context.Context, cronJob *v1beta1.CronJob, opts v1.UpdateOptions) (result *v1beta1.CronJob, err error) {\n\tresult = \u0026v1beta1.CronJob{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"cronjobs\").\n\t\tName(cronJob.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(cronJob).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":144,"to":158}} {"id":100026448,"name":"Delete","signature":"func (c *cronJobs) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1beta1/cronjob.go","code":"// Delete takes name of the cronJob and deletes it. Returns an error if one occurs.\nfunc (c *cronJobs) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"cronjobs\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":160,"to":169}} {"id":100026449,"name":"DeleteCollection","signature":"func (c *cronJobs) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1beta1/cronjob.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *cronJobs) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"cronjobs\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":171,"to":185}} {"id":100026450,"name":"Patch","signature":"func (c *cronJobs) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.CronJob, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1beta1/cronjob.go","code":"// Patch applies the patch and returns the patched cronJob.\nfunc (c *cronJobs) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.CronJob, err error) {\n\tresult = \u0026v1beta1.CronJob{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"cronjobs\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":187,"to":200}} {"id":100026451,"name":"Apply","signature":"func (c *cronJobs) Apply(ctx context.Context, cronJob *batchv1beta1.CronJobApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.CronJob, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1beta1/cronjob.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied cronJob.\nfunc (c *cronJobs) Apply(ctx context.Context, cronJob *batchv1beta1.CronJobApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.CronJob, err error) {\n\tif cronJob == nil {\n\t\treturn nil, fmt.Errorf(\"cronJob provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(cronJob)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := cronJob.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"cronJob.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.CronJob{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"cronjobs\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":202,"to":226}} {"id":100026452,"name":"ApplyStatus","signature":"func (c *cronJobs) ApplyStatus(ctx context.Context, cronJob *batchv1beta1.CronJobApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.CronJob, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/batch/v1beta1/cronjob.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *cronJobs) ApplyStatus(ctx context.Context, cronJob *batchv1beta1.CronJobApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.CronJob, err error) {\n\tif cronJob == nil {\n\t\treturn nil, fmt.Errorf(\"cronJob provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(cronJob)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := cronJob.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"cronJob.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1beta1.CronJob{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"cronjobs\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":228,"to":256}} {"id":100026453,"name":"CertificateSigningRequests","signature":"func (c *CertificatesV1Client) CertificateSigningRequests() CertificateSigningRequestInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1/certificates_client.go","code":"func (c *CertificatesV1Client) CertificateSigningRequests() CertificateSigningRequestInterface {\n\treturn newCertificateSigningRequests(c)\n}","line":{"from":39,"to":41}} {"id":100026454,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*CertificatesV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1/certificates_client.go","code":"// NewForConfig creates a new CertificatesV1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*CertificatesV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":43,"to":56}} {"id":100026455,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*CertificatesV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1/certificates_client.go","code":"// NewForConfigAndClient creates a new CertificatesV1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*CertificatesV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026CertificatesV1Client{client}, nil\n}","line":{"from":58,"to":70}} {"id":100026456,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *CertificatesV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1/certificates_client.go","code":"// NewForConfigOrDie creates a new CertificatesV1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *CertificatesV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":72,"to":80}} {"id":100026457,"name":"New","signature":"func New(c rest.Interface) *CertificatesV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1/certificates_client.go","code":"// New creates a new CertificatesV1Client for the given RESTClient.\nfunc New(c rest.Interface) *CertificatesV1Client {\n\treturn \u0026CertificatesV1Client{c}\n}","line":{"from":82,"to":85}} {"id":100026458,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1/certificates_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":87,"to":98}} {"id":100026459,"name":"RESTClient","signature":"func (c *CertificatesV1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1/certificates_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *CertificatesV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":100,"to":107}} {"id":100026460,"name":"newCertificateSigningRequests","signature":"func newCertificateSigningRequests(c *CertificatesV1Client) *certificateSigningRequests","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1/certificatesigningrequest.go","code":"// newCertificateSigningRequests returns a CertificateSigningRequests\nfunc newCertificateSigningRequests(c *CertificatesV1Client) *certificateSigningRequests {\n\treturn \u0026certificateSigningRequests{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":65,"to":70}} {"id":100026461,"name":"Get","signature":"func (c *certificateSigningRequests) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.CertificateSigningRequest, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1/certificatesigningrequest.go","code":"// Get takes name of the certificateSigningRequest, and returns the corresponding certificateSigningRequest object, and an error if there is any.\nfunc (c *certificateSigningRequests) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.CertificateSigningRequest, err error) {\n\tresult = \u0026v1.CertificateSigningRequest{}\n\terr = c.client.Get().\n\t\tResource(\"certificatesigningrequests\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":72,"to":82}} {"id":100026462,"name":"List","signature":"func (c *certificateSigningRequests) List(ctx context.Context, opts metav1.ListOptions) (result *v1.CertificateSigningRequestList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1/certificatesigningrequest.go","code":"// List takes label and field selectors, and returns the list of CertificateSigningRequests that match those selectors.\nfunc (c *certificateSigningRequests) List(ctx context.Context, opts metav1.ListOptions) (result *v1.CertificateSigningRequestList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.CertificateSigningRequestList{}\n\terr = c.client.Get().\n\t\tResource(\"certificatesigningrequests\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":84,"to":98}} {"id":100026463,"name":"Watch","signature":"func (c *certificateSigningRequests) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1/certificatesigningrequest.go","code":"// Watch returns a watch.Interface that watches the requested certificateSigningRequests.\nfunc (c *certificateSigningRequests) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"certificatesigningrequests\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":100,"to":112}} {"id":100026464,"name":"Create","signature":"func (c *certificateSigningRequests) Create(ctx context.Context, certificateSigningRequest *v1.CertificateSigningRequest, opts metav1.CreateOptions) (result *v1.CertificateSigningRequest, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1/certificatesigningrequest.go","code":"// Create takes the representation of a certificateSigningRequest and creates it. Returns the server's representation of the certificateSigningRequest, and an error, if there is any.\nfunc (c *certificateSigningRequests) Create(ctx context.Context, certificateSigningRequest *v1.CertificateSigningRequest, opts metav1.CreateOptions) (result *v1.CertificateSigningRequest, err error) {\n\tresult = \u0026v1.CertificateSigningRequest{}\n\terr = c.client.Post().\n\t\tResource(\"certificatesigningrequests\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(certificateSigningRequest).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":114,"to":124}} {"id":100026465,"name":"Update","signature":"func (c *certificateSigningRequests) Update(ctx context.Context, certificateSigningRequest *v1.CertificateSigningRequest, opts metav1.UpdateOptions) (result *v1.CertificateSigningRequest, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1/certificatesigningrequest.go","code":"// Update takes the representation of a certificateSigningRequest and updates it. Returns the server's representation of the certificateSigningRequest, and an error, if there is any.\nfunc (c *certificateSigningRequests) Update(ctx context.Context, certificateSigningRequest *v1.CertificateSigningRequest, opts metav1.UpdateOptions) (result *v1.CertificateSigningRequest, err error) {\n\tresult = \u0026v1.CertificateSigningRequest{}\n\terr = c.client.Put().\n\t\tResource(\"certificatesigningrequests\").\n\t\tName(certificateSigningRequest.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(certificateSigningRequest).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":126,"to":137}} {"id":100026466,"name":"UpdateStatus","signature":"func (c *certificateSigningRequests) UpdateStatus(ctx context.Context, certificateSigningRequest *v1.CertificateSigningRequest, opts metav1.UpdateOptions) (result *v1.CertificateSigningRequest, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1/certificatesigningrequest.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *certificateSigningRequests) UpdateStatus(ctx context.Context, certificateSigningRequest *v1.CertificateSigningRequest, opts metav1.UpdateOptions) (result *v1.CertificateSigningRequest, err error) {\n\tresult = \u0026v1.CertificateSigningRequest{}\n\terr = c.client.Put().\n\t\tResource(\"certificatesigningrequests\").\n\t\tName(certificateSigningRequest.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(certificateSigningRequest).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":139,"to":152}} {"id":100026467,"name":"Delete","signature":"func (c *certificateSigningRequests) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1/certificatesigningrequest.go","code":"// Delete takes name of the certificateSigningRequest and deletes it. Returns an error if one occurs.\nfunc (c *certificateSigningRequests) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"certificatesigningrequests\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":154,"to":162}} {"id":100026468,"name":"DeleteCollection","signature":"func (c *certificateSigningRequests) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1/certificatesigningrequest.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *certificateSigningRequests) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"certificatesigningrequests\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":164,"to":177}} {"id":100026469,"name":"Patch","signature":"func (c *certificateSigningRequests) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.CertificateSigningRequest, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1/certificatesigningrequest.go","code":"// Patch applies the patch and returns the patched certificateSigningRequest.\nfunc (c *certificateSigningRequests) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.CertificateSigningRequest, err error) {\n\tresult = \u0026v1.CertificateSigningRequest{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"certificatesigningrequests\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":179,"to":191}} {"id":100026470,"name":"Apply","signature":"func (c *certificateSigningRequests) Apply(ctx context.Context, certificateSigningRequest *certificatesv1.CertificateSigningRequestApplyConfiguration, opts metav1.ApplyOptions) (result *v1.CertificateSigningRequest, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1/certificatesigningrequest.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied certificateSigningRequest.\nfunc (c *certificateSigningRequests) Apply(ctx context.Context, certificateSigningRequest *certificatesv1.CertificateSigningRequestApplyConfiguration, opts metav1.ApplyOptions) (result *v1.CertificateSigningRequest, err error) {\n\tif certificateSigningRequest == nil {\n\t\treturn nil, fmt.Errorf(\"certificateSigningRequest provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(certificateSigningRequest)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := certificateSigningRequest.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"certificateSigningRequest.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.CertificateSigningRequest{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"certificatesigningrequests\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":193,"to":216}} {"id":100026471,"name":"ApplyStatus","signature":"func (c *certificateSigningRequests) ApplyStatus(ctx context.Context, certificateSigningRequest *certificatesv1.CertificateSigningRequestApplyConfiguration, opts metav1.ApplyOptions) (result *v1.CertificateSigningRequest, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1/certificatesigningrequest.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *certificateSigningRequests) ApplyStatus(ctx context.Context, certificateSigningRequest *certificatesv1.CertificateSigningRequestApplyConfiguration, opts metav1.ApplyOptions) (result *v1.CertificateSigningRequest, err error) {\n\tif certificateSigningRequest == nil {\n\t\treturn nil, fmt.Errorf(\"certificateSigningRequest provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(certificateSigningRequest)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := certificateSigningRequest.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"certificateSigningRequest.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1.CertificateSigningRequest{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"certificatesigningrequests\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":218,"to":245}} {"id":100026472,"name":"UpdateApproval","signature":"func (c *certificateSigningRequests) UpdateApproval(ctx context.Context, certificateSigningRequestName string, certificateSigningRequest *v1.CertificateSigningRequest, opts metav1.UpdateOptions) (result *v1.CertificateSigningRequest, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1/certificatesigningrequest.go","code":"// UpdateApproval takes the top resource name and the representation of a certificateSigningRequest and updates it. Returns the server's representation of the certificateSigningRequest, and an error, if there is any.\nfunc (c *certificateSigningRequests) UpdateApproval(ctx context.Context, certificateSigningRequestName string, certificateSigningRequest *v1.CertificateSigningRequest, opts metav1.UpdateOptions) (result *v1.CertificateSigningRequest, err error) {\n\tresult = \u0026v1.CertificateSigningRequest{}\n\terr = c.client.Put().\n\t\tResource(\"certificatesigningrequests\").\n\t\tName(certificateSigningRequestName).\n\t\tSubResource(\"approval\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(certificateSigningRequest).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":247,"to":259}} {"id":100026473,"name":"ClusterTrustBundles","signature":"func (c *CertificatesV1alpha1Client) ClusterTrustBundles() ClusterTrustBundleInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1alpha1/certificates_client.go","code":"func (c *CertificatesV1alpha1Client) ClusterTrustBundles() ClusterTrustBundleInterface {\n\treturn newClusterTrustBundles(c)\n}","line":{"from":39,"to":41}} {"id":100026474,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*CertificatesV1alpha1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1alpha1/certificates_client.go","code":"// NewForConfig creates a new CertificatesV1alpha1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*CertificatesV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":43,"to":56}} {"id":100026475,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*CertificatesV1alpha1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1alpha1/certificates_client.go","code":"// NewForConfigAndClient creates a new CertificatesV1alpha1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*CertificatesV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026CertificatesV1alpha1Client{client}, nil\n}","line":{"from":58,"to":70}} {"id":100026476,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *CertificatesV1alpha1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1alpha1/certificates_client.go","code":"// NewForConfigOrDie creates a new CertificatesV1alpha1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *CertificatesV1alpha1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":72,"to":80}} {"id":100026477,"name":"New","signature":"func New(c rest.Interface) *CertificatesV1alpha1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1alpha1/certificates_client.go","code":"// New creates a new CertificatesV1alpha1Client for the given RESTClient.\nfunc New(c rest.Interface) *CertificatesV1alpha1Client {\n\treturn \u0026CertificatesV1alpha1Client{c}\n}","line":{"from":82,"to":85}} {"id":100026478,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1alpha1/certificates_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1alpha1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":87,"to":98}} {"id":100026479,"name":"RESTClient","signature":"func (c *CertificatesV1alpha1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1alpha1/certificates_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *CertificatesV1alpha1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":100,"to":107}} {"id":100026480,"name":"newClusterTrustBundles","signature":"func newClusterTrustBundles(c *CertificatesV1alpha1Client) *clusterTrustBundles","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1alpha1/clustertrustbundle.go","code":"// newClusterTrustBundles returns a ClusterTrustBundles\nfunc newClusterTrustBundles(c *CertificatesV1alpha1Client) *clusterTrustBundles {\n\treturn \u0026clusterTrustBundles{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100026481,"name":"Get","signature":"func (c *clusterTrustBundles) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.ClusterTrustBundle, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1alpha1/clustertrustbundle.go","code":"// Get takes name of the clusterTrustBundle, and returns the corresponding clusterTrustBundle object, and an error if there is any.\nfunc (c *clusterTrustBundles) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.ClusterTrustBundle, err error) {\n\tresult = \u0026v1alpha1.ClusterTrustBundle{}\n\terr = c.client.Get().\n\t\tResource(\"clustertrustbundles\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100026482,"name":"List","signature":"func (c *clusterTrustBundles) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.ClusterTrustBundleList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1alpha1/clustertrustbundle.go","code":"// List takes label and field selectors, and returns the list of ClusterTrustBundles that match those selectors.\nfunc (c *clusterTrustBundles) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.ClusterTrustBundleList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1alpha1.ClusterTrustBundleList{}\n\terr = c.client.Get().\n\t\tResource(\"clustertrustbundles\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100026483,"name":"Watch","signature":"func (c *clusterTrustBundles) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1alpha1/clustertrustbundle.go","code":"// Watch returns a watch.Interface that watches the requested clusterTrustBundles.\nfunc (c *clusterTrustBundles) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"clustertrustbundles\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100026484,"name":"Create","signature":"func (c *clusterTrustBundles) Create(ctx context.Context, clusterTrustBundle *v1alpha1.ClusterTrustBundle, opts v1.CreateOptions) (result *v1alpha1.ClusterTrustBundle, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1alpha1/clustertrustbundle.go","code":"// Create takes the representation of a clusterTrustBundle and creates it. Returns the server's representation of the clusterTrustBundle, and an error, if there is any.\nfunc (c *clusterTrustBundles) Create(ctx context.Context, clusterTrustBundle *v1alpha1.ClusterTrustBundle, opts v1.CreateOptions) (result *v1alpha1.ClusterTrustBundle, err error) {\n\tresult = \u0026v1alpha1.ClusterTrustBundle{}\n\terr = c.client.Post().\n\t\tResource(\"clustertrustbundles\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(clusterTrustBundle).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100026485,"name":"Update","signature":"func (c *clusterTrustBundles) Update(ctx context.Context, clusterTrustBundle *v1alpha1.ClusterTrustBundle, opts v1.UpdateOptions) (result *v1alpha1.ClusterTrustBundle, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1alpha1/clustertrustbundle.go","code":"// Update takes the representation of a clusterTrustBundle and updates it. Returns the server's representation of the clusterTrustBundle, and an error, if there is any.\nfunc (c *clusterTrustBundles) Update(ctx context.Context, clusterTrustBundle *v1alpha1.ClusterTrustBundle, opts v1.UpdateOptions) (result *v1alpha1.ClusterTrustBundle, err error) {\n\tresult = \u0026v1alpha1.ClusterTrustBundle{}\n\terr = c.client.Put().\n\t\tResource(\"clustertrustbundles\").\n\t\tName(clusterTrustBundle.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(clusterTrustBundle).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100026486,"name":"Delete","signature":"func (c *clusterTrustBundles) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1alpha1/clustertrustbundle.go","code":"// Delete takes name of the clusterTrustBundle and deletes it. Returns an error if one occurs.\nfunc (c *clusterTrustBundles) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"clustertrustbundles\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100026487,"name":"DeleteCollection","signature":"func (c *clusterTrustBundles) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1alpha1/clustertrustbundle.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *clusterTrustBundles) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"clustertrustbundles\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100026488,"name":"Patch","signature":"func (c *clusterTrustBundles) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.ClusterTrustBundle, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1alpha1/clustertrustbundle.go","code":"// Patch applies the patch and returns the patched clusterTrustBundle.\nfunc (c *clusterTrustBundles) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.ClusterTrustBundle, err error) {\n\tresult = \u0026v1alpha1.ClusterTrustBundle{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"clustertrustbundles\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100026489,"name":"Apply","signature":"func (c *clusterTrustBundles) Apply(ctx context.Context, clusterTrustBundle *certificatesv1alpha1.ClusterTrustBundleApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.ClusterTrustBundle, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1alpha1/clustertrustbundle.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied clusterTrustBundle.\nfunc (c *clusterTrustBundles) Apply(ctx context.Context, clusterTrustBundle *certificatesv1alpha1.ClusterTrustBundleApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.ClusterTrustBundle, err error) {\n\tif clusterTrustBundle == nil {\n\t\treturn nil, fmt.Errorf(\"clusterTrustBundle provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(clusterTrustBundle)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := clusterTrustBundle.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"clusterTrustBundle.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1alpha1.ClusterTrustBundle{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"clustertrustbundles\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100026490,"name":"CertificateSigningRequests","signature":"func (c *CertificatesV1beta1Client) CertificateSigningRequests() CertificateSigningRequestInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1beta1/certificates_client.go","code":"func (c *CertificatesV1beta1Client) CertificateSigningRequests() CertificateSigningRequestInterface {\n\treturn newCertificateSigningRequests(c)\n}","line":{"from":39,"to":41}} {"id":100026491,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*CertificatesV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1beta1/certificates_client.go","code":"// NewForConfig creates a new CertificatesV1beta1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*CertificatesV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":43,"to":56}} {"id":100026492,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*CertificatesV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1beta1/certificates_client.go","code":"// NewForConfigAndClient creates a new CertificatesV1beta1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*CertificatesV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026CertificatesV1beta1Client{client}, nil\n}","line":{"from":58,"to":70}} {"id":100026493,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *CertificatesV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1beta1/certificates_client.go","code":"// NewForConfigOrDie creates a new CertificatesV1beta1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *CertificatesV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":72,"to":80}} {"id":100026494,"name":"New","signature":"func New(c rest.Interface) *CertificatesV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1beta1/certificates_client.go","code":"// New creates a new CertificatesV1beta1Client for the given RESTClient.\nfunc New(c rest.Interface) *CertificatesV1beta1Client {\n\treturn \u0026CertificatesV1beta1Client{c}\n}","line":{"from":82,"to":85}} {"id":100026495,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1beta1/certificates_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":87,"to":98}} {"id":100026496,"name":"RESTClient","signature":"func (c *CertificatesV1beta1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1beta1/certificates_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *CertificatesV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":100,"to":107}} {"id":100026497,"name":"newCertificateSigningRequests","signature":"func newCertificateSigningRequests(c *CertificatesV1beta1Client) *certificateSigningRequests","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1beta1/certificatesigningrequest.go","code":"// newCertificateSigningRequests returns a CertificateSigningRequests\nfunc newCertificateSigningRequests(c *CertificatesV1beta1Client) *certificateSigningRequests {\n\treturn \u0026certificateSigningRequests{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":63,"to":68}} {"id":100026498,"name":"Get","signature":"func (c *certificateSigningRequests) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.CertificateSigningRequest, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1beta1/certificatesigningrequest.go","code":"// Get takes name of the certificateSigningRequest, and returns the corresponding certificateSigningRequest object, and an error if there is any.\nfunc (c *certificateSigningRequests) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.CertificateSigningRequest, err error) {\n\tresult = \u0026v1beta1.CertificateSigningRequest{}\n\terr = c.client.Get().\n\t\tResource(\"certificatesigningrequests\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":80}} {"id":100026499,"name":"List","signature":"func (c *certificateSigningRequests) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.CertificateSigningRequestList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1beta1/certificatesigningrequest.go","code":"// List takes label and field selectors, and returns the list of CertificateSigningRequests that match those selectors.\nfunc (c *certificateSigningRequests) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.CertificateSigningRequestList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.CertificateSigningRequestList{}\n\terr = c.client.Get().\n\t\tResource(\"certificatesigningrequests\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":82,"to":96}} {"id":100026500,"name":"Watch","signature":"func (c *certificateSigningRequests) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1beta1/certificatesigningrequest.go","code":"// Watch returns a watch.Interface that watches the requested certificateSigningRequests.\nfunc (c *certificateSigningRequests) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"certificatesigningrequests\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":98,"to":110}} {"id":100026501,"name":"Create","signature":"func (c *certificateSigningRequests) Create(ctx context.Context, certificateSigningRequest *v1beta1.CertificateSigningRequest, opts v1.CreateOptions) (result *v1beta1.CertificateSigningRequest, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1beta1/certificatesigningrequest.go","code":"// Create takes the representation of a certificateSigningRequest and creates it. Returns the server's representation of the certificateSigningRequest, and an error, if there is any.\nfunc (c *certificateSigningRequests) Create(ctx context.Context, certificateSigningRequest *v1beta1.CertificateSigningRequest, opts v1.CreateOptions) (result *v1beta1.CertificateSigningRequest, err error) {\n\tresult = \u0026v1beta1.CertificateSigningRequest{}\n\terr = c.client.Post().\n\t\tResource(\"certificatesigningrequests\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(certificateSigningRequest).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":112,"to":122}} {"id":100026502,"name":"Update","signature":"func (c *certificateSigningRequests) Update(ctx context.Context, certificateSigningRequest *v1beta1.CertificateSigningRequest, opts v1.UpdateOptions) (result *v1beta1.CertificateSigningRequest, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1beta1/certificatesigningrequest.go","code":"// Update takes the representation of a certificateSigningRequest and updates it. Returns the server's representation of the certificateSigningRequest, and an error, if there is any.\nfunc (c *certificateSigningRequests) Update(ctx context.Context, certificateSigningRequest *v1beta1.CertificateSigningRequest, opts v1.UpdateOptions) (result *v1beta1.CertificateSigningRequest, err error) {\n\tresult = \u0026v1beta1.CertificateSigningRequest{}\n\terr = c.client.Put().\n\t\tResource(\"certificatesigningrequests\").\n\t\tName(certificateSigningRequest.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(certificateSigningRequest).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":124,"to":135}} {"id":100026503,"name":"UpdateStatus","signature":"func (c *certificateSigningRequests) UpdateStatus(ctx context.Context, certificateSigningRequest *v1beta1.CertificateSigningRequest, opts v1.UpdateOptions) (result *v1beta1.CertificateSigningRequest, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1beta1/certificatesigningrequest.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *certificateSigningRequests) UpdateStatus(ctx context.Context, certificateSigningRequest *v1beta1.CertificateSigningRequest, opts v1.UpdateOptions) (result *v1beta1.CertificateSigningRequest, err error) {\n\tresult = \u0026v1beta1.CertificateSigningRequest{}\n\terr = c.client.Put().\n\t\tResource(\"certificatesigningrequests\").\n\t\tName(certificateSigningRequest.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(certificateSigningRequest).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":137,"to":150}} {"id":100026504,"name":"Delete","signature":"func (c *certificateSigningRequests) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1beta1/certificatesigningrequest.go","code":"// Delete takes name of the certificateSigningRequest and deletes it. Returns an error if one occurs.\nfunc (c *certificateSigningRequests) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"certificatesigningrequests\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":152,"to":160}} {"id":100026505,"name":"DeleteCollection","signature":"func (c *certificateSigningRequests) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1beta1/certificatesigningrequest.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *certificateSigningRequests) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"certificatesigningrequests\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":162,"to":175}} {"id":100026506,"name":"Patch","signature":"func (c *certificateSigningRequests) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.CertificateSigningRequest, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1beta1/certificatesigningrequest.go","code":"// Patch applies the patch and returns the patched certificateSigningRequest.\nfunc (c *certificateSigningRequests) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.CertificateSigningRequest, err error) {\n\tresult = \u0026v1beta1.CertificateSigningRequest{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"certificatesigningrequests\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":177,"to":189}} {"id":100026507,"name":"Apply","signature":"func (c *certificateSigningRequests) Apply(ctx context.Context, certificateSigningRequest *certificatesv1beta1.CertificateSigningRequestApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.CertificateSigningRequest, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1beta1/certificatesigningrequest.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied certificateSigningRequest.\nfunc (c *certificateSigningRequests) Apply(ctx context.Context, certificateSigningRequest *certificatesv1beta1.CertificateSigningRequestApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.CertificateSigningRequest, err error) {\n\tif certificateSigningRequest == nil {\n\t\treturn nil, fmt.Errorf(\"certificateSigningRequest provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(certificateSigningRequest)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := certificateSigningRequest.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"certificateSigningRequest.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.CertificateSigningRequest{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"certificatesigningrequests\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":191,"to":214}} {"id":100026508,"name":"ApplyStatus","signature":"func (c *certificateSigningRequests) ApplyStatus(ctx context.Context, certificateSigningRequest *certificatesv1beta1.CertificateSigningRequestApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.CertificateSigningRequest, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1beta1/certificatesigningrequest.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *certificateSigningRequests) ApplyStatus(ctx context.Context, certificateSigningRequest *certificatesv1beta1.CertificateSigningRequestApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.CertificateSigningRequest, err error) {\n\tif certificateSigningRequest == nil {\n\t\treturn nil, fmt.Errorf(\"certificateSigningRequest provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(certificateSigningRequest)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := certificateSigningRequest.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"certificateSigningRequest.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1beta1.CertificateSigningRequest{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"certificatesigningrequests\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":216,"to":243}} {"id":100026509,"name":"UpdateApproval","signature":"func (c *certificateSigningRequests) UpdateApproval(ctx context.Context, certificateSigningRequest *certificates.CertificateSigningRequest, opts metav1.UpdateOptions) (result *certificates.CertificateSigningRequest, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/certificates/v1beta1/certificatesigningrequest_expansion.go","code":"func (c *certificateSigningRequests) UpdateApproval(ctx context.Context, certificateSigningRequest *certificates.CertificateSigningRequest, opts metav1.UpdateOptions) (result *certificates.CertificateSigningRequest, err error) {\n\tresult = \u0026certificates.CertificateSigningRequest{}\n\terr = c.client.Put().\n\t\tResource(\"certificatesigningrequests\").\n\t\tName(certificateSigningRequest.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(certificateSigningRequest).\n\t\tSubResource(\"approval\").\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":31,"to":42}} {"id":100026510,"name":"Leases","signature":"func (c *CoordinationV1Client) Leases(namespace string) LeaseInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1/coordination_client.go","code":"func (c *CoordinationV1Client) Leases(namespace string) LeaseInterface {\n\treturn newLeases(c, namespace)\n}","line":{"from":39,"to":41}} {"id":100026511,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*CoordinationV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1/coordination_client.go","code":"// NewForConfig creates a new CoordinationV1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*CoordinationV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":43,"to":56}} {"id":100026512,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*CoordinationV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1/coordination_client.go","code":"// NewForConfigAndClient creates a new CoordinationV1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*CoordinationV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026CoordinationV1Client{client}, nil\n}","line":{"from":58,"to":70}} {"id":100026513,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *CoordinationV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1/coordination_client.go","code":"// NewForConfigOrDie creates a new CoordinationV1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *CoordinationV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":72,"to":80}} {"id":100026514,"name":"New","signature":"func New(c rest.Interface) *CoordinationV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1/coordination_client.go","code":"// New creates a new CoordinationV1Client for the given RESTClient.\nfunc New(c rest.Interface) *CoordinationV1Client {\n\treturn \u0026CoordinationV1Client{c}\n}","line":{"from":82,"to":85}} {"id":100026515,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1/coordination_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":87,"to":98}} {"id":100026516,"name":"RESTClient","signature":"func (c *CoordinationV1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1/coordination_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *CoordinationV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":100,"to":107}} {"id":100026517,"name":"newLeases","signature":"func newLeases(c *CoordinationV1Client, namespace string) *leases","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1/lease.go","code":"// newLeases returns a Leases\nfunc newLeases(c *CoordinationV1Client, namespace string) *leases {\n\treturn \u0026leases{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":62,"to":68}} {"id":100026518,"name":"Get","signature":"func (c *leases) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Lease, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1/lease.go","code":"// Get takes name of the lease, and returns the corresponding lease object, and an error if there is any.\nfunc (c *leases) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Lease, err error) {\n\tresult = \u0026v1.Lease{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"leases\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":81}} {"id":100026519,"name":"List","signature":"func (c *leases) List(ctx context.Context, opts metav1.ListOptions) (result *v1.LeaseList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1/lease.go","code":"// List takes label and field selectors, and returns the list of Leases that match those selectors.\nfunc (c *leases) List(ctx context.Context, opts metav1.ListOptions) (result *v1.LeaseList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.LeaseList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"leases\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":83,"to":98}} {"id":100026520,"name":"Watch","signature":"func (c *leases) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1/lease.go","code":"// Watch returns a watch.Interface that watches the requested leases.\nfunc (c *leases) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"leases\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":100,"to":113}} {"id":100026521,"name":"Create","signature":"func (c *leases) Create(ctx context.Context, lease *v1.Lease, opts metav1.CreateOptions) (result *v1.Lease, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1/lease.go","code":"// Create takes the representation of a lease and creates it. Returns the server's representation of the lease, and an error, if there is any.\nfunc (c *leases) Create(ctx context.Context, lease *v1.Lease, opts metav1.CreateOptions) (result *v1.Lease, err error) {\n\tresult = \u0026v1.Lease{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"leases\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(lease).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":115,"to":126}} {"id":100026522,"name":"Update","signature":"func (c *leases) Update(ctx context.Context, lease *v1.Lease, opts metav1.UpdateOptions) (result *v1.Lease, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1/lease.go","code":"// Update takes the representation of a lease and updates it. Returns the server's representation of the lease, and an error, if there is any.\nfunc (c *leases) Update(ctx context.Context, lease *v1.Lease, opts metav1.UpdateOptions) (result *v1.Lease, err error) {\n\tresult = \u0026v1.Lease{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"leases\").\n\t\tName(lease.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(lease).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":128,"to":140}} {"id":100026523,"name":"Delete","signature":"func (c *leases) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1/lease.go","code":"// Delete takes name of the lease and deletes it. Returns an error if one occurs.\nfunc (c *leases) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"leases\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":142,"to":151}} {"id":100026524,"name":"DeleteCollection","signature":"func (c *leases) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1/lease.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *leases) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"leases\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":153,"to":167}} {"id":100026525,"name":"Patch","signature":"func (c *leases) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Lease, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1/lease.go","code":"// Patch applies the patch and returns the patched lease.\nfunc (c *leases) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Lease, err error) {\n\tresult = \u0026v1.Lease{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"leases\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":169,"to":182}} {"id":100026526,"name":"Apply","signature":"func (c *leases) Apply(ctx context.Context, lease *coordinationv1.LeaseApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Lease, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1/lease.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied lease.\nfunc (c *leases) Apply(ctx context.Context, lease *coordinationv1.LeaseApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Lease, err error) {\n\tif lease == nil {\n\t\treturn nil, fmt.Errorf(\"lease provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(lease)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := lease.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"lease.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.Lease{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"leases\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":184,"to":208}} {"id":100026527,"name":"Leases","signature":"func (c *CoordinationV1beta1Client) Leases(namespace string) LeaseInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1beta1/coordination_client.go","code":"func (c *CoordinationV1beta1Client) Leases(namespace string) LeaseInterface {\n\treturn newLeases(c, namespace)\n}","line":{"from":39,"to":41}} {"id":100026528,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*CoordinationV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1beta1/coordination_client.go","code":"// NewForConfig creates a new CoordinationV1beta1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*CoordinationV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":43,"to":56}} {"id":100026529,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*CoordinationV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1beta1/coordination_client.go","code":"// NewForConfigAndClient creates a new CoordinationV1beta1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*CoordinationV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026CoordinationV1beta1Client{client}, nil\n}","line":{"from":58,"to":70}} {"id":100026530,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *CoordinationV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1beta1/coordination_client.go","code":"// NewForConfigOrDie creates a new CoordinationV1beta1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *CoordinationV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":72,"to":80}} {"id":100026531,"name":"New","signature":"func New(c rest.Interface) *CoordinationV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1beta1/coordination_client.go","code":"// New creates a new CoordinationV1beta1Client for the given RESTClient.\nfunc New(c rest.Interface) *CoordinationV1beta1Client {\n\treturn \u0026CoordinationV1beta1Client{c}\n}","line":{"from":82,"to":85}} {"id":100026532,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1beta1/coordination_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":87,"to":98}} {"id":100026533,"name":"RESTClient","signature":"func (c *CoordinationV1beta1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1beta1/coordination_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *CoordinationV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":100,"to":107}} {"id":100026534,"name":"newLeases","signature":"func newLeases(c *CoordinationV1beta1Client, namespace string) *leases","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1beta1/lease.go","code":"// newLeases returns a Leases\nfunc newLeases(c *CoordinationV1beta1Client, namespace string) *leases {\n\treturn \u0026leases{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":62,"to":68}} {"id":100026535,"name":"Get","signature":"func (c *leases) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.Lease, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1beta1/lease.go","code":"// Get takes name of the lease, and returns the corresponding lease object, and an error if there is any.\nfunc (c *leases) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.Lease, err error) {\n\tresult = \u0026v1beta1.Lease{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"leases\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":81}} {"id":100026536,"name":"List","signature":"func (c *leases) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.LeaseList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1beta1/lease.go","code":"// List takes label and field selectors, and returns the list of Leases that match those selectors.\nfunc (c *leases) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.LeaseList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.LeaseList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"leases\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":83,"to":98}} {"id":100026537,"name":"Watch","signature":"func (c *leases) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1beta1/lease.go","code":"// Watch returns a watch.Interface that watches the requested leases.\nfunc (c *leases) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"leases\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":100,"to":113}} {"id":100026538,"name":"Create","signature":"func (c *leases) Create(ctx context.Context, lease *v1beta1.Lease, opts v1.CreateOptions) (result *v1beta1.Lease, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1beta1/lease.go","code":"// Create takes the representation of a lease and creates it. Returns the server's representation of the lease, and an error, if there is any.\nfunc (c *leases) Create(ctx context.Context, lease *v1beta1.Lease, opts v1.CreateOptions) (result *v1beta1.Lease, err error) {\n\tresult = \u0026v1beta1.Lease{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"leases\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(lease).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":115,"to":126}} {"id":100026539,"name":"Update","signature":"func (c *leases) Update(ctx context.Context, lease *v1beta1.Lease, opts v1.UpdateOptions) (result *v1beta1.Lease, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1beta1/lease.go","code":"// Update takes the representation of a lease and updates it. Returns the server's representation of the lease, and an error, if there is any.\nfunc (c *leases) Update(ctx context.Context, lease *v1beta1.Lease, opts v1.UpdateOptions) (result *v1beta1.Lease, err error) {\n\tresult = \u0026v1beta1.Lease{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"leases\").\n\t\tName(lease.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(lease).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":128,"to":140}} {"id":100026540,"name":"Delete","signature":"func (c *leases) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1beta1/lease.go","code":"// Delete takes name of the lease and deletes it. Returns an error if one occurs.\nfunc (c *leases) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"leases\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":142,"to":151}} {"id":100026541,"name":"DeleteCollection","signature":"func (c *leases) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1beta1/lease.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *leases) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"leases\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":153,"to":167}} {"id":100026542,"name":"Patch","signature":"func (c *leases) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.Lease, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1beta1/lease.go","code":"// Patch applies the patch and returns the patched lease.\nfunc (c *leases) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.Lease, err error) {\n\tresult = \u0026v1beta1.Lease{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"leases\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":169,"to":182}} {"id":100026543,"name":"Apply","signature":"func (c *leases) Apply(ctx context.Context, lease *coordinationv1beta1.LeaseApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Lease, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/coordination/v1beta1/lease.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied lease.\nfunc (c *leases) Apply(ctx context.Context, lease *coordinationv1beta1.LeaseApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Lease, err error) {\n\tif lease == nil {\n\t\treturn nil, fmt.Errorf(\"lease provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(lease)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := lease.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"lease.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.Lease{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"leases\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":184,"to":208}} {"id":100026544,"name":"newComponentStatuses","signature":"func newComponentStatuses(c *CoreV1Client) *componentStatuses","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/componentstatus.go","code":"// newComponentStatuses returns a ComponentStatuses\nfunc newComponentStatuses(c *CoreV1Client) *componentStatuses {\n\treturn \u0026componentStatuses{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100026545,"name":"Get","signature":"func (c *componentStatuses) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ComponentStatus, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/componentstatus.go","code":"// Get takes name of the componentStatus, and returns the corresponding componentStatus object, and an error if there is any.\nfunc (c *componentStatuses) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ComponentStatus, err error) {\n\tresult = \u0026v1.ComponentStatus{}\n\terr = c.client.Get().\n\t\tResource(\"componentstatuses\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100026546,"name":"List","signature":"func (c *componentStatuses) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ComponentStatusList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/componentstatus.go","code":"// List takes label and field selectors, and returns the list of ComponentStatuses that match those selectors.\nfunc (c *componentStatuses) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ComponentStatusList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.ComponentStatusList{}\n\terr = c.client.Get().\n\t\tResource(\"componentstatuses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100026547,"name":"Watch","signature":"func (c *componentStatuses) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/componentstatus.go","code":"// Watch returns a watch.Interface that watches the requested componentStatuses.\nfunc (c *componentStatuses) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"componentstatuses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100026548,"name":"Create","signature":"func (c *componentStatuses) Create(ctx context.Context, componentStatus *v1.ComponentStatus, opts metav1.CreateOptions) (result *v1.ComponentStatus, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/componentstatus.go","code":"// Create takes the representation of a componentStatus and creates it. Returns the server's representation of the componentStatus, and an error, if there is any.\nfunc (c *componentStatuses) Create(ctx context.Context, componentStatus *v1.ComponentStatus, opts metav1.CreateOptions) (result *v1.ComponentStatus, err error) {\n\tresult = \u0026v1.ComponentStatus{}\n\terr = c.client.Post().\n\t\tResource(\"componentstatuses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(componentStatus).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100026549,"name":"Update","signature":"func (c *componentStatuses) Update(ctx context.Context, componentStatus *v1.ComponentStatus, opts metav1.UpdateOptions) (result *v1.ComponentStatus, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/componentstatus.go","code":"// Update takes the representation of a componentStatus and updates it. Returns the server's representation of the componentStatus, and an error, if there is any.\nfunc (c *componentStatuses) Update(ctx context.Context, componentStatus *v1.ComponentStatus, opts metav1.UpdateOptions) (result *v1.ComponentStatus, err error) {\n\tresult = \u0026v1.ComponentStatus{}\n\terr = c.client.Put().\n\t\tResource(\"componentstatuses\").\n\t\tName(componentStatus.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(componentStatus).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100026550,"name":"Delete","signature":"func (c *componentStatuses) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/componentstatus.go","code":"// Delete takes name of the componentStatus and deletes it. Returns an error if one occurs.\nfunc (c *componentStatuses) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"componentstatuses\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100026551,"name":"DeleteCollection","signature":"func (c *componentStatuses) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/componentstatus.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *componentStatuses) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"componentstatuses\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100026552,"name":"Patch","signature":"func (c *componentStatuses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ComponentStatus, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/componentstatus.go","code":"// Patch applies the patch and returns the patched componentStatus.\nfunc (c *componentStatuses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ComponentStatus, err error) {\n\tresult = \u0026v1.ComponentStatus{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"componentstatuses\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100026553,"name":"Apply","signature":"func (c *componentStatuses) Apply(ctx context.Context, componentStatus *corev1.ComponentStatusApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ComponentStatus, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/componentstatus.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied componentStatus.\nfunc (c *componentStatuses) Apply(ctx context.Context, componentStatus *corev1.ComponentStatusApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ComponentStatus, err error) {\n\tif componentStatus == nil {\n\t\treturn nil, fmt.Errorf(\"componentStatus provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(componentStatus)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := componentStatus.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"componentStatus.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.ComponentStatus{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"componentstatuses\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100026554,"name":"newConfigMaps","signature":"func newConfigMaps(c *CoreV1Client, namespace string) *configMaps","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/configmap.go","code":"// newConfigMaps returns a ConfigMaps\nfunc newConfigMaps(c *CoreV1Client, namespace string) *configMaps {\n\treturn \u0026configMaps{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":62,"to":68}} {"id":100026555,"name":"Get","signature":"func (c *configMaps) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ConfigMap, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/configmap.go","code":"// Get takes name of the configMap, and returns the corresponding configMap object, and an error if there is any.\nfunc (c *configMaps) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ConfigMap, err error) {\n\tresult = \u0026v1.ConfigMap{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"configmaps\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":81}} {"id":100026556,"name":"List","signature":"func (c *configMaps) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ConfigMapList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/configmap.go","code":"// List takes label and field selectors, and returns the list of ConfigMaps that match those selectors.\nfunc (c *configMaps) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ConfigMapList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.ConfigMapList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"configmaps\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":83,"to":98}} {"id":100026557,"name":"Watch","signature":"func (c *configMaps) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/configmap.go","code":"// Watch returns a watch.Interface that watches the requested configMaps.\nfunc (c *configMaps) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"configmaps\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":100,"to":113}} {"id":100026558,"name":"Create","signature":"func (c *configMaps) Create(ctx context.Context, configMap *v1.ConfigMap, opts metav1.CreateOptions) (result *v1.ConfigMap, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/configmap.go","code":"// Create takes the representation of a configMap and creates it. Returns the server's representation of the configMap, and an error, if there is any.\nfunc (c *configMaps) Create(ctx context.Context, configMap *v1.ConfigMap, opts metav1.CreateOptions) (result *v1.ConfigMap, err error) {\n\tresult = \u0026v1.ConfigMap{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"configmaps\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(configMap).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":115,"to":126}} {"id":100026559,"name":"Update","signature":"func (c *configMaps) Update(ctx context.Context, configMap *v1.ConfigMap, opts metav1.UpdateOptions) (result *v1.ConfigMap, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/configmap.go","code":"// Update takes the representation of a configMap and updates it. Returns the server's representation of the configMap, and an error, if there is any.\nfunc (c *configMaps) Update(ctx context.Context, configMap *v1.ConfigMap, opts metav1.UpdateOptions) (result *v1.ConfigMap, err error) {\n\tresult = \u0026v1.ConfigMap{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"configmaps\").\n\t\tName(configMap.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(configMap).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":128,"to":140}} {"id":100026560,"name":"Delete","signature":"func (c *configMaps) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/configmap.go","code":"// Delete takes name of the configMap and deletes it. Returns an error if one occurs.\nfunc (c *configMaps) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"configmaps\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":142,"to":151}} {"id":100026561,"name":"DeleteCollection","signature":"func (c *configMaps) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/configmap.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *configMaps) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"configmaps\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":153,"to":167}} {"id":100026562,"name":"Patch","signature":"func (c *configMaps) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ConfigMap, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/configmap.go","code":"// Patch applies the patch and returns the patched configMap.\nfunc (c *configMaps) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ConfigMap, err error) {\n\tresult = \u0026v1.ConfigMap{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"configmaps\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":169,"to":182}} {"id":100026563,"name":"Apply","signature":"func (c *configMaps) Apply(ctx context.Context, configMap *corev1.ConfigMapApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ConfigMap, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/configmap.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied configMap.\nfunc (c *configMaps) Apply(ctx context.Context, configMap *corev1.ConfigMapApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ConfigMap, err error) {\n\tif configMap == nil {\n\t\treturn nil, fmt.Errorf(\"configMap provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(configMap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := configMap.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"configMap.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.ConfigMap{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"configmaps\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":184,"to":208}} {"id":100026564,"name":"ComponentStatuses","signature":"func (c *CoreV1Client) ComponentStatuses() ComponentStatusInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/core_client.go","code":"func (c *CoreV1Client) ComponentStatuses() ComponentStatusInterface {\n\treturn newComponentStatuses(c)\n}","line":{"from":54,"to":56}} {"id":100026565,"name":"ConfigMaps","signature":"func (c *CoreV1Client) ConfigMaps(namespace string) ConfigMapInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/core_client.go","code":"func (c *CoreV1Client) ConfigMaps(namespace string) ConfigMapInterface {\n\treturn newConfigMaps(c, namespace)\n}","line":{"from":58,"to":60}} {"id":100026566,"name":"Endpoints","signature":"func (c *CoreV1Client) Endpoints(namespace string) EndpointsInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/core_client.go","code":"func (c *CoreV1Client) Endpoints(namespace string) EndpointsInterface {\n\treturn newEndpoints(c, namespace)\n}","line":{"from":62,"to":64}} {"id":100026567,"name":"Events","signature":"func (c *CoreV1Client) Events(namespace string) EventInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/core_client.go","code":"func (c *CoreV1Client) Events(namespace string) EventInterface {\n\treturn newEvents(c, namespace)\n}","line":{"from":66,"to":68}} {"id":100026568,"name":"LimitRanges","signature":"func (c *CoreV1Client) LimitRanges(namespace string) LimitRangeInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/core_client.go","code":"func (c *CoreV1Client) LimitRanges(namespace string) LimitRangeInterface {\n\treturn newLimitRanges(c, namespace)\n}","line":{"from":70,"to":72}} {"id":100026569,"name":"Namespaces","signature":"func (c *CoreV1Client) Namespaces() NamespaceInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/core_client.go","code":"func (c *CoreV1Client) Namespaces() NamespaceInterface {\n\treturn newNamespaces(c)\n}","line":{"from":74,"to":76}} {"id":100026570,"name":"Nodes","signature":"func (c *CoreV1Client) Nodes() NodeInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/core_client.go","code":"func (c *CoreV1Client) Nodes() NodeInterface {\n\treturn newNodes(c)\n}","line":{"from":78,"to":80}} {"id":100026571,"name":"PersistentVolumes","signature":"func (c *CoreV1Client) PersistentVolumes() PersistentVolumeInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/core_client.go","code":"func (c *CoreV1Client) PersistentVolumes() PersistentVolumeInterface {\n\treturn newPersistentVolumes(c)\n}","line":{"from":82,"to":84}} {"id":100026572,"name":"PersistentVolumeClaims","signature":"func (c *CoreV1Client) PersistentVolumeClaims(namespace string) PersistentVolumeClaimInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/core_client.go","code":"func (c *CoreV1Client) PersistentVolumeClaims(namespace string) PersistentVolumeClaimInterface {\n\treturn newPersistentVolumeClaims(c, namespace)\n}","line":{"from":86,"to":88}} {"id":100026573,"name":"Pods","signature":"func (c *CoreV1Client) Pods(namespace string) PodInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/core_client.go","code":"func (c *CoreV1Client) Pods(namespace string) PodInterface {\n\treturn newPods(c, namespace)\n}","line":{"from":90,"to":92}} {"id":100026574,"name":"PodTemplates","signature":"func (c *CoreV1Client) PodTemplates(namespace string) PodTemplateInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/core_client.go","code":"func (c *CoreV1Client) PodTemplates(namespace string) PodTemplateInterface {\n\treturn newPodTemplates(c, namespace)\n}","line":{"from":94,"to":96}} {"id":100026575,"name":"ReplicationControllers","signature":"func (c *CoreV1Client) ReplicationControllers(namespace string) ReplicationControllerInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/core_client.go","code":"func (c *CoreV1Client) ReplicationControllers(namespace string) ReplicationControllerInterface {\n\treturn newReplicationControllers(c, namespace)\n}","line":{"from":98,"to":100}} {"id":100026576,"name":"ResourceQuotas","signature":"func (c *CoreV1Client) ResourceQuotas(namespace string) ResourceQuotaInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/core_client.go","code":"func (c *CoreV1Client) ResourceQuotas(namespace string) ResourceQuotaInterface {\n\treturn newResourceQuotas(c, namespace)\n}","line":{"from":102,"to":104}} {"id":100026577,"name":"Secrets","signature":"func (c *CoreV1Client) Secrets(namespace string) SecretInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/core_client.go","code":"func (c *CoreV1Client) Secrets(namespace string) SecretInterface {\n\treturn newSecrets(c, namespace)\n}","line":{"from":106,"to":108}} {"id":100026578,"name":"Services","signature":"func (c *CoreV1Client) Services(namespace string) ServiceInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/core_client.go","code":"func (c *CoreV1Client) Services(namespace string) ServiceInterface {\n\treturn newServices(c, namespace)\n}","line":{"from":110,"to":112}} {"id":100026579,"name":"ServiceAccounts","signature":"func (c *CoreV1Client) ServiceAccounts(namespace string) ServiceAccountInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/core_client.go","code":"func (c *CoreV1Client) ServiceAccounts(namespace string) ServiceAccountInterface {\n\treturn newServiceAccounts(c, namespace)\n}","line":{"from":114,"to":116}} {"id":100026580,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*CoreV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/core_client.go","code":"// NewForConfig creates a new CoreV1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*CoreV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":118,"to":131}} {"id":100026581,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*CoreV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/core_client.go","code":"// NewForConfigAndClient creates a new CoreV1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*CoreV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026CoreV1Client{client}, nil\n}","line":{"from":133,"to":145}} {"id":100026582,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *CoreV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/core_client.go","code":"// NewForConfigOrDie creates a new CoreV1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *CoreV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":147,"to":155}} {"id":100026583,"name":"New","signature":"func New(c rest.Interface) *CoreV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/core_client.go","code":"// New creates a new CoreV1Client for the given RESTClient.\nfunc New(c rest.Interface) *CoreV1Client {\n\treturn \u0026CoreV1Client{c}\n}","line":{"from":157,"to":160}} {"id":100026584,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/core_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/api\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":162,"to":173}} {"id":100026585,"name":"RESTClient","signature":"func (c *CoreV1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/core_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *CoreV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":175,"to":182}} {"id":100026586,"name":"newEndpoints","signature":"func newEndpoints(c *CoreV1Client, namespace string) *endpoints","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/endpoints.go","code":"// newEndpoints returns a Endpoints\nfunc newEndpoints(c *CoreV1Client, namespace string) *endpoints {\n\treturn \u0026endpoints{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":62,"to":68}} {"id":100026587,"name":"Get","signature":"func (c *endpoints) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Endpoints, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/endpoints.go","code":"// Get takes name of the endpoints, and returns the corresponding endpoints object, and an error if there is any.\nfunc (c *endpoints) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Endpoints, err error) {\n\tresult = \u0026v1.Endpoints{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"endpoints\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":81}} {"id":100026588,"name":"List","signature":"func (c *endpoints) List(ctx context.Context, opts metav1.ListOptions) (result *v1.EndpointsList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/endpoints.go","code":"// List takes label and field selectors, and returns the list of Endpoints that match those selectors.\nfunc (c *endpoints) List(ctx context.Context, opts metav1.ListOptions) (result *v1.EndpointsList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.EndpointsList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"endpoints\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":83,"to":98}} {"id":100026589,"name":"Watch","signature":"func (c *endpoints) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/endpoints.go","code":"// Watch returns a watch.Interface that watches the requested endpoints.\nfunc (c *endpoints) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"endpoints\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":100,"to":113}} {"id":100026590,"name":"Create","signature":"func (c *endpoints) Create(ctx context.Context, endpoints *v1.Endpoints, opts metav1.CreateOptions) (result *v1.Endpoints, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/endpoints.go","code":"// Create takes the representation of a endpoints and creates it. Returns the server's representation of the endpoints, and an error, if there is any.\nfunc (c *endpoints) Create(ctx context.Context, endpoints *v1.Endpoints, opts metav1.CreateOptions) (result *v1.Endpoints, err error) {\n\tresult = \u0026v1.Endpoints{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"endpoints\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(endpoints).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":115,"to":126}} {"id":100026591,"name":"Update","signature":"func (c *endpoints) Update(ctx context.Context, endpoints *v1.Endpoints, opts metav1.UpdateOptions) (result *v1.Endpoints, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/endpoints.go","code":"// Update takes the representation of a endpoints and updates it. Returns the server's representation of the endpoints, and an error, if there is any.\nfunc (c *endpoints) Update(ctx context.Context, endpoints *v1.Endpoints, opts metav1.UpdateOptions) (result *v1.Endpoints, err error) {\n\tresult = \u0026v1.Endpoints{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"endpoints\").\n\t\tName(endpoints.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(endpoints).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":128,"to":140}} {"id":100026592,"name":"Delete","signature":"func (c *endpoints) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/endpoints.go","code":"// Delete takes name of the endpoints and deletes it. Returns an error if one occurs.\nfunc (c *endpoints) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"endpoints\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":142,"to":151}} {"id":100026593,"name":"DeleteCollection","signature":"func (c *endpoints) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/endpoints.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *endpoints) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"endpoints\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":153,"to":167}} {"id":100026594,"name":"Patch","signature":"func (c *endpoints) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Endpoints, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/endpoints.go","code":"// Patch applies the patch and returns the patched endpoints.\nfunc (c *endpoints) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Endpoints, err error) {\n\tresult = \u0026v1.Endpoints{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"endpoints\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":169,"to":182}} {"id":100026595,"name":"Apply","signature":"func (c *endpoints) Apply(ctx context.Context, endpoints *corev1.EndpointsApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Endpoints, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/endpoints.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied endpoints.\nfunc (c *endpoints) Apply(ctx context.Context, endpoints *corev1.EndpointsApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Endpoints, err error) {\n\tif endpoints == nil {\n\t\treturn nil, fmt.Errorf(\"endpoints provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(endpoints)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := endpoints.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"endpoints.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.Endpoints{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"endpoints\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":184,"to":208}} {"id":100026596,"name":"newEvents","signature":"func newEvents(c *CoreV1Client, namespace string) *events","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/event.go","code":"// newEvents returns a Events\nfunc newEvents(c *CoreV1Client, namespace string) *events {\n\treturn \u0026events{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":62,"to":68}} {"id":100026597,"name":"Get","signature":"func (c *events) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Event, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/event.go","code":"// Get takes name of the event, and returns the corresponding event object, and an error if there is any.\nfunc (c *events) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Event, err error) {\n\tresult = \u0026v1.Event{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":81}} {"id":100026598,"name":"List","signature":"func (c *events) List(ctx context.Context, opts metav1.ListOptions) (result *v1.EventList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/event.go","code":"// List takes label and field selectors, and returns the list of Events that match those selectors.\nfunc (c *events) List(ctx context.Context, opts metav1.ListOptions) (result *v1.EventList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.EventList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":83,"to":98}} {"id":100026599,"name":"Watch","signature":"func (c *events) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/event.go","code":"// Watch returns a watch.Interface that watches the requested events.\nfunc (c *events) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":100,"to":113}} {"id":100026600,"name":"Create","signature":"func (c *events) Create(ctx context.Context, event *v1.Event, opts metav1.CreateOptions) (result *v1.Event, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/event.go","code":"// Create takes the representation of a event and creates it. Returns the server's representation of the event, and an error, if there is any.\nfunc (c *events) Create(ctx context.Context, event *v1.Event, opts metav1.CreateOptions) (result *v1.Event, err error) {\n\tresult = \u0026v1.Event{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(event).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":115,"to":126}} {"id":100026601,"name":"Update","signature":"func (c *events) Update(ctx context.Context, event *v1.Event, opts metav1.UpdateOptions) (result *v1.Event, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/event.go","code":"// Update takes the representation of a event and updates it. Returns the server's representation of the event, and an error, if there is any.\nfunc (c *events) Update(ctx context.Context, event *v1.Event, opts metav1.UpdateOptions) (result *v1.Event, err error) {\n\tresult = \u0026v1.Event{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tName(event.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(event).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":128,"to":140}} {"id":100026602,"name":"Delete","signature":"func (c *events) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/event.go","code":"// Delete takes name of the event and deletes it. Returns an error if one occurs.\nfunc (c *events) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":142,"to":151}} {"id":100026603,"name":"DeleteCollection","signature":"func (c *events) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/event.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *events) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":153,"to":167}} {"id":100026604,"name":"Patch","signature":"func (c *events) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Event, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/event.go","code":"// Patch applies the patch and returns the patched event.\nfunc (c *events) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Event, err error) {\n\tresult = \u0026v1.Event{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":169,"to":182}} {"id":100026605,"name":"Apply","signature":"func (c *events) Apply(ctx context.Context, event *corev1.EventApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Event, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/event.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied event.\nfunc (c *events) Apply(ctx context.Context, event *corev1.EventApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Event, err error) {\n\tif event == nil {\n\t\treturn nil, fmt.Errorf(\"event provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(event)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := event.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"event.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.Event{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":184,"to":208}} {"id":100026606,"name":"CreateWithEventNamespace","signature":"func (e *events) CreateWithEventNamespace(event *v1.Event) (*v1.Event, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/event_expansion.go","code":"// CreateWithEventNamespace makes a new event. Returns the copy of the event the server returns,\n// or an error. The namespace to create the event within is deduced from the\n// event; it must either match this event client's namespace, or this event\n// client must have been created with the \"\" namespace.\nfunc (e *events) CreateWithEventNamespace(event *v1.Event) (*v1.Event, error) {\n\tif e.ns != \"\" \u0026\u0026 event.Namespace != e.ns {\n\t\treturn nil, fmt.Errorf(\"can't create an event with namespace '%v' in namespace '%v'\", event.Namespace, e.ns)\n\t}\n\tresult := \u0026v1.Event{}\n\terr := e.client.Post().\n\t\tNamespaceIfScoped(event.Namespace, len(event.Namespace) \u003e 0).\n\t\tResource(\"events\").\n\t\tBody(event).\n\t\tDo(context.TODO()).\n\t\tInto(result)\n\treturn result, err\n}","line":{"from":46,"to":62}} {"id":100026607,"name":"UpdateWithEventNamespace","signature":"func (e *events) UpdateWithEventNamespace(event *v1.Event) (*v1.Event, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/event_expansion.go","code":"// UpdateWithEventNamespace modifies an existing event. It returns the copy of the event that the server returns,\n// or an error. The namespace and key to update the event within is deduced from the event. The\n// namespace must either match this event client's namespace, or this event client must have been\n// created with the \"\" namespace. Update also requires the ResourceVersion to be set in the event\n// object.\nfunc (e *events) UpdateWithEventNamespace(event *v1.Event) (*v1.Event, error) {\n\tif e.ns != \"\" \u0026\u0026 event.Namespace != e.ns {\n\t\treturn nil, fmt.Errorf(\"can't update an event with namespace '%v' in namespace '%v'\", event.Namespace, e.ns)\n\t}\n\tresult := \u0026v1.Event{}\n\terr := e.client.Put().\n\t\tNamespaceIfScoped(event.Namespace, len(event.Namespace) \u003e 0).\n\t\tResource(\"events\").\n\t\tName(event.Name).\n\t\tBody(event).\n\t\tDo(context.TODO()).\n\t\tInto(result)\n\treturn result, err\n}","line":{"from":64,"to":82}} {"id":100026608,"name":"PatchWithEventNamespace","signature":"func (e *events) PatchWithEventNamespace(incompleteEvent *v1.Event, data []byte) (*v1.Event, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/event_expansion.go","code":"// PatchWithEventNamespace modifies an existing event. It returns the copy of\n// the event that the server returns, or an error. The namespace and name of the\n// target event is deduced from the incompleteEvent. The namespace must either\n// match this event client's namespace, or this event client must have been\n// created with the \"\" namespace.\nfunc (e *events) PatchWithEventNamespace(incompleteEvent *v1.Event, data []byte) (*v1.Event, error) {\n\tif e.ns != \"\" \u0026\u0026 incompleteEvent.Namespace != e.ns {\n\t\treturn nil, fmt.Errorf(\"can't patch an event with namespace '%v' in namespace '%v'\", incompleteEvent.Namespace, e.ns)\n\t}\n\tresult := \u0026v1.Event{}\n\terr := e.client.Patch(types.StrategicMergePatchType).\n\t\tNamespaceIfScoped(incompleteEvent.Namespace, len(incompleteEvent.Namespace) \u003e 0).\n\t\tResource(\"events\").\n\t\tName(incompleteEvent.Name).\n\t\tBody(data).\n\t\tDo(context.TODO()).\n\t\tInto(result)\n\treturn result, err\n}","line":{"from":84,"to":102}} {"id":100026609,"name":"Search","signature":"func (e *events) Search(scheme *runtime.Scheme, objOrRef runtime.Object) (*v1.EventList, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/event_expansion.go","code":"// Search finds events about the specified object. The namespace of the\n// object must match this event's client namespace unless the event client\n// was made with the \"\" namespace.\nfunc (e *events) Search(scheme *runtime.Scheme, objOrRef runtime.Object) (*v1.EventList, error) {\n\tref, err := ref.GetReference(scheme, objOrRef)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(e.ns) \u003e 0 \u0026\u0026 ref.Namespace != e.ns {\n\t\treturn nil, fmt.Errorf(\"won't be able to find any events of namespace '%v' in namespace '%v'\", ref.Namespace, e.ns)\n\t}\n\tstringRefKind := string(ref.Kind)\n\tvar refKind *string\n\tif len(stringRefKind) \u003e 0 {\n\t\trefKind = \u0026stringRefKind\n\t}\n\tstringRefUID := string(ref.UID)\n\tvar refUID *string\n\tif len(stringRefUID) \u003e 0 {\n\t\trefUID = \u0026stringRefUID\n\t}\n\tfieldSelector := e.GetFieldSelector(\u0026ref.Name, \u0026ref.Namespace, refKind, refUID)\n\treturn e.List(context.TODO(), metav1.ListOptions{FieldSelector: fieldSelector.String()})\n}","line":{"from":104,"to":127}} {"id":100026610,"name":"GetFieldSelector","signature":"func (e *events) GetFieldSelector(involvedObjectName, involvedObjectNamespace, involvedObjectKind, involvedObjectUID *string) fields.Selector","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/event_expansion.go","code":"// Returns the appropriate field selector based on the API version being used to communicate with the server.\n// The returned field selector can be used with List and Watch to filter desired events.\nfunc (e *events) GetFieldSelector(involvedObjectName, involvedObjectNamespace, involvedObjectKind, involvedObjectUID *string) fields.Selector {\n\tfield := fields.Set{}\n\tif involvedObjectName != nil {\n\t\tfield[\"involvedObject.name\"] = *involvedObjectName\n\t}\n\tif involvedObjectNamespace != nil {\n\t\tfield[\"involvedObject.namespace\"] = *involvedObjectNamespace\n\t}\n\tif involvedObjectKind != nil {\n\t\tfield[\"involvedObject.kind\"] = *involvedObjectKind\n\t}\n\tif involvedObjectUID != nil {\n\t\tfield[\"involvedObject.uid\"] = *involvedObjectUID\n\t}\n\treturn field.AsSelector()\n}","line":{"from":129,"to":146}} {"id":100026611,"name":"GetInvolvedObjectNameFieldLabel","signature":"func GetInvolvedObjectNameFieldLabel(version string) string","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/event_expansion.go","code":"// Returns the appropriate field label to use for name of the involved object as per the given API version.\n// DEPRECATED: please use \"involvedObject.name\" inline.\nfunc GetInvolvedObjectNameFieldLabel(version string) string {\n\treturn \"involvedObject.name\"\n}","line":{"from":148,"to":152}} {"id":100026612,"name":"Create","signature":"func (e *EventSinkImpl) Create(event *v1.Event) (*v1.Event, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/event_expansion.go","code":"func (e *EventSinkImpl) Create(event *v1.Event) (*v1.Event, error) {\n\treturn e.Interface.CreateWithEventNamespace(event)\n}","line":{"from":159,"to":161}} {"id":100026613,"name":"Update","signature":"func (e *EventSinkImpl) Update(event *v1.Event) (*v1.Event, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/event_expansion.go","code":"func (e *EventSinkImpl) Update(event *v1.Event) (*v1.Event, error) {\n\treturn e.Interface.UpdateWithEventNamespace(event)\n}","line":{"from":163,"to":165}} {"id":100026614,"name":"Patch","signature":"func (e *EventSinkImpl) Patch(event *v1.Event, data []byte) (*v1.Event, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/event_expansion.go","code":"func (e *EventSinkImpl) Patch(event *v1.Event, data []byte) (*v1.Event, error) {\n\treturn e.Interface.PatchWithEventNamespace(event, data)\n}","line":{"from":167,"to":169}} {"id":100026615,"name":"newLimitRanges","signature":"func newLimitRanges(c *CoreV1Client, namespace string) *limitRanges","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/limitrange.go","code":"// newLimitRanges returns a LimitRanges\nfunc newLimitRanges(c *CoreV1Client, namespace string) *limitRanges {\n\treturn \u0026limitRanges{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":62,"to":68}} {"id":100026616,"name":"Get","signature":"func (c *limitRanges) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.LimitRange, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/limitrange.go","code":"// Get takes name of the limitRange, and returns the corresponding limitRange object, and an error if there is any.\nfunc (c *limitRanges) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.LimitRange, err error) {\n\tresult = \u0026v1.LimitRange{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"limitranges\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":81}} {"id":100026617,"name":"List","signature":"func (c *limitRanges) List(ctx context.Context, opts metav1.ListOptions) (result *v1.LimitRangeList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/limitrange.go","code":"// List takes label and field selectors, and returns the list of LimitRanges that match those selectors.\nfunc (c *limitRanges) List(ctx context.Context, opts metav1.ListOptions) (result *v1.LimitRangeList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.LimitRangeList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"limitranges\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":83,"to":98}} {"id":100026618,"name":"Watch","signature":"func (c *limitRanges) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/limitrange.go","code":"// Watch returns a watch.Interface that watches the requested limitRanges.\nfunc (c *limitRanges) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"limitranges\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":100,"to":113}} {"id":100026619,"name":"Create","signature":"func (c *limitRanges) Create(ctx context.Context, limitRange *v1.LimitRange, opts metav1.CreateOptions) (result *v1.LimitRange, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/limitrange.go","code":"// Create takes the representation of a limitRange and creates it. Returns the server's representation of the limitRange, and an error, if there is any.\nfunc (c *limitRanges) Create(ctx context.Context, limitRange *v1.LimitRange, opts metav1.CreateOptions) (result *v1.LimitRange, err error) {\n\tresult = \u0026v1.LimitRange{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"limitranges\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(limitRange).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":115,"to":126}} {"id":100026620,"name":"Update","signature":"func (c *limitRanges) Update(ctx context.Context, limitRange *v1.LimitRange, opts metav1.UpdateOptions) (result *v1.LimitRange, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/limitrange.go","code":"// Update takes the representation of a limitRange and updates it. Returns the server's representation of the limitRange, and an error, if there is any.\nfunc (c *limitRanges) Update(ctx context.Context, limitRange *v1.LimitRange, opts metav1.UpdateOptions) (result *v1.LimitRange, err error) {\n\tresult = \u0026v1.LimitRange{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"limitranges\").\n\t\tName(limitRange.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(limitRange).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":128,"to":140}} {"id":100026621,"name":"Delete","signature":"func (c *limitRanges) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/limitrange.go","code":"// Delete takes name of the limitRange and deletes it. Returns an error if one occurs.\nfunc (c *limitRanges) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"limitranges\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":142,"to":151}} {"id":100026622,"name":"DeleteCollection","signature":"func (c *limitRanges) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/limitrange.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *limitRanges) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"limitranges\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":153,"to":167}} {"id":100026623,"name":"Patch","signature":"func (c *limitRanges) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.LimitRange, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/limitrange.go","code":"// Patch applies the patch and returns the patched limitRange.\nfunc (c *limitRanges) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.LimitRange, err error) {\n\tresult = \u0026v1.LimitRange{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"limitranges\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":169,"to":182}} {"id":100026624,"name":"Apply","signature":"func (c *limitRanges) Apply(ctx context.Context, limitRange *corev1.LimitRangeApplyConfiguration, opts metav1.ApplyOptions) (result *v1.LimitRange, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/limitrange.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied limitRange.\nfunc (c *limitRanges) Apply(ctx context.Context, limitRange *corev1.LimitRangeApplyConfiguration, opts metav1.ApplyOptions) (result *v1.LimitRange, err error) {\n\tif limitRange == nil {\n\t\treturn nil, fmt.Errorf(\"limitRange provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(limitRange)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := limitRange.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"limitRange.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.LimitRange{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"limitranges\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":184,"to":208}} {"id":100026625,"name":"newNamespaces","signature":"func newNamespaces(c *CoreV1Client) *namespaces","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/namespace.go","code":"// newNamespaces returns a Namespaces\nfunc newNamespaces(c *CoreV1Client) *namespaces {\n\treturn \u0026namespaces{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":62,"to":67}} {"id":100026626,"name":"Get","signature":"func (c *namespaces) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Namespace, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/namespace.go","code":"// Get takes name of the namespace, and returns the corresponding namespace object, and an error if there is any.\nfunc (c *namespaces) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Namespace, err error) {\n\tresult = \u0026v1.Namespace{}\n\terr = c.client.Get().\n\t\tResource(\"namespaces\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":69,"to":79}} {"id":100026627,"name":"List","signature":"func (c *namespaces) List(ctx context.Context, opts metav1.ListOptions) (result *v1.NamespaceList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/namespace.go","code":"// List takes label and field selectors, and returns the list of Namespaces that match those selectors.\nfunc (c *namespaces) List(ctx context.Context, opts metav1.ListOptions) (result *v1.NamespaceList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.NamespaceList{}\n\terr = c.client.Get().\n\t\tResource(\"namespaces\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":81,"to":95}} {"id":100026628,"name":"Watch","signature":"func (c *namespaces) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/namespace.go","code":"// Watch returns a watch.Interface that watches the requested namespaces.\nfunc (c *namespaces) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"namespaces\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":97,"to":109}} {"id":100026629,"name":"Create","signature":"func (c *namespaces) Create(ctx context.Context, namespace *v1.Namespace, opts metav1.CreateOptions) (result *v1.Namespace, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/namespace.go","code":"// Create takes the representation of a namespace and creates it. Returns the server's representation of the namespace, and an error, if there is any.\nfunc (c *namespaces) Create(ctx context.Context, namespace *v1.Namespace, opts metav1.CreateOptions) (result *v1.Namespace, err error) {\n\tresult = \u0026v1.Namespace{}\n\terr = c.client.Post().\n\t\tResource(\"namespaces\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(namespace).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":111,"to":121}} {"id":100026630,"name":"Update","signature":"func (c *namespaces) Update(ctx context.Context, namespace *v1.Namespace, opts metav1.UpdateOptions) (result *v1.Namespace, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/namespace.go","code":"// Update takes the representation of a namespace and updates it. Returns the server's representation of the namespace, and an error, if there is any.\nfunc (c *namespaces) Update(ctx context.Context, namespace *v1.Namespace, opts metav1.UpdateOptions) (result *v1.Namespace, err error) {\n\tresult = \u0026v1.Namespace{}\n\terr = c.client.Put().\n\t\tResource(\"namespaces\").\n\t\tName(namespace.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(namespace).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":123,"to":134}} {"id":100026631,"name":"UpdateStatus","signature":"func (c *namespaces) UpdateStatus(ctx context.Context, namespace *v1.Namespace, opts metav1.UpdateOptions) (result *v1.Namespace, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/namespace.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *namespaces) UpdateStatus(ctx context.Context, namespace *v1.Namespace, opts metav1.UpdateOptions) (result *v1.Namespace, err error) {\n\tresult = \u0026v1.Namespace{}\n\terr = c.client.Put().\n\t\tResource(\"namespaces\").\n\t\tName(namespace.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(namespace).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":136,"to":149}} {"id":100026632,"name":"Delete","signature":"func (c *namespaces) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/namespace.go","code":"// Delete takes name of the namespace and deletes it. Returns an error if one occurs.\nfunc (c *namespaces) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"namespaces\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":151,"to":159}} {"id":100026633,"name":"Patch","signature":"func (c *namespaces) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Namespace, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/namespace.go","code":"// Patch applies the patch and returns the patched namespace.\nfunc (c *namespaces) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Namespace, err error) {\n\tresult = \u0026v1.Namespace{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"namespaces\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":161,"to":173}} {"id":100026634,"name":"Apply","signature":"func (c *namespaces) Apply(ctx context.Context, namespace *corev1.NamespaceApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Namespace, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/namespace.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied namespace.\nfunc (c *namespaces) Apply(ctx context.Context, namespace *corev1.NamespaceApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Namespace, err error) {\n\tif namespace == nil {\n\t\treturn nil, fmt.Errorf(\"namespace provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := namespace.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"namespace.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.Namespace{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"namespaces\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":175,"to":198}} {"id":100026635,"name":"ApplyStatus","signature":"func (c *namespaces) ApplyStatus(ctx context.Context, namespace *corev1.NamespaceApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Namespace, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/namespace.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *namespaces) ApplyStatus(ctx context.Context, namespace *corev1.NamespaceApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Namespace, err error) {\n\tif namespace == nil {\n\t\treturn nil, fmt.Errorf(\"namespace provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := namespace.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"namespace.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1.Namespace{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"namespaces\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":200,"to":227}} {"id":100026636,"name":"Finalize","signature":"func (c *namespaces) Finalize(ctx context.Context, namespace *v1.Namespace, opts metav1.UpdateOptions) (result *v1.Namespace, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/namespace_expansion.go","code":"// Finalize takes the representation of a namespace to update. Returns the server's representation of the namespace, and an error, if it occurs.\nfunc (c *namespaces) Finalize(ctx context.Context, namespace *v1.Namespace, opts metav1.UpdateOptions) (result *v1.Namespace, err error) {\n\tresult = \u0026v1.Namespace{}\n\terr = c.client.Put().Resource(\"namespaces\").Name(namespace.Name).VersionedParams(\u0026opts, scheme.ParameterCodec).SubResource(\"finalize\").Body(namespace).Do(ctx).Into(result)\n\treturn\n}","line":{"from":32,"to":37}} {"id":100026637,"name":"newNodes","signature":"func newNodes(c *CoreV1Client) *nodes","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/node.go","code":"// newNodes returns a Nodes\nfunc newNodes(c *CoreV1Client) *nodes {\n\treturn \u0026nodes{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":63,"to":68}} {"id":100026638,"name":"Get","signature":"func (c *nodes) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Node, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/node.go","code":"// Get takes name of the node, and returns the corresponding node object, and an error if there is any.\nfunc (c *nodes) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Node, err error) {\n\tresult = \u0026v1.Node{}\n\terr = c.client.Get().\n\t\tResource(\"nodes\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":80}} {"id":100026639,"name":"List","signature":"func (c *nodes) List(ctx context.Context, opts metav1.ListOptions) (result *v1.NodeList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/node.go","code":"// List takes label and field selectors, and returns the list of Nodes that match those selectors.\nfunc (c *nodes) List(ctx context.Context, opts metav1.ListOptions) (result *v1.NodeList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.NodeList{}\n\terr = c.client.Get().\n\t\tResource(\"nodes\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":82,"to":96}} {"id":100026640,"name":"Watch","signature":"func (c *nodes) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/node.go","code":"// Watch returns a watch.Interface that watches the requested nodes.\nfunc (c *nodes) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"nodes\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":98,"to":110}} {"id":100026641,"name":"Create","signature":"func (c *nodes) Create(ctx context.Context, node *v1.Node, opts metav1.CreateOptions) (result *v1.Node, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/node.go","code":"// Create takes the representation of a node and creates it. Returns the server's representation of the node, and an error, if there is any.\nfunc (c *nodes) Create(ctx context.Context, node *v1.Node, opts metav1.CreateOptions) (result *v1.Node, err error) {\n\tresult = \u0026v1.Node{}\n\terr = c.client.Post().\n\t\tResource(\"nodes\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(node).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":112,"to":122}} {"id":100026642,"name":"Update","signature":"func (c *nodes) Update(ctx context.Context, node *v1.Node, opts metav1.UpdateOptions) (result *v1.Node, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/node.go","code":"// Update takes the representation of a node and updates it. Returns the server's representation of the node, and an error, if there is any.\nfunc (c *nodes) Update(ctx context.Context, node *v1.Node, opts metav1.UpdateOptions) (result *v1.Node, err error) {\n\tresult = \u0026v1.Node{}\n\terr = c.client.Put().\n\t\tResource(\"nodes\").\n\t\tName(node.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(node).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":124,"to":135}} {"id":100026643,"name":"UpdateStatus","signature":"func (c *nodes) UpdateStatus(ctx context.Context, node *v1.Node, opts metav1.UpdateOptions) (result *v1.Node, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/node.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *nodes) UpdateStatus(ctx context.Context, node *v1.Node, opts metav1.UpdateOptions) (result *v1.Node, err error) {\n\tresult = \u0026v1.Node{}\n\terr = c.client.Put().\n\t\tResource(\"nodes\").\n\t\tName(node.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(node).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":137,"to":150}} {"id":100026644,"name":"Delete","signature":"func (c *nodes) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/node.go","code":"// Delete takes name of the node and deletes it. Returns an error if one occurs.\nfunc (c *nodes) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"nodes\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":152,"to":160}} {"id":100026645,"name":"DeleteCollection","signature":"func (c *nodes) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/node.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *nodes) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"nodes\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":162,"to":175}} {"id":100026646,"name":"Patch","signature":"func (c *nodes) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Node, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/node.go","code":"// Patch applies the patch and returns the patched node.\nfunc (c *nodes) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Node, err error) {\n\tresult = \u0026v1.Node{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"nodes\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":177,"to":189}} {"id":100026647,"name":"Apply","signature":"func (c *nodes) Apply(ctx context.Context, node *corev1.NodeApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Node, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/node.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied node.\nfunc (c *nodes) Apply(ctx context.Context, node *corev1.NodeApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Node, err error) {\n\tif node == nil {\n\t\treturn nil, fmt.Errorf(\"node provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(node)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := node.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"node.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.Node{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"nodes\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":191,"to":214}} {"id":100026648,"name":"ApplyStatus","signature":"func (c *nodes) ApplyStatus(ctx context.Context, node *corev1.NodeApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Node, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/node.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *nodes) ApplyStatus(ctx context.Context, node *corev1.NodeApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Node, err error) {\n\tif node == nil {\n\t\treturn nil, fmt.Errorf(\"node provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(node)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := node.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"node.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1.Node{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"nodes\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":216,"to":243}} {"id":100026649,"name":"PatchStatus","signature":"func (c *nodes) PatchStatus(ctx context.Context, nodeName string, data []byte) (*v1.Node, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/node_expansion.go","code":"// PatchStatus modifies the status of an existing node. It returns the copy of\n// the node that the server returns, or an error.\nfunc (c *nodes) PatchStatus(ctx context.Context, nodeName string, data []byte) (*v1.Node, error) {\n\tresult := \u0026v1.Node{}\n\terr := c.client.Patch(types.StrategicMergePatchType).\n\t\tResource(\"nodes\").\n\t\tName(nodeName).\n\t\tSubResource(\"status\").\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn result, err\n}","line":{"from":33,"to":45}} {"id":100026650,"name":"newPersistentVolumes","signature":"func newPersistentVolumes(c *CoreV1Client) *persistentVolumes","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/persistentvolume.go","code":"// newPersistentVolumes returns a PersistentVolumes\nfunc newPersistentVolumes(c *CoreV1Client) *persistentVolumes {\n\treturn \u0026persistentVolumes{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":63,"to":68}} {"id":100026651,"name":"Get","signature":"func (c *persistentVolumes) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.PersistentVolume, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/persistentvolume.go","code":"// Get takes name of the persistentVolume, and returns the corresponding persistentVolume object, and an error if there is any.\nfunc (c *persistentVolumes) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.PersistentVolume, err error) {\n\tresult = \u0026v1.PersistentVolume{}\n\terr = c.client.Get().\n\t\tResource(\"persistentvolumes\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":80}} {"id":100026652,"name":"List","signature":"func (c *persistentVolumes) List(ctx context.Context, opts metav1.ListOptions) (result *v1.PersistentVolumeList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/persistentvolume.go","code":"// List takes label and field selectors, and returns the list of PersistentVolumes that match those selectors.\nfunc (c *persistentVolumes) List(ctx context.Context, opts metav1.ListOptions) (result *v1.PersistentVolumeList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.PersistentVolumeList{}\n\terr = c.client.Get().\n\t\tResource(\"persistentvolumes\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":82,"to":96}} {"id":100026653,"name":"Watch","signature":"func (c *persistentVolumes) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/persistentvolume.go","code":"// Watch returns a watch.Interface that watches the requested persistentVolumes.\nfunc (c *persistentVolumes) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"persistentvolumes\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":98,"to":110}} {"id":100026654,"name":"Create","signature":"func (c *persistentVolumes) Create(ctx context.Context, persistentVolume *v1.PersistentVolume, opts metav1.CreateOptions) (result *v1.PersistentVolume, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/persistentvolume.go","code":"// Create takes the representation of a persistentVolume and creates it. Returns the server's representation of the persistentVolume, and an error, if there is any.\nfunc (c *persistentVolumes) Create(ctx context.Context, persistentVolume *v1.PersistentVolume, opts metav1.CreateOptions) (result *v1.PersistentVolume, err error) {\n\tresult = \u0026v1.PersistentVolume{}\n\terr = c.client.Post().\n\t\tResource(\"persistentvolumes\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(persistentVolume).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":112,"to":122}} {"id":100026655,"name":"Update","signature":"func (c *persistentVolumes) Update(ctx context.Context, persistentVolume *v1.PersistentVolume, opts metav1.UpdateOptions) (result *v1.PersistentVolume, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/persistentvolume.go","code":"// Update takes the representation of a persistentVolume and updates it. Returns the server's representation of the persistentVolume, and an error, if there is any.\nfunc (c *persistentVolumes) Update(ctx context.Context, persistentVolume *v1.PersistentVolume, opts metav1.UpdateOptions) (result *v1.PersistentVolume, err error) {\n\tresult = \u0026v1.PersistentVolume{}\n\terr = c.client.Put().\n\t\tResource(\"persistentvolumes\").\n\t\tName(persistentVolume.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(persistentVolume).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":124,"to":135}} {"id":100026656,"name":"UpdateStatus","signature":"func (c *persistentVolumes) UpdateStatus(ctx context.Context, persistentVolume *v1.PersistentVolume, opts metav1.UpdateOptions) (result *v1.PersistentVolume, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/persistentvolume.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *persistentVolumes) UpdateStatus(ctx context.Context, persistentVolume *v1.PersistentVolume, opts metav1.UpdateOptions) (result *v1.PersistentVolume, err error) {\n\tresult = \u0026v1.PersistentVolume{}\n\terr = c.client.Put().\n\t\tResource(\"persistentvolumes\").\n\t\tName(persistentVolume.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(persistentVolume).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":137,"to":150}} {"id":100026657,"name":"Delete","signature":"func (c *persistentVolumes) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/persistentvolume.go","code":"// Delete takes name of the persistentVolume and deletes it. Returns an error if one occurs.\nfunc (c *persistentVolumes) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"persistentvolumes\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":152,"to":160}} {"id":100026658,"name":"DeleteCollection","signature":"func (c *persistentVolumes) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/persistentvolume.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *persistentVolumes) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"persistentvolumes\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":162,"to":175}} {"id":100026659,"name":"Patch","signature":"func (c *persistentVolumes) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.PersistentVolume, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/persistentvolume.go","code":"// Patch applies the patch and returns the patched persistentVolume.\nfunc (c *persistentVolumes) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.PersistentVolume, err error) {\n\tresult = \u0026v1.PersistentVolume{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"persistentvolumes\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":177,"to":189}} {"id":100026660,"name":"Apply","signature":"func (c *persistentVolumes) Apply(ctx context.Context, persistentVolume *corev1.PersistentVolumeApplyConfiguration, opts metav1.ApplyOptions) (result *v1.PersistentVolume, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/persistentvolume.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied persistentVolume.\nfunc (c *persistentVolumes) Apply(ctx context.Context, persistentVolume *corev1.PersistentVolumeApplyConfiguration, opts metav1.ApplyOptions) (result *v1.PersistentVolume, err error) {\n\tif persistentVolume == nil {\n\t\treturn nil, fmt.Errorf(\"persistentVolume provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(persistentVolume)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := persistentVolume.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"persistentVolume.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.PersistentVolume{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"persistentvolumes\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":191,"to":214}} {"id":100026661,"name":"ApplyStatus","signature":"func (c *persistentVolumes) ApplyStatus(ctx context.Context, persistentVolume *corev1.PersistentVolumeApplyConfiguration, opts metav1.ApplyOptions) (result *v1.PersistentVolume, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/persistentvolume.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *persistentVolumes) ApplyStatus(ctx context.Context, persistentVolume *corev1.PersistentVolumeApplyConfiguration, opts metav1.ApplyOptions) (result *v1.PersistentVolume, err error) {\n\tif persistentVolume == nil {\n\t\treturn nil, fmt.Errorf(\"persistentVolume provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(persistentVolume)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := persistentVolume.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"persistentVolume.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1.PersistentVolume{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"persistentvolumes\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":216,"to":243}} {"id":100026662,"name":"newPersistentVolumeClaims","signature":"func newPersistentVolumeClaims(c *CoreV1Client, namespace string) *persistentVolumeClaims","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/persistentvolumeclaim.go","code":"// newPersistentVolumeClaims returns a PersistentVolumeClaims\nfunc newPersistentVolumeClaims(c *CoreV1Client, namespace string) *persistentVolumeClaims {\n\treturn \u0026persistentVolumeClaims{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":64,"to":70}} {"id":100026663,"name":"Get","signature":"func (c *persistentVolumeClaims) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.PersistentVolumeClaim, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/persistentvolumeclaim.go","code":"// Get takes name of the persistentVolumeClaim, and returns the corresponding persistentVolumeClaim object, and an error if there is any.\nfunc (c *persistentVolumeClaims) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.PersistentVolumeClaim, err error) {\n\tresult = \u0026v1.PersistentVolumeClaim{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"persistentvolumeclaims\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":72,"to":83}} {"id":100026664,"name":"List","signature":"func (c *persistentVolumeClaims) List(ctx context.Context, opts metav1.ListOptions) (result *v1.PersistentVolumeClaimList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/persistentvolumeclaim.go","code":"// List takes label and field selectors, and returns the list of PersistentVolumeClaims that match those selectors.\nfunc (c *persistentVolumeClaims) List(ctx context.Context, opts metav1.ListOptions) (result *v1.PersistentVolumeClaimList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.PersistentVolumeClaimList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"persistentvolumeclaims\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":85,"to":100}} {"id":100026665,"name":"Watch","signature":"func (c *persistentVolumeClaims) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/persistentvolumeclaim.go","code":"// Watch returns a watch.Interface that watches the requested persistentVolumeClaims.\nfunc (c *persistentVolumeClaims) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"persistentvolumeclaims\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":102,"to":115}} {"id":100026666,"name":"Create","signature":"func (c *persistentVolumeClaims) Create(ctx context.Context, persistentVolumeClaim *v1.PersistentVolumeClaim, opts metav1.CreateOptions) (result *v1.PersistentVolumeClaim, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/persistentvolumeclaim.go","code":"// Create takes the representation of a persistentVolumeClaim and creates it. Returns the server's representation of the persistentVolumeClaim, and an error, if there is any.\nfunc (c *persistentVolumeClaims) Create(ctx context.Context, persistentVolumeClaim *v1.PersistentVolumeClaim, opts metav1.CreateOptions) (result *v1.PersistentVolumeClaim, err error) {\n\tresult = \u0026v1.PersistentVolumeClaim{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"persistentvolumeclaims\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(persistentVolumeClaim).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":117,"to":128}} {"id":100026667,"name":"Update","signature":"func (c *persistentVolumeClaims) Update(ctx context.Context, persistentVolumeClaim *v1.PersistentVolumeClaim, opts metav1.UpdateOptions) (result *v1.PersistentVolumeClaim, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/persistentvolumeclaim.go","code":"// Update takes the representation of a persistentVolumeClaim and updates it. Returns the server's representation of the persistentVolumeClaim, and an error, if there is any.\nfunc (c *persistentVolumeClaims) Update(ctx context.Context, persistentVolumeClaim *v1.PersistentVolumeClaim, opts metav1.UpdateOptions) (result *v1.PersistentVolumeClaim, err error) {\n\tresult = \u0026v1.PersistentVolumeClaim{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"persistentvolumeclaims\").\n\t\tName(persistentVolumeClaim.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(persistentVolumeClaim).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":130,"to":142}} {"id":100026668,"name":"UpdateStatus","signature":"func (c *persistentVolumeClaims) UpdateStatus(ctx context.Context, persistentVolumeClaim *v1.PersistentVolumeClaim, opts metav1.UpdateOptions) (result *v1.PersistentVolumeClaim, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/persistentvolumeclaim.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *persistentVolumeClaims) UpdateStatus(ctx context.Context, persistentVolumeClaim *v1.PersistentVolumeClaim, opts metav1.UpdateOptions) (result *v1.PersistentVolumeClaim, err error) {\n\tresult = \u0026v1.PersistentVolumeClaim{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"persistentvolumeclaims\").\n\t\tName(persistentVolumeClaim.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(persistentVolumeClaim).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":144,"to":158}} {"id":100026669,"name":"Delete","signature":"func (c *persistentVolumeClaims) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/persistentvolumeclaim.go","code":"// Delete takes name of the persistentVolumeClaim and deletes it. Returns an error if one occurs.\nfunc (c *persistentVolumeClaims) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"persistentvolumeclaims\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":160,"to":169}} {"id":100026670,"name":"DeleteCollection","signature":"func (c *persistentVolumeClaims) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/persistentvolumeclaim.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *persistentVolumeClaims) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"persistentvolumeclaims\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":171,"to":185}} {"id":100026671,"name":"Patch","signature":"func (c *persistentVolumeClaims) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.PersistentVolumeClaim, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/persistentvolumeclaim.go","code":"// Patch applies the patch and returns the patched persistentVolumeClaim.\nfunc (c *persistentVolumeClaims) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.PersistentVolumeClaim, err error) {\n\tresult = \u0026v1.PersistentVolumeClaim{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"persistentvolumeclaims\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":187,"to":200}} {"id":100026672,"name":"Apply","signature":"func (c *persistentVolumeClaims) Apply(ctx context.Context, persistentVolumeClaim *corev1.PersistentVolumeClaimApplyConfiguration, opts metav1.ApplyOptions) (result *v1.PersistentVolumeClaim, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/persistentvolumeclaim.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied persistentVolumeClaim.\nfunc (c *persistentVolumeClaims) Apply(ctx context.Context, persistentVolumeClaim *corev1.PersistentVolumeClaimApplyConfiguration, opts metav1.ApplyOptions) (result *v1.PersistentVolumeClaim, err error) {\n\tif persistentVolumeClaim == nil {\n\t\treturn nil, fmt.Errorf(\"persistentVolumeClaim provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(persistentVolumeClaim)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := persistentVolumeClaim.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"persistentVolumeClaim.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.PersistentVolumeClaim{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"persistentvolumeclaims\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":202,"to":226}} {"id":100026673,"name":"ApplyStatus","signature":"func (c *persistentVolumeClaims) ApplyStatus(ctx context.Context, persistentVolumeClaim *corev1.PersistentVolumeClaimApplyConfiguration, opts metav1.ApplyOptions) (result *v1.PersistentVolumeClaim, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/persistentvolumeclaim.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *persistentVolumeClaims) ApplyStatus(ctx context.Context, persistentVolumeClaim *corev1.PersistentVolumeClaimApplyConfiguration, opts metav1.ApplyOptions) (result *v1.PersistentVolumeClaim, err error) {\n\tif persistentVolumeClaim == nil {\n\t\treturn nil, fmt.Errorf(\"persistentVolumeClaim provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(persistentVolumeClaim)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := persistentVolumeClaim.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"persistentVolumeClaim.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1.PersistentVolumeClaim{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"persistentvolumeclaims\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":228,"to":256}} {"id":100026674,"name":"newPods","signature":"func newPods(c *CoreV1Client, namespace string) *pods","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/pod.go","code":"// newPods returns a Pods\nfunc newPods(c *CoreV1Client, namespace string) *pods {\n\treturn \u0026pods{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":66,"to":72}} {"id":100026675,"name":"Get","signature":"func (c *pods) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Pod, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/pod.go","code":"// Get takes name of the pod, and returns the corresponding pod object, and an error if there is any.\nfunc (c *pods) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Pod, err error) {\n\tresult = \u0026v1.Pod{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"pods\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":74,"to":85}} {"id":100026676,"name":"List","signature":"func (c *pods) List(ctx context.Context, opts metav1.ListOptions) (result *v1.PodList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/pod.go","code":"// List takes label and field selectors, and returns the list of Pods that match those selectors.\nfunc (c *pods) List(ctx context.Context, opts metav1.ListOptions) (result *v1.PodList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.PodList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"pods\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":87,"to":102}} {"id":100026677,"name":"Watch","signature":"func (c *pods) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/pod.go","code":"// Watch returns a watch.Interface that watches the requested pods.\nfunc (c *pods) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"pods\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":104,"to":117}} {"id":100026678,"name":"Create","signature":"func (c *pods) Create(ctx context.Context, pod *v1.Pod, opts metav1.CreateOptions) (result *v1.Pod, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/pod.go","code":"// Create takes the representation of a pod and creates it. Returns the server's representation of the pod, and an error, if there is any.\nfunc (c *pods) Create(ctx context.Context, pod *v1.Pod, opts metav1.CreateOptions) (result *v1.Pod, err error) {\n\tresult = \u0026v1.Pod{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"pods\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(pod).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":119,"to":130}} {"id":100026679,"name":"Update","signature":"func (c *pods) Update(ctx context.Context, pod *v1.Pod, opts metav1.UpdateOptions) (result *v1.Pod, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/pod.go","code":"// Update takes the representation of a pod and updates it. Returns the server's representation of the pod, and an error, if there is any.\nfunc (c *pods) Update(ctx context.Context, pod *v1.Pod, opts metav1.UpdateOptions) (result *v1.Pod, err error) {\n\tresult = \u0026v1.Pod{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"pods\").\n\t\tName(pod.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(pod).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":132,"to":144}} {"id":100026680,"name":"UpdateStatus","signature":"func (c *pods) UpdateStatus(ctx context.Context, pod *v1.Pod, opts metav1.UpdateOptions) (result *v1.Pod, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/pod.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *pods) UpdateStatus(ctx context.Context, pod *v1.Pod, opts metav1.UpdateOptions) (result *v1.Pod, err error) {\n\tresult = \u0026v1.Pod{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"pods\").\n\t\tName(pod.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(pod).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":146,"to":160}} {"id":100026681,"name":"Delete","signature":"func (c *pods) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/pod.go","code":"// Delete takes name of the pod and deletes it. Returns an error if one occurs.\nfunc (c *pods) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"pods\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":162,"to":171}} {"id":100026682,"name":"DeleteCollection","signature":"func (c *pods) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/pod.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *pods) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"pods\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":173,"to":187}} {"id":100026683,"name":"Patch","signature":"func (c *pods) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Pod, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/pod.go","code":"// Patch applies the patch and returns the patched pod.\nfunc (c *pods) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Pod, err error) {\n\tresult = \u0026v1.Pod{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"pods\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":189,"to":202}} {"id":100026684,"name":"Apply","signature":"func (c *pods) Apply(ctx context.Context, pod *corev1.PodApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Pod, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/pod.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied pod.\nfunc (c *pods) Apply(ctx context.Context, pod *corev1.PodApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Pod, err error) {\n\tif pod == nil {\n\t\treturn nil, fmt.Errorf(\"pod provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(pod)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := pod.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"pod.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.Pod{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"pods\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":204,"to":228}} {"id":100026685,"name":"ApplyStatus","signature":"func (c *pods) ApplyStatus(ctx context.Context, pod *corev1.PodApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Pod, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/pod.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *pods) ApplyStatus(ctx context.Context, pod *corev1.PodApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Pod, err error) {\n\tif pod == nil {\n\t\treturn nil, fmt.Errorf(\"pod provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(pod)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := pod.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"pod.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1.Pod{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"pods\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":230,"to":258}} {"id":100026686,"name":"UpdateEphemeralContainers","signature":"func (c *pods) UpdateEphemeralContainers(ctx context.Context, podName string, pod *v1.Pod, opts metav1.UpdateOptions) (result *v1.Pod, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/pod.go","code":"// UpdateEphemeralContainers takes the top resource name and the representation of a pod and updates it. Returns the server's representation of the pod, and an error, if there is any.\nfunc (c *pods) UpdateEphemeralContainers(ctx context.Context, podName string, pod *v1.Pod, opts metav1.UpdateOptions) (result *v1.Pod, err error) {\n\tresult = \u0026v1.Pod{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"pods\").\n\t\tName(podName).\n\t\tSubResource(\"ephemeralcontainers\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(pod).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":260,"to":273}} {"id":100026687,"name":"Bind","signature":"func (c *pods) Bind(ctx context.Context, binding *v1.Binding, opts metav1.CreateOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/pod_expansion.go","code":"// Bind applies the provided binding to the named pod in the current namespace (binding.Namespace is ignored).\nfunc (c *pods) Bind(ctx context.Context, binding *v1.Binding, opts metav1.CreateOptions) error {\n\treturn c.client.Post().Namespace(c.ns).Resource(\"pods\").Name(binding.Name).VersionedParams(\u0026opts, scheme.ParameterCodec).SubResource(\"binding\").Body(binding).Do(ctx).Error()\n}","line":{"from":48,"to":51}} {"id":100026688,"name":"Evict","signature":"func (c *pods) Evict(ctx context.Context, eviction *policyv1beta1.Eviction) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/pod_expansion.go","code":"// Evict submits a policy/v1beta1 Eviction request to the pod's eviction subresource.\n// Equivalent to calling EvictV1beta1.\n// Deprecated: Use EvictV1() (supported in 1.22+) or EvictV1beta1().\nfunc (c *pods) Evict(ctx context.Context, eviction *policyv1beta1.Eviction) error {\n\treturn c.client.Post().Namespace(c.ns).Resource(\"pods\").Name(eviction.Name).SubResource(\"eviction\").Body(eviction).Do(ctx).Error()\n}","line":{"from":53,"to":58}} {"id":100026689,"name":"EvictV1beta1","signature":"func (c *pods) EvictV1beta1(ctx context.Context, eviction *policyv1beta1.Eviction) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/pod_expansion.go","code":"func (c *pods) EvictV1beta1(ctx context.Context, eviction *policyv1beta1.Eviction) error {\n\treturn c.client.Post().Namespace(c.ns).Resource(\"pods\").Name(eviction.Name).SubResource(\"eviction\").Body(eviction).Do(ctx).Error()\n}","line":{"from":60,"to":62}} {"id":100026690,"name":"EvictV1","signature":"func (c *pods) EvictV1(ctx context.Context, eviction *policyv1.Eviction) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/pod_expansion.go","code":"func (c *pods) EvictV1(ctx context.Context, eviction *policyv1.Eviction) error {\n\treturn c.client.Post().Namespace(c.ns).Resource(\"pods\").Name(eviction.Name).SubResource(\"eviction\").Body(eviction).Do(ctx).Error()\n}","line":{"from":64,"to":66}} {"id":100026691,"name":"GetLogs","signature":"func (c *pods) GetLogs(name string, opts *v1.PodLogOptions) *restclient.Request","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/pod_expansion.go","code":"// Get constructs a request for getting the logs for a pod\nfunc (c *pods) GetLogs(name string, opts *v1.PodLogOptions) *restclient.Request {\n\treturn c.client.Get().Namespace(c.ns).Name(name).Resource(\"pods\").SubResource(\"log\").VersionedParams(opts, scheme.ParameterCodec)\n}","line":{"from":68,"to":71}} {"id":100026692,"name":"ProxyGet","signature":"func (c *pods) ProxyGet(scheme, name, port, path string, params map[string]string) restclient.ResponseWrapper","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/pod_expansion.go","code":"// ProxyGet returns a response of the pod by calling it through the proxy.\nfunc (c *pods) ProxyGet(scheme, name, port, path string, params map[string]string) restclient.ResponseWrapper {\n\trequest := c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"pods\").\n\t\tSubResource(\"proxy\").\n\t\tName(net.JoinSchemeNamePort(scheme, name, port)).\n\t\tSuffix(path)\n\tfor k, v := range params {\n\t\trequest = request.Param(k, v)\n\t}\n\treturn request\n}","line":{"from":73,"to":85}} {"id":100026693,"name":"newPodTemplates","signature":"func newPodTemplates(c *CoreV1Client, namespace string) *podTemplates","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/podtemplate.go","code":"// newPodTemplates returns a PodTemplates\nfunc newPodTemplates(c *CoreV1Client, namespace string) *podTemplates {\n\treturn \u0026podTemplates{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":62,"to":68}} {"id":100026694,"name":"Get","signature":"func (c *podTemplates) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.PodTemplate, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/podtemplate.go","code":"// Get takes name of the podTemplate, and returns the corresponding podTemplate object, and an error if there is any.\nfunc (c *podTemplates) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.PodTemplate, err error) {\n\tresult = \u0026v1.PodTemplate{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"podtemplates\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":81}} {"id":100026695,"name":"List","signature":"func (c *podTemplates) List(ctx context.Context, opts metav1.ListOptions) (result *v1.PodTemplateList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/podtemplate.go","code":"// List takes label and field selectors, and returns the list of PodTemplates that match those selectors.\nfunc (c *podTemplates) List(ctx context.Context, opts metav1.ListOptions) (result *v1.PodTemplateList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.PodTemplateList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"podtemplates\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":83,"to":98}} {"id":100026696,"name":"Watch","signature":"func (c *podTemplates) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/podtemplate.go","code":"// Watch returns a watch.Interface that watches the requested podTemplates.\nfunc (c *podTemplates) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"podtemplates\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":100,"to":113}} {"id":100026697,"name":"Create","signature":"func (c *podTemplates) Create(ctx context.Context, podTemplate *v1.PodTemplate, opts metav1.CreateOptions) (result *v1.PodTemplate, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/podtemplate.go","code":"// Create takes the representation of a podTemplate and creates it. Returns the server's representation of the podTemplate, and an error, if there is any.\nfunc (c *podTemplates) Create(ctx context.Context, podTemplate *v1.PodTemplate, opts metav1.CreateOptions) (result *v1.PodTemplate, err error) {\n\tresult = \u0026v1.PodTemplate{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"podtemplates\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(podTemplate).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":115,"to":126}} {"id":100026698,"name":"Update","signature":"func (c *podTemplates) Update(ctx context.Context, podTemplate *v1.PodTemplate, opts metav1.UpdateOptions) (result *v1.PodTemplate, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/podtemplate.go","code":"// Update takes the representation of a podTemplate and updates it. Returns the server's representation of the podTemplate, and an error, if there is any.\nfunc (c *podTemplates) Update(ctx context.Context, podTemplate *v1.PodTemplate, opts metav1.UpdateOptions) (result *v1.PodTemplate, err error) {\n\tresult = \u0026v1.PodTemplate{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"podtemplates\").\n\t\tName(podTemplate.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(podTemplate).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":128,"to":140}} {"id":100026699,"name":"Delete","signature":"func (c *podTemplates) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/podtemplate.go","code":"// Delete takes name of the podTemplate and deletes it. Returns an error if one occurs.\nfunc (c *podTemplates) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"podtemplates\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":142,"to":151}} {"id":100026700,"name":"DeleteCollection","signature":"func (c *podTemplates) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/podtemplate.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *podTemplates) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"podtemplates\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":153,"to":167}} {"id":100026701,"name":"Patch","signature":"func (c *podTemplates) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.PodTemplate, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/podtemplate.go","code":"// Patch applies the patch and returns the patched podTemplate.\nfunc (c *podTemplates) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.PodTemplate, err error) {\n\tresult = \u0026v1.PodTemplate{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"podtemplates\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":169,"to":182}} {"id":100026702,"name":"Apply","signature":"func (c *podTemplates) Apply(ctx context.Context, podTemplate *corev1.PodTemplateApplyConfiguration, opts metav1.ApplyOptions) (result *v1.PodTemplate, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/podtemplate.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied podTemplate.\nfunc (c *podTemplates) Apply(ctx context.Context, podTemplate *corev1.PodTemplateApplyConfiguration, opts metav1.ApplyOptions) (result *v1.PodTemplate, err error) {\n\tif podTemplate == nil {\n\t\treturn nil, fmt.Errorf(\"podTemplate provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(podTemplate)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := podTemplate.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"podTemplate.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.PodTemplate{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"podtemplates\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":184,"to":208}} {"id":100026703,"name":"newReplicationControllers","signature":"func newReplicationControllers(c *CoreV1Client, namespace string) *replicationControllers","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/replicationcontroller.go","code":"// newReplicationControllers returns a ReplicationControllers\nfunc newReplicationControllers(c *CoreV1Client, namespace string) *replicationControllers {\n\treturn \u0026replicationControllers{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":68,"to":74}} {"id":100026704,"name":"Get","signature":"func (c *replicationControllers) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ReplicationController, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/replicationcontroller.go","code":"// Get takes name of the replicationController, and returns the corresponding replicationController object, and an error if there is any.\nfunc (c *replicationControllers) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ReplicationController, err error) {\n\tresult = \u0026v1.ReplicationController{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicationcontrollers\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":76,"to":87}} {"id":100026705,"name":"List","signature":"func (c *replicationControllers) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ReplicationControllerList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/replicationcontroller.go","code":"// List takes label and field selectors, and returns the list of ReplicationControllers that match those selectors.\nfunc (c *replicationControllers) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ReplicationControllerList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.ReplicationControllerList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicationcontrollers\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":89,"to":104}} {"id":100026706,"name":"Watch","signature":"func (c *replicationControllers) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/replicationcontroller.go","code":"// Watch returns a watch.Interface that watches the requested replicationControllers.\nfunc (c *replicationControllers) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicationcontrollers\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":106,"to":119}} {"id":100026707,"name":"Create","signature":"func (c *replicationControllers) Create(ctx context.Context, replicationController *v1.ReplicationController, opts metav1.CreateOptions) (result *v1.ReplicationController, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/replicationcontroller.go","code":"// Create takes the representation of a replicationController and creates it. Returns the server's representation of the replicationController, and an error, if there is any.\nfunc (c *replicationControllers) Create(ctx context.Context, replicationController *v1.ReplicationController, opts metav1.CreateOptions) (result *v1.ReplicationController, err error) {\n\tresult = \u0026v1.ReplicationController{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicationcontrollers\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(replicationController).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":121,"to":132}} {"id":100026708,"name":"Update","signature":"func (c *replicationControllers) Update(ctx context.Context, replicationController *v1.ReplicationController, opts metav1.UpdateOptions) (result *v1.ReplicationController, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/replicationcontroller.go","code":"// Update takes the representation of a replicationController and updates it. Returns the server's representation of the replicationController, and an error, if there is any.\nfunc (c *replicationControllers) Update(ctx context.Context, replicationController *v1.ReplicationController, opts metav1.UpdateOptions) (result *v1.ReplicationController, err error) {\n\tresult = \u0026v1.ReplicationController{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicationcontrollers\").\n\t\tName(replicationController.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(replicationController).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":134,"to":146}} {"id":100026709,"name":"UpdateStatus","signature":"func (c *replicationControllers) UpdateStatus(ctx context.Context, replicationController *v1.ReplicationController, opts metav1.UpdateOptions) (result *v1.ReplicationController, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/replicationcontroller.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *replicationControllers) UpdateStatus(ctx context.Context, replicationController *v1.ReplicationController, opts metav1.UpdateOptions) (result *v1.ReplicationController, err error) {\n\tresult = \u0026v1.ReplicationController{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicationcontrollers\").\n\t\tName(replicationController.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(replicationController).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":148,"to":162}} {"id":100026710,"name":"Delete","signature":"func (c *replicationControllers) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/replicationcontroller.go","code":"// Delete takes name of the replicationController and deletes it. Returns an error if one occurs.\nfunc (c *replicationControllers) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicationcontrollers\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":164,"to":173}} {"id":100026711,"name":"DeleteCollection","signature":"func (c *replicationControllers) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/replicationcontroller.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *replicationControllers) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicationcontrollers\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":175,"to":189}} {"id":100026712,"name":"Patch","signature":"func (c *replicationControllers) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ReplicationController, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/replicationcontroller.go","code":"// Patch applies the patch and returns the patched replicationController.\nfunc (c *replicationControllers) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ReplicationController, err error) {\n\tresult = \u0026v1.ReplicationController{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"replicationcontrollers\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":191,"to":204}} {"id":100026713,"name":"Apply","signature":"func (c *replicationControllers) Apply(ctx context.Context, replicationController *corev1.ReplicationControllerApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ReplicationController, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/replicationcontroller.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied replicationController.\nfunc (c *replicationControllers) Apply(ctx context.Context, replicationController *corev1.ReplicationControllerApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ReplicationController, err error) {\n\tif replicationController == nil {\n\t\treturn nil, fmt.Errorf(\"replicationController provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(replicationController)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := replicationController.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"replicationController.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.ReplicationController{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"replicationcontrollers\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":206,"to":230}} {"id":100026714,"name":"ApplyStatus","signature":"func (c *replicationControllers) ApplyStatus(ctx context.Context, replicationController *corev1.ReplicationControllerApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ReplicationController, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/replicationcontroller.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *replicationControllers) ApplyStatus(ctx context.Context, replicationController *corev1.ReplicationControllerApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ReplicationController, err error) {\n\tif replicationController == nil {\n\t\treturn nil, fmt.Errorf(\"replicationController provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(replicationController)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := replicationController.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"replicationController.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1.ReplicationController{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"replicationcontrollers\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":232,"to":260}} {"id":100026715,"name":"GetScale","signature":"func (c *replicationControllers) GetScale(ctx context.Context, replicationControllerName string, options metav1.GetOptions) (result *autoscalingv1.Scale, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/replicationcontroller.go","code":"// GetScale takes name of the replicationController, and returns the corresponding autoscalingv1.Scale object, and an error if there is any.\nfunc (c *replicationControllers) GetScale(ctx context.Context, replicationControllerName string, options metav1.GetOptions) (result *autoscalingv1.Scale, err error) {\n\tresult = \u0026autoscalingv1.Scale{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicationcontrollers\").\n\t\tName(replicationControllerName).\n\t\tSubResource(\"scale\").\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":262,"to":274}} {"id":100026716,"name":"UpdateScale","signature":"func (c *replicationControllers) UpdateScale(ctx context.Context, replicationControllerName string, scale *autoscalingv1.Scale, opts metav1.UpdateOptions) (result *autoscalingv1.Scale, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/replicationcontroller.go","code":"// UpdateScale takes the top resource name and the representation of a scale and updates it. Returns the server's representation of the scale, and an error, if there is any.\nfunc (c *replicationControllers) UpdateScale(ctx context.Context, replicationControllerName string, scale *autoscalingv1.Scale, opts metav1.UpdateOptions) (result *autoscalingv1.Scale, err error) {\n\tresult = \u0026autoscalingv1.Scale{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicationcontrollers\").\n\t\tName(replicationControllerName).\n\t\tSubResource(\"scale\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(scale).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":276,"to":289}} {"id":100026717,"name":"newResourceQuotas","signature":"func newResourceQuotas(c *CoreV1Client, namespace string) *resourceQuotas","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/resourcequota.go","code":"// newResourceQuotas returns a ResourceQuotas\nfunc newResourceQuotas(c *CoreV1Client, namespace string) *resourceQuotas {\n\treturn \u0026resourceQuotas{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":64,"to":70}} {"id":100026718,"name":"Get","signature":"func (c *resourceQuotas) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ResourceQuota, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/resourcequota.go","code":"// Get takes name of the resourceQuota, and returns the corresponding resourceQuota object, and an error if there is any.\nfunc (c *resourceQuotas) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ResourceQuota, err error) {\n\tresult = \u0026v1.ResourceQuota{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"resourcequotas\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":72,"to":83}} {"id":100026719,"name":"List","signature":"func (c *resourceQuotas) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ResourceQuotaList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/resourcequota.go","code":"// List takes label and field selectors, and returns the list of ResourceQuotas that match those selectors.\nfunc (c *resourceQuotas) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ResourceQuotaList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.ResourceQuotaList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"resourcequotas\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":85,"to":100}} {"id":100026720,"name":"Watch","signature":"func (c *resourceQuotas) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/resourcequota.go","code":"// Watch returns a watch.Interface that watches the requested resourceQuotas.\nfunc (c *resourceQuotas) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"resourcequotas\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":102,"to":115}} {"id":100026721,"name":"Create","signature":"func (c *resourceQuotas) Create(ctx context.Context, resourceQuota *v1.ResourceQuota, opts metav1.CreateOptions) (result *v1.ResourceQuota, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/resourcequota.go","code":"// Create takes the representation of a resourceQuota and creates it. Returns the server's representation of the resourceQuota, and an error, if there is any.\nfunc (c *resourceQuotas) Create(ctx context.Context, resourceQuota *v1.ResourceQuota, opts metav1.CreateOptions) (result *v1.ResourceQuota, err error) {\n\tresult = \u0026v1.ResourceQuota{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"resourcequotas\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(resourceQuota).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":117,"to":128}} {"id":100026722,"name":"Update","signature":"func (c *resourceQuotas) Update(ctx context.Context, resourceQuota *v1.ResourceQuota, opts metav1.UpdateOptions) (result *v1.ResourceQuota, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/resourcequota.go","code":"// Update takes the representation of a resourceQuota and updates it. Returns the server's representation of the resourceQuota, and an error, if there is any.\nfunc (c *resourceQuotas) Update(ctx context.Context, resourceQuota *v1.ResourceQuota, opts metav1.UpdateOptions) (result *v1.ResourceQuota, err error) {\n\tresult = \u0026v1.ResourceQuota{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"resourcequotas\").\n\t\tName(resourceQuota.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(resourceQuota).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":130,"to":142}} {"id":100026723,"name":"UpdateStatus","signature":"func (c *resourceQuotas) UpdateStatus(ctx context.Context, resourceQuota *v1.ResourceQuota, opts metav1.UpdateOptions) (result *v1.ResourceQuota, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/resourcequota.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *resourceQuotas) UpdateStatus(ctx context.Context, resourceQuota *v1.ResourceQuota, opts metav1.UpdateOptions) (result *v1.ResourceQuota, err error) {\n\tresult = \u0026v1.ResourceQuota{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"resourcequotas\").\n\t\tName(resourceQuota.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(resourceQuota).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":144,"to":158}} {"id":100026724,"name":"Delete","signature":"func (c *resourceQuotas) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/resourcequota.go","code":"// Delete takes name of the resourceQuota and deletes it. Returns an error if one occurs.\nfunc (c *resourceQuotas) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"resourcequotas\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":160,"to":169}} {"id":100026725,"name":"DeleteCollection","signature":"func (c *resourceQuotas) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/resourcequota.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *resourceQuotas) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"resourcequotas\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":171,"to":185}} {"id":100026726,"name":"Patch","signature":"func (c *resourceQuotas) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ResourceQuota, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/resourcequota.go","code":"// Patch applies the patch and returns the patched resourceQuota.\nfunc (c *resourceQuotas) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ResourceQuota, err error) {\n\tresult = \u0026v1.ResourceQuota{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"resourcequotas\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":187,"to":200}} {"id":100026727,"name":"Apply","signature":"func (c *resourceQuotas) Apply(ctx context.Context, resourceQuota *corev1.ResourceQuotaApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ResourceQuota, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/resourcequota.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied resourceQuota.\nfunc (c *resourceQuotas) Apply(ctx context.Context, resourceQuota *corev1.ResourceQuotaApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ResourceQuota, err error) {\n\tif resourceQuota == nil {\n\t\treturn nil, fmt.Errorf(\"resourceQuota provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(resourceQuota)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := resourceQuota.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"resourceQuota.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.ResourceQuota{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"resourcequotas\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":202,"to":226}} {"id":100026728,"name":"ApplyStatus","signature":"func (c *resourceQuotas) ApplyStatus(ctx context.Context, resourceQuota *corev1.ResourceQuotaApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ResourceQuota, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/resourcequota.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *resourceQuotas) ApplyStatus(ctx context.Context, resourceQuota *corev1.ResourceQuotaApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ResourceQuota, err error) {\n\tif resourceQuota == nil {\n\t\treturn nil, fmt.Errorf(\"resourceQuota provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(resourceQuota)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := resourceQuota.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"resourceQuota.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1.ResourceQuota{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"resourcequotas\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":228,"to":256}} {"id":100026729,"name":"newSecrets","signature":"func newSecrets(c *CoreV1Client, namespace string) *secrets","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/secret.go","code":"// newSecrets returns a Secrets\nfunc newSecrets(c *CoreV1Client, namespace string) *secrets {\n\treturn \u0026secrets{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":62,"to":68}} {"id":100026730,"name":"Get","signature":"func (c *secrets) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Secret, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/secret.go","code":"// Get takes name of the secret, and returns the corresponding secret object, and an error if there is any.\nfunc (c *secrets) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Secret, err error) {\n\tresult = \u0026v1.Secret{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"secrets\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":81}} {"id":100026731,"name":"List","signature":"func (c *secrets) List(ctx context.Context, opts metav1.ListOptions) (result *v1.SecretList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/secret.go","code":"// List takes label and field selectors, and returns the list of Secrets that match those selectors.\nfunc (c *secrets) List(ctx context.Context, opts metav1.ListOptions) (result *v1.SecretList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.SecretList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"secrets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":83,"to":98}} {"id":100026732,"name":"Watch","signature":"func (c *secrets) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/secret.go","code":"// Watch returns a watch.Interface that watches the requested secrets.\nfunc (c *secrets) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"secrets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":100,"to":113}} {"id":100026733,"name":"Create","signature":"func (c *secrets) Create(ctx context.Context, secret *v1.Secret, opts metav1.CreateOptions) (result *v1.Secret, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/secret.go","code":"// Create takes the representation of a secret and creates it. Returns the server's representation of the secret, and an error, if there is any.\nfunc (c *secrets) Create(ctx context.Context, secret *v1.Secret, opts metav1.CreateOptions) (result *v1.Secret, err error) {\n\tresult = \u0026v1.Secret{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"secrets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(secret).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":115,"to":126}} {"id":100026734,"name":"Update","signature":"func (c *secrets) Update(ctx context.Context, secret *v1.Secret, opts metav1.UpdateOptions) (result *v1.Secret, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/secret.go","code":"// Update takes the representation of a secret and updates it. Returns the server's representation of the secret, and an error, if there is any.\nfunc (c *secrets) Update(ctx context.Context, secret *v1.Secret, opts metav1.UpdateOptions) (result *v1.Secret, err error) {\n\tresult = \u0026v1.Secret{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"secrets\").\n\t\tName(secret.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(secret).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":128,"to":140}} {"id":100026735,"name":"Delete","signature":"func (c *secrets) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/secret.go","code":"// Delete takes name of the secret and deletes it. Returns an error if one occurs.\nfunc (c *secrets) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"secrets\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":142,"to":151}} {"id":100026736,"name":"DeleteCollection","signature":"func (c *secrets) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/secret.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *secrets) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"secrets\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":153,"to":167}} {"id":100026737,"name":"Patch","signature":"func (c *secrets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Secret, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/secret.go","code":"// Patch applies the patch and returns the patched secret.\nfunc (c *secrets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Secret, err error) {\n\tresult = \u0026v1.Secret{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"secrets\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":169,"to":182}} {"id":100026738,"name":"Apply","signature":"func (c *secrets) Apply(ctx context.Context, secret *corev1.SecretApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Secret, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/secret.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied secret.\nfunc (c *secrets) Apply(ctx context.Context, secret *corev1.SecretApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Secret, err error) {\n\tif secret == nil {\n\t\treturn nil, fmt.Errorf(\"secret provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(secret)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := secret.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"secret.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.Secret{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"secrets\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":184,"to":208}} {"id":100026739,"name":"newServices","signature":"func newServices(c *CoreV1Client, namespace string) *services","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/service.go","code":"// newServices returns a Services\nfunc newServices(c *CoreV1Client, namespace string) *services {\n\treturn \u0026services{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":63,"to":69}} {"id":100026740,"name":"Get","signature":"func (c *services) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Service, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/service.go","code":"// Get takes name of the service, and returns the corresponding service object, and an error if there is any.\nfunc (c *services) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Service, err error) {\n\tresult = \u0026v1.Service{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"services\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":71,"to":82}} {"id":100026741,"name":"List","signature":"func (c *services) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ServiceList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/service.go","code":"// List takes label and field selectors, and returns the list of Services that match those selectors.\nfunc (c *services) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ServiceList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.ServiceList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"services\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":84,"to":99}} {"id":100026742,"name":"Watch","signature":"func (c *services) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/service.go","code":"// Watch returns a watch.Interface that watches the requested services.\nfunc (c *services) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"services\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":101,"to":114}} {"id":100026743,"name":"Create","signature":"func (c *services) Create(ctx context.Context, service *v1.Service, opts metav1.CreateOptions) (result *v1.Service, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/service.go","code":"// 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.\nfunc (c *services) Create(ctx context.Context, service *v1.Service, opts metav1.CreateOptions) (result *v1.Service, err error) {\n\tresult = \u0026v1.Service{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"services\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(service).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":116,"to":127}} {"id":100026744,"name":"Update","signature":"func (c *services) Update(ctx context.Context, service *v1.Service, opts metav1.UpdateOptions) (result *v1.Service, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/service.go","code":"// 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.\nfunc (c *services) Update(ctx context.Context, service *v1.Service, opts metav1.UpdateOptions) (result *v1.Service, err error) {\n\tresult = \u0026v1.Service{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"services\").\n\t\tName(service.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(service).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":129,"to":141}} {"id":100026745,"name":"UpdateStatus","signature":"func (c *services) UpdateStatus(ctx context.Context, service *v1.Service, opts metav1.UpdateOptions) (result *v1.Service, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/service.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *services) UpdateStatus(ctx context.Context, service *v1.Service, opts metav1.UpdateOptions) (result *v1.Service, err error) {\n\tresult = \u0026v1.Service{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"services\").\n\t\tName(service.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(service).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":143,"to":157}} {"id":100026746,"name":"Delete","signature":"func (c *services) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/service.go","code":"// Delete takes name of the service and deletes it. Returns an error if one occurs.\nfunc (c *services) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"services\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":159,"to":168}} {"id":100026747,"name":"Patch","signature":"func (c *services) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Service, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/service.go","code":"// Patch applies the patch and returns the patched service.\nfunc (c *services) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Service, err error) {\n\tresult = \u0026v1.Service{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"services\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":170,"to":183}} {"id":100026748,"name":"Apply","signature":"func (c *services) Apply(ctx context.Context, service *corev1.ServiceApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Service, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/service.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied service.\nfunc (c *services) Apply(ctx context.Context, service *corev1.ServiceApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Service, err error) {\n\tif service == nil {\n\t\treturn nil, fmt.Errorf(\"service provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(service)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := service.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"service.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.Service{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"services\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":185,"to":209}} {"id":100026749,"name":"ApplyStatus","signature":"func (c *services) ApplyStatus(ctx context.Context, service *corev1.ServiceApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Service, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/service.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *services) ApplyStatus(ctx context.Context, service *corev1.ServiceApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Service, err error) {\n\tif service == nil {\n\t\treturn nil, fmt.Errorf(\"service provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(service)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := service.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"service.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1.Service{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"services\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":211,"to":239}} {"id":100026750,"name":"ProxyGet","signature":"func (c *services) ProxyGet(scheme, name, port, path string, params map[string]string) restclient.ResponseWrapper","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/service_expansion.go","code":"// ProxyGet returns a response of the service by calling it through the proxy.\nfunc (c *services) ProxyGet(scheme, name, port, path string, params map[string]string) restclient.ResponseWrapper {\n\trequest := c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"services\").\n\t\tSubResource(\"proxy\").\n\t\tName(net.JoinSchemeNamePort(scheme, name, port)).\n\t\tSuffix(path)\n\tfor k, v := range params {\n\t\trequest = request.Param(k, v)\n\t}\n\treturn request\n}","line":{"from":29,"to":41}} {"id":100026751,"name":"newServiceAccounts","signature":"func newServiceAccounts(c *CoreV1Client, namespace string) *serviceAccounts","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/serviceaccount.go","code":"// newServiceAccounts returns a ServiceAccounts\nfunc newServiceAccounts(c *CoreV1Client, namespace string) *serviceAccounts {\n\treturn \u0026serviceAccounts{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":65,"to":71}} {"id":100026752,"name":"Get","signature":"func (c *serviceAccounts) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ServiceAccount, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/serviceaccount.go","code":"// Get takes name of the serviceAccount, and returns the corresponding serviceAccount object, and an error if there is any.\nfunc (c *serviceAccounts) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ServiceAccount, err error) {\n\tresult = \u0026v1.ServiceAccount{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"serviceaccounts\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":73,"to":84}} {"id":100026753,"name":"List","signature":"func (c *serviceAccounts) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ServiceAccountList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/serviceaccount.go","code":"// List takes label and field selectors, and returns the list of ServiceAccounts that match those selectors.\nfunc (c *serviceAccounts) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ServiceAccountList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.ServiceAccountList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"serviceaccounts\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":86,"to":101}} {"id":100026754,"name":"Watch","signature":"func (c *serviceAccounts) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/serviceaccount.go","code":"// Watch returns a watch.Interface that watches the requested serviceAccounts.\nfunc (c *serviceAccounts) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"serviceaccounts\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":103,"to":116}} {"id":100026755,"name":"Create","signature":"func (c *serviceAccounts) Create(ctx context.Context, serviceAccount *v1.ServiceAccount, opts metav1.CreateOptions) (result *v1.ServiceAccount, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/serviceaccount.go","code":"// Create takes the representation of a serviceAccount and creates it. Returns the server's representation of the serviceAccount, and an error, if there is any.\nfunc (c *serviceAccounts) Create(ctx context.Context, serviceAccount *v1.ServiceAccount, opts metav1.CreateOptions) (result *v1.ServiceAccount, err error) {\n\tresult = \u0026v1.ServiceAccount{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"serviceaccounts\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(serviceAccount).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":118,"to":129}} {"id":100026756,"name":"Update","signature":"func (c *serviceAccounts) Update(ctx context.Context, serviceAccount *v1.ServiceAccount, opts metav1.UpdateOptions) (result *v1.ServiceAccount, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/serviceaccount.go","code":"// Update takes the representation of a serviceAccount and updates it. Returns the server's representation of the serviceAccount, and an error, if there is any.\nfunc (c *serviceAccounts) Update(ctx context.Context, serviceAccount *v1.ServiceAccount, opts metav1.UpdateOptions) (result *v1.ServiceAccount, err error) {\n\tresult = \u0026v1.ServiceAccount{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"serviceaccounts\").\n\t\tName(serviceAccount.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(serviceAccount).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":131,"to":143}} {"id":100026757,"name":"Delete","signature":"func (c *serviceAccounts) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/serviceaccount.go","code":"// Delete takes name of the serviceAccount and deletes it. Returns an error if one occurs.\nfunc (c *serviceAccounts) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"serviceaccounts\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":154}} {"id":100026758,"name":"DeleteCollection","signature":"func (c *serviceAccounts) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/serviceaccount.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *serviceAccounts) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"serviceaccounts\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":156,"to":170}} {"id":100026759,"name":"Patch","signature":"func (c *serviceAccounts) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ServiceAccount, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/serviceaccount.go","code":"// Patch applies the patch and returns the patched serviceAccount.\nfunc (c *serviceAccounts) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ServiceAccount, err error) {\n\tresult = \u0026v1.ServiceAccount{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"serviceaccounts\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":172,"to":185}} {"id":100026760,"name":"Apply","signature":"func (c *serviceAccounts) Apply(ctx context.Context, serviceAccount *corev1.ServiceAccountApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ServiceAccount, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/serviceaccount.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied serviceAccount.\nfunc (c *serviceAccounts) Apply(ctx context.Context, serviceAccount *corev1.ServiceAccountApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ServiceAccount, err error) {\n\tif serviceAccount == nil {\n\t\treturn nil, fmt.Errorf(\"serviceAccount provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(serviceAccount)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := serviceAccount.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"serviceAccount.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.ServiceAccount{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"serviceaccounts\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":187,"to":211}} {"id":100026761,"name":"CreateToken","signature":"func (c *serviceAccounts) CreateToken(ctx context.Context, serviceAccountName string, tokenRequest *authenticationv1.TokenRequest, opts metav1.CreateOptions) (result *authenticationv1.TokenRequest, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/core/v1/serviceaccount.go","code":"// CreateToken takes the representation of a tokenRequest and creates it. Returns the server's representation of the tokenRequest, and an error, if there is any.\nfunc (c *serviceAccounts) CreateToken(ctx context.Context, serviceAccountName string, tokenRequest *authenticationv1.TokenRequest, opts metav1.CreateOptions) (result *authenticationv1.TokenRequest, err error) {\n\tresult = \u0026authenticationv1.TokenRequest{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"serviceaccounts\").\n\t\tName(serviceAccountName).\n\t\tSubResource(\"token\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(tokenRequest).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":213,"to":226}} {"id":100026762,"name":"EndpointSlices","signature":"func (c *DiscoveryV1Client) EndpointSlices(namespace string) EndpointSliceInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1/discovery_client.go","code":"func (c *DiscoveryV1Client) EndpointSlices(namespace string) EndpointSliceInterface {\n\treturn newEndpointSlices(c, namespace)\n}","line":{"from":39,"to":41}} {"id":100026763,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*DiscoveryV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1/discovery_client.go","code":"// NewForConfig creates a new DiscoveryV1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*DiscoveryV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":43,"to":56}} {"id":100026764,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*DiscoveryV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1/discovery_client.go","code":"// NewForConfigAndClient creates a new DiscoveryV1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*DiscoveryV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026DiscoveryV1Client{client}, nil\n}","line":{"from":58,"to":70}} {"id":100026765,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *DiscoveryV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1/discovery_client.go","code":"// NewForConfigOrDie creates a new DiscoveryV1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *DiscoveryV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":72,"to":80}} {"id":100026766,"name":"New","signature":"func New(c rest.Interface) *DiscoveryV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1/discovery_client.go","code":"// New creates a new DiscoveryV1Client for the given RESTClient.\nfunc New(c rest.Interface) *DiscoveryV1Client {\n\treturn \u0026DiscoveryV1Client{c}\n}","line":{"from":82,"to":85}} {"id":100026767,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1/discovery_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":87,"to":98}} {"id":100026768,"name":"RESTClient","signature":"func (c *DiscoveryV1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1/discovery_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *DiscoveryV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":100,"to":107}} {"id":100026769,"name":"newEndpointSlices","signature":"func newEndpointSlices(c *DiscoveryV1Client, namespace string) *endpointSlices","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1/endpointslice.go","code":"// newEndpointSlices returns a EndpointSlices\nfunc newEndpointSlices(c *DiscoveryV1Client, namespace string) *endpointSlices {\n\treturn \u0026endpointSlices{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":62,"to":68}} {"id":100026770,"name":"Get","signature":"func (c *endpointSlices) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.EndpointSlice, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1/endpointslice.go","code":"// Get takes name of the endpointSlice, and returns the corresponding endpointSlice object, and an error if there is any.\nfunc (c *endpointSlices) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.EndpointSlice, err error) {\n\tresult = \u0026v1.EndpointSlice{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"endpointslices\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":81}} {"id":100026771,"name":"List","signature":"func (c *endpointSlices) List(ctx context.Context, opts metav1.ListOptions) (result *v1.EndpointSliceList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1/endpointslice.go","code":"// List takes label and field selectors, and returns the list of EndpointSlices that match those selectors.\nfunc (c *endpointSlices) List(ctx context.Context, opts metav1.ListOptions) (result *v1.EndpointSliceList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.EndpointSliceList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"endpointslices\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":83,"to":98}} {"id":100026772,"name":"Watch","signature":"func (c *endpointSlices) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1/endpointslice.go","code":"// Watch returns a watch.Interface that watches the requested endpointSlices.\nfunc (c *endpointSlices) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"endpointslices\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":100,"to":113}} {"id":100026773,"name":"Create","signature":"func (c *endpointSlices) Create(ctx context.Context, endpointSlice *v1.EndpointSlice, opts metav1.CreateOptions) (result *v1.EndpointSlice, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1/endpointslice.go","code":"// Create takes the representation of a endpointSlice and creates it. Returns the server's representation of the endpointSlice, and an error, if there is any.\nfunc (c *endpointSlices) Create(ctx context.Context, endpointSlice *v1.EndpointSlice, opts metav1.CreateOptions) (result *v1.EndpointSlice, err error) {\n\tresult = \u0026v1.EndpointSlice{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"endpointslices\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(endpointSlice).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":115,"to":126}} {"id":100026774,"name":"Update","signature":"func (c *endpointSlices) Update(ctx context.Context, endpointSlice *v1.EndpointSlice, opts metav1.UpdateOptions) (result *v1.EndpointSlice, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1/endpointslice.go","code":"// Update takes the representation of a endpointSlice and updates it. Returns the server's representation of the endpointSlice, and an error, if there is any.\nfunc (c *endpointSlices) Update(ctx context.Context, endpointSlice *v1.EndpointSlice, opts metav1.UpdateOptions) (result *v1.EndpointSlice, err error) {\n\tresult = \u0026v1.EndpointSlice{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"endpointslices\").\n\t\tName(endpointSlice.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(endpointSlice).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":128,"to":140}} {"id":100026775,"name":"Delete","signature":"func (c *endpointSlices) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1/endpointslice.go","code":"// Delete takes name of the endpointSlice and deletes it. Returns an error if one occurs.\nfunc (c *endpointSlices) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"endpointslices\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":142,"to":151}} {"id":100026776,"name":"DeleteCollection","signature":"func (c *endpointSlices) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1/endpointslice.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *endpointSlices) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"endpointslices\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":153,"to":167}} {"id":100026777,"name":"Patch","signature":"func (c *endpointSlices) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.EndpointSlice, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1/endpointslice.go","code":"// Patch applies the patch and returns the patched endpointSlice.\nfunc (c *endpointSlices) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.EndpointSlice, err error) {\n\tresult = \u0026v1.EndpointSlice{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"endpointslices\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":169,"to":182}} {"id":100026778,"name":"Apply","signature":"func (c *endpointSlices) Apply(ctx context.Context, endpointSlice *discoveryv1.EndpointSliceApplyConfiguration, opts metav1.ApplyOptions) (result *v1.EndpointSlice, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1/endpointslice.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied endpointSlice.\nfunc (c *endpointSlices) Apply(ctx context.Context, endpointSlice *discoveryv1.EndpointSliceApplyConfiguration, opts metav1.ApplyOptions) (result *v1.EndpointSlice, err error) {\n\tif endpointSlice == nil {\n\t\treturn nil, fmt.Errorf(\"endpointSlice provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(endpointSlice)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := endpointSlice.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"endpointSlice.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.EndpointSlice{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"endpointslices\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":184,"to":208}} {"id":100026779,"name":"EndpointSlices","signature":"func (c *DiscoveryV1beta1Client) EndpointSlices(namespace string) EndpointSliceInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1beta1/discovery_client.go","code":"func (c *DiscoveryV1beta1Client) EndpointSlices(namespace string) EndpointSliceInterface {\n\treturn newEndpointSlices(c, namespace)\n}","line":{"from":39,"to":41}} {"id":100026780,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*DiscoveryV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1beta1/discovery_client.go","code":"// NewForConfig creates a new DiscoveryV1beta1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*DiscoveryV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":43,"to":56}} {"id":100026781,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*DiscoveryV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1beta1/discovery_client.go","code":"// NewForConfigAndClient creates a new DiscoveryV1beta1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*DiscoveryV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026DiscoveryV1beta1Client{client}, nil\n}","line":{"from":58,"to":70}} {"id":100026782,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *DiscoveryV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1beta1/discovery_client.go","code":"// NewForConfigOrDie creates a new DiscoveryV1beta1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *DiscoveryV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":72,"to":80}} {"id":100026783,"name":"New","signature":"func New(c rest.Interface) *DiscoveryV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1beta1/discovery_client.go","code":"// New creates a new DiscoveryV1beta1Client for the given RESTClient.\nfunc New(c rest.Interface) *DiscoveryV1beta1Client {\n\treturn \u0026DiscoveryV1beta1Client{c}\n}","line":{"from":82,"to":85}} {"id":100026784,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1beta1/discovery_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":87,"to":98}} {"id":100026785,"name":"RESTClient","signature":"func (c *DiscoveryV1beta1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1beta1/discovery_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *DiscoveryV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":100,"to":107}} {"id":100026786,"name":"newEndpointSlices","signature":"func newEndpointSlices(c *DiscoveryV1beta1Client, namespace string) *endpointSlices","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1beta1/endpointslice.go","code":"// newEndpointSlices returns a EndpointSlices\nfunc newEndpointSlices(c *DiscoveryV1beta1Client, namespace string) *endpointSlices {\n\treturn \u0026endpointSlices{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":62,"to":68}} {"id":100026787,"name":"Get","signature":"func (c *endpointSlices) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.EndpointSlice, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1beta1/endpointslice.go","code":"// Get takes name of the endpointSlice, and returns the corresponding endpointSlice object, and an error if there is any.\nfunc (c *endpointSlices) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.EndpointSlice, err error) {\n\tresult = \u0026v1beta1.EndpointSlice{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"endpointslices\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":81}} {"id":100026788,"name":"List","signature":"func (c *endpointSlices) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.EndpointSliceList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1beta1/endpointslice.go","code":"// List takes label and field selectors, and returns the list of EndpointSlices that match those selectors.\nfunc (c *endpointSlices) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.EndpointSliceList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.EndpointSliceList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"endpointslices\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":83,"to":98}} {"id":100026789,"name":"Watch","signature":"func (c *endpointSlices) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1beta1/endpointslice.go","code":"// Watch returns a watch.Interface that watches the requested endpointSlices.\nfunc (c *endpointSlices) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"endpointslices\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":100,"to":113}} {"id":100026790,"name":"Create","signature":"func (c *endpointSlices) Create(ctx context.Context, endpointSlice *v1beta1.EndpointSlice, opts v1.CreateOptions) (result *v1beta1.EndpointSlice, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1beta1/endpointslice.go","code":"// Create takes the representation of a endpointSlice and creates it. Returns the server's representation of the endpointSlice, and an error, if there is any.\nfunc (c *endpointSlices) Create(ctx context.Context, endpointSlice *v1beta1.EndpointSlice, opts v1.CreateOptions) (result *v1beta1.EndpointSlice, err error) {\n\tresult = \u0026v1beta1.EndpointSlice{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"endpointslices\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(endpointSlice).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":115,"to":126}} {"id":100026791,"name":"Update","signature":"func (c *endpointSlices) Update(ctx context.Context, endpointSlice *v1beta1.EndpointSlice, opts v1.UpdateOptions) (result *v1beta1.EndpointSlice, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1beta1/endpointslice.go","code":"// Update takes the representation of a endpointSlice and updates it. Returns the server's representation of the endpointSlice, and an error, if there is any.\nfunc (c *endpointSlices) Update(ctx context.Context, endpointSlice *v1beta1.EndpointSlice, opts v1.UpdateOptions) (result *v1beta1.EndpointSlice, err error) {\n\tresult = \u0026v1beta1.EndpointSlice{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"endpointslices\").\n\t\tName(endpointSlice.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(endpointSlice).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":128,"to":140}} {"id":100026792,"name":"Delete","signature":"func (c *endpointSlices) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1beta1/endpointslice.go","code":"// Delete takes name of the endpointSlice and deletes it. Returns an error if one occurs.\nfunc (c *endpointSlices) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"endpointslices\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":142,"to":151}} {"id":100026793,"name":"DeleteCollection","signature":"func (c *endpointSlices) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1beta1/endpointslice.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *endpointSlices) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"endpointslices\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":153,"to":167}} {"id":100026794,"name":"Patch","signature":"func (c *endpointSlices) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.EndpointSlice, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1beta1/endpointslice.go","code":"// Patch applies the patch and returns the patched endpointSlice.\nfunc (c *endpointSlices) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.EndpointSlice, err error) {\n\tresult = \u0026v1beta1.EndpointSlice{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"endpointslices\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":169,"to":182}} {"id":100026795,"name":"Apply","signature":"func (c *endpointSlices) Apply(ctx context.Context, endpointSlice *discoveryv1beta1.EndpointSliceApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.EndpointSlice, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/discovery/v1beta1/endpointslice.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied endpointSlice.\nfunc (c *endpointSlices) Apply(ctx context.Context, endpointSlice *discoveryv1beta1.EndpointSliceApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.EndpointSlice, err error) {\n\tif endpointSlice == nil {\n\t\treturn nil, fmt.Errorf(\"endpointSlice provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(endpointSlice)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := endpointSlice.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"endpointSlice.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.EndpointSlice{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"endpointslices\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":184,"to":208}} {"id":100026796,"name":"newEvents","signature":"func newEvents(c *EventsV1Client, namespace string) *events","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1/event.go","code":"// newEvents returns a Events\nfunc newEvents(c *EventsV1Client, namespace string) *events {\n\treturn \u0026events{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":62,"to":68}} {"id":100026797,"name":"Get","signature":"func (c *events) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Event, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1/event.go","code":"// Get takes name of the event, and returns the corresponding event object, and an error if there is any.\nfunc (c *events) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Event, err error) {\n\tresult = \u0026v1.Event{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":81}} {"id":100026798,"name":"List","signature":"func (c *events) List(ctx context.Context, opts metav1.ListOptions) (result *v1.EventList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1/event.go","code":"// List takes label and field selectors, and returns the list of Events that match those selectors.\nfunc (c *events) List(ctx context.Context, opts metav1.ListOptions) (result *v1.EventList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.EventList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":83,"to":98}} {"id":100026799,"name":"Watch","signature":"func (c *events) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1/event.go","code":"// Watch returns a watch.Interface that watches the requested events.\nfunc (c *events) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":100,"to":113}} {"id":100026800,"name":"Create","signature":"func (c *events) Create(ctx context.Context, event *v1.Event, opts metav1.CreateOptions) (result *v1.Event, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1/event.go","code":"// Create takes the representation of a event and creates it. Returns the server's representation of the event, and an error, if there is any.\nfunc (c *events) Create(ctx context.Context, event *v1.Event, opts metav1.CreateOptions) (result *v1.Event, err error) {\n\tresult = \u0026v1.Event{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(event).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":115,"to":126}} {"id":100026801,"name":"Update","signature":"func (c *events) Update(ctx context.Context, event *v1.Event, opts metav1.UpdateOptions) (result *v1.Event, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1/event.go","code":"// Update takes the representation of a event and updates it. Returns the server's representation of the event, and an error, if there is any.\nfunc (c *events) Update(ctx context.Context, event *v1.Event, opts metav1.UpdateOptions) (result *v1.Event, err error) {\n\tresult = \u0026v1.Event{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tName(event.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(event).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":128,"to":140}} {"id":100026802,"name":"Delete","signature":"func (c *events) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1/event.go","code":"// Delete takes name of the event and deletes it. Returns an error if one occurs.\nfunc (c *events) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":142,"to":151}} {"id":100026803,"name":"DeleteCollection","signature":"func (c *events) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1/event.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *events) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":153,"to":167}} {"id":100026804,"name":"Patch","signature":"func (c *events) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Event, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1/event.go","code":"// Patch applies the patch and returns the patched event.\nfunc (c *events) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Event, err error) {\n\tresult = \u0026v1.Event{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":169,"to":182}} {"id":100026805,"name":"Apply","signature":"func (c *events) Apply(ctx context.Context, event *eventsv1.EventApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Event, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1/event.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied event.\nfunc (c *events) Apply(ctx context.Context, event *eventsv1.EventApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Event, err error) {\n\tif event == nil {\n\t\treturn nil, fmt.Errorf(\"event provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(event)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := event.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"event.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.Event{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":184,"to":208}} {"id":100026806,"name":"Events","signature":"func (c *EventsV1Client) Events(namespace string) EventInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1/events_client.go","code":"func (c *EventsV1Client) Events(namespace string) EventInterface {\n\treturn newEvents(c, namespace)\n}","line":{"from":39,"to":41}} {"id":100026807,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*EventsV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1/events_client.go","code":"// NewForConfig creates a new EventsV1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*EventsV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":43,"to":56}} {"id":100026808,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*EventsV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1/events_client.go","code":"// NewForConfigAndClient creates a new EventsV1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*EventsV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026EventsV1Client{client}, nil\n}","line":{"from":58,"to":70}} {"id":100026809,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *EventsV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1/events_client.go","code":"// NewForConfigOrDie creates a new EventsV1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *EventsV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":72,"to":80}} {"id":100026810,"name":"New","signature":"func New(c rest.Interface) *EventsV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1/events_client.go","code":"// New creates a new EventsV1Client for the given RESTClient.\nfunc New(c rest.Interface) *EventsV1Client {\n\treturn \u0026EventsV1Client{c}\n}","line":{"from":82,"to":85}} {"id":100026811,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1/events_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":87,"to":98}} {"id":100026812,"name":"RESTClient","signature":"func (c *EventsV1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1/events_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *EventsV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":100,"to":107}} {"id":100026813,"name":"newEvents","signature":"func newEvents(c *EventsV1beta1Client, namespace string) *events","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1beta1/event.go","code":"// newEvents returns a Events\nfunc newEvents(c *EventsV1beta1Client, namespace string) *events {\n\treturn \u0026events{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":62,"to":68}} {"id":100026814,"name":"Get","signature":"func (c *events) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.Event, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1beta1/event.go","code":"// Get takes name of the event, and returns the corresponding event object, and an error if there is any.\nfunc (c *events) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.Event, err error) {\n\tresult = \u0026v1beta1.Event{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":81}} {"id":100026815,"name":"List","signature":"func (c *events) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.EventList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1beta1/event.go","code":"// List takes label and field selectors, and returns the list of Events that match those selectors.\nfunc (c *events) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.EventList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.EventList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":83,"to":98}} {"id":100026816,"name":"Watch","signature":"func (c *events) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1beta1/event.go","code":"// Watch returns a watch.Interface that watches the requested events.\nfunc (c *events) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":100,"to":113}} {"id":100026817,"name":"Create","signature":"func (c *events) Create(ctx context.Context, event *v1beta1.Event, opts v1.CreateOptions) (result *v1beta1.Event, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1beta1/event.go","code":"// Create takes the representation of a event and creates it. Returns the server's representation of the event, and an error, if there is any.\nfunc (c *events) Create(ctx context.Context, event *v1beta1.Event, opts v1.CreateOptions) (result *v1beta1.Event, err error) {\n\tresult = \u0026v1beta1.Event{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(event).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":115,"to":126}} {"id":100026818,"name":"Update","signature":"func (c *events) Update(ctx context.Context, event *v1beta1.Event, opts v1.UpdateOptions) (result *v1beta1.Event, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1beta1/event.go","code":"// Update takes the representation of a event and updates it. Returns the server's representation of the event, and an error, if there is any.\nfunc (c *events) Update(ctx context.Context, event *v1beta1.Event, opts v1.UpdateOptions) (result *v1beta1.Event, err error) {\n\tresult = \u0026v1beta1.Event{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tName(event.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(event).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":128,"to":140}} {"id":100026819,"name":"Delete","signature":"func (c *events) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1beta1/event.go","code":"// Delete takes name of the event and deletes it. Returns an error if one occurs.\nfunc (c *events) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":142,"to":151}} {"id":100026820,"name":"DeleteCollection","signature":"func (c *events) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1beta1/event.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *events) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":153,"to":167}} {"id":100026821,"name":"Patch","signature":"func (c *events) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.Event, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1beta1/event.go","code":"// Patch applies the patch and returns the patched event.\nfunc (c *events) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.Event, err error) {\n\tresult = \u0026v1beta1.Event{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":169,"to":182}} {"id":100026822,"name":"Apply","signature":"func (c *events) Apply(ctx context.Context, event *eventsv1beta1.EventApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Event, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1beta1/event.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied event.\nfunc (c *events) Apply(ctx context.Context, event *eventsv1beta1.EventApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Event, err error) {\n\tif event == nil {\n\t\treturn nil, fmt.Errorf(\"event provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(event)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := event.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"event.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.Event{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"events\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":184,"to":208}} {"id":100026823,"name":"CreateWithEventNamespace","signature":"func (e *events) CreateWithEventNamespace(event *v1beta1.Event) (*v1beta1.Event, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1beta1/event_expansion.go","code":"// CreateWithEventNamespace makes a new event.\n// Returns the copy of the event the server returns, or an error.\n// The namespace to create the event within is deduced from the event.\n// it must either match this event client's namespace, or this event client must\n// have been created with the \"\" namespace.\nfunc (e *events) CreateWithEventNamespace(event *v1beta1.Event) (*v1beta1.Event, error) {\n\tif e.ns != \"\" \u0026\u0026 event.Namespace != e.ns {\n\t\treturn nil, fmt.Errorf(\"can't create an event with namespace '%v' in namespace '%v'\", event.Namespace, e.ns)\n\t}\n\tresult := \u0026v1beta1.Event{}\n\terr := e.client.Post().\n\t\tNamespaceIfScoped(event.Namespace, len(event.Namespace) \u003e 0).\n\t\tResource(\"events\").\n\t\tBody(event).\n\t\tDo(context.TODO()).\n\t\tInto(result)\n\treturn result, err\n}","line":{"from":41,"to":58}} {"id":100026824,"name":"UpdateWithEventNamespace","signature":"func (e *events) UpdateWithEventNamespace(event *v1beta1.Event) (*v1beta1.Event, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1beta1/event_expansion.go","code":"// UpdateWithEventNamespace modifies an existing event.\n// It returns the copy of the event that the server returns, or an error.\n// The namespace and key to update the event within is deduced from the event.\n// The namespace must either match this event client's namespace, or this event client must have been\n// created with the \"\" namespace.\n// Update also requires the ResourceVersion to be set in the event object.\nfunc (e *events) UpdateWithEventNamespace(event *v1beta1.Event) (*v1beta1.Event, error) {\n\tif e.ns != \"\" \u0026\u0026 event.Namespace != e.ns {\n\t\treturn nil, fmt.Errorf(\"can't update an event with namespace '%v' in namespace '%v'\", event.Namespace, e.ns)\n\t}\n\tresult := \u0026v1beta1.Event{}\n\terr := e.client.Put().\n\t\tNamespaceIfScoped(event.Namespace, len(event.Namespace) \u003e 0).\n\t\tResource(\"events\").\n\t\tName(event.Name).\n\t\tBody(event).\n\t\tDo(context.TODO()).\n\t\tInto(result)\n\treturn result, err\n}","line":{"from":60,"to":79}} {"id":100026825,"name":"PatchWithEventNamespace","signature":"func (e *events) PatchWithEventNamespace(event *v1beta1.Event, data []byte) (*v1beta1.Event, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1beta1/event_expansion.go","code":"// PatchWithEventNamespace modifies an existing event.\n// It returns the copy of the event that the server returns, or an error.\n// The namespace and name of the target event is deduced from the event.\n// The namespace must either match this event client's namespace, or this event client must\n// have been created with the \"\" namespace.\nfunc (e *events) PatchWithEventNamespace(event *v1beta1.Event, data []byte) (*v1beta1.Event, error) {\n\tif e.ns != \"\" \u0026\u0026 event.Namespace != e.ns {\n\t\treturn nil, fmt.Errorf(\"can't patch an event with namespace '%v' in namespace '%v'\", event.Namespace, e.ns)\n\t}\n\tresult := \u0026v1beta1.Event{}\n\terr := e.client.Patch(types.StrategicMergePatchType).\n\t\tNamespaceIfScoped(event.Namespace, len(event.Namespace) \u003e 0).\n\t\tResource(\"events\").\n\t\tName(event.Name).\n\t\tBody(data).\n\t\tDo(context.TODO()).\n\t\tInto(result)\n\treturn result, err\n}","line":{"from":81,"to":99}} {"id":100026826,"name":"Events","signature":"func (c *EventsV1beta1Client) Events(namespace string) EventInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1beta1/events_client.go","code":"func (c *EventsV1beta1Client) Events(namespace string) EventInterface {\n\treturn newEvents(c, namespace)\n}","line":{"from":39,"to":41}} {"id":100026827,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*EventsV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1beta1/events_client.go","code":"// NewForConfig creates a new EventsV1beta1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*EventsV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":43,"to":56}} {"id":100026828,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*EventsV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1beta1/events_client.go","code":"// NewForConfigAndClient creates a new EventsV1beta1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*EventsV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026EventsV1beta1Client{client}, nil\n}","line":{"from":58,"to":70}} {"id":100026829,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *EventsV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1beta1/events_client.go","code":"// NewForConfigOrDie creates a new EventsV1beta1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *EventsV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":72,"to":80}} {"id":100026830,"name":"New","signature":"func New(c rest.Interface) *EventsV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1beta1/events_client.go","code":"// New creates a new EventsV1beta1Client for the given RESTClient.\nfunc New(c rest.Interface) *EventsV1beta1Client {\n\treturn \u0026EventsV1beta1Client{c}\n}","line":{"from":82,"to":85}} {"id":100026831,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1beta1/events_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":87,"to":98}} {"id":100026832,"name":"RESTClient","signature":"func (c *EventsV1beta1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/events/v1beta1/events_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *EventsV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":100,"to":107}} {"id":100026833,"name":"newDaemonSets","signature":"func newDaemonSets(c *ExtensionsV1beta1Client, namespace string) *daemonSets","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/daemonset.go","code":"// newDaemonSets returns a DaemonSets\nfunc newDaemonSets(c *ExtensionsV1beta1Client, namespace string) *daemonSets {\n\treturn \u0026daemonSets{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":64,"to":70}} {"id":100026834,"name":"Get","signature":"func (c *daemonSets) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/daemonset.go","code":"// Get takes name of the daemonSet, and returns the corresponding daemonSet object, and an error if there is any.\nfunc (c *daemonSets) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.DaemonSet, err error) {\n\tresult = \u0026v1beta1.DaemonSet{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":72,"to":83}} {"id":100026835,"name":"List","signature":"func (c *daemonSets) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.DaemonSetList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/daemonset.go","code":"// List takes label and field selectors, and returns the list of DaemonSets that match those selectors.\nfunc (c *daemonSets) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.DaemonSetList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.DaemonSetList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":85,"to":100}} {"id":100026836,"name":"Watch","signature":"func (c *daemonSets) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/daemonset.go","code":"// Watch returns a watch.Interface that watches the requested daemonSets.\nfunc (c *daemonSets) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":102,"to":115}} {"id":100026837,"name":"Create","signature":"func (c *daemonSets) Create(ctx context.Context, daemonSet *v1beta1.DaemonSet, opts v1.CreateOptions) (result *v1beta1.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/daemonset.go","code":"// Create takes the representation of a daemonSet and creates it. Returns the server's representation of the daemonSet, and an error, if there is any.\nfunc (c *daemonSets) Create(ctx context.Context, daemonSet *v1beta1.DaemonSet, opts v1.CreateOptions) (result *v1beta1.DaemonSet, err error) {\n\tresult = \u0026v1beta1.DaemonSet{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(daemonSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":117,"to":128}} {"id":100026838,"name":"Update","signature":"func (c *daemonSets) Update(ctx context.Context, daemonSet *v1beta1.DaemonSet, opts v1.UpdateOptions) (result *v1beta1.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/daemonset.go","code":"// Update takes the representation of a daemonSet and updates it. Returns the server's representation of the daemonSet, and an error, if there is any.\nfunc (c *daemonSets) Update(ctx context.Context, daemonSet *v1beta1.DaemonSet, opts v1.UpdateOptions) (result *v1beta1.DaemonSet, err error) {\n\tresult = \u0026v1beta1.DaemonSet{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tName(daemonSet.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(daemonSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":130,"to":142}} {"id":100026839,"name":"UpdateStatus","signature":"func (c *daemonSets) UpdateStatus(ctx context.Context, daemonSet *v1beta1.DaemonSet, opts v1.UpdateOptions) (result *v1beta1.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/daemonset.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *daemonSets) UpdateStatus(ctx context.Context, daemonSet *v1beta1.DaemonSet, opts v1.UpdateOptions) (result *v1beta1.DaemonSet, err error) {\n\tresult = \u0026v1beta1.DaemonSet{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tName(daemonSet.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(daemonSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":144,"to":158}} {"id":100026840,"name":"Delete","signature":"func (c *daemonSets) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/daemonset.go","code":"// Delete takes name of the daemonSet and deletes it. Returns an error if one occurs.\nfunc (c *daemonSets) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":160,"to":169}} {"id":100026841,"name":"DeleteCollection","signature":"func (c *daemonSets) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/daemonset.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *daemonSets) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":171,"to":185}} {"id":100026842,"name":"Patch","signature":"func (c *daemonSets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/daemonset.go","code":"// Patch applies the patch and returns the patched daemonSet.\nfunc (c *daemonSets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.DaemonSet, err error) {\n\tresult = \u0026v1beta1.DaemonSet{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":187,"to":200}} {"id":100026843,"name":"Apply","signature":"func (c *daemonSets) Apply(ctx context.Context, daemonSet *extensionsv1beta1.DaemonSetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/daemonset.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied daemonSet.\nfunc (c *daemonSets) Apply(ctx context.Context, daemonSet *extensionsv1beta1.DaemonSetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.DaemonSet, err error) {\n\tif daemonSet == nil {\n\t\treturn nil, fmt.Errorf(\"daemonSet provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(daemonSet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := daemonSet.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"daemonSet.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.DaemonSet{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":202,"to":226}} {"id":100026844,"name":"ApplyStatus","signature":"func (c *daemonSets) ApplyStatus(ctx context.Context, daemonSet *extensionsv1beta1.DaemonSetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/daemonset.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *daemonSets) ApplyStatus(ctx context.Context, daemonSet *extensionsv1beta1.DaemonSetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.DaemonSet, err error) {\n\tif daemonSet == nil {\n\t\treturn nil, fmt.Errorf(\"daemonSet provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(daemonSet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := daemonSet.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"daemonSet.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1beta1.DaemonSet{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"daemonsets\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":228,"to":256}} {"id":100026845,"name":"newDeployments","signature":"func newDeployments(c *ExtensionsV1beta1Client, namespace string) *deployments","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/deployment.go","code":"// newDeployments returns a Deployments\nfunc newDeployments(c *ExtensionsV1beta1Client, namespace string) *deployments {\n\treturn \u0026deployments{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":68,"to":74}} {"id":100026846,"name":"Get","signature":"func (c *deployments) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/deployment.go","code":"// Get takes name of the deployment, and returns the corresponding deployment object, and an error if there is any.\nfunc (c *deployments) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.Deployment, err error) {\n\tresult = \u0026v1beta1.Deployment{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":76,"to":87}} {"id":100026847,"name":"List","signature":"func (c *deployments) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.DeploymentList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/deployment.go","code":"// List takes label and field selectors, and returns the list of Deployments that match those selectors.\nfunc (c *deployments) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.DeploymentList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.DeploymentList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":89,"to":104}} {"id":100026848,"name":"Watch","signature":"func (c *deployments) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/deployment.go","code":"// Watch returns a watch.Interface that watches the requested deployments.\nfunc (c *deployments) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":106,"to":119}} {"id":100026849,"name":"Create","signature":"func (c *deployments) Create(ctx context.Context, deployment *v1beta1.Deployment, opts v1.CreateOptions) (result *v1beta1.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/deployment.go","code":"// Create takes the representation of a deployment and creates it. Returns the server's representation of the deployment, and an error, if there is any.\nfunc (c *deployments) Create(ctx context.Context, deployment *v1beta1.Deployment, opts v1.CreateOptions) (result *v1beta1.Deployment, err error) {\n\tresult = \u0026v1beta1.Deployment{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(deployment).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":121,"to":132}} {"id":100026850,"name":"Update","signature":"func (c *deployments) Update(ctx context.Context, deployment *v1beta1.Deployment, opts v1.UpdateOptions) (result *v1beta1.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/deployment.go","code":"// Update takes the representation of a deployment and updates it. Returns the server's representation of the deployment, and an error, if there is any.\nfunc (c *deployments) Update(ctx context.Context, deployment *v1beta1.Deployment, opts v1.UpdateOptions) (result *v1beta1.Deployment, err error) {\n\tresult = \u0026v1beta1.Deployment{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(deployment.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(deployment).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":134,"to":146}} {"id":100026851,"name":"UpdateStatus","signature":"func (c *deployments) UpdateStatus(ctx context.Context, deployment *v1beta1.Deployment, opts v1.UpdateOptions) (result *v1beta1.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/deployment.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *deployments) UpdateStatus(ctx context.Context, deployment *v1beta1.Deployment, opts v1.UpdateOptions) (result *v1beta1.Deployment, err error) {\n\tresult = \u0026v1beta1.Deployment{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(deployment.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(deployment).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":148,"to":162}} {"id":100026852,"name":"Delete","signature":"func (c *deployments) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/deployment.go","code":"// Delete takes name of the deployment and deletes it. Returns an error if one occurs.\nfunc (c *deployments) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":164,"to":173}} {"id":100026853,"name":"DeleteCollection","signature":"func (c *deployments) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/deployment.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *deployments) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":175,"to":189}} {"id":100026854,"name":"Patch","signature":"func (c *deployments) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/deployment.go","code":"// Patch applies the patch and returns the patched deployment.\nfunc (c *deployments) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.Deployment, err error) {\n\tresult = \u0026v1beta1.Deployment{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":191,"to":204}} {"id":100026855,"name":"Apply","signature":"func (c *deployments) Apply(ctx context.Context, deployment *extensionsv1beta1.DeploymentApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/deployment.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied deployment.\nfunc (c *deployments) Apply(ctx context.Context, deployment *extensionsv1beta1.DeploymentApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Deployment, err error) {\n\tif deployment == nil {\n\t\treturn nil, fmt.Errorf(\"deployment provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(deployment)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := deployment.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"deployment.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.Deployment{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":206,"to":230}} {"id":100026856,"name":"ApplyStatus","signature":"func (c *deployments) ApplyStatus(ctx context.Context, deployment *extensionsv1beta1.DeploymentApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Deployment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/deployment.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *deployments) ApplyStatus(ctx context.Context, deployment *extensionsv1beta1.DeploymentApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Deployment, err error) {\n\tif deployment == nil {\n\t\treturn nil, fmt.Errorf(\"deployment provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(deployment)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := deployment.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"deployment.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1beta1.Deployment{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":232,"to":260}} {"id":100026857,"name":"GetScale","signature":"func (c *deployments) GetScale(ctx context.Context, deploymentName string, options v1.GetOptions) (result *v1beta1.Scale, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/deployment.go","code":"// GetScale takes name of the deployment, and returns the corresponding v1beta1.Scale object, and an error if there is any.\nfunc (c *deployments) GetScale(ctx context.Context, deploymentName string, options v1.GetOptions) (result *v1beta1.Scale, err error) {\n\tresult = \u0026v1beta1.Scale{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(deploymentName).\n\t\tSubResource(\"scale\").\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":262,"to":274}} {"id":100026858,"name":"UpdateScale","signature":"func (c *deployments) UpdateScale(ctx context.Context, deploymentName string, scale *v1beta1.Scale, opts v1.UpdateOptions) (result *v1beta1.Scale, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/deployment.go","code":"// UpdateScale takes the top resource name and the representation of a scale and updates it. Returns the server's representation of the scale, and an error, if there is any.\nfunc (c *deployments) UpdateScale(ctx context.Context, deploymentName string, scale *v1beta1.Scale, opts v1.UpdateOptions) (result *v1beta1.Scale, err error) {\n\tresult = \u0026v1beta1.Scale{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(deploymentName).\n\t\tSubResource(\"scale\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(scale).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":276,"to":289}} {"id":100026859,"name":"ApplyScale","signature":"func (c *deployments) ApplyScale(ctx context.Context, deploymentName string, scale *extensionsv1beta1.ScaleApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Scale, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/deployment.go","code":"// ApplyScale takes top resource name and the apply declarative configuration for scale,\n// applies it and returns the applied scale, and an error, if there is any.\nfunc (c *deployments) ApplyScale(ctx context.Context, deploymentName string, scale *extensionsv1beta1.ScaleApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Scale, err error) {\n\tif scale == nil {\n\t\treturn nil, fmt.Errorf(\"scale provided to ApplyScale must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(scale)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult = \u0026v1beta1.Scale{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"deployments\").\n\t\tName(deploymentName).\n\t\tSubResource(\"scale\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":291,"to":314}} {"id":100026860,"name":"Rollback","signature":"func (c *deployments) Rollback(ctx context.Context, deploymentRollback *v1beta1.DeploymentRollback, opts metav1.CreateOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/deployment_expansion.go","code":"// Rollback applied the provided DeploymentRollback to the named deployment in the current namespace.\nfunc (c *deployments) Rollback(ctx context.Context, deploymentRollback *v1beta1.DeploymentRollback, opts metav1.CreateOptions) error {\n\treturn c.client.Post().Namespace(c.ns).Resource(\"deployments\").Name(deploymentRollback.Name).VersionedParams(\u0026opts, scheme.ParameterCodec).SubResource(\"rollback\").Body(deploymentRollback).Do(ctx).Error()\n}","line":{"from":32,"to":35}} {"id":100026861,"name":"DaemonSets","signature":"func (c *ExtensionsV1beta1Client) DaemonSets(namespace string) DaemonSetInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/extensions_client.go","code":"func (c *ExtensionsV1beta1Client) DaemonSets(namespace string) DaemonSetInterface {\n\treturn newDaemonSets(c, namespace)\n}","line":{"from":43,"to":45}} {"id":100026862,"name":"Deployments","signature":"func (c *ExtensionsV1beta1Client) Deployments(namespace string) DeploymentInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/extensions_client.go","code":"func (c *ExtensionsV1beta1Client) Deployments(namespace string) DeploymentInterface {\n\treturn newDeployments(c, namespace)\n}","line":{"from":47,"to":49}} {"id":100026863,"name":"Ingresses","signature":"func (c *ExtensionsV1beta1Client) Ingresses(namespace string) IngressInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/extensions_client.go","code":"func (c *ExtensionsV1beta1Client) Ingresses(namespace string) IngressInterface {\n\treturn newIngresses(c, namespace)\n}","line":{"from":51,"to":53}} {"id":100026864,"name":"NetworkPolicies","signature":"func (c *ExtensionsV1beta1Client) NetworkPolicies(namespace string) NetworkPolicyInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/extensions_client.go","code":"func (c *ExtensionsV1beta1Client) NetworkPolicies(namespace string) NetworkPolicyInterface {\n\treturn newNetworkPolicies(c, namespace)\n}","line":{"from":55,"to":57}} {"id":100026865,"name":"ReplicaSets","signature":"func (c *ExtensionsV1beta1Client) ReplicaSets(namespace string) ReplicaSetInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/extensions_client.go","code":"func (c *ExtensionsV1beta1Client) ReplicaSets(namespace string) ReplicaSetInterface {\n\treturn newReplicaSets(c, namespace)\n}","line":{"from":59,"to":61}} {"id":100026866,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*ExtensionsV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/extensions_client.go","code":"// NewForConfig creates a new ExtensionsV1beta1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*ExtensionsV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":63,"to":76}} {"id":100026867,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*ExtensionsV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/extensions_client.go","code":"// NewForConfigAndClient creates a new ExtensionsV1beta1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*ExtensionsV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026ExtensionsV1beta1Client{client}, nil\n}","line":{"from":78,"to":90}} {"id":100026868,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *ExtensionsV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/extensions_client.go","code":"// NewForConfigOrDie creates a new ExtensionsV1beta1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *ExtensionsV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":92,"to":100}} {"id":100026869,"name":"New","signature":"func New(c rest.Interface) *ExtensionsV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/extensions_client.go","code":"// New creates a new ExtensionsV1beta1Client for the given RESTClient.\nfunc New(c rest.Interface) *ExtensionsV1beta1Client {\n\treturn \u0026ExtensionsV1beta1Client{c}\n}","line":{"from":102,"to":105}} {"id":100026870,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/extensions_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":107,"to":118}} {"id":100026871,"name":"RESTClient","signature":"func (c *ExtensionsV1beta1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/extensions_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *ExtensionsV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":120,"to":127}} {"id":100026872,"name":"newIngresses","signature":"func newIngresses(c *ExtensionsV1beta1Client, namespace string) *ingresses","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/ingress.go","code":"// newIngresses returns a Ingresses\nfunc newIngresses(c *ExtensionsV1beta1Client, namespace string) *ingresses {\n\treturn \u0026ingresses{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":64,"to":70}} {"id":100026873,"name":"Get","signature":"func (c *ingresses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.Ingress, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/ingress.go","code":"// Get takes name of the ingress, and returns the corresponding ingress object, and an error if there is any.\nfunc (c *ingresses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.Ingress, err error) {\n\tresult = \u0026v1beta1.Ingress{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":72,"to":83}} {"id":100026874,"name":"List","signature":"func (c *ingresses) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.IngressList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/ingress.go","code":"// List takes label and field selectors, and returns the list of Ingresses that match those selectors.\nfunc (c *ingresses) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.IngressList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.IngressList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":85,"to":100}} {"id":100026875,"name":"Watch","signature":"func (c *ingresses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/ingress.go","code":"// Watch returns a watch.Interface that watches the requested ingresses.\nfunc (c *ingresses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":102,"to":115}} {"id":100026876,"name":"Create","signature":"func (c *ingresses) Create(ctx context.Context, ingress *v1beta1.Ingress, opts v1.CreateOptions) (result *v1beta1.Ingress, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/ingress.go","code":"// Create takes the representation of a ingress and creates it. Returns the server's representation of the ingress, and an error, if there is any.\nfunc (c *ingresses) Create(ctx context.Context, ingress *v1beta1.Ingress, opts v1.CreateOptions) (result *v1beta1.Ingress, err error) {\n\tresult = \u0026v1beta1.Ingress{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(ingress).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":117,"to":128}} {"id":100026877,"name":"Update","signature":"func (c *ingresses) Update(ctx context.Context, ingress *v1beta1.Ingress, opts v1.UpdateOptions) (result *v1beta1.Ingress, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/ingress.go","code":"// Update takes the representation of a ingress and updates it. Returns the server's representation of the ingress, and an error, if there is any.\nfunc (c *ingresses) Update(ctx context.Context, ingress *v1beta1.Ingress, opts v1.UpdateOptions) (result *v1beta1.Ingress, err error) {\n\tresult = \u0026v1beta1.Ingress{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tName(ingress.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(ingress).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":130,"to":142}} {"id":100026878,"name":"UpdateStatus","signature":"func (c *ingresses) UpdateStatus(ctx context.Context, ingress *v1beta1.Ingress, opts v1.UpdateOptions) (result *v1beta1.Ingress, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/ingress.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *ingresses) UpdateStatus(ctx context.Context, ingress *v1beta1.Ingress, opts v1.UpdateOptions) (result *v1beta1.Ingress, err error) {\n\tresult = \u0026v1beta1.Ingress{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tName(ingress.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(ingress).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":144,"to":158}} {"id":100026879,"name":"Delete","signature":"func (c *ingresses) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/ingress.go","code":"// Delete takes name of the ingress and deletes it. Returns an error if one occurs.\nfunc (c *ingresses) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":160,"to":169}} {"id":100026880,"name":"DeleteCollection","signature":"func (c *ingresses) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/ingress.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *ingresses) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":171,"to":185}} {"id":100026881,"name":"Patch","signature":"func (c *ingresses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.Ingress, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/ingress.go","code":"// Patch applies the patch and returns the patched ingress.\nfunc (c *ingresses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.Ingress, err error) {\n\tresult = \u0026v1beta1.Ingress{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":187,"to":200}} {"id":100026882,"name":"Apply","signature":"func (c *ingresses) Apply(ctx context.Context, ingress *extensionsv1beta1.IngressApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Ingress, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/ingress.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied ingress.\nfunc (c *ingresses) Apply(ctx context.Context, ingress *extensionsv1beta1.IngressApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Ingress, err error) {\n\tif ingress == nil {\n\t\treturn nil, fmt.Errorf(\"ingress provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(ingress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := ingress.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"ingress.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.Ingress{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":202,"to":226}} {"id":100026883,"name":"ApplyStatus","signature":"func (c *ingresses) ApplyStatus(ctx context.Context, ingress *extensionsv1beta1.IngressApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Ingress, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/ingress.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *ingresses) ApplyStatus(ctx context.Context, ingress *extensionsv1beta1.IngressApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Ingress, err error) {\n\tif ingress == nil {\n\t\treturn nil, fmt.Errorf(\"ingress provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(ingress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := ingress.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"ingress.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1beta1.Ingress{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":228,"to":256}} {"id":100026884,"name":"newNetworkPolicies","signature":"func newNetworkPolicies(c *ExtensionsV1beta1Client, namespace string) *networkPolicies","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/networkpolicy.go","code":"// newNetworkPolicies returns a NetworkPolicies\nfunc newNetworkPolicies(c *ExtensionsV1beta1Client, namespace string) *networkPolicies {\n\treturn \u0026networkPolicies{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":64,"to":70}} {"id":100026885,"name":"Get","signature":"func (c *networkPolicies) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.NetworkPolicy, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/networkpolicy.go","code":"// Get takes name of the networkPolicy, and returns the corresponding networkPolicy object, and an error if there is any.\nfunc (c *networkPolicies) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.NetworkPolicy, err error) {\n\tresult = \u0026v1beta1.NetworkPolicy{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"networkpolicies\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":72,"to":83}} {"id":100026886,"name":"List","signature":"func (c *networkPolicies) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.NetworkPolicyList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/networkpolicy.go","code":"// List takes label and field selectors, and returns the list of NetworkPolicies that match those selectors.\nfunc (c *networkPolicies) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.NetworkPolicyList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.NetworkPolicyList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"networkpolicies\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":85,"to":100}} {"id":100026887,"name":"Watch","signature":"func (c *networkPolicies) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/networkpolicy.go","code":"// Watch returns a watch.Interface that watches the requested networkPolicies.\nfunc (c *networkPolicies) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"networkpolicies\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":102,"to":115}} {"id":100026888,"name":"Create","signature":"func (c *networkPolicies) Create(ctx context.Context, networkPolicy *v1beta1.NetworkPolicy, opts v1.CreateOptions) (result *v1beta1.NetworkPolicy, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/networkpolicy.go","code":"// Create takes the representation of a networkPolicy and creates it. Returns the server's representation of the networkPolicy, and an error, if there is any.\nfunc (c *networkPolicies) Create(ctx context.Context, networkPolicy *v1beta1.NetworkPolicy, opts v1.CreateOptions) (result *v1beta1.NetworkPolicy, err error) {\n\tresult = \u0026v1beta1.NetworkPolicy{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"networkpolicies\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(networkPolicy).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":117,"to":128}} {"id":100026889,"name":"Update","signature":"func (c *networkPolicies) Update(ctx context.Context, networkPolicy *v1beta1.NetworkPolicy, opts v1.UpdateOptions) (result *v1beta1.NetworkPolicy, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/networkpolicy.go","code":"// Update takes the representation of a networkPolicy and updates it. Returns the server's representation of the networkPolicy, and an error, if there is any.\nfunc (c *networkPolicies) Update(ctx context.Context, networkPolicy *v1beta1.NetworkPolicy, opts v1.UpdateOptions) (result *v1beta1.NetworkPolicy, err error) {\n\tresult = \u0026v1beta1.NetworkPolicy{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"networkpolicies\").\n\t\tName(networkPolicy.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(networkPolicy).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":130,"to":142}} {"id":100026890,"name":"UpdateStatus","signature":"func (c *networkPolicies) UpdateStatus(ctx context.Context, networkPolicy *v1beta1.NetworkPolicy, opts v1.UpdateOptions) (result *v1beta1.NetworkPolicy, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/networkpolicy.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *networkPolicies) UpdateStatus(ctx context.Context, networkPolicy *v1beta1.NetworkPolicy, opts v1.UpdateOptions) (result *v1beta1.NetworkPolicy, err error) {\n\tresult = \u0026v1beta1.NetworkPolicy{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"networkpolicies\").\n\t\tName(networkPolicy.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(networkPolicy).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":144,"to":158}} {"id":100026891,"name":"Delete","signature":"func (c *networkPolicies) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/networkpolicy.go","code":"// Delete takes name of the networkPolicy and deletes it. Returns an error if one occurs.\nfunc (c *networkPolicies) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"networkpolicies\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":160,"to":169}} {"id":100026892,"name":"DeleteCollection","signature":"func (c *networkPolicies) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/networkpolicy.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *networkPolicies) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"networkpolicies\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":171,"to":185}} {"id":100026893,"name":"Patch","signature":"func (c *networkPolicies) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.NetworkPolicy, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/networkpolicy.go","code":"// Patch applies the patch and returns the patched networkPolicy.\nfunc (c *networkPolicies) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.NetworkPolicy, err error) {\n\tresult = \u0026v1beta1.NetworkPolicy{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"networkpolicies\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":187,"to":200}} {"id":100026894,"name":"Apply","signature":"func (c *networkPolicies) Apply(ctx context.Context, networkPolicy *extensionsv1beta1.NetworkPolicyApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.NetworkPolicy, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/networkpolicy.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied networkPolicy.\nfunc (c *networkPolicies) Apply(ctx context.Context, networkPolicy *extensionsv1beta1.NetworkPolicyApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.NetworkPolicy, err error) {\n\tif networkPolicy == nil {\n\t\treturn nil, fmt.Errorf(\"networkPolicy provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(networkPolicy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := networkPolicy.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"networkPolicy.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.NetworkPolicy{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"networkpolicies\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":202,"to":226}} {"id":100026895,"name":"ApplyStatus","signature":"func (c *networkPolicies) ApplyStatus(ctx context.Context, networkPolicy *extensionsv1beta1.NetworkPolicyApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.NetworkPolicy, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/networkpolicy.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *networkPolicies) ApplyStatus(ctx context.Context, networkPolicy *extensionsv1beta1.NetworkPolicyApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.NetworkPolicy, err error) {\n\tif networkPolicy == nil {\n\t\treturn nil, fmt.Errorf(\"networkPolicy provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(networkPolicy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := networkPolicy.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"networkPolicy.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1beta1.NetworkPolicy{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"networkpolicies\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":228,"to":256}} {"id":100026896,"name":"newReplicaSets","signature":"func newReplicaSets(c *ExtensionsV1beta1Client, namespace string) *replicaSets","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/replicaset.go","code":"// newReplicaSets returns a ReplicaSets\nfunc newReplicaSets(c *ExtensionsV1beta1Client, namespace string) *replicaSets {\n\treturn \u0026replicaSets{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":68,"to":74}} {"id":100026897,"name":"Get","signature":"func (c *replicaSets) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/replicaset.go","code":"// Get takes name of the replicaSet, and returns the corresponding replicaSet object, and an error if there is any.\nfunc (c *replicaSets) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.ReplicaSet, err error) {\n\tresult = \u0026v1beta1.ReplicaSet{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":76,"to":87}} {"id":100026898,"name":"List","signature":"func (c *replicaSets) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.ReplicaSetList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/replicaset.go","code":"// List takes label and field selectors, and returns the list of ReplicaSets that match those selectors.\nfunc (c *replicaSets) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.ReplicaSetList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.ReplicaSetList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":89,"to":104}} {"id":100026899,"name":"Watch","signature":"func (c *replicaSets) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/replicaset.go","code":"// Watch returns a watch.Interface that watches the requested replicaSets.\nfunc (c *replicaSets) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":106,"to":119}} {"id":100026900,"name":"Create","signature":"func (c *replicaSets) Create(ctx context.Context, replicaSet *v1beta1.ReplicaSet, opts v1.CreateOptions) (result *v1beta1.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/replicaset.go","code":"// Create takes the representation of a replicaSet and creates it. Returns the server's representation of the replicaSet, and an error, if there is any.\nfunc (c *replicaSets) Create(ctx context.Context, replicaSet *v1beta1.ReplicaSet, opts v1.CreateOptions) (result *v1beta1.ReplicaSet, err error) {\n\tresult = \u0026v1beta1.ReplicaSet{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(replicaSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":121,"to":132}} {"id":100026901,"name":"Update","signature":"func (c *replicaSets) Update(ctx context.Context, replicaSet *v1beta1.ReplicaSet, opts v1.UpdateOptions) (result *v1beta1.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/replicaset.go","code":"// Update takes the representation of a replicaSet and updates it. Returns the server's representation of the replicaSet, and an error, if there is any.\nfunc (c *replicaSets) Update(ctx context.Context, replicaSet *v1beta1.ReplicaSet, opts v1.UpdateOptions) (result *v1beta1.ReplicaSet, err error) {\n\tresult = \u0026v1beta1.ReplicaSet{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(replicaSet.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(replicaSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":134,"to":146}} {"id":100026902,"name":"UpdateStatus","signature":"func (c *replicaSets) UpdateStatus(ctx context.Context, replicaSet *v1beta1.ReplicaSet, opts v1.UpdateOptions) (result *v1beta1.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/replicaset.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *replicaSets) UpdateStatus(ctx context.Context, replicaSet *v1beta1.ReplicaSet, opts v1.UpdateOptions) (result *v1beta1.ReplicaSet, err error) {\n\tresult = \u0026v1beta1.ReplicaSet{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(replicaSet.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(replicaSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":148,"to":162}} {"id":100026903,"name":"Delete","signature":"func (c *replicaSets) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/replicaset.go","code":"// Delete takes name of the replicaSet and deletes it. Returns an error if one occurs.\nfunc (c *replicaSets) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":164,"to":173}} {"id":100026904,"name":"DeleteCollection","signature":"func (c *replicaSets) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/replicaset.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *replicaSets) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":175,"to":189}} {"id":100026905,"name":"Patch","signature":"func (c *replicaSets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/replicaset.go","code":"// Patch applies the patch and returns the patched replicaSet.\nfunc (c *replicaSets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.ReplicaSet, err error) {\n\tresult = \u0026v1beta1.ReplicaSet{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":191,"to":204}} {"id":100026906,"name":"Apply","signature":"func (c *replicaSets) Apply(ctx context.Context, replicaSet *extensionsv1beta1.ReplicaSetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/replicaset.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied replicaSet.\nfunc (c *replicaSets) Apply(ctx context.Context, replicaSet *extensionsv1beta1.ReplicaSetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.ReplicaSet, err error) {\n\tif replicaSet == nil {\n\t\treturn nil, fmt.Errorf(\"replicaSet provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(replicaSet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := replicaSet.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"replicaSet.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.ReplicaSet{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":206,"to":230}} {"id":100026907,"name":"ApplyStatus","signature":"func (c *replicaSets) ApplyStatus(ctx context.Context, replicaSet *extensionsv1beta1.ReplicaSetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/replicaset.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *replicaSets) ApplyStatus(ctx context.Context, replicaSet *extensionsv1beta1.ReplicaSetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.ReplicaSet, err error) {\n\tif replicaSet == nil {\n\t\treturn nil, fmt.Errorf(\"replicaSet provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(replicaSet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := replicaSet.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"replicaSet.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1beta1.ReplicaSet{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":232,"to":260}} {"id":100026908,"name":"GetScale","signature":"func (c *replicaSets) GetScale(ctx context.Context, replicaSetName string, options v1.GetOptions) (result *v1beta1.Scale, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/replicaset.go","code":"// GetScale takes name of the replicaSet, and returns the corresponding v1beta1.Scale object, and an error if there is any.\nfunc (c *replicaSets) GetScale(ctx context.Context, replicaSetName string, options v1.GetOptions) (result *v1beta1.Scale, err error) {\n\tresult = \u0026v1beta1.Scale{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(replicaSetName).\n\t\tSubResource(\"scale\").\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":262,"to":274}} {"id":100026909,"name":"UpdateScale","signature":"func (c *replicaSets) UpdateScale(ctx context.Context, replicaSetName string, scale *v1beta1.Scale, opts v1.UpdateOptions) (result *v1beta1.Scale, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/replicaset.go","code":"// UpdateScale takes the top resource name and the representation of a scale and updates it. Returns the server's representation of the scale, and an error, if there is any.\nfunc (c *replicaSets) UpdateScale(ctx context.Context, replicaSetName string, scale *v1beta1.Scale, opts v1.UpdateOptions) (result *v1beta1.Scale, err error) {\n\tresult = \u0026v1beta1.Scale{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(replicaSetName).\n\t\tSubResource(\"scale\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(scale).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":276,"to":289}} {"id":100026910,"name":"ApplyScale","signature":"func (c *replicaSets) ApplyScale(ctx context.Context, replicaSetName string, scale *extensionsv1beta1.ScaleApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Scale, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/extensions/v1beta1/replicaset.go","code":"// ApplyScale takes top resource name and the apply declarative configuration for scale,\n// applies it and returns the applied scale, and an error, if there is any.\nfunc (c *replicaSets) ApplyScale(ctx context.Context, replicaSetName string, scale *extensionsv1beta1.ScaleApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Scale, err error) {\n\tif scale == nil {\n\t\treturn nil, fmt.Errorf(\"scale provided to ApplyScale must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(scale)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult = \u0026v1beta1.Scale{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"replicasets\").\n\t\tName(replicaSetName).\n\t\tSubResource(\"scale\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":291,"to":314}} {"id":100026911,"name":"FlowSchemas","signature":"func (c *FlowcontrolV1alpha1Client) FlowSchemas() FlowSchemaInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/flowcontrol_client.go","code":"func (c *FlowcontrolV1alpha1Client) FlowSchemas() FlowSchemaInterface {\n\treturn newFlowSchemas(c)\n}","line":{"from":40,"to":42}} {"id":100026912,"name":"PriorityLevelConfigurations","signature":"func (c *FlowcontrolV1alpha1Client) PriorityLevelConfigurations() PriorityLevelConfigurationInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/flowcontrol_client.go","code":"func (c *FlowcontrolV1alpha1Client) PriorityLevelConfigurations() PriorityLevelConfigurationInterface {\n\treturn newPriorityLevelConfigurations(c)\n}","line":{"from":44,"to":46}} {"id":100026913,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*FlowcontrolV1alpha1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/flowcontrol_client.go","code":"// NewForConfig creates a new FlowcontrolV1alpha1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*FlowcontrolV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":48,"to":61}} {"id":100026914,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*FlowcontrolV1alpha1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/flowcontrol_client.go","code":"// NewForConfigAndClient creates a new FlowcontrolV1alpha1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*FlowcontrolV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026FlowcontrolV1alpha1Client{client}, nil\n}","line":{"from":63,"to":75}} {"id":100026915,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *FlowcontrolV1alpha1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/flowcontrol_client.go","code":"// NewForConfigOrDie creates a new FlowcontrolV1alpha1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *FlowcontrolV1alpha1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":77,"to":85}} {"id":100026916,"name":"New","signature":"func New(c rest.Interface) *FlowcontrolV1alpha1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/flowcontrol_client.go","code":"// New creates a new FlowcontrolV1alpha1Client for the given RESTClient.\nfunc New(c rest.Interface) *FlowcontrolV1alpha1Client {\n\treturn \u0026FlowcontrolV1alpha1Client{c}\n}","line":{"from":87,"to":90}} {"id":100026917,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/flowcontrol_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1alpha1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":92,"to":103}} {"id":100026918,"name":"RESTClient","signature":"func (c *FlowcontrolV1alpha1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/flowcontrol_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *FlowcontrolV1alpha1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":105,"to":112}} {"id":100026919,"name":"newFlowSchemas","signature":"func newFlowSchemas(c *FlowcontrolV1alpha1Client) *flowSchemas","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/flowschema.go","code":"// newFlowSchemas returns a FlowSchemas\nfunc newFlowSchemas(c *FlowcontrolV1alpha1Client) *flowSchemas {\n\treturn \u0026flowSchemas{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":63,"to":68}} {"id":100026920,"name":"Get","signature":"func (c *flowSchemas) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/flowschema.go","code":"// Get takes name of the flowSchema, and returns the corresponding flowSchema object, and an error if there is any.\nfunc (c *flowSchemas) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.FlowSchema, err error) {\n\tresult = \u0026v1alpha1.FlowSchema{}\n\terr = c.client.Get().\n\t\tResource(\"flowschemas\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":80}} {"id":100026921,"name":"List","signature":"func (c *flowSchemas) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.FlowSchemaList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/flowschema.go","code":"// List takes label and field selectors, and returns the list of FlowSchemas that match those selectors.\nfunc (c *flowSchemas) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.FlowSchemaList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1alpha1.FlowSchemaList{}\n\terr = c.client.Get().\n\t\tResource(\"flowschemas\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":82,"to":96}} {"id":100026922,"name":"Watch","signature":"func (c *flowSchemas) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/flowschema.go","code":"// Watch returns a watch.Interface that watches the requested flowSchemas.\nfunc (c *flowSchemas) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"flowschemas\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":98,"to":110}} {"id":100026923,"name":"Create","signature":"func (c *flowSchemas) Create(ctx context.Context, flowSchema *v1alpha1.FlowSchema, opts v1.CreateOptions) (result *v1alpha1.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/flowschema.go","code":"// Create takes the representation of a flowSchema and creates it. Returns the server's representation of the flowSchema, and an error, if there is any.\nfunc (c *flowSchemas) Create(ctx context.Context, flowSchema *v1alpha1.FlowSchema, opts v1.CreateOptions) (result *v1alpha1.FlowSchema, err error) {\n\tresult = \u0026v1alpha1.FlowSchema{}\n\terr = c.client.Post().\n\t\tResource(\"flowschemas\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(flowSchema).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":112,"to":122}} {"id":100026924,"name":"Update","signature":"func (c *flowSchemas) Update(ctx context.Context, flowSchema *v1alpha1.FlowSchema, opts v1.UpdateOptions) (result *v1alpha1.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/flowschema.go","code":"// Update takes the representation of a flowSchema and updates it. Returns the server's representation of the flowSchema, and an error, if there is any.\nfunc (c *flowSchemas) Update(ctx context.Context, flowSchema *v1alpha1.FlowSchema, opts v1.UpdateOptions) (result *v1alpha1.FlowSchema, err error) {\n\tresult = \u0026v1alpha1.FlowSchema{}\n\terr = c.client.Put().\n\t\tResource(\"flowschemas\").\n\t\tName(flowSchema.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(flowSchema).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":124,"to":135}} {"id":100026925,"name":"UpdateStatus","signature":"func (c *flowSchemas) UpdateStatus(ctx context.Context, flowSchema *v1alpha1.FlowSchema, opts v1.UpdateOptions) (result *v1alpha1.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/flowschema.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *flowSchemas) UpdateStatus(ctx context.Context, flowSchema *v1alpha1.FlowSchema, opts v1.UpdateOptions) (result *v1alpha1.FlowSchema, err error) {\n\tresult = \u0026v1alpha1.FlowSchema{}\n\terr = c.client.Put().\n\t\tResource(\"flowschemas\").\n\t\tName(flowSchema.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(flowSchema).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":137,"to":150}} {"id":100026926,"name":"Delete","signature":"func (c *flowSchemas) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/flowschema.go","code":"// Delete takes name of the flowSchema and deletes it. Returns an error if one occurs.\nfunc (c *flowSchemas) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"flowschemas\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":152,"to":160}} {"id":100026927,"name":"DeleteCollection","signature":"func (c *flowSchemas) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/flowschema.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *flowSchemas) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"flowschemas\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":162,"to":175}} {"id":100026928,"name":"Patch","signature":"func (c *flowSchemas) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/flowschema.go","code":"// Patch applies the patch and returns the patched flowSchema.\nfunc (c *flowSchemas) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.FlowSchema, err error) {\n\tresult = \u0026v1alpha1.FlowSchema{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"flowschemas\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":177,"to":189}} {"id":100026929,"name":"Apply","signature":"func (c *flowSchemas) Apply(ctx context.Context, flowSchema *flowcontrolv1alpha1.FlowSchemaApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/flowschema.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied flowSchema.\nfunc (c *flowSchemas) Apply(ctx context.Context, flowSchema *flowcontrolv1alpha1.FlowSchemaApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.FlowSchema, err error) {\n\tif flowSchema == nil {\n\t\treturn nil, fmt.Errorf(\"flowSchema provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(flowSchema)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := flowSchema.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"flowSchema.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1alpha1.FlowSchema{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"flowschemas\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":191,"to":214}} {"id":100026930,"name":"ApplyStatus","signature":"func (c *flowSchemas) ApplyStatus(ctx context.Context, flowSchema *flowcontrolv1alpha1.FlowSchemaApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/flowschema.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *flowSchemas) ApplyStatus(ctx context.Context, flowSchema *flowcontrolv1alpha1.FlowSchemaApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.FlowSchema, err error) {\n\tif flowSchema == nil {\n\t\treturn nil, fmt.Errorf(\"flowSchema provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(flowSchema)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := flowSchema.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"flowSchema.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1alpha1.FlowSchema{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"flowschemas\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":216,"to":243}} {"id":100026931,"name":"newPriorityLevelConfigurations","signature":"func newPriorityLevelConfigurations(c *FlowcontrolV1alpha1Client) *priorityLevelConfigurations","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// newPriorityLevelConfigurations returns a PriorityLevelConfigurations\nfunc newPriorityLevelConfigurations(c *FlowcontrolV1alpha1Client) *priorityLevelConfigurations {\n\treturn \u0026priorityLevelConfigurations{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":63,"to":68}} {"id":100026932,"name":"Get","signature":"func (c *priorityLevelConfigurations) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// Get takes name of the priorityLevelConfiguration, and returns the corresponding priorityLevelConfiguration object, and an error if there is any.\nfunc (c *priorityLevelConfigurations) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.PriorityLevelConfiguration, err error) {\n\tresult = \u0026v1alpha1.PriorityLevelConfiguration{}\n\terr = c.client.Get().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":80}} {"id":100026933,"name":"List","signature":"func (c *priorityLevelConfigurations) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.PriorityLevelConfigurationList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// List takes label and field selectors, and returns the list of PriorityLevelConfigurations that match those selectors.\nfunc (c *priorityLevelConfigurations) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.PriorityLevelConfigurationList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1alpha1.PriorityLevelConfigurationList{}\n\terr = c.client.Get().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":82,"to":96}} {"id":100026934,"name":"Watch","signature":"func (c *priorityLevelConfigurations) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// Watch returns a watch.Interface that watches the requested priorityLevelConfigurations.\nfunc (c *priorityLevelConfigurations) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":98,"to":110}} {"id":100026935,"name":"Create","signature":"func (c *priorityLevelConfigurations) Create(ctx context.Context, priorityLevelConfiguration *v1alpha1.PriorityLevelConfiguration, opts v1.CreateOptions) (result *v1alpha1.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// Create takes the representation of a priorityLevelConfiguration and creates it. Returns the server's representation of the priorityLevelConfiguration, and an error, if there is any.\nfunc (c *priorityLevelConfigurations) Create(ctx context.Context, priorityLevelConfiguration *v1alpha1.PriorityLevelConfiguration, opts v1.CreateOptions) (result *v1alpha1.PriorityLevelConfiguration, err error) {\n\tresult = \u0026v1alpha1.PriorityLevelConfiguration{}\n\terr = c.client.Post().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(priorityLevelConfiguration).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":112,"to":122}} {"id":100026936,"name":"Update","signature":"func (c *priorityLevelConfigurations) Update(ctx context.Context, priorityLevelConfiguration *v1alpha1.PriorityLevelConfiguration, opts v1.UpdateOptions) (result *v1alpha1.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// Update takes the representation of a priorityLevelConfiguration and updates it. Returns the server's representation of the priorityLevelConfiguration, and an error, if there is any.\nfunc (c *priorityLevelConfigurations) Update(ctx context.Context, priorityLevelConfiguration *v1alpha1.PriorityLevelConfiguration, opts v1.UpdateOptions) (result *v1alpha1.PriorityLevelConfiguration, err error) {\n\tresult = \u0026v1alpha1.PriorityLevelConfiguration{}\n\terr = c.client.Put().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(priorityLevelConfiguration.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(priorityLevelConfiguration).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":124,"to":135}} {"id":100026937,"name":"UpdateStatus","signature":"func (c *priorityLevelConfigurations) UpdateStatus(ctx context.Context, priorityLevelConfiguration *v1alpha1.PriorityLevelConfiguration, opts v1.UpdateOptions) (result *v1alpha1.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *priorityLevelConfigurations) UpdateStatus(ctx context.Context, priorityLevelConfiguration *v1alpha1.PriorityLevelConfiguration, opts v1.UpdateOptions) (result *v1alpha1.PriorityLevelConfiguration, err error) {\n\tresult = \u0026v1alpha1.PriorityLevelConfiguration{}\n\terr = c.client.Put().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(priorityLevelConfiguration.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(priorityLevelConfiguration).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":137,"to":150}} {"id":100026938,"name":"Delete","signature":"func (c *priorityLevelConfigurations) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// Delete takes name of the priorityLevelConfiguration and deletes it. Returns an error if one occurs.\nfunc (c *priorityLevelConfigurations) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":152,"to":160}} {"id":100026939,"name":"DeleteCollection","signature":"func (c *priorityLevelConfigurations) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *priorityLevelConfigurations) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":162,"to":175}} {"id":100026940,"name":"Patch","signature":"func (c *priorityLevelConfigurations) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// Patch applies the patch and returns the patched priorityLevelConfiguration.\nfunc (c *priorityLevelConfigurations) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.PriorityLevelConfiguration, err error) {\n\tresult = \u0026v1alpha1.PriorityLevelConfiguration{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":177,"to":189}} {"id":100026941,"name":"Apply","signature":"func (c *priorityLevelConfigurations) Apply(ctx context.Context, priorityLevelConfiguration *flowcontrolv1alpha1.PriorityLevelConfigurationApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied priorityLevelConfiguration.\nfunc (c *priorityLevelConfigurations) Apply(ctx context.Context, priorityLevelConfiguration *flowcontrolv1alpha1.PriorityLevelConfigurationApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.PriorityLevelConfiguration, err error) {\n\tif priorityLevelConfiguration == nil {\n\t\treturn nil, fmt.Errorf(\"priorityLevelConfiguration provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(priorityLevelConfiguration)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := priorityLevelConfiguration.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"priorityLevelConfiguration.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1alpha1.PriorityLevelConfiguration{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":191,"to":214}} {"id":100026942,"name":"ApplyStatus","signature":"func (c *priorityLevelConfigurations) ApplyStatus(ctx context.Context, priorityLevelConfiguration *flowcontrolv1alpha1.PriorityLevelConfigurationApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *priorityLevelConfigurations) ApplyStatus(ctx context.Context, priorityLevelConfiguration *flowcontrolv1alpha1.PriorityLevelConfigurationApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.PriorityLevelConfiguration, err error) {\n\tif priorityLevelConfiguration == nil {\n\t\treturn nil, fmt.Errorf(\"priorityLevelConfiguration provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(priorityLevelConfiguration)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := priorityLevelConfiguration.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"priorityLevelConfiguration.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1alpha1.PriorityLevelConfiguration{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":216,"to":243}} {"id":100026943,"name":"FlowSchemas","signature":"func (c *FlowcontrolV1beta1Client) FlowSchemas() FlowSchemaInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/flowcontrol_client.go","code":"func (c *FlowcontrolV1beta1Client) FlowSchemas() FlowSchemaInterface {\n\treturn newFlowSchemas(c)\n}","line":{"from":40,"to":42}} {"id":100026944,"name":"PriorityLevelConfigurations","signature":"func (c *FlowcontrolV1beta1Client) PriorityLevelConfigurations() PriorityLevelConfigurationInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/flowcontrol_client.go","code":"func (c *FlowcontrolV1beta1Client) PriorityLevelConfigurations() PriorityLevelConfigurationInterface {\n\treturn newPriorityLevelConfigurations(c)\n}","line":{"from":44,"to":46}} {"id":100026945,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*FlowcontrolV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/flowcontrol_client.go","code":"// NewForConfig creates a new FlowcontrolV1beta1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*FlowcontrolV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":48,"to":61}} {"id":100026946,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*FlowcontrolV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/flowcontrol_client.go","code":"// NewForConfigAndClient creates a new FlowcontrolV1beta1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*FlowcontrolV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026FlowcontrolV1beta1Client{client}, nil\n}","line":{"from":63,"to":75}} {"id":100026947,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *FlowcontrolV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/flowcontrol_client.go","code":"// NewForConfigOrDie creates a new FlowcontrolV1beta1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *FlowcontrolV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":77,"to":85}} {"id":100026948,"name":"New","signature":"func New(c rest.Interface) *FlowcontrolV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/flowcontrol_client.go","code":"// New creates a new FlowcontrolV1beta1Client for the given RESTClient.\nfunc New(c rest.Interface) *FlowcontrolV1beta1Client {\n\treturn \u0026FlowcontrolV1beta1Client{c}\n}","line":{"from":87,"to":90}} {"id":100026949,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/flowcontrol_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":92,"to":103}} {"id":100026950,"name":"RESTClient","signature":"func (c *FlowcontrolV1beta1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/flowcontrol_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *FlowcontrolV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":105,"to":112}} {"id":100026951,"name":"newFlowSchemas","signature":"func newFlowSchemas(c *FlowcontrolV1beta1Client) *flowSchemas","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/flowschema.go","code":"// newFlowSchemas returns a FlowSchemas\nfunc newFlowSchemas(c *FlowcontrolV1beta1Client) *flowSchemas {\n\treturn \u0026flowSchemas{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":63,"to":68}} {"id":100026952,"name":"Get","signature":"func (c *flowSchemas) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/flowschema.go","code":"// Get takes name of the flowSchema, and returns the corresponding flowSchema object, and an error if there is any.\nfunc (c *flowSchemas) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.FlowSchema, err error) {\n\tresult = \u0026v1beta1.FlowSchema{}\n\terr = c.client.Get().\n\t\tResource(\"flowschemas\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":80}} {"id":100026953,"name":"List","signature":"func (c *flowSchemas) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.FlowSchemaList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/flowschema.go","code":"// List takes label and field selectors, and returns the list of FlowSchemas that match those selectors.\nfunc (c *flowSchemas) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.FlowSchemaList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.FlowSchemaList{}\n\terr = c.client.Get().\n\t\tResource(\"flowschemas\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":82,"to":96}} {"id":100026954,"name":"Watch","signature":"func (c *flowSchemas) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/flowschema.go","code":"// Watch returns a watch.Interface that watches the requested flowSchemas.\nfunc (c *flowSchemas) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"flowschemas\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":98,"to":110}} {"id":100026955,"name":"Create","signature":"func (c *flowSchemas) Create(ctx context.Context, flowSchema *v1beta1.FlowSchema, opts v1.CreateOptions) (result *v1beta1.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/flowschema.go","code":"// Create takes the representation of a flowSchema and creates it. Returns the server's representation of the flowSchema, and an error, if there is any.\nfunc (c *flowSchemas) Create(ctx context.Context, flowSchema *v1beta1.FlowSchema, opts v1.CreateOptions) (result *v1beta1.FlowSchema, err error) {\n\tresult = \u0026v1beta1.FlowSchema{}\n\terr = c.client.Post().\n\t\tResource(\"flowschemas\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(flowSchema).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":112,"to":122}} {"id":100026956,"name":"Update","signature":"func (c *flowSchemas) Update(ctx context.Context, flowSchema *v1beta1.FlowSchema, opts v1.UpdateOptions) (result *v1beta1.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/flowschema.go","code":"// Update takes the representation of a flowSchema and updates it. Returns the server's representation of the flowSchema, and an error, if there is any.\nfunc (c *flowSchemas) Update(ctx context.Context, flowSchema *v1beta1.FlowSchema, opts v1.UpdateOptions) (result *v1beta1.FlowSchema, err error) {\n\tresult = \u0026v1beta1.FlowSchema{}\n\terr = c.client.Put().\n\t\tResource(\"flowschemas\").\n\t\tName(flowSchema.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(flowSchema).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":124,"to":135}} {"id":100026957,"name":"UpdateStatus","signature":"func (c *flowSchemas) UpdateStatus(ctx context.Context, flowSchema *v1beta1.FlowSchema, opts v1.UpdateOptions) (result *v1beta1.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/flowschema.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *flowSchemas) UpdateStatus(ctx context.Context, flowSchema *v1beta1.FlowSchema, opts v1.UpdateOptions) (result *v1beta1.FlowSchema, err error) {\n\tresult = \u0026v1beta1.FlowSchema{}\n\terr = c.client.Put().\n\t\tResource(\"flowschemas\").\n\t\tName(flowSchema.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(flowSchema).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":137,"to":150}} {"id":100026958,"name":"Delete","signature":"func (c *flowSchemas) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/flowschema.go","code":"// Delete takes name of the flowSchema and deletes it. Returns an error if one occurs.\nfunc (c *flowSchemas) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"flowschemas\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":152,"to":160}} {"id":100026959,"name":"DeleteCollection","signature":"func (c *flowSchemas) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/flowschema.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *flowSchemas) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"flowschemas\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":162,"to":175}} {"id":100026960,"name":"Patch","signature":"func (c *flowSchemas) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/flowschema.go","code":"// Patch applies the patch and returns the patched flowSchema.\nfunc (c *flowSchemas) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.FlowSchema, err error) {\n\tresult = \u0026v1beta1.FlowSchema{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"flowschemas\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":177,"to":189}} {"id":100026961,"name":"Apply","signature":"func (c *flowSchemas) Apply(ctx context.Context, flowSchema *flowcontrolv1beta1.FlowSchemaApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/flowschema.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied flowSchema.\nfunc (c *flowSchemas) Apply(ctx context.Context, flowSchema *flowcontrolv1beta1.FlowSchemaApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.FlowSchema, err error) {\n\tif flowSchema == nil {\n\t\treturn nil, fmt.Errorf(\"flowSchema provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(flowSchema)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := flowSchema.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"flowSchema.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.FlowSchema{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"flowschemas\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":191,"to":214}} {"id":100026962,"name":"ApplyStatus","signature":"func (c *flowSchemas) ApplyStatus(ctx context.Context, flowSchema *flowcontrolv1beta1.FlowSchemaApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/flowschema.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *flowSchemas) ApplyStatus(ctx context.Context, flowSchema *flowcontrolv1beta1.FlowSchemaApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.FlowSchema, err error) {\n\tif flowSchema == nil {\n\t\treturn nil, fmt.Errorf(\"flowSchema provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(flowSchema)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := flowSchema.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"flowSchema.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1beta1.FlowSchema{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"flowschemas\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":216,"to":243}} {"id":100026963,"name":"newPriorityLevelConfigurations","signature":"func newPriorityLevelConfigurations(c *FlowcontrolV1beta1Client) *priorityLevelConfigurations","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// newPriorityLevelConfigurations returns a PriorityLevelConfigurations\nfunc newPriorityLevelConfigurations(c *FlowcontrolV1beta1Client) *priorityLevelConfigurations {\n\treturn \u0026priorityLevelConfigurations{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":63,"to":68}} {"id":100026964,"name":"Get","signature":"func (c *priorityLevelConfigurations) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// Get takes name of the priorityLevelConfiguration, and returns the corresponding priorityLevelConfiguration object, and an error if there is any.\nfunc (c *priorityLevelConfigurations) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.PriorityLevelConfiguration, err error) {\n\tresult = \u0026v1beta1.PriorityLevelConfiguration{}\n\terr = c.client.Get().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":80}} {"id":100026965,"name":"List","signature":"func (c *priorityLevelConfigurations) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.PriorityLevelConfigurationList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// List takes label and field selectors, and returns the list of PriorityLevelConfigurations that match those selectors.\nfunc (c *priorityLevelConfigurations) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.PriorityLevelConfigurationList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.PriorityLevelConfigurationList{}\n\terr = c.client.Get().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":82,"to":96}} {"id":100026966,"name":"Watch","signature":"func (c *priorityLevelConfigurations) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// Watch returns a watch.Interface that watches the requested priorityLevelConfigurations.\nfunc (c *priorityLevelConfigurations) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":98,"to":110}} {"id":100026967,"name":"Create","signature":"func (c *priorityLevelConfigurations) Create(ctx context.Context, priorityLevelConfiguration *v1beta1.PriorityLevelConfiguration, opts v1.CreateOptions) (result *v1beta1.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// Create takes the representation of a priorityLevelConfiguration and creates it. Returns the server's representation of the priorityLevelConfiguration, and an error, if there is any.\nfunc (c *priorityLevelConfigurations) Create(ctx context.Context, priorityLevelConfiguration *v1beta1.PriorityLevelConfiguration, opts v1.CreateOptions) (result *v1beta1.PriorityLevelConfiguration, err error) {\n\tresult = \u0026v1beta1.PriorityLevelConfiguration{}\n\terr = c.client.Post().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(priorityLevelConfiguration).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":112,"to":122}} {"id":100026968,"name":"Update","signature":"func (c *priorityLevelConfigurations) Update(ctx context.Context, priorityLevelConfiguration *v1beta1.PriorityLevelConfiguration, opts v1.UpdateOptions) (result *v1beta1.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// Update takes the representation of a priorityLevelConfiguration and updates it. Returns the server's representation of the priorityLevelConfiguration, and an error, if there is any.\nfunc (c *priorityLevelConfigurations) Update(ctx context.Context, priorityLevelConfiguration *v1beta1.PriorityLevelConfiguration, opts v1.UpdateOptions) (result *v1beta1.PriorityLevelConfiguration, err error) {\n\tresult = \u0026v1beta1.PriorityLevelConfiguration{}\n\terr = c.client.Put().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(priorityLevelConfiguration.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(priorityLevelConfiguration).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":124,"to":135}} {"id":100026969,"name":"UpdateStatus","signature":"func (c *priorityLevelConfigurations) UpdateStatus(ctx context.Context, priorityLevelConfiguration *v1beta1.PriorityLevelConfiguration, opts v1.UpdateOptions) (result *v1beta1.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *priorityLevelConfigurations) UpdateStatus(ctx context.Context, priorityLevelConfiguration *v1beta1.PriorityLevelConfiguration, opts v1.UpdateOptions) (result *v1beta1.PriorityLevelConfiguration, err error) {\n\tresult = \u0026v1beta1.PriorityLevelConfiguration{}\n\terr = c.client.Put().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(priorityLevelConfiguration.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(priorityLevelConfiguration).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":137,"to":150}} {"id":100026970,"name":"Delete","signature":"func (c *priorityLevelConfigurations) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// Delete takes name of the priorityLevelConfiguration and deletes it. Returns an error if one occurs.\nfunc (c *priorityLevelConfigurations) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":152,"to":160}} {"id":100026971,"name":"DeleteCollection","signature":"func (c *priorityLevelConfigurations) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *priorityLevelConfigurations) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":162,"to":175}} {"id":100026972,"name":"Patch","signature":"func (c *priorityLevelConfigurations) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// Patch applies the patch and returns the patched priorityLevelConfiguration.\nfunc (c *priorityLevelConfigurations) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.PriorityLevelConfiguration, err error) {\n\tresult = \u0026v1beta1.PriorityLevelConfiguration{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":177,"to":189}} {"id":100026973,"name":"Apply","signature":"func (c *priorityLevelConfigurations) Apply(ctx context.Context, priorityLevelConfiguration *flowcontrolv1beta1.PriorityLevelConfigurationApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied priorityLevelConfiguration.\nfunc (c *priorityLevelConfigurations) Apply(ctx context.Context, priorityLevelConfiguration *flowcontrolv1beta1.PriorityLevelConfigurationApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.PriorityLevelConfiguration, err error) {\n\tif priorityLevelConfiguration == nil {\n\t\treturn nil, fmt.Errorf(\"priorityLevelConfiguration provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(priorityLevelConfiguration)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := priorityLevelConfiguration.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"priorityLevelConfiguration.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.PriorityLevelConfiguration{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":191,"to":214}} {"id":100026974,"name":"ApplyStatus","signature":"func (c *priorityLevelConfigurations) ApplyStatus(ctx context.Context, priorityLevelConfiguration *flowcontrolv1beta1.PriorityLevelConfigurationApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *priorityLevelConfigurations) ApplyStatus(ctx context.Context, priorityLevelConfiguration *flowcontrolv1beta1.PriorityLevelConfigurationApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.PriorityLevelConfiguration, err error) {\n\tif priorityLevelConfiguration == nil {\n\t\treturn nil, fmt.Errorf(\"priorityLevelConfiguration provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(priorityLevelConfiguration)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := priorityLevelConfiguration.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"priorityLevelConfiguration.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1beta1.PriorityLevelConfiguration{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":216,"to":243}} {"id":100026975,"name":"FlowSchemas","signature":"func (c *FlowcontrolV1beta2Client) FlowSchemas() FlowSchemaInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/flowcontrol_client.go","code":"func (c *FlowcontrolV1beta2Client) FlowSchemas() FlowSchemaInterface {\n\treturn newFlowSchemas(c)\n}","line":{"from":40,"to":42}} {"id":100026976,"name":"PriorityLevelConfigurations","signature":"func (c *FlowcontrolV1beta2Client) PriorityLevelConfigurations() PriorityLevelConfigurationInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/flowcontrol_client.go","code":"func (c *FlowcontrolV1beta2Client) PriorityLevelConfigurations() PriorityLevelConfigurationInterface {\n\treturn newPriorityLevelConfigurations(c)\n}","line":{"from":44,"to":46}} {"id":100026977,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*FlowcontrolV1beta2Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/flowcontrol_client.go","code":"// NewForConfig creates a new FlowcontrolV1beta2Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*FlowcontrolV1beta2Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":48,"to":61}} {"id":100026978,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*FlowcontrolV1beta2Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/flowcontrol_client.go","code":"// NewForConfigAndClient creates a new FlowcontrolV1beta2Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*FlowcontrolV1beta2Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026FlowcontrolV1beta2Client{client}, nil\n}","line":{"from":63,"to":75}} {"id":100026979,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *FlowcontrolV1beta2Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/flowcontrol_client.go","code":"// NewForConfigOrDie creates a new FlowcontrolV1beta2Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *FlowcontrolV1beta2Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":77,"to":85}} {"id":100026980,"name":"New","signature":"func New(c rest.Interface) *FlowcontrolV1beta2Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/flowcontrol_client.go","code":"// New creates a new FlowcontrolV1beta2Client for the given RESTClient.\nfunc New(c rest.Interface) *FlowcontrolV1beta2Client {\n\treturn \u0026FlowcontrolV1beta2Client{c}\n}","line":{"from":87,"to":90}} {"id":100026981,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/flowcontrol_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta2.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":92,"to":103}} {"id":100026982,"name":"RESTClient","signature":"func (c *FlowcontrolV1beta2Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/flowcontrol_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *FlowcontrolV1beta2Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":105,"to":112}} {"id":100026983,"name":"newFlowSchemas","signature":"func newFlowSchemas(c *FlowcontrolV1beta2Client) *flowSchemas","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/flowschema.go","code":"// newFlowSchemas returns a FlowSchemas\nfunc newFlowSchemas(c *FlowcontrolV1beta2Client) *flowSchemas {\n\treturn \u0026flowSchemas{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":63,"to":68}} {"id":100026984,"name":"Get","signature":"func (c *flowSchemas) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta2.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/flowschema.go","code":"// Get takes name of the flowSchema, and returns the corresponding flowSchema object, and an error if there is any.\nfunc (c *flowSchemas) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta2.FlowSchema, err error) {\n\tresult = \u0026v1beta2.FlowSchema{}\n\terr = c.client.Get().\n\t\tResource(\"flowschemas\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":80}} {"id":100026985,"name":"List","signature":"func (c *flowSchemas) List(ctx context.Context, opts v1.ListOptions) (result *v1beta2.FlowSchemaList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/flowschema.go","code":"// List takes label and field selectors, and returns the list of FlowSchemas that match those selectors.\nfunc (c *flowSchemas) List(ctx context.Context, opts v1.ListOptions) (result *v1beta2.FlowSchemaList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta2.FlowSchemaList{}\n\terr = c.client.Get().\n\t\tResource(\"flowschemas\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":82,"to":96}} {"id":100026986,"name":"Watch","signature":"func (c *flowSchemas) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/flowschema.go","code":"// Watch returns a watch.Interface that watches the requested flowSchemas.\nfunc (c *flowSchemas) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"flowschemas\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":98,"to":110}} {"id":100026987,"name":"Create","signature":"func (c *flowSchemas) Create(ctx context.Context, flowSchema *v1beta2.FlowSchema, opts v1.CreateOptions) (result *v1beta2.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/flowschema.go","code":"// Create takes the representation of a flowSchema and creates it. Returns the server's representation of the flowSchema, and an error, if there is any.\nfunc (c *flowSchemas) Create(ctx context.Context, flowSchema *v1beta2.FlowSchema, opts v1.CreateOptions) (result *v1beta2.FlowSchema, err error) {\n\tresult = \u0026v1beta2.FlowSchema{}\n\terr = c.client.Post().\n\t\tResource(\"flowschemas\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(flowSchema).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":112,"to":122}} {"id":100026988,"name":"Update","signature":"func (c *flowSchemas) Update(ctx context.Context, flowSchema *v1beta2.FlowSchema, opts v1.UpdateOptions) (result *v1beta2.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/flowschema.go","code":"// Update takes the representation of a flowSchema and updates it. Returns the server's representation of the flowSchema, and an error, if there is any.\nfunc (c *flowSchemas) Update(ctx context.Context, flowSchema *v1beta2.FlowSchema, opts v1.UpdateOptions) (result *v1beta2.FlowSchema, err error) {\n\tresult = \u0026v1beta2.FlowSchema{}\n\terr = c.client.Put().\n\t\tResource(\"flowschemas\").\n\t\tName(flowSchema.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(flowSchema).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":124,"to":135}} {"id":100026989,"name":"UpdateStatus","signature":"func (c *flowSchemas) UpdateStatus(ctx context.Context, flowSchema *v1beta2.FlowSchema, opts v1.UpdateOptions) (result *v1beta2.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/flowschema.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *flowSchemas) UpdateStatus(ctx context.Context, flowSchema *v1beta2.FlowSchema, opts v1.UpdateOptions) (result *v1beta2.FlowSchema, err error) {\n\tresult = \u0026v1beta2.FlowSchema{}\n\terr = c.client.Put().\n\t\tResource(\"flowschemas\").\n\t\tName(flowSchema.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(flowSchema).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":137,"to":150}} {"id":100026990,"name":"Delete","signature":"func (c *flowSchemas) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/flowschema.go","code":"// Delete takes name of the flowSchema and deletes it. Returns an error if one occurs.\nfunc (c *flowSchemas) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"flowschemas\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":152,"to":160}} {"id":100026991,"name":"DeleteCollection","signature":"func (c *flowSchemas) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/flowschema.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *flowSchemas) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"flowschemas\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":162,"to":175}} {"id":100026992,"name":"Patch","signature":"func (c *flowSchemas) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta2.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/flowschema.go","code":"// Patch applies the patch and returns the patched flowSchema.\nfunc (c *flowSchemas) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta2.FlowSchema, err error) {\n\tresult = \u0026v1beta2.FlowSchema{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"flowschemas\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":177,"to":189}} {"id":100026993,"name":"Apply","signature":"func (c *flowSchemas) Apply(ctx context.Context, flowSchema *flowcontrolv1beta2.FlowSchemaApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/flowschema.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied flowSchema.\nfunc (c *flowSchemas) Apply(ctx context.Context, flowSchema *flowcontrolv1beta2.FlowSchemaApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.FlowSchema, err error) {\n\tif flowSchema == nil {\n\t\treturn nil, fmt.Errorf(\"flowSchema provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(flowSchema)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := flowSchema.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"flowSchema.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta2.FlowSchema{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"flowschemas\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":191,"to":214}} {"id":100026994,"name":"ApplyStatus","signature":"func (c *flowSchemas) ApplyStatus(ctx context.Context, flowSchema *flowcontrolv1beta2.FlowSchemaApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/flowschema.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *flowSchemas) ApplyStatus(ctx context.Context, flowSchema *flowcontrolv1beta2.FlowSchemaApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.FlowSchema, err error) {\n\tif flowSchema == nil {\n\t\treturn nil, fmt.Errorf(\"flowSchema provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(flowSchema)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := flowSchema.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"flowSchema.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1beta2.FlowSchema{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"flowschemas\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":216,"to":243}} {"id":100026995,"name":"newPriorityLevelConfigurations","signature":"func newPriorityLevelConfigurations(c *FlowcontrolV1beta2Client) *priorityLevelConfigurations","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// newPriorityLevelConfigurations returns a PriorityLevelConfigurations\nfunc newPriorityLevelConfigurations(c *FlowcontrolV1beta2Client) *priorityLevelConfigurations {\n\treturn \u0026priorityLevelConfigurations{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":63,"to":68}} {"id":100026996,"name":"Get","signature":"func (c *priorityLevelConfigurations) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta2.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// Get takes name of the priorityLevelConfiguration, and returns the corresponding priorityLevelConfiguration object, and an error if there is any.\nfunc (c *priorityLevelConfigurations) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta2.PriorityLevelConfiguration, err error) {\n\tresult = \u0026v1beta2.PriorityLevelConfiguration{}\n\terr = c.client.Get().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":80}} {"id":100026997,"name":"List","signature":"func (c *priorityLevelConfigurations) List(ctx context.Context, opts v1.ListOptions) (result *v1beta2.PriorityLevelConfigurationList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// List takes label and field selectors, and returns the list of PriorityLevelConfigurations that match those selectors.\nfunc (c *priorityLevelConfigurations) List(ctx context.Context, opts v1.ListOptions) (result *v1beta2.PriorityLevelConfigurationList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta2.PriorityLevelConfigurationList{}\n\terr = c.client.Get().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":82,"to":96}} {"id":100026998,"name":"Watch","signature":"func (c *priorityLevelConfigurations) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// Watch returns a watch.Interface that watches the requested priorityLevelConfigurations.\nfunc (c *priorityLevelConfigurations) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":98,"to":110}} {"id":100026999,"name":"Create","signature":"func (c *priorityLevelConfigurations) Create(ctx context.Context, priorityLevelConfiguration *v1beta2.PriorityLevelConfiguration, opts v1.CreateOptions) (result *v1beta2.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// Create takes the representation of a priorityLevelConfiguration and creates it. Returns the server's representation of the priorityLevelConfiguration, and an error, if there is any.\nfunc (c *priorityLevelConfigurations) Create(ctx context.Context, priorityLevelConfiguration *v1beta2.PriorityLevelConfiguration, opts v1.CreateOptions) (result *v1beta2.PriorityLevelConfiguration, err error) {\n\tresult = \u0026v1beta2.PriorityLevelConfiguration{}\n\terr = c.client.Post().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(priorityLevelConfiguration).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":112,"to":122}} {"id":100027000,"name":"Update","signature":"func (c *priorityLevelConfigurations) Update(ctx context.Context, priorityLevelConfiguration *v1beta2.PriorityLevelConfiguration, opts v1.UpdateOptions) (result *v1beta2.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// Update takes the representation of a priorityLevelConfiguration and updates it. Returns the server's representation of the priorityLevelConfiguration, and an error, if there is any.\nfunc (c *priorityLevelConfigurations) Update(ctx context.Context, priorityLevelConfiguration *v1beta2.PriorityLevelConfiguration, opts v1.UpdateOptions) (result *v1beta2.PriorityLevelConfiguration, err error) {\n\tresult = \u0026v1beta2.PriorityLevelConfiguration{}\n\terr = c.client.Put().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(priorityLevelConfiguration.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(priorityLevelConfiguration).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":124,"to":135}} {"id":100027001,"name":"UpdateStatus","signature":"func (c *priorityLevelConfigurations) UpdateStatus(ctx context.Context, priorityLevelConfiguration *v1beta2.PriorityLevelConfiguration, opts v1.UpdateOptions) (result *v1beta2.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *priorityLevelConfigurations) UpdateStatus(ctx context.Context, priorityLevelConfiguration *v1beta2.PriorityLevelConfiguration, opts v1.UpdateOptions) (result *v1beta2.PriorityLevelConfiguration, err error) {\n\tresult = \u0026v1beta2.PriorityLevelConfiguration{}\n\terr = c.client.Put().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(priorityLevelConfiguration.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(priorityLevelConfiguration).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":137,"to":150}} {"id":100027002,"name":"Delete","signature":"func (c *priorityLevelConfigurations) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// Delete takes name of the priorityLevelConfiguration and deletes it. Returns an error if one occurs.\nfunc (c *priorityLevelConfigurations) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":152,"to":160}} {"id":100027003,"name":"DeleteCollection","signature":"func (c *priorityLevelConfigurations) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *priorityLevelConfigurations) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":162,"to":175}} {"id":100027004,"name":"Patch","signature":"func (c *priorityLevelConfigurations) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta2.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// Patch applies the patch and returns the patched priorityLevelConfiguration.\nfunc (c *priorityLevelConfigurations) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta2.PriorityLevelConfiguration, err error) {\n\tresult = \u0026v1beta2.PriorityLevelConfiguration{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":177,"to":189}} {"id":100027005,"name":"Apply","signature":"func (c *priorityLevelConfigurations) Apply(ctx context.Context, priorityLevelConfiguration *flowcontrolv1beta2.PriorityLevelConfigurationApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied priorityLevelConfiguration.\nfunc (c *priorityLevelConfigurations) Apply(ctx context.Context, priorityLevelConfiguration *flowcontrolv1beta2.PriorityLevelConfigurationApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.PriorityLevelConfiguration, err error) {\n\tif priorityLevelConfiguration == nil {\n\t\treturn nil, fmt.Errorf(\"priorityLevelConfiguration provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(priorityLevelConfiguration)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := priorityLevelConfiguration.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"priorityLevelConfiguration.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta2.PriorityLevelConfiguration{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":191,"to":214}} {"id":100027006,"name":"ApplyStatus","signature":"func (c *priorityLevelConfigurations) ApplyStatus(ctx context.Context, priorityLevelConfiguration *flowcontrolv1beta2.PriorityLevelConfigurationApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *priorityLevelConfigurations) ApplyStatus(ctx context.Context, priorityLevelConfiguration *flowcontrolv1beta2.PriorityLevelConfigurationApplyConfiguration, opts v1.ApplyOptions) (result *v1beta2.PriorityLevelConfiguration, err error) {\n\tif priorityLevelConfiguration == nil {\n\t\treturn nil, fmt.Errorf(\"priorityLevelConfiguration provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(priorityLevelConfiguration)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := priorityLevelConfiguration.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"priorityLevelConfiguration.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1beta2.PriorityLevelConfiguration{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":216,"to":243}} {"id":100027007,"name":"FlowSchemas","signature":"func (c *FlowcontrolV1beta3Client) FlowSchemas() FlowSchemaInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/flowcontrol_client.go","code":"func (c *FlowcontrolV1beta3Client) FlowSchemas() FlowSchemaInterface {\n\treturn newFlowSchemas(c)\n}","line":{"from":40,"to":42}} {"id":100027008,"name":"PriorityLevelConfigurations","signature":"func (c *FlowcontrolV1beta3Client) PriorityLevelConfigurations() PriorityLevelConfigurationInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/flowcontrol_client.go","code":"func (c *FlowcontrolV1beta3Client) PriorityLevelConfigurations() PriorityLevelConfigurationInterface {\n\treturn newPriorityLevelConfigurations(c)\n}","line":{"from":44,"to":46}} {"id":100027009,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*FlowcontrolV1beta3Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/flowcontrol_client.go","code":"// NewForConfig creates a new FlowcontrolV1beta3Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*FlowcontrolV1beta3Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":48,"to":61}} {"id":100027010,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*FlowcontrolV1beta3Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/flowcontrol_client.go","code":"// NewForConfigAndClient creates a new FlowcontrolV1beta3Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*FlowcontrolV1beta3Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026FlowcontrolV1beta3Client{client}, nil\n}","line":{"from":63,"to":75}} {"id":100027011,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *FlowcontrolV1beta3Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/flowcontrol_client.go","code":"// NewForConfigOrDie creates a new FlowcontrolV1beta3Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *FlowcontrolV1beta3Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":77,"to":85}} {"id":100027012,"name":"New","signature":"func New(c rest.Interface) *FlowcontrolV1beta3Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/flowcontrol_client.go","code":"// New creates a new FlowcontrolV1beta3Client for the given RESTClient.\nfunc New(c rest.Interface) *FlowcontrolV1beta3Client {\n\treturn \u0026FlowcontrolV1beta3Client{c}\n}","line":{"from":87,"to":90}} {"id":100027013,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/flowcontrol_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta3.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":92,"to":103}} {"id":100027014,"name":"RESTClient","signature":"func (c *FlowcontrolV1beta3Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/flowcontrol_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *FlowcontrolV1beta3Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":105,"to":112}} {"id":100027015,"name":"newFlowSchemas","signature":"func newFlowSchemas(c *FlowcontrolV1beta3Client) *flowSchemas","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/flowschema.go","code":"// newFlowSchemas returns a FlowSchemas\nfunc newFlowSchemas(c *FlowcontrolV1beta3Client) *flowSchemas {\n\treturn \u0026flowSchemas{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":63,"to":68}} {"id":100027016,"name":"Get","signature":"func (c *flowSchemas) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta3.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/flowschema.go","code":"// Get takes name of the flowSchema, and returns the corresponding flowSchema object, and an error if there is any.\nfunc (c *flowSchemas) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta3.FlowSchema, err error) {\n\tresult = \u0026v1beta3.FlowSchema{}\n\terr = c.client.Get().\n\t\tResource(\"flowschemas\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":80}} {"id":100027017,"name":"List","signature":"func (c *flowSchemas) List(ctx context.Context, opts v1.ListOptions) (result *v1beta3.FlowSchemaList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/flowschema.go","code":"// List takes label and field selectors, and returns the list of FlowSchemas that match those selectors.\nfunc (c *flowSchemas) List(ctx context.Context, opts v1.ListOptions) (result *v1beta3.FlowSchemaList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta3.FlowSchemaList{}\n\terr = c.client.Get().\n\t\tResource(\"flowschemas\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":82,"to":96}} {"id":100027018,"name":"Watch","signature":"func (c *flowSchemas) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/flowschema.go","code":"// Watch returns a watch.Interface that watches the requested flowSchemas.\nfunc (c *flowSchemas) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"flowschemas\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":98,"to":110}} {"id":100027019,"name":"Create","signature":"func (c *flowSchemas) Create(ctx context.Context, flowSchema *v1beta3.FlowSchema, opts v1.CreateOptions) (result *v1beta3.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/flowschema.go","code":"// Create takes the representation of a flowSchema and creates it. Returns the server's representation of the flowSchema, and an error, if there is any.\nfunc (c *flowSchemas) Create(ctx context.Context, flowSchema *v1beta3.FlowSchema, opts v1.CreateOptions) (result *v1beta3.FlowSchema, err error) {\n\tresult = \u0026v1beta3.FlowSchema{}\n\terr = c.client.Post().\n\t\tResource(\"flowschemas\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(flowSchema).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":112,"to":122}} {"id":100027020,"name":"Update","signature":"func (c *flowSchemas) Update(ctx context.Context, flowSchema *v1beta3.FlowSchema, opts v1.UpdateOptions) (result *v1beta3.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/flowschema.go","code":"// Update takes the representation of a flowSchema and updates it. Returns the server's representation of the flowSchema, and an error, if there is any.\nfunc (c *flowSchemas) Update(ctx context.Context, flowSchema *v1beta3.FlowSchema, opts v1.UpdateOptions) (result *v1beta3.FlowSchema, err error) {\n\tresult = \u0026v1beta3.FlowSchema{}\n\terr = c.client.Put().\n\t\tResource(\"flowschemas\").\n\t\tName(flowSchema.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(flowSchema).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":124,"to":135}} {"id":100027021,"name":"UpdateStatus","signature":"func (c *flowSchemas) UpdateStatus(ctx context.Context, flowSchema *v1beta3.FlowSchema, opts v1.UpdateOptions) (result *v1beta3.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/flowschema.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *flowSchemas) UpdateStatus(ctx context.Context, flowSchema *v1beta3.FlowSchema, opts v1.UpdateOptions) (result *v1beta3.FlowSchema, err error) {\n\tresult = \u0026v1beta3.FlowSchema{}\n\terr = c.client.Put().\n\t\tResource(\"flowschemas\").\n\t\tName(flowSchema.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(flowSchema).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":137,"to":150}} {"id":100027022,"name":"Delete","signature":"func (c *flowSchemas) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/flowschema.go","code":"// Delete takes name of the flowSchema and deletes it. Returns an error if one occurs.\nfunc (c *flowSchemas) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"flowschemas\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":152,"to":160}} {"id":100027023,"name":"DeleteCollection","signature":"func (c *flowSchemas) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/flowschema.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *flowSchemas) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"flowschemas\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":162,"to":175}} {"id":100027024,"name":"Patch","signature":"func (c *flowSchemas) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta3.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/flowschema.go","code":"// Patch applies the patch and returns the patched flowSchema.\nfunc (c *flowSchemas) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta3.FlowSchema, err error) {\n\tresult = \u0026v1beta3.FlowSchema{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"flowschemas\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":177,"to":189}} {"id":100027025,"name":"Apply","signature":"func (c *flowSchemas) Apply(ctx context.Context, flowSchema *flowcontrolv1beta3.FlowSchemaApplyConfiguration, opts v1.ApplyOptions) (result *v1beta3.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/flowschema.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied flowSchema.\nfunc (c *flowSchemas) Apply(ctx context.Context, flowSchema *flowcontrolv1beta3.FlowSchemaApplyConfiguration, opts v1.ApplyOptions) (result *v1beta3.FlowSchema, err error) {\n\tif flowSchema == nil {\n\t\treturn nil, fmt.Errorf(\"flowSchema provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(flowSchema)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := flowSchema.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"flowSchema.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta3.FlowSchema{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"flowschemas\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":191,"to":214}} {"id":100027026,"name":"ApplyStatus","signature":"func (c *flowSchemas) ApplyStatus(ctx context.Context, flowSchema *flowcontrolv1beta3.FlowSchemaApplyConfiguration, opts v1.ApplyOptions) (result *v1beta3.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/flowschema.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *flowSchemas) ApplyStatus(ctx context.Context, flowSchema *flowcontrolv1beta3.FlowSchemaApplyConfiguration, opts v1.ApplyOptions) (result *v1beta3.FlowSchema, err error) {\n\tif flowSchema == nil {\n\t\treturn nil, fmt.Errorf(\"flowSchema provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(flowSchema)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := flowSchema.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"flowSchema.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1beta3.FlowSchema{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"flowschemas\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":216,"to":243}} {"id":100027027,"name":"newPriorityLevelConfigurations","signature":"func newPriorityLevelConfigurations(c *FlowcontrolV1beta3Client) *priorityLevelConfigurations","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// newPriorityLevelConfigurations returns a PriorityLevelConfigurations\nfunc newPriorityLevelConfigurations(c *FlowcontrolV1beta3Client) *priorityLevelConfigurations {\n\treturn \u0026priorityLevelConfigurations{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":63,"to":68}} {"id":100027028,"name":"Get","signature":"func (c *priorityLevelConfigurations) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta3.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// Get takes name of the priorityLevelConfiguration, and returns the corresponding priorityLevelConfiguration object, and an error if there is any.\nfunc (c *priorityLevelConfigurations) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta3.PriorityLevelConfiguration, err error) {\n\tresult = \u0026v1beta3.PriorityLevelConfiguration{}\n\terr = c.client.Get().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":80}} {"id":100027029,"name":"List","signature":"func (c *priorityLevelConfigurations) List(ctx context.Context, opts v1.ListOptions) (result *v1beta3.PriorityLevelConfigurationList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// List takes label and field selectors, and returns the list of PriorityLevelConfigurations that match those selectors.\nfunc (c *priorityLevelConfigurations) List(ctx context.Context, opts v1.ListOptions) (result *v1beta3.PriorityLevelConfigurationList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta3.PriorityLevelConfigurationList{}\n\terr = c.client.Get().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":82,"to":96}} {"id":100027030,"name":"Watch","signature":"func (c *priorityLevelConfigurations) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// Watch returns a watch.Interface that watches the requested priorityLevelConfigurations.\nfunc (c *priorityLevelConfigurations) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":98,"to":110}} {"id":100027031,"name":"Create","signature":"func (c *priorityLevelConfigurations) Create(ctx context.Context, priorityLevelConfiguration *v1beta3.PriorityLevelConfiguration, opts v1.CreateOptions) (result *v1beta3.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// Create takes the representation of a priorityLevelConfiguration and creates it. Returns the server's representation of the priorityLevelConfiguration, and an error, if there is any.\nfunc (c *priorityLevelConfigurations) Create(ctx context.Context, priorityLevelConfiguration *v1beta3.PriorityLevelConfiguration, opts v1.CreateOptions) (result *v1beta3.PriorityLevelConfiguration, err error) {\n\tresult = \u0026v1beta3.PriorityLevelConfiguration{}\n\terr = c.client.Post().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(priorityLevelConfiguration).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":112,"to":122}} {"id":100027032,"name":"Update","signature":"func (c *priorityLevelConfigurations) Update(ctx context.Context, priorityLevelConfiguration *v1beta3.PriorityLevelConfiguration, opts v1.UpdateOptions) (result *v1beta3.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// Update takes the representation of a priorityLevelConfiguration and updates it. Returns the server's representation of the priorityLevelConfiguration, and an error, if there is any.\nfunc (c *priorityLevelConfigurations) Update(ctx context.Context, priorityLevelConfiguration *v1beta3.PriorityLevelConfiguration, opts v1.UpdateOptions) (result *v1beta3.PriorityLevelConfiguration, err error) {\n\tresult = \u0026v1beta3.PriorityLevelConfiguration{}\n\terr = c.client.Put().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(priorityLevelConfiguration.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(priorityLevelConfiguration).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":124,"to":135}} {"id":100027033,"name":"UpdateStatus","signature":"func (c *priorityLevelConfigurations) UpdateStatus(ctx context.Context, priorityLevelConfiguration *v1beta3.PriorityLevelConfiguration, opts v1.UpdateOptions) (result *v1beta3.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *priorityLevelConfigurations) UpdateStatus(ctx context.Context, priorityLevelConfiguration *v1beta3.PriorityLevelConfiguration, opts v1.UpdateOptions) (result *v1beta3.PriorityLevelConfiguration, err error) {\n\tresult = \u0026v1beta3.PriorityLevelConfiguration{}\n\terr = c.client.Put().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(priorityLevelConfiguration.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(priorityLevelConfiguration).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":137,"to":150}} {"id":100027034,"name":"Delete","signature":"func (c *priorityLevelConfigurations) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// Delete takes name of the priorityLevelConfiguration and deletes it. Returns an error if one occurs.\nfunc (c *priorityLevelConfigurations) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":152,"to":160}} {"id":100027035,"name":"DeleteCollection","signature":"func (c *priorityLevelConfigurations) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *priorityLevelConfigurations) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":162,"to":175}} {"id":100027036,"name":"Patch","signature":"func (c *priorityLevelConfigurations) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta3.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// Patch applies the patch and returns the patched priorityLevelConfiguration.\nfunc (c *priorityLevelConfigurations) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta3.PriorityLevelConfiguration, err error) {\n\tresult = \u0026v1beta3.PriorityLevelConfiguration{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":177,"to":189}} {"id":100027037,"name":"Apply","signature":"func (c *priorityLevelConfigurations) Apply(ctx context.Context, priorityLevelConfiguration *flowcontrolv1beta3.PriorityLevelConfigurationApplyConfiguration, opts v1.ApplyOptions) (result *v1beta3.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied priorityLevelConfiguration.\nfunc (c *priorityLevelConfigurations) Apply(ctx context.Context, priorityLevelConfiguration *flowcontrolv1beta3.PriorityLevelConfigurationApplyConfiguration, opts v1.ApplyOptions) (result *v1beta3.PriorityLevelConfiguration, err error) {\n\tif priorityLevelConfiguration == nil {\n\t\treturn nil, fmt.Errorf(\"priorityLevelConfiguration provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(priorityLevelConfiguration)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := priorityLevelConfiguration.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"priorityLevelConfiguration.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta3.PriorityLevelConfiguration{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":191,"to":214}} {"id":100027038,"name":"ApplyStatus","signature":"func (c *priorityLevelConfigurations) ApplyStatus(ctx context.Context, priorityLevelConfiguration *flowcontrolv1beta3.PriorityLevelConfigurationApplyConfiguration, opts v1.ApplyOptions) (result *v1beta3.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *priorityLevelConfigurations) ApplyStatus(ctx context.Context, priorityLevelConfiguration *flowcontrolv1beta3.PriorityLevelConfigurationApplyConfiguration, opts v1.ApplyOptions) (result *v1beta3.PriorityLevelConfiguration, err error) {\n\tif priorityLevelConfiguration == nil {\n\t\treturn nil, fmt.Errorf(\"priorityLevelConfiguration provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(priorityLevelConfiguration)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := priorityLevelConfiguration.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"priorityLevelConfiguration.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1beta3.PriorityLevelConfiguration{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"prioritylevelconfigurations\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":216,"to":243}} {"id":100027039,"name":"newIngresses","signature":"func newIngresses(c *NetworkingV1Client, namespace string) *ingresses","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/ingress.go","code":"// newIngresses returns a Ingresses\nfunc newIngresses(c *NetworkingV1Client, namespace string) *ingresses {\n\treturn \u0026ingresses{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":64,"to":70}} {"id":100027040,"name":"Get","signature":"func (c *ingresses) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Ingress, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/ingress.go","code":"// Get takes name of the ingress, and returns the corresponding ingress object, and an error if there is any.\nfunc (c *ingresses) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Ingress, err error) {\n\tresult = \u0026v1.Ingress{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":72,"to":83}} {"id":100027041,"name":"List","signature":"func (c *ingresses) List(ctx context.Context, opts metav1.ListOptions) (result *v1.IngressList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/ingress.go","code":"// List takes label and field selectors, and returns the list of Ingresses that match those selectors.\nfunc (c *ingresses) List(ctx context.Context, opts metav1.ListOptions) (result *v1.IngressList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.IngressList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":85,"to":100}} {"id":100027042,"name":"Watch","signature":"func (c *ingresses) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/ingress.go","code":"// Watch returns a watch.Interface that watches the requested ingresses.\nfunc (c *ingresses) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":102,"to":115}} {"id":100027043,"name":"Create","signature":"func (c *ingresses) Create(ctx context.Context, ingress *v1.Ingress, opts metav1.CreateOptions) (result *v1.Ingress, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/ingress.go","code":"// Create takes the representation of a ingress and creates it. Returns the server's representation of the ingress, and an error, if there is any.\nfunc (c *ingresses) Create(ctx context.Context, ingress *v1.Ingress, opts metav1.CreateOptions) (result *v1.Ingress, err error) {\n\tresult = \u0026v1.Ingress{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(ingress).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":117,"to":128}} {"id":100027044,"name":"Update","signature":"func (c *ingresses) Update(ctx context.Context, ingress *v1.Ingress, opts metav1.UpdateOptions) (result *v1.Ingress, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/ingress.go","code":"// Update takes the representation of a ingress and updates it. Returns the server's representation of the ingress, and an error, if there is any.\nfunc (c *ingresses) Update(ctx context.Context, ingress *v1.Ingress, opts metav1.UpdateOptions) (result *v1.Ingress, err error) {\n\tresult = \u0026v1.Ingress{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tName(ingress.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(ingress).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":130,"to":142}} {"id":100027045,"name":"UpdateStatus","signature":"func (c *ingresses) UpdateStatus(ctx context.Context, ingress *v1.Ingress, opts metav1.UpdateOptions) (result *v1.Ingress, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/ingress.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *ingresses) UpdateStatus(ctx context.Context, ingress *v1.Ingress, opts metav1.UpdateOptions) (result *v1.Ingress, err error) {\n\tresult = \u0026v1.Ingress{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tName(ingress.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(ingress).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":144,"to":158}} {"id":100027046,"name":"Delete","signature":"func (c *ingresses) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/ingress.go","code":"// Delete takes name of the ingress and deletes it. Returns an error if one occurs.\nfunc (c *ingresses) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":160,"to":169}} {"id":100027047,"name":"DeleteCollection","signature":"func (c *ingresses) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/ingress.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *ingresses) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":171,"to":185}} {"id":100027048,"name":"Patch","signature":"func (c *ingresses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Ingress, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/ingress.go","code":"// Patch applies the patch and returns the patched ingress.\nfunc (c *ingresses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Ingress, err error) {\n\tresult = \u0026v1.Ingress{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":187,"to":200}} {"id":100027049,"name":"Apply","signature":"func (c *ingresses) Apply(ctx context.Context, ingress *networkingv1.IngressApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Ingress, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/ingress.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied ingress.\nfunc (c *ingresses) Apply(ctx context.Context, ingress *networkingv1.IngressApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Ingress, err error) {\n\tif ingress == nil {\n\t\treturn nil, fmt.Errorf(\"ingress provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(ingress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := ingress.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"ingress.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.Ingress{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":202,"to":226}} {"id":100027050,"name":"ApplyStatus","signature":"func (c *ingresses) ApplyStatus(ctx context.Context, ingress *networkingv1.IngressApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Ingress, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/ingress.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *ingresses) ApplyStatus(ctx context.Context, ingress *networkingv1.IngressApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Ingress, err error) {\n\tif ingress == nil {\n\t\treturn nil, fmt.Errorf(\"ingress provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(ingress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := ingress.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"ingress.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1.Ingress{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":228,"to":256}} {"id":100027051,"name":"newIngressClasses","signature":"func newIngressClasses(c *NetworkingV1Client) *ingressClasses","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/ingressclass.go","code":"// newIngressClasses returns a IngressClasses\nfunc newIngressClasses(c *NetworkingV1Client) *ingressClasses {\n\treturn \u0026ingressClasses{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100027052,"name":"Get","signature":"func (c *ingressClasses) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.IngressClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/ingressclass.go","code":"// Get takes name of the ingressClass, and returns the corresponding ingressClass object, and an error if there is any.\nfunc (c *ingressClasses) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.IngressClass, err error) {\n\tresult = \u0026v1.IngressClass{}\n\terr = c.client.Get().\n\t\tResource(\"ingressclasses\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100027053,"name":"List","signature":"func (c *ingressClasses) List(ctx context.Context, opts metav1.ListOptions) (result *v1.IngressClassList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/ingressclass.go","code":"// List takes label and field selectors, and returns the list of IngressClasses that match those selectors.\nfunc (c *ingressClasses) List(ctx context.Context, opts metav1.ListOptions) (result *v1.IngressClassList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.IngressClassList{}\n\terr = c.client.Get().\n\t\tResource(\"ingressclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100027054,"name":"Watch","signature":"func (c *ingressClasses) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/ingressclass.go","code":"// Watch returns a watch.Interface that watches the requested ingressClasses.\nfunc (c *ingressClasses) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"ingressclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100027055,"name":"Create","signature":"func (c *ingressClasses) Create(ctx context.Context, ingressClass *v1.IngressClass, opts metav1.CreateOptions) (result *v1.IngressClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/ingressclass.go","code":"// Create takes the representation of a ingressClass and creates it. Returns the server's representation of the ingressClass, and an error, if there is any.\nfunc (c *ingressClasses) Create(ctx context.Context, ingressClass *v1.IngressClass, opts metav1.CreateOptions) (result *v1.IngressClass, err error) {\n\tresult = \u0026v1.IngressClass{}\n\terr = c.client.Post().\n\t\tResource(\"ingressclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(ingressClass).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100027056,"name":"Update","signature":"func (c *ingressClasses) Update(ctx context.Context, ingressClass *v1.IngressClass, opts metav1.UpdateOptions) (result *v1.IngressClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/ingressclass.go","code":"// Update takes the representation of a ingressClass and updates it. Returns the server's representation of the ingressClass, and an error, if there is any.\nfunc (c *ingressClasses) Update(ctx context.Context, ingressClass *v1.IngressClass, opts metav1.UpdateOptions) (result *v1.IngressClass, err error) {\n\tresult = \u0026v1.IngressClass{}\n\terr = c.client.Put().\n\t\tResource(\"ingressclasses\").\n\t\tName(ingressClass.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(ingressClass).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100027057,"name":"Delete","signature":"func (c *ingressClasses) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/ingressclass.go","code":"// Delete takes name of the ingressClass and deletes it. Returns an error if one occurs.\nfunc (c *ingressClasses) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"ingressclasses\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100027058,"name":"DeleteCollection","signature":"func (c *ingressClasses) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/ingressclass.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *ingressClasses) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"ingressclasses\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100027059,"name":"Patch","signature":"func (c *ingressClasses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.IngressClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/ingressclass.go","code":"// Patch applies the patch and returns the patched ingressClass.\nfunc (c *ingressClasses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.IngressClass, err error) {\n\tresult = \u0026v1.IngressClass{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"ingressclasses\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100027060,"name":"Apply","signature":"func (c *ingressClasses) Apply(ctx context.Context, ingressClass *networkingv1.IngressClassApplyConfiguration, opts metav1.ApplyOptions) (result *v1.IngressClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/ingressclass.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied ingressClass.\nfunc (c *ingressClasses) Apply(ctx context.Context, ingressClass *networkingv1.IngressClassApplyConfiguration, opts metav1.ApplyOptions) (result *v1.IngressClass, err error) {\n\tif ingressClass == nil {\n\t\treturn nil, fmt.Errorf(\"ingressClass provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(ingressClass)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := ingressClass.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"ingressClass.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.IngressClass{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"ingressclasses\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100027061,"name":"Ingresses","signature":"func (c *NetworkingV1Client) Ingresses(namespace string) IngressInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/networking_client.go","code":"func (c *NetworkingV1Client) Ingresses(namespace string) IngressInterface {\n\treturn newIngresses(c, namespace)\n}","line":{"from":41,"to":43}} {"id":100027062,"name":"IngressClasses","signature":"func (c *NetworkingV1Client) IngressClasses() IngressClassInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/networking_client.go","code":"func (c *NetworkingV1Client) IngressClasses() IngressClassInterface {\n\treturn newIngressClasses(c)\n}","line":{"from":45,"to":47}} {"id":100027063,"name":"NetworkPolicies","signature":"func (c *NetworkingV1Client) NetworkPolicies(namespace string) NetworkPolicyInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/networking_client.go","code":"func (c *NetworkingV1Client) NetworkPolicies(namespace string) NetworkPolicyInterface {\n\treturn newNetworkPolicies(c, namespace)\n}","line":{"from":49,"to":51}} {"id":100027064,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*NetworkingV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/networking_client.go","code":"// NewForConfig creates a new NetworkingV1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*NetworkingV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":53,"to":66}} {"id":100027065,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*NetworkingV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/networking_client.go","code":"// NewForConfigAndClient creates a new NetworkingV1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*NetworkingV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026NetworkingV1Client{client}, nil\n}","line":{"from":68,"to":80}} {"id":100027066,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *NetworkingV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/networking_client.go","code":"// NewForConfigOrDie creates a new NetworkingV1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *NetworkingV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":82,"to":90}} {"id":100027067,"name":"New","signature":"func New(c rest.Interface) *NetworkingV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/networking_client.go","code":"// New creates a new NetworkingV1Client for the given RESTClient.\nfunc New(c rest.Interface) *NetworkingV1Client {\n\treturn \u0026NetworkingV1Client{c}\n}","line":{"from":92,"to":95}} {"id":100027068,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/networking_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":97,"to":108}} {"id":100027069,"name":"RESTClient","signature":"func (c *NetworkingV1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/networking_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *NetworkingV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":110,"to":117}} {"id":100027070,"name":"newNetworkPolicies","signature":"func newNetworkPolicies(c *NetworkingV1Client, namespace string) *networkPolicies","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/networkpolicy.go","code":"// newNetworkPolicies returns a NetworkPolicies\nfunc newNetworkPolicies(c *NetworkingV1Client, namespace string) *networkPolicies {\n\treturn \u0026networkPolicies{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":64,"to":70}} {"id":100027071,"name":"Get","signature":"func (c *networkPolicies) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.NetworkPolicy, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/networkpolicy.go","code":"// Get takes name of the networkPolicy, and returns the corresponding networkPolicy object, and an error if there is any.\nfunc (c *networkPolicies) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.NetworkPolicy, err error) {\n\tresult = \u0026v1.NetworkPolicy{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"networkpolicies\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":72,"to":83}} {"id":100027072,"name":"List","signature":"func (c *networkPolicies) List(ctx context.Context, opts metav1.ListOptions) (result *v1.NetworkPolicyList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/networkpolicy.go","code":"// List takes label and field selectors, and returns the list of NetworkPolicies that match those selectors.\nfunc (c *networkPolicies) List(ctx context.Context, opts metav1.ListOptions) (result *v1.NetworkPolicyList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.NetworkPolicyList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"networkpolicies\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":85,"to":100}} {"id":100027073,"name":"Watch","signature":"func (c *networkPolicies) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/networkpolicy.go","code":"// Watch returns a watch.Interface that watches the requested networkPolicies.\nfunc (c *networkPolicies) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"networkpolicies\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":102,"to":115}} {"id":100027074,"name":"Create","signature":"func (c *networkPolicies) Create(ctx context.Context, networkPolicy *v1.NetworkPolicy, opts metav1.CreateOptions) (result *v1.NetworkPolicy, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/networkpolicy.go","code":"// Create takes the representation of a networkPolicy and creates it. Returns the server's representation of the networkPolicy, and an error, if there is any.\nfunc (c *networkPolicies) Create(ctx context.Context, networkPolicy *v1.NetworkPolicy, opts metav1.CreateOptions) (result *v1.NetworkPolicy, err error) {\n\tresult = \u0026v1.NetworkPolicy{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"networkpolicies\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(networkPolicy).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":117,"to":128}} {"id":100027075,"name":"Update","signature":"func (c *networkPolicies) Update(ctx context.Context, networkPolicy *v1.NetworkPolicy, opts metav1.UpdateOptions) (result *v1.NetworkPolicy, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/networkpolicy.go","code":"// Update takes the representation of a networkPolicy and updates it. Returns the server's representation of the networkPolicy, and an error, if there is any.\nfunc (c *networkPolicies) Update(ctx context.Context, networkPolicy *v1.NetworkPolicy, opts metav1.UpdateOptions) (result *v1.NetworkPolicy, err error) {\n\tresult = \u0026v1.NetworkPolicy{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"networkpolicies\").\n\t\tName(networkPolicy.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(networkPolicy).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":130,"to":142}} {"id":100027076,"name":"UpdateStatus","signature":"func (c *networkPolicies) UpdateStatus(ctx context.Context, networkPolicy *v1.NetworkPolicy, opts metav1.UpdateOptions) (result *v1.NetworkPolicy, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/networkpolicy.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *networkPolicies) UpdateStatus(ctx context.Context, networkPolicy *v1.NetworkPolicy, opts metav1.UpdateOptions) (result *v1.NetworkPolicy, err error) {\n\tresult = \u0026v1.NetworkPolicy{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"networkpolicies\").\n\t\tName(networkPolicy.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(networkPolicy).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":144,"to":158}} {"id":100027077,"name":"Delete","signature":"func (c *networkPolicies) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/networkpolicy.go","code":"// Delete takes name of the networkPolicy and deletes it. Returns an error if one occurs.\nfunc (c *networkPolicies) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"networkpolicies\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":160,"to":169}} {"id":100027078,"name":"DeleteCollection","signature":"func (c *networkPolicies) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/networkpolicy.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *networkPolicies) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"networkpolicies\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":171,"to":185}} {"id":100027079,"name":"Patch","signature":"func (c *networkPolicies) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.NetworkPolicy, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/networkpolicy.go","code":"// Patch applies the patch and returns the patched networkPolicy.\nfunc (c *networkPolicies) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.NetworkPolicy, err error) {\n\tresult = \u0026v1.NetworkPolicy{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"networkpolicies\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":187,"to":200}} {"id":100027080,"name":"Apply","signature":"func (c *networkPolicies) Apply(ctx context.Context, networkPolicy *networkingv1.NetworkPolicyApplyConfiguration, opts metav1.ApplyOptions) (result *v1.NetworkPolicy, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/networkpolicy.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied networkPolicy.\nfunc (c *networkPolicies) Apply(ctx context.Context, networkPolicy *networkingv1.NetworkPolicyApplyConfiguration, opts metav1.ApplyOptions) (result *v1.NetworkPolicy, err error) {\n\tif networkPolicy == nil {\n\t\treturn nil, fmt.Errorf(\"networkPolicy provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(networkPolicy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := networkPolicy.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"networkPolicy.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.NetworkPolicy{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"networkpolicies\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":202,"to":226}} {"id":100027081,"name":"ApplyStatus","signature":"func (c *networkPolicies) ApplyStatus(ctx context.Context, networkPolicy *networkingv1.NetworkPolicyApplyConfiguration, opts metav1.ApplyOptions) (result *v1.NetworkPolicy, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1/networkpolicy.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *networkPolicies) ApplyStatus(ctx context.Context, networkPolicy *networkingv1.NetworkPolicyApplyConfiguration, opts metav1.ApplyOptions) (result *v1.NetworkPolicy, err error) {\n\tif networkPolicy == nil {\n\t\treturn nil, fmt.Errorf(\"networkPolicy provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(networkPolicy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := networkPolicy.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"networkPolicy.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1.NetworkPolicy{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"networkpolicies\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":228,"to":256}} {"id":100027082,"name":"newClusterCIDRs","signature":"func newClusterCIDRs(c *NetworkingV1alpha1Client) *clusterCIDRs","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/clustercidr.go","code":"// newClusterCIDRs returns a ClusterCIDRs\nfunc newClusterCIDRs(c *NetworkingV1alpha1Client) *clusterCIDRs {\n\treturn \u0026clusterCIDRs{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100027083,"name":"Get","signature":"func (c *clusterCIDRs) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.ClusterCIDR, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/clustercidr.go","code":"// Get takes name of the clusterCIDR, and returns the corresponding clusterCIDR object, and an error if there is any.\nfunc (c *clusterCIDRs) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.ClusterCIDR, err error) {\n\tresult = \u0026v1alpha1.ClusterCIDR{}\n\terr = c.client.Get().\n\t\tResource(\"clustercidrs\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100027084,"name":"List","signature":"func (c *clusterCIDRs) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.ClusterCIDRList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/clustercidr.go","code":"// List takes label and field selectors, and returns the list of ClusterCIDRs that match those selectors.\nfunc (c *clusterCIDRs) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.ClusterCIDRList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1alpha1.ClusterCIDRList{}\n\terr = c.client.Get().\n\t\tResource(\"clustercidrs\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100027085,"name":"Watch","signature":"func (c *clusterCIDRs) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/clustercidr.go","code":"// Watch returns a watch.Interface that watches the requested clusterCIDRs.\nfunc (c *clusterCIDRs) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"clustercidrs\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100027086,"name":"Create","signature":"func (c *clusterCIDRs) Create(ctx context.Context, clusterCIDR *v1alpha1.ClusterCIDR, opts v1.CreateOptions) (result *v1alpha1.ClusterCIDR, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/clustercidr.go","code":"// Create takes the representation of a clusterCIDR and creates it. Returns the server's representation of the clusterCIDR, and an error, if there is any.\nfunc (c *clusterCIDRs) Create(ctx context.Context, clusterCIDR *v1alpha1.ClusterCIDR, opts v1.CreateOptions) (result *v1alpha1.ClusterCIDR, err error) {\n\tresult = \u0026v1alpha1.ClusterCIDR{}\n\terr = c.client.Post().\n\t\tResource(\"clustercidrs\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(clusterCIDR).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100027087,"name":"Update","signature":"func (c *clusterCIDRs) Update(ctx context.Context, clusterCIDR *v1alpha1.ClusterCIDR, opts v1.UpdateOptions) (result *v1alpha1.ClusterCIDR, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/clustercidr.go","code":"// Update takes the representation of a clusterCIDR and updates it. Returns the server's representation of the clusterCIDR, and an error, if there is any.\nfunc (c *clusterCIDRs) Update(ctx context.Context, clusterCIDR *v1alpha1.ClusterCIDR, opts v1.UpdateOptions) (result *v1alpha1.ClusterCIDR, err error) {\n\tresult = \u0026v1alpha1.ClusterCIDR{}\n\terr = c.client.Put().\n\t\tResource(\"clustercidrs\").\n\t\tName(clusterCIDR.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(clusterCIDR).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100027088,"name":"Delete","signature":"func (c *clusterCIDRs) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/clustercidr.go","code":"// Delete takes name of the clusterCIDR and deletes it. Returns an error if one occurs.\nfunc (c *clusterCIDRs) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"clustercidrs\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100027089,"name":"DeleteCollection","signature":"func (c *clusterCIDRs) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/clustercidr.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *clusterCIDRs) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"clustercidrs\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100027090,"name":"Patch","signature":"func (c *clusterCIDRs) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.ClusterCIDR, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/clustercidr.go","code":"// Patch applies the patch and returns the patched clusterCIDR.\nfunc (c *clusterCIDRs) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.ClusterCIDR, err error) {\n\tresult = \u0026v1alpha1.ClusterCIDR{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"clustercidrs\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100027091,"name":"Apply","signature":"func (c *clusterCIDRs) Apply(ctx context.Context, clusterCIDR *networkingv1alpha1.ClusterCIDRApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.ClusterCIDR, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/clustercidr.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied clusterCIDR.\nfunc (c *clusterCIDRs) Apply(ctx context.Context, clusterCIDR *networkingv1alpha1.ClusterCIDRApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.ClusterCIDR, err error) {\n\tif clusterCIDR == nil {\n\t\treturn nil, fmt.Errorf(\"clusterCIDR provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(clusterCIDR)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := clusterCIDR.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"clusterCIDR.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1alpha1.ClusterCIDR{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"clustercidrs\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100027092,"name":"newIPAddresses","signature":"func newIPAddresses(c *NetworkingV1alpha1Client) *iPAddresses","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/ipaddress.go","code":"// newIPAddresses returns a IPAddresses\nfunc newIPAddresses(c *NetworkingV1alpha1Client) *iPAddresses {\n\treturn \u0026iPAddresses{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100027093,"name":"Get","signature":"func (c *iPAddresses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.IPAddress, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/ipaddress.go","code":"// Get takes name of the iPAddress, and returns the corresponding iPAddress object, and an error if there is any.\nfunc (c *iPAddresses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.IPAddress, err error) {\n\tresult = \u0026v1alpha1.IPAddress{}\n\terr = c.client.Get().\n\t\tResource(\"ipaddresses\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100027094,"name":"List","signature":"func (c *iPAddresses) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.IPAddressList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/ipaddress.go","code":"// List takes label and field selectors, and returns the list of IPAddresses that match those selectors.\nfunc (c *iPAddresses) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.IPAddressList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1alpha1.IPAddressList{}\n\terr = c.client.Get().\n\t\tResource(\"ipaddresses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100027095,"name":"Watch","signature":"func (c *iPAddresses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/ipaddress.go","code":"// Watch returns a watch.Interface that watches the requested iPAddresses.\nfunc (c *iPAddresses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"ipaddresses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100027096,"name":"Create","signature":"func (c *iPAddresses) Create(ctx context.Context, iPAddress *v1alpha1.IPAddress, opts v1.CreateOptions) (result *v1alpha1.IPAddress, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/ipaddress.go","code":"// Create takes the representation of a iPAddress and creates it. Returns the server's representation of the iPAddress, and an error, if there is any.\nfunc (c *iPAddresses) Create(ctx context.Context, iPAddress *v1alpha1.IPAddress, opts v1.CreateOptions) (result *v1alpha1.IPAddress, err error) {\n\tresult = \u0026v1alpha1.IPAddress{}\n\terr = c.client.Post().\n\t\tResource(\"ipaddresses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(iPAddress).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100027097,"name":"Update","signature":"func (c *iPAddresses) Update(ctx context.Context, iPAddress *v1alpha1.IPAddress, opts v1.UpdateOptions) (result *v1alpha1.IPAddress, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/ipaddress.go","code":"// Update takes the representation of a iPAddress and updates it. Returns the server's representation of the iPAddress, and an error, if there is any.\nfunc (c *iPAddresses) Update(ctx context.Context, iPAddress *v1alpha1.IPAddress, opts v1.UpdateOptions) (result *v1alpha1.IPAddress, err error) {\n\tresult = \u0026v1alpha1.IPAddress{}\n\terr = c.client.Put().\n\t\tResource(\"ipaddresses\").\n\t\tName(iPAddress.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(iPAddress).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100027098,"name":"Delete","signature":"func (c *iPAddresses) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/ipaddress.go","code":"// Delete takes name of the iPAddress and deletes it. Returns an error if one occurs.\nfunc (c *iPAddresses) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"ipaddresses\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100027099,"name":"DeleteCollection","signature":"func (c *iPAddresses) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/ipaddress.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *iPAddresses) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"ipaddresses\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100027100,"name":"Patch","signature":"func (c *iPAddresses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.IPAddress, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/ipaddress.go","code":"// Patch applies the patch and returns the patched iPAddress.\nfunc (c *iPAddresses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.IPAddress, err error) {\n\tresult = \u0026v1alpha1.IPAddress{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"ipaddresses\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100027101,"name":"Apply","signature":"func (c *iPAddresses) Apply(ctx context.Context, iPAddress *networkingv1alpha1.IPAddressApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.IPAddress, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/ipaddress.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied iPAddress.\nfunc (c *iPAddresses) Apply(ctx context.Context, iPAddress *networkingv1alpha1.IPAddressApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.IPAddress, err error) {\n\tif iPAddress == nil {\n\t\treturn nil, fmt.Errorf(\"iPAddress provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(iPAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := iPAddress.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"iPAddress.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1alpha1.IPAddress{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"ipaddresses\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100027102,"name":"ClusterCIDRs","signature":"func (c *NetworkingV1alpha1Client) ClusterCIDRs() ClusterCIDRInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/networking_client.go","code":"func (c *NetworkingV1alpha1Client) ClusterCIDRs() ClusterCIDRInterface {\n\treturn newClusterCIDRs(c)\n}","line":{"from":40,"to":42}} {"id":100027103,"name":"IPAddresses","signature":"func (c *NetworkingV1alpha1Client) IPAddresses() IPAddressInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/networking_client.go","code":"func (c *NetworkingV1alpha1Client) IPAddresses() IPAddressInterface {\n\treturn newIPAddresses(c)\n}","line":{"from":44,"to":46}} {"id":100027104,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*NetworkingV1alpha1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/networking_client.go","code":"// NewForConfig creates a new NetworkingV1alpha1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*NetworkingV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":48,"to":61}} {"id":100027105,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*NetworkingV1alpha1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/networking_client.go","code":"// NewForConfigAndClient creates a new NetworkingV1alpha1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*NetworkingV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026NetworkingV1alpha1Client{client}, nil\n}","line":{"from":63,"to":75}} {"id":100027106,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *NetworkingV1alpha1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/networking_client.go","code":"// NewForConfigOrDie creates a new NetworkingV1alpha1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *NetworkingV1alpha1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":77,"to":85}} {"id":100027107,"name":"New","signature":"func New(c rest.Interface) *NetworkingV1alpha1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/networking_client.go","code":"// New creates a new NetworkingV1alpha1Client for the given RESTClient.\nfunc New(c rest.Interface) *NetworkingV1alpha1Client {\n\treturn \u0026NetworkingV1alpha1Client{c}\n}","line":{"from":87,"to":90}} {"id":100027108,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/networking_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1alpha1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":92,"to":103}} {"id":100027109,"name":"RESTClient","signature":"func (c *NetworkingV1alpha1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1alpha1/networking_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *NetworkingV1alpha1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":105,"to":112}} {"id":100027110,"name":"newIngresses","signature":"func newIngresses(c *NetworkingV1beta1Client, namespace string) *ingresses","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/ingress.go","code":"// newIngresses returns a Ingresses\nfunc newIngresses(c *NetworkingV1beta1Client, namespace string) *ingresses {\n\treturn \u0026ingresses{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":64,"to":70}} {"id":100027111,"name":"Get","signature":"func (c *ingresses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.Ingress, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/ingress.go","code":"// Get takes name of the ingress, and returns the corresponding ingress object, and an error if there is any.\nfunc (c *ingresses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.Ingress, err error) {\n\tresult = \u0026v1beta1.Ingress{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":72,"to":83}} {"id":100027112,"name":"List","signature":"func (c *ingresses) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.IngressList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/ingress.go","code":"// List takes label and field selectors, and returns the list of Ingresses that match those selectors.\nfunc (c *ingresses) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.IngressList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.IngressList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":85,"to":100}} {"id":100027113,"name":"Watch","signature":"func (c *ingresses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/ingress.go","code":"// Watch returns a watch.Interface that watches the requested ingresses.\nfunc (c *ingresses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":102,"to":115}} {"id":100027114,"name":"Create","signature":"func (c *ingresses) Create(ctx context.Context, ingress *v1beta1.Ingress, opts v1.CreateOptions) (result *v1beta1.Ingress, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/ingress.go","code":"// Create takes the representation of a ingress and creates it. Returns the server's representation of the ingress, and an error, if there is any.\nfunc (c *ingresses) Create(ctx context.Context, ingress *v1beta1.Ingress, opts v1.CreateOptions) (result *v1beta1.Ingress, err error) {\n\tresult = \u0026v1beta1.Ingress{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(ingress).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":117,"to":128}} {"id":100027115,"name":"Update","signature":"func (c *ingresses) Update(ctx context.Context, ingress *v1beta1.Ingress, opts v1.UpdateOptions) (result *v1beta1.Ingress, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/ingress.go","code":"// Update takes the representation of a ingress and updates it. Returns the server's representation of the ingress, and an error, if there is any.\nfunc (c *ingresses) Update(ctx context.Context, ingress *v1beta1.Ingress, opts v1.UpdateOptions) (result *v1beta1.Ingress, err error) {\n\tresult = \u0026v1beta1.Ingress{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tName(ingress.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(ingress).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":130,"to":142}} {"id":100027116,"name":"UpdateStatus","signature":"func (c *ingresses) UpdateStatus(ctx context.Context, ingress *v1beta1.Ingress, opts v1.UpdateOptions) (result *v1beta1.Ingress, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/ingress.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *ingresses) UpdateStatus(ctx context.Context, ingress *v1beta1.Ingress, opts v1.UpdateOptions) (result *v1beta1.Ingress, err error) {\n\tresult = \u0026v1beta1.Ingress{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tName(ingress.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(ingress).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":144,"to":158}} {"id":100027117,"name":"Delete","signature":"func (c *ingresses) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/ingress.go","code":"// Delete takes name of the ingress and deletes it. Returns an error if one occurs.\nfunc (c *ingresses) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":160,"to":169}} {"id":100027118,"name":"DeleteCollection","signature":"func (c *ingresses) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/ingress.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *ingresses) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":171,"to":185}} {"id":100027119,"name":"Patch","signature":"func (c *ingresses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.Ingress, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/ingress.go","code":"// Patch applies the patch and returns the patched ingress.\nfunc (c *ingresses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.Ingress, err error) {\n\tresult = \u0026v1beta1.Ingress{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":187,"to":200}} {"id":100027120,"name":"Apply","signature":"func (c *ingresses) Apply(ctx context.Context, ingress *networkingv1beta1.IngressApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Ingress, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/ingress.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied ingress.\nfunc (c *ingresses) Apply(ctx context.Context, ingress *networkingv1beta1.IngressApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Ingress, err error) {\n\tif ingress == nil {\n\t\treturn nil, fmt.Errorf(\"ingress provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(ingress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := ingress.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"ingress.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.Ingress{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":202,"to":226}} {"id":100027121,"name":"ApplyStatus","signature":"func (c *ingresses) ApplyStatus(ctx context.Context, ingress *networkingv1beta1.IngressApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Ingress, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/ingress.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *ingresses) ApplyStatus(ctx context.Context, ingress *networkingv1beta1.IngressApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Ingress, err error) {\n\tif ingress == nil {\n\t\treturn nil, fmt.Errorf(\"ingress provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(ingress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := ingress.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"ingress.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1beta1.Ingress{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"ingresses\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":228,"to":256}} {"id":100027122,"name":"newIngressClasses","signature":"func newIngressClasses(c *NetworkingV1beta1Client) *ingressClasses","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/ingressclass.go","code":"// newIngressClasses returns a IngressClasses\nfunc newIngressClasses(c *NetworkingV1beta1Client) *ingressClasses {\n\treturn \u0026ingressClasses{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100027123,"name":"Get","signature":"func (c *ingressClasses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.IngressClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/ingressclass.go","code":"// Get takes name of the ingressClass, and returns the corresponding ingressClass object, and an error if there is any.\nfunc (c *ingressClasses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.IngressClass, err error) {\n\tresult = \u0026v1beta1.IngressClass{}\n\terr = c.client.Get().\n\t\tResource(\"ingressclasses\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100027124,"name":"List","signature":"func (c *ingressClasses) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.IngressClassList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/ingressclass.go","code":"// List takes label and field selectors, and returns the list of IngressClasses that match those selectors.\nfunc (c *ingressClasses) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.IngressClassList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.IngressClassList{}\n\terr = c.client.Get().\n\t\tResource(\"ingressclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100027125,"name":"Watch","signature":"func (c *ingressClasses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/ingressclass.go","code":"// Watch returns a watch.Interface that watches the requested ingressClasses.\nfunc (c *ingressClasses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"ingressclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100027126,"name":"Create","signature":"func (c *ingressClasses) Create(ctx context.Context, ingressClass *v1beta1.IngressClass, opts v1.CreateOptions) (result *v1beta1.IngressClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/ingressclass.go","code":"// Create takes the representation of a ingressClass and creates it. Returns the server's representation of the ingressClass, and an error, if there is any.\nfunc (c *ingressClasses) Create(ctx context.Context, ingressClass *v1beta1.IngressClass, opts v1.CreateOptions) (result *v1beta1.IngressClass, err error) {\n\tresult = \u0026v1beta1.IngressClass{}\n\terr = c.client.Post().\n\t\tResource(\"ingressclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(ingressClass).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100027127,"name":"Update","signature":"func (c *ingressClasses) Update(ctx context.Context, ingressClass *v1beta1.IngressClass, opts v1.UpdateOptions) (result *v1beta1.IngressClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/ingressclass.go","code":"// Update takes the representation of a ingressClass and updates it. Returns the server's representation of the ingressClass, and an error, if there is any.\nfunc (c *ingressClasses) Update(ctx context.Context, ingressClass *v1beta1.IngressClass, opts v1.UpdateOptions) (result *v1beta1.IngressClass, err error) {\n\tresult = \u0026v1beta1.IngressClass{}\n\terr = c.client.Put().\n\t\tResource(\"ingressclasses\").\n\t\tName(ingressClass.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(ingressClass).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100027128,"name":"Delete","signature":"func (c *ingressClasses) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/ingressclass.go","code":"// Delete takes name of the ingressClass and deletes it. Returns an error if one occurs.\nfunc (c *ingressClasses) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"ingressclasses\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100027129,"name":"DeleteCollection","signature":"func (c *ingressClasses) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/ingressclass.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *ingressClasses) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"ingressclasses\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100027130,"name":"Patch","signature":"func (c *ingressClasses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.IngressClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/ingressclass.go","code":"// Patch applies the patch and returns the patched ingressClass.\nfunc (c *ingressClasses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.IngressClass, err error) {\n\tresult = \u0026v1beta1.IngressClass{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"ingressclasses\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100027131,"name":"Apply","signature":"func (c *ingressClasses) Apply(ctx context.Context, ingressClass *networkingv1beta1.IngressClassApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.IngressClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/ingressclass.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied ingressClass.\nfunc (c *ingressClasses) Apply(ctx context.Context, ingressClass *networkingv1beta1.IngressClassApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.IngressClass, err error) {\n\tif ingressClass == nil {\n\t\treturn nil, fmt.Errorf(\"ingressClass provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(ingressClass)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := ingressClass.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"ingressClass.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.IngressClass{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"ingressclasses\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100027132,"name":"Ingresses","signature":"func (c *NetworkingV1beta1Client) Ingresses(namespace string) IngressInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/networking_client.go","code":"func (c *NetworkingV1beta1Client) Ingresses(namespace string) IngressInterface {\n\treturn newIngresses(c, namespace)\n}","line":{"from":40,"to":42}} {"id":100027133,"name":"IngressClasses","signature":"func (c *NetworkingV1beta1Client) IngressClasses() IngressClassInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/networking_client.go","code":"func (c *NetworkingV1beta1Client) IngressClasses() IngressClassInterface {\n\treturn newIngressClasses(c)\n}","line":{"from":44,"to":46}} {"id":100027134,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*NetworkingV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/networking_client.go","code":"// NewForConfig creates a new NetworkingV1beta1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*NetworkingV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":48,"to":61}} {"id":100027135,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*NetworkingV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/networking_client.go","code":"// NewForConfigAndClient creates a new NetworkingV1beta1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*NetworkingV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026NetworkingV1beta1Client{client}, nil\n}","line":{"from":63,"to":75}} {"id":100027136,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *NetworkingV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/networking_client.go","code":"// NewForConfigOrDie creates a new NetworkingV1beta1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *NetworkingV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":77,"to":85}} {"id":100027137,"name":"New","signature":"func New(c rest.Interface) *NetworkingV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/networking_client.go","code":"// New creates a new NetworkingV1beta1Client for the given RESTClient.\nfunc New(c rest.Interface) *NetworkingV1beta1Client {\n\treturn \u0026NetworkingV1beta1Client{c}\n}","line":{"from":87,"to":90}} {"id":100027138,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/networking_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":92,"to":103}} {"id":100027139,"name":"RESTClient","signature":"func (c *NetworkingV1beta1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/networking/v1beta1/networking_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *NetworkingV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":105,"to":112}} {"id":100027140,"name":"RuntimeClasses","signature":"func (c *NodeV1Client) RuntimeClasses() RuntimeClassInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1/node_client.go","code":"func (c *NodeV1Client) RuntimeClasses() RuntimeClassInterface {\n\treturn newRuntimeClasses(c)\n}","line":{"from":39,"to":41}} {"id":100027141,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*NodeV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1/node_client.go","code":"// NewForConfig creates a new NodeV1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*NodeV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":43,"to":56}} {"id":100027142,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*NodeV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1/node_client.go","code":"// NewForConfigAndClient creates a new NodeV1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*NodeV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026NodeV1Client{client}, nil\n}","line":{"from":58,"to":70}} {"id":100027143,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *NodeV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1/node_client.go","code":"// NewForConfigOrDie creates a new NodeV1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *NodeV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":72,"to":80}} {"id":100027144,"name":"New","signature":"func New(c rest.Interface) *NodeV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1/node_client.go","code":"// New creates a new NodeV1Client for the given RESTClient.\nfunc New(c rest.Interface) *NodeV1Client {\n\treturn \u0026NodeV1Client{c}\n}","line":{"from":82,"to":85}} {"id":100027145,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1/node_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":87,"to":98}} {"id":100027146,"name":"RESTClient","signature":"func (c *NodeV1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1/node_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *NodeV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":100,"to":107}} {"id":100027147,"name":"newRuntimeClasses","signature":"func newRuntimeClasses(c *NodeV1Client) *runtimeClasses","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1/runtimeclass.go","code":"// newRuntimeClasses returns a RuntimeClasses\nfunc newRuntimeClasses(c *NodeV1Client) *runtimeClasses {\n\treturn \u0026runtimeClasses{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100027148,"name":"Get","signature":"func (c *runtimeClasses) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.RuntimeClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1/runtimeclass.go","code":"// Get takes name of the runtimeClass, and returns the corresponding runtimeClass object, and an error if there is any.\nfunc (c *runtimeClasses) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.RuntimeClass, err error) {\n\tresult = \u0026v1.RuntimeClass{}\n\terr = c.client.Get().\n\t\tResource(\"runtimeclasses\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100027149,"name":"List","signature":"func (c *runtimeClasses) List(ctx context.Context, opts metav1.ListOptions) (result *v1.RuntimeClassList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1/runtimeclass.go","code":"// List takes label and field selectors, and returns the list of RuntimeClasses that match those selectors.\nfunc (c *runtimeClasses) List(ctx context.Context, opts metav1.ListOptions) (result *v1.RuntimeClassList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.RuntimeClassList{}\n\terr = c.client.Get().\n\t\tResource(\"runtimeclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100027150,"name":"Watch","signature":"func (c *runtimeClasses) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1/runtimeclass.go","code":"// Watch returns a watch.Interface that watches the requested runtimeClasses.\nfunc (c *runtimeClasses) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"runtimeclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100027151,"name":"Create","signature":"func (c *runtimeClasses) Create(ctx context.Context, runtimeClass *v1.RuntimeClass, opts metav1.CreateOptions) (result *v1.RuntimeClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1/runtimeclass.go","code":"// Create takes the representation of a runtimeClass and creates it. Returns the server's representation of the runtimeClass, and an error, if there is any.\nfunc (c *runtimeClasses) Create(ctx context.Context, runtimeClass *v1.RuntimeClass, opts metav1.CreateOptions) (result *v1.RuntimeClass, err error) {\n\tresult = \u0026v1.RuntimeClass{}\n\terr = c.client.Post().\n\t\tResource(\"runtimeclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(runtimeClass).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100027152,"name":"Update","signature":"func (c *runtimeClasses) Update(ctx context.Context, runtimeClass *v1.RuntimeClass, opts metav1.UpdateOptions) (result *v1.RuntimeClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1/runtimeclass.go","code":"// Update takes the representation of a runtimeClass and updates it. Returns the server's representation of the runtimeClass, and an error, if there is any.\nfunc (c *runtimeClasses) Update(ctx context.Context, runtimeClass *v1.RuntimeClass, opts metav1.UpdateOptions) (result *v1.RuntimeClass, err error) {\n\tresult = \u0026v1.RuntimeClass{}\n\terr = c.client.Put().\n\t\tResource(\"runtimeclasses\").\n\t\tName(runtimeClass.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(runtimeClass).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100027153,"name":"Delete","signature":"func (c *runtimeClasses) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1/runtimeclass.go","code":"// Delete takes name of the runtimeClass and deletes it. Returns an error if one occurs.\nfunc (c *runtimeClasses) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"runtimeclasses\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100027154,"name":"DeleteCollection","signature":"func (c *runtimeClasses) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1/runtimeclass.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *runtimeClasses) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"runtimeclasses\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100027155,"name":"Patch","signature":"func (c *runtimeClasses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.RuntimeClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1/runtimeclass.go","code":"// Patch applies the patch and returns the patched runtimeClass.\nfunc (c *runtimeClasses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.RuntimeClass, err error) {\n\tresult = \u0026v1.RuntimeClass{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"runtimeclasses\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100027156,"name":"Apply","signature":"func (c *runtimeClasses) Apply(ctx context.Context, runtimeClass *nodev1.RuntimeClassApplyConfiguration, opts metav1.ApplyOptions) (result *v1.RuntimeClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1/runtimeclass.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied runtimeClass.\nfunc (c *runtimeClasses) Apply(ctx context.Context, runtimeClass *nodev1.RuntimeClassApplyConfiguration, opts metav1.ApplyOptions) (result *v1.RuntimeClass, err error) {\n\tif runtimeClass == nil {\n\t\treturn nil, fmt.Errorf(\"runtimeClass provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(runtimeClass)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := runtimeClass.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"runtimeClass.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.RuntimeClass{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"runtimeclasses\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100027157,"name":"RuntimeClasses","signature":"func (c *NodeV1alpha1Client) RuntimeClasses() RuntimeClassInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1alpha1/node_client.go","code":"func (c *NodeV1alpha1Client) RuntimeClasses() RuntimeClassInterface {\n\treturn newRuntimeClasses(c)\n}","line":{"from":39,"to":41}} {"id":100027158,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*NodeV1alpha1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1alpha1/node_client.go","code":"// NewForConfig creates a new NodeV1alpha1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*NodeV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":43,"to":56}} {"id":100027159,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*NodeV1alpha1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1alpha1/node_client.go","code":"// NewForConfigAndClient creates a new NodeV1alpha1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*NodeV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026NodeV1alpha1Client{client}, nil\n}","line":{"from":58,"to":70}} {"id":100027160,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *NodeV1alpha1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1alpha1/node_client.go","code":"// NewForConfigOrDie creates a new NodeV1alpha1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *NodeV1alpha1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":72,"to":80}} {"id":100027161,"name":"New","signature":"func New(c rest.Interface) *NodeV1alpha1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1alpha1/node_client.go","code":"// New creates a new NodeV1alpha1Client for the given RESTClient.\nfunc New(c rest.Interface) *NodeV1alpha1Client {\n\treturn \u0026NodeV1alpha1Client{c}\n}","line":{"from":82,"to":85}} {"id":100027162,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1alpha1/node_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1alpha1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":87,"to":98}} {"id":100027163,"name":"RESTClient","signature":"func (c *NodeV1alpha1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1alpha1/node_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *NodeV1alpha1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":100,"to":107}} {"id":100027164,"name":"newRuntimeClasses","signature":"func newRuntimeClasses(c *NodeV1alpha1Client) *runtimeClasses","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1alpha1/runtimeclass.go","code":"// newRuntimeClasses returns a RuntimeClasses\nfunc newRuntimeClasses(c *NodeV1alpha1Client) *runtimeClasses {\n\treturn \u0026runtimeClasses{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100027165,"name":"Get","signature":"func (c *runtimeClasses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.RuntimeClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1alpha1/runtimeclass.go","code":"// Get takes name of the runtimeClass, and returns the corresponding runtimeClass object, and an error if there is any.\nfunc (c *runtimeClasses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.RuntimeClass, err error) {\n\tresult = \u0026v1alpha1.RuntimeClass{}\n\terr = c.client.Get().\n\t\tResource(\"runtimeclasses\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100027166,"name":"List","signature":"func (c *runtimeClasses) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.RuntimeClassList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1alpha1/runtimeclass.go","code":"// List takes label and field selectors, and returns the list of RuntimeClasses that match those selectors.\nfunc (c *runtimeClasses) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.RuntimeClassList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1alpha1.RuntimeClassList{}\n\terr = c.client.Get().\n\t\tResource(\"runtimeclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100027167,"name":"Watch","signature":"func (c *runtimeClasses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1alpha1/runtimeclass.go","code":"// Watch returns a watch.Interface that watches the requested runtimeClasses.\nfunc (c *runtimeClasses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"runtimeclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100027168,"name":"Create","signature":"func (c *runtimeClasses) Create(ctx context.Context, runtimeClass *v1alpha1.RuntimeClass, opts v1.CreateOptions) (result *v1alpha1.RuntimeClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1alpha1/runtimeclass.go","code":"// Create takes the representation of a runtimeClass and creates it. Returns the server's representation of the runtimeClass, and an error, if there is any.\nfunc (c *runtimeClasses) Create(ctx context.Context, runtimeClass *v1alpha1.RuntimeClass, opts v1.CreateOptions) (result *v1alpha1.RuntimeClass, err error) {\n\tresult = \u0026v1alpha1.RuntimeClass{}\n\terr = c.client.Post().\n\t\tResource(\"runtimeclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(runtimeClass).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100027169,"name":"Update","signature":"func (c *runtimeClasses) Update(ctx context.Context, runtimeClass *v1alpha1.RuntimeClass, opts v1.UpdateOptions) (result *v1alpha1.RuntimeClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1alpha1/runtimeclass.go","code":"// Update takes the representation of a runtimeClass and updates it. Returns the server's representation of the runtimeClass, and an error, if there is any.\nfunc (c *runtimeClasses) Update(ctx context.Context, runtimeClass *v1alpha1.RuntimeClass, opts v1.UpdateOptions) (result *v1alpha1.RuntimeClass, err error) {\n\tresult = \u0026v1alpha1.RuntimeClass{}\n\terr = c.client.Put().\n\t\tResource(\"runtimeclasses\").\n\t\tName(runtimeClass.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(runtimeClass).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100027170,"name":"Delete","signature":"func (c *runtimeClasses) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1alpha1/runtimeclass.go","code":"// Delete takes name of the runtimeClass and deletes it. Returns an error if one occurs.\nfunc (c *runtimeClasses) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"runtimeclasses\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100027171,"name":"DeleteCollection","signature":"func (c *runtimeClasses) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1alpha1/runtimeclass.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *runtimeClasses) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"runtimeclasses\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100027172,"name":"Patch","signature":"func (c *runtimeClasses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.RuntimeClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1alpha1/runtimeclass.go","code":"// Patch applies the patch and returns the patched runtimeClass.\nfunc (c *runtimeClasses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.RuntimeClass, err error) {\n\tresult = \u0026v1alpha1.RuntimeClass{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"runtimeclasses\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100027173,"name":"Apply","signature":"func (c *runtimeClasses) Apply(ctx context.Context, runtimeClass *nodev1alpha1.RuntimeClassApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.RuntimeClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1alpha1/runtimeclass.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied runtimeClass.\nfunc (c *runtimeClasses) Apply(ctx context.Context, runtimeClass *nodev1alpha1.RuntimeClassApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.RuntimeClass, err error) {\n\tif runtimeClass == nil {\n\t\treturn nil, fmt.Errorf(\"runtimeClass provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(runtimeClass)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := runtimeClass.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"runtimeClass.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1alpha1.RuntimeClass{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"runtimeclasses\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100027174,"name":"RuntimeClasses","signature":"func (c *NodeV1beta1Client) RuntimeClasses() RuntimeClassInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1beta1/node_client.go","code":"func (c *NodeV1beta1Client) RuntimeClasses() RuntimeClassInterface {\n\treturn newRuntimeClasses(c)\n}","line":{"from":39,"to":41}} {"id":100027175,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*NodeV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1beta1/node_client.go","code":"// NewForConfig creates a new NodeV1beta1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*NodeV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":43,"to":56}} {"id":100027176,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*NodeV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1beta1/node_client.go","code":"// NewForConfigAndClient creates a new NodeV1beta1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*NodeV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026NodeV1beta1Client{client}, nil\n}","line":{"from":58,"to":70}} {"id":100027177,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *NodeV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1beta1/node_client.go","code":"// NewForConfigOrDie creates a new NodeV1beta1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *NodeV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":72,"to":80}} {"id":100027178,"name":"New","signature":"func New(c rest.Interface) *NodeV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1beta1/node_client.go","code":"// New creates a new NodeV1beta1Client for the given RESTClient.\nfunc New(c rest.Interface) *NodeV1beta1Client {\n\treturn \u0026NodeV1beta1Client{c}\n}","line":{"from":82,"to":85}} {"id":100027179,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1beta1/node_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":87,"to":98}} {"id":100027180,"name":"RESTClient","signature":"func (c *NodeV1beta1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1beta1/node_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *NodeV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":100,"to":107}} {"id":100027181,"name":"newRuntimeClasses","signature":"func newRuntimeClasses(c *NodeV1beta1Client) *runtimeClasses","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1beta1/runtimeclass.go","code":"// newRuntimeClasses returns a RuntimeClasses\nfunc newRuntimeClasses(c *NodeV1beta1Client) *runtimeClasses {\n\treturn \u0026runtimeClasses{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100027182,"name":"Get","signature":"func (c *runtimeClasses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.RuntimeClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1beta1/runtimeclass.go","code":"// Get takes name of the runtimeClass, and returns the corresponding runtimeClass object, and an error if there is any.\nfunc (c *runtimeClasses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.RuntimeClass, err error) {\n\tresult = \u0026v1beta1.RuntimeClass{}\n\terr = c.client.Get().\n\t\tResource(\"runtimeclasses\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100027183,"name":"List","signature":"func (c *runtimeClasses) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.RuntimeClassList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1beta1/runtimeclass.go","code":"// List takes label and field selectors, and returns the list of RuntimeClasses that match those selectors.\nfunc (c *runtimeClasses) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.RuntimeClassList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.RuntimeClassList{}\n\terr = c.client.Get().\n\t\tResource(\"runtimeclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100027184,"name":"Watch","signature":"func (c *runtimeClasses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1beta1/runtimeclass.go","code":"// Watch returns a watch.Interface that watches the requested runtimeClasses.\nfunc (c *runtimeClasses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"runtimeclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100027185,"name":"Create","signature":"func (c *runtimeClasses) Create(ctx context.Context, runtimeClass *v1beta1.RuntimeClass, opts v1.CreateOptions) (result *v1beta1.RuntimeClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1beta1/runtimeclass.go","code":"// Create takes the representation of a runtimeClass and creates it. Returns the server's representation of the runtimeClass, and an error, if there is any.\nfunc (c *runtimeClasses) Create(ctx context.Context, runtimeClass *v1beta1.RuntimeClass, opts v1.CreateOptions) (result *v1beta1.RuntimeClass, err error) {\n\tresult = \u0026v1beta1.RuntimeClass{}\n\terr = c.client.Post().\n\t\tResource(\"runtimeclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(runtimeClass).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100027186,"name":"Update","signature":"func (c *runtimeClasses) Update(ctx context.Context, runtimeClass *v1beta1.RuntimeClass, opts v1.UpdateOptions) (result *v1beta1.RuntimeClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1beta1/runtimeclass.go","code":"// Update takes the representation of a runtimeClass and updates it. Returns the server's representation of the runtimeClass, and an error, if there is any.\nfunc (c *runtimeClasses) Update(ctx context.Context, runtimeClass *v1beta1.RuntimeClass, opts v1.UpdateOptions) (result *v1beta1.RuntimeClass, err error) {\n\tresult = \u0026v1beta1.RuntimeClass{}\n\terr = c.client.Put().\n\t\tResource(\"runtimeclasses\").\n\t\tName(runtimeClass.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(runtimeClass).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100027187,"name":"Delete","signature":"func (c *runtimeClasses) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1beta1/runtimeclass.go","code":"// Delete takes name of the runtimeClass and deletes it. Returns an error if one occurs.\nfunc (c *runtimeClasses) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"runtimeclasses\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100027188,"name":"DeleteCollection","signature":"func (c *runtimeClasses) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1beta1/runtimeclass.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *runtimeClasses) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"runtimeclasses\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100027189,"name":"Patch","signature":"func (c *runtimeClasses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.RuntimeClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1beta1/runtimeclass.go","code":"// Patch applies the patch and returns the patched runtimeClass.\nfunc (c *runtimeClasses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.RuntimeClass, err error) {\n\tresult = \u0026v1beta1.RuntimeClass{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"runtimeclasses\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100027190,"name":"Apply","signature":"func (c *runtimeClasses) Apply(ctx context.Context, runtimeClass *nodev1beta1.RuntimeClassApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.RuntimeClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/node/v1beta1/runtimeclass.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied runtimeClass.\nfunc (c *runtimeClasses) Apply(ctx context.Context, runtimeClass *nodev1beta1.RuntimeClassApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.RuntimeClass, err error) {\n\tif runtimeClass == nil {\n\t\treturn nil, fmt.Errorf(\"runtimeClass provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(runtimeClass)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := runtimeClass.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"runtimeClass.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.RuntimeClass{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"runtimeclasses\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100027191,"name":"newEvictions","signature":"func newEvictions(c *PolicyV1Client, namespace string) *evictions","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1/eviction.go","code":"// newEvictions returns a Evictions\nfunc newEvictions(c *PolicyV1Client, namespace string) *evictions {\n\treturn \u0026evictions{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":42,"to":48}} {"id":100027192,"name":"Evict","signature":"func (c *evictions) Evict(ctx context.Context, eviction *policy.Eviction) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1/eviction_expansion.go","code":"func (c *evictions) Evict(ctx context.Context, eviction *policy.Eviction) error {\n\treturn c.client.Post().\n\t\tAbsPath(\"/api/v1\").\n\t\tNamespace(eviction.Namespace).\n\t\tResource(\"pods\").\n\t\tName(eviction.Name).\n\t\tSubResource(\"eviction\").\n\t\tBody(eviction).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":30,"to":40}} {"id":100027193,"name":"newPodDisruptionBudgets","signature":"func newPodDisruptionBudgets(c *PolicyV1Client, namespace string) *podDisruptionBudgets","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1/poddisruptionbudget.go","code":"// newPodDisruptionBudgets returns a PodDisruptionBudgets\nfunc newPodDisruptionBudgets(c *PolicyV1Client, namespace string) *podDisruptionBudgets {\n\treturn \u0026podDisruptionBudgets{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":64,"to":70}} {"id":100027194,"name":"Get","signature":"func (c *podDisruptionBudgets) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.PodDisruptionBudget, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1/poddisruptionbudget.go","code":"// Get takes name of the podDisruptionBudget, and returns the corresponding podDisruptionBudget object, and an error if there is any.\nfunc (c *podDisruptionBudgets) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.PodDisruptionBudget, err error) {\n\tresult = \u0026v1.PodDisruptionBudget{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"poddisruptionbudgets\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":72,"to":83}} {"id":100027195,"name":"List","signature":"func (c *podDisruptionBudgets) List(ctx context.Context, opts metav1.ListOptions) (result *v1.PodDisruptionBudgetList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1/poddisruptionbudget.go","code":"// List takes label and field selectors, and returns the list of PodDisruptionBudgets that match those selectors.\nfunc (c *podDisruptionBudgets) List(ctx context.Context, opts metav1.ListOptions) (result *v1.PodDisruptionBudgetList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.PodDisruptionBudgetList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"poddisruptionbudgets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":85,"to":100}} {"id":100027196,"name":"Watch","signature":"func (c *podDisruptionBudgets) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1/poddisruptionbudget.go","code":"// Watch returns a watch.Interface that watches the requested podDisruptionBudgets.\nfunc (c *podDisruptionBudgets) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"poddisruptionbudgets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":102,"to":115}} {"id":100027197,"name":"Create","signature":"func (c *podDisruptionBudgets) Create(ctx context.Context, podDisruptionBudget *v1.PodDisruptionBudget, opts metav1.CreateOptions) (result *v1.PodDisruptionBudget, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1/poddisruptionbudget.go","code":"// Create takes the representation of a podDisruptionBudget and creates it. Returns the server's representation of the podDisruptionBudget, and an error, if there is any.\nfunc (c *podDisruptionBudgets) Create(ctx context.Context, podDisruptionBudget *v1.PodDisruptionBudget, opts metav1.CreateOptions) (result *v1.PodDisruptionBudget, err error) {\n\tresult = \u0026v1.PodDisruptionBudget{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"poddisruptionbudgets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(podDisruptionBudget).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":117,"to":128}} {"id":100027198,"name":"Update","signature":"func (c *podDisruptionBudgets) Update(ctx context.Context, podDisruptionBudget *v1.PodDisruptionBudget, opts metav1.UpdateOptions) (result *v1.PodDisruptionBudget, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1/poddisruptionbudget.go","code":"// Update takes the representation of a podDisruptionBudget and updates it. Returns the server's representation of the podDisruptionBudget, and an error, if there is any.\nfunc (c *podDisruptionBudgets) Update(ctx context.Context, podDisruptionBudget *v1.PodDisruptionBudget, opts metav1.UpdateOptions) (result *v1.PodDisruptionBudget, err error) {\n\tresult = \u0026v1.PodDisruptionBudget{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"poddisruptionbudgets\").\n\t\tName(podDisruptionBudget.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(podDisruptionBudget).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":130,"to":142}} {"id":100027199,"name":"UpdateStatus","signature":"func (c *podDisruptionBudgets) UpdateStatus(ctx context.Context, podDisruptionBudget *v1.PodDisruptionBudget, opts metav1.UpdateOptions) (result *v1.PodDisruptionBudget, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1/poddisruptionbudget.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *podDisruptionBudgets) UpdateStatus(ctx context.Context, podDisruptionBudget *v1.PodDisruptionBudget, opts metav1.UpdateOptions) (result *v1.PodDisruptionBudget, err error) {\n\tresult = \u0026v1.PodDisruptionBudget{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"poddisruptionbudgets\").\n\t\tName(podDisruptionBudget.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(podDisruptionBudget).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":144,"to":158}} {"id":100027200,"name":"Delete","signature":"func (c *podDisruptionBudgets) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1/poddisruptionbudget.go","code":"// Delete takes name of the podDisruptionBudget and deletes it. Returns an error if one occurs.\nfunc (c *podDisruptionBudgets) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"poddisruptionbudgets\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":160,"to":169}} {"id":100027201,"name":"DeleteCollection","signature":"func (c *podDisruptionBudgets) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1/poddisruptionbudget.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *podDisruptionBudgets) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"poddisruptionbudgets\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":171,"to":185}} {"id":100027202,"name":"Patch","signature":"func (c *podDisruptionBudgets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.PodDisruptionBudget, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1/poddisruptionbudget.go","code":"// Patch applies the patch and returns the patched podDisruptionBudget.\nfunc (c *podDisruptionBudgets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.PodDisruptionBudget, err error) {\n\tresult = \u0026v1.PodDisruptionBudget{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"poddisruptionbudgets\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":187,"to":200}} {"id":100027203,"name":"Apply","signature":"func (c *podDisruptionBudgets) Apply(ctx context.Context, podDisruptionBudget *policyv1.PodDisruptionBudgetApplyConfiguration, opts metav1.ApplyOptions) (result *v1.PodDisruptionBudget, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1/poddisruptionbudget.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied podDisruptionBudget.\nfunc (c *podDisruptionBudgets) Apply(ctx context.Context, podDisruptionBudget *policyv1.PodDisruptionBudgetApplyConfiguration, opts metav1.ApplyOptions) (result *v1.PodDisruptionBudget, err error) {\n\tif podDisruptionBudget == nil {\n\t\treturn nil, fmt.Errorf(\"podDisruptionBudget provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(podDisruptionBudget)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := podDisruptionBudget.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"podDisruptionBudget.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.PodDisruptionBudget{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"poddisruptionbudgets\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":202,"to":226}} {"id":100027204,"name":"ApplyStatus","signature":"func (c *podDisruptionBudgets) ApplyStatus(ctx context.Context, podDisruptionBudget *policyv1.PodDisruptionBudgetApplyConfiguration, opts metav1.ApplyOptions) (result *v1.PodDisruptionBudget, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1/poddisruptionbudget.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *podDisruptionBudgets) ApplyStatus(ctx context.Context, podDisruptionBudget *policyv1.PodDisruptionBudgetApplyConfiguration, opts metav1.ApplyOptions) (result *v1.PodDisruptionBudget, err error) {\n\tif podDisruptionBudget == nil {\n\t\treturn nil, fmt.Errorf(\"podDisruptionBudget provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(podDisruptionBudget)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := podDisruptionBudget.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"podDisruptionBudget.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1.PodDisruptionBudget{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"poddisruptionbudgets\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":228,"to":256}} {"id":100027205,"name":"Evictions","signature":"func (c *PolicyV1Client) Evictions(namespace string) EvictionInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1/policy_client.go","code":"func (c *PolicyV1Client) Evictions(namespace string) EvictionInterface {\n\treturn newEvictions(c, namespace)\n}","line":{"from":40,"to":42}} {"id":100027206,"name":"PodDisruptionBudgets","signature":"func (c *PolicyV1Client) PodDisruptionBudgets(namespace string) PodDisruptionBudgetInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1/policy_client.go","code":"func (c *PolicyV1Client) PodDisruptionBudgets(namespace string) PodDisruptionBudgetInterface {\n\treturn newPodDisruptionBudgets(c, namespace)\n}","line":{"from":44,"to":46}} {"id":100027207,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*PolicyV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1/policy_client.go","code":"// NewForConfig creates a new PolicyV1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*PolicyV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":48,"to":61}} {"id":100027208,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*PolicyV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1/policy_client.go","code":"// NewForConfigAndClient creates a new PolicyV1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*PolicyV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026PolicyV1Client{client}, nil\n}","line":{"from":63,"to":75}} {"id":100027209,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *PolicyV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1/policy_client.go","code":"// NewForConfigOrDie creates a new PolicyV1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *PolicyV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":77,"to":85}} {"id":100027210,"name":"New","signature":"func New(c rest.Interface) *PolicyV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1/policy_client.go","code":"// New creates a new PolicyV1Client for the given RESTClient.\nfunc New(c rest.Interface) *PolicyV1Client {\n\treturn \u0026PolicyV1Client{c}\n}","line":{"from":87,"to":90}} {"id":100027211,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1/policy_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":92,"to":103}} {"id":100027212,"name":"RESTClient","signature":"func (c *PolicyV1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1/policy_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *PolicyV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":105,"to":112}} {"id":100027213,"name":"newEvictions","signature":"func newEvictions(c *PolicyV1beta1Client, namespace string) *evictions","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/eviction.go","code":"// newEvictions returns a Evictions\nfunc newEvictions(c *PolicyV1beta1Client, namespace string) *evictions {\n\treturn \u0026evictions{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":42,"to":48}} {"id":100027214,"name":"Evict","signature":"func (c *evictions) Evict(ctx context.Context, eviction *policy.Eviction) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/eviction_expansion.go","code":"func (c *evictions) Evict(ctx context.Context, eviction *policy.Eviction) error {\n\treturn c.client.Post().\n\t\tAbsPath(\"/api/v1\").\n\t\tNamespace(eviction.Namespace).\n\t\tResource(\"pods\").\n\t\tName(eviction.Name).\n\t\tSubResource(\"eviction\").\n\t\tBody(eviction).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":30,"to":40}} {"id":100027215,"name":"newPodDisruptionBudgets","signature":"func newPodDisruptionBudgets(c *PolicyV1beta1Client, namespace string) *podDisruptionBudgets","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/poddisruptionbudget.go","code":"// newPodDisruptionBudgets returns a PodDisruptionBudgets\nfunc newPodDisruptionBudgets(c *PolicyV1beta1Client, namespace string) *podDisruptionBudgets {\n\treturn \u0026podDisruptionBudgets{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":64,"to":70}} {"id":100027216,"name":"Get","signature":"func (c *podDisruptionBudgets) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.PodDisruptionBudget, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/poddisruptionbudget.go","code":"// Get takes name of the podDisruptionBudget, and returns the corresponding podDisruptionBudget object, and an error if there is any.\nfunc (c *podDisruptionBudgets) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.PodDisruptionBudget, err error) {\n\tresult = \u0026v1beta1.PodDisruptionBudget{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"poddisruptionbudgets\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":72,"to":83}} {"id":100027217,"name":"List","signature":"func (c *podDisruptionBudgets) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.PodDisruptionBudgetList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/poddisruptionbudget.go","code":"// List takes label and field selectors, and returns the list of PodDisruptionBudgets that match those selectors.\nfunc (c *podDisruptionBudgets) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.PodDisruptionBudgetList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.PodDisruptionBudgetList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"poddisruptionbudgets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":85,"to":100}} {"id":100027218,"name":"Watch","signature":"func (c *podDisruptionBudgets) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/poddisruptionbudget.go","code":"// Watch returns a watch.Interface that watches the requested podDisruptionBudgets.\nfunc (c *podDisruptionBudgets) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"poddisruptionbudgets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":102,"to":115}} {"id":100027219,"name":"Create","signature":"func (c *podDisruptionBudgets) Create(ctx context.Context, podDisruptionBudget *v1beta1.PodDisruptionBudget, opts v1.CreateOptions) (result *v1beta1.PodDisruptionBudget, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/poddisruptionbudget.go","code":"// Create takes the representation of a podDisruptionBudget and creates it. Returns the server's representation of the podDisruptionBudget, and an error, if there is any.\nfunc (c *podDisruptionBudgets) Create(ctx context.Context, podDisruptionBudget *v1beta1.PodDisruptionBudget, opts v1.CreateOptions) (result *v1beta1.PodDisruptionBudget, err error) {\n\tresult = \u0026v1beta1.PodDisruptionBudget{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"poddisruptionbudgets\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(podDisruptionBudget).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":117,"to":128}} {"id":100027220,"name":"Update","signature":"func (c *podDisruptionBudgets) Update(ctx context.Context, podDisruptionBudget *v1beta1.PodDisruptionBudget, opts v1.UpdateOptions) (result *v1beta1.PodDisruptionBudget, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/poddisruptionbudget.go","code":"// Update takes the representation of a podDisruptionBudget and updates it. Returns the server's representation of the podDisruptionBudget, and an error, if there is any.\nfunc (c *podDisruptionBudgets) Update(ctx context.Context, podDisruptionBudget *v1beta1.PodDisruptionBudget, opts v1.UpdateOptions) (result *v1beta1.PodDisruptionBudget, err error) {\n\tresult = \u0026v1beta1.PodDisruptionBudget{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"poddisruptionbudgets\").\n\t\tName(podDisruptionBudget.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(podDisruptionBudget).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":130,"to":142}} {"id":100027221,"name":"UpdateStatus","signature":"func (c *podDisruptionBudgets) UpdateStatus(ctx context.Context, podDisruptionBudget *v1beta1.PodDisruptionBudget, opts v1.UpdateOptions) (result *v1beta1.PodDisruptionBudget, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/poddisruptionbudget.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *podDisruptionBudgets) UpdateStatus(ctx context.Context, podDisruptionBudget *v1beta1.PodDisruptionBudget, opts v1.UpdateOptions) (result *v1beta1.PodDisruptionBudget, err error) {\n\tresult = \u0026v1beta1.PodDisruptionBudget{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"poddisruptionbudgets\").\n\t\tName(podDisruptionBudget.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(podDisruptionBudget).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":144,"to":158}} {"id":100027222,"name":"Delete","signature":"func (c *podDisruptionBudgets) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/poddisruptionbudget.go","code":"// Delete takes name of the podDisruptionBudget and deletes it. Returns an error if one occurs.\nfunc (c *podDisruptionBudgets) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"poddisruptionbudgets\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":160,"to":169}} {"id":100027223,"name":"DeleteCollection","signature":"func (c *podDisruptionBudgets) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/poddisruptionbudget.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *podDisruptionBudgets) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"poddisruptionbudgets\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":171,"to":185}} {"id":100027224,"name":"Patch","signature":"func (c *podDisruptionBudgets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.PodDisruptionBudget, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/poddisruptionbudget.go","code":"// Patch applies the patch and returns the patched podDisruptionBudget.\nfunc (c *podDisruptionBudgets) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.PodDisruptionBudget, err error) {\n\tresult = \u0026v1beta1.PodDisruptionBudget{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"poddisruptionbudgets\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":187,"to":200}} {"id":100027225,"name":"Apply","signature":"func (c *podDisruptionBudgets) Apply(ctx context.Context, podDisruptionBudget *policyv1beta1.PodDisruptionBudgetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.PodDisruptionBudget, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/poddisruptionbudget.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied podDisruptionBudget.\nfunc (c *podDisruptionBudgets) Apply(ctx context.Context, podDisruptionBudget *policyv1beta1.PodDisruptionBudgetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.PodDisruptionBudget, err error) {\n\tif podDisruptionBudget == nil {\n\t\treturn nil, fmt.Errorf(\"podDisruptionBudget provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(podDisruptionBudget)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := podDisruptionBudget.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"podDisruptionBudget.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.PodDisruptionBudget{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"poddisruptionbudgets\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":202,"to":226}} {"id":100027226,"name":"ApplyStatus","signature":"func (c *podDisruptionBudgets) ApplyStatus(ctx context.Context, podDisruptionBudget *policyv1beta1.PodDisruptionBudgetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.PodDisruptionBudget, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/poddisruptionbudget.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *podDisruptionBudgets) ApplyStatus(ctx context.Context, podDisruptionBudget *policyv1beta1.PodDisruptionBudgetApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.PodDisruptionBudget, err error) {\n\tif podDisruptionBudget == nil {\n\t\treturn nil, fmt.Errorf(\"podDisruptionBudget provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(podDisruptionBudget)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := podDisruptionBudget.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"podDisruptionBudget.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1beta1.PodDisruptionBudget{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"poddisruptionbudgets\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":228,"to":256}} {"id":100027227,"name":"newPodSecurityPolicies","signature":"func newPodSecurityPolicies(c *PolicyV1beta1Client) *podSecurityPolicies","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/podsecuritypolicy.go","code":"// newPodSecurityPolicies returns a PodSecurityPolicies\nfunc newPodSecurityPolicies(c *PolicyV1beta1Client) *podSecurityPolicies {\n\treturn \u0026podSecurityPolicies{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100027228,"name":"Get","signature":"func (c *podSecurityPolicies) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.PodSecurityPolicy, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/podsecuritypolicy.go","code":"// Get takes name of the podSecurityPolicy, and returns the corresponding podSecurityPolicy object, and an error if there is any.\nfunc (c *podSecurityPolicies) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.PodSecurityPolicy, err error) {\n\tresult = \u0026v1beta1.PodSecurityPolicy{}\n\terr = c.client.Get().\n\t\tResource(\"podsecuritypolicies\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100027229,"name":"List","signature":"func (c *podSecurityPolicies) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.PodSecurityPolicyList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/podsecuritypolicy.go","code":"// List takes label and field selectors, and returns the list of PodSecurityPolicies that match those selectors.\nfunc (c *podSecurityPolicies) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.PodSecurityPolicyList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.PodSecurityPolicyList{}\n\terr = c.client.Get().\n\t\tResource(\"podsecuritypolicies\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100027230,"name":"Watch","signature":"func (c *podSecurityPolicies) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/podsecuritypolicy.go","code":"// Watch returns a watch.Interface that watches the requested podSecurityPolicies.\nfunc (c *podSecurityPolicies) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"podsecuritypolicies\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100027231,"name":"Create","signature":"func (c *podSecurityPolicies) Create(ctx context.Context, podSecurityPolicy *v1beta1.PodSecurityPolicy, opts v1.CreateOptions) (result *v1beta1.PodSecurityPolicy, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/podsecuritypolicy.go","code":"// Create takes the representation of a podSecurityPolicy and creates it. Returns the server's representation of the podSecurityPolicy, and an error, if there is any.\nfunc (c *podSecurityPolicies) Create(ctx context.Context, podSecurityPolicy *v1beta1.PodSecurityPolicy, opts v1.CreateOptions) (result *v1beta1.PodSecurityPolicy, err error) {\n\tresult = \u0026v1beta1.PodSecurityPolicy{}\n\terr = c.client.Post().\n\t\tResource(\"podsecuritypolicies\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(podSecurityPolicy).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100027232,"name":"Update","signature":"func (c *podSecurityPolicies) Update(ctx context.Context, podSecurityPolicy *v1beta1.PodSecurityPolicy, opts v1.UpdateOptions) (result *v1beta1.PodSecurityPolicy, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/podsecuritypolicy.go","code":"// Update takes the representation of a podSecurityPolicy and updates it. Returns the server's representation of the podSecurityPolicy, and an error, if there is any.\nfunc (c *podSecurityPolicies) Update(ctx context.Context, podSecurityPolicy *v1beta1.PodSecurityPolicy, opts v1.UpdateOptions) (result *v1beta1.PodSecurityPolicy, err error) {\n\tresult = \u0026v1beta1.PodSecurityPolicy{}\n\terr = c.client.Put().\n\t\tResource(\"podsecuritypolicies\").\n\t\tName(podSecurityPolicy.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(podSecurityPolicy).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100027233,"name":"Delete","signature":"func (c *podSecurityPolicies) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/podsecuritypolicy.go","code":"// Delete takes name of the podSecurityPolicy and deletes it. Returns an error if one occurs.\nfunc (c *podSecurityPolicies) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"podsecuritypolicies\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100027234,"name":"DeleteCollection","signature":"func (c *podSecurityPolicies) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/podsecuritypolicy.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *podSecurityPolicies) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"podsecuritypolicies\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100027235,"name":"Patch","signature":"func (c *podSecurityPolicies) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.PodSecurityPolicy, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/podsecuritypolicy.go","code":"// Patch applies the patch and returns the patched podSecurityPolicy.\nfunc (c *podSecurityPolicies) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.PodSecurityPolicy, err error) {\n\tresult = \u0026v1beta1.PodSecurityPolicy{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"podsecuritypolicies\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100027236,"name":"Apply","signature":"func (c *podSecurityPolicies) Apply(ctx context.Context, podSecurityPolicy *policyv1beta1.PodSecurityPolicyApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.PodSecurityPolicy, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/podsecuritypolicy.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied podSecurityPolicy.\nfunc (c *podSecurityPolicies) Apply(ctx context.Context, podSecurityPolicy *policyv1beta1.PodSecurityPolicyApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.PodSecurityPolicy, err error) {\n\tif podSecurityPolicy == nil {\n\t\treturn nil, fmt.Errorf(\"podSecurityPolicy provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(podSecurityPolicy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := podSecurityPolicy.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"podSecurityPolicy.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.PodSecurityPolicy{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"podsecuritypolicies\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100027237,"name":"Evictions","signature":"func (c *PolicyV1beta1Client) Evictions(namespace string) EvictionInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/policy_client.go","code":"func (c *PolicyV1beta1Client) Evictions(namespace string) EvictionInterface {\n\treturn newEvictions(c, namespace)\n}","line":{"from":41,"to":43}} {"id":100027238,"name":"PodDisruptionBudgets","signature":"func (c *PolicyV1beta1Client) PodDisruptionBudgets(namespace string) PodDisruptionBudgetInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/policy_client.go","code":"func (c *PolicyV1beta1Client) PodDisruptionBudgets(namespace string) PodDisruptionBudgetInterface {\n\treturn newPodDisruptionBudgets(c, namespace)\n}","line":{"from":45,"to":47}} {"id":100027239,"name":"PodSecurityPolicies","signature":"func (c *PolicyV1beta1Client) PodSecurityPolicies() PodSecurityPolicyInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/policy_client.go","code":"func (c *PolicyV1beta1Client) PodSecurityPolicies() PodSecurityPolicyInterface {\n\treturn newPodSecurityPolicies(c)\n}","line":{"from":49,"to":51}} {"id":100027240,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*PolicyV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/policy_client.go","code":"// NewForConfig creates a new PolicyV1beta1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*PolicyV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":53,"to":66}} {"id":100027241,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*PolicyV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/policy_client.go","code":"// NewForConfigAndClient creates a new PolicyV1beta1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*PolicyV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026PolicyV1beta1Client{client}, nil\n}","line":{"from":68,"to":80}} {"id":100027242,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *PolicyV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/policy_client.go","code":"// NewForConfigOrDie creates a new PolicyV1beta1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *PolicyV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":82,"to":90}} {"id":100027243,"name":"New","signature":"func New(c rest.Interface) *PolicyV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/policy_client.go","code":"// New creates a new PolicyV1beta1Client for the given RESTClient.\nfunc New(c rest.Interface) *PolicyV1beta1Client {\n\treturn \u0026PolicyV1beta1Client{c}\n}","line":{"from":92,"to":95}} {"id":100027244,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/policy_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":97,"to":108}} {"id":100027245,"name":"RESTClient","signature":"func (c *PolicyV1beta1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/policy/v1beta1/policy_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *PolicyV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":110,"to":117}} {"id":100027246,"name":"newClusterRoles","signature":"func newClusterRoles(c *RbacV1Client) *clusterRoles","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/clusterrole.go","code":"// newClusterRoles returns a ClusterRoles\nfunc newClusterRoles(c *RbacV1Client) *clusterRoles {\n\treturn \u0026clusterRoles{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100027247,"name":"Get","signature":"func (c *clusterRoles) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ClusterRole, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/clusterrole.go","code":"// Get takes name of the clusterRole, and returns the corresponding clusterRole object, and an error if there is any.\nfunc (c *clusterRoles) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ClusterRole, err error) {\n\tresult = \u0026v1.ClusterRole{}\n\terr = c.client.Get().\n\t\tResource(\"clusterroles\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100027248,"name":"List","signature":"func (c *clusterRoles) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ClusterRoleList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/clusterrole.go","code":"// List takes label and field selectors, and returns the list of ClusterRoles that match those selectors.\nfunc (c *clusterRoles) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ClusterRoleList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.ClusterRoleList{}\n\terr = c.client.Get().\n\t\tResource(\"clusterroles\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100027249,"name":"Watch","signature":"func (c *clusterRoles) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/clusterrole.go","code":"// Watch returns a watch.Interface that watches the requested clusterRoles.\nfunc (c *clusterRoles) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"clusterroles\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100027250,"name":"Create","signature":"func (c *clusterRoles) Create(ctx context.Context, clusterRole *v1.ClusterRole, opts metav1.CreateOptions) (result *v1.ClusterRole, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/clusterrole.go","code":"// Create takes the representation of a clusterRole and creates it. Returns the server's representation of the clusterRole, and an error, if there is any.\nfunc (c *clusterRoles) Create(ctx context.Context, clusterRole *v1.ClusterRole, opts metav1.CreateOptions) (result *v1.ClusterRole, err error) {\n\tresult = \u0026v1.ClusterRole{}\n\terr = c.client.Post().\n\t\tResource(\"clusterroles\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(clusterRole).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100027251,"name":"Update","signature":"func (c *clusterRoles) Update(ctx context.Context, clusterRole *v1.ClusterRole, opts metav1.UpdateOptions) (result *v1.ClusterRole, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/clusterrole.go","code":"// Update takes the representation of a clusterRole and updates it. Returns the server's representation of the clusterRole, and an error, if there is any.\nfunc (c *clusterRoles) Update(ctx context.Context, clusterRole *v1.ClusterRole, opts metav1.UpdateOptions) (result *v1.ClusterRole, err error) {\n\tresult = \u0026v1.ClusterRole{}\n\terr = c.client.Put().\n\t\tResource(\"clusterroles\").\n\t\tName(clusterRole.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(clusterRole).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100027252,"name":"Delete","signature":"func (c *clusterRoles) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/clusterrole.go","code":"// Delete takes name of the clusterRole and deletes it. Returns an error if one occurs.\nfunc (c *clusterRoles) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"clusterroles\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100027253,"name":"DeleteCollection","signature":"func (c *clusterRoles) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/clusterrole.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *clusterRoles) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"clusterroles\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100027254,"name":"Patch","signature":"func (c *clusterRoles) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ClusterRole, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/clusterrole.go","code":"// Patch applies the patch and returns the patched clusterRole.\nfunc (c *clusterRoles) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ClusterRole, err error) {\n\tresult = \u0026v1.ClusterRole{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"clusterroles\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100027255,"name":"Apply","signature":"func (c *clusterRoles) Apply(ctx context.Context, clusterRole *rbacv1.ClusterRoleApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ClusterRole, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/clusterrole.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied clusterRole.\nfunc (c *clusterRoles) Apply(ctx context.Context, clusterRole *rbacv1.ClusterRoleApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ClusterRole, err error) {\n\tif clusterRole == nil {\n\t\treturn nil, fmt.Errorf(\"clusterRole provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(clusterRole)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := clusterRole.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"clusterRole.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.ClusterRole{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"clusterroles\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100027256,"name":"newClusterRoleBindings","signature":"func newClusterRoleBindings(c *RbacV1Client) *clusterRoleBindings","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/clusterrolebinding.go","code":"// newClusterRoleBindings returns a ClusterRoleBindings\nfunc newClusterRoleBindings(c *RbacV1Client) *clusterRoleBindings {\n\treturn \u0026clusterRoleBindings{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100027257,"name":"Get","signature":"func (c *clusterRoleBindings) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ClusterRoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/clusterrolebinding.go","code":"// Get takes name of the clusterRoleBinding, and returns the corresponding clusterRoleBinding object, and an error if there is any.\nfunc (c *clusterRoleBindings) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ClusterRoleBinding, err error) {\n\tresult = \u0026v1.ClusterRoleBinding{}\n\terr = c.client.Get().\n\t\tResource(\"clusterrolebindings\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100027258,"name":"List","signature":"func (c *clusterRoleBindings) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ClusterRoleBindingList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/clusterrolebinding.go","code":"// List takes label and field selectors, and returns the list of ClusterRoleBindings that match those selectors.\nfunc (c *clusterRoleBindings) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ClusterRoleBindingList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.ClusterRoleBindingList{}\n\terr = c.client.Get().\n\t\tResource(\"clusterrolebindings\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100027259,"name":"Watch","signature":"func (c *clusterRoleBindings) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/clusterrolebinding.go","code":"// Watch returns a watch.Interface that watches the requested clusterRoleBindings.\nfunc (c *clusterRoleBindings) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"clusterrolebindings\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100027260,"name":"Create","signature":"func (c *clusterRoleBindings) Create(ctx context.Context, clusterRoleBinding *v1.ClusterRoleBinding, opts metav1.CreateOptions) (result *v1.ClusterRoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/clusterrolebinding.go","code":"// Create takes the representation of a clusterRoleBinding and creates it. Returns the server's representation of the clusterRoleBinding, and an error, if there is any.\nfunc (c *clusterRoleBindings) Create(ctx context.Context, clusterRoleBinding *v1.ClusterRoleBinding, opts metav1.CreateOptions) (result *v1.ClusterRoleBinding, err error) {\n\tresult = \u0026v1.ClusterRoleBinding{}\n\terr = c.client.Post().\n\t\tResource(\"clusterrolebindings\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(clusterRoleBinding).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100027261,"name":"Update","signature":"func (c *clusterRoleBindings) Update(ctx context.Context, clusterRoleBinding *v1.ClusterRoleBinding, opts metav1.UpdateOptions) (result *v1.ClusterRoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/clusterrolebinding.go","code":"// Update takes the representation of a clusterRoleBinding and updates it. Returns the server's representation of the clusterRoleBinding, and an error, if there is any.\nfunc (c *clusterRoleBindings) Update(ctx context.Context, clusterRoleBinding *v1.ClusterRoleBinding, opts metav1.UpdateOptions) (result *v1.ClusterRoleBinding, err error) {\n\tresult = \u0026v1.ClusterRoleBinding{}\n\terr = c.client.Put().\n\t\tResource(\"clusterrolebindings\").\n\t\tName(clusterRoleBinding.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(clusterRoleBinding).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100027262,"name":"Delete","signature":"func (c *clusterRoleBindings) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/clusterrolebinding.go","code":"// Delete takes name of the clusterRoleBinding and deletes it. Returns an error if one occurs.\nfunc (c *clusterRoleBindings) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"clusterrolebindings\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100027263,"name":"DeleteCollection","signature":"func (c *clusterRoleBindings) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/clusterrolebinding.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *clusterRoleBindings) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"clusterrolebindings\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100027264,"name":"Patch","signature":"func (c *clusterRoleBindings) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ClusterRoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/clusterrolebinding.go","code":"// Patch applies the patch and returns the patched clusterRoleBinding.\nfunc (c *clusterRoleBindings) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ClusterRoleBinding, err error) {\n\tresult = \u0026v1.ClusterRoleBinding{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"clusterrolebindings\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100027265,"name":"Apply","signature":"func (c *clusterRoleBindings) Apply(ctx context.Context, clusterRoleBinding *rbacv1.ClusterRoleBindingApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ClusterRoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/clusterrolebinding.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied clusterRoleBinding.\nfunc (c *clusterRoleBindings) Apply(ctx context.Context, clusterRoleBinding *rbacv1.ClusterRoleBindingApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ClusterRoleBinding, err error) {\n\tif clusterRoleBinding == nil {\n\t\treturn nil, fmt.Errorf(\"clusterRoleBinding provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(clusterRoleBinding)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := clusterRoleBinding.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"clusterRoleBinding.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.ClusterRoleBinding{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"clusterrolebindings\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100027266,"name":"ClusterRoles","signature":"func (c *RbacV1Client) ClusterRoles() ClusterRoleInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/rbac_client.go","code":"func (c *RbacV1Client) ClusterRoles() ClusterRoleInterface {\n\treturn newClusterRoles(c)\n}","line":{"from":42,"to":44}} {"id":100027267,"name":"ClusterRoleBindings","signature":"func (c *RbacV1Client) ClusterRoleBindings() ClusterRoleBindingInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/rbac_client.go","code":"func (c *RbacV1Client) ClusterRoleBindings() ClusterRoleBindingInterface {\n\treturn newClusterRoleBindings(c)\n}","line":{"from":46,"to":48}} {"id":100027268,"name":"Roles","signature":"func (c *RbacV1Client) Roles(namespace string) RoleInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/rbac_client.go","code":"func (c *RbacV1Client) Roles(namespace string) RoleInterface {\n\treturn newRoles(c, namespace)\n}","line":{"from":50,"to":52}} {"id":100027269,"name":"RoleBindings","signature":"func (c *RbacV1Client) RoleBindings(namespace string) RoleBindingInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/rbac_client.go","code":"func (c *RbacV1Client) RoleBindings(namespace string) RoleBindingInterface {\n\treturn newRoleBindings(c, namespace)\n}","line":{"from":54,"to":56}} {"id":100027270,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*RbacV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/rbac_client.go","code":"// NewForConfig creates a new RbacV1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*RbacV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":58,"to":71}} {"id":100027271,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*RbacV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/rbac_client.go","code":"// NewForConfigAndClient creates a new RbacV1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*RbacV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026RbacV1Client{client}, nil\n}","line":{"from":73,"to":85}} {"id":100027272,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *RbacV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/rbac_client.go","code":"// NewForConfigOrDie creates a new RbacV1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *RbacV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":87,"to":95}} {"id":100027273,"name":"New","signature":"func New(c rest.Interface) *RbacV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/rbac_client.go","code":"// New creates a new RbacV1Client for the given RESTClient.\nfunc New(c rest.Interface) *RbacV1Client {\n\treturn \u0026RbacV1Client{c}\n}","line":{"from":97,"to":100}} {"id":100027274,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/rbac_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":102,"to":113}} {"id":100027275,"name":"RESTClient","signature":"func (c *RbacV1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/rbac_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *RbacV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":115,"to":122}} {"id":100027276,"name":"newRoles","signature":"func newRoles(c *RbacV1Client, namespace string) *roles","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/role.go","code":"// newRoles returns a Roles\nfunc newRoles(c *RbacV1Client, namespace string) *roles {\n\treturn \u0026roles{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":62,"to":68}} {"id":100027277,"name":"Get","signature":"func (c *roles) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Role, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/role.go","code":"// Get takes name of the role, and returns the corresponding role object, and an error if there is any.\nfunc (c *roles) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.Role, err error) {\n\tresult = \u0026v1.Role{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":81}} {"id":100027278,"name":"List","signature":"func (c *roles) List(ctx context.Context, opts metav1.ListOptions) (result *v1.RoleList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/role.go","code":"// List takes label and field selectors, and returns the list of Roles that match those selectors.\nfunc (c *roles) List(ctx context.Context, opts metav1.ListOptions) (result *v1.RoleList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.RoleList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":83,"to":98}} {"id":100027279,"name":"Watch","signature":"func (c *roles) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/role.go","code":"// Watch returns a watch.Interface that watches the requested roles.\nfunc (c *roles) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":100,"to":113}} {"id":100027280,"name":"Create","signature":"func (c *roles) Create(ctx context.Context, role *v1.Role, opts metav1.CreateOptions) (result *v1.Role, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/role.go","code":"// Create takes the representation of a role and creates it. Returns the server's representation of the role, and an error, if there is any.\nfunc (c *roles) Create(ctx context.Context, role *v1.Role, opts metav1.CreateOptions) (result *v1.Role, err error) {\n\tresult = \u0026v1.Role{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(role).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":115,"to":126}} {"id":100027281,"name":"Update","signature":"func (c *roles) Update(ctx context.Context, role *v1.Role, opts metav1.UpdateOptions) (result *v1.Role, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/role.go","code":"// Update takes the representation of a role and updates it. Returns the server's representation of the role, and an error, if there is any.\nfunc (c *roles) Update(ctx context.Context, role *v1.Role, opts metav1.UpdateOptions) (result *v1.Role, err error) {\n\tresult = \u0026v1.Role{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tName(role.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(role).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":128,"to":140}} {"id":100027282,"name":"Delete","signature":"func (c *roles) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/role.go","code":"// Delete takes name of the role and deletes it. Returns an error if one occurs.\nfunc (c *roles) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":142,"to":151}} {"id":100027283,"name":"DeleteCollection","signature":"func (c *roles) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/role.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *roles) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":153,"to":167}} {"id":100027284,"name":"Patch","signature":"func (c *roles) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Role, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/role.go","code":"// Patch applies the patch and returns the patched role.\nfunc (c *roles) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.Role, err error) {\n\tresult = \u0026v1.Role{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":169,"to":182}} {"id":100027285,"name":"Apply","signature":"func (c *roles) Apply(ctx context.Context, role *rbacv1.RoleApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Role, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/role.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied role.\nfunc (c *roles) Apply(ctx context.Context, role *rbacv1.RoleApplyConfiguration, opts metav1.ApplyOptions) (result *v1.Role, err error) {\n\tif role == nil {\n\t\treturn nil, fmt.Errorf(\"role provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(role)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := role.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"role.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.Role{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":184,"to":208}} {"id":100027286,"name":"newRoleBindings","signature":"func newRoleBindings(c *RbacV1Client, namespace string) *roleBindings","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/rolebinding.go","code":"// newRoleBindings returns a RoleBindings\nfunc newRoleBindings(c *RbacV1Client, namespace string) *roleBindings {\n\treturn \u0026roleBindings{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":62,"to":68}} {"id":100027287,"name":"Get","signature":"func (c *roleBindings) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.RoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/rolebinding.go","code":"// Get takes name of the roleBinding, and returns the corresponding roleBinding object, and an error if there is any.\nfunc (c *roleBindings) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.RoleBinding, err error) {\n\tresult = \u0026v1.RoleBinding{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":81}} {"id":100027288,"name":"List","signature":"func (c *roleBindings) List(ctx context.Context, opts metav1.ListOptions) (result *v1.RoleBindingList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/rolebinding.go","code":"// List takes label and field selectors, and returns the list of RoleBindings that match those selectors.\nfunc (c *roleBindings) List(ctx context.Context, opts metav1.ListOptions) (result *v1.RoleBindingList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.RoleBindingList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":83,"to":98}} {"id":100027289,"name":"Watch","signature":"func (c *roleBindings) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/rolebinding.go","code":"// Watch returns a watch.Interface that watches the requested roleBindings.\nfunc (c *roleBindings) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":100,"to":113}} {"id":100027290,"name":"Create","signature":"func (c *roleBindings) Create(ctx context.Context, roleBinding *v1.RoleBinding, opts metav1.CreateOptions) (result *v1.RoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/rolebinding.go","code":"// Create takes the representation of a roleBinding and creates it. Returns the server's representation of the roleBinding, and an error, if there is any.\nfunc (c *roleBindings) Create(ctx context.Context, roleBinding *v1.RoleBinding, opts metav1.CreateOptions) (result *v1.RoleBinding, err error) {\n\tresult = \u0026v1.RoleBinding{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(roleBinding).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":115,"to":126}} {"id":100027291,"name":"Update","signature":"func (c *roleBindings) Update(ctx context.Context, roleBinding *v1.RoleBinding, opts metav1.UpdateOptions) (result *v1.RoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/rolebinding.go","code":"// Update takes the representation of a roleBinding and updates it. Returns the server's representation of the roleBinding, and an error, if there is any.\nfunc (c *roleBindings) Update(ctx context.Context, roleBinding *v1.RoleBinding, opts metav1.UpdateOptions) (result *v1.RoleBinding, err error) {\n\tresult = \u0026v1.RoleBinding{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tName(roleBinding.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(roleBinding).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":128,"to":140}} {"id":100027292,"name":"Delete","signature":"func (c *roleBindings) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/rolebinding.go","code":"// Delete takes name of the roleBinding and deletes it. Returns an error if one occurs.\nfunc (c *roleBindings) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":142,"to":151}} {"id":100027293,"name":"DeleteCollection","signature":"func (c *roleBindings) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/rolebinding.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *roleBindings) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":153,"to":167}} {"id":100027294,"name":"Patch","signature":"func (c *roleBindings) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.RoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/rolebinding.go","code":"// Patch applies the patch and returns the patched roleBinding.\nfunc (c *roleBindings) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.RoleBinding, err error) {\n\tresult = \u0026v1.RoleBinding{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":169,"to":182}} {"id":100027295,"name":"Apply","signature":"func (c *roleBindings) Apply(ctx context.Context, roleBinding *rbacv1.RoleBindingApplyConfiguration, opts metav1.ApplyOptions) (result *v1.RoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1/rolebinding.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied roleBinding.\nfunc (c *roleBindings) Apply(ctx context.Context, roleBinding *rbacv1.RoleBindingApplyConfiguration, opts metav1.ApplyOptions) (result *v1.RoleBinding, err error) {\n\tif roleBinding == nil {\n\t\treturn nil, fmt.Errorf(\"roleBinding provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(roleBinding)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := roleBinding.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"roleBinding.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.RoleBinding{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":184,"to":208}} {"id":100027296,"name":"newClusterRoles","signature":"func newClusterRoles(c *RbacV1alpha1Client) *clusterRoles","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/clusterrole.go","code":"// newClusterRoles returns a ClusterRoles\nfunc newClusterRoles(c *RbacV1alpha1Client) *clusterRoles {\n\treturn \u0026clusterRoles{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100027297,"name":"Get","signature":"func (c *clusterRoles) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.ClusterRole, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/clusterrole.go","code":"// Get takes name of the clusterRole, and returns the corresponding clusterRole object, and an error if there is any.\nfunc (c *clusterRoles) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.ClusterRole, err error) {\n\tresult = \u0026v1alpha1.ClusterRole{}\n\terr = c.client.Get().\n\t\tResource(\"clusterroles\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100027298,"name":"List","signature":"func (c *clusterRoles) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.ClusterRoleList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/clusterrole.go","code":"// List takes label and field selectors, and returns the list of ClusterRoles that match those selectors.\nfunc (c *clusterRoles) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.ClusterRoleList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1alpha1.ClusterRoleList{}\n\terr = c.client.Get().\n\t\tResource(\"clusterroles\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100027299,"name":"Watch","signature":"func (c *clusterRoles) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/clusterrole.go","code":"// Watch returns a watch.Interface that watches the requested clusterRoles.\nfunc (c *clusterRoles) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"clusterroles\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100027300,"name":"Create","signature":"func (c *clusterRoles) Create(ctx context.Context, clusterRole *v1alpha1.ClusterRole, opts v1.CreateOptions) (result *v1alpha1.ClusterRole, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/clusterrole.go","code":"// Create takes the representation of a clusterRole and creates it. Returns the server's representation of the clusterRole, and an error, if there is any.\nfunc (c *clusterRoles) Create(ctx context.Context, clusterRole *v1alpha1.ClusterRole, opts v1.CreateOptions) (result *v1alpha1.ClusterRole, err error) {\n\tresult = \u0026v1alpha1.ClusterRole{}\n\terr = c.client.Post().\n\t\tResource(\"clusterroles\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(clusterRole).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100027301,"name":"Update","signature":"func (c *clusterRoles) Update(ctx context.Context, clusterRole *v1alpha1.ClusterRole, opts v1.UpdateOptions) (result *v1alpha1.ClusterRole, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/clusterrole.go","code":"// Update takes the representation of a clusterRole and updates it. Returns the server's representation of the clusterRole, and an error, if there is any.\nfunc (c *clusterRoles) Update(ctx context.Context, clusterRole *v1alpha1.ClusterRole, opts v1.UpdateOptions) (result *v1alpha1.ClusterRole, err error) {\n\tresult = \u0026v1alpha1.ClusterRole{}\n\terr = c.client.Put().\n\t\tResource(\"clusterroles\").\n\t\tName(clusterRole.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(clusterRole).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100027302,"name":"Delete","signature":"func (c *clusterRoles) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/clusterrole.go","code":"// Delete takes name of the clusterRole and deletes it. Returns an error if one occurs.\nfunc (c *clusterRoles) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"clusterroles\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100027303,"name":"DeleteCollection","signature":"func (c *clusterRoles) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/clusterrole.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *clusterRoles) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"clusterroles\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100027304,"name":"Patch","signature":"func (c *clusterRoles) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.ClusterRole, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/clusterrole.go","code":"// Patch applies the patch and returns the patched clusterRole.\nfunc (c *clusterRoles) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.ClusterRole, err error) {\n\tresult = \u0026v1alpha1.ClusterRole{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"clusterroles\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100027305,"name":"Apply","signature":"func (c *clusterRoles) Apply(ctx context.Context, clusterRole *rbacv1alpha1.ClusterRoleApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.ClusterRole, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/clusterrole.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied clusterRole.\nfunc (c *clusterRoles) Apply(ctx context.Context, clusterRole *rbacv1alpha1.ClusterRoleApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.ClusterRole, err error) {\n\tif clusterRole == nil {\n\t\treturn nil, fmt.Errorf(\"clusterRole provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(clusterRole)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := clusterRole.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"clusterRole.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1alpha1.ClusterRole{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"clusterroles\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100027306,"name":"newClusterRoleBindings","signature":"func newClusterRoleBindings(c *RbacV1alpha1Client) *clusterRoleBindings","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/clusterrolebinding.go","code":"// newClusterRoleBindings returns a ClusterRoleBindings\nfunc newClusterRoleBindings(c *RbacV1alpha1Client) *clusterRoleBindings {\n\treturn \u0026clusterRoleBindings{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100027307,"name":"Get","signature":"func (c *clusterRoleBindings) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.ClusterRoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/clusterrolebinding.go","code":"// Get takes name of the clusterRoleBinding, and returns the corresponding clusterRoleBinding object, and an error if there is any.\nfunc (c *clusterRoleBindings) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.ClusterRoleBinding, err error) {\n\tresult = \u0026v1alpha1.ClusterRoleBinding{}\n\terr = c.client.Get().\n\t\tResource(\"clusterrolebindings\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100027308,"name":"List","signature":"func (c *clusterRoleBindings) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.ClusterRoleBindingList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/clusterrolebinding.go","code":"// List takes label and field selectors, and returns the list of ClusterRoleBindings that match those selectors.\nfunc (c *clusterRoleBindings) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.ClusterRoleBindingList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1alpha1.ClusterRoleBindingList{}\n\terr = c.client.Get().\n\t\tResource(\"clusterrolebindings\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100027309,"name":"Watch","signature":"func (c *clusterRoleBindings) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/clusterrolebinding.go","code":"// Watch returns a watch.Interface that watches the requested clusterRoleBindings.\nfunc (c *clusterRoleBindings) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"clusterrolebindings\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100027310,"name":"Create","signature":"func (c *clusterRoleBindings) Create(ctx context.Context, clusterRoleBinding *v1alpha1.ClusterRoleBinding, opts v1.CreateOptions) (result *v1alpha1.ClusterRoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/clusterrolebinding.go","code":"// Create takes the representation of a clusterRoleBinding and creates it. Returns the server's representation of the clusterRoleBinding, and an error, if there is any.\nfunc (c *clusterRoleBindings) Create(ctx context.Context, clusterRoleBinding *v1alpha1.ClusterRoleBinding, opts v1.CreateOptions) (result *v1alpha1.ClusterRoleBinding, err error) {\n\tresult = \u0026v1alpha1.ClusterRoleBinding{}\n\terr = c.client.Post().\n\t\tResource(\"clusterrolebindings\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(clusterRoleBinding).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100027311,"name":"Update","signature":"func (c *clusterRoleBindings) Update(ctx context.Context, clusterRoleBinding *v1alpha1.ClusterRoleBinding, opts v1.UpdateOptions) (result *v1alpha1.ClusterRoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/clusterrolebinding.go","code":"// Update takes the representation of a clusterRoleBinding and updates it. Returns the server's representation of the clusterRoleBinding, and an error, if there is any.\nfunc (c *clusterRoleBindings) Update(ctx context.Context, clusterRoleBinding *v1alpha1.ClusterRoleBinding, opts v1.UpdateOptions) (result *v1alpha1.ClusterRoleBinding, err error) {\n\tresult = \u0026v1alpha1.ClusterRoleBinding{}\n\terr = c.client.Put().\n\t\tResource(\"clusterrolebindings\").\n\t\tName(clusterRoleBinding.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(clusterRoleBinding).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100027312,"name":"Delete","signature":"func (c *clusterRoleBindings) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/clusterrolebinding.go","code":"// Delete takes name of the clusterRoleBinding and deletes it. Returns an error if one occurs.\nfunc (c *clusterRoleBindings) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"clusterrolebindings\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100027313,"name":"DeleteCollection","signature":"func (c *clusterRoleBindings) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/clusterrolebinding.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *clusterRoleBindings) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"clusterrolebindings\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100027314,"name":"Patch","signature":"func (c *clusterRoleBindings) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.ClusterRoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/clusterrolebinding.go","code":"// Patch applies the patch and returns the patched clusterRoleBinding.\nfunc (c *clusterRoleBindings) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.ClusterRoleBinding, err error) {\n\tresult = \u0026v1alpha1.ClusterRoleBinding{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"clusterrolebindings\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100027315,"name":"Apply","signature":"func (c *clusterRoleBindings) Apply(ctx context.Context, clusterRoleBinding *rbacv1alpha1.ClusterRoleBindingApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.ClusterRoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/clusterrolebinding.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied clusterRoleBinding.\nfunc (c *clusterRoleBindings) Apply(ctx context.Context, clusterRoleBinding *rbacv1alpha1.ClusterRoleBindingApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.ClusterRoleBinding, err error) {\n\tif clusterRoleBinding == nil {\n\t\treturn nil, fmt.Errorf(\"clusterRoleBinding provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(clusterRoleBinding)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := clusterRoleBinding.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"clusterRoleBinding.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1alpha1.ClusterRoleBinding{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"clusterrolebindings\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100027316,"name":"ClusterRoles","signature":"func (c *RbacV1alpha1Client) ClusterRoles() ClusterRoleInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/rbac_client.go","code":"func (c *RbacV1alpha1Client) ClusterRoles() ClusterRoleInterface {\n\treturn newClusterRoles(c)\n}","line":{"from":42,"to":44}} {"id":100027317,"name":"ClusterRoleBindings","signature":"func (c *RbacV1alpha1Client) ClusterRoleBindings() ClusterRoleBindingInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/rbac_client.go","code":"func (c *RbacV1alpha1Client) ClusterRoleBindings() ClusterRoleBindingInterface {\n\treturn newClusterRoleBindings(c)\n}","line":{"from":46,"to":48}} {"id":100027318,"name":"Roles","signature":"func (c *RbacV1alpha1Client) Roles(namespace string) RoleInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/rbac_client.go","code":"func (c *RbacV1alpha1Client) Roles(namespace string) RoleInterface {\n\treturn newRoles(c, namespace)\n}","line":{"from":50,"to":52}} {"id":100027319,"name":"RoleBindings","signature":"func (c *RbacV1alpha1Client) RoleBindings(namespace string) RoleBindingInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/rbac_client.go","code":"func (c *RbacV1alpha1Client) RoleBindings(namespace string) RoleBindingInterface {\n\treturn newRoleBindings(c, namespace)\n}","line":{"from":54,"to":56}} {"id":100027320,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*RbacV1alpha1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/rbac_client.go","code":"// NewForConfig creates a new RbacV1alpha1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*RbacV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":58,"to":71}} {"id":100027321,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*RbacV1alpha1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/rbac_client.go","code":"// NewForConfigAndClient creates a new RbacV1alpha1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*RbacV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026RbacV1alpha1Client{client}, nil\n}","line":{"from":73,"to":85}} {"id":100027322,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *RbacV1alpha1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/rbac_client.go","code":"// NewForConfigOrDie creates a new RbacV1alpha1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *RbacV1alpha1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":87,"to":95}} {"id":100027323,"name":"New","signature":"func New(c rest.Interface) *RbacV1alpha1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/rbac_client.go","code":"// New creates a new RbacV1alpha1Client for the given RESTClient.\nfunc New(c rest.Interface) *RbacV1alpha1Client {\n\treturn \u0026RbacV1alpha1Client{c}\n}","line":{"from":97,"to":100}} {"id":100027324,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/rbac_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1alpha1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":102,"to":113}} {"id":100027325,"name":"RESTClient","signature":"func (c *RbacV1alpha1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/rbac_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *RbacV1alpha1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":115,"to":122}} {"id":100027326,"name":"newRoles","signature":"func newRoles(c *RbacV1alpha1Client, namespace string) *roles","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/role.go","code":"// newRoles returns a Roles\nfunc newRoles(c *RbacV1alpha1Client, namespace string) *roles {\n\treturn \u0026roles{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":62,"to":68}} {"id":100027327,"name":"Get","signature":"func (c *roles) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.Role, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/role.go","code":"// Get takes name of the role, and returns the corresponding role object, and an error if there is any.\nfunc (c *roles) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.Role, err error) {\n\tresult = \u0026v1alpha1.Role{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":81}} {"id":100027328,"name":"List","signature":"func (c *roles) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.RoleList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/role.go","code":"// List takes label and field selectors, and returns the list of Roles that match those selectors.\nfunc (c *roles) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.RoleList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1alpha1.RoleList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":83,"to":98}} {"id":100027329,"name":"Watch","signature":"func (c *roles) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/role.go","code":"// Watch returns a watch.Interface that watches the requested roles.\nfunc (c *roles) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":100,"to":113}} {"id":100027330,"name":"Create","signature":"func (c *roles) Create(ctx context.Context, role *v1alpha1.Role, opts v1.CreateOptions) (result *v1alpha1.Role, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/role.go","code":"// Create takes the representation of a role and creates it. Returns the server's representation of the role, and an error, if there is any.\nfunc (c *roles) Create(ctx context.Context, role *v1alpha1.Role, opts v1.CreateOptions) (result *v1alpha1.Role, err error) {\n\tresult = \u0026v1alpha1.Role{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(role).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":115,"to":126}} {"id":100027331,"name":"Update","signature":"func (c *roles) Update(ctx context.Context, role *v1alpha1.Role, opts v1.UpdateOptions) (result *v1alpha1.Role, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/role.go","code":"// Update takes the representation of a role and updates it. Returns the server's representation of the role, and an error, if there is any.\nfunc (c *roles) Update(ctx context.Context, role *v1alpha1.Role, opts v1.UpdateOptions) (result *v1alpha1.Role, err error) {\n\tresult = \u0026v1alpha1.Role{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tName(role.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(role).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":128,"to":140}} {"id":100027332,"name":"Delete","signature":"func (c *roles) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/role.go","code":"// Delete takes name of the role and deletes it. Returns an error if one occurs.\nfunc (c *roles) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":142,"to":151}} {"id":100027333,"name":"DeleteCollection","signature":"func (c *roles) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/role.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *roles) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":153,"to":167}} {"id":100027334,"name":"Patch","signature":"func (c *roles) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.Role, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/role.go","code":"// Patch applies the patch and returns the patched role.\nfunc (c *roles) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.Role, err error) {\n\tresult = \u0026v1alpha1.Role{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":169,"to":182}} {"id":100027335,"name":"Apply","signature":"func (c *roles) Apply(ctx context.Context, role *rbacv1alpha1.RoleApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.Role, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/role.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied role.\nfunc (c *roles) Apply(ctx context.Context, role *rbacv1alpha1.RoleApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.Role, err error) {\n\tif role == nil {\n\t\treturn nil, fmt.Errorf(\"role provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(role)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := role.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"role.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1alpha1.Role{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":184,"to":208}} {"id":100027336,"name":"newRoleBindings","signature":"func newRoleBindings(c *RbacV1alpha1Client, namespace string) *roleBindings","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/rolebinding.go","code":"// newRoleBindings returns a RoleBindings\nfunc newRoleBindings(c *RbacV1alpha1Client, namespace string) *roleBindings {\n\treturn \u0026roleBindings{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":62,"to":68}} {"id":100027337,"name":"Get","signature":"func (c *roleBindings) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.RoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/rolebinding.go","code":"// Get takes name of the roleBinding, and returns the corresponding roleBinding object, and an error if there is any.\nfunc (c *roleBindings) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.RoleBinding, err error) {\n\tresult = \u0026v1alpha1.RoleBinding{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":81}} {"id":100027338,"name":"List","signature":"func (c *roleBindings) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.RoleBindingList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/rolebinding.go","code":"// List takes label and field selectors, and returns the list of RoleBindings that match those selectors.\nfunc (c *roleBindings) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.RoleBindingList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1alpha1.RoleBindingList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":83,"to":98}} {"id":100027339,"name":"Watch","signature":"func (c *roleBindings) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/rolebinding.go","code":"// Watch returns a watch.Interface that watches the requested roleBindings.\nfunc (c *roleBindings) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":100,"to":113}} {"id":100027340,"name":"Create","signature":"func (c *roleBindings) Create(ctx context.Context, roleBinding *v1alpha1.RoleBinding, opts v1.CreateOptions) (result *v1alpha1.RoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/rolebinding.go","code":"// Create takes the representation of a roleBinding and creates it. Returns the server's representation of the roleBinding, and an error, if there is any.\nfunc (c *roleBindings) Create(ctx context.Context, roleBinding *v1alpha1.RoleBinding, opts v1.CreateOptions) (result *v1alpha1.RoleBinding, err error) {\n\tresult = \u0026v1alpha1.RoleBinding{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(roleBinding).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":115,"to":126}} {"id":100027341,"name":"Update","signature":"func (c *roleBindings) Update(ctx context.Context, roleBinding *v1alpha1.RoleBinding, opts v1.UpdateOptions) (result *v1alpha1.RoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/rolebinding.go","code":"// Update takes the representation of a roleBinding and updates it. Returns the server's representation of the roleBinding, and an error, if there is any.\nfunc (c *roleBindings) Update(ctx context.Context, roleBinding *v1alpha1.RoleBinding, opts v1.UpdateOptions) (result *v1alpha1.RoleBinding, err error) {\n\tresult = \u0026v1alpha1.RoleBinding{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tName(roleBinding.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(roleBinding).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":128,"to":140}} {"id":100027342,"name":"Delete","signature":"func (c *roleBindings) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/rolebinding.go","code":"// Delete takes name of the roleBinding and deletes it. Returns an error if one occurs.\nfunc (c *roleBindings) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":142,"to":151}} {"id":100027343,"name":"DeleteCollection","signature":"func (c *roleBindings) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/rolebinding.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *roleBindings) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":153,"to":167}} {"id":100027344,"name":"Patch","signature":"func (c *roleBindings) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.RoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/rolebinding.go","code":"// Patch applies the patch and returns the patched roleBinding.\nfunc (c *roleBindings) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.RoleBinding, err error) {\n\tresult = \u0026v1alpha1.RoleBinding{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":169,"to":182}} {"id":100027345,"name":"Apply","signature":"func (c *roleBindings) Apply(ctx context.Context, roleBinding *rbacv1alpha1.RoleBindingApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.RoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1alpha1/rolebinding.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied roleBinding.\nfunc (c *roleBindings) Apply(ctx context.Context, roleBinding *rbacv1alpha1.RoleBindingApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.RoleBinding, err error) {\n\tif roleBinding == nil {\n\t\treturn nil, fmt.Errorf(\"roleBinding provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(roleBinding)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := roleBinding.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"roleBinding.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1alpha1.RoleBinding{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":184,"to":208}} {"id":100027346,"name":"newClusterRoles","signature":"func newClusterRoles(c *RbacV1beta1Client) *clusterRoles","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/clusterrole.go","code":"// newClusterRoles returns a ClusterRoles\nfunc newClusterRoles(c *RbacV1beta1Client) *clusterRoles {\n\treturn \u0026clusterRoles{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100027347,"name":"Get","signature":"func (c *clusterRoles) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.ClusterRole, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/clusterrole.go","code":"// Get takes name of the clusterRole, and returns the corresponding clusterRole object, and an error if there is any.\nfunc (c *clusterRoles) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.ClusterRole, err error) {\n\tresult = \u0026v1beta1.ClusterRole{}\n\terr = c.client.Get().\n\t\tResource(\"clusterroles\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100027348,"name":"List","signature":"func (c *clusterRoles) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.ClusterRoleList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/clusterrole.go","code":"// List takes label and field selectors, and returns the list of ClusterRoles that match those selectors.\nfunc (c *clusterRoles) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.ClusterRoleList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.ClusterRoleList{}\n\terr = c.client.Get().\n\t\tResource(\"clusterroles\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100027349,"name":"Watch","signature":"func (c *clusterRoles) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/clusterrole.go","code":"// Watch returns a watch.Interface that watches the requested clusterRoles.\nfunc (c *clusterRoles) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"clusterroles\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100027350,"name":"Create","signature":"func (c *clusterRoles) Create(ctx context.Context, clusterRole *v1beta1.ClusterRole, opts v1.CreateOptions) (result *v1beta1.ClusterRole, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/clusterrole.go","code":"// Create takes the representation of a clusterRole and creates it. Returns the server's representation of the clusterRole, and an error, if there is any.\nfunc (c *clusterRoles) Create(ctx context.Context, clusterRole *v1beta1.ClusterRole, opts v1.CreateOptions) (result *v1beta1.ClusterRole, err error) {\n\tresult = \u0026v1beta1.ClusterRole{}\n\terr = c.client.Post().\n\t\tResource(\"clusterroles\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(clusterRole).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100027351,"name":"Update","signature":"func (c *clusterRoles) Update(ctx context.Context, clusterRole *v1beta1.ClusterRole, opts v1.UpdateOptions) (result *v1beta1.ClusterRole, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/clusterrole.go","code":"// Update takes the representation of a clusterRole and updates it. Returns the server's representation of the clusterRole, and an error, if there is any.\nfunc (c *clusterRoles) Update(ctx context.Context, clusterRole *v1beta1.ClusterRole, opts v1.UpdateOptions) (result *v1beta1.ClusterRole, err error) {\n\tresult = \u0026v1beta1.ClusterRole{}\n\terr = c.client.Put().\n\t\tResource(\"clusterroles\").\n\t\tName(clusterRole.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(clusterRole).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100027352,"name":"Delete","signature":"func (c *clusterRoles) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/clusterrole.go","code":"// Delete takes name of the clusterRole and deletes it. Returns an error if one occurs.\nfunc (c *clusterRoles) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"clusterroles\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100027353,"name":"DeleteCollection","signature":"func (c *clusterRoles) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/clusterrole.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *clusterRoles) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"clusterroles\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100027354,"name":"Patch","signature":"func (c *clusterRoles) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.ClusterRole, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/clusterrole.go","code":"// Patch applies the patch and returns the patched clusterRole.\nfunc (c *clusterRoles) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.ClusterRole, err error) {\n\tresult = \u0026v1beta1.ClusterRole{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"clusterroles\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100027355,"name":"Apply","signature":"func (c *clusterRoles) Apply(ctx context.Context, clusterRole *rbacv1beta1.ClusterRoleApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.ClusterRole, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/clusterrole.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied clusterRole.\nfunc (c *clusterRoles) Apply(ctx context.Context, clusterRole *rbacv1beta1.ClusterRoleApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.ClusterRole, err error) {\n\tif clusterRole == nil {\n\t\treturn nil, fmt.Errorf(\"clusterRole provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(clusterRole)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := clusterRole.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"clusterRole.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.ClusterRole{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"clusterroles\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100027356,"name":"newClusterRoleBindings","signature":"func newClusterRoleBindings(c *RbacV1beta1Client) *clusterRoleBindings","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/clusterrolebinding.go","code":"// newClusterRoleBindings returns a ClusterRoleBindings\nfunc newClusterRoleBindings(c *RbacV1beta1Client) *clusterRoleBindings {\n\treturn \u0026clusterRoleBindings{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100027357,"name":"Get","signature":"func (c *clusterRoleBindings) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.ClusterRoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/clusterrolebinding.go","code":"// Get takes name of the clusterRoleBinding, and returns the corresponding clusterRoleBinding object, and an error if there is any.\nfunc (c *clusterRoleBindings) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.ClusterRoleBinding, err error) {\n\tresult = \u0026v1beta1.ClusterRoleBinding{}\n\terr = c.client.Get().\n\t\tResource(\"clusterrolebindings\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100027358,"name":"List","signature":"func (c *clusterRoleBindings) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.ClusterRoleBindingList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/clusterrolebinding.go","code":"// List takes label and field selectors, and returns the list of ClusterRoleBindings that match those selectors.\nfunc (c *clusterRoleBindings) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.ClusterRoleBindingList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.ClusterRoleBindingList{}\n\terr = c.client.Get().\n\t\tResource(\"clusterrolebindings\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100027359,"name":"Watch","signature":"func (c *clusterRoleBindings) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/clusterrolebinding.go","code":"// Watch returns a watch.Interface that watches the requested clusterRoleBindings.\nfunc (c *clusterRoleBindings) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"clusterrolebindings\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100027360,"name":"Create","signature":"func (c *clusterRoleBindings) Create(ctx context.Context, clusterRoleBinding *v1beta1.ClusterRoleBinding, opts v1.CreateOptions) (result *v1beta1.ClusterRoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/clusterrolebinding.go","code":"// Create takes the representation of a clusterRoleBinding and creates it. Returns the server's representation of the clusterRoleBinding, and an error, if there is any.\nfunc (c *clusterRoleBindings) Create(ctx context.Context, clusterRoleBinding *v1beta1.ClusterRoleBinding, opts v1.CreateOptions) (result *v1beta1.ClusterRoleBinding, err error) {\n\tresult = \u0026v1beta1.ClusterRoleBinding{}\n\terr = c.client.Post().\n\t\tResource(\"clusterrolebindings\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(clusterRoleBinding).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100027361,"name":"Update","signature":"func (c *clusterRoleBindings) Update(ctx context.Context, clusterRoleBinding *v1beta1.ClusterRoleBinding, opts v1.UpdateOptions) (result *v1beta1.ClusterRoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/clusterrolebinding.go","code":"// Update takes the representation of a clusterRoleBinding and updates it. Returns the server's representation of the clusterRoleBinding, and an error, if there is any.\nfunc (c *clusterRoleBindings) Update(ctx context.Context, clusterRoleBinding *v1beta1.ClusterRoleBinding, opts v1.UpdateOptions) (result *v1beta1.ClusterRoleBinding, err error) {\n\tresult = \u0026v1beta1.ClusterRoleBinding{}\n\terr = c.client.Put().\n\t\tResource(\"clusterrolebindings\").\n\t\tName(clusterRoleBinding.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(clusterRoleBinding).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100027362,"name":"Delete","signature":"func (c *clusterRoleBindings) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/clusterrolebinding.go","code":"// Delete takes name of the clusterRoleBinding and deletes it. Returns an error if one occurs.\nfunc (c *clusterRoleBindings) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"clusterrolebindings\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100027363,"name":"DeleteCollection","signature":"func (c *clusterRoleBindings) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/clusterrolebinding.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *clusterRoleBindings) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"clusterrolebindings\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100027364,"name":"Patch","signature":"func (c *clusterRoleBindings) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.ClusterRoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/clusterrolebinding.go","code":"// Patch applies the patch and returns the patched clusterRoleBinding.\nfunc (c *clusterRoleBindings) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.ClusterRoleBinding, err error) {\n\tresult = \u0026v1beta1.ClusterRoleBinding{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"clusterrolebindings\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100027365,"name":"Apply","signature":"func (c *clusterRoleBindings) Apply(ctx context.Context, clusterRoleBinding *rbacv1beta1.ClusterRoleBindingApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.ClusterRoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/clusterrolebinding.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied clusterRoleBinding.\nfunc (c *clusterRoleBindings) Apply(ctx context.Context, clusterRoleBinding *rbacv1beta1.ClusterRoleBindingApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.ClusterRoleBinding, err error) {\n\tif clusterRoleBinding == nil {\n\t\treturn nil, fmt.Errorf(\"clusterRoleBinding provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(clusterRoleBinding)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := clusterRoleBinding.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"clusterRoleBinding.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.ClusterRoleBinding{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"clusterrolebindings\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100027366,"name":"ClusterRoles","signature":"func (c *RbacV1beta1Client) ClusterRoles() ClusterRoleInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/rbac_client.go","code":"func (c *RbacV1beta1Client) ClusterRoles() ClusterRoleInterface {\n\treturn newClusterRoles(c)\n}","line":{"from":42,"to":44}} {"id":100027367,"name":"ClusterRoleBindings","signature":"func (c *RbacV1beta1Client) ClusterRoleBindings() ClusterRoleBindingInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/rbac_client.go","code":"func (c *RbacV1beta1Client) ClusterRoleBindings() ClusterRoleBindingInterface {\n\treturn newClusterRoleBindings(c)\n}","line":{"from":46,"to":48}} {"id":100027368,"name":"Roles","signature":"func (c *RbacV1beta1Client) Roles(namespace string) RoleInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/rbac_client.go","code":"func (c *RbacV1beta1Client) Roles(namespace string) RoleInterface {\n\treturn newRoles(c, namespace)\n}","line":{"from":50,"to":52}} {"id":100027369,"name":"RoleBindings","signature":"func (c *RbacV1beta1Client) RoleBindings(namespace string) RoleBindingInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/rbac_client.go","code":"func (c *RbacV1beta1Client) RoleBindings(namespace string) RoleBindingInterface {\n\treturn newRoleBindings(c, namespace)\n}","line":{"from":54,"to":56}} {"id":100027370,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*RbacV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/rbac_client.go","code":"// NewForConfig creates a new RbacV1beta1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*RbacV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":58,"to":71}} {"id":100027371,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*RbacV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/rbac_client.go","code":"// NewForConfigAndClient creates a new RbacV1beta1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*RbacV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026RbacV1beta1Client{client}, nil\n}","line":{"from":73,"to":85}} {"id":100027372,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *RbacV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/rbac_client.go","code":"// NewForConfigOrDie creates a new RbacV1beta1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *RbacV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":87,"to":95}} {"id":100027373,"name":"New","signature":"func New(c rest.Interface) *RbacV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/rbac_client.go","code":"// New creates a new RbacV1beta1Client for the given RESTClient.\nfunc New(c rest.Interface) *RbacV1beta1Client {\n\treturn \u0026RbacV1beta1Client{c}\n}","line":{"from":97,"to":100}} {"id":100027374,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/rbac_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":102,"to":113}} {"id":100027375,"name":"RESTClient","signature":"func (c *RbacV1beta1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/rbac_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *RbacV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":115,"to":122}} {"id":100027376,"name":"newRoles","signature":"func newRoles(c *RbacV1beta1Client, namespace string) *roles","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/role.go","code":"// newRoles returns a Roles\nfunc newRoles(c *RbacV1beta1Client, namespace string) *roles {\n\treturn \u0026roles{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":62,"to":68}} {"id":100027377,"name":"Get","signature":"func (c *roles) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.Role, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/role.go","code":"// Get takes name of the role, and returns the corresponding role object, and an error if there is any.\nfunc (c *roles) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.Role, err error) {\n\tresult = \u0026v1beta1.Role{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":81}} {"id":100027378,"name":"List","signature":"func (c *roles) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.RoleList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/role.go","code":"// List takes label and field selectors, and returns the list of Roles that match those selectors.\nfunc (c *roles) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.RoleList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.RoleList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":83,"to":98}} {"id":100027379,"name":"Watch","signature":"func (c *roles) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/role.go","code":"// Watch returns a watch.Interface that watches the requested roles.\nfunc (c *roles) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":100,"to":113}} {"id":100027380,"name":"Create","signature":"func (c *roles) Create(ctx context.Context, role *v1beta1.Role, opts v1.CreateOptions) (result *v1beta1.Role, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/role.go","code":"// Create takes the representation of a role and creates it. Returns the server's representation of the role, and an error, if there is any.\nfunc (c *roles) Create(ctx context.Context, role *v1beta1.Role, opts v1.CreateOptions) (result *v1beta1.Role, err error) {\n\tresult = \u0026v1beta1.Role{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(role).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":115,"to":126}} {"id":100027381,"name":"Update","signature":"func (c *roles) Update(ctx context.Context, role *v1beta1.Role, opts v1.UpdateOptions) (result *v1beta1.Role, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/role.go","code":"// Update takes the representation of a role and updates it. Returns the server's representation of the role, and an error, if there is any.\nfunc (c *roles) Update(ctx context.Context, role *v1beta1.Role, opts v1.UpdateOptions) (result *v1beta1.Role, err error) {\n\tresult = \u0026v1beta1.Role{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tName(role.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(role).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":128,"to":140}} {"id":100027382,"name":"Delete","signature":"func (c *roles) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/role.go","code":"// Delete takes name of the role and deletes it. Returns an error if one occurs.\nfunc (c *roles) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":142,"to":151}} {"id":100027383,"name":"DeleteCollection","signature":"func (c *roles) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/role.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *roles) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":153,"to":167}} {"id":100027384,"name":"Patch","signature":"func (c *roles) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.Role, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/role.go","code":"// Patch applies the patch and returns the patched role.\nfunc (c *roles) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.Role, err error) {\n\tresult = \u0026v1beta1.Role{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":169,"to":182}} {"id":100027385,"name":"Apply","signature":"func (c *roles) Apply(ctx context.Context, role *rbacv1beta1.RoleApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Role, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/role.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied role.\nfunc (c *roles) Apply(ctx context.Context, role *rbacv1beta1.RoleApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.Role, err error) {\n\tif role == nil {\n\t\treturn nil, fmt.Errorf(\"role provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(role)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := role.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"role.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.Role{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"roles\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":184,"to":208}} {"id":100027386,"name":"newRoleBindings","signature":"func newRoleBindings(c *RbacV1beta1Client, namespace string) *roleBindings","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/rolebinding.go","code":"// newRoleBindings returns a RoleBindings\nfunc newRoleBindings(c *RbacV1beta1Client, namespace string) *roleBindings {\n\treturn \u0026roleBindings{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":62,"to":68}} {"id":100027387,"name":"Get","signature":"func (c *roleBindings) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.RoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/rolebinding.go","code":"// Get takes name of the roleBinding, and returns the corresponding roleBinding object, and an error if there is any.\nfunc (c *roleBindings) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.RoleBinding, err error) {\n\tresult = \u0026v1beta1.RoleBinding{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":81}} {"id":100027388,"name":"List","signature":"func (c *roleBindings) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.RoleBindingList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/rolebinding.go","code":"// List takes label and field selectors, and returns the list of RoleBindings that match those selectors.\nfunc (c *roleBindings) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.RoleBindingList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.RoleBindingList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":83,"to":98}} {"id":100027389,"name":"Watch","signature":"func (c *roleBindings) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/rolebinding.go","code":"// Watch returns a watch.Interface that watches the requested roleBindings.\nfunc (c *roleBindings) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":100,"to":113}} {"id":100027390,"name":"Create","signature":"func (c *roleBindings) Create(ctx context.Context, roleBinding *v1beta1.RoleBinding, opts v1.CreateOptions) (result *v1beta1.RoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/rolebinding.go","code":"// Create takes the representation of a roleBinding and creates it. Returns the server's representation of the roleBinding, and an error, if there is any.\nfunc (c *roleBindings) Create(ctx context.Context, roleBinding *v1beta1.RoleBinding, opts v1.CreateOptions) (result *v1beta1.RoleBinding, err error) {\n\tresult = \u0026v1beta1.RoleBinding{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(roleBinding).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":115,"to":126}} {"id":100027391,"name":"Update","signature":"func (c *roleBindings) Update(ctx context.Context, roleBinding *v1beta1.RoleBinding, opts v1.UpdateOptions) (result *v1beta1.RoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/rolebinding.go","code":"// Update takes the representation of a roleBinding and updates it. Returns the server's representation of the roleBinding, and an error, if there is any.\nfunc (c *roleBindings) Update(ctx context.Context, roleBinding *v1beta1.RoleBinding, opts v1.UpdateOptions) (result *v1beta1.RoleBinding, err error) {\n\tresult = \u0026v1beta1.RoleBinding{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tName(roleBinding.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(roleBinding).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":128,"to":140}} {"id":100027392,"name":"Delete","signature":"func (c *roleBindings) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/rolebinding.go","code":"// Delete takes name of the roleBinding and deletes it. Returns an error if one occurs.\nfunc (c *roleBindings) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":142,"to":151}} {"id":100027393,"name":"DeleteCollection","signature":"func (c *roleBindings) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/rolebinding.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *roleBindings) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":153,"to":167}} {"id":100027394,"name":"Patch","signature":"func (c *roleBindings) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.RoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/rolebinding.go","code":"// Patch applies the patch and returns the patched roleBinding.\nfunc (c *roleBindings) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.RoleBinding, err error) {\n\tresult = \u0026v1beta1.RoleBinding{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":169,"to":182}} {"id":100027395,"name":"Apply","signature":"func (c *roleBindings) Apply(ctx context.Context, roleBinding *rbacv1beta1.RoleBindingApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.RoleBinding, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1beta1/rolebinding.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied roleBinding.\nfunc (c *roleBindings) Apply(ctx context.Context, roleBinding *rbacv1beta1.RoleBindingApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.RoleBinding, err error) {\n\tif roleBinding == nil {\n\t\treturn nil, fmt.Errorf(\"roleBinding provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(roleBinding)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := roleBinding.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"roleBinding.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.RoleBinding{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"rolebindings\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":184,"to":208}} {"id":100027396,"name":"newPodSchedulingContexts","signature":"func newPodSchedulingContexts(c *ResourceV1alpha2Client, namespace string) *podSchedulingContexts","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/podschedulingcontext.go","code":"// newPodSchedulingContexts returns a PodSchedulingContexts\nfunc newPodSchedulingContexts(c *ResourceV1alpha2Client, namespace string) *podSchedulingContexts {\n\treturn \u0026podSchedulingContexts{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":64,"to":70}} {"id":100027397,"name":"Get","signature":"func (c *podSchedulingContexts) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha2.PodSchedulingContext, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/podschedulingcontext.go","code":"// Get takes name of the podSchedulingContext, and returns the corresponding podSchedulingContext object, and an error if there is any.\nfunc (c *podSchedulingContexts) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha2.PodSchedulingContext, err error) {\n\tresult = \u0026v1alpha2.PodSchedulingContext{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"podschedulingcontexts\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":72,"to":83}} {"id":100027398,"name":"List","signature":"func (c *podSchedulingContexts) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha2.PodSchedulingContextList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/podschedulingcontext.go","code":"// List takes label and field selectors, and returns the list of PodSchedulingContexts that match those selectors.\nfunc (c *podSchedulingContexts) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha2.PodSchedulingContextList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1alpha2.PodSchedulingContextList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"podschedulingcontexts\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":85,"to":100}} {"id":100027399,"name":"Watch","signature":"func (c *podSchedulingContexts) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/podschedulingcontext.go","code":"// Watch returns a watch.Interface that watches the requested podSchedulingContexts.\nfunc (c *podSchedulingContexts) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"podschedulingcontexts\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":102,"to":115}} {"id":100027400,"name":"Create","signature":"func (c *podSchedulingContexts) Create(ctx context.Context, podSchedulingContext *v1alpha2.PodSchedulingContext, opts v1.CreateOptions) (result *v1alpha2.PodSchedulingContext, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/podschedulingcontext.go","code":"// Create takes the representation of a podSchedulingContext and creates it. Returns the server's representation of the podSchedulingContext, and an error, if there is any.\nfunc (c *podSchedulingContexts) Create(ctx context.Context, podSchedulingContext *v1alpha2.PodSchedulingContext, opts v1.CreateOptions) (result *v1alpha2.PodSchedulingContext, err error) {\n\tresult = \u0026v1alpha2.PodSchedulingContext{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"podschedulingcontexts\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(podSchedulingContext).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":117,"to":128}} {"id":100027401,"name":"Update","signature":"func (c *podSchedulingContexts) Update(ctx context.Context, podSchedulingContext *v1alpha2.PodSchedulingContext, opts v1.UpdateOptions) (result *v1alpha2.PodSchedulingContext, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/podschedulingcontext.go","code":"// Update takes the representation of a podSchedulingContext and updates it. Returns the server's representation of the podSchedulingContext, and an error, if there is any.\nfunc (c *podSchedulingContexts) Update(ctx context.Context, podSchedulingContext *v1alpha2.PodSchedulingContext, opts v1.UpdateOptions) (result *v1alpha2.PodSchedulingContext, err error) {\n\tresult = \u0026v1alpha2.PodSchedulingContext{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"podschedulingcontexts\").\n\t\tName(podSchedulingContext.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(podSchedulingContext).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":130,"to":142}} {"id":100027402,"name":"UpdateStatus","signature":"func (c *podSchedulingContexts) UpdateStatus(ctx context.Context, podSchedulingContext *v1alpha2.PodSchedulingContext, opts v1.UpdateOptions) (result *v1alpha2.PodSchedulingContext, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/podschedulingcontext.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *podSchedulingContexts) UpdateStatus(ctx context.Context, podSchedulingContext *v1alpha2.PodSchedulingContext, opts v1.UpdateOptions) (result *v1alpha2.PodSchedulingContext, err error) {\n\tresult = \u0026v1alpha2.PodSchedulingContext{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"podschedulingcontexts\").\n\t\tName(podSchedulingContext.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(podSchedulingContext).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":144,"to":158}} {"id":100027403,"name":"Delete","signature":"func (c *podSchedulingContexts) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/podschedulingcontext.go","code":"// Delete takes name of the podSchedulingContext and deletes it. Returns an error if one occurs.\nfunc (c *podSchedulingContexts) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"podschedulingcontexts\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":160,"to":169}} {"id":100027404,"name":"DeleteCollection","signature":"func (c *podSchedulingContexts) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/podschedulingcontext.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *podSchedulingContexts) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"podschedulingcontexts\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":171,"to":185}} {"id":100027405,"name":"Patch","signature":"func (c *podSchedulingContexts) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha2.PodSchedulingContext, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/podschedulingcontext.go","code":"// Patch applies the patch and returns the patched podSchedulingContext.\nfunc (c *podSchedulingContexts) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha2.PodSchedulingContext, err error) {\n\tresult = \u0026v1alpha2.PodSchedulingContext{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"podschedulingcontexts\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":187,"to":200}} {"id":100027406,"name":"Apply","signature":"func (c *podSchedulingContexts) Apply(ctx context.Context, podSchedulingContext *resourcev1alpha2.PodSchedulingContextApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha2.PodSchedulingContext, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/podschedulingcontext.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied podSchedulingContext.\nfunc (c *podSchedulingContexts) Apply(ctx context.Context, podSchedulingContext *resourcev1alpha2.PodSchedulingContextApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha2.PodSchedulingContext, err error) {\n\tif podSchedulingContext == nil {\n\t\treturn nil, fmt.Errorf(\"podSchedulingContext provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(podSchedulingContext)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := podSchedulingContext.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"podSchedulingContext.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1alpha2.PodSchedulingContext{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"podschedulingcontexts\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":202,"to":226}} {"id":100027407,"name":"ApplyStatus","signature":"func (c *podSchedulingContexts) ApplyStatus(ctx context.Context, podSchedulingContext *resourcev1alpha2.PodSchedulingContextApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha2.PodSchedulingContext, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/podschedulingcontext.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *podSchedulingContexts) ApplyStatus(ctx context.Context, podSchedulingContext *resourcev1alpha2.PodSchedulingContextApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha2.PodSchedulingContext, err error) {\n\tif podSchedulingContext == nil {\n\t\treturn nil, fmt.Errorf(\"podSchedulingContext provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(podSchedulingContext)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := podSchedulingContext.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"podSchedulingContext.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1alpha2.PodSchedulingContext{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"podschedulingcontexts\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":228,"to":256}} {"id":100027408,"name":"PodSchedulingContexts","signature":"func (c *ResourceV1alpha2Client) PodSchedulingContexts(namespace string) PodSchedulingContextInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resource_client.go","code":"func (c *ResourceV1alpha2Client) PodSchedulingContexts(namespace string) PodSchedulingContextInterface {\n\treturn newPodSchedulingContexts(c, namespace)\n}","line":{"from":42,"to":44}} {"id":100027409,"name":"ResourceClaims","signature":"func (c *ResourceV1alpha2Client) ResourceClaims(namespace string) ResourceClaimInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resource_client.go","code":"func (c *ResourceV1alpha2Client) ResourceClaims(namespace string) ResourceClaimInterface {\n\treturn newResourceClaims(c, namespace)\n}","line":{"from":46,"to":48}} {"id":100027410,"name":"ResourceClaimTemplates","signature":"func (c *ResourceV1alpha2Client) ResourceClaimTemplates(namespace string) ResourceClaimTemplateInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resource_client.go","code":"func (c *ResourceV1alpha2Client) ResourceClaimTemplates(namespace string) ResourceClaimTemplateInterface {\n\treturn newResourceClaimTemplates(c, namespace)\n}","line":{"from":50,"to":52}} {"id":100027411,"name":"ResourceClasses","signature":"func (c *ResourceV1alpha2Client) ResourceClasses() ResourceClassInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resource_client.go","code":"func (c *ResourceV1alpha2Client) ResourceClasses() ResourceClassInterface {\n\treturn newResourceClasses(c)\n}","line":{"from":54,"to":56}} {"id":100027412,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*ResourceV1alpha2Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resource_client.go","code":"// NewForConfig creates a new ResourceV1alpha2Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*ResourceV1alpha2Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":58,"to":71}} {"id":100027413,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*ResourceV1alpha2Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resource_client.go","code":"// NewForConfigAndClient creates a new ResourceV1alpha2Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*ResourceV1alpha2Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026ResourceV1alpha2Client{client}, nil\n}","line":{"from":73,"to":85}} {"id":100027414,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *ResourceV1alpha2Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resource_client.go","code":"// NewForConfigOrDie creates a new ResourceV1alpha2Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *ResourceV1alpha2Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":87,"to":95}} {"id":100027415,"name":"New","signature":"func New(c rest.Interface) *ResourceV1alpha2Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resource_client.go","code":"// New creates a new ResourceV1alpha2Client for the given RESTClient.\nfunc New(c rest.Interface) *ResourceV1alpha2Client {\n\treturn \u0026ResourceV1alpha2Client{c}\n}","line":{"from":97,"to":100}} {"id":100027416,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resource_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1alpha2.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":102,"to":113}} {"id":100027417,"name":"RESTClient","signature":"func (c *ResourceV1alpha2Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resource_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *ResourceV1alpha2Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":115,"to":122}} {"id":100027418,"name":"newResourceClaims","signature":"func newResourceClaims(c *ResourceV1alpha2Client, namespace string) *resourceClaims","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclaim.go","code":"// newResourceClaims returns a ResourceClaims\nfunc newResourceClaims(c *ResourceV1alpha2Client, namespace string) *resourceClaims {\n\treturn \u0026resourceClaims{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":64,"to":70}} {"id":100027419,"name":"Get","signature":"func (c *resourceClaims) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha2.ResourceClaim, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclaim.go","code":"// Get takes name of the resourceClaim, and returns the corresponding resourceClaim object, and an error if there is any.\nfunc (c *resourceClaims) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha2.ResourceClaim, err error) {\n\tresult = \u0026v1alpha2.ResourceClaim{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"resourceclaims\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":72,"to":83}} {"id":100027420,"name":"List","signature":"func (c *resourceClaims) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha2.ResourceClaimList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclaim.go","code":"// List takes label and field selectors, and returns the list of ResourceClaims that match those selectors.\nfunc (c *resourceClaims) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha2.ResourceClaimList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1alpha2.ResourceClaimList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"resourceclaims\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":85,"to":100}} {"id":100027421,"name":"Watch","signature":"func (c *resourceClaims) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclaim.go","code":"// Watch returns a watch.Interface that watches the requested resourceClaims.\nfunc (c *resourceClaims) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"resourceclaims\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":102,"to":115}} {"id":100027422,"name":"Create","signature":"func (c *resourceClaims) Create(ctx context.Context, resourceClaim *v1alpha2.ResourceClaim, opts v1.CreateOptions) (result *v1alpha2.ResourceClaim, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclaim.go","code":"// Create takes the representation of a resourceClaim and creates it. Returns the server's representation of the resourceClaim, and an error, if there is any.\nfunc (c *resourceClaims) Create(ctx context.Context, resourceClaim *v1alpha2.ResourceClaim, opts v1.CreateOptions) (result *v1alpha2.ResourceClaim, err error) {\n\tresult = \u0026v1alpha2.ResourceClaim{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"resourceclaims\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(resourceClaim).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":117,"to":128}} {"id":100027423,"name":"Update","signature":"func (c *resourceClaims) Update(ctx context.Context, resourceClaim *v1alpha2.ResourceClaim, opts v1.UpdateOptions) (result *v1alpha2.ResourceClaim, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclaim.go","code":"// Update takes the representation of a resourceClaim and updates it. Returns the server's representation of the resourceClaim, and an error, if there is any.\nfunc (c *resourceClaims) Update(ctx context.Context, resourceClaim *v1alpha2.ResourceClaim, opts v1.UpdateOptions) (result *v1alpha2.ResourceClaim, err error) {\n\tresult = \u0026v1alpha2.ResourceClaim{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"resourceclaims\").\n\t\tName(resourceClaim.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(resourceClaim).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":130,"to":142}} {"id":100027424,"name":"UpdateStatus","signature":"func (c *resourceClaims) UpdateStatus(ctx context.Context, resourceClaim *v1alpha2.ResourceClaim, opts v1.UpdateOptions) (result *v1alpha2.ResourceClaim, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclaim.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *resourceClaims) UpdateStatus(ctx context.Context, resourceClaim *v1alpha2.ResourceClaim, opts v1.UpdateOptions) (result *v1alpha2.ResourceClaim, err error) {\n\tresult = \u0026v1alpha2.ResourceClaim{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"resourceclaims\").\n\t\tName(resourceClaim.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(resourceClaim).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":144,"to":158}} {"id":100027425,"name":"Delete","signature":"func (c *resourceClaims) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclaim.go","code":"// Delete takes name of the resourceClaim and deletes it. Returns an error if one occurs.\nfunc (c *resourceClaims) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"resourceclaims\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":160,"to":169}} {"id":100027426,"name":"DeleteCollection","signature":"func (c *resourceClaims) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclaim.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *resourceClaims) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"resourceclaims\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":171,"to":185}} {"id":100027427,"name":"Patch","signature":"func (c *resourceClaims) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha2.ResourceClaim, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclaim.go","code":"// Patch applies the patch and returns the patched resourceClaim.\nfunc (c *resourceClaims) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha2.ResourceClaim, err error) {\n\tresult = \u0026v1alpha2.ResourceClaim{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"resourceclaims\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":187,"to":200}} {"id":100027428,"name":"Apply","signature":"func (c *resourceClaims) Apply(ctx context.Context, resourceClaim *resourcev1alpha2.ResourceClaimApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha2.ResourceClaim, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclaim.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied resourceClaim.\nfunc (c *resourceClaims) Apply(ctx context.Context, resourceClaim *resourcev1alpha2.ResourceClaimApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha2.ResourceClaim, err error) {\n\tif resourceClaim == nil {\n\t\treturn nil, fmt.Errorf(\"resourceClaim provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(resourceClaim)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := resourceClaim.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"resourceClaim.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1alpha2.ResourceClaim{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"resourceclaims\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":202,"to":226}} {"id":100027429,"name":"ApplyStatus","signature":"func (c *resourceClaims) ApplyStatus(ctx context.Context, resourceClaim *resourcev1alpha2.ResourceClaimApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha2.ResourceClaim, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclaim.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *resourceClaims) ApplyStatus(ctx context.Context, resourceClaim *resourcev1alpha2.ResourceClaimApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha2.ResourceClaim, err error) {\n\tif resourceClaim == nil {\n\t\treturn nil, fmt.Errorf(\"resourceClaim provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(resourceClaim)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := resourceClaim.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"resourceClaim.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1alpha2.ResourceClaim{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"resourceclaims\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":228,"to":256}} {"id":100027430,"name":"newResourceClaimTemplates","signature":"func newResourceClaimTemplates(c *ResourceV1alpha2Client, namespace string) *resourceClaimTemplates","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclaimtemplate.go","code":"// newResourceClaimTemplates returns a ResourceClaimTemplates\nfunc newResourceClaimTemplates(c *ResourceV1alpha2Client, namespace string) *resourceClaimTemplates {\n\treturn \u0026resourceClaimTemplates{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":62,"to":68}} {"id":100027431,"name":"Get","signature":"func (c *resourceClaimTemplates) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha2.ResourceClaimTemplate, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclaimtemplate.go","code":"// Get takes name of the resourceClaimTemplate, and returns the corresponding resourceClaimTemplate object, and an error if there is any.\nfunc (c *resourceClaimTemplates) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha2.ResourceClaimTemplate, err error) {\n\tresult = \u0026v1alpha2.ResourceClaimTemplate{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"resourceclaimtemplates\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":81}} {"id":100027432,"name":"List","signature":"func (c *resourceClaimTemplates) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha2.ResourceClaimTemplateList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclaimtemplate.go","code":"// List takes label and field selectors, and returns the list of ResourceClaimTemplates that match those selectors.\nfunc (c *resourceClaimTemplates) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha2.ResourceClaimTemplateList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1alpha2.ResourceClaimTemplateList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"resourceclaimtemplates\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":83,"to":98}} {"id":100027433,"name":"Watch","signature":"func (c *resourceClaimTemplates) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclaimtemplate.go","code":"// Watch returns a watch.Interface that watches the requested resourceClaimTemplates.\nfunc (c *resourceClaimTemplates) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"resourceclaimtemplates\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":100,"to":113}} {"id":100027434,"name":"Create","signature":"func (c *resourceClaimTemplates) Create(ctx context.Context, resourceClaimTemplate *v1alpha2.ResourceClaimTemplate, opts v1.CreateOptions) (result *v1alpha2.ResourceClaimTemplate, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclaimtemplate.go","code":"// Create takes the representation of a resourceClaimTemplate and creates it. Returns the server's representation of the resourceClaimTemplate, and an error, if there is any.\nfunc (c *resourceClaimTemplates) Create(ctx context.Context, resourceClaimTemplate *v1alpha2.ResourceClaimTemplate, opts v1.CreateOptions) (result *v1alpha2.ResourceClaimTemplate, err error) {\n\tresult = \u0026v1alpha2.ResourceClaimTemplate{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"resourceclaimtemplates\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(resourceClaimTemplate).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":115,"to":126}} {"id":100027435,"name":"Update","signature":"func (c *resourceClaimTemplates) Update(ctx context.Context, resourceClaimTemplate *v1alpha2.ResourceClaimTemplate, opts v1.UpdateOptions) (result *v1alpha2.ResourceClaimTemplate, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclaimtemplate.go","code":"// Update takes the representation of a resourceClaimTemplate and updates it. Returns the server's representation of the resourceClaimTemplate, and an error, if there is any.\nfunc (c *resourceClaimTemplates) Update(ctx context.Context, resourceClaimTemplate *v1alpha2.ResourceClaimTemplate, opts v1.UpdateOptions) (result *v1alpha2.ResourceClaimTemplate, err error) {\n\tresult = \u0026v1alpha2.ResourceClaimTemplate{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"resourceclaimtemplates\").\n\t\tName(resourceClaimTemplate.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(resourceClaimTemplate).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":128,"to":140}} {"id":100027436,"name":"Delete","signature":"func (c *resourceClaimTemplates) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclaimtemplate.go","code":"// Delete takes name of the resourceClaimTemplate and deletes it. Returns an error if one occurs.\nfunc (c *resourceClaimTemplates) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"resourceclaimtemplates\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":142,"to":151}} {"id":100027437,"name":"DeleteCollection","signature":"func (c *resourceClaimTemplates) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclaimtemplate.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *resourceClaimTemplates) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"resourceclaimtemplates\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":153,"to":167}} {"id":100027438,"name":"Patch","signature":"func (c *resourceClaimTemplates) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha2.ResourceClaimTemplate, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclaimtemplate.go","code":"// Patch applies the patch and returns the patched resourceClaimTemplate.\nfunc (c *resourceClaimTemplates) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha2.ResourceClaimTemplate, err error) {\n\tresult = \u0026v1alpha2.ResourceClaimTemplate{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"resourceclaimtemplates\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":169,"to":182}} {"id":100027439,"name":"Apply","signature":"func (c *resourceClaimTemplates) Apply(ctx context.Context, resourceClaimTemplate *resourcev1alpha2.ResourceClaimTemplateApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha2.ResourceClaimTemplate, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclaimtemplate.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied resourceClaimTemplate.\nfunc (c *resourceClaimTemplates) Apply(ctx context.Context, resourceClaimTemplate *resourcev1alpha2.ResourceClaimTemplateApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha2.ResourceClaimTemplate, err error) {\n\tif resourceClaimTemplate == nil {\n\t\treturn nil, fmt.Errorf(\"resourceClaimTemplate provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(resourceClaimTemplate)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := resourceClaimTemplate.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"resourceClaimTemplate.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1alpha2.ResourceClaimTemplate{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"resourceclaimtemplates\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":184,"to":208}} {"id":100027440,"name":"newResourceClasses","signature":"func newResourceClasses(c *ResourceV1alpha2Client) *resourceClasses","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclass.go","code":"// newResourceClasses returns a ResourceClasses\nfunc newResourceClasses(c *ResourceV1alpha2Client) *resourceClasses {\n\treturn \u0026resourceClasses{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100027441,"name":"Get","signature":"func (c *resourceClasses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha2.ResourceClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclass.go","code":"// Get takes name of the resourceClass, and returns the corresponding resourceClass object, and an error if there is any.\nfunc (c *resourceClasses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha2.ResourceClass, err error) {\n\tresult = \u0026v1alpha2.ResourceClass{}\n\terr = c.client.Get().\n\t\tResource(\"resourceclasses\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100027442,"name":"List","signature":"func (c *resourceClasses) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha2.ResourceClassList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclass.go","code":"// List takes label and field selectors, and returns the list of ResourceClasses that match those selectors.\nfunc (c *resourceClasses) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha2.ResourceClassList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1alpha2.ResourceClassList{}\n\terr = c.client.Get().\n\t\tResource(\"resourceclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100027443,"name":"Watch","signature":"func (c *resourceClasses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclass.go","code":"// Watch returns a watch.Interface that watches the requested resourceClasses.\nfunc (c *resourceClasses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"resourceclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100027444,"name":"Create","signature":"func (c *resourceClasses) Create(ctx context.Context, resourceClass *v1alpha2.ResourceClass, opts v1.CreateOptions) (result *v1alpha2.ResourceClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclass.go","code":"// Create takes the representation of a resourceClass and creates it. Returns the server's representation of the resourceClass, and an error, if there is any.\nfunc (c *resourceClasses) Create(ctx context.Context, resourceClass *v1alpha2.ResourceClass, opts v1.CreateOptions) (result *v1alpha2.ResourceClass, err error) {\n\tresult = \u0026v1alpha2.ResourceClass{}\n\terr = c.client.Post().\n\t\tResource(\"resourceclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(resourceClass).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100027445,"name":"Update","signature":"func (c *resourceClasses) Update(ctx context.Context, resourceClass *v1alpha2.ResourceClass, opts v1.UpdateOptions) (result *v1alpha2.ResourceClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclass.go","code":"// Update takes the representation of a resourceClass and updates it. Returns the server's representation of the resourceClass, and an error, if there is any.\nfunc (c *resourceClasses) Update(ctx context.Context, resourceClass *v1alpha2.ResourceClass, opts v1.UpdateOptions) (result *v1alpha2.ResourceClass, err error) {\n\tresult = \u0026v1alpha2.ResourceClass{}\n\terr = c.client.Put().\n\t\tResource(\"resourceclasses\").\n\t\tName(resourceClass.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(resourceClass).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100027446,"name":"Delete","signature":"func (c *resourceClasses) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclass.go","code":"// Delete takes name of the resourceClass and deletes it. Returns an error if one occurs.\nfunc (c *resourceClasses) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"resourceclasses\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100027447,"name":"DeleteCollection","signature":"func (c *resourceClasses) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclass.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *resourceClasses) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"resourceclasses\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100027448,"name":"Patch","signature":"func (c *resourceClasses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha2.ResourceClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclass.go","code":"// Patch applies the patch and returns the patched resourceClass.\nfunc (c *resourceClasses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha2.ResourceClass, err error) {\n\tresult = \u0026v1alpha2.ResourceClass{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"resourceclasses\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100027449,"name":"Apply","signature":"func (c *resourceClasses) Apply(ctx context.Context, resourceClass *resourcev1alpha2.ResourceClassApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha2.ResourceClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/resource/v1alpha2/resourceclass.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied resourceClass.\nfunc (c *resourceClasses) Apply(ctx context.Context, resourceClass *resourcev1alpha2.ResourceClassApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha2.ResourceClass, err error) {\n\tif resourceClass == nil {\n\t\treturn nil, fmt.Errorf(\"resourceClass provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(resourceClass)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := resourceClass.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"resourceClass.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1alpha2.ResourceClass{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"resourceclasses\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100027450,"name":"newPriorityClasses","signature":"func newPriorityClasses(c *SchedulingV1Client) *priorityClasses","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1/priorityclass.go","code":"// newPriorityClasses returns a PriorityClasses\nfunc newPriorityClasses(c *SchedulingV1Client) *priorityClasses {\n\treturn \u0026priorityClasses{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100027451,"name":"Get","signature":"func (c *priorityClasses) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.PriorityClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1/priorityclass.go","code":"// Get takes name of the priorityClass, and returns the corresponding priorityClass object, and an error if there is any.\nfunc (c *priorityClasses) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.PriorityClass, err error) {\n\tresult = \u0026v1.PriorityClass{}\n\terr = c.client.Get().\n\t\tResource(\"priorityclasses\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100027452,"name":"List","signature":"func (c *priorityClasses) List(ctx context.Context, opts metav1.ListOptions) (result *v1.PriorityClassList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1/priorityclass.go","code":"// List takes label and field selectors, and returns the list of PriorityClasses that match those selectors.\nfunc (c *priorityClasses) List(ctx context.Context, opts metav1.ListOptions) (result *v1.PriorityClassList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.PriorityClassList{}\n\terr = c.client.Get().\n\t\tResource(\"priorityclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100027453,"name":"Watch","signature":"func (c *priorityClasses) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1/priorityclass.go","code":"// Watch returns a watch.Interface that watches the requested priorityClasses.\nfunc (c *priorityClasses) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"priorityclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100027454,"name":"Create","signature":"func (c *priorityClasses) Create(ctx context.Context, priorityClass *v1.PriorityClass, opts metav1.CreateOptions) (result *v1.PriorityClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1/priorityclass.go","code":"// Create takes the representation of a priorityClass and creates it. Returns the server's representation of the priorityClass, and an error, if there is any.\nfunc (c *priorityClasses) Create(ctx context.Context, priorityClass *v1.PriorityClass, opts metav1.CreateOptions) (result *v1.PriorityClass, err error) {\n\tresult = \u0026v1.PriorityClass{}\n\terr = c.client.Post().\n\t\tResource(\"priorityclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(priorityClass).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100027455,"name":"Update","signature":"func (c *priorityClasses) Update(ctx context.Context, priorityClass *v1.PriorityClass, opts metav1.UpdateOptions) (result *v1.PriorityClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1/priorityclass.go","code":"// Update takes the representation of a priorityClass and updates it. Returns the server's representation of the priorityClass, and an error, if there is any.\nfunc (c *priorityClasses) Update(ctx context.Context, priorityClass *v1.PriorityClass, opts metav1.UpdateOptions) (result *v1.PriorityClass, err error) {\n\tresult = \u0026v1.PriorityClass{}\n\terr = c.client.Put().\n\t\tResource(\"priorityclasses\").\n\t\tName(priorityClass.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(priorityClass).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100027456,"name":"Delete","signature":"func (c *priorityClasses) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1/priorityclass.go","code":"// Delete takes name of the priorityClass and deletes it. Returns an error if one occurs.\nfunc (c *priorityClasses) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"priorityclasses\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100027457,"name":"DeleteCollection","signature":"func (c *priorityClasses) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1/priorityclass.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *priorityClasses) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"priorityclasses\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100027458,"name":"Patch","signature":"func (c *priorityClasses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.PriorityClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1/priorityclass.go","code":"// Patch applies the patch and returns the patched priorityClass.\nfunc (c *priorityClasses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.PriorityClass, err error) {\n\tresult = \u0026v1.PriorityClass{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"priorityclasses\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100027459,"name":"Apply","signature":"func (c *priorityClasses) Apply(ctx context.Context, priorityClass *schedulingv1.PriorityClassApplyConfiguration, opts metav1.ApplyOptions) (result *v1.PriorityClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1/priorityclass.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied priorityClass.\nfunc (c *priorityClasses) Apply(ctx context.Context, priorityClass *schedulingv1.PriorityClassApplyConfiguration, opts metav1.ApplyOptions) (result *v1.PriorityClass, err error) {\n\tif priorityClass == nil {\n\t\treturn nil, fmt.Errorf(\"priorityClass provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(priorityClass)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := priorityClass.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"priorityClass.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.PriorityClass{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"priorityclasses\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100027460,"name":"PriorityClasses","signature":"func (c *SchedulingV1Client) PriorityClasses() PriorityClassInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1/scheduling_client.go","code":"func (c *SchedulingV1Client) PriorityClasses() PriorityClassInterface {\n\treturn newPriorityClasses(c)\n}","line":{"from":39,"to":41}} {"id":100027461,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*SchedulingV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1/scheduling_client.go","code":"// NewForConfig creates a new SchedulingV1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*SchedulingV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":43,"to":56}} {"id":100027462,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*SchedulingV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1/scheduling_client.go","code":"// NewForConfigAndClient creates a new SchedulingV1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*SchedulingV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026SchedulingV1Client{client}, nil\n}","line":{"from":58,"to":70}} {"id":100027463,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *SchedulingV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1/scheduling_client.go","code":"// NewForConfigOrDie creates a new SchedulingV1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *SchedulingV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":72,"to":80}} {"id":100027464,"name":"New","signature":"func New(c rest.Interface) *SchedulingV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1/scheduling_client.go","code":"// New creates a new SchedulingV1Client for the given RESTClient.\nfunc New(c rest.Interface) *SchedulingV1Client {\n\treturn \u0026SchedulingV1Client{c}\n}","line":{"from":82,"to":85}} {"id":100027465,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1/scheduling_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":87,"to":98}} {"id":100027466,"name":"RESTClient","signature":"func (c *SchedulingV1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1/scheduling_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *SchedulingV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":100,"to":107}} {"id":100027467,"name":"newPriorityClasses","signature":"func newPriorityClasses(c *SchedulingV1alpha1Client) *priorityClasses","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha1/priorityclass.go","code":"// newPriorityClasses returns a PriorityClasses\nfunc newPriorityClasses(c *SchedulingV1alpha1Client) *priorityClasses {\n\treturn \u0026priorityClasses{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100027468,"name":"Get","signature":"func (c *priorityClasses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.PriorityClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha1/priorityclass.go","code":"// Get takes name of the priorityClass, and returns the corresponding priorityClass object, and an error if there is any.\nfunc (c *priorityClasses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.PriorityClass, err error) {\n\tresult = \u0026v1alpha1.PriorityClass{}\n\terr = c.client.Get().\n\t\tResource(\"priorityclasses\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100027469,"name":"List","signature":"func (c *priorityClasses) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.PriorityClassList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha1/priorityclass.go","code":"// List takes label and field selectors, and returns the list of PriorityClasses that match those selectors.\nfunc (c *priorityClasses) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.PriorityClassList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1alpha1.PriorityClassList{}\n\terr = c.client.Get().\n\t\tResource(\"priorityclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100027470,"name":"Watch","signature":"func (c *priorityClasses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha1/priorityclass.go","code":"// Watch returns a watch.Interface that watches the requested priorityClasses.\nfunc (c *priorityClasses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"priorityclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100027471,"name":"Create","signature":"func (c *priorityClasses) Create(ctx context.Context, priorityClass *v1alpha1.PriorityClass, opts v1.CreateOptions) (result *v1alpha1.PriorityClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha1/priorityclass.go","code":"// Create takes the representation of a priorityClass and creates it. Returns the server's representation of the priorityClass, and an error, if there is any.\nfunc (c *priorityClasses) Create(ctx context.Context, priorityClass *v1alpha1.PriorityClass, opts v1.CreateOptions) (result *v1alpha1.PriorityClass, err error) {\n\tresult = \u0026v1alpha1.PriorityClass{}\n\terr = c.client.Post().\n\t\tResource(\"priorityclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(priorityClass).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100027472,"name":"Update","signature":"func (c *priorityClasses) Update(ctx context.Context, priorityClass *v1alpha1.PriorityClass, opts v1.UpdateOptions) (result *v1alpha1.PriorityClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha1/priorityclass.go","code":"// Update takes the representation of a priorityClass and updates it. Returns the server's representation of the priorityClass, and an error, if there is any.\nfunc (c *priorityClasses) Update(ctx context.Context, priorityClass *v1alpha1.PriorityClass, opts v1.UpdateOptions) (result *v1alpha1.PriorityClass, err error) {\n\tresult = \u0026v1alpha1.PriorityClass{}\n\terr = c.client.Put().\n\t\tResource(\"priorityclasses\").\n\t\tName(priorityClass.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(priorityClass).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100027473,"name":"Delete","signature":"func (c *priorityClasses) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha1/priorityclass.go","code":"// Delete takes name of the priorityClass and deletes it. Returns an error if one occurs.\nfunc (c *priorityClasses) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"priorityclasses\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100027474,"name":"DeleteCollection","signature":"func (c *priorityClasses) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha1/priorityclass.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *priorityClasses) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"priorityclasses\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100027475,"name":"Patch","signature":"func (c *priorityClasses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.PriorityClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha1/priorityclass.go","code":"// Patch applies the patch and returns the patched priorityClass.\nfunc (c *priorityClasses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.PriorityClass, err error) {\n\tresult = \u0026v1alpha1.PriorityClass{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"priorityclasses\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100027476,"name":"Apply","signature":"func (c *priorityClasses) Apply(ctx context.Context, priorityClass *schedulingv1alpha1.PriorityClassApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.PriorityClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha1/priorityclass.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied priorityClass.\nfunc (c *priorityClasses) Apply(ctx context.Context, priorityClass *schedulingv1alpha1.PriorityClassApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.PriorityClass, err error) {\n\tif priorityClass == nil {\n\t\treturn nil, fmt.Errorf(\"priorityClass provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(priorityClass)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := priorityClass.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"priorityClass.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1alpha1.PriorityClass{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"priorityclasses\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100027477,"name":"PriorityClasses","signature":"func (c *SchedulingV1alpha1Client) PriorityClasses() PriorityClassInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha1/scheduling_client.go","code":"func (c *SchedulingV1alpha1Client) PriorityClasses() PriorityClassInterface {\n\treturn newPriorityClasses(c)\n}","line":{"from":39,"to":41}} {"id":100027478,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*SchedulingV1alpha1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha1/scheduling_client.go","code":"// NewForConfig creates a new SchedulingV1alpha1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*SchedulingV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":43,"to":56}} {"id":100027479,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*SchedulingV1alpha1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha1/scheduling_client.go","code":"// NewForConfigAndClient creates a new SchedulingV1alpha1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*SchedulingV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026SchedulingV1alpha1Client{client}, nil\n}","line":{"from":58,"to":70}} {"id":100027480,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *SchedulingV1alpha1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha1/scheduling_client.go","code":"// NewForConfigOrDie creates a new SchedulingV1alpha1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *SchedulingV1alpha1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":72,"to":80}} {"id":100027481,"name":"New","signature":"func New(c rest.Interface) *SchedulingV1alpha1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha1/scheduling_client.go","code":"// New creates a new SchedulingV1alpha1Client for the given RESTClient.\nfunc New(c rest.Interface) *SchedulingV1alpha1Client {\n\treturn \u0026SchedulingV1alpha1Client{c}\n}","line":{"from":82,"to":85}} {"id":100027482,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha1/scheduling_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1alpha1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":87,"to":98}} {"id":100027483,"name":"RESTClient","signature":"func (c *SchedulingV1alpha1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1alpha1/scheduling_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *SchedulingV1alpha1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":100,"to":107}} {"id":100027484,"name":"newPriorityClasses","signature":"func newPriorityClasses(c *SchedulingV1beta1Client) *priorityClasses","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/priorityclass.go","code":"// newPriorityClasses returns a PriorityClasses\nfunc newPriorityClasses(c *SchedulingV1beta1Client) *priorityClasses {\n\treturn \u0026priorityClasses{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100027485,"name":"Get","signature":"func (c *priorityClasses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.PriorityClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/priorityclass.go","code":"// Get takes name of the priorityClass, and returns the corresponding priorityClass object, and an error if there is any.\nfunc (c *priorityClasses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.PriorityClass, err error) {\n\tresult = \u0026v1beta1.PriorityClass{}\n\terr = c.client.Get().\n\t\tResource(\"priorityclasses\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100027486,"name":"List","signature":"func (c *priorityClasses) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.PriorityClassList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/priorityclass.go","code":"// List takes label and field selectors, and returns the list of PriorityClasses that match those selectors.\nfunc (c *priorityClasses) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.PriorityClassList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.PriorityClassList{}\n\terr = c.client.Get().\n\t\tResource(\"priorityclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100027487,"name":"Watch","signature":"func (c *priorityClasses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/priorityclass.go","code":"// Watch returns a watch.Interface that watches the requested priorityClasses.\nfunc (c *priorityClasses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"priorityclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100027488,"name":"Create","signature":"func (c *priorityClasses) Create(ctx context.Context, priorityClass *v1beta1.PriorityClass, opts v1.CreateOptions) (result *v1beta1.PriorityClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/priorityclass.go","code":"// Create takes the representation of a priorityClass and creates it. Returns the server's representation of the priorityClass, and an error, if there is any.\nfunc (c *priorityClasses) Create(ctx context.Context, priorityClass *v1beta1.PriorityClass, opts v1.CreateOptions) (result *v1beta1.PriorityClass, err error) {\n\tresult = \u0026v1beta1.PriorityClass{}\n\terr = c.client.Post().\n\t\tResource(\"priorityclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(priorityClass).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100027489,"name":"Update","signature":"func (c *priorityClasses) Update(ctx context.Context, priorityClass *v1beta1.PriorityClass, opts v1.UpdateOptions) (result *v1beta1.PriorityClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/priorityclass.go","code":"// Update takes the representation of a priorityClass and updates it. Returns the server's representation of the priorityClass, and an error, if there is any.\nfunc (c *priorityClasses) Update(ctx context.Context, priorityClass *v1beta1.PriorityClass, opts v1.UpdateOptions) (result *v1beta1.PriorityClass, err error) {\n\tresult = \u0026v1beta1.PriorityClass{}\n\terr = c.client.Put().\n\t\tResource(\"priorityclasses\").\n\t\tName(priorityClass.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(priorityClass).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100027490,"name":"Delete","signature":"func (c *priorityClasses) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/priorityclass.go","code":"// Delete takes name of the priorityClass and deletes it. Returns an error if one occurs.\nfunc (c *priorityClasses) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"priorityclasses\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100027491,"name":"DeleteCollection","signature":"func (c *priorityClasses) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/priorityclass.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *priorityClasses) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"priorityclasses\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100027492,"name":"Patch","signature":"func (c *priorityClasses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.PriorityClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/priorityclass.go","code":"// Patch applies the patch and returns the patched priorityClass.\nfunc (c *priorityClasses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.PriorityClass, err error) {\n\tresult = \u0026v1beta1.PriorityClass{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"priorityclasses\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100027493,"name":"Apply","signature":"func (c *priorityClasses) Apply(ctx context.Context, priorityClass *schedulingv1beta1.PriorityClassApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.PriorityClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/priorityclass.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied priorityClass.\nfunc (c *priorityClasses) Apply(ctx context.Context, priorityClass *schedulingv1beta1.PriorityClassApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.PriorityClass, err error) {\n\tif priorityClass == nil {\n\t\treturn nil, fmt.Errorf(\"priorityClass provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(priorityClass)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := priorityClass.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"priorityClass.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.PriorityClass{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"priorityclasses\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100027494,"name":"PriorityClasses","signature":"func (c *SchedulingV1beta1Client) PriorityClasses() PriorityClassInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/scheduling_client.go","code":"func (c *SchedulingV1beta1Client) PriorityClasses() PriorityClassInterface {\n\treturn newPriorityClasses(c)\n}","line":{"from":39,"to":41}} {"id":100027495,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*SchedulingV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/scheduling_client.go","code":"// NewForConfig creates a new SchedulingV1beta1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*SchedulingV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":43,"to":56}} {"id":100027496,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*SchedulingV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/scheduling_client.go","code":"// NewForConfigAndClient creates a new SchedulingV1beta1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*SchedulingV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026SchedulingV1beta1Client{client}, nil\n}","line":{"from":58,"to":70}} {"id":100027497,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *SchedulingV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/scheduling_client.go","code":"// NewForConfigOrDie creates a new SchedulingV1beta1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *SchedulingV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":72,"to":80}} {"id":100027498,"name":"New","signature":"func New(c rest.Interface) *SchedulingV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/scheduling_client.go","code":"// New creates a new SchedulingV1beta1Client for the given RESTClient.\nfunc New(c rest.Interface) *SchedulingV1beta1Client {\n\treturn \u0026SchedulingV1beta1Client{c}\n}","line":{"from":82,"to":85}} {"id":100027499,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/scheduling_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":87,"to":98}} {"id":100027500,"name":"RESTClient","signature":"func (c *SchedulingV1beta1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/scheduling_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *SchedulingV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":100,"to":107}} {"id":100027501,"name":"newCSIDrivers","signature":"func newCSIDrivers(c *StorageV1Client) *cSIDrivers","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csidriver.go","code":"// newCSIDrivers returns a CSIDrivers\nfunc newCSIDrivers(c *StorageV1Client) *cSIDrivers {\n\treturn \u0026cSIDrivers{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100027502,"name":"Get","signature":"func (c *cSIDrivers) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.CSIDriver, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csidriver.go","code":"// Get takes name of the cSIDriver, and returns the corresponding cSIDriver object, and an error if there is any.\nfunc (c *cSIDrivers) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.CSIDriver, err error) {\n\tresult = \u0026v1.CSIDriver{}\n\terr = c.client.Get().\n\t\tResource(\"csidrivers\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100027503,"name":"List","signature":"func (c *cSIDrivers) List(ctx context.Context, opts metav1.ListOptions) (result *v1.CSIDriverList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csidriver.go","code":"// List takes label and field selectors, and returns the list of CSIDrivers that match those selectors.\nfunc (c *cSIDrivers) List(ctx context.Context, opts metav1.ListOptions) (result *v1.CSIDriverList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.CSIDriverList{}\n\terr = c.client.Get().\n\t\tResource(\"csidrivers\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100027504,"name":"Watch","signature":"func (c *cSIDrivers) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csidriver.go","code":"// Watch returns a watch.Interface that watches the requested cSIDrivers.\nfunc (c *cSIDrivers) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"csidrivers\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100027505,"name":"Create","signature":"func (c *cSIDrivers) Create(ctx context.Context, cSIDriver *v1.CSIDriver, opts metav1.CreateOptions) (result *v1.CSIDriver, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csidriver.go","code":"// Create takes the representation of a cSIDriver and creates it. Returns the server's representation of the cSIDriver, and an error, if there is any.\nfunc (c *cSIDrivers) Create(ctx context.Context, cSIDriver *v1.CSIDriver, opts metav1.CreateOptions) (result *v1.CSIDriver, err error) {\n\tresult = \u0026v1.CSIDriver{}\n\terr = c.client.Post().\n\t\tResource(\"csidrivers\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(cSIDriver).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100027506,"name":"Update","signature":"func (c *cSIDrivers) Update(ctx context.Context, cSIDriver *v1.CSIDriver, opts metav1.UpdateOptions) (result *v1.CSIDriver, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csidriver.go","code":"// Update takes the representation of a cSIDriver and updates it. Returns the server's representation of the cSIDriver, and an error, if there is any.\nfunc (c *cSIDrivers) Update(ctx context.Context, cSIDriver *v1.CSIDriver, opts metav1.UpdateOptions) (result *v1.CSIDriver, err error) {\n\tresult = \u0026v1.CSIDriver{}\n\terr = c.client.Put().\n\t\tResource(\"csidrivers\").\n\t\tName(cSIDriver.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(cSIDriver).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100027507,"name":"Delete","signature":"func (c *cSIDrivers) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csidriver.go","code":"// Delete takes name of the cSIDriver and deletes it. Returns an error if one occurs.\nfunc (c *cSIDrivers) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"csidrivers\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100027508,"name":"DeleteCollection","signature":"func (c *cSIDrivers) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csidriver.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *cSIDrivers) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"csidrivers\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100027509,"name":"Patch","signature":"func (c *cSIDrivers) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.CSIDriver, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csidriver.go","code":"// Patch applies the patch and returns the patched cSIDriver.\nfunc (c *cSIDrivers) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.CSIDriver, err error) {\n\tresult = \u0026v1.CSIDriver{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"csidrivers\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100027510,"name":"Apply","signature":"func (c *cSIDrivers) Apply(ctx context.Context, cSIDriver *storagev1.CSIDriverApplyConfiguration, opts metav1.ApplyOptions) (result *v1.CSIDriver, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csidriver.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied cSIDriver.\nfunc (c *cSIDrivers) Apply(ctx context.Context, cSIDriver *storagev1.CSIDriverApplyConfiguration, opts metav1.ApplyOptions) (result *v1.CSIDriver, err error) {\n\tif cSIDriver == nil {\n\t\treturn nil, fmt.Errorf(\"cSIDriver provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(cSIDriver)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := cSIDriver.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"cSIDriver.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.CSIDriver{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"csidrivers\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100027511,"name":"newCSINodes","signature":"func newCSINodes(c *StorageV1Client) *cSINodes","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csinode.go","code":"// newCSINodes returns a CSINodes\nfunc newCSINodes(c *StorageV1Client) *cSINodes {\n\treturn \u0026cSINodes{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100027512,"name":"Get","signature":"func (c *cSINodes) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.CSINode, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csinode.go","code":"// Get takes name of the cSINode, and returns the corresponding cSINode object, and an error if there is any.\nfunc (c *cSINodes) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.CSINode, err error) {\n\tresult = \u0026v1.CSINode{}\n\terr = c.client.Get().\n\t\tResource(\"csinodes\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100027513,"name":"List","signature":"func (c *cSINodes) List(ctx context.Context, opts metav1.ListOptions) (result *v1.CSINodeList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csinode.go","code":"// List takes label and field selectors, and returns the list of CSINodes that match those selectors.\nfunc (c *cSINodes) List(ctx context.Context, opts metav1.ListOptions) (result *v1.CSINodeList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.CSINodeList{}\n\terr = c.client.Get().\n\t\tResource(\"csinodes\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100027514,"name":"Watch","signature":"func (c *cSINodes) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csinode.go","code":"// Watch returns a watch.Interface that watches the requested cSINodes.\nfunc (c *cSINodes) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"csinodes\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100027515,"name":"Create","signature":"func (c *cSINodes) Create(ctx context.Context, cSINode *v1.CSINode, opts metav1.CreateOptions) (result *v1.CSINode, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csinode.go","code":"// Create takes the representation of a cSINode and creates it. Returns the server's representation of the cSINode, and an error, if there is any.\nfunc (c *cSINodes) Create(ctx context.Context, cSINode *v1.CSINode, opts metav1.CreateOptions) (result *v1.CSINode, err error) {\n\tresult = \u0026v1.CSINode{}\n\terr = c.client.Post().\n\t\tResource(\"csinodes\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(cSINode).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100027516,"name":"Update","signature":"func (c *cSINodes) Update(ctx context.Context, cSINode *v1.CSINode, opts metav1.UpdateOptions) (result *v1.CSINode, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csinode.go","code":"// Update takes the representation of a cSINode and updates it. Returns the server's representation of the cSINode, and an error, if there is any.\nfunc (c *cSINodes) Update(ctx context.Context, cSINode *v1.CSINode, opts metav1.UpdateOptions) (result *v1.CSINode, err error) {\n\tresult = \u0026v1.CSINode{}\n\terr = c.client.Put().\n\t\tResource(\"csinodes\").\n\t\tName(cSINode.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(cSINode).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100027517,"name":"Delete","signature":"func (c *cSINodes) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csinode.go","code":"// Delete takes name of the cSINode and deletes it. Returns an error if one occurs.\nfunc (c *cSINodes) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"csinodes\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100027518,"name":"DeleteCollection","signature":"func (c *cSINodes) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csinode.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *cSINodes) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"csinodes\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100027519,"name":"Patch","signature":"func (c *cSINodes) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.CSINode, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csinode.go","code":"// Patch applies the patch and returns the patched cSINode.\nfunc (c *cSINodes) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.CSINode, err error) {\n\tresult = \u0026v1.CSINode{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"csinodes\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100027520,"name":"Apply","signature":"func (c *cSINodes) Apply(ctx context.Context, cSINode *storagev1.CSINodeApplyConfiguration, opts metav1.ApplyOptions) (result *v1.CSINode, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csinode.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied cSINode.\nfunc (c *cSINodes) Apply(ctx context.Context, cSINode *storagev1.CSINodeApplyConfiguration, opts metav1.ApplyOptions) (result *v1.CSINode, err error) {\n\tif cSINode == nil {\n\t\treturn nil, fmt.Errorf(\"cSINode provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(cSINode)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := cSINode.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"cSINode.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.CSINode{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"csinodes\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100027521,"name":"newCSIStorageCapacities","signature":"func newCSIStorageCapacities(c *StorageV1Client, namespace string) *cSIStorageCapacities","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csistoragecapacity.go","code":"// newCSIStorageCapacities returns a CSIStorageCapacities\nfunc newCSIStorageCapacities(c *StorageV1Client, namespace string) *cSIStorageCapacities {\n\treturn \u0026cSIStorageCapacities{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":62,"to":68}} {"id":100027522,"name":"Get","signature":"func (c *cSIStorageCapacities) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.CSIStorageCapacity, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csistoragecapacity.go","code":"// Get takes name of the cSIStorageCapacity, and returns the corresponding cSIStorageCapacity object, and an error if there is any.\nfunc (c *cSIStorageCapacities) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.CSIStorageCapacity, err error) {\n\tresult = \u0026v1.CSIStorageCapacity{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":81}} {"id":100027523,"name":"List","signature":"func (c *cSIStorageCapacities) List(ctx context.Context, opts metav1.ListOptions) (result *v1.CSIStorageCapacityList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csistoragecapacity.go","code":"// List takes label and field selectors, and returns the list of CSIStorageCapacities that match those selectors.\nfunc (c *cSIStorageCapacities) List(ctx context.Context, opts metav1.ListOptions) (result *v1.CSIStorageCapacityList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.CSIStorageCapacityList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":83,"to":98}} {"id":100027524,"name":"Watch","signature":"func (c *cSIStorageCapacities) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csistoragecapacity.go","code":"// Watch returns a watch.Interface that watches the requested cSIStorageCapacities.\nfunc (c *cSIStorageCapacities) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":100,"to":113}} {"id":100027525,"name":"Create","signature":"func (c *cSIStorageCapacities) Create(ctx context.Context, cSIStorageCapacity *v1.CSIStorageCapacity, opts metav1.CreateOptions) (result *v1.CSIStorageCapacity, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csistoragecapacity.go","code":"// Create takes the representation of a cSIStorageCapacity and creates it. Returns the server's representation of the cSIStorageCapacity, and an error, if there is any.\nfunc (c *cSIStorageCapacities) Create(ctx context.Context, cSIStorageCapacity *v1.CSIStorageCapacity, opts metav1.CreateOptions) (result *v1.CSIStorageCapacity, err error) {\n\tresult = \u0026v1.CSIStorageCapacity{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(cSIStorageCapacity).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":115,"to":126}} {"id":100027526,"name":"Update","signature":"func (c *cSIStorageCapacities) Update(ctx context.Context, cSIStorageCapacity *v1.CSIStorageCapacity, opts metav1.UpdateOptions) (result *v1.CSIStorageCapacity, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csistoragecapacity.go","code":"// Update takes the representation of a cSIStorageCapacity and updates it. Returns the server's representation of the cSIStorageCapacity, and an error, if there is any.\nfunc (c *cSIStorageCapacities) Update(ctx context.Context, cSIStorageCapacity *v1.CSIStorageCapacity, opts metav1.UpdateOptions) (result *v1.CSIStorageCapacity, err error) {\n\tresult = \u0026v1.CSIStorageCapacity{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tName(cSIStorageCapacity.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(cSIStorageCapacity).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":128,"to":140}} {"id":100027527,"name":"Delete","signature":"func (c *cSIStorageCapacities) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csistoragecapacity.go","code":"// Delete takes name of the cSIStorageCapacity and deletes it. Returns an error if one occurs.\nfunc (c *cSIStorageCapacities) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":142,"to":151}} {"id":100027528,"name":"DeleteCollection","signature":"func (c *cSIStorageCapacities) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csistoragecapacity.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *cSIStorageCapacities) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":153,"to":167}} {"id":100027529,"name":"Patch","signature":"func (c *cSIStorageCapacities) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.CSIStorageCapacity, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csistoragecapacity.go","code":"// Patch applies the patch and returns the patched cSIStorageCapacity.\nfunc (c *cSIStorageCapacities) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.CSIStorageCapacity, err error) {\n\tresult = \u0026v1.CSIStorageCapacity{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":169,"to":182}} {"id":100027530,"name":"Apply","signature":"func (c *cSIStorageCapacities) Apply(ctx context.Context, cSIStorageCapacity *storagev1.CSIStorageCapacityApplyConfiguration, opts metav1.ApplyOptions) (result *v1.CSIStorageCapacity, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/csistoragecapacity.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied cSIStorageCapacity.\nfunc (c *cSIStorageCapacities) Apply(ctx context.Context, cSIStorageCapacity *storagev1.CSIStorageCapacityApplyConfiguration, opts metav1.ApplyOptions) (result *v1.CSIStorageCapacity, err error) {\n\tif cSIStorageCapacity == nil {\n\t\treturn nil, fmt.Errorf(\"cSIStorageCapacity provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(cSIStorageCapacity)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := cSIStorageCapacity.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"cSIStorageCapacity.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.CSIStorageCapacity{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":184,"to":208}} {"id":100027531,"name":"CSIDrivers","signature":"func (c *StorageV1Client) CSIDrivers() CSIDriverInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/storage_client.go","code":"func (c *StorageV1Client) CSIDrivers() CSIDriverInterface {\n\treturn newCSIDrivers(c)\n}","line":{"from":43,"to":45}} {"id":100027532,"name":"CSINodes","signature":"func (c *StorageV1Client) CSINodes() CSINodeInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/storage_client.go","code":"func (c *StorageV1Client) CSINodes() CSINodeInterface {\n\treturn newCSINodes(c)\n}","line":{"from":47,"to":49}} {"id":100027533,"name":"CSIStorageCapacities","signature":"func (c *StorageV1Client) CSIStorageCapacities(namespace string) CSIStorageCapacityInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/storage_client.go","code":"func (c *StorageV1Client) CSIStorageCapacities(namespace string) CSIStorageCapacityInterface {\n\treturn newCSIStorageCapacities(c, namespace)\n}","line":{"from":51,"to":53}} {"id":100027534,"name":"StorageClasses","signature":"func (c *StorageV1Client) StorageClasses() StorageClassInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/storage_client.go","code":"func (c *StorageV1Client) StorageClasses() StorageClassInterface {\n\treturn newStorageClasses(c)\n}","line":{"from":55,"to":57}} {"id":100027535,"name":"VolumeAttachments","signature":"func (c *StorageV1Client) VolumeAttachments() VolumeAttachmentInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/storage_client.go","code":"func (c *StorageV1Client) VolumeAttachments() VolumeAttachmentInterface {\n\treturn newVolumeAttachments(c)\n}","line":{"from":59,"to":61}} {"id":100027536,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*StorageV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/storage_client.go","code":"// NewForConfig creates a new StorageV1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*StorageV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":63,"to":76}} {"id":100027537,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*StorageV1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/storage_client.go","code":"// NewForConfigAndClient creates a new StorageV1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*StorageV1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026StorageV1Client{client}, nil\n}","line":{"from":78,"to":90}} {"id":100027538,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *StorageV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/storage_client.go","code":"// NewForConfigOrDie creates a new StorageV1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *StorageV1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":92,"to":100}} {"id":100027539,"name":"New","signature":"func New(c rest.Interface) *StorageV1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/storage_client.go","code":"// New creates a new StorageV1Client for the given RESTClient.\nfunc New(c rest.Interface) *StorageV1Client {\n\treturn \u0026StorageV1Client{c}\n}","line":{"from":102,"to":105}} {"id":100027540,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/storage_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":107,"to":118}} {"id":100027541,"name":"RESTClient","signature":"func (c *StorageV1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/storage_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *StorageV1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":120,"to":127}} {"id":100027542,"name":"newStorageClasses","signature":"func newStorageClasses(c *StorageV1Client) *storageClasses","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/storageclass.go","code":"// newStorageClasses returns a StorageClasses\nfunc newStorageClasses(c *StorageV1Client) *storageClasses {\n\treturn \u0026storageClasses{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100027543,"name":"Get","signature":"func (c *storageClasses) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.StorageClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/storageclass.go","code":"// Get takes name of the storageClass, and returns the corresponding storageClass object, and an error if there is any.\nfunc (c *storageClasses) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.StorageClass, err error) {\n\tresult = \u0026v1.StorageClass{}\n\terr = c.client.Get().\n\t\tResource(\"storageclasses\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100027544,"name":"List","signature":"func (c *storageClasses) List(ctx context.Context, opts metav1.ListOptions) (result *v1.StorageClassList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/storageclass.go","code":"// List takes label and field selectors, and returns the list of StorageClasses that match those selectors.\nfunc (c *storageClasses) List(ctx context.Context, opts metav1.ListOptions) (result *v1.StorageClassList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.StorageClassList{}\n\terr = c.client.Get().\n\t\tResource(\"storageclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100027545,"name":"Watch","signature":"func (c *storageClasses) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/storageclass.go","code":"// Watch returns a watch.Interface that watches the requested storageClasses.\nfunc (c *storageClasses) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"storageclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100027546,"name":"Create","signature":"func (c *storageClasses) Create(ctx context.Context, storageClass *v1.StorageClass, opts metav1.CreateOptions) (result *v1.StorageClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/storageclass.go","code":"// Create takes the representation of a storageClass and creates it. Returns the server's representation of the storageClass, and an error, if there is any.\nfunc (c *storageClasses) Create(ctx context.Context, storageClass *v1.StorageClass, opts metav1.CreateOptions) (result *v1.StorageClass, err error) {\n\tresult = \u0026v1.StorageClass{}\n\terr = c.client.Post().\n\t\tResource(\"storageclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(storageClass).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100027547,"name":"Update","signature":"func (c *storageClasses) Update(ctx context.Context, storageClass *v1.StorageClass, opts metav1.UpdateOptions) (result *v1.StorageClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/storageclass.go","code":"// Update takes the representation of a storageClass and updates it. Returns the server's representation of the storageClass, and an error, if there is any.\nfunc (c *storageClasses) Update(ctx context.Context, storageClass *v1.StorageClass, opts metav1.UpdateOptions) (result *v1.StorageClass, err error) {\n\tresult = \u0026v1.StorageClass{}\n\terr = c.client.Put().\n\t\tResource(\"storageclasses\").\n\t\tName(storageClass.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(storageClass).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100027548,"name":"Delete","signature":"func (c *storageClasses) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/storageclass.go","code":"// Delete takes name of the storageClass and deletes it. Returns an error if one occurs.\nfunc (c *storageClasses) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"storageclasses\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100027549,"name":"DeleteCollection","signature":"func (c *storageClasses) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/storageclass.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *storageClasses) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"storageclasses\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100027550,"name":"Patch","signature":"func (c *storageClasses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.StorageClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/storageclass.go","code":"// Patch applies the patch and returns the patched storageClass.\nfunc (c *storageClasses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.StorageClass, err error) {\n\tresult = \u0026v1.StorageClass{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"storageclasses\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100027551,"name":"Apply","signature":"func (c *storageClasses) Apply(ctx context.Context, storageClass *storagev1.StorageClassApplyConfiguration, opts metav1.ApplyOptions) (result *v1.StorageClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/storageclass.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied storageClass.\nfunc (c *storageClasses) Apply(ctx context.Context, storageClass *storagev1.StorageClassApplyConfiguration, opts metav1.ApplyOptions) (result *v1.StorageClass, err error) {\n\tif storageClass == nil {\n\t\treturn nil, fmt.Errorf(\"storageClass provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(storageClass)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := storageClass.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"storageClass.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.StorageClass{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"storageclasses\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100027552,"name":"newVolumeAttachments","signature":"func newVolumeAttachments(c *StorageV1Client) *volumeAttachments","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/volumeattachment.go","code":"// newVolumeAttachments returns a VolumeAttachments\nfunc newVolumeAttachments(c *StorageV1Client) *volumeAttachments {\n\treturn \u0026volumeAttachments{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":63,"to":68}} {"id":100027553,"name":"Get","signature":"func (c *volumeAttachments) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.VolumeAttachment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/volumeattachment.go","code":"// Get takes name of the volumeAttachment, and returns the corresponding volumeAttachment object, and an error if there is any.\nfunc (c *volumeAttachments) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.VolumeAttachment, err error) {\n\tresult = \u0026v1.VolumeAttachment{}\n\terr = c.client.Get().\n\t\tResource(\"volumeattachments\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":80}} {"id":100027554,"name":"List","signature":"func (c *volumeAttachments) List(ctx context.Context, opts metav1.ListOptions) (result *v1.VolumeAttachmentList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/volumeattachment.go","code":"// List takes label and field selectors, and returns the list of VolumeAttachments that match those selectors.\nfunc (c *volumeAttachments) List(ctx context.Context, opts metav1.ListOptions) (result *v1.VolumeAttachmentList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1.VolumeAttachmentList{}\n\terr = c.client.Get().\n\t\tResource(\"volumeattachments\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":82,"to":96}} {"id":100027555,"name":"Watch","signature":"func (c *volumeAttachments) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/volumeattachment.go","code":"// Watch returns a watch.Interface that watches the requested volumeAttachments.\nfunc (c *volumeAttachments) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"volumeattachments\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":98,"to":110}} {"id":100027556,"name":"Create","signature":"func (c *volumeAttachments) Create(ctx context.Context, volumeAttachment *v1.VolumeAttachment, opts metav1.CreateOptions) (result *v1.VolumeAttachment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/volumeattachment.go","code":"// Create takes the representation of a volumeAttachment and creates it. Returns the server's representation of the volumeAttachment, and an error, if there is any.\nfunc (c *volumeAttachments) Create(ctx context.Context, volumeAttachment *v1.VolumeAttachment, opts metav1.CreateOptions) (result *v1.VolumeAttachment, err error) {\n\tresult = \u0026v1.VolumeAttachment{}\n\terr = c.client.Post().\n\t\tResource(\"volumeattachments\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(volumeAttachment).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":112,"to":122}} {"id":100027557,"name":"Update","signature":"func (c *volumeAttachments) Update(ctx context.Context, volumeAttachment *v1.VolumeAttachment, opts metav1.UpdateOptions) (result *v1.VolumeAttachment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/volumeattachment.go","code":"// Update takes the representation of a volumeAttachment and updates it. Returns the server's representation of the volumeAttachment, and an error, if there is any.\nfunc (c *volumeAttachments) Update(ctx context.Context, volumeAttachment *v1.VolumeAttachment, opts metav1.UpdateOptions) (result *v1.VolumeAttachment, err error) {\n\tresult = \u0026v1.VolumeAttachment{}\n\terr = c.client.Put().\n\t\tResource(\"volumeattachments\").\n\t\tName(volumeAttachment.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(volumeAttachment).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":124,"to":135}} {"id":100027558,"name":"UpdateStatus","signature":"func (c *volumeAttachments) UpdateStatus(ctx context.Context, volumeAttachment *v1.VolumeAttachment, opts metav1.UpdateOptions) (result *v1.VolumeAttachment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/volumeattachment.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *volumeAttachments) UpdateStatus(ctx context.Context, volumeAttachment *v1.VolumeAttachment, opts metav1.UpdateOptions) (result *v1.VolumeAttachment, err error) {\n\tresult = \u0026v1.VolumeAttachment{}\n\terr = c.client.Put().\n\t\tResource(\"volumeattachments\").\n\t\tName(volumeAttachment.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(volumeAttachment).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":137,"to":150}} {"id":100027559,"name":"Delete","signature":"func (c *volumeAttachments) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/volumeattachment.go","code":"// Delete takes name of the volumeAttachment and deletes it. Returns an error if one occurs.\nfunc (c *volumeAttachments) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"volumeattachments\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":152,"to":160}} {"id":100027560,"name":"DeleteCollection","signature":"func (c *volumeAttachments) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/volumeattachment.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *volumeAttachments) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"volumeattachments\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":162,"to":175}} {"id":100027561,"name":"Patch","signature":"func (c *volumeAttachments) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.VolumeAttachment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/volumeattachment.go","code":"// Patch applies the patch and returns the patched volumeAttachment.\nfunc (c *volumeAttachments) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.VolumeAttachment, err error) {\n\tresult = \u0026v1.VolumeAttachment{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"volumeattachments\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":177,"to":189}} {"id":100027562,"name":"Apply","signature":"func (c *volumeAttachments) Apply(ctx context.Context, volumeAttachment *storagev1.VolumeAttachmentApplyConfiguration, opts metav1.ApplyOptions) (result *v1.VolumeAttachment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/volumeattachment.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied volumeAttachment.\nfunc (c *volumeAttachments) Apply(ctx context.Context, volumeAttachment *storagev1.VolumeAttachmentApplyConfiguration, opts metav1.ApplyOptions) (result *v1.VolumeAttachment, err error) {\n\tif volumeAttachment == nil {\n\t\treturn nil, fmt.Errorf(\"volumeAttachment provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(volumeAttachment)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := volumeAttachment.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"volumeAttachment.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1.VolumeAttachment{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"volumeattachments\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":191,"to":214}} {"id":100027563,"name":"ApplyStatus","signature":"func (c *volumeAttachments) ApplyStatus(ctx context.Context, volumeAttachment *storagev1.VolumeAttachmentApplyConfiguration, opts metav1.ApplyOptions) (result *v1.VolumeAttachment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1/volumeattachment.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *volumeAttachments) ApplyStatus(ctx context.Context, volumeAttachment *storagev1.VolumeAttachmentApplyConfiguration, opts metav1.ApplyOptions) (result *v1.VolumeAttachment, err error) {\n\tif volumeAttachment == nil {\n\t\treturn nil, fmt.Errorf(\"volumeAttachment provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(volumeAttachment)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := volumeAttachment.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"volumeAttachment.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1.VolumeAttachment{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"volumeattachments\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":216,"to":243}} {"id":100027564,"name":"newCSIStorageCapacities","signature":"func newCSIStorageCapacities(c *StorageV1alpha1Client, namespace string) *cSIStorageCapacities","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/csistoragecapacity.go","code":"// newCSIStorageCapacities returns a CSIStorageCapacities\nfunc newCSIStorageCapacities(c *StorageV1alpha1Client, namespace string) *cSIStorageCapacities {\n\treturn \u0026cSIStorageCapacities{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":62,"to":68}} {"id":100027565,"name":"Get","signature":"func (c *cSIStorageCapacities) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.CSIStorageCapacity, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/csistoragecapacity.go","code":"// Get takes name of the cSIStorageCapacity, and returns the corresponding cSIStorageCapacity object, and an error if there is any.\nfunc (c *cSIStorageCapacities) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.CSIStorageCapacity, err error) {\n\tresult = \u0026v1alpha1.CSIStorageCapacity{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":81}} {"id":100027566,"name":"List","signature":"func (c *cSIStorageCapacities) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.CSIStorageCapacityList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/csistoragecapacity.go","code":"// List takes label and field selectors, and returns the list of CSIStorageCapacities that match those selectors.\nfunc (c *cSIStorageCapacities) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.CSIStorageCapacityList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1alpha1.CSIStorageCapacityList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":83,"to":98}} {"id":100027567,"name":"Watch","signature":"func (c *cSIStorageCapacities) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/csistoragecapacity.go","code":"// Watch returns a watch.Interface that watches the requested cSIStorageCapacities.\nfunc (c *cSIStorageCapacities) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":100,"to":113}} {"id":100027568,"name":"Create","signature":"func (c *cSIStorageCapacities) Create(ctx context.Context, cSIStorageCapacity *v1alpha1.CSIStorageCapacity, opts v1.CreateOptions) (result *v1alpha1.CSIStorageCapacity, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/csistoragecapacity.go","code":"// Create takes the representation of a cSIStorageCapacity and creates it. Returns the server's representation of the cSIStorageCapacity, and an error, if there is any.\nfunc (c *cSIStorageCapacities) Create(ctx context.Context, cSIStorageCapacity *v1alpha1.CSIStorageCapacity, opts v1.CreateOptions) (result *v1alpha1.CSIStorageCapacity, err error) {\n\tresult = \u0026v1alpha1.CSIStorageCapacity{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(cSIStorageCapacity).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":115,"to":126}} {"id":100027569,"name":"Update","signature":"func (c *cSIStorageCapacities) Update(ctx context.Context, cSIStorageCapacity *v1alpha1.CSIStorageCapacity, opts v1.UpdateOptions) (result *v1alpha1.CSIStorageCapacity, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/csistoragecapacity.go","code":"// Update takes the representation of a cSIStorageCapacity and updates it. Returns the server's representation of the cSIStorageCapacity, and an error, if there is any.\nfunc (c *cSIStorageCapacities) Update(ctx context.Context, cSIStorageCapacity *v1alpha1.CSIStorageCapacity, opts v1.UpdateOptions) (result *v1alpha1.CSIStorageCapacity, err error) {\n\tresult = \u0026v1alpha1.CSIStorageCapacity{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tName(cSIStorageCapacity.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(cSIStorageCapacity).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":128,"to":140}} {"id":100027570,"name":"Delete","signature":"func (c *cSIStorageCapacities) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/csistoragecapacity.go","code":"// Delete takes name of the cSIStorageCapacity and deletes it. Returns an error if one occurs.\nfunc (c *cSIStorageCapacities) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":142,"to":151}} {"id":100027571,"name":"DeleteCollection","signature":"func (c *cSIStorageCapacities) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/csistoragecapacity.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *cSIStorageCapacities) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":153,"to":167}} {"id":100027572,"name":"Patch","signature":"func (c *cSIStorageCapacities) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.CSIStorageCapacity, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/csistoragecapacity.go","code":"// Patch applies the patch and returns the patched cSIStorageCapacity.\nfunc (c *cSIStorageCapacities) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.CSIStorageCapacity, err error) {\n\tresult = \u0026v1alpha1.CSIStorageCapacity{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":169,"to":182}} {"id":100027573,"name":"Apply","signature":"func (c *cSIStorageCapacities) Apply(ctx context.Context, cSIStorageCapacity *storagev1alpha1.CSIStorageCapacityApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.CSIStorageCapacity, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/csistoragecapacity.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied cSIStorageCapacity.\nfunc (c *cSIStorageCapacities) Apply(ctx context.Context, cSIStorageCapacity *storagev1alpha1.CSIStorageCapacityApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.CSIStorageCapacity, err error) {\n\tif cSIStorageCapacity == nil {\n\t\treturn nil, fmt.Errorf(\"cSIStorageCapacity provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(cSIStorageCapacity)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := cSIStorageCapacity.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"cSIStorageCapacity.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1alpha1.CSIStorageCapacity{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":184,"to":208}} {"id":100027574,"name":"CSIStorageCapacities","signature":"func (c *StorageV1alpha1Client) CSIStorageCapacities(namespace string) CSIStorageCapacityInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/storage_client.go","code":"func (c *StorageV1alpha1Client) CSIStorageCapacities(namespace string) CSIStorageCapacityInterface {\n\treturn newCSIStorageCapacities(c, namespace)\n}","line":{"from":40,"to":42}} {"id":100027575,"name":"VolumeAttachments","signature":"func (c *StorageV1alpha1Client) VolumeAttachments() VolumeAttachmentInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/storage_client.go","code":"func (c *StorageV1alpha1Client) VolumeAttachments() VolumeAttachmentInterface {\n\treturn newVolumeAttachments(c)\n}","line":{"from":44,"to":46}} {"id":100027576,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*StorageV1alpha1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/storage_client.go","code":"// NewForConfig creates a new StorageV1alpha1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*StorageV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":48,"to":61}} {"id":100027577,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*StorageV1alpha1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/storage_client.go","code":"// NewForConfigAndClient creates a new StorageV1alpha1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*StorageV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026StorageV1alpha1Client{client}, nil\n}","line":{"from":63,"to":75}} {"id":100027578,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *StorageV1alpha1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/storage_client.go","code":"// NewForConfigOrDie creates a new StorageV1alpha1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *StorageV1alpha1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":77,"to":85}} {"id":100027579,"name":"New","signature":"func New(c rest.Interface) *StorageV1alpha1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/storage_client.go","code":"// New creates a new StorageV1alpha1Client for the given RESTClient.\nfunc New(c rest.Interface) *StorageV1alpha1Client {\n\treturn \u0026StorageV1alpha1Client{c}\n}","line":{"from":87,"to":90}} {"id":100027580,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/storage_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1alpha1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":92,"to":103}} {"id":100027581,"name":"RESTClient","signature":"func (c *StorageV1alpha1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/storage_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *StorageV1alpha1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":105,"to":112}} {"id":100027582,"name":"newVolumeAttachments","signature":"func newVolumeAttachments(c *StorageV1alpha1Client) *volumeAttachments","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/volumeattachment.go","code":"// newVolumeAttachments returns a VolumeAttachments\nfunc newVolumeAttachments(c *StorageV1alpha1Client) *volumeAttachments {\n\treturn \u0026volumeAttachments{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":63,"to":68}} {"id":100027583,"name":"Get","signature":"func (c *volumeAttachments) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.VolumeAttachment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/volumeattachment.go","code":"// Get takes name of the volumeAttachment, and returns the corresponding volumeAttachment object, and an error if there is any.\nfunc (c *volumeAttachments) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.VolumeAttachment, err error) {\n\tresult = \u0026v1alpha1.VolumeAttachment{}\n\terr = c.client.Get().\n\t\tResource(\"volumeattachments\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":80}} {"id":100027584,"name":"List","signature":"func (c *volumeAttachments) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.VolumeAttachmentList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/volumeattachment.go","code":"// List takes label and field selectors, and returns the list of VolumeAttachments that match those selectors.\nfunc (c *volumeAttachments) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.VolumeAttachmentList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1alpha1.VolumeAttachmentList{}\n\terr = c.client.Get().\n\t\tResource(\"volumeattachments\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":82,"to":96}} {"id":100027585,"name":"Watch","signature":"func (c *volumeAttachments) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/volumeattachment.go","code":"// Watch returns a watch.Interface that watches the requested volumeAttachments.\nfunc (c *volumeAttachments) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"volumeattachments\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":98,"to":110}} {"id":100027586,"name":"Create","signature":"func (c *volumeAttachments) Create(ctx context.Context, volumeAttachment *v1alpha1.VolumeAttachment, opts v1.CreateOptions) (result *v1alpha1.VolumeAttachment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/volumeattachment.go","code":"// Create takes the representation of a volumeAttachment and creates it. Returns the server's representation of the volumeAttachment, and an error, if there is any.\nfunc (c *volumeAttachments) Create(ctx context.Context, volumeAttachment *v1alpha1.VolumeAttachment, opts v1.CreateOptions) (result *v1alpha1.VolumeAttachment, err error) {\n\tresult = \u0026v1alpha1.VolumeAttachment{}\n\terr = c.client.Post().\n\t\tResource(\"volumeattachments\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(volumeAttachment).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":112,"to":122}} {"id":100027587,"name":"Update","signature":"func (c *volumeAttachments) Update(ctx context.Context, volumeAttachment *v1alpha1.VolumeAttachment, opts v1.UpdateOptions) (result *v1alpha1.VolumeAttachment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/volumeattachment.go","code":"// Update takes the representation of a volumeAttachment and updates it. Returns the server's representation of the volumeAttachment, and an error, if there is any.\nfunc (c *volumeAttachments) Update(ctx context.Context, volumeAttachment *v1alpha1.VolumeAttachment, opts v1.UpdateOptions) (result *v1alpha1.VolumeAttachment, err error) {\n\tresult = \u0026v1alpha1.VolumeAttachment{}\n\terr = c.client.Put().\n\t\tResource(\"volumeattachments\").\n\t\tName(volumeAttachment.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(volumeAttachment).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":124,"to":135}} {"id":100027588,"name":"UpdateStatus","signature":"func (c *volumeAttachments) UpdateStatus(ctx context.Context, volumeAttachment *v1alpha1.VolumeAttachment, opts v1.UpdateOptions) (result *v1alpha1.VolumeAttachment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/volumeattachment.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *volumeAttachments) UpdateStatus(ctx context.Context, volumeAttachment *v1alpha1.VolumeAttachment, opts v1.UpdateOptions) (result *v1alpha1.VolumeAttachment, err error) {\n\tresult = \u0026v1alpha1.VolumeAttachment{}\n\terr = c.client.Put().\n\t\tResource(\"volumeattachments\").\n\t\tName(volumeAttachment.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(volumeAttachment).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":137,"to":150}} {"id":100027589,"name":"Delete","signature":"func (c *volumeAttachments) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/volumeattachment.go","code":"// Delete takes name of the volumeAttachment and deletes it. Returns an error if one occurs.\nfunc (c *volumeAttachments) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"volumeattachments\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":152,"to":160}} {"id":100027590,"name":"DeleteCollection","signature":"func (c *volumeAttachments) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/volumeattachment.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *volumeAttachments) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"volumeattachments\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":162,"to":175}} {"id":100027591,"name":"Patch","signature":"func (c *volumeAttachments) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.VolumeAttachment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/volumeattachment.go","code":"// Patch applies the patch and returns the patched volumeAttachment.\nfunc (c *volumeAttachments) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.VolumeAttachment, err error) {\n\tresult = \u0026v1alpha1.VolumeAttachment{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"volumeattachments\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":177,"to":189}} {"id":100027592,"name":"Apply","signature":"func (c *volumeAttachments) Apply(ctx context.Context, volumeAttachment *storagev1alpha1.VolumeAttachmentApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.VolumeAttachment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/volumeattachment.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied volumeAttachment.\nfunc (c *volumeAttachments) Apply(ctx context.Context, volumeAttachment *storagev1alpha1.VolumeAttachmentApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.VolumeAttachment, err error) {\n\tif volumeAttachment == nil {\n\t\treturn nil, fmt.Errorf(\"volumeAttachment provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(volumeAttachment)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := volumeAttachment.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"volumeAttachment.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1alpha1.VolumeAttachment{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"volumeattachments\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":191,"to":214}} {"id":100027593,"name":"ApplyStatus","signature":"func (c *volumeAttachments) ApplyStatus(ctx context.Context, volumeAttachment *storagev1alpha1.VolumeAttachmentApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.VolumeAttachment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1alpha1/volumeattachment.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *volumeAttachments) ApplyStatus(ctx context.Context, volumeAttachment *storagev1alpha1.VolumeAttachmentApplyConfiguration, opts v1.ApplyOptions) (result *v1alpha1.VolumeAttachment, err error) {\n\tif volumeAttachment == nil {\n\t\treturn nil, fmt.Errorf(\"volumeAttachment provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(volumeAttachment)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := volumeAttachment.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"volumeAttachment.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1alpha1.VolumeAttachment{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"volumeattachments\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":216,"to":243}} {"id":100027594,"name":"newCSIDrivers","signature":"func newCSIDrivers(c *StorageV1beta1Client) *cSIDrivers","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csidriver.go","code":"// newCSIDrivers returns a CSIDrivers\nfunc newCSIDrivers(c *StorageV1beta1Client) *cSIDrivers {\n\treturn \u0026cSIDrivers{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100027595,"name":"Get","signature":"func (c *cSIDrivers) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.CSIDriver, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csidriver.go","code":"// Get takes name of the cSIDriver, and returns the corresponding cSIDriver object, and an error if there is any.\nfunc (c *cSIDrivers) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.CSIDriver, err error) {\n\tresult = \u0026v1beta1.CSIDriver{}\n\terr = c.client.Get().\n\t\tResource(\"csidrivers\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100027596,"name":"List","signature":"func (c *cSIDrivers) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.CSIDriverList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csidriver.go","code":"// List takes label and field selectors, and returns the list of CSIDrivers that match those selectors.\nfunc (c *cSIDrivers) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.CSIDriverList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.CSIDriverList{}\n\terr = c.client.Get().\n\t\tResource(\"csidrivers\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100027597,"name":"Watch","signature":"func (c *cSIDrivers) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csidriver.go","code":"// Watch returns a watch.Interface that watches the requested cSIDrivers.\nfunc (c *cSIDrivers) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"csidrivers\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100027598,"name":"Create","signature":"func (c *cSIDrivers) Create(ctx context.Context, cSIDriver *v1beta1.CSIDriver, opts v1.CreateOptions) (result *v1beta1.CSIDriver, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csidriver.go","code":"// Create takes the representation of a cSIDriver and creates it. Returns the server's representation of the cSIDriver, and an error, if there is any.\nfunc (c *cSIDrivers) Create(ctx context.Context, cSIDriver *v1beta1.CSIDriver, opts v1.CreateOptions) (result *v1beta1.CSIDriver, err error) {\n\tresult = \u0026v1beta1.CSIDriver{}\n\terr = c.client.Post().\n\t\tResource(\"csidrivers\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(cSIDriver).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100027599,"name":"Update","signature":"func (c *cSIDrivers) Update(ctx context.Context, cSIDriver *v1beta1.CSIDriver, opts v1.UpdateOptions) (result *v1beta1.CSIDriver, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csidriver.go","code":"// Update takes the representation of a cSIDriver and updates it. Returns the server's representation of the cSIDriver, and an error, if there is any.\nfunc (c *cSIDrivers) Update(ctx context.Context, cSIDriver *v1beta1.CSIDriver, opts v1.UpdateOptions) (result *v1beta1.CSIDriver, err error) {\n\tresult = \u0026v1beta1.CSIDriver{}\n\terr = c.client.Put().\n\t\tResource(\"csidrivers\").\n\t\tName(cSIDriver.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(cSIDriver).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100027600,"name":"Delete","signature":"func (c *cSIDrivers) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csidriver.go","code":"// Delete takes name of the cSIDriver and deletes it. Returns an error if one occurs.\nfunc (c *cSIDrivers) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"csidrivers\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100027601,"name":"DeleteCollection","signature":"func (c *cSIDrivers) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csidriver.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *cSIDrivers) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"csidrivers\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100027602,"name":"Patch","signature":"func (c *cSIDrivers) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.CSIDriver, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csidriver.go","code":"// Patch applies the patch and returns the patched cSIDriver.\nfunc (c *cSIDrivers) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.CSIDriver, err error) {\n\tresult = \u0026v1beta1.CSIDriver{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"csidrivers\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100027603,"name":"Apply","signature":"func (c *cSIDrivers) Apply(ctx context.Context, cSIDriver *storagev1beta1.CSIDriverApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.CSIDriver, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csidriver.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied cSIDriver.\nfunc (c *cSIDrivers) Apply(ctx context.Context, cSIDriver *storagev1beta1.CSIDriverApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.CSIDriver, err error) {\n\tif cSIDriver == nil {\n\t\treturn nil, fmt.Errorf(\"cSIDriver provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(cSIDriver)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := cSIDriver.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"cSIDriver.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.CSIDriver{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"csidrivers\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100027604,"name":"newCSINodes","signature":"func newCSINodes(c *StorageV1beta1Client) *cSINodes","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csinode.go","code":"// newCSINodes returns a CSINodes\nfunc newCSINodes(c *StorageV1beta1Client) *cSINodes {\n\treturn \u0026cSINodes{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100027605,"name":"Get","signature":"func (c *cSINodes) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.CSINode, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csinode.go","code":"// Get takes name of the cSINode, and returns the corresponding cSINode object, and an error if there is any.\nfunc (c *cSINodes) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.CSINode, err error) {\n\tresult = \u0026v1beta1.CSINode{}\n\terr = c.client.Get().\n\t\tResource(\"csinodes\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100027606,"name":"List","signature":"func (c *cSINodes) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.CSINodeList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csinode.go","code":"// List takes label and field selectors, and returns the list of CSINodes that match those selectors.\nfunc (c *cSINodes) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.CSINodeList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.CSINodeList{}\n\terr = c.client.Get().\n\t\tResource(\"csinodes\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100027607,"name":"Watch","signature":"func (c *cSINodes) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csinode.go","code":"// Watch returns a watch.Interface that watches the requested cSINodes.\nfunc (c *cSINodes) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"csinodes\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100027608,"name":"Create","signature":"func (c *cSINodes) Create(ctx context.Context, cSINode *v1beta1.CSINode, opts v1.CreateOptions) (result *v1beta1.CSINode, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csinode.go","code":"// Create takes the representation of a cSINode and creates it. Returns the server's representation of the cSINode, and an error, if there is any.\nfunc (c *cSINodes) Create(ctx context.Context, cSINode *v1beta1.CSINode, opts v1.CreateOptions) (result *v1beta1.CSINode, err error) {\n\tresult = \u0026v1beta1.CSINode{}\n\terr = c.client.Post().\n\t\tResource(\"csinodes\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(cSINode).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100027609,"name":"Update","signature":"func (c *cSINodes) Update(ctx context.Context, cSINode *v1beta1.CSINode, opts v1.UpdateOptions) (result *v1beta1.CSINode, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csinode.go","code":"// Update takes the representation of a cSINode and updates it. Returns the server's representation of the cSINode, and an error, if there is any.\nfunc (c *cSINodes) Update(ctx context.Context, cSINode *v1beta1.CSINode, opts v1.UpdateOptions) (result *v1beta1.CSINode, err error) {\n\tresult = \u0026v1beta1.CSINode{}\n\terr = c.client.Put().\n\t\tResource(\"csinodes\").\n\t\tName(cSINode.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(cSINode).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100027610,"name":"Delete","signature":"func (c *cSINodes) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csinode.go","code":"// Delete takes name of the cSINode and deletes it. Returns an error if one occurs.\nfunc (c *cSINodes) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"csinodes\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100027611,"name":"DeleteCollection","signature":"func (c *cSINodes) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csinode.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *cSINodes) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"csinodes\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100027612,"name":"Patch","signature":"func (c *cSINodes) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.CSINode, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csinode.go","code":"// Patch applies the patch and returns the patched cSINode.\nfunc (c *cSINodes) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.CSINode, err error) {\n\tresult = \u0026v1beta1.CSINode{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"csinodes\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100027613,"name":"Apply","signature":"func (c *cSINodes) Apply(ctx context.Context, cSINode *storagev1beta1.CSINodeApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.CSINode, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csinode.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied cSINode.\nfunc (c *cSINodes) Apply(ctx context.Context, cSINode *storagev1beta1.CSINodeApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.CSINode, err error) {\n\tif cSINode == nil {\n\t\treturn nil, fmt.Errorf(\"cSINode provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(cSINode)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := cSINode.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"cSINode.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.CSINode{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"csinodes\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100027614,"name":"newCSIStorageCapacities","signature":"func newCSIStorageCapacities(c *StorageV1beta1Client, namespace string) *cSIStorageCapacities","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csistoragecapacity.go","code":"// newCSIStorageCapacities returns a CSIStorageCapacities\nfunc newCSIStorageCapacities(c *StorageV1beta1Client, namespace string) *cSIStorageCapacities {\n\treturn \u0026cSIStorageCapacities{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":62,"to":68}} {"id":100027615,"name":"Get","signature":"func (c *cSIStorageCapacities) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.CSIStorageCapacity, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csistoragecapacity.go","code":"// Get takes name of the cSIStorageCapacity, and returns the corresponding cSIStorageCapacity object, and an error if there is any.\nfunc (c *cSIStorageCapacities) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.CSIStorageCapacity, err error) {\n\tresult = \u0026v1beta1.CSIStorageCapacity{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":81}} {"id":100027616,"name":"List","signature":"func (c *cSIStorageCapacities) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.CSIStorageCapacityList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csistoragecapacity.go","code":"// List takes label and field selectors, and returns the list of CSIStorageCapacities that match those selectors.\nfunc (c *cSIStorageCapacities) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.CSIStorageCapacityList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.CSIStorageCapacityList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":83,"to":98}} {"id":100027617,"name":"Watch","signature":"func (c *cSIStorageCapacities) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csistoragecapacity.go","code":"// Watch returns a watch.Interface that watches the requested cSIStorageCapacities.\nfunc (c *cSIStorageCapacities) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":100,"to":113}} {"id":100027618,"name":"Create","signature":"func (c *cSIStorageCapacities) Create(ctx context.Context, cSIStorageCapacity *v1beta1.CSIStorageCapacity, opts v1.CreateOptions) (result *v1beta1.CSIStorageCapacity, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csistoragecapacity.go","code":"// Create takes the representation of a cSIStorageCapacity and creates it. Returns the server's representation of the cSIStorageCapacity, and an error, if there is any.\nfunc (c *cSIStorageCapacities) Create(ctx context.Context, cSIStorageCapacity *v1beta1.CSIStorageCapacity, opts v1.CreateOptions) (result *v1beta1.CSIStorageCapacity, err error) {\n\tresult = \u0026v1beta1.CSIStorageCapacity{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(cSIStorageCapacity).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":115,"to":126}} {"id":100027619,"name":"Update","signature":"func (c *cSIStorageCapacities) Update(ctx context.Context, cSIStorageCapacity *v1beta1.CSIStorageCapacity, opts v1.UpdateOptions) (result *v1beta1.CSIStorageCapacity, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csistoragecapacity.go","code":"// Update takes the representation of a cSIStorageCapacity and updates it. Returns the server's representation of the cSIStorageCapacity, and an error, if there is any.\nfunc (c *cSIStorageCapacities) Update(ctx context.Context, cSIStorageCapacity *v1beta1.CSIStorageCapacity, opts v1.UpdateOptions) (result *v1beta1.CSIStorageCapacity, err error) {\n\tresult = \u0026v1beta1.CSIStorageCapacity{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tName(cSIStorageCapacity.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(cSIStorageCapacity).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":128,"to":140}} {"id":100027620,"name":"Delete","signature":"func (c *cSIStorageCapacities) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csistoragecapacity.go","code":"// Delete takes name of the cSIStorageCapacity and deletes it. Returns an error if one occurs.\nfunc (c *cSIStorageCapacities) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":142,"to":151}} {"id":100027621,"name":"DeleteCollection","signature":"func (c *cSIStorageCapacities) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csistoragecapacity.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *cSIStorageCapacities) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":153,"to":167}} {"id":100027622,"name":"Patch","signature":"func (c *cSIStorageCapacities) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.CSIStorageCapacity, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csistoragecapacity.go","code":"// Patch applies the patch and returns the patched cSIStorageCapacity.\nfunc (c *cSIStorageCapacities) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.CSIStorageCapacity, err error) {\n\tresult = \u0026v1beta1.CSIStorageCapacity{}\n\terr = c.client.Patch(pt).\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":169,"to":182}} {"id":100027623,"name":"Apply","signature":"func (c *cSIStorageCapacities) Apply(ctx context.Context, cSIStorageCapacity *storagev1beta1.CSIStorageCapacityApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.CSIStorageCapacity, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/csistoragecapacity.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied cSIStorageCapacity.\nfunc (c *cSIStorageCapacities) Apply(ctx context.Context, cSIStorageCapacity *storagev1beta1.CSIStorageCapacityApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.CSIStorageCapacity, err error) {\n\tif cSIStorageCapacity == nil {\n\t\treturn nil, fmt.Errorf(\"cSIStorageCapacity provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(cSIStorageCapacity)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := cSIStorageCapacity.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"cSIStorageCapacity.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.CSIStorageCapacity{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tNamespace(c.ns).\n\t\tResource(\"csistoragecapacities\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":184,"to":208}} {"id":100027624,"name":"CSIDrivers","signature":"func (c *StorageV1beta1Client) CSIDrivers() CSIDriverInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/storage_client.go","code":"func (c *StorageV1beta1Client) CSIDrivers() CSIDriverInterface {\n\treturn newCSIDrivers(c)\n}","line":{"from":43,"to":45}} {"id":100027625,"name":"CSINodes","signature":"func (c *StorageV1beta1Client) CSINodes() CSINodeInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/storage_client.go","code":"func (c *StorageV1beta1Client) CSINodes() CSINodeInterface {\n\treturn newCSINodes(c)\n}","line":{"from":47,"to":49}} {"id":100027626,"name":"CSIStorageCapacities","signature":"func (c *StorageV1beta1Client) CSIStorageCapacities(namespace string) CSIStorageCapacityInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/storage_client.go","code":"func (c *StorageV1beta1Client) CSIStorageCapacities(namespace string) CSIStorageCapacityInterface {\n\treturn newCSIStorageCapacities(c, namespace)\n}","line":{"from":51,"to":53}} {"id":100027627,"name":"StorageClasses","signature":"func (c *StorageV1beta1Client) StorageClasses() StorageClassInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/storage_client.go","code":"func (c *StorageV1beta1Client) StorageClasses() StorageClassInterface {\n\treturn newStorageClasses(c)\n}","line":{"from":55,"to":57}} {"id":100027628,"name":"VolumeAttachments","signature":"func (c *StorageV1beta1Client) VolumeAttachments() VolumeAttachmentInterface","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/storage_client.go","code":"func (c *StorageV1beta1Client) VolumeAttachments() VolumeAttachmentInterface {\n\treturn newVolumeAttachments(c)\n}","line":{"from":59,"to":61}} {"id":100027629,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*StorageV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/storage_client.go","code":"// NewForConfig creates a new StorageV1beta1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*StorageV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":63,"to":76}} {"id":100027630,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*StorageV1beta1Client, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/storage_client.go","code":"// NewForConfigAndClient creates a new StorageV1beta1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*StorageV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026StorageV1beta1Client{client}, nil\n}","line":{"from":78,"to":90}} {"id":100027631,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *StorageV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/storage_client.go","code":"// NewForConfigOrDie creates a new StorageV1beta1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *StorageV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":92,"to":100}} {"id":100027632,"name":"New","signature":"func New(c rest.Interface) *StorageV1beta1Client","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/storage_client.go","code":"// New creates a new StorageV1beta1Client for the given RESTClient.\nfunc New(c rest.Interface) *StorageV1beta1Client {\n\treturn \u0026StorageV1beta1Client{c}\n}","line":{"from":102,"to":105}} {"id":100027633,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/storage_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":107,"to":118}} {"id":100027634,"name":"RESTClient","signature":"func (c *StorageV1beta1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/storage_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *StorageV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":120,"to":127}} {"id":100027635,"name":"newStorageClasses","signature":"func newStorageClasses(c *StorageV1beta1Client) *storageClasses","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/storageclass.go","code":"// newStorageClasses returns a StorageClasses\nfunc newStorageClasses(c *StorageV1beta1Client) *storageClasses {\n\treturn \u0026storageClasses{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":61,"to":66}} {"id":100027636,"name":"Get","signature":"func (c *storageClasses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.StorageClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/storageclass.go","code":"// Get takes name of the storageClass, and returns the corresponding storageClass object, and an error if there is any.\nfunc (c *storageClasses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.StorageClass, err error) {\n\tresult = \u0026v1beta1.StorageClass{}\n\terr = c.client.Get().\n\t\tResource(\"storageclasses\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":68,"to":78}} {"id":100027637,"name":"List","signature":"func (c *storageClasses) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.StorageClassList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/storageclass.go","code":"// List takes label and field selectors, and returns the list of StorageClasses that match those selectors.\nfunc (c *storageClasses) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.StorageClassList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.StorageClassList{}\n\terr = c.client.Get().\n\t\tResource(\"storageclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":80,"to":94}} {"id":100027638,"name":"Watch","signature":"func (c *storageClasses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/storageclass.go","code":"// Watch returns a watch.Interface that watches the requested storageClasses.\nfunc (c *storageClasses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"storageclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":96,"to":108}} {"id":100027639,"name":"Create","signature":"func (c *storageClasses) Create(ctx context.Context, storageClass *v1beta1.StorageClass, opts v1.CreateOptions) (result *v1beta1.StorageClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/storageclass.go","code":"// Create takes the representation of a storageClass and creates it. Returns the server's representation of the storageClass, and an error, if there is any.\nfunc (c *storageClasses) Create(ctx context.Context, storageClass *v1beta1.StorageClass, opts v1.CreateOptions) (result *v1beta1.StorageClass, err error) {\n\tresult = \u0026v1beta1.StorageClass{}\n\terr = c.client.Post().\n\t\tResource(\"storageclasses\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(storageClass).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":110,"to":120}} {"id":100027640,"name":"Update","signature":"func (c *storageClasses) Update(ctx context.Context, storageClass *v1beta1.StorageClass, opts v1.UpdateOptions) (result *v1beta1.StorageClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/storageclass.go","code":"// Update takes the representation of a storageClass and updates it. Returns the server's representation of the storageClass, and an error, if there is any.\nfunc (c *storageClasses) Update(ctx context.Context, storageClass *v1beta1.StorageClass, opts v1.UpdateOptions) (result *v1beta1.StorageClass, err error) {\n\tresult = \u0026v1beta1.StorageClass{}\n\terr = c.client.Put().\n\t\tResource(\"storageclasses\").\n\t\tName(storageClass.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(storageClass).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":122,"to":133}} {"id":100027641,"name":"Delete","signature":"func (c *storageClasses) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/storageclass.go","code":"// Delete takes name of the storageClass and deletes it. Returns an error if one occurs.\nfunc (c *storageClasses) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"storageclasses\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":135,"to":143}} {"id":100027642,"name":"DeleteCollection","signature":"func (c *storageClasses) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/storageclass.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *storageClasses) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"storageclasses\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":145,"to":158}} {"id":100027643,"name":"Patch","signature":"func (c *storageClasses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.StorageClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/storageclass.go","code":"// Patch applies the patch and returns the patched storageClass.\nfunc (c *storageClasses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.StorageClass, err error) {\n\tresult = \u0026v1beta1.StorageClass{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"storageclasses\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":160,"to":172}} {"id":100027644,"name":"Apply","signature":"func (c *storageClasses) Apply(ctx context.Context, storageClass *storagev1beta1.StorageClassApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.StorageClass, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/storageclass.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied storageClass.\nfunc (c *storageClasses) Apply(ctx context.Context, storageClass *storagev1beta1.StorageClassApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.StorageClass, err error) {\n\tif storageClass == nil {\n\t\treturn nil, fmt.Errorf(\"storageClass provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(storageClass)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := storageClass.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"storageClass.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.StorageClass{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"storageclasses\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":174,"to":197}} {"id":100027645,"name":"newVolumeAttachments","signature":"func newVolumeAttachments(c *StorageV1beta1Client) *volumeAttachments","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/volumeattachment.go","code":"// newVolumeAttachments returns a VolumeAttachments\nfunc newVolumeAttachments(c *StorageV1beta1Client) *volumeAttachments {\n\treturn \u0026volumeAttachments{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":63,"to":68}} {"id":100027646,"name":"Get","signature":"func (c *volumeAttachments) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.VolumeAttachment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/volumeattachment.go","code":"// Get takes name of the volumeAttachment, and returns the corresponding volumeAttachment object, and an error if there is any.\nfunc (c *volumeAttachments) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.VolumeAttachment, err error) {\n\tresult = \u0026v1beta1.VolumeAttachment{}\n\terr = c.client.Get().\n\t\tResource(\"volumeattachments\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":80}} {"id":100027647,"name":"List","signature":"func (c *volumeAttachments) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.VolumeAttachmentList, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/volumeattachment.go","code":"// List takes label and field selectors, and returns the list of VolumeAttachments that match those selectors.\nfunc (c *volumeAttachments) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.VolumeAttachmentList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.VolumeAttachmentList{}\n\terr = c.client.Get().\n\t\tResource(\"volumeattachments\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":82,"to":96}} {"id":100027648,"name":"Watch","signature":"func (c *volumeAttachments) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/volumeattachment.go","code":"// Watch returns a watch.Interface that watches the requested volumeAttachments.\nfunc (c *volumeAttachments) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"volumeattachments\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":98,"to":110}} {"id":100027649,"name":"Create","signature":"func (c *volumeAttachments) Create(ctx context.Context, volumeAttachment *v1beta1.VolumeAttachment, opts v1.CreateOptions) (result *v1beta1.VolumeAttachment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/volumeattachment.go","code":"// Create takes the representation of a volumeAttachment and creates it. Returns the server's representation of the volumeAttachment, and an error, if there is any.\nfunc (c *volumeAttachments) Create(ctx context.Context, volumeAttachment *v1beta1.VolumeAttachment, opts v1.CreateOptions) (result *v1beta1.VolumeAttachment, err error) {\n\tresult = \u0026v1beta1.VolumeAttachment{}\n\terr = c.client.Post().\n\t\tResource(\"volumeattachments\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(volumeAttachment).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":112,"to":122}} {"id":100027650,"name":"Update","signature":"func (c *volumeAttachments) Update(ctx context.Context, volumeAttachment *v1beta1.VolumeAttachment, opts v1.UpdateOptions) (result *v1beta1.VolumeAttachment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/volumeattachment.go","code":"// Update takes the representation of a volumeAttachment and updates it. Returns the server's representation of the volumeAttachment, and an error, if there is any.\nfunc (c *volumeAttachments) Update(ctx context.Context, volumeAttachment *v1beta1.VolumeAttachment, opts v1.UpdateOptions) (result *v1beta1.VolumeAttachment, err error) {\n\tresult = \u0026v1beta1.VolumeAttachment{}\n\terr = c.client.Put().\n\t\tResource(\"volumeattachments\").\n\t\tName(volumeAttachment.Name).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(volumeAttachment).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":124,"to":135}} {"id":100027651,"name":"UpdateStatus","signature":"func (c *volumeAttachments) UpdateStatus(ctx context.Context, volumeAttachment *v1beta1.VolumeAttachment, opts v1.UpdateOptions) (result *v1beta1.VolumeAttachment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/volumeattachment.go","code":"// UpdateStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().\nfunc (c *volumeAttachments) UpdateStatus(ctx context.Context, volumeAttachment *v1beta1.VolumeAttachment, opts v1.UpdateOptions) (result *v1beta1.VolumeAttachment, err error) {\n\tresult = \u0026v1beta1.VolumeAttachment{}\n\terr = c.client.Put().\n\t\tResource(\"volumeattachments\").\n\t\tName(volumeAttachment.Name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(volumeAttachment).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":137,"to":150}} {"id":100027652,"name":"Delete","signature":"func (c *volumeAttachments) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/volumeattachment.go","code":"// Delete takes name of the volumeAttachment and deletes it. Returns an error if one occurs.\nfunc (c *volumeAttachments) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tResource(\"volumeattachments\").\n\t\tName(name).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":152,"to":160}} {"id":100027653,"name":"DeleteCollection","signature":"func (c *volumeAttachments) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/volumeattachment.go","code":"// DeleteCollection deletes a collection of objects.\nfunc (c *volumeAttachments) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tResource(\"volumeattachments\").\n\t\tVersionedParams(\u0026listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(\u0026opts).\n\t\tDo(ctx).\n\t\tError()\n}","line":{"from":162,"to":175}} {"id":100027654,"name":"Patch","signature":"func (c *volumeAttachments) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.VolumeAttachment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/volumeattachment.go","code":"// Patch applies the patch and returns the patched volumeAttachment.\nfunc (c *volumeAttachments) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.VolumeAttachment, err error) {\n\tresult = \u0026v1beta1.VolumeAttachment{}\n\terr = c.client.Patch(pt).\n\t\tResource(\"volumeattachments\").\n\t\tName(name).\n\t\tSubResource(subresources...).\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":177,"to":189}} {"id":100027655,"name":"Apply","signature":"func (c *volumeAttachments) Apply(ctx context.Context, volumeAttachment *storagev1beta1.VolumeAttachmentApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.VolumeAttachment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/volumeattachment.go","code":"// Apply takes the given apply declarative configuration, applies it and returns the applied volumeAttachment.\nfunc (c *volumeAttachments) Apply(ctx context.Context, volumeAttachment *storagev1beta1.VolumeAttachmentApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.VolumeAttachment, err error) {\n\tif volumeAttachment == nil {\n\t\treturn nil, fmt.Errorf(\"volumeAttachment provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(volumeAttachment)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := volumeAttachment.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"volumeAttachment.Name must be provided to Apply\")\n\t}\n\tresult = \u0026v1beta1.VolumeAttachment{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"volumeattachments\").\n\t\tName(*name).\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":191,"to":214}} {"id":100027656,"name":"ApplyStatus","signature":"func (c *volumeAttachments) ApplyStatus(ctx context.Context, volumeAttachment *storagev1beta1.VolumeAttachmentApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.VolumeAttachment, err error)","file":"staging/src/k8s.io/client-go/kubernetes/typed/storage/v1beta1/volumeattachment.go","code":"// ApplyStatus was generated because the type contains a Status member.\n// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().\nfunc (c *volumeAttachments) ApplyStatus(ctx context.Context, volumeAttachment *storagev1beta1.VolumeAttachmentApplyConfiguration, opts v1.ApplyOptions) (result *v1beta1.VolumeAttachment, err error) {\n\tif volumeAttachment == nil {\n\t\treturn nil, fmt.Errorf(\"volumeAttachment provided to Apply must not be nil\")\n\t}\n\tpatchOpts := opts.ToPatchOptions()\n\tdata, err := json.Marshal(volumeAttachment)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname := volumeAttachment.Name\n\tif name == nil {\n\t\treturn nil, fmt.Errorf(\"volumeAttachment.Name must be provided to Apply\")\n\t}\n\n\tresult = \u0026v1beta1.VolumeAttachment{}\n\terr = c.client.Patch(types.ApplyPatchType).\n\t\tResource(\"volumeattachments\").\n\t\tName(*name).\n\t\tSubResource(\"status\").\n\t\tVersionedParams(\u0026patchOpts, scheme.ParameterCodec).\n\t\tBody(data).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":216,"to":243}} {"id":100027657,"name":"NewMutatingWebhookConfigurationLister","signature":"func NewMutatingWebhookConfigurationLister(indexer cache.Indexer) MutatingWebhookConfigurationLister","file":"staging/src/k8s.io/client-go/listers/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// NewMutatingWebhookConfigurationLister returns a new MutatingWebhookConfigurationLister.\nfunc NewMutatingWebhookConfigurationLister(indexer cache.Indexer) MutatingWebhookConfigurationLister {\n\treturn \u0026mutatingWebhookConfigurationLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027658,"name":"List","signature":"func (s *mutatingWebhookConfigurationLister) List(selector labels.Selector) (ret []*v1.MutatingWebhookConfiguration, err error)","file":"staging/src/k8s.io/client-go/listers/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// List lists all MutatingWebhookConfigurations in the indexer.\nfunc (s *mutatingWebhookConfigurationLister) List(selector labels.Selector) (ret []*v1.MutatingWebhookConfiguration, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.MutatingWebhookConfiguration))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027659,"name":"Get","signature":"func (s *mutatingWebhookConfigurationLister) Get(name string) (*v1.MutatingWebhookConfiguration, error)","file":"staging/src/k8s.io/client-go/listers/admissionregistration/v1/mutatingwebhookconfiguration.go","code":"// Get retrieves the MutatingWebhookConfiguration from the index for a given name.\nfunc (s *mutatingWebhookConfigurationLister) Get(name string) (*v1.MutatingWebhookConfiguration, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"mutatingwebhookconfiguration\"), name)\n\t}\n\treturn obj.(*v1.MutatingWebhookConfiguration), nil\n}","line":{"from":58,"to":68}} {"id":100027660,"name":"NewValidatingWebhookConfigurationLister","signature":"func NewValidatingWebhookConfigurationLister(indexer cache.Indexer) ValidatingWebhookConfigurationLister","file":"staging/src/k8s.io/client-go/listers/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// NewValidatingWebhookConfigurationLister returns a new ValidatingWebhookConfigurationLister.\nfunc NewValidatingWebhookConfigurationLister(indexer cache.Indexer) ValidatingWebhookConfigurationLister {\n\treturn \u0026validatingWebhookConfigurationLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027661,"name":"List","signature":"func (s *validatingWebhookConfigurationLister) List(selector labels.Selector) (ret []*v1.ValidatingWebhookConfiguration, err error)","file":"staging/src/k8s.io/client-go/listers/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// List lists all ValidatingWebhookConfigurations in the indexer.\nfunc (s *validatingWebhookConfigurationLister) List(selector labels.Selector) (ret []*v1.ValidatingWebhookConfiguration, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.ValidatingWebhookConfiguration))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027662,"name":"Get","signature":"func (s *validatingWebhookConfigurationLister) Get(name string) (*v1.ValidatingWebhookConfiguration, error)","file":"staging/src/k8s.io/client-go/listers/admissionregistration/v1/validatingwebhookconfiguration.go","code":"// Get retrieves the ValidatingWebhookConfiguration from the index for a given name.\nfunc (s *validatingWebhookConfigurationLister) Get(name string) (*v1.ValidatingWebhookConfiguration, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"validatingwebhookconfiguration\"), name)\n\t}\n\treturn obj.(*v1.ValidatingWebhookConfiguration), nil\n}","line":{"from":58,"to":68}} {"id":100027663,"name":"NewValidatingAdmissionPolicyLister","signature":"func NewValidatingAdmissionPolicyLister(indexer cache.Indexer) ValidatingAdmissionPolicyLister","file":"staging/src/k8s.io/client-go/listers/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// NewValidatingAdmissionPolicyLister returns a new ValidatingAdmissionPolicyLister.\nfunc NewValidatingAdmissionPolicyLister(indexer cache.Indexer) ValidatingAdmissionPolicyLister {\n\treturn \u0026validatingAdmissionPolicyLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027664,"name":"List","signature":"func (s *validatingAdmissionPolicyLister) List(selector labels.Selector) (ret []*v1alpha1.ValidatingAdmissionPolicy, err error)","file":"staging/src/k8s.io/client-go/listers/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// List lists all ValidatingAdmissionPolicies in the indexer.\nfunc (s *validatingAdmissionPolicyLister) List(selector labels.Selector) (ret []*v1alpha1.ValidatingAdmissionPolicy, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ValidatingAdmissionPolicy))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027665,"name":"Get","signature":"func (s *validatingAdmissionPolicyLister) Get(name string) (*v1alpha1.ValidatingAdmissionPolicy, error)","file":"staging/src/k8s.io/client-go/listers/admissionregistration/v1alpha1/validatingadmissionpolicy.go","code":"// Get retrieves the ValidatingAdmissionPolicy from the index for a given name.\nfunc (s *validatingAdmissionPolicyLister) Get(name string) (*v1alpha1.ValidatingAdmissionPolicy, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"validatingadmissionpolicy\"), name)\n\t}\n\treturn obj.(*v1alpha1.ValidatingAdmissionPolicy), nil\n}","line":{"from":58,"to":68}} {"id":100027666,"name":"NewValidatingAdmissionPolicyBindingLister","signature":"func NewValidatingAdmissionPolicyBindingLister(indexer cache.Indexer) ValidatingAdmissionPolicyBindingLister","file":"staging/src/k8s.io/client-go/listers/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// NewValidatingAdmissionPolicyBindingLister returns a new ValidatingAdmissionPolicyBindingLister.\nfunc NewValidatingAdmissionPolicyBindingLister(indexer cache.Indexer) ValidatingAdmissionPolicyBindingLister {\n\treturn \u0026validatingAdmissionPolicyBindingLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027667,"name":"List","signature":"func (s *validatingAdmissionPolicyBindingLister) List(selector labels.Selector) (ret []*v1alpha1.ValidatingAdmissionPolicyBinding, err error)","file":"staging/src/k8s.io/client-go/listers/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// List lists all ValidatingAdmissionPolicyBindings in the indexer.\nfunc (s *validatingAdmissionPolicyBindingLister) List(selector labels.Selector) (ret []*v1alpha1.ValidatingAdmissionPolicyBinding, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ValidatingAdmissionPolicyBinding))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027668,"name":"Get","signature":"func (s *validatingAdmissionPolicyBindingLister) Get(name string) (*v1alpha1.ValidatingAdmissionPolicyBinding, error)","file":"staging/src/k8s.io/client-go/listers/admissionregistration/v1alpha1/validatingadmissionpolicybinding.go","code":"// Get retrieves the ValidatingAdmissionPolicyBinding from the index for a given name.\nfunc (s *validatingAdmissionPolicyBindingLister) Get(name string) (*v1alpha1.ValidatingAdmissionPolicyBinding, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"validatingadmissionpolicybinding\"), name)\n\t}\n\treturn obj.(*v1alpha1.ValidatingAdmissionPolicyBinding), nil\n}","line":{"from":58,"to":68}} {"id":100027669,"name":"NewMutatingWebhookConfigurationLister","signature":"func NewMutatingWebhookConfigurationLister(indexer cache.Indexer) MutatingWebhookConfigurationLister","file":"staging/src/k8s.io/client-go/listers/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// NewMutatingWebhookConfigurationLister returns a new MutatingWebhookConfigurationLister.\nfunc NewMutatingWebhookConfigurationLister(indexer cache.Indexer) MutatingWebhookConfigurationLister {\n\treturn \u0026mutatingWebhookConfigurationLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027670,"name":"List","signature":"func (s *mutatingWebhookConfigurationLister) List(selector labels.Selector) (ret []*v1beta1.MutatingWebhookConfiguration, err error)","file":"staging/src/k8s.io/client-go/listers/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// List lists all MutatingWebhookConfigurations in the indexer.\nfunc (s *mutatingWebhookConfigurationLister) List(selector labels.Selector) (ret []*v1beta1.MutatingWebhookConfiguration, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.MutatingWebhookConfiguration))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027671,"name":"Get","signature":"func (s *mutatingWebhookConfigurationLister) Get(name string) (*v1beta1.MutatingWebhookConfiguration, error)","file":"staging/src/k8s.io/client-go/listers/admissionregistration/v1beta1/mutatingwebhookconfiguration.go","code":"// Get retrieves the MutatingWebhookConfiguration from the index for a given name.\nfunc (s *mutatingWebhookConfigurationLister) Get(name string) (*v1beta1.MutatingWebhookConfiguration, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"mutatingwebhookconfiguration\"), name)\n\t}\n\treturn obj.(*v1beta1.MutatingWebhookConfiguration), nil\n}","line":{"from":58,"to":68}} {"id":100027672,"name":"NewValidatingWebhookConfigurationLister","signature":"func NewValidatingWebhookConfigurationLister(indexer cache.Indexer) ValidatingWebhookConfigurationLister","file":"staging/src/k8s.io/client-go/listers/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// NewValidatingWebhookConfigurationLister returns a new ValidatingWebhookConfigurationLister.\nfunc NewValidatingWebhookConfigurationLister(indexer cache.Indexer) ValidatingWebhookConfigurationLister {\n\treturn \u0026validatingWebhookConfigurationLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027673,"name":"List","signature":"func (s *validatingWebhookConfigurationLister) List(selector labels.Selector) (ret []*v1beta1.ValidatingWebhookConfiguration, err error)","file":"staging/src/k8s.io/client-go/listers/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// List lists all ValidatingWebhookConfigurations in the indexer.\nfunc (s *validatingWebhookConfigurationLister) List(selector labels.Selector) (ret []*v1beta1.ValidatingWebhookConfiguration, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.ValidatingWebhookConfiguration))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027674,"name":"Get","signature":"func (s *validatingWebhookConfigurationLister) Get(name string) (*v1beta1.ValidatingWebhookConfiguration, error)","file":"staging/src/k8s.io/client-go/listers/admissionregistration/v1beta1/validatingwebhookconfiguration.go","code":"// Get retrieves the ValidatingWebhookConfiguration from the index for a given name.\nfunc (s *validatingWebhookConfigurationLister) Get(name string) (*v1beta1.ValidatingWebhookConfiguration, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"validatingwebhookconfiguration\"), name)\n\t}\n\treturn obj.(*v1beta1.ValidatingWebhookConfiguration), nil\n}","line":{"from":58,"to":68}} {"id":100027675,"name":"NewStorageVersionLister","signature":"func NewStorageVersionLister(indexer cache.Indexer) StorageVersionLister","file":"staging/src/k8s.io/client-go/listers/apiserverinternal/v1alpha1/storageversion.go","code":"// NewStorageVersionLister returns a new StorageVersionLister.\nfunc NewStorageVersionLister(indexer cache.Indexer) StorageVersionLister {\n\treturn \u0026storageVersionLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027676,"name":"List","signature":"func (s *storageVersionLister) List(selector labels.Selector) (ret []*v1alpha1.StorageVersion, err error)","file":"staging/src/k8s.io/client-go/listers/apiserverinternal/v1alpha1/storageversion.go","code":"// List lists all StorageVersions in the indexer.\nfunc (s *storageVersionLister) List(selector labels.Selector) (ret []*v1alpha1.StorageVersion, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.StorageVersion))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027677,"name":"Get","signature":"func (s *storageVersionLister) Get(name string) (*v1alpha1.StorageVersion, error)","file":"staging/src/k8s.io/client-go/listers/apiserverinternal/v1alpha1/storageversion.go","code":"// Get retrieves the StorageVersion from the index for a given name.\nfunc (s *storageVersionLister) Get(name string) (*v1alpha1.StorageVersion, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"storageversion\"), name)\n\t}\n\treturn obj.(*v1alpha1.StorageVersion), nil\n}","line":{"from":58,"to":68}} {"id":100027678,"name":"NewControllerRevisionLister","signature":"func NewControllerRevisionLister(indexer cache.Indexer) ControllerRevisionLister","file":"staging/src/k8s.io/client-go/listers/apps/v1/controllerrevision.go","code":"// NewControllerRevisionLister returns a new ControllerRevisionLister.\nfunc NewControllerRevisionLister(indexer cache.Indexer) ControllerRevisionLister {\n\treturn \u0026controllerRevisionLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027679,"name":"List","signature":"func (s *controllerRevisionLister) List(selector labels.Selector) (ret []*v1.ControllerRevision, err error)","file":"staging/src/k8s.io/client-go/listers/apps/v1/controllerrevision.go","code":"// List lists all ControllerRevisions in the indexer.\nfunc (s *controllerRevisionLister) List(selector labels.Selector) (ret []*v1.ControllerRevision, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.ControllerRevision))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027680,"name":"ControllerRevisions","signature":"func (s *controllerRevisionLister) ControllerRevisions(namespace string) ControllerRevisionNamespaceLister","file":"staging/src/k8s.io/client-go/listers/apps/v1/controllerrevision.go","code":"// ControllerRevisions returns an object that can list and get ControllerRevisions.\nfunc (s *controllerRevisionLister) ControllerRevisions(namespace string) ControllerRevisionNamespaceLister {\n\treturn controllerRevisionNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027681,"name":"List","signature":"func (s controllerRevisionNamespaceLister) List(selector labels.Selector) (ret []*v1.ControllerRevision, err error)","file":"staging/src/k8s.io/client-go/listers/apps/v1/controllerrevision.go","code":"// List lists all ControllerRevisions in the indexer for a given namespace.\nfunc (s controllerRevisionNamespaceLister) List(selector labels.Selector) (ret []*v1.ControllerRevision, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.ControllerRevision))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027682,"name":"Get","signature":"func (s controllerRevisionNamespaceLister) Get(name string) (*v1.ControllerRevision, error)","file":"staging/src/k8s.io/client-go/listers/apps/v1/controllerrevision.go","code":"// Get retrieves the ControllerRevision from the indexer for a given namespace and name.\nfunc (s controllerRevisionNamespaceLister) Get(name string) (*v1.ControllerRevision, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"controllerrevision\"), name)\n\t}\n\treturn obj.(*v1.ControllerRevision), nil\n}","line":{"from":89,"to":99}} {"id":100027683,"name":"NewDaemonSetLister","signature":"func NewDaemonSetLister(indexer cache.Indexer) DaemonSetLister","file":"staging/src/k8s.io/client-go/listers/apps/v1/daemonset.go","code":"// NewDaemonSetLister returns a new DaemonSetLister.\nfunc NewDaemonSetLister(indexer cache.Indexer) DaemonSetLister {\n\treturn \u0026daemonSetLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027684,"name":"List","signature":"func (s *daemonSetLister) List(selector labels.Selector) (ret []*v1.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/listers/apps/v1/daemonset.go","code":"// List lists all DaemonSets in the indexer.\nfunc (s *daemonSetLister) List(selector labels.Selector) (ret []*v1.DaemonSet, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.DaemonSet))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027685,"name":"DaemonSets","signature":"func (s *daemonSetLister) DaemonSets(namespace string) DaemonSetNamespaceLister","file":"staging/src/k8s.io/client-go/listers/apps/v1/daemonset.go","code":"// DaemonSets returns an object that can list and get DaemonSets.\nfunc (s *daemonSetLister) DaemonSets(namespace string) DaemonSetNamespaceLister {\n\treturn daemonSetNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027686,"name":"List","signature":"func (s daemonSetNamespaceLister) List(selector labels.Selector) (ret []*v1.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/listers/apps/v1/daemonset.go","code":"// List lists all DaemonSets in the indexer for a given namespace.\nfunc (s daemonSetNamespaceLister) List(selector labels.Selector) (ret []*v1.DaemonSet, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.DaemonSet))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027687,"name":"Get","signature":"func (s daemonSetNamespaceLister) Get(name string) (*v1.DaemonSet, error)","file":"staging/src/k8s.io/client-go/listers/apps/v1/daemonset.go","code":"// Get retrieves the DaemonSet from the indexer for a given namespace and name.\nfunc (s daemonSetNamespaceLister) Get(name string) (*v1.DaemonSet, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"daemonset\"), name)\n\t}\n\treturn obj.(*v1.DaemonSet), nil\n}","line":{"from":89,"to":99}} {"id":100027688,"name":"GetPodDaemonSets","signature":"func (s *daemonSetLister) GetPodDaemonSets(pod *v1.Pod) ([]*apps.DaemonSet, error)","file":"staging/src/k8s.io/client-go/listers/apps/v1/daemonset_expansion.go","code":"// GetPodDaemonSets returns a list of DaemonSets that potentially match a pod.\n// Only the one specified in the Pod's ControllerRef will actually manage it.\n// Returns an error only if no matching DaemonSets are found.\nfunc (s *daemonSetLister) GetPodDaemonSets(pod *v1.Pod) ([]*apps.DaemonSet, error) {\n\tvar selector labels.Selector\n\tvar daemonSet *apps.DaemonSet\n\n\tif len(pod.Labels) == 0 {\n\t\treturn nil, fmt.Errorf(\"no daemon sets found for pod %v because it has no labels\", pod.Name)\n\t}\n\n\tlist, err := s.DaemonSets(pod.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar daemonSets []*apps.DaemonSet\n\tfor i := range list {\n\t\tdaemonSet = list[i]\n\t\tif daemonSet.Namespace != pod.Namespace {\n\t\t\tcontinue\n\t\t}\n\t\tselector, err = metav1.LabelSelectorAsSelector(daemonSet.Spec.Selector)\n\t\tif err != nil {\n\t\t\t// This object has an invalid selector, it does not match the pod\n\t\t\tcontinue\n\t\t}\n\n\t\t// If a daemonSet with a nil or empty selector creeps in, it should match nothing, not everything.\n\t\tif selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) {\n\t\t\tcontinue\n\t\t}\n\t\tdaemonSets = append(daemonSets, daemonSet)\n\t}\n\n\tif len(daemonSets) == 0 {\n\t\treturn nil, fmt.Errorf(\"could not find daemon set for pod %s in namespace %s with labels: %v\", pod.Name, pod.Namespace, pod.Labels)\n\t}\n\n\treturn daemonSets, nil\n}","line":{"from":39,"to":79}} {"id":100027689,"name":"GetHistoryDaemonSets","signature":"func (s *daemonSetLister) GetHistoryDaemonSets(history *apps.ControllerRevision) ([]*apps.DaemonSet, error)","file":"staging/src/k8s.io/client-go/listers/apps/v1/daemonset_expansion.go","code":"// GetHistoryDaemonSets returns a list of DaemonSets that potentially\n// match a ControllerRevision. Only the one specified in the ControllerRevision's ControllerRef\n// will actually manage it.\n// Returns an error only if no matching DaemonSets are found.\nfunc (s *daemonSetLister) GetHistoryDaemonSets(history *apps.ControllerRevision) ([]*apps.DaemonSet, error) {\n\tif len(history.Labels) == 0 {\n\t\treturn nil, fmt.Errorf(\"no DaemonSet found for ControllerRevision %s because it has no labels\", history.Name)\n\t}\n\n\tlist, err := s.DaemonSets(history.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar daemonSets []*apps.DaemonSet\n\tfor _, ds := range list {\n\t\tselector, err := metav1.LabelSelectorAsSelector(ds.Spec.Selector)\n\t\tif err != nil {\n\t\t\t// This object has an invalid selector, it does not match the history\n\t\t\tcontinue\n\t\t}\n\t\t// If a DaemonSet with a nil or empty selector creeps in, it should match nothing, not everything.\n\t\tif selector.Empty() || !selector.Matches(labels.Set(history.Labels)) {\n\t\t\tcontinue\n\t\t}\n\t\tdaemonSets = append(daemonSets, ds)\n\t}\n\n\tif len(daemonSets) == 0 {\n\t\treturn nil, fmt.Errorf(\"could not find DaemonSets for ControllerRevision %s in namespace %s with labels: %v\", history.Name, history.Namespace, history.Labels)\n\t}\n\n\treturn daemonSets, nil\n}","line":{"from":81,"to":114}} {"id":100027690,"name":"NewDeploymentLister","signature":"func NewDeploymentLister(indexer cache.Indexer) DeploymentLister","file":"staging/src/k8s.io/client-go/listers/apps/v1/deployment.go","code":"// NewDeploymentLister returns a new DeploymentLister.\nfunc NewDeploymentLister(indexer cache.Indexer) DeploymentLister {\n\treturn \u0026deploymentLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027691,"name":"List","signature":"func (s *deploymentLister) List(selector labels.Selector) (ret []*v1.Deployment, err error)","file":"staging/src/k8s.io/client-go/listers/apps/v1/deployment.go","code":"// List lists all Deployments in the indexer.\nfunc (s *deploymentLister) List(selector labels.Selector) (ret []*v1.Deployment, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Deployment))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027692,"name":"Deployments","signature":"func (s *deploymentLister) Deployments(namespace string) DeploymentNamespaceLister","file":"staging/src/k8s.io/client-go/listers/apps/v1/deployment.go","code":"// Deployments returns an object that can list and get Deployments.\nfunc (s *deploymentLister) Deployments(namespace string) DeploymentNamespaceLister {\n\treturn deploymentNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027693,"name":"List","signature":"func (s deploymentNamespaceLister) List(selector labels.Selector) (ret []*v1.Deployment, err error)","file":"staging/src/k8s.io/client-go/listers/apps/v1/deployment.go","code":"// List lists all Deployments in the indexer for a given namespace.\nfunc (s deploymentNamespaceLister) List(selector labels.Selector) (ret []*v1.Deployment, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Deployment))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027694,"name":"Get","signature":"func (s deploymentNamespaceLister) Get(name string) (*v1.Deployment, error)","file":"staging/src/k8s.io/client-go/listers/apps/v1/deployment.go","code":"// Get retrieves the Deployment from the indexer for a given namespace and name.\nfunc (s deploymentNamespaceLister) Get(name string) (*v1.Deployment, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"deployment\"), name)\n\t}\n\treturn obj.(*v1.Deployment), nil\n}","line":{"from":89,"to":99}} {"id":100027695,"name":"NewReplicaSetLister","signature":"func NewReplicaSetLister(indexer cache.Indexer) ReplicaSetLister","file":"staging/src/k8s.io/client-go/listers/apps/v1/replicaset.go","code":"// NewReplicaSetLister returns a new ReplicaSetLister.\nfunc NewReplicaSetLister(indexer cache.Indexer) ReplicaSetLister {\n\treturn \u0026replicaSetLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027696,"name":"List","signature":"func (s *replicaSetLister) List(selector labels.Selector) (ret []*v1.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/listers/apps/v1/replicaset.go","code":"// List lists all ReplicaSets in the indexer.\nfunc (s *replicaSetLister) List(selector labels.Selector) (ret []*v1.ReplicaSet, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.ReplicaSet))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027697,"name":"ReplicaSets","signature":"func (s *replicaSetLister) ReplicaSets(namespace string) ReplicaSetNamespaceLister","file":"staging/src/k8s.io/client-go/listers/apps/v1/replicaset.go","code":"// ReplicaSets returns an object that can list and get ReplicaSets.\nfunc (s *replicaSetLister) ReplicaSets(namespace string) ReplicaSetNamespaceLister {\n\treturn replicaSetNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027698,"name":"List","signature":"func (s replicaSetNamespaceLister) List(selector labels.Selector) (ret []*v1.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/listers/apps/v1/replicaset.go","code":"// List lists all ReplicaSets in the indexer for a given namespace.\nfunc (s replicaSetNamespaceLister) List(selector labels.Selector) (ret []*v1.ReplicaSet, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.ReplicaSet))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027699,"name":"Get","signature":"func (s replicaSetNamespaceLister) Get(name string) (*v1.ReplicaSet, error)","file":"staging/src/k8s.io/client-go/listers/apps/v1/replicaset.go","code":"// Get retrieves the ReplicaSet from the indexer for a given namespace and name.\nfunc (s replicaSetNamespaceLister) Get(name string) (*v1.ReplicaSet, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"replicaset\"), name)\n\t}\n\treturn obj.(*v1.ReplicaSet), nil\n}","line":{"from":89,"to":99}} {"id":100027700,"name":"GetPodReplicaSets","signature":"func (s *replicaSetLister) GetPodReplicaSets(pod *v1.Pod) ([]*apps.ReplicaSet, error)","file":"staging/src/k8s.io/client-go/listers/apps/v1/replicaset_expansion.go","code":"// GetPodReplicaSets returns a list of ReplicaSets that potentially match a pod.\n// Only the one specified in the Pod's ControllerRef will actually manage it.\n// Returns an error only if no matching ReplicaSets are found.\nfunc (s *replicaSetLister) GetPodReplicaSets(pod *v1.Pod) ([]*apps.ReplicaSet, error) {\n\tif len(pod.Labels) == 0 {\n\t\treturn nil, fmt.Errorf(\"no ReplicaSets found for pod %v because it has no labels\", pod.Name)\n\t}\n\n\tlist, err := s.ReplicaSets(pod.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar rss []*apps.ReplicaSet\n\tfor _, rs := range list {\n\t\tif rs.Namespace != pod.Namespace {\n\t\t\tcontinue\n\t\t}\n\t\tselector, err := metav1.LabelSelectorAsSelector(rs.Spec.Selector)\n\t\tif err != nil {\n\t\t\t// This object has an invalid selector, it does not match the pod\n\t\t\tcontinue\n\t\t}\n\n\t\t// If a ReplicaSet with a nil or empty selector creeps in, it should match nothing, not everything.\n\t\tif selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) {\n\t\t\tcontinue\n\t\t}\n\t\trss = append(rss, rs)\n\t}\n\n\tif len(rss) == 0 {\n\t\treturn nil, fmt.Errorf(\"could not find ReplicaSet for pod %s in namespace %s with labels: %v\", pod.Name, pod.Namespace, pod.Labels)\n\t}\n\n\treturn rss, nil\n}","line":{"from":38,"to":74}} {"id":100027701,"name":"NewStatefulSetLister","signature":"func NewStatefulSetLister(indexer cache.Indexer) StatefulSetLister","file":"staging/src/k8s.io/client-go/listers/apps/v1/statefulset.go","code":"// NewStatefulSetLister returns a new StatefulSetLister.\nfunc NewStatefulSetLister(indexer cache.Indexer) StatefulSetLister {\n\treturn \u0026statefulSetLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027702,"name":"List","signature":"func (s *statefulSetLister) List(selector labels.Selector) (ret []*v1.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/listers/apps/v1/statefulset.go","code":"// List lists all StatefulSets in the indexer.\nfunc (s *statefulSetLister) List(selector labels.Selector) (ret []*v1.StatefulSet, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.StatefulSet))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027703,"name":"StatefulSets","signature":"func (s *statefulSetLister) StatefulSets(namespace string) StatefulSetNamespaceLister","file":"staging/src/k8s.io/client-go/listers/apps/v1/statefulset.go","code":"// StatefulSets returns an object that can list and get StatefulSets.\nfunc (s *statefulSetLister) StatefulSets(namespace string) StatefulSetNamespaceLister {\n\treturn statefulSetNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027704,"name":"List","signature":"func (s statefulSetNamespaceLister) List(selector labels.Selector) (ret []*v1.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/listers/apps/v1/statefulset.go","code":"// List lists all StatefulSets in the indexer for a given namespace.\nfunc (s statefulSetNamespaceLister) List(selector labels.Selector) (ret []*v1.StatefulSet, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.StatefulSet))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027705,"name":"Get","signature":"func (s statefulSetNamespaceLister) Get(name string) (*v1.StatefulSet, error)","file":"staging/src/k8s.io/client-go/listers/apps/v1/statefulset.go","code":"// Get retrieves the StatefulSet from the indexer for a given namespace and name.\nfunc (s statefulSetNamespaceLister) Get(name string) (*v1.StatefulSet, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"statefulset\"), name)\n\t}\n\treturn obj.(*v1.StatefulSet), nil\n}","line":{"from":89,"to":99}} {"id":100027706,"name":"GetPodStatefulSets","signature":"func (s *statefulSetLister) GetPodStatefulSets(pod *v1.Pod) ([]*apps.StatefulSet, error)","file":"staging/src/k8s.io/client-go/listers/apps/v1/statefulset_expansion.go","code":"// GetPodStatefulSets returns a list of StatefulSets that potentially match a pod.\n// Only the one specified in the Pod's ControllerRef will actually manage it.\n// Returns an error only if no matching StatefulSets are found.\nfunc (s *statefulSetLister) GetPodStatefulSets(pod *v1.Pod) ([]*apps.StatefulSet, error) {\n\tvar selector labels.Selector\n\tvar ps *apps.StatefulSet\n\n\tif len(pod.Labels) == 0 {\n\t\treturn nil, fmt.Errorf(\"no StatefulSets found for pod %v because it has no labels\", pod.Name)\n\t}\n\n\tlist, err := s.StatefulSets(pod.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar psList []*apps.StatefulSet\n\tfor i := range list {\n\t\tps = list[i]\n\t\tif ps.Namespace != pod.Namespace {\n\t\t\tcontinue\n\t\t}\n\t\tselector, err = metav1.LabelSelectorAsSelector(ps.Spec.Selector)\n\t\tif err != nil {\n\t\t\t// This object has an invalid selector, it does not match the pod\n\t\t\tcontinue\n\t\t}\n\n\t\t// If a StatefulSet with a nil or empty selector creeps in, it should match nothing, not everything.\n\t\tif selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) {\n\t\t\tcontinue\n\t\t}\n\t\tpsList = append(psList, ps)\n\t}\n\n\tif len(psList) == 0 {\n\t\treturn nil, fmt.Errorf(\"could not find StatefulSet for pod %s in namespace %s with labels: %v\", pod.Name, pod.Namespace, pod.Labels)\n\t}\n\n\treturn psList, nil\n}","line":{"from":38,"to":78}} {"id":100027707,"name":"NewControllerRevisionLister","signature":"func NewControllerRevisionLister(indexer cache.Indexer) ControllerRevisionLister","file":"staging/src/k8s.io/client-go/listers/apps/v1beta1/controllerrevision.go","code":"// NewControllerRevisionLister returns a new ControllerRevisionLister.\nfunc NewControllerRevisionLister(indexer cache.Indexer) ControllerRevisionLister {\n\treturn \u0026controllerRevisionLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027708,"name":"List","signature":"func (s *controllerRevisionLister) List(selector labels.Selector) (ret []*v1beta1.ControllerRevision, err error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta1/controllerrevision.go","code":"// List lists all ControllerRevisions in the indexer.\nfunc (s *controllerRevisionLister) List(selector labels.Selector) (ret []*v1beta1.ControllerRevision, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.ControllerRevision))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027709,"name":"ControllerRevisions","signature":"func (s *controllerRevisionLister) ControllerRevisions(namespace string) ControllerRevisionNamespaceLister","file":"staging/src/k8s.io/client-go/listers/apps/v1beta1/controllerrevision.go","code":"// ControllerRevisions returns an object that can list and get ControllerRevisions.\nfunc (s *controllerRevisionLister) ControllerRevisions(namespace string) ControllerRevisionNamespaceLister {\n\treturn controllerRevisionNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027710,"name":"List","signature":"func (s controllerRevisionNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.ControllerRevision, err error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta1/controllerrevision.go","code":"// List lists all ControllerRevisions in the indexer for a given namespace.\nfunc (s controllerRevisionNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.ControllerRevision, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.ControllerRevision))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027711,"name":"Get","signature":"func (s controllerRevisionNamespaceLister) Get(name string) (*v1beta1.ControllerRevision, error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta1/controllerrevision.go","code":"// Get retrieves the ControllerRevision from the indexer for a given namespace and name.\nfunc (s controllerRevisionNamespaceLister) Get(name string) (*v1beta1.ControllerRevision, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"controllerrevision\"), name)\n\t}\n\treturn obj.(*v1beta1.ControllerRevision), nil\n}","line":{"from":89,"to":99}} {"id":100027712,"name":"NewDeploymentLister","signature":"func NewDeploymentLister(indexer cache.Indexer) DeploymentLister","file":"staging/src/k8s.io/client-go/listers/apps/v1beta1/deployment.go","code":"// NewDeploymentLister returns a new DeploymentLister.\nfunc NewDeploymentLister(indexer cache.Indexer) DeploymentLister {\n\treturn \u0026deploymentLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027713,"name":"List","signature":"func (s *deploymentLister) List(selector labels.Selector) (ret []*v1beta1.Deployment, err error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta1/deployment.go","code":"// List lists all Deployments in the indexer.\nfunc (s *deploymentLister) List(selector labels.Selector) (ret []*v1beta1.Deployment, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.Deployment))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027714,"name":"Deployments","signature":"func (s *deploymentLister) Deployments(namespace string) DeploymentNamespaceLister","file":"staging/src/k8s.io/client-go/listers/apps/v1beta1/deployment.go","code":"// Deployments returns an object that can list and get Deployments.\nfunc (s *deploymentLister) Deployments(namespace string) DeploymentNamespaceLister {\n\treturn deploymentNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027715,"name":"List","signature":"func (s deploymentNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.Deployment, err error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta1/deployment.go","code":"// List lists all Deployments in the indexer for a given namespace.\nfunc (s deploymentNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.Deployment, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.Deployment))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027716,"name":"Get","signature":"func (s deploymentNamespaceLister) Get(name string) (*v1beta1.Deployment, error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta1/deployment.go","code":"// Get retrieves the Deployment from the indexer for a given namespace and name.\nfunc (s deploymentNamespaceLister) Get(name string) (*v1beta1.Deployment, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"deployment\"), name)\n\t}\n\treturn obj.(*v1beta1.Deployment), nil\n}","line":{"from":89,"to":99}} {"id":100027717,"name":"NewStatefulSetLister","signature":"func NewStatefulSetLister(indexer cache.Indexer) StatefulSetLister","file":"staging/src/k8s.io/client-go/listers/apps/v1beta1/statefulset.go","code":"// NewStatefulSetLister returns a new StatefulSetLister.\nfunc NewStatefulSetLister(indexer cache.Indexer) StatefulSetLister {\n\treturn \u0026statefulSetLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027718,"name":"List","signature":"func (s *statefulSetLister) List(selector labels.Selector) (ret []*v1beta1.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta1/statefulset.go","code":"// List lists all StatefulSets in the indexer.\nfunc (s *statefulSetLister) List(selector labels.Selector) (ret []*v1beta1.StatefulSet, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.StatefulSet))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027719,"name":"StatefulSets","signature":"func (s *statefulSetLister) StatefulSets(namespace string) StatefulSetNamespaceLister","file":"staging/src/k8s.io/client-go/listers/apps/v1beta1/statefulset.go","code":"// StatefulSets returns an object that can list and get StatefulSets.\nfunc (s *statefulSetLister) StatefulSets(namespace string) StatefulSetNamespaceLister {\n\treturn statefulSetNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027720,"name":"List","signature":"func (s statefulSetNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta1/statefulset.go","code":"// List lists all StatefulSets in the indexer for a given namespace.\nfunc (s statefulSetNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.StatefulSet, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.StatefulSet))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027721,"name":"Get","signature":"func (s statefulSetNamespaceLister) Get(name string) (*v1beta1.StatefulSet, error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta1/statefulset.go","code":"// Get retrieves the StatefulSet from the indexer for a given namespace and name.\nfunc (s statefulSetNamespaceLister) Get(name string) (*v1beta1.StatefulSet, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"statefulset\"), name)\n\t}\n\treturn obj.(*v1beta1.StatefulSet), nil\n}","line":{"from":89,"to":99}} {"id":100027722,"name":"GetPodStatefulSets","signature":"func (s *statefulSetLister) GetPodStatefulSets(pod *v1.Pod) ([]*apps.StatefulSet, error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta1/statefulset_expansion.go","code":"// GetPodStatefulSets returns a list of StatefulSets that potentially match a pod.\n// Only the one specified in the Pod's ControllerRef will actually manage it.\n// Returns an error only if no matching StatefulSets are found.\nfunc (s *statefulSetLister) GetPodStatefulSets(pod *v1.Pod) ([]*apps.StatefulSet, error) {\n\tvar selector labels.Selector\n\tvar ps *apps.StatefulSet\n\n\tif len(pod.Labels) == 0 {\n\t\treturn nil, fmt.Errorf(\"no StatefulSets found for pod %v because it has no labels\", pod.Name)\n\t}\n\n\tlist, err := s.StatefulSets(pod.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar psList []*apps.StatefulSet\n\tfor i := range list {\n\t\tps = list[i]\n\t\tif ps.Namespace != pod.Namespace {\n\t\t\tcontinue\n\t\t}\n\t\tselector, err = metav1.LabelSelectorAsSelector(ps.Spec.Selector)\n\t\tif err != nil {\n\t\t\t// This object has an invalid selector, it does not match the pod\n\t\t\tcontinue\n\t\t}\n\n\t\t// If a StatefulSet with a nil or empty selector creeps in, it should match nothing, not everything.\n\t\tif selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) {\n\t\t\tcontinue\n\t\t}\n\t\tpsList = append(psList, ps)\n\t}\n\n\tif len(psList) == 0 {\n\t\treturn nil, fmt.Errorf(\"could not find StatefulSet for pod %s in namespace %s with labels: %v\", pod.Name, pod.Namespace, pod.Labels)\n\t}\n\n\treturn psList, nil\n}","line":{"from":38,"to":78}} {"id":100027723,"name":"NewControllerRevisionLister","signature":"func NewControllerRevisionLister(indexer cache.Indexer) ControllerRevisionLister","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/controllerrevision.go","code":"// NewControllerRevisionLister returns a new ControllerRevisionLister.\nfunc NewControllerRevisionLister(indexer cache.Indexer) ControllerRevisionLister {\n\treturn \u0026controllerRevisionLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027724,"name":"List","signature":"func (s *controllerRevisionLister) List(selector labels.Selector) (ret []*v1beta2.ControllerRevision, err error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/controllerrevision.go","code":"// List lists all ControllerRevisions in the indexer.\nfunc (s *controllerRevisionLister) List(selector labels.Selector) (ret []*v1beta2.ControllerRevision, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta2.ControllerRevision))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027725,"name":"ControllerRevisions","signature":"func (s *controllerRevisionLister) ControllerRevisions(namespace string) ControllerRevisionNamespaceLister","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/controllerrevision.go","code":"// ControllerRevisions returns an object that can list and get ControllerRevisions.\nfunc (s *controllerRevisionLister) ControllerRevisions(namespace string) ControllerRevisionNamespaceLister {\n\treturn controllerRevisionNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027726,"name":"List","signature":"func (s controllerRevisionNamespaceLister) List(selector labels.Selector) (ret []*v1beta2.ControllerRevision, err error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/controllerrevision.go","code":"// List lists all ControllerRevisions in the indexer for a given namespace.\nfunc (s controllerRevisionNamespaceLister) List(selector labels.Selector) (ret []*v1beta2.ControllerRevision, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta2.ControllerRevision))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027727,"name":"Get","signature":"func (s controllerRevisionNamespaceLister) Get(name string) (*v1beta2.ControllerRevision, error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/controllerrevision.go","code":"// Get retrieves the ControllerRevision from the indexer for a given namespace and name.\nfunc (s controllerRevisionNamespaceLister) Get(name string) (*v1beta2.ControllerRevision, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta2.Resource(\"controllerrevision\"), name)\n\t}\n\treturn obj.(*v1beta2.ControllerRevision), nil\n}","line":{"from":89,"to":99}} {"id":100027728,"name":"NewDaemonSetLister","signature":"func NewDaemonSetLister(indexer cache.Indexer) DaemonSetLister","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/daemonset.go","code":"// NewDaemonSetLister returns a new DaemonSetLister.\nfunc NewDaemonSetLister(indexer cache.Indexer) DaemonSetLister {\n\treturn \u0026daemonSetLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027729,"name":"List","signature":"func (s *daemonSetLister) List(selector labels.Selector) (ret []*v1beta2.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/daemonset.go","code":"// List lists all DaemonSets in the indexer.\nfunc (s *daemonSetLister) List(selector labels.Selector) (ret []*v1beta2.DaemonSet, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta2.DaemonSet))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027730,"name":"DaemonSets","signature":"func (s *daemonSetLister) DaemonSets(namespace string) DaemonSetNamespaceLister","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/daemonset.go","code":"// DaemonSets returns an object that can list and get DaemonSets.\nfunc (s *daemonSetLister) DaemonSets(namespace string) DaemonSetNamespaceLister {\n\treturn daemonSetNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027731,"name":"List","signature":"func (s daemonSetNamespaceLister) List(selector labels.Selector) (ret []*v1beta2.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/daemonset.go","code":"// List lists all DaemonSets in the indexer for a given namespace.\nfunc (s daemonSetNamespaceLister) List(selector labels.Selector) (ret []*v1beta2.DaemonSet, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta2.DaemonSet))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027732,"name":"Get","signature":"func (s daemonSetNamespaceLister) Get(name string) (*v1beta2.DaemonSet, error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/daemonset.go","code":"// Get retrieves the DaemonSet from the indexer for a given namespace and name.\nfunc (s daemonSetNamespaceLister) Get(name string) (*v1beta2.DaemonSet, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta2.Resource(\"daemonset\"), name)\n\t}\n\treturn obj.(*v1beta2.DaemonSet), nil\n}","line":{"from":89,"to":99}} {"id":100027733,"name":"GetPodDaemonSets","signature":"func (s *daemonSetLister) GetPodDaemonSets(pod *v1.Pod) ([]*apps.DaemonSet, error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/daemonset_expansion.go","code":"// GetPodDaemonSets returns a list of DaemonSets that potentially match a pod.\n// Only the one specified in the Pod's ControllerRef will actually manage it.\n// Returns an error only if no matching DaemonSets are found.\nfunc (s *daemonSetLister) GetPodDaemonSets(pod *v1.Pod) ([]*apps.DaemonSet, error) {\n\tvar selector labels.Selector\n\tvar daemonSet *apps.DaemonSet\n\n\tif len(pod.Labels) == 0 {\n\t\treturn nil, fmt.Errorf(\"no daemon sets found for pod %v because it has no labels\", pod.Name)\n\t}\n\n\tlist, err := s.DaemonSets(pod.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar daemonSets []*apps.DaemonSet\n\tfor i := range list {\n\t\tdaemonSet = list[i]\n\t\tif daemonSet.Namespace != pod.Namespace {\n\t\t\tcontinue\n\t\t}\n\t\tselector, err = metav1.LabelSelectorAsSelector(daemonSet.Spec.Selector)\n\t\tif err != nil {\n\t\t\t// This object has an invalid selector, it does not match the pod\n\t\t\tcontinue\n\t\t}\n\n\t\t// If a daemonSet with a nil or empty selector creeps in, it should match nothing, not everything.\n\t\tif selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) {\n\t\t\tcontinue\n\t\t}\n\t\tdaemonSets = append(daemonSets, daemonSet)\n\t}\n\n\tif len(daemonSets) == 0 {\n\t\treturn nil, fmt.Errorf(\"could not find daemon set for pod %s in namespace %s with labels: %v\", pod.Name, pod.Namespace, pod.Labels)\n\t}\n\n\treturn daemonSets, nil\n}","line":{"from":39,"to":79}} {"id":100027734,"name":"GetHistoryDaemonSets","signature":"func (s *daemonSetLister) GetHistoryDaemonSets(history *apps.ControllerRevision) ([]*apps.DaemonSet, error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/daemonset_expansion.go","code":"// GetHistoryDaemonSets returns a list of DaemonSets that potentially\n// match a ControllerRevision. Only the one specified in the ControllerRevision's ControllerRef\n// will actually manage it.\n// Returns an error only if no matching DaemonSets are found.\nfunc (s *daemonSetLister) GetHistoryDaemonSets(history *apps.ControllerRevision) ([]*apps.DaemonSet, error) {\n\tif len(history.Labels) == 0 {\n\t\treturn nil, fmt.Errorf(\"no DaemonSet found for ControllerRevision %s because it has no labels\", history.Name)\n\t}\n\n\tlist, err := s.DaemonSets(history.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar daemonSets []*apps.DaemonSet\n\tfor _, ds := range list {\n\t\tselector, err := metav1.LabelSelectorAsSelector(ds.Spec.Selector)\n\t\tif err != nil {\n\t\t\t// This object has an invalid selector, it does not match the history object\n\t\t\tcontinue\n\t\t}\n\t\t// If a DaemonSet with a nil or empty selector creeps in, it should match nothing, not everything.\n\t\tif selector.Empty() || !selector.Matches(labels.Set(history.Labels)) {\n\t\t\tcontinue\n\t\t}\n\t\tdaemonSets = append(daemonSets, ds)\n\t}\n\n\tif len(daemonSets) == 0 {\n\t\treturn nil, fmt.Errorf(\"could not find DaemonSets for ControllerRevision %s in namespace %s with labels: %v\", history.Name, history.Namespace, history.Labels)\n\t}\n\n\treturn daemonSets, nil\n}","line":{"from":81,"to":114}} {"id":100027735,"name":"NewDeploymentLister","signature":"func NewDeploymentLister(indexer cache.Indexer) DeploymentLister","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/deployment.go","code":"// NewDeploymentLister returns a new DeploymentLister.\nfunc NewDeploymentLister(indexer cache.Indexer) DeploymentLister {\n\treturn \u0026deploymentLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027736,"name":"List","signature":"func (s *deploymentLister) List(selector labels.Selector) (ret []*v1beta2.Deployment, err error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/deployment.go","code":"// List lists all Deployments in the indexer.\nfunc (s *deploymentLister) List(selector labels.Selector) (ret []*v1beta2.Deployment, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta2.Deployment))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027737,"name":"Deployments","signature":"func (s *deploymentLister) Deployments(namespace string) DeploymentNamespaceLister","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/deployment.go","code":"// Deployments returns an object that can list and get Deployments.\nfunc (s *deploymentLister) Deployments(namespace string) DeploymentNamespaceLister {\n\treturn deploymentNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027738,"name":"List","signature":"func (s deploymentNamespaceLister) List(selector labels.Selector) (ret []*v1beta2.Deployment, err error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/deployment.go","code":"// List lists all Deployments in the indexer for a given namespace.\nfunc (s deploymentNamespaceLister) List(selector labels.Selector) (ret []*v1beta2.Deployment, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta2.Deployment))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027739,"name":"Get","signature":"func (s deploymentNamespaceLister) Get(name string) (*v1beta2.Deployment, error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/deployment.go","code":"// Get retrieves the Deployment from the indexer for a given namespace and name.\nfunc (s deploymentNamespaceLister) Get(name string) (*v1beta2.Deployment, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta2.Resource(\"deployment\"), name)\n\t}\n\treturn obj.(*v1beta2.Deployment), nil\n}","line":{"from":89,"to":99}} {"id":100027740,"name":"NewReplicaSetLister","signature":"func NewReplicaSetLister(indexer cache.Indexer) ReplicaSetLister","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/replicaset.go","code":"// NewReplicaSetLister returns a new ReplicaSetLister.\nfunc NewReplicaSetLister(indexer cache.Indexer) ReplicaSetLister {\n\treturn \u0026replicaSetLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027741,"name":"List","signature":"func (s *replicaSetLister) List(selector labels.Selector) (ret []*v1beta2.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/replicaset.go","code":"// List lists all ReplicaSets in the indexer.\nfunc (s *replicaSetLister) List(selector labels.Selector) (ret []*v1beta2.ReplicaSet, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta2.ReplicaSet))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027742,"name":"ReplicaSets","signature":"func (s *replicaSetLister) ReplicaSets(namespace string) ReplicaSetNamespaceLister","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/replicaset.go","code":"// ReplicaSets returns an object that can list and get ReplicaSets.\nfunc (s *replicaSetLister) ReplicaSets(namespace string) ReplicaSetNamespaceLister {\n\treturn replicaSetNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027743,"name":"List","signature":"func (s replicaSetNamespaceLister) List(selector labels.Selector) (ret []*v1beta2.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/replicaset.go","code":"// List lists all ReplicaSets in the indexer for a given namespace.\nfunc (s replicaSetNamespaceLister) List(selector labels.Selector) (ret []*v1beta2.ReplicaSet, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta2.ReplicaSet))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027744,"name":"Get","signature":"func (s replicaSetNamespaceLister) Get(name string) (*v1beta2.ReplicaSet, error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/replicaset.go","code":"// Get retrieves the ReplicaSet from the indexer for a given namespace and name.\nfunc (s replicaSetNamespaceLister) Get(name string) (*v1beta2.ReplicaSet, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta2.Resource(\"replicaset\"), name)\n\t}\n\treturn obj.(*v1beta2.ReplicaSet), nil\n}","line":{"from":89,"to":99}} {"id":100027745,"name":"GetPodReplicaSets","signature":"func (s *replicaSetLister) GetPodReplicaSets(pod *v1.Pod) ([]*apps.ReplicaSet, error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/replicaset_expansion.go","code":"// GetPodReplicaSets returns a list of ReplicaSets that potentially match a pod.\n// Only the one specified in the Pod's ControllerRef will actually manage it.\n// Returns an error only if no matching ReplicaSets are found.\nfunc (s *replicaSetLister) GetPodReplicaSets(pod *v1.Pod) ([]*apps.ReplicaSet, error) {\n\tif len(pod.Labels) == 0 {\n\t\treturn nil, fmt.Errorf(\"no ReplicaSets found for pod %v because it has no labels\", pod.Name)\n\t}\n\n\tlist, err := s.ReplicaSets(pod.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar rss []*apps.ReplicaSet\n\tfor _, rs := range list {\n\t\tif rs.Namespace != pod.Namespace {\n\t\t\tcontinue\n\t\t}\n\t\tselector, err := metav1.LabelSelectorAsSelector(rs.Spec.Selector)\n\t\tif err != nil {\n\t\t\t// This object has an invalid selector, it does not match the pod\n\t\t\tcontinue\n\t\t}\n\n\t\t// If a ReplicaSet with a nil or empty selector creeps in, it should match nothing, not everything.\n\t\tif selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) {\n\t\t\tcontinue\n\t\t}\n\t\trss = append(rss, rs)\n\t}\n\n\tif len(rss) == 0 {\n\t\treturn nil, fmt.Errorf(\"could not find ReplicaSet for pod %s in namespace %s with labels: %v\", pod.Name, pod.Namespace, pod.Labels)\n\t}\n\n\treturn rss, nil\n}","line":{"from":38,"to":74}} {"id":100027746,"name":"NewStatefulSetLister","signature":"func NewStatefulSetLister(indexer cache.Indexer) StatefulSetLister","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/statefulset.go","code":"// NewStatefulSetLister returns a new StatefulSetLister.\nfunc NewStatefulSetLister(indexer cache.Indexer) StatefulSetLister {\n\treturn \u0026statefulSetLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027747,"name":"List","signature":"func (s *statefulSetLister) List(selector labels.Selector) (ret []*v1beta2.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/statefulset.go","code":"// List lists all StatefulSets in the indexer.\nfunc (s *statefulSetLister) List(selector labels.Selector) (ret []*v1beta2.StatefulSet, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta2.StatefulSet))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027748,"name":"StatefulSets","signature":"func (s *statefulSetLister) StatefulSets(namespace string) StatefulSetNamespaceLister","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/statefulset.go","code":"// StatefulSets returns an object that can list and get StatefulSets.\nfunc (s *statefulSetLister) StatefulSets(namespace string) StatefulSetNamespaceLister {\n\treturn statefulSetNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027749,"name":"List","signature":"func (s statefulSetNamespaceLister) List(selector labels.Selector) (ret []*v1beta2.StatefulSet, err error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/statefulset.go","code":"// List lists all StatefulSets in the indexer for a given namespace.\nfunc (s statefulSetNamespaceLister) List(selector labels.Selector) (ret []*v1beta2.StatefulSet, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta2.StatefulSet))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027750,"name":"Get","signature":"func (s statefulSetNamespaceLister) Get(name string) (*v1beta2.StatefulSet, error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/statefulset.go","code":"// Get retrieves the StatefulSet from the indexer for a given namespace and name.\nfunc (s statefulSetNamespaceLister) Get(name string) (*v1beta2.StatefulSet, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta2.Resource(\"statefulset\"), name)\n\t}\n\treturn obj.(*v1beta2.StatefulSet), nil\n}","line":{"from":89,"to":99}} {"id":100027751,"name":"GetPodStatefulSets","signature":"func (s *statefulSetLister) GetPodStatefulSets(pod *v1.Pod) ([]*apps.StatefulSet, error)","file":"staging/src/k8s.io/client-go/listers/apps/v1beta2/statefulset_expansion.go","code":"// GetPodStatefulSets returns a list of StatefulSets that potentially match a pod.\n// Only the one specified in the Pod's ControllerRef will actually manage it.\n// Returns an error only if no matching StatefulSets are found.\nfunc (s *statefulSetLister) GetPodStatefulSets(pod *v1.Pod) ([]*apps.StatefulSet, error) {\n\tvar selector labels.Selector\n\tvar ps *apps.StatefulSet\n\n\tif len(pod.Labels) == 0 {\n\t\treturn nil, fmt.Errorf(\"no StatefulSets found for pod %v because it has no labels\", pod.Name)\n\t}\n\n\tlist, err := s.StatefulSets(pod.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar psList []*apps.StatefulSet\n\tfor i := range list {\n\t\tps = list[i]\n\t\tif ps.Namespace != pod.Namespace {\n\t\t\tcontinue\n\t\t}\n\t\tselector, err = metav1.LabelSelectorAsSelector(ps.Spec.Selector)\n\t\tif err != nil {\n\t\t\t// This object has an invalid selector, it does not match the pod\n\t\t\tcontinue\n\t\t}\n\n\t\t// If a StatefulSet with a nil or empty selector creeps in, it should match nothing, not everything.\n\t\tif selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) {\n\t\t\tcontinue\n\t\t}\n\t\tpsList = append(psList, ps)\n\t}\n\n\tif len(psList) == 0 {\n\t\treturn nil, fmt.Errorf(\"could not find StatefulSet for pod %s in namespace %s with labels: %v\", pod.Name, pod.Namespace, pod.Labels)\n\t}\n\n\treturn psList, nil\n}","line":{"from":38,"to":78}} {"id":100027752,"name":"NewHorizontalPodAutoscalerLister","signature":"func NewHorizontalPodAutoscalerLister(indexer cache.Indexer) HorizontalPodAutoscalerLister","file":"staging/src/k8s.io/client-go/listers/autoscaling/v1/horizontalpodautoscaler.go","code":"// NewHorizontalPodAutoscalerLister returns a new HorizontalPodAutoscalerLister.\nfunc NewHorizontalPodAutoscalerLister(indexer cache.Indexer) HorizontalPodAutoscalerLister {\n\treturn \u0026horizontalPodAutoscalerLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027753,"name":"List","signature":"func (s *horizontalPodAutoscalerLister) List(selector labels.Selector) (ret []*v1.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/listers/autoscaling/v1/horizontalpodautoscaler.go","code":"// List lists all HorizontalPodAutoscalers in the indexer.\nfunc (s *horizontalPodAutoscalerLister) List(selector labels.Selector) (ret []*v1.HorizontalPodAutoscaler, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.HorizontalPodAutoscaler))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027754,"name":"HorizontalPodAutoscalers","signature":"func (s *horizontalPodAutoscalerLister) HorizontalPodAutoscalers(namespace string) HorizontalPodAutoscalerNamespaceLister","file":"staging/src/k8s.io/client-go/listers/autoscaling/v1/horizontalpodautoscaler.go","code":"// HorizontalPodAutoscalers returns an object that can list and get HorizontalPodAutoscalers.\nfunc (s *horizontalPodAutoscalerLister) HorizontalPodAutoscalers(namespace string) HorizontalPodAutoscalerNamespaceLister {\n\treturn horizontalPodAutoscalerNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027755,"name":"List","signature":"func (s horizontalPodAutoscalerNamespaceLister) List(selector labels.Selector) (ret []*v1.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/listers/autoscaling/v1/horizontalpodautoscaler.go","code":"// List lists all HorizontalPodAutoscalers in the indexer for a given namespace.\nfunc (s horizontalPodAutoscalerNamespaceLister) List(selector labels.Selector) (ret []*v1.HorizontalPodAutoscaler, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.HorizontalPodAutoscaler))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027756,"name":"Get","signature":"func (s horizontalPodAutoscalerNamespaceLister) Get(name string) (*v1.HorizontalPodAutoscaler, error)","file":"staging/src/k8s.io/client-go/listers/autoscaling/v1/horizontalpodautoscaler.go","code":"// Get retrieves the HorizontalPodAutoscaler from the indexer for a given namespace and name.\nfunc (s horizontalPodAutoscalerNamespaceLister) Get(name string) (*v1.HorizontalPodAutoscaler, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"horizontalpodautoscaler\"), name)\n\t}\n\treturn obj.(*v1.HorizontalPodAutoscaler), nil\n}","line":{"from":89,"to":99}} {"id":100027757,"name":"NewHorizontalPodAutoscalerLister","signature":"func NewHorizontalPodAutoscalerLister(indexer cache.Indexer) HorizontalPodAutoscalerLister","file":"staging/src/k8s.io/client-go/listers/autoscaling/v2/horizontalpodautoscaler.go","code":"// NewHorizontalPodAutoscalerLister returns a new HorizontalPodAutoscalerLister.\nfunc NewHorizontalPodAutoscalerLister(indexer cache.Indexer) HorizontalPodAutoscalerLister {\n\treturn \u0026horizontalPodAutoscalerLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027758,"name":"List","signature":"func (s *horizontalPodAutoscalerLister) List(selector labels.Selector) (ret []*v2.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/listers/autoscaling/v2/horizontalpodautoscaler.go","code":"// List lists all HorizontalPodAutoscalers in the indexer.\nfunc (s *horizontalPodAutoscalerLister) List(selector labels.Selector) (ret []*v2.HorizontalPodAutoscaler, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v2.HorizontalPodAutoscaler))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027759,"name":"HorizontalPodAutoscalers","signature":"func (s *horizontalPodAutoscalerLister) HorizontalPodAutoscalers(namespace string) HorizontalPodAutoscalerNamespaceLister","file":"staging/src/k8s.io/client-go/listers/autoscaling/v2/horizontalpodautoscaler.go","code":"// HorizontalPodAutoscalers returns an object that can list and get HorizontalPodAutoscalers.\nfunc (s *horizontalPodAutoscalerLister) HorizontalPodAutoscalers(namespace string) HorizontalPodAutoscalerNamespaceLister {\n\treturn horizontalPodAutoscalerNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027760,"name":"List","signature":"func (s horizontalPodAutoscalerNamespaceLister) List(selector labels.Selector) (ret []*v2.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/listers/autoscaling/v2/horizontalpodautoscaler.go","code":"// List lists all HorizontalPodAutoscalers in the indexer for a given namespace.\nfunc (s horizontalPodAutoscalerNamespaceLister) List(selector labels.Selector) (ret []*v2.HorizontalPodAutoscaler, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v2.HorizontalPodAutoscaler))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027761,"name":"Get","signature":"func (s horizontalPodAutoscalerNamespaceLister) Get(name string) (*v2.HorizontalPodAutoscaler, error)","file":"staging/src/k8s.io/client-go/listers/autoscaling/v2/horizontalpodautoscaler.go","code":"// Get retrieves the HorizontalPodAutoscaler from the indexer for a given namespace and name.\nfunc (s horizontalPodAutoscalerNamespaceLister) Get(name string) (*v2.HorizontalPodAutoscaler, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v2.Resource(\"horizontalpodautoscaler\"), name)\n\t}\n\treturn obj.(*v2.HorizontalPodAutoscaler), nil\n}","line":{"from":89,"to":99}} {"id":100027762,"name":"NewHorizontalPodAutoscalerLister","signature":"func NewHorizontalPodAutoscalerLister(indexer cache.Indexer) HorizontalPodAutoscalerLister","file":"staging/src/k8s.io/client-go/listers/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// NewHorizontalPodAutoscalerLister returns a new HorizontalPodAutoscalerLister.\nfunc NewHorizontalPodAutoscalerLister(indexer cache.Indexer) HorizontalPodAutoscalerLister {\n\treturn \u0026horizontalPodAutoscalerLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027763,"name":"List","signature":"func (s *horizontalPodAutoscalerLister) List(selector labels.Selector) (ret []*v2beta1.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/listers/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// List lists all HorizontalPodAutoscalers in the indexer.\nfunc (s *horizontalPodAutoscalerLister) List(selector labels.Selector) (ret []*v2beta1.HorizontalPodAutoscaler, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v2beta1.HorizontalPodAutoscaler))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027764,"name":"HorizontalPodAutoscalers","signature":"func (s *horizontalPodAutoscalerLister) HorizontalPodAutoscalers(namespace string) HorizontalPodAutoscalerNamespaceLister","file":"staging/src/k8s.io/client-go/listers/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// HorizontalPodAutoscalers returns an object that can list and get HorizontalPodAutoscalers.\nfunc (s *horizontalPodAutoscalerLister) HorizontalPodAutoscalers(namespace string) HorizontalPodAutoscalerNamespaceLister {\n\treturn horizontalPodAutoscalerNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027765,"name":"List","signature":"func (s horizontalPodAutoscalerNamespaceLister) List(selector labels.Selector) (ret []*v2beta1.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/listers/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// List lists all HorizontalPodAutoscalers in the indexer for a given namespace.\nfunc (s horizontalPodAutoscalerNamespaceLister) List(selector labels.Selector) (ret []*v2beta1.HorizontalPodAutoscaler, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v2beta1.HorizontalPodAutoscaler))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027766,"name":"Get","signature":"func (s horizontalPodAutoscalerNamespaceLister) Get(name string) (*v2beta1.HorizontalPodAutoscaler, error)","file":"staging/src/k8s.io/client-go/listers/autoscaling/v2beta1/horizontalpodautoscaler.go","code":"// Get retrieves the HorizontalPodAutoscaler from the indexer for a given namespace and name.\nfunc (s horizontalPodAutoscalerNamespaceLister) Get(name string) (*v2beta1.HorizontalPodAutoscaler, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v2beta1.Resource(\"horizontalpodautoscaler\"), name)\n\t}\n\treturn obj.(*v2beta1.HorizontalPodAutoscaler), nil\n}","line":{"from":89,"to":99}} {"id":100027767,"name":"NewHorizontalPodAutoscalerLister","signature":"func NewHorizontalPodAutoscalerLister(indexer cache.Indexer) HorizontalPodAutoscalerLister","file":"staging/src/k8s.io/client-go/listers/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// NewHorizontalPodAutoscalerLister returns a new HorizontalPodAutoscalerLister.\nfunc NewHorizontalPodAutoscalerLister(indexer cache.Indexer) HorizontalPodAutoscalerLister {\n\treturn \u0026horizontalPodAutoscalerLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027768,"name":"List","signature":"func (s *horizontalPodAutoscalerLister) List(selector labels.Selector) (ret []*v2beta2.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/listers/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// List lists all HorizontalPodAutoscalers in the indexer.\nfunc (s *horizontalPodAutoscalerLister) List(selector labels.Selector) (ret []*v2beta2.HorizontalPodAutoscaler, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v2beta2.HorizontalPodAutoscaler))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027769,"name":"HorizontalPodAutoscalers","signature":"func (s *horizontalPodAutoscalerLister) HorizontalPodAutoscalers(namespace string) HorizontalPodAutoscalerNamespaceLister","file":"staging/src/k8s.io/client-go/listers/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// HorizontalPodAutoscalers returns an object that can list and get HorizontalPodAutoscalers.\nfunc (s *horizontalPodAutoscalerLister) HorizontalPodAutoscalers(namespace string) HorizontalPodAutoscalerNamespaceLister {\n\treturn horizontalPodAutoscalerNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027770,"name":"List","signature":"func (s horizontalPodAutoscalerNamespaceLister) List(selector labels.Selector) (ret []*v2beta2.HorizontalPodAutoscaler, err error)","file":"staging/src/k8s.io/client-go/listers/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// List lists all HorizontalPodAutoscalers in the indexer for a given namespace.\nfunc (s horizontalPodAutoscalerNamespaceLister) List(selector labels.Selector) (ret []*v2beta2.HorizontalPodAutoscaler, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v2beta2.HorizontalPodAutoscaler))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027771,"name":"Get","signature":"func (s horizontalPodAutoscalerNamespaceLister) Get(name string) (*v2beta2.HorizontalPodAutoscaler, error)","file":"staging/src/k8s.io/client-go/listers/autoscaling/v2beta2/horizontalpodautoscaler.go","code":"// Get retrieves the HorizontalPodAutoscaler from the indexer for a given namespace and name.\nfunc (s horizontalPodAutoscalerNamespaceLister) Get(name string) (*v2beta2.HorizontalPodAutoscaler, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v2beta2.Resource(\"horizontalpodautoscaler\"), name)\n\t}\n\treturn obj.(*v2beta2.HorizontalPodAutoscaler), nil\n}","line":{"from":89,"to":99}} {"id":100027772,"name":"NewCronJobLister","signature":"func NewCronJobLister(indexer cache.Indexer) CronJobLister","file":"staging/src/k8s.io/client-go/listers/batch/v1/cronjob.go","code":"// NewCronJobLister returns a new CronJobLister.\nfunc NewCronJobLister(indexer cache.Indexer) CronJobLister {\n\treturn \u0026cronJobLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027773,"name":"List","signature":"func (s *cronJobLister) List(selector labels.Selector) (ret []*v1.CronJob, err error)","file":"staging/src/k8s.io/client-go/listers/batch/v1/cronjob.go","code":"// List lists all CronJobs in the indexer.\nfunc (s *cronJobLister) List(selector labels.Selector) (ret []*v1.CronJob, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.CronJob))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027774,"name":"CronJobs","signature":"func (s *cronJobLister) CronJobs(namespace string) CronJobNamespaceLister","file":"staging/src/k8s.io/client-go/listers/batch/v1/cronjob.go","code":"// CronJobs returns an object that can list and get CronJobs.\nfunc (s *cronJobLister) CronJobs(namespace string) CronJobNamespaceLister {\n\treturn cronJobNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027775,"name":"List","signature":"func (s cronJobNamespaceLister) List(selector labels.Selector) (ret []*v1.CronJob, err error)","file":"staging/src/k8s.io/client-go/listers/batch/v1/cronjob.go","code":"// List lists all CronJobs in the indexer for a given namespace.\nfunc (s cronJobNamespaceLister) List(selector labels.Selector) (ret []*v1.CronJob, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.CronJob))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027776,"name":"Get","signature":"func (s cronJobNamespaceLister) Get(name string) (*v1.CronJob, error)","file":"staging/src/k8s.io/client-go/listers/batch/v1/cronjob.go","code":"// Get retrieves the CronJob from the indexer for a given namespace and name.\nfunc (s cronJobNamespaceLister) Get(name string) (*v1.CronJob, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"cronjob\"), name)\n\t}\n\treturn obj.(*v1.CronJob), nil\n}","line":{"from":89,"to":99}} {"id":100027777,"name":"NewJobLister","signature":"func NewJobLister(indexer cache.Indexer) JobLister","file":"staging/src/k8s.io/client-go/listers/batch/v1/job.go","code":"// NewJobLister returns a new JobLister.\nfunc NewJobLister(indexer cache.Indexer) JobLister {\n\treturn \u0026jobLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027778,"name":"List","signature":"func (s *jobLister) List(selector labels.Selector) (ret []*v1.Job, err error)","file":"staging/src/k8s.io/client-go/listers/batch/v1/job.go","code":"// List lists all Jobs in the indexer.\nfunc (s *jobLister) List(selector labels.Selector) (ret []*v1.Job, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Job))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027779,"name":"Jobs","signature":"func (s *jobLister) Jobs(namespace string) JobNamespaceLister","file":"staging/src/k8s.io/client-go/listers/batch/v1/job.go","code":"// Jobs returns an object that can list and get Jobs.\nfunc (s *jobLister) Jobs(namespace string) JobNamespaceLister {\n\treturn jobNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027780,"name":"List","signature":"func (s jobNamespaceLister) List(selector labels.Selector) (ret []*v1.Job, err error)","file":"staging/src/k8s.io/client-go/listers/batch/v1/job.go","code":"// List lists all Jobs in the indexer for a given namespace.\nfunc (s jobNamespaceLister) List(selector labels.Selector) (ret []*v1.Job, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Job))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027781,"name":"Get","signature":"func (s jobNamespaceLister) Get(name string) (*v1.Job, error)","file":"staging/src/k8s.io/client-go/listers/batch/v1/job.go","code":"// Get retrieves the Job from the indexer for a given namespace and name.\nfunc (s jobNamespaceLister) Get(name string) (*v1.Job, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"job\"), name)\n\t}\n\treturn obj.(*v1.Job), nil\n}","line":{"from":89,"to":99}} {"id":100027782,"name":"GetPodJobs","signature":"func (l *jobLister) GetPodJobs(pod *v1.Pod) (jobs []batch.Job, err error)","file":"staging/src/k8s.io/client-go/listers/batch/v1/job_expansion.go","code":"// GetPodJobs returns a list of Jobs that potentially\n// match a Pod. Only the one specified in the Pod's ControllerRef\n// will actually manage it.\n// Returns an error only if no matching Jobs are found.\nfunc (l *jobLister) GetPodJobs(pod *v1.Pod) (jobs []batch.Job, err error) {\n\tif len(pod.Labels) == 0 {\n\t\terr = fmt.Errorf(\"no jobs found for pod %v because it has no labels\", pod.Name)\n\t\treturn\n\t}\n\n\tvar list []*batch.Job\n\tlist, err = l.Jobs(pod.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn\n\t}\n\tfor _, job := range list {\n\t\tselector, err := metav1.LabelSelectorAsSelector(job.Spec.Selector)\n\t\tif err != nil {\n\t\t\t// This object has an invalid selector, it does not match the pod\n\t\t\tcontinue\n\t\t}\n\t\tif !selector.Matches(labels.Set(pod.Labels)) {\n\t\t\tcontinue\n\t\t}\n\t\tjobs = append(jobs, *job)\n\t}\n\tif len(jobs) == 0 {\n\t\terr = fmt.Errorf(\"could not find jobs for pod %s in namespace %s with labels: %v\", pod.Name, pod.Namespace, pod.Labels)\n\t}\n\treturn\n}","line":{"from":38,"to":68}} {"id":100027783,"name":"NewCronJobLister","signature":"func NewCronJobLister(indexer cache.Indexer) CronJobLister","file":"staging/src/k8s.io/client-go/listers/batch/v1beta1/cronjob.go","code":"// NewCronJobLister returns a new CronJobLister.\nfunc NewCronJobLister(indexer cache.Indexer) CronJobLister {\n\treturn \u0026cronJobLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027784,"name":"List","signature":"func (s *cronJobLister) List(selector labels.Selector) (ret []*v1beta1.CronJob, err error)","file":"staging/src/k8s.io/client-go/listers/batch/v1beta1/cronjob.go","code":"// List lists all CronJobs in the indexer.\nfunc (s *cronJobLister) List(selector labels.Selector) (ret []*v1beta1.CronJob, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.CronJob))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027785,"name":"CronJobs","signature":"func (s *cronJobLister) CronJobs(namespace string) CronJobNamespaceLister","file":"staging/src/k8s.io/client-go/listers/batch/v1beta1/cronjob.go","code":"// CronJobs returns an object that can list and get CronJobs.\nfunc (s *cronJobLister) CronJobs(namespace string) CronJobNamespaceLister {\n\treturn cronJobNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027786,"name":"List","signature":"func (s cronJobNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.CronJob, err error)","file":"staging/src/k8s.io/client-go/listers/batch/v1beta1/cronjob.go","code":"// List lists all CronJobs in the indexer for a given namespace.\nfunc (s cronJobNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.CronJob, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.CronJob))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027787,"name":"Get","signature":"func (s cronJobNamespaceLister) Get(name string) (*v1beta1.CronJob, error)","file":"staging/src/k8s.io/client-go/listers/batch/v1beta1/cronjob.go","code":"// Get retrieves the CronJob from the indexer for a given namespace and name.\nfunc (s cronJobNamespaceLister) Get(name string) (*v1beta1.CronJob, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"cronjob\"), name)\n\t}\n\treturn obj.(*v1beta1.CronJob), nil\n}","line":{"from":89,"to":99}} {"id":100027788,"name":"NewCertificateSigningRequestLister","signature":"func NewCertificateSigningRequestLister(indexer cache.Indexer) CertificateSigningRequestLister","file":"staging/src/k8s.io/client-go/listers/certificates/v1/certificatesigningrequest.go","code":"// NewCertificateSigningRequestLister returns a new CertificateSigningRequestLister.\nfunc NewCertificateSigningRequestLister(indexer cache.Indexer) CertificateSigningRequestLister {\n\treturn \u0026certificateSigningRequestLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027789,"name":"List","signature":"func (s *certificateSigningRequestLister) List(selector labels.Selector) (ret []*v1.CertificateSigningRequest, err error)","file":"staging/src/k8s.io/client-go/listers/certificates/v1/certificatesigningrequest.go","code":"// List lists all CertificateSigningRequests in the indexer.\nfunc (s *certificateSigningRequestLister) List(selector labels.Selector) (ret []*v1.CertificateSigningRequest, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.CertificateSigningRequest))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027790,"name":"Get","signature":"func (s *certificateSigningRequestLister) Get(name string) (*v1.CertificateSigningRequest, error)","file":"staging/src/k8s.io/client-go/listers/certificates/v1/certificatesigningrequest.go","code":"// Get retrieves the CertificateSigningRequest from the index for a given name.\nfunc (s *certificateSigningRequestLister) Get(name string) (*v1.CertificateSigningRequest, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"certificatesigningrequest\"), name)\n\t}\n\treturn obj.(*v1.CertificateSigningRequest), nil\n}","line":{"from":58,"to":68}} {"id":100027791,"name":"NewClusterTrustBundleLister","signature":"func NewClusterTrustBundleLister(indexer cache.Indexer) ClusterTrustBundleLister","file":"staging/src/k8s.io/client-go/listers/certificates/v1alpha1/clustertrustbundle.go","code":"// NewClusterTrustBundleLister returns a new ClusterTrustBundleLister.\nfunc NewClusterTrustBundleLister(indexer cache.Indexer) ClusterTrustBundleLister {\n\treturn \u0026clusterTrustBundleLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027792,"name":"List","signature":"func (s *clusterTrustBundleLister) List(selector labels.Selector) (ret []*v1alpha1.ClusterTrustBundle, err error)","file":"staging/src/k8s.io/client-go/listers/certificates/v1alpha1/clustertrustbundle.go","code":"// List lists all ClusterTrustBundles in the indexer.\nfunc (s *clusterTrustBundleLister) List(selector labels.Selector) (ret []*v1alpha1.ClusterTrustBundle, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ClusterTrustBundle))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027793,"name":"Get","signature":"func (s *clusterTrustBundleLister) Get(name string) (*v1alpha1.ClusterTrustBundle, error)","file":"staging/src/k8s.io/client-go/listers/certificates/v1alpha1/clustertrustbundle.go","code":"// Get retrieves the ClusterTrustBundle from the index for a given name.\nfunc (s *clusterTrustBundleLister) Get(name string) (*v1alpha1.ClusterTrustBundle, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"clustertrustbundle\"), name)\n\t}\n\treturn obj.(*v1alpha1.ClusterTrustBundle), nil\n}","line":{"from":58,"to":68}} {"id":100027794,"name":"NewCertificateSigningRequestLister","signature":"func NewCertificateSigningRequestLister(indexer cache.Indexer) CertificateSigningRequestLister","file":"staging/src/k8s.io/client-go/listers/certificates/v1beta1/certificatesigningrequest.go","code":"// NewCertificateSigningRequestLister returns a new CertificateSigningRequestLister.\nfunc NewCertificateSigningRequestLister(indexer cache.Indexer) CertificateSigningRequestLister {\n\treturn \u0026certificateSigningRequestLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027795,"name":"List","signature":"func (s *certificateSigningRequestLister) List(selector labels.Selector) (ret []*v1beta1.CertificateSigningRequest, err error)","file":"staging/src/k8s.io/client-go/listers/certificates/v1beta1/certificatesigningrequest.go","code":"// List lists all CertificateSigningRequests in the indexer.\nfunc (s *certificateSigningRequestLister) List(selector labels.Selector) (ret []*v1beta1.CertificateSigningRequest, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.CertificateSigningRequest))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027796,"name":"Get","signature":"func (s *certificateSigningRequestLister) Get(name string) (*v1beta1.CertificateSigningRequest, error)","file":"staging/src/k8s.io/client-go/listers/certificates/v1beta1/certificatesigningrequest.go","code":"// Get retrieves the CertificateSigningRequest from the index for a given name.\nfunc (s *certificateSigningRequestLister) Get(name string) (*v1beta1.CertificateSigningRequest, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"certificatesigningrequest\"), name)\n\t}\n\treturn obj.(*v1beta1.CertificateSigningRequest), nil\n}","line":{"from":58,"to":68}} {"id":100027797,"name":"NewLeaseLister","signature":"func NewLeaseLister(indexer cache.Indexer) LeaseLister","file":"staging/src/k8s.io/client-go/listers/coordination/v1/lease.go","code":"// NewLeaseLister returns a new LeaseLister.\nfunc NewLeaseLister(indexer cache.Indexer) LeaseLister {\n\treturn \u0026leaseLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027798,"name":"List","signature":"func (s *leaseLister) List(selector labels.Selector) (ret []*v1.Lease, err error)","file":"staging/src/k8s.io/client-go/listers/coordination/v1/lease.go","code":"// List lists all Leases in the indexer.\nfunc (s *leaseLister) List(selector labels.Selector) (ret []*v1.Lease, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Lease))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027799,"name":"Leases","signature":"func (s *leaseLister) Leases(namespace string) LeaseNamespaceLister","file":"staging/src/k8s.io/client-go/listers/coordination/v1/lease.go","code":"// Leases returns an object that can list and get Leases.\nfunc (s *leaseLister) Leases(namespace string) LeaseNamespaceLister {\n\treturn leaseNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027800,"name":"List","signature":"func (s leaseNamespaceLister) List(selector labels.Selector) (ret []*v1.Lease, err error)","file":"staging/src/k8s.io/client-go/listers/coordination/v1/lease.go","code":"// List lists all Leases in the indexer for a given namespace.\nfunc (s leaseNamespaceLister) List(selector labels.Selector) (ret []*v1.Lease, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Lease))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027801,"name":"Get","signature":"func (s leaseNamespaceLister) Get(name string) (*v1.Lease, error)","file":"staging/src/k8s.io/client-go/listers/coordination/v1/lease.go","code":"// Get retrieves the Lease from the indexer for a given namespace and name.\nfunc (s leaseNamespaceLister) Get(name string) (*v1.Lease, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"lease\"), name)\n\t}\n\treturn obj.(*v1.Lease), nil\n}","line":{"from":89,"to":99}} {"id":100027802,"name":"NewLeaseLister","signature":"func NewLeaseLister(indexer cache.Indexer) LeaseLister","file":"staging/src/k8s.io/client-go/listers/coordination/v1beta1/lease.go","code":"// NewLeaseLister returns a new LeaseLister.\nfunc NewLeaseLister(indexer cache.Indexer) LeaseLister {\n\treturn \u0026leaseLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027803,"name":"List","signature":"func (s *leaseLister) List(selector labels.Selector) (ret []*v1beta1.Lease, err error)","file":"staging/src/k8s.io/client-go/listers/coordination/v1beta1/lease.go","code":"// List lists all Leases in the indexer.\nfunc (s *leaseLister) List(selector labels.Selector) (ret []*v1beta1.Lease, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.Lease))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027804,"name":"Leases","signature":"func (s *leaseLister) Leases(namespace string) LeaseNamespaceLister","file":"staging/src/k8s.io/client-go/listers/coordination/v1beta1/lease.go","code":"// Leases returns an object that can list and get Leases.\nfunc (s *leaseLister) Leases(namespace string) LeaseNamespaceLister {\n\treturn leaseNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027805,"name":"List","signature":"func (s leaseNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.Lease, err error)","file":"staging/src/k8s.io/client-go/listers/coordination/v1beta1/lease.go","code":"// List lists all Leases in the indexer for a given namespace.\nfunc (s leaseNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.Lease, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.Lease))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027806,"name":"Get","signature":"func (s leaseNamespaceLister) Get(name string) (*v1beta1.Lease, error)","file":"staging/src/k8s.io/client-go/listers/coordination/v1beta1/lease.go","code":"// Get retrieves the Lease from the indexer for a given namespace and name.\nfunc (s leaseNamespaceLister) Get(name string) (*v1beta1.Lease, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"lease\"), name)\n\t}\n\treturn obj.(*v1beta1.Lease), nil\n}","line":{"from":89,"to":99}} {"id":100027807,"name":"NewComponentStatusLister","signature":"func NewComponentStatusLister(indexer cache.Indexer) ComponentStatusLister","file":"staging/src/k8s.io/client-go/listers/core/v1/componentstatus.go","code":"// NewComponentStatusLister returns a new ComponentStatusLister.\nfunc NewComponentStatusLister(indexer cache.Indexer) ComponentStatusLister {\n\treturn \u0026componentStatusLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027808,"name":"List","signature":"func (s *componentStatusLister) List(selector labels.Selector) (ret []*v1.ComponentStatus, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/componentstatus.go","code":"// List lists all ComponentStatuses in the indexer.\nfunc (s *componentStatusLister) List(selector labels.Selector) (ret []*v1.ComponentStatus, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.ComponentStatus))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027809,"name":"Get","signature":"func (s *componentStatusLister) Get(name string) (*v1.ComponentStatus, error)","file":"staging/src/k8s.io/client-go/listers/core/v1/componentstatus.go","code":"// Get retrieves the ComponentStatus from the index for a given name.\nfunc (s *componentStatusLister) Get(name string) (*v1.ComponentStatus, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"componentstatus\"), name)\n\t}\n\treturn obj.(*v1.ComponentStatus), nil\n}","line":{"from":58,"to":68}} {"id":100027810,"name":"NewConfigMapLister","signature":"func NewConfigMapLister(indexer cache.Indexer) ConfigMapLister","file":"staging/src/k8s.io/client-go/listers/core/v1/configmap.go","code":"// NewConfigMapLister returns a new ConfigMapLister.\nfunc NewConfigMapLister(indexer cache.Indexer) ConfigMapLister {\n\treturn \u0026configMapLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027811,"name":"List","signature":"func (s *configMapLister) List(selector labels.Selector) (ret []*v1.ConfigMap, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/configmap.go","code":"// List lists all ConfigMaps in the indexer.\nfunc (s *configMapLister) List(selector labels.Selector) (ret []*v1.ConfigMap, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.ConfigMap))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027812,"name":"ConfigMaps","signature":"func (s *configMapLister) ConfigMaps(namespace string) ConfigMapNamespaceLister","file":"staging/src/k8s.io/client-go/listers/core/v1/configmap.go","code":"// ConfigMaps returns an object that can list and get ConfigMaps.\nfunc (s *configMapLister) ConfigMaps(namespace string) ConfigMapNamespaceLister {\n\treturn configMapNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027813,"name":"List","signature":"func (s configMapNamespaceLister) List(selector labels.Selector) (ret []*v1.ConfigMap, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/configmap.go","code":"// List lists all ConfigMaps in the indexer for a given namespace.\nfunc (s configMapNamespaceLister) List(selector labels.Selector) (ret []*v1.ConfigMap, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.ConfigMap))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027814,"name":"Get","signature":"func (s configMapNamespaceLister) Get(name string) (*v1.ConfigMap, error)","file":"staging/src/k8s.io/client-go/listers/core/v1/configmap.go","code":"// Get retrieves the ConfigMap from the indexer for a given namespace and name.\nfunc (s configMapNamespaceLister) Get(name string) (*v1.ConfigMap, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"configmap\"), name)\n\t}\n\treturn obj.(*v1.ConfigMap), nil\n}","line":{"from":89,"to":99}} {"id":100027815,"name":"NewEndpointsLister","signature":"func NewEndpointsLister(indexer cache.Indexer) EndpointsLister","file":"staging/src/k8s.io/client-go/listers/core/v1/endpoints.go","code":"// NewEndpointsLister returns a new EndpointsLister.\nfunc NewEndpointsLister(indexer cache.Indexer) EndpointsLister {\n\treturn \u0026endpointsLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027816,"name":"List","signature":"func (s *endpointsLister) List(selector labels.Selector) (ret []*v1.Endpoints, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/endpoints.go","code":"// List lists all Endpoints in the indexer.\nfunc (s *endpointsLister) List(selector labels.Selector) (ret []*v1.Endpoints, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Endpoints))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027817,"name":"Endpoints","signature":"func (s *endpointsLister) Endpoints(namespace string) EndpointsNamespaceLister","file":"staging/src/k8s.io/client-go/listers/core/v1/endpoints.go","code":"// Endpoints returns an object that can list and get Endpoints.\nfunc (s *endpointsLister) Endpoints(namespace string) EndpointsNamespaceLister {\n\treturn endpointsNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027818,"name":"List","signature":"func (s endpointsNamespaceLister) List(selector labels.Selector) (ret []*v1.Endpoints, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/endpoints.go","code":"// List lists all Endpoints in the indexer for a given namespace.\nfunc (s endpointsNamespaceLister) List(selector labels.Selector) (ret []*v1.Endpoints, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Endpoints))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027819,"name":"Get","signature":"func (s endpointsNamespaceLister) Get(name string) (*v1.Endpoints, error)","file":"staging/src/k8s.io/client-go/listers/core/v1/endpoints.go","code":"// Get retrieves the Endpoints from the indexer for a given namespace and name.\nfunc (s endpointsNamespaceLister) Get(name string) (*v1.Endpoints, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"endpoints\"), name)\n\t}\n\treturn obj.(*v1.Endpoints), nil\n}","line":{"from":89,"to":99}} {"id":100027820,"name":"NewEventLister","signature":"func NewEventLister(indexer cache.Indexer) EventLister","file":"staging/src/k8s.io/client-go/listers/core/v1/event.go","code":"// NewEventLister returns a new EventLister.\nfunc NewEventLister(indexer cache.Indexer) EventLister {\n\treturn \u0026eventLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027821,"name":"List","signature":"func (s *eventLister) List(selector labels.Selector) (ret []*v1.Event, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/event.go","code":"// List lists all Events in the indexer.\nfunc (s *eventLister) List(selector labels.Selector) (ret []*v1.Event, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Event))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027822,"name":"Events","signature":"func (s *eventLister) Events(namespace string) EventNamespaceLister","file":"staging/src/k8s.io/client-go/listers/core/v1/event.go","code":"// Events returns an object that can list and get Events.\nfunc (s *eventLister) Events(namespace string) EventNamespaceLister {\n\treturn eventNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027823,"name":"List","signature":"func (s eventNamespaceLister) List(selector labels.Selector) (ret []*v1.Event, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/event.go","code":"// List lists all Events in the indexer for a given namespace.\nfunc (s eventNamespaceLister) List(selector labels.Selector) (ret []*v1.Event, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Event))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027824,"name":"Get","signature":"func (s eventNamespaceLister) Get(name string) (*v1.Event, error)","file":"staging/src/k8s.io/client-go/listers/core/v1/event.go","code":"// Get retrieves the Event from the indexer for a given namespace and name.\nfunc (s eventNamespaceLister) Get(name string) (*v1.Event, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"event\"), name)\n\t}\n\treturn obj.(*v1.Event), nil\n}","line":{"from":89,"to":99}} {"id":100027825,"name":"NewLimitRangeLister","signature":"func NewLimitRangeLister(indexer cache.Indexer) LimitRangeLister","file":"staging/src/k8s.io/client-go/listers/core/v1/limitrange.go","code":"// NewLimitRangeLister returns a new LimitRangeLister.\nfunc NewLimitRangeLister(indexer cache.Indexer) LimitRangeLister {\n\treturn \u0026limitRangeLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027826,"name":"List","signature":"func (s *limitRangeLister) List(selector labels.Selector) (ret []*v1.LimitRange, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/limitrange.go","code":"// List lists all LimitRanges in the indexer.\nfunc (s *limitRangeLister) List(selector labels.Selector) (ret []*v1.LimitRange, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.LimitRange))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027827,"name":"LimitRanges","signature":"func (s *limitRangeLister) LimitRanges(namespace string) LimitRangeNamespaceLister","file":"staging/src/k8s.io/client-go/listers/core/v1/limitrange.go","code":"// LimitRanges returns an object that can list and get LimitRanges.\nfunc (s *limitRangeLister) LimitRanges(namespace string) LimitRangeNamespaceLister {\n\treturn limitRangeNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027828,"name":"List","signature":"func (s limitRangeNamespaceLister) List(selector labels.Selector) (ret []*v1.LimitRange, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/limitrange.go","code":"// List lists all LimitRanges in the indexer for a given namespace.\nfunc (s limitRangeNamespaceLister) List(selector labels.Selector) (ret []*v1.LimitRange, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.LimitRange))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027829,"name":"Get","signature":"func (s limitRangeNamespaceLister) Get(name string) (*v1.LimitRange, error)","file":"staging/src/k8s.io/client-go/listers/core/v1/limitrange.go","code":"// Get retrieves the LimitRange from the indexer for a given namespace and name.\nfunc (s limitRangeNamespaceLister) Get(name string) (*v1.LimitRange, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"limitrange\"), name)\n\t}\n\treturn obj.(*v1.LimitRange), nil\n}","line":{"from":89,"to":99}} {"id":100027830,"name":"NewNamespaceLister","signature":"func NewNamespaceLister(indexer cache.Indexer) NamespaceLister","file":"staging/src/k8s.io/client-go/listers/core/v1/namespace.go","code":"// NewNamespaceLister returns a new NamespaceLister.\nfunc NewNamespaceLister(indexer cache.Indexer) NamespaceLister {\n\treturn \u0026namespaceLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027831,"name":"List","signature":"func (s *namespaceLister) List(selector labels.Selector) (ret []*v1.Namespace, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/namespace.go","code":"// List lists all Namespaces in the indexer.\nfunc (s *namespaceLister) List(selector labels.Selector) (ret []*v1.Namespace, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Namespace))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027832,"name":"Get","signature":"func (s *namespaceLister) Get(name string) (*v1.Namespace, error)","file":"staging/src/k8s.io/client-go/listers/core/v1/namespace.go","code":"// Get retrieves the Namespace from the index for a given name.\nfunc (s *namespaceLister) Get(name string) (*v1.Namespace, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"namespace\"), name)\n\t}\n\treturn obj.(*v1.Namespace), nil\n}","line":{"from":58,"to":68}} {"id":100027833,"name":"NewNodeLister","signature":"func NewNodeLister(indexer cache.Indexer) NodeLister","file":"staging/src/k8s.io/client-go/listers/core/v1/node.go","code":"// NewNodeLister returns a new NodeLister.\nfunc NewNodeLister(indexer cache.Indexer) NodeLister {\n\treturn \u0026nodeLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027834,"name":"List","signature":"func (s *nodeLister) List(selector labels.Selector) (ret []*v1.Node, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/node.go","code":"// List lists all Nodes in the indexer.\nfunc (s *nodeLister) List(selector labels.Selector) (ret []*v1.Node, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Node))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027835,"name":"Get","signature":"func (s *nodeLister) Get(name string) (*v1.Node, error)","file":"staging/src/k8s.io/client-go/listers/core/v1/node.go","code":"// Get retrieves the Node from the index for a given name.\nfunc (s *nodeLister) Get(name string) (*v1.Node, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"node\"), name)\n\t}\n\treturn obj.(*v1.Node), nil\n}","line":{"from":58,"to":68}} {"id":100027836,"name":"NewPersistentVolumeLister","signature":"func NewPersistentVolumeLister(indexer cache.Indexer) PersistentVolumeLister","file":"staging/src/k8s.io/client-go/listers/core/v1/persistentvolume.go","code":"// NewPersistentVolumeLister returns a new PersistentVolumeLister.\nfunc NewPersistentVolumeLister(indexer cache.Indexer) PersistentVolumeLister {\n\treturn \u0026persistentVolumeLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027837,"name":"List","signature":"func (s *persistentVolumeLister) List(selector labels.Selector) (ret []*v1.PersistentVolume, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/persistentvolume.go","code":"// List lists all PersistentVolumes in the indexer.\nfunc (s *persistentVolumeLister) List(selector labels.Selector) (ret []*v1.PersistentVolume, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.PersistentVolume))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027838,"name":"Get","signature":"func (s *persistentVolumeLister) Get(name string) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/client-go/listers/core/v1/persistentvolume.go","code":"// Get retrieves the PersistentVolume from the index for a given name.\nfunc (s *persistentVolumeLister) Get(name string) (*v1.PersistentVolume, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"persistentvolume\"), name)\n\t}\n\treturn obj.(*v1.PersistentVolume), nil\n}","line":{"from":58,"to":68}} {"id":100027839,"name":"NewPersistentVolumeClaimLister","signature":"func NewPersistentVolumeClaimLister(indexer cache.Indexer) PersistentVolumeClaimLister","file":"staging/src/k8s.io/client-go/listers/core/v1/persistentvolumeclaim.go","code":"// NewPersistentVolumeClaimLister returns a new PersistentVolumeClaimLister.\nfunc NewPersistentVolumeClaimLister(indexer cache.Indexer) PersistentVolumeClaimLister {\n\treturn \u0026persistentVolumeClaimLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027840,"name":"List","signature":"func (s *persistentVolumeClaimLister) List(selector labels.Selector) (ret []*v1.PersistentVolumeClaim, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/persistentvolumeclaim.go","code":"// List lists all PersistentVolumeClaims in the indexer.\nfunc (s *persistentVolumeClaimLister) List(selector labels.Selector) (ret []*v1.PersistentVolumeClaim, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.PersistentVolumeClaim))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027841,"name":"PersistentVolumeClaims","signature":"func (s *persistentVolumeClaimLister) PersistentVolumeClaims(namespace string) PersistentVolumeClaimNamespaceLister","file":"staging/src/k8s.io/client-go/listers/core/v1/persistentvolumeclaim.go","code":"// PersistentVolumeClaims returns an object that can list and get PersistentVolumeClaims.\nfunc (s *persistentVolumeClaimLister) PersistentVolumeClaims(namespace string) PersistentVolumeClaimNamespaceLister {\n\treturn persistentVolumeClaimNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027842,"name":"List","signature":"func (s persistentVolumeClaimNamespaceLister) List(selector labels.Selector) (ret []*v1.PersistentVolumeClaim, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/persistentvolumeclaim.go","code":"// List lists all PersistentVolumeClaims in the indexer for a given namespace.\nfunc (s persistentVolumeClaimNamespaceLister) List(selector labels.Selector) (ret []*v1.PersistentVolumeClaim, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.PersistentVolumeClaim))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027843,"name":"Get","signature":"func (s persistentVolumeClaimNamespaceLister) Get(name string) (*v1.PersistentVolumeClaim, error)","file":"staging/src/k8s.io/client-go/listers/core/v1/persistentvolumeclaim.go","code":"// Get retrieves the PersistentVolumeClaim from the indexer for a given namespace and name.\nfunc (s persistentVolumeClaimNamespaceLister) Get(name string) (*v1.PersistentVolumeClaim, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"persistentvolumeclaim\"), name)\n\t}\n\treturn obj.(*v1.PersistentVolumeClaim), nil\n}","line":{"from":89,"to":99}} {"id":100027844,"name":"NewPodLister","signature":"func NewPodLister(indexer cache.Indexer) PodLister","file":"staging/src/k8s.io/client-go/listers/core/v1/pod.go","code":"// NewPodLister returns a new PodLister.\nfunc NewPodLister(indexer cache.Indexer) PodLister {\n\treturn \u0026podLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027845,"name":"List","signature":"func (s *podLister) List(selector labels.Selector) (ret []*v1.Pod, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/pod.go","code":"// List lists all Pods in the indexer.\nfunc (s *podLister) List(selector labels.Selector) (ret []*v1.Pod, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Pod))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027846,"name":"Pods","signature":"func (s *podLister) Pods(namespace string) PodNamespaceLister","file":"staging/src/k8s.io/client-go/listers/core/v1/pod.go","code":"// Pods returns an object that can list and get Pods.\nfunc (s *podLister) Pods(namespace string) PodNamespaceLister {\n\treturn podNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027847,"name":"List","signature":"func (s podNamespaceLister) List(selector labels.Selector) (ret []*v1.Pod, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/pod.go","code":"// List lists all Pods in the indexer for a given namespace.\nfunc (s podNamespaceLister) List(selector labels.Selector) (ret []*v1.Pod, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Pod))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027848,"name":"Get","signature":"func (s podNamespaceLister) Get(name string) (*v1.Pod, error)","file":"staging/src/k8s.io/client-go/listers/core/v1/pod.go","code":"// Get retrieves the Pod from the indexer for a given namespace and name.\nfunc (s podNamespaceLister) Get(name string) (*v1.Pod, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"pod\"), name)\n\t}\n\treturn obj.(*v1.Pod), nil\n}","line":{"from":89,"to":99}} {"id":100027849,"name":"NewPodTemplateLister","signature":"func NewPodTemplateLister(indexer cache.Indexer) PodTemplateLister","file":"staging/src/k8s.io/client-go/listers/core/v1/podtemplate.go","code":"// NewPodTemplateLister returns a new PodTemplateLister.\nfunc NewPodTemplateLister(indexer cache.Indexer) PodTemplateLister {\n\treturn \u0026podTemplateLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027850,"name":"List","signature":"func (s *podTemplateLister) List(selector labels.Selector) (ret []*v1.PodTemplate, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/podtemplate.go","code":"// List lists all PodTemplates in the indexer.\nfunc (s *podTemplateLister) List(selector labels.Selector) (ret []*v1.PodTemplate, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.PodTemplate))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027851,"name":"PodTemplates","signature":"func (s *podTemplateLister) PodTemplates(namespace string) PodTemplateNamespaceLister","file":"staging/src/k8s.io/client-go/listers/core/v1/podtemplate.go","code":"// PodTemplates returns an object that can list and get PodTemplates.\nfunc (s *podTemplateLister) PodTemplates(namespace string) PodTemplateNamespaceLister {\n\treturn podTemplateNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027852,"name":"List","signature":"func (s podTemplateNamespaceLister) List(selector labels.Selector) (ret []*v1.PodTemplate, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/podtemplate.go","code":"// List lists all PodTemplates in the indexer for a given namespace.\nfunc (s podTemplateNamespaceLister) List(selector labels.Selector) (ret []*v1.PodTemplate, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.PodTemplate))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027853,"name":"Get","signature":"func (s podTemplateNamespaceLister) Get(name string) (*v1.PodTemplate, error)","file":"staging/src/k8s.io/client-go/listers/core/v1/podtemplate.go","code":"// Get retrieves the PodTemplate from the indexer for a given namespace and name.\nfunc (s podTemplateNamespaceLister) Get(name string) (*v1.PodTemplate, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"podtemplate\"), name)\n\t}\n\treturn obj.(*v1.PodTemplate), nil\n}","line":{"from":89,"to":99}} {"id":100027854,"name":"NewReplicationControllerLister","signature":"func NewReplicationControllerLister(indexer cache.Indexer) ReplicationControllerLister","file":"staging/src/k8s.io/client-go/listers/core/v1/replicationcontroller.go","code":"// NewReplicationControllerLister returns a new ReplicationControllerLister.\nfunc NewReplicationControllerLister(indexer cache.Indexer) ReplicationControllerLister {\n\treturn \u0026replicationControllerLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027855,"name":"List","signature":"func (s *replicationControllerLister) List(selector labels.Selector) (ret []*v1.ReplicationController, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/replicationcontroller.go","code":"// List lists all ReplicationControllers in the indexer.\nfunc (s *replicationControllerLister) List(selector labels.Selector) (ret []*v1.ReplicationController, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.ReplicationController))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027856,"name":"ReplicationControllers","signature":"func (s *replicationControllerLister) ReplicationControllers(namespace string) ReplicationControllerNamespaceLister","file":"staging/src/k8s.io/client-go/listers/core/v1/replicationcontroller.go","code":"// ReplicationControllers returns an object that can list and get ReplicationControllers.\nfunc (s *replicationControllerLister) ReplicationControllers(namespace string) ReplicationControllerNamespaceLister {\n\treturn replicationControllerNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027857,"name":"List","signature":"func (s replicationControllerNamespaceLister) List(selector labels.Selector) (ret []*v1.ReplicationController, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/replicationcontroller.go","code":"// List lists all ReplicationControllers in the indexer for a given namespace.\nfunc (s replicationControllerNamespaceLister) List(selector labels.Selector) (ret []*v1.ReplicationController, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.ReplicationController))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027858,"name":"Get","signature":"func (s replicationControllerNamespaceLister) Get(name string) (*v1.ReplicationController, error)","file":"staging/src/k8s.io/client-go/listers/core/v1/replicationcontroller.go","code":"// Get retrieves the ReplicationController from the indexer for a given namespace and name.\nfunc (s replicationControllerNamespaceLister) Get(name string) (*v1.ReplicationController, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"replicationcontroller\"), name)\n\t}\n\treturn obj.(*v1.ReplicationController), nil\n}","line":{"from":89,"to":99}} {"id":100027859,"name":"GetPodControllers","signature":"func (s *replicationControllerLister) GetPodControllers(pod *v1.Pod) ([]*v1.ReplicationController, error)","file":"staging/src/k8s.io/client-go/listers/core/v1/replicationcontroller_expansion.go","code":"// GetPodControllers returns a list of ReplicationControllers that potentially match a pod.\n// Only the one specified in the Pod's ControllerRef will actually manage it.\n// Returns an error only if no matching ReplicationControllers are found.\nfunc (s *replicationControllerLister) GetPodControllers(pod *v1.Pod) ([]*v1.ReplicationController, error) {\n\tif len(pod.Labels) == 0 {\n\t\treturn nil, fmt.Errorf(\"no controllers found for pod %v because it has no labels\", pod.Name)\n\t}\n\n\titems, err := s.ReplicationControllers(pod.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar controllers []*v1.ReplicationController\n\tfor i := range items {\n\t\trc := items[i]\n\t\tselector := labels.Set(rc.Spec.Selector).AsSelectorPreValidated()\n\n\t\t// If an rc with a nil or empty selector creeps in, it should match nothing, not everything.\n\t\tif selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) {\n\t\t\tcontinue\n\t\t}\n\t\tcontrollers = append(controllers, rc)\n\t}\n\n\tif len(controllers) == 0 {\n\t\treturn nil, fmt.Errorf(\"could not find controller for pod %s in namespace %s with labels: %v\", pod.Name, pod.Namespace, pod.Labels)\n\t}\n\n\treturn controllers, nil\n}","line":{"from":36,"to":66}} {"id":100027860,"name":"NewResourceQuotaLister","signature":"func NewResourceQuotaLister(indexer cache.Indexer) ResourceQuotaLister","file":"staging/src/k8s.io/client-go/listers/core/v1/resourcequota.go","code":"// NewResourceQuotaLister returns a new ResourceQuotaLister.\nfunc NewResourceQuotaLister(indexer cache.Indexer) ResourceQuotaLister {\n\treturn \u0026resourceQuotaLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027861,"name":"List","signature":"func (s *resourceQuotaLister) List(selector labels.Selector) (ret []*v1.ResourceQuota, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/resourcequota.go","code":"// List lists all ResourceQuotas in the indexer.\nfunc (s *resourceQuotaLister) List(selector labels.Selector) (ret []*v1.ResourceQuota, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.ResourceQuota))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027862,"name":"ResourceQuotas","signature":"func (s *resourceQuotaLister) ResourceQuotas(namespace string) ResourceQuotaNamespaceLister","file":"staging/src/k8s.io/client-go/listers/core/v1/resourcequota.go","code":"// ResourceQuotas returns an object that can list and get ResourceQuotas.\nfunc (s *resourceQuotaLister) ResourceQuotas(namespace string) ResourceQuotaNamespaceLister {\n\treturn resourceQuotaNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027863,"name":"List","signature":"func (s resourceQuotaNamespaceLister) List(selector labels.Selector) (ret []*v1.ResourceQuota, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/resourcequota.go","code":"// List lists all ResourceQuotas in the indexer for a given namespace.\nfunc (s resourceQuotaNamespaceLister) List(selector labels.Selector) (ret []*v1.ResourceQuota, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.ResourceQuota))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027864,"name":"Get","signature":"func (s resourceQuotaNamespaceLister) Get(name string) (*v1.ResourceQuota, error)","file":"staging/src/k8s.io/client-go/listers/core/v1/resourcequota.go","code":"// Get retrieves the ResourceQuota from the indexer for a given namespace and name.\nfunc (s resourceQuotaNamespaceLister) Get(name string) (*v1.ResourceQuota, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"resourcequota\"), name)\n\t}\n\treturn obj.(*v1.ResourceQuota), nil\n}","line":{"from":89,"to":99}} {"id":100027865,"name":"NewSecretLister","signature":"func NewSecretLister(indexer cache.Indexer) SecretLister","file":"staging/src/k8s.io/client-go/listers/core/v1/secret.go","code":"// NewSecretLister returns a new SecretLister.\nfunc NewSecretLister(indexer cache.Indexer) SecretLister {\n\treturn \u0026secretLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027866,"name":"List","signature":"func (s *secretLister) List(selector labels.Selector) (ret []*v1.Secret, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/secret.go","code":"// List lists all Secrets in the indexer.\nfunc (s *secretLister) List(selector labels.Selector) (ret []*v1.Secret, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Secret))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027867,"name":"Secrets","signature":"func (s *secretLister) Secrets(namespace string) SecretNamespaceLister","file":"staging/src/k8s.io/client-go/listers/core/v1/secret.go","code":"// Secrets returns an object that can list and get Secrets.\nfunc (s *secretLister) Secrets(namespace string) SecretNamespaceLister {\n\treturn secretNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027868,"name":"List","signature":"func (s secretNamespaceLister) List(selector labels.Selector) (ret []*v1.Secret, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/secret.go","code":"// List lists all Secrets in the indexer for a given namespace.\nfunc (s secretNamespaceLister) List(selector labels.Selector) (ret []*v1.Secret, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Secret))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027869,"name":"Get","signature":"func (s secretNamespaceLister) Get(name string) (*v1.Secret, error)","file":"staging/src/k8s.io/client-go/listers/core/v1/secret.go","code":"// Get retrieves the Secret from the indexer for a given namespace and name.\nfunc (s secretNamespaceLister) Get(name string) (*v1.Secret, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"secret\"), name)\n\t}\n\treturn obj.(*v1.Secret), nil\n}","line":{"from":89,"to":99}} {"id":100027870,"name":"NewServiceLister","signature":"func NewServiceLister(indexer cache.Indexer) ServiceLister","file":"staging/src/k8s.io/client-go/listers/core/v1/service.go","code":"// NewServiceLister returns a new ServiceLister.\nfunc NewServiceLister(indexer cache.Indexer) ServiceLister {\n\treturn \u0026serviceLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027871,"name":"List","signature":"func (s *serviceLister) List(selector labels.Selector) (ret []*v1.Service, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/service.go","code":"// List lists all Services in the indexer.\nfunc (s *serviceLister) List(selector labels.Selector) (ret []*v1.Service, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Service))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027872,"name":"Services","signature":"func (s *serviceLister) Services(namespace string) ServiceNamespaceLister","file":"staging/src/k8s.io/client-go/listers/core/v1/service.go","code":"// Services returns an object that can list and get Services.\nfunc (s *serviceLister) Services(namespace string) ServiceNamespaceLister {\n\treturn serviceNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027873,"name":"List","signature":"func (s serviceNamespaceLister) List(selector labels.Selector) (ret []*v1.Service, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/service.go","code":"// List lists all Services in the indexer for a given namespace.\nfunc (s serviceNamespaceLister) List(selector labels.Selector) (ret []*v1.Service, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Service))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027874,"name":"Get","signature":"func (s serviceNamespaceLister) Get(name string) (*v1.Service, error)","file":"staging/src/k8s.io/client-go/listers/core/v1/service.go","code":"// Get retrieves the Service from the indexer for a given namespace and name.\nfunc (s serviceNamespaceLister) Get(name string) (*v1.Service, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"service\"), name)\n\t}\n\treturn obj.(*v1.Service), nil\n}","line":{"from":89,"to":99}} {"id":100027875,"name":"NewServiceAccountLister","signature":"func NewServiceAccountLister(indexer cache.Indexer) ServiceAccountLister","file":"staging/src/k8s.io/client-go/listers/core/v1/serviceaccount.go","code":"// NewServiceAccountLister returns a new ServiceAccountLister.\nfunc NewServiceAccountLister(indexer cache.Indexer) ServiceAccountLister {\n\treturn \u0026serviceAccountLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027876,"name":"List","signature":"func (s *serviceAccountLister) List(selector labels.Selector) (ret []*v1.ServiceAccount, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/serviceaccount.go","code":"// List lists all ServiceAccounts in the indexer.\nfunc (s *serviceAccountLister) List(selector labels.Selector) (ret []*v1.ServiceAccount, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.ServiceAccount))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027877,"name":"ServiceAccounts","signature":"func (s *serviceAccountLister) ServiceAccounts(namespace string) ServiceAccountNamespaceLister","file":"staging/src/k8s.io/client-go/listers/core/v1/serviceaccount.go","code":"// ServiceAccounts returns an object that can list and get ServiceAccounts.\nfunc (s *serviceAccountLister) ServiceAccounts(namespace string) ServiceAccountNamespaceLister {\n\treturn serviceAccountNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027878,"name":"List","signature":"func (s serviceAccountNamespaceLister) List(selector labels.Selector) (ret []*v1.ServiceAccount, err error)","file":"staging/src/k8s.io/client-go/listers/core/v1/serviceaccount.go","code":"// List lists all ServiceAccounts in the indexer for a given namespace.\nfunc (s serviceAccountNamespaceLister) List(selector labels.Selector) (ret []*v1.ServiceAccount, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.ServiceAccount))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027879,"name":"Get","signature":"func (s serviceAccountNamespaceLister) Get(name string) (*v1.ServiceAccount, error)","file":"staging/src/k8s.io/client-go/listers/core/v1/serviceaccount.go","code":"// Get retrieves the ServiceAccount from the indexer for a given namespace and name.\nfunc (s serviceAccountNamespaceLister) Get(name string) (*v1.ServiceAccount, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"serviceaccount\"), name)\n\t}\n\treturn obj.(*v1.ServiceAccount), nil\n}","line":{"from":89,"to":99}} {"id":100027880,"name":"NewEndpointSliceLister","signature":"func NewEndpointSliceLister(indexer cache.Indexer) EndpointSliceLister","file":"staging/src/k8s.io/client-go/listers/discovery/v1/endpointslice.go","code":"// NewEndpointSliceLister returns a new EndpointSliceLister.\nfunc NewEndpointSliceLister(indexer cache.Indexer) EndpointSliceLister {\n\treturn \u0026endpointSliceLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027881,"name":"List","signature":"func (s *endpointSliceLister) List(selector labels.Selector) (ret []*v1.EndpointSlice, err error)","file":"staging/src/k8s.io/client-go/listers/discovery/v1/endpointslice.go","code":"// List lists all EndpointSlices in the indexer.\nfunc (s *endpointSliceLister) List(selector labels.Selector) (ret []*v1.EndpointSlice, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.EndpointSlice))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027882,"name":"EndpointSlices","signature":"func (s *endpointSliceLister) EndpointSlices(namespace string) EndpointSliceNamespaceLister","file":"staging/src/k8s.io/client-go/listers/discovery/v1/endpointslice.go","code":"// EndpointSlices returns an object that can list and get EndpointSlices.\nfunc (s *endpointSliceLister) EndpointSlices(namespace string) EndpointSliceNamespaceLister {\n\treturn endpointSliceNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027883,"name":"List","signature":"func (s endpointSliceNamespaceLister) List(selector labels.Selector) (ret []*v1.EndpointSlice, err error)","file":"staging/src/k8s.io/client-go/listers/discovery/v1/endpointslice.go","code":"// List lists all EndpointSlices in the indexer for a given namespace.\nfunc (s endpointSliceNamespaceLister) List(selector labels.Selector) (ret []*v1.EndpointSlice, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.EndpointSlice))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027884,"name":"Get","signature":"func (s endpointSliceNamespaceLister) Get(name string) (*v1.EndpointSlice, error)","file":"staging/src/k8s.io/client-go/listers/discovery/v1/endpointslice.go","code":"// Get retrieves the EndpointSlice from the indexer for a given namespace and name.\nfunc (s endpointSliceNamespaceLister) Get(name string) (*v1.EndpointSlice, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"endpointslice\"), name)\n\t}\n\treturn obj.(*v1.EndpointSlice), nil\n}","line":{"from":89,"to":99}} {"id":100027885,"name":"NewEndpointSliceLister","signature":"func NewEndpointSliceLister(indexer cache.Indexer) EndpointSliceLister","file":"staging/src/k8s.io/client-go/listers/discovery/v1beta1/endpointslice.go","code":"// NewEndpointSliceLister returns a new EndpointSliceLister.\nfunc NewEndpointSliceLister(indexer cache.Indexer) EndpointSliceLister {\n\treturn \u0026endpointSliceLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027886,"name":"List","signature":"func (s *endpointSliceLister) List(selector labels.Selector) (ret []*v1beta1.EndpointSlice, err error)","file":"staging/src/k8s.io/client-go/listers/discovery/v1beta1/endpointslice.go","code":"// List lists all EndpointSlices in the indexer.\nfunc (s *endpointSliceLister) List(selector labels.Selector) (ret []*v1beta1.EndpointSlice, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.EndpointSlice))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027887,"name":"EndpointSlices","signature":"func (s *endpointSliceLister) EndpointSlices(namespace string) EndpointSliceNamespaceLister","file":"staging/src/k8s.io/client-go/listers/discovery/v1beta1/endpointslice.go","code":"// EndpointSlices returns an object that can list and get EndpointSlices.\nfunc (s *endpointSliceLister) EndpointSlices(namespace string) EndpointSliceNamespaceLister {\n\treturn endpointSliceNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027888,"name":"List","signature":"func (s endpointSliceNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.EndpointSlice, err error)","file":"staging/src/k8s.io/client-go/listers/discovery/v1beta1/endpointslice.go","code":"// List lists all EndpointSlices in the indexer for a given namespace.\nfunc (s endpointSliceNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.EndpointSlice, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.EndpointSlice))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027889,"name":"Get","signature":"func (s endpointSliceNamespaceLister) Get(name string) (*v1beta1.EndpointSlice, error)","file":"staging/src/k8s.io/client-go/listers/discovery/v1beta1/endpointslice.go","code":"// Get retrieves the EndpointSlice from the indexer for a given namespace and name.\nfunc (s endpointSliceNamespaceLister) Get(name string) (*v1beta1.EndpointSlice, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"endpointslice\"), name)\n\t}\n\treturn obj.(*v1beta1.EndpointSlice), nil\n}","line":{"from":89,"to":99}} {"id":100027890,"name":"NewEventLister","signature":"func NewEventLister(indexer cache.Indexer) EventLister","file":"staging/src/k8s.io/client-go/listers/events/v1/event.go","code":"// NewEventLister returns a new EventLister.\nfunc NewEventLister(indexer cache.Indexer) EventLister {\n\treturn \u0026eventLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027891,"name":"List","signature":"func (s *eventLister) List(selector labels.Selector) (ret []*v1.Event, err error)","file":"staging/src/k8s.io/client-go/listers/events/v1/event.go","code":"// List lists all Events in the indexer.\nfunc (s *eventLister) List(selector labels.Selector) (ret []*v1.Event, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Event))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027892,"name":"Events","signature":"func (s *eventLister) Events(namespace string) EventNamespaceLister","file":"staging/src/k8s.io/client-go/listers/events/v1/event.go","code":"// Events returns an object that can list and get Events.\nfunc (s *eventLister) Events(namespace string) EventNamespaceLister {\n\treturn eventNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027893,"name":"List","signature":"func (s eventNamespaceLister) List(selector labels.Selector) (ret []*v1.Event, err error)","file":"staging/src/k8s.io/client-go/listers/events/v1/event.go","code":"// List lists all Events in the indexer for a given namespace.\nfunc (s eventNamespaceLister) List(selector labels.Selector) (ret []*v1.Event, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Event))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027894,"name":"Get","signature":"func (s eventNamespaceLister) Get(name string) (*v1.Event, error)","file":"staging/src/k8s.io/client-go/listers/events/v1/event.go","code":"// Get retrieves the Event from the indexer for a given namespace and name.\nfunc (s eventNamespaceLister) Get(name string) (*v1.Event, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"event\"), name)\n\t}\n\treturn obj.(*v1.Event), nil\n}","line":{"from":89,"to":99}} {"id":100027895,"name":"NewEventLister","signature":"func NewEventLister(indexer cache.Indexer) EventLister","file":"staging/src/k8s.io/client-go/listers/events/v1beta1/event.go","code":"// NewEventLister returns a new EventLister.\nfunc NewEventLister(indexer cache.Indexer) EventLister {\n\treturn \u0026eventLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027896,"name":"List","signature":"func (s *eventLister) List(selector labels.Selector) (ret []*v1beta1.Event, err error)","file":"staging/src/k8s.io/client-go/listers/events/v1beta1/event.go","code":"// List lists all Events in the indexer.\nfunc (s *eventLister) List(selector labels.Selector) (ret []*v1beta1.Event, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.Event))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027897,"name":"Events","signature":"func (s *eventLister) Events(namespace string) EventNamespaceLister","file":"staging/src/k8s.io/client-go/listers/events/v1beta1/event.go","code":"// Events returns an object that can list and get Events.\nfunc (s *eventLister) Events(namespace string) EventNamespaceLister {\n\treturn eventNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027898,"name":"List","signature":"func (s eventNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.Event, err error)","file":"staging/src/k8s.io/client-go/listers/events/v1beta1/event.go","code":"// List lists all Events in the indexer for a given namespace.\nfunc (s eventNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.Event, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.Event))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027899,"name":"Get","signature":"func (s eventNamespaceLister) Get(name string) (*v1beta1.Event, error)","file":"staging/src/k8s.io/client-go/listers/events/v1beta1/event.go","code":"// Get retrieves the Event from the indexer for a given namespace and name.\nfunc (s eventNamespaceLister) Get(name string) (*v1beta1.Event, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"event\"), name)\n\t}\n\treturn obj.(*v1beta1.Event), nil\n}","line":{"from":89,"to":99}} {"id":100027900,"name":"NewDaemonSetLister","signature":"func NewDaemonSetLister(indexer cache.Indexer) DaemonSetLister","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/daemonset.go","code":"// NewDaemonSetLister returns a new DaemonSetLister.\nfunc NewDaemonSetLister(indexer cache.Indexer) DaemonSetLister {\n\treturn \u0026daemonSetLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027901,"name":"List","signature":"func (s *daemonSetLister) List(selector labels.Selector) (ret []*v1beta1.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/daemonset.go","code":"// List lists all DaemonSets in the indexer.\nfunc (s *daemonSetLister) List(selector labels.Selector) (ret []*v1beta1.DaemonSet, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.DaemonSet))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027902,"name":"DaemonSets","signature":"func (s *daemonSetLister) DaemonSets(namespace string) DaemonSetNamespaceLister","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/daemonset.go","code":"// DaemonSets returns an object that can list and get DaemonSets.\nfunc (s *daemonSetLister) DaemonSets(namespace string) DaemonSetNamespaceLister {\n\treturn daemonSetNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027903,"name":"List","signature":"func (s daemonSetNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.DaemonSet, err error)","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/daemonset.go","code":"// List lists all DaemonSets in the indexer for a given namespace.\nfunc (s daemonSetNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.DaemonSet, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.DaemonSet))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027904,"name":"Get","signature":"func (s daemonSetNamespaceLister) Get(name string) (*v1beta1.DaemonSet, error)","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/daemonset.go","code":"// Get retrieves the DaemonSet from the indexer for a given namespace and name.\nfunc (s daemonSetNamespaceLister) Get(name string) (*v1beta1.DaemonSet, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"daemonset\"), name)\n\t}\n\treturn obj.(*v1beta1.DaemonSet), nil\n}","line":{"from":89,"to":99}} {"id":100027905,"name":"GetPodDaemonSets","signature":"func (s *daemonSetLister) GetPodDaemonSets(pod *v1.Pod) ([]*v1beta1.DaemonSet, error)","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/daemonset_expansion.go","code":"// GetPodDaemonSets returns a list of DaemonSets that potentially match a pod.\n// Only the one specified in the Pod's ControllerRef will actually manage it.\n// Returns an error only if no matching DaemonSets are found.\nfunc (s *daemonSetLister) GetPodDaemonSets(pod *v1.Pod) ([]*v1beta1.DaemonSet, error) {\n\tvar selector labels.Selector\n\tvar daemonSet *v1beta1.DaemonSet\n\n\tif len(pod.Labels) == 0 {\n\t\treturn nil, fmt.Errorf(\"no daemon sets found for pod %v because it has no labels\", pod.Name)\n\t}\n\n\tlist, err := s.DaemonSets(pod.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar daemonSets []*v1beta1.DaemonSet\n\tfor i := range list {\n\t\tdaemonSet = list[i]\n\t\tif daemonSet.Namespace != pod.Namespace {\n\t\t\tcontinue\n\t\t}\n\t\tselector, err = metav1.LabelSelectorAsSelector(daemonSet.Spec.Selector)\n\t\tif err != nil {\n\t\t\t// This object has an invalid selector, it does not match the pod\n\t\t\tcontinue\n\t\t}\n\n\t\t// If a daemonSet with a nil or empty selector creeps in, it should match nothing, not everything.\n\t\tif selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) {\n\t\t\tcontinue\n\t\t}\n\t\tdaemonSets = append(daemonSets, daemonSet)\n\t}\n\n\tif len(daemonSets) == 0 {\n\t\treturn nil, fmt.Errorf(\"could not find daemon set for pod %s in namespace %s with labels: %v\", pod.Name, pod.Namespace, pod.Labels)\n\t}\n\n\treturn daemonSets, nil\n}","line":{"from":40,"to":80}} {"id":100027906,"name":"GetHistoryDaemonSets","signature":"func (s *daemonSetLister) GetHistoryDaemonSets(history *apps.ControllerRevision) ([]*v1beta1.DaemonSet, error)","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/daemonset_expansion.go","code":"// GetHistoryDaemonSets returns a list of DaemonSets that potentially\n// match a ControllerRevision. Only the one specified in the ControllerRevision's ControllerRef\n// will actually manage it.\n// Returns an error only if no matching DaemonSets are found.\nfunc (s *daemonSetLister) GetHistoryDaemonSets(history *apps.ControllerRevision) ([]*v1beta1.DaemonSet, error) {\n\tif len(history.Labels) == 0 {\n\t\treturn nil, fmt.Errorf(\"no DaemonSet found for ControllerRevision %s because it has no labels\", history.Name)\n\t}\n\n\tlist, err := s.DaemonSets(history.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar daemonSets []*v1beta1.DaemonSet\n\tfor _, ds := range list {\n\t\tselector, err := metav1.LabelSelectorAsSelector(ds.Spec.Selector)\n\t\tif err != nil {\n\t\t\t// This object has an invalid selector, it does not match the history object\n\t\t\tcontinue\n\t\t}\n\t\t// If a DaemonSet with a nil or empty selector creeps in, it should match nothing, not everything.\n\t\tif selector.Empty() || !selector.Matches(labels.Set(history.Labels)) {\n\t\t\tcontinue\n\t\t}\n\t\tdaemonSets = append(daemonSets, ds)\n\t}\n\n\tif len(daemonSets) == 0 {\n\t\treturn nil, fmt.Errorf(\"could not find DaemonSets for ControllerRevision %s in namespace %s with labels: %v\", history.Name, history.Namespace, history.Labels)\n\t}\n\n\treturn daemonSets, nil\n}","line":{"from":82,"to":115}} {"id":100027907,"name":"NewDeploymentLister","signature":"func NewDeploymentLister(indexer cache.Indexer) DeploymentLister","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/deployment.go","code":"// NewDeploymentLister returns a new DeploymentLister.\nfunc NewDeploymentLister(indexer cache.Indexer) DeploymentLister {\n\treturn \u0026deploymentLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027908,"name":"List","signature":"func (s *deploymentLister) List(selector labels.Selector) (ret []*v1beta1.Deployment, err error)","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/deployment.go","code":"// List lists all Deployments in the indexer.\nfunc (s *deploymentLister) List(selector labels.Selector) (ret []*v1beta1.Deployment, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.Deployment))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027909,"name":"Deployments","signature":"func (s *deploymentLister) Deployments(namespace string) DeploymentNamespaceLister","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/deployment.go","code":"// Deployments returns an object that can list and get Deployments.\nfunc (s *deploymentLister) Deployments(namespace string) DeploymentNamespaceLister {\n\treturn deploymentNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027910,"name":"List","signature":"func (s deploymentNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.Deployment, err error)","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/deployment.go","code":"// List lists all Deployments in the indexer for a given namespace.\nfunc (s deploymentNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.Deployment, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.Deployment))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027911,"name":"Get","signature":"func (s deploymentNamespaceLister) Get(name string) (*v1beta1.Deployment, error)","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/deployment.go","code":"// Get retrieves the Deployment from the indexer for a given namespace and name.\nfunc (s deploymentNamespaceLister) Get(name string) (*v1beta1.Deployment, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"deployment\"), name)\n\t}\n\treturn obj.(*v1beta1.Deployment), nil\n}","line":{"from":89,"to":99}} {"id":100027912,"name":"NewIngressLister","signature":"func NewIngressLister(indexer cache.Indexer) IngressLister","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/ingress.go","code":"// NewIngressLister returns a new IngressLister.\nfunc NewIngressLister(indexer cache.Indexer) IngressLister {\n\treturn \u0026ingressLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027913,"name":"List","signature":"func (s *ingressLister) List(selector labels.Selector) (ret []*v1beta1.Ingress, err error)","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/ingress.go","code":"// List lists all Ingresses in the indexer.\nfunc (s *ingressLister) List(selector labels.Selector) (ret []*v1beta1.Ingress, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.Ingress))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027914,"name":"Ingresses","signature":"func (s *ingressLister) Ingresses(namespace string) IngressNamespaceLister","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/ingress.go","code":"// Ingresses returns an object that can list and get Ingresses.\nfunc (s *ingressLister) Ingresses(namespace string) IngressNamespaceLister {\n\treturn ingressNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027915,"name":"List","signature":"func (s ingressNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.Ingress, err error)","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/ingress.go","code":"// List lists all Ingresses in the indexer for a given namespace.\nfunc (s ingressNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.Ingress, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.Ingress))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027916,"name":"Get","signature":"func (s ingressNamespaceLister) Get(name string) (*v1beta1.Ingress, error)","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/ingress.go","code":"// Get retrieves the Ingress from the indexer for a given namespace and name.\nfunc (s ingressNamespaceLister) Get(name string) (*v1beta1.Ingress, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"ingress\"), name)\n\t}\n\treturn obj.(*v1beta1.Ingress), nil\n}","line":{"from":89,"to":99}} {"id":100027917,"name":"NewNetworkPolicyLister","signature":"func NewNetworkPolicyLister(indexer cache.Indexer) NetworkPolicyLister","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/networkpolicy.go","code":"// NewNetworkPolicyLister returns a new NetworkPolicyLister.\nfunc NewNetworkPolicyLister(indexer cache.Indexer) NetworkPolicyLister {\n\treturn \u0026networkPolicyLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027918,"name":"List","signature":"func (s *networkPolicyLister) List(selector labels.Selector) (ret []*v1beta1.NetworkPolicy, err error)","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/networkpolicy.go","code":"// List lists all NetworkPolicies in the indexer.\nfunc (s *networkPolicyLister) List(selector labels.Selector) (ret []*v1beta1.NetworkPolicy, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.NetworkPolicy))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027919,"name":"NetworkPolicies","signature":"func (s *networkPolicyLister) NetworkPolicies(namespace string) NetworkPolicyNamespaceLister","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/networkpolicy.go","code":"// NetworkPolicies returns an object that can list and get NetworkPolicies.\nfunc (s *networkPolicyLister) NetworkPolicies(namespace string) NetworkPolicyNamespaceLister {\n\treturn networkPolicyNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027920,"name":"List","signature":"func (s networkPolicyNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.NetworkPolicy, err error)","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/networkpolicy.go","code":"// List lists all NetworkPolicies in the indexer for a given namespace.\nfunc (s networkPolicyNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.NetworkPolicy, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.NetworkPolicy))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027921,"name":"Get","signature":"func (s networkPolicyNamespaceLister) Get(name string) (*v1beta1.NetworkPolicy, error)","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/networkpolicy.go","code":"// Get retrieves the NetworkPolicy from the indexer for a given namespace and name.\nfunc (s networkPolicyNamespaceLister) Get(name string) (*v1beta1.NetworkPolicy, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"networkpolicy\"), name)\n\t}\n\treturn obj.(*v1beta1.NetworkPolicy), nil\n}","line":{"from":89,"to":99}} {"id":100027922,"name":"NewReplicaSetLister","signature":"func NewReplicaSetLister(indexer cache.Indexer) ReplicaSetLister","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/replicaset.go","code":"// NewReplicaSetLister returns a new ReplicaSetLister.\nfunc NewReplicaSetLister(indexer cache.Indexer) ReplicaSetLister {\n\treturn \u0026replicaSetLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027923,"name":"List","signature":"func (s *replicaSetLister) List(selector labels.Selector) (ret []*v1beta1.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/replicaset.go","code":"// List lists all ReplicaSets in the indexer.\nfunc (s *replicaSetLister) List(selector labels.Selector) (ret []*v1beta1.ReplicaSet, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.ReplicaSet))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027924,"name":"ReplicaSets","signature":"func (s *replicaSetLister) ReplicaSets(namespace string) ReplicaSetNamespaceLister","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/replicaset.go","code":"// ReplicaSets returns an object that can list and get ReplicaSets.\nfunc (s *replicaSetLister) ReplicaSets(namespace string) ReplicaSetNamespaceLister {\n\treturn replicaSetNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027925,"name":"List","signature":"func (s replicaSetNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.ReplicaSet, err error)","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/replicaset.go","code":"// List lists all ReplicaSets in the indexer for a given namespace.\nfunc (s replicaSetNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.ReplicaSet, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.ReplicaSet))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027926,"name":"Get","signature":"func (s replicaSetNamespaceLister) Get(name string) (*v1beta1.ReplicaSet, error)","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/replicaset.go","code":"// Get retrieves the ReplicaSet from the indexer for a given namespace and name.\nfunc (s replicaSetNamespaceLister) Get(name string) (*v1beta1.ReplicaSet, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"replicaset\"), name)\n\t}\n\treturn obj.(*v1beta1.ReplicaSet), nil\n}","line":{"from":89,"to":99}} {"id":100027927,"name":"GetPodReplicaSets","signature":"func (s *replicaSetLister) GetPodReplicaSets(pod *v1.Pod) ([]*extensions.ReplicaSet, error)","file":"staging/src/k8s.io/client-go/listers/extensions/v1beta1/replicaset_expansion.go","code":"// GetPodReplicaSets returns a list of ReplicaSets that potentially match a pod.\n// Only the one specified in the Pod's ControllerRef will actually manage it.\n// Returns an error only if no matching ReplicaSets are found.\nfunc (s *replicaSetLister) GetPodReplicaSets(pod *v1.Pod) ([]*extensions.ReplicaSet, error) {\n\tif len(pod.Labels) == 0 {\n\t\treturn nil, fmt.Errorf(\"no ReplicaSets found for pod %v because it has no labels\", pod.Name)\n\t}\n\n\tlist, err := s.ReplicaSets(pod.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar rss []*extensions.ReplicaSet\n\tfor _, rs := range list {\n\t\tif rs.Namespace != pod.Namespace {\n\t\t\tcontinue\n\t\t}\n\t\tselector, err := metav1.LabelSelectorAsSelector(rs.Spec.Selector)\n\t\tif err != nil {\n\t\t\t// This object has an invalid selector, it does not match the pod\n\t\t\tcontinue\n\t\t}\n\n\t\t// If a ReplicaSet with a nil or empty selector creeps in, it should match nothing, not everything.\n\t\tif selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) {\n\t\t\tcontinue\n\t\t}\n\t\trss = append(rss, rs)\n\t}\n\n\tif len(rss) == 0 {\n\t\treturn nil, fmt.Errorf(\"could not find ReplicaSet for pod %s in namespace %s with labels: %v\", pod.Name, pod.Namespace, pod.Labels)\n\t}\n\n\treturn rss, nil\n}","line":{"from":38,"to":74}} {"id":100027928,"name":"NewFlowSchemaLister","signature":"func NewFlowSchemaLister(indexer cache.Indexer) FlowSchemaLister","file":"staging/src/k8s.io/client-go/listers/flowcontrol/v1alpha1/flowschema.go","code":"// NewFlowSchemaLister returns a new FlowSchemaLister.\nfunc NewFlowSchemaLister(indexer cache.Indexer) FlowSchemaLister {\n\treturn \u0026flowSchemaLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027929,"name":"List","signature":"func (s *flowSchemaLister) List(selector labels.Selector) (ret []*v1alpha1.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/listers/flowcontrol/v1alpha1/flowschema.go","code":"// List lists all FlowSchemas in the indexer.\nfunc (s *flowSchemaLister) List(selector labels.Selector) (ret []*v1alpha1.FlowSchema, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.FlowSchema))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027930,"name":"Get","signature":"func (s *flowSchemaLister) Get(name string) (*v1alpha1.FlowSchema, error)","file":"staging/src/k8s.io/client-go/listers/flowcontrol/v1alpha1/flowschema.go","code":"// Get retrieves the FlowSchema from the index for a given name.\nfunc (s *flowSchemaLister) Get(name string) (*v1alpha1.FlowSchema, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"flowschema\"), name)\n\t}\n\treturn obj.(*v1alpha1.FlowSchema), nil\n}","line":{"from":58,"to":68}} {"id":100027931,"name":"NewPriorityLevelConfigurationLister","signature":"func NewPriorityLevelConfigurationLister(indexer cache.Indexer) PriorityLevelConfigurationLister","file":"staging/src/k8s.io/client-go/listers/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// NewPriorityLevelConfigurationLister returns a new PriorityLevelConfigurationLister.\nfunc NewPriorityLevelConfigurationLister(indexer cache.Indexer) PriorityLevelConfigurationLister {\n\treturn \u0026priorityLevelConfigurationLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027932,"name":"List","signature":"func (s *priorityLevelConfigurationLister) List(selector labels.Selector) (ret []*v1alpha1.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/listers/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// List lists all PriorityLevelConfigurations in the indexer.\nfunc (s *priorityLevelConfigurationLister) List(selector labels.Selector) (ret []*v1alpha1.PriorityLevelConfiguration, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.PriorityLevelConfiguration))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027933,"name":"Get","signature":"func (s *priorityLevelConfigurationLister) Get(name string) (*v1alpha1.PriorityLevelConfiguration, error)","file":"staging/src/k8s.io/client-go/listers/flowcontrol/v1alpha1/prioritylevelconfiguration.go","code":"// Get retrieves the PriorityLevelConfiguration from the index for a given name.\nfunc (s *priorityLevelConfigurationLister) Get(name string) (*v1alpha1.PriorityLevelConfiguration, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"prioritylevelconfiguration\"), name)\n\t}\n\treturn obj.(*v1alpha1.PriorityLevelConfiguration), nil\n}","line":{"from":58,"to":68}} {"id":100027934,"name":"NewFlowSchemaLister","signature":"func NewFlowSchemaLister(indexer cache.Indexer) FlowSchemaLister","file":"staging/src/k8s.io/client-go/listers/flowcontrol/v1beta1/flowschema.go","code":"// NewFlowSchemaLister returns a new FlowSchemaLister.\nfunc NewFlowSchemaLister(indexer cache.Indexer) FlowSchemaLister {\n\treturn \u0026flowSchemaLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027935,"name":"List","signature":"func (s *flowSchemaLister) List(selector labels.Selector) (ret []*v1beta1.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/listers/flowcontrol/v1beta1/flowschema.go","code":"// List lists all FlowSchemas in the indexer.\nfunc (s *flowSchemaLister) List(selector labels.Selector) (ret []*v1beta1.FlowSchema, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.FlowSchema))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027936,"name":"Get","signature":"func (s *flowSchemaLister) Get(name string) (*v1beta1.FlowSchema, error)","file":"staging/src/k8s.io/client-go/listers/flowcontrol/v1beta1/flowschema.go","code":"// Get retrieves the FlowSchema from the index for a given name.\nfunc (s *flowSchemaLister) Get(name string) (*v1beta1.FlowSchema, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"flowschema\"), name)\n\t}\n\treturn obj.(*v1beta1.FlowSchema), nil\n}","line":{"from":58,"to":68}} {"id":100027937,"name":"NewPriorityLevelConfigurationLister","signature":"func NewPriorityLevelConfigurationLister(indexer cache.Indexer) PriorityLevelConfigurationLister","file":"staging/src/k8s.io/client-go/listers/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// NewPriorityLevelConfigurationLister returns a new PriorityLevelConfigurationLister.\nfunc NewPriorityLevelConfigurationLister(indexer cache.Indexer) PriorityLevelConfigurationLister {\n\treturn \u0026priorityLevelConfigurationLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027938,"name":"List","signature":"func (s *priorityLevelConfigurationLister) List(selector labels.Selector) (ret []*v1beta1.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/listers/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// List lists all PriorityLevelConfigurations in the indexer.\nfunc (s *priorityLevelConfigurationLister) List(selector labels.Selector) (ret []*v1beta1.PriorityLevelConfiguration, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.PriorityLevelConfiguration))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027939,"name":"Get","signature":"func (s *priorityLevelConfigurationLister) Get(name string) (*v1beta1.PriorityLevelConfiguration, error)","file":"staging/src/k8s.io/client-go/listers/flowcontrol/v1beta1/prioritylevelconfiguration.go","code":"// Get retrieves the PriorityLevelConfiguration from the index for a given name.\nfunc (s *priorityLevelConfigurationLister) Get(name string) (*v1beta1.PriorityLevelConfiguration, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"prioritylevelconfiguration\"), name)\n\t}\n\treturn obj.(*v1beta1.PriorityLevelConfiguration), nil\n}","line":{"from":58,"to":68}} {"id":100027940,"name":"NewFlowSchemaLister","signature":"func NewFlowSchemaLister(indexer cache.Indexer) FlowSchemaLister","file":"staging/src/k8s.io/client-go/listers/flowcontrol/v1beta2/flowschema.go","code":"// NewFlowSchemaLister returns a new FlowSchemaLister.\nfunc NewFlowSchemaLister(indexer cache.Indexer) FlowSchemaLister {\n\treturn \u0026flowSchemaLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027941,"name":"List","signature":"func (s *flowSchemaLister) List(selector labels.Selector) (ret []*v1beta2.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/listers/flowcontrol/v1beta2/flowschema.go","code":"// List lists all FlowSchemas in the indexer.\nfunc (s *flowSchemaLister) List(selector labels.Selector) (ret []*v1beta2.FlowSchema, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta2.FlowSchema))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027942,"name":"Get","signature":"func (s *flowSchemaLister) Get(name string) (*v1beta2.FlowSchema, error)","file":"staging/src/k8s.io/client-go/listers/flowcontrol/v1beta2/flowschema.go","code":"// Get retrieves the FlowSchema from the index for a given name.\nfunc (s *flowSchemaLister) Get(name string) (*v1beta2.FlowSchema, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta2.Resource(\"flowschema\"), name)\n\t}\n\treturn obj.(*v1beta2.FlowSchema), nil\n}","line":{"from":58,"to":68}} {"id":100027943,"name":"NewPriorityLevelConfigurationLister","signature":"func NewPriorityLevelConfigurationLister(indexer cache.Indexer) PriorityLevelConfigurationLister","file":"staging/src/k8s.io/client-go/listers/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// NewPriorityLevelConfigurationLister returns a new PriorityLevelConfigurationLister.\nfunc NewPriorityLevelConfigurationLister(indexer cache.Indexer) PriorityLevelConfigurationLister {\n\treturn \u0026priorityLevelConfigurationLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027944,"name":"List","signature":"func (s *priorityLevelConfigurationLister) List(selector labels.Selector) (ret []*v1beta2.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/listers/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// List lists all PriorityLevelConfigurations in the indexer.\nfunc (s *priorityLevelConfigurationLister) List(selector labels.Selector) (ret []*v1beta2.PriorityLevelConfiguration, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta2.PriorityLevelConfiguration))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027945,"name":"Get","signature":"func (s *priorityLevelConfigurationLister) Get(name string) (*v1beta2.PriorityLevelConfiguration, error)","file":"staging/src/k8s.io/client-go/listers/flowcontrol/v1beta2/prioritylevelconfiguration.go","code":"// Get retrieves the PriorityLevelConfiguration from the index for a given name.\nfunc (s *priorityLevelConfigurationLister) Get(name string) (*v1beta2.PriorityLevelConfiguration, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta2.Resource(\"prioritylevelconfiguration\"), name)\n\t}\n\treturn obj.(*v1beta2.PriorityLevelConfiguration), nil\n}","line":{"from":58,"to":68}} {"id":100027946,"name":"NewFlowSchemaLister","signature":"func NewFlowSchemaLister(indexer cache.Indexer) FlowSchemaLister","file":"staging/src/k8s.io/client-go/listers/flowcontrol/v1beta3/flowschema.go","code":"// NewFlowSchemaLister returns a new FlowSchemaLister.\nfunc NewFlowSchemaLister(indexer cache.Indexer) FlowSchemaLister {\n\treturn \u0026flowSchemaLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027947,"name":"List","signature":"func (s *flowSchemaLister) List(selector labels.Selector) (ret []*v1beta3.FlowSchema, err error)","file":"staging/src/k8s.io/client-go/listers/flowcontrol/v1beta3/flowschema.go","code":"// List lists all FlowSchemas in the indexer.\nfunc (s *flowSchemaLister) List(selector labels.Selector) (ret []*v1beta3.FlowSchema, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta3.FlowSchema))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027948,"name":"Get","signature":"func (s *flowSchemaLister) Get(name string) (*v1beta3.FlowSchema, error)","file":"staging/src/k8s.io/client-go/listers/flowcontrol/v1beta3/flowschema.go","code":"// Get retrieves the FlowSchema from the index for a given name.\nfunc (s *flowSchemaLister) Get(name string) (*v1beta3.FlowSchema, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta3.Resource(\"flowschema\"), name)\n\t}\n\treturn obj.(*v1beta3.FlowSchema), nil\n}","line":{"from":58,"to":68}} {"id":100027949,"name":"NewPriorityLevelConfigurationLister","signature":"func NewPriorityLevelConfigurationLister(indexer cache.Indexer) PriorityLevelConfigurationLister","file":"staging/src/k8s.io/client-go/listers/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// NewPriorityLevelConfigurationLister returns a new PriorityLevelConfigurationLister.\nfunc NewPriorityLevelConfigurationLister(indexer cache.Indexer) PriorityLevelConfigurationLister {\n\treturn \u0026priorityLevelConfigurationLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027950,"name":"List","signature":"func (s *priorityLevelConfigurationLister) List(selector labels.Selector) (ret []*v1beta3.PriorityLevelConfiguration, err error)","file":"staging/src/k8s.io/client-go/listers/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// List lists all PriorityLevelConfigurations in the indexer.\nfunc (s *priorityLevelConfigurationLister) List(selector labels.Selector) (ret []*v1beta3.PriorityLevelConfiguration, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta3.PriorityLevelConfiguration))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027951,"name":"Get","signature":"func (s *priorityLevelConfigurationLister) Get(name string) (*v1beta3.PriorityLevelConfiguration, error)","file":"staging/src/k8s.io/client-go/listers/flowcontrol/v1beta3/prioritylevelconfiguration.go","code":"// Get retrieves the PriorityLevelConfiguration from the index for a given name.\nfunc (s *priorityLevelConfigurationLister) Get(name string) (*v1beta3.PriorityLevelConfiguration, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta3.Resource(\"prioritylevelconfiguration\"), name)\n\t}\n\treturn obj.(*v1beta3.PriorityLevelConfiguration), nil\n}","line":{"from":58,"to":68}} {"id":100027952,"name":"NewImageReviewLister","signature":"func NewImageReviewLister(indexer cache.Indexer) ImageReviewLister","file":"staging/src/k8s.io/client-go/listers/imagepolicy/v1alpha1/imagereview.go","code":"// NewImageReviewLister returns a new ImageReviewLister.\nfunc NewImageReviewLister(indexer cache.Indexer) ImageReviewLister {\n\treturn \u0026imageReviewLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027953,"name":"List","signature":"func (s *imageReviewLister) List(selector labels.Selector) (ret []*v1alpha1.ImageReview, err error)","file":"staging/src/k8s.io/client-go/listers/imagepolicy/v1alpha1/imagereview.go","code":"// List lists all ImageReviews in the indexer.\nfunc (s *imageReviewLister) List(selector labels.Selector) (ret []*v1alpha1.ImageReview, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ImageReview))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027954,"name":"Get","signature":"func (s *imageReviewLister) Get(name string) (*v1alpha1.ImageReview, error)","file":"staging/src/k8s.io/client-go/listers/imagepolicy/v1alpha1/imagereview.go","code":"// Get retrieves the ImageReview from the index for a given name.\nfunc (s *imageReviewLister) Get(name string) (*v1alpha1.ImageReview, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"imagereview\"), name)\n\t}\n\treturn obj.(*v1alpha1.ImageReview), nil\n}","line":{"from":58,"to":68}} {"id":100027955,"name":"NewIngressLister","signature":"func NewIngressLister(indexer cache.Indexer) IngressLister","file":"staging/src/k8s.io/client-go/listers/networking/v1/ingress.go","code":"// NewIngressLister returns a new IngressLister.\nfunc NewIngressLister(indexer cache.Indexer) IngressLister {\n\treturn \u0026ingressLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027956,"name":"List","signature":"func (s *ingressLister) List(selector labels.Selector) (ret []*v1.Ingress, err error)","file":"staging/src/k8s.io/client-go/listers/networking/v1/ingress.go","code":"// List lists all Ingresses in the indexer.\nfunc (s *ingressLister) List(selector labels.Selector) (ret []*v1.Ingress, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Ingress))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027957,"name":"Ingresses","signature":"func (s *ingressLister) Ingresses(namespace string) IngressNamespaceLister","file":"staging/src/k8s.io/client-go/listers/networking/v1/ingress.go","code":"// Ingresses returns an object that can list and get Ingresses.\nfunc (s *ingressLister) Ingresses(namespace string) IngressNamespaceLister {\n\treturn ingressNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027958,"name":"List","signature":"func (s ingressNamespaceLister) List(selector labels.Selector) (ret []*v1.Ingress, err error)","file":"staging/src/k8s.io/client-go/listers/networking/v1/ingress.go","code":"// List lists all Ingresses in the indexer for a given namespace.\nfunc (s ingressNamespaceLister) List(selector labels.Selector) (ret []*v1.Ingress, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Ingress))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027959,"name":"Get","signature":"func (s ingressNamespaceLister) Get(name string) (*v1.Ingress, error)","file":"staging/src/k8s.io/client-go/listers/networking/v1/ingress.go","code":"// Get retrieves the Ingress from the indexer for a given namespace and name.\nfunc (s ingressNamespaceLister) Get(name string) (*v1.Ingress, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"ingress\"), name)\n\t}\n\treturn obj.(*v1.Ingress), nil\n}","line":{"from":89,"to":99}} {"id":100027960,"name":"NewIngressClassLister","signature":"func NewIngressClassLister(indexer cache.Indexer) IngressClassLister","file":"staging/src/k8s.io/client-go/listers/networking/v1/ingressclass.go","code":"// NewIngressClassLister returns a new IngressClassLister.\nfunc NewIngressClassLister(indexer cache.Indexer) IngressClassLister {\n\treturn \u0026ingressClassLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027961,"name":"List","signature":"func (s *ingressClassLister) List(selector labels.Selector) (ret []*v1.IngressClass, err error)","file":"staging/src/k8s.io/client-go/listers/networking/v1/ingressclass.go","code":"// List lists all IngressClasses in the indexer.\nfunc (s *ingressClassLister) List(selector labels.Selector) (ret []*v1.IngressClass, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.IngressClass))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027962,"name":"Get","signature":"func (s *ingressClassLister) Get(name string) (*v1.IngressClass, error)","file":"staging/src/k8s.io/client-go/listers/networking/v1/ingressclass.go","code":"// Get retrieves the IngressClass from the index for a given name.\nfunc (s *ingressClassLister) Get(name string) (*v1.IngressClass, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"ingressclass\"), name)\n\t}\n\treturn obj.(*v1.IngressClass), nil\n}","line":{"from":58,"to":68}} {"id":100027963,"name":"NewNetworkPolicyLister","signature":"func NewNetworkPolicyLister(indexer cache.Indexer) NetworkPolicyLister","file":"staging/src/k8s.io/client-go/listers/networking/v1/networkpolicy.go","code":"// NewNetworkPolicyLister returns a new NetworkPolicyLister.\nfunc NewNetworkPolicyLister(indexer cache.Indexer) NetworkPolicyLister {\n\treturn \u0026networkPolicyLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027964,"name":"List","signature":"func (s *networkPolicyLister) List(selector labels.Selector) (ret []*v1.NetworkPolicy, err error)","file":"staging/src/k8s.io/client-go/listers/networking/v1/networkpolicy.go","code":"// List lists all NetworkPolicies in the indexer.\nfunc (s *networkPolicyLister) List(selector labels.Selector) (ret []*v1.NetworkPolicy, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.NetworkPolicy))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027965,"name":"NetworkPolicies","signature":"func (s *networkPolicyLister) NetworkPolicies(namespace string) NetworkPolicyNamespaceLister","file":"staging/src/k8s.io/client-go/listers/networking/v1/networkpolicy.go","code":"// NetworkPolicies returns an object that can list and get NetworkPolicies.\nfunc (s *networkPolicyLister) NetworkPolicies(namespace string) NetworkPolicyNamespaceLister {\n\treturn networkPolicyNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027966,"name":"List","signature":"func (s networkPolicyNamespaceLister) List(selector labels.Selector) (ret []*v1.NetworkPolicy, err error)","file":"staging/src/k8s.io/client-go/listers/networking/v1/networkpolicy.go","code":"// List lists all NetworkPolicies in the indexer for a given namespace.\nfunc (s networkPolicyNamespaceLister) List(selector labels.Selector) (ret []*v1.NetworkPolicy, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.NetworkPolicy))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027967,"name":"Get","signature":"func (s networkPolicyNamespaceLister) Get(name string) (*v1.NetworkPolicy, error)","file":"staging/src/k8s.io/client-go/listers/networking/v1/networkpolicy.go","code":"// Get retrieves the NetworkPolicy from the indexer for a given namespace and name.\nfunc (s networkPolicyNamespaceLister) Get(name string) (*v1.NetworkPolicy, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"networkpolicy\"), name)\n\t}\n\treturn obj.(*v1.NetworkPolicy), nil\n}","line":{"from":89,"to":99}} {"id":100027968,"name":"NewClusterCIDRLister","signature":"func NewClusterCIDRLister(indexer cache.Indexer) ClusterCIDRLister","file":"staging/src/k8s.io/client-go/listers/networking/v1alpha1/clustercidr.go","code":"// NewClusterCIDRLister returns a new ClusterCIDRLister.\nfunc NewClusterCIDRLister(indexer cache.Indexer) ClusterCIDRLister {\n\treturn \u0026clusterCIDRLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027969,"name":"List","signature":"func (s *clusterCIDRLister) List(selector labels.Selector) (ret []*v1alpha1.ClusterCIDR, err error)","file":"staging/src/k8s.io/client-go/listers/networking/v1alpha1/clustercidr.go","code":"// List lists all ClusterCIDRs in the indexer.\nfunc (s *clusterCIDRLister) List(selector labels.Selector) (ret []*v1alpha1.ClusterCIDR, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ClusterCIDR))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027970,"name":"Get","signature":"func (s *clusterCIDRLister) Get(name string) (*v1alpha1.ClusterCIDR, error)","file":"staging/src/k8s.io/client-go/listers/networking/v1alpha1/clustercidr.go","code":"// Get retrieves the ClusterCIDR from the index for a given name.\nfunc (s *clusterCIDRLister) Get(name string) (*v1alpha1.ClusterCIDR, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"clustercidr\"), name)\n\t}\n\treturn obj.(*v1alpha1.ClusterCIDR), nil\n}","line":{"from":58,"to":68}} {"id":100027971,"name":"NewIPAddressLister","signature":"func NewIPAddressLister(indexer cache.Indexer) IPAddressLister","file":"staging/src/k8s.io/client-go/listers/networking/v1alpha1/ipaddress.go","code":"// NewIPAddressLister returns a new IPAddressLister.\nfunc NewIPAddressLister(indexer cache.Indexer) IPAddressLister {\n\treturn \u0026iPAddressLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027972,"name":"List","signature":"func (s *iPAddressLister) List(selector labels.Selector) (ret []*v1alpha1.IPAddress, err error)","file":"staging/src/k8s.io/client-go/listers/networking/v1alpha1/ipaddress.go","code":"// List lists all IPAddresses in the indexer.\nfunc (s *iPAddressLister) List(selector labels.Selector) (ret []*v1alpha1.IPAddress, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.IPAddress))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027973,"name":"Get","signature":"func (s *iPAddressLister) Get(name string) (*v1alpha1.IPAddress, error)","file":"staging/src/k8s.io/client-go/listers/networking/v1alpha1/ipaddress.go","code":"// Get retrieves the IPAddress from the index for a given name.\nfunc (s *iPAddressLister) Get(name string) (*v1alpha1.IPAddress, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"ipaddress\"), name)\n\t}\n\treturn obj.(*v1alpha1.IPAddress), nil\n}","line":{"from":58,"to":68}} {"id":100027974,"name":"NewIngressLister","signature":"func NewIngressLister(indexer cache.Indexer) IngressLister","file":"staging/src/k8s.io/client-go/listers/networking/v1beta1/ingress.go","code":"// NewIngressLister returns a new IngressLister.\nfunc NewIngressLister(indexer cache.Indexer) IngressLister {\n\treturn \u0026ingressLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027975,"name":"List","signature":"func (s *ingressLister) List(selector labels.Selector) (ret []*v1beta1.Ingress, err error)","file":"staging/src/k8s.io/client-go/listers/networking/v1beta1/ingress.go","code":"// List lists all Ingresses in the indexer.\nfunc (s *ingressLister) List(selector labels.Selector) (ret []*v1beta1.Ingress, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.Ingress))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027976,"name":"Ingresses","signature":"func (s *ingressLister) Ingresses(namespace string) IngressNamespaceLister","file":"staging/src/k8s.io/client-go/listers/networking/v1beta1/ingress.go","code":"// Ingresses returns an object that can list and get Ingresses.\nfunc (s *ingressLister) Ingresses(namespace string) IngressNamespaceLister {\n\treturn ingressNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027977,"name":"List","signature":"func (s ingressNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.Ingress, err error)","file":"staging/src/k8s.io/client-go/listers/networking/v1beta1/ingress.go","code":"// List lists all Ingresses in the indexer for a given namespace.\nfunc (s ingressNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.Ingress, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.Ingress))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027978,"name":"Get","signature":"func (s ingressNamespaceLister) Get(name string) (*v1beta1.Ingress, error)","file":"staging/src/k8s.io/client-go/listers/networking/v1beta1/ingress.go","code":"// Get retrieves the Ingress from the indexer for a given namespace and name.\nfunc (s ingressNamespaceLister) Get(name string) (*v1beta1.Ingress, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"ingress\"), name)\n\t}\n\treturn obj.(*v1beta1.Ingress), nil\n}","line":{"from":89,"to":99}} {"id":100027979,"name":"NewIngressClassLister","signature":"func NewIngressClassLister(indexer cache.Indexer) IngressClassLister","file":"staging/src/k8s.io/client-go/listers/networking/v1beta1/ingressclass.go","code":"// NewIngressClassLister returns a new IngressClassLister.\nfunc NewIngressClassLister(indexer cache.Indexer) IngressClassLister {\n\treturn \u0026ingressClassLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027980,"name":"List","signature":"func (s *ingressClassLister) List(selector labels.Selector) (ret []*v1beta1.IngressClass, err error)","file":"staging/src/k8s.io/client-go/listers/networking/v1beta1/ingressclass.go","code":"// List lists all IngressClasses in the indexer.\nfunc (s *ingressClassLister) List(selector labels.Selector) (ret []*v1beta1.IngressClass, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.IngressClass))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027981,"name":"Get","signature":"func (s *ingressClassLister) Get(name string) (*v1beta1.IngressClass, error)","file":"staging/src/k8s.io/client-go/listers/networking/v1beta1/ingressclass.go","code":"// Get retrieves the IngressClass from the index for a given name.\nfunc (s *ingressClassLister) Get(name string) (*v1beta1.IngressClass, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"ingressclass\"), name)\n\t}\n\treturn obj.(*v1beta1.IngressClass), nil\n}","line":{"from":58,"to":68}} {"id":100027982,"name":"NewRuntimeClassLister","signature":"func NewRuntimeClassLister(indexer cache.Indexer) RuntimeClassLister","file":"staging/src/k8s.io/client-go/listers/node/v1/runtimeclass.go","code":"// NewRuntimeClassLister returns a new RuntimeClassLister.\nfunc NewRuntimeClassLister(indexer cache.Indexer) RuntimeClassLister {\n\treturn \u0026runtimeClassLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027983,"name":"List","signature":"func (s *runtimeClassLister) List(selector labels.Selector) (ret []*v1.RuntimeClass, err error)","file":"staging/src/k8s.io/client-go/listers/node/v1/runtimeclass.go","code":"// List lists all RuntimeClasses in the indexer.\nfunc (s *runtimeClassLister) List(selector labels.Selector) (ret []*v1.RuntimeClass, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.RuntimeClass))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027984,"name":"Get","signature":"func (s *runtimeClassLister) Get(name string) (*v1.RuntimeClass, error)","file":"staging/src/k8s.io/client-go/listers/node/v1/runtimeclass.go","code":"// Get retrieves the RuntimeClass from the index for a given name.\nfunc (s *runtimeClassLister) Get(name string) (*v1.RuntimeClass, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"runtimeclass\"), name)\n\t}\n\treturn obj.(*v1.RuntimeClass), nil\n}","line":{"from":58,"to":68}} {"id":100027985,"name":"NewRuntimeClassLister","signature":"func NewRuntimeClassLister(indexer cache.Indexer) RuntimeClassLister","file":"staging/src/k8s.io/client-go/listers/node/v1alpha1/runtimeclass.go","code":"// NewRuntimeClassLister returns a new RuntimeClassLister.\nfunc NewRuntimeClassLister(indexer cache.Indexer) RuntimeClassLister {\n\treturn \u0026runtimeClassLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027986,"name":"List","signature":"func (s *runtimeClassLister) List(selector labels.Selector) (ret []*v1alpha1.RuntimeClass, err error)","file":"staging/src/k8s.io/client-go/listers/node/v1alpha1/runtimeclass.go","code":"// List lists all RuntimeClasses in the indexer.\nfunc (s *runtimeClassLister) List(selector labels.Selector) (ret []*v1alpha1.RuntimeClass, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.RuntimeClass))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027987,"name":"Get","signature":"func (s *runtimeClassLister) Get(name string) (*v1alpha1.RuntimeClass, error)","file":"staging/src/k8s.io/client-go/listers/node/v1alpha1/runtimeclass.go","code":"// Get retrieves the RuntimeClass from the index for a given name.\nfunc (s *runtimeClassLister) Get(name string) (*v1alpha1.RuntimeClass, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"runtimeclass\"), name)\n\t}\n\treturn obj.(*v1alpha1.RuntimeClass), nil\n}","line":{"from":58,"to":68}} {"id":100027988,"name":"NewRuntimeClassLister","signature":"func NewRuntimeClassLister(indexer cache.Indexer) RuntimeClassLister","file":"staging/src/k8s.io/client-go/listers/node/v1beta1/runtimeclass.go","code":"// NewRuntimeClassLister returns a new RuntimeClassLister.\nfunc NewRuntimeClassLister(indexer cache.Indexer) RuntimeClassLister {\n\treturn \u0026runtimeClassLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100027989,"name":"List","signature":"func (s *runtimeClassLister) List(selector labels.Selector) (ret []*v1beta1.RuntimeClass, err error)","file":"staging/src/k8s.io/client-go/listers/node/v1beta1/runtimeclass.go","code":"// List lists all RuntimeClasses in the indexer.\nfunc (s *runtimeClassLister) List(selector labels.Selector) (ret []*v1beta1.RuntimeClass, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.RuntimeClass))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100027990,"name":"Get","signature":"func (s *runtimeClassLister) Get(name string) (*v1beta1.RuntimeClass, error)","file":"staging/src/k8s.io/client-go/listers/node/v1beta1/runtimeclass.go","code":"// Get retrieves the RuntimeClass from the index for a given name.\nfunc (s *runtimeClassLister) Get(name string) (*v1beta1.RuntimeClass, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"runtimeclass\"), name)\n\t}\n\treturn obj.(*v1beta1.RuntimeClass), nil\n}","line":{"from":58,"to":68}} {"id":100027991,"name":"NewEvictionLister","signature":"func NewEvictionLister(indexer cache.Indexer) EvictionLister","file":"staging/src/k8s.io/client-go/listers/policy/v1/eviction.go","code":"// NewEvictionLister returns a new EvictionLister.\nfunc NewEvictionLister(indexer cache.Indexer) EvictionLister {\n\treturn \u0026evictionLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027992,"name":"List","signature":"func (s *evictionLister) List(selector labels.Selector) (ret []*v1.Eviction, err error)","file":"staging/src/k8s.io/client-go/listers/policy/v1/eviction.go","code":"// List lists all Evictions in the indexer.\nfunc (s *evictionLister) List(selector labels.Selector) (ret []*v1.Eviction, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Eviction))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027993,"name":"Evictions","signature":"func (s *evictionLister) Evictions(namespace string) EvictionNamespaceLister","file":"staging/src/k8s.io/client-go/listers/policy/v1/eviction.go","code":"// Evictions returns an object that can list and get Evictions.\nfunc (s *evictionLister) Evictions(namespace string) EvictionNamespaceLister {\n\treturn evictionNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027994,"name":"List","signature":"func (s evictionNamespaceLister) List(selector labels.Selector) (ret []*v1.Eviction, err error)","file":"staging/src/k8s.io/client-go/listers/policy/v1/eviction.go","code":"// List lists all Evictions in the indexer for a given namespace.\nfunc (s evictionNamespaceLister) List(selector labels.Selector) (ret []*v1.Eviction, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Eviction))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100027995,"name":"Get","signature":"func (s evictionNamespaceLister) Get(name string) (*v1.Eviction, error)","file":"staging/src/k8s.io/client-go/listers/policy/v1/eviction.go","code":"// Get retrieves the Eviction from the indexer for a given namespace and name.\nfunc (s evictionNamespaceLister) Get(name string) (*v1.Eviction, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"eviction\"), name)\n\t}\n\treturn obj.(*v1.Eviction), nil\n}","line":{"from":89,"to":99}} {"id":100027996,"name":"NewPodDisruptionBudgetLister","signature":"func NewPodDisruptionBudgetLister(indexer cache.Indexer) PodDisruptionBudgetLister","file":"staging/src/k8s.io/client-go/listers/policy/v1/poddisruptionbudget.go","code":"// NewPodDisruptionBudgetLister returns a new PodDisruptionBudgetLister.\nfunc NewPodDisruptionBudgetLister(indexer cache.Indexer) PodDisruptionBudgetLister {\n\treturn \u0026podDisruptionBudgetLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100027997,"name":"List","signature":"func (s *podDisruptionBudgetLister) List(selector labels.Selector) (ret []*v1.PodDisruptionBudget, err error)","file":"staging/src/k8s.io/client-go/listers/policy/v1/poddisruptionbudget.go","code":"// List lists all PodDisruptionBudgets in the indexer.\nfunc (s *podDisruptionBudgetLister) List(selector labels.Selector) (ret []*v1.PodDisruptionBudget, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.PodDisruptionBudget))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100027998,"name":"PodDisruptionBudgets","signature":"func (s *podDisruptionBudgetLister) PodDisruptionBudgets(namespace string) PodDisruptionBudgetNamespaceLister","file":"staging/src/k8s.io/client-go/listers/policy/v1/poddisruptionbudget.go","code":"// PodDisruptionBudgets returns an object that can list and get PodDisruptionBudgets.\nfunc (s *podDisruptionBudgetLister) PodDisruptionBudgets(namespace string) PodDisruptionBudgetNamespaceLister {\n\treturn podDisruptionBudgetNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100027999,"name":"List","signature":"func (s podDisruptionBudgetNamespaceLister) List(selector labels.Selector) (ret []*v1.PodDisruptionBudget, err error)","file":"staging/src/k8s.io/client-go/listers/policy/v1/poddisruptionbudget.go","code":"// List lists all PodDisruptionBudgets in the indexer for a given namespace.\nfunc (s podDisruptionBudgetNamespaceLister) List(selector labels.Selector) (ret []*v1.PodDisruptionBudget, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.PodDisruptionBudget))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100028000,"name":"Get","signature":"func (s podDisruptionBudgetNamespaceLister) Get(name string) (*v1.PodDisruptionBudget, error)","file":"staging/src/k8s.io/client-go/listers/policy/v1/poddisruptionbudget.go","code":"// Get retrieves the PodDisruptionBudget from the indexer for a given namespace and name.\nfunc (s podDisruptionBudgetNamespaceLister) Get(name string) (*v1.PodDisruptionBudget, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"poddisruptionbudget\"), name)\n\t}\n\treturn obj.(*v1.PodDisruptionBudget), nil\n}","line":{"from":89,"to":99}} {"id":100028001,"name":"GetPodPodDisruptionBudgets","signature":"func (s *podDisruptionBudgetLister) GetPodPodDisruptionBudgets(pod *v1.Pod) ([]*policy.PodDisruptionBudget, error)","file":"staging/src/k8s.io/client-go/listers/policy/v1/poddisruptionbudget_expansion.go","code":"// GetPodPodDisruptionBudgets returns a list of PodDisruptionBudgets matching a pod.\nfunc (s *podDisruptionBudgetLister) GetPodPodDisruptionBudgets(pod *v1.Pod) ([]*policy.PodDisruptionBudget, error) {\n\tvar selector labels.Selector\n\n\tlist, err := s.PodDisruptionBudgets(pod.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar pdbList []*policy.PodDisruptionBudget\n\tfor i := range list {\n\t\tpdb := list[i]\n\t\tselector, err = metav1.LabelSelectorAsSelector(pdb.Spec.Selector)\n\t\tif err != nil {\n\t\t\t// This object has an invalid selector, it does not match the pod\n\t\t\tcontinue\n\t\t}\n\n\t\t// Unlike the v1beta version, here we let an empty selector match everything.\n\t\tif !selector.Matches(labels.Set(pod.Labels)) {\n\t\t\tcontinue\n\t\t}\n\t\tpdbList = append(pdbList, pdb)\n\t}\n\n\tif len(pdbList) == 0 {\n\t\treturn nil, fmt.Errorf(\"could not find PodDisruptionBudget for pod %s in namespace %s with labels: %v\", pod.Name, pod.Namespace, pod.Labels)\n\t}\n\n\treturn pdbList, nil\n}","line":{"from":38,"to":68}} {"id":100028002,"name":"NewEvictionLister","signature":"func NewEvictionLister(indexer cache.Indexer) EvictionLister","file":"staging/src/k8s.io/client-go/listers/policy/v1beta1/eviction.go","code":"// NewEvictionLister returns a new EvictionLister.\nfunc NewEvictionLister(indexer cache.Indexer) EvictionLister {\n\treturn \u0026evictionLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100028003,"name":"List","signature":"func (s *evictionLister) List(selector labels.Selector) (ret []*v1beta1.Eviction, err error)","file":"staging/src/k8s.io/client-go/listers/policy/v1beta1/eviction.go","code":"// List lists all Evictions in the indexer.\nfunc (s *evictionLister) List(selector labels.Selector) (ret []*v1beta1.Eviction, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.Eviction))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100028004,"name":"Evictions","signature":"func (s *evictionLister) Evictions(namespace string) EvictionNamespaceLister","file":"staging/src/k8s.io/client-go/listers/policy/v1beta1/eviction.go","code":"// Evictions returns an object that can list and get Evictions.\nfunc (s *evictionLister) Evictions(namespace string) EvictionNamespaceLister {\n\treturn evictionNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100028005,"name":"List","signature":"func (s evictionNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.Eviction, err error)","file":"staging/src/k8s.io/client-go/listers/policy/v1beta1/eviction.go","code":"// List lists all Evictions in the indexer for a given namespace.\nfunc (s evictionNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.Eviction, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.Eviction))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100028006,"name":"Get","signature":"func (s evictionNamespaceLister) Get(name string) (*v1beta1.Eviction, error)","file":"staging/src/k8s.io/client-go/listers/policy/v1beta1/eviction.go","code":"// Get retrieves the Eviction from the indexer for a given namespace and name.\nfunc (s evictionNamespaceLister) Get(name string) (*v1beta1.Eviction, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"eviction\"), name)\n\t}\n\treturn obj.(*v1beta1.Eviction), nil\n}","line":{"from":89,"to":99}} {"id":100028007,"name":"NewPodDisruptionBudgetLister","signature":"func NewPodDisruptionBudgetLister(indexer cache.Indexer) PodDisruptionBudgetLister","file":"staging/src/k8s.io/client-go/listers/policy/v1beta1/poddisruptionbudget.go","code":"// NewPodDisruptionBudgetLister returns a new PodDisruptionBudgetLister.\nfunc NewPodDisruptionBudgetLister(indexer cache.Indexer) PodDisruptionBudgetLister {\n\treturn \u0026podDisruptionBudgetLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100028008,"name":"List","signature":"func (s *podDisruptionBudgetLister) List(selector labels.Selector) (ret []*v1beta1.PodDisruptionBudget, err error)","file":"staging/src/k8s.io/client-go/listers/policy/v1beta1/poddisruptionbudget.go","code":"// List lists all PodDisruptionBudgets in the indexer.\nfunc (s *podDisruptionBudgetLister) List(selector labels.Selector) (ret []*v1beta1.PodDisruptionBudget, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.PodDisruptionBudget))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100028009,"name":"PodDisruptionBudgets","signature":"func (s *podDisruptionBudgetLister) PodDisruptionBudgets(namespace string) PodDisruptionBudgetNamespaceLister","file":"staging/src/k8s.io/client-go/listers/policy/v1beta1/poddisruptionbudget.go","code":"// PodDisruptionBudgets returns an object that can list and get PodDisruptionBudgets.\nfunc (s *podDisruptionBudgetLister) PodDisruptionBudgets(namespace string) PodDisruptionBudgetNamespaceLister {\n\treturn podDisruptionBudgetNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100028010,"name":"List","signature":"func (s podDisruptionBudgetNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.PodDisruptionBudget, err error)","file":"staging/src/k8s.io/client-go/listers/policy/v1beta1/poddisruptionbudget.go","code":"// List lists all PodDisruptionBudgets in the indexer for a given namespace.\nfunc (s podDisruptionBudgetNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.PodDisruptionBudget, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.PodDisruptionBudget))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100028011,"name":"Get","signature":"func (s podDisruptionBudgetNamespaceLister) Get(name string) (*v1beta1.PodDisruptionBudget, error)","file":"staging/src/k8s.io/client-go/listers/policy/v1beta1/poddisruptionbudget.go","code":"// Get retrieves the PodDisruptionBudget from the indexer for a given namespace and name.\nfunc (s podDisruptionBudgetNamespaceLister) Get(name string) (*v1beta1.PodDisruptionBudget, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"poddisruptionbudget\"), name)\n\t}\n\treturn obj.(*v1beta1.PodDisruptionBudget), nil\n}","line":{"from":89,"to":99}} {"id":100028012,"name":"GetPodPodDisruptionBudgets","signature":"func (s *podDisruptionBudgetLister) GetPodPodDisruptionBudgets(pod *v1.Pod) ([]*policy.PodDisruptionBudget, error)","file":"staging/src/k8s.io/client-go/listers/policy/v1beta1/poddisruptionbudget_expansion.go","code":"// GetPodPodDisruptionBudgets returns a list of PodDisruptionBudgets matching a pod. Returns an error only if no matching PodDisruptionBudgets are found.\nfunc (s *podDisruptionBudgetLister) GetPodPodDisruptionBudgets(pod *v1.Pod) ([]*policy.PodDisruptionBudget, error) {\n\tvar selector labels.Selector\n\n\tlist, err := s.PodDisruptionBudgets(pod.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar pdbList []*policy.PodDisruptionBudget\n\tfor i := range list {\n\t\tpdb := list[i]\n\t\tselector, err = metav1.LabelSelectorAsSelector(pdb.Spec.Selector)\n\t\tif err != nil {\n\t\t\t// This object has an invalid selector, it does not match the pod\n\t\t\tcontinue\n\t\t}\n\n\t\t// If a PDB with a nil or empty selector creeps in, it should match nothing, not everything.\n\t\tif selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) {\n\t\t\tcontinue\n\t\t}\n\t\tpdbList = append(pdbList, pdb)\n\t}\n\n\tif len(pdbList) == 0 {\n\t\treturn nil, fmt.Errorf(\"could not find PodDisruptionBudget for pod %s in namespace %s with labels: %v\", pod.Name, pod.Namespace, pod.Labels)\n\t}\n\n\treturn pdbList, nil\n}","line":{"from":38,"to":68}} {"id":100028013,"name":"NewPodSecurityPolicyLister","signature":"func NewPodSecurityPolicyLister(indexer cache.Indexer) PodSecurityPolicyLister","file":"staging/src/k8s.io/client-go/listers/policy/v1beta1/podsecuritypolicy.go","code":"// NewPodSecurityPolicyLister returns a new PodSecurityPolicyLister.\nfunc NewPodSecurityPolicyLister(indexer cache.Indexer) PodSecurityPolicyLister {\n\treturn \u0026podSecurityPolicyLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100028014,"name":"List","signature":"func (s *podSecurityPolicyLister) List(selector labels.Selector) (ret []*v1beta1.PodSecurityPolicy, err error)","file":"staging/src/k8s.io/client-go/listers/policy/v1beta1/podsecuritypolicy.go","code":"// List lists all PodSecurityPolicies in the indexer.\nfunc (s *podSecurityPolicyLister) List(selector labels.Selector) (ret []*v1beta1.PodSecurityPolicy, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.PodSecurityPolicy))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100028015,"name":"Get","signature":"func (s *podSecurityPolicyLister) Get(name string) (*v1beta1.PodSecurityPolicy, error)","file":"staging/src/k8s.io/client-go/listers/policy/v1beta1/podsecuritypolicy.go","code":"// Get retrieves the PodSecurityPolicy from the index for a given name.\nfunc (s *podSecurityPolicyLister) Get(name string) (*v1beta1.PodSecurityPolicy, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"podsecuritypolicy\"), name)\n\t}\n\treturn obj.(*v1beta1.PodSecurityPolicy), nil\n}","line":{"from":58,"to":68}} {"id":100028016,"name":"NewClusterRoleLister","signature":"func NewClusterRoleLister(indexer cache.Indexer) ClusterRoleLister","file":"staging/src/k8s.io/client-go/listers/rbac/v1/clusterrole.go","code":"// NewClusterRoleLister returns a new ClusterRoleLister.\nfunc NewClusterRoleLister(indexer cache.Indexer) ClusterRoleLister {\n\treturn \u0026clusterRoleLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100028017,"name":"List","signature":"func (s *clusterRoleLister) List(selector labels.Selector) (ret []*v1.ClusterRole, err error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1/clusterrole.go","code":"// List lists all ClusterRoles in the indexer.\nfunc (s *clusterRoleLister) List(selector labels.Selector) (ret []*v1.ClusterRole, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.ClusterRole))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100028018,"name":"Get","signature":"func (s *clusterRoleLister) Get(name string) (*v1.ClusterRole, error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1/clusterrole.go","code":"// Get retrieves the ClusterRole from the index for a given name.\nfunc (s *clusterRoleLister) Get(name string) (*v1.ClusterRole, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"clusterrole\"), name)\n\t}\n\treturn obj.(*v1.ClusterRole), nil\n}","line":{"from":58,"to":68}} {"id":100028019,"name":"NewClusterRoleBindingLister","signature":"func NewClusterRoleBindingLister(indexer cache.Indexer) ClusterRoleBindingLister","file":"staging/src/k8s.io/client-go/listers/rbac/v1/clusterrolebinding.go","code":"// NewClusterRoleBindingLister returns a new ClusterRoleBindingLister.\nfunc NewClusterRoleBindingLister(indexer cache.Indexer) ClusterRoleBindingLister {\n\treturn \u0026clusterRoleBindingLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100028020,"name":"List","signature":"func (s *clusterRoleBindingLister) List(selector labels.Selector) (ret []*v1.ClusterRoleBinding, err error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1/clusterrolebinding.go","code":"// List lists all ClusterRoleBindings in the indexer.\nfunc (s *clusterRoleBindingLister) List(selector labels.Selector) (ret []*v1.ClusterRoleBinding, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.ClusterRoleBinding))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100028021,"name":"Get","signature":"func (s *clusterRoleBindingLister) Get(name string) (*v1.ClusterRoleBinding, error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1/clusterrolebinding.go","code":"// Get retrieves the ClusterRoleBinding from the index for a given name.\nfunc (s *clusterRoleBindingLister) Get(name string) (*v1.ClusterRoleBinding, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"clusterrolebinding\"), name)\n\t}\n\treturn obj.(*v1.ClusterRoleBinding), nil\n}","line":{"from":58,"to":68}} {"id":100028022,"name":"NewRoleLister","signature":"func NewRoleLister(indexer cache.Indexer) RoleLister","file":"staging/src/k8s.io/client-go/listers/rbac/v1/role.go","code":"// NewRoleLister returns a new RoleLister.\nfunc NewRoleLister(indexer cache.Indexer) RoleLister {\n\treturn \u0026roleLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100028023,"name":"List","signature":"func (s *roleLister) List(selector labels.Selector) (ret []*v1.Role, err error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1/role.go","code":"// List lists all Roles in the indexer.\nfunc (s *roleLister) List(selector labels.Selector) (ret []*v1.Role, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Role))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100028024,"name":"Roles","signature":"func (s *roleLister) Roles(namespace string) RoleNamespaceLister","file":"staging/src/k8s.io/client-go/listers/rbac/v1/role.go","code":"// Roles returns an object that can list and get Roles.\nfunc (s *roleLister) Roles(namespace string) RoleNamespaceLister {\n\treturn roleNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100028025,"name":"List","signature":"func (s roleNamespaceLister) List(selector labels.Selector) (ret []*v1.Role, err error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1/role.go","code":"// List lists all Roles in the indexer for a given namespace.\nfunc (s roleNamespaceLister) List(selector labels.Selector) (ret []*v1.Role, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Role))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100028026,"name":"Get","signature":"func (s roleNamespaceLister) Get(name string) (*v1.Role, error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1/role.go","code":"// Get retrieves the Role from the indexer for a given namespace and name.\nfunc (s roleNamespaceLister) Get(name string) (*v1.Role, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"role\"), name)\n\t}\n\treturn obj.(*v1.Role), nil\n}","line":{"from":89,"to":99}} {"id":100028027,"name":"NewRoleBindingLister","signature":"func NewRoleBindingLister(indexer cache.Indexer) RoleBindingLister","file":"staging/src/k8s.io/client-go/listers/rbac/v1/rolebinding.go","code":"// NewRoleBindingLister returns a new RoleBindingLister.\nfunc NewRoleBindingLister(indexer cache.Indexer) RoleBindingLister {\n\treturn \u0026roleBindingLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100028028,"name":"List","signature":"func (s *roleBindingLister) List(selector labels.Selector) (ret []*v1.RoleBinding, err error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1/rolebinding.go","code":"// List lists all RoleBindings in the indexer.\nfunc (s *roleBindingLister) List(selector labels.Selector) (ret []*v1.RoleBinding, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.RoleBinding))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100028029,"name":"RoleBindings","signature":"func (s *roleBindingLister) RoleBindings(namespace string) RoleBindingNamespaceLister","file":"staging/src/k8s.io/client-go/listers/rbac/v1/rolebinding.go","code":"// RoleBindings returns an object that can list and get RoleBindings.\nfunc (s *roleBindingLister) RoleBindings(namespace string) RoleBindingNamespaceLister {\n\treturn roleBindingNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100028030,"name":"List","signature":"func (s roleBindingNamespaceLister) List(selector labels.Selector) (ret []*v1.RoleBinding, err error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1/rolebinding.go","code":"// List lists all RoleBindings in the indexer for a given namespace.\nfunc (s roleBindingNamespaceLister) List(selector labels.Selector) (ret []*v1.RoleBinding, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.RoleBinding))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100028031,"name":"Get","signature":"func (s roleBindingNamespaceLister) Get(name string) (*v1.RoleBinding, error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1/rolebinding.go","code":"// Get retrieves the RoleBinding from the indexer for a given namespace and name.\nfunc (s roleBindingNamespaceLister) Get(name string) (*v1.RoleBinding, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"rolebinding\"), name)\n\t}\n\treturn obj.(*v1.RoleBinding), nil\n}","line":{"from":89,"to":99}} {"id":100028032,"name":"NewClusterRoleLister","signature":"func NewClusterRoleLister(indexer cache.Indexer) ClusterRoleLister","file":"staging/src/k8s.io/client-go/listers/rbac/v1alpha1/clusterrole.go","code":"// NewClusterRoleLister returns a new ClusterRoleLister.\nfunc NewClusterRoleLister(indexer cache.Indexer) ClusterRoleLister {\n\treturn \u0026clusterRoleLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100028033,"name":"List","signature":"func (s *clusterRoleLister) List(selector labels.Selector) (ret []*v1alpha1.ClusterRole, err error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1alpha1/clusterrole.go","code":"// List lists all ClusterRoles in the indexer.\nfunc (s *clusterRoleLister) List(selector labels.Selector) (ret []*v1alpha1.ClusterRole, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ClusterRole))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100028034,"name":"Get","signature":"func (s *clusterRoleLister) Get(name string) (*v1alpha1.ClusterRole, error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1alpha1/clusterrole.go","code":"// Get retrieves the ClusterRole from the index for a given name.\nfunc (s *clusterRoleLister) Get(name string) (*v1alpha1.ClusterRole, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"clusterrole\"), name)\n\t}\n\treturn obj.(*v1alpha1.ClusterRole), nil\n}","line":{"from":58,"to":68}} {"id":100028035,"name":"NewClusterRoleBindingLister","signature":"func NewClusterRoleBindingLister(indexer cache.Indexer) ClusterRoleBindingLister","file":"staging/src/k8s.io/client-go/listers/rbac/v1alpha1/clusterrolebinding.go","code":"// NewClusterRoleBindingLister returns a new ClusterRoleBindingLister.\nfunc NewClusterRoleBindingLister(indexer cache.Indexer) ClusterRoleBindingLister {\n\treturn \u0026clusterRoleBindingLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100028036,"name":"List","signature":"func (s *clusterRoleBindingLister) List(selector labels.Selector) (ret []*v1alpha1.ClusterRoleBinding, err error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1alpha1/clusterrolebinding.go","code":"// List lists all ClusterRoleBindings in the indexer.\nfunc (s *clusterRoleBindingLister) List(selector labels.Selector) (ret []*v1alpha1.ClusterRoleBinding, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ClusterRoleBinding))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100028037,"name":"Get","signature":"func (s *clusterRoleBindingLister) Get(name string) (*v1alpha1.ClusterRoleBinding, error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1alpha1/clusterrolebinding.go","code":"// Get retrieves the ClusterRoleBinding from the index for a given name.\nfunc (s *clusterRoleBindingLister) Get(name string) (*v1alpha1.ClusterRoleBinding, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"clusterrolebinding\"), name)\n\t}\n\treturn obj.(*v1alpha1.ClusterRoleBinding), nil\n}","line":{"from":58,"to":68}} {"id":100028038,"name":"NewRoleLister","signature":"func NewRoleLister(indexer cache.Indexer) RoleLister","file":"staging/src/k8s.io/client-go/listers/rbac/v1alpha1/role.go","code":"// NewRoleLister returns a new RoleLister.\nfunc NewRoleLister(indexer cache.Indexer) RoleLister {\n\treturn \u0026roleLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100028039,"name":"List","signature":"func (s *roleLister) List(selector labels.Selector) (ret []*v1alpha1.Role, err error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1alpha1/role.go","code":"// List lists all Roles in the indexer.\nfunc (s *roleLister) List(selector labels.Selector) (ret []*v1alpha1.Role, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Role))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100028040,"name":"Roles","signature":"func (s *roleLister) Roles(namespace string) RoleNamespaceLister","file":"staging/src/k8s.io/client-go/listers/rbac/v1alpha1/role.go","code":"// Roles returns an object that can list and get Roles.\nfunc (s *roleLister) Roles(namespace string) RoleNamespaceLister {\n\treturn roleNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100028041,"name":"List","signature":"func (s roleNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Role, err error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1alpha1/role.go","code":"// List lists all Roles in the indexer for a given namespace.\nfunc (s roleNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Role, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Role))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100028042,"name":"Get","signature":"func (s roleNamespaceLister) Get(name string) (*v1alpha1.Role, error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1alpha1/role.go","code":"// Get retrieves the Role from the indexer for a given namespace and name.\nfunc (s roleNamespaceLister) Get(name string) (*v1alpha1.Role, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"role\"), name)\n\t}\n\treturn obj.(*v1alpha1.Role), nil\n}","line":{"from":89,"to":99}} {"id":100028043,"name":"NewRoleBindingLister","signature":"func NewRoleBindingLister(indexer cache.Indexer) RoleBindingLister","file":"staging/src/k8s.io/client-go/listers/rbac/v1alpha1/rolebinding.go","code":"// NewRoleBindingLister returns a new RoleBindingLister.\nfunc NewRoleBindingLister(indexer cache.Indexer) RoleBindingLister {\n\treturn \u0026roleBindingLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100028044,"name":"List","signature":"func (s *roleBindingLister) List(selector labels.Selector) (ret []*v1alpha1.RoleBinding, err error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1alpha1/rolebinding.go","code":"// List lists all RoleBindings in the indexer.\nfunc (s *roleBindingLister) List(selector labels.Selector) (ret []*v1alpha1.RoleBinding, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.RoleBinding))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100028045,"name":"RoleBindings","signature":"func (s *roleBindingLister) RoleBindings(namespace string) RoleBindingNamespaceLister","file":"staging/src/k8s.io/client-go/listers/rbac/v1alpha1/rolebinding.go","code":"// RoleBindings returns an object that can list and get RoleBindings.\nfunc (s *roleBindingLister) RoleBindings(namespace string) RoleBindingNamespaceLister {\n\treturn roleBindingNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100028046,"name":"List","signature":"func (s roleBindingNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.RoleBinding, err error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1alpha1/rolebinding.go","code":"// List lists all RoleBindings in the indexer for a given namespace.\nfunc (s roleBindingNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.RoleBinding, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.RoleBinding))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100028047,"name":"Get","signature":"func (s roleBindingNamespaceLister) Get(name string) (*v1alpha1.RoleBinding, error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1alpha1/rolebinding.go","code":"// Get retrieves the RoleBinding from the indexer for a given namespace and name.\nfunc (s roleBindingNamespaceLister) Get(name string) (*v1alpha1.RoleBinding, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"rolebinding\"), name)\n\t}\n\treturn obj.(*v1alpha1.RoleBinding), nil\n}","line":{"from":89,"to":99}} {"id":100028048,"name":"NewClusterRoleLister","signature":"func NewClusterRoleLister(indexer cache.Indexer) ClusterRoleLister","file":"staging/src/k8s.io/client-go/listers/rbac/v1beta1/clusterrole.go","code":"// NewClusterRoleLister returns a new ClusterRoleLister.\nfunc NewClusterRoleLister(indexer cache.Indexer) ClusterRoleLister {\n\treturn \u0026clusterRoleLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100028049,"name":"List","signature":"func (s *clusterRoleLister) List(selector labels.Selector) (ret []*v1beta1.ClusterRole, err error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1beta1/clusterrole.go","code":"// List lists all ClusterRoles in the indexer.\nfunc (s *clusterRoleLister) List(selector labels.Selector) (ret []*v1beta1.ClusterRole, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.ClusterRole))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100028050,"name":"Get","signature":"func (s *clusterRoleLister) Get(name string) (*v1beta1.ClusterRole, error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1beta1/clusterrole.go","code":"// Get retrieves the ClusterRole from the index for a given name.\nfunc (s *clusterRoleLister) Get(name string) (*v1beta1.ClusterRole, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"clusterrole\"), name)\n\t}\n\treturn obj.(*v1beta1.ClusterRole), nil\n}","line":{"from":58,"to":68}} {"id":100028051,"name":"NewClusterRoleBindingLister","signature":"func NewClusterRoleBindingLister(indexer cache.Indexer) ClusterRoleBindingLister","file":"staging/src/k8s.io/client-go/listers/rbac/v1beta1/clusterrolebinding.go","code":"// NewClusterRoleBindingLister returns a new ClusterRoleBindingLister.\nfunc NewClusterRoleBindingLister(indexer cache.Indexer) ClusterRoleBindingLister {\n\treturn \u0026clusterRoleBindingLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100028052,"name":"List","signature":"func (s *clusterRoleBindingLister) List(selector labels.Selector) (ret []*v1beta1.ClusterRoleBinding, err error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1beta1/clusterrolebinding.go","code":"// List lists all ClusterRoleBindings in the indexer.\nfunc (s *clusterRoleBindingLister) List(selector labels.Selector) (ret []*v1beta1.ClusterRoleBinding, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.ClusterRoleBinding))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100028053,"name":"Get","signature":"func (s *clusterRoleBindingLister) Get(name string) (*v1beta1.ClusterRoleBinding, error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1beta1/clusterrolebinding.go","code":"// Get retrieves the ClusterRoleBinding from the index for a given name.\nfunc (s *clusterRoleBindingLister) Get(name string) (*v1beta1.ClusterRoleBinding, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"clusterrolebinding\"), name)\n\t}\n\treturn obj.(*v1beta1.ClusterRoleBinding), nil\n}","line":{"from":58,"to":68}} {"id":100028054,"name":"NewRoleLister","signature":"func NewRoleLister(indexer cache.Indexer) RoleLister","file":"staging/src/k8s.io/client-go/listers/rbac/v1beta1/role.go","code":"// NewRoleLister returns a new RoleLister.\nfunc NewRoleLister(indexer cache.Indexer) RoleLister {\n\treturn \u0026roleLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100028055,"name":"List","signature":"func (s *roleLister) List(selector labels.Selector) (ret []*v1beta1.Role, err error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1beta1/role.go","code":"// List lists all Roles in the indexer.\nfunc (s *roleLister) List(selector labels.Selector) (ret []*v1beta1.Role, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.Role))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100028056,"name":"Roles","signature":"func (s *roleLister) Roles(namespace string) RoleNamespaceLister","file":"staging/src/k8s.io/client-go/listers/rbac/v1beta1/role.go","code":"// Roles returns an object that can list and get Roles.\nfunc (s *roleLister) Roles(namespace string) RoleNamespaceLister {\n\treturn roleNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100028057,"name":"List","signature":"func (s roleNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.Role, err error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1beta1/role.go","code":"// List lists all Roles in the indexer for a given namespace.\nfunc (s roleNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.Role, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.Role))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100028058,"name":"Get","signature":"func (s roleNamespaceLister) Get(name string) (*v1beta1.Role, error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1beta1/role.go","code":"// Get retrieves the Role from the indexer for a given namespace and name.\nfunc (s roleNamespaceLister) Get(name string) (*v1beta1.Role, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"role\"), name)\n\t}\n\treturn obj.(*v1beta1.Role), nil\n}","line":{"from":89,"to":99}} {"id":100028059,"name":"NewRoleBindingLister","signature":"func NewRoleBindingLister(indexer cache.Indexer) RoleBindingLister","file":"staging/src/k8s.io/client-go/listers/rbac/v1beta1/rolebinding.go","code":"// NewRoleBindingLister returns a new RoleBindingLister.\nfunc NewRoleBindingLister(indexer cache.Indexer) RoleBindingLister {\n\treturn \u0026roleBindingLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100028060,"name":"List","signature":"func (s *roleBindingLister) List(selector labels.Selector) (ret []*v1beta1.RoleBinding, err error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1beta1/rolebinding.go","code":"// List lists all RoleBindings in the indexer.\nfunc (s *roleBindingLister) List(selector labels.Selector) (ret []*v1beta1.RoleBinding, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.RoleBinding))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100028061,"name":"RoleBindings","signature":"func (s *roleBindingLister) RoleBindings(namespace string) RoleBindingNamespaceLister","file":"staging/src/k8s.io/client-go/listers/rbac/v1beta1/rolebinding.go","code":"// RoleBindings returns an object that can list and get RoleBindings.\nfunc (s *roleBindingLister) RoleBindings(namespace string) RoleBindingNamespaceLister {\n\treturn roleBindingNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100028062,"name":"List","signature":"func (s roleBindingNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.RoleBinding, err error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1beta1/rolebinding.go","code":"// List lists all RoleBindings in the indexer for a given namespace.\nfunc (s roleBindingNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.RoleBinding, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.RoleBinding))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100028063,"name":"Get","signature":"func (s roleBindingNamespaceLister) Get(name string) (*v1beta1.RoleBinding, error)","file":"staging/src/k8s.io/client-go/listers/rbac/v1beta1/rolebinding.go","code":"// Get retrieves the RoleBinding from the indexer for a given namespace and name.\nfunc (s roleBindingNamespaceLister) Get(name string) (*v1beta1.RoleBinding, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"rolebinding\"), name)\n\t}\n\treturn obj.(*v1beta1.RoleBinding), nil\n}","line":{"from":89,"to":99}} {"id":100028064,"name":"NewPodSchedulingContextLister","signature":"func NewPodSchedulingContextLister(indexer cache.Indexer) PodSchedulingContextLister","file":"staging/src/k8s.io/client-go/listers/resource/v1alpha2/podschedulingcontext.go","code":"// NewPodSchedulingContextLister returns a new PodSchedulingContextLister.\nfunc NewPodSchedulingContextLister(indexer cache.Indexer) PodSchedulingContextLister {\n\treturn \u0026podSchedulingContextLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100028065,"name":"List","signature":"func (s *podSchedulingContextLister) List(selector labels.Selector) (ret []*v1alpha2.PodSchedulingContext, err error)","file":"staging/src/k8s.io/client-go/listers/resource/v1alpha2/podschedulingcontext.go","code":"// List lists all PodSchedulingContexts in the indexer.\nfunc (s *podSchedulingContextLister) List(selector labels.Selector) (ret []*v1alpha2.PodSchedulingContext, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha2.PodSchedulingContext))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100028066,"name":"PodSchedulingContexts","signature":"func (s *podSchedulingContextLister) PodSchedulingContexts(namespace string) PodSchedulingContextNamespaceLister","file":"staging/src/k8s.io/client-go/listers/resource/v1alpha2/podschedulingcontext.go","code":"// PodSchedulingContexts returns an object that can list and get PodSchedulingContexts.\nfunc (s *podSchedulingContextLister) PodSchedulingContexts(namespace string) PodSchedulingContextNamespaceLister {\n\treturn podSchedulingContextNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100028067,"name":"List","signature":"func (s podSchedulingContextNamespaceLister) List(selector labels.Selector) (ret []*v1alpha2.PodSchedulingContext, err error)","file":"staging/src/k8s.io/client-go/listers/resource/v1alpha2/podschedulingcontext.go","code":"// List lists all PodSchedulingContexts in the indexer for a given namespace.\nfunc (s podSchedulingContextNamespaceLister) List(selector labels.Selector) (ret []*v1alpha2.PodSchedulingContext, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha2.PodSchedulingContext))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100028068,"name":"Get","signature":"func (s podSchedulingContextNamespaceLister) Get(name string) (*v1alpha2.PodSchedulingContext, error)","file":"staging/src/k8s.io/client-go/listers/resource/v1alpha2/podschedulingcontext.go","code":"// Get retrieves the PodSchedulingContext from the indexer for a given namespace and name.\nfunc (s podSchedulingContextNamespaceLister) Get(name string) (*v1alpha2.PodSchedulingContext, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha2.Resource(\"podschedulingcontext\"), name)\n\t}\n\treturn obj.(*v1alpha2.PodSchedulingContext), nil\n}","line":{"from":89,"to":99}} {"id":100028069,"name":"NewResourceClaimLister","signature":"func NewResourceClaimLister(indexer cache.Indexer) ResourceClaimLister","file":"staging/src/k8s.io/client-go/listers/resource/v1alpha2/resourceclaim.go","code":"// NewResourceClaimLister returns a new ResourceClaimLister.\nfunc NewResourceClaimLister(indexer cache.Indexer) ResourceClaimLister {\n\treturn \u0026resourceClaimLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100028070,"name":"List","signature":"func (s *resourceClaimLister) List(selector labels.Selector) (ret []*v1alpha2.ResourceClaim, err error)","file":"staging/src/k8s.io/client-go/listers/resource/v1alpha2/resourceclaim.go","code":"// List lists all ResourceClaims in the indexer.\nfunc (s *resourceClaimLister) List(selector labels.Selector) (ret []*v1alpha2.ResourceClaim, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha2.ResourceClaim))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100028071,"name":"ResourceClaims","signature":"func (s *resourceClaimLister) ResourceClaims(namespace string) ResourceClaimNamespaceLister","file":"staging/src/k8s.io/client-go/listers/resource/v1alpha2/resourceclaim.go","code":"// ResourceClaims returns an object that can list and get ResourceClaims.\nfunc (s *resourceClaimLister) ResourceClaims(namespace string) ResourceClaimNamespaceLister {\n\treturn resourceClaimNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100028072,"name":"List","signature":"func (s resourceClaimNamespaceLister) List(selector labels.Selector) (ret []*v1alpha2.ResourceClaim, err error)","file":"staging/src/k8s.io/client-go/listers/resource/v1alpha2/resourceclaim.go","code":"// List lists all ResourceClaims in the indexer for a given namespace.\nfunc (s resourceClaimNamespaceLister) List(selector labels.Selector) (ret []*v1alpha2.ResourceClaim, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha2.ResourceClaim))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100028073,"name":"Get","signature":"func (s resourceClaimNamespaceLister) Get(name string) (*v1alpha2.ResourceClaim, error)","file":"staging/src/k8s.io/client-go/listers/resource/v1alpha2/resourceclaim.go","code":"// Get retrieves the ResourceClaim from the indexer for a given namespace and name.\nfunc (s resourceClaimNamespaceLister) Get(name string) (*v1alpha2.ResourceClaim, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha2.Resource(\"resourceclaim\"), name)\n\t}\n\treturn obj.(*v1alpha2.ResourceClaim), nil\n}","line":{"from":89,"to":99}} {"id":100028074,"name":"NewResourceClaimTemplateLister","signature":"func NewResourceClaimTemplateLister(indexer cache.Indexer) ResourceClaimTemplateLister","file":"staging/src/k8s.io/client-go/listers/resource/v1alpha2/resourceclaimtemplate.go","code":"// NewResourceClaimTemplateLister returns a new ResourceClaimTemplateLister.\nfunc NewResourceClaimTemplateLister(indexer cache.Indexer) ResourceClaimTemplateLister {\n\treturn \u0026resourceClaimTemplateLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100028075,"name":"List","signature":"func (s *resourceClaimTemplateLister) List(selector labels.Selector) (ret []*v1alpha2.ResourceClaimTemplate, err error)","file":"staging/src/k8s.io/client-go/listers/resource/v1alpha2/resourceclaimtemplate.go","code":"// List lists all ResourceClaimTemplates in the indexer.\nfunc (s *resourceClaimTemplateLister) List(selector labels.Selector) (ret []*v1alpha2.ResourceClaimTemplate, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha2.ResourceClaimTemplate))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100028076,"name":"ResourceClaimTemplates","signature":"func (s *resourceClaimTemplateLister) ResourceClaimTemplates(namespace string) ResourceClaimTemplateNamespaceLister","file":"staging/src/k8s.io/client-go/listers/resource/v1alpha2/resourceclaimtemplate.go","code":"// ResourceClaimTemplates returns an object that can list and get ResourceClaimTemplates.\nfunc (s *resourceClaimTemplateLister) ResourceClaimTemplates(namespace string) ResourceClaimTemplateNamespaceLister {\n\treturn resourceClaimTemplateNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100028077,"name":"List","signature":"func (s resourceClaimTemplateNamespaceLister) List(selector labels.Selector) (ret []*v1alpha2.ResourceClaimTemplate, err error)","file":"staging/src/k8s.io/client-go/listers/resource/v1alpha2/resourceclaimtemplate.go","code":"// List lists all ResourceClaimTemplates in the indexer for a given namespace.\nfunc (s resourceClaimTemplateNamespaceLister) List(selector labels.Selector) (ret []*v1alpha2.ResourceClaimTemplate, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha2.ResourceClaimTemplate))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100028078,"name":"Get","signature":"func (s resourceClaimTemplateNamespaceLister) Get(name string) (*v1alpha2.ResourceClaimTemplate, error)","file":"staging/src/k8s.io/client-go/listers/resource/v1alpha2/resourceclaimtemplate.go","code":"// Get retrieves the ResourceClaimTemplate from the indexer for a given namespace and name.\nfunc (s resourceClaimTemplateNamespaceLister) Get(name string) (*v1alpha2.ResourceClaimTemplate, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha2.Resource(\"resourceclaimtemplate\"), name)\n\t}\n\treturn obj.(*v1alpha2.ResourceClaimTemplate), nil\n}","line":{"from":89,"to":99}} {"id":100028079,"name":"NewResourceClassLister","signature":"func NewResourceClassLister(indexer cache.Indexer) ResourceClassLister","file":"staging/src/k8s.io/client-go/listers/resource/v1alpha2/resourceclass.go","code":"// NewResourceClassLister returns a new ResourceClassLister.\nfunc NewResourceClassLister(indexer cache.Indexer) ResourceClassLister {\n\treturn \u0026resourceClassLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100028080,"name":"List","signature":"func (s *resourceClassLister) List(selector labels.Selector) (ret []*v1alpha2.ResourceClass, err error)","file":"staging/src/k8s.io/client-go/listers/resource/v1alpha2/resourceclass.go","code":"// List lists all ResourceClasses in the indexer.\nfunc (s *resourceClassLister) List(selector labels.Selector) (ret []*v1alpha2.ResourceClass, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha2.ResourceClass))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100028081,"name":"Get","signature":"func (s *resourceClassLister) Get(name string) (*v1alpha2.ResourceClass, error)","file":"staging/src/k8s.io/client-go/listers/resource/v1alpha2/resourceclass.go","code":"// Get retrieves the ResourceClass from the index for a given name.\nfunc (s *resourceClassLister) Get(name string) (*v1alpha2.ResourceClass, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha2.Resource(\"resourceclass\"), name)\n\t}\n\treturn obj.(*v1alpha2.ResourceClass), nil\n}","line":{"from":58,"to":68}} {"id":100028082,"name":"NewPriorityClassLister","signature":"func NewPriorityClassLister(indexer cache.Indexer) PriorityClassLister","file":"staging/src/k8s.io/client-go/listers/scheduling/v1/priorityclass.go","code":"// NewPriorityClassLister returns a new PriorityClassLister.\nfunc NewPriorityClassLister(indexer cache.Indexer) PriorityClassLister {\n\treturn \u0026priorityClassLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100028083,"name":"List","signature":"func (s *priorityClassLister) List(selector labels.Selector) (ret []*v1.PriorityClass, err error)","file":"staging/src/k8s.io/client-go/listers/scheduling/v1/priorityclass.go","code":"// List lists all PriorityClasses in the indexer.\nfunc (s *priorityClassLister) List(selector labels.Selector) (ret []*v1.PriorityClass, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.PriorityClass))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100028084,"name":"Get","signature":"func (s *priorityClassLister) Get(name string) (*v1.PriorityClass, error)","file":"staging/src/k8s.io/client-go/listers/scheduling/v1/priorityclass.go","code":"// Get retrieves the PriorityClass from the index for a given name.\nfunc (s *priorityClassLister) Get(name string) (*v1.PriorityClass, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"priorityclass\"), name)\n\t}\n\treturn obj.(*v1.PriorityClass), nil\n}","line":{"from":58,"to":68}} {"id":100028085,"name":"NewPriorityClassLister","signature":"func NewPriorityClassLister(indexer cache.Indexer) PriorityClassLister","file":"staging/src/k8s.io/client-go/listers/scheduling/v1alpha1/priorityclass.go","code":"// NewPriorityClassLister returns a new PriorityClassLister.\nfunc NewPriorityClassLister(indexer cache.Indexer) PriorityClassLister {\n\treturn \u0026priorityClassLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100028086,"name":"List","signature":"func (s *priorityClassLister) List(selector labels.Selector) (ret []*v1alpha1.PriorityClass, err error)","file":"staging/src/k8s.io/client-go/listers/scheduling/v1alpha1/priorityclass.go","code":"// List lists all PriorityClasses in the indexer.\nfunc (s *priorityClassLister) List(selector labels.Selector) (ret []*v1alpha1.PriorityClass, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.PriorityClass))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100028087,"name":"Get","signature":"func (s *priorityClassLister) Get(name string) (*v1alpha1.PriorityClass, error)","file":"staging/src/k8s.io/client-go/listers/scheduling/v1alpha1/priorityclass.go","code":"// Get retrieves the PriorityClass from the index for a given name.\nfunc (s *priorityClassLister) Get(name string) (*v1alpha1.PriorityClass, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"priorityclass\"), name)\n\t}\n\treturn obj.(*v1alpha1.PriorityClass), nil\n}","line":{"from":58,"to":68}} {"id":100028088,"name":"NewPriorityClassLister","signature":"func NewPriorityClassLister(indexer cache.Indexer) PriorityClassLister","file":"staging/src/k8s.io/client-go/listers/scheduling/v1beta1/priorityclass.go","code":"// NewPriorityClassLister returns a new PriorityClassLister.\nfunc NewPriorityClassLister(indexer cache.Indexer) PriorityClassLister {\n\treturn \u0026priorityClassLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100028089,"name":"List","signature":"func (s *priorityClassLister) List(selector labels.Selector) (ret []*v1beta1.PriorityClass, err error)","file":"staging/src/k8s.io/client-go/listers/scheduling/v1beta1/priorityclass.go","code":"// List lists all PriorityClasses in the indexer.\nfunc (s *priorityClassLister) List(selector labels.Selector) (ret []*v1beta1.PriorityClass, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.PriorityClass))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100028090,"name":"Get","signature":"func (s *priorityClassLister) Get(name string) (*v1beta1.PriorityClass, error)","file":"staging/src/k8s.io/client-go/listers/scheduling/v1beta1/priorityclass.go","code":"// Get retrieves the PriorityClass from the index for a given name.\nfunc (s *priorityClassLister) Get(name string) (*v1beta1.PriorityClass, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"priorityclass\"), name)\n\t}\n\treturn obj.(*v1beta1.PriorityClass), nil\n}","line":{"from":58,"to":68}} {"id":100028091,"name":"NewCSIDriverLister","signature":"func NewCSIDriverLister(indexer cache.Indexer) CSIDriverLister","file":"staging/src/k8s.io/client-go/listers/storage/v1/csidriver.go","code":"// NewCSIDriverLister returns a new CSIDriverLister.\nfunc NewCSIDriverLister(indexer cache.Indexer) CSIDriverLister {\n\treturn \u0026cSIDriverLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100028092,"name":"List","signature":"func (s *cSIDriverLister) List(selector labels.Selector) (ret []*v1.CSIDriver, err error)","file":"staging/src/k8s.io/client-go/listers/storage/v1/csidriver.go","code":"// List lists all CSIDrivers in the indexer.\nfunc (s *cSIDriverLister) List(selector labels.Selector) (ret []*v1.CSIDriver, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.CSIDriver))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100028093,"name":"Get","signature":"func (s *cSIDriverLister) Get(name string) (*v1.CSIDriver, error)","file":"staging/src/k8s.io/client-go/listers/storage/v1/csidriver.go","code":"// Get retrieves the CSIDriver from the index for a given name.\nfunc (s *cSIDriverLister) Get(name string) (*v1.CSIDriver, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"csidriver\"), name)\n\t}\n\treturn obj.(*v1.CSIDriver), nil\n}","line":{"from":58,"to":68}} {"id":100028094,"name":"NewCSINodeLister","signature":"func NewCSINodeLister(indexer cache.Indexer) CSINodeLister","file":"staging/src/k8s.io/client-go/listers/storage/v1/csinode.go","code":"// NewCSINodeLister returns a new CSINodeLister.\nfunc NewCSINodeLister(indexer cache.Indexer) CSINodeLister {\n\treturn \u0026cSINodeLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100028095,"name":"List","signature":"func (s *cSINodeLister) List(selector labels.Selector) (ret []*v1.CSINode, err error)","file":"staging/src/k8s.io/client-go/listers/storage/v1/csinode.go","code":"// List lists all CSINodes in the indexer.\nfunc (s *cSINodeLister) List(selector labels.Selector) (ret []*v1.CSINode, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.CSINode))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100028096,"name":"Get","signature":"func (s *cSINodeLister) Get(name string) (*v1.CSINode, error)","file":"staging/src/k8s.io/client-go/listers/storage/v1/csinode.go","code":"// Get retrieves the CSINode from the index for a given name.\nfunc (s *cSINodeLister) Get(name string) (*v1.CSINode, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"csinode\"), name)\n\t}\n\treturn obj.(*v1.CSINode), nil\n}","line":{"from":58,"to":68}} {"id":100028097,"name":"NewCSIStorageCapacityLister","signature":"func NewCSIStorageCapacityLister(indexer cache.Indexer) CSIStorageCapacityLister","file":"staging/src/k8s.io/client-go/listers/storage/v1/csistoragecapacity.go","code":"// NewCSIStorageCapacityLister returns a new CSIStorageCapacityLister.\nfunc NewCSIStorageCapacityLister(indexer cache.Indexer) CSIStorageCapacityLister {\n\treturn \u0026cSIStorageCapacityLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100028098,"name":"List","signature":"func (s *cSIStorageCapacityLister) List(selector labels.Selector) (ret []*v1.CSIStorageCapacity, err error)","file":"staging/src/k8s.io/client-go/listers/storage/v1/csistoragecapacity.go","code":"// List lists all CSIStorageCapacities in the indexer.\nfunc (s *cSIStorageCapacityLister) List(selector labels.Selector) (ret []*v1.CSIStorageCapacity, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.CSIStorageCapacity))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100028099,"name":"CSIStorageCapacities","signature":"func (s *cSIStorageCapacityLister) CSIStorageCapacities(namespace string) CSIStorageCapacityNamespaceLister","file":"staging/src/k8s.io/client-go/listers/storage/v1/csistoragecapacity.go","code":"// CSIStorageCapacities returns an object that can list and get CSIStorageCapacities.\nfunc (s *cSIStorageCapacityLister) CSIStorageCapacities(namespace string) CSIStorageCapacityNamespaceLister {\n\treturn cSIStorageCapacityNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100028100,"name":"List","signature":"func (s cSIStorageCapacityNamespaceLister) List(selector labels.Selector) (ret []*v1.CSIStorageCapacity, err error)","file":"staging/src/k8s.io/client-go/listers/storage/v1/csistoragecapacity.go","code":"// List lists all CSIStorageCapacities in the indexer for a given namespace.\nfunc (s cSIStorageCapacityNamespaceLister) List(selector labels.Selector) (ret []*v1.CSIStorageCapacity, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.CSIStorageCapacity))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100028101,"name":"Get","signature":"func (s cSIStorageCapacityNamespaceLister) Get(name string) (*v1.CSIStorageCapacity, error)","file":"staging/src/k8s.io/client-go/listers/storage/v1/csistoragecapacity.go","code":"// Get retrieves the CSIStorageCapacity from the indexer for a given namespace and name.\nfunc (s cSIStorageCapacityNamespaceLister) Get(name string) (*v1.CSIStorageCapacity, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"csistoragecapacity\"), name)\n\t}\n\treturn obj.(*v1.CSIStorageCapacity), nil\n}","line":{"from":89,"to":99}} {"id":100028102,"name":"NewStorageClassLister","signature":"func NewStorageClassLister(indexer cache.Indexer) StorageClassLister","file":"staging/src/k8s.io/client-go/listers/storage/v1/storageclass.go","code":"// NewStorageClassLister returns a new StorageClassLister.\nfunc NewStorageClassLister(indexer cache.Indexer) StorageClassLister {\n\treturn \u0026storageClassLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100028103,"name":"List","signature":"func (s *storageClassLister) List(selector labels.Selector) (ret []*v1.StorageClass, err error)","file":"staging/src/k8s.io/client-go/listers/storage/v1/storageclass.go","code":"// List lists all StorageClasses in the indexer.\nfunc (s *storageClassLister) List(selector labels.Selector) (ret []*v1.StorageClass, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.StorageClass))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100028104,"name":"Get","signature":"func (s *storageClassLister) Get(name string) (*v1.StorageClass, error)","file":"staging/src/k8s.io/client-go/listers/storage/v1/storageclass.go","code":"// Get retrieves the StorageClass from the index for a given name.\nfunc (s *storageClassLister) Get(name string) (*v1.StorageClass, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"storageclass\"), name)\n\t}\n\treturn obj.(*v1.StorageClass), nil\n}","line":{"from":58,"to":68}} {"id":100028105,"name":"NewVolumeAttachmentLister","signature":"func NewVolumeAttachmentLister(indexer cache.Indexer) VolumeAttachmentLister","file":"staging/src/k8s.io/client-go/listers/storage/v1/volumeattachment.go","code":"// NewVolumeAttachmentLister returns a new VolumeAttachmentLister.\nfunc NewVolumeAttachmentLister(indexer cache.Indexer) VolumeAttachmentLister {\n\treturn \u0026volumeAttachmentLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100028106,"name":"List","signature":"func (s *volumeAttachmentLister) List(selector labels.Selector) (ret []*v1.VolumeAttachment, err error)","file":"staging/src/k8s.io/client-go/listers/storage/v1/volumeattachment.go","code":"// List lists all VolumeAttachments in the indexer.\nfunc (s *volumeAttachmentLister) List(selector labels.Selector) (ret []*v1.VolumeAttachment, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.VolumeAttachment))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100028107,"name":"Get","signature":"func (s *volumeAttachmentLister) Get(name string) (*v1.VolumeAttachment, error)","file":"staging/src/k8s.io/client-go/listers/storage/v1/volumeattachment.go","code":"// Get retrieves the VolumeAttachment from the index for a given name.\nfunc (s *volumeAttachmentLister) Get(name string) (*v1.VolumeAttachment, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"volumeattachment\"), name)\n\t}\n\treturn obj.(*v1.VolumeAttachment), nil\n}","line":{"from":58,"to":68}} {"id":100028108,"name":"NewCSIStorageCapacityLister","signature":"func NewCSIStorageCapacityLister(indexer cache.Indexer) CSIStorageCapacityLister","file":"staging/src/k8s.io/client-go/listers/storage/v1alpha1/csistoragecapacity.go","code":"// NewCSIStorageCapacityLister returns a new CSIStorageCapacityLister.\nfunc NewCSIStorageCapacityLister(indexer cache.Indexer) CSIStorageCapacityLister {\n\treturn \u0026cSIStorageCapacityLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100028109,"name":"List","signature":"func (s *cSIStorageCapacityLister) List(selector labels.Selector) (ret []*v1alpha1.CSIStorageCapacity, err error)","file":"staging/src/k8s.io/client-go/listers/storage/v1alpha1/csistoragecapacity.go","code":"// List lists all CSIStorageCapacities in the indexer.\nfunc (s *cSIStorageCapacityLister) List(selector labels.Selector) (ret []*v1alpha1.CSIStorageCapacity, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.CSIStorageCapacity))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100028110,"name":"CSIStorageCapacities","signature":"func (s *cSIStorageCapacityLister) CSIStorageCapacities(namespace string) CSIStorageCapacityNamespaceLister","file":"staging/src/k8s.io/client-go/listers/storage/v1alpha1/csistoragecapacity.go","code":"// CSIStorageCapacities returns an object that can list and get CSIStorageCapacities.\nfunc (s *cSIStorageCapacityLister) CSIStorageCapacities(namespace string) CSIStorageCapacityNamespaceLister {\n\treturn cSIStorageCapacityNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100028111,"name":"List","signature":"func (s cSIStorageCapacityNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.CSIStorageCapacity, err error)","file":"staging/src/k8s.io/client-go/listers/storage/v1alpha1/csistoragecapacity.go","code":"// List lists all CSIStorageCapacities in the indexer for a given namespace.\nfunc (s cSIStorageCapacityNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.CSIStorageCapacity, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.CSIStorageCapacity))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100028112,"name":"Get","signature":"func (s cSIStorageCapacityNamespaceLister) Get(name string) (*v1alpha1.CSIStorageCapacity, error)","file":"staging/src/k8s.io/client-go/listers/storage/v1alpha1/csistoragecapacity.go","code":"// Get retrieves the CSIStorageCapacity from the indexer for a given namespace and name.\nfunc (s cSIStorageCapacityNamespaceLister) Get(name string) (*v1alpha1.CSIStorageCapacity, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"csistoragecapacity\"), name)\n\t}\n\treturn obj.(*v1alpha1.CSIStorageCapacity), nil\n}","line":{"from":89,"to":99}} {"id":100028113,"name":"NewVolumeAttachmentLister","signature":"func NewVolumeAttachmentLister(indexer cache.Indexer) VolumeAttachmentLister","file":"staging/src/k8s.io/client-go/listers/storage/v1alpha1/volumeattachment.go","code":"// NewVolumeAttachmentLister returns a new VolumeAttachmentLister.\nfunc NewVolumeAttachmentLister(indexer cache.Indexer) VolumeAttachmentLister {\n\treturn \u0026volumeAttachmentLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100028114,"name":"List","signature":"func (s *volumeAttachmentLister) List(selector labels.Selector) (ret []*v1alpha1.VolumeAttachment, err error)","file":"staging/src/k8s.io/client-go/listers/storage/v1alpha1/volumeattachment.go","code":"// List lists all VolumeAttachments in the indexer.\nfunc (s *volumeAttachmentLister) List(selector labels.Selector) (ret []*v1alpha1.VolumeAttachment, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.VolumeAttachment))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100028115,"name":"Get","signature":"func (s *volumeAttachmentLister) Get(name string) (*v1alpha1.VolumeAttachment, error)","file":"staging/src/k8s.io/client-go/listers/storage/v1alpha1/volumeattachment.go","code":"// Get retrieves the VolumeAttachment from the index for a given name.\nfunc (s *volumeAttachmentLister) Get(name string) (*v1alpha1.VolumeAttachment, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"volumeattachment\"), name)\n\t}\n\treturn obj.(*v1alpha1.VolumeAttachment), nil\n}","line":{"from":58,"to":68}} {"id":100028116,"name":"NewCSIDriverLister","signature":"func NewCSIDriverLister(indexer cache.Indexer) CSIDriverLister","file":"staging/src/k8s.io/client-go/listers/storage/v1beta1/csidriver.go","code":"// NewCSIDriverLister returns a new CSIDriverLister.\nfunc NewCSIDriverLister(indexer cache.Indexer) CSIDriverLister {\n\treturn \u0026cSIDriverLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100028117,"name":"List","signature":"func (s *cSIDriverLister) List(selector labels.Selector) (ret []*v1beta1.CSIDriver, err error)","file":"staging/src/k8s.io/client-go/listers/storage/v1beta1/csidriver.go","code":"// List lists all CSIDrivers in the indexer.\nfunc (s *cSIDriverLister) List(selector labels.Selector) (ret []*v1beta1.CSIDriver, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.CSIDriver))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100028118,"name":"Get","signature":"func (s *cSIDriverLister) Get(name string) (*v1beta1.CSIDriver, error)","file":"staging/src/k8s.io/client-go/listers/storage/v1beta1/csidriver.go","code":"// Get retrieves the CSIDriver from the index for a given name.\nfunc (s *cSIDriverLister) Get(name string) (*v1beta1.CSIDriver, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"csidriver\"), name)\n\t}\n\treturn obj.(*v1beta1.CSIDriver), nil\n}","line":{"from":58,"to":68}} {"id":100028119,"name":"NewCSINodeLister","signature":"func NewCSINodeLister(indexer cache.Indexer) CSINodeLister","file":"staging/src/k8s.io/client-go/listers/storage/v1beta1/csinode.go","code":"// NewCSINodeLister returns a new CSINodeLister.\nfunc NewCSINodeLister(indexer cache.Indexer) CSINodeLister {\n\treturn \u0026cSINodeLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100028120,"name":"List","signature":"func (s *cSINodeLister) List(selector labels.Selector) (ret []*v1beta1.CSINode, err error)","file":"staging/src/k8s.io/client-go/listers/storage/v1beta1/csinode.go","code":"// List lists all CSINodes in the indexer.\nfunc (s *cSINodeLister) List(selector labels.Selector) (ret []*v1beta1.CSINode, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.CSINode))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100028121,"name":"Get","signature":"func (s *cSINodeLister) Get(name string) (*v1beta1.CSINode, error)","file":"staging/src/k8s.io/client-go/listers/storage/v1beta1/csinode.go","code":"// Get retrieves the CSINode from the index for a given name.\nfunc (s *cSINodeLister) Get(name string) (*v1beta1.CSINode, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"csinode\"), name)\n\t}\n\treturn obj.(*v1beta1.CSINode), nil\n}","line":{"from":58,"to":68}} {"id":100028122,"name":"NewCSIStorageCapacityLister","signature":"func NewCSIStorageCapacityLister(indexer cache.Indexer) CSIStorageCapacityLister","file":"staging/src/k8s.io/client-go/listers/storage/v1beta1/csistoragecapacity.go","code":"// NewCSIStorageCapacityLister returns a new CSIStorageCapacityLister.\nfunc NewCSIStorageCapacityLister(indexer cache.Indexer) CSIStorageCapacityLister {\n\treturn \u0026cSIStorageCapacityLister{indexer: indexer}\n}","line":{"from":44,"to":47}} {"id":100028123,"name":"List","signature":"func (s *cSIStorageCapacityLister) List(selector labels.Selector) (ret []*v1beta1.CSIStorageCapacity, err error)","file":"staging/src/k8s.io/client-go/listers/storage/v1beta1/csistoragecapacity.go","code":"// List lists all CSIStorageCapacities in the indexer.\nfunc (s *cSIStorageCapacityLister) List(selector labels.Selector) (ret []*v1beta1.CSIStorageCapacity, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.CSIStorageCapacity))\n\t})\n\treturn ret, err\n}","line":{"from":49,"to":55}} {"id":100028124,"name":"CSIStorageCapacities","signature":"func (s *cSIStorageCapacityLister) CSIStorageCapacities(namespace string) CSIStorageCapacityNamespaceLister","file":"staging/src/k8s.io/client-go/listers/storage/v1beta1/csistoragecapacity.go","code":"// CSIStorageCapacities returns an object that can list and get CSIStorageCapacities.\nfunc (s *cSIStorageCapacityLister) CSIStorageCapacities(namespace string) CSIStorageCapacityNamespaceLister {\n\treturn cSIStorageCapacityNamespaceLister{indexer: s.indexer, namespace: namespace}\n}","line":{"from":57,"to":60}} {"id":100028125,"name":"List","signature":"func (s cSIStorageCapacityNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.CSIStorageCapacity, err error)","file":"staging/src/k8s.io/client-go/listers/storage/v1beta1/csistoragecapacity.go","code":"// List lists all CSIStorageCapacities in the indexer for a given namespace.\nfunc (s cSIStorageCapacityNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.CSIStorageCapacity, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.CSIStorageCapacity))\n\t})\n\treturn ret, err\n}","line":{"from":81,"to":87}} {"id":100028126,"name":"Get","signature":"func (s cSIStorageCapacityNamespaceLister) Get(name string) (*v1beta1.CSIStorageCapacity, error)","file":"staging/src/k8s.io/client-go/listers/storage/v1beta1/csistoragecapacity.go","code":"// Get retrieves the CSIStorageCapacity from the indexer for a given namespace and name.\nfunc (s cSIStorageCapacityNamespaceLister) Get(name string) (*v1beta1.CSIStorageCapacity, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"csistoragecapacity\"), name)\n\t}\n\treturn obj.(*v1beta1.CSIStorageCapacity), nil\n}","line":{"from":89,"to":99}} {"id":100028127,"name":"NewStorageClassLister","signature":"func NewStorageClassLister(indexer cache.Indexer) StorageClassLister","file":"staging/src/k8s.io/client-go/listers/storage/v1beta1/storageclass.go","code":"// NewStorageClassLister returns a new StorageClassLister.\nfunc NewStorageClassLister(indexer cache.Indexer) StorageClassLister {\n\treturn \u0026storageClassLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100028128,"name":"List","signature":"func (s *storageClassLister) List(selector labels.Selector) (ret []*v1beta1.StorageClass, err error)","file":"staging/src/k8s.io/client-go/listers/storage/v1beta1/storageclass.go","code":"// List lists all StorageClasses in the indexer.\nfunc (s *storageClassLister) List(selector labels.Selector) (ret []*v1beta1.StorageClass, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.StorageClass))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100028129,"name":"Get","signature":"func (s *storageClassLister) Get(name string) (*v1beta1.StorageClass, error)","file":"staging/src/k8s.io/client-go/listers/storage/v1beta1/storageclass.go","code":"// Get retrieves the StorageClass from the index for a given name.\nfunc (s *storageClassLister) Get(name string) (*v1beta1.StorageClass, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"storageclass\"), name)\n\t}\n\treturn obj.(*v1beta1.StorageClass), nil\n}","line":{"from":58,"to":68}} {"id":100028130,"name":"NewVolumeAttachmentLister","signature":"func NewVolumeAttachmentLister(indexer cache.Indexer) VolumeAttachmentLister","file":"staging/src/k8s.io/client-go/listers/storage/v1beta1/volumeattachment.go","code":"// NewVolumeAttachmentLister returns a new VolumeAttachmentLister.\nfunc NewVolumeAttachmentLister(indexer cache.Indexer) VolumeAttachmentLister {\n\treturn \u0026volumeAttachmentLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100028131,"name":"List","signature":"func (s *volumeAttachmentLister) List(selector labels.Selector) (ret []*v1beta1.VolumeAttachment, err error)","file":"staging/src/k8s.io/client-go/listers/storage/v1beta1/volumeattachment.go","code":"// List lists all VolumeAttachments in the indexer.\nfunc (s *volumeAttachmentLister) List(selector labels.Selector) (ret []*v1beta1.VolumeAttachment, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.VolumeAttachment))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100028132,"name":"Get","signature":"func (s *volumeAttachmentLister) Get(name string) (*v1beta1.VolumeAttachment, error)","file":"staging/src/k8s.io/client-go/listers/storage/v1beta1/volumeattachment.go","code":"// Get retrieves the VolumeAttachment from the index for a given name.\nfunc (s *volumeAttachmentLister) Get(name string) (*v1beta1.VolumeAttachment, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"volumeattachment\"), name)\n\t}\n\treturn obj.(*v1beta1.VolumeAttachment), nil\n}","line":{"from":58,"to":68}} {"id":100028133,"name":"init","signature":"func init()","file":"staging/src/k8s.io/client-go/metadata/metadata.go","code":"func init() {\n\tmetav1.AddToGroupVersion(parameterScheme, versionV1)\n\tmetav1.AddToGroupVersion(deleteScheme, versionV1)\n}","line":{"from":45,"to":48}} {"id":100028134,"name":"ConfigFor","signature":"func ConfigFor(inConfig *rest.Config) *rest.Config","file":"staging/src/k8s.io/client-go/metadata/metadata.go","code":"// ConfigFor returns a copy of the provided config with the\n// appropriate metadata client defaults set.\nfunc ConfigFor(inConfig *rest.Config) *rest.Config {\n\tconfig := rest.CopyConfig(inConfig)\n\tconfig.AcceptContentTypes = \"application/vnd.kubernetes.protobuf,application/json\"\n\tconfig.ContentType = \"application/vnd.kubernetes.protobuf\"\n\tconfig.NegotiatedSerializer = metainternalversionscheme.Codecs.WithoutConversion()\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\treturn config\n}","line":{"from":62,"to":73}} {"id":100028135,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) Interface","file":"staging/src/k8s.io/client-go/metadata/metadata.go","code":"// NewForConfigOrDie creates a new metadata client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) Interface {\n\tret, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ret\n}","line":{"from":75,"to":83}} {"id":100028136,"name":"NewForConfig","signature":"func NewForConfig(inConfig *rest.Config) (Interface, error)","file":"staging/src/k8s.io/client-go/metadata/metadata.go","code":"// NewForConfig creates a new metadata client that can retrieve object\n// metadata details about any Kubernetes object (core, aggregated, or custom\n// resource based) in the form of PartialObjectMetadata objects, or returns\n// an error.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(inConfig *rest.Config) (Interface, error) {\n\tconfig := ConfigFor(inConfig)\n\n\thttpClient, err := rest.HTTPClientFor(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(config, httpClient)\n}","line":{"from":85,"to":99}} {"id":100028137,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(inConfig *rest.Config, h *http.Client) (Interface, error)","file":"staging/src/k8s.io/client-go/metadata/metadata.go","code":"// NewForConfigAndClient creates a new metadata client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(inConfig *rest.Config, h *http.Client) (Interface, error) {\n\tconfig := ConfigFor(inConfig)\n\t// for serializing the options\n\tconfig.GroupVersion = \u0026schema.GroupVersion{}\n\tconfig.APIPath = \"/this-value-should-never-be-sent\"\n\n\trestClient, err := rest.RESTClientForConfigAndClient(config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026Client{client: restClient}, nil\n}","line":{"from":101,"to":115}} {"id":100028138,"name":"Resource","signature":"func (c *Client) Resource(resource schema.GroupVersionResource) Getter","file":"staging/src/k8s.io/client-go/metadata/metadata.go","code":"// Resource returns an interface that can access cluster or namespace\n// scoped instances of resource.\nfunc (c *Client) Resource(resource schema.GroupVersionResource) Getter {\n\treturn \u0026client{client: c, resource: resource}\n}","line":{"from":123,"to":127}} {"id":100028139,"name":"Namespace","signature":"func (c *client) Namespace(ns string) ResourceInterface","file":"staging/src/k8s.io/client-go/metadata/metadata.go","code":"// Namespace returns an interface that can access namespace-scoped instances of the\n// provided resource.\nfunc (c *client) Namespace(ns string) ResourceInterface {\n\tret := *c\n\tret.namespace = ns\n\treturn \u0026ret\n}","line":{"from":129,"to":135}} {"id":100028140,"name":"Delete","signature":"func (c *client) Delete(ctx context.Context, name string, opts metav1.DeleteOptions, subresources ...string) error","file":"staging/src/k8s.io/client-go/metadata/metadata.go","code":"// Delete removes the provided resource from the server.\nfunc (c *client) Delete(ctx context.Context, name string, opts metav1.DeleteOptions, subresources ...string) error {\n\tif len(name) == 0 {\n\t\treturn fmt.Errorf(\"name is required\")\n\t}\n\t// if DeleteOptions are delivered to Negotiator for serialization,\n\t// HTTP-Request header will bring \"Content-Type: application/vnd.kubernetes.protobuf\"\n\t// apiextensions-apiserver uses unstructuredNegotiatedSerializer to decode the input,\n\t// server-side will reply with 406 errors.\n\t// The special treatment here is to be compatible with CRD Handler\n\t// see: https://github.com/kubernetes/kubernetes/blob/1a845ccd076bbf1b03420fe694c85a5cd3bd6bed/staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler.go#L843\n\tdeleteOptionsByte, err := runtime.Encode(deleteOptionsCodec.LegacyCodec(schema.GroupVersion{Version: \"v1\"}), \u0026opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresult := c.client.client.\n\t\tDelete().\n\t\tAbsPath(append(c.makeURLSegments(name), subresources...)...).\n\t\tSetHeader(\"Content-Type\", runtime.ContentTypeJSON).\n\t\tBody(deleteOptionsByte).\n\t\tDo(ctx)\n\treturn result.Error()\n}","line":{"from":137,"to":160}} {"id":100028141,"name":"DeleteCollection","signature":"func (c *client) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOptions metav1.ListOptions) error","file":"staging/src/k8s.io/client-go/metadata/metadata.go","code":"// DeleteCollection triggers deletion of all resources in the specified scope (namespace or cluster).\nfunc (c *client) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOptions metav1.ListOptions) error {\n\t// See comment on Delete\n\tdeleteOptionsByte, err := runtime.Encode(deleteOptionsCodec.LegacyCodec(schema.GroupVersion{Version: \"v1\"}), \u0026opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresult := c.client.client.\n\t\tDelete().\n\t\tAbsPath(c.makeURLSegments(\"\")...).\n\t\tSetHeader(\"Content-Type\", runtime.ContentTypeJSON).\n\t\tBody(deleteOptionsByte).\n\t\tSpecificallyVersionedParams(\u0026listOptions, dynamicParameterCodec, versionV1).\n\t\tDo(ctx)\n\treturn result.Error()\n}","line":{"from":162,"to":178}} {"id":100028142,"name":"Get","signature":"func (c *client) Get(ctx context.Context, name string, opts metav1.GetOptions, subresources ...string) (*metav1.PartialObjectMetadata, error)","file":"staging/src/k8s.io/client-go/metadata/metadata.go","code":"// Get returns the resource with name from the specified scope (namespace or cluster).\nfunc (c *client) Get(ctx context.Context, name string, opts metav1.GetOptions, subresources ...string) (*metav1.PartialObjectMetadata, error) {\n\tif len(name) == 0 {\n\t\treturn nil, fmt.Errorf(\"name is required\")\n\t}\n\tresult := c.client.client.Get().AbsPath(append(c.makeURLSegments(name), subresources...)...).\n\t\tSetHeader(\"Accept\", \"application/vnd.kubernetes.protobuf;as=PartialObjectMetadata;g=meta.k8s.io;v=v1,application/json;as=PartialObjectMetadata;g=meta.k8s.io;v=v1,application/json\").\n\t\tSpecificallyVersionedParams(\u0026opts, dynamicParameterCodec, versionV1).\n\t\tDo(ctx)\n\tif err := result.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\tobj, err := result.Get()\n\tif runtime.IsNotRegisteredError(err) {\n\t\tklog.V(5).Infof(\"Unable to retrieve PartialObjectMetadata: %#v\", err)\n\t\trawBytes, err := result.Raw()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar partial metav1.PartialObjectMetadata\n\t\tif err := json.Unmarshal(rawBytes, \u0026partial); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to decode returned object as PartialObjectMetadata: %v\", err)\n\t\t}\n\t\tif !isLikelyObjectMetadata(\u0026partial) {\n\t\t\treturn nil, fmt.Errorf(\"object does not appear to match the ObjectMeta schema: %#v\", partial)\n\t\t}\n\t\tpartial.TypeMeta = metav1.TypeMeta{}\n\t\treturn \u0026partial, nil\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpartial, ok := obj.(*metav1.PartialObjectMetadata)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unexpected object, expected PartialObjectMetadata but got %T\", obj)\n\t}\n\treturn partial, nil\n}","line":{"from":180,"to":217}} {"id":100028143,"name":"List","signature":"func (c *client) List(ctx context.Context, opts metav1.ListOptions) (*metav1.PartialObjectMetadataList, error)","file":"staging/src/k8s.io/client-go/metadata/metadata.go","code":"// List returns all resources within the specified scope (namespace or cluster).\nfunc (c *client) List(ctx context.Context, opts metav1.ListOptions) (*metav1.PartialObjectMetadataList, error) {\n\tresult := c.client.client.Get().AbsPath(c.makeURLSegments(\"\")...).\n\t\tSetHeader(\"Accept\", \"application/vnd.kubernetes.protobuf;as=PartialObjectMetadataList;g=meta.k8s.io;v=v1,application/json;as=PartialObjectMetadataList;g=meta.k8s.io;v=v1,application/json\").\n\t\tSpecificallyVersionedParams(\u0026opts, dynamicParameterCodec, versionV1).\n\t\tDo(ctx)\n\tif err := result.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\tobj, err := result.Get()\n\tif runtime.IsNotRegisteredError(err) {\n\t\tklog.V(5).Infof(\"Unable to retrieve PartialObjectMetadataList: %#v\", err)\n\t\trawBytes, err := result.Raw()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar partial metav1.PartialObjectMetadataList\n\t\tif err := json.Unmarshal(rawBytes, \u0026partial); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to decode returned object as PartialObjectMetadataList: %v\", err)\n\t\t}\n\t\tpartial.TypeMeta = metav1.TypeMeta{}\n\t\treturn \u0026partial, nil\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpartial, ok := obj.(*metav1.PartialObjectMetadataList)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unexpected object, expected PartialObjectMetadata but got %T\", obj)\n\t}\n\treturn partial, nil\n}","line":{"from":219,"to":250}} {"id":100028144,"name":"Watch","signature":"func (c *client) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/metadata/metadata.go","code":"// Watch finds all changes to the resources in the specified scope (namespace or cluster).\nfunc (c *client) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.client.Get().\n\t\tAbsPath(c.makeURLSegments(\"\")...).\n\t\tSetHeader(\"Accept\", \"application/vnd.kubernetes.protobuf;as=PartialObjectMetadata;g=meta.k8s.io;v=v1,application/json;as=PartialObjectMetadata;g=meta.k8s.io;v=v1,application/json\").\n\t\tSpecificallyVersionedParams(\u0026opts, dynamicParameterCodec, versionV1).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":252,"to":265}} {"id":100028145,"name":"Patch","signature":"func (c *client) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (*metav1.PartialObjectMetadata, error)","file":"staging/src/k8s.io/client-go/metadata/metadata.go","code":"// Patch modifies the named resource in the specified scope (namespace or cluster).\nfunc (c *client) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (*metav1.PartialObjectMetadata, error) {\n\tif len(name) == 0 {\n\t\treturn nil, fmt.Errorf(\"name is required\")\n\t}\n\tresult := c.client.client.\n\t\tPatch(pt).\n\t\tAbsPath(append(c.makeURLSegments(name), subresources...)...).\n\t\tBody(data).\n\t\tSetHeader(\"Accept\", \"application/vnd.kubernetes.protobuf;as=PartialObjectMetadata;g=meta.k8s.io;v=v1,application/json;as=PartialObjectMetadata;g=meta.k8s.io;v=v1,application/json\").\n\t\tSpecificallyVersionedParams(\u0026opts, dynamicParameterCodec, versionV1).\n\t\tDo(ctx)\n\tif err := result.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\tobj, err := result.Get()\n\tif runtime.IsNotRegisteredError(err) {\n\t\trawBytes, err := result.Raw()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar partial metav1.PartialObjectMetadata\n\t\tif err := json.Unmarshal(rawBytes, \u0026partial); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to decode returned object as PartialObjectMetadata: %v\", err)\n\t\t}\n\t\tif !isLikelyObjectMetadata(\u0026partial) {\n\t\t\treturn nil, fmt.Errorf(\"object does not appear to match the ObjectMeta schema\")\n\t\t}\n\t\tpartial.TypeMeta = metav1.TypeMeta{}\n\t\treturn \u0026partial, nil\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpartial, ok := obj.(*metav1.PartialObjectMetadata)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unexpected object, expected PartialObjectMetadata but got %T\", obj)\n\t}\n\treturn partial, nil\n}","line":{"from":267,"to":306}} {"id":100028146,"name":"makeURLSegments","signature":"func (c *client) makeURLSegments(name string) []string","file":"staging/src/k8s.io/client-go/metadata/metadata.go","code":"func (c *client) makeURLSegments(name string) []string {\n\turl := []string{}\n\tif len(c.resource.Group) == 0 {\n\t\turl = append(url, \"api\")\n\t} else {\n\t\turl = append(url, \"apis\", c.resource.Group)\n\t}\n\turl = append(url, c.resource.Version)\n\n\tif len(c.namespace) \u003e 0 {\n\t\turl = append(url, \"namespaces\", c.namespace)\n\t}\n\turl = append(url, c.resource.Resource)\n\n\tif len(name) \u003e 0 {\n\t\turl = append(url, name)\n\t}\n\n\treturn url\n}","line":{"from":308,"to":327}} {"id":100028147,"name":"isLikelyObjectMetadata","signature":"func isLikelyObjectMetadata(meta *metav1.PartialObjectMetadata) bool","file":"staging/src/k8s.io/client-go/metadata/metadata.go","code":"func isLikelyObjectMetadata(meta *metav1.PartialObjectMetadata) bool {\n\treturn len(meta.UID) \u003e 0 || !meta.CreationTimestamp.IsZero() || len(meta.Name) \u003e 0 || len(meta.GenerateName) \u003e 0\n}","line":{"from":329,"to":331}} {"id":100028148,"name":"NewSharedInformerFactory","signature":"func NewSharedInformerFactory(client metadata.Interface, defaultResync time.Duration) SharedInformerFactory","file":"staging/src/k8s.io/client-go/metadata/metadatainformer/informer.go","code":"// NewSharedInformerFactory constructs a new instance of metadataSharedInformerFactory for all namespaces.\nfunc NewSharedInformerFactory(client metadata.Interface, defaultResync time.Duration) SharedInformerFactory {\n\treturn NewFilteredSharedInformerFactory(client, defaultResync, metav1.NamespaceAll, nil)\n}","line":{"from":34,"to":37}} {"id":100028149,"name":"NewFilteredSharedInformerFactory","signature":"func NewFilteredSharedInformerFactory(client metadata.Interface, defaultResync time.Duration, namespace string, tweakListOptions TweakListOptionsFunc) SharedInformerFactory","file":"staging/src/k8s.io/client-go/metadata/metadatainformer/informer.go","code":"// NewFilteredSharedInformerFactory constructs a new instance of metadataSharedInformerFactory.\n// Listers obtained via this factory will be subject to the same filters as specified here.\nfunc NewFilteredSharedInformerFactory(client metadata.Interface, defaultResync time.Duration, namespace string, tweakListOptions TweakListOptionsFunc) SharedInformerFactory {\n\treturn \u0026metadataSharedInformerFactory{\n\t\tclient: client,\n\t\tdefaultResync: defaultResync,\n\t\tnamespace: namespace,\n\t\tinformers: map[schema.GroupVersionResource]informers.GenericInformer{},\n\t\tstartedInformers: make(map[schema.GroupVersionResource]bool),\n\t\ttweakListOptions: tweakListOptions,\n\t}\n}","line":{"from":39,"to":50}} {"id":100028150,"name":"ForResource","signature":"func (f *metadataSharedInformerFactory) ForResource(gvr schema.GroupVersionResource) informers.GenericInformer","file":"staging/src/k8s.io/client-go/metadata/metadatainformer/informer.go","code":"func (f *metadataSharedInformerFactory) ForResource(gvr schema.GroupVersionResource) informers.GenericInformer {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\n\tkey := gvr\n\tinformer, exists := f.informers[key]\n\tif exists {\n\t\treturn informer\n\t}\n\n\tinformer = NewFilteredMetadataInformer(f.client, gvr, f.namespace, f.defaultResync, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n\tf.informers[key] = informer\n\n\treturn informer\n}","line":{"from":72,"to":86}} {"id":100028151,"name":"Start","signature":"func (f *metadataSharedInformerFactory) Start(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/client-go/metadata/metadatainformer/informer.go","code":"// Start initializes all requested informers.\nfunc (f *metadataSharedInformerFactory) Start(stopCh \u003c-chan struct{}) {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\n\tif f.shuttingDown {\n\t\treturn\n\t}\n\n\tfor informerType, informer := range f.informers {\n\t\tif !f.startedInformers[informerType] {\n\t\t\tf.wg.Add(1)\n\t\t\t// We need a new variable in each loop iteration,\n\t\t\t// otherwise the goroutine would use the loop variable\n\t\t\t// and that keeps changing.\n\t\t\tinformer := informer.Informer()\n\t\t\tgo func() {\n\t\t\t\tdefer f.wg.Done()\n\t\t\t\tinformer.Run(stopCh)\n\t\t\t}()\n\t\t\tf.startedInformers[informerType] = true\n\t\t}\n\t}\n}","line":{"from":88,"to":111}} {"id":100028152,"name":"WaitForCacheSync","signature":"func (f *metadataSharedInformerFactory) WaitForCacheSync(stopCh \u003c-chan struct{}) map[schema.GroupVersionResource]bool","file":"staging/src/k8s.io/client-go/metadata/metadatainformer/informer.go","code":"// WaitForCacheSync waits for all started informers' cache were synced.\nfunc (f *metadataSharedInformerFactory) WaitForCacheSync(stopCh \u003c-chan struct{}) map[schema.GroupVersionResource]bool {\n\tinformers := func() map[schema.GroupVersionResource]cache.SharedIndexInformer {\n\t\tf.lock.Lock()\n\t\tdefer f.lock.Unlock()\n\n\t\tinformers := map[schema.GroupVersionResource]cache.SharedIndexInformer{}\n\t\tfor informerType, informer := range f.informers {\n\t\t\tif f.startedInformers[informerType] {\n\t\t\t\tinformers[informerType] = informer.Informer()\n\t\t\t}\n\t\t}\n\t\treturn informers\n\t}()\n\n\tres := map[schema.GroupVersionResource]bool{}\n\tfor informType, informer := range informers {\n\t\tres[informType] = cache.WaitForCacheSync(stopCh, informer.HasSynced)\n\t}\n\treturn res\n}","line":{"from":113,"to":133}} {"id":100028153,"name":"Shutdown","signature":"func (f *metadataSharedInformerFactory) Shutdown()","file":"staging/src/k8s.io/client-go/metadata/metadatainformer/informer.go","code":"func (f *metadataSharedInformerFactory) Shutdown() {\n\t// Will return immediately if there is nothing to wait for.\n\tdefer f.wg.Wait()\n\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\tf.shuttingDown = true\n}","line":{"from":135,"to":142}} {"id":100028154,"name":"NewFilteredMetadataInformer","signature":"func NewFilteredMetadataInformer(client metadata.Interface, gvr schema.GroupVersionResource, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions TweakListOptionsFunc) informers.GenericInformer","file":"staging/src/k8s.io/client-go/metadata/metadatainformer/informer.go","code":"// NewFilteredMetadataInformer constructs a new informer for a metadata type.\nfunc NewFilteredMetadataInformer(client metadata.Interface, gvr schema.GroupVersionResource, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions TweakListOptionsFunc) informers.GenericInformer {\n\treturn \u0026metadataInformer{\n\t\tgvr: gvr,\n\t\tinformer: cache.NewSharedIndexInformer(\n\t\t\t\u0026cache.ListWatch{\n\t\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t\t}\n\t\t\t\t\treturn client.Resource(gvr).Namespace(namespace).List(context.TODO(), options)\n\t\t\t\t},\n\t\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t\t}\n\t\t\t\t\treturn client.Resource(gvr).Namespace(namespace).Watch(context.TODO(), options)\n\t\t\t\t},\n\t\t\t},\n\t\t\t\u0026metav1.PartialObjectMetadata{},\n\t\t\tresyncPeriod,\n\t\t\tindexers,\n\t\t),\n\t}\n}","line":{"from":144,"to":168}} {"id":100028155,"name":"Informer","signature":"func (d *metadataInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/client-go/metadata/metadatainformer/informer.go","code":"func (d *metadataInformer) Informer() cache.SharedIndexInformer {\n\treturn d.informer\n}","line":{"from":177,"to":179}} {"id":100028156,"name":"Lister","signature":"func (d *metadataInformer) Lister() cache.GenericLister","file":"staging/src/k8s.io/client-go/metadata/metadatainformer/informer.go","code":"func (d *metadataInformer) Lister() cache.GenericLister {\n\treturn metadatalister.NewRuntimeObjectShim(metadatalister.New(d.informer.GetIndexer(), d.gvr))\n}","line":{"from":181,"to":183}} {"id":100028157,"name":"New","signature":"func New(indexer cache.Indexer, gvr schema.GroupVersionResource) Lister","file":"staging/src/k8s.io/client-go/metadata/metadatalister/lister.go","code":"// New returns a new Lister.\nfunc New(indexer cache.Indexer, gvr schema.GroupVersionResource) Lister {\n\treturn \u0026metadataLister{indexer: indexer, gvr: gvr}\n}","line":{"from":36,"to":39}} {"id":100028158,"name":"List","signature":"func (l *metadataLister) List(selector labels.Selector) (ret []*metav1.PartialObjectMetadata, err error)","file":"staging/src/k8s.io/client-go/metadata/metadatalister/lister.go","code":"// List lists all resources in the indexer.\nfunc (l *metadataLister) List(selector labels.Selector) (ret []*metav1.PartialObjectMetadata, err error) {\n\terr = cache.ListAll(l.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*metav1.PartialObjectMetadata))\n\t})\n\treturn ret, err\n}","line":{"from":41,"to":47}} {"id":100028159,"name":"Get","signature":"func (l *metadataLister) Get(name string) (*metav1.PartialObjectMetadata, error)","file":"staging/src/k8s.io/client-go/metadata/metadatalister/lister.go","code":"// Get retrieves a resource from the indexer with the given name\nfunc (l *metadataLister) Get(name string) (*metav1.PartialObjectMetadata, error) {\n\tobj, exists, err := l.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(l.gvr.GroupResource(), name)\n\t}\n\treturn obj.(*metav1.PartialObjectMetadata), nil\n}","line":{"from":49,"to":59}} {"id":100028160,"name":"Namespace","signature":"func (l *metadataLister) Namespace(namespace string) NamespaceLister","file":"staging/src/k8s.io/client-go/metadata/metadatalister/lister.go","code":"// Namespace returns an object that can list and get resources from a given namespace.\nfunc (l *metadataLister) Namespace(namespace string) NamespaceLister {\n\treturn \u0026metadataNamespaceLister{indexer: l.indexer, namespace: namespace, gvr: l.gvr}\n}","line":{"from":61,"to":64}} {"id":100028161,"name":"List","signature":"func (l *metadataNamespaceLister) List(selector labels.Selector) (ret []*metav1.PartialObjectMetadata, err error)","file":"staging/src/k8s.io/client-go/metadata/metadatalister/lister.go","code":"// List lists all resources in the indexer for a given namespace.\nfunc (l *metadataNamespaceLister) List(selector labels.Selector) (ret []*metav1.PartialObjectMetadata, err error) {\n\terr = cache.ListAllByNamespace(l.indexer, l.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*metav1.PartialObjectMetadata))\n\t})\n\treturn ret, err\n}","line":{"from":73,"to":79}} {"id":100028162,"name":"Get","signature":"func (l *metadataNamespaceLister) Get(name string) (*metav1.PartialObjectMetadata, error)","file":"staging/src/k8s.io/client-go/metadata/metadatalister/lister.go","code":"// Get retrieves a resource from the indexer for a given namespace and name.\nfunc (l *metadataNamespaceLister) Get(name string) (*metav1.PartialObjectMetadata, error) {\n\tobj, exists, err := l.indexer.GetByKey(l.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(l.gvr.GroupResource(), name)\n\t}\n\treturn obj.(*metav1.PartialObjectMetadata), nil\n}","line":{"from":81,"to":91}} {"id":100028163,"name":"NewRuntimeObjectShim","signature":"func NewRuntimeObjectShim(lister Lister) cache.GenericLister","file":"staging/src/k8s.io/client-go/metadata/metadatalister/shim.go","code":"// NewRuntimeObjectShim returns a new shim for Lister.\n// It wraps Lister so that it implements cache.GenericLister interface\nfunc NewRuntimeObjectShim(lister Lister) cache.GenericLister {\n\treturn \u0026metadataListerShim{lister: lister}\n}","line":{"from":33,"to":37}} {"id":100028164,"name":"List","signature":"func (s *metadataListerShim) List(selector labels.Selector) (ret []runtime.Object, err error)","file":"staging/src/k8s.io/client-go/metadata/metadatalister/shim.go","code":"// List will return all objects across namespaces\nfunc (s *metadataListerShim) List(selector labels.Selector) (ret []runtime.Object, err error) {\n\tobjs, err := s.lister.List(selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret = make([]runtime.Object, len(objs))\n\tfor index, obj := range objs {\n\t\tret[index] = obj\n\t}\n\treturn ret, err\n}","line":{"from":39,"to":51}} {"id":100028165,"name":"Get","signature":"func (s *metadataListerShim) Get(name string) (runtime.Object, error)","file":"staging/src/k8s.io/client-go/metadata/metadatalister/shim.go","code":"// Get will attempt to retrieve assuming that name==key\nfunc (s *metadataListerShim) Get(name string) (runtime.Object, error) {\n\treturn s.lister.Get(name)\n}","line":{"from":53,"to":56}} {"id":100028166,"name":"ByNamespace","signature":"func (s *metadataListerShim) ByNamespace(namespace string) cache.GenericNamespaceLister","file":"staging/src/k8s.io/client-go/metadata/metadatalister/shim.go","code":"func (s *metadataListerShim) ByNamespace(namespace string) cache.GenericNamespaceLister {\n\treturn \u0026metadataNamespaceListerShim{\n\t\tnamespaceLister: s.lister.Namespace(namespace),\n\t}\n}","line":{"from":58,"to":62}} {"id":100028167,"name":"List","signature":"func (ns *metadataNamespaceListerShim) List(selector labels.Selector) (ret []runtime.Object, err error)","file":"staging/src/k8s.io/client-go/metadata/metadatalister/shim.go","code":"// List will return all objects in this namespace\nfunc (ns *metadataNamespaceListerShim) List(selector labels.Selector) (ret []runtime.Object, err error) {\n\tobjs, err := ns.namespaceLister.List(selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret = make([]runtime.Object, len(objs))\n\tfor index, obj := range objs {\n\t\tret[index] = obj\n\t}\n\treturn ret, err\n}","line":{"from":70,"to":82}} {"id":100028168,"name":"Get","signature":"func (ns *metadataNamespaceListerShim) Get(name string) (runtime.Object, error)","file":"staging/src/k8s.io/client-go/metadata/metadatalister/shim.go","code":"// Get will attempt to retrieve by namespace and name\nfunc (ns *metadataNamespaceListerShim) Get(name string) (runtime.Object, error) {\n\treturn ns.namespaceLister.Get(name)\n}","line":{"from":84,"to":87}} {"id":100028169,"name":"NewClient","signature":"func NewClient(other openapi.Client) openapi.Client","file":"staging/src/k8s.io/client-go/openapi/cached/client.go","code":"func NewClient(other openapi.Client) openapi.Client {\n\treturn \u0026client{\n\t\tdelegate: other,\n\t}\n}","line":{"from":33,"to":37}} {"id":100028170,"name":"Paths","signature":"func (c *client) Paths() (map[string]openapi.GroupVersion, error)","file":"staging/src/k8s.io/client-go/openapi/cached/client.go","code":"func (c *client) Paths() (map[string]openapi.GroupVersion, error) {\n\tc.once.Do(func() {\n\t\tuncached, err := c.delegate.Paths()\n\t\tif err != nil {\n\t\t\tc.err = err\n\t\t\treturn\n\t\t}\n\n\t\tresult := make(map[string]openapi.GroupVersion, len(uncached))\n\t\tfor k, v := range uncached {\n\t\t\tresult[k] = newGroupVersion(v)\n\t\t}\n\t\tc.result = result\n\t})\n\treturn c.result, c.err\n}","line":{"from":39,"to":54}} {"id":100028171,"name":"newGroupVersion","signature":"func newGroupVersion(delegate openapi.GroupVersion) *groupversion","file":"staging/src/k8s.io/client-go/openapi/cached/groupversion.go","code":"func newGroupVersion(delegate openapi.GroupVersion) *groupversion {\n\treturn \u0026groupversion{\n\t\tdelegate: delegate,\n\t}\n}","line":{"from":37,"to":41}} {"id":100028172,"name":"Schema","signature":"func (g *groupversion) Schema(contentType string) ([]byte, error)","file":"staging/src/k8s.io/client-go/openapi/cached/groupversion.go","code":"func (g *groupversion) Schema(contentType string) ([]byte, error) {\n\tg.lock.Lock()\n\tdefer g.lock.Unlock()\n\n\tcachedInfo, ok := g.docs[contentType]\n\tif !ok {\n\t\tif g.docs == nil {\n\t\t\tg.docs = make(map[string]docInfo)\n\t\t}\n\n\t\tcachedInfo.data, cachedInfo.err = g.delegate.Schema(contentType)\n\t\tg.docs[contentType] = cachedInfo\n\t}\n\n\treturn cachedInfo.data, cachedInfo.err\n}","line":{"from":43,"to":58}} {"id":100028173,"name":"NewClient","signature":"func NewClient(restClient rest.Interface) Client","file":"staging/src/k8s.io/client-go/openapi/client.go","code":"func NewClient(restClient rest.Interface) Client {\n\treturn \u0026client{\n\t\trestClient: restClient,\n\t}\n}","line":{"from":37,"to":41}} {"id":100028174,"name":"Paths","signature":"func (c *client) Paths() (map[string]GroupVersion, error)","file":"staging/src/k8s.io/client-go/openapi/client.go","code":"func (c *client) Paths() (map[string]GroupVersion, error) {\n\tdata, err := c.restClient.Get().\n\t\tAbsPath(\"/openapi/v3\").\n\t\tDo(context.TODO()).\n\t\tRaw()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdiscoMap := \u0026handler3.OpenAPIV3Discovery{}\n\terr = json.Unmarshal(data, discoMap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create GroupVersions for each element of the result\n\tresult := map[string]GroupVersion{}\n\tfor k, v := range discoMap.Paths {\n\t\t// If the server returned a URL rooted at /openapi/v3, preserve any additional client-side prefix.\n\t\t// If the server returned a URL not rooted at /openapi/v3, treat it as an actual server-relative URL.\n\t\t// See https://github.com/kubernetes/kubernetes/issues/117463 for details\n\t\tuseClientPrefix := strings.HasPrefix(v.ServerRelativeURL, \"/openapi/v3\")\n\t\tresult[k] = newGroupVersion(c, v, useClientPrefix)\n\t}\n\treturn result, nil\n}","line":{"from":43,"to":69}} {"id":100028175,"name":"newGroupVersion","signature":"func newGroupVersion(client *client, item handler3.OpenAPIV3DiscoveryGroupVersion, useClientPrefix bool) *groupversion","file":"staging/src/k8s.io/client-go/openapi/groupversion.go","code":"func newGroupVersion(client *client, item handler3.OpenAPIV3DiscoveryGroupVersion, useClientPrefix bool) *groupversion {\n\treturn \u0026groupversion{client: client, item: item, useClientPrefix: useClientPrefix}\n}","line":{"from":38,"to":40}} {"id":100028176,"name":"Schema","signature":"func (g *groupversion) Schema(contentType string) ([]byte, error)","file":"staging/src/k8s.io/client-go/openapi/groupversion.go","code":"func (g *groupversion) Schema(contentType string) ([]byte, error) {\n\tif !g.useClientPrefix {\n\t\treturn g.client.restClient.Get().\n\t\t\tRequestURI(g.item.ServerRelativeURL).\n\t\t\tSetHeader(\"Accept\", contentType).\n\t\t\tDo(context.TODO()).\n\t\t\tRaw()\n\t}\n\n\tlocator, err := url.Parse(g.item.ServerRelativeURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpath := g.client.restClient.Get().\n\t\tAbsPath(locator.Path).\n\t\tSetHeader(\"Accept\", contentType)\n\n\t// Other than root endpoints(openapiv3/apis), resources have hash query parameter to support etags.\n\t// However, absPath does not support handling query parameters internally,\n\t// so that hash query parameter is added manually\n\tfor k, value := range locator.Query() {\n\t\tfor _, v := range value {\n\t\t\tpath.Param(k, v)\n\t\t}\n\t}\n\n\treturn path.Do(context.TODO()).Raw()\n}","line":{"from":42,"to":70}} {"id":100028177,"name":"NewRoot","signature":"func NewRoot(client openapi.Client) Root","file":"staging/src/k8s.io/client-go/openapi3/root.go","code":"// NewRoot returns a structure implementing the Root interface,\n// created with the passed rest client.\nfunc NewRoot(client openapi.Client) Root {\n\treturn \u0026root{client: client}\n}","line":{"from":67,"to":71}} {"id":100028178,"name":"GroupVersions","signature":"func (r *root) GroupVersions() ([]schema.GroupVersion, error)","file":"staging/src/k8s.io/client-go/openapi3/root.go","code":"func (r *root) GroupVersions() ([]schema.GroupVersion, error) {\n\tpaths, err := r.client.Paths()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Example GroupVersion API path: \"apis/apps/v1\"\n\tgvs := make([]schema.GroupVersion, 0, len(paths))\n\tfor gvAPIPath := range paths {\n\t\tgv, err := pathToGroupVersion(gvAPIPath)\n\t\tif err != nil {\n\t\t\t// Ignore paths which do not parse to GroupVersion\n\t\t\tcontinue\n\t\t}\n\t\tgvs = append(gvs, gv)\n\t}\n\t// Sort GroupVersions alphabetically\n\tsort.Slice(gvs, func(i, j int) bool {\n\t\treturn gvs[i].String() \u003c gvs[j].String()\n\t})\n\treturn gvs, nil\n}","line":{"from":73,"to":93}} {"id":100028179,"name":"GVSpec","signature":"func (r *root) GVSpec(gv schema.GroupVersion) (*spec3.OpenAPI, error)","file":"staging/src/k8s.io/client-go/openapi3/root.go","code":"func (r *root) GVSpec(gv schema.GroupVersion) (*spec3.OpenAPI, error) {\n\topenAPISchemaBytes, err := r.retrieveGVBytes(gv)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Unmarshal the downloaded Group/Version bytes into the spec3.OpenAPI struct.\n\tvar parsedV3Schema spec3.OpenAPI\n\terr = json.Unmarshal(openAPISchemaBytes, \u0026parsedV3Schema)\n\treturn \u0026parsedV3Schema, err\n}","line":{"from":95,"to":104}} {"id":100028180,"name":"GVSpecAsMap","signature":"func (r *root) GVSpecAsMap(gv schema.GroupVersion) (map[string]interface{}, error)","file":"staging/src/k8s.io/client-go/openapi3/root.go","code":"func (r *root) GVSpecAsMap(gv schema.GroupVersion) (map[string]interface{}, error) {\n\tgvOpenAPIBytes, err := r.retrieveGVBytes(gv)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// GroupVersion bytes into unstructured map[string] -\u003e empty interface.\n\tvar gvMap map[string]interface{}\n\terr = json.Unmarshal(gvOpenAPIBytes, \u0026gvMap)\n\treturn gvMap, err\n}","line":{"from":106,"to":115}} {"id":100028181,"name":"retrieveGVBytes","signature":"func (r *root) retrieveGVBytes(gv schema.GroupVersion) ([]byte, error)","file":"staging/src/k8s.io/client-go/openapi3/root.go","code":"// retrieveGVBytes returns the schema for a passed GroupVersion as an\n// unstructured slice of bytes or an error if there is a problem downloading\n// or if the passed GroupVersion is not supported.\nfunc (r *root) retrieveGVBytes(gv schema.GroupVersion) ([]byte, error) {\n\tpaths, err := r.client.Paths()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tapiPath := gvToAPIPath(gv)\n\tgvOpenAPI, found := paths[apiPath]\n\tif !found {\n\t\treturn nil, \u0026GroupVersionNotFoundError{gv: gv}\n\t}\n\treturn gvOpenAPI.Schema(runtime.ContentTypeJSON)\n}","line":{"from":117,"to":131}} {"id":100028182,"name":"gvToAPIPath","signature":"func gvToAPIPath(gv schema.GroupVersion) string","file":"staging/src/k8s.io/client-go/openapi3/root.go","code":"// gvToAPIPath maps the passed GroupVersion to a relative api\n// server url. Example:\n//\n//\tGroupVersion{Group: \"apps\", Version: \"v1\"} -\u003e \"apis/apps/v1\".\nfunc gvToAPIPath(gv schema.GroupVersion) string {\n\tvar resourcePath string\n\tif len(gv.Group) == 0 {\n\t\tresourcePath = fmt.Sprintf(\"api/%s\", gv.Version)\n\t} else {\n\t\tresourcePath = fmt.Sprintf(\"apis/%s/%s\", gv.Group, gv.Version)\n\t}\n\treturn resourcePath\n}","line":{"from":133,"to":145}} {"id":100028183,"name":"pathToGroupVersion","signature":"func pathToGroupVersion(path string) (schema.GroupVersion, error)","file":"staging/src/k8s.io/client-go/openapi3/root.go","code":"// pathToGroupVersion is a helper function parsing the passed relative\n// url into a GroupVersion.\n//\n//\tExample: apis/apps/v1 -\u003e GroupVersion{Group: \"apps\", Version: \"v1\"}\n//\tExample: api/v1 -\u003e GroupVersion{Group: \"\", Version: \"v1\"}\nfunc pathToGroupVersion(path string) (schema.GroupVersion, error) {\n\tvar gv schema.GroupVersion\n\tparts := strings.Split(path, \"/\")\n\tif len(parts) \u003c 2 {\n\t\treturn gv, fmt.Errorf(\"Unable to parse api relative path: %s\", path)\n\t}\n\tapiPrefix := parts[0]\n\tif apiPrefix == \"apis\" {\n\t\t// Example: apis/apps (without version)\n\t\tif len(parts) \u003c 3 {\n\t\t\treturn gv, fmt.Errorf(\"Group without Version not allowed\")\n\t\t}\n\t\tgv.Group = parts[1]\n\t\tgv.Version = parts[2]\n\t} else if apiPrefix == \"api\" {\n\t\tgv.Version = parts[1]\n\t} else {\n\t\treturn gv, fmt.Errorf(\"Unable to parse api relative path: %s\", path)\n\t}\n\treturn gv, nil\n}","line":{"from":147,"to":172}} {"id":100028184,"name":"Error","signature":"func (r *GroupVersionNotFoundError) Error() string","file":"staging/src/k8s.io/client-go/openapi3/root.go","code":"func (r *GroupVersionNotFoundError) Error() string {\n\treturn fmt.Sprintf(\"GroupVersion (%v) not found as OpenAPI V3 path\", r.gv)\n}","line":{"from":180,"to":182}} {"id":100028185,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"staging/src/k8s.io/client-go/pkg/apis/clientauthentication/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(clientauthentication.AddToScheme(scheme))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n}","line":{"from":29,"to":34}} {"id":100028186,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/client-go/pkg/apis/clientauthentication/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100028187,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/client-go/pkg/apis/clientauthentication/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100028188,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/client-go/pkg/apis/clientauthentication/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026ExecCredential{},\n\t)\n\treturn nil\n}","line":{"from":45,"to":50}} {"id":100028189,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/client-go/pkg/apis/clientauthentication/v1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100028190,"name":"init","signature":"func init()","file":"staging/src/k8s.io/client-go/pkg/apis/clientauthentication/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addKnownTypes)\n}","line":{"from":42,"to":47}} {"id":100028191,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/client-go/pkg/apis/clientauthentication/v1/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026ExecCredential{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":49,"to":55}} {"id":100028192,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100028193,"name":"init","signature":"func init()","file":"staging/src/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addKnownTypes)\n}","line":{"from":42,"to":47}} {"id":100028194,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/client-go/pkg/apis/clientauthentication/v1beta1/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026ExecCredential{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":49,"to":55}} {"id":100028195,"name":"Get","signature":"func Get() apimachineryversion.Info","file":"staging/src/k8s.io/client-go/pkg/version/version.go","code":"// Get returns the overall codebase version. It's for detecting\n// what code a binary was built from.\nfunc Get() apimachineryversion.Info {\n\t// These variables typically come from -ldflags settings and in\n\t// their absence fallback to the settings in pkg/version/base.go\n\treturn apimachineryversion.Info{\n\t\tMajor: gitMajor,\n\t\tMinor: gitMinor,\n\t\tGitVersion: gitVersion,\n\t\tGitCommit: gitCommit,\n\t\tGitTreeState: gitTreeState,\n\t\tBuildDate: buildDate,\n\t\tGoVersion: runtime.Version(),\n\t\tCompiler: runtime.Compiler,\n\t\tPlatform: fmt.Sprintf(\"%s/%s\", runtime.GOOS, runtime.GOARCH),\n\t}\n}","line":{"from":26,"to":42}} {"id":100028196,"name":"init","signature":"func init()","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/azure/azure_stub.go","code":"func init() {\n\tif err := rest.RegisterAuthProviderPlugin(\"azure\", newAzureAuthProvider); err != nil {\n\t\tklog.Fatalf(\"Failed to register azure auth plugin: %v\", err)\n\t}\n}","line":{"from":26,"to":30}} {"id":100028197,"name":"newAzureAuthProvider","signature":"func newAzureAuthProvider(_ string, _ map[string]string, _ rest.AuthProviderConfigPersister) (rest.AuthProvider, error)","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/azure/azure_stub.go","code":"func newAzureAuthProvider(_ string, _ map[string]string, _ rest.AuthProviderConfigPersister) (rest.AuthProvider, error) {\n\treturn nil, errors.New(`The azure auth plugin has been removed.\nPlease use the https://github.com/Azure/kubelogin kubectl/client-go credential plugin instead.\nSee https://kubernetes.io/docs/reference/access-authn-authz/authentication/#client-go-credential-plugins for further details`)\n}","line":{"from":32,"to":36}} {"id":100028198,"name":"init","signature":"func init()","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/exec/exec.go","code":"func init() {\n\tinstall.Install(scheme)\n}","line":{"from":65,"to":67}} {"id":100028199,"name":"newCache","signature":"func newCache() *cache","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/exec/exec.go","code":"func newCache() *cache {\n\treturn \u0026cache{m: make(map[string]*Authenticator)}\n}","line":{"from":80,"to":82}} {"id":100028200,"name":"cacheKey","signature":"func cacheKey(conf *api.ExecConfig, cluster *clientauthentication.Cluster) string","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/exec/exec.go","code":"func cacheKey(conf *api.ExecConfig, cluster *clientauthentication.Cluster) string {\n\tkey := struct {\n\t\tconf *api.ExecConfig\n\t\tcluster *clientauthentication.Cluster\n\t}{\n\t\tconf: conf,\n\t\tcluster: cluster,\n\t}\n\treturn spewConfig.Sprint(key)\n}","line":{"from":86,"to":95}} {"id":100028201,"name":"get","signature":"func (c *cache) get(s string) (*Authenticator, bool)","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/exec/exec.go","code":"func (c *cache) get(s string) (*Authenticator, bool) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\ta, ok := c.m[s]\n\treturn a, ok\n}","line":{"from":102,"to":107}} {"id":100028202,"name":"put","signature":"func (c *cache) put(s string, a *Authenticator) *Authenticator","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/exec/exec.go","code":"// put inserts an authenticator into the cache. If an authenticator is already\n// associated with the key, the first one is returned instead.\nfunc (c *cache) put(s string, a *Authenticator) *Authenticator {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\texisting, ok := c.m[s]\n\tif ok {\n\t\treturn existing\n\t}\n\tc.m[s] = a\n\treturn a\n}","line":{"from":109,"to":120}} {"id":100028203,"name":"Do","signature":"func (s *sometimes) Do(f func())","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/exec/exec.go","code":"func (s *sometimes) Do(f func()) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\tnow := s.clock.Now()\n\tif s.window.IsZero() {\n\t\ts.window = now\n\t}\n\n\t// If we are no longer in our saved time window, then we get to reset our run\n\t// count back to 0 and start increasing towards the threshold again.\n\tif inWindow := now.Sub(s.window) \u003c s.interval; !inWindow {\n\t\ts.window = now\n\t\ts.count = 0\n\t}\n\n\t// If we have not run the function more than threshold times in this current\n\t// time window, we get to run it now!\n\tif underThreshold := s.count \u003c s.threshold; underThreshold {\n\t\ts.count++\n\t\tf()\n\t}\n}","line":{"from":136,"to":158}} {"id":100028204,"name":"GetAuthenticator","signature":"func GetAuthenticator(config *api.ExecConfig, cluster *clientauthentication.Cluster) (*Authenticator, error)","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/exec/exec.go","code":"// GetAuthenticator returns an exec-based plugin for providing client credentials.\nfunc GetAuthenticator(config *api.ExecConfig, cluster *clientauthentication.Cluster) (*Authenticator, error) {\n\treturn newAuthenticator(globalCache, term.IsTerminal, config, cluster)\n}","line":{"from":160,"to":163}} {"id":100028205,"name":"newAuthenticator","signature":"func newAuthenticator(c *cache, isTerminalFunc func(int) bool, config *api.ExecConfig, cluster *clientauthentication.Cluster) (*Authenticator, error)","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/exec/exec.go","code":"func newAuthenticator(c *cache, isTerminalFunc func(int) bool, config *api.ExecConfig, cluster *clientauthentication.Cluster) (*Authenticator, error) {\n\tkey := cacheKey(config, cluster)\n\tif a, ok := c.get(key); ok {\n\t\treturn a, nil\n\t}\n\n\tgv, ok := apiVersions[config.APIVersion]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"exec plugin: invalid apiVersion %q\", config.APIVersion)\n\t}\n\n\tconnTracker := connrotation.NewConnectionTracker()\n\tdefaultDialer := connrotation.NewDialerWithTracker(\n\t\t(\u0026net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}).DialContext,\n\t\tconnTracker,\n\t)\n\n\ta := \u0026Authenticator{\n\t\tcmd: config.Command,\n\t\targs: config.Args,\n\t\tgroup: gv,\n\t\tcluster: cluster,\n\t\tprovideClusterInfo: config.ProvideClusterInfo,\n\n\t\tinstallHint: config.InstallHint,\n\t\tsometimes: \u0026sometimes{\n\t\t\tthreshold: 10,\n\t\t\tinterval: time.Hour,\n\t\t\tclock: clock.RealClock{},\n\t\t},\n\n\t\tstdin: os.Stdin,\n\t\tstderr: os.Stderr,\n\t\tinteractiveFunc: func() (bool, error) { return isInteractive(isTerminalFunc, config) },\n\t\tnow: time.Now,\n\t\tenviron: os.Environ,\n\n\t\tconnTracker: connTracker,\n\t}\n\n\tfor _, env := range config.Env {\n\t\ta.env = append(a.env, env.Name+\"=\"+env.Value)\n\t}\n\n\t// these functions are made comparable and stored in the cache so that repeated clientset\n\t// construction with the same rest.Config results in a single TLS cache and Authenticator\n\ta.getCert = \u0026transport.GetCertHolder{GetCert: a.cert}\n\ta.dial = \u0026transport.DialHolder{Dial: defaultDialer.DialContext}\n\n\treturn c.put(key, a), nil\n}","line":{"from":165,"to":215}} {"id":100028206,"name":"isInteractive","signature":"func isInteractive(isTerminalFunc func(int) bool, config *api.ExecConfig) (bool, error)","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/exec/exec.go","code":"func isInteractive(isTerminalFunc func(int) bool, config *api.ExecConfig) (bool, error) {\n\tvar shouldBeInteractive bool\n\tswitch config.InteractiveMode {\n\tcase api.NeverExecInteractiveMode:\n\t\tshouldBeInteractive = false\n\tcase api.IfAvailableExecInteractiveMode:\n\t\tshouldBeInteractive = !config.StdinUnavailable \u0026\u0026 isTerminalFunc(int(os.Stdin.Fd()))\n\tcase api.AlwaysExecInteractiveMode:\n\t\tif !isTerminalFunc(int(os.Stdin.Fd())) {\n\t\t\treturn false, errors.New(\"standard input is not a terminal\")\n\t\t}\n\t\tif config.StdinUnavailable {\n\t\t\tsuffix := \"\"\n\t\t\tif len(config.StdinUnavailableMessage) \u003e 0 {\n\t\t\t\t// only print extra \": \u003cmessage\u003e\" if the user actually specified a message\n\t\t\t\tsuffix = fmt.Sprintf(\": %s\", config.StdinUnavailableMessage)\n\t\t\t}\n\t\t\treturn false, fmt.Errorf(\"standard input is unavailable%s\", suffix)\n\t\t}\n\t\tshouldBeInteractive = true\n\tdefault:\n\t\treturn false, fmt.Errorf(\"unknown interactiveMode: %q\", config.InteractiveMode)\n\t}\n\n\treturn shouldBeInteractive, nil\n}","line":{"from":217,"to":242}} {"id":100028207,"name":"UpdateTransportConfig","signature":"func (a *Authenticator) UpdateTransportConfig(c *transport.Config) error","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/exec/exec.go","code":"// UpdateTransportConfig updates the transport.Config to use credentials\n// returned by the plugin.\nfunc (a *Authenticator) UpdateTransportConfig(c *transport.Config) error {\n\t// If a bearer token is present in the request - avoid the GetCert callback when\n\t// setting up the transport, as that triggers the exec action if the server is\n\t// also configured to allow client certificates for authentication. For requests\n\t// like \"kubectl get --token (token) pods\" we should assume the intention is to\n\t// use the provided token for authentication. The same can be said for when the\n\t// user specifies basic auth or cert auth.\n\tif c.HasTokenAuth() || c.HasBasicAuth() || c.HasCertAuth() {\n\t\treturn nil\n\t}\n\n\tc.Wrap(func(rt http.RoundTripper) http.RoundTripper {\n\t\treturn \u0026roundTripper{a, rt}\n\t})\n\n\tif c.HasCertCallback() {\n\t\treturn errors.New(\"can't add TLS certificate callback: transport.Config.TLS.GetCert already set\")\n\t}\n\tc.TLS.GetCertHolder = a.getCert // comparable for TLS config caching\n\n\tif c.DialHolder != nil {\n\t\tif c.DialHolder.Dial == nil {\n\t\t\treturn errors.New(\"invalid transport.Config.DialHolder: wrapped Dial function is nil\")\n\t\t}\n\n\t\t// if c has a custom dialer, we have to wrap it\n\t\t// TLS config caching is not supported for this config\n\t\td := connrotation.NewDialerWithTracker(c.DialHolder.Dial, a.connTracker)\n\t\tc.DialHolder = \u0026transport.DialHolder{Dial: d.DialContext}\n\t} else {\n\t\tc.DialHolder = a.dial // comparable for TLS config caching\n\t}\n\n\treturn nil\n}","line":{"from":291,"to":327}} {"id":100028208,"name":"WrappedRoundTripper","signature":"func (r *roundTripper) WrappedRoundTripper() http.RoundTripper","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/exec/exec.go","code":"func (r *roundTripper) WrappedRoundTripper() http.RoundTripper {\n\treturn r.base\n}","line":{"from":336,"to":338}} {"id":100028209,"name":"RoundTrip","signature":"func (r *roundTripper) RoundTrip(req *http.Request) (*http.Response, error)","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/exec/exec.go","code":"func (r *roundTripper) RoundTrip(req *http.Request) (*http.Response, error) {\n\t// If a user has already set credentials, use that. This makes commands like\n\t// \"kubectl get --token (token) pods\" work.\n\tif req.Header.Get(\"Authorization\") != \"\" {\n\t\treturn r.base.RoundTrip(req)\n\t}\n\n\tcreds, err := r.a.getCreds()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getting credentials: %v\", err)\n\t}\n\tif creds.token != \"\" {\n\t\treq.Header.Set(\"Authorization\", \"Bearer \"+creds.token)\n\t}\n\n\tres, err := r.base.RoundTrip(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif res.StatusCode == http.StatusUnauthorized {\n\t\tif err := r.a.maybeRefreshCreds(creds); err != nil {\n\t\t\tklog.Errorf(\"refreshing credentials: %v\", err)\n\t\t}\n\t}\n\treturn res, nil\n}","line":{"from":340,"to":365}} {"id":100028210,"name":"credsExpired","signature":"func (a *Authenticator) credsExpired() bool","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/exec/exec.go","code":"func (a *Authenticator) credsExpired() bool {\n\tif a.exp.IsZero() {\n\t\treturn false\n\t}\n\treturn a.now().After(a.exp)\n}","line":{"from":367,"to":372}} {"id":100028211,"name":"cert","signature":"func (a *Authenticator) cert() (*tls.Certificate, error)","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/exec/exec.go","code":"func (a *Authenticator) cert() (*tls.Certificate, error) {\n\tcreds, err := a.getCreds()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn creds.cert, nil\n}","line":{"from":374,"to":380}} {"id":100028212,"name":"getCreds","signature":"func (a *Authenticator) getCreds() (*credentials, error)","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/exec/exec.go","code":"func (a *Authenticator) getCreds() (*credentials, error) {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\n\tif a.cachedCreds != nil \u0026\u0026 !a.credsExpired() {\n\t\treturn a.cachedCreds, nil\n\t}\n\n\tif err := a.refreshCredsLocked(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn a.cachedCreds, nil\n}","line":{"from":382,"to":395}} {"id":100028213,"name":"maybeRefreshCreds","signature":"func (a *Authenticator) maybeRefreshCreds(creds *credentials) error","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/exec/exec.go","code":"// maybeRefreshCreds executes the plugin to force a rotation of the\n// credentials, unless they were rotated already.\nfunc (a *Authenticator) maybeRefreshCreds(creds *credentials) error {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\n\t// Since we're not making a new pointer to a.cachedCreds in getCreds, no\n\t// need to do deep comparison.\n\tif creds != a.cachedCreds {\n\t\t// Credentials already rotated.\n\t\treturn nil\n\t}\n\n\treturn a.refreshCredsLocked()\n}","line":{"from":397,"to":411}} {"id":100028214,"name":"refreshCredsLocked","signature":"func (a *Authenticator) refreshCredsLocked() error","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/exec/exec.go","code":"// refreshCredsLocked executes the plugin and reads the credentials from\n// stdout. It must be called while holding the Authenticator's mutex.\nfunc (a *Authenticator) refreshCredsLocked() error {\n\tinteractive, err := a.interactiveFunc()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"exec plugin cannot support interactive mode: %w\", err)\n\t}\n\n\tcred := \u0026clientauthentication.ExecCredential{\n\t\tSpec: clientauthentication.ExecCredentialSpec{\n\t\t\tInteractive: interactive,\n\t\t},\n\t}\n\tif a.provideClusterInfo {\n\t\tcred.Spec.Cluster = a.cluster\n\t}\n\n\tenv := append(a.environ(), a.env...)\n\tdata, err := runtime.Encode(codecs.LegacyCodec(a.group), cred)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"encode ExecCredentials: %v\", err)\n\t}\n\tenv = append(env, fmt.Sprintf(\"%s=%s\", execInfoEnv, data))\n\n\tstdout := \u0026bytes.Buffer{}\n\tcmd := exec.Command(a.cmd, a.args...)\n\tcmd.Env = env\n\tcmd.Stderr = a.stderr\n\tcmd.Stdout = stdout\n\tif interactive {\n\t\tcmd.Stdin = a.stdin\n\t}\n\n\terr = cmd.Run()\n\tincrementCallsMetric(err)\n\tif err != nil {\n\t\treturn a.wrapCmdRunErrorLocked(err)\n\t}\n\n\t_, gvk, err := codecs.UniversalDecoder(a.group).Decode(stdout.Bytes(), nil, cred)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"decoding stdout: %v\", err)\n\t}\n\tif gvk.Group != a.group.Group || gvk.Version != a.group.Version {\n\t\treturn fmt.Errorf(\"exec plugin is configured to use API version %s, plugin returned version %s\",\n\t\t\ta.group, schema.GroupVersion{Group: gvk.Group, Version: gvk.Version})\n\t}\n\n\tif cred.Status == nil {\n\t\treturn fmt.Errorf(\"exec plugin didn't return a status field\")\n\t}\n\tif cred.Status.Token == \"\" \u0026\u0026 cred.Status.ClientCertificateData == \"\" \u0026\u0026 cred.Status.ClientKeyData == \"\" {\n\t\treturn fmt.Errorf(\"exec plugin didn't return a token or cert/key pair\")\n\t}\n\tif (cred.Status.ClientCertificateData == \"\") != (cred.Status.ClientKeyData == \"\") {\n\t\treturn fmt.Errorf(\"exec plugin returned only certificate or key, not both\")\n\t}\n\n\tif cred.Status.ExpirationTimestamp != nil {\n\t\ta.exp = cred.Status.ExpirationTimestamp.Time\n\t} else {\n\t\ta.exp = time.Time{}\n\t}\n\n\tnewCreds := \u0026credentials{\n\t\ttoken: cred.Status.Token,\n\t}\n\tif cred.Status.ClientKeyData != \"\" \u0026\u0026 cred.Status.ClientCertificateData != \"\" {\n\t\tcert, err := tls.X509KeyPair([]byte(cred.Status.ClientCertificateData), []byte(cred.Status.ClientKeyData))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed parsing client key/certificate: %v\", err)\n\t\t}\n\n\t\t// Leaf is initialized to be nil:\n\t\t// https://golang.org/pkg/crypto/tls/#X509KeyPair\n\t\t// Leaf certificate is the first certificate:\n\t\t// https://golang.org/pkg/crypto/tls/#Certificate\n\t\t// Populating leaf is useful for quickly accessing the underlying x509\n\t\t// certificate values.\n\t\tcert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed parsing client leaf certificate: %v\", err)\n\t\t}\n\t\tnewCreds.cert = \u0026cert\n\t}\n\n\toldCreds := a.cachedCreds\n\ta.cachedCreds = newCreds\n\t// Only close all connections when TLS cert rotates. Token rotation doesn't\n\t// need the extra noise.\n\tif oldCreds != nil \u0026\u0026 !reflect.DeepEqual(oldCreds.cert, a.cachedCreds.cert) {\n\t\t// Can be nil if the exec auth plugin only returned token auth.\n\t\tif oldCreds.cert != nil \u0026\u0026 oldCreds.cert.Leaf != nil {\n\t\t\tmetrics.ClientCertRotationAge.Observe(time.Since(oldCreds.cert.Leaf.NotBefore))\n\t\t}\n\t\ta.connTracker.CloseAll()\n\t}\n\n\texpiry := time.Time{}\n\tif a.cachedCreds.cert != nil \u0026\u0026 a.cachedCreds.cert.Leaf != nil {\n\t\texpiry = a.cachedCreds.cert.Leaf.NotAfter\n\t}\n\texpirationMetrics.set(a, expiry)\n\treturn nil\n}","line":{"from":413,"to":517}} {"id":100028215,"name":"wrapCmdRunErrorLocked","signature":"func (a *Authenticator) wrapCmdRunErrorLocked(err error) error","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/exec/exec.go","code":"// wrapCmdRunErrorLocked pulls out the code to construct a helpful error message\n// for when the exec plugin's binary fails to Run().\n//\n// It must be called while holding the Authenticator's mutex.\nfunc (a *Authenticator) wrapCmdRunErrorLocked(err error) error {\n\tswitch err.(type) {\n\tcase *exec.Error: // Binary does not exist (see exec.Error).\n\t\tbuilder := strings.Builder{}\n\t\tfmt.Fprintf(\u0026builder, \"exec: executable %s not found\", a.cmd)\n\n\t\ta.sometimes.Do(func() {\n\t\t\tfmt.Fprint(\u0026builder, installHintVerboseHelp)\n\t\t\tif a.installHint != \"\" {\n\t\t\t\tfmt.Fprintf(\u0026builder, \"\\n\\n%s\", a.installHint)\n\t\t\t}\n\t\t})\n\n\t\treturn errors.New(builder.String())\n\n\tcase *exec.ExitError: // Binary execution failed (see exec.Cmd.Run()).\n\t\te := err.(*exec.ExitError)\n\t\treturn fmt.Errorf(\n\t\t\t\"exec: executable %s failed with exit code %d\",\n\t\t\ta.cmd,\n\t\t\te.ProcessState.ExitCode(),\n\t\t)\n\n\tdefault:\n\t\treturn fmt.Errorf(\"exec: %v\", err)\n\t}\n}","line":{"from":519,"to":549}} {"id":100028216,"name":"set","signature":"func (c *certificateExpirationTracker) set(a *Authenticator, t time.Time)","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/exec/metrics.go","code":"// set stores the given expiration time and updates the updates the certificate\n// expiry metric to the earliest expiration time.\nfunc (c *certificateExpirationTracker) set(a *Authenticator, t time.Time) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tc.m[a] = t\n\n\tearliest := time.Time{}\n\tfor _, t := range c.m {\n\t\tif t.IsZero() {\n\t\t\tcontinue\n\t\t}\n\t\tif earliest.IsZero() || earliest.After(t) {\n\t\t\tearliest = t\n\t\t}\n\t}\n\tif earliest.IsZero() {\n\t\tc.metricSet(nil)\n\t} else {\n\t\tc.metricSet(\u0026earliest)\n\t}\n}","line":{"from":67,"to":88}} {"id":100028217,"name":"incrementCallsMetric","signature":"func incrementCallsMetric(err error)","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/exec/metrics.go","code":"// incrementCallsMetric increments a global metrics counter for the number of calls to an exec\n// plugin, partitioned by exit code. The provided err should be the return value from\n// exec.Cmd.Run().\nfunc incrementCallsMetric(err error) {\n\texecExitError := \u0026exec.ExitError{}\n\texecError := \u0026exec.Error{}\n\tpathError := \u0026fs.PathError{}\n\tswitch {\n\tcase err == nil: // Binary execution succeeded.\n\t\tmetrics.ExecPluginCalls.Increment(successExitCode, noError)\n\n\tcase errors.As(err, \u0026execExitError): // Binary execution failed (see \"os/exec\".Cmd.Run()).\n\t\tmetrics.ExecPluginCalls.Increment(execExitError.ExitCode(), pluginExecutionError)\n\n\tcase errors.As(err, \u0026execError), errors.As(err, \u0026pathError): // Binary does not exist (see exec.Error, fs.PathError).\n\t\tmetrics.ExecPluginCalls.Increment(failureExitCode, pluginNotFoundError)\n\n\tdefault: // We don't know about this error type.\n\t\tklog.V(2).InfoS(\"unexpected exec plugin return error type\", \"type\", reflect.TypeOf(err).String(), \"err\", err)\n\t\tmetrics.ExecPluginCalls.Increment(failureExitCode, clientInternalError)\n\t}\n}","line":{"from":90,"to":111}} {"id":100028218,"name":"init","signature":"func init()","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/gcp/gcp_stub.go","code":"func init() {\n\tif err := rest.RegisterAuthProviderPlugin(\"gcp\", newGCPAuthProvider); err != nil {\n\t\tklog.Fatalf(\"Failed to register gcp auth plugin: %v\", err)\n\t}\n}","line":{"from":26,"to":30}} {"id":100028219,"name":"newGCPAuthProvider","signature":"func newGCPAuthProvider(_ string, _ map[string]string, _ rest.AuthProviderConfigPersister) (rest.AuthProvider, error)","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/gcp/gcp_stub.go","code":"func newGCPAuthProvider(_ string, _ map[string]string, _ rest.AuthProviderConfigPersister) (rest.AuthProvider, error) {\n\treturn nil, errors.New(`The gcp auth plugin has been removed.\nPlease use the \"gke-gcloud-auth-plugin\" kubectl/client-go credential plugin instead.\nSee https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke for further details`)\n}","line":{"from":32,"to":36}} {"id":100028220,"name":"init","signature":"func init()","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/oidc/oidc.go","code":"func init() {\n\tif err := restclient.RegisterAuthProviderPlugin(\"oidc\", newOIDCAuthProvider); err != nil {\n\t\tklog.Fatalf(\"Failed to register oidc auth plugin: %v\", err)\n\t}\n}","line":{"from":50,"to":54}} {"id":100028221,"name":"newClientCache","signature":"func newClientCache() *clientCache","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/oidc/oidc.go","code":"func newClientCache() *clientCache {\n\treturn \u0026clientCache{cache: make(map[cacheKey]*oidcAuthProvider)}\n}","line":{"from":74,"to":76}} {"id":100028222,"name":"getClient","signature":"func (c *clientCache) getClient(clusterAddress, issuer, clientID string) (*oidcAuthProvider, bool)","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/oidc/oidc.go","code":"func (c *clientCache) getClient(clusterAddress, issuer, clientID string) (*oidcAuthProvider, bool) {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\tclient, ok := c.cache[cacheKey{clusterAddress: clusterAddress, issuerURL: issuer, clientID: clientID}]\n\treturn client, ok\n}","line":{"from":85,"to":90}} {"id":100028223,"name":"setClient","signature":"func (c *clientCache) setClient(clusterAddress, issuer, clientID string, client *oidcAuthProvider) *oidcAuthProvider","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/oidc/oidc.go","code":"// setClient attempts to put the client in the cache but may return any clients\n// with the same keys set before. This is so there's only ever one client for a provider.\nfunc (c *clientCache) setClient(clusterAddress, issuer, clientID string, client *oidcAuthProvider) *oidcAuthProvider {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tkey := cacheKey{clusterAddress: clusterAddress, issuerURL: issuer, clientID: clientID}\n\n\t// If another client has already initialized a client for the given provider we want\n\t// to use that client instead of the one we're trying to set. This is so all transports\n\t// share a client and can coordinate around the same mutex when refreshing and writing\n\t// to the kubeconfig.\n\tif oldClient, ok := c.cache[key]; ok {\n\t\treturn oldClient\n\t}\n\n\tc.cache[key] = client\n\treturn client\n}","line":{"from":92,"to":109}} {"id":100028224,"name":"newOIDCAuthProvider","signature":"func newOIDCAuthProvider(clusterAddress string, cfg map[string]string, persister restclient.AuthProviderConfigPersister) (restclient.AuthProvider, error)","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/oidc/oidc.go","code":"func newOIDCAuthProvider(clusterAddress string, cfg map[string]string, persister restclient.AuthProviderConfigPersister) (restclient.AuthProvider, error) {\n\tissuer := cfg[cfgIssuerURL]\n\tif issuer == \"\" {\n\t\treturn nil, fmt.Errorf(\"Must provide %s\", cfgIssuerURL)\n\t}\n\n\tclientID := cfg[cfgClientID]\n\tif clientID == \"\" {\n\t\treturn nil, fmt.Errorf(\"Must provide %s\", cfgClientID)\n\t}\n\n\t// Check cache for existing provider.\n\tif provider, ok := cache.getClient(clusterAddress, issuer, clientID); ok {\n\t\treturn provider, nil\n\t}\n\n\tif len(cfg[cfgExtraScopes]) \u003e 0 {\n\t\tklog.V(2).Infof(\"%s auth provider field depricated, refresh request don't send scopes\",\n\t\t\tcfgExtraScopes)\n\t}\n\n\tvar certAuthData []byte\n\tvar err error\n\tif cfg[cfgCertificateAuthorityData] != \"\" {\n\t\tcertAuthData, err = base64.StdEncoding.DecodeString(cfg[cfgCertificateAuthorityData])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tclientConfig := restclient.Config{\n\t\tTLSClientConfig: restclient.TLSClientConfig{\n\t\t\tCAFile: cfg[cfgCertificateAuthority],\n\t\t\tCAData: certAuthData,\n\t\t},\n\t}\n\n\ttrans, err := restclient.TransportFor(\u0026clientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thc := \u0026http.Client{Transport: trans}\n\n\tprovider := \u0026oidcAuthProvider{\n\t\tclient: hc,\n\t\tnow: time.Now,\n\t\tcfg: cfg,\n\t\tpersister: persister,\n\t}\n\n\treturn cache.setClient(clusterAddress, issuer, clientID, provider), nil\n}","line":{"from":111,"to":162}} {"id":100028225,"name":"WrapTransport","signature":"func (p *oidcAuthProvider) WrapTransport(rt http.RoundTripper) http.RoundTripper","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/oidc/oidc.go","code":"func (p *oidcAuthProvider) WrapTransport(rt http.RoundTripper) http.RoundTripper {\n\treturn \u0026roundTripper{\n\t\twrapped: rt,\n\t\tprovider: p,\n\t}\n}","line":{"from":178,"to":183}} {"id":100028226,"name":"Login","signature":"func (p *oidcAuthProvider) Login() error","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/oidc/oidc.go","code":"func (p *oidcAuthProvider) Login() error {\n\treturn errors.New(\"not yet implemented\")\n}","line":{"from":185,"to":187}} {"id":100028227,"name":"RoundTrip","signature":"func (r *roundTripper) RoundTrip(req *http.Request) (*http.Response, error)","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/oidc/oidc.go","code":"func (r *roundTripper) RoundTrip(req *http.Request) (*http.Response, error) {\n\tif len(req.Header.Get(\"Authorization\")) != 0 {\n\t\treturn r.wrapped.RoundTrip(req)\n\t}\n\ttoken, err := r.provider.idToken()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// shallow copy of the struct\n\tr2 := new(http.Request)\n\t*r2 = *req\n\t// deep copy of the Header so we don't modify the original\n\t// request's Header (as per RoundTripper contract).\n\tr2.Header = make(http.Header)\n\tfor k, s := range req.Header {\n\t\tr2.Header[k] = s\n\t}\n\tr2.Header.Set(\"Authorization\", fmt.Sprintf(\"Bearer %s\", token))\n\n\treturn r.wrapped.RoundTrip(r2)\n}","line":{"from":196,"to":217}} {"id":100028228,"name":"WrappedRoundTripper","signature":"func (r *roundTripper) WrappedRoundTripper() http.RoundTripper { return r.wrapped }","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/oidc/oidc.go","code":"func (r *roundTripper) WrappedRoundTripper() http.RoundTripper { return r.wrapped }","line":{"from":219,"to":219}} {"id":100028229,"name":"idToken","signature":"func (p *oidcAuthProvider) idToken() (string, error)","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/oidc/oidc.go","code":"func (p *oidcAuthProvider) idToken() (string, error) {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\n\tif idToken, ok := p.cfg[cfgIDToken]; ok \u0026\u0026 len(idToken) \u003e 0 {\n\t\tvalid, err := idTokenExpired(p.now, idToken)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif valid {\n\t\t\t// If the cached id token is still valid use it.\n\t\t\treturn idToken, nil\n\t\t}\n\t}\n\n\t// Try to request a new token using the refresh token.\n\trt, ok := p.cfg[cfgRefreshToken]\n\tif !ok || len(rt) == 0 {\n\t\treturn \"\", errors.New(\"No valid id-token, and cannot refresh without refresh-token\")\n\t}\n\n\t// Determine provider's OAuth2 token endpoint.\n\ttokenURL, err := tokenEndpoint(p.client, p.cfg[cfgIssuerURL])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tconfig := oauth2.Config{\n\t\tClientID: p.cfg[cfgClientID],\n\t\tClientSecret: p.cfg[cfgClientSecret],\n\t\tEndpoint: oauth2.Endpoint{TokenURL: tokenURL},\n\t}\n\n\tctx := context.WithValue(context.Background(), oauth2.HTTPClient, p.client)\n\ttoken, err := config.TokenSource(ctx, \u0026oauth2.Token{RefreshToken: rt}).Token()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to refresh token: %v\", err)\n\t}\n\n\tidToken, ok := token.Extra(\"id_token\").(string)\n\tif !ok {\n\t\t// id_token isn't a required part of a refresh token response, so some\n\t\t// providers (Okta) don't return this value.\n\t\t//\n\t\t// See https://github.com/kubernetes/kubernetes/issues/36847\n\t\treturn \"\", fmt.Errorf(\"token response did not contain an id_token, either the scope \\\"openid\\\" wasn't requested upon login, or the provider doesn't support id_tokens as part of the refresh response\")\n\t}\n\n\t// Create a new config to persist.\n\tnewCfg := make(map[string]string)\n\tfor key, val := range p.cfg {\n\t\tnewCfg[key] = val\n\t}\n\n\t// Update the refresh token if the server returned another one.\n\tif token.RefreshToken != \"\" \u0026\u0026 token.RefreshToken != rt {\n\t\tnewCfg[cfgRefreshToken] = token.RefreshToken\n\t}\n\tnewCfg[cfgIDToken] = idToken\n\n\t// Persist new config and if successful, update the in memory config.\n\tif err = p.persister.Persist(newCfg); err != nil {\n\t\treturn \"\", fmt.Errorf(\"could not persist new tokens: %v\", err)\n\t}\n\tp.cfg = newCfg\n\n\treturn idToken, nil\n}","line":{"from":221,"to":288}} {"id":100028230,"name":"tokenEndpoint","signature":"func tokenEndpoint(client *http.Client, issuer string) (string, error)","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/oidc/oidc.go","code":"// tokenEndpoint uses OpenID Connect discovery to determine the OAuth2 token\n// endpoint for the provider, the endpoint the client will use the refresh\n// token against.\nfunc tokenEndpoint(client *http.Client, issuer string) (string, error) {\n\t// Well known URL for getting OpenID Connect metadata.\n\t//\n\t// https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig\n\twellKnown := strings.TrimSuffix(issuer, \"/\") + \"/.well-known/openid-configuration\"\n\tresp, err := client.Get(wellKnown)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\t// Don't produce an error that's too huge (e.g. if we get HTML back for some reason).\n\t\tconst n = 80\n\t\tif len(body) \u003e n {\n\t\t\tbody = append(body[:n], []byte(\"...\")...)\n\t\t}\n\t\treturn \"\", fmt.Errorf(\"oidc: failed to query metadata endpoint %s: %q\", resp.Status, body)\n\t}\n\n\t// Metadata object. We only care about the token_endpoint, the thing endpoint\n\t// we'll be refreshing against.\n\t//\n\t// https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata\n\tvar metadata struct {\n\t\tTokenURL string `json:\"token_endpoint\"`\n\t}\n\tif err := json.Unmarshal(body, \u0026metadata); err != nil {\n\t\treturn \"\", fmt.Errorf(\"oidc: failed to decode provider discovery object: %v\", err)\n\t}\n\tif metadata.TokenURL == \"\" {\n\t\treturn \"\", fmt.Errorf(\"oidc: discovery object doesn't contain a token_endpoint\")\n\t}\n\treturn metadata.TokenURL, nil\n}","line":{"from":290,"to":331}} {"id":100028231,"name":"idTokenExpired","signature":"func idTokenExpired(now func() time.Time, idToken string) (bool, error)","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/oidc/oidc.go","code":"func idTokenExpired(now func() time.Time, idToken string) (bool, error) {\n\tparts := strings.Split(idToken, \".\")\n\tif len(parts) != 3 {\n\t\treturn false, fmt.Errorf(\"ID Token is not a valid JWT\")\n\t}\n\n\tpayload, err := base64.RawURLEncoding.DecodeString(parts[1])\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tvar claims struct {\n\t\tExpiry jsonTime `json:\"exp\"`\n\t}\n\tif err := json.Unmarshal(payload, \u0026claims); err != nil {\n\t\treturn false, fmt.Errorf(\"parsing claims: %v\", err)\n\t}\n\n\treturn now().Add(expiryDelta).Before(time.Time(claims.Expiry)), nil\n}","line":{"from":333,"to":351}} {"id":100028232,"name":"UnmarshalJSON","signature":"func (j *jsonTime) UnmarshalJSON(b []byte) error","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/oidc/oidc.go","code":"func (j *jsonTime) UnmarshalJSON(b []byte) error {\n\tvar n json.Number\n\tif err := json.Unmarshal(b, \u0026n); err != nil {\n\t\treturn err\n\t}\n\tvar unix int64\n\n\tif t, err := n.Int64(); err == nil {\n\t\tunix = t\n\t} else {\n\t\tf, err := n.Float64()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tunix = int64(f)\n\t}\n\t*j = jsonTime(time.Unix(unix, 0))\n\treturn nil\n}","line":{"from":358,"to":376}} {"id":100028233,"name":"MarshalJSON","signature":"func (j jsonTime) MarshalJSON() ([]byte, error)","file":"staging/src/k8s.io/client-go/plugin/pkg/client/auth/oidc/oidc.go","code":"func (j jsonTime) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(time.Time(j).Unix())\n}","line":{"from":378,"to":380}} {"id":100028234,"name":"NewRESTClient","signature":"func NewRESTClient(baseURL *url.URL, versionedAPIPath string, config ClientContentConfig, rateLimiter flowcontrol.RateLimiter, client *http.Client) (*RESTClient, error)","file":"staging/src/k8s.io/client-go/rest/client.go","code":"// NewRESTClient creates a new RESTClient. This client performs generic REST functions\n// such as Get, Put, Post, and Delete on specified paths.\nfunc NewRESTClient(baseURL *url.URL, versionedAPIPath string, config ClientContentConfig, rateLimiter flowcontrol.RateLimiter, client *http.Client) (*RESTClient, error) {\n\tif len(config.ContentType) == 0 {\n\t\tconfig.ContentType = \"application/json\"\n\t}\n\n\tbase := *baseURL\n\tif !strings.HasSuffix(base.Path, \"/\") {\n\t\tbase.Path += \"/\"\n\t}\n\tbase.RawQuery = \"\"\n\tbase.Fragment = \"\"\n\n\treturn \u0026RESTClient{\n\t\tbase: \u0026base,\n\t\tversionedAPIPath: versionedAPIPath,\n\t\tcontent: config,\n\t\tcreateBackoffMgr: readExpBackoffConfig,\n\t\trateLimiter: rateLimiter,\n\n\t\tClient: client,\n\t}, nil\n}","line":{"from":105,"to":128}} {"id":100028235,"name":"GetRateLimiter","signature":"func (c *RESTClient) GetRateLimiter() flowcontrol.RateLimiter","file":"staging/src/k8s.io/client-go/rest/client.go","code":"// GetRateLimiter returns rate limiter for a given client, or nil if it's called on a nil client\nfunc (c *RESTClient) GetRateLimiter() flowcontrol.RateLimiter {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.rateLimiter\n}","line":{"from":130,"to":136}} {"id":100028236,"name":"readExpBackoffConfig","signature":"func readExpBackoffConfig() BackoffManager","file":"staging/src/k8s.io/client-go/rest/client.go","code":"// readExpBackoffConfig handles the internal logic of determining what the\n// backoff policy is. By default if no information is available, NoBackoff.\n// TODO Generalize this see #17727 .\nfunc readExpBackoffConfig() BackoffManager {\n\tbackoffBase := os.Getenv(envBackoffBase)\n\tbackoffDuration := os.Getenv(envBackoffDuration)\n\n\tbackoffBaseInt, errBase := strconv.ParseInt(backoffBase, 10, 64)\n\tbackoffDurationInt, errDuration := strconv.ParseInt(backoffDuration, 10, 64)\n\tif errBase != nil || errDuration != nil {\n\t\treturn \u0026NoBackoff{}\n\t}\n\treturn \u0026URLBackoff{\n\t\tBackoff: flowcontrol.NewBackOff(\n\t\t\ttime.Duration(backoffBaseInt)*time.Second,\n\t\t\ttime.Duration(backoffDurationInt)*time.Second)}\n}","line":{"from":138,"to":154}} {"id":100028237,"name":"Verb","signature":"func (c *RESTClient) Verb(verb string) *Request","file":"staging/src/k8s.io/client-go/rest/client.go","code":"// Verb begins a request with a verb (GET, POST, PUT, DELETE).\n//\n// Example usage of RESTClient's request building interface:\n// c, err := NewRESTClient(...)\n// if err != nil { ... }\n// resp, err := c.Verb(\"GET\").\n//\n//\tPath(\"pods\").\n//\tSelectorParam(\"labels\", \"area=staging\").\n//\tTimeout(10*time.Second).\n//\tDo()\n//\n// if err != nil { ... }\n// list, ok := resp.(*api.PodList)\nfunc (c *RESTClient) Verb(verb string) *Request {\n\treturn NewRequest(c).Verb(verb)\n}","line":{"from":156,"to":172}} {"id":100028238,"name":"Post","signature":"func (c *RESTClient) Post() *Request","file":"staging/src/k8s.io/client-go/rest/client.go","code":"// Post begins a POST request. Short for c.Verb(\"POST\").\nfunc (c *RESTClient) Post() *Request {\n\treturn c.Verb(\"POST\")\n}","line":{"from":174,"to":177}} {"id":100028239,"name":"Put","signature":"func (c *RESTClient) Put() *Request","file":"staging/src/k8s.io/client-go/rest/client.go","code":"// Put begins a PUT request. Short for c.Verb(\"PUT\").\nfunc (c *RESTClient) Put() *Request {\n\treturn c.Verb(\"PUT\")\n}","line":{"from":179,"to":182}} {"id":100028240,"name":"Patch","signature":"func (c *RESTClient) Patch(pt types.PatchType) *Request","file":"staging/src/k8s.io/client-go/rest/client.go","code":"// Patch begins a PATCH request. Short for c.Verb(\"Patch\").\nfunc (c *RESTClient) Patch(pt types.PatchType) *Request {\n\treturn c.Verb(\"PATCH\").SetHeader(\"Content-Type\", string(pt))\n}","line":{"from":184,"to":187}} {"id":100028241,"name":"Get","signature":"func (c *RESTClient) Get() *Request","file":"staging/src/k8s.io/client-go/rest/client.go","code":"// Get begins a GET request. Short for c.Verb(\"GET\").\nfunc (c *RESTClient) Get() *Request {\n\treturn c.Verb(\"GET\")\n}","line":{"from":189,"to":192}} {"id":100028242,"name":"Delete","signature":"func (c *RESTClient) Delete() *Request","file":"staging/src/k8s.io/client-go/rest/client.go","code":"// Delete begins a DELETE request. Short for c.Verb(\"DELETE\").\nfunc (c *RESTClient) Delete() *Request {\n\treturn c.Verb(\"DELETE\")\n}","line":{"from":194,"to":197}} {"id":100028243,"name":"APIVersion","signature":"func (c *RESTClient) APIVersion() schema.GroupVersion","file":"staging/src/k8s.io/client-go/rest/client.go","code":"// APIVersion returns the APIVersion this RESTClient is expected to use.\nfunc (c *RESTClient) APIVersion() schema.GroupVersion {\n\treturn c.content.GroupVersion\n}","line":{"from":199,"to":202}} {"id":100028244,"name":"GoString","signature":"func (sanitizedAuthConfigPersister) GoString() string","file":"staging/src/k8s.io/client-go/rest/config.go","code":"func (sanitizedAuthConfigPersister) GoString() string {\n\treturn \"rest.AuthProviderConfigPersister(--- REDACTED ---)\"\n}","line":{"from":155,"to":157}} {"id":100028245,"name":"String","signature":"func (sanitizedAuthConfigPersister) String() string","file":"staging/src/k8s.io/client-go/rest/config.go","code":"func (sanitizedAuthConfigPersister) String() string {\n\treturn \"rest.AuthProviderConfigPersister(--- REDACTED ---)\"\n}","line":{"from":158,"to":160}} {"id":100028246,"name":"GoString","signature":"func (sanitizedObject) GoString() string","file":"staging/src/k8s.io/client-go/rest/config.go","code":"func (sanitizedObject) GoString() string {\n\treturn \"runtime.Object(--- REDACTED ---)\"\n}","line":{"from":164,"to":166}} {"id":100028247,"name":"String","signature":"func (sanitizedObject) String() string","file":"staging/src/k8s.io/client-go/rest/config.go","code":"func (sanitizedObject) String() string {\n\treturn \"runtime.Object(--- REDACTED ---)\"\n}","line":{"from":167,"to":169}} {"id":100028248,"name":"GoString","signature":"func (c *Config) GoString() string","file":"staging/src/k8s.io/client-go/rest/config.go","code":"// GoString implements fmt.GoStringer and sanitizes sensitive fields of Config\n// to prevent accidental leaking via logs.\nfunc (c *Config) GoString() string {\n\treturn c.String()\n}","line":{"from":171,"to":175}} {"id":100028249,"name":"String","signature":"func (c *Config) String() string","file":"staging/src/k8s.io/client-go/rest/config.go","code":"// String implements fmt.Stringer and sanitizes sensitive fields of Config to\n// prevent accidental leaking via logs.\nfunc (c *Config) String() string {\n\tif c == nil {\n\t\treturn \"\u003cnil\u003e\"\n\t}\n\tcc := sanitizedConfig(CopyConfig(c))\n\t// Explicitly mark non-empty credential fields as redacted.\n\tif cc.Password != \"\" {\n\t\tcc.Password = \"--- REDACTED ---\"\n\t}\n\tif cc.BearerToken != \"\" {\n\t\tcc.BearerToken = \"--- REDACTED ---\"\n\t}\n\tif cc.AuthConfigPersister != nil {\n\t\tcc.AuthConfigPersister = sanitizedAuthConfigPersister{cc.AuthConfigPersister}\n\t}\n\tif cc.ExecProvider != nil \u0026\u0026 cc.ExecProvider.Config != nil {\n\t\tcc.ExecProvider.Config = sanitizedObject{Object: cc.ExecProvider.Config}\n\t}\n\treturn fmt.Sprintf(\"%#v\", cc)\n}","line":{"from":177,"to":198}} {"id":100028250,"name":"GoString","signature":"func (c TLSClientConfig) GoString() string","file":"staging/src/k8s.io/client-go/rest/config.go","code":"// GoString implements fmt.GoStringer and sanitizes sensitive fields of\n// TLSClientConfig to prevent accidental leaking via logs.\nfunc (c TLSClientConfig) GoString() string {\n\treturn c.String()\n}","line":{"from":252,"to":256}} {"id":100028251,"name":"String","signature":"func (c TLSClientConfig) String() string","file":"staging/src/k8s.io/client-go/rest/config.go","code":"// String implements fmt.Stringer and sanitizes sensitive fields of\n// TLSClientConfig to prevent accidental leaking via logs.\nfunc (c TLSClientConfig) String() string {\n\tcc := sanitizedTLSClientConfig{\n\t\tInsecure: c.Insecure,\n\t\tServerName: c.ServerName,\n\t\tCertFile: c.CertFile,\n\t\tKeyFile: c.KeyFile,\n\t\tCAFile: c.CAFile,\n\t\tCertData: c.CertData,\n\t\tKeyData: c.KeyData,\n\t\tCAData: c.CAData,\n\t\tNextProtos: c.NextProtos,\n\t}\n\t// Explicitly mark non-empty credential fields as redacted.\n\tif len(cc.CertData) != 0 {\n\t\tcc.CertData = []byte(\"--- TRUNCATED ---\")\n\t}\n\tif len(cc.KeyData) != 0 {\n\t\tcc.KeyData = []byte(\"--- REDACTED ---\")\n\t}\n\treturn fmt.Sprintf(\"%#v\", cc)\n}","line":{"from":258,"to":280}} {"id":100028252,"name":"RESTClientFor","signature":"func RESTClientFor(config *Config) (*RESTClient, error)","file":"staging/src/k8s.io/client-go/rest/config.go","code":"// RESTClientFor returns a RESTClient that satisfies the requested attributes on a client Config\n// object. Note that a RESTClient may require fields that are optional when initializing a Client.\n// A RESTClient created by this method is generic - it expects to operate on an API that follows\n// the Kubernetes conventions, but may not be the Kubernetes API.\n// RESTClientFor is equivalent to calling RESTClientForConfigAndClient(config, httpClient),\n// where httpClient was generated with HTTPClientFor(config).\nfunc RESTClientFor(config *Config) (*RESTClient, error) {\n\tif config.GroupVersion == nil {\n\t\treturn nil, fmt.Errorf(\"GroupVersion is required when initializing a RESTClient\")\n\t}\n\tif config.NegotiatedSerializer == nil {\n\t\treturn nil, fmt.Errorf(\"NegotiatedSerializer is required when initializing a RESTClient\")\n\t}\n\n\t// Validate config.Host before constructing the transport/client so we can fail fast.\n\t// ServerURL will be obtained later in RESTClientForConfigAndClient()\n\t_, _, err := defaultServerUrlFor(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thttpClient, err := HTTPClientFor(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn RESTClientForConfigAndClient(config, httpClient)\n}","line":{"from":303,"to":330}} {"id":100028253,"name":"RESTClientForConfigAndClient","signature":"func RESTClientForConfigAndClient(config *Config, httpClient *http.Client) (*RESTClient, error)","file":"staging/src/k8s.io/client-go/rest/config.go","code":"// RESTClientForConfigAndClient returns a RESTClient that satisfies the requested attributes on a\n// client Config object.\n// Unlike RESTClientFor, RESTClientForConfigAndClient allows to pass an http.Client that is shared\n// between all the API Groups and Versions.\n// Note that the http client takes precedence over the transport values configured.\n// The http client defaults to the `http.DefaultClient` if nil.\nfunc RESTClientForConfigAndClient(config *Config, httpClient *http.Client) (*RESTClient, error) {\n\tif config.GroupVersion == nil {\n\t\treturn nil, fmt.Errorf(\"GroupVersion is required when initializing a RESTClient\")\n\t}\n\tif config.NegotiatedSerializer == nil {\n\t\treturn nil, fmt.Errorf(\"NegotiatedSerializer is required when initializing a RESTClient\")\n\t}\n\n\tbaseURL, versionedAPIPath, err := defaultServerUrlFor(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trateLimiter := config.RateLimiter\n\tif rateLimiter == nil {\n\t\tqps := config.QPS\n\t\tif config.QPS == 0.0 {\n\t\t\tqps = DefaultQPS\n\t\t}\n\t\tburst := config.Burst\n\t\tif config.Burst == 0 {\n\t\t\tburst = DefaultBurst\n\t\t}\n\t\tif qps \u003e 0 {\n\t\t\trateLimiter = flowcontrol.NewTokenBucketRateLimiter(qps, burst)\n\t\t}\n\t}\n\n\tvar gv schema.GroupVersion\n\tif config.GroupVersion != nil {\n\t\tgv = *config.GroupVersion\n\t}\n\tclientContent := ClientContentConfig{\n\t\tAcceptContentTypes: config.AcceptContentTypes,\n\t\tContentType: config.ContentType,\n\t\tGroupVersion: gv,\n\t\tNegotiator: runtime.NewClientNegotiator(config.NegotiatedSerializer, gv),\n\t}\n\n\trestClient, err := NewRESTClient(baseURL, versionedAPIPath, clientContent, rateLimiter, httpClient)\n\tif err == nil \u0026\u0026 config.WarningHandler != nil {\n\t\trestClient.warningHandler = config.WarningHandler\n\t}\n\treturn restClient, err\n}","line":{"from":332,"to":382}} {"id":100028254,"name":"UnversionedRESTClientFor","signature":"func UnversionedRESTClientFor(config *Config) (*RESTClient, error)","file":"staging/src/k8s.io/client-go/rest/config.go","code":"// UnversionedRESTClientFor is the same as RESTClientFor, except that it allows\n// the config.Version to be empty.\nfunc UnversionedRESTClientFor(config *Config) (*RESTClient, error) {\n\tif config.NegotiatedSerializer == nil {\n\t\treturn nil, fmt.Errorf(\"NegotiatedSerializer is required when initializing a RESTClient\")\n\t}\n\n\t// Validate config.Host before constructing the transport/client so we can fail fast.\n\t// ServerURL will be obtained later in UnversionedRESTClientForConfigAndClient()\n\t_, _, err := defaultServerUrlFor(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thttpClient, err := HTTPClientFor(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn UnversionedRESTClientForConfigAndClient(config, httpClient)\n}","line":{"from":384,"to":404}} {"id":100028255,"name":"UnversionedRESTClientForConfigAndClient","signature":"func UnversionedRESTClientForConfigAndClient(config *Config, httpClient *http.Client) (*RESTClient, error)","file":"staging/src/k8s.io/client-go/rest/config.go","code":"// UnversionedRESTClientForConfigAndClient is the same as RESTClientForConfigAndClient,\n// except that it allows the config.Version to be empty.\nfunc UnversionedRESTClientForConfigAndClient(config *Config, httpClient *http.Client) (*RESTClient, error) {\n\tif config.NegotiatedSerializer == nil {\n\t\treturn nil, fmt.Errorf(\"NegotiatedSerializer is required when initializing a RESTClient\")\n\t}\n\n\tbaseURL, versionedAPIPath, err := defaultServerUrlFor(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trateLimiter := config.RateLimiter\n\tif rateLimiter == nil {\n\t\tqps := config.QPS\n\t\tif config.QPS == 0.0 {\n\t\t\tqps = DefaultQPS\n\t\t}\n\t\tburst := config.Burst\n\t\tif config.Burst == 0 {\n\t\t\tburst = DefaultBurst\n\t\t}\n\t\tif qps \u003e 0 {\n\t\t\trateLimiter = flowcontrol.NewTokenBucketRateLimiter(qps, burst)\n\t\t}\n\t}\n\n\tgv := metav1.SchemeGroupVersion\n\tif config.GroupVersion != nil {\n\t\tgv = *config.GroupVersion\n\t}\n\tclientContent := ClientContentConfig{\n\t\tAcceptContentTypes: config.AcceptContentTypes,\n\t\tContentType: config.ContentType,\n\t\tGroupVersion: gv,\n\t\tNegotiator: runtime.NewClientNegotiator(config.NegotiatedSerializer, gv),\n\t}\n\n\trestClient, err := NewRESTClient(baseURL, versionedAPIPath, clientContent, rateLimiter, httpClient)\n\tif err == nil \u0026\u0026 config.WarningHandler != nil {\n\t\trestClient.warningHandler = config.WarningHandler\n\t}\n\treturn restClient, err\n}","line":{"from":406,"to":449}} {"id":100028256,"name":"SetKubernetesDefaults","signature":"func SetKubernetesDefaults(config *Config) error","file":"staging/src/k8s.io/client-go/rest/config.go","code":"// SetKubernetesDefaults sets default values on the provided client config for accessing the\n// Kubernetes API or returns an error if any of the defaults are impossible or invalid.\nfunc SetKubernetesDefaults(config *Config) error {\n\tif len(config.UserAgent) == 0 {\n\t\tconfig.UserAgent = DefaultKubernetesUserAgent()\n\t}\n\treturn nil\n}","line":{"from":451,"to":458}} {"id":100028257,"name":"adjustCommit","signature":"func adjustCommit(c string) string","file":"staging/src/k8s.io/client-go/rest/config.go","code":"// adjustCommit returns sufficient significant figures of the commit's git hash.\nfunc adjustCommit(c string) string {\n\tif len(c) == 0 {\n\t\treturn \"unknown\"\n\t}\n\tif len(c) \u003e 7 {\n\t\treturn c[:7]\n\t}\n\treturn c\n}","line":{"from":460,"to":469}} {"id":100028258,"name":"adjustVersion","signature":"func adjustVersion(v string) string","file":"staging/src/k8s.io/client-go/rest/config.go","code":"// adjustVersion strips \"alpha\", \"beta\", etc. from version in form\n// major.minor.patch-[alpha|beta|etc].\nfunc adjustVersion(v string) string {\n\tif len(v) == 0 {\n\t\treturn \"unknown\"\n\t}\n\tseg := strings.SplitN(v, \"-\", 2)\n\treturn seg[0]\n}","line":{"from":471,"to":479}} {"id":100028259,"name":"adjustCommand","signature":"func adjustCommand(p string) string","file":"staging/src/k8s.io/client-go/rest/config.go","code":"// adjustCommand returns the last component of the\n// OS-specific command path for use in User-Agent.\nfunc adjustCommand(p string) string {\n\t// Unlikely, but better than returning \"\".\n\tif len(p) == 0 {\n\t\treturn \"unknown\"\n\t}\n\treturn filepath.Base(p)\n}","line":{"from":481,"to":489}} {"id":100028260,"name":"buildUserAgent","signature":"func buildUserAgent(command, version, os, arch, commit string) string","file":"staging/src/k8s.io/client-go/rest/config.go","code":"// buildUserAgent builds a User-Agent string from given args.\nfunc buildUserAgent(command, version, os, arch, commit string) string {\n\treturn fmt.Sprintf(\n\t\t\"%s/%s (%s/%s) kubernetes/%s\", command, version, os, arch, commit)\n}","line":{"from":491,"to":495}} {"id":100028261,"name":"DefaultKubernetesUserAgent","signature":"func DefaultKubernetesUserAgent() string","file":"staging/src/k8s.io/client-go/rest/config.go","code":"// DefaultKubernetesUserAgent returns a User-Agent string built from static global vars.\nfunc DefaultKubernetesUserAgent() string {\n\treturn buildUserAgent(\n\t\tadjustCommand(os.Args[0]),\n\t\tadjustVersion(version.Get().GitVersion),\n\t\tgruntime.GOOS,\n\t\tgruntime.GOARCH,\n\t\tadjustCommit(version.Get().GitCommit))\n}","line":{"from":497,"to":505}} {"id":100028262,"name":"InClusterConfig","signature":"func InClusterConfig() (*Config, error)","file":"staging/src/k8s.io/client-go/rest/config.go","code":"// InClusterConfig returns a config object which uses the service account\n// kubernetes gives to pods. It's intended for clients that expect to be\n// running inside a pod running on kubernetes. It will return ErrNotInCluster\n// if called from a process not running in a kubernetes environment.\nfunc InClusterConfig() (*Config, error) {\n\tconst (\n\t\ttokenFile = \"/var/run/secrets/kubernetes.io/serviceaccount/token\"\n\t\trootCAFile = \"/var/run/secrets/kubernetes.io/serviceaccount/ca.crt\"\n\t)\n\thost, port := os.Getenv(\"KUBERNETES_SERVICE_HOST\"), os.Getenv(\"KUBERNETES_SERVICE_PORT\")\n\tif len(host) == 0 || len(port) == 0 {\n\t\treturn nil, ErrNotInCluster\n\t}\n\n\ttoken, err := os.ReadFile(tokenFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttlsClientConfig := TLSClientConfig{}\n\n\tif _, err := certutil.NewPool(rootCAFile); err != nil {\n\t\tklog.Errorf(\"Expected to load root CA config from %s, but got err: %v\", rootCAFile, err)\n\t} else {\n\t\ttlsClientConfig.CAFile = rootCAFile\n\t}\n\n\treturn \u0026Config{\n\t\t// TODO: switch to using cluster DNS.\n\t\tHost: \"https://\" + net.JoinHostPort(host, port),\n\t\tTLSClientConfig: tlsClientConfig,\n\t\tBearerToken: string(token),\n\t\tBearerTokenFile: tokenFile,\n\t}, nil\n}","line":{"from":507,"to":541}} {"id":100028263,"name":"IsConfigTransportTLS","signature":"func IsConfigTransportTLS(config Config) bool","file":"staging/src/k8s.io/client-go/rest/config.go","code":"// IsConfigTransportTLS returns true if and only if the provided\n// config will result in a protected connection to the server when it\n// is passed to restclient.RESTClientFor(). Use to determine when to\n// send credentials over the wire.\n//\n// Note: the Insecure flag is ignored when testing for this value, so MITM attacks are\n// still possible.\nfunc IsConfigTransportTLS(config Config) bool {\n\tbaseURL, _, err := defaultServerUrlFor(\u0026config)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn baseURL.Scheme == \"https\"\n}","line":{"from":543,"to":556}} {"id":100028264,"name":"LoadTLSFiles","signature":"func LoadTLSFiles(c *Config) error","file":"staging/src/k8s.io/client-go/rest/config.go","code":"// LoadTLSFiles copies the data from the CertFile, KeyFile, and CAFile fields into the CertData,\n// KeyData, and CAFile fields, or returns an error. If no error is returned, all three fields are\n// either populated or were empty to start.\nfunc LoadTLSFiles(c *Config) error {\n\tvar err error\n\tc.CAData, err = dataFromSliceOrFile(c.CAData, c.CAFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.CertData, err = dataFromSliceOrFile(c.CertData, c.CertFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.KeyData, err = dataFromSliceOrFile(c.KeyData, c.KeyFile)\n\treturn err\n}","line":{"from":558,"to":575}} {"id":100028265,"name":"dataFromSliceOrFile","signature":"func dataFromSliceOrFile(data []byte, file string) ([]byte, error)","file":"staging/src/k8s.io/client-go/rest/config.go","code":"// dataFromSliceOrFile returns data from the slice (if non-empty), or from the file,\n// or an error if an error occurred reading the file\nfunc dataFromSliceOrFile(data []byte, file string) ([]byte, error) {\n\tif len(data) \u003e 0 {\n\t\treturn data, nil\n\t}\n\tif len(file) \u003e 0 {\n\t\tfileData, err := os.ReadFile(file)\n\t\tif err != nil {\n\t\t\treturn []byte{}, err\n\t\t}\n\t\treturn fileData, nil\n\t}\n\treturn nil, nil\n}","line":{"from":577,"to":591}} {"id":100028266,"name":"AddUserAgent","signature":"func AddUserAgent(config *Config, userAgent string) *Config","file":"staging/src/k8s.io/client-go/rest/config.go","code":"func AddUserAgent(config *Config, userAgent string) *Config {\n\tfullUserAgent := DefaultKubernetesUserAgent() + \"/\" + userAgent\n\tconfig.UserAgent = fullUserAgent\n\treturn config\n}","line":{"from":593,"to":597}} {"id":100028267,"name":"AnonymousClientConfig","signature":"func AnonymousClientConfig(config *Config) *Config","file":"staging/src/k8s.io/client-go/rest/config.go","code":"// AnonymousClientConfig returns a copy of the given config with all user credentials (cert/key, bearer token, and username/password) and custom transports (WrapTransport, Transport) removed\nfunc AnonymousClientConfig(config *Config) *Config {\n\t// copy only known safe fields\n\treturn \u0026Config{\n\t\tHost: config.Host,\n\t\tAPIPath: config.APIPath,\n\t\tContentConfig: config.ContentConfig,\n\t\tTLSClientConfig: TLSClientConfig{\n\t\t\tInsecure: config.Insecure,\n\t\t\tServerName: config.ServerName,\n\t\t\tCAFile: config.TLSClientConfig.CAFile,\n\t\t\tCAData: config.TLSClientConfig.CAData,\n\t\t\tNextProtos: config.TLSClientConfig.NextProtos,\n\t\t},\n\t\tRateLimiter: config.RateLimiter,\n\t\tWarningHandler: config.WarningHandler,\n\t\tUserAgent: config.UserAgent,\n\t\tDisableCompression: config.DisableCompression,\n\t\tQPS: config.QPS,\n\t\tBurst: config.Burst,\n\t\tTimeout: config.Timeout,\n\t\tDial: config.Dial,\n\t\tProxy: config.Proxy,\n\t}\n}","line":{"from":599,"to":623}} {"id":100028268,"name":"CopyConfig","signature":"func CopyConfig(config *Config) *Config","file":"staging/src/k8s.io/client-go/rest/config.go","code":"// CopyConfig returns a copy of the given config\nfunc CopyConfig(config *Config) *Config {\n\tc := \u0026Config{\n\t\tHost: config.Host,\n\t\tAPIPath: config.APIPath,\n\t\tContentConfig: config.ContentConfig,\n\t\tUsername: config.Username,\n\t\tPassword: config.Password,\n\t\tBearerToken: config.BearerToken,\n\t\tBearerTokenFile: config.BearerTokenFile,\n\t\tImpersonate: ImpersonationConfig{\n\t\t\tUserName: config.Impersonate.UserName,\n\t\t\tUID: config.Impersonate.UID,\n\t\t\tGroups: config.Impersonate.Groups,\n\t\t\tExtra: config.Impersonate.Extra,\n\t\t},\n\t\tAuthProvider: config.AuthProvider,\n\t\tAuthConfigPersister: config.AuthConfigPersister,\n\t\tExecProvider: config.ExecProvider,\n\t\tTLSClientConfig: TLSClientConfig{\n\t\t\tInsecure: config.TLSClientConfig.Insecure,\n\t\t\tServerName: config.TLSClientConfig.ServerName,\n\t\t\tCertFile: config.TLSClientConfig.CertFile,\n\t\t\tKeyFile: config.TLSClientConfig.KeyFile,\n\t\t\tCAFile: config.TLSClientConfig.CAFile,\n\t\t\tCertData: config.TLSClientConfig.CertData,\n\t\t\tKeyData: config.TLSClientConfig.KeyData,\n\t\t\tCAData: config.TLSClientConfig.CAData,\n\t\t\tNextProtos: config.TLSClientConfig.NextProtos,\n\t\t},\n\t\tUserAgent: config.UserAgent,\n\t\tDisableCompression: config.DisableCompression,\n\t\tTransport: config.Transport,\n\t\tWrapTransport: config.WrapTransport,\n\t\tQPS: config.QPS,\n\t\tBurst: config.Burst,\n\t\tRateLimiter: config.RateLimiter,\n\t\tWarningHandler: config.WarningHandler,\n\t\tTimeout: config.Timeout,\n\t\tDial: config.Dial,\n\t\tProxy: config.Proxy,\n\t}\n\tif config.ExecProvider != nil \u0026\u0026 config.ExecProvider.Config != nil {\n\t\tc.ExecProvider.Config = config.ExecProvider.Config.DeepCopyObject()\n\t}\n\treturn c\n}","line":{"from":625,"to":671}} {"id":100028269,"name":"ConfigToExecCluster","signature":"func ConfigToExecCluster(config *Config) (*clientauthenticationapi.Cluster, error)","file":"staging/src/k8s.io/client-go/rest/exec.go","code":"// ConfigToExecCluster creates a clientauthenticationapi.Cluster with the corresponding fields from\n// the provided Config.\nfunc ConfigToExecCluster(config *Config) (*clientauthenticationapi.Cluster, error) {\n\tcaData, err := dataFromSliceOrFile(config.CAData, config.CAFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load CA bundle for execProvider: %v\", err)\n\t}\n\n\tvar proxyURL string\n\tif config.Proxy != nil {\n\t\treq, err := http.NewRequest(\"\", config.Host, nil)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to create proxy URL request for execProvider: %w\", err)\n\t\t}\n\t\turl, err := config.Proxy(req)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get proxy URL for execProvider: %w\", err)\n\t\t}\n\t\tif url != nil {\n\t\t\tproxyURL = url.String()\n\t\t}\n\t}\n\n\treturn \u0026clientauthenticationapi.Cluster{\n\t\tServer: config.Host,\n\t\tTLSServerName: config.ServerName,\n\t\tInsecureSkipTLSVerify: config.Insecure,\n\t\tCertificateAuthorityData: caData,\n\t\tProxyURL: proxyURL,\n\t\tDisableCompression: config.DisableCompression,\n\t\tConfig: config.ExecProvider.Config,\n\t}, nil\n}","line":{"from":29,"to":61}} {"id":100028270,"name":"ExecClusterToConfig","signature":"func ExecClusterToConfig(cluster *clientauthenticationapi.Cluster) (*Config, error)","file":"staging/src/k8s.io/client-go/rest/exec.go","code":"// ExecClusterToConfig creates a Config with the corresponding fields from the provided\n// clientauthenticationapi.Cluster. The returned Config will be anonymous (i.e., it will not have\n// any authentication-related fields set).\nfunc ExecClusterToConfig(cluster *clientauthenticationapi.Cluster) (*Config, error) {\n\tvar proxy func(*http.Request) (*url.URL, error)\n\tif cluster.ProxyURL != \"\" {\n\t\tproxyURL, err := url.Parse(cluster.ProxyURL)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot parse proxy URL: %w\", err)\n\t\t}\n\t\tproxy = http.ProxyURL(proxyURL)\n\t}\n\n\treturn \u0026Config{\n\t\tHost: cluster.Server,\n\t\tTLSClientConfig: TLSClientConfig{\n\t\t\tInsecure: cluster.InsecureSkipTLSVerify,\n\t\t\tServerName: cluster.TLSServerName,\n\t\t\tCAData: cluster.CertificateAuthorityData,\n\t\t},\n\t\tProxy: proxy,\n\t\tDisableCompression: cluster.DisableCompression,\n\t}, nil\n}","line":{"from":63,"to":86}} {"id":100028271,"name":"Persist","signature":"func (n *noopPersister) Persist(_ map[string]string) error","file":"staging/src/k8s.io/client-go/rest/plugin.go","code":"func (n *noopPersister) Persist(_ map[string]string) error {\n\t// no operation persister\n\treturn nil\n}","line":{"from":53,"to":56}} {"id":100028272,"name":"RegisterAuthProviderPlugin","signature":"func RegisterAuthProviderPlugin(name string, plugin Factory) error","file":"staging/src/k8s.io/client-go/rest/plugin.go","code":"func RegisterAuthProviderPlugin(name string, plugin Factory) error {\n\tpluginsLock.Lock()\n\tdefer pluginsLock.Unlock()\n\tif _, found := plugins[name]; found {\n\t\treturn fmt.Errorf(\"auth Provider Plugin %q was registered twice\", name)\n\t}\n\tklog.V(4).Infof(\"Registered Auth Provider Plugin %q\", name)\n\tplugins[name] = plugin\n\treturn nil\n}","line":{"from":62,"to":71}} {"id":100028273,"name":"GetAuthProvider","signature":"func GetAuthProvider(clusterAddress string, apc *clientcmdapi.AuthProviderConfig, persister AuthProviderConfigPersister) (AuthProvider, error)","file":"staging/src/k8s.io/client-go/rest/plugin.go","code":"func GetAuthProvider(clusterAddress string, apc *clientcmdapi.AuthProviderConfig, persister AuthProviderConfigPersister) (AuthProvider, error) {\n\tpluginsLock.Lock()\n\tdefer pluginsLock.Unlock()\n\tp, ok := plugins[apc.Name]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"no Auth Provider found for name %q\", apc.Name)\n\t}\n\tif persister == nil {\n\t\tpersister = \u0026noopPersister{}\n\t}\n\treturn p(clusterAddress, apc.Config, persister)\n}","line":{"from":73,"to":84}} {"id":100028274,"name":"Error","signature":"func (r *RequestConstructionError) Error() string","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// Error returns a textual description of 'r'.\nfunc (r *RequestConstructionError) Error() string {\n\treturn fmt.Sprintf(\"request construction error: '%v'\", r.Err)\n}","line":{"from":79,"to":82}} {"id":100028275,"name":"defaultRequestRetryFn","signature":"func defaultRequestRetryFn(maxRetries int) WithRetry","file":"staging/src/k8s.io/client-go/rest/request.go","code":"func defaultRequestRetryFn(maxRetries int) WithRetry {\n\treturn \u0026withRetry{maxRetries: maxRetries}\n}","line":{"from":88,"to":90}} {"id":100028276,"name":"NewRequest","signature":"func NewRequest(c *RESTClient) *Request","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// NewRequest creates a new request helper object for accessing runtime.Objects on a server.\nfunc NewRequest(c *RESTClient) *Request {\n\tvar backoff BackoffManager\n\tif c.createBackoffMgr != nil {\n\t\tbackoff = c.createBackoffMgr()\n\t}\n\tif backoff == nil {\n\t\tbackoff = noBackoff\n\t}\n\n\tvar pathPrefix string\n\tif c.base != nil {\n\t\tpathPrefix = path.Join(\"/\", c.base.Path, c.versionedAPIPath)\n\t} else {\n\t\tpathPrefix = path.Join(\"/\", c.versionedAPIPath)\n\t}\n\n\tvar timeout time.Duration\n\tif c.Client != nil {\n\t\ttimeout = c.Client.Timeout\n\t}\n\n\tr := \u0026Request{\n\t\tc: c,\n\t\trateLimiter: c.rateLimiter,\n\t\tbackoff: backoff,\n\t\ttimeout: timeout,\n\t\tpathPrefix: pathPrefix,\n\t\tmaxRetries: 10,\n\t\tretryFn: defaultRequestRetryFn,\n\t\twarningHandler: c.warningHandler,\n\t}\n\n\tswitch {\n\tcase len(c.content.AcceptContentTypes) \u003e 0:\n\t\tr.SetHeader(\"Accept\", c.content.AcceptContentTypes)\n\tcase len(c.content.ContentType) \u003e 0:\n\t\tr.SetHeader(\"Accept\", c.content.ContentType+\", */*\")\n\t}\n\treturn r\n}","line":{"from":129,"to":169}} {"id":100028277,"name":"NewRequestWithClient","signature":"func NewRequestWithClient(base *url.URL, versionedAPIPath string, content ClientContentConfig, client *http.Client) *Request","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// NewRequestWithClient creates a Request with an embedded RESTClient for use in test scenarios.\nfunc NewRequestWithClient(base *url.URL, versionedAPIPath string, content ClientContentConfig, client *http.Client) *Request {\n\treturn NewRequest(\u0026RESTClient{\n\t\tbase: base,\n\t\tversionedAPIPath: versionedAPIPath,\n\t\tcontent: content,\n\t\tClient: client,\n\t})\n}","line":{"from":171,"to":179}} {"id":100028278,"name":"Verb","signature":"func (r *Request) Verb(verb string) *Request","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// Verb sets the verb this request will use.\nfunc (r *Request) Verb(verb string) *Request {\n\tr.verb = verb\n\treturn r\n}","line":{"from":181,"to":185}} {"id":100028279,"name":"Prefix","signature":"func (r *Request) Prefix(segments ...string) *Request","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// Prefix adds segments to the relative beginning to the request path. These\n// items will be placed before the optional Namespace, Resource, or Name sections.\n// Setting AbsPath will clear any previously set Prefix segments\nfunc (r *Request) Prefix(segments ...string) *Request {\n\tif r.err != nil {\n\t\treturn r\n\t}\n\tr.pathPrefix = path.Join(r.pathPrefix, path.Join(segments...))\n\treturn r\n}","line":{"from":187,"to":196}} {"id":100028280,"name":"Suffix","signature":"func (r *Request) Suffix(segments ...string) *Request","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// Suffix appends segments to the end of the path. These items will be placed after the prefix and optional\n// Namespace, Resource, or Name sections.\nfunc (r *Request) Suffix(segments ...string) *Request {\n\tif r.err != nil {\n\t\treturn r\n\t}\n\tr.subpath = path.Join(r.subpath, path.Join(segments...))\n\treturn r\n}","line":{"from":198,"to":206}} {"id":100028281,"name":"Resource","signature":"func (r *Request) Resource(resource string) *Request","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// Resource sets the resource to access (\u003cresource\u003e/[ns/\u003cnamespace\u003e/]\u003cname\u003e)\nfunc (r *Request) Resource(resource string) *Request {\n\tif r.err != nil {\n\t\treturn r\n\t}\n\tif len(r.resource) != 0 {\n\t\tr.err = fmt.Errorf(\"resource already set to %q, cannot change to %q\", r.resource, resource)\n\t\treturn r\n\t}\n\tif msgs := IsValidPathSegmentName(resource); len(msgs) != 0 {\n\t\tr.err = fmt.Errorf(\"invalid resource %q: %v\", resource, msgs)\n\t\treturn r\n\t}\n\tr.resource = resource\n\treturn r\n}","line":{"from":208,"to":223}} {"id":100028282,"name":"BackOff","signature":"func (r *Request) BackOff(manager BackoffManager) *Request","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// BackOff sets the request's backoff manager to the one specified,\n// or defaults to the stub implementation if nil is provided\nfunc (r *Request) BackOff(manager BackoffManager) *Request {\n\tif manager == nil {\n\t\tr.backoff = \u0026NoBackoff{}\n\t\treturn r\n\t}\n\n\tr.backoff = manager\n\treturn r\n}","line":{"from":225,"to":235}} {"id":100028283,"name":"WarningHandler","signature":"func (r *Request) WarningHandler(handler WarningHandler) *Request","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// WarningHandler sets the handler this client uses when warning headers are encountered.\n// If set to nil, this client will use the default warning handler (see SetDefaultWarningHandler).\nfunc (r *Request) WarningHandler(handler WarningHandler) *Request {\n\tr.warningHandler = handler\n\treturn r\n}","line":{"from":237,"to":242}} {"id":100028284,"name":"Throttle","signature":"func (r *Request) Throttle(limiter flowcontrol.RateLimiter) *Request","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// Throttle receives a rate-limiter and sets or replaces an existing request limiter\nfunc (r *Request) Throttle(limiter flowcontrol.RateLimiter) *Request {\n\tr.rateLimiter = limiter\n\treturn r\n}","line":{"from":244,"to":248}} {"id":100028285,"name":"SubResource","signature":"func (r *Request) SubResource(subresources ...string) *Request","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// SubResource sets a sub-resource path which can be multiple segments after the resource\n// name but before the suffix.\nfunc (r *Request) SubResource(subresources ...string) *Request {\n\tif r.err != nil {\n\t\treturn r\n\t}\n\tsubresource := path.Join(subresources...)\n\tif len(r.subresource) != 0 {\n\t\tr.err = fmt.Errorf(\"subresource already set to %q, cannot change to %q\", r.subresource, subresource)\n\t\treturn r\n\t}\n\tfor _, s := range subresources {\n\t\tif msgs := IsValidPathSegmentName(s); len(msgs) != 0 {\n\t\t\tr.err = fmt.Errorf(\"invalid subresource %q: %v\", s, msgs)\n\t\t\treturn r\n\t\t}\n\t}\n\tr.subresource = subresource\n\treturn r\n}","line":{"from":250,"to":269}} {"id":100028286,"name":"Name","signature":"func (r *Request) Name(resourceName string) *Request","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// Name sets the name of a resource to access (\u003cresource\u003e/[ns/\u003cnamespace\u003e/]\u003cname\u003e)\nfunc (r *Request) Name(resourceName string) *Request {\n\tif r.err != nil {\n\t\treturn r\n\t}\n\tif len(resourceName) == 0 {\n\t\tr.err = fmt.Errorf(\"resource name may not be empty\")\n\t\treturn r\n\t}\n\tif len(r.resourceName) != 0 {\n\t\tr.err = fmt.Errorf(\"resource name already set to %q, cannot change to %q\", r.resourceName, resourceName)\n\t\treturn r\n\t}\n\tif msgs := IsValidPathSegmentName(resourceName); len(msgs) != 0 {\n\t\tr.err = fmt.Errorf(\"invalid resource name %q: %v\", resourceName, msgs)\n\t\treturn r\n\t}\n\tr.resourceName = resourceName\n\treturn r\n}","line":{"from":271,"to":290}} {"id":100028287,"name":"Namespace","signature":"func (r *Request) Namespace(namespace string) *Request","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// Namespace applies the namespace scope to a request (\u003cresource\u003e/[ns/\u003cnamespace\u003e/]\u003cname\u003e)\nfunc (r *Request) Namespace(namespace string) *Request {\n\tif r.err != nil {\n\t\treturn r\n\t}\n\tif r.namespaceSet {\n\t\tr.err = fmt.Errorf(\"namespace already set to %q, cannot change to %q\", r.namespace, namespace)\n\t\treturn r\n\t}\n\tif msgs := IsValidPathSegmentName(namespace); len(msgs) != 0 {\n\t\tr.err = fmt.Errorf(\"invalid namespace %q: %v\", namespace, msgs)\n\t\treturn r\n\t}\n\tr.namespaceSet = true\n\tr.namespace = namespace\n\treturn r\n}","line":{"from":292,"to":308}} {"id":100028288,"name":"NamespaceIfScoped","signature":"func (r *Request) NamespaceIfScoped(namespace string, scoped bool) *Request","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// NamespaceIfScoped is a convenience function to set a namespace if scoped is true\nfunc (r *Request) NamespaceIfScoped(namespace string, scoped bool) *Request {\n\tif scoped {\n\t\treturn r.Namespace(namespace)\n\t}\n\treturn r\n}","line":{"from":310,"to":316}} {"id":100028289,"name":"AbsPath","signature":"func (r *Request) AbsPath(segments ...string) *Request","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// AbsPath overwrites an existing path with the segments provided. Trailing slashes are preserved\n// when a single segment is passed.\nfunc (r *Request) AbsPath(segments ...string) *Request {\n\tif r.err != nil {\n\t\treturn r\n\t}\n\tr.pathPrefix = path.Join(r.c.base.Path, path.Join(segments...))\n\tif len(segments) == 1 \u0026\u0026 (len(r.c.base.Path) \u003e 1 || len(segments[0]) \u003e 1) \u0026\u0026 strings.HasSuffix(segments[0], \"/\") {\n\t\t// preserve any trailing slashes for legacy behavior\n\t\tr.pathPrefix += \"/\"\n\t}\n\treturn r\n}","line":{"from":318,"to":330}} {"id":100028290,"name":"RequestURI","signature":"func (r *Request) RequestURI(uri string) *Request","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// RequestURI overwrites existing path and parameters with the value of the provided server relative\n// URI.\nfunc (r *Request) RequestURI(uri string) *Request {\n\tif r.err != nil {\n\t\treturn r\n\t}\n\tlocator, err := url.Parse(uri)\n\tif err != nil {\n\t\tr.err = err\n\t\treturn r\n\t}\n\tr.pathPrefix = locator.Path\n\tif len(locator.Query()) \u003e 0 {\n\t\tif r.params == nil {\n\t\t\tr.params = make(url.Values)\n\t\t}\n\t\tfor k, v := range locator.Query() {\n\t\t\tr.params[k] = v\n\t\t}\n\t}\n\treturn r\n}","line":{"from":332,"to":353}} {"id":100028291,"name":"Param","signature":"func (r *Request) Param(paramName, s string) *Request","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// Param creates a query parameter with the given string value.\nfunc (r *Request) Param(paramName, s string) *Request {\n\tif r.err != nil {\n\t\treturn r\n\t}\n\treturn r.setParam(paramName, s)\n}","line":{"from":355,"to":361}} {"id":100028292,"name":"VersionedParams","signature":"func (r *Request) VersionedParams(obj runtime.Object, codec runtime.ParameterCodec) *Request","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// VersionedParams will take the provided object, serialize it to a map[string][]string using the\n// implicit RESTClient API version and the default parameter codec, and then add those as parameters\n// to the request. Use this to provide versioned query parameters from client libraries.\n// VersionedParams will not write query parameters that have omitempty set and are empty. If a\n// parameter has already been set it is appended to (Params and VersionedParams are additive).\nfunc (r *Request) VersionedParams(obj runtime.Object, codec runtime.ParameterCodec) *Request {\n\treturn r.SpecificallyVersionedParams(obj, codec, r.c.content.GroupVersion)\n}","line":{"from":363,"to":370}} {"id":100028293,"name":"SpecificallyVersionedParams","signature":"func (r *Request) SpecificallyVersionedParams(obj runtime.Object, codec runtime.ParameterCodec, version schema.GroupVersion) *Request","file":"staging/src/k8s.io/client-go/rest/request.go","code":"func (r *Request) SpecificallyVersionedParams(obj runtime.Object, codec runtime.ParameterCodec, version schema.GroupVersion) *Request {\n\tif r.err != nil {\n\t\treturn r\n\t}\n\tparams, err := codec.EncodeParameters(obj, version)\n\tif err != nil {\n\t\tr.err = err\n\t\treturn r\n\t}\n\tfor k, v := range params {\n\t\tif r.params == nil {\n\t\t\tr.params = make(url.Values)\n\t\t}\n\t\tr.params[k] = append(r.params[k], v...)\n\t}\n\treturn r\n}","line":{"from":372,"to":388}} {"id":100028294,"name":"setParam","signature":"func (r *Request) setParam(paramName, value string) *Request","file":"staging/src/k8s.io/client-go/rest/request.go","code":"func (r *Request) setParam(paramName, value string) *Request {\n\tif r.params == nil {\n\t\tr.params = make(url.Values)\n\t}\n\tr.params[paramName] = append(r.params[paramName], value)\n\treturn r\n}","line":{"from":390,"to":396}} {"id":100028295,"name":"SetHeader","signature":"func (r *Request) SetHeader(key string, values ...string) *Request","file":"staging/src/k8s.io/client-go/rest/request.go","code":"func (r *Request) SetHeader(key string, values ...string) *Request {\n\tif r.headers == nil {\n\t\tr.headers = http.Header{}\n\t}\n\tr.headers.Del(key)\n\tfor _, value := range values {\n\t\tr.headers.Add(key, value)\n\t}\n\treturn r\n}","line":{"from":398,"to":407}} {"id":100028296,"name":"Timeout","signature":"func (r *Request) Timeout(d time.Duration) *Request","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// Timeout makes the request use the given duration as an overall timeout for the\n// request. Additionally, if set passes the value as \"timeout\" parameter in URL.\nfunc (r *Request) Timeout(d time.Duration) *Request {\n\tif r.err != nil {\n\t\treturn r\n\t}\n\tr.timeout = d\n\treturn r\n}","line":{"from":409,"to":417}} {"id":100028297,"name":"MaxRetries","signature":"func (r *Request) MaxRetries(maxRetries int) *Request","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// MaxRetries makes the request use the given integer as a ceiling of retrying upon receiving\n// \"Retry-After\" headers and 429 status-code in the response. The default is 10 unless this\n// function is specifically called with a different value.\n// A zero maxRetries prevent it from doing retires and return an error immediately.\nfunc (r *Request) MaxRetries(maxRetries int) *Request {\n\tif maxRetries \u003c 0 {\n\t\tmaxRetries = 0\n\t}\n\tr.maxRetries = maxRetries\n\treturn r\n}","line":{"from":419,"to":429}} {"id":100028298,"name":"Body","signature":"func (r *Request) Body(obj interface{}) *Request","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// Body makes the request use obj as the body. Optional.\n// If obj is a string, try to read a file of that name.\n// If obj is a []byte, send it directly.\n// If obj is an io.Reader, use it directly.\n// If obj is a runtime.Object, marshal it correctly, and set Content-Type header.\n// If obj is a runtime.Object and nil, do nothing.\n// Otherwise, set an error.\nfunc (r *Request) Body(obj interface{}) *Request {\n\tif r.err != nil {\n\t\treturn r\n\t}\n\tswitch t := obj.(type) {\n\tcase string:\n\t\tdata, err := os.ReadFile(t)\n\t\tif err != nil {\n\t\t\tr.err = err\n\t\t\treturn r\n\t\t}\n\t\tglogBody(\"Request Body\", data)\n\t\tr.body = nil\n\t\tr.bodyBytes = data\n\tcase []byte:\n\t\tglogBody(\"Request Body\", t)\n\t\tr.body = nil\n\t\tr.bodyBytes = t\n\tcase io.Reader:\n\t\tr.body = t\n\t\tr.bodyBytes = nil\n\tcase runtime.Object:\n\t\t// callers may pass typed interface pointers, therefore we must check nil with reflection\n\t\tif reflect.ValueOf(t).IsNil() {\n\t\t\treturn r\n\t\t}\n\t\tencoder, err := r.c.content.Negotiator.Encoder(r.c.content.ContentType, nil)\n\t\tif err != nil {\n\t\t\tr.err = err\n\t\t\treturn r\n\t\t}\n\t\tdata, err := runtime.Encode(encoder, t)\n\t\tif err != nil {\n\t\t\tr.err = err\n\t\t\treturn r\n\t\t}\n\t\tglogBody(\"Request Body\", data)\n\t\tr.body = nil\n\t\tr.bodyBytes = data\n\t\tr.SetHeader(\"Content-Type\", r.c.content.ContentType)\n\tdefault:\n\t\tr.err = fmt.Errorf(\"unknown type used for body: %+v\", obj)\n\t}\n\treturn r\n}","line":{"from":431,"to":482}} {"id":100028299,"name":"Error","signature":"func (r *Request) Error() error","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// Error returns any error encountered constructing the request, if any.\nfunc (r *Request) Error() error {\n\treturn r.err\n}","line":{"from":484,"to":487}} {"id":100028300,"name":"URL","signature":"func (r *Request) URL() *url.URL","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// URL returns the current working URL. Check the result of Error() to ensure\n// that the returned URL is valid.\nfunc (r *Request) URL() *url.URL {\n\tp := r.pathPrefix\n\tif r.namespaceSet \u0026\u0026 len(r.namespace) \u003e 0 {\n\t\tp = path.Join(p, \"namespaces\", r.namespace)\n\t}\n\tif len(r.resource) != 0 {\n\t\tp = path.Join(p, strings.ToLower(r.resource))\n\t}\n\t// Join trims trailing slashes, so preserve r.pathPrefix's trailing slash for backwards compatibility if nothing was changed\n\tif len(r.resourceName) != 0 || len(r.subpath) != 0 || len(r.subresource) != 0 {\n\t\tp = path.Join(p, r.resourceName, r.subresource, r.subpath)\n\t}\n\n\tfinalURL := \u0026url.URL{}\n\tif r.c.base != nil {\n\t\t*finalURL = *r.c.base\n\t}\n\tfinalURL.Path = p\n\n\tquery := url.Values{}\n\tfor key, values := range r.params {\n\t\tfor _, value := range values {\n\t\t\tquery.Add(key, value)\n\t\t}\n\t}\n\n\t// timeout is handled specially here.\n\tif r.timeout != 0 {\n\t\tquery.Set(\"timeout\", r.timeout.String())\n\t}\n\tfinalURL.RawQuery = query.Encode()\n\treturn finalURL\n}","line":{"from":489,"to":523}} {"id":100028301,"name":"finalURLTemplate","signature":"func (r Request) finalURLTemplate() url.URL","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// finalURLTemplate is similar to URL(), but will make all specific parameter values equal\n// - instead of name or namespace, \"{name}\" and \"{namespace}\" will be used, and all query\n// parameters will be reset. This creates a copy of the url so as not to change the\n// underlying object.\nfunc (r Request) finalURLTemplate() url.URL {\n\tnewParams := url.Values{}\n\tv := []string{\"{value}\"}\n\tfor k := range r.params {\n\t\tnewParams[k] = v\n\t}\n\tr.params = newParams\n\tu := r.URL()\n\tif u == nil {\n\t\treturn url.URL{}\n\t}\n\n\tsegments := strings.Split(u.Path, \"/\")\n\tgroupIndex := 0\n\tindex := 0\n\ttrimmedBasePath := \"\"\n\tif r.c.base != nil \u0026\u0026 strings.Contains(u.Path, r.c.base.Path) {\n\t\tp := strings.TrimPrefix(u.Path, r.c.base.Path)\n\t\tif !strings.HasPrefix(p, \"/\") {\n\t\t\tp = \"/\" + p\n\t\t}\n\t\t// store the base path that we have trimmed so we can append it\n\t\t// before returning the URL\n\t\ttrimmedBasePath = r.c.base.Path\n\t\tsegments = strings.Split(p, \"/\")\n\t\tgroupIndex = 1\n\t}\n\tif len(segments) \u003c= 2 {\n\t\treturn *u\n\t}\n\n\tconst CoreGroupPrefix = \"api\"\n\tconst NamedGroupPrefix = \"apis\"\n\tisCoreGroup := segments[groupIndex] == CoreGroupPrefix\n\tisNamedGroup := segments[groupIndex] == NamedGroupPrefix\n\tif isCoreGroup {\n\t\t// checking the case of core group with /api/v1/... format\n\t\tindex = groupIndex + 2\n\t} else if isNamedGroup {\n\t\t// checking the case of named group with /apis/apps/v1/... format\n\t\tindex = groupIndex + 3\n\t} else {\n\t\t// this should not happen that the only two possibilities are /api... and /apis..., just want to put an\n\t\t// outlet here in case more API groups are added in future if ever possible:\n\t\t// https://kubernetes.io/docs/concepts/overview/kubernetes-api/#api-groups\n\t\t// if a wrong API groups name is encountered, return the {prefix} for url.Path\n\t\tu.Path = \"/{prefix}\"\n\t\tu.RawQuery = \"\"\n\t\treturn *u\n\t}\n\t// switch segLength := len(segments) - index; segLength {\n\tswitch {\n\t// case len(segments) - index == 1:\n\t// resource (with no name) do nothing\n\tcase len(segments)-index == 2:\n\t\t// /$RESOURCE/$NAME: replace $NAME with {name}\n\t\tsegments[index+1] = \"{name}\"\n\tcase len(segments)-index == 3:\n\t\tif segments[index+2] == \"finalize\" || segments[index+2] == \"status\" {\n\t\t\t// /$RESOURCE/$NAME/$SUBRESOURCE: replace $NAME with {name}\n\t\t\tsegments[index+1] = \"{name}\"\n\t\t} else {\n\t\t\t// /namespace/$NAMESPACE/$RESOURCE: replace $NAMESPACE with {namespace}\n\t\t\tsegments[index+1] = \"{namespace}\"\n\t\t}\n\tcase len(segments)-index \u003e= 4:\n\t\tsegments[index+1] = \"{namespace}\"\n\t\t// /namespace/$NAMESPACE/$RESOURCE/$NAME: replace $NAMESPACE with {namespace}, $NAME with {name}\n\t\tif segments[index+3] != \"finalize\" \u0026\u0026 segments[index+3] != \"status\" {\n\t\t\t// /$RESOURCE/$NAME/$SUBRESOURCE: replace $NAME with {name}\n\t\t\tsegments[index+3] = \"{name}\"\n\t\t}\n\t}\n\tu.Path = path.Join(trimmedBasePath, path.Join(segments...))\n\treturn *u\n}","line":{"from":525,"to":604}} {"id":100028302,"name":"tryThrottleWithInfo","signature":"func (r *Request) tryThrottleWithInfo(ctx context.Context, retryInfo string) error","file":"staging/src/k8s.io/client-go/rest/request.go","code":"func (r *Request) tryThrottleWithInfo(ctx context.Context, retryInfo string) error {\n\tif r.rateLimiter == nil {\n\t\treturn nil\n\t}\n\n\tnow := time.Now()\n\n\terr := r.rateLimiter.Wait(ctx)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"client rate limiter Wait returned an error: %w\", err)\n\t}\n\tlatency := time.Since(now)\n\n\tvar message string\n\tswitch {\n\tcase len(retryInfo) \u003e 0:\n\t\tmessage = fmt.Sprintf(\"Waited for %v, %s - request: %s:%s\", latency, retryInfo, r.verb, r.URL().String())\n\tdefault:\n\t\tmessage = fmt.Sprintf(\"Waited for %v due to client-side throttling, not priority and fairness, request: %s:%s\", latency, r.verb, r.URL().String())\n\t}\n\n\tif latency \u003e longThrottleLatency {\n\t\tklog.V(3).Info(message)\n\t}\n\tif latency \u003e extraLongThrottleLatency {\n\t\t// If the rate limiter latency is very high, the log message should be printed at a higher log level,\n\t\t// but we use a throttled logger to prevent spamming.\n\t\tglobalThrottledLogger.Infof(\"%s\", message)\n\t}\n\tmetrics.RateLimiterLatency.Observe(ctx, r.verb, r.finalURLTemplate(), latency)\n\n\treturn err\n}","line":{"from":606,"to":638}} {"id":100028303,"name":"tryThrottle","signature":"func (r *Request) tryThrottle(ctx context.Context) error","file":"staging/src/k8s.io/client-go/rest/request.go","code":"func (r *Request) tryThrottle(ctx context.Context) error {\n\treturn r.tryThrottleWithInfo(ctx, \"\")\n}","line":{"from":640,"to":642}} {"id":100028304,"name":"attemptToLog","signature":"func (b *throttledLogger) attemptToLog() (klog.Level, bool)","file":"staging/src/k8s.io/client-go/rest/request.go","code":"func (b *throttledLogger) attemptToLog() (klog.Level, bool) {\n\tfor _, setting := range b.settings {\n\t\tif bool(klog.V(setting.logLevel).Enabled()) {\n\t\t\t// Return early without write locking if possible.\n\t\t\tif func() bool {\n\t\t\t\tsetting.lock.RLock()\n\t\t\t\tdefer setting.lock.RUnlock()\n\t\t\t\treturn b.clock.Since(setting.lastLogTime) \u003e= setting.minLogInterval\n\t\t\t}() {\n\t\t\t\tsetting.lock.Lock()\n\t\t\t\tdefer setting.lock.Unlock()\n\t\t\t\tif b.clock.Since(setting.lastLogTime) \u003e= setting.minLogInterval {\n\t\t\t\t\tsetting.lastLogTime = b.clock.Now()\n\t\t\t\t\treturn setting.logLevel, true\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn -1, false\n\t\t}\n\t}\n\treturn -1, false\n}","line":{"from":670,"to":690}} {"id":100028305,"name":"Infof","signature":"func (b *throttledLogger) Infof(message string, args ...interface{})","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// Infof will write a log message at each logLevel specified by the receiver's throttleSettings\n// as long as it hasn't written a log message more recently than minLogInterval.\nfunc (b *throttledLogger) Infof(message string, args ...interface{}) {\n\tif logLevel, ok := b.attemptToLog(); ok {\n\t\tklog.V(logLevel).Infof(message, args...)\n\t}\n}","line":{"from":692,"to":698}} {"id":100028306,"name":"Watch","signature":"func (r *Request) Watch(ctx context.Context) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// Watch attempts to begin watching the requested location.\n// Returns a watch.Interface, or an error.\nfunc (r *Request) Watch(ctx context.Context) (watch.Interface, error) {\n\t// We specifically don't want to rate limit watches, so we\n\t// don't use r.rateLimiter here.\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\n\tclient := r.c.Client\n\tif client == nil {\n\t\tclient = http.DefaultClient\n\t}\n\n\tisErrRetryableFunc := func(request *http.Request, err error) bool {\n\t\t// The watch stream mechanism handles many common partial data errors, so closed\n\t\t// connections can be retried in many cases.\n\t\tif net.IsProbableEOF(err) || net.IsTimeout(err) {\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\tretry := r.retryFn(r.maxRetries)\n\turl := r.URL().String()\n\tfor {\n\t\tif err := retry.Before(ctx, r); err != nil {\n\t\t\treturn nil, retry.WrapPreviousError(err)\n\t\t}\n\n\t\treq, err := r.newHTTPRequest(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tresp, err := client.Do(req)\n\t\tretry.After(ctx, r, resp, err)\n\t\tif err == nil \u0026\u0026 resp.StatusCode == http.StatusOK {\n\t\t\treturn r.newStreamWatcher(resp)\n\t\t}\n\n\t\tdone, transformErr := func() (bool, error) {\n\t\t\tdefer readAndCloseResponseBody(resp)\n\n\t\t\tif retry.IsNextRetry(ctx, r, req, resp, err, isErrRetryableFunc) {\n\t\t\t\treturn false, nil\n\t\t\t}\n\n\t\t\tif resp == nil {\n\t\t\t\t// the server must have sent us an error in 'err'\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\tif result := r.transformResponse(resp, req); result.err != nil {\n\t\t\t\treturn true, result.err\n\t\t\t}\n\t\t\treturn true, fmt.Errorf(\"for request %s, got status: %v\", url, resp.StatusCode)\n\t\t}()\n\t\tif done {\n\t\t\tif isErrRetryableFunc(req, err) {\n\t\t\t\treturn watch.NewEmptyWatch(), nil\n\t\t\t}\n\t\t\tif err == nil {\n\t\t\t\t// if the server sent us an HTTP Response object,\n\t\t\t\t// we need to return the error object from that.\n\t\t\t\terr = transformErr\n\t\t\t}\n\t\t\treturn nil, retry.WrapPreviousError(err)\n\t\t}\n\t}\n}","line":{"from":700,"to":768}} {"id":100028307,"name":"newStreamWatcher","signature":"func (r *Request) newStreamWatcher(resp *http.Response) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/rest/request.go","code":"func (r *Request) newStreamWatcher(resp *http.Response) (watch.Interface, error) {\n\tcontentType := resp.Header.Get(\"Content-Type\")\n\tmediaType, params, err := mime.ParseMediaType(contentType)\n\tif err != nil {\n\t\tklog.V(4).Infof(\"Unexpected content type from the server: %q: %v\", contentType, err)\n\t}\n\tobjectDecoder, streamingSerializer, framer, err := r.c.content.Negotiator.StreamDecoder(mediaType, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thandleWarnings(resp.Header, r.warningHandler)\n\n\tframeReader := framer.NewFrameReader(resp.Body)\n\twatchEventDecoder := streaming.NewDecoder(frameReader, streamingSerializer)\n\n\treturn watch.NewStreamWatcher(\n\t\trestclientwatch.NewDecoder(watchEventDecoder, objectDecoder),\n\t\t// use 500 to indicate that the cause of the error is unknown - other error codes\n\t\t// are more specific to HTTP interactions, and set a reason\n\t\terrors.NewClientErrorReporter(http.StatusInternalServerError, r.verb, \"ClientWatchDecoding\"),\n\t), nil\n}","line":{"from":770,"to":792}} {"id":100028308,"name":"updateRequestResultMetric","signature":"func updateRequestResultMetric(ctx context.Context, req *Request, resp *http.Response, err error)","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// updateRequestResultMetric increments the RequestResult metric counter,\n// it should be called with the (response, err) tuple from the final\n// reply from the server.\nfunc updateRequestResultMetric(ctx context.Context, req *Request, resp *http.Response, err error) {\n\tcode, host := sanitize(req, resp, err)\n\tmetrics.RequestResult.Increment(ctx, code, req.verb, host)\n}","line":{"from":794,"to":800}} {"id":100028309,"name":"updateRequestRetryMetric","signature":"func updateRequestRetryMetric(ctx context.Context, req *Request, resp *http.Response, err error)","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// updateRequestRetryMetric increments the RequestRetry metric counter,\n// it should be called with the (response, err) tuple for each retry\n// except for the final attempt.\nfunc updateRequestRetryMetric(ctx context.Context, req *Request, resp *http.Response, err error) {\n\tcode, host := sanitize(req, resp, err)\n\tmetrics.RequestRetry.IncrementRetry(ctx, code, req.verb, host)\n}","line":{"from":802,"to":808}} {"id":100028310,"name":"sanitize","signature":"func sanitize(req *Request, resp *http.Response, err error) (string, string)","file":"staging/src/k8s.io/client-go/rest/request.go","code":"func sanitize(req *Request, resp *http.Response, err error) (string, string) {\n\thost := \"none\"\n\tif req.c.base != nil {\n\t\thost = req.c.base.Host\n\t}\n\n\t// Errors can be arbitrary strings. Unbound label cardinality is not suitable for a metric\n\t// system so we just report them as `\u003cerror\u003e`.\n\tcode := \"\u003cerror\u003e\"\n\tif resp != nil {\n\t\tcode = strconv.Itoa(resp.StatusCode)\n\t}\n\n\treturn code, host\n}","line":{"from":810,"to":824}} {"id":100028311,"name":"Stream","signature":"func (r *Request) Stream(ctx context.Context) (io.ReadCloser, error)","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// Stream formats and executes the request, and offers streaming of the response.\n// Returns io.ReadCloser which could be used for streaming of the response, or an error\n// Any non-2xx http status code causes an error. If we get a non-2xx code, we try to convert the body into an APIStatus object.\n// If we can, we return that as an error. Otherwise, we create an error that lists the http status and the content of the response.\nfunc (r *Request) Stream(ctx context.Context) (io.ReadCloser, error) {\n\tif r.err != nil {\n\t\treturn nil, r.err\n\t}\n\n\tif err := r.tryThrottle(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := r.c.Client\n\tif client == nil {\n\t\tclient = http.DefaultClient\n\t}\n\n\tretry := r.retryFn(r.maxRetries)\n\turl := r.URL().String()\n\tfor {\n\t\tif err := retry.Before(ctx, r); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treq, err := r.newHTTPRequest(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresp, err := client.Do(req)\n\t\tretry.After(ctx, r, resp, err)\n\t\tif err != nil {\n\t\t\t// we only retry on an HTTP response with 'Retry-After' header\n\t\t\treturn nil, err\n\t\t}\n\n\t\tswitch {\n\t\tcase (resp.StatusCode \u003e= 200) \u0026\u0026 (resp.StatusCode \u003c 300):\n\t\t\thandleWarnings(resp.Header, r.warningHandler)\n\t\t\treturn resp.Body, nil\n\n\t\tdefault:\n\t\t\tdone, transformErr := func() (bool, error) {\n\t\t\t\tdefer resp.Body.Close()\n\n\t\t\t\tif retry.IsNextRetry(ctx, r, req, resp, err, neverRetryError) {\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t\tresult := r.transformResponse(resp, req)\n\t\t\t\tif err := result.Error(); err != nil {\n\t\t\t\t\treturn true, err\n\t\t\t\t}\n\t\t\t\treturn true, fmt.Errorf(\"%d while accessing %v: %s\", result.statusCode, url, string(result.body))\n\t\t\t}()\n\t\t\tif done {\n\t\t\t\treturn nil, transformErr\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":826,"to":885}} {"id":100028312,"name":"requestPreflightCheck","signature":"func (r *Request) requestPreflightCheck() error","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// requestPreflightCheck looks for common programmer errors on Request.\n//\n// We tackle here two programmer mistakes. The first one is to try to create\n// something(POST) using an empty string as namespace with namespaceSet as\n// true. If namespaceSet is true then namespace should also be defined. The\n// second mistake is, when under the same circumstances, the programmer tries\n// to GET, PUT or DELETE a named resource(resourceName != \"\"), again, if\n// namespaceSet is true then namespace must not be empty.\nfunc (r *Request) requestPreflightCheck() error {\n\tif !r.namespaceSet {\n\t\treturn nil\n\t}\n\tif len(r.namespace) \u003e 0 {\n\t\treturn nil\n\t}\n\n\tswitch r.verb {\n\tcase \"POST\":\n\t\treturn fmt.Errorf(\"an empty namespace may not be set during creation\")\n\tcase \"GET\", \"PUT\", \"DELETE\":\n\t\tif len(r.resourceName) \u003e 0 {\n\t\t\treturn fmt.Errorf(\"an empty namespace may not be set when a resource name is provided\")\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":887,"to":912}} {"id":100028313,"name":"newHTTPRequest","signature":"func (r *Request) newHTTPRequest(ctx context.Context) (*http.Request, error)","file":"staging/src/k8s.io/client-go/rest/request.go","code":"func (r *Request) newHTTPRequest(ctx context.Context) (*http.Request, error) {\n\tvar body io.Reader\n\tswitch {\n\tcase r.body != nil \u0026\u0026 r.bodyBytes != nil:\n\t\treturn nil, fmt.Errorf(\"cannot set both body and bodyBytes\")\n\tcase r.body != nil:\n\t\tbody = r.body\n\tcase r.bodyBytes != nil:\n\t\t// Create a new reader specifically for this request.\n\t\t// Giving each request a dedicated reader allows retries to avoid races resetting the request body.\n\t\tbody = bytes.NewReader(r.bodyBytes)\n\t}\n\n\turl := r.URL().String()\n\treq, err := http.NewRequest(r.verb, url, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq = req.WithContext(ctx)\n\treq.Header = r.headers\n\treturn req, nil\n}","line":{"from":914,"to":935}} {"id":100028314,"name":"request","signature":"func (r *Request) request(ctx context.Context, fn func(*http.Request, *http.Response)) error","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// request connects to the server and invokes the provided function when a server response is\n// received. It handles retry behavior and up front validation of requests. It will invoke\n// fn at most once. It will return an error if a problem occurred prior to connecting to the\n// server - the provided function is responsible for handling server errors.\nfunc (r *Request) request(ctx context.Context, fn func(*http.Request, *http.Response)) error {\n\t// Metrics for total request latency\n\tstart := time.Now()\n\tdefer func() {\n\t\tmetrics.RequestLatency.Observe(ctx, r.verb, r.finalURLTemplate(), time.Since(start))\n\t}()\n\n\tif r.err != nil {\n\t\tklog.V(4).Infof(\"Error in request: %v\", r.err)\n\t\treturn r.err\n\t}\n\n\tif err := r.requestPreflightCheck(); err != nil {\n\t\treturn err\n\t}\n\n\tclient := r.c.Client\n\tif client == nil {\n\t\tclient = http.DefaultClient\n\t}\n\n\t// Throttle the first try before setting up the timeout configured on the\n\t// client. We don't want a throttled client to return timeouts to callers\n\t// before it makes a single request.\n\tif err := r.tryThrottle(ctx); err != nil {\n\t\treturn err\n\t}\n\n\tif r.timeout \u003e 0 {\n\t\tvar cancel context.CancelFunc\n\t\tctx, cancel = context.WithTimeout(ctx, r.timeout)\n\t\tdefer cancel()\n\t}\n\n\tisErrRetryableFunc := func(req *http.Request, err error) bool {\n\t\t// \"Connection reset by peer\" or \"apiserver is shutting down\" are usually a transient errors.\n\t\t// Thus in case of \"GET\" operations, we simply retry it.\n\t\t// We are not automatically retrying \"write\" operations, as they are not idempotent.\n\t\tif req.Method != \"GET\" {\n\t\t\treturn false\n\t\t}\n\t\t// For connection errors and apiserver shutdown errors retry.\n\t\tif net.IsConnectionReset(err) || net.IsProbableEOF(err) {\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\t// Right now we make about ten retry attempts if we get a Retry-After response.\n\tretry := r.retryFn(r.maxRetries)\n\tfor {\n\t\tif err := retry.Before(ctx, r); err != nil {\n\t\t\treturn retry.WrapPreviousError(err)\n\t\t}\n\t\treq, err := r.newHTTPRequest(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresp, err := client.Do(req)\n\t\t// The value -1 or a value of 0 with a non-nil Body indicates that the length is unknown.\n\t\t// https://pkg.go.dev/net/http#Request\n\t\tif req.ContentLength \u003e= 0 \u0026\u0026 !(req.Body != nil \u0026\u0026 req.ContentLength == 0) {\n\t\t\tmetrics.RequestSize.Observe(ctx, r.verb, r.URL().Host, float64(req.ContentLength))\n\t\t}\n\t\tretry.After(ctx, r, resp, err)\n\n\t\tdone := func() bool {\n\t\t\tdefer readAndCloseResponseBody(resp)\n\n\t\t\t// if the server returns an error in err, the response will be nil.\n\t\t\tf := func(req *http.Request, resp *http.Response) {\n\t\t\t\tif resp == nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tfn(req, resp)\n\t\t\t}\n\n\t\t\tif retry.IsNextRetry(ctx, r, req, resp, err, isErrRetryableFunc) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tf(req, resp)\n\t\t\treturn true\n\t\t}()\n\t\tif done {\n\t\t\treturn retry.WrapPreviousError(err)\n\t\t}\n\t}\n}","line":{"from":937,"to":1029}} {"id":100028315,"name":"Do","signature":"func (r *Request) Do(ctx context.Context) Result","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// Do formats and executes the request. Returns a Result object for easy response\n// processing.\n//\n// Error type:\n// - If the server responds with a status: *errors.StatusError or *errors.UnexpectedObjectError\n// - http.Client.Do errors are returned directly.\nfunc (r *Request) Do(ctx context.Context) Result {\n\tvar result Result\n\terr := r.request(ctx, func(req *http.Request, resp *http.Response) {\n\t\tresult = r.transformResponse(resp, req)\n\t})\n\tif err != nil {\n\t\treturn Result{err: err}\n\t}\n\tif result.err == nil || len(result.body) \u003e 0 {\n\t\tmetrics.ResponseSize.Observe(ctx, r.verb, r.URL().Host, float64(len(result.body)))\n\t}\n\treturn result\n}","line":{"from":1031,"to":1049}} {"id":100028316,"name":"DoRaw","signature":"func (r *Request) DoRaw(ctx context.Context) ([]byte, error)","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// DoRaw executes the request but does not process the response body.\nfunc (r *Request) DoRaw(ctx context.Context) ([]byte, error) {\n\tvar result Result\n\terr := r.request(ctx, func(req *http.Request, resp *http.Response) {\n\t\tresult.body, result.err = io.ReadAll(resp.Body)\n\t\tglogBody(\"Response Body\", result.body)\n\t\tif resp.StatusCode \u003c http.StatusOK || resp.StatusCode \u003e http.StatusPartialContent {\n\t\t\tresult.err = r.transformUnstructuredResponseError(resp, req, result.body)\n\t\t}\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif result.err == nil || len(result.body) \u003e 0 {\n\t\tmetrics.ResponseSize.Observe(ctx, r.verb, r.URL().Host, float64(len(result.body)))\n\t}\n\treturn result.body, result.err\n}","line":{"from":1051,"to":1068}} {"id":100028317,"name":"transformResponse","signature":"func (r *Request) transformResponse(resp *http.Response, req *http.Request) Result","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// transformResponse converts an API response into a structured API object\nfunc (r *Request) transformResponse(resp *http.Response, req *http.Request) Result {\n\tvar body []byte\n\tif resp.Body != nil {\n\t\tdata, err := io.ReadAll(resp.Body)\n\t\tswitch err.(type) {\n\t\tcase nil:\n\t\t\tbody = data\n\t\tcase http2.StreamError:\n\t\t\t// This is trying to catch the scenario that the server may close the connection when sending the\n\t\t\t// response body. This can be caused by server timeout due to a slow network connection.\n\t\t\t// TODO: Add test for this. Steps may be:\n\t\t\t// 1. client-go (or kubectl) sends a GET request.\n\t\t\t// 2. Apiserver sends back the headers and then part of the body\n\t\t\t// 3. Apiserver closes connection.\n\t\t\t// 4. client-go should catch this and return an error.\n\t\t\tklog.V(2).Infof(\"Stream error %#v when reading response body, may be caused by closed connection.\", err)\n\t\t\tstreamErr := fmt.Errorf(\"stream error when reading response body, may be caused by closed connection. Please retry. Original error: %w\", err)\n\t\t\treturn Result{\n\t\t\t\terr: streamErr,\n\t\t\t}\n\t\tdefault:\n\t\t\tklog.Errorf(\"Unexpected error when reading response body: %v\", err)\n\t\t\tunexpectedErr := fmt.Errorf(\"unexpected error when reading response body. Please retry. Original error: %w\", err)\n\t\t\treturn Result{\n\t\t\t\terr: unexpectedErr,\n\t\t\t}\n\t\t}\n\t}\n\n\tglogBody(\"Response Body\", body)\n\n\t// verify the content type is accurate\n\tvar decoder runtime.Decoder\n\tcontentType := resp.Header.Get(\"Content-Type\")\n\tif len(contentType) == 0 {\n\t\tcontentType = r.c.content.ContentType\n\t}\n\tif len(contentType) \u003e 0 {\n\t\tvar err error\n\t\tmediaType, params, err := mime.ParseMediaType(contentType)\n\t\tif err != nil {\n\t\t\treturn Result{err: errors.NewInternalError(err)}\n\t\t}\n\t\tdecoder, err = r.c.content.Negotiator.Decoder(mediaType, params)\n\t\tif err != nil {\n\t\t\t// if we fail to negotiate a decoder, treat this as an unstructured error\n\t\t\tswitch {\n\t\t\tcase resp.StatusCode == http.StatusSwitchingProtocols:\n\t\t\t\t// no-op, we've been upgraded\n\t\t\tcase resp.StatusCode \u003c http.StatusOK || resp.StatusCode \u003e http.StatusPartialContent:\n\t\t\t\treturn Result{err: r.transformUnstructuredResponseError(resp, req, body)}\n\t\t\t}\n\t\t\treturn Result{\n\t\t\t\tbody: body,\n\t\t\t\tcontentType: contentType,\n\t\t\t\tstatusCode: resp.StatusCode,\n\t\t\t\twarnings: handleWarnings(resp.Header, r.warningHandler),\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch {\n\tcase resp.StatusCode == http.StatusSwitchingProtocols:\n\t\t// no-op, we've been upgraded\n\tcase resp.StatusCode \u003c http.StatusOK || resp.StatusCode \u003e http.StatusPartialContent:\n\t\t// calculate an unstructured error from the response which the Result object may use if the caller\n\t\t// did not return a structured error.\n\t\tretryAfter, _ := retryAfterSeconds(resp)\n\t\terr := r.newUnstructuredResponseError(body, isTextResponse(resp), resp.StatusCode, req.Method, retryAfter)\n\t\treturn Result{\n\t\t\tbody: body,\n\t\t\tcontentType: contentType,\n\t\t\tstatusCode: resp.StatusCode,\n\t\t\tdecoder: decoder,\n\t\t\terr: err,\n\t\t\twarnings: handleWarnings(resp.Header, r.warningHandler),\n\t\t}\n\t}\n\n\treturn Result{\n\t\tbody: body,\n\t\tcontentType: contentType,\n\t\tstatusCode: resp.StatusCode,\n\t\tdecoder: decoder,\n\t\twarnings: handleWarnings(resp.Header, r.warningHandler),\n\t}\n}","line":{"from":1070,"to":1157}} {"id":100028318,"name":"truncateBody","signature":"func truncateBody(body string) string","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// truncateBody decides if the body should be truncated, based on the glog Verbosity.\nfunc truncateBody(body string) string {\n\tmax := 0\n\tswitch {\n\tcase bool(klog.V(10).Enabled()):\n\t\treturn body\n\tcase bool(klog.V(9).Enabled()):\n\t\tmax = 10240\n\tcase bool(klog.V(8).Enabled()):\n\t\tmax = 1024\n\t}\n\n\tif len(body) \u003c= max {\n\t\treturn body\n\t}\n\n\treturn body[:max] + fmt.Sprintf(\" [truncated %d chars]\", len(body)-max)\n}","line":{"from":1159,"to":1176}} {"id":100028319,"name":"glogBody","signature":"func glogBody(prefix string, body []byte)","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// glogBody logs a body output that could be either JSON or protobuf. It explicitly guards against\n// allocating a new string for the body output unless necessary. Uses a simple heuristic to determine\n// whether the body is printable.\nfunc glogBody(prefix string, body []byte) {\n\tif klogV := klog.V(8); klogV.Enabled() {\n\t\tif bytes.IndexFunc(body, func(r rune) bool {\n\t\t\treturn r \u003c 0x0a\n\t\t}) != -1 {\n\t\t\tklogV.Infof(\"%s:\\n%s\", prefix, truncateBody(hex.Dump(body)))\n\t\t} else {\n\t\t\tklogV.Infof(\"%s: %s\", prefix, truncateBody(string(body)))\n\t\t}\n\t}\n}","line":{"from":1178,"to":1191}} {"id":100028320,"name":"transformUnstructuredResponseError","signature":"func (r *Request) transformUnstructuredResponseError(resp *http.Response, req *http.Request, body []byte) error","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// transformUnstructuredResponseError handles an error from the server that is not in a structured form.\n// It is expected to transform any response that is not recognizable as a clear server sent error from the\n// K8S API using the information provided with the request. In practice, HTTP proxies and client libraries\n// introduce a level of uncertainty to the responses returned by servers that in common use result in\n// unexpected responses. The rough structure is:\n//\n// 1. Assume the server sends you something sane - JSON + well defined error objects + proper codes\n// - this is the happy path\n// - when you get this output, trust what the server sends\n// 2. Guard against empty fields / bodies in received JSON and attempt to cull sufficient info from them to\n// generate a reasonable facsimile of the original failure.\n// - Be sure to use a distinct error type or flag that allows a client to distinguish between this and error 1 above\n// 3. Handle true disconnect failures / completely malformed data by moving up to a more generic client error\n// 4. Distinguish between various connection failures like SSL certificates, timeouts, proxy errors, unexpected\n// initial contact, the presence of mismatched body contents from posted content types\n// - Give these a separate distinct error type and capture as much as possible of the original message\n//\n// TODO: introduce transformation of generic http.Client.Do() errors that separates 4.\nfunc (r *Request) transformUnstructuredResponseError(resp *http.Response, req *http.Request, body []byte) error {\n\tif body == nil \u0026\u0026 resp.Body != nil {\n\t\tif data, err := io.ReadAll(\u0026io.LimitedReader{R: resp.Body, N: maxUnstructuredResponseTextBytes}); err == nil {\n\t\t\tbody = data\n\t\t}\n\t}\n\tretryAfter, _ := retryAfterSeconds(resp)\n\treturn r.newUnstructuredResponseError(body, isTextResponse(resp), resp.StatusCode, req.Method, retryAfter)\n}","line":{"from":1196,"to":1222}} {"id":100028321,"name":"newUnstructuredResponseError","signature":"func (r *Request) newUnstructuredResponseError(body []byte, isTextResponse bool, statusCode int, method string, retryAfter int) error","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// newUnstructuredResponseError instantiates the appropriate generic error for the provided input. It also logs the body.\nfunc (r *Request) newUnstructuredResponseError(body []byte, isTextResponse bool, statusCode int, method string, retryAfter int) error {\n\t// cap the amount of output we create\n\tif len(body) \u003e maxUnstructuredResponseTextBytes {\n\t\tbody = body[:maxUnstructuredResponseTextBytes]\n\t}\n\n\tmessage := \"unknown\"\n\tif isTextResponse {\n\t\tmessage = strings.TrimSpace(string(body))\n\t}\n\tvar groupResource schema.GroupResource\n\tif len(r.resource) \u003e 0 {\n\t\tgroupResource.Group = r.c.content.GroupVersion.Group\n\t\tgroupResource.Resource = r.resource\n\t}\n\treturn errors.NewGenericServerResponse(\n\t\tstatusCode,\n\t\tmethod,\n\t\tgroupResource,\n\t\tr.resourceName,\n\t\tmessage,\n\t\tretryAfter,\n\t\ttrue,\n\t)\n}","line":{"from":1224,"to":1249}} {"id":100028322,"name":"isTextResponse","signature":"func isTextResponse(resp *http.Response) bool","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// isTextResponse returns true if the response appears to be a textual media type.\nfunc isTextResponse(resp *http.Response) bool {\n\tcontentType := resp.Header.Get(\"Content-Type\")\n\tif len(contentType) == 0 {\n\t\treturn true\n\t}\n\tmedia, _, err := mime.ParseMediaType(contentType)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn strings.HasPrefix(media, \"text/\")\n}","line":{"from":1251,"to":1262}} {"id":100028323,"name":"retryAfterSeconds","signature":"func retryAfterSeconds(resp *http.Response) (int, bool)","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// retryAfterSeconds returns the value of the Retry-After header and true, or 0 and false if\n// the header was missing or not a valid number.\nfunc retryAfterSeconds(resp *http.Response) (int, bool) {\n\tif h := resp.Header.Get(\"Retry-After\"); len(h) \u003e 0 {\n\t\tif i, err := strconv.Atoi(h); err == nil {\n\t\t\treturn i, true\n\t\t}\n\t}\n\treturn 0, false\n}","line":{"from":1264,"to":1273}} {"id":100028324,"name":"Raw","signature":"func (r Result) Raw() ([]byte, error)","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// Raw returns the raw result.\nfunc (r Result) Raw() ([]byte, error) {\n\treturn r.body, r.err\n}","line":{"from":1286,"to":1289}} {"id":100028325,"name":"Get","signature":"func (r Result) Get() (runtime.Object, error)","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// Get returns the result as an object, which means it passes through the decoder.\n// If the returned object is of type Status and has .Status != StatusSuccess, the\n// additional information in Status will be used to enrich the error.\nfunc (r Result) Get() (runtime.Object, error) {\n\tif r.err != nil {\n\t\t// Check whether the result has a Status object in the body and prefer that.\n\t\treturn nil, r.Error()\n\t}\n\tif r.decoder == nil {\n\t\treturn nil, fmt.Errorf(\"serializer for %s doesn't exist\", r.contentType)\n\t}\n\n\t// decode, but if the result is Status return that as an error instead.\n\tout, _, err := r.decoder.Decode(r.body, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tswitch t := out.(type) {\n\tcase *metav1.Status:\n\t\t// any status besides StatusSuccess is considered an error.\n\t\tif t.Status != metav1.StatusSuccess {\n\t\t\treturn nil, errors.FromObject(t)\n\t\t}\n\t}\n\treturn out, nil\n}","line":{"from":1291,"to":1316}} {"id":100028326,"name":"StatusCode","signature":"func (r Result) StatusCode(statusCode *int) Result","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// StatusCode returns the HTTP status code of the request. (Only valid if no\n// error was returned.)\nfunc (r Result) StatusCode(statusCode *int) Result {\n\t*statusCode = r.statusCode\n\treturn r\n}","line":{"from":1318,"to":1323}} {"id":100028327,"name":"ContentType","signature":"func (r Result) ContentType(contentType *string) Result","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// ContentType returns the \"Content-Type\" response header into the passed\n// string, returning the Result for possible chaining. (Only valid if no\n// error code was returned.)\nfunc (r Result) ContentType(contentType *string) Result {\n\t*contentType = r.contentType\n\treturn r\n}","line":{"from":1325,"to":1331}} {"id":100028328,"name":"Into","signature":"func (r Result) Into(obj runtime.Object) error","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// Into stores the result into obj, if possible. If obj is nil it is ignored.\n// If the returned object is of type Status and has .Status != StatusSuccess, the\n// additional information in Status will be used to enrich the error.\nfunc (r Result) Into(obj runtime.Object) error {\n\tif r.err != nil {\n\t\t// Check whether the result has a Status object in the body and prefer that.\n\t\treturn r.Error()\n\t}\n\tif r.decoder == nil {\n\t\treturn fmt.Errorf(\"serializer for %s doesn't exist\", r.contentType)\n\t}\n\tif len(r.body) == 0 {\n\t\treturn fmt.Errorf(\"0-length response with status code: %d and content type: %s\",\n\t\t\tr.statusCode, r.contentType)\n\t}\n\n\tout, _, err := r.decoder.Decode(r.body, nil, obj)\n\tif err != nil || out == obj {\n\t\treturn err\n\t}\n\t// if a different object is returned, see if it is Status and avoid double decoding\n\t// the object.\n\tswitch t := out.(type) {\n\tcase *metav1.Status:\n\t\t// any status besides StatusSuccess is considered an error.\n\t\tif t.Status != metav1.StatusSuccess {\n\t\t\treturn errors.FromObject(t)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":1333,"to":1363}} {"id":100028329,"name":"WasCreated","signature":"func (r Result) WasCreated(wasCreated *bool) Result","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// WasCreated updates the provided bool pointer to whether the server returned\n// 201 created or a different response.\nfunc (r Result) WasCreated(wasCreated *bool) Result {\n\t*wasCreated = r.statusCode == http.StatusCreated\n\treturn r\n}","line":{"from":1365,"to":1370}} {"id":100028330,"name":"Error","signature":"func (r Result) Error() error","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// Error returns the error executing the request, nil if no error occurred.\n// If the returned object is of type Status and has Status != StatusSuccess, the\n// additional information in Status will be used to enrich the error.\n// See the Request.Do() comment for what errors you might get.\nfunc (r Result) Error() error {\n\t// if we have received an unexpected server error, and we have a body and decoder, we can try to extract\n\t// a Status object.\n\tif r.err == nil || !errors.IsUnexpectedServerError(r.err) || len(r.body) == 0 || r.decoder == nil {\n\t\treturn r.err\n\t}\n\n\t// attempt to convert the body into a Status object\n\t// to be backwards compatible with old servers that do not return a version, default to \"v1\"\n\tout, _, err := r.decoder.Decode(r.body, \u0026schema.GroupVersionKind{Version: \"v1\"}, nil)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"body was not decodable (unable to check for Status): %v\", err)\n\t\treturn r.err\n\t}\n\tswitch t := out.(type) {\n\tcase *metav1.Status:\n\t\t// because we default the kind, we *must* check for StatusFailure\n\t\tif t.Status == metav1.StatusFailure {\n\t\t\treturn errors.FromObject(t)\n\t\t}\n\t}\n\treturn r.err\n}","line":{"from":1372,"to":1398}} {"id":100028331,"name":"Warnings","signature":"func (r Result) Warnings() []net.WarningHeader","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// Warnings returns any warning headers received in the response\nfunc (r Result) Warnings() []net.WarningHeader {\n\treturn r.warnings\n}","line":{"from":1400,"to":1403}} {"id":100028332,"name":"IsValidPathSegmentName","signature":"func IsValidPathSegmentName(name string) []string","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// IsValidPathSegmentName validates the name can be safely encoded as a path segment\nfunc IsValidPathSegmentName(name string) []string {\n\tfor _, illegalName := range NameMayNotBe {\n\t\tif name == illegalName {\n\t\t\treturn []string{fmt.Sprintf(`may not be '%s'`, illegalName)}\n\t\t}\n\t}\n\n\tvar errors []string\n\tfor _, illegalContent := range NameMayNotContain {\n\t\tif strings.Contains(name, illegalContent) {\n\t\t\terrors = append(errors, fmt.Sprintf(`may not contain '%s'`, illegalContent))\n\t\t}\n\t}\n\n\treturn errors\n}","line":{"from":1411,"to":1427}} {"id":100028333,"name":"IsValidPathSegmentPrefix","signature":"func IsValidPathSegmentPrefix(name string) []string","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// IsValidPathSegmentPrefix validates the name can be used as a prefix for a name which will be encoded as a path segment\n// It does not check for exact matches with disallowed names, since an arbitrary suffix might make the name valid\nfunc IsValidPathSegmentPrefix(name string) []string {\n\tvar errors []string\n\tfor _, illegalContent := range NameMayNotContain {\n\t\tif strings.Contains(name, illegalContent) {\n\t\t\terrors = append(errors, fmt.Sprintf(`may not contain '%s'`, illegalContent))\n\t\t}\n\t}\n\n\treturn errors\n}","line":{"from":1429,"to":1440}} {"id":100028334,"name":"ValidatePathSegmentName","signature":"func ValidatePathSegmentName(name string, prefix bool) []string","file":"staging/src/k8s.io/client-go/rest/request.go","code":"// ValidatePathSegmentName validates the name can be safely encoded as a path segment\nfunc ValidatePathSegmentName(name string, prefix bool) []string {\n\tif prefix {\n\t\treturn IsValidPathSegmentPrefix(name)\n\t}\n\treturn IsValidPathSegmentName(name)\n}","line":{"from":1442,"to":1448}} {"id":100028335,"name":"HTTPClientFor","signature":"func HTTPClientFor(config *Config) (*http.Client, error)","file":"staging/src/k8s.io/client-go/rest/transport.go","code":"// HTTPClientFor returns an http.Client that will provide the authentication\n// or transport level security defined by the provided Config. Will return the\n// default http.DefaultClient if no special case behavior is needed.\nfunc HTTPClientFor(config *Config) (*http.Client, error) {\n\ttransport, err := TransportFor(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar httpClient *http.Client\n\tif transport != http.DefaultTransport || config.Timeout \u003e 0 {\n\t\thttpClient = \u0026http.Client{\n\t\t\tTransport: transport,\n\t\t\tTimeout: config.Timeout,\n\t\t}\n\t} else {\n\t\thttpClient = http.DefaultClient\n\t}\n\n\treturn httpClient, nil\n}","line":{"from":29,"to":48}} {"id":100028336,"name":"TLSConfigFor","signature":"func TLSConfigFor(config *Config) (*tls.Config, error)","file":"staging/src/k8s.io/client-go/rest/transport.go","code":"// TLSConfigFor returns a tls.Config that will provide the transport level security defined\n// by the provided Config. Will return nil if no transport level security is requested.\nfunc TLSConfigFor(config *Config) (*tls.Config, error) {\n\tcfg, err := config.TransportConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn transport.TLSConfigFor(cfg)\n}","line":{"from":50,"to":58}} {"id":100028337,"name":"TransportFor","signature":"func TransportFor(config *Config) (http.RoundTripper, error)","file":"staging/src/k8s.io/client-go/rest/transport.go","code":"// TransportFor returns an http.RoundTripper that will provide the authentication\n// or transport level security defined by the provided Config. Will return the\n// default http.DefaultTransport if no special case behavior is needed.\nfunc TransportFor(config *Config) (http.RoundTripper, error) {\n\tcfg, err := config.TransportConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn transport.New(cfg)\n}","line":{"from":60,"to":69}} {"id":100028338,"name":"HTTPWrappersForConfig","signature":"func HTTPWrappersForConfig(config *Config, rt http.RoundTripper) (http.RoundTripper, error)","file":"staging/src/k8s.io/client-go/rest/transport.go","code":"// HTTPWrappersForConfig wraps a round tripper with any relevant layered behavior from the\n// config. Exposed to allow more clients that need HTTP-like behavior but then must hijack\n// the underlying connection (like WebSocket or HTTP2 clients). Pure HTTP clients should use\n// the higher level TransportFor or RESTClientFor methods.\nfunc HTTPWrappersForConfig(config *Config, rt http.RoundTripper) (http.RoundTripper, error) {\n\tcfg, err := config.TransportConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn transport.HTTPWrappersForConfig(cfg, rt)\n}","line":{"from":71,"to":81}} {"id":100028339,"name":"TransportConfig","signature":"func (c *Config) TransportConfig() (*transport.Config, error)","file":"staging/src/k8s.io/client-go/rest/transport.go","code":"// TransportConfig converts a client config to an appropriate transport config.\nfunc (c *Config) TransportConfig() (*transport.Config, error) {\n\tconf := \u0026transport.Config{\n\t\tUserAgent: c.UserAgent,\n\t\tTransport: c.Transport,\n\t\tWrapTransport: c.WrapTransport,\n\t\tDisableCompression: c.DisableCompression,\n\t\tTLS: transport.TLSConfig{\n\t\t\tInsecure: c.Insecure,\n\t\t\tServerName: c.ServerName,\n\t\t\tCAFile: c.CAFile,\n\t\t\tCAData: c.CAData,\n\t\t\tCertFile: c.CertFile,\n\t\t\tCertData: c.CertData,\n\t\t\tKeyFile: c.KeyFile,\n\t\t\tKeyData: c.KeyData,\n\t\t\tNextProtos: c.NextProtos,\n\t\t},\n\t\tUsername: c.Username,\n\t\tPassword: c.Password,\n\t\tBearerToken: c.BearerToken,\n\t\tBearerTokenFile: c.BearerTokenFile,\n\t\tImpersonate: transport.ImpersonationConfig{\n\t\t\tUserName: c.Impersonate.UserName,\n\t\t\tUID: c.Impersonate.UID,\n\t\t\tGroups: c.Impersonate.Groups,\n\t\t\tExtra: c.Impersonate.Extra,\n\t\t},\n\t\tProxy: c.Proxy,\n\t}\n\n\tif c.Dial != nil {\n\t\tconf.DialHolder = \u0026transport.DialHolder{Dial: c.Dial}\n\t}\n\n\tif c.ExecProvider != nil \u0026\u0026 c.AuthProvider != nil {\n\t\treturn nil, errors.New(\"execProvider and authProvider cannot be used in combination\")\n\t}\n\n\tif c.ExecProvider != nil {\n\t\tvar cluster *clientauthentication.Cluster\n\t\tif c.ExecProvider.ProvideClusterInfo {\n\t\t\tvar err error\n\t\t\tcluster, err = ConfigToExecCluster(c)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\tprovider, err := exec.GetAuthenticator(c.ExecProvider, cluster)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := provider.UpdateTransportConfig(conf); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif c.AuthProvider != nil {\n\t\tprovider, err := GetAuthProvider(c.Host, c.AuthProvider, c.AuthConfigPersister)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tconf.Wrap(provider.WrapTransport)\n\t}\n\treturn conf, nil\n}","line":{"from":83,"to":147}} {"id":100028340,"name":"Wrap","signature":"func (c *Config) Wrap(fn transport.WrapperFunc)","file":"staging/src/k8s.io/client-go/rest/transport.go","code":"// Wrap adds a transport middleware function that will give the caller\n// an opportunity to wrap the underlying http.RoundTripper prior to the\n// first API call being made. The provided function is invoked after any\n// existing transport wrappers are invoked.\nfunc (c *Config) Wrap(fn transport.WrapperFunc) {\n\tc.WrapTransport = transport.Wrappers(c.WrapTransport, fn)\n}","line":{"from":149,"to":155}} {"id":100028341,"name":"DefaultServerURL","signature":"func DefaultServerURL(host, apiPath string, groupVersion schema.GroupVersion, defaultTLS bool) (*url.URL, string, error)","file":"staging/src/k8s.io/client-go/rest/url_utils.go","code":"// DefaultServerURL converts a host, host:port, or URL string to the default base server API path\n// to use with a Client at a given API version following the standard conventions for a\n// Kubernetes API.\nfunc DefaultServerURL(host, apiPath string, groupVersion schema.GroupVersion, defaultTLS bool) (*url.URL, string, error) {\n\tif host == \"\" {\n\t\treturn nil, \"\", fmt.Errorf(\"host must be a URL or a host:port pair\")\n\t}\n\tbase := host\n\thostURL, err := url.Parse(base)\n\tif err != nil || hostURL.Scheme == \"\" || hostURL.Host == \"\" {\n\t\tscheme := \"http://\"\n\t\tif defaultTLS {\n\t\t\tscheme = \"https://\"\n\t\t}\n\t\thostURL, err = url.Parse(scheme + base)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tif hostURL.Path != \"\" \u0026\u0026 hostURL.Path != \"/\" {\n\t\t\treturn nil, \"\", fmt.Errorf(\"host must be a URL or a host:port pair: %q\", base)\n\t\t}\n\t}\n\n\t// hostURL.Path is optional; a non-empty Path is treated as a prefix that is to be applied to\n\t// all URIs used to access the host. this is useful when there's a proxy in front of the\n\t// apiserver that has relocated the apiserver endpoints, forwarding all requests from, for\n\t// example, /a/b/c to the apiserver. in this case the Path should be /a/b/c.\n\t//\n\t// if running without a frontend proxy (that changes the location of the apiserver), then\n\t// hostURL.Path should be blank.\n\t//\n\t// versionedAPIPath, a path relative to baseURL.Path, points to a versioned API base\n\tversionedAPIPath := DefaultVersionedAPIPath(apiPath, groupVersion)\n\n\treturn hostURL, versionedAPIPath, nil\n}","line":{"from":27,"to":62}} {"id":100028342,"name":"DefaultVersionedAPIPath","signature":"func DefaultVersionedAPIPath(apiPath string, groupVersion schema.GroupVersion) string","file":"staging/src/k8s.io/client-go/rest/url_utils.go","code":"// DefaultVersionedAPIPathFor constructs the default path for the given group version, assuming the given\n// API path, following the standard conventions of the Kubernetes API.\nfunc DefaultVersionedAPIPath(apiPath string, groupVersion schema.GroupVersion) string {\n\tversionedAPIPath := path.Join(\"/\", apiPath)\n\n\t// Add the version to the end of the path\n\tif len(groupVersion.Group) \u003e 0 {\n\t\tversionedAPIPath = path.Join(versionedAPIPath, groupVersion.Group, groupVersion.Version)\n\n\t} else {\n\t\tversionedAPIPath = path.Join(versionedAPIPath, groupVersion.Version)\n\t}\n\n\treturn versionedAPIPath\n}","line":{"from":64,"to":78}} {"id":100028343,"name":"defaultServerUrlFor","signature":"func defaultServerUrlFor(config *Config) (*url.URL, string, error)","file":"staging/src/k8s.io/client-go/rest/url_utils.go","code":"// defaultServerUrlFor is shared between IsConfigTransportTLS and RESTClientFor. It\n// requires Host and Version to be set prior to being called.\nfunc defaultServerUrlFor(config *Config) (*url.URL, string, error) {\n\t// TODO: move the default to secure when the apiserver supports TLS by default\n\t// config.Insecure is taken to mean \"I want HTTPS but don't bother checking the certs against a CA.\"\n\thasCA := len(config.CAFile) != 0 || len(config.CAData) != 0\n\thasCert := len(config.CertFile) != 0 || len(config.CertData) != 0\n\tdefaultTLS := hasCA || hasCert || config.Insecure\n\thost := config.Host\n\tif host == \"\" {\n\t\thost = \"localhost\"\n\t}\n\n\tif config.GroupVersion != nil {\n\t\treturn DefaultServerURL(host, config.APIPath, *config.GroupVersion, defaultTLS)\n\t}\n\treturn DefaultServerURL(host, config.APIPath, schema.GroupVersion{}, defaultTLS)\n}","line":{"from":80,"to":97}} {"id":100028344,"name":"UpdateBackoff","signature":"func (n *NoBackoff) UpdateBackoff(actualUrl *url.URL, err error, responseCode int)","file":"staging/src/k8s.io/client-go/rest/urlbackoff.go","code":"func (n *NoBackoff) UpdateBackoff(actualUrl *url.URL, err error, responseCode int) {\n\t// do nothing.\n}","line":{"from":52,"to":54}} {"id":100028345,"name":"CalculateBackoff","signature":"func (n *NoBackoff) CalculateBackoff(actualUrl *url.URL) time.Duration","file":"staging/src/k8s.io/client-go/rest/urlbackoff.go","code":"func (n *NoBackoff) CalculateBackoff(actualUrl *url.URL) time.Duration {\n\treturn 0 * time.Second\n}","line":{"from":56,"to":58}} {"id":100028346,"name":"Sleep","signature":"func (n *NoBackoff) Sleep(d time.Duration)","file":"staging/src/k8s.io/client-go/rest/urlbackoff.go","code":"func (n *NoBackoff) Sleep(d time.Duration) {\n\ttime.Sleep(d)\n}","line":{"from":60,"to":62}} {"id":100028347,"name":"Disable","signature":"func (b *URLBackoff) Disable()","file":"staging/src/k8s.io/client-go/rest/urlbackoff.go","code":"// Disable makes the backoff trivial, i.e., sets it to zero. This might be used\n// by tests which want to run 1000s of mock requests without slowing down.\nfunc (b *URLBackoff) Disable() {\n\tklog.V(4).Infof(\"Disabling backoff strategy\")\n\tb.Backoff = flowcontrol.NewBackOff(0*time.Second, 0*time.Second)\n}","line":{"from":64,"to":69}} {"id":100028348,"name":"baseUrlKey","signature":"func (b *URLBackoff) baseUrlKey(rawurl *url.URL) string","file":"staging/src/k8s.io/client-go/rest/urlbackoff.go","code":"// baseUrlKey returns the key which urls will be mapped to.\n// For example, 127.0.0.1:8080/api/v2/abcde -\u003e 127.0.0.1:8080.\nfunc (b *URLBackoff) baseUrlKey(rawurl *url.URL) string {\n\t// Simple implementation for now, just the host.\n\t// We may backoff specific paths (i.e. \"pods\") differentially\n\t// in the future.\n\thost, err := url.Parse(rawurl.String())\n\tif err != nil {\n\t\tklog.V(4).Infof(\"Error extracting url: %v\", rawurl)\n\t\tpanic(\"bad url!\")\n\t}\n\treturn host.Host\n}","line":{"from":71,"to":83}} {"id":100028349,"name":"UpdateBackoff","signature":"func (b *URLBackoff) UpdateBackoff(actualUrl *url.URL, err error, responseCode int)","file":"staging/src/k8s.io/client-go/rest/urlbackoff.go","code":"// UpdateBackoff updates backoff metadata\nfunc (b *URLBackoff) UpdateBackoff(actualUrl *url.URL, err error, responseCode int) {\n\t// range for retry counts that we store is [0,13]\n\tif responseCode \u003e maxResponseCode || serverIsOverloadedSet.Has(responseCode) {\n\t\tb.Backoff.Next(b.baseUrlKey(actualUrl), b.Backoff.Clock.Now())\n\t\treturn\n\t} else if responseCode \u003e= 300 || err != nil {\n\t\tklog.V(4).Infof(\"Client is returning errors: code %v, error %v\", responseCode, err)\n\t}\n\n\t//If we got this far, there is no backoff required for this URL anymore.\n\tb.Backoff.Reset(b.baseUrlKey(actualUrl))\n}","line":{"from":85,"to":97}} {"id":100028350,"name":"CalculateBackoff","signature":"func (b *URLBackoff) CalculateBackoff(actualUrl *url.URL) time.Duration","file":"staging/src/k8s.io/client-go/rest/urlbackoff.go","code":"// CalculateBackoff takes a url and back's off exponentially,\n// based on its knowledge of existing failures.\nfunc (b *URLBackoff) CalculateBackoff(actualUrl *url.URL) time.Duration {\n\treturn b.Backoff.Get(b.baseUrlKey(actualUrl))\n}","line":{"from":99,"to":103}} {"id":100028351,"name":"Sleep","signature":"func (b *URLBackoff) Sleep(d time.Duration)","file":"staging/src/k8s.io/client-go/rest/urlbackoff.go","code":"func (b *URLBackoff) Sleep(d time.Duration) {\n\tb.Backoff.Clock.Sleep(d)\n}","line":{"from":105,"to":107}} {"id":100028352,"name":"SetDefaultWarningHandler","signature":"func SetDefaultWarningHandler(l WarningHandler)","file":"staging/src/k8s.io/client-go/rest/warnings.go","code":"// SetDefaultWarningHandler sets the default handler clients use when warning headers are encountered.\n// By default, warnings are logged. Several built-in implementations are provided:\n// - NoWarnings suppresses warnings.\n// - WarningLogger logs warnings.\n// - NewWarningWriter() outputs warnings to the provided writer.\nfunc SetDefaultWarningHandler(l WarningHandler) {\n\tdefaultWarningHandlerLock.Lock()\n\tdefer defaultWarningHandlerLock.Unlock()\n\tdefaultWarningHandler = l\n}","line":{"from":41,"to":50}} {"id":100028353,"name":"getDefaultWarningHandler","signature":"func getDefaultWarningHandler() WarningHandler","file":"staging/src/k8s.io/client-go/rest/warnings.go","code":"func getDefaultWarningHandler() WarningHandler {\n\tdefaultWarningHandlerLock.RLock()\n\tdefer defaultWarningHandlerLock.RUnlock()\n\tl := defaultWarningHandler\n\treturn l\n}","line":{"from":51,"to":56}} {"id":100028354,"name":"HandleWarningHeader","signature":"func (NoWarnings) HandleWarningHeader(code int, agent string, message string) {}","file":"staging/src/k8s.io/client-go/rest/warnings.go","code":"func (NoWarnings) HandleWarningHeader(code int, agent string, message string) {}","line":{"from":61,"to":61}} {"id":100028355,"name":"HandleWarningHeader","signature":"func (WarningLogger) HandleWarningHeader(code int, agent string, message string)","file":"staging/src/k8s.io/client-go/rest/warnings.go","code":"func (WarningLogger) HandleWarningHeader(code int, agent string, message string) {\n\tif code != 299 || len(message) == 0 {\n\t\treturn\n\t}\n\tklog.Warning(message)\n}","line":{"from":66,"to":71}} {"id":100028356,"name":"NewWarningWriter","signature":"func NewWarningWriter(out io.Writer, opts WarningWriterOptions) *warningWriter","file":"staging/src/k8s.io/client-go/rest/warnings.go","code":"// NewWarningWriter returns an implementation of WarningHandler that outputs code 299 warnings to the specified writer.\nfunc NewWarningWriter(out io.Writer, opts WarningWriterOptions) *warningWriter {\n\th := \u0026warningWriter{out: out, opts: opts}\n\tif opts.Deduplicate {\n\t\th.written = map[string]struct{}{}\n\t}\n\treturn h\n}","line":{"from":93,"to":100}} {"id":100028357,"name":"HandleWarningHeader","signature":"func (w *warningWriter) HandleWarningHeader(code int, agent string, message string)","file":"staging/src/k8s.io/client-go/rest/warnings.go","code":"// HandleWarningHeader prints warnings with code=299 to the configured writer.\nfunc (w *warningWriter) HandleWarningHeader(code int, agent string, message string) {\n\tif code != 299 || len(message) == 0 {\n\t\treturn\n\t}\n\n\tw.writtenLock.Lock()\n\tdefer w.writtenLock.Unlock()\n\n\tif w.opts.Deduplicate {\n\t\tif _, alreadyWritten := w.written[message]; alreadyWritten {\n\t\t\treturn\n\t\t}\n\t\tw.written[message] = struct{}{}\n\t}\n\tw.writtenCount++\n\n\tif w.opts.Color {\n\t\tfmt.Fprintf(w.out, \"%sWarning:%s %s\\n\", yellowColor, resetColor, message)\n\t} else {\n\t\tfmt.Fprintf(w.out, \"Warning: %s\\n\", message)\n\t}\n}","line":{"from":107,"to":129}} {"id":100028358,"name":"WarningCount","signature":"func (w *warningWriter) WarningCount() int","file":"staging/src/k8s.io/client-go/rest/warnings.go","code":"func (w *warningWriter) WarningCount() int {\n\tw.writtenLock.Lock()\n\tdefer w.writtenLock.Unlock()\n\treturn w.writtenCount\n}","line":{"from":131,"to":135}} {"id":100028359,"name":"handleWarnings","signature":"func handleWarnings(headers http.Header, handler WarningHandler) []net.WarningHeader","file":"staging/src/k8s.io/client-go/rest/warnings.go","code":"func handleWarnings(headers http.Header, handler WarningHandler) []net.WarningHeader {\n\tif handler == nil {\n\t\thandler = getDefaultWarningHandler()\n\t}\n\n\twarnings, _ := net.ParseWarningHeaders(headers[\"Warning\"])\n\tfor _, warning := range warnings {\n\t\thandler.HandleWarningHeader(warning.Code, warning.Agent, warning.Text)\n\t}\n\treturn warnings\n}","line":{"from":137,"to":147}} {"id":100028360,"name":"NewDecoder","signature":"func NewDecoder(decoder streaming.Decoder, embeddedDecoder runtime.Decoder) *Decoder","file":"staging/src/k8s.io/client-go/rest/watch/decoder.go","code":"// NewDecoder creates an Decoder for the given writer and codec.\nfunc NewDecoder(decoder streaming.Decoder, embeddedDecoder runtime.Decoder) *Decoder {\n\treturn \u0026Decoder{\n\t\tdecoder: decoder,\n\t\tembeddedDecoder: embeddedDecoder,\n\t}\n}","line":{"from":37,"to":43}} {"id":100028361,"name":"Decode","signature":"func (d *Decoder) Decode() (watch.EventType, runtime.Object, error)","file":"staging/src/k8s.io/client-go/rest/watch/decoder.go","code":"// Decode blocks until it can return the next object in the reader. Returns an error\n// if the reader is closed or an object can't be decoded.\nfunc (d *Decoder) Decode() (watch.EventType, runtime.Object, error) {\n\tvar got metav1.WatchEvent\n\tres, _, err := d.decoder.Decode(nil, \u0026got)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\tif res != \u0026got {\n\t\treturn \"\", nil, fmt.Errorf(\"unable to decode to metav1.Event\")\n\t}\n\tswitch got.Type {\n\tcase string(watch.Added), string(watch.Modified), string(watch.Deleted), string(watch.Error), string(watch.Bookmark):\n\tdefault:\n\t\treturn \"\", nil, fmt.Errorf(\"got invalid watch event type: %v\", got.Type)\n\t}\n\n\tobj, err := runtime.Decode(d.embeddedDecoder, got.Object.Raw)\n\tif err != nil {\n\t\treturn \"\", nil, fmt.Errorf(\"unable to decode watch event: %v\", err)\n\t}\n\treturn watch.EventType(got.Type), obj, nil\n}","line":{"from":45,"to":67}} {"id":100028362,"name":"Close","signature":"func (d *Decoder) Close()","file":"staging/src/k8s.io/client-go/rest/watch/decoder.go","code":"// Close closes the underlying r.\nfunc (d *Decoder) Close() {\n\td.decoder.Close()\n}","line":{"from":69,"to":72}} {"id":100028363,"name":"NewEncoder","signature":"func NewEncoder(encoder streaming.Encoder, embeddedEncoder runtime.Encoder) *Encoder","file":"staging/src/k8s.io/client-go/rest/watch/encoder.go","code":"func NewEncoder(encoder streaming.Encoder, embeddedEncoder runtime.Encoder) *Encoder {\n\treturn \u0026Encoder{\n\t\tencoder: encoder,\n\t\tembeddedEncoder: embeddedEncoder,\n\t}\n}","line":{"from":37,"to":42}} {"id":100028364,"name":"Encode","signature":"func (e *Encoder) Encode(event *watch.Event) error","file":"staging/src/k8s.io/client-go/rest/watch/encoder.go","code":"// Encode writes an event to the writer. Returns an error\n// if the writer is closed or an object can't be encoded.\nfunc (e *Encoder) Encode(event *watch.Event) error {\n\tdata, err := runtime.Encode(e.embeddedEncoder, event.Object)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// FIXME: get rid of json.RawMessage.\n\treturn e.encoder.Encode(\u0026metav1.WatchEvent{\n\t\tType: string(event.Type),\n\t\tObject: runtime.RawExtension{Raw: json.RawMessage(data)},\n\t})\n}","line":{"from":44,"to":56}} {"id":100028365,"name":"IsErrorRetryable","signature":"func (r IsRetryableErrorFunc) IsErrorRetryable(request *http.Request, err error) bool","file":"staging/src/k8s.io/client-go/rest/with_retry.go","code":"func (r IsRetryableErrorFunc) IsErrorRetryable(request *http.Request, err error) bool {\n\treturn r(request, err)\n}","line":{"from":42,"to":44}} {"id":100028366,"name":"trackPreviousError","signature":"func (r *withRetry) trackPreviousError(err error)","file":"staging/src/k8s.io/client-go/rest/with_retry.go","code":"func (r *withRetry) trackPreviousError(err error) {\n\t// keep track of two most recent errors\n\tif r.currentErr != nil {\n\t\tr.previousErr = r.currentErr\n\t}\n\tr.currentErr = err\n}","line":{"from":140,"to":146}} {"id":100028367,"name":"IsNextRetry","signature":"func (r *withRetry) IsNextRetry(ctx context.Context, restReq *Request, httpReq *http.Request, resp *http.Response, err error, f IsRetryableErrorFunc) bool","file":"staging/src/k8s.io/client-go/rest/with_retry.go","code":"func (r *withRetry) IsNextRetry(ctx context.Context, restReq *Request, httpReq *http.Request, resp *http.Response, err error, f IsRetryableErrorFunc) bool {\n\tdefer r.trackPreviousError(err)\n\n\tif httpReq == nil || (resp == nil \u0026\u0026 err == nil) {\n\t\t// bad input, we do nothing.\n\t\treturn false\n\t}\n\n\tif restReq.body != nil {\n\t\t// we have an opaque reader, we can't safely reset it\n\t\treturn false\n\t}\n\n\tr.attempts++\n\tr.retryAfter = \u0026RetryAfter{Attempt: r.attempts}\n\tif r.attempts \u003e r.maxRetries {\n\t\treturn false\n\t}\n\n\t// if the server returned an error, it takes precedence over the http response.\n\tvar errIsRetryable bool\n\tif f != nil \u0026\u0026 err != nil \u0026\u0026 f.IsErrorRetryable(httpReq, err) {\n\t\terrIsRetryable = true\n\t\t// we have a retryable error, for which we will create an\n\t\t// artificial \"Retry-After\" response.\n\t\tresp = retryAfterResponse()\n\t}\n\tif err != nil \u0026\u0026 !errIsRetryable {\n\t\treturn false\n\t}\n\n\t// if we are here, we have either a or b:\n\t// a: we have a retryable error, for which we already\n\t// have an artificial \"Retry-After\" response.\n\t// b: we have a response from the server for which we\n\t// need to check if it is retryable\n\tseconds, wait := checkWait(resp)\n\tif !wait {\n\t\treturn false\n\t}\n\n\tr.retryAfter.Wait = time.Duration(seconds) * time.Second\n\tr.retryAfter.Reason = getRetryReason(r.attempts, seconds, resp, err)\n\n\treturn true\n}","line":{"from":148,"to":193}} {"id":100028368,"name":"Before","signature":"func (r *withRetry) Before(ctx context.Context, request *Request) error","file":"staging/src/k8s.io/client-go/rest/with_retry.go","code":"func (r *withRetry) Before(ctx context.Context, request *Request) error {\n\t// If the request context is already canceled there\n\t// is no need to retry.\n\tif ctx.Err() != nil {\n\t\tr.trackPreviousError(ctx.Err())\n\t\treturn ctx.Err()\n\t}\n\n\turl := request.URL()\n\t// r.retryAfter represents the retry after parameters calculated\n\t// from the (response, err) tuple from the last attempt, so 'Before'\n\t// can apply these retry after parameters prior to the next attempt.\n\t// 'r.retryAfter == nil' indicates that this is the very first attempt.\n\tif r.retryAfter == nil {\n\t\t// we do a backoff sleep before the first attempt is made,\n\t\t// (preserving current behavior).\n\t\tif request.backoff != nil {\n\t\t\trequest.backoff.Sleep(request.backoff.CalculateBackoff(url))\n\t\t}\n\t\treturn nil\n\t}\n\n\t// if we are here, we have made attempt(s) at least once before.\n\tif request.backoff != nil {\n\t\tdelay := request.backoff.CalculateBackoff(url)\n\t\tif r.retryAfter.Wait \u003e delay {\n\t\t\tdelay = r.retryAfter.Wait\n\t\t}\n\t\trequest.backoff.Sleep(delay)\n\t}\n\n\t// We are retrying the request that we already send to\n\t// apiserver at least once before. This request should\n\t// also be throttled with the client-internal rate limiter.\n\tif err := request.tryThrottleWithInfo(ctx, r.retryAfter.Reason); err != nil {\n\t\tr.trackPreviousError(ctx.Err())\n\t\treturn err\n\t}\n\n\tklog.V(4).Infof(\"Got a Retry-After %s response for attempt %d to %v\", r.retryAfter.Wait, r.retryAfter.Attempt, request.URL().String())\n\treturn nil\n}","line":{"from":195,"to":236}} {"id":100028369,"name":"After","signature":"func (r *withRetry) After(ctx context.Context, request *Request, resp *http.Response, err error)","file":"staging/src/k8s.io/client-go/rest/with_retry.go","code":"func (r *withRetry) After(ctx context.Context, request *Request, resp *http.Response, err error) {\n\t// 'After' is invoked immediately after an attempt is made, let's label\n\t// the attempt we have just made as attempt 'N'.\n\t// the current value of r.retryAfter represents the retry after\n\t// parameters calculated from the (response, err) tuple from\n\t// attempt N-1, so r.retryAfter is outdated and should not be\n\t// referred to here.\n\tisRetry := r.retryAfter != nil\n\tr.retryAfter = nil\n\n\t// the client finishes a single request after N attempts (1..N)\n\t// - all attempts (1..N) are counted to the rest_client_requests_total\n\t// metric (current behavior).\n\t// - every attempt after the first (2..N) are counted to the\n\t// rest_client_request_retries_total metric.\n\tupdateRequestResultMetric(ctx, request, resp, err)\n\tif isRetry {\n\t\t// this is attempt 2 or later\n\t\tupdateRequestRetryMetric(ctx, request, resp, err)\n\t}\n\n\tif request.c.base != nil {\n\t\tif err != nil {\n\t\t\trequest.backoff.UpdateBackoff(request.URL(), err, 0)\n\t\t} else {\n\t\t\trequest.backoff.UpdateBackoff(request.URL(), err, resp.StatusCode)\n\t\t}\n\t}\n}","line":{"from":238,"to":266}} {"id":100028370,"name":"WrapPreviousError","signature":"func (r *withRetry) WrapPreviousError(currentErr error) error","file":"staging/src/k8s.io/client-go/rest/with_retry.go","code":"func (r *withRetry) WrapPreviousError(currentErr error) error {\n\tif currentErr == nil || r.previousErr == nil {\n\t\treturn currentErr\n\t}\n\n\t// if both previous and current error objects represent the error,\n\t// then there is no need to wrap the previous error.\n\tif currentErr.Error() == r.previousErr.Error() {\n\t\treturn currentErr\n\t}\n\n\tpreviousErr := r.previousErr\n\t// net/http wraps the underlying error with an url.Error, if the\n\t// previous err object is an instance of url.Error, then we can\n\t// unwrap it to get to the inner error object, this is so we can\n\t// avoid error message like:\n\t// Error: Get \"http://foo.bar/api/v1\": context deadline exceeded - error \\\n\t// from a previous attempt: Error: Get \"http://foo.bar/api/v1\": EOF\n\tif urlErr, ok := r.previousErr.(*url.Error); ok \u0026\u0026 urlErr != nil {\n\t\tif urlErr.Unwrap() != nil {\n\t\t\tpreviousErr = urlErr.Unwrap()\n\t\t}\n\t}\n\n\treturn \u0026wrapPreviousError{\n\t\tcurrentErr: currentErr,\n\t\tpreviousError: previousErr,\n\t}\n}","line":{"from":268,"to":296}} {"id":100028371,"name":"Unwrap","signature":"func (w *wrapPreviousError) Unwrap() error { return w.currentErr }","file":"staging/src/k8s.io/client-go/rest/with_retry.go","code":"func (w *wrapPreviousError) Unwrap() error { return w.currentErr }","line":{"from":302,"to":302}} {"id":100028372,"name":"Error","signature":"func (w *wrapPreviousError) Error() string","file":"staging/src/k8s.io/client-go/rest/with_retry.go","code":"func (w *wrapPreviousError) Error() string {\n\treturn fmt.Sprintf(\"%s - error from a previous attempt: %s\", w.currentErr.Error(), w.previousError.Error())\n}","line":{"from":303,"to":305}} {"id":100028373,"name":"checkWait","signature":"func checkWait(resp *http.Response) (int, bool)","file":"staging/src/k8s.io/client-go/rest/with_retry.go","code":"// checkWait returns true along with a number of seconds if\n// the server instructed us to wait before retrying.\nfunc checkWait(resp *http.Response) (int, bool) {\n\tswitch r := resp.StatusCode; {\n\t// any 500 error code and 429 can trigger a wait\n\tcase r == http.StatusTooManyRequests, r \u003e= 500:\n\tdefault:\n\t\treturn 0, false\n\t}\n\ti, ok := retryAfterSeconds(resp)\n\treturn i, ok\n}","line":{"from":307,"to":318}} {"id":100028374,"name":"getRetryReason","signature":"func getRetryReason(retries, seconds int, resp *http.Response, err error) string","file":"staging/src/k8s.io/client-go/rest/with_retry.go","code":"func getRetryReason(retries, seconds int, resp *http.Response, err error) string {\n\t// priority and fairness sets the UID of the FlowSchema\n\t// associated with a request in the following response Header.\n\tconst responseHeaderMatchedFlowSchemaUID = \"X-Kubernetes-PF-FlowSchema-UID\"\n\n\tmessage := fmt.Sprintf(\"retries: %d, retry-after: %ds\", retries, seconds)\n\n\tswitch {\n\tcase resp.StatusCode == http.StatusTooManyRequests:\n\t\t// it is server-side throttling from priority and fairness\n\t\tflowSchemaUID := resp.Header.Get(responseHeaderMatchedFlowSchemaUID)\n\t\treturn fmt.Sprintf(\"%s - retry-reason: due to server-side throttling, FlowSchema UID: %q\", message, flowSchemaUID)\n\tcase err != nil:\n\t\t// it's a retryable error\n\t\treturn fmt.Sprintf(\"%s - retry-reason: due to retryable error, error: %v\", message, err)\n\tdefault:\n\t\treturn fmt.Sprintf(\"%s - retry-reason: %d\", message, resp.StatusCode)\n\t}\n}","line":{"from":320,"to":338}} {"id":100028375,"name":"readAndCloseResponseBody","signature":"func readAndCloseResponseBody(resp *http.Response)","file":"staging/src/k8s.io/client-go/rest/with_retry.go","code":"func readAndCloseResponseBody(resp *http.Response) {\n\tif resp == nil {\n\t\treturn\n\t}\n\n\t// Ensure the response body is fully read and closed\n\t// before we reconnect, so that we reuse the same TCP\n\t// connection.\n\tconst maxBodySlurpSize = 2 \u003c\u003c 10\n\tdefer resp.Body.Close()\n\n\tif resp.ContentLength \u003c= maxBodySlurpSize {\n\t\tio.Copy(io.Discard, \u0026io.LimitedReader{R: resp.Body, N: maxBodySlurpSize})\n\t}\n}","line":{"from":340,"to":354}} {"id":100028376,"name":"retryAfterResponse","signature":"func retryAfterResponse() *http.Response","file":"staging/src/k8s.io/client-go/rest/with_retry.go","code":"func retryAfterResponse() *http.Response {\n\treturn retryAfterResponseWithDelay(\"1\")\n}","line":{"from":356,"to":358}} {"id":100028377,"name":"retryAfterResponseWithDelay","signature":"func retryAfterResponseWithDelay(delay string) *http.Response","file":"staging/src/k8s.io/client-go/rest/with_retry.go","code":"func retryAfterResponseWithDelay(delay string) *http.Response {\n\treturn retryAfterResponseWithCodeAndDelay(http.StatusInternalServerError, delay)\n}","line":{"from":360,"to":362}} {"id":100028378,"name":"retryAfterResponseWithCodeAndDelay","signature":"func retryAfterResponseWithCodeAndDelay(code int, delay string) *http.Response","file":"staging/src/k8s.io/client-go/rest/with_retry.go","code":"func retryAfterResponseWithCodeAndDelay(code int, delay string) *http.Response {\n\treturn \u0026http.Response{\n\t\tStatusCode: code,\n\t\tHeader: http.Header{\"Retry-After\": []string{delay}},\n\t}\n}","line":{"from":364,"to":369}} {"id":100028379,"name":"Expand","signature":"func (e SimpleCategoryExpander) Expand(category string) ([]schema.GroupResource, bool)","file":"staging/src/k8s.io/client-go/restmapper/category_expansion.go","code":"// Expand fulfills CategoryExpander\nfunc (e SimpleCategoryExpander) Expand(category string) ([]schema.GroupResource, bool) {\n\tret, ok := e.Expansions[category]\n\treturn ret, ok\n}","line":{"from":36,"to":40}} {"id":100028380,"name":"NewDiscoveryCategoryExpander","signature":"func NewDiscoveryCategoryExpander(client discovery.DiscoveryInterface) CategoryExpander","file":"staging/src/k8s.io/client-go/restmapper/category_expansion.go","code":"// NewDiscoveryCategoryExpander returns a category expander that makes use of the \"categories\" fields from\n// the API, found through the discovery client. In case of any error or no category found (which likely\n// means we're at a cluster prior to categories support, fallback to the expander provided.\nfunc NewDiscoveryCategoryExpander(client discovery.DiscoveryInterface) CategoryExpander {\n\tif client == nil {\n\t\tpanic(\"Please provide discovery client to shortcut expander\")\n\t}\n\treturn discoveryCategoryExpander{discoveryClient: client}\n}","line":{"from":48,"to":56}} {"id":100028381,"name":"Expand","signature":"func (e discoveryCategoryExpander) Expand(category string) ([]schema.GroupResource, bool)","file":"staging/src/k8s.io/client-go/restmapper/category_expansion.go","code":"// Expand fulfills CategoryExpander\nfunc (e discoveryCategoryExpander) Expand(category string) ([]schema.GroupResource, bool) {\n\t// Get all supported resources for groups and versions from server, if no resource found, fallback anyway.\n\t_, apiResourceLists, _ := e.discoveryClient.ServerGroupsAndResources()\n\tif len(apiResourceLists) == 0 {\n\t\treturn nil, false\n\t}\n\n\tdiscoveredExpansions := map[string][]schema.GroupResource{}\n\tfor _, apiResourceList := range apiResourceLists {\n\t\tgv, err := schema.ParseGroupVersion(apiResourceList.GroupVersion)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\t// Collect GroupVersions by categories\n\t\tfor _, apiResource := range apiResourceList.APIResources {\n\t\t\tif categories := apiResource.Categories; len(categories) \u003e 0 {\n\t\t\t\tfor _, category := range categories {\n\t\t\t\t\tgroupResource := schema.GroupResource{\n\t\t\t\t\t\tGroup: gv.Group,\n\t\t\t\t\t\tResource: apiResource.Name,\n\t\t\t\t\t}\n\t\t\t\t\tdiscoveredExpansions[category] = append(discoveredExpansions[category], groupResource)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tret, ok := discoveredExpansions[category]\n\treturn ret, ok\n}","line":{"from":58,"to":88}} {"id":100028382,"name":"Expand","signature":"func (u UnionCategoryExpander) Expand(category string) ([]schema.GroupResource, bool)","file":"staging/src/k8s.io/client-go/restmapper/category_expansion.go","code":"// Expand fulfills CategoryExpander\nfunc (u UnionCategoryExpander) Expand(category string) ([]schema.GroupResource, bool) {\n\tret := []schema.GroupResource{}\n\tok := false\n\n\t// Expand the category for each CategoryExpander in the list and merge/combine the results.\n\tfor _, expansion := range u {\n\t\tcurr, currOk := expansion.Expand(category)\n\n\t\tfor _, currGR := range curr {\n\t\t\tfound := false\n\t\t\tfor _, existing := range ret {\n\t\t\t\tif existing == currGR {\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\tret = append(ret, currGR)\n\t\t\t}\n\t\t}\n\t\tok = ok || currOk\n\t}\n\n\treturn ret, ok\n}","line":{"from":94,"to":119}} {"id":100028383,"name":"NewDiscoveryRESTMapper","signature":"func NewDiscoveryRESTMapper(groupResources []*APIGroupResources) meta.RESTMapper","file":"staging/src/k8s.io/client-go/restmapper/discovery.go","code":"// NewDiscoveryRESTMapper returns a PriorityRESTMapper based on the discovered\n// groups and resources passed in.\nfunc NewDiscoveryRESTMapper(groupResources []*APIGroupResources) meta.RESTMapper {\n\tunionMapper := meta.MultiRESTMapper{}\n\n\tvar groupPriority []string\n\t// /v1 is special. It should always come first\n\tresourcePriority := []schema.GroupVersionResource{{Group: \"\", Version: \"v1\", Resource: meta.AnyResource}}\n\tkindPriority := []schema.GroupVersionKind{{Group: \"\", Version: \"v1\", Kind: meta.AnyKind}}\n\n\tfor _, group := range groupResources {\n\t\tgroupPriority = append(groupPriority, group.Group.Name)\n\n\t\t// Make sure the preferred version comes first\n\t\tif len(group.Group.PreferredVersion.Version) != 0 {\n\t\t\tpreferred := group.Group.PreferredVersion.Version\n\t\t\tif _, ok := group.VersionedResources[preferred]; ok {\n\t\t\t\tresourcePriority = append(resourcePriority, schema.GroupVersionResource{\n\t\t\t\t\tGroup: group.Group.Name,\n\t\t\t\t\tVersion: group.Group.PreferredVersion.Version,\n\t\t\t\t\tResource: meta.AnyResource,\n\t\t\t\t})\n\n\t\t\t\tkindPriority = append(kindPriority, schema.GroupVersionKind{\n\t\t\t\t\tGroup: group.Group.Name,\n\t\t\t\t\tVersion: group.Group.PreferredVersion.Version,\n\t\t\t\t\tKind: meta.AnyKind,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\tfor _, discoveryVersion := range group.Group.Versions {\n\t\t\tresources, ok := group.VersionedResources[discoveryVersion.Version]\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Add non-preferred versions after the preferred version, in case there are resources that only exist in those versions\n\t\t\tif discoveryVersion.Version != group.Group.PreferredVersion.Version {\n\t\t\t\tresourcePriority = append(resourcePriority, schema.GroupVersionResource{\n\t\t\t\t\tGroup: group.Group.Name,\n\t\t\t\t\tVersion: discoveryVersion.Version,\n\t\t\t\t\tResource: meta.AnyResource,\n\t\t\t\t})\n\n\t\t\t\tkindPriority = append(kindPriority, schema.GroupVersionKind{\n\t\t\t\t\tGroup: group.Group.Name,\n\t\t\t\t\tVersion: discoveryVersion.Version,\n\t\t\t\t\tKind: meta.AnyKind,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tgv := schema.GroupVersion{Group: group.Group.Name, Version: discoveryVersion.Version}\n\t\t\tversionMapper := meta.NewDefaultRESTMapper([]schema.GroupVersion{gv})\n\n\t\t\tfor _, resource := range resources {\n\t\t\t\tscope := meta.RESTScopeNamespace\n\t\t\t\tif !resource.Namespaced {\n\t\t\t\t\tscope = meta.RESTScopeRoot\n\t\t\t\t}\n\n\t\t\t\t// if we have a slash, then this is a subresource and we shouldn't create mappings for those.\n\t\t\t\tif strings.Contains(resource.Name, \"/\") {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tplural := gv.WithResource(resource.Name)\n\t\t\t\tsingular := gv.WithResource(resource.SingularName)\n\t\t\t\t// this is for legacy resources and servers which don't list singular forms. For those we must still guess.\n\t\t\t\tif len(resource.SingularName) == 0 {\n\t\t\t\t\t_, singular = meta.UnsafeGuessKindToResource(gv.WithKind(resource.Kind))\n\t\t\t\t}\n\n\t\t\t\tversionMapper.AddSpecific(gv.WithKind(strings.ToLower(resource.Kind)), plural, singular, scope)\n\t\t\t\tversionMapper.AddSpecific(gv.WithKind(resource.Kind), plural, singular, scope)\n\t\t\t\t// TODO this is producing unsafe guesses that don't actually work, but it matches previous behavior\n\t\t\t\tversionMapper.Add(gv.WithKind(resource.Kind+\"List\"), scope)\n\t\t\t}\n\t\t\t// TODO why is this type not in discovery (at least for \"v1\")\n\t\t\tversionMapper.Add(gv.WithKind(\"List\"), meta.RESTScopeRoot)\n\t\t\tunionMapper = append(unionMapper, versionMapper)\n\t\t}\n\t}\n\n\tfor _, group := range groupPriority {\n\t\tresourcePriority = append(resourcePriority, schema.GroupVersionResource{\n\t\t\tGroup: group,\n\t\t\tVersion: meta.AnyVersion,\n\t\t\tResource: meta.AnyResource,\n\t\t})\n\t\tkindPriority = append(kindPriority, schema.GroupVersionKind{\n\t\t\tGroup: group,\n\t\t\tVersion: meta.AnyVersion,\n\t\t\tKind: meta.AnyKind,\n\t\t})\n\t}\n\n\treturn meta.PriorityRESTMapper{\n\t\tDelegate: unionMapper,\n\t\tResourcePriority: resourcePriority,\n\t\tKindPriority: kindPriority,\n\t}\n}","line":{"from":41,"to":143}} {"id":100028384,"name":"GetAPIGroupResources","signature":"func GetAPIGroupResources(cl discovery.DiscoveryInterface) ([]*APIGroupResources, error)","file":"staging/src/k8s.io/client-go/restmapper/discovery.go","code":"// GetAPIGroupResources uses the provided discovery client to gather\n// discovery information and populate a slice of APIGroupResources.\nfunc GetAPIGroupResources(cl discovery.DiscoveryInterface) ([]*APIGroupResources, error) {\n\tgs, rs, err := cl.ServerGroupsAndResources()\n\tif rs == nil || gs == nil {\n\t\treturn nil, err\n\t\t// TODO track the errors and update callers to handle partial errors.\n\t}\n\trsm := map[string]*metav1.APIResourceList{}\n\tfor _, r := range rs {\n\t\trsm[r.GroupVersion] = r\n\t}\n\n\tvar result []*APIGroupResources\n\tfor _, group := range gs {\n\t\tgroupResources := \u0026APIGroupResources{\n\t\t\tGroup: *group,\n\t\t\tVersionedResources: make(map[string][]metav1.APIResource),\n\t\t}\n\t\tfor _, version := range group.Versions {\n\t\t\tresources, ok := rsm[version.GroupVersion]\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgroupResources.VersionedResources[version.Version] = resources.APIResources\n\t\t}\n\t\tresult = append(result, groupResources)\n\t}\n\treturn result, nil\n}","line":{"from":145,"to":174}} {"id":100028385,"name":"NewDeferredDiscoveryRESTMapper","signature":"func NewDeferredDiscoveryRESTMapper(cl discovery.CachedDiscoveryInterface) *DeferredDiscoveryRESTMapper","file":"staging/src/k8s.io/client-go/restmapper/discovery.go","code":"// NewDeferredDiscoveryRESTMapper returns a\n// DeferredDiscoveryRESTMapper that will lazily query the provided\n// client for discovery information to do REST mappings.\nfunc NewDeferredDiscoveryRESTMapper(cl discovery.CachedDiscoveryInterface) *DeferredDiscoveryRESTMapper {\n\treturn \u0026DeferredDiscoveryRESTMapper{\n\t\tcl: cl,\n\t}\n}","line":{"from":185,"to":192}} {"id":100028386,"name":"getDelegate","signature":"func (d *DeferredDiscoveryRESTMapper) getDelegate() (meta.RESTMapper, error)","file":"staging/src/k8s.io/client-go/restmapper/discovery.go","code":"func (d *DeferredDiscoveryRESTMapper) getDelegate() (meta.RESTMapper, error) {\n\td.initMu.Lock()\n\tdefer d.initMu.Unlock()\n\n\tif d.delegate != nil {\n\t\treturn d.delegate, nil\n\t}\n\n\tgroupResources, err := GetAPIGroupResources(d.cl)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\td.delegate = NewDiscoveryRESTMapper(groupResources)\n\treturn d.delegate, nil\n}","line":{"from":194,"to":209}} {"id":100028387,"name":"Reset","signature":"func (d *DeferredDiscoveryRESTMapper) Reset()","file":"staging/src/k8s.io/client-go/restmapper/discovery.go","code":"// Reset resets the internally cached Discovery information and will\n// cause the next mapping request to re-discover.\nfunc (d *DeferredDiscoveryRESTMapper) Reset() {\n\tklog.V(5).Info(\"Invalidating discovery information\")\n\n\td.initMu.Lock()\n\tdefer d.initMu.Unlock()\n\n\td.cl.Invalidate()\n\td.delegate = nil\n}","line":{"from":211,"to":221}} {"id":100028388,"name":"KindFor","signature":"func (d *DeferredDiscoveryRESTMapper) KindFor(resource schema.GroupVersionResource) (gvk schema.GroupVersionKind, err error)","file":"staging/src/k8s.io/client-go/restmapper/discovery.go","code":"// KindFor takes a partial resource and returns back the single match.\n// It returns an error if there are multiple matches.\nfunc (d *DeferredDiscoveryRESTMapper) KindFor(resource schema.GroupVersionResource) (gvk schema.GroupVersionKind, err error) {\n\tdel, err := d.getDelegate()\n\tif err != nil {\n\t\treturn schema.GroupVersionKind{}, err\n\t}\n\tgvk, err = del.KindFor(resource)\n\tif err != nil \u0026\u0026 !d.cl.Fresh() {\n\t\td.Reset()\n\t\tgvk, err = d.KindFor(resource)\n\t}\n\treturn\n}","line":{"from":223,"to":236}} {"id":100028389,"name":"KindsFor","signature":"func (d *DeferredDiscoveryRESTMapper) KindsFor(resource schema.GroupVersionResource) (gvks []schema.GroupVersionKind, err error)","file":"staging/src/k8s.io/client-go/restmapper/discovery.go","code":"// KindsFor takes a partial resource and returns back the list of\n// potential kinds in priority order.\nfunc (d *DeferredDiscoveryRESTMapper) KindsFor(resource schema.GroupVersionResource) (gvks []schema.GroupVersionKind, err error) {\n\tdel, err := d.getDelegate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgvks, err = del.KindsFor(resource)\n\tif len(gvks) == 0 \u0026\u0026 !d.cl.Fresh() {\n\t\td.Reset()\n\t\tgvks, err = d.KindsFor(resource)\n\t}\n\treturn\n}","line":{"from":238,"to":251}} {"id":100028390,"name":"ResourceFor","signature":"func (d *DeferredDiscoveryRESTMapper) ResourceFor(input schema.GroupVersionResource) (gvr schema.GroupVersionResource, err error)","file":"staging/src/k8s.io/client-go/restmapper/discovery.go","code":"// ResourceFor takes a partial resource and returns back the single\n// match. It returns an error if there are multiple matches.\nfunc (d *DeferredDiscoveryRESTMapper) ResourceFor(input schema.GroupVersionResource) (gvr schema.GroupVersionResource, err error) {\n\tdel, err := d.getDelegate()\n\tif err != nil {\n\t\treturn schema.GroupVersionResource{}, err\n\t}\n\tgvr, err = del.ResourceFor(input)\n\tif err != nil \u0026\u0026 !d.cl.Fresh() {\n\t\td.Reset()\n\t\tgvr, err = d.ResourceFor(input)\n\t}\n\treturn\n}","line":{"from":253,"to":266}} {"id":100028391,"name":"ResourcesFor","signature":"func (d *DeferredDiscoveryRESTMapper) ResourcesFor(input schema.GroupVersionResource) (gvrs []schema.GroupVersionResource, err error)","file":"staging/src/k8s.io/client-go/restmapper/discovery.go","code":"// ResourcesFor takes a partial resource and returns back the list of\n// potential resource in priority order.\nfunc (d *DeferredDiscoveryRESTMapper) ResourcesFor(input schema.GroupVersionResource) (gvrs []schema.GroupVersionResource, err error) {\n\tdel, err := d.getDelegate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgvrs, err = del.ResourcesFor(input)\n\tif len(gvrs) == 0 \u0026\u0026 !d.cl.Fresh() {\n\t\td.Reset()\n\t\tgvrs, err = d.ResourcesFor(input)\n\t}\n\treturn\n}","line":{"from":268,"to":281}} {"id":100028392,"name":"RESTMapping","signature":"func (d *DeferredDiscoveryRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (m *meta.RESTMapping, err error)","file":"staging/src/k8s.io/client-go/restmapper/discovery.go","code":"// RESTMapping identifies a preferred resource mapping for the\n// provided group kind.\nfunc (d *DeferredDiscoveryRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (m *meta.RESTMapping, err error) {\n\tdel, err := d.getDelegate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tm, err = del.RESTMapping(gk, versions...)\n\tif err != nil \u0026\u0026 !d.cl.Fresh() {\n\t\td.Reset()\n\t\tm, err = d.RESTMapping(gk, versions...)\n\t}\n\treturn\n}","line":{"from":283,"to":296}} {"id":100028393,"name":"RESTMappings","signature":"func (d *DeferredDiscoveryRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) (ms []*meta.RESTMapping, err error)","file":"staging/src/k8s.io/client-go/restmapper/discovery.go","code":"// RESTMappings returns the RESTMappings for the provided group kind\n// in a rough internal preferred order. If no kind is found, it will\n// return a NoResourceMatchError.\nfunc (d *DeferredDiscoveryRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) (ms []*meta.RESTMapping, err error) {\n\tdel, err := d.getDelegate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tms, err = del.RESTMappings(gk, versions...)\n\tif len(ms) == 0 \u0026\u0026 !d.cl.Fresh() {\n\t\td.Reset()\n\t\tms, err = d.RESTMappings(gk, versions...)\n\t}\n\treturn\n}","line":{"from":298,"to":312}} {"id":100028394,"name":"ResourceSingularizer","signature":"func (d *DeferredDiscoveryRESTMapper) ResourceSingularizer(resource string) (singular string, err error)","file":"staging/src/k8s.io/client-go/restmapper/discovery.go","code":"// ResourceSingularizer converts a resource name from plural to\n// singular (e.g., from pods to pod).\nfunc (d *DeferredDiscoveryRESTMapper) ResourceSingularizer(resource string) (singular string, err error) {\n\tdel, err := d.getDelegate()\n\tif err != nil {\n\t\treturn resource, err\n\t}\n\tsingular, err = del.ResourceSingularizer(resource)\n\tif err != nil \u0026\u0026 !d.cl.Fresh() {\n\t\td.Reset()\n\t\tsingular, err = d.ResourceSingularizer(resource)\n\t}\n\treturn\n}","line":{"from":314,"to":327}} {"id":100028395,"name":"String","signature":"func (d *DeferredDiscoveryRESTMapper) String() string","file":"staging/src/k8s.io/client-go/restmapper/discovery.go","code":"func (d *DeferredDiscoveryRESTMapper) String() string {\n\tdel, err := d.getDelegate()\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"DeferredDiscoveryRESTMapper{%v}\", err)\n\t}\n\treturn fmt.Sprintf(\"DeferredDiscoveryRESTMapper{\\n\\t%v\\n}\", del)\n}","line":{"from":329,"to":335}} {"id":100028396,"name":"NewShortcutExpander","signature":"func NewShortcutExpander(delegate meta.RESTMapper, client discovery.DiscoveryInterface) meta.RESTMapper","file":"staging/src/k8s.io/client-go/restmapper/shortcut.go","code":"// NewShortcutExpander wraps a restmapper in a layer that expands shortcuts found via discovery\nfunc NewShortcutExpander(delegate meta.RESTMapper, client discovery.DiscoveryInterface) meta.RESTMapper {\n\treturn shortcutExpander{RESTMapper: delegate, discoveryClient: client}\n}","line":{"from":39,"to":42}} {"id":100028397,"name":"KindFor","signature":"func (e shortcutExpander) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error)","file":"staging/src/k8s.io/client-go/restmapper/shortcut.go","code":"// KindFor fulfills meta.RESTMapper\nfunc (e shortcutExpander) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) {\n\t// expandResourceShortcut works with current API resources as read from discovery cache.\n\t// In case of new CRDs this means we potentially don't have current state of discovery.\n\t// In the current wiring in k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go#toRESTMapper,\n\t// we are using DeferredDiscoveryRESTMapper which on KindFor failure will clear the\n\t// cache and fetch all data from a cluster (see vendor/k8s.io/client-go/restmapper/discovery.go#KindFor).\n\t// Thus another call to expandResourceShortcut, after a NoMatchError should successfully\n\t// read Kind to the user or an error.\n\tgvk, err := e.RESTMapper.KindFor(e.expandResourceShortcut(resource))\n\tif meta.IsNoMatchError(err) {\n\t\treturn e.RESTMapper.KindFor(e.expandResourceShortcut(resource))\n\t}\n\treturn gvk, err\n}","line":{"from":44,"to":58}} {"id":100028398,"name":"KindsFor","signature":"func (e shortcutExpander) KindsFor(resource schema.GroupVersionResource) ([]schema.GroupVersionKind, error)","file":"staging/src/k8s.io/client-go/restmapper/shortcut.go","code":"// KindsFor fulfills meta.RESTMapper\nfunc (e shortcutExpander) KindsFor(resource schema.GroupVersionResource) ([]schema.GroupVersionKind, error) {\n\treturn e.RESTMapper.KindsFor(e.expandResourceShortcut(resource))\n}","line":{"from":60,"to":63}} {"id":100028399,"name":"ResourcesFor","signature":"func (e shortcutExpander) ResourcesFor(resource schema.GroupVersionResource) ([]schema.GroupVersionResource, error)","file":"staging/src/k8s.io/client-go/restmapper/shortcut.go","code":"// ResourcesFor fulfills meta.RESTMapper\nfunc (e shortcutExpander) ResourcesFor(resource schema.GroupVersionResource) ([]schema.GroupVersionResource, error) {\n\treturn e.RESTMapper.ResourcesFor(e.expandResourceShortcut(resource))\n}","line":{"from":65,"to":68}} {"id":100028400,"name":"ResourceFor","signature":"func (e shortcutExpander) ResourceFor(resource schema.GroupVersionResource) (schema.GroupVersionResource, error)","file":"staging/src/k8s.io/client-go/restmapper/shortcut.go","code":"// ResourceFor fulfills meta.RESTMapper\nfunc (e shortcutExpander) ResourceFor(resource schema.GroupVersionResource) (schema.GroupVersionResource, error) {\n\treturn e.RESTMapper.ResourceFor(e.expandResourceShortcut(resource))\n}","line":{"from":70,"to":73}} {"id":100028401,"name":"ResourceSingularizer","signature":"func (e shortcutExpander) ResourceSingularizer(resource string) (string, error)","file":"staging/src/k8s.io/client-go/restmapper/shortcut.go","code":"// ResourceSingularizer fulfills meta.RESTMapper\nfunc (e shortcutExpander) ResourceSingularizer(resource string) (string, error) {\n\treturn e.RESTMapper.ResourceSingularizer(e.expandResourceShortcut(schema.GroupVersionResource{Resource: resource}).Resource)\n}","line":{"from":75,"to":78}} {"id":100028402,"name":"RESTMapping","signature":"func (e shortcutExpander) RESTMapping(gk schema.GroupKind, versions ...string) (*meta.RESTMapping, error)","file":"staging/src/k8s.io/client-go/restmapper/shortcut.go","code":"// RESTMapping fulfills meta.RESTMapper\nfunc (e shortcutExpander) RESTMapping(gk schema.GroupKind, versions ...string) (*meta.RESTMapping, error) {\n\treturn e.RESTMapper.RESTMapping(gk, versions...)\n}","line":{"from":80,"to":83}} {"id":100028403,"name":"RESTMappings","signature":"func (e shortcutExpander) RESTMappings(gk schema.GroupKind, versions ...string) ([]*meta.RESTMapping, error)","file":"staging/src/k8s.io/client-go/restmapper/shortcut.go","code":"// RESTMappings fulfills meta.RESTMapper\nfunc (e shortcutExpander) RESTMappings(gk schema.GroupKind, versions ...string) ([]*meta.RESTMapping, error) {\n\treturn e.RESTMapper.RESTMappings(gk, versions...)\n}","line":{"from":85,"to":88}} {"id":100028404,"name":"getShortcutMappings","signature":"func (e shortcutExpander) getShortcutMappings() ([]*metav1.APIResourceList, []resourceShortcuts, error)","file":"staging/src/k8s.io/client-go/restmapper/shortcut.go","code":"// getShortcutMappings returns a set of tuples which holds short names for resources.\n// First the list of potential resources will be taken from the API server.\n// Next we will append the hardcoded list of resources - to be backward compatible with old servers.\n// NOTE that the list is ordered by group priority.\nfunc (e shortcutExpander) getShortcutMappings() ([]*metav1.APIResourceList, []resourceShortcuts, error) {\n\tres := []resourceShortcuts{}\n\t// get server resources\n\t// This can return an error *and* the results it was able to find. We don't need to fail on the error.\n\t_, apiResList, err := e.discoveryClient.ServerGroupsAndResources()\n\tif err != nil {\n\t\tklog.V(1).Infof(\"Error loading discovery information: %v\", err)\n\t}\n\tfor _, apiResources := range apiResList {\n\t\tgv, err := schema.ParseGroupVersion(apiResources.GroupVersion)\n\t\tif err != nil {\n\t\t\tklog.V(1).Infof(\"Unable to parse groupversion = %s due to = %s\", apiResources.GroupVersion, err.Error())\n\t\t\tcontinue\n\t\t}\n\t\tfor _, apiRes := range apiResources.APIResources {\n\t\t\tfor _, shortName := range apiRes.ShortNames {\n\t\t\t\trs := resourceShortcuts{\n\t\t\t\t\tShortForm: schema.GroupResource{Group: gv.Group, Resource: shortName},\n\t\t\t\t\tLongForm: schema.GroupResource{Group: gv.Group, Resource: apiRes.Name},\n\t\t\t\t}\n\t\t\t\tres = append(res, rs)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn apiResList, res, nil\n}","line":{"from":90,"to":120}} {"id":100028405,"name":"expandResourceShortcut","signature":"func (e shortcutExpander) expandResourceShortcut(resource schema.GroupVersionResource) schema.GroupVersionResource","file":"staging/src/k8s.io/client-go/restmapper/shortcut.go","code":"// expandResourceShortcut will return the expanded version of resource\n// (something that a pkg/api/meta.RESTMapper can understand), if it is\n// indeed a shortcut. If no match has been found, we will match on group prefixing.\n// Lastly we will return resource unmodified.\nfunc (e shortcutExpander) expandResourceShortcut(resource schema.GroupVersionResource) schema.GroupVersionResource {\n\t// get the shortcut mappings and return on first match.\n\tif allResources, shortcutResources, err := e.getShortcutMappings(); err == nil {\n\t\t// avoid expanding if there's an exact match to a full resource name\n\t\tfor _, apiResources := range allResources {\n\t\t\tgv, err := schema.ParseGroupVersion(apiResources.GroupVersion)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(resource.Group) != 0 \u0026\u0026 resource.Group != gv.Group {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor _, apiRes := range apiResources.APIResources {\n\t\t\t\tif resource.Resource == apiRes.Name {\n\t\t\t\t\treturn resource\n\t\t\t\t}\n\t\t\t\tif resource.Resource == apiRes.SingularName {\n\t\t\t\t\treturn resource\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor _, item := range shortcutResources {\n\t\t\tif len(resource.Group) != 0 \u0026\u0026 resource.Group != item.ShortForm.Group {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif resource.Resource == item.ShortForm.Resource {\n\t\t\t\tresource.Resource = item.LongForm.Resource\n\t\t\t\tresource.Group = item.LongForm.Group\n\t\t\t\treturn resource\n\t\t\t}\n\t\t}\n\n\t\t// we didn't find exact match so match on group prefixing. This allows autoscal to match autoscaling\n\t\tif len(resource.Group) == 0 {\n\t\t\treturn resource\n\t\t}\n\t\tfor _, item := range shortcutResources {\n\t\t\tif !strings.HasPrefix(item.ShortForm.Group, resource.Group) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif resource.Resource == item.ShortForm.Resource {\n\t\t\t\tresource.Resource = item.LongForm.Resource\n\t\t\t\tresource.Group = item.LongForm.Group\n\t\t\t\treturn resource\n\t\t\t}\n\t\t}\n\t}\n\n\treturn resource\n}","line":{"from":122,"to":176}} {"id":100028406,"name":"Reset","signature":"func (e shortcutExpander) Reset()","file":"staging/src/k8s.io/client-go/restmapper/shortcut.go","code":"func (e shortcutExpander) Reset() {\n\tmeta.MaybeResetRESTMapper(e.RESTMapper)\n}","line":{"from":178,"to":180}} {"id":100028407,"name":"init","signature":"func init()","file":"staging/src/k8s.io/client-go/scale/client.go","code":"func init() {\n\tmetav1.AddToGroupVersion(parameterScheme, versionV1)\n}","line":{"from":40,"to":42}} {"id":100028408,"name":"NewForConfig","signature":"func NewForConfig(cfg *restclient.Config, mapper PreferredResourceMapper, resolver dynamic.APIPathResolverFunc, scaleKindResolver ScaleKindResolver) (ScalesGetter, error)","file":"staging/src/k8s.io/client-go/scale/client.go","code":"// NewForConfig creates a new ScalesGetter which resolves kinds\n// to resources using the given RESTMapper, and API paths using\n// the given dynamic.APIPathResolverFunc.\nfunc NewForConfig(cfg *restclient.Config, mapper PreferredResourceMapper, resolver dynamic.APIPathResolverFunc, scaleKindResolver ScaleKindResolver) (ScalesGetter, error) {\n\t// so that the RESTClientFor doesn't complain\n\tcfg.GroupVersion = \u0026schema.GroupVersion{}\n\n\tcfg.NegotiatedSerializer = codecs.WithoutConversion()\n\tif len(cfg.UserAgent) == 0 {\n\t\tcfg.UserAgent = restclient.DefaultKubernetesUserAgent()\n\t}\n\n\tclient, err := restclient.RESTClientFor(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn New(client, mapper, resolver, scaleKindResolver), nil\n}","line":{"from":57,"to":75}} {"id":100028409,"name":"New","signature":"func New(baseClient restclient.Interface, mapper PreferredResourceMapper, resolver dynamic.APIPathResolverFunc, scaleKindResolver ScaleKindResolver) ScalesGetter","file":"staging/src/k8s.io/client-go/scale/client.go","code":"// New creates a new ScalesGetter using the given client to make requests.\n// The GroupVersion on the client is ignored.\nfunc New(baseClient restclient.Interface, mapper PreferredResourceMapper, resolver dynamic.APIPathResolverFunc, scaleKindResolver ScaleKindResolver) ScalesGetter {\n\treturn \u0026scaleClient{\n\t\tmapper: mapper,\n\n\t\tapiPathResolverFunc: resolver,\n\t\tscaleKindResolver: scaleKindResolver,\n\t\tclientBase: baseClient,\n\t}\n}","line":{"from":77,"to":87}} {"id":100028410,"name":"apiPathFor","signature":"func (c *scaleClient) apiPathFor(groupVer schema.GroupVersion) string","file":"staging/src/k8s.io/client-go/scale/client.go","code":"// apiPathFor returns the absolute api path for the given GroupVersion\nfunc (c *scaleClient) apiPathFor(groupVer schema.GroupVersion) string {\n\t// we need to set the API path based on GroupVersion (defaulting to the legacy path if none is set)\n\t// TODO: we \"cheat\" here since the API path really only depends on group ATM, but this should\n\t// *probably* take GroupVersionResource and not GroupVersionKind.\n\tapiPath := c.apiPathResolverFunc(groupVer.WithKind(\"\"))\n\tif apiPath == \"\" {\n\t\tapiPath = \"/api\"\n\t}\n\n\treturn restclient.DefaultVersionedAPIPath(apiPath, groupVer)\n}","line":{"from":89,"to":100}} {"id":100028411,"name":"pathAndVersionFor","signature":"func (c *scaleClient) pathAndVersionFor(resource schema.GroupResource) (string, schema.GroupVersionResource, error)","file":"staging/src/k8s.io/client-go/scale/client.go","code":"// pathAndVersionFor returns the appropriate base path and the associated full GroupVersionResource\n// for the given GroupResource\nfunc (c *scaleClient) pathAndVersionFor(resource schema.GroupResource) (string, schema.GroupVersionResource, error) {\n\tgvr, err := c.mapper.ResourceFor(resource.WithVersion(\"\"))\n\tif err != nil {\n\t\treturn \"\", gvr, fmt.Errorf(\"unable to get full preferred group-version-resource for %s: %v\", resource.String(), err)\n\t}\n\n\tgroupVer := gvr.GroupVersion()\n\n\treturn c.apiPathFor(groupVer), gvr, nil\n}","line":{"from":102,"to":113}} {"id":100028412,"name":"convertToScale","signature":"func convertToScale(result *restclient.Result) (*autoscaling.Scale, error)","file":"staging/src/k8s.io/client-go/scale/client.go","code":"// convertToScale converts the response body to autoscaling/v1.Scale\nfunc convertToScale(result *restclient.Result) (*autoscaling.Scale, error) {\n\tscaleBytes, err := result.Raw()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdecoder := scaleConverter.codecs.UniversalDecoder(scaleConverter.ScaleVersions()...)\n\trawScaleObj, err := runtime.Decode(decoder, scaleBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// convert whatever this is to autoscaling/v1.Scale\n\tscaleObj, err := scaleConverter.ConvertToVersion(rawScaleObj, autoscaling.SchemeGroupVersion)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"received an object from a /scale endpoint which was not convertible to autoscaling Scale: %v\", err)\n\t}\n\n\treturn scaleObj.(*autoscaling.Scale), nil\n}","line":{"from":122,"to":141}} {"id":100028413,"name":"Scales","signature":"func (c *scaleClient) Scales(namespace string) ScaleInterface","file":"staging/src/k8s.io/client-go/scale/client.go","code":"func (c *scaleClient) Scales(namespace string) ScaleInterface {\n\treturn \u0026namespacedScaleClient{\n\t\tclient: c,\n\t\tnamespace: namespace,\n\t}\n}","line":{"from":143,"to":148}} {"id":100028414,"name":"Get","signature":"func (c *namespacedScaleClient) Get(ctx context.Context, resource schema.GroupResource, name string, opts metav1.GetOptions) (*autoscaling.Scale, error)","file":"staging/src/k8s.io/client-go/scale/client.go","code":"func (c *namespacedScaleClient) Get(ctx context.Context, resource schema.GroupResource, name string, opts metav1.GetOptions) (*autoscaling.Scale, error) {\n\t// Currently, a /scale endpoint can return different scale types.\n\t// Until we have support for the alternative API representations proposal,\n\t// we need to deal with accepting different API versions.\n\t// In practice, this is autoscaling/v1.Scale and extensions/v1beta1.Scale\n\n\tpath, gvr, err := c.client.pathAndVersionFor(resource)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to get client for %s: %v\", resource.String(), err)\n\t}\n\n\tresult := c.client.clientBase.Get().\n\t\tAbsPath(path).\n\t\tNamespaceIfScoped(c.namespace, c.namespace != \"\").\n\t\tResource(gvr.Resource).\n\t\tName(name).\n\t\tSubResource(\"scale\").\n\t\tSpecificallyVersionedParams(\u0026opts, dynamicParameterCodec, versionV1).\n\t\tDo(ctx)\n\tif err := result.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn convertToScale(\u0026result)\n}","line":{"from":150,"to":174}} {"id":100028415,"name":"Update","signature":"func (c *namespacedScaleClient) Update(ctx context.Context, resource schema.GroupResource, scale *autoscaling.Scale, opts metav1.UpdateOptions) (*autoscaling.Scale, error)","file":"staging/src/k8s.io/client-go/scale/client.go","code":"func (c *namespacedScaleClient) Update(ctx context.Context, resource schema.GroupResource, scale *autoscaling.Scale, opts metav1.UpdateOptions) (*autoscaling.Scale, error) {\n\tpath, gvr, err := c.client.pathAndVersionFor(resource)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to get client for %s: %v\", resource.String(), err)\n\t}\n\n\t// Currently, a /scale endpoint can receive and return different scale types.\n\t// Until we have support for the alternative API representations proposal,\n\t// we need to deal with sending and accepting different API versions.\n\n\t// figure out what scale we actually need here\n\tdesiredGVK, err := c.client.scaleKindResolver.ScaleForResource(gvr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not find proper group-version for scale subresource of %s: %v\", gvr.String(), err)\n\t}\n\n\t// convert this to whatever this endpoint wants\n\tscaleUpdate, err := scaleConverter.ConvertToVersion(scale, desiredGVK.GroupVersion())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not convert scale update to external Scale: %v\", err)\n\t}\n\tencoder := scaleConverter.codecs.LegacyCodec(desiredGVK.GroupVersion())\n\tscaleUpdateBytes, err := runtime.Encode(encoder, scaleUpdate)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not encode scale update to external Scale: %v\", err)\n\t}\n\n\tresult := c.client.clientBase.Put().\n\t\tAbsPath(path).\n\t\tNamespaceIfScoped(c.namespace, c.namespace != \"\").\n\t\tResource(gvr.Resource).\n\t\tName(scale.Name).\n\t\tSubResource(\"scale\").\n\t\tSpecificallyVersionedParams(\u0026opts, dynamicParameterCodec, versionV1).\n\t\tBody(scaleUpdateBytes).\n\t\tDo(ctx)\n\tif err := result.Error(); err != nil {\n\t\t// propagate \"raw\" error from the API\n\t\t// this allows callers to interpret underlying Reason field\n\t\t// for example: errors.IsConflict(err)\n\t\treturn nil, err\n\t}\n\n\treturn convertToScale(\u0026result)\n}","line":{"from":176,"to":220}} {"id":100028416,"name":"Patch","signature":"func (c *namespacedScaleClient) Patch(ctx context.Context, gvr schema.GroupVersionResource, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions) (*autoscaling.Scale, error)","file":"staging/src/k8s.io/client-go/scale/client.go","code":"func (c *namespacedScaleClient) Patch(ctx context.Context, gvr schema.GroupVersionResource, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions) (*autoscaling.Scale, error) {\n\tgroupVersion := gvr.GroupVersion()\n\tresult := c.client.clientBase.Patch(pt).\n\t\tAbsPath(c.client.apiPathFor(groupVersion)).\n\t\tNamespaceIfScoped(c.namespace, c.namespace != \"\").\n\t\tResource(gvr.Resource).\n\t\tName(name).\n\t\tSubResource(\"scale\").\n\t\tSpecificallyVersionedParams(\u0026opts, dynamicParameterCodec, versionV1).\n\t\tBody(data).\n\t\tDo(ctx)\n\tif err := result.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn convertToScale(\u0026result)\n}","line":{"from":222,"to":238}} {"id":100028417,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/client-go/scale/scheme/appsint/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":32,"to":35}} {"id":100028418,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/client-go/scale/scheme/appsint/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":37,"to":40}} {"id":100028419,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/client-go/scale/scheme/appsint/register.go","code":"// Adds the list of known types to api.Scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026scalescheme.Scale{},\n\t)\n\treturn nil\n}","line":{"from":49,"to":55}} {"id":100028420,"name":"Convert_scheme_ScaleStatus_To_v1beta1_ScaleStatus","signature":"func Convert_scheme_ScaleStatus_To_v1beta1_ScaleStatus(in *scheme.ScaleStatus, out *v1beta1.ScaleStatus, s conversion.Scope) error","file":"staging/src/k8s.io/client-go/scale/scheme/appsv1beta1/conversion.go","code":"func Convert_scheme_ScaleStatus_To_v1beta1_ScaleStatus(in *scheme.ScaleStatus, out *v1beta1.ScaleStatus, s conversion.Scope) error {\n\tout.Replicas = in.Replicas\n\tout.Selector = nil\n\tout.TargetSelector = \"\"\n\tif in.Selector != nil {\n\t\tif in.Selector.MatchExpressions == nil || len(in.Selector.MatchExpressions) == 0 {\n\t\t\tout.Selector = in.Selector.MatchLabels\n\t\t}\n\n\t\tselector, err := metav1.LabelSelectorAsSelector(in.Selector)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid label selector: %v\", err)\n\t\t}\n\t\tout.TargetSelector = selector.String()\n\t}\n\n\treturn nil\n}","line":{"from":28,"to":45}} {"id":100028421,"name":"Convert_v1beta1_ScaleStatus_To_scheme_ScaleStatus","signature":"func Convert_v1beta1_ScaleStatus_To_scheme_ScaleStatus(in *v1beta1.ScaleStatus, out *scheme.ScaleStatus, s conversion.Scope) error","file":"staging/src/k8s.io/client-go/scale/scheme/appsv1beta1/conversion.go","code":"func Convert_v1beta1_ScaleStatus_To_scheme_ScaleStatus(in *v1beta1.ScaleStatus, out *scheme.ScaleStatus, s conversion.Scope) error {\n\tout.Replicas = in.Replicas\n\n\t// Normally when 2 fields map to the same internal value we favor the old field, since\n\t// old clients can't be expected to know about new fields but clients that know about the\n\t// new field can be expected to know about the old field (though that's not quite true, due\n\t// to kubectl apply). However, these fields are readonly, so any non-nil value should work.\n\tif in.TargetSelector != \"\" {\n\t\tlabelSelector, err := metav1.ParseToLabelSelector(in.TargetSelector)\n\t\tif err != nil {\n\t\t\tout.Selector = nil\n\t\t\treturn fmt.Errorf(\"failed to parse target selector: %v\", err)\n\t\t}\n\t\tout.Selector = labelSelector\n\t} else if in.Selector != nil {\n\t\tout.Selector = new(metav1.LabelSelector)\n\t\tselector := make(map[string]string)\n\t\tfor key, val := range in.Selector {\n\t\t\tselector[key] = val\n\t\t}\n\t\tout.Selector.MatchLabels = selector\n\t} else {\n\t\tout.Selector = nil\n\t}\n\n\treturn nil\n}","line":{"from":47,"to":73}} {"id":100028422,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/client-go/scale/scheme/appsv1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100028423,"name":"init","signature":"func init()","file":"staging/src/k8s.io/client-go/scale/scheme/appsv1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register()\n}","line":{"from":40,"to":45}} {"id":100028424,"name":"Convert_scheme_ScaleStatus_To_v1beta2_ScaleStatus","signature":"func Convert_scheme_ScaleStatus_To_v1beta2_ScaleStatus(in *scheme.ScaleStatus, out *v1beta2.ScaleStatus, s conversion.Scope) error","file":"staging/src/k8s.io/client-go/scale/scheme/appsv1beta2/conversion.go","code":"func Convert_scheme_ScaleStatus_To_v1beta2_ScaleStatus(in *scheme.ScaleStatus, out *v1beta2.ScaleStatus, s conversion.Scope) error {\n\tout.Replicas = in.Replicas\n\tout.Selector = nil\n\tout.TargetSelector = \"\"\n\tif in.Selector != nil {\n\t\tif in.Selector.MatchExpressions == nil || len(in.Selector.MatchExpressions) == 0 {\n\t\t\tout.Selector = in.Selector.MatchLabels\n\t\t}\n\n\t\tselector, err := metav1.LabelSelectorAsSelector(in.Selector)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid label selector: %v\", err)\n\t\t}\n\t\tout.TargetSelector = selector.String()\n\t}\n\n\treturn nil\n}","line":{"from":28,"to":45}} {"id":100028425,"name":"Convert_v1beta2_ScaleStatus_To_scheme_ScaleStatus","signature":"func Convert_v1beta2_ScaleStatus_To_scheme_ScaleStatus(in *v1beta2.ScaleStatus, out *scheme.ScaleStatus, s conversion.Scope) error","file":"staging/src/k8s.io/client-go/scale/scheme/appsv1beta2/conversion.go","code":"func Convert_v1beta2_ScaleStatus_To_scheme_ScaleStatus(in *v1beta2.ScaleStatus, out *scheme.ScaleStatus, s conversion.Scope) error {\n\tout.Replicas = in.Replicas\n\n\t// Normally when 2 fields map to the same internal value we favor the old field, since\n\t// old clients can't be expected to know about new fields but clients that know about the\n\t// new field can be expected to know about the old field (though that's not quite true, due\n\t// to kubectl apply). However, these fields are readonly, so any non-nil value should work.\n\tif in.TargetSelector != \"\" {\n\t\tlabelSelector, err := metav1.ParseToLabelSelector(in.TargetSelector)\n\t\tif err != nil {\n\t\t\tout.Selector = nil\n\t\t\treturn fmt.Errorf(\"failed to parse target selector: %v\", err)\n\t\t}\n\t\tout.Selector = labelSelector\n\t} else if in.Selector != nil {\n\t\tout.Selector = new(metav1.LabelSelector)\n\t\tselector := make(map[string]string)\n\t\tfor key, val := range in.Selector {\n\t\t\tselector[key] = val\n\t\t}\n\t\tout.Selector.MatchLabels = selector\n\t} else {\n\t\tout.Selector = nil\n\t}\n\n\treturn nil\n}","line":{"from":47,"to":73}} {"id":100028426,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/client-go/scale/scheme/appsv1beta2/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100028427,"name":"init","signature":"func init()","file":"staging/src/k8s.io/client-go/scale/scheme/appsv1beta2/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register()\n}","line":{"from":40,"to":45}} {"id":100028428,"name":"Convert_scheme_ScaleStatus_To_v1_ScaleStatus","signature":"func Convert_scheme_ScaleStatus_To_v1_ScaleStatus(in *scheme.ScaleStatus, out *v1.ScaleStatus, s conversion.Scope) error","file":"staging/src/k8s.io/client-go/scale/scheme/autoscalingv1/conversion.go","code":"func Convert_scheme_ScaleStatus_To_v1_ScaleStatus(in *scheme.ScaleStatus, out *v1.ScaleStatus, s conversion.Scope) error {\n\tout.Replicas = in.Replicas\n\tout.Selector = \"\"\n\tif in.Selector != nil {\n\t\tselector, err := metav1.LabelSelectorAsSelector(in.Selector)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid label selector: %v\", err)\n\t\t}\n\t\tout.Selector = selector.String()\n\t}\n\n\treturn nil\n}","line":{"from":28,"to":40}} {"id":100028429,"name":"Convert_v1_ScaleStatus_To_scheme_ScaleStatus","signature":"func Convert_v1_ScaleStatus_To_scheme_ScaleStatus(in *v1.ScaleStatus, out *scheme.ScaleStatus, s conversion.Scope) error","file":"staging/src/k8s.io/client-go/scale/scheme/autoscalingv1/conversion.go","code":"func Convert_v1_ScaleStatus_To_scheme_ScaleStatus(in *v1.ScaleStatus, out *scheme.ScaleStatus, s conversion.Scope) error {\n\tout.Replicas = in.Replicas\n\tif in.Selector != \"\" {\n\t\tlabelSelector, err := metav1.ParseToLabelSelector(in.Selector)\n\t\tif err != nil {\n\t\t\tout.Selector = nil\n\t\t\treturn fmt.Errorf(\"failed to parse target selector: %v\", err)\n\t\t}\n\t\tout.Selector = labelSelector\n\t}\n\n\treturn nil\n}","line":{"from":42,"to":54}} {"id":100028430,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/client-go/scale/scheme/autoscalingv1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100028431,"name":"init","signature":"func init()","file":"staging/src/k8s.io/client-go/scale/scheme/autoscalingv1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register()\n}","line":{"from":40,"to":45}} {"id":100028432,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/client-go/scale/scheme/extensionsint/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":32,"to":35}} {"id":100028433,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/client-go/scale/scheme/extensionsint/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":37,"to":40}} {"id":100028434,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/client-go/scale/scheme/extensionsint/register.go","code":"// Adds the list of known types to api.Scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026scalescheme.Scale{},\n\t)\n\treturn nil\n}","line":{"from":49,"to":55}} {"id":100028435,"name":"Convert_scheme_ScaleStatus_To_v1beta1_ScaleStatus","signature":"func Convert_scheme_ScaleStatus_To_v1beta1_ScaleStatus(in *scheme.ScaleStatus, out *v1beta1.ScaleStatus, s conversion.Scope) error","file":"staging/src/k8s.io/client-go/scale/scheme/extensionsv1beta1/conversion.go","code":"func Convert_scheme_ScaleStatus_To_v1beta1_ScaleStatus(in *scheme.ScaleStatus, out *v1beta1.ScaleStatus, s conversion.Scope) error {\n\tout.Replicas = in.Replicas\n\tout.Selector = nil\n\tout.TargetSelector = \"\"\n\tif in.Selector != nil {\n\t\tif in.Selector.MatchExpressions == nil || len(in.Selector.MatchExpressions) == 0 {\n\t\t\tout.Selector = in.Selector.MatchLabels\n\t\t}\n\n\t\tselector, err := metav1.LabelSelectorAsSelector(in.Selector)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid label selector: %v\", err)\n\t\t}\n\t\tout.TargetSelector = selector.String()\n\t}\n\n\treturn nil\n}","line":{"from":28,"to":45}} {"id":100028436,"name":"Convert_v1beta1_ScaleStatus_To_scheme_ScaleStatus","signature":"func Convert_v1beta1_ScaleStatus_To_scheme_ScaleStatus(in *v1beta1.ScaleStatus, out *scheme.ScaleStatus, s conversion.Scope) error","file":"staging/src/k8s.io/client-go/scale/scheme/extensionsv1beta1/conversion.go","code":"func Convert_v1beta1_ScaleStatus_To_scheme_ScaleStatus(in *v1beta1.ScaleStatus, out *scheme.ScaleStatus, s conversion.Scope) error {\n\tout.Replicas = in.Replicas\n\n\t// Normally when 2 fields map to the same internal value we favor the old field, since\n\t// old clients can't be expected to know about new fields but clients that know about the\n\t// new field can be expected to know about the old field (though that's not quite true, due\n\t// to kubectl apply). However, these fields are readonly, so any non-nil value should work.\n\tif in.TargetSelector != \"\" {\n\t\tlabelSelector, err := metav1.ParseToLabelSelector(in.TargetSelector)\n\t\tif err != nil {\n\t\t\tout.Selector = nil\n\t\t\treturn fmt.Errorf(\"failed to parse target selector: %v\", err)\n\t\t}\n\t\tout.Selector = labelSelector\n\t} else if in.Selector != nil {\n\t\tout.Selector = new(metav1.LabelSelector)\n\t\tselector := make(map[string]string)\n\t\tfor key, val := range in.Selector {\n\t\t\tselector[key] = val\n\t\t}\n\t\tout.Selector.MatchLabels = selector\n\t} else {\n\t\tout.Selector = nil\n\t}\n\n\treturn nil\n}","line":{"from":47,"to":73}} {"id":100028437,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/client-go/scale/scheme/extensionsv1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":30,"to":33}} {"id":100028438,"name":"init","signature":"func init()","file":"staging/src/k8s.io/client-go/scale/scheme/extensionsv1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register()\n}","line":{"from":40,"to":45}} {"id":100028439,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/client-go/scale/scheme/register.go","code":"// Kind takes an unqualified kind and returns a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":31,"to":34}} {"id":100028440,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/client-go/scale/scheme/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":36,"to":39}} {"id":100028441,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/client-go/scale/scheme/register.go","code":"// Adds the list of known types to api.Scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Scale{},\n\t)\n\treturn nil\n}","line":{"from":48,"to":54}} {"id":100028442,"name":"ScaleForResource","signature":"func (r *discoveryScaleResolver) ScaleForResource(inputRes schema.GroupVersionResource) (scaleVersion schema.GroupVersionKind, err error)","file":"staging/src/k8s.io/client-go/scale/util.go","code":"func (r *discoveryScaleResolver) ScaleForResource(inputRes schema.GroupVersionResource) (scaleVersion schema.GroupVersionKind, err error) {\n\tgroupVerResources, err := r.discoveryClient.ServerResourcesForGroupVersion(inputRes.GroupVersion().String())\n\tif err != nil {\n\t\treturn schema.GroupVersionKind{}, fmt.Errorf(\"unable to fetch discovery information for %s: %v\", inputRes.String(), err)\n\t}\n\n\tfor _, resource := range groupVerResources.APIResources {\n\t\tresourceParts := strings.SplitN(resource.Name, \"/\", 2)\n\t\tif len(resourceParts) != 2 || resourceParts[0] != inputRes.Resource || resourceParts[1] != \"scale\" {\n\t\t\t// skip non-scale resources, or scales for resources that we're not looking for\n\t\t\tcontinue\n\t\t}\n\n\t\tscaleGV := inputRes.GroupVersion()\n\t\tif resource.Group != \"\" \u0026\u0026 resource.Version != \"\" {\n\t\t\tscaleGV = schema.GroupVersion{\n\t\t\t\tGroup: resource.Group,\n\t\t\t\tVersion: resource.Version,\n\t\t\t}\n\t\t}\n\n\t\treturn scaleGV.WithKind(resource.Kind), nil\n\t}\n\n\treturn schema.GroupVersionKind{}, fmt.Errorf(\"could not find scale subresource for %s in discovery information\", inputRes.String())\n}","line":{"from":63,"to":88}} {"id":100028443,"name":"ScaleForResource","signature":"func (r *cachedScaleKindResolver) ScaleForResource(resource schema.GroupVersionResource) (schema.GroupVersionKind, error)","file":"staging/src/k8s.io/client-go/scale/util.go","code":"func (r *cachedScaleKindResolver) ScaleForResource(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) {\n\tr.mu.RLock()\n\tgvk, isCached := r.cache[resource]\n\tr.mu.RUnlock()\n\tif isCached {\n\t\treturn gvk, nil\n\t}\n\n\t// we could have multiple fetches of the same resources, but that's probably\n\t// better than limiting to only one reader at once (mu.Mutex),\n\t// or blocking checks for other resources while we fetch\n\t// (mu.Lock before fetch).\n\tgvk, err := r.base.ScaleForResource(resource)\n\tif err != nil {\n\t\treturn schema.GroupVersionKind{}, err\n\t}\n\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\tr.cache[resource] = gvk\n\n\treturn gvk, nil\n}","line":{"from":99,"to":121}} {"id":100028444,"name":"NewDiscoveryScaleKindResolver","signature":"func NewDiscoveryScaleKindResolver(client discovery.ServerResourcesInterface) ScaleKindResolver","file":"staging/src/k8s.io/client-go/scale/util.go","code":"// NewDiscoveryScaleKindResolver creates a new ScaleKindResolver which uses information from the given\n// disovery client to resolve the correct Scale GroupVersionKind for different resources.\nfunc NewDiscoveryScaleKindResolver(client discovery.ServerResourcesInterface) ScaleKindResolver {\n\tbase := \u0026discoveryScaleResolver{\n\t\tdiscoveryClient: client,\n\t}\n\n\treturn \u0026cachedScaleKindResolver{\n\t\tbase: base,\n\t\tcache: make(map[schema.GroupVersionResource]schema.GroupVersionKind),\n\t}\n}","line":{"from":123,"to":134}} {"id":100028445,"name":"NewScaleConverter","signature":"func NewScaleConverter() *ScaleConverter","file":"staging/src/k8s.io/client-go/scale/util.go","code":"// NewScaleConverter creates a new ScaleConverter for converting between\n// Scales in autoscaling/v1 and extensions/v1beta1.\nfunc NewScaleConverter() *ScaleConverter {\n\tscheme := runtime.NewScheme()\n\tutilruntime.Must(scaleautoscaling.AddToScheme(scheme))\n\tutilruntime.Must(scalescheme.AddToScheme(scheme))\n\tutilruntime.Must(scaleext.AddToScheme(scheme))\n\tutilruntime.Must(scaleextint.AddToScheme(scheme))\n\tutilruntime.Must(scaleappsint.AddToScheme(scheme))\n\tutilruntime.Must(scaleappsv1beta1.AddToScheme(scheme))\n\tutilruntime.Must(scaleappsv1beta2.AddToScheme(scheme))\n\n\treturn \u0026ScaleConverter{\n\t\tscheme: scheme,\n\t\tcodecs: serializer.NewCodecFactory(scheme),\n\t\tinternalVersioner: runtime.NewMultiGroupVersioner(\n\t\t\tscalescheme.SchemeGroupVersion,\n\t\t\tschema.GroupKind{Group: scaleext.GroupName, Kind: \"Scale\"},\n\t\t\tschema.GroupKind{Group: scaleautoscaling.GroupName, Kind: \"Scale\"},\n\t\t\tschema.GroupKind{Group: scaleappsv1beta1.GroupName, Kind: \"Scale\"},\n\t\t\tschema.GroupKind{Group: scaleappsv1beta2.GroupName, Kind: \"Scale\"},\n\t\t),\n\t}\n}","line":{"from":143,"to":166}} {"id":100028446,"name":"Scheme","signature":"func (c *ScaleConverter) Scheme() *runtime.Scheme","file":"staging/src/k8s.io/client-go/scale/util.go","code":"// Scheme returns the scheme used by this scale converter.\nfunc (c *ScaleConverter) Scheme() *runtime.Scheme {\n\treturn c.scheme\n}","line":{"from":168,"to":171}} {"id":100028447,"name":"Codecs","signature":"func (c *ScaleConverter) Codecs() serializer.CodecFactory","file":"staging/src/k8s.io/client-go/scale/util.go","code":"func (c *ScaleConverter) Codecs() serializer.CodecFactory {\n\treturn c.codecs\n}","line":{"from":173,"to":175}} {"id":100028448,"name":"ScaleVersions","signature":"func (c *ScaleConverter) ScaleVersions() []schema.GroupVersion","file":"staging/src/k8s.io/client-go/scale/util.go","code":"func (c *ScaleConverter) ScaleVersions() []schema.GroupVersion {\n\treturn []schema.GroupVersion{\n\t\tscaleautoscaling.SchemeGroupVersion,\n\t\tscalescheme.SchemeGroupVersion,\n\t\tscaleext.SchemeGroupVersion,\n\t\tscaleextint.SchemeGroupVersion,\n\t\tscaleappsint.SchemeGroupVersion,\n\t\tscaleappsv1beta1.SchemeGroupVersion,\n\t\tscaleappsv1beta2.SchemeGroupVersion,\n\t}\n}","line":{"from":177,"to":187}} {"id":100028449,"name":"ConvertToVersion","signature":"func (c *ScaleConverter) ConvertToVersion(in runtime.Object, outVersion schema.GroupVersion) (runtime.Object, error)","file":"staging/src/k8s.io/client-go/scale/util.go","code":"// ConvertToVersion converts the given *external* input object to the given output *external* output group-version.\nfunc (c *ScaleConverter) ConvertToVersion(in runtime.Object, outVersion schema.GroupVersion) (runtime.Object, error) {\n\tscaleInt, err := c.scheme.ConvertToVersion(in, c.internalVersioner)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.scheme.ConvertToVersion(scaleInt, outVersion)\n}","line":{"from":189,"to":197}} {"id":100028450,"name":"LoadFromFile","signature":"func LoadFromFile(path string) (*Info, error)","file":"staging/src/k8s.io/client-go/tools/auth/clientauth.go","code":"// LoadFromFile parses an Info object from a file path.\n// If the file does not exist, then os.IsNotExist(err) == true\nfunc LoadFromFile(path string) (*Info, error) {\n\tvar info Info\n\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\treturn nil, err\n\t}\n\tdata, err := os.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = json.Unmarshal(data, \u0026info)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026info, err\n}","line":{"from":85,"to":101}} {"id":100028451,"name":"MergeWithConfig","signature":"func (info Info) MergeWithConfig(c restclient.Config) (restclient.Config, error)","file":"staging/src/k8s.io/client-go/tools/auth/clientauth.go","code":"// MergeWithConfig returns a copy of a client.Config with values from the Info.\n// The fields of client.Config with a corresponding field in the Info are set\n// with the value from the Info.\nfunc (info Info) MergeWithConfig(c restclient.Config) (restclient.Config, error) {\n\tvar config = c\n\tconfig.Username = info.User\n\tconfig.Password = info.Password\n\tconfig.CAFile = info.CAFile\n\tconfig.CertFile = info.CertFile\n\tconfig.KeyFile = info.KeyFile\n\tconfig.BearerToken = info.BearerToken\n\tif info.Insecure != nil {\n\t\tconfig.Insecure = *info.Insecure\n\t}\n\treturn config, nil\n}","line":{"from":103,"to":118}} {"id":100028452,"name":"Complete","signature":"func (info Info) Complete() bool","file":"staging/src/k8s.io/client-go/tools/auth/clientauth.go","code":"// Complete returns true if the Kubernetes API authorization info is complete.\nfunc (info Info) Complete() bool {\n\treturn len(info.User) \u003e 0 ||\n\t\tlen(info.CertFile) \u003e 0 ||\n\t\tlen(info.BearerToken) \u003e 0\n}","line":{"from":120,"to":125}} {"id":100028453,"name":"init","signature":"func init()","file":"staging/src/k8s.io/client-go/tools/auth/exec/exec.go","code":"func init() {\n\tinstall.Install(scheme)\n}","line":{"from":38,"to":40}} {"id":100028454,"name":"LoadExecCredentialFromEnv","signature":"func LoadExecCredentialFromEnv() (runtime.Object, *rest.Config, error)","file":"staging/src/k8s.io/client-go/tools/auth/exec/exec.go","code":"// LoadExecCredentialFromEnv is a helper-wrapper around LoadExecCredential that loads from the\n// well-known KUBERNETES_EXEC_INFO environment variable.\n//\n// When the KUBERNETES_EXEC_INFO environment variable is not set or is empty, then this function\n// will immediately return an error.\nfunc LoadExecCredentialFromEnv() (runtime.Object, *rest.Config, error) {\n\tenv := os.Getenv(execInfoEnv)\n\tif env == \"\" {\n\t\treturn nil, nil, errors.New(\"KUBERNETES_EXEC_INFO env var is unset or empty\")\n\t}\n\treturn LoadExecCredential([]byte(env))\n}","line":{"from":42,"to":53}} {"id":100028455,"name":"LoadExecCredential","signature":"func LoadExecCredential(data []byte) (runtime.Object, *rest.Config, error)","file":"staging/src/k8s.io/client-go/tools/auth/exec/exec.go","code":"// LoadExecCredential loads the configuration needed for an exec plugin to communicate with a\n// cluster.\n//\n// LoadExecCredential expects the provided data to be a serialized client.authentication.k8s.io\n// ExecCredential object (of any version). If the provided data is invalid (i.e., it cannot be\n// unmarshalled into any known client.authentication.k8s.io ExecCredential version), an error will\n// be returned. A successfully unmarshalled ExecCredential will be returned as the first return\n// value.\n//\n// If the provided data is successfully unmarshalled, but it does not contain cluster information\n// (i.e., ExecCredential.Spec.Cluster == nil), then an error will be returned.\n//\n// Note that the returned rest.Config will use anonymous authentication, since the exec plugin has\n// not returned credentials for this cluster yet.\nfunc LoadExecCredential(data []byte) (runtime.Object, *rest.Config, error) {\n\tobj, gvk, err := codecs.UniversalDeserializer().Decode(data, nil, nil)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"decode: %w\", err)\n\t}\n\n\texpectedGK := schema.GroupKind{\n\t\tGroup: clientauthentication.SchemeGroupVersion.Group,\n\t\tKind: \"ExecCredential\",\n\t}\n\tif gvk.GroupKind() != expectedGK {\n\t\treturn nil, nil, fmt.Errorf(\n\t\t\t\"invalid group/kind: wanted %s, got %s\",\n\t\t\texpectedGK.String(),\n\t\t\tgvk.GroupKind().String(),\n\t\t)\n\t}\n\n\t// Explicitly convert object here so that we can return a nicer error message above for when the\n\t// data represents an invalid type.\n\tvar execCredential clientauthentication.ExecCredential\n\tif err := scheme.Convert(obj, \u0026execCredential, nil); err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"cannot convert to ExecCredential: %w\", err)\n\t}\n\n\tif execCredential.Spec.Cluster == nil {\n\t\treturn nil, nil, errors.New(\"ExecCredential does not contain cluster information\")\n\t}\n\n\trestConfig, err := rest.ExecClusterToConfig(execCredential.Spec.Cluster)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"cannot create rest.Config: %w\", err)\n\t}\n\n\treturn obj, restConfig, nil\n}","line":{"from":55,"to":104}} {"id":100028456,"name":"New","signature":"func New(c *Config) Controller","file":"staging/src/k8s.io/client-go/tools/cache/controller.go","code":"// New makes a new Controller from the given Config.\nfunc New(c *Config) Controller {\n\tctlr := \u0026controller{\n\t\tconfig: *c,\n\t\tclock: \u0026clock.RealClock{},\n\t}\n\treturn ctlr\n}","line":{"from":118,"to":125}} {"id":100028457,"name":"Run","signature":"func (c *controller) Run(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/client-go/tools/cache/controller.go","code":"// Run begins processing items, and will continue until a value is sent down stopCh or it is closed.\n// It's an error to call Run more than once.\n// Run blocks; call via go.\nfunc (c *controller) Run(stopCh \u003c-chan struct{}) {\n\tdefer utilruntime.HandleCrash()\n\tgo func() {\n\t\t\u003c-stopCh\n\t\tc.config.Queue.Close()\n\t}()\n\tr := NewReflectorWithOptions(\n\t\tc.config.ListerWatcher,\n\t\tc.config.ObjectType,\n\t\tc.config.Queue,\n\t\tReflectorOptions{\n\t\t\tResyncPeriod: c.config.FullResyncPeriod,\n\t\t\tTypeDescription: c.config.ObjectDescription,\n\t\t\tClock: c.clock,\n\t\t},\n\t)\n\tr.ShouldResync = c.config.ShouldResync\n\tr.WatchListPageSize = c.config.WatchListPageSize\n\tif c.config.WatchErrorHandler != nil {\n\t\tr.watchErrorHandler = c.config.WatchErrorHandler\n\t}\n\tif s := os.Getenv(\"ENABLE_CLIENT_GO_WATCH_LIST_ALPHA\"); len(s) \u003e 0 {\n\t\tr.UseWatchList = true\n\t}\n\n\tc.reflectorMutex.Lock()\n\tc.reflector = r\n\tc.reflectorMutex.Unlock()\n\n\tvar wg wait.Group\n\n\twg.StartWithChannel(stopCh, r.Run)\n\n\twait.Until(c.processLoop, time.Second, stopCh)\n\twg.Wait()\n}","line":{"from":127,"to":165}} {"id":100028458,"name":"HasSynced","signature":"func (c *controller) HasSynced() bool","file":"staging/src/k8s.io/client-go/tools/cache/controller.go","code":"// Returns true once this controller has completed an initial resource listing\nfunc (c *controller) HasSynced() bool {\n\treturn c.config.Queue.HasSynced()\n}","line":{"from":167,"to":170}} {"id":100028459,"name":"LastSyncResourceVersion","signature":"func (c *controller) LastSyncResourceVersion() string","file":"staging/src/k8s.io/client-go/tools/cache/controller.go","code":"func (c *controller) LastSyncResourceVersion() string {\n\tc.reflectorMutex.RLock()\n\tdefer c.reflectorMutex.RUnlock()\n\tif c.reflector == nil {\n\t\treturn \"\"\n\t}\n\treturn c.reflector.LastSyncResourceVersion()\n}","line":{"from":172,"to":179}} {"id":100028460,"name":"processLoop","signature":"func (c *controller) processLoop()","file":"staging/src/k8s.io/client-go/tools/cache/controller.go","code":"// processLoop drains the work queue.\n// TODO: Consider doing the processing in parallel. This will require a little thought\n// to make sure that we don't end up processing the same object multiple times\n// concurrently.\n//\n// TODO: Plumb through the stopCh here (and down to the queue) so that this can\n// actually exit when the controller is stopped. Or just give up on this stuff\n// ever being stoppable. Converting this whole package to use Context would\n// also be helpful.\nfunc (c *controller) processLoop() {\n\tfor {\n\t\tobj, err := c.config.Queue.Pop(PopProcessFunc(c.config.Process))\n\t\tif err != nil {\n\t\t\tif err == ErrFIFOClosed {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif c.config.RetryOnError {\n\t\t\t\t// This is the safe way to re-enqueue.\n\t\t\t\tc.config.Queue.AddIfNotPresent(obj)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":181,"to":203}} {"id":100028461,"name":"OnAdd","signature":"func (r ResourceEventHandlerFuncs) OnAdd(obj interface{}, isInInitialList bool)","file":"staging/src/k8s.io/client-go/tools/cache/controller.go","code":"// OnAdd calls AddFunc if it's not nil.\nfunc (r ResourceEventHandlerFuncs) OnAdd(obj interface{}, isInInitialList bool) {\n\tif r.AddFunc != nil {\n\t\tr.AddFunc(obj)\n\t}\n}","line":{"from":240,"to":245}} {"id":100028462,"name":"OnUpdate","signature":"func (r ResourceEventHandlerFuncs) OnUpdate(oldObj, newObj interface{})","file":"staging/src/k8s.io/client-go/tools/cache/controller.go","code":"// OnUpdate calls UpdateFunc if it's not nil.\nfunc (r ResourceEventHandlerFuncs) OnUpdate(oldObj, newObj interface{}) {\n\tif r.UpdateFunc != nil {\n\t\tr.UpdateFunc(oldObj, newObj)\n\t}\n}","line":{"from":247,"to":252}} {"id":100028463,"name":"OnDelete","signature":"func (r ResourceEventHandlerFuncs) OnDelete(obj interface{})","file":"staging/src/k8s.io/client-go/tools/cache/controller.go","code":"// OnDelete calls DeleteFunc if it's not nil.\nfunc (r ResourceEventHandlerFuncs) OnDelete(obj interface{}) {\n\tif r.DeleteFunc != nil {\n\t\tr.DeleteFunc(obj)\n\t}\n}","line":{"from":254,"to":259}} {"id":100028464,"name":"OnAdd","signature":"func (r ResourceEventHandlerDetailedFuncs) OnAdd(obj interface{}, isInInitialList bool)","file":"staging/src/k8s.io/client-go/tools/cache/controller.go","code":"// OnAdd calls AddFunc if it's not nil.\nfunc (r ResourceEventHandlerDetailedFuncs) OnAdd(obj interface{}, isInInitialList bool) {\n\tif r.AddFunc != nil {\n\t\tr.AddFunc(obj, isInInitialList)\n\t}\n}","line":{"from":270,"to":275}} {"id":100028465,"name":"OnUpdate","signature":"func (r ResourceEventHandlerDetailedFuncs) OnUpdate(oldObj, newObj interface{})","file":"staging/src/k8s.io/client-go/tools/cache/controller.go","code":"// OnUpdate calls UpdateFunc if it's not nil.\nfunc (r ResourceEventHandlerDetailedFuncs) OnUpdate(oldObj, newObj interface{}) {\n\tif r.UpdateFunc != nil {\n\t\tr.UpdateFunc(oldObj, newObj)\n\t}\n}","line":{"from":277,"to":282}} {"id":100028466,"name":"OnDelete","signature":"func (r ResourceEventHandlerDetailedFuncs) OnDelete(obj interface{})","file":"staging/src/k8s.io/client-go/tools/cache/controller.go","code":"// OnDelete calls DeleteFunc if it's not nil.\nfunc (r ResourceEventHandlerDetailedFuncs) OnDelete(obj interface{}) {\n\tif r.DeleteFunc != nil {\n\t\tr.DeleteFunc(obj)\n\t}\n}","line":{"from":284,"to":289}} {"id":100028467,"name":"OnAdd","signature":"func (r FilteringResourceEventHandler) OnAdd(obj interface{}, isInInitialList bool)","file":"staging/src/k8s.io/client-go/tools/cache/controller.go","code":"// OnAdd calls the nested handler only if the filter succeeds\nfunc (r FilteringResourceEventHandler) OnAdd(obj interface{}, isInInitialList bool) {\n\tif !r.FilterFunc(obj) {\n\t\treturn\n\t}\n\tr.Handler.OnAdd(obj, isInInitialList)\n}","line":{"from":301,"to":307}} {"id":100028468,"name":"OnUpdate","signature":"func (r FilteringResourceEventHandler) OnUpdate(oldObj, newObj interface{})","file":"staging/src/k8s.io/client-go/tools/cache/controller.go","code":"// OnUpdate ensures the proper handler is called depending on whether the filter matches\nfunc (r FilteringResourceEventHandler) OnUpdate(oldObj, newObj interface{}) {\n\tnewer := r.FilterFunc(newObj)\n\tolder := r.FilterFunc(oldObj)\n\tswitch {\n\tcase newer \u0026\u0026 older:\n\t\tr.Handler.OnUpdate(oldObj, newObj)\n\tcase newer \u0026\u0026 !older:\n\t\tr.Handler.OnAdd(newObj, false)\n\tcase !newer \u0026\u0026 older:\n\t\tr.Handler.OnDelete(oldObj)\n\tdefault:\n\t\t// do nothing\n\t}\n}","line":{"from":309,"to":323}} {"id":100028469,"name":"OnDelete","signature":"func (r FilteringResourceEventHandler) OnDelete(obj interface{})","file":"staging/src/k8s.io/client-go/tools/cache/controller.go","code":"// OnDelete calls the nested handler only if the filter succeeds\nfunc (r FilteringResourceEventHandler) OnDelete(obj interface{}) {\n\tif !r.FilterFunc(obj) {\n\t\treturn\n\t}\n\tr.Handler.OnDelete(obj)\n}","line":{"from":325,"to":331}} {"id":100028470,"name":"DeletionHandlingMetaNamespaceKeyFunc","signature":"func DeletionHandlingMetaNamespaceKeyFunc(obj interface{}) (string, error)","file":"staging/src/k8s.io/client-go/tools/cache/controller.go","code":"// DeletionHandlingMetaNamespaceKeyFunc checks for\n// DeletedFinalStateUnknown objects before calling\n// MetaNamespaceKeyFunc.\nfunc DeletionHandlingMetaNamespaceKeyFunc(obj interface{}) (string, error) {\n\tif d, ok := obj.(DeletedFinalStateUnknown); ok {\n\t\treturn d.Key, nil\n\t}\n\treturn MetaNamespaceKeyFunc(obj)\n}","line":{"from":333,"to":341}} {"id":100028471,"name":"NewInformer","signature":"func NewInformer(","file":"staging/src/k8s.io/client-go/tools/cache/controller.go","code":"// NewInformer returns a Store and a controller for populating the store\n// while also providing event notifications. You should only used the returned\n// Store for Get/List operations; Add/Modify/Deletes will cause the event\n// notifications to be faulty.\n//\n// Parameters:\n// - lw is list and watch functions for the source of the resource you want to\n// be informed of.\n// - objType is an object of the type that you expect to receive.\n// - resyncPeriod: if non-zero, will re-list this often (you will get OnUpdate\n// calls, even if nothing changed). Otherwise, re-list will be delayed as\n// long as possible (until the upstream source closes the watch or times out,\n// or you stop the controller).\n// - h is the object you want notifications sent to.\nfunc NewInformer(\n\tlw ListerWatcher,\n\tobjType runtime.Object,\n\tresyncPeriod time.Duration,\n\th ResourceEventHandler,\n) (Store, Controller) {\n\t// This will hold the client state, as we know it.\n\tclientState := NewStore(DeletionHandlingMetaNamespaceKeyFunc)\n\n\treturn clientState, newInformer(lw, objType, resyncPeriod, h, clientState, nil)\n}","line":{"from":343,"to":367}} {"id":100028472,"name":"NewIndexerInformer","signature":"func NewIndexerInformer(","file":"staging/src/k8s.io/client-go/tools/cache/controller.go","code":"// NewIndexerInformer returns an Indexer and a Controller for populating the index\n// while also providing event notifications. You should only used the returned\n// Index for Get/List operations; Add/Modify/Deletes will cause the event\n// notifications to be faulty.\n//\n// Parameters:\n// - lw is list and watch functions for the source of the resource you want to\n// be informed of.\n// - objType is an object of the type that you expect to receive.\n// - resyncPeriod: if non-zero, will re-list this often (you will get OnUpdate\n// calls, even if nothing changed). Otherwise, re-list will be delayed as\n// long as possible (until the upstream source closes the watch or times out,\n// or you stop the controller).\n// - h is the object you want notifications sent to.\n// - indexers is the indexer for the received object type.\nfunc NewIndexerInformer(\n\tlw ListerWatcher,\n\tobjType runtime.Object,\n\tresyncPeriod time.Duration,\n\th ResourceEventHandler,\n\tindexers Indexers,\n) (Indexer, Controller) {\n\t// This will hold the client state, as we know it.\n\tclientState := NewIndexer(DeletionHandlingMetaNamespaceKeyFunc, indexers)\n\n\treturn clientState, newInformer(lw, objType, resyncPeriod, h, clientState, nil)\n}","line":{"from":369,"to":395}} {"id":100028473,"name":"NewTransformingInformer","signature":"func NewTransformingInformer(","file":"staging/src/k8s.io/client-go/tools/cache/controller.go","code":"// NewTransformingInformer returns a Store and a controller for populating\n// the store while also providing event notifications. You should only used\n// the returned Store for Get/List operations; Add/Modify/Deletes will cause\n// the event notifications to be faulty.\n// The given transform function will be called on all objects before they will\n// put into the Store and corresponding Add/Modify/Delete handlers will\n// be invoked for them.\nfunc NewTransformingInformer(\n\tlw ListerWatcher,\n\tobjType runtime.Object,\n\tresyncPeriod time.Duration,\n\th ResourceEventHandler,\n\ttransformer TransformFunc,\n) (Store, Controller) {\n\t// This will hold the client state, as we know it.\n\tclientState := NewStore(DeletionHandlingMetaNamespaceKeyFunc)\n\n\treturn clientState, newInformer(lw, objType, resyncPeriod, h, clientState, transformer)\n}","line":{"from":397,"to":415}} {"id":100028474,"name":"NewTransformingIndexerInformer","signature":"func NewTransformingIndexerInformer(","file":"staging/src/k8s.io/client-go/tools/cache/controller.go","code":"// NewTransformingIndexerInformer returns an Indexer and a controller for\n// populating the index while also providing event notifications. You should\n// only used the returned Index for Get/List operations; Add/Modify/Deletes\n// will cause the event notifications to be faulty.\n// The given transform function will be called on all objects before they will\n// be put into the Index and corresponding Add/Modify/Delete handlers will\n// be invoked for them.\nfunc NewTransformingIndexerInformer(\n\tlw ListerWatcher,\n\tobjType runtime.Object,\n\tresyncPeriod time.Duration,\n\th ResourceEventHandler,\n\tindexers Indexers,\n\ttransformer TransformFunc,\n) (Indexer, Controller) {\n\t// This will hold the client state, as we know it.\n\tclientState := NewIndexer(DeletionHandlingMetaNamespaceKeyFunc, indexers)\n\n\treturn clientState, newInformer(lw, objType, resyncPeriod, h, clientState, transformer)\n}","line":{"from":417,"to":436}} {"id":100028475,"name":"processDeltas","signature":"func processDeltas(","file":"staging/src/k8s.io/client-go/tools/cache/controller.go","code":"// Multiplexes updates in the form of a list of Deltas into a Store, and informs\n// a given handler of events OnUpdate, OnAdd, OnDelete\nfunc processDeltas(\n\t// Object which receives event notifications from the given deltas\n\thandler ResourceEventHandler,\n\tclientState Store,\n\tdeltas Deltas,\n\tisInInitialList bool,\n) error {\n\t// from oldest to newest\n\tfor _, d := range deltas {\n\t\tobj := d.Object\n\n\t\tswitch d.Type {\n\t\tcase Sync, Replaced, Added, Updated:\n\t\t\tif old, exists, err := clientState.Get(obj); err == nil \u0026\u0026 exists {\n\t\t\t\tif err := clientState.Update(obj); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\thandler.OnUpdate(old, obj)\n\t\t\t} else {\n\t\t\t\tif err := clientState.Add(obj); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\thandler.OnAdd(obj, isInInitialList)\n\t\t\t}\n\t\tcase Deleted:\n\t\t\tif err := clientState.Delete(obj); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thandler.OnDelete(obj)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":438,"to":472}} {"id":100028476,"name":"newInformer","signature":"func newInformer(","file":"staging/src/k8s.io/client-go/tools/cache/controller.go","code":"// newInformer returns a controller for populating the store while also\n// providing event notifications.\n//\n// Parameters\n// - lw is list and watch functions for the source of the resource you want to\n// be informed of.\n// - objType is an object of the type that you expect to receive.\n// - resyncPeriod: if non-zero, will re-list this often (you will get OnUpdate\n// calls, even if nothing changed). Otherwise, re-list will be delayed as\n// long as possible (until the upstream source closes the watch or times out,\n// or you stop the controller).\n// - h is the object you want notifications sent to.\n// - clientState is the store you want to populate\nfunc newInformer(\n\tlw ListerWatcher,\n\tobjType runtime.Object,\n\tresyncPeriod time.Duration,\n\th ResourceEventHandler,\n\tclientState Store,\n\ttransformer TransformFunc,\n) Controller {\n\t// This will hold incoming changes. Note how we pass clientState in as a\n\t// KeyLister, that way resync operations will result in the correct set\n\t// of update/delete deltas.\n\tfifo := NewDeltaFIFOWithOptions(DeltaFIFOOptions{\n\t\tKnownObjects: clientState,\n\t\tEmitDeltaTypeReplaced: true,\n\t\tTransformer: transformer,\n\t})\n\n\tcfg := \u0026Config{\n\t\tQueue: fifo,\n\t\tListerWatcher: lw,\n\t\tObjectType: objType,\n\t\tFullResyncPeriod: resyncPeriod,\n\t\tRetryOnError: false,\n\n\t\tProcess: func(obj interface{}, isInInitialList bool) error {\n\t\t\tif deltas, ok := obj.(Deltas); ok {\n\t\t\t\treturn processDeltas(h, clientState, deltas, isInInitialList)\n\t\t\t}\n\t\t\treturn errors.New(\"object given as Process argument is not Deltas\")\n\t\t},\n\t}\n\treturn New(cfg)\n}","line":{"from":474,"to":519}} {"id":100028477,"name":"NewDeltaFIFO","signature":"func NewDeltaFIFO(keyFunc KeyFunc, knownObjects KeyListerGetter) *DeltaFIFO","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"// NewDeltaFIFO returns a Queue which can be used to process changes to items.\n//\n// keyFunc is used to figure out what key an object should have. (It is\n// exposed in the returned DeltaFIFO's KeyOf() method, with additional handling\n// around deleted objects and queue state).\n//\n// 'knownObjects' may be supplied to modify the behavior of Delete,\n// Replace, and Resync. It may be nil if you do not need those\n// modifications.\n//\n// TODO: consider merging keyLister with this object, tracking a list of\n// \"known\" keys when Pop() is called. Have to think about how that\n// affects error retrying.\n//\n//\tNOTE: It is possible to misuse this and cause a race when using an\n//\texternal known object source.\n//\tWhether there is a potential race depends on how the consumer\n//\tmodifies knownObjects. In Pop(), process function is called under\n//\tlock, so it is safe to update data structures in it that need to be\n//\tin sync with the queue (e.g. knownObjects).\n//\n//\tExample:\n//\tIn case of sharedIndexInformer being a consumer\n//\t(https://github.com/kubernetes/kubernetes/blob/0cdd940f/staging/src/k8s.io/client-go/tools/cache/shared_informer.go#L192),\n//\tthere is no race as knownObjects (s.indexer) is modified safely\n//\tunder DeltaFIFO's lock. The only exceptions are GetStore() and\n//\tGetIndexer() methods, which expose ways to modify the underlying\n//\tstorage. Currently these two methods are used for creating Lister\n//\tand internal tests.\n//\n// Also see the comment on DeltaFIFO.\n//\n// Warning: This constructs a DeltaFIFO that does not differentiate between\n// events caused by a call to Replace (e.g., from a relist, which may\n// contain object updates), and synthetic events caused by a periodic resync\n// (which just emit the existing object). See https://issue.k8s.io/86015 for details.\n//\n// Use `NewDeltaFIFOWithOptions(DeltaFIFOOptions{..., EmitDeltaTypeReplaced: true})`\n// instead to receive a `Replaced` event depending on the type.\n//\n// Deprecated: Equivalent to NewDeltaFIFOWithOptions(DeltaFIFOOptions{KeyFunction: keyFunc, KnownObjects: knownObjects})\nfunc NewDeltaFIFO(keyFunc KeyFunc, knownObjects KeyListerGetter) *DeltaFIFO {\n\treturn NewDeltaFIFOWithOptions(DeltaFIFOOptions{\n\t\tKeyFunction: keyFunc,\n\t\tKnownObjects: knownObjects,\n\t})\n}","line":{"from":196,"to":242}} {"id":100028478,"name":"NewDeltaFIFOWithOptions","signature":"func NewDeltaFIFOWithOptions(opts DeltaFIFOOptions) *DeltaFIFO","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"// NewDeltaFIFOWithOptions returns a Queue which can be used to process changes to\n// items. See also the comment on DeltaFIFO.\nfunc NewDeltaFIFOWithOptions(opts DeltaFIFOOptions) *DeltaFIFO {\n\tif opts.KeyFunction == nil {\n\t\topts.KeyFunction = MetaNamespaceKeyFunc\n\t}\n\n\tf := \u0026DeltaFIFO{\n\t\titems: map[string]Deltas{},\n\t\tqueue: []string{},\n\t\tkeyFunc: opts.KeyFunction,\n\t\tknownObjects: opts.KnownObjects,\n\n\t\temitDeltaTypeReplaced: opts.EmitDeltaTypeReplaced,\n\t\ttransformer: opts.Transformer,\n\t}\n\tf.cond.L = \u0026f.lock\n\treturn f\n}","line":{"from":244,"to":262}} {"id":100028479,"name":"Close","signature":"func (f *DeltaFIFO) Close()","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"// Close the queue.\nfunc (f *DeltaFIFO) Close() {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\tf.closed = true\n\tf.cond.Broadcast()\n}","line":{"from":275,"to":281}} {"id":100028480,"name":"KeyOf","signature":"func (f *DeltaFIFO) KeyOf(obj interface{}) (string, error)","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"// KeyOf exposes f's keyFunc, but also detects the key of a Deltas object or\n// DeletedFinalStateUnknown objects.\nfunc (f *DeltaFIFO) KeyOf(obj interface{}) (string, error) {\n\tif d, ok := obj.(Deltas); ok {\n\t\tif len(d) == 0 {\n\t\t\treturn \"\", KeyError{obj, ErrZeroLengthDeltasObject}\n\t\t}\n\t\tobj = d.Newest().Object\n\t}\n\tif d, ok := obj.(DeletedFinalStateUnknown); ok {\n\t\treturn d.Key, nil\n\t}\n\treturn f.keyFunc(obj)\n}","line":{"from":283,"to":296}} {"id":100028481,"name":"HasSynced","signature":"func (f *DeltaFIFO) HasSynced() bool","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"// HasSynced returns true if an Add/Update/Delete/AddIfNotPresent are called first,\n// or the first batch of items inserted by Replace() has been popped.\nfunc (f *DeltaFIFO) HasSynced() bool {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\treturn f.hasSynced_locked()\n}","line":{"from":298,"to":304}} {"id":100028482,"name":"hasSynced_locked","signature":"func (f *DeltaFIFO) hasSynced_locked() bool","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"func (f *DeltaFIFO) hasSynced_locked() bool {\n\treturn f.populated \u0026\u0026 f.initialPopulationCount == 0\n}","line":{"from":306,"to":308}} {"id":100028483,"name":"Add","signature":"func (f *DeltaFIFO) Add(obj interface{}) error","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"// Add inserts an item, and puts it in the queue. The item is only enqueued\n// if it doesn't already exist in the set.\nfunc (f *DeltaFIFO) Add(obj interface{}) error {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\tf.populated = true\n\treturn f.queueActionLocked(Added, obj)\n}","line":{"from":310,"to":317}} {"id":100028484,"name":"Update","signature":"func (f *DeltaFIFO) Update(obj interface{}) error","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"// Update is just like Add, but makes an Updated Delta.\nfunc (f *DeltaFIFO) Update(obj interface{}) error {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\tf.populated = true\n\treturn f.queueActionLocked(Updated, obj)\n}","line":{"from":319,"to":325}} {"id":100028485,"name":"Delete","signature":"func (f *DeltaFIFO) Delete(obj interface{}) error","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"// Delete is just like Add, but makes a Deleted Delta. If the given\n// object does not already exist, it will be ignored. (It may have\n// already been deleted by a Replace (re-list), for example.) In this\n// method `f.knownObjects`, if not nil, provides (via GetByKey)\n// _additional_ objects that are considered to already exist.\nfunc (f *DeltaFIFO) Delete(obj interface{}) error {\n\tid, err := f.KeyOf(obj)\n\tif err != nil {\n\t\treturn KeyError{obj, err}\n\t}\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\tf.populated = true\n\tif f.knownObjects == nil {\n\t\tif _, exists := f.items[id]; !exists {\n\t\t\t// Presumably, this was deleted when a relist happened.\n\t\t\t// Don't provide a second report of the same deletion.\n\t\t\treturn nil\n\t\t}\n\t} else {\n\t\t// We only want to skip the \"deletion\" action if the object doesn't\n\t\t// exist in knownObjects and it doesn't have corresponding item in items.\n\t\t// Note that even if there is a \"deletion\" action in items, we can ignore it,\n\t\t// because it will be deduped automatically in \"queueActionLocked\"\n\t\t_, exists, err := f.knownObjects.GetByKey(id)\n\t\t_, itemsExist := f.items[id]\n\t\tif err == nil \u0026\u0026 !exists \u0026\u0026 !itemsExist {\n\t\t\t// Presumably, this was deleted when a relist happened.\n\t\t\t// Don't provide a second report of the same deletion.\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t// exist in items and/or KnownObjects\n\treturn f.queueActionLocked(Deleted, obj)\n}","line":{"from":327,"to":362}} {"id":100028486,"name":"AddIfNotPresent","signature":"func (f *DeltaFIFO) AddIfNotPresent(obj interface{}) error","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"// AddIfNotPresent inserts an item, and puts it in the queue. If the item is already\n// present in the set, it is neither enqueued nor added to the set.\n//\n// This is useful in a single producer/consumer scenario so that the consumer can\n// safely retry items without contending with the producer and potentially enqueueing\n// stale items.\n//\n// Important: obj must be a Deltas (the output of the Pop() function). Yes, this is\n// different from the Add/Update/Delete functions.\nfunc (f *DeltaFIFO) AddIfNotPresent(obj interface{}) error {\n\tdeltas, ok := obj.(Deltas)\n\tif !ok {\n\t\treturn fmt.Errorf(\"object must be of type deltas, but got: %#v\", obj)\n\t}\n\tid, err := f.KeyOf(deltas)\n\tif err != nil {\n\t\treturn KeyError{obj, err}\n\t}\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\tf.addIfNotPresent(id, deltas)\n\treturn nil\n}","line":{"from":364,"to":386}} {"id":100028487,"name":"addIfNotPresent","signature":"func (f *DeltaFIFO) addIfNotPresent(id string, deltas Deltas)","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"// addIfNotPresent inserts deltas under id if it does not exist, and assumes the caller\n// already holds the fifo lock.\nfunc (f *DeltaFIFO) addIfNotPresent(id string, deltas Deltas) {\n\tf.populated = true\n\tif _, exists := f.items[id]; exists {\n\t\treturn\n\t}\n\n\tf.queue = append(f.queue, id)\n\tf.items[id] = deltas\n\tf.cond.Broadcast()\n}","line":{"from":388,"to":399}} {"id":100028488,"name":"dedupDeltas","signature":"func dedupDeltas(deltas Deltas) Deltas","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"// re-listing and watching can deliver the same update multiple times in any\n// order. This will combine the most recent two deltas if they are the same.\nfunc dedupDeltas(deltas Deltas) Deltas {\n\tn := len(deltas)\n\tif n \u003c 2 {\n\t\treturn deltas\n\t}\n\ta := \u0026deltas[n-1]\n\tb := \u0026deltas[n-2]\n\tif out := isDup(a, b); out != nil {\n\t\tdeltas[n-2] = *out\n\t\treturn deltas[:n-1]\n\t}\n\treturn deltas\n}","line":{"from":401,"to":415}} {"id":100028489,"name":"isDup","signature":"func isDup(a, b *Delta) *Delta","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"// If a \u0026 b represent the same event, returns the delta that ought to be kept.\n// Otherwise, returns nil.\n// TODO: is there anything other than deletions that need deduping?\nfunc isDup(a, b *Delta) *Delta {\n\tif out := isDeletionDup(a, b); out != nil {\n\t\treturn out\n\t}\n\t// TODO: Detect other duplicate situations? Are there any?\n\treturn nil\n}","line":{"from":417,"to":426}} {"id":100028490,"name":"isDeletionDup","signature":"func isDeletionDup(a, b *Delta) *Delta","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"// keep the one with the most information if both are deletions.\nfunc isDeletionDup(a, b *Delta) *Delta {\n\tif b.Type != Deleted || a.Type != Deleted {\n\t\treturn nil\n\t}\n\t// Do more sophisticated checks, or is this sufficient?\n\tif _, ok := b.Object.(DeletedFinalStateUnknown); ok {\n\t\treturn a\n\t}\n\treturn b\n}","line":{"from":428,"to":438}} {"id":100028491,"name":"queueActionLocked","signature":"func (f *DeltaFIFO) queueActionLocked(actionType DeltaType, obj interface{}) error","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"// queueActionLocked appends to the delta list for the object.\n// Caller must lock first.\nfunc (f *DeltaFIFO) queueActionLocked(actionType DeltaType, obj interface{}) error {\n\tid, err := f.KeyOf(obj)\n\tif err != nil {\n\t\treturn KeyError{obj, err}\n\t}\n\n\t// Every object comes through this code path once, so this is a good\n\t// place to call the transform func. If obj is a\n\t// DeletedFinalStateUnknown tombstone, then the containted inner object\n\t// will already have gone through the transformer, but we document that\n\t// this can happen. In cases involving Replace(), such an object can\n\t// come through multiple times.\n\tif f.transformer != nil {\n\t\tvar err error\n\t\tobj, err = f.transformer(obj)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\toldDeltas := f.items[id]\n\tnewDeltas := append(oldDeltas, Delta{actionType, obj})\n\tnewDeltas = dedupDeltas(newDeltas)\n\n\tif len(newDeltas) \u003e 0 {\n\t\tif _, exists := f.items[id]; !exists {\n\t\t\tf.queue = append(f.queue, id)\n\t\t}\n\t\tf.items[id] = newDeltas\n\t\tf.cond.Broadcast()\n\t} else {\n\t\t// This never happens, because dedupDeltas never returns an empty list\n\t\t// when given a non-empty list (as it is here).\n\t\t// If somehow it happens anyway, deal with it but complain.\n\t\tif oldDeltas == nil {\n\t\t\tklog.Errorf(\"Impossible dedupDeltas for id=%q: oldDeltas=%#+v, obj=%#+v; ignoring\", id, oldDeltas, obj)\n\t\t\treturn nil\n\t\t}\n\t\tklog.Errorf(\"Impossible dedupDeltas for id=%q: oldDeltas=%#+v, obj=%#+v; breaking invariant by storing empty Deltas\", id, oldDeltas, obj)\n\t\tf.items[id] = newDeltas\n\t\treturn fmt.Errorf(\"Impossible dedupDeltas for id=%q: oldDeltas=%#+v, obj=%#+v; broke DeltaFIFO invariant by storing empty Deltas\", id, oldDeltas, obj)\n\t}\n\treturn nil\n}","line":{"from":440,"to":485}} {"id":100028492,"name":"List","signature":"func (f *DeltaFIFO) List() []interface{}","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"// List returns a list of all the items; it returns the object\n// from the most recent Delta.\n// You should treat the items returned inside the deltas as immutable.\nfunc (f *DeltaFIFO) List() []interface{} {\n\tf.lock.RLock()\n\tdefer f.lock.RUnlock()\n\treturn f.listLocked()\n}","line":{"from":487,"to":494}} {"id":100028493,"name":"listLocked","signature":"func (f *DeltaFIFO) listLocked() []interface{}","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"func (f *DeltaFIFO) listLocked() []interface{} {\n\tlist := make([]interface{}, 0, len(f.items))\n\tfor _, item := range f.items {\n\t\tlist = append(list, item.Newest().Object)\n\t}\n\treturn list\n}","line":{"from":496,"to":502}} {"id":100028494,"name":"ListKeys","signature":"func (f *DeltaFIFO) ListKeys() []string","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"// ListKeys returns a list of all the keys of the objects currently\n// in the FIFO.\nfunc (f *DeltaFIFO) ListKeys() []string {\n\tf.lock.RLock()\n\tdefer f.lock.RUnlock()\n\tlist := make([]string, 0, len(f.queue))\n\tfor _, key := range f.queue {\n\t\tlist = append(list, key)\n\t}\n\treturn list\n}","line":{"from":504,"to":514}} {"id":100028495,"name":"Get","signature":"func (f *DeltaFIFO) Get(obj interface{}) (item interface{}, exists bool, err error)","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"// Get returns the complete list of deltas for the requested item,\n// or sets exists=false.\n// You should treat the items returned inside the deltas as immutable.\nfunc (f *DeltaFIFO) Get(obj interface{}) (item interface{}, exists bool, err error) {\n\tkey, err := f.KeyOf(obj)\n\tif err != nil {\n\t\treturn nil, false, KeyError{obj, err}\n\t}\n\treturn f.GetByKey(key)\n}","line":{"from":516,"to":525}} {"id":100028496,"name":"GetByKey","signature":"func (f *DeltaFIFO) GetByKey(key string) (item interface{}, exists bool, err error)","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"// GetByKey returns the complete list of deltas for the requested item,\n// setting exists=false if that list is empty.\n// You should treat the items returned inside the deltas as immutable.\nfunc (f *DeltaFIFO) GetByKey(key string) (item interface{}, exists bool, err error) {\n\tf.lock.RLock()\n\tdefer f.lock.RUnlock()\n\td, exists := f.items[key]\n\tif exists {\n\t\t// Copy item's slice so operations on this slice\n\t\t// won't interfere with the object we return.\n\t\td = copyDeltas(d)\n\t}\n\treturn d, exists, nil\n}","line":{"from":527,"to":540}} {"id":100028497,"name":"IsClosed","signature":"func (f *DeltaFIFO) IsClosed() bool","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"// IsClosed checks if the queue is closed\nfunc (f *DeltaFIFO) IsClosed() bool {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\treturn f.closed\n}","line":{"from":542,"to":547}} {"id":100028498,"name":"Pop","signature":"func (f *DeltaFIFO) Pop(process PopProcessFunc) (interface{}, error)","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"// Pop blocks until the queue has some items, and then returns one. If\n// multiple items are ready, they are returned in the order in which they were\n// added/updated. The item is removed from the queue (and the store) before it\n// is returned, so if you don't successfully process it, you need to add it back\n// with AddIfNotPresent().\n// process function is called under lock, so it is safe to update data structures\n// in it that need to be in sync with the queue (e.g. knownKeys). The PopProcessFunc\n// may return an instance of ErrRequeue with a nested error to indicate the current\n// item should be requeued (equivalent to calling AddIfNotPresent under the lock).\n// process should avoid expensive I/O operation so that other queue operations, i.e.\n// Add() and Get(), won't be blocked for too long.\n//\n// Pop returns a 'Deltas', which has a complete list of all the things\n// that happened to the object (deltas) while it was sitting in the queue.\nfunc (f *DeltaFIFO) Pop(process PopProcessFunc) (interface{}, error) {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\tfor {\n\t\tfor len(f.queue) == 0 {\n\t\t\t// When the queue is empty, invocation of Pop() is blocked until new item is enqueued.\n\t\t\t// When Close() is called, the f.closed is set and the condition is broadcasted.\n\t\t\t// Which causes this loop to continue and return from the Pop().\n\t\t\tif f.closed {\n\t\t\t\treturn nil, ErrFIFOClosed\n\t\t\t}\n\n\t\t\tf.cond.Wait()\n\t\t}\n\t\tisInInitialList := !f.hasSynced_locked()\n\t\tid := f.queue[0]\n\t\tf.queue = f.queue[1:]\n\t\tdepth := len(f.queue)\n\t\tif f.initialPopulationCount \u003e 0 {\n\t\t\tf.initialPopulationCount--\n\t\t}\n\t\titem, ok := f.items[id]\n\t\tif !ok {\n\t\t\t// This should never happen\n\t\t\tklog.Errorf(\"Inconceivable! %q was in f.queue but not f.items; ignoring.\", id)\n\t\t\tcontinue\n\t\t}\n\t\tdelete(f.items, id)\n\t\t// Only log traces if the queue depth is greater than 10 and it takes more than\n\t\t// 100 milliseconds to process one item from the queue.\n\t\t// Queue depth never goes high because processing an item is locking the queue,\n\t\t// and new items can't be added until processing finish.\n\t\t// https://github.com/kubernetes/kubernetes/issues/103789\n\t\tif depth \u003e 10 {\n\t\t\ttrace := utiltrace.New(\"DeltaFIFO Pop Process\",\n\t\t\t\tutiltrace.Field{Key: \"ID\", Value: id},\n\t\t\t\tutiltrace.Field{Key: \"Depth\", Value: depth},\n\t\t\t\tutiltrace.Field{Key: \"Reason\", Value: \"slow event handlers blocking the queue\"})\n\t\t\tdefer trace.LogIfLong(100 * time.Millisecond)\n\t\t}\n\t\terr := process(item, isInInitialList)\n\t\tif e, ok := err.(ErrRequeue); ok {\n\t\t\tf.addIfNotPresent(id, item)\n\t\t\terr = e.Err\n\t\t}\n\t\t// Don't need to copyDeltas here, because we're transferring\n\t\t// ownership to the caller.\n\t\treturn item, err\n\t}\n}","line":{"from":549,"to":612}} {"id":100028499,"name":"Replace","signature":"func (f *DeltaFIFO) Replace(list []interface{}, _ string) error","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"// Replace atomically does two things: (1) it adds the given objects\n// using the Sync or Replace DeltaType and then (2) it does some deletions.\n// In particular: for every pre-existing key K that is not the key of\n// an object in `list` there is the effect of\n// `Delete(DeletedFinalStateUnknown{K, O})` where O is the latest known\n// object of K. The pre-existing keys are those in the union set of the keys in\n// `f.items` and `f.knownObjects` (if not nil). The last known object for key K is\n// the one present in the last delta in `f.items`. If there is no delta for K\n// in `f.items`, it is the object in `f.knownObjects`\nfunc (f *DeltaFIFO) Replace(list []interface{}, _ string) error {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\tkeys := make(sets.String, len(list))\n\n\t// keep backwards compat for old clients\n\taction := Sync\n\tif f.emitDeltaTypeReplaced {\n\t\taction = Replaced\n\t}\n\n\t// Add Sync/Replaced action for each new item.\n\tfor _, item := range list {\n\t\tkey, err := f.KeyOf(item)\n\t\tif err != nil {\n\t\t\treturn KeyError{item, err}\n\t\t}\n\t\tkeys.Insert(key)\n\t\tif err := f.queueActionLocked(action, item); err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't enqueue object: %v\", err)\n\t\t}\n\t}\n\n\t// Do deletion detection against objects in the queue\n\tqueuedDeletions := 0\n\tfor k, oldItem := range f.items {\n\t\tif keys.Has(k) {\n\t\t\tcontinue\n\t\t}\n\t\t// Delete pre-existing items not in the new list.\n\t\t// This could happen if watch deletion event was missed while\n\t\t// disconnected from apiserver.\n\t\tvar deletedObj interface{}\n\t\tif n := oldItem.Newest(); n != nil {\n\t\t\tdeletedObj = n.Object\n\n\t\t\t// if the previous object is a DeletedFinalStateUnknown, we have to extract the actual Object\n\t\t\tif d, ok := deletedObj.(DeletedFinalStateUnknown); ok {\n\t\t\t\tdeletedObj = d.Obj\n\t\t\t}\n\t\t}\n\t\tqueuedDeletions++\n\t\tif err := f.queueActionLocked(Deleted, DeletedFinalStateUnknown{k, deletedObj}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif f.knownObjects != nil {\n\t\t// Detect deletions for objects not present in the queue, but present in KnownObjects\n\t\tknownKeys := f.knownObjects.ListKeys()\n\t\tfor _, k := range knownKeys {\n\t\t\tif keys.Has(k) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(f.items[k]) \u003e 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tdeletedObj, exists, err := f.knownObjects.GetByKey(k)\n\t\t\tif err != nil {\n\t\t\t\tdeletedObj = nil\n\t\t\t\tklog.Errorf(\"Unexpected error %v during lookup of key %v, placing DeleteFinalStateUnknown marker without object\", err, k)\n\t\t\t} else if !exists {\n\t\t\t\tdeletedObj = nil\n\t\t\t\tklog.Infof(\"Key %v does not exist in known objects store, placing DeleteFinalStateUnknown marker without object\", k)\n\t\t\t}\n\t\t\tqueuedDeletions++\n\t\t\tif err := f.queueActionLocked(Deleted, DeletedFinalStateUnknown{k, deletedObj}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tif !f.populated {\n\t\tf.populated = true\n\t\tf.initialPopulationCount = keys.Len() + queuedDeletions\n\t}\n\n\treturn nil\n}","line":{"from":614,"to":702}} {"id":100028500,"name":"Resync","signature":"func (f *DeltaFIFO) Resync() error","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"// Resync adds, with a Sync type of Delta, every object listed by\n// `f.knownObjects` whose key is not already queued for processing.\n// If `f.knownObjects` is `nil` then Resync does nothing.\nfunc (f *DeltaFIFO) Resync() error {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\n\tif f.knownObjects == nil {\n\t\treturn nil\n\t}\n\n\tkeys := f.knownObjects.ListKeys()\n\tfor _, k := range keys {\n\t\tif err := f.syncKeyLocked(k); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":704,"to":722}} {"id":100028501,"name":"syncKeyLocked","signature":"func (f *DeltaFIFO) syncKeyLocked(key string) error","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"func (f *DeltaFIFO) syncKeyLocked(key string) error {\n\tobj, exists, err := f.knownObjects.GetByKey(key)\n\tif err != nil {\n\t\tklog.Errorf(\"Unexpected error %v during lookup of key %v, unable to queue object for sync\", err, key)\n\t\treturn nil\n\t} else if !exists {\n\t\tklog.Infof(\"Key %v does not exist in known objects store, unable to queue object for sync\", key)\n\t\treturn nil\n\t}\n\n\t// If we are doing Resync() and there is already an event queued for that object,\n\t// we ignore the Resync for it. This is to avoid the race, in which the resync\n\t// comes with the previous value of object (since queueing an event for the object\n\t// doesn't trigger changing the underlying store \u003cknownObjects\u003e.\n\tid, err := f.KeyOf(obj)\n\tif err != nil {\n\t\treturn KeyError{obj, err}\n\t}\n\tif len(f.items[id]) \u003e 0 {\n\t\treturn nil\n\t}\n\n\tif err := f.queueActionLocked(Sync, obj); err != nil {\n\t\treturn fmt.Errorf(\"couldn't queue object: %v\", err)\n\t}\n\treturn nil\n}","line":{"from":724,"to":750}} {"id":100028502,"name":"Oldest","signature":"func (d Deltas) Oldest() *Delta","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"// Oldest is a convenience function that returns the oldest delta, or\n// nil if there are no deltas.\nfunc (d Deltas) Oldest() *Delta {\n\tif len(d) \u003e 0 {\n\t\treturn \u0026d[0]\n\t}\n\treturn nil\n}","line":{"from":769,"to":776}} {"id":100028503,"name":"Newest","signature":"func (d Deltas) Newest() *Delta","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"// Newest is a convenience function that returns the newest delta, or\n// nil if there are no deltas.\nfunc (d Deltas) Newest() *Delta {\n\tif n := len(d); n \u003e 0 {\n\t\treturn \u0026d[n-1]\n\t}\n\treturn nil\n}","line":{"from":778,"to":785}} {"id":100028504,"name":"copyDeltas","signature":"func copyDeltas(d Deltas) Deltas","file":"staging/src/k8s.io/client-go/tools/cache/delta_fifo.go","code":"// copyDeltas returns a shallow copy of d; that is, it copies the slice but not\n// the objects in the slice. This allows Get/List to return an object that we\n// know won't be clobbered by a subsequent modifications.\nfunc copyDeltas(d Deltas) Deltas {\n\td2 := make(Deltas, len(d))\n\tcopy(d2, d)\n\treturn d2\n}","line":{"from":787,"to":794}} {"id":100028505,"name":"IsExpired","signature":"func (p *TTLPolicy) IsExpired(obj *TimestampedEntry) bool","file":"staging/src/k8s.io/client-go/tools/cache/expiration_cache.go","code":"// IsExpired returns true if the given object is older than the ttl, or it can't\n// determine its age.\nfunc (p *TTLPolicy) IsExpired(obj *TimestampedEntry) bool {\n\treturn p.TTL \u003e 0 \u0026\u0026 p.Clock.Since(obj.Timestamp) \u003e p.TTL\n}","line":{"from":64,"to":68}} {"id":100028506,"name":"getTimestampedEntry","signature":"func (c *ExpirationCache) getTimestampedEntry(key string) (*TimestampedEntry, bool)","file":"staging/src/k8s.io/client-go/tools/cache/expiration_cache.go","code":"// getTimestampedEntry returns the TimestampedEntry stored under the given key.\nfunc (c *ExpirationCache) getTimestampedEntry(key string) (*TimestampedEntry, bool) {\n\titem, _ := c.cacheStorage.Get(key)\n\tif tsEntry, ok := item.(*TimestampedEntry); ok {\n\t\treturn tsEntry, true\n\t}\n\treturn nil, false\n}","line":{"from":80,"to":87}} {"id":100028507,"name":"getOrExpire","signature":"func (c *ExpirationCache) getOrExpire(key string) (interface{}, bool)","file":"staging/src/k8s.io/client-go/tools/cache/expiration_cache.go","code":"// getOrExpire retrieves the object from the TimestampedEntry if and only if it hasn't\n// already expired. It holds a write lock across deletion.\nfunc (c *ExpirationCache) getOrExpire(key string) (interface{}, bool) {\n\t// Prevent all inserts from the time we deem an item as \"expired\" to when we\n\t// delete it, so an un-expired item doesn't sneak in under the same key, just\n\t// before the Delete.\n\tc.expirationLock.Lock()\n\tdefer c.expirationLock.Unlock()\n\ttimestampedItem, exists := c.getTimestampedEntry(key)\n\tif !exists {\n\t\treturn nil, false\n\t}\n\tif c.expirationPolicy.IsExpired(timestampedItem) {\n\t\tc.cacheStorage.Delete(key)\n\t\treturn nil, false\n\t}\n\treturn timestampedItem.Obj, true\n}","line":{"from":89,"to":106}} {"id":100028508,"name":"GetByKey","signature":"func (c *ExpirationCache) GetByKey(key string) (interface{}, bool, error)","file":"staging/src/k8s.io/client-go/tools/cache/expiration_cache.go","code":"// GetByKey returns the item stored under the key, or sets exists=false.\nfunc (c *ExpirationCache) GetByKey(key string) (interface{}, bool, error) {\n\tobj, exists := c.getOrExpire(key)\n\treturn obj, exists, nil\n}","line":{"from":108,"to":112}} {"id":100028509,"name":"Get","signature":"func (c *ExpirationCache) Get(obj interface{}) (interface{}, bool, error)","file":"staging/src/k8s.io/client-go/tools/cache/expiration_cache.go","code":"// Get returns unexpired items. It purges the cache of expired items in the\n// process.\nfunc (c *ExpirationCache) Get(obj interface{}) (interface{}, bool, error) {\n\tkey, err := c.keyFunc(obj)\n\tif err != nil {\n\t\treturn nil, false, KeyError{obj, err}\n\t}\n\tobj, exists := c.getOrExpire(key)\n\treturn obj, exists, nil\n}","line":{"from":114,"to":123}} {"id":100028510,"name":"List","signature":"func (c *ExpirationCache) List() []interface{}","file":"staging/src/k8s.io/client-go/tools/cache/expiration_cache.go","code":"// List retrieves a list of unexpired items. It purges the cache of expired\n// items in the process.\nfunc (c *ExpirationCache) List() []interface{} {\n\titems := c.cacheStorage.List()\n\n\tlist := make([]interface{}, 0, len(items))\n\tfor _, item := range items {\n\t\tkey := item.(*TimestampedEntry).key\n\t\tif obj, exists := c.getOrExpire(key); exists {\n\t\t\tlist = append(list, obj)\n\t\t}\n\t}\n\treturn list\n}","line":{"from":125,"to":138}} {"id":100028511,"name":"ListKeys","signature":"func (c *ExpirationCache) ListKeys() []string","file":"staging/src/k8s.io/client-go/tools/cache/expiration_cache.go","code":"// ListKeys returns a list of all keys in the expiration cache.\nfunc (c *ExpirationCache) ListKeys() []string {\n\treturn c.cacheStorage.ListKeys()\n}","line":{"from":140,"to":143}} {"id":100028512,"name":"Add","signature":"func (c *ExpirationCache) Add(obj interface{}) error","file":"staging/src/k8s.io/client-go/tools/cache/expiration_cache.go","code":"// Add timestamps an item and inserts it into the cache, overwriting entries\n// that might exist under the same key.\nfunc (c *ExpirationCache) Add(obj interface{}) error {\n\tkey, err := c.keyFunc(obj)\n\tif err != nil {\n\t\treturn KeyError{obj, err}\n\t}\n\tc.expirationLock.Lock()\n\tdefer c.expirationLock.Unlock()\n\n\tc.cacheStorage.Add(key, \u0026TimestampedEntry{obj, c.clock.Now(), key})\n\treturn nil\n}","line":{"from":145,"to":157}} {"id":100028513,"name":"Update","signature":"func (c *ExpirationCache) Update(obj interface{}) error","file":"staging/src/k8s.io/client-go/tools/cache/expiration_cache.go","code":"// Update has not been implemented yet for lack of a use case, so this method\n// simply calls `Add`. This effectively refreshes the timestamp.\nfunc (c *ExpirationCache) Update(obj interface{}) error {\n\treturn c.Add(obj)\n}","line":{"from":159,"to":163}} {"id":100028514,"name":"Delete","signature":"func (c *ExpirationCache) Delete(obj interface{}) error","file":"staging/src/k8s.io/client-go/tools/cache/expiration_cache.go","code":"// Delete removes an item from the cache.\nfunc (c *ExpirationCache) Delete(obj interface{}) error {\n\tkey, err := c.keyFunc(obj)\n\tif err != nil {\n\t\treturn KeyError{obj, err}\n\t}\n\tc.expirationLock.Lock()\n\tdefer c.expirationLock.Unlock()\n\tc.cacheStorage.Delete(key)\n\treturn nil\n}","line":{"from":165,"to":175}} {"id":100028515,"name":"Replace","signature":"func (c *ExpirationCache) Replace(list []interface{}, resourceVersion string) error","file":"staging/src/k8s.io/client-go/tools/cache/expiration_cache.go","code":"// Replace will convert all items in the given list to TimestampedEntries\n// before attempting the replace operation. The replace operation will\n// delete the contents of the ExpirationCache `c`.\nfunc (c *ExpirationCache) Replace(list []interface{}, resourceVersion string) error {\n\titems := make(map[string]interface{}, len(list))\n\tts := c.clock.Now()\n\tfor _, item := range list {\n\t\tkey, err := c.keyFunc(item)\n\t\tif err != nil {\n\t\t\treturn KeyError{item, err}\n\t\t}\n\t\titems[key] = \u0026TimestampedEntry{item, ts, key}\n\t}\n\tc.expirationLock.Lock()\n\tdefer c.expirationLock.Unlock()\n\tc.cacheStorage.Replace(items, resourceVersion)\n\treturn nil\n}","line":{"from":177,"to":194}} {"id":100028516,"name":"Resync","signature":"func (c *ExpirationCache) Resync() error","file":"staging/src/k8s.io/client-go/tools/cache/expiration_cache.go","code":"// Resync is a no-op for one of these\nfunc (c *ExpirationCache) Resync() error {\n\treturn nil\n}","line":{"from":196,"to":199}} {"id":100028517,"name":"NewTTLStore","signature":"func NewTTLStore(keyFunc KeyFunc, ttl time.Duration) Store","file":"staging/src/k8s.io/client-go/tools/cache/expiration_cache.go","code":"// NewTTLStore creates and returns a ExpirationCache with a TTLPolicy\nfunc NewTTLStore(keyFunc KeyFunc, ttl time.Duration) Store {\n\treturn NewExpirationStore(keyFunc, \u0026TTLPolicy{ttl, clock.RealClock{}})\n}","line":{"from":201,"to":204}} {"id":100028518,"name":"NewExpirationStore","signature":"func NewExpirationStore(keyFunc KeyFunc, expirationPolicy ExpirationPolicy) Store","file":"staging/src/k8s.io/client-go/tools/cache/expiration_cache.go","code":"// NewExpirationStore creates and returns a ExpirationCache for a given policy\nfunc NewExpirationStore(keyFunc KeyFunc, expirationPolicy ExpirationPolicy) Store {\n\treturn \u0026ExpirationCache{\n\t\tcacheStorage: NewThreadSafeStore(Indexers{}, Indices{}),\n\t\tkeyFunc: keyFunc,\n\t\tclock: clock.RealClock{},\n\t\texpirationPolicy: expirationPolicy,\n\t}\n}","line":{"from":206,"to":214}} {"id":100028519,"name":"Error","signature":"func (e ErrRequeue) Error() string","file":"staging/src/k8s.io/client-go/tools/cache/fifo.go","code":"func (e ErrRequeue) Error() string {\n\tif e.Err == nil {\n\t\treturn \"the popped item should be requeued without returning an error\"\n\t}\n\treturn e.Err.Error()\n}","line":{"from":40,"to":45}} {"id":100028520,"name":"Pop","signature":"func Pop(queue Queue) interface{}","file":"staging/src/k8s.io/client-go/tools/cache/fifo.go","code":"// Pop is helper function for popping from Queue.\n// WARNING: Do NOT use this function in non-test code to avoid races\n// unless you really really really really know what you are doing.\n//\n// NOTE: This function is deprecated and may be removed in the future without\n// additional warning.\nfunc Pop(queue Queue) interface{} {\n\tvar result interface{}\n\tqueue.Pop(func(obj interface{}, isInInitialList bool) error {\n\t\tresult = obj\n\t\treturn nil\n\t})\n\treturn result\n}","line":{"from":82,"to":95}} {"id":100028521,"name":"Close","signature":"func (f *FIFO) Close()","file":"staging/src/k8s.io/client-go/tools/cache/fifo.go","code":"// Close the queue.\nfunc (f *FIFO) Close() {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\tf.closed = true\n\tf.cond.Broadcast()\n}","line":{"from":142,"to":148}} {"id":100028522,"name":"HasSynced","signature":"func (f *FIFO) HasSynced() bool","file":"staging/src/k8s.io/client-go/tools/cache/fifo.go","code":"// HasSynced returns true if an Add/Update/Delete/AddIfNotPresent are called first,\n// or the first batch of items inserted by Replace() has been popped.\nfunc (f *FIFO) HasSynced() bool {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\treturn f.hasSynced_locked()\n}","line":{"from":150,"to":156}} {"id":100028523,"name":"hasSynced_locked","signature":"func (f *FIFO) hasSynced_locked() bool","file":"staging/src/k8s.io/client-go/tools/cache/fifo.go","code":"func (f *FIFO) hasSynced_locked() bool {\n\treturn f.populated \u0026\u0026 f.initialPopulationCount == 0\n}","line":{"from":158,"to":160}} {"id":100028524,"name":"Add","signature":"func (f *FIFO) Add(obj interface{}) error","file":"staging/src/k8s.io/client-go/tools/cache/fifo.go","code":"// Add inserts an item, and puts it in the queue. The item is only enqueued\n// if it doesn't already exist in the set.\nfunc (f *FIFO) Add(obj interface{}) error {\n\tid, err := f.keyFunc(obj)\n\tif err != nil {\n\t\treturn KeyError{obj, err}\n\t}\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\tf.populated = true\n\tif _, exists := f.items[id]; !exists {\n\t\tf.queue = append(f.queue, id)\n\t}\n\tf.items[id] = obj\n\tf.cond.Broadcast()\n\treturn nil\n}","line":{"from":162,"to":178}} {"id":100028525,"name":"AddIfNotPresent","signature":"func (f *FIFO) AddIfNotPresent(obj interface{}) error","file":"staging/src/k8s.io/client-go/tools/cache/fifo.go","code":"// AddIfNotPresent inserts an item, and puts it in the queue. If the item is already\n// present in the set, it is neither enqueued nor added to the set.\n//\n// This is useful in a single producer/consumer scenario so that the consumer can\n// safely retry items without contending with the producer and potentially enqueueing\n// stale items.\nfunc (f *FIFO) AddIfNotPresent(obj interface{}) error {\n\tid, err := f.keyFunc(obj)\n\tif err != nil {\n\t\treturn KeyError{obj, err}\n\t}\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\tf.addIfNotPresent(id, obj)\n\treturn nil\n}","line":{"from":180,"to":195}} {"id":100028526,"name":"addIfNotPresent","signature":"func (f *FIFO) addIfNotPresent(id string, obj interface{})","file":"staging/src/k8s.io/client-go/tools/cache/fifo.go","code":"// addIfNotPresent assumes the fifo lock is already held and adds the provided\n// item to the queue under id if it does not already exist.\nfunc (f *FIFO) addIfNotPresent(id string, obj interface{}) {\n\tf.populated = true\n\tif _, exists := f.items[id]; exists {\n\t\treturn\n\t}\n\n\tf.queue = append(f.queue, id)\n\tf.items[id] = obj\n\tf.cond.Broadcast()\n}","line":{"from":197,"to":208}} {"id":100028527,"name":"Update","signature":"func (f *FIFO) Update(obj interface{}) error","file":"staging/src/k8s.io/client-go/tools/cache/fifo.go","code":"// Update is the same as Add in this implementation.\nfunc (f *FIFO) Update(obj interface{}) error {\n\treturn f.Add(obj)\n}","line":{"from":210,"to":213}} {"id":100028528,"name":"Delete","signature":"func (f *FIFO) Delete(obj interface{}) error","file":"staging/src/k8s.io/client-go/tools/cache/fifo.go","code":"// Delete removes an item. It doesn't add it to the queue, because\n// this implementation assumes the consumer only cares about the objects,\n// not the order in which they were created/added.\nfunc (f *FIFO) Delete(obj interface{}) error {\n\tid, err := f.keyFunc(obj)\n\tif err != nil {\n\t\treturn KeyError{obj, err}\n\t}\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\tf.populated = true\n\tdelete(f.items, id)\n\treturn err\n}","line":{"from":215,"to":228}} {"id":100028529,"name":"List","signature":"func (f *FIFO) List() []interface{}","file":"staging/src/k8s.io/client-go/tools/cache/fifo.go","code":"// List returns a list of all the items.\nfunc (f *FIFO) List() []interface{} {\n\tf.lock.RLock()\n\tdefer f.lock.RUnlock()\n\tlist := make([]interface{}, 0, len(f.items))\n\tfor _, item := range f.items {\n\t\tlist = append(list, item)\n\t}\n\treturn list\n}","line":{"from":230,"to":239}} {"id":100028530,"name":"ListKeys","signature":"func (f *FIFO) ListKeys() []string","file":"staging/src/k8s.io/client-go/tools/cache/fifo.go","code":"// ListKeys returns a list of all the keys of the objects currently\n// in the FIFO.\nfunc (f *FIFO) ListKeys() []string {\n\tf.lock.RLock()\n\tdefer f.lock.RUnlock()\n\tlist := make([]string, 0, len(f.items))\n\tfor key := range f.items {\n\t\tlist = append(list, key)\n\t}\n\treturn list\n}","line":{"from":241,"to":251}} {"id":100028531,"name":"Get","signature":"func (f *FIFO) Get(obj interface{}) (item interface{}, exists bool, err error)","file":"staging/src/k8s.io/client-go/tools/cache/fifo.go","code":"// Get returns the requested item, or sets exists=false.\nfunc (f *FIFO) Get(obj interface{}) (item interface{}, exists bool, err error) {\n\tkey, err := f.keyFunc(obj)\n\tif err != nil {\n\t\treturn nil, false, KeyError{obj, err}\n\t}\n\treturn f.GetByKey(key)\n}","line":{"from":253,"to":260}} {"id":100028532,"name":"GetByKey","signature":"func (f *FIFO) GetByKey(key string) (item interface{}, exists bool, err error)","file":"staging/src/k8s.io/client-go/tools/cache/fifo.go","code":"// GetByKey returns the requested item, or sets exists=false.\nfunc (f *FIFO) GetByKey(key string) (item interface{}, exists bool, err error) {\n\tf.lock.RLock()\n\tdefer f.lock.RUnlock()\n\titem, exists = f.items[key]\n\treturn item, exists, nil\n}","line":{"from":262,"to":268}} {"id":100028533,"name":"IsClosed","signature":"func (f *FIFO) IsClosed() bool","file":"staging/src/k8s.io/client-go/tools/cache/fifo.go","code":"// IsClosed checks if the queue is closed\nfunc (f *FIFO) IsClosed() bool {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\treturn f.closed\n}","line":{"from":270,"to":275}} {"id":100028534,"name":"Pop","signature":"func (f *FIFO) Pop(process PopProcessFunc) (interface{}, error)","file":"staging/src/k8s.io/client-go/tools/cache/fifo.go","code":"// Pop waits until an item is ready and processes it. If multiple items are\n// ready, they are returned in the order in which they were added/updated.\n// The item is removed from the queue (and the store) before it is processed,\n// so if you don't successfully process it, it should be added back with\n// AddIfNotPresent(). process function is called under lock, so it is safe\n// update data structures in it that need to be in sync with the queue.\nfunc (f *FIFO) Pop(process PopProcessFunc) (interface{}, error) {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\tfor {\n\t\tfor len(f.queue) == 0 {\n\t\t\t// When the queue is empty, invocation of Pop() is blocked until new item is enqueued.\n\t\t\t// When Close() is called, the f.closed is set and the condition is broadcasted.\n\t\t\t// Which causes this loop to continue and return from the Pop().\n\t\t\tif f.closed {\n\t\t\t\treturn nil, ErrFIFOClosed\n\t\t\t}\n\n\t\t\tf.cond.Wait()\n\t\t}\n\t\tisInInitialList := !f.hasSynced_locked()\n\t\tid := f.queue[0]\n\t\tf.queue = f.queue[1:]\n\t\tif f.initialPopulationCount \u003e 0 {\n\t\t\tf.initialPopulationCount--\n\t\t}\n\t\titem, ok := f.items[id]\n\t\tif !ok {\n\t\t\t// Item may have been deleted subsequently.\n\t\t\tcontinue\n\t\t}\n\t\tdelete(f.items, id)\n\t\terr := process(item, isInInitialList)\n\t\tif e, ok := err.(ErrRequeue); ok {\n\t\t\tf.addIfNotPresent(id, item)\n\t\t\terr = e.Err\n\t\t}\n\t\treturn item, err\n\t}\n}","line":{"from":277,"to":316}} {"id":100028535,"name":"Replace","signature":"func (f *FIFO) Replace(list []interface{}, resourceVersion string) error","file":"staging/src/k8s.io/client-go/tools/cache/fifo.go","code":"// Replace will delete the contents of 'f', using instead the given map.\n// 'f' takes ownership of the map, you should not reference the map again\n// after calling this function. f's queue is reset, too; upon return, it\n// will contain the items in the map, in no particular order.\nfunc (f *FIFO) Replace(list []interface{}, resourceVersion string) error {\n\titems := make(map[string]interface{}, len(list))\n\tfor _, item := range list {\n\t\tkey, err := f.keyFunc(item)\n\t\tif err != nil {\n\t\t\treturn KeyError{item, err}\n\t\t}\n\t\titems[key] = item\n\t}\n\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\n\tif !f.populated {\n\t\tf.populated = true\n\t\tf.initialPopulationCount = len(items)\n\t}\n\n\tf.items = items\n\tf.queue = f.queue[:0]\n\tfor id := range items {\n\t\tf.queue = append(f.queue, id)\n\t}\n\tif len(f.queue) \u003e 0 {\n\t\tf.cond.Broadcast()\n\t}\n\treturn nil\n}","line":{"from":318,"to":349}} {"id":100028536,"name":"Resync","signature":"func (f *FIFO) Resync() error","file":"staging/src/k8s.io/client-go/tools/cache/fifo.go","code":"// Resync will ensure that every object in the Store has its key in the queue.\n// This should be a no-op, because that property is maintained by all operations.\nfunc (f *FIFO) Resync() error {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\n\tinQueue := sets.NewString()\n\tfor _, id := range f.queue {\n\t\tinQueue.Insert(id)\n\t}\n\tfor id := range f.items {\n\t\tif !inQueue.Has(id) {\n\t\t\tf.queue = append(f.queue, id)\n\t\t}\n\t}\n\tif len(f.queue) \u003e 0 {\n\t\tf.cond.Broadcast()\n\t}\n\treturn nil\n}","line":{"from":351,"to":370}} {"id":100028537,"name":"NewFIFO","signature":"func NewFIFO(keyFunc KeyFunc) *FIFO","file":"staging/src/k8s.io/client-go/tools/cache/fifo.go","code":"// NewFIFO returns a Store which can be used to queue up items to\n// process.\nfunc NewFIFO(keyFunc KeyFunc) *FIFO {\n\tf := \u0026FIFO{\n\t\titems: map[string]interface{}{},\n\t\tqueue: []string{},\n\t\tkeyFunc: keyFunc,\n\t}\n\tf.cond.L = \u0026f.lock\n\treturn f\n}","line":{"from":372,"to":382}} {"id":100028538,"name":"Less","signature":"func (h *heapData) Less(i, j int) bool","file":"staging/src/k8s.io/client-go/tools/cache/heap.go","code":"// Less compares two objects and returns true if the first one should go\n// in front of the second one in the heap.\nfunc (h *heapData) Less(i, j int) bool {\n\tif i \u003e len(h.queue) || j \u003e len(h.queue) {\n\t\treturn false\n\t}\n\titemi, ok := h.items[h.queue[i]]\n\tif !ok {\n\t\treturn false\n\t}\n\titemj, ok := h.items[h.queue[j]]\n\tif !ok {\n\t\treturn false\n\t}\n\treturn h.lessFunc(itemi.obj, itemj.obj)\n}","line":{"from":66,"to":81}} {"id":100028539,"name":"Len","signature":"func (h *heapData) Len() int { return len(h.queue) }","file":"staging/src/k8s.io/client-go/tools/cache/heap.go","code":"// Len returns the number of items in the Heap.\nfunc (h *heapData) Len() int { return len(h.queue) }","line":{"from":83,"to":84}} {"id":100028540,"name":"Swap","signature":"func (h *heapData) Swap(i, j int)","file":"staging/src/k8s.io/client-go/tools/cache/heap.go","code":"// Swap implements swapping of two elements in the heap. This is a part of standard\n// heap interface and should never be called directly.\nfunc (h *heapData) Swap(i, j int) {\n\th.queue[i], h.queue[j] = h.queue[j], h.queue[i]\n\titem := h.items[h.queue[i]]\n\titem.index = i\n\titem = h.items[h.queue[j]]\n\titem.index = j\n}","line":{"from":86,"to":94}} {"id":100028541,"name":"Push","signature":"func (h *heapData) Push(kv interface{})","file":"staging/src/k8s.io/client-go/tools/cache/heap.go","code":"// Push is supposed to be called by heap.Push only.\nfunc (h *heapData) Push(kv interface{}) {\n\tkeyValue := kv.(*itemKeyValue)\n\tn := len(h.queue)\n\th.items[keyValue.key] = \u0026heapItem{keyValue.obj, n}\n\th.queue = append(h.queue, keyValue.key)\n}","line":{"from":96,"to":102}} {"id":100028542,"name":"Pop","signature":"func (h *heapData) Pop() interface{}","file":"staging/src/k8s.io/client-go/tools/cache/heap.go","code":"// Pop is supposed to be called by heap.Pop only.\nfunc (h *heapData) Pop() interface{} {\n\tkey := h.queue[len(h.queue)-1]\n\th.queue = h.queue[0 : len(h.queue)-1]\n\titem, ok := h.items[key]\n\tif !ok {\n\t\t// This is an error\n\t\treturn nil\n\t}\n\tdelete(h.items, key)\n\treturn item.obj\n}","line":{"from":104,"to":115}} {"id":100028543,"name":"Close","signature":"func (h *Heap) Close()","file":"staging/src/k8s.io/client-go/tools/cache/heap.go","code":"// Close the Heap and signals condition variables that may be waiting to pop\n// items from the heap.\nfunc (h *Heap) Close() {\n\th.lock.Lock()\n\tdefer h.lock.Unlock()\n\th.closed = true\n\th.cond.Broadcast()\n}","line":{"from":132,"to":139}} {"id":100028544,"name":"Add","signature":"func (h *Heap) Add(obj interface{}) error","file":"staging/src/k8s.io/client-go/tools/cache/heap.go","code":"// Add inserts an item, and puts it in the queue. The item is updated if it\n// already exists.\nfunc (h *Heap) Add(obj interface{}) error {\n\tkey, err := h.data.keyFunc(obj)\n\tif err != nil {\n\t\treturn KeyError{obj, err}\n\t}\n\th.lock.Lock()\n\tdefer h.lock.Unlock()\n\tif h.closed {\n\t\treturn fmt.Errorf(closedMsg)\n\t}\n\tif _, exists := h.data.items[key]; exists {\n\t\th.data.items[key].obj = obj\n\t\theap.Fix(h.data, h.data.items[key].index)\n\t} else {\n\t\th.addIfNotPresentLocked(key, obj)\n\t}\n\th.cond.Broadcast()\n\treturn nil\n}","line":{"from":141,"to":161}} {"id":100028545,"name":"BulkAdd","signature":"func (h *Heap) BulkAdd(list []interface{}) error","file":"staging/src/k8s.io/client-go/tools/cache/heap.go","code":"// BulkAdd adds all the items in the list to the queue and then signals the condition\n// variable. It is useful when the caller would like to add all of the items\n// to the queue before consumer starts processing them.\nfunc (h *Heap) BulkAdd(list []interface{}) error {\n\th.lock.Lock()\n\tdefer h.lock.Unlock()\n\tif h.closed {\n\t\treturn fmt.Errorf(closedMsg)\n\t}\n\tfor _, obj := range list {\n\t\tkey, err := h.data.keyFunc(obj)\n\t\tif err != nil {\n\t\t\treturn KeyError{obj, err}\n\t\t}\n\t\tif _, exists := h.data.items[key]; exists {\n\t\t\th.data.items[key].obj = obj\n\t\t\theap.Fix(h.data, h.data.items[key].index)\n\t\t} else {\n\t\t\th.addIfNotPresentLocked(key, obj)\n\t\t}\n\t}\n\th.cond.Broadcast()\n\treturn nil\n}","line":{"from":163,"to":186}} {"id":100028546,"name":"AddIfNotPresent","signature":"func (h *Heap) AddIfNotPresent(obj interface{}) error","file":"staging/src/k8s.io/client-go/tools/cache/heap.go","code":"// AddIfNotPresent inserts an item, and puts it in the queue. If an item with\n// the key is present in the map, no changes is made to the item.\n//\n// This is useful in a single producer/consumer scenario so that the consumer can\n// safely retry items without contending with the producer and potentially enqueueing\n// stale items.\nfunc (h *Heap) AddIfNotPresent(obj interface{}) error {\n\tid, err := h.data.keyFunc(obj)\n\tif err != nil {\n\t\treturn KeyError{obj, err}\n\t}\n\th.lock.Lock()\n\tdefer h.lock.Unlock()\n\tif h.closed {\n\t\treturn fmt.Errorf(closedMsg)\n\t}\n\th.addIfNotPresentLocked(id, obj)\n\th.cond.Broadcast()\n\treturn nil\n}","line":{"from":188,"to":207}} {"id":100028547,"name":"addIfNotPresentLocked","signature":"func (h *Heap) addIfNotPresentLocked(key string, obj interface{})","file":"staging/src/k8s.io/client-go/tools/cache/heap.go","code":"// addIfNotPresentLocked assumes the lock is already held and adds the provided\n// item to the queue if it does not already exist.\nfunc (h *Heap) addIfNotPresentLocked(key string, obj interface{}) {\n\tif _, exists := h.data.items[key]; exists {\n\t\treturn\n\t}\n\theap.Push(h.data, \u0026itemKeyValue{key, obj})\n}","line":{"from":209,"to":216}} {"id":100028548,"name":"Update","signature":"func (h *Heap) Update(obj interface{}) error","file":"staging/src/k8s.io/client-go/tools/cache/heap.go","code":"// Update is the same as Add in this implementation. When the item does not\n// exist, it is added.\nfunc (h *Heap) Update(obj interface{}) error {\n\treturn h.Add(obj)\n}","line":{"from":218,"to":222}} {"id":100028549,"name":"Delete","signature":"func (h *Heap) Delete(obj interface{}) error","file":"staging/src/k8s.io/client-go/tools/cache/heap.go","code":"// Delete removes an item.\nfunc (h *Heap) Delete(obj interface{}) error {\n\tkey, err := h.data.keyFunc(obj)\n\tif err != nil {\n\t\treturn KeyError{obj, err}\n\t}\n\th.lock.Lock()\n\tdefer h.lock.Unlock()\n\tif item, ok := h.data.items[key]; ok {\n\t\theap.Remove(h.data, item.index)\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"object not found\")\n}","line":{"from":224,"to":237}} {"id":100028550,"name":"Pop","signature":"func (h *Heap) Pop() (interface{}, error)","file":"staging/src/k8s.io/client-go/tools/cache/heap.go","code":"// Pop waits until an item is ready. If multiple items are\n// ready, they are returned in the order given by Heap.data.lessFunc.\nfunc (h *Heap) Pop() (interface{}, error) {\n\th.lock.Lock()\n\tdefer h.lock.Unlock()\n\tfor len(h.data.queue) == 0 {\n\t\t// When the queue is empty, invocation of Pop() is blocked until new item is enqueued.\n\t\t// When Close() is called, the h.closed is set and the condition is broadcast,\n\t\t// which causes this loop to continue and return from the Pop().\n\t\tif h.closed {\n\t\t\treturn nil, fmt.Errorf(\"heap is closed\")\n\t\t}\n\t\th.cond.Wait()\n\t}\n\tobj := heap.Pop(h.data)\n\tif obj == nil {\n\t\treturn nil, fmt.Errorf(\"object was removed from heap data\")\n\t}\n\n\treturn obj, nil\n}","line":{"from":239,"to":259}} {"id":100028551,"name":"List","signature":"func (h *Heap) List() []interface{}","file":"staging/src/k8s.io/client-go/tools/cache/heap.go","code":"// List returns a list of all the items.\nfunc (h *Heap) List() []interface{} {\n\th.lock.RLock()\n\tdefer h.lock.RUnlock()\n\tlist := make([]interface{}, 0, len(h.data.items))\n\tfor _, item := range h.data.items {\n\t\tlist = append(list, item.obj)\n\t}\n\treturn list\n}","line":{"from":261,"to":270}} {"id":100028552,"name":"ListKeys","signature":"func (h *Heap) ListKeys() []string","file":"staging/src/k8s.io/client-go/tools/cache/heap.go","code":"// ListKeys returns a list of all the keys of the objects currently in the Heap.\nfunc (h *Heap) ListKeys() []string {\n\th.lock.RLock()\n\tdefer h.lock.RUnlock()\n\tlist := make([]string, 0, len(h.data.items))\n\tfor key := range h.data.items {\n\t\tlist = append(list, key)\n\t}\n\treturn list\n}","line":{"from":272,"to":281}} {"id":100028553,"name":"Get","signature":"func (h *Heap) Get(obj interface{}) (interface{}, bool, error)","file":"staging/src/k8s.io/client-go/tools/cache/heap.go","code":"// Get returns the requested item, or sets exists=false.\nfunc (h *Heap) Get(obj interface{}) (interface{}, bool, error) {\n\tkey, err := h.data.keyFunc(obj)\n\tif err != nil {\n\t\treturn nil, false, KeyError{obj, err}\n\t}\n\treturn h.GetByKey(key)\n}","line":{"from":283,"to":290}} {"id":100028554,"name":"GetByKey","signature":"func (h *Heap) GetByKey(key string) (interface{}, bool, error)","file":"staging/src/k8s.io/client-go/tools/cache/heap.go","code":"// GetByKey returns the requested item, or sets exists=false.\nfunc (h *Heap) GetByKey(key string) (interface{}, bool, error) {\n\th.lock.RLock()\n\tdefer h.lock.RUnlock()\n\titem, exists := h.data.items[key]\n\tif !exists {\n\t\treturn nil, false, nil\n\t}\n\treturn item.obj, true, nil\n}","line":{"from":292,"to":301}} {"id":100028555,"name":"IsClosed","signature":"func (h *Heap) IsClosed() bool","file":"staging/src/k8s.io/client-go/tools/cache/heap.go","code":"// IsClosed returns true if the queue is closed.\nfunc (h *Heap) IsClosed() bool {\n\th.lock.RLock()\n\tdefer h.lock.RUnlock()\n\treturn h.closed\n}","line":{"from":303,"to":308}} {"id":100028556,"name":"NewHeap","signature":"func NewHeap(keyFn KeyFunc, lessFn LessFunc) *Heap","file":"staging/src/k8s.io/client-go/tools/cache/heap.go","code":"// NewHeap returns a Heap which can be used to queue up items to process.\nfunc NewHeap(keyFn KeyFunc, lessFn LessFunc) *Heap {\n\th := \u0026Heap{\n\t\tdata: \u0026heapData{\n\t\t\titems: map[string]*heapItem{},\n\t\t\tqueue: []string{},\n\t\t\tkeyFunc: keyFn,\n\t\t\tlessFunc: lessFn,\n\t\t},\n\t}\n\th.cond.L = \u0026h.lock\n\treturn h\n}","line":{"from":310,"to":322}} {"id":100028557,"name":"IndexFuncToKeyFuncAdapter","signature":"func IndexFuncToKeyFuncAdapter(indexFunc IndexFunc) KeyFunc","file":"staging/src/k8s.io/client-go/tools/cache/index.go","code":"// IndexFuncToKeyFuncAdapter adapts an indexFunc to a keyFunc. This is only useful if your index function returns\n// unique values for every object. This conversion can create errors when more than one key is found. You\n// should prefer to make proper key and index functions.\nfunc IndexFuncToKeyFuncAdapter(indexFunc IndexFunc) KeyFunc {\n\treturn func(obj interface{}) (string, error) {\n\t\tindexKeys, err := indexFunc(obj)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif len(indexKeys) \u003e 1 {\n\t\t\treturn \"\", fmt.Errorf(\"too many keys: %v\", indexKeys)\n\t\t}\n\t\tif len(indexKeys) == 0 {\n\t\t\treturn \"\", fmt.Errorf(\"unexpected empty indexKeys\")\n\t\t}\n\t\treturn indexKeys[0], nil\n\t}\n}","line":{"from":61,"to":78}} {"id":100028558,"name":"MetaNamespaceIndexFunc","signature":"func MetaNamespaceIndexFunc(obj interface{}) ([]string, error)","file":"staging/src/k8s.io/client-go/tools/cache/index.go","code":"// MetaNamespaceIndexFunc is a default index function that indexes based on an object's namespace\nfunc MetaNamespaceIndexFunc(obj interface{}) ([]string, error) {\n\tmeta, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn []string{\"\"}, fmt.Errorf(\"object has no meta: %v\", err)\n\t}\n\treturn []string{meta.GetNamespace()}, nil\n}","line":{"from":85,"to":92}} {"id":100028559,"name":"ListAll","signature":"func ListAll(store Store, selector labels.Selector, appendFn AppendFunc) error","file":"staging/src/k8s.io/client-go/tools/cache/listers.go","code":"// ListAll calls appendFn with each value retrieved from store which matches the selector.\nfunc ListAll(store Store, selector labels.Selector, appendFn AppendFunc) error {\n\tselectAll := selector.Empty()\n\tfor _, m := range store.List() {\n\t\tif selectAll {\n\t\t\t// Avoid computing labels of the objects to speed up common flows\n\t\t\t// of listing all objects.\n\t\t\tappendFn(m)\n\t\t\tcontinue\n\t\t}\n\t\tmetadata, err := meta.Accessor(m)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif selector.Matches(labels.Set(metadata.GetLabels())) {\n\t\t\tappendFn(m)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":33,"to":52}} {"id":100028560,"name":"ListAllByNamespace","signature":"func ListAllByNamespace(indexer Indexer, namespace string, selector labels.Selector, appendFn AppendFunc) error","file":"staging/src/k8s.io/client-go/tools/cache/listers.go","code":"// ListAllByNamespace used to list items belongs to namespace from Indexer.\nfunc ListAllByNamespace(indexer Indexer, namespace string, selector labels.Selector, appendFn AppendFunc) error {\n\tif namespace == metav1.NamespaceAll {\n\t\treturn ListAll(indexer, selector, appendFn)\n\t}\n\n\titems, err := indexer.Index(NamespaceIndex, \u0026metav1.ObjectMeta{Namespace: namespace})\n\tif err != nil {\n\t\t// Ignore error; do slow search without index.\n\t\tklog.Warningf(\"can not retrieve list of objects using index : %v\", err)\n\t\tfor _, m := range indexer.List() {\n\t\t\tmetadata, err := meta.Accessor(m)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif metadata.GetNamespace() == namespace \u0026\u0026 selector.Matches(labels.Set(metadata.GetLabels())) {\n\t\t\t\tappendFn(m)\n\t\t\t}\n\n\t\t}\n\t\treturn nil\n\t}\n\n\tselectAll := selector.Empty()\n\tfor _, m := range items {\n\t\tif selectAll {\n\t\t\t// Avoid computing labels of the objects to speed up common flows\n\t\t\t// of listing all objects.\n\t\t\tappendFn(m)\n\t\t\tcontinue\n\t\t}\n\t\tmetadata, err := meta.Accessor(m)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif selector.Matches(labels.Set(metadata.GetLabels())) {\n\t\t\tappendFn(m)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":54,"to":95}} {"id":100028561,"name":"NewGenericLister","signature":"func NewGenericLister(indexer Indexer, resource schema.GroupResource) GenericLister","file":"staging/src/k8s.io/client-go/tools/cache/listers.go","code":"// NewGenericLister creates a new instance for the genericLister.\nfunc NewGenericLister(indexer Indexer, resource schema.GroupResource) GenericLister {\n\treturn \u0026genericLister{indexer: indexer, resource: resource}\n}","line":{"from":115,"to":118}} {"id":100028562,"name":"List","signature":"func (s *genericLister) List(selector labels.Selector) (ret []runtime.Object, err error)","file":"staging/src/k8s.io/client-go/tools/cache/listers.go","code":"func (s *genericLister) List(selector labels.Selector) (ret []runtime.Object, err error) {\n\terr = ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(runtime.Object))\n\t})\n\treturn ret, err\n}","line":{"from":125,"to":130}} {"id":100028563,"name":"ByNamespace","signature":"func (s *genericLister) ByNamespace(namespace string) GenericNamespaceLister","file":"staging/src/k8s.io/client-go/tools/cache/listers.go","code":"func (s *genericLister) ByNamespace(namespace string) GenericNamespaceLister {\n\treturn \u0026genericNamespaceLister{indexer: s.indexer, namespace: namespace, resource: s.resource}\n}","line":{"from":132,"to":134}} {"id":100028564,"name":"Get","signature":"func (s *genericLister) Get(name string) (runtime.Object, error)","file":"staging/src/k8s.io/client-go/tools/cache/listers.go","code":"func (s *genericLister) Get(name string) (runtime.Object, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(s.resource, name)\n\t}\n\treturn obj.(runtime.Object), nil\n}","line":{"from":136,"to":145}} {"id":100028565,"name":"List","signature":"func (s *genericNamespaceLister) List(selector labels.Selector) (ret []runtime.Object, err error)","file":"staging/src/k8s.io/client-go/tools/cache/listers.go","code":"func (s *genericNamespaceLister) List(selector labels.Selector) (ret []runtime.Object, err error) {\n\terr = ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(runtime.Object))\n\t})\n\treturn ret, err\n}","line":{"from":153,"to":158}} {"id":100028566,"name":"Get","signature":"func (s *genericNamespaceLister) Get(name string) (runtime.Object, error)","file":"staging/src/k8s.io/client-go/tools/cache/listers.go","code":"func (s *genericNamespaceLister) Get(name string) (runtime.Object, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(s.resource, name)\n\t}\n\treturn obj.(runtime.Object), nil\n}","line":{"from":160,"to":169}} {"id":100028567,"name":"NewListWatchFromClient","signature":"func NewListWatchFromClient(c Getter, resource string, namespace string, fieldSelector fields.Selector) *ListWatch","file":"staging/src/k8s.io/client-go/tools/cache/listwatch.go","code":"// NewListWatchFromClient creates a new ListWatch from the specified client, resource, namespace and field selector.\nfunc NewListWatchFromClient(c Getter, resource string, namespace string, fieldSelector fields.Selector) *ListWatch {\n\toptionsModifier := func(options *metav1.ListOptions) {\n\t\toptions.FieldSelector = fieldSelector.String()\n\t}\n\treturn NewFilteredListWatchFromClient(c, resource, namespace, optionsModifier)\n}","line":{"from":69,"to":75}} {"id":100028568,"name":"NewFilteredListWatchFromClient","signature":"func NewFilteredListWatchFromClient(c Getter, resource string, namespace string, optionsModifier func(options *metav1.ListOptions)) *ListWatch","file":"staging/src/k8s.io/client-go/tools/cache/listwatch.go","code":"// NewFilteredListWatchFromClient creates a new ListWatch from the specified client, resource, namespace, and option modifier.\n// Option modifier is a function takes a ListOptions and modifies the consumed ListOptions. Provide customized modifier function\n// to apply modification to ListOptions with a field selector, a label selector, or any other desired options.\nfunc NewFilteredListWatchFromClient(c Getter, resource string, namespace string, optionsModifier func(options *metav1.ListOptions)) *ListWatch {\n\tlistFunc := func(options metav1.ListOptions) (runtime.Object, error) {\n\t\toptionsModifier(\u0026options)\n\t\treturn c.Get().\n\t\t\tNamespace(namespace).\n\t\t\tResource(resource).\n\t\t\tVersionedParams(\u0026options, metav1.ParameterCodec).\n\t\t\tDo(context.TODO()).\n\t\t\tGet()\n\t}\n\twatchFunc := func(options metav1.ListOptions) (watch.Interface, error) {\n\t\toptions.Watch = true\n\t\toptionsModifier(\u0026options)\n\t\treturn c.Get().\n\t\t\tNamespace(namespace).\n\t\t\tResource(resource).\n\t\t\tVersionedParams(\u0026options, metav1.ParameterCodec).\n\t\t\tWatch(context.TODO())\n\t}\n\treturn \u0026ListWatch{ListFunc: listFunc, WatchFunc: watchFunc}\n}","line":{"from":77,"to":100}} {"id":100028569,"name":"List","signature":"func (lw *ListWatch) List(options metav1.ListOptions) (runtime.Object, error)","file":"staging/src/k8s.io/client-go/tools/cache/listwatch.go","code":"// List a set of apiserver resources\nfunc (lw *ListWatch) List(options metav1.ListOptions) (runtime.Object, error) {\n\t// ListWatch is used in Reflector, which already supports pagination.\n\t// Don't paginate here to avoid duplication.\n\treturn lw.ListFunc(options)\n}","line":{"from":102,"to":107}} {"id":100028570,"name":"Watch","signature":"func (lw *ListWatch) Watch(options metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/tools/cache/listwatch.go","code":"// Watch a set of apiserver resources\nfunc (lw *ListWatch) Watch(options metav1.ListOptions) (watch.Interface, error) {\n\treturn lw.WatchFunc(options)\n}","line":{"from":109,"to":112}} {"id":100028571,"name":"NewIntegerResourceVersionMutationCache","signature":"func NewIntegerResourceVersionMutationCache(backingCache Store, indexer Indexer, ttl time.Duration, includeAdds bool) MutationCache","file":"staging/src/k8s.io/client-go/tools/cache/mutation_cache.go","code":"// NewIntegerResourceVersionMutationCache returns a MutationCache that understands how to\n// deal with objects that have a resource version that:\n//\n// - is an integer\n// - increases when updated\n// - is comparable across the same resource in a namespace\n//\n// Most backends will have these semantics. Indexer may be nil. ttl controls how long an item\n// remains in the mutation cache before it is removed.\n//\n// If includeAdds is true, objects in the mutation cache will be returned even if they don't exist\n// in the underlying store. This is only safe if your use of the cache can handle mutation entries\n// remaining in the cache for up to ttl when mutations and deletes occur very closely in time.\nfunc NewIntegerResourceVersionMutationCache(backingCache Store, indexer Indexer, ttl time.Duration, includeAdds bool) MutationCache {\n\treturn \u0026mutationCache{\n\t\tbackingCache: backingCache,\n\t\tindexer: indexer,\n\t\tmutationCache: utilcache.NewLRUExpireCache(100),\n\t\tcomparator: etcdObjectVersioner{},\n\t\tttl: ttl,\n\t\tincludeAdds: includeAdds,\n\t}\n}","line":{"from":50,"to":72}} {"id":100028572,"name":"GetByKey","signature":"func (c *mutationCache) GetByKey(key string) (interface{}, bool, error)","file":"staging/src/k8s.io/client-go/tools/cache/mutation_cache.go","code":"// GetByKey is never guaranteed to return back the value set in Mutation. It could be paged out, it could\n// be older than another copy, the backingCache may be more recent or, you might have written twice into the same key.\n// You get a value that was valid at some snapshot of time and will always return the newer of backingCache and mutationCache.\nfunc (c *mutationCache) GetByKey(key string) (interface{}, bool, error) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tobj, exists, err := c.backingCache.GetByKey(key)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\tif !exists {\n\t\tif !c.includeAdds {\n\t\t\t// we can't distinguish between, \"didn't observe create\" and \"was deleted after create\", so\n\t\t\t// if the key is missing, we always return it as missing\n\t\t\treturn nil, false, nil\n\t\t}\n\t\tobj, exists = c.mutationCache.Get(key)\n\t\tif !exists {\n\t\t\treturn nil, false, nil\n\t\t}\n\t}\n\tobjRuntime, ok := obj.(runtime.Object)\n\tif !ok {\n\t\treturn obj, true, nil\n\t}\n\treturn c.newerObject(key, objRuntime), true, nil\n}","line":{"from":88,"to":115}} {"id":100028573,"name":"ByIndex","signature":"func (c *mutationCache) ByIndex(name string, indexKey string) ([]interface{}, error)","file":"staging/src/k8s.io/client-go/tools/cache/mutation_cache.go","code":"// ByIndex returns the newer objects that match the provided index and indexer key.\n// Will return an error if no indexer was provided.\nfunc (c *mutationCache) ByIndex(name string, indexKey string) ([]interface{}, error) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tif c.indexer == nil {\n\t\treturn nil, fmt.Errorf(\"no indexer has been provided to the mutation cache\")\n\t}\n\tkeys, err := c.indexer.IndexKeys(name, indexKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar items []interface{}\n\tkeySet := sets.NewString()\n\tfor _, key := range keys {\n\t\tkeySet.Insert(key)\n\t\tobj, exists, err := c.indexer.GetByKey(key)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !exists {\n\t\t\tcontinue\n\t\t}\n\t\tif objRuntime, ok := obj.(runtime.Object); ok {\n\t\t\titems = append(items, c.newerObject(key, objRuntime))\n\t\t} else {\n\t\t\titems = append(items, obj)\n\t\t}\n\t}\n\n\tif c.includeAdds {\n\t\tfn := c.indexer.GetIndexers()[name]\n\t\t// Keys() is returned oldest to newest, so full traversal does not alter the LRU behavior\n\t\tfor _, key := range c.mutationCache.Keys() {\n\t\t\tupdated, ok := c.mutationCache.Get(key)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif keySet.Has(key.(string)) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\telements, err := fn(updated)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Unable to calculate an index entry for mutation cache entry %s: %v\", key, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor _, inIndex := range elements {\n\t\t\t\tif inIndex != indexKey {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\titems = append(items, updated)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn items, nil\n}","line":{"from":117,"to":174}} {"id":100028574,"name":"newerObject","signature":"func (c *mutationCache) newerObject(key string, backing runtime.Object) runtime.Object","file":"staging/src/k8s.io/client-go/tools/cache/mutation_cache.go","code":"// newerObject checks the mutation cache for a newer object and returns one if found. If the\n// mutated object is older than the backing object, it is removed from the Must be\n// called while the lock is held.\nfunc (c *mutationCache) newerObject(key string, backing runtime.Object) runtime.Object {\n\tmutatedObj, exists := c.mutationCache.Get(key)\n\tif !exists {\n\t\treturn backing\n\t}\n\tmutatedObjRuntime, ok := mutatedObj.(runtime.Object)\n\tif !ok {\n\t\treturn backing\n\t}\n\tif c.comparator.CompareResourceVersion(backing, mutatedObjRuntime) \u003e= 0 {\n\t\tc.mutationCache.Remove(key)\n\t\treturn backing\n\t}\n\treturn mutatedObjRuntime\n}","line":{"from":176,"to":193}} {"id":100028575,"name":"Mutation","signature":"func (c *mutationCache) Mutation(obj interface{})","file":"staging/src/k8s.io/client-go/tools/cache/mutation_cache.go","code":"// Mutation adds a change to the cache that can be returned in GetByKey if it is newer than the backingCache\n// copy. If you call Mutation twice with the same object on different threads, one will win, but its not defined\n// which one. This doesn't affect correctness, since the GetByKey guaranteed of \"later of these two caches\" is\n// preserved, but you may not get the version of the object you want. The object you get is only guaranteed to\n// \"one that was valid at some point in time\", not \"the one that I want\".\nfunc (c *mutationCache) Mutation(obj interface{}) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tkey, err := DeletionHandlingMetaNamespaceKeyFunc(obj)\n\tif err != nil {\n\t\t// this is a \"nice to have\", so failures shouldn't do anything weird\n\t\tutilruntime.HandleError(err)\n\t\treturn\n\t}\n\n\tif objRuntime, ok := obj.(runtime.Object); ok {\n\t\tif mutatedObj, exists := c.mutationCache.Get(key); exists {\n\t\t\tif mutatedObjRuntime, ok := mutatedObj.(runtime.Object); ok {\n\t\t\t\tif c.comparator.CompareResourceVersion(objRuntime, mutatedObjRuntime) \u003c 0 {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tc.mutationCache.Add(key, obj, c.ttl)\n}","line":{"from":195,"to":221}} {"id":100028576,"name":"ObjectResourceVersion","signature":"func (a etcdObjectVersioner) ObjectResourceVersion(obj runtime.Object) (uint64, error)","file":"staging/src/k8s.io/client-go/tools/cache/mutation_cache.go","code":"// ObjectResourceVersion implements Versioner\nfunc (a etcdObjectVersioner) ObjectResourceVersion(obj runtime.Object) (uint64, error) {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tversion := accessor.GetResourceVersion()\n\tif len(version) == 0 {\n\t\treturn 0, nil\n\t}\n\treturn strconv.ParseUint(version, 10, 64)\n}","line":{"from":227,"to":238}} {"id":100028577,"name":"CompareResourceVersion","signature":"func (a etcdObjectVersioner) CompareResourceVersion(lhs, rhs runtime.Object) int","file":"staging/src/k8s.io/client-go/tools/cache/mutation_cache.go","code":"// CompareResourceVersion compares etcd resource versions. Outside this API they are all strings,\n// but etcd resource versions are special, they're actually ints, so we can easily compare them.\nfunc (a etcdObjectVersioner) CompareResourceVersion(lhs, rhs runtime.Object) int {\n\tlhsVersion, err := a.ObjectResourceVersion(lhs)\n\tif err != nil {\n\t\t// coder error\n\t\tpanic(err)\n\t}\n\trhsVersion, err := a.ObjectResourceVersion(rhs)\n\tif err != nil {\n\t\t// coder error\n\t\tpanic(err)\n\t}\n\n\tif lhsVersion == rhsVersion {\n\t\treturn 0\n\t}\n\tif lhsVersion \u003c rhsVersion {\n\t\treturn -1\n\t}\n\n\treturn 1\n}","line":{"from":240,"to":262}} {"id":100028578,"name":"init","signature":"func init()","file":"staging/src/k8s.io/client-go/tools/cache/mutation_detector.go","code":"func init() {\n\tmutationDetectionEnabled, _ = strconv.ParseBool(os.Getenv(\"KUBE_CACHE_MUTATION_DETECTOR\"))\n}","line":{"from":35,"to":37}} {"id":100028579,"name":"NewCacheMutationDetector","signature":"func NewCacheMutationDetector(name string) MutationDetector","file":"staging/src/k8s.io/client-go/tools/cache/mutation_detector.go","code":"// NewCacheMutationDetector creates a new instance for the defaultCacheMutationDetector.\nfunc NewCacheMutationDetector(name string) MutationDetector {\n\tif !mutationDetectionEnabled {\n\t\treturn dummyMutationDetector{}\n\t}\n\tklog.Warningln(\"Mutation detector is enabled, this will result in memory leakage.\")\n\treturn \u0026defaultCacheMutationDetector{name: name, period: 1 * time.Second, retainDuration: 2 * time.Minute}\n}","line":{"from":48,"to":55}} {"id":100028580,"name":"Run","signature":"func (dummyMutationDetector) Run(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/client-go/tools/cache/mutation_detector.go","code":"func (dummyMutationDetector) Run(stopCh \u003c-chan struct{}) {\n}","line":{"from":59,"to":60}} {"id":100028581,"name":"AddObject","signature":"func (dummyMutationDetector) AddObject(obj interface{})","file":"staging/src/k8s.io/client-go/tools/cache/mutation_detector.go","code":"func (dummyMutationDetector) AddObject(obj interface{}) {\n}","line":{"from":61,"to":62}} {"id":100028582,"name":"Run","signature":"func (d *defaultCacheMutationDetector) Run(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/client-go/tools/cache/mutation_detector.go","code":"func (d *defaultCacheMutationDetector) Run(stopCh \u003c-chan struct{}) {\n\t// we DON'T want protection from panics. If we're running this code, we want to die\n\tfor {\n\t\tif d.lastRotated.IsZero() {\n\t\t\td.lastRotated = time.Now()\n\t\t} else if time.Since(d.lastRotated) \u003e d.retainDuration {\n\t\t\td.retainedCachedObjs = d.cachedObjs\n\t\t\td.cachedObjs = nil\n\t\t\td.lastRotated = time.Now()\n\t\t}\n\n\t\td.CompareObjects()\n\n\t\tselect {\n\t\tcase \u003c-stopCh:\n\t\t\treturn\n\t\tcase \u003c-time.After(d.period):\n\t\t}\n\t}\n}","line":{"from":97,"to":116}} {"id":100028583,"name":"AddObject","signature":"func (d *defaultCacheMutationDetector) AddObject(obj interface{})","file":"staging/src/k8s.io/client-go/tools/cache/mutation_detector.go","code":"// AddObject makes a deep copy of the object for later comparison. It only works on runtime.Object\n// but that covers the vast majority of our cached objects\nfunc (d *defaultCacheMutationDetector) AddObject(obj interface{}) {\n\tif _, ok := obj.(DeletedFinalStateUnknown); ok {\n\t\treturn\n\t}\n\tif obj, ok := obj.(runtime.Object); ok {\n\t\tcopiedObj := obj.DeepCopyObject()\n\n\t\td.addedObjsLock.Lock()\n\t\tdefer d.addedObjsLock.Unlock()\n\t\td.addedObjs = append(d.addedObjs, cacheObj{cached: obj, copied: copiedObj})\n\t}\n}","line":{"from":118,"to":131}} {"id":100028584,"name":"CompareObjects","signature":"func (d *defaultCacheMutationDetector) CompareObjects()","file":"staging/src/k8s.io/client-go/tools/cache/mutation_detector.go","code":"func (d *defaultCacheMutationDetector) CompareObjects() {\n\td.compareObjectsLock.Lock()\n\tdefer d.compareObjectsLock.Unlock()\n\n\t// move addedObjs into cachedObjs under lock\n\t// this keeps the critical section small to avoid blocking AddObject while we compare cachedObjs\n\td.addedObjsLock.Lock()\n\td.cachedObjs = append(d.cachedObjs, d.addedObjs...)\n\td.addedObjs = nil\n\td.addedObjsLock.Unlock()\n\n\taltered := false\n\tfor i, obj := range d.cachedObjs {\n\t\tif !reflect.DeepEqual(obj.cached, obj.copied) {\n\t\t\tfmt.Printf(\"CACHE %s[%d] ALTERED!\\n%v\\n\", d.name, i, diff.ObjectGoPrintSideBySide(obj.cached, obj.copied))\n\t\t\taltered = true\n\t\t}\n\t}\n\tfor i, obj := range d.retainedCachedObjs {\n\t\tif !reflect.DeepEqual(obj.cached, obj.copied) {\n\t\t\tfmt.Printf(\"CACHE %s[%d] ALTERED!\\n%v\\n\", d.name, i, diff.ObjectGoPrintSideBySide(obj.cached, obj.copied))\n\t\t\taltered = true\n\t\t}\n\t}\n\n\tif altered {\n\t\tmsg := fmt.Sprintf(\"cache %s modified\", d.name)\n\t\tif d.failureFunc != nil {\n\t\t\td.failureFunc(msg)\n\t\t\treturn\n\t\t}\n\t\tpanic(msg)\n\t}\n}","line":{"from":133,"to":166}} {"id":100028585,"name":"DefaultWatchErrorHandler","signature":"func DefaultWatchErrorHandler(r *Reflector, err error)","file":"staging/src/k8s.io/client-go/tools/cache/reflector.go","code":"// DefaultWatchErrorHandler is the default implementation of WatchErrorHandler\nfunc DefaultWatchErrorHandler(r *Reflector, err error) {\n\tswitch {\n\tcase isExpiredError(err):\n\t\t// Don't set LastSyncResourceVersionUnavailable - LIST call with ResourceVersion=RV already\n\t\t// has a semantic that it returns data at least as fresh as provided RV.\n\t\t// So first try to LIST with setting RV to resource version of last observed object.\n\t\tklog.V(4).Infof(\"%s: watch of %v closed with: %v\", r.name, r.typeDescription, err)\n\tcase err == io.EOF:\n\t\t// watch closed normally\n\tcase err == io.ErrUnexpectedEOF:\n\t\tklog.V(1).Infof(\"%s: Watch for %v closed with unexpected EOF: %v\", r.name, r.typeDescription, err)\n\tdefault:\n\t\tutilruntime.HandleError(fmt.Errorf(\"%s: Failed to watch %v: %v\", r.name, r.typeDescription, err))\n\t}\n}","line":{"from":135,"to":150}} {"id":100028586,"name":"NewNamespaceKeyedIndexerAndReflector","signature":"func NewNamespaceKeyedIndexerAndReflector(lw ListerWatcher, expectedType interface{}, resyncPeriod time.Duration) (indexer Indexer, reflector *Reflector)","file":"staging/src/k8s.io/client-go/tools/cache/reflector.go","code":"// NewNamespaceKeyedIndexerAndReflector creates an Indexer and a Reflector\n// The indexer is configured to key on namespace\nfunc NewNamespaceKeyedIndexerAndReflector(lw ListerWatcher, expectedType interface{}, resyncPeriod time.Duration) (indexer Indexer, reflector *Reflector) {\n\tindexer = NewIndexer(MetaNamespaceKeyFunc, Indexers{NamespaceIndex: MetaNamespaceIndexFunc})\n\treflector = NewReflector(lw, expectedType, indexer, resyncPeriod)\n\treturn indexer, reflector\n}","line":{"from":158,"to":164}} {"id":100028587,"name":"NewReflector","signature":"func NewReflector(lw ListerWatcher, expectedType interface{}, store Store, resyncPeriod time.Duration) *Reflector","file":"staging/src/k8s.io/client-go/tools/cache/reflector.go","code":"// NewReflector creates a new Reflector with its name defaulted to the closest source_file.go:line in the call stack\n// that is outside this package. See NewReflectorWithOptions for further information.\nfunc NewReflector(lw ListerWatcher, expectedType interface{}, store Store, resyncPeriod time.Duration) *Reflector {\n\treturn NewReflectorWithOptions(lw, expectedType, store, ReflectorOptions{ResyncPeriod: resyncPeriod})\n}","line":{"from":166,"to":170}} {"id":100028588,"name":"NewNamedReflector","signature":"func NewNamedReflector(name string, lw ListerWatcher, expectedType interface{}, store Store, resyncPeriod time.Duration) *Reflector","file":"staging/src/k8s.io/client-go/tools/cache/reflector.go","code":"// NewNamedReflector creates a new Reflector with the specified name. See NewReflectorWithOptions for further\n// information.\nfunc NewNamedReflector(name string, lw ListerWatcher, expectedType interface{}, store Store, resyncPeriod time.Duration) *Reflector {\n\treturn NewReflectorWithOptions(lw, expectedType, store, ReflectorOptions{Name: name, ResyncPeriod: resyncPeriod})\n}","line":{"from":172,"to":176}} {"id":100028589,"name":"NewReflectorWithOptions","signature":"func NewReflectorWithOptions(lw ListerWatcher, expectedType interface{}, store Store, options ReflectorOptions) *Reflector","file":"staging/src/k8s.io/client-go/tools/cache/reflector.go","code":"// NewReflectorWithOptions creates a new Reflector object which will keep the\n// given store up to date with the server's contents for the given\n// resource. Reflector promises to only put things in the store that\n// have the type of expectedType, unless expectedType is nil. If\n// resyncPeriod is non-zero, then the reflector will periodically\n// consult its ShouldResync function to determine whether to invoke\n// the Store's Resync operation; `ShouldResync==nil` means always\n// \"yes\". This enables you to use reflectors to periodically process\n// everything as well as incrementally processing the things that\n// change.\nfunc NewReflectorWithOptions(lw ListerWatcher, expectedType interface{}, store Store, options ReflectorOptions) *Reflector {\n\treflectorClock := options.Clock\n\tif reflectorClock == nil {\n\t\treflectorClock = clock.RealClock{}\n\t}\n\tr := \u0026Reflector{\n\t\tname: options.Name,\n\t\tresyncPeriod: options.ResyncPeriod,\n\t\ttypeDescription: options.TypeDescription,\n\t\tlisterWatcher: lw,\n\t\tstore: store,\n\t\t// We used to make the call every 1sec (1 QPS), the goal here is to achieve ~98% traffic reduction when\n\t\t// API server is not healthy. With these parameters, backoff will stop at [30,60) sec interval which is\n\t\t// 0.22 QPS. If we don't backoff for 2min, assume API server is healthy and we reset the backoff.\n\t\tbackoffManager: wait.NewExponentialBackoffManager(800*time.Millisecond, 30*time.Second, 2*time.Minute, 2.0, 1.0, reflectorClock),\n\t\tinitConnBackoffManager: wait.NewExponentialBackoffManager(800*time.Millisecond, 30*time.Second, 2*time.Minute, 2.0, 1.0, reflectorClock),\n\t\tclock: reflectorClock,\n\t\twatchErrorHandler: WatchErrorHandler(DefaultWatchErrorHandler),\n\t\texpectedType: reflect.TypeOf(expectedType),\n\t}\n\n\tif r.name == \"\" {\n\t\tr.name = naming.GetNameFromCallsite(internalPackages...)\n\t}\n\n\tif r.typeDescription == \"\" {\n\t\tr.typeDescription = getTypeDescriptionFromObject(expectedType)\n\t}\n\n\tif r.expectedGVK == nil {\n\t\tr.expectedGVK = getExpectedGVKFromObject(expectedType)\n\t}\n\n\treturn r\n}","line":{"from":199,"to":243}} {"id":100028590,"name":"getTypeDescriptionFromObject","signature":"func getTypeDescriptionFromObject(expectedType interface{}) string","file":"staging/src/k8s.io/client-go/tools/cache/reflector.go","code":"func getTypeDescriptionFromObject(expectedType interface{}) string {\n\tif expectedType == nil {\n\t\treturn defaultExpectedTypeName\n\t}\n\n\treflectDescription := reflect.TypeOf(expectedType).String()\n\n\tobj, ok := expectedType.(*unstructured.Unstructured)\n\tif !ok {\n\t\treturn reflectDescription\n\t}\n\n\tgvk := obj.GroupVersionKind()\n\tif gvk.Empty() {\n\t\treturn reflectDescription\n\t}\n\n\treturn gvk.String()\n}","line":{"from":245,"to":263}} {"id":100028591,"name":"getExpectedGVKFromObject","signature":"func getExpectedGVKFromObject(expectedType interface{}) *schema.GroupVersionKind","file":"staging/src/k8s.io/client-go/tools/cache/reflector.go","code":"func getExpectedGVKFromObject(expectedType interface{}) *schema.GroupVersionKind {\n\tobj, ok := expectedType.(*unstructured.Unstructured)\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tgvk := obj.GroupVersionKind()\n\tif gvk.Empty() {\n\t\treturn nil\n\t}\n\n\treturn \u0026gvk\n}","line":{"from":265,"to":277}} {"id":100028592,"name":"Run","signature":"func (r *Reflector) Run(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/client-go/tools/cache/reflector.go","code":"// Run repeatedly uses the reflector's ListAndWatch to fetch all the\n// objects and subsequent deltas.\n// Run will exit when stopCh is closed.\nfunc (r *Reflector) Run(stopCh \u003c-chan struct{}) {\n\tklog.V(3).Infof(\"Starting reflector %s (%s) from %s\", r.typeDescription, r.resyncPeriod, r.name)\n\twait.BackoffUntil(func() {\n\t\tif err := r.ListAndWatch(stopCh); err != nil {\n\t\t\tr.watchErrorHandler(r, err)\n\t\t}\n\t}, r.backoffManager, true, stopCh)\n\tklog.V(3).Infof(\"Stopping reflector %s (%s) from %s\", r.typeDescription, r.resyncPeriod, r.name)\n}","line":{"from":283,"to":294}} {"id":100028593,"name":"resyncChan","signature":"func (r *Reflector) resyncChan() (\u003c-chan time.Time, func() bool)","file":"staging/src/k8s.io/client-go/tools/cache/reflector.go","code":"// resyncChan returns a channel which will receive something when a resync is\n// required, and a cleanup function.\nfunc (r *Reflector) resyncChan() (\u003c-chan time.Time, func() bool) {\n\tif r.resyncPeriod == 0 {\n\t\treturn neverExitWatch, func() bool { return false }\n\t}\n\t// The cleanup function is required: imagine the scenario where watches\n\t// always fail so we end up listing frequently. Then, if we don't\n\t// manually stop the timer, we could end up with many timers active\n\t// concurrently.\n\tt := r.clock.NewTimer(r.resyncPeriod)\n\treturn t.C(), t.Stop\n}","line":{"from":305,"to":317}} {"id":100028594,"name":"ListAndWatch","signature":"func (r *Reflector) ListAndWatch(stopCh \u003c-chan struct{}) error","file":"staging/src/k8s.io/client-go/tools/cache/reflector.go","code":"// ListAndWatch first lists all items and get the resource version at the moment of call,\n// and then use the resource version to watch.\n// It returns error if ListAndWatch didn't even try to initialize watch.\nfunc (r *Reflector) ListAndWatch(stopCh \u003c-chan struct{}) error {\n\tklog.V(3).Infof(\"Listing and watching %v from %s\", r.typeDescription, r.name)\n\tvar err error\n\tvar w watch.Interface\n\tfallbackToList := !r.UseWatchList\n\n\tif r.UseWatchList {\n\t\tw, err = r.watchList(stopCh)\n\t\tif w == nil \u0026\u0026 err == nil {\n\t\t\t// stopCh was closed\n\t\t\treturn nil\n\t\t}\n\t\tif err != nil {\n\t\t\tif !apierrors.IsInvalid(err) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tklog.Warning(\"the watch-list feature is not supported by the server, falling back to the previous LIST/WATCH semantic\")\n\t\t\tfallbackToList = true\n\t\t\t// Ensure that we won't accidentally pass some garbage down the watch.\n\t\t\tw = nil\n\t\t}\n\t}\n\n\tif fallbackToList {\n\t\terr = r.list(stopCh)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tresyncerrc := make(chan error, 1)\n\tcancelCh := make(chan struct{})\n\tdefer close(cancelCh)\n\tgo r.startResync(stopCh, cancelCh, resyncerrc)\n\treturn r.watch(w, stopCh, resyncerrc)\n}","line":{"from":319,"to":357}} {"id":100028595,"name":"startResync","signature":"func (r *Reflector) startResync(stopCh \u003c-chan struct{}, cancelCh \u003c-chan struct{}, resyncerrc chan error)","file":"staging/src/k8s.io/client-go/tools/cache/reflector.go","code":"// startResync periodically calls r.store.Resync() method.\n// Note that this method is blocking and should be\n// called in a separate goroutine.\nfunc (r *Reflector) startResync(stopCh \u003c-chan struct{}, cancelCh \u003c-chan struct{}, resyncerrc chan error) {\n\tresyncCh, cleanup := r.resyncChan()\n\tdefer func() {\n\t\tcleanup() // Call the last one written into cleanup\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase \u003c-resyncCh:\n\t\tcase \u003c-stopCh:\n\t\t\treturn\n\t\tcase \u003c-cancelCh:\n\t\t\treturn\n\t\t}\n\t\tif r.ShouldResync == nil || r.ShouldResync() {\n\t\t\tklog.V(4).Infof(\"%s: forcing resync\", r.name)\n\t\t\tif err := r.store.Resync(); err != nil {\n\t\t\t\tresyncerrc \u003c- err\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tcleanup()\n\t\tresyncCh, cleanup = r.resyncChan()\n\t}\n}","line":{"from":359,"to":385}} {"id":100028596,"name":"watch","signature":"func (r *Reflector) watch(w watch.Interface, stopCh \u003c-chan struct{}, resyncerrc chan error) error","file":"staging/src/k8s.io/client-go/tools/cache/reflector.go","code":"// watch simply starts a watch request with the server.\nfunc (r *Reflector) watch(w watch.Interface, stopCh \u003c-chan struct{}, resyncerrc chan error) error {\n\tvar err error\n\tretry := NewRetryWithDeadline(r.MaxInternalErrorRetryDuration, time.Minute, apierrors.IsInternalError, r.clock)\n\n\tfor {\n\t\t// give the stopCh a chance to stop the loop, even in case of continue statements further down on errors\n\t\tselect {\n\t\tcase \u003c-stopCh:\n\t\t\treturn nil\n\t\tdefault:\n\t\t}\n\n\t\t// start the clock before sending the request, since some proxies won't flush headers until after the first watch event is sent\n\t\tstart := r.clock.Now()\n\n\t\tif w == nil {\n\t\t\ttimeoutSeconds := int64(minWatchTimeout.Seconds() * (rand.Float64() + 1.0))\n\t\t\toptions := metav1.ListOptions{\n\t\t\t\tResourceVersion: r.LastSyncResourceVersion(),\n\t\t\t\t// We want to avoid situations of hanging watchers. Stop any watchers that do not\n\t\t\t\t// receive any events within the timeout window.\n\t\t\t\tTimeoutSeconds: \u0026timeoutSeconds,\n\t\t\t\t// To reduce load on kube-apiserver on watch restarts, you may enable watch bookmarks.\n\t\t\t\t// Reflector doesn't assume bookmarks are returned at all (if the server do not support\n\t\t\t\t// watch bookmarks, it will ignore this field).\n\t\t\t\tAllowWatchBookmarks: true,\n\t\t\t}\n\n\t\t\tw, err = r.listerWatcher.Watch(options)\n\t\t\tif err != nil {\n\t\t\t\tif canRetry := isWatchErrorRetriable(err); canRetry {\n\t\t\t\t\tklog.V(4).Infof(\"%s: watch of %v returned %v - backing off\", r.name, r.typeDescription, err)\n\t\t\t\t\tselect {\n\t\t\t\t\tcase \u003c-stopCh:\n\t\t\t\t\t\treturn nil\n\t\t\t\t\tcase \u003c-r.initConnBackoffManager.Backoff().C():\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\terr = watchHandler(start, w, r.store, r.expectedType, r.expectedGVK, r.name, r.typeDescription, r.setLastSyncResourceVersion, nil, r.clock, resyncerrc, stopCh)\n\t\t// Ensure that watch will not be reused across iterations.\n\t\tw.Stop()\n\t\tw = nil\n\t\tretry.After(err)\n\t\tif err != nil {\n\t\t\tif err != errorStopRequested {\n\t\t\t\tswitch {\n\t\t\t\tcase isExpiredError(err):\n\t\t\t\t\t// Don't set LastSyncResourceVersionUnavailable - LIST call with ResourceVersion=RV already\n\t\t\t\t\t// has a semantic that it returns data at least as fresh as provided RV.\n\t\t\t\t\t// So first try to LIST with setting RV to resource version of last observed object.\n\t\t\t\t\tklog.V(4).Infof(\"%s: watch of %v closed with: %v\", r.name, r.typeDescription, err)\n\t\t\t\tcase apierrors.IsTooManyRequests(err):\n\t\t\t\t\tklog.V(2).Infof(\"%s: watch of %v returned 429 - backing off\", r.name, r.typeDescription)\n\t\t\t\t\tselect {\n\t\t\t\t\tcase \u003c-stopCh:\n\t\t\t\t\t\treturn nil\n\t\t\t\t\tcase \u003c-r.initConnBackoffManager.Backoff().C():\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\tcase apierrors.IsInternalError(err) \u0026\u0026 retry.ShouldRetry():\n\t\t\t\t\tklog.V(2).Infof(\"%s: retrying watch of %v internal error: %v\", r.name, r.typeDescription, err)\n\t\t\t\t\tcontinue\n\t\t\t\tdefault:\n\t\t\t\t\tklog.Warningf(\"%s: watch of %v ended with: %v\", r.name, r.typeDescription, err)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n}","line":{"from":387,"to":462}} {"id":100028597,"name":"list","signature":"func (r *Reflector) list(stopCh \u003c-chan struct{}) error","file":"staging/src/k8s.io/client-go/tools/cache/reflector.go","code":"// list simply lists all items and records a resource version obtained from the server at the moment of the call.\n// the resource version can be used for further progress notification (aka. watch).\nfunc (r *Reflector) list(stopCh \u003c-chan struct{}) error {\n\tvar resourceVersion string\n\toptions := metav1.ListOptions{ResourceVersion: r.relistResourceVersion()}\n\n\tinitTrace := trace.New(\"Reflector ListAndWatch\", trace.Field{Key: \"name\", Value: r.name})\n\tdefer initTrace.LogIfLong(10 * time.Second)\n\tvar list runtime.Object\n\tvar paginatedResult bool\n\tvar err error\n\tlistCh := make(chan struct{}, 1)\n\tpanicCh := make(chan interface{}, 1)\n\tgo func() {\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\tpanicCh \u003c- r\n\t\t\t}\n\t\t}()\n\t\t// Attempt to gather list in chunks, if supported by listerWatcher, if not, the first\n\t\t// list request will return the full response.\n\t\tpager := pager.New(pager.SimplePageFunc(func(opts metav1.ListOptions) (runtime.Object, error) {\n\t\t\treturn r.listerWatcher.List(opts)\n\t\t}))\n\t\tswitch {\n\t\tcase r.WatchListPageSize != 0:\n\t\t\tpager.PageSize = r.WatchListPageSize\n\t\tcase r.paginatedResult:\n\t\t\t// We got a paginated result initially. Assume this resource and server honor\n\t\t\t// paging requests (i.e. watch cache is probably disabled) and leave the default\n\t\t\t// pager size set.\n\t\tcase options.ResourceVersion != \"\" \u0026\u0026 options.ResourceVersion != \"0\":\n\t\t\t// User didn't explicitly request pagination.\n\t\t\t//\n\t\t\t// With ResourceVersion != \"\", we have a possibility to list from watch cache,\n\t\t\t// but we do that (for ResourceVersion != \"0\") only if Limit is unset.\n\t\t\t// To avoid thundering herd on etcd (e.g. on master upgrades), we explicitly\n\t\t\t// switch off pagination to force listing from watch cache (if enabled).\n\t\t\t// With the existing semantic of RV (result is at least as fresh as provided RV),\n\t\t\t// this is correct and doesn't lead to going back in time.\n\t\t\t//\n\t\t\t// We also don't turn off pagination for ResourceVersion=\"0\", since watch cache\n\t\t\t// is ignoring Limit in that case anyway, and if watch cache is not enabled\n\t\t\t// we don't introduce regression.\n\t\t\tpager.PageSize = 0\n\t\t}\n\n\t\tlist, paginatedResult, err = pager.List(context.Background(), options)\n\t\tif isExpiredError(err) || isTooLargeResourceVersionError(err) {\n\t\t\tr.setIsLastSyncResourceVersionUnavailable(true)\n\t\t\t// Retry immediately if the resource version used to list is unavailable.\n\t\t\t// The pager already falls back to full list if paginated list calls fail due to an \"Expired\" error on\n\t\t\t// continuation pages, but the pager might not be enabled, the full list might fail because the\n\t\t\t// resource version it is listing at is expired or the cache may not yet be synced to the provided\n\t\t\t// resource version. So we need to fallback to resourceVersion=\"\" in all to recover and ensure\n\t\t\t// the reflector makes forward progress.\n\t\t\tlist, paginatedResult, err = pager.List(context.Background(), metav1.ListOptions{ResourceVersion: r.relistResourceVersion()})\n\t\t}\n\t\tclose(listCh)\n\t}()\n\tselect {\n\tcase \u003c-stopCh:\n\t\treturn nil\n\tcase r := \u003c-panicCh:\n\t\tpanic(r)\n\tcase \u003c-listCh:\n\t}\n\tinitTrace.Step(\"Objects listed\", trace.Field{Key: \"error\", Value: err})\n\tif err != nil {\n\t\tklog.Warningf(\"%s: failed to list %v: %v\", r.name, r.typeDescription, err)\n\t\treturn fmt.Errorf(\"failed to list %v: %w\", r.typeDescription, err)\n\t}\n\n\t// We check if the list was paginated and if so set the paginatedResult based on that.\n\t// However, we want to do that only for the initial list (which is the only case\n\t// when we set ResourceVersion=\"0\"). The reasoning behind it is that later, in some\n\t// situations we may force listing directly from etcd (by setting ResourceVersion=\"\")\n\t// which will return paginated result, even if watch cache is enabled. However, in\n\t// that case, we still want to prefer sending requests to watch cache if possible.\n\t//\n\t// Paginated result returned for request with ResourceVersion=\"0\" mean that watch\n\t// cache is disabled and there are a lot of objects of a given type. In such case,\n\t// there is no need to prefer listing from watch cache.\n\tif options.ResourceVersion == \"0\" \u0026\u0026 paginatedResult {\n\t\tr.paginatedResult = true\n\t}\n\n\tr.setIsLastSyncResourceVersionUnavailable(false) // list was successful\n\tlistMetaInterface, err := meta.ListAccessor(list)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to understand list result %#v: %v\", list, err)\n\t}\n\tresourceVersion = listMetaInterface.GetResourceVersion()\n\tinitTrace.Step(\"Resource version extracted\")\n\titems, err := meta.ExtractList(list)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to understand list result %#v (%v)\", list, err)\n\t}\n\tinitTrace.Step(\"Objects extracted\")\n\tif err := r.syncWith(items, resourceVersion); err != nil {\n\t\treturn fmt.Errorf(\"unable to sync list result: %v\", err)\n\t}\n\tinitTrace.Step(\"SyncWith done\")\n\tr.setLastSyncResourceVersion(resourceVersion)\n\tinitTrace.Step(\"Resource version updated\")\n\treturn nil\n}","line":{"from":464,"to":570}} {"id":100028598,"name":"watchList","signature":"func (r *Reflector) watchList(stopCh \u003c-chan struct{}) (watch.Interface, error)","file":"staging/src/k8s.io/client-go/tools/cache/reflector.go","code":"// watchList establishes a stream to get a consistent snapshot of data\n// from the server as described in https://github.com/kubernetes/enhancements/tree/master/keps/sig-api-machinery/3157-watch-list#proposal\n//\n// case 1: start at Most Recent (RV=\"\", ResourceVersionMatch=ResourceVersionMatchNotOlderThan)\n// Establishes a consistent stream with the server.\n// That means the returned data is consistent, as if, served directly from etcd via a quorum read.\n// It begins with synthetic \"Added\" events of all resources up to the most recent ResourceVersion.\n// It ends with a synthetic \"Bookmark\" event containing the most recent ResourceVersion.\n// After receiving a \"Bookmark\" event the reflector is considered to be synchronized.\n// It replaces its internal store with the collected items and\n// reuses the current watch requests for getting further events.\n//\n// case 2: start at Exact (RV\u003e\"0\", ResourceVersionMatch=ResourceVersionMatchNotOlderThan)\n// Establishes a stream with the server at the provided resource version.\n// To establish the initial state the server begins with synthetic \"Added\" events.\n// It ends with a synthetic \"Bookmark\" event containing the provided or newer resource version.\n// After receiving a \"Bookmark\" event the reflector is considered to be synchronized.\n// It replaces its internal store with the collected items and\n// reuses the current watch requests for getting further events.\nfunc (r *Reflector) watchList(stopCh \u003c-chan struct{}) (watch.Interface, error) {\n\tvar w watch.Interface\n\tvar err error\n\tvar temporaryStore Store\n\tvar resourceVersion string\n\t// TODO(#115478): see if this function could be turned\n\t// into a method and see if error handling\n\t// could be unified with the r.watch method\n\tisErrorRetriableWithSideEffectsFn := func(err error) bool {\n\t\tif canRetry := isWatchErrorRetriable(err); canRetry {\n\t\t\tklog.V(2).Infof(\"%s: watch-list of %v returned %v - backing off\", r.name, r.typeDescription, err)\n\t\t\t\u003c-r.initConnBackoffManager.Backoff().C()\n\t\t\treturn true\n\t\t}\n\t\tif isExpiredError(err) || isTooLargeResourceVersionError(err) {\n\t\t\t// we tried to re-establish a watch request but the provided RV\n\t\t\t// has either expired or it is greater than the server knows about.\n\t\t\t// In that case we reset the RV and\n\t\t\t// try to get a consistent snapshot from the watch cache (case 1)\n\t\t\tr.setIsLastSyncResourceVersionUnavailable(true)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\tinitTrace := trace.New(\"Reflector WatchList\", trace.Field{Key: \"name\", Value: r.name})\n\tdefer initTrace.LogIfLong(10 * time.Second)\n\tfor {\n\t\tselect {\n\t\tcase \u003c-stopCh:\n\t\t\treturn nil, nil\n\t\tdefault:\n\t\t}\n\n\t\tresourceVersion = \"\"\n\t\tlastKnownRV := r.rewatchResourceVersion()\n\t\ttemporaryStore = NewStore(DeletionHandlingMetaNamespaceKeyFunc)\n\t\t// TODO(#115478): large \"list\", slow clients, slow network, p\u0026f\n\t\t// might slow down streaming and eventually fail.\n\t\t// maybe in such a case we should retry with an increased timeout?\n\t\ttimeoutSeconds := int64(minWatchTimeout.Seconds() * (rand.Float64() + 1.0))\n\t\toptions := metav1.ListOptions{\n\t\t\tResourceVersion: lastKnownRV,\n\t\t\tAllowWatchBookmarks: true,\n\t\t\tSendInitialEvents: pointer.Bool(true),\n\t\t\tResourceVersionMatch: metav1.ResourceVersionMatchNotOlderThan,\n\t\t\tTimeoutSeconds: \u0026timeoutSeconds,\n\t\t}\n\t\tstart := r.clock.Now()\n\n\t\tw, err = r.listerWatcher.Watch(options)\n\t\tif err != nil {\n\t\t\tif isErrorRetriableWithSideEffectsFn(err) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\tbookmarkReceived := pointer.Bool(false)\n\t\terr = watchHandler(start, w, temporaryStore, r.expectedType, r.expectedGVK, r.name, r.typeDescription,\n\t\t\tfunc(rv string) { resourceVersion = rv },\n\t\t\tbookmarkReceived,\n\t\t\tr.clock, make(chan error), stopCh)\n\t\tif err != nil {\n\t\t\tw.Stop() // stop and retry with clean state\n\t\t\tif err == errorStopRequested {\n\t\t\t\treturn nil, nil\n\t\t\t}\n\t\t\tif isErrorRetriableWithSideEffectsFn(err) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\tif *bookmarkReceived {\n\t\t\tbreak\n\t\t}\n\t}\n\t// We successfully got initial state from watch-list confirmed by the\n\t// \"k8s.io/initial-events-end\" bookmark.\n\tinitTrace.Step(\"Objects streamed\", trace.Field{Key: \"count\", Value: len(temporaryStore.List())})\n\tr.setIsLastSyncResourceVersionUnavailable(false)\n\tif err = r.store.Replace(temporaryStore.List(), resourceVersion); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to sync watch-list result: %v\", err)\n\t}\n\tinitTrace.Step(\"SyncWith done\")\n\tr.setLastSyncResourceVersion(resourceVersion)\n\n\treturn w, nil\n}","line":{"from":572,"to":678}} {"id":100028599,"name":"syncWith","signature":"func (r *Reflector) syncWith(items []runtime.Object, resourceVersion string) error","file":"staging/src/k8s.io/client-go/tools/cache/reflector.go","code":"// syncWith replaces the store's items with the given list.\nfunc (r *Reflector) syncWith(items []runtime.Object, resourceVersion string) error {\n\tfound := make([]interface{}, 0, len(items))\n\tfor _, item := range items {\n\t\tfound = append(found, item)\n\t}\n\treturn r.store.Replace(found, resourceVersion)\n}","line":{"from":680,"to":687}} {"id":100028600,"name":"watchHandler","signature":"func watchHandler(start time.Time,","file":"staging/src/k8s.io/client-go/tools/cache/reflector.go","code":"// watchHandler watches w and sets setLastSyncResourceVersion\nfunc watchHandler(start time.Time,\n\tw watch.Interface,\n\tstore Store,\n\texpectedType reflect.Type,\n\texpectedGVK *schema.GroupVersionKind,\n\tname string,\n\texpectedTypeName string,\n\tsetLastSyncResourceVersion func(string),\n\texitOnInitialEventsEndBookmark *bool,\n\tclock clock.Clock,\n\terrc chan error,\n\tstopCh \u003c-chan struct{},\n) error {\n\teventCount := 0\n\tif exitOnInitialEventsEndBookmark != nil {\n\t\t// set it to false just in case somebody\n\t\t// made it positive\n\t\t*exitOnInitialEventsEndBookmark = false\n\t}\n\nloop:\n\tfor {\n\t\tselect {\n\t\tcase \u003c-stopCh:\n\t\t\treturn errorStopRequested\n\t\tcase err := \u003c-errc:\n\t\t\treturn err\n\t\tcase event, ok := \u003c-w.ResultChan():\n\t\t\tif !ok {\n\t\t\t\tbreak loop\n\t\t\t}\n\t\t\tif event.Type == watch.Error {\n\t\t\t\treturn apierrors.FromObject(event.Object)\n\t\t\t}\n\t\t\tif expectedType != nil {\n\t\t\t\tif e, a := expectedType, reflect.TypeOf(event.Object); e != a {\n\t\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"%s: expected type %v, but watch event object had type %v\", name, e, a))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tif expectedGVK != nil {\n\t\t\t\tif e, a := *expectedGVK, event.Object.GetObjectKind().GroupVersionKind(); e != a {\n\t\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"%s: expected gvk %v, but watch event object had gvk %v\", name, e, a))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tmeta, err := meta.Accessor(event.Object)\n\t\t\tif err != nil {\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"%s: unable to understand watch event %#v\", name, event))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tresourceVersion := meta.GetResourceVersion()\n\t\t\tswitch event.Type {\n\t\t\tcase watch.Added:\n\t\t\t\terr := store.Add(event.Object)\n\t\t\t\tif err != nil {\n\t\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"%s: unable to add watch event object (%#v) to store: %v\", name, event.Object, err))\n\t\t\t\t}\n\t\t\tcase watch.Modified:\n\t\t\t\terr := store.Update(event.Object)\n\t\t\t\tif err != nil {\n\t\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"%s: unable to update watch event object (%#v) to store: %v\", name, event.Object, err))\n\t\t\t\t}\n\t\t\tcase watch.Deleted:\n\t\t\t\t// TODO: Will any consumers need access to the \"last known\n\t\t\t\t// state\", which is passed in event.Object? If so, may need\n\t\t\t\t// to change this.\n\t\t\t\terr := store.Delete(event.Object)\n\t\t\t\tif err != nil {\n\t\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"%s: unable to delete watch event object (%#v) from store: %v\", name, event.Object, err))\n\t\t\t\t}\n\t\t\tcase watch.Bookmark:\n\t\t\t\t// A `Bookmark` means watch has synced here, just update the resourceVersion\n\t\t\t\tif _, ok := meta.GetAnnotations()[\"k8s.io/initial-events-end\"]; ok {\n\t\t\t\t\tif exitOnInitialEventsEndBookmark != nil {\n\t\t\t\t\t\t*exitOnInitialEventsEndBookmark = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"%s: unable to understand watch event %#v\", name, event))\n\t\t\t}\n\t\t\tsetLastSyncResourceVersion(resourceVersion)\n\t\t\tif rvu, ok := store.(ResourceVersionUpdater); ok {\n\t\t\t\trvu.UpdateResourceVersion(resourceVersion)\n\t\t\t}\n\t\t\teventCount++\n\t\t\tif exitOnInitialEventsEndBookmark != nil \u0026\u0026 *exitOnInitialEventsEndBookmark {\n\t\t\t\twatchDuration := clock.Since(start)\n\t\t\t\tklog.V(4).Infof(\"exiting %v Watch because received the bookmark that marks the end of initial events stream, total %v items received in %v\", name, eventCount, watchDuration)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\twatchDuration := clock.Since(start)\n\tif watchDuration \u003c 1*time.Second \u0026\u0026 eventCount == 0 {\n\t\treturn fmt.Errorf(\"very short watch: %s: Unexpected watch close - watch lasted less than a second and no items received\", name)\n\t}\n\tklog.V(4).Infof(\"%s: Watch close - %v total %v items received\", name, expectedTypeName, eventCount)\n\treturn nil\n}","line":{"from":689,"to":790}} {"id":100028601,"name":"LastSyncResourceVersion","signature":"func (r *Reflector) LastSyncResourceVersion() string","file":"staging/src/k8s.io/client-go/tools/cache/reflector.go","code":"// LastSyncResourceVersion is the resource version observed when last sync with the underlying store\n// The value returned is not synchronized with access to the underlying store and is not thread-safe\nfunc (r *Reflector) LastSyncResourceVersion() string {\n\tr.lastSyncResourceVersionMutex.RLock()\n\tdefer r.lastSyncResourceVersionMutex.RUnlock()\n\treturn r.lastSyncResourceVersion\n}","line":{"from":792,"to":798}} {"id":100028602,"name":"setLastSyncResourceVersion","signature":"func (r *Reflector) setLastSyncResourceVersion(v string)","file":"staging/src/k8s.io/client-go/tools/cache/reflector.go","code":"func (r *Reflector) setLastSyncResourceVersion(v string) {\n\tr.lastSyncResourceVersionMutex.Lock()\n\tdefer r.lastSyncResourceVersionMutex.Unlock()\n\tr.lastSyncResourceVersion = v\n}","line":{"from":800,"to":804}} {"id":100028603,"name":"relistResourceVersion","signature":"func (r *Reflector) relistResourceVersion() string","file":"staging/src/k8s.io/client-go/tools/cache/reflector.go","code":"// relistResourceVersion determines the resource version the reflector should list or relist from.\n// Returns either the lastSyncResourceVersion so that this reflector will relist with a resource\n// versions no older than has already been observed in relist results or watch events, or, if the last relist resulted\n// in an HTTP 410 (Gone) status code, returns \"\" so that the relist will use the latest resource version available in\n// etcd via a quorum read.\nfunc (r *Reflector) relistResourceVersion() string {\n\tr.lastSyncResourceVersionMutex.RLock()\n\tdefer r.lastSyncResourceVersionMutex.RUnlock()\n\n\tif r.isLastSyncResourceVersionUnavailable {\n\t\t// Since this reflector makes paginated list requests, and all paginated list requests skip the watch cache\n\t\t// if the lastSyncResourceVersion is unavailable, we set ResourceVersion=\"\" and list again to re-establish reflector\n\t\t// to the latest available ResourceVersion, using a consistent read from etcd.\n\t\treturn \"\"\n\t}\n\tif r.lastSyncResourceVersion == \"\" {\n\t\t// For performance reasons, initial list performed by reflector uses \"0\" as resource version to allow it to\n\t\t// be served from the watch cache if it is enabled.\n\t\treturn \"0\"\n\t}\n\treturn r.lastSyncResourceVersion\n}","line":{"from":806,"to":827}} {"id":100028604,"name":"rewatchResourceVersion","signature":"func (r *Reflector) rewatchResourceVersion() string","file":"staging/src/k8s.io/client-go/tools/cache/reflector.go","code":"// rewatchResourceVersion determines the resource version the reflector should start streaming from.\nfunc (r *Reflector) rewatchResourceVersion() string {\n\tr.lastSyncResourceVersionMutex.RLock()\n\tdefer r.lastSyncResourceVersionMutex.RUnlock()\n\tif r.isLastSyncResourceVersionUnavailable {\n\t\t// initial stream should return data at the most recent resource version.\n\t\t// the returned data must be consistent i.e. as if served from etcd via a quorum read\n\t\treturn \"\"\n\t}\n\treturn r.lastSyncResourceVersion\n}","line":{"from":829,"to":839}} {"id":100028605,"name":"setIsLastSyncResourceVersionUnavailable","signature":"func (r *Reflector) setIsLastSyncResourceVersionUnavailable(isUnavailable bool)","file":"staging/src/k8s.io/client-go/tools/cache/reflector.go","code":"// setIsLastSyncResourceVersionUnavailable sets if the last list or watch request with lastSyncResourceVersion returned\n// \"expired\" or \"too large resource version\" error.\nfunc (r *Reflector) setIsLastSyncResourceVersionUnavailable(isUnavailable bool) {\n\tr.lastSyncResourceVersionMutex.Lock()\n\tdefer r.lastSyncResourceVersionMutex.Unlock()\n\tr.isLastSyncResourceVersionUnavailable = isUnavailable\n}","line":{"from":841,"to":847}} {"id":100028606,"name":"isExpiredError","signature":"func isExpiredError(err error) bool","file":"staging/src/k8s.io/client-go/tools/cache/reflector.go","code":"func isExpiredError(err error) bool {\n\t// In Kubernetes 1.17 and earlier, the api server returns both apierrors.StatusReasonExpired and\n\t// apierrors.StatusReasonGone for HTTP 410 (Gone) status code responses. In 1.18 the kube server is more consistent\n\t// and always returns apierrors.StatusReasonExpired. For backward compatibility we can only remove the apierrors.IsGone\n\t// check when we fully drop support for Kubernetes 1.17 servers from reflectors.\n\treturn apierrors.IsResourceExpired(err) || apierrors.IsGone(err)\n}","line":{"from":849,"to":855}} {"id":100028607,"name":"isTooLargeResourceVersionError","signature":"func isTooLargeResourceVersionError(err error) bool","file":"staging/src/k8s.io/client-go/tools/cache/reflector.go","code":"func isTooLargeResourceVersionError(err error) bool {\n\tif apierrors.HasStatusCause(err, metav1.CauseTypeResourceVersionTooLarge) {\n\t\treturn true\n\t}\n\t// In Kubernetes 1.17.0-1.18.5, the api server doesn't set the error status cause to\n\t// metav1.CauseTypeResourceVersionTooLarge to indicate that the requested minimum resource\n\t// version is larger than the largest currently available resource version. To ensure backward\n\t// compatibility with these server versions we also need to detect the error based on the content\n\t// of the error message field.\n\tif !apierrors.IsTimeout(err) {\n\t\treturn false\n\t}\n\tapierr, ok := err.(apierrors.APIStatus)\n\tif !ok || apierr == nil || apierr.Status().Details == nil {\n\t\treturn false\n\t}\n\tfor _, cause := range apierr.Status().Details.Causes {\n\t\t// Matches the message returned by api server 1.17.0-1.18.5 for this error condition\n\t\tif cause.Message == \"Too large resource version\" {\n\t\t\treturn true\n\t\t}\n\t}\n\n\t// Matches the message returned by api server before 1.17.0\n\tif strings.Contains(apierr.Status().Message, \"Too large resource version\") {\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":857,"to":886}} {"id":100028608,"name":"isWatchErrorRetriable","signature":"func isWatchErrorRetriable(err error) bool","file":"staging/src/k8s.io/client-go/tools/cache/reflector.go","code":"// isWatchErrorRetriable determines if it is safe to retry\n// a watch error retrieved from the server.\nfunc isWatchErrorRetriable(err error) bool {\n\t// If this is \"connection refused\" error, it means that most likely apiserver is not responsive.\n\t// It doesn't make sense to re-list all objects because most likely we will be able to restart\n\t// watch where we ended.\n\t// If that's the case begin exponentially backing off and resend watch request.\n\t// Do the same for \"429\" errors.\n\tif utilnet.IsConnectionRefused(err) || apierrors.IsTooManyRequests(err) {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":888,"to":900}} {"id":100028609,"name":"Inc","signature":"func (noopMetric) Inc() {}","file":"staging/src/k8s.io/client-go/tools/cache/reflector_metrics.go","code":"func (noopMetric) Inc() {}","line":{"from":45,"to":45}} {"id":100028610,"name":"Dec","signature":"func (noopMetric) Dec() {}","file":"staging/src/k8s.io/client-go/tools/cache/reflector_metrics.go","code":"func (noopMetric) Dec() {}","line":{"from":46,"to":46}} {"id":100028611,"name":"Observe","signature":"func (noopMetric) Observe(float64) {}","file":"staging/src/k8s.io/client-go/tools/cache/reflector_metrics.go","code":"func (noopMetric) Observe(float64) {}","line":{"from":47,"to":47}} {"id":100028612,"name":"Set","signature":"func (noopMetric) Set(float64) {}","file":"staging/src/k8s.io/client-go/tools/cache/reflector_metrics.go","code":"func (noopMetric) Set(float64) {}","line":{"from":48,"to":48}} {"id":100028613,"name":"NewListsMetric","signature":"func (noopMetricsProvider) NewListsMetric(name string) CounterMetric { return noopMetric{} }","file":"staging/src/k8s.io/client-go/tools/cache/reflector_metrics.go","code":"func (noopMetricsProvider) NewListsMetric(name string) CounterMetric { return noopMetric{} }","line":{"from":66,"to":66}} {"id":100028614,"name":"NewListDurationMetric","signature":"func (noopMetricsProvider) NewListDurationMetric(name string) SummaryMetric { return noopMetric{} }","file":"staging/src/k8s.io/client-go/tools/cache/reflector_metrics.go","code":"func (noopMetricsProvider) NewListDurationMetric(name string) SummaryMetric { return noopMetric{} }","line":{"from":67,"to":67}} {"id":100028615,"name":"NewItemsInListMetric","signature":"func (noopMetricsProvider) NewItemsInListMetric(name string) SummaryMetric { return noopMetric{} }","file":"staging/src/k8s.io/client-go/tools/cache/reflector_metrics.go","code":"func (noopMetricsProvider) NewItemsInListMetric(name string) SummaryMetric { return noopMetric{} }","line":{"from":68,"to":68}} {"id":100028616,"name":"NewWatchesMetric","signature":"func (noopMetricsProvider) NewWatchesMetric(name string) CounterMetric { return noopMetric{} }","file":"staging/src/k8s.io/client-go/tools/cache/reflector_metrics.go","code":"func (noopMetricsProvider) NewWatchesMetric(name string) CounterMetric { return noopMetric{} }","line":{"from":69,"to":69}} {"id":100028617,"name":"NewShortWatchesMetric","signature":"func (noopMetricsProvider) NewShortWatchesMetric(name string) CounterMetric { return noopMetric{} }","file":"staging/src/k8s.io/client-go/tools/cache/reflector_metrics.go","code":"func (noopMetricsProvider) NewShortWatchesMetric(name string) CounterMetric { return noopMetric{} }","line":{"from":70,"to":70}} {"id":100028618,"name":"NewWatchDurationMetric","signature":"func (noopMetricsProvider) NewWatchDurationMetric(name string) SummaryMetric { return noopMetric{} }","file":"staging/src/k8s.io/client-go/tools/cache/reflector_metrics.go","code":"func (noopMetricsProvider) NewWatchDurationMetric(name string) SummaryMetric { return noopMetric{} }","line":{"from":71,"to":71}} {"id":100028619,"name":"NewItemsInWatchMetric","signature":"func (noopMetricsProvider) NewItemsInWatchMetric(name string) SummaryMetric { return noopMetric{} }","file":"staging/src/k8s.io/client-go/tools/cache/reflector_metrics.go","code":"func (noopMetricsProvider) NewItemsInWatchMetric(name string) SummaryMetric { return noopMetric{} }","line":{"from":72,"to":72}} {"id":100028620,"name":"NewLastResourceVersionMetric","signature":"func (noopMetricsProvider) NewLastResourceVersionMetric(name string) GaugeMetric","file":"staging/src/k8s.io/client-go/tools/cache/reflector_metrics.go","code":"func (noopMetricsProvider) NewLastResourceVersionMetric(name string) GaugeMetric {\n\treturn noopMetric{}\n}","line":{"from":73,"to":75}} {"id":100028621,"name":"SetReflectorMetricsProvider","signature":"func SetReflectorMetricsProvider(metricsProvider MetricsProvider)","file":"staging/src/k8s.io/client-go/tools/cache/reflector_metrics.go","code":"// SetReflectorMetricsProvider sets the metrics provider\nfunc SetReflectorMetricsProvider(metricsProvider MetricsProvider) {\n\tmetricsFactory.setProviders.Do(func() {\n\t\tmetricsFactory.metricsProvider = metricsProvider\n\t})\n}","line":{"from":84,"to":89}} {"id":100028622,"name":"NewRetryWithDeadline","signature":"func NewRetryWithDeadline(maxRetryDuration, minResetPeriod time.Duration, isRetryable func(error) bool, clock clock.Clock) RetryWithDeadline","file":"staging/src/k8s.io/client-go/tools/cache/retry_with_deadline.go","code":"func NewRetryWithDeadline(maxRetryDuration, minResetPeriod time.Duration, isRetryable func(error) bool, clock clock.Clock) RetryWithDeadline {\n\treturn \u0026retryWithDeadlineImpl{\n\t\tfirstErrorTime: time.Time{},\n\t\tlastErrorTime: time.Time{},\n\t\tmaxRetryDuration: maxRetryDuration,\n\t\tminResetPeriod: minResetPeriod,\n\t\tisRetryable: isRetryable,\n\t\tclock: clock,\n\t}\n}","line":{"from":38,"to":47}} {"id":100028623,"name":"reset","signature":"func (r *retryWithDeadlineImpl) reset()","file":"staging/src/k8s.io/client-go/tools/cache/retry_with_deadline.go","code":"func (r *retryWithDeadlineImpl) reset() {\n\tr.firstErrorTime = time.Time{}\n\tr.lastErrorTime = time.Time{}\n}","line":{"from":49,"to":52}} {"id":100028624,"name":"After","signature":"func (r *retryWithDeadlineImpl) After(err error)","file":"staging/src/k8s.io/client-go/tools/cache/retry_with_deadline.go","code":"func (r *retryWithDeadlineImpl) After(err error) {\n\tif r.isRetryable(err) {\n\t\tif r.clock.Now().Sub(r.lastErrorTime) \u003e= r.minResetPeriod {\n\t\t\tr.reset()\n\t\t}\n\n\t\tif r.firstErrorTime.IsZero() {\n\t\t\tr.firstErrorTime = r.clock.Now()\n\t\t}\n\t\tr.lastErrorTime = r.clock.Now()\n\t}\n}","line":{"from":54,"to":65}} {"id":100028625,"name":"ShouldRetry","signature":"func (r *retryWithDeadlineImpl) ShouldRetry() bool","file":"staging/src/k8s.io/client-go/tools/cache/retry_with_deadline.go","code":"func (r *retryWithDeadlineImpl) ShouldRetry() bool {\n\tif r.maxRetryDuration \u003c= time.Duration(0) {\n\t\treturn false\n\t}\n\n\tif r.clock.Now().Sub(r.firstErrorTime) \u003c= r.maxRetryDuration {\n\t\treturn true\n\t}\n\n\tr.reset()\n\treturn false\n}","line":{"from":67,"to":78}} {"id":100028626,"name":"NewSharedInformer","signature":"func NewSharedInformer(lw ListerWatcher, exampleObject runtime.Object, defaultEventHandlerResyncPeriod time.Duration) SharedInformer","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"// NewSharedInformer creates a new instance for the ListerWatcher. See NewSharedIndexInformerWithOptions for full details.\nfunc NewSharedInformer(lw ListerWatcher, exampleObject runtime.Object, defaultEventHandlerResyncPeriod time.Duration) SharedInformer {\n\treturn NewSharedIndexInformer(lw, exampleObject, defaultEventHandlerResyncPeriod, Indexers{})\n}","line":{"from":237,"to":240}} {"id":100028627,"name":"NewSharedIndexInformer","signature":"func NewSharedIndexInformer(lw ListerWatcher, exampleObject runtime.Object, defaultEventHandlerResyncPeriod time.Duration, indexers Indexers) SharedIndexInformer","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"// NewSharedIndexInformer creates a new instance for the ListerWatcher and specified Indexers. See\n// NewSharedIndexInformerWithOptions for full details.\nfunc NewSharedIndexInformer(lw ListerWatcher, exampleObject runtime.Object, defaultEventHandlerResyncPeriod time.Duration, indexers Indexers) SharedIndexInformer {\n\treturn NewSharedIndexInformerWithOptions(\n\t\tlw,\n\t\texampleObject,\n\t\tSharedIndexInformerOptions{\n\t\t\tResyncPeriod: defaultEventHandlerResyncPeriod,\n\t\t\tIndexers: indexers,\n\t\t},\n\t)\n}","line":{"from":242,"to":253}} {"id":100028628,"name":"NewSharedIndexInformerWithOptions","signature":"func NewSharedIndexInformerWithOptions(lw ListerWatcher, exampleObject runtime.Object, options SharedIndexInformerOptions) SharedIndexInformer","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"// NewSharedIndexInformerWithOptions creates a new instance for the ListerWatcher.\n// The created informer will not do resyncs if options.ResyncPeriod is zero. Otherwise: for each\n// handler that with a non-zero requested resync period, whether added\n// before or after the informer starts, the nominal resync period is\n// the requested resync period rounded up to a multiple of the\n// informer's resync checking period. Such an informer's resync\n// checking period is established when the informer starts running,\n// and is the maximum of (a) the minimum of the resync periods\n// requested before the informer starts and the\n// options.ResyncPeriod given here and (b) the constant\n// `minimumResyncPeriod` defined in this file.\nfunc NewSharedIndexInformerWithOptions(lw ListerWatcher, exampleObject runtime.Object, options SharedIndexInformerOptions) SharedIndexInformer {\n\trealClock := \u0026clock.RealClock{}\n\n\treturn \u0026sharedIndexInformer{\n\t\tindexer: NewIndexer(DeletionHandlingMetaNamespaceKeyFunc, options.Indexers),\n\t\tprocessor: \u0026sharedProcessor{clock: realClock},\n\t\tlisterWatcher: lw,\n\t\tobjectType: exampleObject,\n\t\tobjectDescription: options.ObjectDescription,\n\t\tresyncCheckPeriod: options.ResyncPeriod,\n\t\tdefaultEventHandlerResyncPeriod: options.ResyncPeriod,\n\t\tclock: realClock,\n\t\tcacheMutationDetector: NewCacheMutationDetector(fmt.Sprintf(\"%T\", exampleObject)),\n\t}\n}","line":{"from":255,"to":280}} {"id":100028629,"name":"WaitForNamedCacheSync","signature":"func WaitForNamedCacheSync(controllerName string, stopCh \u003c-chan struct{}, cacheSyncs ...InformerSynced) bool","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"// WaitForNamedCacheSync is a wrapper around WaitForCacheSync that generates log messages\n// indicating that the caller identified by name is waiting for syncs, followed by\n// either a successful or failed sync.\nfunc WaitForNamedCacheSync(controllerName string, stopCh \u003c-chan struct{}, cacheSyncs ...InformerSynced) bool {\n\tklog.Infof(\"Waiting for caches to sync for %s\", controllerName)\n\n\tif !WaitForCacheSync(stopCh, cacheSyncs...) {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unable to sync caches for %s\", controllerName))\n\t\treturn false\n\t}\n\n\tklog.Infof(\"Caches are synced for %s\", controllerName)\n\treturn true\n}","line":{"from":307,"to":320}} {"id":100028630,"name":"WaitForCacheSync","signature":"func WaitForCacheSync(stopCh \u003c-chan struct{}, cacheSyncs ...InformerSynced) bool","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"// WaitForCacheSync waits for caches to populate. It returns true if it was successful, false\n// if the controller should shutdown\n// callers should prefer WaitForNamedCacheSync()\nfunc WaitForCacheSync(stopCh \u003c-chan struct{}, cacheSyncs ...InformerSynced) bool {\n\terr := wait.PollImmediateUntil(syncedPollPeriod,\n\t\tfunc() (bool, error) {\n\t\t\tfor _, syncFunc := range cacheSyncs {\n\t\t\t\tif !syncFunc() {\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true, nil\n\t\t},\n\t\tstopCh)\n\tif err != nil {\n\t\tklog.V(2).Infof(\"stop requested\")\n\t\treturn false\n\t}\n\n\tklog.V(4).Infof(\"caches populated\")\n\treturn true\n}","line":{"from":322,"to":343}} {"id":100028631,"name":"Run","signature":"func (v *dummyController) Run(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (v *dummyController) Run(stopCh \u003c-chan struct{}) {\n}","line":{"from":406,"to":407}} {"id":100028632,"name":"HasSynced","signature":"func (v *dummyController) HasSynced() bool","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (v *dummyController) HasSynced() bool {\n\treturn v.informer.HasSynced()\n}","line":{"from":409,"to":411}} {"id":100028633,"name":"LastSyncResourceVersion","signature":"func (v *dummyController) LastSyncResourceVersion() string","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (v *dummyController) LastSyncResourceVersion() string {\n\treturn \"\"\n}","line":{"from":413,"to":415}} {"id":100028634,"name":"SetWatchErrorHandler","signature":"func (s *sharedIndexInformer) SetWatchErrorHandler(handler WatchErrorHandler) error","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (s *sharedIndexInformer) SetWatchErrorHandler(handler WatchErrorHandler) error {\n\ts.startedLock.Lock()\n\tdefer s.startedLock.Unlock()\n\n\tif s.started {\n\t\treturn fmt.Errorf(\"informer has already started\")\n\t}\n\n\ts.watchErrorHandler = handler\n\treturn nil\n}","line":{"from":431,"to":441}} {"id":100028635,"name":"SetTransform","signature":"func (s *sharedIndexInformer) SetTransform(handler TransformFunc) error","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (s *sharedIndexInformer) SetTransform(handler TransformFunc) error {\n\ts.startedLock.Lock()\n\tdefer s.startedLock.Unlock()\n\n\tif s.started {\n\t\treturn fmt.Errorf(\"informer has already started\")\n\t}\n\n\ts.transform = handler\n\treturn nil\n}","line":{"from":443,"to":453}} {"id":100028636,"name":"Run","signature":"func (s *sharedIndexInformer) Run(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (s *sharedIndexInformer) Run(stopCh \u003c-chan struct{}) {\n\tdefer utilruntime.HandleCrash()\n\n\tif s.HasStarted() {\n\t\tklog.Warningf(\"The sharedIndexInformer has started, run more than once is not allowed\")\n\t\treturn\n\t}\n\tfifo := NewDeltaFIFOWithOptions(DeltaFIFOOptions{\n\t\tKnownObjects: s.indexer,\n\t\tEmitDeltaTypeReplaced: true,\n\t\tTransformer: s.transform,\n\t})\n\n\tcfg := \u0026Config{\n\t\tQueue: fifo,\n\t\tListerWatcher: s.listerWatcher,\n\t\tObjectType: s.objectType,\n\t\tObjectDescription: s.objectDescription,\n\t\tFullResyncPeriod: s.resyncCheckPeriod,\n\t\tRetryOnError: false,\n\t\tShouldResync: s.processor.shouldResync,\n\n\t\tProcess: s.HandleDeltas,\n\t\tWatchErrorHandler: s.watchErrorHandler,\n\t}\n\n\tfunc() {\n\t\ts.startedLock.Lock()\n\t\tdefer s.startedLock.Unlock()\n\n\t\ts.controller = New(cfg)\n\t\ts.controller.(*controller).clock = s.clock\n\t\ts.started = true\n\t}()\n\n\t// Separate stop channel because Processor should be stopped strictly after controller\n\tprocessorStopCh := make(chan struct{})\n\tvar wg wait.Group\n\tdefer wg.Wait() // Wait for Processor to stop\n\tdefer close(processorStopCh) // Tell Processor to stop\n\twg.StartWithChannel(processorStopCh, s.cacheMutationDetector.Run)\n\twg.StartWithChannel(processorStopCh, s.processor.run)\n\n\tdefer func() {\n\t\ts.startedLock.Lock()\n\t\tdefer s.startedLock.Unlock()\n\t\ts.stopped = true // Don't want any new listeners\n\t}()\n\ts.controller.Run(stopCh)\n}","line":{"from":455,"to":504}} {"id":100028637,"name":"HasStarted","signature":"func (s *sharedIndexInformer) HasStarted() bool","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (s *sharedIndexInformer) HasStarted() bool {\n\ts.startedLock.Lock()\n\tdefer s.startedLock.Unlock()\n\treturn s.started\n}","line":{"from":506,"to":510}} {"id":100028638,"name":"HasSynced","signature":"func (s *sharedIndexInformer) HasSynced() bool","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (s *sharedIndexInformer) HasSynced() bool {\n\ts.startedLock.Lock()\n\tdefer s.startedLock.Unlock()\n\n\tif s.controller == nil {\n\t\treturn false\n\t}\n\treturn s.controller.HasSynced()\n}","line":{"from":512,"to":520}} {"id":100028639,"name":"LastSyncResourceVersion","signature":"func (s *sharedIndexInformer) LastSyncResourceVersion() string","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (s *sharedIndexInformer) LastSyncResourceVersion() string {\n\ts.startedLock.Lock()\n\tdefer s.startedLock.Unlock()\n\n\tif s.controller == nil {\n\t\treturn \"\"\n\t}\n\treturn s.controller.LastSyncResourceVersion()\n}","line":{"from":522,"to":530}} {"id":100028640,"name":"GetStore","signature":"func (s *sharedIndexInformer) GetStore() Store","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (s *sharedIndexInformer) GetStore() Store {\n\treturn s.indexer\n}","line":{"from":532,"to":534}} {"id":100028641,"name":"GetIndexer","signature":"func (s *sharedIndexInformer) GetIndexer() Indexer","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (s *sharedIndexInformer) GetIndexer() Indexer {\n\treturn s.indexer\n}","line":{"from":536,"to":538}} {"id":100028642,"name":"AddIndexers","signature":"func (s *sharedIndexInformer) AddIndexers(indexers Indexers) error","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (s *sharedIndexInformer) AddIndexers(indexers Indexers) error {\n\ts.startedLock.Lock()\n\tdefer s.startedLock.Unlock()\n\n\tif s.started {\n\t\treturn fmt.Errorf(\"informer has already started\")\n\t}\n\n\treturn s.indexer.AddIndexers(indexers)\n}","line":{"from":540,"to":549}} {"id":100028643,"name":"GetController","signature":"func (s *sharedIndexInformer) GetController() Controller","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (s *sharedIndexInformer) GetController() Controller {\n\treturn \u0026dummyController{informer: s}\n}","line":{"from":551,"to":553}} {"id":100028644,"name":"AddEventHandler","signature":"func (s *sharedIndexInformer) AddEventHandler(handler ResourceEventHandler) (ResourceEventHandlerRegistration, error)","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (s *sharedIndexInformer) AddEventHandler(handler ResourceEventHandler) (ResourceEventHandlerRegistration, error) {\n\treturn s.AddEventHandlerWithResyncPeriod(handler, s.defaultEventHandlerResyncPeriod)\n}","line":{"from":555,"to":557}} {"id":100028645,"name":"determineResyncPeriod","signature":"func determineResyncPeriod(desired, check time.Duration) time.Duration","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func determineResyncPeriod(desired, check time.Duration) time.Duration {\n\tif desired == 0 {\n\t\treturn desired\n\t}\n\tif check == 0 {\n\t\tklog.Warningf(\"The specified resyncPeriod %v is invalid because this shared informer doesn't support resyncing\", desired)\n\t\treturn 0\n\t}\n\tif desired \u003c check {\n\t\tklog.Warningf(\"The specified resyncPeriod %v is being increased to the minimum resyncCheckPeriod %v\", desired, check)\n\t\treturn check\n\t}\n\treturn desired\n}","line":{"from":559,"to":572}} {"id":100028646,"name":"AddEventHandlerWithResyncPeriod","signature":"func (s *sharedIndexInformer) AddEventHandlerWithResyncPeriod(handler ResourceEventHandler, resyncPeriod time.Duration) (ResourceEventHandlerRegistration, error)","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (s *sharedIndexInformer) AddEventHandlerWithResyncPeriod(handler ResourceEventHandler, resyncPeriod time.Duration) (ResourceEventHandlerRegistration, error) {\n\ts.startedLock.Lock()\n\tdefer s.startedLock.Unlock()\n\n\tif s.stopped {\n\t\treturn nil, fmt.Errorf(\"handler %v was not added to shared informer because it has stopped already\", handler)\n\t}\n\n\tif resyncPeriod \u003e 0 {\n\t\tif resyncPeriod \u003c minimumResyncPeriod {\n\t\t\tklog.Warningf(\"resyncPeriod %v is too small. Changing it to the minimum allowed value of %v\", resyncPeriod, minimumResyncPeriod)\n\t\t\tresyncPeriod = minimumResyncPeriod\n\t\t}\n\n\t\tif resyncPeriod \u003c s.resyncCheckPeriod {\n\t\t\tif s.started {\n\t\t\t\tklog.Warningf(\"resyncPeriod %v is smaller than resyncCheckPeriod %v and the informer has already started. Changing it to %v\", resyncPeriod, s.resyncCheckPeriod, s.resyncCheckPeriod)\n\t\t\t\tresyncPeriod = s.resyncCheckPeriod\n\t\t\t} else {\n\t\t\t\t// if the event handler's resyncPeriod is smaller than the current resyncCheckPeriod, update\n\t\t\t\t// resyncCheckPeriod to match resyncPeriod and adjust the resync periods of all the listeners\n\t\t\t\t// accordingly\n\t\t\t\ts.resyncCheckPeriod = resyncPeriod\n\t\t\t\ts.processor.resyncCheckPeriodChanged(resyncPeriod)\n\t\t\t}\n\t\t}\n\t}\n\n\tlistener := newProcessListener(handler, resyncPeriod, determineResyncPeriod(resyncPeriod, s.resyncCheckPeriod), s.clock.Now(), initialBufferSize, s.HasSynced)\n\n\tif !s.started {\n\t\treturn s.processor.addListener(listener), nil\n\t}\n\n\t// in order to safely join, we have to\n\t// 1. stop sending add/update/delete notifications\n\t// 2. do a list against the store\n\t// 3. send synthetic \"Add\" events to the new handler\n\t// 4. unblock\n\ts.blockDeltas.Lock()\n\tdefer s.blockDeltas.Unlock()\n\n\thandle := s.processor.addListener(listener)\n\tfor _, item := range s.indexer.List() {\n\t\t// Note that we enqueue these notifications with the lock held\n\t\t// and before returning the handle. That means there is never a\n\t\t// chance for anyone to call the handle's HasSynced method in a\n\t\t// state when it would falsely return true (i.e., when the\n\t\t// shared informer is synced but it has not observed an Add\n\t\t// with isInitialList being true, nor when the thread\n\t\t// processing notifications somehow goes faster than this\n\t\t// thread adding them and the counter is temporarily zero).\n\t\tlistener.add(addNotification{newObj: item, isInInitialList: true})\n\t}\n\treturn handle, nil\n}","line":{"from":576,"to":631}} {"id":100028647,"name":"HandleDeltas","signature":"func (s *sharedIndexInformer) HandleDeltas(obj interface{}, isInInitialList bool) error","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (s *sharedIndexInformer) HandleDeltas(obj interface{}, isInInitialList bool) error {\n\ts.blockDeltas.Lock()\n\tdefer s.blockDeltas.Unlock()\n\n\tif deltas, ok := obj.(Deltas); ok {\n\t\treturn processDeltas(s, s.indexer, deltas, isInInitialList)\n\t}\n\treturn errors.New(\"object given as Process argument is not Deltas\")\n}","line":{"from":633,"to":641}} {"id":100028648,"name":"OnAdd","signature":"func (s *sharedIndexInformer) OnAdd(obj interface{}, isInInitialList bool)","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"// Conforms to ResourceEventHandler\nfunc (s *sharedIndexInformer) OnAdd(obj interface{}, isInInitialList bool) {\n\t// Invocation of this function is locked under s.blockDeltas, so it is\n\t// save to distribute the notification\n\ts.cacheMutationDetector.AddObject(obj)\n\ts.processor.distribute(addNotification{newObj: obj, isInInitialList: isInInitialList}, false)\n}","line":{"from":643,"to":649}} {"id":100028649,"name":"OnUpdate","signature":"func (s *sharedIndexInformer) OnUpdate(old, new interface{})","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"// Conforms to ResourceEventHandler\nfunc (s *sharedIndexInformer) OnUpdate(old, new interface{}) {\n\tisSync := false\n\n\t// If is a Sync event, isSync should be true\n\t// If is a Replaced event, isSync is true if resource version is unchanged.\n\t// If RV is unchanged: this is a Sync/Replaced event, so isSync is true\n\n\tif accessor, err := meta.Accessor(new); err == nil {\n\t\tif oldAccessor, err := meta.Accessor(old); err == nil {\n\t\t\t// Events that didn't change resourceVersion are treated as resync events\n\t\t\t// and only propagated to listeners that requested resync\n\t\t\tisSync = accessor.GetResourceVersion() == oldAccessor.GetResourceVersion()\n\t\t}\n\t}\n\n\t// Invocation of this function is locked under s.blockDeltas, so it is\n\t// save to distribute the notification\n\ts.cacheMutationDetector.AddObject(new)\n\ts.processor.distribute(updateNotification{oldObj: old, newObj: new}, isSync)\n}","line":{"from":651,"to":671}} {"id":100028650,"name":"OnDelete","signature":"func (s *sharedIndexInformer) OnDelete(old interface{})","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"// Conforms to ResourceEventHandler\nfunc (s *sharedIndexInformer) OnDelete(old interface{}) {\n\t// Invocation of this function is locked under s.blockDeltas, so it is\n\t// save to distribute the notification\n\ts.processor.distribute(deleteNotification{oldObj: old}, false)\n}","line":{"from":673,"to":678}} {"id":100028651,"name":"IsStopped","signature":"func (s *sharedIndexInformer) IsStopped() bool","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"// IsStopped reports whether the informer has already been stopped\nfunc (s *sharedIndexInformer) IsStopped() bool {\n\ts.startedLock.Lock()\n\tdefer s.startedLock.Unlock()\n\treturn s.stopped\n}","line":{"from":680,"to":685}} {"id":100028652,"name":"RemoveEventHandler","signature":"func (s *sharedIndexInformer) RemoveEventHandler(handle ResourceEventHandlerRegistration) error","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (s *sharedIndexInformer) RemoveEventHandler(handle ResourceEventHandlerRegistration) error {\n\ts.startedLock.Lock()\n\tdefer s.startedLock.Unlock()\n\n\t// in order to safely remove, we have to\n\t// 1. stop sending add/update/delete notifications\n\t// 2. remove and stop listener\n\t// 3. unblock\n\ts.blockDeltas.Lock()\n\tdefer s.blockDeltas.Unlock()\n\treturn s.processor.removeListener(handle)\n}","line":{"from":687,"to":698}} {"id":100028653,"name":"getListener","signature":"func (p *sharedProcessor) getListener(registration ResourceEventHandlerRegistration) *processorListener","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (p *sharedProcessor) getListener(registration ResourceEventHandlerRegistration) *processorListener {\n\tp.listenersLock.RLock()\n\tdefer p.listenersLock.RUnlock()\n\n\tif p.listeners == nil {\n\t\treturn nil\n\t}\n\n\tif result, ok := registration.(*processorListener); ok {\n\t\tif _, exists := p.listeners[result]; exists {\n\t\t\treturn result\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":715,"to":730}} {"id":100028654,"name":"addListener","signature":"func (p *sharedProcessor) addListener(listener *processorListener) ResourceEventHandlerRegistration","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (p *sharedProcessor) addListener(listener *processorListener) ResourceEventHandlerRegistration {\n\tp.listenersLock.Lock()\n\tdefer p.listenersLock.Unlock()\n\n\tif p.listeners == nil {\n\t\tp.listeners = make(map[*processorListener]bool)\n\t}\n\n\tp.listeners[listener] = true\n\n\tif p.listenersStarted {\n\t\tp.wg.Start(listener.run)\n\t\tp.wg.Start(listener.pop)\n\t}\n\n\treturn listener\n}","line":{"from":732,"to":748}} {"id":100028655,"name":"removeListener","signature":"func (p *sharedProcessor) removeListener(handle ResourceEventHandlerRegistration) error","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (p *sharedProcessor) removeListener(handle ResourceEventHandlerRegistration) error {\n\tp.listenersLock.Lock()\n\tdefer p.listenersLock.Unlock()\n\n\tlistener, ok := handle.(*processorListener)\n\tif !ok {\n\t\treturn fmt.Errorf(\"invalid key type %t\", handle)\n\t} else if p.listeners == nil {\n\t\t// No listeners are registered, do nothing\n\t\treturn nil\n\t} else if _, exists := p.listeners[listener]; !exists {\n\t\t// Listener is not registered, just do nothing\n\t\treturn nil\n\t}\n\n\tdelete(p.listeners, listener)\n\n\tif p.listenersStarted {\n\t\tclose(listener.addCh)\n\t}\n\n\treturn nil\n}","line":{"from":750,"to":772}} {"id":100028656,"name":"distribute","signature":"func (p *sharedProcessor) distribute(obj interface{}, sync bool)","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (p *sharedProcessor) distribute(obj interface{}, sync bool) {\n\tp.listenersLock.RLock()\n\tdefer p.listenersLock.RUnlock()\n\n\tfor listener, isSyncing := range p.listeners {\n\t\tswitch {\n\t\tcase !sync:\n\t\t\t// non-sync messages are delivered to every listener\n\t\t\tlistener.add(obj)\n\t\tcase isSyncing:\n\t\t\t// sync messages are delivered to every syncing listener\n\t\t\tlistener.add(obj)\n\t\tdefault:\n\t\t\t// skipping a sync obj for a non-syncing listener\n\t\t}\n\t}\n}","line":{"from":774,"to":790}} {"id":100028657,"name":"run","signature":"func (p *sharedProcessor) run(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (p *sharedProcessor) run(stopCh \u003c-chan struct{}) {\n\tfunc() {\n\t\tp.listenersLock.RLock()\n\t\tdefer p.listenersLock.RUnlock()\n\t\tfor listener := range p.listeners {\n\t\t\tp.wg.Start(listener.run)\n\t\t\tp.wg.Start(listener.pop)\n\t\t}\n\t\tp.listenersStarted = true\n\t}()\n\t\u003c-stopCh\n\n\tp.listenersLock.Lock()\n\tdefer p.listenersLock.Unlock()\n\tfor listener := range p.listeners {\n\t\tclose(listener.addCh) // Tell .pop() to stop. .pop() will tell .run() to stop\n\t}\n\n\t// Wipe out list of listeners since they are now closed\n\t// (processorListener cannot be re-used)\n\tp.listeners = nil\n\n\t// Reset to false since no listeners are running\n\tp.listenersStarted = false\n\n\tp.wg.Wait() // Wait for all .pop() and .run() to stop\n}","line":{"from":792,"to":818}} {"id":100028658,"name":"shouldResync","signature":"func (p *sharedProcessor) shouldResync() bool","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"// shouldResync queries every listener to determine if any of them need a resync, based on each\n// listener's resyncPeriod.\nfunc (p *sharedProcessor) shouldResync() bool {\n\tp.listenersLock.Lock()\n\tdefer p.listenersLock.Unlock()\n\n\tresyncNeeded := false\n\tnow := p.clock.Now()\n\tfor listener := range p.listeners {\n\t\t// need to loop through all the listeners to see if they need to resync so we can prepare any\n\t\t// listeners that are going to be resyncing.\n\t\tshouldResync := listener.shouldResync(now)\n\t\tp.listeners[listener] = shouldResync\n\n\t\tif shouldResync {\n\t\t\tresyncNeeded = true\n\t\t\tlistener.determineNextResync(now)\n\t\t}\n\t}\n\treturn resyncNeeded\n}","line":{"from":820,"to":840}} {"id":100028659,"name":"resyncCheckPeriodChanged","signature":"func (p *sharedProcessor) resyncCheckPeriodChanged(resyncCheckPeriod time.Duration)","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (p *sharedProcessor) resyncCheckPeriodChanged(resyncCheckPeriod time.Duration) {\n\tp.listenersLock.RLock()\n\tdefer p.listenersLock.RUnlock()\n\n\tfor listener := range p.listeners {\n\t\tresyncPeriod := determineResyncPeriod(\n\t\t\tlistener.requestedResyncPeriod, resyncCheckPeriod)\n\t\tlistener.setResyncPeriod(resyncPeriod)\n\t}\n}","line":{"from":842,"to":851}} {"id":100028660,"name":"HasSynced","signature":"func (p *processorListener) HasSynced() bool","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"// HasSynced returns true if the source informer has synced, and all\n// corresponding events have been delivered.\nfunc (p *processorListener) HasSynced() bool {\n\treturn p.syncTracker.HasSynced()\n}","line":{"from":902,"to":906}} {"id":100028661,"name":"newProcessListener","signature":"func newProcessListener(handler ResourceEventHandler, requestedResyncPeriod, resyncPeriod time.Duration, now time.Time, bufferSize int, hasSynced func() bool) *processorListener","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func newProcessListener(handler ResourceEventHandler, requestedResyncPeriod, resyncPeriod time.Duration, now time.Time, bufferSize int, hasSynced func() bool) *processorListener {\n\tret := \u0026processorListener{\n\t\tnextCh: make(chan interface{}),\n\t\taddCh: make(chan interface{}),\n\t\thandler: handler,\n\t\tsyncTracker: \u0026synctrack.SingleFileTracker{UpstreamHasSynced: hasSynced},\n\t\tpendingNotifications: *buffer.NewRingGrowing(bufferSize),\n\t\trequestedResyncPeriod: requestedResyncPeriod,\n\t\tresyncPeriod: resyncPeriod,\n\t}\n\n\tret.determineNextResync(now)\n\n\treturn ret\n}","line":{"from":908,"to":922}} {"id":100028662,"name":"add","signature":"func (p *processorListener) add(notification interface{})","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (p *processorListener) add(notification interface{}) {\n\tif a, ok := notification.(addNotification); ok \u0026\u0026 a.isInInitialList {\n\t\tp.syncTracker.Start()\n\t}\n\tp.addCh \u003c- notification\n}","line":{"from":924,"to":929}} {"id":100028663,"name":"pop","signature":"func (p *processorListener) pop()","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (p *processorListener) pop() {\n\tdefer utilruntime.HandleCrash()\n\tdefer close(p.nextCh) // Tell .run() to stop\n\n\tvar nextCh chan\u003c- interface{}\n\tvar notification interface{}\n\tfor {\n\t\tselect {\n\t\tcase nextCh \u003c- notification:\n\t\t\t// Notification dispatched\n\t\t\tvar ok bool\n\t\t\tnotification, ok = p.pendingNotifications.ReadOne()\n\t\t\tif !ok { // Nothing to pop\n\t\t\t\tnextCh = nil // Disable this select case\n\t\t\t}\n\t\tcase notificationToAdd, ok := \u003c-p.addCh:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif notification == nil { // No notification to pop (and pendingNotifications is empty)\n\t\t\t\t// Optimize the case - skip adding to pendingNotifications\n\t\t\t\tnotification = notificationToAdd\n\t\t\t\tnextCh = p.nextCh\n\t\t\t} else { // There is already a notification waiting to be dispatched\n\t\t\t\tp.pendingNotifications.WriteOne(notificationToAdd)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":931,"to":959}} {"id":100028664,"name":"run","signature":"func (p *processorListener) run()","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (p *processorListener) run() {\n\t// this call blocks until the channel is closed. When a panic happens during the notification\n\t// we will catch it, **the offending item will be skipped!**, and after a short delay (one second)\n\t// the next notification will be attempted. This is usually better than the alternative of never\n\t// delivering again.\n\tstopCh := make(chan struct{})\n\twait.Until(func() {\n\t\tfor next := range p.nextCh {\n\t\t\tswitch notification := next.(type) {\n\t\t\tcase updateNotification:\n\t\t\t\tp.handler.OnUpdate(notification.oldObj, notification.newObj)\n\t\t\tcase addNotification:\n\t\t\t\tp.handler.OnAdd(notification.newObj, notification.isInInitialList)\n\t\t\t\tif notification.isInInitialList {\n\t\t\t\t\tp.syncTracker.Finished()\n\t\t\t\t}\n\t\t\tcase deleteNotification:\n\t\t\t\tp.handler.OnDelete(notification.oldObj)\n\t\t\tdefault:\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"unrecognized notification: %T\", next))\n\t\t\t}\n\t\t}\n\t\t// the only way to get here is if the p.nextCh is empty and closed\n\t\tclose(stopCh)\n\t}, 1*time.Second, stopCh)\n}","line":{"from":961,"to":986}} {"id":100028665,"name":"shouldResync","signature":"func (p *processorListener) shouldResync(now time.Time) bool","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"// shouldResync deterimines if the listener needs a resync. If the listener's resyncPeriod is 0,\n// this always returns false.\nfunc (p *processorListener) shouldResync(now time.Time) bool {\n\tp.resyncLock.Lock()\n\tdefer p.resyncLock.Unlock()\n\n\tif p.resyncPeriod == 0 {\n\t\treturn false\n\t}\n\n\treturn now.After(p.nextResync) || now.Equal(p.nextResync)\n}","line":{"from":988,"to":999}} {"id":100028666,"name":"determineNextResync","signature":"func (p *processorListener) determineNextResync(now time.Time)","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (p *processorListener) determineNextResync(now time.Time) {\n\tp.resyncLock.Lock()\n\tdefer p.resyncLock.Unlock()\n\n\tp.nextResync = now.Add(p.resyncPeriod)\n}","line":{"from":1001,"to":1006}} {"id":100028667,"name":"setResyncPeriod","signature":"func (p *processorListener) setResyncPeriod(resyncPeriod time.Duration)","file":"staging/src/k8s.io/client-go/tools/cache/shared_informer.go","code":"func (p *processorListener) setResyncPeriod(resyncPeriod time.Duration) {\n\tp.resyncLock.Lock()\n\tdefer p.resyncLock.Unlock()\n\n\tp.resyncPeriod = resyncPeriod\n}","line":{"from":1008,"to":1013}} {"id":100028668,"name":"Error","signature":"func (k KeyError) Error() string","file":"staging/src/k8s.io/client-go/tools/cache/store.go","code":"// Error gives a human-readable description of the error.\nfunc (k KeyError) Error() string {\n\treturn fmt.Sprintf(\"couldn't create key for object %+v: %v\", k.Obj, k.Err)\n}","line":{"from":83,"to":86}} {"id":100028669,"name":"Unwrap","signature":"func (k KeyError) Unwrap() error","file":"staging/src/k8s.io/client-go/tools/cache/store.go","code":"// Unwrap implements errors.Unwrap\nfunc (k KeyError) Unwrap() error {\n\treturn k.Err\n}","line":{"from":88,"to":91}} {"id":100028670,"name":"MetaNamespaceKeyFunc","signature":"func MetaNamespaceKeyFunc(obj interface{}) (string, error)","file":"staging/src/k8s.io/client-go/tools/cache/store.go","code":"// MetaNamespaceKeyFunc is a convenient default KeyFunc which knows how to make\n// keys for API objects which implement meta.Interface.\n// The key uses the format \u003cnamespace\u003e/\u003cname\u003e unless \u003cnamespace\u003e is empty, then\n// it's just \u003cname\u003e.\n//\n// TODO: replace key-as-string with a key-as-struct so that this\n// packing/unpacking won't be necessary.\nfunc MetaNamespaceKeyFunc(obj interface{}) (string, error) {\n\tif key, ok := obj.(ExplicitKey); ok {\n\t\treturn string(key), nil\n\t}\n\tmeta, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"object has no meta: %v\", err)\n\t}\n\tif len(meta.GetNamespace()) \u003e 0 {\n\t\treturn meta.GetNamespace() + \"/\" + meta.GetName(), nil\n\t}\n\treturn meta.GetName(), nil\n}","line":{"from":97,"to":116}} {"id":100028671,"name":"SplitMetaNamespaceKey","signature":"func SplitMetaNamespaceKey(key string) (namespace, name string, err error)","file":"staging/src/k8s.io/client-go/tools/cache/store.go","code":"// SplitMetaNamespaceKey returns the namespace and name that\n// MetaNamespaceKeyFunc encoded into key.\n//\n// TODO: replace key-as-string with a key-as-struct so that this\n// packing/unpacking won't be necessary.\nfunc SplitMetaNamespaceKey(key string) (namespace, name string, err error) {\n\tparts := strings.Split(key, \"/\")\n\tswitch len(parts) {\n\tcase 1:\n\t\t// name only, no namespace\n\t\treturn \"\", parts[0], nil\n\tcase 2:\n\t\t// namespace and name\n\t\treturn parts[0], parts[1], nil\n\t}\n\n\treturn \"\", \"\", fmt.Errorf(\"unexpected key format: %q\", key)\n}","line":{"from":118,"to":135}} {"id":100028672,"name":"Add","signature":"func (c *cache) Add(obj interface{}) error","file":"staging/src/k8s.io/client-go/tools/cache/store.go","code":"// Add inserts an item into the cache.\nfunc (c *cache) Add(obj interface{}) error {\n\tkey, err := c.keyFunc(obj)\n\tif err != nil {\n\t\treturn KeyError{obj, err}\n\t}\n\tc.cacheStorage.Add(key, obj)\n\treturn nil\n}","line":{"from":149,"to":157}} {"id":100028673,"name":"Update","signature":"func (c *cache) Update(obj interface{}) error","file":"staging/src/k8s.io/client-go/tools/cache/store.go","code":"// Update sets an item in the cache to its updated state.\nfunc (c *cache) Update(obj interface{}) error {\n\tkey, err := c.keyFunc(obj)\n\tif err != nil {\n\t\treturn KeyError{obj, err}\n\t}\n\tc.cacheStorage.Update(key, obj)\n\treturn nil\n}","line":{"from":159,"to":167}} {"id":100028674,"name":"Delete","signature":"func (c *cache) Delete(obj interface{}) error","file":"staging/src/k8s.io/client-go/tools/cache/store.go","code":"// Delete removes an item from the cache.\nfunc (c *cache) Delete(obj interface{}) error {\n\tkey, err := c.keyFunc(obj)\n\tif err != nil {\n\t\treturn KeyError{obj, err}\n\t}\n\tc.cacheStorage.Delete(key)\n\treturn nil\n}","line":{"from":169,"to":177}} {"id":100028675,"name":"List","signature":"func (c *cache) List() []interface{}","file":"staging/src/k8s.io/client-go/tools/cache/store.go","code":"// List returns a list of all the items.\n// List is completely threadsafe as long as you treat all items as immutable.\nfunc (c *cache) List() []interface{} {\n\treturn c.cacheStorage.List()\n}","line":{"from":179,"to":183}} {"id":100028676,"name":"ListKeys","signature":"func (c *cache) ListKeys() []string","file":"staging/src/k8s.io/client-go/tools/cache/store.go","code":"// ListKeys returns a list of all the keys of the objects currently\n// in the cache.\nfunc (c *cache) ListKeys() []string {\n\treturn c.cacheStorage.ListKeys()\n}","line":{"from":185,"to":189}} {"id":100028677,"name":"GetIndexers","signature":"func (c *cache) GetIndexers() Indexers","file":"staging/src/k8s.io/client-go/tools/cache/store.go","code":"// GetIndexers returns the indexers of cache\nfunc (c *cache) GetIndexers() Indexers {\n\treturn c.cacheStorage.GetIndexers()\n}","line":{"from":191,"to":194}} {"id":100028678,"name":"Index","signature":"func (c *cache) Index(indexName string, obj interface{}) ([]interface{}, error)","file":"staging/src/k8s.io/client-go/tools/cache/store.go","code":"// Index returns a list of items that match on the index function\n// Index is thread-safe so long as you treat all items as immutable\nfunc (c *cache) Index(indexName string, obj interface{}) ([]interface{}, error) {\n\treturn c.cacheStorage.Index(indexName, obj)\n}","line":{"from":196,"to":200}} {"id":100028679,"name":"IndexKeys","signature":"func (c *cache) IndexKeys(indexName, indexedValue string) ([]string, error)","file":"staging/src/k8s.io/client-go/tools/cache/store.go","code":"// IndexKeys returns the storage keys of the stored objects whose set of\n// indexed values for the named index includes the given indexed value.\n// The returned keys are suitable to pass to GetByKey().\nfunc (c *cache) IndexKeys(indexName, indexedValue string) ([]string, error) {\n\treturn c.cacheStorage.IndexKeys(indexName, indexedValue)\n}","line":{"from":202,"to":207}} {"id":100028680,"name":"ListIndexFuncValues","signature":"func (c *cache) ListIndexFuncValues(indexName string) []string","file":"staging/src/k8s.io/client-go/tools/cache/store.go","code":"// ListIndexFuncValues returns the list of generated values of an Index func\nfunc (c *cache) ListIndexFuncValues(indexName string) []string {\n\treturn c.cacheStorage.ListIndexFuncValues(indexName)\n}","line":{"from":209,"to":212}} {"id":100028681,"name":"ByIndex","signature":"func (c *cache) ByIndex(indexName, indexedValue string) ([]interface{}, error)","file":"staging/src/k8s.io/client-go/tools/cache/store.go","code":"// ByIndex returns the stored objects whose set of indexed values\n// for the named index includes the given indexed value.\nfunc (c *cache) ByIndex(indexName, indexedValue string) ([]interface{}, error) {\n\treturn c.cacheStorage.ByIndex(indexName, indexedValue)\n}","line":{"from":214,"to":218}} {"id":100028682,"name":"AddIndexers","signature":"func (c *cache) AddIndexers(newIndexers Indexers) error","file":"staging/src/k8s.io/client-go/tools/cache/store.go","code":"func (c *cache) AddIndexers(newIndexers Indexers) error {\n\treturn c.cacheStorage.AddIndexers(newIndexers)\n}","line":{"from":220,"to":222}} {"id":100028683,"name":"Get","signature":"func (c *cache) Get(obj interface{}) (item interface{}, exists bool, err error)","file":"staging/src/k8s.io/client-go/tools/cache/store.go","code":"// Get returns the requested item, or sets exists=false.\n// Get is completely threadsafe as long as you treat all items as immutable.\nfunc (c *cache) Get(obj interface{}) (item interface{}, exists bool, err error) {\n\tkey, err := c.keyFunc(obj)\n\tif err != nil {\n\t\treturn nil, false, KeyError{obj, err}\n\t}\n\treturn c.GetByKey(key)\n}","line":{"from":224,"to":232}} {"id":100028684,"name":"GetByKey","signature":"func (c *cache) GetByKey(key string) (item interface{}, exists bool, err error)","file":"staging/src/k8s.io/client-go/tools/cache/store.go","code":"// GetByKey returns the request item, or exists=false.\n// GetByKey is completely threadsafe as long as you treat all items as immutable.\nfunc (c *cache) GetByKey(key string) (item interface{}, exists bool, err error) {\n\titem, exists = c.cacheStorage.Get(key)\n\treturn item, exists, nil\n}","line":{"from":234,"to":239}} {"id":100028685,"name":"Replace","signature":"func (c *cache) Replace(list []interface{}, resourceVersion string) error","file":"staging/src/k8s.io/client-go/tools/cache/store.go","code":"// Replace will delete the contents of 'c', using instead the given list.\n// 'c' takes ownership of the list, you should not reference the list again\n// after calling this function.\nfunc (c *cache) Replace(list []interface{}, resourceVersion string) error {\n\titems := make(map[string]interface{}, len(list))\n\tfor _, item := range list {\n\t\tkey, err := c.keyFunc(item)\n\t\tif err != nil {\n\t\t\treturn KeyError{item, err}\n\t\t}\n\t\titems[key] = item\n\t}\n\tc.cacheStorage.Replace(items, resourceVersion)\n\treturn nil\n}","line":{"from":241,"to":255}} {"id":100028686,"name":"Resync","signature":"func (c *cache) Resync() error","file":"staging/src/k8s.io/client-go/tools/cache/store.go","code":"// Resync is meaningless for one of these\nfunc (c *cache) Resync() error {\n\treturn nil\n}","line":{"from":257,"to":260}} {"id":100028687,"name":"NewStore","signature":"func NewStore(keyFunc KeyFunc) Store","file":"staging/src/k8s.io/client-go/tools/cache/store.go","code":"// NewStore returns a Store implemented simply with a map and a lock.\nfunc NewStore(keyFunc KeyFunc) Store {\n\treturn \u0026cache{\n\t\tcacheStorage: NewThreadSafeStore(Indexers{}, Indices{}),\n\t\tkeyFunc: keyFunc,\n\t}\n}","line":{"from":262,"to":268}} {"id":100028688,"name":"NewIndexer","signature":"func NewIndexer(keyFunc KeyFunc, indexers Indexers) Indexer","file":"staging/src/k8s.io/client-go/tools/cache/store.go","code":"// NewIndexer returns an Indexer implemented simply with a map and a lock.\nfunc NewIndexer(keyFunc KeyFunc, indexers Indexers) Indexer {\n\treturn \u0026cache{\n\t\tcacheStorage: NewThreadSafeStore(indexers, Indices{}),\n\t\tkeyFunc: keyFunc,\n\t}\n}","line":{"from":270,"to":276}} {"id":100028689,"name":"get","signature":"func (e *cacheEntry[T]) get() (T, error)","file":"staging/src/k8s.io/client-go/tools/cache/synctrack/lazy.go","code":"func (e *cacheEntry[T]) get() (T, error) {\n\tif cur := func() *T {\n\t\te.lock.RLock()\n\t\tdefer e.lock.RUnlock()\n\t\treturn e.result\n\t}(); cur != nil {\n\t\treturn *cur, nil\n\t}\n\n\te.lock.Lock()\n\tdefer e.lock.Unlock()\n\tif e.result != nil {\n\t\treturn *e.result, nil\n\t}\n\tr, err := e.eval()\n\tif err == nil {\n\t\te.result = \u0026r\n\t}\n\treturn r, err\n}","line":{"from":38,"to":57}} {"id":100028690,"name":"newCacheEntry","signature":"func (z *Lazy[T]) newCacheEntry() *cacheEntry[T]","file":"staging/src/k8s.io/client-go/tools/cache/synctrack/lazy.go","code":"func (z *Lazy[T]) newCacheEntry() *cacheEntry[T] {\n\treturn \u0026cacheEntry[T]{eval: z.Evaluate}\n}","line":{"from":59,"to":61}} {"id":100028691,"name":"Notify","signature":"func (z *Lazy[T]) Notify() { z.cache.Swap(z.newCacheEntry()) }","file":"staging/src/k8s.io/client-go/tools/cache/synctrack/lazy.go","code":"// Notify should be called when something has changed necessitating a new call\n// to Evaluate.\nfunc (z *Lazy[T]) Notify() { z.cache.Swap(z.newCacheEntry()) }","line":{"from":63,"to":65}} {"id":100028692,"name":"Get","signature":"func (z *Lazy[T]) Get() (T, error)","file":"staging/src/k8s.io/client-go/tools/cache/synctrack/lazy.go","code":"// Get should be called to get the current result of a call to Evaluate. If the\n// current cached value is stale (due to a call to Notify), then Evaluate will\n// be called synchronously. If subsequent calls to Get happen (without another\n// Notify), they will all wait for the same return value.\n//\n// Error returns are not cached and will cause multiple calls to evaluate!\nfunc (z *Lazy[T]) Get() (T, error) {\n\te := z.cache.Load()\n\tif e == nil {\n\t\t// Since we don't force a constructor, nil is a possible value.\n\t\t// If multiple Gets race to set this, the swap makes sure only\n\t\t// one wins.\n\t\tz.cache.CompareAndSwap(nil, z.newCacheEntry())\n\t\te = z.cache.Load()\n\t}\n\treturn e.get()\n}","line":{"from":67,"to":83}} {"id":100028693,"name":"Start","signature":"func (t *AsyncTracker[T]) Start(key T)","file":"staging/src/k8s.io/client-go/tools/cache/synctrack/synctrack.go","code":"// Start should be called prior to processing each key which is part of the\n// initial list.\nfunc (t *AsyncTracker[T]) Start(key T) {\n\tt.lock.Lock()\n\tdefer t.lock.Unlock()\n\tif t.waiting == nil {\n\t\tt.waiting = sets.New[T](key)\n\t} else {\n\t\tt.waiting.Insert(key)\n\t}\n}","line":{"from":37,"to":47}} {"id":100028694,"name":"Finished","signature":"func (t *AsyncTracker[T]) Finished(key T)","file":"staging/src/k8s.io/client-go/tools/cache/synctrack/synctrack.go","code":"// Finished should be called when finished processing a key which was part of\n// the initial list. Since keys are tracked individually, nothing bad happens\n// if you call Finished without a corresponding call to Start. This makes it\n// easier to use this in combination with e.g. queues which don't make it easy\n// to plumb through the isInInitialList boolean.\nfunc (t *AsyncTracker[T]) Finished(key T) {\n\tt.lock.Lock()\n\tdefer t.lock.Unlock()\n\tif t.waiting != nil {\n\t\tt.waiting.Delete(key)\n\t}\n}","line":{"from":49,"to":60}} {"id":100028695,"name":"HasSynced","signature":"func (t *AsyncTracker[T]) HasSynced() bool","file":"staging/src/k8s.io/client-go/tools/cache/synctrack/synctrack.go","code":"// HasSynced returns true if the source is synced and every key present in the\n// initial list has been processed. This relies on the source not considering\n// itself synced until *after* it has delivered the notification for the last\n// key, and that notification handler must have called Start.\nfunc (t *AsyncTracker[T]) HasSynced() bool {\n\t// Call UpstreamHasSynced first: it might take a lock, which might take\n\t// a significant amount of time, and we can't hold our lock while\n\t// waiting on that or a user is likely to get a deadlock.\n\tif !t.UpstreamHasSynced() {\n\t\treturn false\n\t}\n\tt.lock.Lock()\n\tdefer t.lock.Unlock()\n\treturn t.waiting.Len() == 0\n}","line":{"from":62,"to":76}} {"id":100028696,"name":"Start","signature":"func (t *SingleFileTracker) Start()","file":"staging/src/k8s.io/client-go/tools/cache/synctrack/synctrack.go","code":"// Start should be called prior to processing each key which is part of the\n// initial list.\nfunc (t *SingleFileTracker) Start() {\n\tatomic.AddInt64(\u0026t.count, 1)\n}","line":{"from":90,"to":94}} {"id":100028697,"name":"Finished","signature":"func (t *SingleFileTracker) Finished()","file":"staging/src/k8s.io/client-go/tools/cache/synctrack/synctrack.go","code":"// Finished should be called when finished processing a key which was part of\n// the initial list. You must never call Finished() before (or without) its\n// corresponding Start(), that is a logic error that could cause HasSynced to\n// return a wrong value. To help you notice this should it happen, Finished()\n// will panic if the internal counter goes negative.\nfunc (t *SingleFileTracker) Finished() {\n\tresult := atomic.AddInt64(\u0026t.count, -1)\n\tif result \u003c 0 {\n\t\tpanic(\"synctrack: negative counter; this logic error means HasSynced may return incorrect value\")\n\t}\n}","line":{"from":96,"to":106}} {"id":100028698,"name":"HasSynced","signature":"func (t *SingleFileTracker) HasSynced() bool","file":"staging/src/k8s.io/client-go/tools/cache/synctrack/synctrack.go","code":"// HasSynced returns true if the source is synced and every key present in the\n// initial list has been processed. This relies on the source not considering\n// itself synced until *after* it has delivered the notification for the last\n// key, and that notification handler must have called Start.\nfunc (t *SingleFileTracker) HasSynced() bool {\n\t// Call UpstreamHasSynced first: it might take a lock, which might take\n\t// a significant amount of time, and we don't want to then act on a\n\t// stale count value.\n\tif !t.UpstreamHasSynced() {\n\t\treturn false\n\t}\n\treturn atomic.LoadInt64(\u0026t.count) \u003c= 0\n}","line":{"from":108,"to":120}} {"id":100028699,"name":"reset","signature":"func (i *storeIndex) reset()","file":"staging/src/k8s.io/client-go/tools/cache/thread_safe_store.go","code":"func (i *storeIndex) reset() {\n\ti.indices = Indices{}\n}","line":{"from":70,"to":72}} {"id":100028700,"name":"getKeysFromIndex","signature":"func (i *storeIndex) getKeysFromIndex(indexName string, obj interface{}) (sets.String, error)","file":"staging/src/k8s.io/client-go/tools/cache/thread_safe_store.go","code":"func (i *storeIndex) getKeysFromIndex(indexName string, obj interface{}) (sets.String, error) {\n\tindexFunc := i.indexers[indexName]\n\tif indexFunc == nil {\n\t\treturn nil, fmt.Errorf(\"Index with name %s does not exist\", indexName)\n\t}\n\n\tindexedValues, err := indexFunc(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tindex := i.indices[indexName]\n\n\tvar storeKeySet sets.String\n\tif len(indexedValues) == 1 {\n\t\t// In majority of cases, there is exactly one value matching.\n\t\t// Optimize the most common path - deduping is not needed here.\n\t\tstoreKeySet = index[indexedValues[0]]\n\t} else {\n\t\t// Need to de-dupe the return list.\n\t\t// Since multiple keys are allowed, this can happen.\n\t\tstoreKeySet = sets.String{}\n\t\tfor _, indexedValue := range indexedValues {\n\t\t\tfor key := range index[indexedValue] {\n\t\t\t\tstoreKeySet.Insert(key)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn storeKeySet, nil\n}","line":{"from":74,"to":103}} {"id":100028701,"name":"getKeysByIndex","signature":"func (i *storeIndex) getKeysByIndex(indexName, indexedValue string) (sets.String, error)","file":"staging/src/k8s.io/client-go/tools/cache/thread_safe_store.go","code":"func (i *storeIndex) getKeysByIndex(indexName, indexedValue string) (sets.String, error) {\n\tindexFunc := i.indexers[indexName]\n\tif indexFunc == nil {\n\t\treturn nil, fmt.Errorf(\"Index with name %s does not exist\", indexName)\n\t}\n\n\tindex := i.indices[indexName]\n\treturn index[indexedValue], nil\n}","line":{"from":105,"to":113}} {"id":100028702,"name":"getIndexValues","signature":"func (i *storeIndex) getIndexValues(indexName string) []string","file":"staging/src/k8s.io/client-go/tools/cache/thread_safe_store.go","code":"func (i *storeIndex) getIndexValues(indexName string) []string {\n\tindex := i.indices[indexName]\n\tnames := make([]string, 0, len(index))\n\tfor key := range index {\n\t\tnames = append(names, key)\n\t}\n\treturn names\n}","line":{"from":115,"to":122}} {"id":100028703,"name":"addIndexers","signature":"func (i *storeIndex) addIndexers(newIndexers Indexers) error","file":"staging/src/k8s.io/client-go/tools/cache/thread_safe_store.go","code":"func (i *storeIndex) addIndexers(newIndexers Indexers) error {\n\toldKeys := sets.StringKeySet(i.indexers)\n\tnewKeys := sets.StringKeySet(newIndexers)\n\n\tif oldKeys.HasAny(newKeys.List()...) {\n\t\treturn fmt.Errorf(\"indexer conflict: %v\", oldKeys.Intersection(newKeys))\n\t}\n\n\tfor k, v := range newIndexers {\n\t\ti.indexers[k] = v\n\t}\n\treturn nil\n}","line":{"from":124,"to":136}} {"id":100028704,"name":"updateIndices","signature":"func (i *storeIndex) updateIndices(oldObj interface{}, newObj interface{}, key string)","file":"staging/src/k8s.io/client-go/tools/cache/thread_safe_store.go","code":"// updateIndices modifies the objects location in the managed indexes:\n// - for create you must provide only the newObj\n// - for update you must provide both the oldObj and the newObj\n// - for delete you must provide only the oldObj\n// updateIndices must be called from a function that already has a lock on the cache\nfunc (i *storeIndex) updateIndices(oldObj interface{}, newObj interface{}, key string) {\n\tvar oldIndexValues, indexValues []string\n\tvar err error\n\tfor name, indexFunc := range i.indexers {\n\t\tif oldObj != nil {\n\t\t\toldIndexValues, err = indexFunc(oldObj)\n\t\t} else {\n\t\t\toldIndexValues = oldIndexValues[:0]\n\t\t}\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"unable to calculate an index entry for key %q on index %q: %v\", key, name, err))\n\t\t}\n\n\t\tif newObj != nil {\n\t\t\tindexValues, err = indexFunc(newObj)\n\t\t} else {\n\t\t\tindexValues = indexValues[:0]\n\t\t}\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"unable to calculate an index entry for key %q on index %q: %v\", key, name, err))\n\t\t}\n\n\t\tindex := i.indices[name]\n\t\tif index == nil {\n\t\t\tindex = Index{}\n\t\t\ti.indices[name] = index\n\t\t}\n\n\t\tif len(indexValues) == 1 \u0026\u0026 len(oldIndexValues) == 1 \u0026\u0026 indexValues[0] == oldIndexValues[0] {\n\t\t\t// We optimize for the most common case where indexFunc returns a single value which has not been changed\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, value := range oldIndexValues {\n\t\t\ti.deleteKeyFromIndex(key, value, index)\n\t\t}\n\t\tfor _, value := range indexValues {\n\t\t\ti.addKeyToIndex(key, value, index)\n\t\t}\n\t}\n}","line":{"from":138,"to":183}} {"id":100028705,"name":"addKeyToIndex","signature":"func (i *storeIndex) addKeyToIndex(key, indexValue string, index Index)","file":"staging/src/k8s.io/client-go/tools/cache/thread_safe_store.go","code":"func (i *storeIndex) addKeyToIndex(key, indexValue string, index Index) {\n\tset := index[indexValue]\n\tif set == nil {\n\t\tset = sets.String{}\n\t\tindex[indexValue] = set\n\t}\n\tset.Insert(key)\n}","line":{"from":185,"to":192}} {"id":100028706,"name":"deleteKeyFromIndex","signature":"func (i *storeIndex) deleteKeyFromIndex(key, indexValue string, index Index)","file":"staging/src/k8s.io/client-go/tools/cache/thread_safe_store.go","code":"func (i *storeIndex) deleteKeyFromIndex(key, indexValue string, index Index) {\n\tset := index[indexValue]\n\tif set == nil {\n\t\treturn\n\t}\n\tset.Delete(key)\n\t// If we don't delete the set when zero, indices with high cardinality\n\t// short lived resources can cause memory to increase over time from\n\t// unused empty sets. See `kubernetes/kubernetes/issues/84959`.\n\tif len(set) == 0 {\n\t\tdelete(index, indexValue)\n\t}\n}","line":{"from":194,"to":206}} {"id":100028707,"name":"Add","signature":"func (c *threadSafeMap) Add(key string, obj interface{})","file":"staging/src/k8s.io/client-go/tools/cache/thread_safe_store.go","code":"func (c *threadSafeMap) Add(key string, obj interface{}) {\n\tc.Update(key, obj)\n}","line":{"from":217,"to":219}} {"id":100028708,"name":"Update","signature":"func (c *threadSafeMap) Update(key string, obj interface{})","file":"staging/src/k8s.io/client-go/tools/cache/thread_safe_store.go","code":"func (c *threadSafeMap) Update(key string, obj interface{}) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\toldObject := c.items[key]\n\tc.items[key] = obj\n\tc.index.updateIndices(oldObject, obj, key)\n}","line":{"from":221,"to":227}} {"id":100028709,"name":"Delete","signature":"func (c *threadSafeMap) Delete(key string)","file":"staging/src/k8s.io/client-go/tools/cache/thread_safe_store.go","code":"func (c *threadSafeMap) Delete(key string) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tif obj, exists := c.items[key]; exists {\n\t\tc.index.updateIndices(obj, nil, key)\n\t\tdelete(c.items, key)\n\t}\n}","line":{"from":229,"to":236}} {"id":100028710,"name":"Get","signature":"func (c *threadSafeMap) Get(key string) (item interface{}, exists bool)","file":"staging/src/k8s.io/client-go/tools/cache/thread_safe_store.go","code":"func (c *threadSafeMap) Get(key string) (item interface{}, exists bool) {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\titem, exists = c.items[key]\n\treturn item, exists\n}","line":{"from":238,"to":243}} {"id":100028711,"name":"List","signature":"func (c *threadSafeMap) List() []interface{}","file":"staging/src/k8s.io/client-go/tools/cache/thread_safe_store.go","code":"func (c *threadSafeMap) List() []interface{} {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\tlist := make([]interface{}, 0, len(c.items))\n\tfor _, item := range c.items {\n\t\tlist = append(list, item)\n\t}\n\treturn list\n}","line":{"from":245,"to":253}} {"id":100028712,"name":"ListKeys","signature":"func (c *threadSafeMap) ListKeys() []string","file":"staging/src/k8s.io/client-go/tools/cache/thread_safe_store.go","code":"// ListKeys returns a list of all the keys of the objects currently\n// in the threadSafeMap.\nfunc (c *threadSafeMap) ListKeys() []string {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\tlist := make([]string, 0, len(c.items))\n\tfor key := range c.items {\n\t\tlist = append(list, key)\n\t}\n\treturn list\n}","line":{"from":255,"to":265}} {"id":100028713,"name":"Replace","signature":"func (c *threadSafeMap) Replace(items map[string]interface{}, resourceVersion string)","file":"staging/src/k8s.io/client-go/tools/cache/thread_safe_store.go","code":"func (c *threadSafeMap) Replace(items map[string]interface{}, resourceVersion string) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tc.items = items\n\n\t// rebuild any index\n\tc.index.reset()\n\tfor key, item := range c.items {\n\t\tc.index.updateIndices(nil, item, key)\n\t}\n}","line":{"from":267,"to":277}} {"id":100028714,"name":"Index","signature":"func (c *threadSafeMap) Index(indexName string, obj interface{}) ([]interface{}, error)","file":"staging/src/k8s.io/client-go/tools/cache/thread_safe_store.go","code":"// Index returns a list of items that match the given object on the index function.\n// Index is thread-safe so long as you treat all items as immutable.\nfunc (c *threadSafeMap) Index(indexName string, obj interface{}) ([]interface{}, error) {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\n\tstoreKeySet, err := c.index.getKeysFromIndex(indexName, obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlist := make([]interface{}, 0, storeKeySet.Len())\n\tfor storeKey := range storeKeySet {\n\t\tlist = append(list, c.items[storeKey])\n\t}\n\treturn list, nil\n}","line":{"from":279,"to":295}} {"id":100028715,"name":"ByIndex","signature":"func (c *threadSafeMap) ByIndex(indexName, indexedValue string) ([]interface{}, error)","file":"staging/src/k8s.io/client-go/tools/cache/thread_safe_store.go","code":"// ByIndex returns a list of the items whose indexed values in the given index include the given indexed value\nfunc (c *threadSafeMap) ByIndex(indexName, indexedValue string) ([]interface{}, error) {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\n\tset, err := c.index.getKeysByIndex(indexName, indexedValue)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlist := make([]interface{}, 0, set.Len())\n\tfor key := range set {\n\t\tlist = append(list, c.items[key])\n\t}\n\n\treturn list, nil\n}","line":{"from":297,"to":312}} {"id":100028716,"name":"IndexKeys","signature":"func (c *threadSafeMap) IndexKeys(indexName, indexedValue string) ([]string, error)","file":"staging/src/k8s.io/client-go/tools/cache/thread_safe_store.go","code":"// IndexKeys returns a list of the Store keys of the objects whose indexed values in the given index include the given indexed value.\n// IndexKeys is thread-safe so long as you treat all items as immutable.\nfunc (c *threadSafeMap) IndexKeys(indexName, indexedValue string) ([]string, error) {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\n\tset, err := c.index.getKeysByIndex(indexName, indexedValue)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn set.List(), nil\n}","line":{"from":314,"to":325}} {"id":100028717,"name":"ListIndexFuncValues","signature":"func (c *threadSafeMap) ListIndexFuncValues(indexName string) []string","file":"staging/src/k8s.io/client-go/tools/cache/thread_safe_store.go","code":"func (c *threadSafeMap) ListIndexFuncValues(indexName string) []string {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\n\treturn c.index.getIndexValues(indexName)\n}","line":{"from":327,"to":332}} {"id":100028718,"name":"GetIndexers","signature":"func (c *threadSafeMap) GetIndexers() Indexers","file":"staging/src/k8s.io/client-go/tools/cache/thread_safe_store.go","code":"func (c *threadSafeMap) GetIndexers() Indexers {\n\treturn c.index.indexers\n}","line":{"from":334,"to":336}} {"id":100028719,"name":"AddIndexers","signature":"func (c *threadSafeMap) AddIndexers(newIndexers Indexers) error","file":"staging/src/k8s.io/client-go/tools/cache/thread_safe_store.go","code":"func (c *threadSafeMap) AddIndexers(newIndexers Indexers) error {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tif len(c.items) \u003e 0 {\n\t\treturn fmt.Errorf(\"cannot add indexers to running index\")\n\t}\n\n\treturn c.index.addIndexers(newIndexers)\n}","line":{"from":338,"to":347}} {"id":100028720,"name":"Resync","signature":"func (c *threadSafeMap) Resync() error","file":"staging/src/k8s.io/client-go/tools/cache/thread_safe_store.go","code":"func (c *threadSafeMap) Resync() error {\n\t// Nothing to do\n\treturn nil\n}","line":{"from":349,"to":352}} {"id":100028721,"name":"NewThreadSafeStore","signature":"func NewThreadSafeStore(indexers Indexers, indices Indices) ThreadSafeStore","file":"staging/src/k8s.io/client-go/tools/cache/thread_safe_store.go","code":"// NewThreadSafeStore creates a new instance of ThreadSafeStore.\nfunc NewThreadSafeStore(indexers Indexers, indices Indices) ThreadSafeStore {\n\treturn \u0026threadSafeMap{\n\t\titems: map[string]interface{}{},\n\t\tindex: \u0026storeIndex{\n\t\t\tindexers: indexers,\n\t\t\tindices: indices,\n\t\t},\n\t}\n}","line":{"from":354,"to":363}} {"id":100028722,"name":"Add","signature":"func (u *UndeltaStore) Add(obj interface{}) error","file":"staging/src/k8s.io/client-go/tools/cache/undelta_store.go","code":"// Add inserts an object into the store and sends complete state by calling PushFunc.\n// Note about thread safety. The Store implementation (cache.cache) uses a lock for all methods.\n// In the functions below, the lock gets released and reacquired betweend the {Add,Delete,etc}\n// and the List. So, the following can happen, resulting in two identical calls to PushFunc.\n// time thread 1 thread 2\n// 0 UndeltaStore.Add(a)\n// 1 UndeltaStore.Add(b)\n// 2 Store.Add(a)\n// 3 Store.Add(b)\n// 4 Store.List() -\u003e [a,b]\n// 5 Store.List() -\u003e [a,b]\nfunc (u *UndeltaStore) Add(obj interface{}) error {\n\tif err := u.Store.Add(obj); err != nil {\n\t\treturn err\n\t}\n\tu.PushFunc(u.Store.List())\n\treturn nil\n}","line":{"from":34,"to":51}} {"id":100028723,"name":"Update","signature":"func (u *UndeltaStore) Update(obj interface{}) error","file":"staging/src/k8s.io/client-go/tools/cache/undelta_store.go","code":"// Update sets an item in the cache to its updated state and sends complete state by calling PushFunc.\nfunc (u *UndeltaStore) Update(obj interface{}) error {\n\tif err := u.Store.Update(obj); err != nil {\n\t\treturn err\n\t}\n\tu.PushFunc(u.Store.List())\n\treturn nil\n}","line":{"from":53,"to":60}} {"id":100028724,"name":"Delete","signature":"func (u *UndeltaStore) Delete(obj interface{}) error","file":"staging/src/k8s.io/client-go/tools/cache/undelta_store.go","code":"// Delete removes an item from the cache and sends complete state by calling PushFunc.\nfunc (u *UndeltaStore) Delete(obj interface{}) error {\n\tif err := u.Store.Delete(obj); err != nil {\n\t\treturn err\n\t}\n\tu.PushFunc(u.Store.List())\n\treturn nil\n}","line":{"from":62,"to":69}} {"id":100028725,"name":"Replace","signature":"func (u *UndeltaStore) Replace(list []interface{}, resourceVersion string) error","file":"staging/src/k8s.io/client-go/tools/cache/undelta_store.go","code":"// Replace will delete the contents of current store, using instead the given list.\n// 'u' takes ownership of the list, you should not reference the list again\n// after calling this function.\n// The new contents complete state will be sent by calling PushFunc after replacement.\nfunc (u *UndeltaStore) Replace(list []interface{}, resourceVersion string) error {\n\tif err := u.Store.Replace(list, resourceVersion); err != nil {\n\t\treturn err\n\t}\n\tu.PushFunc(u.Store.List())\n\treturn nil\n}","line":{"from":71,"to":81}} {"id":100028726,"name":"NewUndeltaStore","signature":"func NewUndeltaStore(pushFunc func([]interface{}), keyFunc KeyFunc) *UndeltaStore","file":"staging/src/k8s.io/client-go/tools/cache/undelta_store.go","code":"// NewUndeltaStore returns an UndeltaStore implemented with a Store.\nfunc NewUndeltaStore(pushFunc func([]interface{}), keyFunc KeyFunc) *UndeltaStore {\n\treturn \u0026UndeltaStore{\n\t\tStore: NewStore(keyFunc),\n\t\tPushFunc: pushFunc,\n\t}\n}","line":{"from":83,"to":89}} {"id":100028727,"name":"init","signature":"func init()","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/helpers.go","code":"func init() {\n\tsDec, _ := base64.StdEncoding.DecodeString(\"REDACTED+\")\n\tredactedBytes = []byte(string(sDec))\n\tsDec, _ = base64.StdEncoding.DecodeString(\"DATA+OMITTED\")\n\tdataOmittedBytes = []byte(string(sDec))\n}","line":{"from":30,"to":35}} {"id":100028728,"name":"IsConfigEmpty","signature":"func IsConfigEmpty(config *Config) bool","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/helpers.go","code":"// IsConfigEmpty returns true if the config is empty.\nfunc IsConfigEmpty(config *Config) bool {\n\treturn len(config.AuthInfos) == 0 \u0026\u0026 len(config.Clusters) == 0 \u0026\u0026 len(config.Contexts) == 0 \u0026\u0026\n\t\tlen(config.CurrentContext) == 0 \u0026\u0026\n\t\tlen(config.Preferences.Extensions) == 0 \u0026\u0026 !config.Preferences.Colors \u0026\u0026\n\t\tlen(config.Extensions) == 0\n}","line":{"from":37,"to":43}} {"id":100028729,"name":"MinifyConfig","signature":"func MinifyConfig(config *Config) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/helpers.go","code":"// MinifyConfig read the current context and uses that to keep only the relevant pieces of config\n// This is useful for making secrets based on kubeconfig files\nfunc MinifyConfig(config *Config) error {\n\tif len(config.CurrentContext) == 0 {\n\t\treturn errors.New(\"current-context must exist in order to minify\")\n\t}\n\n\tcurrContext, exists := config.Contexts[config.CurrentContext]\n\tif !exists {\n\t\treturn fmt.Errorf(\"cannot locate context %v\", config.CurrentContext)\n\t}\n\n\tnewContexts := map[string]*Context{}\n\tnewContexts[config.CurrentContext] = currContext\n\n\tnewClusters := map[string]*Cluster{}\n\tif len(currContext.Cluster) \u003e 0 {\n\t\tif _, exists := config.Clusters[currContext.Cluster]; !exists {\n\t\t\treturn fmt.Errorf(\"cannot locate cluster %v\", currContext.Cluster)\n\t\t}\n\n\t\tnewClusters[currContext.Cluster] = config.Clusters[currContext.Cluster]\n\t}\n\n\tnewAuthInfos := map[string]*AuthInfo{}\n\tif len(currContext.AuthInfo) \u003e 0 {\n\t\tif _, exists := config.AuthInfos[currContext.AuthInfo]; !exists {\n\t\t\treturn fmt.Errorf(\"cannot locate user %v\", currContext.AuthInfo)\n\t\t}\n\n\t\tnewAuthInfos[currContext.AuthInfo] = config.AuthInfos[currContext.AuthInfo]\n\t}\n\n\tconfig.AuthInfos = newAuthInfos\n\tconfig.Clusters = newClusters\n\tconfig.Contexts = newContexts\n\n\treturn nil\n}","line":{"from":45,"to":83}} {"id":100028730,"name":"ShortenConfig","signature":"func ShortenConfig(config *Config)","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/helpers.go","code":"// ShortenConfig redacts raw data entries from the config object for a human-readable view.\nfunc ShortenConfig(config *Config) {\n\t// trick json encoder into printing a human-readable string in the raw data\n\t// by base64 decoding what we want to print. Relies on implementation of\n\t// http://golang.org/pkg/encoding/json/#Marshal using base64 to encode []byte\n\tfor key, authInfo := range config.AuthInfos {\n\t\tif len(authInfo.ClientKeyData) \u003e 0 {\n\t\t\tauthInfo.ClientKeyData = dataOmittedBytes\n\t\t}\n\t\tif len(authInfo.ClientCertificateData) \u003e 0 {\n\t\t\tauthInfo.ClientCertificateData = dataOmittedBytes\n\t\t}\n\t\tif len(authInfo.Token) \u003e 0 {\n\t\t\tauthInfo.Token = \"REDACTED\"\n\t\t}\n\t\tconfig.AuthInfos[key] = authInfo\n\t}\n\tfor key, cluster := range config.Clusters {\n\t\tif len(cluster.CertificateAuthorityData) \u003e 0 {\n\t\t\tcluster.CertificateAuthorityData = dataOmittedBytes\n\t\t}\n\t\tconfig.Clusters[key] = cluster\n\t}\n}","line":{"from":90,"to":113}} {"id":100028731,"name":"FlattenConfig","signature":"func FlattenConfig(config *Config) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/helpers.go","code":"// FlattenConfig changes the config object into a self-contained config (useful for making secrets)\nfunc FlattenConfig(config *Config) error {\n\tfor key, authInfo := range config.AuthInfos {\n\t\tbaseDir, err := MakeAbs(path.Dir(authInfo.LocationOfOrigin), \"\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := FlattenContent(\u0026authInfo.ClientCertificate, \u0026authInfo.ClientCertificateData, baseDir); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := FlattenContent(\u0026authInfo.ClientKey, \u0026authInfo.ClientKeyData, baseDir); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tconfig.AuthInfos[key] = authInfo\n\t}\n\tfor key, cluster := range config.Clusters {\n\t\tbaseDir, err := MakeAbs(path.Dir(cluster.LocationOfOrigin), \"\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := FlattenContent(\u0026cluster.CertificateAuthority, \u0026cluster.CertificateAuthorityData, baseDir); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tconfig.Clusters[key] = cluster\n\t}\n\n\treturn nil\n}","line":{"from":115,"to":146}} {"id":100028732,"name":"FlattenContent","signature":"func FlattenContent(path *string, contents *[]byte, baseDir string) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/helpers.go","code":"func FlattenContent(path *string, contents *[]byte, baseDir string) error {\n\tif len(*path) != 0 {\n\t\tif len(*contents) \u003e 0 {\n\t\t\treturn errors.New(\"cannot have values for both path and contents\")\n\t\t}\n\n\t\tvar err error\n\t\tabsPath := ResolvePath(*path, baseDir)\n\t\t*contents, err = os.ReadFile(absPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t*path = \"\"\n\t}\n\n\treturn nil\n}","line":{"from":148,"to":165}} {"id":100028733,"name":"ResolvePath","signature":"func ResolvePath(path string, base string) string","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/helpers.go","code":"// ResolvePath returns the path as an absolute paths, relative to the given base directory\nfunc ResolvePath(path string, base string) string {\n\t// Don't resolve empty paths\n\tif len(path) \u003e 0 {\n\t\t// Don't resolve absolute paths\n\t\tif !filepath.IsAbs(path) {\n\t\t\treturn filepath.Join(base, path)\n\t\t}\n\t}\n\n\treturn path\n}","line":{"from":167,"to":178}} {"id":100028734,"name":"MakeAbs","signature":"func MakeAbs(path, base string) (string, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/helpers.go","code":"func MakeAbs(path, base string) (string, error) {\n\tif filepath.IsAbs(path) {\n\t\treturn path, nil\n\t}\n\tif len(base) == 0 {\n\t\tcwd, err := os.Getwd()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tbase = cwd\n\t}\n\treturn filepath.Join(base, path), nil\n}","line":{"from":180,"to":192}} {"id":100028735,"name":"RedactSecrets","signature":"func RedactSecrets(config *Config) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/helpers.go","code":"// RedactSecrets replaces any sensitive values with REDACTED\nfunc RedactSecrets(config *Config) error {\n\treturn redactSecrets(reflect.ValueOf(config), false)\n}","line":{"from":194,"to":197}} {"id":100028736,"name":"redactSecrets","signature":"func redactSecrets(curr reflect.Value, redact bool) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/helpers.go","code":"func redactSecrets(curr reflect.Value, redact bool) error {\n\tredactedBytes = []byte(\"REDACTED\")\n\tif !curr.IsValid() {\n\t\treturn nil\n\t}\n\n\tactualCurrValue := curr\n\tif curr.Kind() == reflect.Ptr {\n\t\tactualCurrValue = curr.Elem()\n\t}\n\n\tswitch actualCurrValue.Kind() {\n\tcase reflect.Map:\n\t\tfor _, v := range actualCurrValue.MapKeys() {\n\t\t\terr := redactSecrets(actualCurrValue.MapIndex(v), false)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\n\tcase reflect.String:\n\t\tif redact {\n\t\t\tif !actualCurrValue.IsZero() {\n\t\t\t\tactualCurrValue.SetString(\"REDACTED\")\n\t\t\t}\n\t\t}\n\t\treturn nil\n\n\tcase reflect.Slice:\n\t\tif actualCurrValue.Type() == reflect.TypeOf([]byte{}) \u0026\u0026 redact {\n\t\t\tif !actualCurrValue.IsNil() {\n\t\t\t\tactualCurrValue.SetBytes(redactedBytes)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\tfor i := 0; i \u003c actualCurrValue.Len(); i++ {\n\t\t\terr := redactSecrets(actualCurrValue.Index(i), false)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\n\tcase reflect.Struct:\n\t\tfor fieldIndex := 0; fieldIndex \u003c actualCurrValue.NumField(); fieldIndex++ {\n\t\t\tcurrFieldValue := actualCurrValue.Field(fieldIndex)\n\t\t\tcurrFieldType := actualCurrValue.Type().Field(fieldIndex)\n\t\t\tcurrYamlTag := currFieldType.Tag.Get(\"datapolicy\")\n\t\t\tcurrFieldTypeYamlName := strings.Split(currYamlTag, \",\")[0]\n\t\t\tif currFieldTypeYamlName != \"\" {\n\t\t\t\terr := redactSecrets(currFieldValue, true)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terr := redactSecrets(currFieldValue, false)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\n\tdefault:\n\t\treturn nil\n\t}\n}","line":{"from":199,"to":266}} {"id":100028737,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Config{},\n\t)\n\treturn nil\n}","line":{"from":33,"to":38}} {"id":100028738,"name":"GetObjectKind","signature":"func (obj *Config) GetObjectKind() schema.ObjectKind { return obj }","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/register.go","code":"func (obj *Config) GetObjectKind() schema.ObjectKind { return obj }","line":{"from":40,"to":40}} {"id":100028739,"name":"SetGroupVersionKind","signature":"func (obj *Config) SetGroupVersionKind(gvk schema.GroupVersionKind)","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/register.go","code":"func (obj *Config) SetGroupVersionKind(gvk schema.GroupVersionKind) {\n\tobj.APIVersion, obj.Kind = gvk.ToAPIVersionAndKind()\n}","line":{"from":41,"to":43}} {"id":100028740,"name":"GroupVersionKind","signature":"func (obj *Config) GroupVersionKind() schema.GroupVersionKind","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/register.go","code":"func (obj *Config) GroupVersionKind() schema.GroupVersionKind {\n\treturn schema.FromAPIVersionAndKind(obj.APIVersion, obj.Kind)\n}","line":{"from":44,"to":46}} {"id":100028741,"name":"GoString","signature":"func (c AuthProviderConfig) GoString() string","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/types.go","code":"// GoString implements fmt.GoStringer and sanitizes sensitive fields of\n// AuthProviderConfig to prevent accidental leaking via logs.\nfunc (c AuthProviderConfig) GoString() string {\n\treturn c.String()\n}","line":{"from":185,"to":189}} {"id":100028742,"name":"String","signature":"func (c AuthProviderConfig) String() string","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/types.go","code":"// String implements fmt.Stringer and sanitizes sensitive fields of\n// AuthProviderConfig to prevent accidental leaking via logs.\nfunc (c AuthProviderConfig) String() string {\n\tcfg := \"\u003cnil\u003e\"\n\tif c.Config != nil {\n\t\tcfg = \"--- REDACTED ---\"\n\t}\n\treturn fmt.Sprintf(\"api.AuthProviderConfig{Name: %q, Config: map[string]string{%s}}\", c.Name, cfg)\n}","line":{"from":191,"to":199}} {"id":100028743,"name":"GoString","signature":"func (c ExecConfig) GoString() string","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/types.go","code":"// GoString implements fmt.GoStringer and sanitizes sensitive fields of\n// ExecConfig to prevent accidental leaking via logs.\nfunc (c ExecConfig) GoString() string {\n\treturn c.String()\n}","line":{"from":288,"to":292}} {"id":100028744,"name":"String","signature":"func (c ExecConfig) String() string","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/types.go","code":"// String implements fmt.Stringer and sanitizes sensitive fields of ExecConfig\n// to prevent accidental leaking via logs.\nfunc (c ExecConfig) String() string {\n\tvar args []string\n\tif len(c.Args) \u003e 0 {\n\t\targs = []string{\"--- REDACTED ---\"}\n\t}\n\tenv := \"[]ExecEnvVar(nil)\"\n\tif len(c.Env) \u003e 0 {\n\t\tenv = \"[]ExecEnvVar{--- REDACTED ---}\"\n\t}\n\tconfig := \"runtime.Object(nil)\"\n\tif c.Config != nil {\n\t\tconfig = \"runtime.Object(--- REDACTED ---)\"\n\t}\n\treturn fmt.Sprintf(\"api.ExecConfig{Command: %q, Args: %#v, Env: %s, APIVersion: %q, ProvideClusterInfo: %t, Config: %s, StdinUnavailable: %t}\", c.Command, args, env, c.APIVersion, c.ProvideClusterInfo, config, c.StdinUnavailable)\n}","line":{"from":294,"to":310}} {"id":100028745,"name":"NewConfig","signature":"func NewConfig() *Config","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/types.go","code":"// NewConfig is a convenience function that returns a new Config object with non-nil maps\nfunc NewConfig() *Config {\n\treturn \u0026Config{\n\t\tPreferences: *NewPreferences(),\n\t\tClusters: make(map[string]*Cluster),\n\t\tAuthInfos: make(map[string]*AuthInfo),\n\t\tContexts: make(map[string]*Context),\n\t\tExtensions: make(map[string]runtime.Object),\n\t}\n}","line":{"from":339,"to":348}} {"id":100028746,"name":"NewContext","signature":"func NewContext() *Context","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/types.go","code":"// NewContext is a convenience function that returns a new Context\n// object with non-nil maps\nfunc NewContext() *Context {\n\treturn \u0026Context{Extensions: make(map[string]runtime.Object)}\n}","line":{"from":350,"to":354}} {"id":100028747,"name":"NewCluster","signature":"func NewCluster() *Cluster","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/types.go","code":"// NewCluster is a convenience function that returns a new Cluster\n// object with non-nil maps\nfunc NewCluster() *Cluster {\n\treturn \u0026Cluster{Extensions: make(map[string]runtime.Object)}\n}","line":{"from":356,"to":360}} {"id":100028748,"name":"NewAuthInfo","signature":"func NewAuthInfo() *AuthInfo","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/types.go","code":"// NewAuthInfo is a convenience function that returns a new AuthInfo\n// object with non-nil maps\nfunc NewAuthInfo() *AuthInfo {\n\treturn \u0026AuthInfo{\n\t\tExtensions: make(map[string]runtime.Object),\n\t\tImpersonateUserExtra: make(map[string][]string),\n\t}\n}","line":{"from":362,"to":369}} {"id":100028749,"name":"NewPreferences","signature":"func NewPreferences() *Preferences","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/types.go","code":"// NewPreferences is a convenience function that returns a new\n// Preferences object with non-nil maps\nfunc NewPreferences() *Preferences {\n\treturn \u0026Preferences{Extensions: make(map[string]runtime.Object)}\n}","line":{"from":371,"to":375}} {"id":100028750,"name":"Convert_Slice_v1_NamedCluster_To_Map_string_To_Pointer_api_Cluster","signature":"func Convert_Slice_v1_NamedCluster_To_Map_string_To_Pointer_api_Cluster(in *[]NamedCluster, out *map[string]*api.Cluster, s conversion.Scope) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/v1/conversion.go","code":"func Convert_Slice_v1_NamedCluster_To_Map_string_To_Pointer_api_Cluster(in *[]NamedCluster, out *map[string]*api.Cluster, s conversion.Scope) error {\n\tfor _, curr := range *in {\n\t\tnewCluster := api.NewCluster()\n\t\tif err := Convert_v1_Cluster_To_api_Cluster(\u0026curr.Cluster, newCluster, s); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif *out == nil {\n\t\t\t*out = make(map[string]*api.Cluster)\n\t\t}\n\t\tif (*out)[curr.Name] == nil {\n\t\t\t(*out)[curr.Name] = newCluster\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"error converting *[]NamedCluster into *map[string]*api.Cluster: duplicate name \\\"%v\\\" in list: %v\", curr.Name, *in)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":28,"to":44}} {"id":100028751,"name":"Convert_Map_string_To_Pointer_api_Cluster_To_Slice_v1_NamedCluster","signature":"func Convert_Map_string_To_Pointer_api_Cluster_To_Slice_v1_NamedCluster(in *map[string]*api.Cluster, out *[]NamedCluster, s conversion.Scope) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/v1/conversion.go","code":"func Convert_Map_string_To_Pointer_api_Cluster_To_Slice_v1_NamedCluster(in *map[string]*api.Cluster, out *[]NamedCluster, s conversion.Scope) error {\n\tallKeys := make([]string, 0, len(*in))\n\tfor key := range *in {\n\t\tallKeys = append(allKeys, key)\n\t}\n\tsort.Strings(allKeys)\n\n\tfor _, key := range allKeys {\n\t\tnewCluster := (*in)[key]\n\t\toldCluster := Cluster{}\n\t\tif err := Convert_api_Cluster_To_v1_Cluster(newCluster, \u0026oldCluster, s); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnamedCluster := NamedCluster{key, oldCluster}\n\t\t*out = append(*out, namedCluster)\n\t}\n\treturn nil\n}","line":{"from":46,"to":63}} {"id":100028752,"name":"Convert_Slice_v1_NamedAuthInfo_To_Map_string_To_Pointer_api_AuthInfo","signature":"func Convert_Slice_v1_NamedAuthInfo_To_Map_string_To_Pointer_api_AuthInfo(in *[]NamedAuthInfo, out *map[string]*api.AuthInfo, s conversion.Scope) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/v1/conversion.go","code":"func Convert_Slice_v1_NamedAuthInfo_To_Map_string_To_Pointer_api_AuthInfo(in *[]NamedAuthInfo, out *map[string]*api.AuthInfo, s conversion.Scope) error {\n\tfor _, curr := range *in {\n\t\tnewAuthInfo := api.NewAuthInfo()\n\t\tif err := Convert_v1_AuthInfo_To_api_AuthInfo(\u0026curr.AuthInfo, newAuthInfo, s); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif *out == nil {\n\t\t\t*out = make(map[string]*api.AuthInfo)\n\t\t}\n\t\tif (*out)[curr.Name] == nil {\n\t\t\t(*out)[curr.Name] = newAuthInfo\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"error converting *[]NamedAuthInfo into *map[string]*api.AuthInfo: duplicate name \\\"%v\\\" in list: %v\", curr.Name, *in)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":65,"to":81}} {"id":100028753,"name":"Convert_Map_string_To_Pointer_api_AuthInfo_To_Slice_v1_NamedAuthInfo","signature":"func Convert_Map_string_To_Pointer_api_AuthInfo_To_Slice_v1_NamedAuthInfo(in *map[string]*api.AuthInfo, out *[]NamedAuthInfo, s conversion.Scope) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/v1/conversion.go","code":"func Convert_Map_string_To_Pointer_api_AuthInfo_To_Slice_v1_NamedAuthInfo(in *map[string]*api.AuthInfo, out *[]NamedAuthInfo, s conversion.Scope) error {\n\tallKeys := make([]string, 0, len(*in))\n\tfor key := range *in {\n\t\tallKeys = append(allKeys, key)\n\t}\n\tsort.Strings(allKeys)\n\n\tfor _, key := range allKeys {\n\t\tnewAuthInfo := (*in)[key]\n\t\toldAuthInfo := AuthInfo{}\n\t\tif err := Convert_api_AuthInfo_To_v1_AuthInfo(newAuthInfo, \u0026oldAuthInfo, s); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnamedAuthInfo := NamedAuthInfo{key, oldAuthInfo}\n\t\t*out = append(*out, namedAuthInfo)\n\t}\n\treturn nil\n}","line":{"from":83,"to":100}} {"id":100028754,"name":"Convert_Slice_v1_NamedContext_To_Map_string_To_Pointer_api_Context","signature":"func Convert_Slice_v1_NamedContext_To_Map_string_To_Pointer_api_Context(in *[]NamedContext, out *map[string]*api.Context, s conversion.Scope) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/v1/conversion.go","code":"func Convert_Slice_v1_NamedContext_To_Map_string_To_Pointer_api_Context(in *[]NamedContext, out *map[string]*api.Context, s conversion.Scope) error {\n\tfor _, curr := range *in {\n\t\tnewContext := api.NewContext()\n\t\tif err := Convert_v1_Context_To_api_Context(\u0026curr.Context, newContext, s); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif *out == nil {\n\t\t\t*out = make(map[string]*api.Context)\n\t\t}\n\t\tif (*out)[curr.Name] == nil {\n\t\t\t(*out)[curr.Name] = newContext\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"error converting *[]NamedContext into *map[string]*api.Context: duplicate name \\\"%v\\\" in list: %v\", curr.Name, *in)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":102,"to":118}} {"id":100028755,"name":"Convert_Map_string_To_Pointer_api_Context_To_Slice_v1_NamedContext","signature":"func Convert_Map_string_To_Pointer_api_Context_To_Slice_v1_NamedContext(in *map[string]*api.Context, out *[]NamedContext, s conversion.Scope) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/v1/conversion.go","code":"func Convert_Map_string_To_Pointer_api_Context_To_Slice_v1_NamedContext(in *map[string]*api.Context, out *[]NamedContext, s conversion.Scope) error {\n\tallKeys := make([]string, 0, len(*in))\n\tfor key := range *in {\n\t\tallKeys = append(allKeys, key)\n\t}\n\tsort.Strings(allKeys)\n\n\tfor _, key := range allKeys {\n\t\tnewContext := (*in)[key]\n\t\toldContext := Context{}\n\t\tif err := Convert_api_Context_To_v1_Context(newContext, \u0026oldContext, s); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnamedContext := NamedContext{key, oldContext}\n\t\t*out = append(*out, namedContext)\n\t}\n\treturn nil\n}","line":{"from":120,"to":137}} {"id":100028756,"name":"Convert_Slice_v1_NamedExtension_To_Map_string_To_runtime_Object","signature":"func Convert_Slice_v1_NamedExtension_To_Map_string_To_runtime_Object(in *[]NamedExtension, out *map[string]runtime.Object, s conversion.Scope) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/v1/conversion.go","code":"func Convert_Slice_v1_NamedExtension_To_Map_string_To_runtime_Object(in *[]NamedExtension, out *map[string]runtime.Object, s conversion.Scope) error {\n\tfor _, curr := range *in {\n\t\tvar newExtension runtime.Object\n\t\tif err := runtime.Convert_runtime_RawExtension_To_runtime_Object(\u0026curr.Extension, \u0026newExtension, s); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif *out == nil {\n\t\t\t*out = make(map[string]runtime.Object)\n\t\t}\n\t\tif (*out)[curr.Name] == nil {\n\t\t\t(*out)[curr.Name] = newExtension\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"error converting *[]NamedExtension into *map[string]runtime.Object: duplicate name \\\"%v\\\" in list: %v\", curr.Name, *in)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":139,"to":155}} {"id":100028757,"name":"Convert_Map_string_To_runtime_Object_To_Slice_v1_NamedExtension","signature":"func Convert_Map_string_To_runtime_Object_To_Slice_v1_NamedExtension(in *map[string]runtime.Object, out *[]NamedExtension, s conversion.Scope) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/v1/conversion.go","code":"func Convert_Map_string_To_runtime_Object_To_Slice_v1_NamedExtension(in *map[string]runtime.Object, out *[]NamedExtension, s conversion.Scope) error {\n\tallKeys := make([]string, 0, len(*in))\n\tfor key := range *in {\n\t\tallKeys = append(allKeys, key)\n\t}\n\tsort.Strings(allKeys)\n\n\tfor _, key := range allKeys {\n\t\tnewExtension := (*in)[key]\n\t\toldExtension := runtime.RawExtension{}\n\t\tif err := runtime.Convert_runtime_Object_To_runtime_RawExtension(\u0026newExtension, \u0026oldExtension, s); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnamedExtension := NamedExtension{key, oldExtension}\n\t\t*out = append(*out, namedExtension)\n\t}\n\treturn nil\n}","line":{"from":157,"to":174}} {"id":100028758,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/v1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":23,"to":25}} {"id":100028759,"name":"SetDefaults_ExecConfig","signature":"func SetDefaults_ExecConfig(exec *ExecConfig)","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/v1/defaults.go","code":"func SetDefaults_ExecConfig(exec *ExecConfig) {\n\tif len(exec.InteractiveMode) == 0 {\n\t\tswitch exec.APIVersion {\n\t\tcase \"client.authentication.k8s.io/v1beta1\", \"client.authentication.k8s.io/v1alpha1\":\n\t\t\t// default to IfAvailableExecInteractiveMode for backwards compatibility\n\t\t\texec.InteractiveMode = IfAvailableExecInteractiveMode\n\t\tdefault:\n\t\t\t// require other versions to explicitly declare whether they want stdin or not\n\t\t}\n\t}\n}","line":{"from":27,"to":37}} {"id":100028760,"name":"init","signature":"func init()","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addKnownTypes, addDefaultingFuncs)\n}","line":{"from":36,"to":41}} {"id":100028761,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/v1/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026Config{},\n\t)\n\treturn nil\n}","line":{"from":43,"to":48}} {"id":100028762,"name":"GetObjectKind","signature":"func (obj *Config) GetObjectKind() schema.ObjectKind { return obj }","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/v1/register.go","code":"func (obj *Config) GetObjectKind() schema.ObjectKind { return obj }","line":{"from":50,"to":50}} {"id":100028763,"name":"SetGroupVersionKind","signature":"func (obj *Config) SetGroupVersionKind(gvk schema.GroupVersionKind)","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/v1/register.go","code":"func (obj *Config) SetGroupVersionKind(gvk schema.GroupVersionKind) {\n\tobj.APIVersion, obj.Kind = gvk.ToAPIVersionAndKind()\n}","line":{"from":51,"to":53}} {"id":100028764,"name":"GroupVersionKind","signature":"func (obj *Config) GroupVersionKind() schema.GroupVersionKind","file":"staging/src/k8s.io/client-go/tools/clientcmd/api/v1/register.go","code":"func (obj *Config) GroupVersionKind() schema.GroupVersionKind {\n\treturn schema.FromAPIVersionAndKind(obj.APIVersion, obj.Kind)\n}","line":{"from":54,"to":56}} {"id":100028765,"name":"LoadAuth","signature":"func (*defaultAuthLoader) LoadAuth(path string) (*clientauth.Info, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/auth_loaders.go","code":"// LoadAuth for defaultAuthLoader simply delegates to clientauth.LoadFromFile\nfunc (*defaultAuthLoader) LoadAuth(path string) (*clientauth.Info, error) {\n\treturn clientauth.LoadFromFile(path)\n}","line":{"from":39,"to":42}} {"id":100028766,"name":"LoadAuth","signature":"func (a *PromptingAuthLoader) LoadAuth(path string) (*clientauth.Info, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/auth_loaders.go","code":"// LoadAuth parses an AuthInfo object from a file path. It prompts user and creates file if it doesn't exist.\nfunc (a *PromptingAuthLoader) LoadAuth(path string) (*clientauth.Info, error) {\n\t// Prompt for user/pass and write a file if none exists.\n\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\tauthPtr, err := a.Prompt()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tauth := *authPtr\n\t\tdata, err := json.Marshal(auth)\n\t\tif err != nil {\n\t\t\treturn \u0026auth, err\n\t\t}\n\t\terr = os.WriteFile(path, data, 0600)\n\t\treturn \u0026auth, err\n\t}\n\tauthPtr, err := clientauth.LoadFromFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn authPtr, nil\n}","line":{"from":48,"to":69}} {"id":100028767,"name":"Prompt","signature":"func (a *PromptingAuthLoader) Prompt() (*clientauth.Info, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/auth_loaders.go","code":"// Prompt pulls the user and password from a reader\nfunc (a *PromptingAuthLoader) Prompt() (*clientauth.Info, error) {\n\tvar err error\n\tauth := \u0026clientauth.Info{}\n\tauth.User, err = promptForString(\"Username\", a.reader, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tauth.Password, err = promptForString(\"Password\", nil, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn auth, nil\n}","line":{"from":71,"to":84}} {"id":100028768,"name":"promptForString","signature":"func promptForString(field string, r io.Reader, show bool) (result string, err error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/auth_loaders.go","code":"func promptForString(field string, r io.Reader, show bool) (result string, err error) {\n\tfmt.Printf(\"Please enter %s: \", field)\n\tif show {\n\t\t_, err = fmt.Fscan(r, \u0026result)\n\t} else {\n\t\tvar data []byte\n\t\tif term.IsTerminal(int(os.Stdin.Fd())) {\n\t\t\tdata, err = term.ReadPassword(int(os.Stdin.Fd()))\n\t\t\tresult = string(data)\n\t\t} else {\n\t\t\treturn \"\", fmt.Errorf(\"error reading input for %s\", field)\n\t\t}\n\t}\n\treturn result, err\n}","line":{"from":86,"to":100}} {"id":100028769,"name":"NewPromptingAuthLoader","signature":"func NewPromptingAuthLoader(reader io.Reader) *PromptingAuthLoader","file":"staging/src/k8s.io/client-go/tools/clientcmd/auth_loaders.go","code":"// NewPromptingAuthLoader is an AuthLoader that parses an AuthInfo object from a file path. It prompts user and creates file if it doesn't exist.\nfunc NewPromptingAuthLoader(reader io.Reader) *PromptingAuthLoader {\n\treturn \u0026PromptingAuthLoader{reader}\n}","line":{"from":102,"to":105}} {"id":100028770,"name":"NewDefaultAuthLoader","signature":"func NewDefaultAuthLoader() AuthLoader","file":"staging/src/k8s.io/client-go/tools/clientcmd/auth_loaders.go","code":"// NewDefaultAuthLoader returns a default implementation of an AuthLoader that only reads from a config file\nfunc NewDefaultAuthLoader() AuthLoader {\n\treturn \u0026defaultAuthLoader{}\n}","line":{"from":107,"to":110}} {"id":100028771,"name":"getDefaultServer","signature":"func getDefaultServer() string","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"// getDefaultServer returns a default setting for DefaultClientConfig\n// DEPRECATED\nfunc getDefaultServer() string {\n\tif server := os.Getenv(\"KUBERNETES_MASTER\"); len(server) \u003e 0 {\n\t\treturn server\n\t}\n\treturn \"http://localhost:8080\"\n}","line":{"from":52,"to":59}} {"id":100028772,"name":"NewDefaultClientConfig","signature":"func NewDefaultClientConfig(config clientcmdapi.Config, overrides *ConfigOverrides) ClientConfig","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"// NewDefaultClientConfig creates a DirectClientConfig using the config.CurrentContext as the context name\nfunc NewDefaultClientConfig(config clientcmdapi.Config, overrides *ConfigOverrides) ClientConfig {\n\treturn \u0026DirectClientConfig{config, config.CurrentContext, overrides, nil, NewDefaultClientConfigLoadingRules(), promptedCredentials{}}\n}","line":{"from":93,"to":96}} {"id":100028773,"name":"NewNonInteractiveClientConfig","signature":"func NewNonInteractiveClientConfig(config clientcmdapi.Config, contextName string, overrides *ConfigOverrides, configAccess ConfigAccess) ClientConfig","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"// NewNonInteractiveClientConfig creates a DirectClientConfig using the passed context name and does not have a fallback reader for auth information\nfunc NewNonInteractiveClientConfig(config clientcmdapi.Config, contextName string, overrides *ConfigOverrides, configAccess ConfigAccess) ClientConfig {\n\treturn \u0026DirectClientConfig{config, contextName, overrides, nil, configAccess, promptedCredentials{}}\n}","line":{"from":98,"to":101}} {"id":100028774,"name":"NewInteractiveClientConfig","signature":"func NewInteractiveClientConfig(config clientcmdapi.Config, contextName string, overrides *ConfigOverrides, fallbackReader io.Reader, configAccess ConfigAccess) ClientConfig","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"// NewInteractiveClientConfig creates a DirectClientConfig using the passed context name and a reader in case auth information is not provided via files or flags\nfunc NewInteractiveClientConfig(config clientcmdapi.Config, contextName string, overrides *ConfigOverrides, fallbackReader io.Reader, configAccess ConfigAccess) ClientConfig {\n\treturn \u0026DirectClientConfig{config, contextName, overrides, fallbackReader, configAccess, promptedCredentials{}}\n}","line":{"from":103,"to":106}} {"id":100028775,"name":"NewClientConfigFromBytes","signature":"func NewClientConfigFromBytes(configBytes []byte) (ClientConfig, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"// NewClientConfigFromBytes takes your kubeconfig and gives you back a ClientConfig\nfunc NewClientConfigFromBytes(configBytes []byte) (ClientConfig, error) {\n\tconfig, err := Load(configBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026DirectClientConfig{*config, \"\", \u0026ConfigOverrides{}, nil, nil, promptedCredentials{}}, nil\n}","line":{"from":108,"to":116}} {"id":100028776,"name":"RESTConfigFromKubeConfig","signature":"func RESTConfigFromKubeConfig(configBytes []byte) (*restclient.Config, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"// RESTConfigFromKubeConfig is a convenience method to give back a restconfig from your kubeconfig bytes.\n// For programmatic access, this is what you want 80% of the time\nfunc RESTConfigFromKubeConfig(configBytes []byte) (*restclient.Config, error) {\n\tclientConfig, err := NewClientConfigFromBytes(configBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn clientConfig.ClientConfig()\n}","line":{"from":118,"to":126}} {"id":100028777,"name":"RawConfig","signature":"func (config *DirectClientConfig) RawConfig() (clientcmdapi.Config, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"func (config *DirectClientConfig) RawConfig() (clientcmdapi.Config, error) {\n\treturn config.config, nil\n}","line":{"from":128,"to":130}} {"id":100028778,"name":"ClientConfig","signature":"func (config *DirectClientConfig) ClientConfig() (*restclient.Config, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"// ClientConfig implements ClientConfig\nfunc (config *DirectClientConfig) ClientConfig() (*restclient.Config, error) {\n\t// check that getAuthInfo, getContext, and getCluster do not return an error.\n\t// Do this before checking if the current config is usable in the event that an\n\t// AuthInfo, Context, or Cluster config with user-defined names are not found.\n\t// This provides a user with the immediate cause for error if one is found\n\tconfigAuthInfo, err := config.getAuthInfo()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = config.getContext()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfigClusterInfo, err := config.getCluster()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := config.ConfirmUsable(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tclientConfig := \u0026restclient.Config{}\n\tclientConfig.Host = configClusterInfo.Server\n\tif configClusterInfo.ProxyURL != \"\" {\n\t\tu, err := parseProxyURL(configClusterInfo.ProxyURL)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tclientConfig.Proxy = http.ProxyURL(u)\n\t}\n\n\tclientConfig.DisableCompression = configClusterInfo.DisableCompression\n\n\tif config.overrides != nil \u0026\u0026 len(config.overrides.Timeout) \u003e 0 {\n\t\ttimeout, err := ParseTimeout(config.overrides.Timeout)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tclientConfig.Timeout = timeout\n\t}\n\n\tif u, err := url.ParseRequestURI(clientConfig.Host); err == nil \u0026\u0026 u.Opaque == \"\" \u0026\u0026 len(u.Path) \u003e 1 {\n\t\tu.RawQuery = \"\"\n\t\tu.Fragment = \"\"\n\t\tclientConfig.Host = u.String()\n\t}\n\tif len(configAuthInfo.Impersonate) \u003e 0 {\n\t\tclientConfig.Impersonate = restclient.ImpersonationConfig{\n\t\t\tUserName: configAuthInfo.Impersonate,\n\t\t\tUID: configAuthInfo.ImpersonateUID,\n\t\t\tGroups: configAuthInfo.ImpersonateGroups,\n\t\t\tExtra: configAuthInfo.ImpersonateUserExtra,\n\t\t}\n\t}\n\n\t// only try to read the auth information if we are secure\n\tif restclient.IsConfigTransportTLS(*clientConfig) {\n\t\tvar err error\n\t\tvar persister restclient.AuthProviderConfigPersister\n\t\tif config.configAccess != nil {\n\t\t\tauthInfoName, _ := config.getAuthInfoName()\n\t\t\tpersister = PersisterForUser(config.configAccess, authInfoName)\n\t\t}\n\t\tuserAuthPartialConfig, err := config.getUserIdentificationPartialConfig(configAuthInfo, config.fallbackReader, persister, configClusterInfo)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmergo.Merge(clientConfig, userAuthPartialConfig, mergo.WithOverride)\n\n\t\tserverAuthPartialConfig, err := getServerIdentificationPartialConfig(configAuthInfo, configClusterInfo)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmergo.Merge(clientConfig, serverAuthPartialConfig, mergo.WithOverride)\n\t}\n\n\treturn clientConfig, nil\n}","line":{"from":132,"to":213}} {"id":100028779,"name":"getServerIdentificationPartialConfig","signature":"func getServerIdentificationPartialConfig(configAuthInfo clientcmdapi.AuthInfo, configClusterInfo clientcmdapi.Cluster) (*restclient.Config, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"// clientauth.Info object contain both user identification and server identification. We want different precedence orders for\n// both, so we have to split the objects and merge them separately\n// we want this order of precedence for the server identification\n// 1. configClusterInfo (the final result of command line flags and merged .kubeconfig files)\n// 2. configAuthInfo.auth-path (this file can contain information that conflicts with #1, and we want #1 to win the priority)\n// 3. load the ~/.kubernetes_auth file as a default\nfunc getServerIdentificationPartialConfig(configAuthInfo clientcmdapi.AuthInfo, configClusterInfo clientcmdapi.Cluster) (*restclient.Config, error) {\n\tmergedConfig := \u0026restclient.Config{}\n\n\t// configClusterInfo holds the information identify the server provided by .kubeconfig\n\tconfigClientConfig := \u0026restclient.Config{}\n\tconfigClientConfig.CAFile = configClusterInfo.CertificateAuthority\n\tconfigClientConfig.CAData = configClusterInfo.CertificateAuthorityData\n\tconfigClientConfig.Insecure = configClusterInfo.InsecureSkipTLSVerify\n\tconfigClientConfig.ServerName = configClusterInfo.TLSServerName\n\tmergo.Merge(mergedConfig, configClientConfig, mergo.WithOverride)\n\n\treturn mergedConfig, nil\n}","line":{"from":215,"to":233}} {"id":100028780,"name":"getUserIdentificationPartialConfig","signature":"func (config *DirectClientConfig) getUserIdentificationPartialConfig(configAuthInfo clientcmdapi.AuthInfo, fallbackReader io.Reader, persistAuthConfig restclient.AuthProviderConfigPersister, configClusterInfo clientcmdapi.Cluster) (*restclient.Config, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"// clientauth.Info object contain both user identification and server identification. We want different precedence orders for\n// both, so we have to split the objects and merge them separately\n// we want this order of precedence for user identification\n// 1. configAuthInfo minus auth-path (the final result of command line flags and merged .kubeconfig files)\n// 2. configAuthInfo.auth-path (this file can contain information that conflicts with #1, and we want #1 to win the priority)\n// 3. if there is not enough information to identify the user, load try the ~/.kubernetes_auth file\n// 4. if there is not enough information to identify the user, prompt if possible\nfunc (config *DirectClientConfig) getUserIdentificationPartialConfig(configAuthInfo clientcmdapi.AuthInfo, fallbackReader io.Reader, persistAuthConfig restclient.AuthProviderConfigPersister, configClusterInfo clientcmdapi.Cluster) (*restclient.Config, error) {\n\tmergedConfig := \u0026restclient.Config{}\n\n\t// blindly overwrite existing values based on precedence\n\tif len(configAuthInfo.Token) \u003e 0 {\n\t\tmergedConfig.BearerToken = configAuthInfo.Token\n\t\tmergedConfig.BearerTokenFile = configAuthInfo.TokenFile\n\t} else if len(configAuthInfo.TokenFile) \u003e 0 {\n\t\ttokenBytes, err := os.ReadFile(configAuthInfo.TokenFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmergedConfig.BearerToken = string(tokenBytes)\n\t\tmergedConfig.BearerTokenFile = configAuthInfo.TokenFile\n\t}\n\tif len(configAuthInfo.Impersonate) \u003e 0 {\n\t\tmergedConfig.Impersonate = restclient.ImpersonationConfig{\n\t\t\tUserName: configAuthInfo.Impersonate,\n\t\t\tUID: configAuthInfo.ImpersonateUID,\n\t\t\tGroups: configAuthInfo.ImpersonateGroups,\n\t\t\tExtra: configAuthInfo.ImpersonateUserExtra,\n\t\t}\n\t}\n\tif len(configAuthInfo.ClientCertificate) \u003e 0 || len(configAuthInfo.ClientCertificateData) \u003e 0 {\n\t\tmergedConfig.CertFile = configAuthInfo.ClientCertificate\n\t\tmergedConfig.CertData = configAuthInfo.ClientCertificateData\n\t\tmergedConfig.KeyFile = configAuthInfo.ClientKey\n\t\tmergedConfig.KeyData = configAuthInfo.ClientKeyData\n\t}\n\tif len(configAuthInfo.Username) \u003e 0 || len(configAuthInfo.Password) \u003e 0 {\n\t\tmergedConfig.Username = configAuthInfo.Username\n\t\tmergedConfig.Password = configAuthInfo.Password\n\t}\n\tif configAuthInfo.AuthProvider != nil {\n\t\tmergedConfig.AuthProvider = configAuthInfo.AuthProvider\n\t\tmergedConfig.AuthConfigPersister = persistAuthConfig\n\t}\n\tif configAuthInfo.Exec != nil {\n\t\tmergedConfig.ExecProvider = configAuthInfo.Exec\n\t\tmergedConfig.ExecProvider.InstallHint = cleanANSIEscapeCodes(mergedConfig.ExecProvider.InstallHint)\n\t\tmergedConfig.ExecProvider.Config = configClusterInfo.Extensions[clusterExtensionKey]\n\t}\n\n\t// if there still isn't enough information to authenticate the user, try prompting\n\tif !canIdentifyUser(*mergedConfig) \u0026\u0026 (fallbackReader != nil) {\n\t\tif len(config.promptedCredentials.username) \u003e 0 \u0026\u0026 len(config.promptedCredentials.password) \u003e 0 {\n\t\t\tmergedConfig.Username = config.promptedCredentials.username\n\t\t\tmergedConfig.Password = config.promptedCredentials.password\n\t\t\treturn mergedConfig, nil\n\t\t}\n\t\tprompter := NewPromptingAuthLoader(fallbackReader)\n\t\tpromptedAuthInfo, err := prompter.Prompt()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpromptedConfig := makeUserIdentificationConfig(*promptedAuthInfo)\n\t\tpreviouslyMergedConfig := mergedConfig\n\t\tmergedConfig = \u0026restclient.Config{}\n\t\tmergo.Merge(mergedConfig, promptedConfig, mergo.WithOverride)\n\t\tmergo.Merge(mergedConfig, previouslyMergedConfig, mergo.WithOverride)\n\t\tconfig.promptedCredentials.username = mergedConfig.Username\n\t\tconfig.promptedCredentials.password = mergedConfig.Password\n\t}\n\n\treturn mergedConfig, nil\n}","line":{"from":235,"to":307}} {"id":100028781,"name":"makeUserIdentificationConfig","signature":"func makeUserIdentificationConfig(info clientauth.Info) *restclient.Config","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"// makeUserIdentificationFieldsConfig returns a client.Config capable of being merged using mergo for only user identification information\nfunc makeUserIdentificationConfig(info clientauth.Info) *restclient.Config {\n\tconfig := \u0026restclient.Config{}\n\tconfig.Username = info.User\n\tconfig.Password = info.Password\n\tconfig.CertFile = info.CertFile\n\tconfig.KeyFile = info.KeyFile\n\tconfig.BearerToken = info.BearerToken\n\treturn config\n}","line":{"from":309,"to":318}} {"id":100028782,"name":"canIdentifyUser","signature":"func canIdentifyUser(config restclient.Config) bool","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"func canIdentifyUser(config restclient.Config) bool {\n\treturn len(config.Username) \u003e 0 ||\n\t\t(len(config.CertFile) \u003e 0 || len(config.CertData) \u003e 0) ||\n\t\tlen(config.BearerToken) \u003e 0 ||\n\t\tconfig.AuthProvider != nil ||\n\t\tconfig.ExecProvider != nil\n}","line":{"from":320,"to":326}} {"id":100028783,"name":"cleanANSIEscapeCodes","signature":"func cleanANSIEscapeCodes(s string) string","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"// cleanANSIEscapeCodes takes an arbitrary string and ensures that there are no\n// ANSI escape sequences that could put the terminal in a weird state (e.g.,\n// \"\\e[1m\" bolds text)\nfunc cleanANSIEscapeCodes(s string) string {\n\t// spaceControlCharacters includes tab, new line, vertical tab, new page, and\n\t// carriage return. These are in the unicode.Cc category, but that category also\n\t// contains ESC (U+001B) which we don't want.\n\tspaceControlCharacters := unicode.RangeTable{\n\t\tR16: []unicode.Range16{\n\t\t\t{Lo: 0x0009, Hi: 0x000D, Stride: 1},\n\t\t},\n\t}\n\n\t// Why not make this deny-only (instead of allow-only)? Because unicode.C\n\t// contains newline and tab characters that we want.\n\tallowedRanges := []*unicode.RangeTable{\n\t\tunicode.L,\n\t\tunicode.M,\n\t\tunicode.N,\n\t\tunicode.P,\n\t\tunicode.S,\n\t\tunicode.Z,\n\t\t\u0026spaceControlCharacters,\n\t}\n\tbuilder := strings.Builder{}\n\tfor _, roon := range s {\n\t\tif unicode.IsOneOf(allowedRanges, roon) {\n\t\t\tbuilder.WriteRune(roon) // returns nil error, per go doc\n\t\t} else {\n\t\t\tfmt.Fprintf(\u0026builder, \"%U\", roon)\n\t\t}\n\t}\n\treturn builder.String()\n}","line":{"from":328,"to":361}} {"id":100028784,"name":"Namespace","signature":"func (config *DirectClientConfig) Namespace() (string, bool, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"// Namespace implements ClientConfig\nfunc (config *DirectClientConfig) Namespace() (string, bool, error) {\n\tif config.overrides != nil \u0026\u0026 config.overrides.Context.Namespace != \"\" {\n\t\t// In the event we have an empty config but we do have a namespace override, we should return\n\t\t// the namespace override instead of having config.ConfirmUsable() return an error. This allows\n\t\t// things like in-cluster clients to execute `kubectl get pods --namespace=foo` and have the\n\t\t// --namespace flag honored instead of being ignored.\n\t\treturn config.overrides.Context.Namespace, true, nil\n\t}\n\n\tif err := config.ConfirmUsable(); err != nil {\n\t\treturn \"\", false, err\n\t}\n\n\tconfigContext, err := config.getContext()\n\tif err != nil {\n\t\treturn \"\", false, err\n\t}\n\n\tif len(configContext.Namespace) == 0 {\n\t\treturn \"default\", false, nil\n\t}\n\n\treturn configContext.Namespace, false, nil\n}","line":{"from":363,"to":387}} {"id":100028785,"name":"ConfigAccess","signature":"func (config *DirectClientConfig) ConfigAccess() ConfigAccess","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"// ConfigAccess implements ClientConfig\nfunc (config *DirectClientConfig) ConfigAccess() ConfigAccess {\n\treturn config.configAccess\n}","line":{"from":389,"to":392}} {"id":100028786,"name":"ConfirmUsable","signature":"func (config *DirectClientConfig) ConfirmUsable() error","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"// ConfirmUsable looks a particular context and determines if that particular part of the config is useable. There might still be errors in the config,\n// but no errors in the sections requested or referenced. It does not return early so that it can find as many errors as possible.\nfunc (config *DirectClientConfig) ConfirmUsable() error {\n\tvalidationErrors := make([]error, 0)\n\n\tvar contextName string\n\tif len(config.contextName) != 0 {\n\t\tcontextName = config.contextName\n\t} else {\n\t\tcontextName = config.config.CurrentContext\n\t}\n\n\tif len(contextName) \u003e 0 {\n\t\t_, exists := config.config.Contexts[contextName]\n\t\tif !exists {\n\t\t\tvalidationErrors = append(validationErrors, \u0026errContextNotFound{contextName})\n\t\t}\n\t}\n\n\tauthInfoName, _ := config.getAuthInfoName()\n\tauthInfo, _ := config.getAuthInfo()\n\tvalidationErrors = append(validationErrors, validateAuthInfo(authInfoName, authInfo)...)\n\tclusterName, _ := config.getClusterName()\n\tcluster, _ := config.getCluster()\n\tvalidationErrors = append(validationErrors, validateClusterInfo(clusterName, cluster)...)\n\t// when direct client config is specified, and our only error is that no server is defined, we should\n\t// return a standard \"no config\" error\n\tif len(validationErrors) == 1 \u0026\u0026 validationErrors[0] == ErrEmptyCluster {\n\t\treturn newErrConfigurationInvalid([]error{ErrEmptyConfig})\n\t}\n\treturn newErrConfigurationInvalid(validationErrors)\n}","line":{"from":394,"to":425}} {"id":100028787,"name":"getContextName","signature":"func (config *DirectClientConfig) getContextName() (string, bool)","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"// getContextName returns the default, or user-set context name, and a boolean that indicates\n// whether the default context name has been overwritten by a user-set flag, or left as its default value\nfunc (config *DirectClientConfig) getContextName() (string, bool) {\n\tif config.overrides != nil \u0026\u0026 len(config.overrides.CurrentContext) != 0 {\n\t\treturn config.overrides.CurrentContext, true\n\t}\n\tif len(config.contextName) != 0 {\n\t\treturn config.contextName, false\n\t}\n\n\treturn config.config.CurrentContext, false\n}","line":{"from":427,"to":438}} {"id":100028788,"name":"getAuthInfoName","signature":"func (config *DirectClientConfig) getAuthInfoName() (string, bool)","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"// getAuthInfoName returns a string containing the current authinfo name for the current context,\n// and a boolean indicating whether the default authInfo name is overwritten by a user-set flag, or\n// left as its default value\nfunc (config *DirectClientConfig) getAuthInfoName() (string, bool) {\n\tif config.overrides != nil \u0026\u0026 len(config.overrides.Context.AuthInfo) != 0 {\n\t\treturn config.overrides.Context.AuthInfo, true\n\t}\n\tcontext, _ := config.getContext()\n\treturn context.AuthInfo, false\n}","line":{"from":440,"to":449}} {"id":100028789,"name":"getClusterName","signature":"func (config *DirectClientConfig) getClusterName() (string, bool)","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"// getClusterName returns a string containing the default, or user-set cluster name, and a boolean\n// indicating whether the default clusterName has been overwritten by a user-set flag, or left as\n// its default value\nfunc (config *DirectClientConfig) getClusterName() (string, bool) {\n\tif config.overrides != nil \u0026\u0026 len(config.overrides.Context.Cluster) != 0 {\n\t\treturn config.overrides.Context.Cluster, true\n\t}\n\tcontext, _ := config.getContext()\n\treturn context.Cluster, false\n}","line":{"from":451,"to":460}} {"id":100028790,"name":"getContext","signature":"func (config *DirectClientConfig) getContext() (clientcmdapi.Context, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"// getContext returns the clientcmdapi.Context, or an error if a required context is not found.\nfunc (config *DirectClientConfig) getContext() (clientcmdapi.Context, error) {\n\tcontexts := config.config.Contexts\n\tcontextName, required := config.getContextName()\n\n\tmergedContext := clientcmdapi.NewContext()\n\tif configContext, exists := contexts[contextName]; exists {\n\t\tmergo.Merge(mergedContext, configContext, mergo.WithOverride)\n\t} else if required {\n\t\treturn clientcmdapi.Context{}, fmt.Errorf(\"context %q does not exist\", contextName)\n\t}\n\tif config.overrides != nil {\n\t\tmergo.Merge(mergedContext, config.overrides.Context, mergo.WithOverride)\n\t}\n\n\treturn *mergedContext, nil\n}","line":{"from":462,"to":478}} {"id":100028791,"name":"getAuthInfo","signature":"func (config *DirectClientConfig) getAuthInfo() (clientcmdapi.AuthInfo, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"// getAuthInfo returns the clientcmdapi.AuthInfo, or an error if a required auth info is not found.\nfunc (config *DirectClientConfig) getAuthInfo() (clientcmdapi.AuthInfo, error) {\n\tauthInfos := config.config.AuthInfos\n\tauthInfoName, required := config.getAuthInfoName()\n\n\tmergedAuthInfo := clientcmdapi.NewAuthInfo()\n\tif configAuthInfo, exists := authInfos[authInfoName]; exists {\n\t\tmergo.Merge(mergedAuthInfo, configAuthInfo, mergo.WithOverride)\n\t} else if required {\n\t\treturn clientcmdapi.AuthInfo{}, fmt.Errorf(\"auth info %q does not exist\", authInfoName)\n\t}\n\tif config.overrides != nil {\n\t\tmergo.Merge(mergedAuthInfo, config.overrides.AuthInfo, mergo.WithOverride)\n\t}\n\n\treturn *mergedAuthInfo, nil\n}","line":{"from":480,"to":496}} {"id":100028792,"name":"getCluster","signature":"func (config *DirectClientConfig) getCluster() (clientcmdapi.Cluster, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"// getCluster returns the clientcmdapi.Cluster, or an error if a required cluster is not found.\nfunc (config *DirectClientConfig) getCluster() (clientcmdapi.Cluster, error) {\n\tclusterInfos := config.config.Clusters\n\tclusterInfoName, required := config.getClusterName()\n\n\tmergedClusterInfo := clientcmdapi.NewCluster()\n\tif config.overrides != nil {\n\t\tmergo.Merge(mergedClusterInfo, config.overrides.ClusterDefaults, mergo.WithOverride)\n\t}\n\tif configClusterInfo, exists := clusterInfos[clusterInfoName]; exists {\n\t\tmergo.Merge(mergedClusterInfo, configClusterInfo, mergo.WithOverride)\n\t} else if required {\n\t\treturn clientcmdapi.Cluster{}, fmt.Errorf(\"cluster %q does not exist\", clusterInfoName)\n\t}\n\tif config.overrides != nil {\n\t\tmergo.Merge(mergedClusterInfo, config.overrides.ClusterInfo, mergo.WithOverride)\n\t}\n\n\t// * An override of --insecure-skip-tls-verify=true and no accompanying CA/CA data should clear already-set CA/CA data\n\t// otherwise, a kubeconfig containing a CA reference would return an error that \"CA and insecure-skip-tls-verify couldn't both be set\".\n\t// * An override of --certificate-authority should also override TLS skip settings and CA data, otherwise existing CA data will take precedence.\n\tif config.overrides != nil {\n\t\tcaLen := len(config.overrides.ClusterInfo.CertificateAuthority)\n\t\tcaDataLen := len(config.overrides.ClusterInfo.CertificateAuthorityData)\n\t\tif config.overrides.ClusterInfo.InsecureSkipTLSVerify || caLen \u003e 0 || caDataLen \u003e 0 {\n\t\t\tmergedClusterInfo.InsecureSkipTLSVerify = config.overrides.ClusterInfo.InsecureSkipTLSVerify\n\t\t\tmergedClusterInfo.CertificateAuthority = config.overrides.ClusterInfo.CertificateAuthority\n\t\t\tmergedClusterInfo.CertificateAuthorityData = config.overrides.ClusterInfo.CertificateAuthorityData\n\t\t}\n\n\t\t// if the --tls-server-name has been set in overrides, use that value.\n\t\t// if the --server has been set in overrides, then use the value of --tls-server-name specified on the CLI too. This gives the property\n\t\t// that setting a --server will effectively clear the KUBECONFIG value of tls-server-name if it is specified on the command line which is\n\t\t// usually correct.\n\t\tif config.overrides.ClusterInfo.TLSServerName != \"\" || config.overrides.ClusterInfo.Server != \"\" {\n\t\t\tmergedClusterInfo.TLSServerName = config.overrides.ClusterInfo.TLSServerName\n\t\t}\n\t}\n\n\treturn *mergedClusterInfo, nil\n}","line":{"from":498,"to":538}} {"id":100028793,"name":"RawConfig","signature":"func (config *inClusterClientConfig) RawConfig() (clientcmdapi.Config, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"func (config *inClusterClientConfig) RawConfig() (clientcmdapi.Config, error) {\n\treturn clientcmdapi.Config{}, fmt.Errorf(\"inCluster environment config doesn't support multiple clusters\")\n}","line":{"from":549,"to":551}} {"id":100028794,"name":"ClientConfig","signature":"func (config *inClusterClientConfig) ClientConfig() (*restclient.Config, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"func (config *inClusterClientConfig) ClientConfig() (*restclient.Config, error) {\n\tinClusterConfigProvider := config.inClusterConfigProvider\n\tif inClusterConfigProvider == nil {\n\t\tinClusterConfigProvider = restclient.InClusterConfig\n\t}\n\n\ticc, err := inClusterConfigProvider()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// in-cluster configs only takes a host, token, or CA file\n\t// if any of them were individually provided, overwrite anything else\n\tif config.overrides != nil {\n\t\tif server := config.overrides.ClusterInfo.Server; len(server) \u003e 0 {\n\t\t\ticc.Host = server\n\t\t}\n\t\tif len(config.overrides.AuthInfo.Token) \u003e 0 || len(config.overrides.AuthInfo.TokenFile) \u003e 0 {\n\t\t\ticc.BearerToken = config.overrides.AuthInfo.Token\n\t\t\ticc.BearerTokenFile = config.overrides.AuthInfo.TokenFile\n\t\t}\n\t\tif certificateAuthorityFile := config.overrides.ClusterInfo.CertificateAuthority; len(certificateAuthorityFile) \u003e 0 {\n\t\t\ticc.TLSClientConfig.CAFile = certificateAuthorityFile\n\t\t}\n\t}\n\n\treturn icc, nil\n}","line":{"from":553,"to":580}} {"id":100028795,"name":"Namespace","signature":"func (config *inClusterClientConfig) Namespace() (string, bool, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"func (config *inClusterClientConfig) Namespace() (string, bool, error) {\n\t// This way assumes you've set the POD_NAMESPACE environment variable using the downward API.\n\t// This check has to be done first for backwards compatibility with the way InClusterConfig was originally set up\n\tif ns := os.Getenv(\"POD_NAMESPACE\"); ns != \"\" {\n\t\treturn ns, false, nil\n\t}\n\n\t// Fall back to the namespace associated with the service account token, if available\n\tif data, err := os.ReadFile(\"/var/run/secrets/kubernetes.io/serviceaccount/namespace\"); err == nil {\n\t\tif ns := strings.TrimSpace(string(data)); len(ns) \u003e 0 {\n\t\t\treturn ns, false, nil\n\t\t}\n\t}\n\n\treturn \"default\", false, nil\n}","line":{"from":582,"to":597}} {"id":100028796,"name":"ConfigAccess","signature":"func (config *inClusterClientConfig) ConfigAccess() ConfigAccess","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"func (config *inClusterClientConfig) ConfigAccess() ConfigAccess {\n\treturn NewDefaultClientConfigLoadingRules()\n}","line":{"from":599,"to":601}} {"id":100028797,"name":"Possible","signature":"func (config *inClusterClientConfig) Possible() bool","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"// Possible returns true if loading an inside-kubernetes-cluster is possible.\nfunc (config *inClusterClientConfig) Possible() bool {\n\tfi, err := os.Stat(\"/var/run/secrets/kubernetes.io/serviceaccount/token\")\n\treturn os.Getenv(\"KUBERNETES_SERVICE_HOST\") != \"\" \u0026\u0026\n\t\tos.Getenv(\"KUBERNETES_SERVICE_PORT\") != \"\" \u0026\u0026\n\t\terr == nil \u0026\u0026 !fi.IsDir()\n}","line":{"from":603,"to":609}} {"id":100028798,"name":"BuildConfigFromFlags","signature":"func BuildConfigFromFlags(masterUrl, kubeconfigPath string) (*restclient.Config, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"// BuildConfigFromFlags is a helper function that builds configs from a master\n// url or a kubeconfig filepath. These are passed in as command line flags for cluster\n// components. Warnings should reflect this usage. If neither masterUrl or kubeconfigPath\n// are passed in we fallback to inClusterConfig. If inClusterConfig fails, we fallback\n// to the default config.\nfunc BuildConfigFromFlags(masterUrl, kubeconfigPath string) (*restclient.Config, error) {\n\tif kubeconfigPath == \"\" \u0026\u0026 masterUrl == \"\" {\n\t\tklog.Warning(\"Neither --kubeconfig nor --master was specified. Using the inClusterConfig. This might not work.\")\n\t\tkubeconfig, err := restclient.InClusterConfig()\n\t\tif err == nil {\n\t\t\treturn kubeconfig, nil\n\t\t}\n\t\tklog.Warning(\"error creating inClusterConfig, falling back to default config: \", err)\n\t}\n\treturn NewNonInteractiveDeferredLoadingClientConfig(\n\t\t\u0026ClientConfigLoadingRules{ExplicitPath: kubeconfigPath},\n\t\t\u0026ConfigOverrides{ClusterInfo: clientcmdapi.Cluster{Server: masterUrl}}).ClientConfig()\n}","line":{"from":611,"to":628}} {"id":100028799,"name":"BuildConfigFromKubeconfigGetter","signature":"func BuildConfigFromKubeconfigGetter(masterUrl string, kubeconfigGetter KubeconfigGetter) (*restclient.Config, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/client_config.go","code":"// BuildConfigFromKubeconfigGetter is a helper function that builds configs from a master\n// url and a kubeconfigGetter.\nfunc BuildConfigFromKubeconfigGetter(masterUrl string, kubeconfigGetter KubeconfigGetter) (*restclient.Config, error) {\n\t// TODO: We do not need a DeferredLoader here. Refactor code and see if we can use DirectClientConfig here.\n\tcc := NewNonInteractiveDeferredLoadingClientConfig(\n\t\t\u0026ClientConfigGetter{kubeconfigGetter: kubeconfigGetter},\n\t\t\u0026ConfigOverrides{ClusterInfo: clientcmdapi.Cluster{Server: masterUrl}})\n\treturn cc.ClientConfig()\n}","line":{"from":630,"to":638}} {"id":100028800,"name":"GetEnvVarFiles","signature":"func (o *PathOptions) GetEnvVarFiles() []string","file":"staging/src/k8s.io/client-go/tools/clientcmd/config.go","code":"func (o *PathOptions) GetEnvVarFiles() []string {\n\tif len(o.EnvVar) == 0 {\n\t\treturn []string{}\n\t}\n\n\tenvVarValue := os.Getenv(o.EnvVar)\n\tif len(envVarValue) == 0 {\n\t\treturn []string{}\n\t}\n\n\tfileList := filepath.SplitList(envVarValue)\n\t// prevent the same path load multiple times\n\treturn deduplicate(fileList)\n}","line":{"from":70,"to":83}} {"id":100028801,"name":"GetLoadingPrecedence","signature":"func (o *PathOptions) GetLoadingPrecedence() []string","file":"staging/src/k8s.io/client-go/tools/clientcmd/config.go","code":"func (o *PathOptions) GetLoadingPrecedence() []string {\n\tif o.IsExplicitFile() {\n\t\treturn []string{o.GetExplicitFile()}\n\t}\n\n\tif envVarFiles := o.GetEnvVarFiles(); len(envVarFiles) \u003e 0 {\n\t\treturn envVarFiles\n\t}\n\treturn []string{o.GlobalFile}\n}","line":{"from":85,"to":94}} {"id":100028802,"name":"GetStartingConfig","signature":"func (o *PathOptions) GetStartingConfig() (*clientcmdapi.Config, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/config.go","code":"func (o *PathOptions) GetStartingConfig() (*clientcmdapi.Config, error) {\n\t// don't mutate the original\n\tloadingRules := *o.LoadingRules\n\tloadingRules.Precedence = o.GetLoadingPrecedence()\n\n\tclientConfig := NewNonInteractiveDeferredLoadingClientConfig(\u0026loadingRules, \u0026ConfigOverrides{})\n\trawConfig, err := clientConfig.RawConfig()\n\tif os.IsNotExist(err) {\n\t\treturn clientcmdapi.NewConfig(), nil\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026rawConfig, nil\n}","line":{"from":96,"to":111}} {"id":100028803,"name":"GetDefaultFilename","signature":"func (o *PathOptions) GetDefaultFilename() string","file":"staging/src/k8s.io/client-go/tools/clientcmd/config.go","code":"func (o *PathOptions) GetDefaultFilename() string {\n\tif o.IsExplicitFile() {\n\t\treturn o.GetExplicitFile()\n\t}\n\n\tif envVarFiles := o.GetEnvVarFiles(); len(envVarFiles) \u003e 0 {\n\t\tif len(envVarFiles) == 1 {\n\t\t\treturn envVarFiles[0]\n\t\t}\n\n\t\t// if any of the envvar files already exists, return it\n\t\tfor _, envVarFile := range envVarFiles {\n\t\t\tif _, err := os.Stat(envVarFile); err == nil {\n\t\t\t\treturn envVarFile\n\t\t\t}\n\t\t}\n\n\t\t// otherwise, return the last one in the list\n\t\treturn envVarFiles[len(envVarFiles)-1]\n\t}\n\n\treturn o.GlobalFile\n}","line":{"from":113,"to":135}} {"id":100028804,"name":"IsExplicitFile","signature":"func (o *PathOptions) IsExplicitFile() bool","file":"staging/src/k8s.io/client-go/tools/clientcmd/config.go","code":"func (o *PathOptions) IsExplicitFile() bool {\n\treturn len(o.LoadingRules.ExplicitPath) \u003e 0\n}","line":{"from":137,"to":139}} {"id":100028805,"name":"GetExplicitFile","signature":"func (o *PathOptions) GetExplicitFile() string","file":"staging/src/k8s.io/client-go/tools/clientcmd/config.go","code":"func (o *PathOptions) GetExplicitFile() string {\n\treturn o.LoadingRules.ExplicitPath\n}","line":{"from":141,"to":143}} {"id":100028806,"name":"NewDefaultPathOptions","signature":"func NewDefaultPathOptions() *PathOptions","file":"staging/src/k8s.io/client-go/tools/clientcmd/config.go","code":"func NewDefaultPathOptions() *PathOptions {\n\tret := \u0026PathOptions{\n\t\tGlobalFile: RecommendedHomeFile,\n\t\tEnvVar: RecommendedConfigPathEnvVar,\n\t\tExplicitFileFlag: RecommendedConfigPathFlag,\n\n\t\tGlobalFileSubpath: path.Join(RecommendedHomeDir, RecommendedFileName),\n\n\t\tLoadingRules: NewDefaultClientConfigLoadingRules(),\n\t}\n\tret.LoadingRules.DoNotResolvePaths = true\n\n\treturn ret\n}","line":{"from":145,"to":158}} {"id":100028807,"name":"ModifyConfig","signature":"func ModifyConfig(configAccess ConfigAccess, newConfig clientcmdapi.Config, relativizePaths bool) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/config.go","code":"// ModifyConfig takes a Config object, iterates through Clusters, AuthInfos, and Contexts, uses the LocationOfOrigin if specified or\n// uses the default destination file to write the results into. This results in multiple file reads, but it's very easy to follow.\n// Preferences and CurrentContext should always be set in the default destination file. Since we can't distinguish between empty and missing values\n// (no nil strings), we're forced have separate handling for them. In the kubeconfig cases, newConfig should have at most one difference,\n// that means that this code will only write into a single file. If you want to relativizePaths, you must provide a fully qualified path in any\n// modified element.\nfunc ModifyConfig(configAccess ConfigAccess, newConfig clientcmdapi.Config, relativizePaths bool) error {\n\tif UseModifyConfigLock {\n\t\tpossibleSources := configAccess.GetLoadingPrecedence()\n\t\t// sort the possible kubeconfig files so we always \"lock\" in the same order\n\t\t// to avoid deadlock (note: this can fail w/ symlinks, but... come on).\n\t\tsort.Strings(possibleSources)\n\t\tfor _, filename := range possibleSources {\n\t\t\tif err := lockFile(filename); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer unlockFile(filename)\n\t\t}\n\t}\n\n\tstartingConfig, err := configAccess.GetStartingConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// We need to find all differences, locate their original files, read a partial config to modify only that stanza and write out the file.\n\t// Special case the test for current context and preferences since those always write to the default file.\n\tif reflect.DeepEqual(*startingConfig, newConfig) {\n\t\t// nothing to do\n\t\treturn nil\n\t}\n\n\tif startingConfig.CurrentContext != newConfig.CurrentContext {\n\t\tif err := writeCurrentContext(configAccess, newConfig.CurrentContext); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !reflect.DeepEqual(startingConfig.Preferences, newConfig.Preferences) {\n\t\tif err := writePreferences(configAccess, newConfig.Preferences); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Search every cluster, authInfo, and context. First from new to old for differences, then from old to new for deletions\n\tfor key, cluster := range newConfig.Clusters {\n\t\tstartingCluster, exists := startingConfig.Clusters[key]\n\t\tif !reflect.DeepEqual(cluster, startingCluster) || !exists {\n\t\t\tdestinationFile := cluster.LocationOfOrigin\n\t\t\tif len(destinationFile) == 0 {\n\t\t\t\tdestinationFile = configAccess.GetDefaultFilename()\n\t\t\t}\n\n\t\t\tconfigToWrite, err := getConfigFromFile(destinationFile)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tt := *cluster\n\n\t\t\tconfigToWrite.Clusters[key] = \u0026t\n\t\t\tconfigToWrite.Clusters[key].LocationOfOrigin = destinationFile\n\t\t\tif relativizePaths {\n\t\t\t\tif err := RelativizeClusterLocalPaths(configToWrite.Clusters[key]); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif err := WriteToFile(*configToWrite, destinationFile); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// seenConfigs stores a map of config source filenames to computed config objects\n\tseenConfigs := map[string]*clientcmdapi.Config{}\n\n\tfor key, context := range newConfig.Contexts {\n\t\tstartingContext, exists := startingConfig.Contexts[key]\n\t\tif !reflect.DeepEqual(context, startingContext) || !exists {\n\t\t\tdestinationFile := context.LocationOfOrigin\n\t\t\tif len(destinationFile) == 0 {\n\t\t\t\tdestinationFile = configAccess.GetDefaultFilename()\n\t\t\t}\n\n\t\t\t// we only obtain a fresh config object from its source file\n\t\t\t// if we have not seen it already - this prevents us from\n\t\t\t// reading and writing to the same number of files repeatedly\n\t\t\t// when multiple / all contexts share the same destination file.\n\t\t\tconfigToWrite, seen := seenConfigs[destinationFile]\n\t\t\tif !seen {\n\t\t\t\tvar err error\n\t\t\t\tconfigToWrite, err = getConfigFromFile(destinationFile)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tseenConfigs[destinationFile] = configToWrite\n\t\t\t}\n\n\t\t\tconfigToWrite.Contexts[key] = context\n\t\t}\n\t}\n\n\t// actually persist config object changes\n\tfor destinationFile, configToWrite := range seenConfigs {\n\t\tif err := WriteToFile(*configToWrite, destinationFile); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfor key, authInfo := range newConfig.AuthInfos {\n\t\tstartingAuthInfo, exists := startingConfig.AuthInfos[key]\n\t\tif !reflect.DeepEqual(authInfo, startingAuthInfo) || !exists {\n\t\t\tdestinationFile := authInfo.LocationOfOrigin\n\t\t\tif len(destinationFile) == 0 {\n\t\t\t\tdestinationFile = configAccess.GetDefaultFilename()\n\t\t\t}\n\n\t\t\tconfigToWrite, err := getConfigFromFile(destinationFile)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tt := *authInfo\n\t\t\tconfigToWrite.AuthInfos[key] = \u0026t\n\t\t\tconfigToWrite.AuthInfos[key].LocationOfOrigin = destinationFile\n\t\t\tif relativizePaths {\n\t\t\t\tif err := RelativizeAuthInfoLocalPaths(configToWrite.AuthInfos[key]); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif err := WriteToFile(*configToWrite, destinationFile); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tfor key, cluster := range startingConfig.Clusters {\n\t\tif _, exists := newConfig.Clusters[key]; !exists {\n\t\t\tdestinationFile := cluster.LocationOfOrigin\n\t\t\tif len(destinationFile) == 0 {\n\t\t\t\tdestinationFile = configAccess.GetDefaultFilename()\n\t\t\t}\n\n\t\t\tconfigToWrite, err := getConfigFromFile(destinationFile)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdelete(configToWrite.Clusters, key)\n\n\t\t\tif err := WriteToFile(*configToWrite, destinationFile); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tfor key, context := range startingConfig.Contexts {\n\t\tif _, exists := newConfig.Contexts[key]; !exists {\n\t\t\tdestinationFile := context.LocationOfOrigin\n\t\t\tif len(destinationFile) == 0 {\n\t\t\t\tdestinationFile = configAccess.GetDefaultFilename()\n\t\t\t}\n\n\t\t\tconfigToWrite, err := getConfigFromFile(destinationFile)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdelete(configToWrite.Contexts, key)\n\n\t\t\tif err := WriteToFile(*configToWrite, destinationFile); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tfor key, authInfo := range startingConfig.AuthInfos {\n\t\tif _, exists := newConfig.AuthInfos[key]; !exists {\n\t\t\tdestinationFile := authInfo.LocationOfOrigin\n\t\t\tif len(destinationFile) == 0 {\n\t\t\t\tdestinationFile = configAccess.GetDefaultFilename()\n\t\t\t}\n\n\t\t\tconfigToWrite, err := getConfigFromFile(destinationFile)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdelete(configToWrite.AuthInfos, key)\n\n\t\t\tif err := WriteToFile(*configToWrite, destinationFile); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":160,"to":354}} {"id":100028808,"name":"PersisterForUser","signature":"func PersisterForUser(configAccess ConfigAccess, user string) restclient.AuthProviderConfigPersister","file":"staging/src/k8s.io/client-go/tools/clientcmd/config.go","code":"func PersisterForUser(configAccess ConfigAccess, user string) restclient.AuthProviderConfigPersister {\n\treturn \u0026persister{configAccess, user}\n}","line":{"from":356,"to":358}} {"id":100028809,"name":"Persist","signature":"func (p *persister) Persist(config map[string]string) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/config.go","code":"func (p *persister) Persist(config map[string]string) error {\n\tnewConfig, err := p.configAccess.GetStartingConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\tauthInfo, ok := newConfig.AuthInfos[p.user]\n\tif ok \u0026\u0026 authInfo.AuthProvider != nil {\n\t\tauthInfo.AuthProvider.Config = config\n\t\treturn ModifyConfig(p.configAccess, *newConfig, false)\n\t}\n\treturn nil\n}","line":{"from":365,"to":376}} {"id":100028810,"name":"writeCurrentContext","signature":"func writeCurrentContext(configAccess ConfigAccess, newCurrentContext string) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/config.go","code":"// writeCurrentContext takes three possible paths.\n// If newCurrentContext is the same as the startingConfig's current context, then we exit.\n// If newCurrentContext has a value, then that value is written into the default destination file.\n// If newCurrentContext is empty, then we find the config file that is setting the CurrentContext and clear the value from that file\nfunc writeCurrentContext(configAccess ConfigAccess, newCurrentContext string) error {\n\tif startingConfig, err := configAccess.GetStartingConfig(); err != nil {\n\t\treturn err\n\t} else if startingConfig.CurrentContext == newCurrentContext {\n\t\treturn nil\n\t}\n\n\tif configAccess.IsExplicitFile() {\n\t\tfile := configAccess.GetExplicitFile()\n\t\tcurrConfig, err := getConfigFromFile(file)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcurrConfig.CurrentContext = newCurrentContext\n\t\tif err := WriteToFile(*currConfig, file); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tif len(newCurrentContext) \u003e 0 {\n\t\tdestinationFile := configAccess.GetDefaultFilename()\n\t\tconfig, err := getConfigFromFile(destinationFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tconfig.CurrentContext = newCurrentContext\n\n\t\tif err := WriteToFile(*config, destinationFile); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\n\t// we're supposed to be clearing the current context. We need to find the first spot in the chain that is setting it and clear it\n\tfor _, file := range configAccess.GetLoadingPrecedence() {\n\t\tif _, err := os.Stat(file); err == nil {\n\t\t\tcurrConfig, err := getConfigFromFile(file)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif len(currConfig.CurrentContext) \u003e 0 {\n\t\t\t\tcurrConfig.CurrentContext = newCurrentContext\n\t\t\t\tif err := WriteToFile(*currConfig, file); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn errors.New(\"no config found to write context\")\n}","line":{"from":378,"to":438}} {"id":100028811,"name":"writePreferences","signature":"func writePreferences(configAccess ConfigAccess, newPrefs clientcmdapi.Preferences) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/config.go","code":"func writePreferences(configAccess ConfigAccess, newPrefs clientcmdapi.Preferences) error {\n\tif startingConfig, err := configAccess.GetStartingConfig(); err != nil {\n\t\treturn err\n\t} else if reflect.DeepEqual(startingConfig.Preferences, newPrefs) {\n\t\treturn nil\n\t}\n\n\tif configAccess.IsExplicitFile() {\n\t\tfile := configAccess.GetExplicitFile()\n\t\tcurrConfig, err := getConfigFromFile(file)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcurrConfig.Preferences = newPrefs\n\t\tif err := WriteToFile(*currConfig, file); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tfor _, file := range configAccess.GetLoadingPrecedence() {\n\t\tcurrConfig, err := getConfigFromFile(file)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif !reflect.DeepEqual(currConfig.Preferences, newPrefs) {\n\t\t\tcurrConfig.Preferences = newPrefs\n\t\t\tif err := WriteToFile(*currConfig, file); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn errors.New(\"no config found to write preferences\")\n}","line":{"from":440,"to":478}} {"id":100028812,"name":"getConfigFromFile","signature":"func getConfigFromFile(filename string) (*clientcmdapi.Config, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/config.go","code":"// getConfigFromFile tries to read a kubeconfig file and if it can't, returns an error. One exception, missing files result in empty configs, not an error.\nfunc getConfigFromFile(filename string) (*clientcmdapi.Config, error) {\n\tconfig, err := LoadFromFile(filename)\n\tif err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\treturn nil, err\n\t}\n\tif config == nil {\n\t\tconfig = clientcmdapi.NewConfig()\n\t}\n\treturn config, nil\n}","line":{"from":480,"to":490}} {"id":100028813,"name":"GetConfigFromFileOrDie","signature":"func GetConfigFromFileOrDie(filename string) *clientcmdapi.Config","file":"staging/src/k8s.io/client-go/tools/clientcmd/config.go","code":"// GetConfigFromFileOrDie tries to read a kubeconfig file and if it can't, it calls exit. One exception, missing files result in empty configs, not an exit\nfunc GetConfigFromFileOrDie(filename string) *clientcmdapi.Config {\n\tconfig, err := getConfigFromFile(filename)\n\tif err != nil {\n\t\tklog.FatalDepth(1, err)\n\t}\n\n\treturn config\n}","line":{"from":492,"to":500}} {"id":100028814,"name":"newTransformingStringValue","signature":"func newTransformingStringValue(val string, target *string, transformer func(string) (string, error)) *transformingStringValue","file":"staging/src/k8s.io/client-go/tools/clientcmd/flag.go","code":"func newTransformingStringValue(val string, target *string, transformer func(string) (string, error)) *transformingStringValue {\n\t*target = val\n\treturn \u0026transformingStringValue{\n\t\ttarget: target,\n\t\ttransformer: transformer,\n\t}\n}","line":{"from":26,"to":32}} {"id":100028815,"name":"Set","signature":"func (t *transformingStringValue) Set(val string) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/flag.go","code":"func (t *transformingStringValue) Set(val string) error {\n\tval, err := t.transformer(val)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*t.target = val\n\treturn nil\n}","line":{"from":34,"to":41}} {"id":100028816,"name":"Type","signature":"func (t *transformingStringValue) Type() string","file":"staging/src/k8s.io/client-go/tools/clientcmd/flag.go","code":"func (t *transformingStringValue) Type() string {\n\treturn \"string\"\n}","line":{"from":43,"to":45}} {"id":100028817,"name":"String","signature":"func (t *transformingStringValue) String() string","file":"staging/src/k8s.io/client-go/tools/clientcmd/flag.go","code":"func (t *transformingStringValue) String() string {\n\treturn string(*t.target)\n}","line":{"from":47,"to":49}} {"id":100028818,"name":"ParseTimeout","signature":"func ParseTimeout(duration string) (time.Duration, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/helpers.go","code":"// ParseTimeout returns a parsed duration from a string\n// A duration string value must be a positive integer, optionally followed by a corresponding time unit (s|m|h).\nfunc ParseTimeout(duration string) (time.Duration, error) {\n\tif i, err := strconv.ParseInt(duration, 10, 64); err == nil \u0026\u0026 i \u003e= 0 {\n\t\treturn (time.Duration(i) * time.Second), nil\n\t}\n\tif requestTimeout, err := time.ParseDuration(duration); err == nil {\n\t\treturn requestTimeout, nil\n\t}\n\treturn 0, fmt.Errorf(\"Invalid timeout value. Timeout must be a single integer in seconds, or an integer followed by a corresponding time unit (e.g. 1s | 2m | 3h)\")\n}","line":{"from":26,"to":36}} {"id":100028819,"name":"parseProxyURL","signature":"func parseProxyURL(proxyURL string) (*url.URL, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/helpers.go","code":"func parseProxyURL(proxyURL string) (*url.URL, error) {\n\tu, err := url.Parse(proxyURL)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not parse: %v\", proxyURL)\n\t}\n\n\tswitch u.Scheme {\n\tcase \"http\", \"https\", \"socks5\":\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported scheme %q, must be http, https, or socks5\", u.Scheme)\n\t}\n\treturn u, nil\n}","line":{"from":38,"to":50}} {"id":100028820,"name":"currentMigrationRules","signature":"func currentMigrationRules() map[string]string","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"// currentMigrationRules returns a map that holds the history of recommended home directories used in previous versions.\n// Any future changes to RecommendedHomeFile and related are expected to add a migration rule here, in order to make\n// sure existing config files are migrated to their new locations properly.\nfunc currentMigrationRules() map[string]string {\n\tvar oldRecommendedHomeFileName string\n\tif goruntime.GOOS == \"windows\" {\n\t\toldRecommendedHomeFileName = RecommendedFileName\n\t} else {\n\t\toldRecommendedHomeFileName = \".kubeconfig\"\n\t}\n\treturn map[string]string{\n\t\tRecommendedHomeFile: filepath.Join(os.Getenv(\"HOME\"), RecommendedHomeDir, oldRecommendedHomeFileName),\n\t}\n}","line":{"from":53,"to":66}} {"id":100028821,"name":"Load","signature":"func (g *ClientConfigGetter) Load() (*clientcmdapi.Config, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"func (g *ClientConfigGetter) Load() (*clientcmdapi.Config, error) {\n\treturn g.kubeconfigGetter()\n}","line":{"from":85,"to":87}} {"id":100028822,"name":"GetLoadingPrecedence","signature":"func (g *ClientConfigGetter) GetLoadingPrecedence() []string","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"func (g *ClientConfigGetter) GetLoadingPrecedence() []string {\n\treturn nil\n}","line":{"from":89,"to":91}} {"id":100028823,"name":"GetStartingConfig","signature":"func (g *ClientConfigGetter) GetStartingConfig() (*clientcmdapi.Config, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"func (g *ClientConfigGetter) GetStartingConfig() (*clientcmdapi.Config, error) {\n\treturn g.kubeconfigGetter()\n}","line":{"from":92,"to":94}} {"id":100028824,"name":"GetDefaultFilename","signature":"func (g *ClientConfigGetter) GetDefaultFilename() string","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"func (g *ClientConfigGetter) GetDefaultFilename() string {\n\treturn \"\"\n}","line":{"from":95,"to":97}} {"id":100028825,"name":"IsExplicitFile","signature":"func (g *ClientConfigGetter) IsExplicitFile() bool","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"func (g *ClientConfigGetter) IsExplicitFile() bool {\n\treturn false\n}","line":{"from":98,"to":100}} {"id":100028826,"name":"GetExplicitFile","signature":"func (g *ClientConfigGetter) GetExplicitFile() string","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"func (g *ClientConfigGetter) GetExplicitFile() string {\n\treturn \"\"\n}","line":{"from":101,"to":103}} {"id":100028827,"name":"IsDefaultConfig","signature":"func (g *ClientConfigGetter) IsDefaultConfig(config *restclient.Config) bool","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"func (g *ClientConfigGetter) IsDefaultConfig(config *restclient.Config) bool {\n\treturn false\n}","line":{"from":104,"to":106}} {"id":100028828,"name":"NewDefaultClientConfigLoadingRules","signature":"func NewDefaultClientConfigLoadingRules() *ClientConfigLoadingRules","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"// NewDefaultClientConfigLoadingRules returns a ClientConfigLoadingRules object with default fields filled in. You are not required to\n// use this constructor\nfunc NewDefaultClientConfigLoadingRules() *ClientConfigLoadingRules {\n\tchain := []string{}\n\twarnIfAllMissing := false\n\n\tenvVarFiles := os.Getenv(RecommendedConfigPathEnvVar)\n\tif len(envVarFiles) != 0 {\n\t\tfileList := filepath.SplitList(envVarFiles)\n\t\t// prevent the same path load multiple times\n\t\tchain = append(chain, deduplicate(fileList)...)\n\t\twarnIfAllMissing = true\n\n\t} else {\n\t\tchain = append(chain, RecommendedHomeFile)\n\t}\n\n\treturn \u0026ClientConfigLoadingRules{\n\t\tPrecedence: chain,\n\t\tMigrationRules: currentMigrationRules(),\n\t\tWarnIfAllMissing: warnIfAllMissing,\n\t}\n}","line":{"from":136,"to":158}} {"id":100028829,"name":"Load","signature":"func (rules *ClientConfigLoadingRules) Load() (*clientcmdapi.Config, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"// Load starts by running the MigrationRules and then\n// takes the loading rules and returns a Config object based on following rules.\n//\n//\tif the ExplicitPath, return the unmerged explicit file\n//\tOtherwise, return a merged config based on the Precedence slice\n//\n// A missing ExplicitPath file produces an error. Empty filenames or other missing files are ignored.\n// Read errors or files with non-deserializable content produce errors.\n// The first file to set a particular map key wins and map key's value is never changed.\n// BUT, if you set a struct value that is NOT contained inside of map, the value WILL be changed.\n// This results in some odd looking logic to merge in one direction, merge in the other, and then merge the two.\n// It also means that if two files specify a \"red-user\", only values from the first file's red-user are used. Even\n// non-conflicting entries from the second file's \"red-user\" are discarded.\n// Relative paths inside of the .kubeconfig files are resolved against the .kubeconfig file's parent folder\n// and only absolute file paths are returned.\nfunc (rules *ClientConfigLoadingRules) Load() (*clientcmdapi.Config, error) {\n\tif err := rules.Migrate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\terrlist := []error{}\n\tmissingList := []string{}\n\n\tkubeConfigFiles := []string{}\n\n\t// Make sure a file we were explicitly told to use exists\n\tif len(rules.ExplicitPath) \u003e 0 {\n\t\tif _, err := os.Stat(rules.ExplicitPath); os.IsNotExist(err) {\n\t\t\treturn nil, err\n\t\t}\n\t\tkubeConfigFiles = append(kubeConfigFiles, rules.ExplicitPath)\n\n\t} else {\n\t\tkubeConfigFiles = append(kubeConfigFiles, rules.Precedence...)\n\t}\n\n\tkubeconfigs := []*clientcmdapi.Config{}\n\t// read and cache the config files so that we only look at them once\n\tfor _, filename := range kubeConfigFiles {\n\t\tif len(filename) == 0 {\n\t\t\t// no work to do\n\t\t\tcontinue\n\t\t}\n\n\t\tconfig, err := LoadFromFile(filename)\n\n\t\tif os.IsNotExist(err) {\n\t\t\t// skip missing files\n\t\t\t// Add to the missing list to produce a warning\n\t\t\tmissingList = append(missingList, filename)\n\t\t\tcontinue\n\t\t}\n\n\t\tif err != nil {\n\t\t\terrlist = append(errlist, fmt.Errorf(\"error loading config file \\\"%s\\\": %v\", filename, err))\n\t\t\tcontinue\n\t\t}\n\n\t\tkubeconfigs = append(kubeconfigs, config)\n\t}\n\n\tif rules.WarnIfAllMissing \u0026\u0026 len(missingList) \u003e 0 \u0026\u0026 len(kubeconfigs) == 0 {\n\t\tklog.Warningf(\"Config not found: %s\", strings.Join(missingList, \", \"))\n\t}\n\n\t// first merge all of our maps\n\tmapConfig := clientcmdapi.NewConfig()\n\n\tfor _, kubeconfig := range kubeconfigs {\n\t\tmergo.Merge(mapConfig, kubeconfig, mergo.WithOverride)\n\t}\n\n\t// merge all of the struct values in the reverse order so that priority is given correctly\n\t// errors are not added to the list the second time\n\tnonMapConfig := clientcmdapi.NewConfig()\n\tfor i := len(kubeconfigs) - 1; i \u003e= 0; i-- {\n\t\tkubeconfig := kubeconfigs[i]\n\t\tmergo.Merge(nonMapConfig, kubeconfig, mergo.WithOverride)\n\t}\n\n\t// since values are overwritten, but maps values are not, we can merge the non-map config on top of the map config and\n\t// get the values we expect.\n\tconfig := clientcmdapi.NewConfig()\n\tmergo.Merge(config, mapConfig, mergo.WithOverride)\n\tmergo.Merge(config, nonMapConfig, mergo.WithOverride)\n\n\tif rules.ResolvePaths() {\n\t\tif err := ResolveLocalPaths(config); err != nil {\n\t\t\terrlist = append(errlist, err)\n\t\t}\n\t}\n\treturn config, utilerrors.NewAggregate(errlist)\n}","line":{"from":160,"to":252}} {"id":100028830,"name":"Migrate","signature":"func (rules *ClientConfigLoadingRules) Migrate() error","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"// Migrate uses the MigrationRules map. If a destination file is not present, then the source file is checked.\n// If the source file is present, then it is copied to the destination file BEFORE any further loading happens.\nfunc (rules *ClientConfigLoadingRules) Migrate() error {\n\tif rules.MigrationRules == nil {\n\t\treturn nil\n\t}\n\n\tfor destination, source := range rules.MigrationRules {\n\t\tif _, err := os.Stat(destination); err == nil {\n\t\t\t// if the destination already exists, do nothing\n\t\t\tcontinue\n\t\t} else if os.IsPermission(err) {\n\t\t\t// if we can't access the file, skip it\n\t\t\tcontinue\n\t\t} else if !os.IsNotExist(err) {\n\t\t\t// if we had an error other than non-existence, fail\n\t\t\treturn err\n\t\t}\n\n\t\tif sourceInfo, err := os.Stat(source); err != nil {\n\t\t\tif os.IsNotExist(err) || os.IsPermission(err) {\n\t\t\t\t// if the source file doesn't exist or we can't access it, there's no work to do.\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// if we had an error other than non-existence, fail\n\t\t\treturn err\n\t\t} else if sourceInfo.IsDir() {\n\t\t\treturn fmt.Errorf(\"cannot migrate %v to %v because it is a directory\", source, destination)\n\t\t}\n\n\t\tdata, err := os.ReadFile(source)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// destination is created with mode 0666 before umask\n\t\terr = os.WriteFile(destination, data, 0666)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":254,"to":297}} {"id":100028831,"name":"GetLoadingPrecedence","signature":"func (rules *ClientConfigLoadingRules) GetLoadingPrecedence() []string","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"// GetLoadingPrecedence implements ConfigAccess\nfunc (rules *ClientConfigLoadingRules) GetLoadingPrecedence() []string {\n\tif len(rules.ExplicitPath) \u003e 0 {\n\t\treturn []string{rules.ExplicitPath}\n\t}\n\n\treturn rules.Precedence\n}","line":{"from":299,"to":306}} {"id":100028832,"name":"GetStartingConfig","signature":"func (rules *ClientConfigLoadingRules) GetStartingConfig() (*clientcmdapi.Config, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"// GetStartingConfig implements ConfigAccess\nfunc (rules *ClientConfigLoadingRules) GetStartingConfig() (*clientcmdapi.Config, error) {\n\tclientConfig := NewNonInteractiveDeferredLoadingClientConfig(rules, \u0026ConfigOverrides{})\n\trawConfig, err := clientConfig.RawConfig()\n\tif os.IsNotExist(err) {\n\t\treturn clientcmdapi.NewConfig(), nil\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026rawConfig, nil\n}","line":{"from":308,"to":320}} {"id":100028833,"name":"GetDefaultFilename","signature":"func (rules *ClientConfigLoadingRules) GetDefaultFilename() string","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"// GetDefaultFilename implements ConfigAccess\nfunc (rules *ClientConfigLoadingRules) GetDefaultFilename() string {\n\t// Explicit file if we have one.\n\tif rules.IsExplicitFile() {\n\t\treturn rules.GetExplicitFile()\n\t}\n\t// Otherwise, first existing file from precedence.\n\tfor _, filename := range rules.GetLoadingPrecedence() {\n\t\tif _, err := os.Stat(filename); err == nil {\n\t\t\treturn filename\n\t\t}\n\t}\n\t// If none exists, use the first from precedence.\n\tif len(rules.Precedence) \u003e 0 {\n\t\treturn rules.Precedence[0]\n\t}\n\treturn \"\"\n}","line":{"from":322,"to":339}} {"id":100028834,"name":"IsExplicitFile","signature":"func (rules *ClientConfigLoadingRules) IsExplicitFile() bool","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"// IsExplicitFile implements ConfigAccess\nfunc (rules *ClientConfigLoadingRules) IsExplicitFile() bool {\n\treturn len(rules.ExplicitPath) \u003e 0\n}","line":{"from":341,"to":344}} {"id":100028835,"name":"GetExplicitFile","signature":"func (rules *ClientConfigLoadingRules) GetExplicitFile() string","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"// GetExplicitFile implements ConfigAccess\nfunc (rules *ClientConfigLoadingRules) GetExplicitFile() string {\n\treturn rules.ExplicitPath\n}","line":{"from":346,"to":349}} {"id":100028836,"name":"IsDefaultConfig","signature":"func (rules *ClientConfigLoadingRules) IsDefaultConfig(config *restclient.Config) bool","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"// IsDefaultConfig returns true if the provided configuration matches the default\nfunc (rules *ClientConfigLoadingRules) IsDefaultConfig(config *restclient.Config) bool {\n\tif rules.DefaultClientConfig == nil {\n\t\treturn false\n\t}\n\tdefaultConfig, err := rules.DefaultClientConfig.ClientConfig()\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn reflect.DeepEqual(config, defaultConfig)\n}","line":{"from":351,"to":361}} {"id":100028837,"name":"LoadFromFile","signature":"func LoadFromFile(filename string) (*clientcmdapi.Config, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"// LoadFromFile takes a filename and deserializes the contents into Config object\nfunc LoadFromFile(filename string) (*clientcmdapi.Config, error) {\n\tkubeconfigBytes, err := os.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfig, err := Load(kubeconfigBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tklog.V(6).Infoln(\"Config loaded from file: \", filename)\n\n\t// set LocationOfOrigin on every Cluster, User, and Context\n\tfor key, obj := range config.AuthInfos {\n\t\tobj.LocationOfOrigin = filename\n\t\tconfig.AuthInfos[key] = obj\n\t}\n\tfor key, obj := range config.Clusters {\n\t\tobj.LocationOfOrigin = filename\n\t\tconfig.Clusters[key] = obj\n\t}\n\tfor key, obj := range config.Contexts {\n\t\tobj.LocationOfOrigin = filename\n\t\tconfig.Contexts[key] = obj\n\t}\n\n\tif config.AuthInfos == nil {\n\t\tconfig.AuthInfos = map[string]*clientcmdapi.AuthInfo{}\n\t}\n\tif config.Clusters == nil {\n\t\tconfig.Clusters = map[string]*clientcmdapi.Cluster{}\n\t}\n\tif config.Contexts == nil {\n\t\tconfig.Contexts = map[string]*clientcmdapi.Context{}\n\t}\n\n\treturn config, nil\n}","line":{"from":363,"to":400}} {"id":100028838,"name":"Load","signature":"func Load(data []byte) (*clientcmdapi.Config, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"// Load takes a byte slice and deserializes the contents into Config object.\n// Encapsulates deserialization without assuming the source is a file.\nfunc Load(data []byte) (*clientcmdapi.Config, error) {\n\tconfig := clientcmdapi.NewConfig()\n\t// if there's no data in a file, return the default object instead of failing (DecodeInto reject empty input)\n\tif len(data) == 0 {\n\t\treturn config, nil\n\t}\n\tdecoded, _, err := clientcmdlatest.Codec.Decode(data, \u0026schema.GroupVersionKind{Version: clientcmdlatest.Version, Kind: \"Config\"}, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn decoded.(*clientcmdapi.Config), nil\n}","line":{"from":402,"to":415}} {"id":100028839,"name":"WriteToFile","signature":"func WriteToFile(config clientcmdapi.Config, filename string) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"// WriteToFile serializes the config to yaml and writes it out to a file. If not present, it creates the file with the mode 0600. If it is present\n// it stomps the contents\nfunc WriteToFile(config clientcmdapi.Config, filename string) error {\n\tcontent, err := Write(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdir := filepath.Dir(filename)\n\tif _, err := os.Stat(dir); os.IsNotExist(err) {\n\t\tif err = os.MkdirAll(dir, 0755); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := os.WriteFile(filename, content, 0600); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":417,"to":435}} {"id":100028840,"name":"lockFile","signature":"func lockFile(filename string) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"func lockFile(filename string) error {\n\t// TODO: find a way to do this with actual file locks. Will\n\t// probably need separate solution for windows and Linux.\n\n\t// Make sure the dir exists before we try to create a lock file.\n\tdir := filepath.Dir(filename)\n\tif _, err := os.Stat(dir); os.IsNotExist(err) {\n\t\tif err = os.MkdirAll(dir, 0755); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tf, err := os.OpenFile(lockName(filename), os.O_CREATE|os.O_EXCL, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\tf.Close()\n\treturn nil\n}","line":{"from":437,"to":454}} {"id":100028841,"name":"unlockFile","signature":"func unlockFile(filename string) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"func unlockFile(filename string) error {\n\treturn os.Remove(lockName(filename))\n}","line":{"from":456,"to":458}} {"id":100028842,"name":"lockName","signature":"func lockName(filename string) string","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"func lockName(filename string) string {\n\treturn filename + \".lock\"\n}","line":{"from":460,"to":462}} {"id":100028843,"name":"Write","signature":"func Write(config clientcmdapi.Config) ([]byte, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"// Write serializes the config to yaml.\n// Encapsulates serialization without assuming the destination is a file.\nfunc Write(config clientcmdapi.Config) ([]byte, error) {\n\treturn runtime.Encode(clientcmdlatest.Codec, \u0026config)\n}","line":{"from":464,"to":468}} {"id":100028844,"name":"ResolvePaths","signature":"func (rules ClientConfigLoadingRules) ResolvePaths() bool","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"func (rules ClientConfigLoadingRules) ResolvePaths() bool {\n\treturn !rules.DoNotResolvePaths\n}","line":{"from":470,"to":472}} {"id":100028845,"name":"ResolveLocalPaths","signature":"func ResolveLocalPaths(config *clientcmdapi.Config) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"// ResolveLocalPaths resolves all relative paths in the config object with respect to the stanza's LocationOfOrigin\n// this cannot be done directly inside of LoadFromFile because doing so there would make it impossible to load a file without\n// modification of its contents.\nfunc ResolveLocalPaths(config *clientcmdapi.Config) error {\n\tfor _, cluster := range config.Clusters {\n\t\tif len(cluster.LocationOfOrigin) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tbase, err := filepath.Abs(filepath.Dir(cluster.LocationOfOrigin))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not determine the absolute path of config file %s: %v\", cluster.LocationOfOrigin, err)\n\t\t}\n\n\t\tif err := ResolvePaths(GetClusterFileReferences(cluster), base); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfor _, authInfo := range config.AuthInfos {\n\t\tif len(authInfo.LocationOfOrigin) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tbase, err := filepath.Abs(filepath.Dir(authInfo.LocationOfOrigin))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not determine the absolute path of config file %s: %v\", authInfo.LocationOfOrigin, err)\n\t\t}\n\n\t\tif err := ResolvePaths(GetAuthInfoFileReferences(authInfo), base); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":474,"to":506}} {"id":100028846,"name":"RelativizeClusterLocalPaths","signature":"func RelativizeClusterLocalPaths(cluster *clientcmdapi.Cluster) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"// RelativizeClusterLocalPaths first absolutizes the paths by calling ResolveLocalPaths. This assumes that any NEW path is already\n// absolute, but any existing path will be resolved relative to LocationOfOrigin\nfunc RelativizeClusterLocalPaths(cluster *clientcmdapi.Cluster) error {\n\tif len(cluster.LocationOfOrigin) == 0 {\n\t\treturn fmt.Errorf(\"no location of origin for %s\", cluster.Server)\n\t}\n\tbase, err := filepath.Abs(filepath.Dir(cluster.LocationOfOrigin))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not determine the absolute path of config file %s: %v\", cluster.LocationOfOrigin, err)\n\t}\n\n\tif err := ResolvePaths(GetClusterFileReferences(cluster), base); err != nil {\n\t\treturn err\n\t}\n\tif err := RelativizePathWithNoBacksteps(GetClusterFileReferences(cluster), base); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":508,"to":527}} {"id":100028847,"name":"RelativizeAuthInfoLocalPaths","signature":"func RelativizeAuthInfoLocalPaths(authInfo *clientcmdapi.AuthInfo) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"// RelativizeAuthInfoLocalPaths first absolutizes the paths by calling ResolveLocalPaths. This assumes that any NEW path is already\n// absolute, but any existing path will be resolved relative to LocationOfOrigin\nfunc RelativizeAuthInfoLocalPaths(authInfo *clientcmdapi.AuthInfo) error {\n\tif len(authInfo.LocationOfOrigin) == 0 {\n\t\treturn fmt.Errorf(\"no location of origin for %v\", authInfo)\n\t}\n\tbase, err := filepath.Abs(filepath.Dir(authInfo.LocationOfOrigin))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not determine the absolute path of config file %s: %v\", authInfo.LocationOfOrigin, err)\n\t}\n\n\tif err := ResolvePaths(GetAuthInfoFileReferences(authInfo), base); err != nil {\n\t\treturn err\n\t}\n\tif err := RelativizePathWithNoBacksteps(GetAuthInfoFileReferences(authInfo), base); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":529,"to":548}} {"id":100028848,"name":"RelativizeConfigPaths","signature":"func RelativizeConfigPaths(config *clientcmdapi.Config, base string) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"func RelativizeConfigPaths(config *clientcmdapi.Config, base string) error {\n\treturn RelativizePathWithNoBacksteps(GetConfigFileReferences(config), base)\n}","line":{"from":550,"to":552}} {"id":100028849,"name":"ResolveConfigPaths","signature":"func ResolveConfigPaths(config *clientcmdapi.Config, base string) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"func ResolveConfigPaths(config *clientcmdapi.Config, base string) error {\n\treturn ResolvePaths(GetConfigFileReferences(config), base)\n}","line":{"from":554,"to":556}} {"id":100028850,"name":"GetConfigFileReferences","signature":"func GetConfigFileReferences(config *clientcmdapi.Config) []*string","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"func GetConfigFileReferences(config *clientcmdapi.Config) []*string {\n\trefs := []*string{}\n\n\tfor _, cluster := range config.Clusters {\n\t\trefs = append(refs, GetClusterFileReferences(cluster)...)\n\t}\n\tfor _, authInfo := range config.AuthInfos {\n\t\trefs = append(refs, GetAuthInfoFileReferences(authInfo)...)\n\t}\n\n\treturn refs\n}","line":{"from":558,"to":569}} {"id":100028851,"name":"GetClusterFileReferences","signature":"func GetClusterFileReferences(cluster *clientcmdapi.Cluster) []*string","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"func GetClusterFileReferences(cluster *clientcmdapi.Cluster) []*string {\n\treturn []*string{\u0026cluster.CertificateAuthority}\n}","line":{"from":571,"to":573}} {"id":100028852,"name":"GetAuthInfoFileReferences","signature":"func GetAuthInfoFileReferences(authInfo *clientcmdapi.AuthInfo) []*string","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"func GetAuthInfoFileReferences(authInfo *clientcmdapi.AuthInfo) []*string {\n\ts := []*string{\u0026authInfo.ClientCertificate, \u0026authInfo.ClientKey, \u0026authInfo.TokenFile}\n\t// Only resolve exec command if it isn't PATH based.\n\tif authInfo.Exec != nil \u0026\u0026 strings.ContainsRune(authInfo.Exec.Command, filepath.Separator) {\n\t\ts = append(s, \u0026authInfo.Exec.Command)\n\t}\n\treturn s\n}","line":{"from":575,"to":582}} {"id":100028853,"name":"ResolvePaths","signature":"func ResolvePaths(refs []*string, base string) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"// ResolvePaths updates the given refs to be absolute paths, relative to the given base directory\nfunc ResolvePaths(refs []*string, base string) error {\n\tfor _, ref := range refs {\n\t\t// Don't resolve empty paths\n\t\tif len(*ref) \u003e 0 {\n\t\t\t// Don't resolve absolute paths\n\t\t\tif !filepath.IsAbs(*ref) {\n\t\t\t\t*ref = filepath.Join(base, *ref)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":584,"to":596}} {"id":100028854,"name":"RelativizePathWithNoBacksteps","signature":"func RelativizePathWithNoBacksteps(refs []*string, base string) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"// RelativizePathWithNoBacksteps updates the given refs to be relative paths, relative to the given base directory as long as they do not require backsteps.\n// Any path requiring a backstep is left as-is as long it is absolute. Any non-absolute path that can't be relativized produces an error\nfunc RelativizePathWithNoBacksteps(refs []*string, base string) error {\n\tfor _, ref := range refs {\n\t\t// Don't relativize empty paths\n\t\tif len(*ref) \u003e 0 {\n\t\t\trel, err := MakeRelative(*ref, base)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// if we have a backstep, don't mess with the path\n\t\t\tif strings.HasPrefix(rel, \"../\") {\n\t\t\t\tif filepath.IsAbs(*ref) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\treturn fmt.Errorf(\"%v requires backsteps and is not absolute\", *ref)\n\t\t\t}\n\n\t\t\t*ref = rel\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":598,"to":622}} {"id":100028855,"name":"MakeRelative","signature":"func MakeRelative(path, base string) (string, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"func MakeRelative(path, base string) (string, error) {\n\tif len(path) \u003e 0 {\n\t\trel, err := filepath.Rel(base, path)\n\t\tif err != nil {\n\t\t\treturn path, err\n\t\t}\n\t\treturn rel, nil\n\t}\n\treturn path, nil\n}","line":{"from":624,"to":633}} {"id":100028856,"name":"deduplicate","signature":"func deduplicate(s []string) []string","file":"staging/src/k8s.io/client-go/tools/clientcmd/loader.go","code":"// deduplicate removes any duplicated values and returns a new slice, keeping the order unchanged\nfunc deduplicate(s []string) []string {\n\tencountered := map[string]bool{}\n\tret := make([]string, 0)\n\tfor i := range s {\n\t\tif encountered[s[i]] {\n\t\t\tcontinue\n\t\t}\n\t\tencountered[s[i]] = true\n\t\tret = append(ret, s[i])\n\t}\n\treturn ret\n}","line":{"from":635,"to":647}} {"id":100028857,"name":"NewNonInteractiveDeferredLoadingClientConfig","signature":"func NewNonInteractiveDeferredLoadingClientConfig(loader ClientConfigLoader, overrides *ConfigOverrides) ClientConfig","file":"staging/src/k8s.io/client-go/tools/clientcmd/merged_client_builder.go","code":"// NewNonInteractiveDeferredLoadingClientConfig creates a ConfigClientClientConfig using the passed context name\nfunc NewNonInteractiveDeferredLoadingClientConfig(loader ClientConfigLoader, overrides *ConfigOverrides) ClientConfig {\n\treturn \u0026DeferredLoadingClientConfig{loader: loader, overrides: overrides, icc: \u0026inClusterClientConfig{overrides: overrides}}\n}","line":{"from":52,"to":55}} {"id":100028858,"name":"NewInteractiveDeferredLoadingClientConfig","signature":"func NewInteractiveDeferredLoadingClientConfig(loader ClientConfigLoader, overrides *ConfigOverrides, fallbackReader io.Reader) ClientConfig","file":"staging/src/k8s.io/client-go/tools/clientcmd/merged_client_builder.go","code":"// NewInteractiveDeferredLoadingClientConfig creates a ConfigClientClientConfig using the passed context name and the fallback auth reader\nfunc NewInteractiveDeferredLoadingClientConfig(loader ClientConfigLoader, overrides *ConfigOverrides, fallbackReader io.Reader) ClientConfig {\n\treturn \u0026DeferredLoadingClientConfig{loader: loader, overrides: overrides, icc: \u0026inClusterClientConfig{overrides: overrides}, fallbackReader: fallbackReader}\n}","line":{"from":57,"to":60}} {"id":100028859,"name":"createClientConfig","signature":"func (config *DeferredLoadingClientConfig) createClientConfig() (ClientConfig, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/merged_client_builder.go","code":"func (config *DeferredLoadingClientConfig) createClientConfig() (ClientConfig, error) {\n\tconfig.loadingLock.Lock()\n\tdefer config.loadingLock.Unlock()\n\n\tif config.clientConfig != nil {\n\t\treturn config.clientConfig, nil\n\t}\n\tmergedConfig, err := config.loader.Load()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar currentContext string\n\tif config.overrides != nil {\n\t\tcurrentContext = config.overrides.CurrentContext\n\t}\n\tif config.fallbackReader != nil {\n\t\tconfig.clientConfig = NewInteractiveClientConfig(*mergedConfig, currentContext, config.overrides, config.fallbackReader, config.loader)\n\t} else {\n\t\tconfig.clientConfig = NewNonInteractiveClientConfig(*mergedConfig, currentContext, config.overrides, config.loader)\n\t}\n\treturn config.clientConfig, nil\n}","line":{"from":62,"to":84}} {"id":100028860,"name":"RawConfig","signature":"func (config *DeferredLoadingClientConfig) RawConfig() (clientcmdapi.Config, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/merged_client_builder.go","code":"func (config *DeferredLoadingClientConfig) RawConfig() (clientcmdapi.Config, error) {\n\tmergedConfig, err := config.createClientConfig()\n\tif err != nil {\n\t\treturn clientcmdapi.Config{}, err\n\t}\n\n\treturn mergedConfig.RawConfig()\n}","line":{"from":86,"to":93}} {"id":100028861,"name":"ClientConfig","signature":"func (config *DeferredLoadingClientConfig) ClientConfig() (*restclient.Config, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/merged_client_builder.go","code":"// ClientConfig implements ClientConfig\nfunc (config *DeferredLoadingClientConfig) ClientConfig() (*restclient.Config, error) {\n\tmergedClientConfig, err := config.createClientConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// load the configuration and return on non-empty errors and if the\n\t// content differs from the default config\n\tmergedConfig, err := mergedClientConfig.ClientConfig()\n\tswitch {\n\tcase err != nil:\n\t\tif !IsEmptyConfig(err) {\n\t\t\t// return on any error except empty config\n\t\t\treturn nil, err\n\t\t}\n\tcase mergedConfig != nil:\n\t\t// the configuration is valid, but if this is equal to the defaults we should try\n\t\t// in-cluster configuration\n\t\tif !config.loader.IsDefaultConfig(mergedConfig) {\n\t\t\treturn mergedConfig, nil\n\t\t}\n\t}\n\n\t// check for in-cluster configuration and use it\n\tif config.icc.Possible() {\n\t\tklog.V(4).Infof(\"Using in-cluster configuration\")\n\t\treturn config.icc.ClientConfig()\n\t}\n\n\t// return the result of the merged client config\n\treturn mergedConfig, err\n}","line":{"from":95,"to":127}} {"id":100028862,"name":"Namespace","signature":"func (config *DeferredLoadingClientConfig) Namespace() (string, bool, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/merged_client_builder.go","code":"// Namespace implements KubeConfig\nfunc (config *DeferredLoadingClientConfig) Namespace() (string, bool, error) {\n\tmergedKubeConfig, err := config.createClientConfig()\n\tif err != nil {\n\t\treturn \"\", false, err\n\t}\n\n\tns, overridden, err := mergedKubeConfig.Namespace()\n\t// if we get an error and it is not empty config, or if the merged config defined an explicit namespace, or\n\t// if in-cluster config is not possible, return immediately\n\tif (err != nil \u0026\u0026 !IsEmptyConfig(err)) || overridden || !config.icc.Possible() {\n\t\t// return on any error except empty config\n\t\treturn ns, overridden, err\n\t}\n\n\tif len(ns) \u003e 0 {\n\t\t// if we got a non-default namespace from the kubeconfig, use it\n\t\tif ns != \"default\" {\n\t\t\treturn ns, false, nil\n\t\t}\n\n\t\t// if we got a default namespace, determine whether it was explicit or implicit\n\t\tif raw, err := mergedKubeConfig.RawConfig(); err == nil {\n\t\t\t// determine the current context\n\t\t\tcurrentContext := raw.CurrentContext\n\t\t\tif config.overrides != nil \u0026\u0026 len(config.overrides.CurrentContext) \u003e 0 {\n\t\t\t\tcurrentContext = config.overrides.CurrentContext\n\t\t\t}\n\t\t\tif context := raw.Contexts[currentContext]; context != nil \u0026\u0026 len(context.Namespace) \u003e 0 {\n\t\t\t\treturn ns, false, nil\n\t\t\t}\n\t\t}\n\t}\n\n\tklog.V(4).Infof(\"Using in-cluster namespace\")\n\n\t// allow the namespace from the service account token directory to be used.\n\treturn config.icc.Namespace()\n}","line":{"from":129,"to":167}} {"id":100028863,"name":"ConfigAccess","signature":"func (config *DeferredLoadingClientConfig) ConfigAccess() ConfigAccess","file":"staging/src/k8s.io/client-go/tools/clientcmd/merged_client_builder.go","code":"// ConfigAccess implements ClientConfig\nfunc (config *DeferredLoadingClientConfig) ConfigAccess() ConfigAccess {\n\treturn config.loader\n}","line":{"from":169,"to":172}} {"id":100028864,"name":"AddSecretAnnotation","signature":"func (f FlagInfo) AddSecretAnnotation(flags *pflag.FlagSet) FlagInfo","file":"staging/src/k8s.io/client-go/tools/clientcmd/overrides.go","code":"// AddSecretAnnotation add secret flag to Annotation.\nfunc (f FlagInfo) AddSecretAnnotation(flags *pflag.FlagSet) FlagInfo {\n\tflags.SetAnnotation(f.LongName, \"classified\", []string{\"true\"})\n\treturn f\n}","line":{"from":94,"to":98}} {"id":100028865,"name":"BindStringFlag","signature":"func (f FlagInfo) BindStringFlag(flags *pflag.FlagSet, target *string) FlagInfo","file":"staging/src/k8s.io/client-go/tools/clientcmd/overrides.go","code":"// BindStringFlag binds the flag based on the provided info. If LongName == \"\", nothing is registered\nfunc (f FlagInfo) BindStringFlag(flags *pflag.FlagSet, target *string) FlagInfo {\n\t// you can't register a flag without a long name\n\tif len(f.LongName) \u003e 0 {\n\t\tflags.StringVarP(target, f.LongName, f.ShortName, f.Default, f.Description)\n\t}\n\treturn f\n}","line":{"from":100,"to":107}} {"id":100028866,"name":"BindTransformingStringFlag","signature":"func (f FlagInfo) BindTransformingStringFlag(flags *pflag.FlagSet, target *string, transformer func(string) (string, error)) FlagInfo","file":"staging/src/k8s.io/client-go/tools/clientcmd/overrides.go","code":"// BindTransformingStringFlag binds the flag based on the provided info. If LongName == \"\", nothing is registered\nfunc (f FlagInfo) BindTransformingStringFlag(flags *pflag.FlagSet, target *string, transformer func(string) (string, error)) FlagInfo {\n\t// you can't register a flag without a long name\n\tif len(f.LongName) \u003e 0 {\n\t\tflags.VarP(newTransformingStringValue(f.Default, target, transformer), f.LongName, f.ShortName, f.Description)\n\t}\n\treturn f\n}","line":{"from":109,"to":116}} {"id":100028867,"name":"BindStringArrayFlag","signature":"func (f FlagInfo) BindStringArrayFlag(flags *pflag.FlagSet, target *[]string) FlagInfo","file":"staging/src/k8s.io/client-go/tools/clientcmd/overrides.go","code":"// BindStringSliceFlag binds the flag based on the provided info. If LongName == \"\", nothing is registered\nfunc (f FlagInfo) BindStringArrayFlag(flags *pflag.FlagSet, target *[]string) FlagInfo {\n\t// you can't register a flag without a long name\n\tif len(f.LongName) \u003e 0 {\n\t\tsliceVal := []string{}\n\t\tif len(f.Default) \u003e 0 {\n\t\t\tsliceVal = []string{f.Default}\n\t\t}\n\t\tflags.StringArrayVarP(target, f.LongName, f.ShortName, sliceVal, f.Description)\n\t}\n\treturn f\n}","line":{"from":118,"to":129}} {"id":100028868,"name":"BindBoolFlag","signature":"func (f FlagInfo) BindBoolFlag(flags *pflag.FlagSet, target *bool) FlagInfo","file":"staging/src/k8s.io/client-go/tools/clientcmd/overrides.go","code":"// BindBoolFlag binds the flag based on the provided info. If LongName == \"\", nothing is registered\nfunc (f FlagInfo) BindBoolFlag(flags *pflag.FlagSet, target *bool) FlagInfo {\n\t// you can't register a flag without a long name\n\tif len(f.LongName) \u003e 0 {\n\t\t// try to parse Default as a bool. If it fails, assume false\n\t\tboolVal, err := strconv.ParseBool(f.Default)\n\t\tif err != nil {\n\t\t\tboolVal = false\n\t\t}\n\n\t\tflags.BoolVarP(target, f.LongName, f.ShortName, boolVal, f.Description)\n\t}\n\treturn f\n}","line":{"from":131,"to":144}} {"id":100028869,"name":"RecommendedConfigOverrideFlags","signature":"func RecommendedConfigOverrideFlags(prefix string) ConfigOverrideFlags","file":"staging/src/k8s.io/client-go/tools/clientcmd/overrides.go","code":"// RecommendedConfigOverrideFlags is a convenience method to return recommended flag names prefixed with a string of your choosing\nfunc RecommendedConfigOverrideFlags(prefix string) ConfigOverrideFlags {\n\treturn ConfigOverrideFlags{\n\t\tAuthOverrideFlags: RecommendedAuthOverrideFlags(prefix),\n\t\tClusterOverrideFlags: RecommendedClusterOverrideFlags(prefix),\n\t\tContextOverrideFlags: RecommendedContextOverrideFlags(prefix),\n\n\t\tCurrentContext: FlagInfo{prefix + FlagContext, \"\", \"\", \"The name of the kubeconfig context to use\"},\n\t\tTimeout: FlagInfo{prefix + FlagTimeout, \"\", \"0\", \"The length of time to wait before giving up on a single server request. Non-zero values should contain a corresponding time unit (e.g. 1s, 2m, 3h). A value of zero means don't timeout requests.\"},\n\t}\n}","line":{"from":169,"to":179}} {"id":100028870,"name":"RecommendedAuthOverrideFlags","signature":"func RecommendedAuthOverrideFlags(prefix string) AuthOverrideFlags","file":"staging/src/k8s.io/client-go/tools/clientcmd/overrides.go","code":"// RecommendedAuthOverrideFlags is a convenience method to return recommended flag names prefixed with a string of your choosing\nfunc RecommendedAuthOverrideFlags(prefix string) AuthOverrideFlags {\n\treturn AuthOverrideFlags{\n\t\tClientCertificate: FlagInfo{prefix + FlagCertFile, \"\", \"\", \"Path to a client certificate file for TLS\"},\n\t\tClientKey: FlagInfo{prefix + FlagKeyFile, \"\", \"\", \"Path to a client key file for TLS\"},\n\t\tToken: FlagInfo{prefix + FlagBearerToken, \"\", \"\", \"Bearer token for authentication to the API server\"},\n\t\tImpersonate: FlagInfo{prefix + FlagImpersonate, \"\", \"\", \"Username to impersonate for the operation\"},\n\t\tImpersonateUID: FlagInfo{prefix + FlagImpersonateUID, \"\", \"\", \"UID to impersonate for the operation\"},\n\t\tImpersonateGroups: FlagInfo{prefix + FlagImpersonateGroup, \"\", \"\", \"Group to impersonate for the operation, this flag can be repeated to specify multiple groups.\"},\n\t\tUsername: FlagInfo{prefix + FlagUsername, \"\", \"\", \"Username for basic authentication to the API server\"},\n\t\tPassword: FlagInfo{prefix + FlagPassword, \"\", \"\", \"Password for basic authentication to the API server\"},\n\t}\n}","line":{"from":181,"to":193}} {"id":100028871,"name":"RecommendedClusterOverrideFlags","signature":"func RecommendedClusterOverrideFlags(prefix string) ClusterOverrideFlags","file":"staging/src/k8s.io/client-go/tools/clientcmd/overrides.go","code":"// RecommendedClusterOverrideFlags is a convenience method to return recommended flag names prefixed with a string of your choosing\nfunc RecommendedClusterOverrideFlags(prefix string) ClusterOverrideFlags {\n\treturn ClusterOverrideFlags{\n\t\tAPIServer: FlagInfo{prefix + FlagAPIServer, \"\", \"\", \"The address and port of the Kubernetes API server\"},\n\t\tCertificateAuthority: FlagInfo{prefix + FlagCAFile, \"\", \"\", \"Path to a cert file for the certificate authority\"},\n\t\tInsecureSkipTLSVerify: FlagInfo{prefix + FlagInsecure, \"\", \"false\", \"If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure\"},\n\t\tTLSServerName: FlagInfo{prefix + FlagTLSServerName, \"\", \"\", \"If provided, this name will be used to validate server certificate. If this is not provided, hostname used to contact the server is used.\"},\n\t\tProxyURL: FlagInfo{prefix + FlagProxyURL, \"\", \"\", \"If provided, this URL will be used to connect via proxy\"},\n\t\tDisableCompression: FlagInfo{prefix + FlagDisableCompression, \"\", \"\", \"If true, opt-out of response compression for all requests to the server\"},\n\t}\n}","line":{"from":195,"to":205}} {"id":100028872,"name":"RecommendedContextOverrideFlags","signature":"func RecommendedContextOverrideFlags(prefix string) ContextOverrideFlags","file":"staging/src/k8s.io/client-go/tools/clientcmd/overrides.go","code":"// RecommendedContextOverrideFlags is a convenience method to return recommended flag names prefixed with a string of your choosing\nfunc RecommendedContextOverrideFlags(prefix string) ContextOverrideFlags {\n\treturn ContextOverrideFlags{\n\t\tClusterName: FlagInfo{prefix + FlagClusterName, \"\", \"\", \"The name of the kubeconfig cluster to use\"},\n\t\tAuthInfoName: FlagInfo{prefix + FlagAuthInfoName, \"\", \"\", \"The name of the kubeconfig user to use\"},\n\t\tNamespace: FlagInfo{prefix + FlagNamespace, \"n\", \"\", \"If present, the namespace scope for this CLI request\"},\n\t}\n}","line":{"from":207,"to":214}} {"id":100028873,"name":"BindOverrideFlags","signature":"func BindOverrideFlags(overrides *ConfigOverrides, flags *pflag.FlagSet, flagNames ConfigOverrideFlags)","file":"staging/src/k8s.io/client-go/tools/clientcmd/overrides.go","code":"// BindOverrideFlags is a convenience method to bind the specified flags to their associated variables\nfunc BindOverrideFlags(overrides *ConfigOverrides, flags *pflag.FlagSet, flagNames ConfigOverrideFlags) {\n\tBindAuthInfoFlags(\u0026overrides.AuthInfo, flags, flagNames.AuthOverrideFlags)\n\tBindClusterFlags(\u0026overrides.ClusterInfo, flags, flagNames.ClusterOverrideFlags)\n\tBindContextFlags(\u0026overrides.Context, flags, flagNames.ContextOverrideFlags)\n\tflagNames.CurrentContext.BindStringFlag(flags, \u0026overrides.CurrentContext)\n\tflagNames.Timeout.BindStringFlag(flags, \u0026overrides.Timeout)\n}","line":{"from":216,"to":223}} {"id":100028874,"name":"BindAuthInfoFlags","signature":"func BindAuthInfoFlags(authInfo *clientcmdapi.AuthInfo, flags *pflag.FlagSet, flagNames AuthOverrideFlags)","file":"staging/src/k8s.io/client-go/tools/clientcmd/overrides.go","code":"// BindAuthInfoFlags is a convenience method to bind the specified flags to their associated variables\nfunc BindAuthInfoFlags(authInfo *clientcmdapi.AuthInfo, flags *pflag.FlagSet, flagNames AuthOverrideFlags) {\n\tflagNames.ClientCertificate.BindStringFlag(flags, \u0026authInfo.ClientCertificate).AddSecretAnnotation(flags)\n\tflagNames.ClientKey.BindStringFlag(flags, \u0026authInfo.ClientKey).AddSecretAnnotation(flags)\n\tflagNames.Token.BindStringFlag(flags, \u0026authInfo.Token).AddSecretAnnotation(flags)\n\tflagNames.Impersonate.BindStringFlag(flags, \u0026authInfo.Impersonate).AddSecretAnnotation(flags)\n\tflagNames.ImpersonateUID.BindStringFlag(flags, \u0026authInfo.ImpersonateUID).AddSecretAnnotation(flags)\n\tflagNames.ImpersonateGroups.BindStringArrayFlag(flags, \u0026authInfo.ImpersonateGroups).AddSecretAnnotation(flags)\n\tflagNames.Username.BindStringFlag(flags, \u0026authInfo.Username).AddSecretAnnotation(flags)\n\tflagNames.Password.BindStringFlag(flags, \u0026authInfo.Password).AddSecretAnnotation(flags)\n}","line":{"from":225,"to":235}} {"id":100028875,"name":"BindClusterFlags","signature":"func BindClusterFlags(clusterInfo *clientcmdapi.Cluster, flags *pflag.FlagSet, flagNames ClusterOverrideFlags)","file":"staging/src/k8s.io/client-go/tools/clientcmd/overrides.go","code":"// BindClusterFlags is a convenience method to bind the specified flags to their associated variables\nfunc BindClusterFlags(clusterInfo *clientcmdapi.Cluster, flags *pflag.FlagSet, flagNames ClusterOverrideFlags) {\n\tflagNames.APIServer.BindStringFlag(flags, \u0026clusterInfo.Server)\n\tflagNames.CertificateAuthority.BindStringFlag(flags, \u0026clusterInfo.CertificateAuthority)\n\tflagNames.InsecureSkipTLSVerify.BindBoolFlag(flags, \u0026clusterInfo.InsecureSkipTLSVerify)\n\tflagNames.TLSServerName.BindStringFlag(flags, \u0026clusterInfo.TLSServerName)\n\tflagNames.ProxyURL.BindStringFlag(flags, \u0026clusterInfo.ProxyURL)\n\tflagNames.DisableCompression.BindBoolFlag(flags, \u0026clusterInfo.DisableCompression)\n}","line":{"from":237,"to":245}} {"id":100028876,"name":"BindContextFlags","signature":"func BindContextFlags(contextInfo *clientcmdapi.Context, flags *pflag.FlagSet, flagNames ContextOverrideFlags)","file":"staging/src/k8s.io/client-go/tools/clientcmd/overrides.go","code":"// BindFlags is a convenience method to bind the specified flags to their associated variables\nfunc BindContextFlags(contextInfo *clientcmdapi.Context, flags *pflag.FlagSet, flagNames ContextOverrideFlags) {\n\tflagNames.ClusterName.BindStringFlag(flags, \u0026contextInfo.Cluster)\n\tflagNames.AuthInfoName.BindStringFlag(flags, \u0026contextInfo.AuthInfo)\n\tflagNames.Namespace.BindTransformingStringFlag(flags, \u0026contextInfo.Namespace, RemoveNamespacesPrefix)\n}","line":{"from":247,"to":252}} {"id":100028877,"name":"RemoveNamespacesPrefix","signature":"func RemoveNamespacesPrefix(value string) (string, error)","file":"staging/src/k8s.io/client-go/tools/clientcmd/overrides.go","code":"// RemoveNamespacesPrefix is a transformer that strips \"ns/\", \"namespace/\" and \"namespaces/\" prefixes case-insensitively\nfunc RemoveNamespacesPrefix(value string) (string, error) {\n\tfor _, prefix := range []string{\"namespaces/\", \"namespace/\", \"ns/\"} {\n\t\tif len(value) \u003e len(prefix) \u0026\u0026 strings.EqualFold(value[0:len(prefix)], prefix) {\n\t\t\tvalue = value[len(prefix):]\n\t\t\tbreak\n\t\t}\n\t}\n\treturn value, nil\n}","line":{"from":254,"to":263}} {"id":100028878,"name":"NewEmptyConfigError","signature":"func NewEmptyConfigError(message string) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/validation.go","code":"// NewEmptyConfigError returns an error wrapping the given message which IsEmptyConfig() will recognize as an empty config error\nfunc NewEmptyConfigError(message string) error {\n\treturn \u0026errEmptyConfig{message}\n}","line":{"from":38,"to":41}} {"id":100028879,"name":"Error","signature":"func (e *errEmptyConfig) Error() string","file":"staging/src/k8s.io/client-go/tools/clientcmd/validation.go","code":"func (e *errEmptyConfig) Error() string {\n\treturn e.message\n}","line":{"from":47,"to":49}} {"id":100028880,"name":"Error","signature":"func (e *errContextNotFound) Error() string","file":"staging/src/k8s.io/client-go/tools/clientcmd/validation.go","code":"func (e *errContextNotFound) Error() string {\n\treturn fmt.Sprintf(\"context was not found for specified context: %v\", e.ContextName)\n}","line":{"from":55,"to":57}} {"id":100028881,"name":"IsContextNotFound","signature":"func IsContextNotFound(err error) bool","file":"staging/src/k8s.io/client-go/tools/clientcmd/validation.go","code":"// IsContextNotFound returns a boolean indicating whether the error is known to\n// report that a context was not found\nfunc IsContextNotFound(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\tif _, ok := err.(*errContextNotFound); ok || err == ErrNoContext {\n\t\treturn true\n\t}\n\treturn strings.Contains(err.Error(), \"context was not found for specified context\")\n}","line":{"from":59,"to":69}} {"id":100028882,"name":"IsEmptyConfig","signature":"func IsEmptyConfig(err error) bool","file":"staging/src/k8s.io/client-go/tools/clientcmd/validation.go","code":"// IsEmptyConfig returns true if the provided error indicates the provided configuration\n// is empty.\nfunc IsEmptyConfig(err error) bool {\n\tswitch t := err.(type) {\n\tcase errConfigurationInvalid:\n\t\tif len(t) != 1 {\n\t\t\treturn false\n\t\t}\n\t\t_, ok := t[0].(*errEmptyConfig)\n\t\treturn ok\n\t}\n\t_, ok := err.(*errEmptyConfig)\n\treturn ok\n}","line":{"from":71,"to":84}} {"id":100028883,"name":"newErrConfigurationInvalid","signature":"func newErrConfigurationInvalid(errs []error) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/validation.go","code":"func newErrConfigurationInvalid(errs []error) error {\n\tswitch len(errs) {\n\tcase 0:\n\t\treturn nil\n\tdefault:\n\t\treturn errConfigurationInvalid(errs)\n\t}\n}","line":{"from":93,"to":100}} {"id":100028884,"name":"Error","signature":"func (e errConfigurationInvalid) Error() string","file":"staging/src/k8s.io/client-go/tools/clientcmd/validation.go","code":"// Error implements the error interface\nfunc (e errConfigurationInvalid) Error() string {\n\treturn fmt.Sprintf(\"invalid configuration: %v\", utilerrors.NewAggregate(e).Error())\n}","line":{"from":102,"to":105}} {"id":100028885,"name":"Errors","signature":"func (e errConfigurationInvalid) Errors() []error","file":"staging/src/k8s.io/client-go/tools/clientcmd/validation.go","code":"// Errors implements the utilerrors.Aggregate interface\nfunc (e errConfigurationInvalid) Errors() []error {\n\treturn e\n}","line":{"from":107,"to":110}} {"id":100028886,"name":"Is","signature":"func (e errConfigurationInvalid) Is(target error) bool","file":"staging/src/k8s.io/client-go/tools/clientcmd/validation.go","code":"// Is implements the utilerrors.Aggregate interface\nfunc (e errConfigurationInvalid) Is(target error) bool {\n\treturn e.visit(func(err error) bool {\n\t\treturn errors.Is(err, target)\n\t})\n}","line":{"from":112,"to":117}} {"id":100028887,"name":"visit","signature":"func (e errConfigurationInvalid) visit(f func(err error) bool) bool","file":"staging/src/k8s.io/client-go/tools/clientcmd/validation.go","code":"func (e errConfigurationInvalid) visit(f func(err error) bool) bool {\n\tfor _, err := range e {\n\t\tswitch err := err.(type) {\n\t\tcase errConfigurationInvalid:\n\t\t\tif match := err.visit(f); match {\n\t\t\t\treturn match\n\t\t\t}\n\t\tcase utilerrors.Aggregate:\n\t\t\tfor _, nestedErr := range err.Errors() {\n\t\t\t\tif match := f(nestedErr); match {\n\t\t\t\t\treturn match\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\tif match := f(err); match {\n\t\t\t\treturn match\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":119,"to":140}} {"id":100028888,"name":"IsConfigurationInvalid","signature":"func IsConfigurationInvalid(err error) bool","file":"staging/src/k8s.io/client-go/tools/clientcmd/validation.go","code":"// IsConfigurationInvalid returns true if the provided error indicates the configuration is invalid.\nfunc IsConfigurationInvalid(err error) bool {\n\tswitch err.(type) {\n\tcase *errContextNotFound, errConfigurationInvalid:\n\t\treturn true\n\t}\n\treturn IsContextNotFound(err)\n}","line":{"from":142,"to":149}} {"id":100028889,"name":"Validate","signature":"func Validate(config clientcmdapi.Config) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/validation.go","code":"// Validate checks for errors in the Config. It does not return early so that it can find as many errors as possible.\nfunc Validate(config clientcmdapi.Config) error {\n\tvalidationErrors := make([]error, 0)\n\n\tif clientcmdapi.IsConfigEmpty(\u0026config) {\n\t\treturn newErrConfigurationInvalid([]error{ErrEmptyConfig})\n\t}\n\n\tif len(config.CurrentContext) != 0 {\n\t\tif _, exists := config.Contexts[config.CurrentContext]; !exists {\n\t\t\tvalidationErrors = append(validationErrors, \u0026errContextNotFound{config.CurrentContext})\n\t\t}\n\t}\n\n\tfor contextName, context := range config.Contexts {\n\t\tvalidationErrors = append(validationErrors, validateContext(contextName, *context, config)...)\n\t}\n\n\tfor authInfoName, authInfo := range config.AuthInfos {\n\t\tvalidationErrors = append(validationErrors, validateAuthInfo(authInfoName, *authInfo)...)\n\t}\n\n\tfor clusterName, clusterInfo := range config.Clusters {\n\t\tvalidationErrors = append(validationErrors, validateClusterInfo(clusterName, *clusterInfo)...)\n\t}\n\n\treturn newErrConfigurationInvalid(validationErrors)\n}","line":{"from":151,"to":178}} {"id":100028890,"name":"ConfirmUsable","signature":"func ConfirmUsable(config clientcmdapi.Config, passedContextName string) error","file":"staging/src/k8s.io/client-go/tools/clientcmd/validation.go","code":"// ConfirmUsable looks a particular context and determines if that particular part of the config is useable. There might still be errors in the config,\n// but no errors in the sections requested or referenced. It does not return early so that it can find as many errors as possible.\nfunc ConfirmUsable(config clientcmdapi.Config, passedContextName string) error {\n\tvalidationErrors := make([]error, 0)\n\n\tif clientcmdapi.IsConfigEmpty(\u0026config) {\n\t\treturn newErrConfigurationInvalid([]error{ErrEmptyConfig})\n\t}\n\n\tvar contextName string\n\tif len(passedContextName) != 0 {\n\t\tcontextName = passedContextName\n\t} else {\n\t\tcontextName = config.CurrentContext\n\t}\n\n\tif len(contextName) == 0 {\n\t\treturn ErrNoContext\n\t}\n\n\tcontext, exists := config.Contexts[contextName]\n\tif !exists {\n\t\tvalidationErrors = append(validationErrors, \u0026errContextNotFound{contextName})\n\t}\n\n\tif exists {\n\t\tvalidationErrors = append(validationErrors, validateContext(contextName, *context, config)...)\n\n\t\t// Default to empty users and clusters and let the validation function report an error.\n\t\tauthInfo := config.AuthInfos[context.AuthInfo]\n\t\tif authInfo == nil {\n\t\t\tauthInfo = \u0026clientcmdapi.AuthInfo{}\n\t\t}\n\t\tvalidationErrors = append(validationErrors, validateAuthInfo(context.AuthInfo, *authInfo)...)\n\n\t\tcluster := config.Clusters[context.Cluster]\n\t\tif cluster == nil {\n\t\t\tcluster = \u0026clientcmdapi.Cluster{}\n\t\t}\n\t\tvalidationErrors = append(validationErrors, validateClusterInfo(context.Cluster, *cluster)...)\n\t}\n\n\treturn newErrConfigurationInvalid(validationErrors)\n}","line":{"from":180,"to":223}} {"id":100028891,"name":"validateClusterInfo","signature":"func validateClusterInfo(clusterName string, clusterInfo clientcmdapi.Cluster) []error","file":"staging/src/k8s.io/client-go/tools/clientcmd/validation.go","code":"// validateClusterInfo looks for conflicts and errors in the cluster info\nfunc validateClusterInfo(clusterName string, clusterInfo clientcmdapi.Cluster) []error {\n\tvalidationErrors := make([]error, 0)\n\n\temptyCluster := clientcmdapi.NewCluster()\n\tif reflect.DeepEqual(*emptyCluster, clusterInfo) {\n\t\treturn []error{ErrEmptyCluster}\n\t}\n\n\tif len(clusterInfo.Server) == 0 {\n\t\tif len(clusterName) == 0 {\n\t\t\tvalidationErrors = append(validationErrors, fmt.Errorf(\"default cluster has no server defined\"))\n\t\t} else {\n\t\t\tvalidationErrors = append(validationErrors, fmt.Errorf(\"no server found for cluster %q\", clusterName))\n\t\t}\n\t}\n\tif proxyURL := clusterInfo.ProxyURL; proxyURL != \"\" {\n\t\tif _, err := parseProxyURL(proxyURL); err != nil {\n\t\t\tvalidationErrors = append(validationErrors, fmt.Errorf(\"invalid 'proxy-url' %q for cluster %q: %w\", proxyURL, clusterName, err))\n\t\t}\n\t}\n\t// Make sure CA data and CA file aren't both specified\n\tif len(clusterInfo.CertificateAuthority) != 0 \u0026\u0026 len(clusterInfo.CertificateAuthorityData) != 0 {\n\t\tvalidationErrors = append(validationErrors, fmt.Errorf(\"certificate-authority-data and certificate-authority are both specified for %v. certificate-authority-data will override.\", clusterName))\n\t}\n\tif len(clusterInfo.CertificateAuthority) != 0 {\n\t\tclientCertCA, err := os.Open(clusterInfo.CertificateAuthority)\n\t\tif err != nil {\n\t\t\tvalidationErrors = append(validationErrors, fmt.Errorf(\"unable to read certificate-authority %v for %v due to %w\", clusterInfo.CertificateAuthority, clusterName, err))\n\t\t} else {\n\t\t\tdefer clientCertCA.Close()\n\t\t}\n\t}\n\n\treturn validationErrors\n}","line":{"from":225,"to":260}} {"id":100028892,"name":"validateAuthInfo","signature":"func validateAuthInfo(authInfoName string, authInfo clientcmdapi.AuthInfo) []error","file":"staging/src/k8s.io/client-go/tools/clientcmd/validation.go","code":"// validateAuthInfo looks for conflicts and errors in the auth info\nfunc validateAuthInfo(authInfoName string, authInfo clientcmdapi.AuthInfo) []error {\n\tvalidationErrors := make([]error, 0)\n\n\tusingAuthPath := false\n\tmethods := make([]string, 0, 3)\n\tif len(authInfo.Token) != 0 {\n\t\tmethods = append(methods, \"token\")\n\t}\n\tif len(authInfo.Username) != 0 || len(authInfo.Password) != 0 {\n\t\tmethods = append(methods, \"basicAuth\")\n\t}\n\n\tif len(authInfo.ClientCertificate) != 0 || len(authInfo.ClientCertificateData) != 0 {\n\t\t// Make sure cert data and file aren't both specified\n\t\tif len(authInfo.ClientCertificate) != 0 \u0026\u0026 len(authInfo.ClientCertificateData) != 0 {\n\t\t\tvalidationErrors = append(validationErrors, fmt.Errorf(\"client-cert-data and client-cert are both specified for %v. client-cert-data will override.\", authInfoName))\n\t\t}\n\t\t// Make sure key data and file aren't both specified\n\t\tif len(authInfo.ClientKey) != 0 \u0026\u0026 len(authInfo.ClientKeyData) != 0 {\n\t\t\tvalidationErrors = append(validationErrors, fmt.Errorf(\"client-key-data and client-key are both specified for %v; client-key-data will override\", authInfoName))\n\t\t}\n\t\t// Make sure a key is specified\n\t\tif len(authInfo.ClientKey) == 0 \u0026\u0026 len(authInfo.ClientKeyData) == 0 {\n\t\t\tvalidationErrors = append(validationErrors, fmt.Errorf(\"client-key-data or client-key must be specified for %v to use the clientCert authentication method.\", authInfoName))\n\t\t}\n\n\t\tif len(authInfo.ClientCertificate) != 0 {\n\t\t\tclientCertFile, err := os.Open(authInfo.ClientCertificate)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrors = append(validationErrors, fmt.Errorf(\"unable to read client-cert %v for %v due to %w\", authInfo.ClientCertificate, authInfoName, err))\n\t\t\t} else {\n\t\t\t\tdefer clientCertFile.Close()\n\t\t\t}\n\t\t}\n\t\tif len(authInfo.ClientKey) != 0 {\n\t\t\tclientKeyFile, err := os.Open(authInfo.ClientKey)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrors = append(validationErrors, fmt.Errorf(\"unable to read client-key %v for %v due to %w\", authInfo.ClientKey, authInfoName, err))\n\t\t\t} else {\n\t\t\t\tdefer clientKeyFile.Close()\n\t\t\t}\n\t\t}\n\t}\n\n\tif authInfo.Exec != nil {\n\t\tif authInfo.AuthProvider != nil {\n\t\t\tvalidationErrors = append(validationErrors, fmt.Errorf(\"authProvider cannot be provided in combination with an exec plugin for %s\", authInfoName))\n\t\t}\n\t\tif len(authInfo.Exec.Command) == 0 {\n\t\t\tvalidationErrors = append(validationErrors, fmt.Errorf(\"command must be specified for %v to use exec authentication plugin\", authInfoName))\n\t\t}\n\t\tif len(authInfo.Exec.APIVersion) == 0 {\n\t\t\tvalidationErrors = append(validationErrors, fmt.Errorf(\"apiVersion must be specified for %v to use exec authentication plugin\", authInfoName))\n\t\t}\n\t\tfor _, v := range authInfo.Exec.Env {\n\t\t\tif len(v.Name) == 0 {\n\t\t\t\tvalidationErrors = append(validationErrors, fmt.Errorf(\"env variable name must be specified for %v to use exec authentication plugin\", authInfoName))\n\t\t\t}\n\t\t}\n\t\tswitch authInfo.Exec.InteractiveMode {\n\t\tcase \"\":\n\t\t\tvalidationErrors = append(validationErrors, fmt.Errorf(\"interactiveMode must be specified for %v to use exec authentication plugin\", authInfoName))\n\t\tcase clientcmdapi.NeverExecInteractiveMode, clientcmdapi.IfAvailableExecInteractiveMode, clientcmdapi.AlwaysExecInteractiveMode:\n\t\t\t// These are valid\n\t\tdefault:\n\t\t\tvalidationErrors = append(validationErrors, fmt.Errorf(\"invalid interactiveMode for %v: %q\", authInfoName, authInfo.Exec.InteractiveMode))\n\t\t}\n\t}\n\n\t// authPath also provides information for the client to identify the server, so allow multiple auth methods in that case\n\tif (len(methods) \u003e 1) \u0026\u0026 (!usingAuthPath) {\n\t\tvalidationErrors = append(validationErrors, fmt.Errorf(\"more than one authentication method found for %v; found %v, only one is allowed\", authInfoName, methods))\n\t}\n\n\t// ImpersonateUID, ImpersonateGroups or ImpersonateUserExtra should be requested with a user\n\tif (len(authInfo.ImpersonateUID) \u003e 0 || len(authInfo.ImpersonateGroups) \u003e 0 || len(authInfo.ImpersonateUserExtra) \u003e 0) \u0026\u0026 (len(authInfo.Impersonate) == 0) {\n\t\tvalidationErrors = append(validationErrors, fmt.Errorf(\"requesting uid, groups or user-extra for %v without impersonating a user\", authInfoName))\n\t}\n\treturn validationErrors\n}","line":{"from":262,"to":342}} {"id":100028893,"name":"validateContext","signature":"func validateContext(contextName string, context clientcmdapi.Context, config clientcmdapi.Config) []error","file":"staging/src/k8s.io/client-go/tools/clientcmd/validation.go","code":"// validateContext looks for errors in the context. It is not transitive, so errors in the reference authInfo or cluster configs are not included in this return\nfunc validateContext(contextName string, context clientcmdapi.Context, config clientcmdapi.Config) []error {\n\tvalidationErrors := make([]error, 0)\n\n\tif len(contextName) == 0 {\n\t\tvalidationErrors = append(validationErrors, fmt.Errorf(\"empty context name for %#v is not allowed\", context))\n\t}\n\n\tif len(context.AuthInfo) == 0 {\n\t\tvalidationErrors = append(validationErrors, fmt.Errorf(\"user was not specified for context %q\", contextName))\n\t} else if _, exists := config.AuthInfos[context.AuthInfo]; !exists {\n\t\tvalidationErrors = append(validationErrors, fmt.Errorf(\"user %q was not found for context %q\", context.AuthInfo, contextName))\n\t}\n\n\tif len(context.Cluster) == 0 {\n\t\tvalidationErrors = append(validationErrors, fmt.Errorf(\"cluster was not specified for context %q\", contextName))\n\t} else if _, exists := config.Clusters[context.Cluster]; !exists {\n\t\tvalidationErrors = append(validationErrors, fmt.Errorf(\"cluster %q was not found for context %q\", context.Cluster, contextName))\n\t}\n\n\tif len(context.Namespace) != 0 {\n\t\tif len(validation.IsDNS1123Label(context.Namespace)) != 0 {\n\t\t\tvalidationErrors = append(validationErrors, fmt.Errorf(\"namespace %q for context %q does not conform to the kubernetes DNS_LABEL rules\", context.Namespace, contextName))\n\t\t}\n\t}\n\n\treturn validationErrors\n}","line":{"from":344,"to":371}} {"id":100028894,"name":"Create","signature":"func (e *EventSinkImpl) Create(event *eventsv1.Event) (*eventsv1.Event, error)","file":"staging/src/k8s.io/client-go/tools/events/event_broadcaster.go","code":"// Create takes the representation of a event and creates it. Returns the server's representation of the event, and an error, if there is any.\nfunc (e *EventSinkImpl) Create(event *eventsv1.Event) (*eventsv1.Event, error) {\n\tif event.Namespace == \"\" {\n\t\treturn nil, fmt.Errorf(\"can't create an event with empty namespace\")\n\t}\n\treturn e.Interface.Events(event.Namespace).Create(context.TODO(), event, metav1.CreateOptions{})\n}","line":{"from":83,"to":89}} {"id":100028895,"name":"Update","signature":"func (e *EventSinkImpl) Update(event *eventsv1.Event) (*eventsv1.Event, error)","file":"staging/src/k8s.io/client-go/tools/events/event_broadcaster.go","code":"// Update takes the representation of a event and updates it. Returns the server's representation of the event, and an error, if there is any.\nfunc (e *EventSinkImpl) Update(event *eventsv1.Event) (*eventsv1.Event, error) {\n\tif event.Namespace == \"\" {\n\t\treturn nil, fmt.Errorf(\"can't update an event with empty namespace\")\n\t}\n\treturn e.Interface.Events(event.Namespace).Update(context.TODO(), event, metav1.UpdateOptions{})\n}","line":{"from":91,"to":97}} {"id":100028896,"name":"Patch","signature":"func (e *EventSinkImpl) Patch(event *eventsv1.Event, data []byte) (*eventsv1.Event, error)","file":"staging/src/k8s.io/client-go/tools/events/event_broadcaster.go","code":"// Patch applies the patch and returns the patched event, and an error, if there is any.\nfunc (e *EventSinkImpl) Patch(event *eventsv1.Event, data []byte) (*eventsv1.Event, error) {\n\tif event.Namespace == \"\" {\n\t\treturn nil, fmt.Errorf(\"can't patch an event with empty namespace\")\n\t}\n\treturn e.Interface.Events(event.Namespace).Patch(context.TODO(), event.Name, types.StrategicMergePatchType, data, metav1.PatchOptions{})\n}","line":{"from":99,"to":105}} {"id":100028897,"name":"NewBroadcaster","signature":"func NewBroadcaster(sink EventSink) EventBroadcaster","file":"staging/src/k8s.io/client-go/tools/events/event_broadcaster.go","code":"// NewBroadcaster Creates a new event broadcaster.\nfunc NewBroadcaster(sink EventSink) EventBroadcaster {\n\treturn newBroadcaster(sink, defaultSleepDuration, map[eventKey]*eventsv1.Event{})\n}","line":{"from":107,"to":110}} {"id":100028898,"name":"newBroadcaster","signature":"func newBroadcaster(sink EventSink, sleepDuration time.Duration, eventCache map[eventKey]*eventsv1.Event) EventBroadcaster","file":"staging/src/k8s.io/client-go/tools/events/event_broadcaster.go","code":"// NewBroadcasterForTest Creates a new event broadcaster for test purposes.\nfunc newBroadcaster(sink EventSink, sleepDuration time.Duration, eventCache map[eventKey]*eventsv1.Event) EventBroadcaster {\n\treturn \u0026eventBroadcasterImpl{\n\t\tBroadcaster: watch.NewBroadcaster(maxQueuedEvents, watch.DropIfChannelFull),\n\t\teventCache: eventCache,\n\t\tsleepDuration: sleepDuration,\n\t\tsink: sink,\n\t}\n}","line":{"from":112,"to":120}} {"id":100028899,"name":"Shutdown","signature":"func (e *eventBroadcasterImpl) Shutdown()","file":"staging/src/k8s.io/client-go/tools/events/event_broadcaster.go","code":"func (e *eventBroadcasterImpl) Shutdown() {\n\te.Broadcaster.Shutdown()\n}","line":{"from":122,"to":124}} {"id":100028900,"name":"refreshExistingEventSeries","signature":"func (e *eventBroadcasterImpl) refreshExistingEventSeries()","file":"staging/src/k8s.io/client-go/tools/events/event_broadcaster.go","code":"// refreshExistingEventSeries refresh events TTL\nfunc (e *eventBroadcasterImpl) refreshExistingEventSeries() {\n\t// TODO: Investigate whether lock contention won't be a problem\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\tfor isomorphicKey, event := range e.eventCache {\n\t\tif event.Series != nil {\n\t\t\tif recordedEvent, retry := recordEvent(e.sink, event); !retry {\n\t\t\t\tif recordedEvent != nil {\n\t\t\t\t\te.eventCache[isomorphicKey] = recordedEvent\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":126,"to":140}} {"id":100028901,"name":"finishSeries","signature":"func (e *eventBroadcasterImpl) finishSeries()","file":"staging/src/k8s.io/client-go/tools/events/event_broadcaster.go","code":"// finishSeries checks if a series has ended and either:\n// - write final count to the apiserver\n// - delete a singleton event (i.e. series field is nil) from the cache\nfunc (e *eventBroadcasterImpl) finishSeries() {\n\t// TODO: Investigate whether lock contention won't be a problem\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\tfor isomorphicKey, event := range e.eventCache {\n\t\teventSerie := event.Series\n\t\tif eventSerie != nil {\n\t\t\tif eventSerie.LastObservedTime.Time.Before(time.Now().Add(-finishTime)) {\n\t\t\t\tif _, retry := recordEvent(e.sink, event); !retry {\n\t\t\t\t\tdelete(e.eventCache, isomorphicKey)\n\t\t\t\t}\n\t\t\t}\n\t\t} else if event.EventTime.Time.Before(time.Now().Add(-finishTime)) {\n\t\t\tdelete(e.eventCache, isomorphicKey)\n\t\t}\n\t}\n}","line":{"from":142,"to":161}} {"id":100028902,"name":"NewRecorder","signature":"func (e *eventBroadcasterImpl) NewRecorder(scheme *runtime.Scheme, reportingController string) EventRecorder","file":"staging/src/k8s.io/client-go/tools/events/event_broadcaster.go","code":"// NewRecorder returns an EventRecorder that records events with the given event source.\nfunc (e *eventBroadcasterImpl) NewRecorder(scheme *runtime.Scheme, reportingController string) EventRecorder {\n\thostname, _ := os.Hostname()\n\treportingInstance := reportingController + \"-\" + hostname\n\treturn \u0026recorderImpl{scheme, reportingController, reportingInstance, e.Broadcaster, clock.RealClock{}}\n}","line":{"from":163,"to":168}} {"id":100028903,"name":"recordToSink","signature":"func (e *eventBroadcasterImpl) recordToSink(event *eventsv1.Event, clock clock.Clock)","file":"staging/src/k8s.io/client-go/tools/events/event_broadcaster.go","code":"func (e *eventBroadcasterImpl) recordToSink(event *eventsv1.Event, clock clock.Clock) {\n\t// Make a copy before modification, because there could be multiple listeners.\n\teventCopy := event.DeepCopy()\n\tgo func() {\n\t\tevToRecord := func() *eventsv1.Event {\n\t\t\te.mu.Lock()\n\t\t\tdefer e.mu.Unlock()\n\t\t\teventKey := getKey(eventCopy)\n\t\t\tisomorphicEvent, isIsomorphic := e.eventCache[eventKey]\n\t\t\tif isIsomorphic {\n\t\t\t\tif isomorphicEvent.Series != nil {\n\t\t\t\t\tisomorphicEvent.Series.Count++\n\t\t\t\t\tisomorphicEvent.Series.LastObservedTime = metav1.MicroTime{Time: clock.Now()}\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\tisomorphicEvent.Series = \u0026eventsv1.EventSeries{\n\t\t\t\t\tCount: 2,\n\t\t\t\t\tLastObservedTime: metav1.MicroTime{Time: clock.Now()},\n\t\t\t\t}\n\t\t\t\t// Make a copy of the Event to make sure that recording it\n\t\t\t\t// doesn't mess with the object stored in cache.\n\t\t\t\treturn isomorphicEvent.DeepCopy()\n\t\t\t}\n\t\t\te.eventCache[eventKey] = eventCopy\n\t\t\t// Make a copy of the Event to make sure that recording it doesn't\n\t\t\t// mess with the object stored in cache.\n\t\t\treturn eventCopy.DeepCopy()\n\t\t}()\n\t\tif evToRecord != nil {\n\t\t\t// TODO: Add a metric counting the number of recording attempts\n\t\t\te.attemptRecording(evToRecord)\n\t\t\t// We don't want the new recorded Event to be reflected in the\n\t\t\t// client's cache because server-side mutations could mess with the\n\t\t\t// aggregation mechanism used by the client.\n\t\t}\n\t}()\n}","line":{"from":170,"to":206}} {"id":100028904,"name":"attemptRecording","signature":"func (e *eventBroadcasterImpl) attemptRecording(event *eventsv1.Event) *eventsv1.Event","file":"staging/src/k8s.io/client-go/tools/events/event_broadcaster.go","code":"func (e *eventBroadcasterImpl) attemptRecording(event *eventsv1.Event) *eventsv1.Event {\n\ttries := 0\n\tfor {\n\t\tif recordedEvent, retry := recordEvent(e.sink, event); !retry {\n\t\t\treturn recordedEvent\n\t\t}\n\t\ttries++\n\t\tif tries \u003e= maxTriesPerEvent {\n\t\t\tklog.Errorf(\"Unable to write event '%#v' (retry limit exceeded!)\", event)\n\t\t\treturn nil\n\t\t}\n\t\t// Randomize sleep so that various clients won't all be\n\t\t// synced up if the master goes down.\n\t\ttime.Sleep(wait.Jitter(e.sleepDuration, 0.25))\n\t}\n}","line":{"from":208,"to":223}} {"id":100028905,"name":"recordEvent","signature":"func recordEvent(sink EventSink, event *eventsv1.Event) (*eventsv1.Event, bool)","file":"staging/src/k8s.io/client-go/tools/events/event_broadcaster.go","code":"func recordEvent(sink EventSink, event *eventsv1.Event) (*eventsv1.Event, bool) {\n\tvar newEvent *eventsv1.Event\n\tvar err error\n\tisEventSeries := event.Series != nil\n\tif isEventSeries {\n\t\tpatch, patchBytesErr := createPatchBytesForSeries(event)\n\t\tif patchBytesErr != nil {\n\t\t\tklog.Errorf(\"Unable to calculate diff, no merge is possible: %v\", patchBytesErr)\n\t\t\treturn nil, false\n\t\t}\n\t\tnewEvent, err = sink.Patch(event, patch)\n\t}\n\t// Update can fail because the event may have been removed and it no longer exists.\n\tif !isEventSeries || (isEventSeries \u0026\u0026 util.IsKeyNotFoundError(err)) {\n\t\t// Making sure that ResourceVersion is empty on creation\n\t\tevent.ResourceVersion = \"\"\n\t\tnewEvent, err = sink.Create(event)\n\t}\n\tif err == nil {\n\t\treturn newEvent, false\n\t}\n\t// If we can't contact the server, then hold everything while we keep trying.\n\t// Otherwise, something about the event is malformed and we should abandon it.\n\tswitch err.(type) {\n\tcase *restclient.RequestConstructionError:\n\t\t// We will construct the request the same next time, so don't keep trying.\n\t\tklog.Errorf(\"Unable to construct event '%#v': '%v' (will not retry!)\", event, err)\n\t\treturn nil, false\n\tcase *errors.StatusError:\n\t\tif errors.IsAlreadyExists(err) {\n\t\t\t// If we tried to create an Event from an EventSerie, it means that\n\t\t\t// the original Patch request failed because the Event we were\n\t\t\t// trying to patch didn't exist. If the creation failed because the\n\t\t\t// Event now exists, it is safe to retry. This occurs when a new\n\t\t\t// Event is emitted twice in a very short period of time.\n\t\t\tif isEventSeries {\n\t\t\t\treturn nil, true\n\t\t\t}\n\t\t\tklog.V(5).Infof(\"Server rejected event '%#v': '%v' (will not retry!)\", event, err)\n\t\t} else {\n\t\t\tklog.Errorf(\"Server rejected event '%#v': '%v' (will not retry!)\", event, err)\n\t\t}\n\t\treturn nil, false\n\tcase *errors.UnexpectedObjectError:\n\t\t// We don't expect this; it implies the server's response didn't match a\n\t\t// known pattern. Go ahead and retry.\n\tdefault:\n\t\t// This case includes actual http transport errors. Go ahead and retry.\n\t}\n\tklog.Errorf(\"Unable to write event: '%v' (may retry after sleeping)\", err)\n\treturn nil, true\n}","line":{"from":225,"to":276}} {"id":100028906,"name":"createPatchBytesForSeries","signature":"func createPatchBytesForSeries(event *eventsv1.Event) ([]byte, error)","file":"staging/src/k8s.io/client-go/tools/events/event_broadcaster.go","code":"func createPatchBytesForSeries(event *eventsv1.Event) ([]byte, error) {\n\toldEvent := event.DeepCopy()\n\toldEvent.Series = nil\n\toldData, err := json.Marshal(oldEvent)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnewData, err := json.Marshal(event)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn strategicpatch.CreateTwoWayMergePatch(oldData, newData, eventsv1.Event{})\n}","line":{"from":278,"to":290}} {"id":100028907,"name":"getKey","signature":"func getKey(event *eventsv1.Event) eventKey","file":"staging/src/k8s.io/client-go/tools/events/event_broadcaster.go","code":"func getKey(event *eventsv1.Event) eventKey {\n\tkey := eventKey{\n\t\teventType: event.Type,\n\t\taction: event.Action,\n\t\treason: event.Reason,\n\t\treportingController: event.ReportingController,\n\t\treportingInstance: event.ReportingInstance,\n\t\tregarding: event.Regarding,\n\t}\n\tif event.Related != nil {\n\t\tkey.related = *event.Related\n\t}\n\treturn key\n}","line":{"from":292,"to":305}} {"id":100028908,"name":"StartStructuredLogging","signature":"func (e *eventBroadcasterImpl) StartStructuredLogging(verbosity klog.Level) func()","file":"staging/src/k8s.io/client-go/tools/events/event_broadcaster.go","code":"// StartStructuredLogging starts sending events received from this EventBroadcaster to the structured logging function.\n// The return value can be ignored or used to stop recording, if desired.\n// TODO: this function should also return an error.\nfunc (e *eventBroadcasterImpl) StartStructuredLogging(verbosity klog.Level) func() {\n\tstopWatcher, err := e.StartEventWatcher(\n\t\tfunc(obj runtime.Object) {\n\t\t\tevent, ok := obj.(*eventsv1.Event)\n\t\t\tif !ok {\n\t\t\t\tklog.Errorf(\"unexpected type, expected eventsv1.Event\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tklog.V(verbosity).InfoS(\"Event occurred\", \"object\", klog.KRef(event.Regarding.Namespace, event.Regarding.Name), \"kind\", event.Regarding.Kind, \"apiVersion\", event.Regarding.APIVersion, \"type\", event.Type, \"reason\", event.Reason, \"action\", event.Action, \"note\", event.Note)\n\t\t})\n\tif err != nil {\n\t\tklog.Errorf(\"failed to start event watcher: '%v'\", err)\n\t\treturn func() {}\n\t}\n\treturn stopWatcher\n}","line":{"from":307,"to":325}} {"id":100028909,"name":"StartEventWatcher","signature":"func (e *eventBroadcasterImpl) StartEventWatcher(eventHandler func(event runtime.Object)) (func(), error)","file":"staging/src/k8s.io/client-go/tools/events/event_broadcaster.go","code":"// StartEventWatcher starts sending events received from this EventBroadcaster to the given event handler function.\n// The return value is used to stop recording\nfunc (e *eventBroadcasterImpl) StartEventWatcher(eventHandler func(event runtime.Object)) (func(), error) {\n\twatcher, err := e.Watch()\n\tif err != nil {\n\t\tklog.Errorf(\"Unable start event watcher: '%v' (will not retry!)\", err)\n\t\treturn nil, err\n\t}\n\tgo func() {\n\t\tdefer utilruntime.HandleCrash()\n\t\tfor {\n\t\t\twatchEvent, ok := \u003c-watcher.ResultChan()\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\teventHandler(watchEvent.Object)\n\t\t}\n\t}()\n\treturn watcher.Stop, nil\n}","line":{"from":327,"to":346}} {"id":100028910,"name":"startRecordingEvents","signature":"func (e *eventBroadcasterImpl) startRecordingEvents(stopCh \u003c-chan struct{}) error","file":"staging/src/k8s.io/client-go/tools/events/event_broadcaster.go","code":"func (e *eventBroadcasterImpl) startRecordingEvents(stopCh \u003c-chan struct{}) error {\n\teventHandler := func(obj runtime.Object) {\n\t\tevent, ok := obj.(*eventsv1.Event)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"unexpected type, expected eventsv1.Event\")\n\t\t\treturn\n\t\t}\n\t\te.recordToSink(event, clock.RealClock{})\n\t}\n\tstopWatcher, err := e.StartEventWatcher(eventHandler)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo func() {\n\t\t\u003c-stopCh\n\t\tstopWatcher()\n\t}()\n\treturn nil\n}","line":{"from":348,"to":366}} {"id":100028911,"name":"StartRecordingToSink","signature":"func (e *eventBroadcasterImpl) StartRecordingToSink(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/client-go/tools/events/event_broadcaster.go","code":"// StartRecordingToSink starts sending events received from the specified eventBroadcaster to the given sink.\nfunc (e *eventBroadcasterImpl) StartRecordingToSink(stopCh \u003c-chan struct{}) {\n\tgo wait.Until(e.refreshExistingEventSeries, refreshTime, stopCh)\n\tgo wait.Until(e.finishSeries, finishTime, stopCh)\n\terr := e.startRecordingEvents(stopCh)\n\tif err != nil {\n\t\tklog.Errorf(\"unexpected type, expected eventsv1.Event\")\n\t\treturn\n\t}\n}","line":{"from":368,"to":377}} {"id":100028912,"name":"NewEventBroadcasterAdapter","signature":"func NewEventBroadcasterAdapter(client clientset.Interface) EventBroadcasterAdapter","file":"staging/src/k8s.io/client-go/tools/events/event_broadcaster.go","code":"// NewEventBroadcasterAdapter creates a wrapper around new and legacy broadcasters to simplify\n// migration of individual components to the new Event API.\nfunc NewEventBroadcasterAdapter(client clientset.Interface) EventBroadcasterAdapter {\n\teventClient := \u0026eventBroadcasterAdapterImpl{}\n\tif _, err := client.Discovery().ServerResourcesForGroupVersion(eventsv1.SchemeGroupVersion.String()); err == nil {\n\t\teventClient.eventsv1Client = client.EventsV1()\n\t\teventClient.eventsv1Broadcaster = NewBroadcaster(\u0026EventSinkImpl{Interface: eventClient.eventsv1Client})\n\t}\n\t// Even though there can soon exist cases when coreBroadcaster won't really be needed,\n\t// we create it unconditionally because its overhead is minor and will simplify using usage\n\t// patterns of this library in all components.\n\teventClient.coreClient = client.CoreV1()\n\teventClient.coreBroadcaster = record.NewBroadcaster()\n\treturn eventClient\n}","line":{"from":386,"to":400}} {"id":100028913,"name":"StartRecordingToSink","signature":"func (e *eventBroadcasterAdapterImpl) StartRecordingToSink(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/client-go/tools/events/event_broadcaster.go","code":"// StartRecordingToSink starts sending events received from the specified eventBroadcaster to the given sink.\nfunc (e *eventBroadcasterAdapterImpl) StartRecordingToSink(stopCh \u003c-chan struct{}) {\n\tif e.eventsv1Broadcaster != nil \u0026\u0026 e.eventsv1Client != nil {\n\t\te.eventsv1Broadcaster.StartRecordingToSink(stopCh)\n\t}\n\tif e.coreBroadcaster != nil \u0026\u0026 e.coreClient != nil {\n\t\te.coreBroadcaster.StartRecordingToSink(\u0026typedv1core.EventSinkImpl{Interface: e.coreClient.Events(\"\")})\n\t}\n}","line":{"from":402,"to":410}} {"id":100028914,"name":"NewRecorder","signature":"func (e *eventBroadcasterAdapterImpl) NewRecorder(name string) EventRecorder","file":"staging/src/k8s.io/client-go/tools/events/event_broadcaster.go","code":"func (e *eventBroadcasterAdapterImpl) NewRecorder(name string) EventRecorder {\n\tif e.eventsv1Broadcaster != nil \u0026\u0026 e.eventsv1Client != nil {\n\t\treturn e.eventsv1Broadcaster.NewRecorder(scheme.Scheme, name)\n\t}\n\treturn record.NewEventRecorderAdapter(e.DeprecatedNewLegacyRecorder(name))\n}","line":{"from":412,"to":417}} {"id":100028915,"name":"DeprecatedNewLegacyRecorder","signature":"func (e *eventBroadcasterAdapterImpl) DeprecatedNewLegacyRecorder(name string) record.EventRecorder","file":"staging/src/k8s.io/client-go/tools/events/event_broadcaster.go","code":"func (e *eventBroadcasterAdapterImpl) DeprecatedNewLegacyRecorder(name string) record.EventRecorder {\n\treturn e.coreBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: name})\n}","line":{"from":419,"to":421}} {"id":100028916,"name":"Shutdown","signature":"func (e *eventBroadcasterAdapterImpl) Shutdown()","file":"staging/src/k8s.io/client-go/tools/events/event_broadcaster.go","code":"func (e *eventBroadcasterAdapterImpl) Shutdown() {\n\tif e.coreBroadcaster != nil {\n\t\te.coreBroadcaster.Shutdown()\n\t}\n\tif e.eventsv1Broadcaster != nil {\n\t\te.eventsv1Broadcaster.Shutdown()\n\t}\n}","line":{"from":423,"to":430}} {"id":100028917,"name":"Eventf","signature":"func (recorder *recorderImpl) Eventf(regarding runtime.Object, related runtime.Object, eventtype, reason, action, note string, args ...interface{})","file":"staging/src/k8s.io/client-go/tools/events/event_recorder.go","code":"func (recorder *recorderImpl) Eventf(regarding runtime.Object, related runtime.Object, eventtype, reason, action, note string, args ...interface{}) {\n\ttimestamp := metav1.MicroTime{Time: time.Now()}\n\tmessage := fmt.Sprintf(note, args...)\n\trefRegarding, err := reference.GetReference(recorder.scheme, regarding)\n\tif err != nil {\n\t\tklog.Errorf(\"Could not construct reference to: '%#v' due to: '%v'. Will not report event: '%v' '%v' '%v'\", regarding, err, eventtype, reason, message)\n\t\treturn\n\t}\n\n\tvar refRelated *v1.ObjectReference\n\tif related != nil {\n\t\trefRelated, err = reference.GetReference(recorder.scheme, related)\n\t\tif err != nil {\n\t\t\tklog.V(9).Infof(\"Could not construct reference to: '%#v' due to: '%v'.\", related, err)\n\t\t}\n\t}\n\tif !util.ValidateEventType(eventtype) {\n\t\tklog.Errorf(\"Unsupported event type: '%v'\", eventtype)\n\t\treturn\n\t}\n\tevent := recorder.makeEvent(refRegarding, refRelated, timestamp, eventtype, reason, message, recorder.reportingController, recorder.reportingInstance, action)\n\tgo func() {\n\t\tdefer utilruntime.HandleCrash()\n\t\trecorder.Action(watch.Added, event)\n\t}()\n}","line":{"from":43,"to":68}} {"id":100028918,"name":"makeEvent","signature":"func (recorder *recorderImpl) makeEvent(refRegarding *v1.ObjectReference, refRelated *v1.ObjectReference, timestamp metav1.MicroTime, eventtype, reason, message string, reportingController string, reportingInstance string, action string) *eventsv1.Event","file":"staging/src/k8s.io/client-go/tools/events/event_recorder.go","code":"func (recorder *recorderImpl) makeEvent(refRegarding *v1.ObjectReference, refRelated *v1.ObjectReference, timestamp metav1.MicroTime, eventtype, reason, message string, reportingController string, reportingInstance string, action string) *eventsv1.Event {\n\tt := metav1.Time{Time: recorder.clock.Now()}\n\tnamespace := refRegarding.Namespace\n\tif namespace == \"\" {\n\t\tnamespace = metav1.NamespaceDefault\n\t}\n\treturn \u0026eventsv1.Event{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: fmt.Sprintf(\"%v.%x\", refRegarding.Name, t.UnixNano()),\n\t\t\tNamespace: namespace,\n\t\t},\n\t\tEventTime: timestamp,\n\t\tSeries: nil,\n\t\tReportingController: reportingController,\n\t\tReportingInstance: reportingInstance,\n\t\tAction: action,\n\t\tReason: reason,\n\t\tRegarding: *refRegarding,\n\t\tRelated: refRelated,\n\t\tNote: message,\n\t\tType: eventtype,\n\t}\n}","line":{"from":70,"to":92}} {"id":100028919,"name":"GetFieldSelector","signature":"func GetFieldSelector(eventsGroupVersion schema.GroupVersion, regardingGroupVersionKind schema.GroupVersionKind, regardingName string, regardingUID types.UID) (fields.Selector, error)","file":"staging/src/k8s.io/client-go/tools/events/helper.go","code":"// GetFieldSelector returns the appropriate field selector based on the API version being used to communicate with the server.\n// The returned field selector can be used with List and Watch to filter desired events.\nfunc GetFieldSelector(eventsGroupVersion schema.GroupVersion, regardingGroupVersionKind schema.GroupVersionKind, regardingName string, regardingUID types.UID) (fields.Selector, error) {\n\tfield := fields.Set{}\n\n\tif _, ok := mapping[eventsGroupVersion]; !ok {\n\t\treturn nil, fmt.Errorf(\"unknown version %v\", eventsGroupVersion)\n\t}\n\tprefix := mapping[eventsGroupVersion]\n\n\tif len(regardingName) \u003e 0 {\n\t\tfield[prefix+\".name\"] = regardingName\n\t}\n\n\tif len(regardingGroupVersionKind.Kind) \u003e 0 {\n\t\tfield[prefix+\".kind\"] = regardingGroupVersionKind.Kind\n\t}\n\n\tregardingGroupVersion := regardingGroupVersionKind.GroupVersion()\n\tif !regardingGroupVersion.Empty() {\n\t\tfield[prefix+\".apiVersion\"] = regardingGroupVersion.String()\n\t}\n\n\tif len(regardingUID) \u003e 0 {\n\t\tfield[prefix+\".uid\"] = string(regardingUID)\n\t}\n\n\treturn field.AsSelector(), nil\n}","line":{"from":36,"to":64}} {"id":100028920,"name":"Name","signature":"func (l *HealthzAdaptor) Name() string","file":"staging/src/k8s.io/client-go/tools/leaderelection/healthzadaptor.go","code":"// Name returns the name of the health check we are implementing.\nfunc (l *HealthzAdaptor) Name() string {\n\treturn \"leaderElection\"\n}","line":{"from":38,"to":41}} {"id":100028921,"name":"Check","signature":"func (l *HealthzAdaptor) Check(req *http.Request) error","file":"staging/src/k8s.io/client-go/tools/leaderelection/healthzadaptor.go","code":"// Check is called by the healthz endpoint handler.\n// It fails (returns an error) if we own the lease but had not been able to renew it.\nfunc (l *HealthzAdaptor) Check(req *http.Request) error {\n\tl.pointerLock.Lock()\n\tdefer l.pointerLock.Unlock()\n\tif l.le == nil {\n\t\treturn nil\n\t}\n\treturn l.le.Check(l.timeout)\n}","line":{"from":43,"to":52}} {"id":100028922,"name":"SetLeaderElection","signature":"func (l *HealthzAdaptor) SetLeaderElection(le *LeaderElector)","file":"staging/src/k8s.io/client-go/tools/leaderelection/healthzadaptor.go","code":"// SetLeaderElection ties a leader election object to a HealthzAdaptor\nfunc (l *HealthzAdaptor) SetLeaderElection(le *LeaderElector) {\n\tl.pointerLock.Lock()\n\tdefer l.pointerLock.Unlock()\n\tl.le = le\n}","line":{"from":54,"to":59}} {"id":100028923,"name":"NewLeaderHealthzAdaptor","signature":"func NewLeaderHealthzAdaptor(timeout time.Duration) *HealthzAdaptor","file":"staging/src/k8s.io/client-go/tools/leaderelection/healthzadaptor.go","code":"// NewLeaderHealthzAdaptor creates a basic healthz adaptor to monitor a leader election.\n// timeout determines the time beyond the lease expiry to be allowed for timeout.\n// checks within the timeout period after the lease expires will still return healthy.\nfunc NewLeaderHealthzAdaptor(timeout time.Duration) *HealthzAdaptor {\n\tresult := \u0026HealthzAdaptor{\n\t\ttimeout: timeout,\n\t}\n\treturn result\n}","line":{"from":61,"to":69}} {"id":100028924,"name":"NewLeaderElector","signature":"func NewLeaderElector(lec LeaderElectionConfig) (*LeaderElector, error)","file":"staging/src/k8s.io/client-go/tools/leaderelection/leaderelection.go","code":"// NewLeaderElector creates a LeaderElector from a LeaderElectionConfig\nfunc NewLeaderElector(lec LeaderElectionConfig) (*LeaderElector, error) {\n\tif lec.LeaseDuration \u003c= lec.RenewDeadline {\n\t\treturn nil, fmt.Errorf(\"leaseDuration must be greater than renewDeadline\")\n\t}\n\tif lec.RenewDeadline \u003c= time.Duration(JitterFactor*float64(lec.RetryPeriod)) {\n\t\treturn nil, fmt.Errorf(\"renewDeadline must be greater than retryPeriod*JitterFactor\")\n\t}\n\tif lec.LeaseDuration \u003c 1 {\n\t\treturn nil, fmt.Errorf(\"leaseDuration must be greater than zero\")\n\t}\n\tif lec.RenewDeadline \u003c 1 {\n\t\treturn nil, fmt.Errorf(\"renewDeadline must be greater than zero\")\n\t}\n\tif lec.RetryPeriod \u003c 1 {\n\t\treturn nil, fmt.Errorf(\"retryPeriod must be greater than zero\")\n\t}\n\tif lec.Callbacks.OnStartedLeading == nil {\n\t\treturn nil, fmt.Errorf(\"OnStartedLeading callback must not be nil\")\n\t}\n\tif lec.Callbacks.OnStoppedLeading == nil {\n\t\treturn nil, fmt.Errorf(\"OnStoppedLeading callback must not be nil\")\n\t}\n\n\tif lec.Lock == nil {\n\t\treturn nil, fmt.Errorf(\"Lock must not be nil.\")\n\t}\n\tle := LeaderElector{\n\t\tconfig: lec,\n\t\tclock: clock.RealClock{},\n\t\tmetrics: globalMetricsFactory.newLeaderMetrics(),\n\t}\n\tle.metrics.leaderOff(le.config.Name)\n\treturn \u0026le, nil\n}","line":{"from":75,"to":109}} {"id":100028925,"name":"Run","signature":"func (le *LeaderElector) Run(ctx context.Context)","file":"staging/src/k8s.io/client-go/tools/leaderelection/leaderelection.go","code":"// Run starts the leader election loop. Run will not return\n// before leader election loop is stopped by ctx or it has\n// stopped holding the leader lease\nfunc (le *LeaderElector) Run(ctx context.Context) {\n\tdefer runtime.HandleCrash()\n\tdefer le.config.Callbacks.OnStoppedLeading()\n\n\tif !le.acquire(ctx) {\n\t\treturn // ctx signalled done\n\t}\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\tgo le.config.Callbacks.OnStartedLeading(ctx)\n\tle.renew(ctx)\n}","line":{"from":196,"to":210}} {"id":100028926,"name":"RunOrDie","signature":"func RunOrDie(ctx context.Context, lec LeaderElectionConfig)","file":"staging/src/k8s.io/client-go/tools/leaderelection/leaderelection.go","code":"// RunOrDie starts a client with the provided config or panics if the config\n// fails to validate. RunOrDie blocks until leader election loop is\n// stopped by ctx or it has stopped holding the leader lease\nfunc RunOrDie(ctx context.Context, lec LeaderElectionConfig) {\n\tle, err := NewLeaderElector(lec)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif lec.WatchDog != nil {\n\t\tlec.WatchDog.SetLeaderElection(le)\n\t}\n\tle.Run(ctx)\n}","line":{"from":212,"to":224}} {"id":100028927,"name":"GetLeader","signature":"func (le *LeaderElector) GetLeader() string","file":"staging/src/k8s.io/client-go/tools/leaderelection/leaderelection.go","code":"// GetLeader returns the identity of the last observed leader or returns the empty string if\n// no leader has yet been observed.\n// This function is for informational purposes. (e.g. monitoring, logs, etc.)\nfunc (le *LeaderElector) GetLeader() string {\n\treturn le.getObservedRecord().HolderIdentity\n}","line":{"from":226,"to":231}} {"id":100028928,"name":"IsLeader","signature":"func (le *LeaderElector) IsLeader() bool","file":"staging/src/k8s.io/client-go/tools/leaderelection/leaderelection.go","code":"// IsLeader returns true if the last observed leader was this client else returns false.\nfunc (le *LeaderElector) IsLeader() bool {\n\treturn le.getObservedRecord().HolderIdentity == le.config.Lock.Identity()\n}","line":{"from":233,"to":236}} {"id":100028929,"name":"acquire","signature":"func (le *LeaderElector) acquire(ctx context.Context) bool","file":"staging/src/k8s.io/client-go/tools/leaderelection/leaderelection.go","code":"// acquire loops calling tryAcquireOrRenew and returns true immediately when tryAcquireOrRenew succeeds.\n// Returns false if ctx signals done.\nfunc (le *LeaderElector) acquire(ctx context.Context) bool {\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\tsucceeded := false\n\tdesc := le.config.Lock.Describe()\n\tklog.Infof(\"attempting to acquire leader lease %v...\", desc)\n\twait.JitterUntil(func() {\n\t\tsucceeded = le.tryAcquireOrRenew(ctx)\n\t\tle.maybeReportTransition()\n\t\tif !succeeded {\n\t\t\tklog.V(4).Infof(\"failed to acquire lease %v\", desc)\n\t\t\treturn\n\t\t}\n\t\tle.config.Lock.RecordEvent(\"became leader\")\n\t\tle.metrics.leaderOn(le.config.Name)\n\t\tklog.Infof(\"successfully acquired lease %v\", desc)\n\t\tcancel()\n\t}, le.config.RetryPeriod, JitterFactor, true, ctx.Done())\n\treturn succeeded\n}","line":{"from":238,"to":259}} {"id":100028930,"name":"renew","signature":"func (le *LeaderElector) renew(ctx context.Context)","file":"staging/src/k8s.io/client-go/tools/leaderelection/leaderelection.go","code":"// renew loops calling tryAcquireOrRenew and returns immediately when tryAcquireOrRenew fails or ctx signals done.\nfunc (le *LeaderElector) renew(ctx context.Context) {\n\tdefer le.config.Lock.RecordEvent(\"stopped leading\")\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\twait.Until(func() {\n\t\ttimeoutCtx, timeoutCancel := context.WithTimeout(ctx, le.config.RenewDeadline)\n\t\tdefer timeoutCancel()\n\t\terr := wait.PollImmediateUntil(le.config.RetryPeriod, func() (bool, error) {\n\t\t\treturn le.tryAcquireOrRenew(timeoutCtx), nil\n\t\t}, timeoutCtx.Done())\n\n\t\tle.maybeReportTransition()\n\t\tdesc := le.config.Lock.Describe()\n\t\tif err == nil {\n\t\t\tklog.V(5).Infof(\"successfully renewed lease %v\", desc)\n\t\t\treturn\n\t\t}\n\t\tle.metrics.leaderOff(le.config.Name)\n\t\tklog.Infof(\"failed to renew lease %v: %v\", desc, err)\n\t\tcancel()\n\t}, le.config.RetryPeriod, ctx.Done())\n\n\t// if we hold the lease, give it up\n\tif le.config.ReleaseOnCancel {\n\t\tle.release()\n\t}\n}","line":{"from":261,"to":288}} {"id":100028931,"name":"release","signature":"func (le *LeaderElector) release() bool","file":"staging/src/k8s.io/client-go/tools/leaderelection/leaderelection.go","code":"// release attempts to release the leader lease if we have acquired it.\nfunc (le *LeaderElector) release() bool {\n\tif !le.IsLeader() {\n\t\treturn true\n\t}\n\tnow := metav1.NewTime(le.clock.Now())\n\tleaderElectionRecord := rl.LeaderElectionRecord{\n\t\tLeaderTransitions: le.observedRecord.LeaderTransitions,\n\t\tLeaseDurationSeconds: 1,\n\t\tRenewTime: now,\n\t\tAcquireTime: now,\n\t}\n\tif err := le.config.Lock.Update(context.TODO(), leaderElectionRecord); err != nil {\n\t\tklog.Errorf(\"Failed to release lock: %v\", err)\n\t\treturn false\n\t}\n\n\tle.setObservedRecord(\u0026leaderElectionRecord)\n\treturn true\n}","line":{"from":290,"to":309}} {"id":100028932,"name":"tryAcquireOrRenew","signature":"func (le *LeaderElector) tryAcquireOrRenew(ctx context.Context) bool","file":"staging/src/k8s.io/client-go/tools/leaderelection/leaderelection.go","code":"// tryAcquireOrRenew tries to acquire a leader lease if it is not already acquired,\n// else it tries to renew the lease if it has already been acquired. Returns true\n// on success else returns false.\nfunc (le *LeaderElector) tryAcquireOrRenew(ctx context.Context) bool {\n\tnow := metav1.NewTime(le.clock.Now())\n\tleaderElectionRecord := rl.LeaderElectionRecord{\n\t\tHolderIdentity: le.config.Lock.Identity(),\n\t\tLeaseDurationSeconds: int(le.config.LeaseDuration / time.Second),\n\t\tRenewTime: now,\n\t\tAcquireTime: now,\n\t}\n\n\t// 1. obtain or create the ElectionRecord\n\toldLeaderElectionRecord, oldLeaderElectionRawRecord, err := le.config.Lock.Get(ctx)\n\tif err != nil {\n\t\tif !errors.IsNotFound(err) {\n\t\t\tklog.Errorf(\"error retrieving resource lock %v: %v\", le.config.Lock.Describe(), err)\n\t\t\treturn false\n\t\t}\n\t\tif err = le.config.Lock.Create(ctx, leaderElectionRecord); err != nil {\n\t\t\tklog.Errorf(\"error initially creating leader election record: %v\", err)\n\t\t\treturn false\n\t\t}\n\n\t\tle.setObservedRecord(\u0026leaderElectionRecord)\n\n\t\treturn true\n\t}\n\n\t// 2. Record obtained, check the Identity \u0026 Time\n\tif !bytes.Equal(le.observedRawRecord, oldLeaderElectionRawRecord) {\n\t\tle.setObservedRecord(oldLeaderElectionRecord)\n\n\t\tle.observedRawRecord = oldLeaderElectionRawRecord\n\t}\n\tif len(oldLeaderElectionRecord.HolderIdentity) \u003e 0 \u0026\u0026\n\t\tle.observedTime.Add(time.Second*time.Duration(oldLeaderElectionRecord.LeaseDurationSeconds)).After(now.Time) \u0026\u0026\n\t\t!le.IsLeader() {\n\t\tklog.V(4).Infof(\"lock is held by %v and has not yet expired\", oldLeaderElectionRecord.HolderIdentity)\n\t\treturn false\n\t}\n\n\t// 3. We're going to try to update. The leaderElectionRecord is set to it's default\n\t// here. Let's correct it before updating.\n\tif le.IsLeader() {\n\t\tleaderElectionRecord.AcquireTime = oldLeaderElectionRecord.AcquireTime\n\t\tleaderElectionRecord.LeaderTransitions = oldLeaderElectionRecord.LeaderTransitions\n\t} else {\n\t\tleaderElectionRecord.LeaderTransitions = oldLeaderElectionRecord.LeaderTransitions + 1\n\t}\n\n\t// update the lock itself\n\tif err = le.config.Lock.Update(ctx, leaderElectionRecord); err != nil {\n\t\tklog.Errorf(\"Failed to update lock: %v\", err)\n\t\treturn false\n\t}\n\n\tle.setObservedRecord(\u0026leaderElectionRecord)\n\treturn true\n}","line":{"from":311,"to":370}} {"id":100028933,"name":"maybeReportTransition","signature":"func (le *LeaderElector) maybeReportTransition()","file":"staging/src/k8s.io/client-go/tools/leaderelection/leaderelection.go","code":"func (le *LeaderElector) maybeReportTransition() {\n\tif le.observedRecord.HolderIdentity == le.reportedLeader {\n\t\treturn\n\t}\n\tle.reportedLeader = le.observedRecord.HolderIdentity\n\tif le.config.Callbacks.OnNewLeader != nil {\n\t\tgo le.config.Callbacks.OnNewLeader(le.reportedLeader)\n\t}\n}","line":{"from":372,"to":380}} {"id":100028934,"name":"Check","signature":"func (le *LeaderElector) Check(maxTolerableExpiredLease time.Duration) error","file":"staging/src/k8s.io/client-go/tools/leaderelection/leaderelection.go","code":"// Check will determine if the current lease is expired by more than timeout.\nfunc (le *LeaderElector) Check(maxTolerableExpiredLease time.Duration) error {\n\tif !le.IsLeader() {\n\t\t// Currently not concerned with the case that we are hot standby\n\t\treturn nil\n\t}\n\t// If we are more than timeout seconds after the lease duration that is past the timeout\n\t// on the lease renew. Time to start reporting ourselves as unhealthy. We should have\n\t// died but conditions like deadlock can prevent this. (See #70819)\n\tif le.clock.Since(le.observedTime) \u003e le.config.LeaseDuration+maxTolerableExpiredLease {\n\t\treturn fmt.Errorf(\"failed election to renew leadership on lease %s\", le.config.Name)\n\t}\n\n\treturn nil\n}","line":{"from":382,"to":396}} {"id":100028935,"name":"setObservedRecord","signature":"func (le *LeaderElector) setObservedRecord(observedRecord *rl.LeaderElectionRecord)","file":"staging/src/k8s.io/client-go/tools/leaderelection/leaderelection.go","code":"// setObservedRecord will set a new observedRecord and update observedTime to the current time.\n// Protect critical sections with lock.\nfunc (le *LeaderElector) setObservedRecord(observedRecord *rl.LeaderElectionRecord) {\n\tle.observedRecordLock.Lock()\n\tdefer le.observedRecordLock.Unlock()\n\n\tle.observedRecord = *observedRecord\n\tle.observedTime = le.clock.Now()\n}","line":{"from":398,"to":406}} {"id":100028936,"name":"getObservedRecord","signature":"func (le *LeaderElector) getObservedRecord() rl.LeaderElectionRecord","file":"staging/src/k8s.io/client-go/tools/leaderelection/leaderelection.go","code":"// getObservedRecord returns observersRecord.\n// Protect critical sections with lock.\nfunc (le *LeaderElector) getObservedRecord() rl.LeaderElectionRecord {\n\tle.observedRecordLock.Lock()\n\tdefer le.observedRecordLock.Unlock()\n\n\treturn le.observedRecord\n}","line":{"from":408,"to":415}} {"id":100028937,"name":"On","signature":"func (noopMetric) On(name string) {}","file":"staging/src/k8s.io/client-go/tools/leaderelection/metrics.go","code":"func (noopMetric) On(name string) {}","line":{"from":40,"to":40}} {"id":100028938,"name":"Off","signature":"func (noopMetric) Off(name string) {}","file":"staging/src/k8s.io/client-go/tools/leaderelection/metrics.go","code":"func (noopMetric) Off(name string) {}","line":{"from":41,"to":41}} {"id":100028939,"name":"leaderOn","signature":"func (m *defaultLeaderMetrics) leaderOn(name string)","file":"staging/src/k8s.io/client-go/tools/leaderelection/metrics.go","code":"func (m *defaultLeaderMetrics) leaderOn(name string) {\n\tif m == nil {\n\t\treturn\n\t}\n\tm.leader.On(name)\n}","line":{"from":49,"to":54}} {"id":100028940,"name":"leaderOff","signature":"func (m *defaultLeaderMetrics) leaderOff(name string)","file":"staging/src/k8s.io/client-go/tools/leaderelection/metrics.go","code":"func (m *defaultLeaderMetrics) leaderOff(name string) {\n\tif m == nil {\n\t\treturn\n\t}\n\tm.leader.Off(name)\n}","line":{"from":56,"to":61}} {"id":100028941,"name":"leaderOn","signature":"func (noMetrics) leaderOn(name string) {}","file":"staging/src/k8s.io/client-go/tools/leaderelection/metrics.go","code":"func (noMetrics) leaderOn(name string) {}","line":{"from":65,"to":65}} {"id":100028942,"name":"leaderOff","signature":"func (noMetrics) leaderOff(name string) {}","file":"staging/src/k8s.io/client-go/tools/leaderelection/metrics.go","code":"func (noMetrics) leaderOff(name string) {}","line":{"from":66,"to":66}} {"id":100028943,"name":"NewLeaderMetric","signature":"func (_ noopMetricsProvider) NewLeaderMetric() SwitchMetric","file":"staging/src/k8s.io/client-go/tools/leaderelection/metrics.go","code":"func (_ noopMetricsProvider) NewLeaderMetric() SwitchMetric {\n\treturn noopMetric{}\n}","line":{"from":75,"to":77}} {"id":100028944,"name":"setProvider","signature":"func (f *leaderMetricsFactory) setProvider(mp MetricsProvider)","file":"staging/src/k8s.io/client-go/tools/leaderelection/metrics.go","code":"func (f *leaderMetricsFactory) setProvider(mp MetricsProvider) {\n\tf.onlyOnce.Do(func() {\n\t\tf.metricsProvider = mp\n\t})\n}","line":{"from":89,"to":93}} {"id":100028945,"name":"newLeaderMetrics","signature":"func (f *leaderMetricsFactory) newLeaderMetrics() leaderMetricsAdapter","file":"staging/src/k8s.io/client-go/tools/leaderelection/metrics.go","code":"func (f *leaderMetricsFactory) newLeaderMetrics() leaderMetricsAdapter {\n\tmp := f.metricsProvider\n\tif mp == (noopMetricsProvider{}) {\n\t\treturn noMetrics{}\n\t}\n\treturn \u0026defaultLeaderMetrics{\n\t\tleader: mp.NewLeaderMetric(),\n\t}\n}","line":{"from":95,"to":103}} {"id":100028946,"name":"SetProvider","signature":"func SetProvider(metricsProvider MetricsProvider)","file":"staging/src/k8s.io/client-go/tools/leaderelection/metrics.go","code":"// SetProvider sets the metrics provider for all subsequently created work\n// queues. Only the first call has an effect.\nfunc SetProvider(metricsProvider MetricsProvider) {\n\tglobalMetricsFactory.setProvider(metricsProvider)\n}","line":{"from":105,"to":109}} {"id":100028947,"name":"Get","signature":"func (cml *configMapLock) Get(ctx context.Context) (*LeaderElectionRecord, []byte, error)","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/configmaplock.go","code":"// Get returns the election record from a ConfigMap Annotation\nfunc (cml *configMapLock) Get(ctx context.Context) (*LeaderElectionRecord, []byte, error) {\n\tvar record LeaderElectionRecord\n\tcm, err := cml.Client.ConfigMaps(cml.ConfigMapMeta.Namespace).Get(ctx, cml.ConfigMapMeta.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tcml.cm = cm\n\tif cml.cm.Annotations == nil {\n\t\tcml.cm.Annotations = make(map[string]string)\n\t}\n\trecordStr, found := cml.cm.Annotations[LeaderElectionRecordAnnotationKey]\n\trecordBytes := []byte(recordStr)\n\tif found {\n\t\tif err := json.Unmarshal(recordBytes, \u0026record); err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\treturn \u0026record, recordBytes, nil\n}","line":{"from":44,"to":63}} {"id":100028948,"name":"Create","signature":"func (cml *configMapLock) Create(ctx context.Context, ler LeaderElectionRecord) error","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/configmaplock.go","code":"// Create attempts to create a LeaderElectionRecord annotation\nfunc (cml *configMapLock) Create(ctx context.Context, ler LeaderElectionRecord) error {\n\trecordBytes, err := json.Marshal(ler)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcml.cm, err = cml.Client.ConfigMaps(cml.ConfigMapMeta.Namespace).Create(ctx, \u0026v1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cml.ConfigMapMeta.Name,\n\t\t\tNamespace: cml.ConfigMapMeta.Namespace,\n\t\t\tAnnotations: map[string]string{\n\t\t\t\tLeaderElectionRecordAnnotationKey: string(recordBytes),\n\t\t\t},\n\t\t},\n\t}, metav1.CreateOptions{})\n\treturn err\n}","line":{"from":65,"to":81}} {"id":100028949,"name":"Update","signature":"func (cml *configMapLock) Update(ctx context.Context, ler LeaderElectionRecord) error","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/configmaplock.go","code":"// Update will update an existing annotation on a given resource.\nfunc (cml *configMapLock) Update(ctx context.Context, ler LeaderElectionRecord) error {\n\tif cml.cm == nil {\n\t\treturn errors.New(\"configmap not initialized, call get or create first\")\n\t}\n\trecordBytes, err := json.Marshal(ler)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif cml.cm.Annotations == nil {\n\t\tcml.cm.Annotations = make(map[string]string)\n\t}\n\tcml.cm.Annotations[LeaderElectionRecordAnnotationKey] = string(recordBytes)\n\tcm, err := cml.Client.ConfigMaps(cml.ConfigMapMeta.Namespace).Update(ctx, cml.cm, metav1.UpdateOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\tcml.cm = cm\n\treturn nil\n}","line":{"from":83,"to":102}} {"id":100028950,"name":"RecordEvent","signature":"func (cml *configMapLock) RecordEvent(s string)","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/configmaplock.go","code":"// RecordEvent in leader election while adding meta-data\nfunc (cml *configMapLock) RecordEvent(s string) {\n\tif cml.LockConfig.EventRecorder == nil {\n\t\treturn\n\t}\n\tevents := fmt.Sprintf(\"%v %v\", cml.LockConfig.Identity, s)\n\tsubject := \u0026v1.ConfigMap{ObjectMeta: cml.cm.ObjectMeta}\n\t// Populate the type meta, so we don't have to get it from the schema\n\tsubject.Kind = \"ConfigMap\"\n\tsubject.APIVersion = v1.SchemeGroupVersion.String()\n\tcml.LockConfig.EventRecorder.Eventf(subject, v1.EventTypeNormal, \"LeaderElection\", events)\n}","line":{"from":104,"to":115}} {"id":100028951,"name":"Describe","signature":"func (cml *configMapLock) Describe() string","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/configmaplock.go","code":"// Describe is used to convert details on current resource lock\n// into a string\nfunc (cml *configMapLock) Describe() string {\n\treturn fmt.Sprintf(\"%v/%v\", cml.ConfigMapMeta.Namespace, cml.ConfigMapMeta.Name)\n}","line":{"from":117,"to":121}} {"id":100028952,"name":"Identity","signature":"func (cml *configMapLock) Identity() string","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/configmaplock.go","code":"// Identity returns the Identity of the lock\nfunc (cml *configMapLock) Identity() string {\n\treturn cml.LockConfig.Identity\n}","line":{"from":123,"to":126}} {"id":100028953,"name":"Get","signature":"func (el *endpointsLock) Get(ctx context.Context) (*LeaderElectionRecord, []byte, error)","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/endpointslock.go","code":"// Get returns the election record from a Endpoints Annotation\nfunc (el *endpointsLock) Get(ctx context.Context) (*LeaderElectionRecord, []byte, error) {\n\tvar record LeaderElectionRecord\n\tep, err := el.Client.Endpoints(el.EndpointsMeta.Namespace).Get(ctx, el.EndpointsMeta.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tel.e = ep\n\tif el.e.Annotations == nil {\n\t\tel.e.Annotations = make(map[string]string)\n\t}\n\trecordStr, found := el.e.Annotations[LeaderElectionRecordAnnotationKey]\n\trecordBytes := []byte(recordStr)\n\tif found {\n\t\tif err := json.Unmarshal(recordBytes, \u0026record); err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\treturn \u0026record, recordBytes, nil\n}","line":{"from":39,"to":58}} {"id":100028954,"name":"Create","signature":"func (el *endpointsLock) Create(ctx context.Context, ler LeaderElectionRecord) error","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/endpointslock.go","code":"// Create attempts to create a LeaderElectionRecord annotation\nfunc (el *endpointsLock) Create(ctx context.Context, ler LeaderElectionRecord) error {\n\trecordBytes, err := json.Marshal(ler)\n\tif err != nil {\n\t\treturn err\n\t}\n\tel.e, err = el.Client.Endpoints(el.EndpointsMeta.Namespace).Create(ctx, \u0026v1.Endpoints{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: el.EndpointsMeta.Name,\n\t\t\tNamespace: el.EndpointsMeta.Namespace,\n\t\t\tAnnotations: map[string]string{\n\t\t\t\tLeaderElectionRecordAnnotationKey: string(recordBytes),\n\t\t\t},\n\t\t},\n\t}, metav1.CreateOptions{})\n\treturn err\n}","line":{"from":60,"to":76}} {"id":100028955,"name":"Update","signature":"func (el *endpointsLock) Update(ctx context.Context, ler LeaderElectionRecord) error","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/endpointslock.go","code":"// Update will update and existing annotation on a given resource.\nfunc (el *endpointsLock) Update(ctx context.Context, ler LeaderElectionRecord) error {\n\tif el.e == nil {\n\t\treturn errors.New(\"endpoint not initialized, call get or create first\")\n\t}\n\trecordBytes, err := json.Marshal(ler)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif el.e.Annotations == nil {\n\t\tel.e.Annotations = make(map[string]string)\n\t}\n\tel.e.Annotations[LeaderElectionRecordAnnotationKey] = string(recordBytes)\n\te, err := el.Client.Endpoints(el.EndpointsMeta.Namespace).Update(ctx, el.e, metav1.UpdateOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\tel.e = e\n\treturn nil\n}","line":{"from":78,"to":97}} {"id":100028956,"name":"RecordEvent","signature":"func (el *endpointsLock) RecordEvent(s string)","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/endpointslock.go","code":"// RecordEvent in leader election while adding meta-data\nfunc (el *endpointsLock) RecordEvent(s string) {\n\tif el.LockConfig.EventRecorder == nil {\n\t\treturn\n\t}\n\tevents := fmt.Sprintf(\"%v %v\", el.LockConfig.Identity, s)\n\tsubject := \u0026v1.Endpoints{ObjectMeta: el.e.ObjectMeta}\n\t// Populate the type meta, so we don't have to get it from the schema\n\tsubject.Kind = \"Endpoints\"\n\tsubject.APIVersion = v1.SchemeGroupVersion.String()\n\tel.LockConfig.EventRecorder.Eventf(subject, v1.EventTypeNormal, \"LeaderElection\", events)\n}","line":{"from":99,"to":110}} {"id":100028957,"name":"Describe","signature":"func (el *endpointsLock) Describe() string","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/endpointslock.go","code":"// Describe is used to convert details on current resource lock\n// into a string\nfunc (el *endpointsLock) Describe() string {\n\treturn fmt.Sprintf(\"%v/%v\", el.EndpointsMeta.Namespace, el.EndpointsMeta.Name)\n}","line":{"from":112,"to":116}} {"id":100028958,"name":"Identity","signature":"func (el *endpointsLock) Identity() string","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/endpointslock.go","code":"// Identity returns the Identity of the lock\nfunc (el *endpointsLock) Identity() string {\n\treturn el.LockConfig.Identity\n}","line":{"from":118,"to":121}} {"id":100028959,"name":"New","signature":"func New(lockType string, ns string, name string, coreClient corev1.CoreV1Interface, coordinationClient coordinationv1.CoordinationV1Interface, rlc ResourceLockConfig) (Interface, error)","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/interface.go","code":"// Manufacture will create a lock of a given type according to the input parameters\nfunc New(lockType string, ns string, name string, coreClient corev1.CoreV1Interface, coordinationClient coordinationv1.CoordinationV1Interface, rlc ResourceLockConfig) (Interface, error) {\n\tendpointsLock := \u0026endpointsLock{\n\t\tEndpointsMeta: metav1.ObjectMeta{\n\t\t\tNamespace: ns,\n\t\t\tName: name,\n\t\t},\n\t\tClient: coreClient,\n\t\tLockConfig: rlc,\n\t}\n\tconfigmapLock := \u0026configMapLock{\n\t\tConfigMapMeta: metav1.ObjectMeta{\n\t\t\tNamespace: ns,\n\t\t\tName: name,\n\t\t},\n\t\tClient: coreClient,\n\t\tLockConfig: rlc,\n\t}\n\tleaseLock := \u0026LeaseLock{\n\t\tLeaseMeta: metav1.ObjectMeta{\n\t\t\tNamespace: ns,\n\t\t\tName: name,\n\t\t},\n\t\tClient: coordinationClient,\n\t\tLockConfig: rlc,\n\t}\n\tswitch lockType {\n\tcase endpointsResourceLock:\n\t\treturn nil, fmt.Errorf(\"endpoints lock is removed, migrate to %s\", EndpointsLeasesResourceLock)\n\tcase configMapsResourceLock:\n\t\treturn nil, fmt.Errorf(\"configmaps lock is removed, migrate to %s\", ConfigMapsLeasesResourceLock)\n\tcase LeasesResourceLock:\n\t\treturn leaseLock, nil\n\tcase EndpointsLeasesResourceLock:\n\t\treturn \u0026MultiLock{\n\t\t\tPrimary: endpointsLock,\n\t\t\tSecondary: leaseLock,\n\t\t}, nil\n\tcase ConfigMapsLeasesResourceLock:\n\t\treturn \u0026MultiLock{\n\t\t\tPrimary: configmapLock,\n\t\t\tSecondary: leaseLock,\n\t\t}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Invalid lock-type %s\", lockType)\n\t}\n}","line":{"from":165,"to":211}} {"id":100028960,"name":"NewFromKubeconfig","signature":"func NewFromKubeconfig(lockType string, ns string, name string, rlc ResourceLockConfig, kubeconfig *restclient.Config, renewDeadline time.Duration) (Interface, error)","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/interface.go","code":"// NewFromKubeconfig will create a lock of a given type according to the input parameters.\n// Timeout set for a client used to contact to Kubernetes should be lower than\n// RenewDeadline to keep a single hung request from forcing a leader loss.\n// Setting it to max(time.Second, RenewDeadline/2) as a reasonable heuristic.\nfunc NewFromKubeconfig(lockType string, ns string, name string, rlc ResourceLockConfig, kubeconfig *restclient.Config, renewDeadline time.Duration) (Interface, error) {\n\t// shallow copy, do not modify the kubeconfig\n\tconfig := *kubeconfig\n\ttimeout := renewDeadline / 2\n\tif timeout \u003c time.Second {\n\t\ttimeout = time.Second\n\t}\n\tconfig.Timeout = timeout\n\tleaderElectionClient := clientset.NewForConfigOrDie(restclient.AddUserAgent(\u0026config, \"leader-election\"))\n\treturn New(lockType, ns, name, leaderElectionClient.CoreV1(), leaderElectionClient.CoordinationV1(), rlc)\n}","line":{"from":213,"to":227}} {"id":100028961,"name":"Get","signature":"func (ll *LeaseLock) Get(ctx context.Context) (*LeaderElectionRecord, []byte, error)","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/leaselock.go","code":"// Get returns the election record from a Lease spec\nfunc (ll *LeaseLock) Get(ctx context.Context) (*LeaderElectionRecord, []byte, error) {\n\tlease, err := ll.Client.Leases(ll.LeaseMeta.Namespace).Get(ctx, ll.LeaseMeta.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tll.lease = lease\n\trecord := LeaseSpecToLeaderElectionRecord(\u0026ll.lease.Spec)\n\trecordByte, err := json.Marshal(*record)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn record, recordByte, nil\n}","line":{"from":40,"to":53}} {"id":100028962,"name":"Create","signature":"func (ll *LeaseLock) Create(ctx context.Context, ler LeaderElectionRecord) error","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/leaselock.go","code":"// Create attempts to create a Lease\nfunc (ll *LeaseLock) Create(ctx context.Context, ler LeaderElectionRecord) error {\n\tvar err error\n\tll.lease, err = ll.Client.Leases(ll.LeaseMeta.Namespace).Create(ctx, \u0026coordinationv1.Lease{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: ll.LeaseMeta.Name,\n\t\t\tNamespace: ll.LeaseMeta.Namespace,\n\t\t},\n\t\tSpec: LeaderElectionRecordToLeaseSpec(\u0026ler),\n\t}, metav1.CreateOptions{})\n\treturn err\n}","line":{"from":55,"to":66}} {"id":100028963,"name":"Update","signature":"func (ll *LeaseLock) Update(ctx context.Context, ler LeaderElectionRecord) error","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/leaselock.go","code":"// Update will update an existing Lease spec.\nfunc (ll *LeaseLock) Update(ctx context.Context, ler LeaderElectionRecord) error {\n\tif ll.lease == nil {\n\t\treturn errors.New(\"lease not initialized, call get or create first\")\n\t}\n\tll.lease.Spec = LeaderElectionRecordToLeaseSpec(\u0026ler)\n\n\tlease, err := ll.Client.Leases(ll.LeaseMeta.Namespace).Update(ctx, ll.lease, metav1.UpdateOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tll.lease = lease\n\treturn nil\n}","line":{"from":68,"to":82}} {"id":100028964,"name":"RecordEvent","signature":"func (ll *LeaseLock) RecordEvent(s string)","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/leaselock.go","code":"// RecordEvent in leader election while adding meta-data\nfunc (ll *LeaseLock) RecordEvent(s string) {\n\tif ll.LockConfig.EventRecorder == nil {\n\t\treturn\n\t}\n\tevents := fmt.Sprintf(\"%v %v\", ll.LockConfig.Identity, s)\n\tsubject := \u0026coordinationv1.Lease{ObjectMeta: ll.lease.ObjectMeta}\n\t// Populate the type meta, so we don't have to get it from the schema\n\tsubject.Kind = \"Lease\"\n\tsubject.APIVersion = coordinationv1.SchemeGroupVersion.String()\n\tll.LockConfig.EventRecorder.Eventf(subject, corev1.EventTypeNormal, \"LeaderElection\", events)\n}","line":{"from":84,"to":95}} {"id":100028965,"name":"Describe","signature":"func (ll *LeaseLock) Describe() string","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/leaselock.go","code":"// Describe is used to convert details on current resource lock\n// into a string\nfunc (ll *LeaseLock) Describe() string {\n\treturn fmt.Sprintf(\"%v/%v\", ll.LeaseMeta.Namespace, ll.LeaseMeta.Name)\n}","line":{"from":97,"to":101}} {"id":100028966,"name":"Identity","signature":"func (ll *LeaseLock) Identity() string","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/leaselock.go","code":"// Identity returns the Identity of the lock\nfunc (ll *LeaseLock) Identity() string {\n\treturn ll.LockConfig.Identity\n}","line":{"from":103,"to":106}} {"id":100028967,"name":"LeaseSpecToLeaderElectionRecord","signature":"func LeaseSpecToLeaderElectionRecord(spec *coordinationv1.LeaseSpec) *LeaderElectionRecord","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/leaselock.go","code":"func LeaseSpecToLeaderElectionRecord(spec *coordinationv1.LeaseSpec) *LeaderElectionRecord {\n\tvar r LeaderElectionRecord\n\tif spec.HolderIdentity != nil {\n\t\tr.HolderIdentity = *spec.HolderIdentity\n\t}\n\tif spec.LeaseDurationSeconds != nil {\n\t\tr.LeaseDurationSeconds = int(*spec.LeaseDurationSeconds)\n\t}\n\tif spec.LeaseTransitions != nil {\n\t\tr.LeaderTransitions = int(*spec.LeaseTransitions)\n\t}\n\tif spec.AcquireTime != nil {\n\t\tr.AcquireTime = metav1.Time{Time: spec.AcquireTime.Time}\n\t}\n\tif spec.RenewTime != nil {\n\t\tr.RenewTime = metav1.Time{Time: spec.RenewTime.Time}\n\t}\n\treturn \u0026r\n\n}","line":{"from":108,"to":127}} {"id":100028968,"name":"LeaderElectionRecordToLeaseSpec","signature":"func LeaderElectionRecordToLeaseSpec(ler *LeaderElectionRecord) coordinationv1.LeaseSpec","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/leaselock.go","code":"func LeaderElectionRecordToLeaseSpec(ler *LeaderElectionRecord) coordinationv1.LeaseSpec {\n\tleaseDurationSeconds := int32(ler.LeaseDurationSeconds)\n\tleaseTransitions := int32(ler.LeaderTransitions)\n\treturn coordinationv1.LeaseSpec{\n\t\tHolderIdentity: \u0026ler.HolderIdentity,\n\t\tLeaseDurationSeconds: \u0026leaseDurationSeconds,\n\t\tAcquireTime: \u0026metav1.MicroTime{Time: ler.AcquireTime.Time},\n\t\tRenewTime: \u0026metav1.MicroTime{Time: ler.RenewTime.Time},\n\t\tLeaseTransitions: \u0026leaseTransitions,\n\t}\n}","line":{"from":129,"to":139}} {"id":100028969,"name":"Get","signature":"func (ml *MultiLock) Get(ctx context.Context) (*LeaderElectionRecord, []byte, error)","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/multilock.go","code":"// Get returns the older election record of the lock\nfunc (ml *MultiLock) Get(ctx context.Context) (*LeaderElectionRecord, []byte, error) {\n\tprimary, primaryRaw, err := ml.Primary.Get(ctx)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tsecondary, secondaryRaw, err := ml.Secondary.Get(ctx)\n\tif err != nil {\n\t\t// Lock is held by old client\n\t\tif apierrors.IsNotFound(err) \u0026\u0026 primary.HolderIdentity != ml.Identity() {\n\t\t\treturn primary, primaryRaw, nil\n\t\t}\n\t\treturn nil, nil, err\n\t}\n\n\tif primary.HolderIdentity != secondary.HolderIdentity {\n\t\tprimary.HolderIdentity = UnknownLeader\n\t\tprimaryRaw, err = json.Marshal(primary)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\treturn primary, ConcatRawRecord(primaryRaw, secondaryRaw), nil\n}","line":{"from":37,"to":61}} {"id":100028970,"name":"Create","signature":"func (ml *MultiLock) Create(ctx context.Context, ler LeaderElectionRecord) error","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/multilock.go","code":"// Create attempts to create both primary lock and secondary lock\nfunc (ml *MultiLock) Create(ctx context.Context, ler LeaderElectionRecord) error {\n\terr := ml.Primary.Create(ctx, ler)\n\tif err != nil \u0026\u0026 !apierrors.IsAlreadyExists(err) {\n\t\treturn err\n\t}\n\treturn ml.Secondary.Create(ctx, ler)\n}","line":{"from":63,"to":70}} {"id":100028971,"name":"Update","signature":"func (ml *MultiLock) Update(ctx context.Context, ler LeaderElectionRecord) error","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/multilock.go","code":"// Update will update and existing annotation on both two resources.\nfunc (ml *MultiLock) Update(ctx context.Context, ler LeaderElectionRecord) error {\n\terr := ml.Primary.Update(ctx, ler)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, _, err = ml.Secondary.Get(ctx)\n\tif err != nil \u0026\u0026 apierrors.IsNotFound(err) {\n\t\treturn ml.Secondary.Create(ctx, ler)\n\t}\n\treturn ml.Secondary.Update(ctx, ler)\n}","line":{"from":72,"to":83}} {"id":100028972,"name":"RecordEvent","signature":"func (ml *MultiLock) RecordEvent(s string)","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/multilock.go","code":"// RecordEvent in leader election while adding meta-data\nfunc (ml *MultiLock) RecordEvent(s string) {\n\tml.Primary.RecordEvent(s)\n\tml.Secondary.RecordEvent(s)\n}","line":{"from":85,"to":89}} {"id":100028973,"name":"Describe","signature":"func (ml *MultiLock) Describe() string","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/multilock.go","code":"// Describe is used to convert details on current resource lock\n// into a string\nfunc (ml *MultiLock) Describe() string {\n\treturn ml.Primary.Describe()\n}","line":{"from":91,"to":95}} {"id":100028974,"name":"Identity","signature":"func (ml *MultiLock) Identity() string","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/multilock.go","code":"// Identity returns the Identity of the lock\nfunc (ml *MultiLock) Identity() string {\n\treturn ml.Primary.Identity()\n}","line":{"from":97,"to":100}} {"id":100028975,"name":"ConcatRawRecord","signature":"func ConcatRawRecord(primaryRaw, secondaryRaw []byte) []byte","file":"staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/multilock.go","code":"func ConcatRawRecord(primaryRaw, secondaryRaw []byte) []byte {\n\treturn bytes.Join([][]byte{primaryRaw, secondaryRaw}, []byte(\",\"))\n}","line":{"from":102,"to":104}} {"id":100028976,"name":"Register","signature":"func Register(opts RegisterOpts)","file":"staging/src/k8s.io/client-go/tools/metrics/metrics.go","code":"// Register registers metrics for the rest client to use. This can\n// only be called once.\nfunc Register(opts RegisterOpts) {\n\tregisterMetrics.Do(func() {\n\t\tif opts.ClientCertExpiry != nil {\n\t\t\tClientCertExpiry = opts.ClientCertExpiry\n\t\t}\n\t\tif opts.ClientCertRotationAge != nil {\n\t\t\tClientCertRotationAge = opts.ClientCertRotationAge\n\t\t}\n\t\tif opts.RequestLatency != nil {\n\t\t\tRequestLatency = opts.RequestLatency\n\t\t}\n\t\tif opts.RequestSize != nil {\n\t\t\tRequestSize = opts.RequestSize\n\t\t}\n\t\tif opts.ResponseSize != nil {\n\t\t\tResponseSize = opts.ResponseSize\n\t\t}\n\t\tif opts.RateLimiterLatency != nil {\n\t\t\tRateLimiterLatency = opts.RateLimiterLatency\n\t\t}\n\t\tif opts.RequestResult != nil {\n\t\t\tRequestResult = opts.RequestResult\n\t\t}\n\t\tif opts.ExecPluginCalls != nil {\n\t\t\tExecPluginCalls = opts.ExecPluginCalls\n\t\t}\n\t\tif opts.RequestRetry != nil {\n\t\t\tRequestRetry = opts.RequestRetry\n\t\t}\n\t})\n}","line":{"from":103,"to":135}} {"id":100028977,"name":"Observe","signature":"func (noopDuration) Observe(time.Duration) {}","file":"staging/src/k8s.io/client-go/tools/metrics/metrics.go","code":"func (noopDuration) Observe(time.Duration) {}","line":{"from":139,"to":139}} {"id":100028978,"name":"Set","signature":"func (noopExpiry) Set(*time.Time) {}","file":"staging/src/k8s.io/client-go/tools/metrics/metrics.go","code":"func (noopExpiry) Set(*time.Time) {}","line":{"from":143,"to":143}} {"id":100028979,"name":"Observe","signature":"func (noopLatency) Observe(context.Context, string, url.URL, time.Duration) {}","file":"staging/src/k8s.io/client-go/tools/metrics/metrics.go","code":"func (noopLatency) Observe(context.Context, string, url.URL, time.Duration) {}","line":{"from":147,"to":147}} {"id":100028980,"name":"Observe","signature":"func (noopSize) Observe(context.Context, string, string, float64) {}","file":"staging/src/k8s.io/client-go/tools/metrics/metrics.go","code":"func (noopSize) Observe(context.Context, string, string, float64) {}","line":{"from":151,"to":151}} {"id":100028981,"name":"Increment","signature":"func (noopResult) Increment(context.Context, string, string, string) {}","file":"staging/src/k8s.io/client-go/tools/metrics/metrics.go","code":"func (noopResult) Increment(context.Context, string, string, string) {}","line":{"from":155,"to":155}} {"id":100028982,"name":"Increment","signature":"func (noopCalls) Increment(int, string) {}","file":"staging/src/k8s.io/client-go/tools/metrics/metrics.go","code":"func (noopCalls) Increment(int, string) {}","line":{"from":159,"to":159}} {"id":100028983,"name":"IncrementRetry","signature":"func (noopRetry) IncrementRetry(context.Context, string, string, string) {}","file":"staging/src/k8s.io/client-go/tools/metrics/metrics.go","code":"func (noopRetry) IncrementRetry(context.Context, string, string, string) {}","line":{"from":163,"to":163}} {"id":100028984,"name":"SimplePageFunc","signature":"func SimplePageFunc(fn func(opts metav1.ListOptions) (runtime.Object, error)) ListPageFunc","file":"staging/src/k8s.io/client-go/tools/pager/pager.go","code":"// SimplePageFunc adapts a context-less list function into one that accepts a context.\nfunc SimplePageFunc(fn func(opts metav1.ListOptions) (runtime.Object, error)) ListPageFunc {\n\treturn func(ctx context.Context, opts metav1.ListOptions) (runtime.Object, error) {\n\t\treturn fn(opts)\n\t}\n}","line":{"from":37,"to":42}} {"id":100028985,"name":"New","signature":"func New(fn ListPageFunc) *ListPager","file":"staging/src/k8s.io/client-go/tools/pager/pager.go","code":"// New creates a new pager from the provided pager function using the default\n// options. It will fall back to a full list if an expiration error is encountered\n// as a last resort.\nfunc New(fn ListPageFunc) *ListPager {\n\treturn \u0026ListPager{\n\t\tPageSize: defaultPageSize,\n\t\tPageFn: fn,\n\t\tFullListIfExpired: true,\n\t\tPageBufferSize: defaultPageBufferSize,\n\t}\n}","line":{"from":58,"to":68}} {"id":100028986,"name":"List","signature":"func (p *ListPager) List(ctx context.Context, options metav1.ListOptions) (runtime.Object, bool, error)","file":"staging/src/k8s.io/client-go/tools/pager/pager.go","code":"// List returns a single list object, but attempts to retrieve smaller chunks from the\n// server to reduce the impact on the server. If the chunk attempt fails, it will load\n// the full list instead. The Limit field on options, if unset, will default to the page size.\nfunc (p *ListPager) List(ctx context.Context, options metav1.ListOptions) (runtime.Object, bool, error) {\n\tif options.Limit == 0 {\n\t\toptions.Limit = p.PageSize\n\t}\n\trequestedResourceVersion := options.ResourceVersion\n\trequestedResourceVersionMatch := options.ResourceVersionMatch\n\tvar list *metainternalversion.List\n\tpaginatedResult := false\n\n\tfor {\n\t\tselect {\n\t\tcase \u003c-ctx.Done():\n\t\t\treturn nil, paginatedResult, ctx.Err()\n\t\tdefault:\n\t\t}\n\n\t\tobj, err := p.PageFn(ctx, options)\n\t\tif err != nil {\n\t\t\t// Only fallback to full list if an \"Expired\" errors is returned, FullListIfExpired is true, and\n\t\t\t// the \"Expired\" error occurred in page 2 or later (since full list is intended to prevent a pager.List from\n\t\t\t// failing when the resource versions is established by the first page request falls out of the compaction\n\t\t\t// during the subsequent list requests).\n\t\t\tif !errors.IsResourceExpired(err) || !p.FullListIfExpired || options.Continue == \"\" {\n\t\t\t\treturn nil, paginatedResult, err\n\t\t\t}\n\t\t\t// the list expired while we were processing, fall back to a full list at\n\t\t\t// the requested ResourceVersion.\n\t\t\toptions.Limit = 0\n\t\t\toptions.Continue = \"\"\n\t\t\toptions.ResourceVersion = requestedResourceVersion\n\t\t\toptions.ResourceVersionMatch = requestedResourceVersionMatch\n\t\t\tresult, err := p.PageFn(ctx, options)\n\t\t\treturn result, paginatedResult, err\n\t\t}\n\t\tm, err := meta.ListAccessor(obj)\n\t\tif err != nil {\n\t\t\treturn nil, paginatedResult, fmt.Errorf(\"returned object must be a list: %v\", err)\n\t\t}\n\n\t\t// exit early and return the object we got if we haven't processed any pages\n\t\tif len(m.GetContinue()) == 0 \u0026\u0026 list == nil {\n\t\t\treturn obj, paginatedResult, nil\n\t\t}\n\n\t\t// initialize the list and fill its contents\n\t\tif list == nil {\n\t\t\tlist = \u0026metainternalversion.List{Items: make([]runtime.Object, 0, options.Limit+1)}\n\t\t\tlist.ResourceVersion = m.GetResourceVersion()\n\t\t\tlist.SelfLink = m.GetSelfLink()\n\t\t}\n\t\tif err := meta.EachListItem(obj, func(obj runtime.Object) error {\n\t\t\tlist.Items = append(list.Items, obj)\n\t\t\treturn nil\n\t\t}); err != nil {\n\t\t\treturn nil, paginatedResult, err\n\t\t}\n\n\t\t// if we have no more items, return the list\n\t\tif len(m.GetContinue()) == 0 {\n\t\t\treturn list, paginatedResult, nil\n\t\t}\n\n\t\t// set the next loop up\n\t\toptions.Continue = m.GetContinue()\n\t\t// Clear the ResourceVersion(Match) on the subsequent List calls to avoid the\n\t\t// `specifying resource version is not allowed when using continue` error.\n\t\t// See https://github.com/kubernetes/kubernetes/issues/85221#issuecomment-553748143.\n\t\toptions.ResourceVersion = \"\"\n\t\toptions.ResourceVersionMatch = \"\"\n\t\t// At this point, result is already paginated.\n\t\tpaginatedResult = true\n\t}\n}","line":{"from":73,"to":148}} {"id":100028987,"name":"EachListItem","signature":"func (p *ListPager) EachListItem(ctx context.Context, options metav1.ListOptions, fn func(obj runtime.Object) error) error","file":"staging/src/k8s.io/client-go/tools/pager/pager.go","code":"// EachListItem fetches runtime.Object items using this ListPager and invokes fn on each item. If\n// fn returns an error, processing stops and that error is returned. If fn does not return an error,\n// any error encountered while retrieving the list from the server is returned. If the context\n// cancels or times out, the context error is returned. Since the list is retrieved in paginated\n// chunks, an \"Expired\" error (metav1.StatusReasonExpired) may be returned if the pagination list\n// requests exceed the expiration limit of the apiserver being called.\n//\n// Items are retrieved in chunks from the server to reduce the impact on the server with up to\n// ListPager.PageBufferSize chunks buffered concurrently in the background.\nfunc (p *ListPager) EachListItem(ctx context.Context, options metav1.ListOptions, fn func(obj runtime.Object) error) error {\n\treturn p.eachListChunkBuffered(ctx, options, func(obj runtime.Object) error {\n\t\treturn meta.EachListItem(obj, fn)\n\t})\n}","line":{"from":150,"to":163}} {"id":100028988,"name":"eachListChunkBuffered","signature":"func (p *ListPager) eachListChunkBuffered(ctx context.Context, options metav1.ListOptions, fn func(obj runtime.Object) error) error","file":"staging/src/k8s.io/client-go/tools/pager/pager.go","code":"// eachListChunkBuffered fetches runtimeObject list chunks using this ListPager and invokes fn on\n// each list chunk. If fn returns an error, processing stops and that error is returned. If fn does\n// not return an error, any error encountered while retrieving the list from the server is\n// returned. If the context cancels or times out, the context error is returned. Since the list is\n// retrieved in paginated chunks, an \"Expired\" error (metav1.StatusReasonExpired) may be returned if\n// the pagination list requests exceed the expiration limit of the apiserver being called.\n//\n// Up to ListPager.PageBufferSize chunks are buffered concurrently in the background.\nfunc (p *ListPager) eachListChunkBuffered(ctx context.Context, options metav1.ListOptions, fn func(obj runtime.Object) error) error {\n\tif p.PageBufferSize \u003c 0 {\n\t\treturn fmt.Errorf(\"ListPager.PageBufferSize must be \u003e= 0, got %d\", p.PageBufferSize)\n\t}\n\n\t// Ensure background goroutine is stopped if this call exits before all list items are\n\t// processed. Cancelation error from this deferred cancel call is never returned to caller;\n\t// either the list result has already been sent to bgResultC or the fn error is returned and\n\t// the cancelation error is discarded.\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\tchunkC := make(chan runtime.Object, p.PageBufferSize)\n\tbgResultC := make(chan error, 1)\n\tgo func() {\n\t\tdefer utilruntime.HandleCrash()\n\n\t\tvar err error\n\t\tdefer func() {\n\t\t\tclose(chunkC)\n\t\t\tbgResultC \u003c- err\n\t\t}()\n\t\terr = p.eachListChunk(ctx, options, func(chunk runtime.Object) error {\n\t\t\tselect {\n\t\t\tcase chunkC \u003c- chunk: // buffer the chunk, this can block\n\t\t\tcase \u003c-ctx.Done():\n\t\t\t\treturn ctx.Err()\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t}()\n\n\tfor o := range chunkC {\n\t\tselect {\n\t\tcase \u003c-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tdefault:\n\t\t}\n\t\terr := fn(o)\n\t\tif err != nil {\n\t\t\treturn err // any fn error should be returned immediately\n\t\t}\n\t}\n\t// promote the results of our background goroutine to the foreground\n\treturn \u003c-bgResultC\n}","line":{"from":165,"to":218}} {"id":100028989,"name":"eachListChunk","signature":"func (p *ListPager) eachListChunk(ctx context.Context, options metav1.ListOptions, fn func(obj runtime.Object) error) error","file":"staging/src/k8s.io/client-go/tools/pager/pager.go","code":"// eachListChunk fetches runtimeObject list chunks using this ListPager and invokes fn on each list\n// chunk. If fn returns an error, processing stops and that error is returned. If fn does not return\n// an error, any error encountered while retrieving the list from the server is returned. If the\n// context cancels or times out, the context error is returned. Since the list is retrieved in\n// paginated chunks, an \"Expired\" error (metav1.StatusReasonExpired) may be returned if the\n// pagination list requests exceed the expiration limit of the apiserver being called.\nfunc (p *ListPager) eachListChunk(ctx context.Context, options metav1.ListOptions, fn func(obj runtime.Object) error) error {\n\tif options.Limit == 0 {\n\t\toptions.Limit = p.PageSize\n\t}\n\tfor {\n\t\tselect {\n\t\tcase \u003c-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tdefault:\n\t\t}\n\n\t\tobj, err := p.PageFn(ctx, options)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tm, err := meta.ListAccessor(obj)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"returned object must be a list: %v\", err)\n\t\t}\n\t\tif err := fn(obj); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// if we have no more items, return.\n\t\tif len(m.GetContinue()) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\t// set the next loop up\n\t\toptions.Continue = m.GetContinue()\n\t}\n}","line":{"from":220,"to":255}} {"id":100028990,"name":"parsePorts","signature":"func parsePorts(ports []string) ([]ForwardedPort, error)","file":"staging/src/k8s.io/client-go/tools/portforward/portforward.go","code":"/*\nvalid port specifications:\n\n5000\n- forwards from localhost:5000 to pod:5000\n\n8888:5000\n- forwards from localhost:8888 to pod:5000\n\n0:5000\n:5000\n - selects a random available local port,\n forwards from localhost:\u003crandom port\u003e to pod:5000\n*/\nfunc parsePorts(ports []string) ([]ForwardedPort, error) {\n\tvar forwards []ForwardedPort\n\tfor _, portString := range ports {\n\t\tparts := strings.Split(portString, \":\")\n\t\tvar localString, remoteString string\n\t\tif len(parts) == 1 {\n\t\t\tlocalString = parts[0]\n\t\t\tremoteString = parts[0]\n\t\t} else if len(parts) == 2 {\n\t\t\tlocalString = parts[0]\n\t\t\tif localString == \"\" {\n\t\t\t\t// support :5000\n\t\t\t\tlocalString = \"0\"\n\t\t\t}\n\t\t\tremoteString = parts[1]\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"invalid port format '%s'\", portString)\n\t\t}\n\n\t\tlocalPort, err := strconv.ParseUint(localString, 10, 16)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error parsing local port '%s': %s\", localString, err)\n\t\t}\n\n\t\tremotePort, err := strconv.ParseUint(remoteString, 10, 16)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error parsing remote port '%s': %s\", remoteString, err)\n\t\t}\n\t\tif remotePort == 0 {\n\t\t\treturn nil, fmt.Errorf(\"remote port must be \u003e 0\")\n\t\t}\n\n\t\tforwards = append(forwards, ForwardedPort{uint16(localPort), uint16(remotePort)})\n\t}\n\n\treturn forwards, nil\n}","line":{"from":65,"to":115}} {"id":100028991,"name":"parseAddresses","signature":"func parseAddresses(addressesToParse []string) ([]listenAddress, error)","file":"staging/src/k8s.io/client-go/tools/portforward/portforward.go","code":"func parseAddresses(addressesToParse []string) ([]listenAddress, error) {\n\tvar addresses []listenAddress\n\tparsed := make(map[string]listenAddress)\n\tfor _, address := range addressesToParse {\n\t\tif address == \"localhost\" {\n\t\t\tif _, exists := parsed[\"127.0.0.1\"]; !exists {\n\t\t\t\tip := listenAddress{address: \"127.0.0.1\", protocol: \"tcp4\", failureMode: \"all\"}\n\t\t\t\tparsed[ip.address] = ip\n\t\t\t}\n\t\t\tif _, exists := parsed[\"::1\"]; !exists {\n\t\t\t\tip := listenAddress{address: \"::1\", protocol: \"tcp6\", failureMode: \"all\"}\n\t\t\t\tparsed[ip.address] = ip\n\t\t\t}\n\t\t} else if netutils.ParseIPSloppy(address).To4() != nil {\n\t\t\tparsed[address] = listenAddress{address: address, protocol: \"tcp4\", failureMode: \"any\"}\n\t\t} else if netutils.ParseIPSloppy(address) != nil {\n\t\t\tparsed[address] = listenAddress{address: address, protocol: \"tcp6\", failureMode: \"any\"}\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"%s is not a valid IP\", address)\n\t\t}\n\t}\n\taddresses = make([]listenAddress, len(parsed))\n\tid := 0\n\tfor _, v := range parsed {\n\t\taddresses[id] = v\n\t\tid++\n\t}\n\t// Sort addresses before returning to get a stable order\n\tsort.Slice(addresses, func(i, j int) bool { return addresses[i].address \u003c addresses[j].address })\n\n\treturn addresses, nil\n}","line":{"from":123,"to":154}} {"id":100028992,"name":"New","signature":"func New(dialer httpstream.Dialer, ports []string, stopChan \u003c-chan struct{}, readyChan chan struct{}, out, errOut io.Writer) (*PortForwarder, error)","file":"staging/src/k8s.io/client-go/tools/portforward/portforward.go","code":"// New creates a new PortForwarder with localhost listen addresses.\nfunc New(dialer httpstream.Dialer, ports []string, stopChan \u003c-chan struct{}, readyChan chan struct{}, out, errOut io.Writer) (*PortForwarder, error) {\n\treturn NewOnAddresses(dialer, []string{\"localhost\"}, ports, stopChan, readyChan, out, errOut)\n}","line":{"from":156,"to":159}} {"id":100028993,"name":"NewOnAddresses","signature":"func NewOnAddresses(dialer httpstream.Dialer, addresses []string, ports []string, stopChan \u003c-chan struct{}, readyChan chan struct{}, out, errOut io.Writer) (*PortForwarder, error)","file":"staging/src/k8s.io/client-go/tools/portforward/portforward.go","code":"// NewOnAddresses creates a new PortForwarder with custom listen addresses.\nfunc NewOnAddresses(dialer httpstream.Dialer, addresses []string, ports []string, stopChan \u003c-chan struct{}, readyChan chan struct{}, out, errOut io.Writer) (*PortForwarder, error) {\n\tif len(addresses) == 0 {\n\t\treturn nil, errors.New(\"you must specify at least 1 address\")\n\t}\n\tparsedAddresses, err := parseAddresses(addresses)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(ports) == 0 {\n\t\treturn nil, errors.New(\"you must specify at least 1 port\")\n\t}\n\tparsedPorts, err := parsePorts(ports)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026PortForwarder{\n\t\tdialer: dialer,\n\t\taddresses: parsedAddresses,\n\t\tports: parsedPorts,\n\t\tstopChan: stopChan,\n\t\tReady: readyChan,\n\t\tout: out,\n\t\terrOut: errOut,\n\t}, nil\n}","line":{"from":161,"to":186}} {"id":100028994,"name":"ForwardPorts","signature":"func (pf *PortForwarder) ForwardPorts() error","file":"staging/src/k8s.io/client-go/tools/portforward/portforward.go","code":"// ForwardPorts formats and executes a port forwarding request. The connection will remain\n// open until stopChan is closed.\nfunc (pf *PortForwarder) ForwardPorts() error {\n\tdefer pf.Close()\n\n\tvar err error\n\tpf.streamConn, _, err = pf.dialer.Dial(PortForwardProtocolV1Name)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error upgrading connection: %s\", err)\n\t}\n\tdefer pf.streamConn.Close()\n\n\treturn pf.forward()\n}","line":{"from":188,"to":201}} {"id":100028995,"name":"forward","signature":"func (pf *PortForwarder) forward() error","file":"staging/src/k8s.io/client-go/tools/portforward/portforward.go","code":"// forward dials the remote host specific in req, upgrades the request, starts\n// listeners for each port specified in ports, and forwards local connections\n// to the remote host via streams.\nfunc (pf *PortForwarder) forward() error {\n\tvar err error\n\n\tlistenSuccess := false\n\tfor i := range pf.ports {\n\t\tport := \u0026pf.ports[i]\n\t\terr = pf.listenOnPort(port)\n\t\tswitch {\n\t\tcase err == nil:\n\t\t\tlistenSuccess = true\n\t\tdefault:\n\t\t\tif pf.errOut != nil {\n\t\t\t\tfmt.Fprintf(pf.errOut, \"Unable to listen on port %d: %v\\n\", port.Local, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif !listenSuccess {\n\t\treturn fmt.Errorf(\"unable to listen on any of the requested ports: %v\", pf.ports)\n\t}\n\n\tif pf.Ready != nil {\n\t\tclose(pf.Ready)\n\t}\n\n\t// wait for interrupt or conn closure\n\tselect {\n\tcase \u003c-pf.stopChan:\n\tcase \u003c-pf.streamConn.CloseChan():\n\t\treturn ErrLostConnectionToPod\n\t}\n\n\treturn nil\n}","line":{"from":203,"to":239}} {"id":100028996,"name":"listenOnPort","signature":"func (pf *PortForwarder) listenOnPort(port *ForwardedPort) error","file":"staging/src/k8s.io/client-go/tools/portforward/portforward.go","code":"// listenOnPort delegates listener creation and waits for connections on requested bind addresses.\n// An error is raised based on address groups (default and localhost) and their failure modes\nfunc (pf *PortForwarder) listenOnPort(port *ForwardedPort) error {\n\tvar errors []error\n\tfailCounters := make(map[string]int, 2)\n\tsuccessCounters := make(map[string]int, 2)\n\tfor _, addr := range pf.addresses {\n\t\terr := pf.listenOnPortAndAddress(port, addr.protocol, addr.address)\n\t\tif err != nil {\n\t\t\terrors = append(errors, err)\n\t\t\tfailCounters[addr.failureMode]++\n\t\t} else {\n\t\t\tsuccessCounters[addr.failureMode]++\n\t\t}\n\t}\n\tif successCounters[\"all\"] == 0 \u0026\u0026 failCounters[\"all\"] \u003e 0 {\n\t\treturn fmt.Errorf(\"%s: %v\", \"Listeners failed to create with the following errors\", errors)\n\t}\n\tif failCounters[\"any\"] \u003e 0 {\n\t\treturn fmt.Errorf(\"%s: %v\", \"Listeners failed to create with the following errors\", errors)\n\t}\n\treturn nil\n}","line":{"from":241,"to":263}} {"id":100028997,"name":"listenOnPortAndAddress","signature":"func (pf *PortForwarder) listenOnPortAndAddress(port *ForwardedPort, protocol string, address string) error","file":"staging/src/k8s.io/client-go/tools/portforward/portforward.go","code":"// listenOnPortAndAddress delegates listener creation and waits for new connections\n// in the background f\nfunc (pf *PortForwarder) listenOnPortAndAddress(port *ForwardedPort, protocol string, address string) error {\n\tlistener, err := pf.getListener(protocol, address, port)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpf.listeners = append(pf.listeners, listener)\n\tgo pf.waitForConnection(listener, *port)\n\treturn nil\n}","line":{"from":265,"to":275}} {"id":100028998,"name":"getListener","signature":"func (pf *PortForwarder) getListener(protocol string, hostname string, port *ForwardedPort) (net.Listener, error)","file":"staging/src/k8s.io/client-go/tools/portforward/portforward.go","code":"// getListener creates a listener on the interface targeted by the given hostname on the given port with\n// the given protocol. protocol is in net.Listen style which basically admits values like tcp, tcp4, tcp6\nfunc (pf *PortForwarder) getListener(protocol string, hostname string, port *ForwardedPort) (net.Listener, error) {\n\tlistener, err := net.Listen(protocol, net.JoinHostPort(hostname, strconv.Itoa(int(port.Local))))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create listener: Error %s\", err)\n\t}\n\tlistenerAddress := listener.Addr().String()\n\thost, localPort, _ := net.SplitHostPort(listenerAddress)\n\tlocalPortUInt, err := strconv.ParseUint(localPort, 10, 16)\n\n\tif err != nil {\n\t\tfmt.Fprintf(pf.out, \"Failed to forward from %s:%d -\u003e %d\\n\", hostname, localPortUInt, port.Remote)\n\t\treturn nil, fmt.Errorf(\"error parsing local port: %s from %s (%s)\", err, listenerAddress, host)\n\t}\n\tport.Local = uint16(localPortUInt)\n\tif pf.out != nil {\n\t\tfmt.Fprintf(pf.out, \"Forwarding from %s -\u003e %d\\n\", net.JoinHostPort(hostname, strconv.Itoa(int(localPortUInt))), port.Remote)\n\t}\n\n\treturn listener, nil\n}","line":{"from":277,"to":298}} {"id":100028999,"name":"waitForConnection","signature":"func (pf *PortForwarder) waitForConnection(listener net.Listener, port ForwardedPort)","file":"staging/src/k8s.io/client-go/tools/portforward/portforward.go","code":"// waitForConnection waits for new connections to listener and handles them in\n// the background.\nfunc (pf *PortForwarder) waitForConnection(listener net.Listener, port ForwardedPort) {\n\tfor {\n\t\tselect {\n\t\tcase \u003c-pf.streamConn.CloseChan():\n\t\t\treturn\n\t\tdefault:\n\t\t\tconn, err := listener.Accept()\n\t\t\tif err != nil {\n\t\t\t\t// TODO consider using something like https://github.com/hydrogen18/stoppableListener?\n\t\t\t\tif !strings.Contains(strings.ToLower(err.Error()), \"use of closed network connection\") {\n\t\t\t\t\truntime.HandleError(fmt.Errorf(\"error accepting connection on port %d: %v\", port.Local, err))\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tgo pf.handleConnection(conn, port)\n\t\t}\n\t}\n}","line":{"from":300,"to":319}} {"id":100029000,"name":"nextRequestID","signature":"func (pf *PortForwarder) nextRequestID() int","file":"staging/src/k8s.io/client-go/tools/portforward/portforward.go","code":"func (pf *PortForwarder) nextRequestID() int {\n\tpf.requestIDLock.Lock()\n\tdefer pf.requestIDLock.Unlock()\n\tid := pf.requestID\n\tpf.requestID++\n\treturn id\n}","line":{"from":321,"to":327}} {"id":100029001,"name":"handleConnection","signature":"func (pf *PortForwarder) handleConnection(conn net.Conn, port ForwardedPort)","file":"staging/src/k8s.io/client-go/tools/portforward/portforward.go","code":"// handleConnection copies data between the local connection and the stream to\n// the remote server.\nfunc (pf *PortForwarder) handleConnection(conn net.Conn, port ForwardedPort) {\n\tdefer conn.Close()\n\n\tif pf.out != nil {\n\t\tfmt.Fprintf(pf.out, \"Handling connection for %d\\n\", port.Local)\n\t}\n\n\trequestID := pf.nextRequestID()\n\n\t// create error stream\n\theaders := http.Header{}\n\theaders.Set(v1.StreamType, v1.StreamTypeError)\n\theaders.Set(v1.PortHeader, fmt.Sprintf(\"%d\", port.Remote))\n\theaders.Set(v1.PortForwardRequestIDHeader, strconv.Itoa(requestID))\n\terrorStream, err := pf.streamConn.CreateStream(headers)\n\tif err != nil {\n\t\truntime.HandleError(fmt.Errorf(\"error creating error stream for port %d -\u003e %d: %v\", port.Local, port.Remote, err))\n\t\treturn\n\t}\n\t// we're not writing to this stream\n\terrorStream.Close()\n\tdefer pf.streamConn.RemoveStreams(errorStream)\n\n\terrorChan := make(chan error)\n\tgo func() {\n\t\tmessage, err := io.ReadAll(errorStream)\n\t\tswitch {\n\t\tcase err != nil:\n\t\t\terrorChan \u003c- fmt.Errorf(\"error reading from error stream for port %d -\u003e %d: %v\", port.Local, port.Remote, err)\n\t\tcase len(message) \u003e 0:\n\t\t\terrorChan \u003c- fmt.Errorf(\"an error occurred forwarding %d -\u003e %d: %v\", port.Local, port.Remote, string(message))\n\t\t}\n\t\tclose(errorChan)\n\t}()\n\n\t// create data stream\n\theaders.Set(v1.StreamType, v1.StreamTypeData)\n\tdataStream, err := pf.streamConn.CreateStream(headers)\n\tif err != nil {\n\t\truntime.HandleError(fmt.Errorf(\"error creating forwarding stream for port %d -\u003e %d: %v\", port.Local, port.Remote, err))\n\t\treturn\n\t}\n\tdefer pf.streamConn.RemoveStreams(dataStream)\n\n\tlocalError := make(chan struct{})\n\tremoteDone := make(chan struct{})\n\n\tgo func() {\n\t\t// Copy from the remote side to the local port.\n\t\tif _, err := io.Copy(conn, dataStream); err != nil \u0026\u0026 !strings.Contains(err.Error(), \"use of closed network connection\") {\n\t\t\truntime.HandleError(fmt.Errorf(\"error copying from remote stream to local connection: %v\", err))\n\t\t}\n\n\t\t// inform the select below that the remote copy is done\n\t\tclose(remoteDone)\n\t}()\n\n\tgo func() {\n\t\t// inform server we're not sending any more data after copy unblocks\n\t\tdefer dataStream.Close()\n\n\t\t// Copy from the local port to the remote side.\n\t\tif _, err := io.Copy(dataStream, conn); err != nil \u0026\u0026 !strings.Contains(err.Error(), \"use of closed network connection\") {\n\t\t\truntime.HandleError(fmt.Errorf(\"error copying from local connection to remote stream: %v\", err))\n\t\t\t// break out of the select below without waiting for the other copy to finish\n\t\t\tclose(localError)\n\t\t}\n\t}()\n\n\t// wait for either a local-\u003eremote error or for copying from remote-\u003elocal to finish\n\tselect {\n\tcase \u003c-remoteDone:\n\tcase \u003c-localError:\n\t}\n\n\t// always expect something on errorChan (it may be nil)\n\terr = \u003c-errorChan\n\tif err != nil {\n\t\truntime.HandleError(err)\n\t\tpf.streamConn.Close()\n\t}\n}","line":{"from":329,"to":412}} {"id":100029002,"name":"Close","signature":"func (pf *PortForwarder) Close()","file":"staging/src/k8s.io/client-go/tools/portforward/portforward.go","code":"// Close stops all listeners of PortForwarder.\nfunc (pf *PortForwarder) Close() {\n\t// stop all listeners\n\tfor _, l := range pf.listeners {\n\t\tif err := l.Close(); err != nil {\n\t\t\truntime.HandleError(fmt.Errorf(\"error closing listener: %v\", err))\n\t\t}\n\t}\n}","line":{"from":414,"to":422}} {"id":100029003,"name":"GetPorts","signature":"func (pf *PortForwarder) GetPorts() ([]ForwardedPort, error)","file":"staging/src/k8s.io/client-go/tools/portforward/portforward.go","code":"// GetPorts will return the ports that were forwarded; this can be used to\n// retrieve the locally-bound port in cases where the input was port 0. This\n// function will signal an error if the Ready channel is nil or if the\n// listeners are not ready yet; this function will succeed after the Ready\n// channel has been closed.\nfunc (pf *PortForwarder) GetPorts() ([]ForwardedPort, error) {\n\tif pf.Ready == nil {\n\t\treturn nil, fmt.Errorf(\"no Ready channel provided\")\n\t}\n\tselect {\n\tcase \u003c-pf.Ready:\n\t\treturn pf.ports, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"listeners not ready\")\n\t}\n}","line":{"from":424,"to":439}} {"id":100029004,"name":"NewEventRecorderAdapter","signature":"func NewEventRecorderAdapter(recorder EventRecorder) *EventRecorderAdapter","file":"staging/src/k8s.io/client-go/tools/record/event.go","code":"// NewEventRecorderAdapter returns an adapter implementing the new\n// \"k8s.io/client-go/tools/events\".EventRecorder interface.\nfunc NewEventRecorderAdapter(recorder EventRecorder) *EventRecorderAdapter {\n\treturn \u0026EventRecorderAdapter{\n\t\trecorder: recorder,\n\t}\n}","line":{"from":148,"to":154}} {"id":100029005,"name":"Eventf","signature":"func (a *EventRecorderAdapter) Eventf(regarding, _ runtime.Object, eventtype, reason, action, note string, args ...interface{})","file":"staging/src/k8s.io/client-go/tools/record/event.go","code":"// Eventf is a wrapper around v1 Eventf\nfunc (a *EventRecorderAdapter) Eventf(regarding, _ runtime.Object, eventtype, reason, action, note string, args ...interface{}) {\n\ta.recorder.Eventf(regarding, eventtype, reason, note, args...)\n}","line":{"from":156,"to":159}} {"id":100029006,"name":"NewBroadcaster","signature":"func NewBroadcaster() EventBroadcaster","file":"staging/src/k8s.io/client-go/tools/record/event.go","code":"// Creates a new event broadcaster.\nfunc NewBroadcaster() EventBroadcaster {\n\treturn newEventBroadcaster(watch.NewLongQueueBroadcaster(maxQueuedEvents, watch.DropIfChannelFull), defaultSleepDuration)\n}","line":{"from":161,"to":164}} {"id":100029007,"name":"NewBroadcasterForTests","signature":"func NewBroadcasterForTests(sleepDuration time.Duration) EventBroadcaster","file":"staging/src/k8s.io/client-go/tools/record/event.go","code":"func NewBroadcasterForTests(sleepDuration time.Duration) EventBroadcaster {\n\treturn newEventBroadcaster(watch.NewLongQueueBroadcaster(maxQueuedEvents, watch.DropIfChannelFull), sleepDuration)\n}","line":{"from":166,"to":168}} {"id":100029008,"name":"NewBroadcasterWithCorrelatorOptions","signature":"func NewBroadcasterWithCorrelatorOptions(options CorrelatorOptions) EventBroadcaster","file":"staging/src/k8s.io/client-go/tools/record/event.go","code":"func NewBroadcasterWithCorrelatorOptions(options CorrelatorOptions) EventBroadcaster {\n\teventBroadcaster := newEventBroadcaster(watch.NewLongQueueBroadcaster(maxQueuedEvents, watch.DropIfChannelFull), defaultSleepDuration)\n\teventBroadcaster.options = options\n\treturn eventBroadcaster\n}","line":{"from":170,"to":174}} {"id":100029009,"name":"newEventBroadcaster","signature":"func newEventBroadcaster(broadcaster *watch.Broadcaster, sleepDuration time.Duration) *eventBroadcasterImpl","file":"staging/src/k8s.io/client-go/tools/record/event.go","code":"func newEventBroadcaster(broadcaster *watch.Broadcaster, sleepDuration time.Duration) *eventBroadcasterImpl {\n\teventBroadcaster := \u0026eventBroadcasterImpl{\n\t\tBroadcaster: broadcaster,\n\t\tsleepDuration: sleepDuration,\n\t}\n\teventBroadcaster.cancelationCtx, eventBroadcaster.cancel = context.WithCancel(context.Background())\n\treturn eventBroadcaster\n}","line":{"from":176,"to":183}} {"id":100029010,"name":"StartRecordingToSink","signature":"func (e *eventBroadcasterImpl) StartRecordingToSink(sink EventSink) watch.Interface","file":"staging/src/k8s.io/client-go/tools/record/event.go","code":"// StartRecordingToSink starts sending events received from the specified eventBroadcaster to the given sink.\n// The return value can be ignored or used to stop recording, if desired.\n// TODO: make me an object with parameterizable queue length and retry interval\nfunc (e *eventBroadcasterImpl) StartRecordingToSink(sink EventSink) watch.Interface {\n\teventCorrelator := NewEventCorrelatorWithOptions(e.options)\n\treturn e.StartEventWatcher(\n\t\tfunc(event *v1.Event) {\n\t\t\te.recordToSink(sink, event, eventCorrelator)\n\t\t})\n}","line":{"from":193,"to":202}} {"id":100029011,"name":"Shutdown","signature":"func (e *eventBroadcasterImpl) Shutdown()","file":"staging/src/k8s.io/client-go/tools/record/event.go","code":"func (e *eventBroadcasterImpl) Shutdown() {\n\te.Broadcaster.Shutdown()\n\te.cancel()\n}","line":{"from":204,"to":207}} {"id":100029012,"name":"recordToSink","signature":"func (e *eventBroadcasterImpl) recordToSink(sink EventSink, event *v1.Event, eventCorrelator *EventCorrelator)","file":"staging/src/k8s.io/client-go/tools/record/event.go","code":"func (e *eventBroadcasterImpl) recordToSink(sink EventSink, event *v1.Event, eventCorrelator *EventCorrelator) {\n\t// Make a copy before modification, because there could be multiple listeners.\n\t// Events are safe to copy like this.\n\teventCopy := *event\n\tevent = \u0026eventCopy\n\tresult, err := eventCorrelator.EventCorrelate(event)\n\tif err != nil {\n\t\tutilruntime.HandleError(err)\n\t}\n\tif result.Skip {\n\t\treturn\n\t}\n\ttries := 0\n\tfor {\n\t\tif recordEvent(sink, result.Event, result.Patch, result.Event.Count \u003e 1, eventCorrelator) {\n\t\t\tbreak\n\t\t}\n\t\ttries++\n\t\tif tries \u003e= maxTriesPerEvent {\n\t\t\tklog.Errorf(\"Unable to write event '%#v' (retry limit exceeded!)\", event)\n\t\t\tbreak\n\t\t}\n\n\t\t// Randomize the first sleep so that various clients won't all be\n\t\t// synced up if the master goes down.\n\t\tdelay := e.sleepDuration\n\t\tif tries == 1 {\n\t\t\tdelay = time.Duration(float64(delay) * rand.Float64())\n\t\t}\n\t\tselect {\n\t\tcase \u003c-e.cancelationCtx.Done():\n\t\t\tklog.Errorf(\"Unable to write event '%#v' (broadcaster is shut down)\", event)\n\t\t\treturn\n\t\tcase \u003c-time.After(delay):\n\t\t}\n\t}\n}","line":{"from":209,"to":245}} {"id":100029013,"name":"recordEvent","signature":"func recordEvent(sink EventSink, event *v1.Event, patch []byte, updateExistingEvent bool, eventCorrelator *EventCorrelator) bool","file":"staging/src/k8s.io/client-go/tools/record/event.go","code":"// recordEvent attempts to write event to a sink. It returns true if the event\n// was successfully recorded or discarded, false if it should be retried.\n// If updateExistingEvent is false, it creates a new event, otherwise it updates\n// existing event.\nfunc recordEvent(sink EventSink, event *v1.Event, patch []byte, updateExistingEvent bool, eventCorrelator *EventCorrelator) bool {\n\tvar newEvent *v1.Event\n\tvar err error\n\tif updateExistingEvent {\n\t\tnewEvent, err = sink.Patch(event, patch)\n\t}\n\t// Update can fail because the event may have been removed and it no longer exists.\n\tif !updateExistingEvent || (updateExistingEvent \u0026\u0026 util.IsKeyNotFoundError(err)) {\n\t\t// Making sure that ResourceVersion is empty on creation\n\t\tevent.ResourceVersion = \"\"\n\t\tnewEvent, err = sink.Create(event)\n\t}\n\tif err == nil {\n\t\t// we need to update our event correlator with the server returned state to handle name/resourceversion\n\t\teventCorrelator.UpdateState(newEvent)\n\t\treturn true\n\t}\n\n\t// If we can't contact the server, then hold everything while we keep trying.\n\t// Otherwise, something about the event is malformed and we should abandon it.\n\tswitch err.(type) {\n\tcase *restclient.RequestConstructionError:\n\t\t// We will construct the request the same next time, so don't keep trying.\n\t\tklog.Errorf(\"Unable to construct event '%#v': '%v' (will not retry!)\", event, err)\n\t\treturn true\n\tcase *errors.StatusError:\n\t\tif errors.IsAlreadyExists(err) {\n\t\t\tklog.V(5).Infof(\"Server rejected event '%#v': '%v' (will not retry!)\", event, err)\n\t\t} else {\n\t\t\tklog.Errorf(\"Server rejected event '%#v': '%v' (will not retry!)\", event, err)\n\t\t}\n\t\treturn true\n\tcase *errors.UnexpectedObjectError:\n\t\t// We don't expect this; it implies the server's response didn't match a\n\t\t// known pattern. Go ahead and retry.\n\tdefault:\n\t\t// This case includes actual http transport errors. Go ahead and retry.\n\t}\n\tklog.Errorf(\"Unable to write event: '%#v': '%v'(may retry after sleeping)\", event, err)\n\treturn false\n}","line":{"from":247,"to":291}} {"id":100029014,"name":"StartLogging","signature":"func (e *eventBroadcasterImpl) StartLogging(logf func(format string, args ...interface{})) watch.Interface","file":"staging/src/k8s.io/client-go/tools/record/event.go","code":"// StartLogging starts sending events received from this EventBroadcaster to the given logging function.\n// The return value can be ignored or used to stop recording, if desired.\nfunc (e *eventBroadcasterImpl) StartLogging(logf func(format string, args ...interface{})) watch.Interface {\n\treturn e.StartEventWatcher(\n\t\tfunc(e *v1.Event) {\n\t\t\tlogf(\"Event(%#v): type: '%v' reason: '%v' %v\", e.InvolvedObject, e.Type, e.Reason, e.Message)\n\t\t})\n}","line":{"from":293,"to":300}} {"id":100029015,"name":"StartStructuredLogging","signature":"func (e *eventBroadcasterImpl) StartStructuredLogging(verbosity klog.Level) watch.Interface","file":"staging/src/k8s.io/client-go/tools/record/event.go","code":"// StartStructuredLogging starts sending events received from this EventBroadcaster to the structured logging function.\n// The return value can be ignored or used to stop recording, if desired.\nfunc (e *eventBroadcasterImpl) StartStructuredLogging(verbosity klog.Level) watch.Interface {\n\treturn e.StartEventWatcher(\n\t\tfunc(e *v1.Event) {\n\t\t\tklog.V(verbosity).InfoS(\"Event occurred\", \"object\", klog.KRef(e.InvolvedObject.Namespace, e.InvolvedObject.Name), \"fieldPath\", e.InvolvedObject.FieldPath, \"kind\", e.InvolvedObject.Kind, \"apiVersion\", e.InvolvedObject.APIVersion, \"type\", e.Type, \"reason\", e.Reason, \"message\", e.Message)\n\t\t})\n}","line":{"from":302,"to":309}} {"id":100029016,"name":"StartEventWatcher","signature":"func (e *eventBroadcasterImpl) StartEventWatcher(eventHandler func(*v1.Event)) watch.Interface","file":"staging/src/k8s.io/client-go/tools/record/event.go","code":"// StartEventWatcher starts sending events received from this EventBroadcaster to the given event handler function.\n// The return value can be ignored or used to stop recording, if desired.\nfunc (e *eventBroadcasterImpl) StartEventWatcher(eventHandler func(*v1.Event)) watch.Interface {\n\twatcher, err := e.Watch()\n\tif err != nil {\n\t\tklog.Errorf(\"Unable start event watcher: '%v' (will not retry!)\", err)\n\t}\n\tgo func() {\n\t\tdefer utilruntime.HandleCrash()\n\t\tfor watchEvent := range watcher.ResultChan() {\n\t\t\tevent, ok := watchEvent.Object.(*v1.Event)\n\t\t\tif !ok {\n\t\t\t\t// This is all local, so there's no reason this should\n\t\t\t\t// ever happen.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\teventHandler(event)\n\t\t}\n\t}()\n\treturn watcher\n}","line":{"from":311,"to":331}} {"id":100029017,"name":"NewRecorder","signature":"func (e *eventBroadcasterImpl) NewRecorder(scheme *runtime.Scheme, source v1.EventSource) EventRecorder","file":"staging/src/k8s.io/client-go/tools/record/event.go","code":"// NewRecorder returns an EventRecorder that records events with the given event source.\nfunc (e *eventBroadcasterImpl) NewRecorder(scheme *runtime.Scheme, source v1.EventSource) EventRecorder {\n\treturn \u0026recorderImpl{scheme, source, e.Broadcaster, clock.RealClock{}}\n}","line":{"from":333,"to":336}} {"id":100029018,"name":"generateEvent","signature":"func (recorder *recorderImpl) generateEvent(object runtime.Object, annotations map[string]string, eventtype, reason, message string)","file":"staging/src/k8s.io/client-go/tools/record/event.go","code":"func (recorder *recorderImpl) generateEvent(object runtime.Object, annotations map[string]string, eventtype, reason, message string) {\n\tref, err := ref.GetReference(recorder.scheme, object)\n\tif err != nil {\n\t\tklog.Errorf(\"Could not construct reference to: '%#v' due to: '%v'. Will not report event: '%v' '%v' '%v'\", object, err, eventtype, reason, message)\n\t\treturn\n\t}\n\n\tif !util.ValidateEventType(eventtype) {\n\t\tklog.Errorf(\"Unsupported event type: '%v'\", eventtype)\n\t\treturn\n\t}\n\n\tevent := recorder.makeEvent(ref, annotations, eventtype, reason, message)\n\tevent.Source = recorder.source\n\n\t// NOTE: events should be a non-blocking operation, but we also need to not\n\t// put this in a goroutine, otherwise we'll race to write to a closed channel\n\t// when we go to shut down this broadcaster. Just drop events if we get overloaded,\n\t// and log an error if that happens (we've configured the broadcaster to drop\n\t// outgoing events anyway).\n\tsent, err := recorder.ActionOrDrop(watch.Added, event)\n\tif err != nil {\n\t\tklog.Errorf(\"unable to record event: %v (will not retry!)\", err)\n\t\treturn\n\t}\n\tif !sent {\n\t\tklog.Errorf(\"unable to record event: too many queued events, dropped event %#v\", event)\n\t}\n}","line":{"from":345,"to":373}} {"id":100029019,"name":"Event","signature":"func (recorder *recorderImpl) Event(object runtime.Object, eventtype, reason, message string)","file":"staging/src/k8s.io/client-go/tools/record/event.go","code":"func (recorder *recorderImpl) Event(object runtime.Object, eventtype, reason, message string) {\n\trecorder.generateEvent(object, nil, eventtype, reason, message)\n}","line":{"from":375,"to":377}} {"id":100029020,"name":"Eventf","signature":"func (recorder *recorderImpl) Eventf(object runtime.Object, eventtype, reason, messageFmt string, args ...interface{})","file":"staging/src/k8s.io/client-go/tools/record/event.go","code":"func (recorder *recorderImpl) Eventf(object runtime.Object, eventtype, reason, messageFmt string, args ...interface{}) {\n\trecorder.Event(object, eventtype, reason, fmt.Sprintf(messageFmt, args...))\n}","line":{"from":379,"to":381}} {"id":100029021,"name":"AnnotatedEventf","signature":"func (recorder *recorderImpl) AnnotatedEventf(object runtime.Object, annotations map[string]string, eventtype, reason, messageFmt string, args ...interface{})","file":"staging/src/k8s.io/client-go/tools/record/event.go","code":"func (recorder *recorderImpl) AnnotatedEventf(object runtime.Object, annotations map[string]string, eventtype, reason, messageFmt string, args ...interface{}) {\n\trecorder.generateEvent(object, annotations, eventtype, reason, fmt.Sprintf(messageFmt, args...))\n}","line":{"from":383,"to":385}} {"id":100029022,"name":"makeEvent","signature":"func (recorder *recorderImpl) makeEvent(ref *v1.ObjectReference, annotations map[string]string, eventtype, reason, message string) *v1.Event","file":"staging/src/k8s.io/client-go/tools/record/event.go","code":"func (recorder *recorderImpl) makeEvent(ref *v1.ObjectReference, annotations map[string]string, eventtype, reason, message string) *v1.Event {\n\tt := metav1.Time{Time: recorder.clock.Now()}\n\tnamespace := ref.Namespace\n\tif namespace == \"\" {\n\t\tnamespace = metav1.NamespaceDefault\n\t}\n\treturn \u0026v1.Event{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: fmt.Sprintf(\"%v.%x\", ref.Name, t.UnixNano()),\n\t\t\tNamespace: namespace,\n\t\t\tAnnotations: annotations,\n\t\t},\n\t\tInvolvedObject: *ref,\n\t\tReason: reason,\n\t\tMessage: message,\n\t\tFirstTimestamp: t,\n\t\tLastTimestamp: t,\n\t\tCount: 1,\n\t\tType: eventtype,\n\t}\n}","line":{"from":387,"to":407}} {"id":100029023,"name":"getEventKey","signature":"func getEventKey(event *v1.Event) string","file":"staging/src/k8s.io/client-go/tools/record/events_cache.go","code":"// getEventKey builds unique event key based on source, involvedObject, reason, message\nfunc getEventKey(event *v1.Event) string {\n\treturn strings.Join([]string{\n\t\tevent.Source.Component,\n\t\tevent.Source.Host,\n\t\tevent.InvolvedObject.Kind,\n\t\tevent.InvolvedObject.Namespace,\n\t\tevent.InvolvedObject.Name,\n\t\tevent.InvolvedObject.FieldPath,\n\t\tstring(event.InvolvedObject.UID),\n\t\tevent.InvolvedObject.APIVersion,\n\t\tevent.Type,\n\t\tevent.Reason,\n\t\tevent.Message,\n\t},\n\t\t\"\")\n}","line":{"from":52,"to":68}} {"id":100029024,"name":"getSpamKey","signature":"func getSpamKey(event *v1.Event) string","file":"staging/src/k8s.io/client-go/tools/record/events_cache.go","code":"// getSpamKey builds unique event key based on source, involvedObject\nfunc getSpamKey(event *v1.Event) string {\n\treturn strings.Join([]string{\n\t\tevent.Source.Component,\n\t\tevent.Source.Host,\n\t\tevent.InvolvedObject.Kind,\n\t\tevent.InvolvedObject.Namespace,\n\t\tevent.InvolvedObject.Name,\n\t\tstring(event.InvolvedObject.UID),\n\t\tevent.InvolvedObject.APIVersion,\n\t},\n\t\t\"\")\n}","line":{"from":70,"to":82}} {"id":100029025,"name":"NewEventSourceObjectSpamFilter","signature":"func NewEventSourceObjectSpamFilter(lruCacheSize, burst int, qps float32, clock clock.PassiveClock, spamKeyFunc EventSpamKeyFunc) *EventSourceObjectSpamFilter","file":"staging/src/k8s.io/client-go/tools/record/events_cache.go","code":"// NewEventSourceObjectSpamFilter allows burst events from a source about an object with the specified qps refill.\nfunc NewEventSourceObjectSpamFilter(lruCacheSize, burst int, qps float32, clock clock.PassiveClock, spamKeyFunc EventSpamKeyFunc) *EventSourceObjectSpamFilter {\n\treturn \u0026EventSourceObjectSpamFilter{\n\t\tcache: lru.New(lruCacheSize),\n\t\tburst: burst,\n\t\tqps: qps,\n\t\tclock: clock,\n\t\tspamKeyFunc: spamKeyFunc,\n\t}\n}","line":{"from":111,"to":120}} {"id":100029026,"name":"Filter","signature":"func (f *EventSourceObjectSpamFilter) Filter(event *v1.Event) bool","file":"staging/src/k8s.io/client-go/tools/record/events_cache.go","code":"// Filter controls that a given source+object are not exceeding the allowed rate.\nfunc (f *EventSourceObjectSpamFilter) Filter(event *v1.Event) bool {\n\tvar record spamRecord\n\n\t// controls our cached information about this event\n\teventKey := f.spamKeyFunc(event)\n\n\t// do we have a record of similar events in our cache?\n\tf.Lock()\n\tdefer f.Unlock()\n\tvalue, found := f.cache.Get(eventKey)\n\tif found {\n\t\trecord = value.(spamRecord)\n\t}\n\n\t// verify we have a rate limiter for this record\n\tif record.rateLimiter == nil {\n\t\trecord.rateLimiter = flowcontrol.NewTokenBucketPassiveRateLimiterWithClock(f.qps, f.burst, f.clock)\n\t}\n\n\t// ensure we have available rate\n\tfilter := !record.rateLimiter.TryAccept()\n\n\t// update the cache\n\tf.cache.Add(eventKey, record)\n\n\treturn filter\n}","line":{"from":128,"to":155}} {"id":100029027,"name":"EventAggregatorByReasonFunc","signature":"func EventAggregatorByReasonFunc(event *v1.Event) (string, string)","file":"staging/src/k8s.io/client-go/tools/record/events_cache.go","code":"// EventAggregatorByReasonFunc aggregates events by exact match on event.Source, event.InvolvedObject, event.Type,\n// event.Reason, event.ReportingController and event.ReportingInstance\nfunc EventAggregatorByReasonFunc(event *v1.Event) (string, string) {\n\treturn strings.Join([]string{\n\t\tevent.Source.Component,\n\t\tevent.Source.Host,\n\t\tevent.InvolvedObject.Kind,\n\t\tevent.InvolvedObject.Namespace,\n\t\tevent.InvolvedObject.Name,\n\t\tstring(event.InvolvedObject.UID),\n\t\tevent.InvolvedObject.APIVersion,\n\t\tevent.Type,\n\t\tevent.Reason,\n\t\tevent.ReportingController,\n\t\tevent.ReportingInstance,\n\t},\n\t\t\"\"), event.Message\n}","line":{"from":163,"to":180}} {"id":100029028,"name":"EventAggregatorByReasonMessageFunc","signature":"func EventAggregatorByReasonMessageFunc(event *v1.Event) string","file":"staging/src/k8s.io/client-go/tools/record/events_cache.go","code":"// EventAggregatorByReasonMessageFunc returns an aggregate message by prefixing the incoming message\nfunc EventAggregatorByReasonMessageFunc(event *v1.Event) string {\n\treturn \"(combined from similar events): \" + event.Message\n}","line":{"from":185,"to":188}} {"id":100029029,"name":"NewEventAggregator","signature":"func NewEventAggregator(lruCacheSize int, keyFunc EventAggregatorKeyFunc, messageFunc EventAggregatorMessageFunc,","file":"staging/src/k8s.io/client-go/tools/record/events_cache.go","code":"// NewEventAggregator returns a new instance of an EventAggregator\nfunc NewEventAggregator(lruCacheSize int, keyFunc EventAggregatorKeyFunc, messageFunc EventAggregatorMessageFunc,\n\tmaxEvents int, maxIntervalInSeconds int, clock clock.PassiveClock) *EventAggregator {\n\treturn \u0026EventAggregator{\n\t\tcache: lru.New(lruCacheSize),\n\t\tkeyFunc: keyFunc,\n\t\tmessageFunc: messageFunc,\n\t\tmaxEvents: uint(maxEvents),\n\t\tmaxIntervalInSeconds: uint(maxIntervalInSeconds),\n\t\tclock: clock,\n\t}\n}","line":{"from":213,"to":224}} {"id":100029030,"name":"EventAggregate","signature":"func (e *EventAggregator) EventAggregate(newEvent *v1.Event) (*v1.Event, string)","file":"staging/src/k8s.io/client-go/tools/record/events_cache.go","code":"// EventAggregate checks if a similar event has been seen according to the\n// aggregation configuration (max events, max interval, etc) and returns:\n//\n// - The (potentially modified) event that should be created\n// - The cache key for the event, for correlation purposes. This will be set to\n// the full key for normal events, and to the result of\n// EventAggregatorMessageFunc for aggregate events.\nfunc (e *EventAggregator) EventAggregate(newEvent *v1.Event) (*v1.Event, string) {\n\tnow := metav1.NewTime(e.clock.Now())\n\tvar record aggregateRecord\n\t// eventKey is the full cache key for this event\n\teventKey := getEventKey(newEvent)\n\t// aggregateKey is for the aggregate event, if one is needed.\n\taggregateKey, localKey := e.keyFunc(newEvent)\n\n\t// Do we have a record of similar events in our cache?\n\te.Lock()\n\tdefer e.Unlock()\n\tvalue, found := e.cache.Get(aggregateKey)\n\tif found {\n\t\trecord = value.(aggregateRecord)\n\t}\n\n\t// Is the previous record too old? If so, make a fresh one. Note: if we didn't\n\t// find a similar record, its lastTimestamp will be the zero value, so we\n\t// create a new one in that case.\n\tmaxInterval := time.Duration(e.maxIntervalInSeconds) * time.Second\n\tinterval := now.Time.Sub(record.lastTimestamp.Time)\n\tif interval \u003e maxInterval {\n\t\trecord = aggregateRecord{localKeys: sets.NewString()}\n\t}\n\n\t// Write the new event into the aggregation record and put it on the cache\n\trecord.localKeys.Insert(localKey)\n\trecord.lastTimestamp = now\n\te.cache.Add(aggregateKey, record)\n\n\t// If we are not yet over the threshold for unique events, don't correlate them\n\tif uint(record.localKeys.Len()) \u003c e.maxEvents {\n\t\treturn newEvent, eventKey\n\t}\n\n\t// do not grow our local key set any larger than max\n\trecord.localKeys.PopAny()\n\n\t// create a new aggregate event, and return the aggregateKey as the cache key\n\t// (so that it can be overwritten.)\n\teventCopy := \u0026v1.Event{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: fmt.Sprintf(\"%v.%x\", newEvent.InvolvedObject.Name, now.UnixNano()),\n\t\t\tNamespace: newEvent.Namespace,\n\t\t},\n\t\tCount: 1,\n\t\tFirstTimestamp: now,\n\t\tInvolvedObject: newEvent.InvolvedObject,\n\t\tLastTimestamp: now,\n\t\tMessage: e.messageFunc(newEvent),\n\t\tType: newEvent.Type,\n\t\tReason: newEvent.Reason,\n\t\tSource: newEvent.Source,\n\t}\n\treturn eventCopy, aggregateKey\n}","line":{"from":235,"to":297}} {"id":100029031,"name":"newEventLogger","signature":"func newEventLogger(lruCacheEntries int, clock clock.PassiveClock) *eventLogger","file":"staging/src/k8s.io/client-go/tools/record/events_cache.go","code":"// newEventLogger observes events and counts their frequencies\nfunc newEventLogger(lruCacheEntries int, clock clock.PassiveClock) *eventLogger {\n\treturn \u0026eventLogger{cache: lru.New(lruCacheEntries), clock: clock}\n}","line":{"from":321,"to":324}} {"id":100029032,"name":"eventObserve","signature":"func (e *eventLogger) eventObserve(newEvent *v1.Event, key string) (*v1.Event, []byte, error)","file":"staging/src/k8s.io/client-go/tools/record/events_cache.go","code":"// eventObserve records an event, or updates an existing one if key is a cache hit\nfunc (e *eventLogger) eventObserve(newEvent *v1.Event, key string) (*v1.Event, []byte, error) {\n\tvar (\n\t\tpatch []byte\n\t\terr error\n\t)\n\teventCopy := *newEvent\n\tevent := \u0026eventCopy\n\n\te.Lock()\n\tdefer e.Unlock()\n\n\t// Check if there is an existing event we should update\n\tlastObservation := e.lastEventObservationFromCache(key)\n\n\t// If we found a result, prepare a patch\n\tif lastObservation.count \u003e 0 {\n\t\t// update the event based on the last observation so patch will work as desired\n\t\tevent.Name = lastObservation.name\n\t\tevent.ResourceVersion = lastObservation.resourceVersion\n\t\tevent.FirstTimestamp = lastObservation.firstTimestamp\n\t\tevent.Count = int32(lastObservation.count) + 1\n\n\t\teventCopy2 := *event\n\t\teventCopy2.Count = 0\n\t\teventCopy2.LastTimestamp = metav1.NewTime(time.Unix(0, 0))\n\t\teventCopy2.Message = \"\"\n\n\t\tnewData, _ := json.Marshal(event)\n\t\toldData, _ := json.Marshal(eventCopy2)\n\t\tpatch, err = strategicpatch.CreateTwoWayMergePatch(oldData, newData, event)\n\t}\n\n\t// record our new observation\n\te.cache.Add(\n\t\tkey,\n\t\teventLog{\n\t\t\tcount: uint(event.Count),\n\t\t\tfirstTimestamp: event.FirstTimestamp,\n\t\t\tname: event.Name,\n\t\t\tresourceVersion: event.ResourceVersion,\n\t\t},\n\t)\n\treturn event, patch, err\n}","line":{"from":326,"to":370}} {"id":100029033,"name":"updateState","signature":"func (e *eventLogger) updateState(event *v1.Event)","file":"staging/src/k8s.io/client-go/tools/record/events_cache.go","code":"// updateState updates its internal tracking information based on latest server state\nfunc (e *eventLogger) updateState(event *v1.Event) {\n\tkey := getEventKey(event)\n\te.Lock()\n\tdefer e.Unlock()\n\t// record our new observation\n\te.cache.Add(\n\t\tkey,\n\t\teventLog{\n\t\t\tcount: uint(event.Count),\n\t\t\tfirstTimestamp: event.FirstTimestamp,\n\t\t\tname: event.Name,\n\t\t\tresourceVersion: event.ResourceVersion,\n\t\t},\n\t)\n}","line":{"from":372,"to":387}} {"id":100029034,"name":"lastEventObservationFromCache","signature":"func (e *eventLogger) lastEventObservationFromCache(key string) eventLog","file":"staging/src/k8s.io/client-go/tools/record/events_cache.go","code":"// lastEventObservationFromCache returns the event from the cache, reads must be protected via external lock\nfunc (e *eventLogger) lastEventObservationFromCache(key string) eventLog {\n\tvalue, ok := e.cache.Get(key)\n\tif ok {\n\t\tobservationValue, ok := value.(eventLog)\n\t\tif ok {\n\t\t\treturn observationValue\n\t\t}\n\t}\n\treturn eventLog{}\n}","line":{"from":389,"to":399}} {"id":100029035,"name":"NewEventCorrelator","signature":"func NewEventCorrelator(clock clock.PassiveClock) *EventCorrelator","file":"staging/src/k8s.io/client-go/tools/record/events_cache.go","code":"// NewEventCorrelator returns an EventCorrelator configured with default values.\n//\n// The EventCorrelator is responsible for event filtering, aggregating, and counting\n// prior to interacting with the API server to record the event.\n//\n// The default behavior is as follows:\n// - Aggregation is performed if a similar event is recorded 10 times\n// in a 10 minute rolling interval. A similar event is an event that varies only by\n// the Event.Message field. Rather than recording the precise event, aggregation\n// will create a new event whose message reports that it has combined events with\n// the same reason.\n// - Events are incrementally counted if the exact same event is encountered multiple\n// times.\n// - A source may burst 25 events about an object, but has a refill rate budget\n// per object of 1 event every 5 minutes to control long-tail of spam.\nfunc NewEventCorrelator(clock clock.PassiveClock) *EventCorrelator {\n\tcacheSize := maxLruCacheEntries\n\tspamFilter := NewEventSourceObjectSpamFilter(cacheSize, defaultSpamBurst, defaultSpamQPS, clock, getSpamKey)\n\treturn \u0026EventCorrelator{\n\t\tfilterFunc: spamFilter.Filter,\n\t\taggregator: NewEventAggregator(\n\t\t\tcacheSize,\n\t\t\tEventAggregatorByReasonFunc,\n\t\t\tEventAggregatorByReasonMessageFunc,\n\t\t\tdefaultAggregateMaxEvents,\n\t\t\tdefaultAggregateIntervalInSeconds,\n\t\t\tclock),\n\n\t\tlogger: newEventLogger(cacheSize, clock),\n\t}\n}","line":{"from":424,"to":454}} {"id":100029036,"name":"NewEventCorrelatorWithOptions","signature":"func NewEventCorrelatorWithOptions(options CorrelatorOptions) *EventCorrelator","file":"staging/src/k8s.io/client-go/tools/record/events_cache.go","code":"func NewEventCorrelatorWithOptions(options CorrelatorOptions) *EventCorrelator {\n\toptionsWithDefaults := populateDefaults(options)\n\tspamFilter := NewEventSourceObjectSpamFilter(\n\t\toptionsWithDefaults.LRUCacheSize,\n\t\toptionsWithDefaults.BurstSize,\n\t\toptionsWithDefaults.QPS,\n\t\toptionsWithDefaults.Clock,\n\t\toptionsWithDefaults.SpamKeyFunc)\n\treturn \u0026EventCorrelator{\n\t\tfilterFunc: spamFilter.Filter,\n\t\taggregator: NewEventAggregator(\n\t\t\toptionsWithDefaults.LRUCacheSize,\n\t\t\toptionsWithDefaults.KeyFunc,\n\t\t\toptionsWithDefaults.MessageFunc,\n\t\t\toptionsWithDefaults.MaxEvents,\n\t\t\toptionsWithDefaults.MaxIntervalInSeconds,\n\t\t\toptionsWithDefaults.Clock),\n\t\tlogger: newEventLogger(optionsWithDefaults.LRUCacheSize, optionsWithDefaults.Clock),\n\t}\n}","line":{"from":456,"to":475}} {"id":100029037,"name":"populateDefaults","signature":"func populateDefaults(options CorrelatorOptions) CorrelatorOptions","file":"staging/src/k8s.io/client-go/tools/record/events_cache.go","code":"// populateDefaults populates the zero value options with defaults\nfunc populateDefaults(options CorrelatorOptions) CorrelatorOptions {\n\tif options.LRUCacheSize == 0 {\n\t\toptions.LRUCacheSize = maxLruCacheEntries\n\t}\n\tif options.BurstSize == 0 {\n\t\toptions.BurstSize = defaultSpamBurst\n\t}\n\tif options.QPS == 0 {\n\t\toptions.QPS = defaultSpamQPS\n\t}\n\tif options.KeyFunc == nil {\n\t\toptions.KeyFunc = EventAggregatorByReasonFunc\n\t}\n\tif options.MessageFunc == nil {\n\t\toptions.MessageFunc = EventAggregatorByReasonMessageFunc\n\t}\n\tif options.MaxEvents == 0 {\n\t\toptions.MaxEvents = defaultAggregateMaxEvents\n\t}\n\tif options.MaxIntervalInSeconds == 0 {\n\t\toptions.MaxIntervalInSeconds = defaultAggregateIntervalInSeconds\n\t}\n\tif options.Clock == nil {\n\t\toptions.Clock = clock.RealClock{}\n\t}\n\tif options.SpamKeyFunc == nil {\n\t\toptions.SpamKeyFunc = getSpamKey\n\t}\n\treturn options\n}","line":{"from":477,"to":507}} {"id":100029038,"name":"EventCorrelate","signature":"func (c *EventCorrelator) EventCorrelate(newEvent *v1.Event) (*EventCorrelateResult, error)","file":"staging/src/k8s.io/client-go/tools/record/events_cache.go","code":"// EventCorrelate filters, aggregates, counts, and de-duplicates all incoming events\nfunc (c *EventCorrelator) EventCorrelate(newEvent *v1.Event) (*EventCorrelateResult, error) {\n\tif newEvent == nil {\n\t\treturn nil, fmt.Errorf(\"event is nil\")\n\t}\n\taggregateEvent, ckey := c.aggregator.EventAggregate(newEvent)\n\tobservedEvent, patch, err := c.logger.eventObserve(aggregateEvent, ckey)\n\tif c.filterFunc(observedEvent) {\n\t\treturn \u0026EventCorrelateResult{Skip: true}, nil\n\t}\n\treturn \u0026EventCorrelateResult{Event: observedEvent, Patch: patch}, err\n}","line":{"from":509,"to":520}} {"id":100029039,"name":"UpdateState","signature":"func (c *EventCorrelator) UpdateState(event *v1.Event)","file":"staging/src/k8s.io/client-go/tools/record/events_cache.go","code":"// UpdateState based on the latest observed state from server\nfunc (c *EventCorrelator) UpdateState(event *v1.Event) {\n\tc.logger.updateState(event)\n}","line":{"from":522,"to":525}} {"id":100029040,"name":"ValidateEventType","signature":"func ValidateEventType(eventtype string) bool","file":"staging/src/k8s.io/client-go/tools/record/util/util.go","code":"// ValidateEventType checks that eventtype is an expected type of event\nfunc ValidateEventType(eventtype string) bool {\n\tswitch eventtype {\n\tcase v1.EventTypeNormal, v1.EventTypeWarning:\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":26,"to":33}} {"id":100029041,"name":"IsKeyNotFoundError","signature":"func IsKeyNotFoundError(err error) bool","file":"staging/src/k8s.io/client-go/tools/record/util/util.go","code":"// IsKeyNotFoundError is utility function that checks if an error is not found error\nfunc IsKeyNotFoundError(err error) bool {\n\tstatusErr, _ := err.(*errors.StatusError)\n\n\treturn statusErr != nil \u0026\u0026 statusErr.Status().Code == http.StatusNotFound\n}","line":{"from":35,"to":40}} {"id":100029042,"name":"GetReference","signature":"func GetReference(scheme *runtime.Scheme, obj runtime.Object) (*v1.ObjectReference, error)","file":"staging/src/k8s.io/client-go/tools/reference/ref.go","code":"// GetReference returns an ObjectReference which refers to the given\n// object, or an error if the object doesn't follow the conventions\n// that would allow this.\n// TODO: should take a meta.Interface see https://issue.k8s.io/7127\nfunc GetReference(scheme *runtime.Scheme, obj runtime.Object) (*v1.ObjectReference, error) {\n\tif obj == nil {\n\t\treturn nil, ErrNilObject\n\t}\n\tif ref, ok := obj.(*v1.ObjectReference); ok {\n\t\t// Don't make a reference to a reference.\n\t\treturn ref, nil\n\t}\n\n\t// An object that implements only List has enough metadata to build a reference\n\tvar listMeta metav1.Common\n\tobjectMeta, err := meta.Accessor(obj)\n\tif err != nil {\n\t\tlistMeta, err = meta.CommonAccessor(obj)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tlistMeta = objectMeta\n\t}\n\n\tgvk := obj.GetObjectKind().GroupVersionKind()\n\n\t// If object meta doesn't contain data about kind and/or version,\n\t// we are falling back to scheme.\n\t//\n\t// TODO: This doesn't work for CRDs, which are not registered in scheme.\n\tif gvk.Empty() {\n\t\tgvks, _, err := scheme.ObjectKinds(obj)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(gvks) == 0 || gvks[0].Empty() {\n\t\t\treturn nil, fmt.Errorf(\"unexpected gvks registered for object %T: %v\", obj, gvks)\n\t\t}\n\t\t// TODO: The same object can be registered for multiple group versions\n\t\t// (although in practise this doesn't seem to be used).\n\t\t// In such case, the version set may not be correct.\n\t\tgvk = gvks[0]\n\t}\n\n\tkind := gvk.Kind\n\tversion := gvk.GroupVersion().String()\n\n\t// only has list metadata\n\tif objectMeta == nil {\n\t\treturn \u0026v1.ObjectReference{\n\t\t\tKind: kind,\n\t\t\tAPIVersion: version,\n\t\t\tResourceVersion: listMeta.GetResourceVersion(),\n\t\t}, nil\n\t}\n\n\treturn \u0026v1.ObjectReference{\n\t\tKind: kind,\n\t\tAPIVersion: version,\n\t\tName: objectMeta.GetName(),\n\t\tNamespace: objectMeta.GetNamespace(),\n\t\tUID: objectMeta.GetUID(),\n\t\tResourceVersion: objectMeta.GetResourceVersion(),\n\t}, nil\n}","line":{"from":34,"to":99}} {"id":100029043,"name":"GetPartialReference","signature":"func GetPartialReference(scheme *runtime.Scheme, obj runtime.Object, fieldPath string) (*v1.ObjectReference, error)","file":"staging/src/k8s.io/client-go/tools/reference/ref.go","code":"// GetPartialReference is exactly like GetReference, but allows you to set the FieldPath.\nfunc GetPartialReference(scheme *runtime.Scheme, obj runtime.Object, fieldPath string) (*v1.ObjectReference, error) {\n\tref, err := GetReference(scheme, obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tref.FieldPath = fieldPath\n\treturn ref, nil\n}","line":{"from":101,"to":109}} {"id":100029044,"name":"watchErrorStream","signature":"func watchErrorStream(errorStream io.Reader, d errorStreamDecoder) chan error","file":"staging/src/k8s.io/client-go/tools/remotecommand/errorstream.go","code":"// watchErrorStream watches the errorStream for remote command error data,\n// decodes it with the given errorStreamDecoder, sends the decoded error (or nil if the remote\n// command exited successfully) to the returned error channel, and closes it.\n// This function returns immediately.\nfunc watchErrorStream(errorStream io.Reader, d errorStreamDecoder) chan error {\n\terrorChan := make(chan error)\n\n\tgo func() {\n\t\tdefer runtime.HandleCrash()\n\n\t\tmessage, err := io.ReadAll(errorStream)\n\t\tswitch {\n\t\tcase err != nil \u0026\u0026 err != io.EOF:\n\t\t\terrorChan \u003c- fmt.Errorf(\"error reading from error stream: %s\", err)\n\t\tcase len(message) \u003e 0:\n\t\t\terrorChan \u003c- d.decode(message)\n\t\tdefault:\n\t\t\terrorChan \u003c- nil\n\t\t}\n\t\tclose(errorChan)\n\t}()\n\n\treturn errorChan\n}","line":{"from":31,"to":54}} {"id":100029045,"name":"Read","signature":"func (r readerWrapper) Read(p []byte) (int, error)","file":"staging/src/k8s.io/client-go/tools/remotecommand/reader.go","code":"func (r readerWrapper) Read(p []byte) (int, error) {\n\treturn r.reader.Read(p)\n}","line":{"from":39,"to":41}} {"id":100029046,"name":"NewSPDYExecutor","signature":"func NewSPDYExecutor(config *restclient.Config, method string, url *url.URL) (Executor, error)","file":"staging/src/k8s.io/client-go/tools/remotecommand/remotecommand.go","code":"// NewSPDYExecutor connects to the provided server and upgrades the connection to\n// multiplexed bidirectional streams.\nfunc NewSPDYExecutor(config *restclient.Config, method string, url *url.URL) (Executor, error) {\n\twrapper, upgradeRoundTripper, err := spdy.RoundTripperFor(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewSPDYExecutorForTransports(wrapper, upgradeRoundTripper, method, url)\n}","line":{"from":77,"to":85}} {"id":100029047,"name":"NewSPDYExecutorForTransports","signature":"func NewSPDYExecutorForTransports(transport http.RoundTripper, upgrader spdy.Upgrader, method string, url *url.URL) (Executor, error)","file":"staging/src/k8s.io/client-go/tools/remotecommand/remotecommand.go","code":"// NewSPDYExecutorForTransports connects to the provided server using the given transport,\n// upgrades the response using the given upgrader to multiplexed bidirectional streams.\nfunc NewSPDYExecutorForTransports(transport http.RoundTripper, upgrader spdy.Upgrader, method string, url *url.URL) (Executor, error) {\n\treturn NewSPDYExecutorForProtocols(\n\t\ttransport, upgrader, method, url,\n\t\tremotecommand.StreamProtocolV4Name,\n\t\tremotecommand.StreamProtocolV3Name,\n\t\tremotecommand.StreamProtocolV2Name,\n\t\tremotecommand.StreamProtocolV1Name,\n\t)\n}","line":{"from":87,"to":97}} {"id":100029048,"name":"NewSPDYExecutorForProtocols","signature":"func NewSPDYExecutorForProtocols(transport http.RoundTripper, upgrader spdy.Upgrader, method string, url *url.URL, protocols ...string) (Executor, error)","file":"staging/src/k8s.io/client-go/tools/remotecommand/remotecommand.go","code":"// NewSPDYExecutorForProtocols connects to the provided server and upgrades the connection to\n// multiplexed bidirectional streams using only the provided protocols. Exposed for testing, most\n// callers should use NewSPDYExecutor or NewSPDYExecutorForTransports.\nfunc NewSPDYExecutorForProtocols(transport http.RoundTripper, upgrader spdy.Upgrader, method string, url *url.URL, protocols ...string) (Executor, error) {\n\treturn \u0026streamExecutor{\n\t\tupgrader: upgrader,\n\t\ttransport: transport,\n\t\tmethod: method,\n\t\turl: url,\n\t\tprotocols: protocols,\n\t}, nil\n}","line":{"from":99,"to":110}} {"id":100029049,"name":"Stream","signature":"func (e *streamExecutor) Stream(options StreamOptions) error","file":"staging/src/k8s.io/client-go/tools/remotecommand/remotecommand.go","code":"// Stream opens a protocol streamer to the server and streams until a client closes\n// the connection or the server disconnects.\nfunc (e *streamExecutor) Stream(options StreamOptions) error {\n\treturn e.StreamWithContext(context.Background(), options)\n}","line":{"from":112,"to":116}} {"id":100029050,"name":"newConnectionAndStream","signature":"func (e *streamExecutor) newConnectionAndStream(ctx context.Context, options StreamOptions) (httpstream.Connection, streamProtocolHandler, error)","file":"staging/src/k8s.io/client-go/tools/remotecommand/remotecommand.go","code":"// newConnectionAndStream creates a new SPDY connection and a stream protocol handler upon it.\nfunc (e *streamExecutor) newConnectionAndStream(ctx context.Context, options StreamOptions) (httpstream.Connection, streamProtocolHandler, error) {\n\treq, err := http.NewRequestWithContext(ctx, e.method, e.url.String(), nil)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"error creating request: %v\", err)\n\t}\n\n\tconn, protocol, err := spdy.Negotiate(\n\t\te.upgrader,\n\t\t\u0026http.Client{Transport: e.transport},\n\t\treq,\n\t\te.protocols...,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar streamer streamProtocolHandler\n\n\tswitch protocol {\n\tcase remotecommand.StreamProtocolV4Name:\n\t\tstreamer = newStreamProtocolV4(options)\n\tcase remotecommand.StreamProtocolV3Name:\n\t\tstreamer = newStreamProtocolV3(options)\n\tcase remotecommand.StreamProtocolV2Name:\n\t\tstreamer = newStreamProtocolV2(options)\n\tcase \"\":\n\t\tklog.V(4).Infof(\"The server did not negotiate a streaming protocol version. Falling back to %s\", remotecommand.StreamProtocolV1Name)\n\t\tfallthrough\n\tcase remotecommand.StreamProtocolV1Name:\n\t\tstreamer = newStreamProtocolV1(options)\n\t}\n\n\treturn conn, streamer, nil\n}","line":{"from":118,"to":152}} {"id":100029051,"name":"StreamWithContext","signature":"func (e *streamExecutor) StreamWithContext(ctx context.Context, options StreamOptions) error","file":"staging/src/k8s.io/client-go/tools/remotecommand/remotecommand.go","code":"// StreamWithContext opens a protocol streamer to the server and streams until a client closes\n// the connection or the server disconnects or the context is done.\nfunc (e *streamExecutor) StreamWithContext(ctx context.Context, options StreamOptions) error {\n\tconn, streamer, err := e.newConnectionAndStream(ctx, options)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tpanicChan := make(chan any, 1)\n\terrorChan := make(chan error, 1)\n\tgo func() {\n\t\tdefer func() {\n\t\t\tif p := recover(); p != nil {\n\t\t\t\tpanicChan \u003c- p\n\t\t\t}\n\t\t}()\n\t\terrorChan \u003c- streamer.stream(conn)\n\t}()\n\n\tselect {\n\tcase p := \u003c-panicChan:\n\t\tpanic(p)\n\tcase err := \u003c-errorChan:\n\t\treturn err\n\tcase \u003c-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n}","line":{"from":154,"to":182}} {"id":100029052,"name":"newStreamProtocolV1","signature":"func newStreamProtocolV1(options StreamOptions) streamProtocolHandler","file":"staging/src/k8s.io/client-go/tools/remotecommand/v1.go","code":"func newStreamProtocolV1(options StreamOptions) streamProtocolHandler {\n\treturn \u0026streamProtocolV1{\n\t\tStreamOptions: options,\n\t}\n}","line":{"from":44,"to":48}} {"id":100029053,"name":"stream","signature":"func (p *streamProtocolV1) stream(conn streamCreator) error","file":"staging/src/k8s.io/client-go/tools/remotecommand/v1.go","code":"func (p *streamProtocolV1) stream(conn streamCreator) error {\n\tdoneChan := make(chan struct{}, 2)\n\terrorChan := make(chan error)\n\n\tcp := func(s string, dst io.Writer, src io.Reader) {\n\t\tklog.V(6).Infof(\"Copying %s\", s)\n\t\tdefer klog.V(6).Infof(\"Done copying %s\", s)\n\t\tif _, err := io.Copy(dst, src); err != nil \u0026\u0026 err != io.EOF {\n\t\t\tklog.Errorf(\"Error copying %s: %v\", s, err)\n\t\t}\n\t\tif s == v1.StreamTypeStdout || s == v1.StreamTypeStderr {\n\t\t\tdoneChan \u003c- struct{}{}\n\t\t}\n\t}\n\n\t// set up all the streams first\n\tvar err error\n\theaders := http.Header{}\n\theaders.Set(v1.StreamType, v1.StreamTypeError)\n\tp.errorStream, err = conn.CreateStream(headers)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer p.errorStream.Reset()\n\n\t// Create all the streams first, then start the copy goroutines. The server doesn't start its copy\n\t// goroutines until it's received all of the streams. If the client creates the stdin stream and\n\t// immediately begins copying stdin data to the server, it's possible to overwhelm and wedge the\n\t// spdy frame handler in the server so that it is full of unprocessed frames. The frames aren't\n\t// getting processed because the server hasn't started its copying, and it won't do that until it\n\t// gets all the streams. By creating all the streams first, we ensure that the server is ready to\n\t// process data before the client starts sending any. See https://issues.k8s.io/16373 for more info.\n\tif p.Stdin != nil {\n\t\theaders.Set(v1.StreamType, v1.StreamTypeStdin)\n\t\tp.remoteStdin, err = conn.CreateStream(headers)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer p.remoteStdin.Reset()\n\t}\n\n\tif p.Stdout != nil {\n\t\theaders.Set(v1.StreamType, v1.StreamTypeStdout)\n\t\tp.remoteStdout, err = conn.CreateStream(headers)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer p.remoteStdout.Reset()\n\t}\n\n\tif p.Stderr != nil \u0026\u0026 !p.Tty {\n\t\theaders.Set(v1.StreamType, v1.StreamTypeStderr)\n\t\tp.remoteStderr, err = conn.CreateStream(headers)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer p.remoteStderr.Reset()\n\t}\n\n\t// now that all the streams have been created, proceed with reading \u0026 copying\n\n\t// always read from errorStream\n\tgo func() {\n\t\tmessage, err := io.ReadAll(p.errorStream)\n\t\tif err != nil \u0026\u0026 err != io.EOF {\n\t\t\terrorChan \u003c- fmt.Errorf(\"Error reading from error stream: %s\", err)\n\t\t\treturn\n\t\t}\n\t\tif len(message) \u003e 0 {\n\t\t\terrorChan \u003c- fmt.Errorf(\"Error executing remote command: %s\", message)\n\t\t\treturn\n\t\t}\n\t}()\n\n\tif p.Stdin != nil {\n\t\t// TODO this goroutine will never exit cleanly (the io.Copy never unblocks)\n\t\t// because stdin is not closed until the process exits. If we try to call\n\t\t// stdin.Close(), it returns no error but doesn't unblock the copy. It will\n\t\t// exit when the process exits, instead.\n\t\tgo cp(v1.StreamTypeStdin, p.remoteStdin, readerWrapper{p.Stdin})\n\t}\n\n\twaitCount := 0\n\tcompletedStreams := 0\n\n\tif p.Stdout != nil {\n\t\twaitCount++\n\t\tgo cp(v1.StreamTypeStdout, p.Stdout, p.remoteStdout)\n\t}\n\n\tif p.Stderr != nil \u0026\u0026 !p.Tty {\n\t\twaitCount++\n\t\tgo cp(v1.StreamTypeStderr, p.Stderr, p.remoteStderr)\n\t}\n\nLoop:\n\tfor {\n\t\tselect {\n\t\tcase \u003c-doneChan:\n\t\t\tcompletedStreams++\n\t\t\tif completedStreams == waitCount {\n\t\t\t\tbreak Loop\n\t\t\t}\n\t\tcase err := \u003c-errorChan:\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":50,"to":159}} {"id":100029054,"name":"newStreamProtocolV2","signature":"func newStreamProtocolV2(options StreamOptions) streamProtocolHandler","file":"staging/src/k8s.io/client-go/tools/remotecommand/v2.go","code":"func newStreamProtocolV2(options StreamOptions) streamProtocolHandler {\n\treturn \u0026streamProtocolV2{\n\t\tStreamOptions: options,\n\t}\n}","line":{"from":44,"to":48}} {"id":100029055,"name":"createStreams","signature":"func (p *streamProtocolV2) createStreams(conn streamCreator) error","file":"staging/src/k8s.io/client-go/tools/remotecommand/v2.go","code":"func (p *streamProtocolV2) createStreams(conn streamCreator) error {\n\tvar err error\n\theaders := http.Header{}\n\n\t// set up error stream\n\theaders.Set(v1.StreamType, v1.StreamTypeError)\n\tp.errorStream, err = conn.CreateStream(headers)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set up stdin stream\n\tif p.Stdin != nil {\n\t\theaders.Set(v1.StreamType, v1.StreamTypeStdin)\n\t\tp.remoteStdin, err = conn.CreateStream(headers)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// set up stdout stream\n\tif p.Stdout != nil {\n\t\theaders.Set(v1.StreamType, v1.StreamTypeStdout)\n\t\tp.remoteStdout, err = conn.CreateStream(headers)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// set up stderr stream\n\tif p.Stderr != nil \u0026\u0026 !p.Tty {\n\t\theaders.Set(v1.StreamType, v1.StreamTypeStderr)\n\t\tp.remoteStderr, err = conn.CreateStream(headers)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":50,"to":88}} {"id":100029056,"name":"copyStdin","signature":"func (p *streamProtocolV2) copyStdin()","file":"staging/src/k8s.io/client-go/tools/remotecommand/v2.go","code":"func (p *streamProtocolV2) copyStdin() {\n\tif p.Stdin != nil {\n\t\tvar once sync.Once\n\n\t\t// copy from client's stdin to container's stdin\n\t\tgo func() {\n\t\t\tdefer runtime.HandleCrash()\n\n\t\t\t// if p.stdin is noninteractive, p.g. `echo abc | kubectl exec -i \u003cpod\u003e -- cat`, make sure\n\t\t\t// we close remoteStdin as soon as the copy from p.stdin to remoteStdin finishes. Otherwise\n\t\t\t// the executed command will remain running.\n\t\t\tdefer once.Do(func() { p.remoteStdin.Close() })\n\n\t\t\tif _, err := io.Copy(p.remoteStdin, readerWrapper{p.Stdin}); err != nil {\n\t\t\t\truntime.HandleError(err)\n\t\t\t}\n\t\t}()\n\n\t\t// read from remoteStdin until the stream is closed. this is essential to\n\t\t// be able to exit interactive sessions cleanly and not leak goroutines or\n\t\t// hang the client's terminal.\n\t\t//\n\t\t// TODO we aren't using go-dockerclient any more; revisit this to determine if it's still\n\t\t// required by engine-api.\n\t\t//\n\t\t// go-dockerclient's current hijack implementation\n\t\t// (https://github.com/fsouza/go-dockerclient/blob/89f3d56d93788dfe85f864a44f85d9738fca0670/client.go#L564)\n\t\t// waits for all three streams (stdin/stdout/stderr) to finish copying\n\t\t// before returning. When hijack finishes copying stdout/stderr, it calls\n\t\t// Close() on its side of remoteStdin, which allows this copy to complete.\n\t\t// When that happens, we must Close() on our side of remoteStdin, to\n\t\t// allow the copy in hijack to complete, and hijack to return.\n\t\tgo func() {\n\t\t\tdefer runtime.HandleCrash()\n\t\t\tdefer once.Do(func() { p.remoteStdin.Close() })\n\n\t\t\t// this \"copy\" doesn't actually read anything - it's just here to wait for\n\t\t\t// the server to close remoteStdin.\n\t\t\tif _, err := io.Copy(io.Discard, p.remoteStdin); err != nil {\n\t\t\t\truntime.HandleError(err)\n\t\t\t}\n\t\t}()\n\t}\n}","line":{"from":90,"to":133}} {"id":100029057,"name":"copyStdout","signature":"func (p *streamProtocolV2) copyStdout(wg *sync.WaitGroup)","file":"staging/src/k8s.io/client-go/tools/remotecommand/v2.go","code":"func (p *streamProtocolV2) copyStdout(wg *sync.WaitGroup) {\n\tif p.Stdout == nil {\n\t\treturn\n\t}\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer runtime.HandleCrash()\n\t\tdefer wg.Done()\n\t\t// make sure, packet in queue can be consumed.\n\t\t// block in queue may lead to deadlock in conn.server\n\t\t// issue: https://github.com/kubernetes/kubernetes/issues/96339\n\t\tdefer io.Copy(io.Discard, p.remoteStdout)\n\n\t\tif _, err := io.Copy(p.Stdout, p.remoteStdout); err != nil {\n\t\t\truntime.HandleError(err)\n\t\t}\n\t}()\n}","line":{"from":135,"to":153}} {"id":100029058,"name":"copyStderr","signature":"func (p *streamProtocolV2) copyStderr(wg *sync.WaitGroup)","file":"staging/src/k8s.io/client-go/tools/remotecommand/v2.go","code":"func (p *streamProtocolV2) copyStderr(wg *sync.WaitGroup) {\n\tif p.Stderr == nil || p.Tty {\n\t\treturn\n\t}\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer runtime.HandleCrash()\n\t\tdefer wg.Done()\n\t\tdefer io.Copy(io.Discard, p.remoteStderr)\n\n\t\tif _, err := io.Copy(p.Stderr, p.remoteStderr); err != nil {\n\t\t\truntime.HandleError(err)\n\t\t}\n\t}()\n}","line":{"from":155,"to":170}} {"id":100029059,"name":"stream","signature":"func (p *streamProtocolV2) stream(conn streamCreator) error","file":"staging/src/k8s.io/client-go/tools/remotecommand/v2.go","code":"func (p *streamProtocolV2) stream(conn streamCreator) error {\n\tif err := p.createStreams(conn); err != nil {\n\t\treturn err\n\t}\n\n\t// now that all the streams have been created, proceed with reading \u0026 copying\n\n\terrorChan := watchErrorStream(p.errorStream, \u0026errorDecoderV2{})\n\n\tp.copyStdin()\n\n\tvar wg sync.WaitGroup\n\tp.copyStdout(\u0026wg)\n\tp.copyStderr(\u0026wg)\n\n\t// we're waiting for stdout/stderr to finish copying\n\twg.Wait()\n\n\t// waits for errorStream to finish reading with an error or nil\n\treturn \u003c-errorChan\n}","line":{"from":172,"to":192}} {"id":100029060,"name":"decode","signature":"func (d *errorDecoderV2) decode(message []byte) error","file":"staging/src/k8s.io/client-go/tools/remotecommand/v2.go","code":"func (d *errorDecoderV2) decode(message []byte) error {\n\treturn fmt.Errorf(\"error executing remote command: %s\", message)\n}","line":{"from":197,"to":199}} {"id":100029061,"name":"newStreamProtocolV3","signature":"func newStreamProtocolV3(options StreamOptions) streamProtocolHandler","file":"staging/src/k8s.io/client-go/tools/remotecommand/v3.go","code":"func newStreamProtocolV3(options StreamOptions) streamProtocolHandler {\n\treturn \u0026streamProtocolV3{\n\t\tstreamProtocolV2: newStreamProtocolV2(options).(*streamProtocolV2),\n\t}\n}","line":{"from":39,"to":43}} {"id":100029062,"name":"createStreams","signature":"func (p *streamProtocolV3) createStreams(conn streamCreator) error","file":"staging/src/k8s.io/client-go/tools/remotecommand/v3.go","code":"func (p *streamProtocolV3) createStreams(conn streamCreator) error {\n\t// set up the streams from v2\n\tif err := p.streamProtocolV2.createStreams(conn); err != nil {\n\t\treturn err\n\t}\n\n\t// set up resize stream\n\tif p.Tty {\n\t\theaders := http.Header{}\n\t\theaders.Set(v1.StreamType, v1.StreamTypeResize)\n\t\tvar err error\n\t\tp.resizeStream, err = conn.CreateStream(headers)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":45,"to":63}} {"id":100029063,"name":"handleResizes","signature":"func (p *streamProtocolV3) handleResizes()","file":"staging/src/k8s.io/client-go/tools/remotecommand/v3.go","code":"func (p *streamProtocolV3) handleResizes() {\n\tif p.resizeStream == nil || p.TerminalSizeQueue == nil {\n\t\treturn\n\t}\n\tgo func() {\n\t\tdefer runtime.HandleCrash()\n\n\t\tencoder := json.NewEncoder(p.resizeStream)\n\t\tfor {\n\t\t\tsize := p.TerminalSizeQueue.Next()\n\t\t\tif size == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err := encoder.Encode(\u0026size); err != nil {\n\t\t\t\truntime.HandleError(err)\n\t\t\t}\n\t\t}\n\t}()\n}","line":{"from":65,"to":83}} {"id":100029064,"name":"stream","signature":"func (p *streamProtocolV3) stream(conn streamCreator) error","file":"staging/src/k8s.io/client-go/tools/remotecommand/v3.go","code":"func (p *streamProtocolV3) stream(conn streamCreator) error {\n\tif err := p.createStreams(conn); err != nil {\n\t\treturn err\n\t}\n\n\t// now that all the streams have been created, proceed with reading \u0026 copying\n\n\terrorChan := watchErrorStream(p.errorStream, \u0026errorDecoderV3{})\n\n\tp.handleResizes()\n\n\tp.copyStdin()\n\n\tvar wg sync.WaitGroup\n\tp.copyStdout(\u0026wg)\n\tp.copyStderr(\u0026wg)\n\n\t// we're waiting for stdout/stderr to finish copying\n\twg.Wait()\n\n\t// waits for errorStream to finish reading with an error or nil\n\treturn \u003c-errorChan\n}","line":{"from":85,"to":107}} {"id":100029065,"name":"newStreamProtocolV4","signature":"func newStreamProtocolV4(options StreamOptions) streamProtocolHandler","file":"staging/src/k8s.io/client-go/tools/remotecommand/v4.go","code":"func newStreamProtocolV4(options StreamOptions) streamProtocolHandler {\n\treturn \u0026streamProtocolV4{\n\t\tstreamProtocolV3: newStreamProtocolV3(options).(*streamProtocolV3),\n\t}\n}","line":{"from":40,"to":44}} {"id":100029066,"name":"createStreams","signature":"func (p *streamProtocolV4) createStreams(conn streamCreator) error","file":"staging/src/k8s.io/client-go/tools/remotecommand/v4.go","code":"func (p *streamProtocolV4) createStreams(conn streamCreator) error {\n\treturn p.streamProtocolV3.createStreams(conn)\n}","line":{"from":46,"to":48}} {"id":100029067,"name":"handleResizes","signature":"func (p *streamProtocolV4) handleResizes()","file":"staging/src/k8s.io/client-go/tools/remotecommand/v4.go","code":"func (p *streamProtocolV4) handleResizes() {\n\tp.streamProtocolV3.handleResizes()\n}","line":{"from":50,"to":52}} {"id":100029068,"name":"stream","signature":"func (p *streamProtocolV4) stream(conn streamCreator) error","file":"staging/src/k8s.io/client-go/tools/remotecommand/v4.go","code":"func (p *streamProtocolV4) stream(conn streamCreator) error {\n\tif err := p.createStreams(conn); err != nil {\n\t\treturn err\n\t}\n\n\t// now that all the streams have been created, proceed with reading \u0026 copying\n\n\terrorChan := watchErrorStream(p.errorStream, \u0026errorDecoderV4{})\n\n\tp.handleResizes()\n\n\tp.copyStdin()\n\n\tvar wg sync.WaitGroup\n\tp.copyStdout(\u0026wg)\n\tp.copyStderr(\u0026wg)\n\n\t// we're waiting for stdout/stderr to finish copying\n\twg.Wait()\n\n\t// waits for errorStream to finish reading with an error or nil\n\treturn \u003c-errorChan\n}","line":{"from":54,"to":76}} {"id":100029069,"name":"decode","signature":"func (d *errorDecoderV4) decode(message []byte) error","file":"staging/src/k8s.io/client-go/tools/remotecommand/v4.go","code":"func (d *errorDecoderV4) decode(message []byte) error {\n\tstatus := metav1.Status{}\n\terr := json.Unmarshal(message, \u0026status)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error stream protocol error: %v in %q\", err, string(message))\n\t}\n\tswitch status.Status {\n\tcase metav1.StatusSuccess:\n\t\treturn nil\n\tcase metav1.StatusFailure:\n\t\tif status.Reason == remotecommand.NonZeroExitCodeReason {\n\t\t\tif status.Details == nil {\n\t\t\t\treturn errors.New(\"error stream protocol error: details must be set\")\n\t\t\t}\n\t\t\tfor i := range status.Details.Causes {\n\t\t\t\tc := \u0026status.Details.Causes[i]\n\t\t\t\tif c.Type != remotecommand.ExitCodeCauseType {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\trc, err := strconv.ParseUint(c.Message, 10, 8)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"error stream protocol error: invalid exit code value %q\", c.Message)\n\t\t\t\t}\n\t\t\t\treturn exec.CodeExitError{\n\t\t\t\t\tErr: fmt.Errorf(\"command terminated with exit code %d\", rc),\n\t\t\t\t\tCode: int(rc),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn fmt.Errorf(\"error stream protocol error: no %s cause given\", remotecommand.ExitCodeCauseType)\n\t\t}\n\tdefault:\n\t\treturn errors.New(\"error stream protocol error: unknown error\")\n\t}\n\n\treturn fmt.Errorf(status.Message)\n}","line":{"from":82,"to":119}} {"id":100029070,"name":"newEventProcessor","signature":"func newEventProcessor(out chan\u003c- watch.Event) *eventProcessor","file":"staging/src/k8s.io/client-go/tools/watch/informerwatcher.go","code":"func newEventProcessor(out chan\u003c- watch.Event) *eventProcessor {\n\treturn \u0026eventProcessor{\n\t\tout: out,\n\t\tcond: sync.NewCond(\u0026sync.Mutex{}),\n\t\tdone: make(chan struct{}),\n\t}\n}","line":{"from":27,"to":33}} {"id":100029071,"name":"run","signature":"func (e *eventProcessor) run()","file":"staging/src/k8s.io/client-go/tools/watch/informerwatcher.go","code":"func (e *eventProcessor) run() {\n\tfor {\n\t\tbatch := e.takeBatch()\n\t\te.writeBatch(batch)\n\t\tif e.stopped() {\n\t\t\treturn\n\t\t}\n\t}\n}","line":{"from":49,"to":57}} {"id":100029072,"name":"takeBatch","signature":"func (e *eventProcessor) takeBatch() []watch.Event","file":"staging/src/k8s.io/client-go/tools/watch/informerwatcher.go","code":"func (e *eventProcessor) takeBatch() []watch.Event {\n\te.cond.L.Lock()\n\tdefer e.cond.L.Unlock()\n\n\tfor len(e.buff) == 0 \u0026\u0026 !e.stopped() {\n\t\te.cond.Wait()\n\t}\n\n\tbatch := e.buff\n\te.buff = nil\n\treturn batch\n}","line":{"from":59,"to":70}} {"id":100029073,"name":"writeBatch","signature":"func (e *eventProcessor) writeBatch(events []watch.Event)","file":"staging/src/k8s.io/client-go/tools/watch/informerwatcher.go","code":"func (e *eventProcessor) writeBatch(events []watch.Event) {\n\tfor _, event := range events {\n\t\tselect {\n\t\tcase e.out \u003c- event:\n\t\tcase \u003c-e.done:\n\t\t\treturn\n\t\t}\n\t}\n}","line":{"from":72,"to":80}} {"id":100029074,"name":"push","signature":"func (e *eventProcessor) push(event watch.Event)","file":"staging/src/k8s.io/client-go/tools/watch/informerwatcher.go","code":"func (e *eventProcessor) push(event watch.Event) {\n\te.cond.L.Lock()\n\tdefer e.cond.L.Unlock()\n\tdefer e.cond.Signal()\n\te.buff = append(e.buff, event)\n}","line":{"from":82,"to":87}} {"id":100029075,"name":"stopped","signature":"func (e *eventProcessor) stopped() bool","file":"staging/src/k8s.io/client-go/tools/watch/informerwatcher.go","code":"func (e *eventProcessor) stopped() bool {\n\tselect {\n\tcase \u003c-e.done:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":89,"to":96}} {"id":100029076,"name":"stop","signature":"func (e *eventProcessor) stop()","file":"staging/src/k8s.io/client-go/tools/watch/informerwatcher.go","code":"func (e *eventProcessor) stop() {\n\tclose(e.done)\n\te.cond.Signal()\n}","line":{"from":98,"to":101}} {"id":100029077,"name":"NewIndexerInformerWatcher","signature":"func NewIndexerInformerWatcher(lw cache.ListerWatcher, objType runtime.Object) (cache.Indexer, cache.Controller, watch.Interface, \u003c-chan struct{})","file":"staging/src/k8s.io/client-go/tools/watch/informerwatcher.go","code":"// NewIndexerInformerWatcher will create an IndexerInformer and wrap it into watch.Interface\n// so you can use it anywhere where you'd have used a regular Watcher returned from Watch method.\n// it also returns a channel you can use to wait for the informers to fully shutdown.\nfunc NewIndexerInformerWatcher(lw cache.ListerWatcher, objType runtime.Object) (cache.Indexer, cache.Controller, watch.Interface, \u003c-chan struct{}) {\n\tch := make(chan watch.Event)\n\tw := watch.NewProxyWatcher(ch)\n\te := newEventProcessor(ch)\n\n\tindexer, informer := cache.NewIndexerInformer(lw, objType, 0, cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\te.push(watch.Event{\n\t\t\t\tType: watch.Added,\n\t\t\t\tObject: obj.(runtime.Object),\n\t\t\t})\n\t\t},\n\t\tUpdateFunc: func(old, new interface{}) {\n\t\t\te.push(watch.Event{\n\t\t\t\tType: watch.Modified,\n\t\t\t\tObject: new.(runtime.Object),\n\t\t\t})\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tstaleObj, stale := obj.(cache.DeletedFinalStateUnknown)\n\t\t\tif stale {\n\t\t\t\t// We have no means of passing the additional information down using\n\t\t\t\t// watch API based on watch.Event but the caller can filter such\n\t\t\t\t// objects by checking if metadata.deletionTimestamp is set\n\t\t\t\tobj = staleObj.Obj\n\t\t\t}\n\n\t\t\te.push(watch.Event{\n\t\t\t\tType: watch.Deleted,\n\t\t\t\tObject: obj.(runtime.Object),\n\t\t\t})\n\t\t},\n\t}, cache.Indexers{})\n\n\tgo e.run()\n\n\tdoneCh := make(chan struct{})\n\tgo func() {\n\t\tdefer close(doneCh)\n\t\tdefer e.stop()\n\t\tinformer.Run(w.StopChan())\n\t}()\n\n\treturn indexer, informer, w, doneCh\n}","line":{"from":103,"to":150}} {"id":100029078,"name":"NewRetryWatcher","signature":"func NewRetryWatcher(initialResourceVersion string, watcherClient cache.Watcher) (*RetryWatcher, error)","file":"staging/src/k8s.io/client-go/tools/watch/retrywatcher.go","code":"// NewRetryWatcher creates a new RetryWatcher.\n// It will make sure that watches gets restarted in case of recoverable errors.\n// The initialResourceVersion will be given to watch method when first called.\nfunc NewRetryWatcher(initialResourceVersion string, watcherClient cache.Watcher) (*RetryWatcher, error) {\n\treturn newRetryWatcher(initialResourceVersion, watcherClient, 1*time.Second)\n}","line":{"from":59,"to":64}} {"id":100029079,"name":"newRetryWatcher","signature":"func newRetryWatcher(initialResourceVersion string, watcherClient cache.Watcher, minRestartDelay time.Duration) (*RetryWatcher, error)","file":"staging/src/k8s.io/client-go/tools/watch/retrywatcher.go","code":"func newRetryWatcher(initialResourceVersion string, watcherClient cache.Watcher, minRestartDelay time.Duration) (*RetryWatcher, error) {\n\tswitch initialResourceVersion {\n\tcase \"\", \"0\":\n\t\t// TODO: revisit this if we ever get WATCH v2 where it means start \"now\"\n\t\t// without doing the synthetic list of objects at the beginning (see #74022)\n\t\treturn nil, fmt.Errorf(\"initial RV %q is not supported due to issues with underlying WATCH\", initialResourceVersion)\n\tdefault:\n\t\tbreak\n\t}\n\n\trw := \u0026RetryWatcher{\n\t\tlastResourceVersion: initialResourceVersion,\n\t\twatcherClient: watcherClient,\n\t\tstopChan: make(chan struct{}),\n\t\tdoneChan: make(chan struct{}),\n\t\tresultChan: make(chan watch.Event, 0),\n\t\tminRestartDelay: minRestartDelay,\n\t}\n\n\tgo rw.receive()\n\treturn rw, nil\n}","line":{"from":66,"to":87}} {"id":100029080,"name":"send","signature":"func (rw *RetryWatcher) send(event watch.Event) bool","file":"staging/src/k8s.io/client-go/tools/watch/retrywatcher.go","code":"func (rw *RetryWatcher) send(event watch.Event) bool {\n\t// Writing to an unbuffered channel is blocking operation\n\t// and we need to check if stop wasn't requested while doing so.\n\tselect {\n\tcase rw.resultChan \u003c- event:\n\t\treturn true\n\tcase \u003c-rw.stopChan:\n\t\treturn false\n\t}\n}","line":{"from":89,"to":98}} {"id":100029081,"name":"doReceive","signature":"func (rw *RetryWatcher) doReceive() (bool, time.Duration)","file":"staging/src/k8s.io/client-go/tools/watch/retrywatcher.go","code":"// doReceive returns true when it is done, false otherwise.\n// If it is not done the second return value holds the time to wait before calling it again.\nfunc (rw *RetryWatcher) doReceive() (bool, time.Duration) {\n\twatcher, err := rw.watcherClient.Watch(metav1.ListOptions{\n\t\tResourceVersion: rw.lastResourceVersion,\n\t\tAllowWatchBookmarks: true,\n\t})\n\t// We are very unlikely to hit EOF here since we are just establishing the call,\n\t// but it may happen that the apiserver is just shutting down (e.g. being restarted)\n\t// This is consistent with how it is handled for informers\n\tswitch err {\n\tcase nil:\n\t\tbreak\n\n\tcase io.EOF:\n\t\t// watch closed normally\n\t\treturn false, 0\n\n\tcase io.ErrUnexpectedEOF:\n\t\tklog.V(1).InfoS(\"Watch closed with unexpected EOF\", \"err\", err)\n\t\treturn false, 0\n\n\tdefault:\n\t\tmsg := \"Watch failed\"\n\t\tif net.IsProbableEOF(err) || net.IsTimeout(err) {\n\t\t\tklog.V(5).InfoS(msg, \"err\", err)\n\t\t\t// Retry\n\t\t\treturn false, 0\n\t\t}\n\n\t\tklog.ErrorS(err, msg)\n\t\t// Retry\n\t\treturn false, 0\n\t}\n\n\tif watcher == nil {\n\t\tklog.ErrorS(nil, \"Watch returned nil watcher\")\n\t\t// Retry\n\t\treturn false, 0\n\t}\n\n\tch := watcher.ResultChan()\n\tdefer watcher.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase \u003c-rw.stopChan:\n\t\t\tklog.V(4).InfoS(\"Stopping RetryWatcher.\")\n\t\t\treturn true, 0\n\t\tcase event, ok := \u003c-ch:\n\t\t\tif !ok {\n\t\t\t\tklog.V(4).InfoS(\"Failed to get event! Re-creating the watcher.\", \"resourceVersion\", rw.lastResourceVersion)\n\t\t\t\treturn false, 0\n\t\t\t}\n\n\t\t\t// We need to inspect the event and get ResourceVersion out of it\n\t\t\tswitch event.Type {\n\t\t\tcase watch.Added, watch.Modified, watch.Deleted, watch.Bookmark:\n\t\t\t\tmetaObject, ok := event.Object.(resourceVersionGetter)\n\t\t\t\tif !ok {\n\t\t\t\t\t_ = rw.send(watch.Event{\n\t\t\t\t\t\tType: watch.Error,\n\t\t\t\t\t\tObject: \u0026apierrors.NewInternalError(errors.New(\"retryWatcher: doesn't support resourceVersion\")).ErrStatus,\n\t\t\t\t\t})\n\t\t\t\t\t// We have to abort here because this might cause lastResourceVersion inconsistency by skipping a potential RV with valid data!\n\t\t\t\t\treturn true, 0\n\t\t\t\t}\n\n\t\t\t\tresourceVersion := metaObject.GetResourceVersion()\n\t\t\t\tif resourceVersion == \"\" {\n\t\t\t\t\t_ = rw.send(watch.Event{\n\t\t\t\t\t\tType: watch.Error,\n\t\t\t\t\t\tObject: \u0026apierrors.NewInternalError(fmt.Errorf(\"retryWatcher: object %#v doesn't support resourceVersion\", event.Object)).ErrStatus,\n\t\t\t\t\t})\n\t\t\t\t\t// We have to abort here because this might cause lastResourceVersion inconsistency by skipping a potential RV with valid data!\n\t\t\t\t\treturn true, 0\n\t\t\t\t}\n\n\t\t\t\t// All is fine; send the non-bookmark events and update resource version.\n\t\t\t\tif event.Type != watch.Bookmark {\n\t\t\t\t\tok = rw.send(event)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn true, 0\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\trw.lastResourceVersion = resourceVersion\n\n\t\t\t\tcontinue\n\n\t\t\tcase watch.Error:\n\t\t\t\t// This round trip allows us to handle unstructured status\n\t\t\t\terrObject := apierrors.FromObject(event.Object)\n\t\t\t\tstatusErr, ok := errObject.(*apierrors.StatusError)\n\t\t\t\tif !ok {\n\t\t\t\t\tklog.Error(spew.Sprintf(\"Received an error which is not *metav1.Status but %#+v\", event.Object))\n\t\t\t\t\t// Retry unknown errors\n\t\t\t\t\treturn false, 0\n\t\t\t\t}\n\n\t\t\t\tstatus := statusErr.ErrStatus\n\n\t\t\t\tstatusDelay := time.Duration(0)\n\t\t\t\tif status.Details != nil {\n\t\t\t\t\tstatusDelay = time.Duration(status.Details.RetryAfterSeconds) * time.Second\n\t\t\t\t}\n\n\t\t\t\tswitch status.Code {\n\t\t\t\tcase http.StatusGone:\n\t\t\t\t\t// Never retry RV too old errors\n\t\t\t\t\t_ = rw.send(event)\n\t\t\t\t\treturn true, 0\n\n\t\t\t\tcase http.StatusGatewayTimeout, http.StatusInternalServerError:\n\t\t\t\t\t// Retry\n\t\t\t\t\treturn false, statusDelay\n\n\t\t\t\tdefault:\n\t\t\t\t\t// We retry by default. RetryWatcher is meant to proceed unless it is certain\n\t\t\t\t\t// that it can't. If we are not certain, we proceed with retry and leave it\n\t\t\t\t\t// up to the user to timeout if needed.\n\n\t\t\t\t\t// Log here so we have a record of hitting the unexpected error\n\t\t\t\t\t// and we can whitelist some error codes if we missed any that are expected.\n\t\t\t\t\tklog.V(5).Info(spew.Sprintf(\"Retrying after unexpected error: %#+v\", event.Object))\n\n\t\t\t\t\t// Retry\n\t\t\t\t\treturn false, statusDelay\n\t\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\tklog.Errorf(\"Failed to recognize Event type %q\", event.Type)\n\t\t\t\t_ = rw.send(watch.Event{\n\t\t\t\t\tType: watch.Error,\n\t\t\t\t\tObject: \u0026apierrors.NewInternalError(fmt.Errorf(\"retryWatcher failed to recognize Event type %q\", event.Type)).ErrStatus,\n\t\t\t\t})\n\t\t\t\t// We are unable to restart the watch and have to stop the loop or this might cause lastResourceVersion inconsistency by skipping a potential RV with valid data!\n\t\t\t\treturn true, 0\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":100,"to":240}} {"id":100029082,"name":"receive","signature":"func (rw *RetryWatcher) receive()","file":"staging/src/k8s.io/client-go/tools/watch/retrywatcher.go","code":"// receive reads the result from a watcher, restarting it if necessary.\nfunc (rw *RetryWatcher) receive() {\n\tdefer close(rw.doneChan)\n\tdefer close(rw.resultChan)\n\n\tklog.V(4).Info(\"Starting RetryWatcher.\")\n\tdefer klog.V(4).Info(\"Stopping RetryWatcher.\")\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tgo func() {\n\t\tselect {\n\t\tcase \u003c-rw.stopChan:\n\t\t\tcancel()\n\t\t\treturn\n\t\tcase \u003c-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}()\n\n\t// We use non sliding until so we don't introduce delays on happy path when WATCH call\n\t// timeouts or gets closed and we need to reestablish it while also avoiding hot loops.\n\twait.NonSlidingUntilWithContext(ctx, func(ctx context.Context) {\n\t\tdone, retryAfter := rw.doReceive()\n\t\tif done {\n\t\t\tcancel()\n\t\t\treturn\n\t\t}\n\n\t\ttimer := time.NewTimer(retryAfter)\n\t\tselect {\n\t\tcase \u003c-ctx.Done():\n\t\t\ttimer.Stop()\n\t\t\treturn\n\t\tcase \u003c-timer.C:\n\t\t}\n\n\t\tklog.V(4).Infof(\"Restarting RetryWatcher at RV=%q\", rw.lastResourceVersion)\n\t}, rw.minRestartDelay)\n}","line":{"from":242,"to":281}} {"id":100029083,"name":"ResultChan","signature":"func (rw *RetryWatcher) ResultChan() \u003c-chan watch.Event","file":"staging/src/k8s.io/client-go/tools/watch/retrywatcher.go","code":"// ResultChan implements Interface.\nfunc (rw *RetryWatcher) ResultChan() \u003c-chan watch.Event {\n\treturn rw.resultChan\n}","line":{"from":283,"to":286}} {"id":100029084,"name":"Stop","signature":"func (rw *RetryWatcher) Stop()","file":"staging/src/k8s.io/client-go/tools/watch/retrywatcher.go","code":"// Stop implements Interface.\nfunc (rw *RetryWatcher) Stop() {\n\tclose(rw.stopChan)\n}","line":{"from":288,"to":291}} {"id":100029085,"name":"Done","signature":"func (rw *RetryWatcher) Done() \u003c-chan struct{}","file":"staging/src/k8s.io/client-go/tools/watch/retrywatcher.go","code":"// Done allows the caller to be notified when Retry watcher stops.\nfunc (rw *RetryWatcher) Done() \u003c-chan struct{} {\n\treturn rw.doneChan\n}","line":{"from":293,"to":296}} {"id":100029086,"name":"UntilWithoutRetry","signature":"func UntilWithoutRetry(ctx context.Context, watcher watch.Interface, conditions ...ConditionFunc) (*watch.Event, error)","file":"staging/src/k8s.io/client-go/tools/watch/until.go","code":"// UntilWithoutRetry reads items from the watch until each provided condition succeeds, and then returns the last watch\n// encountered. The first condition that returns an error terminates the watch (and the event is also returned).\n// If no event has been received, the returned event will be nil.\n// Conditions are satisfied sequentially so as to provide a useful primitive for higher level composition.\n// Waits until context deadline or until context is canceled.\n//\n// Warning: Unless you have a very specific use case (probably a special Watcher) don't use this function!!!\n// Warning: This will fail e.g. on API timeouts and/or 'too old resource version' error.\n// Warning: You are most probably looking for a function *Until* or *UntilWithSync* below,\n// Warning: solving such issues.\n// TODO: Consider making this function private to prevent misuse when the other occurrences in our codebase are gone.\nfunc UntilWithoutRetry(ctx context.Context, watcher watch.Interface, conditions ...ConditionFunc) (*watch.Event, error) {\n\tch := watcher.ResultChan()\n\tdefer watcher.Stop()\n\tvar lastEvent *watch.Event\n\tfor _, condition := range conditions {\n\t\t// check the next condition against the previous event and short circuit waiting for the next watch\n\t\tif lastEvent != nil {\n\t\t\tdone, err := condition(*lastEvent)\n\t\t\tif err != nil {\n\t\t\t\treturn lastEvent, err\n\t\t\t}\n\t\t\tif done {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\tConditionSucceeded:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event, ok := \u003c-ch:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn lastEvent, ErrWatchClosed\n\t\t\t\t}\n\t\t\t\tlastEvent = \u0026event\n\n\t\t\t\tdone, err := condition(event)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn lastEvent, err\n\t\t\t\t}\n\t\t\t\tif done {\n\t\t\t\t\tbreak ConditionSucceeded\n\t\t\t\t}\n\n\t\t\tcase \u003c-ctx.Done():\n\t\t\t\treturn lastEvent, wait.ErrWaitTimeout\n\t\t\t}\n\t\t}\n\t}\n\treturn lastEvent, nil\n}","line":{"from":45,"to":94}} {"id":100029087,"name":"Until","signature":"func Until(ctx context.Context, initialResourceVersion string, watcherClient cache.Watcher, conditions ...ConditionFunc) (*watch.Event, error)","file":"staging/src/k8s.io/client-go/tools/watch/until.go","code":"// Until wraps the watcherClient's watch function with RetryWatcher making sure that watcher gets restarted in case of errors.\n// The initialResourceVersion will be given to watch method when first called. It shall not be \"\" or \"0\"\n// given the underlying WATCH call issues (#74022).\n// Remaining behaviour is identical to function UntilWithoutRetry. (See above.)\n// Until can deal with API timeouts and lost connections.\n// It guarantees you to see all events and in the order they happened.\n// Due to this guarantee there is no way it can deal with 'Resource version too old error'. It will fail in this case.\n// (See `UntilWithSync` if you'd prefer to recover from all the errors including RV too old by re-listing\n// those items. In normal code you should care about being level driven so you'd not care about not seeing all the edges.)\n//\n// The most frequent usage for Until would be a test where you want to verify exact order of events (\"edges\").\nfunc Until(ctx context.Context, initialResourceVersion string, watcherClient cache.Watcher, conditions ...ConditionFunc) (*watch.Event, error) {\n\tw, err := NewRetryWatcher(initialResourceVersion, watcherClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn UntilWithoutRetry(ctx, w, conditions...)\n}","line":{"from":96,"to":114}} {"id":100029088,"name":"UntilWithSync","signature":"func UntilWithSync(ctx context.Context, lw cache.ListerWatcher, objType runtime.Object, precondition PreconditionFunc, conditions ...ConditionFunc) (*watch.Event, error)","file":"staging/src/k8s.io/client-go/tools/watch/until.go","code":"// UntilWithSync creates an informer from lw, optionally checks precondition when the store is synced,\n// and watches the output until each provided condition succeeds, in a way that is identical\n// to function UntilWithoutRetry. (See above.)\n// UntilWithSync can deal with all errors like API timeout, lost connections and 'Resource version too old'.\n// It is the only function that can recover from 'Resource version too old', Until and UntilWithoutRetry will\n// just fail in that case. On the other hand it can't provide you with guarantees as strong as using simple\n// Watch method with Until. It can skip some intermediate events in case of watch function failing but it will\n// re-list to recover and you always get an event, if there has been a change, after recovery.\n// Also with the current implementation based on DeltaFIFO, order of the events you receive is guaranteed only for\n// particular object, not between more of them even it's the same resource.\n// The most frequent usage would be a command that needs to watch the \"state of the world\" and should't fail, like:\n// waiting for object reaching a state, \"small\" controllers, ...\nfunc UntilWithSync(ctx context.Context, lw cache.ListerWatcher, objType runtime.Object, precondition PreconditionFunc, conditions ...ConditionFunc) (*watch.Event, error) {\n\tindexer, informer, watcher, done := NewIndexerInformerWatcher(lw, objType)\n\t// We need to wait for the internal informers to fully stop so it's easier to reason about\n\t// and it works with non-thread safe clients.\n\tdefer func() { \u003c-done }()\n\t// Proxy watcher can be stopped multiple times so it's fine to use defer here to cover alternative branches and\n\t// let UntilWithoutRetry to stop it\n\tdefer watcher.Stop()\n\n\tif precondition != nil {\n\t\tif !cache.WaitForCacheSync(ctx.Done(), informer.HasSynced) {\n\t\t\treturn nil, fmt.Errorf(\"UntilWithSync: unable to sync caches: %w\", ctx.Err())\n\t\t}\n\n\t\tdone, err := precondition(indexer)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif done {\n\t\t\treturn nil, nil\n\t\t}\n\t}\n\n\treturn UntilWithoutRetry(ctx, watcher, conditions...)\n}","line":{"from":116,"to":153}} {"id":100029089,"name":"ContextWithOptionalTimeout","signature":"func ContextWithOptionalTimeout(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc)","file":"staging/src/k8s.io/client-go/tools/watch/until.go","code":"// ContextWithOptionalTimeout wraps context.WithTimeout and handles infinite timeouts expressed as 0 duration.\nfunc ContextWithOptionalTimeout(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc) {\n\tif timeout \u003c 0 {\n\t\t// This should be handled in validation\n\t\tklog.Errorf(\"Timeout for context shall not be negative!\")\n\t\ttimeout = 0\n\t}\n\n\tif timeout == 0 {\n\t\treturn context.WithCancel(parent)\n\t}\n\n\treturn context.WithTimeout(parent, timeout)\n}","line":{"from":155,"to":168}} {"id":100029090,"name":"String","signature":"func (t tlsCacheKey) String() string","file":"staging/src/k8s.io/client-go/transport/cache.go","code":"func (t tlsCacheKey) String() string {\n\tkeyText := \"\u003cnone\u003e\"\n\tif len(t.keyData) \u003e 0 {\n\t\tkeyText = \"\u003credacted\u003e\"\n\t}\n\treturn fmt.Sprintf(\"insecure:%v, caData:%#v, certData:%#v, keyData:%s, serverName:%s, disableCompression:%t, getCert:%p, dial:%p\",\n\t\tt.insecure, t.caData, t.certData, keyText, t.serverName, t.disableCompression, t.getCert, t.dial)\n}","line":{"from":64,"to":71}} {"id":100029091,"name":"get","signature":"func (c *tlsTransportCache) get(config *Config) (http.RoundTripper, error)","file":"staging/src/k8s.io/client-go/transport/cache.go","code":"func (c *tlsTransportCache) get(config *Config) (http.RoundTripper, error) {\n\tkey, canCache, err := tlsConfigKey(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif canCache {\n\t\t// Ensure we only create a single transport for the given TLS options\n\t\tc.mu.Lock()\n\t\tdefer c.mu.Unlock()\n\n\t\t// See if we already have a custom transport for this config\n\t\tif t, ok := c.transports[key]; ok {\n\t\t\treturn t, nil\n\t\t}\n\t}\n\n\t// Get the TLS options for this client config\n\ttlsConfig, err := TLSConfigFor(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// The options didn't require a custom TLS config\n\tif tlsConfig == nil \u0026\u0026 config.DialHolder == nil \u0026\u0026 config.Proxy == nil {\n\t\treturn http.DefaultTransport, nil\n\t}\n\n\tvar dial func(ctx context.Context, network, address string) (net.Conn, error)\n\tif config.DialHolder != nil {\n\t\tdial = config.DialHolder.Dial\n\t} else {\n\t\tdial = (\u0026net.Dialer{\n\t\t\tTimeout: 30 * time.Second,\n\t\t\tKeepAlive: 30 * time.Second,\n\t\t}).DialContext\n\t}\n\n\t// If we use are reloading files, we need to handle certificate rotation properly\n\t// TODO(jackkleeman): We can also add rotation here when config.HasCertCallback() is true\n\tif config.TLS.ReloadTLSFiles \u0026\u0026 tlsConfig != nil \u0026\u0026 tlsConfig.GetClientCertificate != nil {\n\t\tdynamicCertDialer := certRotatingDialer(tlsConfig.GetClientCertificate, dial)\n\t\ttlsConfig.GetClientCertificate = dynamicCertDialer.GetClientCertificate\n\t\tdial = dynamicCertDialer.connDialer.DialContext\n\t\tgo dynamicCertDialer.Run(DialerStopCh)\n\t}\n\n\tproxy := http.ProxyFromEnvironment\n\tif config.Proxy != nil {\n\t\tproxy = config.Proxy\n\t}\n\n\ttransport := utilnet.SetTransportDefaults(\u0026http.Transport{\n\t\tProxy: proxy,\n\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t\tTLSClientConfig: tlsConfig,\n\t\tMaxIdleConnsPerHost: idleConnsPerHost,\n\t\tDialContext: dial,\n\t\tDisableCompression: config.DisableCompression,\n\t})\n\n\tif canCache {\n\t\t// Cache a single transport for these options\n\t\tc.transports[key] = transport\n\t}\n\n\treturn transport, nil\n}","line":{"from":73,"to":139}} {"id":100029092,"name":"tlsConfigKey","signature":"func tlsConfigKey(c *Config) (tlsCacheKey, bool, error)","file":"staging/src/k8s.io/client-go/transport/cache.go","code":"// tlsConfigKey returns a unique key for tls.Config objects returned from TLSConfigFor\nfunc tlsConfigKey(c *Config) (tlsCacheKey, bool, error) {\n\t// Make sure ca/key/cert content is loaded\n\tif err := loadTLSFiles(c); err != nil {\n\t\treturn tlsCacheKey{}, false, err\n\t}\n\n\tif c.Proxy != nil {\n\t\t// cannot determine equality for functions\n\t\treturn tlsCacheKey{}, false, nil\n\t}\n\n\tk := tlsCacheKey{\n\t\tinsecure: c.TLS.Insecure,\n\t\tcaData: string(c.TLS.CAData),\n\t\tserverName: c.TLS.ServerName,\n\t\tnextProtos: strings.Join(c.TLS.NextProtos, \",\"),\n\t\tdisableCompression: c.DisableCompression,\n\t\tgetCert: c.TLS.GetCertHolder,\n\t\tdial: c.DialHolder,\n\t}\n\n\tif c.TLS.ReloadTLSFiles {\n\t\tk.certFile = c.TLS.CertFile\n\t\tk.keyFile = c.TLS.KeyFile\n\t} else {\n\t\tk.certData = string(c.TLS.CertData)\n\t\tk.keyData = string(c.TLS.KeyData)\n\t}\n\n\treturn k, true, nil\n}","line":{"from":141,"to":172}} {"id":100029093,"name":"isComparable","signature":"func isComparable[T comparable]() {}","file":"staging/src/k8s.io/client-go/transport/cache_go118.go","code":"func isComparable[T comparable]() {}","line":{"from":24,"to":24}} {"id":100029094,"name":"certRotatingDialer","signature":"func certRotatingDialer(reload reloadFunc, dial utilnet.DialFunc) *dynamicClientCert","file":"staging/src/k8s.io/client-go/transport/cert_rotation.go","code":"func certRotatingDialer(reload reloadFunc, dial utilnet.DialFunc) *dynamicClientCert {\n\td := \u0026dynamicClientCert{\n\t\treload: reload,\n\t\tconnDialer: connrotation.NewDialer(connrotation.DialFunc(dial)),\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"DynamicClientCertificate\"),\n\t}\n\n\treturn d\n}","line":{"from":53,"to":61}} {"id":100029095,"name":"loadClientCert","signature":"func (c *dynamicClientCert) loadClientCert() (*tls.Certificate, error)","file":"staging/src/k8s.io/client-go/transport/cert_rotation.go","code":"// loadClientCert calls the callback and rotates connections if needed\nfunc (c *dynamicClientCert) loadClientCert() (*tls.Certificate, error) {\n\tcert, err := c.reload(nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// check to see if we have a change. If the values are the same, do nothing.\n\tc.certMtx.RLock()\n\thaveCert := c.clientCert != nil\n\tif certsEqual(c.clientCert, cert) {\n\t\tc.certMtx.RUnlock()\n\t\treturn c.clientCert, nil\n\t}\n\tc.certMtx.RUnlock()\n\n\tc.certMtx.Lock()\n\tc.clientCert = cert\n\tc.certMtx.Unlock()\n\n\t// The first certificate requested is not a rotation that is worth closing connections for\n\tif !haveCert {\n\t\treturn cert, nil\n\t}\n\n\tklog.V(1).Infof(\"certificate rotation detected, shutting down client connections to start using new credentials\")\n\tc.connDialer.CloseAll()\n\n\treturn cert, nil\n}","line":{"from":63,"to":92}} {"id":100029096,"name":"certsEqual","signature":"func certsEqual(left, right *tls.Certificate) bool","file":"staging/src/k8s.io/client-go/transport/cert_rotation.go","code":"// certsEqual compares tls Certificates, ignoring the Leaf which may get filled in dynamically\nfunc certsEqual(left, right *tls.Certificate) bool {\n\tif left == nil || right == nil {\n\t\treturn left == right\n\t}\n\n\tif !byteMatrixEqual(left.Certificate, right.Certificate) {\n\t\treturn false\n\t}\n\n\tif !reflect.DeepEqual(left.PrivateKey, right.PrivateKey) {\n\t\treturn false\n\t}\n\n\tif !byteMatrixEqual(left.SignedCertificateTimestamps, right.SignedCertificateTimestamps) {\n\t\treturn false\n\t}\n\n\tif !bytes.Equal(left.OCSPStaple, right.OCSPStaple) {\n\t\treturn false\n\t}\n\n\treturn true\n}","line":{"from":94,"to":117}} {"id":100029097,"name":"byteMatrixEqual","signature":"func byteMatrixEqual(left, right [][]byte) bool","file":"staging/src/k8s.io/client-go/transport/cert_rotation.go","code":"func byteMatrixEqual(left, right [][]byte) bool {\n\tif len(left) != len(right) {\n\t\treturn false\n\t}\n\n\tfor i := range left {\n\t\tif !bytes.Equal(left[i], right[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":119,"to":130}} {"id":100029098,"name":"Run","signature":"func (c *dynamicClientCert) Run(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/client-go/transport/cert_rotation.go","code":"// run starts the controller and blocks until stopCh is closed.\nfunc (c *dynamicClientCert) Run(stopCh \u003c-chan struct{}) {\n\tdefer utilruntime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\n\tklog.V(3).Infof(\"Starting client certificate rotation controller\")\n\tdefer klog.V(3).Infof(\"Shutting down client certificate rotation controller\")\n\n\tgo wait.Until(c.runWorker, time.Second, stopCh)\n\n\tgo wait.PollImmediateUntil(CertCallbackRefreshDuration, func() (bool, error) {\n\t\tc.queue.Add(workItemKey)\n\t\treturn false, nil\n\t}, stopCh)\n\n\t\u003c-stopCh\n}","line":{"from":132,"to":148}} {"id":100029099,"name":"runWorker","signature":"func (c *dynamicClientCert) runWorker()","file":"staging/src/k8s.io/client-go/transport/cert_rotation.go","code":"func (c *dynamicClientCert) runWorker() {\n\tfor c.processNextWorkItem() {\n\t}\n}","line":{"from":150,"to":153}} {"id":100029100,"name":"processNextWorkItem","signature":"func (c *dynamicClientCert) processNextWorkItem() bool","file":"staging/src/k8s.io/client-go/transport/cert_rotation.go","code":"func (c *dynamicClientCert) processNextWorkItem() bool {\n\tdsKey, quit := c.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.queue.Done(dsKey)\n\n\t_, err := c.loadClientCert()\n\tif err == nil {\n\t\tc.queue.Forget(dsKey)\n\t\treturn true\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"%v failed with : %v\", dsKey, err))\n\tc.queue.AddRateLimited(dsKey)\n\n\treturn true\n}","line":{"from":155,"to":172}} {"id":100029101,"name":"GetClientCertificate","signature":"func (c *dynamicClientCert) GetClientCertificate(*tls.CertificateRequestInfo) (*tls.Certificate, error)","file":"staging/src/k8s.io/client-go/transport/cert_rotation.go","code":"func (c *dynamicClientCert) GetClientCertificate(*tls.CertificateRequestInfo) (*tls.Certificate, error) {\n\treturn c.loadClientCert()\n}","line":{"from":174,"to":176}} {"id":100029102,"name":"HasCA","signature":"func (c *Config) HasCA() bool","file":"staging/src/k8s.io/client-go/transport/config.go","code":"// HasCA returns whether the configuration has a certificate authority or not.\nfunc (c *Config) HasCA() bool {\n\treturn len(c.TLS.CAData) \u003e 0 || len(c.TLS.CAFile) \u003e 0\n}","line":{"from":99,"to":102}} {"id":100029103,"name":"HasBasicAuth","signature":"func (c *Config) HasBasicAuth() bool","file":"staging/src/k8s.io/client-go/transport/config.go","code":"// HasBasicAuth returns whether the configuration has basic authentication or not.\nfunc (c *Config) HasBasicAuth() bool {\n\treturn len(c.Username) != 0\n}","line":{"from":104,"to":107}} {"id":100029104,"name":"HasTokenAuth","signature":"func (c *Config) HasTokenAuth() bool","file":"staging/src/k8s.io/client-go/transport/config.go","code":"// HasTokenAuth returns whether the configuration has token authentication or not.\nfunc (c *Config) HasTokenAuth() bool {\n\treturn len(c.BearerToken) != 0 || len(c.BearerTokenFile) != 0\n}","line":{"from":109,"to":112}} {"id":100029105,"name":"HasCertAuth","signature":"func (c *Config) HasCertAuth() bool","file":"staging/src/k8s.io/client-go/transport/config.go","code":"// HasCertAuth returns whether the configuration has certificate authentication or not.\nfunc (c *Config) HasCertAuth() bool {\n\treturn (len(c.TLS.CertData) != 0 || len(c.TLS.CertFile) != 0) \u0026\u0026 (len(c.TLS.KeyData) != 0 || len(c.TLS.KeyFile) != 0)\n}","line":{"from":114,"to":117}} {"id":100029106,"name":"HasCertCallback","signature":"func (c *Config) HasCertCallback() bool","file":"staging/src/k8s.io/client-go/transport/config.go","code":"// HasCertCallback returns whether the configuration has certificate callback or not.\nfunc (c *Config) HasCertCallback() bool {\n\treturn c.TLS.GetCertHolder != nil\n}","line":{"from":119,"to":122}} {"id":100029107,"name":"Wrap","signature":"func (c *Config) Wrap(fn WrapperFunc)","file":"staging/src/k8s.io/client-go/transport/config.go","code":"// Wrap adds a transport middleware function that will give the caller\n// an opportunity to wrap the underlying http.RoundTripper prior to the\n// first API call being made. The provided function is invoked after any\n// existing transport wrappers are invoked.\nfunc (c *Config) Wrap(fn WrapperFunc) {\n\tc.WrapTransport = Wrappers(c.WrapTransport, fn)\n}","line":{"from":124,"to":130}} {"id":100029108,"name":"HTTPWrappersForConfig","signature":"func HTTPWrappersForConfig(config *Config, rt http.RoundTripper) (http.RoundTripper, error)","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"// HTTPWrappersForConfig wraps a round tripper with any relevant layered\n// behavior from the config. Exposed to allow more clients that need HTTP-like\n// behavior but then must hijack the underlying connection (like WebSocket or\n// HTTP2 clients). Pure HTTP clients should use the RoundTripper returned from\n// New.\nfunc HTTPWrappersForConfig(config *Config, rt http.RoundTripper) (http.RoundTripper, error) {\n\tif config.WrapTransport != nil {\n\t\trt = config.WrapTransport(rt)\n\t}\n\n\trt = DebugWrappers(rt)\n\n\t// Set authentication wrappers\n\tswitch {\n\tcase config.HasBasicAuth() \u0026\u0026 config.HasTokenAuth():\n\t\treturn nil, fmt.Errorf(\"username/password or bearer token may be set, but not both\")\n\tcase config.HasTokenAuth():\n\t\tvar err error\n\t\trt, err = NewBearerAuthWithRefreshRoundTripper(config.BearerToken, config.BearerTokenFile, rt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tcase config.HasBasicAuth():\n\t\trt = NewBasicAuthRoundTripper(config.Username, config.Password, rt)\n\t}\n\tif len(config.UserAgent) \u003e 0 {\n\t\trt = NewUserAgentRoundTripper(config.UserAgent, rt)\n\t}\n\tif len(config.Impersonate.UserName) \u003e 0 ||\n\t\tlen(config.Impersonate.UID) \u003e 0 ||\n\t\tlen(config.Impersonate.Groups) \u003e 0 ||\n\t\tlen(config.Impersonate.Extra) \u003e 0 {\n\t\trt = NewImpersonatingRoundTripper(config.Impersonate, rt)\n\t}\n\treturn rt, nil\n}","line":{"from":34,"to":69}} {"id":100029109,"name":"DebugWrappers","signature":"func DebugWrappers(rt http.RoundTripper) http.RoundTripper","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"// DebugWrappers wraps a round tripper and logs based on the current log level.\nfunc DebugWrappers(rt http.RoundTripper) http.RoundTripper {\n\tswitch {\n\tcase bool(klog.V(9).Enabled()):\n\t\trt = NewDebuggingRoundTripper(rt, DebugCurlCommand, DebugURLTiming, DebugDetailedTiming, DebugResponseHeaders)\n\tcase bool(klog.V(8).Enabled()):\n\t\trt = NewDebuggingRoundTripper(rt, DebugJustURL, DebugRequestHeaders, DebugResponseStatus, DebugResponseHeaders)\n\tcase bool(klog.V(7).Enabled()):\n\t\trt = NewDebuggingRoundTripper(rt, DebugJustURL, DebugRequestHeaders, DebugResponseStatus)\n\tcase bool(klog.V(6).Enabled()):\n\t\trt = NewDebuggingRoundTripper(rt, DebugURLTiming)\n\t}\n\n\treturn rt\n}","line":{"from":71,"to":85}} {"id":100029110,"name":"NewAuthProxyRoundTripper","signature":"func NewAuthProxyRoundTripper(username string, groups []string, extra map[string][]string, rt http.RoundTripper) http.RoundTripper","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"// NewAuthProxyRoundTripper provides a roundtripper which will add auth proxy fields to requests for\n// authentication terminating proxy cases\n// assuming you pull the user from the context:\n// username is the user.Info.GetName() of the user\n// groups is the user.Info.GetGroups() of the user\n// extra is the user.Info.GetExtra() of the user\n// extra can contain any additional information that the authenticator\n// thought was interesting, for example authorization scopes.\n// In order to faithfully round-trip through an impersonation flow, these keys\n// MUST be lowercase.\nfunc NewAuthProxyRoundTripper(username string, groups []string, extra map[string][]string, rt http.RoundTripper) http.RoundTripper {\n\treturn \u0026authProxyRoundTripper{\n\t\tusername: username,\n\t\tgroups: groups,\n\t\textra: extra,\n\t\trt: rt,\n\t}\n}","line":{"from":97,"to":114}} {"id":100029111,"name":"RoundTrip","signature":"func (rt *authProxyRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"func (rt *authProxyRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {\n\treq = utilnet.CloneRequest(req)\n\tSetAuthProxyHeaders(req, rt.username, rt.groups, rt.extra)\n\n\treturn rt.rt.RoundTrip(req)\n}","line":{"from":116,"to":121}} {"id":100029112,"name":"SetAuthProxyHeaders","signature":"func SetAuthProxyHeaders(req *http.Request, username string, groups []string, extra map[string][]string)","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"// SetAuthProxyHeaders stomps the auth proxy header fields. It mutates its argument.\nfunc SetAuthProxyHeaders(req *http.Request, username string, groups []string, extra map[string][]string) {\n\treq.Header.Del(\"X-Remote-User\")\n\treq.Header.Del(\"X-Remote-Group\")\n\tfor key := range req.Header {\n\t\tif strings.HasPrefix(strings.ToLower(key), strings.ToLower(\"X-Remote-Extra-\")) {\n\t\t\treq.Header.Del(key)\n\t\t}\n\t}\n\n\treq.Header.Set(\"X-Remote-User\", username)\n\tfor _, group := range groups {\n\t\treq.Header.Add(\"X-Remote-Group\", group)\n\t}\n\tfor key, values := range extra {\n\t\tfor _, value := range values {\n\t\t\treq.Header.Add(\"X-Remote-Extra-\"+headerKeyEscape(key), value)\n\t\t}\n\t}\n}","line":{"from":123,"to":142}} {"id":100029113,"name":"CancelRequest","signature":"func (rt *authProxyRoundTripper) CancelRequest(req *http.Request)","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"func (rt *authProxyRoundTripper) CancelRequest(req *http.Request) {\n\ttryCancelRequest(rt.WrappedRoundTripper(), req)\n}","line":{"from":144,"to":146}} {"id":100029114,"name":"WrappedRoundTripper","signature":"func (rt *authProxyRoundTripper) WrappedRoundTripper() http.RoundTripper { return rt.rt }","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"func (rt *authProxyRoundTripper) WrappedRoundTripper() http.RoundTripper { return rt.rt }","line":{"from":148,"to":148}} {"id":100029115,"name":"NewUserAgentRoundTripper","signature":"func NewUserAgentRoundTripper(agent string, rt http.RoundTripper) http.RoundTripper","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"// NewUserAgentRoundTripper will add User-Agent header to a request unless it has already been set.\nfunc NewUserAgentRoundTripper(agent string, rt http.RoundTripper) http.RoundTripper {\n\treturn \u0026userAgentRoundTripper{agent, rt}\n}","line":{"from":157,"to":160}} {"id":100029116,"name":"RoundTrip","signature":"func (rt *userAgentRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"func (rt *userAgentRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {\n\tif len(req.Header.Get(\"User-Agent\")) != 0 {\n\t\treturn rt.rt.RoundTrip(req)\n\t}\n\treq = utilnet.CloneRequest(req)\n\treq.Header.Set(\"User-Agent\", rt.agent)\n\treturn rt.rt.RoundTrip(req)\n}","line":{"from":162,"to":169}} {"id":100029117,"name":"CancelRequest","signature":"func (rt *userAgentRoundTripper) CancelRequest(req *http.Request)","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"func (rt *userAgentRoundTripper) CancelRequest(req *http.Request) {\n\ttryCancelRequest(rt.WrappedRoundTripper(), req)\n}","line":{"from":171,"to":173}} {"id":100029118,"name":"WrappedRoundTripper","signature":"func (rt *userAgentRoundTripper) WrappedRoundTripper() http.RoundTripper { return rt.rt }","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"func (rt *userAgentRoundTripper) WrappedRoundTripper() http.RoundTripper { return rt.rt }","line":{"from":175,"to":175}} {"id":100029119,"name":"NewBasicAuthRoundTripper","signature":"func NewBasicAuthRoundTripper(username, password string, rt http.RoundTripper) http.RoundTripper","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"// NewBasicAuthRoundTripper will apply a BASIC auth authorization header to a\n// request unless it has already been set.\nfunc NewBasicAuthRoundTripper(username, password string, rt http.RoundTripper) http.RoundTripper {\n\treturn \u0026basicAuthRoundTripper{username, password, rt}\n}","line":{"from":185,"to":189}} {"id":100029120,"name":"RoundTrip","signature":"func (rt *basicAuthRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"func (rt *basicAuthRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {\n\tif len(req.Header.Get(\"Authorization\")) != 0 {\n\t\treturn rt.rt.RoundTrip(req)\n\t}\n\treq = utilnet.CloneRequest(req)\n\treq.SetBasicAuth(rt.username, rt.password)\n\treturn rt.rt.RoundTrip(req)\n}","line":{"from":191,"to":198}} {"id":100029121,"name":"CancelRequest","signature":"func (rt *basicAuthRoundTripper) CancelRequest(req *http.Request)","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"func (rt *basicAuthRoundTripper) CancelRequest(req *http.Request) {\n\ttryCancelRequest(rt.WrappedRoundTripper(), req)\n}","line":{"from":200,"to":202}} {"id":100029122,"name":"WrappedRoundTripper","signature":"func (rt *basicAuthRoundTripper) WrappedRoundTripper() http.RoundTripper { return rt.rt }","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"func (rt *basicAuthRoundTripper) WrappedRoundTripper() http.RoundTripper { return rt.rt }","line":{"from":204,"to":204}} {"id":100029123,"name":"NewImpersonatingRoundTripper","signature":"func NewImpersonatingRoundTripper(impersonate ImpersonationConfig, delegate http.RoundTripper) http.RoundTripper","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"// NewImpersonatingRoundTripper will add an Act-As header to a request unless it has already been set.\nfunc NewImpersonatingRoundTripper(impersonate ImpersonationConfig, delegate http.RoundTripper) http.RoundTripper {\n\treturn \u0026impersonatingRoundTripper{impersonate, delegate}\n}","line":{"from":236,"to":239}} {"id":100029124,"name":"RoundTrip","signature":"func (rt *impersonatingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"func (rt *impersonatingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {\n\t// use the user header as marker for the rest.\n\tif len(req.Header.Get(ImpersonateUserHeader)) != 0 {\n\t\treturn rt.delegate.RoundTrip(req)\n\t}\n\treq = utilnet.CloneRequest(req)\n\treq.Header.Set(ImpersonateUserHeader, rt.impersonate.UserName)\n\tif rt.impersonate.UID != \"\" {\n\t\treq.Header.Set(ImpersonateUIDHeader, rt.impersonate.UID)\n\t}\n\tfor _, group := range rt.impersonate.Groups {\n\t\treq.Header.Add(ImpersonateGroupHeader, group)\n\t}\n\tfor k, vv := range rt.impersonate.Extra {\n\t\tfor _, v := range vv {\n\t\t\treq.Header.Add(ImpersonateUserExtraHeaderPrefix+headerKeyEscape(k), v)\n\t\t}\n\t}\n\n\treturn rt.delegate.RoundTrip(req)\n}","line":{"from":241,"to":261}} {"id":100029125,"name":"CancelRequest","signature":"func (rt *impersonatingRoundTripper) CancelRequest(req *http.Request)","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"func (rt *impersonatingRoundTripper) CancelRequest(req *http.Request) {\n\ttryCancelRequest(rt.WrappedRoundTripper(), req)\n}","line":{"from":263,"to":265}} {"id":100029126,"name":"WrappedRoundTripper","signature":"func (rt *impersonatingRoundTripper) WrappedRoundTripper() http.RoundTripper { return rt.delegate }","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"func (rt *impersonatingRoundTripper) WrappedRoundTripper() http.RoundTripper { return rt.delegate }","line":{"from":267,"to":267}} {"id":100029127,"name":"NewBearerAuthRoundTripper","signature":"func NewBearerAuthRoundTripper(bearer string, rt http.RoundTripper) http.RoundTripper","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"// NewBearerAuthRoundTripper adds the provided bearer token to a request\n// unless the authorization header has already been set.\nfunc NewBearerAuthRoundTripper(bearer string, rt http.RoundTripper) http.RoundTripper {\n\treturn \u0026bearerAuthRoundTripper{bearer, nil, rt}\n}","line":{"from":277,"to":281}} {"id":100029128,"name":"NewBearerAuthWithRefreshRoundTripper","signature":"func NewBearerAuthWithRefreshRoundTripper(bearer string, tokenFile string, rt http.RoundTripper) (http.RoundTripper, error)","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"// NewBearerAuthWithRefreshRoundTripper adds the provided bearer token to a request\n// unless the authorization header has already been set.\n// If tokenFile is non-empty, it is periodically read,\n// and the last successfully read content is used as the bearer token.\n// If tokenFile is non-empty and bearer is empty, the tokenFile is read\n// immediately to populate the initial bearer token.\nfunc NewBearerAuthWithRefreshRoundTripper(bearer string, tokenFile string, rt http.RoundTripper) (http.RoundTripper, error) {\n\tif len(tokenFile) == 0 {\n\t\treturn \u0026bearerAuthRoundTripper{bearer, nil, rt}, nil\n\t}\n\tsource := NewCachedFileTokenSource(tokenFile)\n\tif len(bearer) == 0 {\n\t\ttoken, err := source.Token()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbearer = token.AccessToken\n\t}\n\treturn \u0026bearerAuthRoundTripper{bearer, source, rt}, nil\n}","line":{"from":283,"to":302}} {"id":100029129,"name":"RoundTrip","signature":"func (rt *bearerAuthRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"func (rt *bearerAuthRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {\n\tif len(req.Header.Get(\"Authorization\")) != 0 {\n\t\treturn rt.rt.RoundTrip(req)\n\t}\n\n\treq = utilnet.CloneRequest(req)\n\ttoken := rt.bearer\n\tif rt.source != nil {\n\t\tif refreshedToken, err := rt.source.Token(); err == nil {\n\t\t\ttoken = refreshedToken.AccessToken\n\t\t}\n\t}\n\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"Bearer %s\", token))\n\treturn rt.rt.RoundTrip(req)\n}","line":{"from":304,"to":318}} {"id":100029130,"name":"CancelRequest","signature":"func (rt *bearerAuthRoundTripper) CancelRequest(req *http.Request)","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"func (rt *bearerAuthRoundTripper) CancelRequest(req *http.Request) {\n\ttryCancelRequest(rt.WrappedRoundTripper(), req)\n}","line":{"from":320,"to":322}} {"id":100029131,"name":"WrappedRoundTripper","signature":"func (rt *bearerAuthRoundTripper) WrappedRoundTripper() http.RoundTripper { return rt.rt }","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"func (rt *bearerAuthRoundTripper) WrappedRoundTripper() http.RoundTripper { return rt.rt }","line":{"from":324,"to":324}} {"id":100029132,"name":"newRequestInfo","signature":"func newRequestInfo(req *http.Request) *requestInfo","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"// newRequestInfo creates a new RequestInfo based on an http request\nfunc newRequestInfo(req *http.Request) *requestInfo {\n\treturn \u0026requestInfo{\n\t\tRequestURL: req.URL.String(),\n\t\tRequestVerb: req.Method,\n\t\tRequestHeaders: req.Header,\n\t}\n}","line":{"from":347,"to":354}} {"id":100029133,"name":"complete","signature":"func (r *requestInfo) complete(response *http.Response, err error)","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"// complete adds information about the response to the requestInfo\nfunc (r *requestInfo) complete(response *http.Response, err error) {\n\tif err != nil {\n\t\tr.ResponseErr = err\n\t\treturn\n\t}\n\tr.ResponseStatus = response.Status\n\tr.ResponseHeaders = response.Header\n}","line":{"from":356,"to":364}} {"id":100029134,"name":"toCurl","signature":"func (r *requestInfo) toCurl() string","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"// toCurl returns a string that can be run as a command in a terminal (minus the body)\nfunc (r *requestInfo) toCurl() string {\n\theaders := \"\"\n\tfor key, values := range r.RequestHeaders {\n\t\tfor _, value := range values {\n\t\t\tvalue = maskValue(key, value)\n\t\t\theaders += fmt.Sprintf(` -H %q`, fmt.Sprintf(\"%s: %s\", key, value))\n\t\t}\n\t}\n\n\treturn fmt.Sprintf(\"curl -v -X%s %s '%s'\", r.RequestVerb, headers, r.RequestURL)\n}","line":{"from":366,"to":377}} {"id":100029135,"name":"NewDebuggingRoundTripper","signature":"func NewDebuggingRoundTripper(rt http.RoundTripper, levels ...DebugLevel) http.RoundTripper","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"// NewDebuggingRoundTripper allows to display in the logs output debug information\n// on the API requests performed by the client.\nfunc NewDebuggingRoundTripper(rt http.RoundTripper, levels ...DebugLevel) http.RoundTripper {\n\tdrt := \u0026debuggingRoundTripper{\n\t\tdelegatedRoundTripper: rt,\n\t\tlevels: make(map[DebugLevel]bool, len(levels)),\n\t}\n\tfor _, v := range levels {\n\t\tdrt.levels[v] = true\n\t}\n\treturn drt\n}","line":{"from":410,"to":421}} {"id":100029136,"name":"CancelRequest","signature":"func (rt *debuggingRoundTripper) CancelRequest(req *http.Request)","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"func (rt *debuggingRoundTripper) CancelRequest(req *http.Request) {\n\ttryCancelRequest(rt.WrappedRoundTripper(), req)\n}","line":{"from":423,"to":425}} {"id":100029137,"name":"maskValue","signature":"func maskValue(key string, value string) string","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"// maskValue masks credential content from authorization headers\n// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization\nfunc maskValue(key string, value string) string {\n\tif !strings.EqualFold(key, \"Authorization\") {\n\t\treturn value\n\t}\n\tif len(value) == 0 {\n\t\treturn \"\"\n\t}\n\tvar authType string\n\tif i := strings.Index(value, \" \"); i \u003e 0 {\n\t\tauthType = value[0:i]\n\t} else {\n\t\tauthType = value\n\t}\n\tif !knownAuthTypes[strings.ToLower(authType)] {\n\t\treturn \"\u003cmasked\u003e\"\n\t}\n\tif len(value) \u003e len(authType)+1 {\n\t\tvalue = authType + \" \u003cmasked\u003e\"\n\t} else {\n\t\tvalue = authType\n\t}\n\treturn value\n}","line":{"from":433,"to":457}} {"id":100029138,"name":"RoundTrip","signature":"func (rt *debuggingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"func (rt *debuggingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {\n\treqInfo := newRequestInfo(req)\n\n\tif rt.levels[DebugJustURL] {\n\t\tklog.Infof(\"%s %s\", reqInfo.RequestVerb, reqInfo.RequestURL)\n\t}\n\tif rt.levels[DebugCurlCommand] {\n\t\tklog.Infof(\"%s\", reqInfo.toCurl())\n\t}\n\tif rt.levels[DebugRequestHeaders] {\n\t\tklog.Info(\"Request Headers:\")\n\t\tfor key, values := range reqInfo.RequestHeaders {\n\t\t\tfor _, value := range values {\n\t\t\t\tvalue = maskValue(key, value)\n\t\t\t\tklog.Infof(\" %s: %s\", key, value)\n\t\t\t}\n\t\t}\n\t}\n\n\tstartTime := time.Now()\n\n\tif rt.levels[DebugDetailedTiming] {\n\t\tvar getConn, dnsStart, dialStart, tlsStart, serverStart time.Time\n\t\tvar host string\n\t\ttrace := \u0026httptrace.ClientTrace{\n\t\t\t// DNS\n\t\t\tDNSStart: func(info httptrace.DNSStartInfo) {\n\t\t\t\treqInfo.muTrace.Lock()\n\t\t\t\tdefer reqInfo.muTrace.Unlock()\n\t\t\t\tdnsStart = time.Now()\n\t\t\t\thost = info.Host\n\t\t\t},\n\t\t\tDNSDone: func(info httptrace.DNSDoneInfo) {\n\t\t\t\treqInfo.muTrace.Lock()\n\t\t\t\tdefer reqInfo.muTrace.Unlock()\n\t\t\t\treqInfo.DNSLookup = time.Since(dnsStart)\n\t\t\t\tklog.Infof(\"HTTP Trace: DNS Lookup for %s resolved to %v\", host, info.Addrs)\n\t\t\t},\n\t\t\t// Dial\n\t\t\tConnectStart: func(network, addr string) {\n\t\t\t\treqInfo.muTrace.Lock()\n\t\t\t\tdefer reqInfo.muTrace.Unlock()\n\t\t\t\tdialStart = time.Now()\n\t\t\t},\n\t\t\tConnectDone: func(network, addr string, err error) {\n\t\t\t\treqInfo.muTrace.Lock()\n\t\t\t\tdefer reqInfo.muTrace.Unlock()\n\t\t\t\treqInfo.Dialing = time.Since(dialStart)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Infof(\"HTTP Trace: Dial to %s:%s failed: %v\", network, addr, err)\n\t\t\t\t} else {\n\t\t\t\t\tklog.Infof(\"HTTP Trace: Dial to %s:%s succeed\", network, addr)\n\t\t\t\t}\n\t\t\t},\n\t\t\t// TLS\n\t\t\tTLSHandshakeStart: func() {\n\t\t\t\ttlsStart = time.Now()\n\t\t\t},\n\t\t\tTLSHandshakeDone: func(_ tls.ConnectionState, _ error) {\n\t\t\t\treqInfo.muTrace.Lock()\n\t\t\t\tdefer reqInfo.muTrace.Unlock()\n\t\t\t\treqInfo.TLSHandshake = time.Since(tlsStart)\n\t\t\t},\n\t\t\t// Connection (it can be DNS + Dial or just the time to get one from the connection pool)\n\t\t\tGetConn: func(hostPort string) {\n\t\t\t\tgetConn = time.Now()\n\t\t\t},\n\t\t\tGotConn: func(info httptrace.GotConnInfo) {\n\t\t\t\treqInfo.muTrace.Lock()\n\t\t\t\tdefer reqInfo.muTrace.Unlock()\n\t\t\t\treqInfo.GetConnection = time.Since(getConn)\n\t\t\t\treqInfo.ConnectionReused = info.Reused\n\t\t\t},\n\t\t\t// Server Processing (time since we wrote the request until first byte is received)\n\t\t\tWroteRequest: func(info httptrace.WroteRequestInfo) {\n\t\t\t\treqInfo.muTrace.Lock()\n\t\t\t\tdefer reqInfo.muTrace.Unlock()\n\t\t\t\tserverStart = time.Now()\n\t\t\t},\n\t\t\tGotFirstResponseByte: func() {\n\t\t\t\treqInfo.muTrace.Lock()\n\t\t\t\tdefer reqInfo.muTrace.Unlock()\n\t\t\t\treqInfo.ServerProcessing = time.Since(serverStart)\n\t\t\t},\n\t\t}\n\t\treq = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))\n\t}\n\n\tresponse, err := rt.delegatedRoundTripper.RoundTrip(req)\n\treqInfo.Duration = time.Since(startTime)\n\n\treqInfo.complete(response, err)\n\n\tif rt.levels[DebugURLTiming] {\n\t\tklog.Infof(\"%s %s %s in %d milliseconds\", reqInfo.RequestVerb, reqInfo.RequestURL, reqInfo.ResponseStatus, reqInfo.Duration.Nanoseconds()/int64(time.Millisecond))\n\t}\n\tif rt.levels[DebugDetailedTiming] {\n\t\tstats := \"\"\n\t\tif !reqInfo.ConnectionReused {\n\t\t\tstats += fmt.Sprintf(`DNSLookup %d ms Dial %d ms TLSHandshake %d ms`,\n\t\t\t\treqInfo.DNSLookup.Nanoseconds()/int64(time.Millisecond),\n\t\t\t\treqInfo.Dialing.Nanoseconds()/int64(time.Millisecond),\n\t\t\t\treqInfo.TLSHandshake.Nanoseconds()/int64(time.Millisecond),\n\t\t\t)\n\t\t} else {\n\t\t\tstats += fmt.Sprintf(`GetConnection %d ms`, reqInfo.GetConnection.Nanoseconds()/int64(time.Millisecond))\n\t\t}\n\t\tif reqInfo.ServerProcessing != 0 {\n\t\t\tstats += fmt.Sprintf(` ServerProcessing %d ms`, reqInfo.ServerProcessing.Nanoseconds()/int64(time.Millisecond))\n\t\t}\n\t\tstats += fmt.Sprintf(` Duration %d ms`, reqInfo.Duration.Nanoseconds()/int64(time.Millisecond))\n\t\tklog.Infof(\"HTTP Statistics: %s\", stats)\n\t}\n\n\tif rt.levels[DebugResponseStatus] {\n\t\tklog.Infof(\"Response Status: %s in %d milliseconds\", reqInfo.ResponseStatus, reqInfo.Duration.Nanoseconds()/int64(time.Millisecond))\n\t}\n\tif rt.levels[DebugResponseHeaders] {\n\t\tklog.Info(\"Response Headers:\")\n\t\tfor key, values := range reqInfo.ResponseHeaders {\n\t\t\tfor _, value := range values {\n\t\t\t\tklog.Infof(\" %s: %s\", key, value)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn response, err\n}","line":{"from":459,"to":586}} {"id":100029139,"name":"WrappedRoundTripper","signature":"func (rt *debuggingRoundTripper) WrappedRoundTripper() http.RoundTripper","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"func (rt *debuggingRoundTripper) WrappedRoundTripper() http.RoundTripper {\n\treturn rt.delegatedRoundTripper\n}","line":{"from":588,"to":590}} {"id":100029140,"name":"legalHeaderByte","signature":"func legalHeaderByte(b byte) bool","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"func legalHeaderByte(b byte) bool {\n\treturn int(b) \u003c len(legalHeaderKeyBytes) \u0026\u0026 legalHeaderKeyBytes[b]\n}","line":{"from":592,"to":594}} {"id":100029141,"name":"shouldEscape","signature":"func shouldEscape(b byte) bool","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"func shouldEscape(b byte) bool {\n\t// url.PathUnescape() returns an error if any '%' is not followed by two\n\t// hexadecimal digits, so we'll intentionally encode it.\n\treturn !legalHeaderByte(b) || b == '%'\n}","line":{"from":596,"to":600}} {"id":100029142,"name":"headerKeyEscape","signature":"func headerKeyEscape(key string) string","file":"staging/src/k8s.io/client-go/transport/round_trippers.go","code":"func headerKeyEscape(key string) string {\n\tbuf := strings.Builder{}\n\tfor i := 0; i \u003c len(key); i++ {\n\t\tb := key[i]\n\t\tif shouldEscape(b) {\n\t\t\t// %-encode bytes that should be escaped:\n\t\t\t// https://tools.ietf.org/html/rfc3986#section-2.1\n\t\t\tfmt.Fprintf(\u0026buf, \"%%%02X\", b)\n\t\t\tcontinue\n\t\t}\n\t\tbuf.WriteByte(b)\n\t}\n\treturn buf.String()\n}","line":{"from":602,"to":615}} {"id":100029143,"name":"RoundTripperFor","signature":"func RoundTripperFor(config *restclient.Config) (http.RoundTripper, Upgrader, error)","file":"staging/src/k8s.io/client-go/transport/spdy/spdy.go","code":"// RoundTripperFor returns a round tripper and upgrader to use with SPDY.\nfunc RoundTripperFor(config *restclient.Config) (http.RoundTripper, Upgrader, error) {\n\ttlsConfig, err := restclient.TLSConfigFor(config)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tproxy := http.ProxyFromEnvironment\n\tif config.Proxy != nil {\n\t\tproxy = config.Proxy\n\t}\n\tupgradeRoundTripper := spdy.NewRoundTripperWithConfig(spdy.RoundTripperConfig{\n\t\tTLS: tlsConfig,\n\t\tProxier: proxy,\n\t\tPingPeriod: time.Second * 5,\n\t})\n\twrapper, err := restclient.HTTPWrappersForConfig(config, upgradeRoundTripper)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn wrapper, upgradeRoundTripper, nil\n}","line":{"from":36,"to":56}} {"id":100029144,"name":"NewDialer","signature":"func NewDialer(upgrader Upgrader, client *http.Client, method string, url *url.URL) httpstream.Dialer","file":"staging/src/k8s.io/client-go/transport/spdy/spdy.go","code":"// NewDialer will create a dialer that connects to the provided URL and upgrades the connection to SPDY.\nfunc NewDialer(upgrader Upgrader, client *http.Client, method string, url *url.URL) httpstream.Dialer {\n\treturn \u0026dialer{\n\t\tclient: client,\n\t\tupgrader: upgrader,\n\t\tmethod: method,\n\t\turl: url,\n\t}\n}","line":{"from":68,"to":76}} {"id":100029145,"name":"Dial","signature":"func (d *dialer) Dial(protocols ...string) (httpstream.Connection, string, error)","file":"staging/src/k8s.io/client-go/transport/spdy/spdy.go","code":"func (d *dialer) Dial(protocols ...string) (httpstream.Connection, string, error) {\n\treq, err := http.NewRequest(d.method, d.url.String(), nil)\n\tif err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"error creating request: %v\", err)\n\t}\n\treturn Negotiate(d.upgrader, d.client, req, protocols...)\n}","line":{"from":78,"to":84}} {"id":100029146,"name":"Negotiate","signature":"func Negotiate(upgrader Upgrader, client *http.Client, req *http.Request, protocols ...string) (httpstream.Connection, string, error)","file":"staging/src/k8s.io/client-go/transport/spdy/spdy.go","code":"// Negotiate opens a connection to a remote server and attempts to negotiate\n// a SPDY connection. Upon success, it returns the connection and the protocol selected by\n// the server. The client transport must use the upgradeRoundTripper - see RoundTripperFor.\nfunc Negotiate(upgrader Upgrader, client *http.Client, req *http.Request, protocols ...string) (httpstream.Connection, string, error) {\n\tfor i := range protocols {\n\t\treq.Header.Add(httpstream.HeaderProtocolVersion, protocols[i])\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"error sending request: %v\", err)\n\t}\n\tdefer resp.Body.Close()\n\tconn, err := upgrader.NewConnection(resp)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\treturn conn, resp.Header.Get(httpstream.HeaderProtocolVersion), nil\n}","line":{"from":86,"to":103}} {"id":100029147,"name":"TokenSourceWrapTransport","signature":"func TokenSourceWrapTransport(ts oauth2.TokenSource) func(http.RoundTripper) http.RoundTripper","file":"staging/src/k8s.io/client-go/transport/token_source.go","code":"// TokenSourceWrapTransport returns a WrapTransport that injects bearer tokens\n// authentication from an oauth2.TokenSource.\nfunc TokenSourceWrapTransport(ts oauth2.TokenSource) func(http.RoundTripper) http.RoundTripper {\n\treturn func(rt http.RoundTripper) http.RoundTripper {\n\t\treturn \u0026tokenSourceTransport{\n\t\t\tbase: rt,\n\t\t\tort: \u0026oauth2.Transport{\n\t\t\t\tSource: ts,\n\t\t\t\tBase: rt,\n\t\t\t},\n\t\t}\n\t}\n}","line":{"from":33,"to":45}} {"id":100029148,"name":"ResettableTokenSourceWrapTransport","signature":"func ResettableTokenSourceWrapTransport(ts ResettableTokenSource) func(http.RoundTripper) http.RoundTripper","file":"staging/src/k8s.io/client-go/transport/token_source.go","code":"// ResettableTokenSourceWrapTransport returns a WrapTransport that injects bearer tokens\n// authentication from an ResettableTokenSource.\nfunc ResettableTokenSourceWrapTransport(ts ResettableTokenSource) func(http.RoundTripper) http.RoundTripper {\n\treturn func(rt http.RoundTripper) http.RoundTripper {\n\t\treturn \u0026tokenSourceTransport{\n\t\t\tbase: rt,\n\t\t\tort: \u0026oauth2.Transport{\n\t\t\t\tSource: ts,\n\t\t\t\tBase: rt,\n\t\t\t},\n\t\t\tsrc: ts,\n\t\t}\n\t}\n}","line":{"from":52,"to":65}} {"id":100029149,"name":"NewCachedFileTokenSource","signature":"func NewCachedFileTokenSource(path string) *cachingTokenSource","file":"staging/src/k8s.io/client-go/transport/token_source.go","code":"// NewCachedFileTokenSource returns a resettable token source which reads a\n// token from a file at a specified path and periodically reloads it.\nfunc NewCachedFileTokenSource(path string) *cachingTokenSource {\n\treturn \u0026cachingTokenSource{\n\t\tnow: time.Now,\n\t\tleeway: 10 * time.Second,\n\t\tbase: \u0026fileTokenSource{\n\t\t\tpath: path,\n\t\t\t// This period was picked because it is half of the duration between when the kubelet\n\t\t\t// refreshes a projected service account token and when the original token expires.\n\t\t\t// Default token lifetime is 10 minutes, and the kubelet starts refreshing at 80% of lifetime.\n\t\t\t// This should induce re-reading at a frequency that works with the token volume source.\n\t\t\tperiod: time.Minute,\n\t\t},\n\t}\n}","line":{"from":67,"to":82}} {"id":100029150,"name":"NewCachedTokenSource","signature":"func NewCachedTokenSource(ts oauth2.TokenSource) *cachingTokenSource","file":"staging/src/k8s.io/client-go/transport/token_source.go","code":"// NewCachedTokenSource returns resettable token source with caching. It reads\n// a token from a designed TokenSource if not in cache or expired.\nfunc NewCachedTokenSource(ts oauth2.TokenSource) *cachingTokenSource {\n\treturn \u0026cachingTokenSource{\n\t\tnow: time.Now,\n\t\tbase: ts,\n\t}\n}","line":{"from":84,"to":91}} {"id":100029151,"name":"RoundTrip","signature":"func (tst *tokenSourceTransport) RoundTrip(req *http.Request) (*http.Response, error)","file":"staging/src/k8s.io/client-go/transport/token_source.go","code":"func (tst *tokenSourceTransport) RoundTrip(req *http.Request) (*http.Response, error) {\n\t// This is to allow --token to override other bearer token providers.\n\tif req.Header.Get(\"Authorization\") != \"\" {\n\t\treturn tst.base.RoundTrip(req)\n\t}\n\t// record time before RoundTrip to make sure newly acquired Unauthorized\n\t// token would not be reset. Another request from user is required to reset\n\t// and proceed.\n\tstart := time.Now()\n\tresp, err := tst.ort.RoundTrip(req)\n\tif err == nil \u0026\u0026 resp != nil \u0026\u0026 resp.StatusCode == 401 \u0026\u0026 tst.src != nil {\n\t\ttst.src.ResetTokenOlderThan(start)\n\t}\n\treturn resp, err\n}","line":{"from":101,"to":115}} {"id":100029152,"name":"CancelRequest","signature":"func (tst *tokenSourceTransport) CancelRequest(req *http.Request)","file":"staging/src/k8s.io/client-go/transport/token_source.go","code":"func (tst *tokenSourceTransport) CancelRequest(req *http.Request) {\n\tif req.Header.Get(\"Authorization\") != \"\" {\n\t\ttryCancelRequest(tst.base, req)\n\t\treturn\n\t}\n\ttryCancelRequest(tst.ort, req)\n}","line":{"from":117,"to":123}} {"id":100029153,"name":"WrappedRoundTripper","signature":"func (tst *tokenSourceTransport) WrappedRoundTripper() http.RoundTripper { return tst.base }","file":"staging/src/k8s.io/client-go/transport/token_source.go","code":"func (tst *tokenSourceTransport) WrappedRoundTripper() http.RoundTripper { return tst.base }","line":{"from":125,"to":125}} {"id":100029154,"name":"Token","signature":"func (ts *fileTokenSource) Token() (*oauth2.Token, error)","file":"staging/src/k8s.io/client-go/transport/token_source.go","code":"func (ts *fileTokenSource) Token() (*oauth2.Token, error) {\n\ttokb, err := os.ReadFile(ts.path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read token file %q: %v\", ts.path, err)\n\t}\n\ttok := strings.TrimSpace(string(tokb))\n\tif len(tok) == 0 {\n\t\treturn nil, fmt.Errorf(\"read empty token from file %q\", ts.path)\n\t}\n\n\treturn \u0026oauth2.Token{\n\t\tAccessToken: tok,\n\t\tExpiry: time.Now().Add(ts.period),\n\t}, nil\n}","line":{"from":134,"to":148}} {"id":100029155,"name":"Token","signature":"func (ts *cachingTokenSource) Token() (*oauth2.Token, error)","file":"staging/src/k8s.io/client-go/transport/token_source.go","code":"func (ts *cachingTokenSource) Token() (*oauth2.Token, error) {\n\tnow := ts.now()\n\t// fast path\n\tts.RLock()\n\ttok := ts.tok\n\tts.RUnlock()\n\n\tif tok != nil \u0026\u0026 tok.Expiry.Add(-1*ts.leeway).After(now) {\n\t\treturn tok, nil\n\t}\n\n\t// slow path\n\tts.Lock()\n\tdefer ts.Unlock()\n\tif tok := ts.tok; tok != nil \u0026\u0026 tok.Expiry.Add(-1*ts.leeway).After(now) {\n\t\treturn tok, nil\n\t}\n\n\ttok, err := ts.base.Token()\n\tif err != nil {\n\t\tif ts.tok == nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tklog.Errorf(\"Unable to rotate token: %v\", err)\n\t\treturn ts.tok, nil\n\t}\n\n\tts.t = ts.now()\n\tts.tok = tok\n\treturn tok, nil\n}","line":{"from":162,"to":192}} {"id":100029156,"name":"ResetTokenOlderThan","signature":"func (ts *cachingTokenSource) ResetTokenOlderThan(t time.Time)","file":"staging/src/k8s.io/client-go/transport/token_source.go","code":"func (ts *cachingTokenSource) ResetTokenOlderThan(t time.Time) {\n\tts.Lock()\n\tdefer ts.Unlock()\n\tif ts.t.Before(t) {\n\t\tts.tok = nil\n\t\tts.t = time.Time{}\n\t}\n}","line":{"from":194,"to":201}} {"id":100029157,"name":"New","signature":"func New(config *Config) (http.RoundTripper, error)","file":"staging/src/k8s.io/client-go/transport/transport.go","code":"// New returns an http.RoundTripper that will provide the authentication\n// or transport level security defined by the provided Config.\nfunc New(config *Config) (http.RoundTripper, error) {\n\t// Set transport level security\n\tif config.Transport != nil \u0026\u0026 (config.HasCA() || config.HasCertAuth() || config.HasCertCallback() || config.TLS.Insecure) {\n\t\treturn nil, fmt.Errorf(\"using a custom transport with TLS certificate options or the insecure flag is not allowed\")\n\t}\n\n\tif !isValidHolders(config) {\n\t\treturn nil, fmt.Errorf(\"misconfigured holder for dialer or cert callback\")\n\t}\n\n\tvar (\n\t\trt http.RoundTripper\n\t\terr error\n\t)\n\n\tif config.Transport != nil {\n\t\trt = config.Transport\n\t} else {\n\t\trt, err = tlsCache.get(config)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn HTTPWrappersForConfig(config, rt)\n}","line":{"from":34,"to":61}} {"id":100029158,"name":"isValidHolders","signature":"func isValidHolders(config *Config) bool","file":"staging/src/k8s.io/client-go/transport/transport.go","code":"func isValidHolders(config *Config) bool {\n\tif config.TLS.GetCertHolder != nil \u0026\u0026 config.TLS.GetCertHolder.GetCert == nil {\n\t\treturn false\n\t}\n\n\tif config.DialHolder != nil \u0026\u0026 config.DialHolder.Dial == nil {\n\t\treturn false\n\t}\n\n\treturn true\n}","line":{"from":63,"to":73}} {"id":100029159,"name":"TLSConfigFor","signature":"func TLSConfigFor(c *Config) (*tls.Config, error)","file":"staging/src/k8s.io/client-go/transport/transport.go","code":"// TLSConfigFor returns a tls.Config that will provide the transport level security defined\n// by the provided Config. Will return nil if no transport level security is requested.\nfunc TLSConfigFor(c *Config) (*tls.Config, error) {\n\tif !(c.HasCA() || c.HasCertAuth() || c.HasCertCallback() || c.TLS.Insecure || len(c.TLS.ServerName) \u003e 0 || len(c.TLS.NextProtos) \u003e 0) {\n\t\treturn nil, nil\n\t}\n\tif c.HasCA() \u0026\u0026 c.TLS.Insecure {\n\t\treturn nil, fmt.Errorf(\"specifying a root certificates file with the insecure flag is not allowed\")\n\t}\n\tif err := loadTLSFiles(c); err != nil {\n\t\treturn nil, err\n\t}\n\n\ttlsConfig := \u0026tls.Config{\n\t\t// Can't use SSLv3 because of POODLE and BEAST\n\t\t// Can't use TLSv1.0 because of POODLE and BEAST using CBC cipher\n\t\t// Can't use TLSv1.1 because of RC4 cipher usage\n\t\tMinVersion: tls.VersionTLS12,\n\t\tInsecureSkipVerify: c.TLS.Insecure,\n\t\tServerName: c.TLS.ServerName,\n\t\tNextProtos: c.TLS.NextProtos,\n\t}\n\n\tif c.HasCA() {\n\t\trootCAs, err := rootCertPool(c.TLS.CAData)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to load root certificates: %w\", err)\n\t\t}\n\t\ttlsConfig.RootCAs = rootCAs\n\t}\n\n\tvar staticCert *tls.Certificate\n\t// Treat cert as static if either key or cert was data, not a file\n\tif c.HasCertAuth() \u0026\u0026 !c.TLS.ReloadTLSFiles {\n\t\t// If key/cert were provided, verify them before setting up\n\t\t// tlsConfig.GetClientCertificate.\n\t\tcert, err := tls.X509KeyPair(c.TLS.CertData, c.TLS.KeyData)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstaticCert = \u0026cert\n\t}\n\n\tvar dynamicCertLoader func() (*tls.Certificate, error)\n\tif c.TLS.ReloadTLSFiles {\n\t\tdynamicCertLoader = cachingCertificateLoader(c.TLS.CertFile, c.TLS.KeyFile)\n\t}\n\n\tif c.HasCertAuth() || c.HasCertCallback() {\n\t\ttlsConfig.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) {\n\t\t\t// Note: static key/cert data always take precedence over cert\n\t\t\t// callback.\n\t\t\tif staticCert != nil {\n\t\t\t\treturn staticCert, nil\n\t\t\t}\n\t\t\t// key/cert files lead to ReloadTLSFiles being set - takes precedence over cert callback\n\t\t\tif dynamicCertLoader != nil {\n\t\t\t\treturn dynamicCertLoader()\n\t\t\t}\n\t\t\tif c.HasCertCallback() {\n\t\t\t\tcert, err := c.TLS.GetCertHolder.GetCert()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\t// GetCert may return empty value, meaning no cert.\n\t\t\t\tif cert != nil {\n\t\t\t\t\treturn cert, nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Both c.TLS.CertData/KeyData were unset and GetCert didn't return\n\t\t\t// anything. Return an empty tls.Certificate, no client cert will\n\t\t\t// be sent to the server.\n\t\t\treturn \u0026tls.Certificate{}, nil\n\t\t}\n\t}\n\n\treturn tlsConfig, nil\n}","line":{"from":75,"to":153}} {"id":100029160,"name":"loadTLSFiles","signature":"func loadTLSFiles(c *Config) error","file":"staging/src/k8s.io/client-go/transport/transport.go","code":"// loadTLSFiles copies the data from the CertFile, KeyFile, and CAFile fields into the CertData,\n// KeyData, and CAFile fields, or returns an error. If no error is returned, all three fields are\n// either populated or were empty to start.\nfunc loadTLSFiles(c *Config) error {\n\tvar err error\n\tc.TLS.CAData, err = dataFromSliceOrFile(c.TLS.CAData, c.TLS.CAFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Check that we are purely loading from files\n\tif len(c.TLS.CertFile) \u003e 0 \u0026\u0026 len(c.TLS.CertData) == 0 \u0026\u0026 len(c.TLS.KeyFile) \u003e 0 \u0026\u0026 len(c.TLS.KeyData) == 0 {\n\t\tc.TLS.ReloadTLSFiles = true\n\t}\n\n\tc.TLS.CertData, err = dataFromSliceOrFile(c.TLS.CertData, c.TLS.CertFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.TLS.KeyData, err = dataFromSliceOrFile(c.TLS.KeyData, c.TLS.KeyFile)\n\treturn err\n}","line":{"from":155,"to":177}} {"id":100029161,"name":"dataFromSliceOrFile","signature":"func dataFromSliceOrFile(data []byte, file string) ([]byte, error)","file":"staging/src/k8s.io/client-go/transport/transport.go","code":"// dataFromSliceOrFile returns data from the slice (if non-empty), or from the file,\n// or an error if an error occurred reading the file\nfunc dataFromSliceOrFile(data []byte, file string) ([]byte, error) {\n\tif len(data) \u003e 0 {\n\t\treturn data, nil\n\t}\n\tif len(file) \u003e 0 {\n\t\tfileData, err := os.ReadFile(file)\n\t\tif err != nil {\n\t\t\treturn []byte{}, err\n\t\t}\n\t\treturn fileData, nil\n\t}\n\treturn nil, nil\n}","line":{"from":179,"to":193}} {"id":100029162,"name":"rootCertPool","signature":"func rootCertPool(caData []byte) (*x509.CertPool, error)","file":"staging/src/k8s.io/client-go/transport/transport.go","code":"// rootCertPool returns nil if caData is empty. When passed along, this will mean \"use system CAs\".\n// When caData is not empty, it will be the ONLY information used in the CertPool.\nfunc rootCertPool(caData []byte) (*x509.CertPool, error) {\n\t// What we really want is a copy of x509.systemRootsPool, but that isn't exposed. It's difficult to build (see the go\n\t// code for a look at the platform specific insanity), so we'll use the fact that RootCAs == nil gives us the system values\n\t// It doesn't allow trusting either/or, but hopefully that won't be an issue\n\tif len(caData) == 0 {\n\t\treturn nil, nil\n\t}\n\n\t// if we have caData, use it\n\tcertPool := x509.NewCertPool()\n\tif ok := certPool.AppendCertsFromPEM(caData); !ok {\n\t\treturn nil, createErrorParsingCAData(caData)\n\t}\n\treturn certPool, nil\n}","line":{"from":195,"to":211}} {"id":100029163,"name":"createErrorParsingCAData","signature":"func createErrorParsingCAData(pemCerts []byte) error","file":"staging/src/k8s.io/client-go/transport/transport.go","code":"// createErrorParsingCAData ALWAYS returns an error. We call it because know we failed to AppendCertsFromPEM\n// but we don't know the specific error because that API is just true/false\nfunc createErrorParsingCAData(pemCerts []byte) error {\n\tfor len(pemCerts) \u003e 0 {\n\t\tvar block *pem.Block\n\t\tblock, pemCerts = pem.Decode(pemCerts)\n\t\tif block == nil {\n\t\t\treturn fmt.Errorf(\"unable to parse bytes as PEM block\")\n\t\t}\n\n\t\tif block.Type != \"CERTIFICATE\" || len(block.Headers) != 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif _, err := x509.ParseCertificate(block.Bytes); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to parse certificate: %w\", err)\n\t\t}\n\t}\n\treturn fmt.Errorf(\"no valid certificate authority data seen\")\n}","line":{"from":213,"to":232}} {"id":100029164,"name":"Wrappers","signature":"func Wrappers(fns ...WrapperFunc) WrapperFunc","file":"staging/src/k8s.io/client-go/transport/transport.go","code":"// Wrappers accepts any number of wrappers and returns a wrapper\n// function that is the equivalent of calling each of them in order. Nil\n// values are ignored, which makes this function convenient for incrementally\n// wrapping a function.\nfunc Wrappers(fns ...WrapperFunc) WrapperFunc {\n\tif len(fns) == 0 {\n\t\treturn nil\n\t}\n\t// optimize the common case of wrapping a possibly nil transport wrapper\n\t// with an additional wrapper\n\tif len(fns) == 2 \u0026\u0026 fns[0] == nil {\n\t\treturn fns[1]\n\t}\n\treturn func(rt http.RoundTripper) http.RoundTripper {\n\t\tbase := rt\n\t\tfor _, fn := range fns {\n\t\t\tif fn != nil {\n\t\t\t\tbase = fn(base)\n\t\t\t}\n\t\t}\n\t\treturn base\n\t}\n}","line":{"from":239,"to":261}} {"id":100029165,"name":"ContextCanceller","signature":"func ContextCanceller(ctx context.Context, err error) WrapperFunc","file":"staging/src/k8s.io/client-go/transport/transport.go","code":"// ContextCanceller prevents new requests after the provided context is finished.\n// err is returned when the context is closed, allowing the caller to provide a context\n// appropriate error.\nfunc ContextCanceller(ctx context.Context, err error) WrapperFunc {\n\treturn func(rt http.RoundTripper) http.RoundTripper {\n\t\treturn \u0026contextCanceller{\n\t\t\tctx: ctx,\n\t\t\trt: rt,\n\t\t\terr: err,\n\t\t}\n\t}\n}","line":{"from":263,"to":274}} {"id":100029166,"name":"RoundTrip","signature":"func (b *contextCanceller) RoundTrip(req *http.Request) (*http.Response, error)","file":"staging/src/k8s.io/client-go/transport/transport.go","code":"func (b *contextCanceller) RoundTrip(req *http.Request) (*http.Response, error) {\n\tselect {\n\tcase \u003c-b.ctx.Done():\n\t\treturn nil, b.err\n\tdefault:\n\t\treturn b.rt.RoundTrip(req)\n\t}\n}","line":{"from":282,"to":289}} {"id":100029167,"name":"tryCancelRequest","signature":"func tryCancelRequest(rt http.RoundTripper, req *http.Request)","file":"staging/src/k8s.io/client-go/transport/transport.go","code":"func tryCancelRequest(rt http.RoundTripper, req *http.Request) {\n\ttype canceler interface {\n\t\tCancelRequest(*http.Request)\n\t}\n\tswitch rt := rt.(type) {\n\tcase canceler:\n\t\trt.CancelRequest(req)\n\tcase utilnet.RoundTripperWrapper:\n\t\ttryCancelRequest(rt.WrappedRoundTripper(), req)\n\tdefault:\n\t\tklog.Warningf(\"Unable to cancel request for %T\", rt)\n\t}\n}","line":{"from":291,"to":303}} {"id":100029168,"name":"isStale","signature":"func (c *certificateCacheEntry) isStale() bool","file":"staging/src/k8s.io/client-go/transport/transport.go","code":"// isStale returns true when this cache entry is too old to be usable\nfunc (c *certificateCacheEntry) isStale() bool {\n\treturn time.Since(c.birth) \u003e time.Second\n}","line":{"from":311,"to":314}} {"id":100029169,"name":"newCertificateCacheEntry","signature":"func newCertificateCacheEntry(certFile, keyFile string) certificateCacheEntry","file":"staging/src/k8s.io/client-go/transport/transport.go","code":"func newCertificateCacheEntry(certFile, keyFile string) certificateCacheEntry {\n\tcert, err := tls.LoadX509KeyPair(certFile, keyFile)\n\treturn certificateCacheEntry{cert: \u0026cert, err: err, birth: time.Now()}\n}","line":{"from":316,"to":319}} {"id":100029170,"name":"cachingCertificateLoader","signature":"func cachingCertificateLoader(certFile, keyFile string) func() (*tls.Certificate, error)","file":"staging/src/k8s.io/client-go/transport/transport.go","code":"// cachingCertificateLoader ensures that we don't hammer the filesystem when opening many connections\n// the underlying cert files are read at most once every second\nfunc cachingCertificateLoader(certFile, keyFile string) func() (*tls.Certificate, error) {\n\tcurrent := newCertificateCacheEntry(certFile, keyFile)\n\tvar currentMtx sync.RWMutex\n\n\treturn func() (*tls.Certificate, error) {\n\t\tcurrentMtx.RLock()\n\t\tif current.isStale() {\n\t\t\tcurrentMtx.RUnlock()\n\n\t\t\tcurrentMtx.Lock()\n\t\t\tdefer currentMtx.Unlock()\n\n\t\t\tif current.isStale() {\n\t\t\t\tcurrent = newCertificateCacheEntry(certFile, keyFile)\n\t\t\t}\n\t\t} else {\n\t\t\tdefer currentMtx.RUnlock()\n\t\t}\n\n\t\treturn current.cert, current.err\n\t}\n}","line":{"from":321,"to":344}} {"id":100029171,"name":"NewSelfSignedCACert","signature":"func NewSelfSignedCACert(cfg Config, key crypto.Signer) (*x509.Certificate, error)","file":"staging/src/k8s.io/client-go/util/cert/cert.go","code":"// NewSelfSignedCACert creates a CA certificate\nfunc NewSelfSignedCACert(cfg Config, key crypto.Signer) (*x509.Certificate, error) {\n\tnow := time.Now()\n\t// returns a uniform random value in [0, max-1), then add 1 to serial to make it a uniform random value in [1, max).\n\tserial, err := cryptorand.Int(cryptorand.Reader, new(big.Int).SetInt64(math.MaxInt64-1))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tserial = new(big.Int).Add(serial, big.NewInt(1))\n\ttmpl := x509.Certificate{\n\t\tSerialNumber: serial,\n\t\tSubject: pkix.Name{\n\t\t\tCommonName: cfg.CommonName,\n\t\t\tOrganization: cfg.Organization,\n\t\t},\n\t\tDNSNames: []string{cfg.CommonName},\n\t\tNotBefore: now.UTC(),\n\t\tNotAfter: now.Add(duration365d * 10).UTC(),\n\t\tKeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,\n\t\tBasicConstraintsValid: true,\n\t\tIsCA: true,\n\t}\n\n\tcertDERBytes, err := x509.CreateCertificate(cryptorand.Reader, \u0026tmpl, \u0026tmpl, key.Public(), key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn x509.ParseCertificate(certDERBytes)\n}","line":{"from":58,"to":86}} {"id":100029172,"name":"GenerateSelfSignedCertKey","signature":"func GenerateSelfSignedCertKey(host string, alternateIPs []net.IP, alternateDNS []string) ([]byte, []byte, error)","file":"staging/src/k8s.io/client-go/util/cert/cert.go","code":"// GenerateSelfSignedCertKey creates a self-signed certificate and key for the given host.\n// Host may be an IP or a DNS name\n// You may also specify additional subject alt names (either ip or dns names) for the certificate.\nfunc GenerateSelfSignedCertKey(host string, alternateIPs []net.IP, alternateDNS []string) ([]byte, []byte, error) {\n\treturn GenerateSelfSignedCertKeyWithFixtures(host, alternateIPs, alternateDNS, \"\")\n}","line":{"from":88,"to":93}} {"id":100029173,"name":"GenerateSelfSignedCertKeyWithFixtures","signature":"func GenerateSelfSignedCertKeyWithFixtures(host string, alternateIPs []net.IP, alternateDNS []string, fixtureDirectory string) ([]byte, []byte, error)","file":"staging/src/k8s.io/client-go/util/cert/cert.go","code":"// GenerateSelfSignedCertKeyWithFixtures creates a self-signed certificate and key for the given host.\n// Host may be an IP or a DNS name. You may also specify additional subject alt names (either ip or dns names)\n// for the certificate.\n//\n// If fixtureDirectory is non-empty, it is a directory path which can contain pre-generated certs. The format is:\n// \u003chost\u003e_\u003cip\u003e-\u003cip\u003e_\u003calternateDNS\u003e-\u003calternateDNS\u003e.crt\n// \u003chost\u003e_\u003cip\u003e-\u003cip\u003e_\u003calternateDNS\u003e-\u003calternateDNS\u003e.key\n// Certs/keys not existing in that directory are created.\nfunc GenerateSelfSignedCertKeyWithFixtures(host string, alternateIPs []net.IP, alternateDNS []string, fixtureDirectory string) ([]byte, []byte, error) {\n\tvalidFrom := time.Now().Add(-time.Hour) // valid an hour earlier to avoid flakes due to clock skew\n\tmaxAge := time.Hour * 24 * 365 // one year self-signed certs\n\n\tbaseName := fmt.Sprintf(\"%s_%s_%s\", host, strings.Join(ipsToStrings(alternateIPs), \"-\"), strings.Join(alternateDNS, \"-\"))\n\tcertFixturePath := filepath.Join(fixtureDirectory, baseName+\".crt\")\n\tkeyFixturePath := filepath.Join(fixtureDirectory, baseName+\".key\")\n\tif len(fixtureDirectory) \u003e 0 {\n\t\tcert, err := os.ReadFile(certFixturePath)\n\t\tif err == nil {\n\t\t\tkey, err := os.ReadFile(keyFixturePath)\n\t\t\tif err == nil {\n\t\t\t\treturn cert, key, nil\n\t\t\t}\n\t\t\treturn nil, nil, fmt.Errorf(\"cert %s can be read, but key %s cannot: %v\", certFixturePath, keyFixturePath, err)\n\t\t}\n\t\tmaxAge = 100 * time.Hour * 24 * 365 // 100 years fixtures\n\t}\n\n\tcaKey, err := rsa.GenerateKey(cryptorand.Reader, 2048)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\t// returns a uniform random value in [0, max-1), then add 1 to serial to make it a uniform random value in [1, max).\n\tserial, err := cryptorand.Int(cryptorand.Reader, new(big.Int).SetInt64(math.MaxInt64-1))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tserial = new(big.Int).Add(serial, big.NewInt(1))\n\tcaTemplate := x509.Certificate{\n\t\tSerialNumber: serial,\n\t\tSubject: pkix.Name{\n\t\t\tCommonName: fmt.Sprintf(\"%s-ca@%d\", host, time.Now().Unix()),\n\t\t},\n\t\tNotBefore: validFrom,\n\t\tNotAfter: validFrom.Add(maxAge),\n\n\t\tKeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,\n\t\tBasicConstraintsValid: true,\n\t\tIsCA: true,\n\t}\n\n\tcaDERBytes, err := x509.CreateCertificate(cryptorand.Reader, \u0026caTemplate, \u0026caTemplate, \u0026caKey.PublicKey, caKey)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tcaCertificate, err := x509.ParseCertificate(caDERBytes)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tpriv, err := rsa.GenerateKey(cryptorand.Reader, 2048)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\t// returns a uniform random value in [0, max-1), then add 1 to serial to make it a uniform random value in [1, max).\n\tserial, err = cryptorand.Int(cryptorand.Reader, new(big.Int).SetInt64(math.MaxInt64-1))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tserial = new(big.Int).Add(serial, big.NewInt(1))\n\ttemplate := x509.Certificate{\n\t\tSerialNumber: serial,\n\t\tSubject: pkix.Name{\n\t\t\tCommonName: fmt.Sprintf(\"%s@%d\", host, time.Now().Unix()),\n\t\t},\n\t\tNotBefore: validFrom,\n\t\tNotAfter: validFrom.Add(maxAge),\n\n\t\tKeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,\n\t\tExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},\n\t\tBasicConstraintsValid: true,\n\t}\n\n\tif ip := netutils.ParseIPSloppy(host); ip != nil {\n\t\ttemplate.IPAddresses = append(template.IPAddresses, ip)\n\t} else {\n\t\ttemplate.DNSNames = append(template.DNSNames, host)\n\t}\n\n\ttemplate.IPAddresses = append(template.IPAddresses, alternateIPs...)\n\ttemplate.DNSNames = append(template.DNSNames, alternateDNS...)\n\n\tderBytes, err := x509.CreateCertificate(cryptorand.Reader, \u0026template, caCertificate, \u0026priv.PublicKey, caKey)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Generate cert, followed by ca\n\tcertBuffer := bytes.Buffer{}\n\tif err := pem.Encode(\u0026certBuffer, \u0026pem.Block{Type: CertificateBlockType, Bytes: derBytes}); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif err := pem.Encode(\u0026certBuffer, \u0026pem.Block{Type: CertificateBlockType, Bytes: caDERBytes}); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Generate key\n\tkeyBuffer := bytes.Buffer{}\n\tif err := pem.Encode(\u0026keyBuffer, \u0026pem.Block{Type: keyutil.RSAPrivateKeyBlockType, Bytes: x509.MarshalPKCS1PrivateKey(priv)}); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif len(fixtureDirectory) \u003e 0 {\n\t\tif err := os.WriteFile(certFixturePath, certBuffer.Bytes(), 0644); err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"failed to write cert fixture to %s: %v\", certFixturePath, err)\n\t\t}\n\t\tif err := os.WriteFile(keyFixturePath, keyBuffer.Bytes(), 0600); err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"failed to write key fixture to %s: %v\", certFixturePath, err)\n\t\t}\n\t}\n\n\treturn certBuffer.Bytes(), keyBuffer.Bytes(), nil\n}","line":{"from":95,"to":217}} {"id":100029174,"name":"ipsToStrings","signature":"func ipsToStrings(ips []net.IP) []string","file":"staging/src/k8s.io/client-go/util/cert/cert.go","code":"func ipsToStrings(ips []net.IP) []string {\n\tss := make([]string, 0, len(ips))\n\tfor _, ip := range ips {\n\t\tss = append(ss, ip.String())\n\t}\n\treturn ss\n}","line":{"from":219,"to":225}} {"id":100029175,"name":"MakeCSR","signature":"func MakeCSR(privateKey interface{}, subject *pkix.Name, dnsSANs []string, ipSANs []net.IP) (csr []byte, err error)","file":"staging/src/k8s.io/client-go/util/cert/csr.go","code":"// MakeCSR generates a PEM-encoded CSR using the supplied private key, subject, and SANs.\n// All key types that are implemented via crypto.Signer are supported (This includes *rsa.PrivateKey and *ecdsa.PrivateKey.)\nfunc MakeCSR(privateKey interface{}, subject *pkix.Name, dnsSANs []string, ipSANs []net.IP) (csr []byte, err error) {\n\ttemplate := \u0026x509.CertificateRequest{\n\t\tSubject: *subject,\n\t\tDNSNames: dnsSANs,\n\t\tIPAddresses: ipSANs,\n\t}\n\n\treturn MakeCSRFromTemplate(privateKey, template)\n}","line":{"from":28,"to":38}} {"id":100029176,"name":"MakeCSRFromTemplate","signature":"func MakeCSRFromTemplate(privateKey interface{}, template *x509.CertificateRequest) ([]byte, error)","file":"staging/src/k8s.io/client-go/util/cert/csr.go","code":"// MakeCSRFromTemplate generates a PEM-encoded CSR using the supplied private\n// key and certificate request as a template. All key types that are\n// implemented via crypto.Signer are supported (This includes *rsa.PrivateKey\n// and *ecdsa.PrivateKey.)\nfunc MakeCSRFromTemplate(privateKey interface{}, template *x509.CertificateRequest) ([]byte, error) {\n\tt := *template\n\tt.SignatureAlgorithm = sigType(privateKey)\n\n\tcsrDER, err := x509.CreateCertificateRequest(cryptorand.Reader, \u0026t, privateKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcsrPemBlock := \u0026pem.Block{\n\t\tType: CertificateRequestBlockType,\n\t\tBytes: csrDER,\n\t}\n\n\treturn pem.EncodeToMemory(csrPemBlock), nil\n}","line":{"from":40,"to":59}} {"id":100029177,"name":"sigType","signature":"func sigType(privateKey interface{}) x509.SignatureAlgorithm","file":"staging/src/k8s.io/client-go/util/cert/csr.go","code":"func sigType(privateKey interface{}) x509.SignatureAlgorithm {\n\t// Customize the signature for RSA keys, depending on the key size\n\tif privateKey, ok := privateKey.(*rsa.PrivateKey); ok {\n\t\tkeySize := privateKey.N.BitLen()\n\t\tswitch {\n\t\tcase keySize \u003e= 4096:\n\t\t\treturn x509.SHA512WithRSA\n\t\tcase keySize \u003e= 3072:\n\t\t\treturn x509.SHA384WithRSA\n\t\tdefault:\n\t\t\treturn x509.SHA256WithRSA\n\t\t}\n\t}\n\treturn x509.UnknownSignatureAlgorithm\n}","line":{"from":61,"to":75}} {"id":100029178,"name":"CanReadCertAndKey","signature":"func CanReadCertAndKey(certPath, keyPath string) (bool, error)","file":"staging/src/k8s.io/client-go/util/cert/io.go","code":"// CanReadCertAndKey returns true if the certificate and key files already exists,\n// otherwise returns false. If lost one of cert and key, returns error.\nfunc CanReadCertAndKey(certPath, keyPath string) (bool, error) {\n\tcertReadable := canReadFile(certPath)\n\tkeyReadable := canReadFile(keyPath)\n\n\tif certReadable == false \u0026\u0026 keyReadable == false {\n\t\treturn false, nil\n\t}\n\n\tif certReadable == false {\n\t\treturn false, fmt.Errorf(\"error reading %s, certificate and key must be supplied as a pair\", certPath)\n\t}\n\n\tif keyReadable == false {\n\t\treturn false, fmt.Errorf(\"error reading %s, certificate and key must be supplied as a pair\", keyPath)\n\t}\n\n\treturn true, nil\n}","line":{"from":26,"to":45}} {"id":100029179,"name":"canReadFile","signature":"func canReadFile(path string) bool","file":"staging/src/k8s.io/client-go/util/cert/io.go","code":"// If the file represented by path exists and\n// readable, returns true otherwise returns false.\nfunc canReadFile(path string) bool {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tdefer f.Close()\n\n\treturn true\n}","line":{"from":47,"to":58}} {"id":100029180,"name":"WriteCert","signature":"func WriteCert(certPath string, data []byte) error","file":"staging/src/k8s.io/client-go/util/cert/io.go","code":"// WriteCert writes the pem-encoded certificate data to certPath.\n// The certificate file will be created with file mode 0644.\n// If the certificate file already exists, it will be overwritten.\n// The parent directory of the certPath will be created as needed with file mode 0755.\nfunc WriteCert(certPath string, data []byte) error {\n\tif err := os.MkdirAll(filepath.Dir(certPath), os.FileMode(0755)); err != nil {\n\t\treturn err\n\t}\n\treturn os.WriteFile(certPath, data, os.FileMode(0644))\n}","line":{"from":60,"to":69}} {"id":100029181,"name":"NewPool","signature":"func NewPool(filename string) (*x509.CertPool, error)","file":"staging/src/k8s.io/client-go/util/cert/io.go","code":"// NewPool returns an x509.CertPool containing the certificates in the given PEM-encoded file.\n// Returns an error if the file could not be read, a certificate could not be parsed, or if the file does not contain any certificates\nfunc NewPool(filename string) (*x509.CertPool, error) {\n\tpemBlock, err := os.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpool, err := NewPoolFromBytes(pemBlock)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating pool from %s: %s\", filename, err)\n\t}\n\treturn pool, nil\n}","line":{"from":71,"to":84}} {"id":100029182,"name":"NewPoolFromBytes","signature":"func NewPoolFromBytes(pemBlock []byte) (*x509.CertPool, error)","file":"staging/src/k8s.io/client-go/util/cert/io.go","code":"// NewPoolFromBytes returns an x509.CertPool containing the certificates in the given PEM-encoded bytes.\n// Returns an error if the file could not be read, a certificate could not be parsed, or if the file does not contain any certificates\nfunc NewPoolFromBytes(pemBlock []byte) (*x509.CertPool, error) {\n\tcerts, err := ParseCertsPEM(pemBlock)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpool := x509.NewCertPool()\n\tfor _, cert := range certs {\n\t\tpool.AddCert(cert)\n\t}\n\treturn pool, nil\n}","line":{"from":86,"to":98}} {"id":100029183,"name":"CertsFromFile","signature":"func CertsFromFile(file string) ([]*x509.Certificate, error)","file":"staging/src/k8s.io/client-go/util/cert/io.go","code":"// CertsFromFile returns the x509.Certificates contained in the given PEM-encoded file.\n// Returns an error if the file could not be read, a certificate could not be parsed, or if the file does not contain any certificates\nfunc CertsFromFile(file string) ([]*x509.Certificate, error) {\n\tpemBlock, err := os.ReadFile(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcerts, err := ParseCertsPEM(pemBlock)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading %s: %s\", file, err)\n\t}\n\treturn certs, nil\n}","line":{"from":100,"to":112}} {"id":100029184,"name":"ParseCertsPEM","signature":"func ParseCertsPEM(pemCerts []byte) ([]*x509.Certificate, error)","file":"staging/src/k8s.io/client-go/util/cert/pem.go","code":"// ParseCertsPEM returns the x509.Certificates contained in the given PEM-encoded byte array\n// Returns an error if a certificate could not be parsed, or if the data does not contain any certificates\nfunc ParseCertsPEM(pemCerts []byte) ([]*x509.Certificate, error) {\n\tok := false\n\tcerts := []*x509.Certificate{}\n\tfor len(pemCerts) \u003e 0 {\n\t\tvar block *pem.Block\n\t\tblock, pemCerts = pem.Decode(pemCerts)\n\t\tif block == nil {\n\t\t\tbreak\n\t\t}\n\t\t// Only use PEM \"CERTIFICATE\" blocks without extra headers\n\t\tif block.Type != CertificateBlockType || len(block.Headers) != 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tcert, err := x509.ParseCertificate(block.Bytes)\n\t\tif err != nil {\n\t\t\treturn certs, err\n\t\t}\n\n\t\tcerts = append(certs, cert)\n\t\tok = true\n\t}\n\n\tif !ok {\n\t\treturn certs, errors.New(\"data does not contain any valid RSA or ECDSA certificates\")\n\t}\n\treturn certs, nil\n}","line":{"from":33,"to":62}} {"id":100029185,"name":"EncodeCertificates","signature":"func EncodeCertificates(certs ...*x509.Certificate) ([]byte, error)","file":"staging/src/k8s.io/client-go/util/cert/pem.go","code":"// EncodeCertificates returns the PEM-encoded byte array that represents by the specified certs.\nfunc EncodeCertificates(certs ...*x509.Certificate) ([]byte, error) {\n\tb := bytes.Buffer{}\n\tfor _, cert := range certs {\n\t\tif err := pem.Encode(\u0026b, \u0026pem.Block{Type: CertificateBlockType, Bytes: cert.Raw}); err != nil {\n\t\t\treturn []byte{}, err\n\t\t}\n\t}\n\treturn b.Bytes(), nil\n}","line":{"from":64,"to":73}} {"id":100029186,"name":"GetClientCANames","signature":"func GetClientCANames(apiHost string) ([]string, error)","file":"staging/src/k8s.io/client-go/util/cert/server_inspection.go","code":"// GetClientCANames gets the CA names for client certs that a server accepts. This is useful when inspecting the\n// state of particular servers. apiHost is \"host:port\"\nfunc GetClientCANames(apiHost string) ([]string, error) {\n\t// when we run this the second time, we know which one we are expecting\n\tacceptableCAs := []string{}\n\ttlsConfig := \u0026tls.Config{\n\t\tInsecureSkipVerify: true, // this is insecure to always get to the GetClientCertificate\n\t\tGetClientCertificate: func(hello *tls.CertificateRequestInfo) (*tls.Certificate, error) {\n\t\t\tacceptableCAs = []string{}\n\t\t\tfor _, curr := range hello.AcceptableCAs {\n\t\t\t\tacceptableCAs = append(acceptableCAs, string(curr))\n\t\t\t}\n\t\t\treturn \u0026tls.Certificate{}, nil\n\t\t},\n\t}\n\n\tconn, err := tls.Dial(\"tcp\", apiHost, tlsConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := conn.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn acceptableCAs, nil\n}","line":{"from":27,"to":52}} {"id":100029187,"name":"GetClientCANamesForURL","signature":"func GetClientCANamesForURL(kubeConfigURL string) ([]string, error)","file":"staging/src/k8s.io/client-go/util/cert/server_inspection.go","code":"// GetClientCANamesForURL is GetClientCANames against a URL string like we use in kubeconfigs\nfunc GetClientCANamesForURL(kubeConfigURL string) ([]string, error) {\n\tapiserverURL, err := url.Parse(kubeConfigURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn GetClientCANames(apiserverURL.Host)\n}","line":{"from":54,"to":61}} {"id":100029188,"name":"GetServingCertificates","signature":"func GetServingCertificates(apiHost, serverName string) ([]*x509.Certificate, [][]byte, error)","file":"staging/src/k8s.io/client-go/util/cert/server_inspection.go","code":"// GetServingCertificates returns the x509 certs used by a server as certificates and pem encoded bytes.\n// The serverName is optional for specifying a different name to get SNI certificates. apiHost is \"host:port\"\nfunc GetServingCertificates(apiHost, serverName string) ([]*x509.Certificate, [][]byte, error) {\n\ttlsConfig := \u0026tls.Config{\n\t\tInsecureSkipVerify: true, // this is insecure so that we always get connected\n\t}\n\t// if a name is specified for SNI, set it.\n\tif len(serverName) \u003e 0 {\n\t\ttlsConfig.ServerName = serverName\n\t}\n\n\tconn, err := tls.Dial(\"tcp\", apiHost, tlsConfig)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif err = conn.Close(); err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to close connection : %v\", err)\n\t}\n\n\tpeerCerts := conn.ConnectionState().PeerCertificates\n\tpeerCertBytes := [][]byte{}\n\tfor _, a := range peerCerts {\n\t\tactualCert, err := EncodeCertificates(a)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tpeerCertBytes = append(peerCertBytes, []byte(strings.TrimSpace(string(actualCert))))\n\t}\n\n\treturn peerCerts, peerCertBytes, err\n}","line":{"from":63,"to":93}} {"id":100029189,"name":"GetServingCertificatesForURL","signature":"func GetServingCertificatesForURL(kubeConfigURL, serverName string) ([]*x509.Certificate, [][]byte, error)","file":"staging/src/k8s.io/client-go/util/cert/server_inspection.go","code":"// GetServingCertificatesForURL is GetServingCertificates against a URL string like we use in kubeconfigs\nfunc GetServingCertificatesForURL(kubeConfigURL, serverName string) ([]*x509.Certificate, [][]byte, error) {\n\tapiserverURL, err := url.Parse(kubeConfigURL)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn GetServingCertificates(apiserverURL.Host, serverName)\n}","line":{"from":95,"to":102}} {"id":100029190,"name":"Error","signature":"func (e *NoCertKeyError) Error() string { return string(*e) }","file":"staging/src/k8s.io/client-go/util/certificate/certificate_manager.go","code":"func (e *NoCertKeyError) Error() string { return string(*e) }","line":{"from":255,"to":255}} {"id":100029191,"name":"NewManager","signature":"func NewManager(config *Config) (Manager, error)","file":"staging/src/k8s.io/client-go/util/certificate/certificate_manager.go","code":"// NewManager returns a new certificate manager. A certificate manager is\n// responsible for being the authoritative source of certificates in the\n// Kubelet and handling updates due to rotation.\nfunc NewManager(config *Config) (Manager, error) {\n\tcert, forceRotation, err := getCurrentCertificateOrBootstrap(\n\t\tconfig.CertificateStore,\n\t\tconfig.BootstrapCertificatePEM,\n\t\tconfig.BootstrapKeyPEM)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgetTemplate := config.GetTemplate\n\tif getTemplate == nil {\n\t\tgetTemplate = func() *x509.CertificateRequest { return config.Template }\n\t}\n\n\tif config.GetUsages != nil \u0026\u0026 config.Usages != nil {\n\t\treturn nil, errors.New(\"cannot specify both GetUsages and Usages\")\n\t}\n\tif config.GetUsages == nil \u0026\u0026 config.Usages == nil {\n\t\treturn nil, errors.New(\"either GetUsages or Usages should be specified\")\n\t}\n\tvar getUsages func(interface{}) []certificates.KeyUsage\n\tif config.GetUsages != nil {\n\t\tgetUsages = config.GetUsages\n\t} else {\n\t\tgetUsages = func(interface{}) []certificates.KeyUsage { return config.Usages }\n\t}\n\tm := manager{\n\t\tstopCh: make(chan struct{}),\n\t\tclientsetFn: config.ClientsetFn,\n\t\tgetTemplate: getTemplate,\n\t\tdynamicTemplate: config.GetTemplate != nil,\n\t\tsignerName: config.SignerName,\n\t\trequestedCertificateLifetime: config.RequestedCertificateLifetime,\n\t\tgetUsages: getUsages,\n\t\tcertStore: config.CertificateStore,\n\t\tcert: cert,\n\t\tforceRotation: forceRotation,\n\t\tcertificateRotation: config.CertificateRotation,\n\t\tcertificateRenewFailure: config.CertificateRenewFailure,\n\t\tnow: time.Now,\n\t}\n\n\tname := config.Name\n\tif len(name) == 0 {\n\t\tname = m.signerName\n\t}\n\tif len(name) == 0 {\n\t\tusages := getUsages(nil)\n\t\tswitch {\n\t\tcase hasKeyUsage(usages, certificates.UsageClientAuth):\n\t\t\tname = string(certificates.UsageClientAuth)\n\t\tdefault:\n\t\t\tname = \"certificate\"\n\t\t}\n\t}\n\n\tm.name = name\n\tm.logf = config.Logf\n\tif m.logf == nil {\n\t\tm.logf = func(format string, args ...interface{}) { klog.V(2).Infof(format, args...) }\n\t}\n\n\treturn \u0026m, nil\n}","line":{"from":294,"to":360}} {"id":100029192,"name":"Current","signature":"func (m *manager) Current() *tls.Certificate","file":"staging/src/k8s.io/client-go/util/certificate/certificate_manager.go","code":"// Current returns the currently selected certificate from the certificate\n// manager. This can be nil if the manager was initialized without a\n// certificate and has not yet received one from the\n// CertificateSigningRequestClient, or if the current cert has expired.\nfunc (m *manager) Current() *tls.Certificate {\n\tm.certAccessLock.RLock()\n\tdefer m.certAccessLock.RUnlock()\n\tif m.cert != nil \u0026\u0026 m.cert.Leaf != nil \u0026\u0026 m.now().After(m.cert.Leaf.NotAfter) {\n\t\tm.logf(\"%s: Current certificate is expired\", m.name)\n\t\treturn nil\n\t}\n\treturn m.cert\n}","line":{"from":362,"to":374}} {"id":100029193,"name":"ServerHealthy","signature":"func (m *manager) ServerHealthy() bool","file":"staging/src/k8s.io/client-go/util/certificate/certificate_manager.go","code":"// ServerHealthy returns true if the cert manager believes the server\n// is currently alive.\nfunc (m *manager) ServerHealthy() bool {\n\tm.certAccessLock.RLock()\n\tdefer m.certAccessLock.RUnlock()\n\treturn m.serverHealth\n}","line":{"from":376,"to":382}} {"id":100029194,"name":"Stop","signature":"func (m *manager) Stop()","file":"staging/src/k8s.io/client-go/util/certificate/certificate_manager.go","code":"// Stop terminates the manager.\nfunc (m *manager) Stop() {\n\tm.clientAccessLock.Lock()\n\tdefer m.clientAccessLock.Unlock()\n\tif m.stopped {\n\t\treturn\n\t}\n\tclose(m.stopCh)\n\tm.stopped = true\n}","line":{"from":384,"to":393}} {"id":100029195,"name":"Start","signature":"func (m *manager) Start()","file":"staging/src/k8s.io/client-go/util/certificate/certificate_manager.go","code":"// Start will start the background work of rotating the certificates.\nfunc (m *manager) Start() {\n\t// Certificate rotation depends on access to the API server certificate\n\t// signing API, so don't start the certificate manager if we don't have a\n\t// client.\n\tif m.clientsetFn == nil {\n\t\tm.logf(\"%s: Certificate rotation is not enabled, no connection to the apiserver\", m.name)\n\t\treturn\n\t}\n\tm.logf(\"%s: Certificate rotation is enabled\", m.name)\n\n\ttemplateChanged := make(chan struct{})\n\tgo wait.Until(func() {\n\t\tdeadline := m.nextRotationDeadline()\n\t\tif sleepInterval := deadline.Sub(m.now()); sleepInterval \u003e 0 {\n\t\t\tm.logf(\"%s: Waiting %v for next certificate rotation\", m.name, sleepInterval)\n\n\t\t\ttimer := time.NewTimer(sleepInterval)\n\t\t\tdefer timer.Stop()\n\n\t\t\tselect {\n\t\t\tcase \u003c-timer.C:\n\t\t\t\t// unblock when deadline expires\n\t\t\tcase \u003c-templateChanged:\n\t\t\t\t_, lastRequestTemplate := m.getLastRequest()\n\t\t\t\tif reflect.DeepEqual(lastRequestTemplate, m.getTemplate()) {\n\t\t\t\t\t// if the template now matches what we last requested, restart the rotation deadline loop\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tm.logf(\"%s: Certificate template changed, rotating\", m.name)\n\t\t\t}\n\t\t}\n\n\t\t// Don't enter rotateCerts and trigger backoff if we don't even have a template to request yet\n\t\tif m.getTemplate() == nil {\n\t\t\treturn\n\t\t}\n\n\t\tbackoff := wait.Backoff{\n\t\t\tDuration: 2 * time.Second,\n\t\t\tFactor: 2,\n\t\t\tJitter: 0.1,\n\t\t\tSteps: 5,\n\t\t}\n\t\tif err := wait.ExponentialBackoff(backoff, m.rotateCerts); err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"%s: Reached backoff limit, still unable to rotate certs: %v\", m.name, err))\n\t\t\twait.PollInfinite(32*time.Second, m.rotateCerts)\n\t\t}\n\t}, time.Second, m.stopCh)\n\n\tif m.dynamicTemplate {\n\t\tgo wait.Until(func() {\n\t\t\t// check if the current template matches what we last requested\n\t\t\tlastRequestCancel, lastRequestTemplate := m.getLastRequest()\n\n\t\t\tif !m.certSatisfiesTemplate() \u0026\u0026 !reflect.DeepEqual(lastRequestTemplate, m.getTemplate()) {\n\t\t\t\t// if the template is different, queue up an interrupt of the rotation deadline loop.\n\t\t\t\t// if we've requested a CSR that matches the new template by the time the interrupt is handled, the interrupt is disregarded.\n\t\t\t\tif lastRequestCancel != nil {\n\t\t\t\t\t// if we're currently waiting on a submitted request that no longer matches what we want, stop waiting\n\t\t\t\t\tlastRequestCancel()\n\t\t\t\t}\n\t\t\t\tselect {\n\t\t\t\tcase templateChanged \u003c- struct{}{}:\n\t\t\t\tcase \u003c-m.stopCh:\n\t\t\t\t}\n\t\t\t}\n\t\t}, time.Second, m.stopCh)\n\t}\n}","line":{"from":395,"to":464}} {"id":100029196,"name":"getCurrentCertificateOrBootstrap","signature":"func getCurrentCertificateOrBootstrap(","file":"staging/src/k8s.io/client-go/util/certificate/certificate_manager.go","code":"func getCurrentCertificateOrBootstrap(\n\tstore Store,\n\tbootstrapCertificatePEM []byte,\n\tbootstrapKeyPEM []byte) (cert *tls.Certificate, shouldRotate bool, errResult error) {\n\n\tcurrentCert, err := store.Current()\n\tif err == nil {\n\t\t// if the current cert is expired, fall back to the bootstrap cert\n\t\tif currentCert.Leaf != nil \u0026\u0026 time.Now().Before(currentCert.Leaf.NotAfter) {\n\t\t\treturn currentCert, false, nil\n\t\t}\n\t} else {\n\t\tif _, ok := err.(*NoCertKeyError); !ok {\n\t\t\treturn nil, false, err\n\t\t}\n\t}\n\n\tif bootstrapCertificatePEM == nil || bootstrapKeyPEM == nil {\n\t\treturn nil, true, nil\n\t}\n\n\tbootstrapCert, err := tls.X509KeyPair(bootstrapCertificatePEM, bootstrapKeyPEM)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\tif len(bootstrapCert.Certificate) \u003c 1 {\n\t\treturn nil, false, fmt.Errorf(\"no cert/key data found\")\n\t}\n\n\tcerts, err := x509.ParseCertificates(bootstrapCert.Certificate[0])\n\tif err != nil {\n\t\treturn nil, false, fmt.Errorf(\"unable to parse certificate data: %v\", err)\n\t}\n\tif len(certs) \u003c 1 {\n\t\treturn nil, false, fmt.Errorf(\"no cert data found\")\n\t}\n\tbootstrapCert.Leaf = certs[0]\n\n\tif _, err := store.Update(bootstrapCertificatePEM, bootstrapKeyPEM); err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unable to set the cert/key pair to the bootstrap certificate: %v\", err))\n\t}\n\n\treturn \u0026bootstrapCert, true, nil\n}","line":{"from":466,"to":509}} {"id":100029197,"name":"getClientset","signature":"func (m *manager) getClientset() (clientset.Interface, error)","file":"staging/src/k8s.io/client-go/util/certificate/certificate_manager.go","code":"func (m *manager) getClientset() (clientset.Interface, error) {\n\tcurrent := m.Current()\n\tm.clientAccessLock.Lock()\n\tdefer m.clientAccessLock.Unlock()\n\treturn m.clientsetFn(current)\n}","line":{"from":511,"to":516}} {"id":100029198,"name":"RotateCerts","signature":"func (m *manager) RotateCerts() (bool, error)","file":"staging/src/k8s.io/client-go/util/certificate/certificate_manager.go","code":"// RotateCerts is exposed for testing only and is not a part of the public interface.\n// Returns true if it changed the cert, false otherwise. Error is only returned in\n// exceptional cases.\nfunc (m *manager) RotateCerts() (bool, error) {\n\treturn m.rotateCerts()\n}","line":{"from":518,"to":523}} {"id":100029199,"name":"rotateCerts","signature":"func (m *manager) rotateCerts() (bool, error)","file":"staging/src/k8s.io/client-go/util/certificate/certificate_manager.go","code":"// rotateCerts attempts to request a client cert from the server, wait a reasonable\n// period of time for it to be signed, and then update the cert on disk. If it cannot\n// retrieve a cert, it will return false. It will only return error in exceptional cases.\n// This method also keeps track of \"server health\" by interpreting the responses it gets\n// from the server on the various calls it makes.\n// TODO: return errors, have callers handle and log them correctly\nfunc (m *manager) rotateCerts() (bool, error) {\n\tm.logf(\"%s: Rotating certificates\", m.name)\n\n\ttemplate, csrPEM, keyPEM, privateKey, err := m.generateCSR()\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"%s: Unable to generate a certificate signing request: %v\", m.name, err))\n\t\tif m.certificateRenewFailure != nil {\n\t\t\tm.certificateRenewFailure.Inc()\n\t\t}\n\t\treturn false, nil\n\t}\n\n\t// request the client each time\n\tclientSet, err := m.getClientset()\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"%s: Unable to load a client to request certificates: %v\", m.name, err))\n\t\tif m.certificateRenewFailure != nil {\n\t\t\tm.certificateRenewFailure.Inc()\n\t\t}\n\t\treturn false, nil\n\t}\n\n\tgetUsages := m.getUsages\n\tif m.getUsages == nil {\n\t\tgetUsages = DefaultKubeletClientGetUsages\n\t}\n\tusages := getUsages(privateKey)\n\t// Call the Certificate Signing Request API to get a certificate for the\n\t// new private key\n\treqName, reqUID, err := csr.RequestCertificate(clientSet, csrPEM, \"\", m.signerName, m.requestedCertificateLifetime, usages, privateKey)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"%s: Failed while requesting a signed certificate from the control plane: %v\", m.name, err))\n\t\tif m.certificateRenewFailure != nil {\n\t\t\tm.certificateRenewFailure.Inc()\n\t\t}\n\t\treturn false, m.updateServerError(err)\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), certificateWaitTimeout)\n\tdefer cancel()\n\n\t// Once we've successfully submitted a CSR for this template, record that we did so\n\tm.setLastRequest(cancel, template)\n\n\t// Wait for the certificate to be signed. This interface and internal timout\n\t// is a remainder after the old design using raw watch wrapped with backoff.\n\tcrtPEM, err := csr.WaitForCertificate(ctx, clientSet, reqName, reqUID)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"%s: certificate request was not signed: %v\", m.name, err))\n\t\tif m.certificateRenewFailure != nil {\n\t\t\tm.certificateRenewFailure.Inc()\n\t\t}\n\t\treturn false, nil\n\t}\n\n\tcert, err := m.certStore.Update(crtPEM, keyPEM)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"%s: Unable to store the new cert/key pair: %v\", m.name, err))\n\t\tif m.certificateRenewFailure != nil {\n\t\t\tm.certificateRenewFailure.Inc()\n\t\t}\n\t\treturn false, nil\n\t}\n\n\tif old := m.updateCached(cert); old != nil \u0026\u0026 m.certificateRotation != nil {\n\t\tm.certificateRotation.Observe(m.now().Sub(old.Leaf.NotBefore).Seconds())\n\t}\n\n\treturn true, nil\n}","line":{"from":525,"to":600}} {"id":100029200,"name":"certSatisfiesTemplateLocked","signature":"func (m *manager) certSatisfiesTemplateLocked() bool","file":"staging/src/k8s.io/client-go/util/certificate/certificate_manager.go","code":"// Check that the current certificate on disk satisfies the requests from the\n// current template.\n//\n// Note that extra items in the certificate's SAN or orgs that don't exist in\n// the template will not trigger a renewal.\n//\n// Requires certAccessLock to be locked.\nfunc (m *manager) certSatisfiesTemplateLocked() bool {\n\tif m.cert == nil {\n\t\treturn false\n\t}\n\n\tif template := m.getTemplate(); template != nil {\n\t\tif template.Subject.CommonName != m.cert.Leaf.Subject.CommonName {\n\t\t\tm.logf(\"%s: Current certificate CN (%s) does not match requested CN (%s)\", m.name, m.cert.Leaf.Subject.CommonName, template.Subject.CommonName)\n\t\t\treturn false\n\t\t}\n\n\t\tcurrentDNSNames := sets.NewString(m.cert.Leaf.DNSNames...)\n\t\tdesiredDNSNames := sets.NewString(template.DNSNames...)\n\t\tmissingDNSNames := desiredDNSNames.Difference(currentDNSNames)\n\t\tif len(missingDNSNames) \u003e 0 {\n\t\t\tm.logf(\"%s: Current certificate is missing requested DNS names %v\", m.name, missingDNSNames.List())\n\t\t\treturn false\n\t\t}\n\n\t\tcurrentIPs := sets.NewString()\n\t\tfor _, ip := range m.cert.Leaf.IPAddresses {\n\t\t\tcurrentIPs.Insert(ip.String())\n\t\t}\n\t\tdesiredIPs := sets.NewString()\n\t\tfor _, ip := range template.IPAddresses {\n\t\t\tdesiredIPs.Insert(ip.String())\n\t\t}\n\t\tmissingIPs := desiredIPs.Difference(currentIPs)\n\t\tif len(missingIPs) \u003e 0 {\n\t\t\tm.logf(\"%s: Current certificate is missing requested IP addresses %v\", m.name, missingIPs.List())\n\t\t\treturn false\n\t\t}\n\n\t\tcurrentOrgs := sets.NewString(m.cert.Leaf.Subject.Organization...)\n\t\tdesiredOrgs := sets.NewString(template.Subject.Organization...)\n\t\tmissingOrgs := desiredOrgs.Difference(currentOrgs)\n\t\tif len(missingOrgs) \u003e 0 {\n\t\t\tm.logf(\"%s: Current certificate is missing requested orgs %v\", m.name, missingOrgs.List())\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}","line":{"from":602,"to":652}} {"id":100029201,"name":"certSatisfiesTemplate","signature":"func (m *manager) certSatisfiesTemplate() bool","file":"staging/src/k8s.io/client-go/util/certificate/certificate_manager.go","code":"func (m *manager) certSatisfiesTemplate() bool {\n\tm.certAccessLock.RLock()\n\tdefer m.certAccessLock.RUnlock()\n\treturn m.certSatisfiesTemplateLocked()\n}","line":{"from":654,"to":658}} {"id":100029202,"name":"nextRotationDeadline","signature":"func (m *manager) nextRotationDeadline() time.Time","file":"staging/src/k8s.io/client-go/util/certificate/certificate_manager.go","code":"// nextRotationDeadline returns a value for the threshold at which the\n// current certificate should be rotated, 80%+/-10% of the expiration of the\n// certificate.\nfunc (m *manager) nextRotationDeadline() time.Time {\n\t// forceRotation is not protected by locks\n\tif m.forceRotation {\n\t\tm.forceRotation = false\n\t\treturn m.now()\n\t}\n\n\tm.certAccessLock.RLock()\n\tdefer m.certAccessLock.RUnlock()\n\n\tif !m.certSatisfiesTemplateLocked() {\n\t\treturn m.now()\n\t}\n\n\tnotAfter := m.cert.Leaf.NotAfter\n\ttotalDuration := float64(notAfter.Sub(m.cert.Leaf.NotBefore))\n\tdeadline := m.cert.Leaf.NotBefore.Add(jitteryDuration(totalDuration))\n\n\tm.logf(\"%s: Certificate expiration is %v, rotation deadline is %v\", m.name, notAfter, deadline)\n\treturn deadline\n}","line":{"from":660,"to":683}} {"id":100029203,"name":"updateCached","signature":"func (m *manager) updateCached(cert *tls.Certificate) *tls.Certificate","file":"staging/src/k8s.io/client-go/util/certificate/certificate_manager.go","code":"// updateCached sets the most recent retrieved cert and returns the old cert.\n// It also sets the server as assumed healthy.\nfunc (m *manager) updateCached(cert *tls.Certificate) *tls.Certificate {\n\tm.certAccessLock.Lock()\n\tdefer m.certAccessLock.Unlock()\n\tm.serverHealth = true\n\told := m.cert\n\tm.cert = cert\n\treturn old\n}","line":{"from":697,"to":706}} {"id":100029204,"name":"updateServerError","signature":"func (m *manager) updateServerError(err error) error","file":"staging/src/k8s.io/client-go/util/certificate/certificate_manager.go","code":"// updateServerError takes an error returned by the server and infers\n// the health of the server based on the error. It will return nil if\n// the error does not require immediate termination of any wait loops,\n// and otherwise it will return the error.\nfunc (m *manager) updateServerError(err error) error {\n\tm.certAccessLock.Lock()\n\tdefer m.certAccessLock.Unlock()\n\tswitch {\n\tcase apierrors.IsUnauthorized(err):\n\t\t// SSL terminating proxies may report this error instead of the master\n\t\tm.serverHealth = true\n\tcase apierrors.IsUnexpectedServerError(err):\n\t\t// generally indicates a proxy or other load balancer problem, rather than a problem coming\n\t\t// from the master\n\t\tm.serverHealth = false\n\tdefault:\n\t\t// Identify known errors that could be expected for a cert request that\n\t\t// indicate everything is working normally\n\t\tm.serverHealth = apierrors.IsNotFound(err) || apierrors.IsForbidden(err)\n\t}\n\treturn nil\n}","line":{"from":708,"to":729}} {"id":100029205,"name":"generateCSR","signature":"func (m *manager) generateCSR() (template *x509.CertificateRequest, csrPEM []byte, keyPEM []byte, key interface{}, err error)","file":"staging/src/k8s.io/client-go/util/certificate/certificate_manager.go","code":"func (m *manager) generateCSR() (template *x509.CertificateRequest, csrPEM []byte, keyPEM []byte, key interface{}, err error) {\n\t// Generate a new private key.\n\tprivateKey, err := ecdsa.GenerateKey(elliptic.P256(), cryptorand.Reader)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, fmt.Errorf(\"%s: unable to generate a new private key: %v\", m.name, err)\n\t}\n\tder, err := x509.MarshalECPrivateKey(privateKey)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, fmt.Errorf(\"%s: unable to marshal the new key to DER: %v\", m.name, err)\n\t}\n\n\tkeyPEM = pem.EncodeToMemory(\u0026pem.Block{Type: keyutil.ECPrivateKeyBlockType, Bytes: der})\n\n\ttemplate = m.getTemplate()\n\tif template == nil {\n\t\treturn nil, nil, nil, nil, fmt.Errorf(\"%s: unable to create a csr, no template available\", m.name)\n\t}\n\tcsrPEM, err = cert.MakeCSRFromTemplate(privateKey, template)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, fmt.Errorf(\"%s: unable to create a csr from the private key: %v\", m.name, err)\n\t}\n\treturn template, csrPEM, keyPEM, privateKey, nil\n}","line":{"from":731,"to":753}} {"id":100029206,"name":"getLastRequest","signature":"func (m *manager) getLastRequest() (context.CancelFunc, *x509.CertificateRequest)","file":"staging/src/k8s.io/client-go/util/certificate/certificate_manager.go","code":"func (m *manager) getLastRequest() (context.CancelFunc, *x509.CertificateRequest) {\n\tm.lastRequestLock.Lock()\n\tdefer m.lastRequestLock.Unlock()\n\treturn m.lastRequestCancel, m.lastRequest\n}","line":{"from":755,"to":759}} {"id":100029207,"name":"setLastRequest","signature":"func (m *manager) setLastRequest(cancel context.CancelFunc, r *x509.CertificateRequest)","file":"staging/src/k8s.io/client-go/util/certificate/certificate_manager.go","code":"func (m *manager) setLastRequest(cancel context.CancelFunc, r *x509.CertificateRequest) {\n\tm.lastRequestLock.Lock()\n\tdefer m.lastRequestLock.Unlock()\n\tm.lastRequestCancel = cancel\n\tm.lastRequest = r\n}","line":{"from":761,"to":766}} {"id":100029208,"name":"hasKeyUsage","signature":"func hasKeyUsage(usages []certificates.KeyUsage, usage certificates.KeyUsage) bool","file":"staging/src/k8s.io/client-go/util/certificate/certificate_manager.go","code":"func hasKeyUsage(usages []certificates.KeyUsage, usage certificates.KeyUsage) bool {\n\tfor _, u := range usages {\n\t\tif u == usage {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":768,"to":775}} {"id":100029209,"name":"NewFileStore","signature":"func NewFileStore(","file":"staging/src/k8s.io/client-go/util/certificate/certificate_store.go","code":"// NewFileStore returns a concrete implementation of a Store that is based on\n// storing the cert/key pairs in a single file per pair on disk in the\n// designated directory. When starting up it will look for the currently\n// selected cert/key pair in:\n//\n// 1. ${certDirectory}/${pairNamePrefix}-current.pem - both cert and key are in the same file.\n// 2. ${certFile}, ${keyFile}\n// 3. ${certDirectory}/${pairNamePrefix}.crt, ${keyDirectory}/${pairNamePrefix}.key\n//\n// The first one found will be used. If rotation is enabled, future cert/key\n// updates will be written to the ${certDirectory} directory and\n// ${certDirectory}/${pairNamePrefix}-current.pem will be created as a soft\n// link to the currently selected cert/key pair.\nfunc NewFileStore(\n\tpairNamePrefix string,\n\tcertDirectory string,\n\tkeyDirectory string,\n\tcertFile string,\n\tkeyFile string) (FileStore, error) {\n\n\ts := fileStore{\n\t\tpairNamePrefix: pairNamePrefix,\n\t\tcertDirectory: certDirectory,\n\t\tkeyDirectory: keyDirectory,\n\t\tcertFile: certFile,\n\t\tkeyFile: keyFile,\n\t}\n\tif err := s.recover(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026s, nil\n}","line":{"from":57,"to":88}} {"id":100029210,"name":"CurrentPath","signature":"func (s *fileStore) CurrentPath() string","file":"staging/src/k8s.io/client-go/util/certificate/certificate_store.go","code":"// CurrentPath returns the path to the current version of these certificates.\nfunc (s *fileStore) CurrentPath() string {\n\treturn filepath.Join(s.certDirectory, s.filename(currentPair))\n}","line":{"from":90,"to":93}} {"id":100029211,"name":"recover","signature":"func (s *fileStore) recover() error","file":"staging/src/k8s.io/client-go/util/certificate/certificate_store.go","code":"// recover checks if there is a certificate rotation that was interrupted while\n// progress, and if so, attempts to recover to a good state.\nfunc (s *fileStore) recover() error {\n\t// If the 'current' file doesn't exist, continue on with the recovery process.\n\tcurrentPath := filepath.Join(s.certDirectory, s.filename(currentPair))\n\tif exists, err := fileExists(currentPath); err != nil {\n\t\treturn err\n\t} else if exists {\n\t\treturn nil\n\t}\n\n\t// If the 'updated' file exists, and it is a symbolic link, continue on\n\t// with the recovery process.\n\tupdatedPath := filepath.Join(s.certDirectory, s.filename(updatedPair))\n\tif fi, err := os.Lstat(updatedPath); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t} else if fi.Mode()\u0026os.ModeSymlink != os.ModeSymlink {\n\t\treturn fmt.Errorf(\"expected %q to be a symlink but it is a file\", updatedPath)\n\t}\n\n\t// Move the 'updated' symlink to 'current'.\n\tif err := os.Rename(updatedPath, currentPath); err != nil {\n\t\treturn fmt.Errorf(\"unable to rename %q to %q: %v\", updatedPath, currentPath, err)\n\t}\n\treturn nil\n}","line":{"from":95,"to":123}} {"id":100029212,"name":"Current","signature":"func (s *fileStore) Current() (*tls.Certificate, error)","file":"staging/src/k8s.io/client-go/util/certificate/certificate_store.go","code":"func (s *fileStore) Current() (*tls.Certificate, error) {\n\tpairFile := filepath.Join(s.certDirectory, s.filename(currentPair))\n\tif pairFileExists, err := fileExists(pairFile); err != nil {\n\t\treturn nil, err\n\t} else if pairFileExists {\n\t\tklog.Infof(\"Loading cert/key pair from %q.\", pairFile)\n\t\treturn loadFile(pairFile)\n\t}\n\n\tcertFileExists, err := fileExists(s.certFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkeyFileExists, err := fileExists(s.keyFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif certFileExists \u0026\u0026 keyFileExists {\n\t\tklog.Infof(\"Loading cert/key pair from (%q, %q).\", s.certFile, s.keyFile)\n\t\treturn loadX509KeyPair(s.certFile, s.keyFile)\n\t}\n\n\tc := filepath.Join(s.certDirectory, s.pairNamePrefix+certExtension)\n\tk := filepath.Join(s.keyDirectory, s.pairNamePrefix+keyExtension)\n\tcertFileExists, err = fileExists(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkeyFileExists, err = fileExists(k)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif certFileExists \u0026\u0026 keyFileExists {\n\t\tklog.Infof(\"Loading cert/key pair from (%q, %q).\", c, k)\n\t\treturn loadX509KeyPair(c, k)\n\t}\n\n\tnoKeyErr := NoCertKeyError(\n\t\tfmt.Sprintf(\"no cert/key files read at %q, (%q, %q) or (%q, %q)\",\n\t\t\tpairFile,\n\t\t\ts.certFile,\n\t\t\ts.keyFile,\n\t\t\ts.certDirectory,\n\t\t\ts.keyDirectory))\n\treturn nil, \u0026noKeyErr\n}","line":{"from":125,"to":170}} {"id":100029213,"name":"loadFile","signature":"func loadFile(pairFile string) (*tls.Certificate, error)","file":"staging/src/k8s.io/client-go/util/certificate/certificate_store.go","code":"func loadFile(pairFile string) (*tls.Certificate, error) {\n\t// LoadX509KeyPair knows how to parse combined cert and private key from\n\t// the same file.\n\tcert, err := tls.LoadX509KeyPair(pairFile, pairFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not convert data from %q into cert/key pair: %v\", pairFile, err)\n\t}\n\tcerts, err := x509.ParseCertificates(cert.Certificate[0])\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to parse certificate data: %v\", err)\n\t}\n\tcert.Leaf = certs[0]\n\treturn \u0026cert, nil\n}","line":{"from":172,"to":185}} {"id":100029214,"name":"Update","signature":"func (s *fileStore) Update(certData, keyData []byte) (*tls.Certificate, error)","file":"staging/src/k8s.io/client-go/util/certificate/certificate_store.go","code":"func (s *fileStore) Update(certData, keyData []byte) (*tls.Certificate, error) {\n\tts := time.Now().Format(\"2006-01-02-15-04-05\")\n\tpemFilename := s.filename(ts)\n\n\tif err := os.MkdirAll(s.certDirectory, 0755); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not create directory %q to store certificates: %v\", s.certDirectory, err)\n\t}\n\tcertPath := filepath.Join(s.certDirectory, pemFilename)\n\n\tf, err := os.OpenFile(certPath, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0600)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not open %q: %v\", certPath, err)\n\t}\n\tdefer f.Close()\n\n\t// First cert is leaf, remainder are intermediates\n\tcerts, err := certutil.ParseCertsPEM(certData)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid certificate data: %v\", err)\n\t}\n\tfor _, c := range certs {\n\t\tpem.Encode(f, \u0026pem.Block{Type: \"CERTIFICATE\", Bytes: c.Raw})\n\t}\n\n\tkeyBlock, _ := pem.Decode(keyData)\n\tif keyBlock == nil {\n\t\treturn nil, fmt.Errorf(\"invalid key data\")\n\t}\n\tpem.Encode(f, keyBlock)\n\n\tcert, err := loadFile(certPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := s.updateSymlink(certPath); err != nil {\n\t\treturn nil, err\n\t}\n\treturn cert, nil\n}","line":{"from":187,"to":226}} {"id":100029215,"name":"updateSymlink","signature":"func (s *fileStore) updateSymlink(filename string) error","file":"staging/src/k8s.io/client-go/util/certificate/certificate_store.go","code":"// updateSymLink updates the current symlink to point to the file that is\n// passed it. It will fail if there is a non-symlink file exists where the\n// symlink is expected to be.\nfunc (s *fileStore) updateSymlink(filename string) error {\n\t// If the 'current' file either doesn't exist, or is already a symlink,\n\t// proceed. Otherwise, this is an unrecoverable error.\n\tcurrentPath := filepath.Join(s.certDirectory, s.filename(currentPair))\n\tcurrentPathExists := false\n\tif fi, err := os.Lstat(currentPath); err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn err\n\t\t}\n\t} else if fi.Mode()\u0026os.ModeSymlink != os.ModeSymlink {\n\t\treturn fmt.Errorf(\"expected %q to be a symlink but it is a file\", currentPath)\n\t} else {\n\t\tcurrentPathExists = true\n\t}\n\n\t// If the 'updated' file doesn't exist, proceed. If it exists but it is a\n\t// symlink, delete it. Otherwise, this is an unrecoverable error.\n\tupdatedPath := filepath.Join(s.certDirectory, s.filename(updatedPair))\n\tif fi, err := os.Lstat(updatedPath); err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn err\n\t\t}\n\t} else if fi.Mode()\u0026os.ModeSymlink != os.ModeSymlink {\n\t\treturn fmt.Errorf(\"expected %q to be a symlink but it is a file\", updatedPath)\n\t} else {\n\t\tif err := os.Remove(updatedPath); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to remove %q: %v\", updatedPath, err)\n\t\t}\n\t}\n\n\t// Check that the new cert/key pair file exists to avoid rotating to an\n\t// invalid cert/key.\n\tif filenameExists, err := fileExists(filename); err != nil {\n\t\treturn err\n\t} else if !filenameExists {\n\t\treturn fmt.Errorf(\"file %q does not exist so it can not be used as the currently selected cert/key\", filename)\n\t}\n\n\t// Ensure the source path is absolute to ensure the symlink target is\n\t// correct when certDirectory is a relative path.\n\tfilename, err := filepath.Abs(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Create the 'updated' symlink pointing to the requested file name.\n\tif err := os.Symlink(filename, updatedPath); err != nil {\n\t\treturn fmt.Errorf(\"unable to create a symlink from %q to %q: %v\", updatedPath, filename, err)\n\t}\n\n\t// Replace the 'current' symlink.\n\tif currentPathExists {\n\t\tif err := os.Remove(currentPath); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to remove %q: %v\", currentPath, err)\n\t\t}\n\t}\n\tif err := os.Rename(updatedPath, currentPath); err != nil {\n\t\treturn fmt.Errorf(\"unable to rename %q to %q: %v\", updatedPath, currentPath, err)\n\t}\n\treturn nil\n}","line":{"from":228,"to":291}} {"id":100029216,"name":"filename","signature":"func (s *fileStore) filename(qualifier string) string","file":"staging/src/k8s.io/client-go/util/certificate/certificate_store.go","code":"func (s *fileStore) filename(qualifier string) string {\n\treturn s.pairNamePrefix + \"-\" + qualifier + pemExtension\n}","line":{"from":293,"to":295}} {"id":100029217,"name":"loadX509KeyPair","signature":"func loadX509KeyPair(certFile, keyFile string) (*tls.Certificate, error)","file":"staging/src/k8s.io/client-go/util/certificate/certificate_store.go","code":"func loadX509KeyPair(certFile, keyFile string) (*tls.Certificate, error) {\n\tcert, err := tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcerts, err := x509.ParseCertificates(cert.Certificate[0])\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to parse certificate data: %v\", err)\n\t}\n\tcert.Leaf = certs[0]\n\treturn \u0026cert, nil\n}","line":{"from":297,"to":308}} {"id":100029218,"name":"fileExists","signature":"func fileExists(filename string) (bool, error)","file":"staging/src/k8s.io/client-go/util/certificate/certificate_store.go","code":"// FileExists checks if specified file exists.\nfunc fileExists(filename string) (bool, error) {\n\tif _, err := os.Stat(filename); os.IsNotExist(err) {\n\t\treturn false, nil\n\t} else if err != nil {\n\t\treturn false, err\n\t}\n\treturn true, nil\n}","line":{"from":310,"to":318}} {"id":100029219,"name":"RequestCertificate","signature":"func RequestCertificate(client clientset.Interface, csrData []byte, name, signerName string, requestedDuration *time.Duration, usages []certificatesv1.KeyUsage, privateKey interface{}) (reqName string, reqUID types.UID, err error)","file":"staging/src/k8s.io/client-go/util/certificate/csr/csr.go","code":"// RequestCertificate will either use an existing (if this process has run\n// before but not to completion) or create a certificate signing request using the\n// PEM encoded CSR and send it to API server. An optional requestedDuration may be passed\n// to set the spec.expirationSeconds field on the CSR to control the lifetime of the issued\n// certificate. This is not guaranteed as the signer may choose to ignore the request.\nfunc RequestCertificate(client clientset.Interface, csrData []byte, name, signerName string, requestedDuration *time.Duration, usages []certificatesv1.KeyUsage, privateKey interface{}) (reqName string, reqUID types.UID, err error) {\n\tcsr := \u0026certificatesv1.CertificateSigningRequest{\n\t\t// Username, UID, Groups will be injected by API server.\n\t\tTypeMeta: metav1.TypeMeta{Kind: \"CertificateSigningRequest\"},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t},\n\t\tSpec: certificatesv1.CertificateSigningRequestSpec{\n\t\t\tRequest: csrData,\n\t\t\tUsages: usages,\n\t\t\tSignerName: signerName,\n\t\t},\n\t}\n\tif len(csr.Name) == 0 {\n\t\tcsr.GenerateName = \"csr-\"\n\t}\n\tif requestedDuration != nil {\n\t\tcsr.Spec.ExpirationSeconds = DurationToExpirationSeconds(*requestedDuration)\n\t}\n\n\treqName, reqUID, err = create(client, csr)\n\tswitch {\n\tcase err == nil:\n\t\treturn reqName, reqUID, err\n\n\tcase apierrors.IsAlreadyExists(err) \u0026\u0026 len(name) \u003e 0:\n\t\tklog.Infof(\"csr for this node already exists, reusing\")\n\t\treq, err := get(client, name)\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", formatError(\"cannot retrieve certificate signing request: %v\", err)\n\t\t}\n\t\tif err := ensureCompatible(req, csr, privateKey); err != nil {\n\t\t\treturn \"\", \"\", fmt.Errorf(\"retrieved csr is not compatible: %v\", err)\n\t\t}\n\t\tklog.Infof(\"csr for this node is still valid\")\n\t\treturn req.Name, req.UID, nil\n\n\tdefault:\n\t\treturn \"\", \"\", formatError(\"cannot create certificate signing request: %v\", err)\n\t}\n}","line":{"from":45,"to":90}} {"id":100029220,"name":"DurationToExpirationSeconds","signature":"func DurationToExpirationSeconds(duration time.Duration) *int32","file":"staging/src/k8s.io/client-go/util/certificate/csr/csr.go","code":"func DurationToExpirationSeconds(duration time.Duration) *int32 {\n\treturn pointer.Int32(int32(duration / time.Second))\n}","line":{"from":92,"to":94}} {"id":100029221,"name":"ExpirationSecondsToDuration","signature":"func ExpirationSecondsToDuration(expirationSeconds int32) time.Duration","file":"staging/src/k8s.io/client-go/util/certificate/csr/csr.go","code":"func ExpirationSecondsToDuration(expirationSeconds int32) time.Duration {\n\treturn time.Duration(expirationSeconds) * time.Second\n}","line":{"from":96,"to":98}} {"id":100029222,"name":"get","signature":"func get(client clientset.Interface, name string) (*certificatesv1.CertificateSigningRequest, error)","file":"staging/src/k8s.io/client-go/util/certificate/csr/csr.go","code":"func get(client clientset.Interface, name string) (*certificatesv1.CertificateSigningRequest, error) {\n\tv1req, v1err := client.CertificatesV1().CertificateSigningRequests().Get(context.TODO(), name, metav1.GetOptions{})\n\tif v1err == nil || !apierrors.IsNotFound(v1err) {\n\t\treturn v1req, v1err\n\t}\n\n\tv1beta1req, v1beta1err := client.CertificatesV1beta1().CertificateSigningRequests().Get(context.TODO(), name, metav1.GetOptions{})\n\tif v1beta1err != nil {\n\t\treturn nil, v1beta1err\n\t}\n\n\tv1req = \u0026certificatesv1.CertificateSigningRequest{\n\t\tObjectMeta: v1beta1req.ObjectMeta,\n\t\tSpec: certificatesv1.CertificateSigningRequestSpec{\n\t\t\tRequest: v1beta1req.Spec.Request,\n\t\t},\n\t}\n\tif v1beta1req.Spec.SignerName != nil {\n\t\tv1req.Spec.SignerName = *v1beta1req.Spec.SignerName\n\t}\n\tfor _, usage := range v1beta1req.Spec.Usages {\n\t\tv1req.Spec.Usages = append(v1req.Spec.Usages, certificatesv1.KeyUsage(usage))\n\t}\n\treturn v1req, nil\n}","line":{"from":100,"to":124}} {"id":100029223,"name":"create","signature":"func create(client clientset.Interface, csr *certificatesv1.CertificateSigningRequest) (reqName string, reqUID types.UID, err error)","file":"staging/src/k8s.io/client-go/util/certificate/csr/csr.go","code":"func create(client clientset.Interface, csr *certificatesv1.CertificateSigningRequest) (reqName string, reqUID types.UID, err error) {\n\t// only attempt a create via v1 if we specified signerName and usages and are not using the legacy unknown signerName\n\tif len(csr.Spec.Usages) \u003e 0 \u0026\u0026 len(csr.Spec.SignerName) \u003e 0 \u0026\u0026 csr.Spec.SignerName != \"kubernetes.io/legacy-unknown\" {\n\t\tv1req, v1err := client.CertificatesV1().CertificateSigningRequests().Create(context.TODO(), csr, metav1.CreateOptions{})\n\t\tswitch {\n\t\tcase v1err != nil \u0026\u0026 apierrors.IsNotFound(v1err):\n\t\t\t// v1 CSR API was not found, continue to try v1beta1\n\n\t\tcase v1err != nil:\n\t\t\t// other creation error\n\t\t\treturn \"\", \"\", v1err\n\n\t\tdefault:\n\t\t\t// success\n\t\t\treturn v1req.Name, v1req.UID, v1err\n\t\t}\n\t}\n\n\t// convert relevant bits to v1beta1\n\tv1beta1csr := \u0026certificatesv1beta1.CertificateSigningRequest{\n\t\tObjectMeta: csr.ObjectMeta,\n\t\tSpec: certificatesv1beta1.CertificateSigningRequestSpec{\n\t\t\tSignerName: \u0026csr.Spec.SignerName,\n\t\t\tRequest: csr.Spec.Request,\n\t\t},\n\t}\n\tfor _, usage := range csr.Spec.Usages {\n\t\tv1beta1csr.Spec.Usages = append(v1beta1csr.Spec.Usages, certificatesv1beta1.KeyUsage(usage))\n\t}\n\n\t// create v1beta1\n\tv1beta1req, v1beta1err := client.CertificatesV1beta1().CertificateSigningRequests().Create(context.TODO(), v1beta1csr, metav1.CreateOptions{})\n\tif v1beta1err != nil {\n\t\treturn \"\", \"\", v1beta1err\n\t}\n\treturn v1beta1req.Name, v1beta1req.UID, nil\n}","line":{"from":126,"to":162}} {"id":100029224,"name":"WaitForCertificate","signature":"func WaitForCertificate(ctx context.Context, client clientset.Interface, reqName string, reqUID types.UID) (certData []byte, err error)","file":"staging/src/k8s.io/client-go/util/certificate/csr/csr.go","code":"// WaitForCertificate waits for a certificate to be issued until timeout, or returns an error.\nfunc WaitForCertificate(ctx context.Context, client clientset.Interface, reqName string, reqUID types.UID) (certData []byte, err error) {\n\tfieldSelector := fields.OneTermEqualSelector(\"metadata.name\", reqName).String()\n\n\tvar lw *cache.ListWatch\n\tvar obj runtime.Object\n\tfor {\n\t\t// see if the v1 API is available\n\t\tif _, err := client.CertificatesV1().CertificateSigningRequests().List(ctx, metav1.ListOptions{FieldSelector: fieldSelector}); err == nil {\n\t\t\t// watch v1 objects\n\t\t\tobj = \u0026certificatesv1.CertificateSigningRequest{}\n\t\t\tlw = \u0026cache.ListWatch{\n\t\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\t\toptions.FieldSelector = fieldSelector\n\t\t\t\t\treturn client.CertificatesV1().CertificateSigningRequests().List(ctx, options)\n\t\t\t\t},\n\t\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\t\toptions.FieldSelector = fieldSelector\n\t\t\t\t\treturn client.CertificatesV1().CertificateSigningRequests().Watch(ctx, options)\n\t\t\t\t},\n\t\t\t}\n\t\t\tbreak\n\t\t} else {\n\t\t\tklog.V(2).Infof(\"error fetching v1 certificate signing request: %v\", err)\n\t\t}\n\n\t\t// return if we've timed out\n\t\tif err := ctx.Err(); err != nil {\n\t\t\treturn nil, wait.ErrWaitTimeout\n\t\t}\n\n\t\t// see if the v1beta1 API is available\n\t\tif _, err := client.CertificatesV1beta1().CertificateSigningRequests().List(ctx, metav1.ListOptions{FieldSelector: fieldSelector}); err == nil {\n\t\t\t// watch v1beta1 objects\n\t\t\tobj = \u0026certificatesv1beta1.CertificateSigningRequest{}\n\t\t\tlw = \u0026cache.ListWatch{\n\t\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\t\toptions.FieldSelector = fieldSelector\n\t\t\t\t\treturn client.CertificatesV1beta1().CertificateSigningRequests().List(ctx, options)\n\t\t\t\t},\n\t\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\t\toptions.FieldSelector = fieldSelector\n\t\t\t\t\treturn client.CertificatesV1beta1().CertificateSigningRequests().Watch(ctx, options)\n\t\t\t\t},\n\t\t\t}\n\t\t\tbreak\n\t\t} else {\n\t\t\tklog.V(2).Infof(\"error fetching v1beta1 certificate signing request: %v\", err)\n\t\t}\n\n\t\t// return if we've timed out\n\t\tif err := ctx.Err(); err != nil {\n\t\t\treturn nil, wait.ErrWaitTimeout\n\t\t}\n\n\t\t// wait and try again\n\t\ttime.Sleep(time.Second)\n\t}\n\n\tvar issuedCertificate []byte\n\t_, err = watchtools.UntilWithSync(\n\t\tctx,\n\t\tlw,\n\t\tobj,\n\t\tnil,\n\t\tfunc(event watch.Event) (bool, error) {\n\t\t\tswitch event.Type {\n\t\t\tcase watch.Modified, watch.Added:\n\t\t\tcase watch.Deleted:\n\t\t\t\treturn false, fmt.Errorf(\"csr %q was deleted\", reqName)\n\t\t\tdefault:\n\t\t\t\treturn false, nil\n\t\t\t}\n\n\t\t\tswitch csr := event.Object.(type) {\n\t\t\tcase *certificatesv1.CertificateSigningRequest:\n\t\t\t\tif csr.UID != reqUID {\n\t\t\t\t\treturn false, fmt.Errorf(\"csr %q changed UIDs\", csr.Name)\n\t\t\t\t}\n\t\t\t\tapproved := false\n\t\t\t\tfor _, c := range csr.Status.Conditions {\n\t\t\t\t\tif c.Type == certificatesv1.CertificateDenied {\n\t\t\t\t\t\treturn false, fmt.Errorf(\"certificate signing request is denied, reason: %v, message: %v\", c.Reason, c.Message)\n\t\t\t\t\t}\n\t\t\t\t\tif c.Type == certificatesv1.CertificateFailed {\n\t\t\t\t\t\treturn false, fmt.Errorf(\"certificate signing request failed, reason: %v, message: %v\", c.Reason, c.Message)\n\t\t\t\t\t}\n\t\t\t\t\tif c.Type == certificatesv1.CertificateApproved {\n\t\t\t\t\t\tapproved = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif approved {\n\t\t\t\t\tif len(csr.Status.Certificate) \u003e 0 {\n\t\t\t\t\t\tklog.V(2).Infof(\"certificate signing request %s is issued\", csr.Name)\n\t\t\t\t\t\tissuedCertificate = csr.Status.Certificate\n\t\t\t\t\t\treturn true, nil\n\t\t\t\t\t}\n\t\t\t\t\tklog.V(2).Infof(\"certificate signing request %s is approved, waiting to be issued\", csr.Name)\n\t\t\t\t}\n\n\t\t\tcase *certificatesv1beta1.CertificateSigningRequest:\n\t\t\t\tif csr.UID != reqUID {\n\t\t\t\t\treturn false, fmt.Errorf(\"csr %q changed UIDs\", csr.Name)\n\t\t\t\t}\n\t\t\t\tapproved := false\n\t\t\t\tfor _, c := range csr.Status.Conditions {\n\t\t\t\t\tif c.Type == certificatesv1beta1.CertificateDenied {\n\t\t\t\t\t\treturn false, fmt.Errorf(\"certificate signing request is denied, reason: %v, message: %v\", c.Reason, c.Message)\n\t\t\t\t\t}\n\t\t\t\t\tif c.Type == certificatesv1beta1.CertificateFailed {\n\t\t\t\t\t\treturn false, fmt.Errorf(\"certificate signing request failed, reason: %v, message: %v\", c.Reason, c.Message)\n\t\t\t\t\t}\n\t\t\t\t\tif c.Type == certificatesv1beta1.CertificateApproved {\n\t\t\t\t\t\tapproved = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif approved {\n\t\t\t\t\tif len(csr.Status.Certificate) \u003e 0 {\n\t\t\t\t\t\tklog.V(2).Infof(\"certificate signing request %s is issued\", csr.Name)\n\t\t\t\t\t\tissuedCertificate = csr.Status.Certificate\n\t\t\t\t\t\treturn true, nil\n\t\t\t\t\t}\n\t\t\t\t\tklog.V(2).Infof(\"certificate signing request %s is approved, waiting to be issued\", csr.Name)\n\t\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\treturn false, fmt.Errorf(\"unexpected type received: %T\", event.Object)\n\t\t\t}\n\n\t\t\treturn false, nil\n\t\t},\n\t)\n\tif err == wait.ErrWaitTimeout {\n\t\treturn nil, wait.ErrWaitTimeout\n\t}\n\tif err != nil {\n\t\treturn nil, formatError(\"cannot watch on the certificate signing request: %v\", err)\n\t}\n\n\treturn issuedCertificate, nil\n}","line":{"from":164,"to":304}} {"id":100029225,"name":"ensureCompatible","signature":"func ensureCompatible(new, orig *certificatesv1.CertificateSigningRequest, privateKey interface{}) error","file":"staging/src/k8s.io/client-go/util/certificate/csr/csr.go","code":"// ensureCompatible ensures that a CSR object is compatible with an original CSR\nfunc ensureCompatible(new, orig *certificatesv1.CertificateSigningRequest, privateKey interface{}) error {\n\tnewCSR, err := parseCSR(new.Spec.Request)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to parse new csr: %v\", err)\n\t}\n\torigCSR, err := parseCSR(orig.Spec.Request)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to parse original csr: %v\", err)\n\t}\n\tif !reflect.DeepEqual(newCSR.Subject, origCSR.Subject) {\n\t\treturn fmt.Errorf(\"csr subjects differ: new: %#v, orig: %#v\", newCSR.Subject, origCSR.Subject)\n\t}\n\tif len(new.Spec.SignerName) \u003e 0 \u0026\u0026 len(orig.Spec.SignerName) \u003e 0 \u0026\u0026 new.Spec.SignerName != orig.Spec.SignerName {\n\t\treturn fmt.Errorf(\"csr signerNames differ: new %q, orig: %q\", new.Spec.SignerName, orig.Spec.SignerName)\n\t}\n\tsigner, ok := privateKey.(crypto.Signer)\n\tif !ok {\n\t\treturn fmt.Errorf(\"privateKey is not a signer\")\n\t}\n\tnewCSR.PublicKey = signer.Public()\n\tif err := newCSR.CheckSignature(); err != nil {\n\t\treturn fmt.Errorf(\"error validating signature new CSR against old key: %v\", err)\n\t}\n\tif len(new.Status.Certificate) \u003e 0 {\n\t\tcerts, err := certutil.ParseCertsPEM(new.Status.Certificate)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error parsing signed certificate for CSR: %v\", err)\n\t\t}\n\t\tnow := time.Now()\n\t\tfor _, cert := range certs {\n\t\t\tif now.After(cert.NotAfter) {\n\t\t\t\treturn fmt.Errorf(\"one of the certificates for the CSR has expired: %s\", cert.NotAfter)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":306,"to":343}} {"id":100029226,"name":"formatError","signature":"func formatError(format string, err error) error","file":"staging/src/k8s.io/client-go/util/certificate/csr/csr.go","code":"// formatError preserves the type of an API message but alters the message. Expects\n// a single argument format string, and returns the wrapped error.\nfunc formatError(format string, err error) error {\n\tif s, ok := err.(apierrors.APIStatus); ok {\n\t\tse := \u0026apierrors.StatusError{ErrStatus: s.Status()}\n\t\tse.ErrStatus.Message = fmt.Sprintf(format, se.ErrStatus.Message)\n\t\treturn se\n\t}\n\treturn fmt.Errorf(format, err)\n}","line":{"from":345,"to":354}} {"id":100029227,"name":"parseCSR","signature":"func parseCSR(pemData []byte) (*x509.CertificateRequest, error)","file":"staging/src/k8s.io/client-go/util/certificate/csr/csr.go","code":"// parseCSR extracts the CSR from the API object and decodes it.\nfunc parseCSR(pemData []byte) (*x509.CertificateRequest, error) {\n\t// extract PEM from request object\n\tblock, _ := pem.Decode(pemData)\n\tif block == nil || block.Type != \"CERTIFICATE REQUEST\" {\n\t\treturn nil, fmt.Errorf(\"PEM block type must be CERTIFICATE REQUEST\")\n\t}\n\treturn x509.ParseCertificateRequest(block.Bytes)\n}","line":{"from":356,"to":364}} {"id":100029228,"name":"NewDialer","signature":"func NewDialer(dial DialFunc) *Dialer","file":"staging/src/k8s.io/client-go/util/connrotation/connrotation.go","code":"// NewDialer creates a new Dialer instance.\n// Equivalent to NewDialerWithTracker(dial, nil).\nfunc NewDialer(dial DialFunc) *Dialer {\n\treturn NewDialerWithTracker(dial, nil)\n}","line":{"from":39,"to":43}} {"id":100029229,"name":"NewDialerWithTracker","signature":"func NewDialerWithTracker(dial DialFunc, tracker *ConnectionTracker) *Dialer","file":"staging/src/k8s.io/client-go/util/connrotation/connrotation.go","code":"// NewDialerWithTracker creates a new Dialer instance.\n//\n// If dial is not nil, it will be used to create new underlying connections.\n// Otherwise net.DialContext is used.\n// If tracker is not nil, it will be used to track new underlying connections.\n// Otherwise NewConnectionTracker() is used.\nfunc NewDialerWithTracker(dial DialFunc, tracker *ConnectionTracker) *Dialer {\n\tif tracker == nil {\n\t\ttracker = NewConnectionTracker()\n\t}\n\treturn \u0026Dialer{\n\t\tdial: dial,\n\t\tConnectionTracker: tracker,\n\t}\n}","line":{"from":45,"to":59}} {"id":100029230,"name":"NewConnectionTracker","signature":"func NewConnectionTracker() *ConnectionTracker","file":"staging/src/k8s.io/client-go/util/connrotation/connrotation.go","code":"// NewConnectionTracker returns a connection tracker for use with NewDialerWithTracker\nfunc NewConnectionTracker() *ConnectionTracker {\n\treturn \u0026ConnectionTracker{\n\t\tconns: make(map[*closableConn]struct{}),\n\t}\n}","line":{"from":67,"to":72}} {"id":100029231,"name":"CloseAll","signature":"func (c *ConnectionTracker) CloseAll()","file":"staging/src/k8s.io/client-go/util/connrotation/connrotation.go","code":"// CloseAll forcibly closes all tracked connections.\n//\n// Note: new connections may get created before CloseAll returns.\nfunc (c *ConnectionTracker) CloseAll() {\n\tc.mu.Lock()\n\tconns := c.conns\n\tc.conns = make(map[*closableConn]struct{})\n\tc.mu.Unlock()\n\n\tfor conn := range conns {\n\t\tconn.Close()\n\t}\n}","line":{"from":74,"to":86}} {"id":100029232,"name":"Track","signature":"func (c *ConnectionTracker) Track(conn net.Conn) net.Conn","file":"staging/src/k8s.io/client-go/util/connrotation/connrotation.go","code":"// Track adds the connection to the list of tracked connections,\n// and returns a wrapped copy of the connection that stops tracking the connection\n// when it is closed.\nfunc (c *ConnectionTracker) Track(conn net.Conn) net.Conn {\n\tclosable := \u0026closableConn{Conn: conn}\n\n\t// When the connection is closed, remove it from the map. This will\n\t// be no-op if the connection isn't in the map, e.g. if CloseAll()\n\t// is called.\n\tclosable.onClose = func() {\n\t\tc.mu.Lock()\n\t\tdelete(c.conns, closable)\n\t\tc.mu.Unlock()\n\t}\n\n\t// Start tracking the connection\n\tc.mu.Lock()\n\tc.conns[closable] = struct{}{}\n\tc.mu.Unlock()\n\n\treturn closable\n}","line":{"from":88,"to":109}} {"id":100029233,"name":"Dial","signature":"func (d *Dialer) Dial(network, address string) (net.Conn, error)","file":"staging/src/k8s.io/client-go/util/connrotation/connrotation.go","code":"// Dial creates a new tracked connection.\nfunc (d *Dialer) Dial(network, address string) (net.Conn, error) {\n\treturn d.DialContext(context.Background(), network, address)\n}","line":{"from":111,"to":114}} {"id":100029234,"name":"DialContext","signature":"func (d *Dialer) DialContext(ctx context.Context, network, address string) (net.Conn, error)","file":"staging/src/k8s.io/client-go/util/connrotation/connrotation.go","code":"// DialContext creates a new tracked connection.\nfunc (d *Dialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {\n\tconn, err := d.dial(ctx, network, address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn d.ConnectionTracker.Track(conn), nil\n}","line":{"from":116,"to":123}} {"id":100029235,"name":"Close","signature":"func (c *closableConn) Close() error","file":"staging/src/k8s.io/client-go/util/connrotation/connrotation.go","code":"func (c *closableConn) Close() error {\n\tgo c.onClose()\n\treturn c.Conn.Close()\n}","line":{"from":130,"to":133}} {"id":100029236,"name":"FindFieldsOwners","signature":"func FindFieldsOwners(","file":"staging/src/k8s.io/client-go/util/csaupgrade/upgrade.go","code":"// Finds all managed fields owners of the given operation type which owns all of\n// the fields in the given set\n//\n// If there is an error decoding one of the fieldsets for any reason, it is ignored\n// and assumed not to match the query.\nfunc FindFieldsOwners(\n\tmanagedFields []metav1.ManagedFieldsEntry,\n\toperation metav1.ManagedFieldsOperationType,\n\tfields *fieldpath.Set,\n) []metav1.ManagedFieldsEntry {\n\tvar result []metav1.ManagedFieldsEntry\n\tfor _, entry := range managedFields {\n\t\tif entry.Operation != operation {\n\t\t\tcontinue\n\t\t}\n\n\t\tfieldSet, err := decodeManagedFieldsEntrySet(entry)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif fields.Difference(\u0026fieldSet).Empty() {\n\t\t\tresult = append(result, entry)\n\t\t}\n\t}\n\treturn result\n}","line":{"from":33,"to":59}} {"id":100029237,"name":"UpgradeManagedFields","signature":"func UpgradeManagedFields(","file":"staging/src/k8s.io/client-go/util/csaupgrade/upgrade.go","code":"// Upgrades the Manager information for fields managed with client-side-apply (CSA)\n// Prepares fields owned by `csaManager` for 'Update' operations for use now\n// with the given `ssaManager` for `Apply` operations.\n//\n// This transformation should be performed on an object if it has been previously\n// managed using client-side-apply to prepare it for future use with\n// server-side-apply.\n//\n// Caveats:\n// 1. This operation is not reversible. Information about which fields the client\n// owned will be lost in this operation.\n// 2. Supports being performed either before or after initial server-side apply.\n// 3. Client-side apply tends to own more fields (including fields that are defaulted),\n// this will possibly remove this defaults, they will be re-defaulted, that's fine.\n// 4. Care must be taken to not overwrite the managed fields on the server if they\n// have changed before sending a patch.\n//\n// obj - Target of the operation which has been managed with CSA in the past\n// csaManagerNames - Names of FieldManagers to merge into ssaManagerName\n// ssaManagerName - Name of FieldManager to be used for `Apply` operations\nfunc UpgradeManagedFields(\n\tobj runtime.Object,\n\tcsaManagerNames sets.Set[string],\n\tssaManagerName string,\n) error {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfilteredManagers := accessor.GetManagedFields()\n\n\tfor csaManagerName := range csaManagerNames {\n\t\tfilteredManagers, err = upgradedManagedFields(\n\t\t\tfilteredManagers, csaManagerName, ssaManagerName)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Commit changes to object\n\taccessor.SetManagedFields(filteredManagers)\n\treturn nil\n}","line":{"from":61,"to":105}} {"id":100029238,"name":"UpgradeManagedFieldsPatch","signature":"func UpgradeManagedFieldsPatch(","file":"staging/src/k8s.io/client-go/util/csaupgrade/upgrade.go","code":"// Calculates a minimal JSON Patch to send to upgrade managed fields\n// See `UpgradeManagedFields` for more information.\n//\n// obj - Target of the operation which has been managed with CSA in the past\n// csaManagerNames - Names of FieldManagers to merge into ssaManagerName\n// ssaManagerName - Name of FieldManager to be used for `Apply` operations\n//\n// Returns non-nil error if there was an error, a JSON patch, or nil bytes if\n// there is no work to be done.\nfunc UpgradeManagedFieldsPatch(\n\tobj runtime.Object,\n\tcsaManagerNames sets.Set[string],\n\tssaManagerName string) ([]byte, error) {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmanagedFields := accessor.GetManagedFields()\n\tfilteredManagers := accessor.GetManagedFields()\n\tfor csaManagerName := range csaManagerNames {\n\t\tfilteredManagers, err = upgradedManagedFields(\n\t\t\tfilteredManagers, csaManagerName, ssaManagerName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif reflect.DeepEqual(managedFields, filteredManagers) {\n\t\t// If the managed fields have not changed from the transformed version,\n\t\t// there is no patch to perform\n\t\treturn nil, nil\n\t}\n\n\t// Create a patch with a diff between old and new objects.\n\t// Just include all managed fields since that is only thing that will change\n\t//\n\t// Also include test for RV to avoid race condition\n\tjsonPatch := []map[string]interface{}{\n\t\t{\n\t\t\t\"op\": \"replace\",\n\t\t\t\"path\": \"/metadata/managedFields\",\n\t\t\t\"value\": filteredManagers,\n\t\t},\n\t\t{\n\t\t\t// Use \"replace\" instead of \"test\" operation so that etcd rejects with\n\t\t\t// 409 conflict instead of apiserver with an invalid request\n\t\t\t\"op\": \"replace\",\n\t\t\t\"path\": \"/metadata/resourceVersion\",\n\t\t\t\"value\": accessor.GetResourceVersion(),\n\t\t},\n\t}\n\n\treturn json.Marshal(jsonPatch)\n}","line":{"from":107,"to":161}} {"id":100029239,"name":"upgradedManagedFields","signature":"func upgradedManagedFields(","file":"staging/src/k8s.io/client-go/util/csaupgrade/upgrade.go","code":"// Returns a copy of the provided managed fields that has been migrated from\n// client-side-apply to server-side-apply, or an error if there was an issue\nfunc upgradedManagedFields(\n\tmanagedFields []metav1.ManagedFieldsEntry,\n\tcsaManagerName string,\n\tssaManagerName string,\n) ([]metav1.ManagedFieldsEntry, error) {\n\tif managedFields == nil {\n\t\treturn nil, nil\n\t}\n\n\t// Create managed fields clone since we modify the values\n\tmanagedFieldsCopy := make([]metav1.ManagedFieldsEntry, len(managedFields))\n\tif copy(managedFieldsCopy, managedFields) != len(managedFields) {\n\t\treturn nil, errors.New(\"failed to copy managed fields\")\n\t}\n\tmanagedFields = managedFieldsCopy\n\n\t// Locate SSA manager\n\treplaceIndex, managerExists := findFirstIndex(managedFields,\n\t\tfunc(entry metav1.ManagedFieldsEntry) bool {\n\t\t\treturn entry.Manager == ssaManagerName \u0026\u0026\n\t\t\t\tentry.Operation == metav1.ManagedFieldsOperationApply \u0026\u0026\n\t\t\t\tentry.Subresource == \"\"\n\t\t})\n\n\tif !managerExists {\n\t\t// SSA manager does not exist. Find the most recent matching CSA manager,\n\t\t// convert it to an SSA manager.\n\t\t//\n\t\t// (find first index, since managed fields are sorted so that most recent is\n\t\t// first in the list)\n\t\treplaceIndex, managerExists = findFirstIndex(managedFields,\n\t\t\tfunc(entry metav1.ManagedFieldsEntry) bool {\n\t\t\t\treturn entry.Manager == csaManagerName \u0026\u0026\n\t\t\t\t\tentry.Operation == metav1.ManagedFieldsOperationUpdate \u0026\u0026\n\t\t\t\t\tentry.Subresource == \"\"\n\t\t\t})\n\n\t\tif !managerExists {\n\t\t\t// There are no CSA managers that need to be converted. Nothing to do\n\t\t\t// Return early\n\t\t\treturn managedFields, nil\n\t\t}\n\n\t\t// Convert CSA manager into SSA manager\n\t\tmanagedFields[replaceIndex].Operation = metav1.ManagedFieldsOperationApply\n\t\tmanagedFields[replaceIndex].Manager = ssaManagerName\n\t}\n\terr := unionManagerIntoIndex(managedFields, replaceIndex, csaManagerName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create version of managed fields which has no CSA managers with the given name\n\tfilteredManagers := filter(managedFields, func(entry metav1.ManagedFieldsEntry) bool {\n\t\treturn !(entry.Manager == csaManagerName \u0026\u0026\n\t\t\tentry.Operation == metav1.ManagedFieldsOperationUpdate \u0026\u0026\n\t\t\tentry.Subresource == \"\")\n\t})\n\n\treturn filteredManagers, nil\n}","line":{"from":163,"to":225}} {"id":100029240,"name":"unionManagerIntoIndex","signature":"func unionManagerIntoIndex(","file":"staging/src/k8s.io/client-go/util/csaupgrade/upgrade.go","code":"// Locates an Update manager entry named `csaManagerName` with the same APIVersion\n// as the manager at the targetIndex. Unions both manager's fields together\n// into the manager specified by `targetIndex`. No other managers are modified.\nfunc unionManagerIntoIndex(\n\tentries []metav1.ManagedFieldsEntry,\n\ttargetIndex int,\n\tcsaManagerName string,\n) error {\n\tssaManager := entries[targetIndex]\n\n\t// find Update manager of same APIVersion, union ssa fields with it.\n\t// discard all other Update managers of the same name\n\tcsaManagerIndex, csaManagerExists := findFirstIndex(entries,\n\t\tfunc(entry metav1.ManagedFieldsEntry) bool {\n\t\t\treturn entry.Manager == csaManagerName \u0026\u0026\n\t\t\t\tentry.Operation == metav1.ManagedFieldsOperationUpdate \u0026\u0026\n\t\t\t\t//!TODO: some users may want to migrate subresources.\n\t\t\t\t// should thread through the args at some point.\n\t\t\t\tentry.Subresource == \"\" \u0026\u0026\n\t\t\t\tentry.APIVersion == ssaManager.APIVersion\n\t\t})\n\n\ttargetFieldSet, err := decodeManagedFieldsEntrySet(ssaManager)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to convert fields to set: %w\", err)\n\t}\n\n\tcombinedFieldSet := \u0026targetFieldSet\n\n\t// Union the csa manager with the existing SSA manager. Do nothing if\n\t// there was no good candidate found\n\tif csaManagerExists {\n\t\tcsaManager := entries[csaManagerIndex]\n\n\t\tcsaFieldSet, err := decodeManagedFieldsEntrySet(csaManager)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to convert fields to set: %w\", err)\n\t\t}\n\n\t\tcombinedFieldSet = combinedFieldSet.Union(\u0026csaFieldSet)\n\t}\n\n\t// Encode the fields back to the serialized format\n\terr = encodeManagedFieldsEntrySet(\u0026entries[targetIndex], *combinedFieldSet)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to encode field set: %w\", err)\n\t}\n\n\treturn nil\n}","line":{"from":227,"to":276}} {"id":100029241,"name":"findFirstIndex","signature":"func findFirstIndex[T any](","file":"staging/src/k8s.io/client-go/util/csaupgrade/upgrade.go","code":"func findFirstIndex[T any](\n\tcollection []T,\n\tpredicate func(T) bool,\n) (int, bool) {\n\tfor idx, entry := range collection {\n\t\tif predicate(entry) {\n\t\t\treturn idx, true\n\t\t}\n\t}\n\n\treturn -1, false\n}","line":{"from":278,"to":289}} {"id":100029242,"name":"filter","signature":"func filter[T any](","file":"staging/src/k8s.io/client-go/util/csaupgrade/upgrade.go","code":"func filter[T any](\n\tcollection []T,\n\tpredicate func(T) bool,\n) []T {\n\tresult := make([]T, 0, len(collection))\n\n\tfor _, value := range collection {\n\t\tif predicate(value) {\n\t\t\tresult = append(result, value)\n\t\t}\n\t}\n\n\tif len(result) == 0 {\n\t\treturn nil\n\t}\n\n\treturn result\n}","line":{"from":291,"to":308}} {"id":100029243,"name":"decodeManagedFieldsEntrySet","signature":"func decodeManagedFieldsEntrySet(f metav1.ManagedFieldsEntry) (s fieldpath.Set, err error)","file":"staging/src/k8s.io/client-go/util/csaupgrade/upgrade.go","code":"// Included from fieldmanager.internal to avoid dependency cycle\n// FieldsToSet creates a set paths from an input trie of fields\nfunc decodeManagedFieldsEntrySet(f metav1.ManagedFieldsEntry) (s fieldpath.Set, err error) {\n\terr = s.FromJSON(bytes.NewReader(f.FieldsV1.Raw))\n\treturn s, err\n}","line":{"from":310,"to":315}} {"id":100029244,"name":"encodeManagedFieldsEntrySet","signature":"func encodeManagedFieldsEntrySet(f *metav1.ManagedFieldsEntry, s fieldpath.Set) (err error)","file":"staging/src/k8s.io/client-go/util/csaupgrade/upgrade.go","code":"// SetToFields creates a trie of fields from an input set of paths\nfunc encodeManagedFieldsEntrySet(f *metav1.ManagedFieldsEntry, s fieldpath.Set) (err error) {\n\tf.FieldsV1.Raw, err = s.ToJSON()\n\treturn err\n}","line":{"from":317,"to":321}} {"id":100029245,"name":"Error","signature":"func (e CodeExitError) Error() string","file":"staging/src/k8s.io/client-go/util/exec/exec.go","code":"func (e CodeExitError) Error() string {\n\treturn e.Err.Error()\n}","line":{"from":38,"to":40}} {"id":100029246,"name":"String","signature":"func (e CodeExitError) String() string","file":"staging/src/k8s.io/client-go/util/exec/exec.go","code":"func (e CodeExitError) String() string {\n\treturn e.Err.Error()\n}","line":{"from":42,"to":44}} {"id":100029247,"name":"Exited","signature":"func (e CodeExitError) Exited() bool","file":"staging/src/k8s.io/client-go/util/exec/exec.go","code":"func (e CodeExitError) Exited() bool {\n\treturn true\n}","line":{"from":46,"to":48}} {"id":100029248,"name":"ExitStatus","signature":"func (e CodeExitError) ExitStatus() int","file":"staging/src/k8s.io/client-go/util/exec/exec.go","code":"func (e CodeExitError) ExitStatus() int {\n\treturn e.Code\n}","line":{"from":50,"to":52}} {"id":100029249,"name":"NewFakeBackOff","signature":"func NewFakeBackOff(initial, max time.Duration, tc *testingclock.FakeClock) *Backoff","file":"staging/src/k8s.io/client-go/util/flowcontrol/backoff.go","code":"func NewFakeBackOff(initial, max time.Duration, tc *testingclock.FakeClock) *Backoff {\n\treturn newBackoff(tc, initial, max, 0.0)\n}","line":{"from":48,"to":50}} {"id":100029250,"name":"NewBackOff","signature":"func NewBackOff(initial, max time.Duration) *Backoff","file":"staging/src/k8s.io/client-go/util/flowcontrol/backoff.go","code":"func NewBackOff(initial, max time.Duration) *Backoff {\n\treturn NewBackOffWithJitter(initial, max, 0.0)\n}","line":{"from":52,"to":54}} {"id":100029251,"name":"NewFakeBackOffWithJitter","signature":"func NewFakeBackOffWithJitter(initial, max time.Duration, tc *testingclock.FakeClock, maxJitterFactor float64) *Backoff","file":"staging/src/k8s.io/client-go/util/flowcontrol/backoff.go","code":"func NewFakeBackOffWithJitter(initial, max time.Duration, tc *testingclock.FakeClock, maxJitterFactor float64) *Backoff {\n\treturn newBackoff(tc, initial, max, maxJitterFactor)\n}","line":{"from":56,"to":58}} {"id":100029252,"name":"NewBackOffWithJitter","signature":"func NewBackOffWithJitter(initial, max time.Duration, maxJitterFactor float64) *Backoff","file":"staging/src/k8s.io/client-go/util/flowcontrol/backoff.go","code":"func NewBackOffWithJitter(initial, max time.Duration, maxJitterFactor float64) *Backoff {\n\tclock := clock.RealClock{}\n\treturn newBackoff(clock, initial, max, maxJitterFactor)\n}","line":{"from":60,"to":63}} {"id":100029253,"name":"newBackoff","signature":"func newBackoff(clock clock.Clock, initial, max time.Duration, maxJitterFactor float64) *Backoff","file":"staging/src/k8s.io/client-go/util/flowcontrol/backoff.go","code":"func newBackoff(clock clock.Clock, initial, max time.Duration, maxJitterFactor float64) *Backoff {\n\tvar random *rand.Rand\n\tif maxJitterFactor \u003e 0 {\n\t\trandom = rand.New(rand.NewSource(clock.Now().UnixNano()))\n\t}\n\treturn \u0026Backoff{\n\t\tperItemBackoff: map[string]*backoffEntry{},\n\t\tClock: clock,\n\t\tdefaultDuration: initial,\n\t\tmaxDuration: max,\n\t\tmaxJitterFactor: maxJitterFactor,\n\t\trand: random,\n\t}\n}","line":{"from":65,"to":78}} {"id":100029254,"name":"Get","signature":"func (p *Backoff) Get(id string) time.Duration","file":"staging/src/k8s.io/client-go/util/flowcontrol/backoff.go","code":"// Get the current backoff Duration\nfunc (p *Backoff) Get(id string) time.Duration {\n\tp.RLock()\n\tdefer p.RUnlock()\n\tvar delay time.Duration\n\tentry, ok := p.perItemBackoff[id]\n\tif ok {\n\t\tdelay = entry.backoff\n\t}\n\treturn delay\n}","line":{"from":80,"to":90}} {"id":100029255,"name":"Next","signature":"func (p *Backoff) Next(id string, eventTime time.Time)","file":"staging/src/k8s.io/client-go/util/flowcontrol/backoff.go","code":"// move backoff to the next mark, capping at maxDuration\nfunc (p *Backoff) Next(id string, eventTime time.Time) {\n\tp.Lock()\n\tdefer p.Unlock()\n\tentry, ok := p.perItemBackoff[id]\n\tif !ok || hasExpired(eventTime, entry.lastUpdate, p.maxDuration) {\n\t\tentry = p.initEntryUnsafe(id)\n\t\tentry.backoff += p.jitter(entry.backoff)\n\t} else {\n\t\tdelay := entry.backoff * 2 // exponential\n\t\tdelay += p.jitter(entry.backoff) // add some jitter to the delay\n\t\tentry.backoff = time.Duration(integer.Int64Min(int64(delay), int64(p.maxDuration)))\n\t}\n\tentry.lastUpdate = p.Clock.Now()\n}","line":{"from":92,"to":106}} {"id":100029256,"name":"Reset","signature":"func (p *Backoff) Reset(id string)","file":"staging/src/k8s.io/client-go/util/flowcontrol/backoff.go","code":"// Reset forces clearing of all backoff data for a given key.\nfunc (p *Backoff) Reset(id string) {\n\tp.Lock()\n\tdefer p.Unlock()\n\tdelete(p.perItemBackoff, id)\n}","line":{"from":108,"to":113}} {"id":100029257,"name":"IsInBackOffSince","signature":"func (p *Backoff) IsInBackOffSince(id string, eventTime time.Time) bool","file":"staging/src/k8s.io/client-go/util/flowcontrol/backoff.go","code":"// Returns True if the elapsed time since eventTime is smaller than the current backoff window\nfunc (p *Backoff) IsInBackOffSince(id string, eventTime time.Time) bool {\n\tp.RLock()\n\tdefer p.RUnlock()\n\tentry, ok := p.perItemBackoff[id]\n\tif !ok {\n\t\treturn false\n\t}\n\tif hasExpired(eventTime, entry.lastUpdate, p.maxDuration) {\n\t\treturn false\n\t}\n\treturn p.Clock.Since(eventTime) \u003c entry.backoff\n}","line":{"from":115,"to":127}} {"id":100029258,"name":"IsInBackOffSinceUpdate","signature":"func (p *Backoff) IsInBackOffSinceUpdate(id string, eventTime time.Time) bool","file":"staging/src/k8s.io/client-go/util/flowcontrol/backoff.go","code":"// Returns True if time since lastupdate is less than the current backoff window.\nfunc (p *Backoff) IsInBackOffSinceUpdate(id string, eventTime time.Time) bool {\n\tp.RLock()\n\tdefer p.RUnlock()\n\tentry, ok := p.perItemBackoff[id]\n\tif !ok {\n\t\treturn false\n\t}\n\tif hasExpired(eventTime, entry.lastUpdate, p.maxDuration) {\n\t\treturn false\n\t}\n\treturn eventTime.Sub(entry.lastUpdate) \u003c entry.backoff\n}","line":{"from":129,"to":141}} {"id":100029259,"name":"GC","signature":"func (p *Backoff) GC()","file":"staging/src/k8s.io/client-go/util/flowcontrol/backoff.go","code":"// Garbage collect records that have aged past maxDuration. Backoff users are expected\n// to invoke this periodically.\nfunc (p *Backoff) GC() {\n\tp.Lock()\n\tdefer p.Unlock()\n\tnow := p.Clock.Now()\n\tfor id, entry := range p.perItemBackoff {\n\t\tif now.Sub(entry.lastUpdate) \u003e p.maxDuration*2 {\n\t\t\t// GC when entry has not been updated for 2*maxDuration\n\t\t\tdelete(p.perItemBackoff, id)\n\t\t}\n\t}\n}","line":{"from":143,"to":155}} {"id":100029260,"name":"DeleteEntry","signature":"func (p *Backoff) DeleteEntry(id string)","file":"staging/src/k8s.io/client-go/util/flowcontrol/backoff.go","code":"func (p *Backoff) DeleteEntry(id string) {\n\tp.Lock()\n\tdefer p.Unlock()\n\tdelete(p.perItemBackoff, id)\n}","line":{"from":157,"to":161}} {"id":100029261,"name":"initEntryUnsafe","signature":"func (p *Backoff) initEntryUnsafe(id string) *backoffEntry","file":"staging/src/k8s.io/client-go/util/flowcontrol/backoff.go","code":"// Take a lock on *Backoff, before calling initEntryUnsafe\nfunc (p *Backoff) initEntryUnsafe(id string) *backoffEntry {\n\tentry := \u0026backoffEntry{backoff: p.defaultDuration}\n\tp.perItemBackoff[id] = entry\n\treturn entry\n}","line":{"from":163,"to":168}} {"id":100029262,"name":"jitter","signature":"func (p *Backoff) jitter(delay time.Duration) time.Duration","file":"staging/src/k8s.io/client-go/util/flowcontrol/backoff.go","code":"func (p *Backoff) jitter(delay time.Duration) time.Duration {\n\tif p.rand == nil {\n\t\treturn 0\n\t}\n\n\treturn time.Duration(p.rand.Float64() * p.maxJitterFactor * float64(delay))\n}","line":{"from":170,"to":176}} {"id":100029263,"name":"hasExpired","signature":"func hasExpired(eventTime time.Time, lastUpdate time.Time, maxDuration time.Duration) bool","file":"staging/src/k8s.io/client-go/util/flowcontrol/backoff.go","code":"// After 2*maxDuration we restart the backoff factor to the beginning\nfunc hasExpired(eventTime time.Time, lastUpdate time.Time, maxDuration time.Duration) bool {\n\treturn eventTime.Sub(lastUpdate) \u003e maxDuration*2 // consider stable if it's ok for twice the maxDuration\n}","line":{"from":178,"to":181}} {"id":100029264,"name":"NewTokenBucketRateLimiter","signature":"func NewTokenBucketRateLimiter(qps float32, burst int) RateLimiter","file":"staging/src/k8s.io/client-go/util/flowcontrol/throttle.go","code":"// NewTokenBucketRateLimiter creates a rate limiter which implements a token bucket approach.\n// The rate limiter allows bursts of up to 'burst' to exceed the QPS, while still maintaining a\n// smoothed qps rate of 'qps'.\n// The bucket is initially filled with 'burst' tokens, and refills at a rate of 'qps'.\n// The maximum number of tokens in the bucket is capped at 'burst'.\nfunc NewTokenBucketRateLimiter(qps float32, burst int) RateLimiter {\n\tlimiter := rate.NewLimiter(rate.Limit(qps), burst)\n\treturn newTokenBucketRateLimiterWithClock(limiter, clock.RealClock{}, qps)\n}","line":{"from":58,"to":66}} {"id":100029265,"name":"NewTokenBucketPassiveRateLimiter","signature":"func NewTokenBucketPassiveRateLimiter(qps float32, burst int) PassiveRateLimiter","file":"staging/src/k8s.io/client-go/util/flowcontrol/throttle.go","code":"// NewTokenBucketPassiveRateLimiter is similar to NewTokenBucketRateLimiter except that it returns\n// a PassiveRateLimiter which does not have Accept() and Wait() methods.\nfunc NewTokenBucketPassiveRateLimiter(qps float32, burst int) PassiveRateLimiter {\n\tlimiter := rate.NewLimiter(rate.Limit(qps), burst)\n\treturn newTokenBucketRateLimiterWithPassiveClock(limiter, clock.RealClock{}, qps)\n}","line":{"from":68,"to":73}} {"id":100029266,"name":"NewTokenBucketRateLimiterWithClock","signature":"func NewTokenBucketRateLimiterWithClock(qps float32, burst int, c Clock) RateLimiter","file":"staging/src/k8s.io/client-go/util/flowcontrol/throttle.go","code":"// NewTokenBucketRateLimiterWithClock is identical to NewTokenBucketRateLimiter\n// but allows an injectable clock, for testing.\nfunc NewTokenBucketRateLimiterWithClock(qps float32, burst int, c Clock) RateLimiter {\n\tlimiter := rate.NewLimiter(rate.Limit(qps), burst)\n\treturn newTokenBucketRateLimiterWithClock(limiter, c, qps)\n}","line":{"from":83,"to":88}} {"id":100029267,"name":"NewTokenBucketPassiveRateLimiterWithClock","signature":"func NewTokenBucketPassiveRateLimiterWithClock(qps float32, burst int, c clock.PassiveClock) PassiveRateLimiter","file":"staging/src/k8s.io/client-go/util/flowcontrol/throttle.go","code":"// NewTokenBucketPassiveRateLimiterWithClock is similar to NewTokenBucketRateLimiterWithClock\n// except that it returns a PassiveRateLimiter which does not have Accept() and Wait() methods\n// and uses a PassiveClock.\nfunc NewTokenBucketPassiveRateLimiterWithClock(qps float32, burst int, c clock.PassiveClock) PassiveRateLimiter {\n\tlimiter := rate.NewLimiter(rate.Limit(qps), burst)\n\treturn newTokenBucketRateLimiterWithPassiveClock(limiter, c, qps)\n}","line":{"from":90,"to":96}} {"id":100029268,"name":"newTokenBucketRateLimiterWithClock","signature":"func newTokenBucketRateLimiterWithClock(limiter *rate.Limiter, c Clock, qps float32) *tokenBucketRateLimiter","file":"staging/src/k8s.io/client-go/util/flowcontrol/throttle.go","code":"func newTokenBucketRateLimiterWithClock(limiter *rate.Limiter, c Clock, qps float32) *tokenBucketRateLimiter {\n\treturn \u0026tokenBucketRateLimiter{\n\t\ttokenBucketPassiveRateLimiter: *newTokenBucketRateLimiterWithPassiveClock(limiter, c, qps),\n\t\tclock: c,\n\t}\n}","line":{"from":98,"to":103}} {"id":100029269,"name":"newTokenBucketRateLimiterWithPassiveClock","signature":"func newTokenBucketRateLimiterWithPassiveClock(limiter *rate.Limiter, c clock.PassiveClock, qps float32) *tokenBucketPassiveRateLimiter","file":"staging/src/k8s.io/client-go/util/flowcontrol/throttle.go","code":"func newTokenBucketRateLimiterWithPassiveClock(limiter *rate.Limiter, c clock.PassiveClock, qps float32) *tokenBucketPassiveRateLimiter {\n\treturn \u0026tokenBucketPassiveRateLimiter{\n\t\tlimiter: limiter,\n\t\tqps: qps,\n\t\tclock: c,\n\t}\n}","line":{"from":105,"to":111}} {"id":100029270,"name":"Stop","signature":"func (tbprl *tokenBucketPassiveRateLimiter) Stop()","file":"staging/src/k8s.io/client-go/util/flowcontrol/throttle.go","code":"func (tbprl *tokenBucketPassiveRateLimiter) Stop() {\n}","line":{"from":113,"to":114}} {"id":100029271,"name":"QPS","signature":"func (tbprl *tokenBucketPassiveRateLimiter) QPS() float32","file":"staging/src/k8s.io/client-go/util/flowcontrol/throttle.go","code":"func (tbprl *tokenBucketPassiveRateLimiter) QPS() float32 {\n\treturn tbprl.qps\n}","line":{"from":116,"to":118}} {"id":100029272,"name":"TryAccept","signature":"func (tbprl *tokenBucketPassiveRateLimiter) TryAccept() bool","file":"staging/src/k8s.io/client-go/util/flowcontrol/throttle.go","code":"func (tbprl *tokenBucketPassiveRateLimiter) TryAccept() bool {\n\treturn tbprl.limiter.AllowN(tbprl.clock.Now(), 1)\n}","line":{"from":120,"to":122}} {"id":100029273,"name":"Accept","signature":"func (tbrl *tokenBucketRateLimiter) Accept()","file":"staging/src/k8s.io/client-go/util/flowcontrol/throttle.go","code":"// Accept will block until a token becomes available\nfunc (tbrl *tokenBucketRateLimiter) Accept() {\n\tnow := tbrl.clock.Now()\n\ttbrl.clock.Sleep(tbrl.limiter.ReserveN(now, 1).DelayFrom(now))\n}","line":{"from":124,"to":128}} {"id":100029274,"name":"Wait","signature":"func (tbrl *tokenBucketRateLimiter) Wait(ctx context.Context) error","file":"staging/src/k8s.io/client-go/util/flowcontrol/throttle.go","code":"func (tbrl *tokenBucketRateLimiter) Wait(ctx context.Context) error {\n\treturn tbrl.limiter.Wait(ctx)\n}","line":{"from":130,"to":132}} {"id":100029275,"name":"NewFakeAlwaysRateLimiter","signature":"func NewFakeAlwaysRateLimiter() RateLimiter","file":"staging/src/k8s.io/client-go/util/flowcontrol/throttle.go","code":"func NewFakeAlwaysRateLimiter() RateLimiter {\n\treturn \u0026fakeAlwaysRateLimiter{}\n}","line":{"from":136,"to":138}} {"id":100029276,"name":"TryAccept","signature":"func (t *fakeAlwaysRateLimiter) TryAccept() bool","file":"staging/src/k8s.io/client-go/util/flowcontrol/throttle.go","code":"func (t *fakeAlwaysRateLimiter) TryAccept() bool {\n\treturn true\n}","line":{"from":140,"to":142}} {"id":100029277,"name":"Stop","signature":"func (t *fakeAlwaysRateLimiter) Stop() {}","file":"staging/src/k8s.io/client-go/util/flowcontrol/throttle.go","code":"func (t *fakeAlwaysRateLimiter) Stop() {}","line":{"from":144,"to":144}} {"id":100029278,"name":"Accept","signature":"func (t *fakeAlwaysRateLimiter) Accept() {}","file":"staging/src/k8s.io/client-go/util/flowcontrol/throttle.go","code":"func (t *fakeAlwaysRateLimiter) Accept() {}","line":{"from":146,"to":146}} {"id":100029279,"name":"QPS","signature":"func (t *fakeAlwaysRateLimiter) QPS() float32","file":"staging/src/k8s.io/client-go/util/flowcontrol/throttle.go","code":"func (t *fakeAlwaysRateLimiter) QPS() float32 {\n\treturn 1\n}","line":{"from":148,"to":150}} {"id":100029280,"name":"Wait","signature":"func (t *fakeAlwaysRateLimiter) Wait(ctx context.Context) error","file":"staging/src/k8s.io/client-go/util/flowcontrol/throttle.go","code":"func (t *fakeAlwaysRateLimiter) Wait(ctx context.Context) error {\n\treturn nil\n}","line":{"from":152,"to":154}} {"id":100029281,"name":"NewFakeNeverRateLimiter","signature":"func NewFakeNeverRateLimiter() RateLimiter","file":"staging/src/k8s.io/client-go/util/flowcontrol/throttle.go","code":"func NewFakeNeverRateLimiter() RateLimiter {\n\trl := fakeNeverRateLimiter{}\n\trl.wg.Add(1)\n\treturn \u0026rl\n}","line":{"from":160,"to":164}} {"id":100029282,"name":"TryAccept","signature":"func (t *fakeNeverRateLimiter) TryAccept() bool","file":"staging/src/k8s.io/client-go/util/flowcontrol/throttle.go","code":"func (t *fakeNeverRateLimiter) TryAccept() bool {\n\treturn false\n}","line":{"from":166,"to":168}} {"id":100029283,"name":"Stop","signature":"func (t *fakeNeverRateLimiter) Stop()","file":"staging/src/k8s.io/client-go/util/flowcontrol/throttle.go","code":"func (t *fakeNeverRateLimiter) Stop() {\n\tt.wg.Done()\n}","line":{"from":170,"to":172}} {"id":100029284,"name":"Accept","signature":"func (t *fakeNeverRateLimiter) Accept()","file":"staging/src/k8s.io/client-go/util/flowcontrol/throttle.go","code":"func (t *fakeNeverRateLimiter) Accept() {\n\tt.wg.Wait()\n}","line":{"from":174,"to":176}} {"id":100029285,"name":"QPS","signature":"func (t *fakeNeverRateLimiter) QPS() float32","file":"staging/src/k8s.io/client-go/util/flowcontrol/throttle.go","code":"func (t *fakeNeverRateLimiter) QPS() float32 {\n\treturn 1\n}","line":{"from":178,"to":180}} {"id":100029286,"name":"Wait","signature":"func (t *fakeNeverRateLimiter) Wait(ctx context.Context) error","file":"staging/src/k8s.io/client-go/util/flowcontrol/throttle.go","code":"func (t *fakeNeverRateLimiter) Wait(ctx context.Context) error {\n\treturn errors.New(\"can not be accept\")\n}","line":{"from":182,"to":184}} {"id":100029287,"name":"HomeDir","signature":"func HomeDir() string","file":"staging/src/k8s.io/client-go/util/homedir/homedir.go","code":"// HomeDir returns the home directory for the current user.\n// On Windows:\n// 1. the first of %HOME%, %HOMEDRIVE%%HOMEPATH%, %USERPROFILE% containing a `.kube\\config` file is returned.\n// 2. if none of those locations contain a `.kube\\config` file, the first of %HOME%, %USERPROFILE%, %HOMEDRIVE%%HOMEPATH% that exists and is writeable is returned.\n// 3. if none of those locations are writeable, the first of %HOME%, %USERPROFILE%, %HOMEDRIVE%%HOMEPATH% that exists is returned.\n// 4. if none of those locations exists, the first of %HOME%, %USERPROFILE%, %HOMEDRIVE%%HOMEPATH% that is set is returned.\nfunc HomeDir() string {\n\tif runtime.GOOS == \"windows\" {\n\t\thome := os.Getenv(\"HOME\")\n\t\thomeDriveHomePath := \"\"\n\t\tif homeDrive, homePath := os.Getenv(\"HOMEDRIVE\"), os.Getenv(\"HOMEPATH\"); len(homeDrive) \u003e 0 \u0026\u0026 len(homePath) \u003e 0 {\n\t\t\thomeDriveHomePath = homeDrive + homePath\n\t\t}\n\t\tuserProfile := os.Getenv(\"USERPROFILE\")\n\n\t\t// Return first of %HOME%, %HOMEDRIVE%/%HOMEPATH%, %USERPROFILE% that contains a `.kube\\config` file.\n\t\t// %HOMEDRIVE%/%HOMEPATH% is preferred over %USERPROFILE% for backwards-compatibility.\n\t\tfor _, p := range []string{home, homeDriveHomePath, userProfile} {\n\t\t\tif len(p) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif _, err := os.Stat(filepath.Join(p, \".kube\", \"config\")); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn p\n\t\t}\n\n\t\tfirstSetPath := \"\"\n\t\tfirstExistingPath := \"\"\n\n\t\t// Prefer %USERPROFILE% over %HOMEDRIVE%/%HOMEPATH% for compatibility with other auth-writing tools\n\t\tfor _, p := range []string{home, userProfile, homeDriveHomePath} {\n\t\t\tif len(p) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(firstSetPath) == 0 {\n\t\t\t\t// remember the first path that is set\n\t\t\t\tfirstSetPath = p\n\t\t\t}\n\t\t\tinfo, err := os.Stat(p)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(firstExistingPath) == 0 {\n\t\t\t\t// remember the first path that exists\n\t\t\t\tfirstExistingPath = p\n\t\t\t}\n\t\t\tif info.IsDir() \u0026\u0026 info.Mode().Perm()\u0026(1\u003c\u003c(uint(7))) != 0 {\n\t\t\t\t// return first path that is writeable\n\t\t\t\treturn p\n\t\t\t}\n\t\t}\n\n\t\t// If none are writeable, return first location that exists\n\t\tif len(firstExistingPath) \u003e 0 {\n\t\t\treturn firstExistingPath\n\t\t}\n\n\t\t// If none exist, return first location that is set\n\t\tif len(firstSetPath) \u003e 0 {\n\t\t\treturn firstSetPath\n\t\t}\n\n\t\t// We've got nothing\n\t\treturn \"\"\n\t}\n\treturn os.Getenv(\"HOME\")\n}","line":{"from":25,"to":92}} {"id":100029288,"name":"New","signature":"func New(name string) *JSONPath","file":"staging/src/k8s.io/client-go/util/jsonpath/jsonpath.go","code":"// New creates a new JSONPath with the given name.\nfunc New(name string) *JSONPath {\n\treturn \u0026JSONPath{\n\t\tname: name,\n\t\tbeginRange: 0,\n\t\tinRange: 0,\n\t\tendRange: 0,\n\t}\n}","line":{"from":43,"to":51}} {"id":100029289,"name":"AllowMissingKeys","signature":"func (j *JSONPath) AllowMissingKeys(allow bool) *JSONPath","file":"staging/src/k8s.io/client-go/util/jsonpath/jsonpath.go","code":"// AllowMissingKeys allows a caller to specify whether they want an error if a field or map key\n// cannot be located, or simply an empty result. The receiver is returned for chaining.\nfunc (j *JSONPath) AllowMissingKeys(allow bool) *JSONPath {\n\tj.allowMissingKeys = allow\n\treturn j\n}","line":{"from":53,"to":58}} {"id":100029290,"name":"Parse","signature":"func (j *JSONPath) Parse(text string) error","file":"staging/src/k8s.io/client-go/util/jsonpath/jsonpath.go","code":"// Parse parses the given template and returns an error.\nfunc (j *JSONPath) Parse(text string) error {\n\tvar err error\n\tj.parser, err = Parse(j.name, text)\n\treturn err\n}","line":{"from":60,"to":65}} {"id":100029291,"name":"Execute","signature":"func (j *JSONPath) Execute(wr io.Writer, data interface{}) error","file":"staging/src/k8s.io/client-go/util/jsonpath/jsonpath.go","code":"// Execute bounds data into template and writes the result.\nfunc (j *JSONPath) Execute(wr io.Writer, data interface{}) error {\n\tfullResults, err := j.FindResults(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor ix := range fullResults {\n\t\tif err := j.PrintResults(wr, fullResults[ix]); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":67,"to":79}} {"id":100029292,"name":"FindResults","signature":"func (j *JSONPath) FindResults(data interface{}) ([][]reflect.Value, error)","file":"staging/src/k8s.io/client-go/util/jsonpath/jsonpath.go","code":"func (j *JSONPath) FindResults(data interface{}) ([][]reflect.Value, error) {\n\tif j.parser == nil {\n\t\treturn nil, fmt.Errorf(\"%s is an incomplete jsonpath template\", j.name)\n\t}\n\n\tcur := []reflect.Value{reflect.ValueOf(data)}\n\tnodes := j.parser.Root.Nodes\n\tfullResult := [][]reflect.Value{}\n\tfor i := 0; i \u003c len(nodes); i++ {\n\t\tnode := nodes[i]\n\t\tresults, err := j.walk(cur, node)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// encounter an end node, break the current block\n\t\tif j.endRange \u003e 0 \u0026\u0026 j.endRange \u003c= j.inRange {\n\t\t\tj.endRange--\n\t\t\tj.lastEndNode = \u0026nodes[i]\n\t\t\tbreak\n\t\t}\n\t\t// encounter a range node, start a range loop\n\t\tif j.beginRange \u003e 0 {\n\t\t\tj.beginRange--\n\t\t\tj.inRange++\n\t\t\tif len(results) \u003e 0 {\n\t\t\t\tfor _, value := range results {\n\t\t\t\t\tj.parser.Root.Nodes = nodes[i+1:]\n\t\t\t\t\tnextResults, err := j.FindResults(value.Interface())\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tfullResult = append(fullResult, nextResults...)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// If the range has no results, we still need to process the nodes within the range\n\t\t\t\t// so the position will advance to the end node\n\t\t\t\tj.parser.Root.Nodes = nodes[i+1:]\n\t\t\t\t_, err := j.FindResults(nil)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tj.inRange--\n\n\t\t\t// Fast forward to resume processing after the most recent end node that was encountered\n\t\t\tfor k := i + 1; k \u003c len(nodes); k++ {\n\t\t\t\tif \u0026nodes[k] == j.lastEndNode {\n\t\t\t\t\ti = k\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tfullResult = append(fullResult, results)\n\t}\n\treturn fullResult, nil\n}","line":{"from":81,"to":138}} {"id":100029293,"name":"EnableJSONOutput","signature":"func (j *JSONPath) EnableJSONOutput(v bool)","file":"staging/src/k8s.io/client-go/util/jsonpath/jsonpath.go","code":"// EnableJSONOutput changes the PrintResults behavior to return a JSON array of results\nfunc (j *JSONPath) EnableJSONOutput(v bool) {\n\tj.outputJSON = v\n}","line":{"from":140,"to":143}} {"id":100029294,"name":"PrintResults","signature":"func (j *JSONPath) PrintResults(wr io.Writer, results []reflect.Value) error","file":"staging/src/k8s.io/client-go/util/jsonpath/jsonpath.go","code":"// PrintResults writes the results into writer\nfunc (j *JSONPath) PrintResults(wr io.Writer, results []reflect.Value) error {\n\tif j.outputJSON {\n\t\t// convert the []reflect.Value to something that json\n\t\t// will be able to marshal\n\t\tr := make([]interface{}, 0, len(results))\n\t\tfor i := range results {\n\t\t\tr = append(r, results[i].Interface())\n\t\t}\n\t\tresults = []reflect.Value{reflect.ValueOf(r)}\n\t}\n\tfor i, r := range results {\n\t\tvar text []byte\n\t\tvar err error\n\t\toutputJSON := true\n\t\tkind := r.Kind()\n\t\tif kind == reflect.Interface {\n\t\t\tkind = r.Elem().Kind()\n\t\t}\n\t\tswitch kind {\n\t\tcase reflect.Map:\n\t\tcase reflect.Array:\n\t\tcase reflect.Slice:\n\t\tcase reflect.Struct:\n\t\tdefault:\n\t\t\toutputJSON = false\n\t\t}\n\t\tswitch {\n\t\tcase outputJSON || j.outputJSON:\n\t\t\tif j.outputJSON {\n\t\t\t\ttext, err = json.MarshalIndent(r.Interface(), \"\", \" \")\n\t\t\t\ttext = append(text, '\\n')\n\t\t\t} else {\n\t\t\t\ttext, err = json.Marshal(r.Interface())\n\t\t\t}\n\t\tdefault:\n\t\t\ttext, err = j.evalToText(r)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif i != len(results)-1 {\n\t\t\ttext = append(text, ' ')\n\t\t}\n\t\tif _, err = wr.Write(text); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n\n}","line":{"from":145,"to":196}} {"id":100029295,"name":"walk","signature":"func (j *JSONPath) walk(value []reflect.Value, node Node) ([]reflect.Value, error)","file":"staging/src/k8s.io/client-go/util/jsonpath/jsonpath.go","code":"// walk visits tree rooted at the given node in DFS order\nfunc (j *JSONPath) walk(value []reflect.Value, node Node) ([]reflect.Value, error) {\n\tswitch node := node.(type) {\n\tcase *ListNode:\n\t\treturn j.evalList(value, node)\n\tcase *TextNode:\n\t\treturn []reflect.Value{reflect.ValueOf(node.Text)}, nil\n\tcase *FieldNode:\n\t\treturn j.evalField(value, node)\n\tcase *ArrayNode:\n\t\treturn j.evalArray(value, node)\n\tcase *FilterNode:\n\t\treturn j.evalFilter(value, node)\n\tcase *IntNode:\n\t\treturn j.evalInt(value, node)\n\tcase *BoolNode:\n\t\treturn j.evalBool(value, node)\n\tcase *FloatNode:\n\t\treturn j.evalFloat(value, node)\n\tcase *WildcardNode:\n\t\treturn j.evalWildcard(value, node)\n\tcase *RecursiveNode:\n\t\treturn j.evalRecursive(value, node)\n\tcase *UnionNode:\n\t\treturn j.evalUnion(value, node)\n\tcase *IdentifierNode:\n\t\treturn j.evalIdentifier(value, node)\n\tdefault:\n\t\treturn value, fmt.Errorf(\"unexpected Node %v\", node)\n\t}\n}","line":{"from":198,"to":228}} {"id":100029296,"name":"evalInt","signature":"func (j *JSONPath) evalInt(input []reflect.Value, node *IntNode) ([]reflect.Value, error)","file":"staging/src/k8s.io/client-go/util/jsonpath/jsonpath.go","code":"// evalInt evaluates IntNode\nfunc (j *JSONPath) evalInt(input []reflect.Value, node *IntNode) ([]reflect.Value, error) {\n\tresult := make([]reflect.Value, len(input))\n\tfor i := range input {\n\t\tresult[i] = reflect.ValueOf(node.Value)\n\t}\n\treturn result, nil\n}","line":{"from":230,"to":237}} {"id":100029297,"name":"evalFloat","signature":"func (j *JSONPath) evalFloat(input []reflect.Value, node *FloatNode) ([]reflect.Value, error)","file":"staging/src/k8s.io/client-go/util/jsonpath/jsonpath.go","code":"// evalFloat evaluates FloatNode\nfunc (j *JSONPath) evalFloat(input []reflect.Value, node *FloatNode) ([]reflect.Value, error) {\n\tresult := make([]reflect.Value, len(input))\n\tfor i := range input {\n\t\tresult[i] = reflect.ValueOf(node.Value)\n\t}\n\treturn result, nil\n}","line":{"from":239,"to":246}} {"id":100029298,"name":"evalBool","signature":"func (j *JSONPath) evalBool(input []reflect.Value, node *BoolNode) ([]reflect.Value, error)","file":"staging/src/k8s.io/client-go/util/jsonpath/jsonpath.go","code":"// evalBool evaluates BoolNode\nfunc (j *JSONPath) evalBool(input []reflect.Value, node *BoolNode) ([]reflect.Value, error) {\n\tresult := make([]reflect.Value, len(input))\n\tfor i := range input {\n\t\tresult[i] = reflect.ValueOf(node.Value)\n\t}\n\treturn result, nil\n}","line":{"from":248,"to":255}} {"id":100029299,"name":"evalList","signature":"func (j *JSONPath) evalList(value []reflect.Value, node *ListNode) ([]reflect.Value, error)","file":"staging/src/k8s.io/client-go/util/jsonpath/jsonpath.go","code":"// evalList evaluates ListNode\nfunc (j *JSONPath) evalList(value []reflect.Value, node *ListNode) ([]reflect.Value, error) {\n\tvar err error\n\tcurValue := value\n\tfor _, node := range node.Nodes {\n\t\tcurValue, err = j.walk(curValue, node)\n\t\tif err != nil {\n\t\t\treturn curValue, err\n\t\t}\n\t}\n\treturn curValue, nil\n}","line":{"from":257,"to":268}} {"id":100029300,"name":"evalIdentifier","signature":"func (j *JSONPath) evalIdentifier(input []reflect.Value, node *IdentifierNode) ([]reflect.Value, error)","file":"staging/src/k8s.io/client-go/util/jsonpath/jsonpath.go","code":"// evalIdentifier evaluates IdentifierNode\nfunc (j *JSONPath) evalIdentifier(input []reflect.Value, node *IdentifierNode) ([]reflect.Value, error) {\n\tresults := []reflect.Value{}\n\tswitch node.Name {\n\tcase \"range\":\n\t\tj.beginRange++\n\t\tresults = input\n\tcase \"end\":\n\t\tif j.inRange \u003e 0 {\n\t\t\tj.endRange++\n\t\t} else {\n\t\t\treturn results, fmt.Errorf(\"not in range, nothing to end\")\n\t\t}\n\tdefault:\n\t\treturn input, fmt.Errorf(\"unrecognized identifier %v\", node.Name)\n\t}\n\treturn results, nil\n}","line":{"from":270,"to":287}} {"id":100029301,"name":"evalArray","signature":"func (j *JSONPath) evalArray(input []reflect.Value, node *ArrayNode) ([]reflect.Value, error)","file":"staging/src/k8s.io/client-go/util/jsonpath/jsonpath.go","code":"// evalArray evaluates ArrayNode\nfunc (j *JSONPath) evalArray(input []reflect.Value, node *ArrayNode) ([]reflect.Value, error) {\n\tresult := []reflect.Value{}\n\tfor _, value := range input {\n\n\t\tvalue, isNil := template.Indirect(value)\n\t\tif isNil {\n\t\t\tcontinue\n\t\t}\n\t\tif value.Kind() != reflect.Array \u0026\u0026 value.Kind() != reflect.Slice {\n\t\t\treturn input, fmt.Errorf(\"%v is not array or slice\", value.Type())\n\t\t}\n\t\tparams := node.Params\n\t\tif !params[0].Known {\n\t\t\tparams[0].Value = 0\n\t\t}\n\t\tif params[0].Value \u003c 0 {\n\t\t\tparams[0].Value += value.Len()\n\t\t}\n\t\tif !params[1].Known {\n\t\t\tparams[1].Value = value.Len()\n\t\t}\n\n\t\tif params[1].Value \u003c 0 || (params[1].Value == 0 \u0026\u0026 params[1].Derived) {\n\t\t\tparams[1].Value += value.Len()\n\t\t}\n\t\tsliceLength := value.Len()\n\t\tif params[1].Value != params[0].Value { // if you're requesting zero elements, allow it through.\n\t\t\tif params[0].Value \u003e= sliceLength || params[0].Value \u003c 0 {\n\t\t\t\treturn input, fmt.Errorf(\"array index out of bounds: index %d, length %d\", params[0].Value, sliceLength)\n\t\t\t}\n\t\t\tif params[1].Value \u003e sliceLength || params[1].Value \u003c 0 {\n\t\t\t\treturn input, fmt.Errorf(\"array index out of bounds: index %d, length %d\", params[1].Value-1, sliceLength)\n\t\t\t}\n\t\t\tif params[0].Value \u003e params[1].Value {\n\t\t\t\treturn input, fmt.Errorf(\"starting index %d is greater than ending index %d\", params[0].Value, params[1].Value)\n\t\t\t}\n\t\t} else {\n\t\t\treturn result, nil\n\t\t}\n\n\t\tvalue = value.Slice(params[0].Value, params[1].Value)\n\n\t\tstep := 1\n\t\tif params[2].Known {\n\t\t\tif params[2].Value \u003c= 0 {\n\t\t\t\treturn input, fmt.Errorf(\"step must be \u003e 0\")\n\t\t\t}\n\t\t\tstep = params[2].Value\n\t\t}\n\t\tfor i := 0; i \u003c value.Len(); i += step {\n\t\t\tresult = append(result, value.Index(i))\n\t\t}\n\t}\n\treturn result, nil\n}","line":{"from":289,"to":344}} {"id":100029302,"name":"evalUnion","signature":"func (j *JSONPath) evalUnion(input []reflect.Value, node *UnionNode) ([]reflect.Value, error)","file":"staging/src/k8s.io/client-go/util/jsonpath/jsonpath.go","code":"// evalUnion evaluates UnionNode\nfunc (j *JSONPath) evalUnion(input []reflect.Value, node *UnionNode) ([]reflect.Value, error) {\n\tresult := []reflect.Value{}\n\tfor _, listNode := range node.Nodes {\n\t\ttemp, err := j.evalList(input, listNode)\n\t\tif err != nil {\n\t\t\treturn input, err\n\t\t}\n\t\tresult = append(result, temp...)\n\t}\n\treturn result, nil\n}","line":{"from":346,"to":357}} {"id":100029303,"name":"findFieldInValue","signature":"func (j *JSONPath) findFieldInValue(value *reflect.Value, node *FieldNode) (reflect.Value, error)","file":"staging/src/k8s.io/client-go/util/jsonpath/jsonpath.go","code":"func (j *JSONPath) findFieldInValue(value *reflect.Value, node *FieldNode) (reflect.Value, error) {\n\tt := value.Type()\n\tvar inlineValue *reflect.Value\n\tfor ix := 0; ix \u003c t.NumField(); ix++ {\n\t\tf := t.Field(ix)\n\t\tjsonTag := f.Tag.Get(\"json\")\n\t\tparts := strings.Split(jsonTag, \",\")\n\t\tif len(parts) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif parts[0] == node.Value {\n\t\t\treturn value.Field(ix), nil\n\t\t}\n\t\tif len(parts[0]) == 0 {\n\t\t\tval := value.Field(ix)\n\t\t\tinlineValue = \u0026val\n\t\t}\n\t}\n\tif inlineValue != nil {\n\t\tif inlineValue.Kind() == reflect.Struct {\n\t\t\t// handle 'inline'\n\t\t\tmatch, err := j.findFieldInValue(inlineValue, node)\n\t\t\tif err != nil {\n\t\t\t\treturn reflect.Value{}, err\n\t\t\t}\n\t\t\tif match.IsValid() {\n\t\t\t\treturn match, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn value.FieldByName(node.Value), nil\n}","line":{"from":359,"to":390}} {"id":100029304,"name":"evalField","signature":"func (j *JSONPath) evalField(input []reflect.Value, node *FieldNode) ([]reflect.Value, error)","file":"staging/src/k8s.io/client-go/util/jsonpath/jsonpath.go","code":"// evalField evaluates field of struct or key of map.\nfunc (j *JSONPath) evalField(input []reflect.Value, node *FieldNode) ([]reflect.Value, error) {\n\tresults := []reflect.Value{}\n\t// If there's no input, there's no output\n\tif len(input) == 0 {\n\t\treturn results, nil\n\t}\n\tfor _, value := range input {\n\t\tvar result reflect.Value\n\t\tvalue, isNil := template.Indirect(value)\n\t\tif isNil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif value.Kind() == reflect.Struct {\n\t\t\tvar err error\n\t\t\tif result, err = j.findFieldInValue(\u0026value, node); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else if value.Kind() == reflect.Map {\n\t\t\tmapKeyType := value.Type().Key()\n\t\t\tnodeValue := reflect.ValueOf(node.Value)\n\t\t\t// node value type must be convertible to map key type\n\t\t\tif !nodeValue.Type().ConvertibleTo(mapKeyType) {\n\t\t\t\treturn results, fmt.Errorf(\"%s is not convertible to %s\", nodeValue, mapKeyType)\n\t\t\t}\n\t\t\tresult = value.MapIndex(nodeValue.Convert(mapKeyType))\n\t\t}\n\t\tif result.IsValid() {\n\t\t\tresults = append(results, result)\n\t\t}\n\t}\n\tif len(results) == 0 {\n\t\tif j.allowMissingKeys {\n\t\t\treturn results, nil\n\t\t}\n\t\treturn results, fmt.Errorf(\"%s is not found\", node.Value)\n\t}\n\treturn results, nil\n}","line":{"from":392,"to":431}} {"id":100029305,"name":"evalWildcard","signature":"func (j *JSONPath) evalWildcard(input []reflect.Value, node *WildcardNode) ([]reflect.Value, error)","file":"staging/src/k8s.io/client-go/util/jsonpath/jsonpath.go","code":"// evalWildcard extracts all contents of the given value\nfunc (j *JSONPath) evalWildcard(input []reflect.Value, node *WildcardNode) ([]reflect.Value, error) {\n\tresults := []reflect.Value{}\n\tfor _, value := range input {\n\t\tvalue, isNil := template.Indirect(value)\n\t\tif isNil {\n\t\t\tcontinue\n\t\t}\n\n\t\tkind := value.Kind()\n\t\tif kind == reflect.Struct {\n\t\t\tfor i := 0; i \u003c value.NumField(); i++ {\n\t\t\t\tresults = append(results, value.Field(i))\n\t\t\t}\n\t\t} else if kind == reflect.Map {\n\t\t\tfor _, key := range value.MapKeys() {\n\t\t\t\tresults = append(results, value.MapIndex(key))\n\t\t\t}\n\t\t} else if kind == reflect.Array || kind == reflect.Slice || kind == reflect.String {\n\t\t\tfor i := 0; i \u003c value.Len(); i++ {\n\t\t\t\tresults = append(results, value.Index(i))\n\t\t\t}\n\t\t}\n\t}\n\treturn results, nil\n}","line":{"from":433,"to":458}} {"id":100029306,"name":"evalRecursive","signature":"func (j *JSONPath) evalRecursive(input []reflect.Value, node *RecursiveNode) ([]reflect.Value, error)","file":"staging/src/k8s.io/client-go/util/jsonpath/jsonpath.go","code":"// evalRecursive visits the given value recursively and pushes all of them to result\nfunc (j *JSONPath) evalRecursive(input []reflect.Value, node *RecursiveNode) ([]reflect.Value, error) {\n\tresult := []reflect.Value{}\n\tfor _, value := range input {\n\t\tresults := []reflect.Value{}\n\t\tvalue, isNil := template.Indirect(value)\n\t\tif isNil {\n\t\t\tcontinue\n\t\t}\n\n\t\tkind := value.Kind()\n\t\tif kind == reflect.Struct {\n\t\t\tfor i := 0; i \u003c value.NumField(); i++ {\n\t\t\t\tresults = append(results, value.Field(i))\n\t\t\t}\n\t\t} else if kind == reflect.Map {\n\t\t\tfor _, key := range value.MapKeys() {\n\t\t\t\tresults = append(results, value.MapIndex(key))\n\t\t\t}\n\t\t} else if kind == reflect.Array || kind == reflect.Slice || kind == reflect.String {\n\t\t\tfor i := 0; i \u003c value.Len(); i++ {\n\t\t\t\tresults = append(results, value.Index(i))\n\t\t\t}\n\t\t}\n\t\tif len(results) != 0 {\n\t\t\tresult = append(result, value)\n\t\t\toutput, err := j.evalRecursive(results, node)\n\t\t\tif err != nil {\n\t\t\t\treturn result, err\n\t\t\t}\n\t\t\tresult = append(result, output...)\n\t\t}\n\t}\n\treturn result, nil\n}","line":{"from":460,"to":494}} {"id":100029307,"name":"evalFilter","signature":"func (j *JSONPath) evalFilter(input []reflect.Value, node *FilterNode) ([]reflect.Value, error)","file":"staging/src/k8s.io/client-go/util/jsonpath/jsonpath.go","code":"// evalFilter filters array according to FilterNode\nfunc (j *JSONPath) evalFilter(input []reflect.Value, node *FilterNode) ([]reflect.Value, error) {\n\tresults := []reflect.Value{}\n\tfor _, value := range input {\n\t\tvalue, _ = template.Indirect(value)\n\n\t\tif value.Kind() != reflect.Array \u0026\u0026 value.Kind() != reflect.Slice {\n\t\t\treturn input, fmt.Errorf(\"%v is not array or slice and cannot be filtered\", value)\n\t\t}\n\t\tfor i := 0; i \u003c value.Len(); i++ {\n\t\t\ttemp := []reflect.Value{value.Index(i)}\n\t\t\tlefts, err := j.evalList(temp, node.Left)\n\n\t\t\t//case exists\n\t\t\tif node.Operator == \"exists\" {\n\t\t\t\tif len(lefts) \u003e 0 {\n\t\t\t\t\tresults = append(results, value.Index(i))\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\treturn input, err\n\t\t\t}\n\n\t\t\tvar left, right interface{}\n\t\t\tswitch {\n\t\t\tcase len(lefts) == 0:\n\t\t\t\tcontinue\n\t\t\tcase len(lefts) \u003e 1:\n\t\t\t\treturn input, fmt.Errorf(\"can only compare one element at a time\")\n\t\t\t}\n\t\t\tleft = lefts[0].Interface()\n\n\t\t\trights, err := j.evalList(temp, node.Right)\n\t\t\tif err != nil {\n\t\t\t\treturn input, err\n\t\t\t}\n\t\t\tswitch {\n\t\t\tcase len(rights) == 0:\n\t\t\t\tcontinue\n\t\t\tcase len(rights) \u003e 1:\n\t\t\t\treturn input, fmt.Errorf(\"can only compare one element at a time\")\n\t\t\t}\n\t\t\tright = rights[0].Interface()\n\n\t\t\tpass := false\n\t\t\tswitch node.Operator {\n\t\t\tcase \"\u003c\":\n\t\t\t\tpass, err = template.Less(left, right)\n\t\t\tcase \"\u003e\":\n\t\t\t\tpass, err = template.Greater(left, right)\n\t\t\tcase \"==\":\n\t\t\t\tpass, err = template.Equal(left, right)\n\t\t\tcase \"!=\":\n\t\t\t\tpass, err = template.NotEqual(left, right)\n\t\t\tcase \"\u003c=\":\n\t\t\t\tpass, err = template.LessEqual(left, right)\n\t\t\tcase \"\u003e=\":\n\t\t\t\tpass, err = template.GreaterEqual(left, right)\n\t\t\tdefault:\n\t\t\t\treturn results, fmt.Errorf(\"unrecognized filter operator %s\", node.Operator)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn results, err\n\t\t\t}\n\t\t\tif pass {\n\t\t\t\tresults = append(results, value.Index(i))\n\t\t\t}\n\t\t}\n\t}\n\treturn results, nil\n}","line":{"from":496,"to":568}} {"id":100029308,"name":"evalToText","signature":"func (j *JSONPath) evalToText(v reflect.Value) ([]byte, error)","file":"staging/src/k8s.io/client-go/util/jsonpath/jsonpath.go","code":"// evalToText translates reflect value to corresponding text\nfunc (j *JSONPath) evalToText(v reflect.Value) ([]byte, error) {\n\tiface, ok := template.PrintableValue(v)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"can't print type %s\", v.Type())\n\t}\n\tvar buffer bytes.Buffer\n\tfmt.Fprint(\u0026buffer, iface)\n\treturn buffer.Bytes(), nil\n}","line":{"from":570,"to":579}} {"id":100029309,"name":"Type","signature":"func (t NodeType) Type() NodeType","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"// Type returns itself and provides an easy default implementation\nfunc (t NodeType) Type() NodeType {\n\treturn t\n}","line":{"from":24,"to":27}} {"id":100029310,"name":"String","signature":"func (t NodeType) String() string","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"func (t NodeType) String() string {\n\treturn NodeTypeName[t]\n}","line":{"from":29,"to":31}} {"id":100029311,"name":"newList","signature":"func newList() *ListNode","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"func newList() *ListNode {\n\treturn \u0026ListNode{NodeType: NodeList}\n}","line":{"from":74,"to":76}} {"id":100029312,"name":"append","signature":"func (l *ListNode) append(n Node)","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"func (l *ListNode) append(n Node) {\n\tl.Nodes = append(l.Nodes, n)\n}","line":{"from":78,"to":80}} {"id":100029313,"name":"String","signature":"func (l *ListNode) String() string","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"func (l *ListNode) String() string {\n\treturn l.Type().String()\n}","line":{"from":82,"to":84}} {"id":100029314,"name":"newText","signature":"func newText(text string) *TextNode","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"func newText(text string) *TextNode {\n\treturn \u0026TextNode{NodeType: NodeText, Text: text}\n}","line":{"from":92,"to":94}} {"id":100029315,"name":"String","signature":"func (t *TextNode) String() string","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"func (t *TextNode) String() string {\n\treturn fmt.Sprintf(\"%s: %s\", t.Type(), t.Text)\n}","line":{"from":96,"to":98}} {"id":100029316,"name":"newField","signature":"func newField(value string) *FieldNode","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"func newField(value string) *FieldNode {\n\treturn \u0026FieldNode{NodeType: NodeField, Value: value}\n}","line":{"from":106,"to":108}} {"id":100029317,"name":"String","signature":"func (f *FieldNode) String() string","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"func (f *FieldNode) String() string {\n\treturn fmt.Sprintf(\"%s: %s\", f.Type(), f.Value)\n}","line":{"from":110,"to":112}} {"id":100029318,"name":"newIdentifier","signature":"func newIdentifier(value string) *IdentifierNode","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"func newIdentifier(value string) *IdentifierNode {\n\treturn \u0026IdentifierNode{\n\t\tNodeType: NodeIdentifier,\n\t\tName: value,\n\t}\n}","line":{"from":120,"to":125}} {"id":100029319,"name":"String","signature":"func (f *IdentifierNode) String() string","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"func (f *IdentifierNode) String() string {\n\treturn fmt.Sprintf(\"%s: %s\", f.Type(), f.Name)\n}","line":{"from":127,"to":129}} {"id":100029320,"name":"newArray","signature":"func newArray(params [3]ParamsEntry) *ArrayNode","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"func newArray(params [3]ParamsEntry) *ArrayNode {\n\treturn \u0026ArrayNode{\n\t\tNodeType: NodeArray,\n\t\tParams: params,\n\t}\n}","line":{"from":144,"to":149}} {"id":100029321,"name":"String","signature":"func (a *ArrayNode) String() string","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"func (a *ArrayNode) String() string {\n\treturn fmt.Sprintf(\"%s: %v\", a.Type(), a.Params)\n}","line":{"from":151,"to":153}} {"id":100029322,"name":"newFilter","signature":"func newFilter(left, right *ListNode, operator string) *FilterNode","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"func newFilter(left, right *ListNode, operator string) *FilterNode {\n\treturn \u0026FilterNode{\n\t\tNodeType: NodeFilter,\n\t\tLeft: left,\n\t\tRight: right,\n\t\tOperator: operator,\n\t}\n}","line":{"from":163,"to":170}} {"id":100029323,"name":"String","signature":"func (f *FilterNode) String() string","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"func (f *FilterNode) String() string {\n\treturn fmt.Sprintf(\"%s: %s %s %s\", f.Type(), f.Left, f.Operator, f.Right)\n}","line":{"from":172,"to":174}} {"id":100029324,"name":"newInt","signature":"func newInt(num int) *IntNode","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"func newInt(num int) *IntNode {\n\treturn \u0026IntNode{NodeType: NodeInt, Value: num}\n}","line":{"from":182,"to":184}} {"id":100029325,"name":"String","signature":"func (i *IntNode) String() string","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"func (i *IntNode) String() string {\n\treturn fmt.Sprintf(\"%s: %d\", i.Type(), i.Value)\n}","line":{"from":186,"to":188}} {"id":100029326,"name":"newFloat","signature":"func newFloat(num float64) *FloatNode","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"func newFloat(num float64) *FloatNode {\n\treturn \u0026FloatNode{NodeType: NodeFloat, Value: num}\n}","line":{"from":196,"to":198}} {"id":100029327,"name":"String","signature":"func (i *FloatNode) String() string","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"func (i *FloatNode) String() string {\n\treturn fmt.Sprintf(\"%s: %f\", i.Type(), i.Value)\n}","line":{"from":200,"to":202}} {"id":100029328,"name":"newWildcard","signature":"func newWildcard() *WildcardNode","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"func newWildcard() *WildcardNode {\n\treturn \u0026WildcardNode{NodeType: NodeWildcard}\n}","line":{"from":209,"to":211}} {"id":100029329,"name":"String","signature":"func (i *WildcardNode) String() string","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"func (i *WildcardNode) String() string {\n\treturn i.Type().String()\n}","line":{"from":213,"to":215}} {"id":100029330,"name":"newRecursive","signature":"func newRecursive() *RecursiveNode","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"func newRecursive() *RecursiveNode {\n\treturn \u0026RecursiveNode{NodeType: NodeRecursive}\n}","line":{"from":222,"to":224}} {"id":100029331,"name":"String","signature":"func (r *RecursiveNode) String() string","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"func (r *RecursiveNode) String() string {\n\treturn r.Type().String()\n}","line":{"from":226,"to":228}} {"id":100029332,"name":"newUnion","signature":"func newUnion(nodes []*ListNode) *UnionNode","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"func newUnion(nodes []*ListNode) *UnionNode {\n\treturn \u0026UnionNode{NodeType: NodeUnion, Nodes: nodes}\n}","line":{"from":236,"to":238}} {"id":100029333,"name":"String","signature":"func (u *UnionNode) String() string","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"func (u *UnionNode) String() string {\n\treturn u.Type().String()\n}","line":{"from":240,"to":242}} {"id":100029334,"name":"newBool","signature":"func newBool(value bool) *BoolNode","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"func newBool(value bool) *BoolNode {\n\treturn \u0026BoolNode{NodeType: NodeBool, Value: value}\n}","line":{"from":250,"to":252}} {"id":100029335,"name":"String","signature":"func (b *BoolNode) String() string","file":"staging/src/k8s.io/client-go/util/jsonpath/node.go","code":"func (b *BoolNode) String() string {\n\treturn fmt.Sprintf(\"%s: %t\", b.Type(), b.Value)\n}","line":{"from":254,"to":256}} {"id":100029336,"name":"Parse","signature":"func Parse(name, text string) (*Parser, error)","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"// Parse parsed the given text and return a node Parser.\n// If an error is encountered, parsing stops and an empty\n// Parser is returned with the error\nfunc Parse(name, text string) (*Parser, error) {\n\tp := NewParser(name)\n\terr := p.Parse(text)\n\tif err != nil {\n\t\tp = nil\n\t}\n\treturn p, err\n}","line":{"from":51,"to":61}} {"id":100029337,"name":"NewParser","signature":"func NewParser(name string) *Parser","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"func NewParser(name string) *Parser {\n\treturn \u0026Parser{\n\t\tName: name,\n\t}\n}","line":{"from":63,"to":67}} {"id":100029338,"name":"parseAction","signature":"func parseAction(name, text string) (*Parser, error)","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"// parseAction parsed the expression inside delimiter\nfunc parseAction(name, text string) (*Parser, error) {\n\tp, err := Parse(name, fmt.Sprintf(\"%s%s%s\", leftDelim, text, rightDelim))\n\t// when error happens, p will be nil, so we need to return here\n\tif err != nil {\n\t\treturn p, err\n\t}\n\tp.Root = p.Root.Nodes[0].(*ListNode)\n\treturn p, nil\n}","line":{"from":69,"to":78}} {"id":100029339,"name":"Parse","signature":"func (p *Parser) Parse(text string) error","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"func (p *Parser) Parse(text string) error {\n\tp.input = text\n\tp.Root = newList()\n\tp.pos = 0\n\treturn p.parseText(p.Root)\n}","line":{"from":80,"to":85}} {"id":100029340,"name":"consumeText","signature":"func (p *Parser) consumeText() string","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"// consumeText return the parsed text since last cosumeText\nfunc (p *Parser) consumeText() string {\n\tvalue := p.input[p.start:p.pos]\n\tp.start = p.pos\n\treturn value\n}","line":{"from":87,"to":92}} {"id":100029341,"name":"next","signature":"func (p *Parser) next() rune","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"// next returns the next rune in the input.\nfunc (p *Parser) next() rune {\n\tif p.pos \u003e= len(p.input) {\n\t\tp.width = 0\n\t\treturn eof\n\t}\n\tr, w := utf8.DecodeRuneInString(p.input[p.pos:])\n\tp.width = w\n\tp.pos += p.width\n\treturn r\n}","line":{"from":94,"to":104}} {"id":100029342,"name":"peek","signature":"func (p *Parser) peek() rune","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"// peek returns but does not consume the next rune in the input.\nfunc (p *Parser) peek() rune {\n\tr := p.next()\n\tp.backup()\n\treturn r\n}","line":{"from":106,"to":111}} {"id":100029343,"name":"backup","signature":"func (p *Parser) backup()","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"// backup steps back one rune. Can only be called once per call of next.\nfunc (p *Parser) backup() {\n\tp.pos -= p.width\n}","line":{"from":113,"to":116}} {"id":100029344,"name":"parseText","signature":"func (p *Parser) parseText(cur *ListNode) error","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"func (p *Parser) parseText(cur *ListNode) error {\n\tfor {\n\t\tif strings.HasPrefix(p.input[p.pos:], leftDelim) {\n\t\t\tif p.pos \u003e p.start {\n\t\t\t\tcur.append(newText(p.consumeText()))\n\t\t\t}\n\t\t\treturn p.parseLeftDelim(cur)\n\t\t}\n\t\tif p.next() == eof {\n\t\t\tbreak\n\t\t}\n\t}\n\t// Correctly reached EOF.\n\tif p.pos \u003e p.start {\n\t\tcur.append(newText(p.consumeText()))\n\t}\n\treturn nil\n}","line":{"from":118,"to":135}} {"id":100029345,"name":"parseLeftDelim","signature":"func (p *Parser) parseLeftDelim(cur *ListNode) error","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"// parseLeftDelim scans the left delimiter, which is known to be present.\nfunc (p *Parser) parseLeftDelim(cur *ListNode) error {\n\tp.pos += len(leftDelim)\n\tp.consumeText()\n\tnewNode := newList()\n\tcur.append(newNode)\n\tcur = newNode\n\treturn p.parseInsideAction(cur)\n}","line":{"from":137,"to":145}} {"id":100029346,"name":"parseInsideAction","signature":"func (p *Parser) parseInsideAction(cur *ListNode) error","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"func (p *Parser) parseInsideAction(cur *ListNode) error {\n\tprefixMap := map[string]func(*ListNode) error{\n\t\trightDelim: p.parseRightDelim,\n\t\t\"[?(\": p.parseFilter,\n\t\t\"..\": p.parseRecursive,\n\t}\n\tfor prefix, parseFunc := range prefixMap {\n\t\tif strings.HasPrefix(p.input[p.pos:], prefix) {\n\t\t\treturn parseFunc(cur)\n\t\t}\n\t}\n\n\tswitch r := p.next(); {\n\tcase r == eof || isEndOfLine(r):\n\t\treturn fmt.Errorf(\"unclosed action\")\n\tcase r == ' ':\n\t\tp.consumeText()\n\tcase r == '@' || r == '$': //the current object, just pass it\n\t\tp.consumeText()\n\tcase r == '[':\n\t\treturn p.parseArray(cur)\n\tcase r == '\"' || r == '\\'':\n\t\treturn p.parseQuote(cur, r)\n\tcase r == '.':\n\t\treturn p.parseField(cur)\n\tcase r == '+' || r == '-' || unicode.IsDigit(r):\n\t\tp.backup()\n\t\treturn p.parseNumber(cur)\n\tcase isAlphaNumeric(r):\n\t\tp.backup()\n\t\treturn p.parseIdentifier(cur)\n\tdefault:\n\t\treturn fmt.Errorf(\"unrecognized character in action: %#U\", r)\n\t}\n\treturn p.parseInsideAction(cur)\n}","line":{"from":147,"to":182}} {"id":100029347,"name":"parseRightDelim","signature":"func (p *Parser) parseRightDelim(cur *ListNode) error","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"// parseRightDelim scans the right delimiter, which is known to be present.\nfunc (p *Parser) parseRightDelim(cur *ListNode) error {\n\tp.pos += len(rightDelim)\n\tp.consumeText()\n\treturn p.parseText(p.Root)\n}","line":{"from":184,"to":189}} {"id":100029348,"name":"parseIdentifier","signature":"func (p *Parser) parseIdentifier(cur *ListNode) error","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"// parseIdentifier scans build-in keywords, like \"range\" \"end\"\nfunc (p *Parser) parseIdentifier(cur *ListNode) error {\n\tvar r rune\n\tfor {\n\t\tr = p.next()\n\t\tif isTerminator(r) {\n\t\t\tp.backup()\n\t\t\tbreak\n\t\t}\n\t}\n\tvalue := p.consumeText()\n\n\tif isBool(value) {\n\t\tv, err := strconv.ParseBool(value)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"can not parse bool '%s': %s\", value, err.Error())\n\t\t}\n\n\t\tcur.append(newBool(v))\n\t} else {\n\t\tcur.append(newIdentifier(value))\n\t}\n\n\treturn p.parseInsideAction(cur)\n}","line":{"from":191,"to":215}} {"id":100029349,"name":"parseRecursive","signature":"func (p *Parser) parseRecursive(cur *ListNode) error","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"// parseRecursive scans the recursive descent operator ..\nfunc (p *Parser) parseRecursive(cur *ListNode) error {\n\tif lastIndex := len(cur.Nodes) - 1; lastIndex \u003e= 0 \u0026\u0026 cur.Nodes[lastIndex].Type() == NodeRecursive {\n\t\treturn fmt.Errorf(\"invalid multiple recursive descent\")\n\t}\n\tp.pos += len(\"..\")\n\tp.consumeText()\n\tcur.append(newRecursive())\n\tif r := p.peek(); isAlphaNumeric(r) {\n\t\treturn p.parseField(cur)\n\t}\n\treturn p.parseInsideAction(cur)\n}","line":{"from":217,"to":229}} {"id":100029350,"name":"parseNumber","signature":"func (p *Parser) parseNumber(cur *ListNode) error","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"// parseNumber scans number\nfunc (p *Parser) parseNumber(cur *ListNode) error {\n\tr := p.peek()\n\tif r == '+' || r == '-' {\n\t\tp.next()\n\t}\n\tfor {\n\t\tr = p.next()\n\t\tif r != '.' \u0026\u0026 !unicode.IsDigit(r) {\n\t\t\tp.backup()\n\t\t\tbreak\n\t\t}\n\t}\n\tvalue := p.consumeText()\n\ti, err := strconv.Atoi(value)\n\tif err == nil {\n\t\tcur.append(newInt(i))\n\t\treturn p.parseInsideAction(cur)\n\t}\n\td, err := strconv.ParseFloat(value, 64)\n\tif err == nil {\n\t\tcur.append(newFloat(d))\n\t\treturn p.parseInsideAction(cur)\n\t}\n\treturn fmt.Errorf(\"cannot parse number %s\", value)\n}","line":{"from":231,"to":256}} {"id":100029351,"name":"parseArray","signature":"func (p *Parser) parseArray(cur *ListNode) error","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"// parseArray scans array index selection\nfunc (p *Parser) parseArray(cur *ListNode) error {\nLoop:\n\tfor {\n\t\tswitch p.next() {\n\t\tcase eof, '\\n':\n\t\t\treturn fmt.Errorf(\"unterminated array\")\n\t\tcase ']':\n\t\t\tbreak Loop\n\t\t}\n\t}\n\ttext := p.consumeText()\n\ttext = text[1 : len(text)-1]\n\tif text == \"*\" {\n\t\ttext = \":\"\n\t}\n\n\t//union operator\n\tstrs := strings.Split(text, \",\")\n\tif len(strs) \u003e 1 {\n\t\tunion := []*ListNode{}\n\t\tfor _, str := range strs {\n\t\t\tparser, err := parseAction(\"union\", fmt.Sprintf(\"[%s]\", strings.Trim(str, \" \")))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tunion = append(union, parser.Root)\n\t\t}\n\t\tcur.append(newUnion(union))\n\t\treturn p.parseInsideAction(cur)\n\t}\n\n\t// dict key\n\tvalue := dictKeyRex.FindStringSubmatch(text)\n\tif value != nil {\n\t\tparser, err := parseAction(\"arraydict\", fmt.Sprintf(\".%s\", value[1]))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, node := range parser.Root.Nodes {\n\t\t\tcur.append(node)\n\t\t}\n\t\treturn p.parseInsideAction(cur)\n\t}\n\n\t//slice operator\n\tvalue = sliceOperatorRex.FindStringSubmatch(text)\n\tif value == nil {\n\t\treturn fmt.Errorf(\"invalid array index %s\", text)\n\t}\n\tvalue = value[1:]\n\tparams := [3]ParamsEntry{}\n\tfor i := 0; i \u003c 3; i++ {\n\t\tif value[i] != \"\" {\n\t\t\tif i \u003e 0 {\n\t\t\t\tvalue[i] = value[i][1:]\n\t\t\t}\n\t\t\tif i \u003e 0 \u0026\u0026 value[i] == \"\" {\n\t\t\t\tparams[i].Known = false\n\t\t\t} else {\n\t\t\t\tvar err error\n\t\t\t\tparams[i].Known = true\n\t\t\t\tparams[i].Value, err = strconv.Atoi(value[i])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"array index %s is not a number\", value[i])\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif i == 1 {\n\t\t\t\tparams[i].Known = true\n\t\t\t\tparams[i].Value = params[0].Value + 1\n\t\t\t\tparams[i].Derived = true\n\t\t\t} else {\n\t\t\t\tparams[i].Known = false\n\t\t\t\tparams[i].Value = 0\n\t\t\t}\n\t\t}\n\t}\n\tcur.append(newArray(params))\n\treturn p.parseInsideAction(cur)\n}","line":{"from":258,"to":338}} {"id":100029352,"name":"parseFilter","signature":"func (p *Parser) parseFilter(cur *ListNode) error","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"// parseFilter scans filter inside array selection\nfunc (p *Parser) parseFilter(cur *ListNode) error {\n\tp.pos += len(\"[?(\")\n\tp.consumeText()\n\tbegin := false\n\tend := false\n\tvar pair rune\n\nLoop:\n\tfor {\n\t\tr := p.next()\n\t\tswitch r {\n\t\tcase eof, '\\n':\n\t\t\treturn fmt.Errorf(\"unterminated filter\")\n\t\tcase '\"', '\\'':\n\t\t\tif begin == false {\n\t\t\t\t//save the paired rune\n\t\t\t\tbegin = true\n\t\t\t\tpair = r\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t//only add when met paired rune\n\t\t\tif p.input[p.pos-2] != '\\\\' \u0026\u0026 r == pair {\n\t\t\t\tend = true\n\t\t\t}\n\t\tcase ')':\n\t\t\t//in rightParser below quotes only appear zero or once\n\t\t\t//and must be paired at the beginning and end\n\t\t\tif begin == end {\n\t\t\t\tbreak Loop\n\t\t\t}\n\t\t}\n\t}\n\tif p.next() != ']' {\n\t\treturn fmt.Errorf(\"unclosed array expect ]\")\n\t}\n\treg := regexp.MustCompile(`^([^!\u003c\u003e=]+)([!\u003c\u003e=]+)(.+?)$`)\n\ttext := p.consumeText()\n\ttext = text[:len(text)-2]\n\tvalue := reg.FindStringSubmatch(text)\n\tif value == nil {\n\t\tparser, err := parseAction(\"text\", text)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcur.append(newFilter(parser.Root, newList(), \"exists\"))\n\t} else {\n\t\tleftParser, err := parseAction(\"left\", value[1])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\trightParser, err := parseAction(\"right\", value[3])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcur.append(newFilter(leftParser.Root, rightParser.Root, value[2]))\n\t}\n\treturn p.parseInsideAction(cur)\n}","line":{"from":340,"to":398}} {"id":100029353,"name":"parseQuote","signature":"func (p *Parser) parseQuote(cur *ListNode, end rune) error","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"// parseQuote unquotes string inside double or single quote\nfunc (p *Parser) parseQuote(cur *ListNode, end rune) error {\nLoop:\n\tfor {\n\t\tswitch p.next() {\n\t\tcase eof, '\\n':\n\t\t\treturn fmt.Errorf(\"unterminated quoted string\")\n\t\tcase end:\n\t\t\t//if it's not escape break the Loop\n\t\t\tif p.input[p.pos-2] != '\\\\' {\n\t\t\t\tbreak Loop\n\t\t\t}\n\t\t}\n\t}\n\tvalue := p.consumeText()\n\ts, err := UnquoteExtend(value)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unquote string %s error %v\", value, err)\n\t}\n\tcur.append(newText(s))\n\treturn p.parseInsideAction(cur)\n}","line":{"from":400,"to":421}} {"id":100029354,"name":"parseField","signature":"func (p *Parser) parseField(cur *ListNode) error","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"// parseField scans a field until a terminator\nfunc (p *Parser) parseField(cur *ListNode) error {\n\tp.consumeText()\n\tfor p.advance() {\n\t}\n\tvalue := p.consumeText()\n\tif value == \"*\" {\n\t\tcur.append(newWildcard())\n\t} else {\n\t\tcur.append(newField(strings.Replace(value, \"\\\\\", \"\", -1)))\n\t}\n\treturn p.parseInsideAction(cur)\n}","line":{"from":423,"to":435}} {"id":100029355,"name":"advance","signature":"func (p *Parser) advance() bool","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"// advance scans until next non-escaped terminator\nfunc (p *Parser) advance() bool {\n\tr := p.next()\n\tif r == '\\\\' {\n\t\tp.next()\n\t} else if isTerminator(r) {\n\t\tp.backup()\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":437,"to":447}} {"id":100029356,"name":"isTerminator","signature":"func isTerminator(r rune) bool","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"// isTerminator reports whether the input is at valid termination character to appear after an identifier.\nfunc isTerminator(r rune) bool {\n\tif isSpace(r) || isEndOfLine(r) {\n\t\treturn true\n\t}\n\tswitch r {\n\tcase eof, '.', ',', '[', ']', '$', '@', '{', '}':\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":449,"to":459}} {"id":100029357,"name":"isSpace","signature":"func isSpace(r rune) bool","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"// isSpace reports whether r is a space character.\nfunc isSpace(r rune) bool {\n\treturn r == ' ' || r == '\\t'\n}","line":{"from":461,"to":464}} {"id":100029358,"name":"isEndOfLine","signature":"func isEndOfLine(r rune) bool","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"// isEndOfLine reports whether r is an end-of-line character.\nfunc isEndOfLine(r rune) bool {\n\treturn r == '\\r' || r == '\\n'\n}","line":{"from":466,"to":469}} {"id":100029359,"name":"isAlphaNumeric","signature":"func isAlphaNumeric(r rune) bool","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"// isAlphaNumeric reports whether r is an alphabetic, digit, or underscore.\nfunc isAlphaNumeric(r rune) bool {\n\treturn r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r)\n}","line":{"from":471,"to":474}} {"id":100029360,"name":"isBool","signature":"func isBool(s string) bool","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"// isBool reports whether s is a boolean value.\nfunc isBool(s string) bool {\n\treturn s == \"true\" || s == \"false\"\n}","line":{"from":476,"to":479}} {"id":100029361,"name":"UnquoteExtend","signature":"func UnquoteExtend(s string) (string, error)","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"// UnquoteExtend is almost same as strconv.Unquote(), but it support parse single quotes as a string\nfunc UnquoteExtend(s string) (string, error) {\n\tn := len(s)\n\tif n \u003c 2 {\n\t\treturn \"\", ErrSyntax\n\t}\n\tquote := s[0]\n\tif quote != s[n-1] {\n\t\treturn \"\", ErrSyntax\n\t}\n\ts = s[1 : n-1]\n\n\tif quote != '\"' \u0026\u0026 quote != '\\'' {\n\t\treturn \"\", ErrSyntax\n\t}\n\n\t// Is it trivial? Avoid allocation.\n\tif !contains(s, '\\\\') \u0026\u0026 !contains(s, quote) {\n\t\treturn s, nil\n\t}\n\n\tvar runeTmp [utf8.UTFMax]byte\n\tbuf := make([]byte, 0, 3*len(s)/2) // Try to avoid more allocations.\n\tfor len(s) \u003e 0 {\n\t\tc, multibyte, ss, err := strconv.UnquoteChar(s, quote)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\ts = ss\n\t\tif c \u003c utf8.RuneSelf || !multibyte {\n\t\t\tbuf = append(buf, byte(c))\n\t\t} else {\n\t\t\tn := utf8.EncodeRune(runeTmp[:], c)\n\t\t\tbuf = append(buf, runeTmp[:n]...)\n\t\t}\n\t}\n\treturn string(buf), nil\n}","line":{"from":481,"to":518}} {"id":100029362,"name":"contains","signature":"func contains(s string, c byte) bool","file":"staging/src/k8s.io/client-go/util/jsonpath/parser.go","code":"func contains(s string, c byte) bool {\n\tfor i := 0; i \u003c len(s); i++ {\n\t\tif s[i] == c {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":520,"to":527}} {"id":100029363,"name":"MakeEllipticPrivateKeyPEM","signature":"func MakeEllipticPrivateKeyPEM() ([]byte, error)","file":"staging/src/k8s.io/client-go/util/keyutil/key.go","code":"// MakeEllipticPrivateKeyPEM creates an ECDSA private key\nfunc MakeEllipticPrivateKeyPEM() ([]byte, error) {\n\tprivateKey, err := ecdsa.GenerateKey(elliptic.P256(), cryptorand.Reader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tderBytes, err := x509.MarshalECPrivateKey(privateKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprivateKeyPemBlock := \u0026pem.Block{\n\t\tType: ECPrivateKeyBlockType,\n\t\tBytes: derBytes,\n\t}\n\treturn pem.EncodeToMemory(privateKeyPemBlock), nil\n}","line":{"from":44,"to":61}} {"id":100029364,"name":"WriteKey","signature":"func WriteKey(keyPath string, data []byte) error","file":"staging/src/k8s.io/client-go/util/keyutil/key.go","code":"// WriteKey writes the pem-encoded key data to keyPath.\n// The key file will be created with file mode 0600.\n// If the key file already exists, it will be overwritten.\n// The parent directory of the keyPath will be created as needed with file mode 0755.\nfunc WriteKey(keyPath string, data []byte) error {\n\tif err := os.MkdirAll(filepath.Dir(keyPath), os.FileMode(0755)); err != nil {\n\t\treturn err\n\t}\n\treturn os.WriteFile(keyPath, data, os.FileMode(0600))\n}","line":{"from":63,"to":72}} {"id":100029365,"name":"LoadOrGenerateKeyFile","signature":"func LoadOrGenerateKeyFile(keyPath string) (data []byte, wasGenerated bool, err error)","file":"staging/src/k8s.io/client-go/util/keyutil/key.go","code":"// LoadOrGenerateKeyFile looks for a key in the file at the given path. If it\n// can't find one, it will generate a new key and store it there.\nfunc LoadOrGenerateKeyFile(keyPath string) (data []byte, wasGenerated bool, err error) {\n\tloadedData, err := os.ReadFile(keyPath)\n\t// Call verifyKeyData to ensure the file wasn't empty/corrupt.\n\tif err == nil \u0026\u0026 verifyKeyData(loadedData) {\n\t\treturn loadedData, false, err\n\t}\n\tif !os.IsNotExist(err) {\n\t\treturn nil, false, fmt.Errorf(\"error loading key from %s: %v\", keyPath, err)\n\t}\n\n\tgeneratedData, err := MakeEllipticPrivateKeyPEM()\n\tif err != nil {\n\t\treturn nil, false, fmt.Errorf(\"error generating key: %v\", err)\n\t}\n\tif err := WriteKey(keyPath, generatedData); err != nil {\n\t\treturn nil, false, fmt.Errorf(\"error writing key to %s: %v\", keyPath, err)\n\t}\n\treturn generatedData, true, nil\n}","line":{"from":74,"to":94}} {"id":100029366,"name":"MarshalPrivateKeyToPEM","signature":"func MarshalPrivateKeyToPEM(privateKey crypto.PrivateKey) ([]byte, error)","file":"staging/src/k8s.io/client-go/util/keyutil/key.go","code":"// MarshalPrivateKeyToPEM converts a known private key type of RSA or ECDSA to\n// a PEM encoded block or returns an error.\nfunc MarshalPrivateKeyToPEM(privateKey crypto.PrivateKey) ([]byte, error) {\n\tswitch t := privateKey.(type) {\n\tcase *ecdsa.PrivateKey:\n\t\tderBytes, err := x509.MarshalECPrivateKey(t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tblock := \u0026pem.Block{\n\t\t\tType: ECPrivateKeyBlockType,\n\t\t\tBytes: derBytes,\n\t\t}\n\t\treturn pem.EncodeToMemory(block), nil\n\tcase *rsa.PrivateKey:\n\t\tblock := \u0026pem.Block{\n\t\t\tType: RSAPrivateKeyBlockType,\n\t\t\tBytes: x509.MarshalPKCS1PrivateKey(t),\n\t\t}\n\t\treturn pem.EncodeToMemory(block), nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"private key is not a recognized type: %T\", privateKey)\n\t}\n}","line":{"from":96,"to":119}} {"id":100029367,"name":"PrivateKeyFromFile","signature":"func PrivateKeyFromFile(file string) (interface{}, error)","file":"staging/src/k8s.io/client-go/util/keyutil/key.go","code":"// PrivateKeyFromFile returns the private key in rsa.PrivateKey or ecdsa.PrivateKey format from a given PEM-encoded file.\n// Returns an error if the file could not be read or if the private key could not be parsed.\nfunc PrivateKeyFromFile(file string) (interface{}, error) {\n\tdata, err := os.ReadFile(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkey, err := ParsePrivateKeyPEM(data)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading private key file %s: %v\", file, err)\n\t}\n\treturn key, nil\n}","line":{"from":121,"to":133}} {"id":100029368,"name":"PublicKeysFromFile","signature":"func PublicKeysFromFile(file string) ([]interface{}, error)","file":"staging/src/k8s.io/client-go/util/keyutil/key.go","code":"// PublicKeysFromFile returns the public keys in rsa.PublicKey or ecdsa.PublicKey format from a given PEM-encoded file.\n// Reads public keys from both public and private key files.\nfunc PublicKeysFromFile(file string) ([]interface{}, error) {\n\tdata, err := os.ReadFile(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkeys, err := ParsePublicKeysPEM(data)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading public key file %s: %v\", file, err)\n\t}\n\treturn keys, nil\n}","line":{"from":135,"to":147}} {"id":100029369,"name":"verifyKeyData","signature":"func verifyKeyData(data []byte) bool","file":"staging/src/k8s.io/client-go/util/keyutil/key.go","code":"// verifyKeyData returns true if the provided data appears to be a valid private key.\nfunc verifyKeyData(data []byte) bool {\n\tif len(data) == 0 {\n\t\treturn false\n\t}\n\t_, err := ParsePrivateKeyPEM(data)\n\treturn err == nil\n}","line":{"from":149,"to":156}} {"id":100029370,"name":"ParsePrivateKeyPEM","signature":"func ParsePrivateKeyPEM(keyData []byte) (interface{}, error)","file":"staging/src/k8s.io/client-go/util/keyutil/key.go","code":"// ParsePrivateKeyPEM returns a private key parsed from a PEM block in the supplied data.\n// Recognizes PEM blocks for \"EC PRIVATE KEY\", \"RSA PRIVATE KEY\", or \"PRIVATE KEY\"\nfunc ParsePrivateKeyPEM(keyData []byte) (interface{}, error) {\n\tvar privateKeyPemBlock *pem.Block\n\tfor {\n\t\tprivateKeyPemBlock, keyData = pem.Decode(keyData)\n\t\tif privateKeyPemBlock == nil {\n\t\t\tbreak\n\t\t}\n\n\t\tswitch privateKeyPemBlock.Type {\n\t\tcase ECPrivateKeyBlockType:\n\t\t\t// ECDSA Private Key in ASN.1 format\n\t\t\tif key, err := x509.ParseECPrivateKey(privateKeyPemBlock.Bytes); err == nil {\n\t\t\t\treturn key, nil\n\t\t\t}\n\t\tcase RSAPrivateKeyBlockType:\n\t\t\t// RSA Private Key in PKCS#1 format\n\t\t\tif key, err := x509.ParsePKCS1PrivateKey(privateKeyPemBlock.Bytes); err == nil {\n\t\t\t\treturn key, nil\n\t\t\t}\n\t\tcase PrivateKeyBlockType:\n\t\t\t// RSA or ECDSA Private Key in unencrypted PKCS#8 format\n\t\t\tif key, err := x509.ParsePKCS8PrivateKey(privateKeyPemBlock.Bytes); err == nil {\n\t\t\t\treturn key, nil\n\t\t\t}\n\t\t}\n\n\t\t// tolerate non-key PEM blocks for compatibility with things like \"EC PARAMETERS\" blocks\n\t\t// originally, only the first PEM block was parsed and expected to be a key block\n\t}\n\n\t// we read all the PEM blocks and didn't recognize one\n\treturn nil, fmt.Errorf(\"data does not contain a valid RSA or ECDSA private key\")\n}","line":{"from":158,"to":192}} {"id":100029371,"name":"ParsePublicKeysPEM","signature":"func ParsePublicKeysPEM(keyData []byte) ([]interface{}, error)","file":"staging/src/k8s.io/client-go/util/keyutil/key.go","code":"// ParsePublicKeysPEM is a helper function for reading an array of rsa.PublicKey or ecdsa.PublicKey from a PEM-encoded byte array.\n// Reads public keys from both public and private key files.\nfunc ParsePublicKeysPEM(keyData []byte) ([]interface{}, error) {\n\tvar block *pem.Block\n\tkeys := []interface{}{}\n\tfor {\n\t\t// read the next block\n\t\tblock, keyData = pem.Decode(keyData)\n\t\tif block == nil {\n\t\t\tbreak\n\t\t}\n\n\t\t// test block against parsing functions\n\t\tif privateKey, err := parseRSAPrivateKey(block.Bytes); err == nil {\n\t\t\tkeys = append(keys, \u0026privateKey.PublicKey)\n\t\t\tcontinue\n\t\t}\n\t\tif publicKey, err := parseRSAPublicKey(block.Bytes); err == nil {\n\t\t\tkeys = append(keys, publicKey)\n\t\t\tcontinue\n\t\t}\n\t\tif privateKey, err := parseECPrivateKey(block.Bytes); err == nil {\n\t\t\tkeys = append(keys, \u0026privateKey.PublicKey)\n\t\t\tcontinue\n\t\t}\n\t\tif publicKey, err := parseECPublicKey(block.Bytes); err == nil {\n\t\t\tkeys = append(keys, publicKey)\n\t\t\tcontinue\n\t\t}\n\n\t\t// tolerate non-key PEM blocks for backwards compatibility\n\t\t// originally, only the first PEM block was parsed and expected to be a key block\n\t}\n\n\tif len(keys) == 0 {\n\t\treturn nil, fmt.Errorf(\"data does not contain any valid RSA or ECDSA public keys\")\n\t}\n\treturn keys, nil\n}","line":{"from":194,"to":232}} {"id":100029372,"name":"parseRSAPublicKey","signature":"func parseRSAPublicKey(data []byte) (*rsa.PublicKey, error)","file":"staging/src/k8s.io/client-go/util/keyutil/key.go","code":"// parseRSAPublicKey parses a single RSA public key from the provided data\nfunc parseRSAPublicKey(data []byte) (*rsa.PublicKey, error) {\n\tvar err error\n\n\t// Parse the key\n\tvar parsedKey interface{}\n\tif parsedKey, err = x509.ParsePKIXPublicKey(data); err != nil {\n\t\tif cert, err := x509.ParseCertificate(data); err == nil {\n\t\t\tparsedKey = cert.PublicKey\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Test if parsed key is an RSA Public Key\n\tvar pubKey *rsa.PublicKey\n\tvar ok bool\n\tif pubKey, ok = parsedKey.(*rsa.PublicKey); !ok {\n\t\treturn nil, fmt.Errorf(\"data doesn't contain valid RSA Public Key\")\n\t}\n\n\treturn pubKey, nil\n}","line":{"from":234,"to":256}} {"id":100029373,"name":"parseRSAPrivateKey","signature":"func parseRSAPrivateKey(data []byte) (*rsa.PrivateKey, error)","file":"staging/src/k8s.io/client-go/util/keyutil/key.go","code":"// parseRSAPrivateKey parses a single RSA private key from the provided data\nfunc parseRSAPrivateKey(data []byte) (*rsa.PrivateKey, error) {\n\tvar err error\n\n\t// Parse the key\n\tvar parsedKey interface{}\n\tif parsedKey, err = x509.ParsePKCS1PrivateKey(data); err != nil {\n\t\tif parsedKey, err = x509.ParsePKCS8PrivateKey(data); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Test if parsed key is an RSA Private Key\n\tvar privKey *rsa.PrivateKey\n\tvar ok bool\n\tif privKey, ok = parsedKey.(*rsa.PrivateKey); !ok {\n\t\treturn nil, fmt.Errorf(\"data doesn't contain valid RSA Private Key\")\n\t}\n\n\treturn privKey, nil\n}","line":{"from":258,"to":278}} {"id":100029374,"name":"parseECPublicKey","signature":"func parseECPublicKey(data []byte) (*ecdsa.PublicKey, error)","file":"staging/src/k8s.io/client-go/util/keyutil/key.go","code":"// parseECPublicKey parses a single ECDSA public key from the provided data\nfunc parseECPublicKey(data []byte) (*ecdsa.PublicKey, error) {\n\tvar err error\n\n\t// Parse the key\n\tvar parsedKey interface{}\n\tif parsedKey, err = x509.ParsePKIXPublicKey(data); err != nil {\n\t\tif cert, err := x509.ParseCertificate(data); err == nil {\n\t\t\tparsedKey = cert.PublicKey\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Test if parsed key is an ECDSA Public Key\n\tvar pubKey *ecdsa.PublicKey\n\tvar ok bool\n\tif pubKey, ok = parsedKey.(*ecdsa.PublicKey); !ok {\n\t\treturn nil, fmt.Errorf(\"data doesn't contain valid ECDSA Public Key\")\n\t}\n\n\treturn pubKey, nil\n}","line":{"from":280,"to":302}} {"id":100029375,"name":"parseECPrivateKey","signature":"func parseECPrivateKey(data []byte) (*ecdsa.PrivateKey, error)","file":"staging/src/k8s.io/client-go/util/keyutil/key.go","code":"// parseECPrivateKey parses a single ECDSA private key from the provided data\nfunc parseECPrivateKey(data []byte) (*ecdsa.PrivateKey, error) {\n\tvar err error\n\n\t// Parse the key\n\tvar parsedKey interface{}\n\tif parsedKey, err = x509.ParseECPrivateKey(data); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Test if parsed key is an ECDSA Private Key\n\tvar privKey *ecdsa.PrivateKey\n\tvar ok bool\n\tif privKey, ok = parsedKey.(*ecdsa.PrivateKey); !ok {\n\t\treturn nil, fmt.Errorf(\"data doesn't contain valid ECDSA Private Key\")\n\t}\n\n\treturn privKey, nil\n}","line":{"from":304,"to":322}} {"id":100029376,"name":"OnError","signature":"func OnError(backoff wait.Backoff, retriable func(error) bool, fn func() error) error","file":"staging/src/k8s.io/client-go/util/retry/util.go","code":"// OnError allows the caller to retry fn in case the error returned by fn is retriable\n// according to the provided function. backoff defines the maximum retries and the wait\n// interval between two retries.\nfunc OnError(backoff wait.Backoff, retriable func(error) bool, fn func() error) error {\n\tvar lastErr error\n\terr := wait.ExponentialBackoff(backoff, func() (bool, error) {\n\t\terr := fn()\n\t\tswitch {\n\t\tcase err == nil:\n\t\t\treturn true, nil\n\t\tcase retriable(err):\n\t\t\tlastErr = err\n\t\t\treturn false, nil\n\t\tdefault:\n\t\t\treturn false, err\n\t\t}\n\t})\n\tif err == wait.ErrWaitTimeout {\n\t\terr = lastErr\n\t}\n\treturn err\n}","line":{"from":45,"to":66}} {"id":100029377,"name":"RetryOnConflict","signature":"func RetryOnConflict(backoff wait.Backoff, fn func() error) error","file":"staging/src/k8s.io/client-go/util/retry/util.go","code":"// RetryOnConflict is used to make an update to a resource when you have to worry about\n// conflicts caused by other code making unrelated updates to the resource at the same\n// time. fn should fetch the resource to be modified, make appropriate changes to it, try\n// to update it, and return (unmodified) the error from the update function. On a\n// successful update, RetryOnConflict will return nil. If the update function returns a\n// \"Conflict\" error, RetryOnConflict will wait some amount of time as described by\n// backoff, and then try again. On a non-\"Conflict\" error, or if it retries too many times\n// and gives up, RetryOnConflict will return an error to the caller.\n//\n//\terr := retry.RetryOnConflict(retry.DefaultRetry, func() error {\n//\t // Fetch the resource here; you need to refetch it on every try, since\n//\t // if you got a conflict on the last update attempt then you need to get\n//\t // the current version before making your own changes.\n//\t pod, err := c.Pods(\"mynamespace\").Get(name, metav1.GetOptions{})\n//\t if err != nil {\n//\t return err\n//\t }\n//\n//\t // Make whatever updates to the resource are needed\n//\t pod.Status.Phase = v1.PodFailed\n//\n//\t // Try to update\n//\t _, err = c.Pods(\"mynamespace\").UpdateStatus(pod)\n//\t // You have to return err itself here (not wrapped inside another error)\n//\t // so that RetryOnConflict can identify it correctly.\n//\t return err\n//\t})\n//\tif err != nil {\n//\t // May be conflict if max retries were hit, or may be something unrelated\n//\t // like permissions or a network error\n//\t return err\n//\t}\n//\t...\n//\n// TODO: Make Backoff an interface?\nfunc RetryOnConflict(backoff wait.Backoff, fn func() error) error {\n\treturn OnError(backoff, errors.IsConflict, fn)\n}","line":{"from":68,"to":105}} {"id":100029378,"name":"DefaultControllerRateLimiter","signature":"func DefaultControllerRateLimiter() RateLimiter","file":"staging/src/k8s.io/client-go/util/workqueue/default_rate_limiters.go","code":"// DefaultControllerRateLimiter is a no-arg constructor for a default rate limiter for a workqueue. It has\n// both overall and per-item rate limiting. The overall is a token bucket and the per-item is exponential\nfunc DefaultControllerRateLimiter() RateLimiter {\n\treturn NewMaxOfRateLimiter(\n\t\tNewItemExponentialFailureRateLimiter(5*time.Millisecond, 1000*time.Second),\n\t\t// 10 qps, 100 bucket size. This is only for retry speed and its only the overall factor (not per item)\n\t\t\u0026BucketRateLimiter{Limiter: rate.NewLimiter(rate.Limit(10), 100)},\n\t)\n}","line":{"from":37,"to":45}} {"id":100029379,"name":"When","signature":"func (r *BucketRateLimiter) When(item interface{}) time.Duration","file":"staging/src/k8s.io/client-go/util/workqueue/default_rate_limiters.go","code":"func (r *BucketRateLimiter) When(item interface{}) time.Duration {\n\treturn r.Limiter.Reserve().Delay()\n}","line":{"from":54,"to":56}} {"id":100029380,"name":"NumRequeues","signature":"func (r *BucketRateLimiter) NumRequeues(item interface{}) int","file":"staging/src/k8s.io/client-go/util/workqueue/default_rate_limiters.go","code":"func (r *BucketRateLimiter) NumRequeues(item interface{}) int {\n\treturn 0\n}","line":{"from":58,"to":60}} {"id":100029381,"name":"Forget","signature":"func (r *BucketRateLimiter) Forget(item interface{})","file":"staging/src/k8s.io/client-go/util/workqueue/default_rate_limiters.go","code":"func (r *BucketRateLimiter) Forget(item interface{}) {\n}","line":{"from":62,"to":63}} {"id":100029382,"name":"NewItemExponentialFailureRateLimiter","signature":"func NewItemExponentialFailureRateLimiter(baseDelay time.Duration, maxDelay time.Duration) RateLimiter","file":"staging/src/k8s.io/client-go/util/workqueue/default_rate_limiters.go","code":"func NewItemExponentialFailureRateLimiter(baseDelay time.Duration, maxDelay time.Duration) RateLimiter {\n\treturn \u0026ItemExponentialFailureRateLimiter{\n\t\tfailures: map[interface{}]int{},\n\t\tbaseDelay: baseDelay,\n\t\tmaxDelay: maxDelay,\n\t}\n}","line":{"from":77,"to":83}} {"id":100029383,"name":"DefaultItemBasedRateLimiter","signature":"func DefaultItemBasedRateLimiter() RateLimiter","file":"staging/src/k8s.io/client-go/util/workqueue/default_rate_limiters.go","code":"func DefaultItemBasedRateLimiter() RateLimiter {\n\treturn NewItemExponentialFailureRateLimiter(time.Millisecond, 1000*time.Second)\n}","line":{"from":85,"to":87}} {"id":100029384,"name":"When","signature":"func (r *ItemExponentialFailureRateLimiter) When(item interface{}) time.Duration","file":"staging/src/k8s.io/client-go/util/workqueue/default_rate_limiters.go","code":"func (r *ItemExponentialFailureRateLimiter) When(item interface{}) time.Duration {\n\tr.failuresLock.Lock()\n\tdefer r.failuresLock.Unlock()\n\n\texp := r.failures[item]\n\tr.failures[item] = r.failures[item] + 1\n\n\t// The backoff is capped such that 'calculated' value never overflows.\n\tbackoff := float64(r.baseDelay.Nanoseconds()) * math.Pow(2, float64(exp))\n\tif backoff \u003e math.MaxInt64 {\n\t\treturn r.maxDelay\n\t}\n\n\tcalculated := time.Duration(backoff)\n\tif calculated \u003e r.maxDelay {\n\t\treturn r.maxDelay\n\t}\n\n\treturn calculated\n}","line":{"from":89,"to":108}} {"id":100029385,"name":"NumRequeues","signature":"func (r *ItemExponentialFailureRateLimiter) NumRequeues(item interface{}) int","file":"staging/src/k8s.io/client-go/util/workqueue/default_rate_limiters.go","code":"func (r *ItemExponentialFailureRateLimiter) NumRequeues(item interface{}) int {\n\tr.failuresLock.Lock()\n\tdefer r.failuresLock.Unlock()\n\n\treturn r.failures[item]\n}","line":{"from":110,"to":115}} {"id":100029386,"name":"Forget","signature":"func (r *ItemExponentialFailureRateLimiter) Forget(item interface{})","file":"staging/src/k8s.io/client-go/util/workqueue/default_rate_limiters.go","code":"func (r *ItemExponentialFailureRateLimiter) Forget(item interface{}) {\n\tr.failuresLock.Lock()\n\tdefer r.failuresLock.Unlock()\n\n\tdelete(r.failures, item)\n}","line":{"from":117,"to":122}} {"id":100029387,"name":"NewItemFastSlowRateLimiter","signature":"func NewItemFastSlowRateLimiter(fastDelay, slowDelay time.Duration, maxFastAttempts int) RateLimiter","file":"staging/src/k8s.io/client-go/util/workqueue/default_rate_limiters.go","code":"func NewItemFastSlowRateLimiter(fastDelay, slowDelay time.Duration, maxFastAttempts int) RateLimiter {\n\treturn \u0026ItemFastSlowRateLimiter{\n\t\tfailures: map[interface{}]int{},\n\t\tfastDelay: fastDelay,\n\t\tslowDelay: slowDelay,\n\t\tmaxFastAttempts: maxFastAttempts,\n\t}\n}","line":{"from":136,"to":143}} {"id":100029388,"name":"When","signature":"func (r *ItemFastSlowRateLimiter) When(item interface{}) time.Duration","file":"staging/src/k8s.io/client-go/util/workqueue/default_rate_limiters.go","code":"func (r *ItemFastSlowRateLimiter) When(item interface{}) time.Duration {\n\tr.failuresLock.Lock()\n\tdefer r.failuresLock.Unlock()\n\n\tr.failures[item] = r.failures[item] + 1\n\n\tif r.failures[item] \u003c= r.maxFastAttempts {\n\t\treturn r.fastDelay\n\t}\n\n\treturn r.slowDelay\n}","line":{"from":145,"to":156}} {"id":100029389,"name":"NumRequeues","signature":"func (r *ItemFastSlowRateLimiter) NumRequeues(item interface{}) int","file":"staging/src/k8s.io/client-go/util/workqueue/default_rate_limiters.go","code":"func (r *ItemFastSlowRateLimiter) NumRequeues(item interface{}) int {\n\tr.failuresLock.Lock()\n\tdefer r.failuresLock.Unlock()\n\n\treturn r.failures[item]\n}","line":{"from":158,"to":163}} {"id":100029390,"name":"Forget","signature":"func (r *ItemFastSlowRateLimiter) Forget(item interface{})","file":"staging/src/k8s.io/client-go/util/workqueue/default_rate_limiters.go","code":"func (r *ItemFastSlowRateLimiter) Forget(item interface{}) {\n\tr.failuresLock.Lock()\n\tdefer r.failuresLock.Unlock()\n\n\tdelete(r.failures, item)\n}","line":{"from":165,"to":170}} {"id":100029391,"name":"When","signature":"func (r *MaxOfRateLimiter) When(item interface{}) time.Duration","file":"staging/src/k8s.io/client-go/util/workqueue/default_rate_limiters.go","code":"func (r *MaxOfRateLimiter) When(item interface{}) time.Duration {\n\tret := time.Duration(0)\n\tfor _, limiter := range r.limiters {\n\t\tcurr := limiter.When(item)\n\t\tif curr \u003e ret {\n\t\t\tret = curr\n\t\t}\n\t}\n\n\treturn ret\n}","line":{"from":179,"to":189}} {"id":100029392,"name":"NewMaxOfRateLimiter","signature":"func NewMaxOfRateLimiter(limiters ...RateLimiter) RateLimiter","file":"staging/src/k8s.io/client-go/util/workqueue/default_rate_limiters.go","code":"func NewMaxOfRateLimiter(limiters ...RateLimiter) RateLimiter {\n\treturn \u0026MaxOfRateLimiter{limiters: limiters}\n}","line":{"from":191,"to":193}} {"id":100029393,"name":"NumRequeues","signature":"func (r *MaxOfRateLimiter) NumRequeues(item interface{}) int","file":"staging/src/k8s.io/client-go/util/workqueue/default_rate_limiters.go","code":"func (r *MaxOfRateLimiter) NumRequeues(item interface{}) int {\n\tret := 0\n\tfor _, limiter := range r.limiters {\n\t\tcurr := limiter.NumRequeues(item)\n\t\tif curr \u003e ret {\n\t\t\tret = curr\n\t\t}\n\t}\n\n\treturn ret\n}","line":{"from":195,"to":205}} {"id":100029394,"name":"Forget","signature":"func (r *MaxOfRateLimiter) Forget(item interface{})","file":"staging/src/k8s.io/client-go/util/workqueue/default_rate_limiters.go","code":"func (r *MaxOfRateLimiter) Forget(item interface{}) {\n\tfor _, limiter := range r.limiters {\n\t\tlimiter.Forget(item)\n\t}\n}","line":{"from":207,"to":211}} {"id":100029395,"name":"NewWithMaxWaitRateLimiter","signature":"func NewWithMaxWaitRateLimiter(limiter RateLimiter, maxDelay time.Duration) RateLimiter","file":"staging/src/k8s.io/client-go/util/workqueue/default_rate_limiters.go","code":"func NewWithMaxWaitRateLimiter(limiter RateLimiter, maxDelay time.Duration) RateLimiter {\n\treturn \u0026WithMaxWaitRateLimiter{limiter: limiter, maxDelay: maxDelay}\n}","line":{"from":219,"to":221}} {"id":100029396,"name":"When","signature":"func (w WithMaxWaitRateLimiter) When(item interface{}) time.Duration","file":"staging/src/k8s.io/client-go/util/workqueue/default_rate_limiters.go","code":"func (w WithMaxWaitRateLimiter) When(item interface{}) time.Duration {\n\tdelay := w.limiter.When(item)\n\tif delay \u003e w.maxDelay {\n\t\treturn w.maxDelay\n\t}\n\n\treturn delay\n}","line":{"from":223,"to":230}} {"id":100029397,"name":"Forget","signature":"func (w WithMaxWaitRateLimiter) Forget(item interface{})","file":"staging/src/k8s.io/client-go/util/workqueue/default_rate_limiters.go","code":"func (w WithMaxWaitRateLimiter) Forget(item interface{}) {\n\tw.limiter.Forget(item)\n}","line":{"from":232,"to":234}} {"id":100029398,"name":"NumRequeues","signature":"func (w WithMaxWaitRateLimiter) NumRequeues(item interface{}) int","file":"staging/src/k8s.io/client-go/util/workqueue/default_rate_limiters.go","code":"func (w WithMaxWaitRateLimiter) NumRequeues(item interface{}) int {\n\treturn w.limiter.NumRequeues(item)\n}","line":{"from":236,"to":238}} {"id":100029399,"name":"NewDelayingQueue","signature":"func NewDelayingQueue() DelayingInterface","file":"staging/src/k8s.io/client-go/util/workqueue/delaying_queue.go","code":"// NewDelayingQueue constructs a new workqueue with delayed queuing ability.\n// NewDelayingQueue does not emit metrics. For use with a MetricsProvider, please use\n// NewDelayingQueueWithConfig instead and specify a name.\nfunc NewDelayingQueue() DelayingInterface {\n\treturn NewDelayingQueueWithConfig(DelayingQueueConfig{})\n}","line":{"from":52,"to":57}} {"id":100029400,"name":"NewDelayingQueueWithConfig","signature":"func NewDelayingQueueWithConfig(config DelayingQueueConfig) DelayingInterface","file":"staging/src/k8s.io/client-go/util/workqueue/delaying_queue.go","code":"// NewDelayingQueueWithConfig constructs a new workqueue with options to\n// customize different properties.\nfunc NewDelayingQueueWithConfig(config DelayingQueueConfig) DelayingInterface {\n\tif config.Clock == nil {\n\t\tconfig.Clock = clock.RealClock{}\n\t}\n\n\tif config.Queue == nil {\n\t\tconfig.Queue = NewWithConfig(QueueConfig{\n\t\t\tName: config.Name,\n\t\t\tMetricsProvider: config.MetricsProvider,\n\t\t\tClock: config.Clock,\n\t\t})\n\t}\n\n\treturn newDelayingQueue(config.Clock, config.Queue, config.Name, config.MetricsProvider)\n}","line":{"from":59,"to":75}} {"id":100029401,"name":"NewDelayingQueueWithCustomQueue","signature":"func NewDelayingQueueWithCustomQueue(q Interface, name string) DelayingInterface","file":"staging/src/k8s.io/client-go/util/workqueue/delaying_queue.go","code":"// NewDelayingQueueWithCustomQueue constructs a new workqueue with ability to\n// inject custom queue Interface instead of the default one\n// Deprecated: Use NewDelayingQueueWithConfig instead.\nfunc NewDelayingQueueWithCustomQueue(q Interface, name string) DelayingInterface {\n\treturn NewDelayingQueueWithConfig(DelayingQueueConfig{\n\t\tName: name,\n\t\tQueue: q,\n\t})\n}","line":{"from":77,"to":85}} {"id":100029402,"name":"NewNamedDelayingQueue","signature":"func NewNamedDelayingQueue(name string) DelayingInterface","file":"staging/src/k8s.io/client-go/util/workqueue/delaying_queue.go","code":"// NewNamedDelayingQueue constructs a new named workqueue with delayed queuing ability.\n// Deprecated: Use NewDelayingQueueWithConfig instead.\nfunc NewNamedDelayingQueue(name string) DelayingInterface {\n\treturn NewDelayingQueueWithConfig(DelayingQueueConfig{Name: name})\n}","line":{"from":87,"to":91}} {"id":100029403,"name":"NewDelayingQueueWithCustomClock","signature":"func NewDelayingQueueWithCustomClock(clock clock.WithTicker, name string) DelayingInterface","file":"staging/src/k8s.io/client-go/util/workqueue/delaying_queue.go","code":"// NewDelayingQueueWithCustomClock constructs a new named workqueue\n// with ability to inject real or fake clock for testing purposes.\n// Deprecated: Use NewDelayingQueueWithConfig instead.\nfunc NewDelayingQueueWithCustomClock(clock clock.WithTicker, name string) DelayingInterface {\n\treturn NewDelayingQueueWithConfig(DelayingQueueConfig{\n\t\tName: name,\n\t\tClock: clock,\n\t})\n}","line":{"from":93,"to":101}} {"id":100029404,"name":"newDelayingQueue","signature":"func newDelayingQueue(clock clock.WithTicker, q Interface, name string, provider MetricsProvider) *delayingType","file":"staging/src/k8s.io/client-go/util/workqueue/delaying_queue.go","code":"func newDelayingQueue(clock clock.WithTicker, q Interface, name string, provider MetricsProvider) *delayingType {\n\tret := \u0026delayingType{\n\t\tInterface: q,\n\t\tclock: clock,\n\t\theartbeat: clock.NewTicker(maxWait),\n\t\tstopCh: make(chan struct{}),\n\t\twaitingForAddCh: make(chan *waitFor, 1000),\n\t\tmetrics: newRetryMetrics(name, provider),\n\t}\n\n\tgo ret.waitingLoop()\n\treturn ret\n}","line":{"from":103,"to":115}} {"id":100029405,"name":"Len","signature":"func (pq waitForPriorityQueue) Len() int","file":"staging/src/k8s.io/client-go/util/workqueue/delaying_queue.go","code":"func (pq waitForPriorityQueue) Len() int {\n\treturn len(pq)\n}","line":{"from":157,"to":159}} {"id":100029406,"name":"Less","signature":"func (pq waitForPriorityQueue) Less(i, j int) bool","file":"staging/src/k8s.io/client-go/util/workqueue/delaying_queue.go","code":"func (pq waitForPriorityQueue) Less(i, j int) bool {\n\treturn pq[i].readyAt.Before(pq[j].readyAt)\n}","line":{"from":160,"to":162}} {"id":100029407,"name":"Swap","signature":"func (pq waitForPriorityQueue) Swap(i, j int)","file":"staging/src/k8s.io/client-go/util/workqueue/delaying_queue.go","code":"func (pq waitForPriorityQueue) Swap(i, j int) {\n\tpq[i], pq[j] = pq[j], pq[i]\n\tpq[i].index = i\n\tpq[j].index = j\n}","line":{"from":163,"to":167}} {"id":100029408,"name":"Push","signature":"func (pq *waitForPriorityQueue) Push(x interface{})","file":"staging/src/k8s.io/client-go/util/workqueue/delaying_queue.go","code":"// Push adds an item to the queue. Push should not be called directly; instead,\n// use `heap.Push`.\nfunc (pq *waitForPriorityQueue) Push(x interface{}) {\n\tn := len(*pq)\n\titem := x.(*waitFor)\n\titem.index = n\n\t*pq = append(*pq, item)\n}","line":{"from":169,"to":176}} {"id":100029409,"name":"Pop","signature":"func (pq *waitForPriorityQueue) Pop() interface{}","file":"staging/src/k8s.io/client-go/util/workqueue/delaying_queue.go","code":"// Pop removes an item from the queue. Pop should not be called directly;\n// instead, use `heap.Pop`.\nfunc (pq *waitForPriorityQueue) Pop() interface{} {\n\tn := len(*pq)\n\titem := (*pq)[n-1]\n\titem.index = -1\n\t*pq = (*pq)[0:(n - 1)]\n\treturn item\n}","line":{"from":178,"to":186}} {"id":100029410,"name":"Peek","signature":"func (pq waitForPriorityQueue) Peek() interface{}","file":"staging/src/k8s.io/client-go/util/workqueue/delaying_queue.go","code":"// Peek returns the item at the beginning of the queue, without removing the\n// item or otherwise mutating the queue. It is safe to call directly.\nfunc (pq waitForPriorityQueue) Peek() interface{} {\n\treturn pq[0]\n}","line":{"from":188,"to":192}} {"id":100029411,"name":"ShutDown","signature":"func (q *delayingType) ShutDown()","file":"staging/src/k8s.io/client-go/util/workqueue/delaying_queue.go","code":"// ShutDown stops the queue. After the queue drains, the returned shutdown bool\n// on Get() will be true. This method may be invoked more than once.\nfunc (q *delayingType) ShutDown() {\n\tq.stopOnce.Do(func() {\n\t\tq.Interface.ShutDown()\n\t\tclose(q.stopCh)\n\t\tq.heartbeat.Stop()\n\t})\n}","line":{"from":194,"to":202}} {"id":100029412,"name":"AddAfter","signature":"func (q *delayingType) AddAfter(item interface{}, duration time.Duration)","file":"staging/src/k8s.io/client-go/util/workqueue/delaying_queue.go","code":"// AddAfter adds the given item to the work queue after the given delay\nfunc (q *delayingType) AddAfter(item interface{}, duration time.Duration) {\n\t// don't add if we're already shutting down\n\tif q.ShuttingDown() {\n\t\treturn\n\t}\n\n\tq.metrics.retry()\n\n\t// immediately add things with no delay\n\tif duration \u003c= 0 {\n\t\tq.Add(item)\n\t\treturn\n\t}\n\n\tselect {\n\tcase \u003c-q.stopCh:\n\t\t// unblock if ShutDown() is called\n\tcase q.waitingForAddCh \u003c- \u0026waitFor{data: item, readyAt: q.clock.Now().Add(duration)}:\n\t}\n}","line":{"from":204,"to":224}} {"id":100029413,"name":"waitingLoop","signature":"func (q *delayingType) waitingLoop()","file":"staging/src/k8s.io/client-go/util/workqueue/delaying_queue.go","code":"// waitingLoop runs until the workqueue is shutdown and keeps a check on the list of items to be added.\nfunc (q *delayingType) waitingLoop() {\n\tdefer utilruntime.HandleCrash()\n\n\t// Make a placeholder channel to use when there are no items in our list\n\tnever := make(\u003c-chan time.Time)\n\n\t// Make a timer that expires when the item at the head of the waiting queue is ready\n\tvar nextReadyAtTimer clock.Timer\n\n\twaitingForQueue := \u0026waitForPriorityQueue{}\n\theap.Init(waitingForQueue)\n\n\twaitingEntryByData := map[t]*waitFor{}\n\n\tfor {\n\t\tif q.Interface.ShuttingDown() {\n\t\t\treturn\n\t\t}\n\n\t\tnow := q.clock.Now()\n\n\t\t// Add ready entries\n\t\tfor waitingForQueue.Len() \u003e 0 {\n\t\t\tentry := waitingForQueue.Peek().(*waitFor)\n\t\t\tif entry.readyAt.After(now) {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tentry = heap.Pop(waitingForQueue).(*waitFor)\n\t\t\tq.Add(entry.data)\n\t\t\tdelete(waitingEntryByData, entry.data)\n\t\t}\n\n\t\t// Set up a wait for the first item's readyAt (if one exists)\n\t\tnextReadyAt := never\n\t\tif waitingForQueue.Len() \u003e 0 {\n\t\t\tif nextReadyAtTimer != nil {\n\t\t\t\tnextReadyAtTimer.Stop()\n\t\t\t}\n\t\t\tentry := waitingForQueue.Peek().(*waitFor)\n\t\t\tnextReadyAtTimer = q.clock.NewTimer(entry.readyAt.Sub(now))\n\t\t\tnextReadyAt = nextReadyAtTimer.C()\n\t\t}\n\n\t\tselect {\n\t\tcase \u003c-q.stopCh:\n\t\t\treturn\n\n\t\tcase \u003c-q.heartbeat.C():\n\t\t\t// continue the loop, which will add ready items\n\n\t\tcase \u003c-nextReadyAt:\n\t\t\t// continue the loop, which will add ready items\n\n\t\tcase waitEntry := \u003c-q.waitingForAddCh:\n\t\t\tif waitEntry.readyAt.After(q.clock.Now()) {\n\t\t\t\tinsert(waitingForQueue, waitingEntryByData, waitEntry)\n\t\t\t} else {\n\t\t\t\tq.Add(waitEntry.data)\n\t\t\t}\n\n\t\t\tdrained := false\n\t\t\tfor !drained {\n\t\t\t\tselect {\n\t\t\t\tcase waitEntry := \u003c-q.waitingForAddCh:\n\t\t\t\t\tif waitEntry.readyAt.After(q.clock.Now()) {\n\t\t\t\t\t\tinsert(waitingForQueue, waitingEntryByData, waitEntry)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tq.Add(waitEntry.data)\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\tdrained = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":231,"to":308}} {"id":100029414,"name":"insert","signature":"func insert(q *waitForPriorityQueue, knownEntries map[t]*waitFor, entry *waitFor)","file":"staging/src/k8s.io/client-go/util/workqueue/delaying_queue.go","code":"// insert adds the entry to the priority queue, or updates the readyAt if it already exists in the queue\nfunc insert(q *waitForPriorityQueue, knownEntries map[t]*waitFor, entry *waitFor) {\n\t// if the entry already exists, update the time only if it would cause the item to be queued sooner\n\texisting, exists := knownEntries[entry.data]\n\tif exists {\n\t\tif existing.readyAt.After(entry.readyAt) {\n\t\t\texisting.readyAt = entry.readyAt\n\t\t\theap.Fix(q, existing.index)\n\t\t}\n\n\t\treturn\n\t}\n\n\theap.Push(q, entry)\n\tknownEntries[entry.data] = entry\n}","line":{"from":310,"to":325}} {"id":100029415,"name":"Inc","signature":"func (noopMetric) Inc() {}","file":"staging/src/k8s.io/client-go/util/workqueue/metrics.go","code":"func (noopMetric) Inc() {}","line":{"from":67,"to":67}} {"id":100029416,"name":"Dec","signature":"func (noopMetric) Dec() {}","file":"staging/src/k8s.io/client-go/util/workqueue/metrics.go","code":"func (noopMetric) Dec() {}","line":{"from":68,"to":68}} {"id":100029417,"name":"Set","signature":"func (noopMetric) Set(float64) {}","file":"staging/src/k8s.io/client-go/util/workqueue/metrics.go","code":"func (noopMetric) Set(float64) {}","line":{"from":69,"to":69}} {"id":100029418,"name":"Observe","signature":"func (noopMetric) Observe(float64) {}","file":"staging/src/k8s.io/client-go/util/workqueue/metrics.go","code":"func (noopMetric) Observe(float64) {}","line":{"from":70,"to":70}} {"id":100029419,"name":"add","signature":"func (m *defaultQueueMetrics) add(item t)","file":"staging/src/k8s.io/client-go/util/workqueue/metrics.go","code":"func (m *defaultQueueMetrics) add(item t) {\n\tif m == nil {\n\t\treturn\n\t}\n\n\tm.adds.Inc()\n\tm.depth.Inc()\n\tif _, exists := m.addTimes[item]; !exists {\n\t\tm.addTimes[item] = m.clock.Now()\n\t}\n}","line":{"from":92,"to":102}} {"id":100029420,"name":"get","signature":"func (m *defaultQueueMetrics) get(item t)","file":"staging/src/k8s.io/client-go/util/workqueue/metrics.go","code":"func (m *defaultQueueMetrics) get(item t) {\n\tif m == nil {\n\t\treturn\n\t}\n\n\tm.depth.Dec()\n\tm.processingStartTimes[item] = m.clock.Now()\n\tif startTime, exists := m.addTimes[item]; exists {\n\t\tm.latency.Observe(m.sinceInSeconds(startTime))\n\t\tdelete(m.addTimes, item)\n\t}\n}","line":{"from":104,"to":115}} {"id":100029421,"name":"done","signature":"func (m *defaultQueueMetrics) done(item t)","file":"staging/src/k8s.io/client-go/util/workqueue/metrics.go","code":"func (m *defaultQueueMetrics) done(item t) {\n\tif m == nil {\n\t\treturn\n\t}\n\n\tif startTime, exists := m.processingStartTimes[item]; exists {\n\t\tm.workDuration.Observe(m.sinceInSeconds(startTime))\n\t\tdelete(m.processingStartTimes, item)\n\t}\n}","line":{"from":117,"to":126}} {"id":100029422,"name":"updateUnfinishedWork","signature":"func (m *defaultQueueMetrics) updateUnfinishedWork()","file":"staging/src/k8s.io/client-go/util/workqueue/metrics.go","code":"func (m *defaultQueueMetrics) updateUnfinishedWork() {\n\t// Note that a summary metric would be better for this, but prometheus\n\t// doesn't seem to have non-hacky ways to reset the summary metrics.\n\tvar total float64\n\tvar oldest float64\n\tfor _, t := range m.processingStartTimes {\n\t\tage := m.sinceInSeconds(t)\n\t\ttotal += age\n\t\tif age \u003e oldest {\n\t\t\toldest = age\n\t\t}\n\t}\n\tm.unfinishedWorkSeconds.Set(total)\n\tm.longestRunningProcessor.Set(oldest)\n}","line":{"from":128,"to":142}} {"id":100029423,"name":"add","signature":"func (noMetrics) add(item t) {}","file":"staging/src/k8s.io/client-go/util/workqueue/metrics.go","code":"func (noMetrics) add(item t) {}","line":{"from":146,"to":146}} {"id":100029424,"name":"get","signature":"func (noMetrics) get(item t) {}","file":"staging/src/k8s.io/client-go/util/workqueue/metrics.go","code":"func (noMetrics) get(item t) {}","line":{"from":147,"to":147}} {"id":100029425,"name":"done","signature":"func (noMetrics) done(item t) {}","file":"staging/src/k8s.io/client-go/util/workqueue/metrics.go","code":"func (noMetrics) done(item t) {}","line":{"from":148,"to":148}} {"id":100029426,"name":"updateUnfinishedWork","signature":"func (noMetrics) updateUnfinishedWork() {}","file":"staging/src/k8s.io/client-go/util/workqueue/metrics.go","code":"func (noMetrics) updateUnfinishedWork() {}","line":{"from":149,"to":149}} {"id":100029427,"name":"sinceInSeconds","signature":"func (m *defaultQueueMetrics) sinceInSeconds(start time.Time) float64","file":"staging/src/k8s.io/client-go/util/workqueue/metrics.go","code":"// Gets the time since the specified start in seconds.\nfunc (m *defaultQueueMetrics) sinceInSeconds(start time.Time) float64 {\n\treturn m.clock.Since(start).Seconds()\n}","line":{"from":151,"to":154}} {"id":100029428,"name":"retry","signature":"func (m *defaultRetryMetrics) retry()","file":"staging/src/k8s.io/client-go/util/workqueue/metrics.go","code":"func (m *defaultRetryMetrics) retry() {\n\tif m == nil {\n\t\treturn\n\t}\n\n\tm.retries.Inc()\n}","line":{"from":164,"to":170}} {"id":100029429,"name":"NewDepthMetric","signature":"func (_ noopMetricsProvider) NewDepthMetric(name string) GaugeMetric","file":"staging/src/k8s.io/client-go/util/workqueue/metrics.go","code":"func (_ noopMetricsProvider) NewDepthMetric(name string) GaugeMetric {\n\treturn noopMetric{}\n}","line":{"from":185,"to":187}} {"id":100029430,"name":"NewAddsMetric","signature":"func (_ noopMetricsProvider) NewAddsMetric(name string) CounterMetric","file":"staging/src/k8s.io/client-go/util/workqueue/metrics.go","code":"func (_ noopMetricsProvider) NewAddsMetric(name string) CounterMetric {\n\treturn noopMetric{}\n}","line":{"from":189,"to":191}} {"id":100029431,"name":"NewLatencyMetric","signature":"func (_ noopMetricsProvider) NewLatencyMetric(name string) HistogramMetric","file":"staging/src/k8s.io/client-go/util/workqueue/metrics.go","code":"func (_ noopMetricsProvider) NewLatencyMetric(name string) HistogramMetric {\n\treturn noopMetric{}\n}","line":{"from":193,"to":195}} {"id":100029432,"name":"NewWorkDurationMetric","signature":"func (_ noopMetricsProvider) NewWorkDurationMetric(name string) HistogramMetric","file":"staging/src/k8s.io/client-go/util/workqueue/metrics.go","code":"func (_ noopMetricsProvider) NewWorkDurationMetric(name string) HistogramMetric {\n\treturn noopMetric{}\n}","line":{"from":197,"to":199}} {"id":100029433,"name":"NewUnfinishedWorkSecondsMetric","signature":"func (_ noopMetricsProvider) NewUnfinishedWorkSecondsMetric(name string) SettableGaugeMetric","file":"staging/src/k8s.io/client-go/util/workqueue/metrics.go","code":"func (_ noopMetricsProvider) NewUnfinishedWorkSecondsMetric(name string) SettableGaugeMetric {\n\treturn noopMetric{}\n}","line":{"from":201,"to":203}} {"id":100029434,"name":"NewLongestRunningProcessorSecondsMetric","signature":"func (_ noopMetricsProvider) NewLongestRunningProcessorSecondsMetric(name string) SettableGaugeMetric","file":"staging/src/k8s.io/client-go/util/workqueue/metrics.go","code":"func (_ noopMetricsProvider) NewLongestRunningProcessorSecondsMetric(name string) SettableGaugeMetric {\n\treturn noopMetric{}\n}","line":{"from":205,"to":207}} {"id":100029435,"name":"NewRetriesMetric","signature":"func (_ noopMetricsProvider) NewRetriesMetric(name string) CounterMetric","file":"staging/src/k8s.io/client-go/util/workqueue/metrics.go","code":"func (_ noopMetricsProvider) NewRetriesMetric(name string) CounterMetric {\n\treturn noopMetric{}\n}","line":{"from":209,"to":211}} {"id":100029436,"name":"setProvider","signature":"func (f *queueMetricsFactory) setProvider(mp MetricsProvider)","file":"staging/src/k8s.io/client-go/util/workqueue/metrics.go","code":"func (f *queueMetricsFactory) setProvider(mp MetricsProvider) {\n\tf.onlyOnce.Do(func() {\n\t\tf.metricsProvider = mp\n\t})\n}","line":{"from":223,"to":227}} {"id":100029437,"name":"newQueueMetrics","signature":"func (f *queueMetricsFactory) newQueueMetrics(name string, clock clock.Clock) queueMetrics","file":"staging/src/k8s.io/client-go/util/workqueue/metrics.go","code":"func (f *queueMetricsFactory) newQueueMetrics(name string, clock clock.Clock) queueMetrics {\n\tmp := f.metricsProvider\n\tif len(name) == 0 || mp == (noopMetricsProvider{}) {\n\t\treturn noMetrics{}\n\t}\n\treturn \u0026defaultQueueMetrics{\n\t\tclock: clock,\n\t\tdepth: mp.NewDepthMetric(name),\n\t\tadds: mp.NewAddsMetric(name),\n\t\tlatency: mp.NewLatencyMetric(name),\n\t\tworkDuration: mp.NewWorkDurationMetric(name),\n\t\tunfinishedWorkSeconds: mp.NewUnfinishedWorkSecondsMetric(name),\n\t\tlongestRunningProcessor: mp.NewLongestRunningProcessorSecondsMetric(name),\n\t\taddTimes: map[t]time.Time{},\n\t\tprocessingStartTimes: map[t]time.Time{},\n\t}\n}","line":{"from":229,"to":245}} {"id":100029438,"name":"newRetryMetrics","signature":"func newRetryMetrics(name string, provider MetricsProvider) retryMetrics","file":"staging/src/k8s.io/client-go/util/workqueue/metrics.go","code":"func newRetryMetrics(name string, provider MetricsProvider) retryMetrics {\n\tvar ret *defaultRetryMetrics\n\tif len(name) == 0 {\n\t\treturn ret\n\t}\n\n\tif provider == nil {\n\t\tprovider = globalMetricsFactory.metricsProvider\n\t}\n\n\treturn \u0026defaultRetryMetrics{\n\t\tretries: provider.NewRetriesMetric(name),\n\t}\n}","line":{"from":247,"to":260}} {"id":100029439,"name":"SetProvider","signature":"func SetProvider(metricsProvider MetricsProvider)","file":"staging/src/k8s.io/client-go/util/workqueue/metrics.go","code":"// SetProvider sets the metrics provider for all subsequently created work\n// queues. Only the first call has an effect.\nfunc SetProvider(metricsProvider MetricsProvider) {\n\tglobalMetricsFactory.setProvider(metricsProvider)\n}","line":{"from":262,"to":266}} {"id":100029440,"name":"WithChunkSize","signature":"func WithChunkSize(c int) func(*options)","file":"staging/src/k8s.io/client-go/util/workqueue/parallelizer.go","code":"// WithChunkSize allows to set chunks of work items to the workers, rather than\n// processing one by one.\n// It is recommended to use this option if the number of pieces significantly\n// higher than the number of workers and the work done for each item is small.\nfunc WithChunkSize(c int) func(*options) {\n\treturn func(o *options) {\n\t\to.chunkSize = c\n\t}\n}","line":{"from":34,"to":42}} {"id":100029441,"name":"ParallelizeUntil","signature":"func ParallelizeUntil(ctx context.Context, workers, pieces int, doWorkPiece DoWorkPieceFunc, opts ...Options)","file":"staging/src/k8s.io/client-go/util/workqueue/parallelizer.go","code":"// ParallelizeUntil is a framework that allows for parallelizing N\n// independent pieces of work until done or the context is canceled.\nfunc ParallelizeUntil(ctx context.Context, workers, pieces int, doWorkPiece DoWorkPieceFunc, opts ...Options) {\n\tif pieces == 0 {\n\t\treturn\n\t}\n\to := options{}\n\tfor _, opt := range opts {\n\t\topt(\u0026o)\n\t}\n\tchunkSize := o.chunkSize\n\tif chunkSize \u003c 1 {\n\t\tchunkSize = 1\n\t}\n\n\tchunks := ceilDiv(pieces, chunkSize)\n\ttoProcess := make(chan int, chunks)\n\tfor i := 0; i \u003c chunks; i++ {\n\t\ttoProcess \u003c- i\n\t}\n\tclose(toProcess)\n\n\tvar stop \u003c-chan struct{}\n\tif ctx != nil {\n\t\tstop = ctx.Done()\n\t}\n\tif chunks \u003c workers {\n\t\tworkers = chunks\n\t}\n\twg := sync.WaitGroup{}\n\twg.Add(workers)\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo func() {\n\t\t\tdefer utilruntime.HandleCrash()\n\t\t\tdefer wg.Done()\n\t\t\tfor chunk := range toProcess {\n\t\t\t\tstart := chunk * chunkSize\n\t\t\t\tend := start + chunkSize\n\t\t\t\tif end \u003e pieces {\n\t\t\t\t\tend = pieces\n\t\t\t\t}\n\t\t\t\tfor p := start; p \u003c end; p++ {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase \u003c-stop:\n\t\t\t\t\t\treturn\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tdoWorkPiece(p)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\twg.Wait()\n}","line":{"from":44,"to":97}} {"id":100029442,"name":"ceilDiv","signature":"func ceilDiv(a, b int) int","file":"staging/src/k8s.io/client-go/util/workqueue/parallelizer.go","code":"func ceilDiv(a, b int) int {\n\treturn (a + b - 1) / b\n}","line":{"from":99,"to":101}} {"id":100029443,"name":"New","signature":"func New() *Type","file":"staging/src/k8s.io/client-go/util/workqueue/queue.go","code":"// New constructs a new work queue (see the package comment).\nfunc New() *Type {\n\treturn NewWithConfig(QueueConfig{\n\t\tName: \"\",\n\t})\n}","line":{"from":49,"to":54}} {"id":100029444,"name":"NewWithConfig","signature":"func NewWithConfig(config QueueConfig) *Type","file":"staging/src/k8s.io/client-go/util/workqueue/queue.go","code":"// NewWithConfig constructs a new workqueue with ability to\n// customize different properties.\nfunc NewWithConfig(config QueueConfig) *Type {\n\treturn newQueueWithConfig(config, defaultUnfinishedWorkUpdatePeriod)\n}","line":{"from":56,"to":60}} {"id":100029445,"name":"NewNamed","signature":"func NewNamed(name string) *Type","file":"staging/src/k8s.io/client-go/util/workqueue/queue.go","code":"// NewNamed creates a new named queue.\n// Deprecated: Use NewWithConfig instead.\nfunc NewNamed(name string) *Type {\n\treturn NewWithConfig(QueueConfig{\n\t\tName: name,\n\t})\n}","line":{"from":62,"to":68}} {"id":100029446,"name":"newQueueWithConfig","signature":"func newQueueWithConfig(config QueueConfig, updatePeriod time.Duration) *Type","file":"staging/src/k8s.io/client-go/util/workqueue/queue.go","code":"// newQueueWithConfig constructs a new named workqueue\n// with the ability to customize different properties for testing purposes\nfunc newQueueWithConfig(config QueueConfig, updatePeriod time.Duration) *Type {\n\tvar metricsFactory *queueMetricsFactory\n\tif config.MetricsProvider != nil {\n\t\tmetricsFactory = \u0026queueMetricsFactory{\n\t\t\tmetricsProvider: config.MetricsProvider,\n\t\t}\n\t} else {\n\t\tmetricsFactory = \u0026globalMetricsFactory\n\t}\n\n\tif config.Clock == nil {\n\t\tconfig.Clock = clock.RealClock{}\n\t}\n\n\treturn newQueue(\n\t\tconfig.Clock,\n\t\tmetricsFactory.newQueueMetrics(config.Name, config.Clock),\n\t\tupdatePeriod,\n\t)\n}","line":{"from":70,"to":91}} {"id":100029447,"name":"newQueue","signature":"func newQueue(c clock.WithTicker, metrics queueMetrics, updatePeriod time.Duration) *Type","file":"staging/src/k8s.io/client-go/util/workqueue/queue.go","code":"func newQueue(c clock.WithTicker, metrics queueMetrics, updatePeriod time.Duration) *Type {\n\tt := \u0026Type{\n\t\tclock: c,\n\t\tdirty: set{},\n\t\tprocessing: set{},\n\t\tcond: sync.NewCond(\u0026sync.Mutex{}),\n\t\tmetrics: metrics,\n\t\tunfinishedWorkUpdatePeriod: updatePeriod,\n\t}\n\n\t// Don't start the goroutine for a type of noMetrics so we don't consume\n\t// resources unnecessarily\n\tif _, ok := metrics.(noMetrics); !ok {\n\t\tgo t.updateUnfinishedWorkLoop()\n\t}\n\n\treturn t\n}","line":{"from":93,"to":110}} {"id":100029448,"name":"has","signature":"func (s set) has(item t) bool","file":"staging/src/k8s.io/client-go/util/workqueue/queue.go","code":"func (s set) has(item t) bool {\n\t_, exists := s[item]\n\treturn exists\n}","line":{"from":145,"to":148}} {"id":100029449,"name":"insert","signature":"func (s set) insert(item t)","file":"staging/src/k8s.io/client-go/util/workqueue/queue.go","code":"func (s set) insert(item t) {\n\ts[item] = empty{}\n}","line":{"from":150,"to":152}} {"id":100029450,"name":"delete","signature":"func (s set) delete(item t)","file":"staging/src/k8s.io/client-go/util/workqueue/queue.go","code":"func (s set) delete(item t) {\n\tdelete(s, item)\n}","line":{"from":154,"to":156}} {"id":100029451,"name":"len","signature":"func (s set) len() int","file":"staging/src/k8s.io/client-go/util/workqueue/queue.go","code":"func (s set) len() int {\n\treturn len(s)\n}","line":{"from":158,"to":160}} {"id":100029452,"name":"Add","signature":"func (q *Type) Add(item interface{})","file":"staging/src/k8s.io/client-go/util/workqueue/queue.go","code":"// Add marks item as needing processing.\nfunc (q *Type) Add(item interface{}) {\n\tq.cond.L.Lock()\n\tdefer q.cond.L.Unlock()\n\tif q.shuttingDown {\n\t\treturn\n\t}\n\tif q.dirty.has(item) {\n\t\treturn\n\t}\n\n\tq.metrics.add(item)\n\n\tq.dirty.insert(item)\n\tif q.processing.has(item) {\n\t\treturn\n\t}\n\n\tq.queue = append(q.queue, item)\n\tq.cond.Signal()\n}","line":{"from":162,"to":182}} {"id":100029453,"name":"Len","signature":"func (q *Type) Len() int","file":"staging/src/k8s.io/client-go/util/workqueue/queue.go","code":"// Len returns the current queue length, for informational purposes only. You\n// shouldn't e.g. gate a call to Add() or Get() on Len() being a particular\n// value, that can't be synchronized properly.\nfunc (q *Type) Len() int {\n\tq.cond.L.Lock()\n\tdefer q.cond.L.Unlock()\n\treturn len(q.queue)\n}","line":{"from":184,"to":191}} {"id":100029454,"name":"Get","signature":"func (q *Type) Get() (item interface{}, shutdown bool)","file":"staging/src/k8s.io/client-go/util/workqueue/queue.go","code":"// Get blocks until it can return an item to be processed. If shutdown = true,\n// the caller should end their goroutine. You must call Done with item when you\n// have finished processing it.\nfunc (q *Type) Get() (item interface{}, shutdown bool) {\n\tq.cond.L.Lock()\n\tdefer q.cond.L.Unlock()\n\tfor len(q.queue) == 0 \u0026\u0026 !q.shuttingDown {\n\t\tq.cond.Wait()\n\t}\n\tif len(q.queue) == 0 {\n\t\t// We must be shutting down.\n\t\treturn nil, true\n\t}\n\n\titem = q.queue[0]\n\t// The underlying array still exists and reference this object, so the object will not be garbage collected.\n\tq.queue[0] = nil\n\tq.queue = q.queue[1:]\n\n\tq.metrics.get(item)\n\n\tq.processing.insert(item)\n\tq.dirty.delete(item)\n\n\treturn item, false\n}","line":{"from":193,"to":218}} {"id":100029455,"name":"Done","signature":"func (q *Type) Done(item interface{})","file":"staging/src/k8s.io/client-go/util/workqueue/queue.go","code":"// Done marks item as done processing, and if it has been marked as dirty again\n// while it was being processed, it will be re-added to the queue for\n// re-processing.\nfunc (q *Type) Done(item interface{}) {\n\tq.cond.L.Lock()\n\tdefer q.cond.L.Unlock()\n\n\tq.metrics.done(item)\n\n\tq.processing.delete(item)\n\tif q.dirty.has(item) {\n\t\tq.queue = append(q.queue, item)\n\t\tq.cond.Signal()\n\t} else if q.processing.len() == 0 {\n\t\tq.cond.Signal()\n\t}\n}","line":{"from":220,"to":236}} {"id":100029456,"name":"ShutDown","signature":"func (q *Type) ShutDown()","file":"staging/src/k8s.io/client-go/util/workqueue/queue.go","code":"// ShutDown will cause q to ignore all new items added to it and\n// immediately instruct the worker goroutines to exit.\nfunc (q *Type) ShutDown() {\n\tq.setDrain(false)\n\tq.shutdown()\n}","line":{"from":238,"to":243}} {"id":100029457,"name":"ShutDownWithDrain","signature":"func (q *Type) ShutDownWithDrain()","file":"staging/src/k8s.io/client-go/util/workqueue/queue.go","code":"// ShutDownWithDrain will cause q to ignore all new items added to it. As soon\n// as the worker goroutines have \"drained\", i.e: finished processing and called\n// Done on all existing items in the queue; they will be instructed to exit and\n// ShutDownWithDrain will return. Hence: a strict requirement for using this is;\n// your workers must ensure that Done is called on all items in the queue once\n// the shut down has been initiated, if that is not the case: this will block\n// indefinitely. It is, however, safe to call ShutDown after having called\n// ShutDownWithDrain, as to force the queue shut down to terminate immediately\n// without waiting for the drainage.\nfunc (q *Type) ShutDownWithDrain() {\n\tq.setDrain(true)\n\tq.shutdown()\n\tfor q.isProcessing() \u0026\u0026 q.shouldDrain() {\n\t\tq.waitForProcessing()\n\t}\n}","line":{"from":245,"to":260}} {"id":100029458,"name":"isProcessing","signature":"func (q *Type) isProcessing() bool","file":"staging/src/k8s.io/client-go/util/workqueue/queue.go","code":"// isProcessing indicates if there are still items on the work queue being\n// processed. It's used to drain the work queue on an eventual shutdown.\nfunc (q *Type) isProcessing() bool {\n\tq.cond.L.Lock()\n\tdefer q.cond.L.Unlock()\n\treturn q.processing.len() != 0\n}","line":{"from":262,"to":268}} {"id":100029459,"name":"waitForProcessing","signature":"func (q *Type) waitForProcessing()","file":"staging/src/k8s.io/client-go/util/workqueue/queue.go","code":"// waitForProcessing waits for the worker goroutines to finish processing items\n// and call Done on them.\nfunc (q *Type) waitForProcessing() {\n\tq.cond.L.Lock()\n\tdefer q.cond.L.Unlock()\n\t// Ensure that we do not wait on a queue which is already empty, as that\n\t// could result in waiting for Done to be called on items in an empty queue\n\t// which has already been shut down, which will result in waiting\n\t// indefinitely.\n\tif q.processing.len() == 0 {\n\t\treturn\n\t}\n\tq.cond.Wait()\n}","line":{"from":270,"to":283}} {"id":100029460,"name":"setDrain","signature":"func (q *Type) setDrain(shouldDrain bool)","file":"staging/src/k8s.io/client-go/util/workqueue/queue.go","code":"func (q *Type) setDrain(shouldDrain bool) {\n\tq.cond.L.Lock()\n\tdefer q.cond.L.Unlock()\n\tq.drain = shouldDrain\n}","line":{"from":285,"to":289}} {"id":100029461,"name":"shouldDrain","signature":"func (q *Type) shouldDrain() bool","file":"staging/src/k8s.io/client-go/util/workqueue/queue.go","code":"func (q *Type) shouldDrain() bool {\n\tq.cond.L.Lock()\n\tdefer q.cond.L.Unlock()\n\treturn q.drain\n}","line":{"from":291,"to":295}} {"id":100029462,"name":"shutdown","signature":"func (q *Type) shutdown()","file":"staging/src/k8s.io/client-go/util/workqueue/queue.go","code":"func (q *Type) shutdown() {\n\tq.cond.L.Lock()\n\tdefer q.cond.L.Unlock()\n\tq.shuttingDown = true\n\tq.cond.Broadcast()\n}","line":{"from":297,"to":302}} {"id":100029463,"name":"ShuttingDown","signature":"func (q *Type) ShuttingDown() bool","file":"staging/src/k8s.io/client-go/util/workqueue/queue.go","code":"func (q *Type) ShuttingDown() bool {\n\tq.cond.L.Lock()\n\tdefer q.cond.L.Unlock()\n\n\treturn q.shuttingDown\n}","line":{"from":304,"to":309}} {"id":100029464,"name":"updateUnfinishedWorkLoop","signature":"func (q *Type) updateUnfinishedWorkLoop()","file":"staging/src/k8s.io/client-go/util/workqueue/queue.go","code":"func (q *Type) updateUnfinishedWorkLoop() {\n\tt := q.clock.NewTicker(q.unfinishedWorkUpdatePeriod)\n\tdefer t.Stop()\n\tfor range t.C() {\n\t\tif !func() bool {\n\t\t\tq.cond.L.Lock()\n\t\t\tdefer q.cond.L.Unlock()\n\t\t\tif !q.shuttingDown {\n\t\t\t\tq.metrics.updateUnfinishedWork()\n\t\t\t\treturn true\n\t\t\t}\n\t\t\treturn false\n\n\t\t}() {\n\t\t\treturn\n\t\t}\n\t}\n}","line":{"from":311,"to":328}} {"id":100029465,"name":"NewRateLimitingQueue","signature":"func NewRateLimitingQueue(rateLimiter RateLimiter) RateLimitingInterface","file":"staging/src/k8s.io/client-go/util/workqueue/rate_limiting_queue.go","code":"// NewRateLimitingQueue constructs a new workqueue with rateLimited queuing ability\n// Remember to call Forget! If you don't, you may end up tracking failures forever.\n// NewRateLimitingQueue does not emit metrics. For use with a MetricsProvider, please use\n// NewRateLimitingQueueWithConfig instead and specify a name.\nfunc NewRateLimitingQueue(rateLimiter RateLimiter) RateLimitingInterface {\n\treturn NewRateLimitingQueueWithConfig(rateLimiter, RateLimitingQueueConfig{})\n}","line":{"from":54,"to":60}} {"id":100029466,"name":"NewRateLimitingQueueWithConfig","signature":"func NewRateLimitingQueueWithConfig(rateLimiter RateLimiter, config RateLimitingQueueConfig) RateLimitingInterface","file":"staging/src/k8s.io/client-go/util/workqueue/rate_limiting_queue.go","code":"// NewRateLimitingQueueWithConfig constructs a new workqueue with rateLimited queuing ability\n// with options to customize different properties.\n// Remember to call Forget! If you don't, you may end up tracking failures forever.\nfunc NewRateLimitingQueueWithConfig(rateLimiter RateLimiter, config RateLimitingQueueConfig) RateLimitingInterface {\n\tif config.Clock == nil {\n\t\tconfig.Clock = clock.RealClock{}\n\t}\n\n\tif config.DelayingQueue == nil {\n\t\tconfig.DelayingQueue = NewDelayingQueueWithConfig(DelayingQueueConfig{\n\t\t\tName: config.Name,\n\t\t\tMetricsProvider: config.MetricsProvider,\n\t\t\tClock: config.Clock,\n\t\t})\n\t}\n\n\treturn \u0026rateLimitingType{\n\t\tDelayingInterface: config.DelayingQueue,\n\t\trateLimiter: rateLimiter,\n\t}\n}","line":{"from":62,"to":82}} {"id":100029467,"name":"NewNamedRateLimitingQueue","signature":"func NewNamedRateLimitingQueue(rateLimiter RateLimiter, name string) RateLimitingInterface","file":"staging/src/k8s.io/client-go/util/workqueue/rate_limiting_queue.go","code":"// NewNamedRateLimitingQueue constructs a new named workqueue with rateLimited queuing ability.\n// Deprecated: Use NewRateLimitingQueueWithConfig instead.\nfunc NewNamedRateLimitingQueue(rateLimiter RateLimiter, name string) RateLimitingInterface {\n\treturn NewRateLimitingQueueWithConfig(rateLimiter, RateLimitingQueueConfig{\n\t\tName: name,\n\t})\n}","line":{"from":84,"to":90}} {"id":100029468,"name":"NewRateLimitingQueueWithDelayingInterface","signature":"func NewRateLimitingQueueWithDelayingInterface(di DelayingInterface, rateLimiter RateLimiter) RateLimitingInterface","file":"staging/src/k8s.io/client-go/util/workqueue/rate_limiting_queue.go","code":"// NewRateLimitingQueueWithDelayingInterface constructs a new named workqueue with rateLimited queuing ability\n// with the option to inject a custom delaying queue instead of the default one.\n// Deprecated: Use NewRateLimitingQueueWithConfig instead.\nfunc NewRateLimitingQueueWithDelayingInterface(di DelayingInterface, rateLimiter RateLimiter) RateLimitingInterface {\n\treturn NewRateLimitingQueueWithConfig(rateLimiter, RateLimitingQueueConfig{\n\t\tDelayingQueue: di,\n\t})\n}","line":{"from":92,"to":99}} {"id":100029469,"name":"AddRateLimited","signature":"func (q *rateLimitingType) AddRateLimited(item interface{})","file":"staging/src/k8s.io/client-go/util/workqueue/rate_limiting_queue.go","code":"// AddRateLimited AddAfter's the item based on the time when the rate limiter says it's ok\nfunc (q *rateLimitingType) AddRateLimited(item interface{}) {\n\tq.DelayingInterface.AddAfter(item, q.rateLimiter.When(item))\n}","line":{"from":108,"to":111}} {"id":100029470,"name":"NumRequeues","signature":"func (q *rateLimitingType) NumRequeues(item interface{}) int","file":"staging/src/k8s.io/client-go/util/workqueue/rate_limiting_queue.go","code":"func (q *rateLimitingType) NumRequeues(item interface{}) int {\n\treturn q.rateLimiter.NumRequeues(item)\n}","line":{"from":113,"to":115}} {"id":100029471,"name":"Forget","signature":"func (q *rateLimitingType) Forget(item interface{})","file":"staging/src/k8s.io/client-go/util/workqueue/rate_limiting_queue.go","code":"func (q *rateLimitingType) Forget(item interface{}) {\n\tq.rateLimiter.Forget(item)\n}","line":{"from":117,"to":119}} {"id":100029472,"name":"NewBuilder","signature":"func NewBuilder() *CommandBuilder","file":"staging/src/k8s.io/cloud-provider/app/builder.go","code":"func NewBuilder() *CommandBuilder {\n\tcb := CommandBuilder{}\n\tcb.webhookConfigs = make(map[string]WebhookConfig)\n\tcb.controllerInitFuncConstructors = make(map[string]ControllerInitFuncConstructor)\n\treturn \u0026cb\n}","line":{"from":44,"to":49}} {"id":100029473,"name":"SetOptions","signature":"func (cb *CommandBuilder) SetOptions(options *options.CloudControllerManagerOptions)","file":"staging/src/k8s.io/cloud-provider/app/builder.go","code":"func (cb *CommandBuilder) SetOptions(options *options.CloudControllerManagerOptions) {\n\tcb.options = options\n}","line":{"from":51,"to":53}} {"id":100029474,"name":"AddFlags","signature":"func (cb *CommandBuilder) AddFlags(additionalFlags cliflag.NamedFlagSets)","file":"staging/src/k8s.io/cloud-provider/app/builder.go","code":"func (cb *CommandBuilder) AddFlags(additionalFlags cliflag.NamedFlagSets) {\n\tcb.additionalFlags = additionalFlags\n}","line":{"from":55,"to":57}} {"id":100029475,"name":"RegisterController","signature":"func (cb *CommandBuilder) RegisterController(name string, constructor ControllerInitFuncConstructor)","file":"staging/src/k8s.io/cloud-provider/app/builder.go","code":"func (cb *CommandBuilder) RegisterController(name string, constructor ControllerInitFuncConstructor) {\n\tcb.controllerInitFuncConstructors[name] = constructor\n}","line":{"from":59,"to":61}} {"id":100029476,"name":"RegisterDefaultControllers","signature":"func (cb *CommandBuilder) RegisterDefaultControllers()","file":"staging/src/k8s.io/cloud-provider/app/builder.go","code":"func (cb *CommandBuilder) RegisterDefaultControllers() {\n\tfor key, val := range DefaultInitFuncConstructors {\n\t\tcb.controllerInitFuncConstructors[key] = val\n\t}\n}","line":{"from":63,"to":67}} {"id":100029477,"name":"RegisterWebhook","signature":"func (cb *CommandBuilder) RegisterWebhook(name string, config WebhookConfig)","file":"staging/src/k8s.io/cloud-provider/app/builder.go","code":"func (cb *CommandBuilder) RegisterWebhook(name string, config WebhookConfig) {\n\tcb.webhookConfigs[name] = config\n}","line":{"from":69,"to":71}} {"id":100029478,"name":"SetCloudInitializer","signature":"func (cb *CommandBuilder) SetCloudInitializer(cloudInitializer InitCloudFunc)","file":"staging/src/k8s.io/cloud-provider/app/builder.go","code":"func (cb *CommandBuilder) SetCloudInitializer(cloudInitializer InitCloudFunc) {\n\tcb.cloudInitializer = cloudInitializer\n}","line":{"from":73,"to":75}} {"id":100029479,"name":"SetStopChannel","signature":"func (cb *CommandBuilder) SetStopChannel(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/cloud-provider/app/builder.go","code":"func (cb *CommandBuilder) SetStopChannel(stopCh \u003c-chan struct{}) {\n\tcb.stopCh = stopCh\n}","line":{"from":77,"to":79}} {"id":100029480,"name":"SetCmdName","signature":"func (cb *CommandBuilder) SetCmdName(name string)","file":"staging/src/k8s.io/cloud-provider/app/builder.go","code":"func (cb *CommandBuilder) SetCmdName(name string) {\n\tcb.cmdName = name\n}","line":{"from":81,"to":83}} {"id":100029481,"name":"SetLongDesc","signature":"func (cb *CommandBuilder) SetLongDesc(long string)","file":"staging/src/k8s.io/cloud-provider/app/builder.go","code":"func (cb *CommandBuilder) SetLongDesc(long string) {\n\tcb.long = long\n}","line":{"from":85,"to":87}} {"id":100029482,"name":"SetProviderDefaults","signature":"func (cb *CommandBuilder) SetProviderDefaults(defaults options.ProviderDefaults)","file":"staging/src/k8s.io/cloud-provider/app/builder.go","code":"// SetProviderDefaults can be called to change the default values for some\n// options when a flag is not set\nfunc (cb *CommandBuilder) SetProviderDefaults(defaults options.ProviderDefaults) {\n\tcb.defaults = \u0026defaults\n}","line":{"from":89,"to":93}} {"id":100029483,"name":"setdefaults","signature":"func (cb *CommandBuilder) setdefaults()","file":"staging/src/k8s.io/cloud-provider/app/builder.go","code":"func (cb *CommandBuilder) setdefaults() {\n\tif cb.stopCh == nil {\n\t\tcb.stopCh = wait.NeverStop\n\t}\n\n\tif cb.cmdName == \"\" {\n\t\tcb.cmdName = \"cloud-controller-manager\"\n\t}\n\n\tif cb.long == \"\" {\n\t\tcb.long = `The Cloud controller manager is a daemon that embeds the cloud specific control loops shipped with Kubernetes.`\n\t}\n\n\tif cb.defaults == nil {\n\t\tcb.defaults = \u0026options.ProviderDefaults{}\n\t}\n\n\tif cb.options == nil {\n\t\topts, err := options.NewCloudControllerManagerOptionsWithProviderDefaults(*cb.defaults)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"unable to initialize command options: %v\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tcb.options = opts\n\t}\n}","line":{"from":95,"to":120}} {"id":100029484,"name":"BuildCommand","signature":"func (cb *CommandBuilder) BuildCommand() *cobra.Command","file":"staging/src/k8s.io/cloud-provider/app/builder.go","code":"func (cb *CommandBuilder) BuildCommand() *cobra.Command {\n\tcb.setdefaults()\n\tcmd := \u0026cobra.Command{\n\t\tUse: cb.cmdName,\n\t\tLong: cb.long,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tverflag.PrintAndExitIfRequested()\n\t\t\tcliflag.PrintFlags(cmd.Flags())\n\n\t\t\tconfig, err := cb.options.Config(ControllerNames(cb.controllerInitFuncConstructors), ControllersDisabledByDefault.List(),\n\t\t\t\tWebhookNames(cb.webhookConfigs), WebhooksDisabledByDefault.List())\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcompletedConfig := config.Complete()\n\t\t\tcloud := cb.cloudInitializer(completedConfig)\n\t\t\tcontrollerInitializers := ConstructControllerInitializers(cb.controllerInitFuncConstructors, completedConfig, cloud)\n\t\t\twebhooks := NewWebhookHandlers(cb.webhookConfigs, completedConfig, cloud)\n\n\t\t\tif err := Run(completedConfig, cloud, controllerInitializers, webhooks, cb.stopCh); err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t\tArgs: func(cmd *cobra.Command, args []string) error {\n\t\t\tfor _, arg := range args {\n\t\t\t\tif len(arg) \u003e 0 {\n\t\t\t\t\treturn fmt.Errorf(\"%q does not take any arguments, got %q\", cmd.CommandPath(), args)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tfs := cmd.Flags()\n\tnamedFlagSets := cb.options.Flags(ControllerNames(cb.controllerInitFuncConstructors), ControllersDisabledByDefault.List(), WebhookNames(cb.webhookConfigs), WebhooksDisabledByDefault.List())\n\tverflag.AddFlags(namedFlagSets.FlagSet(\"global\"))\n\tglobalflag.AddGlobalFlags(namedFlagSets.FlagSet(\"global\"), cmd.Name())\n\n\tfor _, f := range namedFlagSets.FlagSets {\n\t\tfs.AddFlagSet(f)\n\t}\n\tfor _, f := range cb.additionalFlags.FlagSets {\n\t\tfs.AddFlagSet(f)\n\t}\n\n\tusageFmt := \"Usage:\\n %s\\n\"\n\tcols, _, _ := term.TerminalSize(cmd.OutOrStdout())\n\tcmd.SetUsageFunc(func(cmd *cobra.Command) error {\n\t\tfmt.Fprintf(cmd.OutOrStderr(), usageFmt, cmd.UseLine())\n\t\tcliflag.PrintSections(cmd.OutOrStderr(), namedFlagSets, cols)\n\t\treturn nil\n\t})\n\tcmd.SetHelpFunc(func(cmd *cobra.Command, args []string) {\n\t\tfmt.Fprintf(cmd.OutOrStdout(), \"%s\\n\\n\"+usageFmt, cmd.Long, cmd.UseLine())\n\t\tcliflag.PrintSections(cmd.OutOrStdout(), namedFlagSets, cols)\n\t})\n\n\treturn cmd\n}","line":{"from":122,"to":183}} {"id":100029485,"name":"Complete","signature":"func (c *Config) Complete() *CompletedConfig","file":"staging/src/k8s.io/cloud-provider/app/config/config.go","code":"// Complete fills in any fields not set that are required to have valid data. It's mutating the receiver.\nfunc (c *Config) Complete() *CompletedConfig {\n\tcc := completedConfig{c}\n\n\tapiserver.AuthorizeClientBearerToken(c.LoopbackClientConfig, \u0026c.Authentication, \u0026c.Authorization)\n\n\treturn \u0026CompletedConfig{\u0026cc}\n}","line":{"from":76,"to":83}} {"id":100029486,"name":"init","signature":"func init()","file":"staging/src/k8s.io/cloud-provider/app/controllermanager.go","code":"func init() {\n\tutilruntime.Must(features.AddFeatureGates(utilfeature.DefaultMutableFeatureGate))\n\tutilruntime.Must(logsapi.AddFeatureGates(utilfeature.DefaultMutableFeatureGate))\n}","line":{"from":68,"to":71}} {"id":100029487,"name":"NewCloudControllerManagerCommand","signature":"func NewCloudControllerManagerCommand(s *options.CloudControllerManagerOptions, cloudInitializer InitCloudFunc, controllerInitFuncConstructors map[string]ControllerInitFuncConstructor, additionalFlags cliflag.NamedFlagSets, stopCh \u003c-chan struct{}) *cobra.Command","file":"staging/src/k8s.io/cloud-provider/app/controllermanager.go","code":"// NewCloudControllerManagerCommand creates a *cobra.Command object with default parameters\n// controllerInitFuncConstructors is a map of controller name(as defined by controllers flag in https://kubernetes.io/docs/reference/command-line-tools-reference/kube-controller-manager/#options) to their InitFuncConstructor.\n// additionalFlags provides controller specific flags to be included in the complete set of controller manager flags\nfunc NewCloudControllerManagerCommand(s *options.CloudControllerManagerOptions, cloudInitializer InitCloudFunc, controllerInitFuncConstructors map[string]ControllerInitFuncConstructor, additionalFlags cliflag.NamedFlagSets, stopCh \u003c-chan struct{}) *cobra.Command {\n\tlogOptions := logs.NewOptions()\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"cloud-controller-manager\",\n\t\tLong: `The Cloud controller manager is a daemon that embeds\nthe cloud specific control loops shipped with Kubernetes.`,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tverflag.PrintAndExitIfRequested()\n\t\t\tcliflag.PrintFlags(cmd.Flags())\n\n\t\t\tif err := logsapi.ValidateAndApply(logOptions, utilfeature.DefaultFeatureGate); err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tc, err := s.Config(ControllerNames(controllerInitFuncConstructors), ControllersDisabledByDefault.List(), AllWebhooks, DisabledByDefaultWebhooks)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tcompletedConfig := c.Complete()\n\t\t\tcloud := cloudInitializer(completedConfig)\n\t\t\tcontrollerInitializers := ConstructControllerInitializers(controllerInitFuncConstructors, completedConfig, cloud)\n\n\t\t\tif err := Run(completedConfig, cloud, controllerInitializers, make(map[string]WebhookHandler), stopCh); err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t\tArgs: func(cmd *cobra.Command, args []string) error {\n\t\t\tfor _, arg := range args {\n\t\t\t\tif len(arg) \u003e 0 {\n\t\t\t\t\treturn fmt.Errorf(\"%q does not take any arguments, got %q\", cmd.CommandPath(), args)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tfs := cmd.Flags()\n\tnamedFlagSets := s.Flags(ControllerNames(controllerInitFuncConstructors), ControllersDisabledByDefault.List(), AllWebhooks, DisabledByDefaultWebhooks)\n\n\tglobalFlagSet := namedFlagSets.FlagSet(\"global\")\n\tverflag.AddFlags(globalFlagSet)\n\tlogsapi.AddFlags(logOptions, globalFlagSet)\n\tglobalflag.AddGlobalFlags(globalFlagSet, cmd.Name(), logs.SkipLoggingConfigurationFlags())\n\n\tif flag.CommandLine.Lookup(\"cloud-provider-gce-lb-src-cidrs\") != nil {\n\t\t// hoist this flag from the global flagset to preserve the commandline until\n\t\t// the gce cloudprovider is removed.\n\t\tglobalflag.Register(namedFlagSets.FlagSet(\"generic\"), \"cloud-provider-gce-lb-src-cidrs\")\n\t}\n\tif flag.CommandLine.Lookup(\"cloud-provider-gce-l7lb-src-cidrs\") != nil {\n\t\tglobalflag.Register(namedFlagSets.FlagSet(\"generic\"), \"cloud-provider-gce-l7lb-src-cidrs\")\n\t}\n\tfor _, f := range namedFlagSets.FlagSets {\n\t\tfs.AddFlagSet(f)\n\t}\n\tfor _, f := range additionalFlags.FlagSets {\n\t\tfs.AddFlagSet(f)\n\t}\n\n\tusageFmt := \"Usage:\\n %s\\n\"\n\tcols, _, _ := term.TerminalSize(cmd.OutOrStdout())\n\tcmd.SetUsageFunc(func(cmd *cobra.Command) error {\n\t\tfmt.Fprintf(cmd.OutOrStderr(), usageFmt, cmd.UseLine())\n\t\tcliflag.PrintSections(cmd.OutOrStderr(), namedFlagSets, cols)\n\t\treturn nil\n\t})\n\tcmd.SetHelpFunc(func(cmd *cobra.Command, args []string) {\n\t\tfmt.Fprintf(cmd.OutOrStdout(), \"%s\\n\\n\"+usageFmt, cmd.Long, cmd.UseLine())\n\t\tcliflag.PrintSections(cmd.OutOrStdout(), namedFlagSets, cols)\n\t})\n\n\treturn cmd\n}","line":{"from":80,"to":161}} {"id":100029488,"name":"Run","signature":"func Run(c *cloudcontrollerconfig.CompletedConfig, cloud cloudprovider.Interface, controllerInitializers map[string]InitFunc, webhooks map[string]WebhookHandler,","file":"staging/src/k8s.io/cloud-provider/app/controllermanager.go","code":"// Run runs the ExternalCMServer. This should never exit.\nfunc Run(c *cloudcontrollerconfig.CompletedConfig, cloud cloudprovider.Interface, controllerInitializers map[string]InitFunc, webhooks map[string]WebhookHandler,\n\tstopCh \u003c-chan struct{}) error {\n\t// To help debugging, immediately log version\n\tklog.Infof(\"Version: %+v\", version.Get())\n\n\t// Start events processing pipeline.\n\tc.EventBroadcaster.StartStructuredLogging(0)\n\tc.EventBroadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: c.Client.CoreV1().Events(\"\")})\n\tdefer c.EventBroadcaster.Shutdown()\n\n\t// setup /configz endpoint\n\tif cz, err := configz.New(ConfigzName); err == nil {\n\t\tcz.Set(c.ComponentConfig)\n\t} else {\n\t\tklog.Errorf(\"unable to register configz: %v\", err)\n\t}\n\n\t// Setup any health checks we will want to use.\n\tvar checks []healthz.HealthChecker\n\tvar electionChecker *leaderelection.HealthzAdaptor\n\tif c.ComponentConfig.Generic.LeaderElection.LeaderElect {\n\t\telectionChecker = leaderelection.NewLeaderHealthzAdaptor(time.Second * 20)\n\t\tchecks = append(checks, electionChecker)\n\t}\n\n\tif utilfeature.DefaultFeatureGate.Enabled(cmfeatures.CloudControllerManagerWebhook) {\n\t\tif len(webhooks) \u003e 0 {\n\t\t\tklog.Info(\"Webhook Handlers enabled: \", webhooks)\n\t\t\thandler := newHandler(webhooks)\n\t\t\tif _, _, err := c.WebhookSecureServing.Serve(handler, 0, stopCh); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\thealthzHandler := controllerhealthz.NewMutableHealthzHandler(checks...)\n\t// Start the controller manager HTTP server\n\tif c.SecureServing != nil {\n\t\tunsecuredMux := genericcontrollermanager.NewBaseHandler(\u0026c.ComponentConfig.Generic.Debugging, healthzHandler)\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.ComponentSLIs) {\n\t\t\tslis.SLIMetricsWithReset{}.Install(unsecuredMux)\n\t\t}\n\t\thandler := genericcontrollermanager.BuildHandlerChain(unsecuredMux, \u0026c.Authorization, \u0026c.Authentication)\n\t\t// TODO: handle stoppedCh and listenerStoppedCh returned by c.SecureServing.Serve\n\t\tif _, _, err := c.SecureServing.Serve(handler, 0, stopCh); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\trun := func(ctx context.Context, controllerInitializers map[string]InitFunc) {\n\t\tclientBuilder := clientbuilder.SimpleControllerClientBuilder{\n\t\t\tClientConfig: c.Kubeconfig,\n\t\t}\n\t\tcontrollerContext, err := CreateControllerContext(c, clientBuilder, ctx.Done())\n\t\tif err != nil {\n\t\t\tklog.Fatalf(\"error building controller context: %v\", err)\n\t\t}\n\t\tif err := startControllers(ctx, cloud, controllerContext, c, ctx.Done(), controllerInitializers, healthzHandler); err != nil {\n\t\t\tklog.Fatalf(\"error running controllers: %v\", err)\n\t\t}\n\t}\n\n\tif !c.ComponentConfig.Generic.LeaderElection.LeaderElect {\n\t\tctx := wait.ContextForChannel(stopCh)\n\t\trun(ctx, controllerInitializers)\n\t\t\u003c-stopCh\n\t\treturn nil\n\t}\n\n\t// Identity used to distinguish between multiple cloud controller manager instances\n\tid, err := os.Hostname()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// add a uniquifier so that two processes on the same host don't accidentally both become active\n\tid = id + \"_\" + string(uuid.NewUUID())\n\n\t// leaderMigrator will be non-nil if and only if Leader Migration is enabled.\n\tvar leaderMigrator *leadermigration.LeaderMigrator = nil\n\n\t// If leader migration is enabled, use the redirected initialization\n\t// Check feature gate and configuration separately so that any error in configuration checking will not\n\t// affect the result if the feature is not enabled.\n\tif leadermigration.Enabled(\u0026c.ComponentConfig.Generic) {\n\t\tklog.Info(\"starting leader migration\")\n\n\t\tleaderMigrator = leadermigration.NewLeaderMigrator(\u0026c.ComponentConfig.Generic.LeaderMigration,\n\t\t\t\"cloud-controller-manager\")\n\t}\n\n\t// Start the main lock\n\tgo leaderElectAndRun(c, id, electionChecker,\n\t\tc.ComponentConfig.Generic.LeaderElection.ResourceLock,\n\t\tc.ComponentConfig.Generic.LeaderElection.ResourceName,\n\t\tleaderelection.LeaderCallbacks{\n\t\t\tOnStartedLeading: func(ctx context.Context) {\n\t\t\t\tinitializers := controllerInitializers\n\t\t\t\tif leaderMigrator != nil {\n\t\t\t\t\t// If leader migration is enabled, we should start only non-migrated controllers\n\t\t\t\t\t// for the main lock.\n\t\t\t\t\tinitializers = filterInitializers(controllerInitializers, leaderMigrator.FilterFunc, leadermigration.ControllerNonMigrated)\n\t\t\t\t\tklog.Info(\"leader migration: starting main controllers.\")\n\t\t\t\t\t// Signal the main lock is acquired, and thus migration lock is ready to attempt.\n\t\t\t\t\tclose(leaderMigrator.MigrationReady)\n\t\t\t\t}\n\t\t\t\trun(ctx, initializers)\n\t\t\t},\n\t\t\tOnStoppedLeading: func() {\n\t\t\t\tklog.ErrorS(nil, \"leaderelection lost\")\n\t\t\t\tklog.FlushAndExit(klog.ExitFlushTimeout, 1)\n\t\t\t},\n\t\t})\n\n\t// If Leader Migration is enabled, proceed to attempt the migration lock.\n\tif leaderMigrator != nil {\n\t\t// Wait for the signal of main lock being acquired.\n\t\t\u003c-leaderMigrator.MigrationReady\n\n\t\t// Start the migration lock.\n\t\tgo leaderElectAndRun(c, id, electionChecker,\n\t\t\tc.ComponentConfig.Generic.LeaderMigration.ResourceLock,\n\t\t\tc.ComponentConfig.Generic.LeaderMigration.LeaderName,\n\t\t\tleaderelection.LeaderCallbacks{\n\t\t\t\tOnStartedLeading: func(ctx context.Context) {\n\t\t\t\t\tklog.Info(\"leader migration: starting migrated controllers.\")\n\t\t\t\t\trun(ctx, filterInitializers(controllerInitializers, leaderMigrator.FilterFunc, leadermigration.ControllerMigrated))\n\t\t\t\t},\n\t\t\t\tOnStoppedLeading: func() {\n\t\t\t\t\tklog.ErrorS(nil, \"migration leaderelection lost\")\n\t\t\t\t\tklog.FlushAndExit(klog.ExitFlushTimeout, 1)\n\t\t\t\t},\n\t\t\t})\n\t}\n\n\t\u003c-stopCh\n\treturn nil\n}","line":{"from":163,"to":300}} {"id":100029489,"name":"startControllers","signature":"func startControllers(ctx context.Context, cloud cloudprovider.Interface, controllerContext genericcontrollermanager.ControllerContext, c *cloudcontrollerconfig.CompletedConfig, stopCh \u003c-chan struct{}, controllers map[string]InitFunc, healthzHandler *controllerhealthz.MutableHealthzHandler) error","file":"staging/src/k8s.io/cloud-provider/app/controllermanager.go","code":"// startControllers starts the cloud specific controller loops.\nfunc startControllers(ctx context.Context, cloud cloudprovider.Interface, controllerContext genericcontrollermanager.ControllerContext, c *cloudcontrollerconfig.CompletedConfig, stopCh \u003c-chan struct{}, controllers map[string]InitFunc, healthzHandler *controllerhealthz.MutableHealthzHandler) error {\n\t// Initialize the cloud provider with a reference to the clientBuilder\n\tcloud.Initialize(c.ClientBuilder, stopCh)\n\t// Set the informer on the user cloud object\n\tif informerUserCloud, ok := cloud.(cloudprovider.InformerUser); ok {\n\t\tinformerUserCloud.SetInformers(c.SharedInformers)\n\t}\n\tvar controllerChecks []healthz.HealthChecker\n\tfor controllerName, initFn := range controllers {\n\t\tif !genericcontrollermanager.IsControllerEnabled(controllerName, ControllersDisabledByDefault, c.ComponentConfig.Generic.Controllers) {\n\t\t\tklog.Warningf(\"%q is disabled\", controllerName)\n\t\t\tcontinue\n\t\t}\n\n\t\tklog.V(1).Infof(\"Starting %q\", controllerName)\n\t\tctrl, started, err := initFn(ctx, controllerContext)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Error starting %q\", controllerName)\n\t\t\treturn err\n\t\t}\n\t\tif !started {\n\t\t\tklog.Warningf(\"Skipping %q\", controllerName)\n\t\t\tcontinue\n\t\t}\n\t\tcheck := controllerhealthz.NamedPingChecker(controllerName)\n\t\tif ctrl != nil {\n\t\t\tif healthCheckable, ok := ctrl.(controller.HealthCheckable); ok {\n\t\t\t\tif realCheck := healthCheckable.HealthChecker(); realCheck != nil {\n\t\t\t\t\tcheck = controllerhealthz.NamedHealthChecker(controllerName, realCheck)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcontrollerChecks = append(controllerChecks, check)\n\t\tklog.Infof(\"Started %q\", controllerName)\n\n\t\ttime.Sleep(wait.Jitter(c.ComponentConfig.Generic.ControllerStartInterval.Duration, ControllerStartJitter))\n\t}\n\n\thealthzHandler.AddHealthChecker(controllerChecks...)\n\n\t// If apiserver is not running we should wait for some time and fail only then. This is particularly\n\t// important when we start apiserver and controller manager at the same time.\n\tif err := genericcontrollermanager.WaitForAPIServer(c.VersionedClient, 10*time.Second); err != nil {\n\t\tklog.Fatalf(\"Failed to wait for apiserver being healthy: %v\", err)\n\t}\n\n\tc.SharedInformers.Start(stopCh)\n\tcontrollerContext.InformerFactory.Start(controllerContext.Stop)\n\n\t\u003c-stopCh\n\treturn nil\n}","line":{"from":302,"to":354}} {"id":100029490,"name":"ControllerNames","signature":"func ControllerNames(controllerInitFuncConstructors map[string]ControllerInitFuncConstructor) []string","file":"staging/src/k8s.io/cloud-provider/app/controllermanager.go","code":"// ControllerNames indicate the default controller we are known.\nfunc ControllerNames(controllerInitFuncConstructors map[string]ControllerInitFuncConstructor) []string {\n\tret := sets.StringKeySet(controllerInitFuncConstructors)\n\treturn ret.List()\n}","line":{"from":371,"to":375}} {"id":100029491,"name":"ConstructControllerInitializers","signature":"func ConstructControllerInitializers(controllerInitFuncConstructors map[string]ControllerInitFuncConstructor, completedConfig *cloudcontrollerconfig.CompletedConfig, cloud cloudprovider.Interface) map[string]InitFunc","file":"staging/src/k8s.io/cloud-provider/app/controllermanager.go","code":"// ConstructControllerInitializers is a map of controller name(as defined by controllers flag in https://kubernetes.io/docs/reference/command-line-tools-reference/kube-controller-manager/#options) to their InitFuncConstructor.\n// paired to their InitFunc. This allows for structured downstream composition and subdivision.\nfunc ConstructControllerInitializers(controllerInitFuncConstructors map[string]ControllerInitFuncConstructor, completedConfig *cloudcontrollerconfig.CompletedConfig, cloud cloudprovider.Interface) map[string]InitFunc {\n\tcontrollers := map[string]InitFunc{}\n\tfor name, constructor := range controllerInitFuncConstructors {\n\t\tcontrollers[name] = constructor.Constructor(constructor.InitContext, completedConfig, cloud)\n\t}\n\treturn controllers\n}","line":{"from":392,"to":400}} {"id":100029492,"name":"StartCloudNodeControllerWrapper","signature":"func StartCloudNodeControllerWrapper(initContext ControllerInitContext, completedConfig *cloudcontrollerconfig.CompletedConfig, cloud cloudprovider.Interface) InitFunc","file":"staging/src/k8s.io/cloud-provider/app/controllermanager.go","code":"// StartCloudNodeControllerWrapper is used to take cloud config as input and start cloud node controller\nfunc StartCloudNodeControllerWrapper(initContext ControllerInitContext, completedConfig *cloudcontrollerconfig.CompletedConfig, cloud cloudprovider.Interface) InitFunc {\n\treturn func(ctx context.Context, controllerContext genericcontrollermanager.ControllerContext) (controller.Interface, bool, error) {\n\t\treturn startCloudNodeController(ctx, initContext, controllerContext, completedConfig, cloud)\n\t}\n}","line":{"from":411,"to":416}} {"id":100029493,"name":"StartCloudNodeLifecycleControllerWrapper","signature":"func StartCloudNodeLifecycleControllerWrapper(initContext ControllerInitContext, completedConfig *cloudcontrollerconfig.CompletedConfig, cloud cloudprovider.Interface) InitFunc","file":"staging/src/k8s.io/cloud-provider/app/controllermanager.go","code":"// StartCloudNodeLifecycleControllerWrapper is used to take cloud config as input and start cloud node lifecycle controller\nfunc StartCloudNodeLifecycleControllerWrapper(initContext ControllerInitContext, completedConfig *cloudcontrollerconfig.CompletedConfig, cloud cloudprovider.Interface) InitFunc {\n\treturn func(ctx context.Context, controllerContext genericcontrollermanager.ControllerContext) (controller.Interface, bool, error) {\n\t\treturn startCloudNodeLifecycleController(ctx, initContext, controllerContext, completedConfig, cloud)\n\t}\n}","line":{"from":418,"to":423}} {"id":100029494,"name":"StartServiceControllerWrapper","signature":"func StartServiceControllerWrapper(initContext ControllerInitContext, completedConfig *cloudcontrollerconfig.CompletedConfig, cloud cloudprovider.Interface) InitFunc","file":"staging/src/k8s.io/cloud-provider/app/controllermanager.go","code":"// StartServiceControllerWrapper is used to take cloud config as input and start service controller\nfunc StartServiceControllerWrapper(initContext ControllerInitContext, completedConfig *cloudcontrollerconfig.CompletedConfig, cloud cloudprovider.Interface) InitFunc {\n\treturn func(ctx context.Context, controllerContext genericcontrollermanager.ControllerContext) (controller.Interface, bool, error) {\n\t\treturn startServiceController(ctx, initContext, controllerContext, completedConfig, cloud)\n\t}\n}","line":{"from":425,"to":430}} {"id":100029495,"name":"StartRouteControllerWrapper","signature":"func StartRouteControllerWrapper(initContext ControllerInitContext, completedConfig *cloudcontrollerconfig.CompletedConfig, cloud cloudprovider.Interface) InitFunc","file":"staging/src/k8s.io/cloud-provider/app/controllermanager.go","code":"// StartRouteControllerWrapper is used to take cloud config as input and start route controller\nfunc StartRouteControllerWrapper(initContext ControllerInitContext, completedConfig *cloudcontrollerconfig.CompletedConfig, cloud cloudprovider.Interface) InitFunc {\n\treturn func(ctx context.Context, controllerContext genericcontrollermanager.ControllerContext) (controller.Interface, bool, error) {\n\t\treturn startRouteController(ctx, initContext, controllerContext, completedConfig, cloud)\n\t}\n}","line":{"from":432,"to":437}} {"id":100029496,"name":"CreateControllerContext","signature":"func CreateControllerContext(s *cloudcontrollerconfig.CompletedConfig, clientBuilder clientbuilder.ControllerClientBuilder, stop \u003c-chan struct{}) (genericcontrollermanager.ControllerContext, error)","file":"staging/src/k8s.io/cloud-provider/app/controllermanager.go","code":"// CreateControllerContext creates a context struct containing references to resources needed by the\n// controllers such as the cloud provider and clientBuilder. rootClientBuilder is only used for\n// the shared-informers client and token controller.\nfunc CreateControllerContext(s *cloudcontrollerconfig.CompletedConfig, clientBuilder clientbuilder.ControllerClientBuilder, stop \u003c-chan struct{}) (genericcontrollermanager.ControllerContext, error) {\n\tversionedClient := clientBuilder.ClientOrDie(\"shared-informers\")\n\tsharedInformers := informers.NewSharedInformerFactory(versionedClient, ResyncPeriod(s)())\n\n\tmetadataClient := metadata.NewForConfigOrDie(clientBuilder.ConfigOrDie(\"metadata-informers\"))\n\tmetadataInformers := metadatainformer.NewSharedInformerFactory(metadataClient, ResyncPeriod(s)())\n\n\t// If apiserver is not running we should wait for some time and fail only then. This is particularly\n\t// important when we start apiserver and controller manager at the same time.\n\tif err := genericcontrollermanager.WaitForAPIServer(versionedClient, 10*time.Second); err != nil {\n\t\treturn genericcontrollermanager.ControllerContext{}, fmt.Errorf(\"failed to wait for apiserver being healthy: %v\", err)\n\t}\n\n\t// Use a discovery client capable of being refreshed.\n\tdiscoveryClient := clientBuilder.ClientOrDie(\"controller-discovery\")\n\tcachedClient := cacheddiscovery.NewMemCacheClient(discoveryClient.Discovery())\n\trestMapper := restmapper.NewDeferredDiscoveryRESTMapper(cachedClient)\n\tgo wait.Until(func() {\n\t\trestMapper.Reset()\n\t}, 30*time.Second, stop)\n\n\tavailableResources, err := GetAvailableResources(clientBuilder)\n\tif err != nil {\n\t\treturn genericcontrollermanager.ControllerContext{}, err\n\t}\n\n\tctx := genericcontrollermanager.ControllerContext{\n\t\tClientBuilder: clientBuilder,\n\t\tInformerFactory: sharedInformers,\n\t\tObjectOrMetadataInformerFactory: informerfactory.NewInformerFactory(sharedInformers, metadataInformers),\n\t\tRESTMapper: restMapper,\n\t\tAvailableResources: availableResources,\n\t\tStop: stop,\n\t\tInformersStarted: make(chan struct{}),\n\t\tResyncPeriod: ResyncPeriod(s),\n\t\tControllerManagerMetrics: controllersmetrics.NewControllerManagerMetrics(\"cloud-controller-manager\"),\n\t}\n\tcontrollersmetrics.Register()\n\treturn ctx, nil\n}","line":{"from":470,"to":512}} {"id":100029497,"name":"GetAvailableResources","signature":"func GetAvailableResources(clientBuilder clientbuilder.ControllerClientBuilder) (map[schema.GroupVersionResource]bool, error)","file":"staging/src/k8s.io/cloud-provider/app/controllermanager.go","code":"// GetAvailableResources gets the map which contains all available resources of the apiserver\n// TODO: In general, any controller checking this needs to be dynamic so\n// users don't have to restart their controller manager if they change the apiserver.\n// Until we get there, the structure here needs to be exposed for the construction of a proper ControllerContext.\nfunc GetAvailableResources(clientBuilder clientbuilder.ControllerClientBuilder) (map[schema.GroupVersionResource]bool, error) {\n\tclient := clientBuilder.ClientOrDie(\"controller-discovery\")\n\tdiscoveryClient := client.Discovery()\n\t_, resourceMap, err := discoveryClient.ServerGroupsAndResources()\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"unable to get all supported resources from server: %v\", err))\n\t}\n\tif len(resourceMap) == 0 {\n\t\treturn nil, fmt.Errorf(\"unable to get any supported resources from server\")\n\t}\n\n\tallResources := map[schema.GroupVersionResource]bool{}\n\tfor _, apiResourceList := range resourceMap {\n\t\tversion, err := schema.ParseGroupVersion(apiResourceList.GroupVersion)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, apiResource := range apiResourceList.APIResources {\n\t\t\tallResources[version.WithResource(apiResource.Name)] = true\n\t\t}\n\t}\n\n\treturn allResources, nil\n}","line":{"from":514,"to":541}} {"id":100029498,"name":"ResyncPeriod","signature":"func ResyncPeriod(c *cloudcontrollerconfig.CompletedConfig) func() time.Duration","file":"staging/src/k8s.io/cloud-provider/app/controllermanager.go","code":"// ResyncPeriod returns a function which generates a duration each time it is\n// invoked; this is so that multiple controllers don't get into lock-step and all\n// hammer the apiserver with list requests simultaneously.\nfunc ResyncPeriod(c *cloudcontrollerconfig.CompletedConfig) func() time.Duration {\n\treturn func() time.Duration {\n\t\tfactor := rand.Float64() + 1\n\t\treturn time.Duration(float64(c.ComponentConfig.Generic.MinResyncPeriod.Nanoseconds()) * factor)\n\t}\n}","line":{"from":543,"to":551}} {"id":100029499,"name":"leaderElectAndRun","signature":"func leaderElectAndRun(c *cloudcontrollerconfig.CompletedConfig, lockIdentity string, electionChecker *leaderelection.HealthzAdaptor, resourceLock string, leaseName string, callbacks leaderelection.LeaderCallbacks)","file":"staging/src/k8s.io/cloud-provider/app/controllermanager.go","code":"// leaderElectAndRun runs the leader election, and runs the callbacks once the leader lease is acquired.\n// TODO: extract this function into staging/controller-manager\nfunc leaderElectAndRun(c *cloudcontrollerconfig.CompletedConfig, lockIdentity string, electionChecker *leaderelection.HealthzAdaptor, resourceLock string, leaseName string, callbacks leaderelection.LeaderCallbacks) {\n\trl, err := resourcelock.NewFromKubeconfig(resourceLock,\n\t\tc.ComponentConfig.Generic.LeaderElection.ResourceNamespace,\n\t\tleaseName,\n\t\tresourcelock.ResourceLockConfig{\n\t\t\tIdentity: lockIdentity,\n\t\t\tEventRecorder: c.EventRecorder,\n\t\t},\n\t\tc.Kubeconfig,\n\t\tc.ComponentConfig.Generic.LeaderElection.RenewDeadline.Duration)\n\tif err != nil {\n\t\tklog.Fatalf(\"error creating lock: %v\", err)\n\t}\n\n\tleaderelection.RunOrDie(context.TODO(), leaderelection.LeaderElectionConfig{\n\t\tLock: rl,\n\t\tLeaseDuration: c.ComponentConfig.Generic.LeaderElection.LeaseDuration.Duration,\n\t\tRenewDeadline: c.ComponentConfig.Generic.LeaderElection.RenewDeadline.Duration,\n\t\tRetryPeriod: c.ComponentConfig.Generic.LeaderElection.RetryPeriod.Duration,\n\t\tCallbacks: callbacks,\n\t\tWatchDog: electionChecker,\n\t\tName: leaseName,\n\t})\n\n\tpanic(\"unreachable\")\n}","line":{"from":553,"to":580}} {"id":100029500,"name":"filterInitializers","signature":"func filterInitializers(allInitializers map[string]InitFunc, filterFunc leadermigration.FilterFunc, expected leadermigration.FilterResult) map[string]InitFunc","file":"staging/src/k8s.io/cloud-provider/app/controllermanager.go","code":"// filterInitializers returns initializers that has filterFunc(name) == expected.\n// filterFunc can be nil, in which case the original initializers will be returned directly.\n// InitFunc is local to cloud-controller-manager, and thus filterInitializers has to be local too.\nfunc filterInitializers(allInitializers map[string]InitFunc, filterFunc leadermigration.FilterFunc, expected leadermigration.FilterResult) map[string]InitFunc {\n\tif filterFunc == nil {\n\t\treturn allInitializers\n\t}\n\tinitializers := make(map[string]InitFunc)\n\tfor name, initFunc := range allInitializers {\n\t\tif filterFunc(name) == expected {\n\t\t\tinitializers[name] = initFunc\n\t\t}\n\t}\n\treturn initializers\n}","line":{"from":582,"to":596}} {"id":100029501,"name":"startCloudNodeController","signature":"func startCloudNodeController(ctx context.Context, initContext ControllerInitContext, controlexContext controllermanagerapp.ControllerContext, completedConfig *config.CompletedConfig, cloud cloudprovider.Interface) (controller.Interface, bool, error)","file":"staging/src/k8s.io/cloud-provider/app/core.go","code":"func startCloudNodeController(ctx context.Context, initContext ControllerInitContext, controlexContext controllermanagerapp.ControllerContext, completedConfig *config.CompletedConfig, cloud cloudprovider.Interface) (controller.Interface, bool, error) {\n\t// Start the CloudNodeController\n\tnodeController, err := cloudnodecontroller.NewCloudNodeController(\n\t\tcompletedConfig.SharedInformers.Core().V1().Nodes(),\n\t\t// cloud node controller uses existing cluster role from node-controller\n\t\tcompletedConfig.ClientBuilder.ClientOrDie(initContext.ClientName),\n\t\tcloud,\n\t\tcompletedConfig.ComponentConfig.NodeStatusUpdateFrequency.Duration,\n\t\tcompletedConfig.ComponentConfig.NodeController.ConcurrentNodeSyncs,\n\t)\n\tif err != nil {\n\t\tklog.Warningf(\"failed to start cloud node controller: %s\", err)\n\t\treturn nil, false, nil\n\t}\n\n\tgo nodeController.Run(ctx.Done(), controlexContext.ControllerManagerMetrics)\n\n\treturn nil, true, nil\n}","line":{"from":42,"to":60}} {"id":100029502,"name":"startCloudNodeLifecycleController","signature":"func startCloudNodeLifecycleController(ctx context.Context, initContext ControllerInitContext, controlexContext controllermanagerapp.ControllerContext, completedConfig *config.CompletedConfig, cloud cloudprovider.Interface) (controller.Interface, bool, error)","file":"staging/src/k8s.io/cloud-provider/app/core.go","code":"func startCloudNodeLifecycleController(ctx context.Context, initContext ControllerInitContext, controlexContext controllermanagerapp.ControllerContext, completedConfig *config.CompletedConfig, cloud cloudprovider.Interface) (controller.Interface, bool, error) {\n\t// Start the cloudNodeLifecycleController\n\tcloudNodeLifecycleController, err := cloudnodelifecyclecontroller.NewCloudNodeLifecycleController(\n\t\tcompletedConfig.SharedInformers.Core().V1().Nodes(),\n\t\t// cloud node lifecycle controller uses existing cluster role from node-controller\n\t\tcompletedConfig.ClientBuilder.ClientOrDie(initContext.ClientName),\n\t\tcloud,\n\t\tcompletedConfig.ComponentConfig.KubeCloudShared.NodeMonitorPeriod.Duration,\n\t)\n\tif err != nil {\n\t\tklog.Warningf(\"failed to start cloud node lifecycle controller: %s\", err)\n\t\treturn nil, false, nil\n\t}\n\n\tgo cloudNodeLifecycleController.Run(ctx, controlexContext.ControllerManagerMetrics)\n\n\treturn nil, true, nil\n}","line":{"from":62,"to":79}} {"id":100029503,"name":"startServiceController","signature":"func startServiceController(ctx context.Context, initContext ControllerInitContext, controlexContext controllermanagerapp.ControllerContext, completedConfig *config.CompletedConfig, cloud cloudprovider.Interface) (controller.Interface, bool, error)","file":"staging/src/k8s.io/cloud-provider/app/core.go","code":"func startServiceController(ctx context.Context, initContext ControllerInitContext, controlexContext controllermanagerapp.ControllerContext, completedConfig *config.CompletedConfig, cloud cloudprovider.Interface) (controller.Interface, bool, error) {\n\t// Start the service controller\n\tserviceController, err := servicecontroller.New(\n\t\tcloud,\n\t\tcompletedConfig.ClientBuilder.ClientOrDie(initContext.ClientName),\n\t\tcompletedConfig.SharedInformers.Core().V1().Services(),\n\t\tcompletedConfig.SharedInformers.Core().V1().Nodes(),\n\t\tcompletedConfig.ComponentConfig.KubeCloudShared.ClusterName,\n\t\tutilfeature.DefaultFeatureGate,\n\t)\n\tif err != nil {\n\t\t// This error shouldn't fail. It lives like this as a legacy.\n\t\tklog.Errorf(\"Failed to start service controller: %v\", err)\n\t\treturn nil, false, nil\n\t}\n\n\tgo serviceController.Run(ctx, int(completedConfig.ComponentConfig.ServiceController.ConcurrentServiceSyncs), controlexContext.ControllerManagerMetrics)\n\n\treturn nil, true, nil\n}","line":{"from":81,"to":100}} {"id":100029504,"name":"startRouteController","signature":"func startRouteController(ctx context.Context, initContext ControllerInitContext, controlexContext controllermanagerapp.ControllerContext, completedConfig *config.CompletedConfig, cloud cloudprovider.Interface) (controller.Interface, bool, error)","file":"staging/src/k8s.io/cloud-provider/app/core.go","code":"func startRouteController(ctx context.Context, initContext ControllerInitContext, controlexContext controllermanagerapp.ControllerContext, completedConfig *config.CompletedConfig, cloud cloudprovider.Interface) (controller.Interface, bool, error) {\n\tif !completedConfig.ComponentConfig.KubeCloudShared.ConfigureCloudRoutes {\n\t\tklog.Infof(\"Will not configure cloud provider routes, --configure-cloud-routes: %v\", completedConfig.ComponentConfig.KubeCloudShared.ConfigureCloudRoutes)\n\t\treturn nil, false, nil\n\t}\n\n\t// If CIDRs should be allocated for pods and set on the CloudProvider, then start the route controller\n\troutes, ok := cloud.Routes()\n\tif !ok {\n\t\tklog.Warning(\"--configure-cloud-routes is set, but cloud provider does not support routes. Will not configure cloud provider routes.\")\n\t\treturn nil, false, nil\n\t}\n\n\t// failure: bad cidrs in config\n\tclusterCIDRs, dualStack, err := processCIDRs(completedConfig.ComponentConfig.KubeCloudShared.ClusterCIDR)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\t// failure: more than one cidr but they are not configured as dual stack\n\tif len(clusterCIDRs) \u003e 1 \u0026\u0026 !dualStack {\n\t\treturn nil, false, fmt.Errorf(\"len of ClusterCIDRs==%v and they are not configured as dual stack (at least one from each IPFamily\", len(clusterCIDRs))\n\t}\n\n\t// failure: more than cidrs is not allowed even with dual stack\n\tif len(clusterCIDRs) \u003e 2 {\n\t\treturn nil, false, fmt.Errorf(\"length of clusterCIDRs is:%v more than max allowed of 2\", len(clusterCIDRs))\n\t}\n\n\trouteController := routecontroller.New(\n\t\troutes,\n\t\tcompletedConfig.ClientBuilder.ClientOrDie(initContext.ClientName),\n\t\tcompletedConfig.SharedInformers.Core().V1().Nodes(),\n\t\tcompletedConfig.ComponentConfig.KubeCloudShared.ClusterName,\n\t\tclusterCIDRs,\n\t)\n\tgo routeController.Run(ctx, completedConfig.ComponentConfig.KubeCloudShared.RouteReconciliationPeriod.Duration, controlexContext.ControllerManagerMetrics)\n\n\treturn nil, true, nil\n}","line":{"from":102,"to":141}} {"id":100029505,"name":"processCIDRs","signature":"func processCIDRs(cidrsList string) ([]*net.IPNet, bool, error)","file":"staging/src/k8s.io/cloud-provider/app/core.go","code":"// processCIDRs is a helper function that works on a comma separated cidrs and returns\n// a list of typed cidrs\n// a flag if cidrs represents a dual stack\n// error if failed to parse any of the cidrs\nfunc processCIDRs(cidrsList string) ([]*net.IPNet, bool, error) {\n\tcidrsSplit := strings.Split(strings.TrimSpace(cidrsList), \",\")\n\n\tcidrs, err := netutils.ParseCIDRs(cidrsSplit)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\t// if cidrs has an error then the previous call will fail\n\t// safe to ignore error checking on next call\n\tdualstack, _ := netutils.IsDualStackCIDRs(cidrs)\n\n\treturn cidrs, dualstack, nil\n}","line":{"from":143,"to":160}} {"id":100029506,"name":"init","signature":"func init()","file":"staging/src/k8s.io/cloud-provider/app/webhook_metrics.go","code":"// init registers all metrics\nfunc init() {\n\tfor _, metric := range toRegister {\n\t\tlegacyregistry.MustRegister(metric)\n\t}\n}","line":{"from":33,"to":38}} {"id":100029507,"name":"recordRequestTotal","signature":"func recordRequestTotal(ctx context.Context, code string, webhookName string)","file":"staging/src/k8s.io/cloud-provider/app/webhook_metrics.go","code":"// RecordRequestTotal increments the total number of requests for the webhook.\nfunc recordRequestTotal(ctx context.Context, code string, webhookName string) {\n\trequestTotal.WithContext(ctx).With(map[string]string{\"code\": code, \"webhook\": webhookName}).Add(1)\n}","line":{"from":68,"to":71}} {"id":100029508,"name":"recordRequestLatency","signature":"func recordRequestLatency(ctx context.Context, code string, webhookName string, latency float64)","file":"staging/src/k8s.io/cloud-provider/app/webhook_metrics.go","code":"// RecordRequestLatency measures request latency in seconds for the delegated authorization. Broken down by status code.\nfunc recordRequestLatency(ctx context.Context, code string, webhookName string, latency float64) {\n\trequestLatency.WithContext(ctx).With(map[string]string{\"code\": code, \"webhook\": webhookName}).Observe(latency)\n}","line":{"from":73,"to":76}} {"id":100029509,"name":"init","signature":"func init()","file":"staging/src/k8s.io/cloud-provider/app/webhooks.go","code":"func init() {\n\t_ = corev1.AddToScheme(runtimeScheme)\n\t_ = admissionv1.AddToScheme(runtimeScheme)\n\tserializerInfo, _ := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), runtime.ContentTypeJSON)\n\tencoder = serializerInfo.Serializer\n}","line":{"from":46,"to":51}} {"id":100029510,"name":"NewWebhookHandlers","signature":"func NewWebhookHandlers(webhookConfigs map[string]WebhookConfig, completedConfig *config.CompletedConfig, cloud cloudprovider.Interface) map[string]WebhookHandler","file":"staging/src/k8s.io/cloud-provider/app/webhooks.go","code":"func NewWebhookHandlers(webhookConfigs map[string]WebhookConfig, completedConfig *config.CompletedConfig, cloud cloudprovider.Interface) map[string]WebhookHandler {\n\twebhookHandlers := make(map[string]WebhookHandler)\n\tfor name, config := range webhookConfigs {\n\t\tif !genericcontrollermanager.IsControllerEnabled(name, WebhooksDisabledByDefault, completedConfig.ComponentConfig.Webhook.Webhooks) {\n\t\t\tklog.Warningf(\"Webhook %q is disabled\", name)\n\t\t\tcontinue\n\t\t}\n\t\tklog.Infof(\"Webhook enabled: %q\", name)\n\t\twebhookHandlers[name] = WebhookHandler{\n\t\t\tName: name,\n\t\t\tPath: config.Path,\n\t\t\tAdmissionHandler: config.AdmissionHandler,\n\t\t\tCompletedConfig: completedConfig,\n\t\t\tCloud: cloud,\n\t\t}\n\t}\n\treturn webhookHandlers\n}","line":{"from":70,"to":87}} {"id":100029511,"name":"WebhookNames","signature":"func WebhookNames(webhooks map[string]WebhookConfig) []string","file":"staging/src/k8s.io/cloud-provider/app/webhooks.go","code":"func WebhookNames(webhooks map[string]WebhookConfig) []string {\n\tret := sets.StringKeySet(webhooks)\n\treturn ret.List()\n}","line":{"from":89,"to":92}} {"id":100029512,"name":"newHandler","signature":"func newHandler(webhooks map[string]WebhookHandler) *mux.PathRecorderMux","file":"staging/src/k8s.io/cloud-provider/app/webhooks.go","code":"func newHandler(webhooks map[string]WebhookHandler) *mux.PathRecorderMux {\n\tmux := mux.NewPathRecorderMux(\"controller-manager-webhook\")\n\n\tfor _, handler := range webhooks {\n\t\tmux.Handle(handler.Path, handler)\n\t}\n\n\treturn mux\n}","line":{"from":94,"to":102}} {"id":100029513,"name":"ServeHTTP","signature":"func (h WebhookHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)","file":"staging/src/k8s.io/cloud-provider/app/webhooks.go","code":"func (h WebhookHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tctx := context.Background()\n\tklog.Infof(\"Received validation request: %q\", r.RequestURI)\n\n\tstart := time.Now()\n\tvar (\n\t\tstatusCode int\n\t\terr error\n\t\tin *admissionv1.AdmissionReview\n\t\tadmissionResponse *admissionv1.AdmissionResponse\n\t)\n\tdefer func() {\n\t\tlatency := time.Since(start)\n\n\t\tif statusCode != 0 {\n\t\t\trecordRequestTotal(ctx, strconv.Itoa(statusCode), h.Name)\n\t\t\trecordRequestLatency(ctx, strconv.Itoa(statusCode), h.Name, latency.Seconds())\n\t\t\treturn\n\t\t}\n\n\t\tif err != nil {\n\t\t\trecordRequestTotal(ctx, \"\u003cerror\u003e\", h.Name)\n\t\t\trecordRequestLatency(ctx, \"\u003cerror\u003e\", h.Name, latency.Seconds())\n\t\t}\n\t}()\n\n\tin, err = parseRequest(r)\n\tif err != nil {\n\t\tklog.Error(err)\n\t\tstatusCode = http.StatusBadRequest\n\t\thttp.Error(w, err.Error(), statusCode)\n\t\treturn\n\t}\n\n\tadmissionResponse, err = h.AdmissionHandler(in.Request)\n\tif err != nil {\n\t\te := fmt.Sprintf(\"error generating admission response: %v\", err)\n\t\tklog.Errorf(e)\n\t\tstatusCode = http.StatusInternalServerError\n\t\thttp.Error(w, e, statusCode)\n\t\treturn\n\t} else if admissionResponse == nil {\n\t\te := fmt.Sprintf(\"admission response cannot be nil\")\n\t\tklog.Error(e)\n\t\tstatusCode = http.StatusInternalServerError\n\t\thttp.Error(w, e, statusCode)\n\t\treturn\n\t}\n\n\tadmissionReview := \u0026admissionv1.AdmissionReview{\n\t\tResponse: admissionResponse,\n\t}\n\tadmissionReview.Response.UID = in.Request.UID\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tcodec := codecs.EncoderForVersion(encoder, admissionv1.SchemeGroupVersion)\n\tout, err := runtime.Encode(codec, admissionReview)\n\tif err != nil {\n\t\te := fmt.Sprintf(\"error parsing admission response: %v\", err)\n\t\tklog.Error(e)\n\t\tstatusCode = http.StatusInternalServerError\n\t\thttp.Error(w, e, statusCode)\n\t\treturn\n\t}\n\n\tklog.Infof(\"%s\", out)\n\tfmt.Fprintf(w, \"%s\", out)\n}","line":{"from":104,"to":171}} {"id":100029514,"name":"parseRequest","signature":"func parseRequest(r *http.Request) (*admissionv1.AdmissionReview, error)","file":"staging/src/k8s.io/cloud-provider/app/webhooks.go","code":"// parseRequest extracts an AdmissionReview from an http.Request if possible\nfunc parseRequest(r *http.Request) (*admissionv1.AdmissionReview, error) {\n\n\treview := \u0026admissionv1.AdmissionReview{}\n\n\tif r.Header.Get(\"Content-Type\") != \"application/json\" {\n\t\treturn nil, fmt.Errorf(\"Content-Type: %q should be %q\",\n\t\t\tr.Header.Get(\"Content-Type\"), \"application/json\")\n\t}\n\n\tbodybuf := new(bytes.Buffer)\n\tbodybuf.ReadFrom(r.Body)\n\tbody := bodybuf.Bytes()\n\n\tif len(body) == 0 {\n\t\treturn nil, fmt.Errorf(\"admission request HTTP body is empty\")\n\t}\n\n\tif _, _, err := deserializer.Decode(body, nil, review); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not deserialize incoming admission review: %v\", err)\n\t}\n\n\tif review.Request == nil {\n\t\treturn nil, fmt.Errorf(\"admission review can't be used: Request field is nil\")\n\t}\n\n\treturn review, nil\n}","line":{"from":173,"to":200}} {"id":100029515,"name":"DefaultLoadBalancerName","signature":"func DefaultLoadBalancerName(service *v1.Service) string","file":"staging/src/k8s.io/cloud-provider/cloud.go","code":"// (DEPRECATED) DefaultLoadBalancerName is the default load balancer name that is called from\n// LoadBalancer.GetLoadBalancerName. Use this method to maintain backward compatible names for\n// LoadBalancers that were created prior to Kubernetes v1.12. In the future, each provider should\n// replace this method call in GetLoadBalancerName with a provider-specific implementation that\n// is less cryptic than the Service's UUID.\nfunc DefaultLoadBalancerName(service *v1.Service) string {\n\t//GCE requires that the name of a load balancer starts with a lower case letter.\n\tret := \"a\" + string(service.UID)\n\tret = strings.Replace(ret, \"-\", \"\", -1)\n\t//AWS requires that the name of a load balancer is shorter than 32 bytes.\n\tif len(ret) \u003e 32 {\n\t\tret = ret[:32]\n\t}\n\treturn ret\n}","line":{"from":84,"to":98}} {"id":100029516,"name":"GetInstanceProviderID","signature":"func GetInstanceProviderID(ctx context.Context, cloud Interface, nodeName types.NodeName) (string, error)","file":"staging/src/k8s.io/cloud-provider/cloud.go","code":"// GetInstanceProviderID builds a ProviderID for a node in a cloud.\nfunc GetInstanceProviderID(ctx context.Context, cloud Interface, nodeName types.NodeName) (string, error) {\n\tinstances, ok := cloud.Instances()\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"failed to get instances from cloud provider\")\n\t}\n\tinstanceID, err := instances.InstanceID(ctx, nodeName)\n\tif err != nil {\n\t\tif err == NotImplemented {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\treturn \"\", fmt.Errorf(\"failed to get instance ID from cloud provider: %v\", err)\n\t}\n\treturn cloud.ProviderName() + \"://\" + instanceID, nil\n}","line":{"from":100,"to":115}} {"id":100029517,"name":"init","signature":"func init()","file":"staging/src/k8s.io/cloud-provider/config/install/install.go","code":"func init() {\n\tInstall(Scheme)\n}","line":{"from":35,"to":37}} {"id":100029518,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"staging/src/k8s.io/cloud-provider/config/install/install.go","code":"// Install adds the types of this group into the given scheme.\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(config.AddToScheme(scheme))\n\tutilruntime.Must(v1alpha1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1alpha1.SchemeGroupVersion))\n}","line":{"from":39,"to":44}} {"id":100029519,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/cloud-provider/config/register.go","code":"// addKnownTypes registers known types to the given scheme\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026CloudControllerManagerConfiguration{},\n\t)\n\treturn nil\n}","line":{"from":36,"to":42}} {"id":100029520,"name":"Convert_v1alpha1_KubeCloudSharedConfiguration_To_config_KubeCloudSharedConfiguration","signature":"func Convert_v1alpha1_KubeCloudSharedConfiguration_To_config_KubeCloudSharedConfiguration(in *KubeCloudSharedConfiguration, out *cpconfig.KubeCloudSharedConfiguration, s conversion.Scope) error","file":"staging/src/k8s.io/cloud-provider/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_KubeCloudSharedConfiguration_To_config_KubeCloudSharedConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_KubeCloudSharedConfiguration_To_config_KubeCloudSharedConfiguration(in *KubeCloudSharedConfiguration, out *cpconfig.KubeCloudSharedConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_KubeCloudSharedConfiguration_To_config_KubeCloudSharedConfiguration(in, out, s)\n}","line":{"from":31,"to":34}} {"id":100029521,"name":"Convert_config_KubeCloudSharedConfiguration_To_v1alpha1_KubeCloudSharedConfiguration","signature":"func Convert_config_KubeCloudSharedConfiguration_To_v1alpha1_KubeCloudSharedConfiguration(in *cpconfig.KubeCloudSharedConfiguration, out *KubeCloudSharedConfiguration, s conversion.Scope) error","file":"staging/src/k8s.io/cloud-provider/config/v1alpha1/conversion.go","code":"// Convert_config_KubeCloudSharedConfiguration_To_v1alpha1_KubeCloudSharedConfiguration is an autogenerated conversion function.\nfunc Convert_config_KubeCloudSharedConfiguration_To_v1alpha1_KubeCloudSharedConfiguration(in *cpconfig.KubeCloudSharedConfiguration, out *KubeCloudSharedConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_KubeCloudSharedConfiguration_To_v1alpha1_KubeCloudSharedConfiguration(in, out, s)\n}","line":{"from":36,"to":39}} {"id":100029522,"name":"Convert_v1alpha1_CloudProviderConfiguration_To_config_CloudProviderConfiguration","signature":"func Convert_v1alpha1_CloudProviderConfiguration_To_config_CloudProviderConfiguration(in *CloudProviderConfiguration, out *cpconfig.CloudProviderConfiguration, s conversion.Scope) error","file":"staging/src/k8s.io/cloud-provider/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_CloudProviderConfiguration_To_config_CloudProviderConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_CloudProviderConfiguration_To_config_CloudProviderConfiguration(in *CloudProviderConfiguration, out *cpconfig.CloudProviderConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_CloudProviderConfiguration_To_config_CloudProviderConfiguration(in, out, s)\n}","line":{"from":41,"to":44}} {"id":100029523,"name":"Convert_config_CloudProviderConfiguration_To_v1alpha1_CloudProviderConfiguration","signature":"func Convert_config_CloudProviderConfiguration_To_v1alpha1_CloudProviderConfiguration(in *cpconfig.CloudProviderConfiguration, out *CloudProviderConfiguration, s conversion.Scope) error","file":"staging/src/k8s.io/cloud-provider/config/v1alpha1/conversion.go","code":"// Convert_config_CloudProviderConfiguration_To_v1alpha1_CloudProviderConfiguration is an autogenerated conversion function.\nfunc Convert_config_CloudProviderConfiguration_To_v1alpha1_CloudProviderConfiguration(in *cpconfig.CloudProviderConfiguration, out *CloudProviderConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_CloudProviderConfiguration_To_v1alpha1_CloudProviderConfiguration(in, out, s)\n}","line":{"from":46,"to":49}} {"id":100029524,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/cloud-provider/config/v1alpha1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":30,"to":32}} {"id":100029525,"name":"SetDefaults_CloudControllerManagerConfiguration","signature":"func SetDefaults_CloudControllerManagerConfiguration(obj *CloudControllerManagerConfiguration)","file":"staging/src/k8s.io/cloud-provider/config/v1alpha1/defaults.go","code":"func SetDefaults_CloudControllerManagerConfiguration(obj *CloudControllerManagerConfiguration) {\n\tzero := metav1.Duration{}\n\tif obj.NodeStatusUpdateFrequency == zero {\n\t\tobj.NodeStatusUpdateFrequency = metav1.Duration{Duration: 5 * time.Minute}\n\t}\n\n\t// These defaults override the recommended defaults from the apimachineryconfigv1alpha1 package that are applied automatically\n\t// These client-connection defaults are specific to the cloud-controller-manager\n\tif obj.Generic.ClientConnection.QPS == 0 {\n\t\tobj.Generic.ClientConnection.QPS = 20\n\t}\n\tif obj.Generic.ClientConnection.Burst == 0 {\n\t\tobj.Generic.ClientConnection.Burst = 30\n\t}\n\n\t// Use the default RecommendedDefaultGenericControllerManagerConfiguration options\n\tcmconfigv1alpha1.RecommendedDefaultGenericControllerManagerConfiguration(\u0026obj.Generic)\n\t// Use the default RecommendedDefaultServiceControllerConfiguration options\n\tserviceconfigv1alpha1.RecommendedDefaultServiceControllerConfiguration(\u0026obj.ServiceController)\n\t// Use the default RecommendedDefaultNodeControllerConfiguration options\n\tnodeconfigv1alpha1.RecommendedDefaultNodeControllerConfiguration(\u0026obj.NodeController)\n}","line":{"from":34,"to":55}} {"id":100029526,"name":"SetDefaults_KubeCloudSharedConfiguration","signature":"func SetDefaults_KubeCloudSharedConfiguration(obj *KubeCloudSharedConfiguration)","file":"staging/src/k8s.io/cloud-provider/config/v1alpha1/defaults.go","code":"func SetDefaults_KubeCloudSharedConfiguration(obj *KubeCloudSharedConfiguration) {\n\tzero := metav1.Duration{}\n\tif obj.NodeMonitorPeriod == zero {\n\t\tobj.NodeMonitorPeriod = metav1.Duration{Duration: 5 * time.Second}\n\t}\n\tif obj.ClusterName == \"\" {\n\t\tobj.ClusterName = \"kubernetes\"\n\t}\n\tif obj.ConfigureCloudRoutes == nil {\n\t\tobj.ConfigureCloudRoutes = utilpointer.BoolPtr(true)\n\t}\n\tif obj.RouteReconciliationPeriod == zero {\n\t\tobj.RouteReconciliationPeriod = metav1.Duration{Duration: 10 * time.Second}\n\t}\n}","line":{"from":57,"to":71}} {"id":100029527,"name":"init","signature":"func init()","file":"staging/src/k8s.io/cloud-provider/config/v1alpha1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addDefaultingFuncs)\n}","line":{"from":39,"to":44}} {"id":100029528,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/cloud-provider/config/v1alpha1/register.go","code":"// addKnownTypes registers known types to the given scheme\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026CloudControllerManagerConfiguration{},\n\t)\n\treturn nil\n}","line":{"from":46,"to":52}} {"id":100029529,"name":"Convert_config_NodeControllerConfiguration_To_v1alpha1_NodeControllerConfiguration","signature":"func Convert_config_NodeControllerConfiguration_To_v1alpha1_NodeControllerConfiguration(in *config.NodeControllerConfiguration, out *NodeControllerConfiguration, s conversion.Scope) error","file":"staging/src/k8s.io/cloud-provider/controllers/node/config/v1alpha1/conversion.go","code":"// Convert_config_NodeControllerConfiguration_To_v1alpha1_NodeControllerConfiguration is an autogenerated conversion function.\nfunc Convert_config_NodeControllerConfiguration_To_v1alpha1_NodeControllerConfiguration(in *config.NodeControllerConfiguration, out *NodeControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_NodeControllerConfiguration_To_v1alpha1_NodeControllerConfiguration(in, out, s)\n}","line":{"from":31,"to":34}} {"id":100029530,"name":"Convert_v1alpha1_NodeControllerConfiguration_To_config_NodeControllerConfiguration","signature":"func Convert_v1alpha1_NodeControllerConfiguration_To_config_NodeControllerConfiguration(in *NodeControllerConfiguration, out *config.NodeControllerConfiguration, s conversion.Scope) error","file":"staging/src/k8s.io/cloud-provider/controllers/node/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_NodeControllerConfiguration_To_config_NodeControllerConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_NodeControllerConfiguration_To_config_NodeControllerConfiguration(in *NodeControllerConfiguration, out *config.NodeControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_NodeControllerConfiguration_To_config_NodeControllerConfiguration(in, out, s)\n}","line":{"from":36,"to":39}} {"id":100029531,"name":"RecommendedDefaultNodeControllerConfiguration","signature":"func RecommendedDefaultNodeControllerConfiguration(obj *NodeControllerConfiguration)","file":"staging/src/k8s.io/cloud-provider/controllers/node/config/v1alpha1/defaults.go","code":"func RecommendedDefaultNodeControllerConfiguration(obj *NodeControllerConfiguration) {\n\tif obj.ConcurrentNodeSyncs == 0 {\n\t\tobj.ConcurrentNodeSyncs = 1\n\t}\n}","line":{"from":19,"to":23}} {"id":100029532,"name":"NewCloudNodeController","signature":"func NewCloudNodeController(","file":"staging/src/k8s.io/cloud-provider/controllers/node/node_controller.go","code":"// NewCloudNodeController creates a CloudNodeController object\nfunc NewCloudNodeController(\n\tnodeInformer coreinformers.NodeInformer,\n\tkubeClient clientset.Interface,\n\tcloud cloudprovider.Interface,\n\tnodeStatusUpdateFrequency time.Duration,\n\tworkerCount int32) (*CloudNodeController, error) {\n\n\teventBroadcaster := record.NewBroadcaster()\n\trecorder := eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"cloud-node-controller\"})\n\n\t_, instancesSupported := cloud.Instances()\n\t_, instancesV2Supported := cloud.InstancesV2()\n\tif !instancesSupported \u0026\u0026 !instancesV2Supported {\n\t\treturn nil, errors.New(\"cloud provider does not support instances\")\n\t}\n\n\tcnc := \u0026CloudNodeController{\n\t\tnodeInformer: nodeInformer,\n\t\tkubeClient: kubeClient,\n\t\tbroadcaster: eventBroadcaster,\n\t\trecorder: recorder,\n\t\tcloud: cloud,\n\t\tnodeStatusUpdateFrequency: nodeStatusUpdateFrequency,\n\t\tworkerCount: workerCount,\n\t\tnodesLister: nodeInformer.Lister(),\n\t\tnodesSynced: nodeInformer.Informer().HasSynced,\n\t\tworkqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"Nodes\"),\n\t}\n\n\t// Use shared informer to listen to add/update of nodes. Note that any nodes\n\t// that exist before node controller starts will show up in the update method\n\tcnc.nodeInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: cnc.enqueueNode,\n\t\tUpdateFunc: func(oldObj, newObj interface{}) { cnc.enqueueNode(newObj) },\n\t})\n\n\treturn cnc, nil\n}","line":{"from":112,"to":150}} {"id":100029533,"name":"Run","signature":"func (cnc *CloudNodeController) Run(stopCh \u003c-chan struct{}, controllerManagerMetrics *controllersmetrics.ControllerManagerMetrics)","file":"staging/src/k8s.io/cloud-provider/controllers/node/node_controller.go","code":"// Run will sync informer caches and starting workers.\n// This controller updates newly registered nodes with information\n// from the cloud provider. This call is blocking so should be called\n// via a goroutine\nfunc (cnc *CloudNodeController) Run(stopCh \u003c-chan struct{}, controllerManagerMetrics *controllersmetrics.ControllerManagerMetrics) {\n\tdefer utilruntime.HandleCrash()\n\tdefer cnc.workqueue.ShutDown()\n\n\t// Start event processing pipeline.\n\tklog.Infof(\"Sending events to api server.\")\n\tcontrollerManagerMetrics.ControllerStarted(\"cloud-node\")\n\tdefer controllerManagerMetrics.ControllerStopped(\"cloud-node\")\n\n\tcnc.broadcaster.StartStructuredLogging(0)\n\tcnc.broadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: cnc.kubeClient.CoreV1().Events(\"\")})\n\tdefer cnc.broadcaster.Shutdown()\n\n\t// Wait for the caches to be synced before starting workers\n\tklog.Info(\"Waiting for informer caches to sync\")\n\tif ok := cache.WaitForCacheSync(stopCh, cnc.nodesSynced); !ok {\n\t\tklog.Errorf(\"failed to wait for caches to sync\")\n\t\treturn\n\t}\n\n\t// The periodic loop for updateNodeStatus polls the Cloud Provider periodically\n\t// to reconcile the nodes addresses and labels.\n\tgo wait.Until(func() {\n\t\tif err := cnc.UpdateNodeStatus(context.TODO()); err != nil {\n\t\t\tklog.Errorf(\"failed to update node status: %v\", err)\n\t\t}\n\t}, cnc.nodeStatusUpdateFrequency, stopCh)\n\n\t// These workers initialize the nodes added to the cluster,\n\t// those that are Tainted with TaintExternalCloudProvider.\n\tfor i := int32(0); i \u003c cnc.workerCount; i++ {\n\t\tgo wait.Until(cnc.runWorker, time.Second, stopCh)\n\t}\n\n\t\u003c-stopCh\n}","line":{"from":152,"to":191}} {"id":100029534,"name":"runWorker","signature":"func (cnc *CloudNodeController) runWorker()","file":"staging/src/k8s.io/cloud-provider/controllers/node/node_controller.go","code":"// runWorker is a long-running function that will continually call the\n// processNextWorkItem function in order to read and process a message on the\n// workqueue.\nfunc (cnc *CloudNodeController) runWorker() {\n\tfor cnc.processNextWorkItem() {\n\t}\n}","line":{"from":193,"to":199}} {"id":100029535,"name":"processNextWorkItem","signature":"func (cnc *CloudNodeController) processNextWorkItem() bool","file":"staging/src/k8s.io/cloud-provider/controllers/node/node_controller.go","code":"// processNextWorkItem will read a single work item off the workqueue and\n// attempt to process it, by calling the syncHandler.\nfunc (cnc *CloudNodeController) processNextWorkItem() bool {\n\tobj, shutdown := cnc.workqueue.Get()\n\tif shutdown {\n\t\treturn false\n\t}\n\n\t// We wrap this block in a func so we can defer cnc.workqueue.Done.\n\terr := func(obj interface{}) error {\n\t\tdefer cnc.workqueue.Done(obj)\n\n\t\tvar key string\n\t\tvar ok bool\n\t\tif key, ok = obj.(string); !ok {\n\t\t\tcnc.workqueue.Forget(obj)\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"expected string in workqueue but got %#v\", obj))\n\t\t\treturn nil\n\t\t}\n\n\t\t// Run the syncHandler, passing it the key of the\n\t\t// Node resource to be synced.\n\t\tif err := cnc.syncHandler(key); err != nil {\n\t\t\t// Put the item back on the workqueue to handle any transient errors.\n\t\t\tcnc.workqueue.AddRateLimited(key)\n\t\t\treturn fmt.Errorf(\"error syncing '%s': %s, requeuing\", key, err.Error())\n\t\t}\n\n\t\t// Finally, if no error occurs we Forget this item so it does not\n\t\t// get queued again until another change happens.\n\t\tcnc.workqueue.Forget(obj)\n\t\treturn nil\n\t}(obj)\n\n\tif err != nil {\n\t\tutilruntime.HandleError(err)\n\t\treturn true\n\t}\n\n\treturn true\n}","line":{"from":201,"to":241}} {"id":100029536,"name":"syncHandler","signature":"func (cnc *CloudNodeController) syncHandler(key string) error","file":"staging/src/k8s.io/cloud-provider/controllers/node/node_controller.go","code":"// syncHandler implements the logic of the controller.\nfunc (cnc *CloudNodeController) syncHandler(key string) error {\n\t_, name, err := cache.SplitMetaNamespaceKey(key)\n\tif err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"invalid resource key: %s\", key))\n\t\treturn nil\n\t}\n\n\treturn cnc.syncNode(context.TODO(), name)\n}","line":{"from":243,"to":252}} {"id":100029537,"name":"UpdateNodeStatus","signature":"func (cnc *CloudNodeController) UpdateNodeStatus(ctx context.Context) error","file":"staging/src/k8s.io/cloud-provider/controllers/node/node_controller.go","code":"// UpdateNodeStatus updates the node status, such as node addresses\nfunc (cnc *CloudNodeController) UpdateNodeStatus(ctx context.Context) error {\n\tstart := time.Now()\n\tnodes, err := cnc.nodesLister.List(labels.Everything())\n\tif err != nil {\n\t\tklog.Errorf(\"Error monitoring node status: %v\", err)\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tklog.V(2).Infof(\"Update %d nodes status took %v.\", len(nodes), time.Since(start))\n\t}()\n\n\tupdateNodeFunc := func(piece int) {\n\t\tnode := nodes[piece].DeepCopy()\n\t\t// Do not process nodes that are still tainted, those will be processed by syncNode()\n\t\tcloudTaint := getCloudTaint(node.Spec.Taints)\n\t\tif cloudTaint != nil {\n\t\t\tklog.V(5).Infof(\"This node %s is still tainted. Will not process.\", node.Name)\n\t\t\treturn\n\t\t}\n\n\t\tinstanceMetadata, err := cnc.getInstanceNodeAddresses(ctx, node)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Error getting instance metadata for node addresses: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\tcnc.updateNodeAddress(ctx, node, instanceMetadata)\n\n\t\terr = cnc.reconcileNodeLabels(node.Name)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Error reconciling node labels for node %q, err: %v\", node.Name, err)\n\t\t}\n\t}\n\n\tworkqueue.ParallelizeUntil(ctx, int(cnc.workerCount), len(nodes), updateNodeFunc)\n\treturn nil\n}","line":{"from":254,"to":291}} {"id":100029538,"name":"enqueueNode","signature":"func (cnc *CloudNodeController) enqueueNode(obj interface{})","file":"staging/src/k8s.io/cloud-provider/controllers/node/node_controller.go","code":"// enqueueNode takes a Node resource and converts it into a key\n// string which is then put onto the work queue.\nfunc (cnc *CloudNodeController) enqueueNode(obj interface{}) {\n\tvar key string\n\tvar err error\n\tif key, err = cache.MetaNamespaceKeyFunc(obj); err != nil {\n\t\tutilruntime.HandleError(err)\n\t\treturn\n\t}\n\tcnc.workqueue.Add(key)\n}","line":{"from":293,"to":303}} {"id":100029539,"name":"reconcileNodeLabels","signature":"func (cnc *CloudNodeController) reconcileNodeLabels(nodeName string) error","file":"staging/src/k8s.io/cloud-provider/controllers/node/node_controller.go","code":"// reconcileNodeLabels reconciles node labels transitioning from beta to GA\nfunc (cnc *CloudNodeController) reconcileNodeLabels(nodeName string) error {\n\tnode, err := cnc.nodeInformer.Lister().Get(nodeName)\n\tif err != nil {\n\t\t// If node not found, just ignore it.\n\t\tif apierrors.IsNotFound(err) {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn err\n\t}\n\n\tif node.Labels == nil {\n\t\t// Nothing to reconcile.\n\t\treturn nil\n\t}\n\n\tlabelsToUpdate := map[string]string{}\n\tfor _, r := range labelReconcileInfo {\n\t\tprimaryValue, primaryExists := node.Labels[r.primaryKey]\n\t\tsecondaryValue, secondaryExists := node.Labels[r.secondaryKey]\n\n\t\tif !primaryExists {\n\t\t\t// The primary label key does not exist. This should not happen\n\t\t\t// within our supported version skew range, when no external\n\t\t\t// components/factors modifying the node object. Ignore this case.\n\t\t\tcontinue\n\t\t}\n\t\tif secondaryExists \u0026\u0026 primaryValue != secondaryValue {\n\t\t\t// Secondary label exists, but not consistent with the primary\n\t\t\t// label. Need to reconcile.\n\t\t\tlabelsToUpdate[r.secondaryKey] = primaryValue\n\n\t\t} else if !secondaryExists \u0026\u0026 r.ensureSecondaryExists {\n\t\t\t// Apply secondary label based on primary label.\n\t\t\tlabelsToUpdate[r.secondaryKey] = primaryValue\n\t\t}\n\t}\n\n\tif len(labelsToUpdate) == 0 {\n\t\treturn nil\n\t}\n\n\tif !cloudnodeutil.AddOrUpdateLabelsOnNode(cnc.kubeClient, labelsToUpdate, node) {\n\t\treturn fmt.Errorf(\"failed update labels for node %+v\", node)\n\t}\n\n\treturn nil\n}","line":{"from":305,"to":353}} {"id":100029540,"name":"updateNodeAddress","signature":"func (cnc *CloudNodeController) updateNodeAddress(ctx context.Context, node *v1.Node, instanceMetadata *cloudprovider.InstanceMetadata)","file":"staging/src/k8s.io/cloud-provider/controllers/node/node_controller.go","code":"// UpdateNodeAddress updates the nodeAddress of a single node\nfunc (cnc *CloudNodeController) updateNodeAddress(ctx context.Context, node *v1.Node, instanceMetadata *cloudprovider.InstanceMetadata) {\n\t// Do not process nodes that are still tainted\n\tcloudTaint := getCloudTaint(node.Spec.Taints)\n\tif cloudTaint != nil {\n\t\tklog.V(5).Infof(\"This node %s is still tainted. Will not process.\", node.Name)\n\t\treturn\n\t}\n\n\tnodeAddresses := instanceMetadata.NodeAddresses\n\tif len(nodeAddresses) == 0 {\n\t\tklog.V(5).Infof(\"Skipping node address update for node %q since cloud provider did not return any\", node.Name)\n\t\treturn\n\t}\n\n\t// Check if a hostname address exists in the cloud provided addresses\n\thostnameExists := false\n\tfor i := range nodeAddresses {\n\t\tif nodeAddresses[i].Type == v1.NodeHostName {\n\t\t\thostnameExists = true\n\t\t\tbreak\n\t\t}\n\t}\n\t// If hostname was not present in cloud provided addresses, use the hostname\n\t// from the existing node (populated by kubelet)\n\tif !hostnameExists {\n\t\tfor _, addr := range node.Status.Addresses {\n\t\t\tif addr.Type == v1.NodeHostName {\n\t\t\t\tnodeAddresses = append(nodeAddresses, addr)\n\t\t\t}\n\t\t}\n\t}\n\t// If kubelet provided a node IP, prefer it in the node address list\n\tnodeAddresses, err := updateNodeAddressesFromNodeIP(node, nodeAddresses)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to update node addresses for node %q: %v\", node.Name, err)\n\t\treturn\n\t}\n\n\tif !nodeAddressesChangeDetected(node.Status.Addresses, nodeAddresses) {\n\t\treturn\n\t}\n\tnewNode := node.DeepCopy()\n\tnewNode.Status.Addresses = nodeAddresses\n\tif _, _, err := nodeutil.PatchNodeStatus(cnc.kubeClient.CoreV1(), types.NodeName(node.Name), node, newNode); err != nil {\n\t\tklog.Errorf(\"Error patching node with cloud ip addresses = [%v]\", err)\n\t}\n}","line":{"from":355,"to":402}} {"id":100029541,"name":"syncNode","signature":"func (cnc *CloudNodeController) syncNode(ctx context.Context, nodeName string) error","file":"staging/src/k8s.io/cloud-provider/controllers/node/node_controller.go","code":"// syncNode handles updating existing nodes registered with the cloud taint\n// and processes nodes that were added into the cluster, and cloud initialize them if appropriate.\nfunc (cnc *CloudNodeController) syncNode(ctx context.Context, nodeName string) error {\n\tcurNode, err := cnc.nodeInformer.Lister().Get(nodeName)\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn err\n\t}\n\n\tcloudTaint := getCloudTaint(curNode.Spec.Taints)\n\tif cloudTaint == nil {\n\t\t// Node object received from event had the cloud taint but was outdated,\n\t\t// the node has actually already been initialized, so this sync event can be ignored.\n\t\treturn nil\n\t}\n\n\tklog.Infof(\"Initializing node %s with cloud provider\", nodeName)\n\n\tcopyNode := curNode.DeepCopy()\n\tproviderID, err := cnc.getProviderID(ctx, copyNode)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get provider ID for node %s at cloudprovider: %v\", nodeName, err)\n\t}\n\n\tinstanceMetadata, err := cnc.getInstanceMetadata(ctx, providerID, copyNode)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get instance metadata for node %s: %v\", nodeName, err)\n\t}\n\tif instanceMetadata == nil {\n\t\t// do nothing when external cloud providers provide nil instanceMetadata\n\t\tklog.Infof(\"Skip sync node %s because cloud provided nil metadata\", nodeName)\n\t\treturn nil\n\t}\n\n\tnodeModifiers, err := cnc.getNodeModifiersFromCloudProvider(ctx, providerID, copyNode, instanceMetadata)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get node modifiers from cloud provider: %v\", err)\n\t}\n\n\tnodeModifiers = append(nodeModifiers, func(n *v1.Node) {\n\t\tn.Spec.Taints = excludeCloudTaint(n.Spec.Taints)\n\t})\n\n\terr = clientretry.RetryOnConflict(UpdateNodeSpecBackoff, func() error {\n\t\tvar curNode *v1.Node\n\t\tif cnc.cloud.ProviderName() == \"gce\" {\n\t\t\t// TODO(wlan0): Move this logic to the route controller using the node taint instead of condition\n\t\t\t// Since there are node taints, do we still need this?\n\t\t\t// This condition marks the node as unusable until routes are initialized in the cloud provider\n\t\t\tif err := nodeutil.SetNodeCondition(cnc.kubeClient, types.NodeName(nodeName), v1.NodeCondition{\n\t\t\t\tType: v1.NodeNetworkUnavailable,\n\t\t\t\tStatus: v1.ConditionTrue,\n\t\t\t\tReason: \"NoRouteCreated\",\n\t\t\t\tMessage: \"Node created without a route\",\n\t\t\t\tLastTransitionTime: metav1.Now(),\n\t\t\t}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// fetch latest node from API server since GCE-specific condition was set and informer cache may be stale\n\t\t\tcurNode, err = cnc.kubeClient.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tcurNode, err = cnc.nodeInformer.Lister().Get(nodeName)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tnewNode := curNode.DeepCopy()\n\t\tfor _, modify := range nodeModifiers {\n\t\t\tmodify(newNode)\n\t\t}\n\n\t\t_, err = cnc.kubeClient.CoreV1().Nodes().Update(context.TODO(), newNode, metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// After adding, call UpdateNodeAddress to set the CloudProvider provided IPAddresses\n\t\t// So that users do not see any significant delay in IP addresses being filled into the node\n\t\tcnc.updateNodeAddress(ctx, newNode, instanceMetadata)\n\n\t\tklog.Infof(\"Successfully initialized node %s with cloud provider\", nodeName)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcnc.recorder.Event(copyNode, v1.EventTypeNormal, \"Synced\", \"Node synced successfully\")\n\treturn nil\n}","line":{"from":408,"to":505}} {"id":100029542,"name":"getNodeModifiersFromCloudProvider","signature":"func (cnc *CloudNodeController) getNodeModifiersFromCloudProvider(","file":"staging/src/k8s.io/cloud-provider/controllers/node/node_controller.go","code":"// getNodeModifiersFromCloudProvider returns a slice of nodeModifiers that update\n// a node object with provider-specific information.\n// All of the returned functions are idempotent, because they are used in a retry-if-conflict\n// loop, meaning they could get called multiple times.\nfunc (cnc *CloudNodeController) getNodeModifiersFromCloudProvider(\n\tctx context.Context,\n\tproviderID string,\n\tnode *v1.Node,\n\tinstanceMeta *cloudprovider.InstanceMetadata,\n) ([]nodeModifier, error) {\n\n\tvar nodeModifiers []nodeModifier\n\tif node.Spec.ProviderID == \"\" {\n\t\tif providerID != \"\" {\n\t\t\tnodeModifiers = append(nodeModifiers, func(n *v1.Node) { n.Spec.ProviderID = providerID })\n\t\t} else if instanceMeta.ProviderID != \"\" {\n\t\t\tnodeModifiers = append(nodeModifiers, func(n *v1.Node) { n.Spec.ProviderID = instanceMeta.ProviderID })\n\t\t}\n\t}\n\n\t// If kubelet annotated the node with a node IP, ensure that it is valid\n\t// and can be applied to the discovered node addresses before removing\n\t// the taint on the node.\n\t_, err := updateNodeAddressesFromNodeIP(node, instanceMeta.NodeAddresses)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"provided node ip for node %q is not valid: %w\", node.Name, err)\n\t}\n\n\tif instanceMeta.InstanceType != \"\" {\n\t\tklog.V(2).Infof(\"Adding node label from cloud provider: %s=%s\", v1.LabelInstanceType, instanceMeta.InstanceType)\n\t\tklog.V(2).Infof(\"Adding node label from cloud provider: %s=%s\", v1.LabelInstanceTypeStable, instanceMeta.InstanceType)\n\t\tnodeModifiers = append(nodeModifiers, func(n *v1.Node) {\n\t\t\tif n.Labels == nil {\n\t\t\t\tn.Labels = map[string]string{}\n\t\t\t}\n\t\t\tn.Labels[v1.LabelInstanceType] = instanceMeta.InstanceType\n\t\t\tn.Labels[v1.LabelInstanceTypeStable] = instanceMeta.InstanceType\n\t\t})\n\t}\n\n\tif instanceMeta.Zone != \"\" {\n\t\tklog.V(2).Infof(\"Adding node label from cloud provider: %s=%s\", v1.LabelFailureDomainBetaZone, instanceMeta.Zone)\n\t\tklog.V(2).Infof(\"Adding node label from cloud provider: %s=%s\", v1.LabelTopologyZone, instanceMeta.Zone)\n\t\tnodeModifiers = append(nodeModifiers, func(n *v1.Node) {\n\t\t\tif n.Labels == nil {\n\t\t\t\tn.Labels = map[string]string{}\n\t\t\t}\n\t\t\tn.Labels[v1.LabelFailureDomainBetaZone] = instanceMeta.Zone\n\t\t\tn.Labels[v1.LabelTopologyZone] = instanceMeta.Zone\n\t\t})\n\t}\n\tif instanceMeta.Region != \"\" {\n\t\tklog.V(2).Infof(\"Adding node label from cloud provider: %s=%s\", v1.LabelFailureDomainBetaRegion, instanceMeta.Region)\n\t\tklog.V(2).Infof(\"Adding node label from cloud provider: %s=%s\", v1.LabelTopologyRegion, instanceMeta.Region)\n\t\tnodeModifiers = append(nodeModifiers, func(n *v1.Node) {\n\t\t\tif n.Labels == nil {\n\t\t\t\tn.Labels = map[string]string{}\n\t\t\t}\n\t\t\tn.Labels[v1.LabelFailureDomainBetaRegion] = instanceMeta.Region\n\t\t\tn.Labels[v1.LabelTopologyRegion] = instanceMeta.Region\n\t\t})\n\t}\n\n\treturn nodeModifiers, nil\n}","line":{"from":507,"to":571}} {"id":100029543,"name":"getProviderID","signature":"func (cnc *CloudNodeController) getProviderID(ctx context.Context, node *v1.Node) (string, error)","file":"staging/src/k8s.io/cloud-provider/controllers/node/node_controller.go","code":"func (cnc *CloudNodeController) getProviderID(ctx context.Context, node *v1.Node) (string, error) {\n\tif node.Spec.ProviderID != \"\" {\n\t\treturn node.Spec.ProviderID, nil\n\t}\n\n\tif _, ok := cnc.cloud.InstancesV2(); ok {\n\t\t// We don't need providerID when we call InstanceMetadata for InstancesV2\n\t\treturn \"\", nil\n\t}\n\n\tproviderID, err := cloudprovider.GetInstanceProviderID(ctx, cnc.cloud, types.NodeName(node.Name))\n\tif err == cloudprovider.NotImplemented {\n\t\t// if the cloud provider being used does not support provider IDs,\n\t\t// we can safely continue since we will attempt to set node\n\t\t// addresses given the node name in getNodeAddressesByProviderIDOrName\n\t\tklog.Warningf(\"cloud provider does not set node provider ID, using node name to discover node %s\", node.Name)\n\t\treturn \"\", nil\n\t}\n\n\t// if the cloud provider being used supports provider IDs, we want\n\t// to propagate the error so that we re-try in the future; if we\n\t// do not, the taint will be removed, and this will not be retried\n\treturn providerID, err\n}","line":{"from":573,"to":596}} {"id":100029544,"name":"getInstanceMetadata","signature":"func (cnc *CloudNodeController) getInstanceMetadata(ctx context.Context, providerID string, node *v1.Node) (*cloudprovider.InstanceMetadata, error)","file":"staging/src/k8s.io/cloud-provider/controllers/node/node_controller.go","code":"// getInstanceMetadata get instance type and nodeAddresses, use Instances if InstancesV2 is off.\nfunc (cnc *CloudNodeController) getInstanceMetadata(ctx context.Context, providerID string, node *v1.Node) (*cloudprovider.InstanceMetadata, error) {\n\tif instancesV2, ok := cnc.cloud.InstancesV2(); instancesV2 != nil \u0026\u0026 ok {\n\t\treturn instancesV2.InstanceMetadata(ctx, node)\n\t}\n\n\t// If InstancesV2 not implement, use Instances.\n\tinstances, ok := cnc.cloud.Instances()\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to get instances from cloud provider\")\n\t}\n\tnodeAddresses, err := getNodeAddressesByProviderIDOrName(ctx, instances, providerID, node.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinstanceType, err := getInstanceTypeByProviderIDOrName(ctx, instances, providerID, node.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinstanceMetadata := \u0026cloudprovider.InstanceMetadata{\n\t\tInstanceType: instanceType,\n\t\tNodeAddresses: nodeAddresses,\n\t}\n\n\tzones, ok := cnc.cloud.Zones()\n\tif !ok {\n\t\treturn instanceMetadata, nil\n\t}\n\n\tzone, err := getZoneByProviderIDOrName(ctx, zones, providerID, node.Name)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get zone from cloud provider: %v\", err)\n\t}\n\n\tif zone.FailureDomain != \"\" {\n\t\tinstanceMetadata.Zone = zone.FailureDomain\n\t}\n\n\tif zone.Region != \"\" {\n\t\tinstanceMetadata.Region = zone.Region\n\t}\n\n\treturn instanceMetadata, nil\n}","line":{"from":598,"to":642}} {"id":100029545,"name":"getInstanceNodeAddresses","signature":"func (cnc *CloudNodeController) getInstanceNodeAddresses(ctx context.Context, node *v1.Node) (*cloudprovider.InstanceMetadata, error)","file":"staging/src/k8s.io/cloud-provider/controllers/node/node_controller.go","code":"// getInstanceAddresses returns InstanceMetadata.NodeAddresses. If InstancesV2 not supported, it won't get instanceType\n// which avoid an api call compared with getInstanceMetadata.\nfunc (cnc *CloudNodeController) getInstanceNodeAddresses(ctx context.Context, node *v1.Node) (*cloudprovider.InstanceMetadata, error) {\n\tif instancesV2, ok := cnc.cloud.InstancesV2(); instancesV2 != nil \u0026\u0026 ok {\n\t\treturn instancesV2.InstanceMetadata(ctx, node)\n\t}\n\n\t// If InstancesV2 not implement, use Instances.\n\tinstances, ok := cnc.cloud.Instances()\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to get instances from cloud provider\")\n\t}\n\tnodeAddresses, err := getNodeAddressesByProviderIDOrName(ctx, instances, node.Spec.ProviderID, node.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026cloudprovider.InstanceMetadata{\n\t\tNodeAddresses: nodeAddresses,\n\t}, nil\n}","line":{"from":644,"to":664}} {"id":100029546,"name":"getCloudTaint","signature":"func getCloudTaint(taints []v1.Taint) *v1.Taint","file":"staging/src/k8s.io/cloud-provider/controllers/node/node_controller.go","code":"func getCloudTaint(taints []v1.Taint) *v1.Taint {\n\tfor _, taint := range taints {\n\t\tif taint.Key == cloudproviderapi.TaintExternalCloudProvider {\n\t\t\treturn \u0026taint\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":666,"to":673}} {"id":100029547,"name":"excludeCloudTaint","signature":"func excludeCloudTaint(taints []v1.Taint) []v1.Taint","file":"staging/src/k8s.io/cloud-provider/controllers/node/node_controller.go","code":"func excludeCloudTaint(taints []v1.Taint) []v1.Taint {\n\tnewTaints := []v1.Taint{}\n\tfor _, taint := range taints {\n\t\tif taint.Key == cloudproviderapi.TaintExternalCloudProvider {\n\t\t\tcontinue\n\t\t}\n\t\tnewTaints = append(newTaints, taint)\n\t}\n\treturn newTaints\n}","line":{"from":675,"to":684}} {"id":100029548,"name":"ensureNodeExistsByProviderID","signature":"func ensureNodeExistsByProviderID(ctx context.Context, instances cloudprovider.Instances, node *v1.Node) (bool, error)","file":"staging/src/k8s.io/cloud-provider/controllers/node/node_controller.go","code":"// ensureNodeExistsByProviderID checks if the instance exists by the provider id,\n// If provider id in spec is empty it calls instanceId with node name to get provider id\nfunc ensureNodeExistsByProviderID(ctx context.Context, instances cloudprovider.Instances, node *v1.Node) (bool, error) {\n\tproviderID := node.Spec.ProviderID\n\tif providerID == \"\" {\n\t\tvar err error\n\t\tproviderID, err = instances.InstanceID(ctx, types.NodeName(node.Name))\n\t\tif err != nil {\n\t\t\tif err == cloudprovider.InstanceNotFound {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn false, err\n\t\t}\n\n\t\tif providerID == \"\" {\n\t\t\tklog.Warningf(\"Cannot find valid providerID for node name %q, assuming non existence\", node.Name)\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\treturn instances.InstanceExistsByProviderID(ctx, providerID)\n}","line":{"from":686,"to":707}} {"id":100029549,"name":"getNodeAddressesByProviderIDOrName","signature":"func getNodeAddressesByProviderIDOrName(ctx context.Context, instances cloudprovider.Instances, providerID, nodeName string) ([]v1.NodeAddress, error)","file":"staging/src/k8s.io/cloud-provider/controllers/node/node_controller.go","code":"func getNodeAddressesByProviderIDOrName(ctx context.Context, instances cloudprovider.Instances, providerID, nodeName string) ([]v1.NodeAddress, error) {\n\tnodeAddresses, err := instances.NodeAddressesByProviderID(ctx, providerID)\n\tif err != nil {\n\t\tproviderIDErr := err\n\t\tnodeAddresses, err = instances.NodeAddresses(ctx, types.NodeName(nodeName))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error fetching node by provider ID: %v, and error by node name: %v\", providerIDErr, err)\n\t\t}\n\t}\n\treturn nodeAddresses, nil\n}","line":{"from":709,"to":719}} {"id":100029550,"name":"nodeAddressesChangeDetected","signature":"func nodeAddressesChangeDetected(addressSet1, addressSet2 []v1.NodeAddress) bool","file":"staging/src/k8s.io/cloud-provider/controllers/node/node_controller.go","code":"func nodeAddressesChangeDetected(addressSet1, addressSet2 []v1.NodeAddress) bool {\n\tif len(addressSet1) != len(addressSet2) {\n\t\treturn true\n\t}\n\taddressMap1 := map[v1.NodeAddressType]string{}\n\n\tfor i := range addressSet1 {\n\t\taddressMap1[addressSet1[i].Type] = addressSet1[i].Address\n\t}\n\n\tfor _, v := range addressSet2 {\n\t\tif addressMap1[v.Type] != v.Address {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":721,"to":737}} {"id":100029551,"name":"updateNodeAddressesFromNodeIP","signature":"func updateNodeAddressesFromNodeIP(node *v1.Node, nodeAddresses []v1.NodeAddress) ([]v1.NodeAddress, error)","file":"staging/src/k8s.io/cloud-provider/controllers/node/node_controller.go","code":"func updateNodeAddressesFromNodeIP(node *v1.Node, nodeAddresses []v1.NodeAddress) ([]v1.NodeAddress, error) {\n\tvar err error\n\n\tprovidedNodeIP, exists := node.ObjectMeta.Annotations[cloudproviderapi.AnnotationAlphaProvidedIPAddr]\n\tif exists {\n\t\tnodeAddresses, err = cloudnodeutil.GetNodeAddressesFromNodeIP(providedNodeIP, nodeAddresses, utilfeature.DefaultFeatureGate.Enabled(features.CloudDualStackNodeIPs))\n\t}\n\n\treturn nodeAddresses, err\n}","line":{"from":739,"to":748}} {"id":100029552,"name":"getInstanceTypeByProviderIDOrName","signature":"func getInstanceTypeByProviderIDOrName(ctx context.Context, instances cloudprovider.Instances, providerID, nodeName string) (string, error)","file":"staging/src/k8s.io/cloud-provider/controllers/node/node_controller.go","code":"// getInstanceTypeByProviderIDOrName will attempt to get the instance type of node using its providerID\n// then it's name. If both attempts fail, an error is returned.\nfunc getInstanceTypeByProviderIDOrName(ctx context.Context, instances cloudprovider.Instances, providerID, nodeName string) (string, error) {\n\tinstanceType, err := instances.InstanceTypeByProviderID(ctx, providerID)\n\tif err != nil {\n\t\tproviderIDErr := err\n\t\tinstanceType, err = instances.InstanceType(ctx, types.NodeName(nodeName))\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"InstanceType: Error fetching by providerID: %v Error fetching by NodeName: %v\", providerIDErr, err)\n\t\t}\n\t}\n\treturn instanceType, err\n}","line":{"from":750,"to":762}} {"id":100029553,"name":"getZoneByProviderIDOrName","signature":"func getZoneByProviderIDOrName(ctx context.Context, zones cloudprovider.Zones, providerID, nodeName string) (cloudprovider.Zone, error)","file":"staging/src/k8s.io/cloud-provider/controllers/node/node_controller.go","code":"// getZoneByProviderIDorName will attempt to get the zone of node using its providerID\n// then it's name. If both attempts fail, an error is returned.\nfunc getZoneByProviderIDOrName(ctx context.Context, zones cloudprovider.Zones, providerID, nodeName string) (cloudprovider.Zone, error) {\n\tzone, err := zones.GetZoneByProviderID(ctx, providerID)\n\tif err != nil {\n\t\tproviderIDErr := err\n\t\tzone, err = zones.GetZoneByNodeName(ctx, types.NodeName(nodeName))\n\t\tif err != nil {\n\t\t\treturn cloudprovider.Zone{}, fmt.Errorf(\"Zone: Error fetching by providerID: %v Error fetching by NodeName: %v\", providerIDErr, err)\n\t\t}\n\t}\n\n\treturn zone, nil\n}","line":{"from":764,"to":777}} {"id":100029554,"name":"NewCloudNodeLifecycleController","signature":"func NewCloudNodeLifecycleController(","file":"staging/src/k8s.io/cloud-provider/controllers/nodelifecycle/node_lifecycle_controller.go","code":"func NewCloudNodeLifecycleController(\n\tnodeInformer coreinformers.NodeInformer,\n\tkubeClient clientset.Interface,\n\tcloud cloudprovider.Interface,\n\tnodeMonitorPeriod time.Duration) (*CloudNodeLifecycleController, error) {\n\n\teventBroadcaster := record.NewBroadcaster()\n\trecorder := eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"cloud-node-lifecycle-controller\"})\n\n\tif kubeClient == nil {\n\t\treturn nil, errors.New(\"kubernetes client is nil\")\n\t}\n\n\tif cloud == nil {\n\t\treturn nil, errors.New(\"no cloud provider provided\")\n\t}\n\n\t_, instancesSupported := cloud.Instances()\n\t_, instancesV2Supported := cloud.InstancesV2()\n\tif !instancesSupported \u0026\u0026 !instancesV2Supported {\n\t\treturn nil, errors.New(\"cloud provider does not support instances\")\n\t}\n\n\tc := \u0026CloudNodeLifecycleController{\n\t\tkubeClient: kubeClient,\n\t\tnodeLister: nodeInformer.Lister(),\n\t\tbroadcaster: eventBroadcaster,\n\t\trecorder: recorder,\n\t\tcloud: cloud,\n\t\tnodeMonitorPeriod: nodeMonitorPeriod,\n\t}\n\n\treturn c, nil\n}","line":{"from":70,"to":103}} {"id":100029555,"name":"Run","signature":"func (c *CloudNodeLifecycleController) Run(ctx context.Context, controllerManagerMetrics *controllersmetrics.ControllerManagerMetrics)","file":"staging/src/k8s.io/cloud-provider/controllers/nodelifecycle/node_lifecycle_controller.go","code":"// Run starts the main loop for this controller. Run is blocking so should\n// be called via a goroutine\nfunc (c *CloudNodeLifecycleController) Run(ctx context.Context, controllerManagerMetrics *controllersmetrics.ControllerManagerMetrics) {\n\tdefer utilruntime.HandleCrash()\n\tcontrollerManagerMetrics.ControllerStarted(\"cloud-node-lifecycle\")\n\tdefer controllerManagerMetrics.ControllerStopped(\"cloud-node-lifecycle\")\n\n\t// Start event processing pipeline.\n\tklog.Info(\"Sending events to api server\")\n\tc.broadcaster.StartStructuredLogging(0)\n\tc.broadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: c.kubeClient.CoreV1().Events(\"\")})\n\tdefer c.broadcaster.Shutdown()\n\n\t// The following loops run communicate with the APIServer with a worst case complexity\n\t// of O(num_nodes) per cycle. These functions are justified here because these events fire\n\t// very infrequently. DO NOT MODIFY this to perform frequent operations.\n\n\t// Start a loop to periodically check if any nodes have been\n\t// deleted or shutdown from the cloudprovider\n\twait.UntilWithContext(ctx, c.MonitorNodes, c.nodeMonitorPeriod)\n}","line":{"from":105,"to":125}} {"id":100029556,"name":"MonitorNodes","signature":"func (c *CloudNodeLifecycleController) MonitorNodes(ctx context.Context)","file":"staging/src/k8s.io/cloud-provider/controllers/nodelifecycle/node_lifecycle_controller.go","code":"// MonitorNodes checks to see if nodes in the cluster have been deleted\n// or shutdown. If deleted, it deletes the node resource. If shutdown it\n// applies a shutdown taint to the node\nfunc (c *CloudNodeLifecycleController) MonitorNodes(ctx context.Context) {\n\tnodes, err := c.nodeLister.List(labels.Everything())\n\tif err != nil {\n\t\tklog.Errorf(\"error listing nodes from cache: %s\", err)\n\t\treturn\n\t}\n\n\tfor _, node := range nodes {\n\t\t// Default NodeReady status to v1.ConditionUnknown\n\t\tstatus := v1.ConditionUnknown\n\t\tif _, c := nodeutil.GetNodeCondition(\u0026node.Status, v1.NodeReady); c != nil {\n\t\t\tstatus = c.Status\n\t\t}\n\n\t\tif status == v1.ConditionTrue {\n\t\t\t// if taint exist remove taint\n\t\t\terr = cloudnodeutil.RemoveTaintOffNode(c.kubeClient, node.Name, node, ShutdownTaint)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"error patching node taints: %v\", err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// At this point the node has NotReady status, we need to check if the node has been removed\n\t\t// from the cloud provider. If node cannot be found in cloudprovider, then delete the node\n\t\texists, err := ensureNodeExistsByProviderID(ctx, c.cloud, node)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"error checking if node %s exists: %v\", node.Name, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif !exists {\n\t\t\t// Current node does not exist, we should delete it, its taints do not matter anymore\n\n\t\t\tklog.V(2).Infof(\"deleting node since it is no longer present in cloud provider: %s\", node.Name)\n\n\t\t\tref := \u0026v1.ObjectReference{\n\t\t\t\tKind: \"Node\",\n\t\t\t\tName: node.Name,\n\t\t\t\tUID: types.UID(node.UID),\n\t\t\t\tNamespace: \"\",\n\t\t\t}\n\n\t\t\tc.recorder.Eventf(ref, v1.EventTypeNormal, deleteNodeEvent,\n\t\t\t\t\"Deleting node %s because it does not exist in the cloud provider\", node.Name)\n\n\t\t\tif err := c.kubeClient.CoreV1().Nodes().Delete(ctx, node.Name, metav1.DeleteOptions{}); err != nil {\n\t\t\t\tklog.Errorf(\"unable to delete node %q: %v\", node.Name, err)\n\t\t\t}\n\t\t} else {\n\t\t\t// Node exists. We need to check this to get taint working in similar in all cloudproviders\n\t\t\t// current problem is that shutdown nodes are not working in similar way ie. all cloudproviders\n\t\t\t// does not delete node from kubernetes cluster when instance it is shutdown see issue #46442\n\t\t\tshutdown, err := shutdownInCloudProvider(ctx, c.cloud, node)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"error checking if node %s is shutdown: %v\", node.Name, err)\n\t\t\t}\n\n\t\t\tif shutdown \u0026\u0026 err == nil {\n\t\t\t\t// if node is shutdown add shutdown taint\n\t\t\t\terr = cloudnodeutil.AddOrUpdateTaintOnNode(c.kubeClient, node.Name, ShutdownTaint)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Errorf(\"failed to apply shutdown taint to node %s, it may have been deleted.\", node.Name)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":127,"to":197}} {"id":100029557,"name":"shutdownInCloudProvider","signature":"func shutdownInCloudProvider(ctx context.Context, cloud cloudprovider.Interface, node *v1.Node) (bool, error)","file":"staging/src/k8s.io/cloud-provider/controllers/nodelifecycle/node_lifecycle_controller.go","code":"// shutdownInCloudProvider returns true if the node is shutdown on the cloud provider\nfunc shutdownInCloudProvider(ctx context.Context, cloud cloudprovider.Interface, node *v1.Node) (bool, error) {\n\tif instanceV2, ok := cloud.InstancesV2(); ok {\n\t\treturn instanceV2.InstanceShutdown(ctx, node)\n\t}\n\n\tinstances, ok := cloud.Instances()\n\tif !ok {\n\t\treturn false, errors.New(\"cloud provider does not support instances\")\n\t}\n\n\tshutdown, err := instances.InstanceShutdownByProviderID(ctx, node.Spec.ProviderID)\n\tif err == cloudprovider.NotImplemented {\n\t\treturn false, nil\n\t}\n\n\treturn shutdown, err\n}","line":{"from":199,"to":216}} {"id":100029558,"name":"ensureNodeExistsByProviderID","signature":"func ensureNodeExistsByProviderID(ctx context.Context, cloud cloudprovider.Interface, node *v1.Node) (bool, error)","file":"staging/src/k8s.io/cloud-provider/controllers/nodelifecycle/node_lifecycle_controller.go","code":"// ensureNodeExistsByProviderID checks if the instance exists by the provider id,\n// If provider id in spec is empty it calls instanceId with node name to get provider id\nfunc ensureNodeExistsByProviderID(ctx context.Context, cloud cloudprovider.Interface, node *v1.Node) (bool, error) {\n\tif instanceV2, ok := cloud.InstancesV2(); ok {\n\t\treturn instanceV2.InstanceExists(ctx, node)\n\t}\n\n\tinstances, ok := cloud.Instances()\n\tif !ok {\n\t\treturn false, errors.New(\"instances interface not supported in the cloud provider\")\n\t}\n\n\tproviderID := node.Spec.ProviderID\n\tif providerID == \"\" {\n\t\tvar err error\n\t\tproviderID, err = instances.InstanceID(ctx, types.NodeName(node.Name))\n\t\tif err != nil {\n\t\t\tif err == cloudprovider.InstanceNotFound {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn false, err\n\t\t}\n\n\t\tif providerID == \"\" {\n\t\t\tklog.Warningf(\"Cannot find valid providerID for node name %q, assuming non existence\", node.Name)\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\treturn instances.InstanceExistsByProviderID(ctx, providerID)\n}","line":{"from":218,"to":248}} {"id":100029559,"name":"New","signature":"func New(routes cloudprovider.Routes, kubeClient clientset.Interface, nodeInformer coreinformers.NodeInformer, clusterName string, clusterCIDRs []*net.IPNet) *RouteController","file":"staging/src/k8s.io/cloud-provider/controllers/route/route_controller.go","code":"func New(routes cloudprovider.Routes, kubeClient clientset.Interface, nodeInformer coreinformers.NodeInformer, clusterName string, clusterCIDRs []*net.IPNet) *RouteController {\n\tif len(clusterCIDRs) == 0 {\n\t\tklog.Fatal(\"RouteController: Must specify clusterCIDR.\")\n\t}\n\n\teventBroadcaster := record.NewBroadcaster()\n\trecorder := eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"route_controller\"})\n\n\trc := \u0026RouteController{\n\t\troutes: routes,\n\t\tkubeClient: kubeClient,\n\t\tclusterName: clusterName,\n\t\tclusterCIDRs: clusterCIDRs,\n\t\tnodeLister: nodeInformer.Lister(),\n\t\tnodeListerSynced: nodeInformer.Informer().HasSynced,\n\t\tbroadcaster: eventBroadcaster,\n\t\trecorder: recorder,\n\t}\n\n\treturn rc\n}","line":{"from":72,"to":92}} {"id":100029560,"name":"Run","signature":"func (rc *RouteController) Run(ctx context.Context, syncPeriod time.Duration, controllerManagerMetrics *controllersmetrics.ControllerManagerMetrics)","file":"staging/src/k8s.io/cloud-provider/controllers/route/route_controller.go","code":"func (rc *RouteController) Run(ctx context.Context, syncPeriod time.Duration, controllerManagerMetrics *controllersmetrics.ControllerManagerMetrics) {\n\tdefer utilruntime.HandleCrash()\n\n\t// Start event processing pipeline.\n\tif rc.broadcaster != nil {\n\t\trc.broadcaster.StartStructuredLogging(0)\n\t\trc.broadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: rc.kubeClient.CoreV1().Events(\"\")})\n\t\tdefer rc.broadcaster.Shutdown()\n\t}\n\n\tklog.Info(\"Starting route controller\")\n\tdefer klog.Info(\"Shutting down route controller\")\n\tcontrollerManagerMetrics.ControllerStarted(\"route\")\n\tdefer controllerManagerMetrics.ControllerStopped(\"route\")\n\n\tif !cache.WaitForNamedCacheSync(\"route\", ctx.Done(), rc.nodeListerSynced) {\n\t\treturn\n\t}\n\n\t// TODO: If we do just the full Resync every 5 minutes (default value)\n\t// that means that we may wait up to 5 minutes before even starting\n\t// creating a route for it. This is bad.\n\t// We should have a watch on node and if we observe a new node (with CIDR?)\n\t// trigger reconciliation for that node.\n\tgo wait.NonSlidingUntil(func() {\n\t\tif err := rc.reconcileNodeRoutes(ctx); err != nil {\n\t\t\tklog.Errorf(\"Couldn't reconcile node routes: %v\", err)\n\t\t}\n\t}, syncPeriod, ctx.Done())\n\n\t\u003c-ctx.Done()\n}","line":{"from":94,"to":125}} {"id":100029561,"name":"reconcileNodeRoutes","signature":"func (rc *RouteController) reconcileNodeRoutes(ctx context.Context) error","file":"staging/src/k8s.io/cloud-provider/controllers/route/route_controller.go","code":"func (rc *RouteController) reconcileNodeRoutes(ctx context.Context) error {\n\trouteList, err := rc.routes.ListRoutes(ctx, rc.clusterName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error listing routes: %v\", err)\n\t}\n\tnodes, err := rc.nodeLister.List(labels.Everything())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error listing nodes: %v\", err)\n\t}\n\treturn rc.reconcile(ctx, nodes, routeList)\n}","line":{"from":127,"to":137}} {"id":100029562,"name":"reconcile","signature":"func (rc *RouteController) reconcile(ctx context.Context, nodes []*v1.Node, routes []*cloudprovider.Route) error","file":"staging/src/k8s.io/cloud-provider/controllers/route/route_controller.go","code":"func (rc *RouteController) reconcile(ctx context.Context, nodes []*v1.Node, routes []*cloudprovider.Route) error {\n\tvar l sync.Mutex\n\t// routeMap includes info about a target Node and its addresses, routes and a map between Pod CIDRs and actions.\n\t// If action is add/remove, the route will be added/removed.\n\t// If action is keep, the route will not be touched.\n\t// If action is update, the route will be deleted and then added.\n\trouteMap := make(map[types.NodeName]routeNode)\n\n\t// Put current routes into routeMap.\n\tfor _, route := range routes {\n\t\tif route.TargetNode == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\trn, ok := routeMap[route.TargetNode]\n\t\tif !ok {\n\t\t\trn = routeNode{\n\t\t\t\tname: route.TargetNode,\n\t\t\t\taddrs: []v1.NodeAddress{},\n\t\t\t\troutes: []*cloudprovider.Route{},\n\t\t\t\tcidrWithActions: \u0026map[string]routeAction{},\n\t\t\t}\n\t\t} else if rn.routes == nil {\n\t\t\trn.routes = []*cloudprovider.Route{}\n\t\t}\n\t\trn.routes = append(rn.routes, route)\n\t\trouteMap[route.TargetNode] = rn\n\t}\n\n\twg := sync.WaitGroup{}\n\trateLimiter := make(chan struct{}, maxConcurrentRouteOperations)\n\t// searches existing routes by node for a matching route\n\n\t// Check Nodes and their Pod CIDRs. Then put expected route actions into nodePodCIDRActionMap.\n\t// Add addresses of Nodes into routeMap.\n\tfor _, node := range nodes {\n\t\t// Skip if the node hasn't been assigned a CIDR yet.\n\t\tif len(node.Spec.PodCIDRs) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tnodeName := types.NodeName(node.Name)\n\t\tl.Lock()\n\t\trn, ok := routeMap[nodeName]\n\t\tif !ok {\n\t\t\trn = routeNode{\n\t\t\t\tname: nodeName,\n\t\t\t\taddrs: []v1.NodeAddress{},\n\t\t\t\troutes: []*cloudprovider.Route{},\n\t\t\t\tcidrWithActions: \u0026map[string]routeAction{},\n\t\t\t}\n\t\t}\n\t\trn.addrs = node.Status.Addresses\n\t\trouteMap[nodeName] = rn\n\t\tl.Unlock()\n\t\t// for every node, for every cidr\n\t\tfor _, podCIDR := range node.Spec.PodCIDRs {\n\t\t\t// we add it to our nodeCIDRs map here because if we don't consider Node addresses change,\n\t\t\t// add and delete go routines run simultaneously.\n\t\t\tl.Lock()\n\t\t\taction := getRouteAction(rn.routes, podCIDR, nodeName, node.Status.Addresses)\n\t\t\t(*routeMap[nodeName].cidrWithActions)[podCIDR] = action\n\t\t\tl.Unlock()\n\t\t\tklog.Infof(\"action for Node %q with CIDR %q: %q\", nodeName, podCIDR, action)\n\t\t}\n\t}\n\n\t// searches our bag of node -\u003e cidrs for a match\n\t// If the action doesn't exist, action is remove or update, then the route should be deleted.\n\tshouldDeleteRoute := func(nodeName types.NodeName, cidr string) bool {\n\t\tl.Lock()\n\t\tdefer l.Unlock()\n\n\t\tcidrWithActions := routeMap[nodeName].cidrWithActions\n\t\tif cidrWithActions == nil {\n\t\t\treturn true\n\t\t}\n\t\taction, exist := (*cidrWithActions)[cidr]\n\t\tif !exist || action == remove || action == update {\n\t\t\tklog.Infof(\"route should be deleted, spec: exist: %v, action: %q, Node %q, CIDR %q\", exist, action, nodeName, cidr)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\t// remove routes that are not in use or need to be updated.\n\tfor _, route := range routes {\n\t\tif !rc.isResponsibleForRoute(route) {\n\t\t\tcontinue\n\t\t}\n\t\t// Check if this route is a blackhole, or applies to a node we know about \u0026 CIDR status is created.\n\t\tif route.Blackhole || shouldDeleteRoute(route.TargetNode, route.DestinationCIDR) {\n\t\t\twg.Add(1)\n\t\t\t// Delete the route.\n\t\t\tgo func(route *cloudprovider.Route, startTime time.Time) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\t// respect the rate limiter\n\t\t\t\trateLimiter \u003c- struct{}{}\n\t\t\t\tklog.Infof(\"Deleting route %s %s\", route.Name, route.DestinationCIDR)\n\t\t\t\tif err := rc.routes.DeleteRoute(ctx, rc.clusterName, route); err != nil {\n\t\t\t\t\tklog.Errorf(\"Could not delete route %s %s after %v: %v\", route.Name, route.DestinationCIDR, time.Since(startTime), err)\n\t\t\t\t} else {\n\t\t\t\t\tklog.Infof(\"Deleted route %s %s after %v\", route.Name, route.DestinationCIDR, time.Since(startTime))\n\t\t\t\t}\n\t\t\t\t\u003c-rateLimiter\n\t\t\t}(route, time.Now())\n\t\t}\n\t}\n\t// https://github.com/kubernetes/kubernetes/issues/98359\n\t// When routesUpdated is true, Route addition and deletion cannot run simultaneously because if action is update,\n\t// the same route may be added and deleted.\n\tif len(routes) != 0 \u0026\u0026 routes[0].EnableNodeAddresses {\n\t\twg.Wait()\n\t}\n\n\t// Now create new routes or update existing ones.\n\tfor _, node := range nodes {\n\t\t// Skip if the node hasn't been assigned a CIDR yet.\n\t\tif len(node.Spec.PodCIDRs) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tnodeName := types.NodeName(node.Name)\n\n\t\t// for every node, for every cidr\n\t\tfor _, podCIDR := range node.Spec.PodCIDRs {\n\t\t\tl.Lock()\n\t\t\taction := (*routeMap[nodeName].cidrWithActions)[podCIDR]\n\t\t\tl.Unlock()\n\t\t\tif action == keep || action == remove {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// if we are here, then a route needs to be created for this node\n\t\t\troute := \u0026cloudprovider.Route{\n\t\t\t\tTargetNode: nodeName,\n\t\t\t\tTargetNodeAddresses: node.Status.Addresses,\n\t\t\t\tDestinationCIDR: podCIDR,\n\t\t\t}\n\t\t\tklog.Infof(\"route spec to be created: %v\", route)\n\t\t\t// cloud providers that:\n\t\t\t// - depend on nameHint\n\t\t\t// - trying to support dual stack\n\t\t\t// will have to carefully generate new route names that allow node-\u003e(multi cidr)\n\t\t\tnameHint := string(node.UID)\n\t\t\twg.Add(1)\n\t\t\tgo func(nodeName types.NodeName, nameHint string, route *cloudprovider.Route) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\terr := clientretry.RetryOnConflict(updateNetworkConditionBackoff, func() error {\n\t\t\t\t\tstartTime := time.Now()\n\t\t\t\t\t// Ensure that we don't have more than maxConcurrentRouteOperations\n\t\t\t\t\t// CreateRoute calls in flight.\n\t\t\t\t\trateLimiter \u003c- struct{}{}\n\t\t\t\t\tklog.Infof(\"Creating route for node %s %s with hint %s, throttled %v\", nodeName, route.DestinationCIDR, nameHint, time.Since(startTime))\n\t\t\t\t\terr := rc.routes.CreateRoute(ctx, rc.clusterName, nameHint, route)\n\t\t\t\t\t\u003c-rateLimiter\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tmsg := fmt.Sprintf(\"Could not create route %s %s for node %s after %v: %v\", nameHint, route.DestinationCIDR, nodeName, time.Since(startTime), err)\n\t\t\t\t\t\tif rc.recorder != nil {\n\t\t\t\t\t\t\trc.recorder.Eventf(\n\t\t\t\t\t\t\t\t\u0026v1.ObjectReference{\n\t\t\t\t\t\t\t\t\tKind: \"Node\",\n\t\t\t\t\t\t\t\t\tName: string(nodeName),\n\t\t\t\t\t\t\t\t\tUID: types.UID(nodeName),\n\t\t\t\t\t\t\t\t\tNamespace: \"\",\n\t\t\t\t\t\t\t\t}, v1.EventTypeWarning, \"FailedToCreateRoute\", msg)\n\t\t\t\t\t\t\tklog.V(4).Infof(msg)\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tl.Lock()\n\t\t\t\t\t// Mark the route action as done (keep)\n\t\t\t\t\t(*routeMap[nodeName].cidrWithActions)[route.DestinationCIDR] = keep\n\t\t\t\t\tl.Unlock()\n\t\t\t\t\tklog.Infof(\"Created route for node %s %s with hint %s after %v\", nodeName, route.DestinationCIDR, nameHint, time.Since(startTime))\n\t\t\t\t\treturn nil\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Errorf(\"Could not create route %s %s for node %s: %v\", nameHint, route.DestinationCIDR, nodeName, err)\n\t\t\t\t}\n\t\t\t}(nodeName, nameHint, route)\n\t\t}\n\t}\n\twg.Wait()\n\n\t// after all route actions have been done (or not), we start updating\n\t// all nodes' statuses with the outcome\n\tfor _, node := range nodes {\n\t\tactions := routeMap[types.NodeName(node.Name)].cidrWithActions\n\t\tif actions == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\twg.Add(1)\n\t\tif len(*actions) == 0 {\n\t\t\tgo func(n *v1.Node) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tklog.Infof(\"node %v has no routes assigned to it. NodeNetworkUnavailable will be set to true\", n.Name)\n\t\t\t\tif err := rc.updateNetworkingCondition(n, false); err != nil {\n\t\t\t\t\tklog.Errorf(\"failed to update networking condition when no actions: %v\", err)\n\t\t\t\t}\n\t\t\t}(node)\n\t\t\tcontinue\n\t\t}\n\n\t\t// check if all route actions were done. if so, then it should be ready\n\t\tallRoutesCreated := true\n\t\tfor _, action := range *actions {\n\t\t\tif action == add || action == update {\n\t\t\t\tallRoutesCreated = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tgo func(n *v1.Node) {\n\t\t\tdefer wg.Done()\n\t\t\tif err := rc.updateNetworkingCondition(n, allRoutesCreated); err != nil {\n\t\t\t\tklog.Errorf(\"failed to update networking condition: %v\", err)\n\t\t\t}\n\t\t}(node)\n\t}\n\twg.Wait()\n\treturn nil\n}","line":{"from":155,"to":373}} {"id":100029563,"name":"updateNetworkingCondition","signature":"func (rc *RouteController) updateNetworkingCondition(node *v1.Node, routesCreated bool) error","file":"staging/src/k8s.io/cloud-provider/controllers/route/route_controller.go","code":"func (rc *RouteController) updateNetworkingCondition(node *v1.Node, routesCreated bool) error {\n\t_, condition := nodeutil.GetNodeCondition(\u0026(node.Status), v1.NodeNetworkUnavailable)\n\tif routesCreated \u0026\u0026 condition != nil \u0026\u0026 condition.Status == v1.ConditionFalse {\n\t\tklog.V(2).Infof(\"set node %v with NodeNetworkUnavailable=false was canceled because it is already set\", node.Name)\n\t\treturn nil\n\t}\n\n\tif !routesCreated \u0026\u0026 condition != nil \u0026\u0026 condition.Status == v1.ConditionTrue {\n\t\tklog.V(2).Infof(\"set node %v with NodeNetworkUnavailable=true was canceled because it is already set\", node.Name)\n\t\treturn nil\n\t}\n\n\tklog.Infof(\"Patching node status %v with %v previous condition was:%+v\", node.Name, routesCreated, condition)\n\n\t// either condition is not there, or has a value != to what we need\n\t// start setting it\n\terr := clientretry.RetryOnConflict(updateNetworkConditionBackoff, func() error {\n\t\tvar err error\n\t\t// Patch could also fail, even though the chance is very slim. So we still do\n\t\t// patch in the retry loop.\n\t\tcurrentTime := metav1.Now()\n\t\tif routesCreated {\n\t\t\terr = nodeutil.SetNodeCondition(rc.kubeClient, types.NodeName(node.Name), v1.NodeCondition{\n\t\t\t\tType: v1.NodeNetworkUnavailable,\n\t\t\t\tStatus: v1.ConditionFalse,\n\t\t\t\tReason: \"RouteCreated\",\n\t\t\t\tMessage: \"RouteController created a route\",\n\t\t\t\tLastTransitionTime: currentTime,\n\t\t\t})\n\t\t} else {\n\t\t\terr = nodeutil.SetNodeCondition(rc.kubeClient, types.NodeName(node.Name), v1.NodeCondition{\n\t\t\t\tType: v1.NodeNetworkUnavailable,\n\t\t\t\tStatus: v1.ConditionTrue,\n\t\t\t\tReason: \"NoRouteCreated\",\n\t\t\t\tMessage: \"RouteController failed to create a route\",\n\t\t\t\tLastTransitionTime: currentTime,\n\t\t\t})\n\t\t}\n\t\tif err != nil {\n\t\t\tklog.V(4).Infof(\"Error updating node %s, retrying: %v\", types.NodeName(node.Name), err)\n\t\t}\n\t\treturn err\n\t})\n\n\tif err != nil {\n\t\tklog.Errorf(\"Error updating node %s: %v\", node.Name, err)\n\t}\n\n\treturn err\n}","line":{"from":375,"to":424}} {"id":100029564,"name":"isResponsibleForRoute","signature":"func (rc *RouteController) isResponsibleForRoute(route *cloudprovider.Route) bool","file":"staging/src/k8s.io/cloud-provider/controllers/route/route_controller.go","code":"func (rc *RouteController) isResponsibleForRoute(route *cloudprovider.Route) bool {\n\t_, cidr, err := netutils.ParseCIDRSloppy(route.DestinationCIDR)\n\tif err != nil {\n\t\tklog.Errorf(\"Ignoring route %s, unparsable CIDR: %v\", route.Name, err)\n\t\treturn false\n\t}\n\t// Not responsible if this route's CIDR is not within our clusterCIDR\n\tlastIP := make([]byte, len(cidr.IP))\n\tfor i := range lastIP {\n\t\tlastIP[i] = cidr.IP[i] | ^cidr.Mask[i]\n\t}\n\n\t// check across all cluster cidrs\n\tfor _, clusterCIDR := range rc.clusterCIDRs {\n\t\tif clusterCIDR.Contains(cidr.IP) || clusterCIDR.Contains(lastIP) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":426,"to":445}} {"id":100029565,"name":"getRouteAction","signature":"func getRouteAction(routes []*cloudprovider.Route, cidr string, nodeName types.NodeName, realNodeAddrs []v1.NodeAddress) routeAction","file":"staging/src/k8s.io/cloud-provider/controllers/route/route_controller.go","code":"// getRouteAction returns an action according to if there's a route matches a specific cidr and target Node addresses.\nfunc getRouteAction(routes []*cloudprovider.Route, cidr string, nodeName types.NodeName, realNodeAddrs []v1.NodeAddress) routeAction {\n\tfor _, route := range routes {\n\t\tif route.DestinationCIDR == cidr {\n\t\t\tif !route.EnableNodeAddresses || equalNodeAddrs(realNodeAddrs, route.TargetNodeAddresses) {\n\t\t\t\treturn keep\n\t\t\t}\n\t\t\tklog.Infof(\"Node addresses have changed from %v to %v\", route.TargetNodeAddresses, realNodeAddrs)\n\t\t\treturn update\n\t\t}\n\t}\n\treturn add\n}","line":{"from":447,"to":459}} {"id":100029566,"name":"equalNodeAddrs","signature":"func equalNodeAddrs(addrs0 []v1.NodeAddress, addrs1 []v1.NodeAddress) bool","file":"staging/src/k8s.io/cloud-provider/controllers/route/route_controller.go","code":"func equalNodeAddrs(addrs0 []v1.NodeAddress, addrs1 []v1.NodeAddress) bool {\n\tif len(addrs0) != len(addrs1) {\n\t\treturn false\n\t}\n\tfor _, ip0 := range addrs0 {\n\t\tfound := false\n\t\tfor _, ip1 := range addrs1 {\n\t\t\tif reflect.DeepEqual(ip0, ip1) {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":461,"to":478}} {"id":100029567,"name":"Convert_v1alpha1_ServiceControllerConfiguration_To_config_ServiceControllerConfiguration","signature":"func Convert_v1alpha1_ServiceControllerConfiguration_To_config_ServiceControllerConfiguration(in *ServiceControllerConfiguration, out *serviceconfig.ServiceControllerConfiguration, s conversion.Scope) error","file":"staging/src/k8s.io/cloud-provider/controllers/service/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_ServiceControllerConfiguration_To_config_ServiceControllerConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_ServiceControllerConfiguration_To_config_ServiceControllerConfiguration(in *ServiceControllerConfiguration, out *serviceconfig.ServiceControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_ServiceControllerConfiguration_To_config_ServiceControllerConfiguration(in, out, s)\n}","line":{"from":31,"to":34}} {"id":100029568,"name":"Convert_config_ServiceControllerConfiguration_To_v1alpha1_ServiceControllerConfiguration","signature":"func Convert_config_ServiceControllerConfiguration_To_v1alpha1_ServiceControllerConfiguration(in *serviceconfig.ServiceControllerConfiguration, out *ServiceControllerConfiguration, s conversion.Scope) error","file":"staging/src/k8s.io/cloud-provider/controllers/service/config/v1alpha1/conversion.go","code":"// Convert_config_ServiceControllerConfiguration_To_v1alpha1_ServiceControllerConfiguration is an autogenerated conversion function.\nfunc Convert_config_ServiceControllerConfiguration_To_v1alpha1_ServiceControllerConfiguration(in *serviceconfig.ServiceControllerConfiguration, out *ServiceControllerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_ServiceControllerConfiguration_To_v1alpha1_ServiceControllerConfiguration(in, out, s)\n}","line":{"from":36,"to":39}} {"id":100029569,"name":"RecommendedDefaultServiceControllerConfiguration","signature":"func RecommendedDefaultServiceControllerConfiguration(obj *ServiceControllerConfiguration)","file":"staging/src/k8s.io/cloud-provider/controllers/service/config/v1alpha1/defaults.go","code":"// RecommendedDefaultServiceControllerConfiguration defaults a pointer to a\n// ServiceControllerConfiguration struct. This will set the recommended default\n// values, but they may be subject to change between API versions. This function\n// is intentionally not registered in the scheme as a \"normal\" `SetDefaults_Foo`\n// function to allow consumers of this type to set whatever defaults for their\n// embedded configs. Forcing consumers to use these defaults would be problematic\n// as defaulting in the scheme is done as part of the conversion, and there would\n// be no easy way to opt-out. Instead, if you want to use this defaulting method\n// run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDefaultServiceControllerConfiguration(obj *ServiceControllerConfiguration) {\n\tif obj.ConcurrentServiceSyncs == 0 {\n\t\tobj.ConcurrentServiceSyncs = 1\n\t}\n}","line":{"from":19,"to":32}} {"id":100029570,"name":"New","signature":"func New(","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"// New returns a new service controller to keep cloud provider service resources\n// (like load balancers) in sync with the registry.\nfunc New(\n\tcloud cloudprovider.Interface,\n\tkubeClient clientset.Interface,\n\tserviceInformer coreinformers.ServiceInformer,\n\tnodeInformer coreinformers.NodeInformer,\n\tclusterName string,\n\tfeatureGate featuregate.FeatureGate,\n) (*Controller, error) {\n\tbroadcaster := record.NewBroadcaster()\n\trecorder := broadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"service-controller\"})\n\n\tregisterMetrics()\n\ts := \u0026Controller{\n\t\tcloud: cloud,\n\t\tkubeClient: kubeClient,\n\t\tclusterName: clusterName,\n\t\tcache: \u0026serviceCache{serviceMap: make(map[string]*cachedService)},\n\t\teventBroadcaster: broadcaster,\n\t\teventRecorder: recorder,\n\t\tnodeLister: nodeInformer.Lister(),\n\t\tnodeListerSynced: nodeInformer.Informer().HasSynced,\n\t\tserviceQueue: workqueue.NewNamedRateLimitingQueue(workqueue.NewItemExponentialFailureRateLimiter(minRetryDelay, maxRetryDelay), \"service\"),\n\t\tnodeQueue: workqueue.NewNamedRateLimitingQueue(workqueue.NewItemExponentialFailureRateLimiter(minRetryDelay, maxRetryDelay), \"node\"),\n\t\tlastSyncedNodes: []*v1.Node{},\n\t}\n\n\tserviceInformer.Informer().AddEventHandlerWithResyncPeriod(\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: func(cur interface{}) {\n\t\t\t\tsvc, ok := cur.(*v1.Service)\n\t\t\t\t// Check cleanup here can provide a remedy when controller failed to handle\n\t\t\t\t// changes before it exiting (e.g. crashing, restart, etc.).\n\t\t\t\tif ok \u0026\u0026 (wantsLoadBalancer(svc) || needsCleanup(svc)) {\n\t\t\t\t\ts.enqueueService(cur)\n\t\t\t\t}\n\t\t\t},\n\t\t\tUpdateFunc: func(old, cur interface{}) {\n\t\t\t\toldSvc, ok1 := old.(*v1.Service)\n\t\t\t\tcurSvc, ok2 := cur.(*v1.Service)\n\t\t\t\tif ok1 \u0026\u0026 ok2 \u0026\u0026 (s.needsUpdate(oldSvc, curSvc) || needsCleanup(curSvc)) {\n\t\t\t\t\ts.enqueueService(cur)\n\t\t\t\t}\n\t\t\t},\n\t\t\t// No need to handle deletion event because the deletion would be handled by\n\t\t\t// the update path when the deletion timestamp is added.\n\t\t},\n\t\tserviceSyncPeriod,\n\t)\n\ts.serviceLister = serviceInformer.Lister()\n\ts.serviceListerSynced = serviceInformer.Informer().HasSynced\n\n\tnodeInformer.Informer().AddEventHandlerWithResyncPeriod(\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: func(cur interface{}) {\n\t\t\t\ts.enqueueNode(cur)\n\t\t\t},\n\t\t\tUpdateFunc: func(old, cur interface{}) {\n\t\t\t\toldNode, ok := old.(*v1.Node)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tcurNode, ok := cur.(*v1.Node)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif !shouldSyncUpdatedNode(oldNode, curNode) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\ts.enqueueNode(curNode)\n\t\t\t},\n\t\t\tDeleteFunc: func(old interface{}) {\n\t\t\t\ts.enqueueNode(old)\n\t\t\t},\n\t\t},\n\t\tnodeSyncPeriod,\n\t)\n\n\tif err := s.init(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s, nil\n}","line":{"from":100,"to":187}} {"id":100029571,"name":"enqueueService","signature":"func (c *Controller) enqueueService(obj interface{})","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"// obj could be an *v1.Service, or a DeletionFinalStateUnknown marker item.\nfunc (c *Controller) enqueueService(obj interface{}) {\n\tkey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)\n\tif err != nil {\n\t\truntime.HandleError(fmt.Errorf(\"couldn't get key for object %#v: %v\", obj, err))\n\t\treturn\n\t}\n\tc.serviceQueue.Add(key)\n}","line":{"from":189,"to":197}} {"id":100029572,"name":"enqueueNode","signature":"func (c *Controller) enqueueNode(obj interface{})","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"// obj could be an *v1.Service, or a DeletionFinalStateUnknown marker item.\nfunc (c *Controller) enqueueNode(obj interface{}) {\n\tkey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)\n\tif err != nil {\n\t\truntime.HandleError(fmt.Errorf(\"couldn't get key for object %#v: %v\", obj, err))\n\t\treturn\n\t}\n\tc.nodeQueue.Add(key)\n}","line":{"from":199,"to":207}} {"id":100029573,"name":"Run","signature":"func (c *Controller) Run(ctx context.Context, workers int, controllerManagerMetrics *controllersmetrics.ControllerManagerMetrics)","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"// Run starts a background goroutine that watches for changes to services that\n// have (or had) LoadBalancers=true and ensures that they have\n// load balancers created and deleted appropriately.\n// serviceSyncPeriod controls how often we check the cluster's services to\n// ensure that the correct load balancers exist.\n// nodeSyncPeriod controls how often we check the cluster's nodes to determine\n// if load balancers need to be updated to point to a new set.\n//\n// It's an error to call Run() more than once for a given ServiceController\n// object.\nfunc (c *Controller) Run(ctx context.Context, workers int, controllerManagerMetrics *controllersmetrics.ControllerManagerMetrics) {\n\tdefer runtime.HandleCrash()\n\tdefer c.serviceQueue.ShutDown()\n\tdefer c.nodeQueue.ShutDown()\n\n\t// Start event processing pipeline.\n\tc.eventBroadcaster.StartStructuredLogging(0)\n\tc.eventBroadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: c.kubeClient.CoreV1().Events(\"\")})\n\tdefer c.eventBroadcaster.Shutdown()\n\n\tklog.Info(\"Starting service controller\")\n\tdefer klog.Info(\"Shutting down service controller\")\n\tcontrollerManagerMetrics.ControllerStarted(\"service\")\n\tdefer controllerManagerMetrics.ControllerStopped(\"service\")\n\n\tif !cache.WaitForNamedCacheSync(\"service\", ctx.Done(), c.serviceListerSynced, c.nodeListerSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.UntilWithContext(ctx, c.serviceWorker, time.Second)\n\t}\n\n\t// Initialize one go-routine servicing node events. This ensure we only\n\t// process one node at any given moment in time\n\tgo wait.UntilWithContext(ctx, func(ctx context.Context) { c.nodeWorker(ctx, workers) }, time.Second)\n\n\t\u003c-ctx.Done()\n}","line":{"from":209,"to":247}} {"id":100029574,"name":"serviceWorker","signature":"func (c *Controller) serviceWorker(ctx context.Context)","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"// worker runs a worker thread that just dequeues items, processes them, and marks them done.\n// It enforces that the syncHandler is never invoked concurrently with the same key.\nfunc (c *Controller) serviceWorker(ctx context.Context) {\n\tfor c.processNextServiceItem(ctx) {\n\t}\n}","line":{"from":249,"to":254}} {"id":100029575,"name":"nodeWorker","signature":"func (c *Controller) nodeWorker(ctx context.Context, workers int)","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"// worker runs a worker thread that just dequeues items, processes them, and marks them done.\n// It enforces that the syncHandler is never invoked concurrently with the same key.\nfunc (c *Controller) nodeWorker(ctx context.Context, workers int) {\n\tfor c.processNextNodeItem(ctx, workers) {\n\t}\n}","line":{"from":256,"to":261}} {"id":100029576,"name":"processNextNodeItem","signature":"func (c *Controller) processNextNodeItem(ctx context.Context, workers int) bool","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"func (c *Controller) processNextNodeItem(ctx context.Context, workers int) bool {\n\tkey, quit := c.nodeQueue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.nodeQueue.Done(key)\n\n\tfor serviceToRetry := range c.syncNodes(ctx, workers) {\n\t\tc.serviceQueue.Add(serviceToRetry)\n\t}\n\n\tc.nodeQueue.Forget(key)\n\treturn true\n}","line":{"from":263,"to":276}} {"id":100029577,"name":"processNextServiceItem","signature":"func (c *Controller) processNextServiceItem(ctx context.Context) bool","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"func (c *Controller) processNextServiceItem(ctx context.Context) bool {\n\tkey, quit := c.serviceQueue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.serviceQueue.Done(key)\n\n\terr := c.syncService(ctx, key.(string))\n\tif err == nil {\n\t\tc.serviceQueue.Forget(key)\n\t\treturn true\n\t}\n\n\truntime.HandleError(fmt.Errorf(\"error processing service %v (will retry): %v\", key, err))\n\tc.serviceQueue.AddRateLimited(key)\n\treturn true\n}","line":{"from":278,"to":294}} {"id":100029578,"name":"init","signature":"func (c *Controller) init() error","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"func (c *Controller) init() error {\n\tif c.cloud == nil {\n\t\treturn fmt.Errorf(\"WARNING: no cloud provider provided, services of type LoadBalancer will fail\")\n\t}\n\n\tbalancer, ok := c.cloud.LoadBalancer()\n\tif !ok {\n\t\treturn fmt.Errorf(\"the cloud provider does not support external load balancers\")\n\t}\n\tc.balancer = balancer\n\n\treturn nil\n}","line":{"from":296,"to":308}} {"id":100029579,"name":"processServiceCreateOrUpdate","signature":"func (c *Controller) processServiceCreateOrUpdate(ctx context.Context, service *v1.Service, key string) error","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"// processServiceCreateOrUpdate operates loadbalancers for the incoming service accordingly.\n// Returns an error if processing the service update failed.\nfunc (c *Controller) processServiceCreateOrUpdate(ctx context.Context, service *v1.Service, key string) error {\n\t// TODO(@MrHohn): Remove the cache once we get rid of the non-finalizer deletion\n\t// path. Ref https://github.com/kubernetes/enhancements/issues/980.\n\tcachedService := c.cache.getOrCreate(key)\n\tif cachedService.state != nil \u0026\u0026 cachedService.state.UID != service.UID {\n\t\t// This happens only when a service is deleted and re-created\n\t\t// in a short period, which is only possible when it doesn't\n\t\t// contain finalizer.\n\t\tif err := c.processLoadBalancerDelete(ctx, cachedService.state, key); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// Always cache the service, we need the info for service deletion in case\n\t// when load balancer cleanup is not handled via finalizer.\n\tcachedService.state = service\n\top, err := c.syncLoadBalancerIfNeeded(ctx, service, key)\n\tif err != nil {\n\t\tc.eventRecorder.Eventf(service, v1.EventTypeWarning, \"SyncLoadBalancerFailed\", \"Error syncing load balancer: %v\", err)\n\t\treturn err\n\t}\n\tif op == deleteLoadBalancer {\n\t\t// Only delete the cache upon successful load balancer deletion.\n\t\tc.cache.delete(key)\n\t}\n\n\treturn nil\n}","line":{"from":310,"to":338}} {"id":100029580,"name":"syncLoadBalancerIfNeeded","signature":"func (c *Controller) syncLoadBalancerIfNeeded(ctx context.Context, service *v1.Service, key string) (loadBalancerOperation, error)","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"// syncLoadBalancerIfNeeded ensures that service's status is synced up with loadbalancer\n// i.e. creates loadbalancer for service if requested and deletes loadbalancer if the service\n// doesn't want a loadbalancer no more. Returns whatever error occurred.\nfunc (c *Controller) syncLoadBalancerIfNeeded(ctx context.Context, service *v1.Service, key string) (loadBalancerOperation, error) {\n\t// Note: It is safe to just call EnsureLoadBalancer. But, on some clouds that requires a delete \u0026 create,\n\t// which may involve service interruption. Also, we would like user-friendly events.\n\n\t// Save the state so we can avoid a write if it doesn't change\n\tpreviousStatus := service.Status.LoadBalancer.DeepCopy()\n\tvar newStatus *v1.LoadBalancerStatus\n\tvar op loadBalancerOperation\n\tvar err error\n\n\tif !wantsLoadBalancer(service) || needsCleanup(service) {\n\t\t// Delete the load balancer if service no longer wants one, or if service needs cleanup.\n\t\top = deleteLoadBalancer\n\t\tnewStatus = \u0026v1.LoadBalancerStatus{}\n\t\t_, exists, err := c.balancer.GetLoadBalancer(ctx, c.clusterName, service)\n\t\tif err != nil {\n\t\t\treturn op, fmt.Errorf(\"failed to check if load balancer exists before cleanup: %v\", err)\n\t\t}\n\t\tif exists {\n\t\t\tklog.V(2).Infof(\"Deleting existing load balancer for service %s\", key)\n\t\t\tc.eventRecorder.Event(service, v1.EventTypeNormal, \"DeletingLoadBalancer\", \"Deleting load balancer\")\n\t\t\tif err := c.balancer.EnsureLoadBalancerDeleted(ctx, c.clusterName, service); err != nil {\n\t\t\t\tif err == cloudprovider.ImplementedElsewhere {\n\t\t\t\t\tklog.V(4).Infof(\"LoadBalancer for service %s implemented by a different controller %s, Ignoring error on deletion\", key, c.cloud.ProviderName())\n\t\t\t\t} else {\n\t\t\t\t\treturn op, fmt.Errorf(\"failed to delete load balancer: %v\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Always remove finalizer when load balancer is deleted, this ensures Services\n\t\t// can be deleted after all corresponding load balancer resources are deleted.\n\t\tif err := c.removeFinalizer(service); err != nil {\n\t\t\treturn op, fmt.Errorf(\"failed to remove load balancer cleanup finalizer: %v\", err)\n\t\t}\n\t\tc.eventRecorder.Event(service, v1.EventTypeNormal, \"DeletedLoadBalancer\", \"Deleted load balancer\")\n\t} else {\n\t\t// Create or update the load balancer if service wants one.\n\t\top = ensureLoadBalancer\n\t\tklog.V(2).Infof(\"Ensuring load balancer for service %s\", key)\n\t\tc.eventRecorder.Event(service, v1.EventTypeNormal, \"EnsuringLoadBalancer\", \"Ensuring load balancer\")\n\t\t// Always add a finalizer prior to creating load balancers, this ensures Services\n\t\t// can't be deleted until all corresponding load balancer resources are also deleted.\n\t\tif err := c.addFinalizer(service); err != nil {\n\t\t\treturn op, fmt.Errorf(\"failed to add load balancer cleanup finalizer: %v\", err)\n\t\t}\n\t\tnewStatus, err = c.ensureLoadBalancer(ctx, service)\n\t\tif err != nil {\n\t\t\tif err == cloudprovider.ImplementedElsewhere {\n\t\t\t\t// ImplementedElsewhere indicates that the ensureLoadBalancer is a nop and the\n\t\t\t\t// functionality is implemented by a different controller. In this case, we\n\t\t\t\t// return immediately without doing anything.\n\t\t\t\tklog.V(4).Infof(\"LoadBalancer for service %s implemented by a different controller %s, Ignoring error\", key, c.cloud.ProviderName())\n\t\t\t\treturn op, nil\n\t\t\t}\n\t\t\treturn op, fmt.Errorf(\"failed to ensure load balancer: %v\", err)\n\t\t}\n\t\tif newStatus == nil {\n\t\t\treturn op, fmt.Errorf(\"service status returned by EnsureLoadBalancer is nil\")\n\t\t}\n\n\t\tc.eventRecorder.Event(service, v1.EventTypeNormal, \"EnsuredLoadBalancer\", \"Ensured load balancer\")\n\t}\n\n\tif err := c.patchStatus(service, previousStatus, newStatus); err != nil {\n\t\t// Only retry error that isn't not found:\n\t\t// - Not found error mostly happens when service disappears right after\n\t\t// we remove the finalizer.\n\t\t// - We can't patch status on non-exist service anyway.\n\t\tif !errors.IsNotFound(err) {\n\t\t\treturn op, fmt.Errorf(\"failed to update load balancer status: %v\", err)\n\t\t}\n\t}\n\n\treturn op, nil\n}","line":{"from":347,"to":424}} {"id":100029581,"name":"ensureLoadBalancer","signature":"func (c *Controller) ensureLoadBalancer(ctx context.Context, service *v1.Service) (*v1.LoadBalancerStatus, error)","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"func (c *Controller) ensureLoadBalancer(ctx context.Context, service *v1.Service) (*v1.LoadBalancerStatus, error) {\n\tnodes, err := listWithPredicates(c.nodeLister, getNodePredicatesForService(service)...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// If there are no available nodes for LoadBalancer service, make a EventTypeWarning event for it.\n\tif len(nodes) == 0 {\n\t\tc.eventRecorder.Event(service, v1.EventTypeWarning, \"UnAvailableLoadBalancer\", \"There are no available nodes for LoadBalancer\")\n\t}\n\n\t// - Only one protocol supported per service\n\t// - Not all cloud providers support all protocols and the next step is expected to return\n\t// an error for unsupported protocols\n\treturn c.balancer.EnsureLoadBalancer(ctx, c.clusterName, service, nodes)\n}","line":{"from":426,"to":441}} {"id":100029582,"name":"ListKeys","signature":"func (s *serviceCache) ListKeys() []string","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"// ListKeys implements the interface required by DeltaFIFO to list the keys we\n// already know about.\nfunc (s *serviceCache) ListKeys() []string {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\tkeys := make([]string, 0, len(s.serviceMap))\n\tfor k := range s.serviceMap {\n\t\tkeys = append(keys, k)\n\t}\n\treturn keys\n}","line":{"from":443,"to":453}} {"id":100029583,"name":"GetByKey","signature":"func (s *serviceCache) GetByKey(key string) (interface{}, bool, error)","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"// GetByKey returns the value stored in the serviceMap under the given key\nfunc (s *serviceCache) GetByKey(key string) (interface{}, bool, error) {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\tif v, ok := s.serviceMap[key]; ok {\n\t\treturn v, true, nil\n\t}\n\treturn nil, false, nil\n}","line":{"from":455,"to":463}} {"id":100029584,"name":"allServices","signature":"func (s *serviceCache) allServices() []*v1.Service","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"// ListKeys implements the interface required by DeltaFIFO to list the keys we\n// already know about.\nfunc (s *serviceCache) allServices() []*v1.Service {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\tservices := make([]*v1.Service, 0, len(s.serviceMap))\n\tfor _, v := range s.serviceMap {\n\t\tservices = append(services, v.state)\n\t}\n\treturn services\n}","line":{"from":465,"to":475}} {"id":100029585,"name":"get","signature":"func (s *serviceCache) get(serviceName string) (*cachedService, bool)","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"func (s *serviceCache) get(serviceName string) (*cachedService, bool) {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\tservice, ok := s.serviceMap[serviceName]\n\treturn service, ok\n}","line":{"from":477,"to":482}} {"id":100029586,"name":"getOrCreate","signature":"func (s *serviceCache) getOrCreate(serviceName string) *cachedService","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"func (s *serviceCache) getOrCreate(serviceName string) *cachedService {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tservice, ok := s.serviceMap[serviceName]\n\tif !ok {\n\t\tservice = \u0026cachedService{}\n\t\ts.serviceMap[serviceName] = service\n\t}\n\treturn service\n}","line":{"from":484,"to":493}} {"id":100029587,"name":"set","signature":"func (s *serviceCache) set(serviceName string, service *cachedService)","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"func (s *serviceCache) set(serviceName string, service *cachedService) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\ts.serviceMap[serviceName] = service\n}","line":{"from":495,"to":499}} {"id":100029588,"name":"delete","signature":"func (s *serviceCache) delete(serviceName string)","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"func (s *serviceCache) delete(serviceName string) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tdelete(s.serviceMap, serviceName)\n}","line":{"from":501,"to":505}} {"id":100029589,"name":"needsCleanup","signature":"func needsCleanup(service *v1.Service) bool","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"// needsCleanup checks if load balancer needs to be cleaned up as indicated by finalizer.\nfunc needsCleanup(service *v1.Service) bool {\n\tif !servicehelper.HasLBFinalizer(service) {\n\t\treturn false\n\t}\n\n\tif service.ObjectMeta.DeletionTimestamp != nil {\n\t\treturn true\n\t}\n\n\t// Service doesn't want loadBalancer but owns loadBalancer finalizer also need to be cleaned up.\n\tif service.Spec.Type != v1.ServiceTypeLoadBalancer {\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":507,"to":523}} {"id":100029590,"name":"needsUpdate","signature":"func (c *Controller) needsUpdate(oldService *v1.Service, newService *v1.Service) bool","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"// needsUpdate checks if load balancer needs to be updated due to change in attributes.\nfunc (c *Controller) needsUpdate(oldService *v1.Service, newService *v1.Service) bool {\n\tif !wantsLoadBalancer(oldService) \u0026\u0026 !wantsLoadBalancer(newService) {\n\t\treturn false\n\t}\n\tif wantsLoadBalancer(oldService) != wantsLoadBalancer(newService) {\n\t\tc.eventRecorder.Eventf(newService, v1.EventTypeNormal, \"Type\", \"%v -\u003e %v\",\n\t\t\toldService.Spec.Type, newService.Spec.Type)\n\t\treturn true\n\t}\n\n\tif wantsLoadBalancer(newService) \u0026\u0026 !reflect.DeepEqual(oldService.Spec.LoadBalancerSourceRanges, newService.Spec.LoadBalancerSourceRanges) {\n\t\tc.eventRecorder.Eventf(newService, v1.EventTypeNormal, \"LoadBalancerSourceRanges\", \"%v -\u003e %v\",\n\t\t\toldService.Spec.LoadBalancerSourceRanges, newService.Spec.LoadBalancerSourceRanges)\n\t\treturn true\n\t}\n\n\tif !portsEqualForLB(oldService, newService) || oldService.Spec.SessionAffinity != newService.Spec.SessionAffinity {\n\t\treturn true\n\t}\n\n\tif !reflect.DeepEqual(oldService.Spec.SessionAffinityConfig, newService.Spec.SessionAffinityConfig) {\n\t\treturn true\n\t}\n\tif !loadBalancerIPsAreEqual(oldService, newService) {\n\t\tc.eventRecorder.Eventf(newService, v1.EventTypeNormal, \"LoadbalancerIP\", \"%v -\u003e %v\",\n\t\t\toldService.Spec.LoadBalancerIP, newService.Spec.LoadBalancerIP)\n\t\treturn true\n\t}\n\tif len(oldService.Spec.ExternalIPs) != len(newService.Spec.ExternalIPs) {\n\t\tc.eventRecorder.Eventf(newService, v1.EventTypeNormal, \"ExternalIP\", \"Count: %v -\u003e %v\",\n\t\t\tlen(oldService.Spec.ExternalIPs), len(newService.Spec.ExternalIPs))\n\t\treturn true\n\t}\n\tfor i := range oldService.Spec.ExternalIPs {\n\t\tif oldService.Spec.ExternalIPs[i] != newService.Spec.ExternalIPs[i] {\n\t\t\tc.eventRecorder.Eventf(newService, v1.EventTypeNormal, \"ExternalIP\", \"Added: %v\",\n\t\t\t\tnewService.Spec.ExternalIPs[i])\n\t\t\treturn true\n\t\t}\n\t}\n\tif !reflect.DeepEqual(oldService.Annotations, newService.Annotations) {\n\t\treturn true\n\t}\n\tif oldService.UID != newService.UID {\n\t\tc.eventRecorder.Eventf(newService, v1.EventTypeNormal, \"UID\", \"%v -\u003e %v\",\n\t\t\toldService.UID, newService.UID)\n\t\treturn true\n\t}\n\tif oldService.Spec.ExternalTrafficPolicy != newService.Spec.ExternalTrafficPolicy {\n\t\tc.eventRecorder.Eventf(newService, v1.EventTypeNormal, \"ExternalTrafficPolicy\", \"%v -\u003e %v\",\n\t\t\toldService.Spec.ExternalTrafficPolicy, newService.Spec.ExternalTrafficPolicy)\n\t\treturn true\n\t}\n\tif oldService.Spec.HealthCheckNodePort != newService.Spec.HealthCheckNodePort {\n\t\tc.eventRecorder.Eventf(newService, v1.EventTypeNormal, \"HealthCheckNodePort\", \"%v -\u003e %v\",\n\t\t\toldService.Spec.HealthCheckNodePort, newService.Spec.HealthCheckNodePort)\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":525,"to":586}} {"id":100029591,"name":"getPortsForLB","signature":"func getPortsForLB(service *v1.Service) []*v1.ServicePort","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"func getPortsForLB(service *v1.Service) []*v1.ServicePort {\n\tports := []*v1.ServicePort{}\n\tfor i := range service.Spec.Ports {\n\t\tsp := \u0026service.Spec.Ports[i]\n\t\tports = append(ports, sp)\n\t}\n\treturn ports\n}","line":{"from":588,"to":595}} {"id":100029592,"name":"portsEqualForLB","signature":"func portsEqualForLB(x, y *v1.Service) bool","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"func portsEqualForLB(x, y *v1.Service) bool {\n\txPorts := getPortsForLB(x)\n\tyPorts := getPortsForLB(y)\n\treturn portSlicesEqualForLB(xPorts, yPorts)\n}","line":{"from":597,"to":601}} {"id":100029593,"name":"portSlicesEqualForLB","signature":"func portSlicesEqualForLB(x, y []*v1.ServicePort) bool","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"func portSlicesEqualForLB(x, y []*v1.ServicePort) bool {\n\tif len(x) != len(y) {\n\t\treturn false\n\t}\n\n\tfor i := range x {\n\t\tif !portEqualForLB(x[i], y[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":603,"to":614}} {"id":100029594,"name":"portEqualForLB","signature":"func portEqualForLB(x, y *v1.ServicePort) bool","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"func portEqualForLB(x, y *v1.ServicePort) bool {\n\t// TODO: Should we check name? (In theory, an LB could expose it)\n\tif x.Name != y.Name {\n\t\treturn false\n\t}\n\n\tif x.Protocol != y.Protocol {\n\t\treturn false\n\t}\n\n\tif x.Port != y.Port {\n\t\treturn false\n\t}\n\n\tif x.NodePort != y.NodePort {\n\t\treturn false\n\t}\n\n\tif x.TargetPort != y.TargetPort {\n\t\treturn false\n\t}\n\n\tif !reflect.DeepEqual(x.AppProtocol, y.AppProtocol) {\n\t\treturn false\n\t}\n\n\treturn true\n}","line":{"from":616,"to":643}} {"id":100029595,"name":"serviceKeys","signature":"func serviceKeys(services []*v1.Service) sets.String","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"func serviceKeys(services []*v1.Service) sets.String {\n\tret := sets.NewString()\n\tfor _, service := range services {\n\t\tkey, _ := cache.MetaNamespaceKeyFunc(service)\n\t\tret.Insert(key)\n\t}\n\treturn ret\n}","line":{"from":645,"to":652}} {"id":100029596,"name":"nodeNames","signature":"func nodeNames(nodes []*v1.Node) sets.String","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"func nodeNames(nodes []*v1.Node) sets.String {\n\tret := sets.NewString()\n\tfor _, node := range nodes {\n\t\tret.Insert(node.Name)\n\t}\n\treturn ret\n}","line":{"from":654,"to":660}} {"id":100029597,"name":"shouldSyncUpdatedNode","signature":"func shouldSyncUpdatedNode(oldNode, newNode *v1.Node) bool","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"func shouldSyncUpdatedNode(oldNode, newNode *v1.Node) bool {\n\t// Evaluate the individual node exclusion predicate before evaluating the\n\t// compounded result of all predicates. We don't sync changes on the\n\t// readiness condition for eTP:Local services or when\n\t// StableLoadBalancerNodeSet is enabled, hence if a node remains NotReady\n\t// and a user adds the exclusion label we will need to sync as to make sure\n\t// this change is reflected correctly on ETP=local services. The sync\n\t// function compares lastSyncedNodes with the new (existing) set of nodes\n\t// for each service, so services which are synced with the same set of nodes\n\t// should be skipped internally in the sync function. This is needed as to\n\t// trigger a global sync for all services and make sure no service gets\n\t// skipped due to a changing node predicate.\n\tif respectsPredicates(oldNode, nodeIncludedPredicate) != respectsPredicates(newNode, nodeIncludedPredicate) {\n\t\treturn true\n\t}\n\t// For the same reason as above, also check for changes to the providerID\n\tif respectsPredicates(oldNode, nodeHasProviderIDPredicate) != respectsPredicates(newNode, nodeHasProviderIDPredicate) {\n\t\treturn true\n\t}\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.StableLoadBalancerNodeSet) {\n\t\treturn respectsPredicates(oldNode, allNodePredicates...) != respectsPredicates(newNode, allNodePredicates...)\n\t}\n\treturn false\n}","line":{"from":662,"to":685}} {"id":100029598,"name":"syncNodes","signature":"func (c *Controller) syncNodes(ctx context.Context, workers int) sets.String","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"// syncNodes handles updating the hosts pointed to by all load\n// balancers whenever the set of nodes in the cluster changes.\nfunc (c *Controller) syncNodes(ctx context.Context, workers int) sets.String {\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tlatency := time.Since(startTime).Seconds()\n\t\tklog.V(4).Infof(\"It took %v seconds to finish syncNodes\", latency)\n\t\tnodeSyncLatency.Observe(latency)\n\t}()\n\n\tklog.V(2).Infof(\"Syncing backends for all LB services.\")\n\tservicesToUpdate := c.cache.allServices()\n\tnumServices := len(servicesToUpdate)\n\tservicesToRetry := c.updateLoadBalancerHosts(ctx, servicesToUpdate, workers)\n\tklog.V(2).Infof(\"Successfully updated %d out of %d load balancers to direct traffic to the updated set of nodes\",\n\t\tnumServices-len(servicesToRetry), numServices)\n\treturn servicesToRetry\n}","line":{"from":687,"to":704}} {"id":100029599,"name":"nodeSyncService","signature":"func (c *Controller) nodeSyncService(svc *v1.Service, oldNodes, newNodes []*v1.Node) bool","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"// nodeSyncService syncs the nodes for one load balancer type service. The return value\n// indicates if we should retry. Hence, this functions returns false if we've updated\n// load balancers and finished doing it successfully, or didn't try to at all because\n// there's no need. This function returns true if we tried to update load balancers and\n// failed, indicating to the caller that we should try again.\nfunc (c *Controller) nodeSyncService(svc *v1.Service, oldNodes, newNodes []*v1.Node) bool {\n\tconst retSuccess = false\n\tconst retNeedRetry = true\n\tif svc == nil || !wantsLoadBalancer(svc) {\n\t\treturn retSuccess\n\t}\n\tnewNodes = filterWithPredicates(newNodes, getNodePredicatesForService(svc)...)\n\toldNodes = filterWithPredicates(oldNodes, getNodePredicatesForService(svc)...)\n\tif nodeNames(newNodes).Equal(nodeNames(oldNodes)) {\n\t\treturn retSuccess\n\t}\n\tklog.V(4).Infof(\"nodeSyncService started for service %s/%s\", svc.Namespace, svc.Name)\n\tif err := c.lockedUpdateLoadBalancerHosts(svc, newNodes); err != nil {\n\t\truntime.HandleError(fmt.Errorf(\"failed to update load balancer hosts for service %s/%s: %v\", svc.Namespace, svc.Name, err))\n\t\tnodeSyncErrorCount.Inc()\n\t\treturn retNeedRetry\n\t}\n\tklog.V(4).Infof(\"nodeSyncService finished successfully for service %s/%s\", svc.Namespace, svc.Name)\n\treturn retSuccess\n}","line":{"from":706,"to":730}} {"id":100029600,"name":"updateLoadBalancerHosts","signature":"func (c *Controller) updateLoadBalancerHosts(ctx context.Context, services []*v1.Service, workers int) (servicesToRetry sets.String)","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"// updateLoadBalancerHosts updates all existing load balancers so that\n// they will match the latest list of nodes with input number of workers.\n// Returns the list of services that couldn't be updated.\nfunc (c *Controller) updateLoadBalancerHosts(ctx context.Context, services []*v1.Service, workers int) (servicesToRetry sets.String) {\n\tklog.V(4).Infof(\"Running updateLoadBalancerHosts(len(services)==%d, workers==%d)\", len(services), workers)\n\n\t// Include all nodes and let nodeSyncService filter and figure out if\n\t// the update is relevant for the service in question.\n\tnodes, err := listWithPredicates(c.nodeLister)\n\tif err != nil {\n\t\truntime.HandleError(fmt.Errorf(\"failed to retrieve node list: %v\", err))\n\t\treturn serviceKeys(services)\n\t}\n\n\t// lock for servicesToRetry\n\tservicesToRetry = sets.NewString()\n\tlock := sync.Mutex{}\n\n\tdoWork := func(piece int) {\n\t\tif shouldRetry := c.nodeSyncService(services[piece], c.lastSyncedNodes, nodes); !shouldRetry {\n\t\t\treturn\n\t\t}\n\t\tlock.Lock()\n\t\tdefer lock.Unlock()\n\t\tkey := fmt.Sprintf(\"%s/%s\", services[piece].Namespace, services[piece].Name)\n\t\tservicesToRetry.Insert(key)\n\t}\n\tworkqueue.ParallelizeUntil(ctx, workers, len(services), doWork)\n\tc.lastSyncedNodes = nodes\n\tklog.V(4).Infof(\"Finished updateLoadBalancerHosts\")\n\treturn servicesToRetry\n}","line":{"from":732,"to":763}} {"id":100029601,"name":"lockedUpdateLoadBalancerHosts","signature":"func (c *Controller) lockedUpdateLoadBalancerHosts(service *v1.Service, hosts []*v1.Node) error","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"// Updates the load balancer of a service, assuming we hold the mutex\n// associated with the service.\nfunc (c *Controller) lockedUpdateLoadBalancerHosts(service *v1.Service, hosts []*v1.Node) error {\n\tstartTime := time.Now()\n\tloadBalancerSyncCount.Inc()\n\tdefer func() {\n\t\tlatency := time.Since(startTime).Seconds()\n\t\tklog.V(4).Infof(\"It took %v seconds to update load balancer hosts for service %s/%s\", latency, service.Namespace, service.Name)\n\t\tupdateLoadBalancerHostLatency.Observe(latency)\n\t}()\n\n\tklog.V(2).Infof(\"Updating backends for load balancer %s/%s with node set: %v\", service.Namespace, service.Name, nodeNames(hosts))\n\t// This operation doesn't normally take very long (and happens pretty often), so we only record the final event\n\terr := c.balancer.UpdateLoadBalancer(context.TODO(), c.clusterName, service, hosts)\n\tif err == nil {\n\t\t// If there are no available nodes for LoadBalancer service, make a EventTypeWarning event for it.\n\t\tif len(hosts) == 0 {\n\t\t\tc.eventRecorder.Event(service, v1.EventTypeWarning, \"UnAvailableLoadBalancer\", \"There are no available nodes for LoadBalancer\")\n\t\t} else {\n\t\t\tc.eventRecorder.Event(service, v1.EventTypeNormal, \"UpdatedLoadBalancer\", \"Updated load balancer with new hosts\")\n\t\t}\n\t\treturn nil\n\t}\n\tif err == cloudprovider.ImplementedElsewhere {\n\t\t// ImplementedElsewhere indicates that the UpdateLoadBalancer is a nop and the\n\t\t// functionality is implemented by a different controller. In this case, we\n\t\t// return immediately without doing anything.\n\t\treturn nil\n\t}\n\t// It's only an actual error if the load balancer still exists.\n\tif _, exists, err := c.balancer.GetLoadBalancer(context.TODO(), c.clusterName, service); err != nil {\n\t\truntime.HandleError(fmt.Errorf(\"failed to check if load balancer exists for service %s/%s: %v\", service.Namespace, service.Name, err))\n\t} else if !exists {\n\t\treturn nil\n\t}\n\n\tc.eventRecorder.Eventf(service, v1.EventTypeWarning, \"UpdateLoadBalancerFailed\", \"Error updating load balancer with new hosts %v: %v\", nodeNames(hosts), err)\n\treturn err\n}","line":{"from":765,"to":803}} {"id":100029602,"name":"wantsLoadBalancer","signature":"func wantsLoadBalancer(service *v1.Service) bool","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"func wantsLoadBalancer(service *v1.Service) bool {\n\t// if LoadBalancerClass is set, the user does not want the default cloud-provider Load Balancer\n\treturn service.Spec.Type == v1.ServiceTypeLoadBalancer \u0026\u0026 service.Spec.LoadBalancerClass == nil\n}","line":{"from":805,"to":808}} {"id":100029603,"name":"loadBalancerIPsAreEqual","signature":"func loadBalancerIPsAreEqual(oldService, newService *v1.Service) bool","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"func loadBalancerIPsAreEqual(oldService, newService *v1.Service) bool {\n\treturn oldService.Spec.LoadBalancerIP == newService.Spec.LoadBalancerIP\n}","line":{"from":810,"to":812}} {"id":100029604,"name":"syncService","signature":"func (c *Controller) syncService(ctx context.Context, key string) error","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"// syncService will sync the Service with the given key if it has had its expectations fulfilled,\n// meaning it did not expect to see any more of its pods created or deleted. This function is not meant to be\n// invoked concurrently with the same key.\nfunc (c *Controller) syncService(ctx context.Context, key string) error {\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tklog.V(4).Infof(\"Finished syncing service %q (%v)\", key, time.Since(startTime))\n\t}()\n\n\tnamespace, name, err := cache.SplitMetaNamespaceKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// service holds the latest service info from apiserver\n\tservice, err := c.serviceLister.Services(namespace).Get(name)\n\tswitch {\n\tcase errors.IsNotFound(err):\n\t\t// service absence in store means watcher caught the deletion, ensure LB info is cleaned\n\t\terr = c.processServiceDeletion(ctx, key)\n\tcase err != nil:\n\t\truntime.HandleError(fmt.Errorf(\"Unable to retrieve service %v from store: %v\", key, err))\n\tdefault:\n\t\t// It is not safe to modify an object returned from an informer.\n\t\t// As reconcilers may modify the service object we need to copy\n\t\t// it first.\n\t\terr = c.processServiceCreateOrUpdate(ctx, service.DeepCopy(), key)\n\t}\n\n\treturn err\n}","line":{"from":814,"to":844}} {"id":100029605,"name":"processServiceDeletion","signature":"func (c *Controller) processServiceDeletion(ctx context.Context, key string) error","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"func (c *Controller) processServiceDeletion(ctx context.Context, key string) error {\n\tcachedService, ok := c.cache.get(key)\n\tif !ok {\n\t\t// Cache does not contains the key means:\n\t\t// - We didn't create a Load Balancer for the deleted service at all.\n\t\t// - We already deleted the Load Balancer that was created for the service.\n\t\t// In both cases we have nothing left to do.\n\t\treturn nil\n\t}\n\tklog.V(2).Infof(\"Service %v has been deleted. Attempting to cleanup load balancer resources\", key)\n\tif err := c.processLoadBalancerDelete(ctx, cachedService.state, key); err != nil {\n\t\treturn err\n\t}\n\tc.cache.delete(key)\n\treturn nil\n}","line":{"from":846,"to":861}} {"id":100029606,"name":"processLoadBalancerDelete","signature":"func (c *Controller) processLoadBalancerDelete(ctx context.Context, service *v1.Service, key string) error","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"func (c *Controller) processLoadBalancerDelete(ctx context.Context, service *v1.Service, key string) error {\n\t// delete load balancer info only if the service type is LoadBalancer\n\tif !wantsLoadBalancer(service) {\n\t\treturn nil\n\t}\n\tc.eventRecorder.Event(service, v1.EventTypeNormal, \"DeletingLoadBalancer\", \"Deleting load balancer\")\n\tif err := c.balancer.EnsureLoadBalancerDeleted(ctx, c.clusterName, service); err != nil {\n\t\tc.eventRecorder.Eventf(service, v1.EventTypeWarning, \"DeleteLoadBalancerFailed\", \"Error deleting load balancer: %v\", err)\n\t\treturn err\n\t}\n\tc.eventRecorder.Event(service, v1.EventTypeNormal, \"DeletedLoadBalancer\", \"Deleted load balancer\")\n\treturn nil\n}","line":{"from":863,"to":875}} {"id":100029607,"name":"addFinalizer","signature":"func (c *Controller) addFinalizer(service *v1.Service) error","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"// addFinalizer patches the service to add finalizer.\nfunc (c *Controller) addFinalizer(service *v1.Service) error {\n\tif servicehelper.HasLBFinalizer(service) {\n\t\treturn nil\n\t}\n\n\t// Make a copy so we don't mutate the shared informer cache.\n\tupdated := service.DeepCopy()\n\tupdated.ObjectMeta.Finalizers = append(updated.ObjectMeta.Finalizers, servicehelper.LoadBalancerCleanupFinalizer)\n\n\tklog.V(2).Infof(\"Adding finalizer to service %s/%s\", updated.Namespace, updated.Name)\n\t_, err := servicehelper.PatchService(c.kubeClient.CoreV1(), service, updated)\n\treturn err\n}","line":{"from":877,"to":890}} {"id":100029608,"name":"removeFinalizer","signature":"func (c *Controller) removeFinalizer(service *v1.Service) error","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"// removeFinalizer patches the service to remove finalizer.\nfunc (c *Controller) removeFinalizer(service *v1.Service) error {\n\tif !servicehelper.HasLBFinalizer(service) {\n\t\treturn nil\n\t}\n\n\t// Make a copy so we don't mutate the shared informer cache.\n\tupdated := service.DeepCopy()\n\tupdated.ObjectMeta.Finalizers = removeString(updated.ObjectMeta.Finalizers, servicehelper.LoadBalancerCleanupFinalizer)\n\n\tklog.V(2).Infof(\"Removing finalizer from service %s/%s\", updated.Namespace, updated.Name)\n\t_, err := servicehelper.PatchService(c.kubeClient.CoreV1(), service, updated)\n\treturn err\n}","line":{"from":892,"to":905}} {"id":100029609,"name":"removeString","signature":"func removeString(slice []string, s string) []string","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"// removeString returns a newly created []string that contains all items from slice that\n// are not equal to s.\nfunc removeString(slice []string, s string) []string {\n\tvar newSlice []string\n\tfor _, item := range slice {\n\t\tif item != s {\n\t\t\tnewSlice = append(newSlice, item)\n\t\t}\n\t}\n\treturn newSlice\n}","line":{"from":907,"to":917}} {"id":100029610,"name":"patchStatus","signature":"func (c *Controller) patchStatus(service *v1.Service, previousStatus, newStatus *v1.LoadBalancerStatus) error","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"// patchStatus patches the service with the given LoadBalancerStatus.\nfunc (c *Controller) patchStatus(service *v1.Service, previousStatus, newStatus *v1.LoadBalancerStatus) error {\n\tif servicehelper.LoadBalancerStatusEqual(previousStatus, newStatus) {\n\t\treturn nil\n\t}\n\t// Make a copy so we don't mutate the shared informer cache.\n\tupdated := service.DeepCopy()\n\tupdated.Status.LoadBalancer = *newStatus\n\n\tklog.V(2).Infof(\"Patching status for service %s/%s\", updated.Namespace, updated.Name)\n\t_, err := servicehelper.PatchService(c.kubeClient.CoreV1(), service, updated)\n\treturn err\n}","line":{"from":919,"to":931}} {"id":100029611,"name":"getNodePredicatesForService","signature":"func getNodePredicatesForService(service *v1.Service) []NodeConditionPredicate","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"func getNodePredicatesForService(service *v1.Service) []NodeConditionPredicate {\n\tif utilfeature.DefaultFeatureGate.Enabled(features.StableLoadBalancerNodeSet) {\n\t\treturn stableNodeSetPredicates\n\t}\n\tif service.Spec.ExternalTrafficPolicy == v1.ServiceExternalTrafficPolicyLocal {\n\t\treturn etpLocalNodePredicates\n\t}\n\treturn allNodePredicates\n}","line":{"from":962,"to":970}} {"id":100029612,"name":"nodeIncludedPredicate","signature":"func nodeIncludedPredicate(node *v1.Node) bool","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"// We consider the node for load balancing only when the node is not labelled for exclusion.\nfunc nodeIncludedPredicate(node *v1.Node) bool {\n\t_, hasExcludeBalancerLabel := node.Labels[v1.LabelNodeExcludeBalancers]\n\treturn !hasExcludeBalancerLabel\n}","line":{"from":972,"to":976}} {"id":100029613,"name":"nodeHasProviderIDPredicate","signature":"func nodeHasProviderIDPredicate(node *v1.Node) bool","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"func nodeHasProviderIDPredicate(node *v1.Node) bool {\n\treturn node.Spec.ProviderID != \"\"\n}","line":{"from":978,"to":980}} {"id":100029614,"name":"nodeUnTaintedPredicate","signature":"func nodeUnTaintedPredicate(node *v1.Node) bool","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"// We consider the node for load balancing only when its not tainted for deletion by the cluster autoscaler.\nfunc nodeUnTaintedPredicate(node *v1.Node) bool {\n\tfor _, taint := range node.Spec.Taints {\n\t\tif taint.Key == ToBeDeletedTaint {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":982,"to":990}} {"id":100029615,"name":"nodeReadyPredicate","signature":"func nodeReadyPredicate(node *v1.Node) bool","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"// We consider the node for load balancing only when its NodeReady condition status is ConditionTrue\nfunc nodeReadyPredicate(node *v1.Node) bool {\n\tfor _, cond := range node.Status.Conditions {\n\t\tif cond.Type == v1.NodeReady {\n\t\t\treturn cond.Status == v1.ConditionTrue\n\t\t}\n\t}\n\treturn false\n}","line":{"from":992,"to":1000}} {"id":100029616,"name":"nodeNotDeletedPredicate","signature":"func nodeNotDeletedPredicate(node *v1.Node) bool","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"func nodeNotDeletedPredicate(node *v1.Node) bool {\n\treturn node.DeletionTimestamp.IsZero()\n}","line":{"from":1002,"to":1004}} {"id":100029617,"name":"listWithPredicates","signature":"func listWithPredicates(nodeLister corelisters.NodeLister, predicates ...NodeConditionPredicate) ([]*v1.Node, error)","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"// listWithPredicate gets nodes that matches all predicate functions.\nfunc listWithPredicates(nodeLister corelisters.NodeLister, predicates ...NodeConditionPredicate) ([]*v1.Node, error) {\n\tnodes, err := nodeLister.List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn filterWithPredicates(nodes, predicates...), nil\n}","line":{"from":1006,"to":1013}} {"id":100029618,"name":"filterWithPredicates","signature":"func filterWithPredicates(nodes []*v1.Node, predicates ...NodeConditionPredicate) []*v1.Node","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"func filterWithPredicates(nodes []*v1.Node, predicates ...NodeConditionPredicate) []*v1.Node {\n\tvar filtered []*v1.Node\n\tfor i := range nodes {\n\t\tif respectsPredicates(nodes[i], predicates...) {\n\t\t\tfiltered = append(filtered, nodes[i])\n\t\t}\n\t}\n\treturn filtered\n}","line":{"from":1015,"to":1023}} {"id":100029619,"name":"respectsPredicates","signature":"func respectsPredicates(node *v1.Node, predicates ...NodeConditionPredicate) bool","file":"staging/src/k8s.io/cloud-provider/controllers/service/controller.go","code":"func respectsPredicates(node *v1.Node, predicates ...NodeConditionPredicate) bool {\n\tfor _, p := range predicates {\n\t\tif !p(node) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":1025,"to":1032}} {"id":100029620,"name":"registerMetrics","signature":"func registerMetrics()","file":"staging/src/k8s.io/cloud-provider/controllers/service/metrics.go","code":"// registerMetrics registers service-controller metrics.\nfunc registerMetrics() {\n\tregister.Do(func() {\n\t\tlegacyregistry.MustRegister(loadBalancerSyncCount)\n\t\tlegacyregistry.MustRegister(nodeSyncLatency)\n\t\tlegacyregistry.MustRegister(nodeSyncErrorCount)\n\t\tlegacyregistry.MustRegister(updateLoadBalancerHostLatency)\n\t})\n}","line":{"from":33,"to":41}} {"id":100029621,"name":"AddToNodeAddresses","signature":"func AddToNodeAddresses(addresses *[]v1.NodeAddress, addAddresses ...v1.NodeAddress)","file":"staging/src/k8s.io/cloud-provider/node/helpers/address.go","code":"// AddToNodeAddresses appends the NodeAddresses to the passed-by-pointer slice,\n// only if they do not already exist\nfunc AddToNodeAddresses(addresses *[]v1.NodeAddress, addAddresses ...v1.NodeAddress) {\n\tfor _, add := range addAddresses {\n\t\texists := false\n\t\tfor _, existing := range *addresses {\n\t\t\tif existing.Address == add.Address \u0026\u0026 existing.Type == add.Type {\n\t\t\t\texists = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !exists {\n\t\t\t*addresses = append(*addresses, add)\n\t\t}\n\t}\n}","line":{"from":28,"to":43}} {"id":100029622,"name":"GetNodeAddressesFromNodeIPLegacy","signature":"func GetNodeAddressesFromNodeIPLegacy(nodeIP net.IP, cloudNodeAddresses []v1.NodeAddress) ([]v1.NodeAddress, error)","file":"staging/src/k8s.io/cloud-provider/node/helpers/address.go","code":"// GetNodeAddressesFromNodeIPLegacy filters node addresses to prefer a specific node IP or\n// address family. This function is used only with legacy cloud providers.\n//\n// If nodeIP is either '0.0.0.0' or '::' it is taken to represent any address of\n// that address family: IPv4 or IPv6. i.e. if nodeIP is '0.0.0.0' we will return\n// node addresses sorted such that all IPv4 addresses are listed before IPv6\n// addresses.\n//\n// If nodeIP is a specific IP, either IPv4 or IPv6, we will return node\n// addresses filtered such that:\n// - Any address matching nodeIP will be listed first.\n// - If nodeIP matches an address of a particular type (internal or external),\n// that will be the *only* address of that type returned.\n// - All remaining addresses are listed after.\nfunc GetNodeAddressesFromNodeIPLegacy(nodeIP net.IP, cloudNodeAddresses []v1.NodeAddress) ([]v1.NodeAddress, error) {\n\t// If nodeIP is unset, just use the addresses provided by the cloud provider as-is\n\tif nodeIP == nil {\n\t\treturn cloudNodeAddresses, nil\n\t}\n\n\t// nodeIP is \"0.0.0.0\" or \"::\"; sort cloudNodeAddresses to\n\t// prefer addresses of the matching family\n\tif nodeIP.IsUnspecified() {\n\t\tpreferIPv4 := nodeIP.To4() != nil\n\t\tisPreferredIPFamily := func(ip net.IP) bool { return (ip.To4() != nil) == preferIPv4 }\n\n\t\tsortedAddresses := make([]v1.NodeAddress, 0, len(cloudNodeAddresses))\n\t\tfor _, nodeAddress := range cloudNodeAddresses {\n\t\t\tip := netutils.ParseIPSloppy(nodeAddress.Address)\n\t\t\tif ip == nil || isPreferredIPFamily(ip) {\n\t\t\t\tsortedAddresses = append(sortedAddresses, nodeAddress)\n\t\t\t}\n\t\t}\n\t\tfor _, nodeAddress := range cloudNodeAddresses {\n\t\t\tip := netutils.ParseIPSloppy(nodeAddress.Address)\n\t\t\tif ip != nil \u0026\u0026 !isPreferredIPFamily(ip) {\n\t\t\t\tsortedAddresses = append(sortedAddresses, nodeAddress)\n\t\t\t}\n\t\t}\n\t\treturn sortedAddresses, nil\n\t}\n\n\t// Otherwise the result is the same as for GetNodeAddressesFromNodeIP\n\treturn GetNodeAddressesFromNodeIP(nodeIP.String(), cloudNodeAddresses, false)\n}","line":{"from":45,"to":89}} {"id":100029623,"name":"GetNodeAddressesFromNodeIP","signature":"func GetNodeAddressesFromNodeIP(providedNodeIP string, cloudNodeAddresses []v1.NodeAddress, allowDualStack bool) ([]v1.NodeAddress, error)","file":"staging/src/k8s.io/cloud-provider/node/helpers/address.go","code":"// GetNodeAddressesFromNodeIP filters the provided list of nodeAddresses to match the\n// providedNodeIP from the Node annotation (which is assumed to be non-empty). This is\n// used for external cloud providers.\n//\n// It will return node addresses filtered such that:\n// - Any address matching nodeIP will be listed first.\n// - If nodeIP matches an address of a particular type (internal or external),\n// that will be the *only* address of that type returned.\n// - All remaining addresses are listed after.\n//\n// (This does not have the same behavior with `0.0.0.0` and `::` as\n// GetNodeAddressesFromNodeIPLegacy, because that case never occurs for external cloud\n// providers, because kubelet does not set the `provided-node-ip` annotation in that\n// case.)\nfunc GetNodeAddressesFromNodeIP(providedNodeIP string, cloudNodeAddresses []v1.NodeAddress, allowDualStack bool) ([]v1.NodeAddress, error) {\n\tnodeIPs, err := nodeutil.ParseNodeIPAnnotation(providedNodeIP, allowDualStack)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse node IP %q: %v\", providedNodeIP, err)\n\t}\n\n\tenforcedNodeAddresses := []v1.NodeAddress{}\n\tnodeIPTypes := make(map[v1.NodeAddressType]bool)\n\n\tfor _, nodeIP := range nodeIPs {\n\t\t// For every address supplied by the cloud provider that matches nodeIP,\n\t\t// nodeIP is the enforced node address for that address Type (like\n\t\t// InternalIP and ExternalIP), meaning other addresses of the same Type\n\t\t// are discarded. See #61921 for more information: some cloud providers\n\t\t// may supply secondary IPs, so nodeIP serves as a way to ensure that the\n\t\t// correct IPs show up on a Node object.\n\n\t\tmatched := false\n\t\tfor _, nodeAddress := range cloudNodeAddresses {\n\t\t\tif netutils.ParseIPSloppy(nodeAddress.Address).Equal(nodeIP) {\n\t\t\t\tenforcedNodeAddresses = append(enforcedNodeAddresses, v1.NodeAddress{Type: nodeAddress.Type, Address: nodeAddress.Address})\n\t\t\t\tnodeIPTypes[nodeAddress.Type] = true\n\t\t\t\tmatched = true\n\t\t\t}\n\t\t}\n\n\t\t// nodeIP must be among the addresses supplied by the cloud provider\n\t\tif !matched {\n\t\t\treturn nil, fmt.Errorf(\"failed to get node address from cloud provider that matches ip: %v\", nodeIP)\n\t\t}\n\t}\n\n\t// Now use all other addresses supplied by the cloud provider NOT of the same Type\n\t// as any nodeIP.\n\tfor _, nodeAddress := range cloudNodeAddresses {\n\t\tif !nodeIPTypes[nodeAddress.Type] {\n\t\t\tenforcedNodeAddresses = append(enforcedNodeAddresses, v1.NodeAddress{Type: nodeAddress.Type, Address: nodeAddress.Address})\n\t\t}\n\t}\n\n\treturn enforcedNodeAddresses, nil\n}","line":{"from":91,"to":146}} {"id":100029624,"name":"AddOrUpdateLabelsOnNode","signature":"func AddOrUpdateLabelsOnNode(kubeClient clientset.Interface, labelsToUpdate map[string]string, node *v1.Node) bool","file":"staging/src/k8s.io/cloud-provider/node/helpers/labels.go","code":"// AddOrUpdateLabelsOnNode updates the labels on the node and returns true on\n// success and false on failure.\nfunc AddOrUpdateLabelsOnNode(kubeClient clientset.Interface, labelsToUpdate map[string]string, node *v1.Node) bool {\n\terr := addOrUpdateLabelsOnNode(kubeClient, node.Name, labelsToUpdate)\n\tif err != nil {\n\t\tutilruntime.HandleError(\n\t\t\tfmt.Errorf(\n\t\t\t\t\"unable to update labels %+v for Node %q: %v\",\n\t\t\t\tlabelsToUpdate,\n\t\t\t\tnode.Name,\n\t\t\t\terr))\n\t\treturn false\n\t}\n\n\tklog.V(4).Infof(\"Updated labels %+v to Node %v\", labelsToUpdate, node.Name)\n\treturn true\n}","line":{"from":42,"to":58}} {"id":100029625,"name":"addOrUpdateLabelsOnNode","signature":"func addOrUpdateLabelsOnNode(kubeClient clientset.Interface, nodeName string, labelsToUpdate map[string]string) error","file":"staging/src/k8s.io/cloud-provider/node/helpers/labels.go","code":"func addOrUpdateLabelsOnNode(kubeClient clientset.Interface, nodeName string, labelsToUpdate map[string]string) error {\n\tfirstTry := true\n\treturn clientretry.RetryOnConflict(updateLabelBackoff, func() error {\n\t\tvar err error\n\t\tvar node *v1.Node\n\t\t// First we try getting node from the API server cache, as it's cheaper. If it fails\n\t\t// we get it from etcd to be sure to have fresh data.\n\t\tif firstTry {\n\t\t\tnode, err = kubeClient.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{ResourceVersion: \"0\"})\n\t\t\tfirstTry = false\n\t\t} else {\n\t\t\tnode, err = kubeClient.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{})\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Make a copy of the node and update the labels.\n\t\tnewNode := node.DeepCopy()\n\t\tif newNode.Labels == nil {\n\t\t\tnewNode.Labels = make(map[string]string)\n\t\t}\n\t\tfor key, value := range labelsToUpdate {\n\t\t\tnewNode.Labels[key] = value\n\t\t}\n\n\t\toldData, err := json.Marshal(node)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to marshal the existing node %#v: %v\", node, err)\n\t\t}\n\t\tnewData, err := json.Marshal(newNode)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to marshal the new node %#v: %v\", newNode, err)\n\t\t}\n\t\tpatchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, \u0026v1.Node{})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create a two-way merge patch: %v\", err)\n\t\t}\n\t\tif _, err := kubeClient.CoreV1().Nodes().Patch(context.TODO(), node.Name, types.StrategicMergePatchType, patchBytes, metav1.PatchOptions{}); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to patch the node: %v\", err)\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":60,"to":103}} {"id":100029626,"name":"AddOrUpdateTaintOnNode","signature":"func AddOrUpdateTaintOnNode(c clientset.Interface, nodeName string, taints ...*v1.Taint) error","file":"staging/src/k8s.io/cloud-provider/node/helpers/taints.go","code":"// AddOrUpdateTaintOnNode add taints to the node. If taint was added into node, it'll issue API calls\n// to update nodes; otherwise, no API calls. Return error if any.\nfunc AddOrUpdateTaintOnNode(c clientset.Interface, nodeName string, taints ...*v1.Taint) error {\n\tif len(taints) == 0 {\n\t\treturn nil\n\t}\n\tfirstTry := true\n\treturn clientretry.RetryOnConflict(updateTaintBackoff, func() error {\n\t\tvar err error\n\t\tvar oldNode *v1.Node\n\t\t// First we try getting node from the API server cache, as it's cheaper. If it fails\n\t\t// we get it from etcd to be sure to have fresh data.\n\t\tif firstTry {\n\t\t\toldNode, err = c.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{ResourceVersion: \"0\"})\n\t\t\tfirstTry = false\n\t\t} else {\n\t\t\toldNode, err = c.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{})\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar newNode *v1.Node\n\t\toldNodeCopy := oldNode\n\t\tupdated := false\n\t\tfor _, taint := range taints {\n\t\t\tcurNewNode, ok, err := addOrUpdateTaint(oldNodeCopy, taint)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to update taint of node\")\n\t\t\t}\n\t\t\tupdated = updated || ok\n\t\t\tnewNode = curNewNode\n\t\t\toldNodeCopy = curNewNode\n\t\t}\n\t\tif !updated {\n\t\t\treturn nil\n\t\t}\n\t\treturn PatchNodeTaints(c, nodeName, oldNode, newNode)\n\t})\n}","line":{"from":49,"to":88}} {"id":100029627,"name":"PatchNodeTaints","signature":"func PatchNodeTaints(c clientset.Interface, nodeName string, oldNode *v1.Node, newNode *v1.Node) error","file":"staging/src/k8s.io/cloud-provider/node/helpers/taints.go","code":"// PatchNodeTaints patches node's taints.\nfunc PatchNodeTaints(c clientset.Interface, nodeName string, oldNode *v1.Node, newNode *v1.Node) error {\n\t// Strip base diff node from RV to ensure that our Patch request will set RV to check for conflicts over .spec.taints.\n\t// This is needed because .spec.taints does not specify patchMergeKey and patchStrategy and adding them is no longer an option for compatibility reasons.\n\t// Using other Patch strategy works for adding new taints, however will not resolve problem with taint removal.\n\toldNodeNoRV := oldNode.DeepCopy()\n\toldNodeNoRV.ResourceVersion = \"\"\n\toldDataNoRV, err := json.Marshal(\u0026oldNodeNoRV)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal old node %#v for node %q: %v\", oldNodeNoRV, nodeName, err)\n\t}\n\n\tnewTaints := newNode.Spec.Taints\n\tnewNodeClone := oldNode.DeepCopy()\n\tnewNodeClone.Spec.Taints = newTaints\n\tnewData, err := json.Marshal(newNodeClone)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal new node %#v for node %q: %v\", newNodeClone, nodeName, err)\n\t}\n\n\tpatchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldDataNoRV, newData, v1.Node{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create patch for node %q: %v\", nodeName, err)\n\t}\n\n\t_, err = c.CoreV1().Nodes().Patch(context.TODO(), nodeName, types.StrategicMergePatchType, patchBytes, metav1.PatchOptions{})\n\treturn err\n}","line":{"from":90,"to":117}} {"id":100029628,"name":"addOrUpdateTaint","signature":"func addOrUpdateTaint(node *v1.Node, taint *v1.Taint) (*v1.Node, bool, error)","file":"staging/src/k8s.io/cloud-provider/node/helpers/taints.go","code":"// addOrUpdateTaint tries to add a taint to annotations list. Returns a new copy of updated Node and true if something was updated\n// false otherwise.\nfunc addOrUpdateTaint(node *v1.Node, taint *v1.Taint) (*v1.Node, bool, error) {\n\tnewNode := node.DeepCopy()\n\tnodeTaints := newNode.Spec.Taints\n\n\tvar newTaints []v1.Taint\n\tupdated := false\n\tfor i := range nodeTaints {\n\t\tif taint.MatchTaint(\u0026nodeTaints[i]) {\n\t\t\tif equality.Semantic.DeepEqual(*taint, nodeTaints[i]) {\n\t\t\t\treturn newNode, false, nil\n\t\t\t}\n\t\t\tnewTaints = append(newTaints, *taint)\n\t\t\tupdated = true\n\t\t\tcontinue\n\t\t}\n\n\t\tnewTaints = append(newTaints, nodeTaints[i])\n\t}\n\n\tif !updated {\n\t\tnewTaints = append(newTaints, *taint)\n\t}\n\n\tnewNode.Spec.Taints = newTaints\n\treturn newNode, true, nil\n}","line":{"from":119,"to":146}} {"id":100029629,"name":"RemoveTaintOffNode","signature":"func RemoveTaintOffNode(c clientset.Interface, nodeName string, node *v1.Node, taints ...*v1.Taint) error","file":"staging/src/k8s.io/cloud-provider/node/helpers/taints.go","code":"// RemoveTaintOffNode is for cleaning up taints temporarily added to node,\n// won't fail if target taint doesn't exist or has been removed.\n// If passed a node it'll check if there's anything to be done, if taint is not present it won't issue\n// any API calls.\nfunc RemoveTaintOffNode(c clientset.Interface, nodeName string, node *v1.Node, taints ...*v1.Taint) error {\n\tif len(taints) == 0 {\n\t\treturn nil\n\t}\n\t// Short circuit for limiting amount of API calls.\n\tif node != nil {\n\t\tmatch := false\n\t\tfor _, taint := range taints {\n\t\t\tif taintExists(node.Spec.Taints, taint) {\n\t\t\t\tmatch = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !match {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tfirstTry := true\n\treturn clientretry.RetryOnConflict(updateTaintBackoff, func() error {\n\t\tvar err error\n\t\tvar oldNode *v1.Node\n\t\t// First we try getting node from the API server cache, as it's cheaper. If it fails\n\t\t// we get it from etcd to be sure to have fresh data.\n\t\tif firstTry {\n\t\t\toldNode, err = c.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{ResourceVersion: \"0\"})\n\t\t\tfirstTry = false\n\t\t} else {\n\t\t\toldNode, err = c.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{})\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar newNode *v1.Node\n\t\toldNodeCopy := oldNode\n\t\tupdated := false\n\t\tfor _, taint := range taints {\n\t\t\tcurNewNode, ok, err := removeTaint(oldNodeCopy, taint)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to remove taint of node\")\n\t\t\t}\n\t\t\tupdated = updated || ok\n\t\t\tnewNode = curNewNode\n\t\t\toldNodeCopy = curNewNode\n\t\t}\n\t\tif !updated {\n\t\t\treturn nil\n\t\t}\n\t\treturn PatchNodeTaints(c, nodeName, oldNode, newNode)\n\t})\n}","line":{"from":148,"to":203}} {"id":100029630,"name":"taintExists","signature":"func taintExists(taints []v1.Taint, taintToFind *v1.Taint) bool","file":"staging/src/k8s.io/cloud-provider/node/helpers/taints.go","code":"// taintExists checks if the given taint exists in list of taints. Returns true if exists false otherwise.\nfunc taintExists(taints []v1.Taint, taintToFind *v1.Taint) bool {\n\tfor _, taint := range taints {\n\t\tif taint.MatchTaint(taintToFind) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":205,"to":213}} {"id":100029631,"name":"removeTaint","signature":"func removeTaint(node *v1.Node, taint *v1.Taint) (*v1.Node, bool, error)","file":"staging/src/k8s.io/cloud-provider/node/helpers/taints.go","code":"// removeTaint tries to remove a taint from annotations list. Returns a new copy of updated Node and true if something was updated\n// false otherwise.\nfunc removeTaint(node *v1.Node, taint *v1.Taint) (*v1.Node, bool, error) {\n\tnewNode := node.DeepCopy()\n\tnodeTaints := newNode.Spec.Taints\n\tif len(nodeTaints) == 0 {\n\t\treturn newNode, false, nil\n\t}\n\n\tif !taintExists(nodeTaints, taint) {\n\t\treturn newNode, false, nil\n\t}\n\n\tnewTaints, _ := deleteTaint(nodeTaints, taint)\n\tnewNode.Spec.Taints = newTaints\n\treturn newNode, true, nil\n}","line":{"from":215,"to":231}} {"id":100029632,"name":"deleteTaint","signature":"func deleteTaint(taints []v1.Taint, taintToDelete *v1.Taint) ([]v1.Taint, bool)","file":"staging/src/k8s.io/cloud-provider/node/helpers/taints.go","code":"// deleteTaint removes all the taints that have the same key and effect to given taintToDelete.\nfunc deleteTaint(taints []v1.Taint, taintToDelete *v1.Taint) ([]v1.Taint, bool) {\n\tnewTaints := []v1.Taint{}\n\tdeleted := false\n\tfor i := range taints {\n\t\tif taintToDelete.MatchTaint(\u0026taints[i]) {\n\t\t\tdeleted = true\n\t\t\tcontinue\n\t\t}\n\t\tnewTaints = append(newTaints, taints[i])\n\t}\n\treturn newTaints, deleted\n}","line":{"from":233,"to":245}} {"id":100029633,"name":"Validate","signature":"func (s *CloudProviderOptions) Validate() []error","file":"staging/src/k8s.io/cloud-provider/options/cloudprovider.go","code":"// Validate checks validation of cloudprovider options.\nfunc (s *CloudProviderOptions) Validate() []error {\n\tallErrors := []error{}\n\treturn allErrors\n}","line":{"from":29,"to":33}} {"id":100029634,"name":"AddFlags","signature":"func (s *CloudProviderOptions) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/cloud-provider/options/cloudprovider.go","code":"// AddFlags adds flags related to cloudprovider for controller manager to the specified FlagSet.\nfunc (s *CloudProviderOptions) AddFlags(fs *pflag.FlagSet) {\n\tfs.StringVar(\u0026s.Name, \"cloud-provider\", s.Name,\n\t\t\"The provider for cloud services. Empty string for no provider.\")\n\n\tfs.StringVar(\u0026s.CloudConfigFile, \"cloud-config\", s.CloudConfigFile,\n\t\t\"The path to the cloud provider configuration file. Empty string for no configuration file.\")\n}","line":{"from":35,"to":42}} {"id":100029635,"name":"ApplyTo","signature":"func (s *CloudProviderOptions) ApplyTo(cfg *cpconfig.CloudProviderConfiguration) error","file":"staging/src/k8s.io/cloud-provider/options/cloudprovider.go","code":"// ApplyTo fills up cloudprovider config with options.\nfunc (s *CloudProviderOptions) ApplyTo(cfg *cpconfig.CloudProviderConfiguration) error {\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\tcfg.Name = s.Name\n\tcfg.CloudConfigFile = s.CloudConfigFile\n\n\treturn nil\n}","line":{"from":44,"to":54}} {"id":100029636,"name":"NewKubeCloudSharedOptions","signature":"func NewKubeCloudSharedOptions(cfg *cpconfig.KubeCloudSharedConfiguration) *KubeCloudSharedOptions","file":"staging/src/k8s.io/cloud-provider/options/kubecloudshared.go","code":"// NewKubeCloudSharedOptions returns common/default configuration values for both\n// the kube-controller-manager and the cloud-contoller-manager. Any common changes should\n// be made here. Any individual changes should be made in that controller.\nfunc NewKubeCloudSharedOptions(cfg *cpconfig.KubeCloudSharedConfiguration) *KubeCloudSharedOptions {\n\to := \u0026KubeCloudSharedOptions{\n\t\tKubeCloudSharedConfiguration: cfg,\n\t\tCloudProvider: \u0026CloudProviderOptions{\n\t\t\tCloudProviderConfiguration: \u0026cpconfig.CloudProviderConfiguration{},\n\t\t},\n\t}\n\n\treturn o\n}","line":{"from":31,"to":43}} {"id":100029637,"name":"AddFlags","signature":"func (o *KubeCloudSharedOptions) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/cloud-provider/options/kubecloudshared.go","code":"// AddFlags adds flags related to shared variable for controller manager to the specified FlagSet.\nfunc (o *KubeCloudSharedOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\to.CloudProvider.AddFlags(fs)\n\tfs.StringVar(\u0026o.ExternalCloudVolumePlugin, \"external-cloud-volume-plugin\", o.ExternalCloudVolumePlugin, \"The plugin to use when cloud provider is set to external. Can be empty, should only be set when cloud-provider is external. Currently used to allow node and volume controllers to work for in tree cloud providers.\")\n\tfs.BoolVar(\u0026o.UseServiceAccountCredentials, \"use-service-account-credentials\", o.UseServiceAccountCredentials, \"If true, use individual service account credentials for each controller.\")\n\tfs.BoolVar(\u0026o.AllowUntaggedCloud, \"allow-untagged-cloud\", false, \"Allow the cluster to run without the cluster-id on cloud instances. This is a legacy mode of operation and a cluster-id will be required in the future.\")\n\tfs.MarkDeprecated(\"allow-untagged-cloud\", \"This flag is deprecated and will be removed in a future release. A cluster-id will be required on cloud instances.\")\n\tfs.DurationVar(\u0026o.RouteReconciliationPeriod.Duration, \"route-reconciliation-period\", o.RouteReconciliationPeriod.Duration, \"The period for reconciling routes created for Nodes by cloud provider.\")\n\tfs.DurationVar(\u0026o.NodeMonitorPeriod.Duration, \"node-monitor-period\", o.NodeMonitorPeriod.Duration,\n\t\t\"The period for syncing NodeStatus in NodeController.\")\n\tfs.StringVar(\u0026o.ClusterName, \"cluster-name\", o.ClusterName, \"The instance prefix for the cluster.\")\n\tfs.StringVar(\u0026o.ClusterCIDR, \"cluster-cidr\", o.ClusterCIDR, \"CIDR Range for Pods in cluster. Requires --allocate-node-cidrs to be true\")\n\tfs.BoolVar(\u0026o.AllocateNodeCIDRs, \"allocate-node-cidrs\", false, \"Should CIDRs for Pods be allocated and set on the cloud provider.\")\n\tfs.StringVar(\u0026o.CIDRAllocatorType, \"cidr-allocator-type\", \"RangeAllocator\", \"Type of CIDR allocator to use\")\n\tfs.BoolVar(\u0026o.ConfigureCloudRoutes, \"configure-cloud-routes\", true, \"Should CIDRs allocated by allocate-node-cidrs be configured on the cloud provider.\")\n\n\tfs.DurationVar(\u0026o.NodeSyncPeriod.Duration, \"node-sync-period\", 0, \"\"+\n\t\t\"This flag is deprecated and will be removed in future releases. See node-monitor-period for Node health checking or \"+\n\t\t\"route-reconciliation-period for cloud provider's route configuration settings.\")\n\tfs.MarkDeprecated(\"node-sync-period\", \"This flag is currently no-op and will be deleted.\")\n}","line":{"from":45,"to":69}} {"id":100029638,"name":"ApplyTo","signature":"func (o *KubeCloudSharedOptions) ApplyTo(cfg *cpconfig.KubeCloudSharedConfiguration) error","file":"staging/src/k8s.io/cloud-provider/options/kubecloudshared.go","code":"// ApplyTo fills up KubeCloudShared config with options.\nfunc (o *KubeCloudSharedOptions) ApplyTo(cfg *cpconfig.KubeCloudSharedConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tif err := o.CloudProvider.ApplyTo(\u0026cfg.CloudProvider); err != nil {\n\t\treturn err\n\t}\n\n\tcfg.ExternalCloudVolumePlugin = o.ExternalCloudVolumePlugin\n\tcfg.UseServiceAccountCredentials = o.UseServiceAccountCredentials\n\tcfg.AllowUntaggedCloud = o.AllowUntaggedCloud\n\tcfg.RouteReconciliationPeriod = o.RouteReconciliationPeriod\n\tcfg.NodeMonitorPeriod = o.NodeMonitorPeriod\n\tcfg.ClusterName = o.ClusterName\n\tcfg.ClusterCIDR = o.ClusterCIDR\n\tcfg.AllocateNodeCIDRs = o.AllocateNodeCIDRs\n\tcfg.CIDRAllocatorType = o.CIDRAllocatorType\n\tcfg.ConfigureCloudRoutes = o.ConfigureCloudRoutes\n\tcfg.NodeSyncPeriod = o.NodeSyncPeriod\n\n\treturn nil\n}","line":{"from":71,"to":94}} {"id":100029639,"name":"Validate","signature":"func (o *KubeCloudSharedOptions) Validate() []error","file":"staging/src/k8s.io/cloud-provider/options/kubecloudshared.go","code":"// Validate checks validation of KubeCloudSharedOptions.\nfunc (o *KubeCloudSharedOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\terrs = append(errs, o.CloudProvider.Validate()...)\n\n\treturn errs\n}","line":{"from":96,"to":106}} {"id":100029640,"name":"AddFlags","signature":"func (o *NodeControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/cloud-provider/options/nodecontroller.go","code":"// AddFlags adds flags related to ServiceController for controller manager to the specified FlagSet.\nfunc (o *NodeControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.Int32Var(\u0026o.ConcurrentNodeSyncs, \"concurrent-node-syncs\", o.ConcurrentNodeSyncs, \"Number of workers concurrently synchronizing nodes.\")\n}","line":{"from":32,"to":39}} {"id":100029641,"name":"ApplyTo","signature":"func (o *NodeControllerOptions) ApplyTo(cfg *nodeconfig.NodeControllerConfiguration) error","file":"staging/src/k8s.io/cloud-provider/options/nodecontroller.go","code":"// ApplyTo fills up ServiceController config with options.\nfunc (o *NodeControllerOptions) ApplyTo(cfg *nodeconfig.NodeControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ConcurrentNodeSyncs = o.ConcurrentNodeSyncs\n\n\treturn nil\n}","line":{"from":41,"to":50}} {"id":100029642,"name":"Validate","signature":"func (o *NodeControllerOptions) Validate() []error","file":"staging/src/k8s.io/cloud-provider/options/nodecontroller.go","code":"// Validate checks validation of NodeControllerOptions.\nfunc (o *NodeControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tvar errors []error\n\tif o.ConcurrentNodeSyncs \u003c= 0 {\n\t\terrors = append(errors, fmt.Errorf(\"concurrent-node-syncs must be a positive number\"))\n\t}\n\treturn errors\n}","line":{"from":52,"to":62}} {"id":100029643,"name":"NewCloudControllerManagerOptions","signature":"func NewCloudControllerManagerOptions() (*CloudControllerManagerOptions, error)","file":"staging/src/k8s.io/cloud-provider/options/options.go","code":"// NewCloudControllerManagerOptions creates a new ExternalCMServer with a default config.\nfunc NewCloudControllerManagerOptions() (*CloudControllerManagerOptions, error) {\n\treturn NewCloudControllerManagerOptionsWithProviderDefaults(ProviderDefaults{})\n}","line":{"from":85,"to":88}} {"id":100029644,"name":"NewCloudControllerManagerOptionsWithProviderDefaults","signature":"func NewCloudControllerManagerOptionsWithProviderDefaults(defaults ProviderDefaults) (*CloudControllerManagerOptions, error)","file":"staging/src/k8s.io/cloud-provider/options/options.go","code":"// NewCloudControllerManagerOptionsWithProviderDefaults creates a new\n// ExternalCMServer with a default config, but allows the cloud provider to\n// override a select number of default option values.\nfunc NewCloudControllerManagerOptionsWithProviderDefaults(defaults ProviderDefaults) (*CloudControllerManagerOptions, error) {\n\tcomponentConfig, err := NewDefaultComponentConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts := CloudControllerManagerOptions{\n\t\tGeneric: cmoptions.NewGenericControllerManagerConfigurationOptions(\u0026componentConfig.Generic),\n\t\tKubeCloudShared: NewKubeCloudSharedOptions(\u0026componentConfig.KubeCloudShared),\n\t\tNodeController: \u0026NodeControllerOptions{\n\t\t\tNodeControllerConfiguration: \u0026componentConfig.NodeController,\n\t\t},\n\t\tServiceController: \u0026ServiceControllerOptions{\n\t\t\tServiceControllerConfiguration: \u0026componentConfig.ServiceController,\n\t\t},\n\t\tSecureServing: apiserveroptions.NewSecureServingOptions().WithLoopback(),\n\t\tWebhook: NewWebhookOptions(),\n\t\tWebhookServing: NewWebhookServingOptions(defaults),\n\t\tAuthentication: apiserveroptions.NewDelegatingAuthenticationOptions(),\n\t\tAuthorization: apiserveroptions.NewDelegatingAuthorizationOptions(),\n\t\tNodeStatusUpdateFrequency: componentConfig.NodeStatusUpdateFrequency,\n\t}\n\n\ts.Authentication.RemoteKubeConfigFileOptional = true\n\ts.Authorization.RemoteKubeConfigFileOptional = true\n\n\t// Set the PairName but leave certificate directory blank to generate in-memory by default\n\ts.SecureServing.ServerCert.CertDirectory = \"\"\n\ts.SecureServing.ServerCert.PairName = \"cloud-controller-manager\"\n\ts.SecureServing.BindPort = cloudprovider.CloudControllerManagerPort\n\n\ts.Generic.LeaderElection.ResourceName = \"cloud-controller-manager\"\n\ts.Generic.LeaderElection.ResourceNamespace = \"kube-system\"\n\n\treturn \u0026s, nil\n}","line":{"from":90,"to":128}} {"id":100029645,"name":"NewDefaultComponentConfig","signature":"func NewDefaultComponentConfig() (*ccmconfig.CloudControllerManagerConfiguration, error)","file":"staging/src/k8s.io/cloud-provider/options/options.go","code":"// NewDefaultComponentConfig returns cloud-controller manager configuration object.\nfunc NewDefaultComponentConfig() (*ccmconfig.CloudControllerManagerConfiguration, error) {\n\tversioned := \u0026ccmconfigv1alpha1.CloudControllerManagerConfiguration{}\n\tccmconfigscheme.Scheme.Default(versioned)\n\n\tinternal := \u0026ccmconfig.CloudControllerManagerConfiguration{}\n\tif err := ccmconfigscheme.Scheme.Convert(versioned, internal, nil); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn internal, nil\n}","line":{"from":130,"to":141}} {"id":100029646,"name":"Flags","signature":"func (o *CloudControllerManagerOptions) Flags(allControllers, disabledByDefaultControllers, allWebhooks, disabledByDefaultWebhooks []string) cliflag.NamedFlagSets","file":"staging/src/k8s.io/cloud-provider/options/options.go","code":"// Flags returns flags for a specific CloudController by section name\nfunc (o *CloudControllerManagerOptions) Flags(allControllers, disabledByDefaultControllers, allWebhooks, disabledByDefaultWebhooks []string) cliflag.NamedFlagSets {\n\tfss := cliflag.NamedFlagSets{}\n\to.Generic.AddFlags(\u0026fss, allControllers, disabledByDefaultControllers)\n\to.KubeCloudShared.AddFlags(fss.FlagSet(\"generic\"))\n\to.NodeController.AddFlags(fss.FlagSet(\"node controller\"))\n\to.ServiceController.AddFlags(fss.FlagSet(\"service controller\"))\n\tif o.Webhook != nil {\n\t\to.Webhook.AddFlags(fss.FlagSet(\"webhook\"), allWebhooks, disabledByDefaultWebhooks)\n\t}\n\tif o.WebhookServing != nil {\n\t\to.WebhookServing.AddFlags(fss.FlagSet(\"webhook serving\"))\n\t}\n\n\to.SecureServing.AddFlags(fss.FlagSet(\"secure serving\"))\n\to.Authentication.AddFlags(fss.FlagSet(\"authentication\"))\n\to.Authorization.AddFlags(fss.FlagSet(\"authorization\"))\n\n\tfs := fss.FlagSet(\"misc\")\n\tfs.StringVar(\u0026o.Master, \"master\", o.Master, \"The address of the Kubernetes API server (overrides any value in kubeconfig).\")\n\tfs.StringVar(\u0026o.Generic.ClientConnection.Kubeconfig, \"kubeconfig\", o.Generic.ClientConnection.Kubeconfig, \"Path to kubeconfig file with authorization and master location information (the master location can be overridden by the master flag).\")\n\tfs.DurationVar(\u0026o.NodeStatusUpdateFrequency.Duration, \"node-status-update-frequency\", o.NodeStatusUpdateFrequency.Duration, \"Specifies how often the controller updates nodes' status.\")\n\tutilfeature.DefaultMutableFeatureGate.AddFlag(fss.FlagSet(\"generic\"))\n\n\treturn fss\n}","line":{"from":143,"to":168}} {"id":100029647,"name":"ApplyTo","signature":"func (o *CloudControllerManagerOptions) ApplyTo(c *config.Config, userAgent string) error","file":"staging/src/k8s.io/cloud-provider/options/options.go","code":"// ApplyTo fills up cloud controller manager config with options.\nfunc (o *CloudControllerManagerOptions) ApplyTo(c *config.Config, userAgent string) error {\n\tvar err error\n\n\t// Build kubeconfig first to so that if it fails, it doesn't cause leaking\n\t// goroutines (started from initializing secure serving - which underneath\n\t// creates a queue which in its constructor starts a goroutine).\n\tc.Kubeconfig, err = clientcmd.BuildConfigFromFlags(o.Master, o.Generic.ClientConnection.Kubeconfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.Kubeconfig.DisableCompression = true\n\tc.Kubeconfig.ContentConfig.AcceptContentTypes = o.Generic.ClientConnection.AcceptContentTypes\n\tc.Kubeconfig.ContentConfig.ContentType = o.Generic.ClientConnection.ContentType\n\tc.Kubeconfig.QPS = o.Generic.ClientConnection.QPS\n\tc.Kubeconfig.Burst = int(o.Generic.ClientConnection.Burst)\n\n\tif err = o.Generic.ApplyTo(\u0026c.ComponentConfig.Generic); err != nil {\n\t\treturn err\n\t}\n\tif err = o.KubeCloudShared.ApplyTo(\u0026c.ComponentConfig.KubeCloudShared); err != nil {\n\t\treturn err\n\t}\n\tif err = o.ServiceController.ApplyTo(\u0026c.ComponentConfig.ServiceController); err != nil {\n\t\treturn err\n\t}\n\tif o.Webhook != nil {\n\t\tif err = o.Webhook.ApplyTo(\u0026c.ComponentConfig.Webhook); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif o.WebhookServing != nil {\n\t\tif err = o.WebhookServing.ApplyTo(\u0026c.WebhookSecureServing); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif err = o.SecureServing.ApplyTo(\u0026c.SecureServing, \u0026c.LoopbackClientConfig); err != nil {\n\t\treturn err\n\t}\n\tif o.SecureServing.BindPort != 0 || o.SecureServing.Listener != nil {\n\t\tif err = o.Authentication.ApplyTo(\u0026c.Authentication, c.SecureServing, nil); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err = o.Authorization.ApplyTo(\u0026c.Authorization); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tc.Client, err = clientset.NewForConfig(restclient.AddUserAgent(c.Kubeconfig, userAgent))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.EventBroadcaster = record.NewBroadcaster()\n\tc.EventRecorder = c.EventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: userAgent})\n\n\trootClientBuilder := clientbuilder.SimpleControllerClientBuilder{\n\t\tClientConfig: c.Kubeconfig,\n\t}\n\tif c.ComponentConfig.KubeCloudShared.UseServiceAccountCredentials {\n\t\tc.ClientBuilder = clientbuilder.NewDynamicClientBuilder(\n\t\t\trestclient.AnonymousClientConfig(c.Kubeconfig),\n\t\t\tc.Client.CoreV1(),\n\t\t\tmetav1.NamespaceSystem)\n\t} else {\n\t\tc.ClientBuilder = rootClientBuilder\n\t}\n\tc.VersionedClient = rootClientBuilder.ClientOrDie(\"shared-informers\")\n\tc.SharedInformers = informers.NewSharedInformerFactory(c.VersionedClient, resyncPeriod(c)())\n\n\t// sync back to component config\n\t// TODO: find more elegant way than syncing back the values.\n\tc.ComponentConfig.NodeStatusUpdateFrequency = o.NodeStatusUpdateFrequency\n\tc.ComponentConfig.NodeController.ConcurrentNodeSyncs = o.NodeController.ConcurrentNodeSyncs\n\n\treturn nil\n}","line":{"from":170,"to":246}} {"id":100029648,"name":"Validate","signature":"func (o *CloudControllerManagerOptions) Validate(allControllers, disabledByDefaultControllers, allWebhooks, disabledByDefaultWebhooks []string) error","file":"staging/src/k8s.io/cloud-provider/options/options.go","code":"// Validate is used to validate config before launching the cloud controller manager\nfunc (o *CloudControllerManagerOptions) Validate(allControllers, disabledByDefaultControllers, allWebhooks, disabledByDefaultWebhooks []string) error {\n\terrors := []error{}\n\n\terrors = append(errors, o.Generic.Validate(allControllers, disabledByDefaultControllers)...)\n\terrors = append(errors, o.KubeCloudShared.Validate()...)\n\terrors = append(errors, o.ServiceController.Validate()...)\n\terrors = append(errors, o.SecureServing.Validate()...)\n\terrors = append(errors, o.Authentication.Validate()...)\n\terrors = append(errors, o.Authorization.Validate()...)\n\n\tif o.Webhook != nil {\n\t\terrors = append(errors, o.Webhook.Validate(allWebhooks, disabledByDefaultWebhooks)...)\n\t}\n\tif o.WebhookServing != nil {\n\t\terrors = append(errors, o.WebhookServing.Validate()...)\n\n\t\tif o.WebhookServing.BindPort == o.SecureServing.BindPort {\n\t\t\terrors = append(errors, fmt.Errorf(\"--webhook-secure-port cannot be the same value as --secure-port\"))\n\t\t}\n\t}\n\tif len(o.KubeCloudShared.CloudProvider.Name) == 0 {\n\t\terrors = append(errors, fmt.Errorf(\"--cloud-provider cannot be empty\"))\n\t}\n\n\treturn utilerrors.NewAggregate(errors)\n}","line":{"from":248,"to":274}} {"id":100029649,"name":"resyncPeriod","signature":"func resyncPeriod(c *config.Config) func() time.Duration","file":"staging/src/k8s.io/cloud-provider/options/options.go","code":"// resyncPeriod computes the time interval a shared informer waits before resyncing with the api server\nfunc resyncPeriod(c *config.Config) func() time.Duration {\n\treturn func() time.Duration {\n\t\tfactor := rand.Float64() + 1\n\t\treturn time.Duration(float64(c.ComponentConfig.Generic.MinResyncPeriod.Nanoseconds()) * factor)\n\t}\n}","line":{"from":276,"to":282}} {"id":100029650,"name":"Config","signature":"func (o *CloudControllerManagerOptions) Config(allControllers, disabledByDefaultControllers, allWebhooks, disabledByDefaultWebhooks []string) (*config.Config, error)","file":"staging/src/k8s.io/cloud-provider/options/options.go","code":"// Config return a cloud controller manager config objective\nfunc (o *CloudControllerManagerOptions) Config(allControllers, disabledByDefaultControllers, allWebhooks, disabledByDefaultWebhooks []string) (*config.Config, error) {\n\tif err := o.Validate(allControllers, disabledByDefaultControllers, allWebhooks, disabledByDefaultWebhooks); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := o.SecureServing.MaybeDefaultWithSelfSignedCerts(\"localhost\", nil, []net.IP{netutils.ParseIPSloppy(\"127.0.0.1\")}); err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating self-signed certificates: %v\", err)\n\t}\n\n\tif o.WebhookServing != nil {\n\t\tif err := o.WebhookServing.MaybeDefaultWithSelfSignedCerts(\"localhost\", nil, []net.IP{netutils.ParseIPSloppy(\"127.0.0.1\")}); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error creating self-signed certificates for webhook: %v\", err)\n\t\t}\n\t}\n\n\tc := \u0026config.Config{}\n\tif err := o.ApplyTo(c, CloudControllerManagerUserAgent); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}","line":{"from":284,"to":306}} {"id":100029651,"name":"AddFlags","signature":"func (o *ServiceControllerOptions) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/cloud-provider/options/servicecontroller.go","code":"// AddFlags adds flags related to ServiceController for controller manager to the specified FlagSet.\nfunc (o *ServiceControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.Int32Var(\u0026o.ConcurrentServiceSyncs, \"concurrent-service-syncs\", o.ConcurrentServiceSyncs, \"The number of services that are allowed to sync concurrently. Larger number = more responsive service management, but more CPU (and network) load\")\n}","line":{"from":29,"to":36}} {"id":100029652,"name":"ApplyTo","signature":"func (o *ServiceControllerOptions) ApplyTo(cfg *serviceconfig.ServiceControllerConfiguration) error","file":"staging/src/k8s.io/cloud-provider/options/servicecontroller.go","code":"// ApplyTo fills up ServiceController config with options.\nfunc (o *ServiceControllerOptions) ApplyTo(cfg *serviceconfig.ServiceControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ConcurrentServiceSyncs = o.ConcurrentServiceSyncs\n\n\treturn nil\n}","line":{"from":38,"to":47}} {"id":100029653,"name":"Validate","signature":"func (o *ServiceControllerOptions) Validate() []error","file":"staging/src/k8s.io/cloud-provider/options/servicecontroller.go","code":"// Validate checks validation of ServiceControllerOptions.\nfunc (o *ServiceControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\treturn errs\n}","line":{"from":49,"to":57}} {"id":100029654,"name":"NewWebhookOptions","signature":"func NewWebhookOptions() *WebhookOptions","file":"staging/src/k8s.io/cloud-provider/options/webhook.go","code":"func NewWebhookOptions() *WebhookOptions {\n\to := \u0026WebhookOptions{}\n\treturn o\n}","line":{"from":44,"to":47}} {"id":100029655,"name":"AddFlags","signature":"func (o *WebhookOptions) AddFlags(fs *pflag.FlagSet, allWebhooks, disabledByDefaultWebhooks []string)","file":"staging/src/k8s.io/cloud-provider/options/webhook.go","code":"func (o *WebhookOptions) AddFlags(fs *pflag.FlagSet, allWebhooks, disabledByDefaultWebhooks []string) {\n\tfs.StringSliceVar(\u0026o.Webhooks, \"webhooks\", o.Webhooks, fmt.Sprintf(\"\"+\n\t\t\"A list of webhooks to enable. '*' enables all on-by-default webhooks, 'foo' enables the webhook \"+\n\t\t\"named 'foo', '-foo' disables the webhook named 'foo'.\\nAll webhooks: %s\\nDisabled-by-default webhooks: %s\",\n\t\tstrings.Join(allWebhooks, \", \"), strings.Join(disabledByDefaultWebhooks, \", \")))\n}","line":{"from":49,"to":54}} {"id":100029656,"name":"Validate","signature":"func (o *WebhookOptions) Validate(allWebhooks, disabledByDefaultWebhooks []string) []error","file":"staging/src/k8s.io/cloud-provider/options/webhook.go","code":"func (o *WebhookOptions) Validate(allWebhooks, disabledByDefaultWebhooks []string) []error {\n\tallErrors := []error{}\n\n\tallWebhooksSet := sets.NewString(allWebhooks...)\n\ttoValidate := sets.NewString(o.Webhooks...)\n\ttoValidate.Insert(disabledByDefaultWebhooks...)\n\tfor _, webhook := range toValidate.List() {\n\t\tif webhook == \"*\" {\n\t\t\tcontinue\n\t\t}\n\t\twebhook = strings.TrimPrefix(webhook, \"-\")\n\t\tif !allWebhooksSet.Has(webhook) {\n\t\t\tallErrors = append(allErrors, fmt.Errorf(\"%q is not in the list of known webhooks\", webhook))\n\t\t}\n\t}\n\n\treturn allErrors\n}","line":{"from":56,"to":73}} {"id":100029657,"name":"ApplyTo","signature":"func (o *WebhookOptions) ApplyTo(cfg *config.WebhookConfiguration) error","file":"staging/src/k8s.io/cloud-provider/options/webhook.go","code":"func (o *WebhookOptions) ApplyTo(cfg *config.WebhookConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.Webhooks = o.Webhooks\n\n\treturn nil\n}","line":{"from":75,"to":83}} {"id":100029658,"name":"NewWebhookServingOptions","signature":"func NewWebhookServingOptions(defaults ProviderDefaults) *WebhookServingOptions","file":"staging/src/k8s.io/cloud-provider/options/webhook.go","code":"func NewWebhookServingOptions(defaults ProviderDefaults) *WebhookServingOptions {\n\tvar (\n\t\tbindAddress net.IP\n\t\tbindPort int\n\t)\n\n\tif defaults.WebhookBindAddress != nil {\n\t\tbindAddress = *defaults.WebhookBindAddress\n\t} else {\n\t\tbindAddress = netutils.ParseIPSloppy(\"0.0.0.0\")\n\t}\n\n\tif defaults.WebhookBindPort != nil {\n\t\tbindPort = *defaults.WebhookBindPort\n\t} else {\n\t\tbindPort = CloudControllerManagerWebhookPort\n\t}\n\n\treturn \u0026WebhookServingOptions{\n\t\tSecureServingOptions: \u0026apiserveroptions.SecureServingOptions{\n\t\t\tBindAddress: bindAddress,\n\t\t\tBindPort: bindPort,\n\t\t\tServerCert: apiserveroptions.GeneratableKeyCert{\n\t\t\t\tCertDirectory: \"\",\n\t\t\t\tPairName: \"cloud-controller-manager-webhook\",\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":89,"to":117}} {"id":100029659,"name":"AddFlags","signature":"func (o *WebhookServingOptions) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/cloud-provider/options/webhook.go","code":"func (o *WebhookServingOptions) AddFlags(fs *pflag.FlagSet) {\n\tfs.IPVar(\u0026o.BindAddress, \"webhook-bind-address\", o.BindAddress, \"\"+\n\t\t\"The IP address on which to listen for the --webhook-secure-port port. The \"+\n\t\t\"associated interface(s) must be reachable by the rest of the cluster, and by CLI/web \"+\n\t\tfmt.Sprintf(\"clients. If set to an unspecified address (0.0.0.0 or ::), all interfaces will be used. If unset, defaults to %v.\", o.BindAddress))\n\n\tfs.IntVar(\u0026o.BindPort, \"webhook-secure-port\", o.BindPort, fmt.Sprintf(\"Secure port to serve cloud provider webhooks. If unset, defaults to %d.\", o.BindPort))\n\n\tfs.StringVar(\u0026o.ServerCert.CertDirectory, \"webhook-cert-dir\", o.ServerCert.CertDirectory, \"\"+\n\t\t\"The directory where the TLS certs are located. \"+\n\t\t\"If --tls-cert-file and --tls-private-key-file are provided, this flag will be ignored.\")\n\n\tfs.StringVar(\u0026o.ServerCert.CertKey.CertFile, \"webhook-tls-cert-file\", o.ServerCert.CertKey.CertFile, \"\"+\n\t\t\"File containing the default x509 Certificate for HTTPS. (CA cert, if any, concatenated \"+\n\t\t\"after server cert). If HTTPS serving is enabled, and --tls-cert-file and \"+\n\t\t\"--tls-private-key-file are not provided, a self-signed certificate and key \"+\n\t\t\"are generated for the public address and saved to the directory specified by --cert-dir.\")\n\n\tfs.StringVar(\u0026o.ServerCert.CertKey.KeyFile, \"webhook-tls-private-key-file\", o.ServerCert.CertKey.KeyFile,\n\t\t\"File containing the default x509 private key matching --tls-cert-file.\")\n}","line":{"from":119,"to":139}} {"id":100029660,"name":"Validate","signature":"func (o *WebhookServingOptions) Validate() []error","file":"staging/src/k8s.io/cloud-provider/options/webhook.go","code":"func (o *WebhookServingOptions) Validate() []error {\n\tallErrors := []error{}\n\tif o.BindPort \u003c 0 || o.BindPort \u003e 65535 {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"--webhook-secure-port %v must be between 0 and 65535, inclusive. A value of 0 disables the webhook endpoint entirely.\", o.BindPort))\n\t}\n\n\tif (len(o.ServerCert.CertKey.CertFile) != 0 || len(o.ServerCert.CertKey.KeyFile) != 0) \u0026\u0026 o.ServerCert.GeneratedCert != nil {\n\t\tallErrors = append(allErrors, fmt.Errorf(\"cert/key file and in-memory certificate cannot both be set\"))\n\t}\n\n\treturn allErrors\n}","line":{"from":141,"to":152}} {"id":100029661,"name":"ApplyTo","signature":"func (o *WebhookServingOptions) ApplyTo(cfg **server.SecureServingInfo) error","file":"staging/src/k8s.io/cloud-provider/options/webhook.go","code":"func (o *WebhookServingOptions) ApplyTo(cfg **server.SecureServingInfo) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tif o.BindPort \u003c= 0 {\n\t\treturn nil\n\t}\n\n\tvar err error\n\tvar listener net.Listener\n\taddr := net.JoinHostPort(o.BindAddress.String(), strconv.Itoa(o.BindPort))\n\n\tl := net.ListenConfig{}\n\n\tlistener, o.BindPort, err = createListener(addr, l)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create listener: %v\", err)\n\t}\n\n\t*cfg = \u0026server.SecureServingInfo{\n\t\tListener: listener,\n\t}\n\n\tserverCertFile, serverKeyFile := o.ServerCert.CertKey.CertFile, o.ServerCert.CertKey.KeyFile\n\tif len(serverCertFile) != 0 || len(serverKeyFile) != 0 {\n\t\tvar err error\n\t\t(*cfg).Cert, err = dynamiccertificates.NewDynamicServingContentFromFiles(\"serving-cert\", serverCertFile, serverKeyFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else if o.ServerCert.GeneratedCert != nil {\n\t\t(*cfg).Cert = o.ServerCert.GeneratedCert\n\t}\n\n\treturn nil\n}","line":{"from":154,"to":190}} {"id":100029662,"name":"createListener","signature":"func createListener(addr string, config net.ListenConfig) (net.Listener, int, error)","file":"staging/src/k8s.io/cloud-provider/options/webhook.go","code":"func createListener(addr string, config net.ListenConfig) (net.Listener, int, error) {\n\tln, err := config.Listen(context.TODO(), \"tcp\", addr)\n\tif err != nil {\n\t\treturn nil, 0, fmt.Errorf(\"failed to listen on %v: %v\", addr, err)\n\t}\n\n\t// get port\n\ttcpAddr, ok := ln.Addr().(*net.TCPAddr)\n\tif !ok {\n\t\tln.Close()\n\t\treturn nil, 0, fmt.Errorf(\"invalid listen address: %q\", ln.Addr().String())\n\t}\n\n\treturn ln, tcpAddr.Port, nil\n}","line":{"from":192,"to":206}} {"id":100029663,"name":"RegisterCloudProvider","signature":"func RegisterCloudProvider(name string, cloud Factory)","file":"staging/src/k8s.io/cloud-provider/plugins.go","code":"// RegisterCloudProvider registers a cloudprovider.Factory by name. This\n// is expected to happen during app startup.\nfunc RegisterCloudProvider(name string, cloud Factory) {\n\tprovidersMutex.Lock()\n\tdefer providersMutex.Unlock()\n\tif _, found := providers[name]; found {\n\t\tklog.Fatalf(\"Cloud provider %q was registered twice\", name)\n\t}\n\tklog.V(1).Infof(\"Registered cloud provider %q\", name)\n\tproviders[name] = cloud\n}","line":{"from":51,"to":61}} {"id":100029664,"name":"IsCloudProvider","signature":"func IsCloudProvider(name string) bool","file":"staging/src/k8s.io/cloud-provider/plugins.go","code":"// IsCloudProvider returns true if name corresponds to an already registered\n// cloud provider.\nfunc IsCloudProvider(name string) bool {\n\tprovidersMutex.Lock()\n\tdefer providersMutex.Unlock()\n\t_, found := providers[name]\n\treturn found\n}","line":{"from":63,"to":70}} {"id":100029665,"name":"GetCloudProvider","signature":"func GetCloudProvider(name string, config io.Reader) (Interface, error)","file":"staging/src/k8s.io/cloud-provider/plugins.go","code":"// GetCloudProvider creates an instance of the named cloud provider, or nil if\n// the name is unknown. The error return is only used if the named provider\n// was known but failed to initialize. The config parameter specifies the\n// io.Reader handler of the configuration file for the cloud provider, or nil\n// for no configuration.\nfunc GetCloudProvider(name string, config io.Reader) (Interface, error) {\n\tprovidersMutex.Lock()\n\tdefer providersMutex.Unlock()\n\tf, found := providers[name]\n\tif !found {\n\t\treturn nil, nil\n\t}\n\treturn f(config)\n}","line":{"from":72,"to":85}} {"id":100029666,"name":"IsExternal","signature":"func IsExternal(name string) bool","file":"staging/src/k8s.io/cloud-provider/plugins.go","code":"// Detects if the string is an external cloud provider\nfunc IsExternal(name string) bool {\n\treturn name == externalCloudProvider\n}","line":{"from":87,"to":90}} {"id":100029667,"name":"IsDeprecatedInternal","signature":"func IsDeprecatedInternal(name string) bool","file":"staging/src/k8s.io/cloud-provider/plugins.go","code":"// IsDeprecatedInternal is responsible for preventing cloud.Interface\n// from being initialized in kubelet, kube-controller-manager or kube-api-server\nfunc IsDeprecatedInternal(name string) bool {\n\tfor _, provider := range deprecatedCloudProviders {\n\t\tif provider.name == name {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":92,"to":102}} {"id":100029668,"name":"DisableWarningForProvider","signature":"func DisableWarningForProvider(providerName string)","file":"staging/src/k8s.io/cloud-provider/plugins.go","code":"// DisableWarningForProvider logs information about disabled cloud provider state\nfunc DisableWarningForProvider(providerName string) {\n\tfor _, provider := range deprecatedCloudProviders {\n\t\tif provider.name == providerName {\n\t\t\tklog.Infof(\"INFO: Please make sure you are running external cloud controller manager binary for provider %q.\"+\n\t\t\t\t\"In-tree cloud providers are currently disabled. Refer to https://github.com/kubernetes/kubernetes/tree/master/staging/src/k8s.io/cloud-provider/sample\"+\n\t\t\t\t\"for example implementation.\", providerName)\n\t\t\tdetail := fmt.Sprintf(\"Please reach to sig-cloud-provider and use 'external' cloud provider for %q: %s\", providerName, provider.detail)\n\t\t\tklog.Warningf(\"WARNING: %q built-in cloud provider is now disabled. %s\", providerName, detail)\n\t\t\tbreak\n\t\t}\n\t}\n}","line":{"from":104,"to":116}} {"id":100029669,"name":"DeprecationWarningForProvider","signature":"func DeprecationWarningForProvider(providerName string)","file":"staging/src/k8s.io/cloud-provider/plugins.go","code":"// DeprecationWarningForProvider logs information about deprecated cloud provider state\nfunc DeprecationWarningForProvider(providerName string) {\n\tfor _, provider := range deprecatedCloudProviders {\n\t\tif provider.name != providerName {\n\t\t\tcontinue\n\t\t}\n\n\t\tdetail := provider.detail\n\t\tif provider.external {\n\t\t\tdetail = fmt.Sprintf(\"Please use 'external' cloud provider for %s: %s\", providerName, provider.detail)\n\t\t}\n\n\t\tklog.Warningf(\"WARNING: %s built-in cloud provider is now deprecated. %s\", providerName, detail)\n\t\tbreak\n\t}\n}","line":{"from":118,"to":133}} {"id":100029670,"name":"InitCloudProvider","signature":"func InitCloudProvider(name string, configFilePath string) (Interface, error)","file":"staging/src/k8s.io/cloud-provider/plugins.go","code":"// InitCloudProvider creates an instance of the named cloud provider.\nfunc InitCloudProvider(name string, configFilePath string) (Interface, error) {\n\tvar cloud Interface\n\tvar err error\n\n\tif name == \"\" {\n\t\treturn nil, nil\n\t}\n\n\tif IsExternal(name) {\n\t\tklog.Info(\"External cloud provider specified\")\n\t\treturn nil, nil\n\t}\n\n\tif configFilePath != \"\" {\n\t\tvar config *os.File\n\t\tconfig, err = os.Open(configFilePath)\n\t\tif err != nil {\n\t\t\tklog.Fatalf(\"Couldn't open cloud provider configuration %s: %#v\",\n\t\t\t\tconfigFilePath, err)\n\t\t}\n\n\t\tdefer config.Close()\n\t\tcloud, err = GetCloudProvider(name, config)\n\t} else {\n\t\t// Pass explicit nil so plugins can actually check for nil. See\n\t\t// \"Why is my nil error value not equal to nil?\" in golang.org/doc/faq.\n\t\tcloud, err = GetCloudProvider(name, nil)\n\t}\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not init cloud provider %q: %v\", name, err)\n\t}\n\tif cloud == nil {\n\t\treturn nil, fmt.Errorf(\"unknown cloud provider %q\", name)\n\t}\n\n\treturn cloud, nil\n}","line":{"from":135,"to":173}} {"id":100029671,"name":"IsAllowAll","signature":"func IsAllowAll(ipnets utilnet.IPNetSet) bool","file":"staging/src/k8s.io/cloud-provider/service/helpers/helper.go","code":"// IsAllowAll checks whether the utilnet.IPNet allows traffic from 0.0.0.0/0\nfunc IsAllowAll(ipnets utilnet.IPNetSet) bool {\n\tfor _, s := range ipnets.StringSlice() {\n\t\tif s == \"0.0.0.0/0\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":47,"to":55}} {"id":100029672,"name":"GetLoadBalancerSourceRanges","signature":"func GetLoadBalancerSourceRanges(service *v1.Service) (utilnet.IPNetSet, error)","file":"staging/src/k8s.io/cloud-provider/service/helpers/helper.go","code":"// GetLoadBalancerSourceRanges first try to parse and verify LoadBalancerSourceRanges field from a service.\n// If the field is not specified, turn to parse and verify the AnnotationLoadBalancerSourceRangesKey annotation from a service,\n// extracting the source ranges to allow, and if not present returns a default (allow-all) value.\nfunc GetLoadBalancerSourceRanges(service *v1.Service) (utilnet.IPNetSet, error) {\n\tvar ipnets utilnet.IPNetSet\n\tvar err error\n\t// if SourceRange field is specified, ignore sourceRange annotation\n\tif len(service.Spec.LoadBalancerSourceRanges) \u003e 0 {\n\t\tspecs := service.Spec.LoadBalancerSourceRanges\n\t\tipnets, err = utilnet.ParseIPNets(specs...)\n\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"service.Spec.LoadBalancerSourceRanges: %v is not valid. Expecting a list of IP ranges. For example, 10.0.0.0/24. Error msg: %v\", specs, err)\n\t\t}\n\t} else {\n\t\tval := service.Annotations[v1.AnnotationLoadBalancerSourceRangesKey]\n\t\tval = strings.TrimSpace(val)\n\t\tif val == \"\" {\n\t\t\tval = defaultLoadBalancerSourceRanges\n\t\t}\n\t\tspecs := strings.Split(val, \",\")\n\t\tipnets, err = utilnet.ParseIPNets(specs...)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%s: %s is not valid. Expecting a comma-separated list of source IP ranges. For example, 10.0.0.0/24,192.168.2.0/24\", v1.AnnotationLoadBalancerSourceRangesKey, val)\n\t\t}\n\t}\n\treturn ipnets, nil\n}","line":{"from":57,"to":84}} {"id":100029673,"name":"GetServiceHealthCheckPathPort","signature":"func GetServiceHealthCheckPathPort(service *v1.Service) (string, int32)","file":"staging/src/k8s.io/cloud-provider/service/helpers/helper.go","code":"// GetServiceHealthCheckPathPort returns the path and nodePort programmed into the Cloud LB Health Check\nfunc GetServiceHealthCheckPathPort(service *v1.Service) (string, int32) {\n\tif !NeedsHealthCheck(service) {\n\t\treturn \"\", 0\n\t}\n\tport := service.Spec.HealthCheckNodePort\n\tif port == 0 {\n\t\treturn \"\", 0\n\t}\n\treturn \"/healthz\", port\n}","line":{"from":86,"to":96}} {"id":100029674,"name":"RequestsOnlyLocalTraffic","signature":"func RequestsOnlyLocalTraffic(service *v1.Service) bool","file":"staging/src/k8s.io/cloud-provider/service/helpers/helper.go","code":"// RequestsOnlyLocalTraffic checks if service requests OnlyLocal traffic.\nfunc RequestsOnlyLocalTraffic(service *v1.Service) bool {\n\tif service.Spec.Type != v1.ServiceTypeLoadBalancer \u0026\u0026\n\t\tservice.Spec.Type != v1.ServiceTypeNodePort {\n\t\treturn false\n\t}\n\treturn service.Spec.ExternalTrafficPolicy == v1.ServiceExternalTrafficPolicyLocal\n}","line":{"from":98,"to":105}} {"id":100029675,"name":"NeedsHealthCheck","signature":"func NeedsHealthCheck(service *v1.Service) bool","file":"staging/src/k8s.io/cloud-provider/service/helpers/helper.go","code":"// NeedsHealthCheck checks if service needs health check.\nfunc NeedsHealthCheck(service *v1.Service) bool {\n\tif service.Spec.Type != v1.ServiceTypeLoadBalancer {\n\t\treturn false\n\t}\n\treturn RequestsOnlyLocalTraffic(service)\n}","line":{"from":107,"to":113}} {"id":100029676,"name":"HasLBFinalizer","signature":"func HasLBFinalizer(service *v1.Service) bool","file":"staging/src/k8s.io/cloud-provider/service/helpers/helper.go","code":"// HasLBFinalizer checks if service contains LoadBalancerCleanupFinalizer.\nfunc HasLBFinalizer(service *v1.Service) bool {\n\tfor _, finalizer := range service.ObjectMeta.Finalizers {\n\t\tif finalizer == LoadBalancerCleanupFinalizer {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":115,"to":123}} {"id":100029677,"name":"LoadBalancerStatusEqual","signature":"func LoadBalancerStatusEqual(l, r *v1.LoadBalancerStatus) bool","file":"staging/src/k8s.io/cloud-provider/service/helpers/helper.go","code":"// LoadBalancerStatusEqual checks if load balancer status are equal\nfunc LoadBalancerStatusEqual(l, r *v1.LoadBalancerStatus) bool {\n\treturn ingressSliceEqual(l.Ingress, r.Ingress)\n}","line":{"from":125,"to":128}} {"id":100029678,"name":"PatchService","signature":"func PatchService(c corev1.CoreV1Interface, oldSvc, newSvc *v1.Service) (*v1.Service, error)","file":"staging/src/k8s.io/cloud-provider/service/helpers/helper.go","code":"// PatchService patches the given service's Status or ObjectMeta based on the original and\n// updated ones. Change to spec will be ignored.\nfunc PatchService(c corev1.CoreV1Interface, oldSvc, newSvc *v1.Service) (*v1.Service, error) {\n\t// Reset spec to make sure only patch for Status or ObjectMeta.\n\tnewSvc.Spec = oldSvc.Spec\n\n\tpatchBytes, err := getPatchBytes(oldSvc, newSvc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.Services(oldSvc.Namespace).Patch(context.TODO(), oldSvc.Name, types.StrategicMergePatchType, patchBytes, metav1.PatchOptions{}, \"status\")\n\n}","line":{"from":130,"to":143}} {"id":100029679,"name":"getPatchBytes","signature":"func getPatchBytes(oldSvc, newSvc *v1.Service) ([]byte, error)","file":"staging/src/k8s.io/cloud-provider/service/helpers/helper.go","code":"func getPatchBytes(oldSvc, newSvc *v1.Service) ([]byte, error) {\n\toldData, err := json.Marshal(oldSvc)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to Marshal oldData for svc %s/%s: %v\", oldSvc.Namespace, oldSvc.Name, err)\n\t}\n\n\tnewData, err := json.Marshal(newSvc)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to Marshal newData for svc %s/%s: %v\", newSvc.Namespace, newSvc.Name, err)\n\t}\n\n\tpatchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, v1.Service{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to CreateTwoWayMergePatch for svc %s/%s: %v\", oldSvc.Namespace, oldSvc.Name, err)\n\t}\n\treturn patchBytes, nil\n\n}","line":{"from":145,"to":162}} {"id":100029680,"name":"ingressSliceEqual","signature":"func ingressSliceEqual(lhs, rhs []v1.LoadBalancerIngress) bool","file":"staging/src/k8s.io/cloud-provider/service/helpers/helper.go","code":"func ingressSliceEqual(lhs, rhs []v1.LoadBalancerIngress) bool {\n\tif len(lhs) != len(rhs) {\n\t\treturn false\n\t}\n\tfor i := range lhs {\n\t\tif !ingressEqual(\u0026lhs[i], \u0026rhs[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":164,"to":174}} {"id":100029681,"name":"ingressEqual","signature":"func ingressEqual(lhs, rhs *v1.LoadBalancerIngress) bool","file":"staging/src/k8s.io/cloud-provider/service/helpers/helper.go","code":"func ingressEqual(lhs, rhs *v1.LoadBalancerIngress) bool {\n\tif lhs.IP != rhs.IP {\n\t\treturn false\n\t}\n\tif lhs.Hostname != rhs.Hostname {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":176,"to":184}} {"id":100029682,"name":"NewDeletedVolumeInUseError","signature":"func NewDeletedVolumeInUseError(message string) error","file":"staging/src/k8s.io/cloud-provider/volume/errors/errors.go","code":"// NewDeletedVolumeInUseError returns a new instance of DeletedVolumeInUseError\n// error.\nfunc NewDeletedVolumeInUseError(message string) error {\n\treturn deletedVolumeInUseError(message)\n}","line":{"from":23,"to":27}} {"id":100029683,"name":"IsDeletedVolumeInUse","signature":"func IsDeletedVolumeInUse(err error) bool","file":"staging/src/k8s.io/cloud-provider/volume/errors/errors.go","code":"// IsDeletedVolumeInUse returns true if an error returned from Delete() is\n// deletedVolumeInUseError\nfunc IsDeletedVolumeInUse(err error) bool {\n\tswitch err.(type) {\n\tcase deletedVolumeInUseError:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":33,"to":42}} {"id":100029684,"name":"Error","signature":"func (err deletedVolumeInUseError) Error() string","file":"staging/src/k8s.io/cloud-provider/volume/errors/errors.go","code":"func (err deletedVolumeInUseError) Error() string {\n\treturn string(err)\n}","line":{"from":44,"to":46}} {"id":100029685,"name":"Error","signature":"func (err *DanglingAttachError) Error() string","file":"staging/src/k8s.io/cloud-provider/volume/errors/errors.go","code":"func (err *DanglingAttachError) Error() string {\n\treturn err.msg\n}","line":{"from":56,"to":58}} {"id":100029686,"name":"NewDanglingError","signature":"func NewDanglingError(msg string, node k8stypes.NodeName, devicePath string) error","file":"staging/src/k8s.io/cloud-provider/volume/errors/errors.go","code":"// NewDanglingError create a new dangling error\nfunc NewDanglingError(msg string, node k8stypes.NodeName, devicePath string) error {\n\treturn \u0026DanglingAttachError{\n\t\tmsg: msg,\n\t\tCurrentNode: node,\n\t\tDevicePath: devicePath,\n\t}\n}","line":{"from":60,"to":67}} {"id":100029687,"name":"IsDanglingError","signature":"func IsDanglingError(err error) bool","file":"staging/src/k8s.io/cloud-provider/volume/errors/errors.go","code":"// IsDanglingError returns true if an error is DanglingAttachError\nfunc IsDanglingError(err error) bool {\n\tswitch err.(type) {\n\tcase *DanglingAttachError:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":69,"to":77}} {"id":100029688,"name":"RoundUpToGiB","signature":"func RoundUpToGiB(size resource.Quantity) (int64, error)","file":"staging/src/k8s.io/cloud-provider/volume/helpers/rounding.go","code":"// RoundUpToGiB rounds up given quantity upto chunks of GiB\nfunc RoundUpToGiB(size resource.Quantity) (int64, error) {\n\treturn roundUpSizeInt64(size, GiB)\n}","line":{"from":54,"to":57}} {"id":100029689,"name":"RoundUpToMB","signature":"func RoundUpToMB(size resource.Quantity) (int64, error)","file":"staging/src/k8s.io/cloud-provider/volume/helpers/rounding.go","code":"// RoundUpToMB rounds up given quantity to chunks of MB\nfunc RoundUpToMB(size resource.Quantity) (int64, error) {\n\treturn roundUpSizeInt64(size, MB)\n}","line":{"from":59,"to":62}} {"id":100029690,"name":"RoundUpToMiB","signature":"func RoundUpToMiB(size resource.Quantity) (int64, error)","file":"staging/src/k8s.io/cloud-provider/volume/helpers/rounding.go","code":"// RoundUpToMiB rounds up given quantity upto chunks of MiB\nfunc RoundUpToMiB(size resource.Quantity) (int64, error) {\n\treturn roundUpSizeInt64(size, MiB)\n}","line":{"from":64,"to":67}} {"id":100029691,"name":"RoundUpToKB","signature":"func RoundUpToKB(size resource.Quantity) (int64, error)","file":"staging/src/k8s.io/cloud-provider/volume/helpers/rounding.go","code":"// RoundUpToKB rounds up given quantity to chunks of KB\nfunc RoundUpToKB(size resource.Quantity) (int64, error) {\n\treturn roundUpSizeInt64(size, KB)\n}","line":{"from":69,"to":72}} {"id":100029692,"name":"RoundUpToKiB","signature":"func RoundUpToKiB(size resource.Quantity) (int64, error)","file":"staging/src/k8s.io/cloud-provider/volume/helpers/rounding.go","code":"// RoundUpToKiB rounds up given quantity to chunks of KiB\nfunc RoundUpToKiB(size resource.Quantity) (int64, error) {\n\treturn roundUpSizeInt64(size, KiB)\n}","line":{"from":74,"to":77}} {"id":100029693,"name":"RoundUpToB","signature":"func RoundUpToB(size resource.Quantity) (int64, error)","file":"staging/src/k8s.io/cloud-provider/volume/helpers/rounding.go","code":"// RoundUpToB rounds up given quantity to chunks of bytes\nfunc RoundUpToB(size resource.Quantity) (int64, error) {\n\treturn roundUpSizeInt64(size, 1)\n}","line":{"from":79,"to":82}} {"id":100029694,"name":"RoundUpToGiBInt","signature":"func RoundUpToGiBInt(size resource.Quantity) (int, error)","file":"staging/src/k8s.io/cloud-provider/volume/helpers/rounding.go","code":"// RoundUpToGiBInt rounds up given quantity upto chunks of GiB. It returns an\n// int instead of an int64 and an error if there's overflow\nfunc RoundUpToGiBInt(size resource.Quantity) (int, error) {\n\treturn roundUpSizeInt(size, GiB)\n}","line":{"from":84,"to":88}} {"id":100029695,"name":"RoundUpToMBInt","signature":"func RoundUpToMBInt(size resource.Quantity) (int, error)","file":"staging/src/k8s.io/cloud-provider/volume/helpers/rounding.go","code":"// RoundUpToMBInt rounds up given quantity to chunks of MB. It returns an\n// int instead of an int64 and an error if there's overflow\nfunc RoundUpToMBInt(size resource.Quantity) (int, error) {\n\treturn roundUpSizeInt(size, MB)\n}","line":{"from":90,"to":94}} {"id":100029696,"name":"RoundUpToMiBInt","signature":"func RoundUpToMiBInt(size resource.Quantity) (int, error)","file":"staging/src/k8s.io/cloud-provider/volume/helpers/rounding.go","code":"// RoundUpToMiBInt rounds up given quantity upto chunks of MiB. It returns an\n// int instead of an int64 and an error if there's overflow\nfunc RoundUpToMiBInt(size resource.Quantity) (int, error) {\n\treturn roundUpSizeInt(size, MiB)\n}","line":{"from":96,"to":100}} {"id":100029697,"name":"RoundUpToKBInt","signature":"func RoundUpToKBInt(size resource.Quantity) (int, error)","file":"staging/src/k8s.io/cloud-provider/volume/helpers/rounding.go","code":"// RoundUpToKBInt rounds up given quantity to chunks of KB. It returns an\n// int instead of an int64 and an error if there's overflow\nfunc RoundUpToKBInt(size resource.Quantity) (int, error) {\n\treturn roundUpSizeInt(size, KB)\n}","line":{"from":102,"to":106}} {"id":100029698,"name":"RoundUpToKiBInt","signature":"func RoundUpToKiBInt(size resource.Quantity) (int, error)","file":"staging/src/k8s.io/cloud-provider/volume/helpers/rounding.go","code":"// RoundUpToKiBInt rounds up given quantity upto chunks of KiB. It returns an\n// int instead of an int64 and an error if there's overflow\nfunc RoundUpToKiBInt(size resource.Quantity) (int, error) {\n\treturn roundUpSizeInt(size, KiB)\n}","line":{"from":108,"to":112}} {"id":100029699,"name":"RoundUpToGiBInt32","signature":"func RoundUpToGiBInt32(size resource.Quantity) (int32, error)","file":"staging/src/k8s.io/cloud-provider/volume/helpers/rounding.go","code":"// RoundUpToGiBInt32 rounds up given quantity up to chunks of GiB. It returns an\n// int32 instead of an int64 and an error if there's overflow\nfunc RoundUpToGiBInt32(size resource.Quantity) (int32, error) {\n\treturn roundUpSizeInt32(size, GiB)\n}","line":{"from":114,"to":118}} {"id":100029700,"name":"roundUpSizeInt","signature":"func roundUpSizeInt(size resource.Quantity, allocationUnitBytes int64) (int, error)","file":"staging/src/k8s.io/cloud-provider/volume/helpers/rounding.go","code":"// roundUpSizeInt calculates how many allocation units are needed to accommodate\n// a volume of a given size. It returns an int and an error if there's overflow\nfunc roundUpSizeInt(size resource.Quantity, allocationUnitBytes int64) (int, error) {\n\tif bits.UintSize == 32 {\n\t\tres, err := roundUpSizeInt32(size, allocationUnitBytes)\n\t\treturn int(res), err\n\t}\n\tres, err := roundUpSizeInt64(size, allocationUnitBytes)\n\treturn int(res), err\n}","line":{"from":120,"to":129}} {"id":100029701,"name":"roundUpSizeInt32","signature":"func roundUpSizeInt32(size resource.Quantity, allocationUnitBytes int64) (int32, error)","file":"staging/src/k8s.io/cloud-provider/volume/helpers/rounding.go","code":"// roundUpSizeInt32 calculates how many allocation units are needed to accommodate\n// a volume of a given size. It returns an int32 and an error if there's overflow\nfunc roundUpSizeInt32(size resource.Quantity, allocationUnitBytes int64) (int32, error) {\n\troundedUpInt32, err := roundUpSizeInt64(size, allocationUnitBytes)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif roundedUpInt32 \u003e math.MaxInt32 {\n\t\treturn 0, fmt.Errorf(\"quantity %s is too great, overflows int32\", size.String())\n\t}\n\treturn int32(roundedUpInt32), nil\n}","line":{"from":131,"to":142}} {"id":100029702,"name":"roundUpSizeInt64","signature":"func roundUpSizeInt64(size resource.Quantity, allocationUnitBytes int64) (int64, error)","file":"staging/src/k8s.io/cloud-provider/volume/helpers/rounding.go","code":"// roundUpSizeInt64 calculates how many allocation units are needed to accommodate\n// a volume of a given size. It returns an int64 and an error if there's overflow\nfunc roundUpSizeInt64(size resource.Quantity, allocationUnitBytes int64) (int64, error) {\n\t// Use CmpInt64() to find out if the value of \"size\" would overflow an\n\t// int64 and therefore have Value() return a wrong result. Then, retrieve\n\t// the value as int64 and perform the rounding.\n\t// It's not convenient to use AsScale() and related functions as they don't\n\t// support BinarySI format, nor can we use AsInt64() directly since it's\n\t// only implemented for int64 scaled numbers (int64Amount).\n\n\t// CmpInt64() actually returns 0 when comparing an amount bigger than MaxInt64.\n\tif size.CmpInt64(math.MaxInt64) \u003e= 0 {\n\t\treturn 0, fmt.Errorf(\"quantity %s is too great, overflows int64\", size.String())\n\t}\n\tvolumeSizeBytes := size.Value()\n\n\troundedUp := volumeSizeBytes / allocationUnitBytes\n\tif volumeSizeBytes%allocationUnitBytes \u003e 0 {\n\t\troundedUp++\n\t}\n\treturn roundedUp, nil\n}","line":{"from":144,"to":165}} {"id":100029703,"name":"LabelZonesToSet","signature":"func LabelZonesToSet(labelZonesValue string) (sets.String, error)","file":"staging/src/k8s.io/cloud-provider/volume/helpers/zones.go","code":"// LabelZonesToSet converts a PV label value from string containing a delimited list of zones to set\nfunc LabelZonesToSet(labelZonesValue string) (sets.String, error) {\n\treturn stringToSet(labelZonesValue, cloudvolume.LabelMultiZoneDelimiter)\n}","line":{"from":32,"to":35}} {"id":100029704,"name":"ZonesSetToLabelValue","signature":"func ZonesSetToLabelValue(strSet sets.String) string","file":"staging/src/k8s.io/cloud-provider/volume/helpers/zones.go","code":"// ZonesSetToLabelValue converts zones set to label value\nfunc ZonesSetToLabelValue(strSet sets.String) string {\n\treturn strings.Join(strSet.UnsortedList(), cloudvolume.LabelMultiZoneDelimiter)\n}","line":{"from":37,"to":40}} {"id":100029705,"name":"ZonesToSet","signature":"func ZonesToSet(zonesString string) (sets.String, error)","file":"staging/src/k8s.io/cloud-provider/volume/helpers/zones.go","code":"// ZonesToSet converts a string containing a comma separated list of zones to set\nfunc ZonesToSet(zonesString string) (sets.String, error) {\n\tzones, err := stringToSet(zonesString, \",\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing zones %s, must be strings separated by commas: %v\", zonesString, err)\n\t}\n\treturn zones, nil\n}","line":{"from":42,"to":49}} {"id":100029706,"name":"stringToSet","signature":"func stringToSet(str, delimiter string) (sets.String, error)","file":"staging/src/k8s.io/cloud-provider/volume/helpers/zones.go","code":"// StringToSet converts a string containing list separated by specified delimiter to a set\nfunc stringToSet(str, delimiter string) (sets.String, error) {\n\tzonesSlice := strings.Split(str, delimiter)\n\tzonesSet := make(sets.String)\n\tfor _, zone := range zonesSlice {\n\t\ttrimmedZone := strings.TrimSpace(zone)\n\t\tif trimmedZone == \"\" {\n\t\t\treturn make(sets.String), fmt.Errorf(\n\t\t\t\t\"%q separated list (%q) must not contain an empty string\",\n\t\t\t\tdelimiter,\n\t\t\t\tstr)\n\t\t}\n\t\tzonesSet.Insert(trimmedZone)\n\t}\n\treturn zonesSet, nil\n}","line":{"from":51,"to":66}} {"id":100029707,"name":"LabelZonesToList","signature":"func LabelZonesToList(labelZonesValue string) ([]string, error)","file":"staging/src/k8s.io/cloud-provider/volume/helpers/zones.go","code":"// LabelZonesToList converts a PV label value from string containing a delimited list of zones to list\nfunc LabelZonesToList(labelZonesValue string) ([]string, error) {\n\treturn stringToList(labelZonesValue, cloudvolume.LabelMultiZoneDelimiter)\n}","line":{"from":68,"to":71}} {"id":100029708,"name":"stringToList","signature":"func stringToList(str, delimiter string) ([]string, error)","file":"staging/src/k8s.io/cloud-provider/volume/helpers/zones.go","code":"// StringToList converts a string containing list separated by specified delimiter to a list\nfunc stringToList(str, delimiter string) ([]string, error) {\n\tzonesSlice := make([]string, 0)\n\tfor _, zone := range strings.Split(str, delimiter) {\n\t\ttrimmedZone := strings.TrimSpace(zone)\n\t\tif trimmedZone == \"\" {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"%q separated list (%q) must not contain an empty string\",\n\t\t\t\tdelimiter,\n\t\t\t\tstr)\n\t\t}\n\t\tzonesSlice = append(zonesSlice, trimmedZone)\n\t}\n\treturn zonesSlice, nil\n}","line":{"from":73,"to":87}} {"id":100029709,"name":"SelectZoneForVolume","signature":"func SelectZoneForVolume(zoneParameterPresent, zonesParameterPresent bool, zoneParameter string, zonesParameter, zonesWithNodes sets.String, node *v1.Node, allowedTopologies []v1.TopologySelectorTerm, pvcName string) (string, error)","file":"staging/src/k8s.io/cloud-provider/volume/helpers/zones.go","code":"// SelectZoneForVolume is a wrapper around SelectZonesForVolume\n// to select a single zone for a volume based on parameters\nfunc SelectZoneForVolume(zoneParameterPresent, zonesParameterPresent bool, zoneParameter string, zonesParameter, zonesWithNodes sets.String, node *v1.Node, allowedTopologies []v1.TopologySelectorTerm, pvcName string) (string, error) {\n\tzones, err := SelectZonesForVolume(zoneParameterPresent, zonesParameterPresent, zoneParameter, zonesParameter, zonesWithNodes, node, allowedTopologies, pvcName, 1)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tzone, ok := zones.PopAny()\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"could not determine a zone to provision volume in\")\n\t}\n\treturn zone, nil\n}","line":{"from":89,"to":101}} {"id":100029710,"name":"SelectZonesForVolume","signature":"func SelectZonesForVolume(zoneParameterPresent, zonesParameterPresent bool, zoneParameter string, zonesParameter, zonesWithNodes sets.String, node *v1.Node, allowedTopologies []v1.TopologySelectorTerm, pvcName string, numReplicas uint32) (sets.String, error)","file":"staging/src/k8s.io/cloud-provider/volume/helpers/zones.go","code":"// SelectZonesForVolume selects zones for a volume based on several factors:\n// node.zone, allowedTopologies, zone/zones parameters from storageclass,\n// zones with active nodes from the cluster. The number of zones = replicas.\nfunc SelectZonesForVolume(zoneParameterPresent, zonesParameterPresent bool, zoneParameter string, zonesParameter, zonesWithNodes sets.String, node *v1.Node, allowedTopologies []v1.TopologySelectorTerm, pvcName string, numReplicas uint32) (sets.String, error) {\n\tif zoneParameterPresent \u0026\u0026 zonesParameterPresent {\n\t\treturn nil, fmt.Errorf(\"both zone and zones StorageClass parameters must not be used at the same time\")\n\t}\n\n\tvar zoneFromNode string\n\t// pick one zone from node if present\n\tif node != nil {\n\t\t// VolumeScheduling implicit since node is not nil\n\t\tif zoneParameterPresent || zonesParameterPresent {\n\t\t\treturn nil, fmt.Errorf(\"zone[s] cannot be specified in StorageClass if VolumeBindingMode is set to WaitForFirstConsumer. Please specify allowedTopologies in StorageClass for constraining zones\")\n\t\t}\n\n\t\t// pick node's zone for one of the replicas\n\t\tvar ok bool\n\t\tzoneFromNode, ok = node.ObjectMeta.Labels[v1.LabelTopologyZone]\n\t\tif !ok {\n\t\t\tzoneFromNode, ok = node.ObjectMeta.Labels[v1.LabelFailureDomainBetaZone]\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"Either %s or %s Label for node missing\", v1.LabelTopologyZone, v1.LabelFailureDomainBetaZone)\n\t\t\t}\n\t\t}\n\t\t// if single replica volume and node with zone found, return immediately\n\t\tif numReplicas == 1 {\n\t\t\treturn sets.NewString(zoneFromNode), nil\n\t\t}\n\t}\n\n\t// pick zone from allowedZones if specified\n\tallowedZones, err := ZonesFromAllowedTopologies(allowedTopologies)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif (len(allowedTopologies) \u003e 0) \u0026\u0026 (allowedZones.Len() == 0) {\n\t\treturn nil, fmt.Errorf(\"no matchLabelExpressions with %s key found in allowedTopologies. Please specify matchLabelExpressions with %s key\", v1.LabelTopologyZone, v1.LabelTopologyZone)\n\t}\n\n\tif allowedZones.Len() \u003e 0 {\n\t\t// VolumeScheduling implicit since allowedZones present\n\t\tif zoneParameterPresent || zonesParameterPresent {\n\t\t\treturn nil, fmt.Errorf(\"zone[s] cannot be specified in StorageClass if allowedTopologies specified\")\n\t\t}\n\t\t// scheduler will guarantee if node != null above, zoneFromNode is member of allowedZones.\n\t\t// so if zoneFromNode != \"\", we can safely assume it is part of allowedZones.\n\t\tzones, err := chooseZonesForVolumeIncludingZone(allowedZones, pvcName, zoneFromNode, numReplicas)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot process zones in allowedTopologies: %v\", err)\n\t\t}\n\t\treturn zones, nil\n\t}\n\n\t// pick zone from parameters if present\n\tif zoneParameterPresent {\n\t\tif numReplicas \u003e 1 {\n\t\t\treturn nil, fmt.Errorf(\"zone cannot be specified if desired number of replicas for pv is greather than 1. Please specify zones or allowedTopologies to specify desired zones\")\n\t\t}\n\t\treturn sets.NewString(zoneParameter), nil\n\t}\n\n\tif zonesParameterPresent {\n\t\tif uint32(zonesParameter.Len()) \u003c numReplicas {\n\t\t\treturn nil, fmt.Errorf(\"not enough zones found in zones parameter to provision a volume with %d replicas. Found %d zones, need %d zones\", numReplicas, zonesParameter.Len(), numReplicas)\n\t\t}\n\t\t// directly choose from zones parameter; no zone from node need to be considered\n\t\treturn ChooseZonesForVolume(zonesParameter, pvcName, numReplicas), nil\n\t}\n\n\t// pick zone from zones with nodes\n\tif zonesWithNodes.Len() \u003e 0 {\n\t\t// If node != null (and thus zoneFromNode != \"\"), zoneFromNode will be member of zonesWithNodes\n\t\tzones, err := chooseZonesForVolumeIncludingZone(zonesWithNodes, pvcName, zoneFromNode, numReplicas)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot process zones where nodes exist in the cluster: %v\", err)\n\t\t}\n\t\treturn zones, nil\n\t}\n\treturn nil, fmt.Errorf(\"cannot determine zones to provision volume in\")\n}","line":{"from":103,"to":184}} {"id":100029711,"name":"ZonesFromAllowedTopologies","signature":"func ZonesFromAllowedTopologies(allowedTopologies []v1.TopologySelectorTerm) (sets.String, error)","file":"staging/src/k8s.io/cloud-provider/volume/helpers/zones.go","code":"// ZonesFromAllowedTopologies returns a list of zones specified in allowedTopologies\nfunc ZonesFromAllowedTopologies(allowedTopologies []v1.TopologySelectorTerm) (sets.String, error) {\n\tzones := make(sets.String)\n\tfor _, term := range allowedTopologies {\n\t\tfor _, exp := range term.MatchLabelExpressions {\n\t\t\tif exp.Key == v1.LabelTopologyZone || exp.Key == v1.LabelFailureDomainBetaZone {\n\t\t\t\tfor _, value := range exp.Values {\n\t\t\t\t\tzones.Insert(value)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn nil, fmt.Errorf(\"unsupported key found in matchLabelExpressions: %s\", exp.Key)\n\t\t\t}\n\t\t}\n\t}\n\treturn zones, nil\n}","line":{"from":186,"to":201}} {"id":100029712,"name":"chooseZonesForVolumeIncludingZone","signature":"func chooseZonesForVolumeIncludingZone(zones sets.String, pvcName, zoneToInclude string, numReplicas uint32) (sets.String, error)","file":"staging/src/k8s.io/cloud-provider/volume/helpers/zones.go","code":"// chooseZonesForVolumeIncludingZone is a wrapper around ChooseZonesForVolume that ensures zoneToInclude is chosen\n// zoneToInclude can either be empty in which case it is ignored. If non-empty, zoneToInclude is expected to be member of zones.\n// numReplicas is expected to be \u003e 0 and \u003c= zones.Len()\nfunc chooseZonesForVolumeIncludingZone(zones sets.String, pvcName, zoneToInclude string, numReplicas uint32) (sets.String, error) {\n\tif numReplicas == 0 {\n\t\treturn nil, fmt.Errorf(\"invalid number of replicas passed\")\n\t}\n\tif uint32(zones.Len()) \u003c numReplicas {\n\t\treturn nil, fmt.Errorf(\"not enough zones found to provision a volume with %d replicas. Need at least %d distinct zones for a volume with %d replicas\", numReplicas, numReplicas, numReplicas)\n\t}\n\tif zoneToInclude != \"\" \u0026\u0026 !zones.Has(zoneToInclude) {\n\t\treturn nil, fmt.Errorf(\"zone to be included: %s needs to be member of set: %v\", zoneToInclude, zones)\n\t}\n\tif uint32(zones.Len()) == numReplicas {\n\t\treturn zones, nil\n\t}\n\tif zoneToInclude != \"\" {\n\t\tzones.Delete(zoneToInclude)\n\t\tnumReplicas = numReplicas - 1\n\t}\n\tzonesChosen := ChooseZonesForVolume(zones, pvcName, numReplicas)\n\tif zoneToInclude != \"\" {\n\t\tzonesChosen.Insert(zoneToInclude)\n\t}\n\treturn zonesChosen, nil\n}","line":{"from":203,"to":228}} {"id":100029713,"name":"ChooseZonesForVolume","signature":"func ChooseZonesForVolume(zones sets.String, pvcName string, numZones uint32) sets.String","file":"staging/src/k8s.io/cloud-provider/volume/helpers/zones.go","code":"// ChooseZonesForVolume is identical to ChooseZoneForVolume, but selects a multiple zones, for multi-zone disks.\nfunc ChooseZonesForVolume(zones sets.String, pvcName string, numZones uint32) sets.String {\n\t// No zones available, return empty set.\n\treplicaZones := sets.NewString()\n\tif zones.Len() == 0 {\n\t\treturn replicaZones\n\t}\n\n\t// We create the volume in a zone determined by the name\n\t// Eventually the scheduler will coordinate placement into an available zone\n\thash, index := getPVCNameHashAndIndexOffset(pvcName)\n\n\t// Zones.List returns zones in a consistent order (sorted)\n\t// We do have a potential failure case where volumes will not be properly spread,\n\t// if the set of zones changes during StatefulSet volume creation. However, this is\n\t// probably relatively unlikely because we expect the set of zones to be essentially\n\t// static for clusters.\n\t// Hopefully we can address this problem if/when we do full scheduler integration of\n\t// PVC placement (which could also e.g. avoid putting volumes in overloaded or\n\t// unhealthy zones)\n\tzoneSlice := zones.List()\n\n\tstartingIndex := index * numZones\n\tfor index = startingIndex; index \u003c startingIndex+numZones; index++ {\n\t\tzone := zoneSlice[(hash+index)%uint32(len(zoneSlice))]\n\t\treplicaZones.Insert(zone)\n\t}\n\n\tklog.V(2).Infof(\"Creating volume for replicated PVC %q; chosen zones=%q from zones=%q\",\n\t\tpvcName, replicaZones.UnsortedList(), zoneSlice)\n\treturn replicaZones\n}","line":{"from":230,"to":261}} {"id":100029714,"name":"getPVCNameHashAndIndexOffset","signature":"func getPVCNameHashAndIndexOffset(pvcName string) (hash uint32, index uint32)","file":"staging/src/k8s.io/cloud-provider/volume/helpers/zones.go","code":"func getPVCNameHashAndIndexOffset(pvcName string) (hash uint32, index uint32) {\n\tif pvcName == \"\" {\n\t\t// We should always be called with a name; this shouldn't happen\n\t\tklog.Warningf(\"No name defined during volume create; choosing random zone\")\n\n\t\thash = rand.Uint32()\n\t} else {\n\t\thashString := pvcName\n\n\t\t// Heuristic to make sure that volumes in a StatefulSet are spread across zones\n\t\t// StatefulSet PVCs are (currently) named ClaimName-StatefulSetName-Id,\n\t\t// where Id is an integer index.\n\t\t// Note though that if a StatefulSet pod has multiple claims, we need them to be\n\t\t// in the same zone, because otherwise the pod will be unable to mount both volumes,\n\t\t// and will be unschedulable. So we hash _only_ the \"StatefulSetName\" portion when\n\t\t// it looks like `ClaimName-StatefulSetName-Id`.\n\t\t// We continue to round-robin volume names that look like `Name-Id` also; this is a useful\n\t\t// feature for users that are creating statefulset-like functionality without using statefulsets.\n\t\tlastDash := strings.LastIndexByte(pvcName, '-')\n\t\tif lastDash != -1 {\n\t\t\tstatefulsetIDString := pvcName[lastDash+1:]\n\t\t\tstatefulsetID, err := strconv.ParseUint(statefulsetIDString, 10, 32)\n\t\t\tif err == nil {\n\t\t\t\t// Offset by the statefulsetID, so we round-robin across zones\n\t\t\t\tindex = uint32(statefulsetID)\n\t\t\t\t// We still hash the volume name, but only the prefix\n\t\t\t\thashString = pvcName[:lastDash]\n\n\t\t\t\t// In the special case where it looks like `ClaimName-StatefulSetName-Id`,\n\t\t\t\t// hash only the StatefulSetName, so that different claims on the same StatefulSet\n\t\t\t\t// member end up in the same zone.\n\t\t\t\t// Note that StatefulSetName (and ClaimName) might themselves both have dashes.\n\t\t\t\t// We actually just take the portion after the final - of ClaimName-StatefulSetName.\n\t\t\t\t// For our purposes it doesn't much matter (just suboptimal spreading).\n\t\t\t\tlastDash := strings.LastIndexByte(hashString, '-')\n\t\t\t\tif lastDash != -1 {\n\t\t\t\t\thashString = hashString[lastDash+1:]\n\t\t\t\t}\n\n\t\t\t\tklog.V(2).Infof(\"Detected StatefulSet-style volume name %q; index=%d\", pvcName, index)\n\t\t\t}\n\t\t}\n\n\t\t// We hash the (base) volume name, so we don't bias towards the first N zones\n\t\th := fnv.New32()\n\t\th.Write([]byte(hashString))\n\t\thash = h.Sum32()\n\t}\n\n\treturn hash, index\n}","line":{"from":263,"to":313}} {"id":100029715,"name":"ComputeDetachedSignature","signature":"func ComputeDetachedSignature(content, tokenID, tokenSecret string) (string, error)","file":"staging/src/k8s.io/cluster-bootstrap/token/jws/jws.go","code":"// ComputeDetachedSignature takes content and token details and computes a detached\n// JWS signature. This is described in Appendix F of RFC 7515. Basically, this\n// is a regular JWS with the content part of the signature elided.\nfunc ComputeDetachedSignature(content, tokenID, tokenSecret string) (string, error) {\n\tjwk := \u0026jose.JSONWebKey{\n\t\tKey: []byte(tokenSecret),\n\t\tKeyID: tokenID,\n\t}\n\n\topts := \u0026jose.SignerOptions{\n\t\t// Since this is a symmetric key, go-jose doesn't automatically include\n\t\t// the KeyID as part of the protected header. We have to pass it here\n\t\t// explicitly.\n\t\tExtraHeaders: map[jose.HeaderKey]interface{}{\n\t\t\t\"kid\": tokenID,\n\t\t},\n\t}\n\n\tsigner, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.HS256, Key: jwk}, opts)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"can't make a HS256 signer from the given token: %v\", err)\n\t}\n\n\tjws, err := signer.Sign([]byte(content))\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"can't HS256-sign the given token: %v\", err)\n\t}\n\n\tfullSig, err := jws.CompactSerialize()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"can't serialize the given token: %v\", err)\n\t}\n\treturn stripContent(fullSig)\n}","line":{"from":26,"to":59}} {"id":100029716,"name":"stripContent","signature":"func stripContent(fullSig string) (string, error)","file":"staging/src/k8s.io/cluster-bootstrap/token/jws/jws.go","code":"// stripContent will remove the content part of a compact JWS\n//\n// The `go-jose` library doesn't support generating signatures with \"detached\"\n// content. To make up for this we take the full compact signature, break it\n// apart and put it back together without the content section.\nfunc stripContent(fullSig string) (string, error) {\n\tparts := strings.Split(fullSig, \".\")\n\tif len(parts) != 3 {\n\t\treturn \"\", fmt.Errorf(\"compact JWS format must have three parts\")\n\t}\n\n\treturn parts[0] + \"..\" + parts[2], nil\n}","line":{"from":61,"to":73}} {"id":100029717,"name":"DetachedTokenIsValid","signature":"func DetachedTokenIsValid(detachedToken, content, tokenID, tokenSecret string) bool","file":"staging/src/k8s.io/cluster-bootstrap/token/jws/jws.go","code":"// DetachedTokenIsValid checks whether a given detached JWS-encoded token matches JWS output of the given content and token\nfunc DetachedTokenIsValid(detachedToken, content, tokenID, tokenSecret string) bool {\n\tnewToken, err := ComputeDetachedSignature(content, tokenID, tokenSecret)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn detachedToken == newToken\n}","line":{"from":75,"to":82}} {"id":100029718,"name":"GenerateBootstrapToken","signature":"func GenerateBootstrapToken() (string, error)","file":"staging/src/k8s.io/cluster-bootstrap/token/util/helpers.go","code":"// GenerateBootstrapToken generates a new, random Bootstrap Token.\nfunc GenerateBootstrapToken() (string, error) {\n\ttokenID, err := randBytes(api.BootstrapTokenIDBytes)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ttokenSecret, err := randBytes(api.BootstrapTokenSecretBytes)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn TokenFromIDAndSecret(tokenID, tokenSecret), nil\n}","line":{"from":44,"to":57}} {"id":100029719,"name":"randBytes","signature":"func randBytes(length int) (string, error)","file":"staging/src/k8s.io/cluster-bootstrap/token/util/helpers.go","code":"// randBytes returns a random string consisting of the characters in\n// validBootstrapTokenChars, with the length customized by the parameter\nfunc randBytes(length int) (string, error) {\n\t// len(\"0123456789abcdefghijklmnopqrstuvwxyz\") = 36 which doesn't evenly divide\n\t// the possible values of a byte: 256 mod 36 = 4. Discard any random bytes we\n\t// read that are \u003e= 252 so the bytes we evenly divide the character set.\n\tconst maxByteValue = 252\n\n\tvar (\n\t\tb byte\n\t\terr error\n\t\ttoken = make([]byte, length)\n\t)\n\n\treader := bufio.NewReaderSize(rand.Reader, length*2)\n\tfor i := range token {\n\t\tfor {\n\t\t\tif b, err = reader.ReadByte(); err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\tif b \u003c maxByteValue {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\ttoken[i] = validBootstrapTokenChars[int(b)%len(validBootstrapTokenChars)]\n\t}\n\n\treturn string(token), nil\n}","line":{"from":59,"to":88}} {"id":100029720,"name":"TokenFromIDAndSecret","signature":"func TokenFromIDAndSecret(id, secret string) string","file":"staging/src/k8s.io/cluster-bootstrap/token/util/helpers.go","code":"// TokenFromIDAndSecret returns the full token which is of the form \"{id}.{secret}\"\nfunc TokenFromIDAndSecret(id, secret string) string {\n\treturn fmt.Sprintf(\"%s.%s\", id, secret)\n}","line":{"from":90,"to":93}} {"id":100029721,"name":"IsValidBootstrapToken","signature":"func IsValidBootstrapToken(token string) bool","file":"staging/src/k8s.io/cluster-bootstrap/token/util/helpers.go","code":"// IsValidBootstrapToken returns whether the given string is valid as a Bootstrap Token and\n// in other words satisfies the BootstrapTokenRegexp\nfunc IsValidBootstrapToken(token string) bool {\n\treturn BootstrapTokenRegexp.MatchString(token)\n}","line":{"from":95,"to":99}} {"id":100029722,"name":"IsValidBootstrapTokenID","signature":"func IsValidBootstrapTokenID(tokenID string) bool","file":"staging/src/k8s.io/cluster-bootstrap/token/util/helpers.go","code":"// IsValidBootstrapTokenID returns whether the given string is valid as a Bootstrap Token ID and\n// in other words satisfies the BootstrapTokenIDRegexp\nfunc IsValidBootstrapTokenID(tokenID string) bool {\n\treturn BootstrapTokenIDRegexp.MatchString(tokenID)\n}","line":{"from":101,"to":105}} {"id":100029723,"name":"BootstrapTokenSecretName","signature":"func BootstrapTokenSecretName(tokenID string) string","file":"staging/src/k8s.io/cluster-bootstrap/token/util/helpers.go","code":"// BootstrapTokenSecretName returns the expected name for the Secret storing the\n// Bootstrap Token in the Kubernetes API.\nfunc BootstrapTokenSecretName(tokenID string) string {\n\treturn fmt.Sprintf(\"%s%s\", api.BootstrapTokenSecretPrefix, tokenID)\n}","line":{"from":107,"to":111}} {"id":100029724,"name":"ValidateBootstrapGroupName","signature":"func ValidateBootstrapGroupName(name string) error","file":"staging/src/k8s.io/cluster-bootstrap/token/util/helpers.go","code":"// ValidateBootstrapGroupName checks if the provided group name is a valid\n// bootstrap group name. Returns nil if valid or a validation error if invalid.\n// TODO(dixudx): should be moved to util/secrets\nfunc ValidateBootstrapGroupName(name string) error {\n\tif BootstrapGroupRegexp.Match([]byte(name)) {\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"bootstrap group %q is invalid (must match %s)\", name, api.BootstrapGroupPattern)\n}","line":{"from":113,"to":121}} {"id":100029725,"name":"ValidateUsages","signature":"func ValidateUsages(usages []string) error","file":"staging/src/k8s.io/cluster-bootstrap/token/util/helpers.go","code":"// ValidateUsages validates that the passed in string are valid usage strings for bootstrap tokens.\nfunc ValidateUsages(usages []string) error {\n\tvalidUsages := sets.NewString(api.KnownTokenUsages...)\n\tinvalidUsages := sets.NewString()\n\tfor _, usage := range usages {\n\t\tif !validUsages.Has(usage) {\n\t\t\tinvalidUsages.Insert(usage)\n\t\t}\n\t}\n\tif len(invalidUsages) \u003e 0 {\n\t\treturn fmt.Errorf(\"invalid bootstrap token usage string: %s, valid usage options: %s\", strings.Join(invalidUsages.List(), \",\"), strings.Join(api.KnownTokenUsages, \",\"))\n\t}\n\treturn nil\n}","line":{"from":123,"to":136}} {"id":100029726,"name":"GetData","signature":"func GetData(secret *v1.Secret, key string) string","file":"staging/src/k8s.io/cluster-bootstrap/util/secrets/secrets.go","code":"// GetData returns the string value for the given key in the specified Secret\n// If there is an error or if the key doesn't exist, an empty string is returned.\nfunc GetData(secret *v1.Secret, key string) string {\n\tif secret.Data == nil {\n\t\treturn \"\"\n\t}\n\tif val, ok := secret.Data[key]; ok {\n\t\treturn string(val)\n\t}\n\treturn \"\"\n}","line":{"from":35,"to":45}} {"id":100029727,"name":"HasExpired","signature":"func HasExpired(secret *v1.Secret, currentTime time.Time) bool","file":"staging/src/k8s.io/cluster-bootstrap/util/secrets/secrets.go","code":"// HasExpired will identify whether the secret expires\nfunc HasExpired(secret *v1.Secret, currentTime time.Time) bool {\n\t_, expired := GetExpiration(secret, currentTime)\n\n\treturn expired\n}","line":{"from":47,"to":52}} {"id":100029728,"name":"GetExpiration","signature":"func GetExpiration(secret *v1.Secret, currentTime time.Time) (timeRemaining time.Duration, isExpired bool)","file":"staging/src/k8s.io/cluster-bootstrap/util/secrets/secrets.go","code":"// GetExpiration checks if the secret expires\n// isExpired indicates if the secret is already expired.\n// timeRemaining indicates how long until it does expire.\n// if the secret has no expiration timestamp, returns 0, false.\n// if there is an error parsing the secret's expiration timestamp, returns 0, true.\nfunc GetExpiration(secret *v1.Secret, currentTime time.Time) (timeRemaining time.Duration, isExpired bool) {\n\texpiration := GetData(secret, api.BootstrapTokenExpirationKey)\n\tif len(expiration) == 0 {\n\t\treturn 0, false\n\t}\n\texpTime, err := time.Parse(time.RFC3339, expiration)\n\tif err != nil {\n\t\tklog.V(3).Infof(\"Unparseable expiration time (%s) in %s/%s Secret: %v. Treating as expired.\",\n\t\t\texpiration, secret.Namespace, secret.Name, err)\n\t\treturn 0, true\n\t}\n\n\ttimeRemaining = expTime.Sub(currentTime)\n\tif timeRemaining \u003c= 0 {\n\t\tklog.V(3).Infof(\"Expired bootstrap token in %s/%s Secret: %v\",\n\t\t\tsecret.Namespace, secret.Name, expiration)\n\t\treturn 0, true\n\t}\n\treturn timeRemaining, false\n}","line":{"from":54,"to":78}} {"id":100029729,"name":"ParseName","signature":"func ParseName(name string) (secretID string, ok bool)","file":"staging/src/k8s.io/cluster-bootstrap/util/secrets/secrets.go","code":"// ParseName parses the name of the secret to extract the secret ID.\nfunc ParseName(name string) (secretID string, ok bool) {\n\tr := secretNameRe.FindStringSubmatch(name)\n\tif r == nil {\n\t\treturn \"\", false\n\t}\n\treturn r[1], true\n}","line":{"from":80,"to":87}} {"id":100029730,"name":"GetGroups","signature":"func GetGroups(secret *v1.Secret) ([]string, error)","file":"staging/src/k8s.io/cluster-bootstrap/util/secrets/secrets.go","code":"// GetGroups loads and validates the bootstrapapi.BootstrapTokenExtraGroupsKey\n// key from the bootstrap token secret, returning a list of group names or an\n// error if any of the group names are invalid.\nfunc GetGroups(secret *v1.Secret) ([]string, error) {\n\t// always include the default group\n\tgroups := sets.NewString(api.BootstrapDefaultGroup)\n\n\t// grab any extra groups and if there are none, return just the default\n\textraGroupsString := GetData(secret, api.BootstrapTokenExtraGroupsKey)\n\tif extraGroupsString == \"\" {\n\t\treturn groups.List(), nil\n\t}\n\n\t// validate the names of the extra groups\n\tfor _, group := range strings.Split(extraGroupsString, \",\") {\n\t\tif err := legacyutil.ValidateBootstrapGroupName(group); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tgroups.Insert(group)\n\t}\n\n\t// return the result as a deduplicated, sorted list\n\treturn groups.List(), nil\n}","line":{"from":89,"to":112}} {"id":100029731,"name":"ParseToken","signature":"func ParseToken(s string) (tokenID, tokenSecret string, err error)","file":"staging/src/k8s.io/cluster-bootstrap/util/tokens/tokens.go","code":"// ParseToken tries and parse a valid token from a string.\n// A token ID and token secret are returned in case of success, an error otherwise.\nfunc ParseToken(s string) (tokenID, tokenSecret string, err error) {\n\tsplit := bootstrapTokenRe.FindStringSubmatch(s)\n\tif len(split) != 3 {\n\t\treturn \"\", \"\", fmt.Errorf(\"token [%q] was not of form [%q]\", s, api.BootstrapTokenPattern)\n\t}\n\treturn split[1], split[2], nil\n}","line":{"from":30,"to":38}} {"id":100029732,"name":"NewDefaults","signature":"func NewDefaults() (*args.GeneratorArgs, *CustomArgs)","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/args/args.go","code":"// NewDefaults returns default arguments for the generator.\nfunc NewDefaults() (*args.GeneratorArgs, *CustomArgs) {\n\tgenericArgs := args.Default().WithoutDefaultFlagParsing()\n\tcustomArgs := \u0026CustomArgs{\n\t\tExternalApplyConfigurations: map[types.Name]string{\n\t\t\t// Always include TypeMeta and ObjectMeta. They are sufficient for the vast majority of use cases.\n\t\t\t{Package: \"k8s.io/apimachinery/pkg/apis/meta/v1\", Name: \"TypeMeta\"}: \"k8s.io/client-go/applyconfigurations/meta/v1\",\n\t\t\t{Package: \"k8s.io/apimachinery/pkg/apis/meta/v1\", Name: \"ObjectMeta\"}: \"k8s.io/client-go/applyconfigurations/meta/v1\",\n\t\t\t{Package: \"k8s.io/apimachinery/pkg/apis/meta/v1\", Name: \"OwnerReference\"}: \"k8s.io/client-go/applyconfigurations/meta/v1\",\n\t\t},\n\t}\n\tgenericArgs.CustomArgs = customArgs\n\n\tif pkg := codegenutil.CurrentPackage(); len(pkg) != 0 {\n\t\tgenericArgs.OutputPackagePath = path.Join(pkg, \"pkg/client/applyconfigurations\")\n\t}\n\n\treturn genericArgs, customArgs\n}","line":{"from":47,"to":65}} {"id":100029733,"name":"AddFlags","signature":"func (ca *CustomArgs) AddFlags(fs *pflag.FlagSet, inputBase string)","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/args/args.go","code":"func (ca *CustomArgs) AddFlags(fs *pflag.FlagSet, inputBase string) {\n\tpflag.Var(NewExternalApplyConfigurationValue(\u0026ca.ExternalApplyConfigurations, nil), \"external-applyconfigurations\",\n\t\t\"list of comma separated external apply configurations locations in \u003ctype-package\u003e.\u003ctype-name\u003e:\u003capplyconfiguration-package\u003e form.\"+\n\t\t\t\"For example: k8s.io/api/apps/v1.Deployment:k8s.io/client-go/applyconfigurations/apps/v1\")\n\tpflag.StringVar(\u0026ca.OpenAPISchemaFilePath, \"openapi-schema\", \"\",\n\t\t\"path to the openapi schema containing all the types that apply configurations will be generated for\")\n}","line":{"from":67,"to":73}} {"id":100029734,"name":"Validate","signature":"func Validate(genericArgs *args.GeneratorArgs) error","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/args/args.go","code":"// Validate checks the given arguments.\nfunc Validate(genericArgs *args.GeneratorArgs) error {\n\tif len(genericArgs.OutputPackagePath) == 0 {\n\t\treturn fmt.Errorf(\"output package cannot be empty\")\n\t}\n\treturn nil\n}","line":{"from":75,"to":81}} {"id":100029735,"name":"NewExternalApplyConfigurationValue","signature":"func NewExternalApplyConfigurationValue(externals *map[types.Name]string, def []string) *externalApplyConfigurationValue","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/args/externaltypes.go","code":"func NewExternalApplyConfigurationValue(externals *map[types.Name]string, def []string) *externalApplyConfigurationValue {\n\tval := new(externalApplyConfigurationValue)\n\tval.externals = externals\n\tif def != nil {\n\t\tif err := val.set(def); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\treturn val\n}","line":{"from":33,"to":42}} {"id":100029736,"name":"set","signature":"func (s *externalApplyConfigurationValue) set(vs []string) error","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/args/externaltypes.go","code":"func (s *externalApplyConfigurationValue) set(vs []string) error {\n\tfor _, input := range vs {\n\t\ttyp, pkg, err := parseExternalMapping(input)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, ok := (*s.externals)[typ]; ok {\n\t\t\treturn fmt.Errorf(\"duplicate type found in --external-applyconfigurations: %v\", typ)\n\t\t}\n\t\t(*s.externals)[typ] = pkg\n\t}\n\n\treturn nil\n}","line":{"from":46,"to":59}} {"id":100029737,"name":"Set","signature":"func (s *externalApplyConfigurationValue) Set(val string) error","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/args/externaltypes.go","code":"func (s *externalApplyConfigurationValue) Set(val string) error {\n\tvs, err := readAsCSV(val)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := s.set(vs); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":61,"to":71}} {"id":100029738,"name":"Type","signature":"func (s *externalApplyConfigurationValue) Type() string","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/args/externaltypes.go","code":"func (s *externalApplyConfigurationValue) Type() string {\n\treturn \"string\"\n}","line":{"from":73,"to":75}} {"id":100029739,"name":"String","signature":"func (s *externalApplyConfigurationValue) String() string","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/args/externaltypes.go","code":"func (s *externalApplyConfigurationValue) String() string {\n\tvar strs []string\n\tfor k, v := range *s.externals {\n\t\tstrs = append(strs, fmt.Sprintf(\"%s.%s:%s\", k.Package, k.Name, v))\n\t}\n\tstr, _ := writeAsCSV(strs)\n\treturn \"[\" + str + \"]\"\n}","line":{"from":77,"to":84}} {"id":100029740,"name":"readAsCSV","signature":"func readAsCSV(val string) ([]string, error)","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/args/externaltypes.go","code":"func readAsCSV(val string) ([]string, error) {\n\tif val == \"\" {\n\t\treturn []string{}, nil\n\t}\n\tstringReader := strings.NewReader(val)\n\tcsvReader := csv.NewReader(stringReader)\n\treturn csvReader.Read()\n}","line":{"from":86,"to":93}} {"id":100029741,"name":"writeAsCSV","signature":"func writeAsCSV(vals []string) (string, error)","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/args/externaltypes.go","code":"func writeAsCSV(vals []string) (string, error) {\n\tb := \u0026bytes.Buffer{}\n\tw := csv.NewWriter(b)\n\terr := w.Write(vals)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tw.Flush()\n\treturn strings.TrimSuffix(b.String(), \"\\n\"), nil\n}","line":{"from":95,"to":104}} {"id":100029742,"name":"parseExternalMapping","signature":"func parseExternalMapping(mapping string) (typ types.Name, pkg string, err error)","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/args/externaltypes.go","code":"func parseExternalMapping(mapping string) (typ types.Name, pkg string, err error) {\n\tparts := strings.Split(mapping, \":\")\n\tif len(parts) != 2 {\n\t\treturn types.Name{}, \"\", fmt.Errorf(\"expected string of the form \u003cpackage\u003e.\u003ctypeName\u003e:\u003capplyconfiguration-package\u003e but got %s\", mapping)\n\t}\n\tpackageTypeStr := parts[0]\n\tpkg = parts[1]\n\t// need to split on the *last* dot, since k8s.io (and other valid packages) have a dot in it\n\tlastDot := strings.LastIndex(packageTypeStr, \".\")\n\tif lastDot == -1 || lastDot == len(packageTypeStr)-1 {\n\t\treturn types.Name{}, \"\", fmt.Errorf(\"expected package and type of the form \u003cpackage\u003e.\u003ctypeName\u003e but got %s\", packageTypeStr)\n\t}\n\tstructPkg := packageTypeStr[:lastDot]\n\tstructType := packageTypeStr[lastDot+1:]\n\n\treturn types.Name{Package: structPkg, Name: structType}, pkg, nil\n}","line":{"from":106,"to":122}} {"id":100029743,"name":"Filter","signature":"func (g *applyConfigurationGenerator) Filter(_ *generator.Context, t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/applyconfiguration.go","code":"func (g *applyConfigurationGenerator) Filter(_ *generator.Context, t *types.Type) bool {\n\treturn t == g.applyConfig.Type\n}","line":{"from":46,"to":48}} {"id":100029744,"name":"Namers","signature":"func (g *applyConfigurationGenerator) Namers(*generator.Context) namer.NameSystems","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/applyconfiguration.go","code":"func (g *applyConfigurationGenerator) Namers(*generator.Context) namer.NameSystems {\n\treturn namer.NameSystems{\n\t\t\"raw\": namer.NewRawNamer(g.localPackage.Package, g.imports),\n\t\t\"singularKind\": namer.NewPublicNamer(0),\n\t}\n}","line":{"from":50,"to":55}} {"id":100029745,"name":"Imports","signature":"func (g *applyConfigurationGenerator) Imports(*generator.Context) (imports []string)","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/applyconfiguration.go","code":"func (g *applyConfigurationGenerator) Imports(*generator.Context) (imports []string) {\n\treturn g.imports.ImportLines()\n}","line":{"from":57,"to":59}} {"id":100029746,"name":"GenerateType","signature":"func (g *applyConfigurationGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/applyconfiguration.go","code":"func (g *applyConfigurationGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {\n\tsw := generator.NewSnippetWriter(w, c, \"$\", \"$\")\n\n\tklog.V(5).Infof(\"processing type %v\", t)\n\ttypeParams := TypeParams{\n\t\tStruct: t,\n\t\tApplyConfig: g.applyConfig,\n\t\tTags: genclientTags(t),\n\t\tAPIVersion: g.groupVersion.ToAPIVersion(),\n\t\tExtractInto: extractInto,\n\t\tParserFunc: types.Ref(g.outputPackage+\"/internal\", \"Parser\"),\n\t\tOpenAPIType: g.openAPIType,\n\t}\n\n\tg.generateStruct(sw, typeParams)\n\n\tif typeParams.Tags.GenerateClient {\n\t\tif typeParams.Tags.NonNamespaced {\n\t\t\tsw.Do(clientgenTypeConstructorNonNamespaced, typeParams)\n\t\t} else {\n\t\t\tsw.Do(clientgenTypeConstructorNamespaced, typeParams)\n\t\t}\n\t\tif typeParams.OpenAPIType != nil {\n\t\t\tg.generateClientgenExtract(sw, typeParams, !typeParams.Tags.NoStatus)\n\t\t}\n\t} else {\n\t\tif hasTypeMetaField(t) {\n\t\t\tsw.Do(constructorWithTypeMeta, typeParams)\n\t\t} else {\n\t\t\tsw.Do(constructor, typeParams)\n\t\t}\n\t}\n\tg.generateWithFuncs(t, typeParams, sw, nil)\n\treturn sw.Error()\n}","line":{"from":83,"to":117}} {"id":100029747,"name":"hasTypeMetaField","signature":"func hasTypeMetaField(t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/applyconfiguration.go","code":"func hasTypeMetaField(t *types.Type) bool {\n\tfor _, member := range t.Members {\n\t\tif typeMeta.Name == member.Type.Name \u0026\u0026 member.Embedded {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":119,"to":126}} {"id":100029748,"name":"blocklisted","signature":"func blocklisted(t *types.Type, member types.Member) bool","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/applyconfiguration.go","code":"func blocklisted(t *types.Type, member types.Member) bool {\n\tif objectMeta.Name == t.Name \u0026\u0026 member.Name == \"ManagedFields\" {\n\t\treturn true\n\t}\n\tif objectMeta.Name == t.Name \u0026\u0026 member.Name == \"SelfLink\" {\n\t\treturn true\n\t}\n\t// Hide any fields which are en route to deletion.\n\tif strings.HasPrefix(member.Name, \"ZZZ_\") {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":128,"to":140}} {"id":100029749,"name":"generateWithFuncs","signature":"func (g *applyConfigurationGenerator) generateWithFuncs(t *types.Type, typeParams TypeParams, sw *generator.SnippetWriter, embed *memberParams)","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/applyconfiguration.go","code":"func (g *applyConfigurationGenerator) generateWithFuncs(t *types.Type, typeParams TypeParams, sw *generator.SnippetWriter, embed *memberParams) {\n\tfor _, member := range t.Members {\n\t\tif blocklisted(t, member) {\n\t\t\tcontinue\n\t\t}\n\t\tmemberType := g.refGraph.applyConfigForType(member.Type)\n\t\tif g.refGraph.isApplyConfig(member.Type) {\n\t\t\tmemberType = \u0026types.Type{Kind: types.Pointer, Elem: memberType}\n\t\t}\n\t\tif jsonTags, ok := lookupJSONTags(member); ok {\n\t\t\tmemberParams := memberParams{\n\t\t\t\tTypeParams: typeParams,\n\t\t\t\tMember: member,\n\t\t\t\tMemberType: memberType,\n\t\t\t\tJSONTags: jsonTags,\n\t\t\t\tEmbeddedIn: embed,\n\t\t\t}\n\t\t\tif memberParams.Member.Embedded {\n\t\t\t\tg.generateWithFuncs(member.Type, typeParams, sw, \u0026memberParams)\n\t\t\t\tif !jsonTags.inline {\n\t\t\t\t\t// non-inlined embeds are nillable and need a \"ensure exists\" utility function\n\t\t\t\t\tsw.Do(ensureEmbedExists, memberParams)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// For slices where the items are generated apply configuration types, accept varargs of\n\t\t\t// pointers of the type as \"with\" function arguments so the \"with\" function can be used like so:\n\t\t\t// WithFoos(Foo().WithName(\"x\"), Foo().WithName(\"y\"))\n\t\t\tif t := deref(member.Type); t.Kind == types.Slice \u0026\u0026 g.refGraph.isApplyConfig(t.Elem) {\n\t\t\t\tmemberParams.ArgType = \u0026types.Type{Kind: types.Pointer, Elem: memberType.Elem}\n\t\t\t\tg.generateMemberWithForSlice(sw, member, memberParams)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Note: There are no maps where the values are generated apply configurations (because\n\t\t\t// associative lists are used instead). So if a type like this is ever introduced, the\n\t\t\t// default \"with\" function generator will produce a working (but not entirely convenient \"with\" function)\n\t\t\t// that would be used like so:\n\t\t\t// WithMap(map[string]FooApplyConfiguration{*Foo().WithName(\"x\")})\n\n\t\t\tswitch memberParams.Member.Type.Kind {\n\t\t\tcase types.Slice:\n\t\t\t\tmemberParams.ArgType = memberType.Elem\n\t\t\t\tg.generateMemberWithForSlice(sw, member, memberParams)\n\t\t\tcase types.Map:\n\t\t\t\tg.generateMemberWithForMap(sw, memberParams)\n\t\t\tdefault:\n\t\t\t\tg.generateMemberWith(sw, memberParams)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":142,"to":193}} {"id":100029750,"name":"generateStruct","signature":"func (g *applyConfigurationGenerator) generateStruct(sw *generator.SnippetWriter, typeParams TypeParams)","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/applyconfiguration.go","code":"func (g *applyConfigurationGenerator) generateStruct(sw *generator.SnippetWriter, typeParams TypeParams) {\n\tsw.Do(\"// $.ApplyConfig.ApplyConfiguration|public$ represents an declarative configuration of the $.ApplyConfig.Type|public$ type for use\\n\", typeParams)\n\tsw.Do(\"// with apply.\\n\", typeParams)\n\tsw.Do(\"type $.ApplyConfig.ApplyConfiguration|public$ struct {\\n\", typeParams)\n\tfor _, structMember := range typeParams.Struct.Members {\n\t\tif blocklisted(typeParams.Struct, structMember) {\n\t\t\tcontinue\n\t\t}\n\t\tif structMemberTags, ok := lookupJSONTags(structMember); ok {\n\t\t\tif !structMemberTags.inline {\n\t\t\t\tstructMemberTags.omitempty = true\n\t\t\t}\n\t\t\tparams := memberParams{\n\t\t\t\tTypeParams: typeParams,\n\t\t\t\tMember: structMember,\n\t\t\t\tMemberType: g.refGraph.applyConfigForType(structMember.Type),\n\t\t\t\tJSONTags: structMemberTags,\n\t\t\t}\n\t\t\tif structMember.Embedded {\n\t\t\t\tif structMemberTags.inline {\n\t\t\t\t\tsw.Do(\"$.MemberType|raw$ `json:\\\"$.JSONTags$\\\"`\\n\", params)\n\t\t\t\t} else {\n\t\t\t\t\tsw.Do(\"*$.MemberType|raw$ `json:\\\"$.JSONTags$\\\"`\\n\", params)\n\t\t\t\t}\n\t\t\t} else if isNillable(structMember.Type) {\n\t\t\t\tsw.Do(\"$.Member.Name$ $.MemberType|raw$ `json:\\\"$.JSONTags$\\\"`\\n\", params)\n\t\t\t} else {\n\t\t\t\tsw.Do(\"$.Member.Name$ *$.MemberType|raw$ `json:\\\"$.JSONTags$\\\"`\\n\", params)\n\t\t\t}\n\t\t}\n\t}\n\tsw.Do(\"}\\n\", typeParams)\n}","line":{"from":195,"to":227}} {"id":100029751,"name":"deref","signature":"func deref(t *types.Type) *types.Type","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/applyconfiguration.go","code":"func deref(t *types.Type) *types.Type {\n\tfor t.Kind == types.Pointer {\n\t\tt = t.Elem\n\t}\n\treturn t\n}","line":{"from":229,"to":234}} {"id":100029752,"name":"isNillable","signature":"func isNillable(t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/applyconfiguration.go","code":"func isNillable(t *types.Type) bool {\n\treturn t.Kind == types.Slice || t.Kind == types.Map\n}","line":{"from":236,"to":238}} {"id":100029753,"name":"generateMemberWith","signature":"func (g *applyConfigurationGenerator) generateMemberWith(sw *generator.SnippetWriter, memberParams memberParams)","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/applyconfiguration.go","code":"func (g *applyConfigurationGenerator) generateMemberWith(sw *generator.SnippetWriter, memberParams memberParams) {\n\tsw.Do(\"// With$.Member.Name$ sets the $.Member.Name$ field in the declarative configuration to the given value\\n\", memberParams)\n\tsw.Do(\"// and returns the receiver, so that objects can be built by chaining \\\"With\\\" function invocations.\\n\", memberParams)\n\tsw.Do(\"// If called multiple times, the $.Member.Name$ field is set to the value of the last call.\\n\", memberParams)\n\tsw.Do(\"func (b *$.ApplyConfig.ApplyConfiguration|public$) With$.Member.Name$(value $.MemberType|raw$) *$.ApplyConfig.ApplyConfiguration|public$ {\\n\", memberParams)\n\tg.ensureEnbedExistsIfApplicable(sw, memberParams)\n\tif g.refGraph.isApplyConfig(memberParams.Member.Type) || isNillable(memberParams.Member.Type) {\n\t\tsw.Do(\"b.$.Member.Name$ = value\\n\", memberParams)\n\t} else {\n\t\tsw.Do(\"b.$.Member.Name$ = \u0026value\\n\", memberParams)\n\t}\n\tsw.Do(\" return b\\n\", memberParams)\n\tsw.Do(\"}\\n\", memberParams)\n}","line":{"from":240,"to":253}} {"id":100029754,"name":"generateMemberWithForSlice","signature":"func (g *applyConfigurationGenerator) generateMemberWithForSlice(sw *generator.SnippetWriter, member types.Member, memberParams memberParams)","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/applyconfiguration.go","code":"func (g *applyConfigurationGenerator) generateMemberWithForSlice(sw *generator.SnippetWriter, member types.Member, memberParams memberParams) {\n\tmemberIsPointerToSlice := member.Type.Kind == types.Pointer\n\tif memberIsPointerToSlice {\n\t\tsw.Do(ensureNonEmbedSliceExists, memberParams)\n\t}\n\n\tsw.Do(\"// With$.Member.Name$ adds the given value to the $.Member.Name$ field in the declarative configuration\\n\", memberParams)\n\tsw.Do(\"// and returns the receiver, so that objects can be build by chaining \\\"With\\\" function invocations.\\n\", memberParams)\n\tsw.Do(\"// If called multiple times, values provided by each call will be appended to the $.Member.Name$ field.\\n\", memberParams)\n\tsw.Do(\"func (b *$.ApplyConfig.ApplyConfiguration|public$) With$.Member.Name$(values ...$.ArgType|raw$) *$.ApplyConfig.ApplyConfiguration|public$ {\\n\", memberParams)\n\tg.ensureEnbedExistsIfApplicable(sw, memberParams)\n\n\tif memberIsPointerToSlice {\n\t\tsw.Do(\"b.ensure$.MemberType.Elem|public$Exists()\\n\", memberParams)\n\t}\n\n\tsw.Do(\" for i := range values {\\n\", memberParams)\n\tif memberParams.ArgType.Kind == types.Pointer {\n\t\tsw.Do(\"if values[i] == nil {\\n\", memberParams)\n\t\tsw.Do(\" panic(\\\"nil value passed to With$.Member.Name$\\\")\\n\", memberParams)\n\t\tsw.Do(\"}\\n\", memberParams)\n\n\t\tif memberIsPointerToSlice {\n\t\t\tsw.Do(\"*b.$.Member.Name$ = append(*b.$.Member.Name$, *values[i])\\n\", memberParams)\n\t\t} else {\n\t\t\tsw.Do(\"b.$.Member.Name$ = append(b.$.Member.Name$, *values[i])\\n\", memberParams)\n\t\t}\n\t} else {\n\t\tif memberIsPointerToSlice {\n\t\t\tsw.Do(\"*b.$.Member.Name$ = append(*b.$.Member.Name$, values[i])\\n\", memberParams)\n\t\t} else {\n\t\t\tsw.Do(\"b.$.Member.Name$ = append(b.$.Member.Name$, values[i])\\n\", memberParams)\n\t\t}\n\t}\n\tsw.Do(\" }\\n\", memberParams)\n\tsw.Do(\" return b\\n\", memberParams)\n\tsw.Do(\"}\\n\", memberParams)\n}","line":{"from":255,"to":292}} {"id":100029755,"name":"generateMemberWithForMap","signature":"func (g *applyConfigurationGenerator) generateMemberWithForMap(sw *generator.SnippetWriter, memberParams memberParams)","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/applyconfiguration.go","code":"func (g *applyConfigurationGenerator) generateMemberWithForMap(sw *generator.SnippetWriter, memberParams memberParams) {\n\tsw.Do(\"// With$.Member.Name$ puts the entries into the $.Member.Name$ field in the declarative configuration\\n\", memberParams)\n\tsw.Do(\"// and returns the receiver, so that objects can be build by chaining \\\"With\\\" function invocations.\\n\", memberParams)\n\tsw.Do(\"// If called multiple times, the entries provided by each call will be put on the $.Member.Name$ field,\\n\", memberParams)\n\tsw.Do(\"// overwriting an existing map entries in $.Member.Name$ field with the same key.\\n\", memberParams)\n\tsw.Do(\"func (b *$.ApplyConfig.ApplyConfiguration|public$) With$.Member.Name$(entries $.MemberType|raw$) *$.ApplyConfig.ApplyConfiguration|public$ {\\n\", memberParams)\n\tg.ensureEnbedExistsIfApplicable(sw, memberParams)\n\tsw.Do(\" if b.$.Member.Name$ == nil \u0026\u0026 len(entries) \u003e 0 {\\n\", memberParams)\n\tsw.Do(\" b.$.Member.Name$ = make($.MemberType|raw$, len(entries))\\n\", memberParams)\n\tsw.Do(\" }\\n\", memberParams)\n\tsw.Do(\" for k, v := range entries {\\n\", memberParams)\n\tsw.Do(\" b.$.Member.Name$[k] = v\\n\", memberParams)\n\tsw.Do(\" }\\n\", memberParams)\n\tsw.Do(\" return b\\n\", memberParams)\n\tsw.Do(\"}\\n\", memberParams)\n}","line":{"from":294,"to":309}} {"id":100029756,"name":"ensureEnbedExistsIfApplicable","signature":"func (g *applyConfigurationGenerator) ensureEnbedExistsIfApplicable(sw *generator.SnippetWriter, memberParams memberParams)","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/applyconfiguration.go","code":"func (g *applyConfigurationGenerator) ensureEnbedExistsIfApplicable(sw *generator.SnippetWriter, memberParams memberParams) {\n\t// Embedded types that are not inlined must be nillable so they are not included in the apply configuration\n\t// when all their fields are omitted.\n\tif memberParams.EmbeddedIn != nil \u0026\u0026 !memberParams.EmbeddedIn.JSONTags.inline {\n\t\tsw.Do(\"b.ensure$.MemberType.Elem|public$Exists()\\n\", memberParams.EmbeddedIn)\n\t}\n}","line":{"from":311,"to":317}} {"id":100029757,"name":"generateClientgenExtract","signature":"func (g *applyConfigurationGenerator) generateClientgenExtract(sw *generator.SnippetWriter, typeParams TypeParams, includeStatus bool)","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/applyconfiguration.go","code":"func (g *applyConfigurationGenerator) generateClientgenExtract(sw *generator.SnippetWriter, typeParams TypeParams, includeStatus bool) {\n\tsw.Do(`\n// Extract$.ApplyConfig.Type|public$ extracts the applied configuration owned by fieldManager from\n// $.Struct|private$. If no managedFields are found in $.Struct|private$ for fieldManager, a\n// $.ApplyConfig.ApplyConfiguration|public$ is returned with only the Name, Namespace (if applicable),\n// APIVersion and Kind populated. It is possible that no managed fields were found for because other\n// field managers have taken ownership of all the fields previously owned by fieldManager, or because\n// the fieldManager never owned fields any fields.\n// $.Struct|private$ must be a unmodified $.Struct|public$ API object that was retrieved from the Kubernetes API.\n// Extract$.ApplyConfig.Type|public$ provides a way to perform a extract/modify-in-place/apply workflow.\n// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously\n// applied if another fieldManager has updated or force applied any of the previously applied fields.\n// Experimental!\nfunc Extract$.ApplyConfig.Type|public$($.Struct|private$ *$.Struct|raw$, fieldManager string) (*$.ApplyConfig.ApplyConfiguration|public$, error) {\n\treturn extract$.ApplyConfig.Type|public$($.Struct|private$, fieldManager, \"\")\n}`, typeParams)\n\tif includeStatus {\n\t\tsw.Do(`\n// Extract$.ApplyConfig.Type|public$Status is the same as Extract$.ApplyConfig.Type|public$ except\n// that it extracts the status subresource applied configuration.\n// Experimental!\nfunc Extract$.ApplyConfig.Type|public$Status($.Struct|private$ *$.Struct|raw$, fieldManager string) (*$.ApplyConfig.ApplyConfiguration|public$, error) {\n\treturn extract$.ApplyConfig.Type|public$($.Struct|private$, fieldManager, \"status\")\n}\n`, typeParams)\n\t}\n\tsw.Do(`\nfunc extract$.ApplyConfig.Type|public$($.Struct|private$ *$.Struct|raw$, fieldManager string, subresource string) (*$.ApplyConfig.ApplyConfiguration|public$, error) {\n\tb := \u0026$.ApplyConfig.ApplyConfiguration|public${}\n\terr := $.ExtractInto|raw$($.Struct|private$, $.ParserFunc|raw$().Type(\"$.OpenAPIType$\"), fieldManager, b, subresource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.WithName($.Struct|private$.Name)\n`, typeParams)\n\tif !typeParams.Tags.NonNamespaced {\n\t\tsw.Do(\"b.WithNamespace($.Struct|private$.Namespace)\\n\", typeParams)\n\t}\n\tsw.Do(`\n\tb.WithKind(\"$.ApplyConfig.Type|singularKind$\")\n\tb.WithAPIVersion(\"$.APIVersion$\")\n\treturn b, nil\n}\n`, typeParams)\n}","line":{"from":379,"to":423}} {"id":100029758,"name":"Filter","signature":"func (g *internalGenerator) Filter(*generator.Context, *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/internal.go","code":"func (g *internalGenerator) Filter(*generator.Context, *types.Type) bool {\n\t// generate file exactly once\n\tif !g.filtered {\n\t\tg.filtered = true\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":42,"to":49}} {"id":100029759,"name":"Namers","signature":"func (g *internalGenerator) Namers(*generator.Context) namer.NameSystems","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/internal.go","code":"func (g *internalGenerator) Namers(*generator.Context) namer.NameSystems {\n\treturn namer.NameSystems{\n\t\t\"raw\": namer.NewRawNamer(g.outputPackage, g.imports),\n\t\t\"singularKind\": namer.NewPublicNamer(0),\n\t}\n}","line":{"from":51,"to":56}} {"id":100029760,"name":"Imports","signature":"func (g *internalGenerator) Imports(*generator.Context) (imports []string)","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/internal.go","code":"func (g *internalGenerator) Imports(*generator.Context) (imports []string) {\n\treturn g.imports.ImportLines()\n}","line":{"from":58,"to":60}} {"id":100029761,"name":"GenerateType","signature":"func (g *internalGenerator) GenerateType(c *generator.Context, _ *types.Type, w io.Writer) error","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/internal.go","code":"func (g *internalGenerator) GenerateType(c *generator.Context, _ *types.Type, w io.Writer) error {\n\tsw := generator.NewSnippetWriter(w, c, \"{{\", \"}}\")\n\n\tschema, err := schemaconv.ToSchema(g.typeModels.models)\n\tif err != nil {\n\t\treturn err\n\t}\n\tschemaYAML, err := yaml.Marshal(schema)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsw.Do(schemaBlock, map[string]interface{}{\n\t\t\"schemaYAML\": string(schemaYAML),\n\t\t\"smdParser\": smdParser,\n\t\t\"smdNewParser\": smdNewParser,\n\t\t\"yamlObject\": yamlObject,\n\t\t\"yamlUnmarshal\": yamlUnmarshal,\n\t})\n\n\treturn sw.Error()\n}","line":{"from":62,"to":82}} {"id":100029762,"name":"String","signature":"func (t JSONTags) String() string","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/jsontagutil.go","code":"func (t JSONTags) String() string {\n\tvar tag string\n\tif !t.inline {\n\t\ttag += t.name\n\t}\n\tif t.omitempty {\n\t\ttag += \",omitempty\"\n\t}\n\tif t.inline {\n\t\ttag += \",inline\"\n\t}\n\treturn tag\n}","line":{"from":37,"to":49}} {"id":100029763,"name":"lookupJSONTags","signature":"func lookupJSONTags(m types.Member) (JSONTags, bool)","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/jsontagutil.go","code":"func lookupJSONTags(m types.Member) (JSONTags, bool) {\n\ttag := reflect.StructTag(m.Tags).Get(\"json\")\n\tif tag == \"\" || tag == \"-\" {\n\t\treturn JSONTags{}, false\n\t}\n\tname, opts := parseTag(tag)\n\tif name == \"\" {\n\t\tname = m.Name\n\t}\n\treturn JSONTags{\n\t\tname: name,\n\t\tomit: false,\n\t\tinline: opts.Contains(\"inline\"),\n\t\tomitempty: opts.Contains(\"omitempty\"),\n\t}, true\n}","line":{"from":51,"to":66}} {"id":100029764,"name":"parseTag","signature":"func parseTag(tag string) (string, tagOptions)","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/jsontagutil.go","code":"// parseTag splits a struct field's json tag into its name and\n// comma-separated options.\nfunc parseTag(tag string) (string, tagOptions) {\n\tif idx := strings.Index(tag, \",\"); idx != -1 {\n\t\treturn tag[:idx], tagOptions(tag[idx+1:])\n\t}\n\treturn tag, \"\"\n}","line":{"from":70,"to":77}} {"id":100029765,"name":"Contains","signature":"func (o tagOptions) Contains(optionName string) bool","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/jsontagutil.go","code":"// Contains reports whether a comma-separated listAlias of options\n// contains a particular substr flag. substr must be surrounded by a\n// string boundary or commas.\nfunc (o tagOptions) Contains(optionName string) bool {\n\tif len(o) == 0 {\n\t\treturn false\n\t}\n\ts := string(o)\n\tfor s != \"\" {\n\t\tvar next string\n\t\ti := strings.Index(s, \",\")\n\t\tif i \u003e= 0 {\n\t\t\ts, next = s[:i], s[i+1:]\n\t\t}\n\t\tif s == optionName {\n\t\t\treturn true\n\t\t}\n\t\ts = next\n\t}\n\treturn false\n}","line":{"from":79,"to":99}} {"id":100029766,"name":"newTypeModels","signature":"func newTypeModels(openAPISchemaFilePath string, pkgTypes map[string]*types.Package) (*typeModels, error)","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/openapi.go","code":"func newTypeModels(openAPISchemaFilePath string, pkgTypes map[string]*types.Package) (*typeModels, error) {\n\tif len(openAPISchemaFilePath) == 0 {\n\t\treturn emptyModels, nil // No Extract\u003ctype\u003e() functions will be generated.\n\t}\n\n\trawOpenAPISchema, err := os.ReadFile(openAPISchemaFilePath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read openapi-schema file: %w\", err)\n\t}\n\n\t// Read in the provided openAPI schema.\n\topenAPISchema := \u0026spec.Swagger{}\n\terr = json.Unmarshal(rawOpenAPISchema, openAPISchema)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal typeModels JSON: %w\", err)\n\t}\n\n\t// Build a mapping from openAPI type name to GVK.\n\t// Find the root types needed by by client-go for apply.\n\tgvkToOpenAPIType := map[gvk]string{}\n\trootDefs := map[string]spec.Schema{}\n\tfor _, p := range pkgTypes {\n\t\tgv := groupVersion(p)\n\t\tfor _, t := range p.Types {\n\t\t\ttags := genclientTags(t)\n\t\t\thasApply := tags.HasVerb(\"apply\") || tags.HasVerb(\"applyStatus\")\n\t\t\tif tags.GenerateClient \u0026\u0026 hasApply {\n\t\t\t\topenAPIType := friendlyName(typeName(t))\n\t\t\t\tgvk := gvk{\n\t\t\t\t\tgroup: gv.Group.String(),\n\t\t\t\t\tversion: gv.Version.String(),\n\t\t\t\t\tkind: t.Name.Name,\n\t\t\t\t}\n\t\t\t\trootDefs[openAPIType] = openAPISchema.Definitions[openAPIType]\n\t\t\t\tgvkToOpenAPIType[gvk] = openAPIType\n\t\t\t}\n\t\t}\n\t}\n\n\t// Trim the schema down to just the types needed by client-go for apply.\n\trequiredDefs := make(map[string]spec.Schema)\n\tfor name, def := range rootDefs {\n\t\trequiredDefs[name] = def\n\t\tfindReferenced(\u0026def, openAPISchema.Definitions, requiredDefs)\n\t}\n\topenAPISchema.Definitions = requiredDefs\n\n\t// Convert the openAPI schema to the models format and validate it.\n\tmodels, err := toValidatedModels(openAPISchema)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026typeModels{models: models, gvkToOpenAPIType: gvkToOpenAPIType}, nil\n}","line":{"from":40,"to":93}} {"id":100029767,"name":"toValidatedModels","signature":"func toValidatedModels(openAPISchema *spec.Swagger) (utilproto.Models, error)","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/openapi.go","code":"func toValidatedModels(openAPISchema *spec.Swagger) (utilproto.Models, error) {\n\t// openapi_v2.ParseDocument only accepts a []byte of the JSON or YAML file to be parsed.\n\t// so we do an inefficient marshal back to json and then read it back in as yaml\n\t// but get the benefit of running the models through utilproto.NewOpenAPIData to\n\t// validate all the references between types\n\trawMinimalOpenAPISchema, err := json.Marshal(openAPISchema)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal openAPI as JSON: %w\", err)\n\t}\n\n\tdocument, err := openapiv2.ParseDocument(rawMinimalOpenAPISchema)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse OpenAPI document for file: %w\", err)\n\t}\n\t// Construct the models and validate all references are valid.\n\tmodels, err := utilproto.NewOpenAPIData(document)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create OpenAPI models for file: %w\", err)\n\t}\n\treturn models, nil\n}","line":{"from":100,"to":120}} {"id":100029768,"name":"findReferenced","signature":"func findReferenced(def *spec.Schema, allSchemas, referencedOut map[string]spec.Schema)","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/openapi.go","code":"// findReferenced recursively finds all schemas referenced from the given def.\n// toValidatedModels makes sure no references get missed.\nfunc findReferenced(def *spec.Schema, allSchemas, referencedOut map[string]spec.Schema) {\n\t// follow $ref, if any\n\trefPtr := def.Ref.GetPointer()\n\tif refPtr != nil \u0026\u0026 !refPtr.IsEmpty() {\n\t\tname := refPtr.String()\n\t\tif !strings.HasPrefix(name, \"/definitions/\") {\n\t\t\treturn\n\t\t}\n\t\tname = strings.TrimPrefix(name, \"/definitions/\")\n\t\tschema, ok := allSchemas[name]\n\t\tif !ok {\n\t\t\tpanic(fmt.Sprintf(\"allSchemas schema is missing referenced type: %s\", name))\n\t\t}\n\t\tif _, ok := referencedOut[name]; !ok {\n\t\t\treferencedOut[name] = schema\n\t\t\tfindReferenced(\u0026schema, allSchemas, referencedOut)\n\t\t}\n\t}\n\n\t// follow any nested schemas\n\tif def.Items != nil {\n\t\tif def.Items.Schema != nil {\n\t\t\tfindReferenced(def.Items.Schema, allSchemas, referencedOut)\n\t\t}\n\t\tfor _, item := range def.Items.Schemas {\n\t\t\tfindReferenced(\u0026item, allSchemas, referencedOut)\n\t\t}\n\t}\n\tif def.AllOf != nil {\n\t\tfor _, s := range def.AllOf {\n\t\t\tfindReferenced(\u0026s, allSchemas, referencedOut)\n\t\t}\n\t}\n\tif def.AnyOf != nil {\n\t\tfor _, s := range def.AnyOf {\n\t\t\tfindReferenced(\u0026s, allSchemas, referencedOut)\n\t\t}\n\t}\n\tif def.OneOf != nil {\n\t\tfor _, s := range def.OneOf {\n\t\t\tfindReferenced(\u0026s, allSchemas, referencedOut)\n\t\t}\n\t}\n\tif def.Not != nil {\n\t\tfindReferenced(def.Not, allSchemas, referencedOut)\n\t}\n\tif def.Properties != nil {\n\t\tfor _, prop := range def.Properties {\n\t\t\tfindReferenced(\u0026prop, allSchemas, referencedOut)\n\t\t}\n\t}\n\tif def.AdditionalProperties != nil \u0026\u0026 def.AdditionalProperties.Schema != nil {\n\t\tfindReferenced(def.AdditionalProperties.Schema, allSchemas, referencedOut)\n\t}\n\tif def.PatternProperties != nil {\n\t\tfor _, s := range def.PatternProperties {\n\t\t\tfindReferenced(\u0026s, allSchemas, referencedOut)\n\t\t}\n\t}\n\tif def.Dependencies != nil {\n\t\tfor _, d := range def.Dependencies {\n\t\t\tif d.Schema != nil {\n\t\t\t\tfindReferenced(d.Schema, allSchemas, referencedOut)\n\t\t\t}\n\t\t}\n\t}\n\tif def.AdditionalItems != nil \u0026\u0026 def.AdditionalItems.Schema != nil {\n\t\tfindReferenced(def.AdditionalItems.Schema, allSchemas, referencedOut)\n\t}\n\tif def.Definitions != nil {\n\t\tfor _, s := range def.Definitions {\n\t\t\tfindReferenced(\u0026s, allSchemas, referencedOut)\n\t\t}\n\t}\n}","line":{"from":122,"to":198}} {"id":100029769,"name":"NameSystems","signature":"func NameSystems() namer.NameSystems","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/packages.go","code":"// NameSystems returns the name system used by the generators in this package.\nfunc NameSystems() namer.NameSystems {\n\treturn namer.NameSystems{\n\t\t\"public\": namer.NewPublicNamer(0),\n\t\t\"private\": namer.NewPrivateNamer(0),\n\t\t\"raw\": namer.NewRawNamer(\"\", nil),\n\t}\n}","line":{"from":42,"to":49}} {"id":100029770,"name":"DefaultNameSystem","signature":"func DefaultNameSystem() string","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/packages.go","code":"// DefaultNameSystem returns the default name system for ordering the types to be\n// processed by the generators in this package.\nfunc DefaultNameSystem() string {\n\treturn \"public\"\n}","line":{"from":51,"to":55}} {"id":100029771,"name":"Packages","signature":"func Packages(context *generator.Context, arguments *args.GeneratorArgs) generator.Packages","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/packages.go","code":"// Packages makes the client package definition.\nfunc Packages(context *generator.Context, arguments *args.GeneratorArgs) generator.Packages {\n\tboilerplate, err := arguments.LoadGoBoilerplate()\n\tif err != nil {\n\t\tklog.Fatalf(\"Failed loading boilerplate: %v\", err)\n\t}\n\n\tpkgTypes := packageTypesForInputDirs(context, arguments.InputDirs, arguments.OutputPackagePath)\n\tcustomArgs := arguments.CustomArgs.(*applygenargs.CustomArgs)\n\tinitialTypes := customArgs.ExternalApplyConfigurations\n\trefs := refGraphForReachableTypes(context.Universe, pkgTypes, initialTypes)\n\ttypeModels, err := newTypeModels(customArgs.OpenAPISchemaFilePath, pkgTypes)\n\tif err != nil {\n\t\tklog.Fatalf(\"Failed build type models from typeModels %s: %v\", customArgs.OpenAPISchemaFilePath, err)\n\t}\n\n\tgroupVersions := make(map[string]clientgentypes.GroupVersions)\n\tgroupGoNames := make(map[string]string)\n\tapplyConfigsForGroupVersion := make(map[clientgentypes.GroupVersion][]applyConfig)\n\n\tvar packageList generator.Packages\n\tfor pkg, p := range pkgTypes {\n\t\tgv := groupVersion(p)\n\n\t\tpkgType := types.Name{Name: gv.Group.PackageName(), Package: pkg}\n\n\t\tvar toGenerate []applyConfig\n\t\tfor _, t := range p.Types {\n\t\t\t// If we don't have an ObjectMeta field, we lack the information required to make the Apply or ApplyStatus call\n\t\t\t// to the kube-apiserver, so we don't need to generate the type at all\n\t\t\tclientTags := genclientTags(t)\n\t\t\tif clientTags.GenerateClient \u0026\u0026 !hasObjectMetaField(t) {\n\t\t\t\tklog.V(5).Infof(\"skipping type %v because does not have ObjectMeta\", t)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif typePkg, ok := refs[t.Name]; ok {\n\t\t\t\ttoGenerate = append(toGenerate, applyConfig{\n\t\t\t\t\tType: t,\n\t\t\t\t\tApplyConfiguration: types.Ref(typePkg, t.Name.Name+ApplyConfigurationTypeSuffix),\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\tif len(toGenerate) == 0 {\n\t\t\tcontinue // Don't generate empty packages\n\t\t}\n\t\tsort.Sort(applyConfigSort(toGenerate))\n\n\t\t// generate the apply configurations\n\t\tpackageList = append(packageList, generatorForApplyConfigurationsPackage(arguments.OutputPackagePath, boilerplate, pkgType, gv, toGenerate, refs, typeModels))\n\n\t\t// group all the generated apply configurations by gv so ForKind() can be generated\n\t\tgroupPackageName := gv.Group.NonEmpty()\n\t\tgroupVersionsEntry, ok := groupVersions[groupPackageName]\n\t\tif !ok {\n\t\t\tgroupVersionsEntry = clientgentypes.GroupVersions{\n\t\t\t\tPackageName: groupPackageName,\n\t\t\t\tGroup: gv.Group,\n\t\t\t}\n\t\t}\n\t\tgroupVersionsEntry.Versions = append(groupVersionsEntry.Versions, clientgentypes.PackageVersion{\n\t\t\tVersion: gv.Version,\n\t\t\tPackage: path.Clean(p.Path),\n\t\t})\n\n\t\tgroupGoNames[groupPackageName] = goName(gv, p)\n\t\tapplyConfigsForGroupVersion[gv] = toGenerate\n\t\tgroupVersions[groupPackageName] = groupVersionsEntry\n\t}\n\n\t// generate ForKind() utility function\n\tpackageList = append(packageList, generatorForUtils(arguments.OutputPackagePath, boilerplate, groupVersions, applyConfigsForGroupVersion, groupGoNames))\n\t// generate internal embedded schema, required for generated Extract functions\n\tpackageList = append(packageList, generatorForInternal(filepath.Join(arguments.OutputPackagePath, \"internal\"), boilerplate, typeModels))\n\n\treturn packageList\n}","line":{"from":57,"to":132}} {"id":100029772,"name":"friendlyName","signature":"func friendlyName(name string) string","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/packages.go","code":"func friendlyName(name string) string {\n\tnameParts := strings.Split(name, \"/\")\n\t// Reverse first part. e.g., io.k8s... instead of k8s.io...\n\tif len(nameParts) \u003e 0 \u0026\u0026 strings.Contains(nameParts[0], \".\") {\n\t\tparts := strings.Split(nameParts[0], \".\")\n\t\tfor i, j := 0, len(parts)-1; i \u003c j; i, j = i+1, j-1 {\n\t\t\tparts[i], parts[j] = parts[j], parts[i]\n\t\t}\n\t\tnameParts[0] = strings.Join(parts, \".\")\n\t}\n\treturn strings.Join(nameParts, \".\")\n}","line":{"from":134,"to":145}} {"id":100029773,"name":"typeName","signature":"func typeName(t *types.Type) string","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/packages.go","code":"func typeName(t *types.Type) string {\n\ttypePackage := t.Name.Package\n\tif strings.Contains(typePackage, \"/vendor/\") {\n\t\ttypePackage = typePackage[strings.Index(typePackage, \"/vendor/\")+len(\"/vendor/\"):]\n\t}\n\treturn fmt.Sprintf(\"%s.%s\", typePackage, t.Name.Name)\n}","line":{"from":147,"to":153}} {"id":100029774,"name":"generatorForApplyConfigurationsPackage","signature":"func generatorForApplyConfigurationsPackage(outputPackagePath string, boilerplate []byte, packageName types.Name, gv clientgentypes.GroupVersion, typesToGenerate []applyConfig, refs refGraph, models *typeModels) *generator.DefaultPackage","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/packages.go","code":"func generatorForApplyConfigurationsPackage(outputPackagePath string, boilerplate []byte, packageName types.Name, gv clientgentypes.GroupVersion, typesToGenerate []applyConfig, refs refGraph, models *typeModels) *generator.DefaultPackage {\n\treturn \u0026generator.DefaultPackage{\n\t\tPackageName: gv.Version.PackageName(),\n\t\tPackagePath: packageName.Package,\n\t\tHeaderText: boilerplate,\n\t\tGeneratorFunc: func(c *generator.Context) (generators []generator.Generator) {\n\t\t\tfor _, toGenerate := range typesToGenerate {\n\t\t\t\tvar openAPIType *string\n\t\t\t\tgvk := gvk{\n\t\t\t\t\tgroup: gv.Group.String(),\n\t\t\t\t\tversion: gv.Version.String(),\n\t\t\t\t\tkind: toGenerate.Type.Name.Name,\n\t\t\t\t}\n\t\t\t\tif v, ok := models.gvkToOpenAPIType[gvk]; ok {\n\t\t\t\t\topenAPIType = \u0026v\n\t\t\t\t}\n\n\t\t\t\tgenerators = append(generators, \u0026applyConfigurationGenerator{\n\t\t\t\t\tDefaultGen: generator.DefaultGen{\n\t\t\t\t\t\tOptionalName: strings.ToLower(toGenerate.Type.Name.Name),\n\t\t\t\t\t},\n\t\t\t\t\toutputPackage: outputPackagePath,\n\t\t\t\t\tlocalPackage: packageName,\n\t\t\t\t\tgroupVersion: gv,\n\t\t\t\t\tapplyConfig: toGenerate,\n\t\t\t\t\timports: generator.NewImportTracker(),\n\t\t\t\t\trefGraph: refs,\n\t\t\t\t\topenAPIType: openAPIType,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn generators\n\t\t},\n\t}\n}","line":{"from":155,"to":188}} {"id":100029775,"name":"generatorForUtils","signature":"func generatorForUtils(outPackagePath string, boilerplate []byte, groupVersions map[string]clientgentypes.GroupVersions, applyConfigsForGroupVersion map[clientgentypes.GroupVersion][]applyConfig, groupGoNames map[string]string) *generator.DefaultPackage","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/packages.go","code":"func generatorForUtils(outPackagePath string, boilerplate []byte, groupVersions map[string]clientgentypes.GroupVersions, applyConfigsForGroupVersion map[clientgentypes.GroupVersion][]applyConfig, groupGoNames map[string]string) *generator.DefaultPackage {\n\treturn \u0026generator.DefaultPackage{\n\t\tPackageName: filepath.Base(outPackagePath),\n\t\tPackagePath: outPackagePath,\n\t\tHeaderText: boilerplate,\n\t\tGeneratorFunc: func(c *generator.Context) (generators []generator.Generator) {\n\t\t\tgenerators = append(generators, \u0026utilGenerator{\n\t\t\t\tDefaultGen: generator.DefaultGen{\n\t\t\t\t\tOptionalName: \"utils\",\n\t\t\t\t},\n\t\t\t\toutputPackage: outPackagePath,\n\t\t\t\timports: generator.NewImportTracker(),\n\t\t\t\tgroupVersions: groupVersions,\n\t\t\t\ttypesForGroupVersion: applyConfigsForGroupVersion,\n\t\t\t\tgroupGoNames: groupGoNames,\n\t\t\t})\n\t\t\treturn generators\n\t\t},\n\t}\n}","line":{"from":190,"to":209}} {"id":100029776,"name":"generatorForInternal","signature":"func generatorForInternal(outPackagePath string, boilerplate []byte, models *typeModels) *generator.DefaultPackage","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/packages.go","code":"func generatorForInternal(outPackagePath string, boilerplate []byte, models *typeModels) *generator.DefaultPackage {\n\treturn \u0026generator.DefaultPackage{\n\t\tPackageName: filepath.Base(outPackagePath),\n\t\tPackagePath: outPackagePath,\n\t\tHeaderText: boilerplate,\n\t\tGeneratorFunc: func(c *generator.Context) (generators []generator.Generator) {\n\t\t\tgenerators = append(generators, \u0026internalGenerator{\n\t\t\t\tDefaultGen: generator.DefaultGen{\n\t\t\t\t\tOptionalName: \"internal\",\n\t\t\t\t},\n\t\t\t\toutputPackage: outPackagePath,\n\t\t\t\timports: generator.NewImportTracker(),\n\t\t\t\ttypeModels: models,\n\t\t\t})\n\t\t\treturn generators\n\t\t},\n\t}\n}","line":{"from":211,"to":228}} {"id":100029777,"name":"goName","signature":"func goName(gv clientgentypes.GroupVersion, p *types.Package) string","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/packages.go","code":"func goName(gv clientgentypes.GroupVersion, p *types.Package) string {\n\tgoName := namer.IC(strings.Split(gv.Group.NonEmpty(), \".\")[0])\n\tif override := types.ExtractCommentTags(\"+\", p.Comments)[\"groupGoName\"]; override != nil {\n\t\tgoName = namer.IC(override[0])\n\t}\n\treturn goName\n}","line":{"from":230,"to":236}} {"id":100029778,"name":"packageTypesForInputDirs","signature":"func packageTypesForInputDirs(context *generator.Context, inputDirs []string, outputPath string) map[string]*types.Package","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/packages.go","code":"func packageTypesForInputDirs(context *generator.Context, inputDirs []string, outputPath string) map[string]*types.Package {\n\tpkgTypes := map[string]*types.Package{}\n\tfor _, inputDir := range inputDirs {\n\t\tp := context.Universe.Package(inputDir)\n\t\tinternal := isInternalPackage(p)\n\t\tif internal {\n\t\t\tklog.Warningf(\"Skipping internal package: %s\", p.Path)\n\t\t\tcontinue\n\t\t}\n\t\t// This is how the client generator finds the package we are creating. It uses the API package name, not the group name.\n\t\t// This matches the approach of the client-gen, so the two generator can work together.\n\t\t// For example, if openshift/api/cloudnetwork/v1 contains an apigroup cloud.network.openshift.io, the client-gen\n\t\t// builds a package called cloudnetwork/v1 to contain it. This change makes the applyconfiguration-gen use the same.\n\t\t_, gvPackageString := util.ParsePathGroupVersion(p.Path)\n\t\tpkg := filepath.Join(outputPath, strings.ToLower(gvPackageString))\n\t\tpkgTypes[pkg] = p\n\t}\n\treturn pkgTypes\n}","line":{"from":238,"to":256}} {"id":100029779,"name":"groupVersion","signature":"func groupVersion(p *types.Package) (gv clientgentypes.GroupVersion)","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/packages.go","code":"func groupVersion(p *types.Package) (gv clientgentypes.GroupVersion) {\n\tparts := strings.Split(p.Path, \"/\")\n\tgv.Group = clientgentypes.Group(parts[len(parts)-2])\n\tgv.Version = clientgentypes.Version(parts[len(parts)-1])\n\n\t// If there's a comment of the form \"// +groupName=somegroup\" or\n\t// \"// +groupName=somegroup.foo.bar.io\", use the first field (somegroup) as the name of the\n\t// group when generating.\n\tif override := types.ExtractCommentTags(\"+\", p.Comments)[\"groupName\"]; override != nil {\n\t\tgv.Group = clientgentypes.Group(override[0])\n\t}\n\treturn gv\n}","line":{"from":258,"to":270}} {"id":100029780,"name":"isInternalPackage","signature":"func isInternalPackage(p *types.Package) bool","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/packages.go","code":"// isInternalPackage returns true if the package is an internal package\nfunc isInternalPackage(p *types.Package) bool {\n\tfor _, t := range p.Types {\n\t\tfor _, member := range t.Members {\n\t\t\tif member.Name == \"ObjectMeta\" {\n\t\t\t\treturn isInternal(member)\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":272,"to":282}} {"id":100029781,"name":"isInternal","signature":"func isInternal(m types.Member) bool","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/packages.go","code":"// isInternal returns true if the tags for a member do not contain a json tag\nfunc isInternal(m types.Member) bool {\n\t_, ok := lookupJSONTags(m)\n\treturn !ok\n}","line":{"from":284,"to":288}} {"id":100029782,"name":"hasObjectMetaField","signature":"func hasObjectMetaField(t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/packages.go","code":"func hasObjectMetaField(t *types.Type) bool {\n\tfor _, member := range t.Members {\n\t\tif objectMeta.Name == member.Type.Name \u0026\u0026 member.Embedded {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":290,"to":297}} {"id":100029783,"name":"refGraphForReachableTypes","signature":"func refGraphForReachableTypes(universe types.Universe, pkgTypes map[string]*types.Package, initialTypes map[types.Name]string) refGraph","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/refgraph.go","code":"// refGraphForReachableTypes returns a refGraph that contains all reachable types from\n// the root clientgen types of the provided packages.\nfunc refGraphForReachableTypes(universe types.Universe, pkgTypes map[string]*types.Package, initialTypes map[types.Name]string) refGraph {\n\tvar refs refGraph = initialTypes\n\n\t// Include only types that are reachable from the root clientgen types.\n\t// We don't want to generate apply configurations for types that are not reachable from a root\n\t// clientgen type.\n\treachableTypes := map[types.Name]*types.Type{}\n\tfor _, p := range pkgTypes {\n\t\tfor _, t := range p.Types {\n\t\t\ttags := genclientTags(t)\n\t\t\thasApply := tags.HasVerb(\"apply\") || tags.HasVerb(\"applyStatus\")\n\t\t\tif tags.GenerateClient \u0026\u0026 hasApply {\n\t\t\t\tfindReachableTypes(t, reachableTypes)\n\t\t\t}\n\t\t\t// If any apply extensions have custom inputs, add them.\n\t\t\tfor _, extension := range tags.Extensions {\n\t\t\t\tif extension.HasVerb(\"apply\") {\n\t\t\t\t\tif len(extension.InputTypeOverride) \u003e 0 {\n\t\t\t\t\t\tinputType := *t\n\t\t\t\t\t\tif name, pkg := extension.Input(); len(pkg) \u003e 0 {\n\t\t\t\t\t\t\tinputType = *(universe.Type(types.Name{Package: pkg, Name: name}))\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tinputType.Name.Name = extension.InputTypeOverride\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfindReachableTypes(\u0026inputType, reachableTypes)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfor pkg, p := range pkgTypes {\n\t\tfor _, t := range p.Types {\n\t\t\tif _, ok := reachableTypes[t.Name]; !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif requiresApplyConfiguration(t) {\n\t\t\t\trefs[t.Name] = pkg\n\t\t\t}\n\t\t}\n\t}\n\n\treturn refs\n}","line":{"from":29,"to":73}} {"id":100029784,"name":"applyConfigForType","signature":"func (t refGraph) applyConfigForType(field *types.Type) *types.Type","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/refgraph.go","code":"// applyConfigForType find the type used in the generate apply configurations for a field.\n// This may either be an existing type or one of the other generated applyConfig types.\nfunc (t refGraph) applyConfigForType(field *types.Type) *types.Type {\n\tswitch field.Kind {\n\tcase types.Struct:\n\t\tif pkg, ok := t[field.Name]; ok { // TODO(jpbetz): Refs to types defined in a separate system (e.g. TypeMeta if generating a 3rd party controller) end up referencing the go struct, not the apply configuration type\n\t\t\treturn types.Ref(pkg, field.Name.Name+ApplyConfigurationTypeSuffix)\n\t\t}\n\t\treturn field\n\tcase types.Map:\n\t\tif _, ok := t[field.Elem.Name]; ok {\n\t\t\treturn \u0026types.Type{\n\t\t\t\tKind: types.Map,\n\t\t\t\tElem: t.applyConfigForType(field.Elem),\n\t\t\t\tKey: t.applyConfigForType(field.Key),\n\t\t\t}\n\t\t}\n\t\treturn field\n\tcase types.Slice:\n\t\tif _, ok := t[field.Elem.Name]; ok {\n\t\t\treturn \u0026types.Type{\n\t\t\t\tKind: types.Slice,\n\t\t\t\tElem: t.applyConfigForType(field.Elem),\n\t\t\t}\n\t\t}\n\t\treturn field\n\tcase types.Pointer:\n\t\treturn t.applyConfigForType(field.Elem)\n\tdefault:\n\t\treturn field\n\t}\n}","line":{"from":75,"to":106}} {"id":100029785,"name":"isApplyConfig","signature":"func (t refGraph) isApplyConfig(field *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/refgraph.go","code":"func (t refGraph) isApplyConfig(field *types.Type) bool {\n\tswitch field.Kind {\n\tcase types.Struct:\n\t\t_, ok := t[field.Name]\n\t\treturn ok\n\tcase types.Pointer:\n\t\treturn t.isApplyConfig(field.Elem)\n\t}\n\treturn false\n}","line":{"from":108,"to":117}} {"id":100029786,"name":"genclientTags","signature":"func genclientTags(t *types.Type) util.Tags","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/refgraph.go","code":"// genclientTags returns the genclient Tags for the given type.\nfunc genclientTags(t *types.Type) util.Tags {\n\treturn util.MustParseClientGenTags(append(t.SecondClosestCommentLines, t.CommentLines...))\n}","line":{"from":119,"to":122}} {"id":100029787,"name":"findReachableTypes","signature":"func findReachableTypes(t *types.Type, referencedTypes map[types.Name]*types.Type)","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/refgraph.go","code":"// findReachableTypes finds all types transitively reachable from a given root type, including\n// the root type itself.\nfunc findReachableTypes(t *types.Type, referencedTypes map[types.Name]*types.Type) {\n\tif _, ok := referencedTypes[t.Name]; ok {\n\t\treturn\n\t}\n\treferencedTypes[t.Name] = t\n\n\tif t.Elem != nil {\n\t\tfindReachableTypes(t.Elem, referencedTypes)\n\t}\n\tif t.Underlying != nil {\n\t\tfindReachableTypes(t.Underlying, referencedTypes)\n\t}\n\tif t.Key != nil {\n\t\tfindReachableTypes(t.Key, referencedTypes)\n\t}\n\tfor _, m := range t.Members {\n\t\tfindReachableTypes(m.Type, referencedTypes)\n\t}\n}","line":{"from":124,"to":144}} {"id":100029788,"name":"requiresApplyConfiguration","signature":"func requiresApplyConfiguration(t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/refgraph.go","code":"// requiresApplyConfiguration returns true if a type applyConfig should be generated for the given type.\n// types applyConfig are only generated for struct types that contain fields with json tags.\nfunc requiresApplyConfiguration(t *types.Type) bool {\n\tfor t.Kind == types.Alias {\n\t\tt = t.Underlying\n\t}\n\tif t.Kind != types.Struct {\n\t\treturn false\n\t}\n\tif _, ok := excludeTypes[t.Name]; ok {\n\t\treturn false\n\t}\n\tvar hasJSONTaggedMembers bool\n\tfor _, member := range t.Members {\n\t\tif _, ok := lookupJSONTags(member); ok {\n\t\t\thasJSONTaggedMembers = true\n\t\t}\n\t}\n\tif !hasJSONTaggedMembers {\n\t\treturn false\n\t}\n\n\treturn true\n}","line":{"from":156,"to":179}} {"id":100029789,"name":"Filter","signature":"func (g *utilGenerator) Filter(*generator.Context, *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/util.go","code":"func (g *utilGenerator) Filter(*generator.Context, *types.Type) bool {\n\t// generate file exactly once\n\tif !g.filtered {\n\t\tg.filtered = true\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":44,"to":51}} {"id":100029790,"name":"Namers","signature":"func (g *utilGenerator) Namers(*generator.Context) namer.NameSystems","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/util.go","code":"func (g *utilGenerator) Namers(*generator.Context) namer.NameSystems {\n\treturn namer.NameSystems{\n\t\t\"raw\": namer.NewRawNamer(g.outputPackage, g.imports),\n\t\t\"singularKind\": namer.NewPublicNamer(0),\n\t}\n}","line":{"from":53,"to":58}} {"id":100029791,"name":"Imports","signature":"func (g *utilGenerator) Imports(*generator.Context) (imports []string)","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/util.go","code":"func (g *utilGenerator) Imports(*generator.Context) (imports []string) {\n\treturn g.imports.ImportLines()\n}","line":{"from":60,"to":62}} {"id":100029792,"name":"Len","signature":"func (g groupSort) Len() int { return len(g) }","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/util.go","code":"func (g groupSort) Len() int { return len(g) }","line":{"from":72,"to":72}} {"id":100029793,"name":"Less","signature":"func (g groupSort) Less(i, j int) bool","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/util.go","code":"func (g groupSort) Less(i, j int) bool {\n\treturn strings.ToLower(g[i].Name) \u003c strings.ToLower(g[j].Name)\n}","line":{"from":73,"to":75}} {"id":100029794,"name":"Swap","signature":"func (g groupSort) Swap(i, j int) { g[i], g[j] = g[j], g[i] }","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/util.go","code":"func (g groupSort) Swap(i, j int) { g[i], g[j] = g[j], g[i] }","line":{"from":76,"to":76}} {"id":100029795,"name":"Len","signature":"func (v versionSort) Len() int { return len(v) }","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/util.go","code":"func (v versionSort) Len() int { return len(v) }","line":{"from":86,"to":86}} {"id":100029796,"name":"Less","signature":"func (v versionSort) Less(i, j int) bool","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/util.go","code":"func (v versionSort) Less(i, j int) bool {\n\treturn strings.ToLower(v[i].Name) \u003c strings.ToLower(v[j].Name)\n}","line":{"from":87,"to":89}} {"id":100029797,"name":"Swap","signature":"func (v versionSort) Swap(i, j int) { v[i], v[j] = v[j], v[i] }","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/util.go","code":"func (v versionSort) Swap(i, j int) { v[i], v[j] = v[j], v[i] }","line":{"from":90,"to":90}} {"id":100029798,"name":"Len","signature":"func (v applyConfigSort) Len() int { return len(v) }","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/util.go","code":"func (v applyConfigSort) Len() int { return len(v) }","line":{"from":99,"to":99}} {"id":100029799,"name":"Less","signature":"func (v applyConfigSort) Less(i, j int) bool","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/util.go","code":"func (v applyConfigSort) Less(i, j int) bool {\n\treturn strings.ToLower(v[i].Type.Name.Name) \u003c strings.ToLower(v[j].Type.Name.Name)\n}","line":{"from":100,"to":102}} {"id":100029800,"name":"Swap","signature":"func (v applyConfigSort) Swap(i, j int) { v[i], v[j] = v[j], v[i] }","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/util.go","code":"func (v applyConfigSort) Swap(i, j int) { v[i], v[j] = v[j], v[i] }","line":{"from":103,"to":103}} {"id":100029801,"name":"GenerateType","signature":"func (g *utilGenerator) GenerateType(c *generator.Context, _ *types.Type, w io.Writer) error","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/generators/util.go","code":"func (g *utilGenerator) GenerateType(c *generator.Context, _ *types.Type, w io.Writer) error {\n\tsw := generator.NewSnippetWriter(w, c, \"{{\", \"}}\")\n\n\tvar groups []group\n\tschemeGVs := make(map[*version]*types.Type)\n\n\tfor groupPackageName, groupVersions := range g.groupVersions {\n\t\tgroup := group{\n\t\t\tGroupGoName: g.groupGoNames[groupPackageName],\n\t\t\tName: groupVersions.Group.NonEmpty(),\n\t\t\tVersions: []*version{},\n\t\t}\n\t\tfor _, v := range groupVersions.Versions {\n\t\t\tgv := clientgentypes.GroupVersion{Group: groupVersions.Group, Version: v.Version}\n\t\t\tversion := \u0026version{\n\t\t\t\tName: v.Version.NonEmpty(),\n\t\t\t\tGoName: namer.IC(v.Version.NonEmpty()),\n\t\t\t\tResources: g.typesForGroupVersion[gv],\n\t\t\t}\n\t\t\tschemeGVs[version] = c.Universe.Variable(types.Name{\n\t\t\t\tPackage: g.typesForGroupVersion[gv][0].Type.Name.Package,\n\t\t\t\tName: \"SchemeGroupVersion\",\n\t\t\t})\n\t\t\tgroup.Versions = append(group.Versions, version)\n\t\t}\n\t\tsort.Sort(versionSort(group.Versions))\n\t\tgroups = append(groups, group)\n\t}\n\tsort.Sort(groupSort(groups))\n\n\tm := map[string]interface{}{\n\t\t\"groups\": groups,\n\t\t\"schemeGVs\": schemeGVs,\n\t\t\"schemaGroupVersionKind\": groupVersionKind,\n\t\t\"applyConfiguration\": applyConfiguration,\n\t}\n\tsw.Do(forKindFunc, m)\n\n\treturn sw.Error()\n}","line":{"from":105,"to":144}} {"id":100029802,"name":"main","signature":"func main()","file":"staging/src/k8s.io/code-generator/cmd/applyconfiguration-gen/main.go","code":"func main() {\n\tklog.InitFlags(nil)\n\tgenericArgs, customArgs := generatorargs.NewDefaults()\n\tgenericArgs.AddFlags(pflag.CommandLine)\n\tcustomArgs.AddFlags(pflag.CommandLine, \"k8s.io/kubernetes/pkg/apis\") // TODO: move this input path out of applyconfiguration-gen\n\tif err := flag.Set(\"logtostderr\", \"true\"); err != nil {\n\t\tklog.Fatalf(\"Error: %v\", err)\n\t}\n\tpflag.CommandLine.AddGoFlagSet(flag.CommandLine)\n\tpflag.Parse()\n\n\tif err := generatorargs.Validate(genericArgs); err != nil {\n\t\tklog.Fatalf(\"Error: %v\", err)\n\t}\n\n\t// Run it.\n\tif err := genericArgs.Execute(\n\t\tgenerators.NameSystems(),\n\t\tgenerators.DefaultNameSystem(),\n\t\tgenerators.Packages,\n\t); err != nil {\n\t\tklog.Fatalf(\"Error: %v\", err)\n\t}\n\tklog.V(2).Info(\"Completed successfully.\")\n}","line":{"from":30,"to":54}} {"id":100029803,"name":"NewDefaults","signature":"func NewDefaults() (*args.GeneratorArgs, *CustomArgs)","file":"staging/src/k8s.io/code-generator/cmd/client-gen/args/args.go","code":"func NewDefaults() (*args.GeneratorArgs, *CustomArgs) {\n\tgenericArgs := args.Default().WithoutDefaultFlagParsing()\n\tcustomArgs := \u0026CustomArgs{\n\t\tClientsetName: \"internalclientset\",\n\t\tClientsetAPIPath: \"/apis\",\n\t\tClientsetOnly: false,\n\t\tFakeClient: true,\n\t\tPluralExceptions: []string{\"Endpoints:Endpoints\"},\n\t\tApplyConfigurationPackage: \"\",\n\t}\n\tgenericArgs.CustomArgs = customArgs\n\tgenericArgs.InputDirs = DefaultInputDirs\n\n\tif pkg := codegenutil.CurrentPackage(); len(pkg) != 0 {\n\t\tgenericArgs.OutputPackagePath = path.Join(pkg, \"pkg/client/clientset\")\n\t}\n\n\treturn genericArgs, customArgs\n}","line":{"from":62,"to":80}} {"id":100029804,"name":"AddFlags","signature":"func (ca *CustomArgs) AddFlags(fs *pflag.FlagSet, inputBase string)","file":"staging/src/k8s.io/code-generator/cmd/client-gen/args/args.go","code":"func (ca *CustomArgs) AddFlags(fs *pflag.FlagSet, inputBase string) {\n\tgvsBuilder := NewGroupVersionsBuilder(\u0026ca.Groups)\n\tpflag.Var(NewGVPackagesValue(gvsBuilder, nil), \"input\", \"group/versions that client-gen will generate clients for. At most one version per group is allowed. Specified in the format \\\"group1/version1,group2/version2...\\\".\")\n\tpflag.Var(NewGVTypesValue(\u0026ca.IncludedTypesOverrides, []string{}), \"included-types-overrides\", \"list of group/version/type for which client should be generated. By default, client is generated for all types which have genclient in types.go. This overrides that. For each groupVersion in this list, only the types mentioned here will be included. The default check of genclient will be used for other group versions.\")\n\tpflag.Var(NewInputBasePathValue(gvsBuilder, inputBase), \"input-base\", \"base path to look for the api group.\")\n\tpflag.StringVarP(\u0026ca.ClientsetName, \"clientset-name\", \"n\", ca.ClientsetName, \"the name of the generated clientset package.\")\n\tpflag.StringVarP(\u0026ca.ClientsetAPIPath, \"clientset-api-path\", \"\", ca.ClientsetAPIPath, \"the value of default API HTTP path, starting with / and without trailing /.\")\n\tpflag.BoolVar(\u0026ca.ClientsetOnly, \"clientset-only\", ca.ClientsetOnly, \"when set, client-gen only generates the clientset shell, without generating the individual typed clients\")\n\tpflag.BoolVar(\u0026ca.FakeClient, \"fake-clientset\", ca.FakeClient, \"when set, client-gen will generate the fake clientset that can be used in tests\")\n\n\tfs.StringSliceVar(\u0026ca.PluralExceptions, \"plural-exceptions\", ca.PluralExceptions, \"list of comma separated plural exception definitions in Type:PluralizedType form\")\n\tfs.StringVar(\u0026ca.ApplyConfigurationPackage, \"apply-configuration-package\", ca.ApplyConfigurationPackage, \"optional package of apply configurations, generated by applyconfiguration-gen, that are required to generate Apply functions for each type in the clientset. By default Apply functions are not generated.\")\n\n\t// support old flags\n\tfs.SetNormalizeFunc(mapFlagName(\"clientset-path\", \"output-package\", fs.GetNormalizeFunc()))\n}","line":{"from":82,"to":97}} {"id":100029805,"name":"Validate","signature":"func Validate(genericArgs *args.GeneratorArgs) error","file":"staging/src/k8s.io/code-generator/cmd/client-gen/args/args.go","code":"func Validate(genericArgs *args.GeneratorArgs) error {\n\tcustomArgs := genericArgs.CustomArgs.(*CustomArgs)\n\n\tif len(genericArgs.OutputPackagePath) == 0 {\n\t\treturn fmt.Errorf(\"output package cannot be empty\")\n\t}\n\tif len(customArgs.ClientsetName) == 0 {\n\t\treturn fmt.Errorf(\"clientset name cannot be empty\")\n\t}\n\tif len(customArgs.ClientsetAPIPath) == 0 {\n\t\treturn fmt.Errorf(\"clientset API path cannot be empty\")\n\t}\n\n\treturn nil\n}","line":{"from":99,"to":113}} {"id":100029806,"name":"GroupVersionPackages","signature":"func (ca *CustomArgs) GroupVersionPackages() map[types.GroupVersion]string","file":"staging/src/k8s.io/code-generator/cmd/client-gen/args/args.go","code":"// GroupVersionPackages returns a map from GroupVersion to the package with the types.go.\nfunc (ca *CustomArgs) GroupVersionPackages() map[types.GroupVersion]string {\n\tres := map[types.GroupVersion]string{}\n\tfor _, pkg := range ca.Groups {\n\t\tfor _, v := range pkg.Versions {\n\t\t\tres[types.GroupVersion{Group: pkg.Group, Version: v.Version}] = v.Package\n\t\t}\n\t}\n\treturn res\n}","line":{"from":115,"to":124}} {"id":100029807,"name":"mapFlagName","signature":"func mapFlagName(from, to string, old func(fs *pflag.FlagSet, name string) pflag.NormalizedName) func(fs *pflag.FlagSet, name string) pflag.NormalizedName","file":"staging/src/k8s.io/code-generator/cmd/client-gen/args/args.go","code":"func mapFlagName(from, to string, old func(fs *pflag.FlagSet, name string) pflag.NormalizedName) func(fs *pflag.FlagSet, name string) pflag.NormalizedName {\n\treturn func(fs *pflag.FlagSet, name string) pflag.NormalizedName {\n\t\tif name == from {\n\t\t\tname = to\n\t\t}\n\t\treturn old(fs, name)\n\t}\n}","line":{"from":126,"to":133}} {"id":100029808,"name":"NewInputBasePathValue","signature":"func NewInputBasePathValue(builder *groupVersionsBuilder, def string) *inputBasePathValue","file":"staging/src/k8s.io/code-generator/cmd/client-gen/args/gvpackages.go","code":"func NewInputBasePathValue(builder *groupVersionsBuilder, def string) *inputBasePathValue {\n\tv := \u0026inputBasePathValue{\n\t\tbuilder: builder,\n\t}\n\tv.Set(def)\n\treturn v\n}","line":{"from":37,"to":43}} {"id":100029809,"name":"Set","signature":"func (s *inputBasePathValue) Set(val string) error","file":"staging/src/k8s.io/code-generator/cmd/client-gen/args/gvpackages.go","code":"func (s *inputBasePathValue) Set(val string) error {\n\ts.builder.importBasePath = val\n\treturn s.builder.update()\n}","line":{"from":45,"to":48}} {"id":100029810,"name":"Type","signature":"func (s *inputBasePathValue) Type() string","file":"staging/src/k8s.io/code-generator/cmd/client-gen/args/gvpackages.go","code":"func (s *inputBasePathValue) Type() string {\n\treturn \"string\"\n}","line":{"from":50,"to":52}} {"id":100029811,"name":"String","signature":"func (s *inputBasePathValue) String() string","file":"staging/src/k8s.io/code-generator/cmd/client-gen/args/gvpackages.go","code":"func (s *inputBasePathValue) String() string {\n\treturn s.builder.importBasePath\n}","line":{"from":54,"to":56}} {"id":100029812,"name":"NewGVPackagesValue","signature":"func NewGVPackagesValue(builder *groupVersionsBuilder, def []string) *gvPackagesValue","file":"staging/src/k8s.io/code-generator/cmd/client-gen/args/gvpackages.go","code":"func NewGVPackagesValue(builder *groupVersionsBuilder, def []string) *gvPackagesValue {\n\tgvp := new(gvPackagesValue)\n\tgvp.builder = builder\n\tif def != nil {\n\t\tif err := gvp.set(def); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\treturn gvp\n}","line":{"from":64,"to":73}} {"id":100029813,"name":"set","signature":"func (s *gvPackagesValue) set(vs []string) error","file":"staging/src/k8s.io/code-generator/cmd/client-gen/args/gvpackages.go","code":"func (s *gvPackagesValue) set(vs []string) error {\n\tif s.changed {\n\t\ts.groups = append(s.groups, vs...)\n\t} else {\n\t\ts.groups = append([]string(nil), vs...)\n\t}\n\n\ts.builder.groups = s.groups\n\treturn s.builder.update()\n}","line":{"from":77,"to":86}} {"id":100029814,"name":"Set","signature":"func (s *gvPackagesValue) Set(val string) error","file":"staging/src/k8s.io/code-generator/cmd/client-gen/args/gvpackages.go","code":"func (s *gvPackagesValue) Set(val string) error {\n\tvs, err := readAsCSV(val)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := s.set(vs); err != nil {\n\t\treturn err\n\t}\n\ts.changed = true\n\treturn nil\n}","line":{"from":88,"to":98}} {"id":100029815,"name":"Type","signature":"func (s *gvPackagesValue) Type() string","file":"staging/src/k8s.io/code-generator/cmd/client-gen/args/gvpackages.go","code":"func (s *gvPackagesValue) Type() string {\n\treturn \"stringSlice\"\n}","line":{"from":100,"to":102}} {"id":100029816,"name":"String","signature":"func (s *gvPackagesValue) String() string","file":"staging/src/k8s.io/code-generator/cmd/client-gen/args/gvpackages.go","code":"func (s *gvPackagesValue) String() string {\n\tstr, _ := writeAsCSV(s.groups)\n\treturn \"[\" + str + \"]\"\n}","line":{"from":104,"to":107}} {"id":100029817,"name":"NewGroupVersionsBuilder","signature":"func NewGroupVersionsBuilder(groups *[]types.GroupVersions) *groupVersionsBuilder","file":"staging/src/k8s.io/code-generator/cmd/client-gen/args/gvpackages.go","code":"func NewGroupVersionsBuilder(groups *[]types.GroupVersions) *groupVersionsBuilder {\n\treturn \u0026groupVersionsBuilder{\n\t\tvalue: groups,\n\t}\n}","line":{"from":115,"to":119}} {"id":100029818,"name":"update","signature":"func (p *groupVersionsBuilder) update() error","file":"staging/src/k8s.io/code-generator/cmd/client-gen/args/gvpackages.go","code":"func (p *groupVersionsBuilder) update() error {\n\tvar seenGroups = make(map[types.Group]*types.GroupVersions)\n\tfor _, v := range p.groups {\n\t\tpth, gvString := util.ParsePathGroupVersion(v)\n\t\tgv, err := types.ToGroupVersion(gvString)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tversionPkg := types.PackageVersion{Package: path.Join(p.importBasePath, pth, gv.Group.NonEmpty(), gv.Version.String()), Version: gv.Version}\n\t\tif group, ok := seenGroups[gv.Group]; ok {\n\t\t\tseenGroups[gv.Group].Versions = append(group.Versions, versionPkg)\n\t\t} else {\n\t\t\tseenGroups[gv.Group] = \u0026types.GroupVersions{\n\t\t\t\tPackageName: gv.Group.NonEmpty(),\n\t\t\t\tGroup: gv.Group,\n\t\t\t\tVersions: []types.PackageVersion{versionPkg},\n\t\t\t}\n\t\t}\n\t}\n\n\tvar groupNames []string\n\tfor groupName := range seenGroups {\n\t\tgroupNames = append(groupNames, groupName.String())\n\t}\n\tsort.Strings(groupNames)\n\t*p.value = []types.GroupVersions{}\n\tfor _, groupName := range groupNames {\n\t\t*p.value = append(*p.value, *seenGroups[types.Group(groupName)])\n\t}\n\n\treturn nil\n}","line":{"from":121,"to":153}} {"id":100029819,"name":"readAsCSV","signature":"func readAsCSV(val string) ([]string, error)","file":"staging/src/k8s.io/code-generator/cmd/client-gen/args/gvpackages.go","code":"func readAsCSV(val string) ([]string, error) {\n\tif val == \"\" {\n\t\treturn []string{}, nil\n\t}\n\tstringReader := strings.NewReader(val)\n\tcsvReader := csv.NewReader(stringReader)\n\treturn csvReader.Read()\n}","line":{"from":155,"to":162}} {"id":100029820,"name":"writeAsCSV","signature":"func writeAsCSV(vals []string) (string, error)","file":"staging/src/k8s.io/code-generator/cmd/client-gen/args/gvpackages.go","code":"func writeAsCSV(vals []string) (string, error) {\n\tb := \u0026bytes.Buffer{}\n\tw := csv.NewWriter(b)\n\terr := w.Write(vals)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tw.Flush()\n\treturn strings.TrimSuffix(b.String(), \"\\n\"), nil\n}","line":{"from":164,"to":173}} {"id":100029821,"name":"NewGVTypesValue","signature":"func NewGVTypesValue(gvToTypes *map[types.GroupVersion][]string, def []string) *gvTypeValue","file":"staging/src/k8s.io/code-generator/cmd/client-gen/args/gvtype.go","code":"func NewGVTypesValue(gvToTypes *map[types.GroupVersion][]string, def []string) *gvTypeValue {\n\tgvt := new(gvTypeValue)\n\tgvt.gvToTypes = gvToTypes\n\tif def != nil {\n\t\tif err := gvt.set(def); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\treturn gvt\n}","line":{"from":32,"to":41}} {"id":100029822,"name":"set","signature":"func (s *gvTypeValue) set(vs []string) error","file":"staging/src/k8s.io/code-generator/cmd/client-gen/args/gvtype.go","code":"func (s *gvTypeValue) set(vs []string) error {\n\tif !s.changed {\n\t\t*s.gvToTypes = map[types.GroupVersion][]string{}\n\t}\n\n\tfor _, input := range vs {\n\t\tgvString, typeStr, err := parseGroupVersionType(input)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgv, err := types.ToGroupVersion(gvString)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttypes, ok := (*s.gvToTypes)[gv]\n\t\tif !ok {\n\t\t\ttypes = []string{}\n\t\t}\n\t\ttypes = append(types, typeStr)\n\t\t(*s.gvToTypes)[gv] = types\n\t}\n\n\treturn nil\n}","line":{"from":45,"to":68}} {"id":100029823,"name":"Set","signature":"func (s *gvTypeValue) Set(val string) error","file":"staging/src/k8s.io/code-generator/cmd/client-gen/args/gvtype.go","code":"func (s *gvTypeValue) Set(val string) error {\n\tvs, err := readAsCSV(val)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := s.set(vs); err != nil {\n\t\treturn err\n\t}\n\ts.changed = true\n\treturn nil\n}","line":{"from":70,"to":80}} {"id":100029824,"name":"Type","signature":"func (s *gvTypeValue) Type() string","file":"staging/src/k8s.io/code-generator/cmd/client-gen/args/gvtype.go","code":"func (s *gvTypeValue) Type() string {\n\treturn \"stringSlice\"\n}","line":{"from":82,"to":84}} {"id":100029825,"name":"String","signature":"func (s *gvTypeValue) String() string","file":"staging/src/k8s.io/code-generator/cmd/client-gen/args/gvtype.go","code":"func (s *gvTypeValue) String() string {\n\tstrs := make([]string, 0, len(*s.gvToTypes))\n\tfor gv, ts := range *s.gvToTypes {\n\t\tfor _, t := range ts {\n\t\t\tstrs = append(strs, gv.Group.String()+\"/\"+gv.Version.String()+\"/\"+t)\n\t\t}\n\t}\n\tstr, _ := writeAsCSV(strs)\n\treturn \"[\" + str + \"]\"\n}","line":{"from":86,"to":95}} {"id":100029826,"name":"parseGroupVersionType","signature":"func parseGroupVersionType(gvtString string) (gvString string, typeStr string, err error)","file":"staging/src/k8s.io/code-generator/cmd/client-gen/args/gvtype.go","code":"func parseGroupVersionType(gvtString string) (gvString string, typeStr string, err error) {\n\tinvalidFormatErr := fmt.Errorf(\"invalid value: %s, should be of the form group/version/type\", gvtString)\n\tsubs := strings.Split(gvtString, \"/\")\n\tlength := len(subs)\n\tswitch length {\n\tcase 2:\n\t\t// gvtString of the form group/type, e.g. api/Service,extensions/ReplicaSet\n\t\treturn subs[0] + \"/\", subs[1], nil\n\tcase 3:\n\t\treturn strings.Join(subs[:length-1], \"/\"), subs[length-1], nil\n\tdefault:\n\t\treturn \"\", \"\", invalidFormatErr\n\t}\n}","line":{"from":97,"to":110}} {"id":100029827,"name":"NameSystems","signature":"func NameSystems(pluralExceptions map[string]string) namer.NameSystems","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/client_generator.go","code":"// NameSystems returns the name system used by the generators in this package.\nfunc NameSystems(pluralExceptions map[string]string) namer.NameSystems {\n\tlowercaseNamer := namer.NewAllLowercasePluralNamer(pluralExceptions)\n\n\tpublicNamer := \u0026ExceptionNamer{\n\t\tExceptions: map[string]string{\n\t\t\t// these exceptions are used to deconflict the generated code\n\t\t\t// you can put your fully qualified package like\n\t\t\t// to generate a name that doesn't conflict with your group.\n\t\t\t// \"k8s.io/apis/events/v1beta1.Event\": \"EventResource\"\n\t\t},\n\t\tKeyFunc: func(t *types.Type) string {\n\t\t\treturn t.Name.Package + \".\" + t.Name.Name\n\t\t},\n\t\tDelegate: namer.NewPublicNamer(0),\n\t}\n\tprivateNamer := \u0026ExceptionNamer{\n\t\tExceptions: map[string]string{\n\t\t\t// these exceptions are used to deconflict the generated code\n\t\t\t// you can put your fully qualified package like\n\t\t\t// to generate a name that doesn't conflict with your group.\n\t\t\t// \"k8s.io/apis/events/v1beta1.Event\": \"eventResource\"\n\t\t},\n\t\tKeyFunc: func(t *types.Type) string {\n\t\t\treturn t.Name.Package + \".\" + t.Name.Name\n\t\t},\n\t\tDelegate: namer.NewPrivateNamer(0),\n\t}\n\tpublicPluralNamer := \u0026ExceptionNamer{\n\t\tExceptions: map[string]string{\n\t\t\t// these exceptions are used to deconflict the generated code\n\t\t\t// you can put your fully qualified package like\n\t\t\t// to generate a name that doesn't conflict with your group.\n\t\t\t// \"k8s.io/apis/events/v1beta1.Event\": \"EventResource\"\n\t\t},\n\t\tKeyFunc: func(t *types.Type) string {\n\t\t\treturn t.Name.Package + \".\" + t.Name.Name\n\t\t},\n\t\tDelegate: namer.NewPublicPluralNamer(pluralExceptions),\n\t}\n\tprivatePluralNamer := \u0026ExceptionNamer{\n\t\tExceptions: map[string]string{\n\t\t\t// you can put your fully qualified package like\n\t\t\t// to generate a name that doesn't conflict with your group.\n\t\t\t// \"k8s.io/apis/events/v1beta1.Event\": \"eventResource\"\n\t\t\t// these exceptions are used to deconflict the generated code\n\t\t\t\"k8s.io/apis/events/v1beta1.Event\": \"eventResources\",\n\t\t\t\"k8s.io/kubernetes/pkg/apis/events.Event\": \"eventResources\",\n\t\t},\n\t\tKeyFunc: func(t *types.Type) string {\n\t\t\treturn t.Name.Package + \".\" + t.Name.Name\n\t\t},\n\t\tDelegate: namer.NewPrivatePluralNamer(pluralExceptions),\n\t}\n\n\treturn namer.NameSystems{\n\t\t\"singularKind\": namer.NewPublicNamer(0),\n\t\t\"public\": publicNamer,\n\t\t\"private\": privateNamer,\n\t\t\"raw\": namer.NewRawNamer(\"\", nil),\n\t\t\"publicPlural\": publicPluralNamer,\n\t\t\"privatePlural\": privatePluralNamer,\n\t\t\"allLowercasePlural\": lowercaseNamer,\n\t\t\"resource\": codegennamer.NewTagOverrideNamer(\"resourceName\", lowercaseNamer),\n\t}\n}","line":{"from":40,"to":105}} {"id":100029828,"name":"Name","signature":"func (n *ExceptionNamer) Name(t *types.Type) string","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/client_generator.go","code":"// Name provides the requested name for a type.\nfunc (n *ExceptionNamer) Name(t *types.Type) string {\n\tkey := n.KeyFunc(t)\n\tif exception, ok := n.Exceptions[key]; ok {\n\t\treturn exception\n\t}\n\treturn n.Delegate.Name(t)\n}","line":{"from":116,"to":123}} {"id":100029829,"name":"DefaultNameSystem","signature":"func DefaultNameSystem() string","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/client_generator.go","code":"// DefaultNameSystem returns the default name system for ordering the types to be\n// processed by the generators in this package.\nfunc DefaultNameSystem() string {\n\treturn \"public\"\n}","line":{"from":125,"to":129}} {"id":100029830,"name":"packageForGroup","signature":"func packageForGroup(gv clientgentypes.GroupVersion, typeList []*types.Type, clientsetPackage string, groupPackageName string, groupGoName string, apiPath string, srcTreePath string, inputPackage string, applyBuilderPackage string, boilerplate []byte) generator.Package","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/client_generator.go","code":"func packageForGroup(gv clientgentypes.GroupVersion, typeList []*types.Type, clientsetPackage string, groupPackageName string, groupGoName string, apiPath string, srcTreePath string, inputPackage string, applyBuilderPackage string, boilerplate []byte) generator.Package {\n\tgroupVersionClientPackage := filepath.Join(clientsetPackage, \"typed\", strings.ToLower(groupPackageName), strings.ToLower(gv.Version.NonEmpty()))\n\treturn \u0026generator.DefaultPackage{\n\t\tPackageName: strings.ToLower(gv.Version.NonEmpty()),\n\t\tPackagePath: groupVersionClientPackage,\n\t\tHeaderText: boilerplate,\n\t\tPackageDocumentation: []byte(\"// This package has the automatically generated typed clients.\\n\"),\n\t\t// GeneratorFunc returns a list of generators. Each generator makes a\n\t\t// single file.\n\t\tGeneratorFunc: func(c *generator.Context) (generators []generator.Generator) {\n\t\t\tgenerators = []generator.Generator{\n\t\t\t\t// Always generate a \"doc.go\" file.\n\t\t\t\tgenerator.DefaultGen{OptionalName: \"doc\"},\n\t\t\t}\n\t\t\t// Since we want a file per type that we generate a client for, we\n\t\t\t// have to provide a function for this.\n\t\t\tfor _, t := range typeList {\n\t\t\t\tgenerators = append(generators, \u0026genClientForType{\n\t\t\t\t\tDefaultGen: generator.DefaultGen{\n\t\t\t\t\t\tOptionalName: strings.ToLower(c.Namers[\"private\"].Name(t)),\n\t\t\t\t\t},\n\t\t\t\t\toutputPackage: groupVersionClientPackage,\n\t\t\t\t\tinputPackage: inputPackage,\n\t\t\t\t\tclientsetPackage: clientsetPackage,\n\t\t\t\t\tapplyConfigurationPackage: applyBuilderPackage,\n\t\t\t\t\tgroup: gv.Group.NonEmpty(),\n\t\t\t\t\tversion: gv.Version.String(),\n\t\t\t\t\tgroupGoName: groupGoName,\n\t\t\t\t\ttypeToMatch: t,\n\t\t\t\t\timports: generator.NewImportTracker(),\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tgenerators = append(generators, \u0026genGroup{\n\t\t\t\tDefaultGen: generator.DefaultGen{\n\t\t\t\t\tOptionalName: groupPackageName + \"_client\",\n\t\t\t\t},\n\t\t\t\toutputPackage: groupVersionClientPackage,\n\t\t\t\tinputPackage: inputPackage,\n\t\t\t\tclientsetPackage: clientsetPackage,\n\t\t\t\tgroup: gv.Group.NonEmpty(),\n\t\t\t\tversion: gv.Version.String(),\n\t\t\t\tgroupGoName: groupGoName,\n\t\t\t\tapiPath: apiPath,\n\t\t\t\ttypes: typeList,\n\t\t\t\timports: generator.NewImportTracker(),\n\t\t\t})\n\n\t\t\texpansionFileName := \"generated_expansion\"\n\t\t\tgenerators = append(generators, \u0026genExpansion{\n\t\t\t\tgroupPackagePath: filepath.Join(srcTreePath, groupVersionClientPackage),\n\t\t\t\tDefaultGen: generator.DefaultGen{\n\t\t\t\t\tOptionalName: expansionFileName,\n\t\t\t\t},\n\t\t\t\ttypes: typeList,\n\t\t\t})\n\n\t\t\treturn generators\n\t\t},\n\t\tFilterFunc: func(c *generator.Context, t *types.Type) bool {\n\t\t\treturn util.MustParseClientGenTags(append(t.SecondClosestCommentLines, t.CommentLines...)).GenerateClient\n\t\t},\n\t}\n}","line":{"from":131,"to":194}} {"id":100029831,"name":"packageForClientset","signature":"func packageForClientset(customArgs *clientgenargs.CustomArgs, clientsetPackage string, groupGoNames map[clientgentypes.GroupVersion]string, boilerplate []byte) generator.Package","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/client_generator.go","code":"func packageForClientset(customArgs *clientgenargs.CustomArgs, clientsetPackage string, groupGoNames map[clientgentypes.GroupVersion]string, boilerplate []byte) generator.Package {\n\treturn \u0026generator.DefaultPackage{\n\t\tPackageName: customArgs.ClientsetName,\n\t\tPackagePath: clientsetPackage,\n\t\tHeaderText: boilerplate,\n\t\t// GeneratorFunc returns a list of generators. Each generator generates a\n\t\t// single file.\n\t\tGeneratorFunc: func(c *generator.Context) (generators []generator.Generator) {\n\t\t\tgenerators = []generator.Generator{\n\t\t\t\t\u0026genClientset{\n\t\t\t\t\tDefaultGen: generator.DefaultGen{\n\t\t\t\t\t\tOptionalName: \"clientset\",\n\t\t\t\t\t},\n\t\t\t\t\tgroups: customArgs.Groups,\n\t\t\t\t\tgroupGoNames: groupGoNames,\n\t\t\t\t\tclientsetPackage: clientsetPackage,\n\t\t\t\t\toutputPackage: customArgs.ClientsetName,\n\t\t\t\t\timports: generator.NewImportTracker(),\n\t\t\t\t},\n\t\t\t}\n\t\t\treturn generators\n\t\t},\n\t}\n}","line":{"from":196,"to":219}} {"id":100029832,"name":"packageForScheme","signature":"func packageForScheme(customArgs *clientgenargs.CustomArgs, clientsetPackage string, srcTreePath string, groupGoNames map[clientgentypes.GroupVersion]string, boilerplate []byte) generator.Package","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/client_generator.go","code":"func packageForScheme(customArgs *clientgenargs.CustomArgs, clientsetPackage string, srcTreePath string, groupGoNames map[clientgentypes.GroupVersion]string, boilerplate []byte) generator.Package {\n\tschemePackage := filepath.Join(clientsetPackage, \"scheme\")\n\n\t// create runtime.Registry for internal client because it has to know about group versions\n\tinternalClient := false\nNextGroup:\n\tfor _, group := range customArgs.Groups {\n\t\tfor _, v := range group.Versions {\n\t\t\tif v.String() == \"\" {\n\t\t\t\tinternalClient = true\n\t\t\t\tbreak NextGroup\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \u0026generator.DefaultPackage{\n\t\tPackageName: \"scheme\",\n\t\tPackagePath: schemePackage,\n\t\tHeaderText: boilerplate,\n\t\tPackageDocumentation: []byte(\"// This package contains the scheme of the automatically generated clientset.\\n\"),\n\t\t// GeneratorFunc returns a list of generators. Each generator generates a\n\t\t// single file.\n\t\tGeneratorFunc: func(c *generator.Context) (generators []generator.Generator) {\n\t\t\tgenerators = []generator.Generator{\n\t\t\t\t// Always generate a \"doc.go\" file.\n\t\t\t\tgenerator.DefaultGen{OptionalName: \"doc\"},\n\n\t\t\t\t\u0026scheme.GenScheme{\n\t\t\t\t\tDefaultGen: generator.DefaultGen{\n\t\t\t\t\t\tOptionalName: \"register\",\n\t\t\t\t\t},\n\t\t\t\t\tInputPackages: customArgs.GroupVersionPackages(),\n\t\t\t\t\tOutputPackage: schemePackage,\n\t\t\t\t\tOutputPath: filepath.Join(srcTreePath, schemePackage),\n\t\t\t\t\tGroups: customArgs.Groups,\n\t\t\t\t\tGroupGoNames: groupGoNames,\n\t\t\t\t\tImportTracker: generator.NewImportTracker(),\n\t\t\t\t\tCreateRegistry: internalClient,\n\t\t\t\t},\n\t\t\t}\n\t\t\treturn generators\n\t\t},\n\t}\n}","line":{"from":221,"to":264}} {"id":100029833,"name":"applyGroupOverrides","signature":"func applyGroupOverrides(universe types.Universe, customArgs *clientgenargs.CustomArgs)","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/client_generator.go","code":"// applyGroupOverrides applies group name overrides to each package, if applicable. If there is a\n// comment of the form \"// +groupName=somegroup\" or \"// +groupName=somegroup.foo.bar.io\", use the\n// first field (somegroup) as the name of the group in Go code, e.g. as the func name in a clientset.\n//\n// If the first field of the groupName is not unique within the clientset, use \"// +groupName=unique\nfunc applyGroupOverrides(universe types.Universe, customArgs *clientgenargs.CustomArgs) {\n\t// Create a map from \"old GV\" to \"new GV\" so we know what changes we need to make.\n\tchanges := make(map[clientgentypes.GroupVersion]clientgentypes.GroupVersion)\n\tfor gv, inputDir := range customArgs.GroupVersionPackages() {\n\t\tp := universe.Package(genutil.Vendorless(inputDir))\n\t\tif override := types.ExtractCommentTags(\"+\", p.Comments)[\"groupName\"]; override != nil {\n\t\t\tnewGV := clientgentypes.GroupVersion{\n\t\t\t\tGroup: clientgentypes.Group(override[0]),\n\t\t\t\tVersion: gv.Version,\n\t\t\t}\n\t\t\tchanges[gv] = newGV\n\t\t}\n\t}\n\n\t// Modify customArgs.Groups based on the groupName overrides.\n\tnewGroups := make([]clientgentypes.GroupVersions, 0, len(customArgs.Groups))\n\tfor _, gvs := range customArgs.Groups {\n\t\tgv := clientgentypes.GroupVersion{\n\t\t\tGroup: gvs.Group,\n\t\t\tVersion: gvs.Versions[0].Version, // we only need a version, and the first will do\n\t\t}\n\t\tif newGV, ok := changes[gv]; ok {\n\t\t\t// There's an override, so use it.\n\t\t\tnewGVS := clientgentypes.GroupVersions{\n\t\t\t\tPackageName: gvs.PackageName,\n\t\t\t\tGroup: newGV.Group,\n\t\t\t\tVersions: gvs.Versions,\n\t\t\t}\n\t\t\tnewGroups = append(newGroups, newGVS)\n\t\t} else {\n\t\t\t// No override.\n\t\t\tnewGroups = append(newGroups, gvs)\n\t\t}\n\t}\n\tcustomArgs.Groups = newGroups\n}","line":{"from":266,"to":306}} {"id":100029834,"name":"Packages","signature":"func Packages(context *generator.Context, arguments *args.GeneratorArgs) generator.Packages","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/client_generator.go","code":"// Packages makes the client package definition.\nfunc Packages(context *generator.Context, arguments *args.GeneratorArgs) generator.Packages {\n\tboilerplate, err := arguments.LoadGoBoilerplate()\n\tif err != nil {\n\t\tklog.Fatalf(\"Failed loading boilerplate: %v\", err)\n\t}\n\n\tcustomArgs, ok := arguments.CustomArgs.(*clientgenargs.CustomArgs)\n\tif !ok {\n\t\tklog.Fatalf(\"cannot convert arguments.CustomArgs to clientgenargs.CustomArgs\")\n\t}\n\tincludedTypesOverrides := customArgs.IncludedTypesOverrides\n\n\tapplyGroupOverrides(context.Universe, customArgs)\n\n\tgvToTypes := map[clientgentypes.GroupVersion][]*types.Type{}\n\tgroupGoNames := make(map[clientgentypes.GroupVersion]string)\n\tfor gv, inputDir := range customArgs.GroupVersionPackages() {\n\t\tp := context.Universe.Package(path.Vendorless(inputDir))\n\n\t\t// If there's a comment of the form \"// +groupGoName=SomeUniqueShortName\", use that as\n\t\t// the Go group identifier in CamelCase. It defaults\n\t\tgroupGoNames[gv] = namer.IC(strings.Split(gv.Group.NonEmpty(), \".\")[0])\n\t\tif override := types.ExtractCommentTags(\"+\", p.Comments)[\"groupGoName\"]; override != nil {\n\t\t\tgroupGoNames[gv] = namer.IC(override[0])\n\t\t}\n\n\t\t// Package are indexed with the vendor prefix stripped\n\t\tfor n, t := range p.Types {\n\t\t\t// filter out types which are not included in user specified overrides.\n\t\t\ttypesOverride, ok := includedTypesOverrides[gv]\n\t\t\tif ok {\n\t\t\t\tfound := false\n\t\t\t\tfor _, typeStr := range typesOverride {\n\t\t\t\t\tif typeStr == n {\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !found {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// User has not specified any override for this group version.\n\t\t\t\t// filter out types which don't have genclient.\n\t\t\t\tif tags := util.MustParseClientGenTags(append(t.SecondClosestCommentLines, t.CommentLines...)); !tags.GenerateClient {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tif _, found := gvToTypes[gv]; !found {\n\t\t\t\tgvToTypes[gv] = []*types.Type{}\n\t\t\t}\n\t\t\tgvToTypes[gv] = append(gvToTypes[gv], t)\n\t\t}\n\t}\n\n\tvar packageList []generator.Package\n\tclientsetPackage := filepath.Join(arguments.OutputPackagePath, customArgs.ClientsetName)\n\n\tpackageList = append(packageList, packageForClientset(customArgs, clientsetPackage, groupGoNames, boilerplate))\n\tpackageList = append(packageList, packageForScheme(customArgs, clientsetPackage, arguments.OutputBase, groupGoNames, boilerplate))\n\tif customArgs.FakeClient {\n\t\tpackageList = append(packageList, fake.PackageForClientset(customArgs, clientsetPackage, groupGoNames, boilerplate))\n\t}\n\n\t// If --clientset-only=true, we don't regenerate the individual typed clients.\n\tif customArgs.ClientsetOnly {\n\t\treturn generator.Packages(packageList)\n\t}\n\n\torderer := namer.Orderer{Namer: namer.NewPrivateNamer(0)}\n\tgvPackages := customArgs.GroupVersionPackages()\n\tfor _, group := range customArgs.Groups {\n\t\tfor _, version := range group.Versions {\n\t\t\tgv := clientgentypes.GroupVersion{Group: group.Group, Version: version.Version}\n\t\t\ttypes := gvToTypes[gv]\n\t\t\tinputPath := gvPackages[gv]\n\t\t\tpackageList = append(packageList, packageForGroup(gv, orderer.OrderTypes(types), clientsetPackage, group.PackageName, groupGoNames[gv], customArgs.ClientsetAPIPath, arguments.OutputBase, inputPath, customArgs.ApplyConfigurationPackage, boilerplate))\n\t\t\tif customArgs.FakeClient {\n\t\t\t\tpackageList = append(packageList, fake.PackageForGroup(gv, orderer.OrderTypes(types), clientsetPackage, group.PackageName, groupGoNames[gv], inputPath, customArgs.ApplyConfigurationPackage, boilerplate))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn generator.Packages(packageList)\n}","line":{"from":308,"to":393}} {"id":100029835,"name":"Namers","signature":"func (g *genClientset) Namers(c *generator.Context) namer.NameSystems","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/generator_for_clientset.go","code":"func (g *genClientset) Namers(c *generator.Context) namer.NameSystems {\n\treturn namer.NameSystems{\n\t\t\"raw\": namer.NewRawNamer(g.outputPackage, g.imports),\n\t}\n}","line":{"from":44,"to":48}} {"id":100029836,"name":"Filter","signature":"func (g *genClientset) Filter(c *generator.Context, t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/generator_for_clientset.go","code":"// We only want to call GenerateType() once.\nfunc (g *genClientset) Filter(c *generator.Context, t *types.Type) bool {\n\tret := !g.clientsetGenerated\n\tg.clientsetGenerated = true\n\treturn ret\n}","line":{"from":50,"to":55}} {"id":100029837,"name":"Imports","signature":"func (g *genClientset) Imports(c *generator.Context) (imports []string)","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/generator_for_clientset.go","code":"func (g *genClientset) Imports(c *generator.Context) (imports []string) {\n\timports = append(imports, g.imports.ImportLines()...)\n\tfor _, group := range g.groups {\n\t\tfor _, version := range group.Versions {\n\t\t\ttypedClientPath := filepath.Join(g.clientsetPackage, \"typed\", strings.ToLower(group.PackageName), strings.ToLower(version.NonEmpty()))\n\t\t\tgroupAlias := strings.ToLower(g.groupGoNames[clientgentypes.GroupVersion{Group: group.Group, Version: version.Version}])\n\t\t\timports = append(imports, fmt.Sprintf(\"%s%s \\\"%s\\\"\", groupAlias, strings.ToLower(version.NonEmpty()), typedClientPath))\n\t\t}\n\t}\n\treturn\n}","line":{"from":57,"to":67}} {"id":100029838,"name":"GenerateType","signature":"func (g *genClientset) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/generator_for_clientset.go","code":"func (g *genClientset) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {\n\t// TODO: We actually don't need any type information to generate the clientset,\n\t// perhaps we can adapt the go2ild framework to this kind of usage.\n\tsw := generator.NewSnippetWriter(w, c, \"$\", \"$\")\n\n\tallGroups := clientgentypes.ToGroupVersionInfo(g.groups, g.groupGoNames)\n\tm := map[string]interface{}{\n\t\t\"allGroups\": allGroups,\n\t\t\"Config\": c.Universe.Type(types.Name{Package: \"k8s.io/client-go/rest\", Name: \"Config\"}),\n\t\t\"DefaultKubernetesUserAgent\": c.Universe.Function(types.Name{Package: \"k8s.io/client-go/rest\", Name: \"DefaultKubernetesUserAgent\"}),\n\t\t\"RESTClientInterface\": c.Universe.Type(types.Name{Package: \"k8s.io/client-go/rest\", Name: \"Interface\"}),\n\t\t\"RESTHTTPClientFor\": c.Universe.Function(types.Name{Package: \"k8s.io/client-go/rest\", Name: \"HTTPClientFor\"}),\n\t\t\"DiscoveryInterface\": c.Universe.Type(types.Name{Package: \"k8s.io/client-go/discovery\", Name: \"DiscoveryInterface\"}),\n\t\t\"DiscoveryClient\": c.Universe.Type(types.Name{Package: \"k8s.io/client-go/discovery\", Name: \"DiscoveryClient\"}),\n\t\t\"NewDiscoveryClientForConfigAndClient\": c.Universe.Function(types.Name{Package: \"k8s.io/client-go/discovery\", Name: \"NewDiscoveryClientForConfigAndClient\"}),\n\t\t\"NewDiscoveryClientForConfigOrDie\": c.Universe.Function(types.Name{Package: \"k8s.io/client-go/discovery\", Name: \"NewDiscoveryClientForConfigOrDie\"}),\n\t\t\"NewDiscoveryClient\": c.Universe.Function(types.Name{Package: \"k8s.io/client-go/discovery\", Name: \"NewDiscoveryClient\"}),\n\t\t\"flowcontrolNewTokenBucketRateLimiter\": c.Universe.Function(types.Name{Package: \"k8s.io/client-go/util/flowcontrol\", Name: \"NewTokenBucketRateLimiter\"}),\n\t}\n\tsw.Do(clientsetInterface, m)\n\tsw.Do(clientsetTemplate, m)\n\tfor _, g := range allGroups {\n\t\tsw.Do(clientsetInterfaceImplTemplate, g)\n\t}\n\tsw.Do(getDiscoveryTemplate, m)\n\tsw.Do(newClientsetForConfigTemplate, m)\n\tsw.Do(newClientsetForConfigAndClientTemplate, m)\n\tsw.Do(newClientsetForConfigOrDieTemplate, m)\n\tsw.Do(newClientsetForRESTClientTemplate, m)\n\n\treturn sw.Error()\n}","line":{"from":69,"to":100}} {"id":100029839,"name":"Filter","signature":"func (g *genExpansion) Filter(c *generator.Context, t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/generator_for_expansion.go","code":"// We only want to call GenerateType() once per group.\nfunc (g *genExpansion) Filter(c *generator.Context, t *types.Type) bool {\n\treturn len(g.types) == 0 || t == g.types[0]\n}","line":{"from":37,"to":40}} {"id":100029840,"name":"GenerateType","signature":"func (g *genExpansion) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/generator_for_expansion.go","code":"func (g *genExpansion) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {\n\tsw := generator.NewSnippetWriter(w, c, \"$\", \"$\")\n\tfor _, t := range g.types {\n\t\tif _, err := os.Stat(filepath.Join(g.groupPackagePath, strings.ToLower(t.Name.Name+\"_expansion.go\"))); os.IsNotExist(err) {\n\t\t\tsw.Do(expansionInterfaceTemplate, t)\n\t\t}\n\t}\n\treturn sw.Error()\n}","line":{"from":42,"to":50}} {"id":100029841,"name":"Filter","signature":"func (g *genGroup) Filter(c *generator.Context, t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/generator_for_group.go","code":"// We only want to call GenerateType() once per group.\nfunc (g *genGroup) Filter(c *generator.Context, t *types.Type) bool {\n\tif !g.called {\n\t\tg.called = true\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":50,"to":57}} {"id":100029842,"name":"Namers","signature":"func (g *genGroup) Namers(c *generator.Context) namer.NameSystems","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/generator_for_group.go","code":"func (g *genGroup) Namers(c *generator.Context) namer.NameSystems {\n\treturn namer.NameSystems{\n\t\t\"raw\": namer.NewRawNamer(g.outputPackage, g.imports),\n\t}\n}","line":{"from":59,"to":63}} {"id":100029843,"name":"Imports","signature":"func (g *genGroup) Imports(c *generator.Context) (imports []string)","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/generator_for_group.go","code":"func (g *genGroup) Imports(c *generator.Context) (imports []string) {\n\timports = append(imports, g.imports.ImportLines()...)\n\timports = append(imports, filepath.Join(g.clientsetPackage, \"scheme\"))\n\treturn\n}","line":{"from":65,"to":69}} {"id":100029844,"name":"GenerateType","signature":"func (g *genGroup) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/generator_for_group.go","code":"func (g *genGroup) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {\n\tsw := generator.NewSnippetWriter(w, c, \"$\", \"$\")\n\n\tapiPath := func(group string) string {\n\t\tif group == \"core\" {\n\t\t\treturn `\"/api\"`\n\t\t}\n\t\treturn `\"` + g.apiPath + `\"`\n\t}\n\n\tgroupName := g.group\n\tif g.group == \"core\" {\n\t\tgroupName = \"\"\n\t}\n\t// allow user to define a group name that's different from the one parsed from the directory.\n\tp := c.Universe.Package(path.Vendorless(g.inputPackage))\n\tif override := types.ExtractCommentTags(\"+\", p.Comments)[\"groupName\"]; override != nil {\n\t\tgroupName = override[0]\n\t}\n\n\tm := map[string]interface{}{\n\t\t\"group\": g.group,\n\t\t\"version\": g.version,\n\t\t\"groupName\": groupName,\n\t\t\"GroupGoName\": g.groupGoName,\n\t\t\"Version\": namer.IC(g.version),\n\t\t\"types\": g.types,\n\t\t\"apiPath\": apiPath(g.group),\n\t\t\"schemaGroupVersion\": c.Universe.Type(types.Name{Package: \"k8s.io/apimachinery/pkg/runtime/schema\", Name: \"GroupVersion\"}),\n\t\t\"runtimeAPIVersionInternal\": c.Universe.Variable(types.Name{Package: \"k8s.io/apimachinery/pkg/runtime\", Name: \"APIVersionInternal\"}),\n\t\t\"restConfig\": c.Universe.Type(types.Name{Package: \"k8s.io/client-go/rest\", Name: \"Config\"}),\n\t\t\"restDefaultKubernetesUserAgent\": c.Universe.Function(types.Name{Package: \"k8s.io/client-go/rest\", Name: \"DefaultKubernetesUserAgent\"}),\n\t\t\"restRESTClientInterface\": c.Universe.Type(types.Name{Package: \"k8s.io/client-go/rest\", Name: \"Interface\"}),\n\t\t\"RESTHTTPClientFor\": c.Universe.Function(types.Name{Package: \"k8s.io/client-go/rest\", Name: \"HTTPClientFor\"}),\n\t\t\"restRESTClientFor\": c.Universe.Function(types.Name{Package: \"k8s.io/client-go/rest\", Name: \"RESTClientFor\"}),\n\t\t\"restRESTClientForConfigAndClient\": c.Universe.Function(types.Name{Package: \"k8s.io/client-go/rest\", Name: \"RESTClientForConfigAndClient\"}),\n\t\t\"SchemeGroupVersion\": c.Universe.Variable(types.Name{Package: path.Vendorless(g.inputPackage), Name: \"SchemeGroupVersion\"}),\n\t}\n\tsw.Do(groupInterfaceTemplate, m)\n\tsw.Do(groupClientTemplate, m)\n\tfor _, t := range g.types {\n\t\ttags, err := util.ParseClientGenTags(append(t.SecondClosestCommentLines, t.CommentLines...))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\twrapper := map[string]interface{}{\n\t\t\t\"type\": t,\n\t\t\t\"GroupGoName\": g.groupGoName,\n\t\t\t\"Version\": namer.IC(g.version),\n\t\t}\n\t\tif tags.NonNamespaced {\n\t\t\tsw.Do(getterImplNonNamespaced, wrapper)\n\t\t} else {\n\t\t\tsw.Do(getterImplNamespaced, wrapper)\n\t\t}\n\t}\n\tsw.Do(newClientForConfigTemplate, m)\n\tsw.Do(newClientForConfigAndClientTemplate, m)\n\tsw.Do(newClientForConfigOrDieTemplate, m)\n\tsw.Do(newClientForRESTClientTemplate, m)\n\tif g.version == \"\" {\n\t\tsw.Do(setInternalVersionClientDefaultsTemplate, m)\n\t} else {\n\t\tsw.Do(setClientDefaultsTemplate, m)\n\t}\n\tsw.Do(getRESTClient, m)\n\n\treturn sw.Error()\n}","line":{"from":71,"to":139}} {"id":100029845,"name":"Filter","signature":"func (g *genClientForType) Filter(c *generator.Context, t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/generator_for_type.go","code":"// Filter ignores all but one type because we're making a single file per type.\nfunc (g *genClientForType) Filter(c *generator.Context, t *types.Type) bool {\n\treturn t == g.typeToMatch\n}","line":{"from":48,"to":51}} {"id":100029846,"name":"Namers","signature":"func (g *genClientForType) Namers(c *generator.Context) namer.NameSystems","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/generator_for_type.go","code":"func (g *genClientForType) Namers(c *generator.Context) namer.NameSystems {\n\treturn namer.NameSystems{\n\t\t\"raw\": namer.NewRawNamer(g.outputPackage, g.imports),\n\t}\n}","line":{"from":53,"to":57}} {"id":100029847,"name":"Imports","signature":"func (g *genClientForType) Imports(c *generator.Context) (imports []string)","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/generator_for_type.go","code":"func (g *genClientForType) Imports(c *generator.Context) (imports []string) {\n\treturn g.imports.ImportLines()\n}","line":{"from":59,"to":61}} {"id":100029848,"name":"genStatus","signature":"func genStatus(t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/generator_for_type.go","code":"// Ideally, we'd like genStatus to return true if there is a subresource path\n// registered for \"status\" in the API server, but we do not have that\n// information, so genStatus returns true if the type has a status field.\nfunc genStatus(t *types.Type) bool {\n\t// Default to true if we have a Status member\n\thasStatus := false\n\tfor _, m := range t.Members {\n\t\tif m.Name == \"Status\" {\n\t\t\thasStatus = true\n\t\t\tbreak\n\t\t}\n\t}\n\treturn hasStatus \u0026\u0026 !util.MustParseClientGenTags(append(t.SecondClosestCommentLines, t.CommentLines...)).NoStatus\n}","line":{"from":63,"to":76}} {"id":100029849,"name":"GenerateType","signature":"func (g *genClientForType) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/generator_for_type.go","code":"// GenerateType makes the body of a file implementing the individual typed client for type t.\nfunc (g *genClientForType) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {\n\tgenerateApply := len(g.applyConfigurationPackage) \u003e 0\n\tdefaultVerbTemplates := buildDefaultVerbTemplates(generateApply)\n\tsubresourceDefaultVerbTemplates := buildSubresourceDefaultVerbTemplates(generateApply)\n\tsw := generator.NewSnippetWriter(w, c, \"$\", \"$\")\n\tpkg := filepath.Base(t.Name.Package)\n\ttags, err := util.ParseClientGenTags(append(t.SecondClosestCommentLines, t.CommentLines...))\n\tif err != nil {\n\t\treturn err\n\t}\n\ttype extendedInterfaceMethod struct {\n\t\ttemplate string\n\t\targs map[string]interface{}\n\t}\n\t_, typeGVString := util.ParsePathGroupVersion(g.inputPackage)\n\textendedMethods := []extendedInterfaceMethod{}\n\tfor _, e := range tags.Extensions {\n\t\tif e.HasVerb(\"apply\") \u0026\u0026 !generateApply {\n\t\t\tcontinue\n\t\t}\n\t\tinputType := *t\n\t\tresultType := *t\n\t\tinputGVString := typeGVString\n\t\t// TODO: Extract this to some helper method as this code is copied into\n\t\t// 2 other places.\n\t\tif len(e.InputTypeOverride) \u003e 0 {\n\t\t\tif name, pkg := e.Input(); len(pkg) \u003e 0 {\n\t\t\t\t_, inputGVString = util.ParsePathGroupVersion(pkg)\n\t\t\t\tnewType := c.Universe.Type(types.Name{Package: pkg, Name: name})\n\t\t\t\tinputType = *newType\n\t\t\t} else {\n\t\t\t\tinputType.Name.Name = e.InputTypeOverride\n\t\t\t}\n\t\t}\n\t\tif len(e.ResultTypeOverride) \u003e 0 {\n\t\t\tif name, pkg := e.Result(); len(pkg) \u003e 0 {\n\t\t\t\tnewType := c.Universe.Type(types.Name{Package: pkg, Name: name})\n\t\t\t\tresultType = *newType\n\t\t\t} else {\n\t\t\t\tresultType.Name.Name = e.ResultTypeOverride\n\t\t\t}\n\t\t}\n\t\tvar updatedVerbtemplate string\n\t\tif _, exists := subresourceDefaultVerbTemplates[e.VerbType]; e.IsSubresource() \u0026\u0026 exists {\n\t\t\tupdatedVerbtemplate = e.VerbName + \"(\" + strings.TrimPrefix(subresourceDefaultVerbTemplates[e.VerbType], strings.Title(e.VerbType)+\"(\")\n\t\t} else {\n\t\t\tupdatedVerbtemplate = e.VerbName + \"(\" + strings.TrimPrefix(defaultVerbTemplates[e.VerbType], strings.Title(e.VerbType)+\"(\")\n\t\t}\n\t\textendedMethod := extendedInterfaceMethod{\n\t\t\ttemplate: updatedVerbtemplate,\n\t\t\targs: map[string]interface{}{\n\t\t\t\t\"type\": t,\n\t\t\t\t\"inputType\": \u0026inputType,\n\t\t\t\t\"resultType\": \u0026resultType,\n\t\t\t\t\"CreateOptions\": c.Universe.Type(types.Name{Package: \"k8s.io/apimachinery/pkg/apis/meta/v1\", Name: \"CreateOptions\"}),\n\t\t\t\t\"GetOptions\": c.Universe.Type(types.Name{Package: \"k8s.io/apimachinery/pkg/apis/meta/v1\", Name: \"GetOptions\"}),\n\t\t\t\t\"ListOptions\": c.Universe.Type(types.Name{Package: \"k8s.io/apimachinery/pkg/apis/meta/v1\", Name: \"ListOptions\"}),\n\t\t\t\t\"UpdateOptions\": c.Universe.Type(types.Name{Package: \"k8s.io/apimachinery/pkg/apis/meta/v1\", Name: \"UpdateOptions\"}),\n\t\t\t\t\"ApplyOptions\": c.Universe.Type(types.Name{Package: \"k8s.io/apimachinery/pkg/apis/meta/v1\", Name: \"ApplyOptions\"}),\n\t\t\t\t\"PatchType\": c.Universe.Type(types.Name{Package: \"k8s.io/apimachinery/pkg/types\", Name: \"PatchType\"}),\n\t\t\t\t\"jsonMarshal\": c.Universe.Type(types.Name{Package: \"encoding/json\", Name: \"Marshal\"}),\n\t\t\t},\n\t\t}\n\t\tif e.HasVerb(\"apply\") {\n\t\t\textendedMethod.args[\"inputApplyConfig\"] = types.Ref(path.Join(g.applyConfigurationPackage, inputGVString), inputType.Name.Name+\"ApplyConfiguration\")\n\t\t}\n\t\textendedMethods = append(extendedMethods, extendedMethod)\n\t}\n\tm := map[string]interface{}{\n\t\t\"type\": t,\n\t\t\"inputType\": t,\n\t\t\"resultType\": t,\n\t\t\"package\": pkg,\n\t\t\"Package\": namer.IC(pkg),\n\t\t\"namespaced\": !tags.NonNamespaced,\n\t\t\"Group\": namer.IC(g.group),\n\t\t\"subresource\": false,\n\t\t\"subresourcePath\": \"\",\n\t\t\"GroupGoName\": g.groupGoName,\n\t\t\"Version\": namer.IC(g.version),\n\t\t\"CreateOptions\": c.Universe.Type(types.Name{Package: \"k8s.io/apimachinery/pkg/apis/meta/v1\", Name: \"CreateOptions\"}),\n\t\t\"DeleteOptions\": c.Universe.Type(types.Name{Package: \"k8s.io/apimachinery/pkg/apis/meta/v1\", Name: \"DeleteOptions\"}),\n\t\t\"GetOptions\": c.Universe.Type(types.Name{Package: \"k8s.io/apimachinery/pkg/apis/meta/v1\", Name: \"GetOptions\"}),\n\t\t\"ListOptions\": c.Universe.Type(types.Name{Package: \"k8s.io/apimachinery/pkg/apis/meta/v1\", Name: \"ListOptions\"}),\n\t\t\"PatchOptions\": c.Universe.Type(types.Name{Package: \"k8s.io/apimachinery/pkg/apis/meta/v1\", Name: \"PatchOptions\"}),\n\t\t\"ApplyOptions\": c.Universe.Type(types.Name{Package: \"k8s.io/apimachinery/pkg/apis/meta/v1\", Name: \"ApplyOptions\"}),\n\t\t\"UpdateOptions\": c.Universe.Type(types.Name{Package: \"k8s.io/apimachinery/pkg/apis/meta/v1\", Name: \"UpdateOptions\"}),\n\t\t\"PatchType\": c.Universe.Type(types.Name{Package: \"k8s.io/apimachinery/pkg/types\", Name: \"PatchType\"}),\n\t\t\"ApplyPatchType\": c.Universe.Type(types.Name{Package: \"k8s.io/apimachinery/pkg/types\", Name: \"ApplyPatchType\"}),\n\t\t\"watchInterface\": c.Universe.Type(types.Name{Package: \"k8s.io/apimachinery/pkg/watch\", Name: \"Interface\"}),\n\t\t\"RESTClientInterface\": c.Universe.Type(types.Name{Package: \"k8s.io/client-go/rest\", Name: \"Interface\"}),\n\t\t\"schemeParameterCodec\": c.Universe.Variable(types.Name{Package: filepath.Join(g.clientsetPackage, \"scheme\"), Name: \"ParameterCodec\"}),\n\t\t\"jsonMarshal\": c.Universe.Type(types.Name{Package: \"encoding/json\", Name: \"Marshal\"}),\n\t}\n\n\tif generateApply {\n\t\t// Generated apply configuration type references required for generated Apply function\n\t\t_, gvString := util.ParsePathGroupVersion(g.inputPackage)\n\t\tm[\"inputApplyConfig\"] = types.Ref(path.Join(g.applyConfigurationPackage, gvString), t.Name.Name+\"ApplyConfiguration\")\n\t}\n\n\tsw.Do(getterComment, m)\n\tif tags.NonNamespaced {\n\t\tsw.Do(getterNonNamespaced, m)\n\t} else {\n\t\tsw.Do(getterNamespaced, m)\n\t}\n\n\tsw.Do(interfaceTemplate1, m)\n\tif !tags.NoVerbs {\n\t\tif !genStatus(t) {\n\t\t\ttags.SkipVerbs = append(tags.SkipVerbs, \"updateStatus\")\n\t\t\ttags.SkipVerbs = append(tags.SkipVerbs, \"applyStatus\")\n\t\t}\n\t\tinterfaceSuffix := \"\"\n\t\tif len(extendedMethods) \u003e 0 {\n\t\t\tinterfaceSuffix = \"\\n\"\n\t\t}\n\t\tsw.Do(\"\\n\"+generateInterface(defaultVerbTemplates, tags)+interfaceSuffix, m)\n\t\t// add extended verbs into interface\n\t\tfor _, v := range extendedMethods {\n\t\t\tsw.Do(v.template+interfaceSuffix, v.args)\n\t\t}\n\n\t}\n\tsw.Do(interfaceTemplate4, m)\n\n\tif tags.NonNamespaced {\n\t\tsw.Do(structNonNamespaced, m)\n\t\tsw.Do(newStructNonNamespaced, m)\n\t} else {\n\t\tsw.Do(structNamespaced, m)\n\t\tsw.Do(newStructNamespaced, m)\n\t}\n\n\tif tags.NoVerbs {\n\t\treturn sw.Error()\n\t}\n\n\tif tags.HasVerb(\"get\") {\n\t\tsw.Do(getTemplate, m)\n\t}\n\tif tags.HasVerb(\"list\") {\n\t\tsw.Do(listTemplate, m)\n\t}\n\tif tags.HasVerb(\"watch\") {\n\t\tsw.Do(watchTemplate, m)\n\t}\n\n\tif tags.HasVerb(\"create\") {\n\t\tsw.Do(createTemplate, m)\n\t}\n\tif tags.HasVerb(\"update\") {\n\t\tsw.Do(updateTemplate, m)\n\t}\n\tif tags.HasVerb(\"updateStatus\") {\n\t\tsw.Do(updateStatusTemplate, m)\n\t}\n\tif tags.HasVerb(\"delete\") {\n\t\tsw.Do(deleteTemplate, m)\n\t}\n\tif tags.HasVerb(\"deleteCollection\") {\n\t\tsw.Do(deleteCollectionTemplate, m)\n\t}\n\tif tags.HasVerb(\"patch\") {\n\t\tsw.Do(patchTemplate, m)\n\t}\n\tif tags.HasVerb(\"apply\") \u0026\u0026 generateApply {\n\t\tsw.Do(applyTemplate, m)\n\t}\n\tif tags.HasVerb(\"applyStatus\") \u0026\u0026 generateApply {\n\t\tsw.Do(applyStatusTemplate, m)\n\t}\n\n\t// generate expansion methods\n\tfor _, e := range tags.Extensions {\n\t\tif e.HasVerb(\"apply\") \u0026\u0026 !generateApply {\n\t\t\tcontinue\n\t\t}\n\t\tinputType := *t\n\t\tresultType := *t\n\t\tinputGVString := typeGVString\n\t\tif len(e.InputTypeOverride) \u003e 0 {\n\t\t\tif name, pkg := e.Input(); len(pkg) \u003e 0 {\n\t\t\t\t_, inputGVString = util.ParsePathGroupVersion(pkg)\n\t\t\t\tnewType := c.Universe.Type(types.Name{Package: pkg, Name: name})\n\t\t\t\tinputType = *newType\n\t\t\t} else {\n\t\t\t\tinputType.Name.Name = e.InputTypeOverride\n\t\t\t}\n\t\t}\n\t\tif len(e.ResultTypeOverride) \u003e 0 {\n\t\t\tif name, pkg := e.Result(); len(pkg) \u003e 0 {\n\t\t\t\tnewType := c.Universe.Type(types.Name{Package: pkg, Name: name})\n\t\t\t\tresultType = *newType\n\t\t\t} else {\n\t\t\t\tresultType.Name.Name = e.ResultTypeOverride\n\t\t\t}\n\t\t}\n\t\tm[\"inputType\"] = \u0026inputType\n\t\tm[\"resultType\"] = \u0026resultType\n\t\tm[\"subresourcePath\"] = e.SubResourcePath\n\t\tif e.HasVerb(\"apply\") {\n\t\t\tm[\"inputApplyConfig\"] = types.Ref(path.Join(g.applyConfigurationPackage, inputGVString), inputType.Name.Name+\"ApplyConfiguration\")\n\t\t}\n\n\t\tif e.HasVerb(\"get\") {\n\t\t\tif e.IsSubresource() {\n\t\t\t\tsw.Do(adjustTemplate(e.VerbName, e.VerbType, getSubresourceTemplate), m)\n\t\t\t} else {\n\t\t\t\tsw.Do(adjustTemplate(e.VerbName, e.VerbType, getTemplate), m)\n\t\t\t}\n\t\t}\n\n\t\tif e.HasVerb(\"list\") {\n\t\t\tif e.IsSubresource() {\n\t\t\t\tsw.Do(adjustTemplate(e.VerbName, e.VerbType, listSubresourceTemplate), m)\n\t\t\t} else {\n\t\t\t\tsw.Do(adjustTemplate(e.VerbName, e.VerbType, listTemplate), m)\n\t\t\t}\n\t\t}\n\n\t\t// TODO: Figure out schemantic for watching a sub-resource.\n\t\tif e.HasVerb(\"watch\") {\n\t\t\tsw.Do(adjustTemplate(e.VerbName, e.VerbType, watchTemplate), m)\n\t\t}\n\n\t\tif e.HasVerb(\"create\") {\n\t\t\tif e.IsSubresource() {\n\t\t\t\tsw.Do(adjustTemplate(e.VerbName, e.VerbType, createSubresourceTemplate), m)\n\t\t\t} else {\n\t\t\t\tsw.Do(adjustTemplate(e.VerbName, e.VerbType, createTemplate), m)\n\t\t\t}\n\t\t}\n\n\t\tif e.HasVerb(\"update\") {\n\t\t\tif e.IsSubresource() {\n\t\t\t\tsw.Do(adjustTemplate(e.VerbName, e.VerbType, updateSubresourceTemplate), m)\n\t\t\t} else {\n\t\t\t\tsw.Do(adjustTemplate(e.VerbName, e.VerbType, updateTemplate), m)\n\t\t\t}\n\t\t}\n\n\t\t// TODO: Figure out schemantic for deleting a sub-resource (what arguments\n\t\t// are passed, does it need two names? etc.\n\t\tif e.HasVerb(\"delete\") {\n\t\t\tsw.Do(adjustTemplate(e.VerbName, e.VerbType, deleteTemplate), m)\n\t\t}\n\n\t\tif e.HasVerb(\"patch\") {\n\t\t\tsw.Do(adjustTemplate(e.VerbName, e.VerbType, patchTemplate), m)\n\t\t}\n\n\t\tif e.HasVerb(\"apply\") {\n\t\t\tif e.IsSubresource() {\n\t\t\t\tsw.Do(adjustTemplate(e.VerbName, e.VerbType, applySubresourceTemplate), m)\n\t\t\t} else {\n\t\t\t\tsw.Do(adjustTemplate(e.VerbName, e.VerbType, applyTemplate), m)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn sw.Error()\n}","line":{"from":78,"to":342}} {"id":100029850,"name":"adjustTemplate","signature":"func adjustTemplate(name, verbType, template string) string","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/generator_for_type.go","code":"// adjustTemplate adjust the origin verb template using the expansion name.\n// TODO: Make the verbs in templates parametrized so the strings.Replace() is\n// not needed.\nfunc adjustTemplate(name, verbType, template string) string {\n\treturn strings.Replace(template, \" \"+strings.Title(verbType), \" \"+name, -1)\n}","line":{"from":344,"to":349}} {"id":100029851,"name":"generateInterface","signature":"func generateInterface(defaultVerbTemplates map[string]string, tags util.Tags) string","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/generator_for_type.go","code":"func generateInterface(defaultVerbTemplates map[string]string, tags util.Tags) string {\n\t// need an ordered list here to guarantee order of generated methods.\n\tout := []string{}\n\tfor _, m := range util.SupportedVerbs {\n\t\tif tags.HasVerb(m) \u0026\u0026 len(defaultVerbTemplates[m]) \u003e 0 {\n\t\t\tout = append(out, defaultVerbTemplates[m])\n\t\t}\n\t}\n\treturn strings.Join(out, \"\\n\")\n}","line":{"from":351,"to":360}} {"id":100029852,"name":"buildSubresourceDefaultVerbTemplates","signature":"func buildSubresourceDefaultVerbTemplates(generateApply bool) map[string]string","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/generator_for_type.go","code":"func buildSubresourceDefaultVerbTemplates(generateApply bool) map[string]string {\n\tm := map[string]string{\n\t\t\"create\": `Create(ctx context.Context, $.type|private$Name string, $.inputType|private$ *$.inputType|raw$, opts $.CreateOptions|raw$) (*$.resultType|raw$, error)`,\n\t\t\"list\": `List(ctx context.Context, $.type|private$Name string, opts $.ListOptions|raw$) (*$.resultType|raw$List, error)`,\n\t\t\"update\": `Update(ctx context.Context, $.type|private$Name string, $.inputType|private$ *$.inputType|raw$, opts $.UpdateOptions|raw$) (*$.resultType|raw$, error)`,\n\t\t\"get\": `Get(ctx context.Context, $.type|private$Name string, options $.GetOptions|raw$) (*$.resultType|raw$, error)`,\n\t}\n\tif generateApply {\n\t\tm[\"apply\"] = `Apply(ctx context.Context, $.type|private$Name string, $.inputType|private$ *$.inputApplyConfig|raw$, opts $.ApplyOptions|raw$) (*$.resultType|raw$, error)`\n\t}\n\treturn m\n}","line":{"from":362,"to":373}} {"id":100029853,"name":"buildDefaultVerbTemplates","signature":"func buildDefaultVerbTemplates(generateApply bool) map[string]string","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/generator_for_type.go","code":"func buildDefaultVerbTemplates(generateApply bool) map[string]string {\n\tm := map[string]string{\n\t\t\"create\": `Create(ctx context.Context, $.inputType|private$ *$.inputType|raw$, opts $.CreateOptions|raw$) (*$.resultType|raw$, error)`,\n\t\t\"update\": `Update(ctx context.Context, $.inputType|private$ *$.inputType|raw$, opts $.UpdateOptions|raw$) (*$.resultType|raw$, error)`,\n\t\t\"updateStatus\": `UpdateStatus(ctx context.Context, $.inputType|private$ *$.type|raw$, opts $.UpdateOptions|raw$) (*$.type|raw$, error)`,\n\t\t\"delete\": `Delete(ctx context.Context, name string, opts $.DeleteOptions|raw$) error`,\n\t\t\"deleteCollection\": `DeleteCollection(ctx context.Context, opts $.DeleteOptions|raw$, listOpts $.ListOptions|raw$) error`,\n\t\t\"get\": `Get(ctx context.Context, name string, opts $.GetOptions|raw$) (*$.resultType|raw$, error)`,\n\t\t\"list\": `List(ctx context.Context, opts $.ListOptions|raw$) (*$.resultType|raw$List, error)`,\n\t\t\"watch\": `Watch(ctx context.Context, opts $.ListOptions|raw$) ($.watchInterface|raw$, error)`,\n\t\t\"patch\": `Patch(ctx context.Context, name string, pt $.PatchType|raw$, data []byte, opts $.PatchOptions|raw$, subresources ...string) (result *$.resultType|raw$, err error)`,\n\t}\n\tif generateApply {\n\t\tm[\"apply\"] = `Apply(ctx context.Context, $.inputType|private$ *$.inputApplyConfig|raw$, opts $.ApplyOptions|raw$) (result *$.resultType|raw$, err error)`\n\t\tm[\"applyStatus\"] = `ApplyStatus(ctx context.Context, $.inputType|private$ *$.inputApplyConfig|raw$, opts $.ApplyOptions|raw$) (result *$.resultType|raw$, err error)`\n\t}\n\treturn m\n}","line":{"from":375,"to":392}} {"id":100029854,"name":"Namers","signature":"func (g *GenScheme) Namers(c *generator.Context) namer.NameSystems","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/scheme/generator_for_scheme.go","code":"func (g *GenScheme) Namers(c *generator.Context) namer.NameSystems {\n\treturn namer.NameSystems{\n\t\t\"raw\": namer.NewRawNamer(g.OutputPackage, g.ImportTracker),\n\t}\n}","line":{"from":47,"to":51}} {"id":100029855,"name":"Filter","signature":"func (g *GenScheme) Filter(c *generator.Context, t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/scheme/generator_for_scheme.go","code":"// We only want to call GenerateType() once.\nfunc (g *GenScheme) Filter(c *generator.Context, t *types.Type) bool {\n\tret := !g.schemeGenerated\n\tg.schemeGenerated = true\n\treturn ret\n}","line":{"from":53,"to":58}} {"id":100029856,"name":"Imports","signature":"func (g *GenScheme) Imports(c *generator.Context) (imports []string)","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/scheme/generator_for_scheme.go","code":"func (g *GenScheme) Imports(c *generator.Context) (imports []string) {\n\timports = append(imports, g.ImportTracker.ImportLines()...)\n\tfor _, group := range g.Groups {\n\t\tfor _, version := range group.Versions {\n\t\t\tpackagePath := g.InputPackages[clientgentypes.GroupVersion{Group: group.Group, Version: version.Version}]\n\t\t\tgroupAlias := strings.ToLower(g.GroupGoNames[clientgentypes.GroupVersion{Group: group.Group, Version: version.Version}])\n\t\t\tif g.CreateRegistry {\n\t\t\t\t// import the install package for internal clientsets instead of the type package with register.go\n\t\t\t\tif version.Version != \"\" {\n\t\t\t\t\tpackagePath = filepath.Dir(packagePath)\n\t\t\t\t}\n\t\t\t\tpackagePath = filepath.Join(packagePath, \"install\")\n\n\t\t\t\timports = append(imports, fmt.Sprintf(\"%s \\\"%s\\\"\", groupAlias, path.Vendorless(packagePath)))\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\timports = append(imports, fmt.Sprintf(\"%s%s \\\"%s\\\"\", groupAlias, strings.ToLower(version.Version.NonEmpty()), path.Vendorless(packagePath)))\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}","line":{"from":60,"to":81}} {"id":100029857,"name":"GenerateType","signature":"func (g *GenScheme) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/scheme/generator_for_scheme.go","code":"func (g *GenScheme) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {\n\tsw := generator.NewSnippetWriter(w, c, \"$\", \"$\")\n\n\tallGroupVersions := clientgentypes.ToGroupVersionInfo(g.Groups, g.GroupGoNames)\n\tallInstallGroups := clientgentypes.ToGroupInstallPackages(g.Groups, g.GroupGoNames)\n\n\tm := map[string]interface{}{\n\t\t\"publicScheme\": !g.PrivateScheme,\n\t\t\"allGroupVersions\": allGroupVersions,\n\t\t\"allInstallGroups\": allInstallGroups,\n\t\t\"customRegister\": false,\n\t\t\"runtimeNewParameterCodec\": c.Universe.Function(types.Name{Package: \"k8s.io/apimachinery/pkg/runtime\", Name: \"NewParameterCodec\"}),\n\t\t\"runtimeNewScheme\": c.Universe.Function(types.Name{Package: \"k8s.io/apimachinery/pkg/runtime\", Name: \"NewScheme\"}),\n\t\t\"serializerNewCodecFactory\": c.Universe.Function(types.Name{Package: \"k8s.io/apimachinery/pkg/runtime/serializer\", Name: \"NewCodecFactory\"}),\n\t\t\"runtimeScheme\": c.Universe.Type(types.Name{Package: \"k8s.io/apimachinery/pkg/runtime\", Name: \"Scheme\"}),\n\t\t\"runtimeSchemeBuilder\": c.Universe.Type(types.Name{Package: \"k8s.io/apimachinery/pkg/runtime\", Name: \"SchemeBuilder\"}),\n\t\t\"runtimeUtilMust\": c.Universe.Function(types.Name{Package: \"k8s.io/apimachinery/pkg/util/runtime\", Name: \"Must\"}),\n\t\t\"schemaGroupVersion\": c.Universe.Type(types.Name{Package: \"k8s.io/apimachinery/pkg/runtime/schema\", Name: \"GroupVersion\"}),\n\t\t\"metav1AddToGroupVersion\": c.Universe.Function(types.Name{Package: \"k8s.io/apimachinery/pkg/apis/meta/v1\", Name: \"AddToGroupVersion\"}),\n\t}\n\tglobals := map[string]string{\n\t\t\"Scheme\": \"Scheme\",\n\t\t\"Codecs\": \"Codecs\",\n\t\t\"ParameterCodec\": \"ParameterCodec\",\n\t\t\"Registry\": \"Registry\",\n\t}\n\tfor k, v := range globals {\n\t\tif g.PrivateScheme {\n\t\t\tm[k] = strings.ToLower(v[0:1]) + v[1:]\n\t\t} else {\n\t\t\tm[k] = v\n\t\t}\n\t}\n\n\tsw.Do(globalsTemplate, m)\n\n\tif g.OutputPath != \"\" {\n\t\tif _, err := os.Stat(filepath.Join(g.OutputPath, strings.ToLower(\"register_custom.go\"))); err == nil {\n\t\t\tm[\"customRegister\"] = true\n\t\t}\n\t}\n\n\tif g.CreateRegistry {\n\t\tsw.Do(registryRegistration, m)\n\t} else {\n\t\tsw.Do(simpleRegistration, m)\n\t}\n\n\treturn sw.Error()\n}","line":{"from":83,"to":132}} {"id":100029858,"name":"ParsePathGroupVersion","signature":"func ParsePathGroupVersion(pgvString string) (gvPath string, gvString string)","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/util/gvpackages.go","code":"func ParsePathGroupVersion(pgvString string) (gvPath string, gvString string) {\n\tsubs := strings.Split(pgvString, \"/\")\n\tlength := len(subs)\n\tswitch length {\n\tcase 0, 1, 2:\n\t\treturn \"\", pgvString\n\tdefault:\n\t\treturn strings.Join(subs[:length-2], \"/\"), strings.Join(subs[length-2:], \"/\")\n\t}\n}","line":{"from":21,"to":30}} {"id":100029859,"name":"IsSubresource","signature":"func (e *extension) IsSubresource() bool","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/util/tags.go","code":"// IsSubresource indicates if this extension should generate the sub-resource.\nfunc (e *extension) IsSubresource() bool {\n\treturn len(e.SubResourcePath) \u003e 0\n}","line":{"from":129,"to":132}} {"id":100029860,"name":"HasVerb","signature":"func (e *extension) HasVerb(verb string) bool","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/util/tags.go","code":"// HasVerb checks if the extension matches the given verb.\nfunc (e *extension) HasVerb(verb string) bool {\n\treturn e.VerbType == verb\n}","line":{"from":134,"to":137}} {"id":100029861,"name":"Input","signature":"func (e *extension) Input() (string, string)","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/util/tags.go","code":"// Input returns the input override package path and the type.\nfunc (e *extension) Input() (string, string) {\n\tparts := strings.Split(e.InputTypeOverride, \".\")\n\treturn parts[len(parts)-1], strings.Join(parts[0:len(parts)-1], \".\")\n}","line":{"from":139,"to":143}} {"id":100029862,"name":"Result","signature":"func (e *extension) Result() (string, string)","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/util/tags.go","code":"// Result returns the result override package path and the type.\nfunc (e *extension) Result() (string, string) {\n\tparts := strings.Split(e.ResultTypeOverride, \".\")\n\treturn parts[len(parts)-1], strings.Join(parts[0:len(parts)-1], \".\")\n}","line":{"from":145,"to":149}} {"id":100029863,"name":"HasVerb","signature":"func (t Tags) HasVerb(verb string) bool","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/util/tags.go","code":"// HasVerb returns true if we should include the given verb in final client interface and\n// generate the function for it.\nfunc (t Tags) HasVerb(verb string) bool {\n\tif len(t.SkipVerbs) == 0 {\n\t\treturn true\n\t}\n\tfor _, s := range t.SkipVerbs {\n\t\tif verb == s {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":168,"to":180}} {"id":100029864,"name":"MustParseClientGenTags","signature":"func MustParseClientGenTags(lines []string) Tags","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/util/tags.go","code":"// MustParseClientGenTags calls ParseClientGenTags but instead of returning error it panics.\nfunc MustParseClientGenTags(lines []string) Tags {\n\ttags, err := ParseClientGenTags(lines)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\treturn tags\n}","line":{"from":182,"to":189}} {"id":100029865,"name":"ParseClientGenTags","signature":"func ParseClientGenTags(lines []string) (Tags, error)","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/util/tags.go","code":"// ParseClientGenTags parse the provided genclient tags and validates that no unknown\n// tags are provided.\nfunc ParseClientGenTags(lines []string) (Tags, error) {\n\tret := Tags{}\n\tvalues := types.ExtractCommentTags(\"+\", lines)\n\tvar value []string\n\tvalue, ret.GenerateClient = values[\"genclient\"]\n\t// Check the old format and error when used to avoid generating client when //+genclient=false\n\tif len(value) \u003e 0 \u0026\u0026 len(value[0]) \u003e 0 {\n\t\treturn ret, fmt.Errorf(\"+genclient=%s is invalid, use //+genclient if you want to generate client or omit it when you want to disable generation\", value)\n\t}\n\t_, ret.NonNamespaced = values[genClientPrefix+\"nonNamespaced\"]\n\t// Check the old format and error when used\n\tif value := values[\"nonNamespaced\"]; len(value) \u003e 0 \u0026\u0026 len(value[0]) \u003e 0 {\n\t\treturn ret, fmt.Errorf(\"+nonNamespaced=%s is invalid, use //+genclient:nonNamespaced instead\", value[0])\n\t}\n\t_, ret.NoVerbs = values[genClientPrefix+\"noVerbs\"]\n\t_, ret.NoStatus = values[genClientPrefix+\"noStatus\"]\n\tonlyVerbs := []string{}\n\tif _, isReadonly := values[genClientPrefix+\"readonly\"]; isReadonly {\n\t\tonlyVerbs = ReadonlyVerbs\n\t}\n\t// Check the old format and error when used\n\tif value := values[\"readonly\"]; len(value) \u003e 0 \u0026\u0026 len(value[0]) \u003e 0 {\n\t\treturn ret, fmt.Errorf(\"+readonly=%s is invalid, use //+genclient:readonly instead\", value[0])\n\t}\n\tif v, exists := values[genClientPrefix+\"skipVerbs\"]; exists {\n\t\tret.SkipVerbs = strings.Split(v[0], \",\")\n\t}\n\tif v, exists := values[genClientPrefix+\"onlyVerbs\"]; exists || len(onlyVerbs) \u003e 0 {\n\t\tif len(v) \u003e 0 {\n\t\t\tonlyVerbs = append(onlyVerbs, strings.Split(v[0], \",\")...)\n\t\t}\n\t\tskipVerbs := []string{}\n\t\tfor _, m := range SupportedVerbs {\n\t\t\tskip := true\n\t\t\tfor _, o := range onlyVerbs {\n\t\t\t\tif o == m {\n\t\t\t\t\tskip = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Check for conflicts\n\t\t\tfor _, v := range skipVerbs {\n\t\t\t\tif v == m {\n\t\t\t\t\treturn ret, fmt.Errorf(\"verb %q used both in genclient:skipVerbs and genclient:onlyVerbs\", v)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif skip {\n\t\t\t\tskipVerbs = append(skipVerbs, m)\n\t\t\t}\n\t\t}\n\t\tret.SkipVerbs = skipVerbs\n\t}\n\tvar err error\n\tif ret.Extensions, err = parseClientExtensions(values); err != nil {\n\t\treturn ret, err\n\t}\n\treturn ret, validateClientGenTags(values)\n}","line":{"from":191,"to":250}} {"id":100029866,"name":"parseClientExtensions","signature":"func parseClientExtensions(tags map[string][]string) ([]extension, error)","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/util/tags.go","code":"func parseClientExtensions(tags map[string][]string) ([]extension, error) {\n\tvar ret []extension\n\tfor name, values := range tags {\n\t\tif !strings.HasPrefix(name, genClientPrefix+\"method\") {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, value := range values {\n\t\t\t// the value comes in this form: \"Foo,verb=create\"\n\t\t\text := extension{}\n\t\t\tparts := strings.Split(value, \",\")\n\t\t\tif len(parts) == 0 {\n\t\t\t\treturn nil, fmt.Errorf(\"invalid of empty extension verb name: %q\", value)\n\t\t\t}\n\t\t\t// The first part represents the name of the extension\n\t\t\text.VerbName = parts[0]\n\t\t\tif len(ext.VerbName) == 0 {\n\t\t\t\treturn nil, fmt.Errorf(\"must specify a verb name (// +genclient:method=Foo,verb=create)\")\n\t\t\t}\n\t\t\t// Parse rest of the arguments\n\t\t\tparams := parts[1:]\n\t\t\tfor _, p := range params {\n\t\t\t\tparts := strings.Split(p, \"=\")\n\t\t\t\tif len(parts) != 2 {\n\t\t\t\t\treturn nil, fmt.Errorf(\"invalid extension tag specification %q\", p)\n\t\t\t\t}\n\t\t\t\tkey, val := strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1])\n\t\t\t\tif len(val) == 0 {\n\t\t\t\t\treturn nil, fmt.Errorf(\"empty value of %q for %q extension\", key, ext.VerbName)\n\t\t\t\t}\n\t\t\t\tswitch key {\n\t\t\t\tcase \"verb\":\n\t\t\t\t\text.VerbType = val\n\t\t\t\tcase \"subresource\":\n\t\t\t\t\text.SubResourcePath = val\n\t\t\t\tcase \"input\":\n\t\t\t\t\text.InputTypeOverride = val\n\t\t\t\tcase \"result\":\n\t\t\t\t\text.ResultTypeOverride = val\n\t\t\t\tdefault:\n\t\t\t\t\treturn nil, fmt.Errorf(\"unknown extension configuration key %q\", key)\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Validate resulting extension configuration\n\t\t\tif len(ext.VerbType) == 0 {\n\t\t\t\treturn nil, fmt.Errorf(\"verb type must be specified (use '// +genclient:method=%s,verb=create')\", ext.VerbName)\n\t\t\t}\n\t\t\tif len(ext.ResultTypeOverride) \u003e 0 {\n\t\t\t\tsupported := false\n\t\t\t\tfor _, v := range resultTypeSupportedVerbs {\n\t\t\t\t\tif ext.VerbType == v {\n\t\t\t\t\t\tsupported = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !supported {\n\t\t\t\t\treturn nil, fmt.Errorf(\"%s: result type is not supported for %q verbs (supported verbs: %#v)\", ext.VerbName, ext.VerbType, resultTypeSupportedVerbs)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(ext.InputTypeOverride) \u003e 0 {\n\t\t\t\tsupported := false\n\t\t\t\tfor _, v := range inputTypeSupportedVerbs {\n\t\t\t\t\tif ext.VerbType == v {\n\t\t\t\t\t\tsupported = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !supported {\n\t\t\t\t\treturn nil, fmt.Errorf(\"%s: input type is not supported for %q verbs (supported verbs: %#v)\", ext.VerbName, ext.VerbType, inputTypeSupportedVerbs)\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, t := range unsupportedExtensionVerbs {\n\t\t\t\tif ext.VerbType == t {\n\t\t\t\t\treturn nil, fmt.Errorf(\"verb %q is not supported by extension generator\", ext.VerbType)\n\t\t\t\t}\n\t\t\t}\n\t\t\tret = append(ret, ext)\n\t\t}\n\t}\n\treturn ret, nil\n}","line":{"from":252,"to":331}} {"id":100029867,"name":"validateClientGenTags","signature":"func validateClientGenTags(values map[string][]string) error","file":"staging/src/k8s.io/code-generator/cmd/client-gen/generators/util/tags.go","code":"// validateTags validates that only supported genclient tags were provided.\nfunc validateClientGenTags(values map[string][]string) error {\n\tfor _, k := range supportedTags {\n\t\tdelete(values, k)\n\t}\n\tfor key := range values {\n\t\tif strings.HasPrefix(key, strings.TrimSuffix(genClientPrefix, \":\")) {\n\t\t\treturn errors.New(\"unknown tag detected: \" + key)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":333,"to":344}} {"id":100029868,"name":"main","signature":"func main()","file":"staging/src/k8s.io/code-generator/cmd/client-gen/main.go","code":"func main() {\n\tklog.InitFlags(nil)\n\tgenericArgs, customArgs := generatorargs.NewDefaults()\n\n\t// Override defaults.\n\t// TODO: move this out of client-gen\n\tgenericArgs.OutputPackagePath = \"k8s.io/kubernetes/pkg/client/clientset_generated/\"\n\n\tgenericArgs.AddFlags(pflag.CommandLine)\n\tcustomArgs.AddFlags(pflag.CommandLine, \"k8s.io/kubernetes/pkg/apis\") // TODO: move this input path out of client-gen\n\tflag.Set(\"logtostderr\", \"true\")\n\tpflag.CommandLine.AddGoFlagSet(flag.CommandLine)\n\tpflag.Parse()\n\n\t// add group version package as input dirs for gengo\n\tfor _, pkg := range customArgs.Groups {\n\t\tfor _, v := range pkg.Versions {\n\t\t\tgenericArgs.InputDirs = append(genericArgs.InputDirs, v.Package)\n\t\t}\n\t}\n\n\tif err := generatorargs.Validate(genericArgs); err != nil {\n\t\tklog.Fatalf(\"Error: %v\", err)\n\t}\n\n\tif err := genericArgs.Execute(\n\t\tgenerators.NameSystems(util.PluralExceptionListToMapOrDie(customArgs.PluralExceptions)),\n\t\tgenerators.DefaultNameSystem(),\n\t\tgenerators.Packages,\n\t); err != nil {\n\t\tklog.Fatalf(\"Error: %v\", err)\n\t}\n}","line":{"from":31,"to":63}} {"id":100029869,"name":"Vendorless","signature":"func Vendorless(p string) string","file":"staging/src/k8s.io/code-generator/cmd/client-gen/path/path.go","code":"// Vendorless removes the longest match of \"*/vendor/\" from the front of p.\n// It is useful if a package locates in vendor/, e.g.,\n// k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/apis/meta/v1, because gengo\n// indexes the package with its import path, e.g.,\n// k8s.io/apimachinery/pkg/apis/meta/v1,\nfunc Vendorless(p string) string {\n\tif pos := strings.LastIndex(p, \"/vendor/\"); pos != -1 {\n\t\treturn p[pos+len(\"/vendor/\"):]\n\t}\n\treturn p\n}","line":{"from":21,"to":31}} {"id":100029870,"name":"ToGroupVersion","signature":"func ToGroupVersion(gv string) (GroupVersion, error)","file":"staging/src/k8s.io/code-generator/cmd/client-gen/types/helpers.go","code":"// ToGroupVersion turns \"group/version\" string into a GroupVersion struct. It reports error\n// if it cannot parse the string.\nfunc ToGroupVersion(gv string) (GroupVersion, error) {\n\t// this can be the internal version for the legacy kube types\n\t// TODO once we've cleared the last uses as strings, this special case should be removed.\n\tif (len(gv) == 0) || (gv == \"/\") {\n\t\treturn GroupVersion{}, nil\n\t}\n\n\tswitch strings.Count(gv, \"/\") {\n\tcase 0:\n\t\treturn GroupVersion{Group(gv), \"\"}, nil\n\tcase 1:\n\t\ti := strings.Index(gv, \"/\")\n\t\treturn GroupVersion{Group(gv[:i]), Version(gv[i+1:])}, nil\n\tdefault:\n\t\treturn GroupVersion{}, fmt.Errorf(\"unexpected GroupVersion string: %v\", gv)\n\t}\n}","line":{"from":28,"to":46}} {"id":100029871,"name":"Len","signature":"func (a sortableSliceOfVersions) Len() int { return len(a) }","file":"staging/src/k8s.io/code-generator/cmd/client-gen/types/helpers.go","code":"func (a sortableSliceOfVersions) Len() int { return len(a) }","line":{"from":50,"to":50}} {"id":100029872,"name":"Swap","signature":"func (a sortableSliceOfVersions) Swap(i, j int) { a[i], a[j] = a[j], a[i] }","file":"staging/src/k8s.io/code-generator/cmd/client-gen/types/helpers.go","code":"func (a sortableSliceOfVersions) Swap(i, j int) { a[i], a[j] = a[j], a[i] }","line":{"from":51,"to":51}} {"id":100029873,"name":"Less","signature":"func (a sortableSliceOfVersions) Less(i, j int) bool","file":"staging/src/k8s.io/code-generator/cmd/client-gen/types/helpers.go","code":"func (a sortableSliceOfVersions) Less(i, j int) bool {\n\tvi, vj := strings.TrimLeft(a[i], \"v\"), strings.TrimLeft(a[j], \"v\")\n\tmajor := regexp.MustCompile(\"^[0-9]+\")\n\tviMajor, vjMajor := major.FindString(vi), major.FindString(vj)\n\tviRemaining, vjRemaining := strings.TrimLeft(vi, viMajor), strings.TrimLeft(vj, vjMajor)\n\tswitch {\n\tcase len(viRemaining) == 0 \u0026\u0026 len(vjRemaining) == 0:\n\t\treturn viMajor \u003c vjMajor\n\tcase len(viRemaining) == 0 \u0026\u0026 len(vjRemaining) != 0:\n\t\t// stable version is greater than unstable version\n\t\treturn false\n\tcase len(viRemaining) != 0 \u0026\u0026 len(vjRemaining) == 0:\n\t\t// stable version is greater than unstable version\n\t\treturn true\n\t}\n\t// neither are stable versions\n\tif viMajor != vjMajor {\n\t\treturn viMajor \u003c vjMajor\n\t}\n\t// assuming at most we have one alpha or one beta version, so if vi contains \"alpha\", it's the lesser one.\n\treturn strings.Contains(viRemaining, \"alpha\")\n}","line":{"from":52,"to":73}} {"id":100029874,"name":"defaultVersion","signature":"func defaultVersion(versions []PackageVersion) Version","file":"staging/src/k8s.io/code-generator/cmd/client-gen/types/helpers.go","code":"// Determine the default version among versions. If a user calls a group client\n// without specifying the version (e.g., c.CoreV1(), instead of c.CoreV1()), the\n// default version will be returned.\nfunc defaultVersion(versions []PackageVersion) Version {\n\tvar versionStrings []string\n\tfor _, version := range versions {\n\t\tversionStrings = append(versionStrings, version.Version.String())\n\t}\n\tsort.Sort(sortableSliceOfVersions(versionStrings))\n\treturn Version(versionStrings[len(versionStrings)-1])\n}","line":{"from":75,"to":85}} {"id":100029875,"name":"ToGroupVersionInfo","signature":"func ToGroupVersionInfo(groups []GroupVersions, groupGoNames map[GroupVersion]string) []GroupVersionInfo","file":"staging/src/k8s.io/code-generator/cmd/client-gen/types/helpers.go","code":"// ToGroupVersionInfo is a helper function used by generators for groups.\nfunc ToGroupVersionInfo(groups []GroupVersions, groupGoNames map[GroupVersion]string) []GroupVersionInfo {\n\tvar groupVersionPackages []GroupVersionInfo\n\tfor _, group := range groups {\n\t\tfor _, version := range group.Versions {\n\t\t\tgroupGoName := groupGoNames[GroupVersion{Group: group.Group, Version: version.Version}]\n\t\t\tgroupVersionPackages = append(groupVersionPackages, GroupVersionInfo{\n\t\t\t\tGroup: Group(namer.IC(group.Group.NonEmpty())),\n\t\t\t\tVersion: Version(namer.IC(version.Version.String())),\n\t\t\t\tPackageAlias: strings.ToLower(groupGoName + version.Version.NonEmpty()),\n\t\t\t\tGroupGoName: groupGoName,\n\t\t\t\tLowerCaseGroupGoName: namer.IL(groupGoName),\n\t\t\t})\n\t\t}\n\t}\n\treturn groupVersionPackages\n}","line":{"from":87,"to":103}} {"id":100029876,"name":"ToGroupInstallPackages","signature":"func ToGroupInstallPackages(groups []GroupVersions, groupGoNames map[GroupVersion]string) []GroupInstallPackage","file":"staging/src/k8s.io/code-generator/cmd/client-gen/types/helpers.go","code":"func ToGroupInstallPackages(groups []GroupVersions, groupGoNames map[GroupVersion]string) []GroupInstallPackage {\n\tvar groupInstallPackages []GroupInstallPackage\n\tfor _, group := range groups {\n\t\tdefaultVersion := defaultVersion(group.Versions)\n\t\tgroupGoName := groupGoNames[GroupVersion{Group: group.Group, Version: defaultVersion}]\n\t\tgroupInstallPackages = append(groupInstallPackages, GroupInstallPackage{\n\t\t\tGroup: Group(namer.IC(group.Group.NonEmpty())),\n\t\t\tInstallPackageAlias: strings.ToLower(groupGoName),\n\t\t})\n\t}\n\treturn groupInstallPackages\n}","line":{"from":105,"to":116}} {"id":100029877,"name":"String","signature":"func (v Version) String() string","file":"staging/src/k8s.io/code-generator/cmd/client-gen/types/types.go","code":"func (v Version) String() string {\n\treturn string(v)\n}","line":{"from":23,"to":25}} {"id":100029878,"name":"NonEmpty","signature":"func (v Version) NonEmpty() string","file":"staging/src/k8s.io/code-generator/cmd/client-gen/types/types.go","code":"func (v Version) NonEmpty() string {\n\tif v == \"\" {\n\t\treturn \"internalVersion\"\n\t}\n\treturn v.String()\n}","line":{"from":27,"to":32}} {"id":100029879,"name":"PackageName","signature":"func (v Version) PackageName() string","file":"staging/src/k8s.io/code-generator/cmd/client-gen/types/types.go","code":"func (v Version) PackageName() string {\n\treturn strings.ToLower(v.NonEmpty())\n}","line":{"from":34,"to":36}} {"id":100029880,"name":"String","signature":"func (g Group) String() string","file":"staging/src/k8s.io/code-generator/cmd/client-gen/types/types.go","code":"func (g Group) String() string {\n\treturn string(g)\n}","line":{"from":40,"to":42}} {"id":100029881,"name":"NonEmpty","signature":"func (g Group) NonEmpty() string","file":"staging/src/k8s.io/code-generator/cmd/client-gen/types/types.go","code":"func (g Group) NonEmpty() string {\n\tif g == \"api\" {\n\t\treturn \"core\"\n\t}\n\treturn string(g)\n}","line":{"from":44,"to":49}} {"id":100029882,"name":"PackageName","signature":"func (g Group) PackageName() string","file":"staging/src/k8s.io/code-generator/cmd/client-gen/types/types.go","code":"func (g Group) PackageName() string {\n\tparts := strings.Split(g.NonEmpty(), \".\")\n\tif parts[0] == \"internal\" \u0026\u0026 len(parts) \u003e 1 {\n\t\treturn strings.ToLower(parts[1] + parts[0])\n\t}\n\treturn strings.ToLower(parts[0])\n}","line":{"from":51,"to":57}} {"id":100029883,"name":"ToAPIVersion","signature":"func (gv GroupVersion) ToAPIVersion() string","file":"staging/src/k8s.io/code-generator/cmd/client-gen/types/types.go","code":"func (gv GroupVersion) ToAPIVersion() string {\n\tif len(gv.Group) \u003e 0 \u0026\u0026 gv.Group.NonEmpty() != \"core\" {\n\t\treturn gv.Group.String() + \"/\" + gv.Version.String()\n\t} else {\n\t\treturn gv.Version.String()\n\t}\n}","line":{"from":70,"to":76}} {"id":100029884,"name":"NewDefaults","signature":"func NewDefaults() (*args.GeneratorArgs, *CustomArgs)","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/args/args.go","code":"// NewDefaults returns default arguments for the generator.\nfunc NewDefaults() (*args.GeneratorArgs, *CustomArgs) {\n\tgenericArgs := args.Default().WithoutDefaultFlagParsing()\n\tcustomArgs := \u0026CustomArgs{\n\t\tBasePeerDirs: DefaultBasePeerDirs,\n\t\tSkipUnsafe: false,\n\t}\n\tgenericArgs.CustomArgs = customArgs\n\tgenericArgs.OutputFileBaseName = \"conversion_generated\"\n\treturn genericArgs, customArgs\n}","line":{"from":57,"to":67}} {"id":100029885,"name":"AddFlags","signature":"func (ca *CustomArgs) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/args/args.go","code":"// AddFlags add the generator flags to the flag set.\nfunc (ca *CustomArgs) AddFlags(fs *pflag.FlagSet) {\n\tpflag.CommandLine.StringSliceVar(\u0026ca.BasePeerDirs, \"base-peer-dirs\", ca.BasePeerDirs,\n\t\t\"Comma-separated list of apimachinery import paths which are considered, after tag-specified peers, for conversions. Only change these if you have very good reasons.\")\n\tpflag.CommandLine.StringSliceVar(\u0026ca.ExtraPeerDirs, \"extra-peer-dirs\", ca.ExtraPeerDirs,\n\t\t\"Application specific comma-separated list of import paths which are considered, after tag-specified peers and base-peer-dirs, for conversions.\")\n\tpflag.CommandLine.StringSliceVar(\u0026ca.ExtraDirs, \"extra-dirs\", ca.ExtraDirs,\n\t\t\"Application specific comma-separated list of import paths which are loaded and considered for callable conversions, but are not considered peers for conversion.\")\n\tpflag.CommandLine.BoolVar(\u0026ca.SkipUnsafe, \"skip-unsafe\", ca.SkipUnsafe,\n\t\t\"If true, will not generate code using unsafe pointer conversions; resulting code may be slower.\")\n}","line":{"from":69,"to":79}} {"id":100029886,"name":"Validate","signature":"func Validate(genericArgs *args.GeneratorArgs) error","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/args/args.go","code":"// Validate checks the given arguments.\nfunc Validate(genericArgs *args.GeneratorArgs) error {\n\t_ = genericArgs.CustomArgs.(*CustomArgs)\n\n\tif len(genericArgs.OutputFileBaseName) == 0 {\n\t\treturn fmt.Errorf(\"output file base name cannot be empty\")\n\t}\n\n\treturn nil\n}","line":{"from":81,"to":90}} {"id":100029887,"name":"extractTag","signature":"func extractTag(comments []string) []string","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func extractTag(comments []string) []string {\n\treturn types.ExtractCommentTags(\"+\", comments)[tagName]\n}","line":{"from":54,"to":56}} {"id":100029888,"name":"extractExplicitFromTag","signature":"func extractExplicitFromTag(comments []string) []string","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func extractExplicitFromTag(comments []string) []string {\n\treturn types.ExtractCommentTags(\"+\", comments)[explicitFromTagName]\n}","line":{"from":58,"to":60}} {"id":100029889,"name":"extractExternalTypesTag","signature":"func extractExternalTypesTag(comments []string) []string","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func extractExternalTypesTag(comments []string) []string {\n\treturn types.ExtractCommentTags(\"+\", comments)[externalTypesTagName]\n}","line":{"from":62,"to":64}} {"id":100029890,"name":"isCopyOnly","signature":"func isCopyOnly(comments []string) bool","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func isCopyOnly(comments []string) bool {\n\tvalues := types.ExtractCommentTags(\"+\", comments)[\"k8s:conversion-fn\"]\n\treturn len(values) == 1 \u0026\u0026 values[0] == \"copy-only\"\n}","line":{"from":66,"to":69}} {"id":100029891,"name":"isDrop","signature":"func isDrop(comments []string) bool","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func isDrop(comments []string) bool {\n\tvalues := types.ExtractCommentTags(\"+\", comments)[\"k8s:conversion-fn\"]\n\treturn len(values) == 1 \u0026\u0026 values[0] == \"drop\"\n}","line":{"from":71,"to":74}} {"id":100029892,"name":"conversionNamer","signature":"func conversionNamer() *namer.NameStrategy","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"// TODO: This is created only to reduce number of changes in a single PR.\n// Remove it and use PublicNamer instead.\nfunc conversionNamer() *namer.NameStrategy {\n\treturn \u0026namer.NameStrategy{\n\t\tJoin: func(pre string, in []string, post string) string {\n\t\t\treturn strings.Join(in, \"_\")\n\t\t},\n\t\tPrependPackageNames: 1,\n\t}\n}","line":{"from":76,"to":85}} {"id":100029893,"name":"defaultFnNamer","signature":"func defaultFnNamer() *namer.NameStrategy","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func defaultFnNamer() *namer.NameStrategy {\n\treturn \u0026namer.NameStrategy{\n\t\tPrefix: \"SetDefaults_\",\n\t\tJoin: func(pre string, in []string, post string) string {\n\t\t\treturn pre + strings.Join(in, \"_\") + post\n\t\t},\n\t}\n}","line":{"from":87,"to":94}} {"id":100029894,"name":"NameSystems","signature":"func NameSystems() namer.NameSystems","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"// NameSystems returns the name system used by the generators in this package.\nfunc NameSystems() namer.NameSystems {\n\treturn namer.NameSystems{\n\t\t\"public\": conversionNamer(),\n\t\t\"raw\": namer.NewRawNamer(\"\", nil),\n\t\t\"defaultfn\": defaultFnNamer(),\n\t}\n}","line":{"from":96,"to":103}} {"id":100029895,"name":"DefaultNameSystem","signature":"func DefaultNameSystem() string","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"// DefaultNameSystem returns the default name system for ordering the types to be\n// processed by the generators in this package.\nfunc DefaultNameSystem() string {\n\treturn \"public\"\n}","line":{"from":105,"to":109}} {"id":100029896,"name":"getPeerTypeFor","signature":"func getPeerTypeFor(context *generator.Context, t *types.Type, potenialPeerPkgs []string) *types.Type","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func getPeerTypeFor(context *generator.Context, t *types.Type, potenialPeerPkgs []string) *types.Type {\n\tfor _, ppp := range potenialPeerPkgs {\n\t\tp := context.Universe.Package(ppp)\n\t\tif p == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif p.Has(t.Name.Name) {\n\t\t\treturn p.Type(t.Name.Name)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":111,"to":122}} {"id":100029897,"name":"getManualConversionFunctions","signature":"func getManualConversionFunctions(context *generator.Context, pkg *types.Package, manualMap conversionFuncMap)","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"// Returns all manually-defined conversion functions in the package.\nfunc getManualConversionFunctions(context *generator.Context, pkg *types.Package, manualMap conversionFuncMap) {\n\tif pkg == nil {\n\t\tklog.Warning(\"Skipping nil package passed to getManualConversionFunctions\")\n\t\treturn\n\t}\n\tklog.V(5).Infof(\"Scanning for conversion functions in %v\", pkg.Name)\n\n\tscopeName := types.Ref(conversionPackagePath, \"Scope\").Name\n\terrorName := types.Ref(\"\", \"error\").Name\n\tbuffer := \u0026bytes.Buffer{}\n\tsw := generator.NewSnippetWriter(buffer, context, \"$\", \"$\")\n\n\tfor _, f := range pkg.Functions {\n\t\tif f.Underlying == nil || f.Underlying.Kind != types.Func {\n\t\t\tklog.Errorf(\"Malformed function: %#v\", f)\n\t\t\tcontinue\n\t\t}\n\t\tif f.Underlying.Signature == nil {\n\t\t\tklog.Errorf(\"Function without signature: %#v\", f)\n\t\t\tcontinue\n\t\t}\n\t\tklog.V(8).Infof(\"Considering function %s\", f.Name)\n\t\tsignature := f.Underlying.Signature\n\t\t// Check whether the function is conversion function.\n\t\t// Note that all of them have signature:\n\t\t// func Convert_inType_To_outType(inType, outType, conversion.Scope) error\n\t\tif signature.Receiver != nil {\n\t\t\tklog.V(8).Infof(\"%s has a receiver\", f.Name)\n\t\t\tcontinue\n\t\t}\n\t\tif len(signature.Parameters) != 3 || signature.Parameters[2].Name != scopeName {\n\t\t\tklog.V(8).Infof(\"%s has wrong parameters\", f.Name)\n\t\t\tcontinue\n\t\t}\n\t\tif len(signature.Results) != 1 || signature.Results[0].Name != errorName {\n\t\t\tklog.V(8).Infof(\"%s has wrong results\", f.Name)\n\t\t\tcontinue\n\t\t}\n\t\tinType := signature.Parameters[0]\n\t\toutType := signature.Parameters[1]\n\t\tif inType.Kind != types.Pointer || outType.Kind != types.Pointer {\n\t\t\tklog.V(8).Infof(\"%s has wrong parameter types\", f.Name)\n\t\t\tcontinue\n\t\t}\n\t\t// Now check if the name satisfies the convention.\n\t\t// TODO: This should call the Namer directly.\n\t\targs := argsFromType(inType.Elem, outType.Elem)\n\t\tsw.Do(\"Convert_$.inType|public$_To_$.outType|public$\", args)\n\t\tif f.Name.Name == buffer.String() {\n\t\t\tklog.V(4).Infof(\"Found conversion function %s\", f.Name)\n\t\t\tkey := conversionPair{inType.Elem, outType.Elem}\n\t\t\t// We might scan the same package twice, and that's OK.\n\t\t\tif v, ok := manualMap[key]; ok \u0026\u0026 v != nil \u0026\u0026 v.Name.Package != pkg.Path {\n\t\t\t\tpanic(fmt.Sprintf(\"duplicate static conversion defined: %s -\u003e %s from:\\n%s.%s\\n%s.%s\", key.inType, key.outType, v.Name.Package, v.Name.Name, f.Name.Package, f.Name.Name))\n\t\t\t}\n\t\t\tmanualMap[key] = f\n\t\t} else {\n\t\t\t// prevent user error when they don't get the correct conversion signature\n\t\t\tif strings.HasPrefix(f.Name.Name, \"Convert_\") {\n\t\t\t\tklog.Errorf(\"Rename function %s %s -\u003e %s to match expected conversion signature\", f.Name.Package, f.Name.Name, buffer.String())\n\t\t\t}\n\t\t\tklog.V(8).Infof(\"%s has wrong name\", f.Name)\n\t\t}\n\t\tbuffer.Reset()\n\t}\n}","line":{"from":133,"to":199}} {"id":100029898,"name":"Packages","signature":"func Packages(context *generator.Context, arguments *args.GeneratorArgs) generator.Packages","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func Packages(context *generator.Context, arguments *args.GeneratorArgs) generator.Packages {\n\tboilerplate, err := arguments.LoadGoBoilerplate()\n\tif err != nil {\n\t\tklog.Fatalf(\"Failed loading boilerplate: %v\", err)\n\t}\n\n\tpackages := generator.Packages{}\n\theader := append([]byte(fmt.Sprintf(\"// +build !%s\\n\\n\", arguments.GeneratedBuildTag)), boilerplate...)\n\n\t// Accumulate pre-existing conversion functions.\n\t// TODO: This is too ad-hoc. We need a better way.\n\tmanualConversions := conversionFuncMap{}\n\n\t// Record types that are memory equivalent. A type is memory equivalent\n\t// if it has the same memory layout and no nested manual conversion is\n\t// defined.\n\t// TODO: in the future, relax the nested manual conversion requirement\n\t// if we can show that a large enough types are memory identical but\n\t// have non-trivial conversion\n\tmemoryEquivalentTypes := equalMemoryTypes{}\n\n\t// We are generating conversions only for packages that are explicitly\n\t// passed as InputDir.\n\tprocessed := map[string]bool{}\n\tfor _, i := range context.Inputs {\n\t\t// skip duplicates\n\t\tif processed[i] {\n\t\t\tcontinue\n\t\t}\n\t\tprocessed[i] = true\n\n\t\tklog.V(5).Infof(\"considering pkg %q\", i)\n\t\tpkg := context.Universe[i]\n\t\t// typesPkg is where the versioned types are defined. Sometimes it is\n\t\t// different from pkg. For example, kubernetes core/v1 types are defined\n\t\t// in vendor/k8s.io/api/core/v1, while pkg is at pkg/api/v1.\n\t\ttypesPkg := pkg\n\t\tif pkg == nil {\n\t\t\t// If the input had no Go files, for example.\n\t\t\tcontinue\n\t\t}\n\n\t\t// Add conversion and defaulting functions.\n\t\tgetManualConversionFunctions(context, pkg, manualConversions)\n\n\t\t// Only generate conversions for packages which explicitly request it\n\t\t// by specifying one or more \"+k8s:conversion-gen=\u003cpeer-pkg\u003e\"\n\t\t// in their doc.go file.\n\t\tpeerPkgs := extractTag(pkg.Comments)\n\t\tif peerPkgs != nil {\n\t\t\tklog.V(5).Infof(\" tags: %q\", peerPkgs)\n\t\t\tif len(peerPkgs) == 1 \u0026\u0026 peerPkgs[0] == \"false\" {\n\t\t\t\t// If a single +k8s:conversion-gen=false tag is defined, we still want\n\t\t\t\t// the generator to fire for this package for explicit conversions, but\n\t\t\t\t// we are clearing the peerPkgs to not generate any standard conversions.\n\t\t\t\tpeerPkgs = nil\n\t\t\t}\n\t\t} else {\n\t\t\tklog.V(5).Infof(\" no tag\")\n\t\t\tcontinue\n\t\t}\n\t\tskipUnsafe := false\n\t\textraDirs := []string{}\n\t\tif customArgs, ok := arguments.CustomArgs.(*conversionargs.CustomArgs); ok {\n\t\t\tif len(peerPkgs) \u003e 0 {\n\t\t\t\tpeerPkgs = append(peerPkgs, customArgs.BasePeerDirs...)\n\t\t\t\tpeerPkgs = append(peerPkgs, customArgs.ExtraPeerDirs...)\n\t\t\t}\n\t\t\textraDirs = customArgs.ExtraDirs\n\t\t\tskipUnsafe = customArgs.SkipUnsafe\n\t\t}\n\n\t\t// if the external types are not in the same package where the conversion functions to be generated\n\t\texternalTypesValues := extractExternalTypesTag(pkg.Comments)\n\t\tif externalTypesValues != nil {\n\t\t\tif len(externalTypesValues) != 1 {\n\t\t\t\tklog.Fatalf(\" expect only one value for %q tag, got: %q\", externalTypesTagName, externalTypesValues)\n\t\t\t}\n\t\t\texternalTypes := externalTypesValues[0]\n\t\t\tklog.V(5).Infof(\" external types tags: %q\", externalTypes)\n\t\t\tvar err error\n\t\t\ttypesPkg, err = context.AddDirectory(externalTypes)\n\t\t\tif err != nil {\n\t\t\t\tklog.Fatalf(\"cannot import package %s\", externalTypes)\n\t\t\t}\n\t\t\t// update context.Order to the latest context.Universe\n\t\t\torderer := namer.Orderer{Namer: namer.NewPublicNamer(1)}\n\t\t\tcontext.Order = orderer.OrderUniverse(context.Universe)\n\t\t}\n\n\t\t// if the source path is within a /vendor/ directory (for example,\n\t\t// k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/apis/meta/v1), allow\n\t\t// generation to output to the proper relative path (under vendor).\n\t\t// Otherwise, the generator will create the file in the wrong location\n\t\t// in the output directory.\n\t\t// TODO: build a more fundamental concept in gengo for dealing with modifications\n\t\t// to vendored packages.\n\t\tfor i := range peerPkgs {\n\t\t\tpeerPkgs[i] = genutil.Vendorless(peerPkgs[i])\n\t\t}\n\t\tfor i := range extraDirs {\n\t\t\textraDirs[i] = genutil.Vendorless(extraDirs[i])\n\t\t}\n\n\t\t// Make sure our peer-packages are added and fully parsed.\n\t\tfor _, pp := range append(peerPkgs, extraDirs...) {\n\t\t\tcontext.AddDir(pp)\n\t\t\tp := context.Universe[pp]\n\t\t\tif nil == p {\n\t\t\t\tklog.Fatalf(\"failed to find pkg: %s\", pp)\n\t\t\t}\n\t\t\tgetManualConversionFunctions(context, p, manualConversions)\n\t\t}\n\n\t\tunsafeEquality := TypesEqual(memoryEquivalentTypes)\n\t\tif skipUnsafe {\n\t\t\tunsafeEquality = noEquality{}\n\t\t}\n\n\t\tpath := pkg.Path\n\t\t// if the source path is within a /vendor/ directory (for example,\n\t\t// k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/apis/meta/v1), allow\n\t\t// generation to output to the proper relative path (under vendor).\n\t\t// Otherwise, the generator will create the file in the wrong location\n\t\t// in the output directory.\n\t\t// TODO: build a more fundamental concept in gengo for dealing with modifications\n\t\t// to vendored packages.\n\t\tif strings.HasPrefix(pkg.SourcePath, arguments.OutputBase) {\n\t\t\texpandedPath := strings.TrimPrefix(pkg.SourcePath, arguments.OutputBase)\n\t\t\tif strings.Contains(expandedPath, \"/vendor/\") {\n\t\t\t\tpath = expandedPath\n\t\t\t}\n\t\t}\n\t\tpackages = append(packages,\n\t\t\t\u0026generator.DefaultPackage{\n\t\t\t\tPackageName: filepath.Base(pkg.Path),\n\t\t\t\tPackagePath: path,\n\t\t\t\tHeaderText: header,\n\t\t\t\tGeneratorFunc: func(c *generator.Context) (generators []generator.Generator) {\n\t\t\t\t\treturn []generator.Generator{\n\t\t\t\t\t\tNewGenConversion(arguments.OutputFileBaseName, typesPkg.Path, pkg.Path, manualConversions, peerPkgs, unsafeEquality),\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tFilterFunc: func(c *generator.Context, t *types.Type) bool {\n\t\t\t\t\treturn t.Name.Package == typesPkg.Path\n\t\t\t\t},\n\t\t\t})\n\t}\n\n\t// If there is a manual conversion defined between two types, exclude it\n\t// from being a candidate for unsafe conversion\n\tfor k, v := range manualConversions {\n\t\tif isCopyOnly(v.CommentLines) {\n\t\t\tklog.V(5).Infof(\"Conversion function %s will not block memory copy because it is copy-only\", v.Name)\n\t\t\tcontinue\n\t\t}\n\t\t// this type should be excluded from all equivalence, because the converter must be called.\n\t\tmemoryEquivalentTypes.Skip(k.inType, k.outType)\n\t}\n\n\treturn packages\n}","line":{"from":201,"to":362}} {"id":100029899,"name":"Skip","signature":"func (e equalMemoryTypes) Skip(a, b *types.Type)","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (e equalMemoryTypes) Skip(a, b *types.Type) {\n\te[conversionPair{a, b}] = false\n\te[conversionPair{b, a}] = false\n}","line":{"from":366,"to":369}} {"id":100029900,"name":"Equal","signature":"func (e equalMemoryTypes) Equal(a, b *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (e equalMemoryTypes) Equal(a, b *types.Type) bool {\n\t// alreadyVisitedTypes holds all the types that have already been checked in the structural type recursion.\n\talreadyVisitedTypes := make(map[*types.Type]bool)\n\treturn e.cachingEqual(a, b, alreadyVisitedTypes)\n}","line":{"from":371,"to":375}} {"id":100029901,"name":"cachingEqual","signature":"func (e equalMemoryTypes) cachingEqual(a, b *types.Type, alreadyVisitedTypes map[*types.Type]bool) bool","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (e equalMemoryTypes) cachingEqual(a, b *types.Type, alreadyVisitedTypes map[*types.Type]bool) bool {\n\tif a == b {\n\t\treturn true\n\t}\n\tif equal, ok := e[conversionPair{a, b}]; ok {\n\t\treturn equal\n\t}\n\tif equal, ok := e[conversionPair{b, a}]; ok {\n\t\treturn equal\n\t}\n\tresult := e.equal(a, b, alreadyVisitedTypes)\n\te[conversionPair{a, b}] = result\n\te[conversionPair{b, a}] = result\n\treturn result\n}","line":{"from":377,"to":391}} {"id":100029902,"name":"equal","signature":"func (e equalMemoryTypes) equal(a, b *types.Type, alreadyVisitedTypes map[*types.Type]bool) bool","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (e equalMemoryTypes) equal(a, b *types.Type, alreadyVisitedTypes map[*types.Type]bool) bool {\n\tin, out := unwrapAlias(a), unwrapAlias(b)\n\tswitch {\n\tcase in == out:\n\t\treturn true\n\tcase in.Kind == out.Kind:\n\t\t// if the type exists already, return early to avoid recursion\n\t\tif alreadyVisitedTypes[in] {\n\t\t\treturn true\n\t\t}\n\t\talreadyVisitedTypes[in] = true\n\n\t\tswitch in.Kind {\n\t\tcase types.Struct:\n\t\t\tif len(in.Members) != len(out.Members) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tfor i, inMember := range in.Members {\n\t\t\t\toutMember := out.Members[i]\n\t\t\t\tif !e.cachingEqual(inMember.Type, outMember.Type, alreadyVisitedTypes) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\tcase types.Pointer:\n\t\t\treturn e.cachingEqual(in.Elem, out.Elem, alreadyVisitedTypes)\n\t\tcase types.Map:\n\t\t\treturn e.cachingEqual(in.Key, out.Key, alreadyVisitedTypes) \u0026\u0026 e.cachingEqual(in.Elem, out.Elem, alreadyVisitedTypes)\n\t\tcase types.Slice:\n\t\t\treturn e.cachingEqual(in.Elem, out.Elem, alreadyVisitedTypes)\n\t\tcase types.Interface:\n\t\t\t// TODO: determine whether the interfaces are actually equivalent - for now, they must have the\n\t\t\t// same type.\n\t\t\treturn false\n\t\tcase types.Builtin:\n\t\t\treturn in.Name.Name == out.Name.Name\n\t\t}\n\t}\n\treturn false\n}","line":{"from":393,"to":432}} {"id":100029903,"name":"findMember","signature":"func findMember(t *types.Type, name string) (types.Member, bool)","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func findMember(t *types.Type, name string) (types.Member, bool) {\n\tif t.Kind != types.Struct {\n\t\treturn types.Member{}, false\n\t}\n\tfor _, member := range t.Members {\n\t\tif member.Name == name {\n\t\t\treturn member, true\n\t\t}\n\t}\n\treturn types.Member{}, false\n}","line":{"from":434,"to":444}} {"id":100029904,"name":"unwrapAlias","signature":"func unwrapAlias(in *types.Type) *types.Type","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"// unwrapAlias recurses down aliased types to find the bedrock type.\nfunc unwrapAlias(in *types.Type) *types.Type {\n\tfor in.Kind == types.Alias {\n\t\tin = in.Underlying\n\t}\n\treturn in\n}","line":{"from":446,"to":452}} {"id":100029905,"name":"Equal","signature":"func (noEquality) Equal(_, _ *types.Type) bool { return false }","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (noEquality) Equal(_, _ *types.Type) bool { return false }","line":{"from":461,"to":461}} {"id":100029906,"name":"NewGenConversion","signature":"func NewGenConversion(sanitizedName, typesPackage, outputPackage string, manualConversions conversionFuncMap, peerPkgs []string, useUnsafe TypesEqual) generator.Generator","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func NewGenConversion(sanitizedName, typesPackage, outputPackage string, manualConversions conversionFuncMap, peerPkgs []string, useUnsafe TypesEqual) generator.Generator {\n\treturn \u0026genConversion{\n\t\tDefaultGen: generator.DefaultGen{\n\t\t\tOptionalName: sanitizedName,\n\t\t},\n\t\ttypesPackage: typesPackage,\n\t\toutputPackage: outputPackage,\n\t\tpeerPackages: peerPkgs,\n\t\tmanualConversions: manualConversions,\n\t\timports: generator.NewImportTracker(),\n\t\ttypes: []*types.Type{},\n\t\texplicitConversions: []conversionPair{},\n\t\tskippedFields: map[*types.Type][]string{},\n\t\tuseUnsafe: useUnsafe,\n\t}\n}","line":{"from":485,"to":500}} {"id":100029907,"name":"Namers","signature":"func (g *genConversion) Namers(c *generator.Context) namer.NameSystems","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (g *genConversion) Namers(c *generator.Context) namer.NameSystems {\n\t// Have the raw namer for this file track what it imports.\n\treturn namer.NameSystems{\n\t\t\"raw\": namer.NewRawNamer(g.outputPackage, g.imports),\n\t\t\"publicIT\": \u0026namerPlusImportTracking{\n\t\t\tdelegate: conversionNamer(),\n\t\t\ttracker: g.imports,\n\t\t},\n\t}\n}","line":{"from":502,"to":511}} {"id":100029908,"name":"Name","signature":"func (n *namerPlusImportTracking) Name(t *types.Type) string","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (n *namerPlusImportTracking) Name(t *types.Type) string {\n\tn.tracker.AddType(t)\n\treturn n.delegate.Name(t)\n}","line":{"from":518,"to":521}} {"id":100029909,"name":"convertibleOnlyWithinPackage","signature":"func (g *genConversion) convertibleOnlyWithinPackage(inType, outType *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (g *genConversion) convertibleOnlyWithinPackage(inType, outType *types.Type) bool {\n\tvar t *types.Type\n\tvar other *types.Type\n\tif inType.Name.Package == g.typesPackage {\n\t\tt, other = inType, outType\n\t} else {\n\t\tt, other = outType, inType\n\t}\n\n\tif t.Name.Package != g.typesPackage {\n\t\treturn false\n\t}\n\t// If the type has opted out, skip it.\n\ttagvals := extractTag(t.CommentLines)\n\tif tagvals != nil {\n\t\tif tagvals[0] != \"false\" {\n\t\t\tklog.Fatalf(\"Type %v: unsupported %s value: %q\", t, tagName, tagvals[0])\n\t\t}\n\t\tklog.V(5).Infof(\"type %v requests no conversion generation, skipping\", t)\n\t\treturn false\n\t}\n\t// TODO: Consider generating functions for other kinds too.\n\tif t.Kind != types.Struct {\n\t\treturn false\n\t}\n\t// Also, filter out private types.\n\tif namer.IsPrivateGoName(other.Name.Name) {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":523,"to":553}} {"id":100029910,"name":"getExplicitFromTypes","signature":"func getExplicitFromTypes(t *types.Type) []types.Name","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func getExplicitFromTypes(t *types.Type) []types.Name {\n\tcomments := append(t.SecondClosestCommentLines, t.CommentLines...)\n\tpaths := extractExplicitFromTag(comments)\n\tresult := []types.Name{}\n\tfor _, path := range paths {\n\t\titems := strings.Split(path, \".\")\n\t\tif len(items) != 2 {\n\t\t\tklog.Errorf(\"Unexpected k8s:conversion-gen:explicit-from tag: %s\", path)\n\t\t\tcontinue\n\t\t}\n\t\tswitch {\n\t\tcase items[0] == \"net/url\" \u0026\u0026 items[1] == \"Values\":\n\t\tdefault:\n\t\t\tklog.Fatalf(\"Not supported k8s:conversion-gen:explicit-from tag: %s\", path)\n\t\t}\n\t\tresult = append(result, types.Name{Package: items[0], Name: items[1]})\n\t}\n\treturn result\n}","line":{"from":555,"to":573}} {"id":100029911,"name":"Filter","signature":"func (g *genConversion) Filter(c *generator.Context, t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (g *genConversion) Filter(c *generator.Context, t *types.Type) bool {\n\tconvertibleWithPeer := func() bool {\n\t\tpeerType := getPeerTypeFor(c, t, g.peerPackages)\n\t\tif peerType == nil {\n\t\t\treturn false\n\t\t}\n\t\tif !g.convertibleOnlyWithinPackage(t, peerType) {\n\t\t\treturn false\n\t\t}\n\t\tg.types = append(g.types, t)\n\t\treturn true\n\t}()\n\n\texplicitlyConvertible := func() bool {\n\t\tinTypes := getExplicitFromTypes(t)\n\t\tif len(inTypes) == 0 {\n\t\t\treturn false\n\t\t}\n\t\tfor i := range inTypes {\n\t\t\tpair := conversionPair{\n\t\t\t\tinType: \u0026types.Type{Name: inTypes[i]},\n\t\t\t\toutType: t,\n\t\t\t}\n\t\t\tg.explicitConversions = append(g.explicitConversions, pair)\n\t\t}\n\t\treturn true\n\t}()\n\n\treturn convertibleWithPeer || explicitlyConvertible\n}","line":{"from":575,"to":604}} {"id":100029912,"name":"isOtherPackage","signature":"func (g *genConversion) isOtherPackage(pkg string) bool","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (g *genConversion) isOtherPackage(pkg string) bool {\n\tif pkg == g.outputPackage {\n\t\treturn false\n\t}\n\tif strings.HasSuffix(pkg, `\"`+g.outputPackage+`\"`) {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":606,"to":614}} {"id":100029913,"name":"Imports","signature":"func (g *genConversion) Imports(c *generator.Context) (imports []string)","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (g *genConversion) Imports(c *generator.Context) (imports []string) {\n\tvar importLines []string\n\tfor _, singleImport := range g.imports.ImportLines() {\n\t\tif g.isOtherPackage(singleImport) {\n\t\t\timportLines = append(importLines, singleImport)\n\t\t}\n\t}\n\treturn importLines\n}","line":{"from":616,"to":624}} {"id":100029914,"name":"argsFromType","signature":"func argsFromType(inType, outType *types.Type) generator.Args","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func argsFromType(inType, outType *types.Type) generator.Args {\n\treturn generator.Args{\n\t\t\"inType\": inType,\n\t\t\"outType\": outType,\n\t}\n}","line":{"from":626,"to":631}} {"id":100029915,"name":"preexists","signature":"func (g *genConversion) preexists(inType, outType *types.Type) (*types.Type, bool)","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (g *genConversion) preexists(inType, outType *types.Type) (*types.Type, bool) {\n\tfunction, ok := g.manualConversions[conversionPair{inType, outType}]\n\treturn function, ok\n}","line":{"from":635,"to":638}} {"id":100029916,"name":"Init","signature":"func (g *genConversion) Init(c *generator.Context, w io.Writer) error","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (g *genConversion) Init(c *generator.Context, w io.Writer) error {\n\tklogV := klog.V(5)\n\tif klogV.Enabled() {\n\t\tif m, ok := g.useUnsafe.(equalMemoryTypes); ok {\n\t\t\tvar result []string\n\t\t\tklogV.Info(\"All objects without identical memory layout:\")\n\t\t\tfor k, v := range m {\n\t\t\t\tif v {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tresult = append(result, fmt.Sprintf(\" %s -\u003e %s = %t\", k.inType, k.outType, v))\n\t\t\t}\n\t\t\tsort.Strings(result)\n\t\t\tfor _, s := range result {\n\t\t\t\tklogV.Info(s)\n\t\t\t}\n\t\t}\n\t}\n\tsw := generator.NewSnippetWriter(w, c, \"$\", \"$\")\n\tsw.Do(\"func init() {\\n\", nil)\n\tsw.Do(\"localSchemeBuilder.Register(RegisterConversions)\\n\", nil)\n\tsw.Do(\"}\\n\", nil)\n\n\tscheme := c.Universe.Type(types.Name{Package: runtimePackagePath, Name: \"Scheme\"})\n\tschemePtr := \u0026types.Type{\n\t\tKind: types.Pointer,\n\t\tElem: scheme,\n\t}\n\tsw.Do(\"// RegisterConversions adds conversion functions to the given scheme.\\n\", nil)\n\tsw.Do(\"// Public to allow building arbitrary schemes.\\n\", nil)\n\tsw.Do(\"func RegisterConversions(s $.|raw$) error {\\n\", schemePtr)\n\tfor _, t := range g.types {\n\t\tpeerType := getPeerTypeFor(c, t, g.peerPackages)\n\t\tif _, found := g.preexists(t, peerType); !found {\n\t\t\targs := argsFromType(t, peerType).With(\"Scope\", types.Ref(conversionPackagePath, \"Scope\"))\n\t\t\tsw.Do(\"if err := s.AddGeneratedConversionFunc((*$.inType|raw$)(nil), (*$.outType|raw$)(nil), func(a, b interface{}, scope $.Scope|raw$) error { return \"+nameTmpl+\"(a.(*$.inType|raw$), b.(*$.outType|raw$), scope) }); err != nil { return err }\\n\", args)\n\t\t}\n\t\tif _, found := g.preexists(peerType, t); !found {\n\t\t\targs := argsFromType(peerType, t).With(\"Scope\", types.Ref(conversionPackagePath, \"Scope\"))\n\t\t\tsw.Do(\"if err := s.AddGeneratedConversionFunc((*$.inType|raw$)(nil), (*$.outType|raw$)(nil), func(a, b interface{}, scope $.Scope|raw$) error { return \"+nameTmpl+\"(a.(*$.inType|raw$), b.(*$.outType|raw$), scope) }); err != nil { return err }\\n\", args)\n\t\t}\n\t}\n\n\tfor i := range g.explicitConversions {\n\t\targs := argsFromType(g.explicitConversions[i].inType, g.explicitConversions[i].outType).With(\"Scope\", types.Ref(conversionPackagePath, \"Scope\"))\n\t\tsw.Do(\"if err := s.AddGeneratedConversionFunc((*$.inType|raw$)(nil), (*$.outType|raw$)(nil), func(a, b interface{}, scope $.Scope|raw$) error { return \"+nameTmpl+\"(a.(*$.inType|raw$), b.(*$.outType|raw$), scope) }); err != nil { return err }\\n\", args)\n\t}\n\n\tvar pairs []conversionPair\n\tfor pair, t := range g.manualConversions {\n\t\tif t.Name.Package != g.outputPackage {\n\t\t\tcontinue\n\t\t}\n\t\tpairs = append(pairs, pair)\n\t}\n\t// sort by name of the conversion function\n\tsort.Slice(pairs, func(i, j int) bool {\n\t\tif g.manualConversions[pairs[i]].Name.Name \u003c g.manualConversions[pairs[j]].Name.Name {\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t})\n\tfor _, pair := range pairs {\n\t\targs := argsFromType(pair.inType, pair.outType).With(\"Scope\", types.Ref(conversionPackagePath, \"Scope\")).With(\"fn\", g.manualConversions[pair])\n\t\tsw.Do(\"if err := s.AddConversionFunc((*$.inType|raw$)(nil), (*$.outType|raw$)(nil), func(a, b interface{}, scope $.Scope|raw$) error { return $.fn|raw$(a.(*$.inType|raw$), b.(*$.outType|raw$), scope) }); err != nil { return err }\\n\", args)\n\t}\n\n\tsw.Do(\"return nil\\n\", nil)\n\tsw.Do(\"}\\n\\n\", nil)\n\treturn sw.Error()\n}","line":{"from":640,"to":710}} {"id":100029917,"name":"GenerateType","signature":"func (g *genConversion) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (g *genConversion) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {\n\tklog.V(5).Infof(\"generating for type %v\", t)\n\tsw := generator.NewSnippetWriter(w, c, \"$\", \"$\")\n\n\tif peerType := getPeerTypeFor(c, t, g.peerPackages); peerType != nil {\n\t\tg.generateConversion(t, peerType, sw)\n\t\tg.generateConversion(peerType, t, sw)\n\t}\n\n\tfor _, inTypeName := range getExplicitFromTypes(t) {\n\t\tinPkg, ok := c.Universe[inTypeName.Package]\n\t\tif !ok {\n\t\t\tklog.Errorf(\"Unrecognized package: %s\", inTypeName.Package)\n\t\t\tcontinue\n\t\t}\n\t\tinType, ok := inPkg.Types[inTypeName.Name]\n\t\tif !ok {\n\t\t\tklog.Errorf(\"Unrecognized type in package %s: %s\", inTypeName.Package, inTypeName.Name)\n\t\t\tcontinue\n\t\t}\n\t\tswitch {\n\t\tcase inType.Name.Package == \"net/url\" \u0026\u0026 inType.Name.Name == \"Values\":\n\t\t\tg.generateFromUrlValues(inType, t, sw)\n\t\tdefault:\n\t\t\tklog.Errorf(\"Not supported input type: %#v\", inType.Name)\n\t\t}\n\t}\n\n\treturn sw.Error()\n}","line":{"from":712,"to":741}} {"id":100029918,"name":"generateConversion","signature":"func (g *genConversion) generateConversion(inType, outType *types.Type, sw *generator.SnippetWriter)","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (g *genConversion) generateConversion(inType, outType *types.Type, sw *generator.SnippetWriter) {\n\targs := argsFromType(inType, outType).\n\t\tWith(\"Scope\", types.Ref(conversionPackagePath, \"Scope\"))\n\n\tsw.Do(\"func auto\"+nameTmpl+\"(in *$.inType|raw$, out *$.outType|raw$, s $.Scope|raw$) error {\\n\", args)\n\tg.generateFor(inType, outType, sw)\n\tsw.Do(\"return nil\\n\", nil)\n\tsw.Do(\"}\\n\\n\", nil)\n\n\tif _, found := g.preexists(inType, outType); found {\n\t\t// There is a public manual Conversion method: use it.\n\t} else if skipped := g.skippedFields[inType]; len(skipped) != 0 {\n\t\t// The inType had some fields we could not generate.\n\t\tklog.Errorf(\"Warning: could not find nor generate a final Conversion function for %v -\u003e %v\", inType, outType)\n\t\tklog.Errorf(\" the following fields need manual conversion:\")\n\t\tfor _, f := range skipped {\n\t\t\tklog.Errorf(\" - %v\", f)\n\t\t}\n\t} else {\n\t\t// Emit a public conversion function.\n\t\tsw.Do(\"// \"+nameTmpl+\" is an autogenerated conversion function.\\n\", args)\n\t\tsw.Do(\"func \"+nameTmpl+\"(in *$.inType|raw$, out *$.outType|raw$, s $.Scope|raw$) error {\\n\", args)\n\t\tsw.Do(\"return auto\"+nameTmpl+\"(in, out, s)\\n\", args)\n\t\tsw.Do(\"}\\n\\n\", nil)\n\t}\n}","line":{"from":743,"to":768}} {"id":100029919,"name":"generateFor","signature":"func (g *genConversion) generateFor(inType, outType *types.Type, sw *generator.SnippetWriter)","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"// we use the system of shadowing 'in' and 'out' so that the same code is valid\n// at any nesting level. This makes the autogenerator easy to understand, and\n// the compiler shouldn't care.\nfunc (g *genConversion) generateFor(inType, outType *types.Type, sw *generator.SnippetWriter) {\n\tklog.V(5).Infof(\"generating %v -\u003e %v\", inType, outType)\n\tvar f func(*types.Type, *types.Type, *generator.SnippetWriter)\n\n\tswitch inType.Kind {\n\tcase types.Builtin:\n\t\tf = g.doBuiltin\n\tcase types.Map:\n\t\tf = g.doMap\n\tcase types.Slice:\n\t\tf = g.doSlice\n\tcase types.Struct:\n\t\tf = g.doStruct\n\tcase types.Pointer:\n\t\tf = g.doPointer\n\tcase types.Alias:\n\t\tf = g.doAlias\n\tdefault:\n\t\tf = g.doUnknown\n\t}\n\n\tf(inType, outType, sw)\n}","line":{"from":770,"to":795}} {"id":100029920,"name":"doBuiltin","signature":"func (g *genConversion) doBuiltin(inType, outType *types.Type, sw *generator.SnippetWriter)","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (g *genConversion) doBuiltin(inType, outType *types.Type, sw *generator.SnippetWriter) {\n\tif inType == outType {\n\t\tsw.Do(\"*out = *in\\n\", nil)\n\t} else {\n\t\tsw.Do(\"*out = $.|raw$(*in)\\n\", outType)\n\t}\n}","line":{"from":797,"to":803}} {"id":100029921,"name":"doMap","signature":"func (g *genConversion) doMap(inType, outType *types.Type, sw *generator.SnippetWriter)","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (g *genConversion) doMap(inType, outType *types.Type, sw *generator.SnippetWriter) {\n\tsw.Do(\"*out = make($.|raw$, len(*in))\\n\", outType)\n\tif isDirectlyAssignable(inType.Key, outType.Key) {\n\t\tsw.Do(\"for key, val := range *in {\\n\", nil)\n\t\tif isDirectlyAssignable(inType.Elem, outType.Elem) {\n\t\t\tif inType.Key == outType.Key {\n\t\t\t\tsw.Do(\"(*out)[key] = \", nil)\n\t\t\t} else {\n\t\t\t\tsw.Do(\"(*out)[$.|raw$(key)] = \", outType.Key)\n\t\t\t}\n\t\t\tif inType.Elem == outType.Elem {\n\t\t\t\tsw.Do(\"val\\n\", nil)\n\t\t\t} else {\n\t\t\t\tsw.Do(\"$.|raw$(val)\\n\", outType.Elem)\n\t\t\t}\n\t\t} else {\n\t\t\tconversionExists := true\n\t\t\tif function, ok := g.preexists(inType.Elem, outType.Elem); ok {\n\t\t\t\tsw.Do(\"newVal := new($.|raw$)\\n\", outType.Elem)\n\t\t\t\tsw.Do(\"if err := $.|raw$(\u0026val, newVal, s); err != nil {\\n\", function)\n\t\t\t} else if g.convertibleOnlyWithinPackage(inType.Elem, outType.Elem) {\n\t\t\t\tsw.Do(\"newVal := new($.|raw$)\\n\", outType.Elem)\n\t\t\t\tsw.Do(\"if err := \"+nameTmpl+\"(\u0026val, newVal, s); err != nil {\\n\", argsFromType(inType.Elem, outType.Elem))\n\t\t\t} else {\n\t\t\t\targs := argsFromType(inType.Elem, outType.Elem)\n\t\t\t\tsw.Do(\"// FIXME: Provide conversion function to convert $.inType|raw$ to $.outType|raw$\\n\", args)\n\t\t\t\tsw.Do(\"compileErrorOnMissingConversion()\\n\", nil)\n\t\t\t\tconversionExists = false\n\t\t\t}\n\t\t\tif conversionExists {\n\t\t\t\tsw.Do(\"return err\\n\", nil)\n\t\t\t\tsw.Do(\"}\\n\", nil)\n\t\t\t\tif inType.Key == outType.Key {\n\t\t\t\t\tsw.Do(\"(*out)[key] = *newVal\\n\", nil)\n\t\t\t\t} else {\n\t\t\t\t\tsw.Do(\"(*out)[$.|raw$(key)] = *newVal\\n\", outType.Key)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// TODO: Implement it when necessary.\n\t\tsw.Do(\"for range *in {\\n\", nil)\n\t\tsw.Do(\"// FIXME: Converting unassignable keys unsupported $.|raw$\\n\", inType.Key)\n\t}\n\tsw.Do(\"}\\n\", nil)\n}","line":{"from":805,"to":850}} {"id":100029922,"name":"doSlice","signature":"func (g *genConversion) doSlice(inType, outType *types.Type, sw *generator.SnippetWriter)","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (g *genConversion) doSlice(inType, outType *types.Type, sw *generator.SnippetWriter) {\n\tsw.Do(\"*out = make($.|raw$, len(*in))\\n\", outType)\n\tif inType.Elem == outType.Elem \u0026\u0026 inType.Elem.Kind == types.Builtin {\n\t\tsw.Do(\"copy(*out, *in)\\n\", nil)\n\t} else {\n\t\tsw.Do(\"for i := range *in {\\n\", nil)\n\t\tif isDirectlyAssignable(inType.Elem, outType.Elem) {\n\t\t\tif inType.Elem == outType.Elem {\n\t\t\t\tsw.Do(\"(*out)[i] = (*in)[i]\\n\", nil)\n\t\t\t} else {\n\t\t\t\tsw.Do(\"(*out)[i] = $.|raw$((*in)[i])\\n\", outType.Elem)\n\t\t\t}\n\t\t} else {\n\t\t\tconversionExists := true\n\t\t\tif function, ok := g.preexists(inType.Elem, outType.Elem); ok {\n\t\t\t\tsw.Do(\"if err := $.|raw$(\u0026(*in)[i], \u0026(*out)[i], s); err != nil {\\n\", function)\n\t\t\t} else if g.convertibleOnlyWithinPackage(inType.Elem, outType.Elem) {\n\t\t\t\tsw.Do(\"if err := \"+nameTmpl+\"(\u0026(*in)[i], \u0026(*out)[i], s); err != nil {\\n\", argsFromType(inType.Elem, outType.Elem))\n\t\t\t} else {\n\t\t\t\targs := argsFromType(inType.Elem, outType.Elem)\n\t\t\t\tsw.Do(\"// FIXME: Provide conversion function to convert $.inType|raw$ to $.outType|raw$\\n\", args)\n\t\t\t\tsw.Do(\"compileErrorOnMissingConversion()\\n\", nil)\n\t\t\t\tconversionExists = false\n\t\t\t}\n\t\t\tif conversionExists {\n\t\t\t\tsw.Do(\"return err\\n\", nil)\n\t\t\t\tsw.Do(\"}\\n\", nil)\n\t\t\t}\n\t\t}\n\t\tsw.Do(\"}\\n\", nil)\n\t}\n}","line":{"from":852,"to":883}} {"id":100029923,"name":"doStruct","signature":"func (g *genConversion) doStruct(inType, outType *types.Type, sw *generator.SnippetWriter)","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (g *genConversion) doStruct(inType, outType *types.Type, sw *generator.SnippetWriter) {\n\tfor _, inMember := range inType.Members {\n\t\tif tagvals := extractTag(inMember.CommentLines); tagvals != nil \u0026\u0026 tagvals[0] == \"false\" {\n\t\t\t// This field is excluded from conversion.\n\t\t\tsw.Do(\"// INFO: in.\"+inMember.Name+\" opted out of conversion generation\\n\", nil)\n\t\t\tcontinue\n\t\t}\n\t\toutMember, found := findMember(outType, inMember.Name)\n\t\tif !found {\n\t\t\t// This field doesn't exist in the peer.\n\t\t\tsw.Do(\"// WARNING: in.\"+inMember.Name+\" requires manual conversion: does not exist in peer-type\\n\", nil)\n\t\t\tg.skippedFields[inType] = append(g.skippedFields[inType], inMember.Name)\n\t\t\tcontinue\n\t\t}\n\n\t\tinMemberType, outMemberType := inMember.Type, outMember.Type\n\t\t// create a copy of both underlying types but give them the top level alias name (since aliases\n\t\t// are assignable)\n\t\tif underlying := unwrapAlias(inMemberType); underlying != inMemberType {\n\t\t\tcopied := *underlying\n\t\t\tcopied.Name = inMemberType.Name\n\t\t\tinMemberType = \u0026copied\n\t\t}\n\t\tif underlying := unwrapAlias(outMemberType); underlying != outMemberType {\n\t\t\tcopied := *underlying\n\t\t\tcopied.Name = outMemberType.Name\n\t\t\toutMemberType = \u0026copied\n\t\t}\n\n\t\targs := argsFromType(inMemberType, outMemberType).With(\"name\", inMember.Name)\n\n\t\t// try a direct memory copy for any type that has exactly equivalent values\n\t\tif g.useUnsafe.Equal(inMemberType, outMemberType) {\n\t\t\targs = args.\n\t\t\t\tWith(\"Pointer\", types.Ref(\"unsafe\", \"Pointer\")).\n\t\t\t\tWith(\"SliceHeader\", types.Ref(\"reflect\", \"SliceHeader\"))\n\t\t\tswitch inMemberType.Kind {\n\t\t\tcase types.Pointer:\n\t\t\t\tsw.Do(\"out.$.name$ = ($.outType|raw$)($.Pointer|raw$(in.$.name$))\\n\", args)\n\t\t\t\tcontinue\n\t\t\tcase types.Map:\n\t\t\t\tsw.Do(\"out.$.name$ = *(*$.outType|raw$)($.Pointer|raw$(\u0026in.$.name$))\\n\", args)\n\t\t\t\tcontinue\n\t\t\tcase types.Slice:\n\t\t\t\tsw.Do(\"out.$.name$ = *(*$.outType|raw$)($.Pointer|raw$(\u0026in.$.name$))\\n\", args)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\t// check based on the top level name, not the underlying names\n\t\tif function, ok := g.preexists(inMember.Type, outMember.Type); ok {\n\t\t\tif isDrop(function.CommentLines) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// copy-only functions that are directly assignable can be inlined instead of invoked.\n\t\t\t// As an example, conversion functions exist that allow types with private fields to be\n\t\t\t// correctly copied between types. These functions are equivalent to a memory assignment,\n\t\t\t// and are necessary for the reflection path, but should not block memory conversion.\n\t\t\t// Convert_unversioned_Time_to_unversioned_Time is an example of this logic.\n\t\t\tif !isCopyOnly(function.CommentLines) || !g.isFastConversion(inMemberType, outMemberType) {\n\t\t\t\targs[\"function\"] = function\n\t\t\t\tsw.Do(\"if err := $.function|raw$(\u0026in.$.name$, \u0026out.$.name$, s); err != nil {\\n\", args)\n\t\t\t\tsw.Do(\"return err\\n\", nil)\n\t\t\t\tsw.Do(\"}\\n\", nil)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tklog.V(5).Infof(\"Skipped function %s because it is copy-only and we can use direct assignment\", function.Name)\n\t\t}\n\n\t\t// If we can't auto-convert, punt before we emit any code.\n\t\tif inMemberType.Kind != outMemberType.Kind {\n\t\t\tsw.Do(\"// WARNING: in.\"+inMember.Name+\" requires manual conversion: inconvertible types (\"+\n\t\t\t\tinMemberType.String()+\" vs \"+outMemberType.String()+\")\\n\", nil)\n\t\t\tg.skippedFields[inType] = append(g.skippedFields[inType], inMember.Name)\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch inMemberType.Kind {\n\t\tcase types.Builtin:\n\t\t\tif inMemberType == outMemberType {\n\t\t\t\tsw.Do(\"out.$.name$ = in.$.name$\\n\", args)\n\t\t\t} else {\n\t\t\t\tsw.Do(\"out.$.name$ = $.outType|raw$(in.$.name$)\\n\", args)\n\t\t\t}\n\t\tcase types.Map, types.Slice, types.Pointer:\n\t\t\tif g.isDirectlyAssignable(inMemberType, outMemberType) {\n\t\t\t\tsw.Do(\"out.$.name$ = in.$.name$\\n\", args)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tsw.Do(\"if in.$.name$ != nil {\\n\", args)\n\t\t\tsw.Do(\"in, out := \u0026in.$.name$, \u0026out.$.name$\\n\", args)\n\t\t\tg.generateFor(inMemberType, outMemberType, sw)\n\t\t\tsw.Do(\"} else {\\n\", nil)\n\t\t\tsw.Do(\"out.$.name$ = nil\\n\", args)\n\t\t\tsw.Do(\"}\\n\", nil)\n\t\tcase types.Struct:\n\t\t\tif g.isDirectlyAssignable(inMemberType, outMemberType) {\n\t\t\t\tsw.Do(\"out.$.name$ = in.$.name$\\n\", args)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconversionExists := true\n\t\t\tif g.convertibleOnlyWithinPackage(inMemberType, outMemberType) {\n\t\t\t\tsw.Do(\"if err := \"+nameTmpl+\"(\u0026in.$.name$, \u0026out.$.name$, s); err != nil {\\n\", args)\n\t\t\t} else {\n\t\t\t\targs := argsFromType(inMemberType, outMemberType)\n\t\t\t\tsw.Do(\"// FIXME: Provide conversion function to convert $.inType|raw$ to $.outType|raw$\\n\", args)\n\t\t\t\tsw.Do(\"compileErrorOnMissingConversion()\\n\", nil)\n\t\t\t\tconversionExists = false\n\t\t\t}\n\t\t\tif conversionExists {\n\t\t\t\tsw.Do(\"return err\\n\", nil)\n\t\t\t\tsw.Do(\"}\\n\", nil)\n\t\t\t}\n\t\tcase types.Alias:\n\t\t\tif isDirectlyAssignable(inMemberType, outMemberType) {\n\t\t\t\tif inMemberType == outMemberType {\n\t\t\t\t\tsw.Do(\"out.$.name$ = in.$.name$\\n\", args)\n\t\t\t\t} else {\n\t\t\t\t\tsw.Do(\"out.$.name$ = $.outType|raw$(in.$.name$)\\n\", args)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconversionExists := true\n\t\t\t\tif g.convertibleOnlyWithinPackage(inMemberType, outMemberType) {\n\t\t\t\t\tsw.Do(\"if err := \"+nameTmpl+\"(\u0026in.$.name$, \u0026out.$.name$, s); err != nil {\\n\", args)\n\t\t\t\t} else {\n\t\t\t\t\targs := argsFromType(inMemberType, outMemberType)\n\t\t\t\t\tsw.Do(\"// FIXME: Provide conversion function to convert $.inType|raw$ to $.outType|raw$\\n\", args)\n\t\t\t\t\tsw.Do(\"compileErrorOnMissingConversion()\\n\", nil)\n\t\t\t\t\tconversionExists = false\n\t\t\t\t}\n\t\t\t\tif conversionExists {\n\t\t\t\t\tsw.Do(\"return err\\n\", nil)\n\t\t\t\t\tsw.Do(\"}\\n\", nil)\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\tconversionExists := true\n\t\t\tif g.convertibleOnlyWithinPackage(inMemberType, outMemberType) {\n\t\t\t\tsw.Do(\"if err := \"+nameTmpl+\"(\u0026in.$.name$, \u0026out.$.name$, s); err != nil {\\n\", args)\n\t\t\t} else {\n\t\t\t\targs := argsFromType(inMemberType, outMemberType)\n\t\t\t\tsw.Do(\"// FIXME: Provide conversion function to convert $.inType|raw$ to $.outType|raw$\\n\", args)\n\t\t\t\tsw.Do(\"compileErrorOnMissingConversion()\\n\", nil)\n\t\t\t\tconversionExists = false\n\t\t\t}\n\t\t\tif conversionExists {\n\t\t\t\tsw.Do(\"return err\\n\", nil)\n\t\t\t\tsw.Do(\"}\\n\", nil)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":885,"to":1037}} {"id":100029924,"name":"isFastConversion","signature":"func (g *genConversion) isFastConversion(inType, outType *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (g *genConversion) isFastConversion(inType, outType *types.Type) bool {\n\tswitch inType.Kind {\n\tcase types.Builtin:\n\t\treturn true\n\tcase types.Map, types.Slice, types.Pointer, types.Struct, types.Alias:\n\t\treturn g.isDirectlyAssignable(inType, outType)\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":1039,"to":1048}} {"id":100029925,"name":"isDirectlyAssignable","signature":"func (g *genConversion) isDirectlyAssignable(inType, outType *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (g *genConversion) isDirectlyAssignable(inType, outType *types.Type) bool {\n\treturn unwrapAlias(inType) == unwrapAlias(outType)\n}","line":{"from":1050,"to":1052}} {"id":100029926,"name":"doPointer","signature":"func (g *genConversion) doPointer(inType, outType *types.Type, sw *generator.SnippetWriter)","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (g *genConversion) doPointer(inType, outType *types.Type, sw *generator.SnippetWriter) {\n\tsw.Do(\"*out = new($.Elem|raw$)\\n\", outType)\n\tif isDirectlyAssignable(inType.Elem, outType.Elem) {\n\t\tif inType.Elem == outType.Elem {\n\t\t\tsw.Do(\"**out = **in\\n\", nil)\n\t\t} else {\n\t\t\tsw.Do(\"**out = $.|raw$(**in)\\n\", outType.Elem)\n\t\t}\n\t} else {\n\t\tconversionExists := true\n\t\tif function, ok := g.preexists(inType.Elem, outType.Elem); ok {\n\t\t\tsw.Do(\"if err := $.|raw$(*in, *out, s); err != nil {\\n\", function)\n\t\t} else if g.convertibleOnlyWithinPackage(inType.Elem, outType.Elem) {\n\t\t\tsw.Do(\"if err := \"+nameTmpl+\"(*in, *out, s); err != nil {\\n\", argsFromType(inType.Elem, outType.Elem))\n\t\t} else {\n\t\t\targs := argsFromType(inType.Elem, outType.Elem)\n\t\t\tsw.Do(\"// FIXME: Provide conversion function to convert $.inType|raw$ to $.outType|raw$\\n\", args)\n\t\t\tsw.Do(\"compileErrorOnMissingConversion()\\n\", nil)\n\t\t\tconversionExists = false\n\t\t}\n\t\tif conversionExists {\n\t\t\tsw.Do(\"return err\\n\", nil)\n\t\t\tsw.Do(\"}\\n\", nil)\n\t\t}\n\t}\n}","line":{"from":1054,"to":1079}} {"id":100029927,"name":"doAlias","signature":"func (g *genConversion) doAlias(inType, outType *types.Type, sw *generator.SnippetWriter)","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (g *genConversion) doAlias(inType, outType *types.Type, sw *generator.SnippetWriter) {\n\t// TODO: Add support for aliases.\n\tg.doUnknown(inType, outType, sw)\n}","line":{"from":1081,"to":1084}} {"id":100029928,"name":"doUnknown","signature":"func (g *genConversion) doUnknown(inType, outType *types.Type, sw *generator.SnippetWriter)","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (g *genConversion) doUnknown(inType, outType *types.Type, sw *generator.SnippetWriter) {\n\tsw.Do(\"// FIXME: Type $.|raw$ is unsupported.\\n\", inType)\n}","line":{"from":1086,"to":1088}} {"id":100029929,"name":"generateFromUrlValues","signature":"func (g *genConversion) generateFromUrlValues(inType, outType *types.Type, sw *generator.SnippetWriter)","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (g *genConversion) generateFromUrlValues(inType, outType *types.Type, sw *generator.SnippetWriter) {\n\targs := generator.Args{\n\t\t\"inType\": inType,\n\t\t\"outType\": outType,\n\t\t\"Scope\": types.Ref(conversionPackagePath, \"Scope\"),\n\t}\n\tsw.Do(\"func auto\"+nameTmpl+\"(in *$.inType|raw$, out *$.outType|raw$, s $.Scope|raw$) error {\\n\", args)\n\tfor _, outMember := range outType.Members {\n\t\tif tagvals := extractTag(outMember.CommentLines); tagvals != nil \u0026\u0026 tagvals[0] == \"false\" {\n\t\t\t// This field is excluded from conversion.\n\t\t\tsw.Do(\"// INFO: in.\"+outMember.Name+\" opted out of conversion generation\\n\", nil)\n\t\t\tcontinue\n\t\t}\n\t\tjsonTag := reflect.StructTag(outMember.Tags).Get(\"json\")\n\t\tindex := strings.Index(jsonTag, \",\")\n\t\tif index == -1 {\n\t\t\tindex = len(jsonTag)\n\t\t}\n\t\tif index == 0 {\n\t\t\tmemberArgs := generator.Args{\n\t\t\t\t\"name\": outMember.Name,\n\t\t\t}\n\t\t\tsw.Do(\"// WARNING: Field $.name$ does not have json tag, skipping.\\n\\n\", memberArgs)\n\t\t\tcontinue\n\t\t}\n\t\tmemberArgs := generator.Args{\n\t\t\t\"name\": outMember.Name,\n\t\t\t\"tag\": jsonTag[:index],\n\t\t}\n\t\tsw.Do(\"if values, ok := map[string][]string(*in)[\\\"$.tag$\\\"]; ok \u0026\u0026 len(values) \u003e 0 {\\n\", memberArgs)\n\t\tg.fromValuesEntry(inType.Underlying.Elem, outMember, sw)\n\t\tsw.Do(\"} else {\\n\", nil)\n\t\tg.setZeroValue(outMember, sw)\n\t\tsw.Do(\"}\\n\", nil)\n\t}\n\tsw.Do(\"return nil\\n\", nil)\n\tsw.Do(\"}\\n\\n\", nil)\n\n\tif _, found := g.preexists(inType, outType); found {\n\t\t// There is a public manual Conversion method: use it.\n\t} else {\n\t\t// Emit a public conversion function.\n\t\tsw.Do(\"// \"+nameTmpl+\" is an autogenerated conversion function.\\n\", args)\n\t\tsw.Do(\"func \"+nameTmpl+\"(in *$.inType|raw$, out *$.outType|raw$, s $.Scope|raw$) error {\\n\", args)\n\t\tsw.Do(\"return auto\"+nameTmpl+\"(in, out, s)\\n\", args)\n\t\tsw.Do(\"}\\n\\n\", nil)\n\t}\n}","line":{"from":1090,"to":1137}} {"id":100029930,"name":"fromValuesEntry","signature":"func (g *genConversion) fromValuesEntry(inType *types.Type, outMember types.Member, sw *generator.SnippetWriter)","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (g *genConversion) fromValuesEntry(inType *types.Type, outMember types.Member, sw *generator.SnippetWriter) {\n\tmemberArgs := generator.Args{\n\t\t\"name\": outMember.Name,\n\t\t\"type\": outMember.Type,\n\t}\n\tif function, ok := g.preexists(inType, outMember.Type); ok {\n\t\targs := memberArgs.With(\"function\", function)\n\t\tsw.Do(\"if err := $.function|raw$(\u0026values, \u0026out.$.name$, s); err != nil {\\n\", args)\n\t\tsw.Do(\"return err\\n\", nil)\n\t\tsw.Do(\"}\\n\", nil)\n\t\treturn\n\t}\n\tswitch {\n\tcase outMember.Type == types.String:\n\t\tsw.Do(\"out.$.name$ = values[0]\\n\", memberArgs)\n\tcase g.useUnsafe.Equal(inType, outMember.Type):\n\t\targs := memberArgs.With(\"Pointer\", types.Ref(\"unsafe\", \"Pointer\"))\n\t\tswitch inType.Kind {\n\t\tcase types.Pointer:\n\t\t\tsw.Do(\"out.$.name$ = ($.type|raw$)($.Pointer|raw$(\u0026values))\\n\", args)\n\t\tcase types.Map, types.Slice:\n\t\t\tsw.Do(\"out.$.name$ = *(*$.type|raw$)($.Pointer|raw$(\u0026values))\\n\", args)\n\t\tdefault:\n\t\t\t// TODO: Support other types to allow more auto-conversions.\n\t\t\tsw.Do(\"// FIXME: out.$.name$ is of not yet supported type and requires manual conversion\\n\", memberArgs)\n\t\t}\n\tdefault:\n\t\t// TODO: Support other types to allow more auto-conversions.\n\t\tsw.Do(\"// FIXME: out.$.name$ is of not yet supported type and requires manual conversion\\n\", memberArgs)\n\t}\n}","line":{"from":1139,"to":1169}} {"id":100029931,"name":"setZeroValue","signature":"func (g *genConversion) setZeroValue(outMember types.Member, sw *generator.SnippetWriter)","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func (g *genConversion) setZeroValue(outMember types.Member, sw *generator.SnippetWriter) {\n\toutMemberType := unwrapAlias(outMember.Type)\n\tmemberArgs := generator.Args{\n\t\t\"name\": outMember.Name,\n\t\t\"alias\": outMember.Type,\n\t\t\"type\": outMemberType,\n\t}\n\n\tswitch outMemberType.Kind {\n\tcase types.Builtin:\n\t\tswitch outMemberType {\n\t\tcase types.String:\n\t\t\tsw.Do(\"out.$.name$ = \\\"\\\"\\n\", memberArgs)\n\t\tcase types.Int64, types.Int32, types.Int16, types.Int, types.Uint64, types.Uint32, types.Uint16, types.Uint:\n\t\t\tsw.Do(\"out.$.name$ = 0\\n\", memberArgs)\n\t\tcase types.Uintptr, types.Byte:\n\t\t\tsw.Do(\"out.$.name$ = 0\\n\", memberArgs)\n\t\tcase types.Float64, types.Float32, types.Float:\n\t\t\tsw.Do(\"out.$.name$ = 0\\n\", memberArgs)\n\t\tcase types.Bool:\n\t\t\tsw.Do(\"out.$.name$ = false\\n\", memberArgs)\n\t\tdefault:\n\t\t\tsw.Do(\"// FIXME: out.$.name$ is of unsupported type and requires manual conversion\\n\", memberArgs)\n\t\t}\n\tcase types.Struct:\n\t\tif outMemberType == outMember.Type {\n\t\t\tsw.Do(\"out.$.name$ = $.type|raw${}\\n\", memberArgs)\n\t\t} else {\n\t\t\tsw.Do(\"out.$.name$ = $.alias|raw$($.type|raw${})\\n\", memberArgs)\n\t\t}\n\tcase types.Map, types.Slice, types.Pointer:\n\t\tsw.Do(\"out.$.name$ = nil\\n\", memberArgs)\n\tcase types.Alias:\n\t\t// outMemberType was already unwrapped from aliases - so that should never happen.\n\t\tsw.Do(\"// FIXME: unexpected error for out.$.name$\\n\", memberArgs)\n\tcase types.Interface, types.Array:\n\t\tsw.Do(\"out.$.name$ = nil\\n\", memberArgs)\n\tdefault:\n\t\tsw.Do(\"// FIXME: out.$.name$ is of unsupported type and requires manual conversion\\n\", memberArgs)\n\t}\n}","line":{"from":1171,"to":1211}} {"id":100029932,"name":"isDirectlyAssignable","signature":"func isDirectlyAssignable(inType, outType *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func isDirectlyAssignable(inType, outType *types.Type) bool {\n\t// TODO: This should maybe check for actual assignability between the two\n\t// types, rather than superficial traits that happen to indicate it is\n\t// assignable in the ways we currently use this code.\n\treturn inType.IsAssignable() \u0026\u0026 (inType.IsPrimitive() || isSamePackage(inType, outType))\n}","line":{"from":1213,"to":1218}} {"id":100029933,"name":"isSamePackage","signature":"func isSamePackage(inType, outType *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go","code":"func isSamePackage(inType, outType *types.Type) bool {\n\treturn inType.Name.Package == outType.Name.Package\n}","line":{"from":1220,"to":1222}} {"id":100029934,"name":"main","signature":"func main()","file":"staging/src/k8s.io/code-generator/cmd/conversion-gen/main.go","code":"func main() {\n\tklog.InitFlags(nil)\n\tgenericArgs, customArgs := generatorargs.NewDefaults()\n\n\tgenericArgs.AddFlags(pflag.CommandLine)\n\tcustomArgs.AddFlags(pflag.CommandLine)\n\tflag.Set(\"logtostderr\", \"true\")\n\tpflag.CommandLine.AddGoFlagSet(flag.CommandLine)\n\tpflag.Parse()\n\n\t// k8s.io/apimachinery/pkg/runtime contains a number of manual conversions,\n\t// that we need to generate conversions.\n\t// Packages being dependencies of explicitly requested packages are only\n\t// partially scanned - only types explicitly used are being traversed.\n\t// Not used functions or types are omitted.\n\t// Adding this explicitly to InputDirs ensures that the package is fully\n\t// scanned and all functions are parsed and processed.\n\tgenericArgs.InputDirs = append(genericArgs.InputDirs, \"k8s.io/apimachinery/pkg/runtime\")\n\n\tif err := generatorargs.Validate(genericArgs); err != nil {\n\t\tklog.Fatalf(\"Error: %v\", err)\n\t}\n\n\t// Run it.\n\tif err := genericArgs.Execute(\n\t\tgenerators.NameSystems(),\n\t\tgenerators.DefaultNameSystem(),\n\t\tgenerators.Packages,\n\t); err != nil {\n\t\tklog.Fatalf(\"Error: %v\", err)\n\t}\n\tklog.V(2).Info(\"Completed successfully.\")\n}","line":{"from":107,"to":139}} {"id":100029935,"name":"NewDefaults","signature":"func NewDefaults() (*args.GeneratorArgs, *CustomArgs)","file":"staging/src/k8s.io/code-generator/cmd/deepcopy-gen/args/args.go","code":"// NewDefaults returns default arguments for the generator.\nfunc NewDefaults() (*args.GeneratorArgs, *CustomArgs) {\n\tgenericArgs := args.Default().WithoutDefaultFlagParsing()\n\tcustomArgs := \u0026CustomArgs{}\n\tgenericArgs.CustomArgs = (*generators.CustomArgs)(customArgs) // convert to upstream type to make type-casts work there\n\tgenericArgs.OutputFileBaseName = \"deepcopy_generated\"\n\treturn genericArgs, customArgs\n}","line":{"from":30,"to":37}} {"id":100029936,"name":"AddFlags","signature":"func (ca *CustomArgs) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/code-generator/cmd/deepcopy-gen/args/args.go","code":"// AddFlags add the generator flags to the flag set.\nfunc (ca *CustomArgs) AddFlags(fs *pflag.FlagSet) {\n\tpflag.CommandLine.StringSliceVar(\u0026ca.BoundingDirs, \"bounding-dirs\", ca.BoundingDirs,\n\t\t\"Comma-separated list of import paths which bound the types for which deep-copies will be generated.\")\n}","line":{"from":39,"to":43}} {"id":100029937,"name":"Validate","signature":"func Validate(genericArgs *args.GeneratorArgs) error","file":"staging/src/k8s.io/code-generator/cmd/deepcopy-gen/args/args.go","code":"// Validate checks the given arguments.\nfunc Validate(genericArgs *args.GeneratorArgs) error {\n\t_ = genericArgs.CustomArgs.(*generators.CustomArgs)\n\n\tif len(genericArgs.OutputFileBaseName) == 0 {\n\t\treturn fmt.Errorf(\"output file base name cannot be empty\")\n\t}\n\n\treturn nil\n}","line":{"from":45,"to":54}} {"id":100029938,"name":"main","signature":"func main()","file":"staging/src/k8s.io/code-generator/cmd/deepcopy-gen/main.go","code":"func main() {\n\tklog.InitFlags(nil)\n\tgenericArgs, customArgs := generatorargs.NewDefaults()\n\n\tgenericArgs.AddFlags(pflag.CommandLine)\n\tcustomArgs.AddFlags(pflag.CommandLine)\n\tflag.Set(\"logtostderr\", \"true\")\n\tpflag.CommandLine.AddGoFlagSet(flag.CommandLine)\n\tpflag.Parse()\n\n\tif err := generatorargs.Validate(genericArgs); err != nil {\n\t\tklog.Fatalf(\"Error: %v\", err)\n\t}\n\n\t// Run it.\n\tif err := genericArgs.Execute(\n\t\tgenerators.NameSystems(),\n\t\tgenerators.DefaultNameSystem(),\n\t\tgenerators.Packages,\n\t); err != nil {\n\t\tklog.Fatalf(\"Error: %v\", err)\n\t}\n\tklog.V(2).Info(\"Completed successfully.\")\n}","line":{"from":58,"to":81}} {"id":100029939,"name":"NewDefaults","signature":"func NewDefaults() (*args.GeneratorArgs, *CustomArgs)","file":"staging/src/k8s.io/code-generator/cmd/defaulter-gen/args/args.go","code":"// NewDefaults returns default arguments for the generator.\nfunc NewDefaults() (*args.GeneratorArgs, *CustomArgs) {\n\tgenericArgs := args.Default().WithoutDefaultFlagParsing()\n\tcustomArgs := \u0026CustomArgs{}\n\tgenericArgs.CustomArgs = (*generators.CustomArgs)(customArgs) // convert to upstream type to make type-casts work there\n\tgenericArgs.OutputFileBaseName = \"zz_generated.defaults\"\n\treturn genericArgs, customArgs\n}","line":{"from":30,"to":37}} {"id":100029940,"name":"AddFlags","signature":"func (ca *CustomArgs) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/code-generator/cmd/defaulter-gen/args/args.go","code":"// AddFlags add the generator flags to the flag set.\nfunc (ca *CustomArgs) AddFlags(fs *pflag.FlagSet) {\n\tpflag.CommandLine.StringSliceVar(\u0026ca.ExtraPeerDirs, \"extra-peer-dirs\", ca.ExtraPeerDirs,\n\t\t\"Comma-separated list of import paths which are considered, after tag-specified peers, for conversions.\")\n}","line":{"from":39,"to":43}} {"id":100029941,"name":"Validate","signature":"func Validate(genericArgs *args.GeneratorArgs) error","file":"staging/src/k8s.io/code-generator/cmd/defaulter-gen/args/args.go","code":"// Validate checks the given arguments.\nfunc Validate(genericArgs *args.GeneratorArgs) error {\n\t_ = genericArgs.CustomArgs.(*generators.CustomArgs)\n\n\tif len(genericArgs.OutputFileBaseName) == 0 {\n\t\treturn fmt.Errorf(\"output file base name cannot be empty\")\n\t}\n\n\treturn nil\n}","line":{"from":45,"to":54}} {"id":100029942,"name":"main","signature":"func main()","file":"staging/src/k8s.io/code-generator/cmd/defaulter-gen/main.go","code":"func main() {\n\tklog.InitFlags(nil)\n\tgenericArgs, customArgs := generatorargs.NewDefaults()\n\n\tgenericArgs.AddFlags(pflag.CommandLine)\n\tcustomArgs.AddFlags(pflag.CommandLine)\n\tflag.Set(\"logtostderr\", \"true\")\n\tpflag.CommandLine.AddGoFlagSet(flag.CommandLine)\n\tpflag.Parse()\n\n\tif err := generatorargs.Validate(genericArgs); err != nil {\n\t\tklog.Fatalf(\"Error: %v\", err)\n\t}\n\n\t// Run it.\n\tif err := genericArgs.Execute(\n\t\tgenerators.NameSystems(),\n\t\tgenerators.DefaultNameSystem(),\n\t\tgenerators.Packages,\n\t); err != nil {\n\t\tklog.Fatalf(\"Error: %v\", err)\n\t}\n\tklog.V(2).Info(\"Completed successfully.\")\n}","line":{"from":54,"to":77}} {"id":100029943,"name":"init","signature":"func init()","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/main.go","code":"func init() {\n\tklog.InitFlags(nil)\n\tg.BindFlags(flag.CommandLine)\n\tgoflag.Set(\"logtostderr\", \"true\")\n\tflag.CommandLine.AddGoFlagSet(goflag.CommandLine)\n}","line":{"from":31,"to":36}} {"id":100029944,"name":"main","signature":"func main()","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/main.go","code":"func main() {\n\tflag.Parse()\n\tprotobuf.Run(g)\n}","line":{"from":38,"to":41}} {"id":100029945,"name":"New","signature":"func New() *Generator","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/cmd.go","code":"func New() *Generator {\n\tsourceTree := args.DefaultSourceTree()\n\tcommon := args.GeneratorArgs{\n\t\tOutputBase: sourceTree,\n\t}\n\tdefaultProtoImport := filepath.Join(sourceTree, \"k8s.io\", \"kubernetes\", \"vendor\", \"github.com\", \"gogo\", \"protobuf\", \"protobuf\")\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Fatalf(\"Cannot get current directory.\")\n\t}\n\treturn \u0026Generator{\n\t\tCommon: common,\n\t\tOutputBase: sourceTree,\n\t\tVendorOutputBase: filepath.Join(cwd, \"vendor\"),\n\t\tProtoImport: []string{defaultProtoImport},\n\t\tAPIMachineryPackages: strings.Join([]string{\n\t\t\t`+k8s.io/apimachinery/pkg/util/intstr`,\n\t\t\t`+k8s.io/apimachinery/pkg/api/resource`,\n\t\t\t`+k8s.io/apimachinery/pkg/runtime/schema`,\n\t\t\t`+k8s.io/apimachinery/pkg/runtime`,\n\t\t\t`k8s.io/apimachinery/pkg/apis/meta/v1`,\n\t\t\t`k8s.io/apimachinery/pkg/apis/meta/v1beta1`,\n\t\t\t`k8s.io/apimachinery/pkg/apis/testapigroup/v1`,\n\t\t}, \",\"),\n\t\tPackages: \"\",\n\t\tDropEmbeddedFields: \"k8s.io/apimachinery/pkg/apis/meta/v1.TypeMeta\",\n\t}\n}","line":{"from":56,"to":83}} {"id":100029946,"name":"BindFlags","signature":"func (g *Generator) BindFlags(flag *flag.FlagSet)","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/cmd.go","code":"func (g *Generator) BindFlags(flag *flag.FlagSet) {\n\tflag.StringVarP(\u0026g.Common.GoHeaderFilePath, \"go-header-file\", \"h\", g.Common.GoHeaderFilePath, \"File containing boilerplate header text. The string YEAR will be replaced with the current 4-digit year.\")\n\tflag.BoolVar(\u0026g.Common.VerifyOnly, \"verify-only\", g.Common.VerifyOnly, \"If true, only verify existing output, do not write anything.\")\n\tflag.StringVarP(\u0026g.Packages, \"packages\", \"p\", g.Packages, \"comma-separated list of directories to get input types from. Directories prefixed with '-' are not generated, directories prefixed with '+' only create types with explicit IDL instructions.\")\n\tflag.StringVar(\u0026g.APIMachineryPackages, \"apimachinery-packages\", g.APIMachineryPackages, \"comma-separated list of directories to get apimachinery input types from which are needed by any API. Directories prefixed with '-' are not generated, directories prefixed with '+' only create types with explicit IDL instructions.\")\n\tflag.StringVarP(\u0026g.OutputBase, \"output-base\", \"o\", g.OutputBase, \"Output base; defaults to $GOPATH/src/\")\n\tflag.StringVar(\u0026g.VendorOutputBase, \"vendor-output-base\", g.VendorOutputBase, \"The vendor/ directory to look for packages in; defaults to $PWD/vendor/.\")\n\tflag.StringSliceVar(\u0026g.ProtoImport, \"proto-import\", g.ProtoImport, \"The search path for the core protobuf .protos, required; defaults $GOPATH/src/k8s.io/kubernetes/vendor/github.com/gogo/protobuf/protobuf.\")\n\tflag.StringVar(\u0026g.Conditional, \"conditional\", g.Conditional, \"An optional Golang build tag condition to add to the generated Go code\")\n\tflag.BoolVar(\u0026g.Clean, \"clean\", g.Clean, \"If true, remove all generated files for the specified Packages.\")\n\tflag.BoolVar(\u0026g.OnlyIDL, \"only-idl\", g.OnlyIDL, \"If true, only generate the IDL for each package.\")\n\tflag.BoolVar(\u0026g.KeepGogoproto, \"keep-gogoproto\", g.KeepGogoproto, \"If true, the generated IDL will contain gogoprotobuf extensions which are normally removed\")\n\tflag.BoolVar(\u0026g.SkipGeneratedRewrite, \"skip-generated-rewrite\", g.SkipGeneratedRewrite, \"If true, skip fixing up the generated.pb.go file (debugging only).\")\n\tflag.StringVar(\u0026g.DropEmbeddedFields, \"drop-embedded-fields\", g.DropEmbeddedFields, \"Comma-delimited list of embedded Go types to omit from generated protobufs\")\n\tflag.StringVar(\u0026g.TrimPathPrefix, \"trim-path-prefix\", g.TrimPathPrefix, \"If set, trim the specified prefix from --output-package when generating files.\")\n}","line":{"from":85,"to":100}} {"id":100029947,"name":"Run","signature":"func Run(g *Generator)","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/cmd.go","code":"func Run(g *Generator) {\n\tif g.Common.VerifyOnly {\n\t\tg.OnlyIDL = true\n\t\tg.Clean = false\n\t}\n\n\tb := parser.New()\n\tb.AddBuildTags(\"proto\")\n\n\tomitTypes := map[types.Name]struct{}{}\n\tfor _, t := range strings.Split(g.DropEmbeddedFields, \",\") {\n\t\tname := types.Name{}\n\t\tif i := strings.LastIndex(t, \".\"); i != -1 {\n\t\t\tname.Package, name.Name = t[:i], t[i+1:]\n\t\t} else {\n\t\t\tname.Name = t\n\t\t}\n\t\tif len(name.Name) == 0 {\n\t\t\tlog.Fatalf(\"--drop-embedded-types requires names in the form of [GOPACKAGE.]TYPENAME: %v\", t)\n\t\t}\n\t\tomitTypes[name] = struct{}{}\n\t}\n\n\tboilerplate, err := g.Common.LoadGoBoilerplate()\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed loading boilerplate (consider using the go-header-file flag): %v\", err)\n\t}\n\n\tprotobufNames := NewProtobufNamer()\n\toutputPackages := generator.Packages{}\n\tnonOutputPackages := map[string]struct{}{}\n\n\tvar packages []string\n\tif len(g.APIMachineryPackages) != 0 {\n\t\tpackages = append(packages, strings.Split(g.APIMachineryPackages, \",\")...)\n\t}\n\tif len(g.Packages) != 0 {\n\t\tpackages = append(packages, strings.Split(g.Packages, \",\")...)\n\t}\n\tif len(packages) == 0 {\n\t\tlog.Fatalf(\"Both apimachinery-packages and packages are empty. At least one package must be specified.\")\n\t}\n\n\tfor _, d := range packages {\n\t\tgenerateAllTypes, outputPackage := true, true\n\t\tswitch {\n\t\tcase strings.HasPrefix(d, \"+\"):\n\t\t\td = d[1:]\n\t\t\tgenerateAllTypes = false\n\t\tcase strings.HasPrefix(d, \"-\"):\n\t\t\td = d[1:]\n\t\t\toutputPackage = false\n\t\t}\n\t\tname := protoSafePackage(d)\n\t\tparts := strings.SplitN(d, \"=\", 2)\n\t\tif len(parts) \u003e 1 {\n\t\t\td = parts[0]\n\t\t\tname = parts[1]\n\t\t}\n\t\tp := newProtobufPackage(d, name, generateAllTypes, omitTypes)\n\t\theader := append([]byte{}, boilerplate...)\n\t\theader = append(header, p.HeaderText...)\n\t\tp.HeaderText = header\n\t\tprotobufNames.Add(p)\n\t\tif outputPackage {\n\t\t\toutputPackages = append(outputPackages, p)\n\t\t} else {\n\t\t\tnonOutputPackages[name] = struct{}{}\n\t\t}\n\t}\n\n\tif !g.Common.VerifyOnly {\n\t\tfor _, p := range outputPackages {\n\t\t\tif err := p.(*protobufPackage).Clean(g.OutputBase); err != nil {\n\t\t\t\tlog.Fatalf(\"Unable to clean package %s: %v\", p.Name(), err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif g.Clean {\n\t\treturn\n\t}\n\n\tfor _, p := range protobufNames.List() {\n\t\tif err := b.AddDir(p.Path()); err != nil {\n\t\t\tlog.Fatalf(\"Unable to add directory %q: %v\", p.Path(), err)\n\t\t}\n\t}\n\n\tc, err := generator.NewContext(\n\t\tb,\n\t\tnamer.NameSystems{\n\t\t\t\"public\": namer.NewPublicNamer(3),\n\t\t\t\"proto\": protobufNames,\n\t\t},\n\t\t\"public\",\n\t)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed making a context: %v\", err)\n\t}\n\n\tc.Verify = g.Common.VerifyOnly\n\tc.FileTypes[\"protoidl\"] = NewProtoFile()\n\tc.TrimPathPrefix = g.TrimPathPrefix\n\n\t// order package by imports, importees first\n\tdeps := deps(c, protobufNames.packages)\n\torder, err := importOrder(deps)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to order packages by imports: %v\", err)\n\t}\n\ttopologicalPos := map[string]int{}\n\tfor i, p := range order {\n\t\ttopologicalPos[p] = i\n\t}\n\tsort.Sort(positionOrder{topologicalPos, protobufNames.packages})\n\n\tvar vendoredOutputPackages, localOutputPackages generator.Packages\n\tfor _, p := range protobufNames.packages {\n\t\tif _, ok := nonOutputPackages[p.Name()]; ok {\n\t\t\t// if we're not outputting the package, don't include it in either package list\n\t\t\tcontinue\n\t\t}\n\t\tp.Vendored = strings.Contains(c.Universe[p.PackagePath].SourcePath, \"/vendor/\")\n\t\tif p.Vendored {\n\t\t\tvendoredOutputPackages = append(vendoredOutputPackages, p)\n\t\t} else {\n\t\t\tlocalOutputPackages = append(localOutputPackages, p)\n\t\t}\n\t}\n\n\tif err := protobufNames.AssignTypesToPackages(c); err != nil {\n\t\tlog.Fatalf(\"Failed to identify Common types: %v\", err)\n\t}\n\n\tif err := c.ExecutePackages(g.VendorOutputBase, vendoredOutputPackages); err != nil {\n\t\tlog.Fatalf(\"Failed executing vendor generator: %v\", err)\n\t}\n\tif err := c.ExecutePackages(g.OutputBase, localOutputPackages); err != nil {\n\t\tlog.Fatalf(\"Failed executing local generator: %v\", err)\n\t}\n\n\tif g.OnlyIDL {\n\t\treturn\n\t}\n\n\tif _, err := exec.LookPath(\"protoc\"); err != nil {\n\t\tlog.Fatalf(\"Unable to find 'protoc': %v\", err)\n\t}\n\n\tsearchArgs := []string{\"-I\", \".\", \"-I\", g.OutputBase}\n\tif len(g.ProtoImport) != 0 {\n\t\tfor _, s := range g.ProtoImport {\n\t\t\tsearchArgs = append(searchArgs, \"-I\", s)\n\t\t}\n\t}\n\targs := append(searchArgs, fmt.Sprintf(\"--gogo_out=%s\", g.OutputBase))\n\n\tbuf := \u0026bytes.Buffer{}\n\tif len(g.Conditional) \u003e 0 {\n\t\tfmt.Fprintf(buf, \"// +build %s\\n\\n\", g.Conditional)\n\t}\n\tbuf.Write(boilerplate)\n\n\tfor _, outputPackage := range outputPackages {\n\t\tp := outputPackage.(*protobufPackage)\n\n\t\tpath := filepath.Join(g.OutputBase, p.ImportPath())\n\t\toutputPath := filepath.Join(g.OutputBase, p.OutputPath())\n\t\tif p.Vendored {\n\t\t\tpath = filepath.Join(g.VendorOutputBase, p.ImportPath())\n\t\t\toutputPath = filepath.Join(g.VendorOutputBase, p.OutputPath())\n\t\t}\n\n\t\t// When working outside of GOPATH, we typically won't want to generate the\n\t\t// full path for a package. For example, if our current project's root/base\n\t\t// package is github.com/foo/bar, outDir=., p.Path()=github.com/foo/bar/generated,\n\t\t// then we really want to be writing files to ./generated, not ./github.com/foo/bar/generated.\n\t\t// The following will trim a path prefix (github.com/foo/bar) from p.Path() to arrive at\n\t\t// a relative path that works with projects not in GOPATH.\n\t\tif g.TrimPathPrefix != \"\" {\n\t\t\tseparator := string(filepath.Separator)\n\t\t\tif !strings.HasSuffix(g.TrimPathPrefix, separator) {\n\t\t\t\tg.TrimPathPrefix += separator\n\t\t\t}\n\n\t\t\tpath = strings.TrimPrefix(path, g.TrimPathPrefix)\n\t\t\toutputPath = strings.TrimPrefix(outputPath, g.TrimPathPrefix)\n\t\t}\n\n\t\t// generate the gogoprotobuf protoc\n\t\tcmd := exec.Command(\"protoc\", append(args, path)...)\n\t\tout, err := cmd.CombinedOutput()\n\t\tif err != nil {\n\t\t\tlog.Println(strings.Join(cmd.Args, \" \"))\n\t\t\tlog.Println(string(out))\n\t\t\tlog.Fatalf(\"Unable to generate protoc on %s: %v\", p.PackageName, err)\n\t\t}\n\n\t\tif g.SkipGeneratedRewrite {\n\t\t\tcontinue\n\t\t}\n\n\t\t// alter the generated protobuf file to remove the generated types (but leave the serializers) and rewrite the\n\t\t// package statement to match the desired package name\n\t\tif err := RewriteGeneratedGogoProtobufFile(outputPath, p.ExtractGeneratedType, p.OptionalTypeName, buf.Bytes()); err != nil {\n\t\t\tlog.Fatalf(\"Unable to rewrite generated %s: %v\", outputPath, err)\n\t\t}\n\n\t\t// sort imports\n\t\tcmd = exec.Command(\"goimports\", \"-w\", outputPath)\n\t\tout, err = cmd.CombinedOutput()\n\t\tif len(out) \u003e 0 {\n\t\t\tlog.Print(string(out))\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Println(strings.Join(cmd.Args, \" \"))\n\t\t\tlog.Fatalf(\"Unable to rewrite imports for %s: %v\", p.PackageName, err)\n\t\t}\n\n\t\t// format and simplify the generated file\n\t\tcmd = exec.Command(\"gofmt\", \"-s\", \"-w\", outputPath)\n\t\tout, err = cmd.CombinedOutput()\n\t\tif len(out) \u003e 0 {\n\t\t\tlog.Print(string(out))\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Println(strings.Join(cmd.Args, \" \"))\n\t\t\tlog.Fatalf(\"Unable to apply gofmt for %s: %v\", p.PackageName, err)\n\t\t}\n\t}\n\n\tif g.SkipGeneratedRewrite {\n\t\treturn\n\t}\n\n\tif !g.KeepGogoproto {\n\t\t// generate, but do so without gogoprotobuf extensions\n\t\tfor _, outputPackage := range outputPackages {\n\t\t\tp := outputPackage.(*protobufPackage)\n\t\t\tp.OmitGogo = true\n\t\t}\n\t\tif err := c.ExecutePackages(g.VendorOutputBase, vendoredOutputPackages); err != nil {\n\t\t\tlog.Fatalf(\"Failed executing vendor generator: %v\", err)\n\t\t}\n\t\tif err := c.ExecutePackages(g.OutputBase, localOutputPackages); err != nil {\n\t\t\tlog.Fatalf(\"Failed executing local generator: %v\", err)\n\t\t}\n\t}\n\n\tfor _, outputPackage := range outputPackages {\n\t\tp := outputPackage.(*protobufPackage)\n\n\t\tif len(p.StructTags) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tpattern := filepath.Join(g.OutputBase, p.PackagePath, \"*.go\")\n\t\tif p.Vendored {\n\t\t\tpattern = filepath.Join(g.VendorOutputBase, p.PackagePath, \"*.go\")\n\t\t}\n\t\tfiles, err := filepath.Glob(pattern)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Can't glob pattern %q: %v\", pattern, err)\n\t\t}\n\n\t\tfor _, s := range files {\n\t\t\tif strings.HasSuffix(s, \"_test.go\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := RewriteTypesWithProtobufStructTags(s, p.StructTags); err != nil {\n\t\t\t\tlog.Fatalf(\"Unable to rewrite with struct tags %s: %v\", s, err)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":102,"to":377}} {"id":100029948,"name":"deps","signature":"func deps(c *generator.Context, pkgs []*protobufPackage) map[string][]string","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/cmd.go","code":"func deps(c *generator.Context, pkgs []*protobufPackage) map[string][]string {\n\tret := map[string][]string{}\n\tfor _, p := range pkgs {\n\t\tpkg, ok := c.Universe[p.PackagePath]\n\t\tif !ok {\n\t\t\tlog.Fatalf(\"Unrecognized package: %s\", p.PackagePath)\n\t\t}\n\n\t\tfor _, d := range pkg.Imports {\n\t\t\tret[p.PackagePath] = append(ret[p.PackagePath], d.Path)\n\t\t}\n\t}\n\treturn ret\n}","line":{"from":379,"to":392}} {"id":100029949,"name":"importOrder","signature":"func importOrder(deps map[string][]string) ([]string, error)","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/cmd.go","code":"// given a set of pkg-\u003e[]deps, return the order that ensures all deps are processed before the things that depend on them\nfunc importOrder(deps map[string][]string) ([]string, error) {\n\t// add all nodes and edges\n\tvar remainingNodes = map[string]struct{}{}\n\tvar graph = map[edge]struct{}{}\n\tfor to, froms := range deps {\n\t\tremainingNodes[to] = struct{}{}\n\t\tfor _, from := range froms {\n\t\t\tremainingNodes[from] = struct{}{}\n\t\t\tgraph[edge{from: from, to: to}] = struct{}{}\n\t\t}\n\t}\n\n\t// find initial nodes without any dependencies\n\tsorted := findAndRemoveNodesWithoutDependencies(remainingNodes, graph)\n\tfor i := 0; i \u003c len(sorted); i++ {\n\t\tnode := sorted[i]\n\t\tremoveEdgesFrom(node, graph)\n\t\tsorted = append(sorted, findAndRemoveNodesWithoutDependencies(remainingNodes, graph)...)\n\t}\n\tif len(remainingNodes) \u003e 0 {\n\t\treturn nil, fmt.Errorf(\"cycle: remaining nodes: %#v, remaining edges: %#v\", remainingNodes, graph)\n\t}\n\t//for _, n := range sorted {\n\t//\tfmt.Println(\"topological order\", n)\n\t//}\n\treturn sorted, nil\n}","line":{"from":394,"to":421}} {"id":100029950,"name":"findAndRemoveNodesWithoutDependencies","signature":"func findAndRemoveNodesWithoutDependencies(nodes map[string]struct{}, graph map[edge]struct{}) []string","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/cmd.go","code":"// findAndRemoveNodesWithoutDependencies finds nodes in the given set which are not pointed to by any edges in the graph,\n// removes them from the set of nodes, and returns them in sorted order\nfunc findAndRemoveNodesWithoutDependencies(nodes map[string]struct{}, graph map[edge]struct{}) []string {\n\troots := []string{}\n\t// iterate over all nodes as potential \"to\" nodes\n\tfor node := range nodes {\n\t\tincoming := false\n\t\t// iterate over all remaining edges\n\t\tfor edge := range graph {\n\t\t\t// if there's any edge to the node we care about, it's not a root\n\t\t\tif edge.to == node {\n\t\t\t\tincoming = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\t// if there are no incoming edges, remove from the set of remaining nodes and add to our results\n\t\tif !incoming {\n\t\t\tdelete(nodes, node)\n\t\t\troots = append(roots, node)\n\t\t}\n\t}\n\tsort.Strings(roots)\n\treturn roots\n}","line":{"from":429,"to":452}} {"id":100029951,"name":"removeEdgesFrom","signature":"func removeEdgesFrom(node string, graph map[edge]struct{})","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/cmd.go","code":"// removeEdgesFrom removes any edges from the graph where edge.from == node\nfunc removeEdgesFrom(node string, graph map[edge]struct{}) {\n\tfor edge := range graph {\n\t\tif edge.from == node {\n\t\t\tdelete(graph, edge)\n\t\t}\n\t}\n}","line":{"from":454,"to":461}} {"id":100029952,"name":"Len","signature":"func (o positionOrder) Len() int","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/cmd.go","code":"func (o positionOrder) Len() int {\n\treturn len(o.elements)\n}","line":{"from":468,"to":470}} {"id":100029953,"name":"Less","signature":"func (o positionOrder) Less(i, j int) bool","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/cmd.go","code":"func (o positionOrder) Less(i, j int) bool {\n\treturn o.pos[o.elements[i].PackagePath] \u003c o.pos[o.elements[j].PackagePath]\n}","line":{"from":472,"to":474}} {"id":100029954,"name":"Swap","signature":"func (o positionOrder) Swap(i, j int)","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/cmd.go","code":"func (o positionOrder) Swap(i, j int) {\n\tx := o.elements[i]\n\to.elements[i] = o.elements[j]\n\to.elements[j] = x\n}","line":{"from":476,"to":480}} {"id":100029955,"name":"PackageVars","signature":"func (g *genProtoIDL) PackageVars(c *generator.Context) []string","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go","code":"func (g *genProtoIDL) PackageVars(c *generator.Context) []string {\n\tif g.omitGogo {\n\t\treturn []string{\n\t\t\tfmt.Sprintf(\"option go_package = %q;\", g.localGoPackage.Package),\n\t\t}\n\t}\n\treturn []string{\n\t\t\"option (gogoproto.marshaler_all) = true;\",\n\t\t\"option (gogoproto.stable_marshaler_all) = true;\",\n\t\t\"option (gogoproto.sizer_all) = true;\",\n\t\t\"option (gogoproto.goproto_stringer_all) = false;\",\n\t\t\"option (gogoproto.stringer_all) = true;\",\n\t\t\"option (gogoproto.unmarshaler_all) = true;\",\n\t\t\"option (gogoproto.goproto_unrecognized_all) = false;\",\n\t\t\"option (gogoproto.goproto_enum_prefix_all) = false;\",\n\t\t\"option (gogoproto.goproto_getters_all) = false;\",\n\t\tfmt.Sprintf(\"option go_package = %q;\", g.localGoPackage.Package),\n\t}\n}","line":{"from":47,"to":65}} {"id":100029956,"name":"Filename","signature":"func (g *genProtoIDL) Filename() string { return g.OptionalName + \".proto\" }","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go","code":"func (g *genProtoIDL) Filename() string { return g.OptionalName + \".proto\" }","line":{"from":66,"to":66}} {"id":100029957,"name":"FileType","signature":"func (g *genProtoIDL) FileType() string { return \"protoidl\" }","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go","code":"func (g *genProtoIDL) FileType() string { return \"protoidl\" }","line":{"from":67,"to":67}} {"id":100029958,"name":"Namers","signature":"func (g *genProtoIDL) Namers(c *generator.Context) namer.NameSystems","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go","code":"func (g *genProtoIDL) Namers(c *generator.Context) namer.NameSystems {\n\treturn namer.NameSystems{\n\t\t// The local namer returns the correct protobuf name for a proto type\n\t\t// in the context of a package\n\t\t\"local\": localNamer{g.localPackage},\n\t}\n}","line":{"from":68,"to":74}} {"id":100029959,"name":"Filter","signature":"func (g *genProtoIDL) Filter(c *generator.Context, t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go","code":"// Filter ignores types that are identified as not exportable.\nfunc (g *genProtoIDL) Filter(c *generator.Context, t *types.Type) bool {\n\ttagVals := types.ExtractCommentTags(\"+\", t.CommentLines)[\"protobuf\"]\n\tif tagVals != nil {\n\t\tif tagVals[0] == \"false\" {\n\t\t\t// Type specified \"false\".\n\t\t\treturn false\n\t\t}\n\t\tif tagVals[0] == \"true\" {\n\t\t\t// Type specified \"true\".\n\t\t\treturn true\n\t\t}\n\t\tklog.Fatalf(`Comment tag \"protobuf\" must be true or false, found: %q`, tagVals[0])\n\t}\n\tif !g.generateAll {\n\t\t// We're not generating everything.\n\t\treturn false\n\t}\n\tseen := map[*types.Type]bool{}\n\tok := isProtoable(seen, t)\n\treturn ok\n}","line":{"from":76,"to":97}} {"id":100029960,"name":"isProtoable","signature":"func isProtoable(seen map[*types.Type]bool, t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go","code":"func isProtoable(seen map[*types.Type]bool, t *types.Type) bool {\n\tif seen[t] {\n\t\t// be optimistic in the case of type cycles.\n\t\treturn true\n\t}\n\tseen[t] = true\n\tswitch t.Kind {\n\tcase types.Builtin:\n\t\treturn true\n\tcase types.Alias:\n\t\treturn isProtoable(seen, t.Underlying)\n\tcase types.Slice, types.Pointer:\n\t\treturn isProtoable(seen, t.Elem)\n\tcase types.Map:\n\t\treturn isProtoable(seen, t.Key) \u0026\u0026 isProtoable(seen, t.Elem)\n\tcase types.Struct:\n\t\tif len(t.Members) == 0 {\n\t\t\treturn true\n\t\t}\n\t\tfor _, m := range t.Members {\n\t\t\tif isProtoable(seen, m.Type) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\tcase types.Func, types.Chan:\n\t\treturn false\n\tcase types.DeclarationOf, types.Unknown, types.Unsupported:\n\t\treturn false\n\tcase types.Interface:\n\t\treturn false\n\tdefault:\n\t\tlog.Printf(\"WARNING: type %q is not portable: %s\", t.Kind, t.Name)\n\t\treturn false\n\t}\n}","line":{"from":99,"to":134}} {"id":100029961,"name":"isOptionalAlias","signature":"func isOptionalAlias(t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go","code":"// isOptionalAlias should return true if the specified type has an underlying type\n// (is an alias) of a map or slice and has the comment tag protobuf.nullable=true,\n// indicating that the type should be nullable in protobuf.\nfunc isOptionalAlias(t *types.Type) bool {\n\tif t.Underlying == nil || (t.Underlying.Kind != types.Map \u0026\u0026 t.Underlying.Kind != types.Slice) {\n\t\treturn false\n\t}\n\tif extractBoolTagOrDie(\"protobuf.nullable\", t.CommentLines) == false {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":136,"to":147}} {"id":100029962,"name":"Imports","signature":"func (g *genProtoIDL) Imports(c *generator.Context) (imports []string)","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go","code":"func (g *genProtoIDL) Imports(c *generator.Context) (imports []string) {\n\tlines := []string{}\n\t// TODO: this could be expressed more cleanly\n\tfor _, line := range g.imports.ImportLines() {\n\t\tif g.omitGogo \u0026\u0026 line == \"github.com/gogo/protobuf/gogoproto/gogo.proto\" {\n\t\t\tcontinue\n\t\t}\n\t\tlines = append(lines, line)\n\t}\n\treturn lines\n}","line":{"from":149,"to":159}} {"id":100029963,"name":"GenerateType","signature":"func (g *genProtoIDL) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go","code":"// GenerateType makes the body of a file implementing a set for type t.\nfunc (g *genProtoIDL) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {\n\tsw := generator.NewSnippetWriter(w, c, \"$\", \"$\")\n\tb := bodyGen{\n\t\tlocator: \u0026protobufLocator{\n\t\t\tnamer: c.Namers[\"proto\"].(ProtobufFromGoNamer),\n\t\t\ttracker: g.imports,\n\t\t\tuniverse: c.Universe,\n\n\t\t\tlocalGoPackage: g.localGoPackage.Package,\n\t\t},\n\t\tlocalPackage: g.localPackage,\n\n\t\tomitGogo: g.omitGogo,\n\t\tomitFieldTypes: g.omitFieldTypes,\n\n\t\tt: t,\n\t}\n\tswitch t.Kind {\n\tcase types.Alias:\n\t\treturn b.doAlias(sw)\n\tcase types.Struct:\n\t\treturn b.doStruct(sw)\n\tdefault:\n\t\treturn b.unknown(sw)\n\t}\n}","line":{"from":161,"to":187}} {"id":100029964,"name":"CastTypeName","signature":"func (p protobufLocator) CastTypeName(name types.Name) string","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go","code":"// CastTypeName returns the cast type name of a Go type\n// TODO: delegate to a new localgo namer?\nfunc (p protobufLocator) CastTypeName(name types.Name) string {\n\tif name.Package == p.localGoPackage {\n\t\treturn name.Name\n\t}\n\treturn name.String()\n}","line":{"from":209,"to":216}} {"id":100029965,"name":"GoTypeForName","signature":"func (p protobufLocator) GoTypeForName(name types.Name) *types.Type","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go","code":"func (p protobufLocator) GoTypeForName(name types.Name) *types.Type {\n\tif len(name.Package) == 0 {\n\t\tname.Package = p.localGoPackage\n\t}\n\treturn p.universe.Type(name)\n}","line":{"from":218,"to":223}} {"id":100029966,"name":"ProtoTypeFor","signature":"func (p protobufLocator) ProtoTypeFor(t *types.Type) (*types.Type, error)","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go","code":"// ProtoTypeFor locates a Protobuf type for the provided Go type (if possible).\nfunc (p protobufLocator) ProtoTypeFor(t *types.Type) (*types.Type, error) {\n\tswitch {\n\t// we've already converted the type, or it's a map\n\tcase t.Kind == types.Protobuf || t.Kind == types.Map:\n\t\tp.tracker.AddType(t)\n\t\treturn t, nil\n\t}\n\t// it's a fundamental type\n\tif t, ok := isFundamentalProtoType(t); ok {\n\t\tp.tracker.AddType(t)\n\t\treturn t, nil\n\t}\n\t// it's a message\n\tif t.Kind == types.Struct || isOptionalAlias(t) {\n\t\tt := \u0026types.Type{\n\t\t\tName: p.namer.GoNameToProtoName(t.Name),\n\t\t\tKind: types.Protobuf,\n\n\t\t\tCommentLines: t.CommentLines,\n\t\t}\n\t\tp.tracker.AddType(t)\n\t\treturn t, nil\n\t}\n\treturn nil, errUnrecognizedType\n}","line":{"from":225,"to":250}} {"id":100029967,"name":"unknown","signature":"func (b bodyGen) unknown(sw *generator.SnippetWriter) error","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go","code":"func (b bodyGen) unknown(sw *generator.SnippetWriter) error {\n\treturn fmt.Errorf(\"not sure how to generate: %#v\", b.t)\n}","line":{"from":261,"to":263}} {"id":100029968,"name":"doAlias","signature":"func (b bodyGen) doAlias(sw *generator.SnippetWriter) error","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go","code":"func (b bodyGen) doAlias(sw *generator.SnippetWriter) error {\n\tif !isOptionalAlias(b.t) {\n\t\treturn nil\n\t}\n\n\tvar kind string\n\tswitch b.t.Underlying.Kind {\n\tcase types.Map:\n\t\tkind = \"map\"\n\tdefault:\n\t\tkind = \"slice\"\n\t}\n\toptional := \u0026types.Type{\n\t\tName: b.t.Name,\n\t\tKind: types.Struct,\n\n\t\tCommentLines: b.t.CommentLines,\n\t\tSecondClosestCommentLines: b.t.SecondClosestCommentLines,\n\t\tMembers: []types.Member{\n\t\t\t{\n\t\t\t\tName: \"Items\",\n\t\t\t\tCommentLines: []string{fmt.Sprintf(\"items, if empty, will result in an empty %s\\n\", kind)},\n\t\t\t\tType: b.t.Underlying,\n\t\t\t},\n\t\t},\n\t}\n\tnested := b\n\tnested.t = optional\n\treturn nested.doStruct(sw)\n}","line":{"from":265,"to":294}} {"id":100029969,"name":"doStruct","signature":"func (b bodyGen) doStruct(sw *generator.SnippetWriter) error","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go","code":"func (b bodyGen) doStruct(sw *generator.SnippetWriter) error {\n\tif len(b.t.Name.Name) == 0 {\n\t\treturn nil\n\t}\n\tif namer.IsPrivateGoName(b.t.Name.Name) {\n\t\treturn nil\n\t}\n\n\tvar alias *types.Type\n\tvar fields []protoField\n\toptions := []string{}\n\tallOptions := types.ExtractCommentTags(\"+\", b.t.CommentLines)\n\tfor k, v := range allOptions {\n\t\tswitch {\n\t\tcase strings.HasPrefix(k, \"protobuf.options.\"):\n\t\t\tkey := strings.TrimPrefix(k, \"protobuf.options.\")\n\t\t\tswitch key {\n\t\t\tcase \"marshal\":\n\t\t\t\tif v[0] == \"false\" {\n\t\t\t\t\tif !b.omitGogo {\n\t\t\t\t\t\toptions = append(options,\n\t\t\t\t\t\t\t\"(gogoproto.marshaler) = false\",\n\t\t\t\t\t\t\t\"(gogoproto.unmarshaler) = false\",\n\t\t\t\t\t\t\t\"(gogoproto.sizer) = false\",\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tif !b.omitGogo || !strings.HasPrefix(key, \"(gogoproto.\") {\n\t\t\t\t\tif key == \"(gogoproto.goproto_stringer)\" \u0026\u0026 v[0] == \"false\" {\n\t\t\t\t\t\toptions = append(options, \"(gogoproto.stringer) = false\")\n\t\t\t\t\t}\n\t\t\t\t\toptions = append(options, fmt.Sprintf(\"%s = %s\", key, v[0]))\n\t\t\t\t}\n\t\t\t}\n\t\t// protobuf.as allows a type to have the same message contents as another Go type\n\t\tcase k == \"protobuf.as\":\n\t\t\tfields = nil\n\t\t\tif alias = b.locator.GoTypeForName(types.Name{Name: v[0]}); alias == nil {\n\t\t\t\treturn fmt.Errorf(\"type %v references alias %q which does not exist\", b.t, v[0])\n\t\t\t}\n\t\t// protobuf.embed instructs the generator to use the named type in this package\n\t\t// as an embedded message.\n\t\tcase k == \"protobuf.embed\":\n\t\t\tfields = []protoField{\n\t\t\t\t{\n\t\t\t\t\tTag: 1,\n\t\t\t\t\tName: v[0],\n\t\t\t\t\tType: \u0026types.Type{\n\t\t\t\t\t\tName: types.Name{\n\t\t\t\t\t\t\tName: v[0],\n\t\t\t\t\t\t\tPackage: b.localPackage.Package,\n\t\t\t\t\t\t\tPath: b.localPackage.Path,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t}\n\tif alias == nil {\n\t\talias = b.t\n\t}\n\n\t// If we don't explicitly embed anything, generate fields by traversing fields.\n\tif fields == nil {\n\t\tmemberFields, err := membersToFields(b.locator, alias, b.localPackage, b.omitFieldTypes)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"type %v cannot be converted to protobuf: %v\", b.t, err)\n\t\t}\n\t\tfields = memberFields\n\t}\n\n\tout := sw.Out()\n\tgenComment(out, b.t.CommentLines, \"\")\n\tsw.Do(`message $.Name.Name$ {\n`, b.t)\n\n\tif len(options) \u003e 0 {\n\t\tsort.Strings(options)\n\t\tfor _, s := range options {\n\t\t\tfmt.Fprintf(out, \" option %s;\\n\", s)\n\t\t}\n\t\tfmt.Fprintln(out)\n\t}\n\n\tfor i, field := range fields {\n\t\tgenComment(out, field.CommentLines, \" \")\n\t\tfmt.Fprintf(out, \" \")\n\t\tswitch {\n\t\tcase field.Map:\n\t\tcase field.Repeated:\n\t\t\tfmt.Fprintf(out, \"repeated \")\n\t\tcase field.Required:\n\t\t\tfmt.Fprintf(out, \"required \")\n\t\tdefault:\n\t\t\tfmt.Fprintf(out, \"optional \")\n\t\t}\n\t\tsw.Do(`$.Type|local$ $.Name$ = $.Tag$`, field)\n\t\tif len(field.Extras) \u003e 0 {\n\t\t\textras := []string{}\n\t\t\tfor k, v := range field.Extras {\n\t\t\t\tif b.omitGogo \u0026\u0026 strings.HasPrefix(k, \"(gogoproto.\") {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\textras = append(extras, fmt.Sprintf(\"%s = %s\", k, v))\n\t\t\t}\n\t\t\tsort.Strings(extras)\n\t\t\tif len(extras) \u003e 0 {\n\t\t\t\tfmt.Fprintf(out, \" [\")\n\t\t\t\tfmt.Fprint(out, strings.Join(extras, \", \"))\n\t\t\t\tfmt.Fprintf(out, \"]\")\n\t\t\t}\n\t\t}\n\t\tfmt.Fprintf(out, \";\\n\")\n\t\tif i != len(fields)-1 {\n\t\t\tfmt.Fprintf(out, \"\\n\")\n\t\t}\n\t}\n\tfmt.Fprintf(out, \"}\\n\\n\")\n\treturn nil\n}","line":{"from":296,"to":416}} {"id":100029970,"name":"isFundamentalProtoType","signature":"func isFundamentalProtoType(t *types.Type) (*types.Type, bool)","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go","code":"func isFundamentalProtoType(t *types.Type) (*types.Type, bool) {\n\t// TODO: when we enable proto3, also include other fundamental types in the google.protobuf package\n\t// switch {\n\t// case t.Kind == types.Struct \u0026\u0026 t.Name == types.Name{Package: \"time\", Name: \"Time\"}:\n\t// \treturn \u0026types.Type{\n\t// \t\tKind: types.Protobuf,\n\t// \t\tName: types.Name{Path: \"google/protobuf/timestamp.proto\", Package: \"google.protobuf\", Name: \"Timestamp\"},\n\t// \t}, true\n\t// }\n\tswitch t.Kind {\n\tcase types.Slice:\n\t\tif t.Elem.Name.Name == \"byte\" \u0026\u0026 len(t.Elem.Name.Package) == 0 {\n\t\t\treturn \u0026types.Type{Name: types.Name{Name: \"bytes\"}, Kind: types.Protobuf}, true\n\t\t}\n\tcase types.Builtin:\n\t\tswitch t.Name.Name {\n\t\tcase \"string\", \"uint32\", \"int32\", \"uint64\", \"int64\", \"bool\":\n\t\t\treturn \u0026types.Type{Name: types.Name{Name: t.Name.Name}, Kind: types.Protobuf}, true\n\t\tcase \"int\":\n\t\t\treturn \u0026types.Type{Name: types.Name{Name: \"int64\"}, Kind: types.Protobuf}, true\n\t\tcase \"uint\":\n\t\t\treturn \u0026types.Type{Name: types.Name{Name: \"uint64\"}, Kind: types.Protobuf}, true\n\t\tcase \"float64\", \"float\":\n\t\t\treturn \u0026types.Type{Name: types.Name{Name: \"double\"}, Kind: types.Protobuf}, true\n\t\tcase \"float32\":\n\t\t\treturn \u0026types.Type{Name: types.Name{Name: \"float\"}, Kind: types.Protobuf}, true\n\t\tcase \"uintptr\":\n\t\t\treturn \u0026types.Type{Name: types.Name{Name: \"uint64\"}, Kind: types.Protobuf}, true\n\t\t}\n\t\t// TODO: complex?\n\t}\n\treturn t, false\n}","line":{"from":438,"to":470}} {"id":100029971,"name":"memberTypeToProtobufField","signature":"func memberTypeToProtobufField(locator ProtobufLocator, field *protoField, t *types.Type) error","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go","code":"func memberTypeToProtobufField(locator ProtobufLocator, field *protoField, t *types.Type) error {\n\tvar err error\n\tswitch t.Kind {\n\tcase types.Protobuf:\n\t\tfield.Type, err = locator.ProtoTypeFor(t)\n\tcase types.Builtin:\n\t\tfield.Type, err = locator.ProtoTypeFor(t)\n\tcase types.Map:\n\t\tvalueField := \u0026protoField{}\n\t\tif err := memberTypeToProtobufField(locator, valueField, t.Elem); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tkeyField := \u0026protoField{}\n\t\tif err := memberTypeToProtobufField(locator, keyField, t.Key); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// All other protobuf types have kind types.Protobuf, so setting types.Map\n\t\t// here would be very misleading.\n\t\tfield.Type = \u0026types.Type{\n\t\t\tKind: types.Protobuf,\n\t\t\tKey: keyField.Type,\n\t\t\tElem: valueField.Type,\n\t\t}\n\t\tif !strings.HasPrefix(t.Name.Name, \"map[\") {\n\t\t\tfield.Extras[\"(gogoproto.casttype)\"] = strconv.Quote(locator.CastTypeName(t.Name))\n\t\t}\n\t\tif k, ok := keyField.Extras[\"(gogoproto.casttype)\"]; ok {\n\t\t\tfield.Extras[\"(gogoproto.castkey)\"] = k\n\t\t}\n\t\tif v, ok := valueField.Extras[\"(gogoproto.casttype)\"]; ok {\n\t\t\tfield.Extras[\"(gogoproto.castvalue)\"] = v\n\t\t}\n\t\tfield.Map = true\n\tcase types.Pointer:\n\t\tif err := memberTypeToProtobufField(locator, field, t.Elem); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfield.Nullable = true\n\tcase types.Alias:\n\t\tif isOptionalAlias(t) {\n\t\t\tfield.Type, err = locator.ProtoTypeFor(t)\n\t\t\tfield.Nullable = true\n\t\t} else {\n\t\t\tif err := memberTypeToProtobufField(locator, field, t.Underlying); err != nil {\n\t\t\t\tlog.Printf(\"failed to alias: %s %s: err %v\", t.Name, t.Underlying.Name, err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// If this is not an alias to a slice, cast to the alias\n\t\t\tif !field.Repeated {\n\t\t\t\tif field.Extras == nil {\n\t\t\t\t\tfield.Extras = make(map[string]string)\n\t\t\t\t}\n\t\t\t\tfield.Extras[\"(gogoproto.casttype)\"] = strconv.Quote(locator.CastTypeName(t.Name))\n\t\t\t}\n\t\t}\n\tcase types.Slice:\n\t\tif t.Elem.Name.Name == \"byte\" \u0026\u0026 len(t.Elem.Name.Package) == 0 {\n\t\t\tfield.Type = \u0026types.Type{Name: types.Name{Name: \"bytes\"}, Kind: types.Protobuf}\n\t\t\treturn nil\n\t\t}\n\t\tif err := memberTypeToProtobufField(locator, field, t.Elem); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfield.Repeated = true\n\tcase types.Struct:\n\t\tif len(t.Name.Name) == 0 {\n\t\t\treturn errUnrecognizedType\n\t\t}\n\t\tfield.Type, err = locator.ProtoTypeFor(t)\n\t\tfield.Nullable = false\n\tdefault:\n\t\treturn errUnrecognizedType\n\t}\n\treturn err\n}","line":{"from":472,"to":546}} {"id":100029972,"name":"protobufTagToField","signature":"func protobufTagToField(tag string, field *protoField, m types.Member, t *types.Type, localPackage types.Name) error","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go","code":"// protobufTagToField extracts information from an existing protobuf tag\nfunc protobufTagToField(tag string, field *protoField, m types.Member, t *types.Type, localPackage types.Name) error {\n\tif len(tag) == 0 || tag == \"-\" {\n\t\treturn nil\n\t}\n\n\t// protobuf:\"bytes,3,opt,name=Id,customtype=github.com/gogo/protobuf/test.Uuid\"\n\tparts := strings.Split(tag, \",\")\n\tif len(parts) \u003c 3 {\n\t\treturn fmt.Errorf(\"member %q of %q malformed 'protobuf' tag, not enough segments\\n\", m.Name, t.Name)\n\t}\n\tprotoTag, err := strconv.Atoi(parts[1])\n\tif err != nil {\n\t\treturn fmt.Errorf(\"member %q of %q malformed 'protobuf' tag, field ID is %q which is not an integer: %v\\n\", m.Name, t.Name, parts[1], err)\n\t}\n\tfield.Tag = protoTag\n\n\t// In general there is doesn't make sense to parse the protobuf tags to get the type,\n\t// as all auto-generated once will have wire type \"bytes\", \"varint\" or \"fixed64\".\n\t// However, sometimes we explicitly set them to have a custom serialization, e.g.:\n\t// type Time struct {\n\t// time.Time `protobuf:\"Timestamp,1,req,name=time\"`\n\t// }\n\t// to force the generator to use a given type (that we manually wrote serialization \u0026\n\t// deserialization methods for).\n\tswitch parts[0] {\n\tcase \"varint\", \"fixed32\", \"fixed64\", \"bytes\", \"group\":\n\tdefault:\n\t\tvar name types.Name\n\t\tif last := strings.LastIndex(parts[0], \".\"); last != -1 {\n\t\t\tprefix := parts[0][:last]\n\t\t\tname = types.Name{\n\t\t\t\tName: parts[0][last+1:],\n\t\t\t\tPackage: prefix,\n\t\t\t\tPath: strings.Replace(prefix, \".\", \"/\", -1),\n\t\t\t}\n\t\t} else {\n\t\t\tname = types.Name{\n\t\t\t\tName: parts[0],\n\t\t\t\tPackage: localPackage.Package,\n\t\t\t\tPath: localPackage.Path,\n\t\t\t}\n\t\t}\n\t\tfield.Type = \u0026types.Type{\n\t\t\tName: name,\n\t\t\tKind: types.Protobuf,\n\t\t}\n\t}\n\n\tprotoExtra := make(map[string]string)\n\tfor i, extra := range parts[3:] {\n\t\tparts := strings.SplitN(extra, \"=\", 2)\n\t\tif len(parts) != 2 {\n\t\t\treturn fmt.Errorf(\"member %q of %q malformed 'protobuf' tag, tag %d should be key=value, got %q\\n\", m.Name, t.Name, i+4, extra)\n\t\t}\n\t\tswitch parts[0] {\n\t\tcase \"name\":\n\t\t\tprotoExtra[parts[0]] = parts[1]\n\t\tcase \"casttype\", \"castkey\", \"castvalue\":\n\t\t\tparts[0] = fmt.Sprintf(\"(gogoproto.%s)\", parts[0])\n\t\t\tprotoExtra[parts[0]] = strconv.Quote(parts[1])\n\t\t}\n\t}\n\n\tfield.Extras = protoExtra\n\tif name, ok := protoExtra[\"name\"]; ok {\n\t\tfield.Name = name\n\t\tdelete(protoExtra, \"name\")\n\t}\n\n\treturn nil\n}","line":{"from":548,"to":619}} {"id":100029973,"name":"membersToFields","signature":"func membersToFields(locator ProtobufLocator, t *types.Type, localPackage types.Name, omitFieldTypes map[types.Name]struct{}) ([]protoField, error)","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go","code":"func membersToFields(locator ProtobufLocator, t *types.Type, localPackage types.Name, omitFieldTypes map[types.Name]struct{}) ([]protoField, error) {\n\tfields := []protoField{}\n\n\tfor _, m := range t.Members {\n\t\tif namer.IsPrivateGoName(m.Name) {\n\t\t\t// skip private fields\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := omitFieldTypes[types.Name{Name: m.Type.Name.Name, Package: m.Type.Name.Package}]; ok {\n\t\t\tcontinue\n\t\t}\n\t\ttags := reflect.StructTag(m.Tags)\n\t\tfield := protoField{\n\t\t\tLocalPackage: localPackage,\n\n\t\t\tTag: -1,\n\t\t\tExtras: make(map[string]string),\n\t\t}\n\n\t\tprotobufTag := tags.Get(\"protobuf\")\n\t\tif protobufTag == \"-\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := protobufTagToField(protobufTag, \u0026field, m, t, localPackage); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// extract information from JSON field tag\n\t\tif tag := tags.Get(\"json\"); len(tag) \u003e 0 {\n\t\t\tparts := strings.Split(tag, \",\")\n\t\t\tif len(field.Name) == 0 \u0026\u0026 len(parts[0]) != 0 {\n\t\t\t\tfield.Name = parts[0]\n\t\t\t}\n\t\t\tif field.Tag == -1 \u0026\u0026 field.Name == \"-\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tif field.Type == nil {\n\t\t\tif err := memberTypeToProtobufField(locator, \u0026field, m.Type); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"unable to embed type %q as field %q in %q: %v\", m.Type, field.Name, t.Name, err)\n\t\t\t}\n\t\t}\n\t\tif len(field.Name) == 0 {\n\t\t\tfield.Name = namer.IL(m.Name)\n\t\t}\n\n\t\tif field.Map \u0026\u0026 field.Repeated {\n\t\t\t// maps cannot be repeated\n\t\t\tfield.Repeated = false\n\t\t\tfield.Nullable = true\n\t\t}\n\n\t\tif !field.Nullable {\n\t\t\tfield.Extras[\"(gogoproto.nullable)\"] = \"false\"\n\t\t}\n\t\tif (field.Type.Name.Name == \"bytes\" \u0026\u0026 field.Type.Name.Package == \"\") || (field.Repeated \u0026\u0026 field.Type.Name.Package == \"\" \u0026\u0026 namer.IsPrivateGoName(field.Type.Name.Name)) {\n\t\t\tdelete(field.Extras, \"(gogoproto.nullable)\")\n\t\t}\n\t\tif field.Name != m.Name {\n\t\t\tfield.Extras[\"(gogoproto.customname)\"] = strconv.Quote(m.Name)\n\t\t}\n\t\tfield.CommentLines = m.CommentLines\n\t\tfields = append(fields, field)\n\t}\n\n\t// assign tags\n\thighest := 0\n\tbyTag := make(map[int]*protoField)\n\t// fields are in Go struct order, which we preserve\n\tfor i := range fields {\n\t\tfield := \u0026fields[i]\n\t\ttag := field.Tag\n\t\tif tag != -1 {\n\t\t\tif existing, ok := byTag[tag]; ok {\n\t\t\t\treturn nil, fmt.Errorf(\"field %q and %q both have tag %d\", field.Name, existing.Name, tag)\n\t\t\t}\n\t\t\tbyTag[tag] = field\n\t\t}\n\t\tif tag \u003e highest {\n\t\t\thighest = tag\n\t\t}\n\t}\n\t// starting from the highest observed tag, assign new field tags\n\tfor i := range fields {\n\t\tfield := \u0026fields[i]\n\t\tif field.Tag != -1 {\n\t\t\tcontinue\n\t\t}\n\t\thighest++\n\t\tfield.Tag = highest\n\t\tbyTag[field.Tag] = field\n\t}\n\treturn fields, nil\n}","line":{"from":621,"to":716}} {"id":100029974,"name":"genComment","signature":"func genComment(out io.Writer, lines []string, indent string)","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go","code":"func genComment(out io.Writer, lines []string, indent string) {\n\tfor {\n\t\tl := len(lines)\n\t\tif l == 0 || len(lines[l-1]) != 0 {\n\t\t\tbreak\n\t\t}\n\t\tlines = lines[:l-1]\n\t}\n\tfor _, c := range lines {\n\t\tif len(c) == 0 {\n\t\t\tfmt.Fprintf(out, \"%s//\\n\", indent) // avoid trailing whitespace\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Fprintf(out, \"%s// %s\\n\", indent, c)\n\t}\n}","line":{"from":718,"to":733}} {"id":100029975,"name":"formatProtoFile","signature":"func formatProtoFile(source []byte) ([]byte, error)","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go","code":"func formatProtoFile(source []byte) ([]byte, error) {\n\t// TODO; Is there any protobuf formatter?\n\treturn source, nil\n}","line":{"from":735,"to":738}} {"id":100029976,"name":"assembleProtoFile","signature":"func assembleProtoFile(w io.Writer, f *generator.File)","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go","code":"func assembleProtoFile(w io.Writer, f *generator.File) {\n\tw.Write(f.Header)\n\n\tfmt.Fprint(w, \"syntax = \\\"proto2\\\";\\n\\n\")\n\n\tif len(f.PackageName) \u003e 0 {\n\t\tfmt.Fprintf(w, \"package %s;\\n\\n\", f.PackageName)\n\t}\n\n\tif len(f.Imports) \u003e 0 {\n\t\timports := []string{}\n\t\tfor i := range f.Imports {\n\t\t\timports = append(imports, i)\n\t\t}\n\t\tsort.Strings(imports)\n\t\tfor _, s := range imports {\n\t\t\tfmt.Fprintf(w, \"import %q;\\n\", s)\n\t\t}\n\t\tfmt.Fprint(w, \"\\n\")\n\t}\n\n\tif f.Vars.Len() \u003e 0 {\n\t\tfmt.Fprintf(w, \"%s\\n\", f.Vars.String())\n\t}\n\n\tw.Write(f.Body.Bytes())\n}","line":{"from":740,"to":766}} {"id":100029977,"name":"NewProtoFile","signature":"func NewProtoFile() *generator.DefaultFileType","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/generator.go","code":"func NewProtoFile() *generator.DefaultFileType {\n\treturn \u0026generator.DefaultFileType{\n\t\tFormat: formatProtoFile,\n\t\tAssemble: assembleProtoFile,\n\t}\n}","line":{"from":768,"to":773}} {"id":100029978,"name":"NewImportTracker","signature":"func NewImportTracker(local types.Name, typesToAdd ...*types.Type) *ImportTracker","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/import_tracker.go","code":"func NewImportTracker(local types.Name, typesToAdd ...*types.Type) *ImportTracker {\n\ttracker := namer.NewDefaultImportTracker(local)\n\ttracker.IsInvalidType = func(t *types.Type) bool { return t.Kind != types.Protobuf }\n\ttracker.LocalName = func(name types.Name) string { return name.Package }\n\ttracker.PrintImport = func(path, name string) string { return path }\n\n\ttracker.AddTypes(typesToAdd...)\n\treturn \u0026ImportTracker{\n\t\tDefaultImportTracker: tracker,\n\t}\n}","line":{"from":28,"to":38}} {"id":100029979,"name":"AddNullable","signature":"func (tracker *ImportTracker) AddNullable()","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/import_tracker.go","code":"// AddNullable ensures that support for the nullable Gogo-protobuf extension is added.\nfunc (tracker *ImportTracker) AddNullable() {\n\ttracker.AddType(\u0026types.Type{\n\t\tKind: types.Protobuf,\n\t\tName: types.Name{\n\t\t\tName: \"nullable\",\n\t\t\tPackage: \"gogoproto\",\n\t\t\tPath: \"github.com/gogo/protobuf/gogoproto/gogo.proto\",\n\t\t},\n\t})\n}","line":{"from":40,"to":50}} {"id":100029980,"name":"Name","signature":"func (n localNamer) Name(t *types.Type) string","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/namer.go","code":"func (n localNamer) Name(t *types.Type) string {\n\tif t.Key != nil \u0026\u0026 t.Elem != nil {\n\t\treturn fmt.Sprintf(\"map\u003c%s, %s\u003e\", n.Name(t.Key), n.Name(t.Elem))\n\t}\n\tif len(n.localPackage.Package) != 0 \u0026\u0026 n.localPackage.Package == t.Name.Package {\n\t\treturn t.Name.Name\n\t}\n\treturn t.Name.String()\n}","line":{"from":33,"to":41}} {"id":100029981,"name":"NewProtobufNamer","signature":"func NewProtobufNamer() *protobufNamer","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/namer.go","code":"func NewProtobufNamer() *protobufNamer {\n\treturn \u0026protobufNamer{\n\t\tpackagesByPath: make(map[string]*protobufPackage),\n\t}\n}","line":{"from":48,"to":52}} {"id":100029982,"name":"Name","signature":"func (n *protobufNamer) Name(t *types.Type) string","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/namer.go","code":"func (n *protobufNamer) Name(t *types.Type) string {\n\tif t.Kind == types.Map {\n\t\treturn fmt.Sprintf(\"map\u003c%s, %s\u003e\", n.Name(t.Key), n.Name(t.Elem))\n\t}\n\treturn t.Name.String()\n}","line":{"from":54,"to":59}} {"id":100029983,"name":"List","signature":"func (n *protobufNamer) List() []generator.Package","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/namer.go","code":"func (n *protobufNamer) List() []generator.Package {\n\tpackages := make([]generator.Package, 0, len(n.packages))\n\tfor i := range n.packages {\n\t\tpackages = append(packages, n.packages[i])\n\t}\n\treturn packages\n}","line":{"from":61,"to":67}} {"id":100029984,"name":"Add","signature":"func (n *protobufNamer) Add(p *protobufPackage)","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/namer.go","code":"func (n *protobufNamer) Add(p *protobufPackage) {\n\tif _, ok := n.packagesByPath[p.PackagePath]; !ok {\n\t\tn.packagesByPath[p.PackagePath] = p\n\t\tn.packages = append(n.packages, p)\n\t}\n}","line":{"from":69,"to":74}} {"id":100029985,"name":"GoNameToProtoName","signature":"func (n *protobufNamer) GoNameToProtoName(name types.Name) types.Name","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/namer.go","code":"func (n *protobufNamer) GoNameToProtoName(name types.Name) types.Name {\n\tif p, ok := n.packagesByPath[name.Package]; ok {\n\t\treturn types.Name{\n\t\t\tName: name.Name,\n\t\t\tPackage: p.PackageName,\n\t\t\tPath: p.ImportPath(),\n\t\t}\n\t}\n\tfor _, p := range n.packages {\n\t\tif _, ok := p.FilterTypes[name]; ok {\n\t\t\treturn types.Name{\n\t\t\t\tName: name.Name,\n\t\t\t\tPackage: p.PackageName,\n\t\t\t\tPath: p.ImportPath(),\n\t\t\t}\n\t\t}\n\t}\n\treturn types.Name{Name: name.Name}\n}","line":{"from":76,"to":94}} {"id":100029986,"name":"protoSafePackage","signature":"func protoSafePackage(name string) string","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/namer.go","code":"func protoSafePackage(name string) string {\n\tpkg := strings.Replace(name, \"/\", \".\", -1)\n\treturn strings.Replace(pkg, \"-\", \"_\", -1)\n}","line":{"from":96,"to":99}} {"id":100029987,"name":"assignGoTypeToProtoPackage","signature":"func assignGoTypeToProtoPackage(p *protobufPackage, t *types.Type, local, global typeNameSet, optional map[types.Name]struct{})","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/namer.go","code":"// assignGoTypeToProtoPackage looks for Go and Protobuf types that are referenced by a type in\n// a package. It will not recurse into protobuf types.\nfunc assignGoTypeToProtoPackage(p *protobufPackage, t *types.Type, local, global typeNameSet, optional map[types.Name]struct{}) {\n\tnewT, isProto := isFundamentalProtoType(t)\n\tif isProto {\n\t\tt = newT\n\t}\n\tif otherP, ok := global[t.Name]; ok {\n\t\tif _, ok := local[t.Name]; !ok {\n\t\t\tp.Imports.AddType(\u0026types.Type{\n\t\t\t\tKind: types.Protobuf,\n\t\t\t\tName: otherP.ProtoTypeName(),\n\t\t\t})\n\t\t}\n\t\treturn\n\t}\n\tif t.Name.Package == p.PackagePath {\n\t\t// Associate types only to their own package\n\t\tglobal[t.Name] = p\n\t}\n\tif _, ok := local[t.Name]; ok {\n\t\treturn\n\t}\n\t// don't recurse into existing proto types\n\tif isProto {\n\t\tp.Imports.AddType(t)\n\t\treturn\n\t}\n\n\tlocal[t.Name] = p\n\tfor _, m := range t.Members {\n\t\tif namer.IsPrivateGoName(m.Name) {\n\t\t\tcontinue\n\t\t}\n\t\tfield := \u0026protoField{}\n\t\ttag := reflect.StructTag(m.Tags).Get(\"protobuf\")\n\t\tif tag == \"-\" {\n\t\t\tcontinue\n\t\t}\n\t\tif err := protobufTagToField(tag, field, m, t, p.ProtoTypeName()); err == nil \u0026\u0026 field.Type != nil {\n\t\t\tassignGoTypeToProtoPackage(p, field.Type, local, global, optional)\n\t\t\tcontinue\n\t\t}\n\t\tassignGoTypeToProtoPackage(p, m.Type, local, global, optional)\n\t}\n\t// TODO: should methods be walked?\n\tif t.Elem != nil {\n\t\tassignGoTypeToProtoPackage(p, t.Elem, local, global, optional)\n\t}\n\tif t.Key != nil {\n\t\tassignGoTypeToProtoPackage(p, t.Key, local, global, optional)\n\t}\n\tif t.Underlying != nil {\n\t\tif t.Kind == types.Alias \u0026\u0026 isOptionalAlias(t) {\n\t\t\toptional[t.Name] = struct{}{}\n\t\t}\n\t\tassignGoTypeToProtoPackage(p, t.Underlying, local, global, optional)\n\t}\n}","line":{"from":103,"to":161}} {"id":100029988,"name":"isTypeApplicableToProtobuf","signature":"func isTypeApplicableToProtobuf(t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/namer.go","code":"// isTypeApplicableToProtobuf checks to see if a type is relevant for protobuf processing.\n// Currently, it filters out functions and private types.\nfunc isTypeApplicableToProtobuf(t *types.Type) bool {\n\t// skip functions -- we don't care about them for protobuf\n\tif t.Kind == types.Func || (t.Kind == types.DeclarationOf \u0026\u0026 t.Underlying.Kind == types.Func) {\n\t\treturn false\n\t}\n\t// skip private types\n\tif namer.IsPrivateGoName(t.Name.Name) {\n\t\treturn false\n\t}\n\n\treturn true\n}","line":{"from":163,"to":176}} {"id":100029989,"name":"AssignTypesToPackages","signature":"func (n *protobufNamer) AssignTypesToPackages(c *generator.Context) error","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/namer.go","code":"func (n *protobufNamer) AssignTypesToPackages(c *generator.Context) error {\n\tglobal := make(typeNameSet)\n\tfor _, p := range n.packages {\n\t\tlocal := make(typeNameSet)\n\t\toptional := make(map[types.Name]struct{})\n\t\tp.Imports = NewImportTracker(p.ProtoTypeName())\n\t\tfor _, t := range c.Order {\n\t\t\tif t.Name.Package != p.PackagePath {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !isTypeApplicableToProtobuf(t) {\n\t\t\t\t// skip types that we don't care about, like functions\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tassignGoTypeToProtoPackage(p, t, local, global, optional)\n\t\t}\n\t\tp.FilterTypes = make(map[types.Name]struct{})\n\t\tp.LocalNames = make(map[string]struct{})\n\t\tp.OptionalTypeNames = make(map[string]struct{})\n\t\tfor k, v := range local {\n\t\t\tif v == p {\n\t\t\t\tp.FilterTypes[k] = struct{}{}\n\t\t\t\tp.LocalNames[k.Name] = struct{}{}\n\t\t\t\tif _, ok := optional[k]; ok {\n\t\t\t\t\tp.OptionalTypeNames[k.Name] = struct{}{}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":178,"to":208}} {"id":100029990,"name":"newProtobufPackage","signature":"func newProtobufPackage(packagePath, packageName string, generateAll bool, omitFieldTypes map[types.Name]struct{}) *protobufPackage","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/package.go","code":"func newProtobufPackage(packagePath, packageName string, generateAll bool, omitFieldTypes map[types.Name]struct{}) *protobufPackage {\n\tpkg := \u0026protobufPackage{\n\t\tDefaultPackage: generator.DefaultPackage{\n\t\t\t// The protobuf package name (foo.bar.baz)\n\t\t\tPackageName: packageName,\n\t\t\t// A path segment relative to the GOPATH root (foo/bar/baz)\n\t\t\tPackagePath: packagePath,\n\t\t\tHeaderText: []byte(\n\t\t\t\t`\n// This file was autogenerated by go-to-protobuf. Do not edit it manually!\n\n`),\n\t\t\tPackageDocumentation: []byte(fmt.Sprintf(\n\t\t\t\t`// Package %s is an autogenerated protobuf IDL.\n`, packageName)),\n\t\t},\n\t\tGenerateAll: generateAll,\n\t\tOmitFieldTypes: omitFieldTypes,\n\t}\n\tpkg.FilterFunc = pkg.filterFunc\n\tpkg.GeneratorFunc = pkg.generatorFunc\n\treturn pkg\n}","line":{"from":32,"to":54}} {"id":100029991,"name":"Clean","signature":"func (p *protobufPackage) Clean(outputBase string) error","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/package.go","code":"func (p *protobufPackage) Clean(outputBase string) error {\n\tfor _, s := range []string{p.ImportPath(), p.OutputPath()} {\n\t\tif err := os.Remove(filepath.Join(outputBase, s)); err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":92,"to":99}} {"id":100029992,"name":"ProtoTypeName","signature":"func (p *protobufPackage) ProtoTypeName() types.Name","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/package.go","code":"func (p *protobufPackage) ProtoTypeName() types.Name {\n\treturn types.Name{\n\t\tName: p.Path(), // the go path \"foo/bar/baz\"\n\t\tPackage: p.Name(), // the protobuf package \"foo.bar.baz\"\n\t\tPath: p.ImportPath(), // the path of the import to get the proto\n\t}\n}","line":{"from":101,"to":107}} {"id":100029993,"name":"filterFunc","signature":"func (p *protobufPackage) filterFunc(c *generator.Context, t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/package.go","code":"func (p *protobufPackage) filterFunc(c *generator.Context, t *types.Type) bool {\n\tswitch t.Kind {\n\tcase types.Func, types.Chan:\n\t\treturn false\n\tcase types.Struct:\n\t\tif t.Name.Name == \"struct{}\" {\n\t\t\treturn false\n\t\t}\n\tcase types.Builtin:\n\t\treturn false\n\tcase types.Alias:\n\t\tif !isOptionalAlias(t) {\n\t\t\treturn false\n\t\t}\n\tcase types.Slice, types.Array, types.Map:\n\t\treturn false\n\tcase types.Pointer:\n\t\treturn false\n\t}\n\tif _, ok := isFundamentalProtoType(t); ok {\n\t\treturn false\n\t}\n\t_, ok := p.FilterTypes[t.Name]\n\treturn ok\n}","line":{"from":109,"to":133}} {"id":100029994,"name":"HasGoType","signature":"func (p *protobufPackage) HasGoType(name string) bool","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/package.go","code":"func (p *protobufPackage) HasGoType(name string) bool {\n\t_, ok := p.LocalNames[name]\n\treturn ok\n}","line":{"from":135,"to":138}} {"id":100029995,"name":"OptionalTypeName","signature":"func (p *protobufPackage) OptionalTypeName(name string) bool","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/package.go","code":"func (p *protobufPackage) OptionalTypeName(name string) bool {\n\t_, ok := p.OptionalTypeNames[name]\n\treturn ok\n}","line":{"from":140,"to":143}} {"id":100029996,"name":"ExtractGeneratedType","signature":"func (p *protobufPackage) ExtractGeneratedType(t *ast.TypeSpec) bool","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/package.go","code":"func (p *protobufPackage) ExtractGeneratedType(t *ast.TypeSpec) bool {\n\tif !p.HasGoType(t.Name.Name) {\n\t\treturn false\n\t}\n\n\tswitch s := t.Type.(type) {\n\tcase *ast.StructType:\n\t\tfor i, f := range s.Fields.List {\n\t\t\tif len(f.Tag.Value) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttag := strings.Trim(f.Tag.Value, \"`\")\n\t\t\tprotobufTag := reflect.StructTag(tag).Get(\"protobuf\")\n\t\t\tif len(protobufTag) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(f.Names) \u003e 1 {\n\t\t\t\tlog.Printf(\"WARNING: struct %s field %d %s: defined multiple names but single protobuf tag\", t.Name.Name, i, f.Names[0].Name)\n\t\t\t\t// TODO hard error?\n\t\t\t}\n\t\t\tif p.StructTags == nil {\n\t\t\t\tp.StructTags = make(map[string]map[string]string)\n\t\t\t}\n\t\t\tm := p.StructTags[t.Name.Name]\n\t\t\tif m == nil {\n\t\t\t\tm = make(map[string]string)\n\t\t\t\tp.StructTags[t.Name.Name] = m\n\t\t\t}\n\t\t\tm[f.Names[0].Name] = tag\n\t\t}\n\tdefault:\n\t\tlog.Printf(\"WARNING: unexpected Go AST type definition: %#v\", t)\n\t}\n\n\treturn true\n}","line":{"from":145,"to":180}} {"id":100029997,"name":"generatorFunc","signature":"func (p *protobufPackage) generatorFunc(c *generator.Context) []generator.Generator","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/package.go","code":"func (p *protobufPackage) generatorFunc(c *generator.Context) []generator.Generator {\n\tgenerators := []generator.Generator{}\n\n\tp.Imports.AddNullable()\n\n\tgenerators = append(generators, \u0026genProtoIDL{\n\t\tDefaultGen: generator.DefaultGen{\n\t\t\tOptionalName: \"generated\",\n\t\t},\n\t\tlocalPackage: types.Name{Package: p.PackageName, Path: p.PackagePath},\n\t\tlocalGoPackage: types.Name{Package: p.PackagePath, Name: p.GoPackageName()},\n\t\timports: p.Imports,\n\t\tgenerateAll: p.GenerateAll,\n\t\tomitGogo: p.OmitGogo,\n\t\tomitFieldTypes: p.OmitFieldTypes,\n\t})\n\treturn generators\n}","line":{"from":182,"to":199}} {"id":100029998,"name":"GoPackageName","signature":"func (p *protobufPackage) GoPackageName() string","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/package.go","code":"func (p *protobufPackage) GoPackageName() string {\n\treturn filepath.Base(p.PackagePath)\n}","line":{"from":201,"to":203}} {"id":100029999,"name":"ImportPath","signature":"func (p *protobufPackage) ImportPath() string","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/package.go","code":"func (p *protobufPackage) ImportPath() string {\n\treturn filepath.Join(p.PackagePath, \"generated.proto\")\n}","line":{"from":205,"to":207}} {"id":100030000,"name":"OutputPath","signature":"func (p *protobufPackage) OutputPath() string","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/package.go","code":"func (p *protobufPackage) OutputPath() string {\n\treturn filepath.Join(p.PackagePath, \"generated.pb.go\")\n}","line":{"from":209,"to":211}} {"id":100030001,"name":"rewriteFile","signature":"func rewriteFile(name string, header []byte, rewriteFn func(*token.FileSet, *ast.File) error) error","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/parser.go","code":"func rewriteFile(name string, header []byte, rewriteFn func(*token.FileSet, *ast.File) error) error {\n\tfset := token.NewFileSet()\n\tsrc, err := os.ReadFile(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfile, err := parser.ParseFile(fset, name, src, parser.DeclarationErrors|parser.ParseComments)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := rewriteFn(fset, file); err != nil {\n\t\treturn err\n\t}\n\n\tb := \u0026bytes.Buffer{}\n\tb.Write(header)\n\tif err := printer.Fprint(b, fset, file); err != nil {\n\t\treturn err\n\t}\n\n\tbody, err := format.Source(b.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf, err := os.OpenFile(name, os.O_WRONLY|os.O_TRUNC, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tif _, err := f.Write(body); err != nil {\n\t\treturn err\n\t}\n\treturn f.Close()\n}","line":{"from":35,"to":70}} {"id":100030002,"name":"RewriteGeneratedGogoProtobufFile","signature":"func RewriteGeneratedGogoProtobufFile(name string, extractFn ExtractFunc, optionalFn OptionalFunc, header []byte) error","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/parser.go","code":"func RewriteGeneratedGogoProtobufFile(name string, extractFn ExtractFunc, optionalFn OptionalFunc, header []byte) error {\n\treturn rewriteFile(name, header, func(fset *token.FileSet, file *ast.File) error {\n\t\tcmap := ast.NewCommentMap(fset, file, file.Comments)\n\n\t\t// transform methods that point to optional maps or slices\n\t\tfor _, d := range file.Decls {\n\t\t\trewriteOptionalMethods(d, optionalFn)\n\t\t}\n\n\t\t// remove types that are already declared\n\t\tdecls := []ast.Decl{}\n\t\tfor _, d := range file.Decls {\n\t\t\tif dropExistingTypeDeclarations(d, extractFn) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif dropEmptyImportDeclarations(d) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdecls = append(decls, d)\n\t\t}\n\t\tfile.Decls = decls\n\n\t\t// remove unmapped comments\n\t\tfile.Comments = cmap.Filter(file).Comments()\n\t\treturn nil\n\t})\n}","line":{"from":80,"to":106}} {"id":100030003,"name":"rewriteOptionalMethods","signature":"func rewriteOptionalMethods(decl ast.Decl, isOptional OptionalFunc)","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/parser.go","code":"// rewriteOptionalMethods makes specific mutations to marshaller methods that belong to types identified\n// as being \"optional\" (they may be nil on the wire). This allows protobuf to serialize a map or slice and\n// properly discriminate between empty and nil (which is not possible in protobuf).\n// TODO: move into upstream gogo-protobuf once https://github.com/gogo/protobuf/issues/181\n// has agreement\nfunc rewriteOptionalMethods(decl ast.Decl, isOptional OptionalFunc) {\n\tswitch t := decl.(type) {\n\tcase *ast.FuncDecl:\n\t\tident, ptr, ok := receiver(t)\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\n\t\t// correct initialization of the form `m.Field = \u0026OptionalType{}` to\n\t\t// `m.Field = OptionalType{}`\n\t\tif t.Name.Name == \"Unmarshal\" {\n\t\t\tast.Walk(optionalAssignmentVisitor{fn: isOptional}, t.Body)\n\t\t}\n\n\t\tif !isOptional(ident.Name) {\n\t\t\treturn\n\t\t}\n\n\t\tswitch t.Name.Name {\n\t\tcase \"Unmarshal\":\n\t\t\tast.Walk(\u0026optionalItemsVisitor{}, t.Body)\n\t\tcase \"MarshalTo\", \"Size\", \"String\", \"MarshalToSizedBuffer\":\n\t\t\tast.Walk(\u0026optionalItemsVisitor{}, t.Body)\n\t\t\tfallthrough\n\t\tcase \"Marshal\":\n\t\t\t// if the method has a pointer receiver, set it back to a normal receiver\n\t\t\tif ptr {\n\t\t\t\tt.Recv.List[0].Type = ident\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":108,"to":144}} {"id":100030004,"name":"Visit","signature":"func (v optionalAssignmentVisitor) Visit(n ast.Node) ast.Visitor","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/parser.go","code":"// Visit walks the provided node, transforming field initializations of the form\n// m.Field = \u0026OptionalType{} -\u003e m.Field = OptionalType{}\nfunc (v optionalAssignmentVisitor) Visit(n ast.Node) ast.Visitor {\n\tswitch t := n.(type) {\n\tcase *ast.AssignStmt:\n\t\tif len(t.Lhs) == 1 \u0026\u0026 len(t.Rhs) == 1 {\n\t\t\tif !isFieldSelector(t.Lhs[0], \"m\", \"\") {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tunary, ok := t.Rhs[0].(*ast.UnaryExpr)\n\t\t\tif !ok || unary.Op != token.AND {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tcomposite, ok := unary.X.(*ast.CompositeLit)\n\t\t\tif !ok || composite.Type == nil || len(composite.Elts) != 0 {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif ident, ok := composite.Type.(*ast.Ident); ok \u0026\u0026 v.fn(ident.Name) {\n\t\t\t\tt.Rhs[0] = composite\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\treturn v\n}","line":{"from":150,"to":174}} {"id":100030005,"name":"Visit","signature":"func (v *optionalItemsVisitor) Visit(n ast.Node) ast.Visitor","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/parser.go","code":"// Visit walks the provided node, looking for specific patterns to transform that match\n// the effective outcome of turning struct{ map[x]y || []x } into map[x]y or []x.\nfunc (v *optionalItemsVisitor) Visit(n ast.Node) ast.Visitor {\n\tswitch t := n.(type) {\n\tcase *ast.RangeStmt:\n\t\tif isFieldSelector(t.X, \"m\", \"Items\") {\n\t\t\tt.X = \u0026ast.Ident{Name: \"m\"}\n\t\t}\n\tcase *ast.AssignStmt:\n\t\tif len(t.Lhs) == 1 \u0026\u0026 len(t.Rhs) == 1 {\n\t\t\tswitch lhs := t.Lhs[0].(type) {\n\t\t\tcase *ast.IndexExpr:\n\t\t\t\tif isFieldSelector(lhs.X, \"m\", \"Items\") {\n\t\t\t\t\tlhs.X = \u0026ast.StarExpr{X: \u0026ast.Ident{Name: \"m\"}}\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tif isFieldSelector(t.Lhs[0], \"m\", \"Items\") {\n\t\t\t\t\tt.Lhs[0] = \u0026ast.StarExpr{X: \u0026ast.Ident{Name: \"m\"}}\n\t\t\t\t}\n\t\t\t}\n\t\t\tswitch rhs := t.Rhs[0].(type) {\n\t\t\tcase *ast.CallExpr:\n\t\t\t\tif ident, ok := rhs.Fun.(*ast.Ident); ok \u0026\u0026 ident.Name == \"append\" {\n\t\t\t\t\tast.Walk(v, rhs)\n\t\t\t\t\tif len(rhs.Args) \u003e 0 {\n\t\t\t\t\t\tswitch arg := rhs.Args[0].(type) {\n\t\t\t\t\t\tcase *ast.Ident:\n\t\t\t\t\t\t\tif arg.Name == \"m\" {\n\t\t\t\t\t\t\t\trhs.Args[0] = \u0026ast.StarExpr{X: \u0026ast.Ident{Name: \"m\"}}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase *ast.IfStmt:\n\t\tswitch cond := t.Cond.(type) {\n\t\tcase *ast.BinaryExpr:\n\t\t\tif cond.Op == token.EQL {\n\t\t\t\tif isFieldSelector(cond.X, \"m\", \"Items\") \u0026\u0026 isIdent(cond.Y, \"nil\") {\n\t\t\t\t\tcond.X = \u0026ast.StarExpr{X: \u0026ast.Ident{Name: \"m\"}}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif t.Init != nil {\n\t\t\t// Find form:\n\t\t\t// if err := m[len(m.Items)-1].Unmarshal(data[iNdEx:postIndex]); err != nil {\n\t\t\t// \treturn err\n\t\t\t// }\n\t\t\tswitch s := t.Init.(type) {\n\t\t\tcase *ast.AssignStmt:\n\t\t\t\tif call, ok := s.Rhs[0].(*ast.CallExpr); ok {\n\t\t\t\t\tif sel, ok := call.Fun.(*ast.SelectorExpr); ok {\n\t\t\t\t\t\tif x, ok := sel.X.(*ast.IndexExpr); ok {\n\t\t\t\t\t\t\t// m[] -\u003e (*m)[]\n\t\t\t\t\t\t\tif sel2, ok := x.X.(*ast.SelectorExpr); ok {\n\t\t\t\t\t\t\t\tif ident, ok := sel2.X.(*ast.Ident); ok \u0026\u0026 ident.Name == \"m\" {\n\t\t\t\t\t\t\t\t\tx.X = \u0026ast.StarExpr{X: \u0026ast.Ident{Name: \"m\"}}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// len(m.Items) -\u003e len(*m)\n\t\t\t\t\t\t\tif bin, ok := x.Index.(*ast.BinaryExpr); ok {\n\t\t\t\t\t\t\t\tif call2, ok := bin.X.(*ast.CallExpr); ok \u0026\u0026 len(call2.Args) == 1 {\n\t\t\t\t\t\t\t\t\tif isFieldSelector(call2.Args[0], \"m\", \"Items\") {\n\t\t\t\t\t\t\t\t\t\tcall2.Args[0] = \u0026ast.StarExpr{X: \u0026ast.Ident{Name: \"m\"}}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase *ast.IndexExpr:\n\t\tif isFieldSelector(t.X, \"m\", \"Items\") {\n\t\t\tt.X = \u0026ast.Ident{Name: \"m\"}\n\t\t\treturn nil\n\t\t}\n\tcase *ast.CallExpr:\n\t\tchanged := false\n\t\tfor i := range t.Args {\n\t\t\tif isFieldSelector(t.Args[i], \"m\", \"Items\") {\n\t\t\t\tt.Args[i] = \u0026ast.Ident{Name: \"m\"}\n\t\t\t\tchanged = true\n\t\t\t}\n\t\t}\n\t\tif changed {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn v\n}","line":{"from":178,"to":270}} {"id":100030006,"name":"isFieldSelector","signature":"func isFieldSelector(n ast.Expr, name, field string) bool","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/parser.go","code":"func isFieldSelector(n ast.Expr, name, field string) bool {\n\ts, ok := n.(*ast.SelectorExpr)\n\tif !ok || s.Sel == nil || (field != \"\" \u0026\u0026 s.Sel.Name != field) {\n\t\treturn false\n\t}\n\treturn isIdent(s.X, name)\n}","line":{"from":272,"to":278}} {"id":100030007,"name":"isIdent","signature":"func isIdent(n ast.Expr, value string) bool","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/parser.go","code":"func isIdent(n ast.Expr, value string) bool {\n\tident, ok := n.(*ast.Ident)\n\treturn ok \u0026\u0026 ident.Name == value\n}","line":{"from":280,"to":283}} {"id":100030008,"name":"receiver","signature":"func receiver(f *ast.FuncDecl) (ident *ast.Ident, pointer bool, ok bool)","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/parser.go","code":"func receiver(f *ast.FuncDecl) (ident *ast.Ident, pointer bool, ok bool) {\n\tif f.Recv == nil || len(f.Recv.List) != 1 {\n\t\treturn nil, false, false\n\t}\n\tswitch t := f.Recv.List[0].Type.(type) {\n\tcase *ast.StarExpr:\n\t\tidentity, ok := t.X.(*ast.Ident)\n\t\tif !ok {\n\t\t\treturn nil, false, false\n\t\t}\n\t\treturn identity, true, true\n\tcase *ast.Ident:\n\t\treturn t, false, true\n\t}\n\treturn nil, false, false\n}","line":{"from":285,"to":300}} {"id":100030009,"name":"dropExistingTypeDeclarations","signature":"func dropExistingTypeDeclarations(decl ast.Decl, extractFn ExtractFunc) bool","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/parser.go","code":"// dropExistingTypeDeclarations removes any type declaration for which extractFn returns true. The function\n// returns true if the entire declaration should be dropped.\nfunc dropExistingTypeDeclarations(decl ast.Decl, extractFn ExtractFunc) bool {\n\tswitch t := decl.(type) {\n\tcase *ast.GenDecl:\n\t\tif t.Tok != token.TYPE {\n\t\t\treturn false\n\t\t}\n\t\tspecs := []ast.Spec{}\n\t\tfor _, s := range t.Specs {\n\t\t\tswitch spec := s.(type) {\n\t\t\tcase *ast.TypeSpec:\n\t\t\t\tif extractFn(spec) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tspecs = append(specs, spec)\n\t\t\t}\n\t\t}\n\t\tif len(specs) == 0 {\n\t\t\treturn true\n\t\t}\n\t\tt.Specs = specs\n\t}\n\treturn false\n}","line":{"from":302,"to":326}} {"id":100030010,"name":"dropEmptyImportDeclarations","signature":"func dropEmptyImportDeclarations(decl ast.Decl) bool","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/parser.go","code":"// dropEmptyImportDeclarations strips any generated but no-op imports from the generated code\n// to prevent generation from being able to define side-effects. The function returns true\n// if the entire declaration should be dropped.\nfunc dropEmptyImportDeclarations(decl ast.Decl) bool {\n\tswitch t := decl.(type) {\n\tcase *ast.GenDecl:\n\t\tif t.Tok != token.IMPORT {\n\t\t\treturn false\n\t\t}\n\t\tspecs := []ast.Spec{}\n\t\tfor _, s := range t.Specs {\n\t\t\tswitch spec := s.(type) {\n\t\t\tcase *ast.ImportSpec:\n\t\t\t\tif spec.Name != nil \u0026\u0026 spec.Name.Name == \"_\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tspecs = append(specs, spec)\n\t\t\t}\n\t\t}\n\t\tif len(specs) == 0 {\n\t\t\treturn true\n\t\t}\n\t\tt.Specs = specs\n\t}\n\treturn false\n}","line":{"from":328,"to":353}} {"id":100030011,"name":"RewriteTypesWithProtobufStructTags","signature":"func RewriteTypesWithProtobufStructTags(name string, structTags map[string]map[string]string) error","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/parser.go","code":"func RewriteTypesWithProtobufStructTags(name string, structTags map[string]map[string]string) error {\n\treturn rewriteFile(name, []byte{}, func(fset *token.FileSet, file *ast.File) error {\n\t\tallErrs := []error{}\n\n\t\t// set any new struct tags\n\t\tfor _, d := range file.Decls {\n\t\t\tif errs := updateStructTags(d, structTags, []string{\"protobuf\"}); len(errs) \u003e 0 {\n\t\t\t\tallErrs = append(allErrs, errs...)\n\t\t\t}\n\t\t}\n\n\t\tif len(allErrs) \u003e 0 {\n\t\t\tvar s string\n\t\t\tfor _, err := range allErrs {\n\t\t\t\ts += err.Error() + \"\\n\"\n\t\t\t}\n\t\t\treturn errors.New(s)\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":355,"to":375}} {"id":100030012,"name":"getFieldName","signature":"func getFieldName(expr ast.Expr, structname string) (name string, err error)","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/parser.go","code":"func getFieldName(expr ast.Expr, structname string) (name string, err error) {\n\tfor {\n\t\tswitch t := expr.(type) {\n\t\tcase *ast.Ident:\n\t\t\treturn t.Name, nil\n\t\tcase *ast.SelectorExpr:\n\t\t\treturn t.Sel.Name, nil\n\t\tcase *ast.StarExpr:\n\t\t\texpr = t.X\n\t\tdefault:\n\t\t\treturn \"\", fmt.Errorf(\"unable to get name for tag from struct %q, field %#v\", structname, t)\n\t\t}\n\t}\n}","line":{"from":377,"to":390}} {"id":100030013,"name":"updateStructTags","signature":"func updateStructTags(decl ast.Decl, structTags map[string]map[string]string, toCopy []string) []error","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/parser.go","code":"func updateStructTags(decl ast.Decl, structTags map[string]map[string]string, toCopy []string) []error {\n\tvar errs []error\n\tt, ok := decl.(*ast.GenDecl)\n\tif !ok {\n\t\treturn nil\n\t}\n\tif t.Tok != token.TYPE {\n\t\treturn nil\n\t}\n\n\tfor _, s := range t.Specs {\n\t\tspec, ok := s.(*ast.TypeSpec)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\ttypeName := spec.Name.Name\n\t\tfieldTags, ok := structTags[typeName]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tst, ok := spec.Type.(*ast.StructType)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor i := range st.Fields.List {\n\t\t\tf := st.Fields.List[i]\n\t\t\tvar name string\n\t\t\tvar err error\n\t\t\tif len(f.Names) == 0 {\n\t\t\t\tname, err = getFieldName(f.Type, spec.Name.Name)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrs = append(errs, err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tname = f.Names[0].Name\n\t\t\t}\n\t\t\tvalue, ok := fieldTags[name]\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvar tags customreflect.StructTags\n\t\t\tif f.Tag != nil {\n\t\t\t\toldTags, err := customreflect.ParseStructTags(strings.Trim(f.Tag.Value, \"`\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\terrs = append(errs, fmt.Errorf(\"unable to read struct tag from struct %q, field %q: %v\", spec.Name.Name, name, err))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\ttags = oldTags\n\t\t\t}\n\t\t\tfor _, name := range toCopy {\n\t\t\t\t// don't overwrite existing tags\n\t\t\t\tif tags.Has(name) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// append new tags\n\t\t\t\tif v := reflect.StructTag(value).Get(name); len(v) \u003e 0 {\n\t\t\t\t\ttags = append(tags, customreflect.StructTag{Name: name, Value: v})\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(tags) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif f.Tag == nil {\n\t\t\t\tf.Tag = \u0026ast.BasicLit{}\n\t\t\t}\n\t\t\tf.Tag.Value = tags.String()\n\t\t}\n\t}\n\treturn errs\n}","line":{"from":392,"to":463}} {"id":100030014,"name":"extractBoolTagOrDie","signature":"func extractBoolTagOrDie(key string, lines []string) bool","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protobuf/tags.go","code":"// extractBoolTagOrDie gets the comment-tags for the key and asserts that, if\n// it exists, the value is boolean. If the tag did not exist, it returns\n// false.\nfunc extractBoolTagOrDie(key string, lines []string) bool {\n\tval, err := types.ExtractSingleBoolCommentTag(\"+\", key, false, lines)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\treturn val\n}","line":{"from":24,"to":33}} {"id":100030015,"name":"main","signature":"func main()","file":"staging/src/k8s.io/code-generator/cmd/go-to-protobuf/protoc-gen-gogo/main.go","code":"func main() {\n\t// read input\n\trequest := command.Read()\n\n\t// if we're given paths as inputs, generate .pb.go files based on those paths\n\tfor _, file := range request.FileToGenerate {\n\t\tif strings.Contains(file, \"/\") {\n\t\t\tparam := \"paths=source_relative\"\n\t\t\trequest.Parameter = \u0026param\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// generate\n\tcommand.Write(command.Generate(request))\n}","line":{"from":32,"to":47}} {"id":100030016,"name":"main","signature":"func main()","file":"staging/src/k8s.io/code-generator/cmd/import-boss/main.go","code":"func main() {\n\tklog.InitFlags(nil)\n\targuments := args.Default()\n\n\tpflag.CommandLine.BoolVar(\u0026arguments.IncludeTestFiles, \"include-test-files\", false, \"If true, include *_test.go files.\")\n\n\tif err := arguments.Execute(\n\t\tgenerators.NameSystems(),\n\t\tgenerators.DefaultNameSystem(),\n\t\tgenerators.Packages,\n\t); err != nil {\n\t\tklog.Errorf(\"Error: %v\", err)\n\t\tos.Exit(1)\n\t}\n\tklog.V(2).Info(\"Completed successfully.\")\n}","line":{"from":30,"to":45}} {"id":100030017,"name":"NewDefaults","signature":"func NewDefaults() (*args.GeneratorArgs, *CustomArgs)","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/args/args.go","code":"// NewDefaults returns default arguments for the generator.\nfunc NewDefaults() (*args.GeneratorArgs, *CustomArgs) {\n\tgenericArgs := args.Default().WithoutDefaultFlagParsing()\n\tcustomArgs := \u0026CustomArgs{\n\t\tSingleDirectory: false,\n\t\tPluralExceptions: []string{\"Endpoints:Endpoints\"},\n\t}\n\tgenericArgs.CustomArgs = customArgs\n\n\tif pkg := codegenutil.CurrentPackage(); len(pkg) != 0 {\n\t\tgenericArgs.OutputPackagePath = path.Join(pkg, \"pkg/client/informers\")\n\t\tcustomArgs.VersionedClientSetPackage = path.Join(pkg, \"pkg/client/clientset/versioned\")\n\t\tcustomArgs.InternalClientSetPackage = path.Join(pkg, \"pkg/client/clientset/internalversion\")\n\t\tcustomArgs.ListersPackage = path.Join(pkg, \"pkg/client/listers\")\n\t}\n\n\treturn genericArgs, customArgs\n}","line":{"from":40,"to":57}} {"id":100030018,"name":"AddFlags","signature":"func (ca *CustomArgs) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/args/args.go","code":"// AddFlags add the generator flags to the flag set.\nfunc (ca *CustomArgs) AddFlags(fs *pflag.FlagSet) {\n\tfs.StringVar(\u0026ca.InternalClientSetPackage, \"internal-clientset-package\", ca.InternalClientSetPackage, \"the full package name for the internal clientset to use\")\n\tfs.StringVar(\u0026ca.VersionedClientSetPackage, \"versioned-clientset-package\", ca.VersionedClientSetPackage, \"the full package name for the versioned clientset to use\")\n\tfs.StringVar(\u0026ca.ListersPackage, \"listers-package\", ca.ListersPackage, \"the full package name for the listers to use\")\n\tfs.BoolVar(\u0026ca.SingleDirectory, \"single-directory\", ca.SingleDirectory, \"if true, omit the intermediate \\\"internalversion\\\" and \\\"externalversions\\\" subdirectories\")\n\tfs.StringSliceVar(\u0026ca.PluralExceptions, \"plural-exceptions\", ca.PluralExceptions, \"list of comma separated plural exception definitions in Type:PluralizedType format\")\n}","line":{"from":59,"to":66}} {"id":100030019,"name":"Validate","signature":"func Validate(genericArgs *args.GeneratorArgs) error","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/args/args.go","code":"// Validate checks the given arguments.\nfunc Validate(genericArgs *args.GeneratorArgs) error {\n\tcustomArgs := genericArgs.CustomArgs.(*CustomArgs)\n\n\tif len(genericArgs.OutputPackagePath) == 0 {\n\t\treturn fmt.Errorf(\"output package cannot be empty\")\n\t}\n\tif len(customArgs.VersionedClientSetPackage) == 0 {\n\t\treturn fmt.Errorf(\"versioned clientset package cannot be empty\")\n\t}\n\tif len(customArgs.ListersPackage) == 0 {\n\t\treturn fmt.Errorf(\"listers package cannot be empty\")\n\t}\n\n\treturn nil\n}","line":{"from":68,"to":83}} {"id":100030020,"name":"Filter","signature":"func (g *factoryGenerator) Filter(c *generator.Context, t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/factory.go","code":"func (g *factoryGenerator) Filter(c *generator.Context, t *types.Type) bool {\n\tif !g.filtered {\n\t\tg.filtered = true\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":46,"to":52}} {"id":100030021,"name":"Namers","signature":"func (g *factoryGenerator) Namers(c *generator.Context) namer.NameSystems","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/factory.go","code":"func (g *factoryGenerator) Namers(c *generator.Context) namer.NameSystems {\n\treturn namer.NameSystems{\n\t\t\"raw\": namer.NewRawNamer(g.outputPackage, g.imports),\n\t}\n}","line":{"from":54,"to":58}} {"id":100030022,"name":"Imports","signature":"func (g *factoryGenerator) Imports(c *generator.Context) (imports []string)","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/factory.go","code":"func (g *factoryGenerator) Imports(c *generator.Context) (imports []string) {\n\timports = append(imports, g.imports.ImportLines()...)\n\treturn\n}","line":{"from":60,"to":63}} {"id":100030023,"name":"GenerateType","signature":"func (g *factoryGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/factory.go","code":"func (g *factoryGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {\n\tsw := generator.NewSnippetWriter(w, c, \"{{\", \"}}\")\n\n\tklog.V(5).Infof(\"processing type %v\", t)\n\n\tgvInterfaces := make(map[string]*types.Type)\n\tgvNewFuncs := make(map[string]*types.Type)\n\tfor groupPkgName := range g.groupVersions {\n\t\tgvInterfaces[groupPkgName] = c.Universe.Type(types.Name{Package: path.Join(g.outputPackage, groupPkgName), Name: \"Interface\"})\n\t\tgvNewFuncs[groupPkgName] = c.Universe.Function(types.Name{Package: path.Join(g.outputPackage, groupPkgName), Name: \"New\"})\n\t}\n\tm := map[string]interface{}{\n\t\t\"cacheSharedIndexInformer\": c.Universe.Type(cacheSharedIndexInformer),\n\t\t\"groupVersions\": g.groupVersions,\n\t\t\"gvInterfaces\": gvInterfaces,\n\t\t\"gvNewFuncs\": gvNewFuncs,\n\t\t\"gvGoNames\": g.gvGoNames,\n\t\t\"interfacesNewInformerFunc\": c.Universe.Type(types.Name{Package: g.internalInterfacesPackage, Name: \"NewInformerFunc\"}),\n\t\t\"interfacesTweakListOptionsFunc\": c.Universe.Type(types.Name{Package: g.internalInterfacesPackage, Name: \"TweakListOptionsFunc\"}),\n\t\t\"informerFactoryInterface\": c.Universe.Type(types.Name{Package: g.internalInterfacesPackage, Name: \"SharedInformerFactory\"}),\n\t\t\"clientSetInterface\": c.Universe.Type(types.Name{Package: g.clientSetPackage, Name: \"Interface\"}),\n\t\t\"reflectType\": c.Universe.Type(reflectType),\n\t\t\"runtimeObject\": c.Universe.Type(runtimeObject),\n\t\t\"schemaGroupVersionResource\": c.Universe.Type(schemaGroupVersionResource),\n\t\t\"syncMutex\": c.Universe.Type(syncMutex),\n\t\t\"timeDuration\": c.Universe.Type(timeDuration),\n\t\t\"namespaceAll\": c.Universe.Type(metav1NamespaceAll),\n\t\t\"object\": c.Universe.Type(metav1Object),\n\t}\n\n\tsw.Do(sharedInformerFactoryStruct, m)\n\tsw.Do(sharedInformerFactoryInterface, m)\n\n\treturn sw.Error()\n}","line":{"from":65,"to":99}} {"id":100030024,"name":"Filter","signature":"func (g *factoryInterfaceGenerator) Filter(c *generator.Context, t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/factoryinterface.go","code":"func (g *factoryInterfaceGenerator) Filter(c *generator.Context, t *types.Type) bool {\n\tif !g.filtered {\n\t\tg.filtered = true\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":41,"to":47}} {"id":100030025,"name":"Namers","signature":"func (g *factoryInterfaceGenerator) Namers(c *generator.Context) namer.NameSystems","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/factoryinterface.go","code":"func (g *factoryInterfaceGenerator) Namers(c *generator.Context) namer.NameSystems {\n\treturn namer.NameSystems{\n\t\t\"raw\": namer.NewRawNamer(g.outputPackage, g.imports),\n\t}\n}","line":{"from":49,"to":53}} {"id":100030026,"name":"Imports","signature":"func (g *factoryInterfaceGenerator) Imports(c *generator.Context) (imports []string)","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/factoryinterface.go","code":"func (g *factoryInterfaceGenerator) Imports(c *generator.Context) (imports []string) {\n\timports = append(imports, g.imports.ImportLines()...)\n\treturn\n}","line":{"from":55,"to":58}} {"id":100030027,"name":"GenerateType","signature":"func (g *factoryInterfaceGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/factoryinterface.go","code":"func (g *factoryInterfaceGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {\n\tsw := generator.NewSnippetWriter(w, c, \"{{\", \"}}\")\n\n\tklog.V(5).Infof(\"processing type %v\", t)\n\n\tm := map[string]interface{}{\n\t\t\"cacheSharedIndexInformer\": c.Universe.Type(cacheSharedIndexInformer),\n\t\t\"clientSetPackage\": c.Universe.Type(types.Name{Package: g.clientSetPackage, Name: \"Interface\"}),\n\t\t\"runtimeObject\": c.Universe.Type(runtimeObject),\n\t\t\"timeDuration\": c.Universe.Type(timeDuration),\n\t\t\"v1ListOptions\": c.Universe.Type(v1ListOptions),\n\t}\n\n\tsw.Do(externalSharedInformerFactoryInterface, m)\n\n\treturn sw.Error()\n}","line":{"from":60,"to":76}} {"id":100030028,"name":"Filter","signature":"func (g *genericGenerator) Filter(c *generator.Context, t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/generic.go","code":"func (g *genericGenerator) Filter(c *generator.Context, t *types.Type) bool {\n\tif !g.filtered {\n\t\tg.filtered = true\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":45,"to":51}} {"id":100030029,"name":"Namers","signature":"func (g *genericGenerator) Namers(c *generator.Context) namer.NameSystems","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/generic.go","code":"func (g *genericGenerator) Namers(c *generator.Context) namer.NameSystems {\n\treturn namer.NameSystems{\n\t\t\"raw\": namer.NewRawNamer(g.outputPackage, g.imports),\n\t\t\"allLowercasePlural\": namer.NewAllLowercasePluralNamer(g.pluralExceptions),\n\t\t\"publicPlural\": namer.NewPublicPluralNamer(g.pluralExceptions),\n\t\t\"resource\": codegennamer.NewTagOverrideNamer(\"resourceName\", namer.NewAllLowercasePluralNamer(g.pluralExceptions)),\n\t}\n}","line":{"from":53,"to":60}} {"id":100030030,"name":"Imports","signature":"func (g *genericGenerator) Imports(c *generator.Context) (imports []string)","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/generic.go","code":"func (g *genericGenerator) Imports(c *generator.Context) (imports []string) {\n\timports = append(imports, g.imports.ImportLines()...)\n\timports = append(imports, \"fmt\")\n\treturn\n}","line":{"from":62,"to":66}} {"id":100030031,"name":"Len","signature":"func (g groupSort) Len() int { return len(g) }","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/generic.go","code":"func (g groupSort) Len() int { return len(g) }","line":{"from":76,"to":76}} {"id":100030032,"name":"Less","signature":"func (g groupSort) Less(i, j int) bool","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/generic.go","code":"func (g groupSort) Less(i, j int) bool {\n\treturn strings.ToLower(g[i].Name) \u003c strings.ToLower(g[j].Name)\n}","line":{"from":77,"to":79}} {"id":100030033,"name":"Swap","signature":"func (g groupSort) Swap(i, j int) { g[i], g[j] = g[j], g[i] }","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/generic.go","code":"func (g groupSort) Swap(i, j int) { g[i], g[j] = g[j], g[i] }","line":{"from":80,"to":80}} {"id":100030034,"name":"Len","signature":"func (v versionSort) Len() int { return len(v) }","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/generic.go","code":"func (v versionSort) Len() int { return len(v) }","line":{"from":90,"to":90}} {"id":100030035,"name":"Less","signature":"func (v versionSort) Less(i, j int) bool","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/generic.go","code":"func (v versionSort) Less(i, j int) bool {\n\treturn strings.ToLower(v[i].Name) \u003c strings.ToLower(v[j].Name)\n}","line":{"from":91,"to":93}} {"id":100030036,"name":"Swap","signature":"func (v versionSort) Swap(i, j int) { v[i], v[j] = v[j], v[i] }","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/generic.go","code":"func (v versionSort) Swap(i, j int) { v[i], v[j] = v[j], v[i] }","line":{"from":94,"to":94}} {"id":100030037,"name":"GenerateType","signature":"func (g *genericGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/generic.go","code":"func (g *genericGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {\n\tsw := generator.NewSnippetWriter(w, c, \"{{\", \"}}\")\n\n\tgroups := []group{}\n\tschemeGVs := make(map[*version]*types.Type)\n\n\torderer := namer.Orderer{Namer: namer.NewPrivateNamer(0)}\n\tfor groupPackageName, groupVersions := range g.groupVersions {\n\t\tgroup := group{\n\t\t\tGroupGoName: g.groupGoNames[groupPackageName],\n\t\t\tName: groupVersions.Group.NonEmpty(),\n\t\t\tVersions: []*version{},\n\t\t}\n\t\tfor _, v := range groupVersions.Versions {\n\t\t\tgv := clientgentypes.GroupVersion{Group: groupVersions.Group, Version: v.Version}\n\t\t\tversion := \u0026version{\n\t\t\t\tName: v.Version.NonEmpty(),\n\t\t\t\tGoName: namer.IC(v.Version.NonEmpty()),\n\t\t\t\tResources: orderer.OrderTypes(g.typesForGroupVersion[gv]),\n\t\t\t}\n\t\t\tfunc() {\n\t\t\t\tschemeGVs[version] = c.Universe.Variable(types.Name{Package: g.typesForGroupVersion[gv][0].Name.Package, Name: \"SchemeGroupVersion\"})\n\t\t\t}()\n\t\t\tgroup.Versions = append(group.Versions, version)\n\t\t}\n\t\tsort.Sort(versionSort(group.Versions))\n\t\tgroups = append(groups, group)\n\t}\n\tsort.Sort(groupSort(groups))\n\n\tm := map[string]interface{}{\n\t\t\"cacheGenericLister\": c.Universe.Type(cacheGenericLister),\n\t\t\"cacheNewGenericLister\": c.Universe.Function(cacheNewGenericLister),\n\t\t\"cacheSharedIndexInformer\": c.Universe.Type(cacheSharedIndexInformer),\n\t\t\"groups\": groups,\n\t\t\"schemeGVs\": schemeGVs,\n\t\t\"schemaGroupResource\": c.Universe.Type(schemaGroupResource),\n\t\t\"schemaGroupVersionResource\": c.Universe.Type(schemaGroupVersionResource),\n\t}\n\n\tsw.Do(genericInformer, m)\n\tsw.Do(forResource, m)\n\n\treturn sw.Error()\n}","line":{"from":96,"to":140}} {"id":100030038,"name":"Filter","signature":"func (g *groupInterfaceGenerator) Filter(c *generator.Context, t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/groupinterface.go","code":"func (g *groupInterfaceGenerator) Filter(c *generator.Context, t *types.Type) bool {\n\tif !g.filtered {\n\t\tg.filtered = true\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":42,"to":48}} {"id":100030039,"name":"Namers","signature":"func (g *groupInterfaceGenerator) Namers(c *generator.Context) namer.NameSystems","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/groupinterface.go","code":"func (g *groupInterfaceGenerator) Namers(c *generator.Context) namer.NameSystems {\n\treturn namer.NameSystems{\n\t\t\"raw\": namer.NewRawNamer(g.outputPackage, g.imports),\n\t}\n}","line":{"from":50,"to":54}} {"id":100030040,"name":"Imports","signature":"func (g *groupInterfaceGenerator) Imports(c *generator.Context) (imports []string)","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/groupinterface.go","code":"func (g *groupInterfaceGenerator) Imports(c *generator.Context) (imports []string) {\n\timports = append(imports, g.imports.ImportLines()...)\n\treturn\n}","line":{"from":56,"to":59}} {"id":100030041,"name":"GenerateType","signature":"func (g *groupInterfaceGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/groupinterface.go","code":"func (g *groupInterfaceGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {\n\tsw := generator.NewSnippetWriter(w, c, \"$\", \"$\")\n\n\tversions := make([]versionData, 0, len(g.groupVersions.Versions))\n\tfor _, version := range g.groupVersions.Versions {\n\t\tgv := clientgentypes.GroupVersion{Group: g.groupVersions.Group, Version: version.Version}\n\t\tversionPackage := filepath.Join(g.outputPackage, strings.ToLower(gv.Version.NonEmpty()))\n\t\tiface := c.Universe.Type(types.Name{Package: versionPackage, Name: \"Interface\"})\n\t\tversions = append(versions, versionData{\n\t\t\tName: namer.IC(version.Version.NonEmpty()),\n\t\t\tInterface: iface,\n\t\t\tNew: c.Universe.Function(types.Name{Package: versionPackage, Name: \"New\"}),\n\t\t})\n\t}\n\tm := map[string]interface{}{\n\t\t\"interfacesTweakListOptionsFunc\": c.Universe.Type(types.Name{Package: g.internalInterfacesPackage, Name: \"TweakListOptionsFunc\"}),\n\t\t\"interfacesSharedInformerFactory\": c.Universe.Type(types.Name{Package: g.internalInterfacesPackage, Name: \"SharedInformerFactory\"}),\n\t\t\"versions\": versions,\n\t}\n\n\tsw.Do(groupTemplate, m)\n\n\treturn sw.Error()\n}","line":{"from":67,"to":90}} {"id":100030042,"name":"Filter","signature":"func (g *informerGenerator) Filter(c *generator.Context, t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/informer.go","code":"func (g *informerGenerator) Filter(c *generator.Context, t *types.Type) bool {\n\treturn t == g.typeToGenerate\n}","line":{"from":51,"to":53}} {"id":100030043,"name":"Namers","signature":"func (g *informerGenerator) Namers(c *generator.Context) namer.NameSystems","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/informer.go","code":"func (g *informerGenerator) Namers(c *generator.Context) namer.NameSystems {\n\treturn namer.NameSystems{\n\t\t\"raw\": namer.NewRawNamer(g.outputPackage, g.imports),\n\t}\n}","line":{"from":55,"to":59}} {"id":100030044,"name":"Imports","signature":"func (g *informerGenerator) Imports(c *generator.Context) (imports []string)","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/informer.go","code":"func (g *informerGenerator) Imports(c *generator.Context) (imports []string) {\n\timports = append(imports, g.imports.ImportLines()...)\n\treturn\n}","line":{"from":61,"to":64}} {"id":100030045,"name":"GenerateType","signature":"func (g *informerGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/informer.go","code":"func (g *informerGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {\n\tsw := generator.NewSnippetWriter(w, c, \"$\", \"$\")\n\n\tklog.V(5).Infof(\"processing type %v\", t)\n\n\tlisterPackage := fmt.Sprintf(\"%s/%s/%s\", g.listersPackage, g.groupPkgName, strings.ToLower(g.groupVersion.Version.NonEmpty()))\n\tclientSetInterface := c.Universe.Type(types.Name{Package: g.clientSetPackage, Name: \"Interface\"})\n\tinformerFor := \"InformerFor\"\n\n\ttags, err := util.ParseClientGenTags(append(t.SecondClosestCommentLines, t.CommentLines...))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm := map[string]interface{}{\n\t\t\"apiScheme\": c.Universe.Type(apiScheme),\n\t\t\"cacheIndexers\": c.Universe.Type(cacheIndexers),\n\t\t\"cacheListWatch\": c.Universe.Type(cacheListWatch),\n\t\t\"cacheMetaNamespaceIndexFunc\": c.Universe.Function(cacheMetaNamespaceIndexFunc),\n\t\t\"cacheNamespaceIndex\": c.Universe.Variable(cacheNamespaceIndex),\n\t\t\"cacheNewSharedIndexInformer\": c.Universe.Function(cacheNewSharedIndexInformer),\n\t\t\"cacheSharedIndexInformer\": c.Universe.Type(cacheSharedIndexInformer),\n\t\t\"clientSetInterface\": clientSetInterface,\n\t\t\"group\": namer.IC(g.groupGoName),\n\t\t\"informerFor\": informerFor,\n\t\t\"interfacesTweakListOptionsFunc\": c.Universe.Type(types.Name{Package: g.internalInterfacesPackage, Name: \"TweakListOptionsFunc\"}),\n\t\t\"interfacesSharedInformerFactory\": c.Universe.Type(types.Name{Package: g.internalInterfacesPackage, Name: \"SharedInformerFactory\"}),\n\t\t\"listOptions\": c.Universe.Type(listOptions),\n\t\t\"lister\": c.Universe.Type(types.Name{Package: listerPackage, Name: t.Name.Name + \"Lister\"}),\n\t\t\"namespaceAll\": c.Universe.Type(metav1NamespaceAll),\n\t\t\"namespaced\": !tags.NonNamespaced,\n\t\t\"newLister\": c.Universe.Function(types.Name{Package: listerPackage, Name: \"New\" + t.Name.Name + \"Lister\"}),\n\t\t\"runtimeObject\": c.Universe.Type(runtimeObject),\n\t\t\"timeDuration\": c.Universe.Type(timeDuration),\n\t\t\"type\": t,\n\t\t\"v1ListOptions\": c.Universe.Type(v1ListOptions),\n\t\t\"version\": namer.IC(g.groupVersion.Version.String()),\n\t\t\"watchInterface\": c.Universe.Type(watchInterface),\n\t}\n\n\tsw.Do(typeInformerInterface, m)\n\tsw.Do(typeInformerStruct, m)\n\tsw.Do(typeInformerPublicConstructor, m)\n\tsw.Do(typeFilteredInformerPublicConstructor, m)\n\tsw.Do(typeInformerConstructor, m)\n\tsw.Do(typeInformerInformer, m)\n\tsw.Do(typeInformerLister, m)\n\n\treturn sw.Error()\n}","line":{"from":66,"to":115}} {"id":100030046,"name":"NameSystems","signature":"func NameSystems(pluralExceptions map[string]string) namer.NameSystems","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/packages.go","code":"// NameSystems returns the name system used by the generators in this package.\nfunc NameSystems(pluralExceptions map[string]string) namer.NameSystems {\n\treturn namer.NameSystems{\n\t\t\"public\": namer.NewPublicNamer(0),\n\t\t\"private\": namer.NewPrivateNamer(0),\n\t\t\"raw\": namer.NewRawNamer(\"\", nil),\n\t\t\"publicPlural\": namer.NewPublicPluralNamer(pluralExceptions),\n\t\t\"allLowercasePlural\": namer.NewAllLowercasePluralNamer(pluralExceptions),\n\t\t\"lowercaseSingular\": \u0026lowercaseSingularNamer{},\n\t}\n}","line":{"from":37,"to":47}} {"id":100030047,"name":"Name","signature":"func (n *lowercaseSingularNamer) Name(t *types.Type) string","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/packages.go","code":"// Name returns t's name in all lowercase.\nfunc (n *lowercaseSingularNamer) Name(t *types.Type) string {\n\treturn strings.ToLower(t.Name.Name)\n}","line":{"from":52,"to":55}} {"id":100030048,"name":"DefaultNameSystem","signature":"func DefaultNameSystem() string","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/packages.go","code":"// DefaultNameSystem returns the default name system for ordering the types to be\n// processed by the generators in this package.\nfunc DefaultNameSystem() string {\n\treturn \"public\"\n}","line":{"from":57,"to":61}} {"id":100030049,"name":"objectMetaForPackage","signature":"func objectMetaForPackage(p *types.Package) (*types.Type, bool, error)","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/packages.go","code":"// objectMetaForPackage returns the type of ObjectMeta used by package p.\nfunc objectMetaForPackage(p *types.Package) (*types.Type, bool, error) {\n\tgeneratingForPackage := false\n\tfor _, t := range p.Types {\n\t\tif !util.MustParseClientGenTags(append(t.SecondClosestCommentLines, t.CommentLines...)).GenerateClient {\n\t\t\tcontinue\n\t\t}\n\t\tgeneratingForPackage = true\n\t\tfor _, member := range t.Members {\n\t\t\tif member.Name == \"ObjectMeta\" {\n\t\t\t\treturn member.Type, isInternal(member), nil\n\t\t\t}\n\t\t}\n\t}\n\tif generatingForPackage {\n\t\treturn nil, false, fmt.Errorf(\"unable to find ObjectMeta for any types in package %s\", p.Path)\n\t}\n\treturn nil, false, nil\n}","line":{"from":63,"to":81}} {"id":100030050,"name":"isInternal","signature":"func isInternal(m types.Member) bool","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/packages.go","code":"// isInternal returns true if the tags for a member do not contain a json tag\nfunc isInternal(m types.Member) bool {\n\treturn !strings.Contains(m.Tags, \"json\")\n}","line":{"from":83,"to":86}} {"id":100030051,"name":"packageForInternalInterfaces","signature":"func packageForInternalInterfaces(base string) string","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/packages.go","code":"func packageForInternalInterfaces(base string) string {\n\treturn filepath.Join(base, \"internalinterfaces\")\n}","line":{"from":88,"to":90}} {"id":100030052,"name":"Packages","signature":"func Packages(context *generator.Context, arguments *args.GeneratorArgs) generator.Packages","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/packages.go","code":"// Packages makes the client package definition.\nfunc Packages(context *generator.Context, arguments *args.GeneratorArgs) generator.Packages {\n\tboilerplate, err := arguments.LoadGoBoilerplate()\n\tif err != nil {\n\t\tklog.Fatalf(\"Failed loading boilerplate: %v\", err)\n\t}\n\n\tcustomArgs, ok := arguments.CustomArgs.(*informergenargs.CustomArgs)\n\tif !ok {\n\t\tklog.Fatalf(\"Wrong CustomArgs type: %T\", arguments.CustomArgs)\n\t}\n\n\tinternalVersionPackagePath := filepath.Join(arguments.OutputPackagePath)\n\texternalVersionPackagePath := filepath.Join(arguments.OutputPackagePath)\n\tif !customArgs.SingleDirectory {\n\t\tinternalVersionPackagePath = filepath.Join(arguments.OutputPackagePath, \"internalversion\")\n\t\texternalVersionPackagePath = filepath.Join(arguments.OutputPackagePath, \"externalversions\")\n\t}\n\n\tvar packageList generator.Packages\n\ttypesForGroupVersion := make(map[clientgentypes.GroupVersion][]*types.Type)\n\n\texternalGroupVersions := make(map[string]clientgentypes.GroupVersions)\n\tinternalGroupVersions := make(map[string]clientgentypes.GroupVersions)\n\tgroupGoNames := make(map[string]string)\n\tfor _, inputDir := range arguments.InputDirs {\n\t\tp := context.Universe.Package(genutil.Vendorless(inputDir))\n\n\t\tobjectMeta, internal, err := objectMetaForPackage(p)\n\t\tif err != nil {\n\t\t\tklog.Fatal(err)\n\t\t}\n\t\tif objectMeta == nil {\n\t\t\t// no types in this package had genclient\n\t\t\tcontinue\n\t\t}\n\n\t\tvar gv clientgentypes.GroupVersion\n\t\tvar targetGroupVersions map[string]clientgentypes.GroupVersions\n\n\t\tif internal {\n\t\t\tlastSlash := strings.LastIndex(p.Path, \"/\")\n\t\t\tif lastSlash == -1 {\n\t\t\t\tklog.Fatalf(\"error constructing internal group version for package %q\", p.Path)\n\t\t\t}\n\t\t\tgv.Group = clientgentypes.Group(p.Path[lastSlash+1:])\n\t\t\ttargetGroupVersions = internalGroupVersions\n\t\t} else {\n\t\t\tparts := strings.Split(p.Path, \"/\")\n\t\t\tgv.Group = clientgentypes.Group(parts[len(parts)-2])\n\t\t\tgv.Version = clientgentypes.Version(parts[len(parts)-1])\n\t\t\ttargetGroupVersions = externalGroupVersions\n\t\t}\n\t\tgroupPackageName := gv.Group.NonEmpty()\n\t\tgvPackage := path.Clean(p.Path)\n\n\t\t// If there's a comment of the form \"// +groupName=somegroup\" or\n\t\t// \"// +groupName=somegroup.foo.bar.io\", use the first field (somegroup) as the name of the\n\t\t// group when generating.\n\t\tif override := types.ExtractCommentTags(\"+\", p.Comments)[\"groupName\"]; override != nil {\n\t\t\tgv.Group = clientgentypes.Group(override[0])\n\t\t}\n\n\t\t// If there's a comment of the form \"// +groupGoName=SomeUniqueShortName\", use that as\n\t\t// the Go group identifier in CamelCase. It defaults\n\t\tgroupGoNames[groupPackageName] = namer.IC(strings.Split(gv.Group.NonEmpty(), \".\")[0])\n\t\tif override := types.ExtractCommentTags(\"+\", p.Comments)[\"groupGoName\"]; override != nil {\n\t\t\tgroupGoNames[groupPackageName] = namer.IC(override[0])\n\t\t}\n\n\t\tvar typesToGenerate []*types.Type\n\t\tfor _, t := range p.Types {\n\t\t\ttags := util.MustParseClientGenTags(append(t.SecondClosestCommentLines, t.CommentLines...))\n\t\t\tif !tags.GenerateClient || tags.NoVerbs || !tags.HasVerb(\"list\") || !tags.HasVerb(\"watch\") {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ttypesToGenerate = append(typesToGenerate, t)\n\n\t\t\tif _, ok := typesForGroupVersion[gv]; !ok {\n\t\t\t\ttypesForGroupVersion[gv] = []*types.Type{}\n\t\t\t}\n\t\t\ttypesForGroupVersion[gv] = append(typesForGroupVersion[gv], t)\n\t\t}\n\t\tif len(typesToGenerate) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tgroupVersionsEntry, ok := targetGroupVersions[groupPackageName]\n\t\tif !ok {\n\t\t\tgroupVersionsEntry = clientgentypes.GroupVersions{\n\t\t\t\tPackageName: groupPackageName,\n\t\t\t\tGroup: gv.Group,\n\t\t\t}\n\t\t}\n\t\tgroupVersionsEntry.Versions = append(groupVersionsEntry.Versions, clientgentypes.PackageVersion{Version: gv.Version, Package: gvPackage})\n\t\ttargetGroupVersions[groupPackageName] = groupVersionsEntry\n\n\t\torderer := namer.Orderer{Namer: namer.NewPrivateNamer(0)}\n\t\ttypesToGenerate = orderer.OrderTypes(typesToGenerate)\n\n\t\tif internal {\n\t\t\tpackageList = append(packageList, versionPackage(internalVersionPackagePath, groupPackageName, gv, groupGoNames[groupPackageName], boilerplate, typesToGenerate, customArgs.InternalClientSetPackage, customArgs.ListersPackage))\n\t\t} else {\n\t\t\tpackageList = append(packageList, versionPackage(externalVersionPackagePath, groupPackageName, gv, groupGoNames[groupPackageName], boilerplate, typesToGenerate, customArgs.VersionedClientSetPackage, customArgs.ListersPackage))\n\t\t}\n\t}\n\n\tif len(externalGroupVersions) != 0 {\n\t\tpackageList = append(packageList, factoryInterfacePackage(externalVersionPackagePath, boilerplate, customArgs.VersionedClientSetPackage))\n\t\tpackageList = append(packageList, factoryPackage(externalVersionPackagePath, boilerplate, groupGoNames, genutil.PluralExceptionListToMapOrDie(customArgs.PluralExceptions), externalGroupVersions,\n\t\t\tcustomArgs.VersionedClientSetPackage,\n\t\t\ttypesForGroupVersion))\n\t\tfor _, gvs := range externalGroupVersions {\n\t\t\tpackageList = append(packageList, groupPackage(externalVersionPackagePath, gvs, boilerplate))\n\t\t}\n\t}\n\n\tif len(internalGroupVersions) != 0 {\n\t\tpackageList = append(packageList, factoryInterfacePackage(internalVersionPackagePath, boilerplate, customArgs.InternalClientSetPackage))\n\t\tpackageList = append(packageList, factoryPackage(internalVersionPackagePath, boilerplate, groupGoNames, genutil.PluralExceptionListToMapOrDie(customArgs.PluralExceptions), internalGroupVersions, customArgs.InternalClientSetPackage, typesForGroupVersion))\n\t\tfor _, gvs := range internalGroupVersions {\n\t\t\tpackageList = append(packageList, groupPackage(internalVersionPackagePath, gvs, boilerplate))\n\t\t}\n\t}\n\n\treturn packageList\n}","line":{"from":92,"to":219}} {"id":100030053,"name":"factoryPackage","signature":"func factoryPackage(basePackage string, boilerplate []byte, groupGoNames, pluralExceptions map[string]string, groupVersions map[string]clientgentypes.GroupVersions, clientSetPackage string,","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/packages.go","code":"func factoryPackage(basePackage string, boilerplate []byte, groupGoNames, pluralExceptions map[string]string, groupVersions map[string]clientgentypes.GroupVersions, clientSetPackage string,\n\ttypesForGroupVersion map[clientgentypes.GroupVersion][]*types.Type) generator.Package {\n\treturn \u0026generator.DefaultPackage{\n\t\tPackageName: filepath.Base(basePackage),\n\t\tPackagePath: basePackage,\n\t\tHeaderText: boilerplate,\n\t\tGeneratorFunc: func(c *generator.Context) (generators []generator.Generator) {\n\t\t\tgenerators = append(generators, \u0026factoryGenerator{\n\t\t\t\tDefaultGen: generator.DefaultGen{\n\t\t\t\t\tOptionalName: \"factory\",\n\t\t\t\t},\n\t\t\t\toutputPackage: basePackage,\n\t\t\t\timports: generator.NewImportTracker(),\n\t\t\t\tgroupVersions: groupVersions,\n\t\t\t\tclientSetPackage: clientSetPackage,\n\t\t\t\tinternalInterfacesPackage: packageForInternalInterfaces(basePackage),\n\t\t\t\tgvGoNames: groupGoNames,\n\t\t\t})\n\n\t\t\tgenerators = append(generators, \u0026genericGenerator{\n\t\t\t\tDefaultGen: generator.DefaultGen{\n\t\t\t\t\tOptionalName: \"generic\",\n\t\t\t\t},\n\t\t\t\toutputPackage: basePackage,\n\t\t\t\timports: generator.NewImportTracker(),\n\t\t\t\tgroupVersions: groupVersions,\n\t\t\t\tpluralExceptions: pluralExceptions,\n\t\t\t\ttypesForGroupVersion: typesForGroupVersion,\n\t\t\t\tgroupGoNames: groupGoNames,\n\t\t\t})\n\n\t\t\treturn generators\n\t\t},\n\t}\n}","line":{"from":221,"to":255}} {"id":100030054,"name":"factoryInterfacePackage","signature":"func factoryInterfacePackage(basePackage string, boilerplate []byte, clientSetPackage string) generator.Package","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/packages.go","code":"func factoryInterfacePackage(basePackage string, boilerplate []byte, clientSetPackage string) generator.Package {\n\tpackagePath := packageForInternalInterfaces(basePackage)\n\n\treturn \u0026generator.DefaultPackage{\n\t\tPackageName: filepath.Base(packagePath),\n\t\tPackagePath: packagePath,\n\t\tHeaderText: boilerplate,\n\t\tGeneratorFunc: func(c *generator.Context) (generators []generator.Generator) {\n\t\t\tgenerators = append(generators, \u0026factoryInterfaceGenerator{\n\t\t\t\tDefaultGen: generator.DefaultGen{\n\t\t\t\t\tOptionalName: \"factory_interfaces\",\n\t\t\t\t},\n\t\t\t\toutputPackage: packagePath,\n\t\t\t\timports: generator.NewImportTracker(),\n\t\t\t\tclientSetPackage: clientSetPackage,\n\t\t\t})\n\n\t\t\treturn generators\n\t\t},\n\t}\n}","line":{"from":257,"to":277}} {"id":100030055,"name":"groupPackage","signature":"func groupPackage(basePackage string, groupVersions clientgentypes.GroupVersions, boilerplate []byte) generator.Package","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/packages.go","code":"func groupPackage(basePackage string, groupVersions clientgentypes.GroupVersions, boilerplate []byte) generator.Package {\n\tpackagePath := filepath.Join(basePackage, groupVersions.PackageName)\n\tgroupPkgName := strings.Split(string(groupVersions.PackageName), \".\")[0]\n\n\treturn \u0026generator.DefaultPackage{\n\t\tPackageName: groupPkgName,\n\t\tPackagePath: packagePath,\n\t\tHeaderText: boilerplate,\n\t\tGeneratorFunc: func(c *generator.Context) (generators []generator.Generator) {\n\t\t\tgenerators = append(generators, \u0026groupInterfaceGenerator{\n\t\t\t\tDefaultGen: generator.DefaultGen{\n\t\t\t\t\tOptionalName: \"interface\",\n\t\t\t\t},\n\t\t\t\toutputPackage: packagePath,\n\t\t\t\tgroupVersions: groupVersions,\n\t\t\t\timports: generator.NewImportTracker(),\n\t\t\t\tinternalInterfacesPackage: packageForInternalInterfaces(basePackage),\n\t\t\t})\n\t\t\treturn generators\n\t\t},\n\t\tFilterFunc: func(c *generator.Context, t *types.Type) bool {\n\t\t\ttags := util.MustParseClientGenTags(append(t.SecondClosestCommentLines, t.CommentLines...))\n\t\t\treturn tags.GenerateClient \u0026\u0026 tags.HasVerb(\"list\") \u0026\u0026 tags.HasVerb(\"watch\")\n\t\t},\n\t}\n}","line":{"from":279,"to":304}} {"id":100030056,"name":"versionPackage","signature":"func versionPackage(basePackage string, groupPkgName string, gv clientgentypes.GroupVersion, groupGoName string, boilerplate []byte, typesToGenerate []*types.Type, clientSetPackage, listersPackage string) generator.Package","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/packages.go","code":"func versionPackage(basePackage string, groupPkgName string, gv clientgentypes.GroupVersion, groupGoName string, boilerplate []byte, typesToGenerate []*types.Type, clientSetPackage, listersPackage string) generator.Package {\n\tpackagePath := filepath.Join(basePackage, groupPkgName, strings.ToLower(gv.Version.NonEmpty()))\n\n\treturn \u0026generator.DefaultPackage{\n\t\tPackageName: strings.ToLower(gv.Version.NonEmpty()),\n\t\tPackagePath: packagePath,\n\t\tHeaderText: boilerplate,\n\t\tGeneratorFunc: func(c *generator.Context) (generators []generator.Generator) {\n\t\t\tgenerators = append(generators, \u0026versionInterfaceGenerator{\n\t\t\t\tDefaultGen: generator.DefaultGen{\n\t\t\t\t\tOptionalName: \"interface\",\n\t\t\t\t},\n\t\t\t\toutputPackage: packagePath,\n\t\t\t\timports: generator.NewImportTracker(),\n\t\t\t\ttypes: typesToGenerate,\n\t\t\t\tinternalInterfacesPackage: packageForInternalInterfaces(basePackage),\n\t\t\t})\n\n\t\t\tfor _, t := range typesToGenerate {\n\t\t\t\tgenerators = append(generators, \u0026informerGenerator{\n\t\t\t\t\tDefaultGen: generator.DefaultGen{\n\t\t\t\t\t\tOptionalName: strings.ToLower(t.Name.Name),\n\t\t\t\t\t},\n\t\t\t\t\toutputPackage: packagePath,\n\t\t\t\t\tgroupPkgName: groupPkgName,\n\t\t\t\t\tgroupVersion: gv,\n\t\t\t\t\tgroupGoName: groupGoName,\n\t\t\t\t\ttypeToGenerate: t,\n\t\t\t\t\timports: generator.NewImportTracker(),\n\t\t\t\t\tclientSetPackage: clientSetPackage,\n\t\t\t\t\tlistersPackage: listersPackage,\n\t\t\t\t\tinternalInterfacesPackage: packageForInternalInterfaces(basePackage),\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn generators\n\t\t},\n\t\tFilterFunc: func(c *generator.Context, t *types.Type) bool {\n\t\t\ttags := util.MustParseClientGenTags(append(t.SecondClosestCommentLines, t.CommentLines...))\n\t\t\treturn tags.GenerateClient \u0026\u0026 tags.HasVerb(\"list\") \u0026\u0026 tags.HasVerb(\"watch\")\n\t\t},\n\t}\n}","line":{"from":306,"to":347}} {"id":100030057,"name":"Filter","signature":"func (g *versionInterfaceGenerator) Filter(c *generator.Context, t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/versioninterface.go","code":"func (g *versionInterfaceGenerator) Filter(c *generator.Context, t *types.Type) bool {\n\tif !g.filtered {\n\t\tg.filtered = true\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":41,"to":47}} {"id":100030058,"name":"Namers","signature":"func (g *versionInterfaceGenerator) Namers(c *generator.Context) namer.NameSystems","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/versioninterface.go","code":"func (g *versionInterfaceGenerator) Namers(c *generator.Context) namer.NameSystems {\n\treturn namer.NameSystems{\n\t\t\"raw\": namer.NewRawNamer(g.outputPackage, g.imports),\n\t}\n}","line":{"from":49,"to":53}} {"id":100030059,"name":"Imports","signature":"func (g *versionInterfaceGenerator) Imports(c *generator.Context) (imports []string)","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/versioninterface.go","code":"func (g *versionInterfaceGenerator) Imports(c *generator.Context) (imports []string) {\n\timports = append(imports, g.imports.ImportLines()...)\n\treturn\n}","line":{"from":55,"to":58}} {"id":100030060,"name":"GenerateType","signature":"func (g *versionInterfaceGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/generators/versioninterface.go","code":"func (g *versionInterfaceGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {\n\tsw := generator.NewSnippetWriter(w, c, \"$\", \"$\")\n\n\tm := map[string]interface{}{\n\t\t\"interfacesTweakListOptionsFunc\": c.Universe.Type(types.Name{Package: g.internalInterfacesPackage, Name: \"TweakListOptionsFunc\"}),\n\t\t\"interfacesSharedInformerFactory\": c.Universe.Type(types.Name{Package: g.internalInterfacesPackage, Name: \"SharedInformerFactory\"}),\n\t\t\"types\": g.types,\n\t}\n\n\tsw.Do(versionTemplate, m)\n\tfor _, typeDef := range g.types {\n\t\ttags, err := util.ParseClientGenTags(append(typeDef.SecondClosestCommentLines, typeDef.CommentLines...))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tm[\"namespaced\"] = !tags.NonNamespaced\n\t\tm[\"type\"] = typeDef\n\t\tsw.Do(versionFuncTemplate, m)\n\t}\n\n\treturn sw.Error()\n}","line":{"from":60,"to":81}} {"id":100030061,"name":"main","signature":"func main()","file":"staging/src/k8s.io/code-generator/cmd/informer-gen/main.go","code":"func main() {\n\tklog.InitFlags(nil)\n\tgenericArgs, customArgs := generatorargs.NewDefaults()\n\n\t// Override defaults.\n\t// TODO: move out of informer-gen\n\tgenericArgs.OutputPackagePath = \"k8s.io/kubernetes/pkg/client/informers/informers_generated\"\n\tcustomArgs.VersionedClientSetPackage = \"k8s.io/kubernetes/pkg/client/clientset_generated/clientset\"\n\tcustomArgs.InternalClientSetPackage = \"k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset\"\n\tcustomArgs.ListersPackage = \"k8s.io/kubernetes/pkg/client/listers\"\n\n\tgenericArgs.AddFlags(pflag.CommandLine)\n\tcustomArgs.AddFlags(pflag.CommandLine)\n\tflag.Set(\"logtostderr\", \"true\")\n\tpflag.CommandLine.AddGoFlagSet(flag.CommandLine)\n\tpflag.Parse()\n\n\tif err := generatorargs.Validate(genericArgs); err != nil {\n\t\tklog.Fatalf(\"Error: %v\", err)\n\t}\n\n\t// Run it.\n\tif err := genericArgs.Execute(\n\t\tgenerators.NameSystems(util.PluralExceptionListToMapOrDie(customArgs.PluralExceptions)),\n\t\tgenerators.DefaultNameSystem(),\n\t\tgenerators.Packages,\n\t); err != nil {\n\t\tklog.Fatalf(\"Error: %v\", err)\n\t}\n\tklog.V(2).Info(\"Completed successfully.\")\n}","line":{"from":30,"to":60}} {"id":100030062,"name":"NewDefaults","signature":"func NewDefaults() (*args.GeneratorArgs, *CustomArgs)","file":"staging/src/k8s.io/code-generator/cmd/lister-gen/args/args.go","code":"// NewDefaults returns default arguments for the generator.\nfunc NewDefaults() (*args.GeneratorArgs, *CustomArgs) {\n\tgenericArgs := args.Default().WithoutDefaultFlagParsing()\n\tcustomArgs := \u0026CustomArgs{\n\t\tPluralExceptions: []string{\"Endpoints:Endpoints\"},\n\t}\n\tgenericArgs.CustomArgs = customArgs\n\n\tif pkg := codegenutil.CurrentPackage(); len(pkg) != 0 {\n\t\tgenericArgs.OutputPackagePath = path.Join(pkg, \"pkg/client/listers\")\n\t}\n\n\treturn genericArgs, customArgs\n}","line":{"from":35,"to":48}} {"id":100030063,"name":"AddFlags","signature":"func (ca *CustomArgs) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/code-generator/cmd/lister-gen/args/args.go","code":"// AddFlags add the generator flags to the flag set.\nfunc (ca *CustomArgs) AddFlags(fs *pflag.FlagSet) {\n\tfs.StringSliceVar(\u0026ca.PluralExceptions, \"plural-exceptions\", ca.PluralExceptions, \"list of comma separated plural exception definitions in Type:PluralizedType format\")\n}","line":{"from":50,"to":53}} {"id":100030064,"name":"Validate","signature":"func Validate(genericArgs *args.GeneratorArgs) error","file":"staging/src/k8s.io/code-generator/cmd/lister-gen/args/args.go","code":"// Validate checks the given arguments.\nfunc Validate(genericArgs *args.GeneratorArgs) error {\n\t_ = genericArgs.CustomArgs.(*CustomArgs)\n\n\tif len(genericArgs.OutputPackagePath) == 0 {\n\t\treturn fmt.Errorf(\"output package cannot be empty\")\n\t}\n\n\treturn nil\n}","line":{"from":55,"to":64}} {"id":100030065,"name":"Filter","signature":"func (g *expansionGenerator) Filter(c *generator.Context, t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/lister-gen/generators/expansion.go","code":"// We only want to call GenerateType() once per group.\nfunc (g *expansionGenerator) Filter(c *generator.Context, t *types.Type) bool {\n\treturn t == g.types[0]\n}","line":{"from":38,"to":41}} {"id":100030066,"name":"GenerateType","signature":"func (g *expansionGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error","file":"staging/src/k8s.io/code-generator/cmd/lister-gen/generators/expansion.go","code":"func (g *expansionGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {\n\tsw := generator.NewSnippetWriter(w, c, \"$\", \"$\")\n\tfor _, t := range g.types {\n\t\ttags := util.MustParseClientGenTags(append(t.SecondClosestCommentLines, t.CommentLines...))\n\t\tif _, err := os.Stat(filepath.Join(g.packagePath, strings.ToLower(t.Name.Name+\"_expansion.go\"))); os.IsNotExist(err) {\n\t\t\tsw.Do(expansionInterfaceTemplate, t)\n\t\t\tif !tags.NonNamespaced {\n\t\t\t\tsw.Do(namespacedExpansionInterfaceTemplate, t)\n\t\t\t}\n\t\t}\n\t}\n\treturn sw.Error()\n}","line":{"from":43,"to":55}} {"id":100030067,"name":"NameSystems","signature":"func NameSystems(pluralExceptions map[string]string) namer.NameSystems","file":"staging/src/k8s.io/code-generator/cmd/lister-gen/generators/lister.go","code":"// NameSystems returns the name system used by the generators in this package.\nfunc NameSystems(pluralExceptions map[string]string) namer.NameSystems {\n\treturn namer.NameSystems{\n\t\t\"public\": namer.NewPublicNamer(0),\n\t\t\"private\": namer.NewPrivateNamer(0),\n\t\t\"raw\": namer.NewRawNamer(\"\", nil),\n\t\t\"publicPlural\": namer.NewPublicPluralNamer(pluralExceptions),\n\t\t\"allLowercasePlural\": namer.NewAllLowercasePluralNamer(pluralExceptions),\n\t\t\"lowercaseSingular\": \u0026lowercaseSingularNamer{},\n\t}\n}","line":{"from":36,"to":46}} {"id":100030068,"name":"Name","signature":"func (n *lowercaseSingularNamer) Name(t *types.Type) string","file":"staging/src/k8s.io/code-generator/cmd/lister-gen/generators/lister.go","code":"// Name returns t's name in all lowercase.\nfunc (n *lowercaseSingularNamer) Name(t *types.Type) string {\n\treturn strings.ToLower(t.Name.Name)\n}","line":{"from":51,"to":54}} {"id":100030069,"name":"DefaultNameSystem","signature":"func DefaultNameSystem() string","file":"staging/src/k8s.io/code-generator/cmd/lister-gen/generators/lister.go","code":"// DefaultNameSystem returns the default name system for ordering the types to be\n// processed by the generators in this package.\nfunc DefaultNameSystem() string {\n\treturn \"public\"\n}","line":{"from":56,"to":60}} {"id":100030070,"name":"Packages","signature":"func Packages(context *generator.Context, arguments *args.GeneratorArgs) generator.Packages","file":"staging/src/k8s.io/code-generator/cmd/lister-gen/generators/lister.go","code":"// Packages makes the client package definition.\nfunc Packages(context *generator.Context, arguments *args.GeneratorArgs) generator.Packages {\n\tboilerplate, err := arguments.LoadGoBoilerplate()\n\tif err != nil {\n\t\tklog.Fatalf(\"Failed loading boilerplate: %v\", err)\n\t}\n\n\tvar packageList generator.Packages\n\tfor _, inputDir := range arguments.InputDirs {\n\t\tp := context.Universe.Package(inputDir)\n\n\t\tobjectMeta, internal, err := objectMetaForPackage(p)\n\t\tif err != nil {\n\t\t\tklog.Fatal(err)\n\t\t}\n\t\tif objectMeta == nil {\n\t\t\t// no types in this package had genclient\n\t\t\tcontinue\n\t\t}\n\n\t\tvar gv clientgentypes.GroupVersion\n\t\tvar internalGVPkg string\n\n\t\tif internal {\n\t\t\tlastSlash := strings.LastIndex(p.Path, \"/\")\n\t\t\tif lastSlash == -1 {\n\t\t\t\tklog.Fatalf(\"error constructing internal group version for package %q\", p.Path)\n\t\t\t}\n\t\t\tgv.Group = clientgentypes.Group(p.Path[lastSlash+1:])\n\t\t\tinternalGVPkg = p.Path\n\t\t} else {\n\t\t\tparts := strings.Split(p.Path, \"/\")\n\t\t\tgv.Group = clientgentypes.Group(parts[len(parts)-2])\n\t\t\tgv.Version = clientgentypes.Version(parts[len(parts)-1])\n\n\t\t\tinternalGVPkg = strings.Join(parts[0:len(parts)-1], \"/\")\n\t\t}\n\t\tgroupPackageName := strings.ToLower(gv.Group.NonEmpty())\n\n\t\t// If there's a comment of the form \"// +groupName=somegroup\" or\n\t\t// \"// +groupName=somegroup.foo.bar.io\", use the first field (somegroup) as the name of the\n\t\t// group when generating.\n\t\tif override := types.ExtractCommentTags(\"+\", p.Comments)[\"groupName\"]; override != nil {\n\t\t\tgv.Group = clientgentypes.Group(strings.SplitN(override[0], \".\", 2)[0])\n\t\t}\n\n\t\tvar typesToGenerate []*types.Type\n\t\tfor _, t := range p.Types {\n\t\t\ttags := util.MustParseClientGenTags(append(t.SecondClosestCommentLines, t.CommentLines...))\n\t\t\tif !tags.GenerateClient || !tags.HasVerb(\"list\") || !tags.HasVerb(\"get\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttypesToGenerate = append(typesToGenerate, t)\n\t\t}\n\t\tif len(typesToGenerate) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\torderer := namer.Orderer{Namer: namer.NewPrivateNamer(0)}\n\t\ttypesToGenerate = orderer.OrderTypes(typesToGenerate)\n\n\t\tpackagePath := filepath.Join(arguments.OutputPackagePath, groupPackageName, strings.ToLower(gv.Version.NonEmpty()))\n\t\tpackageList = append(packageList, \u0026generator.DefaultPackage{\n\t\t\tPackageName: strings.ToLower(gv.Version.NonEmpty()),\n\t\t\tPackagePath: packagePath,\n\t\t\tHeaderText: boilerplate,\n\t\t\tGeneratorFunc: func(c *generator.Context) (generators []generator.Generator) {\n\t\t\t\tgenerators = append(generators, \u0026expansionGenerator{\n\t\t\t\t\tDefaultGen: generator.DefaultGen{\n\t\t\t\t\t\tOptionalName: \"expansion_generated\",\n\t\t\t\t\t},\n\t\t\t\t\tpackagePath: filepath.Join(arguments.OutputBase, packagePath),\n\t\t\t\t\ttypes: typesToGenerate,\n\t\t\t\t})\n\n\t\t\t\tfor _, t := range typesToGenerate {\n\t\t\t\t\tgenerators = append(generators, \u0026listerGenerator{\n\t\t\t\t\t\tDefaultGen: generator.DefaultGen{\n\t\t\t\t\t\t\tOptionalName: strings.ToLower(t.Name.Name),\n\t\t\t\t\t\t},\n\t\t\t\t\t\toutputPackage: arguments.OutputPackagePath,\n\t\t\t\t\t\tgroupVersion: gv,\n\t\t\t\t\t\tinternalGVPkg: internalGVPkg,\n\t\t\t\t\t\ttypeToGenerate: t,\n\t\t\t\t\t\timports: generator.NewImportTracker(),\n\t\t\t\t\t\tobjectMeta: objectMeta,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\treturn generators\n\t\t\t},\n\t\t\tFilterFunc: func(c *generator.Context, t *types.Type) bool {\n\t\t\t\ttags := util.MustParseClientGenTags(append(t.SecondClosestCommentLines, t.CommentLines...))\n\t\t\t\treturn tags.GenerateClient \u0026\u0026 tags.HasVerb(\"list\") \u0026\u0026 tags.HasVerb(\"get\")\n\t\t\t},\n\t\t})\n\t}\n\n\treturn packageList\n}","line":{"from":62,"to":159}} {"id":100030071,"name":"objectMetaForPackage","signature":"func objectMetaForPackage(p *types.Package) (*types.Type, bool, error)","file":"staging/src/k8s.io/code-generator/cmd/lister-gen/generators/lister.go","code":"// objectMetaForPackage returns the type of ObjectMeta used by package p.\nfunc objectMetaForPackage(p *types.Package) (*types.Type, bool, error) {\n\tgeneratingForPackage := false\n\tfor _, t := range p.Types {\n\t\t// filter out types which don't have genclient.\n\t\tif !util.MustParseClientGenTags(append(t.SecondClosestCommentLines, t.CommentLines...)).GenerateClient {\n\t\t\tcontinue\n\t\t}\n\t\tgeneratingForPackage = true\n\t\tfor _, member := range t.Members {\n\t\t\tif member.Name == \"ObjectMeta\" {\n\t\t\t\treturn member.Type, isInternal(member), nil\n\t\t\t}\n\t\t}\n\t}\n\tif generatingForPackage {\n\t\treturn nil, false, fmt.Errorf(\"unable to find ObjectMeta for any types in package %s\", p.Path)\n\t}\n\treturn nil, false, nil\n}","line":{"from":161,"to":180}} {"id":100030072,"name":"isInternal","signature":"func isInternal(m types.Member) bool","file":"staging/src/k8s.io/code-generator/cmd/lister-gen/generators/lister.go","code":"// isInternal returns true if the tags for a member do not contain a json tag\nfunc isInternal(m types.Member) bool {\n\treturn !strings.Contains(m.Tags, \"json\")\n}","line":{"from":182,"to":185}} {"id":100030073,"name":"Filter","signature":"func (g *listerGenerator) Filter(c *generator.Context, t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/lister-gen/generators/lister.go","code":"func (g *listerGenerator) Filter(c *generator.Context, t *types.Type) bool {\n\treturn t == g.typeToGenerate\n}","line":{"from":201,"to":203}} {"id":100030074,"name":"Namers","signature":"func (g *listerGenerator) Namers(c *generator.Context) namer.NameSystems","file":"staging/src/k8s.io/code-generator/cmd/lister-gen/generators/lister.go","code":"func (g *listerGenerator) Namers(c *generator.Context) namer.NameSystems {\n\treturn namer.NameSystems{\n\t\t\"raw\": namer.NewRawNamer(g.outputPackage, g.imports),\n\t}\n}","line":{"from":205,"to":209}} {"id":100030075,"name":"Imports","signature":"func (g *listerGenerator) Imports(c *generator.Context) (imports []string)","file":"staging/src/k8s.io/code-generator/cmd/lister-gen/generators/lister.go","code":"func (g *listerGenerator) Imports(c *generator.Context) (imports []string) {\n\timports = append(imports, g.imports.ImportLines()...)\n\timports = append(imports, \"k8s.io/apimachinery/pkg/api/errors\")\n\timports = append(imports, \"k8s.io/apimachinery/pkg/labels\")\n\t// for Indexer\n\timports = append(imports, \"k8s.io/client-go/tools/cache\")\n\treturn\n}","line":{"from":211,"to":218}} {"id":100030076,"name":"GenerateType","signature":"func (g *listerGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error","file":"staging/src/k8s.io/code-generator/cmd/lister-gen/generators/lister.go","code":"func (g *listerGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {\n\tsw := generator.NewSnippetWriter(w, c, \"$\", \"$\")\n\n\tklog.V(5).Infof(\"processing type %v\", t)\n\tm := map[string]interface{}{\n\t\t\"Resource\": c.Universe.Function(types.Name{Package: t.Name.Package, Name: \"Resource\"}),\n\t\t\"type\": t,\n\t\t\"objectMeta\": g.objectMeta,\n\t}\n\n\ttags, err := util.ParseClientGenTags(append(t.SecondClosestCommentLines, t.CommentLines...))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif tags.NonNamespaced {\n\t\tsw.Do(typeListerInterface_NonNamespaced, m)\n\t} else {\n\t\tsw.Do(typeListerInterface, m)\n\t}\n\n\tsw.Do(typeListerStruct, m)\n\tsw.Do(typeListerConstructor, m)\n\tsw.Do(typeLister_List, m)\n\n\tif tags.NonNamespaced {\n\t\tsw.Do(typeLister_NonNamespacedGet, m)\n\t\treturn sw.Error()\n\t}\n\n\tsw.Do(typeLister_NamespaceLister, m)\n\tsw.Do(namespaceListerInterface, m)\n\tsw.Do(namespaceListerStruct, m)\n\tsw.Do(namespaceLister_List, m)\n\tsw.Do(namespaceLister_Get, m)\n\n\treturn sw.Error()\n}","line":{"from":220,"to":257}} {"id":100030077,"name":"main","signature":"func main()","file":"staging/src/k8s.io/code-generator/cmd/lister-gen/main.go","code":"func main() {\n\tklog.InitFlags(nil)\n\tgenericArgs, customArgs := generatorargs.NewDefaults()\n\n\t// Override defaults.\n\t// TODO: move this out of lister-gen\n\tgenericArgs.OutputPackagePath = \"k8s.io/kubernetes/pkg/client/listers\"\n\n\tgenericArgs.AddFlags(pflag.CommandLine)\n\tcustomArgs.AddFlags(pflag.CommandLine)\n\tflag.Set(\"logtostderr\", \"true\")\n\tpflag.CommandLine.AddGoFlagSet(flag.CommandLine)\n\tpflag.Parse()\n\n\tif err := generatorargs.Validate(genericArgs); err != nil {\n\t\tklog.Fatalf(\"Error: %v\", err)\n\t}\n\n\t// Run it.\n\tif err := genericArgs.Execute(\n\t\tgenerators.NameSystems(util.PluralExceptionListToMapOrDie(customArgs.PluralExceptions)),\n\t\tgenerators.DefaultNameSystem(),\n\t\tgenerators.Packages,\n\t); err != nil {\n\t\tklog.Fatalf(\"Error: %v\", err)\n\t}\n\tklog.V(2).Info(\"Completed successfully.\")\n}","line":{"from":30,"to":57}} {"id":100030078,"name":"main","signature":"func main()","file":"staging/src/k8s.io/code-generator/cmd/openapi-gen/main.go","code":"func main() {\n\tklog.InitFlags(nil)\n\tgenericArgs, customArgs := generatorargs.NewDefaults()\n\n\tgenericArgs.AddFlags(pflag.CommandLine)\n\tcustomArgs.AddFlags(pflag.CommandLine)\n\tflag.Set(\"logtostderr\", \"true\")\n\tpflag.CommandLine.AddGoFlagSet(flag.CommandLine)\n\tpflag.Parse()\n\n\tif err := generatorargs.Validate(genericArgs); err != nil {\n\t\tlog.Fatalf(\"Arguments validation error: %v\", err)\n\t}\n\n\t// Generates the code for the OpenAPIDefinitions.\n\tif err := genericArgs.Execute(\n\t\tgenerators.NameSystems(),\n\t\tgenerators.DefaultNameSystem(),\n\t\tgenerators.Packages,\n\t); err != nil {\n\t\tlog.Fatalf(\"OpenAPI code generation error: %v\", err)\n\t}\n}","line":{"from":35,"to":57}} {"id":100030079,"name":"NewDefaults","signature":"func NewDefaults() (*args.GeneratorArgs, *CustomArgs)","file":"staging/src/k8s.io/code-generator/cmd/prerelease-lifecycle-gen/args/args.go","code":"// NewDefaults returns default arguments for the generator.\nfunc NewDefaults() (*args.GeneratorArgs, *CustomArgs) {\n\tgenericArgs := args.Default().WithoutDefaultFlagParsing()\n\tcustomArgs := \u0026CustomArgs{}\n\tgenericArgs.CustomArgs = (*statusgenerators.CustomArgs)(customArgs) // convert to upstream type to make type-casts work there\n\tgenericArgs.OutputFileBaseName = \"zz_prerelease_lifecycle_generated\"\n\treturn genericArgs, customArgs\n}","line":{"from":30,"to":37}} {"id":100030080,"name":"AddFlags","signature":"func (ca *CustomArgs) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/code-generator/cmd/prerelease-lifecycle-gen/args/args.go","code":"// AddFlags add the generator flags to the flag set.\nfunc (ca *CustomArgs) AddFlags(fs *pflag.FlagSet) {\n}","line":{"from":39,"to":41}} {"id":100030081,"name":"Validate","signature":"func Validate(genericArgs *args.GeneratorArgs) error","file":"staging/src/k8s.io/code-generator/cmd/prerelease-lifecycle-gen/args/args.go","code":"// Validate checks the given arguments.\nfunc Validate(genericArgs *args.GeneratorArgs) error {\n\t_ = genericArgs.CustomArgs.(*statusgenerators.CustomArgs)\n\n\tif len(genericArgs.OutputFileBaseName) == 0 {\n\t\treturn fmt.Errorf(\"output file base name cannot be empty\")\n\t}\n\n\treturn nil\n}","line":{"from":43,"to":52}} {"id":100030082,"name":"main","signature":"func main()","file":"staging/src/k8s.io/code-generator/cmd/prerelease-lifecycle-gen/main.go","code":"func main() {\n\tklog.InitFlags(nil)\n\tgenericArgs, customArgs := generatorargs.NewDefaults()\n\n\tgenericArgs.AddFlags(pflag.CommandLine)\n\tcustomArgs.AddFlags(pflag.CommandLine)\n\tflag.Set(\"logtostderr\", \"true\")\n\tpflag.CommandLine.AddGoFlagSet(flag.CommandLine)\n\tpflag.Parse()\n\n\tif err := generatorargs.Validate(genericArgs); err != nil {\n\t\tklog.Fatalf(\"Error: %v\", err)\n\t}\n\n\t// Run it.\n\tif err := genericArgs.Execute(\n\t\tstatusgenerators.NameSystems(),\n\t\tstatusgenerators.DefaultNameSystem(),\n\t\tstatusgenerators.Packages,\n\t); err != nil {\n\t\tklog.Fatalf(\"Error: %v\", err)\n\t}\n\tklog.V(2).Info(\"Completed successfully.\")\n}","line":{"from":46,"to":69}} {"id":100030083,"name":"extractEnabledTypeTag","signature":"func extractEnabledTypeTag(t *types.Type) *tagValue","file":"staging/src/k8s.io/code-generator/cmd/prerelease-lifecycle-gen/prerelease-lifecycle-generators/status.go","code":"func extractEnabledTypeTag(t *types.Type) *tagValue {\n\tcomments := append(append([]string{}, t.SecondClosestCommentLines...), t.CommentLines...)\n\treturn extractTag(tagEnabledName, comments)\n}","line":{"from":55,"to":58}} {"id":100030084,"name":"tagExists","signature":"func tagExists(tagName string, t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/prerelease-lifecycle-gen/prerelease-lifecycle-generators/status.go","code":"func tagExists(tagName string, t *types.Type) bool {\n\tcomments := append(append([]string{}, t.SecondClosestCommentLines...), t.CommentLines...)\n\trawTag := extractTag(tagName, comments)\n\treturn rawTag != nil\n}","line":{"from":60,"to":64}} {"id":100030085,"name":"extractKubeVersionTag","signature":"func extractKubeVersionTag(tagName string, t *types.Type) (*tagValue, int, int, error)","file":"staging/src/k8s.io/code-generator/cmd/prerelease-lifecycle-gen/prerelease-lifecycle-generators/status.go","code":"func extractKubeVersionTag(tagName string, t *types.Type) (*tagValue, int, int, error) {\n\tcomments := append(append([]string{}, t.SecondClosestCommentLines...), t.CommentLines...)\n\trawTag := extractTag(tagName, comments)\n\tif rawTag == nil || len(rawTag.value) == 0 {\n\t\treturn nil, -1, -1, fmt.Errorf(\"%v missing %v=Version tag\", t, tagName)\n\t}\n\n\tsplitValue := strings.Split(rawTag.value, \".\")\n\tif len(splitValue) != 2 || len(splitValue[0]) == 0 || len(splitValue[0]) == 0 {\n\t\treturn nil, -1, -1, fmt.Errorf(\"%v format must match %v=xx.yy tag\", t, tagName)\n\t}\n\tmajor, err := strconv.ParseInt(splitValue[0], 10, 32)\n\tif err != nil {\n\t\treturn nil, -1, -1, fmt.Errorf(\"%v format must match %v=xx.yy : %w\", t, tagName, err)\n\t}\n\tminor, err := strconv.ParseInt(splitValue[1], 10, 32)\n\tif err != nil {\n\t\treturn nil, -1, -1, fmt.Errorf(\"%v format must match %v=xx.yy : %w\", t, tagName, err)\n\t}\n\n\treturn rawTag, int(major), int(minor), nil\n}","line":{"from":66,"to":87}} {"id":100030086,"name":"extractIntroducedTag","signature":"func extractIntroducedTag(t *types.Type) (*tagValue, int, int, error)","file":"staging/src/k8s.io/code-generator/cmd/prerelease-lifecycle-gen/prerelease-lifecycle-generators/status.go","code":"func extractIntroducedTag(t *types.Type) (*tagValue, int, int, error) {\n\treturn extractKubeVersionTag(introducedTagName, t)\n}","line":{"from":89,"to":91}} {"id":100030087,"name":"extractDeprecatedTag","signature":"func extractDeprecatedTag(t *types.Type) (*tagValue, int, int, error)","file":"staging/src/k8s.io/code-generator/cmd/prerelease-lifecycle-gen/prerelease-lifecycle-generators/status.go","code":"func extractDeprecatedTag(t *types.Type) (*tagValue, int, int, error) {\n\treturn extractKubeVersionTag(deprecatedTagName, t)\n}","line":{"from":93,"to":95}} {"id":100030088,"name":"extractRemovedTag","signature":"func extractRemovedTag(t *types.Type) (*tagValue, int, int, error)","file":"staging/src/k8s.io/code-generator/cmd/prerelease-lifecycle-gen/prerelease-lifecycle-generators/status.go","code":"func extractRemovedTag(t *types.Type) (*tagValue, int, int, error) {\n\treturn extractKubeVersionTag(removedTagName, t)\n}","line":{"from":97,"to":99}} {"id":100030089,"name":"extractReplacementTag","signature":"func extractReplacementTag(t *types.Type) (group, version, kind string, hasReplacement bool, err error)","file":"staging/src/k8s.io/code-generator/cmd/prerelease-lifecycle-gen/prerelease-lifecycle-generators/status.go","code":"func extractReplacementTag(t *types.Type) (group, version, kind string, hasReplacement bool, err error) {\n\tcomments := append(append([]string{}, t.SecondClosestCommentLines...), t.CommentLines...)\n\n\ttagVals := types.ExtractCommentTags(\"+\", comments)[replacementTagName]\n\tif len(tagVals) == 0 {\n\t\t// No match for the tag.\n\t\treturn \"\", \"\", \"\", false, nil\n\t}\n\t// If there are multiple values, abort.\n\tif len(tagVals) \u003e 1 {\n\t\treturn \"\", \"\", \"\", false, fmt.Errorf(\"Found %d %s tags: %q\", len(tagVals), replacementTagName, tagVals)\n\t}\n\ttagValue := tagVals[0]\n\tparts := strings.Split(tagValue, \",\")\n\tif len(parts) != 3 {\n\t\treturn \"\", \"\", \"\", false, fmt.Errorf(`%s value must be \"\u003cgroup\u003e,\u003cversion\u003e,\u003ckind\u003e\", got %q`, replacementTagName, tagValue)\n\t}\n\tgroup, version, kind = parts[0], parts[1], parts[2]\n\tif len(version) == 0 || len(kind) == 0 {\n\t\treturn \"\", \"\", \"\", false, fmt.Errorf(`%s value must be \"\u003cgroup\u003e,\u003cversion\u003e,\u003ckind\u003e\", got %q`, replacementTagName, tagValue)\n\t}\n\t// sanity check the group\n\tif strings.ToLower(group) != group {\n\t\treturn \"\", \"\", \"\", false, fmt.Errorf(`replacement group must be all lower-case, got %q`, group)\n\t}\n\t// sanity check the version\n\tif !strings.HasPrefix(version, \"v\") || strings.ToLower(version) != version {\n\t\treturn \"\", \"\", \"\", false, fmt.Errorf(`replacement version must start with \"v\" and be all lower-case, got %q`, version)\n\t}\n\t// sanity check the kind\n\tif strings.ToUpper(kind[:1]) != kind[:1] {\n\t\treturn \"\", \"\", \"\", false, fmt.Errorf(`replacement kind must start with uppercase-letter, got %q`, kind)\n\t}\n\treturn group, version, kind, true, nil\n}","line":{"from":101,"to":135}} {"id":100030090,"name":"extractTag","signature":"func extractTag(tagName string, comments []string) *tagValue","file":"staging/src/k8s.io/code-generator/cmd/prerelease-lifecycle-gen/prerelease-lifecycle-generators/status.go","code":"func extractTag(tagName string, comments []string) *tagValue {\n\ttagVals := types.ExtractCommentTags(\"+\", comments)[tagName]\n\tif tagVals == nil {\n\t\t// No match for the tag.\n\t\treturn nil\n\t}\n\t// If there are multiple values, abort.\n\tif len(tagVals) \u003e 1 {\n\t\tklog.Fatalf(\"Found %d %s tags: %q\", len(tagVals), tagName, tagVals)\n\t}\n\n\t// If we got here we are returning something.\n\ttag := \u0026tagValue{}\n\n\t// Get the primary value.\n\tparts := strings.Split(tagVals[0], \",\")\n\tif len(parts) \u003e= 1 {\n\t\ttag.value = parts[0]\n\t}\n\n\t// Parse extra arguments.\n\tparts = parts[1:]\n\tfor i := range parts {\n\t\tkv := strings.SplitN(parts[i], \"=\", 2)\n\t\tk := kv[0]\n\t\t//v := \"\"\n\t\t//if len(kv) == 2 {\n\t\t//\tv = kv[1]\n\t\t//}\n\t\tswitch k {\n\t\t//case \"register\":\n\t\t//\tif v != \"false\" {\n\t\t//\t\ttag.register = true\n\t\t//\t}\n\t\tdefault:\n\t\t\tklog.Fatalf(\"Unsupported %s param: %q\", tagName, parts[i])\n\t\t}\n\t}\n\treturn tag\n}","line":{"from":137,"to":176}} {"id":100030091,"name":"NameSystems","signature":"func NameSystems() namer.NameSystems","file":"staging/src/k8s.io/code-generator/cmd/prerelease-lifecycle-gen/prerelease-lifecycle-generators/status.go","code":"// NameSystems returns the name system used by the generators in this package.\nfunc NameSystems() namer.NameSystems {\n\treturn namer.NameSystems{\n\t\t\"public\": namer.NewPublicNamer(1),\n\t\t\"raw\": namer.NewRawNamer(\"\", nil),\n\t}\n}","line":{"from":178,"to":184}} {"id":100030092,"name":"DefaultNameSystem","signature":"func DefaultNameSystem() string","file":"staging/src/k8s.io/code-generator/cmd/prerelease-lifecycle-gen/prerelease-lifecycle-generators/status.go","code":"// DefaultNameSystem returns the default name system for ordering the types to be\n// processed by the generators in this package.\nfunc DefaultNameSystem() string {\n\treturn \"public\"\n}","line":{"from":186,"to":190}} {"id":100030093,"name":"Packages","signature":"func Packages(context *generator.Context, arguments *args.GeneratorArgs) generator.Packages","file":"staging/src/k8s.io/code-generator/cmd/prerelease-lifecycle-gen/prerelease-lifecycle-generators/status.go","code":"// Packages makes the package definition.\nfunc Packages(context *generator.Context, arguments *args.GeneratorArgs) generator.Packages {\n\tboilerplate, err := arguments.LoadGoBoilerplate()\n\tif err != nil {\n\t\tklog.Fatalf(\"Failed loading boilerplate: %v\", err)\n\t}\n\n\tinputs := sets.NewString(context.Inputs...)\n\tpackages := generator.Packages{}\n\theader := append([]byte(fmt.Sprintf(\"// +build !%s\\n\\n\", arguments.GeneratedBuildTag)), boilerplate...)\n\n\tfor i := range inputs {\n\t\tklog.V(5).Infof(\"Considering pkg %q\", i)\n\t\tpkg := context.Universe[i]\n\t\tif pkg == nil {\n\t\t\t// If the input had no Go files, for example.\n\t\t\tcontinue\n\t\t}\n\n\t\tptag := extractTag(tagEnabledName, pkg.Comments)\n\t\tpkgNeedsGeneration := false\n\t\tif ptag != nil {\n\t\t\tpkgNeedsGeneration, err = strconv.ParseBool(ptag.value)\n\t\t\tif err != nil {\n\t\t\t\tklog.Fatalf(\"Package %v: unsupported %s value: %q :%w\", i, tagEnabledName, ptag.value, err)\n\t\t\t}\n\t\t}\n\t\tif !pkgNeedsGeneration {\n\t\t\tklog.V(5).Infof(\" skipping package\")\n\t\t\tcontinue\n\t\t}\n\t\tklog.V(3).Infof(\"Generating package %q\", pkg.Path)\n\n\t\t// If the pkg-scoped tag says to generate, we can skip scanning types.\n\t\tif !pkgNeedsGeneration {\n\t\t\t// If the pkg-scoped tag did not exist, scan all types for one that\n\t\t\t// explicitly wants generation.\n\t\t\tfor _, t := range pkg.Types {\n\t\t\t\tklog.V(5).Infof(\" considering type %q\", t.Name.String())\n\t\t\t\tttag := extractEnabledTypeTag(t)\n\t\t\t\tif ttag != nil \u0026\u0026 ttag.value == \"true\" {\n\t\t\t\t\tklog.V(5).Infof(\" tag=true\")\n\t\t\t\t\tif !isAPIType(t) {\n\t\t\t\t\t\tklog.Fatalf(\"Type %v requests deepcopy generation but is not copyable\", t)\n\t\t\t\t\t}\n\t\t\t\t\tpkgNeedsGeneration = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif pkgNeedsGeneration {\n\t\t\tpath := pkg.Path\n\t\t\t// if the source path is within a /vendor/ directory (for example,\n\t\t\t// k8s.io/kubernetes/vendor/k8s.io/apimachinery/pkg/apis/meta/v1), allow\n\t\t\t// generation to output to the proper relative path (under vendor).\n\t\t\t// Otherwise, the generator will create the file in the wrong location\n\t\t\t// in the output directory.\n\t\t\t// TODO: build a more fundamental concept in gengo for dealing with modifications\n\t\t\t// to vendored packages.\n\t\t\tif strings.HasPrefix(pkg.SourcePath, arguments.OutputBase) {\n\t\t\t\texpandedPath := strings.TrimPrefix(pkg.SourcePath, arguments.OutputBase)\n\t\t\t\tif strings.Contains(expandedPath, \"/vendor/\") {\n\t\t\t\t\tpath = expandedPath\n\t\t\t\t}\n\t\t\t}\n\t\t\tpackages = append(packages,\n\t\t\t\t\u0026generator.DefaultPackage{\n\t\t\t\t\tPackageName: strings.Split(filepath.Base(pkg.Path), \".\")[0],\n\t\t\t\t\tPackagePath: path,\n\t\t\t\t\tHeaderText: header,\n\t\t\t\t\tGeneratorFunc: func(c *generator.Context) (generators []generator.Generator) {\n\t\t\t\t\t\treturn []generator.Generator{\n\t\t\t\t\t\t\tNewPrereleaseLifecycleGen(arguments.OutputFileBaseName, pkg.Path),\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tFilterFunc: func(c *generator.Context, t *types.Type) bool {\n\t\t\t\t\t\treturn t.Name.Package == pkg.Path\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t}\n\t}\n\treturn packages\n}","line":{"from":192,"to":275}} {"id":100030094,"name":"NewPrereleaseLifecycleGen","signature":"func NewPrereleaseLifecycleGen(sanitizedName, targetPackage string) generator.Generator","file":"staging/src/k8s.io/code-generator/cmd/prerelease-lifecycle-gen/prerelease-lifecycle-generators/status.go","code":"// NewPrereleaseLifecycleGen creates a generator for the prerelease-lifecycle-generator\nfunc NewPrereleaseLifecycleGen(sanitizedName, targetPackage string) generator.Generator {\n\treturn \u0026genPreleaseLifecycle{\n\t\tDefaultGen: generator.DefaultGen{\n\t\t\tOptionalName: sanitizedName,\n\t\t},\n\t\ttargetPackage: targetPackage,\n\t\timports: generator.NewImportTracker(),\n\t\ttypesForInit: make([]*types.Type, 0),\n\t}\n}","line":{"from":285,"to":295}} {"id":100030095,"name":"Namers","signature":"func (g *genPreleaseLifecycle) Namers(c *generator.Context) namer.NameSystems","file":"staging/src/k8s.io/code-generator/cmd/prerelease-lifecycle-gen/prerelease-lifecycle-generators/status.go","code":"func (g *genPreleaseLifecycle) Namers(c *generator.Context) namer.NameSystems {\n\treturn namer.NameSystems{\n\t\t\"public\": namer.NewPublicNamer(1),\n\t\t\"intrapackage\": namer.NewPublicNamer(0),\n\t\t\"raw\": namer.NewRawNamer(\"\", nil),\n\t}\n}","line":{"from":297,"to":303}} {"id":100030096,"name":"Filter","signature":"func (g *genPreleaseLifecycle) Filter(c *generator.Context, t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/prerelease-lifecycle-gen/prerelease-lifecycle-generators/status.go","code":"func (g *genPreleaseLifecycle) Filter(c *generator.Context, t *types.Type) bool {\n\t// Filter out types not being processed or not copyable within the package.\n\tif !isAPIType(t) {\n\t\tklog.V(2).Infof(\"Type %v is not a valid target for status\", t)\n\t\treturn false\n\t}\n\tg.typesForInit = append(g.typesForInit, t)\n\treturn true\n}","line":{"from":305,"to":313}} {"id":100030097,"name":"versionMethod","signature":"func versionMethod(methodName string, t *types.Type) (*types.Signature, error)","file":"staging/src/k8s.io/code-generator/cmd/prerelease-lifecycle-gen/prerelease-lifecycle-generators/status.go","code":"// versionMethod returns the signature of an \u003cmethodName\u003e() method, nil or an error\n// if the type is wrong. Introduced() allows more efficient deep copy\n// implementations to be defined by the type's author. The correct signature\n//\n//\tfunc (t *T) \u003cmethodName\u003e() string\nfunc versionMethod(methodName string, t *types.Type) (*types.Signature, error) {\n\tf, found := t.Methods[methodName]\n\tif !found {\n\t\treturn nil, nil\n\t}\n\tif len(f.Signature.Parameters) != 0 {\n\t\treturn nil, fmt.Errorf(\"type %v: invalid %v signature, expected no parameters\", t, methodName)\n\t}\n\tif len(f.Signature.Results) != 2 {\n\t\treturn nil, fmt.Errorf(\"type %v: invalid %v signature, expected exactly two result types\", t, methodName)\n\t}\n\n\tptrRcvr := f.Signature.Receiver != nil \u0026\u0026 f.Signature.Receiver.Kind == types.Pointer \u0026\u0026 f.Signature.Receiver.Elem.Name == t.Name\n\tnonPtrRcvr := f.Signature.Receiver != nil \u0026\u0026 f.Signature.Receiver.Name == t.Name\n\n\tif !ptrRcvr \u0026\u0026 !nonPtrRcvr {\n\t\t// this should never happen\n\t\treturn nil, fmt.Errorf(\"type %v: invalid %v signature, expected a receiver of type %s or *%s\", t, methodName, t.Name.Name, t.Name.Name)\n\t}\n\n\treturn f.Signature, nil\n}","line":{"from":315,"to":341}} {"id":100030098,"name":"versionedMethodOrDie","signature":"func versionedMethodOrDie(methodName string, t *types.Type) *types.Signature","file":"staging/src/k8s.io/code-generator/cmd/prerelease-lifecycle-gen/prerelease-lifecycle-generators/status.go","code":"// versionedMethodOrDie returns the signature of a \u003cmethodName\u003e() method, nil or calls klog.Fatalf\n// if the type is wrong.\nfunc versionedMethodOrDie(methodName string, t *types.Type) *types.Signature {\n\tret, err := versionMethod(methodName, t)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\treturn ret\n}","line":{"from":343,"to":351}} {"id":100030099,"name":"isAPIType","signature":"func isAPIType(t *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/prerelease-lifecycle-gen/prerelease-lifecycle-generators/status.go","code":"// isAPIType indicates whether or not a type could be used to serve an API. That means, \"does it have TypeMeta\".\n// This doesn't mean the type is served, but we will handle all TypeMeta types.\nfunc isAPIType(t *types.Type) bool {\n\t// Filter out private types.\n\tif namer.IsPrivateGoName(t.Name.Name) {\n\t\treturn false\n\t}\n\n\tif t.Kind != types.Struct {\n\t\treturn false\n\t}\n\n\tfor _, currMember := range t.Members {\n\t\tif currMember.Embedded \u0026\u0026 currMember.Name == \"TypeMeta\" {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tif t.Kind == types.Alias {\n\t\treturn isAPIType(t.Underlying)\n\t}\n\n\treturn false\n}","line":{"from":353,"to":376}} {"id":100030100,"name":"isOtherPackage","signature":"func (g *genPreleaseLifecycle) isOtherPackage(pkg string) bool","file":"staging/src/k8s.io/code-generator/cmd/prerelease-lifecycle-gen/prerelease-lifecycle-generators/status.go","code":"func (g *genPreleaseLifecycle) isOtherPackage(pkg string) bool {\n\tif pkg == g.targetPackage {\n\t\treturn false\n\t}\n\tif strings.HasSuffix(pkg, \"\\\"\"+g.targetPackage+\"\\\"\") {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":378,"to":386}} {"id":100030101,"name":"Imports","signature":"func (g *genPreleaseLifecycle) Imports(c *generator.Context) (imports []string)","file":"staging/src/k8s.io/code-generator/cmd/prerelease-lifecycle-gen/prerelease-lifecycle-generators/status.go","code":"func (g *genPreleaseLifecycle) Imports(c *generator.Context) (imports []string) {\n\timportLines := []string{}\n\tfor _, singleImport := range g.imports.ImportLines() {\n\t\tif g.isOtherPackage(singleImport) {\n\t\t\timportLines = append(importLines, singleImport)\n\t\t}\n\t}\n\treturn importLines\n}","line":{"from":388,"to":396}} {"id":100030102,"name":"argsFromType","signature":"func (g *genPreleaseLifecycle) argsFromType(c *generator.Context, t *types.Type) (generator.Args, error)","file":"staging/src/k8s.io/code-generator/cmd/prerelease-lifecycle-gen/prerelease-lifecycle-generators/status.go","code":"func (g *genPreleaseLifecycle) argsFromType(c *generator.Context, t *types.Type) (generator.Args, error) {\n\ta := generator.Args{\n\t\t\"type\": t,\n\t}\n\t_, introducedMajor, introducedMinor, err := extractIntroducedTag(t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ta = a.\n\t\tWith(\"introducedMajor\", introducedMajor).\n\t\tWith(\"introducedMinor\", introducedMinor)\n\n\t// compute based on our policy\n\tdeprecatedMajor := introducedMajor\n\tdeprecatedMinor := introducedMinor + 3\n\t// if someone intentionally override the deprecation release\n\tif tagExists(deprecatedTagName, t) {\n\t\t_, deprecatedMajor, deprecatedMinor, err = extractDeprecatedTag(t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\ta = a.\n\t\tWith(\"deprecatedMajor\", deprecatedMajor).\n\t\tWith(\"deprecatedMinor\", deprecatedMinor)\n\n\t// compute based on our policy\n\tremovedMajor := deprecatedMajor\n\tremovedMinor := deprecatedMinor + 3\n\t// if someone intentionally override the removed release\n\tif tagExists(removedTagName, t) {\n\t\t_, removedMajor, removedMinor, err = extractRemovedTag(t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\ta = a.\n\t\tWith(\"removedMajor\", removedMajor).\n\t\tWith(\"removedMinor\", removedMinor)\n\n\treplacementGroup, replacementVersion, replacementKind, hasReplacement, err := extractReplacementTag(t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif hasReplacement {\n\t\tgvkType := c.Universe.Type(types.Name{Package: \"k8s.io/apimachinery/pkg/runtime/schema\", Name: \"GroupVersionKind\"})\n\t\tg.imports.AddType(gvkType)\n\t\ta = a.\n\t\t\tWith(\"replacementGroup\", replacementGroup).\n\t\t\tWith(\"replacementVersion\", replacementVersion).\n\t\t\tWith(\"replacementKind\", replacementKind).\n\t\t\tWith(\"GroupVersionKind\", gvkType)\n\t}\n\n\treturn a, nil\n}","line":{"from":398,"to":453}} {"id":100030103,"name":"Init","signature":"func (g *genPreleaseLifecycle) Init(c *generator.Context, w io.Writer) error","file":"staging/src/k8s.io/code-generator/cmd/prerelease-lifecycle-gen/prerelease-lifecycle-generators/status.go","code":"func (g *genPreleaseLifecycle) Init(c *generator.Context, w io.Writer) error {\n\treturn nil\n}","line":{"from":455,"to":457}} {"id":100030104,"name":"GenerateType","signature":"func (g *genPreleaseLifecycle) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error","file":"staging/src/k8s.io/code-generator/cmd/prerelease-lifecycle-gen/prerelease-lifecycle-generators/status.go","code":"func (g *genPreleaseLifecycle) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {\n\tklog.V(3).Infof(\"Generating prerelease-lifecycle for type %v\", t)\n\n\tsw := generator.NewSnippetWriter(w, c, \"$\", \"$\")\n\targs, err := g.argsFromType(c, t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif versionedMethodOrDie(\"APILifecycleIntroduced\", t) == nil {\n\t\tsw.Do(\"// APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison.\\n\", args)\n\t\tsw.Do(\"// It is controlled by \\\"\"+introducedTagName+\"\\\" tags in types.go.\\n\", args)\n\t\tsw.Do(\"func (in *$.type|intrapackage$) APILifecycleIntroduced() (major, minor int) {\\n\", args)\n\t\tsw.Do(\" return $.introducedMajor$, $.introducedMinor$\\n\", args)\n\t\tsw.Do(\"}\\n\\n\", nil)\n\t}\n\tif versionedMethodOrDie(\"APILifecycleDeprecated\", t) == nil {\n\t\tsw.Do(\"// APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison.\\n\", args)\n\t\tsw.Do(\"// It is controlled by \\\"\"+deprecatedTagName+\"\\\" tags in types.go or \\\"\"+introducedTagName+\"\\\" plus three minor.\\n\", args)\n\t\tsw.Do(\"func (in *$.type|intrapackage$) APILifecycleDeprecated() (major, minor int) {\\n\", args)\n\t\tsw.Do(\" return $.deprecatedMajor$, $.deprecatedMinor$\\n\", args)\n\t\tsw.Do(\"}\\n\\n\", nil)\n\t}\n\tif _, hasReplacement := args[\"replacementKind\"]; hasReplacement {\n\t\tif versionedMethodOrDie(\"APILifecycleReplacement\", t) == nil {\n\t\t\tsw.Do(\"// APILifecycleReplacement is an autogenerated function, returning the group, version, and kind that should be used instead of this deprecated type.\\n\", args)\n\t\t\tsw.Do(\"// It is controlled by \\\"\"+replacementTagName+\"=\u003cgroup\u003e,\u003cversion\u003e,\u003ckind\u003e\\\" tags in types.go.\\n\", args)\n\t\t\tsw.Do(\"func (in *$.type|intrapackage$) APILifecycleReplacement() ($.GroupVersionKind|raw$) {\\n\", args)\n\t\t\tsw.Do(\" return $.GroupVersionKind|raw${Group:\\\"$.replacementGroup$\\\", Version:\\\"$.replacementVersion$\\\", Kind:\\\"$.replacementKind$\\\"}\\n\", args)\n\t\t\tsw.Do(\"}\\n\\n\", nil)\n\t\t}\n\t}\n\tif versionedMethodOrDie(\"APILifecycleRemoved\", t) == nil {\n\t\tsw.Do(\"// APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison.\\n\", args)\n\t\tsw.Do(\"// It is controlled by \\\"\"+removedTagName+\"\\\" tags in types.go or \\\"\"+deprecatedTagName+\"\\\" plus three minor.\\n\", args)\n\t\tsw.Do(\"func (in *$.type|intrapackage$) APILifecycleRemoved() (major, minor int) {\\n\", args)\n\t\tsw.Do(\" return $.removedMajor$, $.removedMinor$\\n\", args)\n\t\tsw.Do(\"}\\n\\n\", nil)\n\t}\n\n\treturn sw.Error()\n}","line":{"from":459,"to":500}} {"id":100030105,"name":"NewDefaults","signature":"func NewDefaults() *args.GeneratorArgs","file":"staging/src/k8s.io/code-generator/cmd/register-gen/args/args.go","code":"// NewDefaults returns default arguments for the generator.\nfunc NewDefaults() *args.GeneratorArgs {\n\tgenericArgs := args.Default().WithoutDefaultFlagParsing()\n\tgenericArgs.OutputFileBaseName = \"zz_generated.register\"\n\treturn genericArgs\n}","line":{"from":25,"to":30}} {"id":100030106,"name":"Validate","signature":"func Validate(genericArgs *args.GeneratorArgs) error","file":"staging/src/k8s.io/code-generator/cmd/register-gen/args/args.go","code":"// Validate checks the given arguments.\nfunc Validate(genericArgs *args.GeneratorArgs) error {\n\tif len(genericArgs.OutputFileBaseName) == 0 {\n\t\treturn fmt.Errorf(\"output file base name cannot be empty\")\n\t}\n\n\treturn nil\n}","line":{"from":32,"to":39}} {"id":100030107,"name":"NameSystems","signature":"func NameSystems() namer.NameSystems","file":"staging/src/k8s.io/code-generator/cmd/register-gen/generators/packages.go","code":"// NameSystems returns the name system used by the generators in this package.\nfunc NameSystems() namer.NameSystems {\n\treturn namer.NameSystems{}\n}","line":{"from":34,"to":37}} {"id":100030108,"name":"DefaultNameSystem","signature":"func DefaultNameSystem() string","file":"staging/src/k8s.io/code-generator/cmd/register-gen/generators/packages.go","code":"// DefaultNameSystem returns the default name system for ordering the types to be\n// processed by the generators in this package.\nfunc DefaultNameSystem() string {\n\treturn \"public\"\n}","line":{"from":39,"to":43}} {"id":100030109,"name":"Packages","signature":"func Packages(context *generator.Context, arguments *args.GeneratorArgs) generator.Packages","file":"staging/src/k8s.io/code-generator/cmd/register-gen/generators/packages.go","code":"// Packages makes packages to generate.\nfunc Packages(context *generator.Context, arguments *args.GeneratorArgs) generator.Packages {\n\tboilerplate, err := arguments.LoadGoBoilerplate()\n\tif err != nil {\n\t\tklog.Fatalf(\"Failed loading boilerplate: %v\", err)\n\t}\n\n\tpackages := generator.Packages{}\n\tfor _, inputDir := range arguments.InputDirs {\n\t\tpkg := context.Universe.Package(inputDir)\n\t\tinternal, err := isInternal(pkg)\n\t\tif err != nil {\n\t\t\tklog.V(5).Infof(\"skipping the generation of %s file, due to err %v\", arguments.OutputFileBaseName, err)\n\t\t\tcontinue\n\t\t}\n\t\tif internal {\n\t\t\tklog.V(5).Infof(\"skipping the generation of %s file because %s package contains internal types, note that internal types don't have \\\"json\\\" tags\", arguments.OutputFileBaseName, pkg.Name)\n\t\t\tcontinue\n\t\t}\n\t\tregisterFileName := \"register.go\"\n\t\tsearchPath := path.Join(args.DefaultSourceTree(), inputDir, registerFileName)\n\t\tif _, err := os.Stat(path.Join(searchPath)); err == nil {\n\t\t\tklog.V(5).Infof(\"skipping the generation of %s file because %s already exists in the path %s\", arguments.OutputFileBaseName, registerFileName, searchPath)\n\t\t\tcontinue\n\t\t} else if err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\t\tklog.Fatalf(\"an error %v has occurred while checking if %s exists\", err, registerFileName)\n\t\t}\n\n\t\tgv := clientgentypes.GroupVersion{}\n\t\t{\n\t\t\tpathParts := strings.Split(pkg.Path, \"/\")\n\t\t\tif len(pathParts) \u003c 2 {\n\t\t\t\tklog.Errorf(\"the path of the package must contain the group name and the version, path = %s\", pkg.Path)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgv.Group = clientgentypes.Group(pathParts[len(pathParts)-2])\n\t\t\tgv.Version = clientgentypes.Version(pathParts[len(pathParts)-1])\n\n\t\t\t// if there is a comment of the form \"// +groupName=somegroup\" or \"// +groupName=somegroup.foo.bar.io\",\n\t\t\t// extract the fully qualified API group name from it and overwrite the group inferred from the package path\n\t\t\tif override := types.ExtractCommentTags(\"+\", pkg.Comments)[\"groupName\"]; override != nil {\n\t\t\t\tgroupName := override[0]\n\t\t\t\tklog.V(5).Infof(\"overriding the group name with = %s\", groupName)\n\t\t\t\tgv.Group = clientgentypes.Group(groupName)\n\t\t\t}\n\t\t}\n\n\t\ttypesToRegister := []*types.Type{}\n\t\tfor _, t := range pkg.Types {\n\t\t\tklog.V(5).Infof(\"considering type = %s\", t.Name.String())\n\t\t\tfor _, typeMember := range t.Members {\n\t\t\t\tif typeMember.Name == \"TypeMeta\" \u0026\u0026 typeMember.Embedded == true {\n\t\t\t\t\ttypesToRegister = append(typesToRegister, t)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpackages = append(packages,\n\t\t\t\u0026generator.DefaultPackage{\n\t\t\t\tPackageName: pkg.Name,\n\t\t\t\tPackagePath: pkg.Path,\n\t\t\t\tHeaderText: boilerplate,\n\t\t\t\tGeneratorFunc: func(c *generator.Context) (generators []generator.Generator) {\n\t\t\t\t\treturn []generator.Generator{\n\t\t\t\t\t\t\u0026registerExternalGenerator{\n\t\t\t\t\t\t\tDefaultGen: generator.DefaultGen{\n\t\t\t\t\t\t\t\tOptionalName: arguments.OutputFileBaseName,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tgv: gv,\n\t\t\t\t\t\t\ttypesToGenerate: typesToRegister,\n\t\t\t\t\t\t\toutputPackage: pkg.Path,\n\t\t\t\t\t\t\timports: generator.NewImportTracker(),\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t})\n\t}\n\n\treturn packages\n}","line":{"from":45,"to":124}} {"id":100030110,"name":"isInternal","signature":"func isInternal(p *types.Package) (bool, error)","file":"staging/src/k8s.io/code-generator/cmd/register-gen/generators/packages.go","code":"// isInternal determines whether the given package\n// contains the internal types or not\nfunc isInternal(p *types.Package) (bool, error) {\n\tfor _, t := range p.Types {\n\t\tfor _, member := range t.Members {\n\t\t\tif member.Name == \"TypeMeta\" {\n\t\t\t\treturn !strings.Contains(member.Tags, \"json\"), nil\n\t\t\t}\n\t\t}\n\t}\n\treturn false, fmt.Errorf(\"unable to find TypeMeta for any types in package %s\", p.Path)\n}","line":{"from":126,"to":137}} {"id":100030111,"name":"Filter","signature":"func (g *registerExternalGenerator) Filter(_ *generator.Context, _ *types.Type) bool","file":"staging/src/k8s.io/code-generator/cmd/register-gen/generators/register_external.go","code":"func (g *registerExternalGenerator) Filter(_ *generator.Context, _ *types.Type) bool {\n\treturn false\n}","line":{"from":39,"to":41}} {"id":100030112,"name":"Imports","signature":"func (g *registerExternalGenerator) Imports(c *generator.Context) (imports []string)","file":"staging/src/k8s.io/code-generator/cmd/register-gen/generators/register_external.go","code":"func (g *registerExternalGenerator) Imports(c *generator.Context) (imports []string) {\n\treturn g.imports.ImportLines()\n}","line":{"from":43,"to":45}} {"id":100030113,"name":"Namers","signature":"func (g *registerExternalGenerator) Namers(_ *generator.Context) namer.NameSystems","file":"staging/src/k8s.io/code-generator/cmd/register-gen/generators/register_external.go","code":"func (g *registerExternalGenerator) Namers(_ *generator.Context) namer.NameSystems {\n\treturn namer.NameSystems{\n\t\t\"raw\": namer.NewRawNamer(g.outputPackage, g.imports),\n\t}\n}","line":{"from":47,"to":51}} {"id":100030114,"name":"Finalize","signature":"func (g *registerExternalGenerator) Finalize(context *generator.Context, w io.Writer) error","file":"staging/src/k8s.io/code-generator/cmd/register-gen/generators/register_external.go","code":"func (g *registerExternalGenerator) Finalize(context *generator.Context, w io.Writer) error {\n\ttypesToGenerateOnlyNames := make([]string, len(g.typesToGenerate))\n\tfor index, typeToGenerate := range g.typesToGenerate {\n\t\ttypesToGenerateOnlyNames[index] = typeToGenerate.Name.Name\n\t}\n\n\t// sort the list of types to register, so that the generator produces stable output\n\tsort.Strings(typesToGenerateOnlyNames)\n\n\tsw := generator.NewSnippetWriter(w, context, \"$\", \"$\")\n\tm := map[string]interface{}{\n\t\t\"groupName\": g.gv.Group,\n\t\t\"version\": g.gv.Version,\n\t\t\"types\": typesToGenerateOnlyNames,\n\t\t\"addToGroupVersion\": context.Universe.Function(types.Name{Package: \"k8s.io/apimachinery/pkg/apis/meta/v1\", Name: \"AddToGroupVersion\"}),\n\t\t\"groupVersion\": context.Universe.Type(types.Name{Package: \"k8s.io/apimachinery/pkg/apis/meta/v1\", Name: \"GroupVersion\"}),\n\t}\n\tsw.Do(registerExternalTypesTemplate, m)\n\treturn sw.Error()\n}","line":{"from":53,"to":72}} {"id":100030115,"name":"main","signature":"func main()","file":"staging/src/k8s.io/code-generator/cmd/register-gen/main.go","code":"func main() {\n\tklog.InitFlags(nil)\n\tgenericArgs := generatorargs.NewDefaults()\n\tgenericArgs.AddFlags(pflag.CommandLine)\n\tflag.Set(\"logtostderr\", \"true\")\n\tpflag.CommandLine.AddGoFlagSet(flag.CommandLine)\n\n\tpflag.Parse()\n\tif err := generatorargs.Validate(genericArgs); err != nil {\n\t\tklog.Fatalf(\"Error: %v\", err)\n\t}\n\n\tif err := genericArgs.Execute(\n\t\tgenerators.NameSystems(),\n\t\tgenerators.DefaultNameSystem(),\n\t\tgenerators.Packages,\n\t); err != nil {\n\t\tklog.Fatalf(\"Error: %v\", err)\n\t}\n\tklog.V(2).Info(\"Completed successfully.\")\n}","line":{"from":29,"to":49}} {"id":100030116,"name":"main","signature":"func main()","file":"staging/src/k8s.io/code-generator/cmd/set-gen/main.go","code":"func main() {\n\tklog.InitFlags(nil)\n\targuments := args.Default()\n\n\t// Override defaults.\n\targuments.InputDirs = []string{\"k8s.io/kubernetes/pkg/util/sets/types\"}\n\targuments.OutputPackagePath = \"k8s.io/apimachinery/pkg/util/sets\"\n\n\tif err := arguments.Execute(\n\t\tgenerators.NameSystems(),\n\t\tgenerators.DefaultNameSystem(),\n\t\tgenerators.Packages,\n\t); err != nil {\n\t\tklog.Errorf(\"Error: %v\", err)\n\t\tos.Exit(1)\n\t}\n\tklog.V(2).Info(\"Completed successfully.\")\n}","line":{"from":36,"to":53}} {"id":100030117,"name":"Name","signature":"func (n *TagOverrideNamer) Name(t *types.Type) string","file":"staging/src/k8s.io/code-generator/pkg/namer/tag-override.go","code":"// Name returns the tag value if it exists. It no tag was found the fallback namer will be used\nfunc (n *TagOverrideNamer) Name(t *types.Type) string {\n\tif nameOverride := extractTag(n.tagName, append(t.SecondClosestCommentLines, t.CommentLines...)); nameOverride != \"\" {\n\t\treturn nameOverride\n\t}\n\n\treturn n.fallback.Name(t)\n}","line":{"from":31,"to":38}} {"id":100030118,"name":"NewTagOverrideNamer","signature":"func NewTagOverrideNamer(tagName string, fallback namer.Namer) namer.Namer","file":"staging/src/k8s.io/code-generator/pkg/namer/tag-override.go","code":"// NewTagOverrideNamer creates a namer.Namer which uses the contents of the given tag as\n// the name, or falls back to another Namer if the tag is not present.\nfunc NewTagOverrideNamer(tagName string, fallback namer.Namer) namer.Namer {\n\treturn \u0026TagOverrideNamer{\n\t\ttagName: tagName,\n\t\tfallback: fallback,\n\t}\n}","line":{"from":40,"to":47}} {"id":100030119,"name":"extractTag","signature":"func extractTag(key string, lines []string) string","file":"staging/src/k8s.io/code-generator/pkg/namer/tag-override.go","code":"// extractTag gets the comment-tags for the key. If the tag did not exist, it\n// returns the empty string.\nfunc extractTag(key string, lines []string) string {\n\tval, present := types.ExtractCommentTags(\"+\", lines)[key]\n\tif !present || len(val) \u003c 1 {\n\t\treturn \"\"\n\t}\n\n\treturn val[0]\n}","line":{"from":49,"to":58}} {"id":100030120,"name":"CurrentPackage","signature":"func CurrentPackage() string","file":"staging/src/k8s.io/code-generator/pkg/util/build.go","code":"// CurrentPackage returns the go package of the current directory, or \"\" if it cannot\n// be derived from the GOPATH.\nfunc CurrentPackage() string {\n\tfor _, root := range gobuild.Default.SrcDirs() {\n\t\tif pkg, ok := hasSubdir(root, \".\"); ok {\n\t\t\treturn pkg\n\t\t}\n\t}\n\treturn \"\"\n}","line":{"from":25,"to":34}} {"id":100030121,"name":"hasSubdir","signature":"func hasSubdir(root, dir string) (rel string, ok bool)","file":"staging/src/k8s.io/code-generator/pkg/util/build.go","code":"func hasSubdir(root, dir string) (rel string, ok bool) {\n\t// ensure a tailing separator to properly compare on word-boundaries\n\tconst sep = string(filepath.Separator)\n\troot = filepath.Clean(root)\n\tif !strings.HasSuffix(root, sep) {\n\t\troot += sep\n\t}\n\n\t// check whether root dir starts with root\n\tdir = filepath.Clean(dir)\n\tif !strings.HasPrefix(dir, root) {\n\t\treturn \"\", false\n\t}\n\n\t// cut off root\n\treturn filepath.ToSlash(dir[len(root):]), true\n}","line":{"from":36,"to":52}} {"id":100030122,"name":"Vendorless","signature":"func Vendorless(p string) string","file":"staging/src/k8s.io/code-generator/pkg/util/build.go","code":"// Vendorless trims vendor prefix from a package path to make it canonical\nfunc Vendorless(p string) string {\n\tif pos := strings.LastIndex(p, \"/vendor/\"); pos != -1 {\n\t\treturn p[pos+len(\"/vendor/\"):]\n\t}\n\treturn p\n}","line":{"from":54,"to":60}} {"id":100030123,"name":"PluralExceptionListToMapOrDie","signature":"func PluralExceptionListToMapOrDie(pluralExceptions []string) map[string]string","file":"staging/src/k8s.io/code-generator/pkg/util/plural_exceptions.go","code":"// PluralExceptionListToMapOrDie converts the list in \"Type:PluralType\" to map[string]string.\n// This is used for pluralizer.\n// If the format is wrong, this function will panic.\nfunc PluralExceptionListToMapOrDie(pluralExceptions []string) map[string]string {\n\tpluralExceptionMap := make(map[string]string, len(pluralExceptions))\n\tfor i := range pluralExceptions {\n\t\tparts := strings.Split(pluralExceptions[i], \":\")\n\t\tif len(parts) != 2 {\n\t\t\tpanic(fmt.Sprintf(\"invalid plural exception definition: %s\", pluralExceptions[i]))\n\t\t}\n\t\tpluralExceptionMap[parts[0]] = parts[1]\n\t}\n\treturn pluralExceptionMap\n}","line":{"from":24,"to":37}} {"id":100030124,"name":"init","signature":"func init()","file":"staging/src/k8s.io/component-base/cli/flag/ciphersuites_flag.go","code":"func init() {\n\tfor _, suite := range tls.CipherSuites() {\n\t\tciphers[suite.Name] = suite.ID\n\t}\n\t// keep legacy names for backward compatibility\n\tciphers[\"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305\"] = tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256\n\tciphers[\"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305\"] = tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256\n\n\tfor _, suite := range tls.InsecureCipherSuites() {\n\t\tinsecureCiphers[suite.Name] = suite.ID\n\t}\n}","line":{"from":33,"to":44}} {"id":100030125,"name":"InsecureTLSCiphers","signature":"func InsecureTLSCiphers() map[string]uint16","file":"staging/src/k8s.io/component-base/cli/flag/ciphersuites_flag.go","code":"// InsecureTLSCiphers returns the cipher suites implemented by crypto/tls which have\n// security issues.\nfunc InsecureTLSCiphers() map[string]uint16 {\n\tcipherKeys := make(map[string]uint16, len(insecureCiphers))\n\tfor k, v := range insecureCiphers {\n\t\tcipherKeys[k] = v\n\t}\n\treturn cipherKeys\n}","line":{"from":46,"to":54}} {"id":100030126,"name":"InsecureTLSCipherNames","signature":"func InsecureTLSCipherNames() []string","file":"staging/src/k8s.io/component-base/cli/flag/ciphersuites_flag.go","code":"// InsecureTLSCipherNames returns a list of cipher suite names implemented by crypto/tls\n// which have security issues.\nfunc InsecureTLSCipherNames() []string {\n\tcipherKeys := sets.NewString()\n\tfor key := range insecureCiphers {\n\t\tcipherKeys.Insert(key)\n\t}\n\treturn cipherKeys.List()\n}","line":{"from":56,"to":64}} {"id":100030127,"name":"PreferredTLSCipherNames","signature":"func PreferredTLSCipherNames() []string","file":"staging/src/k8s.io/component-base/cli/flag/ciphersuites_flag.go","code":"// PreferredTLSCipherNames returns a list of cipher suite names implemented by crypto/tls.\nfunc PreferredTLSCipherNames() []string {\n\tcipherKeys := sets.NewString()\n\tfor key := range ciphers {\n\t\tcipherKeys.Insert(key)\n\t}\n\treturn cipherKeys.List()\n}","line":{"from":66,"to":73}} {"id":100030128,"name":"allCiphers","signature":"func allCiphers() map[string]uint16","file":"staging/src/k8s.io/component-base/cli/flag/ciphersuites_flag.go","code":"func allCiphers() map[string]uint16 {\n\tacceptedCiphers := make(map[string]uint16, len(ciphers)+len(insecureCiphers))\n\tfor k, v := range ciphers {\n\t\tacceptedCiphers[k] = v\n\t}\n\tfor k, v := range insecureCiphers {\n\t\tacceptedCiphers[k] = v\n\t}\n\treturn acceptedCiphers\n}","line":{"from":75,"to":84}} {"id":100030129,"name":"TLSCipherPossibleValues","signature":"func TLSCipherPossibleValues() []string","file":"staging/src/k8s.io/component-base/cli/flag/ciphersuites_flag.go","code":"// TLSCipherPossibleValues returns all acceptable cipher suite names.\n// This is a combination of both InsecureTLSCipherNames() and PreferredTLSCipherNames().\nfunc TLSCipherPossibleValues() []string {\n\tcipherKeys := sets.NewString()\n\tacceptedCiphers := allCiphers()\n\tfor key := range acceptedCiphers {\n\t\tcipherKeys.Insert(key)\n\t}\n\treturn cipherKeys.List()\n}","line":{"from":86,"to":95}} {"id":100030130,"name":"TLSCipherSuites","signature":"func TLSCipherSuites(cipherNames []string) ([]uint16, error)","file":"staging/src/k8s.io/component-base/cli/flag/ciphersuites_flag.go","code":"// TLSCipherSuites returns a list of cipher suite IDs from the cipher suite names passed.\nfunc TLSCipherSuites(cipherNames []string) ([]uint16, error) {\n\tif len(cipherNames) == 0 {\n\t\treturn nil, nil\n\t}\n\tciphersIntSlice := make([]uint16, 0)\n\tpossibleCiphers := allCiphers()\n\tfor _, cipher := range cipherNames {\n\t\tintValue, ok := possibleCiphers[cipher]\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"Cipher suite %s not supported or doesn't exist\", cipher)\n\t\t}\n\t\tciphersIntSlice = append(ciphersIntSlice, intValue)\n\t}\n\treturn ciphersIntSlice, nil\n}","line":{"from":97,"to":112}} {"id":100030131,"name":"TLSPossibleVersions","signature":"func TLSPossibleVersions() []string","file":"staging/src/k8s.io/component-base/cli/flag/ciphersuites_flag.go","code":"// TLSPossibleVersions returns all acceptable values for TLS Version.\nfunc TLSPossibleVersions() []string {\n\tversionsKeys := sets.NewString()\n\tfor key := range versions {\n\t\tversionsKeys.Insert(key)\n\t}\n\treturn versionsKeys.List()\n}","line":{"from":121,"to":128}} {"id":100030132,"name":"TLSVersion","signature":"func TLSVersion(versionName string) (uint16, error)","file":"staging/src/k8s.io/component-base/cli/flag/ciphersuites_flag.go","code":"// TLSVersion returns the TLS Version ID for the version name passed.\nfunc TLSVersion(versionName string) (uint16, error) {\n\tif len(versionName) == 0 {\n\t\treturn DefaultTLSVersion(), nil\n\t}\n\tif version, ok := versions[versionName]; ok {\n\t\treturn version, nil\n\t}\n\treturn 0, fmt.Errorf(\"unknown tls version %q\", versionName)\n}","line":{"from":130,"to":139}} {"id":100030133,"name":"DefaultTLSVersion","signature":"func DefaultTLSVersion() uint16","file":"staging/src/k8s.io/component-base/cli/flag/ciphersuites_flag.go","code":"// DefaultTLSVersion defines the default TLS Version.\nfunc DefaultTLSVersion() uint16 {\n\t// Can't use SSLv3 because of POODLE and BEAST\n\t// Can't use TLSv1.0 because of POODLE and BEAST using CBC cipher\n\t// Can't use TLSv1.1 because of RC4 cipher usage\n\treturn tls.VersionTLS12\n}","line":{"from":141,"to":147}} {"id":100030134,"name":"NewColonSeparatedMultimapStringString","signature":"func NewColonSeparatedMultimapStringString(m *map[string][]string) *ColonSeparatedMultimapStringString","file":"staging/src/k8s.io/component-base/cli/flag/colon_separated_multimap_string_string.go","code":"// NewColonSeparatedMultimapStringString takes a pointer to a map[string][]string and returns the\n// ColonSeparatedMultimapStringString flag parsing shim for that map.\nfunc NewColonSeparatedMultimapStringString(m *map[string][]string) *ColonSeparatedMultimapStringString {\n\treturn \u0026ColonSeparatedMultimapStringString{Multimap: m}\n}","line":{"from":40,"to":44}} {"id":100030135,"name":"Set","signature":"func (m *ColonSeparatedMultimapStringString) Set(value string) error","file":"staging/src/k8s.io/component-base/cli/flag/colon_separated_multimap_string_string.go","code":"// Set implements github.com/spf13/pflag.Value\nfunc (m *ColonSeparatedMultimapStringString) Set(value string) error {\n\tif m.Multimap == nil {\n\t\treturn fmt.Errorf(\"no target (nil pointer to map[string][]string)\")\n\t}\n\tif !m.initialized || *m.Multimap == nil {\n\t\t// clear default values, or allocate if no existing map\n\t\t*m.Multimap = make(map[string][]string)\n\t\tm.initialized = true\n\t}\n\tfor _, pair := range strings.Split(value, \",\") {\n\t\tif len(pair) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tkv := strings.SplitN(pair, \":\", 2)\n\t\tif len(kv) != 2 {\n\t\t\treturn fmt.Errorf(\"malformed pair, expect string:string\")\n\t\t}\n\t\tk := strings.TrimSpace(kv[0])\n\t\tv := strings.TrimSpace(kv[1])\n\t\t(*m.Multimap)[k] = append((*m.Multimap)[k], v)\n\t}\n\treturn nil\n}","line":{"from":46,"to":69}} {"id":100030136,"name":"String","signature":"func (m *ColonSeparatedMultimapStringString) String() string","file":"staging/src/k8s.io/component-base/cli/flag/colon_separated_multimap_string_string.go","code":"// String implements github.com/spf13/pflag.Value\nfunc (m *ColonSeparatedMultimapStringString) String() string {\n\ttype kv struct {\n\t\tk string\n\t\tv string\n\t}\n\tkvs := make([]kv, 0, len(*m.Multimap))\n\tfor k, vs := range *m.Multimap {\n\t\tfor i := range vs {\n\t\t\tkvs = append(kvs, kv{k: k, v: vs[i]})\n\t\t}\n\t}\n\t// stable sort by keys, order of values should be preserved\n\tsort.SliceStable(kvs, func(i, j int) bool {\n\t\treturn kvs[i].k \u003c kvs[j].k\n\t})\n\tpairs := make([]string, 0, len(kvs))\n\tfor i := range kvs {\n\t\tpairs = append(pairs, fmt.Sprintf(\"%s:%s\", kvs[i].k, kvs[i].v))\n\t}\n\treturn strings.Join(pairs, \",\")\n}","line":{"from":71,"to":92}} {"id":100030137,"name":"Type","signature":"func (m *ColonSeparatedMultimapStringString) Type() string","file":"staging/src/k8s.io/component-base/cli/flag/colon_separated_multimap_string_string.go","code":"// Type implements github.com/spf13/pflag.Value\nfunc (m *ColonSeparatedMultimapStringString) Type() string {\n\treturn \"colonSeparatedMultimapStringString\"\n}","line":{"from":94,"to":97}} {"id":100030138,"name":"Empty","signature":"func (m *ColonSeparatedMultimapStringString) Empty() bool","file":"staging/src/k8s.io/component-base/cli/flag/colon_separated_multimap_string_string.go","code":"// Empty implements OmitEmpty\nfunc (m *ColonSeparatedMultimapStringString) Empty() bool {\n\treturn len(*m.Multimap) == 0\n}","line":{"from":99,"to":102}} {"id":100030139,"name":"String","signature":"func (m *ConfigurationMap) String() string","file":"staging/src/k8s.io/component-base/cli/flag/configuration_map.go","code":"func (m *ConfigurationMap) String() string {\n\tpairs := []string{}\n\tfor k, v := range *m {\n\t\tpairs = append(pairs, fmt.Sprintf(\"%s=%s\", k, v))\n\t}\n\tsort.Strings(pairs)\n\treturn strings.Join(pairs, \",\")\n}","line":{"from":27,"to":34}} {"id":100030140,"name":"Set","signature":"func (m *ConfigurationMap) Set(value string) error","file":"staging/src/k8s.io/component-base/cli/flag/configuration_map.go","code":"func (m *ConfigurationMap) Set(value string) error {\n\tfor _, s := range strings.Split(value, \",\") {\n\t\tif len(s) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tarr := strings.SplitN(s, \"=\", 2)\n\t\tif len(arr) == 2 {\n\t\t\t(*m)[strings.TrimSpace(arr[0])] = strings.TrimSpace(arr[1])\n\t\t} else {\n\t\t\t(*m)[strings.TrimSpace(arr[0])] = \"\"\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":36,"to":49}} {"id":100030141,"name":"Type","signature":"func (*ConfigurationMap) Type() string","file":"staging/src/k8s.io/component-base/cli/flag/configuration_map.go","code":"func (*ConfigurationMap) Type() string {\n\treturn \"mapStringString\"\n}","line":{"from":51,"to":53}} {"id":100030142,"name":"WordSepNormalizeFunc","signature":"func WordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName","file":"staging/src/k8s.io/component-base/cli/flag/flags.go","code":"// WordSepNormalizeFunc changes all flags that contain \"_\" separators\nfunc WordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {\n\tif strings.Contains(name, \"_\") {\n\t\treturn pflag.NormalizedName(strings.Replace(name, \"_\", \"-\", -1))\n\t}\n\treturn pflag.NormalizedName(name)\n}","line":{"from":29,"to":35}} {"id":100030143,"name":"WarnWordSepNormalizeFunc","signature":"func WarnWordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName","file":"staging/src/k8s.io/component-base/cli/flag/flags.go","code":"// WarnWordSepNormalizeFunc changes and warns for flags that contain \"_\" separators\nfunc WarnWordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {\n\tif strings.Contains(name, \"_\") {\n\t\tnname := strings.Replace(name, \"_\", \"-\", -1)\n\t\tif _, alreadyWarned := underscoreWarnings[name]; !alreadyWarned {\n\t\t\tklog.Warningf(\"using an underscore in a flag name is not supported. %s has been converted to %s.\", name, nname)\n\t\t\tunderscoreWarnings[name] = true\n\t\t}\n\n\t\treturn pflag.NormalizedName(nname)\n\t}\n\treturn pflag.NormalizedName(name)\n}","line":{"from":37,"to":49}} {"id":100030144,"name":"InitFlags","signature":"func InitFlags()","file":"staging/src/k8s.io/component-base/cli/flag/flags.go","code":"// InitFlags normalizes, parses, then logs the command line flags\nfunc InitFlags() {\n\tpflag.CommandLine.SetNormalizeFunc(WordSepNormalizeFunc)\n\tpflag.CommandLine.AddGoFlagSet(goflag.CommandLine)\n\tpflag.Parse()\n\tpflag.VisitAll(func(flag *pflag.Flag) {\n\t\tklog.V(2).Infof(\"FLAG: --%s=%q\", flag.Name, flag.Value)\n\t})\n}","line":{"from":51,"to":59}} {"id":100030145,"name":"PrintFlags","signature":"func PrintFlags(flags *pflag.FlagSet)","file":"staging/src/k8s.io/component-base/cli/flag/flags.go","code":"// PrintFlags logs the flags in the flagset\nfunc PrintFlags(flags *pflag.FlagSet) {\n\tflags.VisitAll(func(flag *pflag.Flag) {\n\t\tklog.V(1).Infof(\"FLAG: --%s=%q\", flag.Name, flag.Value)\n\t})\n}","line":{"from":61,"to":66}} {"id":100030146,"name":"NewLangleSeparatedMapStringString","signature":"func NewLangleSeparatedMapStringString(m *map[string]string) *LangleSeparatedMapStringString","file":"staging/src/k8s.io/component-base/cli/flag/langle_separated_map_string_string.go","code":"// NewLangleSeparatedMapStringString takes a pointer to a map[string]string and returns the\n// LangleSeparatedMapStringString flag parsing shim for that map\nfunc NewLangleSeparatedMapStringString(m *map[string]string) *LangleSeparatedMapStringString {\n\treturn \u0026LangleSeparatedMapStringString{Map: m}\n}","line":{"from":33,"to":37}} {"id":100030147,"name":"String","signature":"func (m *LangleSeparatedMapStringString) String() string","file":"staging/src/k8s.io/component-base/cli/flag/langle_separated_map_string_string.go","code":"// String implements github.com/spf13/pflag.Value\nfunc (m *LangleSeparatedMapStringString) String() string {\n\tpairs := []string{}\n\tfor k, v := range *m.Map {\n\t\tpairs = append(pairs, fmt.Sprintf(\"%s\u003c%s\", k, v))\n\t}\n\tsort.Strings(pairs)\n\treturn strings.Join(pairs, \",\")\n}","line":{"from":39,"to":47}} {"id":100030148,"name":"Set","signature":"func (m *LangleSeparatedMapStringString) Set(value string) error","file":"staging/src/k8s.io/component-base/cli/flag/langle_separated_map_string_string.go","code":"// Set implements github.com/spf13/pflag.Value\nfunc (m *LangleSeparatedMapStringString) Set(value string) error {\n\tif m.Map == nil {\n\t\treturn fmt.Errorf(\"no target (nil pointer to map[string]string)\")\n\t}\n\tif !m.initialized || *m.Map == nil {\n\t\t// clear default values, or allocate if no existing map\n\t\t*m.Map = make(map[string]string)\n\t\tm.initialized = true\n\t}\n\tfor _, s := range strings.Split(value, \",\") {\n\t\tif len(s) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tarr := strings.SplitN(s, \"\u003c\", 2)\n\t\tif len(arr) != 2 {\n\t\t\treturn fmt.Errorf(\"malformed pair, expect string\u003cstring\")\n\t\t}\n\t\tk := strings.TrimSpace(arr[0])\n\t\tv := strings.TrimSpace(arr[1])\n\t\t(*m.Map)[k] = v\n\t}\n\treturn nil\n}","line":{"from":49,"to":72}} {"id":100030149,"name":"Type","signature":"func (*LangleSeparatedMapStringString) Type() string","file":"staging/src/k8s.io/component-base/cli/flag/langle_separated_map_string_string.go","code":"// Type implements github.com/spf13/pflag.Value\nfunc (*LangleSeparatedMapStringString) Type() string {\n\treturn \"mapStringString\"\n}","line":{"from":74,"to":77}} {"id":100030150,"name":"Empty","signature":"func (m *LangleSeparatedMapStringString) Empty() bool","file":"staging/src/k8s.io/component-base/cli/flag/langle_separated_map_string_string.go","code":"// Empty implements OmitEmpty\nfunc (m *LangleSeparatedMapStringString) Empty() bool {\n\treturn len(*m.Map) == 0\n}","line":{"from":79,"to":82}} {"id":100030151,"name":"NewMapStringBool","signature":"func NewMapStringBool(m *map[string]bool) *MapStringBool","file":"staging/src/k8s.io/component-base/cli/flag/map_string_bool.go","code":"// NewMapStringBool takes a pointer to a map[string]string and returns the\n// MapStringBool flag parsing shim for that map\nfunc NewMapStringBool(m *map[string]bool) *MapStringBool {\n\treturn \u0026MapStringBool{Map: m}\n}","line":{"from":34,"to":38}} {"id":100030152,"name":"String","signature":"func (m *MapStringBool) String() string","file":"staging/src/k8s.io/component-base/cli/flag/map_string_bool.go","code":"// String implements github.com/spf13/pflag.Value\nfunc (m *MapStringBool) String() string {\n\tif m == nil || m.Map == nil {\n\t\treturn \"\"\n\t}\n\tpairs := []string{}\n\tfor k, v := range *m.Map {\n\t\tpairs = append(pairs, fmt.Sprintf(\"%s=%t\", k, v))\n\t}\n\tsort.Strings(pairs)\n\treturn strings.Join(pairs, \",\")\n}","line":{"from":40,"to":51}} {"id":100030153,"name":"Set","signature":"func (m *MapStringBool) Set(value string) error","file":"staging/src/k8s.io/component-base/cli/flag/map_string_bool.go","code":"// Set implements github.com/spf13/pflag.Value\nfunc (m *MapStringBool) Set(value string) error {\n\tif m.Map == nil {\n\t\treturn fmt.Errorf(\"no target (nil pointer to map[string]bool)\")\n\t}\n\tif !m.initialized || *m.Map == nil {\n\t\t// clear default values, or allocate if no existing map\n\t\t*m.Map = make(map[string]bool)\n\t\tm.initialized = true\n\t}\n\tfor _, s := range strings.Split(value, \",\") {\n\t\tif len(s) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tarr := strings.SplitN(s, \"=\", 2)\n\t\tif len(arr) != 2 {\n\t\t\treturn fmt.Errorf(\"malformed pair, expect string=bool\")\n\t\t}\n\t\tk := strings.TrimSpace(arr[0])\n\t\tv := strings.TrimSpace(arr[1])\n\t\tboolValue, err := strconv.ParseBool(v)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid value of %s: %s, err: %v\", k, v, err)\n\t\t}\n\t\t(*m.Map)[k] = boolValue\n\t}\n\treturn nil\n}","line":{"from":53,"to":80}} {"id":100030154,"name":"Type","signature":"func (*MapStringBool) Type() string","file":"staging/src/k8s.io/component-base/cli/flag/map_string_bool.go","code":"// Type implements github.com/spf13/pflag.Value\nfunc (*MapStringBool) Type() string {\n\treturn \"mapStringBool\"\n}","line":{"from":82,"to":85}} {"id":100030155,"name":"Empty","signature":"func (m *MapStringBool) Empty() bool","file":"staging/src/k8s.io/component-base/cli/flag/map_string_bool.go","code":"// Empty implements OmitEmpty\nfunc (m *MapStringBool) Empty() bool {\n\treturn len(*m.Map) == 0\n}","line":{"from":87,"to":90}} {"id":100030156,"name":"NewMapStringString","signature":"func NewMapStringString(m *map[string]string) *MapStringString","file":"staging/src/k8s.io/component-base/cli/flag/map_string_string.go","code":"// NewMapStringString takes a pointer to a map[string]string and returns the\n// MapStringString flag parsing shim for that map\nfunc NewMapStringString(m *map[string]string) *MapStringString {\n\treturn \u0026MapStringString{Map: m}\n}","line":{"from":36,"to":40}} {"id":100030157,"name":"NewMapStringStringNoSplit","signature":"func NewMapStringStringNoSplit(m *map[string]string) *MapStringString","file":"staging/src/k8s.io/component-base/cli/flag/map_string_string.go","code":"// NewMapStringString takes a pointer to a map[string]string and sets `NoSplit`\n// value to `true` and returns the MapStringString flag parsing shim for that map\nfunc NewMapStringStringNoSplit(m *map[string]string) *MapStringString {\n\treturn \u0026MapStringString{\n\t\tMap: m,\n\t\tNoSplit: true,\n\t}\n}","line":{"from":42,"to":49}} {"id":100030158,"name":"String","signature":"func (m *MapStringString) String() string","file":"staging/src/k8s.io/component-base/cli/flag/map_string_string.go","code":"// String implements github.com/spf13/pflag.Value\nfunc (m *MapStringString) String() string {\n\tif m == nil || m.Map == nil {\n\t\treturn \"\"\n\t}\n\tpairs := []string{}\n\tfor k, v := range *m.Map {\n\t\tpairs = append(pairs, fmt.Sprintf(\"%s=%s\", k, v))\n\t}\n\tsort.Strings(pairs)\n\treturn strings.Join(pairs, \",\")\n}","line":{"from":51,"to":62}} {"id":100030159,"name":"Set","signature":"func (m *MapStringString) Set(value string) error","file":"staging/src/k8s.io/component-base/cli/flag/map_string_string.go","code":"// Set implements github.com/spf13/pflag.Value\nfunc (m *MapStringString) Set(value string) error {\n\tif m.Map == nil {\n\t\treturn fmt.Errorf(\"no target (nil pointer to map[string]string)\")\n\t}\n\tif !m.initialized || *m.Map == nil {\n\t\t// clear default values, or allocate if no existing map\n\t\t*m.Map = make(map[string]string)\n\t\tm.initialized = true\n\t}\n\n\t// account for comma-separated key-value pairs in a single invocation\n\tif !m.NoSplit {\n\t\tfor _, s := range strings.Split(value, \",\") {\n\t\t\tif len(s) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tarr := strings.SplitN(s, \"=\", 2)\n\t\t\tif len(arr) != 2 {\n\t\t\t\treturn fmt.Errorf(\"malformed pair, expect string=string\")\n\t\t\t}\n\t\t\tk := strings.TrimSpace(arr[0])\n\t\t\tv := strings.TrimSpace(arr[1])\n\t\t\t(*m.Map)[k] = v\n\t\t}\n\t\treturn nil\n\t}\n\n\t// account for only one key-value pair in a single invocation\n\tarr := strings.SplitN(value, \"=\", 2)\n\tif len(arr) != 2 {\n\t\treturn fmt.Errorf(\"malformed pair, expect string=string\")\n\t}\n\tk := strings.TrimSpace(arr[0])\n\tv := strings.TrimSpace(arr[1])\n\t(*m.Map)[k] = v\n\treturn nil\n\n}","line":{"from":64,"to":102}} {"id":100030160,"name":"Type","signature":"func (*MapStringString) Type() string","file":"staging/src/k8s.io/component-base/cli/flag/map_string_string.go","code":"// Type implements github.com/spf13/pflag.Value\nfunc (*MapStringString) Type() string {\n\treturn \"mapStringString\"\n}","line":{"from":104,"to":107}} {"id":100030161,"name":"Empty","signature":"func (m *MapStringString) Empty() bool","file":"staging/src/k8s.io/component-base/cli/flag/map_string_string.go","code":"// Empty implements OmitEmpty\nfunc (m *MapStringString) Empty() bool {\n\treturn len(*m.Map) == 0\n}","line":{"from":109,"to":112}} {"id":100030162,"name":"String","signature":"func (nkc *NamedCertKey) String() string","file":"staging/src/k8s.io/component-base/cli/flag/namedcertkey_flag.go","code":"func (nkc *NamedCertKey) String() string {\n\ts := nkc.CertFile + \",\" + nkc.KeyFile\n\tif len(nkc.Names) \u003e 0 {\n\t\ts = s + \":\" + strings.Join(nkc.Names, \",\")\n\t}\n\treturn s\n}","line":{"from":33,"to":39}} {"id":100030163,"name":"Set","signature":"func (nkc *NamedCertKey) Set(value string) error","file":"staging/src/k8s.io/component-base/cli/flag/namedcertkey_flag.go","code":"func (nkc *NamedCertKey) Set(value string) error {\n\tcs := strings.SplitN(value, \":\", 2)\n\tvar keycert string\n\tif len(cs) == 2 {\n\t\tvar names string\n\t\tkeycert, names = strings.TrimSpace(cs[0]), strings.TrimSpace(cs[1])\n\t\tif names == \"\" {\n\t\t\treturn errors.New(\"empty names list is not allowed\")\n\t\t}\n\t\tnkc.Names = nil\n\t\tfor _, name := range strings.Split(names, \",\") {\n\t\t\tnkc.Names = append(nkc.Names, strings.TrimSpace(name))\n\t\t}\n\t} else {\n\t\tnkc.Names = nil\n\t\tkeycert = strings.TrimSpace(cs[0])\n\t}\n\tcs = strings.Split(keycert, \",\")\n\tif len(cs) != 2 {\n\t\treturn errors.New(\"expected comma separated certificate and key file paths\")\n\t}\n\tnkc.CertFile = strings.TrimSpace(cs[0])\n\tnkc.KeyFile = strings.TrimSpace(cs[1])\n\treturn nil\n}","line":{"from":41,"to":65}} {"id":100030164,"name":"Type","signature":"func (*NamedCertKey) Type() string","file":"staging/src/k8s.io/component-base/cli/flag/namedcertkey_flag.go","code":"func (*NamedCertKey) Type() string {\n\treturn \"namedCertKey\"\n}","line":{"from":67,"to":69}} {"id":100030165,"name":"NewNamedCertKeyArray","signature":"func NewNamedCertKeyArray(p *[]NamedCertKey) *NamedCertKeyArray","file":"staging/src/k8s.io/component-base/cli/flag/namedcertkey_flag.go","code":"// NewNamedKeyCertArray creates a new NamedCertKeyArray with the internal value\n// pointing to p.\nfunc NewNamedCertKeyArray(p *[]NamedCertKey) *NamedCertKeyArray {\n\treturn \u0026NamedCertKeyArray{\n\t\tvalue: p,\n\t}\n}","line":{"from":80,"to":86}} {"id":100030166,"name":"Set","signature":"func (a *NamedCertKeyArray) Set(val string) error","file":"staging/src/k8s.io/component-base/cli/flag/namedcertkey_flag.go","code":"func (a *NamedCertKeyArray) Set(val string) error {\n\tnkc := NamedCertKey{}\n\terr := nkc.Set(val)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !a.changed {\n\t\t*a.value = []NamedCertKey{nkc}\n\t\ta.changed = true\n\t} else {\n\t\t*a.value = append(*a.value, nkc)\n\t}\n\treturn nil\n}","line":{"from":88,"to":101}} {"id":100030167,"name":"Type","signature":"func (a *NamedCertKeyArray) Type() string","file":"staging/src/k8s.io/component-base/cli/flag/namedcertkey_flag.go","code":"func (a *NamedCertKeyArray) Type() string {\n\treturn \"namedCertKey\"\n}","line":{"from":103,"to":105}} {"id":100030168,"name":"String","signature":"func (a *NamedCertKeyArray) String() string","file":"staging/src/k8s.io/component-base/cli/flag/namedcertkey_flag.go","code":"func (a *NamedCertKeyArray) String() string {\n\tnkcs := make([]string, 0, len(*a.value))\n\tfor i := range *a.value {\n\t\tnkcs = append(nkcs, (*a.value)[i].String())\n\t}\n\treturn \"[\" + strings.Join(nkcs, \";\") + \"]\"\n}","line":{"from":107,"to":113}} {"id":100030169,"name":"String","signature":"func (NoOp) String() string","file":"staging/src/k8s.io/component-base/cli/flag/noop.go","code":"func (NoOp) String() string {\n\treturn \"\"\n}","line":{"from":31,"to":33}} {"id":100030170,"name":"Set","signature":"func (NoOp) Set(val string) error","file":"staging/src/k8s.io/component-base/cli/flag/noop.go","code":"func (NoOp) Set(val string) error {\n\treturn nil\n}","line":{"from":35,"to":37}} {"id":100030171,"name":"Type","signature":"func (NoOp) Type() string","file":"staging/src/k8s.io/component-base/cli/flag/noop.go","code":"func (NoOp) Type() string {\n\treturn \"NoOp\"\n}","line":{"from":39,"to":41}} {"id":100030172,"name":"FlagSet","signature":"func (nfs *NamedFlagSets) FlagSet(name string) *pflag.FlagSet","file":"staging/src/k8s.io/component-base/cli/flag/sectioned.go","code":"// FlagSet returns the flag set with the given name and adds it to the\n// ordered name list if it is not in there yet.\nfunc (nfs *NamedFlagSets) FlagSet(name string) *pflag.FlagSet {\n\tif nfs.FlagSets == nil {\n\t\tnfs.FlagSets = map[string]*pflag.FlagSet{}\n\t}\n\tif _, ok := nfs.FlagSets[name]; !ok {\n\t\tflagSet := pflag.NewFlagSet(name, pflag.ExitOnError)\n\t\tflagSet.SetNormalizeFunc(pflag.CommandLine.GetNormalizeFunc())\n\t\tif nfs.NormalizeNameFunc != nil {\n\t\t\tflagSet.SetNormalizeFunc(nfs.NormalizeNameFunc)\n\t\t}\n\t\tnfs.FlagSets[name] = flagSet\n\t\tnfs.Order = append(nfs.Order, name)\n\t}\n\treturn nfs.FlagSets[name]\n}","line":{"from":43,"to":59}} {"id":100030173,"name":"PrintSections","signature":"func PrintSections(w io.Writer, fss NamedFlagSets, cols int)","file":"staging/src/k8s.io/component-base/cli/flag/sectioned.go","code":"// PrintSections prints the given names flag sets in sections, with the maximal given column number.\n// If cols is zero, lines are not wrapped.\nfunc PrintSections(w io.Writer, fss NamedFlagSets, cols int) {\n\tfor _, name := range fss.Order {\n\t\tfs := fss.FlagSets[name]\n\t\tif !fs.HasFlags() {\n\t\t\tcontinue\n\t\t}\n\n\t\twideFS := pflag.NewFlagSet(\"\", pflag.ExitOnError)\n\t\twideFS.AddFlagSet(fs)\n\n\t\tvar zzz string\n\t\tif cols \u003e 24 {\n\t\t\tzzz = strings.Repeat(\"z\", cols-24)\n\t\t\twideFS.Int(zzz, 0, strings.Repeat(\"z\", cols-24))\n\t\t}\n\n\t\tvar buf bytes.Buffer\n\t\tfmt.Fprintf(\u0026buf, \"\\n%s flags:\\n\\n%s\", strings.ToUpper(name[:1])+name[1:], wideFS.FlagUsagesWrapped(cols))\n\n\t\tif cols \u003e 24 {\n\t\t\ti := strings.Index(buf.String(), zzz)\n\t\t\tlines := strings.Split(buf.String()[:i], \"\\n\")\n\t\t\tfmt.Fprint(w, strings.Join(lines[:len(lines)-1], \"\\n\"))\n\t\t\tfmt.Fprintln(w)\n\t\t} else {\n\t\t\tfmt.Fprint(w, buf.String())\n\t\t}\n\t}\n}","line":{"from":61,"to":91}} {"id":100030174,"name":"SetUsageAndHelpFunc","signature":"func SetUsageAndHelpFunc(cmd *cobra.Command, fss NamedFlagSets, cols int)","file":"staging/src/k8s.io/component-base/cli/flag/sectioned.go","code":"// SetUsageAndHelpFunc set both usage and help function.\n// Print the flag sets we need instead of all of them.\nfunc SetUsageAndHelpFunc(cmd *cobra.Command, fss NamedFlagSets, cols int) {\n\tcmd.SetUsageFunc(func(cmd *cobra.Command) error {\n\t\tfmt.Fprintf(cmd.OutOrStderr(), usageFmt, cmd.UseLine())\n\t\tPrintSections(cmd.OutOrStderr(), fss, cols)\n\t\treturn nil\n\t})\n\tcmd.SetHelpFunc(func(cmd *cobra.Command, args []string) {\n\t\tfmt.Fprintf(cmd.OutOrStdout(), \"%s\\n\\n\"+usageFmt, cmd.Long, cmd.UseLine())\n\t\tPrintSections(cmd.OutOrStdout(), fss, cols)\n\t})\n}","line":{"from":93,"to":105}} {"id":100030175,"name":"NewStringFlag","signature":"func NewStringFlag(defaultVal string) StringFlag","file":"staging/src/k8s.io/component-base/cli/flag/string_flag.go","code":"func NewStringFlag(defaultVal string) StringFlag {\n\treturn StringFlag{value: defaultVal}\n}","line":{"from":27,"to":29}} {"id":100030176,"name":"Default","signature":"func (f *StringFlag) Default(value string)","file":"staging/src/k8s.io/component-base/cli/flag/string_flag.go","code":"func (f *StringFlag) Default(value string) {\n\tf.value = value\n}","line":{"from":31,"to":33}} {"id":100030177,"name":"String","signature":"func (f StringFlag) String() string","file":"staging/src/k8s.io/component-base/cli/flag/string_flag.go","code":"func (f StringFlag) String() string {\n\treturn f.value\n}","line":{"from":35,"to":37}} {"id":100030178,"name":"Value","signature":"func (f StringFlag) Value() string","file":"staging/src/k8s.io/component-base/cli/flag/string_flag.go","code":"func (f StringFlag) Value() string {\n\treturn f.value\n}","line":{"from":39,"to":41}} {"id":100030179,"name":"Set","signature":"func (f *StringFlag) Set(value string) error","file":"staging/src/k8s.io/component-base/cli/flag/string_flag.go","code":"func (f *StringFlag) Set(value string) error {\n\tf.value = value\n\tf.provided = true\n\n\treturn nil\n}","line":{"from":43,"to":48}} {"id":100030180,"name":"Provided","signature":"func (f StringFlag) Provided() bool","file":"staging/src/k8s.io/component-base/cli/flag/string_flag.go","code":"func (f StringFlag) Provided() bool {\n\treturn f.provided\n}","line":{"from":50,"to":52}} {"id":100030181,"name":"Type","signature":"func (f *StringFlag) Type() string","file":"staging/src/k8s.io/component-base/cli/flag/string_flag.go","code":"func (f *StringFlag) Type() string {\n\treturn \"string\"\n}","line":{"from":54,"to":56}} {"id":100030182,"name":"NewStringSlice","signature":"func NewStringSlice(s *[]string) *StringSlice","file":"staging/src/k8s.io/component-base/cli/flag/string_slice_flag.go","code":"func NewStringSlice(s *[]string) *StringSlice {\n\treturn \u0026StringSlice{value: s}\n}","line":{"from":34,"to":36}} {"id":100030183,"name":"String","signature":"func (s *StringSlice) String() string","file":"staging/src/k8s.io/component-base/cli/flag/string_slice_flag.go","code":"func (s *StringSlice) String() string {\n\tif s == nil || s.value == nil {\n\t\treturn \"\"\n\t}\n\treturn strings.Join(*s.value, \" \")\n}","line":{"from":41,"to":46}} {"id":100030184,"name":"Set","signature":"func (s *StringSlice) Set(val string) error","file":"staging/src/k8s.io/component-base/cli/flag/string_slice_flag.go","code":"func (s *StringSlice) Set(val string) error {\n\tif s.value == nil {\n\t\treturn fmt.Errorf(\"no target (nil pointer to []string)\")\n\t}\n\tif !s.changed {\n\t\t*s.value = make([]string, 0)\n\t}\n\t*s.value = append(*s.value, val)\n\ts.changed = true\n\treturn nil\n}","line":{"from":48,"to":58}} {"id":100030185,"name":"Type","signature":"func (StringSlice) Type() string","file":"staging/src/k8s.io/component-base/cli/flag/string_slice_flag.go","code":"func (StringSlice) Type() string {\n\treturn \"sliceString\"\n}","line":{"from":60,"to":62}} {"id":100030186,"name":"Default","signature":"func (f *Tristate) Default(value bool)","file":"staging/src/k8s.io/component-base/cli/flag/tristate.go","code":"func (f *Tristate) Default(value bool) {\n\t*f = triFromBool(value)\n}","line":{"from":34,"to":36}} {"id":100030187,"name":"String","signature":"func (f Tristate) String() string","file":"staging/src/k8s.io/component-base/cli/flag/tristate.go","code":"func (f Tristate) String() string {\n\tb := boolFromTri(f)\n\treturn fmt.Sprintf(\"%t\", b)\n}","line":{"from":38,"to":41}} {"id":100030188,"name":"Value","signature":"func (f Tristate) Value() bool","file":"staging/src/k8s.io/component-base/cli/flag/tristate.go","code":"func (f Tristate) Value() bool {\n\tb := boolFromTri(f)\n\treturn b\n}","line":{"from":43,"to":46}} {"id":100030189,"name":"Set","signature":"func (f *Tristate) Set(value string) error","file":"staging/src/k8s.io/component-base/cli/flag/tristate.go","code":"func (f *Tristate) Set(value string) error {\n\tboolVal, err := strconv.ParseBool(value)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*f = triFromBool(boolVal)\n\treturn nil\n}","line":{"from":48,"to":56}} {"id":100030190,"name":"Provided","signature":"func (f Tristate) Provided() bool","file":"staging/src/k8s.io/component-base/cli/flag/tristate.go","code":"func (f Tristate) Provided() bool {\n\tif f != Unset {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":58,"to":63}} {"id":100030191,"name":"Type","signature":"func (f *Tristate) Type() string","file":"staging/src/k8s.io/component-base/cli/flag/tristate.go","code":"func (f *Tristate) Type() string {\n\treturn \"tristate\"\n}","line":{"from":65,"to":67}} {"id":100030192,"name":"boolFromTri","signature":"func boolFromTri(t Tristate) bool","file":"staging/src/k8s.io/component-base/cli/flag/tristate.go","code":"func boolFromTri(t Tristate) bool {\n\tif t == True {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}","line":{"from":69,"to":75}} {"id":100030193,"name":"triFromBool","signature":"func triFromBool(b bool) Tristate","file":"staging/src/k8s.io/component-base/cli/flag/tristate.go","code":"func triFromBool(b bool) Tristate {\n\tif b {\n\t\treturn True\n\t} else {\n\t\treturn False\n\t}\n}","line":{"from":77,"to":83}} {"id":100030194,"name":"AddGlobalFlags","signature":"func AddGlobalFlags(fs *pflag.FlagSet, name string, opts ...logs.Option)","file":"staging/src/k8s.io/component-base/cli/globalflag/globalflags.go","code":"// AddGlobalFlags explicitly registers flags that libraries (klog, verflag, etc.) register\n// against the global flagsets from \"flag\" and \"k8s.io/klog/v2\".\n// We do this in order to prevent unwanted flags from leaking into the component's flagset.\n//\n// k8s.io/component-base/logs.SkipLoggingConfigurationFlags must be used as\n// option when the program also uses a LoggingConfiguration struct for\n// configuring logging. Then only flags not covered by that get added.\nfunc AddGlobalFlags(fs *pflag.FlagSet, name string, opts ...logs.Option) {\n\tlogs.AddFlags(fs, opts...)\n\n\tfs.BoolP(\"help\", \"h\", false, fmt.Sprintf(\"help for %s\", name))\n}","line":{"from":27,"to":38}} {"id":100030195,"name":"Register","signature":"func Register(local *pflag.FlagSet, globalName string)","file":"staging/src/k8s.io/component-base/cli/globalflag/globalflags.go","code":"// Register adds a flag to local that targets the Value associated with the Flag named globalName in flag.CommandLine.\nfunc Register(local *pflag.FlagSet, globalName string) {\n\tif f := flag.CommandLine.Lookup(globalName); f != nil {\n\t\tpflagFlag := pflag.PFlagFromGoFlag(f)\n\t\tnormalizeFunc := local.GetNormalizeFunc()\n\t\tpflagFlag.Name = string(normalizeFunc(local, pflagFlag.Name))\n\t\tlocal.AddFlag(pflagFlag)\n\t} else {\n\t\tpanic(fmt.Sprintf(\"failed to find flag in global flagset (flag): %s\", globalName))\n\t}\n}","line":{"from":40,"to":50}} {"id":100030196,"name":"Run","signature":"func Run(cmd *cobra.Command) int","file":"staging/src/k8s.io/component-base/cli/run.go","code":"// Run provides the common boilerplate code around executing a cobra command.\n// For example, it ensures that logging is set up properly. Logging\n// flags get added to the command line if not added already. Flags get normalized\n// so that help texts show them with hyphens. Underscores are accepted\n// as alternative for the command parameters.\n//\n// Run tries to be smart about how to print errors that are returned by the\n// command: before logging is known to be set up, it prints them as plain text\n// to stderr. This covers command line flag parse errors and unknown commands.\n// Afterwards it logs them. This covers runtime errors.\n//\n// Commands like kubectl where logging is not normally part of the runtime output\n// should use RunNoErrOutput instead and deal with the returned error themselves.\nfunc Run(cmd *cobra.Command) int {\n\tif logsInitialized, err := run(cmd); err != nil {\n\t\t// If the error is about flag parsing, then printing that error\n\t\t// with the decoration that klog would add (\"E0923\n\t\t// 23:02:03.219216 4168816 run.go:61] unknown shorthand flag\")\n\t\t// is less readable. Using klog.Fatal is even worse because it\n\t\t// dumps a stack trace that isn't about the error.\n\t\t//\n\t\t// But if it is some other error encountered at runtime, then\n\t\t// we want to log it as error, at least in most commands because\n\t\t// their output is a log event stream.\n\t\t//\n\t\t// We can distinguish these two cases depending on whether\n\t\t// we got to logs.InitLogs() above.\n\t\t//\n\t\t// This heuristic might be problematic for command line\n\t\t// tools like kubectl where the output is carefully controlled\n\t\t// and not a log by default. They should use RunNoErrOutput\n\t\t// instead.\n\t\t//\n\t\t// The usage of klog is problematic also because we don't know\n\t\t// whether the command has managed to configure it. This cannot\n\t\t// be checked right now, but may become possible when the early\n\t\t// logging proposal from\n\t\t// https://github.com/kubernetes/enhancements/pull/3078\n\t\t// (\"contextual logging\") is implemented.\n\t\tif !logsInitialized {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error: %v\\n\", err)\n\t\t} else {\n\t\t\tklog.ErrorS(err, \"command failed\")\n\t\t}\n\t\treturn 1\n\t}\n\treturn 0\n}","line":{"from":32,"to":79}} {"id":100030197,"name":"RunNoErrOutput","signature":"func RunNoErrOutput(cmd *cobra.Command) error","file":"staging/src/k8s.io/component-base/cli/run.go","code":"// RunNoErrOutput is a version of Run which returns the cobra command error\n// instead of printing it.\nfunc RunNoErrOutput(cmd *cobra.Command) error {\n\t_, err := run(cmd)\n\treturn err\n}","line":{"from":81,"to":86}} {"id":100030198,"name":"run","signature":"func run(cmd *cobra.Command) (logsInitialized bool, err error)","file":"staging/src/k8s.io/component-base/cli/run.go","code":"func run(cmd *cobra.Command) (logsInitialized bool, err error) {\n\trand.Seed(time.Now().UnixNano())\n\tdefer logs.FlushLogs()\n\n\tcmd.SetGlobalNormalizationFunc(cliflag.WordSepNormalizeFunc)\n\n\t// When error printing is enabled for the Cobra command, a flag parse\n\t// error gets printed first, then optionally the often long usage\n\t// text. This is very unreadable in a console because the last few\n\t// lines that will be visible on screen don't include the error.\n\t//\n\t// The recommendation from #sig-cli was to print the usage text, then\n\t// the error. We implement this consistently for all commands here.\n\t// However, we don't want to print the usage text when command\n\t// execution fails for other reasons than parsing. We detect this via\n\t// the FlagParseError callback.\n\t//\n\t// Some commands, like kubectl, already deal with this themselves.\n\t// We don't change the behavior for those.\n\tif !cmd.SilenceUsage {\n\t\tcmd.SilenceUsage = true\n\t\tcmd.SetFlagErrorFunc(func(c *cobra.Command, err error) error {\n\t\t\t// Re-enable usage printing.\n\t\t\tc.SilenceUsage = false\n\t\t\treturn err\n\t\t})\n\t}\n\n\t// In all cases error printing is done below.\n\tcmd.SilenceErrors = true\n\n\t// This is idempotent.\n\tlogs.AddFlags(cmd.PersistentFlags())\n\n\t// Inject logs.InitLogs after command line parsing into one of the\n\t// PersistentPre* functions.\n\tswitch {\n\tcase cmd.PersistentPreRun != nil:\n\t\tpre := cmd.PersistentPreRun\n\t\tcmd.PersistentPreRun = func(cmd *cobra.Command, args []string) {\n\t\t\tlogs.InitLogs()\n\t\t\tlogsInitialized = true\n\t\t\tpre(cmd, args)\n\t\t}\n\tcase cmd.PersistentPreRunE != nil:\n\t\tpre := cmd.PersistentPreRunE\n\t\tcmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {\n\t\t\tlogs.InitLogs()\n\t\t\tlogsInitialized = true\n\t\t\treturn pre(cmd, args)\n\t\t}\n\tdefault:\n\t\tcmd.PersistentPreRun = func(cmd *cobra.Command, args []string) {\n\t\t\tlogs.InitLogs()\n\t\t\tlogsInitialized = true\n\t\t}\n\t}\n\n\terr = cmd.Execute()\n\treturn\n}","line":{"from":88,"to":148}} {"id":100030199,"name":"NewLenientSchemeAndCodecs","signature":"func NewLenientSchemeAndCodecs(addToSchemeFns ...func(s *runtime.Scheme) error) (*runtime.Scheme, *serializer.CodecFactory, error)","file":"staging/src/k8s.io/component-base/codec/codec.go","code":"// NewLenientSchemeAndCodecs constructs a CodecFactory with strict decoding\n// disabled, that has only the Schemes registered into it which are passed\n// and added via AddToScheme functions. This can be used to skip strict decoding\n// a specific version only.\nfunc NewLenientSchemeAndCodecs(addToSchemeFns ...func(s *runtime.Scheme) error) (*runtime.Scheme, *serializer.CodecFactory, error) {\n\tlenientScheme := runtime.NewScheme()\n\tfor _, s := range addToSchemeFns {\n\t\tif err := s(lenientScheme); err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"unable to add API to lenient scheme: %v\", err)\n\t\t}\n\t}\n\tlenientCodecs := serializer.NewCodecFactory(lenientScheme, serializer.DisableStrict)\n\treturn lenientScheme, \u0026lenientCodecs, nil\n}","line":{"from":26,"to":39}} {"id":100030200,"name":"BindLeaderElectionFlags","signature":"func BindLeaderElectionFlags(l *config.LeaderElectionConfiguration, fs *pflag.FlagSet)","file":"staging/src/k8s.io/component-base/config/options/leaderelectionconfig.go","code":"// BindLeaderElectionFlags binds the LeaderElectionConfiguration struct fields to a flagset\nfunc BindLeaderElectionFlags(l *config.LeaderElectionConfiguration, fs *pflag.FlagSet) {\n\tfs.BoolVar(\u0026l.LeaderElect, \"leader-elect\", l.LeaderElect, \"\"+\n\t\t\"Start a leader election client and gain leadership before \"+\n\t\t\"executing the main loop. Enable this when running replicated \"+\n\t\t\"components for high availability.\")\n\tfs.DurationVar(\u0026l.LeaseDuration.Duration, \"leader-elect-lease-duration\", l.LeaseDuration.Duration, \"\"+\n\t\t\"The duration that non-leader candidates will wait after observing a leadership \"+\n\t\t\"renewal until attempting to acquire leadership of a led but unrenewed leader \"+\n\t\t\"slot. This is effectively the maximum duration that a leader can be stopped \"+\n\t\t\"before it is replaced by another candidate. This is only applicable if leader \"+\n\t\t\"election is enabled.\")\n\tfs.DurationVar(\u0026l.RenewDeadline.Duration, \"leader-elect-renew-deadline\", l.RenewDeadline.Duration, \"\"+\n\t\t\"The interval between attempts by the acting master to renew a leadership slot \"+\n\t\t\"before it stops leading. This must be less than the lease duration. \"+\n\t\t\"This is only applicable if leader election is enabled.\")\n\tfs.DurationVar(\u0026l.RetryPeriod.Duration, \"leader-elect-retry-period\", l.RetryPeriod.Duration, \"\"+\n\t\t\"The duration the clients should wait between attempting acquisition and renewal \"+\n\t\t\"of a leadership. This is only applicable if leader election is enabled.\")\n\tfs.StringVar(\u0026l.ResourceLock, \"leader-elect-resource-lock\", l.ResourceLock, \"\"+\n\t\t\"The type of resource object that is used for locking during \"+\n\t\t\"leader election. Supported options are 'leases', 'endpointsleases' \"+\n\t\t\"and 'configmapsleases'.\")\n\tfs.StringVar(\u0026l.ResourceName, \"leader-elect-resource-name\", l.ResourceName, \"\"+\n\t\t\"The name of resource object that is used for locking during \"+\n\t\t\"leader election.\")\n\tfs.StringVar(\u0026l.ResourceNamespace, \"leader-elect-resource-namespace\", l.ResourceNamespace, \"\"+\n\t\t\"The namespace of resource object that is used for locking during \"+\n\t\t\"leader election.\")\n}","line":{"from":24,"to":53}} {"id":100030201,"name":"Convert_v1alpha1_ClientConnectionConfiguration_To_config_ClientConnectionConfiguration","signature":"func Convert_v1alpha1_ClientConnectionConfiguration_To_config_ClientConnectionConfiguration(in *ClientConnectionConfiguration, out *config.ClientConnectionConfiguration, s conversion.Scope) error","file":"staging/src/k8s.io/component-base/config/v1alpha1/conversion.go","code":"func Convert_v1alpha1_ClientConnectionConfiguration_To_config_ClientConnectionConfiguration(in *ClientConnectionConfiguration, out *config.ClientConnectionConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_ClientConnectionConfiguration_To_config_ClientConnectionConfiguration(in, out, s)\n}","line":{"from":31,"to":33}} {"id":100030202,"name":"Convert_config_ClientConnectionConfiguration_To_v1alpha1_ClientConnectionConfiguration","signature":"func Convert_config_ClientConnectionConfiguration_To_v1alpha1_ClientConnectionConfiguration(in *config.ClientConnectionConfiguration, out *ClientConnectionConfiguration, s conversion.Scope) error","file":"staging/src/k8s.io/component-base/config/v1alpha1/conversion.go","code":"func Convert_config_ClientConnectionConfiguration_To_v1alpha1_ClientConnectionConfiguration(in *config.ClientConnectionConfiguration, out *ClientConnectionConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_ClientConnectionConfiguration_To_v1alpha1_ClientConnectionConfiguration(in, out, s)\n}","line":{"from":35,"to":37}} {"id":100030203,"name":"Convert_v1alpha1_DebuggingConfiguration_To_config_DebuggingConfiguration","signature":"func Convert_v1alpha1_DebuggingConfiguration_To_config_DebuggingConfiguration(in *DebuggingConfiguration, out *config.DebuggingConfiguration, s conversion.Scope) error","file":"staging/src/k8s.io/component-base/config/v1alpha1/conversion.go","code":"func Convert_v1alpha1_DebuggingConfiguration_To_config_DebuggingConfiguration(in *DebuggingConfiguration, out *config.DebuggingConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_DebuggingConfiguration_To_config_DebuggingConfiguration(in, out, s)\n}","line":{"from":39,"to":41}} {"id":100030204,"name":"Convert_config_DebuggingConfiguration_To_v1alpha1_DebuggingConfiguration","signature":"func Convert_config_DebuggingConfiguration_To_v1alpha1_DebuggingConfiguration(in *config.DebuggingConfiguration, out *DebuggingConfiguration, s conversion.Scope) error","file":"staging/src/k8s.io/component-base/config/v1alpha1/conversion.go","code":"func Convert_config_DebuggingConfiguration_To_v1alpha1_DebuggingConfiguration(in *config.DebuggingConfiguration, out *DebuggingConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_DebuggingConfiguration_To_v1alpha1_DebuggingConfiguration(in, out, s)\n}","line":{"from":43,"to":45}} {"id":100030205,"name":"Convert_v1alpha1_LeaderElectionConfiguration_To_config_LeaderElectionConfiguration","signature":"func Convert_v1alpha1_LeaderElectionConfiguration_To_config_LeaderElectionConfiguration(in *LeaderElectionConfiguration, out *config.LeaderElectionConfiguration, s conversion.Scope) error","file":"staging/src/k8s.io/component-base/config/v1alpha1/conversion.go","code":"func Convert_v1alpha1_LeaderElectionConfiguration_To_config_LeaderElectionConfiguration(in *LeaderElectionConfiguration, out *config.LeaderElectionConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_LeaderElectionConfiguration_To_config_LeaderElectionConfiguration(in, out, s)\n}","line":{"from":47,"to":49}} {"id":100030206,"name":"Convert_config_LeaderElectionConfiguration_To_v1alpha1_LeaderElectionConfiguration","signature":"func Convert_config_LeaderElectionConfiguration_To_v1alpha1_LeaderElectionConfiguration(in *config.LeaderElectionConfiguration, out *LeaderElectionConfiguration, s conversion.Scope) error","file":"staging/src/k8s.io/component-base/config/v1alpha1/conversion.go","code":"func Convert_config_LeaderElectionConfiguration_To_v1alpha1_LeaderElectionConfiguration(in *config.LeaderElectionConfiguration, out *LeaderElectionConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_LeaderElectionConfiguration_To_v1alpha1_LeaderElectionConfiguration(in, out, s)\n}","line":{"from":51,"to":53}} {"id":100030207,"name":"RecommendedDefaultLeaderElectionConfiguration","signature":"func RecommendedDefaultLeaderElectionConfiguration(obj *LeaderElectionConfiguration)","file":"staging/src/k8s.io/component-base/config/v1alpha1/defaults.go","code":"// RecommendedDefaultLeaderElectionConfiguration defaults a pointer to a\n// LeaderElectionConfiguration struct. This will set the recommended default\n// values, but they may be subject to change between API versions. This function\n// is intentionally not registered in the scheme as a \"normal\" `SetDefaults_Foo`\n// function to allow consumers of this type to set whatever defaults for their\n// embedded configs. Forcing consumers to use these defaults would be problematic\n// as defaulting in the scheme is done as part of the conversion, and there would\n// be no easy way to opt-out. Instead, if you want to use this defaulting method\n// run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDefaultLeaderElectionConfiguration(obj *LeaderElectionConfiguration) {\n\tzero := metav1.Duration{}\n\tif obj.LeaseDuration == zero {\n\t\tobj.LeaseDuration = metav1.Duration{Duration: 15 * time.Second}\n\t}\n\tif obj.RenewDeadline == zero {\n\t\tobj.RenewDeadline = metav1.Duration{Duration: 10 * time.Second}\n\t}\n\tif obj.RetryPeriod == zero {\n\t\tobj.RetryPeriod = metav1.Duration{Duration: 2 * time.Second}\n\t}\n\tif obj.ResourceLock == \"\" {\n\t\t// TODO(#80289): Figure out how to migrate to LeaseLock at this point.\n\t\t// This will most probably require going through EndpointsLease first.\n\t\tobj.ResourceLock = EndpointsResourceLock\n\t}\n\tif obj.LeaderElect == nil {\n\t\tobj.LeaderElect = utilpointer.BoolPtr(true)\n\t}\n}","line":{"from":26,"to":54}} {"id":100030208,"name":"RecommendedDefaultClientConnectionConfiguration","signature":"func RecommendedDefaultClientConnectionConfiguration(obj *ClientConnectionConfiguration)","file":"staging/src/k8s.io/component-base/config/v1alpha1/defaults.go","code":"// RecommendedDefaultClientConnectionConfiguration defaults a pointer to a\n// ClientConnectionConfiguration struct. This will set the recommended default\n// values, but they may be subject to change between API versions. This function\n// is intentionally not registered in the scheme as a \"normal\" `SetDefaults_Foo`\n// function to allow consumers of this type to set whatever defaults for their\n// embedded configs. Forcing consumers to use these defaults would be problematic\n// as defaulting in the scheme is done as part of the conversion, and there would\n// be no easy way to opt-out. Instead, if you want to use this defaulting method\n// run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDefaultClientConnectionConfiguration(obj *ClientConnectionConfiguration) {\n\tif len(obj.ContentType) == 0 {\n\t\tobj.ContentType = \"application/vnd.kubernetes.protobuf\"\n\t}\n\tif obj.QPS == 0.0 {\n\t\tobj.QPS = 50.0\n\t}\n\tif obj.Burst == 0 {\n\t\tobj.Burst = 100\n\t}\n}","line":{"from":56,"to":75}} {"id":100030209,"name":"RecommendedDebuggingConfiguration","signature":"func RecommendedDebuggingConfiguration(obj *DebuggingConfiguration)","file":"staging/src/k8s.io/component-base/config/v1alpha1/defaults.go","code":"// RecommendedDebuggingConfiguration defaults profiling and debugging configuration.\n// This will set the recommended default\n// values, but they may be subject to change between API versions. This function\n// is intentionally not registered in the scheme as a \"normal\" `SetDefaults_Foo`\n// function to allow consumers of this type to set whatever defaults for their\n// embedded configs. Forcing consumers to use these defaults would be problematic\n// as defaulting in the scheme is done as part of the conversion, and there would\n// be no easy way to opt-out. Instead, if you want to use this defaulting method\n// run it in your wrapper struct of this type in its `SetDefaults_` method.\nfunc RecommendedDebuggingConfiguration(obj *DebuggingConfiguration) {\n\tif obj.EnableProfiling == nil {\n\t\tobj.EnableProfiling = utilpointer.BoolPtr(true) // profile debugging is cheap to have exposed and standard on kube binaries\n\t}\n}","line":{"from":77,"to":90}} {"id":100030210,"name":"NewRecommendedDebuggingConfiguration","signature":"func NewRecommendedDebuggingConfiguration() *DebuggingConfiguration","file":"staging/src/k8s.io/component-base/config/v1alpha1/defaults.go","code":"// NewRecommendedDebuggingConfiguration returns the current recommended DebuggingConfiguration.\n// This may change between releases as recommendations shift.\nfunc NewRecommendedDebuggingConfiguration() *DebuggingConfiguration {\n\tret := \u0026DebuggingConfiguration{}\n\tRecommendedDebuggingConfiguration(ret)\n\treturn ret\n}","line":{"from":92,"to":98}} {"id":100030211,"name":"ValidateClientConnectionConfiguration","signature":"func ValidateClientConnectionConfiguration(cc *config.ClientConnectionConfiguration, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/component-base/config/validation/validation.go","code":"// ValidateClientConnectionConfiguration ensures validation of the ClientConnectionConfiguration struct\nfunc ValidateClientConnectionConfiguration(cc *config.ClientConnectionConfiguration, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif cc.Burst \u003c 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"burst\"), cc.Burst, \"must be non-negative\"))\n\t}\n\treturn allErrs\n}","line":{"from":24,"to":31}} {"id":100030212,"name":"ValidateLeaderElectionConfiguration","signature":"func ValidateLeaderElectionConfiguration(cc *config.LeaderElectionConfiguration, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/component-base/config/validation/validation.go","code":"// ValidateLeaderElectionConfiguration ensures validation of the LeaderElectionConfiguration struct\nfunc ValidateLeaderElectionConfiguration(cc *config.LeaderElectionConfiguration, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif !cc.LeaderElect {\n\t\treturn allErrs\n\t}\n\tif cc.LeaseDuration.Duration \u003c= 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"leaseDuration\"), cc.LeaseDuration, \"must be greater than zero\"))\n\t}\n\tif cc.RenewDeadline.Duration \u003c= 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"renewDeadline\"), cc.RenewDeadline, \"must be greater than zero\"))\n\t}\n\tif cc.RetryPeriod.Duration \u003c= 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"retryPeriod\"), cc.RetryPeriod, \"must be greater than zero\"))\n\t}\n\tif cc.LeaseDuration.Duration \u003c= cc.RenewDeadline.Duration {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"leaseDuration\"), cc.RenewDeadline, \"LeaseDuration must be greater than RenewDeadline\"))\n\t}\n\tif len(cc.ResourceLock) == 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"resourceLock\"), cc.ResourceLock, \"resourceLock is required\"))\n\t}\n\tif len(cc.ResourceNamespace) == 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"resourceNamespace\"), cc.ResourceNamespace, \"resourceNamespace is required\"))\n\t}\n\tif len(cc.ResourceName) == 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"resourceName\"), cc.ResourceName, \"resourceName is required\"))\n\t}\n\treturn allErrs\n}","line":{"from":33,"to":61}} {"id":100030213,"name":"InstallHandler","signature":"func InstallHandler(m mux)","file":"staging/src/k8s.io/component-base/configz/configz.go","code":"// InstallHandler adds an HTTP handler on the given mux for the \"/configz\"\n// endpoint which serves all registered ComponentConfigs in JSON format.\nfunc InstallHandler(m mux) {\n\tm.Handle(\"/configz\", http.HandlerFunc(handle))\n}","line":{"from":61,"to":65}} {"id":100030214,"name":"New","signature":"func New(name string) (*Config, error)","file":"staging/src/k8s.io/component-base/configz/configz.go","code":"// New creates a Config object with the given name. Each Config is registered\n// with this package's \"/configz\" handler.\nfunc New(name string) (*Config, error) {\n\tconfigsGuard.Lock()\n\tdefer configsGuard.Unlock()\n\tif _, found := configs[name]; found {\n\t\treturn nil, fmt.Errorf(\"register config %q twice\", name)\n\t}\n\tnewConfig := Config{}\n\tconfigs[name] = \u0026newConfig\n\treturn \u0026newConfig, nil\n}","line":{"from":71,"to":82}} {"id":100030215,"name":"Delete","signature":"func Delete(name string)","file":"staging/src/k8s.io/component-base/configz/configz.go","code":"// Delete removes the named ComponentConfig from this package's \"/configz\"\n// handler.\nfunc Delete(name string) {\n\tconfigsGuard.Lock()\n\tdefer configsGuard.Unlock()\n\tdelete(configs, name)\n}","line":{"from":84,"to":90}} {"id":100030216,"name":"Set","signature":"func (v *Config) Set(val interface{})","file":"staging/src/k8s.io/component-base/configz/configz.go","code":"// Set sets the ComponentConfig for this Config.\nfunc (v *Config) Set(val interface{}) {\n\tconfigsGuard.Lock()\n\tdefer configsGuard.Unlock()\n\tv.val = val\n}","line":{"from":92,"to":97}} {"id":100030217,"name":"MarshalJSON","signature":"func (v *Config) MarshalJSON() ([]byte, error)","file":"staging/src/k8s.io/component-base/configz/configz.go","code":"// MarshalJSON marshals the ComponentConfig as JSON data.\nfunc (v *Config) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(v.val)\n}","line":{"from":99,"to":102}} {"id":100030218,"name":"handle","signature":"func handle(w http.ResponseWriter, r *http.Request)","file":"staging/src/k8s.io/component-base/configz/configz.go","code":"func handle(w http.ResponseWriter, r *http.Request) {\n\tif err := write(w); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}","line":{"from":104,"to":108}} {"id":100030219,"name":"write","signature":"func write(w http.ResponseWriter) error","file":"staging/src/k8s.io/component-base/configz/configz.go","code":"func write(w http.ResponseWriter) error {\n\tvar b []byte\n\tvar err error\n\tfunc() {\n\t\tconfigsGuard.RLock()\n\t\tdefer configsGuard.RUnlock()\n\t\tb, err = json.Marshal(configs)\n\t}()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error marshaling json: %v\", err)\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\t_, err = w.Write(b)\n\treturn err\n}","line":{"from":110,"to":125}} {"id":100030220,"name":"setUnsetAlphaGates","signature":"func setUnsetAlphaGates(known map[Feature]FeatureSpec, enabled map[Feature]bool, val bool)","file":"staging/src/k8s.io/component-base/featuregate/feature_gate.go","code":"func setUnsetAlphaGates(known map[Feature]FeatureSpec, enabled map[Feature]bool, val bool) {\n\tfor k, v := range known {\n\t\tif v.PreRelease == Alpha {\n\t\t\tif _, found := enabled[k]; !found {\n\t\t\t\tenabled[k] = val\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":136,"to":144}} {"id":100030221,"name":"setUnsetBetaGates","signature":"func setUnsetBetaGates(known map[Feature]FeatureSpec, enabled map[Feature]bool, val bool)","file":"staging/src/k8s.io/component-base/featuregate/feature_gate.go","code":"func setUnsetBetaGates(known map[Feature]FeatureSpec, enabled map[Feature]bool, val bool) {\n\tfor k, v := range known {\n\t\tif v.PreRelease == Beta {\n\t\t\tif _, found := enabled[k]; !found {\n\t\t\t\tenabled[k] = val\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":146,"to":154}} {"id":100030222,"name":"NewFeatureGate","signature":"func NewFeatureGate() *featureGate","file":"staging/src/k8s.io/component-base/featuregate/feature_gate.go","code":"func NewFeatureGate() *featureGate {\n\tknown := map[Feature]FeatureSpec{}\n\tfor k, v := range defaultFeatures {\n\t\tknown[k] = v\n\t}\n\n\tknownValue := \u0026atomic.Value{}\n\tknownValue.Store(known)\n\n\tenabled := map[Feature]bool{}\n\tenabledValue := \u0026atomic.Value{}\n\tenabledValue.Store(enabled)\n\n\tf := \u0026featureGate{\n\t\tfeatureGateName: naming.GetNameFromCallsite(internalPackages...),\n\t\tknown: knownValue,\n\t\tspecial: specialFeatures,\n\t\tenabled: enabledValue,\n\t}\n\treturn f\n}","line":{"from":163,"to":183}} {"id":100030223,"name":"Set","signature":"func (f *featureGate) Set(value string) error","file":"staging/src/k8s.io/component-base/featuregate/feature_gate.go","code":"// Set parses a string of the form \"key1=value1,key2=value2,...\" into a\n// map[string]bool of known keys or returns an error.\nfunc (f *featureGate) Set(value string) error {\n\tm := make(map[string]bool)\n\tfor _, s := range strings.Split(value, \",\") {\n\t\tif len(s) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tarr := strings.SplitN(s, \"=\", 2)\n\t\tk := strings.TrimSpace(arr[0])\n\t\tif len(arr) != 2 {\n\t\t\treturn fmt.Errorf(\"missing bool value for %s\", k)\n\t\t}\n\t\tv := strings.TrimSpace(arr[1])\n\t\tboolValue, err := strconv.ParseBool(v)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid value of %s=%s, err: %v\", k, v, err)\n\t\t}\n\t\tm[k] = boolValue\n\t}\n\treturn f.SetFromMap(m)\n}","line":{"from":185,"to":206}} {"id":100030224,"name":"SetFromMap","signature":"func (f *featureGate) SetFromMap(m map[string]bool) error","file":"staging/src/k8s.io/component-base/featuregate/feature_gate.go","code":"// SetFromMap stores flag gates for known features from a map[string]bool or returns an error\nfunc (f *featureGate) SetFromMap(m map[string]bool) error {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\n\t// Copy existing state\n\tknown := map[Feature]FeatureSpec{}\n\tfor k, v := range f.known.Load().(map[Feature]FeatureSpec) {\n\t\tknown[k] = v\n\t}\n\tenabled := map[Feature]bool{}\n\tfor k, v := range f.enabled.Load().(map[Feature]bool) {\n\t\tenabled[k] = v\n\t}\n\n\tfor k, v := range m {\n\t\tk := Feature(k)\n\t\tfeatureSpec, ok := known[k]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unrecognized feature gate: %s\", k)\n\t\t}\n\t\tif featureSpec.LockToDefault \u0026\u0026 featureSpec.Default != v {\n\t\t\treturn fmt.Errorf(\"cannot set feature gate %v to %v, feature is locked to %v\", k, v, featureSpec.Default)\n\t\t}\n\t\tenabled[k] = v\n\t\t// Handle \"special\" features like \"all alpha gates\"\n\t\tif fn, found := f.special[k]; found {\n\t\t\tfn(known, enabled, v)\n\t\t}\n\n\t\tif featureSpec.PreRelease == Deprecated {\n\t\t\tklog.Warningf(\"Setting deprecated feature gate %s=%t. It will be removed in a future release.\", k, v)\n\t\t} else if featureSpec.PreRelease == GA {\n\t\t\tklog.Warningf(\"Setting GA feature gate %s=%t. It will be removed in a future release.\", k, v)\n\t\t}\n\t}\n\n\t// Persist changes\n\tf.known.Store(known)\n\tf.enabled.Store(enabled)\n\n\tklog.V(1).Infof(\"feature gates: %v\", f.enabled)\n\treturn nil\n}","line":{"from":208,"to":251}} {"id":100030225,"name":"String","signature":"func (f *featureGate) String() string","file":"staging/src/k8s.io/component-base/featuregate/feature_gate.go","code":"// String returns a string containing all enabled feature gates, formatted as \"key1=value1,key2=value2,...\".\nfunc (f *featureGate) String() string {\n\tpairs := []string{}\n\tfor k, v := range f.enabled.Load().(map[Feature]bool) {\n\t\tpairs = append(pairs, fmt.Sprintf(\"%s=%t\", k, v))\n\t}\n\tsort.Strings(pairs)\n\treturn strings.Join(pairs, \",\")\n}","line":{"from":253,"to":261}} {"id":100030226,"name":"Type","signature":"func (f *featureGate) Type() string","file":"staging/src/k8s.io/component-base/featuregate/feature_gate.go","code":"func (f *featureGate) Type() string {\n\treturn \"mapStringBool\"\n}","line":{"from":263,"to":265}} {"id":100030227,"name":"Add","signature":"func (f *featureGate) Add(features map[Feature]FeatureSpec) error","file":"staging/src/k8s.io/component-base/featuregate/feature_gate.go","code":"// Add adds features to the featureGate.\nfunc (f *featureGate) Add(features map[Feature]FeatureSpec) error {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\n\tif f.closed {\n\t\treturn fmt.Errorf(\"cannot add a feature gate after adding it to the flag set\")\n\t}\n\n\t// Copy existing state\n\tknown := map[Feature]FeatureSpec{}\n\tfor k, v := range f.known.Load().(map[Feature]FeatureSpec) {\n\t\tknown[k] = v\n\t}\n\n\tfor name, spec := range features {\n\t\tif existingSpec, found := known[name]; found {\n\t\t\tif existingSpec == spec {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"feature gate %q with different spec already exists: %v\", name, existingSpec)\n\t\t}\n\n\t\tknown[name] = spec\n\t}\n\n\t// Persist updated state\n\tf.known.Store(known)\n\n\treturn nil\n}","line":{"from":267,"to":297}} {"id":100030228,"name":"GetAll","signature":"func (f *featureGate) GetAll() map[Feature]FeatureSpec","file":"staging/src/k8s.io/component-base/featuregate/feature_gate.go","code":"// GetAll returns a copy of the map of known feature names to feature specs.\nfunc (f *featureGate) GetAll() map[Feature]FeatureSpec {\n\tretval := map[Feature]FeatureSpec{}\n\tfor k, v := range f.known.Load().(map[Feature]FeatureSpec) {\n\t\tretval[k] = v\n\t}\n\treturn retval\n}","line":{"from":299,"to":306}} {"id":100030229,"name":"Enabled","signature":"func (f *featureGate) Enabled(key Feature) bool","file":"staging/src/k8s.io/component-base/featuregate/feature_gate.go","code":"// Enabled returns true if the key is enabled. If the key is not known, this call will panic.\nfunc (f *featureGate) Enabled(key Feature) bool {\n\tif v, ok := f.enabled.Load().(map[Feature]bool)[key]; ok {\n\t\treturn v\n\t}\n\tif v, ok := f.known.Load().(map[Feature]FeatureSpec)[key]; ok {\n\t\treturn v.Default\n\t}\n\n\tpanic(fmt.Errorf(\"feature %q is not registered in FeatureGate %q\", key, f.featureGateName))\n}","line":{"from":308,"to":318}} {"id":100030230,"name":"AddFlag","signature":"func (f *featureGate) AddFlag(fs *pflag.FlagSet)","file":"staging/src/k8s.io/component-base/featuregate/feature_gate.go","code":"// AddFlag adds a flag for setting global feature gates to the specified FlagSet.\nfunc (f *featureGate) AddFlag(fs *pflag.FlagSet) {\n\tf.lock.Lock()\n\t// TODO(mtaufen): Shouldn't we just close it on the first Set/SetFromMap instead?\n\t// Not all components expose a feature gates flag using this AddFlag method, and\n\t// in the future, all components will completely stop exposing a feature gates flag,\n\t// in favor of componentconfig.\n\tf.closed = true\n\tf.lock.Unlock()\n\n\tknown := f.KnownFeatures()\n\tfs.Var(f, flagName, \"\"+\n\t\t\"A set of key=value pairs that describe feature gates for alpha/experimental features. \"+\n\t\t\"Options are:\\n\"+strings.Join(known, \"\\n\"))\n}","line":{"from":320,"to":334}} {"id":100030231,"name":"AddMetrics","signature":"func (f *featureGate) AddMetrics()","file":"staging/src/k8s.io/component-base/featuregate/feature_gate.go","code":"func (f *featureGate) AddMetrics() {\n\tfor feature, featureSpec := range f.GetAll() {\n\t\tfeaturemetrics.RecordFeatureInfo(context.Background(), string(feature), string(featureSpec.PreRelease), f.Enabled(feature))\n\t}\n}","line":{"from":336,"to":340}} {"id":100030232,"name":"KnownFeatures","signature":"func (f *featureGate) KnownFeatures() []string","file":"staging/src/k8s.io/component-base/featuregate/feature_gate.go","code":"// KnownFeatures returns a slice of strings describing the FeatureGate's known features.\n// Deprecated and GA features are hidden from the list.\nfunc (f *featureGate) KnownFeatures() []string {\n\tvar known []string\n\tfor k, v := range f.known.Load().(map[Feature]FeatureSpec) {\n\t\tif v.PreRelease == GA || v.PreRelease == Deprecated {\n\t\t\tcontinue\n\t\t}\n\t\tknown = append(known, fmt.Sprintf(\"%s=true|false (%s - default=%t)\", k, v.PreRelease, v.Default))\n\t}\n\tsort.Strings(known)\n\treturn known\n}","line":{"from":342,"to":354}} {"id":100030233,"name":"DeepCopy","signature":"func (f *featureGate) DeepCopy() MutableFeatureGate","file":"staging/src/k8s.io/component-base/featuregate/feature_gate.go","code":"// DeepCopy returns a deep copy of the FeatureGate object, such that gates can be\n// set on the copy without mutating the original. This is useful for validating\n// config against potential feature gate changes before committing those changes.\nfunc (f *featureGate) DeepCopy() MutableFeatureGate {\n\t// Copy existing state.\n\tknown := map[Feature]FeatureSpec{}\n\tfor k, v := range f.known.Load().(map[Feature]FeatureSpec) {\n\t\tknown[k] = v\n\t}\n\tenabled := map[Feature]bool{}\n\tfor k, v := range f.enabled.Load().(map[Feature]bool) {\n\t\tenabled[k] = v\n\t}\n\n\t// Store copied state in new atomics.\n\tknownValue := \u0026atomic.Value{}\n\tknownValue.Store(known)\n\tenabledValue := \u0026atomic.Value{}\n\tenabledValue.Store(enabled)\n\n\t// Construct a new featureGate around the copied state.\n\t// Note that specialFeatures is treated as immutable by convention,\n\t// and we maintain the value of f.closed across the copy.\n\treturn \u0026featureGate{\n\t\tspecial: specialFeatures,\n\t\tknown: knownValue,\n\t\tenabled: enabledValue,\n\t\tclosed: f.closed,\n\t}\n}","line":{"from":356,"to":385}} {"id":100030234,"name":"featureGates","signature":"func featureGates() map[featuregate.Feature]featuregate.FeatureSpec","file":"staging/src/k8s.io/component-base/logs/api/v1/kube_features.go","code":"func featureGates() map[featuregate.Feature]featuregate.FeatureSpec {\n\treturn map[featuregate.Feature]featuregate.FeatureSpec{\n\t\tContextualLogging: {Default: contextualLoggingDefault, PreRelease: featuregate.Alpha},\n\n\t\tLoggingAlphaOptions: {Default: false, PreRelease: featuregate.Alpha},\n\t\tLoggingBetaOptions: {Default: true, PreRelease: featuregate.Beta},\n\t}\n}","line":{"from":58,"to":65}} {"id":100030235,"name":"AddFeatureGates","signature":"func AddFeatureGates(mutableFeatureGate featuregate.MutableFeatureGate) error","file":"staging/src/k8s.io/component-base/logs/api/v1/kube_features.go","code":"// AddFeatureGates adds all feature gates used by this package.\nfunc AddFeatureGates(mutableFeatureGate featuregate.MutableFeatureGate) error {\n\treturn mutableFeatureGate.Add(featureGates())\n}","line":{"from":67,"to":70}} {"id":100030236,"name":"NewLoggingConfiguration","signature":"func NewLoggingConfiguration() *LoggingConfiguration","file":"staging/src/k8s.io/component-base/logs/api/v1/options.go","code":"// NewLoggingConfiguration returns a struct holding the default logging configuration.\nfunc NewLoggingConfiguration() *LoggingConfiguration {\n\tc := LoggingConfiguration{}\n\tSetRecommendedLoggingConfiguration(\u0026c)\n\treturn \u0026c\n}","line":{"from":53,"to":58}} {"id":100030237,"name":"ValidateAndApply","signature":"func ValidateAndApply(c *LoggingConfiguration, featureGate featuregate.FeatureGate) error","file":"staging/src/k8s.io/component-base/logs/api/v1/options.go","code":"// ValidateAndApply combines validation and application of the logging configuration.\n// This should be invoked as early as possible because then the rest of the program\n// startup (including validation of other options) will already run with the final\n// logging configuration.\n//\n// The optional FeatureGate controls logging features. If nil, the default for\n// these features is used.\nfunc ValidateAndApply(c *LoggingConfiguration, featureGate featuregate.FeatureGate) error {\n\treturn validateAndApply(c, nil, featureGate, nil)\n}","line":{"from":60,"to":69}} {"id":100030238,"name":"ValidateAndApplyWithOptions","signature":"func ValidateAndApplyWithOptions(c *LoggingConfiguration, options *LoggingOptions, featureGate featuregate.FeatureGate) error","file":"staging/src/k8s.io/component-base/logs/api/v1/options.go","code":"// ValidateAndApplyWithOptions is a variant of ValidateAndApply which accepts\n// additional options beyond those that can be configured through the API. This\n// is meant for testing.\nfunc ValidateAndApplyWithOptions(c *LoggingConfiguration, options *LoggingOptions, featureGate featuregate.FeatureGate) error {\n\treturn validateAndApply(c, options, featureGate, nil)\n}","line":{"from":71,"to":76}} {"id":100030239,"name":"ValidateAndApplyAsField","signature":"func ValidateAndApplyAsField(c *LoggingConfiguration, featureGate featuregate.FeatureGate, fldPath *field.Path) error","file":"staging/src/k8s.io/component-base/logs/api/v1/options.go","code":"// ValidateAndApplyAsField is a variant of ValidateAndApply that should be used\n// when the LoggingConfiguration is embedded in some larger configuration\n// structure.\nfunc ValidateAndApplyAsField(c *LoggingConfiguration, featureGate featuregate.FeatureGate, fldPath *field.Path) error {\n\treturn validateAndApply(c, nil, featureGate, fldPath)\n}","line":{"from":90,"to":95}} {"id":100030240,"name":"validateAndApply","signature":"func validateAndApply(c *LoggingConfiguration, options *LoggingOptions, featureGate featuregate.FeatureGate, fldPath *field.Path) error","file":"staging/src/k8s.io/component-base/logs/api/v1/options.go","code":"func validateAndApply(c *LoggingConfiguration, options *LoggingOptions, featureGate featuregate.FeatureGate, fldPath *field.Path) error {\n\terrs := Validate(c, featureGate, fldPath)\n\tif len(errs) \u003e 0 {\n\t\treturn errs.ToAggregate()\n\t}\n\treturn apply(c, options, featureGate)\n}","line":{"from":97,"to":103}} {"id":100030241,"name":"Validate","signature":"func Validate(c *LoggingConfiguration, featureGate featuregate.FeatureGate, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/component-base/logs/api/v1/options.go","code":"// Validate can be used to check for invalid settings without applying them.\n// Most binaries should validate and apply the logging configuration as soon\n// as possible via ValidateAndApply. The field path is optional: nil\n// can be passed when the struct is not embedded in some larger struct.\nfunc Validate(c *LoggingConfiguration, featureGate featuregate.FeatureGate, fldPath *field.Path) field.ErrorList {\n\terrs := field.ErrorList{}\n\tif c.Format != DefaultLogFormat {\n\t\t// WordSepNormalizeFunc is just a guess. Commands should use it,\n\t\t// but we cannot know for sure.\n\t\tallFlags := unsupportedLoggingFlags(cliflag.WordSepNormalizeFunc)\n\t\tfor _, f := range allFlags {\n\t\t\tif f.DefValue != f.Value.String() {\n\t\t\t\terrs = append(errs, field.Invalid(fldPath.Child(\"format\"), c.Format, fmt.Sprintf(\"Non-default format doesn't honor flag: %s\", f.Name)))\n\t\t\t}\n\t\t}\n\t}\n\tformat, err := logRegistry.get(c.Format)\n\tif err != nil {\n\t\terrs = append(errs, field.Invalid(fldPath.Child(\"format\"), c.Format, \"Unsupported log format\"))\n\t} else if format != nil {\n\t\tif format.feature != LoggingStableOptions {\n\t\t\tenabled := featureGates()[format.feature].Default\n\t\t\tif featureGate != nil {\n\t\t\t\tenabled = featureGate.Enabled(format.feature)\n\t\t\t}\n\t\t\tif !enabled {\n\t\t\t\terrs = append(errs, field.Forbidden(fldPath.Child(\"format\"), fmt.Sprintf(\"Log format %s is disabled, see %s feature\", c.Format, format.feature)))\n\t\t\t}\n\t\t}\n\t}\n\n\t// The type in our struct is uint32, but klog only accepts positive int32.\n\tif c.Verbosity \u003e math.MaxInt32 {\n\t\terrs = append(errs, field.Invalid(fldPath.Child(\"verbosity\"), c.Verbosity, fmt.Sprintf(\"Must be \u003c= %d\", math.MaxInt32)))\n\t}\n\tvmoduleFldPath := fldPath.Child(\"vmodule\")\n\tif len(c.VModule) \u003e 0 \u0026\u0026 c.Format != \"\" \u0026\u0026 c.Format != \"text\" {\n\t\terrs = append(errs, field.Forbidden(vmoduleFldPath, \"Only supported for text log format\"))\n\t}\n\tfor i, item := range c.VModule {\n\t\tif item.FilePattern == \"\" {\n\t\t\terrs = append(errs, field.Required(vmoduleFldPath.Index(i), \"File pattern must not be empty\"))\n\t\t}\n\t\tif strings.ContainsAny(item.FilePattern, \"=,\") {\n\t\t\terrs = append(errs, field.Invalid(vmoduleFldPath.Index(i), item.FilePattern, \"File pattern must not contain equal sign or comma\"))\n\t\t}\n\t\tif item.Verbosity \u003e math.MaxInt32 {\n\t\t\terrs = append(errs, field.Invalid(vmoduleFldPath.Index(i), item.Verbosity, fmt.Sprintf(\"Must be \u003c= %d\", math.MaxInt32)))\n\t\t}\n\t}\n\n\terrs = append(errs, validateFormatOptions(c, featureGate, fldPath.Child(\"options\"))...)\n\treturn errs\n}","line":{"from":105,"to":158}} {"id":100030242,"name":"validateFormatOptions","signature":"func validateFormatOptions(c *LoggingConfiguration, featureGate featuregate.FeatureGate, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/component-base/logs/api/v1/options.go","code":"func validateFormatOptions(c *LoggingConfiguration, featureGate featuregate.FeatureGate, fldPath *field.Path) field.ErrorList {\n\terrs := field.ErrorList{}\n\terrs = append(errs, validateJSONOptions(c, featureGate, fldPath.Child(\"json\"))...)\n\treturn errs\n}","line":{"from":160,"to":164}} {"id":100030243,"name":"validateJSONOptions","signature":"func validateJSONOptions(c *LoggingConfiguration, featureGate featuregate.FeatureGate, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/component-base/logs/api/v1/options.go","code":"func validateJSONOptions(c *LoggingConfiguration, featureGate featuregate.FeatureGate, fldPath *field.Path) field.ErrorList {\n\terrs := field.ErrorList{}\n\tif gate := LoggingAlphaOptions; c.Options.JSON.SplitStream \u0026\u0026 !featureEnabled(featureGate, gate) {\n\t\terrs = append(errs, field.Forbidden(fldPath.Child(\"splitStream\"), fmt.Sprintf(\"Feature %s is disabled\", gate)))\n\t}\n\tif gate := LoggingAlphaOptions; c.Options.JSON.InfoBufferSize.Value() != 0 \u0026\u0026 !featureEnabled(featureGate, gate) {\n\t\terrs = append(errs, field.Forbidden(fldPath.Child(\"infoBufferSize\"), fmt.Sprintf(\"Feature %s is disabled\", gate)))\n\t}\n\treturn errs\n}","line":{"from":166,"to":175}} {"id":100030244,"name":"featureEnabled","signature":"func featureEnabled(featureGate featuregate.FeatureGate, feature featuregate.Feature) bool","file":"staging/src/k8s.io/component-base/logs/api/v1/options.go","code":"func featureEnabled(featureGate featuregate.FeatureGate, feature featuregate.Feature) bool {\n\tenabled := false\n\tif featureGate != nil {\n\t\tenabled = featureGate.Enabled(feature)\n\t}\n\treturn enabled\n}","line":{"from":177,"to":183}} {"id":100030245,"name":"apply","signature":"func apply(c *LoggingConfiguration, options *LoggingOptions, featureGate featuregate.FeatureGate) error","file":"staging/src/k8s.io/component-base/logs/api/v1/options.go","code":"func apply(c *LoggingConfiguration, options *LoggingOptions, featureGate featuregate.FeatureGate) error {\n\tcontextualLoggingEnabled := contextualLoggingDefault\n\tif featureGate != nil {\n\t\tcontextualLoggingEnabled = featureGate.Enabled(ContextualLogging)\n\t}\n\n\t// if log format not exists, use nil loggr\n\tformat, _ := logRegistry.get(c.Format)\n\tif format.factory == nil {\n\t\tklog.ClearLogger()\n\t} else {\n\t\tif options == nil {\n\t\t\toptions = \u0026LoggingOptions{\n\t\t\t\tErrorStream: os.Stderr,\n\t\t\t\tInfoStream: os.Stdout,\n\t\t\t}\n\t\t}\n\t\tlog, control := format.factory.Create(*c, *options)\n\t\tif control.SetVerbosityLevel != nil {\n\t\t\tsetverbositylevel.Mutex.Lock()\n\t\t\tdefer setverbositylevel.Mutex.Unlock()\n\t\t\tsetverbositylevel.Callbacks = append(setverbositylevel.Callbacks, control.SetVerbosityLevel)\n\t\t}\n\t\tklog.SetLoggerWithOptions(log, klog.ContextualLogger(contextualLoggingEnabled), klog.FlushLogger(control.Flush))\n\t}\n\tif err := loggingFlags.Lookup(\"v\").Value.Set(VerbosityLevelPflag(\u0026c.Verbosity).String()); err != nil {\n\t\treturn fmt.Errorf(\"internal error while setting klog verbosity: %v\", err)\n\t}\n\tif err := loggingFlags.Lookup(\"vmodule\").Value.Set(VModuleConfigurationPflag(\u0026c.VModule).String()); err != nil {\n\t\treturn fmt.Errorf(\"internal error while setting klog vmodule: %v\", err)\n\t}\n\tklog.StartFlushDaemon(c.FlushFrequency)\n\tklog.EnableContextualLogging(contextualLoggingEnabled)\n\treturn nil\n}","line":{"from":185,"to":219}} {"id":100030246,"name":"AddFlags","signature":"func AddFlags(c *LoggingConfiguration, fs *pflag.FlagSet)","file":"staging/src/k8s.io/component-base/logs/api/v1/options.go","code":"// AddFlags adds command line flags for the configuration.\nfunc AddFlags(c *LoggingConfiguration, fs *pflag.FlagSet) {\n\taddFlags(c, fs)\n}","line":{"from":221,"to":224}} {"id":100030247,"name":"AddGoFlags","signature":"func AddGoFlags(c *LoggingConfiguration, fs *flag.FlagSet)","file":"staging/src/k8s.io/component-base/logs/api/v1/options.go","code":"// AddGoFlags is a variant of AddFlags for a standard FlagSet.\nfunc AddGoFlags(c *LoggingConfiguration, fs *flag.FlagSet) {\n\taddFlags(c, goFlagSet{FlagSet: fs})\n}","line":{"from":226,"to":229}} {"id":100030248,"name":"Var","signature":"func (fs goFlagSet) Var(value pflag.Value, name string, usage string)","file":"staging/src/k8s.io/component-base/logs/api/v1/options.go","code":"func (fs goFlagSet) Var(value pflag.Value, name string, usage string) {\n\tfs.FlagSet.Var(value, name, usage)\n}","line":{"from":246,"to":248}} {"id":100030249,"name":"VarP","signature":"func (fs goFlagSet) VarP(value pflag.Value, name, shorthand, usage string)","file":"staging/src/k8s.io/component-base/logs/api/v1/options.go","code":"func (fs goFlagSet) VarP(value pflag.Value, name, shorthand, usage string) {\n\t// Ignore shorthand, it's not needed and not supported.\n\tfs.FlagSet.Var(value, name, usage)\n}","line":{"from":250,"to":253}} {"id":100030250,"name":"addFlags","signature":"func addFlags(c *LoggingConfiguration, fs flagSet)","file":"staging/src/k8s.io/component-base/logs/api/v1/options.go","code":"// addFlags can be used with both flag.FlagSet and pflag.FlagSet. The internal\n// interface definition avoids duplicating this code.\nfunc addFlags(c *LoggingConfiguration, fs flagSet) {\n\tformats := logRegistry.list()\n\tfs.StringVar(\u0026c.Format, \"logging-format\", c.Format, fmt.Sprintf(\"Sets the log format. Permitted formats: %s.\", formats))\n\t// No new log formats should be added after generation is of flag options\n\tlogRegistry.freeze()\n\n\tfs.DurationVar(\u0026c.FlushFrequency, LogFlushFreqFlagName, c.FlushFrequency, \"Maximum number of seconds between log flushes\")\n\tfs.VarP(VerbosityLevelPflag(\u0026c.Verbosity), \"v\", \"v\", \"number for the log level verbosity\")\n\tfs.Var(VModuleConfigurationPflag(\u0026c.VModule), \"vmodule\", \"comma-separated list of pattern=N settings for file-filtered logging (only works for text log format)\")\n\n\t// JSON options. We only register them if \"json\" is a valid format. The\n\t// config file API however always has them.\n\tif _, err := logRegistry.get(\"json\"); err == nil {\n\t\tfs.BoolVar(\u0026c.Options.JSON.SplitStream, \"log-json-split-stream\", false, \"[Alpha] In JSON format, write error messages to stderr and info messages to stdout. The default is to write a single stream to stdout. Enable the LoggingAlphaOptions feature gate to use this.\")\n\t\tfs.Var(\u0026c.Options.JSON.InfoBufferSize, \"log-json-info-buffer-size\", \"[Alpha] In JSON format with split output streams, the info messages can be buffered for a while to increase performance. The default value of zero bytes disables buffering. The size can be specified as number of bytes (512), multiples of 1000 (1K), multiples of 1024 (2Ki), or powers of those (3M, 4G, 5Mi, 6Gi). Enable the LoggingAlphaOptions feature gate to use this.\")\n\t}\n}","line":{"from":255,"to":273}} {"id":100030251,"name":"SetRecommendedLoggingConfiguration","signature":"func SetRecommendedLoggingConfiguration(c *LoggingConfiguration)","file":"staging/src/k8s.io/component-base/logs/api/v1/options.go","code":"// SetRecommendedLoggingConfiguration sets the default logging configuration\n// for fields that are unset.\n//\n// Consumers who embed LoggingConfiguration in their own configuration structs\n// may set custom defaults and then should call this function to add the\n// global defaults.\nfunc SetRecommendedLoggingConfiguration(c *LoggingConfiguration) {\n\tif c.Format == \"\" {\n\t\tc.Format = \"text\"\n\t}\n\tif c.FlushFrequency == 0 {\n\t\tc.FlushFrequency = LogFlushFreqDefault\n\t}\n\tvar empty resource.QuantityValue\n\tif c.Options.JSON.InfoBufferSize == empty {\n\t\tc.Options.JSON.InfoBufferSize = resource.QuantityValue{\n\t\t\t// This is similar, but not quite the same as a default\n\t\t\t// constructed instance.\n\t\t\tQuantity: *resource.NewQuantity(0, resource.DecimalSI),\n\t\t}\n\t\t// This sets the unexported Quantity.s which will be compared\n\t\t// by reflect.DeepEqual in some tests.\n\t\t_ = c.Options.JSON.InfoBufferSize.String()\n\t}\n}","line":{"from":275,"to":299}} {"id":100030252,"name":"init","signature":"func init()","file":"staging/src/k8s.io/component-base/logs/api/v1/options.go","code":"func init() {\n\tvar fs flag.FlagSet\n\tklogflags.Init(\u0026fs)\n\tloggingFlags.AddGoFlagSet(\u0026fs)\n}","line":{"from":305,"to":309}} {"id":100030253,"name":"unsupportedLoggingFlags","signature":"func unsupportedLoggingFlags(normalizeFunc func(f *pflag.FlagSet, name string) pflag.NormalizedName) []*pflag.Flag","file":"staging/src/k8s.io/component-base/logs/api/v1/options.go","code":"// unsupportedLoggingFlags lists unsupported logging flags. The normalize\n// function is optional.\nfunc unsupportedLoggingFlags(normalizeFunc func(f *pflag.FlagSet, name string) pflag.NormalizedName) []*pflag.Flag {\n\t// k8s.io/component-base/logs and klog flags\n\tpfs := \u0026pflag.FlagSet{}\n\tloggingFlags.VisitAll(func(flag *pflag.Flag) {\n\t\tif _, found := supportedLogsFlags[flag.Name]; !found {\n\t\t\t// Normalization changes flag.Name, so make a copy.\n\t\t\tclone := *flag\n\t\t\tpfs.AddFlag(\u0026clone)\n\t\t}\n\t})\n\n\t// Apply normalization.\n\tpfs.SetNormalizeFunc(normalizeFunc)\n\n\tvar allFlags []*pflag.Flag\n\tpfs.VisitAll(func(flag *pflag.Flag) {\n\t\tallFlags = append(allFlags, flag)\n\t})\n\treturn allFlags\n}","line":{"from":316,"to":337}} {"id":100030254,"name":"VModuleConfigurationPflag","signature":"func VModuleConfigurationPflag(value *VModuleConfiguration) pflag.Value","file":"staging/src/k8s.io/component-base/logs/api/v1/pflags.go","code":"// VModuleConfigurationPflag implements the pflag.Value interface for a\n// VModuleConfiguration. The value pointer must not be nil.\nfunc VModuleConfigurationPflag(value *VModuleConfiguration) pflag.Value {\n\treturn vmoduleConfigurationPFlag{value}\n}","line":{"from":27,"to":31}} {"id":100030255,"name":"String","signature":"func (wrapper vmoduleConfigurationPFlag) String() string","file":"staging/src/k8s.io/component-base/logs/api/v1/pflags.go","code":"// String returns the -vmodule parameter (comma-separated list of pattern=N).\nfunc (wrapper vmoduleConfigurationPFlag) String() string {\n\tif wrapper.value == nil {\n\t\treturn \"\"\n\t}\n\tvar patterns []string\n\tfor _, item := range *wrapper.value {\n\t\tpatterns = append(patterns, fmt.Sprintf(\"%s=%d\", item.FilePattern, item.Verbosity))\n\t}\n\treturn strings.Join(patterns, \",\")\n}","line":{"from":37,"to":47}} {"id":100030256,"name":"Set","signature":"func (wrapper vmoduleConfigurationPFlag) Set(value string) error","file":"staging/src/k8s.io/component-base/logs/api/v1/pflags.go","code":"// Set parses the -vmodule parameter (comma-separated list of pattern=N).\nfunc (wrapper vmoduleConfigurationPFlag) Set(value string) error {\n\t// This code mirrors https://github.com/kubernetes/klog/blob/9ad246211af1ed84621ee94a26fcce0038b69cd1/klog.go#L287-L313\n\n\tfor _, pat := range strings.Split(value, \",\") {\n\t\tif len(pat) == 0 {\n\t\t\t// Empty strings such as from a trailing comma can be ignored.\n\t\t\tcontinue\n\t\t}\n\t\tpatLev := strings.Split(pat, \"=\")\n\t\tif len(patLev) != 2 || len(patLev[0]) == 0 || len(patLev[1]) == 0 {\n\t\t\treturn fmt.Errorf(\"%q does not have the pattern=N format\", pat)\n\t\t}\n\t\tpattern := patLev[0]\n\t\t// 31 instead of 32 to ensure that it also fits into int32.\n\t\tv, err := strconv.ParseUint(patLev[1], 10, 31)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"parsing verbosity in %q: %v\", pat, err)\n\t\t}\n\t\t*wrapper.value = append(*wrapper.value, VModuleItem{FilePattern: pattern, Verbosity: VerbosityLevel(v)})\n\t}\n\treturn nil\n}","line":{"from":49,"to":71}} {"id":100030257,"name":"Type","signature":"func (wrapper vmoduleConfigurationPFlag) Type() string","file":"staging/src/k8s.io/component-base/logs/api/v1/pflags.go","code":"func (wrapper vmoduleConfigurationPFlag) Type() string {\n\treturn \"pattern=N,...\"\n}","line":{"from":73,"to":75}} {"id":100030258,"name":"VerbosityLevelPflag","signature":"func VerbosityLevelPflag(value *VerbosityLevel) pflag.Value","file":"staging/src/k8s.io/component-base/logs/api/v1/pflags.go","code":"// VerbosityLevelPflag implements the pflag.Value interface for a verbosity\n// level value.\nfunc VerbosityLevelPflag(value *VerbosityLevel) pflag.Value {\n\treturn verbosityLevelPflag{value}\n}","line":{"from":77,"to":81}} {"id":100030259,"name":"String","signature":"func (wrapper verbosityLevelPflag) String() string","file":"staging/src/k8s.io/component-base/logs/api/v1/pflags.go","code":"func (wrapper verbosityLevelPflag) String() string {\n\tif wrapper.value == nil {\n\t\treturn \"0\"\n\t}\n\treturn strconv.FormatInt(int64(*wrapper.value), 10)\n}","line":{"from":87,"to":92}} {"id":100030260,"name":"Get","signature":"func (wrapper verbosityLevelPflag) Get() interface{}","file":"staging/src/k8s.io/component-base/logs/api/v1/pflags.go","code":"func (wrapper verbosityLevelPflag) Get() interface{} {\n\tif wrapper.value == nil {\n\t\treturn VerbosityLevel(0)\n\t}\n\treturn *wrapper.value\n}","line":{"from":94,"to":99}} {"id":100030261,"name":"Set","signature":"func (wrapper verbosityLevelPflag) Set(value string) error","file":"staging/src/k8s.io/component-base/logs/api/v1/pflags.go","code":"func (wrapper verbosityLevelPflag) Set(value string) error {\n\t// Limited to int32 for compatibility with klog.\n\tv, err := strconv.ParseUint(value, 10, 31)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*wrapper.value = VerbosityLevel(v)\n\treturn nil\n}","line":{"from":101,"to":109}} {"id":100030262,"name":"Type","signature":"func (wrapper verbosityLevelPflag) Type() string","file":"staging/src/k8s.io/component-base/logs/api/v1/pflags.go","code":"func (wrapper verbosityLevelPflag) Type() string {\n\treturn \"Level\"\n}","line":{"from":111,"to":113}} {"id":100030263,"name":"RegisterLogFormat","signature":"func RegisterLogFormat(name string, factory LogFormatFactory, feature featuregate.Feature) error","file":"staging/src/k8s.io/component-base/logs/api/v1/registry.go","code":"// RegisterLogFormat registers support for a new logging format. This must be called\n// before using any of the methods in LoggingConfiguration. The feature must\n// be one of those defined in this package (typically LoggingAlphaOptions,\n// LoggingBetaOptions or LoggingStableOptions).\nfunc RegisterLogFormat(name string, factory LogFormatFactory, feature featuregate.Feature) error {\n\treturn logRegistry.register(name, logFormat{factory, feature})\n}","line":{"from":67,"to":73}} {"id":100030264,"name":"newLogFormatRegistry","signature":"func newLogFormatRegistry() *logFormatRegistry","file":"staging/src/k8s.io/component-base/logs/api/v1/registry.go","code":"func newLogFormatRegistry() *logFormatRegistry {\n\tregistry := \u0026logFormatRegistry{\n\t\tregistry: make(map[string]logFormat),\n\t\tfrozen: false,\n\t}\n\tregistry.register(\"text\", logFormat{feature: LoggingStableOptions})\n\treturn registry\n}","line":{"from":75,"to":82}} {"id":100030265,"name":"register","signature":"func (lfr *logFormatRegistry) register(name string, format logFormat) error","file":"staging/src/k8s.io/component-base/logs/api/v1/registry.go","code":"// register adds a new log format. It's an error to modify an existing one.\nfunc (lfr *logFormatRegistry) register(name string, format logFormat) error {\n\tif lfr.frozen {\n\t\treturn fmt.Errorf(\"log format registry is frozen, unable to register log format %s\", name)\n\t}\n\tif _, ok := lfr.registry[name]; ok {\n\t\treturn fmt.Errorf(\"log format: %s already exists\", name)\n\t}\n\tif _, ok := featureGates()[format.feature]; !ok \u0026\u0026 format.feature != LoggingStableOptions {\n\t\treturn fmt.Errorf(\"log format %s: unsupported feature gate %s\", name, format.feature)\n\t}\n\tlfr.registry[name] = format\n\treturn nil\n}","line":{"from":84,"to":97}} {"id":100030266,"name":"get","signature":"func (lfr *logFormatRegistry) get(name string) (*logFormat, error)","file":"staging/src/k8s.io/component-base/logs/api/v1/registry.go","code":"// get specified log format factory\nfunc (lfr *logFormatRegistry) get(name string) (*logFormat, error) {\n\tformat, ok := lfr.registry[name]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"log format: %s does not exists\", name)\n\t}\n\treturn \u0026format, nil\n}","line":{"from":99,"to":106}} {"id":100030267,"name":"list","signature":"func (lfr *logFormatRegistry) list() string","file":"staging/src/k8s.io/component-base/logs/api/v1/registry.go","code":"// list names of registered log formats, including feature gates (sorted)\nfunc (lfr *logFormatRegistry) list() string {\n\tformats := make([]string, 0, len(lfr.registry))\n\tfor name, format := range lfr.registry {\n\t\titem := fmt.Sprintf(`\"%s\"`, name)\n\t\tif format.feature != LoggingStableOptions {\n\t\t\titem += fmt.Sprintf(\" (gated by %s)\", format.feature)\n\t\t}\n\t\tformats = append(formats, item)\n\t}\n\tsort.Strings(formats)\n\treturn strings.Join(formats, \", \")\n}","line":{"from":108,"to":120}} {"id":100030268,"name":"freeze","signature":"func (lfr *logFormatRegistry) freeze()","file":"staging/src/k8s.io/component-base/logs/api/v1/registry.go","code":"// freeze prevents further modifications of the registered log formats.\nfunc (lfr *logFormatRegistry) freeze() {\n\tlfr.frozen = true\n}","line":{"from":122,"to":125}} {"id":100030269,"name":"Verify","signature":"func Verify(value interface{}) []string","file":"staging/src/k8s.io/component-base/logs/datapol/datapol.go","code":"// Verify returns a list of the datatypes contained in the argument that can be\n// considered sensitive w.r.t. to logging\nfunc Verify(value interface{}) []string {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\t//TODO maybe export a metric\n\t\t\tklog.Warningf(\"Error while inspecting arguments for sensitive data: %v\", r)\n\t\t}\n\t}()\n\tt := reflect.ValueOf(value)\n\tif t.Kind() == reflect.Pointer {\n\t\tt = t.Elem()\n\t}\n\treturn datatypes(t)\n}","line":{"from":28,"to":42}} {"id":100030270,"name":"datatypes","signature":"func datatypes(v reflect.Value) []string","file":"staging/src/k8s.io/component-base/logs/datapol/datapol.go","code":"func datatypes(v reflect.Value) []string {\n\tif types := byType(v.Type()); len(types) \u003e 0 {\n\t\t// Slices, and maps can be nil or empty, only the nil case is zero\n\t\tswitch v.Kind() {\n\t\tcase reflect.Slice, reflect.Map:\n\t\t\tif !v.IsZero() \u0026\u0026 v.Len() \u003e 0 {\n\t\t\t\treturn types\n\t\t\t}\n\t\tdefault:\n\t\t\tif !v.IsZero() {\n\t\t\t\treturn types\n\t\t\t}\n\t\t}\n\t}\n\tswitch v.Kind() {\n\tcase reflect.Interface:\n\t\treturn datatypes(v.Elem())\n\tcase reflect.Slice, reflect.Array:\n\t\tfor i := 0; i \u003c v.Len(); i++ {\n\t\t\tif types := datatypes(v.Index(i)); len(types) \u003e 0 {\n\t\t\t\treturn types\n\t\t\t}\n\t\t}\n\tcase reflect.Map:\n\t\tmapIter := v.MapRange()\n\t\tfor mapIter.Next() {\n\t\t\tk := mapIter.Key()\n\t\t\tv := mapIter.Value()\n\t\t\tif types := datatypes(k); len(types) \u003e 0 {\n\t\t\t\treturn types\n\t\t\t}\n\t\t\tif types := datatypes(v); len(types) \u003e 0 {\n\t\t\t\treturn types\n\t\t\t}\n\t\t}\n\tcase reflect.Struct:\n\t\tt := v.Type()\n\t\tnumField := t.NumField()\n\n\t\tfor i := 0; i \u003c numField; i++ {\n\t\t\tf := t.Field(i)\n\t\t\tif f.Type.Kind() == reflect.Pointer {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif reason, ok := f.Tag.Lookup(\"datapolicy\"); ok {\n\t\t\t\tif !v.Field(i).IsZero() {\n\t\t\t\t\treturn strings.Split(reason, \",\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tif types := datatypes(v.Field(i)); len(types) \u003e 0 {\n\t\t\t\treturn types\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":44,"to":99}} {"id":100030271,"name":"GlobalDatapolicyMapping","signature":"func GlobalDatapolicyMapping(v interface{}) []string","file":"staging/src/k8s.io/component-base/logs/datapol/externaltypes.go","code":"// GlobalDatapolicyMapping returns the list of sensitive datatypes are embedded\n// in types not native to Kubernetes.\nfunc GlobalDatapolicyMapping(v interface{}) []string {\n\treturn byType(reflect.TypeOf(v))\n}","line":{"from":30,"to":34}} {"id":100030272,"name":"byType","signature":"func byType(t reflect.Type) []string","file":"staging/src/k8s.io/component-base/logs/datapol/externaltypes.go","code":"func byType(t reflect.Type) []string {\n\t// Use string representation of the type to prevent taking a depency on the actual type.\n\tswitch fmt.Sprintf(\"%s.%s\", t.PkgPath(), t.Name()) {\n\tcase httpHeader:\n\t\treturn []string{\"password\", \"token\"}\n\tcase httpCookie:\n\t\treturn []string{\"token\"}\n\tcase x509Certificate:\n\t\treturn []string{\"security-key\"}\n\tdefault:\n\t\treturn nil\n\t}\n\n}","line":{"from":36,"to":49}} {"id":100030273,"name":"ZapV","signature":"func (r *runtime) ZapV() zapcore.Level","file":"staging/src/k8s.io/component-base/logs/json/json.go","code":"func (r *runtime) ZapV() zapcore.Level {\n\t// zap levels are inverted: everything with a verbosity \u003e= threshold gets logged.\n\treturn -zapcore.Level(atomic.LoadUint32(\u0026r.v))\n}","line":{"from":42,"to":45}} {"id":100030274,"name":"Enabled","signature":"func (r *runtime) Enabled(level zapcore.Level) bool","file":"staging/src/k8s.io/component-base/logs/json/json.go","code":"// Enabled implements the zapcore.LevelEnabler interface.\nfunc (r *runtime) Enabled(level zapcore.Level) bool {\n\treturn level \u003e= r.ZapV()\n}","line":{"from":47,"to":50}} {"id":100030275,"name":"SetVerbosityLevel","signature":"func (r *runtime) SetVerbosityLevel(v uint32) error","file":"staging/src/k8s.io/component-base/logs/json/json.go","code":"func (r *runtime) SetVerbosityLevel(v uint32) error {\n\tatomic.StoreUint32(\u0026r.v, v)\n\treturn nil\n}","line":{"from":52,"to":55}} {"id":100030276,"name":"NewJSONLogger","signature":"func NewJSONLogger(v logsapi.VerbosityLevel, infoStream, errorStream zapcore.WriteSyncer, encoderConfig *zapcore.EncoderConfig) (logr.Logger, logsapi.RuntimeControl)","file":"staging/src/k8s.io/component-base/logs/json/json.go","code":"// NewJSONLogger creates a new json logr.Logger and its associated\n// control interface. The separate error stream is optional and may be nil.\n// The encoder config is also optional.\nfunc NewJSONLogger(v logsapi.VerbosityLevel, infoStream, errorStream zapcore.WriteSyncer, encoderConfig *zapcore.EncoderConfig) (logr.Logger, logsapi.RuntimeControl) {\n\tr := \u0026runtime{v: uint32(v)}\n\n\tif encoderConfig == nil {\n\t\tencoderConfig = \u0026zapcore.EncoderConfig{\n\t\t\tMessageKey: \"msg\",\n\t\t\tCallerKey: \"caller\",\n\t\t\tNameKey: \"logger\",\n\t\t\tTimeKey: \"ts\",\n\t\t\tEncodeTime: epochMillisTimeEncoder,\n\t\t\tEncodeDuration: zapcore.StringDurationEncoder,\n\t\t\tEncodeCaller: zapcore.ShortCallerEncoder,\n\t\t}\n\t}\n\n\tencoder := zapcore.NewJSONEncoder(*encoderConfig)\n\tvar core zapcore.Core\n\tif errorStream == nil {\n\t\tcore = zapcore.NewCore(encoder, infoStream, r)\n\t} else {\n\t\thighPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {\n\t\t\treturn lvl \u003e= zapcore.ErrorLevel \u0026\u0026 r.Enabled(lvl)\n\t\t})\n\t\tlowPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {\n\t\t\treturn lvl \u003c zapcore.ErrorLevel \u0026\u0026 r.Enabled(lvl)\n\t\t})\n\t\tcore = zapcore.NewTee(\n\t\t\tzapcore.NewCore(encoder, errorStream, highPriority),\n\t\t\tzapcore.NewCore(encoder, infoStream, lowPriority),\n\t\t)\n\t}\n\tl := zap.New(core, zap.WithCaller(true))\n\treturn zapr.NewLoggerWithOptions(l, zapr.LogInfoLevel(\"v\"), zapr.ErrorKey(\"err\")),\n\t\tlogsapi.RuntimeControl{\n\t\t\tSetVerbosityLevel: r.SetVerbosityLevel,\n\t\t\tFlush: func() {\n\t\t\t\t_ = l.Sync()\n\t\t\t},\n\t\t}\n}","line":{"from":59,"to":101}} {"id":100030277,"name":"epochMillisTimeEncoder","signature":"func epochMillisTimeEncoder(_ time.Time, enc zapcore.PrimitiveArrayEncoder)","file":"staging/src/k8s.io/component-base/logs/json/json.go","code":"func epochMillisTimeEncoder(_ time.Time, enc zapcore.PrimitiveArrayEncoder) {\n\tnanos := timeNow().UnixNano()\n\tmillis := float64(nanos) / float64(time.Millisecond)\n\tenc.AppendFloat64(millis)\n}","line":{"from":103,"to":107}} {"id":100030278,"name":"Feature","signature":"func (f Factory) Feature() featuregate.Feature","file":"staging/src/k8s.io/component-base/logs/json/json.go","code":"func (f Factory) Feature() featuregate.Feature {\n\treturn logsapi.LoggingBetaOptions\n}","line":{"from":114,"to":116}} {"id":100030279,"name":"Create","signature":"func (f Factory) Create(c logsapi.LoggingConfiguration, o logsapi.LoggingOptions) (logr.Logger, logsapi.RuntimeControl)","file":"staging/src/k8s.io/component-base/logs/json/json.go","code":"func (f Factory) Create(c logsapi.LoggingConfiguration, o logsapi.LoggingOptions) (logr.Logger, logsapi.RuntimeControl) {\n\t// We intentionally avoid all os.File.Sync calls. Output is unbuffered,\n\t// therefore we don't need to flush, and calling the underlying fsync\n\t// would just slow down writing.\n\t//\n\t// The assumption is that logging only needs to ensure that data gets\n\t// written to the output stream before the process terminates, but\n\t// doesn't need to worry about data not being written because of a\n\t// system crash or powerloss.\n\tstderr := zapcore.Lock(AddNopSync(o.ErrorStream))\n\tif c.Options.JSON.SplitStream {\n\t\tstdout := zapcore.Lock(AddNopSync(o.InfoStream))\n\t\tsize := c.Options.JSON.InfoBufferSize.Value()\n\t\tif size \u003e 0 {\n\t\t\t// Prevent integer overflow.\n\t\t\tif size \u003e 2*1024*1024*1024 {\n\t\t\t\tsize = 2 * 1024 * 1024 * 1024\n\t\t\t}\n\t\t\tstdout = \u0026zapcore.BufferedWriteSyncer{\n\t\t\t\tWS: stdout,\n\t\t\t\tSize: int(size),\n\t\t\t}\n\t\t}\n\t\t// stdout for info messages, stderr for errors.\n\t\treturn NewJSONLogger(c.Verbosity, stdout, stderr, nil)\n\t}\n\t// Write info messages and errors to stderr to prevent mixing with normal program output.\n\treturn NewJSONLogger(c.Verbosity, stderr, nil, nil)\n}","line":{"from":118,"to":146}} {"id":100030280,"name":"AddNopSync","signature":"func AddNopSync(writer io.Writer) zapcore.WriteSyncer","file":"staging/src/k8s.io/component-base/logs/json/json.go","code":"// AddNoSync adds a NOP Sync implementation.\nfunc AddNopSync(writer io.Writer) zapcore.WriteSyncer {\n\treturn nopSync{Writer: writer}\n}","line":{"from":148,"to":151}} {"id":100030281,"name":"Sync","signature":"func (f nopSync) Sync() error","file":"staging/src/k8s.io/component-base/logs/json/json.go","code":"func (f nopSync) Sync() error {\n\treturn nil\n}","line":{"from":157,"to":159}} {"id":100030282,"name":"init","signature":"func init()","file":"staging/src/k8s.io/component-base/logs/json/register/register.go","code":"func init() {\n\t// JSON format is optional klog format\n\tif err := logsapi.RegisterLogFormat(logsapi.JSONLogFormat, json.Factory{}, logsapi.LoggingBetaOptions); err != nil {\n\t\tpanic(err)\n\t}\n}","line":{"from":24,"to":29}} {"id":100030283,"name":"Init","signature":"func Init(fs *flag.FlagSet)","file":"staging/src/k8s.io/component-base/logs/klogflags/klogflags.go","code":"// Init is a replacement for klog.InitFlags which only adds those flags\n// that are still supported for Kubernetes components (i.e. -v and -vmodule).\n// See\n// https://github.com/kubernetes/enhancements/tree/master/keps/sig-instrumentation/2845-deprecate-klog-specific-flags-in-k8s-components.\nfunc Init(fs *flag.FlagSet) {\n\tvar allFlags flag.FlagSet\n\tklog.InitFlags(\u0026allFlags)\n\tif fs == nil {\n\t\tfs = flag.CommandLine\n\t}\n\tallFlags.VisitAll(func(f *flag.Flag) {\n\t\tswitch f.Name {\n\t\tcase \"v\", \"vmodule\":\n\t\t\tfs.Var(f.Value, f.Name, f.Usage)\n\t\t}\n\t})\n}","line":{"from":25,"to":41}} {"id":100030284,"name":"main","signature":"func main()","file":"staging/src/k8s.io/component-base/logs/kube-log-runner/kube-log-runner.go","code":"func main() {\n\tflag.Parse()\n\n\tif err := configureAndRun(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","line":{"from":37,"to":43}} {"id":100030285,"name":"configureAndRun","signature":"func configureAndRun() error","file":"staging/src/k8s.io/component-base/logs/kube-log-runner/kube-log-runner.go","code":"func configureAndRun() error {\n\tvar (\n\t\toutputStream io.Writer = os.Stdout\n\t\terrStream io.Writer = os.Stderr\n\t)\n\n\targs := flag.Args()\n\tif len(args) == 0 {\n\t\treturn fmt.Errorf(\"not enough arguments to run\")\n\t}\n\n\tif logFilePath != nil \u0026\u0026 *logFilePath != \"\" {\n\t\tlogFile, err := os.OpenFile(*logFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create log file %v: %w\", *logFilePath, err)\n\t\t}\n\t\tif *alsoToStdOut {\n\t\t\toutputStream = io.MultiWriter(os.Stdout, logFile)\n\t\t} else {\n\t\t\toutputStream = logFile\n\t\t}\n\t}\n\n\tif *redirectStderr {\n\t\terrStream = outputStream\n\t}\n\n\texe := args[0]\n\tvar exeArgs []string\n\tif len(args) \u003e 1 {\n\t\texeArgs = args[1:]\n\t}\n\tcmd := exec.Command(exe, exeArgs...)\n\tcmd.Stdout = outputStream\n\tcmd.Stderr = errStream\n\n\tlog.Printf(\"Running command:\\n%v\", cmdInfo(cmd))\n\terr := cmd.Start()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"starting command: %w\", err)\n\t}\n\n\t// Handle signals and shutdown process gracefully.\n\tgo setupSigHandler(cmd.Process)\n\tif err := cmd.Wait(); err != nil {\n\t\treturn fmt.Errorf(\"running command: %w\", err)\n\t}\n\treturn nil\n}","line":{"from":45,"to":93}} {"id":100030286,"name":"cmdInfo","signature":"func cmdInfo(cmd *exec.Cmd) string","file":"staging/src/k8s.io/component-base/logs/kube-log-runner/kube-log-runner.go","code":"// cmdInfo generates a useful look at what the command is for printing/debug.\nfunc cmdInfo(cmd *exec.Cmd) string {\n\treturn fmt.Sprintf(\n\t\t`Command env: (log-file=%v, also-stdout=%v, redirect-stderr=%v)\nRun from directory: %v\nExecutable path: %v\nArgs (comma-delimited): %v`, *logFilePath, *alsoToStdOut, *redirectStderr,\n\t\tcmd.Dir, cmd.Path, strings.Join(cmd.Args, \",\"),\n\t)\n}","line":{"from":95,"to":104}} {"id":100030287,"name":"setupSigHandler","signature":"func setupSigHandler(process *os.Process)","file":"staging/src/k8s.io/component-base/logs/kube-log-runner/kube-log-runner.go","code":"// setupSigHandler will forward any termination signals to the process\nfunc setupSigHandler(process *os.Process) {\n\t// terminationSignals are signals that cause the program to exit in the\n\t// supported platforms (linux, darwin, windows).\n\tterminationSignals := []os.Signal{syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT}\n\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, terminationSignals...)\n\n\t// Block until a signal is received.\n\tlog.Println(\"Now listening for interrupts\")\n\ts := \u003c-c\n\tlog.Printf(\"Got signal: %v. Sending down to process (PID: %v)\", s, process.Pid)\n\tif err := process.Signal(s); err != nil {\n\t\tlog.Fatalf(\"Failed to signal process: %v\", err)\n\t}\n\tlog.Printf(\"Signalled process %v successfully.\", process.Pid)\n}","line":{"from":106,"to":123}} {"id":100030288,"name":"NewLogReduction","signature":"func NewLogReduction(identicalErrorDelay time.Duration) *LogReduction","file":"staging/src/k8s.io/component-base/logs/logreduction/logreduction.go","code":"// NewLogReduction returns an initialized LogReduction\nfunc NewLogReduction(identicalErrorDelay time.Duration) *LogReduction {\n\tl := new(LogReduction)\n\tl.lastError = make(map[string]string)\n\tl.errorPrinted = make(map[string]time.Time)\n\tl.identicalErrorDelay = identicalErrorDelay\n\treturn l\n}","line":{"from":37,"to":44}} {"id":100030289,"name":"cleanupErrorTimeouts","signature":"func (l *LogReduction) cleanupErrorTimeouts()","file":"staging/src/k8s.io/component-base/logs/logreduction/logreduction.go","code":"func (l *LogReduction) cleanupErrorTimeouts() {\n\tfor name, timeout := range l.errorPrinted {\n\t\tif nowfunc().Sub(timeout) \u003e= l.identicalErrorDelay {\n\t\t\tdelete(l.errorPrinted, name)\n\t\t\tdelete(l.lastError, name)\n\t\t}\n\t}\n}","line":{"from":46,"to":53}} {"id":100030290,"name":"ShouldMessageBePrinted","signature":"func (l *LogReduction) ShouldMessageBePrinted(message string, parentID string) bool","file":"staging/src/k8s.io/component-base/logs/logreduction/logreduction.go","code":"// ShouldMessageBePrinted determines whether a message should be printed based\n// on how long ago this particular message was last printed\nfunc (l *LogReduction) ShouldMessageBePrinted(message string, parentID string) bool {\n\tl.errorMapLock.Lock()\n\tdefer l.errorMapLock.Unlock()\n\tl.cleanupErrorTimeouts()\n\tlastMsg, ok := l.lastError[parentID]\n\tlastPrinted, ok1 := l.errorPrinted[parentID]\n\tif !ok || !ok1 || message != lastMsg || nowfunc().Sub(lastPrinted) \u003e= l.identicalErrorDelay {\n\t\tl.errorPrinted[parentID] = nowfunc()\n\t\tl.lastError[parentID] = message\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":55,"to":69}} {"id":100030291,"name":"ClearID","signature":"func (l *LogReduction) ClearID(parentID string)","file":"staging/src/k8s.io/component-base/logs/logreduction/logreduction.go","code":"// ClearID clears out log reduction records pertaining to a particular parent\n// (e. g. container ID)\nfunc (l *LogReduction) ClearID(parentID string) {\n\tl.errorMapLock.Lock()\n\tdefer l.errorMapLock.Unlock()\n\tdelete(l.lastError, parentID)\n\tdelete(l.errorPrinted, parentID)\n}","line":{"from":71,"to":78}} {"id":100030292,"name":"init","signature":"func init()","file":"staging/src/k8s.io/component-base/logs/logs.go","code":"func init() {\n\tklogflags.Init(packageFlags)\n\tpackageFlags.DurationVar(\u0026logFlushFreq, logsapi.LogFlushFreqFlagName, logsapi.LogFlushFreqDefault, \"Maximum number of seconds between log flushes\")\n}","line":{"from":46,"to":49}} {"id":100030293,"name":"SkipLoggingConfigurationFlags","signature":"func SkipLoggingConfigurationFlags() Option","file":"staging/src/k8s.io/component-base/logs/logs.go","code":"// SkipLoggingConfigurationFlags must be used as option for AddFlags when\n// the program also uses a LoggingConfiguration struct for configuring\n// logging. Then only flags not covered by that get added.\nfunc SkipLoggingConfigurationFlags() Option {\n\treturn func(o *addFlagsOptions) {\n\t\to.skipLoggingConfigurationFlags = true\n\t}\n}","line":{"from":57,"to":64}} {"id":100030294,"name":"AddFlags","signature":"func AddFlags(fs *pflag.FlagSet, opts ...Option)","file":"staging/src/k8s.io/component-base/logs/logs.go","code":"// AddFlags registers this package's flags on arbitrary FlagSets. This includes\n// the klog flags, with the original underscore as separator between. If\n// commands want hyphens as separators, they can set\n// k8s.io/component-base/cli/flag/WordSepNormalizeFunc as normalization\n// function on the flag set before calling AddFlags.\n//\n// May be called more than once.\nfunc AddFlags(fs *pflag.FlagSet, opts ...Option) {\n\to := addFlagsOptions{}\n\tfor _, opt := range opts {\n\t\topt(\u0026o)\n\t}\n\n\t// Add all supported flags.\n\tpackageFlags.VisitAll(func(f *flag.Flag) {\n\t\tpf := pflag.PFlagFromGoFlag(f)\n\t\tswitch f.Name {\n\t\tcase \"v\", logsapi.LogFlushFreqFlagName:\n\t\t\t// unchanged, potentially skip it\n\t\t\tif o.skipLoggingConfigurationFlags {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase \"vmodule\":\n\t\t\tif o.skipLoggingConfigurationFlags {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpf.Usage += vmoduleUsage\n\t\t}\n\t\tif fs.Lookup(pf.Name) == nil {\n\t\t\tfs.AddFlag(pf)\n\t\t}\n\t})\n}","line":{"from":73,"to":105}} {"id":100030295,"name":"AddGoFlags","signature":"func AddGoFlags(fs *flag.FlagSet, opts ...Option)","file":"staging/src/k8s.io/component-base/logs/logs.go","code":"// AddGoFlags is a variant of AddFlags for traditional Go flag.FlagSet.\n// Commands should use pflag whenever possible for the sake of consistency.\n// Cases where this function is needed include tests (they have to set up flags\n// in flag.CommandLine) and commands that for historic reasons use Go\n// flag.Parse and cannot change to pflag because it would break their command\n// line interface.\nfunc AddGoFlags(fs *flag.FlagSet, opts ...Option) {\n\to := addFlagsOptions{}\n\tfor _, opt := range opts {\n\t\topt(\u0026o)\n\t}\n\n\t// Add flags with deprecation remark added to the usage text of\n\t// some klog flags.\n\tpackageFlags.VisitAll(func(f *flag.Flag) {\n\t\tusage := f.Usage\n\t\tswitch f.Name {\n\t\tcase \"v\", logsapi.LogFlushFreqFlagName:\n\t\t\t// unchanged\n\t\t\tif o.skipLoggingConfigurationFlags {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase \"vmodule\":\n\t\t\tif o.skipLoggingConfigurationFlags {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tusage += vmoduleUsage\n\t\t}\n\t\tfs.Var(f.Value, f.Name, usage)\n\t})\n}","line":{"from":107,"to":137}} {"id":100030296,"name":"Write","signature":"func (writer KlogWriter) Write(data []byte) (n int, err error)","file":"staging/src/k8s.io/component-base/logs/logs.go","code":"// Write implements the io.Writer interface.\nfunc (writer KlogWriter) Write(data []byte) (n int, err error) {\n\tklog.InfoDepth(1, string(data))\n\treturn len(data), nil\n}","line":{"from":142,"to":146}} {"id":100030297,"name":"InitLogs","signature":"func InitLogs()","file":"staging/src/k8s.io/component-base/logs/logs.go","code":"// InitLogs initializes logs the way we want for Kubernetes.\n// It should be called after parsing flags. If called before that,\n// it will use the default log settings.\n//\n// InitLogs disables support for contextual logging in klog while\n// that Kubernetes feature is not considered stable yet. Commands\n// which want to support contextual logging can:\n// - call klog.EnableContextualLogging after calling InitLogs,\n// with a fixed `true` or depending on some command line flag or\n// a feature gate check\n// - set up a FeatureGate instance, the advanced logging configuration\n// with Options and call Options.ValidateAndApply with the FeatureGate;\n// k8s.io/component-base/logs/example/cmd demonstrates how to do that\nfunc InitLogs() {\n\tlog.SetOutput(KlogWriter{})\n\tlog.SetFlags(0)\n\n\t// Start flushing now. If LoggingConfiguration.ApplyAndValidate is\n\t// used, it will restart the daemon with the log flush interval defined\n\t// there.\n\tklog.StartFlushDaemon(logFlushFreq)\n\n\t// This is the default in Kubernetes. Options.ValidateAndApply\n\t// will override this with the result of a feature gate check.\n\tklog.EnableContextualLogging(false)\n}","line":{"from":148,"to":173}} {"id":100030298,"name":"FlushLogs","signature":"func FlushLogs()","file":"staging/src/k8s.io/component-base/logs/logs.go","code":"// FlushLogs flushes logs immediately. This should be called at the end of\n// the main function via defer to ensure that all pending log messages\n// are printed before exiting the program.\nfunc FlushLogs() {\n\tklog.Flush()\n}","line":{"from":175,"to":180}} {"id":100030299,"name":"NewLogger","signature":"func NewLogger(prefix string) *log.Logger","file":"staging/src/k8s.io/component-base/logs/logs.go","code":"// NewLogger creates a new log.Logger which sends logs to klog.Info.\nfunc NewLogger(prefix string) *log.Logger {\n\treturn log.New(KlogWriter{}, prefix, 0)\n}","line":{"from":182,"to":185}} {"id":100030300,"name":"GlogSetter","signature":"func GlogSetter(val string) (string, error)","file":"staging/src/k8s.io/component-base/logs/logs.go","code":"// GlogSetter modifies the verbosity threshold for the entire program.\n// Some components have HTTP-based APIs for invoking this at runtime.\nfunc GlogSetter(val string) (string, error) {\n\tv, err := strconv.ParseUint(val, 10, 32)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar level klog.Level\n\tif err := level.Set(val); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed set klog.logging.verbosity %s: %v\", val, err)\n\t}\n\n\tsetverbositylevel.Mutex.Lock()\n\tdefer setverbositylevel.Mutex.Unlock()\n\tfor _, cb := range setverbositylevel.Callbacks {\n\t\tif err := cb(uint32(v)); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\treturn fmt.Sprintf(\"successfully set klog.logging.verbosity to %s\", val), nil\n}","line":{"from":187,"to":209}} {"id":100030301,"name":"LinearBuckets","signature":"func LinearBuckets(start, width float64, count int) []float64","file":"staging/src/k8s.io/component-base/metrics/buckets.go","code":"// LinearBuckets is a wrapper for prometheus.LinearBuckets.\nfunc LinearBuckets(start, width float64, count int) []float64 {\n\treturn prometheus.LinearBuckets(start, width, count)\n}","line":{"from":26,"to":29}} {"id":100030302,"name":"ExponentialBuckets","signature":"func ExponentialBuckets(start, factor float64, count int) []float64","file":"staging/src/k8s.io/component-base/metrics/buckets.go","code":"// ExponentialBuckets is a wrapper for prometheus.ExponentialBuckets.\nfunc ExponentialBuckets(start, factor float64, count int) []float64 {\n\treturn prometheus.ExponentialBuckets(start, factor, count)\n}","line":{"from":31,"to":34}} {"id":100030303,"name":"MergeBuckets","signature":"func MergeBuckets(buckets ...[]float64) []float64","file":"staging/src/k8s.io/component-base/metrics/buckets.go","code":"// MergeBuckets merges buckets together\nfunc MergeBuckets(buckets ...[]float64) []float64 {\n\tresult := make([]float64, 1)\n\tfor _, s := range buckets {\n\t\tresult = append(result, s...)\n\t}\n\treturn result\n}","line":{"from":36,"to":43}} {"id":100030304,"name":"DescribeWithStability","signature":"func (bsc *BaseStableCollector) DescribeWithStability(ch chan\u003c- *Desc)","file":"staging/src/k8s.io/component-base/metrics/collector.go","code":"// DescribeWithStability sends all descriptors to the provided channel.\n// Every custom collector should over-write this method.\nfunc (bsc *BaseStableCollector) DescribeWithStability(ch chan\u003c- *Desc) {\n\tpanic(fmt.Errorf(\"custom collector should over-write DescribeWithStability method\"))\n}","line":{"from":58,"to":62}} {"id":100030305,"name":"Describe","signature":"func (bsc *BaseStableCollector) Describe(ch chan\u003c- *prometheus.Desc)","file":"staging/src/k8s.io/component-base/metrics/collector.go","code":"// Describe sends all descriptors to the provided channel.\n// It intended to be called by prometheus registry.\nfunc (bsc *BaseStableCollector) Describe(ch chan\u003c- *prometheus.Desc) {\n\tfor _, d := range bsc.registerable {\n\t\tch \u003c- d.toPrometheusDesc()\n\t}\n}","line":{"from":64,"to":70}} {"id":100030306,"name":"CollectWithStability","signature":"func (bsc *BaseStableCollector) CollectWithStability(ch chan\u003c- Metric)","file":"staging/src/k8s.io/component-base/metrics/collector.go","code":"// CollectWithStability sends all metrics to the provided channel.\n// Every custom collector should over-write this method.\nfunc (bsc *BaseStableCollector) CollectWithStability(ch chan\u003c- Metric) {\n\tpanic(fmt.Errorf(\"custom collector should over-write CollectWithStability method\"))\n}","line":{"from":72,"to":76}} {"id":100030307,"name":"Collect","signature":"func (bsc *BaseStableCollector) Collect(ch chan\u003c- prometheus.Metric)","file":"staging/src/k8s.io/component-base/metrics/collector.go","code":"// Collect is called by the Prometheus registry when collecting metrics.\nfunc (bsc *BaseStableCollector) Collect(ch chan\u003c- prometheus.Metric) {\n\tmch := make(chan Metric)\n\n\tgo func() {\n\t\tbsc.self.CollectWithStability(mch)\n\t\tclose(mch)\n\t}()\n\n\tfor m := range mch {\n\t\t// nil Metric usually means hidden metrics\n\t\tif m == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tch \u003c- prometheus.Metric(m)\n\t}\n}","line":{"from":78,"to":95}} {"id":100030308,"name":"add","signature":"func (bsc *BaseStableCollector) add(d *Desc)","file":"staging/src/k8s.io/component-base/metrics/collector.go","code":"func (bsc *BaseStableCollector) add(d *Desc) {\n\tif len(d.fqName) == 0 {\n\t\tpanic(\"nameless metrics will be not allowed\")\n\t}\n\n\tif bsc.descriptors == nil {\n\t\tbsc.descriptors = make(map[string]*Desc)\n\t}\n\n\tif _, exist := bsc.descriptors[d.fqName]; exist {\n\t\tpanic(fmt.Sprintf(\"duplicate metrics (%s) will be not allowed\", d.fqName))\n\t}\n\n\tbsc.descriptors[d.fqName] = d\n}","line":{"from":97,"to":111}} {"id":100030309,"name":"init","signature":"func (bsc *BaseStableCollector) init(self StableCollector)","file":"staging/src/k8s.io/component-base/metrics/collector.go","code":"// Init intends to be called by registry.\nfunc (bsc *BaseStableCollector) init(self StableCollector) {\n\tbsc.self = self\n\n\tdch := make(chan *Desc)\n\n\t// collect all possible descriptions from custom side\n\tgo func() {\n\t\tbsc.self.DescribeWithStability(dch)\n\t\tclose(dch)\n\t}()\n\n\tfor d := range dch {\n\t\tbsc.add(d)\n\t}\n}","line":{"from":113,"to":128}} {"id":100030310,"name":"trackRegistrableDescriptor","signature":"func (bsc *BaseStableCollector) trackRegistrableDescriptor(d *Desc)","file":"staging/src/k8s.io/component-base/metrics/collector.go","code":"func (bsc *BaseStableCollector) trackRegistrableDescriptor(d *Desc) {\n\tif bsc.registerable == nil {\n\t\tbsc.registerable = make(map[string]*Desc)\n\t}\n\n\tbsc.registerable[d.fqName] = d\n}","line":{"from":130,"to":136}} {"id":100030311,"name":"trackHiddenDescriptor","signature":"func (bsc *BaseStableCollector) trackHiddenDescriptor(d *Desc)","file":"staging/src/k8s.io/component-base/metrics/collector.go","code":"func (bsc *BaseStableCollector) trackHiddenDescriptor(d *Desc) {\n\tif bsc.hidden == nil {\n\t\tbsc.hidden = make(map[string]*Desc)\n\t}\n\n\tbsc.hidden[d.fqName] = d\n}","line":{"from":138,"to":144}} {"id":100030312,"name":"Create","signature":"func (bsc *BaseStableCollector) Create(version *semver.Version, self StableCollector) bool","file":"staging/src/k8s.io/component-base/metrics/collector.go","code":"// Create intends to be called by registry.\n// Create will return true as long as there is one or more metrics not be hidden.\n// Otherwise return false, that means the whole collector will be ignored by registry.\nfunc (bsc *BaseStableCollector) Create(version *semver.Version, self StableCollector) bool {\n\tbsc.init(self)\n\n\tfor _, d := range bsc.descriptors {\n\t\td.create(version)\n\t\tif d.IsHidden() {\n\t\t\tbsc.trackHiddenDescriptor(d)\n\t\t} else {\n\t\t\tbsc.trackRegistrableDescriptor(d)\n\t\t}\n\t}\n\n\tif len(bsc.registerable) \u003e 0 {\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":146,"to":166}} {"id":100030313,"name":"ClearState","signature":"func (bsc *BaseStableCollector) ClearState()","file":"staging/src/k8s.io/component-base/metrics/collector.go","code":"// ClearState will clear all the states marked by Create.\n// It intends to be used for re-register a hidden metric.\nfunc (bsc *BaseStableCollector) ClearState() {\n\tfor _, d := range bsc.descriptors {\n\t\td.ClearState()\n\t}\n\n\tbsc.descriptors = nil\n\tbsc.registerable = nil\n\tbsc.hidden = nil\n\tbsc.self = nil\n}","line":{"from":168,"to":179}} {"id":100030314,"name":"HiddenMetrics","signature":"func (bsc *BaseStableCollector) HiddenMetrics() (fqNames []string)","file":"staging/src/k8s.io/component-base/metrics/collector.go","code":"// HiddenMetrics tells the list of hidden metrics with fqName.\nfunc (bsc *BaseStableCollector) HiddenMetrics() (fqNames []string) {\n\tfor i := range bsc.hidden {\n\t\tfqNames = append(fqNames, bsc.hidden[i].fqName)\n\t}\n\treturn\n}","line":{"from":181,"to":187}} {"id":100030315,"name":"NewCounter","signature":"func NewCounter(opts *CounterOpts) *Counter","file":"staging/src/k8s.io/component-base/metrics/counter.go","code":"// NewCounter returns an object which satisfies the kubeCollector and CounterMetric interfaces.\n// However, the object returned will not measure anything unless the collector is first\n// registered, since the metric is lazily instantiated.\nfunc NewCounter(opts *CounterOpts) *Counter {\n\topts.StabilityLevel.setDefaults()\n\n\tkc := \u0026Counter{\n\t\tCounterOpts: opts,\n\t\tlazyMetric: lazyMetric{stabilityLevel: opts.StabilityLevel},\n\t}\n\tkc.setPrometheusCounter(noop)\n\tkc.lazyInit(kc, BuildFQName(opts.Namespace, opts.Subsystem, opts.Name))\n\treturn kc\n}","line":{"from":39,"to":52}} {"id":100030316,"name":"Desc","signature":"func (c *Counter) Desc() *prometheus.Desc","file":"staging/src/k8s.io/component-base/metrics/counter.go","code":"func (c *Counter) Desc() *prometheus.Desc {\n\treturn c.metric.Desc()\n}","line":{"from":54,"to":56}} {"id":100030317,"name":"Write","signature":"func (c *Counter) Write(to *dto.Metric) error","file":"staging/src/k8s.io/component-base/metrics/counter.go","code":"func (c *Counter) Write(to *dto.Metric) error {\n\treturn c.metric.Write(to)\n}","line":{"from":58,"to":60}} {"id":100030318,"name":"Reset","signature":"func (c *Counter) Reset()","file":"staging/src/k8s.io/component-base/metrics/counter.go","code":"// Reset resets the underlying prometheus Counter to start counting from 0 again\nfunc (c *Counter) Reset() {\n\tif !c.IsCreated() {\n\t\treturn\n\t}\n\tc.setPrometheusCounter(prometheus.NewCounter(c.CounterOpts.toPromCounterOpts()))\n}","line":{"from":62,"to":68}} {"id":100030319,"name":"setPrometheusCounter","signature":"func (c *Counter) setPrometheusCounter(counter prometheus.Counter)","file":"staging/src/k8s.io/component-base/metrics/counter.go","code":"// setPrometheusCounter sets the underlying CounterMetric object, i.e. the thing that does the measurement.\nfunc (c *Counter) setPrometheusCounter(counter prometheus.Counter) {\n\tc.CounterMetric = counter\n\tc.initSelfCollection(counter)\n}","line":{"from":70,"to":74}} {"id":100030320,"name":"DeprecatedVersion","signature":"func (c *Counter) DeprecatedVersion() *semver.Version","file":"staging/src/k8s.io/component-base/metrics/counter.go","code":"// DeprecatedVersion returns a pointer to the Version or nil\nfunc (c *Counter) DeprecatedVersion() *semver.Version {\n\treturn parseSemver(c.CounterOpts.DeprecatedVersion)\n}","line":{"from":76,"to":79}} {"id":100030321,"name":"initializeMetric","signature":"func (c *Counter) initializeMetric()","file":"staging/src/k8s.io/component-base/metrics/counter.go","code":"// initializeMetric invocation creates the actual underlying Counter. Until this method is called\n// the underlying counter is a no-op.\nfunc (c *Counter) initializeMetric() {\n\tc.CounterOpts.annotateStabilityLevel()\n\t// this actually creates the underlying prometheus counter.\n\tc.setPrometheusCounter(prometheus.NewCounter(c.CounterOpts.toPromCounterOpts()))\n}","line":{"from":81,"to":87}} {"id":100030322,"name":"initializeDeprecatedMetric","signature":"func (c *Counter) initializeDeprecatedMetric()","file":"staging/src/k8s.io/component-base/metrics/counter.go","code":"// initializeDeprecatedMetric invocation creates the actual (but deprecated) Counter. Until this method\n// is called the underlying counter is a no-op.\nfunc (c *Counter) initializeDeprecatedMetric() {\n\tc.CounterOpts.markDeprecated()\n\tc.initializeMetric()\n}","line":{"from":89,"to":94}} {"id":100030323,"name":"WithContext","signature":"func (c *Counter) WithContext(ctx context.Context) CounterMetric","file":"staging/src/k8s.io/component-base/metrics/counter.go","code":"// WithContext allows the normal Counter metric to pass in context. The context is no-op now.\nfunc (c *Counter) WithContext(ctx context.Context) CounterMetric {\n\treturn c.CounterMetric\n}","line":{"from":96,"to":99}} {"id":100030324,"name":"NewCounterVec","signature":"func NewCounterVec(opts *CounterOpts, labels []string) *CounterVec","file":"staging/src/k8s.io/component-base/metrics/counter.go","code":"// NewCounterVec returns an object which satisfies the kubeCollector and (almost) CounterVecMetric interfaces.\n// However, the object returned will not measure anything unless the collector is first\n// registered, since the metric is lazily instantiated, and only members extracted after\n// registration will actually measure anything.\nfunc NewCounterVec(opts *CounterOpts, labels []string) *CounterVec {\n\topts.StabilityLevel.setDefaults()\n\n\tfqName := BuildFQName(opts.Namespace, opts.Subsystem, opts.Name)\n\tallowListLock.RLock()\n\tif allowList, ok := labelValueAllowLists[fqName]; ok {\n\t\topts.LabelValueAllowLists = allowList\n\t}\n\tallowListLock.RUnlock()\n\n\tcv := \u0026CounterVec{\n\t\tCounterVec: noopCounterVec,\n\t\tCounterOpts: opts,\n\t\toriginalLabels: labels,\n\t\tlazyMetric: lazyMetric{stabilityLevel: opts.StabilityLevel},\n\t}\n\tcv.lazyInit(cv, fqName)\n\treturn cv\n}","line":{"from":114,"to":136}} {"id":100030325,"name":"DeprecatedVersion","signature":"func (v *CounterVec) DeprecatedVersion() *semver.Version","file":"staging/src/k8s.io/component-base/metrics/counter.go","code":"// DeprecatedVersion returns a pointer to the Version or nil\nfunc (v *CounterVec) DeprecatedVersion() *semver.Version {\n\treturn parseSemver(v.CounterOpts.DeprecatedVersion)\n\n}","line":{"from":138,"to":142}} {"id":100030326,"name":"initializeMetric","signature":"func (v *CounterVec) initializeMetric()","file":"staging/src/k8s.io/component-base/metrics/counter.go","code":"// initializeMetric invocation creates the actual underlying CounterVec. Until this method is called\n// the underlying counterVec is a no-op.\nfunc (v *CounterVec) initializeMetric() {\n\tv.CounterOpts.annotateStabilityLevel()\n\tv.CounterVec = prometheus.NewCounterVec(v.CounterOpts.toPromCounterOpts(), v.originalLabels)\n}","line":{"from":144,"to":149}} {"id":100030327,"name":"initializeDeprecatedMetric","signature":"func (v *CounterVec) initializeDeprecatedMetric()","file":"staging/src/k8s.io/component-base/metrics/counter.go","code":"// initializeDeprecatedMetric invocation creates the actual (but deprecated) CounterVec. Until this method is called\n// the underlying counterVec is a no-op.\nfunc (v *CounterVec) initializeDeprecatedMetric() {\n\tv.CounterOpts.markDeprecated()\n\tv.initializeMetric()\n}","line":{"from":151,"to":156}} {"id":100030328,"name":"WithLabelValues","signature":"func (v *CounterVec) WithLabelValues(lvs ...string) CounterMetric","file":"staging/src/k8s.io/component-base/metrics/counter.go","code":"// WithLabelValues returns the Counter for the given slice of label\n// values (same order as the VariableLabels in Desc). If that combination of\n// label values is accessed for the first time, a new Counter is created IFF the counterVec\n// has been registered to a metrics registry.\nfunc (v *CounterVec) WithLabelValues(lvs ...string) CounterMetric {\n\tif !v.IsCreated() {\n\t\treturn noop // return no-op counter\n\t}\n\tif v.LabelValueAllowLists != nil {\n\t\tv.LabelValueAllowLists.ConstrainToAllowedList(v.originalLabels, lvs)\n\t}\n\treturn v.CounterVec.WithLabelValues(lvs...)\n}","line":{"from":169,"to":181}} {"id":100030329,"name":"With","signature":"func (v *CounterVec) With(labels map[string]string) CounterMetric","file":"staging/src/k8s.io/component-base/metrics/counter.go","code":"// With returns the Counter for the given Labels map (the label names\n// must match those of the VariableLabels in Desc). If that label map is\n// accessed for the first time, a new Counter is created IFF the counterVec has\n// been registered to a metrics registry.\nfunc (v *CounterVec) With(labels map[string]string) CounterMetric {\n\tif !v.IsCreated() {\n\t\treturn noop // return no-op counter\n\t}\n\tif v.LabelValueAllowLists != nil {\n\t\tv.LabelValueAllowLists.ConstrainLabelMap(labels)\n\t}\n\treturn v.CounterVec.With(labels)\n}","line":{"from":183,"to":195}} {"id":100030330,"name":"Delete","signature":"func (v *CounterVec) Delete(labels map[string]string) bool","file":"staging/src/k8s.io/component-base/metrics/counter.go","code":"// Delete deletes the metric where the variable labels are the same as those\n// passed in as labels. It returns true if a metric was deleted.\n//\n// It is not an error if the number and names of the Labels are inconsistent\n// with those of the VariableLabels in Desc. However, such inconsistent Labels\n// can never match an actual metric, so the method will always return false in\n// that case.\nfunc (v *CounterVec) Delete(labels map[string]string) bool {\n\tif !v.IsCreated() {\n\t\treturn false // since we haven't created the metric, we haven't deleted a metric with the passed in values\n\t}\n\treturn v.CounterVec.Delete(labels)\n}","line":{"from":197,"to":209}} {"id":100030331,"name":"Reset","signature":"func (v *CounterVec) Reset()","file":"staging/src/k8s.io/component-base/metrics/counter.go","code":"// Reset deletes all metrics in this vector.\nfunc (v *CounterVec) Reset() {\n\tif !v.IsCreated() {\n\t\treturn\n\t}\n\n\tv.CounterVec.Reset()\n}","line":{"from":211,"to":218}} {"id":100030332,"name":"WithContext","signature":"func (v *CounterVec) WithContext(ctx context.Context) *CounterVecWithContext","file":"staging/src/k8s.io/component-base/metrics/counter.go","code":"// WithContext returns wrapped CounterVec with context\nfunc (v *CounterVec) WithContext(ctx context.Context) *CounterVecWithContext {\n\treturn \u0026CounterVecWithContext{\n\t\tctx: ctx,\n\t\tCounterVec: v,\n\t}\n}","line":{"from":220,"to":226}} {"id":100030333,"name":"WithLabelValues","signature":"func (vc *CounterVecWithContext) WithLabelValues(lvs ...string) CounterMetric","file":"staging/src/k8s.io/component-base/metrics/counter.go","code":"// WithLabelValues is the wrapper of CounterVec.WithLabelValues.\nfunc (vc *CounterVecWithContext) WithLabelValues(lvs ...string) CounterMetric {\n\treturn vc.CounterVec.WithLabelValues(lvs...)\n}","line":{"from":234,"to":237}} {"id":100030334,"name":"With","signature":"func (vc *CounterVecWithContext) With(labels map[string]string) CounterMetric","file":"staging/src/k8s.io/component-base/metrics/counter.go","code":"// With is the wrapper of CounterVec.With.\nfunc (vc *CounterVecWithContext) With(labels map[string]string) CounterMetric {\n\treturn vc.CounterVec.With(labels)\n}","line":{"from":239,"to":242}} {"id":100030335,"name":"NewDesc","signature":"func NewDesc(fqName string, help string, variableLabels []string, constLabels Labels,","file":"staging/src/k8s.io/component-base/metrics/desc.go","code":"// NewDesc extends prometheus.NewDesc with stability support.\n//\n// The stabilityLevel should be valid stability label, such as \"metrics.ALPHA\"\n// and \"metrics.STABLE\"(Maybe \"metrics.BETA\" in future). Default value \"metrics.ALPHA\"\n// will be used in case of empty or invalid stability label.\n//\n// The deprecatedVersion represents in which version this Metric be deprecated.\n// The deprecation policy outlined by the control plane metrics stability KEP.\nfunc NewDesc(fqName string, help string, variableLabels []string, constLabels Labels,\n\tstabilityLevel StabilityLevel, deprecatedVersion string) *Desc {\n\td := \u0026Desc{\n\t\tfqName: fqName,\n\t\thelp: help,\n\t\tannotatedHelp: help,\n\t\tvariableLabels: variableLabels,\n\t\tconstLabels: constLabels,\n\t\tstabilityLevel: stabilityLevel,\n\t\tdeprecatedVersion: deprecatedVersion,\n\t}\n\td.stabilityLevel.setDefaults()\n\n\treturn d\n}","line":{"from":63,"to":85}} {"id":100030336,"name":"String","signature":"func (d *Desc) String() string","file":"staging/src/k8s.io/component-base/metrics/desc.go","code":"// String formats the Desc as a string.\n// The stability metadata maybe annotated in 'HELP' section if called after registry,\n// otherwise not.\n// e.g. \"Desc{fqName: \"normal_stable_descriptor\", help: \"[STABLE] this is a stable descriptor\", constLabels: {}, variableLabels: []}\"\nfunc (d *Desc) String() string {\n\tif d.isCreated {\n\t\treturn d.promDesc.String()\n\t}\n\n\treturn prometheus.NewDesc(d.fqName, d.help, d.variableLabels, prometheus.Labels(d.constLabels)).String()\n}","line":{"from":87,"to":97}} {"id":100030337,"name":"toPrometheusDesc","signature":"func (d *Desc) toPrometheusDesc() *prometheus.Desc","file":"staging/src/k8s.io/component-base/metrics/desc.go","code":"// toPrometheusDesc transform self to prometheus.Desc\nfunc (d *Desc) toPrometheusDesc() *prometheus.Desc {\n\treturn d.promDesc\n}","line":{"from":99,"to":102}} {"id":100030338,"name":"DeprecatedVersion","signature":"func (d *Desc) DeprecatedVersion() *semver.Version","file":"staging/src/k8s.io/component-base/metrics/desc.go","code":"// DeprecatedVersion returns a pointer to the Version or nil\nfunc (d *Desc) DeprecatedVersion() *semver.Version {\n\treturn parseSemver(d.deprecatedVersion)\n\n}","line":{"from":104,"to":108}} {"id":100030339,"name":"determineDeprecationStatus","signature":"func (d *Desc) determineDeprecationStatus(version semver.Version)","file":"staging/src/k8s.io/component-base/metrics/desc.go","code":"func (d *Desc) determineDeprecationStatus(version semver.Version) {\n\tselfVersion := d.DeprecatedVersion()\n\tif selfVersion == nil {\n\t\treturn\n\t}\n\td.markDeprecationOnce.Do(func() {\n\t\tif selfVersion.LTE(version) {\n\t\t\td.isDeprecated = true\n\t\t}\n\t\tif ShouldShowHidden() {\n\t\t\tklog.Warningf(\"Hidden metrics(%s) have been manually overridden, showing this very deprecated metric.\", d.fqName)\n\t\t\treturn\n\t\t}\n\t\tif shouldHide(\u0026version, selfVersion) {\n\t\t\t// TODO(RainbowMango): Remove this log temporarily. https://github.com/kubernetes/kubernetes/issues/85369\n\t\t\t// klog.Warningf(\"This metric(%s) has been deprecated for more than one release, hiding.\", d.fqName)\n\t\t\td.isHidden = true\n\t\t}\n\t})\n}","line":{"from":110,"to":129}} {"id":100030340,"name":"IsHidden","signature":"func (d *Desc) IsHidden() bool","file":"staging/src/k8s.io/component-base/metrics/desc.go","code":"// IsHidden returns if metric will be hidden\nfunc (d *Desc) IsHidden() bool {\n\treturn d.isHidden\n}","line":{"from":131,"to":134}} {"id":100030341,"name":"IsDeprecated","signature":"func (d *Desc) IsDeprecated() bool","file":"staging/src/k8s.io/component-base/metrics/desc.go","code":"// IsDeprecated returns if metric has been deprecated\nfunc (d *Desc) IsDeprecated() bool {\n\treturn d.isDeprecated\n}","line":{"from":136,"to":139}} {"id":100030342,"name":"IsCreated","signature":"func (d *Desc) IsCreated() bool","file":"staging/src/k8s.io/component-base/metrics/desc.go","code":"// IsCreated returns if metric has been created.\nfunc (d *Desc) IsCreated() bool {\n\td.createLock.RLock()\n\tdefer d.createLock.RUnlock()\n\n\treturn d.isCreated\n}","line":{"from":141,"to":147}} {"id":100030343,"name":"create","signature":"func (d *Desc) create(version *semver.Version) bool","file":"staging/src/k8s.io/component-base/metrics/desc.go","code":"// create forces the initialization of Desc which has been deferred until\n// the point at which this method is invoked. This method will determine whether\n// the Desc is deprecated or hidden, no-opting if the Desc should be considered\n// hidden. Furthermore, this function no-opts and returns true if Desc is already\n// created.\nfunc (d *Desc) create(version *semver.Version) bool {\n\tif version != nil {\n\t\td.determineDeprecationStatus(*version)\n\t}\n\n\t// let's not create if this metric is slated to be hidden\n\tif d.IsHidden() {\n\t\treturn false\n\t}\n\td.createOnce.Do(func() {\n\t\td.createLock.Lock()\n\t\tdefer d.createLock.Unlock()\n\n\t\td.isCreated = true\n\t\tif d.IsDeprecated() {\n\t\t\td.initializeDeprecatedDesc()\n\t\t} else {\n\t\t\td.initialize()\n\t\t}\n\t})\n\treturn d.IsCreated()\n}","line":{"from":149,"to":175}} {"id":100030344,"name":"ClearState","signature":"func (d *Desc) ClearState()","file":"staging/src/k8s.io/component-base/metrics/desc.go","code":"// ClearState will clear all the states marked by Create.\n// It intends to be used for re-register a hidden metric.\nfunc (d *Desc) ClearState() {\n\td.isDeprecated = false\n\td.isHidden = false\n\td.isCreated = false\n\n\td.markDeprecationOnce = *new(sync.Once)\n\td.createOnce = *new(sync.Once)\n\td.deprecateOnce = *new(sync.Once)\n\td.hideOnce = *new(sync.Once)\n\td.annotateOnce = *new(sync.Once)\n\n\td.annotatedHelp = d.help\n\td.promDesc = nil\n}","line":{"from":177,"to":192}} {"id":100030345,"name":"markDeprecated","signature":"func (d *Desc) markDeprecated()","file":"staging/src/k8s.io/component-base/metrics/desc.go","code":"func (d *Desc) markDeprecated() {\n\td.deprecateOnce.Do(func() {\n\t\td.annotatedHelp = fmt.Sprintf(\"(Deprecated since %s) %s\", d.deprecatedVersion, d.annotatedHelp)\n\t})\n}","line":{"from":194,"to":198}} {"id":100030346,"name":"annotateStabilityLevel","signature":"func (d *Desc) annotateStabilityLevel()","file":"staging/src/k8s.io/component-base/metrics/desc.go","code":"func (d *Desc) annotateStabilityLevel() {\n\td.annotateOnce.Do(func() {\n\t\td.annotatedHelp = fmt.Sprintf(\"[%v] %v\", d.stabilityLevel, d.annotatedHelp)\n\t})\n}","line":{"from":200,"to":204}} {"id":100030347,"name":"initialize","signature":"func (d *Desc) initialize()","file":"staging/src/k8s.io/component-base/metrics/desc.go","code":"func (d *Desc) initialize() {\n\td.annotateStabilityLevel()\n\n\t// this actually creates the underlying prometheus desc.\n\td.promDesc = prometheus.NewDesc(d.fqName, d.annotatedHelp, d.variableLabels, prometheus.Labels(d.constLabels))\n}","line":{"from":206,"to":211}} {"id":100030348,"name":"initializeDeprecatedDesc","signature":"func (d *Desc) initializeDeprecatedDesc()","file":"staging/src/k8s.io/component-base/metrics/desc.go","code":"func (d *Desc) initializeDeprecatedDesc() {\n\td.markDeprecated()\n\td.initialize()\n}","line":{"from":213,"to":216}} {"id":100030349,"name":"GetRawDesc","signature":"func (d *Desc) GetRawDesc() *Desc","file":"staging/src/k8s.io/component-base/metrics/desc.go","code":"// GetRawDesc will returns a new *Desc with original parameters provided to NewDesc().\n//\n// It will be useful in testing scenario that the same Desc be registered to different registry.\n// 1. Desc `D` is registered to registry 'A' in TestA (Note: `D` maybe created)\n// 2. Desc `D` is registered to registry 'B' in TestB (Note: since 'D' has been created once, thus will be ignored by registry 'B')\nfunc (d *Desc) GetRawDesc() *Desc {\n\treturn NewDesc(d.fqName, d.help, d.variableLabels, d.constLabels, d.stabilityLevel, d.deprecatedVersion)\n}","line":{"from":218,"to":225}} {"id":100030350,"name":"featureGates","signature":"func featureGates() map[featuregate.Feature]featuregate.FeatureSpec","file":"staging/src/k8s.io/component-base/metrics/features/kube_features.go","code":"func featureGates() map[featuregate.Feature]featuregate.FeatureSpec {\n\treturn map[featuregate.Feature]featuregate.FeatureSpec{\n\t\tComponentSLIs: {Default: true, PreRelease: featuregate.Beta},\n\t}\n}","line":{"from":30,"to":34}} {"id":100030351,"name":"AddFeatureGates","signature":"func AddFeatureGates(mutableFeatureGate featuregate.MutableFeatureGate) error","file":"staging/src/k8s.io/component-base/metrics/features/kube_features.go","code":"// AddFeatureGates adds all feature gates used by this package.\nfunc AddFeatureGates(mutableFeatureGate featuregate.MutableFeatureGate) error {\n\treturn mutableFeatureGate.Add(featureGates())\n}","line":{"from":36,"to":39}} {"id":100030352,"name":"NewGauge","signature":"func NewGauge(opts *GaugeOpts) *Gauge","file":"staging/src/k8s.io/component-base/metrics/gauge.go","code":"// NewGauge returns an object which satisfies the kubeCollector, Registerable, and Gauge interfaces.\n// However, the object returned will not measure anything unless the collector is first\n// registered, since the metric is lazily instantiated.\nfunc NewGauge(opts *GaugeOpts) *Gauge {\n\topts.StabilityLevel.setDefaults()\n\n\tkc := \u0026Gauge{\n\t\tGaugeOpts: opts,\n\t\tlazyMetric: lazyMetric{stabilityLevel: opts.StabilityLevel},\n\t}\n\tkc.setPrometheusGauge(noop)\n\tkc.lazyInit(kc, BuildFQName(opts.Namespace, opts.Subsystem, opts.Name))\n\treturn kc\n}","line":{"from":41,"to":54}} {"id":100030353,"name":"setPrometheusGauge","signature":"func (g *Gauge) setPrometheusGauge(gauge prometheus.Gauge)","file":"staging/src/k8s.io/component-base/metrics/gauge.go","code":"// setPrometheusGauge sets the underlying KubeGauge object, i.e. the thing that does the measurement.\nfunc (g *Gauge) setPrometheusGauge(gauge prometheus.Gauge) {\n\tg.GaugeMetric = gauge\n\tg.initSelfCollection(gauge)\n}","line":{"from":56,"to":60}} {"id":100030354,"name":"DeprecatedVersion","signature":"func (g *Gauge) DeprecatedVersion() *semver.Version","file":"staging/src/k8s.io/component-base/metrics/gauge.go","code":"// DeprecatedVersion returns a pointer to the Version or nil\nfunc (g *Gauge) DeprecatedVersion() *semver.Version {\n\treturn parseSemver(g.GaugeOpts.DeprecatedVersion)\n}","line":{"from":62,"to":65}} {"id":100030355,"name":"initializeMetric","signature":"func (g *Gauge) initializeMetric()","file":"staging/src/k8s.io/component-base/metrics/gauge.go","code":"// initializeMetric invocation creates the actual underlying Gauge. Until this method is called\n// the underlying gauge is a no-op.\nfunc (g *Gauge) initializeMetric() {\n\tg.GaugeOpts.annotateStabilityLevel()\n\t// this actually creates the underlying prometheus gauge.\n\tg.setPrometheusGauge(prometheus.NewGauge(g.GaugeOpts.toPromGaugeOpts()))\n}","line":{"from":67,"to":73}} {"id":100030356,"name":"initializeDeprecatedMetric","signature":"func (g *Gauge) initializeDeprecatedMetric()","file":"staging/src/k8s.io/component-base/metrics/gauge.go","code":"// initializeDeprecatedMetric invocation creates the actual (but deprecated) Gauge. Until this method\n// is called the underlying gauge is a no-op.\nfunc (g *Gauge) initializeDeprecatedMetric() {\n\tg.GaugeOpts.markDeprecated()\n\tg.initializeMetric()\n}","line":{"from":75,"to":80}} {"id":100030357,"name":"WithContext","signature":"func (g *Gauge) WithContext(ctx context.Context) GaugeMetric","file":"staging/src/k8s.io/component-base/metrics/gauge.go","code":"// WithContext allows the normal Gauge metric to pass in context. The context is no-op now.\nfunc (g *Gauge) WithContext(ctx context.Context) GaugeMetric {\n\treturn g.GaugeMetric\n}","line":{"from":82,"to":85}} {"id":100030358,"name":"NewGaugeVec","signature":"func NewGaugeVec(opts *GaugeOpts, labels []string) *GaugeVec","file":"staging/src/k8s.io/component-base/metrics/gauge.go","code":"// NewGaugeVec returns an object which satisfies the kubeCollector, Registerable, and GaugeVecMetric interfaces.\n// However, the object returned will not measure anything unless the collector is first\n// registered, since the metric is lazily instantiated, and only members extracted after\n// registration will actually measure anything.\nfunc NewGaugeVec(opts *GaugeOpts, labels []string) *GaugeVec {\n\topts.StabilityLevel.setDefaults()\n\n\tfqName := BuildFQName(opts.Namespace, opts.Subsystem, opts.Name)\n\tallowListLock.RLock()\n\tif allowList, ok := labelValueAllowLists[fqName]; ok {\n\t\topts.LabelValueAllowLists = allowList\n\t}\n\tallowListLock.RUnlock()\n\n\tcv := \u0026GaugeVec{\n\t\tGaugeVec: noopGaugeVec,\n\t\tGaugeOpts: opts,\n\t\toriginalLabels: labels,\n\t\tlazyMetric: lazyMetric{stabilityLevel: opts.StabilityLevel},\n\t}\n\tcv.lazyInit(cv, fqName)\n\treturn cv\n}","line":{"from":100,"to":122}} {"id":100030359,"name":"DeprecatedVersion","signature":"func (v *GaugeVec) DeprecatedVersion() *semver.Version","file":"staging/src/k8s.io/component-base/metrics/gauge.go","code":"// DeprecatedVersion returns a pointer to the Version or nil\nfunc (v *GaugeVec) DeprecatedVersion() *semver.Version {\n\treturn parseSemver(v.GaugeOpts.DeprecatedVersion)\n}","line":{"from":124,"to":127}} {"id":100030360,"name":"initializeMetric","signature":"func (v *GaugeVec) initializeMetric()","file":"staging/src/k8s.io/component-base/metrics/gauge.go","code":"// initializeMetric invocation creates the actual underlying GaugeVec. Until this method is called\n// the underlying gaugeVec is a no-op.\nfunc (v *GaugeVec) initializeMetric() {\n\tv.GaugeOpts.annotateStabilityLevel()\n\tv.GaugeVec = prometheus.NewGaugeVec(v.GaugeOpts.toPromGaugeOpts(), v.originalLabels)\n}","line":{"from":129,"to":134}} {"id":100030361,"name":"initializeDeprecatedMetric","signature":"func (v *GaugeVec) initializeDeprecatedMetric()","file":"staging/src/k8s.io/component-base/metrics/gauge.go","code":"// initializeDeprecatedMetric invocation creates the actual (but deprecated) GaugeVec. Until this method is called\n// the underlying gaugeVec is a no-op.\nfunc (v *GaugeVec) initializeDeprecatedMetric() {\n\tv.GaugeOpts.markDeprecated()\n\tv.initializeMetric()\n}","line":{"from":136,"to":141}} {"id":100030362,"name":"WithLabelValuesChecked","signature":"func (v *GaugeVec) WithLabelValuesChecked(lvs ...string) (GaugeMetric, error)","file":"staging/src/k8s.io/component-base/metrics/gauge.go","code":"func (v *GaugeVec) WithLabelValuesChecked(lvs ...string) (GaugeMetric, error) {\n\tif !v.IsCreated() {\n\t\tif v.IsHidden() {\n\t\t\treturn noop, nil\n\t\t}\n\t\treturn noop, errNotRegistered // return no-op gauge\n\t}\n\tif v.LabelValueAllowLists != nil {\n\t\tv.LabelValueAllowLists.ConstrainToAllowedList(v.originalLabels, lvs)\n\t}\n\telt, err := v.GaugeVec.GetMetricWithLabelValues(lvs...)\n\treturn elt, err\n}","line":{"from":143,"to":155}} {"id":100030363,"name":"WithLabelValues","signature":"func (v *GaugeVec) WithLabelValues(lvs ...string) GaugeMetric","file":"staging/src/k8s.io/component-base/metrics/gauge.go","code":"// WithLabelValues returns the GaugeMetric for the given slice of label\n// values (same order as the VariableLabels in Desc). If that combination of\n// label values is accessed for the first time, a new GaugeMetric is created IFF the gaugeVec\n// has been registered to a metrics registry.\nfunc (v *GaugeVec) WithLabelValues(lvs ...string) GaugeMetric {\n\tans, err := v.WithLabelValuesChecked(lvs...)\n\tif err == nil || ErrIsNotRegistered(err) {\n\t\treturn ans\n\t}\n\tpanic(err)\n}","line":{"from":168,"to":178}} {"id":100030364,"name":"WithChecked","signature":"func (v *GaugeVec) WithChecked(labels map[string]string) (GaugeMetric, error)","file":"staging/src/k8s.io/component-base/metrics/gauge.go","code":"func (v *GaugeVec) WithChecked(labels map[string]string) (GaugeMetric, error) {\n\tif !v.IsCreated() {\n\t\tif v.IsHidden() {\n\t\t\treturn noop, nil\n\t\t}\n\t\treturn noop, errNotRegistered // return no-op gauge\n\t}\n\tif v.LabelValueAllowLists != nil {\n\t\tv.LabelValueAllowLists.ConstrainLabelMap(labels)\n\t}\n\telt, err := v.GaugeVec.GetMetricWith(labels)\n\treturn elt, err\n}","line":{"from":180,"to":192}} {"id":100030365,"name":"With","signature":"func (v *GaugeVec) With(labels map[string]string) GaugeMetric","file":"staging/src/k8s.io/component-base/metrics/gauge.go","code":"// With returns the GaugeMetric for the given Labels map (the label names\n// must match those of the VariableLabels in Desc). If that label map is\n// accessed for the first time, a new GaugeMetric is created IFF the gaugeVec has\n// been registered to a metrics registry.\nfunc (v *GaugeVec) With(labels map[string]string) GaugeMetric {\n\tans, err := v.WithChecked(labels)\n\tif err == nil || ErrIsNotRegistered(err) {\n\t\treturn ans\n\t}\n\tpanic(err)\n}","line":{"from":194,"to":204}} {"id":100030366,"name":"Delete","signature":"func (v *GaugeVec) Delete(labels map[string]string) bool","file":"staging/src/k8s.io/component-base/metrics/gauge.go","code":"// Delete deletes the metric where the variable labels are the same as those\n// passed in as labels. It returns true if a metric was deleted.\n//\n// It is not an error if the number and names of the Labels are inconsistent\n// with those of the VariableLabels in Desc. However, such inconsistent Labels\n// can never match an actual metric, so the method will always return false in\n// that case.\nfunc (v *GaugeVec) Delete(labels map[string]string) bool {\n\tif !v.IsCreated() {\n\t\treturn false // since we haven't created the metric, we haven't deleted a metric with the passed in values\n\t}\n\treturn v.GaugeVec.Delete(labels)\n}","line":{"from":206,"to":218}} {"id":100030367,"name":"Reset","signature":"func (v *GaugeVec) Reset()","file":"staging/src/k8s.io/component-base/metrics/gauge.go","code":"// Reset deletes all metrics in this vector.\nfunc (v *GaugeVec) Reset() {\n\tif !v.IsCreated() {\n\t\treturn\n\t}\n\n\tv.GaugeVec.Reset()\n}","line":{"from":220,"to":227}} {"id":100030368,"name":"newGaugeFunc","signature":"func newGaugeFunc(opts *GaugeOpts, function func() float64, v semver.Version) GaugeFunc","file":"staging/src/k8s.io/component-base/metrics/gauge.go","code":"func newGaugeFunc(opts *GaugeOpts, function func() float64, v semver.Version) GaugeFunc {\n\tg := NewGauge(opts)\n\n\tif !g.Create(\u0026v) {\n\t\treturn nil\n\t}\n\n\treturn prometheus.NewGaugeFunc(g.GaugeOpts.toPromGaugeOpts(), function)\n}","line":{"from":229,"to":237}} {"id":100030369,"name":"NewGaugeFunc","signature":"func NewGaugeFunc(opts *GaugeOpts, function func() float64) GaugeFunc","file":"staging/src/k8s.io/component-base/metrics/gauge.go","code":"// NewGaugeFunc creates a new GaugeFunc based on the provided GaugeOpts. The\n// value reported is determined by calling the given function from within the\n// Write method. Take into account that metric collection may happen\n// concurrently. If that results in concurrent calls to Write, like in the case\n// where a GaugeFunc is directly registered with Prometheus, the provided\n// function must be concurrency-safe.\nfunc NewGaugeFunc(opts *GaugeOpts, function func() float64) GaugeFunc {\n\tv := parseVersion(version.Get())\n\n\treturn newGaugeFunc(opts, function, v)\n}","line":{"from":239,"to":249}} {"id":100030370,"name":"WithContext","signature":"func (v *GaugeVec) WithContext(ctx context.Context) *GaugeVecWithContext","file":"staging/src/k8s.io/component-base/metrics/gauge.go","code":"// WithContext returns wrapped GaugeVec with context\nfunc (v *GaugeVec) WithContext(ctx context.Context) *GaugeVecWithContext {\n\treturn \u0026GaugeVecWithContext{\n\t\tctx: ctx,\n\t\tGaugeVec: v,\n\t}\n}","line":{"from":251,"to":257}} {"id":100030371,"name":"InterfaceWithContext","signature":"func (v *GaugeVec) InterfaceWithContext(ctx context.Context) GaugeVecMetric","file":"staging/src/k8s.io/component-base/metrics/gauge.go","code":"func (v *GaugeVec) InterfaceWithContext(ctx context.Context) GaugeVecMetric {\n\treturn v.WithContext(ctx)\n}","line":{"from":259,"to":261}} {"id":100030372,"name":"WithLabelValues","signature":"func (vc *GaugeVecWithContext) WithLabelValues(lvs ...string) GaugeMetric","file":"staging/src/k8s.io/component-base/metrics/gauge.go","code":"// WithLabelValues is the wrapper of GaugeVec.WithLabelValues.\nfunc (vc *GaugeVecWithContext) WithLabelValues(lvs ...string) GaugeMetric {\n\treturn vc.GaugeVec.WithLabelValues(lvs...)\n}","line":{"from":269,"to":272}} {"id":100030373,"name":"With","signature":"func (vc *GaugeVecWithContext) With(labels map[string]string) GaugeMetric","file":"staging/src/k8s.io/component-base/metrics/gauge.go","code":"// With is the wrapper of GaugeVec.With.\nfunc (vc *GaugeVecWithContext) With(labels map[string]string) GaugeMetric {\n\treturn vc.GaugeVec.With(labels)\n}","line":{"from":274,"to":277}} {"id":100030374,"name":"NewHistogram","signature":"func NewHistogram(opts *HistogramOpts) *Histogram","file":"staging/src/k8s.io/component-base/metrics/histogram.go","code":"// NewHistogram returns an object which is Histogram-like. However, nothing\n// will be measured until the histogram is registered somewhere.\nfunc NewHistogram(opts *HistogramOpts) *Histogram {\n\topts.StabilityLevel.setDefaults()\n\n\th := \u0026Histogram{\n\t\tHistogramOpts: opts,\n\t\tlazyMetric: lazyMetric{stabilityLevel: opts.StabilityLevel},\n\t}\n\th.setPrometheusHistogram(noopMetric{})\n\th.lazyInit(h, BuildFQName(opts.Namespace, opts.Subsystem, opts.Name))\n\treturn h\n}","line":{"from":35,"to":47}} {"id":100030375,"name":"setPrometheusHistogram","signature":"func (h *Histogram) setPrometheusHistogram(histogram prometheus.Histogram)","file":"staging/src/k8s.io/component-base/metrics/histogram.go","code":"// setPrometheusHistogram sets the underlying KubeGauge object, i.e. the thing that does the measurement.\nfunc (h *Histogram) setPrometheusHistogram(histogram prometheus.Histogram) {\n\th.ObserverMetric = histogram\n\th.initSelfCollection(histogram)\n}","line":{"from":49,"to":53}} {"id":100030376,"name":"DeprecatedVersion","signature":"func (h *Histogram) DeprecatedVersion() *semver.Version","file":"staging/src/k8s.io/component-base/metrics/histogram.go","code":"// DeprecatedVersion returns a pointer to the Version or nil\nfunc (h *Histogram) DeprecatedVersion() *semver.Version {\n\treturn parseSemver(h.HistogramOpts.DeprecatedVersion)\n}","line":{"from":55,"to":58}} {"id":100030377,"name":"initializeMetric","signature":"func (h *Histogram) initializeMetric()","file":"staging/src/k8s.io/component-base/metrics/histogram.go","code":"// initializeMetric invokes the actual prometheus.Histogram object instantiation\n// and stores a reference to it\nfunc (h *Histogram) initializeMetric() {\n\th.HistogramOpts.annotateStabilityLevel()\n\t// this actually creates the underlying prometheus gauge.\n\th.setPrometheusHistogram(prometheus.NewHistogram(h.HistogramOpts.toPromHistogramOpts()))\n}","line":{"from":60,"to":66}} {"id":100030378,"name":"initializeDeprecatedMetric","signature":"func (h *Histogram) initializeDeprecatedMetric()","file":"staging/src/k8s.io/component-base/metrics/histogram.go","code":"// initializeDeprecatedMetric invokes the actual prometheus.Histogram object instantiation\n// but modifies the Help description prior to object instantiation.\nfunc (h *Histogram) initializeDeprecatedMetric() {\n\th.HistogramOpts.markDeprecated()\n\th.initializeMetric()\n}","line":{"from":68,"to":73}} {"id":100030379,"name":"WithContext","signature":"func (h *Histogram) WithContext(ctx context.Context) ObserverMetric","file":"staging/src/k8s.io/component-base/metrics/histogram.go","code":"// WithContext allows the normal Histogram metric to pass in context. The context is no-op now.\nfunc (h *Histogram) WithContext(ctx context.Context) ObserverMetric {\n\treturn h.ObserverMetric\n}","line":{"from":75,"to":78}} {"id":100030380,"name":"NewHistogramVec","signature":"func NewHistogramVec(opts *HistogramOpts, labels []string) *HistogramVec","file":"staging/src/k8s.io/component-base/metrics/histogram.go","code":"func NewHistogramVec(opts *HistogramOpts, labels []string) *HistogramVec {\n\topts.StabilityLevel.setDefaults()\n\n\tfqName := BuildFQName(opts.Namespace, opts.Subsystem, opts.Name)\n\tallowListLock.RLock()\n\tif allowList, ok := labelValueAllowLists[fqName]; ok {\n\t\topts.LabelValueAllowLists = allowList\n\t}\n\tallowListLock.RUnlock()\n\n\tv := \u0026HistogramVec{\n\t\tHistogramVec: noopHistogramVec,\n\t\tHistogramOpts: opts,\n\t\toriginalLabels: labels,\n\t\tlazyMetric: lazyMetric{stabilityLevel: opts.StabilityLevel},\n\t}\n\tv.lazyInit(v, fqName)\n\treturn v\n}","line":{"from":95,"to":113}} {"id":100030381,"name":"DeprecatedVersion","signature":"func (v *HistogramVec) DeprecatedVersion() *semver.Version","file":"staging/src/k8s.io/component-base/metrics/histogram.go","code":"// DeprecatedVersion returns a pointer to the Version or nil\nfunc (v *HistogramVec) DeprecatedVersion() *semver.Version {\n\treturn parseSemver(v.HistogramOpts.DeprecatedVersion)\n}","line":{"from":115,"to":118}} {"id":100030382,"name":"initializeMetric","signature":"func (v *HistogramVec) initializeMetric()","file":"staging/src/k8s.io/component-base/metrics/histogram.go","code":"func (v *HistogramVec) initializeMetric() {\n\tv.HistogramOpts.annotateStabilityLevel()\n\tv.HistogramVec = prometheus.NewHistogramVec(v.HistogramOpts.toPromHistogramOpts(), v.originalLabels)\n}","line":{"from":120,"to":123}} {"id":100030383,"name":"initializeDeprecatedMetric","signature":"func (v *HistogramVec) initializeDeprecatedMetric()","file":"staging/src/k8s.io/component-base/metrics/histogram.go","code":"func (v *HistogramVec) initializeDeprecatedMetric() {\n\tv.HistogramOpts.markDeprecated()\n\tv.initializeMetric()\n}","line":{"from":125,"to":128}} {"id":100030384,"name":"WithLabelValues","signature":"func (v *HistogramVec) WithLabelValues(lvs ...string) ObserverMetric","file":"staging/src/k8s.io/component-base/metrics/histogram.go","code":"// WithLabelValues returns the ObserverMetric for the given slice of label\n// values (same order as the VariableLabels in Desc). If that combination of\n// label values is accessed for the first time, a new ObserverMetric is created IFF the HistogramVec\n// has been registered to a metrics registry.\nfunc (v *HistogramVec) WithLabelValues(lvs ...string) ObserverMetric {\n\tif !v.IsCreated() {\n\t\treturn noop\n\t}\n\tif v.LabelValueAllowLists != nil {\n\t\tv.LabelValueAllowLists.ConstrainToAllowedList(v.originalLabels, lvs)\n\t}\n\treturn v.HistogramVec.WithLabelValues(lvs...)\n}","line":{"from":141,"to":153}} {"id":100030385,"name":"With","signature":"func (v *HistogramVec) With(labels map[string]string) ObserverMetric","file":"staging/src/k8s.io/component-base/metrics/histogram.go","code":"// With returns the ObserverMetric for the given Labels map (the label names\n// must match those of the VariableLabels in Desc). If that label map is\n// accessed for the first time, a new ObserverMetric is created IFF the HistogramVec has\n// been registered to a metrics registry.\nfunc (v *HistogramVec) With(labels map[string]string) ObserverMetric {\n\tif !v.IsCreated() {\n\t\treturn noop\n\t}\n\tif v.LabelValueAllowLists != nil {\n\t\tv.LabelValueAllowLists.ConstrainLabelMap(labels)\n\t}\n\treturn v.HistogramVec.With(labels)\n}","line":{"from":155,"to":167}} {"id":100030386,"name":"Delete","signature":"func (v *HistogramVec) Delete(labels map[string]string) bool","file":"staging/src/k8s.io/component-base/metrics/histogram.go","code":"// Delete deletes the metric where the variable labels are the same as those\n// passed in as labels. It returns true if a metric was deleted.\n//\n// It is not an error if the number and names of the Labels are inconsistent\n// with those of the VariableLabels in Desc. However, such inconsistent Labels\n// can never match an actual metric, so the method will always return false in\n// that case.\nfunc (v *HistogramVec) Delete(labels map[string]string) bool {\n\tif !v.IsCreated() {\n\t\treturn false // since we haven't created the metric, we haven't deleted a metric with the passed in values\n\t}\n\treturn v.HistogramVec.Delete(labels)\n}","line":{"from":169,"to":181}} {"id":100030387,"name":"Reset","signature":"func (v *HistogramVec) Reset()","file":"staging/src/k8s.io/component-base/metrics/histogram.go","code":"// Reset deletes all metrics in this vector.\nfunc (v *HistogramVec) Reset() {\n\tif !v.IsCreated() {\n\t\treturn\n\t}\n\n\tv.HistogramVec.Reset()\n}","line":{"from":183,"to":190}} {"id":100030388,"name":"WithContext","signature":"func (v *HistogramVec) WithContext(ctx context.Context) *HistogramVecWithContext","file":"staging/src/k8s.io/component-base/metrics/histogram.go","code":"// WithContext returns wrapped HistogramVec with context\nfunc (v *HistogramVec) WithContext(ctx context.Context) *HistogramVecWithContext {\n\treturn \u0026HistogramVecWithContext{\n\t\tctx: ctx,\n\t\tHistogramVec: v,\n\t}\n}","line":{"from":192,"to":198}} {"id":100030389,"name":"WithLabelValues","signature":"func (vc *HistogramVecWithContext) WithLabelValues(lvs ...string) ObserverMetric","file":"staging/src/k8s.io/component-base/metrics/histogram.go","code":"// WithLabelValues is the wrapper of HistogramVec.WithLabelValues.\nfunc (vc *HistogramVecWithContext) WithLabelValues(lvs ...string) ObserverMetric {\n\treturn vc.HistogramVec.WithLabelValues(lvs...)\n}","line":{"from":206,"to":209}} {"id":100030390,"name":"With","signature":"func (vc *HistogramVecWithContext) With(labels map[string]string) ObserverMetric","file":"staging/src/k8s.io/component-base/metrics/histogram.go","code":"// With is the wrapper of HistogramVec.With.\nfunc (vc *HistogramVecWithContext) With(labels map[string]string) ObserverMetric {\n\treturn vc.HistogramVec.With(labels)\n}","line":{"from":211,"to":214}} {"id":100030391,"name":"toPromhttpHandlerOpts","signature":"func (ho *HandlerOpts) toPromhttpHandlerOpts() promhttp.HandlerOpts","file":"staging/src/k8s.io/component-base/metrics/http.go","code":"func (ho *HandlerOpts) toPromhttpHandlerOpts() promhttp.HandlerOpts {\n\treturn promhttp.HandlerOpts(*ho)\n}","line":{"from":52,"to":54}} {"id":100030392,"name":"HandlerFor","signature":"func HandlerFor(reg Gatherer, opts HandlerOpts) http.Handler","file":"staging/src/k8s.io/component-base/metrics/http.go","code":"// HandlerFor returns an uninstrumented http.Handler for the provided\n// Gatherer. The behavior of the Handler is defined by the provided\n// HandlerOpts. Thus, HandlerFor is useful to create http.Handlers for custom\n// Gatherers, with non-default HandlerOpts, and/or with custom (or no)\n// instrumentation. Use the InstrumentMetricHandler function to apply the same\n// kind of instrumentation as it is used by the Handler function.\nfunc HandlerFor(reg Gatherer, opts HandlerOpts) http.Handler {\n\treturn promhttp.HandlerFor(reg, opts.toPromhttpHandlerOpts())\n}","line":{"from":56,"to":64}} {"id":100030393,"name":"HandlerWithReset","signature":"func HandlerWithReset(reg KubeRegistry, opts HandlerOpts) http.Handler","file":"staging/src/k8s.io/component-base/metrics/http.go","code":"// HandlerWithReset return an http.Handler with Reset\nfunc HandlerWithReset(reg KubeRegistry, opts HandlerOpts) http.Handler {\n\tdefaultHandler := promhttp.HandlerFor(reg, opts.toPromhttpHandlerOpts())\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method == http.MethodDelete {\n\t\t\treg.Reset()\n\t\t\tio.WriteString(w, \"metrics reset\\n\")\n\t\t\treturn\n\t\t}\n\t\tdefaultHandler.ServeHTTP(w, r)\n\t})\n}","line":{"from":66,"to":77}} {"id":100030394,"name":"init","signature":"func init()","file":"staging/src/k8s.io/component-base/metrics/legacyregistry/registry.go","code":"func init() {\n\tRawMustRegister(collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}))\n\tRawMustRegister(collectors.NewGoCollector(collectors.WithGoCollectorRuntimeMetrics(collectors.MetricsAll)))\n\tdefaultRegistry.RegisterMetaMetrics()\n}","line":{"from":50,"to":54}} {"id":100030395,"name":"Handler","signature":"func Handler() http.Handler","file":"staging/src/k8s.io/component-base/metrics/legacyregistry/registry.go","code":"// Handler returns an HTTP handler for the DefaultGatherer. It is\n// already instrumented with InstrumentHandler (using \"prometheus\" as handler\n// name).\nfunc Handler() http.Handler {\n\treturn promhttp.InstrumentMetricHandler(prometheus.DefaultRegisterer, promhttp.HandlerFor(defaultRegistry, promhttp.HandlerOpts{}))\n}","line":{"from":56,"to":61}} {"id":100030396,"name":"HandlerWithReset","signature":"func HandlerWithReset() http.Handler","file":"staging/src/k8s.io/component-base/metrics/legacyregistry/registry.go","code":"// HandlerWithReset returns an HTTP handler for the DefaultGatherer but invokes\n// registry reset if the http method is DELETE.\nfunc HandlerWithReset() http.Handler {\n\treturn promhttp.InstrumentMetricHandler(\n\t\tprometheus.DefaultRegisterer,\n\t\tmetrics.HandlerWithReset(defaultRegistry, metrics.HandlerOpts{}))\n}","line":{"from":63,"to":69}} {"id":100030397,"name":"CustomRegister","signature":"func CustomRegister(c metrics.StableCollector) error","file":"staging/src/k8s.io/component-base/metrics/legacyregistry/registry.go","code":"// CustomRegister registers a custom collector but uses the global registry.\nfunc CustomRegister(c metrics.StableCollector) error {\n\terr := defaultRegistry.CustomRegister(c)\n\n\t//TODO(RainbowMango): Maybe we can wrap this error by error wrapping.(Golang 1.13)\n\t_ = prometheus.Register(c)\n\n\treturn err\n}","line":{"from":71,"to":79}} {"id":100030398,"name":"CustomMustRegister","signature":"func CustomMustRegister(cs ...metrics.StableCollector)","file":"staging/src/k8s.io/component-base/metrics/legacyregistry/registry.go","code":"// CustomMustRegister registers custom collectors but uses the global registry.\nfunc CustomMustRegister(cs ...metrics.StableCollector) {\n\tdefaultRegistry.CustomMustRegister(cs...)\n\n\tfor _, c := range cs {\n\t\tprometheus.MustRegister(c)\n\t}\n}","line":{"from":81,"to":88}} {"id":100030399,"name":"IsCreated","signature":"func (r *lazyMetric) IsCreated() bool","file":"staging/src/k8s.io/component-base/metrics/metric.go","code":"func (r *lazyMetric) IsCreated() bool {\n\tr.createLock.RLock()\n\tdefer r.createLock.RUnlock()\n\treturn r.isCreated\n}","line":{"from":78,"to":82}} {"id":100030400,"name":"lazyInit","signature":"func (r *lazyMetric) lazyInit(self kubeCollector, fqName string)","file":"staging/src/k8s.io/component-base/metrics/metric.go","code":"// lazyInit provides the lazyMetric with a reference to the kubeCollector it is supposed\n// to allow lazy initialization for. It should be invoked in the factory function which creates new\n// kubeCollector type objects.\nfunc (r *lazyMetric) lazyInit(self kubeCollector, fqName string) {\n\tr.fqName = fqName\n\tr.self = self\n}","line":{"from":84,"to":90}} {"id":100030401,"name":"preprocessMetric","signature":"func (r *lazyMetric) preprocessMetric(version semver.Version)","file":"staging/src/k8s.io/component-base/metrics/metric.go","code":"// preprocessMetric figures out whether the lazy metric should be hidden or not.\n// This method takes a Version argument which should be the version of the binary in which\n// this code is currently being executed. A metric can be hidden under two conditions:\n// 1. if the metric is deprecated and is outside the grace period (i.e. has been\n// deprecated for more than one release\n// 2. if the metric is manually disabled via a CLI flag.\n//\n// Disclaimer: disabling a metric via a CLI flag has higher precedence than\n// deprecation and will override show-hidden-metrics for the explicitly\n// disabled metric.\nfunc (r *lazyMetric) preprocessMetric(version semver.Version) {\n\tdisabledMetricsLock.RLock()\n\tdefer disabledMetricsLock.RUnlock()\n\t// disabling metrics is higher in precedence than showing hidden metrics\n\tif _, ok := disabledMetrics[r.fqName]; ok {\n\t\tr.isHidden = true\n\t\treturn\n\t}\n\tselfVersion := r.self.DeprecatedVersion()\n\tif selfVersion == nil {\n\t\treturn\n\t}\n\tr.markDeprecationOnce.Do(func() {\n\t\tif selfVersion.LTE(version) {\n\t\t\tr.isDeprecated = true\n\t\t}\n\n\t\tif ShouldShowHidden() {\n\t\t\tklog.Warningf(\"Hidden metrics (%s) have been manually overridden, showing this very deprecated metric.\", r.fqName)\n\t\t\treturn\n\t\t}\n\t\tif shouldHide(\u0026version, selfVersion) {\n\t\t\t// TODO(RainbowMango): Remove this log temporarily. https://github.com/kubernetes/kubernetes/issues/85369\n\t\t\t// klog.Warningf(\"This metric has been deprecated for more than one release, hiding.\")\n\t\t\tr.isHidden = true\n\t\t}\n\t})\n}","line":{"from":92,"to":129}} {"id":100030402,"name":"IsHidden","signature":"func (r *lazyMetric) IsHidden() bool","file":"staging/src/k8s.io/component-base/metrics/metric.go","code":"func (r *lazyMetric) IsHidden() bool {\n\treturn r.isHidden\n}","line":{"from":131,"to":133}} {"id":100030403,"name":"IsDeprecated","signature":"func (r *lazyMetric) IsDeprecated() bool","file":"staging/src/k8s.io/component-base/metrics/metric.go","code":"func (r *lazyMetric) IsDeprecated() bool {\n\treturn r.isDeprecated\n}","line":{"from":135,"to":137}} {"id":100030404,"name":"Create","signature":"func (r *lazyMetric) Create(version *semver.Version) bool","file":"staging/src/k8s.io/component-base/metrics/metric.go","code":"// Create forces the initialization of metric which has been deferred until\n// the point at which this method is invoked. This method will determine whether\n// the metric is deprecated or hidden, no-opting if the metric should be considered\n// hidden. Furthermore, this function no-opts and returns true if metric is already\n// created.\nfunc (r *lazyMetric) Create(version *semver.Version) bool {\n\tif version != nil {\n\t\tr.preprocessMetric(*version)\n\t}\n\t// let's not create if this metric is slated to be hidden\n\tif r.IsHidden() {\n\t\treturn false\n\t}\n\n\tr.createOnce.Do(func() {\n\t\tr.createLock.Lock()\n\t\tdefer r.createLock.Unlock()\n\t\tr.isCreated = true\n\t\tif r.IsDeprecated() {\n\t\t\tr.self.initializeDeprecatedMetric()\n\t\t} else {\n\t\t\tr.self.initializeMetric()\n\t\t}\n\t})\n\tsl := r.stabilityLevel\n\tdeprecatedV := r.self.DeprecatedVersion()\n\tdv := \"\"\n\tif deprecatedV != nil {\n\t\tdv = deprecatedV.String()\n\t}\n\tregisteredMetrics.WithLabelValues(string(sl), dv).Inc()\n\treturn r.IsCreated()\n}","line":{"from":139,"to":171}} {"id":100030405,"name":"ClearState","signature":"func (r *lazyMetric) ClearState()","file":"staging/src/k8s.io/component-base/metrics/metric.go","code":"// ClearState will clear all the states marked by Create.\n// It intends to be used for re-register a hidden metric.\nfunc (r *lazyMetric) ClearState() {\n\tr.createLock.Lock()\n\tdefer r.createLock.Unlock()\n\n\tr.isDeprecated = false\n\tr.isHidden = false\n\tr.isCreated = false\n\tr.markDeprecationOnce = sync.Once{}\n\tr.createOnce = sync.Once{}\n}","line":{"from":173,"to":184}} {"id":100030406,"name":"FQName","signature":"func (r *lazyMetric) FQName() string","file":"staging/src/k8s.io/component-base/metrics/metric.go","code":"// FQName returns the fully-qualified metric name of the collector.\nfunc (r *lazyMetric) FQName() string {\n\treturn r.fqName\n}","line":{"from":186,"to":189}} {"id":100030407,"name":"initSelfCollection","signature":"func (c *selfCollector) initSelfCollection(m prometheus.Metric)","file":"staging/src/k8s.io/component-base/metrics/metric.go","code":"func (c *selfCollector) initSelfCollection(m prometheus.Metric) {\n\tc.metric = m\n}","line":{"from":201,"to":203}} {"id":100030408,"name":"Describe","signature":"func (c *selfCollector) Describe(ch chan\u003c- *prometheus.Desc)","file":"staging/src/k8s.io/component-base/metrics/metric.go","code":"func (c *selfCollector) Describe(ch chan\u003c- *prometheus.Desc) {\n\tch \u003c- c.metric.Desc()\n}","line":{"from":205,"to":207}} {"id":100030409,"name":"Collect","signature":"func (c *selfCollector) Collect(ch chan\u003c- prometheus.Metric)","file":"staging/src/k8s.io/component-base/metrics/metric.go","code":"func (c *selfCollector) Collect(ch chan\u003c- prometheus.Metric) {\n\tch \u003c- c.metric\n}","line":{"from":209,"to":211}} {"id":100030410,"name":"Inc","signature":"func (noopMetric) Inc() {}","file":"staging/src/k8s.io/component-base/metrics/metric.go","code":"func (noopMetric) Inc() {}","line":{"from":224,"to":224}} {"id":100030411,"name":"Add","signature":"func (noopMetric) Add(float64) {}","file":"staging/src/k8s.io/component-base/metrics/metric.go","code":"func (noopMetric) Add(float64) {}","line":{"from":225,"to":225}} {"id":100030412,"name":"Dec","signature":"func (noopMetric) Dec() {}","file":"staging/src/k8s.io/component-base/metrics/metric.go","code":"func (noopMetric) Dec() {}","line":{"from":226,"to":226}} {"id":100030413,"name":"Set","signature":"func (noopMetric) Set(float64) {}","file":"staging/src/k8s.io/component-base/metrics/metric.go","code":"func (noopMetric) Set(float64) {}","line":{"from":227,"to":227}} {"id":100030414,"name":"Sub","signature":"func (noopMetric) Sub(float64) {}","file":"staging/src/k8s.io/component-base/metrics/metric.go","code":"func (noopMetric) Sub(float64) {}","line":{"from":228,"to":228}} {"id":100030415,"name":"Observe","signature":"func (noopMetric) Observe(float64) {}","file":"staging/src/k8s.io/component-base/metrics/metric.go","code":"func (noopMetric) Observe(float64) {}","line":{"from":229,"to":229}} {"id":100030416,"name":"ObserveWithWeight","signature":"func (noopMetric) ObserveWithWeight(float64, uint64) {}","file":"staging/src/k8s.io/component-base/metrics/metric.go","code":"func (noopMetric) ObserveWithWeight(float64, uint64) {}","line":{"from":230,"to":230}} {"id":100030417,"name":"SetToCurrentTime","signature":"func (noopMetric) SetToCurrentTime() {}","file":"staging/src/k8s.io/component-base/metrics/metric.go","code":"func (noopMetric) SetToCurrentTime() {}","line":{"from":231,"to":231}} {"id":100030418,"name":"Desc","signature":"func (noopMetric) Desc() *prometheus.Desc { return nil }","file":"staging/src/k8s.io/component-base/metrics/metric.go","code":"func (noopMetric) Desc() *prometheus.Desc { return nil }","line":{"from":232,"to":232}} {"id":100030419,"name":"Write","signature":"func (noopMetric) Write(*dto.Metric) error { return nil }","file":"staging/src/k8s.io/component-base/metrics/metric.go","code":"func (noopMetric) Write(*dto.Metric) error { return nil }","line":{"from":233,"to":233}} {"id":100030420,"name":"Describe","signature":"func (noopMetric) Describe(chan\u003c- *prometheus.Desc) {}","file":"staging/src/k8s.io/component-base/metrics/metric.go","code":"func (noopMetric) Describe(chan\u003c- *prometheus.Desc) {}","line":{"from":234,"to":234}} {"id":100030421,"name":"Collect","signature":"func (noopMetric) Collect(chan\u003c- prometheus.Metric) {}","file":"staging/src/k8s.io/component-base/metrics/metric.go","code":"func (noopMetric) Collect(chan\u003c- prometheus.Metric) {}","line":{"from":235,"to":235}} {"id":100030422,"name":"NewOptions","signature":"func NewOptions() *Options","file":"staging/src/k8s.io/component-base/metrics/options.go","code":"// NewOptions returns default metrics options\nfunc NewOptions() *Options {\n\treturn \u0026Options{}\n}","line":{"from":36,"to":39}} {"id":100030423,"name":"Validate","signature":"func (o *Options) Validate() []error","file":"staging/src/k8s.io/component-base/metrics/options.go","code":"// Validate validates metrics flags options.\nfunc (o *Options) Validate() []error {\n\tvar errs []error\n\terr := validateShowHiddenMetricsVersion(parseVersion(version.Get()), o.ShowHiddenMetricsForVersion)\n\tif err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\tif err := validateAllowMetricLabel(o.AllowListMapping); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\tif len(errs) == 0 {\n\t\treturn nil\n\t}\n\treturn errs\n}","line":{"from":41,"to":57}} {"id":100030424,"name":"AddFlags","signature":"func (o *Options) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/component-base/metrics/options.go","code":"// AddFlags adds flags for exposing component metrics.\nfunc (o *Options) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\tfs.StringVar(\u0026o.ShowHiddenMetricsForVersion, \"show-hidden-metrics-for-version\", o.ShowHiddenMetricsForVersion,\n\t\t\"The previous version for which you want to show hidden metrics. \"+\n\t\t\t\"Only the previous minor version is meaningful, other values will not be allowed. \"+\n\t\t\t\"The format is \u003cmajor\u003e.\u003cminor\u003e, e.g.: '1.16'. \"+\n\t\t\t\"The purpose of this format is make sure you have the opportunity to notice if the next release hides additional metrics, \"+\n\t\t\t\"rather than being surprised when they are permanently removed in the release after that.\")\n\tfs.StringSliceVar(\u0026o.DisabledMetrics,\n\t\t\"disabled-metrics\",\n\t\to.DisabledMetrics,\n\t\t\"This flag provides an escape hatch for misbehaving metrics. \"+\n\t\t\t\"You must provide the fully qualified metric name in order to disable it. \"+\n\t\t\t\"Disclaimer: disabling metrics is higher in precedence than showing hidden metrics.\")\n\tfs.StringToStringVar(\u0026o.AllowListMapping, \"allow-metric-labels\", o.AllowListMapping,\n\t\t\"The map from metric-label to value allow-list of this label. The key's format is \u003cMetricName\u003e,\u003cLabelName\u003e. \"+\n\t\t\t\"The value's format is \u003callowed_value\u003e,\u003callowed_value\u003e...\"+\n\t\t\t\"e.g. metric1,label1='v1,v2,v3', metric1,label2='v1,v2,v3' metric2,label1='v1,v2,v3'.\")\n}","line":{"from":59,"to":80}} {"id":100030425,"name":"Apply","signature":"func (o *Options) Apply()","file":"staging/src/k8s.io/component-base/metrics/options.go","code":"// Apply applies parameters into global configuration of metrics.\nfunc (o *Options) Apply() {\n\tif o == nil {\n\t\treturn\n\t}\n\tif len(o.ShowHiddenMetricsForVersion) \u003e 0 {\n\t\tSetShowHidden()\n\t}\n\t// set disabled metrics\n\tfor _, metricName := range o.DisabledMetrics {\n\t\tSetDisabledMetric(metricName)\n\t}\n\tif o.AllowListMapping != nil {\n\t\tSetLabelAllowListFromCLI(o.AllowListMapping)\n\t}\n}","line":{"from":82,"to":97}} {"id":100030426,"name":"validateShowHiddenMetricsVersion","signature":"func validateShowHiddenMetricsVersion(currentVersion semver.Version, targetVersionStr string) error","file":"staging/src/k8s.io/component-base/metrics/options.go","code":"func validateShowHiddenMetricsVersion(currentVersion semver.Version, targetVersionStr string) error {\n\tif targetVersionStr == \"\" {\n\t\treturn nil\n\t}\n\n\tvalidVersionStr := fmt.Sprintf(\"%d.%d\", currentVersion.Major, currentVersion.Minor-1)\n\tif targetVersionStr != validVersionStr {\n\t\treturn fmt.Errorf(\"--show-hidden-metrics-for-version must be omitted or have the value '%v'. Only the previous minor version is allowed\", validVersionStr)\n\t}\n\n\treturn nil\n}","line":{"from":99,"to":110}} {"id":100030427,"name":"validateAllowMetricLabel","signature":"func validateAllowMetricLabel(allowListMapping map[string]string) error","file":"staging/src/k8s.io/component-base/metrics/options.go","code":"func validateAllowMetricLabel(allowListMapping map[string]string) error {\n\tif allowListMapping == nil {\n\t\treturn nil\n\t}\n\tmetricNameRegex := `[a-zA-Z_:][a-zA-Z0-9_:]*`\n\tlabelRegex := `[a-zA-Z_][a-zA-Z0-9_]*`\n\tfor k := range allowListMapping {\n\t\treg := regexp.MustCompile(metricNameRegex + `,` + labelRegex)\n\t\tif reg.FindString(k) != k {\n\t\t\treturn fmt.Errorf(\"--allow-metric-labels must has a list of kv pair with format `metricName:labelName=labelValue, labelValue,...`\")\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":112,"to":125}} {"id":100030428,"name":"BuildFQName","signature":"func BuildFQName(namespace, subsystem, name string) string","file":"staging/src/k8s.io/component-base/metrics/opts.go","code":"// BuildFQName joins the given three name components by \"_\". Empty name\n// components are ignored. If the name parameter itself is empty, an empty\n// string is returned, no matter what. Metric implementations included in this\n// library use this function internally to generate the fully-qualified metric\n// name from the name component in their Opts. Users of the library will only\n// need this function if they implement their own Metric or instantiate a Desc\n// (with NewDesc) directly.\nfunc BuildFQName(namespace, subsystem, name string) string {\n\treturn prometheus.BuildFQName(namespace, subsystem, name)\n}","line":{"from":54,"to":63}} {"id":100030429,"name":"setDefaults","signature":"func (sl *StabilityLevel) setDefaults()","file":"staging/src/k8s.io/component-base/metrics/opts.go","code":"// setDefaults takes 'ALPHA' in case of empty.\nfunc (sl *StabilityLevel) setDefaults() {\n\tswitch *sl {\n\tcase \"\":\n\t\t*sl = ALPHA\n\tdefault:\n\t\t// no-op, since we have a StabilityLevel already\n\t}\n}","line":{"from":83,"to":91}} {"id":100030430,"name":"markDeprecated","signature":"func (o *CounterOpts) markDeprecated()","file":"staging/src/k8s.io/component-base/metrics/opts.go","code":"// Modify help description on the metric description.\nfunc (o *CounterOpts) markDeprecated() {\n\to.deprecateOnce.Do(func() {\n\t\to.Help = fmt.Sprintf(\"(Deprecated since %v) %v\", o.DeprecatedVersion, o.Help)\n\t})\n}","line":{"from":96,"to":101}} {"id":100030431,"name":"annotateStabilityLevel","signature":"func (o *CounterOpts) annotateStabilityLevel()","file":"staging/src/k8s.io/component-base/metrics/opts.go","code":"// annotateStabilityLevel annotates help description on the metric description with the stability level\n// of the metric\nfunc (o *CounterOpts) annotateStabilityLevel() {\n\to.annotateOnce.Do(func() {\n\t\to.Help = fmt.Sprintf(\"[%v] %v\", o.StabilityLevel, o.Help)\n\t})\n}","line":{"from":103,"to":109}} {"id":100030432,"name":"toPromCounterOpts","signature":"func (o *CounterOpts) toPromCounterOpts() prometheus.CounterOpts","file":"staging/src/k8s.io/component-base/metrics/opts.go","code":"// convenience function to allow easy transformation to the prometheus\n// counterpart. This will do more once we have a proper label abstraction\nfunc (o *CounterOpts) toPromCounterOpts() prometheus.CounterOpts {\n\treturn prometheus.CounterOpts{\n\t\tNamespace: o.Namespace,\n\t\tSubsystem: o.Subsystem,\n\t\tName: o.Name,\n\t\tHelp: o.Help,\n\t\tConstLabels: o.ConstLabels,\n\t}\n}","line":{"from":111,"to":121}} {"id":100030433,"name":"markDeprecated","signature":"func (o *GaugeOpts) markDeprecated()","file":"staging/src/k8s.io/component-base/metrics/opts.go","code":"// Modify help description on the metric description.\nfunc (o *GaugeOpts) markDeprecated() {\n\to.deprecateOnce.Do(func() {\n\t\to.Help = fmt.Sprintf(\"(Deprecated since %v) %v\", o.DeprecatedVersion, o.Help)\n\t})\n}","line":{"from":126,"to":131}} {"id":100030434,"name":"annotateStabilityLevel","signature":"func (o *GaugeOpts) annotateStabilityLevel()","file":"staging/src/k8s.io/component-base/metrics/opts.go","code":"// annotateStabilityLevel annotates help description on the metric description with the stability level\n// of the metric\nfunc (o *GaugeOpts) annotateStabilityLevel() {\n\to.annotateOnce.Do(func() {\n\t\to.Help = fmt.Sprintf(\"[%v] %v\", o.StabilityLevel, o.Help)\n\t})\n}","line":{"from":133,"to":139}} {"id":100030435,"name":"toPromGaugeOpts","signature":"func (o *GaugeOpts) toPromGaugeOpts() prometheus.GaugeOpts","file":"staging/src/k8s.io/component-base/metrics/opts.go","code":"// convenience function to allow easy transformation to the prometheus\n// counterpart. This will do more once we have a proper label abstraction\nfunc (o *GaugeOpts) toPromGaugeOpts() prometheus.GaugeOpts {\n\treturn prometheus.GaugeOpts{\n\t\tNamespace: o.Namespace,\n\t\tSubsystem: o.Subsystem,\n\t\tName: o.Name,\n\t\tHelp: o.Help,\n\t\tConstLabels: o.ConstLabels,\n\t}\n}","line":{"from":141,"to":151}} {"id":100030436,"name":"markDeprecated","signature":"func (o *HistogramOpts) markDeprecated()","file":"staging/src/k8s.io/component-base/metrics/opts.go","code":"// Modify help description on the metric description.\nfunc (o *HistogramOpts) markDeprecated() {\n\to.deprecateOnce.Do(func() {\n\t\to.Help = fmt.Sprintf(\"(Deprecated since %v) %v\", o.DeprecatedVersion, o.Help)\n\t})\n}","line":{"from":171,"to":176}} {"id":100030437,"name":"annotateStabilityLevel","signature":"func (o *HistogramOpts) annotateStabilityLevel()","file":"staging/src/k8s.io/component-base/metrics/opts.go","code":"// annotateStabilityLevel annotates help description on the metric description with the stability level\n// of the metric\nfunc (o *HistogramOpts) annotateStabilityLevel() {\n\to.annotateOnce.Do(func() {\n\t\to.Help = fmt.Sprintf(\"[%v] %v\", o.StabilityLevel, o.Help)\n\t})\n}","line":{"from":178,"to":184}} {"id":100030438,"name":"toPromHistogramOpts","signature":"func (o *HistogramOpts) toPromHistogramOpts() prometheus.HistogramOpts","file":"staging/src/k8s.io/component-base/metrics/opts.go","code":"// convenience function to allow easy transformation to the prometheus\n// counterpart. This will do more once we have a proper label abstraction\nfunc (o *HistogramOpts) toPromHistogramOpts() prometheus.HistogramOpts {\n\treturn prometheus.HistogramOpts{\n\t\tNamespace: o.Namespace,\n\t\tSubsystem: o.Subsystem,\n\t\tName: o.Name,\n\t\tHelp: o.Help,\n\t\tConstLabels: o.ConstLabels,\n\t\tBuckets: o.Buckets,\n\t}\n}","line":{"from":186,"to":197}} {"id":100030439,"name":"markDeprecated","signature":"func (o *TimingHistogramOpts) markDeprecated()","file":"staging/src/k8s.io/component-base/metrics/opts.go","code":"// Modify help description on the metric description.\nfunc (o *TimingHistogramOpts) markDeprecated() {\n\to.deprecateOnce.Do(func() {\n\t\to.Help = fmt.Sprintf(\"(Deprecated since %v) %v\", o.DeprecatedVersion, o.Help)\n\t})\n}","line":{"from":218,"to":223}} {"id":100030440,"name":"annotateStabilityLevel","signature":"func (o *TimingHistogramOpts) annotateStabilityLevel()","file":"staging/src/k8s.io/component-base/metrics/opts.go","code":"// annotateStabilityLevel annotates help description on the metric description with the stability level\n// of the metric\nfunc (o *TimingHistogramOpts) annotateStabilityLevel() {\n\to.annotateOnce.Do(func() {\n\t\to.Help = fmt.Sprintf(\"[%v] %v\", o.StabilityLevel, o.Help)\n\t})\n}","line":{"from":225,"to":231}} {"id":100030441,"name":"toPromHistogramOpts","signature":"func (o *TimingHistogramOpts) toPromHistogramOpts() promext.TimingHistogramOpts","file":"staging/src/k8s.io/component-base/metrics/opts.go","code":"// convenience function to allow easy transformation to the prometheus\n// counterpart. This will do more once we have a proper label abstraction\nfunc (o *TimingHistogramOpts) toPromHistogramOpts() promext.TimingHistogramOpts {\n\treturn promext.TimingHistogramOpts{\n\t\tNamespace: o.Namespace,\n\t\tSubsystem: o.Subsystem,\n\t\tName: o.Name,\n\t\tHelp: o.Help,\n\t\tConstLabels: o.ConstLabels,\n\t\tBuckets: o.Buckets,\n\t\tInitialValue: o.InitialValue,\n\t}\n}","line":{"from":233,"to":245}} {"id":100030442,"name":"markDeprecated","signature":"func (o *SummaryOpts) markDeprecated()","file":"staging/src/k8s.io/component-base/metrics/opts.go","code":"// Modify help description on the metric description.\nfunc (o *SummaryOpts) markDeprecated() {\n\to.deprecateOnce.Do(func() {\n\t\to.Help = fmt.Sprintf(\"(Deprecated since %v) %v\", o.DeprecatedVersion, o.Help)\n\t})\n}","line":{"from":269,"to":274}} {"id":100030443,"name":"annotateStabilityLevel","signature":"func (o *SummaryOpts) annotateStabilityLevel()","file":"staging/src/k8s.io/component-base/metrics/opts.go","code":"// annotateStabilityLevel annotates help description on the metric description with the stability level\n// of the metric\nfunc (o *SummaryOpts) annotateStabilityLevel() {\n\to.annotateOnce.Do(func() {\n\t\to.Help = fmt.Sprintf(\"[%v] %v\", o.StabilityLevel, o.Help)\n\t})\n}","line":{"from":276,"to":282}} {"id":100030444,"name":"toPromSummaryOpts","signature":"func (o *SummaryOpts) toPromSummaryOpts() prometheus.SummaryOpts","file":"staging/src/k8s.io/component-base/metrics/opts.go","code":"// convenience function to allow easy transformation to the prometheus\n// counterpart. This will do more once we have a proper label abstraction\nfunc (o *SummaryOpts) toPromSummaryOpts() prometheus.SummaryOpts {\n\t// we need to retain existing quantile behavior for backwards compatibility,\n\t// so let's do what prometheus used to do prior to v1.\n\tobjectives := o.Objectives\n\tif objectives == nil {\n\t\tobjectives = defObjectives\n\t}\n\treturn prometheus.SummaryOpts{\n\t\tNamespace: o.Namespace,\n\t\tSubsystem: o.Subsystem,\n\t\tName: o.Name,\n\t\tHelp: o.Help,\n\t\tConstLabels: o.ConstLabels,\n\t\tObjectives: objectives,\n\t\tMaxAge: o.MaxAge,\n\t\tAgeBuckets: o.AgeBuckets,\n\t\tBufCap: o.BufCap,\n\t}\n}","line":{"from":290,"to":310}} {"id":100030445,"name":"ConstrainToAllowedList","signature":"func (allowList *MetricLabelAllowList) ConstrainToAllowedList(labelNameList, labelValueList []string)","file":"staging/src/k8s.io/component-base/metrics/opts.go","code":"func (allowList *MetricLabelAllowList) ConstrainToAllowedList(labelNameList, labelValueList []string) {\n\tfor index, value := range labelValueList {\n\t\tname := labelNameList[index]\n\t\tif allowValues, ok := allowList.labelToAllowList[name]; ok {\n\t\t\tif !allowValues.Has(value) {\n\t\t\t\tlabelValueList[index] = \"unexpected\"\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":316,"to":325}} {"id":100030446,"name":"ConstrainLabelMap","signature":"func (allowList *MetricLabelAllowList) ConstrainLabelMap(labels map[string]string)","file":"staging/src/k8s.io/component-base/metrics/opts.go","code":"func (allowList *MetricLabelAllowList) ConstrainLabelMap(labels map[string]string) {\n\tfor name, value := range labels {\n\t\tif allowValues, ok := allowList.labelToAllowList[name]; ok {\n\t\t\tif !allowValues.Has(value) {\n\t\t\t\tlabels[name] = \"unexpected\"\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":327,"to":335}} {"id":100030447,"name":"SetLabelAllowListFromCLI","signature":"func SetLabelAllowListFromCLI(allowListMapping map[string]string)","file":"staging/src/k8s.io/component-base/metrics/opts.go","code":"func SetLabelAllowListFromCLI(allowListMapping map[string]string) {\n\tallowListLock.Lock()\n\tdefer allowListLock.Unlock()\n\tfor metricLabelName, labelValues := range allowListMapping {\n\t\tmetricName := strings.Split(metricLabelName, \",\")[0]\n\t\tlabelName := strings.Split(metricLabelName, \",\")[1]\n\t\tvalueSet := sets.NewString(strings.Split(labelValues, \",\")...)\n\n\t\tallowList, ok := labelValueAllowLists[metricName]\n\t\tif ok {\n\t\t\tallowList.labelToAllowList[labelName] = valueSet\n\t\t} else {\n\t\t\tlabelToAllowList := make(map[string]sets.String)\n\t\t\tlabelToAllowList[labelName] = valueSet\n\t\t\tlabelValueAllowLists[metricName] = \u0026MetricLabelAllowList{\n\t\t\t\tlabelToAllowList,\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":337,"to":356}} {"id":100030448,"name":"RegisterProcessStartTime","signature":"func RegisterProcessStartTime(registrationFunc func(Registerable) error) error","file":"staging/src/k8s.io/component-base/metrics/processstarttime.go","code":"// RegisterProcessStartTime registers the process_start_time_seconds to\n// a prometheus registry. This metric needs to be included to ensure counter\n// data fidelity.\nfunc RegisterProcessStartTime(registrationFunc func(Registerable) error) error {\n\tstart, err := getProcessStart()\n\tif err != nil {\n\t\tklog.Errorf(\"Could not get process start time, %v\", err)\n\t\tstart = float64(time.Now().Unix())\n\t}\n\t// processStartTime is a lazy metric which only get initialized after registered.\n\t// so we need to register the metric first and then set the value for it\n\tif err = registrationFunc(processStartTime); err != nil {\n\t\treturn err\n\t}\n\n\tprocessStartTime.WithLabelValues().Set(start)\n\treturn nil\n}","line":{"from":34,"to":51}} {"id":100030449,"name":"getProcessStart","signature":"func getProcessStart() (float64, error)","file":"staging/src/k8s.io/component-base/metrics/processstarttime_others.go","code":"func getProcessStart() (float64, error) {\n\tpid := os.Getpid()\n\tp, err := procfs.NewProc(pid)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif stat, err := p.Stat(); err == nil {\n\t\treturn stat.StartTime()\n\t}\n\treturn 0, err\n}","line":{"from":28,"to":39}} {"id":100030450,"name":"getProcessStart","signature":"func getProcessStart() (float64, error)","file":"staging/src/k8s.io/component-base/metrics/processstarttime_windows.go","code":"func getProcessStart() (float64, error) {\n\tprocessHandle := windows.CurrentProcess()\n\n\tvar creationTime, exitTime, kernelTime, userTime windows.Filetime\n\tif err := windows.GetProcessTimes(processHandle, \u0026creationTime, \u0026exitTime, \u0026kernelTime, \u0026userTime); err != nil {\n\t\treturn 0, err\n\t}\n\treturn float64(creationTime.Nanoseconds() / 1e9), nil\n}","line":{"from":26,"to":34}} {"id":100030451,"name":"init","signature":"func init()","file":"staging/src/k8s.io/component-base/metrics/prometheus/clientgo/leaderelection/metrics.go","code":"func init() {\n\tlegacyregistry.MustRegister(leaderGauge)\n\tleaderelection.SetProvider(prometheusMetricsProvider{})\n}","line":{"from":33,"to":36}} {"id":100030452,"name":"NewLeaderMetric","signature":"func (prometheusMetricsProvider) NewLeaderMetric() leaderelection.SwitchMetric","file":"staging/src/k8s.io/component-base/metrics/prometheus/clientgo/leaderelection/metrics.go","code":"func (prometheusMetricsProvider) NewLeaderMetric() leaderelection.SwitchMetric {\n\treturn \u0026switchAdapter{gauge: leaderGauge}\n}","line":{"from":40,"to":42}} {"id":100030453,"name":"On","signature":"func (s *switchAdapter) On(name string)","file":"staging/src/k8s.io/component-base/metrics/prometheus/clientgo/leaderelection/metrics.go","code":"func (s *switchAdapter) On(name string) {\n\ts.gauge.WithLabelValues(name).Set(1.0)\n}","line":{"from":48,"to":50}} {"id":100030454,"name":"Off","signature":"func (s *switchAdapter) Off(name string)","file":"staging/src/k8s.io/component-base/metrics/prometheus/clientgo/leaderelection/metrics.go","code":"func (s *switchAdapter) Off(name string) {\n\ts.gauge.WithLabelValues(name).Set(0.0)\n}","line":{"from":52,"to":54}} {"id":100030455,"name":"NewControllerManagerMetrics","signature":"func NewControllerManagerMetrics(manager string) *ControllerManagerMetrics","file":"staging/src/k8s.io/component-base/metrics/prometheus/controllers/metrics.go","code":"// NewControllerManagerMetrics create a new ControllerManagerMetrics, with specific manager name.\nfunc NewControllerManagerMetrics(manager string) *ControllerManagerMetrics {\n\tcontrollerMetrics := \u0026ControllerManagerMetrics{\n\t\tmanager: manager,\n\t}\n\treturn controllerMetrics\n}","line":{"from":43,"to":49}} {"id":100030456,"name":"Register","signature":"func Register()","file":"staging/src/k8s.io/component-base/metrics/prometheus/controllers/metrics.go","code":"// Register controller manager metrics.\nfunc Register() {\n\tonce.Do(func() {\n\t\tlegacyregistry.MustRegister(controllerInstanceCount)\n\t})\n}","line":{"from":51,"to":56}} {"id":100030457,"name":"ControllerStarted","signature":"func (a *ControllerManagerMetrics) ControllerStarted(name string)","file":"staging/src/k8s.io/component-base/metrics/prometheus/controllers/metrics.go","code":"// ControllerStarted sets the controllerInstanceCount to 1.\n// These values use set instead of inc/dec to avoid accidentally double counting\n// a controller that starts but fails to properly signal when it crashes.\nfunc (a *ControllerManagerMetrics) ControllerStarted(name string) {\n\tcontrollerInstanceCount.With(k8smetrics.Labels{\"name\": name, \"manager\": a.manager}).Set(float64(1))\n}","line":{"from":58,"to":63}} {"id":100030458,"name":"ControllerStopped","signature":"func (a *ControllerManagerMetrics) ControllerStopped(name string)","file":"staging/src/k8s.io/component-base/metrics/prometheus/controllers/metrics.go","code":"// ControllerStopped sets the controllerInstanceCount to 0.\nfunc (a *ControllerManagerMetrics) ControllerStopped(name string) {\n\tcontrollerInstanceCount.With(k8smetrics.Labels{\"name\": name, \"manager\": a.manager}).Set(float64(0))\n}","line":{"from":65,"to":68}} {"id":100030459,"name":"init","signature":"func init()","file":"staging/src/k8s.io/component-base/metrics/prometheus/feature/metrics.go","code":"func init() {\n\tlegacyregistry.MustRegister(featureInfo)\n}","line":{"from":39,"to":41}} {"id":100030460,"name":"ResetFeatureInfoMetric","signature":"func ResetFeatureInfoMetric()","file":"staging/src/k8s.io/component-base/metrics/prometheus/feature/metrics.go","code":"func ResetFeatureInfoMetric() {\n\tfeatureInfo.Reset()\n}","line":{"from":43,"to":45}} {"id":100030461,"name":"RecordFeatureInfo","signature":"func RecordFeatureInfo(ctx context.Context, name string, stage string, enabled bool)","file":"staging/src/k8s.io/component-base/metrics/prometheus/feature/metrics.go","code":"func RecordFeatureInfo(ctx context.Context, name string, stage string, enabled bool) {\n\tvalue := 0.0\n\tif enabled {\n\t\tvalue = 1.0\n\t}\n\tfeatureInfo.WithContext(ctx).WithLabelValues(name, stage).Set(value)\n}","line":{"from":47,"to":53}} {"id":100030462,"name":"init","signature":"func init()","file":"staging/src/k8s.io/component-base/metrics/prometheus/restclient/metrics.go","code":"func init() {\n\n\tlegacyregistry.MustRegister(requestLatency)\n\tlegacyregistry.MustRegister(requestSize)\n\tlegacyregistry.MustRegister(responseSize)\n\tlegacyregistry.MustRegister(rateLimiterLatency)\n\tlegacyregistry.MustRegister(requestResult)\n\tlegacyregistry.MustRegister(requestRetry)\n\tlegacyregistry.RawMustRegister(execPluginCertTTL)\n\tlegacyregistry.MustRegister(execPluginCertRotation)\n\tmetrics.Register(metrics.RegisterOpts{\n\t\tClientCertExpiry: execPluginCertTTLAdapter,\n\t\tClientCertRotationAge: \u0026rotationAdapter{m: execPluginCertRotation},\n\t\tRequestLatency: \u0026latencyAdapter{m: requestLatency},\n\t\tRequestSize: \u0026sizeAdapter{m: requestSize},\n\t\tResponseSize: \u0026sizeAdapter{m: responseSize},\n\t\tRateLimiterLatency: \u0026latencyAdapter{m: rateLimiterLatency},\n\t\tRequestResult: \u0026resultAdapter{requestResult},\n\t\tRequestRetry: \u0026retryAdapter{requestRetry},\n\t\tExecPluginCalls: \u0026callsAdapter{m: execPluginCalls},\n\t})\n}","line":{"from":157,"to":178}} {"id":100030463,"name":"Observe","signature":"func (l *latencyAdapter) Observe(ctx context.Context, verb string, u url.URL, latency time.Duration)","file":"staging/src/k8s.io/component-base/metrics/prometheus/restclient/metrics.go","code":"func (l *latencyAdapter) Observe(ctx context.Context, verb string, u url.URL, latency time.Duration) {\n\tl.m.WithContext(ctx).WithLabelValues(verb, u.Host).Observe(latency.Seconds())\n}","line":{"from":184,"to":186}} {"id":100030464,"name":"Observe","signature":"func (s *sizeAdapter) Observe(ctx context.Context, verb string, host string, size float64)","file":"staging/src/k8s.io/component-base/metrics/prometheus/restclient/metrics.go","code":"func (s *sizeAdapter) Observe(ctx context.Context, verb string, host string, size float64) {\n\ts.m.WithContext(ctx).WithLabelValues(verb, host).Observe(size)\n}","line":{"from":192,"to":194}} {"id":100030465,"name":"Increment","signature":"func (r *resultAdapter) Increment(ctx context.Context, code, method, host string)","file":"staging/src/k8s.io/component-base/metrics/prometheus/restclient/metrics.go","code":"func (r *resultAdapter) Increment(ctx context.Context, code, method, host string) {\n\tr.m.WithContext(ctx).WithLabelValues(code, method, host).Inc()\n}","line":{"from":200,"to":202}} {"id":100030466,"name":"Set","signature":"func (e *expiryToTTLAdapter) Set(expiry *time.Time)","file":"staging/src/k8s.io/component-base/metrics/prometheus/restclient/metrics.go","code":"func (e *expiryToTTLAdapter) Set(expiry *time.Time) {\n\te.e = expiry\n}","line":{"from":208,"to":210}} {"id":100030467,"name":"Observe","signature":"func (r *rotationAdapter) Observe(d time.Duration)","file":"staging/src/k8s.io/component-base/metrics/prometheus/restclient/metrics.go","code":"func (r *rotationAdapter) Observe(d time.Duration) {\n\tr.m.Observe(d.Seconds())\n}","line":{"from":216,"to":218}} {"id":100030468,"name":"Increment","signature":"func (r *callsAdapter) Increment(code int, callStatus string)","file":"staging/src/k8s.io/component-base/metrics/prometheus/restclient/metrics.go","code":"func (r *callsAdapter) Increment(code int, callStatus string) {\n\tr.m.WithLabelValues(fmt.Sprintf(\"%d\", code), callStatus).Inc()\n}","line":{"from":224,"to":226}} {"id":100030469,"name":"IncrementRetry","signature":"func (r *retryAdapter) IncrementRetry(ctx context.Context, code, method, host string)","file":"staging/src/k8s.io/component-base/metrics/prometheus/restclient/metrics.go","code":"func (r *retryAdapter) IncrementRetry(ctx context.Context, code, method, host string) {\n\tr.m.WithContext(ctx).WithLabelValues(code, method, host).Inc()\n}","line":{"from":232,"to":234}} {"id":100030470,"name":"Register","signature":"func Register(registry k8smetrics.KubeRegistry)","file":"staging/src/k8s.io/component-base/metrics/prometheus/slis/metrics.go","code":"func Register(registry k8smetrics.KubeRegistry) {\n\tregistry.Register(healthcheck)\n\tregistry.Register(healthchecksTotal)\n}","line":{"from":57,"to":60}} {"id":100030471,"name":"ResetHealthMetrics","signature":"func ResetHealthMetrics()","file":"staging/src/k8s.io/component-base/metrics/prometheus/slis/metrics.go","code":"func ResetHealthMetrics() {\n\thealthcheck.Reset()\n\thealthchecksTotal.Reset()\n}","line":{"from":62,"to":65}} {"id":100030472,"name":"ObserveHealthcheck","signature":"func ObserveHealthcheck(ctx context.Context, name string, healthcheckType string, status HealthcheckStatus) error","file":"staging/src/k8s.io/component-base/metrics/prometheus/slis/metrics.go","code":"func ObserveHealthcheck(ctx context.Context, name string, healthcheckType string, status HealthcheckStatus) error {\n\tif status == Success {\n\t\thealthcheck.WithContext(ctx).WithLabelValues(name, healthcheckType).Set(1)\n\t} else {\n\t\thealthcheck.WithContext(ctx).WithLabelValues(name, healthcheckType).Set(0)\n\t}\n\n\thealthchecksTotal.WithContext(ctx).WithLabelValues(name, healthcheckType, string(status)).Inc()\n\treturn nil\n}","line":{"from":67,"to":76}} {"id":100030473,"name":"Install","signature":"func (s SLIMetrics) Install(m mux)","file":"staging/src/k8s.io/component-base/metrics/prometheus/slis/routes.go","code":"// Install adds the DefaultMetrics handler\nfunc (s SLIMetrics) Install(m mux) {\n\tinstallOnce.Do(func() {\n\t\tRegister(Registry)\n\t\tm.Handle(\"/metrics/slis\", metrics.HandlerFor(Registry, metrics.HandlerOpts{}))\n\t})\n}","line":{"from":37,"to":43}} {"id":100030474,"name":"Install","signature":"func (s SLIMetricsWithReset) Install(m mux)","file":"staging/src/k8s.io/component-base/metrics/prometheus/slis/routes.go","code":"// Install adds the DefaultMetrics handler\nfunc (s SLIMetricsWithReset) Install(m mux) {\n\tinstallWithResetOnce.Do(func() {\n\t\tRegister(Registry)\n\t\tm.Handle(\"/metrics/slis\", metrics.HandlerWithReset(Registry, metrics.HandlerOpts{}))\n\t})\n}","line":{"from":47,"to":53}} {"id":100030475,"name":"init","signature":"func init()","file":"staging/src/k8s.io/component-base/metrics/prometheus/version/metrics.go","code":"// RegisterBuildInfo registers the build and version info in a metadata metric in prometheus\nfunc init() {\n\tinfo := version.Get()\n\tlegacyregistry.MustRegister(buildInfo)\n\tbuildInfo.WithLabelValues(info.Major, info.Minor, info.GitVersion, info.GitCommit, info.GitTreeState, info.BuildDate, info.GoVersion, info.Compiler, info.Platform).Set(1)\n}","line":{"from":36,"to":41}} {"id":100030476,"name":"init","signature":"func init()","file":"staging/src/k8s.io/component-base/metrics/prometheus/workqueue/metrics.go","code":"func init() {\n\tfor _, m := range metrics {\n\t\tlegacyregistry.MustRegister(m)\n\t}\n\tworkqueue.SetProvider(prometheusMetricsProvider{})\n}","line":{"from":104,"to":109}} {"id":100030477,"name":"NewDepthMetric","signature":"func (prometheusMetricsProvider) NewDepthMetric(name string) workqueue.GaugeMetric","file":"staging/src/k8s.io/component-base/metrics/prometheus/workqueue/metrics.go","code":"func (prometheusMetricsProvider) NewDepthMetric(name string) workqueue.GaugeMetric {\n\treturn depth.WithLabelValues(name)\n}","line":{"from":111,"to":113}} {"id":100030478,"name":"NewAddsMetric","signature":"func (prometheusMetricsProvider) NewAddsMetric(name string) workqueue.CounterMetric","file":"staging/src/k8s.io/component-base/metrics/prometheus/workqueue/metrics.go","code":"func (prometheusMetricsProvider) NewAddsMetric(name string) workqueue.CounterMetric {\n\treturn adds.WithLabelValues(name)\n}","line":{"from":115,"to":117}} {"id":100030479,"name":"NewLatencyMetric","signature":"func (prometheusMetricsProvider) NewLatencyMetric(name string) workqueue.HistogramMetric","file":"staging/src/k8s.io/component-base/metrics/prometheus/workqueue/metrics.go","code":"func (prometheusMetricsProvider) NewLatencyMetric(name string) workqueue.HistogramMetric {\n\treturn latency.WithLabelValues(name)\n}","line":{"from":119,"to":121}} {"id":100030480,"name":"NewWorkDurationMetric","signature":"func (prometheusMetricsProvider) NewWorkDurationMetric(name string) workqueue.HistogramMetric","file":"staging/src/k8s.io/component-base/metrics/prometheus/workqueue/metrics.go","code":"func (prometheusMetricsProvider) NewWorkDurationMetric(name string) workqueue.HistogramMetric {\n\treturn workDuration.WithLabelValues(name)\n}","line":{"from":123,"to":125}} {"id":100030481,"name":"NewUnfinishedWorkSecondsMetric","signature":"func (prometheusMetricsProvider) NewUnfinishedWorkSecondsMetric(name string) workqueue.SettableGaugeMetric","file":"staging/src/k8s.io/component-base/metrics/prometheus/workqueue/metrics.go","code":"func (prometheusMetricsProvider) NewUnfinishedWorkSecondsMetric(name string) workqueue.SettableGaugeMetric {\n\treturn unfinished.WithLabelValues(name)\n}","line":{"from":127,"to":129}} {"id":100030482,"name":"NewLongestRunningProcessorSecondsMetric","signature":"func (prometheusMetricsProvider) NewLongestRunningProcessorSecondsMetric(name string) workqueue.SettableGaugeMetric","file":"staging/src/k8s.io/component-base/metrics/prometheus/workqueue/metrics.go","code":"func (prometheusMetricsProvider) NewLongestRunningProcessorSecondsMetric(name string) workqueue.SettableGaugeMetric {\n\treturn longestRunningProcessor.WithLabelValues(name)\n}","line":{"from":131,"to":133}} {"id":100030483,"name":"NewRetriesMetric","signature":"func (prometheusMetricsProvider) NewRetriesMetric(name string) workqueue.CounterMetric","file":"staging/src/k8s.io/component-base/metrics/prometheus/workqueue/metrics.go","code":"func (prometheusMetricsProvider) NewRetriesMetric(name string) workqueue.CounterMetric {\n\treturn retries.WithLabelValues(name)\n}","line":{"from":135,"to":137}} {"id":100030484,"name":"NewTimingHistogram","signature":"func NewTimingHistogram(opts TimingHistogramOpts) (TimingHistogram, error)","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/timing_histogram.go","code":"// NewTimingHistogram creates a new TimingHistogram\nfunc NewTimingHistogram(opts TimingHistogramOpts) (TimingHistogram, error) {\n\treturn NewTestableTimingHistogram(time.Now, opts)\n}","line":{"from":77,"to":80}} {"id":100030485,"name":"NewTestableTimingHistogram","signature":"func NewTestableTimingHistogram(nowFunc func() time.Time, opts TimingHistogramOpts) (TimingHistogram, error)","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/timing_histogram.go","code":"// NewTestableTimingHistogram creates a TimingHistogram that uses a mockable clock\nfunc NewTestableTimingHistogram(nowFunc func() time.Time, opts TimingHistogramOpts) (TimingHistogram, error) {\n\tdesc := prometheus.NewDesc(\n\t\tprometheus.BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),\n\t\twrapTimingHelp(opts.Help),\n\t\tnil,\n\t\topts.ConstLabels,\n\t)\n\treturn newTimingHistogram(nowFunc, desc, opts)\n}","line":{"from":82,"to":91}} {"id":100030486,"name":"wrapTimingHelp","signature":"func wrapTimingHelp(given string) string","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/timing_histogram.go","code":"func wrapTimingHelp(given string) string {\n\treturn \"EXPERIMENTAL: \" + given\n}","line":{"from":93,"to":95}} {"id":100030487,"name":"newTimingHistogram","signature":"func newTimingHistogram(nowFunc func() time.Time, desc *prometheus.Desc, opts TimingHistogramOpts, variableLabelValues ...string) (TimingHistogram, error)","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/timing_histogram.go","code":"func newTimingHistogram(nowFunc func() time.Time, desc *prometheus.Desc, opts TimingHistogramOpts, variableLabelValues ...string) (TimingHistogram, error) {\n\tallLabelsM := prometheus.Labels{}\n\tallLabelsS := prometheus.MakeLabelPairs(desc, variableLabelValues)\n\tfor _, pair := range allLabelsS {\n\t\tif pair == nil || pair.Name == nil || pair.Value == nil {\n\t\t\treturn nil, errors.New(\"prometheus.MakeLabelPairs returned a nil\")\n\t\t}\n\t\tallLabelsM[*pair.Name] = *pair.Value\n\t}\n\tweighted, err := newWeightedHistogram(desc, WeightedHistogramOpts{\n\t\tNamespace: opts.Namespace,\n\t\tSubsystem: opts.Subsystem,\n\t\tName: opts.Name,\n\t\tHelp: opts.Help,\n\t\tConstLabels: allLabelsM,\n\t\tBuckets: opts.Buckets,\n\t}, variableLabelValues...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026timingHistogram{\n\t\tnowFunc: nowFunc,\n\t\tweighted: weighted,\n\t\tlastSetTime: nowFunc(),\n\t\tvalue: opts.InitialValue,\n\t}, nil\n}","line":{"from":97,"to":123}} {"id":100030488,"name":"Set","signature":"func (th *timingHistogram) Set(newValue float64)","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/timing_histogram.go","code":"func (th *timingHistogram) Set(newValue float64) {\n\tth.update(func(float64) float64 { return newValue })\n}","line":{"from":137,"to":139}} {"id":100030489,"name":"Inc","signature":"func (th *timingHistogram) Inc()","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/timing_histogram.go","code":"func (th *timingHistogram) Inc() {\n\tth.update(func(oldValue float64) float64 { return oldValue + 1 })\n}","line":{"from":141,"to":143}} {"id":100030490,"name":"Dec","signature":"func (th *timingHistogram) Dec()","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/timing_histogram.go","code":"func (th *timingHistogram) Dec() {\n\tth.update(func(oldValue float64) float64 { return oldValue - 1 })\n}","line":{"from":145,"to":147}} {"id":100030491,"name":"Add","signature":"func (th *timingHistogram) Add(delta float64)","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/timing_histogram.go","code":"func (th *timingHistogram) Add(delta float64) {\n\tth.update(func(oldValue float64) float64 { return oldValue + delta })\n}","line":{"from":149,"to":151}} {"id":100030492,"name":"Sub","signature":"func (th *timingHistogram) Sub(delta float64)","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/timing_histogram.go","code":"func (th *timingHistogram) Sub(delta float64) {\n\tth.update(func(oldValue float64) float64 { return oldValue - delta })\n}","line":{"from":153,"to":155}} {"id":100030493,"name":"SetToCurrentTime","signature":"func (th *timingHistogram) SetToCurrentTime()","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/timing_histogram.go","code":"func (th *timingHistogram) SetToCurrentTime() {\n\tth.update(func(oldValue float64) float64 { return th.nowFunc().Sub(time.Unix(0, 0)).Seconds() })\n}","line":{"from":157,"to":159}} {"id":100030494,"name":"update","signature":"func (th *timingHistogram) update(updateFn func(float64) float64)","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/timing_histogram.go","code":"func (th *timingHistogram) update(updateFn func(float64) float64) {\n\tth.weighted.lock.Lock()\n\tdefer th.weighted.lock.Unlock()\n\tnow := th.nowFunc()\n\tdelta := now.Sub(th.lastSetTime)\n\tvalue := th.value\n\tif delta \u003e 0 {\n\t\tth.weighted.observeWithWeightLocked(value, uint64(delta))\n\t\tth.lastSetTime = now\n\t}\n\tth.value = updateFn(value)\n}","line":{"from":161,"to":172}} {"id":100030495,"name":"Desc","signature":"func (th *timingHistogram) Desc() *prometheus.Desc","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/timing_histogram.go","code":"func (th *timingHistogram) Desc() *prometheus.Desc {\n\treturn th.weighted.Desc()\n}","line":{"from":174,"to":176}} {"id":100030496,"name":"Write","signature":"func (th *timingHistogram) Write(dest *dto.Metric) error","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/timing_histogram.go","code":"func (th *timingHistogram) Write(dest *dto.Metric) error {\n\tth.Add(0) // account for time since last update\n\treturn th.weighted.Write(dest)\n}","line":{"from":178,"to":181}} {"id":100030497,"name":"Describe","signature":"func (th *timingHistogram) Describe(ch chan\u003c- *prometheus.Desc)","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/timing_histogram.go","code":"func (th *timingHistogram) Describe(ch chan\u003c- *prometheus.Desc) {\n\tch \u003c- th.weighted.Desc()\n}","line":{"from":183,"to":185}} {"id":100030498,"name":"Collect","signature":"func (th *timingHistogram) Collect(ch chan\u003c- prometheus.Metric)","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/timing_histogram.go","code":"func (th *timingHistogram) Collect(ch chan\u003c- prometheus.Metric) {\n\tch \u003c- th\n}","line":{"from":187,"to":189}} {"id":100030499,"name":"NewTimingHistogramVec","signature":"func NewTimingHistogramVec(opts TimingHistogramOpts, labelNames ...string) *TimingHistogramVec","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/timing_histogram_vec.go","code":"func NewTimingHistogramVec(opts TimingHistogramOpts, labelNames ...string) *TimingHistogramVec {\n\treturn NewTestableTimingHistogramVec(time.Now, opts, labelNames...)\n}","line":{"from":43,"to":45}} {"id":100030500,"name":"NewTestableTimingHistogramVec","signature":"func NewTestableTimingHistogramVec(nowFunc func() time.Time, opts TimingHistogramOpts, labelNames ...string) *TimingHistogramVec","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/timing_histogram_vec.go","code":"func NewTestableTimingHistogramVec(nowFunc func() time.Time, opts TimingHistogramOpts, labelNames ...string) *TimingHistogramVec {\n\tdesc := prometheus.NewDesc(\n\t\tprometheus.BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),\n\t\twrapTimingHelp(opts.Help),\n\t\tlabelNames,\n\t\topts.ConstLabels,\n\t)\n\treturn \u0026TimingHistogramVec{\n\t\tMetricVec: prometheus.NewMetricVec(desc, func(lvs ...string) prometheus.Metric {\n\t\t\tmetric, err := newTimingHistogram(nowFunc, desc, opts, lvs...)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err) // like in prometheus.newHistogram\n\t\t\t}\n\t\t\treturn metric\n\t\t}),\n\t}\n}","line":{"from":47,"to":63}} {"id":100030501,"name":"GetMetricWith","signature":"func (hv *TimingHistogramVec) GetMetricWith(labels prometheus.Labels) (GaugeOps, error)","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/timing_histogram_vec.go","code":"func (hv *TimingHistogramVec) GetMetricWith(labels prometheus.Labels) (GaugeOps, error) {\n\tmetric, err := hv.MetricVec.GetMetricWith(labels)\n\tif metric != nil {\n\t\treturn metric.(GaugeOps), err\n\t}\n\treturn nil, err\n}","line":{"from":65,"to":71}} {"id":100030502,"name":"GetMetricWithLabelValues","signature":"func (hv *TimingHistogramVec) GetMetricWithLabelValues(lvs ...string) (GaugeOps, error)","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/timing_histogram_vec.go","code":"func (hv *TimingHistogramVec) GetMetricWithLabelValues(lvs ...string) (GaugeOps, error) {\n\tmetric, err := hv.MetricVec.GetMetricWithLabelValues(lvs...)\n\tif metric != nil {\n\t\treturn metric.(GaugeOps), err\n\t}\n\treturn nil, err\n}","line":{"from":73,"to":79}} {"id":100030503,"name":"With","signature":"func (hv *TimingHistogramVec) With(labels prometheus.Labels) GaugeOps","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/timing_histogram_vec.go","code":"func (hv *TimingHistogramVec) With(labels prometheus.Labels) GaugeOps {\n\th, err := hv.GetMetricWith(labels)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn h\n}","line":{"from":81,"to":87}} {"id":100030504,"name":"WithLabelValues","signature":"func (hv *TimingHistogramVec) WithLabelValues(lvs ...string) GaugeOps","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/timing_histogram_vec.go","code":"func (hv *TimingHistogramVec) WithLabelValues(lvs ...string) GaugeOps {\n\th, err := hv.GetMetricWithLabelValues(lvs...)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn h\n}","line":{"from":89,"to":95}} {"id":100030505,"name":"CurryWith","signature":"func (hv *TimingHistogramVec) CurryWith(labels prometheus.Labels) (GaugeVecOps, error)","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/timing_histogram_vec.go","code":"func (hv *TimingHistogramVec) CurryWith(labels prometheus.Labels) (GaugeVecOps, error) {\n\tvec, err := hv.MetricVec.CurryWith(labels)\n\tif vec != nil {\n\t\treturn \u0026TimingHistogramVec{MetricVec: vec}, err\n\t}\n\treturn nil, err\n}","line":{"from":97,"to":103}} {"id":100030506,"name":"MustCurryWith","signature":"func (hv *TimingHistogramVec) MustCurryWith(labels prometheus.Labels) GaugeVecOps","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/timing_histogram_vec.go","code":"func (hv *TimingHistogramVec) MustCurryWith(labels prometheus.Labels) GaugeVecOps {\n\tvec, err := hv.CurryWith(labels)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn vec\n}","line":{"from":105,"to":111}} {"id":100030507,"name":"NewWeightedHistogram","signature":"func NewWeightedHistogram(opts WeightedHistogramOpts) (WeightedHistogram, error)","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/weighted_histogram.go","code":"// NewWeightedHistogram creates a new WeightedHistogram\nfunc NewWeightedHistogram(opts WeightedHistogramOpts) (WeightedHistogram, error) {\n\tdesc := prometheus.NewDesc(\n\t\tprometheus.BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),\n\t\twrapWeightedHelp(opts.Help),\n\t\tnil,\n\t\topts.ConstLabels,\n\t)\n\treturn newWeightedHistogram(desc, opts)\n}","line":{"from":53,"to":62}} {"id":100030508,"name":"wrapWeightedHelp","signature":"func wrapWeightedHelp(given string) string","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/weighted_histogram.go","code":"func wrapWeightedHelp(given string) string {\n\treturn \"EXPERIMENTAL: \" + given\n}","line":{"from":64,"to":66}} {"id":100030509,"name":"newWeightedHistogram","signature":"func newWeightedHistogram(desc *prometheus.Desc, opts WeightedHistogramOpts, variableLabelValues ...string) (*weightedHistogram, error)","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/weighted_histogram.go","code":"func newWeightedHistogram(desc *prometheus.Desc, opts WeightedHistogramOpts, variableLabelValues ...string) (*weightedHistogram, error) {\n\tif len(opts.Buckets) == 0 {\n\t\topts.Buckets = prometheus.DefBuckets\n\t}\n\n\tfor i, upperBound := range opts.Buckets {\n\t\tif i \u003c len(opts.Buckets)-1 {\n\t\t\tif upperBound \u003e= opts.Buckets[i+1] {\n\t\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\t\"histogram buckets must be in increasing order: %f \u003e= %f\",\n\t\t\t\t\tupperBound, opts.Buckets[i+1],\n\t\t\t\t)\n\t\t\t}\n\t\t} else {\n\t\t\tif math.IsInf(upperBound, +1) {\n\t\t\t\t// The +Inf bucket is implicit. Remove it here.\n\t\t\t\topts.Buckets = opts.Buckets[:i]\n\t\t\t}\n\t\t}\n\t}\n\tupperBounds := make([]float64, len(opts.Buckets))\n\tcopy(upperBounds, opts.Buckets)\n\n\treturn \u0026weightedHistogram{\n\t\tdesc: desc,\n\t\tvariableLabelValues: variableLabelValues,\n\t\tupperBounds: upperBounds,\n\t\tbuckets: make([]uint64, len(upperBounds)+1),\n\t\thotCount: initialHotCount,\n\t}, nil\n}","line":{"from":68,"to":98}} {"id":100030510,"name":"ObserveWithWeight","signature":"func (sh *weightedHistogram) ObserveWithWeight(value float64, weight uint64)","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/weighted_histogram.go","code":"func (sh *weightedHistogram) ObserveWithWeight(value float64, weight uint64) {\n\tidx := sort.SearchFloat64s(sh.upperBounds, value)\n\tsh.lock.Lock()\n\tdefer sh.lock.Unlock()\n\tsh.updateLocked(idx, value, weight)\n}","line":{"from":143,"to":148}} {"id":100030511,"name":"observeWithWeightLocked","signature":"func (sh *weightedHistogram) observeWithWeightLocked(value float64, weight uint64)","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/weighted_histogram.go","code":"func (sh *weightedHistogram) observeWithWeightLocked(value float64, weight uint64) {\n\tidx := sort.SearchFloat64s(sh.upperBounds, value)\n\tsh.updateLocked(idx, value, weight)\n}","line":{"from":150,"to":153}} {"id":100030512,"name":"updateLocked","signature":"func (sh *weightedHistogram) updateLocked(idx int, value float64, weight uint64)","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/weighted_histogram.go","code":"func (sh *weightedHistogram) updateLocked(idx int, value float64, weight uint64) {\n\tsh.buckets[idx] += weight\n\tnewSumHot := sh.sumHot + float64(weight)*value\n\tsh.hotCount++\n\tif sh.hotCount \u003e= 0 {\n\t\tsh.hotCount = initialHotCount\n\t\tif math.Abs(newSumHot) \u003e sh.transferThreshold {\n\t\t\tnewSumCold := sh.sumCold + newSumHot\n\t\t\tsh.sumCold = newSumCold\n\t\t\tsh.transferThreshold = math.Abs(newSumCold / 67108864)\n\t\t\tsh.sumHot = 0\n\t\t\treturn\n\t\t}\n\t}\n\tsh.sumHot = newSumHot\n}","line":{"from":155,"to":170}} {"id":100030513,"name":"Desc","signature":"func (sh *weightedHistogram) Desc() *prometheus.Desc","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/weighted_histogram.go","code":"func (sh *weightedHistogram) Desc() *prometheus.Desc {\n\treturn sh.desc\n}","line":{"from":172,"to":174}} {"id":100030514,"name":"Write","signature":"func (sh *weightedHistogram) Write(dest *dto.Metric) error","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/weighted_histogram.go","code":"func (sh *weightedHistogram) Write(dest *dto.Metric) error {\n\tcount, sum, buckets := func() (uint64, float64, map[float64]uint64) {\n\t\tsh.lock.Lock()\n\t\tdefer sh.lock.Unlock()\n\t\tnBounds := len(sh.upperBounds)\n\t\tbuckets := make(map[float64]uint64, nBounds)\n\t\tvar count uint64\n\t\tfor idx, upperBound := range sh.upperBounds {\n\t\t\tcount += sh.buckets[idx]\n\t\t\tbuckets[upperBound] = count\n\t\t}\n\t\tcount += sh.buckets[nBounds]\n\t\treturn count, sh.sumHot + sh.sumCold, buckets\n\t}()\n\tmetric, err := prometheus.NewConstHistogram(sh.desc, count, sum, buckets, sh.variableLabelValues...)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn metric.Write(dest)\n}","line":{"from":176,"to":195}} {"id":100030515,"name":"Describe","signature":"func (sh *weightedHistogram) Describe(ch chan\u003c- *prometheus.Desc)","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/weighted_histogram.go","code":"func (sh *weightedHistogram) Describe(ch chan\u003c- *prometheus.Desc) {\n\tch \u003c- sh.desc\n}","line":{"from":197,"to":199}} {"id":100030516,"name":"Collect","signature":"func (sh *weightedHistogram) Collect(ch chan\u003c- prometheus.Metric)","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/weighted_histogram.go","code":"func (sh *weightedHistogram) Collect(ch chan\u003c- prometheus.Metric) {\n\tch \u003c- sh\n}","line":{"from":201,"to":203}} {"id":100030517,"name":"NewWeightedHistogramVec","signature":"func NewWeightedHistogramVec(opts WeightedHistogramOpts, labelNames ...string) *WeightedHistogramVec","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/weighted_histogram_vec.go","code":"func NewWeightedHistogramVec(opts WeightedHistogramOpts, labelNames ...string) *WeightedHistogramVec {\n\tdesc := prometheus.NewDesc(\n\t\tprometheus.BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),\n\t\twrapWeightedHelp(opts.Help),\n\t\tlabelNames,\n\t\topts.ConstLabels,\n\t)\n\treturn \u0026WeightedHistogramVec{\n\t\tMetricVec: prometheus.NewMetricVec(desc, func(lvs ...string) prometheus.Metric {\n\t\t\tmetric, err := newWeightedHistogram(desc, opts, lvs...)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err) // like in prometheus.newHistogram\n\t\t\t}\n\t\t\treturn metric\n\t\t}),\n\t}\n}","line":{"from":42,"to":58}} {"id":100030518,"name":"GetMetricWith","signature":"func (hv *WeightedHistogramVec) GetMetricWith(labels prometheus.Labels) (WeightedObserver, error)","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/weighted_histogram_vec.go","code":"func (hv *WeightedHistogramVec) GetMetricWith(labels prometheus.Labels) (WeightedObserver, error) {\n\tmetric, err := hv.MetricVec.GetMetricWith(labels)\n\tif metric != nil {\n\t\treturn metric.(WeightedObserver), err\n\t}\n\treturn nil, err\n}","line":{"from":60,"to":66}} {"id":100030519,"name":"GetMetricWithLabelValues","signature":"func (hv *WeightedHistogramVec) GetMetricWithLabelValues(lvs ...string) (WeightedObserver, error)","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/weighted_histogram_vec.go","code":"func (hv *WeightedHistogramVec) GetMetricWithLabelValues(lvs ...string) (WeightedObserver, error) {\n\tmetric, err := hv.MetricVec.GetMetricWithLabelValues(lvs...)\n\tif metric != nil {\n\t\treturn metric.(WeightedObserver), err\n\t}\n\treturn nil, err\n}","line":{"from":68,"to":74}} {"id":100030520,"name":"With","signature":"func (hv *WeightedHistogramVec) With(labels prometheus.Labels) WeightedObserver","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/weighted_histogram_vec.go","code":"func (hv *WeightedHistogramVec) With(labels prometheus.Labels) WeightedObserver {\n\th, err := hv.GetMetricWith(labels)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn h\n}","line":{"from":76,"to":82}} {"id":100030521,"name":"WithLabelValues","signature":"func (hv *WeightedHistogramVec) WithLabelValues(lvs ...string) WeightedObserver","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/weighted_histogram_vec.go","code":"func (hv *WeightedHistogramVec) WithLabelValues(lvs ...string) WeightedObserver {\n\th, err := hv.GetMetricWithLabelValues(lvs...)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn h\n}","line":{"from":84,"to":90}} {"id":100030522,"name":"CurryWith","signature":"func (hv *WeightedHistogramVec) CurryWith(labels prometheus.Labels) (WeightedObserverVec, error)","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/weighted_histogram_vec.go","code":"func (hv *WeightedHistogramVec) CurryWith(labels prometheus.Labels) (WeightedObserverVec, error) {\n\tvec, err := hv.MetricVec.CurryWith(labels)\n\tif vec != nil {\n\t\treturn \u0026WeightedHistogramVec{MetricVec: vec}, err\n\t}\n\treturn nil, err\n}","line":{"from":92,"to":98}} {"id":100030523,"name":"MustCurryWith","signature":"func (hv *WeightedHistogramVec) MustCurryWith(labels prometheus.Labels) WeightedObserverVec","file":"staging/src/k8s.io/component-base/metrics/prometheusextension/weighted_histogram_vec.go","code":"func (hv *WeightedHistogramVec) MustCurryWith(labels prometheus.Labels) WeightedObserverVec {\n\tvec, err := hv.CurryWith(labels)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn vec\n}","line":{"from":100,"to":106}} {"id":100030524,"name":"shouldHide","signature":"func shouldHide(currentVersion *semver.Version, deprecatedVersion *semver.Version) bool","file":"staging/src/k8s.io/component-base/metrics/registry.go","code":"// shouldHide be used to check if a specific metric with deprecated version should be hidden\n// according to metrics deprecation lifecycle.\nfunc shouldHide(currentVersion *semver.Version, deprecatedVersion *semver.Version) bool {\n\tguardVersion, err := semver.Make(fmt.Sprintf(\"%d.%d.0\", currentVersion.Major, currentVersion.Minor))\n\tif err != nil {\n\t\tpanic(\"failed to make version from current version\")\n\t}\n\n\tif deprecatedVersion.LT(guardVersion) {\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":66,"to":79}} {"id":100030525,"name":"ValidateShowHiddenMetricsVersion","signature":"func ValidateShowHiddenMetricsVersion(v string) []error","file":"staging/src/k8s.io/component-base/metrics/registry.go","code":"// ValidateShowHiddenMetricsVersion checks invalid version for which show hidden metrics.\nfunc ValidateShowHiddenMetricsVersion(v string) []error {\n\terr := validateShowHiddenMetricsVersion(parseVersion(version.Get()), v)\n\tif err != nil {\n\t\treturn []error{err}\n\t}\n\n\treturn nil\n}","line":{"from":81,"to":89}} {"id":100030526,"name":"SetDisabledMetric","signature":"func SetDisabledMetric(name string)","file":"staging/src/k8s.io/component-base/metrics/registry.go","code":"func SetDisabledMetric(name string) {\n\tdisabledMetricsLock.Lock()\n\tdefer disabledMetricsLock.Unlock()\n\tdisabledMetrics[name] = struct{}{}\n\tdisabledMetricsTotal.Inc()\n}","line":{"from":91,"to":96}} {"id":100030527,"name":"SetShowHidden","signature":"func SetShowHidden()","file":"staging/src/k8s.io/component-base/metrics/registry.go","code":"// SetShowHidden will enable showing hidden metrics. This will no-opt\n// after the initial call\nfunc SetShowHidden() {\n\tshowHiddenOnce.Do(func() {\n\t\tshowHidden.Store(true)\n\n\t\t// re-register collectors that has been hidden in phase of last registry.\n\t\tfor _, r := range registries {\n\t\t\tr.enableHiddenCollectors()\n\t\t\tr.enableHiddenStableCollectors()\n\t\t}\n\t})\n}","line":{"from":98,"to":110}} {"id":100030528,"name":"ShouldShowHidden","signature":"func ShouldShowHidden() bool","file":"staging/src/k8s.io/component-base/metrics/registry.go","code":"// ShouldShowHidden returns whether showing hidden deprecated metrics\n// is enabled. While the primary usecase for this is internal (to determine\n// registration behavior) this can also be used to introspect\nfunc ShouldShowHidden() bool {\n\treturn showHidden.Load()\n}","line":{"from":112,"to":117}} {"id":100030529,"name":"Register","signature":"func (kr *kubeRegistry) Register(c Registerable) error","file":"staging/src/k8s.io/component-base/metrics/registry.go","code":"// Register registers a new Collector to be included in metrics\n// collection. It returns an error if the descriptors provided by the\n// Collector are invalid or if they — in combination with descriptors of\n// already registered Collectors — do not fulfill the consistency and\n// uniqueness criteria described in the documentation of metric.Desc.\nfunc (kr *kubeRegistry) Register(c Registerable) error {\n\tif c.Create(\u0026kr.version) {\n\t\tdefer kr.addResettable(c)\n\t\treturn kr.PromRegistry.Register(c)\n\t}\n\n\tkr.trackHiddenCollector(c)\n\treturn nil\n}","line":{"from":180,"to":193}} {"id":100030530,"name":"Registerer","signature":"func (kr *kubeRegistry) Registerer() prometheus.Registerer","file":"staging/src/k8s.io/component-base/metrics/registry.go","code":"// Registerer exposes the underlying prometheus.Registerer\nfunc (kr *kubeRegistry) Registerer() prometheus.Registerer {\n\treturn kr.PromRegistry\n}","line":{"from":195,"to":198}} {"id":100030531,"name":"Gatherer","signature":"func (kr *kubeRegistry) Gatherer() prometheus.Gatherer","file":"staging/src/k8s.io/component-base/metrics/registry.go","code":"// Gatherer exposes the underlying prometheus.Gatherer\nfunc (kr *kubeRegistry) Gatherer() prometheus.Gatherer {\n\treturn kr.PromRegistry\n}","line":{"from":200,"to":203}} {"id":100030532,"name":"MustRegister","signature":"func (kr *kubeRegistry) MustRegister(cs ...Registerable)","file":"staging/src/k8s.io/component-base/metrics/registry.go","code":"// MustRegister works like Register but registers any number of\n// Collectors and panics upon the first registration that causes an\n// error.\nfunc (kr *kubeRegistry) MustRegister(cs ...Registerable) {\n\tmetrics := make([]prometheus.Collector, 0, len(cs))\n\tfor _, c := range cs {\n\t\tif c.Create(\u0026kr.version) {\n\t\t\tmetrics = append(metrics, c)\n\t\t\tkr.addResettable(c)\n\t\t} else {\n\t\t\tkr.trackHiddenCollector(c)\n\t\t}\n\t}\n\tkr.PromRegistry.MustRegister(metrics...)\n}","line":{"from":205,"to":219}} {"id":100030533,"name":"CustomRegister","signature":"func (kr *kubeRegistry) CustomRegister(c StableCollector) error","file":"staging/src/k8s.io/component-base/metrics/registry.go","code":"// CustomRegister registers a new custom collector.\nfunc (kr *kubeRegistry) CustomRegister(c StableCollector) error {\n\tkr.trackStableCollectors(c)\n\tdefer kr.addResettable(c)\n\tif c.Create(\u0026kr.version, c) {\n\t\treturn kr.PromRegistry.Register(c)\n\t}\n\treturn nil\n}","line":{"from":221,"to":229}} {"id":100030534,"name":"CustomMustRegister","signature":"func (kr *kubeRegistry) CustomMustRegister(cs ...StableCollector)","file":"staging/src/k8s.io/component-base/metrics/registry.go","code":"// CustomMustRegister works like CustomRegister but registers any number of\n// StableCollectors and panics upon the first registration that causes an\n// error.\nfunc (kr *kubeRegistry) CustomMustRegister(cs ...StableCollector) {\n\tkr.trackStableCollectors(cs...)\n\tcollectors := make([]prometheus.Collector, 0, len(cs))\n\tfor _, c := range cs {\n\t\tif c.Create(\u0026kr.version, c) {\n\t\t\tkr.addResettable(c)\n\t\t\tcollectors = append(collectors, c)\n\t\t}\n\t}\n\tkr.PromRegistry.MustRegister(collectors...)\n}","line":{"from":231,"to":244}} {"id":100030535,"name":"RawMustRegister","signature":"func (kr *kubeRegistry) RawMustRegister(cs ...prometheus.Collector)","file":"staging/src/k8s.io/component-base/metrics/registry.go","code":"// RawMustRegister takes a native prometheus.Collector and registers the collector\n// to the registry. This bypasses metrics safety checks, so should only be used\n// to register custom prometheus collectors.\n//\n// Deprecated\nfunc (kr *kubeRegistry) RawMustRegister(cs ...prometheus.Collector) {\n\tkr.PromRegistry.MustRegister(cs...)\n\tfor _, c := range cs {\n\t\tkr.addResettable(c)\n\t}\n}","line":{"from":246,"to":256}} {"id":100030536,"name":"addResettable","signature":"func (kr *kubeRegistry) addResettable(i interface{})","file":"staging/src/k8s.io/component-base/metrics/registry.go","code":"// addResettable will automatically add our metric to our reset\n// list if it satisfies the interface\nfunc (kr *kubeRegistry) addResettable(i interface{}) {\n\tkr.resetLock.Lock()\n\tdefer kr.resetLock.Unlock()\n\tif resettable, ok := i.(resettable); ok {\n\t\tkr.resettables = append(kr.resettables, resettable)\n\t}\n}","line":{"from":258,"to":266}} {"id":100030537,"name":"Unregister","signature":"func (kr *kubeRegistry) Unregister(collector Collector) bool","file":"staging/src/k8s.io/component-base/metrics/registry.go","code":"// Unregister unregisters the Collector that equals the Collector passed\n// in as an argument. (Two Collectors are considered equal if their\n// Describe method yields the same set of descriptors.) The function\n// returns whether a Collector was unregistered. Note that an unchecked\n// Collector cannot be unregistered (as its Describe method does not\n// yield any descriptor).\nfunc (kr *kubeRegistry) Unregister(collector Collector) bool {\n\treturn kr.PromRegistry.Unregister(collector)\n}","line":{"from":268,"to":276}} {"id":100030538,"name":"Gather","signature":"func (kr *kubeRegistry) Gather() ([]*dto.MetricFamily, error)","file":"staging/src/k8s.io/component-base/metrics/registry.go","code":"// Gather calls the Collect method of the registered Collectors and then\n// gathers the collected metrics into a lexicographically sorted slice\n// of uniquely named MetricFamily protobufs. Gather ensures that the\n// returned slice is valid and self-consistent so that it can be used\n// for valid exposition. As an exception to the strict consistency\n// requirements described for metric.Desc, Gather will tolerate\n// different sets of label names for metrics of the same metric family.\nfunc (kr *kubeRegistry) Gather() ([]*dto.MetricFamily, error) {\n\treturn kr.PromRegistry.Gather()\n}","line":{"from":278,"to":287}} {"id":100030539,"name":"trackHiddenCollector","signature":"func (kr *kubeRegistry) trackHiddenCollector(c Registerable)","file":"staging/src/k8s.io/component-base/metrics/registry.go","code":"// trackHiddenCollector stores all hidden collectors.\nfunc (kr *kubeRegistry) trackHiddenCollector(c Registerable) {\n\tkr.hiddenCollectorsLock.Lock()\n\tdefer kr.hiddenCollectorsLock.Unlock()\n\n\tkr.hiddenCollectors[c.FQName()] = c\n\thiddenMetricsTotal.Inc()\n}","line":{"from":289,"to":296}} {"id":100030540,"name":"trackStableCollectors","signature":"func (kr *kubeRegistry) trackStableCollectors(cs ...StableCollector)","file":"staging/src/k8s.io/component-base/metrics/registry.go","code":"// trackStableCollectors stores all custom collectors.\nfunc (kr *kubeRegistry) trackStableCollectors(cs ...StableCollector) {\n\tkr.stableCollectorsLock.Lock()\n\tdefer kr.stableCollectorsLock.Unlock()\n\n\tkr.stableCollectors = append(kr.stableCollectors, cs...)\n}","line":{"from":298,"to":304}} {"id":100030541,"name":"enableHiddenCollectors","signature":"func (kr *kubeRegistry) enableHiddenCollectors()","file":"staging/src/k8s.io/component-base/metrics/registry.go","code":"// enableHiddenCollectors will re-register all of the hidden collectors.\nfunc (kr *kubeRegistry) enableHiddenCollectors() {\n\tif len(kr.hiddenCollectors) == 0 {\n\t\treturn\n\t}\n\n\tkr.hiddenCollectorsLock.Lock()\n\tcs := make([]Registerable, 0, len(kr.hiddenCollectors))\n\n\tfor _, c := range kr.hiddenCollectors {\n\t\tc.ClearState()\n\t\tcs = append(cs, c)\n\t}\n\n\tkr.hiddenCollectors = make(map[string]Registerable)\n\tkr.hiddenCollectorsLock.Unlock()\n\tkr.MustRegister(cs...)\n}","line":{"from":306,"to":323}} {"id":100030542,"name":"enableHiddenStableCollectors","signature":"func (kr *kubeRegistry) enableHiddenStableCollectors()","file":"staging/src/k8s.io/component-base/metrics/registry.go","code":"// enableHiddenStableCollectors will re-register the stable collectors if there is one or more hidden metrics in it.\n// Since we can not register a metrics twice, so we have to unregister first then register again.\nfunc (kr *kubeRegistry) enableHiddenStableCollectors() {\n\tif len(kr.stableCollectors) == 0 {\n\t\treturn\n\t}\n\n\tkr.stableCollectorsLock.Lock()\n\n\tcs := make([]StableCollector, 0, len(kr.stableCollectors))\n\tfor _, c := range kr.stableCollectors {\n\t\tif len(c.HiddenMetrics()) \u003e 0 {\n\t\t\tkr.Unregister(c) // unregister must happens before clear state, otherwise no metrics would be unregister\n\t\t\tc.ClearState()\n\t\t\tcs = append(cs, c)\n\t\t}\n\t}\n\n\tkr.stableCollectors = nil\n\tkr.stableCollectorsLock.Unlock()\n\tkr.CustomMustRegister(cs...)\n}","line":{"from":325,"to":346}} {"id":100030543,"name":"Reset","signature":"func (kr *kubeRegistry) Reset()","file":"staging/src/k8s.io/component-base/metrics/registry.go","code":"// Reset invokes Reset on all metrics that are resettable.\nfunc (kr *kubeRegistry) Reset() {\n\tkr.resetLock.RLock()\n\tdefer kr.resetLock.RUnlock()\n\tfor _, r := range kr.resettables {\n\t\tr.Reset()\n\t}\n}","line":{"from":348,"to":355}} {"id":100030544,"name":"newKubeRegistry","signature":"func newKubeRegistry(v apimachineryversion.Info) *kubeRegistry","file":"staging/src/k8s.io/component-base/metrics/registry.go","code":"func newKubeRegistry(v apimachineryversion.Info) *kubeRegistry {\n\tr := \u0026kubeRegistry{\n\t\tPromRegistry: prometheus.NewRegistry(),\n\t\tversion: parseVersion(v),\n\t\thiddenCollectors: make(map[string]Registerable),\n\t\tresettables: make([]resettable, 0),\n\t}\n\n\tregistriesLock.Lock()\n\tdefer registriesLock.Unlock()\n\tregistries = append(registries, r)\n\n\treturn r\n}","line":{"from":360,"to":373}} {"id":100030545,"name":"NewKubeRegistry","signature":"func NewKubeRegistry() KubeRegistry","file":"staging/src/k8s.io/component-base/metrics/registry.go","code":"// NewKubeRegistry creates a new vanilla Registry\nfunc NewKubeRegistry() KubeRegistry {\n\tr := newKubeRegistry(BuildVersion())\n\treturn r\n}","line":{"from":375,"to":379}} {"id":100030546,"name":"RegisterMetaMetrics","signature":"func (r *kubeRegistry) RegisterMetaMetrics()","file":"staging/src/k8s.io/component-base/metrics/registry.go","code":"func (r *kubeRegistry) RegisterMetaMetrics() {\n\tr.MustRegister(registeredMetrics)\n\tr.MustRegister(disabledMetricsTotal)\n\tr.MustRegister(hiddenMetricsTotal)\n}","line":{"from":381,"to":385}} {"id":100030547,"name":"NewSummary","signature":"func NewSummary(opts *SummaryOpts) *Summary","file":"staging/src/k8s.io/component-base/metrics/summary.go","code":"// NewSummary returns an object which is Summary-like. However, nothing\n// will be measured until the summary is registered somewhere.\n//\n// DEPRECATED: as per the metrics overhaul KEP\nfunc NewSummary(opts *SummaryOpts) *Summary {\n\topts.StabilityLevel.setDefaults()\n\n\ts := \u0026Summary{\n\t\tSummaryOpts: opts,\n\t\tlazyMetric: lazyMetric{stabilityLevel: opts.StabilityLevel},\n\t}\n\ts.setPrometheusSummary(noopMetric{})\n\ts.lazyInit(s, BuildFQName(opts.Namespace, opts.Subsystem, opts.Name))\n\treturn s\n}","line":{"from":43,"to":57}} {"id":100030548,"name":"setPrometheusSummary","signature":"func (s *Summary) setPrometheusSummary(summary prometheus.Summary)","file":"staging/src/k8s.io/component-base/metrics/summary.go","code":"// setPrometheusSummary sets the underlying KubeGauge object, i.e. the thing that does the measurement.\nfunc (s *Summary) setPrometheusSummary(summary prometheus.Summary) {\n\ts.ObserverMetric = summary\n\ts.initSelfCollection(summary)\n}","line":{"from":59,"to":63}} {"id":100030549,"name":"DeprecatedVersion","signature":"func (s *Summary) DeprecatedVersion() *semver.Version","file":"staging/src/k8s.io/component-base/metrics/summary.go","code":"// DeprecatedVersion returns a pointer to the Version or nil\nfunc (s *Summary) DeprecatedVersion() *semver.Version {\n\treturn parseSemver(s.SummaryOpts.DeprecatedVersion)\n}","line":{"from":65,"to":68}} {"id":100030550,"name":"initializeMetric","signature":"func (s *Summary) initializeMetric()","file":"staging/src/k8s.io/component-base/metrics/summary.go","code":"// initializeMetric invokes the actual prometheus.Summary object instantiation\n// and stores a reference to it\nfunc (s *Summary) initializeMetric() {\n\ts.SummaryOpts.annotateStabilityLevel()\n\t// this actually creates the underlying prometheus gauge.\n\ts.setPrometheusSummary(prometheus.NewSummary(s.SummaryOpts.toPromSummaryOpts()))\n}","line":{"from":70,"to":76}} {"id":100030551,"name":"initializeDeprecatedMetric","signature":"func (s *Summary) initializeDeprecatedMetric()","file":"staging/src/k8s.io/component-base/metrics/summary.go","code":"// initializeDeprecatedMetric invokes the actual prometheus.Summary object instantiation\n// but modifies the Help description prior to object instantiation.\nfunc (s *Summary) initializeDeprecatedMetric() {\n\ts.SummaryOpts.markDeprecated()\n\ts.initializeMetric()\n}","line":{"from":78,"to":83}} {"id":100030552,"name":"WithContext","signature":"func (s *Summary) WithContext(ctx context.Context) ObserverMetric","file":"staging/src/k8s.io/component-base/metrics/summary.go","code":"// WithContext allows the normal Summary metric to pass in context. The context is no-op now.\nfunc (s *Summary) WithContext(ctx context.Context) ObserverMetric {\n\treturn s.ObserverMetric\n}","line":{"from":85,"to":88}} {"id":100030553,"name":"NewSummaryVec","signature":"func NewSummaryVec(opts *SummaryOpts, labels []string) *SummaryVec","file":"staging/src/k8s.io/component-base/metrics/summary.go","code":"// NewSummaryVec returns an object which satisfies kubeCollector and wraps the\n// prometheus.SummaryVec object. However, the object returned will not measure\n// anything unless the collector is first registered, since the metric is lazily instantiated,\n// and only members extracted after\n// registration will actually measure anything.\n//\n// DEPRECATED: as per the metrics overhaul KEP\nfunc NewSummaryVec(opts *SummaryOpts, labels []string) *SummaryVec {\n\topts.StabilityLevel.setDefaults()\n\n\tfqName := BuildFQName(opts.Namespace, opts.Subsystem, opts.Name)\n\tallowListLock.RLock()\n\tif allowList, ok := labelValueAllowLists[fqName]; ok {\n\t\topts.LabelValueAllowLists = allowList\n\t}\n\tallowListLock.RUnlock()\n\n\tv := \u0026SummaryVec{\n\t\tSummaryOpts: opts,\n\t\toriginalLabels: labels,\n\t\tlazyMetric: lazyMetric{stabilityLevel: opts.StabilityLevel},\n\t}\n\tv.lazyInit(v, fqName)\n\treturn v\n}","line":{"from":101,"to":125}} {"id":100030554,"name":"DeprecatedVersion","signature":"func (v *SummaryVec) DeprecatedVersion() *semver.Version","file":"staging/src/k8s.io/component-base/metrics/summary.go","code":"// DeprecatedVersion returns a pointer to the Version or nil\nfunc (v *SummaryVec) DeprecatedVersion() *semver.Version {\n\treturn parseSemver(v.SummaryOpts.DeprecatedVersion)\n}","line":{"from":127,"to":130}} {"id":100030555,"name":"initializeMetric","signature":"func (v *SummaryVec) initializeMetric()","file":"staging/src/k8s.io/component-base/metrics/summary.go","code":"func (v *SummaryVec) initializeMetric() {\n\tv.SummaryOpts.annotateStabilityLevel()\n\tv.SummaryVec = prometheus.NewSummaryVec(v.SummaryOpts.toPromSummaryOpts(), v.originalLabels)\n}","line":{"from":132,"to":135}} {"id":100030556,"name":"initializeDeprecatedMetric","signature":"func (v *SummaryVec) initializeDeprecatedMetric()","file":"staging/src/k8s.io/component-base/metrics/summary.go","code":"func (v *SummaryVec) initializeDeprecatedMetric() {\n\tv.SummaryOpts.markDeprecated()\n\tv.initializeMetric()\n}","line":{"from":137,"to":140}} {"id":100030557,"name":"WithLabelValues","signature":"func (v *SummaryVec) WithLabelValues(lvs ...string) ObserverMetric","file":"staging/src/k8s.io/component-base/metrics/summary.go","code":"// WithLabelValues returns the ObserverMetric for the given slice of label\n// values (same order as the VariableLabels in Desc). If that combination of\n// label values is accessed for the first time, a new ObserverMetric is created IFF the summaryVec\n// has been registered to a metrics registry.\nfunc (v *SummaryVec) WithLabelValues(lvs ...string) ObserverMetric {\n\tif !v.IsCreated() {\n\t\treturn noop\n\t}\n\tif v.LabelValueAllowLists != nil {\n\t\tv.LabelValueAllowLists.ConstrainToAllowedList(v.originalLabels, lvs)\n\t}\n\treturn v.SummaryVec.WithLabelValues(lvs...)\n}","line":{"from":153,"to":165}} {"id":100030558,"name":"With","signature":"func (v *SummaryVec) With(labels map[string]string) ObserverMetric","file":"staging/src/k8s.io/component-base/metrics/summary.go","code":"// With returns the ObserverMetric for the given Labels map (the label names\n// must match those of the VariableLabels in Desc). If that label map is\n// accessed for the first time, a new ObserverMetric is created IFF the summaryVec has\n// been registered to a metrics registry.\nfunc (v *SummaryVec) With(labels map[string]string) ObserverMetric {\n\tif !v.IsCreated() {\n\t\treturn noop\n\t}\n\tif v.LabelValueAllowLists != nil {\n\t\tv.LabelValueAllowLists.ConstrainLabelMap(labels)\n\t}\n\treturn v.SummaryVec.With(labels)\n}","line":{"from":167,"to":179}} {"id":100030559,"name":"Delete","signature":"func (v *SummaryVec) Delete(labels map[string]string) bool","file":"staging/src/k8s.io/component-base/metrics/summary.go","code":"// Delete deletes the metric where the variable labels are the same as those\n// passed in as labels. It returns true if a metric was deleted.\n//\n// It is not an error if the number and names of the Labels are inconsistent\n// with those of the VariableLabels in Desc. However, such inconsistent Labels\n// can never match an actual metric, so the method will always return false in\n// that case.\nfunc (v *SummaryVec) Delete(labels map[string]string) bool {\n\tif !v.IsCreated() {\n\t\treturn false // since we haven't created the metric, we haven't deleted a metric with the passed in values\n\t}\n\treturn v.SummaryVec.Delete(labels)\n}","line":{"from":181,"to":193}} {"id":100030560,"name":"Reset","signature":"func (v *SummaryVec) Reset()","file":"staging/src/k8s.io/component-base/metrics/summary.go","code":"// Reset deletes all metrics in this vector.\nfunc (v *SummaryVec) Reset() {\n\tif !v.IsCreated() {\n\t\treturn\n\t}\n\n\tv.SummaryVec.Reset()\n}","line":{"from":195,"to":202}} {"id":100030561,"name":"WithContext","signature":"func (v *SummaryVec) WithContext(ctx context.Context) *SummaryVecWithContext","file":"staging/src/k8s.io/component-base/metrics/summary.go","code":"// WithContext returns wrapped SummaryVec with context\nfunc (v *SummaryVec) WithContext(ctx context.Context) *SummaryVecWithContext {\n\treturn \u0026SummaryVecWithContext{\n\t\tctx: ctx,\n\t\tSummaryVec: v,\n\t}\n}","line":{"from":204,"to":210}} {"id":100030562,"name":"WithLabelValues","signature":"func (vc *SummaryVecWithContext) WithLabelValues(lvs ...string) ObserverMetric","file":"staging/src/k8s.io/component-base/metrics/summary.go","code":"// WithLabelValues is the wrapper of SummaryVec.WithLabelValues.\nfunc (vc *SummaryVecWithContext) WithLabelValues(lvs ...string) ObserverMetric {\n\treturn vc.SummaryVec.WithLabelValues(lvs...)\n}","line":{"from":218,"to":221}} {"id":100030563,"name":"With","signature":"func (vc *SummaryVecWithContext) With(labels map[string]string) ObserverMetric","file":"staging/src/k8s.io/component-base/metrics/summary.go","code":"// With is the wrapper of SummaryVec.With.\nfunc (vc *SummaryVecWithContext) With(labels map[string]string) ObserverMetric {\n\treturn vc.SummaryVec.With(labels)\n}","line":{"from":223,"to":226}} {"id":100030564,"name":"NewTimingHistogram","signature":"func NewTimingHistogram(opts *TimingHistogramOpts) *TimingHistogram","file":"staging/src/k8s.io/component-base/metrics/timing_histogram.go","code":"// NewTimingHistogram returns an object which is TimingHistogram-like. However, nothing\n// will be measured until the histogram is registered somewhere.\nfunc NewTimingHistogram(opts *TimingHistogramOpts) *TimingHistogram {\n\treturn NewTestableTimingHistogram(time.Now, opts)\n}","line":{"from":47,"to":51}} {"id":100030565,"name":"NewTestableTimingHistogram","signature":"func NewTestableTimingHistogram(nowFunc func() time.Time, opts *TimingHistogramOpts) *TimingHistogram","file":"staging/src/k8s.io/component-base/metrics/timing_histogram.go","code":"// NewTestableTimingHistogram adds injection of the clock\nfunc NewTestableTimingHistogram(nowFunc func() time.Time, opts *TimingHistogramOpts) *TimingHistogram {\n\topts.StabilityLevel.setDefaults()\n\n\th := \u0026TimingHistogram{\n\t\tTimingHistogramOpts: opts,\n\t\tnowFunc: nowFunc,\n\t\tlazyMetric: lazyMetric{stabilityLevel: opts.StabilityLevel},\n\t}\n\th.setPrometheusHistogram(noopMetric{})\n\th.lazyInit(h, BuildFQName(opts.Namespace, opts.Subsystem, opts.Name))\n\treturn h\n}","line":{"from":53,"to":65}} {"id":100030566,"name":"setPrometheusHistogram","signature":"func (h *TimingHistogram) setPrometheusHistogram(histogram promext.TimingHistogram)","file":"staging/src/k8s.io/component-base/metrics/timing_histogram.go","code":"// setPrometheusHistogram sets the underlying KubeGauge object, i.e. the thing that does the measurement.\nfunc (h *TimingHistogram) setPrometheusHistogram(histogram promext.TimingHistogram) {\n\th.PrometheusTimingHistogram = histogram\n\th.initSelfCollection(histogram)\n}","line":{"from":67,"to":71}} {"id":100030567,"name":"DeprecatedVersion","signature":"func (h *TimingHistogram) DeprecatedVersion() *semver.Version","file":"staging/src/k8s.io/component-base/metrics/timing_histogram.go","code":"// DeprecatedVersion returns a pointer to the Version or nil\nfunc (h *TimingHistogram) DeprecatedVersion() *semver.Version {\n\treturn parseSemver(h.TimingHistogramOpts.DeprecatedVersion)\n}","line":{"from":73,"to":76}} {"id":100030568,"name":"initializeMetric","signature":"func (h *TimingHistogram) initializeMetric()","file":"staging/src/k8s.io/component-base/metrics/timing_histogram.go","code":"// initializeMetric invokes the actual prometheus.Histogram object instantiation\n// and stores a reference to it\nfunc (h *TimingHistogram) initializeMetric() {\n\th.TimingHistogramOpts.annotateStabilityLevel()\n\t// this actually creates the underlying prometheus gauge.\n\thistogram, err := promext.NewTestableTimingHistogram(h.nowFunc, h.TimingHistogramOpts.toPromHistogramOpts())\n\tif err != nil {\n\t\tpanic(err) // handle as for regular histograms\n\t}\n\th.setPrometheusHistogram(histogram)\n}","line":{"from":78,"to":88}} {"id":100030569,"name":"initializeDeprecatedMetric","signature":"func (h *TimingHistogram) initializeDeprecatedMetric()","file":"staging/src/k8s.io/component-base/metrics/timing_histogram.go","code":"// initializeDeprecatedMetric invokes the actual prometheus.Histogram object instantiation\n// but modifies the Help description prior to object instantiation.\nfunc (h *TimingHistogram) initializeDeprecatedMetric() {\n\th.TimingHistogramOpts.markDeprecated()\n\th.initializeMetric()\n}","line":{"from":90,"to":95}} {"id":100030570,"name":"WithContext","signature":"func (h *TimingHistogram) WithContext(ctx context.Context) GaugeMetric","file":"staging/src/k8s.io/component-base/metrics/timing_histogram.go","code":"// WithContext allows the normal TimingHistogram metric to pass in context. The context is no-op now.\nfunc (h *TimingHistogram) WithContext(ctx context.Context) GaugeMetric {\n\treturn h.PrometheusTimingHistogram\n}","line":{"from":97,"to":100}} {"id":100030571,"name":"NewTimingHistogramVec","signature":"func NewTimingHistogramVec(opts *TimingHistogramOpts, labels []string) *TimingHistogramVec","file":"staging/src/k8s.io/component-base/metrics/timing_histogram.go","code":"// NewTimingHistogramVec returns an object which satisfies the kubeCollector, Registerable, and GaugeVecMetric interfaces\n// and wraps an underlying promext.TimingHistogramVec object. Note well the way that\n// behavior depends on registration and whether this is hidden.\nfunc NewTimingHistogramVec(opts *TimingHistogramOpts, labels []string) *TimingHistogramVec {\n\treturn NewTestableTimingHistogramVec(time.Now, opts, labels)\n}","line":{"from":116,"to":121}} {"id":100030572,"name":"NewTestableTimingHistogramVec","signature":"func NewTestableTimingHistogramVec(nowFunc func() time.Time, opts *TimingHistogramOpts, labels []string) *TimingHistogramVec","file":"staging/src/k8s.io/component-base/metrics/timing_histogram.go","code":"// NewTestableTimingHistogramVec adds injection of the clock.\nfunc NewTestableTimingHistogramVec(nowFunc func() time.Time, opts *TimingHistogramOpts, labels []string) *TimingHistogramVec {\n\topts.StabilityLevel.setDefaults()\n\n\tfqName := BuildFQName(opts.Namespace, opts.Subsystem, opts.Name)\n\tallowListLock.RLock()\n\tif allowList, ok := labelValueAllowLists[fqName]; ok {\n\t\topts.LabelValueAllowLists = allowList\n\t}\n\tallowListLock.RUnlock()\n\n\tv := \u0026TimingHistogramVec{\n\t\tTimingHistogramVec: noopTimingHistogramVec,\n\t\tTimingHistogramOpts: opts,\n\t\tnowFunc: nowFunc,\n\t\toriginalLabels: labels,\n\t\tlazyMetric: lazyMetric{stabilityLevel: opts.StabilityLevel},\n\t}\n\tv.lazyInit(v, fqName)\n\treturn v\n}","line":{"from":123,"to":143}} {"id":100030573,"name":"DeprecatedVersion","signature":"func (v *TimingHistogramVec) DeprecatedVersion() *semver.Version","file":"staging/src/k8s.io/component-base/metrics/timing_histogram.go","code":"// DeprecatedVersion returns a pointer to the Version or nil\nfunc (v *TimingHistogramVec) DeprecatedVersion() *semver.Version {\n\treturn parseSemver(v.TimingHistogramOpts.DeprecatedVersion)\n}","line":{"from":145,"to":148}} {"id":100030574,"name":"initializeMetric","signature":"func (v *TimingHistogramVec) initializeMetric()","file":"staging/src/k8s.io/component-base/metrics/timing_histogram.go","code":"func (v *TimingHistogramVec) initializeMetric() {\n\tv.TimingHistogramOpts.annotateStabilityLevel()\n\tv.TimingHistogramVec = promext.NewTestableTimingHistogramVec(v.nowFunc, v.TimingHistogramOpts.toPromHistogramOpts(), v.originalLabels...)\n}","line":{"from":150,"to":153}} {"id":100030575,"name":"initializeDeprecatedMetric","signature":"func (v *TimingHistogramVec) initializeDeprecatedMetric()","file":"staging/src/k8s.io/component-base/metrics/timing_histogram.go","code":"func (v *TimingHistogramVec) initializeDeprecatedMetric() {\n\tv.TimingHistogramOpts.markDeprecated()\n\tv.initializeMetric()\n}","line":{"from":155,"to":158}} {"id":100030576,"name":"WithLabelValuesChecked","signature":"func (v *TimingHistogramVec) WithLabelValuesChecked(lvs ...string) (GaugeMetric, error)","file":"staging/src/k8s.io/component-base/metrics/timing_histogram.go","code":"// WithLabelValuesChecked, if called before this vector has been registered in\n// at least one registry, will return a noop gauge and\n// an error that passes ErrIsNotRegistered.\n// If called on a hidden vector,\n// will return a noop gauge and a nil error.\n// If called with a syntactic problem in the labels, will\n// return a noop gauge and an error about the labels.\n// If none of the above apply, this method will return\n// the appropriate vector member and a nil error.\nfunc (v *TimingHistogramVec) WithLabelValuesChecked(lvs ...string) (GaugeMetric, error) {\n\tif !v.IsCreated() {\n\t\tif v.IsHidden() {\n\t\t\treturn noop, nil\n\t\t}\n\t\treturn noop, errNotRegistered\n\t}\n\tif v.LabelValueAllowLists != nil {\n\t\tv.LabelValueAllowLists.ConstrainToAllowedList(v.originalLabels, lvs)\n\t}\n\tops, err := v.TimingHistogramVec.GetMetricWithLabelValues(lvs...)\n\tif err != nil {\n\t\treturn noop, err\n\t}\n\treturn ops.(GaugeMetric), err\n}","line":{"from":160,"to":184}} {"id":100030577,"name":"WithLabelValues","signature":"func (v *TimingHistogramVec) WithLabelValues(lvs ...string) GaugeMetric","file":"staging/src/k8s.io/component-base/metrics/timing_histogram.go","code":"// WithLabelValues calls WithLabelValuesChecked\n// and handles errors as follows.\n// An error that passes ErrIsNotRegistered is ignored\n// and the noop gauge is returned;\n// all other errors cause a panic.\nfunc (v *TimingHistogramVec) WithLabelValues(lvs ...string) GaugeMetric {\n\tans, err := v.WithLabelValuesChecked(lvs...)\n\tif err == nil || ErrIsNotRegistered(err) {\n\t\treturn ans\n\t}\n\tpanic(err)\n}","line":{"from":186,"to":197}} {"id":100030578,"name":"WithChecked","signature":"func (v *TimingHistogramVec) WithChecked(labels map[string]string) (GaugeMetric, error)","file":"staging/src/k8s.io/component-base/metrics/timing_histogram.go","code":"// WithChecked, if called before this vector has been registered in\n// at least one registry, will return a noop gauge and\n// an error that passes ErrIsNotRegistered.\n// If called on a hidden vector,\n// will return a noop gauge and a nil error.\n// If called with a syntactic problem in the labels, will\n// return a noop gauge and an error about the labels.\n// If none of the above apply, this method will return\n// the appropriate vector member and a nil error.\nfunc (v *TimingHistogramVec) WithChecked(labels map[string]string) (GaugeMetric, error) {\n\tif !v.IsCreated() {\n\t\tif v.IsHidden() {\n\t\t\treturn noop, nil\n\t\t}\n\t\treturn noop, errNotRegistered\n\t}\n\tif v.LabelValueAllowLists != nil {\n\t\tv.LabelValueAllowLists.ConstrainLabelMap(labels)\n\t}\n\tops, err := v.TimingHistogramVec.GetMetricWith(labels)\n\treturn ops.(GaugeMetric), err\n}","line":{"from":199,"to":220}} {"id":100030579,"name":"With","signature":"func (v *TimingHistogramVec) With(labels map[string]string) GaugeMetric","file":"staging/src/k8s.io/component-base/metrics/timing_histogram.go","code":"// With calls WithChecked and handles errors as follows.\n// An error that passes ErrIsNotRegistered is ignored\n// and the noop gauge is returned;\n// all other errors cause a panic.\nfunc (v *TimingHistogramVec) With(labels map[string]string) GaugeMetric {\n\tans, err := v.WithChecked(labels)\n\tif err == nil || ErrIsNotRegistered(err) {\n\t\treturn ans\n\t}\n\tpanic(err)\n}","line":{"from":222,"to":232}} {"id":100030580,"name":"Delete","signature":"func (v *TimingHistogramVec) Delete(labels map[string]string) bool","file":"staging/src/k8s.io/component-base/metrics/timing_histogram.go","code":"// Delete deletes the metric where the variable labels are the same as those\n// passed in as labels. It returns true if a metric was deleted.\n//\n// It is not an error if the number and names of the Labels are inconsistent\n// with those of the VariableLabels in Desc. However, such inconsistent Labels\n// can never match an actual metric, so the method will always return false in\n// that case.\nfunc (v *TimingHistogramVec) Delete(labels map[string]string) bool {\n\tif !v.IsCreated() {\n\t\treturn false // since we haven't created the metric, we haven't deleted a metric with the passed in values\n\t}\n\treturn v.TimingHistogramVec.Delete(labels)\n}","line":{"from":234,"to":246}} {"id":100030581,"name":"Reset","signature":"func (v *TimingHistogramVec) Reset()","file":"staging/src/k8s.io/component-base/metrics/timing_histogram.go","code":"// Reset deletes all metrics in this vector.\nfunc (v *TimingHistogramVec) Reset() {\n\tif !v.IsCreated() {\n\t\treturn\n\t}\n\n\tv.TimingHistogramVec.Reset()\n}","line":{"from":248,"to":255}} {"id":100030582,"name":"InterfaceWithContext","signature":"func (v *TimingHistogramVec) InterfaceWithContext(ctx context.Context) GaugeVecMetric","file":"staging/src/k8s.io/component-base/metrics/timing_histogram.go","code":"// WithContext returns wrapped TimingHistogramVec with context\nfunc (v *TimingHistogramVec) InterfaceWithContext(ctx context.Context) GaugeVecMetric {\n\treturn \u0026TimingHistogramVecWithContext{\n\t\tctx: ctx,\n\t\tTimingHistogramVec: v,\n\t}\n}","line":{"from":257,"to":263}} {"id":100030583,"name":"toPromValueType","signature":"func (vt *ValueType) toPromValueType() prometheus.ValueType","file":"staging/src/k8s.io/component-base/metrics/value.go","code":"func (vt *ValueType) toPromValueType() prometheus.ValueType {\n\treturn prometheus.ValueType(*vt)\n}","line":{"from":36,"to":38}} {"id":100030584,"name":"NewLazyConstMetric","signature":"func NewLazyConstMetric(desc *Desc, valueType ValueType, value float64, labelValues ...string) Metric","file":"staging/src/k8s.io/component-base/metrics/value.go","code":"// NewLazyConstMetric is a helper of MustNewConstMetric.\n//\n// Note: If the metrics described by the desc is hidden, the metrics will not be created.\nfunc NewLazyConstMetric(desc *Desc, valueType ValueType, value float64, labelValues ...string) Metric {\n\tif desc.IsHidden() {\n\t\treturn nil\n\t}\n\treturn prometheus.MustNewConstMetric(desc.toPrometheusDesc(), valueType.toPromValueType(), value, labelValues...)\n}","line":{"from":40,"to":48}} {"id":100030585,"name":"NewConstMetric","signature":"func NewConstMetric(desc *Desc, valueType ValueType, value float64, labelValues ...string) (Metric, error)","file":"staging/src/k8s.io/component-base/metrics/value.go","code":"// NewConstMetric is a helper of NewConstMetric.\n//\n// Note: If the metrics described by the desc is hidden, the metrics will not be created.\nfunc NewConstMetric(desc *Desc, valueType ValueType, value float64, labelValues ...string) (Metric, error) {\n\tif desc.IsHidden() {\n\t\treturn nil, nil\n\t}\n\treturn prometheus.NewConstMetric(desc.toPrometheusDesc(), valueType.toPromValueType(), value, labelValues...)\n}","line":{"from":50,"to":58}} {"id":100030586,"name":"NewLazyMetricWithTimestamp","signature":"func NewLazyMetricWithTimestamp(t time.Time, m Metric) Metric","file":"staging/src/k8s.io/component-base/metrics/value.go","code":"// NewLazyMetricWithTimestamp is a helper of NewMetricWithTimestamp.\n//\n// Warning: the Metric 'm' must be the one created by NewLazyConstMetric(),\n// otherwise, no stability guarantees would be offered.\nfunc NewLazyMetricWithTimestamp(t time.Time, m Metric) Metric {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\treturn prometheus.NewMetricWithTimestamp(t, m)\n}","line":{"from":60,"to":70}} {"id":100030587,"name":"RegisterBuildInfo","signature":"func RegisterBuildInfo(r KubeRegistry)","file":"staging/src/k8s.io/component-base/metrics/version.go","code":"// RegisterBuildInfo registers the build and version info in a metadata metric in prometheus\nfunc RegisterBuildInfo(r KubeRegistry) {\n\tinfo := version.Get()\n\tr.MustRegister(buildInfo)\n\tbuildInfo.WithLabelValues(info.Major, info.Minor, info.GitVersion, info.GitCommit, info.GitTreeState, info.BuildDate, info.GoVersion, info.Compiler, info.Platform).Set(1)\n}","line":{"from":32,"to":37}} {"id":100030588,"name":"parseSemver","signature":"func parseSemver(s string) *semver.Version","file":"staging/src/k8s.io/component-base/metrics/version_parser.go","code":"func parseSemver(s string) *semver.Version {\n\tif s != \"\" {\n\t\tsv := semver.MustParse(s)\n\t\treturn \u0026sv\n\t}\n\treturn nil\n}","line":{"from":36,"to":42}} {"id":100030589,"name":"parseVersion","signature":"func parseVersion(ver apimachineryversion.Info) semver.Version","file":"staging/src/k8s.io/component-base/metrics/version_parser.go","code":"func parseVersion(ver apimachineryversion.Info) semver.Version {\n\tmatches := versionRe.FindAllStringSubmatch(ver.String(), -1)\n\n\tif len(matches) != 1 {\n\t\tpanic(fmt.Sprintf(\"version string \\\"%v\\\" doesn't match expected regular expression: \\\"%v\\\"\", ver.String(), versionRe.String()))\n\t}\n\treturn semver.MustParse(matches[0][1])\n}","line":{"from":43,"to":50}} {"id":100030590,"name":"ErrIsNotRegistered","signature":"func ErrIsNotRegistered(err error) bool","file":"staging/src/k8s.io/component-base/metrics/wrappers.go","code":"func ErrIsNotRegistered(err error) bool {\n\treturn err == errNotRegistered\n}","line":{"from":163,"to":165}} {"id":100030591,"name":"TerminalSize","signature":"func TerminalSize(w io.Writer) (int, int, error)","file":"staging/src/k8s.io/component-base/term/term.go","code":"// TerminalSize returns the current width and height of the user's terminal. If it isn't a terminal,\n// nil is returned. On error, zero values are returned for width and height.\n// Usually w must be the stdout of the process. Stderr won't work.\nfunc TerminalSize(w io.Writer) (int, int, error) {\n\toutFd, isTerminal := term.GetFdInfo(w)\n\tif !isTerminal {\n\t\treturn 0, 0, fmt.Errorf(\"given writer is no terminal\")\n\t}\n\twinsize, err := term.GetWinsize(outFd)\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\treturn int(winsize.Width), int(winsize.Height), nil\n}","line":{"from":26,"to":39}} {"id":100030592,"name":"ValidateTracingConfiguration","signature":"func ValidateTracingConfiguration(traceConfig *TracingConfiguration, featureGate featuregate.FeatureGate, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/component-base/tracing/api/v1/config.go","code":"// ValidateTracingConfiguration validates the tracing configuration\nfunc ValidateTracingConfiguration(traceConfig *TracingConfiguration, featureGate featuregate.FeatureGate, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif traceConfig == nil {\n\t\treturn allErrs\n\t}\n\tif traceConfig.SamplingRatePerMillion != nil {\n\t\tallErrs = append(allErrs, validateSamplingRate(*traceConfig.SamplingRatePerMillion, fldPath.Child(\"samplingRatePerMillion\"))...)\n\t}\n\tif traceConfig.Endpoint != nil {\n\t\tallErrs = append(allErrs, validateEndpoint(*traceConfig.Endpoint, fldPath.Child(\"endpoint\"))...)\n\t}\n\treturn allErrs\n}","line":{"from":32,"to":45}} {"id":100030593,"name":"validateSamplingRate","signature":"func validateSamplingRate(rate int32, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/component-base/tracing/api/v1/config.go","code":"func validateSamplingRate(rate int32, fldPath *field.Path) field.ErrorList {\n\terrs := field.ErrorList{}\n\tif rate \u003c 0 {\n\t\terrs = append(errs, field.Invalid(\n\t\t\tfldPath, rate,\n\t\t\t\"sampling rate must be positive\",\n\t\t))\n\t}\n\tif rate \u003e maxSamplingRatePerMillion {\n\t\terrs = append(errs, field.Invalid(\n\t\t\tfldPath, rate,\n\t\t\t\"sampling rate per million must be less than or equal to one million\",\n\t\t))\n\t}\n\treturn errs\n}","line":{"from":47,"to":62}} {"id":100030594,"name":"validateEndpoint","signature":"func validateEndpoint(endpoint string, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/component-base/tracing/api/v1/config.go","code":"func validateEndpoint(endpoint string, fldPath *field.Path) field.ErrorList {\n\terrs := field.ErrorList{}\n\tif !strings.Contains(endpoint, \"//\") {\n\t\tendpoint = \"dns://\" + endpoint\n\t}\n\turl, err := url.Parse(endpoint)\n\tif err != nil {\n\t\terrs = append(errs, field.Invalid(\n\t\t\tfldPath, endpoint,\n\t\t\terr.Error(),\n\t\t))\n\t\treturn errs\n\t}\n\tswitch url.Scheme {\n\tcase \"dns\":\n\tcase \"unix\":\n\tcase \"unix-abstract\":\n\tdefault:\n\t\terrs = append(errs, field.Invalid(\n\t\t\tfldPath, endpoint,\n\t\t\tfmt.Sprintf(\"unsupported scheme: %v. Options are none, dns, unix, or unix-abstract. See https://github.com/grpc/grpc/blob/master/doc/naming.md\", url.Scheme),\n\t\t))\n\t}\n\treturn errs\n}","line":{"from":64,"to":88}} {"id":100030595,"name":"Start","signature":"func Start(ctx context.Context, name string, attributes ...attribute.KeyValue) (context.Context, *Span)","file":"staging/src/k8s.io/component-base/tracing/tracing.go","code":"// Start creates spans using both OpenTelemetry, and the k8s.io/utils/trace package.\n// It only creates an OpenTelemetry span if the incoming context already includes a span.\nfunc Start(ctx context.Context, name string, attributes ...attribute.KeyValue) (context.Context, *Span) {\n\t// If the incoming context already includes an OpenTelemetry span, create a child span with the provided name and attributes.\n\t// If the caller is not using OpenTelemetry, or has tracing disabled (e.g. with a component-specific feature flag), this is a noop.\n\tctx, otelSpan := trace.SpanFromContext(ctx).TracerProvider().Tracer(instrumentationScope).Start(ctx, name, trace.WithAttributes(attributes...))\n\t// If there is already a utiltrace span in the context, use that as our parent span.\n\tutilSpan := utiltrace.FromContext(ctx).Nest(name, attributesToFields(attributes)...)\n\t// Set the trace as active in the context so that subsequent Start calls create nested spans.\n\treturn utiltrace.ContextWithTrace(ctx, utilSpan), \u0026Span{\n\t\totelSpan: otelSpan,\n\t\tutilSpan: utilSpan,\n\t}\n}","line":{"from":31,"to":44}} {"id":100030596,"name":"AddEvent","signature":"func (s *Span) AddEvent(name string, attributes ...attribute.KeyValue)","file":"staging/src/k8s.io/component-base/tracing/tracing.go","code":"// AddEvent adds a point-in-time event with a name and attributes.\nfunc (s *Span) AddEvent(name string, attributes ...attribute.KeyValue) {\n\ts.otelSpan.AddEvent(name, trace.WithAttributes(attributes...))\n\tif s.utilSpan != nil {\n\t\ts.utilSpan.Step(name, attributesToFields(attributes)...)\n\t}\n}","line":{"from":55,"to":61}} {"id":100030597,"name":"End","signature":"func (s *Span) End(logThreshold time.Duration)","file":"staging/src/k8s.io/component-base/tracing/tracing.go","code":"// End ends the span, and logs if the span duration is greater than the logThreshold.\nfunc (s *Span) End(logThreshold time.Duration) {\n\ts.otelSpan.End()\n\tif s.utilSpan != nil {\n\t\ts.utilSpan.LogIfLong(logThreshold)\n\t}\n}","line":{"from":63,"to":69}} {"id":100030598,"name":"attributesToFields","signature":"func attributesToFields(attributes []attribute.KeyValue) []utiltrace.Field","file":"staging/src/k8s.io/component-base/tracing/tracing.go","code":"func attributesToFields(attributes []attribute.KeyValue) []utiltrace.Field {\n\tfields := make([]utiltrace.Field, len(attributes))\n\tfor i := range attributes {\n\t\tattr := attributes[i]\n\t\tfields[i] = utiltrace.Field{Key: string(attr.Key), Value: attr.Value.AsInterface()}\n\t}\n\treturn fields\n}","line":{"from":71,"to":78}} {"id":100030599,"name":"SpanFromContext","signature":"func SpanFromContext(ctx context.Context) *Span","file":"staging/src/k8s.io/component-base/tracing/tracing.go","code":"// SpanFromContext returns the *Span from the current context. It is composed of the active\n// OpenTelemetry and k8s.io/utils/trace spans.\nfunc SpanFromContext(ctx context.Context) *Span {\n\treturn \u0026Span{\n\t\totelSpan: trace.SpanFromContext(ctx),\n\t\tutilSpan: utiltrace.FromContext(ctx),\n\t}\n}","line":{"from":80,"to":87}} {"id":100030600,"name":"ContextWithSpan","signature":"func ContextWithSpan(ctx context.Context, s *Span) context.Context","file":"staging/src/k8s.io/component-base/tracing/tracing.go","code":"// ContextWithSpan returns a context with the Span included in the context.\nfunc ContextWithSpan(ctx context.Context, s *Span) context.Context {\n\treturn trace.ContextWithSpan(utiltrace.ContextWithTrace(ctx, s.utilSpan), s.otelSpan)\n}","line":{"from":89,"to":92}} {"id":100030601,"name":"Shutdown","signature":"func (n *noopTracerProvider) Shutdown(context.Context) error","file":"staging/src/k8s.io/component-base/tracing/utils.go","code":"func (n *noopTracerProvider) Shutdown(context.Context) error {\n\treturn nil\n}","line":{"from":44,"to":46}} {"id":100030602,"name":"NewNoopTracerProvider","signature":"func NewNoopTracerProvider() TracerProvider","file":"staging/src/k8s.io/component-base/tracing/utils.go","code":"func NewNoopTracerProvider() TracerProvider {\n\treturn \u0026noopTracerProvider{TracerProvider: oteltrace.NewNoopTracerProvider()}\n}","line":{"from":48,"to":50}} {"id":100030603,"name":"NewProvider","signature":"func NewProvider(ctx context.Context,","file":"staging/src/k8s.io/component-base/tracing/utils.go","code":"// NewProvider creates a TracerProvider in a component, and enforces recommended tracing behavior\nfunc NewProvider(ctx context.Context,\n\ttracingConfig *v1.TracingConfiguration,\n\taddedOpts []otlptracegrpc.Option,\n\tresourceOpts []resource.Option,\n) (TracerProvider, error) {\n\tif tracingConfig == nil {\n\t\treturn NewNoopTracerProvider(), nil\n\t}\n\topts := append([]otlptracegrpc.Option{}, addedOpts...)\n\tif tracingConfig.Endpoint != nil {\n\t\topts = append(opts, otlptracegrpc.WithEndpoint(*tracingConfig.Endpoint))\n\t}\n\topts = append(opts, otlptracegrpc.WithInsecure())\n\texporter, err := otlptracegrpc.New(ctx, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tres, err := resource.New(ctx, resourceOpts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// sampler respects parent span's sampling rate or\n\t// otherwise never samples.\n\tsampler := sdktrace.NeverSample()\n\t// Or, emit spans for a fraction of transactions\n\tif tracingConfig.SamplingRatePerMillion != nil \u0026\u0026 *tracingConfig.SamplingRatePerMillion \u003e 0 {\n\t\tsampler = sdktrace.TraceIDRatioBased(float64(*tracingConfig.SamplingRatePerMillion) / float64(1000000))\n\t}\n\t// batch span processor to aggregate spans before export.\n\tbsp := sdktrace.NewBatchSpanProcessor(exporter)\n\ttp := sdktrace.NewTracerProvider(\n\t\tsdktrace.WithSampler(sdktrace.ParentBased(sampler)),\n\t\tsdktrace.WithSpanProcessor(bsp),\n\t\tsdktrace.WithResource(res),\n\t)\n\treturn tp, nil\n}","line":{"from":52,"to":90}} {"id":100030604,"name":"WithTracing","signature":"func WithTracing(handler http.Handler, tp oteltrace.TracerProvider, serviceName string) http.Handler","file":"staging/src/k8s.io/component-base/tracing/utils.go","code":"// WithTracing adds tracing to requests if the incoming request is sampled\nfunc WithTracing(handler http.Handler, tp oteltrace.TracerProvider, serviceName string) http.Handler {\n\topts := []otelhttp.Option{\n\t\totelhttp.WithPropagators(Propagators()),\n\t\totelhttp.WithTracerProvider(tp),\n\t}\n\t// With Noop TracerProvider, the otelhttp still handles context propagation.\n\t// See https://github.com/open-telemetry/opentelemetry-go/tree/main/example/passthrough\n\treturn otelhttp.NewHandler(handler, serviceName, opts...)\n}","line":{"from":92,"to":101}} {"id":100030605,"name":"WrapperFor","signature":"func WrapperFor(tp oteltrace.TracerProvider) transport.WrapperFunc","file":"staging/src/k8s.io/component-base/tracing/utils.go","code":"// WrapperFor can be used to add tracing to a *rest.Config.\n// Example usage:\n// tp := NewProvider(...)\n// config, _ := rest.InClusterConfig()\n// config.Wrap(WrapperFor(tp))\n// kubeclient, _ := clientset.NewForConfig(config)\nfunc WrapperFor(tp oteltrace.TracerProvider) transport.WrapperFunc {\n\treturn func(rt http.RoundTripper) http.RoundTripper {\n\t\topts := []otelhttp.Option{\n\t\t\totelhttp.WithPropagators(Propagators()),\n\t\t\totelhttp.WithTracerProvider(tp),\n\t\t}\n\t\t// With Noop TracerProvider, the otelhttp still handles context propagation.\n\t\t// See https://github.com/open-telemetry/opentelemetry-go/tree/main/example/passthrough\n\t\treturn otelhttp.NewTransport(rt, opts...)\n\t}\n}","line":{"from":103,"to":119}} {"id":100030606,"name":"Propagators","signature":"func Propagators() propagation.TextMapPropagator","file":"staging/src/k8s.io/component-base/tracing/utils.go","code":"// Propagators returns the recommended set of propagators.\nfunc Propagators() propagation.TextMapPropagator {\n\treturn propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{})\n}","line":{"from":121,"to":124}} {"id":100030607,"name":"IsBoolFlag","signature":"func (v *versionValue) IsBoolFlag() bool","file":"staging/src/k8s.io/component-base/version/verflag/verflag.go","code":"func (v *versionValue) IsBoolFlag() bool {\n\treturn true\n}","line":{"from":41,"to":43}} {"id":100030608,"name":"Get","signature":"func (v *versionValue) Get() interface{}","file":"staging/src/k8s.io/component-base/version/verflag/verflag.go","code":"func (v *versionValue) Get() interface{} {\n\treturn versionValue(*v)\n}","line":{"from":45,"to":47}} {"id":100030609,"name":"Set","signature":"func (v *versionValue) Set(s string) error","file":"staging/src/k8s.io/component-base/version/verflag/verflag.go","code":"func (v *versionValue) Set(s string) error {\n\tif s == strRawVersion {\n\t\t*v = VersionRaw\n\t\treturn nil\n\t}\n\tboolVal, err := strconv.ParseBool(s)\n\tif boolVal {\n\t\t*v = VersionTrue\n\t} else {\n\t\t*v = VersionFalse\n\t}\n\treturn err\n}","line":{"from":49,"to":61}} {"id":100030610,"name":"String","signature":"func (v *versionValue) String() string","file":"staging/src/k8s.io/component-base/version/verflag/verflag.go","code":"func (v *versionValue) String() string {\n\tif *v == VersionRaw {\n\t\treturn strRawVersion\n\t}\n\treturn fmt.Sprintf(\"%v\", bool(*v == VersionTrue))\n}","line":{"from":63,"to":68}} {"id":100030611,"name":"Type","signature":"func (v *versionValue) Type() string","file":"staging/src/k8s.io/component-base/version/verflag/verflag.go","code":"// The type of the flag as required by the pflag.Value interface\nfunc (v *versionValue) Type() string {\n\treturn \"version\"\n}","line":{"from":70,"to":73}} {"id":100030612,"name":"VersionVar","signature":"func VersionVar(p *versionValue, name string, value versionValue, usage string)","file":"staging/src/k8s.io/component-base/version/verflag/verflag.go","code":"func VersionVar(p *versionValue, name string, value versionValue, usage string) {\n\t*p = value\n\tflag.Var(p, name, usage)\n\t// \"--version\" will be treated as \"--version=true\"\n\tflag.Lookup(name).NoOptDefVal = \"true\"\n}","line":{"from":75,"to":80}} {"id":100030613,"name":"Version","signature":"func Version(name string, value versionValue, usage string) *versionValue","file":"staging/src/k8s.io/component-base/version/verflag/verflag.go","code":"func Version(name string, value versionValue, usage string) *versionValue {\n\tp := new(versionValue)\n\tVersionVar(p, name, value, usage)\n\treturn p\n}","line":{"from":82,"to":86}} {"id":100030614,"name":"AddFlags","signature":"func AddFlags(fs *flag.FlagSet)","file":"staging/src/k8s.io/component-base/version/verflag/verflag.go","code":"// AddFlags registers this package's flags on arbitrary FlagSets, such that they point to the\n// same value as the global flags.\nfunc AddFlags(fs *flag.FlagSet) {\n\tfs.AddFlag(flag.Lookup(versionFlagName))\n}","line":{"from":95,"to":99}} {"id":100030615,"name":"PrintAndExitIfRequested","signature":"func PrintAndExitIfRequested()","file":"staging/src/k8s.io/component-base/version/verflag/verflag.go","code":"// PrintAndExitIfRequested will check if the -version flag was passed\n// and, if so, print the version and exit.\nfunc PrintAndExitIfRequested() {\n\tif *versionFlag == VersionRaw {\n\t\tfmt.Printf(\"%#v\\n\", version.Get())\n\t\tos.Exit(0)\n\t} else if *versionFlag == VersionTrue {\n\t\tfmt.Printf(\"%s %s\\n\", programName, version.Get())\n\t\tos.Exit(0)\n\t}\n}","line":{"from":101,"to":111}} {"id":100030616,"name":"Get","signature":"func Get() apimachineryversion.Info","file":"staging/src/k8s.io/component-base/version/version.go","code":"// Get returns the overall codebase version. It's for detecting\n// what code a binary was built from.\nfunc Get() apimachineryversion.Info {\n\t// These variables typically come from -ldflags settings and in\n\t// their absence fallback to the settings in ./base.go\n\treturn apimachineryversion.Info{\n\t\tMajor: gitMajor,\n\t\tMinor: gitMinor,\n\t\tGitVersion: gitVersion,\n\t\tGitCommit: gitCommit,\n\t\tGitTreeState: gitTreeState,\n\t\tBuildDate: buildDate,\n\t\tGoVersion: runtime.Version(),\n\t\tCompiler: runtime.Compiler,\n\t\tPlatform: fmt.Sprintf(\"%s/%s\", runtime.GOOS, runtime.GOARCH),\n\t}\n}","line":{"from":26,"to":42}} {"id":100030617,"name":"NewController","signature":"func NewController(clock clock.Clock, client clientset.Interface, holderIdentity string, leaseDurationSeconds int32, onRepeatedHeartbeatFailure func(), renewInterval time.Duration, leaseName, leaseNamespace string, newLeasePostProcessFunc ProcessLeaseFunc) Controller","file":"staging/src/k8s.io/component-helpers/apimachinery/lease/controller.go","code":"// NewController constructs and returns a controller\nfunc NewController(clock clock.Clock, client clientset.Interface, holderIdentity string, leaseDurationSeconds int32, onRepeatedHeartbeatFailure func(), renewInterval time.Duration, leaseName, leaseNamespace string, newLeasePostProcessFunc ProcessLeaseFunc) Controller {\n\tvar leaseClient coordclientset.LeaseInterface\n\tif client != nil {\n\t\tleaseClient = client.CoordinationV1().Leases(leaseNamespace)\n\t}\n\treturn \u0026controller{\n\t\tclient: client,\n\t\tleaseClient: leaseClient,\n\t\tholderIdentity: holderIdentity,\n\t\tleaseName: leaseName,\n\t\tleaseNamespace: leaseNamespace,\n\t\tleaseDurationSeconds: leaseDurationSeconds,\n\t\trenewInterval: renewInterval,\n\t\tclock: clock,\n\t\tonRepeatedHeartbeatFailure: onRepeatedHeartbeatFailure,\n\t\tnewLeasePostProcessFunc: newLeasePostProcessFunc,\n\t}\n}","line":{"from":74,"to":92}} {"id":100030618,"name":"Run","signature":"func (c *controller) Run(ctx context.Context)","file":"staging/src/k8s.io/component-helpers/apimachinery/lease/controller.go","code":"// Run runs the controller\nfunc (c *controller) Run(ctx context.Context) {\n\tif c.leaseClient == nil {\n\t\tklog.FromContext(ctx).Info(\"lease controller has nil lease client, will not claim or renew leases\")\n\t\treturn\n\t}\n\twait.JitterUntilWithContext(ctx, c.sync, c.renewInterval, 0.04, true)\n}","line":{"from":94,"to":101}} {"id":100030619,"name":"sync","signature":"func (c *controller) sync(ctx context.Context)","file":"staging/src/k8s.io/component-helpers/apimachinery/lease/controller.go","code":"func (c *controller) sync(ctx context.Context) {\n\tif c.latestLease != nil {\n\t\t// As long as the lease is not (or very rarely) updated by any other agent than the component itself,\n\t\t// we can optimistically assume it didn't change since our last update and try updating\n\t\t// based on the version from that time. Thanks to it we avoid GET call and reduce load\n\t\t// on etcd and kube-apiserver.\n\t\t// If at some point other agents will also be frequently updating the Lease object, this\n\t\t// can result in performance degradation, because we will end up with calling additional\n\t\t// GET/PUT - at this point this whole \"if\" should be removed.\n\t\terr := c.retryUpdateLease(ctx, c.latestLease)\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\t\tklog.FromContext(ctx).Info(\"failed to update lease using latest lease, fallback to ensure lease\", \"err\", err)\n\t}\n\n\tlease, created := c.backoffEnsureLease(ctx)\n\tc.latestLease = lease\n\t// we don't need to update the lease if we just created it\n\tif !created \u0026\u0026 lease != nil {\n\t\tif err := c.retryUpdateLease(ctx, lease); err != nil {\n\t\t\tklog.FromContext(ctx).Error(err, \"Will retry updating lease\", \"interval\", c.renewInterval)\n\t\t}\n\t}\n}","line":{"from":103,"to":127}} {"id":100030620,"name":"backoffEnsureLease","signature":"func (c *controller) backoffEnsureLease(ctx context.Context) (*coordinationv1.Lease, bool)","file":"staging/src/k8s.io/component-helpers/apimachinery/lease/controller.go","code":"// backoffEnsureLease attempts to create the lease if it does not exist,\n// and uses exponentially increasing waits to prevent overloading the API server\n// with retries. Returns the lease, and true if this call created the lease,\n// false otherwise.\nfunc (c *controller) backoffEnsureLease(ctx context.Context) (*coordinationv1.Lease, bool) {\n\tvar (\n\t\tlease *coordinationv1.Lease\n\t\tcreated bool\n\t\terr error\n\t)\n\tsleep := 100 * time.Millisecond\n\tfor {\n\t\tlease, created, err = c.ensureLease(ctx)\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t\tsleep = minDuration(2*sleep, maxBackoff)\n\t\tklog.FromContext(ctx).Error(err, \"Failed to ensure lease exists, will retry\", \"interval\", sleep)\n\t\t// backoff wait with early return if the context gets canceled\n\t\tselect {\n\t\tcase \u003c-ctx.Done():\n\t\t\treturn nil, false\n\t\tcase \u003c-time.After(sleep):\n\t\t}\n\t}\n\treturn lease, created\n}","line":{"from":129,"to":155}} {"id":100030621,"name":"ensureLease","signature":"func (c *controller) ensureLease(ctx context.Context) (*coordinationv1.Lease, bool, error)","file":"staging/src/k8s.io/component-helpers/apimachinery/lease/controller.go","code":"// ensureLease creates the lease if it does not exist. Returns the lease and\n// a bool (true if this call created the lease), or any error that occurs.\nfunc (c *controller) ensureLease(ctx context.Context) (*coordinationv1.Lease, bool, error) {\n\tlease, err := c.leaseClient.Get(ctx, c.leaseName, metav1.GetOptions{})\n\tif apierrors.IsNotFound(err) {\n\t\t// lease does not exist, create it.\n\t\tleaseToCreate, err := c.newLease(nil)\n\t\t// An error occurred during allocating the new lease (likely from newLeasePostProcessFunc).\n\t\t// Given that we weren't able to set the lease correctly, we simply\n\t\t// not create it this time - we will retry in the next iteration.\n\t\tif err != nil {\n\t\t\treturn nil, false, nil\n\t\t}\n\t\tlease, err := c.leaseClient.Create(ctx, leaseToCreate, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\treturn nil, false, err\n\t\t}\n\t\treturn lease, true, nil\n\t} else if err != nil {\n\t\t// unexpected error getting lease\n\t\treturn nil, false, err\n\t}\n\t// lease already existed\n\treturn lease, false, nil\n}","line":{"from":157,"to":181}} {"id":100030622,"name":"retryUpdateLease","signature":"func (c *controller) retryUpdateLease(ctx context.Context, base *coordinationv1.Lease) error","file":"staging/src/k8s.io/component-helpers/apimachinery/lease/controller.go","code":"// retryUpdateLease attempts to update the lease for maxUpdateRetries,\n// call this once you're sure the lease has been created\nfunc (c *controller) retryUpdateLease(ctx context.Context, base *coordinationv1.Lease) error {\n\tfor i := 0; i \u003c maxUpdateRetries; i++ {\n\t\tleaseToUpdate, _ := c.newLease(base)\n\t\tlease, err := c.leaseClient.Update(ctx, leaseToUpdate, metav1.UpdateOptions{})\n\t\tif err == nil {\n\t\t\tc.latestLease = lease\n\t\t\treturn nil\n\t\t}\n\t\tklog.FromContext(ctx).Error(err, \"Failed to update lease\")\n\t\t// OptimisticLockError requires getting the newer version of lease to proceed.\n\t\tif apierrors.IsConflict(err) {\n\t\t\tbase, _ = c.backoffEnsureLease(ctx)\n\t\t\tcontinue\n\t\t}\n\t\tif i \u003e 0 \u0026\u0026 c.onRepeatedHeartbeatFailure != nil {\n\t\t\tc.onRepeatedHeartbeatFailure()\n\t\t}\n\t}\n\treturn fmt.Errorf(\"failed %d attempts to update lease\", maxUpdateRetries)\n}","line":{"from":183,"to":204}} {"id":100030623,"name":"newLease","signature":"func (c *controller) newLease(base *coordinationv1.Lease) (*coordinationv1.Lease, error)","file":"staging/src/k8s.io/component-helpers/apimachinery/lease/controller.go","code":"// newLease constructs a new lease if base is nil, or returns a copy of base\n// with desired state asserted on the copy.\n// Note that an error will block lease CREATE, causing the CREATE to be retried in\n// the next iteration; but the error won't block lease refresh (UPDATE).\nfunc (c *controller) newLease(base *coordinationv1.Lease) (*coordinationv1.Lease, error) {\n\t// Use the bare minimum set of fields; other fields exist for debugging/legacy,\n\t// but we don't need to make component heartbeats more complicated by using them.\n\tvar lease *coordinationv1.Lease\n\tif base == nil {\n\t\tlease = \u0026coordinationv1.Lease{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: c.leaseName,\n\t\t\t\tNamespace: c.leaseNamespace,\n\t\t\t},\n\t\t\tSpec: coordinationv1.LeaseSpec{\n\t\t\t\tHolderIdentity: pointer.StringPtr(c.holderIdentity),\n\t\t\t\tLeaseDurationSeconds: pointer.Int32Ptr(c.leaseDurationSeconds),\n\t\t\t},\n\t\t}\n\t} else {\n\t\tlease = base.DeepCopy()\n\t}\n\tlease.Spec.RenewTime = \u0026metav1.MicroTime{Time: c.clock.Now()}\n\n\tif c.newLeasePostProcessFunc != nil {\n\t\terr := c.newLeasePostProcessFunc(lease)\n\t\treturn lease, err\n\t}\n\n\treturn lease, nil\n}","line":{"from":206,"to":236}} {"id":100030624,"name":"minDuration","signature":"func minDuration(a, b time.Duration) time.Duration","file":"staging/src/k8s.io/component-helpers/apimachinery/lease/controller.go","code":"func minDuration(a, b time.Duration) time.Duration {\n\tif a \u003c b {\n\t\treturn a\n\t}\n\treturn b\n}","line":{"from":238,"to":243}} {"id":100030625,"name":"UpdateDisruptionAllowedCondition","signature":"func UpdateDisruptionAllowedCondition(pdb *policy.PodDisruptionBudget)","file":"staging/src/k8s.io/component-helpers/apps/poddisruptionbudget/helpers.go","code":"// UpdateDisruptionAllowedCondition updates the DisruptionAllowed condition\n// on a PodDisruptionBudget based on the value of the DisruptionsAllowed field.\nfunc UpdateDisruptionAllowedCondition(pdb *policy.PodDisruptionBudget) {\n\tif pdb.Status.Conditions == nil {\n\t\tpdb.Status.Conditions = make([]metav1.Condition, 0)\n\t}\n\tif pdb.Status.DisruptionsAllowed \u003e 0 {\n\t\tapimeta.SetStatusCondition(\u0026pdb.Status.Conditions, metav1.Condition{\n\t\t\tType: policy.DisruptionAllowedCondition,\n\t\t\tReason: policy.SufficientPodsReason,\n\t\t\tStatus: metav1.ConditionTrue,\n\t\t\tObservedGeneration: pdb.Status.ObservedGeneration,\n\t\t})\n\t} else {\n\t\tapimeta.SetStatusCondition(\u0026pdb.Status.Conditions, metav1.Condition{\n\t\t\tType: policy.DisruptionAllowedCondition,\n\t\t\tReason: policy.InsufficientPodsReason,\n\t\t\tStatus: metav1.ConditionFalse,\n\t\t\tObservedGeneration: pdb.Status.ObservedGeneration,\n\t\t})\n\t}\n}","line":{"from":25,"to":46}} {"id":100030626,"name":"ConditionsAreUpToDate","signature":"func ConditionsAreUpToDate(pdb *policy.PodDisruptionBudget) bool","file":"staging/src/k8s.io/component-helpers/apps/poddisruptionbudget/helpers.go","code":"// ConditionsAreUpToDate checks whether the status and reason for the\n// DisruptionAllowed condition are set to the correct values based on the\n// DisruptionsAllowed field.\nfunc ConditionsAreUpToDate(pdb *policy.PodDisruptionBudget) bool {\n\tcond := apimeta.FindStatusCondition(pdb.Status.Conditions, policy.DisruptionAllowedCondition)\n\tif cond == nil {\n\t\treturn false\n\t}\n\n\tif pdb.Status.ObservedGeneration != pdb.Generation {\n\t\treturn false\n\t}\n\n\tif pdb.Status.DisruptionsAllowed \u003e 0 {\n\t\treturn cond.Status == metav1.ConditionTrue \u0026\u0026 cond.Reason == policy.SufficientPodsReason\n\t}\n\treturn cond.Status == metav1.ConditionFalse \u0026\u0026 cond.Reason == policy.InsufficientPodsReason\n}","line":{"from":48,"to":65}} {"id":100030627,"name":"GetObject","signature":"func (o ClusterRoleRuleOwner) GetObject() runtime.Object","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrole_interfaces.go","code":"func (o ClusterRoleRuleOwner) GetObject() runtime.Object {\n\treturn o.ClusterRole\n}","line":{"from":35,"to":37}} {"id":100030628,"name":"GetNamespace","signature":"func (o ClusterRoleRuleOwner) GetNamespace() string","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrole_interfaces.go","code":"func (o ClusterRoleRuleOwner) GetNamespace() string {\n\treturn o.ClusterRole.Namespace\n}","line":{"from":39,"to":41}} {"id":100030629,"name":"GetName","signature":"func (o ClusterRoleRuleOwner) GetName() string","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrole_interfaces.go","code":"func (o ClusterRoleRuleOwner) GetName() string {\n\treturn o.ClusterRole.Name\n}","line":{"from":43,"to":45}} {"id":100030630,"name":"GetLabels","signature":"func (o ClusterRoleRuleOwner) GetLabels() map[string]string","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrole_interfaces.go","code":"func (o ClusterRoleRuleOwner) GetLabels() map[string]string {\n\treturn o.ClusterRole.Labels\n}","line":{"from":47,"to":49}} {"id":100030631,"name":"SetLabels","signature":"func (o ClusterRoleRuleOwner) SetLabels(in map[string]string)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrole_interfaces.go","code":"func (o ClusterRoleRuleOwner) SetLabels(in map[string]string) {\n\to.ClusterRole.Labels = in\n}","line":{"from":51,"to":53}} {"id":100030632,"name":"GetAnnotations","signature":"func (o ClusterRoleRuleOwner) GetAnnotations() map[string]string","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrole_interfaces.go","code":"func (o ClusterRoleRuleOwner) GetAnnotations() map[string]string {\n\treturn o.ClusterRole.Annotations\n}","line":{"from":55,"to":57}} {"id":100030633,"name":"SetAnnotations","signature":"func (o ClusterRoleRuleOwner) SetAnnotations(in map[string]string)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrole_interfaces.go","code":"func (o ClusterRoleRuleOwner) SetAnnotations(in map[string]string) {\n\to.ClusterRole.Annotations = in\n}","line":{"from":59,"to":61}} {"id":100030634,"name":"GetRules","signature":"func (o ClusterRoleRuleOwner) GetRules() []rbacv1.PolicyRule","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrole_interfaces.go","code":"func (o ClusterRoleRuleOwner) GetRules() []rbacv1.PolicyRule {\n\treturn o.ClusterRole.Rules\n}","line":{"from":63,"to":65}} {"id":100030635,"name":"SetRules","signature":"func (o ClusterRoleRuleOwner) SetRules(in []rbacv1.PolicyRule)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrole_interfaces.go","code":"func (o ClusterRoleRuleOwner) SetRules(in []rbacv1.PolicyRule) {\n\to.ClusterRole.Rules = in\n}","line":{"from":67,"to":69}} {"id":100030636,"name":"GetAggregationRule","signature":"func (o ClusterRoleRuleOwner) GetAggregationRule() *rbacv1.AggregationRule","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrole_interfaces.go","code":"func (o ClusterRoleRuleOwner) GetAggregationRule() *rbacv1.AggregationRule {\n\treturn o.ClusterRole.AggregationRule\n}","line":{"from":71,"to":73}} {"id":100030637,"name":"SetAggregationRule","signature":"func (o ClusterRoleRuleOwner) SetAggregationRule(in *rbacv1.AggregationRule)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrole_interfaces.go","code":"func (o ClusterRoleRuleOwner) SetAggregationRule(in *rbacv1.AggregationRule) {\n\to.ClusterRole.AggregationRule = in\n}","line":{"from":75,"to":77}} {"id":100030638,"name":"Get","signature":"func (c ClusterRoleModifier) Get(namespace, name string) (RuleOwner, error)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrole_interfaces.go","code":"func (c ClusterRoleModifier) Get(namespace, name string) (RuleOwner, error) {\n\tret, err := c.Client.Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ClusterRoleRuleOwner{ClusterRole: ret}, err\n}","line":{"from":83,"to":89}} {"id":100030639,"name":"Create","signature":"func (c ClusterRoleModifier) Create(in RuleOwner) (RuleOwner, error)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrole_interfaces.go","code":"func (c ClusterRoleModifier) Create(in RuleOwner) (RuleOwner, error) {\n\tret, err := c.Client.Create(context.TODO(), in.(ClusterRoleRuleOwner).ClusterRole, metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ClusterRoleRuleOwner{ClusterRole: ret}, err\n}","line":{"from":91,"to":97}} {"id":100030640,"name":"Update","signature":"func (c ClusterRoleModifier) Update(in RuleOwner) (RuleOwner, error)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrole_interfaces.go","code":"func (c ClusterRoleModifier) Update(in RuleOwner) (RuleOwner, error) {\n\tret, err := c.Client.Update(context.TODO(), in.(ClusterRoleRuleOwner).ClusterRole, metav1.UpdateOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ClusterRoleRuleOwner{ClusterRole: ret}, err\n\n}","line":{"from":99,"to":106}} {"id":100030641,"name":"GetObject","signature":"func (o ClusterRoleBindingAdapter) GetObject() runtime.Object","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrolebinding_interfaces.go","code":"func (o ClusterRoleBindingAdapter) GetObject() runtime.Object {\n\treturn o.ClusterRoleBinding\n}","line":{"from":36,"to":38}} {"id":100030642,"name":"GetNamespace","signature":"func (o ClusterRoleBindingAdapter) GetNamespace() string","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrolebinding_interfaces.go","code":"func (o ClusterRoleBindingAdapter) GetNamespace() string {\n\treturn o.ClusterRoleBinding.Namespace\n}","line":{"from":40,"to":42}} {"id":100030643,"name":"GetName","signature":"func (o ClusterRoleBindingAdapter) GetName() string","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrolebinding_interfaces.go","code":"func (o ClusterRoleBindingAdapter) GetName() string {\n\treturn o.ClusterRoleBinding.Name\n}","line":{"from":44,"to":46}} {"id":100030644,"name":"GetUID","signature":"func (o ClusterRoleBindingAdapter) GetUID() types.UID","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrolebinding_interfaces.go","code":"func (o ClusterRoleBindingAdapter) GetUID() types.UID {\n\treturn o.ClusterRoleBinding.UID\n}","line":{"from":48,"to":50}} {"id":100030645,"name":"GetLabels","signature":"func (o ClusterRoleBindingAdapter) GetLabels() map[string]string","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrolebinding_interfaces.go","code":"func (o ClusterRoleBindingAdapter) GetLabels() map[string]string {\n\treturn o.ClusterRoleBinding.Labels\n}","line":{"from":52,"to":54}} {"id":100030646,"name":"SetLabels","signature":"func (o ClusterRoleBindingAdapter) SetLabels(in map[string]string)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrolebinding_interfaces.go","code":"func (o ClusterRoleBindingAdapter) SetLabels(in map[string]string) {\n\to.ClusterRoleBinding.Labels = in\n}","line":{"from":56,"to":58}} {"id":100030647,"name":"GetAnnotations","signature":"func (o ClusterRoleBindingAdapter) GetAnnotations() map[string]string","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrolebinding_interfaces.go","code":"func (o ClusterRoleBindingAdapter) GetAnnotations() map[string]string {\n\treturn o.ClusterRoleBinding.Annotations\n}","line":{"from":60,"to":62}} {"id":100030648,"name":"SetAnnotations","signature":"func (o ClusterRoleBindingAdapter) SetAnnotations(in map[string]string)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrolebinding_interfaces.go","code":"func (o ClusterRoleBindingAdapter) SetAnnotations(in map[string]string) {\n\to.ClusterRoleBinding.Annotations = in\n}","line":{"from":64,"to":66}} {"id":100030649,"name":"GetRoleRef","signature":"func (o ClusterRoleBindingAdapter) GetRoleRef() rbacv1.RoleRef","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrolebinding_interfaces.go","code":"func (o ClusterRoleBindingAdapter) GetRoleRef() rbacv1.RoleRef {\n\treturn o.ClusterRoleBinding.RoleRef\n}","line":{"from":68,"to":70}} {"id":100030650,"name":"GetSubjects","signature":"func (o ClusterRoleBindingAdapter) GetSubjects() []rbacv1.Subject","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrolebinding_interfaces.go","code":"func (o ClusterRoleBindingAdapter) GetSubjects() []rbacv1.Subject {\n\treturn o.ClusterRoleBinding.Subjects\n}","line":{"from":72,"to":74}} {"id":100030651,"name":"SetSubjects","signature":"func (o ClusterRoleBindingAdapter) SetSubjects(in []rbacv1.Subject)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrolebinding_interfaces.go","code":"func (o ClusterRoleBindingAdapter) SetSubjects(in []rbacv1.Subject) {\n\to.ClusterRoleBinding.Subjects = in\n}","line":{"from":76,"to":78}} {"id":100030652,"name":"Get","signature":"func (c ClusterRoleBindingClientAdapter) Get(namespace, name string) (RoleBinding, error)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrolebinding_interfaces.go","code":"func (c ClusterRoleBindingClientAdapter) Get(namespace, name string) (RoleBinding, error) {\n\tret, err := c.Client.Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ClusterRoleBindingAdapter{ClusterRoleBinding: ret}, err\n}","line":{"from":84,"to":90}} {"id":100030653,"name":"Create","signature":"func (c ClusterRoleBindingClientAdapter) Create(in RoleBinding) (RoleBinding, error)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrolebinding_interfaces.go","code":"func (c ClusterRoleBindingClientAdapter) Create(in RoleBinding) (RoleBinding, error) {\n\tret, err := c.Client.Create(context.TODO(), in.(ClusterRoleBindingAdapter).ClusterRoleBinding, metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ClusterRoleBindingAdapter{ClusterRoleBinding: ret}, err\n}","line":{"from":92,"to":98}} {"id":100030654,"name":"Update","signature":"func (c ClusterRoleBindingClientAdapter) Update(in RoleBinding) (RoleBinding, error)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrolebinding_interfaces.go","code":"func (c ClusterRoleBindingClientAdapter) Update(in RoleBinding) (RoleBinding, error) {\n\tret, err := c.Client.Update(context.TODO(), in.(ClusterRoleBindingAdapter).ClusterRoleBinding, metav1.UpdateOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ClusterRoleBindingAdapter{ClusterRoleBinding: ret}, err\n\n}","line":{"from":100,"to":107}} {"id":100030655,"name":"Delete","signature":"func (c ClusterRoleBindingClientAdapter) Delete(namespace, name string, uid types.UID) error","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/clusterrolebinding_interfaces.go","code":"func (c ClusterRoleBindingClientAdapter) Delete(namespace, name string, uid types.UID) error {\n\treturn c.Client.Delete(context.TODO(), name, metav1.DeleteOptions{Preconditions: \u0026metav1.Preconditions{UID: \u0026uid}})\n}","line":{"from":109,"to":111}} {"id":100030656,"name":"tryEnsureNamespace","signature":"func tryEnsureNamespace(client corev1client.NamespaceInterface, namespace string) error","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/namespace.go","code":"// tryEnsureNamespace gets or creates the given namespace while ignoring forbidden errors.\n// It is a best effort attempt as the user may not be able to get or create namespaces.\n// This allows us to handle flows where the user can only mutate roles and role bindings.\nfunc tryEnsureNamespace(client corev1client.NamespaceInterface, namespace string) error {\n\t_, getErr := client.Get(context.TODO(), namespace, metav1.GetOptions{})\n\tif getErr == nil {\n\t\treturn nil\n\t}\n\n\tif fatalGetErr := utilerrors.FilterOut(getErr, apierrors.IsNotFound, apierrors.IsForbidden); fatalGetErr != nil {\n\t\treturn fatalGetErr\n\t}\n\n\tns := \u0026corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace}}\n\t_, createErr := client.Create(context.TODO(), ns, metav1.CreateOptions{})\n\n\treturn utilerrors.FilterOut(createErr, apierrors.IsAlreadyExists, apierrors.IsForbidden)\n}","line":{"from":28,"to":45}} {"id":100030657,"name":"Run","signature":"func (o *ReconcileRoleOptions) Run() (*ReconcileClusterRoleResult, error)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/reconcile_role.go","code":"func (o *ReconcileRoleOptions) Run() (*ReconcileClusterRoleResult, error) {\n\treturn o.run(0)\n}","line":{"from":97,"to":99}} {"id":100030658,"name":"run","signature":"func (o *ReconcileRoleOptions) run(attempts int) (*ReconcileClusterRoleResult, error)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/reconcile_role.go","code":"func (o *ReconcileRoleOptions) run(attempts int) (*ReconcileClusterRoleResult, error) {\n\t// This keeps us from retrying forever if a role keeps appearing and disappearing as we reconcile.\n\t// Conflict errors on update are handled at a higher level.\n\tif attempts \u003e 2 {\n\t\treturn nil, fmt.Errorf(\"exceeded maximum attempts\")\n\t}\n\n\tvar result *ReconcileClusterRoleResult\n\n\texisting, err := o.Client.Get(o.Role.GetNamespace(), o.Role.GetName())\n\tswitch {\n\tcase errors.IsNotFound(err):\n\t\taggregationRule := o.Role.GetAggregationRule()\n\t\tif aggregationRule == nil {\n\t\t\taggregationRule = \u0026rbacv1.AggregationRule{}\n\t\t}\n\t\tresult = \u0026ReconcileClusterRoleResult{\n\t\t\tRole: o.Role,\n\t\t\tMissingRules: o.Role.GetRules(),\n\t\t\tMissingAggregationRuleSelectors: aggregationRule.ClusterRoleSelectors,\n\t\t\tOperation: ReconcileCreate,\n\t\t}\n\n\tcase err != nil:\n\t\treturn nil, err\n\n\tdefault:\n\t\tresult, err = computeReconciledRole(existing, o.Role, o.RemoveExtraPermissions)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// If reconcile-protected, short-circuit\n\tif result.Protected {\n\t\treturn result, nil\n\t}\n\t// If we're in dry-run mode, short-circuit\n\tif !o.Confirm {\n\t\treturn result, nil\n\t}\n\n\tswitch result.Operation {\n\tcase ReconcileCreate:\n\t\tcreated, err := o.Client.Create(result.Role)\n\t\t// If created since we started this reconcile, re-run\n\t\tif errors.IsAlreadyExists(err) {\n\t\t\treturn o.run(attempts + 1)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult.Role = created\n\n\tcase ReconcileUpdate:\n\t\tupdated, err := o.Client.Update(result.Role)\n\t\t// If deleted since we started this reconcile, re-run\n\t\tif errors.IsNotFound(err) {\n\t\t\treturn o.run(attempts + 1)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult.Role = updated\n\n\tcase ReconcileNone:\n\t\t// no-op\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid operation: %v\", result.Operation)\n\t}\n\n\treturn result, nil\n}","line":{"from":101,"to":174}} {"id":100030659,"name":"computeReconciledRole","signature":"func computeReconciledRole(existing, expected RuleOwner, removeExtraPermissions bool) (*ReconcileClusterRoleResult, error)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/reconcile_role.go","code":"// computeReconciledRole returns the role that must be created and/or updated to make the\n// existing role's permissions match the expected role's permissions\nfunc computeReconciledRole(existing, expected RuleOwner, removeExtraPermissions bool) (*ReconcileClusterRoleResult, error) {\n\tresult := \u0026ReconcileClusterRoleResult{Operation: ReconcileNone}\n\n\tresult.Protected = (existing.GetAnnotations()[rbacv1.AutoUpdateAnnotationKey] == \"false\")\n\n\t// Start with a copy of the existing object\n\tresult.Role = existing.DeepCopyRuleOwner()\n\n\t// Merge expected annotations and labels\n\tresult.Role.SetAnnotations(merge(expected.GetAnnotations(), result.Role.GetAnnotations()))\n\tif !reflect.DeepEqual(result.Role.GetAnnotations(), existing.GetAnnotations()) {\n\t\tresult.Operation = ReconcileUpdate\n\t}\n\tresult.Role.SetLabels(merge(expected.GetLabels(), result.Role.GetLabels()))\n\tif !reflect.DeepEqual(result.Role.GetLabels(), existing.GetLabels()) {\n\t\tresult.Operation = ReconcileUpdate\n\t}\n\n\t// Compute extra and missing rules\n\t// Don't compute extra permissions if expected and existing roles are both aggregated\n\tif expected.GetAggregationRule() == nil || existing.GetAggregationRule() == nil {\n\t\t_, result.ExtraRules = validation.Covers(expected.GetRules(), existing.GetRules())\n\t}\n\t_, result.MissingRules = validation.Covers(existing.GetRules(), expected.GetRules())\n\n\tswitch {\n\tcase !removeExtraPermissions \u0026\u0026 len(result.MissingRules) \u003e 0:\n\t\t// add missing rules in the union case\n\t\tresult.Role.SetRules(append(result.Role.GetRules(), result.MissingRules...))\n\t\tresult.Operation = ReconcileUpdate\n\n\tcase removeExtraPermissions \u0026\u0026 (len(result.MissingRules) \u003e 0 || len(result.ExtraRules) \u003e 0):\n\t\t// stomp to expected rules in the non-union case\n\t\tresult.Role.SetRules(expected.GetRules())\n\t\tresult.Operation = ReconcileUpdate\n\t}\n\n\t// Compute extra and missing rules\n\t_, result.ExtraAggregationRuleSelectors = aggregationRuleCovers(expected.GetAggregationRule(), existing.GetAggregationRule())\n\t_, result.MissingAggregationRuleSelectors = aggregationRuleCovers(existing.GetAggregationRule(), expected.GetAggregationRule())\n\n\tswitch {\n\tcase expected.GetAggregationRule() == nil \u0026\u0026 existing.GetAggregationRule() != nil:\n\t\t// we didn't expect this to be an aggregated role at all, remove the existing aggregation\n\t\tresult.Role.SetAggregationRule(nil)\n\t\tresult.Operation = ReconcileUpdate\n\n\tcase !removeExtraPermissions \u0026\u0026 len(result.MissingAggregationRuleSelectors) \u003e 0:\n\t\t// add missing rules in the union case\n\t\taggregationRule := result.Role.GetAggregationRule()\n\t\tif aggregationRule == nil {\n\t\t\taggregationRule = \u0026rbacv1.AggregationRule{}\n\t\t}\n\t\taggregationRule.ClusterRoleSelectors = append(aggregationRule.ClusterRoleSelectors, result.MissingAggregationRuleSelectors...)\n\t\tresult.Role.SetAggregationRule(aggregationRule)\n\t\tresult.Operation = ReconcileUpdate\n\n\tcase removeExtraPermissions \u0026\u0026 (len(result.MissingAggregationRuleSelectors) \u003e 0 || len(result.ExtraAggregationRuleSelectors) \u003e 0):\n\t\tresult.Role.SetAggregationRule(expected.GetAggregationRule())\n\t\tresult.Operation = ReconcileUpdate\n\t}\n\n\treturn result, nil\n}","line":{"from":176,"to":241}} {"id":100030660,"name":"merge","signature":"func merge(maps ...map[string]string) map[string]string","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/reconcile_role.go","code":"// merge combines the given maps with the later annotations having higher precedence\nfunc merge(maps ...map[string]string) map[string]string {\n\tvar output map[string]string = nil\n\tfor _, m := range maps {\n\t\tif m != nil \u0026\u0026 output == nil {\n\t\t\toutput = map[string]string{}\n\t\t}\n\t\tfor k, v := range m {\n\t\t\toutput[k] = v\n\t\t}\n\t}\n\treturn output\n}","line":{"from":243,"to":255}} {"id":100030661,"name":"aggregationRuleCovers","signature":"func aggregationRuleCovers(ownerRule, servantRule *rbacv1.AggregationRule) (bool, []metav1.LabelSelector)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/reconcile_role.go","code":"// aggregationRuleCovers determines whether or not the ownerSelectors cover the servantSelectors in terms of semantically\n// equal label selectors.\n// It returns whether or not the ownerSelectors cover and a list of the rules that the ownerSelectors do not cover.\nfunc aggregationRuleCovers(ownerRule, servantRule *rbacv1.AggregationRule) (bool, []metav1.LabelSelector) {\n\tswitch {\n\tcase ownerRule == nil \u0026\u0026 servantRule == nil:\n\t\treturn true, []metav1.LabelSelector{}\n\tcase ownerRule == nil \u0026\u0026 servantRule != nil:\n\t\treturn false, servantRule.ClusterRoleSelectors\n\tcase ownerRule != nil \u0026\u0026 servantRule == nil:\n\t\treturn true, []metav1.LabelSelector{}\n\n\t}\n\n\townerSelectors := ownerRule.ClusterRoleSelectors\n\tservantSelectors := servantRule.ClusterRoleSelectors\n\tuncoveredSelectors := []metav1.LabelSelector{}\n\n\tfor _, servantSelector := range servantSelectors {\n\t\tcovered := false\n\t\tfor _, ownerSelector := range ownerSelectors {\n\t\t\tif equality.Semantic.DeepEqual(ownerSelector, servantSelector) {\n\t\t\t\tcovered = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !covered {\n\t\t\tuncoveredSelectors = append(uncoveredSelectors, servantSelector)\n\t\t}\n\t}\n\n\treturn (len(uncoveredSelectors) == 0), uncoveredSelectors\n}","line":{"from":257,"to":289}} {"id":100030662,"name":"Run","signature":"func (o *ReconcileRoleBindingOptions) Run() (*ReconcileClusterRoleBindingResult, error)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/reconcile_rolebindings.go","code":"func (o *ReconcileRoleBindingOptions) Run() (*ReconcileClusterRoleBindingResult, error) {\n\treturn o.run(0)\n}","line":{"from":84,"to":86}} {"id":100030663,"name":"run","signature":"func (o *ReconcileRoleBindingOptions) run(attempts int) (*ReconcileClusterRoleBindingResult, error)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/reconcile_rolebindings.go","code":"func (o *ReconcileRoleBindingOptions) run(attempts int) (*ReconcileClusterRoleBindingResult, error) {\n\t// This keeps us from retrying forever if a rolebinding keeps appearing and disappearing as we reconcile.\n\t// Conflict errors on update are handled at a higher level.\n\tif attempts \u003e 3 {\n\t\treturn nil, fmt.Errorf(\"exceeded maximum attempts\")\n\t}\n\n\tvar result *ReconcileClusterRoleBindingResult\n\n\texistingBinding, err := o.Client.Get(o.RoleBinding.GetNamespace(), o.RoleBinding.GetName())\n\tswitch {\n\tcase errors.IsNotFound(err):\n\t\tresult = \u0026ReconcileClusterRoleBindingResult{\n\t\t\tRoleBinding: o.RoleBinding,\n\t\t\tMissingSubjects: o.RoleBinding.GetSubjects(),\n\t\t\tOperation: ReconcileCreate,\n\t\t}\n\n\tcase err != nil:\n\t\treturn nil, err\n\n\tdefault:\n\t\tresult, err = computeReconciledRoleBinding(existingBinding, o.RoleBinding, o.RemoveExtraSubjects)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// If reconcile-protected, short-circuit\n\tif result.Protected {\n\t\treturn result, nil\n\t}\n\t// If we're in dry-run mode, short-circuit\n\tif !o.Confirm {\n\t\treturn result, nil\n\t}\n\n\tswitch result.Operation {\n\tcase ReconcileRecreate:\n\t\t// Try deleting\n\t\terr := o.Client.Delete(existingBinding.GetNamespace(), existingBinding.GetName(), existingBinding.GetUID())\n\t\tswitch {\n\t\tcase err == nil, errors.IsNotFound(err):\n\t\t\t// object no longer exists, as desired\n\t\tcase errors.IsConflict(err):\n\t\t\t// delete failed because our UID precondition conflicted\n\t\t\t// this could mean another object exists with a different UID, re-run\n\t\t\treturn o.run(attempts + 1)\n\t\tdefault:\n\t\t\t// return other errors\n\t\t\treturn nil, err\n\t\t}\n\t\t// continue to create\n\t\tfallthrough\n\tcase ReconcileCreate:\n\t\tcreated, err := o.Client.Create(result.RoleBinding)\n\t\t// If created since we started this reconcile, re-run\n\t\tif errors.IsAlreadyExists(err) {\n\t\t\treturn o.run(attempts + 1)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult.RoleBinding = created\n\n\tcase ReconcileUpdate:\n\t\tupdated, err := o.Client.Update(result.RoleBinding)\n\t\t// If deleted since we started this reconcile, re-run\n\t\tif errors.IsNotFound(err) {\n\t\t\treturn o.run(attempts + 1)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult.RoleBinding = updated\n\n\tcase ReconcileNone:\n\t\t// no-op\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid operation: %v\", result.Operation)\n\t}\n\n\treturn result, nil\n}","line":{"from":88,"to":172}} {"id":100030664,"name":"computeReconciledRoleBinding","signature":"func computeReconciledRoleBinding(existing, expected RoleBinding, removeExtraSubjects bool) (*ReconcileClusterRoleBindingResult, error)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/reconcile_rolebindings.go","code":"// computeReconciledRoleBinding returns the rolebinding that must be created and/or updated to make the\n// existing rolebinding's subjects, roleref, labels, and annotations match the expected rolebinding\nfunc computeReconciledRoleBinding(existing, expected RoleBinding, removeExtraSubjects bool) (*ReconcileClusterRoleBindingResult, error) {\n\tresult := \u0026ReconcileClusterRoleBindingResult{Operation: ReconcileNone}\n\n\tresult.Protected = (existing.GetAnnotations()[rbacv1.AutoUpdateAnnotationKey] == \"false\")\n\n\t// Reset the binding completely if the roleRef is different\n\tif expected.GetRoleRef() != existing.GetRoleRef() {\n\t\tresult.RoleBinding = expected\n\t\tresult.Operation = ReconcileRecreate\n\t\treturn result, nil\n\t}\n\n\t// Start with a copy of the existing object\n\tresult.RoleBinding = existing.DeepCopyRoleBinding()\n\n\t// Merge expected annotations and labels\n\tresult.RoleBinding.SetAnnotations(merge(expected.GetAnnotations(), result.RoleBinding.GetAnnotations()))\n\tif !reflect.DeepEqual(result.RoleBinding.GetAnnotations(), existing.GetAnnotations()) {\n\t\tresult.Operation = ReconcileUpdate\n\t}\n\tresult.RoleBinding.SetLabels(merge(expected.GetLabels(), result.RoleBinding.GetLabels()))\n\tif !reflect.DeepEqual(result.RoleBinding.GetLabels(), existing.GetLabels()) {\n\t\tresult.Operation = ReconcileUpdate\n\t}\n\n\t// Compute extra and missing subjects\n\tresult.MissingSubjects, result.ExtraSubjects = diffSubjectLists(expected.GetSubjects(), existing.GetSubjects())\n\n\tswitch {\n\tcase !removeExtraSubjects \u0026\u0026 len(result.MissingSubjects) \u003e 0:\n\t\t// add missing subjects in the union case\n\t\tresult.RoleBinding.SetSubjects(append(result.RoleBinding.GetSubjects(), result.MissingSubjects...))\n\t\tresult.Operation = ReconcileUpdate\n\n\tcase removeExtraSubjects \u0026\u0026 (len(result.MissingSubjects) \u003e 0 || len(result.ExtraSubjects) \u003e 0):\n\t\t// stomp to expected subjects in the non-union case\n\t\tresult.RoleBinding.SetSubjects(expected.GetSubjects())\n\t\tresult.Operation = ReconcileUpdate\n\t}\n\n\treturn result, nil\n}","line":{"from":174,"to":217}} {"id":100030665,"name":"contains","signature":"func contains(list []rbacv1.Subject, item rbacv1.Subject) bool","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/reconcile_rolebindings.go","code":"func contains(list []rbacv1.Subject, item rbacv1.Subject) bool {\n\tfor _, listItem := range list {\n\t\tif listItem == item {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":219,"to":226}} {"id":100030666,"name":"diffSubjectLists","signature":"func diffSubjectLists(list1 []rbacv1.Subject, list2 []rbacv1.Subject) (list1Only []rbacv1.Subject, list2Only []rbacv1.Subject)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/reconcile_rolebindings.go","code":"// diffSubjectLists returns lists containing the items unique to each provided list:\n//\n//\tlist1Only = list1 - list2\n//\tlist2Only = list2 - list1\n//\n// if both returned lists are empty, the provided lists are equal\nfunc diffSubjectLists(list1 []rbacv1.Subject, list2 []rbacv1.Subject) (list1Only []rbacv1.Subject, list2Only []rbacv1.Subject) {\n\tfor _, list1Item := range list1 {\n\t\tif !contains(list2, list1Item) {\n\t\t\tif !contains(list1Only, list1Item) {\n\t\t\t\tlist1Only = append(list1Only, list1Item)\n\t\t\t}\n\t\t}\n\t}\n\tfor _, list2Item := range list2 {\n\t\tif !contains(list1, list2Item) {\n\t\t\tif !contains(list2Only, list2Item) {\n\t\t\t\tlist2Only = append(list2Only, list2Item)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}","line":{"from":228,"to":250}} {"id":100030667,"name":"GetObject","signature":"func (o RoleRuleOwner) GetObject() runtime.Object","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/role_interfaces.go","code":"func (o RoleRuleOwner) GetObject() runtime.Object {\n\treturn o.Role\n}","line":{"from":36,"to":38}} {"id":100030668,"name":"GetNamespace","signature":"func (o RoleRuleOwner) GetNamespace() string","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/role_interfaces.go","code":"func (o RoleRuleOwner) GetNamespace() string {\n\treturn o.Role.Namespace\n}","line":{"from":40,"to":42}} {"id":100030669,"name":"GetName","signature":"func (o RoleRuleOwner) GetName() string","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/role_interfaces.go","code":"func (o RoleRuleOwner) GetName() string {\n\treturn o.Role.Name\n}","line":{"from":44,"to":46}} {"id":100030670,"name":"GetLabels","signature":"func (o RoleRuleOwner) GetLabels() map[string]string","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/role_interfaces.go","code":"func (o RoleRuleOwner) GetLabels() map[string]string {\n\treturn o.Role.Labels\n}","line":{"from":48,"to":50}} {"id":100030671,"name":"SetLabels","signature":"func (o RoleRuleOwner) SetLabels(in map[string]string)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/role_interfaces.go","code":"func (o RoleRuleOwner) SetLabels(in map[string]string) {\n\to.Role.Labels = in\n}","line":{"from":52,"to":54}} {"id":100030672,"name":"GetAnnotations","signature":"func (o RoleRuleOwner) GetAnnotations() map[string]string","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/role_interfaces.go","code":"func (o RoleRuleOwner) GetAnnotations() map[string]string {\n\treturn o.Role.Annotations\n}","line":{"from":56,"to":58}} {"id":100030673,"name":"SetAnnotations","signature":"func (o RoleRuleOwner) SetAnnotations(in map[string]string)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/role_interfaces.go","code":"func (o RoleRuleOwner) SetAnnotations(in map[string]string) {\n\to.Role.Annotations = in\n}","line":{"from":60,"to":62}} {"id":100030674,"name":"GetRules","signature":"func (o RoleRuleOwner) GetRules() []rbacv1.PolicyRule","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/role_interfaces.go","code":"func (o RoleRuleOwner) GetRules() []rbacv1.PolicyRule {\n\treturn o.Role.Rules\n}","line":{"from":64,"to":66}} {"id":100030675,"name":"SetRules","signature":"func (o RoleRuleOwner) SetRules(in []rbacv1.PolicyRule)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/role_interfaces.go","code":"func (o RoleRuleOwner) SetRules(in []rbacv1.PolicyRule) {\n\to.Role.Rules = in\n}","line":{"from":68,"to":70}} {"id":100030676,"name":"GetAggregationRule","signature":"func (o RoleRuleOwner) GetAggregationRule() *rbacv1.AggregationRule","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/role_interfaces.go","code":"func (o RoleRuleOwner) GetAggregationRule() *rbacv1.AggregationRule {\n\treturn nil\n}","line":{"from":72,"to":74}} {"id":100030677,"name":"SetAggregationRule","signature":"func (o RoleRuleOwner) SetAggregationRule(in *rbacv1.AggregationRule)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/role_interfaces.go","code":"func (o RoleRuleOwner) SetAggregationRule(in *rbacv1.AggregationRule) {\n}","line":{"from":76,"to":77}} {"id":100030678,"name":"Get","signature":"func (c RoleModifier) Get(namespace, name string) (RuleOwner, error)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/role_interfaces.go","code":"func (c RoleModifier) Get(namespace, name string) (RuleOwner, error) {\n\tret, err := c.Client.Roles(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn RoleRuleOwner{Role: ret}, err\n}","line":{"from":84,"to":90}} {"id":100030679,"name":"Create","signature":"func (c RoleModifier) Create(in RuleOwner) (RuleOwner, error)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/role_interfaces.go","code":"func (c RoleModifier) Create(in RuleOwner) (RuleOwner, error) {\n\tif err := tryEnsureNamespace(c.NamespaceClient, in.GetNamespace()); err != nil {\n\t\treturn nil, err\n\t}\n\n\tret, err := c.Client.Roles(in.GetNamespace()).Create(context.TODO(), in.(RoleRuleOwner).Role, metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn RoleRuleOwner{Role: ret}, err\n}","line":{"from":92,"to":102}} {"id":100030680,"name":"Update","signature":"func (c RoleModifier) Update(in RuleOwner) (RuleOwner, error)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/role_interfaces.go","code":"func (c RoleModifier) Update(in RuleOwner) (RuleOwner, error) {\n\tret, err := c.Client.Roles(in.GetNamespace()).Update(context.TODO(), in.(RoleRuleOwner).Role, metav1.UpdateOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn RoleRuleOwner{Role: ret}, err\n\n}","line":{"from":104,"to":111}} {"id":100030681,"name":"GetObject","signature":"func (o RoleBindingAdapter) GetObject() runtime.Object","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/rolebinding_interfaces.go","code":"func (o RoleBindingAdapter) GetObject() runtime.Object {\n\treturn o.RoleBinding\n}","line":{"from":37,"to":39}} {"id":100030682,"name":"GetNamespace","signature":"func (o RoleBindingAdapter) GetNamespace() string","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/rolebinding_interfaces.go","code":"func (o RoleBindingAdapter) GetNamespace() string {\n\treturn o.RoleBinding.Namespace\n}","line":{"from":41,"to":43}} {"id":100030683,"name":"GetName","signature":"func (o RoleBindingAdapter) GetName() string","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/rolebinding_interfaces.go","code":"func (o RoleBindingAdapter) GetName() string {\n\treturn o.RoleBinding.Name\n}","line":{"from":45,"to":47}} {"id":100030684,"name":"GetUID","signature":"func (o RoleBindingAdapter) GetUID() types.UID","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/rolebinding_interfaces.go","code":"func (o RoleBindingAdapter) GetUID() types.UID {\n\treturn o.RoleBinding.UID\n}","line":{"from":49,"to":51}} {"id":100030685,"name":"GetLabels","signature":"func (o RoleBindingAdapter) GetLabels() map[string]string","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/rolebinding_interfaces.go","code":"func (o RoleBindingAdapter) GetLabels() map[string]string {\n\treturn o.RoleBinding.Labels\n}","line":{"from":53,"to":55}} {"id":100030686,"name":"SetLabels","signature":"func (o RoleBindingAdapter) SetLabels(in map[string]string)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/rolebinding_interfaces.go","code":"func (o RoleBindingAdapter) SetLabels(in map[string]string) {\n\to.RoleBinding.Labels = in\n}","line":{"from":57,"to":59}} {"id":100030687,"name":"GetAnnotations","signature":"func (o RoleBindingAdapter) GetAnnotations() map[string]string","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/rolebinding_interfaces.go","code":"func (o RoleBindingAdapter) GetAnnotations() map[string]string {\n\treturn o.RoleBinding.Annotations\n}","line":{"from":61,"to":63}} {"id":100030688,"name":"SetAnnotations","signature":"func (o RoleBindingAdapter) SetAnnotations(in map[string]string)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/rolebinding_interfaces.go","code":"func (o RoleBindingAdapter) SetAnnotations(in map[string]string) {\n\to.RoleBinding.Annotations = in\n}","line":{"from":65,"to":67}} {"id":100030689,"name":"GetRoleRef","signature":"func (o RoleBindingAdapter) GetRoleRef() rbacv1.RoleRef","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/rolebinding_interfaces.go","code":"func (o RoleBindingAdapter) GetRoleRef() rbacv1.RoleRef {\n\treturn o.RoleBinding.RoleRef\n}","line":{"from":69,"to":71}} {"id":100030690,"name":"GetSubjects","signature":"func (o RoleBindingAdapter) GetSubjects() []rbacv1.Subject","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/rolebinding_interfaces.go","code":"func (o RoleBindingAdapter) GetSubjects() []rbacv1.Subject {\n\treturn o.RoleBinding.Subjects\n}","line":{"from":73,"to":75}} {"id":100030691,"name":"SetSubjects","signature":"func (o RoleBindingAdapter) SetSubjects(in []rbacv1.Subject)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/rolebinding_interfaces.go","code":"func (o RoleBindingAdapter) SetSubjects(in []rbacv1.Subject) {\n\to.RoleBinding.Subjects = in\n}","line":{"from":77,"to":79}} {"id":100030692,"name":"Get","signature":"func (c RoleBindingClientAdapter) Get(namespace, name string) (RoleBinding, error)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/rolebinding_interfaces.go","code":"func (c RoleBindingClientAdapter) Get(namespace, name string) (RoleBinding, error) {\n\tret, err := c.Client.RoleBindings(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn RoleBindingAdapter{RoleBinding: ret}, err\n}","line":{"from":86,"to":92}} {"id":100030693,"name":"Create","signature":"func (c RoleBindingClientAdapter) Create(in RoleBinding) (RoleBinding, error)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/rolebinding_interfaces.go","code":"func (c RoleBindingClientAdapter) Create(in RoleBinding) (RoleBinding, error) {\n\tif err := tryEnsureNamespace(c.NamespaceClient, in.GetNamespace()); err != nil {\n\t\treturn nil, err\n\t}\n\n\tret, err := c.Client.RoleBindings(in.GetNamespace()).Create(context.TODO(), in.(RoleBindingAdapter).RoleBinding, metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn RoleBindingAdapter{RoleBinding: ret}, err\n}","line":{"from":94,"to":104}} {"id":100030694,"name":"Update","signature":"func (c RoleBindingClientAdapter) Update(in RoleBinding) (RoleBinding, error)","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/rolebinding_interfaces.go","code":"func (c RoleBindingClientAdapter) Update(in RoleBinding) (RoleBinding, error) {\n\tret, err := c.Client.RoleBindings(in.GetNamespace()).Update(context.TODO(), in.(RoleBindingAdapter).RoleBinding, metav1.UpdateOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn RoleBindingAdapter{RoleBinding: ret}, err\n\n}","line":{"from":106,"to":113}} {"id":100030695,"name":"Delete","signature":"func (c RoleBindingClientAdapter) Delete(namespace, name string, uid types.UID) error","file":"staging/src/k8s.io/component-helpers/auth/rbac/reconciliation/rolebinding_interfaces.go","code":"func (c RoleBindingClientAdapter) Delete(namespace, name string, uid types.UID) error {\n\treturn c.Client.RoleBindings(namespace).Delete(context.TODO(), name, metav1.DeleteOptions{Preconditions: \u0026metav1.Preconditions{UID: \u0026uid}})\n}","line":{"from":115,"to":117}} {"id":100030696,"name":"Covers","signature":"func Covers(ownerRules, servantRules []rbacv1.PolicyRule) (bool, []rbacv1.PolicyRule)","file":"staging/src/k8s.io/component-helpers/auth/rbac/validation/policy_comparator.go","code":"// Covers determines whether or not the ownerRules cover the servantRules in terms of allowed actions.\n// It returns whether or not the ownerRules cover and a list of the rules that the ownerRules do not cover.\nfunc Covers(ownerRules, servantRules []rbacv1.PolicyRule) (bool, []rbacv1.PolicyRule) {\n\t// 1. Break every servantRule into individual rule tuples: group, verb, resource, resourceName\n\t// 2. Compare the mini-rules against each owner rule. Because the breakdown is down to the most atomic level, we're guaranteed that each mini-servant rule will be either fully covered or not covered by a single owner rule\n\t// 3. Any left over mini-rules means that we are not covered and we have a nice list of them.\n\t// TODO: it might be nice to collapse the list down into something more human readable\n\n\tsubrules := []rbacv1.PolicyRule{}\n\tfor _, servantRule := range servantRules {\n\t\tsubrules = append(subrules, BreakdownRule(servantRule)...)\n\t}\n\n\tuncoveredRules := []rbacv1.PolicyRule{}\n\tfor _, subrule := range subrules {\n\t\tcovered := false\n\t\tfor _, ownerRule := range ownerRules {\n\t\t\tif ruleCovers(ownerRule, subrule) {\n\t\t\t\tcovered = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !covered {\n\t\t\tuncoveredRules = append(uncoveredRules, subrule)\n\t\t}\n\t}\n\n\treturn (len(uncoveredRules) == 0), uncoveredRules\n}","line":{"from":25,"to":54}} {"id":100030697,"name":"BreakdownRule","signature":"func BreakdownRule(rule rbacv1.PolicyRule) []rbacv1.PolicyRule","file":"staging/src/k8s.io/component-helpers/auth/rbac/validation/policy_comparator.go","code":"// BreadownRule takes a rule and builds an equivalent list of rules that each have at most one verb, one\n// resource, and one resource name\nfunc BreakdownRule(rule rbacv1.PolicyRule) []rbacv1.PolicyRule {\n\tsubrules := []rbacv1.PolicyRule{}\n\tfor _, group := range rule.APIGroups {\n\t\tfor _, resource := range rule.Resources {\n\t\t\tfor _, verb := range rule.Verbs {\n\t\t\t\tif len(rule.ResourceNames) \u003e 0 {\n\t\t\t\t\tfor _, resourceName := range rule.ResourceNames {\n\t\t\t\t\t\tsubrules = append(subrules, rbacv1.PolicyRule{APIGroups: []string{group}, Resources: []string{resource}, Verbs: []string{verb}, ResourceNames: []string{resourceName}})\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\tsubrules = append(subrules, rbacv1.PolicyRule{APIGroups: []string{group}, Resources: []string{resource}, Verbs: []string{verb}})\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\n\t// Non-resource URLs are unique because they only combine with verbs.\n\tfor _, nonResourceURL := range rule.NonResourceURLs {\n\t\tfor _, verb := range rule.Verbs {\n\t\t\tsubrules = append(subrules, rbacv1.PolicyRule{NonResourceURLs: []string{nonResourceURL}, Verbs: []string{verb}})\n\t\t}\n\t}\n\n\treturn subrules\n}","line":{"from":56,"to":84}} {"id":100030698,"name":"has","signature":"func has(set []string, ele string) bool","file":"staging/src/k8s.io/component-helpers/auth/rbac/validation/policy_comparator.go","code":"func has(set []string, ele string) bool {\n\tfor _, s := range set {\n\t\tif s == ele {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":86,"to":93}} {"id":100030699,"name":"hasAll","signature":"func hasAll(set, contains []string) bool","file":"staging/src/k8s.io/component-helpers/auth/rbac/validation/policy_comparator.go","code":"func hasAll(set, contains []string) bool {\n\towning := make(map[string]struct{}, len(set))\n\tfor _, ele := range set {\n\t\towning[ele] = struct{}{}\n\t}\n\tfor _, ele := range contains {\n\t\tif _, ok := owning[ele]; !ok {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":95,"to":106}} {"id":100030700,"name":"resourceCoversAll","signature":"func resourceCoversAll(setResources, coversResources []string) bool","file":"staging/src/k8s.io/component-helpers/auth/rbac/validation/policy_comparator.go","code":"func resourceCoversAll(setResources, coversResources []string) bool {\n\t// if we have a star or an exact match on all resources, then we match\n\tif has(setResources, rbacv1.ResourceAll) || hasAll(setResources, coversResources) {\n\t\treturn true\n\t}\n\n\tfor _, path := range coversResources {\n\t\t// if we have an exact match, then we match.\n\t\tif has(setResources, path) {\n\t\t\tcontinue\n\t\t}\n\t\t// if we're not a subresource, then we definitely don't match. fail.\n\t\tif !strings.Contains(path, \"/\") {\n\t\t\treturn false\n\t\t}\n\t\ttokens := strings.SplitN(path, \"/\", 2)\n\t\tresourceToCheck := \"*/\" + tokens[1]\n\t\tif !has(setResources, resourceToCheck) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}","line":{"from":108,"to":131}} {"id":100030701,"name":"nonResourceURLsCoversAll","signature":"func nonResourceURLsCoversAll(set, covers []string) bool","file":"staging/src/k8s.io/component-helpers/auth/rbac/validation/policy_comparator.go","code":"func nonResourceURLsCoversAll(set, covers []string) bool {\n\tfor _, path := range covers {\n\t\tcovered := false\n\t\tfor _, owner := range set {\n\t\t\tif nonResourceURLCovers(owner, path) {\n\t\t\t\tcovered = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !covered {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":133,"to":147}} {"id":100030702,"name":"nonResourceURLCovers","signature":"func nonResourceURLCovers(ownerPath, subPath string) bool","file":"staging/src/k8s.io/component-helpers/auth/rbac/validation/policy_comparator.go","code":"func nonResourceURLCovers(ownerPath, subPath string) bool {\n\tif ownerPath == subPath {\n\t\treturn true\n\t}\n\treturn strings.HasSuffix(ownerPath, \"*\") \u0026\u0026 strings.HasPrefix(subPath, strings.TrimRight(ownerPath, \"*\"))\n}","line":{"from":149,"to":154}} {"id":100030703,"name":"ruleCovers","signature":"func ruleCovers(ownerRule, subRule rbacv1.PolicyRule) bool","file":"staging/src/k8s.io/component-helpers/auth/rbac/validation/policy_comparator.go","code":"// ruleCovers determines whether the ownerRule (which may have multiple verbs, resources, and resourceNames) covers\n// the subrule (which may only contain at most one verb, resource, and resourceName)\nfunc ruleCovers(ownerRule, subRule rbacv1.PolicyRule) bool {\n\tverbMatches := has(ownerRule.Verbs, rbacv1.VerbAll) || hasAll(ownerRule.Verbs, subRule.Verbs)\n\tgroupMatches := has(ownerRule.APIGroups, rbacv1.APIGroupAll) || hasAll(ownerRule.APIGroups, subRule.APIGroups)\n\tresourceMatches := resourceCoversAll(ownerRule.Resources, subRule.Resources)\n\tnonResourceURLMatches := nonResourceURLsCoversAll(ownerRule.NonResourceURLs, subRule.NonResourceURLs)\n\n\tresourceNameMatches := false\n\n\tif len(subRule.ResourceNames) == 0 {\n\t\tresourceNameMatches = (len(ownerRule.ResourceNames) == 0)\n\t} else {\n\t\tresourceNameMatches = (len(ownerRule.ResourceNames) == 0) || hasAll(ownerRule.ResourceNames, subRule.ResourceNames)\n\t}\n\n\treturn verbMatches \u0026\u0026 groupMatches \u0026\u0026 resourceMatches \u0026\u0026 resourceNameMatches \u0026\u0026 nonResourceURLMatches\n}","line":{"from":156,"to":173}} {"id":100030704,"name":"GetZoneKey","signature":"func GetZoneKey(node *v1.Node) string","file":"staging/src/k8s.io/component-helpers/node/topology/helpers.go","code":"// GetZoneKey is a helper function that builds a string identifier that is unique per failure-zone;\n// it returns empty-string for no zone.\n// Since there are currently two separate zone keys:\n// - \"failure-domain.beta.kubernetes.io/zone\"\n// - \"topology.kubernetes.io/zone\"\n//\n// GetZoneKey will first check failure-domain.beta.kubernetes.io/zone and if not exists, will then check\n// topology.kubernetes.io/zone\nfunc GetZoneKey(node *v1.Node) string {\n\tlabels := node.Labels\n\tif labels == nil {\n\t\treturn \"\"\n\t}\n\n\t// TODO: \"failure-domain.beta...\" names are deprecated, but will\n\t// stick around a long time due to existing on old extant objects like PVs.\n\t// Maybe one day we can stop considering them (see #88493).\n\tzone, ok := labels[v1.LabelFailureDomainBetaZone]\n\tif !ok {\n\t\tzone, _ = labels[v1.LabelTopologyZone]\n\t}\n\n\tregion, ok := labels[v1.LabelFailureDomainBetaRegion]\n\tif !ok {\n\t\tregion, _ = labels[v1.LabelTopologyRegion]\n\t}\n\n\tif region == \"\" \u0026\u0026 zone == \"\" {\n\t\treturn \"\"\n\t}\n\n\t// We include the null character just in case region or failureDomain has a colon\n\t// (We do assume there's no null characters in a region or failureDomain)\n\t// As a nice side-benefit, the null character is not printed by fmt.Print or glog\n\treturn region + \":\\x00:\" + zone\n}","line":{"from":23,"to":58}} {"id":100030705,"name":"PatchNodeCIDRs","signature":"func PatchNodeCIDRs(c clientset.Interface, node types.NodeName, cidrs []string) error","file":"staging/src/k8s.io/component-helpers/node/util/cidr.go","code":"// PatchNodeCIDRs patches the specified node.CIDR=cidrs[0] and node.CIDRs to the given value.\nfunc PatchNodeCIDRs(c clientset.Interface, node types.NodeName, cidrs []string) error {\n\t// set the pod cidrs list and set the old pod cidr field\n\tpatch := nodeForCIDRMergePatch{\n\t\tSpec: nodeSpecForMergePatch{\n\t\t\tPodCIDR: cidrs[0],\n\t\t\tPodCIDRs: cidrs,\n\t\t},\n\t}\n\n\tpatchBytes, err := json.Marshal(\u0026patch)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to json.Marshal CIDR: %v\", err)\n\t}\n\tklog.V(4).Infof(\"cidrs patch bytes are:%s\", string(patchBytes))\n\tif _, err := c.CoreV1().Nodes().Patch(context.TODO(), string(node), types.StrategicMergePatchType, patchBytes, metav1.PatchOptions{}); err != nil {\n\t\treturn fmt.Errorf(\"failed to patch node CIDR: %v\", err)\n\t}\n\treturn nil\n}","line":{"from":39,"to":58}} {"id":100030706,"name":"GetNodeCondition","signature":"func GetNodeCondition(status *v1.NodeStatus, conditionType v1.NodeConditionType) (int, *v1.NodeCondition)","file":"staging/src/k8s.io/component-helpers/node/util/conditions.go","code":"// GetNodeCondition extracts the provided condition from the given status and returns that.\n// Returns nil and -1 if the condition is not present, and the index of the located condition.\nfunc GetNodeCondition(status *v1.NodeStatus, conditionType v1.NodeConditionType) (int, *v1.NodeCondition) {\n\tif status == nil {\n\t\treturn -1, nil\n\t}\n\tfor i := range status.Conditions {\n\t\tif status.Conditions[i].Type == conditionType {\n\t\t\treturn i, \u0026status.Conditions[i]\n\t\t}\n\t}\n\treturn -1, nil\n}","line":{"from":30,"to":42}} {"id":100030707,"name":"SetNodeCondition","signature":"func SetNodeCondition(c clientset.Interface, node types.NodeName, condition v1.NodeCondition) error","file":"staging/src/k8s.io/component-helpers/node/util/conditions.go","code":"// SetNodeCondition updates specific node condition with patch operation.\nfunc SetNodeCondition(c clientset.Interface, node types.NodeName, condition v1.NodeCondition) error {\n\tcondition.LastHeartbeatTime = metav1.NewTime(time.Now())\n\tpatch, err := json.Marshal(map[string]interface{}{\n\t\t\"status\": map[string]interface{}{\n\t\t\t\"conditions\": []v1.NodeCondition{condition},\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = c.CoreV1().Nodes().PatchStatus(context.TODO(), string(node), patch)\n\treturn err\n}","line":{"from":44,"to":57}} {"id":100030708,"name":"GetHostname","signature":"func GetHostname(hostnameOverride string) (string, error)","file":"staging/src/k8s.io/component-helpers/node/util/hostname.go","code":"// GetHostname returns OS's hostname if 'hostnameOverride' is empty; otherwise, it returns\n// 'hostnameOverride'. In either case, the value is canonicalized (trimmed and\n// lowercased).\nfunc GetHostname(hostnameOverride string) (string, error) {\n\thostName := hostnameOverride\n\tif len(hostName) == 0 {\n\t\tnodeName, err := os.Hostname()\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"couldn't determine hostname: %w\", err)\n\t\t}\n\t\thostName = nodeName\n\t}\n\n\t// Trim whitespaces first to avoid getting an empty hostname\n\t// For linux, the hostname is read from file /proc/sys/kernel/hostname directly\n\thostName = strings.TrimSpace(hostName)\n\tif len(hostName) == 0 {\n\t\treturn \"\", fmt.Errorf(\"empty hostname is invalid\")\n\t}\n\n\treturn strings.ToLower(hostName), nil\n}","line":{"from":25,"to":46}} {"id":100030709,"name":"parseNodeIP","signature":"func parseNodeIP(nodeIP string, allowDual, sloppy bool) ([]net.IP, error)","file":"staging/src/k8s.io/component-helpers/node/util/ips.go","code":"// parseNodeIP implements ParseNodeIPArgument and ParseNodeIPAnnotation\nfunc parseNodeIP(nodeIP string, allowDual, sloppy bool) ([]net.IP, error) {\n\tvar nodeIPs []net.IP\n\tif nodeIP != \"\" || !sloppy {\n\t\tfor _, ip := range strings.Split(nodeIP, \",\") {\n\t\t\tif sloppy {\n\t\t\t\tip = strings.TrimSpace(ip)\n\t\t\t}\n\t\t\tparsedNodeIP := netutils.ParseIPSloppy(ip)\n\t\t\tif parsedNodeIP == nil {\n\t\t\t\tif sloppy {\n\t\t\t\t\tklog.InfoS(\"Could not parse node IP. Ignoring\", \"IP\", ip)\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, fmt.Errorf(\"could not parse %q\", ip)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnodeIPs = append(nodeIPs, parsedNodeIP)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(nodeIPs) \u003e 2 || (len(nodeIPs) == 2 \u0026\u0026 netutils.IsIPv6(nodeIPs[0]) == netutils.IsIPv6(nodeIPs[1])) {\n\t\treturn nil, fmt.Errorf(\"must contain either a single IP or a dual-stack pair of IPs\")\n\t} else if len(nodeIPs) == 2 \u0026\u0026 !allowDual {\n\t\treturn nil, fmt.Errorf(\"dual-stack not supported in this configuration\")\n\t} else if len(nodeIPs) == 2 \u0026\u0026 (nodeIPs[0].IsUnspecified() || nodeIPs[1].IsUnspecified()) {\n\t\treturn nil, fmt.Errorf(\"dual-stack node IP cannot include '0.0.0.0' or '::'\")\n\t}\n\n\treturn nodeIPs, nil\n}","line":{"from":33,"to":63}} {"id":100030710,"name":"ParseNodeIPArgument","signature":"func ParseNodeIPArgument(nodeIP, cloudProvider string, allowCloudDualStack bool) ([]net.IP, error)","file":"staging/src/k8s.io/component-helpers/node/util/ips.go","code":"// ParseNodeIPArgument parses kubelet's --node-ip argument. If nodeIP contains invalid\n// values, they will be logged and ignored. Dual-stack node IPs are allowed if\n// cloudProvider is unset, or if it is `\"external\"` and allowCloudDualStack is true.\nfunc ParseNodeIPArgument(nodeIP, cloudProvider string, allowCloudDualStack bool) ([]net.IP, error) {\n\tvar allowDualStack bool\n\tif (cloudProvider == cloudProviderNone) || (cloudProvider == cloudProviderExternal \u0026\u0026 allowCloudDualStack) {\n\t\tallowDualStack = true\n\t}\n\treturn parseNodeIP(nodeIP, allowDualStack, true)\n}","line":{"from":65,"to":74}} {"id":100030711,"name":"ParseNodeIPAnnotation","signature":"func ParseNodeIPAnnotation(nodeIP string, allowDualStack bool) ([]net.IP, error)","file":"staging/src/k8s.io/component-helpers/node/util/ips.go","code":"// ParseNodeIPAnnotation parses the `alpha.kubernetes.io/provided-node-ip` annotation,\n// which can be either a single IP address or (if allowDualStack is true) a\n// comma-separated pair of IP addresses. Unlike with ParseNodeIPArgument, invalid values\n// are considered an error.\nfunc ParseNodeIPAnnotation(nodeIP string, allowDualStack bool) ([]net.IP, error) {\n\treturn parseNodeIP(nodeIP, allowDualStack, false)\n}","line":{"from":76,"to":82}} {"id":100030712,"name":"PatchNodeStatus","signature":"func PatchNodeStatus(c v1core.CoreV1Interface, nodeName types.NodeName, oldNode *v1.Node, newNode *v1.Node) (*v1.Node, []byte, error)","file":"staging/src/k8s.io/component-helpers/node/util/status.go","code":"// PatchNodeStatus patches node status.\nfunc PatchNodeStatus(c v1core.CoreV1Interface, nodeName types.NodeName, oldNode *v1.Node, newNode *v1.Node) (*v1.Node, []byte, error) {\n\tpatchBytes, err := preparePatchBytesforNodeStatus(nodeName, oldNode, newNode)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tupdatedNode, err := c.Nodes().Patch(context.TODO(), string(nodeName), types.StrategicMergePatchType, patchBytes, metav1.PatchOptions{}, \"status\")\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to patch status %q for node %q: %v\", patchBytes, nodeName, err)\n\t}\n\treturn updatedNode, patchBytes, nil\n}","line":{"from":32,"to":44}} {"id":100030713,"name":"preparePatchBytesforNodeStatus","signature":"func preparePatchBytesforNodeStatus(nodeName types.NodeName, oldNode *v1.Node, newNode *v1.Node) ([]byte, error)","file":"staging/src/k8s.io/component-helpers/node/util/status.go","code":"func preparePatchBytesforNodeStatus(nodeName types.NodeName, oldNode *v1.Node, newNode *v1.Node) ([]byte, error) {\n\toldData, err := json.Marshal(oldNode)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to Marshal oldData for node %q: %v\", nodeName, err)\n\t}\n\n\t// NodeStatus.Addresses is incorrectly annotated as patchStrategy=merge, which\n\t// will cause strategicpatch.CreateTwoWayMergePatch to create an incorrect patch\n\t// if it changed.\n\tmanuallyPatchAddresses := (len(oldNode.Status.Addresses) \u003e 0) \u0026\u0026 !equality.Semantic.DeepEqual(oldNode.Status.Addresses, newNode.Status.Addresses)\n\n\t// Reset spec to make sure only patch for Status or ObjectMeta is generated.\n\t// Note that we don't reset ObjectMeta here, because:\n\t// 1. This aligns with Nodes().UpdateStatus().\n\t// 2. Some component does use this to update node annotations.\n\tdiffNode := newNode.DeepCopy()\n\tdiffNode.Spec = oldNode.Spec\n\tif manuallyPatchAddresses {\n\t\tdiffNode.Status.Addresses = oldNode.Status.Addresses\n\t}\n\tnewData, err := json.Marshal(diffNode)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to Marshal newData for node %q: %v\", nodeName, err)\n\t}\n\n\tpatchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, v1.Node{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to CreateTwoWayMergePatch for node %q: %v\", nodeName, err)\n\t}\n\tif manuallyPatchAddresses {\n\t\tpatchBytes, err = fixupPatchForNodeStatusAddresses(patchBytes, newNode.Status.Addresses)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to fix up NodeAddresses in patch for node %q: %v\", nodeName, err)\n\t\t}\n\t}\n\n\treturn patchBytes, nil\n}","line":{"from":46,"to":83}} {"id":100030714,"name":"fixupPatchForNodeStatusAddresses","signature":"func fixupPatchForNodeStatusAddresses(patchBytes []byte, addresses []v1.NodeAddress) ([]byte, error)","file":"staging/src/k8s.io/component-helpers/node/util/status.go","code":"// fixupPatchForNodeStatusAddresses adds a replace-strategy patch for Status.Addresses to\n// the existing patch\nfunc fixupPatchForNodeStatusAddresses(patchBytes []byte, addresses []v1.NodeAddress) ([]byte, error) {\n\t// Given patchBytes='{\"status\": {\"conditions\": [ ... ], \"phase\": ...}}' and\n\t// addresses=[{\"type\": \"InternalIP\", \"address\": \"10.0.0.1\"}], we need to generate:\n\t//\n\t// {\n\t// \"status\": {\n\t// \"conditions\": [ ... ],\n\t// \"phase\": ...,\n\t// \"addresses\": [\n\t// {\n\t// \"type\": \"InternalIP\",\n\t// \"address\": \"10.0.0.1\"\n\t// },\n\t// {\n\t// \"$patch\": \"replace\"\n\t// }\n\t// ]\n\t// }\n\t// }\n\n\tvar patchMap map[string]interface{}\n\tif err := json.Unmarshal(patchBytes, \u0026patchMap); err != nil {\n\t\treturn nil, err\n\t}\n\n\taddrBytes, err := json.Marshal(addresses)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar addrArray []interface{}\n\tif err := json.Unmarshal(addrBytes, \u0026addrArray); err != nil {\n\t\treturn nil, err\n\t}\n\taddrArray = append(addrArray, map[string]interface{}{\"$patch\": \"replace\"})\n\n\tstatus := patchMap[\"status\"]\n\tif status == nil {\n\t\tstatus = map[string]interface{}{}\n\t\tpatchMap[\"status\"] = status\n\t}\n\tstatusMap, ok := status.(map[string]interface{})\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unexpected data in patch\")\n\t}\n\tstatusMap[\"addresses\"] = addrArray\n\n\treturn json.Marshal(patchMap)\n}","line":{"from":85,"to":134}} {"id":100030715,"name":"New","signature":"func New() Interface","file":"staging/src/k8s.io/component-helpers/node/util/sysctl/sysctl.go","code":"// New returns a new Interface for accessing sysctl\nfunc New() Interface {\n\treturn \u0026procSysctl{}\n}","line":{"from":75,"to":78}} {"id":100030716,"name":"GetSysctl","signature":"func (*procSysctl) GetSysctl(sysctl string) (int, error)","file":"staging/src/k8s.io/component-helpers/node/util/sysctl/sysctl.go","code":"// GetSysctl returns the value for the specified sysctl setting\nfunc (*procSysctl) GetSysctl(sysctl string) (int, error) {\n\tdata, err := os.ReadFile(path.Join(sysctlBase, sysctl))\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\tval, err := strconv.Atoi(strings.Trim(string(data), \" \\n\"))\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\treturn val, nil\n}","line":{"from":84,"to":95}} {"id":100030717,"name":"SetSysctl","signature":"func (*procSysctl) SetSysctl(sysctl string, newVal int) error","file":"staging/src/k8s.io/component-helpers/node/util/sysctl/sysctl.go","code":"// SetSysctl modifies the specified sysctl flag to the new value\nfunc (*procSysctl) SetSysctl(sysctl string, newVal int) error {\n\treturn os.WriteFile(path.Join(sysctlBase, sysctl), []byte(strconv.Itoa(newVal)), 0640)\n}","line":{"from":97,"to":100}} {"id":100030718,"name":"PodPriority","signature":"func PodPriority(pod *v1.Pod) int32","file":"staging/src/k8s.io/component-helpers/scheduling/corev1/helpers.go","code":"// PodPriority returns priority of the given pod.\nfunc PodPriority(pod *v1.Pod) int32 {\n\tif pod.Spec.Priority != nil {\n\t\treturn *pod.Spec.Priority\n\t}\n\t// When priority of a running pod is nil, it means it was created at a time\n\t// that there was no global default priority class and the priority class\n\t// name of the pod was empty. So, we resolve to the static default priority.\n\treturn 0\n}","line":{"from":26,"to":35}} {"id":100030719,"name":"MatchNodeSelectorTerms","signature":"func MatchNodeSelectorTerms(","file":"staging/src/k8s.io/component-helpers/scheduling/corev1/helpers.go","code":"// MatchNodeSelectorTerms checks whether the node labels and fields match node selector terms in ORed;\n// nil or empty term matches no objects.\nfunc MatchNodeSelectorTerms(\n\tnode *v1.Node,\n\tnodeSelector *v1.NodeSelector,\n) (bool, error) {\n\tif node == nil {\n\t\treturn false, nil\n\t}\n\treturn nodeaffinity.NewLazyErrorNodeSelector(nodeSelector).Match(node)\n}","line":{"from":37,"to":47}} {"id":100030720,"name":"GetAvoidPodsFromNodeAnnotations","signature":"func GetAvoidPodsFromNodeAnnotations(annotations map[string]string) (v1.AvoidPods, error)","file":"staging/src/k8s.io/component-helpers/scheduling/corev1/helpers.go","code":"// GetAvoidPodsFromNodeAnnotations scans the list of annotations and\n// returns the pods that needs to be avoided for this node from scheduling\nfunc GetAvoidPodsFromNodeAnnotations(annotations map[string]string) (v1.AvoidPods, error) {\n\tvar avoidPods v1.AvoidPods\n\tif len(annotations) \u003e 0 \u0026\u0026 annotations[v1.PreferAvoidPodsAnnotationKey] != \"\" {\n\t\terr := json.Unmarshal([]byte(annotations[v1.PreferAvoidPodsAnnotationKey]), \u0026avoidPods)\n\t\tif err != nil {\n\t\t\treturn avoidPods, err\n\t\t}\n\t}\n\treturn avoidPods, nil\n}","line":{"from":49,"to":60}} {"id":100030721,"name":"TolerationsTolerateTaint","signature":"func TolerationsTolerateTaint(tolerations []v1.Toleration, taint *v1.Taint) bool","file":"staging/src/k8s.io/component-helpers/scheduling/corev1/helpers.go","code":"// TolerationsTolerateTaint checks if taint is tolerated by any of the tolerations.\nfunc TolerationsTolerateTaint(tolerations []v1.Toleration, taint *v1.Taint) bool {\n\tfor i := range tolerations {\n\t\tif tolerations[i].ToleratesTaint(taint) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":62,"to":70}} {"id":100030722,"name":"FindMatchingUntoleratedTaint","signature":"func FindMatchingUntoleratedTaint(taints []v1.Taint, tolerations []v1.Toleration, inclusionFilter taintsFilterFunc) (v1.Taint, bool)","file":"staging/src/k8s.io/component-helpers/scheduling/corev1/helpers.go","code":"// FindMatchingUntoleratedTaint checks if the given tolerations tolerates\n// all the filtered taints, and returns the first taint without a toleration\n// Returns true if there is an untolerated taint\n// Returns false if all taints are tolerated\nfunc FindMatchingUntoleratedTaint(taints []v1.Taint, tolerations []v1.Toleration, inclusionFilter taintsFilterFunc) (v1.Taint, bool) {\n\tfilteredTaints := getFilteredTaints(taints, inclusionFilter)\n\tfor _, taint := range filteredTaints {\n\t\tif !TolerationsTolerateTaint(tolerations, \u0026taint) {\n\t\t\treturn taint, true\n\t\t}\n\t}\n\treturn v1.Taint{}, false\n}","line":{"from":74,"to":86}} {"id":100030723,"name":"getFilteredTaints","signature":"func getFilteredTaints(taints []v1.Taint, inclusionFilter taintsFilterFunc) []v1.Taint","file":"staging/src/k8s.io/component-helpers/scheduling/corev1/helpers.go","code":"// getFilteredTaints returns a list of taints satisfying the filter predicate\nfunc getFilteredTaints(taints []v1.Taint, inclusionFilter taintsFilterFunc) []v1.Taint {\n\tif inclusionFilter == nil {\n\t\treturn taints\n\t}\n\tfilteredTaints := []v1.Taint{}\n\tfor _, taint := range taints {\n\t\tif !inclusionFilter(\u0026taint) {\n\t\t\tcontinue\n\t\t}\n\t\tfilteredTaints = append(filteredTaints, taint)\n\t}\n\treturn filteredTaints\n}","line":{"from":88,"to":101}} {"id":100030724,"name":"NewNodeSelector","signature":"func NewNodeSelector(ns *v1.NodeSelector, opts ...field.PathOption) (*NodeSelector, error)","file":"staging/src/k8s.io/component-helpers/scheduling/corev1/nodeaffinity/nodeaffinity.go","code":"// NewNodeSelector returns a NodeSelector or aggregate parsing errors found.\nfunc NewNodeSelector(ns *v1.NodeSelector, opts ...field.PathOption) (*NodeSelector, error) {\n\tlazy := NewLazyErrorNodeSelector(ns, opts...)\n\tvar errs []error\n\tfor _, term := range lazy.terms {\n\t\tif len(term.parseErrs) \u003e 0 {\n\t\t\terrs = append(errs, term.parseErrs...)\n\t\t}\n\t}\n\tif len(errs) != 0 {\n\t\treturn nil, errors.Flatten(errors.NewAggregate(errs))\n\t}\n\treturn \u0026NodeSelector{lazy: *lazy}, nil\n}","line":{"from":39,"to":52}} {"id":100030725,"name":"NewLazyErrorNodeSelector","signature":"func NewLazyErrorNodeSelector(ns *v1.NodeSelector, opts ...field.PathOption) *LazyErrorNodeSelector","file":"staging/src/k8s.io/component-helpers/scheduling/corev1/nodeaffinity/nodeaffinity.go","code":"// NewLazyErrorNodeSelector creates a NodeSelector that only reports parse\n// errors when no terms match.\nfunc NewLazyErrorNodeSelector(ns *v1.NodeSelector, opts ...field.PathOption) *LazyErrorNodeSelector {\n\tp := field.ToPath(opts...)\n\tparsedTerms := make([]nodeSelectorTerm, 0, len(ns.NodeSelectorTerms))\n\tpath := p.Child(\"nodeSelectorTerms\")\n\tfor i, term := range ns.NodeSelectorTerms {\n\t\t// nil or empty term selects no objects\n\t\tif isEmptyNodeSelectorTerm(\u0026term) {\n\t\t\tcontinue\n\t\t}\n\t\tp := path.Index(i)\n\t\tparsedTerms = append(parsedTerms, newNodeSelectorTerm(\u0026term, p))\n\t}\n\treturn \u0026LazyErrorNodeSelector{\n\t\tterms: parsedTerms,\n\t}\n}","line":{"from":54,"to":71}} {"id":100030726,"name":"Match","signature":"func (ns *NodeSelector) Match(node *v1.Node) bool","file":"staging/src/k8s.io/component-helpers/scheduling/corev1/nodeaffinity/nodeaffinity.go","code":"// Match checks whether the node labels and fields match the selector terms, ORed;\n// nil or empty term matches no objects.\nfunc (ns *NodeSelector) Match(node *v1.Node) bool {\n\t// parse errors are reported in NewNodeSelector.\n\tmatch, _ := ns.lazy.Match(node)\n\treturn match\n}","line":{"from":73,"to":79}} {"id":100030727,"name":"Match","signature":"func (ns *LazyErrorNodeSelector) Match(node *v1.Node) (bool, error)","file":"staging/src/k8s.io/component-helpers/scheduling/corev1/nodeaffinity/nodeaffinity.go","code":"// Match checks whether the node labels and fields match the selector terms, ORed;\n// nil or empty term matches no objects.\n// Parse errors are only returned if no terms matched.\nfunc (ns *LazyErrorNodeSelector) Match(node *v1.Node) (bool, error) {\n\tif node == nil {\n\t\treturn false, nil\n\t}\n\tnodeLabels := labels.Set(node.Labels)\n\tnodeFields := extractNodeFields(node)\n\n\tvar errs []error\n\tfor _, term := range ns.terms {\n\t\tmatch, tErrs := term.match(nodeLabels, nodeFields)\n\t\tif len(tErrs) \u003e 0 {\n\t\t\terrs = append(errs, tErrs...)\n\t\t\tcontinue\n\t\t}\n\t\tif match {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, errors.Flatten(errors.NewAggregate(errs))\n}","line":{"from":81,"to":103}} {"id":100030728,"name":"NewPreferredSchedulingTerms","signature":"func NewPreferredSchedulingTerms(terms []v1.PreferredSchedulingTerm, opts ...field.PathOption) (*PreferredSchedulingTerms, error)","file":"staging/src/k8s.io/component-helpers/scheduling/corev1/nodeaffinity/nodeaffinity.go","code":"// NewPreferredSchedulingTerms returns a PreferredSchedulingTerms or all the parsing errors found.\n// If a v1.PreferredSchedulingTerm has a 0 weight, its parsing is skipped.\nfunc NewPreferredSchedulingTerms(terms []v1.PreferredSchedulingTerm, opts ...field.PathOption) (*PreferredSchedulingTerms, error) {\n\tp := field.ToPath(opts...)\n\tvar errs []error\n\tparsedTerms := make([]preferredSchedulingTerm, 0, len(terms))\n\tfor i, term := range terms {\n\t\tpath := p.Index(i)\n\t\tif term.Weight == 0 || isEmptyNodeSelectorTerm(\u0026term.Preference) {\n\t\t\tcontinue\n\t\t}\n\t\tparsedTerm := preferredSchedulingTerm{\n\t\t\tnodeSelectorTerm: newNodeSelectorTerm(\u0026term.Preference, path),\n\t\t\tweight: int(term.Weight),\n\t\t}\n\t\tif len(parsedTerm.parseErrs) \u003e 0 {\n\t\t\terrs = append(errs, parsedTerm.parseErrs...)\n\t\t} else {\n\t\t\tparsedTerms = append(parsedTerms, parsedTerm)\n\t\t}\n\t}\n\tif len(errs) != 0 {\n\t\treturn nil, errors.Flatten(errors.NewAggregate(errs))\n\t}\n\treturn \u0026PreferredSchedulingTerms{terms: parsedTerms}, nil\n}","line":{"from":110,"to":135}} {"id":100030729,"name":"Score","signature":"func (t *PreferredSchedulingTerms) Score(node *v1.Node) int64","file":"staging/src/k8s.io/component-helpers/scheduling/corev1/nodeaffinity/nodeaffinity.go","code":"// Score returns a score for a Node: the sum of the weights of the terms that\n// match the Node.\nfunc (t *PreferredSchedulingTerms) Score(node *v1.Node) int64 {\n\tvar score int64\n\tnodeLabels := labels.Set(node.Labels)\n\tnodeFields := extractNodeFields(node)\n\tfor _, term := range t.terms {\n\t\t// parse errors are reported in NewPreferredSchedulingTerms.\n\t\tif ok, _ := term.match(nodeLabels, nodeFields); ok {\n\t\t\tscore += int64(term.weight)\n\t\t}\n\t}\n\treturn score\n}","line":{"from":137,"to":150}} {"id":100030730,"name":"isEmptyNodeSelectorTerm","signature":"func isEmptyNodeSelectorTerm(term *v1.NodeSelectorTerm) bool","file":"staging/src/k8s.io/component-helpers/scheduling/corev1/nodeaffinity/nodeaffinity.go","code":"func isEmptyNodeSelectorTerm(term *v1.NodeSelectorTerm) bool {\n\treturn len(term.MatchExpressions) == 0 \u0026\u0026 len(term.MatchFields) == 0\n}","line":{"from":152,"to":154}} {"id":100030731,"name":"extractNodeFields","signature":"func extractNodeFields(n *v1.Node) fields.Set","file":"staging/src/k8s.io/component-helpers/scheduling/corev1/nodeaffinity/nodeaffinity.go","code":"func extractNodeFields(n *v1.Node) fields.Set {\n\tf := make(fields.Set)\n\tif len(n.Name) \u003e 0 {\n\t\tf[\"metadata.name\"] = n.Name\n\t}\n\treturn f\n}","line":{"from":156,"to":162}} {"id":100030732,"name":"newNodeSelectorTerm","signature":"func newNodeSelectorTerm(term *v1.NodeSelectorTerm, path *field.Path) nodeSelectorTerm","file":"staging/src/k8s.io/component-helpers/scheduling/corev1/nodeaffinity/nodeaffinity.go","code":"func newNodeSelectorTerm(term *v1.NodeSelectorTerm, path *field.Path) nodeSelectorTerm {\n\tvar parsedTerm nodeSelectorTerm\n\tvar errs []error\n\tif len(term.MatchExpressions) != 0 {\n\t\tp := path.Child(\"matchExpressions\")\n\t\tparsedTerm.matchLabels, errs = nodeSelectorRequirementsAsSelector(term.MatchExpressions, p)\n\t\tif errs != nil {\n\t\t\tparsedTerm.parseErrs = append(parsedTerm.parseErrs, errs...)\n\t\t}\n\t}\n\tif len(term.MatchFields) != 0 {\n\t\tp := path.Child(\"matchFields\")\n\t\tparsedTerm.matchFields, errs = nodeSelectorRequirementsAsFieldSelector(term.MatchFields, p)\n\t\tif errs != nil {\n\t\t\tparsedTerm.parseErrs = append(parsedTerm.parseErrs, errs...)\n\t\t}\n\t}\n\treturn parsedTerm\n}","line":{"from":170,"to":188}} {"id":100030733,"name":"match","signature":"func (t *nodeSelectorTerm) match(nodeLabels labels.Set, nodeFields fields.Set) (bool, []error)","file":"staging/src/k8s.io/component-helpers/scheduling/corev1/nodeaffinity/nodeaffinity.go","code":"func (t *nodeSelectorTerm) match(nodeLabels labels.Set, nodeFields fields.Set) (bool, []error) {\n\tif t.parseErrs != nil {\n\t\treturn false, t.parseErrs\n\t}\n\tif t.matchLabels != nil \u0026\u0026 !t.matchLabels.Matches(nodeLabels) {\n\t\treturn false, nil\n\t}\n\tif t.matchFields != nil \u0026\u0026 len(nodeFields) \u003e 0 \u0026\u0026 !t.matchFields.Matches(nodeFields) {\n\t\treturn false, nil\n\t}\n\treturn true, nil\n}","line":{"from":190,"to":201}} {"id":100030734,"name":"nodeSelectorRequirementsAsSelector","signature":"func nodeSelectorRequirementsAsSelector(nsm []v1.NodeSelectorRequirement, path *field.Path) (labels.Selector, []error)","file":"staging/src/k8s.io/component-helpers/scheduling/corev1/nodeaffinity/nodeaffinity.go","code":"// nodeSelectorRequirementsAsSelector converts the []NodeSelectorRequirement api type into a struct that implements\n// labels.Selector.\nfunc nodeSelectorRequirementsAsSelector(nsm []v1.NodeSelectorRequirement, path *field.Path) (labels.Selector, []error) {\n\tif len(nsm) == 0 {\n\t\treturn labels.Nothing(), nil\n\t}\n\tvar errs []error\n\tselector := labels.NewSelector()\n\tfor i, expr := range nsm {\n\t\tp := path.Index(i)\n\t\tvar op selection.Operator\n\t\tswitch expr.Operator {\n\t\tcase v1.NodeSelectorOpIn:\n\t\t\top = selection.In\n\t\tcase v1.NodeSelectorOpNotIn:\n\t\t\top = selection.NotIn\n\t\tcase v1.NodeSelectorOpExists:\n\t\t\top = selection.Exists\n\t\tcase v1.NodeSelectorOpDoesNotExist:\n\t\t\top = selection.DoesNotExist\n\t\tcase v1.NodeSelectorOpGt:\n\t\t\top = selection.GreaterThan\n\t\tcase v1.NodeSelectorOpLt:\n\t\t\top = selection.LessThan\n\t\tdefault:\n\t\t\terrs = append(errs, field.NotSupported(p.Child(\"operator\"), expr.Operator, nil))\n\t\t\tcontinue\n\t\t}\n\t\tr, err := labels.NewRequirement(expr.Key, op, expr.Values, field.WithPath(p))\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t} else {\n\t\t\tselector = selector.Add(*r)\n\t\t}\n\t}\n\tif len(errs) != 0 {\n\t\treturn nil, errs\n\t}\n\treturn selector, nil\n}","line":{"from":203,"to":242}} {"id":100030735,"name":"nodeSelectorRequirementsAsFieldSelector","signature":"func nodeSelectorRequirementsAsFieldSelector(nsr []v1.NodeSelectorRequirement, path *field.Path) (fields.Selector, []error)","file":"staging/src/k8s.io/component-helpers/scheduling/corev1/nodeaffinity/nodeaffinity.go","code":"// nodeSelectorRequirementsAsFieldSelector converts the []NodeSelectorRequirement core type into a struct that implements\n// fields.Selector.\nfunc nodeSelectorRequirementsAsFieldSelector(nsr []v1.NodeSelectorRequirement, path *field.Path) (fields.Selector, []error) {\n\tif len(nsr) == 0 {\n\t\treturn fields.Nothing(), nil\n\t}\n\tvar errs []error\n\n\tvar selectors []fields.Selector\n\tfor i, expr := range nsr {\n\t\tp := path.Index(i)\n\t\tswitch expr.Operator {\n\t\tcase v1.NodeSelectorOpIn:\n\t\t\tif len(expr.Values) != 1 {\n\t\t\t\terrs = append(errs, field.Invalid(p.Child(\"values\"), expr.Values, \"must have one element\"))\n\t\t\t} else {\n\t\t\t\tselectors = append(selectors, fields.OneTermEqualSelector(expr.Key, expr.Values[0]))\n\t\t\t}\n\n\t\tcase v1.NodeSelectorOpNotIn:\n\t\t\tif len(expr.Values) != 1 {\n\t\t\t\terrs = append(errs, field.Invalid(p.Child(\"values\"), expr.Values, \"must have one element\"))\n\t\t\t} else {\n\t\t\t\tselectors = append(selectors, fields.OneTermNotEqualSelector(expr.Key, expr.Values[0]))\n\t\t\t}\n\n\t\tdefault:\n\t\t\terrs = append(errs, field.NotSupported(p.Child(\"operator\"), expr.Operator, validFieldSelectorOperators))\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn nil, errs\n\t}\n\treturn fields.AndSelectors(selectors...), nil\n}","line":{"from":249,"to":284}} {"id":100030736,"name":"GetRequiredNodeAffinity","signature":"func GetRequiredNodeAffinity(pod *v1.Pod) RequiredNodeAffinity","file":"staging/src/k8s.io/component-helpers/scheduling/corev1/nodeaffinity/nodeaffinity.go","code":"// GetRequiredNodeAffinity returns the parsing result of pod's nodeSelector and nodeAffinity.\nfunc GetRequiredNodeAffinity(pod *v1.Pod) RequiredNodeAffinity {\n\tvar selector labels.Selector\n\tif len(pod.Spec.NodeSelector) \u003e 0 {\n\t\tselector = labels.SelectorFromSet(pod.Spec.NodeSelector)\n\t}\n\t// Use LazyErrorNodeSelector for backwards compatibility of parsing errors.\n\tvar affinity *LazyErrorNodeSelector\n\tif pod.Spec.Affinity != nil \u0026\u0026\n\t\tpod.Spec.Affinity.NodeAffinity != nil \u0026\u0026\n\t\tpod.Spec.Affinity.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution != nil {\n\t\taffinity = NewLazyErrorNodeSelector(pod.Spec.Affinity.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution)\n\t}\n\treturn RequiredNodeAffinity{labelSelector: selector, nodeSelector: affinity}\n}","line":{"from":296,"to":310}} {"id":100030737,"name":"Match","signature":"func (s RequiredNodeAffinity) Match(node *v1.Node) (bool, error)","file":"staging/src/k8s.io/component-helpers/scheduling/corev1/nodeaffinity/nodeaffinity.go","code":"// Match checks whether the pod is schedulable onto nodes according to\n// the requirements in both nodeSelector and nodeAffinity.\nfunc (s RequiredNodeAffinity) Match(node *v1.Node) (bool, error) {\n\tif s.labelSelector != nil {\n\t\tif !s.labelSelector.Matches(labels.Set(node.Labels)) {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\tif s.nodeSelector != nil {\n\t\treturn s.nodeSelector.Match(node)\n\t}\n\treturn true, nil\n}","line":{"from":312,"to":324}} {"id":100030738,"name":"VolumeClaimName","signature":"func VolumeClaimName(pod *v1.Pod, volume *v1.Volume) string","file":"staging/src/k8s.io/component-helpers/storage/ephemeral/ephemeral.go","code":"// VolumeClaimName returns the name of the PersistentVolumeClaim\n// object that gets created for the generic ephemeral inline volume. The\n// name is deterministic and therefore this function does not need any\n// additional information besides the Pod name and volume name and it\n// will never fail.\n//\n// Before using the PVC for the Pod, the caller must check that it is\n// indeed the PVC that was created for the Pod by calling IsUsable.\nfunc VolumeClaimName(pod *v1.Pod, volume *v1.Volume) string {\n\treturn pod.Name + \"-\" + volume.Name\n}","line":{"from":33,"to":43}} {"id":100030739,"name":"VolumeIsForPod","signature":"func VolumeIsForPod(pod *v1.Pod, pvc *v1.PersistentVolumeClaim) error","file":"staging/src/k8s.io/component-helpers/storage/ephemeral/ephemeral.go","code":"// VolumeIsForPod checks that the PVC is the ephemeral volume that\n// was created for the Pod. It returns an error that is informative\n// enough to be returned by the caller without adding further details\n// about the Pod or PVC.\nfunc VolumeIsForPod(pod *v1.Pod, pvc *v1.PersistentVolumeClaim) error {\n\t// Checking the namespaces is just a precaution. The caller should\n\t// never pass in a PVC that isn't from the same namespace as the\n\t// Pod.\n\tif pvc.Namespace != pod.Namespace || !metav1.IsControlledBy(pvc, pod) {\n\t\treturn fmt.Errorf(\"PVC %s/%s was not created for pod %s/%s (pod is not owner)\", pvc.Namespace, pvc.Name, pod.Namespace, pod.Name)\n\t}\n\treturn nil\n}","line":{"from":45,"to":57}} {"id":100030740,"name":"GetPersistentVolumeClaimClass","signature":"func GetPersistentVolumeClaimClass(claim *v1.PersistentVolumeClaim) string","file":"staging/src/k8s.io/component-helpers/storage/volume/helpers.go","code":"// GetPersistentVolumeClaimClass returns StorageClassName. If no storage class was\n// requested, it returns \"\".\nfunc GetPersistentVolumeClaimClass(claim *v1.PersistentVolumeClaim) string {\n\t// Use beta annotation first\n\tif class, found := claim.Annotations[v1.BetaStorageClassAnnotation]; found {\n\t\treturn class\n\t}\n\n\tif claim.Spec.StorageClassName != nil {\n\t\treturn *claim.Spec.StorageClassName\n\t}\n\n\treturn \"\"\n}","line":{"from":27,"to":40}} {"id":100030741,"name":"GetPersistentVolumeClass","signature":"func GetPersistentVolumeClass(volume *v1.PersistentVolume) string","file":"staging/src/k8s.io/component-helpers/storage/volume/helpers.go","code":"// GetPersistentVolumeClass returns StorageClassName.\nfunc GetPersistentVolumeClass(volume *v1.PersistentVolume) string {\n\t// Use beta annotation first\n\tif class, found := volume.Annotations[v1.BetaStorageClassAnnotation]; found {\n\t\treturn class\n\t}\n\n\treturn volume.Spec.StorageClassName\n}","line":{"from":42,"to":50}} {"id":100030742,"name":"CheckNodeAffinity","signature":"func CheckNodeAffinity(pv *v1.PersistentVolume, nodeLabels map[string]string) error","file":"staging/src/k8s.io/component-helpers/storage/volume/helpers.go","code":"// CheckNodeAffinity looks at the PV node affinity, and checks if the node has the same corresponding labels\n// This ensures that we don't mount a volume that doesn't belong to this node\nfunc CheckNodeAffinity(pv *v1.PersistentVolume, nodeLabels map[string]string) error {\n\tif pv.Spec.NodeAffinity == nil {\n\t\treturn nil\n\t}\n\n\tif pv.Spec.NodeAffinity.Required != nil {\n\t\tnode := \u0026v1.Node{ObjectMeta: metav1.ObjectMeta{Labels: nodeLabels}}\n\t\tterms := pv.Spec.NodeAffinity.Required\n\t\tif matches, err := corev1.MatchNodeSelectorTerms(node, terms); err != nil {\n\t\t\treturn err\n\t\t} else if !matches {\n\t\t\treturn fmt.Errorf(\"no matching NodeSelectorTerms\")\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":52,"to":70}} {"id":100030743,"name":"IsDelayBindingProvisioning","signature":"func IsDelayBindingProvisioning(claim *v1.PersistentVolumeClaim) bool","file":"staging/src/k8s.io/component-helpers/storage/volume/pv_helpers.go","code":"// IsDelayBindingProvisioning checks if claim provisioning with selected-node annotation\nfunc IsDelayBindingProvisioning(claim *v1.PersistentVolumeClaim) bool {\n\t// When feature VolumeScheduling enabled,\n\t// Scheduler signal to the PV controller to start dynamic\n\t// provisioning by setting the \"AnnSelectedNode\" annotation\n\t// in the PVC\n\t_, ok := claim.Annotations[AnnSelectedNode]\n\treturn ok\n}","line":{"from":84,"to":92}} {"id":100030744,"name":"IsDelayBindingMode","signature":"func IsDelayBindingMode(claim *v1.PersistentVolumeClaim, classLister storagelisters.StorageClassLister) (bool, error)","file":"staging/src/k8s.io/component-helpers/storage/volume/pv_helpers.go","code":"// IsDelayBindingMode checks if claim is in delay binding mode.\nfunc IsDelayBindingMode(claim *v1.PersistentVolumeClaim, classLister storagelisters.StorageClassLister) (bool, error) {\n\tclassName := GetPersistentVolumeClaimClass(claim)\n\tif className == \"\" {\n\t\treturn false, nil\n\t}\n\n\tclass, err := classLister.Get(className)\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn false, err\n\t}\n\n\tif class.VolumeBindingMode == nil {\n\t\treturn false, fmt.Errorf(\"VolumeBindingMode not set for StorageClass %q\", className)\n\t}\n\n\treturn *class.VolumeBindingMode == storage.VolumeBindingWaitForFirstConsumer, nil\n}","line":{"from":94,"to":114}} {"id":100030745,"name":"GetBindVolumeToClaim","signature":"func GetBindVolumeToClaim(volume *v1.PersistentVolume, claim *v1.PersistentVolumeClaim) (*v1.PersistentVolume, bool, error)","file":"staging/src/k8s.io/component-helpers/storage/volume/pv_helpers.go","code":"// GetBindVolumeToClaim returns a new volume which is bound to given claim. In\n// addition, it returns a bool which indicates whether we made modification on\n// original volume.\nfunc GetBindVolumeToClaim(volume *v1.PersistentVolume, claim *v1.PersistentVolumeClaim) (*v1.PersistentVolume, bool, error) {\n\tdirty := false\n\n\t// Check if the volume was already bound (either by user or by controller)\n\tshouldSetBoundByController := false\n\tif !IsVolumeBoundToClaim(volume, claim) {\n\t\tshouldSetBoundByController = true\n\t}\n\n\t// The volume from method args can be pointing to watcher cache. We must not\n\t// modify these, therefore create a copy.\n\tvolumeClone := volume.DeepCopy()\n\n\t// Bind the volume to the claim if it is not bound yet\n\tif volume.Spec.ClaimRef == nil ||\n\t\tvolume.Spec.ClaimRef.Name != claim.Name ||\n\t\tvolume.Spec.ClaimRef.Namespace != claim.Namespace ||\n\t\tvolume.Spec.ClaimRef.UID != claim.UID {\n\n\t\tclaimRef, err := reference.GetReference(scheme.Scheme, claim)\n\t\tif err != nil {\n\t\t\treturn nil, false, fmt.Errorf(\"unexpected error getting claim reference: %w\", err)\n\t\t}\n\t\tvolumeClone.Spec.ClaimRef = claimRef\n\t\tdirty = true\n\t}\n\n\t// Set AnnBoundByController if it is not set yet\n\tif shouldSetBoundByController \u0026\u0026 !metav1.HasAnnotation(volumeClone.ObjectMeta, AnnBoundByController) {\n\t\tmetav1.SetMetaDataAnnotation(\u0026volumeClone.ObjectMeta, AnnBoundByController, \"yes\")\n\t\tdirty = true\n\t}\n\n\treturn volumeClone, dirty, nil\n}","line":{"from":116,"to":153}} {"id":100030746,"name":"IsVolumeBoundToClaim","signature":"func IsVolumeBoundToClaim(volume *v1.PersistentVolume, claim *v1.PersistentVolumeClaim) bool","file":"staging/src/k8s.io/component-helpers/storage/volume/pv_helpers.go","code":"// IsVolumeBoundToClaim returns true, if given volume is pre-bound or bound\n// to specific claim. Both claim.Name and claim.Namespace must be equal.\n// If claim.UID is present in volume.Spec.ClaimRef, it must be equal too.\nfunc IsVolumeBoundToClaim(volume *v1.PersistentVolume, claim *v1.PersistentVolumeClaim) bool {\n\tif volume.Spec.ClaimRef == nil {\n\t\treturn false\n\t}\n\tif claim.Name != volume.Spec.ClaimRef.Name || claim.Namespace != volume.Spec.ClaimRef.Namespace {\n\t\treturn false\n\t}\n\tif volume.Spec.ClaimRef.UID != \"\" \u0026\u0026 claim.UID != volume.Spec.ClaimRef.UID {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":155,"to":169}} {"id":100030747,"name":"FindMatchingVolume","signature":"func FindMatchingVolume(","file":"staging/src/k8s.io/component-helpers/storage/volume/pv_helpers.go","code":"// FindMatchingVolume goes through the list of volumes to find the best matching volume\n// for the claim.\n//\n// This function is used by both the PV controller and scheduler.\n//\n// delayBinding is true only in the PV controller path. When set, prebound PVs are still returned\n// as a match for the claim, but unbound PVs are skipped.\n//\n// node is set only in the scheduler path. When set, the PV node affinity is checked against\n// the node's labels.\n//\n// excludedVolumes is only used in the scheduler path, and is needed for evaluating multiple\n// unbound PVCs for a single Pod at one time. As each PVC finds a matching PV, the chosen\n// PV needs to be excluded from future matching.\nfunc FindMatchingVolume(\n\tclaim *v1.PersistentVolumeClaim,\n\tvolumes []*v1.PersistentVolume,\n\tnode *v1.Node,\n\texcludedVolumes map[string]*v1.PersistentVolume,\n\tdelayBinding bool) (*v1.PersistentVolume, error) {\n\n\tvar smallestVolume *v1.PersistentVolume\n\tvar smallestVolumeQty resource.Quantity\n\trequestedQty := claim.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]\n\trequestedClass := GetPersistentVolumeClaimClass(claim)\n\n\tvar selector labels.Selector\n\tif claim.Spec.Selector != nil {\n\t\tinternalSelector, err := metav1.LabelSelectorAsSelector(claim.Spec.Selector)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error creating internal label selector for claim: %v: %v\", claimToClaimKey(claim), err)\n\t\t}\n\t\tselector = internalSelector\n\t}\n\n\t// Go through all available volumes with two goals:\n\t// - find a volume that is either pre-bound by user or dynamically\n\t// provisioned for this claim. Because of this we need to loop through\n\t// all volumes.\n\t// - find the smallest matching one if there is no volume pre-bound to\n\t// the claim.\n\tfor _, volume := range volumes {\n\t\tif _, ok := excludedVolumes[volume.Name]; ok {\n\t\t\t// Skip volumes in the excluded list\n\t\t\tcontinue\n\t\t}\n\t\tif volume.Spec.ClaimRef != nil \u0026\u0026 !IsVolumeBoundToClaim(volume, claim) {\n\t\t\tcontinue\n\t\t}\n\n\t\tvolumeQty := volume.Spec.Capacity[v1.ResourceStorage]\n\t\tif volumeQty.Cmp(requestedQty) \u003c 0 {\n\t\t\tcontinue\n\t\t}\n\t\t// filter out mismatching volumeModes\n\t\tif CheckVolumeModeMismatches(\u0026claim.Spec, \u0026volume.Spec) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// check if PV's DeletionTimeStamp is set, if so, skip this volume.\n\t\tif volume.ObjectMeta.DeletionTimestamp != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tnodeAffinityValid := true\n\t\tif node != nil {\n\t\t\t// Scheduler path, check that the PV NodeAffinity\n\t\t\t// is satisfied by the node\n\t\t\t// CheckNodeAffinity is the most expensive call in this loop.\n\t\t\t// We should check cheaper conditions first or consider optimizing this function.\n\t\t\terr := CheckNodeAffinity(volume, node.Labels)\n\t\t\tif err != nil {\n\t\t\t\tnodeAffinityValid = false\n\t\t\t}\n\t\t}\n\n\t\tif IsVolumeBoundToClaim(volume, claim) {\n\t\t\t// If PV node affinity is invalid, return no match.\n\t\t\t// This means the prebound PV (and therefore PVC)\n\t\t\t// is not suitable for this node.\n\t\t\tif !nodeAffinityValid {\n\t\t\t\treturn nil, nil\n\t\t\t}\n\n\t\t\treturn volume, nil\n\t\t}\n\n\t\tif node == nil \u0026\u0026 delayBinding {\n\t\t\t// PV controller does not bind this claim.\n\t\t\t// Scheduler will handle binding unbound volumes\n\t\t\t// Scheduler path will have node != nil\n\t\t\tcontinue\n\t\t}\n\n\t\t// filter out:\n\t\t// - volumes in non-available phase\n\t\t// - volumes whose labels don't match the claim's selector, if specified\n\t\t// - volumes in Class that is not requested\n\t\t// - volumes whose NodeAffinity does not match the node\n\t\tif volume.Status.Phase != v1.VolumeAvailable {\n\t\t\t// We ignore volumes in non-available phase, because volumes that\n\t\t\t// satisfies matching criteria will be updated to available, binding\n\t\t\t// them now has high chance of encountering unnecessary failures\n\t\t\t// due to API conflicts.\n\t\t\tcontinue\n\t\t} else if selector != nil \u0026\u0026 !selector.Matches(labels.Set(volume.Labels)) {\n\t\t\tcontinue\n\t\t}\n\t\tif GetPersistentVolumeClass(volume) != requestedClass {\n\t\t\tcontinue\n\t\t}\n\t\tif !nodeAffinityValid {\n\t\t\tcontinue\n\t\t}\n\n\t\tif node != nil {\n\t\t\t// Scheduler path\n\t\t\t// Check that the access modes match\n\t\t\tif !CheckAccessModes(claim, volume) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tif smallestVolume == nil || smallestVolumeQty.Cmp(volumeQty) \u003e 0 {\n\t\t\tsmallestVolume = volume\n\t\t\tsmallestVolumeQty = volumeQty\n\t\t}\n\t}\n\n\tif smallestVolume != nil {\n\t\t// Found a matching volume\n\t\treturn smallestVolume, nil\n\t}\n\n\treturn nil, nil\n}","line":{"from":171,"to":306}} {"id":100030748,"name":"CheckVolumeModeMismatches","signature":"func CheckVolumeModeMismatches(pvcSpec *v1.PersistentVolumeClaimSpec, pvSpec *v1.PersistentVolumeSpec) bool","file":"staging/src/k8s.io/component-helpers/storage/volume/pv_helpers.go","code":"// CheckVolumeModeMismatches is a convenience method that checks volumeMode for PersistentVolume\n// and PersistentVolumeClaims\nfunc CheckVolumeModeMismatches(pvcSpec *v1.PersistentVolumeClaimSpec, pvSpec *v1.PersistentVolumeSpec) bool {\n\t// In HA upgrades, we cannot guarantee that the apiserver is on a version \u003e= controller-manager.\n\t// So we default a nil volumeMode to filesystem\n\trequestedVolumeMode := v1.PersistentVolumeFilesystem\n\tif pvcSpec.VolumeMode != nil {\n\t\trequestedVolumeMode = *pvcSpec.VolumeMode\n\t}\n\tpvVolumeMode := v1.PersistentVolumeFilesystem\n\tif pvSpec.VolumeMode != nil {\n\t\tpvVolumeMode = *pvSpec.VolumeMode\n\t}\n\treturn requestedVolumeMode != pvVolumeMode\n}","line":{"from":308,"to":322}} {"id":100030749,"name":"CheckAccessModes","signature":"func CheckAccessModes(claim *v1.PersistentVolumeClaim, volume *v1.PersistentVolume) bool","file":"staging/src/k8s.io/component-helpers/storage/volume/pv_helpers.go","code":"// CheckAccessModes returns true if PV satisfies all the PVC's requested AccessModes\nfunc CheckAccessModes(claim *v1.PersistentVolumeClaim, volume *v1.PersistentVolume) bool {\n\tpvModesMap := map[v1.PersistentVolumeAccessMode]bool{}\n\tfor _, mode := range volume.Spec.AccessModes {\n\t\tpvModesMap[mode] = true\n\t}\n\n\tfor _, mode := range claim.Spec.AccessModes {\n\t\t_, ok := pvModesMap[mode]\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":324,"to":338}} {"id":100030750,"name":"claimToClaimKey","signature":"func claimToClaimKey(claim *v1.PersistentVolumeClaim) string","file":"staging/src/k8s.io/component-helpers/storage/volume/pv_helpers.go","code":"func claimToClaimKey(claim *v1.PersistentVolumeClaim) string {\n\treturn fmt.Sprintf(\"%s/%s\", claim.Namespace, claim.Name)\n}","line":{"from":340,"to":342}} {"id":100030751,"name":"WaitForAPIServer","signature":"func WaitForAPIServer(client clientset.Interface, timeout time.Duration) error","file":"staging/src/k8s.io/controller-manager/app/helper.go","code":"// WaitForAPIServer waits for the API Server's /healthz endpoint to report \"ok\" with timeout.\nfunc WaitForAPIServer(client clientset.Interface, timeout time.Duration) error {\n\tvar lastErr error\n\n\terr := wait.PollImmediate(time.Second, timeout, func() (bool, error) {\n\t\thealthStatus := 0\n\t\tresult := client.Discovery().RESTClient().Get().AbsPath(\"/healthz\").Do(context.TODO()).StatusCode(\u0026healthStatus)\n\t\tif result.Error() != nil {\n\t\t\tlastErr = fmt.Errorf(\"failed to get apiserver /healthz status: %v\", result.Error())\n\t\t\treturn false, nil\n\t\t}\n\t\tif healthStatus != http.StatusOK {\n\t\t\tcontent, _ := result.Raw()\n\t\t\tlastErr = fmt.Errorf(\"APIServer isn't healthy: %v\", string(content))\n\t\t\tklog.Warningf(\"APIServer isn't healthy yet: %v. Waiting a little while.\", string(content))\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%v: %v\", err, lastErr)\n\t}\n\n\treturn nil\n}","line":{"from":31,"to":57}} {"id":100030752,"name":"IsControllerEnabled","signature":"func IsControllerEnabled(name string, disabledByDefaultControllers sets.String, controllers []string) bool","file":"staging/src/k8s.io/controller-manager/app/helper.go","code":"// IsControllerEnabled check if a specified controller enabled or not.\nfunc IsControllerEnabled(name string, disabledByDefaultControllers sets.String, controllers []string) bool {\n\thasStar := false\n\tfor _, ctrl := range controllers {\n\t\tif ctrl == name {\n\t\t\treturn true\n\t\t}\n\t\tif ctrl == \"-\"+name {\n\t\t\treturn false\n\t\t}\n\t\tif ctrl == \"*\" {\n\t\t\thasStar = true\n\t\t}\n\t}\n\t// if we get here, there was no explicit choice\n\tif !hasStar {\n\t\t// nothing on by default\n\t\treturn false\n\t}\n\n\treturn !disabledByDefaultControllers.Has(name)\n}","line":{"from":59,"to":80}} {"id":100030753,"name":"BuildHandlerChain","signature":"func BuildHandlerChain(apiHandler http.Handler, authorizationInfo *apiserver.AuthorizationInfo, authenticationInfo *apiserver.AuthenticationInfo) http.Handler","file":"staging/src/k8s.io/controller-manager/app/serve.go","code":"// BuildHandlerChain builds a handler chain with a base handler and CompletedConfig.\nfunc BuildHandlerChain(apiHandler http.Handler, authorizationInfo *apiserver.AuthorizationInfo, authenticationInfo *apiserver.AuthenticationInfo) http.Handler {\n\trequestInfoResolver := \u0026apirequest.RequestInfoFactory{}\n\tfailedHandler := genericapifilters.Unauthorized(scheme.Codecs)\n\n\thandler := apiHandler\n\tif authorizationInfo != nil {\n\t\thandler = genericapifilters.WithAuthorization(apiHandler, authorizationInfo.Authorizer, scheme.Codecs)\n\t}\n\tif authenticationInfo != nil {\n\t\thandler = genericapifilters.WithAuthentication(handler, authenticationInfo.Authenticator, failedHandler, nil, nil)\n\t}\n\thandler = genericapifilters.WithRequestInfo(handler, requestInfoResolver)\n\thandler = genericapifilters.WithCacheControl(handler)\n\thandler = genericfilters.WithHTTPLogging(handler)\n\thandler = genericfilters.WithPanicRecovery(handler, requestInfoResolver)\n\n\treturn handler\n}","line":{"from":37,"to":55}} {"id":100030754,"name":"NewBaseHandler","signature":"func NewBaseHandler(c *componentbaseconfig.DebuggingConfiguration, healthzHandler http.Handler) *mux.PathRecorderMux","file":"staging/src/k8s.io/controller-manager/app/serve.go","code":"// NewBaseHandler takes in CompletedConfig and returns a handler.\nfunc NewBaseHandler(c *componentbaseconfig.DebuggingConfiguration, healthzHandler http.Handler) *mux.PathRecorderMux {\n\tmux := mux.NewPathRecorderMux(\"controller-manager\")\n\tmux.Handle(\"/healthz\", healthzHandler)\n\tif c.EnableProfiling {\n\t\troutes.Profiling{}.Install(mux)\n\t\tif c.EnableContentionProfiling {\n\t\t\tgoruntime.SetBlockProfileRate(1)\n\t\t}\n\t\troutes.DebugFlags{}.Install(mux, \"v\", routes.StringFlagPutHandler(logs.GlogSetter))\n\t}\n\tconfigz.InstallHandler(mux)\n\tmux.Handle(\"/metrics\", legacyregistry.Handler())\n\n\treturn mux\n}","line":{"from":57,"to":72}} {"id":100030755,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/controller-manager/config/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026LeaderMigrationConfiguration{},\n\t)\n\treturn nil\n}","line":{"from":40,"to":46}} {"id":100030756,"name":"init","signature":"func init()","file":"staging/src/k8s.io/controller-manager/config/v1/conversion.go","code":"func init() {\n\tlocalSchemeBuilder.Register(RegisterConversions)\n}","line":{"from":27,"to":29}} {"id":100030757,"name":"RegisterConversions","signature":"func RegisterConversions(s *runtime.Scheme) error","file":"staging/src/k8s.io/controller-manager/config/v1/conversion.go","code":"// RegisterConversions adds conversion functions to the given scheme.\n// Public to allow building arbitrary schemes.\nfunc RegisterConversions(s *runtime.Scheme) error {\n\tif err := s.AddGeneratedConversionFunc((*ControllerLeaderConfiguration)(nil), (*config.ControllerLeaderConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error {\n\t\treturn Convert_v1_ControllerLeaderConfiguration_To_config_ControllerLeaderConfiguration(a.(*ControllerLeaderConfiguration), b.(*config.ControllerLeaderConfiguration), scope)\n\t}); err != nil {\n\t\treturn err\n\t}\n\tif err := s.AddGeneratedConversionFunc((*config.ControllerLeaderConfiguration)(nil), (*ControllerLeaderConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error {\n\t\treturn Convert_config_ControllerLeaderConfiguration_To_v1_ControllerLeaderConfiguration(a.(*config.ControllerLeaderConfiguration), b.(*ControllerLeaderConfiguration), scope)\n\t}); err != nil {\n\t\treturn err\n\t}\n\tif err := s.AddGeneratedConversionFunc((*LeaderMigrationConfiguration)(nil), (*config.LeaderMigrationConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error {\n\t\treturn Convert_v1_LeaderMigrationConfiguration_To_config_LeaderMigrationConfiguration(a.(*LeaderMigrationConfiguration), b.(*config.LeaderMigrationConfiguration), scope)\n\t}); err != nil {\n\t\treturn err\n\t}\n\tif err := s.AddGeneratedConversionFunc((*config.LeaderMigrationConfiguration)(nil), (*LeaderMigrationConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error {\n\t\treturn Convert_config_LeaderMigrationConfiguration_To_v1_LeaderMigrationConfiguration(a.(*config.LeaderMigrationConfiguration), b.(*LeaderMigrationConfiguration), scope)\n\t}); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":33,"to":57}} {"id":100030758,"name":"Convert_config_LeaderMigrationConfiguration_To_v1_LeaderMigrationConfiguration","signature":"func Convert_config_LeaderMigrationConfiguration_To_v1_LeaderMigrationConfiguration(in *config.LeaderMigrationConfiguration, out *LeaderMigrationConfiguration, s conversion.Scope) error","file":"staging/src/k8s.io/controller-manager/config/v1/conversion.go","code":"func Convert_config_LeaderMigrationConfiguration_To_v1_LeaderMigrationConfiguration(in *config.LeaderMigrationConfiguration, out *LeaderMigrationConfiguration, s conversion.Scope) error {\n\tout.LeaderName = in.LeaderName\n\tout.ControllerLeaders = *(*[]ControllerLeaderConfiguration)(unsafe.Pointer(\u0026in.ControllerLeaders))\n\treturn nil\n}","line":{"from":59,"to":63}} {"id":100030759,"name":"Convert_v1_LeaderMigrationConfiguration_To_config_LeaderMigrationConfiguration","signature":"func Convert_v1_LeaderMigrationConfiguration_To_config_LeaderMigrationConfiguration(in *LeaderMigrationConfiguration, out *config.LeaderMigrationConfiguration, s conversion.Scope) error","file":"staging/src/k8s.io/controller-manager/config/v1/conversion.go","code":"func Convert_v1_LeaderMigrationConfiguration_To_config_LeaderMigrationConfiguration(in *LeaderMigrationConfiguration, out *config.LeaderMigrationConfiguration, s conversion.Scope) error {\n\tout.LeaderName = in.LeaderName\n\tout.ControllerLeaders = *(*[]config.ControllerLeaderConfiguration)(unsafe.Pointer(\u0026in.ControllerLeaders))\n\tout.ResourceLock = ResourceLockLeases\n\treturn nil\n}","line":{"from":65,"to":70}} {"id":100030760,"name":"Convert_v1_ControllerLeaderConfiguration_To_config_ControllerLeaderConfiguration","signature":"func Convert_v1_ControllerLeaderConfiguration_To_config_ControllerLeaderConfiguration(in *ControllerLeaderConfiguration, out *config.ControllerLeaderConfiguration, s conversion.Scope) error","file":"staging/src/k8s.io/controller-manager/config/v1/conversion.go","code":"func Convert_v1_ControllerLeaderConfiguration_To_config_ControllerLeaderConfiguration(in *ControllerLeaderConfiguration, out *config.ControllerLeaderConfiguration, s conversion.Scope) error {\n\tout.Name = in.Name\n\tout.Component = in.Component\n\treturn nil\n}","line":{"from":72,"to":76}} {"id":100030761,"name":"Convert_config_ControllerLeaderConfiguration_To_v1_ControllerLeaderConfiguration","signature":"func Convert_config_ControllerLeaderConfiguration_To_v1_ControllerLeaderConfiguration(in *config.ControllerLeaderConfiguration, out *ControllerLeaderConfiguration, s conversion.Scope) error","file":"staging/src/k8s.io/controller-manager/config/v1/conversion.go","code":"func Convert_config_ControllerLeaderConfiguration_To_v1_ControllerLeaderConfiguration(in *config.ControllerLeaderConfiguration, out *ControllerLeaderConfiguration, s conversion.Scope) error {\n\tout.Name = in.Name\n\tout.Component = in.Component\n\treturn nil\n}","line":{"from":78,"to":82}} {"id":100030762,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/controller-manager/config/v1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026LeaderMigrationConfiguration{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":41,"to":48}} {"id":100030763,"name":"Convert_v1alpha1_GenericControllerManagerConfiguration_To_config_GenericControllerManagerConfiguration","signature":"func Convert_v1alpha1_GenericControllerManagerConfiguration_To_config_GenericControllerManagerConfiguration(in *GenericControllerManagerConfiguration, out *cmconfig.GenericControllerManagerConfiguration, s conversion.Scope) error","file":"staging/src/k8s.io/controller-manager/config/v1alpha1/conversion.go","code":"// Convert_v1alpha1_GenericControllerManagerConfiguration_To_config_GenericControllerManagerConfiguration is an autogenerated conversion function.\nfunc Convert_v1alpha1_GenericControllerManagerConfiguration_To_config_GenericControllerManagerConfiguration(in *GenericControllerManagerConfiguration, out *cmconfig.GenericControllerManagerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_v1alpha1_GenericControllerManagerConfiguration_To_config_GenericControllerManagerConfiguration(in, out, s)\n}","line":{"from":31,"to":34}} {"id":100030764,"name":"Convert_config_GenericControllerManagerConfiguration_To_v1alpha1_GenericControllerManagerConfiguration","signature":"func Convert_config_GenericControllerManagerConfiguration_To_v1alpha1_GenericControllerManagerConfiguration(in *cmconfig.GenericControllerManagerConfiguration, out *GenericControllerManagerConfiguration, s conversion.Scope) error","file":"staging/src/k8s.io/controller-manager/config/v1alpha1/conversion.go","code":"// Convert_config_GenericControllerManagerConfiguration_To_v1alpha1_GenericControllerManagerConfiguration is an autogenerated conversion function.\nfunc Convert_config_GenericControllerManagerConfiguration_To_v1alpha1_GenericControllerManagerConfiguration(in *cmconfig.GenericControllerManagerConfiguration, out *GenericControllerManagerConfiguration, s conversion.Scope) error {\n\treturn autoConvert_config_GenericControllerManagerConfiguration_To_v1alpha1_GenericControllerManagerConfiguration(in, out, s)\n}","line":{"from":36,"to":39}} {"id":100030765,"name":"RecommendedDefaultGenericControllerManagerConfiguration","signature":"func RecommendedDefaultGenericControllerManagerConfiguration(obj *GenericControllerManagerConfiguration)","file":"staging/src/k8s.io/controller-manager/config/v1alpha1/defaults.go","code":"func RecommendedDefaultGenericControllerManagerConfiguration(obj *GenericControllerManagerConfiguration) {\n\tzero := metav1.Duration{}\n\tif obj.Address == \"\" {\n\t\tobj.Address = \"0.0.0.0\"\n\t}\n\tif obj.MinResyncPeriod == zero {\n\t\tobj.MinResyncPeriod = metav1.Duration{Duration: 12 * time.Hour}\n\t}\n\tif obj.ControllerStartInterval == zero {\n\t\tobj.ControllerStartInterval = metav1.Duration{Duration: 0 * time.Second}\n\t}\n\tif len(obj.Controllers) == 0 {\n\t\tobj.Controllers = []string{\"*\"}\n\t}\n\n\tif len(obj.LeaderElection.ResourceLock) == 0 {\n\t\t// Use lease-based leader election to reduce cost.\n\t\t// We migrated for EndpointsLease lock in 1.17 and starting in 1.20 we\n\t\t// migrated to Lease lock.\n\t\tobj.LeaderElection.ResourceLock = \"leases\"\n\t}\n\n\t// Use the default ClientConnectionConfiguration and LeaderElectionConfiguration options\n\tcomponentbaseconfigv1alpha1.RecommendedDefaultClientConnectionConfiguration(\u0026obj.ClientConnection)\n\tcomponentbaseconfigv1alpha1.RecommendedDefaultLeaderElectionConfiguration(\u0026obj.LeaderElection)\n}","line":{"from":26,"to":51}} {"id":100030766,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/controller-manager/config/v1alpha1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026LeaderMigrationConfiguration{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":41,"to":48}} {"id":100030767,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/controller-manager/config/v1beta1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026LeaderMigrationConfiguration{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":41,"to":48}} {"id":100030768,"name":"RecommendedDebuggingOptions","signature":"func RecommendedDebuggingOptions() *DebuggingOptions","file":"staging/src/k8s.io/controller-manager/options/debugging.go","code":"// RecommendedDebuggingOptions returns the currently recommended debugging options. These are subject to change\n// between releases as we add options and decide which features should be exposed or not by default.\nfunc RecommendedDebuggingOptions() *DebuggingOptions {\n\treturn \u0026DebuggingOptions{\n\t\tDebuggingConfiguration: \u0026componentbaseconfig.DebuggingConfiguration{\n\t\t\tEnableProfiling: true, // profile debugging is cheap to have exposed and standard on kube binaries\n\t\t},\n\t}\n}","line":{"from":30,"to":38}} {"id":100030769,"name":"AddFlags","signature":"func (o *DebuggingOptions) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/controller-manager/options/debugging.go","code":"// AddFlags adds flags related to debugging for controller manager to the specified FlagSet.\nfunc (o *DebuggingOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.BoolVar(\u0026o.EnableProfiling, \"profiling\", o.EnableProfiling,\n\t\t\"Enable profiling via web interface host:port/debug/pprof/\")\n\tfs.BoolVar(\u0026o.EnableContentionProfiling, \"contention-profiling\", o.EnableContentionProfiling,\n\t\t\"Enable block profiling, if profiling is enabled\")\n}","line":{"from":40,"to":50}} {"id":100030770,"name":"ApplyTo","signature":"func (o *DebuggingOptions) ApplyTo(cfg *componentbaseconfig.DebuggingConfiguration) error","file":"staging/src/k8s.io/controller-manager/options/debugging.go","code":"// ApplyTo fills up Debugging config with options.\nfunc (o *DebuggingOptions) ApplyTo(cfg *componentbaseconfig.DebuggingConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.EnableProfiling = o.EnableProfiling\n\tcfg.EnableContentionProfiling = o.EnableContentionProfiling\n\n\treturn nil\n}","line":{"from":52,"to":62}} {"id":100030771,"name":"Validate","signature":"func (o *DebuggingOptions) Validate() []error","file":"staging/src/k8s.io/controller-manager/options/debugging.go","code":"// Validate checks validation of DebuggingOptions.\nfunc (o *DebuggingOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\treturn errs\n}","line":{"from":64,"to":72}} {"id":100030772,"name":"NewGenericControllerManagerConfigurationOptions","signature":"func NewGenericControllerManagerConfigurationOptions(cfg *cmconfig.GenericControllerManagerConfiguration) *GenericControllerManagerConfigurationOptions","file":"staging/src/k8s.io/controller-manager/options/generic.go","code":"// NewGenericControllerManagerConfigurationOptions returns generic configuration default values for both\n// the kube-controller-manager and the cloud-contoller-manager. Any common changes should\n// be made here. Any individual changes should be made in that controller.\nfunc NewGenericControllerManagerConfigurationOptions(cfg *cmconfig.GenericControllerManagerConfiguration) *GenericControllerManagerConfigurationOptions {\n\to := \u0026GenericControllerManagerConfigurationOptions{\n\t\tGenericControllerManagerConfiguration: cfg,\n\t\tDebugging: RecommendedDebuggingOptions(),\n\t\tLeaderMigration: \u0026migration.LeaderMigrationOptions{},\n\t}\n\n\treturn o\n}","line":{"from":38,"to":49}} {"id":100030773,"name":"AddFlags","signature":"func (o *GenericControllerManagerConfigurationOptions) AddFlags(fss *cliflag.NamedFlagSets, allControllers, disabledByDefaultControllers []string)","file":"staging/src/k8s.io/controller-manager/options/generic.go","code":"// AddFlags adds flags related to generic for controller manager to the specified FlagSet.\nfunc (o *GenericControllerManagerConfigurationOptions) AddFlags(fss *cliflag.NamedFlagSets, allControllers, disabledByDefaultControllers []string) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\to.Debugging.AddFlags(fss.FlagSet(\"debugging\"))\n\to.LeaderMigration.AddFlags(fss.FlagSet(\"leader-migration\"))\n\tgenericfs := fss.FlagSet(\"generic\")\n\tgenericfs.DurationVar(\u0026o.MinResyncPeriod.Duration, \"min-resync-period\", o.MinResyncPeriod.Duration, \"The resync period in reflectors will be random between MinResyncPeriod and 2*MinResyncPeriod.\")\n\tgenericfs.StringVar(\u0026o.ClientConnection.ContentType, \"kube-api-content-type\", o.ClientConnection.ContentType, \"Content type of requests sent to apiserver.\")\n\tgenericfs.Float32Var(\u0026o.ClientConnection.QPS, \"kube-api-qps\", o.ClientConnection.QPS, \"QPS to use while talking with kubernetes apiserver.\")\n\tgenericfs.Int32Var(\u0026o.ClientConnection.Burst, \"kube-api-burst\", o.ClientConnection.Burst, \"Burst to use while talking with kubernetes apiserver.\")\n\tgenericfs.DurationVar(\u0026o.ControllerStartInterval.Duration, \"controller-start-interval\", o.ControllerStartInterval.Duration, \"Interval between starting controller managers.\")\n\tgenericfs.StringSliceVar(\u0026o.Controllers, \"controllers\", o.Controllers, fmt.Sprintf(\"\"+\n\t\t\"A list of controllers to enable. '*' enables all on-by-default controllers, 'foo' enables the controller \"+\n\t\t\"named 'foo', '-foo' disables the controller named 'foo'.\\nAll controllers: %s\\nDisabled-by-default controllers: %s\",\n\t\tstrings.Join(allControllers, \", \"), strings.Join(disabledByDefaultControllers, \", \")))\n\n\toptions.BindLeaderElectionFlags(\u0026o.LeaderElection, genericfs)\n}","line":{"from":51,"to":71}} {"id":100030774,"name":"ApplyTo","signature":"func (o *GenericControllerManagerConfigurationOptions) ApplyTo(cfg *cmconfig.GenericControllerManagerConfiguration) error","file":"staging/src/k8s.io/controller-manager/options/generic.go","code":"// ApplyTo fills up generic config with options.\nfunc (o *GenericControllerManagerConfigurationOptions) ApplyTo(cfg *cmconfig.GenericControllerManagerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tif err := o.Debugging.ApplyTo(\u0026cfg.Debugging); err != nil {\n\t\treturn err\n\t}\n\tif err := o.LeaderMigration.ApplyTo(cfg); err != nil {\n\t\treturn err\n\t}\n\tcfg.Port = o.Port\n\tcfg.Address = o.Address\n\tcfg.MinResyncPeriod = o.MinResyncPeriod\n\tcfg.ClientConnection = o.ClientConnection\n\tcfg.ControllerStartInterval = o.ControllerStartInterval\n\tcfg.LeaderElection = o.LeaderElection\n\tcfg.Controllers = o.Controllers\n\n\treturn nil\n}","line":{"from":73,"to":94}} {"id":100030775,"name":"Validate","signature":"func (o *GenericControllerManagerConfigurationOptions) Validate(allControllers []string, disabledByDefaultControllers []string) []error","file":"staging/src/k8s.io/controller-manager/options/generic.go","code":"// Validate checks validation of GenericOptions.\nfunc (o *GenericControllerManagerConfigurationOptions) Validate(allControllers []string, disabledByDefaultControllers []string) []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\terrs = append(errs, o.Debugging.Validate()...)\n\n\t// TODO: This can be removed when ResourceLock is not available\n\t// Lock the ResourceLock using leases\n\tif o.LeaderElection.LeaderElect \u0026\u0026 o.LeaderElection.ResourceLock != \"leases\" {\n\t\terrs = append(errs, fmt.Errorf(`resourceLock value must be \"leases\"`))\n\t}\n\n\tallControllersSet := sets.NewString(allControllers...)\n\tfor _, controller := range o.Controllers {\n\t\tif controller == \"*\" {\n\t\t\tcontinue\n\t\t}\n\t\tcontroller = strings.TrimPrefix(controller, \"-\")\n\t\tif !allControllersSet.Has(controller) {\n\t\t\terrs = append(errs, fmt.Errorf(\"%q is not in the list of known controllers\", controller))\n\t\t}\n\t}\n\n\treturn errs\n}","line":{"from":96,"to":123}} {"id":100030776,"name":"Config","signature":"func (b SimpleControllerClientBuilder) Config(name string) (*restclient.Config, error)","file":"staging/src/k8s.io/controller-manager/pkg/clientbuilder/client_builder.go","code":"// Config returns a client config for a fixed client\nfunc (b SimpleControllerClientBuilder) Config(name string) (*restclient.Config, error) {\n\tclientConfig := *b.ClientConfig\n\treturn restclient.AddUserAgent(\u0026clientConfig, name), nil\n}","line":{"from":44,"to":48}} {"id":100030777,"name":"ConfigOrDie","signature":"func (b SimpleControllerClientBuilder) ConfigOrDie(name string) *restclient.Config","file":"staging/src/k8s.io/controller-manager/pkg/clientbuilder/client_builder.go","code":"// ConfigOrDie returns a client config if no error from previous config func.\n// If it gets an error getting the client, it will log the error and kill the process it's running in.\nfunc (b SimpleControllerClientBuilder) ConfigOrDie(name string) *restclient.Config {\n\tclientConfig, err := b.Config(name)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\treturn clientConfig\n}","line":{"from":50,"to":58}} {"id":100030778,"name":"Client","signature":"func (b SimpleControllerClientBuilder) Client(name string) (clientset.Interface, error)","file":"staging/src/k8s.io/controller-manager/pkg/clientbuilder/client_builder.go","code":"// Client returns a clientset.Interface built from the ClientBuilder\nfunc (b SimpleControllerClientBuilder) Client(name string) (clientset.Interface, error) {\n\tclientConfig, err := b.Config(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn clientset.NewForConfig(clientConfig)\n}","line":{"from":60,"to":67}} {"id":100030779,"name":"ClientOrDie","signature":"func (b SimpleControllerClientBuilder) ClientOrDie(name string) clientset.Interface","file":"staging/src/k8s.io/controller-manager/pkg/clientbuilder/client_builder.go","code":"// ClientOrDie returns a clientset.interface built from the ClientBuilder with no error.\n// If it gets an error getting the client, it will log the error and kill the process it's running in.\nfunc (b SimpleControllerClientBuilder) ClientOrDie(name string) clientset.Interface {\n\tclient, err := b.Client(name)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\treturn client\n}","line":{"from":69,"to":77}} {"id":100030780,"name":"DiscoveryClient","signature":"func (b SimpleControllerClientBuilder) DiscoveryClient(name string) (discovery.DiscoveryInterface, error)","file":"staging/src/k8s.io/controller-manager/pkg/clientbuilder/client_builder.go","code":"// DiscoveryClient returns a discovery.DiscoveryInterface built from the ClientBuilder\n// Discovery is special because it will artificially pump the burst quite high to handle the many discovery requests.\nfunc (b SimpleControllerClientBuilder) DiscoveryClient(name string) (discovery.DiscoveryInterface, error) {\n\tclientConfig, err := b.Config(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Discovery makes a lot of requests infrequently. This allows the burst to succeed and refill to happen\n\t// in just a few seconds.\n\tclientConfig.Burst = 200\n\tclientConfig.QPS = 20\n\treturn clientset.NewForConfig(clientConfig)\n}","line":{"from":79,"to":91}} {"id":100030781,"name":"DiscoveryClientOrDie","signature":"func (b SimpleControllerClientBuilder) DiscoveryClientOrDie(name string) discovery.DiscoveryInterface","file":"staging/src/k8s.io/controller-manager/pkg/clientbuilder/client_builder.go","code":"// DiscoveryClientOrDie returns a discovery.DiscoveryInterface built from the ClientBuilder with no error.\n// Discovery is special because it will artificially pump the burst quite high to handle the many discovery requests.\n// If it gets an error getting the client, it will log the error and kill the process it's running in.\nfunc (b SimpleControllerClientBuilder) DiscoveryClientOrDie(name string) discovery.DiscoveryInterface {\n\tclient, err := b.DiscoveryClient(name)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\treturn client\n}","line":{"from":93,"to":102}} {"id":100030782,"name":"NewDynamicClientBuilder","signature":"func NewDynamicClientBuilder(clientConfig *restclient.Config, coreClient v1core.CoreV1Interface, ns string) ControllerClientBuilder","file":"staging/src/k8s.io/controller-manager/pkg/clientbuilder/client_builder_dynamic.go","code":"// NewDynamicClientBuilder returns client builder which uses TokenRequest feature and refresh service account token periodically\nfunc NewDynamicClientBuilder(clientConfig *restclient.Config, coreClient v1core.CoreV1Interface, ns string) ControllerClientBuilder {\n\tbuilder := \u0026DynamicControllerClientBuilder{\n\t\tClientConfig: clientConfig,\n\t\tCoreClient: coreClient,\n\t\tNamespace: ns,\n\t\troundTripperFuncMap: map[string]func(http.RoundTripper) http.RoundTripper{},\n\t\texpirationSeconds: defaultExpirationSeconds,\n\t\tleewayPercent: defaultLeewayPercent,\n\t\tclock: clock.RealClock{},\n\t}\n\treturn builder\n}","line":{"from":78,"to":90}} {"id":100030783,"name":"NewTestDynamicClientBuilder","signature":"func NewTestDynamicClientBuilder(clientConfig *restclient.Config, coreClient v1core.CoreV1Interface, ns string, expirationSeconds int64, leewayPercent int) ControllerClientBuilder","file":"staging/src/k8s.io/controller-manager/pkg/clientbuilder/client_builder_dynamic.go","code":"// this function only for test purpose, don't call it\nfunc NewTestDynamicClientBuilder(clientConfig *restclient.Config, coreClient v1core.CoreV1Interface, ns string, expirationSeconds int64, leewayPercent int) ControllerClientBuilder {\n\tbuilder := \u0026DynamicControllerClientBuilder{\n\t\tClientConfig: clientConfig,\n\t\tCoreClient: coreClient,\n\t\tNamespace: ns,\n\t\troundTripperFuncMap: map[string]func(http.RoundTripper) http.RoundTripper{},\n\t\texpirationSeconds: expirationSeconds,\n\t\tleewayPercent: leewayPercent,\n\t\tclock: clock.RealClock{},\n\t}\n\treturn builder\n}","line":{"from":92,"to":104}} {"id":100030784,"name":"Config","signature":"func (t *DynamicControllerClientBuilder) Config(saName string) (*restclient.Config, error)","file":"staging/src/k8s.io/controller-manager/pkg/clientbuilder/client_builder_dynamic.go","code":"func (t *DynamicControllerClientBuilder) Config(saName string) (*restclient.Config, error) {\n\t_, err := getOrCreateServiceAccount(t.CoreClient, t.Namespace, saName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfigCopy := constructClient(t.Namespace, saName, t.ClientConfig)\n\n\tt.mutex.Lock()\n\tdefer t.mutex.Unlock()\n\n\trt, ok := t.roundTripperFuncMap[saName]\n\tif ok {\n\t\tconfigCopy.Wrap(rt)\n\t} else {\n\t\tcachedTokenSource := transport.NewCachedTokenSource(\u0026tokenSourceImpl{\n\t\t\tnamespace: t.Namespace,\n\t\t\tserviceAccountName: saName,\n\t\t\tcoreClient: t.CoreClient,\n\t\t\texpirationSeconds: t.expirationSeconds,\n\t\t\tleewayPercent: t.leewayPercent,\n\t\t})\n\t\tconfigCopy.Wrap(transport.ResettableTokenSourceWrapTransport(cachedTokenSource))\n\t\tt.roundTripperFuncMap[saName] = configCopy.WrapTransport\n\t}\n\n\treturn \u0026configCopy, nil\n}","line":{"from":106,"to":133}} {"id":100030785,"name":"ConfigOrDie","signature":"func (t *DynamicControllerClientBuilder) ConfigOrDie(name string) *restclient.Config","file":"staging/src/k8s.io/controller-manager/pkg/clientbuilder/client_builder_dynamic.go","code":"func (t *DynamicControllerClientBuilder) ConfigOrDie(name string) *restclient.Config {\n\tclientConfig, err := t.Config(name)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\treturn clientConfig\n}","line":{"from":135,"to":141}} {"id":100030786,"name":"Client","signature":"func (t *DynamicControllerClientBuilder) Client(name string) (clientset.Interface, error)","file":"staging/src/k8s.io/controller-manager/pkg/clientbuilder/client_builder_dynamic.go","code":"func (t *DynamicControllerClientBuilder) Client(name string) (clientset.Interface, error) {\n\tclientConfig, err := t.Config(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn clientset.NewForConfig(clientConfig)\n}","line":{"from":143,"to":149}} {"id":100030787,"name":"ClientOrDie","signature":"func (t *DynamicControllerClientBuilder) ClientOrDie(name string) clientset.Interface","file":"staging/src/k8s.io/controller-manager/pkg/clientbuilder/client_builder_dynamic.go","code":"func (t *DynamicControllerClientBuilder) ClientOrDie(name string) clientset.Interface {\n\tclient, err := t.Client(name)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\treturn client\n}","line":{"from":151,"to":157}} {"id":100030788,"name":"DiscoveryClient","signature":"func (t *DynamicControllerClientBuilder) DiscoveryClient(name string) (discovery.DiscoveryInterface, error)","file":"staging/src/k8s.io/controller-manager/pkg/clientbuilder/client_builder_dynamic.go","code":"func (t *DynamicControllerClientBuilder) DiscoveryClient(name string) (discovery.DiscoveryInterface, error) {\n\tclientConfig, err := t.Config(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Discovery makes a lot of requests infrequently. This allows the burst to succeed and refill to happen\n\t// in just a few seconds.\n\tclientConfig.Burst = 200\n\tclientConfig.QPS = 20\n\treturn clientset.NewForConfig(clientConfig)\n}","line":{"from":159,"to":169}} {"id":100030789,"name":"DiscoveryClientOrDie","signature":"func (t *DynamicControllerClientBuilder) DiscoveryClientOrDie(name string) discovery.DiscoveryInterface","file":"staging/src/k8s.io/controller-manager/pkg/clientbuilder/client_builder_dynamic.go","code":"func (t *DynamicControllerClientBuilder) DiscoveryClientOrDie(name string) discovery.DiscoveryInterface {\n\tclient, err := t.DiscoveryClient(name)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\treturn client\n}","line":{"from":171,"to":177}} {"id":100030790,"name":"Token","signature":"func (ts *tokenSourceImpl) Token() (*oauth2.Token, error)","file":"staging/src/k8s.io/controller-manager/pkg/clientbuilder/client_builder_dynamic.go","code":"func (ts *tokenSourceImpl) Token() (*oauth2.Token, error) {\n\tvar retTokenRequest *v1authenticationapi.TokenRequest\n\n\tbackoff := wait.Backoff{\n\t\tDuration: 500 * time.Millisecond,\n\t\tFactor: 2, // double the timeout for every failure\n\t\tSteps: 4,\n\t}\n\tif err := wait.ExponentialBackoff(backoff, func() (bool, error) {\n\t\tif _, inErr := getOrCreateServiceAccount(ts.coreClient, ts.namespace, ts.serviceAccountName); inErr != nil {\n\t\t\tklog.Warningf(\"get or create service account failed: %v\", inErr)\n\t\t\treturn false, nil\n\t\t}\n\n\t\ttr, inErr := ts.coreClient.ServiceAccounts(ts.namespace).CreateToken(context.TODO(), ts.serviceAccountName, \u0026v1authenticationapi.TokenRequest{\n\t\t\tSpec: v1authenticationapi.TokenRequestSpec{\n\t\t\t\tExpirationSeconds: utilpointer.Int64Ptr(ts.expirationSeconds),\n\t\t\t},\n\t\t}, metav1.CreateOptions{})\n\t\tif inErr != nil {\n\t\t\tklog.Warningf(\"get token failed: %v\", inErr)\n\t\t\treturn false, nil\n\t\t}\n\t\tretTokenRequest = tr\n\t\treturn true, nil\n\t}); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get token for %s/%s: %v\", ts.namespace, ts.serviceAccountName, err)\n\t}\n\n\tif retTokenRequest.Spec.ExpirationSeconds == nil {\n\t\treturn nil, fmt.Errorf(\"nil pointer of expiration in token request\")\n\t}\n\n\tlifetime := retTokenRequest.Status.ExpirationTimestamp.Time.Sub(time.Now())\n\tif lifetime \u003c time.Minute*10 {\n\t\t// possible clock skew issue, pin to minimum token lifetime\n\t\tlifetime = time.Minute * 10\n\t}\n\n\tleeway := time.Duration(int64(lifetime) * int64(ts.leewayPercent) / 100)\n\texpiry := time.Now().Add(lifetime).Add(-1 * leeway)\n\n\treturn \u0026oauth2.Token{\n\t\tAccessToken: retTokenRequest.Status.Token,\n\t\tTokenType: \"Bearer\",\n\t\tExpiry: expiry,\n\t}, nil\n}","line":{"from":187,"to":234}} {"id":100030791,"name":"constructClient","signature":"func constructClient(saNamespace, saName string, config *restclient.Config) restclient.Config","file":"staging/src/k8s.io/controller-manager/pkg/clientbuilder/client_builder_dynamic.go","code":"func constructClient(saNamespace, saName string, config *restclient.Config) restclient.Config {\n\tusername := apiserverserviceaccount.MakeUsername(saNamespace, saName)\n\t// make a shallow copy\n\t// the caller already castrated the config during creation\n\t// this allows for potential extensions in the future\n\t// for example it preserve HTTP wrappers for custom behavior per request\n\tret := *config\n\trestclient.AddUserAgent(\u0026ret, username)\n\treturn ret\n}","line":{"from":236,"to":245}} {"id":100030792,"name":"getOrCreateServiceAccount","signature":"func getOrCreateServiceAccount(coreClient v1core.CoreV1Interface, namespace, name string) (*v1.ServiceAccount, error)","file":"staging/src/k8s.io/controller-manager/pkg/clientbuilder/client_builder_dynamic.go","code":"func getOrCreateServiceAccount(coreClient v1core.CoreV1Interface, namespace, name string) (*v1.ServiceAccount, error) {\n\tsa, err := coreClient.ServiceAccounts(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\tif err == nil {\n\t\treturn sa, nil\n\t}\n\tif !apierrors.IsNotFound(err) {\n\t\treturn nil, err\n\t}\n\n\t// Create the namespace if we can't verify it exists.\n\t// Tolerate errors, since we don't know whether this component has namespace creation permissions.\n\tif _, err := coreClient.Namespaces().Get(context.TODO(), namespace, metav1.GetOptions{}); apierrors.IsNotFound(err) {\n\t\tif _, err = coreClient.Namespaces().Create(context.TODO(), \u0026v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace}}, metav1.CreateOptions{}); err != nil \u0026\u0026 !apierrors.IsAlreadyExists(err) {\n\t\t\tklog.Warningf(\"create non-exist namespace %s failed:%v\", namespace, err)\n\t\t}\n\t}\n\n\t// Create the service account\n\tsa, err = coreClient.ServiceAccounts(namespace).Create(context.TODO(), \u0026v1.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Namespace: namespace, Name: name}}, metav1.CreateOptions{})\n\tif apierrors.IsAlreadyExists(err) {\n\t\t// If we're racing to init and someone else already created it, re-fetch\n\t\treturn coreClient.ServiceAccounts(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\t}\n\treturn sa, err\n}","line":{"from":247,"to":271}} {"id":100030793,"name":"SetupCurrentKubernetesSpecificFeatureGates","signature":"func SetupCurrentKubernetesSpecificFeatureGates(featuregates featuregate.MutableFeatureGate) error","file":"staging/src/k8s.io/controller-manager/pkg/features/kube_features.go","code":"func SetupCurrentKubernetesSpecificFeatureGates(featuregates featuregate.MutableFeatureGate) error {\n\treturn featuregates.Add(cloudPublicFeatureGates)\n}","line":{"from":57,"to":59}} {"id":100030794,"name":"init","signature":"func init()","file":"staging/src/k8s.io/controller-manager/pkg/features/register/register.go","code":"func init() {\n\truntime.Must(features.SetupCurrentKubernetesSpecificFeatureGates(utilfeature.DefaultMutableFeatureGate))\n}","line":{"from":25,"to":27}} {"id":100030795,"name":"ServeHTTP","signature":"func (h *MutableHealthzHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request)","file":"staging/src/k8s.io/controller-manager/pkg/healthz/handler.go","code":"func (h *MutableHealthzHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {\n\th.mutex.RLock()\n\tdefer h.mutex.RUnlock()\n\n\th.handler.ServeHTTP(writer, request)\n}","line":{"from":42,"to":47}} {"id":100030796,"name":"AddHealthChecker","signature":"func (h *MutableHealthzHandler) AddHealthChecker(checks ...healthz.HealthChecker)","file":"staging/src/k8s.io/controller-manager/pkg/healthz/handler.go","code":"// AddHealthChecker adds health check(s) to the handler.\n//\n// Every time this function is called, the handler have to be re-initiated.\n// It is advised to add as many checks at once as possible.\nfunc (h *MutableHealthzHandler) AddHealthChecker(checks ...healthz.HealthChecker) {\n\th.mutex.Lock()\n\tdefer h.mutex.Unlock()\n\n\th.checks = append(h.checks, checks...)\n\tnewMux := mux.NewPathRecorderMux(\"healthz\")\n\thealthz.InstallHandler(newMux, h.checks...)\n\th.handler = newMux\n}","line":{"from":49,"to":61}} {"id":100030797,"name":"NewMutableHealthzHandler","signature":"func NewMutableHealthzHandler(checks ...healthz.HealthChecker) *MutableHealthzHandler","file":"staging/src/k8s.io/controller-manager/pkg/healthz/handler.go","code":"func NewMutableHealthzHandler(checks ...healthz.HealthChecker) *MutableHealthzHandler {\n\th := \u0026MutableHealthzHandler{}\n\th.AddHealthChecker(checks...)\n\n\treturn h\n}","line":{"from":63,"to":68}} {"id":100030798,"name":"NamedPingChecker","signature":"func NamedPingChecker(name string) healthz.HealthChecker","file":"staging/src/k8s.io/controller-manager/pkg/healthz/healthz.go","code":"// NamedPingChecker returns a health check with given name\n// that returns no error when checked.\nfunc NamedPingChecker(name string) healthz.HealthChecker {\n\treturn NamedHealthChecker(name, healthz.PingHealthz)\n}","line":{"from":25,"to":29}} {"id":100030799,"name":"NamedHealthChecker","signature":"func NamedHealthChecker(name string, check UnnamedHealthChecker) healthz.HealthChecker","file":"staging/src/k8s.io/controller-manager/pkg/healthz/healthz.go","code":"// NamedHealthChecker creates a named health check from\n// an unnamed one.\nfunc NamedHealthChecker(name string, check UnnamedHealthChecker) healthz.HealthChecker {\n\treturn healthz.NamedCheck(name, check.Check)\n}","line":{"from":31,"to":35}} {"id":100030800,"name":"ForResource","signature":"func (i *informerFactory) ForResource(resource schema.GroupVersionResource) (informers.GenericInformer, error)","file":"staging/src/k8s.io/controller-manager/pkg/informerfactory/informer_factory.go","code":"func (i *informerFactory) ForResource(resource schema.GroupVersionResource) (informers.GenericInformer, error) {\n\tinformer, err := i.typedInformerFactory.ForResource(resource)\n\tif err != nil {\n\t\treturn i.metadataInformerFactory.ForResource(resource), nil\n\t}\n\treturn informer, nil\n}","line":{"from":36,"to":42}} {"id":100030801,"name":"Start","signature":"func (i *informerFactory) Start(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/controller-manager/pkg/informerfactory/informer_factory.go","code":"func (i *informerFactory) Start(stopCh \u003c-chan struct{}) {\n\ti.typedInformerFactory.Start(stopCh)\n\ti.metadataInformerFactory.Start(stopCh)\n}","line":{"from":44,"to":47}} {"id":100030802,"name":"NewInformerFactory","signature":"func NewInformerFactory(typedInformerFactory informers.SharedInformerFactory, metadataInformerFactory metadatainformer.SharedInformerFactory) InformerFactory","file":"staging/src/k8s.io/controller-manager/pkg/informerfactory/informer_factory.go","code":"// NewInformerFactory creates a new InformerFactory which works with both typed\n// resources and metadata-only resources\nfunc NewInformerFactory(typedInformerFactory informers.SharedInformerFactory, metadataInformerFactory metadatainformer.SharedInformerFactory) InformerFactory {\n\treturn \u0026informerFactory{\n\t\ttypedInformerFactory: typedInformerFactory,\n\t\tmetadataInformerFactory: metadataInformerFactory,\n\t}\n}","line":{"from":49,"to":56}} {"id":100030803,"name":"init","signature":"func init()","file":"staging/src/k8s.io/controller-manager/pkg/leadermigration/config/config.go","code":"func init() {\n\t// internal\n\tutil.Must(internal.AddToScheme(cfgScheme))\n\n\t// v1alpha1\n\tutil.Must(v1alpha1.AddToScheme(cfgScheme))\n\tutil.Must(cfgScheme.SetVersionPriority(v1alpha1.SchemeGroupVersion))\n\n\t// v1beta1\n\tutil.Must(v1beta1.AddToScheme(cfgScheme))\n\tutil.Must(cfgScheme.SetVersionPriority(v1beta1.SchemeGroupVersion))\n\n\t// v1\n\tutil.Must(v1.AddToScheme(cfgScheme))\n\tutil.Must(cfgScheme.SetVersionPriority(v1.SchemeGroupVersion))\n}","line":{"from":41,"to":56}} {"id":100030804,"name":"ReadLeaderMigrationConfiguration","signature":"func ReadLeaderMigrationConfiguration(configFilePath string) (*internal.LeaderMigrationConfiguration, error)","file":"staging/src/k8s.io/controller-manager/pkg/leadermigration/config/config.go","code":"// ReadLeaderMigrationConfiguration reads LeaderMigrationConfiguration from a YAML file at the given path.\n// The parsed LeaderMigrationConfiguration may be invalid.\n// It returns an error if the file did not exist.\nfunc ReadLeaderMigrationConfiguration(configFilePath string) (*internal.LeaderMigrationConfiguration, error) {\n\tdata, err := os.ReadFile(configFilePath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to read leader migration configuration from %q: %w\", configFilePath, err)\n\t}\n\tconfig, gvk, err := serializer.NewCodecFactory(cfgScheme).UniversalDecoder().Decode(data, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinternalConfig, ok := config.(*internal.LeaderMigrationConfiguration)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unexpected config type: %v\", gvk)\n\t}\n\treturn internalConfig, nil\n}","line":{"from":58,"to":75}} {"id":100030805,"name":"ValidateLeaderMigrationConfiguration","signature":"func ValidateLeaderMigrationConfiguration(config *internal.LeaderMigrationConfiguration) (allErrs field.ErrorList)","file":"staging/src/k8s.io/controller-manager/pkg/leadermigration/config/config.go","code":"// ValidateLeaderMigrationConfiguration validates the LeaderMigrationConfiguration against common errors.\n// It checks required names and whether resourceLock is either 'leases' or 'endpoints'.\n// It will return nil if it does not find anything wrong.\nfunc ValidateLeaderMigrationConfiguration(config *internal.LeaderMigrationConfiguration) (allErrs field.ErrorList) {\n\tif config.LeaderName == \"\" {\n\t\tallErrs = append(allErrs, field.Required(field.NewPath(\"leaderName\"),\n\t\t\t\"leaderName must be set for LeaderMigrationConfiguration\"))\n\t}\n\tif config.ResourceLock != ResourceLockLeases \u0026\u0026 config.ResourceLock != ResourceLockEndpoints {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"resourceLock\"), config.ResourceLock,\n\t\t\t\"resource Lock must be one of 'leases' or 'endpoints'\"))\n\t}\n\t// validate controllerLeaders\n\tfldPath := field.NewPath(\"controllerLeaders\")\n\tfor i, controllerLeader := range config.ControllerLeaders {\n\t\tpath := fldPath.Index(i)\n\t\tallErrs = append(allErrs, validateControllerLeaderConfiguration(path, \u0026controllerLeader)...)\n\t}\n\treturn\n}","line":{"from":77,"to":96}} {"id":100030806,"name":"validateControllerLeaderConfiguration","signature":"func validateControllerLeaderConfiguration(path *field.Path, config *internal.ControllerLeaderConfiguration) (allErrs field.ErrorList)","file":"staging/src/k8s.io/controller-manager/pkg/leadermigration/config/config.go","code":"func validateControllerLeaderConfiguration(path *field.Path, config *internal.ControllerLeaderConfiguration) (allErrs field.ErrorList) {\n\tif config == nil {\n\t\treturn\n\t}\n\tif config.Component == \"\" {\n\t\tallErrs = append(allErrs, field.Required(path.Child(\"component\"), \"component must be set\"))\n\t}\n\tif config.Name == \"\" {\n\t\tallErrs = append(allErrs, field.Required(path.Child(\"name\"), \"name must be set\"))\n\t}\n\treturn\n}","line":{"from":98,"to":109}} {"id":100030807,"name":"DefaultLeaderMigrationConfiguration","signature":"func DefaultLeaderMigrationConfiguration() *internal.LeaderMigrationConfiguration","file":"staging/src/k8s.io/controller-manager/pkg/leadermigration/config/default.go","code":"// DefaultLeaderMigrationConfiguration returns the default LeaderMigrationConfiguration\n// that is valid for this release of Kubernetes.\nfunc DefaultLeaderMigrationConfiguration() *internal.LeaderMigrationConfiguration {\n\treturn \u0026internal.LeaderMigrationConfiguration{\n\t\tLeaderName: \"cloud-provider-extraction-migration\",\n\t\tResourceLock: ResourceLockLeases,\n\t\tControllerLeaders: []internal.ControllerLeaderConfiguration{\n\t\t\t{\n\t\t\t\tName: \"route\",\n\t\t\t\tComponent: \"*\",\n\t\t\t}, {\n\t\t\t\tName: \"service\",\n\t\t\t\tComponent: \"*\",\n\t\t\t}, {\n\t\t\t\tName: \"cloud-node-lifecycle\",\n\t\t\t\tComponent: \"*\",\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":21,"to":40}} {"id":100030808,"name":"NewLeaderMigrator","signature":"func NewLeaderMigrator(config *internal.LeaderMigrationConfiguration, component string) *LeaderMigrator","file":"staging/src/k8s.io/controller-manager/pkg/leadermigration/migrator.go","code":"// NewLeaderMigrator creates a LeaderMigrator with given config for the given component. component\n// indicates which controller manager is requesting this leader migration, and it should be consistent\n// with the component field of ControllerLeaderConfiguration.\nfunc NewLeaderMigrator(config *internal.LeaderMigrationConfiguration, component string) *LeaderMigrator {\n\tmigratedControllers := make(map[string]bool)\n\tfor _, leader := range config.ControllerLeaders {\n\t\tmigratedControllers[leader.Name] = leader.Component == component || leader.Component == \"*\"\n\t}\n\treturn \u0026LeaderMigrator{\n\t\tMigrationReady: make(chan struct{}),\n\t\tFilterFunc: func(controllerName string) FilterResult {\n\t\t\tshouldRun, ok := migratedControllers[controllerName]\n\t\t\tif ok {\n\t\t\t\t// The controller is included in the migration\n\t\t\t\tif shouldRun {\n\t\t\t\t\t// If the controller manager should run the controller,\n\t\t\t\t\t// start it in the migration lock.\n\t\t\t\t\treturn ControllerMigrated\n\t\t\t\t}\n\t\t\t\t// Otherwise, the controller should be started by\n\t\t\t\t// some other controller manager.\n\t\t\t\treturn ControllerUnowned\n\t\t\t}\n\t\t\t// The controller is not included in the migration,\n\t\t\t// and should be started in the main lock.\n\t\t\treturn ControllerNonMigrated\n\t\t},\n\t}\n}","line":{"from":33,"to":61}} {"id":100030809,"name":"DefaultLeaderMigrationOptions","signature":"func DefaultLeaderMigrationOptions() *LeaderMigrationOptions","file":"staging/src/k8s.io/controller-manager/pkg/leadermigration/options/options.go","code":"// DefaultLeaderMigrationOptions returns a LeaderMigrationOptions with default values.\nfunc DefaultLeaderMigrationOptions() *LeaderMigrationOptions {\n\treturn \u0026LeaderMigrationOptions{\n\t\tEnabled: false,\n\t\tControllerMigrationConfig: \"\",\n\t}\n}","line":{"from":39,"to":45}} {"id":100030810,"name":"AddFlags","signature":"func (o *LeaderMigrationOptions) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/controller-manager/pkg/leadermigration/options/options.go","code":"// AddFlags adds all flags related to leader migration to given flag set.\nfunc (o *LeaderMigrationOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\tfs.BoolVar(\u0026o.Enabled, \"enable-leader-migration\", false, \"Whether to enable controller leader migration.\")\n\tfs.StringVar(\u0026o.ControllerMigrationConfig, \"leader-migration-config\", \"\",\n\t\t\"Path to the config file for controller leader migration, \"+\n\t\t\t\"or empty to use the value that reflects default configuration of the controller manager. \"+\n\t\t\t\"The config file should be of type LeaderMigrationConfiguration, group controllermanager.config.k8s.io, version v1alpha1.\")\n}","line":{"from":47,"to":57}} {"id":100030811,"name":"ApplyTo","signature":"func (o *LeaderMigrationOptions) ApplyTo(cfg *config.GenericControllerManagerConfiguration) error","file":"staging/src/k8s.io/controller-manager/pkg/leadermigration/options/options.go","code":"// ApplyTo applies the options of leader migration to generic configuration.\nfunc (o *LeaderMigrationOptions) ApplyTo(cfg *config.GenericControllerManagerConfiguration) error {\n\tif o == nil {\n\t\t// an nil LeaderMigrationOptions indicates that default options should be used\n\t\t// in which case leader migration will be disabled\n\t\tcfg.LeaderMigrationEnabled = false\n\t\treturn nil\n\t}\n\tcfg.LeaderMigrationEnabled = o.Enabled\n\tif !cfg.LeaderMigrationEnabled {\n\t\treturn nil\n\t}\n\tif o.ControllerMigrationConfig == \"\" {\n\t\tcfg.LeaderMigration = *migrationconfig.DefaultLeaderMigrationConfiguration()\n\t\treturn nil\n\t}\n\tleaderMigrationConfig, err := migrationconfig.ReadLeaderMigrationConfiguration(o.ControllerMigrationConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\terrs := migrationconfig.ValidateLeaderMigrationConfiguration(leaderMigrationConfig)\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"failed to parse leader migration configuration: %v\", errs)\n\t}\n\tcfg.LeaderMigration = *leaderMigrationConfig\n\treturn nil\n}","line":{"from":59,"to":85}} {"id":100030812,"name":"Enabled","signature":"func Enabled(genericConfig *config.GenericControllerManagerConfiguration) bool","file":"staging/src/k8s.io/controller-manager/pkg/leadermigration/util.go","code":"// Enabled checks whether Leader Migration should be enabled, given the GenericControllerManagerConfiguration.\n// It considers the feature gate first, and will always return false if the feature gate is not enabled.\nfunc Enabled(genericConfig *config.GenericControllerManagerConfiguration) bool {\n\treturn genericConfig.LeaderElection.LeaderElect \u0026\u0026 genericConfig.LeaderMigrationEnabled\n}","line":{"from":21,"to":25}} {"id":100030813,"name":"IsNotFound","signature":"func IsNotFound(err error) bool","file":"staging/src/k8s.io/cri-api/pkg/errors/errors.go","code":"// IsNotFound returns a boolean indicating whether the error\n// is grpc not found error.\n// See https://github.com/grpc/grpc/blob/master/doc/statuscodes.md\n// for a list of grpc status codes.\nfunc IsNotFound(err error) bool {\n\ts, ok := status.FromError(err)\n\tif !ok {\n\t\treturn ok\n\t}\n\tif s.Code() == codes.NotFound {\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":24,"to":38}} {"id":100030814,"name":"NewAWSElasticBlockStoreCSITranslator","signature":"func NewAWSElasticBlockStoreCSITranslator() InTreePlugin","file":"staging/src/k8s.io/csi-translation-lib/plugins/aws_ebs.go","code":"// NewAWSElasticBlockStoreCSITranslator returns a new instance of awsElasticBlockStoreTranslator\nfunc NewAWSElasticBlockStoreCSITranslator() InTreePlugin {\n\treturn \u0026awsElasticBlockStoreCSITranslator{}\n}","line":{"from":54,"to":57}} {"id":100030815,"name":"TranslateInTreeStorageClassToCSI","signature":"func (t *awsElasticBlockStoreCSITranslator) TranslateInTreeStorageClassToCSI(sc *storage.StorageClass) (*storage.StorageClass, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/aws_ebs.go","code":"// TranslateInTreeStorageClassToCSI translates InTree EBS storage class parameters to CSI storage class\nfunc (t *awsElasticBlockStoreCSITranslator) TranslateInTreeStorageClassToCSI(sc *storage.StorageClass) (*storage.StorageClass, error) {\n\tvar (\n\t\tgeneratedTopologies []v1.TopologySelectorTerm\n\t\tparams = map[string]string{}\n\t)\n\tfor k, v := range sc.Parameters {\n\t\tswitch strings.ToLower(k) {\n\t\tcase fsTypeKey:\n\t\t\tparams[csiFsTypeKey] = v\n\t\tcase zoneKey:\n\t\t\tgeneratedTopologies = generateToplogySelectors(AWSEBSTopologyKey, []string{v})\n\t\tcase zonesKey:\n\t\t\tgeneratedTopologies = generateToplogySelectors(AWSEBSTopologyKey, strings.Split(v, \",\"))\n\t\tcase iopsPerGBKey:\n\t\t\t// Keep iopsPerGBKey\n\t\t\tparams[k] = v\n\t\t\t// Preserve current in-tree volume plugin behavior and allow the CSI\n\t\t\t// driver to bump volume IOPS when volume size * iopsPerGB is too low.\n\t\t\tparams[allowIncreaseIOPSKey] = \"true\"\n\t\tdefault:\n\t\t\tparams[k] = v\n\t\t}\n\t}\n\n\tif len(generatedTopologies) \u003e 0 \u0026\u0026 len(sc.AllowedTopologies) \u003e 0 {\n\t\treturn nil, fmt.Errorf(\"cannot simultaneously set allowed topologies and zone/zones parameters\")\n\t} else if len(generatedTopologies) \u003e 0 {\n\t\tsc.AllowedTopologies = generatedTopologies\n\t} else if len(sc.AllowedTopologies) \u003e 0 {\n\t\tnewTopologies, err := translateAllowedTopologies(sc.AllowedTopologies, AWSEBSTopologyKey)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed translating allowed topologies: %v\", err)\n\t\t}\n\t\tsc.AllowedTopologies = newTopologies\n\t}\n\n\tsc.Parameters = params\n\n\treturn sc, nil\n}","line":{"from":59,"to":99}} {"id":100030816,"name":"TranslateInTreeInlineVolumeToCSI","signature":"func (t *awsElasticBlockStoreCSITranslator) TranslateInTreeInlineVolumeToCSI(volume *v1.Volume, podNamespace string) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/aws_ebs.go","code":"// TranslateInTreeInlineVolumeToCSI takes a Volume with AWSElasticBlockStore set from in-tree\n// and converts the AWSElasticBlockStore source to a CSIPersistentVolumeSource\nfunc (t *awsElasticBlockStoreCSITranslator) TranslateInTreeInlineVolumeToCSI(volume *v1.Volume, podNamespace string) (*v1.PersistentVolume, error) {\n\tif volume == nil || volume.AWSElasticBlockStore == nil {\n\t\treturn nil, fmt.Errorf(\"volume is nil or AWS EBS not defined on volume\")\n\t}\n\tebsSource := volume.AWSElasticBlockStore\n\tvolumeHandle, err := KubernetesVolumeIDToEBSVolumeID(ebsSource.VolumeID)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to translate Kubernetes ID to EBS Volume ID %v\", err)\n\t}\n\tpv := \u0026v1.PersistentVolume{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t// Must be unique per disk as it is used as the unique part of the\n\t\t\t// staging path\n\t\t\tName: fmt.Sprintf(\"%s-%s\", AWSEBSDriverName, volumeHandle),\n\t\t},\n\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\tPersistentVolumeSource: v1.PersistentVolumeSource{\n\t\t\t\tCSI: \u0026v1.CSIPersistentVolumeSource{\n\t\t\t\t\tDriver: AWSEBSDriverName,\n\t\t\t\t\tVolumeHandle: volumeHandle,\n\t\t\t\t\tReadOnly: ebsSource.ReadOnly,\n\t\t\t\t\tFSType: ebsSource.FSType,\n\t\t\t\t\tVolumeAttributes: map[string]string{\n\t\t\t\t\t\t\"partition\": strconv.FormatInt(int64(ebsSource.Partition), 10),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tAccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce},\n\t\t},\n\t}\n\treturn pv, nil\n}","line":{"from":101,"to":134}} {"id":100030817,"name":"TranslateInTreePVToCSI","signature":"func (t *awsElasticBlockStoreCSITranslator) TranslateInTreePVToCSI(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/aws_ebs.go","code":"// TranslateInTreePVToCSI takes a PV with AWSElasticBlockStore set from in-tree\n// and converts the AWSElasticBlockStore source to a CSIPersistentVolumeSource\nfunc (t *awsElasticBlockStoreCSITranslator) TranslateInTreePVToCSI(pv *v1.PersistentVolume) (*v1.PersistentVolume, error) {\n\tif pv == nil || pv.Spec.AWSElasticBlockStore == nil {\n\t\treturn nil, fmt.Errorf(\"pv is nil or AWS EBS not defined on pv\")\n\t}\n\n\tebsSource := pv.Spec.AWSElasticBlockStore\n\n\tvolumeHandle, err := KubernetesVolumeIDToEBSVolumeID(ebsSource.VolumeID)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to translate Kubernetes ID to EBS Volume ID %v\", err)\n\t}\n\n\tcsiSource := \u0026v1.CSIPersistentVolumeSource{\n\t\tDriver: AWSEBSDriverName,\n\t\tVolumeHandle: volumeHandle,\n\t\tReadOnly: ebsSource.ReadOnly,\n\t\tFSType: ebsSource.FSType,\n\t\tVolumeAttributes: map[string]string{\n\t\t\t\"partition\": strconv.FormatInt(int64(ebsSource.Partition), 10),\n\t\t},\n\t}\n\n\tif err := translateTopologyFromInTreeToCSI(pv, AWSEBSTopologyKey); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to translate topology: %v\", err)\n\t}\n\n\tpv.Spec.AWSElasticBlockStore = nil\n\tpv.Spec.CSI = csiSource\n\treturn pv, nil\n}","line":{"from":136,"to":167}} {"id":100030818,"name":"TranslateCSIPVToInTree","signature":"func (t *awsElasticBlockStoreCSITranslator) TranslateCSIPVToInTree(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/aws_ebs.go","code":"// TranslateCSIPVToInTree takes a PV with CSIPersistentVolumeSource set and\n// translates the EBS CSI source to a AWSElasticBlockStore source.\nfunc (t *awsElasticBlockStoreCSITranslator) TranslateCSIPVToInTree(pv *v1.PersistentVolume) (*v1.PersistentVolume, error) {\n\tif pv == nil || pv.Spec.CSI == nil {\n\t\treturn nil, fmt.Errorf(\"pv is nil or CSI source not defined on pv\")\n\t}\n\n\tcsiSource := pv.Spec.CSI\n\n\tebsSource := \u0026v1.AWSElasticBlockStoreVolumeSource{\n\t\tVolumeID: csiSource.VolumeHandle,\n\t\tFSType: csiSource.FSType,\n\t\tReadOnly: csiSource.ReadOnly,\n\t}\n\n\tif partition, ok := csiSource.VolumeAttributes[\"partition\"]; ok {\n\t\tpartValue, err := strconv.Atoi(partition)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to convert partition %v to integer: %v\", partition, err)\n\t\t}\n\t\tebsSource.Partition = int32(partValue)\n\t}\n\n\t// translate CSI topology to In-tree topology for rollback compatibility\n\tif err := translateTopologyFromCSIToInTree(pv, AWSEBSTopologyKey, getAwsRegionFromZones); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to translate topology. PV:%+v. Error:%v\", *pv, err)\n\t}\n\n\tpv.Spec.CSI = nil\n\tpv.Spec.AWSElasticBlockStore = ebsSource\n\treturn pv, nil\n}","line":{"from":169,"to":200}} {"id":100030819,"name":"CanSupport","signature":"func (t *awsElasticBlockStoreCSITranslator) CanSupport(pv *v1.PersistentVolume) bool","file":"staging/src/k8s.io/csi-translation-lib/plugins/aws_ebs.go","code":"// CanSupport tests whether the plugin supports a given persistent volume\n// specification from the API. The spec pointer should be considered\n// const.\nfunc (t *awsElasticBlockStoreCSITranslator) CanSupport(pv *v1.PersistentVolume) bool {\n\treturn pv != nil \u0026\u0026 pv.Spec.AWSElasticBlockStore != nil\n}","line":{"from":202,"to":207}} {"id":100030820,"name":"CanSupportInline","signature":"func (t *awsElasticBlockStoreCSITranslator) CanSupportInline(volume *v1.Volume) bool","file":"staging/src/k8s.io/csi-translation-lib/plugins/aws_ebs.go","code":"// CanSupportInline tests whether the plugin supports a given inline volume\n// specification from the API. The spec pointer should be considered\n// const.\nfunc (t *awsElasticBlockStoreCSITranslator) CanSupportInline(volume *v1.Volume) bool {\n\treturn volume != nil \u0026\u0026 volume.AWSElasticBlockStore != nil\n}","line":{"from":209,"to":214}} {"id":100030821,"name":"GetInTreePluginName","signature":"func (t *awsElasticBlockStoreCSITranslator) GetInTreePluginName() string","file":"staging/src/k8s.io/csi-translation-lib/plugins/aws_ebs.go","code":"// GetInTreePluginName returns the name of the intree plugin driver\nfunc (t *awsElasticBlockStoreCSITranslator) GetInTreePluginName() string {\n\treturn AWSEBSInTreePluginName\n}","line":{"from":216,"to":219}} {"id":100030822,"name":"GetCSIPluginName","signature":"func (t *awsElasticBlockStoreCSITranslator) GetCSIPluginName() string","file":"staging/src/k8s.io/csi-translation-lib/plugins/aws_ebs.go","code":"// GetCSIPluginName returns the name of the CSI plugin\nfunc (t *awsElasticBlockStoreCSITranslator) GetCSIPluginName() string {\n\treturn AWSEBSDriverName\n}","line":{"from":221,"to":224}} {"id":100030823,"name":"RepairVolumeHandle","signature":"func (t *awsElasticBlockStoreCSITranslator) RepairVolumeHandle(volumeHandle, nodeID string) (string, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/aws_ebs.go","code":"func (t *awsElasticBlockStoreCSITranslator) RepairVolumeHandle(volumeHandle, nodeID string) (string, error) {\n\treturn volumeHandle, nil\n}","line":{"from":226,"to":228}} {"id":100030824,"name":"KubernetesVolumeIDToEBSVolumeID","signature":"func KubernetesVolumeIDToEBSVolumeID(kubernetesID string) (string, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/aws_ebs.go","code":"// KubernetesVolumeIDToEBSVolumeID translates Kubernetes volume ID to EBS volume ID\n// KubernetesVolumeID forms:\n// - aws://\u003czone\u003e/\u003cawsVolumeId\u003e\n// - aws:///\u003cawsVolumeId\u003e\n// - \u003cawsVolumeId\u003e\n//\n// EBS Volume ID form:\n// - vol-\u003calphanumberic\u003e\n//\n// This translation shouldn't be needed and should be fixed in long run\n// See https://github.com/kubernetes/kubernetes/issues/73730\nfunc KubernetesVolumeIDToEBSVolumeID(kubernetesID string) (string, error) {\n\t// name looks like aws://availability-zone/awsVolumeId\n\n\t// The original idea of the URL-style name was to put the AZ into the\n\t// host, so we could find the AZ immediately from the name without\n\t// querying the API. But it turns out we don't actually need it for\n\t// multi-AZ clusters, as we put the AZ into the labels on the PV instead.\n\t// However, if in future we want to support multi-AZ cluster\n\t// volume-awareness without using PersistentVolumes, we likely will\n\t// want the AZ in the host.\n\tif !strings.HasPrefix(kubernetesID, \"aws://\") {\n\t\t// Assume a bare aws volume id (vol-1234...)\n\t\treturn kubernetesID, nil\n\t}\n\turl, err := url.Parse(kubernetesID)\n\tif err != nil {\n\t\t// TODO: Maybe we should pass a URL into the Volume functions\n\t\treturn \"\", fmt.Errorf(\"Invalid disk name (%s): %v\", kubernetesID, err)\n\t}\n\tif url.Scheme != \"aws\" {\n\t\treturn \"\", fmt.Errorf(\"Invalid scheme for AWS volume (%s)\", kubernetesID)\n\t}\n\n\tawsID := url.Path\n\tawsID = strings.Trim(awsID, \"/\")\n\n\t// We sanity check the resulting volume; the two known formats are\n\t// vol-12345678 and vol-12345678abcdef01\n\tif !awsVolumeRegMatch.MatchString(awsID) {\n\t\treturn \"\", fmt.Errorf(\"Invalid format for AWS volume (%s)\", kubernetesID)\n\t}\n\n\treturn awsID, nil\n}","line":{"from":233,"to":277}} {"id":100030825,"name":"getAwsRegionFromZones","signature":"func getAwsRegionFromZones(zones []string) (string, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/aws_ebs.go","code":"func getAwsRegionFromZones(zones []string) (string, error) {\n\tregions := sets.String{}\n\tif len(zones) \u003c 1 {\n\t\treturn \"\", fmt.Errorf(\"no zones specified\")\n\t}\n\n\t// AWS zones can be in four forms:\n\t// us-west-2a, us-gov-east-1a, us-west-2-lax-1a (local zone) and us-east-1-wl1-bos-wlz-1 (wavelength).\n\tfor _, zone := range zones {\n\t\tsplitZone := strings.Split(zone, \"-\")\n\t\tif (len(splitZone) == 3 || len(splitZone) == 4) \u0026\u0026 len(splitZone[len(splitZone)-1]) == 2 {\n\t\t\t// this would break if we ever have a location with more than 9 regions, ie us-west-10.\n\t\t\tsplitZone[len(splitZone)-1] = splitZone[len(splitZone)-1][:1]\n\t\t\tregions.Insert(strings.Join(splitZone, \"-\"))\n\t\t} else if len(splitZone) == 5 || len(splitZone) == 7 {\n\t\t\t// local zone or wavelength\n\t\t\tregions.Insert(strings.Join(splitZone[:3], \"-\"))\n\t\t} else {\n\t\t\treturn \"\", fmt.Errorf(\"Unexpected zone format: %v is not a valid AWS zone\", zone)\n\t\t}\n\t}\n\tif regions.Len() != 1 {\n\t\treturn \"\", fmt.Errorf(\"multiple or no regions gotten from zones, got: %v\", regions)\n\t}\n\treturn regions.UnsortedList()[0], nil\n}","line":{"from":279,"to":304}} {"id":100030826,"name":"NewAzureDiskCSITranslator","signature":"func NewAzureDiskCSITranslator() InTreePlugin","file":"staging/src/k8s.io/csi-translation-lib/plugins/azure_disk.go","code":"// NewAzureDiskCSITranslator returns a new instance of azureDiskTranslator\nfunc NewAzureDiskCSITranslator() InTreePlugin {\n\treturn \u0026azureDiskCSITranslator{}\n}","line":{"from":57,"to":60}} {"id":100030827,"name":"TranslateInTreeStorageClassToCSI","signature":"func (t *azureDiskCSITranslator) TranslateInTreeStorageClassToCSI(sc *storage.StorageClass) (*storage.StorageClass, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/azure_disk.go","code":"// TranslateInTreeStorageClassToCSI translates InTree Azure Disk storage class parameters to CSI storage class\nfunc (t *azureDiskCSITranslator) TranslateInTreeStorageClassToCSI(sc *storage.StorageClass) (*storage.StorageClass, error) {\n\tvar (\n\t\tgeneratedTopologies []v1.TopologySelectorTerm\n\t\tparams = map[string]string{}\n\t)\n\tfor k, v := range sc.Parameters {\n\t\tswitch strings.ToLower(k) {\n\t\tcase zoneKey:\n\t\t\tgeneratedTopologies = generateToplogySelectors(AzureDiskTopologyKey, []string{v})\n\t\tcase zonesKey:\n\t\t\tgeneratedTopologies = generateToplogySelectors(AzureDiskTopologyKey, strings.Split(v, \",\"))\n\t\tdefault:\n\t\t\tparams[k] = v\n\t\t}\n\t}\n\n\tif len(generatedTopologies) \u003e 0 \u0026\u0026 len(sc.AllowedTopologies) \u003e 0 {\n\t\treturn nil, fmt.Errorf(\"cannot simultaneously set allowed topologies and zone/zones parameters\")\n\t} else if len(generatedTopologies) \u003e 0 {\n\t\tsc.AllowedTopologies = generatedTopologies\n\t} else if len(sc.AllowedTopologies) \u003e 0 {\n\t\tnewTopologies, err := translateAllowedTopologies(sc.AllowedTopologies, AzureDiskTopologyKey)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed translating allowed topologies: %v\", err)\n\t\t}\n\t\tsc.AllowedTopologies = newTopologies\n\t}\n\tsc.AllowedTopologies = t.replaceFailureDomainsToCSI(sc.AllowedTopologies)\n\n\tsc.Parameters = params\n\n\treturn sc, nil\n}","line":{"from":62,"to":95}} {"id":100030828,"name":"TranslateInTreeInlineVolumeToCSI","signature":"func (t *azureDiskCSITranslator) TranslateInTreeInlineVolumeToCSI(volume *v1.Volume, podNamespace string) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/azure_disk.go","code":"// TranslateInTreeInlineVolumeToCSI takes a Volume with AzureDisk set from in-tree\n// and converts the AzureDisk source to a CSIPersistentVolumeSource\nfunc (t *azureDiskCSITranslator) TranslateInTreeInlineVolumeToCSI(volume *v1.Volume, podNamespace string) (*v1.PersistentVolume, error) {\n\tif volume == nil || volume.AzureDisk == nil {\n\t\treturn nil, fmt.Errorf(\"volume is nil or Azure Disk not defined on volume\")\n\t}\n\n\tazureSource := volume.AzureDisk\n\tif azureSource.Kind != nil \u0026\u0026 !strings.EqualFold(string(*azureSource.Kind), managed) {\n\t\treturn nil, fmt.Errorf(\"kind(%v) is not supported in csi migration\", *azureSource.Kind)\n\t}\n\tpv := \u0026v1.PersistentVolume{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t// Must be unique per disk as it is used as the unique part of the\n\t\t\t// staging path\n\t\t\tName: azureSource.DataDiskURI,\n\t\t},\n\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\tPersistentVolumeSource: v1.PersistentVolumeSource{\n\t\t\t\tCSI: \u0026v1.CSIPersistentVolumeSource{\n\t\t\t\t\tDriver: AzureDiskDriverName,\n\t\t\t\t\tVolumeHandle: azureSource.DataDiskURI,\n\t\t\t\t\tVolumeAttributes: map[string]string{azureDiskKind: managed},\n\t\t\t\t},\n\t\t\t},\n\t\t\tAccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce},\n\t\t},\n\t}\n\tif azureSource.ReadOnly != nil {\n\t\tpv.Spec.PersistentVolumeSource.CSI.ReadOnly = *azureSource.ReadOnly\n\t}\n\n\tif azureSource.CachingMode != nil \u0026\u0026 *azureSource.CachingMode != \"\" {\n\t\tpv.Spec.PersistentVolumeSource.CSI.VolumeAttributes[azureDiskCachingMode] = string(*azureSource.CachingMode)\n\t}\n\tif azureSource.FSType != nil {\n\t\tpv.Spec.PersistentVolumeSource.CSI.FSType = *azureSource.FSType\n\t\tpv.Spec.PersistentVolumeSource.CSI.VolumeAttributes[azureDiskFSType] = *azureSource.FSType\n\t}\n\tpv.Spec.PersistentVolumeSource.CSI.VolumeAttributes[azureDiskKind] = managed\n\n\treturn pv, nil\n}","line":{"from":97,"to":139}} {"id":100030829,"name":"TranslateInTreePVToCSI","signature":"func (t *azureDiskCSITranslator) TranslateInTreePVToCSI(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/azure_disk.go","code":"// TranslateInTreePVToCSI takes a PV with AzureDisk set from in-tree\n// and converts the AzureDisk source to a CSIPersistentVolumeSource\nfunc (t *azureDiskCSITranslator) TranslateInTreePVToCSI(pv *v1.PersistentVolume) (*v1.PersistentVolume, error) {\n\tif pv == nil || pv.Spec.AzureDisk == nil {\n\t\treturn nil, fmt.Errorf(\"pv is nil or Azure Disk source not defined on pv\")\n\t}\n\n\tvar (\n\t\tazureSource = pv.Spec.PersistentVolumeSource.AzureDisk\n\n\t\t// refer to https://github.com/kubernetes-sigs/azuredisk-csi-driver/blob/master/docs/driver-parameters.md\n\t\tcsiSource = \u0026v1.CSIPersistentVolumeSource{\n\t\t\tDriver: AzureDiskDriverName,\n\t\t\tVolumeAttributes: map[string]string{azureDiskKind: managed},\n\t\t\tVolumeHandle: azureSource.DataDiskURI,\n\t\t}\n\t)\n\n\tif azureSource.Kind != nil \u0026\u0026 !strings.EqualFold(string(*azureSource.Kind), managed) {\n\t\treturn nil, fmt.Errorf(\"kind(%v) is not supported in csi migration\", *azureSource.Kind)\n\t}\n\n\tif azureSource.CachingMode != nil {\n\t\tcsiSource.VolumeAttributes[azureDiskCachingMode] = string(*azureSource.CachingMode)\n\t}\n\n\tif azureSource.FSType != nil {\n\t\tcsiSource.FSType = *azureSource.FSType\n\t\tcsiSource.VolumeAttributes[azureDiskFSType] = *azureSource.FSType\n\t}\n\tcsiSource.VolumeAttributes[azureDiskKind] = managed\n\n\tif azureSource.ReadOnly != nil {\n\t\tcsiSource.ReadOnly = *azureSource.ReadOnly\n\t}\n\n\tpv.Spec.PersistentVolumeSource.AzureDisk = nil\n\tpv.Spec.PersistentVolumeSource.CSI = csiSource\n\n\treturn pv, nil\n}","line":{"from":141,"to":181}} {"id":100030830,"name":"TranslateCSIPVToInTree","signature":"func (t *azureDiskCSITranslator) TranslateCSIPVToInTree(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/azure_disk.go","code":"// TranslateCSIPVToInTree takes a PV with CSIPersistentVolumeSource set and\n// translates the Azure Disk CSI source to a AzureDisk source.\nfunc (t *azureDiskCSITranslator) TranslateCSIPVToInTree(pv *v1.PersistentVolume) (*v1.PersistentVolume, error) {\n\tif pv == nil || pv.Spec.CSI == nil {\n\t\treturn nil, fmt.Errorf(\"pv is nil or CSI source not defined on pv\")\n\t}\n\tcsiSource := pv.Spec.CSI\n\n\tdiskURI := csiSource.VolumeHandle\n\tdiskName, err := getDiskName(diskURI)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// refer to https://github.com/kubernetes-sigs/azuredisk-csi-driver/blob/master/docs/driver-parameters.md\n\tmanaged := v1.AzureManagedDisk\n\tazureSource := \u0026v1.AzureDiskVolumeSource{\n\t\tDiskName: diskName,\n\t\tDataDiskURI: diskURI,\n\t\tFSType: \u0026csiSource.FSType,\n\t\tReadOnly: \u0026csiSource.ReadOnly,\n\t\tKind: \u0026managed,\n\t}\n\n\tif csiSource.VolumeAttributes != nil {\n\t\tfor k, v := range csiSource.VolumeAttributes {\n\t\t\tswitch strings.ToLower(k) {\n\t\t\tcase azureDiskCachingMode:\n\t\t\t\tif v != \"\" {\n\t\t\t\t\tmode := v1.AzureDataDiskCachingMode(v)\n\t\t\t\t\tazureSource.CachingMode = \u0026mode\n\t\t\t\t}\n\t\t\tcase azureDiskFSType:\n\t\t\t\tif v != \"\" {\n\t\t\t\t\tfsType := v\n\t\t\t\t\tazureSource.FSType = \u0026fsType\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tazureSource.Kind = \u0026managed\n\t}\n\n\tpv.Spec.CSI = nil\n\tpv.Spec.AzureDisk = azureSource\n\n\treturn pv, nil\n}","line":{"from":183,"to":229}} {"id":100030831,"name":"CanSupport","signature":"func (t *azureDiskCSITranslator) CanSupport(pv *v1.PersistentVolume) bool","file":"staging/src/k8s.io/csi-translation-lib/plugins/azure_disk.go","code":"// CanSupport tests whether the plugin supports a given volume\n// specification from the API. The spec pointer should be considered\n// const.\nfunc (t *azureDiskCSITranslator) CanSupport(pv *v1.PersistentVolume) bool {\n\treturn pv != nil \u0026\u0026 pv.Spec.AzureDisk != nil\n}","line":{"from":231,"to":236}} {"id":100030832,"name":"CanSupportInline","signature":"func (t *azureDiskCSITranslator) CanSupportInline(volume *v1.Volume) bool","file":"staging/src/k8s.io/csi-translation-lib/plugins/azure_disk.go","code":"// CanSupportInline tests whether the plugin supports a given inline volume\n// specification from the API. The spec pointer should be considered\n// const.\nfunc (t *azureDiskCSITranslator) CanSupportInline(volume *v1.Volume) bool {\n\treturn volume != nil \u0026\u0026 volume.AzureDisk != nil\n}","line":{"from":238,"to":243}} {"id":100030833,"name":"GetInTreePluginName","signature":"func (t *azureDiskCSITranslator) GetInTreePluginName() string","file":"staging/src/k8s.io/csi-translation-lib/plugins/azure_disk.go","code":"// GetInTreePluginName returns the name of the intree plugin driver\nfunc (t *azureDiskCSITranslator) GetInTreePluginName() string {\n\treturn AzureDiskInTreePluginName\n}","line":{"from":245,"to":248}} {"id":100030834,"name":"GetCSIPluginName","signature":"func (t *azureDiskCSITranslator) GetCSIPluginName() string","file":"staging/src/k8s.io/csi-translation-lib/plugins/azure_disk.go","code":"// GetCSIPluginName returns the name of the CSI plugin\nfunc (t *azureDiskCSITranslator) GetCSIPluginName() string {\n\treturn AzureDiskDriverName\n}","line":{"from":250,"to":253}} {"id":100030835,"name":"RepairVolumeHandle","signature":"func (t *azureDiskCSITranslator) RepairVolumeHandle(volumeHandle, nodeID string) (string, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/azure_disk.go","code":"func (t *azureDiskCSITranslator) RepairVolumeHandle(volumeHandle, nodeID string) (string, error) {\n\treturn volumeHandle, nil\n}","line":{"from":255,"to":257}} {"id":100030836,"name":"isManagedDisk","signature":"func isManagedDisk(diskURI string) bool","file":"staging/src/k8s.io/csi-translation-lib/plugins/azure_disk.go","code":"func isManagedDisk(diskURI string) bool {\n\tif len(diskURI) \u003e 4 \u0026\u0026 strings.ToLower(diskURI[:4]) == \"http\" {\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":259,"to":264}} {"id":100030837,"name":"getDiskName","signature":"func getDiskName(diskURI string) (string, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/azure_disk.go","code":"func getDiskName(diskURI string) (string, error) {\n\tdiskPathRE := managedDiskPathRE\n\tif !isManagedDisk(diskURI) {\n\t\tdiskPathRE = unmanagedDiskPathRE\n\t}\n\n\tmatches := diskPathRE.FindStringSubmatch(diskURI)\n\tif len(matches) != 2 {\n\t\treturn \"\", fmt.Errorf(\"could not get disk name from %s, correct format: %s\", diskURI, diskPathRE)\n\t}\n\treturn matches[1], nil\n}","line":{"from":266,"to":277}} {"id":100030838,"name":"replaceFailureDomainsToCSI","signature":"func (t *azureDiskCSITranslator) replaceFailureDomainsToCSI(terms []v1.TopologySelectorTerm) []v1.TopologySelectorTerm","file":"staging/src/k8s.io/csi-translation-lib/plugins/azure_disk.go","code":"// Replace topology values for failure domains (\"\u003cnumber\u003e\") to \"\",\n// as it's the value that the CSI driver expects.\nfunc (t *azureDiskCSITranslator) replaceFailureDomainsToCSI(terms []v1.TopologySelectorTerm) []v1.TopologySelectorTerm {\n\tif terms == nil {\n\t\treturn nil\n\t}\n\n\tnewTopologies := []v1.TopologySelectorTerm{}\n\tfor _, term := range terms {\n\t\tnewTerm := term.DeepCopy()\n\t\tfor i := range newTerm.MatchLabelExpressions {\n\t\t\texp := \u0026newTerm.MatchLabelExpressions[i]\n\t\t\tif exp.Key == AzureDiskTopologyKey {\n\t\t\t\tfor j := range exp.Values {\n\t\t\t\t\tif unzonedCSIRegionRE.Match([]byte(exp.Values[j])) {\n\t\t\t\t\t\t// Topologies \"0\", \"1\" etc are used when in-tree topology is translated to CSI in Azure\n\t\t\t\t\t\t// regions that don't have availability zones. E.g.:\n\t\t\t\t\t\t// topology.kubernetes.io/region: westus\n\t\t\t\t\t\t// topology.kubernetes.io/zone: \"0\"\n\t\t\t\t\t\t// The CSI driver uses zone \"\" instead of \"0\" in this case.\n\t\t\t\t\t\t// topology.disk.csi.azure.com/zone\": \"\"\n\t\t\t\t\t\texp.Values[j] = \"\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tnewTopologies = append(newTopologies, *newTerm)\n\t}\n\treturn newTopologies\n}","line":{"from":279,"to":308}} {"id":100030839,"name":"NewAzureFileCSITranslator","signature":"func NewAzureFileCSITranslator() InTreePlugin","file":"staging/src/k8s.io/csi-translation-lib/plugins/azure_file.go","code":"// NewAzureFileCSITranslator returns a new instance of azureFileTranslator\nfunc NewAzureFileCSITranslator() InTreePlugin {\n\treturn \u0026azureFileCSITranslator{}\n}","line":{"from":56,"to":59}} {"id":100030840,"name":"TranslateInTreeStorageClassToCSI","signature":"func (t *azureFileCSITranslator) TranslateInTreeStorageClassToCSI(sc *storage.StorageClass) (*storage.StorageClass, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/azure_file.go","code":"// TranslateInTreeStorageClassToCSI translates InTree Azure File storage class parameters to CSI storage class\nfunc (t *azureFileCSITranslator) TranslateInTreeStorageClassToCSI(sc *storage.StorageClass) (*storage.StorageClass, error) {\n\treturn sc, nil\n}","line":{"from":61,"to":64}} {"id":100030841,"name":"TranslateInTreeInlineVolumeToCSI","signature":"func (t *azureFileCSITranslator) TranslateInTreeInlineVolumeToCSI(volume *v1.Volume, podNamespace string) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/azure_file.go","code":"// TranslateInTreeInlineVolumeToCSI takes a Volume with AzureFile set from in-tree\n// and converts the AzureFile source to a CSIPersistentVolumeSource\nfunc (t *azureFileCSITranslator) TranslateInTreeInlineVolumeToCSI(volume *v1.Volume, podNamespace string) (*v1.PersistentVolume, error) {\n\tif volume == nil || volume.AzureFile == nil {\n\t\treturn nil, fmt.Errorf(\"volume is nil or Azure File not defined on volume\")\n\t}\n\n\tazureSource := volume.AzureFile\n\taccountName, err := getStorageAccountName(azureSource.SecretName)\n\tif err != nil {\n\t\tklog.Warningf(\"getStorageAccountName(%s) returned with error: %v\", azureSource.SecretName, err)\n\t\taccountName = azureSource.SecretName\n\t}\n\n\tsecretNamespace := defaultSecretNamespace\n\tif podNamespace != \"\" {\n\t\tsecretNamespace = podNamespace\n\t}\n\tvolumeID := fmt.Sprintf(volumeIDTemplate, \"\", accountName, azureSource.ShareName, volume.Name, secretNamespace)\n\n\tvar (\n\t\tpv = \u0026v1.PersistentVolume{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t// Must be unique as it is used as the unique part of the staging path\n\t\t\t\tName: volumeID,\n\t\t\t},\n\t\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\t\tPersistentVolumeSource: v1.PersistentVolumeSource{\n\t\t\t\t\tCSI: \u0026v1.CSIPersistentVolumeSource{\n\t\t\t\t\t\tDriver: AzureFileDriverName,\n\t\t\t\t\t\tVolumeHandle: volumeID,\n\t\t\t\t\t\tReadOnly: azureSource.ReadOnly,\n\t\t\t\t\t\tVolumeAttributes: map[string]string{shareNameField: azureSource.ShareName},\n\t\t\t\t\t\tNodeStageSecretRef: \u0026v1.SecretReference{\n\t\t\t\t\t\t\tName: azureSource.SecretName,\n\t\t\t\t\t\t\tNamespace: secretNamespace,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tAccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteMany},\n\t\t\t},\n\t\t}\n\t)\n\n\treturn pv, nil\n}","line":{"from":66,"to":111}} {"id":100030842,"name":"TranslateInTreePVToCSI","signature":"func (t *azureFileCSITranslator) TranslateInTreePVToCSI(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/azure_file.go","code":"// TranslateInTreePVToCSI takes a PV with AzureFile set from in-tree\n// and converts the AzureFile source to a CSIPersistentVolumeSource\nfunc (t *azureFileCSITranslator) TranslateInTreePVToCSI(pv *v1.PersistentVolume) (*v1.PersistentVolume, error) {\n\tif pv == nil || pv.Spec.AzureFile == nil {\n\t\treturn nil, fmt.Errorf(\"pv is nil or Azure File source not defined on pv\")\n\t}\n\n\tazureSource := pv.Spec.PersistentVolumeSource.AzureFile\n\taccountName, err := getStorageAccountName(azureSource.SecretName)\n\tif err != nil {\n\t\tklog.Warningf(\"getStorageAccountName(%s) returned with error: %v\", azureSource.SecretName, err)\n\t\taccountName = azureSource.SecretName\n\t}\n\tresourceGroup := \"\"\n\tif pv.ObjectMeta.Annotations != nil {\n\t\tif v, ok := pv.ObjectMeta.Annotations[resourceGroupAnnotation]; ok {\n\t\t\tresourceGroup = v\n\t\t}\n\t}\n\n\t// Secret is required when mounting a volume but pod presence cannot be assumed - we should not try to read pod now.\n\tnamespace := \"\"\n\t// Try to read SecretNamespace from source pv.\n\tif azureSource.SecretNamespace != nil {\n\t\tnamespace = *azureSource.SecretNamespace\n\t} else {\n\t\t// Try to read namespace from ClaimRef which should be always present.\n\t\tif pv.Spec.ClaimRef != nil {\n\t\t\tnamespace = pv.Spec.ClaimRef.Namespace\n\t\t}\n\t}\n\n\tif len(namespace) == 0 {\n\t\treturn nil, fmt.Errorf(\"could not find a secret namespace in PersistentVolumeSource or ClaimRef\")\n\t}\n\n\tvolumeID := fmt.Sprintf(volumeIDTemplate, resourceGroup, accountName, azureSource.ShareName, pv.ObjectMeta.Name, namespace)\n\n\tvar (\n\t\t// refer to https://github.com/kubernetes-sigs/azurefile-csi-driver/blob/master/docs/driver-parameters.md\n\t\tcsiSource = \u0026v1.CSIPersistentVolumeSource{\n\t\t\tDriver: AzureFileDriverName,\n\t\t\tNodeStageSecretRef: \u0026v1.SecretReference{\n\t\t\t\tName: azureSource.SecretName,\n\t\t\t\tNamespace: namespace,\n\t\t\t},\n\t\t\tReadOnly: azureSource.ReadOnly,\n\t\t\tVolumeAttributes: map[string]string{shareNameField: azureSource.ShareName},\n\t\t\tVolumeHandle: volumeID,\n\t\t}\n\t)\n\n\tpv.Spec.PersistentVolumeSource.AzureFile = nil\n\tpv.Spec.PersistentVolumeSource.CSI = csiSource\n\n\treturn pv, nil\n}","line":{"from":113,"to":169}} {"id":100030843,"name":"TranslateCSIPVToInTree","signature":"func (t *azureFileCSITranslator) TranslateCSIPVToInTree(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/azure_file.go","code":"// TranslateCSIPVToInTree takes a PV with CSIPersistentVolumeSource set and\n// translates the Azure File CSI source to a AzureFile source.\nfunc (t *azureFileCSITranslator) TranslateCSIPVToInTree(pv *v1.PersistentVolume) (*v1.PersistentVolume, error) {\n\tif pv == nil || pv.Spec.CSI == nil {\n\t\treturn nil, fmt.Errorf(\"pv is nil or CSI source not defined on pv\")\n\t}\n\tcsiSource := pv.Spec.CSI\n\n\t// refer to https://github.com/kubernetes-sigs/azurefile-csi-driver/blob/master/docs/driver-parameters.md\n\tazureSource := \u0026v1.AzureFilePersistentVolumeSource{\n\t\tReadOnly: csiSource.ReadOnly,\n\t}\n\n\tfor k, v := range csiSource.VolumeAttributes {\n\t\tswitch strings.ToLower(k) {\n\t\tcase shareNameField:\n\t\t\tazureSource.ShareName = v\n\t\tcase secretNameField:\n\t\t\tazureSource.SecretName = v\n\t\tcase secretNamespaceField:\n\t\t\tns := v\n\t\t\tazureSource.SecretNamespace = \u0026ns\n\t\t}\n\t}\n\n\tresourceGroup := \"\"\n\tif csiSource.NodeStageSecretRef != nil \u0026\u0026 csiSource.NodeStageSecretRef.Name != \"\" {\n\t\tazureSource.SecretName = csiSource.NodeStageSecretRef.Name\n\t\tazureSource.SecretNamespace = \u0026csiSource.NodeStageSecretRef.Namespace\n\t}\n\tif azureSource.ShareName == \"\" || azureSource.SecretName == \"\" {\n\t\trg, storageAccount, fileShareName, _, err := getFileShareInfo(csiSource.VolumeHandle)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif azureSource.ShareName == \"\" {\n\t\t\tazureSource.ShareName = fileShareName\n\t\t}\n\t\tif azureSource.SecretName == \"\" {\n\t\t\tazureSource.SecretName = fmt.Sprintf(secretNameTemplate, storageAccount)\n\t\t}\n\t\tresourceGroup = rg\n\t}\n\n\tif azureSource.SecretNamespace == nil {\n\t\tns := defaultSecretNamespace\n\t\tazureSource.SecretNamespace = \u0026ns\n\t}\n\n\tpv.Spec.CSI = nil\n\tpv.Spec.AzureFile = azureSource\n\tif pv.ObjectMeta.Annotations == nil {\n\t\tpv.ObjectMeta.Annotations = map[string]string{}\n\t}\n\tif resourceGroup != \"\" {\n\t\tpv.ObjectMeta.Annotations[resourceGroupAnnotation] = resourceGroup\n\t}\n\n\treturn pv, nil\n}","line":{"from":171,"to":230}} {"id":100030844,"name":"CanSupport","signature":"func (t *azureFileCSITranslator) CanSupport(pv *v1.PersistentVolume) bool","file":"staging/src/k8s.io/csi-translation-lib/plugins/azure_file.go","code":"// CanSupport tests whether the plugin supports a given volume\n// specification from the API. The spec pointer should be considered\n// const.\nfunc (t *azureFileCSITranslator) CanSupport(pv *v1.PersistentVolume) bool {\n\treturn pv != nil \u0026\u0026 pv.Spec.AzureFile != nil\n}","line":{"from":232,"to":237}} {"id":100030845,"name":"CanSupportInline","signature":"func (t *azureFileCSITranslator) CanSupportInline(volume *v1.Volume) bool","file":"staging/src/k8s.io/csi-translation-lib/plugins/azure_file.go","code":"// CanSupportInline tests whether the plugin supports a given inline volume\n// specification from the API. The spec pointer should be considered\n// const.\nfunc (t *azureFileCSITranslator) CanSupportInline(volume *v1.Volume) bool {\n\treturn volume != nil \u0026\u0026 volume.AzureFile != nil\n}","line":{"from":239,"to":244}} {"id":100030846,"name":"GetInTreePluginName","signature":"func (t *azureFileCSITranslator) GetInTreePluginName() string","file":"staging/src/k8s.io/csi-translation-lib/plugins/azure_file.go","code":"// GetInTreePluginName returns the name of the intree plugin driver\nfunc (t *azureFileCSITranslator) GetInTreePluginName() string {\n\treturn AzureFileInTreePluginName\n}","line":{"from":246,"to":249}} {"id":100030847,"name":"GetCSIPluginName","signature":"func (t *azureFileCSITranslator) GetCSIPluginName() string","file":"staging/src/k8s.io/csi-translation-lib/plugins/azure_file.go","code":"// GetCSIPluginName returns the name of the CSI plugin\nfunc (t *azureFileCSITranslator) GetCSIPluginName() string {\n\treturn AzureFileDriverName\n}","line":{"from":251,"to":254}} {"id":100030848,"name":"RepairVolumeHandle","signature":"func (t *azureFileCSITranslator) RepairVolumeHandle(volumeHandle, nodeID string) (string, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/azure_file.go","code":"func (t *azureFileCSITranslator) RepairVolumeHandle(volumeHandle, nodeID string) (string, error) {\n\treturn volumeHandle, nil\n}","line":{"from":256,"to":258}} {"id":100030849,"name":"getFileShareInfo","signature":"func getFileShareInfo(id string) (string, string, string, string, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/azure_file.go","code":"// get file share info according to volume id, e.g.\n// input: \"rg#f5713de20cde511e8ba4900#pvc-file-dynamic-17e43f84-f474-11e8-acd0-000d3a00df41#diskname.vhd\"\n// output: rg, f5713de20cde511e8ba4900, pvc-file-dynamic-17e43f84-f474-11e8-acd0-000d3a00df41, diskname.vhd\nfunc getFileShareInfo(id string) (string, string, string, string, error) {\n\tsegments := strings.Split(id, separator)\n\tif len(segments) \u003c 3 {\n\t\treturn \"\", \"\", \"\", \"\", fmt.Errorf(\"error parsing volume id: %q, should at least contain two #\", id)\n\t}\n\tvar diskName string\n\tif len(segments) \u003e 3 {\n\t\tdiskName = segments[3]\n\t}\n\treturn segments[0], segments[1], segments[2], diskName, nil\n}","line":{"from":260,"to":273}} {"id":100030850,"name":"getStorageAccountName","signature":"func getStorageAccountName(secretName string) (string, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/azure_file.go","code":"// get storage account name from secret name\nfunc getStorageAccountName(secretName string) (string, error) {\n\tmatches := secretNameFormatRE.FindStringSubmatch(secretName)\n\tif len(matches) != 2 {\n\t\treturn \"\", fmt.Errorf(\"could not get account name from %s, correct format: %s\", secretName, secretNameFormatRE)\n\t}\n\treturn matches[1], nil\n}","line":{"from":275,"to":282}} {"id":100030851,"name":"NewGCEPersistentDiskCSITranslator","signature":"func NewGCEPersistentDiskCSITranslator() InTreePlugin","file":"staging/src/k8s.io/csi-translation-lib/plugins/gce_pd.go","code":"// NewGCEPersistentDiskCSITranslator returns a new instance of gcePersistentDiskTranslator\nfunc NewGCEPersistentDiskCSITranslator() InTreePlugin {\n\treturn \u0026gcePersistentDiskCSITranslator{}\n}","line":{"from":62,"to":65}} {"id":100030852,"name":"generateToplogySelectors","signature":"func generateToplogySelectors(key string, values []string) []v1.TopologySelectorTerm","file":"staging/src/k8s.io/csi-translation-lib/plugins/gce_pd.go","code":"func generateToplogySelectors(key string, values []string) []v1.TopologySelectorTerm {\n\treturn []v1.TopologySelectorTerm{\n\t\t{\n\t\t\tMatchLabelExpressions: []v1.TopologySelectorLabelRequirement{\n\t\t\t\t{\n\t\t\t\t\tKey: key,\n\t\t\t\t\tValues: values,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":67,"to":78}} {"id":100030853,"name":"TranslateInTreeStorageClassToCSI","signature":"func (g *gcePersistentDiskCSITranslator) TranslateInTreeStorageClassToCSI(sc *storage.StorageClass) (*storage.StorageClass, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/gce_pd.go","code":"// TranslateInTreeStorageClassToCSI translates InTree GCE storage class parameters to CSI storage class\nfunc (g *gcePersistentDiskCSITranslator) TranslateInTreeStorageClassToCSI(sc *storage.StorageClass) (*storage.StorageClass, error) {\n\tvar generatedTopologies []v1.TopologySelectorTerm\n\n\tnp := map[string]string{}\n\tfor k, v := range sc.Parameters {\n\t\tswitch strings.ToLower(k) {\n\t\tcase fsTypeKey:\n\t\t\t// prefixed fstype parameter is stripped out by external provisioner\n\t\t\tnp[csiFsTypeKey] = v\n\t\t// Strip out zone and zones parameters and translate them into topologies instead\n\t\tcase zoneKey:\n\t\t\tgeneratedTopologies = generateToplogySelectors(GCEPDTopologyKey, []string{v})\n\t\tcase zonesKey:\n\t\t\tgeneratedTopologies = generateToplogySelectors(GCEPDTopologyKey, strings.Split(v, \",\"))\n\t\tdefault:\n\t\t\tnp[k] = v\n\t\t}\n\t}\n\n\tif len(generatedTopologies) \u003e 0 \u0026\u0026 len(sc.AllowedTopologies) \u003e 0 {\n\t\treturn nil, fmt.Errorf(\"cannot simultaneously set allowed topologies and zone/zones parameters\")\n\t} else if len(generatedTopologies) \u003e 0 {\n\t\tsc.AllowedTopologies = generatedTopologies\n\t} else if len(sc.AllowedTopologies) \u003e 0 {\n\t\tnewTopologies, err := translateAllowedTopologies(sc.AllowedTopologies, GCEPDTopologyKey)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed translating allowed topologies: %v\", err)\n\t\t}\n\t\tsc.AllowedTopologies = newTopologies\n\t}\n\n\tsc.Parameters = np\n\n\treturn sc, nil\n}","line":{"from":80,"to":115}} {"id":100030854,"name":"backwardCompatibleAccessModes","signature":"func backwardCompatibleAccessModes(ams []v1.PersistentVolumeAccessMode) []v1.PersistentVolumeAccessMode","file":"staging/src/k8s.io/csi-translation-lib/plugins/gce_pd.go","code":"// backwardCompatibleAccessModes translates all instances of ReadWriteMany\n// access mode from the in-tree plugin to ReadWriteOnce. This is because in-tree\n// plugin never supported ReadWriteMany but also did not validate or enforce\n// this access mode for pre-provisioned volumes. The GCE PD CSI Driver validates\n// and enforces (fails) ReadWriteMany. Therefore we treat all in-tree\n// ReadWriteMany as ReadWriteOnce volumes to not break legacy volumes. It also\n// takes [ReadWriteOnce, ReadOnlyMany] and makes it ReadWriteOnce. This is\n// because the in-tree plugin does not enforce access modes and just attaches\n// the disk in ReadWriteOnce mode; however, the CSI external-attacher will fail\n// this combination because technically [ReadWriteOnce, ReadOnlyMany] is not\n// supportable on an attached volume\n// See: https://github.com/kubernetes-csi/external-attacher/issues/153\nfunc backwardCompatibleAccessModes(ams []v1.PersistentVolumeAccessMode) []v1.PersistentVolumeAccessMode {\n\tif ams == nil {\n\t\treturn nil\n\t}\n\n\ts := map[v1.PersistentVolumeAccessMode]bool{}\n\tvar newAM []v1.PersistentVolumeAccessMode\n\n\tfor _, am := range ams {\n\t\tif am == v1.ReadWriteMany {\n\t\t\t// ReadWriteMany is unsupported in CSI, but in-tree did no\n\t\t\t// validation and treated it as ReadWriteOnce\n\t\t\ts[v1.ReadWriteOnce] = true\n\t\t} else {\n\t\t\ts[am] = true\n\t\t}\n\t}\n\n\tswitch {\n\tcase s[v1.ReadOnlyMany] \u0026\u0026 s[v1.ReadWriteOnce]:\n\t\t// ROX,RWO is unsupported in CSI, but in-tree did not validation and\n\t\t// treated it as ReadWriteOnce\n\t\tnewAM = []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}\n\tcase s[v1.ReadWriteOnce]:\n\t\tnewAM = []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}\n\tcase s[v1.ReadOnlyMany]:\n\t\tnewAM = []v1.PersistentVolumeAccessMode{v1.ReadOnlyMany}\n\tdefault:\n\t\tnewAM = []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}\n\t}\n\n\treturn newAM\n}","line":{"from":117,"to":161}} {"id":100030855,"name":"TranslateInTreeInlineVolumeToCSI","signature":"func (g *gcePersistentDiskCSITranslator) TranslateInTreeInlineVolumeToCSI(volume *v1.Volume, podNamespace string) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/gce_pd.go","code":"// TranslateInTreeInlineVolumeToCSI takes a Volume with GCEPersistentDisk set from in-tree\n// and converts the GCEPersistentDisk source to a CSIPersistentVolumeSource\nfunc (g *gcePersistentDiskCSITranslator) TranslateInTreeInlineVolumeToCSI(volume *v1.Volume, podNamespace string) (*v1.PersistentVolume, error) {\n\tif volume == nil || volume.GCEPersistentDisk == nil {\n\t\treturn nil, fmt.Errorf(\"volume is nil or GCE PD not defined on volume\")\n\t}\n\n\tpdSource := volume.GCEPersistentDisk\n\n\tpartition := \"\"\n\tif pdSource.Partition != 0 {\n\t\tpartition = strconv.Itoa(int(pdSource.Partition))\n\t}\n\n\tvar am v1.PersistentVolumeAccessMode\n\tif pdSource.ReadOnly {\n\t\tam = v1.ReadOnlyMany\n\t} else {\n\t\tam = v1.ReadWriteOnce\n\t}\n\n\tfsMode := v1.PersistentVolumeFilesystem\n\treturn \u0026v1.PersistentVolume{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t// Must be unique per disk as it is used as the unique part of the\n\t\t\t// staging path\n\t\t\tName: fmt.Sprintf(\"%s-%s\", GCEPDDriverName, pdSource.PDName),\n\t\t},\n\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\tPersistentVolumeSource: v1.PersistentVolumeSource{\n\t\t\t\tCSI: \u0026v1.CSIPersistentVolumeSource{\n\t\t\t\t\tDriver: GCEPDDriverName,\n\t\t\t\t\tVolumeHandle: fmt.Sprintf(volIDZonalFmt, UnspecifiedValue, UnspecifiedValue, pdSource.PDName),\n\t\t\t\t\tReadOnly: pdSource.ReadOnly,\n\t\t\t\t\tFSType: pdSource.FSType,\n\t\t\t\t\tVolumeAttributes: map[string]string{\n\t\t\t\t\t\t\"partition\": partition,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tAccessModes: []v1.PersistentVolumeAccessMode{am},\n\t\t\tVolumeMode: \u0026fsMode,\n\t\t},\n\t}, nil\n}","line":{"from":163,"to":207}} {"id":100030856,"name":"TranslateInTreePVToCSI","signature":"func (g *gcePersistentDiskCSITranslator) TranslateInTreePVToCSI(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/gce_pd.go","code":"// TranslateInTreePVToCSI takes a PV with GCEPersistentDisk set from in-tree\n// and converts the GCEPersistentDisk source to a CSIPersistentVolumeSource\nfunc (g *gcePersistentDiskCSITranslator) TranslateInTreePVToCSI(pv *v1.PersistentVolume) (*v1.PersistentVolume, error) {\n\tvar volID string\n\n\tif pv == nil || pv.Spec.GCEPersistentDisk == nil {\n\t\treturn nil, fmt.Errorf(\"pv is nil or GCE Persistent Disk source not defined on pv\")\n\t}\n\n\t// depend on which version it migrates from, the label could be failuredomain beta or topology GA version\n\tzonesLabel := pv.Labels[v1.LabelFailureDomainBetaZone]\n\tif zonesLabel == \"\" {\n\t\tzonesLabel = pv.Labels[v1.LabelTopologyZone]\n\t}\n\n\tzones := strings.Split(zonesLabel, labelMultiZoneDelimiter)\n\tif len(zones) == 1 \u0026\u0026 len(zones[0]) != 0 {\n\t\t// Zonal\n\t\tvolID = fmt.Sprintf(volIDZonalFmt, UnspecifiedValue, zones[0], pv.Spec.GCEPersistentDisk.PDName)\n\t} else if len(zones) \u003e 1 {\n\t\t// Regional\n\t\tregion, err := gceGetRegionFromZones(zones)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get region from zones: %v\", err)\n\t\t}\n\t\tvolID = fmt.Sprintf(volIDRegionalFmt, UnspecifiedValue, region, pv.Spec.GCEPersistentDisk.PDName)\n\t} else {\n\t\t// Unspecified\n\t\tvolID = fmt.Sprintf(volIDZonalFmt, UnspecifiedValue, UnspecifiedValue, pv.Spec.GCEPersistentDisk.PDName)\n\t}\n\n\tgceSource := pv.Spec.PersistentVolumeSource.GCEPersistentDisk\n\n\tpartition := \"\"\n\tif gceSource.Partition != 0 {\n\t\tpartition = strconv.Itoa(int(gceSource.Partition))\n\t}\n\n\tcsiSource := \u0026v1.CSIPersistentVolumeSource{\n\t\tDriver: GCEPDDriverName,\n\t\tVolumeHandle: volID,\n\t\tReadOnly: gceSource.ReadOnly,\n\t\tFSType: gceSource.FSType,\n\t\tVolumeAttributes: map[string]string{\n\t\t\t\"partition\": partition,\n\t\t},\n\t}\n\n\tif err := translateTopologyFromInTreeToCSI(pv, GCEPDTopologyKey); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to translate topology: %v\", err)\n\t}\n\n\tpv.Spec.PersistentVolumeSource.GCEPersistentDisk = nil\n\tpv.Spec.PersistentVolumeSource.CSI = csiSource\n\tpv.Spec.AccessModes = backwardCompatibleAccessModes(pv.Spec.AccessModes)\n\n\treturn pv, nil\n}","line":{"from":209,"to":266}} {"id":100030857,"name":"TranslateCSIPVToInTree","signature":"func (g *gcePersistentDiskCSITranslator) TranslateCSIPVToInTree(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/gce_pd.go","code":"// TranslateCSIPVToInTree takes a PV with CSIPersistentVolumeSource set and\n// translates the GCE PD CSI source to a GCEPersistentDisk source.\nfunc (g *gcePersistentDiskCSITranslator) TranslateCSIPVToInTree(pv *v1.PersistentVolume) (*v1.PersistentVolume, error) {\n\tif pv == nil || pv.Spec.CSI == nil {\n\t\treturn nil, fmt.Errorf(\"pv is nil or CSI source not defined on pv\")\n\t}\n\tcsiSource := pv.Spec.CSI\n\n\tpdName, err := pdNameFromVolumeID(csiSource.VolumeHandle)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgceSource := \u0026v1.GCEPersistentDiskVolumeSource{\n\t\tPDName: pdName,\n\t\tFSType: csiSource.FSType,\n\t\tReadOnly: csiSource.ReadOnly,\n\t}\n\tif partition, ok := csiSource.VolumeAttributes[\"partition\"]; ok \u0026\u0026 partition != \"\" {\n\t\tpartInt, err := strconv.Atoi(partition)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to convert partition %v to integer: %v\", partition, err)\n\t\t}\n\t\tgceSource.Partition = int32(partInt)\n\t}\n\n\t// translate CSI topology to In-tree topology for rollback compatibility\n\tif err := translateTopologyFromCSIToInTree(pv, GCEPDTopologyKey, gceGetRegionFromZones); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to translate topology. PV:%+v. Error:%v\", *pv, err)\n\t}\n\n\tpv.Spec.CSI = nil\n\tpv.Spec.GCEPersistentDisk = gceSource\n\n\treturn pv, nil\n}","line":{"from":268,"to":303}} {"id":100030858,"name":"CanSupport","signature":"func (g *gcePersistentDiskCSITranslator) CanSupport(pv *v1.PersistentVolume) bool","file":"staging/src/k8s.io/csi-translation-lib/plugins/gce_pd.go","code":"// CanSupport tests whether the plugin supports a given persistent volume\n// specification from the API. The spec pointer should be considered\n// const.\nfunc (g *gcePersistentDiskCSITranslator) CanSupport(pv *v1.PersistentVolume) bool {\n\treturn pv != nil \u0026\u0026 pv.Spec.GCEPersistentDisk != nil\n}","line":{"from":305,"to":310}} {"id":100030859,"name":"CanSupportInline","signature":"func (g *gcePersistentDiskCSITranslator) CanSupportInline(volume *v1.Volume) bool","file":"staging/src/k8s.io/csi-translation-lib/plugins/gce_pd.go","code":"// CanSupportInline tests whether the plugin supports a given inline volume\n// specification from the API. The spec pointer should be considered\n// const.\nfunc (g *gcePersistentDiskCSITranslator) CanSupportInline(volume *v1.Volume) bool {\n\treturn volume != nil \u0026\u0026 volume.GCEPersistentDisk != nil\n}","line":{"from":312,"to":317}} {"id":100030860,"name":"GetInTreePluginName","signature":"func (g *gcePersistentDiskCSITranslator) GetInTreePluginName() string","file":"staging/src/k8s.io/csi-translation-lib/plugins/gce_pd.go","code":"// GetInTreePluginName returns the name of the intree plugin driver\nfunc (g *gcePersistentDiskCSITranslator) GetInTreePluginName() string {\n\treturn GCEPDInTreePluginName\n}","line":{"from":319,"to":322}} {"id":100030861,"name":"GetCSIPluginName","signature":"func (g *gcePersistentDiskCSITranslator) GetCSIPluginName() string","file":"staging/src/k8s.io/csi-translation-lib/plugins/gce_pd.go","code":"// GetCSIPluginName returns the name of the CSI plugin\nfunc (g *gcePersistentDiskCSITranslator) GetCSIPluginName() string {\n\treturn GCEPDDriverName\n}","line":{"from":324,"to":327}} {"id":100030862,"name":"RepairVolumeHandle","signature":"func (g *gcePersistentDiskCSITranslator) RepairVolumeHandle(volumeHandle, nodeID string) (string, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/gce_pd.go","code":"// RepairVolumeHandle returns a fully specified volume handle by inferring\n// project, zone/region from the node ID if the volume handle has UNSPECIFIED\n// sections\nfunc (g *gcePersistentDiskCSITranslator) RepairVolumeHandle(volumeHandle, nodeID string) (string, error) {\n\tvar err error\n\ttok := strings.Split(volumeHandle, \"/\")\n\tif len(tok) \u003c volIDTotalElements {\n\t\treturn \"\", fmt.Errorf(\"volume handle has wrong number of elements; got %v, wanted %v or more\", len(tok), volIDTotalElements)\n\t}\n\tif tok[volIDProjectValue] != UnspecifiedValue {\n\t\treturn volumeHandle, nil\n\t}\n\n\tnodeTok := strings.Split(nodeID, \"/\")\n\tif len(nodeTok) \u003c volIDTotalElements {\n\t\treturn \"\", fmt.Errorf(\"node handle has wrong number of elements; got %v, wanted %v or more\", len(nodeTok), volIDTotalElements)\n\t}\n\n\tswitch tok[volIDRegionalityValue] {\n\tcase \"zones\":\n\t\tzone := \"\"\n\t\tif tok[volIDZoneValue] == UnspecifiedValue {\n\t\t\tzone = nodeTok[volIDZoneValue]\n\t\t} else {\n\t\t\tzone = tok[volIDZoneValue]\n\t\t}\n\t\treturn fmt.Sprintf(volIDZonalFmt, nodeTok[volIDProjectValue], zone, tok[volIDDiskNameValue]), nil\n\tcase \"regions\":\n\t\tregion := \"\"\n\t\tif tok[volIDZoneValue] == UnspecifiedValue {\n\t\t\tregion, err = gceGetRegionFromZones([]string{nodeTok[volIDZoneValue]})\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", fmt.Errorf(\"failed to get region from zone %s: %v\", nodeTok[volIDZoneValue], err)\n\t\t\t}\n\t\t} else {\n\t\t\tregion = tok[volIDZoneValue]\n\t\t}\n\t\treturn fmt.Sprintf(volIDRegionalFmt, nodeTok[volIDProjectValue], region, tok[volIDDiskNameValue]), nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"expected volume handle to have zones or regions regionality value, got: %s\", tok[volIDRegionalityValue])\n\t}\n}","line":{"from":329,"to":370}} {"id":100030863,"name":"pdNameFromVolumeID","signature":"func pdNameFromVolumeID(id string) (string, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/gce_pd.go","code":"func pdNameFromVolumeID(id string) (string, error) {\n\tsplitID := strings.Split(id, \"/\")\n\tif len(splitID) \u003c volIDTotalElements {\n\t\treturn \"\", fmt.Errorf(\"failed to get id components.Got: %v, wanted %v components or more. \", len(splitID), volIDTotalElements)\n\t}\n\treturn splitID[volIDDiskNameValue], nil\n}","line":{"from":372,"to":378}} {"id":100030864,"name":"gceGetRegionFromZones","signature":"func gceGetRegionFromZones(zones []string) (string, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/gce_pd.go","code":"// TODO: Replace this with the imported one from GCE PD CSI Driver when\n// the driver removes all k8s/k8s dependencies\nfunc gceGetRegionFromZones(zones []string) (string, error) {\n\tregions := sets.String{}\n\tif len(zones) \u003c 1 {\n\t\treturn \"\", fmt.Errorf(\"no zones specified\")\n\t}\n\tfor _, zone := range zones {\n\t\t// Zone expected format {locale}-{region}-{zone}\n\t\tsplitZone := strings.Split(zone, \"-\")\n\t\tif len(splitZone) != 3 {\n\t\t\treturn \"\", fmt.Errorf(\"zone in unexpected format, expected: {locale}-{region}-{zone}, got: %v\", zone)\n\t\t}\n\t\tregions.Insert(strings.Join(splitZone[0:2], \"-\"))\n\t}\n\tif regions.Len() != 1 {\n\t\treturn \"\", fmt.Errorf(\"multiple or no regions gotten from zones, got: %v\", regions)\n\t}\n\treturn regions.UnsortedList()[0], nil\n}","line":{"from":380,"to":399}} {"id":100030865,"name":"replaceTopology","signature":"func replaceTopology(pv *v1.PersistentVolume, oldKey, newKey string) error","file":"staging/src/k8s.io/csi-translation-lib/plugins/in_tree_volume.go","code":"// replaceTopology overwrites an existing key in NodeAffinity by a new one.\n// If there are any newKey already exist in an expression of a term, we will\n// not combine the replaced key Values with the existing ones.\n// So there might be duplication if there is any newKey expression\n// already in the terms.\nfunc replaceTopology(pv *v1.PersistentVolume, oldKey, newKey string) error {\n\t// Make sure the necessary fields exist\n\tif pv == nil || pv.Spec.NodeAffinity == nil || pv.Spec.NodeAffinity.Required == nil ||\n\t\tpv.Spec.NodeAffinity.Required.NodeSelectorTerms == nil || len(pv.Spec.NodeAffinity.Required.NodeSelectorTerms) == 0 {\n\t\treturn nil\n\t}\n\tfor i := range pv.Spec.NodeAffinity.Required.NodeSelectorTerms {\n\t\tfor j, r := range pv.Spec.NodeAffinity.Required.NodeSelectorTerms[i].MatchExpressions {\n\t\t\tif r.Key == oldKey {\n\t\t\t\tpv.Spec.NodeAffinity.Required.NodeSelectorTerms[i].MatchExpressions[j].Key = newKey\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":81,"to":101}} {"id":100030866,"name":"getTopologyValues","signature":"func getTopologyValues(pv *v1.PersistentVolume, key string) []string","file":"staging/src/k8s.io/csi-translation-lib/plugins/in_tree_volume.go","code":"// getTopologyValues returns all unique topology values with the given key found in\n// the PV NodeAffinity. Sort by alphabetical order.\n// This function collapses multiple zones into a list that is ORed. This assumes that\n// the plugin does not support a constraint like key in \"zone1\" AND \"zone2\"\nfunc getTopologyValues(pv *v1.PersistentVolume, key string) []string {\n\tif pv.Spec.NodeAffinity == nil ||\n\t\tpv.Spec.NodeAffinity.Required == nil ||\n\t\tlen(pv.Spec.NodeAffinity.Required.NodeSelectorTerms) \u003c 1 {\n\t\treturn nil\n\t}\n\n\tvalues := make(map[string]bool)\n\tfor i := range pv.Spec.NodeAffinity.Required.NodeSelectorTerms {\n\t\tfor _, r := range pv.Spec.NodeAffinity.Required.NodeSelectorTerms[i].MatchExpressions {\n\t\t\tif r.Key == key {\n\t\t\t\tfor _, v := range r.Values {\n\t\t\t\t\tvalues[v] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// remove duplication and sort them in order for better usage\n\tvar re []string\n\tfor k := range values {\n\t\tre = append(re, k)\n\t}\n\tsort.Strings(re)\n\treturn re\n}","line":{"from":103,"to":131}} {"id":100030867,"name":"addTopology","signature":"func addTopology(pv *v1.PersistentVolume, topologyKey string, zones []string) error","file":"staging/src/k8s.io/csi-translation-lib/plugins/in_tree_volume.go","code":"// addTopology appends the topology to the given PV to all Terms.\nfunc addTopology(pv *v1.PersistentVolume, topologyKey string, zones []string) error {\n\t// Make sure there are no duplicate or empty strings\n\tfilteredZones := sets.String{}\n\tfor i := range zones {\n\t\tzone := strings.TrimSpace(zones[i])\n\t\tif len(zone) \u003e 0 {\n\t\t\tfilteredZones.Insert(zone)\n\t\t}\n\t}\n\n\tzones = filteredZones.List()\n\tif len(zones) \u003c 1 {\n\t\treturn errors.New(\"there are no valid zones to add to pv\")\n\t}\n\n\t// Make sure the necessary fields exist\n\tif pv.Spec.NodeAffinity == nil {\n\t\tpv.Spec.NodeAffinity = new(v1.VolumeNodeAffinity)\n\t}\n\n\tif pv.Spec.NodeAffinity.Required == nil {\n\t\tpv.Spec.NodeAffinity.Required = new(v1.NodeSelector)\n\t}\n\n\tif len(pv.Spec.NodeAffinity.Required.NodeSelectorTerms) == 0 {\n\t\tpv.Spec.NodeAffinity.Required.NodeSelectorTerms = make([]v1.NodeSelectorTerm, 1)\n\t}\n\n\ttopology := v1.NodeSelectorRequirement{\n\t\tKey: topologyKey,\n\t\tOperator: v1.NodeSelectorOpIn,\n\t\tValues: zones,\n\t}\n\n\t// add the CSI topology to each term\n\tfor i := range pv.Spec.NodeAffinity.Required.NodeSelectorTerms {\n\t\tpv.Spec.NodeAffinity.Required.NodeSelectorTerms[i].MatchExpressions = append(\n\t\t\tpv.Spec.NodeAffinity.Required.NodeSelectorTerms[i].MatchExpressions,\n\t\t\ttopology,\n\t\t)\n\t}\n\n\treturn nil\n}","line":{"from":133,"to":177}} {"id":100030868,"name":"translateTopologyFromInTreeToCSI","signature":"func translateTopologyFromInTreeToCSI(pv *v1.PersistentVolume, csiTopologyKey string) error","file":"staging/src/k8s.io/csi-translation-lib/plugins/in_tree_volume.go","code":"// translateTopologyFromInTreeToCSI converts existing zone labels or in-tree topology to CSI topology.\n// In-tree topology has precedence over zone labels. When both in-tree topology and zone labels exist\n// for a particular CSI topology, in-tree topology will be used.\n// This function will remove the Beta version Kubernetes topology label in case the node upgrade to a\n// newer version where it does not have any Beta topology label anymore\nfunc translateTopologyFromInTreeToCSI(pv *v1.PersistentVolume, csiTopologyKey string) error {\n\n\tzoneLabel, regionLabel := getTopologyLabel(pv)\n\n\t// If Zone kubernetes topology exist, replace it to use csiTopologyKey\n\tzones := getTopologyValues(pv, zoneLabel)\n\tif len(zones) \u003e 0 {\n\t\treplaceTopology(pv, zoneLabel, csiTopologyKey)\n\t} else {\n\t\t// if nothing is in the NodeAffinity, try to fetch the topology from PV labels\n\t\tif label, ok := pv.Labels[zoneLabel]; ok {\n\t\t\tzones = strings.Split(label, labelMultiZoneDelimiter)\n\t\t\tif len(zones) \u003e 0 {\n\t\t\t\taddTopology(pv, csiTopologyKey, zones)\n\t\t\t}\n\t\t}\n\t}\n\n\t// if the in-tree PV has beta region label, replace it with GA label to ensure\n\t// the scheduler is able to schedule it on new nodes with only GA kubernetes label\n\t// No need to check it for zone label because it has already been replaced if exist\n\tif regionLabel == v1.LabelFailureDomainBetaRegion {\n\t\tregions := getTopologyValues(pv, regionLabel)\n\t\tif len(regions) \u003e 0 {\n\t\t\treplaceTopology(pv, regionLabel, v1.LabelTopologyRegion)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":179,"to":213}} {"id":100030869,"name":"getTopologyLabel","signature":"func getTopologyLabel(pv *v1.PersistentVolume) (zoneLabel string, regionLabel string)","file":"staging/src/k8s.io/csi-translation-lib/plugins/in_tree_volume.go","code":"// getTopologyLabel checks if the kubernetes topology label used in this\n// PV is GA and return the zone/region label used.\n// The version checking follows the following orders\n// 1. Check NodeAffinity\n// 1.1 Check if zoneGA exists, if yes return GA labels\n// 1.2 Check if zoneBeta exists, if yes return Beta labels\n// 2. Check PV labels\n// 2.1 Check if zoneGA exists, if yes return GA labels\n// 2.2 Check if zoneBeta exists, if yes return Beta labels\nfunc getTopologyLabel(pv *v1.PersistentVolume) (zoneLabel string, regionLabel string) {\n\n\tif zoneGA := TopologyKeyExist(v1.LabelTopologyZone, pv.Spec.NodeAffinity); zoneGA {\n\t\treturn v1.LabelTopologyZone, v1.LabelTopologyRegion\n\t}\n\tif zoneBeta := TopologyKeyExist(v1.LabelFailureDomainBetaZone, pv.Spec.NodeAffinity); zoneBeta {\n\t\treturn v1.LabelFailureDomainBetaZone, v1.LabelFailureDomainBetaRegion\n\t}\n\tif _, zoneGA := pv.Labels[v1.LabelTopologyZone]; zoneGA {\n\t\treturn v1.LabelTopologyZone, v1.LabelTopologyRegion\n\t}\n\tif _, zoneBeta := pv.Labels[v1.LabelFailureDomainBetaZone]; zoneBeta {\n\t\treturn v1.LabelFailureDomainBetaZone, v1.LabelFailureDomainBetaRegion\n\t}\n\t// No labels or NodeAffinity exist, default to GA version\n\treturn v1.LabelTopologyZone, v1.LabelTopologyRegion\n}","line":{"from":215,"to":240}} {"id":100030870,"name":"TopologyKeyExist","signature":"func TopologyKeyExist(key string, vna *v1.VolumeNodeAffinity) bool","file":"staging/src/k8s.io/csi-translation-lib/plugins/in_tree_volume.go","code":"// TopologyKeyExist checks if a certain key exists in a VolumeNodeAffinity\nfunc TopologyKeyExist(key string, vna *v1.VolumeNodeAffinity) bool {\n\tif vna == nil || vna.Required == nil || vna.Required.NodeSelectorTerms == nil || len(vna.Required.NodeSelectorTerms) == 0 {\n\t\treturn false\n\t}\n\n\tfor _, nodeSelectorTerms := range vna.Required.NodeSelectorTerms {\n\t\tnsrequirements := nodeSelectorTerms.MatchExpressions\n\t\tfor _, nodeSelectorRequirement := range nsrequirements {\n\t\t\tif nodeSelectorRequirement.Key == key {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":242,"to":257}} {"id":100030871,"name":"translateTopologyFromCSIToInTree","signature":"func translateTopologyFromCSIToInTree(pv *v1.PersistentVolume, csiTopologyKey string, regionParser regionParserFn) error","file":"staging/src/k8s.io/csi-translation-lib/plugins/in_tree_volume.go","code":"// translateTopologyFromCSIToInTree translate a CSI topology to\n// Kubernetes topology and add topology labels to it. Note that this function\n// will only work for plugin with a single topologyKey that translates to\n// Kubernetes zone(and region if regionParser is passed in).\n// If a plugin has more than one topologyKey, it will need to be processed\n// separately by the plugin.\n// If regionParser is nil, no region NodeAffinity will be added. If not nil,\n// it'll be passed to regionTopologyHandler, which will add region topology NodeAffinity\n// and labels for the given PV. It assumes the Zone NodeAffinity already exists.\n// In short this function will,\n// 1. Replace all CSI topology to Kubernetes Zone topology label\n// 2. Process and generate region topology if a regionParser is passed\n// 3. Add Kubernetes Topology labels(zone) if they do not exist\nfunc translateTopologyFromCSIToInTree(pv *v1.PersistentVolume, csiTopologyKey string, regionParser regionParserFn) error {\n\n\tzoneLabel, _ := getTopologyLabel(pv)\n\n\t// 1. Replace all CSI topology to Kubernetes Zone label\n\terr := replaceTopology(pv, csiTopologyKey, zoneLabel)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to replace CSI topology to Kubernetes topology, error: %v\", err)\n\t}\n\n\t// 2. Take care of region topology if a regionParser is passed\n\tif regionParser != nil {\n\t\t// let's make less strict on this one. Even if there is an error in the region processing, just ignore it\n\t\terr = regionTopologyHandler(pv, regionParser)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to handle region topology. error: %v\", err)\n\t\t}\n\t}\n\n\t// 3. Add labels about Kubernetes Topology\n\tzoneVals := getTopologyValues(pv, zoneLabel)\n\tif len(zoneVals) \u003e 0 {\n\t\tif pv.Labels == nil {\n\t\t\tpv.Labels = make(map[string]string)\n\t\t}\n\t\t_, zoneOK := pv.Labels[zoneLabel]\n\t\tif !zoneOK {\n\t\t\tzoneValStr := strings.Join(zoneVals, labelMultiZoneDelimiter)\n\t\t\tpv.Labels[zoneLabel] = zoneValStr\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":261,"to":307}} {"id":100030872,"name":"translateAllowedTopologies","signature":"func translateAllowedTopologies(terms []v1.TopologySelectorTerm, key string) ([]v1.TopologySelectorTerm, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/in_tree_volume.go","code":"// translateAllowedTopologies translates allowed topologies within storage class or PV\n// from legacy failure domain to given CSI topology key\nfunc translateAllowedTopologies(terms []v1.TopologySelectorTerm, key string) ([]v1.TopologySelectorTerm, error) {\n\tif terms == nil {\n\t\treturn nil, nil\n\t}\n\n\tnewTopologies := []v1.TopologySelectorTerm{}\n\tfor _, term := range terms {\n\t\tnewTerm := v1.TopologySelectorTerm{}\n\t\tfor _, exp := range term.MatchLabelExpressions {\n\t\t\tvar newExp v1.TopologySelectorLabelRequirement\n\t\t\tif exp.Key == v1.LabelFailureDomainBetaZone || exp.Key == v1.LabelTopologyZone {\n\t\t\t\tnewExp = v1.TopologySelectorLabelRequirement{\n\t\t\t\t\tKey: key,\n\t\t\t\t\tValues: exp.Values,\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Other topologies are passed through unchanged.\n\t\t\t\tnewExp = exp\n\t\t\t}\n\t\t\tnewTerm.MatchLabelExpressions = append(newTerm.MatchLabelExpressions, newExp)\n\t\t}\n\t\tnewTopologies = append(newTopologies, newTerm)\n\t}\n\treturn newTopologies, nil\n}","line":{"from":309,"to":335}} {"id":100030873,"name":"regionTopologyHandler","signature":"func regionTopologyHandler(pv *v1.PersistentVolume, regionParser regionParserFn) error","file":"staging/src/k8s.io/csi-translation-lib/plugins/in_tree_volume.go","code":"// regionTopologyHandler will process the PV and add region\n// kubernetes topology label to its NodeAffinity and labels\n// It assumes the Zone NodeAffinity already exists\n// Each provider is responsible for providing their own regionParser\nfunc regionTopologyHandler(pv *v1.PersistentVolume, regionParser regionParserFn) error {\n\n\t// Make sure the necessary fields exist\n\tif pv == nil || pv.Spec.NodeAffinity == nil || pv.Spec.NodeAffinity.Required == nil ||\n\t\tpv.Spec.NodeAffinity.Required.NodeSelectorTerms == nil || len(pv.Spec.NodeAffinity.Required.NodeSelectorTerms) == 0 {\n\t\treturn nil\n\t}\n\n\tzoneLabel, regionLabel := getTopologyLabel(pv)\n\n\t// process each term\n\tfor index, nodeSelectorTerm := range pv.Spec.NodeAffinity.Required.NodeSelectorTerms {\n\t\t// In the first loop, see if regionLabel already exist\n\t\tregionExist := false\n\t\tvar zoneVals []string\n\t\tfor _, nsRequirement := range nodeSelectorTerm.MatchExpressions {\n\t\t\tif nsRequirement.Key == regionLabel {\n\t\t\t\tregionExist = true\n\t\t\t\tbreak\n\t\t\t} else if nsRequirement.Key == zoneLabel {\n\t\t\t\tzoneVals = append(zoneVals, nsRequirement.Values...)\n\t\t\t}\n\t\t}\n\t\tif regionExist {\n\t\t\t// Regionlabel already exist in this term, skip it\n\t\t\tcontinue\n\t\t}\n\t\t// If no regionLabel found, generate region label from the zoneLabel we collect from this term\n\t\tregionVal, err := regionParser(zoneVals)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Add the regionVal to this term\n\t\tpv.Spec.NodeAffinity.Required.NodeSelectorTerms[index].MatchExpressions =\n\t\t\tappend(pv.Spec.NodeAffinity.Required.NodeSelectorTerms[index].MatchExpressions, v1.NodeSelectorRequirement{\n\t\t\t\tKey: regionLabel,\n\t\t\t\tOperator: v1.NodeSelectorOpIn,\n\t\t\t\tValues: []string{regionVal},\n\t\t\t})\n\n\t}\n\n\t// Add region label\n\tregionVals := getTopologyValues(pv, regionLabel)\n\tif len(regionVals) == 1 {\n\t\t// We should only have exactly 1 region value\n\t\tif pv.Labels == nil {\n\t\t\tpv.Labels = make(map[string]string)\n\t\t}\n\t\t_, regionOK := pv.Labels[regionLabel]\n\t\tif !regionOK {\n\t\t\tpv.Labels[regionLabel] = regionVals[0]\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":337,"to":397}} {"id":100030874,"name":"NewOpenStackCinderCSITranslator","signature":"func NewOpenStackCinderCSITranslator() InTreePlugin","file":"staging/src/k8s.io/csi-translation-lib/plugins/openstack_cinder.go","code":"// NewOpenStackCinderCSITranslator returns a new instance of osCinderCSITranslator\nfunc NewOpenStackCinderCSITranslator() InTreePlugin {\n\treturn \u0026osCinderCSITranslator{}\n}","line":{"from":42,"to":45}} {"id":100030875,"name":"TranslateInTreeStorageClassToCSI","signature":"func (t *osCinderCSITranslator) TranslateInTreeStorageClassToCSI(sc *storage.StorageClass) (*storage.StorageClass, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/openstack_cinder.go","code":"// TranslateInTreeStorageClassToCSI translates InTree Cinder storage class parameters to CSI storage class\nfunc (t *osCinderCSITranslator) TranslateInTreeStorageClassToCSI(sc *storage.StorageClass) (*storage.StorageClass, error) {\n\tvar (\n\t\tparams = map[string]string{}\n\t)\n\tfor k, v := range sc.Parameters {\n\t\tswitch strings.ToLower(k) {\n\t\tcase fsTypeKey:\n\t\t\tparams[csiFsTypeKey] = v\n\t\tdefault:\n\t\t\t// All other parameters are supported by the CSI driver.\n\t\t\t// This includes also \"availability\", therefore do not translate it to sc.AllowedTopologies\n\t\t\tparams[k] = v\n\t\t}\n\t}\n\n\tif len(sc.AllowedTopologies) \u003e 0 {\n\t\tnewTopologies, err := translateAllowedTopologies(sc.AllowedTopologies, CinderTopologyKey)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed translating allowed topologies: %v\", err)\n\t\t}\n\t\tsc.AllowedTopologies = newTopologies\n\t}\n\n\tsc.Parameters = params\n\n\treturn sc, nil\n}","line":{"from":47,"to":74}} {"id":100030876,"name":"TranslateInTreeInlineVolumeToCSI","signature":"func (t *osCinderCSITranslator) TranslateInTreeInlineVolumeToCSI(volume *v1.Volume, podNamespace string) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/openstack_cinder.go","code":"// TranslateInTreeInlineVolumeToCSI takes a Volume with Cinder set from in-tree\n// and converts the Cinder source to a CSIPersistentVolumeSource\nfunc (t *osCinderCSITranslator) TranslateInTreeInlineVolumeToCSI(volume *v1.Volume, podNamespace string) (*v1.PersistentVolume, error) {\n\tif volume == nil || volume.Cinder == nil {\n\t\treturn nil, fmt.Errorf(\"volume is nil or Cinder not defined on volume\")\n\t}\n\n\tcinderSource := volume.Cinder\n\tpv := \u0026v1.PersistentVolume{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t// Must be unique per disk as it is used as the unique part of the\n\t\t\t// staging path\n\t\t\tName: fmt.Sprintf(\"%s-%s\", CinderDriverName, cinderSource.VolumeID),\n\t\t},\n\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\tPersistentVolumeSource: v1.PersistentVolumeSource{\n\t\t\t\tCSI: \u0026v1.CSIPersistentVolumeSource{\n\t\t\t\t\tDriver: CinderDriverName,\n\t\t\t\t\tVolumeHandle: cinderSource.VolumeID,\n\t\t\t\t\tReadOnly: cinderSource.ReadOnly,\n\t\t\t\t\tFSType: cinderSource.FSType,\n\t\t\t\t\tVolumeAttributes: map[string]string{},\n\t\t\t\t},\n\t\t\t},\n\t\t\tAccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce},\n\t\t},\n\t}\n\treturn pv, nil\n}","line":{"from":76,"to":104}} {"id":100030877,"name":"TranslateInTreePVToCSI","signature":"func (t *osCinderCSITranslator) TranslateInTreePVToCSI(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/openstack_cinder.go","code":"// TranslateInTreePVToCSI takes a PV with Cinder set from in-tree\n// and converts the Cinder source to a CSIPersistentVolumeSource\nfunc (t *osCinderCSITranslator) TranslateInTreePVToCSI(pv *v1.PersistentVolume) (*v1.PersistentVolume, error) {\n\tif pv == nil || pv.Spec.Cinder == nil {\n\t\treturn nil, fmt.Errorf(\"pv is nil or Cinder not defined on pv\")\n\t}\n\n\tcinderSource := pv.Spec.Cinder\n\n\tcsiSource := \u0026v1.CSIPersistentVolumeSource{\n\t\tDriver: CinderDriverName,\n\t\tVolumeHandle: cinderSource.VolumeID,\n\t\tReadOnly: cinderSource.ReadOnly,\n\t\tFSType: cinderSource.FSType,\n\t\tVolumeAttributes: map[string]string{},\n\t}\n\n\tif err := translateTopologyFromInTreeToCSI(pv, CinderTopologyKey); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to translate topology: %v\", err)\n\t}\n\n\tpv.Spec.Cinder = nil\n\tpv.Spec.CSI = csiSource\n\treturn pv, nil\n}","line":{"from":106,"to":130}} {"id":100030878,"name":"TranslateCSIPVToInTree","signature":"func (t *osCinderCSITranslator) TranslateCSIPVToInTree(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/openstack_cinder.go","code":"// TranslateCSIPVToInTree takes a PV with CSIPersistentVolumeSource set and\n// translates the Cinder CSI source to a Cinder In-tree source.\nfunc (t *osCinderCSITranslator) TranslateCSIPVToInTree(pv *v1.PersistentVolume) (*v1.PersistentVolume, error) {\n\tif pv == nil || pv.Spec.CSI == nil {\n\t\treturn nil, fmt.Errorf(\"pv is nil or CSI source not defined on pv\")\n\t}\n\n\tcsiSource := pv.Spec.CSI\n\n\tcinderSource := \u0026v1.CinderPersistentVolumeSource{\n\t\tVolumeID: csiSource.VolumeHandle,\n\t\tFSType: csiSource.FSType,\n\t\tReadOnly: csiSource.ReadOnly,\n\t}\n\n\t// translate CSI topology to In-tree topology for rollback compatibility.\n\t// It is not possible to guess Cinder Region from the Zone, therefore leave it empty.\n\tif err := translateTopologyFromCSIToInTree(pv, CinderTopologyKey, nil); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to translate topology. PV:%+v. Error:%v\", *pv, err)\n\t}\n\n\tpv.Spec.CSI = nil\n\tpv.Spec.Cinder = cinderSource\n\treturn pv, nil\n}","line":{"from":132,"to":156}} {"id":100030879,"name":"CanSupport","signature":"func (t *osCinderCSITranslator) CanSupport(pv *v1.PersistentVolume) bool","file":"staging/src/k8s.io/csi-translation-lib/plugins/openstack_cinder.go","code":"// CanSupport tests whether the plugin supports a given persistent volume\n// specification from the API. The spec pointer should be considered\n// const.\nfunc (t *osCinderCSITranslator) CanSupport(pv *v1.PersistentVolume) bool {\n\treturn pv != nil \u0026\u0026 pv.Spec.Cinder != nil\n}","line":{"from":158,"to":163}} {"id":100030880,"name":"CanSupportInline","signature":"func (t *osCinderCSITranslator) CanSupportInline(volume *v1.Volume) bool","file":"staging/src/k8s.io/csi-translation-lib/plugins/openstack_cinder.go","code":"// CanSupportInline tests whether the plugin supports a given inline volume\n// specification from the API. The spec pointer should be considered\n// const.\nfunc (t *osCinderCSITranslator) CanSupportInline(volume *v1.Volume) bool {\n\treturn volume != nil \u0026\u0026 volume.Cinder != nil\n}","line":{"from":165,"to":170}} {"id":100030881,"name":"GetInTreePluginName","signature":"func (t *osCinderCSITranslator) GetInTreePluginName() string","file":"staging/src/k8s.io/csi-translation-lib/plugins/openstack_cinder.go","code":"// GetInTreePluginName returns the name of the intree plugin driver\nfunc (t *osCinderCSITranslator) GetInTreePluginName() string {\n\treturn CinderInTreePluginName\n}","line":{"from":172,"to":175}} {"id":100030882,"name":"GetCSIPluginName","signature":"func (t *osCinderCSITranslator) GetCSIPluginName() string","file":"staging/src/k8s.io/csi-translation-lib/plugins/openstack_cinder.go","code":"// GetCSIPluginName returns the name of the CSI plugin\nfunc (t *osCinderCSITranslator) GetCSIPluginName() string {\n\treturn CinderDriverName\n}","line":{"from":177,"to":180}} {"id":100030883,"name":"RepairVolumeHandle","signature":"func (t *osCinderCSITranslator) RepairVolumeHandle(volumeHandle, nodeID string) (string, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/openstack_cinder.go","code":"func (t *osCinderCSITranslator) RepairVolumeHandle(volumeHandle, nodeID string) (string, error) {\n\treturn volumeHandle, nil\n}","line":{"from":182,"to":184}} {"id":100030884,"name":"NewPortworxCSITranslator","signature":"func NewPortworxCSITranslator() InTreePlugin","file":"staging/src/k8s.io/csi-translation-lib/plugins/portworx.go","code":"func NewPortworxCSITranslator() InTreePlugin {\n\treturn \u0026portworxCSITranslator{}\n}","line":{"from":36,"to":38}} {"id":100030885,"name":"TranslateInTreeStorageClassToCSI","signature":"func (p portworxCSITranslator) TranslateInTreeStorageClassToCSI(sc *storagev1.StorageClass) (*storagev1.StorageClass, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/portworx.go","code":"// TranslateInTreeStorageClassToCSI takes in-tree storage class used by in-tree plugin\n// and translates them to a storageclass consumable by CSI plugin\nfunc (p portworxCSITranslator) TranslateInTreeStorageClassToCSI(sc *storagev1.StorageClass) (*storagev1.StorageClass, error) {\n\tif sc == nil {\n\t\treturn nil, fmt.Errorf(\"sc is nil\")\n\t}\n\tsc.Provisioner = PortworxDriverName\n\treturn sc, nil\n}","line":{"from":40,"to":48}} {"id":100030886,"name":"TranslateInTreeInlineVolumeToCSI","signature":"func (p portworxCSITranslator) TranslateInTreeInlineVolumeToCSI(volume *v1.Volume, podNamespace string) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/portworx.go","code":"// TranslateInTreeInlineVolumeToCSI takes a inline volume and will translate\n// the in-tree inline volume source to a CSIPersistentVolumeSource\nfunc (p portworxCSITranslator) TranslateInTreeInlineVolumeToCSI(volume *v1.Volume, podNamespace string) (*v1.PersistentVolume, error) {\n\tif volume == nil || volume.PortworxVolume == nil {\n\t\treturn nil, fmt.Errorf(\"volume is nil or PortworxVolume not defined on volume\")\n\t}\n\n\tvar am v1.PersistentVolumeAccessMode\n\tif volume.PortworxVolume.ReadOnly {\n\t\tam = v1.ReadOnlyMany\n\t} else {\n\t\tam = v1.ReadWriteOnce\n\t}\n\n\tpv := \u0026v1.PersistentVolume{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: fmt.Sprintf(\"%s-%s\", PortworxDriverName, volume.PortworxVolume.VolumeID),\n\t\t},\n\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\tPersistentVolumeSource: v1.PersistentVolumeSource{\n\t\t\t\tCSI: \u0026v1.CSIPersistentVolumeSource{\n\t\t\t\t\tDriver: PortworxDriverName,\n\t\t\t\t\tVolumeHandle: volume.PortworxVolume.VolumeID,\n\t\t\t\t\tFSType: volume.PortworxVolume.FSType,\n\t\t\t\t\tVolumeAttributes: make(map[string]string),\n\t\t\t\t},\n\t\t\t},\n\t\t\tAccessModes: []v1.PersistentVolumeAccessMode{am},\n\t\t},\n\t}\n\treturn pv, nil\n}","line":{"from":50,"to":81}} {"id":100030887,"name":"TranslateInTreePVToCSI","signature":"func (p portworxCSITranslator) TranslateInTreePVToCSI(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/portworx.go","code":"// TranslateInTreePVToCSI takes a Portworx persistent volume and will translate\n// the in-tree pv source to a CSI Source\nfunc (p portworxCSITranslator) TranslateInTreePVToCSI(pv *v1.PersistentVolume) (*v1.PersistentVolume, error) {\n\tif pv == nil || pv.Spec.PortworxVolume == nil {\n\t\treturn nil, fmt.Errorf(\"pv is nil or PortworxVolume not defined on pv\")\n\t}\n\tcsiSource := \u0026v1.CSIPersistentVolumeSource{\n\t\tDriver: PortworxDriverName,\n\t\tVolumeHandle: pv.Spec.PortworxVolume.VolumeID,\n\t\tFSType: pv.Spec.PortworxVolume.FSType,\n\t\tVolumeAttributes: make(map[string]string), // copy access mode\n\t}\n\tpv.Spec.PortworxVolume = nil\n\tpv.Spec.CSI = csiSource\n\n\treturn pv, nil\n}","line":{"from":83,"to":99}} {"id":100030888,"name":"TranslateCSIPVToInTree","signature":"func (p portworxCSITranslator) TranslateCSIPVToInTree(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/portworx.go","code":"// TranslateCSIPVToInTree takes a PV with a CSI PersistentVolume Source and will translate\n// it to a in-tree Persistent Volume Source for the in-tree volume\nfunc (p portworxCSITranslator) TranslateCSIPVToInTree(pv *v1.PersistentVolume) (*v1.PersistentVolume, error) {\n\tif pv == nil || pv.Spec.CSI == nil {\n\t\treturn nil, fmt.Errorf(\"pv is nil or CSI source not defined on pv\")\n\t}\n\tcsiSource := pv.Spec.CSI\n\n\tportworxSource := \u0026v1.PortworxVolumeSource{\n\t\tVolumeID: csiSource.VolumeHandle,\n\t\tFSType: csiSource.FSType,\n\t\tReadOnly: csiSource.ReadOnly,\n\t}\n\tpv.Spec.CSI = nil\n\tpv.Spec.PortworxVolume = portworxSource\n\n\treturn pv, nil\n}","line":{"from":101,"to":118}} {"id":100030889,"name":"CanSupport","signature":"func (p portworxCSITranslator) CanSupport(pv *v1.PersistentVolume) bool","file":"staging/src/k8s.io/csi-translation-lib/plugins/portworx.go","code":"// CanSupport tests whether the plugin supports a given persistent volume\n// specification from the API.\nfunc (p portworxCSITranslator) CanSupport(pv *v1.PersistentVolume) bool {\n\treturn pv != nil \u0026\u0026 pv.Spec.PortworxVolume != nil\n}","line":{"from":120,"to":124}} {"id":100030890,"name":"CanSupportInline","signature":"func (p portworxCSITranslator) CanSupportInline(volume *v1.Volume) bool","file":"staging/src/k8s.io/csi-translation-lib/plugins/portworx.go","code":"// CanSupportInline tests whether the plugin supports a given inline volume\n// specification from the API.\nfunc (p portworxCSITranslator) CanSupportInline(volume *v1.Volume) bool {\n\treturn volume != nil \u0026\u0026 volume.PortworxVolume != nil\n}","line":{"from":126,"to":130}} {"id":100030891,"name":"GetInTreePluginName","signature":"func (p portworxCSITranslator) GetInTreePluginName() string","file":"staging/src/k8s.io/csi-translation-lib/plugins/portworx.go","code":"// GetInTreePluginName returns the in-tree plugin name this migrates\nfunc (p portworxCSITranslator) GetInTreePluginName() string {\n\treturn PortworxVolumePluginName\n}","line":{"from":132,"to":135}} {"id":100030892,"name":"GetCSIPluginName","signature":"func (p portworxCSITranslator) GetCSIPluginName() string","file":"staging/src/k8s.io/csi-translation-lib/plugins/portworx.go","code":"// GetCSIPluginName returns the name of the CSI plugin that supersedes the in-tree plugin\nfunc (p portworxCSITranslator) GetCSIPluginName() string {\n\treturn PortworxDriverName\n}","line":{"from":137,"to":140}} {"id":100030893,"name":"RepairVolumeHandle","signature":"func (p portworxCSITranslator) RepairVolumeHandle(volumeHandle, nodeID string) (string, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/portworx.go","code":"// RepairVolumeHandle generates a correct volume handle based on node ID information.\nfunc (p portworxCSITranslator) RepairVolumeHandle(volumeHandle, nodeID string) (string, error) {\n\treturn volumeHandle, nil\n}","line":{"from":142,"to":145}} {"id":100030894,"name":"NewRBDCSITranslator","signature":"func NewRBDCSITranslator() InTreePlugin","file":"staging/src/k8s.io/csi-translation-lib/plugins/rbd.go","code":"func NewRBDCSITranslator() InTreePlugin {\n\treturn \u0026rbdCSITranslator{}\n}","line":{"from":65,"to":67}} {"id":100030895,"name":"TranslateInTreeStorageClassToCSI","signature":"func (p rbdCSITranslator) TranslateInTreeStorageClassToCSI(sc *storagev1.StorageClass) (*storagev1.StorageClass, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/rbd.go","code":"// TranslateInTreeStorageClassToCSI takes in-tree storage class used by in-tree plugin\n// and translates them to a storage class consumable by CSI plugin\nfunc (p rbdCSITranslator) TranslateInTreeStorageClassToCSI(sc *storagev1.StorageClass) (*storagev1.StorageClass, error) {\n\tif sc == nil {\n\t\treturn nil, fmt.Errorf(\"sc is nil\")\n\t}\n\n\tvar params = map[string]string{}\n\n\tfillDefaultSCParams(params)\n\tfor k, v := range sc.Parameters {\n\t\tswitch strings.ToLower(k) {\n\t\tcase fsTypeKey:\n\t\t\tparams[csiFsTypeKey] = v\n\t\tcase \"imagefeatures\":\n\t\t\tparams[imgFeatureKey] = v\n\t\tcase poolKey:\n\t\t\tparams[poolKey] = v\n\t\tcase \"imageformat\":\n\t\t\tparams[imgFmtKey] = v\n\t\tcase \"adminid\":\n\t\t\tparams[adminIDKey] = v\n\t\tcase \"adminsecretname\":\n\t\t\tparams[provSecretNameKey] = v\n\t\t\tparams[nodeStageSecretNameKey] = v\n\t\t\tparams[cntrlExpandSecretNameKey] = v\n\t\tcase \"adminsecretnamespace\":\n\t\t\tparams[provSecretNamespaceKey] = v\n\t\t\tparams[nodeStageSecretNamespaceKey] = v\n\t\t\tparams[cntrlExpandSecretNamespaceKey] = v\n\t\tcase monsKey:\n\t\t\tarr := strings.Split(v, \",\")\n\t\t\tif len(arr) \u003c 1 {\n\t\t\t\treturn nil, fmt.Errorf(\"missing Ceph monitors\")\n\t\t\t}\n\t\t\tparams[monsKey] = v\n\t\t\tparams[clusterIDKey] = fmt.Sprintf(\"%x\", md5.Sum([]byte(v)))\n\t\t}\n\t}\n\n\tif params[provSecretNameKey] == \"\" {\n\t\treturn nil, fmt.Errorf(\"missing Ceph admin secret name\")\n\t}\n\tif params[monsKey] == \"\" {\n\t\treturn nil, fmt.Errorf(\"missing Ceph monitors\")\n\t}\n\tsc.Provisioner = RBDDriverName\n\tsc.Parameters = params\n\treturn sc, nil\n}","line":{"from":69,"to":118}} {"id":100030896,"name":"TranslateInTreeInlineVolumeToCSI","signature":"func (p rbdCSITranslator) TranslateInTreeInlineVolumeToCSI(volume *v1.Volume, podNamespace string) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/rbd.go","code":"// TranslateInTreeInlineVolumeToCSI takes an inline volume and will translate\n// the in-tree inline volume source to a CSIPersistentVolumeSource\nfunc (p rbdCSITranslator) TranslateInTreeInlineVolumeToCSI(volume *v1.Volume, podNamespace string) (*v1.PersistentVolume, error) {\n\tif volume == nil || volume.RBD == nil {\n\t\treturn nil, fmt.Errorf(\"volume is nil or RBDVolume not defined on volume\")\n\t}\n\n\tvar am v1.PersistentVolumeAccessMode\n\tif volume.RBD.ReadOnly {\n\t\tam = v1.ReadOnlyMany\n\t} else {\n\t\tam = v1.ReadWriteOnce\n\t}\n\tsecRef := \u0026v1.SecretReference{}\n\tif volume.RBD.SecretRef != nil {\n\t\tsecRef.Name = volume.RBD.SecretRef.Name\n\t\tsecRef.Namespace = podNamespace\n\t}\n\tvolumeAttr := make(map[string]string)\n\tvolumeAttr[clusterIDKey] = fmt.Sprintf(\"%x\", md5.Sum([]byte(strings.Join(volume.RBD.CephMonitors, \",\"))))\n\tvolumeAttr[poolKey] = defaultPoolVal\n\tif volume.RBD.RBDPool != \"\" {\n\t\tvolumeAttr[poolKey] = volume.RBD.RBDPool\n\t}\n\tvolumeAttr[staticVolKey] = defaultMigStaticVal\n\tvolumeAttr[imgFeatureKey] = defaultImgFeatureVal\n\tpv := \u0026v1.PersistentVolume{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: fmt.Sprintf(\"%s-%s\", RBDDriverName, volume.RBD.RBDImage),\n\t\t},\n\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\tPersistentVolumeSource: v1.PersistentVolumeSource{\n\t\t\t\tCSI: \u0026v1.CSIPersistentVolumeSource{\n\t\t\t\t\tDriver: RBDDriverName,\n\t\t\t\t\tVolumeHandle: volume.RBD.RBDImage,\n\t\t\t\t\tFSType: volume.RBD.FSType,\n\t\t\t\t\tVolumeAttributes: volumeAttr,\n\t\t\t\t\tNodeStageSecretRef: secRef,\n\t\t\t\t\tControllerExpandSecretRef: secRef,\n\t\t\t\t},\n\t\t\t},\n\t\t\tAccessModes: []v1.PersistentVolumeAccessMode{am},\n\t\t},\n\t}\n\treturn pv, nil\n}","line":{"from":120,"to":165}} {"id":100030897,"name":"TranslateInTreePVToCSI","signature":"func (p rbdCSITranslator) TranslateInTreePVToCSI(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/rbd.go","code":"// TranslateInTreePVToCSI takes a RBD persistent volume and will translate\n// the in-tree pv source to a CSI Source\nfunc (p rbdCSITranslator) TranslateInTreePVToCSI(pv *v1.PersistentVolume) (*v1.PersistentVolume, error) {\n\tif pv == nil || pv.Spec.RBD == nil {\n\t\treturn nil, fmt.Errorf(\"pv is nil or RBD Volume not defined on pv\")\n\t}\n\tvar volID string\n\tvolumeAttributes := make(map[string]string)\n\n\tif pv.Annotations[CSIRBDVolHandleAnnKey] != \"\" {\n\t\tvolID = pv.Annotations[CSIRBDVolHandleAnnKey]\n\t\tvolumeAttributes[clusterIDKey] = pv.Annotations[clusterIDKey]\n\t} else {\n\t\tmons := strings.Join(pv.Spec.RBD.CephMonitors, \",\")\n\t\tpool := pv.Spec.RBD.RBDPool\n\t\timage := pv.Spec.RBD.RBDImage\n\t\tvolumeAttributes[staticVolKey] = defaultMigStaticVal\n\t\tvolumeAttributes[clusterIDKey] = fmt.Sprintf(\"%x\", md5.Sum([]byte(mons)))\n\t\tvolID = composeMigVolID(mons, pool, image)\n\t}\n\n\terr := fillVolAttrsForRequest(pv, volumeAttributes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif volumeAttributes[imgFeatureKey] == \"\" {\n\t\tvolumeAttributes[imgFeatureKey] = defaultImgFeatureVal\n\t}\n\tvar am v1.PersistentVolumeAccessMode\n\tif pv.Spec.RBD.ReadOnly {\n\t\tam = v1.ReadOnlyMany\n\t} else {\n\t\tam = v1.ReadWriteOnce\n\t}\n\tpv.Spec.AccessModes = []v1.PersistentVolumeAccessMode{am}\n\tcsiSource := \u0026v1.CSIPersistentVolumeSource{\n\t\tDriver: RBDDriverName,\n\t\tFSType: pv.Spec.RBD.FSType,\n\t\tVolumeHandle: volID,\n\t\tVolumeAttributes: volumeAttributes,\n\t\tNodeStageSecretRef: pv.Spec.RBD.SecretRef,\n\t\tControllerExpandSecretRef: pv.Spec.RBD.SecretRef,\n\t}\n\tpv.Spec.RBD = nil\n\tpv.Spec.CSI = csiSource\n\treturn pv, nil\n}","line":{"from":167,"to":213}} {"id":100030898,"name":"TranslateCSIPVToInTree","signature":"func (p rbdCSITranslator) TranslateCSIPVToInTree(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/rbd.go","code":"// TranslateCSIPVToInTree takes a PV with a CSI PersistentVolume Source and will translate\n// it to an in-tree Persistent Volume Source for the in-tree volume\nfunc (p rbdCSITranslator) TranslateCSIPVToInTree(pv *v1.PersistentVolume) (*v1.PersistentVolume, error) {\n\tif pv == nil || pv.Spec.CSI == nil {\n\t\treturn nil, fmt.Errorf(\"pv is nil or CSI source not defined on pv\")\n\t}\n\tvar rbdImageName string\n\tmonSlice := []string{\"\"}\n\tcsiSource := pv.Spec.CSI\n\n\trbdImageName = csiSource.VolumeAttributes[imgNameKey]\n\trbdPool := csiSource.VolumeAttributes[poolKey]\n\tradosUser := csiSource.VolumeAttributes[adminIDKey]\n\tif radosUser == \"\" {\n\t\tradosUser = defaultAdminUser\n\t}\n\n\tRBDSource := \u0026v1.RBDPersistentVolumeSource{\n\t\tCephMonitors: monSlice,\n\t\tRBDImage: rbdImageName,\n\t\tFSType: csiSource.FSType,\n\t\tRBDPool: rbdPool,\n\t\tRadosUser: radosUser,\n\t\tReadOnly: csiSource.ReadOnly,\n\t}\n\n\tif pv.Annotations == nil {\n\t\tpv.Annotations = make(map[string]string)\n\t}\n\tfillAnnotationsFromCSISource(pv, csiSource)\n\tnodeSecret := csiSource.NodeStageSecretRef\n\tif nodeSecret != nil {\n\t\tRBDSource.SecretRef = \u0026v1.SecretReference{Name: nodeSecret.Name, Namespace: nodeSecret.Namespace}\n\t}\n\tpv.Spec.CSI = nil\n\tpv.Spec.RBD = RBDSource\n\n\treturn pv, nil\n}","line":{"from":215,"to":253}} {"id":100030899,"name":"CanSupport","signature":"func (p rbdCSITranslator) CanSupport(pv *v1.PersistentVolume) bool","file":"staging/src/k8s.io/csi-translation-lib/plugins/rbd.go","code":"// CanSupport tests whether the plugin supports a given persistent volume\n// specification from the API.\nfunc (p rbdCSITranslator) CanSupport(pv *v1.PersistentVolume) bool {\n\treturn pv != nil \u0026\u0026 pv.Spec.RBD != nil\n}","line":{"from":255,"to":259}} {"id":100030900,"name":"CanSupportInline","signature":"func (p rbdCSITranslator) CanSupportInline(volume *v1.Volume) bool","file":"staging/src/k8s.io/csi-translation-lib/plugins/rbd.go","code":"// CanSupportInline tests whether the plugin supports a given inline volume\n// specification from the API.\nfunc (p rbdCSITranslator) CanSupportInline(volume *v1.Volume) bool {\n\treturn volume != nil \u0026\u0026 volume.RBD != nil\n}","line":{"from":261,"to":265}} {"id":100030901,"name":"GetInTreePluginName","signature":"func (p rbdCSITranslator) GetInTreePluginName() string","file":"staging/src/k8s.io/csi-translation-lib/plugins/rbd.go","code":"// GetInTreePluginName returns the in-tree plugin name this migrates\nfunc (p rbdCSITranslator) GetInTreePluginName() string {\n\treturn RBDVolumePluginName\n}","line":{"from":267,"to":270}} {"id":100030902,"name":"GetCSIPluginName","signature":"func (p rbdCSITranslator) GetCSIPluginName() string","file":"staging/src/k8s.io/csi-translation-lib/plugins/rbd.go","code":"// GetCSIPluginName returns the name of the CSI plugin that supersedes the in-tree plugin\nfunc (p rbdCSITranslator) GetCSIPluginName() string {\n\treturn RBDDriverName\n}","line":{"from":272,"to":275}} {"id":100030903,"name":"RepairVolumeHandle","signature":"func (p rbdCSITranslator) RepairVolumeHandle(volumeHandle, nodeID string) (string, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/rbd.go","code":"// RepairVolumeHandle generates a correct volume handle based on node ID information.\nfunc (p rbdCSITranslator) RepairVolumeHandle(volumeHandle, nodeID string) (string, error) {\n\treturn volumeHandle, nil\n}","line":{"from":277,"to":280}} {"id":100030904,"name":"fillDefaultSCParams","signature":"func fillDefaultSCParams(params map[string]string)","file":"staging/src/k8s.io/csi-translation-lib/plugins/rbd.go","code":"// fillDefaultSCParams fills some sc parameters with default values\nfunc fillDefaultSCParams(params map[string]string) {\n\tparams[defaultMigKey] = defaultMigStaticVal\n\tparams[poolKey] = defaultPoolVal\n\tparams[provSecretNamespaceKey] = defaultAdminSecretNamespace\n\tparams[cntrlExpandSecretNamespaceKey] = defaultAdminSecretNamespace\n\tparams[nodeStageSecretNamespaceKey] = defaultAdminSecretNamespace\n}","line":{"from":282,"to":289}} {"id":100030905,"name":"composeMigVolID","signature":"func composeMigVolID(mons string, pool string, image string) string","file":"staging/src/k8s.io/csi-translation-lib/plugins/rbd.go","code":"// composeMigVolID composes migration handle for RBD PV\n// mig_mons-afcca55bc1bdd3f479be1e8281c13ab1_image-e0b45b52-7e09-47d3-8f1b-806995fa4412_7265706c696361706f6f6c\nfunc composeMigVolID(mons string, pool string, image string) string {\n\tclusterIDInHandle := md5.Sum([]byte(mons))\n\tclusterField := monsPfx + fmt.Sprintf(\"%x\", clusterIDInHandle)\n\tpoolHashInHandle := hex.EncodeToString([]byte(pool))\n\timageHashInHandle := strings.TrimPrefix(image, defaultIntreeImagePfx)\n\timageField := imgPfx + imageHashInHandle\n\tvolHash := strings.Join([]string{migVolPfx, clusterField, imageField, poolHashInHandle}, \"_\")\n\treturn volHash\n}","line":{"from":291,"to":301}} {"id":100030906,"name":"fillVolAttrsForRequest","signature":"func fillVolAttrsForRequest(pv *v1.PersistentVolume, volumeAttributes map[string]string) error","file":"staging/src/k8s.io/csi-translation-lib/plugins/rbd.go","code":"// fillVolAttrsForRequest fill the volume attributes for node operations\nfunc fillVolAttrsForRequest(pv *v1.PersistentVolume, volumeAttributes map[string]string) error {\n\tif pv == nil || pv.Spec.RBD == nil {\n\t\treturn fmt.Errorf(\"pv is nil or RBD Volume not defined on pv\")\n\t}\n\tvolumeAttributes[imgNameKey] = pv.Spec.RBD.RBDImage\n\tvolumeAttributes[poolKey] = pv.Spec.RBD.RBDPool\n\tvolumeAttributes[imgFeatureKey] = pv.Annotations[imgFeatureKey]\n\tvolumeAttributes[imgFmtKey] = pv.Annotations[imgFmtKey]\n\tvolumeAttributes[journalPoolKey] = pv.Annotations[journalPoolKey]\n\tvolumeAttributes[defaultMigKey] = defaultMigStaticVal\n\tvolumeAttributes[\"tryOtherMounters\"] = defaultMigStaticVal\n\treturn nil\n}","line":{"from":303,"to":316}} {"id":100030907,"name":"fillAnnotationsFromCSISource","signature":"func fillAnnotationsFromCSISource(pv *v1.PersistentVolume, csiSource *v1.CSIPersistentVolumeSource)","file":"staging/src/k8s.io/csi-translation-lib/plugins/rbd.go","code":"// fillAnnotationsFromCSISource capture required information from csi source\nfunc fillAnnotationsFromCSISource(pv *v1.PersistentVolume, csiSource *v1.CSIPersistentVolumeSource) {\n\tpv.Annotations[CSIRBDVolHandleAnnKey] = csiSource.VolumeHandle\n\tpv.Annotations[clusterIDKey] = csiSource.VolumeAttributes[clusterIDKey]\n\tpv.Annotations[journalPoolKey] = csiSource.VolumeAttributes[journalPoolKey]\n\tpv.Annotations[imgFeatureKey] = csiSource.VolumeAttributes[imgFeatureKey]\n\tpv.Annotations[imgFmtKey] = csiSource.VolumeAttributes[imgFmtKey]\n}","line":{"from":318,"to":325}} {"id":100030908,"name":"NewvSphereCSITranslator","signature":"func NewvSphereCSITranslator() InTreePlugin","file":"staging/src/k8s.io/csi-translation-lib/plugins/vsphere_volume.go","code":"// NewvSphereCSITranslator returns a new instance of vSphereCSITranslator\nfunc NewvSphereCSITranslator() InTreePlugin {\n\treturn \u0026vSphereCSITranslator{}\n}","line":{"from":71,"to":74}} {"id":100030909,"name":"TranslateInTreeStorageClassToCSI","signature":"func (t *vSphereCSITranslator) TranslateInTreeStorageClassToCSI(sc *storage.StorageClass) (*storage.StorageClass, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/vsphere_volume.go","code":"// TranslateInTreeStorageClassToCSI translates InTree vSphere storage class parameters to CSI storage class\nfunc (t *vSphereCSITranslator) TranslateInTreeStorageClassToCSI(sc *storage.StorageClass) (*storage.StorageClass, error) {\n\tif sc == nil {\n\t\treturn nil, fmt.Errorf(\"sc is nil\")\n\t}\n\tvar params = map[string]string{}\n\tfor k, v := range sc.Parameters {\n\t\tswitch strings.ToLower(k) {\n\t\tcase fsTypeKey:\n\t\t\tparams[csiFsTypeKey] = v\n\t\tcase paramStoragePolicyName:\n\t\t\tparams[paramStoragePolicyName] = v\n\t\tcase \"datastore\":\n\t\t\tparams[paramDatastore] = v\n\t\tcase \"diskformat\":\n\t\t\tparams[paramDiskFormat] = v\n\t\tcase \"hostfailurestotolerate\":\n\t\t\tparams[paramHostFailuresToTolerate] = v\n\t\tcase \"forceprovisioning\":\n\t\t\tparams[paramForceProvisioning] = v\n\t\tcase \"cachereservation\":\n\t\t\tparams[paramCacheReservation] = v\n\t\tcase \"diskstripes\":\n\t\t\tparams[paramDiskstripes] = v\n\t\tcase \"objectspacereservation\":\n\t\t\tparams[paramObjectspacereservation] = v\n\t\tcase \"iopslimit\":\n\t\t\tparams[paramIopslimit] = v\n\t\tdefault:\n\t\t\tklog.V(2).Infof(\"StorageClass parameter [name:%q, value:%q] is not supported\", k, v)\n\t\t}\n\t}\n\n\t// This helps vSphere CSI driver to identify in-tree provisioner request vs CSI provisioner request\n\t// When this is true, Driver returns initialvolumefilepath in the VolumeContext, which is\n\t// used in TranslateCSIPVToInTree\n\tparams[paramcsiMigration] = \"true\"\n\t// translate AllowedTopologies to vSphere CSI Driver topology\n\tif len(sc.AllowedTopologies) \u003e 0 {\n\t\tnewTopologies, err := translateAllowedTopologies(sc.AllowedTopologies, vSphereCSITopologyZoneKey)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed translating allowed topologies: %v\", err)\n\t\t}\n\t\tsc.AllowedTopologies = newTopologies\n\t}\n\tsc.Parameters = params\n\treturn sc, nil\n}","line":{"from":76,"to":123}} {"id":100030910,"name":"TranslateInTreeInlineVolumeToCSI","signature":"func (t *vSphereCSITranslator) TranslateInTreeInlineVolumeToCSI(volume *v1.Volume, podNamespace string) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/vsphere_volume.go","code":"// TranslateInTreeInlineVolumeToCSI takes a Volume with VsphereVolume set from in-tree\n// and converts the VsphereVolume source to a CSIPersistentVolumeSource\nfunc (t *vSphereCSITranslator) TranslateInTreeInlineVolumeToCSI(volume *v1.Volume, podNamespace string) (*v1.PersistentVolume, error) {\n\tif volume == nil || volume.VsphereVolume == nil {\n\t\treturn nil, fmt.Errorf(\"volume is nil or VsphereVolume not defined on volume\")\n\t}\n\tpv := \u0026v1.PersistentVolume{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t// Must be unique per disk as it is used as the unique part of the\n\t\t\t// staging path\n\t\t\tName: fmt.Sprintf(\"%s-%s\", VSphereDriverName, volume.VsphereVolume.VolumePath),\n\t\t},\n\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\tPersistentVolumeSource: v1.PersistentVolumeSource{\n\t\t\t\tCSI: \u0026v1.CSIPersistentVolumeSource{\n\t\t\t\t\tDriver: VSphereDriverName,\n\t\t\t\t\tVolumeHandle: volume.VsphereVolume.VolumePath,\n\t\t\t\t\tFSType: volume.VsphereVolume.FSType,\n\t\t\t\t\tVolumeAttributes: make(map[string]string),\n\t\t\t\t},\n\t\t\t},\n\t\t\tAccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce},\n\t\t},\n\t}\n\tif volume.VsphereVolume.StoragePolicyName != \"\" {\n\t\tpv.Spec.CSI.VolumeAttributes[paramStoragePolicyName] = pv.Spec.VsphereVolume.StoragePolicyName\n\t}\n\treturn pv, nil\n}","line":{"from":125,"to":153}} {"id":100030911,"name":"TranslateInTreePVToCSI","signature":"func (t *vSphereCSITranslator) TranslateInTreePVToCSI(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/vsphere_volume.go","code":"// TranslateInTreePVToCSI takes a PV with VsphereVolume set from in-tree\n// and converts the VsphereVolume source to a CSIPersistentVolumeSource\nfunc (t *vSphereCSITranslator) TranslateInTreePVToCSI(pv *v1.PersistentVolume) (*v1.PersistentVolume, error) {\n\tif pv == nil || pv.Spec.VsphereVolume == nil {\n\t\treturn nil, fmt.Errorf(\"pv is nil or VsphereVolume not defined on pv\")\n\t}\n\tcsiSource := \u0026v1.CSIPersistentVolumeSource{\n\t\tDriver: VSphereDriverName,\n\t\tVolumeHandle: pv.Spec.VsphereVolume.VolumePath,\n\t\tFSType: pv.Spec.VsphereVolume.FSType,\n\t\tVolumeAttributes: make(map[string]string),\n\t}\n\tif pv.Spec.VsphereVolume.StoragePolicyName != \"\" {\n\t\tcsiSource.VolumeAttributes[paramStoragePolicyName] = pv.Spec.VsphereVolume.StoragePolicyName\n\t}\n\t// translate in-tree topology to CSI topology for migration\n\tif err := translateTopologyFromInTreevSphereToCSI(pv, vSphereCSITopologyZoneKey, vSphereCSITopologyRegionKey); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to translate topology: %v\", err)\n\t}\n\tpv.Spec.VsphereVolume = nil\n\tpv.Spec.CSI = csiSource\n\treturn pv, nil\n}","line":{"from":155,"to":177}} {"id":100030912,"name":"TranslateCSIPVToInTree","signature":"func (t *vSphereCSITranslator) TranslateCSIPVToInTree(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/vsphere_volume.go","code":"// TranslateCSIPVToInTree takes a PV with CSIPersistentVolumeSource set and\n// translates the vSphere CSI source to a vSphereVolume source.\nfunc (t *vSphereCSITranslator) TranslateCSIPVToInTree(pv *v1.PersistentVolume) (*v1.PersistentVolume, error) {\n\tif pv == nil || pv.Spec.CSI == nil {\n\t\treturn nil, fmt.Errorf(\"pv is nil or CSI source not defined on pv\")\n\t}\n\tcsiSource := pv.Spec.CSI\n\tvsphereVirtualDiskVolumeSource := \u0026v1.VsphereVirtualDiskVolumeSource{\n\t\tFSType: csiSource.FSType,\n\t}\n\tvolumeFilePath, ok := csiSource.VolumeAttributes[AttributeInitialVolumeFilepath]\n\tif ok {\n\t\tvsphereVirtualDiskVolumeSource.VolumePath = volumeFilePath\n\t}\n\t// translate CSI topology to In-tree topology for rollback compatibility.\n\tif err := translateTopologyFromCSIToInTreevSphere(pv, vSphereCSITopologyZoneKey, vSphereCSITopologyRegionKey); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to translate topology. PV:%+v. Error:%v\", *pv, err)\n\t}\n\tpv.Spec.CSI = nil\n\tpv.Spec.VsphereVolume = vsphereVirtualDiskVolumeSource\n\treturn pv, nil\n}","line":{"from":179,"to":200}} {"id":100030913,"name":"CanSupport","signature":"func (t *vSphereCSITranslator) CanSupport(pv *v1.PersistentVolume) bool","file":"staging/src/k8s.io/csi-translation-lib/plugins/vsphere_volume.go","code":"// CanSupport tests whether the plugin supports a given persistent volume\n// specification from the API.\nfunc (t *vSphereCSITranslator) CanSupport(pv *v1.PersistentVolume) bool {\n\treturn pv != nil \u0026\u0026 pv.Spec.VsphereVolume != nil\n}","line":{"from":202,"to":206}} {"id":100030914,"name":"CanSupportInline","signature":"func (t *vSphereCSITranslator) CanSupportInline(volume *v1.Volume) bool","file":"staging/src/k8s.io/csi-translation-lib/plugins/vsphere_volume.go","code":"// CanSupportInline tests whether the plugin supports a given inline volume\n// specification from the API.\nfunc (t *vSphereCSITranslator) CanSupportInline(volume *v1.Volume) bool {\n\treturn volume != nil \u0026\u0026 volume.VsphereVolume != nil\n}","line":{"from":208,"to":212}} {"id":100030915,"name":"GetInTreePluginName","signature":"func (t *vSphereCSITranslator) GetInTreePluginName() string","file":"staging/src/k8s.io/csi-translation-lib/plugins/vsphere_volume.go","code":"// GetInTreePluginName returns the name of the in-tree plugin driver\nfunc (t *vSphereCSITranslator) GetInTreePluginName() string {\n\treturn VSphereInTreePluginName\n}","line":{"from":214,"to":217}} {"id":100030916,"name":"GetCSIPluginName","signature":"func (t *vSphereCSITranslator) GetCSIPluginName() string","file":"staging/src/k8s.io/csi-translation-lib/plugins/vsphere_volume.go","code":"// GetCSIPluginName returns the name of the CSI plugin\nfunc (t *vSphereCSITranslator) GetCSIPluginName() string {\n\treturn VSphereDriverName\n}","line":{"from":219,"to":222}} {"id":100030917,"name":"RepairVolumeHandle","signature":"func (t *vSphereCSITranslator) RepairVolumeHandle(volumeHandle, nodeID string) (string, error)","file":"staging/src/k8s.io/csi-translation-lib/plugins/vsphere_volume.go","code":"// RepairVolumeHandle is needed in VerifyVolumesAttached on the external attacher when we need to do strict volume\n// handle matching to check VolumeAttachment attached status.\n// vSphere volume does not need patch to help verify whether that volume is attached.\nfunc (t *vSphereCSITranslator) RepairVolumeHandle(volumeHandle, nodeID string) (string, error) {\n\treturn volumeHandle, nil\n}","line":{"from":224,"to":229}} {"id":100030918,"name":"translateTopologyFromInTreevSphereToCSI","signature":"func translateTopologyFromInTreevSphereToCSI(pv *v1.PersistentVolume, csiTopologyKeyZone string, csiTopologyKeyRegion string) error","file":"staging/src/k8s.io/csi-translation-lib/plugins/vsphere_volume.go","code":"// translateTopologyFromInTreevSphereToCSI converts existing zone labels or in-tree vsphere topology to\n// vSphere CSI topology.\nfunc translateTopologyFromInTreevSphereToCSI(pv *v1.PersistentVolume, csiTopologyKeyZone string, csiTopologyKeyRegion string) error {\n\tzoneLabel, regionLabel := getTopologyLabel(pv)\n\n\t// If Zone kubernetes topology exist, replace it to use csiTopologyKeyZone\n\tzones := getTopologyValues(pv, zoneLabel)\n\tif len(zones) \u003e 0 {\n\t\treplaceTopology(pv, zoneLabel, csiTopologyKeyZone)\n\t} else {\n\t\t// if nothing is in the NodeAffinity, try to fetch the topology from PV labels\n\t\tif label, ok := pv.Labels[zoneLabel]; ok {\n\t\t\tif len(label) \u003e 0 {\n\t\t\t\taddTopology(pv, csiTopologyKeyZone, []string{label})\n\t\t\t}\n\t\t}\n\t}\n\n\t// If region kubernetes topology exist, replace it to use csiTopologyKeyRegion\n\tregions := getTopologyValues(pv, regionLabel)\n\tif len(regions) \u003e 0 {\n\t\treplaceTopology(pv, regionLabel, csiTopologyKeyRegion)\n\t} else {\n\t\t// if nothing is in the NodeAffinity, try to fetch the topology from PV labels\n\t\tif label, ok := pv.Labels[regionLabel]; ok {\n\t\t\tif len(label) \u003e 0 {\n\t\t\t\taddTopology(pv, csiTopologyKeyRegion, []string{label})\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":231,"to":262}} {"id":100030919,"name":"translateTopologyFromCSIToInTreevSphere","signature":"func translateTopologyFromCSIToInTreevSphere(pv *v1.PersistentVolume,","file":"staging/src/k8s.io/csi-translation-lib/plugins/vsphere_volume.go","code":"// translateTopologyFromCSIToInTreevSphere converts CSI zone/region affinity rules to in-tree vSphere zone/region labels\nfunc translateTopologyFromCSIToInTreevSphere(pv *v1.PersistentVolume,\n\tcsiTopologyKeyZone string, csiTopologyKeyRegion string) error {\n\tzoneLabel, regionLabel := getTopologyLabel(pv)\n\n\t// Replace all CSI topology to Kubernetes Zone label\n\terr := replaceTopology(pv, csiTopologyKeyZone, zoneLabel)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to replace CSI topology to Kubernetes topology, error: %v\", err)\n\t}\n\n\t// Replace all CSI topology to Kubernetes Region label\n\terr = replaceTopology(pv, csiTopologyKeyRegion, regionLabel)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to replace CSI topology to Kubernetes topology, error: %v\", err)\n\t}\n\n\tzoneVals := getTopologyValues(pv, zoneLabel)\n\tif len(zoneVals) \u003e 0 {\n\t\tif pv.Labels == nil {\n\t\t\tpv.Labels = make(map[string]string)\n\t\t}\n\t\t_, zoneOK := pv.Labels[zoneLabel]\n\t\tif !zoneOK {\n\t\t\tpv.Labels[zoneLabel] = zoneVals[0]\n\t\t}\n\t}\n\tregionVals := getTopologyValues(pv, regionLabel)\n\tif len(regionVals) \u003e 0 {\n\t\tif pv.Labels == nil {\n\t\t\tpv.Labels = make(map[string]string)\n\t\t}\n\t\t_, regionOK := pv.Labels[regionLabel]\n\t\tif !regionOK {\n\t\t\tpv.Labels[regionLabel] = regionVals[0]\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":264,"to":302}} {"id":100030920,"name":"New","signature":"func New() CSITranslator","file":"staging/src/k8s.io/csi-translation-lib/translate.go","code":"// New creates a new CSITranslator which does real translation\n// for \"in-tree plugins \u003c-\u003e csi drivers\"\nfunc New() CSITranslator {\n\treturn CSITranslator{}\n}","line":{"from":46,"to":50}} {"id":100030921,"name":"TranslateInTreeStorageClassToCSI","signature":"func (CSITranslator) TranslateInTreeStorageClassToCSI(inTreePluginName string, sc *storage.StorageClass) (*storage.StorageClass, error)","file":"staging/src/k8s.io/csi-translation-lib/translate.go","code":"// TranslateInTreeStorageClassToCSI takes in-tree Storage Class\n// and translates it to a set of parameters consumable by CSI plugin\nfunc (CSITranslator) TranslateInTreeStorageClassToCSI(inTreePluginName string, sc *storage.StorageClass) (*storage.StorageClass, error) {\n\tnewSC := sc.DeepCopy()\n\tfor _, curPlugin := range inTreePlugins {\n\t\tif inTreePluginName == curPlugin.GetInTreePluginName() {\n\t\t\treturn curPlugin.TranslateInTreeStorageClassToCSI(newSC)\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"could not find in-tree storage class parameter translation logic for %#v\", inTreePluginName)\n}","line":{"from":52,"to":62}} {"id":100030922,"name":"TranslateInTreeInlineVolumeToCSI","signature":"func (CSITranslator) TranslateInTreeInlineVolumeToCSI(volume *v1.Volume, podNamespace string) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/translate.go","code":"// TranslateInTreeInlineVolumeToCSI takes a inline volume and will translate\n// the in-tree volume source to a CSIPersistentVolumeSource (wrapped in a PV)\n// if the translation logic has been implemented.\nfunc (CSITranslator) TranslateInTreeInlineVolumeToCSI(volume *v1.Volume, podNamespace string) (*v1.PersistentVolume, error) {\n\tif volume == nil {\n\t\treturn nil, fmt.Errorf(\"persistent volume was nil\")\n\t}\n\tfor _, curPlugin := range inTreePlugins {\n\t\tif curPlugin.CanSupportInline(volume) {\n\t\t\tpv, err := curPlugin.TranslateInTreeInlineVolumeToCSI(volume, podNamespace)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\t// Inline volumes only support PersistentVolumeFilesystem (and not block).\n\t\t\t// If VolumeMode has not been set explicitly by plugin-specific\n\t\t\t// translator, set it to Filesystem here.\n\t\t\t// This is only necessary for inline volumes as the default PV\n\t\t\t// initialization that populates VolumeMode does not apply to inline volumes.\n\t\t\tif pv.Spec.VolumeMode == nil {\n\t\t\t\tvolumeMode := v1.PersistentVolumeFilesystem\n\t\t\t\tpv.Spec.VolumeMode = \u0026volumeMode\n\t\t\t}\n\t\t\treturn pv, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"could not find in-tree plugin translation logic for %#v\", volume.Name)\n}","line":{"from":64,"to":90}} {"id":100030923,"name":"TranslateInTreePVToCSI","signature":"func (CSITranslator) TranslateInTreePVToCSI(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/translate.go","code":"// TranslateInTreePVToCSI takes a persistent volume and will translate\n// the in-tree source to a CSI Source if the translation logic\n// has been implemented. The input persistent volume will not\n// be modified\nfunc (CSITranslator) TranslateInTreePVToCSI(pv *v1.PersistentVolume) (*v1.PersistentVolume, error) {\n\tif pv == nil {\n\t\treturn nil, errors.New(\"persistent volume was nil\")\n\t}\n\tcopiedPV := pv.DeepCopy()\n\tfor _, curPlugin := range inTreePlugins {\n\t\tif curPlugin.CanSupport(copiedPV) {\n\t\t\treturn curPlugin.TranslateInTreePVToCSI(copiedPV)\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"could not find in-tree plugin translation logic for %#v\", copiedPV.Name)\n}","line":{"from":92,"to":107}} {"id":100030924,"name":"TranslateCSIPVToInTree","signature":"func (CSITranslator) TranslateCSIPVToInTree(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)","file":"staging/src/k8s.io/csi-translation-lib/translate.go","code":"// TranslateCSIPVToInTree takes a PV with a CSI PersistentVolume Source and will translate\n// it to a in-tree Persistent Volume Source for the specific in-tree volume specified\n// by the `Driver` field in the CSI Source. The input PV object will not be modified.\nfunc (CSITranslator) TranslateCSIPVToInTree(pv *v1.PersistentVolume) (*v1.PersistentVolume, error) {\n\tif pv == nil || pv.Spec.CSI == nil {\n\t\treturn nil, errors.New(\"CSI persistent volume was nil\")\n\t}\n\tcopiedPV := pv.DeepCopy()\n\tfor driverName, curPlugin := range inTreePlugins {\n\t\tif copiedPV.Spec.CSI.Driver == driverName {\n\t\t\treturn curPlugin.TranslateCSIPVToInTree(copiedPV)\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"could not find in-tree plugin translation logic for %s\", copiedPV.Spec.CSI.Driver)\n}","line":{"from":109,"to":123}} {"id":100030925,"name":"IsMigratableIntreePluginByName","signature":"func (CSITranslator) IsMigratableIntreePluginByName(inTreePluginName string) bool","file":"staging/src/k8s.io/csi-translation-lib/translate.go","code":"// IsMigratableIntreePluginByName tests whether there is migration logic for the in-tree plugin\n// whose name matches the given name\nfunc (CSITranslator) IsMigratableIntreePluginByName(inTreePluginName string) bool {\n\tfor _, curPlugin := range inTreePlugins {\n\t\tif curPlugin.GetInTreePluginName() == inTreePluginName {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":125,"to":134}} {"id":100030926,"name":"IsMigratedCSIDriverByName","signature":"func (CSITranslator) IsMigratedCSIDriverByName(csiPluginName string) bool","file":"staging/src/k8s.io/csi-translation-lib/translate.go","code":"// IsMigratedCSIDriverByName tests whether there exists an in-tree plugin with logic\n// to migrate to the CSI driver with given name\nfunc (CSITranslator) IsMigratedCSIDriverByName(csiPluginName string) bool {\n\tif _, ok := inTreePlugins[csiPluginName]; ok {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":136,"to":143}} {"id":100030927,"name":"GetInTreePluginNameFromSpec","signature":"func (CSITranslator) GetInTreePluginNameFromSpec(pv *v1.PersistentVolume, vol *v1.Volume) (string, error)","file":"staging/src/k8s.io/csi-translation-lib/translate.go","code":"// GetInTreePluginNameFromSpec returns the plugin name\nfunc (CSITranslator) GetInTreePluginNameFromSpec(pv *v1.PersistentVolume, vol *v1.Volume) (string, error) {\n\tif pv != nil {\n\t\tfor _, curPlugin := range inTreePlugins {\n\t\t\tif curPlugin.CanSupport(pv) {\n\t\t\t\treturn curPlugin.GetInTreePluginName(), nil\n\t\t\t}\n\t\t}\n\t\treturn \"\", fmt.Errorf(\"could not find in-tree plugin name from persistent volume %v\", pv)\n\t} else if vol != nil {\n\t\tfor _, curPlugin := range inTreePlugins {\n\t\t\tif curPlugin.CanSupportInline(vol) {\n\t\t\t\treturn curPlugin.GetInTreePluginName(), nil\n\t\t\t}\n\t\t}\n\t\treturn \"\", fmt.Errorf(\"could not find in-tree plugin name from volume %v\", vol)\n\t} else {\n\t\treturn \"\", errors.New(\"both persistent volume and volume are nil\")\n\t}\n}","line":{"from":145,"to":164}} {"id":100030928,"name":"GetCSINameFromInTreeName","signature":"func (CSITranslator) GetCSINameFromInTreeName(pluginName string) (string, error)","file":"staging/src/k8s.io/csi-translation-lib/translate.go","code":"// GetCSINameFromInTreeName returns the name of a CSI driver that supersedes the\n// in-tree plugin with the given name\nfunc (CSITranslator) GetCSINameFromInTreeName(pluginName string) (string, error) {\n\tfor csiDriverName, curPlugin := range inTreePlugins {\n\t\tif curPlugin.GetInTreePluginName() == pluginName {\n\t\t\treturn csiDriverName, nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"could not find CSI Driver name for plugin %v\", pluginName)\n}","line":{"from":166,"to":175}} {"id":100030929,"name":"GetInTreeNameFromCSIName","signature":"func (CSITranslator) GetInTreeNameFromCSIName(pluginName string) (string, error)","file":"staging/src/k8s.io/csi-translation-lib/translate.go","code":"// GetInTreeNameFromCSIName returns the name of the in-tree plugin superseded by\n// a CSI driver with the given name\nfunc (CSITranslator) GetInTreeNameFromCSIName(pluginName string) (string, error) {\n\tif plugin, ok := inTreePlugins[pluginName]; ok {\n\t\treturn plugin.GetInTreePluginName(), nil\n\t}\n\treturn \"\", fmt.Errorf(\"could not find In-Tree driver name for CSI plugin %v\", pluginName)\n}","line":{"from":177,"to":184}} {"id":100030930,"name":"IsPVMigratable","signature":"func (CSITranslator) IsPVMigratable(pv *v1.PersistentVolume) bool","file":"staging/src/k8s.io/csi-translation-lib/translate.go","code":"// IsPVMigratable tests whether there is migration logic for the given Persistent Volume\nfunc (CSITranslator) IsPVMigratable(pv *v1.PersistentVolume) bool {\n\tfor _, curPlugin := range inTreePlugins {\n\t\tif curPlugin.CanSupport(pv) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":186,"to":194}} {"id":100030931,"name":"IsInlineMigratable","signature":"func (CSITranslator) IsInlineMigratable(vol *v1.Volume) bool","file":"staging/src/k8s.io/csi-translation-lib/translate.go","code":"// IsInlineMigratable tests whether there is Migration logic for the given Inline Volume\nfunc (CSITranslator) IsInlineMigratable(vol *v1.Volume) bool {\n\tfor _, curPlugin := range inTreePlugins {\n\t\tif curPlugin.CanSupportInline(vol) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":196,"to":204}} {"id":100030932,"name":"RepairVolumeHandle","signature":"func (CSITranslator) RepairVolumeHandle(driverName, volumeHandle, nodeID string) (string, error)","file":"staging/src/k8s.io/csi-translation-lib/translate.go","code":"// RepairVolumeHandle generates a correct volume handle based on node ID information.\nfunc (CSITranslator) RepairVolumeHandle(driverName, volumeHandle, nodeID string) (string, error) {\n\tif plugin, ok := inTreePlugins[driverName]; ok {\n\t\treturn plugin.RepairVolumeHandle(volumeHandle, nodeID)\n\t}\n\treturn \"\", fmt.Errorf(\"could not find In-Tree driver name for CSI plugin %v\", driverName)\n}","line":{"from":206,"to":212}} {"id":100030933,"name":"New","signature":"func New(","file":"staging/src/k8s.io/dynamic-resource-allocation/controller/controller.go","code":"// New creates a new controller.\nfunc New(\n\tctx context.Context,\n\tname string,\n\tdriver Driver,\n\tkubeClient kubernetes.Interface,\n\tinformerFactory informers.SharedInformerFactory) Controller {\n\tlogger := klog.LoggerWithName(klog.FromContext(ctx), \"resource controller\")\n\trcInformer := informerFactory.Resource().V1alpha2().ResourceClasses()\n\tclaimInformer := informerFactory.Resource().V1alpha2().ResourceClaims()\n\tschedulingCtxInformer := informerFactory.Resource().V1alpha2().PodSchedulingContexts()\n\n\teventBroadcaster := record.NewBroadcaster()\n\tgo func() {\n\t\t\u003c-ctx.Done()\n\t\teventBroadcaster.Shutdown()\n\t}()\n\t// TODO: use contextual logging in eventBroadcaster once it\n\t// supports it. There is a StartStructuredLogging API, but it\n\t// uses the global klog, which is worse than redirecting an unstructured\n\t// string into our logger, in particular during testing.\n\teventBroadcaster.StartLogging(func(format string, args ...interface{}) {\n\t\thelper, logger := logger.WithCallStackHelper()\n\t\thelper()\n\t\tlogger.V(2).Info(fmt.Sprintf(format, args...))\n\t})\n\teventBroadcaster.StartRecordingToSink(\u0026corev1types.EventSinkImpl{Interface: kubeClient.CoreV1().Events(v1.NamespaceAll)})\n\teventRecorder := eventBroadcaster.NewRecorder(scheme.Scheme,\n\t\tv1.EventSource{Component: fmt.Sprintf(\"resource driver %s\", name)})\n\n\t// The work queue contains either keys for claims or PodSchedulingContext objects.\n\tqueue := workqueue.NewNamedRateLimitingQueue(\n\t\tworkqueue.DefaultControllerRateLimiter(), fmt.Sprintf(\"%s-queue\", name))\n\n\t// The mutation cache acts as an additional layer for the informer\n\t// cache and after an update made by the controller returns a more\n\t// recent copy until the informer catches up.\n\tclaimInformerCache := claimInformer.Informer().GetIndexer()\n\tclaimCache := cache.NewIntegerResourceVersionMutationCache(claimInformerCache, claimInformerCache, 60*time.Second,\n\t\tfalse /* only cache updated claims that exist in the informer cache */)\n\n\tctrl := \u0026controller{\n\t\tctx: ctx,\n\t\tlogger: logger,\n\t\tname: name,\n\t\tfinalizer: name + \"/deletion-protection\",\n\t\tdriver: driver,\n\t\tkubeClient: kubeClient,\n\t\trcLister: rcInformer.Lister(),\n\t\trcSynced: rcInformer.Informer().HasSynced,\n\t\tclaimCache: claimCache,\n\t\tclaimSynced: claimInformer.Informer().HasSynced,\n\t\tschedulingCtxLister: schedulingCtxInformer.Lister(),\n\t\tschedulingCtxSynced: schedulingCtxInformer.Informer().HasSynced,\n\t\tqueue: queue,\n\t\teventRecorder: eventRecorder,\n\t}\n\n\tloggerV6 := logger.V(6)\n\tif loggerV6.Enabled() {\n\t\tresourceClaimLogger := klog.LoggerWithValues(loggerV6, \"type\", \"ResourceClaim\")\n\t\t_, _ = claimInformer.Informer().AddEventHandler(resourceEventHandlerFuncs(\u0026resourceClaimLogger, ctrl))\n\t\tschedulingCtxLogger := klog.LoggerWithValues(loggerV6, \"type\", \"PodSchedulingContext\")\n\t\t_, _ = schedulingCtxInformer.Informer().AddEventHandler(resourceEventHandlerFuncs(\u0026schedulingCtxLogger, ctrl))\n\t} else {\n\t\t_, _ = claimInformer.Informer().AddEventHandler(resourceEventHandlerFuncs(nil, ctrl))\n\t\t_, _ = schedulingCtxInformer.Informer().AddEventHandler(resourceEventHandlerFuncs(nil, ctrl))\n\t}\n\n\treturn ctrl\n}","line":{"from":150,"to":220}} {"id":100030934,"name":"resourceEventHandlerFuncs","signature":"func resourceEventHandlerFuncs(logger *klog.Logger, ctrl *controller) cache.ResourceEventHandlerFuncs","file":"staging/src/k8s.io/dynamic-resource-allocation/controller/controller.go","code":"func resourceEventHandlerFuncs(logger *klog.Logger, ctrl *controller) cache.ResourceEventHandlerFuncs {\n\treturn cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tctrl.add(logger, obj)\n\t\t},\n\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\tctrl.update(logger, oldObj, newObj)\n\t\t},\n\t\tDeleteFunc: ctrl.delete,\n\t}\n}","line":{"from":222,"to":232}} {"id":100030935,"name":"add","signature":"func (ctrl *controller) add(logger *klog.Logger, obj interface{})","file":"staging/src/k8s.io/dynamic-resource-allocation/controller/controller.go","code":"func (ctrl *controller) add(logger *klog.Logger, obj interface{}) {\n\tif logger != nil {\n\t\tlogger.Info(\"new object\", \"content\", prettyPrint(obj))\n\t}\n\tctrl.addNewOrUpdated(\"Adding new work item\", obj)\n}","line":{"from":239,"to":244}} {"id":100030936,"name":"update","signature":"func (ctrl *controller) update(logger *klog.Logger, oldObj, newObj interface{})","file":"staging/src/k8s.io/dynamic-resource-allocation/controller/controller.go","code":"func (ctrl *controller) update(logger *klog.Logger, oldObj, newObj interface{}) {\n\tif logger != nil {\n\t\tdiff := cmp.Diff(oldObj, newObj)\n\t\tlogger.Info(\"updated object\", \"content\", prettyPrint(newObj), \"diff\", diff)\n\t}\n\tctrl.addNewOrUpdated(\"Adding updated work item\", newObj)\n}","line":{"from":246,"to":252}} {"id":100030937,"name":"addNewOrUpdated","signature":"func (ctrl *controller) addNewOrUpdated(msg string, obj interface{})","file":"staging/src/k8s.io/dynamic-resource-allocation/controller/controller.go","code":"func (ctrl *controller) addNewOrUpdated(msg string, obj interface{}) {\n\tobjKey, err := getKey(obj)\n\tif err != nil {\n\t\tctrl.logger.Error(err, \"Failed to get key\", \"obj\", obj)\n\t\treturn\n\t}\n\tctrl.logger.V(5).Info(msg, \"key\", objKey)\n\tctrl.queue.Add(objKey)\n}","line":{"from":254,"to":262}} {"id":100030938,"name":"delete","signature":"func (ctrl *controller) delete(obj interface{})","file":"staging/src/k8s.io/dynamic-resource-allocation/controller/controller.go","code":"func (ctrl *controller) delete(obj interface{}) {\n\tobjKey, err := getKey(obj)\n\tif err != nil {\n\t\treturn\n\t}\n\tctrl.logger.V(5).Info(\"Removing deleted work item\", \"key\", objKey)\n\tctrl.queue.Forget(objKey)\n}","line":{"from":264,"to":271}} {"id":100030939,"name":"getKey","signature":"func getKey(obj interface{}) (string, error)","file":"staging/src/k8s.io/dynamic-resource-allocation/controller/controller.go","code":"func getKey(obj interface{}) (string, error) {\n\tobjKey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tprefix := \"\"\n\tswitch obj.(type) {\n\tcase *resourcev1alpha2.ResourceClaim:\n\t\tprefix = claimKeyPrefix\n\tcase *resourcev1alpha2.PodSchedulingContext:\n\t\tprefix = schedulingCtxKeyPrefix\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"unexpected object: %T\", obj)\n\t}\n\n\treturn prefix + objKey, nil\n}","line":{"from":273,"to":289}} {"id":100030940,"name":"Run","signature":"func (ctrl *controller) Run(workers int)","file":"staging/src/k8s.io/dynamic-resource-allocation/controller/controller.go","code":"// Run starts the controller.\nfunc (ctrl *controller) Run(workers int) {\n\tdefer ctrl.queue.ShutDown()\n\n\tctrl.logger.Info(\"Starting\", \"driver\", ctrl.name)\n\tdefer ctrl.logger.Info(\"Shutting down\", \"driver\", ctrl.name)\n\n\tstopCh := ctrl.ctx.Done()\n\n\tif !cache.WaitForCacheSync(stopCh, ctrl.rcSynced, ctrl.claimSynced, ctrl.schedulingCtxSynced) {\n\t\tctrl.logger.Error(nil, \"Cannot sync caches\")\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.Until(ctrl.sync, 0, stopCh)\n\t}\n\n\t\u003c-stopCh\n}","line":{"from":291,"to":310}} {"id":100030941,"name":"sync","signature":"func (ctrl *controller) sync()","file":"staging/src/k8s.io/dynamic-resource-allocation/controller/controller.go","code":"// sync is the main worker.\nfunc (ctrl *controller) sync() {\n\tkey, quit := ctrl.queue.Get()\n\tif quit {\n\t\treturn\n\t}\n\tdefer ctrl.queue.Done(key)\n\n\tlogger := klog.LoggerWithValues(ctrl.logger, \"key\", key)\n\tctx := klog.NewContext(ctrl.ctx, logger)\n\tlogger.V(4).Info(\"processing\")\n\tobj, err := ctrl.syncKey(ctx, key.(string))\n\tswitch err {\n\tcase nil:\n\t\tlogger.V(5).Info(\"completed\")\n\t\tctrl.queue.Forget(key)\n\tcase errRequeue:\n\t\tlogger.V(5).Info(\"requeue\")\n\t\tctrl.queue.AddRateLimited(key)\n\tcase errPeriodic:\n\t\tlogger.V(5).Info(\"recheck periodically\")\n\t\tctrl.queue.AddAfter(key, recheckDelay)\n\tdefault:\n\t\tlogger.Error(err, \"processing failed\")\n\t\tif obj != nil {\n\t\t\t// TODO: We don't know here *what* failed. Determine based on error?\n\t\t\tctrl.eventRecorder.Event(obj, v1.EventTypeWarning, \"Failed\", err.Error())\n\t\t}\n\t\tctrl.queue.AddRateLimited(key)\n\t}\n}","line":{"from":322,"to":352}} {"id":100030942,"name":"syncKey","signature":"func (ctrl *controller) syncKey(ctx context.Context, key string) (obj runtime.Object, finalErr error)","file":"staging/src/k8s.io/dynamic-resource-allocation/controller/controller.go","code":"// syncKey looks up a ResourceClaim by its key and processes it.\nfunc (ctrl *controller) syncKey(ctx context.Context, key string) (obj runtime.Object, finalErr error) {\n\tsep := strings.Index(key, \":\")\n\tif sep \u003c 0 {\n\t\treturn nil, fmt.Errorf(\"unexpected key: %s\", key)\n\t}\n\tprefix, object := key[0:sep+1], key[sep+1:]\n\tnamespace, name, err := cache.SplitMetaNamespaceKey(object)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch prefix {\n\tcase claimKeyPrefix:\n\t\tclaim, err := ctrl.getCachedClaim(ctx, object)\n\t\tif claim == nil || err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tobj, finalErr = claim, ctrl.syncClaim(ctx, claim)\n\tcase schedulingCtxKeyPrefix:\n\t\tschedulingCtx, err := ctrl.schedulingCtxLister.PodSchedulingContexts(namespace).Get(name)\n\t\tif err != nil {\n\t\t\tif k8serrors.IsNotFound(err) {\n\t\t\t\tklog.FromContext(ctx).V(5).Info(\"PodSchedulingContext was deleted, no need to process it\")\n\t\t\t\treturn nil, nil\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\tobj, finalErr = schedulingCtx, ctrl.syncPodSchedulingContexts(ctx, schedulingCtx)\n\t}\n\treturn\n}","line":{"from":354,"to":385}} {"id":100030943,"name":"getCachedClaim","signature":"func (ctrl *controller) getCachedClaim(ctx context.Context, key string) (*resourcev1alpha2.ResourceClaim, error)","file":"staging/src/k8s.io/dynamic-resource-allocation/controller/controller.go","code":"func (ctrl *controller) getCachedClaim(ctx context.Context, key string) (*resourcev1alpha2.ResourceClaim, error) {\n\tclaimObj, exists, err := ctrl.claimCache.GetByKey(key)\n\tif !exists || k8serrors.IsNotFound(err) {\n\t\tklog.FromContext(ctx).V(5).Info(\"ResourceClaim not found, no need to process it\")\n\t\treturn nil, nil\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclaim, ok := claimObj.(*resourcev1alpha2.ResourceClaim)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"internal error: got %T instead of *resourcev1alpha2.ResourceClaim from claim cache\", claimObj)\n\t}\n\treturn claim, nil\n}","line":{"from":387,"to":401}} {"id":100030944,"name":"syncClaim","signature":"func (ctrl *controller) syncClaim(ctx context.Context, claim *resourcev1alpha2.ResourceClaim) error","file":"staging/src/k8s.io/dynamic-resource-allocation/controller/controller.go","code":"// syncClaim determines which next action may be needed for a ResourceClaim\n// and does it.\nfunc (ctrl *controller) syncClaim(ctx context.Context, claim *resourcev1alpha2.ResourceClaim) error {\n\tvar err error\n\tlogger := klog.FromContext(ctx)\n\n\tif len(claim.Status.ReservedFor) \u003e 0 {\n\t\t// In use. Nothing that we can do for it now.\n\t\tif loggerV6 := logger.V(6); loggerV6.Enabled() {\n\t\t\tloggerV6.Info(\"ResourceClaim in use\", \"reservedFor\", claim.Status.ReservedFor)\n\t\t} else {\n\t\t\tlogger.V(5).Info(\"ResourceClaim in use\")\n\t\t}\n\t\treturn nil\n\t}\n\n\tif claim.DeletionTimestamp != nil ||\n\t\tclaim.Status.DeallocationRequested {\n\t\t// Ready for deallocation. We might have our finalizer set. The\n\t\t// finalizer is specific to the driver, therefore we know that\n\t\t// this claim is \"ours\" when the finalizer is set.\n\t\thasFinalizer := ctrl.hasFinalizer(claim)\n\t\tlogger.V(5).Info(\"ResourceClaim ready for deallocation\", \"deallocationRequested\", claim.Status.DeallocationRequested, \"deletionTimestamp\", claim.DeletionTimestamp, \"allocated\", claim.Status.Allocation != nil, \"hasFinalizer\", hasFinalizer)\n\t\tif hasFinalizer {\n\t\t\tclaim = claim.DeepCopy()\n\t\t\tif claim.Status.Allocation != nil {\n\t\t\t\t// Allocation was completed. Deallocate before proceeding.\n\t\t\t\tif err := ctrl.driver.Deallocate(ctx, claim); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"deallocate: %v\", err)\n\t\t\t\t}\n\t\t\t\tclaim.Status.Allocation = nil\n\t\t\t\tclaim.Status.DriverName = \"\"\n\t\t\t\tclaim.Status.DeallocationRequested = false\n\t\t\t\tclaim, err = ctrl.kubeClient.ResourceV1alpha2().ResourceClaims(claim.Namespace).UpdateStatus(ctx, claim, metav1.UpdateOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"remove allocation: %v\", err)\n\t\t\t\t}\n\t\t\t\tctrl.claimCache.Mutation(claim)\n\t\t\t} else {\n\t\t\t\t// Ensure that there is no on-going allocation.\n\t\t\t\tif err := ctrl.driver.Deallocate(ctx, claim); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"stop allocation: %v\", err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif claim.Status.DeallocationRequested {\n\t\t\t\t// Still need to remove it.\n\t\t\t\tclaim.Status.DeallocationRequested = false\n\t\t\t\tclaim, err = ctrl.kubeClient.ResourceV1alpha2().ResourceClaims(claim.Namespace).UpdateStatus(ctx, claim, metav1.UpdateOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"remove deallocation: %v\", err)\n\t\t\t\t}\n\t\t\t\tctrl.claimCache.Mutation(claim)\n\t\t\t}\n\n\t\t\tclaim.Finalizers = ctrl.removeFinalizer(claim.Finalizers)\n\t\t\tclaim, err = ctrl.kubeClient.ResourceV1alpha2().ResourceClaims(claim.Namespace).Update(ctx, claim, metav1.UpdateOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"remove finalizer: %v\", err)\n\t\t\t}\n\t\t\tctrl.claimCache.Mutation(claim)\n\t\t}\n\n\t\t// Nothing further to do. The apiserver should remove it shortly.\n\t\treturn nil\n\n\t}\n\n\tif claim.Status.Allocation != nil {\n\t\tlogger.V(5).Info(\"ResourceClaim is allocated\")\n\t\treturn nil\n\t}\n\tif claim.Spec.AllocationMode != resourcev1alpha2.AllocationModeImmediate {\n\t\tlogger.V(5).Info(\"ResourceClaim waiting for first consumer\")\n\t\treturn nil\n\t}\n\n\t// We need the ResourceClass to determine whether we should allocate it.\n\tclass, err := ctrl.rcLister.Get(claim.Spec.ResourceClassName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif class.DriverName != ctrl.name {\n\t\t// Not ours *at the moment*. This can change, so requeue and\n\t\t// check again. We could trigger a faster check when the\n\t\t// ResourceClass changes, but that shouldn't occur much in\n\t\t// practice and thus isn't worth the effort.\n\t\t//\n\t\t// We use exponential backoff because it is unlikely that\n\t\t// the ResourceClass changes much.\n\t\tlogger.V(5).Info(\"ResourceClaim is handled by other driver\", \"driver\", class.DriverName)\n\t\treturn errRequeue\n\t}\n\n\t// Check parameters.\n\tclaimParameters, classParameters, err := ctrl.getParameters(ctx, claim, class)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn ctrl.allocateClaim(ctx, claim, claimParameters, class, classParameters, \"\", nil)\n}","line":{"from":403,"to":504}} {"id":100030945,"name":"getParameters","signature":"func (ctrl *controller) getParameters(ctx context.Context, claim *resourcev1alpha2.ResourceClaim, class *resourcev1alpha2.ResourceClass) (claimParameters, classParameters interface{}, err error)","file":"staging/src/k8s.io/dynamic-resource-allocation/controller/controller.go","code":"func (ctrl *controller) getParameters(ctx context.Context, claim *resourcev1alpha2.ResourceClaim, class *resourcev1alpha2.ResourceClass) (claimParameters, classParameters interface{}, err error) {\n\tclassParameters, err = ctrl.driver.GetClassParameters(ctx, class)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"class parameters %s: %v\", class.ParametersRef, err)\n\t\treturn\n\t}\n\tclaimParameters, err = ctrl.driver.GetClaimParameters(ctx, claim, class, classParameters)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"claim parameters %s: %v\", claim.Spec.ParametersRef, err)\n\t\treturn\n\t}\n\treturn\n}","line":{"from":506,"to":518}} {"id":100030946,"name":"allocateClaim","signature":"func (ctrl *controller) allocateClaim(ctx context.Context,","file":"staging/src/k8s.io/dynamic-resource-allocation/controller/controller.go","code":"func (ctrl *controller) allocateClaim(ctx context.Context,\n\tclaim *resourcev1alpha2.ResourceClaim, claimParameters interface{},\n\tclass *resourcev1alpha2.ResourceClass, classParameters interface{},\n\tselectedNode string,\n\tselectedUser *resourcev1alpha2.ResourceClaimConsumerReference) error {\n\tlogger := klog.FromContext(ctx)\n\n\tif claim.Status.Allocation != nil {\n\t\t// This can happen when two PodSchedulingContext objects trigger\n\t\t// allocation attempts (first one wins) or when we see the\n\t\t// update of the PodSchedulingContext object.\n\t\tlogger.V(5).Info(\"Claim already allocated, nothing to do\")\n\t\treturn nil\n\t}\n\n\tclaim = claim.DeepCopy()\n\tif !ctrl.hasFinalizer(claim) {\n\t\t// Set finalizer before doing anything. We continue with the updated claim.\n\t\tlogger.V(5).Info(\"Adding finalizer\")\n\t\tclaim.Finalizers = append(claim.Finalizers, ctrl.finalizer)\n\t\tvar err error\n\t\tclaim, err = ctrl.kubeClient.ResourceV1alpha2().ResourceClaims(claim.Namespace).Update(ctx, claim, metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"add finalizer: %v\", err)\n\t\t}\n\t\tctrl.claimCache.Mutation(claim)\n\t}\n\n\tlogger.V(5).Info(\"Allocating\")\n\tallocation, err := ctrl.driver.Allocate(ctx, claim, claimParameters, class, classParameters, selectedNode)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"allocate: %v\", err)\n\t}\n\tclaim.Status.Allocation = allocation\n\tclaim.Status.DriverName = ctrl.name\n\tif selectedUser != nil {\n\t\tclaim.Status.ReservedFor = append(claim.Status.ReservedFor, *selectedUser)\n\t}\n\tlogger.V(6).Info(\"Updating claim after allocation\", \"claim\", claim)\n\tclaim, err = ctrl.kubeClient.ResourceV1alpha2().ResourceClaims(claim.Namespace).UpdateStatus(ctx, claim, metav1.UpdateOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"add allocation: %v\", err)\n\t}\n\tctrl.claimCache.Mutation(claim)\n\treturn nil\n}","line":{"from":520,"to":565}} {"id":100030947,"name":"checkPodClaim","signature":"func (ctrl *controller) checkPodClaim(ctx context.Context, pod *v1.Pod, podClaim v1.PodResourceClaim) (*ClaimAllocation, error)","file":"staging/src/k8s.io/dynamic-resource-allocation/controller/controller.go","code":"func (ctrl *controller) checkPodClaim(ctx context.Context, pod *v1.Pod, podClaim v1.PodResourceClaim) (*ClaimAllocation, error) {\n\tclaimName := resourceclaim.Name(pod, \u0026podClaim)\n\tkey := pod.Namespace + \"/\" + claimName\n\tclaim, err := ctrl.getCachedClaim(ctx, key)\n\tif claim == nil || err != nil {\n\t\treturn nil, err\n\t}\n\tif podClaim.Source.ResourceClaimTemplateName != nil {\n\t\tif err := resourceclaim.IsForPod(pod, claim); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif claim.Spec.AllocationMode != resourcev1alpha2.AllocationModeWaitForFirstConsumer {\n\t\t// Nothing to do for it as part of pod scheduling.\n\t\treturn nil, nil\n\t}\n\tclass, err := ctrl.rcLister.Get(claim.Spec.ResourceClassName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif class.DriverName != ctrl.name {\n\t\treturn nil, nil\n\t}\n\t// Check parameters.\n\tclaimParameters, classParameters, err := ctrl.getParameters(ctx, claim, class)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026ClaimAllocation{\n\t\tPodClaimName: podClaim.Name,\n\t\tClaim: claim,\n\t\tClass: class,\n\t\tClaimParameters: claimParameters,\n\t\tClassParameters: classParameters,\n\t}, nil\n}","line":{"from":567,"to":602}} {"id":100030948,"name":"syncPodSchedulingContexts","signature":"func (ctrl *controller) syncPodSchedulingContexts(ctx context.Context, schedulingCtx *resourcev1alpha2.PodSchedulingContext) error","file":"staging/src/k8s.io/dynamic-resource-allocation/controller/controller.go","code":"// syncPodSchedulingContext determines which next action may be needed for a PodSchedulingContext object\n// and does it.\nfunc (ctrl *controller) syncPodSchedulingContexts(ctx context.Context, schedulingCtx *resourcev1alpha2.PodSchedulingContext) error {\n\tlogger := klog.FromContext(ctx)\n\n\t// Ignore deleted objects.\n\tif schedulingCtx.DeletionTimestamp != nil {\n\t\tlogger.V(5).Info(\"PodSchedulingContext marked for deletion\")\n\t\treturn nil\n\t}\n\n\tif schedulingCtx.Spec.SelectedNode == \"\" \u0026\u0026\n\t\tlen(schedulingCtx.Spec.PotentialNodes) == 0 {\n\t\t// Nothing to do? Shouldn't occur.\n\t\tlogger.V(5).Info(\"Waiting for scheduler to set fields\")\n\t\treturn nil\n\t}\n\n\t// Check pod.\n\t// TODO (?): use an informer - only useful when many (most?) pods have claims\n\t// TODO (?): let the scheduler copy all claim names + UIDs into PodSchedulingContext - then we don't need the pod\n\tpod, err := ctrl.kubeClient.CoreV1().Pods(schedulingCtx.Namespace).Get(ctx, schedulingCtx.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\tif pod.DeletionTimestamp != nil {\n\t\tlogger.V(5).Info(\"Pod marked for deletion\")\n\t\treturn nil\n\t}\n\n\t// Still the owner?\n\tif !metav1.IsControlledBy(schedulingCtx, pod) {\n\t\t// Must be obsolete object, do nothing for it.\n\t\tlogger.V(5).Info(\"Pod not owner, PodSchedulingContext is obsolete\")\n\t\treturn nil\n\t}\n\n\t// Find all pending claims that are owned by us. We bail out if any of the pre-requisites\n\t// for pod scheduling (claims exist, classes exist, parameters exist) are not met.\n\t// The scheduler will do the same, except for checking parameters, so usually\n\t// everything should be ready once the PodSchedulingContext object exists.\n\tvar claims claimAllocations\n\tfor _, podClaim := range pod.Spec.ResourceClaims {\n\t\tdelayed, err := ctrl.checkPodClaim(ctx, pod, podClaim)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"pod claim %s: %v\", podClaim.Name, err)\n\t\t}\n\t\tif delayed == nil {\n\t\t\t// Nothing to do for it. This can change, so keep checking.\n\t\t\tcontinue\n\t\t}\n\t\tclaims = append(claims, delayed)\n\t}\n\tif len(claims) == 0 {\n\t\tlogger.V(5).Info(\"Found no pending pod claims\")\n\t\treturn errPeriodic\n\t}\n\n\t// Check current resource availability *before* triggering the\n\t// allocations. If we find that any of the claims cannot be allocated\n\t// for the selected node, we don't need to try for the others either\n\t// and shouldn't, because those allocations might have to be undone to\n\t// pick a better node. If we don't need to allocate now, then we'll\n\t// simply report back the gather information.\n\tif len(schedulingCtx.Spec.PotentialNodes) \u003e 0 {\n\t\tif err := ctrl.driver.UnsuitableNodes(ctx, pod, claims, schedulingCtx.Spec.PotentialNodes); err != nil {\n\t\t\treturn fmt.Errorf(\"checking potential nodes: %v\", err)\n\t\t}\n\t}\n\tselectedNode := schedulingCtx.Spec.SelectedNode\n\tlogger.V(5).Info(\"pending pod claims\", \"claims\", claims, \"selectedNode\", selectedNode)\n\tif selectedNode != \"\" {\n\t\tunsuitable := false\n\t\tfor _, delayed := range claims {\n\t\t\tif hasString(delayed.UnsuitableNodes, selectedNode) {\n\t\t\t\tunsuitable = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif unsuitable {\n\t\t\tlogger.V(2).Info(\"skipping allocation for unsuitable selected node\", \"node\", selectedNode)\n\t\t} else {\n\t\t\tlogger.V(2).Info(\"allocation for selected node\", \"node\", selectedNode)\n\t\t\tselectedUser := \u0026resourcev1alpha2.ResourceClaimConsumerReference{\n\t\t\t\tResource: \"pods\",\n\t\t\t\tName: pod.Name,\n\t\t\t\tUID: pod.UID,\n\t\t\t}\n\t\t\tfor _, delayed := range claims {\n\t\t\t\tif err := ctrl.allocateClaim(ctx, delayed.Claim, delayed.ClaimParameters, delayed.Class, delayed.ClassParameters, selectedNode, selectedUser); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"allocation of pod claim %s failed: %v\", delayed.PodClaimName, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now update unsuitable nodes. This is useful information for the scheduler even if\n\t// we managed to allocate because we might have to undo that.\n\t// TODO: replace with patching the array. We can do that without race conditions\n\t// because each driver is responsible for its own entries.\n\tmodified := false\n\tschedulingCtx = schedulingCtx.DeepCopy()\n\tfor _, delayed := range claims {\n\t\ti := findClaim(schedulingCtx.Status.ResourceClaims, delayed.PodClaimName)\n\t\tif i \u003c 0 {\n\t\t\t// Add new entry.\n\t\t\tschedulingCtx.Status.ResourceClaims = append(schedulingCtx.Status.ResourceClaims,\n\t\t\t\tresourcev1alpha2.ResourceClaimSchedulingStatus{\n\t\t\t\t\tName: delayed.PodClaimName,\n\t\t\t\t\tUnsuitableNodes: delayed.UnsuitableNodes,\n\t\t\t\t})\n\t\t\tmodified = true\n\t\t} else if stringsDiffer(schedulingCtx.Status.ResourceClaims[i].UnsuitableNodes, delayed.UnsuitableNodes) {\n\t\t\t// Update existing entry.\n\t\t\tschedulingCtx.Status.ResourceClaims[i].UnsuitableNodes = delayed.UnsuitableNodes\n\t\t\tmodified = true\n\t\t}\n\t}\n\tif modified {\n\t\tlogger.V(6).Info(\"Updating pod scheduling with modified unsuitable nodes\", \"podSchedulingCtx\", schedulingCtx)\n\t\tif _, err := ctrl.kubeClient.ResourceV1alpha2().PodSchedulingContexts(schedulingCtx.Namespace).UpdateStatus(ctx, schedulingCtx, metav1.UpdateOptions{}); err != nil {\n\t\t\treturn fmt.Errorf(\"update unsuitable node status: %v\", err)\n\t\t}\n\t}\n\n\t// We must keep the object in our queue and keep updating the\n\t// UnsuitableNodes fields.\n\treturn errPeriodic\n}","line":{"from":604,"to":733}} {"id":100030949,"name":"MarshalLog","signature":"func (claims claimAllocations) MarshalLog() interface{}","file":"staging/src/k8s.io/dynamic-resource-allocation/controller/controller.go","code":"// MarshalLog replaces the pointers with the actual structs because\n// we care about the content, not the pointer values.\nfunc (claims claimAllocations) MarshalLog() interface{} {\n\tcontent := make([]ClaimAllocation, 0, len(claims))\n\tfor _, claim := range claims {\n\t\tcontent = append(content, *claim)\n\t}\n\treturn content\n}","line":{"from":737,"to":745}} {"id":100030950,"name":"findClaim","signature":"func findClaim(claims []resourcev1alpha2.ResourceClaimSchedulingStatus, podClaimName string) int","file":"staging/src/k8s.io/dynamic-resource-allocation/controller/controller.go","code":"// findClaim returns the index of the specified pod claim, -1 if not found.\nfunc findClaim(claims []resourcev1alpha2.ResourceClaimSchedulingStatus, podClaimName string) int {\n\tfor i := range claims {\n\t\tif claims[i].Name == podClaimName {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}","line":{"from":749,"to":757}} {"id":100030951,"name":"hasString","signature":"func hasString(strings []string, str string) bool","file":"staging/src/k8s.io/dynamic-resource-allocation/controller/controller.go","code":"// hasString checks for a string in a slice.\nfunc hasString(strings []string, str string) bool {\n\tfor _, s := range strings {\n\t\tif s == str {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":759,"to":767}} {"id":100030952,"name":"stringsDiffer","signature":"func stringsDiffer(a, b []string) bool","file":"staging/src/k8s.io/dynamic-resource-allocation/controller/controller.go","code":"// stringsDiffer does a strict comparison of two string arrays, order of entries matters.\nfunc stringsDiffer(a, b []string) bool {\n\tif len(a) != len(b) {\n\t\treturn true\n\t}\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":769,"to":780}} {"id":100030953,"name":"hasFinalizer","signature":"func (ctrl *controller) hasFinalizer(claim *resourcev1alpha2.ResourceClaim) bool","file":"staging/src/k8s.io/dynamic-resource-allocation/controller/controller.go","code":"// hasFinalizer checks if the claim has the finalizer of the driver.\nfunc (ctrl *controller) hasFinalizer(claim *resourcev1alpha2.ResourceClaim) bool {\n\tfor _, finalizer := range claim.Finalizers {\n\t\tif finalizer == ctrl.finalizer {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":782,"to":790}} {"id":100030954,"name":"removeFinalizer","signature":"func (ctrl *controller) removeFinalizer(in []string) []string","file":"staging/src/k8s.io/dynamic-resource-allocation/controller/controller.go","code":"// removeFinalizer creates a new slice without the finalizer of the driver.\nfunc (ctrl *controller) removeFinalizer(in []string) []string {\n\tout := make([]string, 0, len(in))\n\tfor _, finalizer := range in {\n\t\tif finalizer != ctrl.finalizer {\n\t\t\tout = append(out, finalizer)\n\t\t}\n\t}\n\tif len(out) == 0 {\n\t\treturn nil\n\t}\n\treturn out\n}","line":{"from":792,"to":804}} {"id":100030955,"name":"prettyPrint","signature":"func prettyPrint(obj interface{}) string","file":"staging/src/k8s.io/dynamic-resource-allocation/controller/controller.go","code":"// prettyPrint formats arbitrary objects as JSON or, if that fails, with Sprintf.\nfunc prettyPrint(obj interface{}) string {\n\tbuffer, err := json.Marshal(obj)\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"%s\", obj)\n\t}\n\treturn string(buffer)\n}","line":{"from":806,"to":813}} {"id":100030956,"name":"DriverName","signature":"func DriverName(driverName string) Option","file":"staging/src/k8s.io/dynamic-resource-allocation/kubeletplugin/draplugin.go","code":"// DriverName defines the driver name for the dynamic resource allocation driver.\n// Must be set.\nfunc DriverName(driverName string) Option {\n\treturn func(o *options) error {\n\t\to.driverName = driverName\n\t\treturn nil\n\t}\n}","line":{"from":51,"to":58}} {"id":100030957,"name":"Logger","signature":"func Logger(logger klog.Logger) Option","file":"staging/src/k8s.io/dynamic-resource-allocation/kubeletplugin/draplugin.go","code":"// Logger overrides the default klog.Background logger.\nfunc Logger(logger klog.Logger) Option {\n\treturn func(o *options) error {\n\t\to.logger = logger\n\t\treturn nil\n\t}\n}","line":{"from":60,"to":66}} {"id":100030958,"name":"GRPCVerbosity","signature":"func GRPCVerbosity(level int) Option","file":"staging/src/k8s.io/dynamic-resource-allocation/kubeletplugin/draplugin.go","code":"// GRPCVerbosity sets the verbosity for logging gRPC calls. Default is 4. A negative\n// value disables logging.\nfunc GRPCVerbosity(level int) Option {\n\treturn func(o *options) error {\n\t\to.grpcVerbosity = level\n\t\treturn nil\n\t}\n}","line":{"from":68,"to":75}} {"id":100030959,"name":"RegistrarSocketPath","signature":"func RegistrarSocketPath(path string) Option","file":"staging/src/k8s.io/dynamic-resource-allocation/kubeletplugin/draplugin.go","code":"// RegistrarSocketPath sets the file path for a Unix domain socket.\n// If RegistrarListener is not used, then Start will remove\n// a file at that path, should one exist, and creates a socket\n// itself. Otherwise it uses the provided listener and only\n// removes the socket at the specified path during shutdown.\n//\n// At least one of these two options is required.\nfunc RegistrarSocketPath(path string) Option {\n\treturn func(o *options) error {\n\t\to.pluginRegistrationEndpoint.path = path\n\t\treturn nil\n\t}\n}","line":{"from":77,"to":89}} {"id":100030960,"name":"RegistrarListener","signature":"func RegistrarListener(listener net.Listener) Option","file":"staging/src/k8s.io/dynamic-resource-allocation/kubeletplugin/draplugin.go","code":"// RegistrarListener sets an already created listener for the plugin\n// registrarion API. Can be combined with RegistrarSocketPath.\n//\n// At least one of these two options is required.\nfunc RegistrarListener(listener net.Listener) Option {\n\treturn func(o *options) error {\n\t\to.pluginRegistrationEndpoint.listener = listener\n\t\treturn nil\n\t}\n}","line":{"from":91,"to":100}} {"id":100030961,"name":"PluginSocketPath","signature":"func PluginSocketPath(path string) Option","file":"staging/src/k8s.io/dynamic-resource-allocation/kubeletplugin/draplugin.go","code":"// PluginSocketPath sets the file path for a Unix domain socket.\n// If PluginListener is not used, then Start will remove\n// a file at that path, should one exist, and creates a socket\n// itself. Otherwise it uses the provided listener and only\n// removes the socket at the specified path during shutdown.\n//\n// At least one of these two options is required.\nfunc PluginSocketPath(path string) Option {\n\treturn func(o *options) error {\n\t\to.draEndpoint.path = path\n\t\treturn nil\n\t}\n}","line":{"from":102,"to":114}} {"id":100030962,"name":"PluginListener","signature":"func PluginListener(listener net.Listener) Option","file":"staging/src/k8s.io/dynamic-resource-allocation/kubeletplugin/draplugin.go","code":"// PluginListener sets an already created listener for the dynamic resource\n// allocation plugin API. Can be combined with PluginSocketPath.\n//\n// At least one of these two options is required.\nfunc PluginListener(listener net.Listener) Option {\n\treturn func(o *options) error {\n\t\to.draEndpoint.listener = listener\n\t\treturn nil\n\t}\n}","line":{"from":116,"to":125}} {"id":100030963,"name":"KubeletPluginSocketPath","signature":"func KubeletPluginSocketPath(path string) Option","file":"staging/src/k8s.io/dynamic-resource-allocation/kubeletplugin/draplugin.go","code":"// KubeletPluginSocketPath defines how kubelet will connect to the dynamic\n// resource allocation plugin. This corresponds to PluginSocketPath, except\n// that PluginSocketPath defines the path in the filesystem of the caller and\n// KubeletPluginSocketPath in the filesystem of kubelet.\nfunc KubeletPluginSocketPath(path string) Option {\n\treturn func(o *options) error {\n\t\to.draAddress = path\n\t\treturn nil\n\t}\n}","line":{"from":127,"to":136}} {"id":100030964,"name":"GRPCInterceptor","signature":"func GRPCInterceptor(interceptor grpc.UnaryServerInterceptor) Option","file":"staging/src/k8s.io/dynamic-resource-allocation/kubeletplugin/draplugin.go","code":"// GRPCInterceptor is called for each incoming gRPC method call.\nfunc GRPCInterceptor(interceptor grpc.UnaryServerInterceptor) Option {\n\treturn func(o *options) error {\n\t\to.interceptor = interceptor\n\t\treturn nil\n\t}\n}","line":{"from":138,"to":144}} {"id":100030965,"name":"Start","signature":"func Start(nodeServer drapbv1.NodeServer, opts ...Option) (result DRAPlugin, finalErr error)","file":"staging/src/k8s.io/dynamic-resource-allocation/kubeletplugin/draplugin.go","code":"// Start sets up two gRPC servers (one for registration, one for the DRA node\n// client).\nfunc Start(nodeServer drapbv1.NodeServer, opts ...Option) (result DRAPlugin, finalErr error) {\n\td := \u0026draPlugin{}\n\n\to := options{\n\t\tlogger: klog.Background(),\n\t\tgrpcVerbosity: 4,\n\t}\n\tfor _, option := range opts {\n\t\tif err := option(\u0026o); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif o.driverName == \"\" {\n\t\treturn nil, errors.New(\"driver name must be set\")\n\t}\n\tif o.draAddress == \"\" {\n\t\treturn nil, errors.New(\"DRA address must be set\")\n\t}\n\tvar emptyEndpoint endpoint\n\tif o.draEndpoint == emptyEndpoint {\n\t\treturn nil, errors.New(\"a Unix domain socket path and/or listener must be set for the kubelet plugin\")\n\t}\n\tif o.pluginRegistrationEndpoint == emptyEndpoint {\n\t\treturn nil, errors.New(\"a Unix domain socket path and/or listener must be set for the registrar\")\n\t}\n\n\t// Run the node plugin gRPC server first to ensure that it is ready.\n\tplugin, err := startGRPCServer(klog.LoggerWithName(o.logger, \"dra\"), o.grpcVerbosity, o.interceptor, o.draEndpoint, func(grpcServer *grpc.Server) {\n\t\tdrapbv1.RegisterNodeServer(grpcServer, nodeServer)\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"start node client: %v\", err)\n\t}\n\td.plugin = plugin\n\tdefer func() {\n\t\t// Clean up if we didn't finish succcessfully.\n\t\tif r := recover(); r != nil {\n\t\t\tplugin.stop()\n\t\t\tpanic(r)\n\t\t}\n\t\tif finalErr != nil {\n\t\t\tplugin.stop()\n\t\t}\n\t}()\n\n\t// Now make it available to kubelet.\n\tregistrar, err := startRegistrar(klog.LoggerWithName(o.logger, \"registrar\"), o.grpcVerbosity, o.interceptor, o.driverName, o.draAddress, o.pluginRegistrationEndpoint)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"start registrar: %v\", err)\n\t}\n\td.registrar = registrar\n\n\treturn d, nil\n}","line":{"from":163,"to":219}} {"id":100030966,"name":"Stop","signature":"func (d *draPlugin) Stop()","file":"staging/src/k8s.io/dynamic-resource-allocation/kubeletplugin/draplugin.go","code":"func (d *draPlugin) Stop() {\n\tif d == nil {\n\t\treturn\n\t}\n\td.registrar.stop()\n\td.plugin.stop()\n}","line":{"from":221,"to":227}} {"id":100030967,"name":"RegistrationStatus","signature":"func (d *draPlugin) RegistrationStatus() *registerapi.RegistrationStatus","file":"staging/src/k8s.io/dynamic-resource-allocation/kubeletplugin/draplugin.go","code":"func (d *draPlugin) RegistrationStatus() *registerapi.RegistrationStatus {\n\tif d.registrar == nil {\n\t\treturn nil\n\t}\n\treturn d.registrar.status\n}","line":{"from":229,"to":234}} {"id":100030968,"name":"internal","signature":"func (d *draPlugin) internal() {}","file":"staging/src/k8s.io/dynamic-resource-allocation/kubeletplugin/draplugin.go","code":"func (d *draPlugin) internal() {}","line":{"from":236,"to":236}} {"id":100030969,"name":"startRegistrar","signature":"func startRegistrar(logger klog.Logger, grpcVerbosity int, interceptor grpc.UnaryServerInterceptor, driverName string, endpoint string, pluginRegistrationEndpoint endpoint) (*nodeRegistrar, error)","file":"staging/src/k8s.io/dynamic-resource-allocation/kubeletplugin/noderegistrar.go","code":"// startRegistrar returns a running instance.\nfunc startRegistrar(logger klog.Logger, grpcVerbosity int, interceptor grpc.UnaryServerInterceptor, driverName string, endpoint string, pluginRegistrationEndpoint endpoint) (*nodeRegistrar, error) {\n\tn := \u0026nodeRegistrar{\n\t\tlogger: logger,\n\t\tregistrationServer: registrationServer{\n\t\t\tdriverName: driverName,\n\t\t\tendpoint: endpoint,\n\t\t\tsupportedVersions: []string{\"1.0.0\"}, // TODO: is this correct?\n\t\t},\n\t}\n\ts, err := startGRPCServer(logger, grpcVerbosity, interceptor, pluginRegistrationEndpoint, func(grpcServer *grpc.Server) {\n\t\tregisterapi.RegisterRegistrationServer(grpcServer, n)\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"start gRPC server: %v\", err)\n\t}\n\tn.server = s\n\treturn n, nil\n}","line":{"from":33,"to":51}} {"id":100030970,"name":"stop","signature":"func (s *nodeRegistrar) stop()","file":"staging/src/k8s.io/dynamic-resource-allocation/kubeletplugin/noderegistrar.go","code":"// stop ensures that the registrar is not running anymore and cleans up all resources.\n// It is idempotent and may be called with a nil pointer.\nfunc (s *nodeRegistrar) stop() {\n\tif s == nil {\n\t\treturn\n\t}\n\ts.server.stop()\n}","line":{"from":53,"to":60}} {"id":100030971,"name":"startGRPCServer","signature":"func startGRPCServer(logger klog.Logger, grpcVerbosity int, interceptor grpc.UnaryServerInterceptor, endpoint endpoint, services ...registerService) (*grpcServer, error)","file":"staging/src/k8s.io/dynamic-resource-allocation/kubeletplugin/nonblockinggrpcserver.go","code":"// startGRPCServer sets up the GRPC server on a Unix domain socket and spawns a goroutine\n// which handles requests for arbitrary services.\nfunc startGRPCServer(logger klog.Logger, grpcVerbosity int, interceptor grpc.UnaryServerInterceptor, endpoint endpoint, services ...registerService) (*grpcServer, error) {\n\ts := \u0026grpcServer{\n\t\tlogger: logger,\n\t\tendpoint: endpoint,\n\t\tgrpcVerbosity: grpcVerbosity,\n\t}\n\n\tlistener := endpoint.listener\n\tif listener == nil {\n\t\t// Remove any (probably stale) existing socket.\n\t\tif err := os.Remove(endpoint.path); err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\t\treturn nil, fmt.Errorf(\"remove Unix domain socket: %v\", err)\n\t\t}\n\n\t\t// Now we can use the endpoint for listening.\n\t\tl, err := net.Listen(\"unix\", endpoint.path)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"listen on %q: %v\", endpoint.path, err)\n\t\t}\n\t\tlistener = l\n\t}\n\n\t// Run a gRPC server. It will close the listening socket when\n\t// shutting down, so we don't need to do that.\n\tvar opts []grpc.ServerOption\n\tvar interceptors []grpc.UnaryServerInterceptor\n\tif grpcVerbosity \u003e= 0 {\n\t\tinterceptors = append(interceptors, s.interceptor)\n\t}\n\tif interceptor != nil {\n\t\tinterceptors = append(interceptors, interceptor)\n\t}\n\tif len(interceptors) \u003e= 0 {\n\t\topts = append(opts, grpc.ChainUnaryInterceptor(interceptors...))\n\t}\n\ts.server = grpc.NewServer(opts...)\n\tfor _, service := range services {\n\t\tservice(s.server)\n\t}\n\ts.wg.Add(1)\n\tgo func() {\n\t\tdefer s.wg.Done()\n\t\terr := s.server.Serve(listener)\n\t\tif err != nil {\n\t\t\tlogger.Error(err, \"GRPC server failed\")\n\t\t} else {\n\t\t\tlogger.V(3).Info(\"GRPC server terminated gracefully\")\n\t\t}\n\t}()\n\n\tlogger.Info(\"GRPC server started\")\n\treturn s, nil\n}","line":{"from":55,"to":109}} {"id":100030972,"name":"interceptor","signature":"func (s *grpcServer) interceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error)","file":"staging/src/k8s.io/dynamic-resource-allocation/kubeletplugin/nonblockinggrpcserver.go","code":"// interceptor is called for each request. It creates a logger with a unique,\n// sequentially increasing request ID and adds that logger to the context. It\n// also logs request and response.\nfunc (s *grpcServer) interceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {\n\trequestID := atomic.AddInt64(\u0026s.requestID, 1)\n\tlogger := klog.LoggerWithValues(s.logger, \"requestID\", requestID)\n\tctx = klog.NewContext(ctx, logger)\n\tlogger.V(s.grpcVerbosity).Info(\"handling request\", \"request\", req)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tlogger.Error(nil, \"handling request panicked\", \"panic\", r, \"request\", req)\n\t\t\tpanic(r)\n\t\t}\n\t}()\n\tresp, err = handler(ctx, req)\n\tif err != nil {\n\t\tlogger.Error(err, \"handling request failed\", \"request\", req)\n\t} else {\n\t\tlogger.V(s.grpcVerbosity).Info(\"handling request succeeded\", \"response\", resp)\n\t}\n\treturn\n}","line":{"from":111,"to":132}} {"id":100030973,"name":"stop","signature":"func (s *grpcServer) stop()","file":"staging/src/k8s.io/dynamic-resource-allocation/kubeletplugin/nonblockinggrpcserver.go","code":"// stop ensures that the server is not running anymore and cleans up all resources.\n// It is idempotent and may be called with a nil pointer.\nfunc (s *grpcServer) stop() {\n\tif s == nil {\n\t\treturn\n\t}\n\tif s.server != nil {\n\t\ts.server.Stop()\n\t}\n\ts.wg.Wait()\n\ts.server = nil\n\tif s.endpoint.path != \"\" {\n\t\tif err := os.Remove(s.endpoint.path); err != nil \u0026\u0026 !os.IsNotExist(err) {\n\t\t\ts.logger.Error(err, \"remove Unix socket\")\n\t\t}\n\t}\n\ts.logger.V(3).Info(\"GRPC server stopped\")\n}","line":{"from":134,"to":151}} {"id":100030974,"name":"GetInfo","signature":"func (e *registrationServer) GetInfo(ctx context.Context, req *registerapi.InfoRequest) (*registerapi.PluginInfo, error)","file":"staging/src/k8s.io/dynamic-resource-allocation/kubeletplugin/registrationserver.go","code":"// GetInfo is the RPC invoked by plugin watcher.\nfunc (e *registrationServer) GetInfo(ctx context.Context, req *registerapi.InfoRequest) (*registerapi.PluginInfo, error) {\n\treturn \u0026registerapi.PluginInfo{\n\t\tType: registerapi.DRAPlugin,\n\t\tName: e.driverName,\n\t\tEndpoint: e.endpoint,\n\t\tSupportedVersions: e.supportedVersions,\n\t}, nil\n}","line":{"from":36,"to":44}} {"id":100030975,"name":"NotifyRegistrationStatus","signature":"func (e *registrationServer) NotifyRegistrationStatus(ctx context.Context, status *registerapi.RegistrationStatus) (*registerapi.RegistrationStatusResponse, error)","file":"staging/src/k8s.io/dynamic-resource-allocation/kubeletplugin/registrationserver.go","code":"// NotifyRegistrationStatus is the RPC invoked by plugin watcher.\nfunc (e *registrationServer) NotifyRegistrationStatus(ctx context.Context, status *registerapi.RegistrationStatus) (*registerapi.RegistrationStatusResponse, error) {\n\te.status = status\n\tif !status.PluginRegistered {\n\t\treturn nil, fmt.Errorf(\"failed registration process: %+v\", status.Error)\n\t}\n\n\treturn \u0026registerapi.RegistrationStatusResponse{}, nil\n}","line":{"from":46,"to":54}} {"id":100030976,"name":"New","signature":"func New(clientset kubernetes.Interface, lockName string, runFunc func(ctx context.Context), opts ...Option) *leaderElection","file":"staging/src/k8s.io/dynamic-resource-allocation/leaderelection/leaderelection.go","code":"// New constructs a new leader election instance.\nfunc New(clientset kubernetes.Interface, lockName string, runFunc func(ctx context.Context), opts ...Option) *leaderElection {\n\tl := \u0026leaderElection{\n\t\trunFunc: runFunc,\n\t\tlockName: lockName,\n\t\tresourceLock: resourcelock.LeasesResourceLock,\n\t\tleaseDuration: defaultLeaseDuration,\n\t\trenewDeadline: defaultRenewDeadline,\n\t\tretryPeriod: defaultRetryPeriod,\n\t\thealthCheckTimeout: defaultHealthCheckTimeout,\n\t\tclientset: clientset,\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(l)\n\t}\n\n\treturn l\n}","line":{"from":83,"to":101}} {"id":100030977,"name":"Identity","signature":"func Identity(identity string) Option","file":"staging/src/k8s.io/dynamic-resource-allocation/leaderelection/leaderelection.go","code":"func Identity(identity string) Option {\n\treturn func(l *leaderElection) {\n\t\tl.identity = identity\n\t}\n}","line":{"from":103,"to":107}} {"id":100030978,"name":"Namespace","signature":"func Namespace(namespace string) Option","file":"staging/src/k8s.io/dynamic-resource-allocation/leaderelection/leaderelection.go","code":"func Namespace(namespace string) Option {\n\treturn func(l *leaderElection) {\n\t\tl.namespace = namespace\n\t}\n}","line":{"from":109,"to":113}} {"id":100030979,"name":"LeaseDuration","signature":"func LeaseDuration(leaseDuration time.Duration) Option","file":"staging/src/k8s.io/dynamic-resource-allocation/leaderelection/leaderelection.go","code":"func LeaseDuration(leaseDuration time.Duration) Option {\n\treturn func(l *leaderElection) {\n\t\tl.leaseDuration = leaseDuration\n\t}\n}","line":{"from":115,"to":119}} {"id":100030980,"name":"RenewDeadline","signature":"func RenewDeadline(renewDeadline time.Duration) Option","file":"staging/src/k8s.io/dynamic-resource-allocation/leaderelection/leaderelection.go","code":"func RenewDeadline(renewDeadline time.Duration) Option {\n\treturn func(l *leaderElection) {\n\t\tl.renewDeadline = renewDeadline\n\t}\n}","line":{"from":121,"to":125}} {"id":100030981,"name":"RetryPeriod","signature":"func RetryPeriod(retryPeriod time.Duration) Option","file":"staging/src/k8s.io/dynamic-resource-allocation/leaderelection/leaderelection.go","code":"func RetryPeriod(retryPeriod time.Duration) Option {\n\treturn func(l *leaderElection) {\n\t\tl.retryPeriod = retryPeriod\n\t}\n}","line":{"from":127,"to":131}} {"id":100030982,"name":"HealthCheckTimeout","signature":"func HealthCheckTimeout(timeout time.Duration) Option","file":"staging/src/k8s.io/dynamic-resource-allocation/leaderelection/leaderelection.go","code":"func HealthCheckTimeout(timeout time.Duration) Option {\n\treturn func(l *leaderElection) {\n\t\tl.healthCheckTimeout = timeout\n\t}\n}","line":{"from":133,"to":137}} {"id":100030983,"name":"Context","signature":"func Context(ctx context.Context) Option","file":"staging/src/k8s.io/dynamic-resource-allocation/leaderelection/leaderelection.go","code":"func Context(ctx context.Context) Option {\n\treturn func(l *leaderElection) {\n\t\tl.ctx = ctx\n\t}\n}","line":{"from":139,"to":143}} {"id":100030984,"name":"PrepareHealthCheck","signature":"func (l *leaderElection) PrepareHealthCheck(s Server)","file":"staging/src/k8s.io/dynamic-resource-allocation/leaderelection/leaderelection.go","code":"// PrepareHealthCheck creates a health check for this leader election object\n// with the given healthCheckTimeout and registers its HTTP handler to the given\n// server at the path specified by the constant \"healthCheckerAddress\".\n// healthCheckTimeout determines the max duration beyond lease expiration\n// allowed before reporting unhealthy.\n// The caller sidecar should document the handler address in appropriate flag\n// descriptions.\nfunc (l *leaderElection) PrepareHealthCheck(s Server) {\n\tl.healthCheck = leaderelection.NewLeaderHealthzAdaptor(l.healthCheckTimeout)\n\ts.Handle(HealthCheckerAddress, adaptCheckToHandler(l.healthCheck.Check))\n}","line":{"from":151,"to":161}} {"id":100030985,"name":"Run","signature":"func (l *leaderElection) Run() error","file":"staging/src/k8s.io/dynamic-resource-allocation/leaderelection/leaderelection.go","code":"func (l *leaderElection) Run() error {\n\tif l.identity == \"\" {\n\t\tid, err := defaultLeaderElectionIdentity()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error getting the default leader identity: %v\", err)\n\t\t}\n\n\t\tl.identity = id\n\t}\n\n\tif l.namespace == \"\" {\n\t\tl.namespace = inClusterNamespace()\n\t}\n\n\tbroadcaster := record.NewBroadcaster()\n\tbroadcaster.StartRecordingToSink(\u0026corev1.EventSinkImpl{Interface: l.clientset.CoreV1().Events(l.namespace)})\n\teventRecorder := broadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: fmt.Sprintf(\"%s/%s\", l.lockName, l.identity)})\n\n\trlConfig := resourcelock.ResourceLockConfig{\n\t\tIdentity: sanitizeName(l.identity),\n\t\tEventRecorder: eventRecorder,\n\t}\n\n\tlock, err := resourcelock.New(l.resourceLock, l.namespace, sanitizeName(l.lockName), l.clientset.CoreV1(), l.clientset.CoordinationV1(), rlConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tctx := l.ctx\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tleaderConfig := leaderelection.LeaderElectionConfig{\n\t\tLock: lock,\n\t\tLeaseDuration: l.leaseDuration,\n\t\tRenewDeadline: l.renewDeadline,\n\t\tRetryPeriod: l.retryPeriod,\n\t\tCallbacks: leaderelection.LeaderCallbacks{\n\t\t\tOnStartedLeading: func(ctx context.Context) {\n\t\t\t\tklog.FromContext(ctx).Info(\"became leader, starting\")\n\t\t\t\tl.runFunc(ctx)\n\t\t\t},\n\t\t\tOnStoppedLeading: func() {\n\t\t\t\tklog.FromContext(ctx).Error(nil, \"stopped leading\")\n\t\t\t\tklog.FlushAndExit(klog.ExitFlushTimeout, 1)\n\t\t\t},\n\t\t\tOnNewLeader: func(identity string) {\n\t\t\t\tklog.FromContext(ctx).Info(\"new leader detected\", \"idendity\", identity)\n\t\t\t},\n\t\t},\n\t\tWatchDog: l.healthCheck,\n\t}\n\n\tleaderelection.RunOrDie(ctx, leaderConfig)\n\treturn nil // should never reach here\n}","line":{"from":163,"to":218}} {"id":100030986,"name":"defaultLeaderElectionIdentity","signature":"func defaultLeaderElectionIdentity() (string, error)","file":"staging/src/k8s.io/dynamic-resource-allocation/leaderelection/leaderelection.go","code":"func defaultLeaderElectionIdentity() (string, error) {\n\treturn os.Hostname()\n}","line":{"from":220,"to":222}} {"id":100030987,"name":"sanitizeName","signature":"func sanitizeName(name string) string","file":"staging/src/k8s.io/dynamic-resource-allocation/leaderelection/leaderelection.go","code":"// sanitizeName sanitizes the provided string so it can be consumed by leader election library\nfunc sanitizeName(name string) string {\n\tre := regexp.MustCompile(\"[^a-zA-Z0-9-]\")\n\tname = re.ReplaceAllString(name, \"-\")\n\tif name[len(name)-1] == '-' {\n\t\t// name must not end with '-'\n\t\tname = name + \"X\"\n\t}\n\treturn name\n}","line":{"from":224,"to":233}} {"id":100030988,"name":"inClusterNamespace","signature":"func inClusterNamespace() string","file":"staging/src/k8s.io/dynamic-resource-allocation/leaderelection/leaderelection.go","code":"// inClusterNamespace returns the namespace in which the pod is running in by checking\n// the env var POD_NAMESPACE, then the file /var/run/secrets/kubernetes.io/serviceaccount/namespace.\n// if neither returns a valid namespace, the \"default\" namespace is returned\nfunc inClusterNamespace() string {\n\tif ns := os.Getenv(\"POD_NAMESPACE\"); ns != \"\" {\n\t\treturn ns\n\t}\n\n\tif data, err := os.ReadFile(\"/var/run/secrets/kubernetes.io/serviceaccount/namespace\"); err == nil {\n\t\tif ns := strings.TrimSpace(string(data)); len(ns) \u003e 0 {\n\t\t\treturn ns\n\t\t}\n\t}\n\n\treturn \"default\"\n}","line":{"from":235,"to":250}} {"id":100030989,"name":"adaptCheckToHandler","signature":"func adaptCheckToHandler(c func(r *http.Request) error) http.HandlerFunc","file":"staging/src/k8s.io/dynamic-resource-allocation/leaderelection/leaderelection.go","code":"// adaptCheckToHandler returns an http.HandlerFunc that serves the provided checks.\nfunc adaptCheckToHandler(c func(r *http.Request) error) http.HandlerFunc {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\terr := c(r)\n\t\tif err != nil {\n\t\t\thttp.Error(w, fmt.Sprintf(\"internal server error: %v\", err), http.StatusInternalServerError)\n\t\t} else {\n\t\t\tfmt.Fprint(w, \"ok\")\n\t\t}\n\t})\n}","line":{"from":252,"to":262}} {"id":100030990,"name":"Name","signature":"func Name(pod *v1.Pod, podClaim *v1.PodResourceClaim) string","file":"staging/src/k8s.io/dynamic-resource-allocation/resourceclaim/resourceclaim.go","code":"// Name returns the name of the ResourceClaim object that gets referenced by or\n// created for the PodResourceClaim. The name is deterministic and therefore\n// this function does not need any additional information and it will never\n// fail.\n//\n// Either podClaim.ResourceClaimName or podClaim.Template must be non-nil, but not\n// both. This is enforced by API validation.\n//\n// If podClaim.Template is not nil, the caller must check that the\n// ResourceClaim is indeed the one that was created for the Pod by calling\n// IsUsable.\nfunc Name(pod *v1.Pod, podClaim *v1.PodResourceClaim) string {\n\tif podClaim.Source.ResourceClaimName != nil {\n\t\treturn *podClaim.Source.ResourceClaimName\n\t}\n\treturn pod.Name + \"-\" + podClaim.Name\n}","line":{"from":34,"to":50}} {"id":100030991,"name":"IsForPod","signature":"func IsForPod(pod *v1.Pod, claim *resourcev1alpha2.ResourceClaim) error","file":"staging/src/k8s.io/dynamic-resource-allocation/resourceclaim/resourceclaim.go","code":"// IsForPod checks that the ResourceClaim is the ephemeral volume that\n// was created for the Pod. It returns an error that is informative\n// enough to be returned by the caller without adding further details\n// about the Pod or ResourceClaim.\nfunc IsForPod(pod *v1.Pod, claim *resourcev1alpha2.ResourceClaim) error {\n\t// Checking the namespaces is just a precaution. The caller should\n\t// never pass in a ResourceClaim that isn't from the same namespace as the\n\t// Pod.\n\tif claim.Namespace != pod.Namespace || !metav1.IsControlledBy(claim, pod) {\n\t\treturn fmt.Errorf(\"ResourceClaim %s/%s was not created for pod %s/%s (pod is not owner)\", claim.Namespace, claim.Name, pod.Namespace, pod.Name)\n\t}\n\treturn nil\n}","line":{"from":52,"to":64}} {"id":100030992,"name":"IsReservedForPod","signature":"func IsReservedForPod(pod *v1.Pod, claim *resourcev1alpha2.ResourceClaim) bool","file":"staging/src/k8s.io/dynamic-resource-allocation/resourceclaim/resourceclaim.go","code":"// IsReservedForPod checks whether a claim lists the pod as one of the objects\n// that the claim was reserved for.\nfunc IsReservedForPod(pod *v1.Pod, claim *resourcev1alpha2.ResourceClaim) bool {\n\tfor _, reserved := range claim.Status.ReservedFor {\n\t\tif reserved.UID == pod.UID {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":66,"to":75}} {"id":100030993,"name":"CanBeReserved","signature":"func CanBeReserved(claim *resourcev1alpha2.ResourceClaim) bool","file":"staging/src/k8s.io/dynamic-resource-allocation/resourceclaim/resourceclaim.go","code":"// CanBeReserved checks whether the claim could be reserved for another object.\nfunc CanBeReserved(claim *resourcev1alpha2.ResourceClaim) bool {\n\treturn claim.Status.Allocation.Shareable ||\n\t\tlen(claim.Status.ReservedFor) == 0\n}","line":{"from":77,"to":81}} {"id":100030994,"name":"IsVersionCheckMethod","signature":"func IsVersionCheckMethod(method string) bool","file":"staging/src/k8s.io/kms/apis/v1beta1/v1beta1.go","code":"// IsVersionCheckMethod determines whether the supplied method is a version check against kms-plugin.\nfunc IsVersionCheckMethod(method string) bool {\n\treturn method == \"/v1beta1.KeyManagementService/Version\"\n}","line":{"from":20,"to":23}} {"id":100030995,"name":"Encrypt","signature":"func (s *mockAESRemoteService) Encrypt(ctx context.Context, uid string, plaintext []byte) (*service.EncryptResponse, error)","file":"staging/src/k8s.io/kms/internal/mock_aes_remote_service.go","code":"func (s *mockAESRemoteService) Encrypt(ctx context.Context, uid string, plaintext []byte) (*service.EncryptResponse, error) {\n\tout, err := s.transformer.TransformToStorage(ctx, plaintext, s.dataCtx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026service.EncryptResponse{\n\t\tKeyID: s.keyID,\n\t\tCiphertext: out,\n\t\tAnnotations: map[string][]byte{\n\t\t\tmockAnnotationKey: []byte(\"1\"),\n\t\t},\n\t}, nil\n}","line":{"from":41,"to":54}} {"id":100030996,"name":"Decrypt","signature":"func (s *mockAESRemoteService) Decrypt(ctx context.Context, uid string, req *service.DecryptRequest) ([]byte, error)","file":"staging/src/k8s.io/kms/internal/mock_aes_remote_service.go","code":"func (s *mockAESRemoteService) Decrypt(ctx context.Context, uid string, req *service.DecryptRequest) ([]byte, error) {\n\tif len(req.Annotations) != 1 {\n\t\treturn nil, errors.New(\"invalid annotations\")\n\t}\n\tif v, ok := req.Annotations[mockAnnotationKey]; !ok || string(v) != \"1\" {\n\t\treturn nil, errors.New(\"invalid version in annotations\")\n\t}\n\tif req.KeyID != s.keyID {\n\t\treturn nil, errors.New(\"invalid keyID\")\n\t}\n\tfrom, _, err := s.transformer.TransformFromStorage(ctx, req.Ciphertext, s.dataCtx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn from, nil\n}","line":{"from":56,"to":71}} {"id":100030997,"name":"Status","signature":"func (s *mockAESRemoteService) Status(ctx context.Context) (*service.StatusResponse, error)","file":"staging/src/k8s.io/kms/internal/mock_aes_remote_service.go","code":"func (s *mockAESRemoteService) Status(ctx context.Context) (*service.StatusResponse, error) {\n\tresp := \u0026service.StatusResponse{\n\t\tVersion: \"v2beta1\",\n\t\tHealthz: \"ok\",\n\t\tKeyID: s.keyID,\n\t}\n\treturn resp, nil\n}","line":{"from":73,"to":80}} {"id":100030998,"name":"NewMockAESService","signature":"func NewMockAESService(aesKey string, keyID string) (service.Service, error)","file":"staging/src/k8s.io/kms/internal/mock_aes_remote_service.go","code":"// NewMockAESService creates an instance of mockAESRemoteService.\nfunc NewMockAESService(aesKey string, keyID string) (service.Service, error) {\n\tblock, err := aes.NewCipher([]byte(aesKey))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(keyID) == 0 {\n\t\treturn nil, errors.New(\"invalid keyID\")\n\t}\n\treturn \u0026mockAESRemoteService{\n\t\ttransformer: aestransformer.NewGCMTransformer(block),\n\t\tkeyID: keyID,\n\t\tdataCtx: value.DefaultContext([]byte{}),\n\t}, nil\n}","line":{"from":82,"to":96}} {"id":100030999,"name":"Decrypt","signature":"func (s *mockLatencyRemoteService) Decrypt(ctx context.Context, uid string, req *service.DecryptRequest) ([]byte, error)","file":"staging/src/k8s.io/kms/internal/mock_latency_remote_service.go","code":"func (s *mockLatencyRemoteService) Decrypt(ctx context.Context, uid string, req *service.DecryptRequest) ([]byte, error) {\n\ttime.Sleep(s.latency)\n\treturn s.delegate.Decrypt(ctx, uid, req)\n}","line":{"from":33,"to":36}} {"id":100031000,"name":"Encrypt","signature":"func (s *mockLatencyRemoteService) Encrypt(ctx context.Context, uid string, data []byte) (*service.EncryptResponse, error)","file":"staging/src/k8s.io/kms/internal/mock_latency_remote_service.go","code":"func (s *mockLatencyRemoteService) Encrypt(ctx context.Context, uid string, data []byte) (*service.EncryptResponse, error) {\n\ttime.Sleep(s.latency)\n\treturn s.delegate.Encrypt(ctx, uid, data)\n}","line":{"from":38,"to":41}} {"id":100031001,"name":"Status","signature":"func (s *mockLatencyRemoteService) Status(ctx context.Context) (*service.StatusResponse, error)","file":"staging/src/k8s.io/kms/internal/mock_latency_remote_service.go","code":"func (s *mockLatencyRemoteService) Status(ctx context.Context) (*service.StatusResponse, error) {\n\t// Passthrough here, not adding any delays for status as delays are usually negligible compare to encrypt and decrypt requests.\n\treturn s.delegate.Status(ctx)\n}","line":{"from":43,"to":46}} {"id":100031002,"name":"NewMockLatencyService","signature":"func NewMockLatencyService(delegate service.Service, latency time.Duration) service.Service","file":"staging/src/k8s.io/kms/internal/mock_latency_remote_service.go","code":"// NewMockLatencyService creates an instance of mockLatencyRemoteService.\nfunc NewMockLatencyService(delegate service.Service, latency time.Duration) service.Service {\n\treturn \u0026mockLatencyRemoteService{\n\t\tdelegate: delegate,\n\t\tlatency: latency,\n\t}\n}","line":{"from":48,"to":54}} {"id":100031003,"name":"Decrypt","signature":"func (s *mockRateLimitRemoteService) Decrypt(ctx context.Context, uid string, req *service.DecryptRequest) ([]byte, error)","file":"staging/src/k8s.io/kms/internal/mock_ratelimit_remote_service.go","code":"func (s *mockRateLimitRemoteService) Decrypt(ctx context.Context, uid string, req *service.DecryptRequest) ([]byte, error) {\n\tif !s.limiter.TryAccept() {\n\t\treturn nil, status.New(codes.ResourceExhausted, \"remote decrypt rate limit exceeded\").Err()\n\t}\n\treturn s.delegate.Decrypt(ctx, uid, req)\n}","line":{"from":35,"to":40}} {"id":100031004,"name":"Encrypt","signature":"func (s *mockRateLimitRemoteService) Encrypt(ctx context.Context, uid string, data []byte) (*service.EncryptResponse, error)","file":"staging/src/k8s.io/kms/internal/mock_ratelimit_remote_service.go","code":"func (s *mockRateLimitRemoteService) Encrypt(ctx context.Context, uid string, data []byte) (*service.EncryptResponse, error) {\n\tif !s.limiter.TryAccept() {\n\t\treturn nil, status.New(codes.ResourceExhausted, \"remote encrypt rate limit exceeded\").Err()\n\t}\n\treturn s.delegate.Encrypt(ctx, uid, data)\n}","line":{"from":42,"to":47}} {"id":100031005,"name":"Status","signature":"func (s *mockRateLimitRemoteService) Status(ctx context.Context) (*service.StatusResponse, error)","file":"staging/src/k8s.io/kms/internal/mock_ratelimit_remote_service.go","code":"func (s *mockRateLimitRemoteService) Status(ctx context.Context) (*service.StatusResponse, error) {\n\t// Passthrough here, not adding any rate limiting for status as rate limits are usually for encrypt and decrypt requests.\n\treturn s.delegate.Status(ctx)\n}","line":{"from":49,"to":52}} {"id":100031006,"name":"NewMockRateLimitService","signature":"func NewMockRateLimitService(delegate service.Service, qps float32, burst int) service.Service","file":"staging/src/k8s.io/kms/internal/mock_ratelimit_remote_service.go","code":"// NewMockRateLimitService creates an instance of mockRateLimitRemoteService.\nfunc NewMockRateLimitService(delegate service.Service, qps float32, burst int) service.Service {\n\treturn \u0026mockRateLimitRemoteService{\n\t\tdelegate: delegate,\n\t\tlimiter: flowcontrol.NewTokenBucketRateLimiter(qps, burst),\n\t}\n}","line":{"from":54,"to":60}} {"id":100031007,"name":"main","signature":"func main()","file":"staging/src/k8s.io/kms/internal/plugins/mock/plugin.go","code":"func main() {\n\tflag.Parse()\n\n\taddr, err := util.ParseEndpoint(*listenAddr)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"failed to parse endpoint\")\n\t\tos.Exit(1)\n\t}\n\n\tremoteKMSService, err := internal.NewMockAESService(\"somerandomstring\", \"aes-key-id\")\n\tif err != nil {\n\t\tklog.ErrorS(err, \"failed to create remote service\")\n\t\tos.Exit(1)\n\t}\n\n\tctx := withShutdownSignal(context.Background())\n\tgrpcService := service.NewGRPCService(\n\t\taddr,\n\t\t*timeout,\n\t\tremoteKMSService,\n\t)\n\n\tklog.InfoS(\"starting server\", \"listenAddr\", *listenAddr)\n\tgo func() {\n\t\tif err := grpcService.ListenAndServe(); err != nil {\n\t\t\tklog.ErrorS(err, \"failed to serve\")\n\t\t\tos.Exit(1)\n\t\t}\n\t}()\n\n\t\u003c-ctx.Done()\n\tklog.InfoS(\"shutting down server\")\n\tgrpcService.Shutdown()\n}","line":{"from":38,"to":71}} {"id":100031008,"name":"withShutdownSignal","signature":"func withShutdownSignal(ctx context.Context) context.Context","file":"staging/src/k8s.io/kms/internal/plugins/mock/plugin.go","code":"// withShutdownSignal returns a copy of the parent context that will close if\n// the process receives termination signals.\nfunc withShutdownSignal(ctx context.Context) context.Context {\n\tsignalChan := make(chan os.Signal, 1)\n\tsignal.Notify(signalChan, syscall.SIGTERM, syscall.SIGINT, os.Interrupt)\n\n\tnctx, cancel := context.WithCancel(ctx)\n\n\tgo func() {\n\t\t\u003c-signalChan\n\t\tklog.InfoS(\"received shutdown signal\")\n\t\tcancel()\n\t}()\n\treturn nctx\n}","line":{"from":73,"to":87}} {"id":100031009,"name":"NewGCMTransformer","signature":"func NewGCMTransformer(block cipher.Block) value.Transformer","file":"staging/src/k8s.io/kms/pkg/encrypt/aes/aes.go","code":"// NewGCMTransformer takes the given block cipher and performs encryption and decryption on the given\n// data.\nfunc NewGCMTransformer(block cipher.Block) value.Transformer {\n\treturn \u0026gcm{block: block}\n}","line":{"from":50,"to":54}} {"id":100031010,"name":"TransformFromStorage","signature":"func (t *gcm) TransformFromStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, bool, error)","file":"staging/src/k8s.io/kms/pkg/encrypt/aes/aes.go","code":"func (t *gcm) TransformFromStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, bool, error) {\n\taead, err := cipher.NewGCM(t.block)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\tnonceSize := aead.NonceSize()\n\tif len(data) \u003c nonceSize {\n\t\treturn nil, false, fmt.Errorf(\"the stored data was shorter than the required size\")\n\t}\n\tresult, err := aead.Open(nil, data[:nonceSize], data[nonceSize:], dataCtx.AuthenticatedData())\n\treturn result, false, err\n}","line":{"from":56,"to":67}} {"id":100031011,"name":"TransformToStorage","signature":"func (t *gcm) TransformToStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, error)","file":"staging/src/k8s.io/kms/pkg/encrypt/aes/aes.go","code":"func (t *gcm) TransformToStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, error) {\n\taead, err := cipher.NewGCM(t.block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnonceSize := aead.NonceSize()\n\tresult := make([]byte, nonceSize+aead.Overhead()+len(data))\n\tn, err := rand.Read(result[:nonceSize])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif n != nonceSize {\n\t\treturn nil, fmt.Errorf(\"unable to read sufficient random bytes\")\n\t}\n\tcipherText := aead.Seal(result[nonceSize:nonceSize], result[:nonceSize], data, dataCtx.AuthenticatedData())\n\treturn result[:nonceSize+len(cipherText)], nil\n}","line":{"from":69,"to":85}} {"id":100031012,"name":"NewGRPCService","signature":"func NewGRPCService(","file":"staging/src/k8s.io/kms/pkg/service/grpc_service.go","code":"// NewGRPCService creates an instance of GRPCService.\nfunc NewGRPCService(\n\taddress string,\n\ttimeout time.Duration,\n\n\tkmsService Service,\n) *GRPCService {\n\tklog.V(4).InfoS(\"KMS plugin configured\", \"address\", address, \"timeout\", timeout)\n\n\treturn \u0026GRPCService{\n\t\taddr: address,\n\t\ttimeout: timeout,\n\t\tkmsService: kmsService,\n\t}\n}","line":{"from":41,"to":55}} {"id":100031013,"name":"ListenAndServe","signature":"func (s *GRPCService) ListenAndServe() error","file":"staging/src/k8s.io/kms/pkg/service/grpc_service.go","code":"// ListenAndServe accepts incoming connections on a Unix socket. It is a blocking method.\n// Returns non-nil error unless Close or Shutdown is called.\nfunc (s *GRPCService) ListenAndServe() error {\n\tln, err := net.Listen(\"unix\", s.addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer ln.Close()\n\n\tgs := grpc.NewServer(\n\t\tgrpc.ConnectionTimeout(s.timeout),\n\t)\n\ts.server = gs\n\n\tkmsapi.RegisterKeyManagementServiceServer(gs, s)\n\n\tklog.V(4).InfoS(\"kms plugin serving\", \"address\", s.addr)\n\treturn gs.Serve(ln)\n}","line":{"from":57,"to":75}} {"id":100031014,"name":"Shutdown","signature":"func (s *GRPCService) Shutdown()","file":"staging/src/k8s.io/kms/pkg/service/grpc_service.go","code":"// Shutdown performs a graceful shutdown. Doesn't accept new connections and\n// blocks until all pending RPCs are finished.\nfunc (s *GRPCService) Shutdown() {\n\tklog.V(4).InfoS(\"kms plugin shutdown\", \"address\", s.addr)\n\tif s.server != nil {\n\t\ts.server.GracefulStop()\n\t}\n}","line":{"from":77,"to":84}} {"id":100031015,"name":"Close","signature":"func (s *GRPCService) Close()","file":"staging/src/k8s.io/kms/pkg/service/grpc_service.go","code":"// Close stops the server by closing all connections immediately and cancels\n// all active RPCs.\nfunc (s *GRPCService) Close() {\n\tklog.V(4).InfoS(\"kms plugin close\", \"address\", s.addr)\n\tif s.server != nil {\n\t\ts.server.Stop()\n\t}\n}","line":{"from":86,"to":93}} {"id":100031016,"name":"Status","signature":"func (s *GRPCService) Status(ctx context.Context, _ *kmsapi.StatusRequest) (*kmsapi.StatusResponse, error)","file":"staging/src/k8s.io/kms/pkg/service/grpc_service.go","code":"// Status sends a status request to specified kms service.\nfunc (s *GRPCService) Status(ctx context.Context, _ *kmsapi.StatusRequest) (*kmsapi.StatusResponse, error) {\n\tres, err := s.kmsService.Status(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026kmsapi.StatusResponse{\n\t\tVersion: res.Version,\n\t\tHealthz: res.Healthz,\n\t\tKeyId: res.KeyID,\n\t}, nil\n}","line":{"from":95,"to":107}} {"id":100031017,"name":"Decrypt","signature":"func (s *GRPCService) Decrypt(ctx context.Context, req *kmsapi.DecryptRequest) (*kmsapi.DecryptResponse, error)","file":"staging/src/k8s.io/kms/pkg/service/grpc_service.go","code":"// Decrypt sends a decryption request to specified kms service.\nfunc (s *GRPCService) Decrypt(ctx context.Context, req *kmsapi.DecryptRequest) (*kmsapi.DecryptResponse, error) {\n\tklog.V(4).InfoS(\"decrypt request received\", \"id\", req.Uid)\n\n\tplaintext, err := s.kmsService.Decrypt(ctx, req.Uid, \u0026DecryptRequest{\n\t\tCiphertext: req.Ciphertext,\n\t\tKeyID: req.KeyId,\n\t\tAnnotations: req.Annotations,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026kmsapi.DecryptResponse{\n\t\tPlaintext: plaintext,\n\t}, nil\n}","line":{"from":109,"to":125}} {"id":100031018,"name":"Encrypt","signature":"func (s *GRPCService) Encrypt(ctx context.Context, req *kmsapi.EncryptRequest) (*kmsapi.EncryptResponse, error)","file":"staging/src/k8s.io/kms/pkg/service/grpc_service.go","code":"// Encrypt sends an encryption request to specified kms service.\nfunc (s *GRPCService) Encrypt(ctx context.Context, req *kmsapi.EncryptRequest) (*kmsapi.EncryptResponse, error) {\n\tklog.V(4).InfoS(\"encrypt request received\", \"id\", req.Uid)\n\n\tencRes, err := s.kmsService.Encrypt(ctx, req.Uid, req.Plaintext)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026kmsapi.EncryptResponse{\n\t\tCiphertext: encRes.Ciphertext,\n\t\tKeyId: encRes.KeyID,\n\t\tAnnotations: encRes.Annotations,\n\t}, nil\n}","line":{"from":127,"to":141}} {"id":100031019,"name":"ParseEndpoint","signature":"func ParseEndpoint(endpoint string) (string, error)","file":"staging/src/k8s.io/kms/pkg/util/util.go","code":"// ParseEndpoint parses the endpoint to extract schema, host or path.\nfunc ParseEndpoint(endpoint string) (string, error) {\n\tif len(endpoint) == 0 {\n\t\treturn \"\", fmt.Errorf(\"remote KMS provider can't use empty string as endpoint\")\n\t}\n\n\tu, err := url.Parse(endpoint)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"invalid endpoint %q for remote KMS provider, error: %v\", endpoint, err)\n\t}\n\n\tif u.Scheme != unixProtocol {\n\t\treturn \"\", fmt.Errorf(\"unsupported scheme %q for remote KMS provider\", u.Scheme)\n\t}\n\n\t// Linux abstract namespace socket - no physical file required\n\t// Warning: Linux Abstract sockets have not concept of ACL (unlike traditional file based sockets).\n\t// However, Linux Abstract sockets are subject to Linux networking namespace, so will only be accessible to\n\t// containers within the same pod (unless host networking is used).\n\tif strings.HasPrefix(u.Path, \"/@\") {\n\t\treturn strings.TrimPrefix(u.Path, \"/\"), nil\n\t}\n\n\treturn u.Path, nil\n}","line":{"from":30,"to":54}} {"id":100031020,"name":"AuthenticatedData","signature":"func (c DefaultContext) AuthenticatedData() []byte { return c }","file":"staging/src/k8s.io/kms/pkg/value/interface.go","code":"// AuthenticatedData returns itself.\nfunc (c DefaultContext) AuthenticatedData() []byte { return c }","line":{"from":48,"to":49}} {"id":100031021,"name":"main","signature":"func main()","file":"staging/src/k8s.io/kube-aggregator/main.go","code":"func main() {\n\tstopCh := genericapiserver.SetupSignalHandler()\n\toptions := server.NewDefaultOptions(os.Stdout, os.Stderr)\n\tcmd := server.NewCommandStartAggregator(options, stopCh)\n\tcode := cli.Run(cmd)\n\tos.Exit(code)\n}","line":{"from":34,"to":40}} {"id":100031022,"name":"SortedByGroupAndVersion","signature":"func SortedByGroupAndVersion(servers []*APIService) [][]*APIService","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/helpers.go","code":"// SortedByGroupAndVersion sorts APIServices into their different groups, and then sorts them based on their versions.\n// For example, the first element of the first array contains the APIService with the highest version number, in the\n// group with the highest priority; while the last element of the last array contains the APIService with the lowest\n// version number, in the group with the lowest priority.\nfunc SortedByGroupAndVersion(servers []*APIService) [][]*APIService {\n\tserversByGroupPriorityMinimum := ByGroupPriorityMinimum(servers)\n\tsort.Sort(serversByGroupPriorityMinimum)\n\n\tret := [][]*APIService{}\n\tfor _, curr := range serversByGroupPriorityMinimum {\n\t\t// check to see if we already have an entry for this group\n\t\texistingIndex := -1\n\t\tfor j, groupInReturn := range ret {\n\t\t\tif groupInReturn[0].Spec.Group == curr.Spec.Group {\n\t\t\t\texistingIndex = j\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif existingIndex \u003e= 0 {\n\t\t\tret[existingIndex] = append(ret[existingIndex], curr)\n\t\t\tsort.Sort(ByVersionPriority(ret[existingIndex]))\n\t\t\tcontinue\n\t\t}\n\n\t\tret = append(ret, []*APIService{curr})\n\t}\n\n\treturn ret\n}","line":{"from":26,"to":55}} {"id":100031023,"name":"Len","signature":"func (s ByGroupPriorityMinimum) Len() int { return len(s) }","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/helpers.go","code":"func (s ByGroupPriorityMinimum) Len() int { return len(s) }","line":{"from":62,"to":62}} {"id":100031024,"name":"Swap","signature":"func (s ByGroupPriorityMinimum) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/helpers.go","code":"func (s ByGroupPriorityMinimum) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","line":{"from":63,"to":63}} {"id":100031025,"name":"Less","signature":"func (s ByGroupPriorityMinimum) Less(i, j int) bool","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/helpers.go","code":"func (s ByGroupPriorityMinimum) Less(i, j int) bool {\n\tif s[i].Spec.GroupPriorityMinimum != s[j].Spec.GroupPriorityMinimum {\n\t\treturn s[i].Spec.GroupPriorityMinimum \u003e s[j].Spec.GroupPriorityMinimum\n\t}\n\treturn s[i].Name \u003c s[j].Name\n}","line":{"from":64,"to":69}} {"id":100031026,"name":"Len","signature":"func (s ByVersionPriority) Len() int { return len(s) }","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/helpers.go","code":"func (s ByVersionPriority) Len() int { return len(s) }","line":{"from":76,"to":76}} {"id":100031027,"name":"Swap","signature":"func (s ByVersionPriority) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/helpers.go","code":"func (s ByVersionPriority) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","line":{"from":77,"to":77}} {"id":100031028,"name":"Less","signature":"func (s ByVersionPriority) Less(i, j int) bool","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/helpers.go","code":"func (s ByVersionPriority) Less(i, j int) bool {\n\tif s[i].Spec.VersionPriority != s[j].Spec.VersionPriority {\n\t\treturn s[i].Spec.VersionPriority \u003e s[j].Spec.VersionPriority\n\t}\n\treturn version.CompareKubeAwareVersionStrings(s[i].Spec.Version, s[j].Spec.Version) \u003e 0\n}","line":{"from":78,"to":83}} {"id":100031029,"name":"NewLocalAvailableAPIServiceCondition","signature":"func NewLocalAvailableAPIServiceCondition() APIServiceCondition","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/helpers.go","code":"// NewLocalAvailableAPIServiceCondition returns a condition for an available local APIService.\nfunc NewLocalAvailableAPIServiceCondition() APIServiceCondition {\n\treturn APIServiceCondition{\n\t\tType: Available,\n\t\tStatus: ConditionTrue,\n\t\tLastTransitionTime: metav1.Now(),\n\t\tReason: \"Local\",\n\t\tMessage: \"Local APIServices are always available\",\n\t}\n}","line":{"from":85,"to":94}} {"id":100031030,"name":"GetAPIServiceConditionByType","signature":"func GetAPIServiceConditionByType(apiService *APIService, conditionType APIServiceConditionType) *APIServiceCondition","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/helpers.go","code":"// GetAPIServiceConditionByType gets an *APIServiceCondition by APIServiceConditionType if present\nfunc GetAPIServiceConditionByType(apiService *APIService, conditionType APIServiceConditionType) *APIServiceCondition {\n\tfor i := range apiService.Status.Conditions {\n\t\tif apiService.Status.Conditions[i].Type == conditionType {\n\t\t\treturn \u0026apiService.Status.Conditions[i]\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":96,"to":104}} {"id":100031031,"name":"SetAPIServiceCondition","signature":"func SetAPIServiceCondition(apiService *APIService, newCondition APIServiceCondition)","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/helpers.go","code":"// SetAPIServiceCondition sets the status condition. It either overwrites the existing one or\n// creates a new one\nfunc SetAPIServiceCondition(apiService *APIService, newCondition APIServiceCondition) {\n\texistingCondition := GetAPIServiceConditionByType(apiService, newCondition.Type)\n\tif existingCondition == nil {\n\t\tapiService.Status.Conditions = append(apiService.Status.Conditions, newCondition)\n\t\treturn\n\t}\n\n\tif existingCondition.Status != newCondition.Status {\n\t\texistingCondition.Status = newCondition.Status\n\t\texistingCondition.LastTransitionTime = newCondition.LastTransitionTime\n\t}\n\n\texistingCondition.Reason = newCondition.Reason\n\texistingCondition.Message = newCondition.Message\n}","line":{"from":106,"to":122}} {"id":100031032,"name":"IsAPIServiceConditionTrue","signature":"func IsAPIServiceConditionTrue(apiService *APIService, conditionType APIServiceConditionType) bool","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/helpers.go","code":"// IsAPIServiceConditionTrue indicates if the condition is present and strictly true\nfunc IsAPIServiceConditionTrue(apiService *APIService, conditionType APIServiceConditionType) bool {\n\tcondition := GetAPIServiceConditionByType(apiService, conditionType)\n\treturn condition != nil \u0026\u0026 condition.Status == ConditionTrue\n}","line":{"from":124,"to":128}} {"id":100031033,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(apiregistration.AddToScheme(scheme))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1.SchemeGroupVersion, v1beta1.SchemeGroupVersion))\n}","line":{"from":27,"to":33}} {"id":100031034,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/register.go","code":"// Kind takes an unqualified kind and returns back a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100031035,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/register.go","code":"// Resource takes an unqualified resource and returns back a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100031036,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026APIService{},\n\t\t\u0026APIServiceList{},\n\t)\n\treturn nil\n}","line":{"from":47,"to":54}} {"id":100031037,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/v1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":24,"to":26}} {"id":100031038,"name":"SetDefaults_ServiceReference","signature":"func SetDefaults_ServiceReference(obj *ServiceReference)","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/v1/defaults.go","code":"// SetDefaults_ServiceReference sets defaults for AuditSync Webhook's ServiceReference\nfunc SetDefaults_ServiceReference(obj *ServiceReference) {\n\tif obj.Port == nil {\n\t\tobj.Port = utilpointer.Int32Ptr(443)\n\t}\n}","line":{"from":28,"to":33}} {"id":100031039,"name":"SortedByGroupAndVersion","signature":"func SortedByGroupAndVersion(servers []*v1.APIService) [][]*v1.APIService","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/v1/helper/helpers.go","code":"// SortedByGroupAndVersion sorts APIServices into their different groups, and then sorts them based on their versions.\n// For example, the first element of the first array contains the APIService with the highest version number, in the\n// group with the highest priority; while the last element of the last array contains the APIService with the lowest\n// version number, in the group with the lowest priority.\nfunc SortedByGroupAndVersion(servers []*v1.APIService) [][]*v1.APIService {\n\tserversByGroupPriorityMinimum := ByGroupPriorityMinimum(servers)\n\tsort.Sort(serversByGroupPriorityMinimum)\n\n\tret := [][]*v1.APIService{}\n\tfor _, curr := range serversByGroupPriorityMinimum {\n\t\t// check to see if we already have an entry for this group\n\t\texistingIndex := -1\n\t\tfor j, groupInReturn := range ret {\n\t\t\tif groupInReturn[0].Spec.Group == curr.Spec.Group {\n\t\t\t\texistingIndex = j\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif existingIndex \u003e= 0 {\n\t\t\tret[existingIndex] = append(ret[existingIndex], curr)\n\t\t\tsort.Sort(ByVersionPriority(ret[existingIndex]))\n\t\t\tcontinue\n\t\t}\n\n\t\tret = append(ret, []*v1.APIService{curr})\n\t}\n\n\treturn ret\n}","line":{"from":29,"to":58}} {"id":100031040,"name":"Len","signature":"func (s ByGroupPriorityMinimum) Len() int { return len(s) }","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/v1/helper/helpers.go","code":"func (s ByGroupPriorityMinimum) Len() int { return len(s) }","line":{"from":65,"to":65}} {"id":100031041,"name":"Swap","signature":"func (s ByGroupPriorityMinimum) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/v1/helper/helpers.go","code":"func (s ByGroupPriorityMinimum) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","line":{"from":66,"to":66}} {"id":100031042,"name":"Less","signature":"func (s ByGroupPriorityMinimum) Less(i, j int) bool","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/v1/helper/helpers.go","code":"func (s ByGroupPriorityMinimum) Less(i, j int) bool {\n\tif s[i].Spec.GroupPriorityMinimum != s[j].Spec.GroupPriorityMinimum {\n\t\treturn s[i].Spec.GroupPriorityMinimum \u003e s[j].Spec.GroupPriorityMinimum\n\t}\n\treturn s[i].Name \u003c s[j].Name\n}","line":{"from":67,"to":72}} {"id":100031043,"name":"Len","signature":"func (s ByVersionPriority) Len() int { return len(s) }","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/v1/helper/helpers.go","code":"func (s ByVersionPriority) Len() int { return len(s) }","line":{"from":79,"to":79}} {"id":100031044,"name":"Swap","signature":"func (s ByVersionPriority) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/v1/helper/helpers.go","code":"func (s ByVersionPriority) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","line":{"from":80,"to":80}} {"id":100031045,"name":"Less","signature":"func (s ByVersionPriority) Less(i, j int) bool","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/v1/helper/helpers.go","code":"func (s ByVersionPriority) Less(i, j int) bool {\n\tif s[i].Spec.VersionPriority != s[j].Spec.VersionPriority {\n\t\treturn s[i].Spec.VersionPriority \u003e s[j].Spec.VersionPriority\n\t}\n\treturn version.CompareKubeAwareVersionStrings(s[i].Spec.Version, s[j].Spec.Version) \u003e 0\n}","line":{"from":81,"to":86}} {"id":100031046,"name":"APIServiceNameToGroupVersion","signature":"func APIServiceNameToGroupVersion(apiServiceName string) schema.GroupVersion","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/v1/helper/helpers.go","code":"// APIServiceNameToGroupVersion returns the GroupVersion for a given apiServiceName. The name\n// must be valid, but any object you get back from an informer will be valid.\nfunc APIServiceNameToGroupVersion(apiServiceName string) schema.GroupVersion {\n\ttokens := strings.SplitN(apiServiceName, \".\", 2)\n\treturn schema.GroupVersion{Group: tokens[1], Version: tokens[0]}\n}","line":{"from":88,"to":93}} {"id":100031047,"name":"NewLocalAvailableAPIServiceCondition","signature":"func NewLocalAvailableAPIServiceCondition() v1.APIServiceCondition","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/v1/helper/helpers.go","code":"// NewLocalAvailableAPIServiceCondition returns a condition for an available local APIService.\nfunc NewLocalAvailableAPIServiceCondition() v1.APIServiceCondition {\n\treturn v1.APIServiceCondition{\n\t\tType: v1.Available,\n\t\tStatus: v1.ConditionTrue,\n\t\tLastTransitionTime: metav1.Now(),\n\t\tReason: \"Local\",\n\t\tMessage: \"Local APIServices are always available\",\n\t}\n}","line":{"from":95,"to":104}} {"id":100031048,"name":"SetAPIServiceCondition","signature":"func SetAPIServiceCondition(apiService *v1.APIService, newCondition v1.APIServiceCondition)","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/v1/helper/helpers.go","code":"// SetAPIServiceCondition sets the status condition. It either overwrites the existing one or\n// creates a new one\nfunc SetAPIServiceCondition(apiService *v1.APIService, newCondition v1.APIServiceCondition) {\n\texistingCondition := GetAPIServiceConditionByType(apiService, newCondition.Type)\n\tif existingCondition == nil {\n\t\tapiService.Status.Conditions = append(apiService.Status.Conditions, newCondition)\n\t\treturn\n\t}\n\n\tif existingCondition.Status != newCondition.Status {\n\t\texistingCondition.Status = newCondition.Status\n\t\texistingCondition.LastTransitionTime = newCondition.LastTransitionTime\n\t}\n\n\texistingCondition.Reason = newCondition.Reason\n\texistingCondition.Message = newCondition.Message\n}","line":{"from":106,"to":122}} {"id":100031049,"name":"IsAPIServiceConditionTrue","signature":"func IsAPIServiceConditionTrue(apiService *v1.APIService, conditionType v1.APIServiceConditionType) bool","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/v1/helper/helpers.go","code":"// IsAPIServiceConditionTrue indicates if the condition is present and strictly true\nfunc IsAPIServiceConditionTrue(apiService *v1.APIService, conditionType v1.APIServiceConditionType) bool {\n\tcondition := GetAPIServiceConditionByType(apiService, conditionType)\n\treturn condition != nil \u0026\u0026 condition.Status == v1.ConditionTrue\n}","line":{"from":124,"to":128}} {"id":100031050,"name":"GetAPIServiceConditionByType","signature":"func GetAPIServiceConditionByType(apiService *v1.APIService, conditionType v1.APIServiceConditionType) *v1.APIServiceCondition","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/v1/helper/helpers.go","code":"// GetAPIServiceConditionByType gets an *APIServiceCondition by APIServiceConditionType if present\nfunc GetAPIServiceConditionByType(apiService *v1.APIService, conditionType v1.APIServiceConditionType) *v1.APIServiceCondition {\n\tfor i := range apiService.Status.Conditions {\n\t\tif apiService.Status.Conditions[i].Type == conditionType {\n\t\t\treturn \u0026apiService.Status.Conditions[i]\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":130,"to":138}} {"id":100031051,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/v1/register.go","code":"// Resource takes an unqualified resource and returns back a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100031052,"name":"init","signature":"func init()","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addKnownTypes, addDefaultingFuncs)\n}","line":{"from":46,"to":51}} {"id":100031053,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/v1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026APIService{},\n\t\t\u0026APIServiceList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":53,"to":61}} {"id":100031054,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/v1beta1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":24,"to":26}} {"id":100031055,"name":"SetDefaults_ServiceReference","signature":"func SetDefaults_ServiceReference(obj *ServiceReference)","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/v1beta1/defaults.go","code":"// SetDefaults_ServiceReference sets defaults for AuditSync Webhook's ServiceReference\nfunc SetDefaults_ServiceReference(obj *ServiceReference) {\n\tif obj.Port == nil {\n\t\tobj.Port = utilpointer.Int32Ptr(443)\n\t}\n}","line":{"from":28,"to":33}} {"id":100031056,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns back a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100031057,"name":"init","signature":"func init()","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/v1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addKnownTypes, addDefaultingFuncs)\n}","line":{"from":46,"to":51}} {"id":100031058,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/v1beta1/register.go","code":"// Adds the list of known types to the given scheme.\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026APIService{},\n\t\t\u0026APIServiceList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":53,"to":61}} {"id":100031059,"name":"ValidateAPIService","signature":"func ValidateAPIService(apiService *apiregistration.APIService) field.ErrorList","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/validation/validation.go","code":"// ValidateAPIService validates that the APIService is correctly defined.\nfunc ValidateAPIService(apiService *apiregistration.APIService) field.ErrorList {\n\trequiredName := apiService.Spec.Version + \".\" + apiService.Spec.Group\n\n\tallErrs := validation.ValidateObjectMeta(\u0026apiService.ObjectMeta, false,\n\t\tfunc(name string, prefix bool) []string {\n\t\t\tif minimalFailures := path.IsValidPathSegmentName(name); len(minimalFailures) \u003e 0 {\n\t\t\t\treturn minimalFailures\n\t\t\t}\n\t\t\t// the name *must* be version.group\n\t\t\tif name != requiredName {\n\t\t\t\treturn []string{fmt.Sprintf(\"must be `spec.version+\\\".\\\"+spec.group`: %q\", requiredName)}\n\t\t\t}\n\n\t\t\treturn []string{}\n\t\t},\n\t\tfield.NewPath(\"metadata\"))\n\n\t// in this case we allow empty group\n\tif len(apiService.Spec.Group) == 0 \u0026\u0026 apiService.Spec.Version != \"v1\" {\n\t\tallErrs = append(allErrs, field.Required(field.NewPath(\"spec\", \"group\"), \"only v1 may have an empty group and it better be legacy kube\"))\n\t}\n\tif len(apiService.Spec.Group) \u003e 0 {\n\t\tfor _, errString := range utilvalidation.IsDNS1123Subdomain(apiService.Spec.Group) {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"spec\", \"group\"), apiService.Spec.Group, errString))\n\t\t}\n\t}\n\n\tfor _, errString := range utilvalidation.IsDNS1035Label(apiService.Spec.Version) {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"spec\", \"version\"), apiService.Spec.Version, errString))\n\t}\n\n\tif apiService.Spec.GroupPriorityMinimum \u003c= 0 || apiService.Spec.GroupPriorityMinimum \u003e 20000 {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"spec\", \"groupPriorityMinimum\"), apiService.Spec.GroupPriorityMinimum, \"must be positive and less than 20000\"))\n\t}\n\tif apiService.Spec.VersionPriority \u003c= 0 || apiService.Spec.VersionPriority \u003e 1000 {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"spec\", \"versionPriority\"), apiService.Spec.VersionPriority, \"must be positive and less than 1000\"))\n\t}\n\n\tif apiService.Spec.Service == nil {\n\t\tif len(apiService.Spec.CABundle) != 0 {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"spec\", \"caBundle\"), fmt.Sprintf(\"%d bytes\", len(apiService.Spec.CABundle)), \"local APIServices may not have a caBundle\"))\n\t\t}\n\t\tif apiService.Spec.InsecureSkipTLSVerify {\n\t\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"spec\", \"insecureSkipTLSVerify\"), apiService.Spec.InsecureSkipTLSVerify, \"local APIServices may not have insecureSkipTLSVerify\"))\n\t\t}\n\t\treturn allErrs\n\t}\n\n\tif len(apiService.Spec.Service.Namespace) == 0 {\n\t\tallErrs = append(allErrs, field.Required(field.NewPath(\"spec\", \"service\", \"namespace\"), \"\"))\n\t}\n\tif len(apiService.Spec.Service.Name) == 0 {\n\t\tallErrs = append(allErrs, field.Required(field.NewPath(\"spec\", \"service\", \"name\"), \"\"))\n\t}\n\tif errs := utilvalidation.IsValidPortNum(int(apiService.Spec.Service.Port)); errs != nil {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"spec\", \"service\", \"port\"), apiService.Spec.Service.Port, \"port is not valid: \"+strings.Join(errs, \", \")))\n\t}\n\tif apiService.Spec.InsecureSkipTLSVerify \u0026\u0026 len(apiService.Spec.CABundle) \u003e 0 {\n\t\tallErrs = append(allErrs, field.Invalid(field.NewPath(\"spec\", \"insecureSkipTLSVerify\"), apiService.Spec.InsecureSkipTLSVerify, \"may not be true if caBundle is present\"))\n\t}\n\n\treturn allErrs\n}","line":{"from":31,"to":94}} {"id":100031060,"name":"ValidateAPIServiceUpdate","signature":"func ValidateAPIServiceUpdate(newAPIService *apiregistration.APIService, oldAPIService *apiregistration.APIService) field.ErrorList","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/validation/validation.go","code":"// ValidateAPIServiceUpdate validates an update of APIService.\nfunc ValidateAPIServiceUpdate(newAPIService *apiregistration.APIService, oldAPIService *apiregistration.APIService) field.ErrorList {\n\tallErrs := validation.ValidateObjectMetaUpdate(\u0026newAPIService.ObjectMeta, \u0026oldAPIService.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateAPIService(newAPIService)...)\n\n\treturn allErrs\n}","line":{"from":96,"to":102}} {"id":100031061,"name":"ValidateAPIServiceStatus","signature":"func ValidateAPIServiceStatus(status *apiregistration.APIServiceStatus, fldPath *field.Path) field.ErrorList","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/validation/validation.go","code":"// ValidateAPIServiceStatus validates that the APIService status is one of 'True', 'False' or 'Unknown'.\nfunc ValidateAPIServiceStatus(status *apiregistration.APIServiceStatus, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tfor i, condition := range status.Conditions {\n\t\tif condition.Status != apiregistration.ConditionTrue \u0026\u0026\n\t\t\tcondition.Status != apiregistration.ConditionFalse \u0026\u0026\n\t\t\tcondition.Status != apiregistration.ConditionUnknown {\n\t\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"conditions\").Index(i).Child(\"status\"), condition.Status, []string{\n\t\t\t\tstring(apiregistration.ConditionTrue), string(apiregistration.ConditionFalse), string(apiregistration.ConditionUnknown)}))\n\t\t}\n\t}\n\n\treturn allErrs\n}","line":{"from":104,"to":118}} {"id":100031062,"name":"ValidateAPIServiceStatusUpdate","signature":"func ValidateAPIServiceStatusUpdate(newAPIService *apiregistration.APIService, oldAPIService *apiregistration.APIService) field.ErrorList","file":"staging/src/k8s.io/kube-aggregator/pkg/apis/apiregistration/validation/validation.go","code":"// ValidateAPIServiceStatusUpdate validates an update of the status field of APIService.\nfunc ValidateAPIServiceStatusUpdate(newAPIService *apiregistration.APIService, oldAPIService *apiregistration.APIService) field.ErrorList {\n\tallErrs := validation.ValidateObjectMetaUpdate(\u0026newAPIService.ObjectMeta, \u0026oldAPIService.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateAPIServiceStatus(\u0026newAPIService.Status, field.NewPath(\"status\"))...)\n\treturn allErrs\n}","line":{"from":120,"to":125}} {"id":100031063,"name":"init","signature":"func init()","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/apiserver.go","code":"func init() {\n\t// we need to add the options (like ListOptions) to empty v1\n\tmetav1.AddToGroupVersion(aggregatorscheme.Scheme, schema.GroupVersion{Group: \"\", Version: \"v1\"})\n\n\tunversioned := schema.GroupVersion{Group: \"\", Version: \"v1\"}\n\taggregatorscheme.Scheme.AddUnversionedTypes(unversioned,\n\t\t\u0026metav1.Status{},\n\t\t\u0026metav1.APIVersions{},\n\t\t\u0026metav1.APIGroupList{},\n\t\t\u0026metav1.APIGroup{},\n\t\t\u0026metav1.APIResourceList{},\n\t)\n}","line":{"from":57,"to":69}} {"id":100031064,"name":"Complete","signature":"func (cfg *Config) Complete() CompletedConfig","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/apiserver.go","code":"// Complete fills in any fields not set that are required to have valid data. It's mutating the receiver.\nfunc (cfg *Config) Complete() CompletedConfig {\n\tc := completedConfig{\n\t\tcfg.GenericConfig.Complete(),\n\t\t\u0026cfg.ExtraConfig,\n\t}\n\n\t// the kube aggregator wires its own discovery mechanism\n\t// TODO eventually collapse this by extracting all of the discovery out\n\tc.GenericConfig.EnableDiscovery = false\n\tversion := version.Get()\n\tc.GenericConfig.Version = \u0026version\n\n\treturn CompletedConfig{\u0026c}\n}","line":{"from":168,"to":182}} {"id":100031065,"name":"NewWithDelegate","signature":"func (c completedConfig) NewWithDelegate(delegationTarget genericapiserver.DelegationTarget) (*APIAggregator, error)","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/apiserver.go","code":"// NewWithDelegate returns a new instance of APIAggregator from the given config.\nfunc (c completedConfig) NewWithDelegate(delegationTarget genericapiserver.DelegationTarget) (*APIAggregator, error) {\n\tgenericServer, err := c.GenericConfig.New(\"kube-aggregator\", delegationTarget)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapiregistrationClient, err := clientset.NewForConfig(c.GenericConfig.LoopbackClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinformerFactory := informers.NewSharedInformerFactory(\n\t\tapiregistrationClient,\n\t\t5*time.Minute, // this is effectively used as a refresh interval right now. Might want to do something nicer later on.\n\t)\n\n\t// apiServiceRegistrationControllerInitiated is closed when APIServiceRegistrationController has finished \"installing\" all known APIServices.\n\t// At this point we know that the proxy handler knows about APIServices and can handle client requests.\n\t// Before it might have resulted in a 404 response which could have serious consequences for some controllers like GC and NS\n\t//\n\t// Note that the APIServiceRegistrationController waits for APIServiceInformer to synced before doing its work.\n\tapiServiceRegistrationControllerInitiated := make(chan struct{})\n\tif err := genericServer.RegisterMuxAndDiscoveryCompleteSignal(\"APIServiceRegistrationControllerInitiated\", apiServiceRegistrationControllerInitiated); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar proxyTransportDial *transport.DialHolder\n\tif c.GenericConfig.EgressSelector != nil {\n\t\tegressDialer, err := c.GenericConfig.EgressSelector.Lookup(egressselector.Cluster.AsNetworkContext())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif egressDialer != nil {\n\t\t\tproxyTransportDial = \u0026transport.DialHolder{Dial: egressDialer}\n\t\t}\n\t} else if c.ExtraConfig.ProxyTransport != nil \u0026\u0026 c.ExtraConfig.ProxyTransport.DialContext != nil {\n\t\tproxyTransportDial = \u0026transport.DialHolder{Dial: c.ExtraConfig.ProxyTransport.DialContext}\n\t}\n\n\ts := \u0026APIAggregator{\n\t\tGenericAPIServer: genericServer,\n\t\tdelegateHandler: delegationTarget.UnprotectedHandler(),\n\t\tproxyTransportDial: proxyTransportDial,\n\t\tproxyHandlers: map[string]*proxyHandler{},\n\t\thandledGroups: sets.String{},\n\t\tlister: informerFactory.Apiregistration().V1().APIServices().Lister(),\n\t\tAPIRegistrationInformers: informerFactory,\n\t\tserviceResolver: c.ExtraConfig.ServiceResolver,\n\t\topenAPIConfig: c.GenericConfig.OpenAPIConfig,\n\t\topenAPIV3Config: c.GenericConfig.OpenAPIV3Config,\n\t\tproxyCurrentCertKeyContent: func() (bytes []byte, bytes2 []byte) { return nil, nil },\n\t\trejectForwardingRedirects: c.ExtraConfig.RejectForwardingRedirects,\n\t}\n\n\t// used later to filter the served resource by those that have expired.\n\tresourceExpirationEvaluator, err := genericapiserver.NewResourceExpirationEvaluator(*c.GenericConfig.Version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapiGroupInfo := apiservicerest.NewRESTStorage(c.GenericConfig.MergedResourceConfig, c.GenericConfig.RESTOptionsGetter, resourceExpirationEvaluator.ShouldServeForVersion(1, 22))\n\tif err := s.GenericAPIServer.InstallAPIGroup(\u0026apiGroupInfo); err != nil {\n\t\treturn nil, err\n\t}\n\n\tenabledVersions := sets.NewString()\n\tfor v := range apiGroupInfo.VersionedResourcesStorageMap {\n\t\tenabledVersions.Insert(v)\n\t}\n\tif !enabledVersions.Has(v1.SchemeGroupVersion.Version) {\n\t\treturn nil, fmt.Errorf(\"API group/version %s must be enabled\", v1.SchemeGroupVersion.String())\n\t}\n\n\tapisHandler := \u0026apisHandler{\n\t\tcodecs: aggregatorscheme.Codecs,\n\t\tlister: s.lister,\n\t\tdiscoveryGroup: discoveryGroup(enabledVersions),\n\t}\n\n\tif utilfeature.DefaultFeatureGate.Enabled(genericfeatures.AggregatedDiscoveryEndpoint) {\n\t\tapisHandlerWithAggregationSupport := aggregated.WrapAggregatedDiscoveryToHandler(apisHandler, s.GenericAPIServer.AggregatedDiscoveryGroupManager)\n\t\ts.GenericAPIServer.Handler.NonGoRestfulMux.Handle(\"/apis\", apisHandlerWithAggregationSupport)\n\t} else {\n\t\ts.GenericAPIServer.Handler.NonGoRestfulMux.Handle(\"/apis\", apisHandler)\n\t}\n\ts.GenericAPIServer.Handler.NonGoRestfulMux.UnlistedHandle(\"/apis/\", apisHandler)\n\n\tapiserviceRegistrationController := NewAPIServiceRegistrationController(informerFactory.Apiregistration().V1().APIServices(), s)\n\tif len(c.ExtraConfig.ProxyClientCertFile) \u003e 0 \u0026\u0026 len(c.ExtraConfig.ProxyClientKeyFile) \u003e 0 {\n\t\taggregatorProxyCerts, err := dynamiccertificates.NewDynamicServingContentFromFiles(\"aggregator-proxy-cert\", c.ExtraConfig.ProxyClientCertFile, c.ExtraConfig.ProxyClientKeyFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// We are passing the context to ProxyCerts.RunOnce as it needs to implement RunOnce(ctx) however the\n\t\t// context is not used at all. So passing a empty context shouldn't be a problem\n\t\tctx := context.TODO()\n\t\tif err := aggregatorProxyCerts.RunOnce(ctx); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\taggregatorProxyCerts.AddListener(apiserviceRegistrationController)\n\t\ts.proxyCurrentCertKeyContent = aggregatorProxyCerts.CurrentCertKeyContent\n\n\t\ts.GenericAPIServer.AddPostStartHookOrDie(\"aggregator-reload-proxy-client-cert\", func(postStartHookContext genericapiserver.PostStartHookContext) error {\n\t\t\t// generate a context from stopCh. This is to avoid modifying files which are relying on apiserver\n\t\t\t// TODO: See if we can pass ctx to the current method\n\t\t\tctx, cancel := context.WithCancel(context.Background())\n\t\t\tgo func() {\n\t\t\t\tselect {\n\t\t\t\tcase \u003c-postStartHookContext.StopCh:\n\t\t\t\t\tcancel() // stopCh closed, so cancel our context\n\t\t\t\tcase \u003c-ctx.Done():\n\t\t\t\t}\n\t\t\t}()\n\t\t\tgo aggregatorProxyCerts.Run(ctx, 1)\n\t\t\treturn nil\n\t\t})\n\t}\n\n\tavailableController, err := statuscontrollers.NewAvailableConditionController(\n\t\tinformerFactory.Apiregistration().V1().APIServices(),\n\t\tc.GenericConfig.SharedInformerFactory.Core().V1().Services(),\n\t\tc.GenericConfig.SharedInformerFactory.Core().V1().Endpoints(),\n\t\tapiregistrationClient.ApiregistrationV1(),\n\t\tproxyTransportDial,\n\t\t(func() ([]byte, []byte))(s.proxyCurrentCertKeyContent),\n\t\ts.serviceResolver,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.GenericAPIServer.AddPostStartHookOrDie(\"start-kube-aggregator-informers\", func(context genericapiserver.PostStartHookContext) error {\n\t\tinformerFactory.Start(context.StopCh)\n\t\tc.GenericConfig.SharedInformerFactory.Start(context.StopCh)\n\t\treturn nil\n\t})\n\ts.GenericAPIServer.AddPostStartHookOrDie(\"apiservice-registration-controller\", func(context genericapiserver.PostStartHookContext) error {\n\t\tgo apiserviceRegistrationController.Run(context.StopCh, apiServiceRegistrationControllerInitiated)\n\t\tselect {\n\t\tcase \u003c-context.StopCh:\n\t\tcase \u003c-apiServiceRegistrationControllerInitiated:\n\t\t}\n\n\t\treturn nil\n\t})\n\ts.GenericAPIServer.AddPostStartHookOrDie(\"apiservice-status-available-controller\", func(context genericapiserver.PostStartHookContext) error {\n\t\t// if we end up blocking for long periods of time, we may need to increase workers.\n\t\tgo availableController.Run(5, context.StopCh)\n\t\treturn nil\n\t})\n\n\tif utilfeature.DefaultFeatureGate.Enabled(genericfeatures.StorageVersionAPI) \u0026\u0026\n\t\tutilfeature.DefaultFeatureGate.Enabled(genericfeatures.APIServerIdentity) {\n\t\t// Spawn a goroutine in aggregator apiserver to update storage version for\n\t\t// all built-in resources\n\t\ts.GenericAPIServer.AddPostStartHookOrDie(StorageVersionPostStartHookName, func(hookContext genericapiserver.PostStartHookContext) error {\n\t\t\t// Wait for apiserver-identity to exist first before updating storage\n\t\t\t// versions, to avoid storage version GC accidentally garbage-collecting\n\t\t\t// storage versions.\n\t\t\tkubeClient, err := kubernetes.NewForConfig(hookContext.LoopbackClientConfig)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := wait.PollImmediateUntil(100*time.Millisecond, func() (bool, error) {\n\t\t\t\t_, err := kubeClient.CoordinationV1().Leases(metav1.NamespaceSystem).Get(\n\t\t\t\t\tcontext.TODO(), s.GenericAPIServer.APIServerID, metav1.GetOptions{})\n\t\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\treturn true, nil\n\t\t\t}, hookContext.StopCh); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to wait for apiserver-identity lease %s to be created: %v\",\n\t\t\t\t\ts.GenericAPIServer.APIServerID, err)\n\t\t\t}\n\t\t\t// Technically an apiserver only needs to update storage version once during bootstrap.\n\t\t\t// Reconcile StorageVersion objects every 10 minutes will help in the case that the\n\t\t\t// StorageVersion objects get accidentally modified/deleted by a different agent. In that\n\t\t\t// case, the reconciliation ensures future storage migration still works. If nothing gets\n\t\t\t// changed, the reconciliation update is a noop and gets short-circuited by the apiserver,\n\t\t\t// therefore won't change the resource version and trigger storage migration.\n\t\t\tgo wait.PollImmediateUntil(10*time.Minute, func() (bool, error) {\n\t\t\t\t// All apiservers (aggregator-apiserver, kube-apiserver, apiextensions-apiserver)\n\t\t\t\t// share the same generic apiserver config. The same StorageVersion manager is used\n\t\t\t\t// to register all built-in resources when the generic apiservers install APIs.\n\t\t\t\ts.GenericAPIServer.StorageVersionManager.UpdateStorageVersions(hookContext.LoopbackClientConfig, s.GenericAPIServer.APIServerID)\n\t\t\t\treturn false, nil\n\t\t\t}, hookContext.StopCh)\n\t\t\t// Once the storage version updater finishes the first round of update,\n\t\t\t// the PostStartHook will return to unblock /healthz. The handler chain\n\t\t\t// won't block write requests anymore. Check every second since it's not\n\t\t\t// expensive.\n\t\t\twait.PollImmediateUntil(1*time.Second, func() (bool, error) {\n\t\t\t\treturn s.GenericAPIServer.StorageVersionManager.Completed(), nil\n\t\t\t}, hookContext.StopCh)\n\t\t\treturn nil\n\t\t})\n\t}\n\n\treturn s, nil\n}","line":{"from":184,"to":386}} {"id":100031066,"name":"PrepareRun","signature":"func (s *APIAggregator) PrepareRun() (preparedAPIAggregator, error)","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/apiserver.go","code":"// PrepareRun prepares the aggregator to run, by setting up the OpenAPI spec \u0026\n// aggregated discovery document and calling the generic PrepareRun.\nfunc (s *APIAggregator) PrepareRun() (preparedAPIAggregator, error) {\n\t// add post start hook before generic PrepareRun in order to be before /healthz installation\n\tif s.openAPIConfig != nil {\n\t\ts.GenericAPIServer.AddPostStartHookOrDie(\"apiservice-openapi-controller\", func(context genericapiserver.PostStartHookContext) error {\n\t\t\tgo s.openAPIAggregationController.Run(context.StopCh)\n\t\t\treturn nil\n\t\t})\n\t}\n\n\tif s.openAPIV3Config != nil \u0026\u0026 utilfeature.DefaultFeatureGate.Enabled(genericfeatures.OpenAPIV3) {\n\t\ts.GenericAPIServer.AddPostStartHookOrDie(\"apiservice-openapiv3-controller\", func(context genericapiserver.PostStartHookContext) error {\n\t\t\tgo s.openAPIV3AggregationController.Run(context.StopCh)\n\t\t\treturn nil\n\t\t})\n\t}\n\n\tif utilfeature.DefaultFeatureGate.Enabled(genericfeatures.AggregatedDiscoveryEndpoint) {\n\t\ts.discoveryAggregationController = NewDiscoveryManager(\n\t\t\t// Use aggregator as the source name to avoid overwriting native/CRD\n\t\t\t// groups\n\t\t\ts.GenericAPIServer.AggregatedDiscoveryGroupManager.WithSource(aggregated.AggregatorSource),\n\t\t)\n\n\t\t// Setup discovery endpoint\n\t\ts.GenericAPIServer.AddPostStartHookOrDie(\"apiservice-discovery-controller\", func(context genericapiserver.PostStartHookContext) error {\n\t\t\t// Run discovery manager's worker to watch for new/removed/updated\n\t\t\t// APIServices to the discovery document can be updated at runtime\n\t\t\tgo s.discoveryAggregationController.Run(context.StopCh)\n\t\t\treturn nil\n\t\t})\n\t}\n\n\tprepared := s.GenericAPIServer.PrepareRun()\n\n\t// delay OpenAPI setup until the delegate had a chance to setup their OpenAPI handlers\n\tif s.openAPIConfig != nil {\n\t\tspecDownloader := openapiaggregator.NewDownloader()\n\t\topenAPIAggregator, err := openapiaggregator.BuildAndRegisterAggregator(\n\t\t\t\u0026specDownloader,\n\t\t\ts.GenericAPIServer.NextDelegate(),\n\t\t\ts.GenericAPIServer.Handler.GoRestfulContainer.RegisteredWebServices(),\n\t\t\ts.openAPIConfig,\n\t\t\ts.GenericAPIServer.Handler.NonGoRestfulMux)\n\t\tif err != nil {\n\t\t\treturn preparedAPIAggregator{}, err\n\t\t}\n\t\ts.openAPIAggregationController = openapicontroller.NewAggregationController(\u0026specDownloader, openAPIAggregator)\n\t}\n\n\tif s.openAPIV3Config != nil \u0026\u0026 utilfeature.DefaultFeatureGate.Enabled(genericfeatures.OpenAPIV3) {\n\t\tspecDownloaderV3 := openapiv3aggregator.NewDownloader()\n\t\topenAPIV3Aggregator, err := openapiv3aggregator.BuildAndRegisterAggregator(\n\t\t\tspecDownloaderV3,\n\t\t\ts.GenericAPIServer.NextDelegate(),\n\t\t\ts.GenericAPIServer.Handler.NonGoRestfulMux)\n\t\tif err != nil {\n\t\t\treturn preparedAPIAggregator{}, err\n\t\t}\n\t\ts.openAPIV3AggregationController = openapiv3controller.NewAggregationController(openAPIV3Aggregator)\n\t}\n\n\treturn preparedAPIAggregator{APIAggregator: s, runnable: prepared}, nil\n}","line":{"from":388,"to":452}} {"id":100031067,"name":"Run","signature":"func (s preparedAPIAggregator) Run(stopCh \u003c-chan struct{}) error","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/apiserver.go","code":"func (s preparedAPIAggregator) Run(stopCh \u003c-chan struct{}) error {\n\treturn s.runnable.Run(stopCh)\n}","line":{"from":454,"to":456}} {"id":100031068,"name":"AddAPIService","signature":"func (s *APIAggregator) AddAPIService(apiService *v1.APIService) error","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/apiserver.go","code":"// AddAPIService adds an API service. It is not thread-safe, so only call it on one thread at a time please.\n// It's a slow moving API, so its ok to run the controller on a single thread\nfunc (s *APIAggregator) AddAPIService(apiService *v1.APIService) error {\n\t// if the proxyHandler already exists, it needs to be updated. The aggregation bits do not\n\t// since they are wired against listers because they require multiple resources to respond\n\tif proxyHandler, exists := s.proxyHandlers[apiService.Name]; exists {\n\t\tproxyHandler.updateAPIService(apiService)\n\t\tif s.openAPIAggregationController != nil {\n\t\t\ts.openAPIAggregationController.UpdateAPIService(proxyHandler, apiService)\n\t\t}\n\t\tif s.openAPIV3AggregationController != nil {\n\t\t\ts.openAPIV3AggregationController.UpdateAPIService(proxyHandler, apiService)\n\t\t}\n\t\t// Forward calls to discovery manager to update discovery document\n\t\tif s.discoveryAggregationController != nil {\n\t\t\thandlerCopy := *proxyHandler\n\t\t\thandlerCopy.setServiceAvailable()\n\t\t\ts.discoveryAggregationController.AddAPIService(apiService, \u0026handlerCopy)\n\t\t}\n\t\treturn nil\n\t}\n\n\tproxyPath := \"/apis/\" + apiService.Spec.Group + \"/\" + apiService.Spec.Version\n\t// v1. is a special case for the legacy API. It proxies to a wider set of endpoints.\n\tif apiService.Name == legacyAPIServiceName {\n\t\tproxyPath = \"/api\"\n\t}\n\n\t// register the proxy handler\n\tproxyHandler := \u0026proxyHandler{\n\t\tlocalDelegate: s.delegateHandler,\n\t\tproxyCurrentCertKeyContent: s.proxyCurrentCertKeyContent,\n\t\tproxyTransportDial: s.proxyTransportDial,\n\t\tserviceResolver: s.serviceResolver,\n\t\trejectForwardingRedirects: s.rejectForwardingRedirects,\n\t}\n\tproxyHandler.updateAPIService(apiService)\n\tif s.openAPIAggregationController != nil {\n\t\ts.openAPIAggregationController.AddAPIService(proxyHandler, apiService)\n\t}\n\tif s.openAPIV3AggregationController != nil {\n\t\ts.openAPIV3AggregationController.AddAPIService(proxyHandler, apiService)\n\t}\n\tif s.discoveryAggregationController != nil {\n\t\ts.discoveryAggregationController.AddAPIService(apiService, proxyHandler)\n\t}\n\n\ts.proxyHandlers[apiService.Name] = proxyHandler\n\ts.GenericAPIServer.Handler.NonGoRestfulMux.Handle(proxyPath, proxyHandler)\n\ts.GenericAPIServer.Handler.NonGoRestfulMux.UnlistedHandlePrefix(proxyPath+\"/\", proxyHandler)\n\n\t// if we're dealing with the legacy group, we're done here\n\tif apiService.Name == legacyAPIServiceName {\n\t\treturn nil\n\t}\n\n\t// if we've already registered the path with the handler, we don't want to do it again.\n\tif s.handledGroups.Has(apiService.Spec.Group) {\n\t\treturn nil\n\t}\n\n\t// it's time to register the group aggregation endpoint\n\tgroupPath := \"/apis/\" + apiService.Spec.Group\n\tgroupDiscoveryHandler := \u0026apiGroupHandler{\n\t\tcodecs: aggregatorscheme.Codecs,\n\t\tgroupName: apiService.Spec.Group,\n\t\tlister: s.lister,\n\t\tdelegate: s.delegateHandler,\n\t}\n\t// aggregation is protected\n\ts.GenericAPIServer.Handler.NonGoRestfulMux.Handle(groupPath, groupDiscoveryHandler)\n\ts.GenericAPIServer.Handler.NonGoRestfulMux.UnlistedHandle(groupPath+\"/\", groupDiscoveryHandler)\n\ts.handledGroups.Insert(apiService.Spec.Group)\n\treturn nil\n}","line":{"from":458,"to":532}} {"id":100031069,"name":"RemoveAPIService","signature":"func (s *APIAggregator) RemoveAPIService(apiServiceName string)","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/apiserver.go","code":"// RemoveAPIService removes the APIService from being handled. It is not thread-safe, so only call it on one thread at a time please.\n// It's a slow moving API, so it's ok to run the controller on a single thread.\nfunc (s *APIAggregator) RemoveAPIService(apiServiceName string) {\n\t// Forward calls to discovery manager to update discovery document\n\tif s.discoveryAggregationController != nil {\n\t\ts.discoveryAggregationController.RemoveAPIService(apiServiceName)\n\t}\n\n\tversion := v1helper.APIServiceNameToGroupVersion(apiServiceName)\n\n\tproxyPath := \"/apis/\" + version.Group + \"/\" + version.Version\n\t// v1. is a special case for the legacy API. It proxies to a wider set of endpoints.\n\tif apiServiceName == legacyAPIServiceName {\n\t\tproxyPath = \"/api\"\n\t}\n\ts.GenericAPIServer.Handler.NonGoRestfulMux.Unregister(proxyPath)\n\ts.GenericAPIServer.Handler.NonGoRestfulMux.Unregister(proxyPath + \"/\")\n\tif s.openAPIAggregationController != nil {\n\t\ts.openAPIAggregationController.RemoveAPIService(apiServiceName)\n\t}\n\tif s.openAPIV3AggregationController != nil {\n\t\ts.openAPIAggregationController.RemoveAPIService(apiServiceName)\n\t}\n\tdelete(s.proxyHandlers, apiServiceName)\n\n\t// TODO unregister group level discovery when there are no more versions for the group\n\t// We don't need this right away because the handler properly delegates when no versions are present\n}","line":{"from":534,"to":561}} {"id":100031070,"name":"DefaultAPIResourceConfigSource","signature":"func DefaultAPIResourceConfigSource() *serverstorage.ResourceConfig","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/apiserver.go","code":"// DefaultAPIResourceConfigSource returns default configuration for an APIResource.\nfunc DefaultAPIResourceConfigSource() *serverstorage.ResourceConfig {\n\tret := serverstorage.NewResourceConfig()\n\t// NOTE: GroupVersions listed here will be enabled by default. Don't put alpha versions in the list.\n\tret.EnableVersions(\n\t\tv1.SchemeGroupVersion,\n\t\tv1beta1.SchemeGroupVersion,\n\t)\n\n\treturn ret\n}","line":{"from":563,"to":573}} {"id":100031071,"name":"NewAPIServiceRegistrationController","signature":"func NewAPIServiceRegistrationController(apiServiceInformer informers.APIServiceInformer, apiHandlerManager APIHandlerManager) *APIServiceRegistrationController","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/apiservice_controller.go","code":"// NewAPIServiceRegistrationController returns a new APIServiceRegistrationController.\nfunc NewAPIServiceRegistrationController(apiServiceInformer informers.APIServiceInformer, apiHandlerManager APIHandlerManager) *APIServiceRegistrationController {\n\tc := \u0026APIServiceRegistrationController{\n\t\tapiHandlerManager: apiHandlerManager,\n\t\tapiServiceLister: apiServiceInformer.Lister(),\n\t\tapiServiceSynced: apiServiceInformer.Informer().HasSynced,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"APIServiceRegistrationController\"),\n\t}\n\n\tapiServiceInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: c.addAPIService,\n\t\tUpdateFunc: c.updateAPIService,\n\t\tDeleteFunc: c.deleteAPIService,\n\t})\n\n\tc.syncFn = c.sync\n\n\treturn c\n}","line":{"from":59,"to":77}} {"id":100031072,"name":"sync","signature":"func (c *APIServiceRegistrationController) sync(key string) error","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/apiservice_controller.go","code":"func (c *APIServiceRegistrationController) sync(key string) error {\n\tapiService, err := c.apiServiceLister.Get(key)\n\tif apierrors.IsNotFound(err) {\n\t\tc.apiHandlerManager.RemoveAPIService(key)\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.apiHandlerManager.AddAPIService(apiService)\n}","line":{"from":79,"to":90}} {"id":100031073,"name":"Run","signature":"func (c *APIServiceRegistrationController) Run(stopCh \u003c-chan struct{}, handlerSyncedCh chan\u003c- struct{})","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/apiservice_controller.go","code":"// Run starts APIServiceRegistrationController which will process all registration requests until stopCh is closed.\nfunc (c *APIServiceRegistrationController) Run(stopCh \u003c-chan struct{}, handlerSyncedCh chan\u003c- struct{}) {\n\tdefer utilruntime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\n\tklog.Info(\"Starting APIServiceRegistrationController\")\n\tdefer klog.Info(\"Shutting down APIServiceRegistrationController\")\n\n\tif !controllers.WaitForCacheSync(\"APIServiceRegistrationController\", stopCh, c.apiServiceSynced) {\n\t\treturn\n\t}\n\n\t/// initially sync all APIServices to make sure the proxy handler is complete\n\tif err := wait.PollImmediateUntil(time.Second, func() (bool, error) {\n\t\tservices, err := c.apiServiceLister.List(labels.Everything())\n\t\tif err != nil {\n\t\t\tutilruntime.HandleError(fmt.Errorf(\"failed to initially list APIServices: %v\", err))\n\t\t\treturn false, nil\n\t\t}\n\t\tfor _, s := range services {\n\t\t\tif err := c.apiHandlerManager.AddAPIService(s); err != nil {\n\t\t\t\tutilruntime.HandleError(fmt.Errorf(\"failed to initially sync APIService %s: %v\", s.Name, err))\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t}\n\t\treturn true, nil\n\t}, stopCh); err == wait.ErrWaitTimeout {\n\t\tutilruntime.HandleError(fmt.Errorf(\"timed out waiting for proxy handler to initialize\"))\n\t\treturn\n\t} else if err != nil {\n\t\tpanic(fmt.Errorf(\"unexpected error: %v\", err))\n\t}\n\tclose(handlerSyncedCh)\n\n\t// only start one worker thread since its a slow moving API and the aggregation server adding bits\n\t// aren't threadsafe\n\tgo wait.Until(c.runWorker, time.Second, stopCh)\n\n\t\u003c-stopCh\n}","line":{"from":92,"to":131}} {"id":100031074,"name":"runWorker","signature":"func (c *APIServiceRegistrationController) runWorker()","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/apiservice_controller.go","code":"func (c *APIServiceRegistrationController) runWorker() {\n\tfor c.processNextWorkItem() {\n\t}\n}","line":{"from":133,"to":136}} {"id":100031075,"name":"processNextWorkItem","signature":"func (c *APIServiceRegistrationController) processNextWorkItem() bool","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/apiservice_controller.go","code":"// processNextWorkItem deals with one key off the queue. It returns false when it's time to quit.\nfunc (c *APIServiceRegistrationController) processNextWorkItem() bool {\n\tkey, quit := c.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.queue.Done(key)\n\n\terr := c.syncFn(key.(string))\n\tif err == nil {\n\t\tc.queue.Forget(key)\n\t\treturn true\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"%v failed with : %v\", key, err))\n\tc.queue.AddRateLimited(key)\n\n\treturn true\n}","line":{"from":138,"to":156}} {"id":100031076,"name":"enqueueInternal","signature":"func (c *APIServiceRegistrationController) enqueueInternal(obj *v1.APIService)","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/apiservice_controller.go","code":"func (c *APIServiceRegistrationController) enqueueInternal(obj *v1.APIService) {\n\tkey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)\n\tif err != nil {\n\t\tklog.Errorf(\"Couldn't get key for object %#v: %v\", obj, err)\n\t\treturn\n\t}\n\n\tc.queue.Add(key)\n}","line":{"from":158,"to":166}} {"id":100031077,"name":"addAPIService","signature":"func (c *APIServiceRegistrationController) addAPIService(obj interface{})","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/apiservice_controller.go","code":"func (c *APIServiceRegistrationController) addAPIService(obj interface{}) {\n\tcastObj := obj.(*v1.APIService)\n\tklog.V(4).Infof(\"Adding %s\", castObj.Name)\n\tc.enqueueInternal(castObj)\n}","line":{"from":168,"to":172}} {"id":100031078,"name":"updateAPIService","signature":"func (c *APIServiceRegistrationController) updateAPIService(obj, _ interface{})","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/apiservice_controller.go","code":"func (c *APIServiceRegistrationController) updateAPIService(obj, _ interface{}) {\n\tcastObj := obj.(*v1.APIService)\n\tklog.V(4).Infof(\"Updating %s\", castObj.Name)\n\tc.enqueueInternal(castObj)\n}","line":{"from":174,"to":178}} {"id":100031079,"name":"deleteAPIService","signature":"func (c *APIServiceRegistrationController) deleteAPIService(obj interface{})","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/apiservice_controller.go","code":"func (c *APIServiceRegistrationController) deleteAPIService(obj interface{}) {\n\tcastObj, ok := obj.(*v1.APIService)\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"Couldn't get object from tombstone %#v\", obj)\n\t\t\treturn\n\t\t}\n\t\tcastObj, ok = tombstone.Obj.(*v1.APIService)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"Tombstone contained object that is not expected %#v\", obj)\n\t\t\treturn\n\t\t}\n\t}\n\tklog.V(4).Infof(\"Deleting %q\", castObj.Name)\n\tc.enqueueInternal(castObj)\n}","line":{"from":180,"to":196}} {"id":100031080,"name":"Enqueue","signature":"func (c *APIServiceRegistrationController) Enqueue()","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/apiservice_controller.go","code":"// Enqueue queues all apiservices to be rehandled.\n// This method is used by the controller to notify when the proxy cert content changes.\nfunc (c *APIServiceRegistrationController) Enqueue() {\n\tapiServices, err := c.apiServiceLister.List(labels.Everything())\n\tif err != nil {\n\t\tutilruntime.HandleError(err)\n\t\treturn\n\t}\n\tfor _, apiService := range apiServices {\n\t\tc.addAPIService(apiService)\n\t}\n}","line":{"from":198,"to":209}} {"id":100031081,"name":"discoveryGroup","signature":"func discoveryGroup(enabledVersions sets.String) metav1.APIGroup","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_apis.go","code":"func discoveryGroup(enabledVersions sets.String) metav1.APIGroup {\n\tretval := metav1.APIGroup{\n\t\tName: apiregistrationv1api.GroupName,\n\t\tVersions: []metav1.GroupVersionForDiscovery{\n\t\t\t{\n\t\t\t\tGroupVersion: apiregistrationv1api.SchemeGroupVersion.String(),\n\t\t\t\tVersion: apiregistrationv1api.SchemeGroupVersion.Version,\n\t\t\t},\n\t\t},\n\t\tPreferredVersion: metav1.GroupVersionForDiscovery{\n\t\t\tGroupVersion: apiregistrationv1api.SchemeGroupVersion.String(),\n\t\t\tVersion: apiregistrationv1api.SchemeGroupVersion.Version,\n\t\t},\n\t}\n\n\tif enabledVersions.Has(apiregistrationv1beta1api.SchemeGroupVersion.Version) {\n\t\tretval.Versions = append(retval.Versions, metav1.GroupVersionForDiscovery{\n\t\t\tGroupVersion: apiregistrationv1beta1api.SchemeGroupVersion.String(),\n\t\t\tVersion: apiregistrationv1beta1api.SchemeGroupVersion.Version,\n\t\t})\n\t}\n\n\treturn retval\n}","line":{"from":45,"to":68}} {"id":100031082,"name":"ServeHTTP","signature":"func (r *apisHandler) ServeHTTP(w http.ResponseWriter, req *http.Request)","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_apis.go","code":"func (r *apisHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tdiscoveryGroupList := \u0026metav1.APIGroupList{\n\t\t// always add OUR api group to the list first. Since we'll never have a registered APIService for it\n\t\t// and since this is the crux of the API, having this first will give our names priority. It's good to be king.\n\t\tGroups: []metav1.APIGroup{r.discoveryGroup},\n\t}\n\n\tapiServices, err := r.lister.List(labels.Everything())\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tapiServicesByGroup := apiregistrationv1apihelper.SortedByGroupAndVersion(apiServices)\n\tfor _, apiGroupServers := range apiServicesByGroup {\n\t\t// skip the legacy group\n\t\tif len(apiGroupServers[0].Spec.Group) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tdiscoveryGroup := convertToDiscoveryAPIGroup(apiGroupServers)\n\t\tif discoveryGroup != nil {\n\t\t\tdiscoveryGroupList.Groups = append(discoveryGroupList.Groups, *discoveryGroup)\n\t\t}\n\t}\n\n\tresponsewriters.WriteObjectNegotiated(r.codecs, negotiation.DefaultEndpointRestrictions, schema.GroupVersion{}, w, req, http.StatusOK, discoveryGroupList, false)\n}","line":{"from":70,"to":95}} {"id":100031083,"name":"convertToDiscoveryAPIGroup","signature":"func convertToDiscoveryAPIGroup(apiServices []*apiregistrationv1api.APIService) *metav1.APIGroup","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_apis.go","code":"// convertToDiscoveryAPIGroup takes apiservices in a single group and returns a discovery compatible object.\n// if none of the services are available, it will return nil.\nfunc convertToDiscoveryAPIGroup(apiServices []*apiregistrationv1api.APIService) *metav1.APIGroup {\n\tapiServicesByGroup := apiregistrationv1apihelper.SortedByGroupAndVersion(apiServices)[0]\n\n\tvar discoveryGroup *metav1.APIGroup\n\n\tfor _, apiService := range apiServicesByGroup {\n\t\t// the first APIService which is valid becomes the default\n\t\tif discoveryGroup == nil {\n\t\t\tdiscoveryGroup = \u0026metav1.APIGroup{\n\t\t\t\tName: apiService.Spec.Group,\n\t\t\t\tPreferredVersion: metav1.GroupVersionForDiscovery{\n\t\t\t\t\tGroupVersion: apiService.Spec.Group + \"/\" + apiService.Spec.Version,\n\t\t\t\t\tVersion: apiService.Spec.Version,\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\n\t\tdiscoveryGroup.Versions = append(discoveryGroup.Versions,\n\t\t\tmetav1.GroupVersionForDiscovery{\n\t\t\t\tGroupVersion: apiService.Spec.Group + \"/\" + apiService.Spec.Version,\n\t\t\t\tVersion: apiService.Spec.Version,\n\t\t\t},\n\t\t)\n\t}\n\n\treturn discoveryGroup\n}","line":{"from":97,"to":125}} {"id":100031084,"name":"ServeHTTP","signature":"func (r *apiGroupHandler) ServeHTTP(w http.ResponseWriter, req *http.Request)","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_apis.go","code":"func (r *apiGroupHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tapiServices, err := r.lister.List(labels.Everything())\n\tif statusErr, ok := err.(*apierrors.StatusError); ok {\n\t\tresponsewriters.WriteRawJSON(int(statusErr.Status().Code), statusErr.Status(), w)\n\t\treturn\n\t}\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tapiServicesForGroup := []*apiregistrationv1api.APIService{}\n\tfor _, apiService := range apiServices {\n\t\tif apiService.Spec.Group == r.groupName {\n\t\t\tapiServicesForGroup = append(apiServicesForGroup, apiService)\n\t\t}\n\t}\n\n\tif len(apiServicesForGroup) == 0 {\n\t\tr.delegate.ServeHTTP(w, req)\n\t\treturn\n\t}\n\n\tdiscoveryGroup := convertToDiscoveryAPIGroup(apiServicesForGroup)\n\tif discoveryGroup == nil {\n\t\thttp.Error(w, \"\", http.StatusNotFound)\n\t\treturn\n\t}\n\tresponsewriters.WriteObjectNegotiated(r.codecs, negotiation.DefaultEndpointRestrictions, schema.GroupVersion{}, w, req, http.StatusOK, discoveryGroup, false)\n}","line":{"from":137,"to":166}} {"id":100031085,"name":"String","signature":"func (s serviceKey) String() string","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_discovery.go","code":"// Human-readable String representation used for logs\nfunc (s serviceKey) String() string {\n\treturn fmt.Sprintf(\"%v/%v:%v\", s.Namespace, s.Name, s.Port)\n}","line":{"from":98,"to":101}} {"id":100031086,"name":"newServiceKey","signature":"func newServiceKey(service apiregistrationv1.ServiceReference) serviceKey","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_discovery.go","code":"func newServiceKey(service apiregistrationv1.ServiceReference) serviceKey {\n\t// Docs say. Defaults to 443 for compatibility reasons.\n\t// BETA: Should this be a shared constant to avoid drifting with the\n\t// implementation?\n\tport := int32(443)\n\tif service.Port != nil {\n\t\tport = *service.Port\n\t}\n\n\treturn serviceKey{\n\t\tName: service.Name,\n\t\tNamespace: service.Namespace,\n\t\tPort: port,\n\t}\n}","line":{"from":103,"to":117}} {"id":100031087,"name":"NewDiscoveryManager","signature":"func NewDiscoveryManager(","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_discovery.go","code":"func NewDiscoveryManager(\n\ttarget discoveryendpoint.ResourceManager,\n) DiscoveryAggregationController {\n\treturn \u0026discoveryManager{\n\t\tmergedDiscoveryHandler: target,\n\t\tapiServices: make(map[string]groupVersionInfo),\n\t\tcachedResults: make(map[serviceKey]cachedResult),\n\t\tdirtyAPIServiceQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"discovery-manager\"),\n\t}\n}","line":{"from":162,"to":171}} {"id":100031088,"name":"fetchFreshDiscoveryForService","signature":"func (dm *discoveryManager) fetchFreshDiscoveryForService(gv metav1.GroupVersion, info groupVersionInfo) (*cachedResult, error)","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_discovery.go","code":"// Returns discovery data for the given apiservice.\n// Caches the result.\n// Returns the cached result if it is retrieved after the apiservice was last\n// marked dirty\n// If there was an error in fetching, returns the stale cached result if it exists,\n// and a non-nil error\n// If the result is current, returns nil error and non-nil result\nfunc (dm *discoveryManager) fetchFreshDiscoveryForService(gv metav1.GroupVersion, info groupVersionInfo) (*cachedResult, error) {\n\t// Lookup last cached result for this apiservice's service.\n\tcached, exists := dm.getCacheEntryForService(info.service)\n\n\t// If entry exists and was updated after the given time, just stop now\n\tif exists \u0026\u0026 cached.lastUpdated.After(info.lastMarkedDirty) {\n\t\treturn \u0026cached, nil\n\t}\n\n\t// If we have a handler to contact the server for this APIService, and\n\t// the cache entry is too old to use, refresh the cache entry now.\n\thandler := http.TimeoutHandler(info.handler, 5*time.Second, \"request timed out\")\n\treq, err := http.NewRequest(\"GET\", \"/apis\", nil)\n\tif err != nil {\n\t\t// NewRequest should not fail, but if it does for some reason,\n\t\t// log it and continue\n\t\treturn \u0026cached, fmt.Errorf(\"failed to create http.Request: %v\", err)\n\t}\n\n\t// Apply aggregator user to request\n\treq = req.WithContext(\n\t\trequest.WithUser(\n\t\t\treq.Context(), \u0026user.DefaultInfo{Name: \"system:kube-aggregator\", Groups: []string{\"system:masters\"}}))\n\treq = req.WithContext(request.WithRequestInfo(req.Context(), \u0026request.RequestInfo{\n\t\tPath: req.URL.Path,\n\t\tIsResourceRequest: false,\n\t}))\n\treq.Header.Add(\"Accept\", runtime.ContentTypeJSON+\";g=apidiscovery.k8s.io;v=v2beta1;as=APIGroupDiscoveryList\")\n\n\tif exists \u0026\u0026 len(cached.etag) \u003e 0 {\n\t\treq.Header.Add(\"If-None-Match\", cached.etag)\n\t}\n\n\t// Important that the time recorded in the data's \"lastUpdated\" is conservatively\n\t// from BEFORE the request is dispatched so that lastUpdated can be used to\n\t// de-duplicate requests.\n\tnow := time.Now()\n\twriter := newInMemoryResponseWriter()\n\thandler.ServeHTTP(writer, req)\n\n\tswitch writer.respCode {\n\tcase http.StatusNotModified:\n\t\t// Keep old entry, update timestamp\n\t\tcached = cachedResult{\n\t\t\tdiscovery: cached.discovery,\n\t\t\tetag: cached.etag,\n\t\t\tlastUpdated: now,\n\t\t}\n\n\t\tdm.setCacheEntryForService(info.service, cached)\n\t\treturn \u0026cached, nil\n\tcase http.StatusNotAcceptable:\n\t\t// Discovery Document is not being served at all.\n\t\t// Fall back to legacy discovery information\n\t\tif len(gv.Version) == 0 {\n\t\t\treturn nil, errors.New(\"not found\")\n\t\t}\n\n\t\tvar path string\n\t\tif len(gv.Group) == 0 {\n\t\t\tpath = \"/api/\" + gv.Version\n\t\t} else {\n\t\t\tpath = \"/apis/\" + gv.Group + \"/\" + gv.Version\n\t\t}\n\n\t\treq, err := http.NewRequest(\"GET\", path, nil)\n\t\tif err != nil {\n\t\t\t// NewRequest should not fail, but if it does for some reason,\n\t\t\t// log it and continue\n\t\t\treturn nil, fmt.Errorf(\"failed to create http.Request: %v\", err)\n\t\t}\n\n\t\t// Apply aggregator user to request\n\t\treq = req.WithContext(\n\t\t\trequest.WithUser(\n\t\t\t\treq.Context(), \u0026user.DefaultInfo{Name: \"system:kube-aggregator\"}))\n\n\t\t// req.Header.Add(\"Accept\", runtime.ContentTypeProtobuf)\n\t\treq.Header.Add(\"Accept\", runtime.ContentTypeJSON)\n\n\t\tif exists \u0026\u0026 len(cached.etag) \u003e 0 {\n\t\t\treq.Header.Add(\"If-None-Match\", cached.etag)\n\t\t}\n\n\t\twriter := newInMemoryResponseWriter()\n\t\thandler.ServeHTTP(writer, req)\n\n\t\tif writer.respCode != http.StatusOK {\n\t\t\treturn nil, fmt.Errorf(\"failed to download discovery for %s: %v\", path, writer.String())\n\t\t}\n\n\t\tparsed := \u0026metav1.APIResourceList{}\n\t\tif err := runtime.DecodeInto(scheme.Codecs.UniversalDecoder(), writer.data, parsed); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Create a discomap with single group-version\n\t\tresources, err := endpoints.ConvertGroupVersionIntoToDiscovery(parsed.APIResources)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tdiscoMap := map[metav1.GroupVersion]apidiscoveryv2beta1.APIVersionDiscovery{\n\t\t\t// Convert old-style APIGroupList to new information\n\t\t\tgv: {\n\t\t\t\tVersion: gv.Version,\n\t\t\t\tResources: resources,\n\t\t\t},\n\t\t}\n\n\t\tcached = cachedResult{\n\t\t\tdiscovery: discoMap,\n\t\t\tlastUpdated: now,\n\t\t}\n\n\t\t// Do not save the resolve as the legacy fallback only fetches\n\t\t// one group version and an API Service may serve multiple\n\t\t// group versions.\n\t\treturn \u0026cached, nil\n\n\tcase http.StatusOK:\n\t\tparsed := \u0026apidiscoveryv2beta1.APIGroupDiscoveryList{}\n\t\tif err := runtime.DecodeInto(scheme.Codecs.UniversalDecoder(), writer.data, parsed); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tklog.V(3).Infof(\"DiscoveryManager: Successfully downloaded discovery for %s\", info.service.String())\n\n\t\t// Convert discovery info into a map for convenient lookup later\n\t\tdiscoMap := map[metav1.GroupVersion]apidiscoveryv2beta1.APIVersionDiscovery{}\n\t\tfor _, g := range parsed.Items {\n\t\t\tfor _, v := range g.Versions {\n\t\t\t\tdiscoMap[metav1.GroupVersion{Group: g.Name, Version: v.Version}] = v\n\t\t\t}\n\t\t}\n\n\t\t// Save cached result\n\t\tcached = cachedResult{\n\t\t\tdiscovery: discoMap,\n\t\t\tetag: writer.Header().Get(\"Etag\"),\n\t\t\tlastUpdated: now,\n\t\t}\n\t\tdm.setCacheEntryForService(info.service, cached)\n\t\treturn \u0026cached, nil\n\n\tdefault:\n\t\tklog.Infof(\"DiscoveryManager: Failed to download discovery for %v: %v %s\",\n\t\t\tinfo.service.String(), writer.respCode, writer.data)\n\t\treturn nil, fmt.Errorf(\"service %s returned non-success response code: %v\",\n\t\t\tinfo.service.String(), writer.respCode)\n\t}\n}","line":{"from":173,"to":330}} {"id":100031089,"name":"syncAPIService","signature":"func (dm *discoveryManager) syncAPIService(apiServiceName string) error","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_discovery.go","code":"// Try to sync a single APIService.\nfunc (dm *discoveryManager) syncAPIService(apiServiceName string) error {\n\tinfo, exists := dm.getInfoForAPIService(apiServiceName)\n\n\tgv := helper.APIServiceNameToGroupVersion(apiServiceName)\n\tmgv := metav1.GroupVersion{Group: gv.Group, Version: gv.Version}\n\n\tif !exists {\n\t\t// apiservice was removed. remove it from merged discovery\n\t\tdm.mergedDiscoveryHandler.RemoveGroupVersion(mgv)\n\t\treturn nil\n\t}\n\n\t// Lookup last cached result for this apiservice's service.\n\tcached, err := dm.fetchFreshDiscoveryForService(mgv, info)\n\n\tvar entry apidiscoveryv2beta1.APIVersionDiscovery\n\n\t// Extract the APIService's specific resource information from the\n\t// groupversion\n\tif cached == nil {\n\t\t// There was an error fetching discovery for this APIService, and\n\t\t// there is nothing in the cache for this GV.\n\t\t//\n\t\t// Just use empty GV to mark that GV exists, but no resources.\n\t\t// Also mark that it is stale to indicate the fetch failed\n\t\t// TODO: Maybe also stick in a status for the version the error?\n\t\tentry = apidiscoveryv2beta1.APIVersionDiscovery{\n\t\t\tVersion: gv.Version,\n\t\t}\n\t} else {\n\t\t// Find our specific groupversion within the discovery document\n\t\tentry, exists = cached.discovery[mgv]\n\t\tif exists {\n\t\t\t// The stale/fresh entry has our GV, so we can include it in the doc\n\t\t} else {\n\t\t\t// Successfully fetched discovery information from the server, but\n\t\t\t// the server did not include this groupversion?\n\t\t\tentry = apidiscoveryv2beta1.APIVersionDiscovery{\n\t\t\t\tVersion: gv.Version,\n\t\t\t}\n\t\t}\n\t}\n\n\t// The entry's staleness depends upon if `fetchFreshDiscoveryForService`\n\t// returned an error or not.\n\tif err == nil {\n\t\tentry.Freshness = apidiscoveryv2beta1.DiscoveryFreshnessCurrent\n\t} else {\n\t\tentry.Freshness = apidiscoveryv2beta1.DiscoveryFreshnessStale\n\t}\n\n\tdm.mergedDiscoveryHandler.AddGroupVersion(gv.Group, entry)\n\tdm.mergedDiscoveryHandler.SetGroupVersionPriority(metav1.GroupVersion(gv), info.groupPriority, info.versionPriority)\n\treturn nil\n}","line":{"from":332,"to":387}} {"id":100031090,"name":"Run","signature":"func (dm *discoveryManager) Run(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_discovery.go","code":"// Spwans a goroutune which waits for added/updated apiservices and updates\n// the discovery document accordingly\nfunc (dm *discoveryManager) Run(stopCh \u003c-chan struct{}) {\n\tklog.Info(\"Starting ResourceDiscoveryManager\")\n\n\t// Shutdown the queue since stopCh was signalled\n\tdefer dm.dirtyAPIServiceQueue.ShutDown()\n\n\t// Spawn workers\n\t// These workers wait for APIServices to be marked dirty.\n\t// Worker ensures the cached discovery document hosted by the ServiceReference of\n\t// the APIService is at least as fresh as the APIService, then includes the\n\t// APIService's groupversion into the merged document\n\tfor i := 0; i \u003c 2; i++ {\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tnext, shutdown := dm.dirtyAPIServiceQueue.Get()\n\t\t\t\tif shutdown {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tfunc() {\n\t\t\t\t\tdefer dm.dirtyAPIServiceQueue.Done(next)\n\n\t\t\t\t\tif err := dm.syncAPIService(next.(string)); err != nil {\n\t\t\t\t\t\tdm.dirtyAPIServiceQueue.AddRateLimited(next)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdm.dirtyAPIServiceQueue.Forget(next)\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t}\n\t\t}()\n\t}\n\n\t// Ensure that apiregistration.k8s.io is the first group in the discovery group.\n\tdm.mergedDiscoveryHandler.WithSource(discoveryendpoint.BuiltinSource).SetGroupVersionPriority(APIRegistrationGroupVersion, APIRegistrationGroupPriority, 0)\n\n\twait.PollUntil(1*time.Minute, func() (done bool, err error) {\n\t\tdm.servicesLock.Lock()\n\t\tdefer dm.servicesLock.Unlock()\n\n\t\tnow := time.Now()\n\n\t\t// Mark all non-local APIServices as dirty\n\t\tfor key, info := range dm.apiServices {\n\t\t\tinfo.lastMarkedDirty = now\n\t\t\tdm.apiServices[key] = info\n\t\t\tdm.dirtyAPIServiceQueue.Add(key)\n\t\t}\n\t\treturn false, nil\n\t}, stopCh)\n}","line":{"from":389,"to":440}} {"id":100031091,"name":"AddAPIService","signature":"func (dm *discoveryManager) AddAPIService(apiService *apiregistrationv1.APIService, handler http.Handler)","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_discovery.go","code":"// Adds an APIService to be tracked by the discovery manager. If the APIService\n// is already known\nfunc (dm *discoveryManager) AddAPIService(apiService *apiregistrationv1.APIService, handler http.Handler) {\n\t// If service is nil then its information is contained by a local APIService\n\t// which is has already been added to the manager.\n\tif apiService.Spec.Service == nil {\n\t\treturn\n\t}\n\n\t// Add or update APIService record and mark it as dirty\n\tdm.setInfoForAPIService(apiService.Name, \u0026groupVersionInfo{\n\t\tgroupPriority: int(apiService.Spec.GroupPriorityMinimum),\n\t\tversionPriority: int(apiService.Spec.VersionPriority),\n\t\thandler: handler,\n\t\tlastMarkedDirty: time.Now(),\n\t\tservice: newServiceKey(*apiService.Spec.Service),\n\t})\n\tdm.dirtyAPIServiceQueue.Add(apiService.Name)\n}","line":{"from":442,"to":460}} {"id":100031092,"name":"RemoveAPIService","signature":"func (dm *discoveryManager) RemoveAPIService(apiServiceName string)","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_discovery.go","code":"func (dm *discoveryManager) RemoveAPIService(apiServiceName string) {\n\tif dm.setInfoForAPIService(apiServiceName, nil) != nil {\n\t\t// mark dirty if there was actually something deleted\n\t\tdm.dirtyAPIServiceQueue.Add(apiServiceName)\n\t}\n}","line":{"from":462,"to":467}} {"id":100031093,"name":"getCacheEntryForService","signature":"func (dm *discoveryManager) getCacheEntryForService(key serviceKey) (cachedResult, bool)","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_discovery.go","code":"func (dm *discoveryManager) getCacheEntryForService(key serviceKey) (cachedResult, bool) {\n\tdm.resultsLock.RLock()\n\tdefer dm.resultsLock.RUnlock()\n\n\tresult, ok := dm.cachedResults[key]\n\treturn result, ok\n}","line":{"from":473,"to":479}} {"id":100031094,"name":"setCacheEntryForService","signature":"func (dm *discoveryManager) setCacheEntryForService(key serviceKey, result cachedResult)","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_discovery.go","code":"func (dm *discoveryManager) setCacheEntryForService(key serviceKey, result cachedResult) {\n\tdm.resultsLock.Lock()\n\tdefer dm.resultsLock.Unlock()\n\n\tdm.cachedResults[key] = result\n}","line":{"from":481,"to":486}} {"id":100031095,"name":"getInfoForAPIService","signature":"func (dm *discoveryManager) getInfoForAPIService(name string) (groupVersionInfo, bool)","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_discovery.go","code":"func (dm *discoveryManager) getInfoForAPIService(name string) (groupVersionInfo, bool) {\n\tdm.servicesLock.RLock()\n\tdefer dm.servicesLock.RUnlock()\n\n\tresult, ok := dm.apiServices[name]\n\treturn result, ok\n}","line":{"from":488,"to":494}} {"id":100031096,"name":"setInfoForAPIService","signature":"func (dm *discoveryManager) setInfoForAPIService(name string, result *groupVersionInfo) (oldValueIfExisted *groupVersionInfo)","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_discovery.go","code":"func (dm *discoveryManager) setInfoForAPIService(name string, result *groupVersionInfo) (oldValueIfExisted *groupVersionInfo) {\n\tdm.servicesLock.Lock()\n\tdefer dm.servicesLock.Unlock()\n\n\tif oldValue, exists := dm.apiServices[name]; exists {\n\t\toldValueIfExisted = \u0026oldValue\n\t}\n\n\tif result != nil {\n\t\tdm.apiServices[name] = *result\n\t} else {\n\t\tdelete(dm.apiServices, name)\n\t}\n\n\treturn oldValueIfExisted\n}","line":{"from":496,"to":511}} {"id":100031097,"name":"newInMemoryResponseWriter","signature":"func newInMemoryResponseWriter() *inMemoryResponseWriter","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_discovery.go","code":"func newInMemoryResponseWriter() *inMemoryResponseWriter {\n\treturn \u0026inMemoryResponseWriter{header: http.Header{}}\n}","line":{"from":524,"to":526}} {"id":100031098,"name":"Header","signature":"func (r *inMemoryResponseWriter) Header() http.Header","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_discovery.go","code":"func (r *inMemoryResponseWriter) Header() http.Header {\n\treturn r.header\n}","line":{"from":528,"to":530}} {"id":100031099,"name":"WriteHeader","signature":"func (r *inMemoryResponseWriter) WriteHeader(code int)","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_discovery.go","code":"func (r *inMemoryResponseWriter) WriteHeader(code int) {\n\tr.writeHeaderCalled = true\n\tr.respCode = code\n}","line":{"from":532,"to":535}} {"id":100031100,"name":"Write","signature":"func (r *inMemoryResponseWriter) Write(in []byte) (int, error)","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_discovery.go","code":"func (r *inMemoryResponseWriter) Write(in []byte) (int, error) {\n\tif !r.writeHeaderCalled {\n\t\tr.WriteHeader(http.StatusOK)\n\t}\n\tr.data = append(r.data, in...)\n\treturn len(in), nil\n}","line":{"from":537,"to":543}} {"id":100031101,"name":"String","signature":"func (r *inMemoryResponseWriter) String() string","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_discovery.go","code":"func (r *inMemoryResponseWriter) String() string {\n\ts := fmt.Sprintf(\"ResponseCode: %d\", r.respCode)\n\tif r.data != nil {\n\t\ts += fmt.Sprintf(\", Body: %s\", string(r.data))\n\t}\n\tif r.header != nil {\n\t\ts += fmt.Sprintf(\", Header: %s\", r.header)\n\t}\n\treturn s\n}","line":{"from":545,"to":554}} {"id":100031102,"name":"proxyError","signature":"func proxyError(w http.ResponseWriter, req *http.Request, error string, code int)","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_proxy.go","code":"func proxyError(w http.ResponseWriter, req *http.Request, error string, code int) {\n\thttp.Error(w, error, code)\n\n\tctx := req.Context()\n\tinfo, ok := genericapirequest.RequestInfoFrom(ctx)\n\tif !ok {\n\t\tklog.Warning(\"no RequestInfo found in the context\")\n\t\treturn\n\t}\n\t// TODO: record long-running request differently? The long-running check func does not necessarily match the one of the aggregated apiserver\n\tendpointmetrics.RecordRequestTermination(req, info, aggregatorComponent, code)\n}","line":{"from":94,"to":105}} {"id":100031103,"name":"ServeHTTP","signature":"func (r *proxyHandler) ServeHTTP(w http.ResponseWriter, req *http.Request)","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_proxy.go","code":"func (r *proxyHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tvalue := r.handlingInfo.Load()\n\tif value == nil {\n\t\tr.localDelegate.ServeHTTP(w, req)\n\t\treturn\n\t}\n\thandlingInfo := value.(proxyHandlingInfo)\n\tif handlingInfo.local {\n\t\tif r.localDelegate == nil {\n\t\t\thttp.Error(w, \"\", http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\t\tr.localDelegate.ServeHTTP(w, req)\n\t\treturn\n\t}\n\n\tif !handlingInfo.serviceAvailable {\n\t\tproxyError(w, req, \"service unavailable\", http.StatusServiceUnavailable)\n\t\treturn\n\t}\n\n\tif handlingInfo.transportBuildingError != nil {\n\t\tproxyError(w, req, handlingInfo.transportBuildingError.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tuser, ok := genericapirequest.UserFrom(req.Context())\n\tif !ok {\n\t\tproxyError(w, req, \"missing user\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// write a new location based on the existing request pointed at the target service\n\tlocation := \u0026url.URL{}\n\tlocation.Scheme = \"https\"\n\trloc, err := r.serviceResolver.ResolveEndpoint(handlingInfo.serviceNamespace, handlingInfo.serviceName, handlingInfo.servicePort)\n\tif err != nil {\n\t\tklog.Errorf(\"error resolving %s/%s: %v\", handlingInfo.serviceNamespace, handlingInfo.serviceName, err)\n\t\tproxyError(w, req, \"service unavailable\", http.StatusServiceUnavailable)\n\t\treturn\n\t}\n\tlocation.Host = rloc.Host\n\tlocation.Path = req.URL.Path\n\tlocation.RawQuery = req.URL.Query().Encode()\n\n\tnewReq, cancelFn := newRequestForProxy(location, req)\n\tdefer cancelFn()\n\n\tif handlingInfo.proxyRoundTripper == nil {\n\t\tproxyError(w, req, \"\", http.StatusNotFound)\n\t\treturn\n\t}\n\n\tproxyRoundTripper := handlingInfo.proxyRoundTripper\n\tupgrade := httpstream.IsUpgradeRequest(req)\n\n\tproxyRoundTripper = transport.NewAuthProxyRoundTripper(user.GetName(), user.GetGroups(), user.GetExtra(), proxyRoundTripper)\n\n\t// If we are upgrading, then the upgrade path tries to use this request with the TLS config we provide, but it does\n\t// NOT use the proxyRoundTripper. It's a direct dial that bypasses the proxyRoundTripper. This means that we have to\n\t// attach the \"correct\" user headers to the request ahead of time.\n\tif upgrade {\n\t\ttransport.SetAuthProxyHeaders(newReq, user.GetName(), user.GetGroups(), user.GetExtra())\n\t}\n\n\thandler := proxy.NewUpgradeAwareHandler(location, proxyRoundTripper, true, upgrade, \u0026responder{w: w})\n\tif r.rejectForwardingRedirects {\n\t\thandler.RejectForwardingRedirects = true\n\t}\n\tutilflowcontrol.RequestDelegated(req.Context())\n\thandler.ServeHTTP(w, newReq)\n}","line":{"from":107,"to":178}} {"id":100031104,"name":"newRequestForProxy","signature":"func newRequestForProxy(location *url.URL, req *http.Request) (*http.Request, context.CancelFunc)","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_proxy.go","code":"// newRequestForProxy returns a shallow copy of the original request with a context that may include a timeout for discovery requests\nfunc newRequestForProxy(location *url.URL, req *http.Request) (*http.Request, context.CancelFunc) {\n\tnewCtx := req.Context()\n\tcancelFn := func() {}\n\n\tif requestInfo, ok := genericapirequest.RequestInfoFrom(req.Context()); ok {\n\t\t// trim leading and trailing slashes. Then \"/apis/group/version\" requests are for discovery, so if we have exactly three\n\t\t// segments that we are going to proxy, we have a discovery request.\n\t\tif !requestInfo.IsResourceRequest \u0026\u0026 len(strings.Split(strings.Trim(requestInfo.Path, \"/\"), \"/\")) == 3 {\n\t\t\t// discovery requests are used by kubectl and others to determine which resources a server has. This is a cheap call that\n\t\t\t// should be fast for every aggregated apiserver. Latency for aggregation is expected to be low (as for all extensions)\n\t\t\t// so forcing a short timeout here helps responsiveness of all clients.\n\t\t\tnewCtx, cancelFn = context.WithTimeout(newCtx, aggregatedDiscoveryTimeout)\n\t\t}\n\t}\n\n\t// WithContext creates a shallow clone of the request with the same context.\n\tnewReq := req.WithContext(newCtx)\n\tnewReq.Header = utilnet.CloneHeader(req.Header)\n\tnewReq.URL = location\n\tnewReq.Host = location.Host\n\n\t// If the original request has an audit ID, let's make sure we propagate this\n\t// to the aggregated server.\n\tif auditID, found := audit.AuditIDFrom(req.Context()); found {\n\t\tnewReq.Header.Set(auditinternal.HeaderAuditID, string(auditID))\n\t}\n\n\treturn newReq, cancelFn\n}","line":{"from":180,"to":209}} {"id":100031105,"name":"Object","signature":"func (r *responder) Object(statusCode int, obj runtime.Object)","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_proxy.go","code":"// TODO this should properly handle content type negotiation\n// if the caller asked for protobuf and you write JSON bad things happen.\nfunc (r *responder) Object(statusCode int, obj runtime.Object) {\n\tresponsewriters.WriteRawJSON(statusCode, obj, r.w)\n}","line":{"from":216,"to":220}} {"id":100031106,"name":"Error","signature":"func (r *responder) Error(_ http.ResponseWriter, _ *http.Request, err error)","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_proxy.go","code":"func (r *responder) Error(_ http.ResponseWriter, _ *http.Request, err error) {\n\thttp.Error(r.w, err.Error(), http.StatusServiceUnavailable)\n}","line":{"from":222,"to":224}} {"id":100031107,"name":"setServiceAvailable","signature":"func (r *proxyHandler) setServiceAvailable()","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_proxy.go","code":"// Sets serviceAvailable value on proxyHandler\n// not thread safe\nfunc (r *proxyHandler) setServiceAvailable() {\n\tinfo := r.handlingInfo.Load().(proxyHandlingInfo)\n\tinfo.serviceAvailable = true\n\tr.handlingInfo.Store(info)\n}","line":{"from":228,"to":234}} {"id":100031108,"name":"updateAPIService","signature":"func (r *proxyHandler) updateAPIService(apiService *apiregistrationv1api.APIService)","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/handler_proxy.go","code":"func (r *proxyHandler) updateAPIService(apiService *apiregistrationv1api.APIService) {\n\tif apiService.Spec.Service == nil {\n\t\tr.handlingInfo.Store(proxyHandlingInfo{local: true})\n\t\treturn\n\t}\n\n\tproxyClientCert, proxyClientKey := r.proxyCurrentCertKeyContent()\n\n\ttransportConfig := \u0026transport.Config{\n\t\tTLS: transport.TLSConfig{\n\t\t\tInsecure: apiService.Spec.InsecureSkipTLSVerify,\n\t\t\tServerName: apiService.Spec.Service.Name + \".\" + apiService.Spec.Service.Namespace + \".svc\",\n\t\t\tCertData: proxyClientCert,\n\t\t\tKeyData: proxyClientKey,\n\t\t\tCAData: apiService.Spec.CABundle,\n\t\t},\n\t\tDialHolder: r.proxyTransportDial,\n\t}\n\ttransportConfig.Wrap(x509metrics.NewDeprecatedCertificateRoundTripperWrapperConstructor(\n\t\tx509MissingSANCounter,\n\t\tx509InsecureSHA1Counter,\n\t))\n\n\tnewInfo := proxyHandlingInfo{\n\t\tname: apiService.Name,\n\t\ttransportConfig: transportConfig,\n\t\tserviceName: apiService.Spec.Service.Name,\n\t\tserviceNamespace: apiService.Spec.Service.Namespace,\n\t\tservicePort: *apiService.Spec.Service.Port,\n\t\tserviceAvailable: apiregistrationv1apihelper.IsAPIServiceConditionTrue(apiService, apiregistrationv1api.Available),\n\t}\n\tnewInfo.proxyRoundTripper, newInfo.transportBuildingError = transport.New(newInfo.transportConfig)\n\tif newInfo.transportBuildingError != nil {\n\t\tklog.Warning(newInfo.transportBuildingError.Error())\n\t}\n\tr.handlingInfo.Store(newInfo)\n}","line":{"from":236,"to":272}} {"id":100031109,"name":"init","signature":"func init()","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/metrics.go","code":"func init() {\n\tlegacyregistry.MustRegister(x509MissingSANCounter)\n\tlegacyregistry.MustRegister(x509InsecureSHA1Counter)\n}","line":{"from":49,"to":52}} {"id":100031110,"name":"NewEndpointServiceResolver","signature":"func NewEndpointServiceResolver(services listersv1.ServiceLister, endpoints listersv1.EndpointsLister) ServiceResolver","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/resolvers.go","code":"// NewEndpointServiceResolver returns a ServiceResolver that chooses one of the\n// service's endpoints.\nfunc NewEndpointServiceResolver(services listersv1.ServiceLister, endpoints listersv1.EndpointsLister) ServiceResolver {\n\treturn \u0026aggregatorEndpointRouting{\n\t\tservices: services,\n\t\tendpoints: endpoints,\n\t}\n}","line":{"from":31,"to":38}} {"id":100031111,"name":"ResolveEndpoint","signature":"func (r *aggregatorEndpointRouting) ResolveEndpoint(namespace, name string, port int32) (*url.URL, error)","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/resolvers.go","code":"func (r *aggregatorEndpointRouting) ResolveEndpoint(namespace, name string, port int32) (*url.URL, error) {\n\treturn proxy.ResolveEndpoint(r.services, r.endpoints, namespace, name, port)\n}","line":{"from":45,"to":47}} {"id":100031112,"name":"NewClusterIPServiceResolver","signature":"func NewClusterIPServiceResolver(services listersv1.ServiceLister) ServiceResolver","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/resolvers.go","code":"// NewClusterIPServiceResolver returns a ServiceResolver that directly calls the\n// service's cluster IP.\nfunc NewClusterIPServiceResolver(services listersv1.ServiceLister) ServiceResolver {\n\treturn \u0026aggregatorClusterRouting{\n\t\tservices: services,\n\t}\n}","line":{"from":49,"to":55}} {"id":100031113,"name":"ResolveEndpoint","signature":"func (r *aggregatorClusterRouting) ResolveEndpoint(namespace, name string, port int32) (*url.URL, error)","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/resolvers.go","code":"func (r *aggregatorClusterRouting) ResolveEndpoint(namespace, name string, port int32) (*url.URL, error) {\n\treturn proxy.ResolveCluster(r.services, namespace, name, port)\n}","line":{"from":61,"to":63}} {"id":100031114,"name":"NewLoopbackServiceResolver","signature":"func NewLoopbackServiceResolver(delegate ServiceResolver, host *url.URL) ServiceResolver","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/resolvers.go","code":"// NewLoopbackServiceResolver returns a ServiceResolver that routes\n// the kubernetes/default service with port 443 to loopback.\nfunc NewLoopbackServiceResolver(delegate ServiceResolver, host *url.URL) ServiceResolver {\n\treturn \u0026loopbackResolver{\n\t\tdelegate: delegate,\n\t\thost: host,\n\t}\n}","line":{"from":65,"to":72}} {"id":100031115,"name":"ResolveEndpoint","signature":"func (r *loopbackResolver) ResolveEndpoint(namespace, name string, port int32) (*url.URL, error)","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/resolvers.go","code":"func (r *loopbackResolver) ResolveEndpoint(namespace, name string, port int32) (*url.URL, error) {\n\tif namespace == \"default\" \u0026\u0026 name == \"kubernetes\" \u0026\u0026 port == 443 {\n\t\treturn r.host, nil\n\t}\n\treturn r.delegate.ResolveEndpoint(namespace, name, port)\n}","line":{"from":79,"to":84}} {"id":100031116,"name":"init","signature":"func init()","file":"staging/src/k8s.io/kube-aggregator/pkg/apiserver/scheme/scheme.go","code":"func init() {\n\tinstall.Install(Scheme)\n}","line":{"from":34,"to":36}} {"id":100031117,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/apiregistration/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":41,"to":44}} {"id":100031118,"name":"V1beta1","signature":"func (g *group) V1beta1() v1beta1.Interface","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/apiregistration/interface.go","code":"// V1beta1 returns a new v1beta1.Interface.\nfunc (g *group) V1beta1() v1beta1.Interface {\n\treturn v1beta1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":46,"to":49}} {"id":100031119,"name":"V1","signature":"func (g *group) V1() v1.Interface","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/apiregistration/interface.go","code":"// V1 returns a new v1.Interface.\nfunc (g *group) V1() v1.Interface {\n\treturn v1.New(g.factory, g.namespace, g.tweakListOptions)\n}","line":{"from":51,"to":54}} {"id":100031120,"name":"NewAPIServiceInformer","signature":"func NewAPIServiceInformer(client clientset.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/apiregistration/v1/apiservice.go","code":"// NewAPIServiceInformer constructs a new informer for APIService type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewAPIServiceInformer(client clientset.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredAPIServiceInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100031121,"name":"NewFilteredAPIServiceInformer","signature":"func NewFilteredAPIServiceInformer(client clientset.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/apiregistration/v1/apiservice.go","code":"// NewFilteredAPIServiceInformer constructs a new informer for APIService type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredAPIServiceInformer(client clientset.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.ApiregistrationV1().APIServices().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.ApiregistrationV1().APIServices().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026apiregistrationv1.APIService{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100031122,"name":"defaultInformer","signature":"func (f *aPIServiceInformer) defaultInformer(client clientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/apiregistration/v1/apiservice.go","code":"func (f *aPIServiceInformer) defaultInformer(client clientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredAPIServiceInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100031123,"name":"Informer","signature":"func (f *aPIServiceInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/apiregistration/v1/apiservice.go","code":"func (f *aPIServiceInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026apiregistrationv1.APIService{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100031124,"name":"Lister","signature":"func (f *aPIServiceInformer) Lister() v1.APIServiceLister","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/apiregistration/v1/apiservice.go","code":"func (f *aPIServiceInformer) Lister() v1.APIServiceLister {\n\treturn v1.NewAPIServiceLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100031125,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/apiregistration/v1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":37,"to":40}} {"id":100031126,"name":"APIServices","signature":"func (v *version) APIServices() APIServiceInformer","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/apiregistration/v1/interface.go","code":"// APIServices returns a APIServiceInformer.\nfunc (v *version) APIServices() APIServiceInformer {\n\treturn \u0026aPIServiceInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":42,"to":45}} {"id":100031127,"name":"NewAPIServiceInformer","signature":"func NewAPIServiceInformer(client clientset.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/apiregistration/v1beta1/apiservice.go","code":"// NewAPIServiceInformer constructs a new informer for APIService type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewAPIServiceInformer(client clientset.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {\n\treturn NewFilteredAPIServiceInformer(client, resyncPeriod, indexers, nil)\n}","line":{"from":47,"to":52}} {"id":100031128,"name":"NewFilteredAPIServiceInformer","signature":"func NewFilteredAPIServiceInformer(client clientset.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/apiregistration/v1beta1/apiservice.go","code":"// NewFilteredAPIServiceInformer constructs a new informer for APIService type.\n// Always prefer using an informer factory to get a shared informer instead of getting an independent\n// one. This reduces memory footprint and number of connections to the server.\nfunc NewFilteredAPIServiceInformer(client clientset.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {\n\treturn cache.NewSharedIndexInformer(\n\t\t\u0026cache.ListWatch{\n\t\t\tListFunc: func(options v1.ListOptions) (runtime.Object, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.ApiregistrationV1beta1().APIServices().List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options v1.ListOptions) (watch.Interface, error) {\n\t\t\t\tif tweakListOptions != nil {\n\t\t\t\t\ttweakListOptions(\u0026options)\n\t\t\t\t}\n\t\t\t\treturn client.ApiregistrationV1beta1().APIServices().Watch(context.TODO(), options)\n\t\t\t},\n\t\t},\n\t\t\u0026apiregistrationv1beta1.APIService{},\n\t\tresyncPeriod,\n\t\tindexers,\n\t)\n}","line":{"from":54,"to":77}} {"id":100031129,"name":"defaultInformer","signature":"func (f *aPIServiceInformer) defaultInformer(client clientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/apiregistration/v1beta1/apiservice.go","code":"func (f *aPIServiceInformer) defaultInformer(client clientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {\n\treturn NewFilteredAPIServiceInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)\n}","line":{"from":79,"to":81}} {"id":100031130,"name":"Informer","signature":"func (f *aPIServiceInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/apiregistration/v1beta1/apiservice.go","code":"func (f *aPIServiceInformer) Informer() cache.SharedIndexInformer {\n\treturn f.factory.InformerFor(\u0026apiregistrationv1beta1.APIService{}, f.defaultInformer)\n}","line":{"from":83,"to":85}} {"id":100031131,"name":"Lister","signature":"func (f *aPIServiceInformer) Lister() v1beta1.APIServiceLister","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/apiregistration/v1beta1/apiservice.go","code":"func (f *aPIServiceInformer) Lister() v1beta1.APIServiceLister {\n\treturn v1beta1.NewAPIServiceLister(f.Informer().GetIndexer())\n}","line":{"from":87,"to":89}} {"id":100031132,"name":"New","signature":"func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/apiregistration/v1beta1/interface.go","code":"// New returns a new Interface.\nfunc New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn \u0026version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}\n}","line":{"from":37,"to":40}} {"id":100031133,"name":"APIServices","signature":"func (v *version) APIServices() APIServiceInformer","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/apiregistration/v1beta1/interface.go","code":"// APIServices returns a APIServiceInformer.\nfunc (v *version) APIServices() APIServiceInformer {\n\treturn \u0026aPIServiceInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}\n}","line":{"from":42,"to":45}} {"id":100031134,"name":"WithCustomResyncConfig","signature":"func WithCustomResyncConfig(resyncConfig map[v1.Object]time.Duration) SharedInformerOption","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/factory.go","code":"// WithCustomResyncConfig sets a custom resync period for the specified informer types.\nfunc WithCustomResyncConfig(resyncConfig map[v1.Object]time.Duration) SharedInformerOption {\n\treturn func(factory *sharedInformerFactory) *sharedInformerFactory {\n\t\tfor k, v := range resyncConfig {\n\t\t\tfactory.customResync[reflect.TypeOf(k)] = v\n\t\t}\n\t\treturn factory\n\t}\n}","line":{"from":57,"to":65}} {"id":100031135,"name":"WithTweakListOptions","signature":"func WithTweakListOptions(tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerOption","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/factory.go","code":"// WithTweakListOptions sets a custom filter on all listers of the configured SharedInformerFactory.\nfunc WithTweakListOptions(tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerOption {\n\treturn func(factory *sharedInformerFactory) *sharedInformerFactory {\n\t\tfactory.tweakListOptions = tweakListOptions\n\t\treturn factory\n\t}\n}","line":{"from":67,"to":73}} {"id":100031136,"name":"WithNamespace","signature":"func WithNamespace(namespace string) SharedInformerOption","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/factory.go","code":"// WithNamespace limits the SharedInformerFactory to the specified namespace.\nfunc WithNamespace(namespace string) SharedInformerOption {\n\treturn func(factory *sharedInformerFactory) *sharedInformerFactory {\n\t\tfactory.namespace = namespace\n\t\treturn factory\n\t}\n}","line":{"from":75,"to":81}} {"id":100031137,"name":"NewSharedInformerFactory","signature":"func NewSharedInformerFactory(client clientset.Interface, defaultResync time.Duration) SharedInformerFactory","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/factory.go","code":"// NewSharedInformerFactory constructs a new instance of sharedInformerFactory for all namespaces.\nfunc NewSharedInformerFactory(client clientset.Interface, defaultResync time.Duration) SharedInformerFactory {\n\treturn NewSharedInformerFactoryWithOptions(client, defaultResync)\n}","line":{"from":83,"to":86}} {"id":100031138,"name":"NewFilteredSharedInformerFactory","signature":"func NewFilteredSharedInformerFactory(client clientset.Interface, defaultResync time.Duration, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerFactory","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/factory.go","code":"// NewFilteredSharedInformerFactory constructs a new instance of sharedInformerFactory.\n// Listers obtained via this SharedInformerFactory will be subject to the same filters\n// as specified here.\n// Deprecated: Please use NewSharedInformerFactoryWithOptions instead\nfunc NewFilteredSharedInformerFactory(client clientset.Interface, defaultResync time.Duration, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerFactory {\n\treturn NewSharedInformerFactoryWithOptions(client, defaultResync, WithNamespace(namespace), WithTweakListOptions(tweakListOptions))\n}","line":{"from":88,"to":94}} {"id":100031139,"name":"NewSharedInformerFactoryWithOptions","signature":"func NewSharedInformerFactoryWithOptions(client clientset.Interface, defaultResync time.Duration, options ...SharedInformerOption) SharedInformerFactory","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/factory.go","code":"// NewSharedInformerFactoryWithOptions constructs a new instance of a SharedInformerFactory with additional options.\nfunc NewSharedInformerFactoryWithOptions(client clientset.Interface, defaultResync time.Duration, options ...SharedInformerOption) SharedInformerFactory {\n\tfactory := \u0026sharedInformerFactory{\n\t\tclient: client,\n\t\tnamespace: v1.NamespaceAll,\n\t\tdefaultResync: defaultResync,\n\t\tinformers: make(map[reflect.Type]cache.SharedIndexInformer),\n\t\tstartedInformers: make(map[reflect.Type]bool),\n\t\tcustomResync: make(map[reflect.Type]time.Duration),\n\t}\n\n\t// Apply all options\n\tfor _, opt := range options {\n\t\tfactory = opt(factory)\n\t}\n\n\treturn factory\n}","line":{"from":96,"to":113}} {"id":100031140,"name":"Start","signature":"func (f *sharedInformerFactory) Start(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/factory.go","code":"func (f *sharedInformerFactory) Start(stopCh \u003c-chan struct{}) {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\n\tif f.shuttingDown {\n\t\treturn\n\t}\n\n\tfor informerType, informer := range f.informers {\n\t\tif !f.startedInformers[informerType] {\n\t\t\tf.wg.Add(1)\n\t\t\t// We need a new variable in each loop iteration,\n\t\t\t// otherwise the goroutine would use the loop variable\n\t\t\t// and that keeps changing.\n\t\t\tinformer := informer\n\t\t\tgo func() {\n\t\t\t\tdefer f.wg.Done()\n\t\t\t\tinformer.Run(stopCh)\n\t\t\t}()\n\t\t\tf.startedInformers[informerType] = true\n\t\t}\n\t}\n}","line":{"from":115,"to":137}} {"id":100031141,"name":"Shutdown","signature":"func (f *sharedInformerFactory) Shutdown()","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/factory.go","code":"func (f *sharedInformerFactory) Shutdown() {\n\tf.lock.Lock()\n\tf.shuttingDown = true\n\tf.lock.Unlock()\n\n\t// Will return immediately if there is nothing to wait for.\n\tf.wg.Wait()\n}","line":{"from":139,"to":146}} {"id":100031142,"name":"WaitForCacheSync","signature":"func (f *sharedInformerFactory) WaitForCacheSync(stopCh \u003c-chan struct{}) map[reflect.Type]bool","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/factory.go","code":"func (f *sharedInformerFactory) WaitForCacheSync(stopCh \u003c-chan struct{}) map[reflect.Type]bool {\n\tinformers := func() map[reflect.Type]cache.SharedIndexInformer {\n\t\tf.lock.Lock()\n\t\tdefer f.lock.Unlock()\n\n\t\tinformers := map[reflect.Type]cache.SharedIndexInformer{}\n\t\tfor informerType, informer := range f.informers {\n\t\t\tif f.startedInformers[informerType] {\n\t\t\t\tinformers[informerType] = informer\n\t\t\t}\n\t\t}\n\t\treturn informers\n\t}()\n\n\tres := map[reflect.Type]bool{}\n\tfor informType, informer := range informers {\n\t\tres[informType] = cache.WaitForCacheSync(stopCh, informer.HasSynced)\n\t}\n\treturn res\n}","line":{"from":148,"to":167}} {"id":100031143,"name":"InformerFor","signature":"func (f *sharedInformerFactory) InformerFor(obj runtime.Object, newFunc internalinterfaces.NewInformerFunc) cache.SharedIndexInformer","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/factory.go","code":"// InternalInformerFor returns the SharedIndexInformer for obj using an internal\n// client.\nfunc (f *sharedInformerFactory) InformerFor(obj runtime.Object, newFunc internalinterfaces.NewInformerFunc) cache.SharedIndexInformer {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\n\tinformerType := reflect.TypeOf(obj)\n\tinformer, exists := f.informers[informerType]\n\tif exists {\n\t\treturn informer\n\t}\n\n\tresyncPeriod, exists := f.customResync[informerType]\n\tif !exists {\n\t\tresyncPeriod = f.defaultResync\n\t}\n\n\tinformer = newFunc(f.client, resyncPeriod)\n\tf.informers[informerType] = informer\n\n\treturn informer\n}","line":{"from":169,"to":190}} {"id":100031144,"name":"Apiregistration","signature":"func (f *sharedInformerFactory) Apiregistration() apiregistration.Interface","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/factory.go","code":"func (f *sharedInformerFactory) Apiregistration() apiregistration.Interface {\n\treturn apiregistration.New(f, f.namespace, f.tweakListOptions)\n}","line":{"from":249,"to":251}} {"id":100031145,"name":"Informer","signature":"func (f *genericInformer) Informer() cache.SharedIndexInformer","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/generic.go","code":"// Informer returns the SharedIndexInformer.\nfunc (f *genericInformer) Informer() cache.SharedIndexInformer {\n\treturn f.informer\n}","line":{"from":42,"to":45}} {"id":100031146,"name":"Lister","signature":"func (f *genericInformer) Lister() cache.GenericLister","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/generic.go","code":"// Lister returns the GenericLister.\nfunc (f *genericInformer) Lister() cache.GenericLister {\n\treturn cache.NewGenericLister(f.Informer().GetIndexer(), f.resource)\n}","line":{"from":47,"to":50}} {"id":100031147,"name":"ForResource","signature":"func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error)","file":"staging/src/k8s.io/kube-aggregator/pkg/client/informers/externalversions/generic.go","code":"// ForResource gives generic access to a shared informer of the matching type\n// TODO extend this to unknown resources with a client pool\nfunc (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) {\n\tswitch resource {\n\t// Group=apiregistration.k8s.io, Version=v1\n\tcase v1.SchemeGroupVersion.WithResource(\"apiservices\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Apiregistration().V1().APIServices().Informer()}, nil\n\n\t\t// Group=apiregistration.k8s.io, Version=v1beta1\n\tcase v1beta1.SchemeGroupVersion.WithResource(\"apiservices\"):\n\t\treturn \u0026genericInformer{resource: resource.GroupResource(), informer: f.Apiregistration().V1beta1().APIServices().Informer()}, nil\n\n\t}\n\n\treturn nil, fmt.Errorf(\"no informer found for %v\", resource)\n}","line":{"from":52,"to":67}} {"id":100031148,"name":"NewAPIServiceLister","signature":"func NewAPIServiceLister(indexer cache.Indexer) APIServiceLister","file":"staging/src/k8s.io/kube-aggregator/pkg/client/listers/apiregistration/v1/apiservice.go","code":"// NewAPIServiceLister returns a new APIServiceLister.\nfunc NewAPIServiceLister(indexer cache.Indexer) APIServiceLister {\n\treturn \u0026aPIServiceLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100031149,"name":"List","signature":"func (s *aPIServiceLister) List(selector labels.Selector) (ret []*v1.APIService, err error)","file":"staging/src/k8s.io/kube-aggregator/pkg/client/listers/apiregistration/v1/apiservice.go","code":"// List lists all APIServices in the indexer.\nfunc (s *aPIServiceLister) List(selector labels.Selector) (ret []*v1.APIService, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.APIService))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100031150,"name":"Get","signature":"func (s *aPIServiceLister) Get(name string) (*v1.APIService, error)","file":"staging/src/k8s.io/kube-aggregator/pkg/client/listers/apiregistration/v1/apiservice.go","code":"// Get retrieves the APIService from the index for a given name.\nfunc (s *aPIServiceLister) Get(name string) (*v1.APIService, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"apiservice\"), name)\n\t}\n\treturn obj.(*v1.APIService), nil\n}","line":{"from":58,"to":68}} {"id":100031151,"name":"NewAPIServiceLister","signature":"func NewAPIServiceLister(indexer cache.Indexer) APIServiceLister","file":"staging/src/k8s.io/kube-aggregator/pkg/client/listers/apiregistration/v1beta1/apiservice.go","code":"// NewAPIServiceLister returns a new APIServiceLister.\nfunc NewAPIServiceLister(indexer cache.Indexer) APIServiceLister {\n\treturn \u0026aPIServiceLister{indexer: indexer}\n}","line":{"from":45,"to":48}} {"id":100031152,"name":"List","signature":"func (s *aPIServiceLister) List(selector labels.Selector) (ret []*v1beta1.APIService, err error)","file":"staging/src/k8s.io/kube-aggregator/pkg/client/listers/apiregistration/v1beta1/apiservice.go","code":"// List lists all APIServices in the indexer.\nfunc (s *aPIServiceLister) List(selector labels.Selector) (ret []*v1beta1.APIService, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.APIService))\n\t})\n\treturn ret, err\n}","line":{"from":50,"to":56}} {"id":100031153,"name":"Get","signature":"func (s *aPIServiceLister) Get(name string) (*v1beta1.APIService, error)","file":"staging/src/k8s.io/kube-aggregator/pkg/client/listers/apiregistration/v1beta1/apiservice.go","code":"// Get retrieves the APIService from the index for a given name.\nfunc (s *aPIServiceLister) Get(name string) (*v1beta1.APIService, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"apiservice\"), name)\n\t}\n\treturn obj.(*v1beta1.APIService), nil\n}","line":{"from":58,"to":68}} {"id":100031154,"name":"NewCommandStartAggregator","signature":"func NewCommandStartAggregator(defaults *AggregatorOptions, stopCh \u003c-chan struct{}) *cobra.Command","file":"staging/src/k8s.io/kube-aggregator/pkg/cmd/server/start.go","code":"// NewCommandStartAggregator provides a CLI handler for 'start master' command\n// with a default AggregatorOptions.\nfunc NewCommandStartAggregator(defaults *AggregatorOptions, stopCh \u003c-chan struct{}) *cobra.Command {\n\to := *defaults\n\tcmd := \u0026cobra.Command{\n\t\tShort: \"Launch a API aggregator and proxy server\",\n\t\tLong: \"Launch a API aggregator and proxy server\",\n\t\tRunE: func(c *cobra.Command, args []string) error {\n\t\t\tif err := o.Complete(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := o.Validate(args); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := o.RunAggregator(stopCh); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\n\to.AddFlags(cmd.Flags())\n\treturn cmd\n}","line":{"from":56,"to":79}} {"id":100031155,"name":"AddFlags","signature":"func (o *AggregatorOptions) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/kube-aggregator/pkg/cmd/server/start.go","code":"// AddFlags is necessary because hyperkube doesn't work using cobra, so we have to have different registration and execution paths\nfunc (o *AggregatorOptions) AddFlags(fs *pflag.FlagSet) {\n\to.ServerRunOptions.AddUniversalFlags(fs)\n\to.RecommendedOptions.AddFlags(fs)\n\to.APIEnablement.AddFlags(fs)\n\tfs.StringVar(\u0026o.ProxyClientCertFile, \"proxy-client-cert-file\", o.ProxyClientCertFile, \"client certificate used identify the proxy to the API server\")\n\tfs.StringVar(\u0026o.ProxyClientKeyFile, \"proxy-client-key-file\", o.ProxyClientKeyFile, \"client certificate key used identify the proxy to the API server\")\n}","line":{"from":81,"to":88}} {"id":100031156,"name":"NewDefaultOptions","signature":"func NewDefaultOptions(out, err io.Writer) *AggregatorOptions","file":"staging/src/k8s.io/kube-aggregator/pkg/cmd/server/start.go","code":"// NewDefaultOptions builds a \"normal\" set of options. You wouldn't normally expose this, but hyperkube isn't cobra compatible\nfunc NewDefaultOptions(out, err io.Writer) *AggregatorOptions {\n\to := \u0026AggregatorOptions{\n\t\tServerRunOptions: genericoptions.NewServerRunOptions(),\n\t\tRecommendedOptions: genericoptions.NewRecommendedOptions(\n\t\t\tdefaultEtcdPathPrefix,\n\t\t\taggregatorscheme.Codecs.LegacyCodec(v1beta1.SchemeGroupVersion),\n\t\t),\n\t\tAPIEnablement: genericoptions.NewAPIEnablementOptions(),\n\n\t\tStdOut: out,\n\t\tStdErr: err,\n\t}\n\n\treturn o\n}","line":{"from":90,"to":105}} {"id":100031157,"name":"Validate","signature":"func (o AggregatorOptions) Validate(args []string) error","file":"staging/src/k8s.io/kube-aggregator/pkg/cmd/server/start.go","code":"// Validate validates all the required options.\nfunc (o AggregatorOptions) Validate(args []string) error {\n\terrors := []error{}\n\terrors = append(errors, o.ServerRunOptions.Validate()...)\n\terrors = append(errors, o.RecommendedOptions.Validate()...)\n\terrors = append(errors, o.APIEnablement.Validate(aggregatorscheme.Scheme)...)\n\treturn utilerrors.NewAggregate(errors)\n}","line":{"from":107,"to":114}} {"id":100031158,"name":"Complete","signature":"func (o *AggregatorOptions) Complete() error","file":"staging/src/k8s.io/kube-aggregator/pkg/cmd/server/start.go","code":"// Complete fills in missing Options.\nfunc (o *AggregatorOptions) Complete() error {\n\treturn nil\n}","line":{"from":116,"to":119}} {"id":100031159,"name":"RunAggregator","signature":"func (o AggregatorOptions) RunAggregator(stopCh \u003c-chan struct{}) error","file":"staging/src/k8s.io/kube-aggregator/pkg/cmd/server/start.go","code":"// RunAggregator runs the API Aggregator.\nfunc (o AggregatorOptions) RunAggregator(stopCh \u003c-chan struct{}) error {\n\t// TODO have a \"real\" external address\n\tif err := o.RecommendedOptions.SecureServing.MaybeDefaultWithSelfSignedCerts(\"localhost\", nil, nil); err != nil {\n\t\treturn fmt.Errorf(\"error creating self-signed certificates: %v\", err)\n\t}\n\n\tserverConfig := genericapiserver.NewRecommendedConfig(aggregatorscheme.Codecs)\n\n\tif err := o.ServerRunOptions.ApplyTo(\u0026serverConfig.Config); err != nil {\n\t\treturn err\n\t}\n\tif err := o.RecommendedOptions.ApplyTo(serverConfig); err != nil {\n\t\treturn err\n\t}\n\tif err := o.APIEnablement.ApplyTo(\u0026serverConfig.Config, apiserver.DefaultAPIResourceConfigSource(), aggregatorscheme.Scheme); err != nil {\n\t\treturn err\n\t}\n\tserverConfig.LongRunningFunc = filters.BasicLongRunningRequestCheck(\n\t\tsets.NewString(\"watch\", \"proxy\"),\n\t\tsets.NewString(\"attach\", \"exec\", \"proxy\", \"log\", \"portforward\"),\n\t)\n\tserverConfig.OpenAPIConfig = genericapiserver.DefaultOpenAPIConfig(openapi.GetOpenAPIDefinitions, openapinamer.NewDefinitionNamer(aggregatorscheme.Scheme))\n\tserverConfig.OpenAPIConfig.Info.Title = \"kube-aggregator\"\n\t// prevent generic API server from installing the OpenAPI handler. Aggregator server\n\t// has its own customized OpenAPI handler.\n\tserverConfig.SkipOpenAPIInstallation = true\n\n\tserviceResolver := apiserver.NewClusterIPServiceResolver(serverConfig.SharedInformerFactory.Core().V1().Services().Lister())\n\n\tconfig := apiserver.Config{\n\t\tGenericConfig: serverConfig,\n\t\tExtraConfig: apiserver.ExtraConfig{\n\t\t\tServiceResolver: serviceResolver,\n\t\t},\n\t}\n\n\tif len(o.ProxyClientCertFile) == 0 || len(o.ProxyClientKeyFile) == 0 {\n\t\treturn errors.New(\"missing a client certificate along with a key to identify the proxy to the API server\")\n\t}\n\n\tconfig.ExtraConfig.ProxyClientCertFile = o.ProxyClientCertFile\n\tconfig.ExtraConfig.ProxyClientKeyFile = o.ProxyClientKeyFile\n\n\tserver, err := config.Complete().NewWithDelegate(genericapiserver.NewEmptyDelegate())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprepared, err := server.PrepareRun()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn prepared.Run(stopCh)\n}","line":{"from":121,"to":175}} {"id":100031160,"name":"NewAutoRegisterController","signature":"func NewAutoRegisterController(apiServiceInformer informers.APIServiceInformer, apiServiceClient apiregistrationclient.APIServicesGetter) *autoRegisterController","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/autoregister/autoregister_controller.go","code":"// NewAutoRegisterController creates a new autoRegisterController.\nfunc NewAutoRegisterController(apiServiceInformer informers.APIServiceInformer, apiServiceClient apiregistrationclient.APIServicesGetter) *autoRegisterController {\n\tc := \u0026autoRegisterController{\n\t\tapiServiceLister: apiServiceInformer.Lister(),\n\t\tapiServiceSynced: apiServiceInformer.Informer().HasSynced,\n\t\tapiServiceClient: apiServiceClient,\n\t\tapiServicesToSync: map[string]*v1.APIService{},\n\n\t\tapiServicesAtStart: map[string]bool{},\n\n\t\tsyncedSuccessfullyLock: \u0026sync.RWMutex{},\n\t\tsyncedSuccessfully: map[string]bool{},\n\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"autoregister\"),\n\t}\n\tc.syncHandler = c.checkAPIService\n\n\tapiServiceInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tcast := obj.(*v1.APIService)\n\t\t\tc.queue.Add(cast.Name)\n\t\t},\n\t\tUpdateFunc: func(_, obj interface{}) {\n\t\t\tcast := obj.(*v1.APIService)\n\t\t\tc.queue.Add(cast.Name)\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tcast, ok := obj.(*v1.APIService)\n\t\t\tif !ok {\n\t\t\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\t\t\tif !ok {\n\t\t\t\t\tklog.V(2).Infof(\"Couldn't get object from tombstone %#v\", obj)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcast, ok = tombstone.Obj.(*v1.APIService)\n\t\t\t\tif !ok {\n\t\t\t\t\tklog.V(2).Infof(\"Tombstone contained unexpected object: %#v\", obj)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tc.queue.Add(cast.Name)\n\t\t},\n\t})\n\n\treturn c\n}","line":{"from":87,"to":132}} {"id":100031161,"name":"Run","signature":"func (c *autoRegisterController) Run(workers int, stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/autoregister/autoregister_controller.go","code":"// Run starts the autoregister controller in a loop which syncs API services until stopCh is closed.\nfunc (c *autoRegisterController) Run(workers int, stopCh \u003c-chan struct{}) {\n\t// don't let panics crash the process\n\tdefer utilruntime.HandleCrash()\n\t// make sure the work queue is shutdown which will trigger workers to end\n\tdefer c.queue.ShutDown()\n\n\tklog.Info(\"Starting autoregister controller\")\n\tdefer klog.Info(\"Shutting down autoregister controller\")\n\n\t// wait for your secondary caches to fill before starting your work\n\tif !controllers.WaitForCacheSync(\"autoregister\", stopCh, c.apiServiceSynced) {\n\t\treturn\n\t}\n\n\t// record APIService objects that existed when we started\n\tif services, err := c.apiServiceLister.List(labels.Everything()); err == nil {\n\t\tfor _, service := range services {\n\t\t\tc.apiServicesAtStart[service.Name] = true\n\t\t}\n\t}\n\n\t// start up your worker threads based on workers. Some controllers have multiple kinds of workers\n\tfor i := 0; i \u003c workers; i++ {\n\t\t// runWorker will loop until \"something bad\" happens. The .Until will then rekick the worker\n\t\t// after one second\n\t\tgo wait.Until(c.runWorker, time.Second, stopCh)\n\t}\n\n\t// wait until we're told to stop\n\t\u003c-stopCh\n}","line":{"from":134,"to":165}} {"id":100031162,"name":"runWorker","signature":"func (c *autoRegisterController) runWorker()","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/autoregister/autoregister_controller.go","code":"func (c *autoRegisterController) runWorker() {\n\t// hot loop until we're told to stop. processNextWorkItem will automatically wait until there's work\n\t// available, so we don't worry about secondary waits\n\tfor c.processNextWorkItem() {\n\t}\n}","line":{"from":167,"to":172}} {"id":100031163,"name":"processNextWorkItem","signature":"func (c *autoRegisterController) processNextWorkItem() bool","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/autoregister/autoregister_controller.go","code":"// processNextWorkItem deals with one key off the queue. It returns false when it's time to quit.\nfunc (c *autoRegisterController) processNextWorkItem() bool {\n\t// pull the next work item from queue. It should be a key we use to lookup something in a cache\n\tkey, quit := c.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\t// you always have to indicate to the queue that you've completed a piece of work\n\tdefer c.queue.Done(key)\n\n\t// do your work on the key. This method will contains your \"do stuff\" logic\n\terr := c.syncHandler(key.(string))\n\tif err == nil {\n\t\t// if you had no error, tell the queue to stop tracking history for your key. This will\n\t\t// reset things like failure counts for per-item rate limiting\n\t\tc.queue.Forget(key)\n\t\treturn true\n\t}\n\n\t// there was a failure so be sure to report it. This method allows for pluggable error handling\n\t// which can be used for things like cluster-monitoring\n\tutilruntime.HandleError(fmt.Errorf(\"%v failed with : %v\", key, err))\n\t// since we failed, we should requeue the item to work on later. This method will add a backoff\n\t// to avoid hotlooping on particular items (they're probably still not going to work right away)\n\t// and overall controller protection (everything I've done is broken, this controller needs to\n\t// calm down or it can starve other useful work) cases.\n\tc.queue.AddRateLimited(key)\n\n\treturn true\n}","line":{"from":174,"to":203}} {"id":100031164,"name":"checkAPIService","signature":"func (c *autoRegisterController) checkAPIService(name string) (err error)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/autoregister/autoregister_controller.go","code":"// checkAPIService syncs the current APIService against a list of desired APIService objects\n//\n//\t | A. desired: not found | B. desired: sync on start | C. desired: sync always\n//\t------------------------------------------------|-----------------------|---------------------------|------------------------\n//\t1. current: lookup error | error | error | error\n//\t2. current: not found | - | create once | create\n//\t3. current: no sync | - | - | -\n//\t4. current: sync on start, not present at start | - | - | -\n//\t5. current: sync on start, present at start | delete once | update once | update once\n//\t6. current: sync always | delete | update once | update\nfunc (c *autoRegisterController) checkAPIService(name string) (err error) {\n\tdesired := c.GetAPIServiceToSync(name)\n\tcurr, err := c.apiServiceLister.Get(name)\n\n\t// if we've never synced this service successfully, record a successful sync.\n\thasSynced := c.hasSyncedSuccessfully(name)\n\tif !hasSynced {\n\t\tdefer func() {\n\t\t\tif err == nil {\n\t\t\t\tc.setSyncedSuccessfully(name)\n\t\t\t}\n\t\t}()\n\t}\n\n\tswitch {\n\t// we had a real error, just return it (1A,1B,1C)\n\tcase err != nil \u0026\u0026 !apierrors.IsNotFound(err):\n\t\treturn err\n\n\t// we don't have an entry and we don't want one (2A)\n\tcase apierrors.IsNotFound(err) \u0026\u0026 desired == nil:\n\t\treturn nil\n\n\t// the local object only wants to sync on start and has already synced (2B,5B,6B \"once\" enforcement)\n\tcase isAutomanagedOnStart(desired) \u0026\u0026 hasSynced:\n\t\treturn nil\n\n\t// we don't have an entry and we do want one (2B,2C)\n\tcase apierrors.IsNotFound(err) \u0026\u0026 desired != nil:\n\t\t_, err := c.apiServiceClient.APIServices().Create(context.TODO(), desired, metav1.CreateOptions{})\n\t\tif apierrors.IsAlreadyExists(err) {\n\t\t\t// created in the meantime, we'll get called again\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\n\t// we aren't trying to manage this APIService (3A,3B,3C)\n\tcase !isAutomanaged(curr):\n\t\treturn nil\n\n\t// the remote object only wants to sync on start, but was added after we started (4A,4B,4C)\n\tcase isAutomanagedOnStart(curr) \u0026\u0026 !c.apiServicesAtStart[name]:\n\t\treturn nil\n\n\t// the remote object only wants to sync on start and has already synced (5A,5B,5C \"once\" enforcement)\n\tcase isAutomanagedOnStart(curr) \u0026\u0026 hasSynced:\n\t\treturn nil\n\n\t// we have a spurious APIService that we're managing, delete it (5A,6A)\n\tcase desired == nil:\n\t\topts := metav1.DeleteOptions{Preconditions: metav1.NewUIDPreconditions(string(curr.UID))}\n\t\terr := c.apiServiceClient.APIServices().Delete(context.TODO(), curr.Name, opts)\n\t\tif apierrors.IsNotFound(err) || apierrors.IsConflict(err) {\n\t\t\t// deleted or changed in the meantime, we'll get called again\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\n\t// if the specs already match, nothing for us to do\n\tcase reflect.DeepEqual(curr.Spec, desired.Spec):\n\t\treturn nil\n\t}\n\n\t// we have an entry and we have a desired, now we deconflict. Only a few fields matter. (5B,5C,6B,6C)\n\tapiService := curr.DeepCopy()\n\tapiService.Spec = desired.Spec\n\t_, err = c.apiServiceClient.APIServices().Update(context.TODO(), apiService, metav1.UpdateOptions{})\n\tif apierrors.IsNotFound(err) || apierrors.IsConflict(err) {\n\t\t// deleted or changed in the meantime, we'll get called again\n\t\treturn nil\n\t}\n\treturn err\n}","line":{"from":205,"to":287}} {"id":100031165,"name":"GetAPIServiceToSync","signature":"func (c *autoRegisterController) GetAPIServiceToSync(name string) *v1.APIService","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/autoregister/autoregister_controller.go","code":"// GetAPIServiceToSync gets a single API service to sync.\nfunc (c *autoRegisterController) GetAPIServiceToSync(name string) *v1.APIService {\n\tc.apiServicesToSyncLock.RLock()\n\tdefer c.apiServicesToSyncLock.RUnlock()\n\n\treturn c.apiServicesToSync[name]\n}","line":{"from":289,"to":295}} {"id":100031166,"name":"AddAPIServiceToSyncOnStart","signature":"func (c *autoRegisterController) AddAPIServiceToSyncOnStart(in *v1.APIService)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/autoregister/autoregister_controller.go","code":"// AddAPIServiceToSyncOnStart registers an API service to sync only when the controller starts.\nfunc (c *autoRegisterController) AddAPIServiceToSyncOnStart(in *v1.APIService) {\n\tc.addAPIServiceToSync(in, manageOnStart)\n}","line":{"from":297,"to":300}} {"id":100031167,"name":"AddAPIServiceToSync","signature":"func (c *autoRegisterController) AddAPIServiceToSync(in *v1.APIService)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/autoregister/autoregister_controller.go","code":"// AddAPIServiceToSync registers an API service to sync continuously.\nfunc (c *autoRegisterController) AddAPIServiceToSync(in *v1.APIService) {\n\tc.addAPIServiceToSync(in, manageContinuously)\n}","line":{"from":302,"to":305}} {"id":100031168,"name":"addAPIServiceToSync","signature":"func (c *autoRegisterController) addAPIServiceToSync(in *v1.APIService, syncType string)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/autoregister/autoregister_controller.go","code":"func (c *autoRegisterController) addAPIServiceToSync(in *v1.APIService, syncType string) {\n\tc.apiServicesToSyncLock.Lock()\n\tdefer c.apiServicesToSyncLock.Unlock()\n\n\tapiService := in.DeepCopy()\n\tif apiService.Labels == nil {\n\t\tapiService.Labels = map[string]string{}\n\t}\n\tapiService.Labels[AutoRegisterManagedLabel] = syncType\n\n\tc.apiServicesToSync[apiService.Name] = apiService\n\tc.queue.Add(apiService.Name)\n}","line":{"from":307,"to":319}} {"id":100031169,"name":"RemoveAPIServiceToSync","signature":"func (c *autoRegisterController) RemoveAPIServiceToSync(name string)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/autoregister/autoregister_controller.go","code":"// RemoveAPIServiceToSync deletes a registered APIService.\nfunc (c *autoRegisterController) RemoveAPIServiceToSync(name string) {\n\tc.apiServicesToSyncLock.Lock()\n\tdefer c.apiServicesToSyncLock.Unlock()\n\n\tdelete(c.apiServicesToSync, name)\n\tc.queue.Add(name)\n}","line":{"from":321,"to":328}} {"id":100031170,"name":"hasSyncedSuccessfully","signature":"func (c *autoRegisterController) hasSyncedSuccessfully(name string) bool","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/autoregister/autoregister_controller.go","code":"func (c *autoRegisterController) hasSyncedSuccessfully(name string) bool {\n\tc.syncedSuccessfullyLock.RLock()\n\tdefer c.syncedSuccessfullyLock.RUnlock()\n\treturn c.syncedSuccessfully[name]\n}","line":{"from":330,"to":334}} {"id":100031171,"name":"setSyncedSuccessfully","signature":"func (c *autoRegisterController) setSyncedSuccessfully(name string)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/autoregister/autoregister_controller.go","code":"func (c *autoRegisterController) setSyncedSuccessfully(name string) {\n\tc.syncedSuccessfullyLock.Lock()\n\tdefer c.syncedSuccessfullyLock.Unlock()\n\tc.syncedSuccessfully[name] = true\n}","line":{"from":336,"to":340}} {"id":100031172,"name":"automanagedType","signature":"func automanagedType(service *v1.APIService) string","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/autoregister/autoregister_controller.go","code":"func automanagedType(service *v1.APIService) string {\n\tif service == nil {\n\t\treturn \"\"\n\t}\n\treturn service.Labels[AutoRegisterManagedLabel]\n}","line":{"from":342,"to":347}} {"id":100031173,"name":"isAutomanagedOnStart","signature":"func isAutomanagedOnStart(service *v1.APIService) bool","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/autoregister/autoregister_controller.go","code":"func isAutomanagedOnStart(service *v1.APIService) bool {\n\treturn automanagedType(service) == manageOnStart\n}","line":{"from":349,"to":351}} {"id":100031174,"name":"isAutomanaged","signature":"func isAutomanaged(service *v1.APIService) bool","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/autoregister/autoregister_controller.go","code":"func isAutomanaged(service *v1.APIService) bool {\n\tmanagedType := automanagedType(service)\n\treturn managedType == manageOnStart || managedType == manageContinuously\n}","line":{"from":353,"to":356}} {"id":100031175,"name":"WaitForCacheSync","signature":"func WaitForCacheSync(controllerName string, stopCh \u003c-chan struct{}, cacheSyncs ...cache.InformerSynced) bool","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/cache.go","code":"// WaitForCacheSync is a wrapper around cache.WaitForCacheSync that generates log messages\n// indicating that the controller identified by controllerName is waiting for syncs, followed by\n// either a successful or failed sync.\nfunc WaitForCacheSync(controllerName string, stopCh \u003c-chan struct{}, cacheSyncs ...cache.InformerSynced) bool {\n\tklog.Infof(\"Waiting for caches to sync for %s controller\", controllerName)\n\n\tif !cache.WaitForCacheSync(stopCh, cacheSyncs...) {\n\t\tutilruntime.HandleError(fmt.Errorf(\"Unable to sync caches for %s controller\", controllerName))\n\t\treturn false\n\t}\n\n\tklog.Infof(\"Caches are synced for %s controller\", controllerName)\n\treturn true\n}","line":{"from":28,"to":41}} {"id":100031176,"name":"IsLocalAPIService","signature":"func IsLocalAPIService(apiServiceName string) bool","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator/aggregator.go","code":"// IsLocalAPIService returns true for local specs from delegates.\nfunc IsLocalAPIService(apiServiceName string) bool {\n\treturn strings.HasPrefix(apiServiceName, localDelegateChainNamePrefix)\n}","line":{"from":60,"to":63}} {"id":100031177,"name":"GetAPIServiceNames","signature":"func (s *specAggregator) GetAPIServiceNames() []string","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator/aggregator.go","code":"// GetAPIServiceNames returns the names of APIServices recorded in specAggregator.openAPISpecs.\n// We use this function to pass the names of local APIServices to the controller in this package,\n// so that the controller can periodically sync the OpenAPI spec from delegation API servers.\nfunc (s *specAggregator) GetAPIServiceNames() []string {\n\tnames := make([]string, 0, len(s.openAPISpecs))\n\tfor key := range s.openAPISpecs {\n\t\tnames = append(names, key)\n\t}\n\treturn names\n}","line":{"from":65,"to":74}} {"id":100031178,"name":"BuildAndRegisterAggregator","signature":"func BuildAndRegisterAggregator(downloader *Downloader, delegationTarget server.DelegationTarget, webServices []*restful.WebService,","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator/aggregator.go","code":"// BuildAndRegisterAggregator registered OpenAPI aggregator handler. This function is not thread safe as it only being called on startup.\nfunc BuildAndRegisterAggregator(downloader *Downloader, delegationTarget server.DelegationTarget, webServices []*restful.WebService,\n\tconfig *common.Config, pathHandler common.PathHandler) (SpecAggregator, error) {\n\ts := \u0026specAggregator{\n\t\topenAPISpecs: map[string]*openAPISpecInfo{},\n\t}\n\n\ti := 0\n\t// Build Aggregator's spec\n\taggregatorOpenAPISpec, err := builder.BuildOpenAPISpecFromRoutes(restfuladapter.AdaptWebServices(webServices), config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Reserving non-name spec for aggregator's Spec.\n\ts.addLocalSpec(aggregatorOpenAPISpec, nil, fmt.Sprintf(localDelegateChainNamePattern, i), \"\")\n\ti++\n\tfor delegate := delegationTarget; delegate != nil; delegate = delegate.NextDelegate() {\n\t\thandler := delegate.UnprotectedHandler()\n\t\tif handler == nil {\n\t\t\tcontinue\n\t\t}\n\t\tdelegateSpec, etag, _, err := downloader.Download(handler, \"\")\n\t\tif err != nil {\n\t\t\t// ignore errors for the empty delegate we attach at the end the chain\n\t\t\t// atm the empty delegate returns 503 when the server hasn't been fully initialized\n\t\t\t// and the spec downloader only silences 404s\n\t\t\tif len(delegate.ListedPaths()) == 0 \u0026\u0026 delegate.NextDelegate() == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\tif delegateSpec == nil {\n\t\t\tcontinue\n\t\t}\n\t\ts.addLocalSpec(delegateSpec, handler, fmt.Sprintf(localDelegateChainNamePattern, i), etag)\n\t\ti++\n\t}\n\n\t// Build initial spec to serve.\n\tklog.V(2).Infof(\"Building initial OpenAPI spec\")\n\tdefer func(start time.Time) {\n\t\tduration := time.Since(start)\n\t\tklog.V(2).Infof(\"Finished initial OpenAPI spec generation after %v\", duration)\n\n\t\tregenerationCounter.With(map[string]string{\"apiservice\": \"*\", \"reason\": \"startup\"})\n\t\tregenerationDurationGauge.With(map[string]string{\"reason\": \"startup\"}).Set(duration.Seconds())\n\t}(time.Now())\n\tspecToServe, err := s.buildOpenAPISpec()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Install handler\n\ts.openAPIVersionedService = handler.NewOpenAPIService(specToServe)\n\terr = s.openAPIVersionedService.RegisterOpenAPIVersionedService(\"/openapi/v2\", pathHandler)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s, nil\n}","line":{"from":76,"to":137}} {"id":100031179,"name":"addLocalSpec","signature":"func (s *specAggregator) addLocalSpec(spec *spec.Swagger, localHandler http.Handler, name, etag string)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator/aggregator.go","code":"// This function is not thread safe as it only being called on startup.\nfunc (s *specAggregator) addLocalSpec(spec *spec.Swagger, localHandler http.Handler, name, etag string) {\n\tlocalAPIService := v1.APIService{}\n\tlocalAPIService.Name = name\n\ts.openAPISpecs[name] = \u0026openAPISpecInfo{\n\t\tetag: etag,\n\t\tapiService: localAPIService,\n\t\thandler: localHandler,\n\t\tspec: spec,\n\t}\n}","line":{"from":152,"to":162}} {"id":100031180,"name":"buildOpenAPISpec","signature":"func (s *specAggregator) buildOpenAPISpec() (specToReturn *spec.Swagger, err error)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator/aggregator.go","code":"// buildOpenAPISpec aggregates all OpenAPI specs. It is not thread-safe. The caller is responsible to hold proper locks.\nfunc (s *specAggregator) buildOpenAPISpec() (specToReturn *spec.Swagger, err error) {\n\tspecs := []openAPISpecInfo{}\n\tfor _, specInfo := range s.openAPISpecs {\n\t\tif specInfo.spec == nil {\n\t\t\tcontinue\n\t\t}\n\t\t// Copy the spec before removing the defaults.\n\t\tlocalSpec := *specInfo.spec\n\t\tlocalSpecInfo := *specInfo\n\t\tlocalSpecInfo.spec = \u0026localSpec\n\t\tlocalSpecInfo.spec.Definitions = handler.PruneDefaults(specInfo.spec.Definitions)\n\t\tspecs = append(specs, localSpecInfo)\n\t}\n\tif len(specs) == 0 {\n\t\treturn \u0026spec.Swagger{}, nil\n\t}\n\tsortByPriority(specs)\n\tfor _, specInfo := range specs {\n\t\tif specToReturn == nil {\n\t\t\tspecToReturn = \u0026spec.Swagger{}\n\t\t\t*specToReturn = *specInfo.spec\n\t\t\t// Paths and Definitions are set by MergeSpecsIgnorePathConflict\n\t\t\tspecToReturn.Paths = nil\n\t\t\tspecToReturn.Definitions = nil\n\t\t}\n\t\tif err := aggregator.MergeSpecsIgnorePathConflict(specToReturn, specInfo.spec); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn specToReturn, nil\n}","line":{"from":175,"to":207}} {"id":100031181,"name":"updateOpenAPISpec","signature":"func (s *specAggregator) updateOpenAPISpec() error","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator/aggregator.go","code":"// updateOpenAPISpec aggregates all OpenAPI specs. It is not thread-safe. The caller is responsible to hold proper locks.\nfunc (s *specAggregator) updateOpenAPISpec() error {\n\tif s.openAPIVersionedService == nil {\n\t\treturn nil\n\t}\n\tspecToServe, err := s.buildOpenAPISpec()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn s.openAPIVersionedService.UpdateSpec(specToServe)\n}","line":{"from":209,"to":219}} {"id":100031182,"name":"tryUpdatingServiceSpecs","signature":"func (s *specAggregator) tryUpdatingServiceSpecs(specInfo *openAPISpecInfo) error","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator/aggregator.go","code":"// tryUpdatingServiceSpecs tries updating openAPISpecs map with specified specInfo, and keeps the map intact\n// if the update fails.\nfunc (s *specAggregator) tryUpdatingServiceSpecs(specInfo *openAPISpecInfo) error {\n\tif specInfo == nil {\n\t\treturn fmt.Errorf(\"invalid input: specInfo must be non-nil\")\n\t}\n\t_, updated := s.openAPISpecs[specInfo.apiService.Name]\n\torigSpecInfo, existedBefore := s.openAPISpecs[specInfo.apiService.Name]\n\ts.openAPISpecs[specInfo.apiService.Name] = specInfo\n\n\t// Skip aggregation if OpenAPI spec didn't change\n\tif existedBefore \u0026\u0026 origSpecInfo != nil \u0026\u0026 origSpecInfo.etag == specInfo.etag {\n\t\treturn nil\n\t}\n\tklog.V(2).Infof(\"Updating OpenAPI spec because %s is updated\", specInfo.apiService.Name)\n\tdefer func(start time.Time) {\n\t\tduration := time.Since(start)\n\t\tklog.V(2).Infof(\"Finished OpenAPI spec generation after %v\", duration)\n\n\t\treason := \"add\"\n\t\tif updated {\n\t\t\treason = \"update\"\n\t\t}\n\n\t\tregenerationCounter.With(map[string]string{\"apiservice\": specInfo.apiService.Name, \"reason\": reason})\n\t\tregenerationDurationGauge.With(map[string]string{\"reason\": reason}).Set(duration.Seconds())\n\t}(time.Now())\n\tif err := s.updateOpenAPISpec(); err != nil {\n\t\tif existedBefore {\n\t\t\ts.openAPISpecs[specInfo.apiService.Name] = origSpecInfo\n\t\t} else {\n\t\t\tdelete(s.openAPISpecs, specInfo.apiService.Name)\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":221,"to":257}} {"id":100031183,"name":"tryDeleteServiceSpecs","signature":"func (s *specAggregator) tryDeleteServiceSpecs(apiServiceName string) error","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator/aggregator.go","code":"// tryDeleteServiceSpecs tries delete specified specInfo from openAPISpecs map, and keeps the map intact\n// if the update fails.\nfunc (s *specAggregator) tryDeleteServiceSpecs(apiServiceName string) error {\n\torgSpecInfo, exists := s.openAPISpecs[apiServiceName]\n\tif !exists {\n\t\treturn nil\n\t}\n\tdelete(s.openAPISpecs, apiServiceName)\n\tklog.V(2).Infof(\"Updating OpenAPI spec because %s is removed\", apiServiceName)\n\tdefer func(start time.Time) {\n\t\tduration := time.Since(start)\n\t\tklog.V(2).Infof(\"Finished OpenAPI spec generation after %v\", duration)\n\n\t\tregenerationCounter.With(map[string]string{\"apiservice\": apiServiceName, \"reason\": \"delete\"})\n\t\tregenerationDurationGauge.With(map[string]string{\"reason\": \"delete\"}).Set(duration.Seconds())\n\t}(time.Now())\n\tif err := s.updateOpenAPISpec(); err != nil {\n\t\ts.openAPISpecs[apiServiceName] = orgSpecInfo\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":259,"to":280}} {"id":100031184,"name":"UpdateAPIServiceSpec","signature":"func (s *specAggregator) UpdateAPIServiceSpec(apiServiceName string, spec *spec.Swagger, etag string) error","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator/aggregator.go","code":"// UpdateAPIServiceSpec updates the api service's OpenAPI spec. It is thread safe.\nfunc (s *specAggregator) UpdateAPIServiceSpec(apiServiceName string, spec *spec.Swagger, etag string) error {\n\ts.rwMutex.Lock()\n\tdefer s.rwMutex.Unlock()\n\n\tspecInfo, existingService := s.openAPISpecs[apiServiceName]\n\tif !existingService {\n\t\treturn fmt.Errorf(\"APIService %q does not exists\", apiServiceName)\n\t}\n\n\t// For APIServices (non-local) specs, only merge their /apis/ prefixed endpoint as it is the only paths\n\t// proxy handler delegates.\n\tif specInfo.apiService.Spec.Service != nil {\n\t\tspec = aggregator.FilterSpecByPathsWithoutSideEffects(spec, []string{\"/apis/\"})\n\t}\n\n\treturn s.tryUpdatingServiceSpecs(\u0026openAPISpecInfo{\n\t\tapiService: specInfo.apiService,\n\t\tspec: spec,\n\t\thandler: specInfo.handler,\n\t\tetag: etag,\n\t})\n}","line":{"from":282,"to":304}} {"id":100031185,"name":"AddUpdateAPIService","signature":"func (s *specAggregator) AddUpdateAPIService(handler http.Handler, apiService *v1.APIService) error","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator/aggregator.go","code":"// AddUpdateAPIService adds or updates the api service. It is thread safe.\nfunc (s *specAggregator) AddUpdateAPIService(handler http.Handler, apiService *v1.APIService) error {\n\ts.rwMutex.Lock()\n\tdefer s.rwMutex.Unlock()\n\n\tif apiService.Spec.Service == nil {\n\t\t// All local specs should be already aggregated using local delegate chain\n\t\treturn nil\n\t}\n\n\tnewSpec := \u0026openAPISpecInfo{\n\t\tapiService: *apiService,\n\t\thandler: handler,\n\t}\n\tif specInfo, existingService := s.openAPISpecs[apiService.Name]; existingService {\n\t\tnewSpec.etag = specInfo.etag\n\t\tnewSpec.spec = specInfo.spec\n\t}\n\treturn s.tryUpdatingServiceSpecs(newSpec)\n}","line":{"from":306,"to":325}} {"id":100031186,"name":"RemoveAPIServiceSpec","signature":"func (s *specAggregator) RemoveAPIServiceSpec(apiServiceName string) error","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator/aggregator.go","code":"// RemoveAPIServiceSpec removes an api service from OpenAPI aggregation. If it does not exist, no error is returned.\n// It is thread safe.\nfunc (s *specAggregator) RemoveAPIServiceSpec(apiServiceName string) error {\n\ts.rwMutex.Lock()\n\tdefer s.rwMutex.Unlock()\n\n\tif _, existingService := s.openAPISpecs[apiServiceName]; !existingService {\n\t\treturn nil\n\t}\n\n\treturn s.tryDeleteServiceSpecs(apiServiceName)\n}","line":{"from":327,"to":338}} {"id":100031187,"name":"GetAPIServiceInfo","signature":"func (s *specAggregator) GetAPIServiceInfo(apiServiceName string) (handler http.Handler, etag string, exists bool)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator/aggregator.go","code":"// GetAPIServiceSpec returns api service spec info\nfunc (s *specAggregator) GetAPIServiceInfo(apiServiceName string) (handler http.Handler, etag string, exists bool) {\n\ts.rwMutex.RLock()\n\tdefer s.rwMutex.RUnlock()\n\n\tif info, existingService := s.openAPISpecs[apiServiceName]; existingService {\n\t\treturn info.handler, info.etag, true\n\t}\n\treturn nil, \"\", false\n}","line":{"from":340,"to":349}} {"id":100031188,"name":"NewDownloader","signature":"func NewDownloader() Downloader","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator/downloader.go","code":"// NewDownloader creates a new OpenAPI Downloader.\nfunc NewDownloader() Downloader {\n\treturn Downloader{}\n}","line":{"from":34,"to":37}} {"id":100031189,"name":"handlerWithUser","signature":"func (s *Downloader) handlerWithUser(handler http.Handler, info user.Info) http.Handler","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator/downloader.go","code":"func (s *Downloader) handlerWithUser(handler http.Handler, info user.Info) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\treq = req.WithContext(request.WithUser(req.Context(), info))\n\t\thandler.ServeHTTP(w, req)\n\t})\n}","line":{"from":39,"to":44}} {"id":100031190,"name":"etagFor","signature":"func etagFor(data []byte) string","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator/downloader.go","code":"func etagFor(data []byte) string {\n\treturn fmt.Sprintf(\"%s%X\\\"\", locallyGeneratedEtagPrefix, sha512.Sum512(data))\n}","line":{"from":46,"to":48}} {"id":100031191,"name":"Download","signature":"func (s *Downloader) Download(handler http.Handler, etag string) (returnSpec *spec.Swagger, newEtag string, httpStatus int, err error)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator/downloader.go","code":"// Download downloads openAPI spec from /openapi/v2 endpoint of the given handler.\n// httpStatus is only valid if err == nil\nfunc (s *Downloader) Download(handler http.Handler, etag string) (returnSpec *spec.Swagger, newEtag string, httpStatus int, err error) {\n\thandler = s.handlerWithUser(handler, \u0026user.DefaultInfo{Name: aggregatorUser})\n\thandler = http.TimeoutHandler(handler, specDownloadTimeout, \"request timed out\")\n\n\treq, err := http.NewRequest(\"GET\", \"/openapi/v2\", nil)\n\tif err != nil {\n\t\treturn nil, \"\", 0, err\n\t}\n\treq.Header.Add(\"Accept\", \"application/json\")\n\n\t// Only pass eTag if it is not generated locally\n\tif len(etag) \u003e 0 \u0026\u0026 !strings.HasPrefix(etag, locallyGeneratedEtagPrefix) {\n\t\treq.Header.Add(\"If-None-Match\", etag)\n\t}\n\n\twriter := newInMemoryResponseWriter()\n\thandler.ServeHTTP(writer, req)\n\n\tswitch writer.respCode {\n\tcase http.StatusNotModified:\n\t\tif len(etag) == 0 {\n\t\t\treturn nil, etag, http.StatusNotModified, fmt.Errorf(\"http.StatusNotModified is not allowed in absence of etag\")\n\t\t}\n\t\treturn nil, etag, http.StatusNotModified, nil\n\tcase http.StatusNotFound:\n\t\t// Gracefully skip 404, assuming the server won't provide any spec\n\t\treturn nil, \"\", http.StatusNotFound, nil\n\tcase http.StatusOK:\n\t\topenAPISpec := \u0026spec.Swagger{}\n\t\tif err := openAPISpec.UnmarshalJSON(writer.data); err != nil {\n\t\t\treturn nil, \"\", 0, err\n\t\t}\n\t\tnewEtag = writer.Header().Get(\"Etag\")\n\t\tif len(newEtag) == 0 {\n\t\t\tnewEtag = etagFor(writer.data)\n\t\t\tif len(etag) \u003e 0 \u0026\u0026 strings.HasPrefix(etag, locallyGeneratedEtagPrefix) {\n\t\t\t\t// The function call with an etag and server does not report an etag.\n\t\t\t\t// That means this server does not support etag and the etag that passed\n\t\t\t\t// to the function generated previously by us. Just compare etags and\n\t\t\t\t// return StatusNotModified if they are the same.\n\t\t\t\tif etag == newEtag {\n\t\t\t\t\treturn nil, etag, http.StatusNotModified, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn openAPISpec, newEtag, http.StatusOK, nil\n\tdefault:\n\t\treturn nil, \"\", 0, fmt.Errorf(\"failed to retrieve openAPI spec, http error: %s\", writer.String())\n\t}\n}","line":{"from":50,"to":101}} {"id":100031192,"name":"newInMemoryResponseWriter","signature":"func newInMemoryResponseWriter() *inMemoryResponseWriter","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator/downloader.go","code":"func newInMemoryResponseWriter() *inMemoryResponseWriter {\n\treturn \u0026inMemoryResponseWriter{header: http.Header{}}\n}","line":{"from":111,"to":113}} {"id":100031193,"name":"Header","signature":"func (r *inMemoryResponseWriter) Header() http.Header","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator/downloader.go","code":"func (r *inMemoryResponseWriter) Header() http.Header {\n\treturn r.header\n}","line":{"from":115,"to":117}} {"id":100031194,"name":"WriteHeader","signature":"func (r *inMemoryResponseWriter) WriteHeader(code int)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator/downloader.go","code":"func (r *inMemoryResponseWriter) WriteHeader(code int) {\n\tr.writeHeaderCalled = true\n\tr.respCode = code\n}","line":{"from":119,"to":122}} {"id":100031195,"name":"Write","signature":"func (r *inMemoryResponseWriter) Write(in []byte) (int, error)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator/downloader.go","code":"func (r *inMemoryResponseWriter) Write(in []byte) (int, error) {\n\tif !r.writeHeaderCalled {\n\t\tr.WriteHeader(http.StatusOK)\n\t}\n\tr.data = append(r.data, in...)\n\treturn len(in), nil\n}","line":{"from":124,"to":130}} {"id":100031196,"name":"String","signature":"func (r *inMemoryResponseWriter) String() string","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator/downloader.go","code":"func (r *inMemoryResponseWriter) String() string {\n\ts := fmt.Sprintf(\"ResponseCode: %d\", r.respCode)\n\tif r.data != nil {\n\t\ts += fmt.Sprintf(\", Body: %s\", string(r.data))\n\t}\n\tif r.header != nil {\n\t\ts += fmt.Sprintf(\", Header: %s\", r.header)\n\t}\n\treturn s\n}","line":{"from":132,"to":141}} {"id":100031197,"name":"init","signature":"func init()","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator/metrics.go","code":"func init() {\n\tlegacyregistry.MustRegister(regenerationCounter)\n\tlegacyregistry.MustRegister(regenerationDurationGauge)\n}","line":{"from":43,"to":46}} {"id":100031198,"name":"Len","signature":"func (a byPriority) Len() int { return len(a.specs) }","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator/priority.go","code":"func (a byPriority) Len() int { return len(a.specs) }","line":{"from":29,"to":29}} {"id":100031199,"name":"Swap","signature":"func (a byPriority) Swap(i, j int) { a.specs[i], a.specs[j] = a.specs[j], a.specs[i] }","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator/priority.go","code":"func (a byPriority) Swap(i, j int) { a.specs[i], a.specs[j] = a.specs[j], a.specs[i] }","line":{"from":30,"to":30}} {"id":100031200,"name":"Less","signature":"func (a byPriority) Less(i, j int) bool","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator/priority.go","code":"func (a byPriority) Less(i, j int) bool {\n\t// All local specs will come first\n\tif a.specs[i].apiService.Spec.Service == nil \u0026\u0026 a.specs[j].apiService.Spec.Service != nil {\n\t\treturn true\n\t}\n\tif a.specs[i].apiService.Spec.Service != nil \u0026\u0026 a.specs[j].apiService.Spec.Service == nil {\n\t\treturn false\n\t}\n\t// WARNING: This will result in not following priorities for local APIServices.\n\tif a.specs[i].apiService.Spec.Service == nil {\n\t\t// Sort local specs with their name. This is the order in the delegation chain (aggregator first).\n\t\treturn a.specs[i].apiService.Name \u003c a.specs[j].apiService.Name\n\t}\n\tvar iPriority, jPriority int32\n\tif a.specs[i].apiService.Spec.Group == a.specs[j].apiService.Spec.Group {\n\t\tiPriority = a.specs[i].apiService.Spec.VersionPriority\n\t\tjPriority = a.specs[i].apiService.Spec.VersionPriority\n\t} else {\n\t\tiPriority = a.groupPriorities[a.specs[i].apiService.Spec.Group]\n\t\tjPriority = a.groupPriorities[a.specs[j].apiService.Spec.Group]\n\t}\n\tif iPriority != jPriority {\n\t\t// Sort by priority, higher first\n\t\treturn iPriority \u003e jPriority\n\t}\n\t// Sort by service name.\n\treturn a.specs[i].apiService.Name \u003c a.specs[j].apiService.Name\n}","line":{"from":31,"to":58}} {"id":100031201,"name":"sortByPriority","signature":"func sortByPriority(specs []openAPISpecInfo)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/aggregator/priority.go","code":"func sortByPriority(specs []openAPISpecInfo) {\n\tb := byPriority{\n\t\tspecs: specs,\n\t\tgroupPriorities: map[string]int32{},\n\t}\n\tfor _, spec := range specs {\n\t\tif spec.apiService.Spec.Service == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif pr, found := b.groupPriorities[spec.apiService.Spec.Group]; !found || spec.apiService.Spec.GroupPriorityMinimum \u003e pr {\n\t\t\tb.groupPriorities[spec.apiService.Spec.Group] = spec.apiService.Spec.GroupPriorityMinimum\n\t\t}\n\t}\n\tsort.Sort(b)\n}","line":{"from":60,"to":74}} {"id":100031202,"name":"NewAggregationController","signature":"func NewAggregationController(downloader *aggregator.Downloader, openAPIAggregationManager aggregator.SpecAggregator) *AggregationController","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/controller.go","code":"// NewAggregationController creates new OpenAPI aggregation controller.\nfunc NewAggregationController(downloader *aggregator.Downloader, openAPIAggregationManager aggregator.SpecAggregator) *AggregationController {\n\tc := \u0026AggregationController{\n\t\topenAPIAggregationManager: openAPIAggregationManager,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(\n\t\t\tworkqueue.NewItemExponentialFailureRateLimiter(successfulUpdateDelay, failedUpdateMaxExpDelay),\n\t\t\t\"open_api_aggregation_controller\",\n\t\t),\n\t\tdownloader: downloader,\n\t}\n\n\tc.syncHandler = c.sync\n\n\t// update each service at least once, also those which are not coming from APIServices, namely local services\n\tfor _, name := range openAPIAggregationManager.GetAPIServiceNames() {\n\t\tc.queue.AddAfter(name, time.Second)\n\t}\n\n\treturn c\n}","line":{"from":57,"to":76}} {"id":100031203,"name":"Run","signature":"func (c *AggregationController) Run(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/controller.go","code":"// Run starts OpenAPI AggregationController\nfunc (c *AggregationController) Run(stopCh \u003c-chan struct{}) {\n\tdefer utilruntime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\n\tklog.Info(\"Starting OpenAPI AggregationController\")\n\tdefer klog.Info(\"Shutting down OpenAPI AggregationController\")\n\n\tgo wait.Until(c.runWorker, time.Second, stopCh)\n\n\t\u003c-stopCh\n}","line":{"from":78,"to":89}} {"id":100031204,"name":"runWorker","signature":"func (c *AggregationController) runWorker()","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/controller.go","code":"func (c *AggregationController) runWorker() {\n\tfor c.processNextWorkItem() {\n\t}\n}","line":{"from":91,"to":94}} {"id":100031205,"name":"processNextWorkItem","signature":"func (c *AggregationController) processNextWorkItem() bool","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/controller.go","code":"// processNextWorkItem deals with one key off the queue. It returns false when it's time to quit.\nfunc (c *AggregationController) processNextWorkItem() bool {\n\tkey, quit := c.queue.Get()\n\tdefer c.queue.Done(key)\n\tif quit {\n\t\treturn false\n\t}\n\n\tif aggregator.IsLocalAPIService(key.(string)) {\n\t\t// for local delegation targets that are aggregated once per second, log at\n\t\t// higher level to avoid flooding the log\n\t\tklog.V(6).Infof(\"OpenAPI AggregationController: Processing item %s\", key)\n\t} else {\n\t\tklog.V(4).Infof(\"OpenAPI AggregationController: Processing item %s\", key)\n\t}\n\n\taction, err := c.syncHandler(key.(string))\n\tif err == nil {\n\t\tc.queue.Forget(key)\n\t} else {\n\t\tutilruntime.HandleError(fmt.Errorf(\"loading OpenAPI spec for %q failed with: %v\", key, err))\n\t}\n\n\tswitch action {\n\tcase syncRequeue:\n\t\tif aggregator.IsLocalAPIService(key.(string)) {\n\t\t\tklog.V(7).Infof(\"OpenAPI AggregationController: action for local item %s: Requeue after %s.\", key, successfulUpdateDelayLocal)\n\t\t\tc.queue.AddAfter(key, successfulUpdateDelayLocal)\n\t\t} else {\n\t\t\tklog.V(7).Infof(\"OpenAPI AggregationController: action for item %s: Requeue.\", key)\n\t\t\tc.queue.AddAfter(key, successfulUpdateDelay)\n\t\t}\n\tcase syncRequeueRateLimited:\n\t\tklog.Infof(\"OpenAPI AggregationController: action for item %s: Rate Limited Requeue.\", key)\n\t\tc.queue.AddRateLimited(key)\n\tcase syncNothing:\n\t\tklog.Infof(\"OpenAPI AggregationController: action for item %s: Nothing (removed from the queue).\", key)\n\t}\n\n\treturn true\n}","line":{"from":96,"to":136}} {"id":100031206,"name":"sync","signature":"func (c *AggregationController) sync(key string) (syncAction, error)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/controller.go","code":"func (c *AggregationController) sync(key string) (syncAction, error) {\n\thandler, etag, exists := c.openAPIAggregationManager.GetAPIServiceInfo(key)\n\tif !exists || handler == nil {\n\t\treturn syncNothing, nil\n\t}\n\treturnSpec, newEtag, httpStatus, err := c.downloader.Download(handler, etag)\n\tswitch {\n\tcase err != nil:\n\t\treturn syncRequeueRateLimited, err\n\tcase httpStatus == http.StatusNotModified:\n\tcase httpStatus == http.StatusNotFound || returnSpec == nil:\n\t\treturn syncRequeueRateLimited, fmt.Errorf(\"OpenAPI spec does not exist\")\n\tcase httpStatus == http.StatusOK:\n\t\tif err := c.openAPIAggregationManager.UpdateAPIServiceSpec(key, returnSpec, newEtag); err != nil {\n\t\t\treturn syncRequeueRateLimited, err\n\t\t}\n\t}\n\treturn syncRequeue, nil\n}","line":{"from":138,"to":156}} {"id":100031207,"name":"AddAPIService","signature":"func (c *AggregationController) AddAPIService(handler http.Handler, apiService *v1.APIService)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/controller.go","code":"// AddAPIService adds a new API Service to OpenAPI Aggregation.\nfunc (c *AggregationController) AddAPIService(handler http.Handler, apiService *v1.APIService) {\n\tif apiService.Spec.Service == nil {\n\t\treturn\n\t}\n\tif err := c.openAPIAggregationManager.AddUpdateAPIService(handler, apiService); err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"adding %q to AggregationController failed with: %v\", apiService.Name, err))\n\t}\n\tc.queue.AddAfter(apiService.Name, time.Second)\n}","line":{"from":158,"to":167}} {"id":100031208,"name":"UpdateAPIService","signature":"func (c *AggregationController) UpdateAPIService(handler http.Handler, apiService *v1.APIService)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/controller.go","code":"// UpdateAPIService updates API Service's info and handler.\nfunc (c *AggregationController) UpdateAPIService(handler http.Handler, apiService *v1.APIService) {\n\tif apiService.Spec.Service == nil {\n\t\treturn\n\t}\n\tif err := c.openAPIAggregationManager.AddUpdateAPIService(handler, apiService); err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"updating %q to AggregationController failed with: %v\", apiService.Name, err))\n\t}\n\tkey := apiService.Name\n\tif c.queue.NumRequeues(key) \u003e 0 {\n\t\t// The item has failed before. Remove it from failure queue and\n\t\t// update it in a second\n\t\tc.queue.Forget(key)\n\t\tc.queue.AddAfter(key, time.Second)\n\t}\n\t// Else: The item has been succeeded before and it will be updated soon (after successfulUpdateDelay)\n\t// we don't add it again as it will cause a duplication of items.\n}","line":{"from":169,"to":186}} {"id":100031209,"name":"RemoveAPIService","signature":"func (c *AggregationController) RemoveAPIService(apiServiceName string)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapi/controller.go","code":"// RemoveAPIService removes API Service from OpenAPI Aggregation Controller.\nfunc (c *AggregationController) RemoveAPIService(apiServiceName string) {\n\tif err := c.openAPIAggregationManager.RemoveAPIServiceSpec(apiServiceName); err != nil {\n\t\tutilruntime.HandleError(fmt.Errorf(\"removing %q from AggregationController failed with: %v\", apiServiceName, err))\n\t}\n\t// This will only remove it if it was failing before. If it was successful, processNextWorkItem will figure it out\n\t// and will not add it again to the queue.\n\tc.queue.Forget(apiServiceName)\n}","line":{"from":188,"to":196}} {"id":100031210,"name":"IsLocalAPIService","signature":"func IsLocalAPIService(apiServiceName string) bool","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/aggregator/aggregator.go","code":"// IsLocalAPIService returns true for local specs from delegates.\nfunc IsLocalAPIService(apiServiceName string) bool {\n\treturn strings.HasPrefix(apiServiceName, localDelegateChainNamePrefix)\n}","line":{"from":56,"to":59}} {"id":100031211,"name":"GetAPIServiceNames","signature":"func (s *specProxier) GetAPIServiceNames() []string","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/aggregator/aggregator.go","code":"// GetAPIServiceNames returns the names of APIServices recorded in apiServiceInfo.\n// We use this function to pass the names of local APIServices to the controller in this package,\n// so that the controller can periodically sync the OpenAPI spec from delegation API servers.\nfunc (s *specProxier) GetAPIServiceNames() []string {\n\ts.rwMutex.RLock()\n\tdefer s.rwMutex.RUnlock()\n\n\tnames := make([]string, 0, len(s.apiServiceInfo))\n\tfor key := range s.apiServiceInfo {\n\t\tnames = append(names, key)\n\t}\n\treturn names\n}","line":{"from":61,"to":73}} {"id":100031212,"name":"BuildAndRegisterAggregator","signature":"func BuildAndRegisterAggregator(downloader Downloader, delegationTarget server.DelegationTarget, pathHandler common.PathHandlerByGroupVersion) (SpecProxier, error)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/aggregator/aggregator.go","code":"// BuildAndRegisterAggregator registered OpenAPI aggregator handler. This function is not thread safe as it only being called on startup.\nfunc BuildAndRegisterAggregator(downloader Downloader, delegationTarget server.DelegationTarget, pathHandler common.PathHandlerByGroupVersion) (SpecProxier, error) {\n\ts := \u0026specProxier{\n\t\tapiServiceInfo: map[string]*openAPIV3APIServiceInfo{},\n\t\tdownloader: downloader,\n\t}\n\n\ti := 1\n\tfor delegate := delegationTarget; delegate != nil; delegate = delegate.NextDelegate() {\n\t\thandler := delegate.UnprotectedHandler()\n\t\tif handler == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tapiServiceName := fmt.Sprintf(localDelegateChainNamePattern, i)\n\t\tlocalAPIService := v1.APIService{}\n\t\tlocalAPIService.Name = apiServiceName\n\t\ts.AddUpdateAPIService(handler, \u0026localAPIService)\n\t\ts.UpdateAPIServiceSpec(apiServiceName)\n\t\ti++\n\t}\n\n\thandler := handler3.NewOpenAPIService()\n\ts.openAPIV2ConverterHandler = handler\n\topenAPIV2ConverterMux := mux.NewPathRecorderMux(openAPIV2Converter)\n\ts.openAPIV2ConverterHandler.RegisterOpenAPIV3VersionedService(\"/openapi/v3\", openAPIV2ConverterMux)\n\topenAPIV2ConverterAPIService := v1.APIService{}\n\topenAPIV2ConverterAPIService.Name = openAPIV2Converter\n\ts.AddUpdateAPIService(openAPIV2ConverterMux, \u0026openAPIV2ConverterAPIService)\n\ts.register(pathHandler)\n\n\treturn s, nil\n}","line":{"from":75,"to":107}} {"id":100031213,"name":"AddUpdateAPIService","signature":"func (s *specProxier) AddUpdateAPIService(handler http.Handler, apiservice *v1.APIService)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/aggregator/aggregator.go","code":"// AddUpdateAPIService adds or updates the api service. It is thread safe.\nfunc (s *specProxier) AddUpdateAPIService(handler http.Handler, apiservice *v1.APIService) {\n\ts.rwMutex.Lock()\n\tdefer s.rwMutex.Unlock()\n\t// If the APIService is being updated, use the existing struct.\n\tif apiServiceInfo, ok := s.apiServiceInfo[apiservice.Name]; ok {\n\t\tapiServiceInfo.apiService = *apiservice\n\t\tapiServiceInfo.handler = handler\n\t}\n\ts.apiServiceInfo[apiservice.Name] = \u0026openAPIV3APIServiceInfo{\n\t\tapiService: *apiservice,\n\t\thandler: handler,\n\t}\n}","line":{"from":109,"to":122}} {"id":100031214,"name":"getGroupVersionStringFromAPIService","signature":"func getGroupVersionStringFromAPIService(apiService v1.APIService) string","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/aggregator/aggregator.go","code":"func getGroupVersionStringFromAPIService(apiService v1.APIService) string {\n\tif apiService.Spec.Group == \"\" \u0026\u0026 apiService.Spec.Version == \"\" {\n\t\treturn \"\"\n\t}\n\treturn \"apis/\" + apiService.Spec.Group + \"/\" + apiService.Spec.Version\n}","line":{"from":124,"to":129}} {"id":100031215,"name":"UpdateAPIServiceSpec","signature":"func (s *specProxier) UpdateAPIServiceSpec(apiServiceName string) error","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/aggregator/aggregator.go","code":"// UpdateAPIServiceSpec updates all the OpenAPI v3 specs that the APIService serves.\n// It is thread safe.\nfunc (s *specProxier) UpdateAPIServiceSpec(apiServiceName string) error {\n\ts.rwMutex.Lock()\n\tdefer s.rwMutex.Unlock()\n\treturn s.updateAPIServiceSpecLocked(apiServiceName)\n}","line":{"from":131,"to":137}} {"id":100031216,"name":"updateAPIServiceSpecLocked","signature":"func (s *specProxier) updateAPIServiceSpecLocked(apiServiceName string) error","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/aggregator/aggregator.go","code":"func (s *specProxier) updateAPIServiceSpecLocked(apiServiceName string) error {\n\tapiService, exists := s.apiServiceInfo[apiServiceName]\n\tif !exists {\n\t\treturn fmt.Errorf(\"APIService %s does not exist for update\", apiServiceName)\n\t}\n\n\tif !apiService.isLegacyAPIService {\n\t\tgv, httpStatus, err := s.downloader.OpenAPIV3Root(apiService.handler)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif httpStatus == http.StatusNotFound {\n\t\t\tapiService.isLegacyAPIService = true\n\t\t} else {\n\t\t\ts.apiServiceInfo[apiServiceName].discovery = gv\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tnewDownloader := v2aggregator.Downloader{}\n\tv2Spec, etag, httpStatus, err := newDownloader.Download(apiService.handler, apiService.etag)\n\tif err != nil {\n\t\treturn err\n\t}\n\tapiService.etag = etag\n\tif httpStatus == http.StatusOK {\n\t\tv3Spec := openapiconv.ConvertV2ToV3(v2Spec)\n\t\ts.openAPIV2ConverterHandler.UpdateGroupVersion(getGroupVersionStringFromAPIService(apiService.apiService), v3Spec)\n\t\ts.updateAPIServiceSpecLocked(openAPIV2Converter)\n\t}\n\treturn nil\n}","line":{"from":139,"to":170}} {"id":100031217,"name":"RemoveAPIServiceSpec","signature":"func (s *specProxier) RemoveAPIServiceSpec(apiServiceName string)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/aggregator/aggregator.go","code":"// RemoveAPIServiceSpec removes an api service from the OpenAPI map. If it does not exist, no error is returned.\n// It is thread safe.\nfunc (s *specProxier) RemoveAPIServiceSpec(apiServiceName string) {\n\ts.rwMutex.Lock()\n\tdefer s.rwMutex.Unlock()\n\tif apiServiceInfo, ok := s.apiServiceInfo[apiServiceName]; ok {\n\t\ts.openAPIV2ConverterHandler.DeleteGroupVersion(getGroupVersionStringFromAPIService(apiServiceInfo.apiService))\n\t\tdelete(s.apiServiceInfo, apiServiceName)\n\t}\n}","line":{"from":199,"to":208}} {"id":100031218,"name":"getOpenAPIV3Root","signature":"func (s *specProxier) getOpenAPIV3Root() handler3.OpenAPIV3Discovery","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/aggregator/aggregator.go","code":"func (s *specProxier) getOpenAPIV3Root() handler3.OpenAPIV3Discovery {\n\ts.rwMutex.RLock()\n\tdefer s.rwMutex.RUnlock()\n\n\tmerged := handler3.OpenAPIV3Discovery{\n\t\tPaths: make(map[string]handler3.OpenAPIV3DiscoveryGroupVersion),\n\t}\n\n\tfor _, apiServiceInfo := range s.apiServiceInfo {\n\t\tif apiServiceInfo.discovery == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor key, item := range apiServiceInfo.discovery.Paths {\n\t\t\tmerged.Paths[key] = item\n\t\t}\n\t}\n\treturn merged\n}","line":{"from":210,"to":228}} {"id":100031219,"name":"handleDiscovery","signature":"func (s *specProxier) handleDiscovery(w http.ResponseWriter, r *http.Request)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/aggregator/aggregator.go","code":"// handleDiscovery is the handler for OpenAPI V3 Discovery\nfunc (s *specProxier) handleDiscovery(w http.ResponseWriter, r *http.Request) {\n\tmerged := s.getOpenAPIV3Root()\n\tj, err := json.Marshal(\u0026merged)\n\tif err != nil {\n\t\tw.WriteHeader(500)\n\t\tklog.Errorf(\"failed to created merged OpenAPIv3 discovery response: %s\", err.Error())\n\t\treturn\n\t}\n\n\thttp.ServeContent(w, r, \"/openapi/v3\", time.Now(), bytes.NewReader(j))\n}","line":{"from":230,"to":241}} {"id":100031220,"name":"handleGroupVersion","signature":"func (s *specProxier) handleGroupVersion(w http.ResponseWriter, r *http.Request)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/aggregator/aggregator.go","code":"// handleGroupVersion is the OpenAPI V3 handler for a specified group/version\nfunc (s *specProxier) handleGroupVersion(w http.ResponseWriter, r *http.Request) {\n\ts.rwMutex.RLock()\n\tdefer s.rwMutex.RUnlock()\n\n\t// TODO: Import this logic from kube-openapi instead of duplicating\n\t// URLs for OpenAPI V3 have the format /openapi/v3/\u003cgroupversionpath\u003e\n\t// SplitAfterN with 4 yields [\"\", \"openapi\", \"v3\", \u003cgroupversionpath\u003e]\n\turl := strings.SplitAfterN(r.URL.Path, \"/\", 4)\n\ttargetGV := url[3]\n\n\tfor _, apiServiceInfo := range s.apiServiceInfo {\n\t\tif apiServiceInfo.discovery == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor key := range apiServiceInfo.discovery.Paths {\n\t\t\tif targetGV == key {\n\t\t\t\tapiServiceInfo.handler.ServeHTTP(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\t// No group-versions match the desired request\n\tw.WriteHeader(404)\n}","line":{"from":243,"to":268}} {"id":100031221,"name":"register","signature":"func (s *specProxier) register(handler common.PathHandlerByGroupVersion)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/aggregator/aggregator.go","code":"// Register registers the OpenAPI V3 Discovery and GroupVersion handlers\nfunc (s *specProxier) register(handler common.PathHandlerByGroupVersion) {\n\thandler.Handle(\"/openapi/v3\", metrics.InstrumentHandlerFunc(\"GET\",\n\t\t/* group = */ \"\",\n\t\t/* version = */ \"\",\n\t\t/* resource = */ \"\",\n\t\t/* subresource = */ \"openapi/v3\",\n\t\t/* scope = */ \"\",\n\t\t/* component = */ \"\",\n\t\t/* deprecated */ false,\n\t\t/* removedRelease */ \"\",\n\t\thttp.HandlerFunc(s.handleDiscovery)))\n\thandler.HandlePrefix(\"/openapi/v3/\", metrics.InstrumentHandlerFunc(\"GET\",\n\t\t/* group = */ \"\",\n\t\t/* version = */ \"\",\n\t\t/* resource = */ \"\",\n\t\t/* subresource = */ \"openapi/v3/\",\n\t\t/* scope = */ \"\",\n\t\t/* component = */ \"\",\n\t\t/* deprecated */ false,\n\t\t/* removedRelease */ \"\",\n\t\thttp.HandlerFunc(s.handleGroupVersion)))\n}","line":{"from":270,"to":292}} {"id":100031222,"name":"Error","signature":"func (e *NotFoundError) Error() string","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/aggregator/downloader.go","code":"func (e *NotFoundError) Error() string {\n\treturn \"\"\n}","line":{"from":32,"to":34}} {"id":100031223,"name":"NewDownloader","signature":"func NewDownloader() Downloader","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/aggregator/downloader.go","code":"// NewDownloader creates a new OpenAPI Downloader.\nfunc NewDownloader() Downloader {\n\treturn Downloader{}\n}","line":{"from":40,"to":43}} {"id":100031224,"name":"handlerWithUser","signature":"func (s *Downloader) handlerWithUser(handler http.Handler, info user.Info) http.Handler","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/aggregator/downloader.go","code":"func (s *Downloader) handlerWithUser(handler http.Handler, info user.Info) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\treq = req.WithContext(request.WithUser(req.Context(), info))\n\t\thandler.ServeHTTP(w, req)\n\t})\n}","line":{"from":45,"to":50}} {"id":100031225,"name":"OpenAPIV3Root","signature":"func (s *Downloader) OpenAPIV3Root(handler http.Handler) (*handler3.OpenAPIV3Discovery, int, error)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/aggregator/downloader.go","code":"// OpenAPIV3Root downloads the OpenAPI V3 root document from an APIService\nfunc (s *Downloader) OpenAPIV3Root(handler http.Handler) (*handler3.OpenAPIV3Discovery, int, error) {\n\thandler = s.handlerWithUser(handler, \u0026user.DefaultInfo{Name: aggregatorUser})\n\thandler = http.TimeoutHandler(handler, specDownloadTimeout, \"request timed out\")\n\n\treq, err := http.NewRequest(\"GET\", \"/openapi/v3\", nil)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\twriter := newInMemoryResponseWriter()\n\thandler.ServeHTTP(writer, req)\n\n\tswitch writer.respCode {\n\tcase http.StatusNotFound:\n\t\treturn nil, writer.respCode, nil\n\tcase http.StatusOK:\n\t\tgroups := handler3.OpenAPIV3Discovery{}\n\t\tif err := json.Unmarshal(writer.data, \u0026groups); err != nil {\n\t\t\treturn nil, writer.respCode, err\n\t\t}\n\t\treturn \u0026groups, writer.respCode, nil\n\t}\n\treturn nil, writer.respCode, fmt.Errorf(\"Error, could not get list of group versions for APIService\")\n}","line":{"from":52,"to":75}} {"id":100031226,"name":"newInMemoryResponseWriter","signature":"func newInMemoryResponseWriter() *inMemoryResponseWriter","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/aggregator/downloader.go","code":"func newInMemoryResponseWriter() *inMemoryResponseWriter {\n\treturn \u0026inMemoryResponseWriter{header: http.Header{}}\n}","line":{"from":85,"to":87}} {"id":100031227,"name":"Header","signature":"func (r *inMemoryResponseWriter) Header() http.Header","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/aggregator/downloader.go","code":"func (r *inMemoryResponseWriter) Header() http.Header {\n\treturn r.header\n}","line":{"from":89,"to":91}} {"id":100031228,"name":"WriteHeader","signature":"func (r *inMemoryResponseWriter) WriteHeader(code int)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/aggregator/downloader.go","code":"func (r *inMemoryResponseWriter) WriteHeader(code int) {\n\tr.writeHeaderCalled = true\n\tr.respCode = code\n}","line":{"from":93,"to":96}} {"id":100031229,"name":"Write","signature":"func (r *inMemoryResponseWriter) Write(in []byte) (int, error)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/aggregator/downloader.go","code":"func (r *inMemoryResponseWriter) Write(in []byte) (int, error) {\n\tif !r.writeHeaderCalled {\n\t\tr.WriteHeader(http.StatusOK)\n\t}\n\tr.data = append(r.data, in...)\n\treturn len(in), nil\n}","line":{"from":98,"to":104}} {"id":100031230,"name":"String","signature":"func (r *inMemoryResponseWriter) String() string","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/aggregator/downloader.go","code":"func (r *inMemoryResponseWriter) String() string {\n\ts := fmt.Sprintf(\"ResponseCode: %d\", r.respCode)\n\tif r.data != nil {\n\t\ts += fmt.Sprintf(\", Body: %s\", string(r.data))\n\t}\n\tif r.header != nil {\n\t\ts += fmt.Sprintf(\", Header: %s\", r.header)\n\t}\n\treturn s\n}","line":{"from":106,"to":115}} {"id":100031231,"name":"NewAggregationController","signature":"func NewAggregationController(openAPIAggregationManager aggregator.SpecProxier) *AggregationController","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/controller.go","code":"// NewAggregationController creates new OpenAPI aggregation controller.\nfunc NewAggregationController(openAPIAggregationManager aggregator.SpecProxier) *AggregationController {\n\tc := \u0026AggregationController{\n\t\topenAPIAggregationManager: openAPIAggregationManager,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(\n\t\t\tworkqueue.NewItemExponentialFailureRateLimiter(successfulUpdateDelay, failedUpdateMaxExpDelay),\n\t\t\t\"open_api_v3_aggregation_controller\",\n\t\t),\n\t}\n\n\tc.syncHandler = c.sync\n\n\t// update each service at least once, also those which are not coming from APIServices, namely local services\n\tfor _, name := range openAPIAggregationManager.GetAPIServiceNames() {\n\t\tc.queue.AddAfter(name, time.Second)\n\t}\n\n\treturn c\n}","line":{"from":55,"to":73}} {"id":100031232,"name":"Run","signature":"func (c *AggregationController) Run(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/controller.go","code":"// Run starts OpenAPI AggregationController\nfunc (c *AggregationController) Run(stopCh \u003c-chan struct{}) {\n\tdefer utilruntime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\n\tklog.Info(\"Starting OpenAPI V3 AggregationController\")\n\tdefer klog.Info(\"Shutting down OpenAPI V3 AggregationController\")\n\n\tgo wait.Until(c.runWorker, time.Second, stopCh)\n\n\t\u003c-stopCh\n}","line":{"from":75,"to":86}} {"id":100031233,"name":"runWorker","signature":"func (c *AggregationController) runWorker()","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/controller.go","code":"func (c *AggregationController) runWorker() {\n\tfor c.processNextWorkItem() {\n\t}\n}","line":{"from":88,"to":91}} {"id":100031234,"name":"processNextWorkItem","signature":"func (c *AggregationController) processNextWorkItem() bool","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/controller.go","code":"// processNextWorkItem deals with one key off the queue. It returns false when it's time to quit.\nfunc (c *AggregationController) processNextWorkItem() bool {\n\tkey, quit := c.queue.Get()\n\tdefer c.queue.Done(key)\n\tif quit {\n\t\treturn false\n\t}\n\n\tif aggregator.IsLocalAPIService(key.(string)) {\n\t\t// for local delegation targets that are aggregated once per second, log at\n\t\t// higher level to avoid flooding the log\n\t\tklog.V(6).Infof(\"OpenAPI AggregationController: Processing item %s\", key)\n\t} else {\n\t\tklog.V(4).Infof(\"OpenAPI AggregationController: Processing item %s\", key)\n\t}\n\n\taction, err := c.syncHandler(key.(string))\n\tif err == nil {\n\t\tc.queue.Forget(key)\n\t} else {\n\t\tutilruntime.HandleError(fmt.Errorf(\"loading OpenAPI spec for %q failed with: %v\", key, err))\n\t}\n\n\tswitch action {\n\tcase syncRequeue:\n\t\tif aggregator.IsLocalAPIService(key.(string)) {\n\t\t\tklog.V(7).Infof(\"OpenAPI AggregationController: action for local item %s: Requeue after %s.\", key, successfulUpdateDelayLocal)\n\t\t\tc.queue.AddAfter(key, successfulUpdateDelayLocal)\n\t\t} else {\n\t\t\tklog.V(7).Infof(\"OpenAPI AggregationController: action for item %s: Requeue.\", key)\n\t\t\tc.queue.AddAfter(key, successfulUpdateDelay)\n\t\t}\n\tcase syncRequeueRateLimited:\n\t\tklog.Infof(\"OpenAPI AggregationController: action for item %s: Rate Limited Requeue.\", key)\n\t\tc.queue.AddRateLimited(key)\n\tcase syncNothing:\n\t\tklog.Infof(\"OpenAPI AggregationController: action for item %s: Nothing (removed from the queue).\", key)\n\t}\n\n\treturn true\n}","line":{"from":93,"to":133}} {"id":100031235,"name":"sync","signature":"func (c *AggregationController) sync(key string) (syncAction, error)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/controller.go","code":"func (c *AggregationController) sync(key string) (syncAction, error) {\n\terr := c.openAPIAggregationManager.UpdateAPIServiceSpec(key)\n\tswitch {\n\tcase err != nil:\n\t\treturn syncRequeueRateLimited, err\n\t}\n\treturn syncRequeue, nil\n}","line":{"from":135,"to":142}} {"id":100031236,"name":"AddAPIService","signature":"func (c *AggregationController) AddAPIService(handler http.Handler, apiService *v1.APIService)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/controller.go","code":"// AddAPIService adds a new API Service to OpenAPI Aggregation.\nfunc (c *AggregationController) AddAPIService(handler http.Handler, apiService *v1.APIService) {\n\tif apiService.Spec.Service == nil {\n\t\treturn\n\t}\n\tc.openAPIAggregationManager.AddUpdateAPIService(handler, apiService)\n\tc.queue.AddAfter(apiService.Name, time.Second)\n}","line":{"from":144,"to":151}} {"id":100031237,"name":"UpdateAPIService","signature":"func (c *AggregationController) UpdateAPIService(handler http.Handler, apiService *v1.APIService)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/controller.go","code":"// UpdateAPIService updates API Service's info and handler.\nfunc (c *AggregationController) UpdateAPIService(handler http.Handler, apiService *v1.APIService) {\n\tif apiService.Spec.Service == nil {\n\t\treturn\n\t}\n\tc.openAPIAggregationManager.AddUpdateAPIService(handler, apiService)\n\tkey := apiService.Name\n\tif c.queue.NumRequeues(key) \u003e 0 {\n\t\t// The item has failed before. Remove it from failure queue and\n\t\t// update it in a second\n\t\tc.queue.Forget(key)\n\t\tc.queue.AddAfter(key, time.Second)\n\t}\n}","line":{"from":153,"to":166}} {"id":100031238,"name":"RemoveAPIService","signature":"func (c *AggregationController) RemoveAPIService(apiServiceName string)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/openapiv3/controller.go","code":"// RemoveAPIService removes API Service from OpenAPI Aggregation Controller.\nfunc (c *AggregationController) RemoveAPIService(apiServiceName string) {\n\tc.openAPIAggregationManager.RemoveAPIServiceSpec(apiServiceName)\n\t// This will only remove it if it was failing before. If it was successful, processNextWorkItem will figure it out\n\t// and will not add it again to the queue.\n\tc.queue.Forget(apiServiceName)\n}","line":{"from":168,"to":174}} {"id":100031239,"name":"NewAvailableConditionController","signature":"func NewAvailableConditionController(","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/available_controller.go","code":"// NewAvailableConditionController returns a new AvailableConditionController.\nfunc NewAvailableConditionController(\n\tapiServiceInformer informers.APIServiceInformer,\n\tserviceInformer v1informers.ServiceInformer,\n\tendpointsInformer v1informers.EndpointsInformer,\n\tapiServiceClient apiregistrationclient.APIServicesGetter,\n\tproxyTransportDial *transport.DialHolder,\n\tproxyCurrentCertKeyContent certKeyFunc,\n\tserviceResolver ServiceResolver,\n) (*AvailableConditionController, error) {\n\tc := \u0026AvailableConditionController{\n\t\tapiServiceClient: apiServiceClient,\n\t\tapiServiceLister: apiServiceInformer.Lister(),\n\t\tserviceLister: serviceInformer.Lister(),\n\t\tendpointsLister: endpointsInformer.Lister(),\n\t\tserviceResolver: serviceResolver,\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(\n\t\t\t// We want a fairly tight requeue time. The controller listens to the API, but because it relies on the routability of the\n\t\t\t// service network, it is possible for an external, non-watchable factor to affect availability. This keeps\n\t\t\t// the maximum disruption time to a minimum, but it does prevent hot loops.\n\t\t\tworkqueue.NewItemExponentialFailureRateLimiter(5*time.Millisecond, 30*time.Second),\n\t\t\t\"AvailableConditionController\"),\n\t\tproxyTransportDial: proxyTransportDial,\n\t\tproxyCurrentCertKeyContent: proxyCurrentCertKeyContent,\n\t\tmetrics: newAvailabilityMetrics(),\n\t}\n\n\t// resync on this one because it is low cardinality and rechecking the actual discovery\n\t// allows us to detect health in a more timely fashion when network connectivity to\n\t// nodes is snipped, but the network still attempts to route there. See\n\t// https://github.com/openshift/origin/issues/17159#issuecomment-341798063\n\tapiServiceHandler, _ := apiServiceInformer.Informer().AddEventHandlerWithResyncPeriod(\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: c.addAPIService,\n\t\t\tUpdateFunc: c.updateAPIService,\n\t\t\tDeleteFunc: c.deleteAPIService,\n\t\t},\n\t\t30*time.Second)\n\tc.apiServiceSynced = apiServiceHandler.HasSynced\n\n\tserviceHandler, _ := serviceInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: c.addService,\n\t\tUpdateFunc: c.updateService,\n\t\tDeleteFunc: c.deleteService,\n\t})\n\tc.servicesSynced = serviceHandler.HasSynced\n\n\tendpointsHandler, _ := endpointsInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: c.addEndpoints,\n\t\tUpdateFunc: c.updateEndpoints,\n\t\tDeleteFunc: c.deleteEndpoints,\n\t})\n\tc.endpointsSynced = endpointsHandler.HasSynced\n\n\tc.syncFn = c.sync\n\n\t// TODO: decouple from legacyregistry\n\tvar err error\n\tregisterIntoLegacyRegistryOnce.Do(func() {\n\t\terr = c.metrics.Register(legacyregistry.Register, legacyregistry.CustomRegister)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}","line":{"from":94,"to":160}} {"id":100031240,"name":"sync","signature":"func (c *AvailableConditionController) sync(key string) error","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/available_controller.go","code":"func (c *AvailableConditionController) sync(key string) error {\n\toriginalAPIService, err := c.apiServiceLister.Get(key)\n\tif apierrors.IsNotFound(err) {\n\t\tc.metrics.ForgetAPIService(key)\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// if a particular transport was specified, use that otherwise build one\n\t// construct an http client that will ignore TLS verification (if someone owns the network and messes with your status\n\t// that's not so bad) and sets a very short timeout. This is a best effort GET that provides no additional information\n\ttransportConfig := \u0026transport.Config{\n\t\tTLS: transport.TLSConfig{\n\t\t\tInsecure: true,\n\t\t},\n\t\tDialHolder: c.proxyTransportDial,\n\t}\n\n\tif c.proxyCurrentCertKeyContent != nil {\n\t\tproxyClientCert, proxyClientKey := c.proxyCurrentCertKeyContent()\n\n\t\ttransportConfig.TLS.CertData = proxyClientCert\n\t\ttransportConfig.TLS.KeyData = proxyClientKey\n\t}\n\trestTransport, err := transport.New(transportConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdiscoveryClient := \u0026http.Client{\n\t\tTransport: restTransport,\n\t\t// the request should happen quickly.\n\t\tTimeout: 5 * time.Second,\n\t\tCheckRedirect: func(req *http.Request, via []*http.Request) error {\n\t\t\treturn http.ErrUseLastResponse\n\t\t},\n\t}\n\n\tapiService := originalAPIService.DeepCopy()\n\n\tavailableCondition := apiregistrationv1.APIServiceCondition{\n\t\tType: apiregistrationv1.Available,\n\t\tStatus: apiregistrationv1.ConditionTrue,\n\t\tLastTransitionTime: metav1.Now(),\n\t}\n\n\t// local API services are always considered available\n\tif apiService.Spec.Service == nil {\n\t\tapiregistrationv1apihelper.SetAPIServiceCondition(apiService, apiregistrationv1apihelper.NewLocalAvailableAPIServiceCondition())\n\t\t_, err := c.updateAPIServiceStatus(originalAPIService, apiService)\n\t\treturn err\n\t}\n\n\tservice, err := c.serviceLister.Services(apiService.Spec.Service.Namespace).Get(apiService.Spec.Service.Name)\n\tif apierrors.IsNotFound(err) {\n\t\tavailableCondition.Status = apiregistrationv1.ConditionFalse\n\t\tavailableCondition.Reason = \"ServiceNotFound\"\n\t\tavailableCondition.Message = fmt.Sprintf(\"service/%s in %q is not present\", apiService.Spec.Service.Name, apiService.Spec.Service.Namespace)\n\t\tapiregistrationv1apihelper.SetAPIServiceCondition(apiService, availableCondition)\n\t\t_, err := c.updateAPIServiceStatus(originalAPIService, apiService)\n\t\treturn err\n\t} else if err != nil {\n\t\tavailableCondition.Status = apiregistrationv1.ConditionUnknown\n\t\tavailableCondition.Reason = \"ServiceAccessError\"\n\t\tavailableCondition.Message = fmt.Sprintf(\"service/%s in %q cannot be checked due to: %v\", apiService.Spec.Service.Name, apiService.Spec.Service.Namespace, err)\n\t\tapiregistrationv1apihelper.SetAPIServiceCondition(apiService, availableCondition)\n\t\t_, err := c.updateAPIServiceStatus(originalAPIService, apiService)\n\t\treturn err\n\t}\n\n\tif service.Spec.Type == v1.ServiceTypeClusterIP {\n\t\t// if we have a cluster IP service, it must be listening on configured port and we can check that\n\t\tservicePort := apiService.Spec.Service.Port\n\t\tportName := \"\"\n\t\tfoundPort := false\n\t\tfor _, port := range service.Spec.Ports {\n\t\t\tif port.Port == *servicePort {\n\t\t\t\tfoundPort = true\n\t\t\t\tportName = port.Name\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !foundPort {\n\t\t\tavailableCondition.Status = apiregistrationv1.ConditionFalse\n\t\t\tavailableCondition.Reason = \"ServicePortError\"\n\t\t\tavailableCondition.Message = fmt.Sprintf(\"service/%s in %q is not listening on port %d\", apiService.Spec.Service.Name, apiService.Spec.Service.Namespace, *apiService.Spec.Service.Port)\n\t\t\tapiregistrationv1apihelper.SetAPIServiceCondition(apiService, availableCondition)\n\t\t\t_, err := c.updateAPIServiceStatus(originalAPIService, apiService)\n\t\t\treturn err\n\t\t}\n\n\t\tendpoints, err := c.endpointsLister.Endpoints(apiService.Spec.Service.Namespace).Get(apiService.Spec.Service.Name)\n\t\tif apierrors.IsNotFound(err) {\n\t\t\tavailableCondition.Status = apiregistrationv1.ConditionFalse\n\t\t\tavailableCondition.Reason = \"EndpointsNotFound\"\n\t\t\tavailableCondition.Message = fmt.Sprintf(\"cannot find endpoints for service/%s in %q\", apiService.Spec.Service.Name, apiService.Spec.Service.Namespace)\n\t\t\tapiregistrationv1apihelper.SetAPIServiceCondition(apiService, availableCondition)\n\t\t\t_, err := c.updateAPIServiceStatus(originalAPIService, apiService)\n\t\t\treturn err\n\t\t} else if err != nil {\n\t\t\tavailableCondition.Status = apiregistrationv1.ConditionUnknown\n\t\t\tavailableCondition.Reason = \"EndpointsAccessError\"\n\t\t\tavailableCondition.Message = fmt.Sprintf(\"service/%s in %q cannot be checked due to: %v\", apiService.Spec.Service.Name, apiService.Spec.Service.Namespace, err)\n\t\t\tapiregistrationv1apihelper.SetAPIServiceCondition(apiService, availableCondition)\n\t\t\t_, err := c.updateAPIServiceStatus(originalAPIService, apiService)\n\t\t\treturn err\n\t\t}\n\t\thasActiveEndpoints := false\n\touter:\n\t\tfor _, subset := range endpoints.Subsets {\n\t\t\tif len(subset.Addresses) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor _, endpointPort := range subset.Ports {\n\t\t\t\tif endpointPort.Name == portName {\n\t\t\t\t\thasActiveEndpoints = true\n\t\t\t\t\tbreak outer\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif !hasActiveEndpoints {\n\t\t\tavailableCondition.Status = apiregistrationv1.ConditionFalse\n\t\t\tavailableCondition.Reason = \"MissingEndpoints\"\n\t\t\tavailableCondition.Message = fmt.Sprintf(\"endpoints for service/%s in %q have no addresses with port name %q\", apiService.Spec.Service.Name, apiService.Spec.Service.Namespace, portName)\n\t\t\tapiregistrationv1apihelper.SetAPIServiceCondition(apiService, availableCondition)\n\t\t\t_, err := c.updateAPIServiceStatus(originalAPIService, apiService)\n\t\t\treturn err\n\t\t}\n\t}\n\t// actually try to hit the discovery endpoint when it isn't local and when we're routing as a service.\n\tif apiService.Spec.Service != nil \u0026\u0026 c.serviceResolver != nil {\n\t\tattempts := 5\n\t\tresults := make(chan error, attempts)\n\t\tfor i := 0; i \u003c attempts; i++ {\n\t\t\tgo func() {\n\t\t\t\tdiscoveryURL, err := c.serviceResolver.ResolveEndpoint(apiService.Spec.Service.Namespace, apiService.Spec.Service.Name, *apiService.Spec.Service.Port)\n\t\t\t\tif err != nil {\n\t\t\t\t\tresults \u003c- err\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// render legacyAPIService health check path when it is delegated to a service\n\t\t\t\tif apiService.Name == \"v1.\" {\n\t\t\t\t\tdiscoveryURL.Path = \"/api/\" + apiService.Spec.Version\n\t\t\t\t} else {\n\t\t\t\t\tdiscoveryURL.Path = \"/apis/\" + apiService.Spec.Group + \"/\" + apiService.Spec.Version\n\t\t\t\t}\n\n\t\t\t\terrCh := make(chan error, 1)\n\t\t\t\tgo func() {\n\t\t\t\t\t// be sure to check a URL that the aggregated API server is required to serve\n\t\t\t\t\tnewReq, err := http.NewRequest(\"GET\", discoveryURL.String(), nil)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\terrCh \u003c- err\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\t// setting the system-masters identity ensures that we will always have access rights\n\t\t\t\t\ttransport.SetAuthProxyHeaders(newReq, \"system:kube-aggregator\", []string{\"system:masters\"}, nil)\n\t\t\t\t\tresp, err := discoveryClient.Do(newReq)\n\t\t\t\t\tif resp != nil {\n\t\t\t\t\t\tresp.Body.Close()\n\t\t\t\t\t\t// we should always been in the 200s or 300s\n\t\t\t\t\t\tif resp.StatusCode \u003c http.StatusOK || resp.StatusCode \u003e= http.StatusMultipleChoices {\n\t\t\t\t\t\t\terrCh \u003c- fmt.Errorf(\"bad status from %v: %v\", discoveryURL, resp.StatusCode)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\terrCh \u003c- err\n\t\t\t\t}()\n\n\t\t\t\tselect {\n\t\t\t\tcase err = \u003c-errCh:\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tresults \u003c- fmt.Errorf(\"failing or missing response from %v: %v\", discoveryURL, err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\t// we had trouble with slow dial and DNS responses causing us to wait too long.\n\t\t\t\t\t// we added this as insurance\n\t\t\t\tcase \u003c-time.After(6 * time.Second):\n\t\t\t\t\tresults \u003c- fmt.Errorf(\"timed out waiting for %v\", discoveryURL)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tresults \u003c- nil\n\t\t\t}()\n\t\t}\n\n\t\tvar lastError error\n\t\tfor i := 0; i \u003c attempts; i++ {\n\t\t\tlastError = \u003c-results\n\t\t\t// if we had at least one success, we are successful overall and we can return now\n\t\t\tif lastError == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif lastError != nil {\n\t\t\tavailableCondition.Status = apiregistrationv1.ConditionFalse\n\t\t\tavailableCondition.Reason = \"FailedDiscoveryCheck\"\n\t\t\tavailableCondition.Message = lastError.Error()\n\t\t\tapiregistrationv1apihelper.SetAPIServiceCondition(apiService, availableCondition)\n\t\t\t_, updateErr := c.updateAPIServiceStatus(originalAPIService, apiService)\n\t\t\tif updateErr != nil {\n\t\t\t\treturn updateErr\n\t\t\t}\n\t\t\t// force a requeue to make it very obvious that this will be retried at some point in the future\n\t\t\t// along with other requeues done via service change, endpoint change, and resync\n\t\t\treturn lastError\n\t\t}\n\t}\n\n\tavailableCondition.Reason = \"Passed\"\n\tavailableCondition.Message = \"all checks passed\"\n\tapiregistrationv1apihelper.SetAPIServiceCondition(apiService, availableCondition)\n\t_, err = c.updateAPIServiceStatus(originalAPIService, apiService)\n\treturn err\n}","line":{"from":162,"to":381}} {"id":100031241,"name":"updateAPIServiceStatus","signature":"func (c *AvailableConditionController) updateAPIServiceStatus(originalAPIService, newAPIService *apiregistrationv1.APIService) (*apiregistrationv1.APIService, error)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/available_controller.go","code":"// updateAPIServiceStatus only issues an update if a change is detected. We have a tight resync loop to quickly detect dead\n// apiservices. Doing that means we don't want to quickly issue no-op updates.\nfunc (c *AvailableConditionController) updateAPIServiceStatus(originalAPIService, newAPIService *apiregistrationv1.APIService) (*apiregistrationv1.APIService, error) {\n\t// update this metric on every sync operation to reflect the actual state\n\tc.setUnavailableGauge(newAPIService)\n\n\tif equality.Semantic.DeepEqual(originalAPIService.Status, newAPIService.Status) {\n\t\treturn newAPIService, nil\n\t}\n\n\torig := apiregistrationv1apihelper.GetAPIServiceConditionByType(originalAPIService, apiregistrationv1.Available)\n\tnow := apiregistrationv1apihelper.GetAPIServiceConditionByType(newAPIService, apiregistrationv1.Available)\n\tunknown := apiregistrationv1.APIServiceCondition{\n\t\tType: apiregistrationv1.Available,\n\t\tStatus: apiregistrationv1.ConditionUnknown,\n\t}\n\tif orig == nil {\n\t\torig = \u0026unknown\n\t}\n\tif now == nil {\n\t\tnow = \u0026unknown\n\t}\n\tif *orig != *now {\n\t\tklog.V(2).InfoS(\"changing APIService availability\", \"name\", newAPIService.Name, \"oldStatus\", orig.Status, \"newStatus\", now.Status, \"message\", now.Message, \"reason\", now.Reason)\n\t}\n\n\tnewAPIService, err := c.apiServiceClient.APIServices().UpdateStatus(context.TODO(), newAPIService, metav1.UpdateOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.setUnavailableCounter(originalAPIService, newAPIService)\n\treturn newAPIService, nil\n}","line":{"from":383,"to":416}} {"id":100031242,"name":"Run","signature":"func (c *AvailableConditionController) Run(workers int, stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/available_controller.go","code":"// Run starts the AvailableConditionController loop which manages the availability condition of API services.\nfunc (c *AvailableConditionController) Run(workers int, stopCh \u003c-chan struct{}) {\n\tdefer utilruntime.HandleCrash()\n\tdefer c.queue.ShutDown()\n\n\tklog.Info(\"Starting AvailableConditionController\")\n\tdefer klog.Info(\"Shutting down AvailableConditionController\")\n\n\t// This waits not just for the informers to sync, but for our handlers\n\t// to be called; since the handlers are three different ways of\n\t// enqueueing the same thing, waiting for this permits the queue to\n\t// maximally de-duplicate the entries.\n\tif !controllers.WaitForCacheSync(\"AvailableConditionController\", stopCh, c.apiServiceSynced, c.servicesSynced, c.endpointsSynced) {\n\t\treturn\n\t}\n\n\tfor i := 0; i \u003c workers; i++ {\n\t\tgo wait.Until(c.runWorker, time.Second, stopCh)\n\t}\n\n\t\u003c-stopCh\n}","line":{"from":418,"to":439}} {"id":100031243,"name":"runWorker","signature":"func (c *AvailableConditionController) runWorker()","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/available_controller.go","code":"func (c *AvailableConditionController) runWorker() {\n\tfor c.processNextWorkItem() {\n\t}\n}","line":{"from":441,"to":444}} {"id":100031244,"name":"processNextWorkItem","signature":"func (c *AvailableConditionController) processNextWorkItem() bool","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/available_controller.go","code":"// processNextWorkItem deals with one key off the queue. It returns false when it's time to quit.\nfunc (c *AvailableConditionController) processNextWorkItem() bool {\n\tkey, quit := c.queue.Get()\n\tif quit {\n\t\treturn false\n\t}\n\tdefer c.queue.Done(key)\n\n\terr := c.syncFn(key.(string))\n\tif err == nil {\n\t\tc.queue.Forget(key)\n\t\treturn true\n\t}\n\n\tutilruntime.HandleError(fmt.Errorf(\"%v failed with: %v\", key, err))\n\tc.queue.AddRateLimited(key)\n\n\treturn true\n}","line":{"from":446,"to":464}} {"id":100031245,"name":"addAPIService","signature":"func (c *AvailableConditionController) addAPIService(obj interface{})","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/available_controller.go","code":"func (c *AvailableConditionController) addAPIService(obj interface{}) {\n\tcastObj := obj.(*apiregistrationv1.APIService)\n\tklog.V(4).Infof(\"Adding %s\", castObj.Name)\n\tif castObj.Spec.Service != nil {\n\t\tc.rebuildAPIServiceCache()\n\t}\n\tc.queue.Add(castObj.Name)\n}","line":{"from":466,"to":473}} {"id":100031246,"name":"updateAPIService","signature":"func (c *AvailableConditionController) updateAPIService(oldObj, newObj interface{})","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/available_controller.go","code":"func (c *AvailableConditionController) updateAPIService(oldObj, newObj interface{}) {\n\tcastObj := newObj.(*apiregistrationv1.APIService)\n\toldCastObj := oldObj.(*apiregistrationv1.APIService)\n\tklog.V(4).Infof(\"Updating %s\", oldCastObj.Name)\n\tif !reflect.DeepEqual(castObj.Spec.Service, oldCastObj.Spec.Service) {\n\t\tc.rebuildAPIServiceCache()\n\t}\n\tc.queue.Add(oldCastObj.Name)\n}","line":{"from":475,"to":483}} {"id":100031247,"name":"deleteAPIService","signature":"func (c *AvailableConditionController) deleteAPIService(obj interface{})","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/available_controller.go","code":"func (c *AvailableConditionController) deleteAPIService(obj interface{}) {\n\tcastObj, ok := obj.(*apiregistrationv1.APIService)\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"Couldn't get object from tombstone %#v\", obj)\n\t\t\treturn\n\t\t}\n\t\tcastObj, ok = tombstone.Obj.(*apiregistrationv1.APIService)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"Tombstone contained object that is not expected %#v\", obj)\n\t\t\treturn\n\t\t}\n\t}\n\tklog.V(4).Infof(\"Deleting %q\", castObj.Name)\n\tif castObj.Spec.Service != nil {\n\t\tc.rebuildAPIServiceCache()\n\t}\n\tc.queue.Add(castObj.Name)\n}","line":{"from":485,"to":504}} {"id":100031248,"name":"getAPIServicesFor","signature":"func (c *AvailableConditionController) getAPIServicesFor(obj runtime.Object) []string","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/available_controller.go","code":"func (c *AvailableConditionController) getAPIServicesFor(obj runtime.Object) []string {\n\tmetadata, err := meta.Accessor(obj)\n\tif err != nil {\n\t\tutilruntime.HandleError(err)\n\t\treturn nil\n\t}\n\tc.cacheLock.RLock()\n\tdefer c.cacheLock.RUnlock()\n\treturn c.cache[metadata.GetNamespace()][metadata.GetName()]\n}","line":{"from":506,"to":515}} {"id":100031249,"name":"rebuildAPIServiceCache","signature":"func (c *AvailableConditionController) rebuildAPIServiceCache()","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/available_controller.go","code":"// if the service/endpoint handler wins the race against the cache rebuilding, it may queue a no-longer-relevant apiservice\n// (which will get processed an extra time - this doesn't matter),\n// and miss a newly relevant apiservice (which will get queued by the apiservice handler)\nfunc (c *AvailableConditionController) rebuildAPIServiceCache() {\n\tapiServiceList, _ := c.apiServiceLister.List(labels.Everything())\n\tnewCache := map[string]map[string][]string{}\n\tfor _, apiService := range apiServiceList {\n\t\tif apiService.Spec.Service == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif newCache[apiService.Spec.Service.Namespace] == nil {\n\t\t\tnewCache[apiService.Spec.Service.Namespace] = map[string][]string{}\n\t\t}\n\t\tnewCache[apiService.Spec.Service.Namespace][apiService.Spec.Service.Name] = append(newCache[apiService.Spec.Service.Namespace][apiService.Spec.Service.Name], apiService.Name)\n\t}\n\n\tc.cacheLock.Lock()\n\tdefer c.cacheLock.Unlock()\n\tc.cache = newCache\n}","line":{"from":517,"to":536}} {"id":100031250,"name":"addService","signature":"func (c *AvailableConditionController) addService(obj interface{})","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/available_controller.go","code":"func (c *AvailableConditionController) addService(obj interface{}) {\n\tfor _, apiService := range c.getAPIServicesFor(obj.(*v1.Service)) {\n\t\tc.queue.Add(apiService)\n\t}\n}","line":{"from":540,"to":544}} {"id":100031251,"name":"updateService","signature":"func (c *AvailableConditionController) updateService(obj, _ interface{})","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/available_controller.go","code":"func (c *AvailableConditionController) updateService(obj, _ interface{}) {\n\tfor _, apiService := range c.getAPIServicesFor(obj.(*v1.Service)) {\n\t\tc.queue.Add(apiService)\n\t}\n}","line":{"from":546,"to":550}} {"id":100031252,"name":"deleteService","signature":"func (c *AvailableConditionController) deleteService(obj interface{})","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/available_controller.go","code":"func (c *AvailableConditionController) deleteService(obj interface{}) {\n\tcastObj, ok := obj.(*v1.Service)\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"Couldn't get object from tombstone %#v\", obj)\n\t\t\treturn\n\t\t}\n\t\tcastObj, ok = tombstone.Obj.(*v1.Service)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"Tombstone contained object that is not expected %#v\", obj)\n\t\t\treturn\n\t\t}\n\t}\n\tfor _, apiService := range c.getAPIServicesFor(castObj) {\n\t\tc.queue.Add(apiService)\n\t}\n}","line":{"from":552,"to":569}} {"id":100031253,"name":"addEndpoints","signature":"func (c *AvailableConditionController) addEndpoints(obj interface{})","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/available_controller.go","code":"func (c *AvailableConditionController) addEndpoints(obj interface{}) {\n\tfor _, apiService := range c.getAPIServicesFor(obj.(*v1.Endpoints)) {\n\t\tc.queue.Add(apiService)\n\t}\n}","line":{"from":571,"to":575}} {"id":100031254,"name":"updateEndpoints","signature":"func (c *AvailableConditionController) updateEndpoints(obj, _ interface{})","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/available_controller.go","code":"func (c *AvailableConditionController) updateEndpoints(obj, _ interface{}) {\n\tfor _, apiService := range c.getAPIServicesFor(obj.(*v1.Endpoints)) {\n\t\tc.queue.Add(apiService)\n\t}\n}","line":{"from":577,"to":581}} {"id":100031255,"name":"deleteEndpoints","signature":"func (c *AvailableConditionController) deleteEndpoints(obj interface{})","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/available_controller.go","code":"func (c *AvailableConditionController) deleteEndpoints(obj interface{}) {\n\tcastObj, ok := obj.(*v1.Endpoints)\n\tif !ok {\n\t\ttombstone, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"Couldn't get object from tombstone %#v\", obj)\n\t\t\treturn\n\t\t}\n\t\tcastObj, ok = tombstone.Obj.(*v1.Endpoints)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"Tombstone contained object that is not expected %#v\", obj)\n\t\t\treturn\n\t\t}\n\t}\n\tfor _, apiService := range c.getAPIServicesFor(castObj) {\n\t\tc.queue.Add(apiService)\n\t}\n}","line":{"from":583,"to":600}} {"id":100031256,"name":"setUnavailableGauge","signature":"func (c *AvailableConditionController) setUnavailableGauge(newAPIService *apiregistrationv1.APIService)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/available_controller.go","code":"// setUnavailableGauge set the metrics so that it reflect the current state base on availability of the given service\nfunc (c *AvailableConditionController) setUnavailableGauge(newAPIService *apiregistrationv1.APIService) {\n\tif apiregistrationv1apihelper.IsAPIServiceConditionTrue(newAPIService, apiregistrationv1.Available) {\n\t\tc.metrics.SetAPIServiceAvailable(newAPIService.Name)\n\t\treturn\n\t}\n\n\tc.metrics.SetAPIServiceUnavailable(newAPIService.Name)\n}","line":{"from":602,"to":610}} {"id":100031257,"name":"setUnavailableCounter","signature":"func (c *AvailableConditionController) setUnavailableCounter(originalAPIService, newAPIService *apiregistrationv1.APIService)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/available_controller.go","code":"// setUnavailableCounter increases the metrics only if the given service is unavailable and its APIServiceCondition has changed\nfunc (c *AvailableConditionController) setUnavailableCounter(originalAPIService, newAPIService *apiregistrationv1.APIService) {\n\twasAvailable := apiregistrationv1apihelper.IsAPIServiceConditionTrue(originalAPIService, apiregistrationv1.Available)\n\tisAvailable := apiregistrationv1apihelper.IsAPIServiceConditionTrue(newAPIService, apiregistrationv1.Available)\n\tstatusChanged := isAvailable != wasAvailable\n\n\tif statusChanged \u0026\u0026 !isAvailable {\n\t\treason := \"UnknownReason\"\n\t\tif newCondition := apiregistrationv1apihelper.GetAPIServiceConditionByType(newAPIService, apiregistrationv1.Available); newCondition != nil {\n\t\t\treason = newCondition.Reason\n\t\t}\n\t\tc.metrics.UnavailableCounter(newAPIService.Name, reason).Inc()\n\t}\n}","line":{"from":612,"to":625}} {"id":100031258,"name":"newAvailabilityMetrics","signature":"func newAvailabilityMetrics() *availabilityMetrics","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/metrics.go","code":"func newAvailabilityMetrics() *availabilityMetrics {\n\treturn \u0026availabilityMetrics{\n\t\tunavailableCounter: metrics.NewCounterVec(\n\t\t\t\u0026metrics.CounterOpts{\n\t\t\t\tName: \"aggregator_unavailable_apiservice_total\",\n\t\t\t\tHelp: \"Counter of APIServices which are marked as unavailable broken down by APIService name and reason.\",\n\t\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t\t},\n\t\t\t[]string{\"name\", \"reason\"},\n\t\t),\n\t\tavailabilityCollector: newAvailabilityCollector(),\n\t}\n}","line":{"from":50,"to":62}} {"id":100031259,"name":"Register","signature":"func (m *availabilityMetrics) Register(","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/metrics.go","code":"// Register registers apiservice availability metrics.\nfunc (m *availabilityMetrics) Register(\n\tregistrationFunc func(metrics.Registerable) error,\n\tcustomRegistrationFunc func(metrics.StableCollector) error,\n) error {\n\terr := registrationFunc(m.unavailableCounter)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = customRegistrationFunc(m.availabilityCollector)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":64,"to":80}} {"id":100031260,"name":"UnavailableCounter","signature":"func (m *availabilityMetrics) UnavailableCounter(apiServiceName, reason string) metrics.CounterMetric","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/metrics.go","code":"// UnavailableCounter returns a counter to track apiservices marked as unavailable.\nfunc (m *availabilityMetrics) UnavailableCounter(apiServiceName, reason string) metrics.CounterMetric {\n\treturn m.unavailableCounter.WithLabelValues(apiServiceName, reason)\n}","line":{"from":82,"to":85}} {"id":100031261,"name":"newAvailabilityCollector","signature":"func newAvailabilityCollector() *availabilityCollector","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/metrics.go","code":"func newAvailabilityCollector() *availabilityCollector {\n\treturn \u0026availabilityCollector{\n\t\tavailabilities: make(map[string]bool),\n\t}\n}","line":{"from":97,"to":101}} {"id":100031262,"name":"DescribeWithStability","signature":"func (c *availabilityCollector) DescribeWithStability(ch chan\u003c- *metrics.Desc)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/metrics.go","code":"// DescribeWithStability implements the metrics.StableCollector interface.\nfunc (c *availabilityCollector) DescribeWithStability(ch chan\u003c- *metrics.Desc) {\n\tch \u003c- unavailableGaugeDesc\n}","line":{"from":103,"to":106}} {"id":100031263,"name":"CollectWithStability","signature":"func (c *availabilityCollector) CollectWithStability(ch chan\u003c- metrics.Metric)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/metrics.go","code":"// CollectWithStability implements the metrics.StableCollector interface.\nfunc (c *availabilityCollector) CollectWithStability(ch chan\u003c- metrics.Metric) {\n\tc.mtx.RLock()\n\tdefer c.mtx.RUnlock()\n\n\tfor apiServiceName, isAvailable := range c.availabilities {\n\t\tgaugeValue := 1.0\n\t\tif isAvailable {\n\t\t\tgaugeValue = 0.0\n\t\t}\n\t\tch \u003c- metrics.NewLazyConstMetric(\n\t\t\tunavailableGaugeDesc,\n\t\t\tmetrics.GaugeValue,\n\t\t\tgaugeValue,\n\t\t\tapiServiceName,\n\t\t)\n\t}\n}","line":{"from":108,"to":125}} {"id":100031264,"name":"SetAPIServiceAvailable","signature":"func (c *availabilityCollector) SetAPIServiceAvailable(apiServiceKey string)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/metrics.go","code":"// SetAPIServiceAvailable sets the given apiservice availability gauge to available.\nfunc (c *availabilityCollector) SetAPIServiceAvailable(apiServiceKey string) {\n\tc.setAPIServiceAvailability(apiServiceKey, true)\n}","line":{"from":127,"to":130}} {"id":100031265,"name":"SetAPIServiceUnavailable","signature":"func (c *availabilityCollector) SetAPIServiceUnavailable(apiServiceKey string)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/metrics.go","code":"// SetAPIServiceUnavailable sets the given apiservice availability gauge to unavailable.\nfunc (c *availabilityCollector) SetAPIServiceUnavailable(apiServiceKey string) {\n\tc.setAPIServiceAvailability(apiServiceKey, false)\n}","line":{"from":132,"to":135}} {"id":100031266,"name":"setAPIServiceAvailability","signature":"func (c *availabilityCollector) setAPIServiceAvailability(apiServiceKey string, availability bool)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/metrics.go","code":"func (c *availabilityCollector) setAPIServiceAvailability(apiServiceKey string, availability bool) {\n\tc.mtx.Lock()\n\tdefer c.mtx.Unlock()\n\n\tc.availabilities[apiServiceKey] = availability\n}","line":{"from":137,"to":142}} {"id":100031267,"name":"ForgetAPIService","signature":"func (c *availabilityCollector) ForgetAPIService(apiServiceKey string)","file":"staging/src/k8s.io/kube-aggregator/pkg/controllers/status/metrics.go","code":"// ForgetAPIService removes the availability gauge of the given apiservice.\nfunc (c *availabilityCollector) ForgetAPIService(apiServiceKey string) {\n\tc.mtx.Lock()\n\tdefer c.mtx.Unlock()\n\n\tdelete(c.availabilities, apiServiceKey)\n}","line":{"from":144,"to":150}} {"id":100031268,"name":"NewREST","signature":"func NewREST(scheme *runtime.Scheme, optsGetter generic.RESTOptionsGetter) *REST","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/etcd/etcd.go","code":"// NewREST returns a RESTStorage object that will work against API services.\nfunc NewREST(scheme *runtime.Scheme, optsGetter generic.RESTOptionsGetter) *REST {\n\tstrategy := apiservice.NewStrategy(scheme)\n\tstore := \u0026genericregistry.Store{\n\t\tNewFunc: func() runtime.Object { return \u0026apiregistration.APIService{} },\n\t\tNewListFunc: func() runtime.Object { return \u0026apiregistration.APIServiceList{} },\n\t\tPredicateFunc: apiservice.MatchAPIService,\n\t\tDefaultQualifiedResource: apiregistration.Resource(\"apiservices\"),\n\t\tSingularQualifiedResource: apiregistration.Resource(\"apiservice\"),\n\n\t\tCreateStrategy: strategy,\n\t\tUpdateStrategy: strategy,\n\t\tDeleteStrategy: strategy,\n\t\tResetFieldsStrategy: strategy,\n\n\t\t// TODO: define table converter that exposes more than name/creation timestamp\n\t\tTableConvertor: rest.NewDefaultTableConvertor(apiregistration.Resource(\"apiservices\")),\n\t}\n\toptions := \u0026generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: apiservice.GetAttrs}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\tpanic(err) // TODO: Propagate error up\n\t}\n\treturn \u0026REST{store}\n}","line":{"from":40,"to":63}} {"id":100031269,"name":"Categories","signature":"func (c *REST) Categories() []string","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/etcd/etcd.go","code":"// Categories implements the CategoriesProvider interface. Returns a list of categories a resource is part of.\nfunc (c *REST) Categories() []string {\n\treturn []string{\"api-extensions\"}\n}","line":{"from":68,"to":71}} {"id":100031270,"name":"ConvertToTable","signature":"func (c *REST) ConvertToTable(ctx context.Context, obj runtime.Object, tableOptions runtime.Object) (*metav1.Table, error)","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/etcd/etcd.go","code":"// ConvertToTable implements the TableConvertor interface for REST.\nfunc (c *REST) ConvertToTable(ctx context.Context, obj runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {\n\ttable := \u0026metav1.Table{\n\t\tColumnDefinitions: []metav1.TableColumnDefinition{\n\t\t\t{Name: \"Name\", Type: \"string\", Format: \"name\", Description: swaggerMetadataDescriptions[\"name\"]},\n\t\t\t{Name: \"Service\", Type: \"string\", Description: \"The reference to the service that hosts this API endpoint.\"},\n\t\t\t{Name: \"Available\", Type: \"string\", Description: \"Whether this service is available.\"},\n\t\t\t{Name: \"Age\", Type: \"string\", Description: swaggerMetadataDescriptions[\"creationTimestamp\"]},\n\t\t},\n\t}\n\tif m, err := meta.ListAccessor(obj); err == nil {\n\t\ttable.ResourceVersion = m.GetResourceVersion()\n\t\ttable.Continue = m.GetContinue()\n\t\ttable.RemainingItemCount = m.GetRemainingItemCount()\n\t} else {\n\t\tif m, err := meta.CommonAccessor(obj); err == nil {\n\t\t\ttable.ResourceVersion = m.GetResourceVersion()\n\t\t}\n\t}\n\n\tvar err error\n\ttable.Rows, err = metatable.MetaToTableRow(obj, func(obj runtime.Object, m metav1.Object, name, age string) ([]interface{}, error) {\n\t\tsvc := obj.(*apiregistration.APIService)\n\t\tservice := \"Local\"\n\t\tif svc.Spec.Service != nil {\n\t\t\tservice = fmt.Sprintf(\"%s/%s\", svc.Spec.Service.Namespace, svc.Spec.Service.Name)\n\t\t}\n\t\tstatus := string(apiregistration.ConditionUnknown)\n\t\tif condition := getCondition(svc.Status.Conditions, \"Available\"); condition != nil {\n\t\t\tswitch {\n\t\t\tcase condition.Status == apiregistration.ConditionTrue:\n\t\t\t\tstatus = string(condition.Status)\n\t\t\tcase len(condition.Reason) \u003e 0:\n\t\t\t\tstatus = fmt.Sprintf(\"%s (%s)\", condition.Status, condition.Reason)\n\t\t\tdefault:\n\t\t\t\tstatus = string(condition.Status)\n\t\t\t}\n\t\t}\n\t\treturn []interface{}{name, service, status, age}, nil\n\t})\n\treturn table, err\n}","line":{"from":75,"to":116}} {"id":100031271,"name":"getCondition","signature":"func getCondition(conditions []apiregistration.APIServiceCondition, conditionType apiregistration.APIServiceConditionType) *apiregistration.APIServiceCondition","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/etcd/etcd.go","code":"func getCondition(conditions []apiregistration.APIServiceCondition, conditionType apiregistration.APIServiceConditionType) *apiregistration.APIServiceCondition {\n\tfor i, condition := range conditions {\n\t\tif condition.Type == conditionType {\n\t\t\treturn \u0026conditions[i]\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":118,"to":125}} {"id":100031272,"name":"NewStatusREST","signature":"func NewStatusREST(scheme *runtime.Scheme, rest *REST) *StatusREST","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/etcd/etcd.go","code":"// NewStatusREST makes a RESTStorage for status that has more limited options.\n// It is based on the original REST so that we can share the same underlying store\nfunc NewStatusREST(scheme *runtime.Scheme, rest *REST) *StatusREST {\n\tstrategy := apiservice.NewStatusStrategy(scheme)\n\tstatusStore := *rest.Store\n\tstatusStore.CreateStrategy = nil\n\tstatusStore.DeleteStrategy = nil\n\tstatusStore.UpdateStrategy = strategy\n\tstatusStore.ResetFieldsStrategy = strategy\n\treturn \u0026StatusREST{store: \u0026statusStore}\n}","line":{"from":127,"to":137}} {"id":100031273,"name":"New","signature":"func (r *StatusREST) New() runtime.Object","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/etcd/etcd.go","code":"// New creates a new APIService object.\nfunc (r *StatusREST) New() runtime.Object {\n\treturn \u0026apiregistration.APIService{}\n}","line":{"from":146,"to":149}} {"id":100031274,"name":"Destroy","signature":"func (r *StatusREST) Destroy()","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/etcd/etcd.go","code":"// Destroy cleans up resources on shutdown.\nfunc (r *StatusREST) Destroy() {\n\t// Given that underlying store is shared with REST,\n\t// we don't destroy it here explicitly.\n}","line":{"from":151,"to":155}} {"id":100031275,"name":"Get","signature":"func (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error)","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/etcd/etcd.go","code":"// Get retrieves the object from the storage. It is required to support Patch.\nfunc (r *StatusREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {\n\treturn r.store.Get(ctx, name, options)\n}","line":{"from":157,"to":160}} {"id":100031276,"name":"Update","signature":"func (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error)","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/etcd/etcd.go","code":"// Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {\n\t// We are explicitly setting forceAllowCreate to false in the call to the underlying storage because\n\t// subresources should never allow create on update.\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation, false, options)\n}","line":{"from":162,"to":167}} {"id":100031277,"name":"GetResetFields","signature":"func (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/etcd/etcd.go","code":"// GetResetFields implements rest.ResetFieldsStrategy\nfunc (r *StatusREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\treturn r.store.GetResetFields()\n}","line":{"from":169,"to":172}} {"id":100031278,"name":"NewRESTStorage","signature":"func NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter, shouldServeBeta bool) genericapiserver.APIGroupInfo","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/rest/storage_apiservice.go","code":"// NewRESTStorage returns an APIGroupInfo object that will work against apiservice.\nfunc NewRESTStorage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter, shouldServeBeta bool) genericapiserver.APIGroupInfo {\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(apiregistration.GroupName, aggregatorscheme.Scheme, metav1.ParameterCodec, aggregatorscheme.Codecs)\n\n\tstorage := map[string]rest.Storage{}\n\n\tif resource := \"apiservices\"; apiResourceConfigSource.ResourceEnabled(v1.SchemeGroupVersion.WithResource(resource)) {\n\t\tapiServiceREST := apiservicestorage.NewREST(aggregatorscheme.Scheme, restOptionsGetter)\n\t\tstorage[resource] = apiServiceREST\n\t\tstorage[resource+\"/status\"] = apiservicestorage.NewStatusREST(aggregatorscheme.Scheme, apiServiceREST)\n\t}\n\n\tif len(storage) \u003e 0 {\n\t\tapiGroupInfo.VersionedResourcesStorageMap[\"v1\"] = storage\n\t}\n\n\treturn apiGroupInfo\n}","line":{"from":32,"to":49}} {"id":100031279,"name":"NewStrategy","signature":"func NewStrategy(typer runtime.ObjectTyper) rest.CreateUpdateResetFieldsStrategy","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/strategy.go","code":"// NewStrategy creates a new apiServerStrategy.\nfunc NewStrategy(typer runtime.ObjectTyper) rest.CreateUpdateResetFieldsStrategy {\n\treturn apiServerStrategy{typer, names.SimpleNameGenerator}\n}","line":{"from":46,"to":49}} {"id":100031280,"name":"NamespaceScoped","signature":"func (apiServerStrategy) NamespaceScoped() bool","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/strategy.go","code":"func (apiServerStrategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":51,"to":53}} {"id":100031281,"name":"GetResetFields","signature":"func (apiServerStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/strategy.go","code":"func (apiServerStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"apiregistration.k8s.io/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t\t\"apiregistration.k8s.io/v1beta1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"status\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":55,"to":66}} {"id":100031282,"name":"PrepareForCreate","signature":"func (apiServerStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object)","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/strategy.go","code":"func (apiServerStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\tapiservice := obj.(*apiregistration.APIService)\n\tapiservice.Status = apiregistration.APIServiceStatus{}\n\n\t// mark local API services as immediately available on create\n\tif apiservice.Spec.Service == nil {\n\t\tapiregistration.SetAPIServiceCondition(apiservice, apiregistration.NewLocalAvailableAPIServiceCondition())\n\t}\n}","line":{"from":68,"to":76}} {"id":100031283,"name":"PrepareForUpdate","signature":"func (apiServerStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/strategy.go","code":"func (apiServerStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewAPIService := obj.(*apiregistration.APIService)\n\toldAPIService := old.(*apiregistration.APIService)\n\tnewAPIService.Status = oldAPIService.Status\n}","line":{"from":78,"to":82}} {"id":100031284,"name":"Validate","signature":"func (apiServerStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/strategy.go","code":"func (apiServerStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\treturn validation.ValidateAPIService(obj.(*apiregistration.APIService))\n}","line":{"from":84,"to":86}} {"id":100031285,"name":"WarningsOnCreate","signature":"func (apiServerStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/strategy.go","code":"// WarningsOnCreate returns warnings for the creation of the given object.\nfunc (apiServerStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string {\n\treturn nil\n}","line":{"from":88,"to":91}} {"id":100031286,"name":"AllowCreateOnUpdate","signature":"func (apiServerStrategy) AllowCreateOnUpdate() bool","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/strategy.go","code":"func (apiServerStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":93,"to":95}} {"id":100031287,"name":"AllowUnconditionalUpdate","signature":"func (apiServerStrategy) AllowUnconditionalUpdate() bool","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/strategy.go","code":"func (apiServerStrategy) AllowUnconditionalUpdate() bool {\n\treturn false\n}","line":{"from":97,"to":99}} {"id":100031288,"name":"Canonicalize","signature":"func (apiServerStrategy) Canonicalize(obj runtime.Object)","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/strategy.go","code":"func (apiServerStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":101,"to":102}} {"id":100031289,"name":"ValidateUpdate","signature":"func (apiServerStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/strategy.go","code":"func (apiServerStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateAPIServiceUpdate(obj.(*apiregistration.APIService), old.(*apiregistration.APIService))\n}","line":{"from":104,"to":106}} {"id":100031290,"name":"WarningsOnUpdate","signature":"func (apiServerStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (apiServerStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":108,"to":111}} {"id":100031291,"name":"NewStatusStrategy","signature":"func NewStatusStrategy(typer runtime.ObjectTyper) rest.UpdateResetFieldsStrategy","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/strategy.go","code":"// NewStatusStrategy creates a new apiServerStatusStrategy.\nfunc NewStatusStrategy(typer runtime.ObjectTyper) rest.UpdateResetFieldsStrategy {\n\treturn apiServerStatusStrategy{typer, names.SimpleNameGenerator}\n}","line":{"from":118,"to":121}} {"id":100031292,"name":"NamespaceScoped","signature":"func (apiServerStatusStrategy) NamespaceScoped() bool","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/strategy.go","code":"func (apiServerStatusStrategy) NamespaceScoped() bool {\n\treturn false\n}","line":{"from":123,"to":125}} {"id":100031293,"name":"GetResetFields","signature":"func (apiServerStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/strategy.go","code":"func (apiServerStatusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {\n\tfields := map[fieldpath.APIVersion]*fieldpath.Set{\n\t\t\"apiregistration.k8s.io/v1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t\tfieldpath.MakePathOrDie(\"metadata\"),\n\t\t),\n\t\t\"apiregistration.k8s.io/v1beta1\": fieldpath.NewSet(\n\t\t\tfieldpath.MakePathOrDie(\"spec\"),\n\t\t\tfieldpath.MakePathOrDie(\"metadata\"),\n\t\t),\n\t}\n\n\treturn fields\n}","line":{"from":127,"to":140}} {"id":100031294,"name":"PrepareForUpdate","signature":"func (apiServerStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object)","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/strategy.go","code":"func (apiServerStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewAPIService := obj.(*apiregistration.APIService)\n\toldAPIService := old.(*apiregistration.APIService)\n\tnewAPIService.Spec = oldAPIService.Spec\n\tnewAPIService.Labels = oldAPIService.Labels\n\tnewAPIService.Annotations = oldAPIService.Annotations\n\tnewAPIService.Finalizers = oldAPIService.Finalizers\n\tnewAPIService.OwnerReferences = oldAPIService.OwnerReferences\n}","line":{"from":142,"to":150}} {"id":100031295,"name":"AllowCreateOnUpdate","signature":"func (apiServerStatusStrategy) AllowCreateOnUpdate() bool","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/strategy.go","code":"func (apiServerStatusStrategy) AllowCreateOnUpdate() bool {\n\treturn false\n}","line":{"from":152,"to":154}} {"id":100031296,"name":"AllowUnconditionalUpdate","signature":"func (apiServerStatusStrategy) AllowUnconditionalUpdate() bool","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/strategy.go","code":"func (apiServerStatusStrategy) AllowUnconditionalUpdate() bool {\n\treturn false\n}","line":{"from":156,"to":158}} {"id":100031297,"name":"Canonicalize","signature":"func (apiServerStatusStrategy) Canonicalize(obj runtime.Object)","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/strategy.go","code":"// Canonicalize normalizes the object after validation.\nfunc (apiServerStatusStrategy) Canonicalize(obj runtime.Object) {\n}","line":{"from":160,"to":162}} {"id":100031298,"name":"ValidateUpdate","signature":"func (apiServerStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/strategy.go","code":"// ValidateUpdate validates an update of apiServerStatusStrategy.\nfunc (apiServerStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\treturn validation.ValidateAPIServiceStatusUpdate(obj.(*apiregistration.APIService), old.(*apiregistration.APIService))\n}","line":{"from":164,"to":167}} {"id":100031299,"name":"WarningsOnUpdate","signature":"func (apiServerStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/strategy.go","code":"// WarningsOnUpdate returns warnings for the given update.\nfunc (apiServerStatusStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string {\n\treturn nil\n}","line":{"from":169,"to":172}} {"id":100031300,"name":"GetAttrs","signature":"func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error)","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/strategy.go","code":"// GetAttrs returns the labels and fields of an API server for filtering purposes.\nfunc GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {\n\tapiserver, ok := obj.(*apiregistration.APIService)\n\tif !ok {\n\t\treturn nil, nil, fmt.Errorf(\"given object is not a APIService\")\n\t}\n\treturn labels.Set(apiserver.ObjectMeta.Labels), ToSelectableFields(apiserver), nil\n}","line":{"from":174,"to":181}} {"id":100031301,"name":"MatchAPIService","signature":"func MatchAPIService(label labels.Selector, field fields.Selector) storage.SelectionPredicate","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/strategy.go","code":"// MatchAPIService is the filter used by the generic etcd backend to watch events\n// from etcd to clients of the apiserver only interested in specific labels/fields.\nfunc MatchAPIService(label labels.Selector, field fields.Selector) storage.SelectionPredicate {\n\treturn storage.SelectionPredicate{\n\t\tLabel: label,\n\t\tField: field,\n\t\tGetAttrs: GetAttrs,\n\t}\n}","line":{"from":183,"to":191}} {"id":100031302,"name":"ToSelectableFields","signature":"func ToSelectableFields(obj *apiregistration.APIService) fields.Set","file":"staging/src/k8s.io/kube-aggregator/pkg/registry/apiservice/strategy.go","code":"// ToSelectableFields returns a field set that represents the object.\nfunc ToSelectableFields(obj *apiregistration.APIService) fields.Set {\n\treturn generic.ObjectMetaFieldsSet(\u0026obj.ObjectMeta, true)\n}","line":{"from":193,"to":196}} {"id":100031303,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/kube-controller-manager/config/v1alpha1/register.go","code":"// addKnownTypes registers known types to the given scheme\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026KubeControllerManagerConfiguration{},\n\t)\n\treturn nil\n}","line":{"from":37,"to":43}} {"id":100031304,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/kube-proxy/config/v1alpha1/register.go","code":"// addKnownTypes registers known types to the given scheme\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026KubeProxyConfiguration{},\n\t)\n\treturn nil\n}","line":{"from":37,"to":43}} {"id":100031305,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/kube-scheduler/config/v1/register.go","code":"// addKnownTypes registers known types to the given scheme\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026KubeSchedulerConfiguration{},\n\t\t\u0026DefaultPreemptionArgs{},\n\t\t\u0026InterPodAffinityArgs{},\n\t\t\u0026NodeResourcesBalancedAllocationArgs{},\n\t\t\u0026NodeResourcesFitArgs{},\n\t\t\u0026PodTopologySpreadArgs{},\n\t\t\u0026VolumeBindingArgs{},\n\t\t\u0026NodeAffinityArgs{},\n\t)\n\treturn nil\n}","line":{"from":37,"to":50}} {"id":100031306,"name":"DecodeNestedObjects","signature":"func (c *KubeSchedulerConfiguration) DecodeNestedObjects(d runtime.Decoder) error","file":"staging/src/k8s.io/kube-scheduler/config/v1/types.go","code":"// DecodeNestedObjects decodes plugin args for known types.\nfunc (c *KubeSchedulerConfiguration) DecodeNestedObjects(d runtime.Decoder) error {\n\tvar strictDecodingErrs []error\n\tfor i := range c.Profiles {\n\t\tprof := \u0026c.Profiles[i]\n\t\tfor j := range prof.PluginConfig {\n\t\t\terr := prof.PluginConfig[j].decodeNestedObjects(d)\n\t\t\tif err != nil {\n\t\t\t\tdecodingErr := fmt.Errorf(\"decoding .profiles[%d].pluginConfig[%d]: %w\", i, j, err)\n\t\t\t\tif runtime.IsStrictDecodingError(err) {\n\t\t\t\t\tstrictDecodingErrs = append(strictDecodingErrs, decodingErr)\n\t\t\t\t} else {\n\t\t\t\t\treturn decodingErr\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif len(strictDecodingErrs) \u003e 0 {\n\t\treturn runtime.NewStrictDecodingError(strictDecodingErrs)\n\t}\n\treturn nil\n}","line":{"from":94,"to":115}} {"id":100031307,"name":"EncodeNestedObjects","signature":"func (c *KubeSchedulerConfiguration) EncodeNestedObjects(e runtime.Encoder) error","file":"staging/src/k8s.io/kube-scheduler/config/v1/types.go","code":"// EncodeNestedObjects encodes plugin args.\nfunc (c *KubeSchedulerConfiguration) EncodeNestedObjects(e runtime.Encoder) error {\n\tfor i := range c.Profiles {\n\t\tprof := \u0026c.Profiles[i]\n\t\tfor j := range prof.PluginConfig {\n\t\t\terr := prof.PluginConfig[j].encodeNestedObjects(e)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"encoding .profiles[%d].pluginConfig[%d]: %w\", i, j, err)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":117,"to":129}} {"id":100031308,"name":"decodeNestedObjects","signature":"func (c *PluginConfig) decodeNestedObjects(d runtime.Decoder) error","file":"staging/src/k8s.io/kube-scheduler/config/v1/types.go","code":"func (c *PluginConfig) decodeNestedObjects(d runtime.Decoder) error {\n\tgvk := SchemeGroupVersion.WithKind(c.Name + \"Args\")\n\t// dry-run to detect and skip out-of-tree plugin args.\n\tif _, _, err := d.Decode(nil, \u0026gvk, nil); runtime.IsNotRegisteredError(err) {\n\t\treturn nil\n\t}\n\n\tvar strictDecodingErr error\n\tobj, parsedGvk, err := d.Decode(c.Args.Raw, \u0026gvk, nil)\n\tif err != nil {\n\t\tdecodingArgsErr := fmt.Errorf(\"decoding args for plugin %s: %w\", c.Name, err)\n\t\tif obj != nil \u0026\u0026 runtime.IsStrictDecodingError(err) {\n\t\t\tstrictDecodingErr = runtime.NewStrictDecodingError([]error{decodingArgsErr})\n\t\t} else {\n\t\t\treturn decodingArgsErr\n\t\t}\n\t}\n\tif parsedGvk.GroupKind() != gvk.GroupKind() {\n\t\treturn fmt.Errorf(\"args for plugin %s were not of type %s, got %s\", c.Name, gvk.GroupKind(), parsedGvk.GroupKind())\n\t}\n\tc.Args.Object = obj\n\treturn strictDecodingErr\n}","line":{"from":264,"to":286}} {"id":100031309,"name":"encodeNestedObjects","signature":"func (c *PluginConfig) encodeNestedObjects(e runtime.Encoder) error","file":"staging/src/k8s.io/kube-scheduler/config/v1/types.go","code":"func (c *PluginConfig) encodeNestedObjects(e runtime.Encoder) error {\n\tif c.Args.Object == nil {\n\t\treturn nil\n\t}\n\tvar buf bytes.Buffer\n\terr := e.Encode(c.Args.Object, \u0026buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// The \u003ce\u003e encoder might be a YAML encoder, but the parent encoder expects\n\t// JSON output, so we convert YAML back to JSON.\n\t// This is a no-op if \u003ce\u003e produces JSON.\n\tjson, err := yaml.YAMLToJSON(buf.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.Args.Raw = json\n\treturn nil\n}","line":{"from":288,"to":306}} {"id":100031310,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/kube-scheduler/config/v1beta2/register.go","code":"// addKnownTypes registers known types to the given scheme\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026KubeSchedulerConfiguration{},\n\t\t\u0026DefaultPreemptionArgs{},\n\t\t\u0026InterPodAffinityArgs{},\n\t\t\u0026NodeResourcesBalancedAllocationArgs{},\n\t\t\u0026NodeResourcesFitArgs{},\n\t\t\u0026PodTopologySpreadArgs{},\n\t\t\u0026VolumeBindingArgs{},\n\t\t\u0026NodeAffinityArgs{},\n\t)\n\treturn nil\n}","line":{"from":37,"to":50}} {"id":100031311,"name":"DecodeNestedObjects","signature":"func (c *KubeSchedulerConfiguration) DecodeNestedObjects(d runtime.Decoder) error","file":"staging/src/k8s.io/kube-scheduler/config/v1beta2/types.go","code":"// DecodeNestedObjects decodes plugin args for known types.\nfunc (c *KubeSchedulerConfiguration) DecodeNestedObjects(d runtime.Decoder) error {\n\tvar strictDecodingErrs []error\n\tfor i := range c.Profiles {\n\t\tprof := \u0026c.Profiles[i]\n\t\tfor j := range prof.PluginConfig {\n\t\t\terr := prof.PluginConfig[j].decodeNestedObjects(d)\n\t\t\tif err != nil {\n\t\t\t\tdecodingErr := fmt.Errorf(\"decoding .profiles[%d].pluginConfig[%d]: %w\", i, j, err)\n\t\t\t\tif runtime.IsStrictDecodingError(err) {\n\t\t\t\t\tstrictDecodingErrs = append(strictDecodingErrs, decodingErr)\n\t\t\t\t} else {\n\t\t\t\t\treturn decodingErr\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif len(strictDecodingErrs) \u003e 0 {\n\t\treturn runtime.NewStrictDecodingError(strictDecodingErrs)\n\t}\n\treturn nil\n}","line":{"from":101,"to":122}} {"id":100031312,"name":"EncodeNestedObjects","signature":"func (c *KubeSchedulerConfiguration) EncodeNestedObjects(e runtime.Encoder) error","file":"staging/src/k8s.io/kube-scheduler/config/v1beta2/types.go","code":"// EncodeNestedObjects encodes plugin args.\nfunc (c *KubeSchedulerConfiguration) EncodeNestedObjects(e runtime.Encoder) error {\n\tfor i := range c.Profiles {\n\t\tprof := \u0026c.Profiles[i]\n\t\tfor j := range prof.PluginConfig {\n\t\t\terr := prof.PluginConfig[j].encodeNestedObjects(e)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"encoding .profiles[%d].pluginConfig[%d]: %w\", i, j, err)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":124,"to":136}} {"id":100031313,"name":"decodeNestedObjects","signature":"func (c *PluginConfig) decodeNestedObjects(d runtime.Decoder) error","file":"staging/src/k8s.io/kube-scheduler/config/v1beta2/types.go","code":"func (c *PluginConfig) decodeNestedObjects(d runtime.Decoder) error {\n\tgvk := SchemeGroupVersion.WithKind(c.Name + \"Args\")\n\t// dry-run to detect and skip out-of-tree plugin args.\n\tif _, _, err := d.Decode(nil, \u0026gvk, nil); runtime.IsNotRegisteredError(err) {\n\t\treturn nil\n\t}\n\n\tvar strictDecodingErr error\n\tobj, parsedGvk, err := d.Decode(c.Args.Raw, \u0026gvk, nil)\n\tif err != nil {\n\t\tdecodingArgsErr := fmt.Errorf(\"decoding args for plugin %s: %w\", c.Name, err)\n\t\tif obj != nil \u0026\u0026 runtime.IsStrictDecodingError(err) {\n\t\t\tstrictDecodingErr = runtime.NewStrictDecodingError([]error{decodingArgsErr})\n\t\t} else {\n\t\t\treturn decodingArgsErr\n\t\t}\n\t}\n\tif parsedGvk.GroupKind() != gvk.GroupKind() {\n\t\treturn fmt.Errorf(\"args for plugin %s were not of type %s, got %s\", c.Name, gvk.GroupKind(), parsedGvk.GroupKind())\n\t}\n\tc.Args.Object = obj\n\treturn strictDecodingErr\n}","line":{"from":245,"to":267}} {"id":100031314,"name":"encodeNestedObjects","signature":"func (c *PluginConfig) encodeNestedObjects(e runtime.Encoder) error","file":"staging/src/k8s.io/kube-scheduler/config/v1beta2/types.go","code":"func (c *PluginConfig) encodeNestedObjects(e runtime.Encoder) error {\n\tif c.Args.Object == nil {\n\t\treturn nil\n\t}\n\tvar buf bytes.Buffer\n\terr := e.Encode(c.Args.Object, \u0026buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// The \u003ce\u003e encoder might be a YAML encoder, but the parent encoder expects\n\t// JSON output, so we convert YAML back to JSON.\n\t// This is a no-op if \u003ce\u003e produces JSON.\n\tjson, err := yaml.YAMLToJSON(buf.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.Args.Raw = json\n\treturn nil\n}","line":{"from":269,"to":287}} {"id":100031315,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/kube-scheduler/config/v1beta3/register.go","code":"// addKnownTypes registers known types to the given scheme\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026KubeSchedulerConfiguration{},\n\t\t\u0026DefaultPreemptionArgs{},\n\t\t\u0026InterPodAffinityArgs{},\n\t\t\u0026NodeResourcesBalancedAllocationArgs{},\n\t\t\u0026NodeResourcesFitArgs{},\n\t\t\u0026PodTopologySpreadArgs{},\n\t\t\u0026VolumeBindingArgs{},\n\t\t\u0026NodeAffinityArgs{},\n\t)\n\treturn nil\n}","line":{"from":37,"to":50}} {"id":100031316,"name":"DecodeNestedObjects","signature":"func (c *KubeSchedulerConfiguration) DecodeNestedObjects(d runtime.Decoder) error","file":"staging/src/k8s.io/kube-scheduler/config/v1beta3/types.go","code":"// DecodeNestedObjects decodes plugin args for known types.\nfunc (c *KubeSchedulerConfiguration) DecodeNestedObjects(d runtime.Decoder) error {\n\tvar strictDecodingErrs []error\n\tfor i := range c.Profiles {\n\t\tprof := \u0026c.Profiles[i]\n\t\tfor j := range prof.PluginConfig {\n\t\t\terr := prof.PluginConfig[j].decodeNestedObjects(d)\n\t\t\tif err != nil {\n\t\t\t\tdecodingErr := fmt.Errorf(\"decoding .profiles[%d].pluginConfig[%d]: %w\", i, j, err)\n\t\t\t\tif runtime.IsStrictDecodingError(err) {\n\t\t\t\t\tstrictDecodingErrs = append(strictDecodingErrs, decodingErr)\n\t\t\t\t} else {\n\t\t\t\t\treturn decodingErr\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif len(strictDecodingErrs) \u003e 0 {\n\t\treturn runtime.NewStrictDecodingError(strictDecodingErrs)\n\t}\n\treturn nil\n}","line":{"from":94,"to":115}} {"id":100031317,"name":"EncodeNestedObjects","signature":"func (c *KubeSchedulerConfiguration) EncodeNestedObjects(e runtime.Encoder) error","file":"staging/src/k8s.io/kube-scheduler/config/v1beta3/types.go","code":"// EncodeNestedObjects encodes plugin args.\nfunc (c *KubeSchedulerConfiguration) EncodeNestedObjects(e runtime.Encoder) error {\n\tfor i := range c.Profiles {\n\t\tprof := \u0026c.Profiles[i]\n\t\tfor j := range prof.PluginConfig {\n\t\t\terr := prof.PluginConfig[j].encodeNestedObjects(e)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"encoding .profiles[%d].pluginConfig[%d]: %w\", i, j, err)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":117,"to":129}} {"id":100031318,"name":"decodeNestedObjects","signature":"func (c *PluginConfig) decodeNestedObjects(d runtime.Decoder) error","file":"staging/src/k8s.io/kube-scheduler/config/v1beta3/types.go","code":"func (c *PluginConfig) decodeNestedObjects(d runtime.Decoder) error {\n\tgvk := SchemeGroupVersion.WithKind(c.Name + \"Args\")\n\t// dry-run to detect and skip out-of-tree plugin args.\n\tif _, _, err := d.Decode(nil, \u0026gvk, nil); runtime.IsNotRegisteredError(err) {\n\t\treturn nil\n\t}\n\n\tvar strictDecodingErr error\n\tobj, parsedGvk, err := d.Decode(c.Args.Raw, \u0026gvk, nil)\n\tif err != nil {\n\t\tdecodingArgsErr := fmt.Errorf(\"decoding args for plugin %s: %w\", c.Name, err)\n\t\tif obj != nil \u0026\u0026 runtime.IsStrictDecodingError(err) {\n\t\t\tstrictDecodingErr = runtime.NewStrictDecodingError([]error{decodingArgsErr})\n\t\t} else {\n\t\t\treturn decodingArgsErr\n\t\t}\n\t}\n\tif parsedGvk.GroupKind() != gvk.GroupKind() {\n\t\treturn fmt.Errorf(\"args for plugin %s were not of type %s, got %s\", c.Name, gvk.GroupKind(), parsedGvk.GroupKind())\n\t}\n\tc.Args.Object = obj\n\treturn strictDecodingErr\n}","line":{"from":253,"to":275}} {"id":100031319,"name":"encodeNestedObjects","signature":"func (c *PluginConfig) encodeNestedObjects(e runtime.Encoder) error","file":"staging/src/k8s.io/kube-scheduler/config/v1beta3/types.go","code":"func (c *PluginConfig) encodeNestedObjects(e runtime.Encoder) error {\n\tif c.Args.Object == nil {\n\t\treturn nil\n\t}\n\tvar buf bytes.Buffer\n\terr := e.Encode(c.Args.Object, \u0026buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// The \u003ce\u003e encoder might be a YAML encoder, but the parent encoder expects\n\t// JSON output, so we convert YAML back to JSON.\n\t// This is a no-op if \u003ce\u003e produces JSON.\n\tjson, err := yaml.YAMLToJSON(buf.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.Args.Raw = json\n\treturn nil\n}","line":{"from":277,"to":295}} {"id":100031320,"name":"Accept","signature":"func (elem GroupKindElement) Accept(visitor KindVisitor) error","file":"staging/src/k8s.io/kubectl/pkg/apps/kind_visitor.go","code":"// Accept calls the Visit method on visitor that corresponds to elem's Kind\nfunc (elem GroupKindElement) Accept(visitor KindVisitor) error {\n\tswitch {\n\tcase elem.GroupMatch(\"apps\", \"extensions\") \u0026\u0026 elem.Kind == \"DaemonSet\":\n\t\tvisitor.VisitDaemonSet(elem)\n\tcase elem.GroupMatch(\"apps\", \"extensions\") \u0026\u0026 elem.Kind == \"Deployment\":\n\t\tvisitor.VisitDeployment(elem)\n\tcase elem.GroupMatch(\"batch\") \u0026\u0026 elem.Kind == \"Job\":\n\t\tvisitor.VisitJob(elem)\n\tcase elem.GroupMatch(\"\", \"core\") \u0026\u0026 elem.Kind == \"Pod\":\n\t\tvisitor.VisitPod(elem)\n\tcase elem.GroupMatch(\"apps\", \"extensions\") \u0026\u0026 elem.Kind == \"ReplicaSet\":\n\t\tvisitor.VisitReplicaSet(elem)\n\tcase elem.GroupMatch(\"\", \"core\") \u0026\u0026 elem.Kind == \"ReplicationController\":\n\t\tvisitor.VisitReplicationController(elem)\n\tcase elem.GroupMatch(\"apps\") \u0026\u0026 elem.Kind == \"StatefulSet\":\n\t\tvisitor.VisitStatefulSet(elem)\n\tcase elem.GroupMatch(\"batch\") \u0026\u0026 elem.Kind == \"CronJob\":\n\t\tvisitor.VisitCronJob(elem)\n\tdefault:\n\t\treturn fmt.Errorf(\"no visitor method exists for %v\", elem)\n\t}\n\treturn nil\n}","line":{"from":41,"to":64}} {"id":100031321,"name":"GroupMatch","signature":"func (elem GroupKindElement) GroupMatch(groups ...string) bool","file":"staging/src/k8s.io/kubectl/pkg/apps/kind_visitor.go","code":"// GroupMatch returns true if and only if elem's group matches one\n// of the group arguments\nfunc (elem GroupKindElement) GroupMatch(groups ...string) bool {\n\tfor _, g := range groups {\n\t\tif elem.Group == g {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":66,"to":75}} {"id":100031322,"name":"NewCmdAlpha","signature":"func NewCmdAlpha(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/alpha.go","code":"// NewCmdAlpha creates a command that acts as an alternate root command for features in alpha\nfunc NewCmdAlpha(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"alpha\",\n\t\tShort: i18n.T(\"Commands for features in alpha\"),\n\t\tLong: templates.LongDesc(i18n.T(\"These commands correspond to alpha features that are not enabled in Kubernetes clusters by default.\")),\n\t}\n\n\t// NewKubeletCommand() will hide the alpha command if it has no subcommands. Overriding\n\t// the help function ensures a reasonable message if someone types the hidden command anyway.\n\tif !cmd.HasAvailableSubCommands() {\n\t\tcmd.SetHelpFunc(func(*cobra.Command, []string) {\n\t\t\tcmd.Println(i18n.T(\"No alpha commands are available in this version of kubectl\"))\n\t\t})\n\t}\n\n\treturn cmd\n}","line":{"from":28,"to":45}} {"id":100031323,"name":"NewAnnotateFlags","signature":"func NewAnnotateFlags(streams genericclioptions.IOStreams) *AnnotateFlags","file":"staging/src/k8s.io/kubectl/pkg/cmd/annotate/annotate.go","code":"// NewAnnotateFlags returns a default AnnotateFlags\nfunc NewAnnotateFlags(streams genericclioptions.IOStreams) *AnnotateFlags {\n\treturn \u0026AnnotateFlags{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"annotate\").WithTypeSetter(scheme.Scheme),\n\t\tRecordFlags: genericclioptions.NewRecordFlags(),\n\t\tIOStreams: streams,\n\t}\n}","line":{"from":69,"to":76}} {"id":100031324,"name":"NewCmdAnnotate","signature":"func NewCmdAnnotate(parent string, f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/annotate/annotate.go","code":"// NewCmdAnnotate creates the `annotate` command\nfunc NewCmdAnnotate(parent string, f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\tflags := NewAnnotateFlags(streams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"annotate [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Update the annotations on a resource\"),\n\t\tLong: annotateLong + \"\\n\\n\" + cmdutil.SuggestAPIResources(parent),\n\t\tExample: annotateExample,\n\t\tValidArgsFunction: completion.ResourceTypeAndNameCompletionFunc(f),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\to, err := flags.ToOptions(f, cmd, args)\n\t\t\tcmdutil.CheckErr(err)\n\t\t\tcmdutil.CheckErr(o.RunAnnotate())\n\t\t},\n\t}\n\n\tflags.AddFlags(cmd, streams)\n\n\treturn cmd\n}","line":{"from":145,"to":166}} {"id":100031325,"name":"AddFlags","signature":"func (flags *AnnotateFlags) AddFlags(cmd *cobra.Command, ioStreams genericclioptions.IOStreams)","file":"staging/src/k8s.io/kubectl/pkg/cmd/annotate/annotate.go","code":"// AddFlags registers flags for a cli.\nfunc (flags *AnnotateFlags) AddFlags(cmd *cobra.Command, ioStreams genericclioptions.IOStreams) {\n\tflags.PrintFlags.AddFlags(cmd)\n\tflags.RecordFlags.AddFlags(cmd)\n\n\tcmdutil.AddDryRunFlag(cmd)\n\n\tusage := \"identifying the resource to update the annotation\"\n\tcmdutil.AddFilenameOptionFlags(cmd, \u0026flags.FilenameOptions, usage)\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026flags.FieldManager, \"kubectl-annotate\")\n\tcmdutil.AddLabelSelectorFlagVar(cmd, \u0026flags.Selector)\n\n\tcmd.Flags().BoolVar(\u0026flags.overwrite, \"overwrite\", flags.overwrite, \"If true, allow annotations to be overwritten, otherwise reject annotation updates that overwrite existing annotations.\")\n\tcmd.Flags().BoolVar(\u0026flags.List, \"list\", flags.List, \"If true, display the annotations for a given resource.\")\n\tcmd.Flags().BoolVar(\u0026flags.Local, \"local\", flags.Local, \"If true, annotation will NOT contact api-server but run locally.\")\n\tcmd.Flags().StringVar(\u0026flags.FieldSelector, \"field-selector\", flags.FieldSelector, \"Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector key1=value1,key2=value2). The server only supports a limited number of field queries per type.\")\n\tcmd.Flags().BoolVar(\u0026flags.All, \"all\", flags.All, \"Select all resources, in the namespace of the specified resource types.\")\n\tcmd.Flags().BoolVarP(\u0026flags.AllNamespaces, \"all-namespaces\", \"A\", flags.AllNamespaces, \"If true, check the specified action in all namespaces.\")\n\tcmd.Flags().StringVar(\u0026flags.resourceVersion, \"resource-version\", flags.resourceVersion, i18n.T(\"If non-empty, the annotation update will only succeed if this is the current resource-version for the object. Only valid when specifying a single resource.\"))\n}","line":{"from":168,"to":187}} {"id":100031326,"name":"ToOptions","signature":"func (flags *AnnotateFlags) ToOptions(f cmdutil.Factory, cmd *cobra.Command, args []string) (*AnnotateOptions, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/annotate/annotate.go","code":"// ToOptions converts from CLI inputs to runtime inputs.\nfunc (flags *AnnotateFlags) ToOptions(f cmdutil.Factory, cmd *cobra.Command, args []string) (*AnnotateOptions, error) {\n\toptions := \u0026AnnotateOptions{\n\t\tall: flags.All,\n\t\tallNamespaces: flags.AllNamespaces,\n\t\tFilenameOptions: flags.FilenameOptions,\n\t\tfieldSelector: flags.FieldSelector,\n\t\tfieldManager: flags.FieldManager,\n\t\tIOStreams: flags.IOStreams,\n\t\tlocal: flags.Local,\n\t\tlist: flags.List,\n\t\toverwrite: flags.overwrite,\n\t\tresourceVersion: flags.resourceVersion,\n\t\tRecorder: genericclioptions.NoopRecorder{},\n\t\tselector: flags.Selector,\n\t}\n\n\tvar err error\n\n\tflags.RecordFlags.Complete(cmd)\n\toptions.Recorder, err = flags.RecordFlags.ToRecorder()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\toptions.dryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcmdutil.PrintFlagsWithDryRunStrategy(flags.PrintFlags, options.dryRunStrategy)\n\tprinter, err := flags.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\toptions.PrintObj = func(obj runtime.Object, out io.Writer) error {\n\t\treturn printer.PrintObj(obj, out)\n\t}\n\n\toptions.namespace, options.enforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\toptions.builder = f.NewBuilder()\n\toptions.unstructuredClientForMapping = f.UnstructuredClientForMapping\n\n\t// retrieves resource and annotation args from args\n\t// also checks args to verify that all resources are specified before annotations\n\tresources, annotationArgs, err := cmdutil.GetResourcesAndPairs(args, \"annotation\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\toptions.resources = resources\n\toptions.newAnnotations, options.removeAnnotations, err = parseAnnotations(annotationArgs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Checks the options and flags to see if there is sufficient information run the command.\n\tif flags.List \u0026\u0026 len(flags.OutputFormat) \u003e 0 {\n\t\treturn nil, fmt.Errorf(\"--list and --output may not be specified together\")\n\t}\n\tif flags.All \u0026\u0026 len(flags.Selector) \u003e 0 {\n\t\treturn nil, fmt.Errorf(\"cannot set --all and --selector at the same time\")\n\t}\n\tif flags.All \u0026\u0026 len(flags.FieldSelector) \u003e 0 {\n\t\treturn nil, fmt.Errorf(\"cannot set --all and --field-selector at the same time\")\n\t}\n\n\tif !flags.Local {\n\t\tif len(options.resources) \u003c 1 \u0026\u0026 cmdutil.IsFilenameSliceEmpty(flags.Filenames, flags.Kustomize) {\n\t\t\treturn nil, fmt.Errorf(\"one or more resources must be specified as \u003cresource\u003e \u003cname\u003e or \u003cresource\u003e/\u003cname\u003e\")\n\t\t}\n\t} else {\n\t\tif options.dryRunStrategy == cmdutil.DryRunServer {\n\t\t\treturn nil, fmt.Errorf(\"cannot specify --local and --dry-run=server - did you mean --dry-run=client?\")\n\t\t}\n\t\tif len(options.resources) \u003e 0 {\n\t\t\treturn nil, fmt.Errorf(\"can only use local files by -f rsrc.yaml or --filename=rsrc.json when --local=true is set\")\n\t\t}\n\t\tif cmdutil.IsFilenameSliceEmpty(flags.Filenames, flags.Kustomize) {\n\t\t\treturn nil, fmt.Errorf(\"one or more files must be specified as -f rsrc.yaml or --filename=rsrc.json\")\n\t\t}\n\t}\n\tif len(options.newAnnotations) \u003c 1 \u0026\u0026 len(options.removeAnnotations) \u003c 1 \u0026\u0026 !flags.List {\n\t\treturn nil, fmt.Errorf(\"at least one annotation update is required\")\n\t}\n\terr = validateAnnotations(options.removeAnnotations, options.newAnnotations)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn options, nil\n}","line":{"from":189,"to":282}} {"id":100031327,"name":"RunAnnotate","signature":"func (o AnnotateOptions) RunAnnotate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/annotate/annotate.go","code":"// RunAnnotate does the work\nfunc (o AnnotateOptions) RunAnnotate() error {\n\tb := o.builder.\n\t\tUnstructured().\n\t\tLocalParam(o.local).\n\t\tContinueOnError().\n\t\tNamespaceParam(o.namespace).DefaultNamespace().\n\t\tFilenameParam(o.enforceNamespace, \u0026o.FilenameOptions).\n\t\tFlatten()\n\n\tif !o.local {\n\t\tb = b.LabelSelectorParam(o.selector).\n\t\t\tFieldSelectorParam(o.fieldSelector).\n\t\t\tAllNamespaces(o.allNamespaces).\n\t\t\tResourceTypeOrNameArgs(o.all, o.resources...).\n\t\t\tLatest()\n\t}\n\n\tr := b.Do()\n\tif err := r.Err(); err != nil {\n\t\treturn err\n\t}\n\n\tvar singleItemImpliedResource bool\n\tr.IntoSingleItemImplied(\u0026singleItemImpliedResource)\n\n\t// only apply resource version locking on a single resource.\n\t// we must perform this check after o.builder.Do() as\n\t// []o.resources can not accurately return the proper number\n\t// of resources when they are not passed in \"resource/name\" format.\n\tif !singleItemImpliedResource \u0026\u0026 len(o.resourceVersion) \u003e 0 {\n\t\treturn fmt.Errorf(\"--resource-version may only be used with a single resource\")\n\t}\n\n\treturn r.Visit(func(info *resource.Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar outputObj runtime.Object\n\t\tobj := info.Object\n\n\t\tif o.dryRunStrategy == cmdutil.DryRunClient || o.local || o.list {\n\t\t\tif err := o.updateAnnotations(obj); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\toutputObj = obj\n\t\t} else {\n\t\t\tmapping := info.ResourceMapping()\n\t\t\tname, namespace := info.Name, info.Namespace\n\n\t\t\tif len(o.resourceVersion) != 0 {\n\t\t\t\t// ensure resourceVersion is always sent in the patch by clearing it from the starting JSON\n\t\t\t\taccessor, err := meta.Accessor(obj)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\taccessor.SetResourceVersion(\"\")\n\t\t\t}\n\n\t\t\toldData, err := json.Marshal(obj)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := o.Recorder.Record(info.Object); err != nil {\n\t\t\t\tklog.V(4).Infof(\"error recording current command: %v\", err)\n\t\t\t}\n\t\t\tif err := o.updateAnnotations(obj); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tnewData, err := json.Marshal(obj)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tpatchBytes, err := jsonpatch.CreateMergePatch(oldData, newData)\n\t\t\tcreatedPatch := err == nil\n\t\t\tif err != nil {\n\t\t\t\tklog.V(2).Infof(\"couldn't compute patch: %v\", err)\n\t\t\t}\n\n\t\t\tclient, err := o.unstructuredClientForMapping(mapping)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thelper := resource.\n\t\t\t\tNewHelper(client, mapping).\n\t\t\t\tDryRun(o.dryRunStrategy == cmdutil.DryRunServer).\n\t\t\t\tWithFieldManager(o.fieldManager)\n\n\t\t\tif createdPatch {\n\t\t\t\toutputObj, err = helper.Patch(namespace, name, types.MergePatchType, patchBytes, nil)\n\t\t\t} else {\n\t\t\t\toutputObj, err = helper.Replace(namespace, name, false, obj)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tif o.list {\n\t\t\taccessor, err := meta.Accessor(outputObj)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tindent := \"\"\n\t\t\tif !singleItemImpliedResource {\n\t\t\t\tindent = \" \"\n\t\t\t\tgvks, _, err := unstructuredscheme.NewUnstructuredObjectTyper().ObjectKinds(info.Object)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfmt.Fprintf(o.Out, \"Listing annotations for %s.%s/%s:\\n\", gvks[0].Kind, gvks[0].Group, info.Name)\n\t\t\t}\n\t\t\tfor k, v := range accessor.GetAnnotations() {\n\t\t\t\tfmt.Fprintf(o.Out, \"%s%s=%s\\n\", indent, k, v)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\n\t\treturn o.PrintObj(outputObj, o.Out)\n\t})\n}","line":{"from":284,"to":407}} {"id":100031328,"name":"parseAnnotations","signature":"func parseAnnotations(annotationArgs []string) (map[string]string, []string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/annotate/annotate.go","code":"// parseAnnotations retrieves new and remove annotations from annotation args\nfunc parseAnnotations(annotationArgs []string) (map[string]string, []string, error) {\n\treturn cmdutil.ParsePairs(annotationArgs, \"annotation\", true)\n}","line":{"from":409,"to":412}} {"id":100031329,"name":"validateAnnotations","signature":"func validateAnnotations(removeAnnotations []string, newAnnotations map[string]string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/annotate/annotate.go","code":"// validateAnnotations checks the format of annotation args and checks removed annotations aren't in the new annotations map\nfunc validateAnnotations(removeAnnotations []string, newAnnotations map[string]string) error {\n\tvar modifyRemoveBuf bytes.Buffer\n\tfor _, removeAnnotation := range removeAnnotations {\n\t\tif _, found := newAnnotations[removeAnnotation]; found {\n\t\t\tif modifyRemoveBuf.Len() \u003e 0 {\n\t\t\t\tmodifyRemoveBuf.WriteString(\", \")\n\t\t\t}\n\t\t\tmodifyRemoveBuf.WriteString(fmt.Sprint(removeAnnotation))\n\t\t}\n\t}\n\tif modifyRemoveBuf.Len() \u003e 0 {\n\t\treturn fmt.Errorf(\"can not both modify and remove the following annotation(s) in the same command: %s\", modifyRemoveBuf.String())\n\t}\n\n\treturn nil\n}","line":{"from":414,"to":430}} {"id":100031330,"name":"validateNoAnnotationOverwrites","signature":"func validateNoAnnotationOverwrites(accessor metav1.Object, annotations map[string]string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/annotate/annotate.go","code":"// validateNoAnnotationOverwrites validates that when overwrite is false, to-be-updated annotations don't exist in the object annotation map (yet)\nfunc validateNoAnnotationOverwrites(accessor metav1.Object, annotations map[string]string) error {\n\tvar buf bytes.Buffer\n\tfor key, value := range annotations {\n\t\t// change-cause annotation can always be overwritten\n\t\tif key == polymorphichelpers.ChangeCauseAnnotation {\n\t\t\tcontinue\n\t\t}\n\t\tif currValue, found := accessor.GetAnnotations()[key]; found \u0026\u0026 currValue != value {\n\t\t\tif buf.Len() \u003e 0 {\n\t\t\t\tbuf.WriteString(\"; \")\n\t\t\t}\n\t\t\tbuf.WriteString(fmt.Sprintf(\"'%s' already has a value (%s)\", key, currValue))\n\t\t}\n\t}\n\tif buf.Len() \u003e 0 {\n\t\treturn fmt.Errorf(\"--overwrite is false but found the following declared annotation(s): %s\", buf.String())\n\t}\n\treturn nil\n}","line":{"from":432,"to":451}} {"id":100031331,"name":"updateAnnotations","signature":"func (o AnnotateOptions) updateAnnotations(obj runtime.Object) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/annotate/annotate.go","code":"// updateAnnotations updates annotations of obj\nfunc (o AnnotateOptions) updateAnnotations(obj runtime.Object) error {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !o.overwrite {\n\t\tif err := validateNoAnnotationOverwrites(accessor, o.newAnnotations); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tannotations := accessor.GetAnnotations()\n\tif annotations == nil {\n\t\tannotations = make(map[string]string)\n\t}\n\n\tfor key, value := range o.newAnnotations {\n\t\tannotations[key] = value\n\t}\n\tfor _, annotation := range o.removeAnnotations {\n\t\tdelete(annotations, annotation)\n\t}\n\taccessor.SetAnnotations(annotations)\n\n\tif len(o.resourceVersion) != 0 {\n\t\taccessor.SetResourceVersion(o.resourceVersion)\n\t}\n\treturn nil\n}","line":{"from":453,"to":482}} {"id":100031332,"name":"NewAPIResourceOptions","signature":"func NewAPIResourceOptions(ioStreams genericclioptions.IOStreams) *APIResourceOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/apiresources/apiresources.go","code":"// NewAPIResourceOptions creates the options for APIResource\nfunc NewAPIResourceOptions(ioStreams genericclioptions.IOStreams) *APIResourceOptions {\n\treturn \u0026APIResourceOptions{\n\t\tIOStreams: ioStreams,\n\t\tNamespaced: true,\n\t}\n}","line":{"from":87,"to":93}} {"id":100031333,"name":"NewCmdAPIResources","signature":"func NewCmdAPIResources(restClientGetter genericclioptions.RESTClientGetter, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/apiresources/apiresources.go","code":"// NewCmdAPIResources creates the `api-resources` command\nfunc NewCmdAPIResources(restClientGetter genericclioptions.RESTClientGetter, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewAPIResourceOptions(ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"api-resources\",\n\t\tShort: i18n.T(\"Print the supported API resources on the server\"),\n\t\tLong: i18n.T(\"Print the supported API resources on the server.\"),\n\t\tExample: apiresourcesExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(restClientGetter, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.RunAPIResources())\n\t\t},\n\t}\n\n\tcmd.Flags().BoolVar(\u0026o.NoHeaders, \"no-headers\", o.NoHeaders, \"When using the default or custom-column output format, don't print headers (default print headers).\")\n\tcmd.Flags().StringVarP(\u0026o.Output, \"output\", \"o\", o.Output, `Output format. One of: (wide, name).`)\n\n\tcmd.Flags().StringVar(\u0026o.APIGroup, \"api-group\", o.APIGroup, \"Limit to resources in the specified API group.\")\n\tcmd.Flags().BoolVar(\u0026o.Namespaced, \"namespaced\", o.Namespaced, \"If false, non-namespaced resources will be returned, otherwise returning namespaced resources by default.\")\n\tcmd.Flags().StringSliceVar(\u0026o.Verbs, \"verbs\", o.Verbs, \"Limit to resources that support the specified verbs.\")\n\tcmd.Flags().StringVar(\u0026o.SortBy, \"sort-by\", o.SortBy, \"If non-empty, sort list of resources using specified field. The field can be either 'name' or 'kind'.\")\n\tcmd.Flags().BoolVar(\u0026o.Cached, \"cached\", o.Cached, \"Use the cached list of resources if available.\")\n\tcmd.Flags().StringSliceVar(\u0026o.Categories, \"categories\", o.Categories, \"Limit to resources that belong the the specified categories.\")\n\treturn cmd\n}","line":{"from":95,"to":121}} {"id":100031334,"name":"Validate","signature":"func (o *APIResourceOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apiresources/apiresources.go","code":"// Validate checks to the APIResourceOptions to see if there is sufficient information run the command\nfunc (o *APIResourceOptions) Validate() error {\n\tsupportedOutputTypes := sets.NewString(\"\", \"wide\", \"name\")\n\tif !supportedOutputTypes.Has(o.Output) {\n\t\treturn fmt.Errorf(\"--output %v is not available\", o.Output)\n\t}\n\tsupportedSortTypes := sets.NewString(\"\", \"name\", \"kind\")\n\tif len(o.SortBy) \u003e 0 {\n\t\tif !supportedSortTypes.Has(o.SortBy) {\n\t\t\treturn fmt.Errorf(\"--sort-by accepts only name or kind\")\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":123,"to":136}} {"id":100031335,"name":"Complete","signature":"func (o *APIResourceOptions) Complete(restClientGetter genericclioptions.RESTClientGetter, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apiresources/apiresources.go","code":"// Complete adapts from the command line args and validates them\nfunc (o *APIResourceOptions) Complete(restClientGetter genericclioptions.RESTClientGetter, cmd *cobra.Command, args []string) error {\n\tif len(args) != 0 {\n\t\treturn cmdutil.UsageErrorf(cmd, \"unexpected arguments: %v\", args)\n\t}\n\n\tdiscoveryClient, err := restClientGetter.ToDiscoveryClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.discoveryClient = discoveryClient\n\n\to.groupChanged = cmd.Flags().Changed(\"api-group\")\n\to.nsChanged = cmd.Flags().Changed(\"namespaced\")\n\n\treturn nil\n}","line":{"from":138,"to":154}} {"id":100031336,"name":"RunAPIResources","signature":"func (o *APIResourceOptions) RunAPIResources() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apiresources/apiresources.go","code":"// RunAPIResources does the work\nfunc (o *APIResourceOptions) RunAPIResources() error {\n\tw := printers.GetNewTabWriter(o.Out)\n\tdefer w.Flush()\n\n\tif !o.Cached {\n\t\t// Always request fresh data from the server\n\t\to.discoveryClient.Invalidate()\n\t}\n\n\terrs := []error{}\n\tlists, err := o.discoveryClient.ServerPreferredResources()\n\tif err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\tresources := []groupResource{}\n\n\tfor _, list := range lists {\n\t\tif len(list.APIResources) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tgv, err := schema.ParseGroupVersion(list.GroupVersion)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, resource := range list.APIResources {\n\t\t\tif len(resource.Verbs) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// filter apiGroup\n\t\t\tif o.groupChanged \u0026\u0026 o.APIGroup != gv.Group {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// filter namespaced\n\t\t\tif o.nsChanged \u0026\u0026 o.Namespaced != resource.Namespaced {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// filter to resources that support the specified verbs\n\t\t\tif len(o.Verbs) \u003e 0 \u0026\u0026 !sets.NewString(resource.Verbs...).HasAll(o.Verbs...) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// filter to resources that belong to the specified categories\n\t\t\tif len(o.Categories) \u003e 0 \u0026\u0026 !sets.NewString(resource.Categories...).HasAll(o.Categories...) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tresources = append(resources, groupResource{\n\t\t\t\tAPIGroup: gv.Group,\n\t\t\t\tAPIGroupVersion: gv.String(),\n\t\t\t\tAPIResource: resource,\n\t\t\t})\n\t\t}\n\t}\n\n\tif o.NoHeaders == false \u0026\u0026 o.Output != \"name\" {\n\t\tif err = printContextHeaders(w, o.Output); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tsort.Stable(sortableResource{resources, o.SortBy})\n\tfor _, r := range resources {\n\t\tswitch o.Output {\n\t\tcase \"name\":\n\t\t\tname := r.APIResource.Name\n\t\t\tif len(r.APIGroup) \u003e 0 {\n\t\t\t\tname += \".\" + r.APIGroup\n\t\t\t}\n\t\t\tif _, err := fmt.Fprintf(w, \"%s\\n\", name); err != nil {\n\t\t\t\terrs = append(errs, err)\n\t\t\t}\n\t\tcase \"wide\":\n\t\t\tif _, err := fmt.Fprintf(w, \"%s\\t%s\\t%s\\t%v\\t%s\\t%v\\t%v\\n\",\n\t\t\t\tr.APIResource.Name,\n\t\t\t\tstrings.Join(r.APIResource.ShortNames, \",\"),\n\t\t\t\tr.APIGroupVersion,\n\t\t\t\tr.APIResource.Namespaced,\n\t\t\t\tr.APIResource.Kind,\n\t\t\t\tstrings.Join(r.APIResource.Verbs, \",\"),\n\t\t\t\tstrings.Join(r.APIResource.Categories, \",\")); err != nil {\n\t\t\t\terrs = append(errs, err)\n\t\t\t}\n\t\tcase \"\":\n\t\t\tif _, err := fmt.Fprintf(w, \"%s\\t%s\\t%s\\t%v\\t%s\\n\",\n\t\t\t\tr.APIResource.Name,\n\t\t\t\tstrings.Join(r.APIResource.ShortNames, \",\"),\n\t\t\t\tr.APIGroupVersion,\n\t\t\t\tr.APIResource.Namespaced,\n\t\t\t\tr.APIResource.Kind); err != nil {\n\t\t\t\terrs = append(errs, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(errs) \u003e 0 {\n\t\treturn errors.NewAggregate(errs)\n\t}\n\treturn nil\n}","line":{"from":156,"to":254}} {"id":100031337,"name":"printContextHeaders","signature":"func printContextHeaders(out io.Writer, output string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apiresources/apiresources.go","code":"func printContextHeaders(out io.Writer, output string) error {\n\tcolumnNames := []string{\"NAME\", \"SHORTNAMES\", \"APIVERSION\", \"NAMESPACED\", \"KIND\"}\n\tif output == \"wide\" {\n\t\tcolumnNames = append(columnNames, \"VERBS\", \"CATEGORIES\")\n\t}\n\t_, err := fmt.Fprintf(out, \"%s\\n\", strings.Join(columnNames, \"\\t\"))\n\treturn err\n}","line":{"from":256,"to":263}} {"id":100031338,"name":"Len","signature":"func (s sortableResource) Len() int { return len(s.resources) }","file":"staging/src/k8s.io/kubectl/pkg/cmd/apiresources/apiresources.go","code":"func (s sortableResource) Len() int { return len(s.resources) }","line":{"from":270,"to":270}} {"id":100031339,"name":"Swap","signature":"func (s sortableResource) Swap(i, j int)","file":"staging/src/k8s.io/kubectl/pkg/cmd/apiresources/apiresources.go","code":"func (s sortableResource) Swap(i, j int) {\n\ts.resources[i], s.resources[j] = s.resources[j], s.resources[i]\n}","line":{"from":271,"to":273}} {"id":100031340,"name":"Less","signature":"func (s sortableResource) Less(i, j int) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/apiresources/apiresources.go","code":"func (s sortableResource) Less(i, j int) bool {\n\tret := strings.Compare(s.compareValues(i, j))\n\tif ret \u003e 0 {\n\t\treturn false\n\t} else if ret == 0 {\n\t\treturn strings.Compare(s.resources[i].APIResource.Name, s.resources[j].APIResource.Name) \u003c 0\n\t}\n\treturn true\n}","line":{"from":274,"to":282}} {"id":100031341,"name":"compareValues","signature":"func (s sortableResource) compareValues(i, j int) (string, string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/apiresources/apiresources.go","code":"func (s sortableResource) compareValues(i, j int) (string, string) {\n\tswitch s.sortBy {\n\tcase \"name\":\n\t\treturn s.resources[i].APIResource.Name, s.resources[j].APIResource.Name\n\tcase \"kind\":\n\t\treturn s.resources[i].APIResource.Kind, s.resources[j].APIResource.Kind\n\t}\n\treturn s.resources[i].APIGroup, s.resources[j].APIGroup\n}","line":{"from":284,"to":292}} {"id":100031342,"name":"NewAPIVersionsOptions","signature":"func NewAPIVersionsOptions(ioStreams genericclioptions.IOStreams) *APIVersionsOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/apiresources/apiversions.go","code":"// NewAPIVersionsOptions creates the options for APIVersions\nfunc NewAPIVersionsOptions(ioStreams genericclioptions.IOStreams) *APIVersionsOptions {\n\treturn \u0026APIVersionsOptions{\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":46,"to":51}} {"id":100031343,"name":"NewCmdAPIVersions","signature":"func NewCmdAPIVersions(restClientGetter genericclioptions.RESTClientGetter, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/apiresources/apiversions.go","code":"// NewCmdAPIVersions creates the `api-versions` command\nfunc NewCmdAPIVersions(restClientGetter genericclioptions.RESTClientGetter, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewAPIVersionsOptions(ioStreams)\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"api-versions\",\n\t\tShort: i18n.T(\"Print the supported API versions on the server, in the form of \\\"group/version\\\"\"),\n\t\tLong: i18n.T(\"Print the supported API versions on the server, in the form of \\\"group/version\\\".\"),\n\t\tExample: apiversionsExample,\n\t\tDisableFlagsInUseLine: true,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(restClientGetter, cmd, args))\n\t\t\tcmdutil.CheckErr(o.RunAPIVersions())\n\t\t},\n\t}\n\treturn cmd\n}","line":{"from":53,"to":68}} {"id":100031344,"name":"Complete","signature":"func (o *APIVersionsOptions) Complete(restClientGetter genericclioptions.RESTClientGetter, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apiresources/apiversions.go","code":"// Complete adapts from the command line args and factory to the data required\nfunc (o *APIVersionsOptions) Complete(restClientGetter genericclioptions.RESTClientGetter, cmd *cobra.Command, args []string) error {\n\tif len(args) != 0 {\n\t\treturn cmdutil.UsageErrorf(cmd, \"unexpected arguments: %v\", args)\n\t}\n\tvar err error\n\to.discoveryClient, err = restClientGetter.ToDiscoveryClient()\n\treturn err\n}","line":{"from":70,"to":78}} {"id":100031345,"name":"RunAPIVersions","signature":"func (o *APIVersionsOptions) RunAPIVersions() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apiresources/apiversions.go","code":"// RunAPIVersions does the work\nfunc (o *APIVersionsOptions) RunAPIVersions() error {\n\t// Always request fresh data from the server\n\to.discoveryClient.Invalidate()\n\n\tgroupList, err := o.discoveryClient.ServerGroups()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't get available api versions from server: %v\", err)\n\t}\n\tapiVersions := metav1.ExtractGroupVersions(groupList)\n\tsort.Strings(apiVersions)\n\tfor _, v := range apiVersions {\n\t\tfmt.Fprintln(o.Out, v)\n\t}\n\treturn nil\n}","line":{"from":80,"to":95}} {"id":100031346,"name":"NewApplyFlags","signature":"func NewApplyFlags(streams genericclioptions.IOStreams) *ApplyFlags","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply.go","code":"// NewApplyFlags returns a default ApplyFlags\nfunc NewApplyFlags(streams genericclioptions.IOStreams) *ApplyFlags {\n\treturn \u0026ApplyFlags{\n\t\tRecordFlags: genericclioptions.NewRecordFlags(),\n\t\tDeleteFlags: delete.NewDeleteFlags(\"The files that contain the configurations to apply.\"),\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"created\").WithTypeSetter(scheme.Scheme),\n\n\t\tOverwrite: true,\n\t\tOpenAPIPatch: true,\n\n\t\tIOStreams: streams,\n\t}\n}","line":{"from":181,"to":193}} {"id":100031347,"name":"NewCmdApply","signature":"func NewCmdApply(baseName string, f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply.go","code":"// NewCmdApply creates the `apply` command\nfunc NewCmdApply(baseName string, f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\tflags := NewApplyFlags(ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"apply (-f FILENAME | -k DIRECTORY)\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Apply a configuration to a resource by file name or stdin\"),\n\t\tLong: applyLong,\n\t\tExample: applyExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\to, err := flags.ToOptions(f, cmd, baseName, args)\n\t\t\tcmdutil.CheckErr(err)\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\tflags.AddFlags(cmd)\n\n\t// apply subcommands\n\tcmd.AddCommand(NewCmdApplyViewLastApplied(f, flags.IOStreams))\n\tcmd.AddCommand(NewCmdApplySetLastApplied(f, flags.IOStreams))\n\tcmd.AddCommand(NewCmdApplyEditLastApplied(f, flags.IOStreams))\n\n\treturn cmd\n}","line":{"from":195,"to":221}} {"id":100031348,"name":"AddFlags","signature":"func (flags *ApplyFlags) AddFlags(cmd *cobra.Command)","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply.go","code":"// AddFlags registers flags for a cli\nfunc (flags *ApplyFlags) AddFlags(cmd *cobra.Command) {\n\t// bind flag structs\n\tflags.DeleteFlags.AddFlags(cmd)\n\tflags.RecordFlags.AddFlags(cmd)\n\tflags.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddValidateFlags(cmd)\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmdutil.AddServerSideApplyFlags(cmd)\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026flags.FieldManager, FieldManagerClientSideApply)\n\tcmdutil.AddLabelSelectorFlagVar(cmd, \u0026flags.Selector)\n\tcmdutil.AddPruningFlags(cmd, \u0026flags.Prune, \u0026flags.PruneAllowlist, \u0026flags.PruneWhitelist, \u0026flags.All, \u0026flags.ApplySetRef)\n\n\tcmd.Flags().BoolVar(\u0026flags.Overwrite, \"overwrite\", flags.Overwrite, \"Automatically resolve conflicts between the modified and live configuration by using values from the modified configuration\")\n\tcmd.Flags().BoolVar(\u0026flags.OpenAPIPatch, \"openapi-patch\", flags.OpenAPIPatch, \"If true, use openapi to calculate diff when the openapi presents and the resource can be found in the openapi spec. Otherwise, fall back to use baked-in types.\")\n}","line":{"from":223,"to":239}} {"id":100031349,"name":"ToOptions","signature":"func (flags *ApplyFlags) ToOptions(f cmdutil.Factory, cmd *cobra.Command, baseName string, args []string) (*ApplyOptions, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply.go","code":"// ToOptions converts from CLI inputs to runtime inputs\nfunc (flags *ApplyFlags) ToOptions(f cmdutil.Factory, cmd *cobra.Command, baseName string, args []string) (*ApplyOptions, error) {\n\tif len(args) != 0 {\n\t\treturn nil, cmdutil.UsageErrorf(cmd, \"Unexpected args: %v\", args)\n\t}\n\n\tserverSideApply := cmdutil.GetServerSideApplyFlag(cmd)\n\tforceConflicts := cmdutil.GetForceConflictsFlag(cmd)\n\tdryRunStrategy, err := cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdynamicClient, err := f.DynamicClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfieldManager := GetApplyFieldManagerFlag(cmd, serverSideApply)\n\n\t// allow for a success message operation to be specified at print time\n\ttoPrinter := func(operation string) (printers.ResourcePrinter, error) {\n\t\tflags.PrintFlags.NamePrintFlags.Operation = operation\n\t\tcmdutil.PrintFlagsWithDryRunStrategy(flags.PrintFlags, dryRunStrategy)\n\t\treturn flags.PrintFlags.ToPrinter()\n\t}\n\n\tflags.RecordFlags.Complete(cmd)\n\trecorder, err := flags.RecordFlags.ToRecorder()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdeleteOptions, err := flags.DeleteFlags.ToOptions(dynamicClient, flags.IOStreams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = deleteOptions.FilenameOptions.RequireFilenameOrKustomize()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\topenAPISchema, _ := f.OpenAPISchema()\n\n\tvalidationDirective, err := cmdutil.GetValidationDirective(cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvalidator, err := f.Validator(validationDirective)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbuilder := f.NewBuilder()\n\tmapper, err := f.ToRESTMapper()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnamespace, enforceNamespace, err := f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar applySet *ApplySet\n\tif flags.ApplySetRef != \"\" {\n\t\tparent, err := ParseApplySetParentRef(flags.ApplySetRef, mapper)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid parent reference %q: %w\", flags.ApplySetRef, err)\n\t\t}\n\t\t// ApplySet uses the namespace value from the flag, but not from the kubeconfig or defaults\n\t\t// This means the namespace flag is required when using a namespaced parent.\n\t\tif enforceNamespace \u0026\u0026 parent.IsNamespaced() {\n\t\t\tparent.Namespace = namespace\n\t\t}\n\t\ttooling := ApplySetTooling{Name: baseName, Version: ApplySetToolVersion}\n\t\trestClient, err := f.UnstructuredClientForMapping(parent.RESTMapping)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to initialize RESTClient for ApplySet: %w\", err)\n\t\t}\n\t\tif restClient == nil {\n\t\t\treturn nil, fmt.Errorf(\"could not build RESTClient for ApplySet\")\n\t\t}\n\t\tapplySet = NewApplySet(parent, tooling, mapper, restClient)\n\t}\n\tif flags.Prune {\n\t\tpruneAllowlist := slice.ToSet(flags.PruneAllowlist, flags.PruneWhitelist)\n\t\tflags.PruneResources, err = prune.ParseResources(mapper, pruneAllowlist)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\to := \u0026ApplyOptions{\n\t\t// \tStore baseName for use in printing warnings / messages involving the base command name.\n\t\t// \tThis is useful for downstream command that wrap this one.\n\t\tcmdBaseName: baseName,\n\n\t\tPrintFlags: flags.PrintFlags,\n\n\t\tDeleteOptions: deleteOptions,\n\t\tToPrinter: toPrinter,\n\t\tServerSideApply: serverSideApply,\n\t\tForceConflicts: forceConflicts,\n\t\tFieldManager: fieldManager,\n\t\tSelector: flags.Selector,\n\t\tDryRunStrategy: dryRunStrategy,\n\t\tPrune: flags.Prune,\n\t\tPruneResources: flags.PruneResources,\n\t\tAll: flags.All,\n\t\tOverwrite: flags.Overwrite,\n\t\tOpenAPIPatch: flags.OpenAPIPatch,\n\n\t\tRecorder: recorder,\n\t\tNamespace: namespace,\n\t\tEnforceNamespace: enforceNamespace,\n\t\tValidator: validator,\n\t\tValidationDirective: validationDirective,\n\t\tBuilder: builder,\n\t\tMapper: mapper,\n\t\tDynamicClient: dynamicClient,\n\t\tOpenAPISchema: openAPISchema,\n\n\t\tIOStreams: flags.IOStreams,\n\n\t\tobjects: []*resource.Info{},\n\t\tobjectsCached: false,\n\n\t\tVisitedUids: sets.New[types.UID](),\n\t\tVisitedNamespaces: sets.New[string](),\n\n\t\tApplySet: applySet,\n\t}\n\n\to.PostProcessorFn = o.PrintAndPrunePostProcessor()\n\n\treturn o, nil\n}","line":{"from":241,"to":378}} {"id":100031350,"name":"Validate","signature":"func (o *ApplyOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply.go","code":"// Validate verifies if ApplyOptions are valid and without conflicts.\nfunc (o *ApplyOptions) Validate() error {\n\tif o.ForceConflicts \u0026\u0026 !o.ServerSideApply {\n\t\treturn fmt.Errorf(\"--force-conflicts only works with --server-side\")\n\t}\n\n\tif o.DryRunStrategy == cmdutil.DryRunClient \u0026\u0026 o.ServerSideApply {\n\t\treturn fmt.Errorf(\"--dry-run=client doesn't work with --server-side (did you mean --dry-run=server instead?)\")\n\t}\n\n\tif o.ServerSideApply \u0026\u0026 o.DeleteOptions.ForceDeletion {\n\t\treturn fmt.Errorf(\"--force cannot be used with --server-side\")\n\t}\n\n\tif o.DryRunStrategy == cmdutil.DryRunServer \u0026\u0026 o.DeleteOptions.ForceDeletion {\n\t\treturn fmt.Errorf(\"--dry-run=server cannot be used with --force\")\n\t}\n\n\tif o.All \u0026\u0026 len(o.Selector) \u003e 0 {\n\t\treturn fmt.Errorf(\"cannot set --all and --selector at the same time\")\n\t}\n\n\tif o.ApplySet != nil {\n\t\tif !o.Prune {\n\t\t\treturn fmt.Errorf(\"--applyset requires --prune\")\n\t\t}\n\t\tif err := o.ApplySet.Validate(context.TODO(), o.DynamicClient); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif o.Prune {\n\t\t// Do not force the recreation of an object(s) if we're pruning; this can cause\n\t\t// undefined behavior since object UID's change.\n\t\tif o.DeleteOptions.ForceDeletion {\n\t\t\treturn fmt.Errorf(\"--force cannot be used with --prune\")\n\t\t}\n\n\t\tif o.ApplySet != nil {\n\t\t\tif o.All {\n\t\t\t\treturn fmt.Errorf(\"--all is incompatible with --applyset\")\n\t\t\t} else if o.Selector != \"\" {\n\t\t\t\treturn fmt.Errorf(\"--selector is incompatible with --applyset\")\n\t\t\t} else if len(o.PruneResources) \u003e 0 {\n\t\t\t\treturn fmt.Errorf(\"--prune-allowlist is incompatible with --applyset\")\n\t\t\t}\n\t\t} else {\n\t\t\tif !o.All \u0026\u0026 o.Selector == \"\" {\n\t\t\t\treturn fmt.Errorf(\"all resources selected for prune without explicitly passing --all. To prune all resources, pass the --all flag. If you did not mean to prune all resources, specify a label selector\")\n\t\t\t}\n\t\t\tif o.ServerSideApply {\n\t\t\t\treturn fmt.Errorf(\"--prune is in alpha and doesn't currently work on objects created by server-side apply\")\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":380,"to":436}} {"id":100031351,"name":"isIncompatibleServerError","signature":"func isIncompatibleServerError(err error) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply.go","code":"func isIncompatibleServerError(err error) bool {\n\t// 415: Unsupported media type means we're talking to a server which doesn't\n\t// support server-side apply.\n\tif _, ok := err.(*errors.StatusError); !ok {\n\t\t// Non-StatusError means the error isn't because the server is incompatible.\n\t\treturn false\n\t}\n\treturn err.(*errors.StatusError).Status().Code == http.StatusUnsupportedMediaType\n}","line":{"from":438,"to":446}} {"id":100031352,"name":"GetObjects","signature":"func (o *ApplyOptions) GetObjects() ([]*resource.Info, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply.go","code":"// GetObjects returns a (possibly cached) version of all the valid objects to apply\n// as a slice of pointer to resource.Info and an error if one or more occurred.\n// IMPORTANT: This function can return both valid objects AND an error, since\n// \"ContinueOnError\" is set on the builder. This function should not be called\n// until AFTER the \"complete\" and \"validate\" methods have been called to ensure that\n// the ApplyOptions is filled in and valid.\nfunc (o *ApplyOptions) GetObjects() ([]*resource.Info, error) {\n\tvar err error = nil\n\tif !o.objectsCached {\n\t\tr := o.Builder.\n\t\t\tUnstructured().\n\t\t\tSchema(o.Validator).\n\t\t\tContinueOnError().\n\t\t\tNamespaceParam(o.Namespace).DefaultNamespace().\n\t\t\tFilenameParam(o.EnforceNamespace, \u0026o.DeleteOptions.FilenameOptions).\n\t\t\tLabelSelectorParam(o.Selector).\n\t\t\tFlatten().\n\t\t\tDo()\n\n\t\to.objects, err = r.Infos()\n\n\t\tif o.ApplySet != nil {\n\t\t\tif err := o.ApplySet.AddLabels(o.objects...); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\to.objectsCached = true\n\t}\n\treturn o.objects, err\n}","line":{"from":448,"to":478}} {"id":100031353,"name":"SetObjects","signature":"func (o *ApplyOptions) SetObjects(infos []*resource.Info)","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply.go","code":"// SetObjects stores the set of objects (as resource.Info) to be\n// subsequently applied.\nfunc (o *ApplyOptions) SetObjects(infos []*resource.Info) {\n\to.objects = infos\n\to.objectsCached = true\n}","line":{"from":480,"to":485}} {"id":100031354,"name":"Run","signature":"func (o *ApplyOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply.go","code":"// Run executes the `apply` command.\nfunc (o *ApplyOptions) Run() error {\n\tif o.PreProcessorFn != nil {\n\t\tklog.V(4).Infof(\"Running apply pre-processor function\")\n\t\tif err := o.PreProcessorFn(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Enforce CLI specified namespace on server request.\n\tif o.EnforceNamespace {\n\t\to.VisitedNamespaces.Insert(o.Namespace)\n\t}\n\n\t// Generates the objects using the resource builder if they have not\n\t// already been stored by calling \"SetObjects()\" in the pre-processor.\n\terrs := []error{}\n\tinfos, err := o.GetObjects()\n\tif err != nil {\n\t\terrs = append(errs, err)\n\t}\n\tif len(infos) == 0 \u0026\u0026 len(errs) == 0 {\n\t\treturn fmt.Errorf(\"no objects passed to apply\")\n\t}\n\n\tif o.ApplySet != nil {\n\t\tif err := o.ApplySet.BeforeApply(infos, o.DryRunStrategy, o.ValidationDirective); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Iterate through all objects, applying each one.\n\tfor _, info := range infos {\n\t\tif err := o.applyOneObject(info); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\t// If any errors occurred during apply, then return error (or\n\t// aggregate of errors).\n\tif len(errs) == 1 {\n\t\treturn errs[0]\n\t}\n\tif len(errs) \u003e 1 {\n\t\treturn utilerrors.NewAggregate(errs)\n\t}\n\n\tif o.PostProcessorFn != nil {\n\t\tklog.V(4).Infof(\"Running apply post-processor function\")\n\t\tif err := o.PostProcessorFn(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":487,"to":541}} {"id":100031355,"name":"applyOneObject","signature":"func (o *ApplyOptions) applyOneObject(info *resource.Info) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply.go","code":"func (o *ApplyOptions) applyOneObject(info *resource.Info) error {\n\to.MarkNamespaceVisited(info)\n\n\tif err := o.Recorder.Record(info.Object); err != nil {\n\t\tklog.V(4).Infof(\"error recording current command: %v\", err)\n\t}\n\n\tif len(info.Name) == 0 {\n\t\tmetadata, _ := meta.Accessor(info.Object)\n\t\tgeneratedName := metadata.GetGenerateName()\n\t\tif len(generatedName) \u003e 0 {\n\t\t\treturn fmt.Errorf(\"from %s: cannot use generate name with apply\", generatedName)\n\t\t}\n\t}\n\n\thelper := resource.NewHelper(info.Client, info.Mapping).\n\t\tDryRun(o.DryRunStrategy == cmdutil.DryRunServer).\n\t\tWithFieldManager(o.FieldManager).\n\t\tWithFieldValidation(o.ValidationDirective)\n\n\tif o.ServerSideApply {\n\t\t// Send the full object to be applied on the server side.\n\t\tdata, err := runtime.Encode(unstructured.UnstructuredJSONScheme, info.Object)\n\t\tif err != nil {\n\t\t\treturn cmdutil.AddSourceToErr(\"serverside-apply\", info.Source, err)\n\t\t}\n\n\t\toptions := metav1.PatchOptions{\n\t\t\tForce: \u0026o.ForceConflicts,\n\t\t}\n\t\tobj, err := helper.Patch(\n\t\t\tinfo.Namespace,\n\t\t\tinfo.Name,\n\t\t\ttypes.ApplyPatchType,\n\t\t\tdata,\n\t\t\t\u0026options,\n\t\t)\n\t\tif err != nil {\n\t\t\tif isIncompatibleServerError(err) {\n\t\t\t\terr = fmt.Errorf(\"Server-side apply not available on the server: (%v)\", err)\n\t\t\t}\n\t\t\tif errors.IsConflict(err) {\n\t\t\t\terr = fmt.Errorf(`%v\nPlease review the fields above--they currently have other managers. Here\nare the ways you can resolve this warning:\n* If you intend to manage all of these fields, please re-run the apply\n command with the `+\"`--force-conflicts`\"+` flag.\n* If you do not intend to manage all of the fields, please edit your\n manifest to remove references to the fields that should keep their\n current managers.\n* You may co-own fields by updating your manifest to match the existing\n value; in this case, you'll become the manager if the other manager(s)\n stop managing the field (remove it from their configuration).\nSee https://kubernetes.io/docs/reference/using-api/server-side-apply/#conflicts`, err)\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\n\t\tinfo.Refresh(obj, true)\n\n\t\t// Migrate managed fields if necessary.\n\t\t//\n\t\t// By checking afterward instead of fetching the object beforehand and\n\t\t// unconditionally fetching we can make 3 network requests in the rare\n\t\t// case of migration and 1 request if migration is unnecessary.\n\t\t//\n\t\t// To check beforehand means 2 requests for most operations, and 3\n\t\t// requests in worst case.\n\t\tif err = o.saveLastApplyAnnotationIfNecessary(helper, info); err != nil {\n\t\t\tfmt.Fprintf(o.ErrOut, warningMigrationLastAppliedFailed, err.Error())\n\t\t} else if performedMigration, err := o.migrateToSSAIfNecessary(helper, info); err != nil {\n\t\t\t// Print-error as a warning.\n\t\t\t// This is a non-fatal error because object was successfully applied\n\t\t\t// above, but it might have issues since migration failed.\n\t\t\t//\n\t\t\t// This migration will be re-attempted if necessary upon next\n\t\t\t// apply.\n\t\t\tfmt.Fprintf(o.ErrOut, warningMigrationPatchFailed, err.Error())\n\t\t} else if performedMigration {\n\t\t\tif obj, err = helper.Patch(\n\t\t\t\tinfo.Namespace,\n\t\t\t\tinfo.Name,\n\t\t\t\ttypes.ApplyPatchType,\n\t\t\t\tdata,\n\t\t\t\t\u0026options,\n\t\t\t); err != nil {\n\t\t\t\t// Re-send original SSA patch (this will allow dropped fields to\n\t\t\t\t// finally be removed)\n\t\t\t\tfmt.Fprintf(o.ErrOut, warningMigrationReapplyFailed, err.Error())\n\t\t\t} else {\n\t\t\t\tinfo.Refresh(obj, false)\n\t\t\t}\n\t\t}\n\n\t\tWarnIfDeleting(info.Object, o.ErrOut)\n\n\t\tif err := o.MarkObjectVisited(info); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif o.shouldPrintObject() {\n\t\t\treturn nil\n\t\t}\n\n\t\tprinter, err := o.ToPrinter(\"serverside-applied\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err = printer.PrintObj(info.Object, o.Out); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\t// Get the modified configuration of the object. Embed the result\n\t// as an annotation in the modified configuration, so that it will appear\n\t// in the patch sent to the server.\n\tmodified, err := util.GetModifiedConfiguration(info.Object, true, unstructured.UnstructuredJSONScheme)\n\tif err != nil {\n\t\treturn cmdutil.AddSourceToErr(fmt.Sprintf(\"retrieving modified configuration from:\\n%s\\nfor:\", info.String()), info.Source, err)\n\t}\n\n\tif err := info.Get(); err != nil {\n\t\tif !errors.IsNotFound(err) {\n\t\t\treturn cmdutil.AddSourceToErr(fmt.Sprintf(\"retrieving current configuration of:\\n%s\\nfrom server for:\", info.String()), info.Source, err)\n\t\t}\n\n\t\t// Create the resource if it doesn't exist\n\t\t// First, update the annotation used by kubectl apply\n\t\tif err := util.CreateApplyAnnotation(info.Object, unstructured.UnstructuredJSONScheme); err != nil {\n\t\t\treturn cmdutil.AddSourceToErr(\"creating\", info.Source, err)\n\t\t}\n\n\t\tif o.DryRunStrategy != cmdutil.DryRunClient {\n\t\t\t// Then create the resource and skip the three-way merge\n\t\t\tobj, err := helper.Create(info.Namespace, true, info.Object)\n\t\t\tif err != nil {\n\t\t\t\treturn cmdutil.AddSourceToErr(\"creating\", info.Source, err)\n\t\t\t}\n\t\t\tinfo.Refresh(obj, true)\n\t\t}\n\n\t\tif err := o.MarkObjectVisited(info); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif o.shouldPrintObject() {\n\t\t\treturn nil\n\t\t}\n\n\t\tprinter, err := o.ToPrinter(\"created\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err = printer.PrintObj(info.Object, o.Out); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\tif err := o.MarkObjectVisited(info); err != nil {\n\t\treturn err\n\t}\n\n\tif o.DryRunStrategy != cmdutil.DryRunClient {\n\t\tmetadata, _ := meta.Accessor(info.Object)\n\t\tannotationMap := metadata.GetAnnotations()\n\t\tif _, ok := annotationMap[corev1.LastAppliedConfigAnnotation]; !ok {\n\t\t\tfmt.Fprintf(o.ErrOut, warningNoLastAppliedConfigAnnotation, info.ObjectName(), corev1.LastAppliedConfigAnnotation, o.cmdBaseName)\n\t\t}\n\n\t\tpatcher, err := newPatcher(o, info, helper)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpatchBytes, patchedObject, err := patcher.Patch(info.Object, modified, info.Source, info.Namespace, info.Name, o.ErrOut)\n\t\tif err != nil {\n\t\t\treturn cmdutil.AddSourceToErr(fmt.Sprintf(\"applying patch:\\n%s\\nto:\\n%v\\nfor:\", patchBytes, info), info.Source, err)\n\t\t}\n\n\t\tinfo.Refresh(patchedObject, true)\n\n\t\tWarnIfDeleting(info.Object, o.ErrOut)\n\n\t\tif string(patchBytes) == \"{}\" \u0026\u0026 !o.shouldPrintObject() {\n\t\t\tprinter, err := o.ToPrinter(\"unchanged\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err = printer.PrintObj(info.Object, o.Out); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tif o.shouldPrintObject() {\n\t\treturn nil\n\t}\n\n\tprinter, err := o.ToPrinter(\"configured\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = printer.PrintObj(info.Object, o.Out); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":543,"to":753}} {"id":100031356,"name":"saveLastApplyAnnotationIfNecessary","signature":"func (o *ApplyOptions) saveLastApplyAnnotationIfNecessary(","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply.go","code":"// Saves the last-applied-configuration annotation in a separate SSA field manager\n// to prevent it from being dropped by users who have transitioned to SSA.\n//\n// If this operation is not performed, then the last-applied-configuration annotation\n// would be removed from the object upon the first SSA usage. We want to keep it\n// around for a few releases since it is required to downgrade to\n// SSA per [1] and [2]. This code should be removed once the annotation is\n// deprecated.\n//\n// - [1] https://kubernetes.io/docs/reference/using-api/server-side-apply/#downgrading-from-server-side-apply-to-client-side-apply\n// - [2] https://github.com/kubernetes/kubernetes/pull/90187\n//\n// If the annotation is not already present, or if it is already managed by the\n// separate SSA fieldmanager, this is a no-op.\nfunc (o *ApplyOptions) saveLastApplyAnnotationIfNecessary(\n\thelper *resource.Helper,\n\tinfo *resource.Info,\n) error {\n\tif o.FieldManager != fieldManagerServerSideApply {\n\t\t// There is no point in preserving the annotation if the field manager\n\t\t// will not remain default. This is because the server will not keep\n\t\t// the annotation up to date.\n\t\treturn nil\n\t}\n\n\t// Send an apply patch with the last-applied-annotation\n\t// so that it is not orphaned by SSA in the following patch:\n\taccessor, err := meta.Accessor(info.Object)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Get the current annotations from the object.\n\tannots := accessor.GetAnnotations()\n\tif annots == nil {\n\t\tannots = map[string]string{}\n\t}\n\n\tfieldManager := fieldManagerLastAppliedAnnotation\n\toriginalAnnotation, hasAnnotation := annots[corev1.LastAppliedConfigAnnotation]\n\n\t// If the annotation does not already exist, we do not do anything\n\tif !hasAnnotation {\n\t\treturn nil\n\t}\n\n\t// If there is already an SSA field manager which owns the field, then there\n\t// is nothing to do here.\n\tif owners := csaupgrade.FindFieldsOwners(\n\t\taccessor.GetManagedFields(),\n\t\tmetav1.ManagedFieldsOperationApply,\n\t\tlastAppliedAnnotationFieldPath,\n\t); len(owners) \u003e 0 {\n\t\treturn nil\n\t}\n\n\tjustAnnotation := \u0026unstructured.Unstructured{}\n\tjustAnnotation.SetGroupVersionKind(info.Mapping.GroupVersionKind)\n\tjustAnnotation.SetName(accessor.GetName())\n\tjustAnnotation.SetNamespace(accessor.GetNamespace())\n\tjustAnnotation.SetAnnotations(map[string]string{\n\t\tcorev1.LastAppliedConfigAnnotation: originalAnnotation,\n\t})\n\n\tmodified, err := runtime.Encode(unstructured.UnstructuredJSONScheme, justAnnotation)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\thelperCopy := *helper\n\tnewObj, err := helperCopy.WithFieldManager(fieldManager).Patch(\n\t\tinfo.Namespace,\n\t\tinfo.Name,\n\t\ttypes.ApplyPatchType,\n\t\tmodified,\n\t\tnil,\n\t)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn info.Refresh(newObj, false)\n}","line":{"from":755,"to":838}} {"id":100031357,"name":"migrateToSSAIfNecessary","signature":"func (o *ApplyOptions) migrateToSSAIfNecessary(","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply.go","code":"// Check if the returned object needs to have its kubectl-client-side-apply\n// managed fields migrated server-side-apply.\n//\n// field ownership metadata is stored in three places:\n// - server-side managed fields\n// - client-side managed fields\n// - and the last_applied_configuration annotation.\n//\n// The migration merges the client-side-managed fields into the\n// server-side-managed fields, leaving the last_applied_configuration\n// annotation in place. Server will keep the annotation up to date\n// after every server-side-apply where the following conditions are ment:\n//\n// 1. field manager is 'kubectl'\n// 2. annotation already exists\nfunc (o *ApplyOptions) migrateToSSAIfNecessary(\n\thelper *resource.Helper,\n\tinfo *resource.Info,\n) (migrated bool, err error) {\n\taccessor, err := meta.Accessor(info.Object)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t// To determine which field managers were used by kubectl for client-side-apply\n\t// we search for a manager used in `Update` operations which owns the\n\t// last-applied-annotation.\n\t//\n\t// This is the last client-side-apply manager which changed the field.\n\t//\n\t// There may be multiple owners if multiple managers wrote the same exact\n\t// configuration. In this case there are multiple owners, we want to migrate\n\t// them all.\n\tcsaManagers := csaupgrade.FindFieldsOwners(\n\t\taccessor.GetManagedFields(),\n\t\tmetav1.ManagedFieldsOperationUpdate,\n\t\tlastAppliedAnnotationFieldPath)\n\n\tmanagerNames := sets.New[string]()\n\tfor _, entry := range csaManagers {\n\t\tmanagerNames.Insert(entry.Manager)\n\t}\n\n\t// Re-attempt patch as many times as it is conflicting due to ResourceVersion\n\t// test failing\n\tfor i := 0; i \u003c maxPatchRetry; i++ {\n\t\tvar patchData []byte\n\t\tvar obj runtime.Object\n\n\t\tpatchData, err = csaupgrade.UpgradeManagedFieldsPatch(\n\t\t\tinfo.Object, managerNames, o.FieldManager)\n\n\t\tif err != nil {\n\t\t\t// If patch generation failed there was likely a bug.\n\t\t\treturn false, err\n\t\t} else if patchData == nil {\n\t\t\t// nil patch data means nothing to do - object is already migrated\n\t\t\treturn false, nil\n\t\t}\n\n\t\t// Send the patch to upgrade the managed fields if it is non-nil\n\t\tobj, err = helper.Patch(\n\t\t\tinfo.Namespace,\n\t\t\tinfo.Name,\n\t\t\ttypes.JSONPatchType,\n\t\t\tpatchData,\n\t\t\tnil,\n\t\t)\n\n\t\tif err == nil {\n\t\t\t// Stop retrying upon success.\n\t\t\tinfo.Refresh(obj, false)\n\t\t\treturn true, nil\n\t\t} else if !errors.IsConflict(err) {\n\t\t\t// Only retry if there was a conflict\n\t\t\treturn false, err\n\t\t}\n\n\t\t// Refresh the object for next iteration\n\t\terr = info.Get()\n\t\tif err != nil {\n\t\t\t// If there was an error fetching, return error\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\t// Reaching this point with non-nil error means there was a conflict and\n\t// max retries was hit\n\t// Return the last error witnessed (which will be a conflict)\n\treturn false, err\n}","line":{"from":840,"to":930}} {"id":100031358,"name":"shouldPrintObject","signature":"func (o *ApplyOptions) shouldPrintObject() bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply.go","code":"func (o *ApplyOptions) shouldPrintObject() bool {\n\t// Print object only if output format other than \"name\" is specified\n\tshouldPrint := false\n\toutput := *o.PrintFlags.OutputFormat\n\tshortOutput := output == \"name\"\n\tif len(output) \u003e 0 \u0026\u0026 !shortOutput {\n\t\tshouldPrint = true\n\t}\n\treturn shouldPrint\n}","line":{"from":932,"to":941}} {"id":100031359,"name":"printObjects","signature":"func (o *ApplyOptions) printObjects() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply.go","code":"func (o *ApplyOptions) printObjects() error {\n\n\tif !o.shouldPrintObject() {\n\t\treturn nil\n\t}\n\n\tinfos, err := o.GetObjects()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(infos) \u003e 0 {\n\t\tprinter, err := o.ToPrinter(\"\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tobjToPrint := infos[0].Object\n\t\tif len(infos) \u003e 1 {\n\t\t\tobjs := []runtime.Object{}\n\t\t\tfor _, info := range infos {\n\t\t\t\tobjs = append(objs, info.Object)\n\t\t\t}\n\t\t\tlist := \u0026corev1.List{\n\t\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\t\tKind: \"List\",\n\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t},\n\t\t\t\tListMeta: metav1.ListMeta{},\n\t\t\t}\n\t\t\tif err := meta.SetList(list, objs); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tobjToPrint = list\n\t\t}\n\t\tif err := printer.PrintObj(objToPrint, o.Out); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":943,"to":985}} {"id":100031360,"name":"MarkNamespaceVisited","signature":"func (o *ApplyOptions) MarkNamespaceVisited(info *resource.Info)","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply.go","code":"// MarkNamespaceVisited keeps track of which namespaces the applied\n// objects belong to. Used for pruning.\nfunc (o *ApplyOptions) MarkNamespaceVisited(info *resource.Info) {\n\tif info.Namespaced() {\n\t\to.VisitedNamespaces.Insert(info.Namespace)\n\t}\n}","line":{"from":987,"to":993}} {"id":100031361,"name":"MarkObjectVisited","signature":"func (o *ApplyOptions) MarkObjectVisited(info *resource.Info) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply.go","code":"// MarkObjectVisited keeps track of UIDs of the applied\n// objects. Used for pruning.\nfunc (o *ApplyOptions) MarkObjectVisited(info *resource.Info) error {\n\tmetadata, err := meta.Accessor(info.Object)\n\tif err != nil {\n\t\treturn err\n\t}\n\to.VisitedUids.Insert(metadata.GetUID())\n\n\treturn nil\n}","line":{"from":995,"to":1005}} {"id":100031362,"name":"PrintAndPrunePostProcessor","signature":"func (o *ApplyOptions) PrintAndPrunePostProcessor() func() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply.go","code":"// PrintAndPrunePostProcessor returns a function which meets the PostProcessorFn\n// function signature. This returned function prints all the\n// objects as a list (if configured for that), and prunes the\n// objects not applied. The returned function is the standard\n// apply post processor.\nfunc (o *ApplyOptions) PrintAndPrunePostProcessor() func() error {\n\n\treturn func() error {\n\t\tctx := context.TODO()\n\t\tif err := o.printObjects(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif o.Prune {\n\t\t\tif cmdutil.ApplySet.IsEnabled() \u0026\u0026 o.ApplySet != nil {\n\t\t\t\tif err := o.ApplySet.Prune(ctx, o); err != nil {\n\t\t\t\t\t// Do not update the ApplySet. If pruning failed, we want to keep the superset\n\t\t\t\t\t// of the previous and current resources in the ApplySet, so that the pruning\n\t\t\t\t\t// step of the next apply will be able to clean up the set correctly.\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tp := newPruner(o)\n\t\t\t\treturn p.pruneAll(o)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t}\n}","line":{"from":1007,"to":1036}} {"id":100031363,"name":"GetApplyFieldManagerFlag","signature":"func GetApplyFieldManagerFlag(cmd *cobra.Command, serverSide bool) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply.go","code":"// GetApplyFieldManagerFlag gets the field manager for kubectl apply\n// if it is not set.\n//\n// The default field manager is not `kubectl-apply` to distinguish between\n// client-side and server-side apply.\nfunc GetApplyFieldManagerFlag(cmd *cobra.Command, serverSide bool) string {\n\t// The field manager flag was set\n\tif cmd.Flag(\"field-manager\").Changed {\n\t\treturn cmdutil.GetFlagString(cmd, \"field-manager\")\n\t}\n\n\tif serverSide {\n\t\treturn fieldManagerServerSideApply\n\t}\n\n\treturn FieldManagerClientSideApply\n}","line":{"from":1061,"to":1077}} {"id":100031364,"name":"WarnIfDeleting","signature":"func WarnIfDeleting(obj runtime.Object, stderr io.Writer)","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply.go","code":"// WarnIfDeleting prints a warning if a resource is being deleted\nfunc WarnIfDeleting(obj runtime.Object, stderr io.Writer) {\n\tmetadata, _ := meta.Accessor(obj)\n\tif metadata != nil \u0026\u0026 metadata.GetDeletionTimestamp() != nil {\n\t\t// just warn the user about the conflict\n\t\tfmt.Fprintf(stderr, warningChangesOnDeletingResource, metadata.GetName())\n\t}\n}","line":{"from":1079,"to":1086}} {"id":100031365,"name":"NewCmdApplyEditLastApplied","signature":"func NewCmdApplyEditLastApplied(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply_edit_last_applied.go","code":"// NewCmdApplyEditLastApplied created the cobra CLI command for the `apply edit-last-applied` command.\nfunc NewCmdApplyEditLastApplied(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := editor.NewEditOptions(editor.ApplyEditMode, ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"edit-last-applied (RESOURCE/NAME | -f FILENAME)\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Edit latest last-applied-configuration annotations of a resource/object\"),\n\t\tLong: applyEditLastAppliedLong,\n\t\tExample: applyEditLastAppliedExample,\n\t\tValidArgsFunction: completion.ResourceTypeAndNameCompletionFunc(f),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, args, cmd))\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\t// bind flag structs\n\to.RecordFlags.AddFlags(cmd)\n\to.PrintFlags.AddFlags(cmd)\n\n\tusage := \"to use to edit the resource\"\n\tcmdutil.AddFilenameOptionFlags(cmd, \u0026o.FilenameOptions, usage)\n\tcmd.Flags().BoolVar(\u0026o.WindowsLineEndings, \"windows-line-endings\", o.WindowsLineEndings,\n\t\t\"Defaults to the line ending native to your platform.\")\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.FieldManager, FieldManagerClientSideApply)\n\tcmdutil.AddValidateFlags(cmd)\n\n\treturn cmd\n}","line":{"from":60,"to":89}} {"id":100031366,"name":"NewSetLastAppliedOptions","signature":"func NewSetLastAppliedOptions(ioStreams genericclioptions.IOStreams) *SetLastAppliedOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply_set_last_applied.go","code":"// NewSetLastAppliedOptions takes option arguments from a CLI stream and returns it at SetLastAppliedOptions type.\nfunc NewSetLastAppliedOptions(ioStreams genericclioptions.IOStreams) *SetLastAppliedOptions {\n\treturn \u0026SetLastAppliedOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"configured\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":86,"to":92}} {"id":100031367,"name":"NewCmdApplySetLastApplied","signature":"func NewCmdApplySetLastApplied(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply_set_last_applied.go","code":"// NewCmdApplySetLastApplied creates the cobra CLI `apply` subcommand `set-last-applied`.`\nfunc NewCmdApplySetLastApplied(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewSetLastAppliedOptions(ioStreams)\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"set-last-applied -f FILENAME\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Set the last-applied-configuration annotation on a live object to match the contents of a file\"),\n\t\tLong: applySetLastAppliedLong,\n\t\tExample: applySetLastAppliedExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.RunSetLastApplied())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmd.Flags().BoolVar(\u0026o.CreateAnnotation, \"create-annotation\", o.CreateAnnotation, \"Will create 'last-applied-configuration' annotations if current objects doesn't have one\")\n\tcmdutil.AddJsonFilenameFlag(cmd.Flags(), \u0026o.FilenameOptions.Filenames, \"Filename, directory, or URL to files that contains the last-applied-configuration annotations\")\n\n\treturn cmd\n}","line":{"from":94,"to":117}} {"id":100031368,"name":"Complete","signature":"func (o *SetLastAppliedOptions) Complete(f cmdutil.Factory, cmd *cobra.Command) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply_set_last_applied.go","code":"// Complete populates dry-run and output flag options.\nfunc (o *SetLastAppliedOptions) Complete(f cmdutil.Factory, cmd *cobra.Command) error {\n\tvar err error\n\to.dryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\to.output = cmdutil.GetFlagString(cmd, \"output\")\n\to.shortOutput = o.output == \"name\"\n\n\to.namespace, o.enforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.builder = f.NewBuilder()\n\to.unstructuredClientForMapping = f.UnstructuredClientForMapping\n\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.dryRunStrategy)\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.PrintObj = printer.PrintObj\n\n\treturn nil\n}","line":{"from":119,"to":144}} {"id":100031369,"name":"Validate","signature":"func (o *SetLastAppliedOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply_set_last_applied.go","code":"// Validate checks SetLastAppliedOptions for validity.\nfunc (o *SetLastAppliedOptions) Validate() error {\n\tr := o.builder.\n\t\tUnstructured().\n\t\tNamespaceParam(o.namespace).DefaultNamespace().\n\t\tFilenameParam(o.enforceNamespace, \u0026o.FilenameOptions).\n\t\tFlatten().\n\t\tDo()\n\n\terr := r.Visit(func(info *resource.Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpatchBuf, diffBuf, patchType, err := editor.GetApplyPatch(info.Object.(runtime.Unstructured))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Verify the object exists in the cluster before trying to patch it.\n\t\tif err := info.Get(); err != nil {\n\t\t\tif errors.IsNotFound(err) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn cmdutil.AddSourceToErr(fmt.Sprintf(\"retrieving current configuration of:\\n%s\\nfrom server for:\", info.String()), info.Source, err)\n\t\t}\n\t\toriginalBuf, err := util.GetOriginalConfiguration(info.Object)\n\t\tif err != nil {\n\t\t\treturn cmdutil.AddSourceToErr(fmt.Sprintf(\"retrieving current configuration of:\\n%s\\nfrom server for:\", info.String()), info.Source, err)\n\t\t}\n\t\tif originalBuf == nil \u0026\u0026 !o.CreateAnnotation {\n\t\t\treturn fmt.Errorf(\"no last-applied-configuration annotation found on resource: %s, to create the annotation, run the command with --create-annotation\", info.Name)\n\t\t}\n\n\t\t//only add to PatchBufferList when changed\n\t\tif !bytes.Equal(cmdutil.StripComments(originalBuf), cmdutil.StripComments(diffBuf)) {\n\t\t\tp := PatchBuffer{Patch: patchBuf, PatchType: patchType}\n\t\t\to.patchBufferList = append(o.patchBufferList, p)\n\t\t\to.infoList = append(o.infoList, info)\n\t\t} else {\n\t\t\tfmt.Fprintf(o.Out, \"set-last-applied %s: no changes required.\\n\", info.Name)\n\t\t}\n\n\t\treturn nil\n\t})\n\treturn err\n}","line":{"from":146,"to":191}} {"id":100031370,"name":"RunSetLastApplied","signature":"func (o *SetLastAppliedOptions) RunSetLastApplied() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply_set_last_applied.go","code":"// RunSetLastApplied executes the `set-last-applied` command according to SetLastAppliedOptions.\nfunc (o *SetLastAppliedOptions) RunSetLastApplied() error {\n\tfor i, patch := range o.patchBufferList {\n\t\tinfo := o.infoList[i]\n\t\tfinalObj := info.Object\n\n\t\tif o.dryRunStrategy != cmdutil.DryRunClient {\n\t\t\tmapping := info.ResourceMapping()\n\t\t\tclient, err := o.unstructuredClientForMapping(mapping)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thelper := resource.\n\t\t\t\tNewHelper(client, mapping).\n\t\t\t\tDryRun(o.dryRunStrategy == cmdutil.DryRunServer)\n\t\t\tfinalObj, err = helper.Patch(info.Namespace, info.Name, patch.PatchType, patch.Patch, nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif err := o.PrintObj(finalObj, o.Out); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":193,"to":218}} {"id":100031371,"name":"NewViewLastAppliedOptions","signature":"func NewViewLastAppliedOptions(ioStreams genericclioptions.IOStreams) *ViewLastAppliedOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply_view_last_applied.go","code":"// NewViewLastAppliedOptions takes option arguments from a CLI stream and returns it at ViewLastAppliedOptions type.\nfunc NewViewLastAppliedOptions(ioStreams genericclioptions.IOStreams) *ViewLastAppliedOptions {\n\treturn \u0026ViewLastAppliedOptions{\n\t\tOutputFormat: \"yaml\",\n\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":62,"to":69}} {"id":100031372,"name":"NewCmdApplyViewLastApplied","signature":"func NewCmdApplyViewLastApplied(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply_view_last_applied.go","code":"// NewCmdApplyViewLastApplied creates the cobra CLI `apply` subcommand `view-last-applied`.`\nfunc NewCmdApplyViewLastApplied(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\toptions := NewViewLastAppliedOptions(ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"view-last-applied (TYPE [NAME | -l label] | TYPE/NAME | -f FILENAME)\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"View the latest last-applied-configuration annotations of a resource/object\"),\n\t\tLong: applyViewLastAppliedLong,\n\t\tExample: applyViewLastAppliedExample,\n\t\tValidArgsFunction: completion.ResourceTypeAndNameCompletionFunc(f),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(options.Complete(cmd, f, args))\n\t\t\tcmdutil.CheckErr(options.Validate())\n\t\t\tcmdutil.CheckErr(options.RunApplyViewLastApplied(cmd))\n\t\t},\n\t}\n\n\tcmd.Flags().StringVarP(\u0026options.OutputFormat, \"output\", \"o\", options.OutputFormat, `Output format. Must be one of (yaml, json)`)\n\tcmd.Flags().BoolVar(\u0026options.All, \"all\", options.All, \"Select all resources in the namespace of the specified resource types\")\n\tusage := \"that contains the last-applied-configuration annotations\"\n\tcmdutil.AddFilenameOptionFlags(cmd, \u0026options.FilenameOptions, usage)\n\tcmdutil.AddLabelSelectorFlagVar(cmd, \u0026options.Selector)\n\n\treturn cmd\n}","line":{"from":71,"to":96}} {"id":100031373,"name":"Complete","signature":"func (o *ViewLastAppliedOptions) Complete(cmd *cobra.Command, f cmdutil.Factory, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply_view_last_applied.go","code":"// Complete checks an object for last-applied-configuration annotations.\nfunc (o *ViewLastAppliedOptions) Complete(cmd *cobra.Command, f cmdutil.Factory, args []string) error {\n\tcmdNamespace, enforceNamespace, err := f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr := f.NewBuilder().\n\t\tUnstructured().\n\t\tNamespaceParam(cmdNamespace).DefaultNamespace().\n\t\tFilenameParam(enforceNamespace, \u0026o.FilenameOptions).\n\t\tResourceTypeOrNameArgs(enforceNamespace, args...).\n\t\tSelectAllParam(o.All).\n\t\tLabelSelectorParam(o.Selector).\n\t\tLatest().\n\t\tFlatten().\n\t\tDo()\n\terr = r.Err()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = r.Visit(func(info *resource.Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tconfigString, err := util.GetOriginalConfiguration(info.Object)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif configString == nil {\n\t\t\treturn cmdutil.AddSourceToErr(fmt.Sprintf(\"no last-applied-configuration annotation found on resource: %s\\n\", info.Name), info.Source, err)\n\t\t}\n\t\to.LastAppliedConfigurationList = append(o.LastAppliedConfigurationList, string(configString))\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":98,"to":141}} {"id":100031374,"name":"Validate","signature":"func (o *ViewLastAppliedOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply_view_last_applied.go","code":"// Validate checks ViewLastAppliedOptions for validity.\nfunc (o *ViewLastAppliedOptions) Validate() error {\n\treturn nil\n}","line":{"from":143,"to":146}} {"id":100031375,"name":"RunApplyViewLastApplied","signature":"func (o *ViewLastAppliedOptions) RunApplyViewLastApplied(cmd *cobra.Command) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/apply_view_last_applied.go","code":"// RunApplyViewLastApplied executes the `view-last-applied` command according to ViewLastAppliedOptions.\nfunc (o *ViewLastAppliedOptions) RunApplyViewLastApplied(cmd *cobra.Command) error {\n\tfor _, str := range o.LastAppliedConfigurationList {\n\t\tswitch o.OutputFormat {\n\t\tcase \"json\":\n\t\t\tjsonBuffer := \u0026bytes.Buffer{}\n\t\t\terr := json.Indent(jsonBuffer, []byte(str), \"\", \" \")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfmt.Fprint(o.Out, string(jsonBuffer.Bytes()))\n\t\tcase \"yaml\":\n\t\t\tyamlOutput, err := yaml.JSONToYAML([]byte(str))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfmt.Fprint(o.Out, string(yamlOutput))\n\t\tdefault:\n\t\t\treturn cmdutil.UsageErrorf(\n\t\t\t\tcmd,\n\t\t\t\t\"Unexpected -o output mode: %s, the flag 'output' must be one of yaml|json\",\n\t\t\t\to.OutputFormat)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":148,"to":174}} {"id":100031376,"name":"IsNamespaced","signature":"func (p ApplySetParentRef) IsNamespaced() bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"func (p ApplySetParentRef) IsNamespaced() bool {\n\treturn p.Scope.Name() == meta.RESTScopeNameNamespace\n}","line":{"from":124,"to":126}} {"id":100031377,"name":"String","signature":"func (p ApplySetParentRef) String() string","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"// String returns the string representation of the parent object using the same format\n// that we expect to receive in the --applyset flag on the CLI.\nfunc (p ApplySetParentRef) String() string {\n\treturn fmt.Sprintf(\"%s.%s/%s\", p.Resource.Resource, p.Resource.Group, p.Name)\n}","line":{"from":128,"to":132}} {"id":100031378,"name":"String","signature":"func (t ApplySetTooling) String() string","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"func (t ApplySetTooling) String() string {\n\treturn fmt.Sprintf(\"%s/%s\", t.Name, t.Version)\n}","line":{"from":139,"to":141}} {"id":100031379,"name":"NewApplySet","signature":"func NewApplySet(parent *ApplySetParentRef, tooling ApplySetTooling, mapper meta.RESTMapper, client resource.RESTClient) *ApplySet","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"// NewApplySet creates a new ApplySet object tracked by the given parent object.\nfunc NewApplySet(parent *ApplySetParentRef, tooling ApplySetTooling, mapper meta.RESTMapper, client resource.RESTClient) *ApplySet {\n\treturn \u0026ApplySet{\n\t\tcurrentResources: make(map[schema.GroupVersionResource]*meta.RESTMapping),\n\t\tcurrentNamespaces: make(sets.Set[string]),\n\t\tupdatedResources: make(map[schema.GroupVersionResource]*meta.RESTMapping),\n\t\tupdatedNamespaces: make(sets.Set[string]),\n\t\tparentRef: parent,\n\t\ttoolingID: tooling,\n\t\trestMapper: mapper,\n\t\tclient: client,\n\t}\n}","line":{"from":143,"to":155}} {"id":100031380,"name":"ID","signature":"func (a ApplySet) ID() string","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"func (a ApplySet) ID() string {\n\tunencoded := strings.Join([]string{a.parentRef.Name, a.parentRef.Namespace, a.parentRef.GroupVersionKind.Kind, a.parentRef.GroupVersionKind.Group}, applySetIDPartDelimiter)\n\thashed := sha256.Sum256([]byte(unencoded))\n\tb64 := base64.RawURLEncoding.EncodeToString(hashed[:])\n\t// Label values must start and end with alphanumeric values, so add a known-safe prefix and suffix.\n\treturn fmt.Sprintf(V1ApplySetIdFormat, b64)\n}","line":{"from":162,"to":168}} {"id":100031381,"name":"Validate","signature":"func (a ApplySet) Validate(ctx context.Context, client dynamic.Interface) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"// Validate imposes restrictions on the parent object that is used to track the applyset.\nfunc (a ApplySet) Validate(ctx context.Context, client dynamic.Interface) error {\n\tvar errors []error\n\tif a.parentRef.IsNamespaced() \u0026\u0026 a.parentRef.Namespace == \"\" {\n\t\terrors = append(errors, fmt.Errorf(\"namespace is required to use namespace-scoped ApplySet\"))\n\t}\n\tif !builtinApplySetParentGVRs.Has(a.parentRef.Resource) {\n\t\t// Determine which custom resource types are allowed as ApplySet parents.\n\t\t// Optimization: Since this makes requests, we only do this if they aren't using a default type.\n\t\tpermittedCRParents, err := a.getAllowedCustomResourceParents(ctx, client)\n\t\tif err != nil {\n\t\t\terrors = append(errors, fmt.Errorf(\"identifying allowed custom resource parent types: %w\", err))\n\t\t}\n\t\tparentRefResourceIgnoreVersion := a.parentRef.Resource.GroupResource().WithVersion(\"\")\n\t\tif !permittedCRParents.Has(parentRefResourceIgnoreVersion) {\n\t\t\terrors = append(errors, fmt.Errorf(\"resource %q is not permitted as an ApplySet parent\", a.parentRef.Resource))\n\t\t}\n\t}\n\treturn utilerrors.NewAggregate(errors)\n}","line":{"from":170,"to":189}} {"id":100031382,"name":"labelForCustomParentCRDs","signature":"func (a *ApplySet) labelForCustomParentCRDs() *metav1.LabelSelector","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"func (a *ApplySet) labelForCustomParentCRDs() *metav1.LabelSelector {\n\treturn \u0026metav1.LabelSelector{\n\t\tMatchExpressions: []metav1.LabelSelectorRequirement{{\n\t\t\tKey: ApplysetParentCRDLabel,\n\t\t\tOperator: metav1.LabelSelectorOpExists,\n\t\t}},\n\t}\n}","line":{"from":191,"to":198}} {"id":100031383,"name":"getAllowedCustomResourceParents","signature":"func (a *ApplySet) getAllowedCustomResourceParents(ctx context.Context, client dynamic.Interface) (sets.Set[schema.GroupVersionResource], error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"func (a *ApplySet) getAllowedCustomResourceParents(ctx context.Context, client dynamic.Interface) (sets.Set[schema.GroupVersionResource], error) {\n\topts := metav1.ListOptions{\n\t\tLabelSelector: metav1.FormatLabelSelector(a.labelForCustomParentCRDs()),\n\t}\n\tlist, err := client.Resource(schema.GroupVersionResource{\n\t\tGroup: \"apiextensions.k8s.io\",\n\t\tVersion: \"v1\",\n\t\tResource: \"customresourcedefinitions\",\n\t}).List(ctx, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tset := sets.New[schema.GroupVersionResource]()\n\tfor i := range list.Items {\n\t\t// Custom resources must be named `\u003cnames.plural\u003e.\u003cgroup\u003e`\n\t\t// and are served under `/apis/\u003cgroup\u003e/\u003cversion\u003e/.../\u003cplural\u003e`\n\t\tgr := schema.ParseGroupResource(list.Items[i].GetName())\n\t\tset.Insert(gr.WithVersion(\"\"))\n\t}\n\treturn set, nil\n}","line":{"from":200,"to":220}} {"id":100031384,"name":"LabelsForMember","signature":"func (a *ApplySet) LabelsForMember() map[string]string","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"func (a *ApplySet) LabelsForMember() map[string]string {\n\treturn map[string]string{\n\t\tApplysetPartOfLabel: a.ID(),\n\t}\n}","line":{"from":222,"to":226}} {"id":100031385,"name":"AddLabels","signature":"func (a *ApplySet) AddLabels(objects ...*resource.Info) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"// addLabels sets our tracking labels on each object; this should be called as part of loading the objects.\nfunc (a *ApplySet) AddLabels(objects ...*resource.Info) error {\n\tapplysetLabels := a.LabelsForMember()\n\tfor _, obj := range objects {\n\t\taccessor, err := meta.Accessor(obj.Object)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"getting accessor: %w\", err)\n\t\t}\n\t\tlabels := accessor.GetLabels()\n\t\tif labels == nil {\n\t\t\tlabels = make(map[string]string)\n\t\t}\n\t\tfor k, v := range applysetLabels {\n\t\t\tif _, found := labels[k]; found {\n\t\t\t\treturn fmt.Errorf(\"ApplySet label %q already set in input data\", k)\n\t\t\t}\n\t\t\tlabels[k] = v\n\t\t}\n\t\taccessor.SetLabels(labels)\n\t}\n\n\treturn nil\n}","line":{"from":228,"to":250}} {"id":100031386,"name":"fetchParent","signature":"func (a *ApplySet) fetchParent() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"func (a *ApplySet) fetchParent() error {\n\thelper := resource.NewHelper(a.client, a.parentRef.RESTMapping)\n\tobj, err := helper.Get(a.parentRef.Namespace, a.parentRef.Name)\n\tif errors.IsNotFound(err) {\n\t\tif !builtinApplySetParentGVRs.Has(a.parentRef.Resource) {\n\t\t\treturn fmt.Errorf(\"custom resource ApplySet parents cannot be created automatically\")\n\t\t}\n\t\treturn nil\n\t} else if err != nil {\n\t\treturn fmt.Errorf(\"failed to fetch ApplySet parent object %q: %w\", a.parentRef, err)\n\t} else if obj == nil {\n\t\treturn fmt.Errorf(\"failed to fetch ApplySet parent object %q\", a.parentRef)\n\t}\n\n\tlabels, annotations, err := getLabelsAndAnnotations(obj)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"getting metadata from parent object %q: %w\", a.parentRef, err)\n\t}\n\n\ttoolAnnotation, hasToolAnno := annotations[ApplySetToolingAnnotation]\n\tif !hasToolAnno {\n\t\treturn fmt.Errorf(\"ApplySet parent object %q already exists and is missing required annotation %q\", a.parentRef, ApplySetToolingAnnotation)\n\t}\n\tif managedBy := toolingBaseName(toolAnnotation); managedBy != a.toolingID.Name {\n\t\treturn fmt.Errorf(\"ApplySet parent object %q already exists and is managed by tooling %q instead of %q\", a.parentRef, managedBy, a.toolingID.Name)\n\t}\n\n\tidLabel, hasIDLabel := labels[ApplySetParentIDLabel]\n\tif !hasIDLabel {\n\t\treturn fmt.Errorf(\"ApplySet parent object %q exists and does not have required label %s\", a.parentRef, ApplySetParentIDLabel)\n\t}\n\tif idLabel != a.ID() {\n\t\treturn fmt.Errorf(\"ApplySet parent object %q exists and has incorrect value for label %q (got: %s, want: %s)\", a.parentRef, ApplySetParentIDLabel, idLabel, a.ID())\n\t}\n\n\tif a.currentResources, err = parseResourcesAnnotation(annotations, a.restMapper); err != nil {\n\t\t// TODO: handle GVRs for now-deleted CRDs\n\t\treturn fmt.Errorf(\"parsing ApplySet annotation on %q: %w\", a.parentRef, err)\n\t}\n\ta.currentNamespaces = parseNamespacesAnnotation(annotations)\n\tif a.parentRef.IsNamespaced() {\n\t\ta.currentNamespaces.Insert(a.parentRef.Namespace)\n\t}\n\treturn nil\n}","line":{"from":252,"to":296}} {"id":100031387,"name":"LabelSelectorForMembers","signature":"func (a *ApplySet) LabelSelectorForMembers() string","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"func (a *ApplySet) LabelSelectorForMembers() string {\n\treturn metav1.FormatLabelSelector(\u0026metav1.LabelSelector{\n\t\tMatchLabels: a.LabelsForMember(),\n\t})\n}","line":{"from":297,"to":301}} {"id":100031388,"name":"AllPrunableResources","signature":"func (a *ApplySet) AllPrunableResources() []*meta.RESTMapping","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"// AllPrunableResources returns the list of all resources that should be considered for pruning.\n// This is potentially a superset of the resources types that actually contain resources.\nfunc (a *ApplySet) AllPrunableResources() []*meta.RESTMapping {\n\tvar ret []*meta.RESTMapping\n\tfor _, m := range a.currentResources {\n\t\tret = append(ret, m)\n\t}\n\treturn ret\n}","line":{"from":303,"to":311}} {"id":100031389,"name":"AllPrunableNamespaces","signature":"func (a *ApplySet) AllPrunableNamespaces() []string","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"// AllPrunableNamespaces returns the list of all namespaces that should be considered for pruning.\n// This is potentially a superset of the namespaces that actually contain resources.\nfunc (a *ApplySet) AllPrunableNamespaces() []string {\n\tvar ret []string\n\tfor ns := range a.currentNamespaces {\n\t\tret = append(ret, ns)\n\t}\n\treturn ret\n}","line":{"from":313,"to":321}} {"id":100031390,"name":"getLabelsAndAnnotations","signature":"func getLabelsAndAnnotations(obj runtime.Object) (map[string]string, map[string]string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"func getLabelsAndAnnotations(obj runtime.Object) (map[string]string, map[string]string, error) {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn accessor.GetLabels(), accessor.GetAnnotations(), nil\n}","line":{"from":323,"to":329}} {"id":100031391,"name":"toolingBaseName","signature":"func toolingBaseName(toolAnnotation string) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"func toolingBaseName(toolAnnotation string) string {\n\tparts := strings.Split(toolAnnotation, \"/\")\n\tif len(parts) \u003e= 2 {\n\t\treturn strings.Join(parts[:len(parts)-1], \"/\")\n\t}\n\treturn toolAnnotation\n}","line":{"from":331,"to":337}} {"id":100031392,"name":"parseResourcesAnnotation","signature":"func parseResourcesAnnotation(annotations map[string]string, mapper meta.RESTMapper) (map[schema.GroupVersionResource]*meta.RESTMapping, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"func parseResourcesAnnotation(annotations map[string]string, mapper meta.RESTMapper) (map[schema.GroupVersionResource]*meta.RESTMapping, error) {\n\tannotation, ok := annotations[ApplySetGRsAnnotation]\n\tif !ok {\n\t\t// The spec does not require this annotation. However, 'missing' means 'perform discovery'.\n\t\t// We return an error because we do not currently support dynamic discovery in kubectl apply.\n\t\treturn nil, fmt.Errorf(\"kubectl requires the %q annotation to be set on all ApplySet parent objects\", ApplySetGRsAnnotation)\n\t}\n\tmappings := make(map[schema.GroupVersionResource]*meta.RESTMapping)\n\t// Annotation present but empty means that this is currently an empty set.\n\tif annotation == \"\" {\n\t\treturn mappings, nil\n\t}\n\tfor _, grString := range strings.Split(annotation, \",\") {\n\t\tgr := schema.ParseGroupResource(grString)\n\t\tgvk, err := mapper.KindFor(gr.WithVersion(\"\"))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid group resource in %q annotation: %w\", ApplySetGRsAnnotation, err)\n\t\t}\n\t\tmapping, err := mapper.RESTMapping(gvk.GroupKind())\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"could not find kind for resource in %q annotation: %w\", ApplySetGRsAnnotation, err)\n\t\t}\n\t\tmappings[mapping.Resource] = mapping\n\t}\n\treturn mappings, nil\n}","line":{"from":339,"to":364}} {"id":100031393,"name":"parseNamespacesAnnotation","signature":"func parseNamespacesAnnotation(annotations map[string]string) sets.Set[string]","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"func parseNamespacesAnnotation(annotations map[string]string) sets.Set[string] {\n\tannotation, ok := annotations[ApplySetAdditionalNamespacesAnnotation]\n\tif !ok { // this annotation is completely optional\n\t\treturn sets.Set[string]{}\n\t}\n\t// Don't include an empty namespace\n\tif annotation == \"\" {\n\t\treturn sets.Set[string]{}\n\t}\n\treturn sets.New(strings.Split(annotation, \",\")...)\n}","line":{"from":366,"to":376}} {"id":100031394,"name":"addResource","signature":"func (a *ApplySet) addResource(resource *meta.RESTMapping, namespace string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"// addResource registers the given resource and namespace as being part of the updated set of\n// resources being applied by the current operation.\nfunc (a *ApplySet) addResource(resource *meta.RESTMapping, namespace string) {\n\ta.updatedResources[resource.Resource] = resource\n\tif resource.Scope == meta.RESTScopeNamespace \u0026\u0026 namespace != \"\" {\n\t\ta.updatedNamespaces.Insert(namespace)\n\t}\n}","line":{"from":378,"to":385}} {"id":100031395,"name":"updateParent","signature":"func (a *ApplySet) updateParent(mode ApplySetUpdateMode, dryRun cmdutil.DryRunStrategy, validation string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"func (a *ApplySet) updateParent(mode ApplySetUpdateMode, dryRun cmdutil.DryRunStrategy, validation string) error {\n\tdata, err := json.Marshal(a.buildParentPatch(mode))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to encode patch for ApplySet parent: %w\", err)\n\t}\n\terr = serverSideApplyRequest(a, data, dryRun, validation, false)\n\tif err != nil \u0026\u0026 errors.IsConflict(err) {\n\t\t// Try again with conflicts forced\n\t\tklog.Warningf(\"WARNING: failed to update ApplySet: %s\\nApplySet field manager %s should own these fields. Retrying with conflicts forced.\", err.Error(), a.FieldManager())\n\t\terr = serverSideApplyRequest(a, data, dryRun, validation, true)\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to update ApplySet: %w\", err)\n\t}\n\treturn nil\n}","line":{"from":392,"to":407}} {"id":100031396,"name":"serverSideApplyRequest","signature":"func serverSideApplyRequest(a *ApplySet, data []byte, dryRun cmdutil.DryRunStrategy, validation string, forceConficts bool) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"func serverSideApplyRequest(a *ApplySet, data []byte, dryRun cmdutil.DryRunStrategy, validation string, forceConficts bool) error {\n\tif dryRun == cmdutil.DryRunClient {\n\t\treturn nil\n\t}\n\thelper := resource.NewHelper(a.client, a.parentRef.RESTMapping).\n\t\tDryRun(dryRun == cmdutil.DryRunServer).\n\t\tWithFieldManager(a.FieldManager()).\n\t\tWithFieldValidation(validation)\n\n\toptions := metav1.PatchOptions{\n\t\tForce: \u0026forceConficts,\n\t}\n\t_, err := helper.Patch(\n\t\ta.parentRef.Namespace,\n\t\ta.parentRef.Name,\n\t\ttypes.ApplyPatchType,\n\t\tdata,\n\t\t\u0026options,\n\t)\n\treturn err\n}","line":{"from":409,"to":429}} {"id":100031397,"name":"buildParentPatch","signature":"func (a *ApplySet) buildParentPatch(mode ApplySetUpdateMode) *metav1.PartialObjectMetadata","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"func (a *ApplySet) buildParentPatch(mode ApplySetUpdateMode) *metav1.PartialObjectMetadata {\n\tvar newGRsAnnotation, newNsAnnotation string\n\tswitch mode {\n\tcase updateToSuperset:\n\t\t// If the apply succeeded but pruning failed, the set of group resources that\n\t\t// the ApplySet should track is the superset of the previous and current resources.\n\t\t// This ensures that the resources that failed to be pruned are not orphaned from the set.\n\t\tgrSuperset := sets.KeySet(a.currentResources).Union(sets.KeySet(a.updatedResources))\n\t\tnewGRsAnnotation = generateResourcesAnnotation(grSuperset)\n\t\tnewNsAnnotation = generateNamespacesAnnotation(a.currentNamespaces.Union(a.updatedNamespaces), a.parentRef.Namespace)\n\tcase updateToLatestSet:\n\t\tnewGRsAnnotation = generateResourcesAnnotation(sets.KeySet(a.updatedResources))\n\t\tnewNsAnnotation = generateNamespacesAnnotation(a.updatedNamespaces, a.parentRef.Namespace)\n\t}\n\n\treturn \u0026metav1.PartialObjectMetadata{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: a.parentRef.GroupVersionKind.Kind,\n\t\t\tAPIVersion: a.parentRef.GroupVersionKind.GroupVersion().String(),\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: a.parentRef.Name,\n\t\t\tNamespace: a.parentRef.Namespace,\n\t\t\tAnnotations: map[string]string{\n\t\t\t\tApplySetToolingAnnotation: a.toolingID.String(),\n\t\t\t\tApplySetGRsAnnotation: newGRsAnnotation,\n\t\t\t\tApplySetAdditionalNamespacesAnnotation: newNsAnnotation,\n\t\t\t},\n\t\t\tLabels: map[string]string{\n\t\t\t\tApplySetParentIDLabel: a.ID(),\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":431,"to":464}} {"id":100031398,"name":"generateNamespacesAnnotation","signature":"func generateNamespacesAnnotation(namespaces sets.Set[string], skip string) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"func generateNamespacesAnnotation(namespaces sets.Set[string], skip string) string {\n\tnsList := namespaces.Clone().Delete(skip).UnsortedList()\n\tsort.Strings(nsList)\n\treturn strings.Join(nsList, \",\")\n}","line":{"from":466,"to":470}} {"id":100031399,"name":"generateResourcesAnnotation","signature":"func generateResourcesAnnotation(resources sets.Set[schema.GroupVersionResource]) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"func generateResourcesAnnotation(resources sets.Set[schema.GroupVersionResource]) string {\n\tvar grs []string\n\tfor gvr := range resources {\n\t\tgrs = append(grs, gvr.GroupResource().String())\n\t}\n\tsort.Strings(grs)\n\treturn strings.Join(grs, \",\")\n}","line":{"from":472,"to":479}} {"id":100031400,"name":"FieldManager","signature":"func (a ApplySet) FieldManager() string","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"func (a ApplySet) FieldManager() string {\n\treturn fmt.Sprintf(\"%s-applyset\", a.toolingID.Name)\n}","line":{"from":481,"to":483}} {"id":100031401,"name":"ParseApplySetParentRef","signature":"func ParseApplySetParentRef(parentRefStr string, mapper meta.RESTMapper) (*ApplySetParentRef, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"// ParseApplySetParentRef creates a new ApplySetParentRef from a parent reference in the format [RESOURCE][.GROUP]/NAME\nfunc ParseApplySetParentRef(parentRefStr string, mapper meta.RESTMapper) (*ApplySetParentRef, error) {\n\tvar gvr schema.GroupVersionResource\n\tvar name string\n\n\tif groupRes, nameSuffix, hasTypeInfo := strings.Cut(parentRefStr, \"/\"); hasTypeInfo {\n\t\tname = nameSuffix\n\t\tgvr = schema.ParseGroupResource(groupRes).WithVersion(\"\")\n\t} else {\n\t\tname = parentRefStr\n\t\tgvr = defaultApplySetParentGVR\n\t}\n\n\tif name == \"\" {\n\t\treturn nil, fmt.Errorf(\"name cannot be blank\")\n\t}\n\n\tgvk, err := mapper.KindFor(gvr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmapping, err := mapper.RESTMapping(gvk.GroupKind())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026ApplySetParentRef{Name: name, RESTMapping: mapping}, nil\n}","line":{"from":485,"to":511}} {"id":100031402,"name":"Prune","signature":"func (a *ApplySet) Prune(ctx context.Context, o *ApplyOptions) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"// Prune deletes any objects from the apiserver that are no longer in the applyset.\nfunc (a *ApplySet) Prune(ctx context.Context, o *ApplyOptions) error {\n\tprinter, err := o.ToPrinter(\"pruned\")\n\tif err != nil {\n\t\treturn err\n\t}\n\topt := \u0026ApplySetDeleteOptions{\n\t\tCascadingStrategy: o.DeleteOptions.CascadingStrategy,\n\t\tDryRunStrategy: o.DryRunStrategy,\n\t\tGracePeriod: o.DeleteOptions.GracePeriod,\n\n\t\tPrinter: printer,\n\n\t\tIOStreams: o.IOStreams,\n\t}\n\n\tif err := a.pruneAll(ctx, o.DynamicClient, o.VisitedUids, opt); err != nil {\n\t\treturn err\n\t}\n\n\tif err := a.updateParent(updateToLatestSet, o.DryRunStrategy, o.ValidationDirective); err != nil {\n\t\treturn fmt.Errorf(\"apply and prune succeeded, but ApplySet update failed: %w\", err)\n\t}\n\n\treturn nil\n}","line":{"from":513,"to":538}} {"id":100031403,"name":"BeforeApply","signature":"func (a *ApplySet) BeforeApply(objects []*resource.Info, dryRunStrategy cmdutil.DryRunStrategy, validationDirective string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset.go","code":"// BeforeApply should be called before applying the objects.\n// It pre-updates the parent object so that it covers the resources that will be applied.\n// In this way, even if we are interrupted, we will not leak objects.\nfunc (a *ApplySet) BeforeApply(objects []*resource.Info, dryRunStrategy cmdutil.DryRunStrategy, validationDirective string) error {\n\tif err := a.fetchParent(); err != nil {\n\t\treturn err\n\t}\n\t// Update the live parent object to the superset of the current and previous resources.\n\t// Doing this before the actual apply and prune operations improves behavior by ensuring\n\t// the live object contains the superset on failure. This may cause the next pruning\n\t// operation to make a larger number of GET requests than strictly necessary, but it prevents\n\t// object leakage from the set. The superset will automatically be reduced to the correct\n\t// set by the next successful operation.\n\tfor _, info := range objects {\n\t\ta.addResource(info.ResourceMapping(), info.Namespace)\n\t}\n\tif err := a.updateParent(updateToSuperset, dryRunStrategy, validationDirective); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":540,"to":560}} {"id":100031404,"name":"String","signature":"func (p *PruneObject) String() string","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset_pruner.go","code":"// String returns a human-readable name of the object, for use in debug messages.\nfunc (p *PruneObject) String() string {\n\ts := p.Mapping.GroupVersionKind.GroupKind().String()\n\n\tif p.Namespace != \"\" {\n\t\ts += \" \" + p.Namespace + \"/\" + p.Name\n\t} else {\n\t\ts += \" \" + p.Name\n\t}\n\treturn s\n}","line":{"from":54,"to":64}} {"id":100031405,"name":"FindAllObjectsToPrune","signature":"func (a *ApplySet) FindAllObjectsToPrune(ctx context.Context, dynamicClient dynamic.Interface, visitedUids sets.Set[types.UID]) ([]PruneObject, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset_pruner.go","code":"// FindAllObjectsToPrune returns the list of objects that will be pruned.\n// Calling this instead of Prune can be useful for dry-run / diff behaviour.\nfunc (a *ApplySet) FindAllObjectsToPrune(ctx context.Context, dynamicClient dynamic.Interface, visitedUids sets.Set[types.UID]) ([]PruneObject, error) {\n\ttype task struct {\n\t\tnamespace string\n\t\trestMapping *meta.RESTMapping\n\n\t\terr error\n\t\tresults []PruneObject\n\t}\n\tvar tasks []*task\n\n\t// We run discovery in parallel, in as many goroutines as priority and fairness will allow\n\t// (We don't expect many requests in real-world scenarios - maybe tens, unlikely to be hundreds)\n\tfor _, restMapping := range a.AllPrunableResources() {\n\t\tswitch restMapping.Scope.Name() {\n\t\tcase meta.RESTScopeNameNamespace:\n\t\t\tfor _, namespace := range a.AllPrunableNamespaces() {\n\t\t\t\tif namespace == \"\" {\n\t\t\t\t\t// Just double-check because otherwise we get cryptic error messages\n\t\t\t\t\treturn nil, fmt.Errorf(\"unexpectedly encountered empty namespace during prune of namespace-scoped resource %v\", restMapping.GroupVersionKind)\n\t\t\t\t}\n\t\t\t\ttasks = append(tasks, \u0026task{\n\t\t\t\t\tnamespace: namespace,\n\t\t\t\t\trestMapping: restMapping,\n\t\t\t\t})\n\t\t\t}\n\n\t\tcase meta.RESTScopeNameRoot:\n\t\t\ttasks = append(tasks, \u0026task{\n\t\t\t\trestMapping: restMapping,\n\t\t\t})\n\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unhandled scope %q\", restMapping.Scope.Name())\n\t\t}\n\t}\n\n\tvar wg sync.WaitGroup\n\n\tfor i := range tasks {\n\t\ttask := tasks[i]\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\n\t\t\tresults, err := a.findObjectsToPrune(ctx, dynamicClient, visitedUids, task.namespace, task.restMapping)\n\t\t\tif err != nil {\n\t\t\t\ttask.err = fmt.Errorf(\"listing %v objects for pruning: %w\", task.restMapping.GroupVersionKind.String(), err)\n\t\t\t} else {\n\t\t\t\ttask.results = results\n\t\t\t}\n\t\t}()\n\t}\n\t// Wait for all the goroutines to finish\n\twg.Wait()\n\n\tvar allObjects []PruneObject\n\tfor _, task := range tasks {\n\t\tif task.err != nil {\n\t\t\treturn nil, task.err\n\t\t}\n\t\tallObjects = append(allObjects, task.results...)\n\t}\n\treturn allObjects, nil\n}","line":{"from":66,"to":131}} {"id":100031406,"name":"pruneAll","signature":"func (a *ApplySet) pruneAll(ctx context.Context, dynamicClient dynamic.Interface, visitedUids sets.Set[types.UID], deleteOptions *ApplySetDeleteOptions) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset_pruner.go","code":"func (a *ApplySet) pruneAll(ctx context.Context, dynamicClient dynamic.Interface, visitedUids sets.Set[types.UID], deleteOptions *ApplySetDeleteOptions) error {\n\tallObjects, err := a.FindAllObjectsToPrune(ctx, dynamicClient, visitedUids)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn a.deleteObjects(ctx, dynamicClient, allObjects, deleteOptions)\n}","line":{"from":133,"to":140}} {"id":100031407,"name":"findObjectsToPrune","signature":"func (a *ApplySet) findObjectsToPrune(ctx context.Context, dynamicClient dynamic.Interface, visitedUids sets.Set[types.UID], namespace string, mapping *meta.RESTMapping) ([]PruneObject, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset_pruner.go","code":"func (a *ApplySet) findObjectsToPrune(ctx context.Context, dynamicClient dynamic.Interface, visitedUids sets.Set[types.UID], namespace string, mapping *meta.RESTMapping) ([]PruneObject, error) {\n\tapplysetLabelSelector := a.LabelSelectorForMembers()\n\n\topt := metav1.ListOptions{\n\t\tLabelSelector: applysetLabelSelector,\n\t}\n\n\tklog.V(2).Infof(\"listing objects for pruning; namespace=%q, resource=%v\", namespace, mapping.Resource)\n\tobjects, err := dynamicClient.Resource(mapping.Resource).Namespace(namespace).List(ctx, opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar pruneObjects []PruneObject\n\tfor i := range objects.Items {\n\t\tobj := \u0026objects.Items[i]\n\n\t\tuid := obj.GetUID()\n\t\tif visitedUids.Has(uid) {\n\t\t\tcontinue\n\t\t}\n\t\tname := obj.GetName()\n\t\tpruneObjects = append(pruneObjects, PruneObject{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tMapping: mapping,\n\t\t\tObject: obj,\n\t\t})\n\n\t}\n\treturn pruneObjects, nil\n}","line":{"from":142,"to":173}} {"id":100031408,"name":"deleteObjects","signature":"func (a *ApplySet) deleteObjects(ctx context.Context, dynamicClient dynamic.Interface, pruneObjects []PruneObject, opt *ApplySetDeleteOptions) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/applyset_pruner.go","code":"func (a *ApplySet) deleteObjects(ctx context.Context, dynamicClient dynamic.Interface, pruneObjects []PruneObject, opt *ApplySetDeleteOptions) error {\n\tfor i := range pruneObjects {\n\t\tpruneObject := \u0026pruneObjects[i]\n\n\t\tname := pruneObject.Name\n\t\tnamespace := pruneObject.Namespace\n\t\tmapping := pruneObject.Mapping\n\n\t\tif opt.DryRunStrategy != cmdutil.DryRunClient {\n\t\t\tif err := runDelete(ctx, namespace, name, mapping, dynamicClient, opt.CascadingStrategy, opt.GracePeriod, opt.DryRunStrategy == cmdutil.DryRunServer); err != nil {\n\t\t\t\treturn fmt.Errorf(\"pruning %v: %w\", pruneObject.String(), err)\n\t\t\t}\n\t\t}\n\n\t\topt.Printer.PrintObj(pruneObject.Object, opt.IOStreams.Out)\n\n\t}\n\treturn nil\n}","line":{"from":175,"to":193}} {"id":100031409,"name":"newPatcher","signature":"func newPatcher(o *ApplyOptions, info *resource.Info, helper *resource.Helper) (*Patcher, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/patcher.go","code":"func newPatcher(o *ApplyOptions, info *resource.Info, helper *resource.Helper) (*Patcher, error) {\n\tvar openapiSchema openapi.Resources\n\tif o.OpenAPIPatch {\n\t\topenapiSchema = o.OpenAPISchema\n\t}\n\n\treturn \u0026Patcher{\n\t\tMapping: info.Mapping,\n\t\tHelper: helper,\n\t\tOverwrite: o.Overwrite,\n\t\tBackOff: clockwork.NewRealClock(),\n\t\tForce: o.DeleteOptions.ForceDeletion,\n\t\tCascadingStrategy: o.DeleteOptions.CascadingStrategy,\n\t\tTimeout: o.DeleteOptions.Timeout,\n\t\tGracePeriod: o.DeleteOptions.GracePeriod,\n\t\tOpenapiSchema: openapiSchema,\n\t\tRetries: maxPatchRetry,\n\t}, nil\n}","line":{"from":79,"to":97}} {"id":100031410,"name":"delete","signature":"func (p *Patcher) delete(namespace, name string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/patcher.go","code":"func (p *Patcher) delete(namespace, name string) error {\n\toptions := asDeleteOptions(p.CascadingStrategy, p.GracePeriod)\n\t_, err := p.Helper.DeleteWithOptions(namespace, name, \u0026options)\n\treturn err\n}","line":{"from":99,"to":103}} {"id":100031411,"name":"patchSimple","signature":"func (p *Patcher) patchSimple(obj runtime.Object, modified []byte, namespace, name string, errOut io.Writer) ([]byte, runtime.Object, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/patcher.go","code":"func (p *Patcher) patchSimple(obj runtime.Object, modified []byte, namespace, name string, errOut io.Writer) ([]byte, runtime.Object, error) {\n\t// Serialize the current configuration of the object from the server.\n\tcurrent, err := runtime.Encode(unstructured.UnstructuredJSONScheme, obj)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrapf(err, \"serializing current configuration from:\\n%v\\nfor:\", obj)\n\t}\n\n\t// Retrieve the original configuration of the object from the annotation.\n\toriginal, err := util.GetOriginalConfiguration(obj)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrapf(err, \"retrieving original configuration from:\\n%v\\nfor:\", obj)\n\t}\n\n\tvar patchType types.PatchType\n\tvar patch []byte\n\n\tif p.OpenapiSchema != nil {\n\t\t// if openapischema is used, we'll try to get required patch type for this GVK from Open API.\n\t\t// if it fails or could not find any patch type, fall back to baked-in patch type determination.\n\t\tif patchType, err = p.getPatchTypeFromOpenAPI(p.Mapping.GroupVersionKind); err == nil \u0026\u0026 patchType == types.StrategicMergePatchType {\n\t\t\tpatch, err = p.buildStrategicMergeFromOpenAPI(original, modified, current)\n\t\t\tif err != nil {\n\t\t\t\t// Warn user about problem and continue strategic merge patching using builtin types.\n\t\t\t\tfmt.Fprintf(errOut, \"warning: error calculating patch from openapi spec: %v\\n\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif patch == nil {\n\t\tversionedObj, err := scheme.Scheme.New(p.Mapping.GroupVersionKind)\n\t\tif err == nil {\n\t\t\tpatchType = types.StrategicMergePatchType\n\t\t\tpatch, err = p.buildStrategicMergeFromBuiltins(versionedObj, original, modified, current)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, errors.Wrapf(err, createPatchErrFormat, original, modified, current)\n\t\t\t}\n\t\t} else {\n\t\t\tif !runtime.IsNotRegisteredError(err) {\n\t\t\t\treturn nil, nil, errors.Wrapf(err, \"getting instance of versioned object for %v:\", p.Mapping.GroupVersionKind)\n\t\t\t}\n\n\t\t\tpatchType = types.MergePatchType\n\t\t\tpatch, err = p.buildMergePatch(original, modified, current)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, errors.Wrapf(err, createPatchErrFormat, original, modified, current)\n\t\t\t}\n\t\t}\n\t}\n\n\tif string(patch) == \"{}\" {\n\t\treturn patch, obj, nil\n\t}\n\n\tif p.ResourceVersion != nil {\n\t\tpatch, err = addResourceVersion(patch, *p.ResourceVersion)\n\t\tif err != nil {\n\t\t\treturn nil, nil, errors.Wrap(err, \"Failed to insert resourceVersion in patch\")\n\t\t}\n\t}\n\n\tpatchedObj, err := p.Helper.Patch(namespace, name, patchType, patch, nil)\n\treturn patch, patchedObj, err\n}","line":{"from":105,"to":167}} {"id":100031412,"name":"buildMergePatch","signature":"func (p *Patcher) buildMergePatch(original, modified, current []byte) ([]byte, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/patcher.go","code":"// buildMergePatch builds patch according to the JSONMergePatch which is used for\n// custom resource definitions.\nfunc (p *Patcher) buildMergePatch(original, modified, current []byte) ([]byte, error) {\n\tpreconditions := []mergepatch.PreconditionFunc{mergepatch.RequireKeyUnchanged(\"apiVersion\"),\n\t\tmergepatch.RequireKeyUnchanged(\"kind\"), mergepatch.RequireMetadataKeyUnchanged(\"name\")}\n\tpatch, err := jsonmergepatch.CreateThreeWayJSONMergePatch(original, modified, current, preconditions...)\n\tif err != nil {\n\t\tif mergepatch.IsPreconditionFailed(err) {\n\t\t\treturn nil, fmt.Errorf(\"%s\", \"At least one of apiVersion, kind and name was changed\")\n\t\t}\n\t\treturn nil, err\n\t}\n\n\treturn patch, nil\n}","line":{"from":169,"to":183}} {"id":100031413,"name":"buildStrategicMergeFromOpenAPI","signature":"func (p *Patcher) buildStrategicMergeFromOpenAPI(original, modified, current []byte) ([]byte, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/patcher.go","code":"// buildStrategicMergeFromOpenAPI builds patch from OpenAPI if it is enabled.\n// This is used for core types which is published in openapi.\nfunc (p *Patcher) buildStrategicMergeFromOpenAPI(original, modified, current []byte) ([]byte, error) {\n\tschema := p.OpenapiSchema.LookupResource(p.Mapping.GroupVersionKind)\n\tif schema == nil {\n\t\t// Missing schema returns nil patch; also no error.\n\t\treturn nil, nil\n\t}\n\tlookupPatchMeta := strategicpatch.PatchMetaFromOpenAPI{Schema: schema}\n\tif openapiPatch, err := strategicpatch.CreateThreeWayMergePatch(original, modified, current, lookupPatchMeta, p.Overwrite); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\treturn openapiPatch, nil\n\t}\n}","line":{"from":185,"to":199}} {"id":100031414,"name":"getPatchTypeFromOpenAPI","signature":"func (p *Patcher) getPatchTypeFromOpenAPI(gvk schema.GroupVersionKind) (types.PatchType, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/patcher.go","code":"// getPatchTypeFromOpenAPI looks up patch types supported by given GroupVersionKind in Open API.\nfunc (p *Patcher) getPatchTypeFromOpenAPI(gvk schema.GroupVersionKind) (types.PatchType, error) {\n\tif pc := p.OpenapiSchema.GetConsumes(p.Mapping.GroupVersionKind, \"PATCH\"); pc != nil {\n\t\tfor _, c := range pc {\n\t\t\tif c == string(types.StrategicMergePatchType) {\n\t\t\t\treturn types.StrategicMergePatchType, nil\n\t\t\t}\n\t\t}\n\n\t\treturn types.MergePatchType, nil\n\t}\n\n\treturn types.MergePatchType, fmt.Errorf(\"unable to find any patch type for %s in Open API\", gvk)\n}","line":{"from":201,"to":214}} {"id":100031415,"name":"buildStrategicMergeFromBuiltins","signature":"func (p *Patcher) buildStrategicMergeFromBuiltins(versionedObj runtime.Object, original, modified, current []byte) ([]byte, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/patcher.go","code":"// buildStrategicMergeFromStruct builds patch from struct. This is used when\n// openapi endpoint is not working or user disables it by setting openapi-patch flag\n// to false.\nfunc (p *Patcher) buildStrategicMergeFromBuiltins(versionedObj runtime.Object, original, modified, current []byte) ([]byte, error) {\n\tlookupPatchMeta, err := strategicpatch.NewPatchMetaFromStruct(versionedObj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpatch, err := strategicpatch.CreateThreeWayMergePatch(original, modified, current, lookupPatchMeta, p.Overwrite)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn patch, nil\n}","line":{"from":216,"to":230}} {"id":100031416,"name":"Patch","signature":"func (p *Patcher) Patch(current runtime.Object, modified []byte, source, namespace, name string, errOut io.Writer) ([]byte, runtime.Object, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/patcher.go","code":"// Patch tries to patch an OpenAPI resource. On success, returns the merge patch as well\n// the final patched object. On failure, returns an error.\nfunc (p *Patcher) Patch(current runtime.Object, modified []byte, source, namespace, name string, errOut io.Writer) ([]byte, runtime.Object, error) {\n\tvar getErr error\n\tpatchBytes, patchObject, err := p.patchSimple(current, modified, namespace, name, errOut)\n\tif p.Retries == 0 {\n\t\tp.Retries = maxPatchRetry\n\t}\n\tfor i := 1; i \u003c= p.Retries \u0026\u0026 apierrors.IsConflict(err); i++ {\n\t\tif i \u003e triesBeforeBackOff {\n\t\t\tp.BackOff.Sleep(backOffPeriod)\n\t\t}\n\t\tcurrent, getErr = p.Helper.Get(namespace, name)\n\t\tif getErr != nil {\n\t\t\treturn nil, nil, getErr\n\t\t}\n\t\tpatchBytes, patchObject, err = p.patchSimple(current, modified, namespace, name, errOut)\n\t}\n\tif err != nil {\n\t\tif (apierrors.IsConflict(err) || apierrors.IsInvalid(err)) \u0026\u0026 p.Force {\n\t\t\tpatchBytes, patchObject, err = p.deleteAndCreate(current, modified, namespace, name)\n\t\t} else {\n\t\t\terr = cmdutil.AddSourceToErr(\"patching\", source, err)\n\t\t}\n\t}\n\treturn patchBytes, patchObject, err\n}","line":{"from":232,"to":258}} {"id":100031417,"name":"deleteAndCreate","signature":"func (p *Patcher) deleteAndCreate(original runtime.Object, modified []byte, namespace, name string) ([]byte, runtime.Object, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/patcher.go","code":"func (p *Patcher) deleteAndCreate(original runtime.Object, modified []byte, namespace, name string) ([]byte, runtime.Object, error) {\n\tif err := p.delete(namespace, name); err != nil {\n\t\treturn modified, nil, err\n\t}\n\t// TODO: use wait\n\tif err := wait.PollImmediate(1*time.Second, p.Timeout, func() (bool, error) {\n\t\tif _, err := p.Helper.Get(namespace, name); !apierrors.IsNotFound(err) {\n\t\t\treturn false, err\n\t\t}\n\t\treturn true, nil\n\t}); err != nil {\n\t\treturn modified, nil, err\n\t}\n\tversionedObject, _, err := unstructured.UnstructuredJSONScheme.Decode(modified, nil, nil)\n\tif err != nil {\n\t\treturn modified, nil, err\n\t}\n\tcreatedObject, err := p.Helper.Create(namespace, true, versionedObject)\n\tif err != nil {\n\t\t// restore the original object if we fail to create the new one\n\t\t// but still propagate and advertise error to user\n\t\trecreated, recreateErr := p.Helper.Create(namespace, true, original)\n\t\tif recreateErr != nil {\n\t\t\terr = fmt.Errorf(\"An error occurred force-replacing the existing object with the newly provided one:\\n\\n%v.\\n\\nAdditionally, an error occurred attempting to restore the original object:\\n\\n%v\", err, recreateErr)\n\t\t} else {\n\t\t\tcreatedObject = recreated\n\t\t}\n\t}\n\treturn modified, createdObject, err\n}","line":{"from":260,"to":289}} {"id":100031418,"name":"addResourceVersion","signature":"func addResourceVersion(patch []byte, rv string) ([]byte, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/patcher.go","code":"func addResourceVersion(patch []byte, rv string) ([]byte, error) {\n\tvar patchMap map[string]interface{}\n\terr := json.Unmarshal(patch, \u0026patchMap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tu := unstructured.Unstructured{Object: patchMap}\n\ta, err := meta.Accessor(\u0026u)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ta.SetResourceVersion(rv)\n\n\treturn json.Marshal(patchMap)\n}","line":{"from":291,"to":305}} {"id":100031419,"name":"newPruner","signature":"func newPruner(o *ApplyOptions) pruner","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/prune.go","code":"func newPruner(o *ApplyOptions) pruner {\n\treturn pruner{\n\t\tmapper: o.Mapper,\n\t\tdynamicClient: o.DynamicClient,\n\n\t\tlabelSelector: o.Selector,\n\t\tvisitedUids: o.VisitedUids,\n\t\tvisitedNamespaces: o.VisitedNamespaces,\n\n\t\tcascadingStrategy: o.DeleteOptions.CascadingStrategy,\n\t\tdryRunStrategy: o.DryRunStrategy,\n\t\tgracePeriod: o.DeleteOptions.GracePeriod,\n\n\t\ttoPrinter: o.ToPrinter,\n\n\t\tout: o.Out,\n\t}\n}","line":{"from":53,"to":70}} {"id":100031420,"name":"pruneAll","signature":"func (p *pruner) pruneAll(o *ApplyOptions) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/prune.go","code":"func (p *pruner) pruneAll(o *ApplyOptions) error {\n\n\tnamespacedRESTMappings, nonNamespacedRESTMappings, err := prune.GetRESTMappings(o.Mapper, o.PruneResources, o.Namespace != \"\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error retrieving RESTMappings to prune: %v\", err)\n\t}\n\n\tfor n := range p.visitedNamespaces {\n\t\tfor _, m := range namespacedRESTMappings {\n\t\t\tif err := p.prune(n, m); err != nil {\n\t\t\t\treturn fmt.Errorf(\"error pruning namespaced object %v: %v\", m.GroupVersionKind, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, m := range nonNamespacedRESTMappings {\n\t\tif err := p.prune(metav1.NamespaceNone, m); err != nil {\n\t\t\treturn fmt.Errorf(\"error pruning nonNamespaced object %v: %v\", m.GroupVersionKind, err)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":72,"to":94}} {"id":100031421,"name":"prune","signature":"func (p *pruner) prune(namespace string, mapping *meta.RESTMapping) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/prune.go","code":"func (p *pruner) prune(namespace string, mapping *meta.RESTMapping) error {\n\tobjList, err := p.dynamicClient.Resource(mapping.Resource).\n\t\tNamespace(namespace).\n\t\tList(context.TODO(), metav1.ListOptions{\n\t\t\tLabelSelector: p.labelSelector,\n\t\t\tFieldSelector: p.fieldSelector,\n\t\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tobjs, err := meta.ExtractList(objList)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, obj := range objs {\n\t\tmetadata, err := meta.Accessor(obj)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tannots := metadata.GetAnnotations()\n\t\tif _, ok := annots[corev1.LastAppliedConfigAnnotation]; !ok {\n\t\t\t// don't prune resources not created with apply\n\t\t\tcontinue\n\t\t}\n\t\tuid := metadata.GetUID()\n\t\tif p.visitedUids.Has(uid) {\n\t\t\tcontinue\n\t\t}\n\t\tname := metadata.GetName()\n\t\tif p.dryRunStrategy != cmdutil.DryRunClient {\n\t\t\tif err := p.delete(namespace, name, mapping); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tprinter, err := p.toPrinter(\"pruned\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tprinter.PrintObj(obj, p.out)\n\t}\n\treturn nil\n}","line":{"from":96,"to":140}} {"id":100031422,"name":"delete","signature":"func (p *pruner) delete(namespace, name string, mapping *meta.RESTMapping) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/prune.go","code":"func (p *pruner) delete(namespace, name string, mapping *meta.RESTMapping) error {\n\tctx := context.TODO()\n\treturn runDelete(ctx, namespace, name, mapping, p.dynamicClient, p.cascadingStrategy, p.gracePeriod, p.dryRunStrategy == cmdutil.DryRunServer)\n}","line":{"from":142,"to":145}} {"id":100031423,"name":"runDelete","signature":"func runDelete(ctx context.Context, namespace, name string, mapping *meta.RESTMapping, c dynamic.Interface, cascadingStrategy metav1.DeletionPropagation, gracePeriod int, serverDryRun bool) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/prune.go","code":"func runDelete(ctx context.Context, namespace, name string, mapping *meta.RESTMapping, c dynamic.Interface, cascadingStrategy metav1.DeletionPropagation, gracePeriod int, serverDryRun bool) error {\n\toptions := asDeleteOptions(cascadingStrategy, gracePeriod)\n\tif serverDryRun {\n\t\toptions.DryRun = []string{metav1.DryRunAll}\n\t}\n\treturn c.Resource(mapping.Resource).Namespace(namespace).Delete(ctx, name, options)\n}","line":{"from":147,"to":153}} {"id":100031424,"name":"asDeleteOptions","signature":"func asDeleteOptions(cascadingStrategy metav1.DeletionPropagation, gracePeriod int) metav1.DeleteOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/apply/prune.go","code":"func asDeleteOptions(cascadingStrategy metav1.DeletionPropagation, gracePeriod int) metav1.DeleteOptions {\n\toptions := metav1.DeleteOptions{}\n\tif gracePeriod \u003e= 0 {\n\t\toptions = *metav1.NewDeleteOptions(int64(gracePeriod))\n\t}\n\toptions.PropagationPolicy = \u0026cascadingStrategy\n\treturn options\n}","line":{"from":155,"to":162}} {"id":100031425,"name":"NewAttachOptions","signature":"func NewAttachOptions(streams genericclioptions.IOStreams) *AttachOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/attach/attach.go","code":"// NewAttachOptions creates the options for attach\nfunc NewAttachOptions(streams genericclioptions.IOStreams) *AttachOptions {\n\treturn \u0026AttachOptions{\n\t\tStreamOptions: exec.StreamOptions{\n\t\t\tIOStreams: streams,\n\t\t},\n\t\tAttach: \u0026DefaultRemoteAttach{},\n\t\tAttachFunc: DefaultAttachFunc,\n\t}\n}","line":{"from":90,"to":99}} {"id":100031426,"name":"NewCmdAttach","signature":"func NewCmdAttach(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/attach/attach.go","code":"// NewCmdAttach returns the attach Cobra command\nfunc NewCmdAttach(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\to := NewAttachOptions(streams)\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"attach (POD | TYPE/NAME) -c CONTAINER\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Attach to a running container\"),\n\t\tLong: i18n.T(\"Attach to a process that is already running inside an existing container.\"),\n\t\tExample: attachExample,\n\t\tValidArgsFunction: completion.PodResourceNameCompletionFunc(f),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\tcmdutil.AddPodRunningTimeoutFlag(cmd, defaultPodAttachTimeout)\n\tcmdutil.AddContainerVarFlags(cmd, \u0026o.ContainerName, o.ContainerName)\n\tcmd.Flags().BoolVarP(\u0026o.Stdin, \"stdin\", \"i\", o.Stdin, \"Pass stdin to the container\")\n\tcmd.Flags().BoolVarP(\u0026o.TTY, \"tty\", \"t\", o.TTY, \"Stdin is a TTY\")\n\tcmd.Flags().BoolVarP(\u0026o.Quiet, \"quiet\", \"q\", o.Quiet, \"Only print output from the remote session\")\n\treturn cmd\n}","line":{"from":101,"to":123}} {"id":100031427,"name":"DefaultAttachFunc","signature":"func DefaultAttachFunc(o *AttachOptions, containerToAttach *corev1.Container, raw bool, sizeQueue remotecommand.TerminalSizeQueue) func() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/attach/attach.go","code":"// DefaultAttachFunc is the default AttachFunc used\nfunc DefaultAttachFunc(o *AttachOptions, containerToAttach *corev1.Container, raw bool, sizeQueue remotecommand.TerminalSizeQueue) func() error {\n\treturn func() error {\n\t\trestClient, err := restclient.RESTClientFor(o.Config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treq := restClient.Post().\n\t\t\tResource(\"pods\").\n\t\t\tName(o.Pod.Name).\n\t\t\tNamespace(o.Pod.Namespace).\n\t\t\tSubResource(\"attach\")\n\t\treq.VersionedParams(\u0026corev1.PodAttachOptions{\n\t\t\tContainer: containerToAttach.Name,\n\t\t\tStdin: o.Stdin,\n\t\t\tStdout: o.Out != nil,\n\t\t\tStderr: !o.DisableStderr,\n\t\t\tTTY: raw,\n\t\t}, scheme.ParameterCodec)\n\n\t\treturn o.Attach.Attach(\"POST\", req.URL(), o.Config, o.In, o.Out, o.ErrOut, raw, sizeQueue)\n\t}\n}","line":{"from":130,"to":152}} {"id":100031428,"name":"Attach","signature":"func (*DefaultRemoteAttach) Attach(method string, url *url.URL, config *restclient.Config, stdin io.Reader, stdout, stderr io.Writer, tty bool, terminalSizeQueue remotecommand.TerminalSizeQueue) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/attach/attach.go","code":"// Attach executes attach to a running container\nfunc (*DefaultRemoteAttach) Attach(method string, url *url.URL, config *restclient.Config, stdin io.Reader, stdout, stderr io.Writer, tty bool, terminalSizeQueue remotecommand.TerminalSizeQueue) error {\n\texec, err := remotecommand.NewSPDYExecutor(config, method, url)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn exec.StreamWithContext(context.Background(), remotecommand.StreamOptions{\n\t\tStdin: stdin,\n\t\tStdout: stdout,\n\t\tStderr: stderr,\n\t\tTty: tty,\n\t\tTerminalSizeQueue: terminalSizeQueue,\n\t})\n}","line":{"from":157,"to":170}} {"id":100031429,"name":"Complete","signature":"func (o *AttachOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/attach/attach.go","code":"// Complete verifies command line arguments and loads data from the command environment\nfunc (o *AttachOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\to.Namespace, _, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.AttachablePodFn = polymorphichelpers.AttachablePodForObjectFn\n\n\to.GetPodTimeout, err = cmdutil.GetPodRunningTimeoutFlag(cmd)\n\tif err != nil {\n\t\treturn cmdutil.UsageErrorf(cmd, err.Error())\n\t}\n\n\to.Builder = f.NewBuilder\n\to.Resources = args\n\to.restClientGetter = f\n\n\tconfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.Config = config\n\n\tif o.CommandName == \"\" {\n\t\to.CommandName = cmd.CommandPath()\n\t}\n\n\treturn nil\n}","line":{"from":172,"to":202}} {"id":100031430,"name":"Validate","signature":"func (o *AttachOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/attach/attach.go","code":"// Validate checks that the provided attach options are specified.\nfunc (o *AttachOptions) Validate() error {\n\tif len(o.Resources) == 0 {\n\t\treturn fmt.Errorf(\"at least 1 argument is required for attach\")\n\t}\n\tif len(o.Resources) \u003e 2 {\n\t\treturn fmt.Errorf(\"expected POD, TYPE/NAME, or TYPE NAME, (at most 2 arguments) saw %d: %v\", len(o.Resources), o.Resources)\n\t}\n\tif o.GetPodTimeout \u003c= 0 {\n\t\treturn fmt.Errorf(\"--pod-running-timeout must be higher than zero\")\n\t}\n\n\treturn nil\n}","line":{"from":204,"to":217}} {"id":100031431,"name":"Run","signature":"func (o *AttachOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/attach/attach.go","code":"// Run executes a validated remote execution against a pod.\nfunc (o *AttachOptions) Run() error {\n\tif o.Pod == nil {\n\t\tb := o.Builder().\n\t\t\tWithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).\n\t\t\tNamespaceParam(o.Namespace).DefaultNamespace()\n\n\t\tswitch len(o.Resources) {\n\t\tcase 1:\n\t\t\tb.ResourceNames(\"pods\", o.Resources[0])\n\t\tcase 2:\n\t\t\tb.ResourceNames(o.Resources[0], o.Resources[1])\n\t\t}\n\n\t\tobj, err := b.Do().Object()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\to.Pod, err = o.findAttachablePod(obj)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif o.Pod.Status.Phase == corev1.PodSucceeded || o.Pod.Status.Phase == corev1.PodFailed {\n\t\t\treturn fmt.Errorf(\"cannot attach a container in a completed pod; current phase is %s\", o.Pod.Status.Phase)\n\t\t}\n\t\t// TODO: convert this to a clean \"wait\" behavior\n\t}\n\n\t// check for TTY\n\tcontainerToAttach, err := o.containerToAttachTo(o.Pod)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot attach to the container: %v\", err)\n\t}\n\tif o.TTY \u0026\u0026 !containerToAttach.TTY {\n\t\to.TTY = false\n\t\tif !o.Quiet \u0026\u0026 o.ErrOut != nil {\n\t\t\tfmt.Fprintf(o.ErrOut, \"error: Unable to use a TTY - container %s did not allocate one\\n\", containerToAttach.Name)\n\t\t}\n\t} else if !o.TTY \u0026\u0026 containerToAttach.TTY {\n\t\t// the container was launched with a TTY, so we have to force a TTY here, otherwise you'll get\n\t\t// an error \"Unrecognized input header\"\n\t\to.TTY = true\n\t}\n\n\t// ensure we can recover the terminal while attached\n\tt := o.SetupTTY()\n\n\tvar sizeQueue remotecommand.TerminalSizeQueue\n\tif t.Raw {\n\t\tif size := t.GetSize(); size != nil {\n\t\t\t// fake resizing +1 and then back to normal so that attach-detach-reattach will result in the\n\t\t\t// screen being redrawn\n\t\t\tsizePlusOne := *size\n\t\t\tsizePlusOne.Width++\n\t\t\tsizePlusOne.Height++\n\n\t\t\t// this call spawns a goroutine to monitor/update the terminal size\n\t\t\tsizeQueue = t.MonitorSize(\u0026sizePlusOne, size)\n\t\t}\n\n\t\to.DisableStderr = true\n\t}\n\n\tif !o.Quiet {\n\t\tfmt.Fprintln(o.ErrOut, \"If you don't see a command prompt, try pressing enter.\")\n\t}\n\tif err := t.Safe(o.AttachFunc(o, containerToAttach, t.Raw, sizeQueue)); err != nil {\n\t\treturn err\n\t}\n\n\tif msg := o.reattachMessage(containerToAttach.Name, t.Raw); msg != \"\" {\n\t\tfmt.Fprintln(o.Out, msg)\n\t}\n\treturn nil\n}","line":{"from":219,"to":295}} {"id":100031432,"name":"findAttachablePod","signature":"func (o *AttachOptions) findAttachablePod(obj runtime.Object) (*corev1.Pod, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/attach/attach.go","code":"func (o *AttachOptions) findAttachablePod(obj runtime.Object) (*corev1.Pod, error) {\n\tattachablePod, err := o.AttachablePodFn(o.restClientGetter, obj, o.GetPodTimeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\to.StreamOptions.PodName = attachablePod.Name\n\treturn attachablePod, nil\n}","line":{"from":297,"to":305}} {"id":100031433,"name":"containerToAttachTo","signature":"func (o *AttachOptions) containerToAttachTo(pod *corev1.Pod) (*corev1.Container, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/attach/attach.go","code":"// containerToAttach returns a reference to the container to attach to, given by name.\n// use the kubectl.kubernetes.io/default-container annotation for selecting the container to be attached\n// or the first container in the pod will be chosen If name is empty.\nfunc (o *AttachOptions) containerToAttachTo(pod *corev1.Pod) (*corev1.Container, error) {\n\treturn podcmd.FindOrDefaultContainerByName(pod, o.ContainerName, o.Quiet, o.ErrOut)\n}","line":{"from":307,"to":312}} {"id":100031434,"name":"GetContainerName","signature":"func (o *AttachOptions) GetContainerName(pod *corev1.Pod) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/attach/attach.go","code":"// GetContainerName returns the name of the container to attach to, with a fallback.\nfunc (o *AttachOptions) GetContainerName(pod *corev1.Pod) (string, error) {\n\tc, err := o.containerToAttachTo(pod)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn c.Name, nil\n}","line":{"from":314,"to":321}} {"id":100031435,"name":"reattachMessage","signature":"func (o *AttachOptions) reattachMessage(containerName string, rawTTY bool) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/attach/attach.go","code":"// reattachMessage returns a message to print after attach has completed, or\n// the empty string if no message should be printed.\nfunc (o *AttachOptions) reattachMessage(containerName string, rawTTY bool) string {\n\tif o.Quiet || !o.Stdin || !rawTTY || o.Pod.Spec.RestartPolicy != corev1.RestartPolicyAlways {\n\t\treturn \"\"\n\t}\n\tif _, path := podcmd.FindContainerByName(o.Pod, containerName); strings.HasPrefix(path, \"spec.ephemeralContainers\") {\n\t\treturn fmt.Sprintf(\"Session ended, the ephemeral container will not be restarted but may be reattached using '%s %s -c %s -i -t' if it is still running\", o.CommandName, o.Pod.Name, containerName)\n\t}\n\treturn fmt.Sprintf(\"Session ended, resume using '%s %s -c %s -i -t' command when the pod is running\", o.CommandName, o.Pod.Name, containerName)\n}","line":{"from":323,"to":333}} {"id":100031436,"name":"NewCmdAuth","signature":"func NewCmdAuth(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/auth.go","code":"// NewCmdAuth returns an initialized Command instance for 'auth' sub command\nfunc NewCmdAuth(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\t// Parent command to which all subcommands are added.\n\tcmds := \u0026cobra.Command{\n\t\tUse: \"auth\",\n\t\tShort: \"Inspect authorization\",\n\t\tLong: `Inspect authorization`,\n\t\tRun: cmdutil.DefaultSubCommandRun(streams.ErrOut),\n\t}\n\n\tcmds.AddCommand(NewCmdCanI(f, streams))\n\tcmds.AddCommand(NewCmdReconcile(f, streams))\n\tcmds.AddCommand(NewCmdWhoAmI(f, streams))\n\n\treturn cmds\n}","line":{"from":26,"to":41}} {"id":100031437,"name":"NewCmdCanI","signature":"func NewCmdCanI(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/cani.go","code":"// NewCmdCanI returns an initialized Command for 'auth can-i' sub command\nfunc NewCmdCanI(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\to := \u0026CanIOptions{\n\t\tIOStreams: streams,\n\t}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"can-i VERB [TYPE | TYPE/NAME | NONRESOURCEURL]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: \"Check whether an action is allowed\",\n\t\tLong: canILong,\n\t\tExample: canIExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tvar err error\n\t\t\tif o.List {\n\t\t\t\terr = o.RunAccessList()\n\t\t\t} else {\n\t\t\t\tvar allowed bool\n\t\t\t\tallowed, err = o.RunAccessCheck()\n\t\t\t\tif err == nil {\n\t\t\t\t\tif !allowed {\n\t\t\t\t\t\tos.Exit(1)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcmdutil.CheckErr(err)\n\t\t},\n\t}\n\n\tcmd.Flags().BoolVarP(\u0026o.AllNamespaces, \"all-namespaces\", \"A\", o.AllNamespaces, \"If true, check the specified action in all namespaces.\")\n\tcmd.Flags().BoolVarP(\u0026o.Quiet, \"quiet\", \"q\", o.Quiet, \"If true, suppress output and just return the exit code.\")\n\tcmd.Flags().StringVar(\u0026o.Subresource, \"subresource\", o.Subresource, \"SubResource such as pod/log or deployment/scale\")\n\tcmd.Flags().BoolVar(\u0026o.List, \"list\", o.List, \"If true, prints all allowed actions.\")\n\tcmd.Flags().BoolVar(\u0026o.NoHeaders, \"no-headers\", o.NoHeaders, \"If true, prints allowed actions without headers\")\n\treturn cmd\n}","line":{"from":112,"to":149}} {"id":100031438,"name":"Complete","signature":"func (o *CanIOptions) Complete(f cmdutil.Factory, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/cani.go","code":"// Complete completes all the required options\nfunc (o *CanIOptions) Complete(f cmdutil.Factory, args []string) error {\n\t// Set default WarningPrinter if not already set.\n\tif o.WarningPrinter == nil {\n\t\to.WarningPrinter = printers.NewWarningPrinter(o.ErrOut, printers.WarningPrinterOptions{Color: term.AllowsColorOutput(o.ErrOut)})\n\t}\n\n\tif o.List {\n\t\tif len(args) != 0 {\n\t\t\treturn errors.New(\"list option must be specified with no arguments\")\n\t\t}\n\t} else {\n\t\tif o.Quiet {\n\t\t\to.Out = io.Discard\n\t\t}\n\n\t\tswitch len(args) {\n\t\tcase 2:\n\t\t\to.Verb = args[0]\n\t\t\tif strings.HasPrefix(args[1], \"/\") {\n\t\t\t\to.NonResourceURL = args[1]\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tresourceTokens := strings.SplitN(args[1], \"/\", 2)\n\t\t\trestMapper, err := f.ToRESTMapper()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\to.Resource = o.resourceFor(restMapper, resourceTokens[0])\n\t\t\tif len(resourceTokens) \u003e 1 {\n\t\t\t\to.ResourceName = resourceTokens[1]\n\t\t\t}\n\t\tdefault:\n\t\t\terrString := \"you must specify two arguments: verb resource or verb resource/resourceName.\"\n\t\t\tusageString := \"See 'kubectl auth can-i -h' for help and examples.\"\n\t\t\treturn errors.New(fmt.Sprintf(\"%s\\n%s\", errString, usageString))\n\t\t}\n\t}\n\n\tvar err error\n\tclient, err := f.KubernetesClientSet()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.AuthClient = client.AuthorizationV1()\n\to.DiscoveryClient = client.Discovery()\n\to.Namespace = \"\"\n\tif !o.AllNamespaces {\n\t\to.Namespace, _, err = f.ToRawKubeConfigLoader().Namespace()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":151,"to":206}} {"id":100031439,"name":"Validate","signature":"func (o *CanIOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/cani.go","code":"// Validate makes sure provided values for CanIOptions are valid\nfunc (o *CanIOptions) Validate() error {\n\tif o.List {\n\t\tif o.Quiet || o.AllNamespaces || o.Subresource != \"\" {\n\t\t\treturn errors.New(\"list option can't be specified with neither quiet, all-namespaces nor subresource options\")\n\t\t}\n\t\treturn nil\n\t}\n\n\tif o.WarningPrinter == nil {\n\t\treturn fmt.Errorf(\"WarningPrinter can not be used without initialization\")\n\t}\n\n\tif o.NonResourceURL != \"\" {\n\t\tif o.Subresource != \"\" {\n\t\t\treturn fmt.Errorf(\"--subresource can not be used with NonResourceURL\")\n\t\t}\n\t\tif o.Resource != (schema.GroupVersionResource{}) || o.ResourceName != \"\" {\n\t\t\treturn fmt.Errorf(\"NonResourceURL and ResourceName can not specified together\")\n\t\t}\n\t\tif !isKnownNonResourceVerb(o.Verb) {\n\t\t\to.WarningPrinter.Print(fmt.Sprintf(\"verb '%s' is not a known verb\\n\", o.Verb))\n\t\t}\n\t} else if !o.Resource.Empty() \u0026\u0026 !o.AllNamespaces \u0026\u0026 o.DiscoveryClient != nil {\n\t\tif namespaced, err := isNamespaced(o.Resource, o.DiscoveryClient); err == nil \u0026\u0026 !namespaced {\n\t\t\tif len(o.Resource.Group) == 0 {\n\t\t\t\to.WarningPrinter.Print(fmt.Sprintf(\"resource '%s' is not namespace scoped\\n\", o.Resource.Resource))\n\t\t\t} else {\n\t\t\t\to.WarningPrinter.Print(fmt.Sprintf(\"resource '%s' is not namespace scoped in group '%s'\\n\", o.Resource.Resource, o.Resource.Group))\n\t\t\t}\n\t\t}\n\t\tif !isKnownResourceVerb(o.Verb) {\n\t\t\to.WarningPrinter.Print(fmt.Sprintf(\"verb '%s' is not a known verb\\n\", o.Verb))\n\t\t}\n\t}\n\n\tif o.NoHeaders {\n\t\treturn fmt.Errorf(\"--no-headers cannot be set without --list specified\")\n\t}\n\treturn nil\n}","line":{"from":208,"to":248}} {"id":100031440,"name":"RunAccessList","signature":"func (o *CanIOptions) RunAccessList() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/cani.go","code":"// RunAccessList lists all the access current user has\nfunc (o *CanIOptions) RunAccessList() error {\n\tsar := \u0026authorizationv1.SelfSubjectRulesReview{\n\t\tSpec: authorizationv1.SelfSubjectRulesReviewSpec{\n\t\t\tNamespace: o.Namespace,\n\t\t},\n\t}\n\tresponse, err := o.AuthClient.SelfSubjectRulesReviews().Create(context.TODO(), sar, metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn o.printStatus(response.Status)\n}","line":{"from":250,"to":263}} {"id":100031441,"name":"RunAccessCheck","signature":"func (o *CanIOptions) RunAccessCheck() (bool, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/cani.go","code":"// RunAccessCheck checks if user has access to a certain resource or non resource URL\nfunc (o *CanIOptions) RunAccessCheck() (bool, error) {\n\tvar sar *authorizationv1.SelfSubjectAccessReview\n\tif o.NonResourceURL == \"\" {\n\t\tsar = \u0026authorizationv1.SelfSubjectAccessReview{\n\t\t\tSpec: authorizationv1.SelfSubjectAccessReviewSpec{\n\t\t\t\tResourceAttributes: \u0026authorizationv1.ResourceAttributes{\n\t\t\t\t\tNamespace: o.Namespace,\n\t\t\t\t\tVerb: o.Verb,\n\t\t\t\t\tGroup: o.Resource.Group,\n\t\t\t\t\tResource: o.Resource.Resource,\n\t\t\t\t\tSubresource: o.Subresource,\n\t\t\t\t\tName: o.ResourceName,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t} else {\n\t\tsar = \u0026authorizationv1.SelfSubjectAccessReview{\n\t\t\tSpec: authorizationv1.SelfSubjectAccessReviewSpec{\n\t\t\t\tNonResourceAttributes: \u0026authorizationv1.NonResourceAttributes{\n\t\t\t\t\tVerb: o.Verb,\n\t\t\t\t\tPath: o.NonResourceURL,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\tresponse, err := o.AuthClient.SelfSubjectAccessReviews().Create(context.TODO(), sar, metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif response.Status.Allowed {\n\t\tfmt.Fprintln(o.Out, \"yes\")\n\t} else {\n\t\tfmt.Fprint(o.Out, \"no\")\n\t\tif len(response.Status.Reason) \u003e 0 {\n\t\t\tfmt.Fprintf(o.Out, \" - %v\", response.Status.Reason)\n\t\t}\n\t\tif len(response.Status.EvaluationError) \u003e 0 {\n\t\t\tfmt.Fprintf(o.Out, \" - %v\", response.Status.EvaluationError)\n\t\t}\n\t\tfmt.Fprintln(o.Out)\n\t}\n\n\treturn response.Status.Allowed, nil\n}","line":{"from":265,"to":310}} {"id":100031442,"name":"resourceFor","signature":"func (o *CanIOptions) resourceFor(mapper meta.RESTMapper, resourceArg string) schema.GroupVersionResource","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/cani.go","code":"func (o *CanIOptions) resourceFor(mapper meta.RESTMapper, resourceArg string) schema.GroupVersionResource {\n\tif resourceArg == \"*\" {\n\t\treturn schema.GroupVersionResource{Resource: resourceArg}\n\t}\n\n\tfullySpecifiedGVR, groupResource := schema.ParseResourceArg(strings.ToLower(resourceArg))\n\tgvr := schema.GroupVersionResource{}\n\tif fullySpecifiedGVR != nil {\n\t\tgvr, _ = mapper.ResourceFor(*fullySpecifiedGVR)\n\t}\n\tif gvr.Empty() {\n\t\tvar err error\n\t\tgvr, err = mapper.ResourceFor(groupResource.WithVersion(\"\"))\n\t\tif err != nil {\n\t\t\tif !nonStandardResourceNames.Has(groupResource.String()) {\n\t\t\t\tif len(groupResource.Group) == 0 {\n\t\t\t\t\to.WarningPrinter.Print(fmt.Sprintf(\"the server doesn't have a resource type '%s'\\n\", groupResource.Resource))\n\t\t\t\t} else {\n\t\t\t\t\to.WarningPrinter.Print(fmt.Sprintf(\"the server doesn't have a resource type '%s' in group '%s'\\n\", groupResource.Resource, groupResource.Group))\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn schema.GroupVersionResource{Resource: resourceArg}\n\t\t}\n\t}\n\n\treturn gvr\n}","line":{"from":312,"to":338}} {"id":100031443,"name":"printStatus","signature":"func (o *CanIOptions) printStatus(status authorizationv1.SubjectRulesReviewStatus) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/cani.go","code":"func (o *CanIOptions) printStatus(status authorizationv1.SubjectRulesReviewStatus) error {\n\tif status.Incomplete {\n\t\to.WarningPrinter.Print(fmt.Sprintf(\"the list may be incomplete: %v\", status.EvaluationError))\n\t}\n\n\tbreakdownRules := []rbacv1.PolicyRule{}\n\tfor _, rule := range convertToPolicyRule(status) {\n\t\tbreakdownRules = append(breakdownRules, rbacutil.BreakdownRule(rule)...)\n\t}\n\n\tcompactRules, err := rbacutil.CompactRules(breakdownRules)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsort.Stable(rbacutil.SortableRuleSlice(compactRules))\n\n\tw := printers.GetNewTabWriter(o.Out)\n\tdefer w.Flush()\n\n\tallErrs := []error{}\n\tif !o.NoHeaders {\n\t\tif err := printAccessHeaders(w); err != nil {\n\t\t\tallErrs = append(allErrs, err)\n\t\t}\n\t}\n\n\tif err := printAccess(w, compactRules); err != nil {\n\t\tallErrs = append(allErrs, err)\n\t}\n\treturn utilerrors.NewAggregate(allErrs)\n}","line":{"from":340,"to":370}} {"id":100031444,"name":"convertToPolicyRule","signature":"func convertToPolicyRule(status authorizationv1.SubjectRulesReviewStatus) []rbacv1.PolicyRule","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/cani.go","code":"func convertToPolicyRule(status authorizationv1.SubjectRulesReviewStatus) []rbacv1.PolicyRule {\n\tret := []rbacv1.PolicyRule{}\n\tfor _, resource := range status.ResourceRules {\n\t\tret = append(ret, rbacv1.PolicyRule{\n\t\t\tVerbs: resource.Verbs,\n\t\t\tAPIGroups: resource.APIGroups,\n\t\t\tResources: resource.Resources,\n\t\t\tResourceNames: resource.ResourceNames,\n\t\t})\n\t}\n\n\tfor _, nonResource := range status.NonResourceRules {\n\t\tret = append(ret, rbacv1.PolicyRule{\n\t\t\tVerbs: nonResource.Verbs,\n\t\t\tNonResourceURLs: nonResource.NonResourceURLs,\n\t\t})\n\t}\n\n\treturn ret\n}","line":{"from":372,"to":391}} {"id":100031445,"name":"printAccessHeaders","signature":"func printAccessHeaders(out io.Writer) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/cani.go","code":"func printAccessHeaders(out io.Writer) error {\n\tcolumnNames := []string{\"Resources\", \"Non-Resource URLs\", \"Resource Names\", \"Verbs\"}\n\t_, err := fmt.Fprintf(out, \"%s\\n\", strings.Join(columnNames, \"\\t\"))\n\treturn err\n}","line":{"from":393,"to":397}} {"id":100031446,"name":"printAccess","signature":"func printAccess(out io.Writer, rules []rbacv1.PolicyRule) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/cani.go","code":"func printAccess(out io.Writer, rules []rbacv1.PolicyRule) error {\n\tfor _, r := range rules {\n\t\tif _, err := fmt.Fprintf(out, \"%s\\t%v\\t%v\\t%v\\n\", describe.CombineResourceGroup(r.Resources, r.APIGroups), r.NonResourceURLs, r.ResourceNames, r.Verbs); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":399,"to":406}} {"id":100031447,"name":"isNamespaced","signature":"func isNamespaced(gvr schema.GroupVersionResource, discoveryClient discovery.DiscoveryInterface) (bool, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/cani.go","code":"func isNamespaced(gvr schema.GroupVersionResource, discoveryClient discovery.DiscoveryInterface) (bool, error) {\n\tif gvr.Resource == \"*\" {\n\t\treturn true, nil\n\t}\n\tapiResourceList, err := discoveryClient.ServerResourcesForGroupVersion(schema.GroupVersion{\n\t\tGroup: gvr.Group, Version: gvr.Version,\n\t}.String())\n\tif err != nil {\n\t\treturn true, err\n\t}\n\n\tfor _, resource := range apiResourceList.APIResources {\n\t\tif resource.Name == gvr.Resource {\n\t\t\treturn resource.Namespaced, nil\n\t\t}\n\t}\n\n\treturn false, fmt.Errorf(\"the server doesn't have a resource type '%s' in group '%s'\", gvr.Resource, gvr.Group)\n}","line":{"from":408,"to":426}} {"id":100031448,"name":"isKnownResourceVerb","signature":"func isKnownResourceVerb(s string) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/cani.go","code":"func isKnownResourceVerb(s string) bool {\n\treturn resourceVerbs.Has(s)\n}","line":{"from":428,"to":430}} {"id":100031449,"name":"isKnownNonResourceVerb","signature":"func isKnownNonResourceVerb(s string) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/cani.go","code":"func isKnownNonResourceVerb(s string) bool {\n\treturn nonResourceURLVerbs.Has(s)\n}","line":{"from":432,"to":434}} {"id":100031450,"name":"NewReconcileOptions","signature":"func NewReconcileOptions(ioStreams genericclioptions.IOStreams) *ReconcileOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/reconcile.go","code":"// NewReconcileOptions returns a new ReconcileOptions instance\nfunc NewReconcileOptions(ioStreams genericclioptions.IOStreams) *ReconcileOptions {\n\treturn \u0026ReconcileOptions{\n\t\tFilenameOptions: \u0026resource.FilenameOptions{},\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"reconciled\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":78,"to":85}} {"id":100031451,"name":"NewCmdReconcile","signature":"func NewCmdReconcile(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/reconcile.go","code":"// NewCmdReconcile holds the options for 'auth reconcile' sub command\nfunc NewCmdReconcile(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\to := NewReconcileOptions(streams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"reconcile -f FILENAME\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: \"Reconciles rules for RBAC role, role binding, cluster role, and cluster role binding objects\",\n\t\tLong: reconcileLong,\n\t\tExample: reconcileExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(cmd, f, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.RunReconcile())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddFilenameOptionFlags(cmd, o.FilenameOptions, \"identifying the resource to reconcile.\")\n\tcmd.Flags().BoolVar(\u0026o.RemoveExtraPermissions, \"remove-extra-permissions\", o.RemoveExtraPermissions, \"If true, removes extra permissions added to roles\")\n\tcmd.Flags().BoolVar(\u0026o.RemoveExtraSubjects, \"remove-extra-subjects\", o.RemoveExtraSubjects, \"If true, removes extra subjects added to rolebindings\")\n\tcmdutil.AddDryRunFlag(cmd)\n\n\treturn cmd\n}","line":{"from":87,"to":112}} {"id":100031452,"name":"Complete","signature":"func (o *ReconcileOptions) Complete(cmd *cobra.Command, f cmdutil.Factory, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/reconcile.go","code":"// Complete completes all the required options\nfunc (o *ReconcileOptions) Complete(cmd *cobra.Command, f cmdutil.Factory, args []string) error {\n\tif err := o.FilenameOptions.RequireFilenameOrKustomize(); err != nil {\n\t\treturn err\n\t}\n\n\tif len(args) \u003e 0 {\n\t\treturn errors.New(\"no arguments are allowed\")\n\t}\n\n\tdryRun, err := getClientSideDryRun(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\to.DryRun = dryRun\n\n\tnamespace, enforceNamespace, err := f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr := f.NewBuilder().\n\t\tWithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).\n\t\tContinueOnError().\n\t\tNamespaceParam(namespace).DefaultNamespace().\n\t\tFilenameParam(enforceNamespace, o.FilenameOptions).\n\t\tFlatten().\n\t\tLocal().\n\t\tDo()\n\n\tif err := r.Err(); err != nil {\n\t\treturn err\n\t}\n\to.Visitor = r\n\n\tclientConfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.RBACClient, err = rbacv1client.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\to.NamespaceClient, err = corev1client.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif o.DryRun {\n\t\to.PrintFlags.Complete(\"%s (dry run)\")\n\t}\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.PrintObject = printer.PrintObj\n\treturn nil\n}","line":{"from":114,"to":172}} {"id":100031453,"name":"Validate","signature":"func (o *ReconcileOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/reconcile.go","code":"// Validate makes sure provided values for ReconcileOptions are valid\nfunc (o *ReconcileOptions) Validate() error {\n\tif o.Visitor == nil {\n\t\treturn errors.New(\"ReconcileOptions.Visitor must be set\")\n\t}\n\tif o.RBACClient == nil {\n\t\treturn errors.New(\"ReconcileOptions.RBACClient must be set\")\n\t}\n\tif o.NamespaceClient == nil {\n\t\treturn errors.New(\"ReconcileOptions.NamespaceClient must be set\")\n\t}\n\tif o.PrintObject == nil {\n\t\treturn errors.New(\"ReconcileOptions.Print must be set\")\n\t}\n\tif o.Out == nil {\n\t\treturn errors.New(\"ReconcileOptions.Out must be set\")\n\t}\n\tif o.ErrOut == nil {\n\t\treturn errors.New(\"ReconcileOptions.Err must be set\")\n\t}\n\treturn nil\n}","line":{"from":174,"to":195}} {"id":100031454,"name":"RunReconcile","signature":"func (o *ReconcileOptions) RunReconcile() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/reconcile.go","code":"// RunReconcile performs the execution\nfunc (o *ReconcileOptions) RunReconcile() error {\n\treturn o.Visitor.Visit(func(info *resource.Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tswitch t := info.Object.(type) {\n\t\tcase *rbacv1.Role:\n\t\t\treconcileOptions := reconciliation.ReconcileRoleOptions{\n\t\t\t\tConfirm: !o.DryRun,\n\t\t\t\tRemoveExtraPermissions: o.RemoveExtraPermissions,\n\t\t\t\tRole: reconciliation.RoleRuleOwner{Role: t},\n\t\t\t\tClient: reconciliation.RoleModifier{\n\t\t\t\t\tNamespaceClient: o.NamespaceClient.Namespaces(),\n\t\t\t\t\tClient: o.RBACClient,\n\t\t\t\t},\n\t\t\t}\n\t\t\tresult, err := reconcileOptions.Run()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\to.printResults(result.Role.GetObject(), nil, nil, result.MissingRules, result.ExtraRules, result.Operation, result.Protected)\n\n\t\tcase *rbacv1.ClusterRole:\n\t\t\treconcileOptions := reconciliation.ReconcileRoleOptions{\n\t\t\t\tConfirm: !o.DryRun,\n\t\t\t\tRemoveExtraPermissions: o.RemoveExtraPermissions,\n\t\t\t\tRole: reconciliation.ClusterRoleRuleOwner{ClusterRole: t},\n\t\t\t\tClient: reconciliation.ClusterRoleModifier{\n\t\t\t\t\tClient: o.RBACClient.ClusterRoles(),\n\t\t\t\t},\n\t\t\t}\n\t\t\tresult, err := reconcileOptions.Run()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\to.printResults(result.Role.GetObject(), nil, nil, result.MissingRules, result.ExtraRules, result.Operation, result.Protected)\n\n\t\tcase *rbacv1.RoleBinding:\n\t\t\treconcileOptions := reconciliation.ReconcileRoleBindingOptions{\n\t\t\t\tConfirm: !o.DryRun,\n\t\t\t\tRemoveExtraSubjects: o.RemoveExtraSubjects,\n\t\t\t\tRoleBinding: reconciliation.RoleBindingAdapter{RoleBinding: t},\n\t\t\t\tClient: reconciliation.RoleBindingClientAdapter{\n\t\t\t\t\tClient: o.RBACClient,\n\t\t\t\t\tNamespaceClient: o.NamespaceClient.Namespaces(),\n\t\t\t\t},\n\t\t\t}\n\t\t\tresult, err := reconcileOptions.Run()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\to.printResults(result.RoleBinding.GetObject(), result.MissingSubjects, result.ExtraSubjects, nil, nil, result.Operation, result.Protected)\n\n\t\tcase *rbacv1.ClusterRoleBinding:\n\t\t\treconcileOptions := reconciliation.ReconcileRoleBindingOptions{\n\t\t\t\tConfirm: !o.DryRun,\n\t\t\t\tRemoveExtraSubjects: o.RemoveExtraSubjects,\n\t\t\t\tRoleBinding: reconciliation.ClusterRoleBindingAdapter{ClusterRoleBinding: t},\n\t\t\t\tClient: reconciliation.ClusterRoleBindingClientAdapter{\n\t\t\t\t\tClient: o.RBACClient.ClusterRoleBindings(),\n\t\t\t\t},\n\t\t\t}\n\t\t\tresult, err := reconcileOptions.Run()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\to.printResults(result.RoleBinding.GetObject(), result.MissingSubjects, result.ExtraSubjects, nil, nil, result.Operation, result.Protected)\n\n\t\tcase *rbacv1beta1.Role,\n\t\t\t*rbacv1beta1.RoleBinding,\n\t\t\t*rbacv1beta1.ClusterRole,\n\t\t\t*rbacv1beta1.ClusterRoleBinding,\n\t\t\t*rbacv1alpha1.Role,\n\t\t\t*rbacv1alpha1.RoleBinding,\n\t\t\t*rbacv1alpha1.ClusterRole,\n\t\t\t*rbacv1alpha1.ClusterRoleBinding:\n\t\t\treturn fmt.Errorf(\"only rbac.authorization.k8s.io/v1 is supported: not %T\", t)\n\n\t\tdefault:\n\t\t\tklog.V(1).Infof(\"skipping %#v\", info.Object.GetObjectKind())\n\t\t\t// skip ignored resources\n\t\t}\n\n\t\treturn nil\n\t})\n}","line":{"from":197,"to":284}} {"id":100031455,"name":"printResults","signature":"func (o *ReconcileOptions) printResults(object runtime.Object,","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/reconcile.go","code":"func (o *ReconcileOptions) printResults(object runtime.Object,\n\tmissingSubjects, extraSubjects []rbacv1.Subject,\n\tmissingRules, extraRules []rbacv1.PolicyRule,\n\toperation reconciliation.ReconcileOperation,\n\tprotected bool) {\n\n\to.PrintObject(object, o.Out)\n\n\tcaveat := \"\"\n\tif protected {\n\t\tcaveat = \", but object opted out (rbac.authorization.kubernetes.io/autoupdate: false)\"\n\t}\n\tswitch operation {\n\tcase reconciliation.ReconcileNone:\n\t\treturn\n\tcase reconciliation.ReconcileCreate:\n\t\tfmt.Fprintf(o.ErrOut, \"\\treconciliation required create%s\\n\", caveat)\n\tcase reconciliation.ReconcileUpdate:\n\t\tfmt.Fprintf(o.ErrOut, \"\\treconciliation required update%s\\n\", caveat)\n\tcase reconciliation.ReconcileRecreate:\n\t\tfmt.Fprintf(o.ErrOut, \"\\treconciliation required recreate%s\\n\", caveat)\n\t}\n\n\tif len(missingSubjects) \u003e 0 {\n\t\tfmt.Fprintf(o.ErrOut, \"\\tmissing subjects added:\\n\")\n\t\tfor _, s := range missingSubjects {\n\t\t\tfmt.Fprintf(o.ErrOut, \"\\t\\t%+v\\n\", s)\n\t\t}\n\t}\n\tif o.RemoveExtraSubjects {\n\t\tif len(extraSubjects) \u003e 0 {\n\t\t\tfmt.Fprintf(o.ErrOut, \"\\textra subjects removed:\\n\")\n\t\t\tfor _, s := range extraSubjects {\n\t\t\t\tfmt.Fprintf(o.ErrOut, \"\\t\\t%+v\\n\", s)\n\t\t\t}\n\t\t}\n\t}\n\tif len(missingRules) \u003e 0 {\n\t\tfmt.Fprintf(o.ErrOut, \"\\tmissing rules added:\\n\")\n\t\tfor _, r := range missingRules {\n\t\t\tfmt.Fprintf(o.ErrOut, \"\\t\\t%+v\\n\", r)\n\t\t}\n\t}\n\tif o.RemoveExtraPermissions {\n\t\tif len(extraRules) \u003e 0 {\n\t\t\tfmt.Fprintf(o.ErrOut, \"\\textra rules removed:\\n\")\n\t\t\tfor _, r := range extraRules {\n\t\t\t\tfmt.Fprintf(o.ErrOut, \"\\t\\t%+v\\n\", r)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":286,"to":337}} {"id":100031456,"name":"getClientSideDryRun","signature":"func getClientSideDryRun(cmd *cobra.Command) (bool, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/reconcile.go","code":"func getClientSideDryRun(cmd *cobra.Command) (bool, error) {\n\tdryRunStrategy, err := cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"error accessing --dry-run flag for command %s: %v\", cmd.Name(), err)\n\t}\n\tif dryRunStrategy == cmdutil.DryRunServer {\n\t\treturn false, fmt.Errorf(\"--dry-run=server for command %s is not supported yet\", cmd.Name())\n\t}\n\treturn dryRunStrategy == cmdutil.DryRunClient, nil\n}","line":{"from":339,"to":348}} {"id":100031457,"name":"NewWhoAmIFlags","signature":"func NewWhoAmIFlags(restClientGetter genericclioptions.RESTClientGetter, streams genericclioptions.IOStreams) *WhoAmIFlags","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/whoami.go","code":"// NewWhoAmIFlags returns a default WhoAmIFlags.\nfunc NewWhoAmIFlags(restClientGetter genericclioptions.RESTClientGetter, streams genericclioptions.IOStreams) *WhoAmIFlags {\n\treturn \u0026WhoAmIFlags{\n\t\tRESTClientGetter: restClientGetter,\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: streams,\n\t}\n}","line":{"from":51,"to":58}} {"id":100031458,"name":"AddFlags","signature":"func (flags *WhoAmIFlags) AddFlags(cmd *cobra.Command)","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/whoami.go","code":"// AddFlags registers flags for a cli.\nfunc (flags *WhoAmIFlags) AddFlags(cmd *cobra.Command) {\n\tflags.PrintFlags.AddFlags(cmd)\n}","line":{"from":60,"to":63}} {"id":100031459,"name":"ToOptions","signature":"func (flags *WhoAmIFlags) ToOptions(ctx context.Context, args []string) (*WhoAmIOptions, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/whoami.go","code":"// ToOptions converts from CLI inputs to runtime inputs.\nfunc (flags *WhoAmIFlags) ToOptions(ctx context.Context, args []string) (*WhoAmIOptions, error) {\n\tw := \u0026WhoAmIOptions{\n\t\tctx: ctx,\n\t\tIOStreams: flags.IOStreams,\n\t}\n\n\tclientConfig, err := flags.RESTClientGetter.ToRESTConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tw.authV1alpha1Client, err = authenticationv1alpha1client.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tw.authV1beta1Client, err = authenticationv1beta1client.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !flags.PrintFlags.OutputFlagSpecified() {\n\t\tw.resourcePrinterFunc = printTableSelfSubjectAccessReview\n\t} else {\n\t\tprinter, err := flags.PrintFlags.ToPrinter()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tw.resourcePrinterFunc = printer.PrintObj\n\t}\n\n\treturn w, nil\n}","line":{"from":65,"to":98}} {"id":100031460,"name":"NewCmdWhoAmI","signature":"func NewCmdWhoAmI(restClientGetter genericclioptions.RESTClientGetter, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/whoami.go","code":"// NewCmdWhoAmI returns an initialized Command for 'auth whoami' sub command. Experimental.\nfunc NewCmdWhoAmI(restClientGetter genericclioptions.RESTClientGetter, streams genericclioptions.IOStreams) *cobra.Command {\n\tflags := NewWhoAmIFlags(restClientGetter, streams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"whoami\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: \"Experimental: Check self subject attributes\",\n\t\tLong: whoAmILong,\n\t\tExample: whoAmIExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\to, err := flags.ToOptions(cmd.Context(), args)\n\t\t\tcmdutil.CheckErr(err)\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\tflags.AddFlags(cmd)\n\treturn cmd\n}","line":{"from":131,"to":150}} {"id":100031461,"name":"Run","signature":"func (o WhoAmIOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/whoami.go","code":"// Run prints all user attributes.\nfunc (o WhoAmIOptions) Run() error {\n\tvar (\n\t\tres runtime.Object\n\t\terr error\n\t)\n\n\tres, err = o.authV1beta1Client.\n\t\tSelfSubjectReviews().\n\t\tCreate(context.TODO(), \u0026authenticationv1beta1.SelfSubjectReview{}, metav1.CreateOptions{})\n\tif err != nil \u0026\u0026 errors.IsNotFound(err) {\n\t\t// Fallback to Alpha API if Beta is not enabled\n\t\tres, err = o.authV1alpha1Client.\n\t\t\tSelfSubjectReviews().\n\t\t\tCreate(context.TODO(), \u0026authenticationv1alpha1.SelfSubjectReview{}, metav1.CreateOptions{})\n\t}\n\tif err != nil {\n\t\tswitch {\n\t\tcase errors.IsForbidden(err):\n\t\t\treturn forbiddenErr\n\t\tcase errors.IsNotFound(err):\n\t\t\treturn notEnabledErr\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\treturn o.resourcePrinterFunc(res, o.Out)\n}","line":{"from":161,"to":188}} {"id":100031462,"name":"getUserInfo","signature":"func getUserInfo(obj runtime.Object) (authenticationv1.UserInfo, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/whoami.go","code":"func getUserInfo(obj runtime.Object) (authenticationv1.UserInfo, error) {\n\tswitch obj.(type) {\n\tcase *authenticationv1alpha1.SelfSubjectReview:\n\t\treturn obj.(*authenticationv1alpha1.SelfSubjectReview).Status.UserInfo, nil\n\tcase *authenticationv1beta1.SelfSubjectReview:\n\t\treturn obj.(*authenticationv1beta1.SelfSubjectReview).Status.UserInfo, nil\n\tdefault:\n\t\treturn authenticationv1.UserInfo{}, fmt.Errorf(\"unexpected response type %T, expected SelfSubjectReview\", obj)\n\t}\n}","line":{"from":190,"to":199}} {"id":100031463,"name":"printTableSelfSubjectAccessReview","signature":"func printTableSelfSubjectAccessReview(obj runtime.Object, out io.Writer) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/auth/whoami.go","code":"func printTableSelfSubjectAccessReview(obj runtime.Object, out io.Writer) error {\n\tui, err := getUserInfo(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tw := printers.GetNewTabWriter(out)\n\tdefer w.Flush()\n\n\t_, err = fmt.Fprintf(w, \"ATTRIBUTE\\tVALUE\\n\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot write a header: %w\", err)\n\t}\n\n\tif ui.Username != \"\" {\n\t\t_, err := fmt.Fprintf(w, \"Username\\t%s\\n\", ui.Username)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"cannot write a username: %w\", err)\n\t\t}\n\t}\n\n\tif ui.UID != \"\" {\n\t\t_, err := fmt.Fprintf(w, \"UID\\t%s\\n\", ui.UID)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"cannot write a uid: %w\", err)\n\t\t}\n\t}\n\n\tif len(ui.Groups) \u003e 0 {\n\t\t_, err := fmt.Fprintf(w, \"Groups\\t%v\\n\", ui.Groups)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"cannot write groups: %w\", err)\n\t\t}\n\t}\n\n\tif len(ui.Extra) \u003e 0 {\n\t\tfor _, k := range sets.StringKeySet(ui.Extra).List() {\n\t\t\tv := ui.Extra[k]\n\t\t\t_, err := fmt.Fprintf(w, \"Extra: %s\\t%v\\n\", k, v)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"cannot write an extra: %w\", err)\n\t\t\t}\n\t\t}\n\n\t}\n\treturn nil\n}","line":{"from":201,"to":247}} {"id":100031464,"name":"NewAutoscaleOptions","signature":"func NewAutoscaleOptions(ioStreams genericclioptions.IOStreams) *AutoscaleOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/autoscale/autoscale.go","code":"// NewAutoscaleOptions creates the options for autoscale\nfunc NewAutoscaleOptions(ioStreams genericclioptions.IOStreams) *AutoscaleOptions {\n\treturn \u0026AutoscaleOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"autoscaled\").WithTypeSetter(scheme.Scheme),\n\t\tFilenameOptions: \u0026resource.FilenameOptions{},\n\t\tRecordFlags: genericclioptions.NewRecordFlags(),\n\t\tRecorder: genericclioptions.NoopRecorder{},\n\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":86,"to":96}} {"id":100031465,"name":"NewCmdAutoscale","signature":"func NewCmdAutoscale(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/autoscale/autoscale.go","code":"// NewCmdAutoscale returns the autoscale Cobra command\nfunc NewCmdAutoscale(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewAutoscaleOptions(ioStreams)\n\n\tvalidArgs := []string{\"deployment\", \"replicaset\", \"replicationcontroller\", \"statefulset\"}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"autoscale (-f FILENAME | TYPE NAME | TYPE/NAME) [--min=MINPODS] --max=MAXPODS [--cpu-percent=CPU]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Auto-scale a deployment, replica set, stateful set, or replication controller\"),\n\t\tLong: autoscaleLong,\n\t\tExample: autoscaleExample,\n\t\tValidArgsFunction: completion.SpecifiedResourceTypeAndNameCompletionFunc(f, validArgs),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\t// bind flag structs\n\to.RecordFlags.AddFlags(cmd)\n\to.PrintFlags.AddFlags(cmd)\n\tcmd.Flags().Int32Var(\u0026o.Min, \"min\", -1, \"The lower limit for the number of pods that can be set by the autoscaler. If it's not specified or negative, the server will apply a default value.\")\n\tcmd.Flags().Int32Var(\u0026o.Max, \"max\", -1, \"The upper limit for the number of pods that can be set by the autoscaler. Required.\")\n\tcmd.MarkFlagRequired(\"max\")\n\tcmd.Flags().Int32Var(\u0026o.CPUPercent, \"cpu-percent\", -1, \"The target average CPU utilization (represented as a percent of requested CPU) over all the pods. If it's not specified or negative, a default autoscaling policy will be used.\")\n\tcmd.Flags().StringVar(\u0026o.Name, \"name\", \"\", i18n.T(\"The name for the newly created object. If not specified, the name of the input resource will be used.\"))\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmdutil.AddFilenameOptionFlags(cmd, o.FilenameOptions, \"identifying the resource to autoscale.\")\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.fieldManager, \"kubectl-autoscale\")\n\treturn cmd\n}","line":{"from":98,"to":131}} {"id":100031466,"name":"Complete","signature":"func (o *AutoscaleOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/autoscale/autoscale.go","code":"// Complete verifies command line arguments and loads data from the command environment\nfunc (o *AutoscaleOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\to.dryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdiscoveryClient, err := f.ToDiscoveryClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.createAnnotation = cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag)\n\to.builder = f.NewBuilder()\n\to.scaleKindResolver = scale.NewDiscoveryScaleKindResolver(discoveryClient)\n\to.args = args\n\to.RecordFlags.Complete(cmd)\n\n\to.Recorder, err = o.RecordFlags.ToRecorder()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tkubeClient, err := f.KubernetesClientSet()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.HPAClient = kubeClient.AutoscalingV1()\n\n\to.namespace, o.enforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.ToPrinter = func(operation string) (printers.ResourcePrinter, error) {\n\t\to.PrintFlags.NamePrintFlags.Operation = operation\n\t\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.dryRunStrategy)\n\n\t\treturn o.PrintFlags.ToPrinter()\n\t}\n\n\treturn nil\n}","line":{"from":133,"to":174}} {"id":100031467,"name":"Validate","signature":"func (o *AutoscaleOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/autoscale/autoscale.go","code":"// Validate checks that the provided attach options are specified.\nfunc (o *AutoscaleOptions) Validate() error {\n\tif o.Max \u003c 1 {\n\t\treturn fmt.Errorf(\"--max=MAXPODS is required and must be at least 1, max: %d\", o.Max)\n\t}\n\tif o.Max \u003c o.Min {\n\t\treturn fmt.Errorf(\"--max=MAXPODS must be larger or equal to --min=MINPODS, max: %d, min: %d\", o.Max, o.Min)\n\t}\n\n\treturn nil\n}","line":{"from":176,"to":186}} {"id":100031468,"name":"Run","signature":"func (o *AutoscaleOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/autoscale/autoscale.go","code":"// Run performs the execution\nfunc (o *AutoscaleOptions) Run() error {\n\tr := o.builder.\n\t\tUnstructured().\n\t\tContinueOnError().\n\t\tNamespaceParam(o.namespace).DefaultNamespace().\n\t\tFilenameParam(o.enforceNamespace, o.FilenameOptions).\n\t\tResourceTypeOrNameArgs(false, o.args...).\n\t\tFlatten().\n\t\tDo()\n\tif err := r.Err(); err != nil {\n\t\treturn err\n\t}\n\n\tcount := 0\n\terr := r.Visit(func(info *resource.Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tmapping := info.ResourceMapping()\n\t\tgvr := mapping.GroupVersionKind.GroupVersion().WithResource(mapping.Resource.Resource)\n\t\tif _, err := o.scaleKindResolver.ScaleForResource(gvr); err != nil {\n\t\t\treturn fmt.Errorf(\"cannot autoscale a %v: %v\", mapping.GroupVersionKind.Kind, err)\n\t\t}\n\n\t\thpa := o.createHorizontalPodAutoscaler(info.Name, mapping)\n\n\t\tif err := o.Recorder.Record(hpa); err != nil {\n\t\t\tklog.V(4).Infof(\"error recording current command: %v\", err)\n\t\t}\n\n\t\tif o.dryRunStrategy == cmdutil.DryRunClient {\n\t\t\tcount++\n\n\t\t\tprinter, err := o.ToPrinter(\"created\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn printer.PrintObj(hpa, o.Out)\n\t\t}\n\n\t\tif err := util.CreateOrUpdateAnnotation(o.createAnnotation, hpa, scheme.DefaultJSONEncoder()); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcreateOptions := metav1.CreateOptions{}\n\t\tif o.fieldManager != \"\" {\n\t\t\tcreateOptions.FieldManager = o.fieldManager\n\t\t}\n\t\tif o.dryRunStrategy == cmdutil.DryRunServer {\n\t\t\tcreateOptions.DryRun = []string{metav1.DryRunAll}\n\t\t}\n\t\tactualHPA, err := o.HPAClient.HorizontalPodAutoscalers(o.namespace).Create(context.TODO(), hpa, createOptions)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcount++\n\t\tprinter, err := o.ToPrinter(\"autoscaled\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn printer.PrintObj(actualHPA, o.Out)\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tif count == 0 {\n\t\treturn fmt.Errorf(\"no objects passed to autoscale\")\n\t}\n\treturn nil\n}","line":{"from":188,"to":260}} {"id":100031469,"name":"createHorizontalPodAutoscaler","signature":"func (o *AutoscaleOptions) createHorizontalPodAutoscaler(refName string, mapping *meta.RESTMapping) *autoscalingv1.HorizontalPodAutoscaler","file":"staging/src/k8s.io/kubectl/pkg/cmd/autoscale/autoscale.go","code":"func (o *AutoscaleOptions) createHorizontalPodAutoscaler(refName string, mapping *meta.RESTMapping) *autoscalingv1.HorizontalPodAutoscaler {\n\tname := o.Name\n\tif len(name) == 0 {\n\t\tname = refName\n\t}\n\n\tscaler := autoscalingv1.HorizontalPodAutoscaler{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t},\n\t\tSpec: autoscalingv1.HorizontalPodAutoscalerSpec{\n\t\t\tScaleTargetRef: autoscalingv1.CrossVersionObjectReference{\n\t\t\t\tAPIVersion: mapping.GroupVersionKind.GroupVersion().String(),\n\t\t\t\tKind: mapping.GroupVersionKind.Kind,\n\t\t\t\tName: refName,\n\t\t\t},\n\t\t\tMaxReplicas: o.Max,\n\t\t},\n\t}\n\n\tif o.Min \u003e 0 {\n\t\tv := int32(o.Min)\n\t\tscaler.Spec.MinReplicas = \u0026v\n\t}\n\tif o.CPUPercent \u003e= 0 {\n\t\tc := int32(o.CPUPercent)\n\t\tscaler.Spec.TargetCPUUtilizationPercentage = \u0026c\n\t}\n\n\treturn \u0026scaler\n}","line":{"from":262,"to":292}} {"id":100031470,"name":"NewCmdCertificate","signature":"func NewCmdCertificate(restClientGetter genericclioptions.RESTClientGetter, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/certificates/certificates.go","code":"// NewCmdCertificate returns `certificate` Cobra command\nfunc NewCmdCertificate(restClientGetter genericclioptions.RESTClientGetter, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"certificate SUBCOMMAND\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Modify certificate resources.\"),\n\t\tLong: i18n.T(\"Modify certificate resources.\"),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmd.Help()\n\t\t},\n\t}\n\n\tcmd.AddCommand(NewCmdCertificateApprove(restClientGetter, ioStreams))\n\tcmd.AddCommand(NewCmdCertificateDeny(restClientGetter, ioStreams))\n\n\treturn cmd\n}","line":{"from":42,"to":58}} {"id":100031471,"name":"NewCertificateOptions","signature":"func NewCertificateOptions(ioStreams genericclioptions.IOStreams, operation string) *CertificateOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/certificates/certificates.go","code":"// NewCertificateOptions creates CertificateOptions struct for `certificate` command\nfunc NewCertificateOptions(ioStreams genericclioptions.IOStreams, operation string) *CertificateOptions {\n\treturn \u0026CertificateOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(operation).WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":76,"to":82}} {"id":100031472,"name":"Complete","signature":"func (o *CertificateOptions) Complete(restClientGetter genericclioptions.RESTClientGetter, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/certificates/certificates.go","code":"// Complete loads data from the command environment\nfunc (o *CertificateOptions) Complete(restClientGetter genericclioptions.RESTClientGetter, cmd *cobra.Command, args []string) error {\n\to.csrNames = args\n\to.outputStyle = cmdutil.GetFlagString(cmd, \"output\")\n\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.PrintObj = func(obj runtime.Object, out io.Writer) error {\n\t\treturn printer.PrintObj(obj, out)\n\t}\n\n\to.builder = resource.NewBuilder(restClientGetter)\n\n\tclientConfig, err := restClientGetter.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.certificatesV1Client, err = v1.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":84,"to":111}} {"id":100031473,"name":"Validate","signature":"func (o *CertificateOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/certificates/certificates.go","code":"// Validate checks if the provided `certificate` arguments are valid\nfunc (o *CertificateOptions) Validate() error {\n\tif len(o.csrNames) \u003c 1 \u0026\u0026 cmdutil.IsFilenameSliceEmpty(o.Filenames, o.Kustomize) {\n\t\treturn fmt.Errorf(\"one or more CSRs must be specified as \u003cname\u003e or -f \u003cfilename\u003e\")\n\t}\n\treturn nil\n}","line":{"from":113,"to":119}} {"id":100031474,"name":"NewCmdCertificateApprove","signature":"func NewCmdCertificateApprove(restClientGetter genericclioptions.RESTClientGetter, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/certificates/certificates.go","code":"// NewCmdCertificateApprove returns the `certificate approve` Cobra command\nfunc NewCmdCertificateApprove(restClientGetter genericclioptions.RESTClientGetter, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewCertificateOptions(ioStreams, \"approved\")\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"approve (-f FILENAME | NAME)\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Approve a certificate signing request\"),\n\t\tLong: templates.LongDesc(i18n.T(`\n\t\tApprove a certificate signing request.\n\n\t\tkubectl certificate approve allows a cluster admin to approve a certificate\n\t\tsigning request (CSR). This action tells a certificate signing controller to\n\t\tissue a certificate to the requestor with the attributes requested in the CSR.\n\n\t\tSECURITY NOTICE: Depending on the requested attributes, the issued certificate\n\t\tcan potentially grant a requester access to cluster resources or to authenticate\n\t\tas a requested identity. Before approving a CSR, ensure you understand what the\n\t\tsigned certificate can do.\n\t\t`)),\n\t\tExample: templates.Examples(i18n.T(`\n\t\t\t# Approve CSR 'csr-sqgzp'\n\t\t\tkubectl certificate approve csr-sqgzp\n\t\t`)),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(restClientGetter, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.RunCertificateApprove(cmdutil.GetFlagBool(cmd, \"force\")))\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmd.Flags().Bool(\"force\", false, \"Update the CSR even if it is already approved.\")\n\tcmdutil.AddFilenameOptionFlags(cmd, \u0026o.FilenameOptions, \"identifying the resource to update\")\n\n\treturn cmd\n}","line":{"from":121,"to":158}} {"id":100031475,"name":"RunCertificateApprove","signature":"func (o *CertificateOptions) RunCertificateApprove(force bool) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/certificates/certificates.go","code":"// RunCertificateApprove approves a certificate signing request\nfunc (o *CertificateOptions) RunCertificateApprove(force bool) error {\n\treturn o.modifyCertificateCondition(\n\t\to.builder,\n\t\tforce,\n\t\taddConditionIfNeeded(string(certificatesv1.CertificateDenied), string(certificatesv1.CertificateApproved), \"KubectlApprove\", \"This CSR was approved by kubectl certificate approve.\"),\n\t)\n}","line":{"from":160,"to":167}} {"id":100031476,"name":"NewCmdCertificateDeny","signature":"func NewCmdCertificateDeny(restClientGetter genericclioptions.RESTClientGetter, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/certificates/certificates.go","code":"// NewCmdCertificateDeny returns the `certificate deny` Cobra command\nfunc NewCmdCertificateDeny(restClientGetter genericclioptions.RESTClientGetter, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewCertificateOptions(ioStreams, \"denied\")\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"deny (-f FILENAME | NAME)\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Deny a certificate signing request\"),\n\t\tLong: templates.LongDesc(i18n.T(`\n\t\tDeny a certificate signing request.\n\n\t\tkubectl certificate deny allows a cluster admin to deny a certificate\n\t\tsigning request (CSR). This action tells a certificate signing controller to\n\t\tnot to issue a certificate to the requestor.\n\t\t`)),\n\t\tExample: templates.Examples(i18n.T(`\n\t\t\t# Deny CSR 'csr-sqgzp'\n\t\t\tkubectl certificate deny csr-sqgzp\n\t\t`)),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(restClientGetter, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.RunCertificateDeny(cmdutil.GetFlagBool(cmd, \"force\")))\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmd.Flags().Bool(\"force\", false, \"Update the CSR even if it is already denied.\")\n\tcmdutil.AddFilenameOptionFlags(cmd, \u0026o.FilenameOptions, \"identifying the resource to update\")\n\n\treturn cmd\n}","line":{"from":169,"to":201}} {"id":100031477,"name":"RunCertificateDeny","signature":"func (o *CertificateOptions) RunCertificateDeny(force bool) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/certificates/certificates.go","code":"// RunCertificateDeny denies a certificate signing request\nfunc (o *CertificateOptions) RunCertificateDeny(force bool) error {\n\treturn o.modifyCertificateCondition(\n\t\to.builder,\n\t\tforce,\n\t\taddConditionIfNeeded(string(certificatesv1.CertificateApproved), string(certificatesv1.CertificateDenied), \"KubectlDeny\", \"This CSR was denied by kubectl certificate deny.\"),\n\t)\n}","line":{"from":203,"to":210}} {"id":100031478,"name":"modifyCertificateCondition","signature":"func (o *CertificateOptions) modifyCertificateCondition(builder *resource.Builder, force bool, modify func(csr runtime.Object) (runtime.Object, bool, error)) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/certificates/certificates.go","code":"func (o *CertificateOptions) modifyCertificateCondition(builder *resource.Builder, force bool, modify func(csr runtime.Object) (runtime.Object, bool, error)) error {\n\tvar found int\n\tr := builder.\n\t\tUnstructured().\n\t\tContinueOnError().\n\t\tFilenameParam(false, \u0026o.FilenameOptions).\n\t\tResourceNames(\"certificatesigningrequests\", o.csrNames...).\n\t\tRequireObject(true).\n\t\tFlatten().\n\t\tLatest().\n\t\tDo()\n\terr := r.Visit(func(info *resource.Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor i := 0; ; i++ {\n\t\t\tobj, ok := info.Object.(*unstructured.Unstructured)\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"expected *unstructured.Unstructured, got %T\", obj)\n\t\t\t}\n\t\t\tif want, got := certificatesv1.Kind(\"CertificateSigningRequest\"), obj.GetObjectKind().GroupVersionKind().GroupKind(); want != got {\n\t\t\t\treturn fmt.Errorf(\"can only handle %s objects, got %s\", want.String(), got.String())\n\t\t\t}\n\t\t\tvar csr runtime.Object\n\t\t\t// get a typed object\n\t\t\tcsr, err = o.certificatesV1Client.CertificateSigningRequests().Get(context.TODO(), obj.GetName(), metav1.GetOptions{})\n\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\treturn fmt.Errorf(\"could not find v1 version of %s: %v\", obj.GetName(), err)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tmodifiedCSR, hasCondition, err := modify(csr)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !hasCondition || force {\n\t\t\t\tif mCSR, ok := modifiedCSR.(*certificatesv1.CertificateSigningRequest); ok {\n\t\t\t\t\t_, err = o.certificatesV1Client.CertificateSigningRequests().UpdateApproval(context.TODO(), mCSR.Name, mCSR, metav1.UpdateOptions{})\n\t\t\t\t} else {\n\t\t\t\t\treturn fmt.Errorf(\"can only handle certificates.k8s.io CertificateSigningRequest objects, got %T\", mCSR)\n\t\t\t\t}\n\n\t\t\t\tif apierrors.IsConflict(err) \u0026\u0026 i \u003c 10 {\n\t\t\t\t\tif err := info.Get(); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tfound++\n\n\t\treturn o.PrintObj(info.Object, o.Out)\n\t})\n\tif found == 0 \u0026\u0026 err == nil {\n\t\tfmt.Fprintf(o.Out, \"No resources found\\n\")\n\t}\n\treturn err\n}","line":{"from":212,"to":276}} {"id":100031479,"name":"addConditionIfNeeded","signature":"func addConditionIfNeeded(mustNotHaveConditionType, conditionType, reason, message string) func(runtime.Object) (runtime.Object, bool, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/certificates/certificates.go","code":"func addConditionIfNeeded(mustNotHaveConditionType, conditionType, reason, message string) func(runtime.Object) (runtime.Object, bool, error) {\n\treturn func(obj runtime.Object) (runtime.Object, bool, error) {\n\t\tif csr, ok := obj.(*certificatesv1.CertificateSigningRequest); ok {\n\t\t\tvar alreadyHasCondition bool\n\t\t\tfor _, c := range csr.Status.Conditions {\n\t\t\t\tif string(c.Type) == mustNotHaveConditionType {\n\t\t\t\t\treturn nil, false, fmt.Errorf(\"certificate signing request %q is already %s\", csr.Name, c.Type)\n\t\t\t\t}\n\t\t\t\tif string(c.Type) == conditionType {\n\t\t\t\t\talreadyHasCondition = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif alreadyHasCondition {\n\t\t\t\treturn csr, true, nil\n\t\t\t}\n\t\t\tcsr.Status.Conditions = append(csr.Status.Conditions, certificatesv1.CertificateSigningRequestCondition{\n\t\t\t\tType: certificatesv1.RequestConditionType(conditionType),\n\t\t\t\tStatus: corev1.ConditionTrue,\n\t\t\t\tReason: reason,\n\t\t\t\tMessage: message,\n\t\t\t\tLastUpdateTime: metav1.Now(),\n\t\t\t})\n\t\t\treturn csr, false, nil\n\t\t} else {\n\t\t\treturn csr, false, nil\n\t\t}\n\t}\n}","line":{"from":278,"to":305}} {"id":100031480,"name":"NewCmdClusterInfo","signature":"func NewCmdClusterInfo(restClientGetter genericclioptions.RESTClientGetter, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/clusterinfo/clusterinfo.go","code":"func NewCmdClusterInfo(restClientGetter genericclioptions.RESTClientGetter, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := \u0026ClusterInfoOptions{\n\t\tIOStreams: ioStreams,\n\t}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"cluster-info\",\n\t\tShort: i18n.T(\"Display cluster information\"),\n\t\tLong: longDescr,\n\t\tExample: clusterinfoExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(restClientGetter, cmd))\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\tcmd.AddCommand(NewCmdClusterInfoDump(restClientGetter, ioStreams))\n\treturn cmd\n}","line":{"from":58,"to":75}} {"id":100031481,"name":"Complete","signature":"func (o *ClusterInfoOptions) Complete(restClientGetter genericclioptions.RESTClientGetter, cmd *cobra.Command) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/clusterinfo/clusterinfo.go","code":"func (o *ClusterInfoOptions) Complete(restClientGetter genericclioptions.RESTClientGetter, cmd *cobra.Command) error {\n\tvar err error\n\to.Client, err = restClientGetter.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmdNamespace := cmdutil.GetFlagString(cmd, \"namespace\")\n\tif cmdNamespace == \"\" {\n\t\tcmdNamespace = metav1.NamespaceSystem\n\t}\n\to.Namespace = cmdNamespace\n\n\to.Builder = resource.NewBuilder(restClientGetter)\n\treturn nil\n}","line":{"from":77,"to":92}} {"id":100031482,"name":"Run","signature":"func (o *ClusterInfoOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/clusterinfo/clusterinfo.go","code":"func (o *ClusterInfoOptions) Run() error {\n\t// TODO use generalized labels once they are implemented (#341)\n\tb := o.Builder.\n\t\tWithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).\n\t\tNamespaceParam(o.Namespace).DefaultNamespace().\n\t\tLabelSelectorParam(\"kubernetes.io/cluster-service=true\").\n\t\tResourceTypeOrNameArgs(false, []string{\"services\"}...).\n\t\tLatest()\n\terr := b.Do().Visit(func(r *resource.Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tprintService(o.Out, \"Kubernetes control plane\", o.Client.Host)\n\n\t\tservices := r.Object.(*corev1.ServiceList).Items\n\t\tfor _, service := range services {\n\t\t\tvar link string\n\t\t\tif len(service.Status.LoadBalancer.Ingress) \u003e 0 {\n\t\t\t\tingress := service.Status.LoadBalancer.Ingress[0]\n\t\t\t\tip := ingress.IP\n\t\t\t\tif ip == \"\" {\n\t\t\t\t\tip = ingress.Hostname\n\t\t\t\t}\n\t\t\t\tfor _, port := range service.Spec.Ports {\n\t\t\t\t\tlink += \"http://\" + ip + \":\" + strconv.Itoa(int(port.Port)) + \" \"\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tname := service.ObjectMeta.Name\n\n\t\t\t\tif len(service.Spec.Ports) \u003e 0 {\n\t\t\t\t\tport := service.Spec.Ports[0]\n\n\t\t\t\t\t// guess if the scheme is https\n\t\t\t\t\tscheme := \"\"\n\t\t\t\t\tif port.Name == \"https\" || port.Port == 443 {\n\t\t\t\t\t\tscheme = \"https\"\n\t\t\t\t\t}\n\n\t\t\t\t\t// format is \u003cscheme\u003e:\u003cservice-name\u003e:\u003cservice-port-name\u003e\n\t\t\t\t\tname = utilnet.JoinSchemeNamePort(scheme, service.ObjectMeta.Name, port.Name)\n\t\t\t\t}\n\n\t\t\t\tif len(o.Client.GroupVersion.Group) == 0 {\n\t\t\t\t\tlink = o.Client.Host + \"/api/\" + o.Client.GroupVersion.Version + \"/namespaces/\" + service.ObjectMeta.Namespace + \"/services/\" + name + \"/proxy\"\n\t\t\t\t} else {\n\t\t\t\t\tlink = o.Client.Host + \"/api/\" + o.Client.GroupVersion.Group + \"/\" + o.Client.GroupVersion.Version + \"/namespaces/\" + service.ObjectMeta.Namespace + \"/services/\" + name + \"/proxy\"\n\n\t\t\t\t}\n\t\t\t}\n\t\t\tname := service.ObjectMeta.Labels[\"kubernetes.io/name\"]\n\t\t\tif len(name) == 0 {\n\t\t\t\tname = service.ObjectMeta.Name\n\t\t\t}\n\t\t\tprintService(o.Out, name, link)\n\t\t}\n\t\treturn nil\n\t})\n\to.Out.Write([]byte(\"\\nTo further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.\\n\"))\n\treturn err\n\n\t// TODO consider printing more information about cluster\n}","line":{"from":94,"to":155}} {"id":100031483,"name":"printService","signature":"func printService(out io.Writer, name, link string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/clusterinfo/clusterinfo.go","code":"func printService(out io.Writer, name, link string) {\n\tct.ChangeColor(ct.Green, false, ct.None, false)\n\tfmt.Fprint(out, name)\n\tct.ResetColor()\n\tfmt.Fprint(out, \" is running at \")\n\tct.ChangeColor(ct.Yellow, false, ct.None, false)\n\tfmt.Fprint(out, link)\n\tct.ResetColor()\n\tfmt.Fprintln(out, \"\")\n}","line":{"from":157,"to":166}} {"id":100031484,"name":"NewCmdClusterInfoDump","signature":"func NewCmdClusterInfoDump(restClientGetter genericclioptions.RESTClientGetter, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/clusterinfo/clusterinfo_dump.go","code":"func NewCmdClusterInfoDump(restClientGetter genericclioptions.RESTClientGetter, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := \u0026ClusterInfoDumpOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"\").WithTypeSetter(scheme.Scheme).WithDefaultOutput(\"json\"),\n\n\t\tIOStreams: ioStreams,\n\t}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"dump\",\n\t\tShort: i18n.T(\"Dump relevant information for debugging and diagnosis\"),\n\t\tLong: dumpLong,\n\t\tExample: dumpExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(restClientGetter, cmd))\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmd.Flags().StringVar(\u0026o.OutputDir, \"output-directory\", o.OutputDir, i18n.T(\"Where to output the files. If empty or '-' uses stdout, otherwise creates a directory hierarchy in that directory\"))\n\tcmd.Flags().StringSliceVar(\u0026o.Namespaces, \"namespaces\", o.Namespaces, \"A comma separated list of namespaces to dump.\")\n\tcmd.Flags().BoolVarP(\u0026o.AllNamespaces, \"all-namespaces\", \"A\", o.AllNamespaces, \"If true, dump all namespaces. If true, --namespaces is ignored.\")\n\tcmdutil.AddPodRunningTimeoutFlag(cmd, defaultPodLogsTimeout)\n\treturn cmd\n}","line":{"from":65,"to":90}} {"id":100031485,"name":"setupOutputWriter","signature":"func setupOutputWriter(dir string, defaultWriter io.Writer, filename string, fileExtension string) io.Writer","file":"staging/src/k8s.io/kubectl/pkg/cmd/clusterinfo/clusterinfo_dump.go","code":"func setupOutputWriter(dir string, defaultWriter io.Writer, filename string, fileExtension string) io.Writer {\n\tif len(dir) == 0 || dir == \"-\" {\n\t\treturn defaultWriter\n\t}\n\tfullFile := path.Join(dir, filename) + fileExtension\n\tparent := path.Dir(fullFile)\n\tcmdutil.CheckErr(os.MkdirAll(parent, 0755))\n\n\tfile, err := os.Create(fullFile)\n\tcmdutil.CheckErr(err)\n\treturn file\n}","line":{"from":116,"to":127}} {"id":100031486,"name":"Complete","signature":"func (o *ClusterInfoDumpOptions) Complete(restClientGetter genericclioptions.RESTClientGetter, cmd *cobra.Command) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/clusterinfo/clusterinfo_dump.go","code":"func (o *ClusterInfoDumpOptions) Complete(restClientGetter genericclioptions.RESTClientGetter, cmd *cobra.Command) error {\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.PrintObj = printer.PrintObj\n\n\tconfig, err := restClientGetter.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.CoreClient, err = corev1client.NewForConfig(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.AppsClient, err = appsv1client.NewForConfig(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Timeout, err = cmdutil.GetPodRunningTimeoutFlag(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Namespace, _, err = restClientGetter.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.RESTClientGetter = restClientGetter\n\to.LogsForObject = polymorphichelpers.LogsForObjectFn\n\n\treturn nil\n}","line":{"from":129,"to":166}} {"id":100031487,"name":"Run","signature":"func (o *ClusterInfoDumpOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/clusterinfo/clusterinfo_dump.go","code":"func (o *ClusterInfoDumpOptions) Run() error {\n\tnodes, err := o.CoreClient.Nodes().List(context.TODO(), metav1.ListOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfileExtension := \".txt\"\n\tif o.PrintFlags.OutputFormat != nil {\n\t\tswitch *o.PrintFlags.OutputFormat {\n\t\tcase \"json\":\n\t\t\tfileExtension = \".json\"\n\t\tcase \"yaml\":\n\t\t\tfileExtension = \".yaml\"\n\t\t}\n\t}\n\n\tif err := o.PrintObj(nodes, setupOutputWriter(o.OutputDir, o.Out, \"nodes\", fileExtension)); err != nil {\n\t\treturn err\n\t}\n\n\tvar namespaces []string\n\tif o.AllNamespaces {\n\t\tnamespaceList, err := o.CoreClient.Namespaces().List(context.TODO(), metav1.ListOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor ix := range namespaceList.Items {\n\t\t\tnamespaces = append(namespaces, namespaceList.Items[ix].Name)\n\t\t}\n\t} else {\n\t\tif len(o.Namespaces) == 0 {\n\t\t\tnamespaces = []string{\n\t\t\t\tmetav1.NamespaceSystem,\n\t\t\t\to.Namespace,\n\t\t\t}\n\t\t} else {\n\t\t\tnamespaces = o.Namespaces\n\t\t}\n\t}\n\tfor _, namespace := range namespaces {\n\t\t// TODO: this is repetitive in the extreme. Use reflection or\n\t\t// something to make this a for loop.\n\t\tevents, err := o.CoreClient.Events(namespace).List(context.TODO(), metav1.ListOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := o.PrintObj(events, setupOutputWriter(o.OutputDir, o.Out, path.Join(namespace, \"events\"), fileExtension)); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trcs, err := o.CoreClient.ReplicationControllers(namespace).List(context.TODO(), metav1.ListOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := o.PrintObj(rcs, setupOutputWriter(o.OutputDir, o.Out, path.Join(namespace, \"replication-controllers\"), fileExtension)); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tsvcs, err := o.CoreClient.Services(namespace).List(context.TODO(), metav1.ListOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := o.PrintObj(svcs, setupOutputWriter(o.OutputDir, o.Out, path.Join(namespace, \"services\"), fileExtension)); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tsets, err := o.AppsClient.DaemonSets(namespace).List(context.TODO(), metav1.ListOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := o.PrintObj(sets, setupOutputWriter(o.OutputDir, o.Out, path.Join(namespace, \"daemonsets\"), fileExtension)); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdeps, err := o.AppsClient.Deployments(namespace).List(context.TODO(), metav1.ListOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := o.PrintObj(deps, setupOutputWriter(o.OutputDir, o.Out, path.Join(namespace, \"deployments\"), fileExtension)); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trps, err := o.AppsClient.ReplicaSets(namespace).List(context.TODO(), metav1.ListOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := o.PrintObj(rps, setupOutputWriter(o.OutputDir, o.Out, path.Join(namespace, \"replicasets\"), fileExtension)); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tpods, err := o.CoreClient.Pods(namespace).List(context.TODO(), metav1.ListOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := o.PrintObj(pods, setupOutputWriter(o.OutputDir, o.Out, path.Join(namespace, \"pods\"), fileExtension)); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tprintContainer := func(writer io.Writer, container corev1.Container, pod *corev1.Pod) {\n\t\t\twriter.Write([]byte(fmt.Sprintf(\"==== START logs for container %s of pod %s/%s ====\\n\", container.Name, pod.Namespace, pod.Name)))\n\t\t\tdefer writer.Write([]byte(fmt.Sprintf(\"==== END logs for container %s of pod %s/%s ====\\n\", container.Name, pod.Namespace, pod.Name)))\n\n\t\t\trequests, err := o.LogsForObject(o.RESTClientGetter, pod, \u0026corev1.PodLogOptions{Container: container.Name}, timeout, false)\n\t\t\tif err != nil {\n\t\t\t\t// Print error and return.\n\t\t\t\twriter.Write([]byte(fmt.Sprintf(\"Create log request error: %s\\n\", err.Error())))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor _, request := range requests {\n\t\t\t\tdata, err := request.DoRaw(context.TODO())\n\t\t\t\tif err != nil {\n\t\t\t\t\t// Print error and return.\n\t\t\t\t\twriter.Write([]byte(fmt.Sprintf(\"Request log error: %s\\n\", err.Error())))\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\twriter.Write(data)\n\t\t\t}\n\t\t}\n\n\t\tfor ix := range pods.Items {\n\t\t\tpod := \u0026pods.Items[ix]\n\t\t\tinitcontainers := pod.Spec.InitContainers\n\t\t\tcontainers := pod.Spec.Containers\n\t\t\twriter := setupOutputWriter(o.OutputDir, o.Out, path.Join(namespace, pod.Name, \"logs\"), \".txt\")\n\n\t\t\tfor i := range initcontainers {\n\t\t\t\tprintContainer(writer, initcontainers[i], pod)\n\t\t\t}\n\t\t\tfor i := range containers {\n\t\t\t\tprintContainer(writer, containers[i], pod)\n\t\t\t}\n\t\t}\n\t}\n\n\tdest := o.OutputDir\n\tif len(dest) \u003e 0 \u0026\u0026 dest != \"-\" {\n\t\tfmt.Fprintf(o.Out, \"Cluster info dumped to %s\\n\", dest)\n\t}\n\treturn nil\n}","line":{"from":168,"to":309}} {"id":100031488,"name":"NewDefaultKubectlCommand","signature":"func NewDefaultKubectlCommand() *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/cmd.go","code":"// NewDefaultKubectlCommand creates the `kubectl` command with default arguments\nfunc NewDefaultKubectlCommand() *cobra.Command {\n\treturn NewDefaultKubectlCommandWithArgs(KubectlOptions{\n\t\tPluginHandler: NewDefaultPluginHandler(plugin.ValidPluginFilenamePrefixes),\n\t\tArguments: os.Args,\n\t\tConfigFlags: defaultConfigFlags,\n\t\tIOStreams: genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr},\n\t})\n}","line":{"from":100,"to":108}} {"id":100031489,"name":"NewDefaultKubectlCommandWithArgs","signature":"func NewDefaultKubectlCommandWithArgs(o KubectlOptions) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/cmd.go","code":"// NewDefaultKubectlCommandWithArgs creates the `kubectl` command with arguments\nfunc NewDefaultKubectlCommandWithArgs(o KubectlOptions) *cobra.Command {\n\tcmd := NewKubectlCommand(o)\n\n\tif o.PluginHandler == nil {\n\t\treturn cmd\n\t}\n\n\tif len(o.Arguments) \u003e 1 {\n\t\tcmdPathPieces := o.Arguments[1:]\n\n\t\t// only look for suitable extension executables if\n\t\t// the specified command does not already exist\n\t\tif foundCmd, foundArgs, err := cmd.Find(cmdPathPieces); err != nil {\n\t\t\t// Also check the commands that will be added by Cobra.\n\t\t\t// These commands are only added once rootCmd.Execute() is called, so we\n\t\t\t// need to check them explicitly here.\n\t\t\tvar cmdName string // first \"non-flag\" arguments\n\t\t\tfor _, arg := range cmdPathPieces {\n\t\t\t\tif !strings.HasPrefix(arg, \"-\") {\n\t\t\t\t\tcmdName = arg\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tswitch cmdName {\n\t\t\tcase \"help\", cobra.ShellCompRequestCmd, cobra.ShellCompNoDescRequestCmd:\n\t\t\t\t// Don't search for a plugin\n\t\t\tdefault:\n\t\t\t\tif err := HandlePluginCommand(o.PluginHandler, cmdPathPieces, false); err != nil {\n\t\t\t\t\tfmt.Fprintf(o.IOStreams.ErrOut, \"Error: %v\\n\", err)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\t\t\t}\n\t\t} else if err == nil {\n\t\t\tif cmdutil.CmdPluginAsSubcommand.IsEnabled() {\n\t\t\t\t// Command exists(e.g. kubectl create), but it is not certain that\n\t\t\t\t// subcommand also exists (e.g. kubectl create networkpolicy)\n\t\t\t\tif _, ok := allowedCmdsSubcommandPlugin[foundCmd.Name()]; ok {\n\t\t\t\t\tvar subcommand string\n\t\t\t\t\tfor _, arg := range foundArgs { // first \"non-flag\" argument as subcommand\n\t\t\t\t\t\tif !strings.HasPrefix(arg, \"-\") {\n\t\t\t\t\t\t\tsubcommand = arg\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbuiltinSubcmdExist := false\n\t\t\t\t\tfor _, subcmd := range foundCmd.Commands() {\n\t\t\t\t\t\tif subcmd.Name() == subcommand {\n\t\t\t\t\t\t\tbuiltinSubcmdExist = true\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif !builtinSubcmdExist {\n\t\t\t\t\t\tif err := HandlePluginCommand(o.PluginHandler, cmdPathPieces, true); err != nil {\n\t\t\t\t\t\t\tfmt.Fprintf(o.IOStreams.ErrOut, \"Error: %v\\n\", err)\n\t\t\t\t\t\t\tos.Exit(1)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn cmd\n}","line":{"from":110,"to":176}} {"id":100031490,"name":"NewDefaultPluginHandler","signature":"func NewDefaultPluginHandler(validPrefixes []string) *DefaultPluginHandler","file":"staging/src/k8s.io/kubectl/pkg/cmd/cmd.go","code":"// NewDefaultPluginHandler instantiates the DefaultPluginHandler with a list of\n// given filename prefixes used to identify valid plugin filenames.\nfunc NewDefaultPluginHandler(validPrefixes []string) *DefaultPluginHandler {\n\treturn \u0026DefaultPluginHandler{\n\t\tValidPrefixes: validPrefixes,\n\t}\n}","line":{"from":198,"to":204}} {"id":100031491,"name":"Lookup","signature":"func (h *DefaultPluginHandler) Lookup(filename string) (string, bool)","file":"staging/src/k8s.io/kubectl/pkg/cmd/cmd.go","code":"// Lookup implements PluginHandler\nfunc (h *DefaultPluginHandler) Lookup(filename string) (string, bool) {\n\tfor _, prefix := range h.ValidPrefixes {\n\t\tpath, err := exec.LookPath(fmt.Sprintf(\"%s-%s\", prefix, filename))\n\t\tif shouldSkipOnLookPathErr(err) || len(path) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\treturn path, true\n\t}\n\treturn \"\", false\n}","line":{"from":206,"to":216}} {"id":100031492,"name":"Command","signature":"func Command(name string, arg ...string) *exec.Cmd","file":"staging/src/k8s.io/kubectl/pkg/cmd/cmd.go","code":"func Command(name string, arg ...string) *exec.Cmd {\n\tcmd := \u0026exec.Cmd{\n\t\tPath: name,\n\t\tArgs: append([]string{name}, arg...),\n\t}\n\tif filepath.Base(name) == name {\n\t\tlp, err := exec.LookPath(name)\n\t\tif lp != \"\" \u0026\u0026 !shouldSkipOnLookPathErr(err) {\n\t\t\t// Update cmd.Path even if err is non-nil.\n\t\t\t// If err is ErrDot (especially on Windows), lp may include a resolved\n\t\t\t// extension (like .exe or .bat) that should be preserved.\n\t\t\tcmd.Path = lp\n\t\t}\n\t}\n\treturn cmd\n}","line":{"from":218,"to":233}} {"id":100031493,"name":"Execute","signature":"func (h *DefaultPluginHandler) Execute(executablePath string, cmdArgs, environment []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/cmd.go","code":"// Execute implements PluginHandler\nfunc (h *DefaultPluginHandler) Execute(executablePath string, cmdArgs, environment []string) error {\n\n\t// Windows does not support exec syscall.\n\tif runtime.GOOS == \"windows\" {\n\t\tcmd := Command(executablePath, cmdArgs...)\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\t\tcmd.Stdin = os.Stdin\n\t\tcmd.Env = environment\n\t\terr := cmd.Run()\n\t\tif err == nil {\n\t\t\tos.Exit(0)\n\t\t}\n\t\treturn err\n\t}\n\n\t// invoke cmd binary relaying the environment and args given\n\t// append executablePath to cmdArgs, as execve will make first argument the \"binary name\".\n\treturn syscall.Exec(executablePath, append([]string{executablePath}, cmdArgs...), environment)\n}","line":{"from":235,"to":255}} {"id":100031494,"name":"HandlePluginCommand","signature":"func HandlePluginCommand(pluginHandler PluginHandler, cmdArgs []string, exactMatch bool) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/cmd.go","code":"// HandlePluginCommand receives a pluginHandler and command-line arguments and attempts to find\n// a plugin executable on the PATH that satisfies the given arguments.\nfunc HandlePluginCommand(pluginHandler PluginHandler, cmdArgs []string, exactMatch bool) error {\n\tvar remainingArgs []string // all \"non-flag\" arguments\n\tfor _, arg := range cmdArgs {\n\t\tif strings.HasPrefix(arg, \"-\") {\n\t\t\tbreak\n\t\t}\n\t\tremainingArgs = append(remainingArgs, strings.Replace(arg, \"-\", \"_\", -1))\n\t}\n\n\tif len(remainingArgs) == 0 {\n\t\t// the length of cmdArgs is at least 1\n\t\treturn fmt.Errorf(\"flags cannot be placed before plugin name: %s\", cmdArgs[0])\n\t}\n\n\tfoundBinaryPath := \"\"\n\n\t// attempt to find binary, starting at longest possible name with given cmdArgs\n\tfor len(remainingArgs) \u003e 0 {\n\t\tpath, found := pluginHandler.Lookup(strings.Join(remainingArgs, \"-\"))\n\t\tif !found {\n\t\t\tif exactMatch {\n\t\t\t\t// if exactMatch is true, we shouldn't continue searching with shorter names.\n\t\t\t\t// this is especially for not searching kubectl-create plugin\n\t\t\t\t// when kubectl-create-foo plugin is not found.\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tremainingArgs = remainingArgs[:len(remainingArgs)-1]\n\t\t\tcontinue\n\t\t}\n\n\t\tfoundBinaryPath = path\n\t\tbreak\n\t}\n\n\tif len(foundBinaryPath) == 0 {\n\t\treturn nil\n\t}\n\n\t// invoke cmd binary relaying the current environment and args given\n\tif err := pluginHandler.Execute(foundBinaryPath, cmdArgs[len(remainingArgs):], os.Environ()); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":257,"to":303}} {"id":100031495,"name":"NewKubectlCommand","signature":"func NewKubectlCommand(o KubectlOptions) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/cmd.go","code":"// NewKubectlCommand creates the `kubectl` command and its nested children.\nfunc NewKubectlCommand(o KubectlOptions) *cobra.Command {\n\twarningHandler := rest.NewWarningWriter(o.IOStreams.ErrOut, rest.WarningWriterOptions{Deduplicate: true, Color: term.AllowsColorOutput(o.IOStreams.ErrOut)})\n\twarningsAsErrors := false\n\t// Parent command to which all subcommands are added.\n\tcmds := \u0026cobra.Command{\n\t\tUse: \"kubectl\",\n\t\tShort: i18n.T(\"kubectl controls the Kubernetes cluster manager\"),\n\t\tLong: templates.LongDesc(`\n kubectl controls the Kubernetes cluster manager.\n\n Find more information at:\n https://kubernetes.io/docs/reference/kubectl/`),\n\t\tRun: runHelp,\n\t\t// Hook before and after Run initialize and write profiles to disk,\n\t\t// respectively.\n\t\tPersistentPreRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\trest.SetDefaultWarningHandler(warningHandler)\n\n\t\t\tif cmd.Name() == cobra.ShellCompRequestCmd {\n\t\t\t\t// This is the __complete or __completeNoDesc command which\n\t\t\t\t// indicates shell completion has been requested.\n\t\t\t\tplugin.SetupPluginCompletion(cmd, args)\n\t\t\t}\n\n\t\t\treturn initProfiling()\n\t\t},\n\t\tPersistentPostRunE: func(*cobra.Command, []string) error {\n\t\t\tif err := flushProfiling(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif warningsAsErrors {\n\t\t\t\tcount := warningHandler.WarningCount()\n\t\t\t\tswitch count {\n\t\t\t\tcase 0:\n\t\t\t\t\t// no warnings\n\t\t\t\tcase 1:\n\t\t\t\t\treturn fmt.Errorf(\"%d warning received\", count)\n\t\t\t\tdefault:\n\t\t\t\t\treturn fmt.Errorf(\"%d warnings received\", count)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\t// From this point and forward we get warnings on flags that contain \"_\" separators\n\t// when adding them with hyphen instead of the original name.\n\tcmds.SetGlobalNormalizationFunc(cliflag.WarnWordSepNormalizeFunc)\n\n\tflags := cmds.PersistentFlags()\n\n\taddProfilingFlags(flags)\n\n\tflags.BoolVar(\u0026warningsAsErrors, \"warnings-as-errors\", warningsAsErrors, \"Treat warnings received from the server as errors and exit with a non-zero exit code\")\n\n\tkubeConfigFlags := o.ConfigFlags\n\tif kubeConfigFlags == nil {\n\t\tkubeConfigFlags = defaultConfigFlags\n\t}\n\tkubeConfigFlags.AddFlags(flags)\n\tmatchVersionKubeConfigFlags := cmdutil.NewMatchVersionFlags(kubeConfigFlags)\n\tmatchVersionKubeConfigFlags.AddFlags(flags)\n\t// Updates hooks to add kubectl command headers: SIG CLI KEP 859.\n\taddCmdHeaderHooks(cmds, kubeConfigFlags)\n\n\tf := cmdutil.NewFactory(matchVersionKubeConfigFlags)\n\n\t// Proxy command is incompatible with CommandHeaderRoundTripper, so\n\t// clear the WrapConfigFn before running proxy command.\n\tproxyCmd := proxy.NewCmdProxy(f, o.IOStreams)\n\tproxyCmd.PreRun = func(cmd *cobra.Command, args []string) {\n\t\tkubeConfigFlags.WrapConfigFn = nil\n\t}\n\n\t// Avoid import cycle by setting ValidArgsFunction here instead of in NewCmdGet()\n\tgetCmd := get.NewCmdGet(\"kubectl\", f, o.IOStreams)\n\tgetCmd.ValidArgsFunction = utilcomp.ResourceTypeAndNameCompletionFunc(f)\n\n\tgroups := templates.CommandGroups{\n\t\t{\n\t\t\tMessage: \"Basic Commands (Beginner):\",\n\t\t\tCommands: []*cobra.Command{\n\t\t\t\tcreate.NewCmdCreate(f, o.IOStreams),\n\t\t\t\texpose.NewCmdExposeService(f, o.IOStreams),\n\t\t\t\trun.NewCmdRun(f, o.IOStreams),\n\t\t\t\tset.NewCmdSet(f, o.IOStreams),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tMessage: \"Basic Commands (Intermediate):\",\n\t\t\tCommands: []*cobra.Command{\n\t\t\t\texplain.NewCmdExplain(\"kubectl\", f, o.IOStreams),\n\t\t\t\tgetCmd,\n\t\t\t\tedit.NewCmdEdit(f, o.IOStreams),\n\t\t\t\tdelete.NewCmdDelete(f, o.IOStreams),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tMessage: \"Deploy Commands:\",\n\t\t\tCommands: []*cobra.Command{\n\t\t\t\trollout.NewCmdRollout(f, o.IOStreams),\n\t\t\t\tscale.NewCmdScale(f, o.IOStreams),\n\t\t\t\tautoscale.NewCmdAutoscale(f, o.IOStreams),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tMessage: \"Cluster Management Commands:\",\n\t\t\tCommands: []*cobra.Command{\n\t\t\t\tcertificates.NewCmdCertificate(f, o.IOStreams),\n\t\t\t\tclusterinfo.NewCmdClusterInfo(f, o.IOStreams),\n\t\t\t\ttop.NewCmdTop(f, o.IOStreams),\n\t\t\t\tdrain.NewCmdCordon(f, o.IOStreams),\n\t\t\t\tdrain.NewCmdUncordon(f, o.IOStreams),\n\t\t\t\tdrain.NewCmdDrain(f, o.IOStreams),\n\t\t\t\ttaint.NewCmdTaint(f, o.IOStreams),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tMessage: \"Troubleshooting and Debugging Commands:\",\n\t\t\tCommands: []*cobra.Command{\n\t\t\t\tdescribe.NewCmdDescribe(\"kubectl\", f, o.IOStreams),\n\t\t\t\tlogs.NewCmdLogs(f, o.IOStreams),\n\t\t\t\tattach.NewCmdAttach(f, o.IOStreams),\n\t\t\t\tcmdexec.NewCmdExec(f, o.IOStreams),\n\t\t\t\tportforward.NewCmdPortForward(f, o.IOStreams),\n\t\t\t\tproxyCmd,\n\t\t\t\tcp.NewCmdCp(f, o.IOStreams),\n\t\t\t\tauth.NewCmdAuth(f, o.IOStreams),\n\t\t\t\tdebug.NewCmdDebug(f, o.IOStreams),\n\t\t\t\tevents.NewCmdEvents(f, o.IOStreams),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tMessage: \"Advanced Commands:\",\n\t\t\tCommands: []*cobra.Command{\n\t\t\t\tdiff.NewCmdDiff(f, o.IOStreams),\n\t\t\t\tapply.NewCmdApply(\"kubectl\", f, o.IOStreams),\n\t\t\t\tpatch.NewCmdPatch(f, o.IOStreams),\n\t\t\t\treplace.NewCmdReplace(f, o.IOStreams),\n\t\t\t\twait.NewCmdWait(f, o.IOStreams),\n\t\t\t\tkustomize.NewCmdKustomize(o.IOStreams),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tMessage: \"Settings Commands:\",\n\t\t\tCommands: []*cobra.Command{\n\t\t\t\tlabel.NewCmdLabel(f, o.IOStreams),\n\t\t\t\tannotate.NewCmdAnnotate(\"kubectl\", f, o.IOStreams),\n\t\t\t\tcompletion.NewCmdCompletion(o.IOStreams.Out, \"\"),\n\t\t\t},\n\t\t},\n\t}\n\tgroups.Add(cmds)\n\n\tfilters := []string{\"options\"}\n\n\t// Hide the \"alpha\" subcommand if there are no alpha commands in this build.\n\talpha := NewCmdAlpha(f, o.IOStreams)\n\tif !alpha.HasSubCommands() {\n\t\tfilters = append(filters, alpha.Name())\n\t}\n\n\ttemplates.ActsAsRootCommand(cmds, filters, groups...)\n\n\tutilcomp.SetFactoryForCompletion(f)\n\tregisterCompletionFuncForGlobalFlags(cmds, f)\n\n\tcmds.AddCommand(alpha)\n\tcmds.AddCommand(cmdconfig.NewCmdConfig(clientcmd.NewDefaultPathOptions(), o.IOStreams))\n\tcmds.AddCommand(plugin.NewCmdPlugin(o.IOStreams))\n\tcmds.AddCommand(version.NewCmdVersion(f, o.IOStreams))\n\tcmds.AddCommand(apiresources.NewCmdAPIVersions(f, o.IOStreams))\n\tcmds.AddCommand(apiresources.NewCmdAPIResources(f, o.IOStreams))\n\tcmds.AddCommand(options.NewCmdOptions(o.IOStreams.Out))\n\n\t// Stop warning about normalization of flags. That makes it possible to\n\t// add the klog flags later.\n\tcmds.SetGlobalNormalizationFunc(cliflag.WordSepNormalizeFunc)\n\treturn cmds\n}","line":{"from":305,"to":484}} {"id":100031496,"name":"addCmdHeaderHooks","signature":"func addCmdHeaderHooks(cmds *cobra.Command, kubeConfigFlags *genericclioptions.ConfigFlags)","file":"staging/src/k8s.io/kubectl/pkg/cmd/cmd.go","code":"// addCmdHeaderHooks performs updates on two hooks:\n// 1. Modifies the passed \"cmds\" persistent pre-run function to parse command headers.\n// These headers will be subsequently added as X-headers to every\n// REST call.\n// 2. Adds CommandHeaderRoundTripper as a wrapper around the standard\n// RoundTripper. CommandHeaderRoundTripper adds X-Headers then delegates\n// to standard RoundTripper.\n//\n// For beta, these hooks are updated unless the KUBECTL_COMMAND_HEADERS environment variable\n// is set, and the value of the env var is false (or zero).\n// See SIG CLI KEP 859 for more information:\n//\n//\thttps://github.com/kubernetes/enhancements/tree/master/keps/sig-cli/859-kubectl-headers\nfunc addCmdHeaderHooks(cmds *cobra.Command, kubeConfigFlags *genericclioptions.ConfigFlags) {\n\t// If the feature gate env var is set to \"false\", then do no add kubectl command headers.\n\tif value, exists := os.LookupEnv(kubectlCmdHeaders); exists {\n\t\tif value == \"false\" || value == \"0\" {\n\t\t\tklog.V(5).Infoln(\"kubectl command headers turned off\")\n\t\t\treturn\n\t\t}\n\t}\n\tklog.V(5).Infoln(\"kubectl command headers turned on\")\n\tcrt := \u0026genericclioptions.CommandHeaderRoundTripper{}\n\texistingPreRunE := cmds.PersistentPreRunE\n\t// Add command parsing to the existing persistent pre-run function.\n\tcmds.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {\n\t\tcrt.ParseCommandHeaders(cmd, args)\n\t\treturn existingPreRunE(cmd, args)\n\t}\n\twrapConfigFn := kubeConfigFlags.WrapConfigFn\n\t// Wraps CommandHeaderRoundTripper around standard RoundTripper.\n\tkubeConfigFlags.WrapConfigFn = func(c *rest.Config) *rest.Config {\n\t\tif wrapConfigFn != nil {\n\t\t\tc = wrapConfigFn(c)\n\t\t}\n\t\tc.Wrap(func(rt http.RoundTripper) http.RoundTripper {\n\t\t\t// Must be separate RoundTripper; not \"crt\" closure.\n\t\t\t// Fixes: https://github.com/kubernetes/kubectl/issues/1098\n\t\t\treturn \u0026genericclioptions.CommandHeaderRoundTripper{\n\t\t\t\tDelegate: rt,\n\t\t\t\tHeaders: crt.Headers,\n\t\t\t}\n\t\t})\n\t\treturn c\n\t}\n}","line":{"from":486,"to":531}} {"id":100031497,"name":"runHelp","signature":"func runHelp(cmd *cobra.Command, args []string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/cmd.go","code":"func runHelp(cmd *cobra.Command, args []string) {\n\tcmd.Help()\n}","line":{"from":533,"to":535}} {"id":100031498,"name":"registerCompletionFuncForGlobalFlags","signature":"func registerCompletionFuncForGlobalFlags(cmd *cobra.Command, f cmdutil.Factory)","file":"staging/src/k8s.io/kubectl/pkg/cmd/cmd.go","code":"func registerCompletionFuncForGlobalFlags(cmd *cobra.Command, f cmdutil.Factory) {\n\tcmdutil.CheckErr(cmd.RegisterFlagCompletionFunc(\n\t\t\"namespace\",\n\t\tfunc(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\t\t\treturn utilcomp.CompGetResource(f, \"namespace\", toComplete), cobra.ShellCompDirectiveNoFileComp\n\t\t}))\n\tcmdutil.CheckErr(cmd.RegisterFlagCompletionFunc(\n\t\t\"context\",\n\t\tfunc(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\t\t\treturn utilcomp.ListContextsInConfig(toComplete), cobra.ShellCompDirectiveNoFileComp\n\t\t}))\n\tcmdutil.CheckErr(cmd.RegisterFlagCompletionFunc(\n\t\t\"cluster\",\n\t\tfunc(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\t\t\treturn utilcomp.ListClustersInConfig(toComplete), cobra.ShellCompDirectiveNoFileComp\n\t\t}))\n\tcmdutil.CheckErr(cmd.RegisterFlagCompletionFunc(\n\t\t\"user\",\n\t\tfunc(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\t\t\treturn utilcomp.ListUsersInConfig(toComplete), cobra.ShellCompDirectiveNoFileComp\n\t\t}))\n}","line":{"from":537,"to":558}} {"id":100031499,"name":"NewCmdCompletion","signature":"func NewCmdCompletion(out io.Writer, boilerPlate string) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/completion/completion.go","code":"// NewCmdCompletion creates the `completion` command\nfunc NewCmdCompletion(out io.Writer, boilerPlate string) *cobra.Command {\n\tshells := []string{}\n\tfor s := range completionShells {\n\t\tshells = append(shells, s)\n\t}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"completion SHELL\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Output shell completion code for the specified shell (bash, zsh, fish, or powershell)\"),\n\t\tLong: completionLong,\n\t\tExample: completionExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(RunCompletion(out, boilerPlate, cmd, args))\n\t\t},\n\t\tValidArgs: shells,\n\t}\n\n\treturn cmd\n}","line":{"from":124,"to":144}} {"id":100031500,"name":"RunCompletion","signature":"func RunCompletion(out io.Writer, boilerPlate string, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/completion/completion.go","code":"// RunCompletion checks given arguments and executes command\nfunc RunCompletion(out io.Writer, boilerPlate string, cmd *cobra.Command, args []string) error {\n\tif len(args) == 0 {\n\t\treturn cmdutil.UsageErrorf(cmd, \"Shell not specified.\")\n\t}\n\tif len(args) \u003e 1 {\n\t\treturn cmdutil.UsageErrorf(cmd, \"Too many arguments. Expected only the shell type.\")\n\t}\n\trun, found := completionShells[args[0]]\n\tif !found {\n\t\treturn cmdutil.UsageErrorf(cmd, \"Unsupported shell type %q.\", args[0])\n\t}\n\n\treturn run(out, boilerPlate, cmd.Parent())\n}","line":{"from":146,"to":160}} {"id":100031501,"name":"runCompletionBash","signature":"func runCompletionBash(out io.Writer, boilerPlate string, kubectl *cobra.Command) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/completion/completion.go","code":"func runCompletionBash(out io.Writer, boilerPlate string, kubectl *cobra.Command) error {\n\tif len(boilerPlate) == 0 {\n\t\tboilerPlate = defaultBoilerPlate\n\t}\n\tif _, err := out.Write([]byte(boilerPlate)); err != nil {\n\t\treturn err\n\t}\n\n\treturn kubectl.GenBashCompletionV2(out, true)\n}","line":{"from":162,"to":171}} {"id":100031502,"name":"runCompletionZsh","signature":"func runCompletionZsh(out io.Writer, boilerPlate string, kubectl *cobra.Command) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/completion/completion.go","code":"func runCompletionZsh(out io.Writer, boilerPlate string, kubectl *cobra.Command) error {\n\tzshHead := fmt.Sprintf(\"#compdef %[1]s\\ncompdef _%[1]s %[1]s\\n\", kubectl.Name())\n\tout.Write([]byte(zshHead))\n\n\tif len(boilerPlate) == 0 {\n\t\tboilerPlate = defaultBoilerPlate\n\t}\n\tif _, err := out.Write([]byte(boilerPlate)); err != nil {\n\t\treturn err\n\t}\n\n\treturn kubectl.GenZshCompletion(out)\n}","line":{"from":173,"to":185}} {"id":100031503,"name":"runCompletionFish","signature":"func runCompletionFish(out io.Writer, boilerPlate string, kubectl *cobra.Command) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/completion/completion.go","code":"func runCompletionFish(out io.Writer, boilerPlate string, kubectl *cobra.Command) error {\n\tif len(boilerPlate) == 0 {\n\t\tboilerPlate = defaultBoilerPlate\n\t}\n\tif _, err := out.Write([]byte(boilerPlate)); err != nil {\n\t\treturn err\n\t}\n\n\treturn kubectl.GenFishCompletion(out, true)\n}","line":{"from":187,"to":196}} {"id":100031504,"name":"runCompletionPwsh","signature":"func runCompletionPwsh(out io.Writer, boilerPlate string, kubectl *cobra.Command) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/completion/completion.go","code":"func runCompletionPwsh(out io.Writer, boilerPlate string, kubectl *cobra.Command) error {\n\tif len(boilerPlate) == 0 {\n\t\tboilerPlate = defaultBoilerPlate\n\t}\n\n\tif _, err := out.Write([]byte(boilerPlate)); err != nil {\n\t\treturn err\n\t}\n\n\treturn kubectl.GenPowerShellCompletionWithDesc(out)\n}","line":{"from":198,"to":208}} {"id":100031505,"name":"NewCmdConfig","signature":"func NewCmdConfig(pathOptions *clientcmd.PathOptions, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/config.go","code":"// NewCmdConfig creates a command object for the \"config\" action, and adds all child commands to it.\nfunc NewCmdConfig(pathOptions *clientcmd.PathOptions, streams genericclioptions.IOStreams) *cobra.Command {\n\tif len(pathOptions.ExplicitFileFlag) == 0 {\n\t\tpathOptions.ExplicitFileFlag = clientcmd.RecommendedConfigPathFlag\n\t}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"config SUBCOMMAND\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Modify kubeconfig files\"),\n\t\tLong: templates.LongDesc(i18n.T(`\n\t\t\tModify kubeconfig files using subcommands like \"kubectl config set current-context my-context\"\n\n\t\t\tThe loading order follows these rules:\n\n\t\t\t1. If the --`) + pathOptions.ExplicitFileFlag + i18n.T(` flag is set, then only that file is loaded. The flag may only be set once and no merging takes place.\n\t\t\t2. If $`) + pathOptions.EnvVar + i18n.T(` environment variable is set, then it is used as a list of paths (normal path delimiting rules for your system). These paths are merged. When a value is modified, it is modified in the file that defines the stanza. When a value is created, it is created in the first file that exists. If no files in the chain exist, then it creates the last file in the list.\n\t\t\t3. Otherwise, `) + path.Join(\"${HOME}\", pathOptions.GlobalFileSubpath) + i18n.T(` is used and no merging takes place.`)),\n\t\tRun: cmdutil.DefaultSubCommandRun(streams.ErrOut),\n\t}\n\n\t// file paths are common to all sub commands\n\tcmd.PersistentFlags().StringVar(\u0026pathOptions.LoadingRules.ExplicitPath, pathOptions.ExplicitFileFlag, pathOptions.LoadingRules.ExplicitPath, \"use a particular kubeconfig file\")\n\n\t// TODO(juanvallejo): update all subcommands to work with genericclioptions.IOStreams\n\tcmd.AddCommand(NewCmdConfigView(streams, pathOptions))\n\tcmd.AddCommand(NewCmdConfigSetCluster(streams.Out, pathOptions))\n\tcmd.AddCommand(NewCmdConfigSetCredentials(streams.Out, pathOptions))\n\tcmd.AddCommand(NewCmdConfigSetContext(streams.Out, pathOptions))\n\tcmd.AddCommand(NewCmdConfigSet(streams.Out, pathOptions))\n\tcmd.AddCommand(NewCmdConfigUnset(streams.Out, pathOptions))\n\tcmd.AddCommand(NewCmdConfigCurrentContext(streams.Out, pathOptions))\n\tcmd.AddCommand(NewCmdConfigUseContext(streams.Out, pathOptions))\n\tcmd.AddCommand(NewCmdConfigGetContexts(streams, pathOptions))\n\tcmd.AddCommand(NewCmdConfigGetClusters(streams.Out, pathOptions))\n\tcmd.AddCommand(NewCmdConfigGetUsers(streams, pathOptions))\n\tcmd.AddCommand(NewCmdConfigDeleteCluster(streams.Out, pathOptions))\n\tcmd.AddCommand(NewCmdConfigDeleteContext(streams.Out, streams.ErrOut, pathOptions))\n\tcmd.AddCommand(NewCmdConfigDeleteUser(streams, pathOptions))\n\tcmd.AddCommand(NewCmdConfigRenameContext(streams.Out, pathOptions))\n\n\treturn cmd\n}","line":{"from":33,"to":75}} {"id":100031506,"name":"toBool","signature":"func toBool(propertyValue string) (bool, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/config.go","code":"func toBool(propertyValue string) (bool, error) {\n\tboolValue := false\n\tif len(propertyValue) != 0 {\n\t\tvar err error\n\t\tboolValue, err = strconv.ParseBool(propertyValue)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\treturn boolValue, nil\n}","line":{"from":77,"to":88}} {"id":100031507,"name":"helpErrorf","signature":"func helpErrorf(cmd *cobra.Command, format string, args ...interface{}) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/config.go","code":"func helpErrorf(cmd *cobra.Command, format string, args ...interface{}) error {\n\tcmd.Help()\n\tmsg := fmt.Sprintf(format, args...)\n\treturn fmt.Errorf(\"%s\", msg)\n}","line":{"from":90,"to":94}} {"id":100031508,"name":"NewCmdConfigCurrentContext","signature":"func NewCmdConfigCurrentContext(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/current_context.go","code":"// NewCmdConfigCurrentContext returns a Command instance for 'config current-context' sub command\nfunc NewCmdConfigCurrentContext(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {\n\toptions := \u0026CurrentContextOptions{ConfigAccess: configAccess}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"current-context\",\n\t\tShort: i18n.T(\"Display the current-context\"),\n\t\tLong: currentContextLong,\n\t\tExample: currentContextExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(RunCurrentContext(out, options))\n\t\t},\n\t}\n\n\treturn cmd\n}","line":{"from":45,"to":60}} {"id":100031509,"name":"RunCurrentContext","signature":"func RunCurrentContext(out io.Writer, options *CurrentContextOptions) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/current_context.go","code":"// RunCurrentContext performs the execution of 'config current-context' sub command\nfunc RunCurrentContext(out io.Writer, options *CurrentContextOptions) error {\n\tconfig, err := options.ConfigAccess.GetStartingConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif config.CurrentContext == \"\" {\n\t\terr = fmt.Errorf(\"current-context is not set\")\n\t\treturn err\n\t}\n\n\tfmt.Fprintf(out, \"%s\\n\", config.CurrentContext)\n\treturn nil\n}","line":{"from":62,"to":76}} {"id":100031510,"name":"NewCmdConfigDeleteCluster","signature":"func NewCmdConfigDeleteCluster(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/delete_cluster.go","code":"// NewCmdConfigDeleteCluster returns a Command instance for 'config delete-cluster' sub command\nfunc NewCmdConfigDeleteCluster(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"delete-cluster NAME\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Delete the specified cluster from the kubeconfig\"),\n\t\tLong: i18n.T(\"Delete the specified cluster from the kubeconfig.\"),\n\t\tExample: deleteClusterExample,\n\t\tValidArgsFunction: completion.ClusterCompletionFunc,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(runDeleteCluster(out, configAccess, cmd))\n\t\t},\n\t}\n\n\treturn cmd\n}","line":{"from":37,"to":52}} {"id":100031511,"name":"runDeleteCluster","signature":"func runDeleteCluster(out io.Writer, configAccess clientcmd.ConfigAccess, cmd *cobra.Command) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/delete_cluster.go","code":"func runDeleteCluster(out io.Writer, configAccess clientcmd.ConfigAccess, cmd *cobra.Command) error {\n\tconfig, err := configAccess.GetStartingConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\targs := cmd.Flags().Args()\n\tif len(args) != 1 {\n\t\tcmd.Help()\n\t\treturn nil\n\t}\n\n\tconfigFile := configAccess.GetDefaultFilename()\n\tif configAccess.IsExplicitFile() {\n\t\tconfigFile = configAccess.GetExplicitFile()\n\t}\n\n\tname := args[0]\n\t_, ok := config.Clusters[name]\n\tif !ok {\n\t\treturn fmt.Errorf(\"cannot delete cluster %s, not in %s\", name, configFile)\n\t}\n\n\tdelete(config.Clusters, name)\n\n\tif err := clientcmd.ModifyConfig(configAccess, *config, true); err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Fprintf(out, \"deleted cluster %s from %s\\n\", name, configFile)\n\n\treturn nil\n}","line":{"from":54,"to":86}} {"id":100031512,"name":"NewCmdConfigDeleteContext","signature":"func NewCmdConfigDeleteContext(out, errOut io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/delete_context.go","code":"// NewCmdConfigDeleteContext returns a Command instance for 'config delete-context' sub command\nfunc NewCmdConfigDeleteContext(out, errOut io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"delete-context NAME\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Delete the specified context from the kubeconfig\"),\n\t\tLong: i18n.T(\"Delete the specified context from the kubeconfig.\"),\n\t\tExample: deleteContextExample,\n\t\tValidArgsFunction: completion.ContextCompletionFunc,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(runDeleteContext(out, errOut, configAccess, cmd))\n\t\t},\n\t}\n\n\treturn cmd\n}","line":{"from":37,"to":52}} {"id":100031513,"name":"runDeleteContext","signature":"func runDeleteContext(out, errOut io.Writer, configAccess clientcmd.ConfigAccess, cmd *cobra.Command) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/delete_context.go","code":"func runDeleteContext(out, errOut io.Writer, configAccess clientcmd.ConfigAccess, cmd *cobra.Command) error {\n\tconfig, err := configAccess.GetStartingConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\targs := cmd.Flags().Args()\n\tif len(args) != 1 {\n\t\tcmd.Help()\n\t\treturn nil\n\t}\n\n\tconfigFile := configAccess.GetDefaultFilename()\n\tif configAccess.IsExplicitFile() {\n\t\tconfigFile = configAccess.GetExplicitFile()\n\t}\n\n\tname := args[0]\n\t_, ok := config.Contexts[name]\n\tif !ok {\n\t\treturn fmt.Errorf(\"cannot delete context %s, not in %s\", name, configFile)\n\t}\n\n\tif config.CurrentContext == name {\n\t\tfmt.Fprint(errOut, \"warning: this removed your active context, use \\\"kubectl config use-context\\\" to select a different one\\n\")\n\t}\n\n\tdelete(config.Contexts, name)\n\n\tif err := clientcmd.ModifyConfig(configAccess, *config, true); err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Fprintf(out, \"deleted context %s from %s\\n\", name, configFile)\n\n\treturn nil\n}","line":{"from":54,"to":90}} {"id":100031514,"name":"NewDeleteUserOptions","signature":"func NewDeleteUserOptions(ioStreams genericclioptions.IOStreams, configAccess clientcmd.ConfigAccess) *DeleteUserOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/delete_user.go","code":"// NewDeleteUserOptions creates the options for the command\nfunc NewDeleteUserOptions(ioStreams genericclioptions.IOStreams, configAccess clientcmd.ConfigAccess) *DeleteUserOptions {\n\treturn \u0026DeleteUserOptions{\n\t\tconfigAccess: configAccess,\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":50,"to":56}} {"id":100031515,"name":"NewCmdConfigDeleteUser","signature":"func NewCmdConfigDeleteUser(streams genericclioptions.IOStreams, configAccess clientcmd.ConfigAccess) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/delete_user.go","code":"// NewCmdConfigDeleteUser returns a Command instance for 'config delete-user' sub command\nfunc NewCmdConfigDeleteUser(streams genericclioptions.IOStreams, configAccess clientcmd.ConfigAccess) *cobra.Command {\n\to := NewDeleteUserOptions(streams, configAccess)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"delete-user NAME\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Delete the specified user from the kubeconfig\"),\n\t\tLong: i18n.T(\"Delete the specified user from the kubeconfig.\"),\n\t\tExample: deleteUserExample,\n\t\tValidArgsFunction: completion.UserCompletionFunc,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\treturn cmd\n}","line":{"from":58,"to":77}} {"id":100031516,"name":"Complete","signature":"func (o *DeleteUserOptions) Complete(cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/delete_user.go","code":"// Complete sets up the command to run\nfunc (o *DeleteUserOptions) Complete(cmd *cobra.Command, args []string) error {\n\tconfig, err := o.configAccess.GetStartingConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.config = config\n\n\tif len(args) != 1 {\n\t\treturn cmdutil.UsageErrorf(cmd, \"user to delete is required\")\n\t}\n\to.user = args[0]\n\n\tconfigFile := o.configAccess.GetDefaultFilename()\n\tif o.configAccess.IsExplicitFile() {\n\t\tconfigFile = o.configAccess.GetExplicitFile()\n\t}\n\to.configFile = configFile\n\n\treturn nil\n}","line":{"from":79,"to":99}} {"id":100031517,"name":"Validate","signature":"func (o *DeleteUserOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/delete_user.go","code":"// Validate ensures the command has enough info to run\nfunc (o *DeleteUserOptions) Validate() error {\n\t_, ok := o.config.AuthInfos[o.user]\n\tif !ok {\n\t\treturn fmt.Errorf(\"cannot delete user %s, not in %s\", o.user, o.configFile)\n\t}\n\n\treturn nil\n}","line":{"from":101,"to":109}} {"id":100031518,"name":"Run","signature":"func (o *DeleteUserOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/delete_user.go","code":"// Run performs the command\nfunc (o *DeleteUserOptions) Run() error {\n\tdelete(o.config.AuthInfos, o.user)\n\n\tif err := clientcmd.ModifyConfig(o.configAccess, *o.config, true); err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Fprintf(o.Out, \"deleted user %s from %s\\n\", o.user, o.configFile)\n\n\treturn nil\n}","line":{"from":111,"to":122}} {"id":100031519,"name":"NewCmdConfigGetClusters","signature":"func NewCmdConfigGetClusters(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/get_clusters.go","code":"// NewCmdConfigGetClusters creates a command object for the \"get-clusters\" action, which\n// lists all clusters defined in the kubeconfig.\nfunc NewCmdConfigGetClusters(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"get-clusters\",\n\t\tShort: i18n.T(\"Display clusters defined in the kubeconfig\"),\n\t\tLong: i18n.T(\"Display clusters defined in the kubeconfig.\"),\n\t\tExample: getClustersExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(runGetClusters(out, configAccess))\n\t\t},\n\t}\n\n\treturn cmd\n}","line":{"from":36,"to":50}} {"id":100031520,"name":"runGetClusters","signature":"func runGetClusters(out io.Writer, configAccess clientcmd.ConfigAccess) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/get_clusters.go","code":"func runGetClusters(out io.Writer, configAccess clientcmd.ConfigAccess) error {\n\tconfig, err := configAccess.GetStartingConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Fprintf(out, \"NAME\\n\")\n\tfor name := range config.Clusters {\n\t\tfmt.Fprintf(out, \"%s\\n\", name)\n\t}\n\n\treturn nil\n}","line":{"from":52,"to":64}} {"id":100031521,"name":"NewCmdConfigGetContexts","signature":"func NewCmdConfigGetContexts(streams genericclioptions.IOStreams, configAccess clientcmd.ConfigAccess) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/get_contexts.go","code":"// NewCmdConfigGetContexts creates a command object for the \"get-contexts\" action, which\n// retrieves one or more contexts from a kubeconfig.\nfunc NewCmdConfigGetContexts(streams genericclioptions.IOStreams, configAccess clientcmd.ConfigAccess) *cobra.Command {\n\toptions := \u0026GetContextsOptions{\n\t\tconfigAccess: configAccess,\n\n\t\tIOStreams: streams,\n\t}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"get-contexts [(-o|--output=)name)]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Describe one or many contexts\"),\n\t\tLong: getContextsLong,\n\t\tExample: getContextsExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(options.Complete(cmd, args))\n\t\t\tcmdutil.CheckErr(options.Validate())\n\t\t\tcmdutil.CheckErr(options.RunGetContexts())\n\t\t},\n\t}\n\n\tcmd.Flags().BoolVar(\u0026options.noHeaders, \"no-headers\", options.noHeaders, \"When using the default or custom-column output format, don't print headers (default print headers).\")\n\tcmd.Flags().StringVarP(\u0026options.outputFormat, \"output\", \"o\", options.outputFormat, `Output format. One of: (name).`)\n\treturn cmd\n}","line":{"from":63,"to":88}} {"id":100031522,"name":"Complete","signature":"func (o *GetContextsOptions) Complete(cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/get_contexts.go","code":"// Complete assigns GetContextsOptions from the args.\nfunc (o *GetContextsOptions) Complete(cmd *cobra.Command, args []string) error {\n\tsupportedOutputTypes := sets.NewString(\"\", \"name\")\n\tif !supportedOutputTypes.Has(o.outputFormat) {\n\t\treturn fmt.Errorf(\"--output %v is not available in kubectl config get-contexts; resetting to default output format\", o.outputFormat)\n\t}\n\to.contextNames = args\n\to.nameOnly = false\n\tif o.outputFormat == \"name\" {\n\t\to.nameOnly = true\n\t}\n\to.showHeaders = true\n\tif cmdutil.GetFlagBool(cmd, \"no-headers\") || o.nameOnly {\n\t\to.showHeaders = false\n\t}\n\n\treturn nil\n}","line":{"from":90,"to":107}} {"id":100031523,"name":"Validate","signature":"func (o *GetContextsOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/get_contexts.go","code":"// Validate ensures the of output format\nfunc (o *GetContextsOptions) Validate() error {\n\treturn nil\n}","line":{"from":109,"to":112}} {"id":100031524,"name":"RunGetContexts","signature":"func (o GetContextsOptions) RunGetContexts() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/get_contexts.go","code":"// RunGetContexts implements all the necessary functionality for context retrieval.\nfunc (o GetContextsOptions) RunGetContexts() error {\n\tconfig, err := o.configAccess.GetStartingConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tout, found := o.Out.(*tabwriter.Writer)\n\tif !found {\n\t\tout = printers.GetNewTabWriter(o.Out)\n\t\tdefer out.Flush()\n\t}\n\n\t// Build a list of context names to print, and warn if any requested contexts are not found.\n\t// Do this before printing the headers so it doesn't look ugly.\n\tallErrs := []error{}\n\ttoPrint := []string{}\n\tif len(o.contextNames) == 0 {\n\t\tfor name := range config.Contexts {\n\t\t\ttoPrint = append(toPrint, name)\n\t\t}\n\t} else {\n\t\tfor _, name := range o.contextNames {\n\t\t\t_, ok := config.Contexts[name]\n\t\t\tif ok {\n\t\t\t\ttoPrint = append(toPrint, name)\n\t\t\t} else {\n\t\t\t\tallErrs = append(allErrs, fmt.Errorf(\"context %v not found\", name))\n\t\t\t}\n\t\t}\n\t}\n\tif o.showHeaders {\n\t\terr = printContextHeaders(out, o.nameOnly)\n\t\tif err != nil {\n\t\t\tallErrs = append(allErrs, err)\n\t\t}\n\t}\n\n\tsort.Strings(toPrint)\n\tfor _, name := range toPrint {\n\t\terr = printContext(name, config.Contexts[name], out, o.nameOnly, config.CurrentContext == name)\n\t\tif err != nil {\n\t\t\tallErrs = append(allErrs, err)\n\t\t}\n\t}\n\n\treturn utilerrors.NewAggregate(allErrs)\n}","line":{"from":114,"to":161}} {"id":100031525,"name":"printContextHeaders","signature":"func printContextHeaders(out io.Writer, nameOnly bool) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/get_contexts.go","code":"func printContextHeaders(out io.Writer, nameOnly bool) error {\n\tcolumnNames := []string{\"CURRENT\", \"NAME\", \"CLUSTER\", \"AUTHINFO\", \"NAMESPACE\"}\n\tif nameOnly {\n\t\tcolumnNames = columnNames[:1]\n\t}\n\t_, err := fmt.Fprintf(out, \"%s\\n\", strings.Join(columnNames, \"\\t\"))\n\treturn err\n}","line":{"from":163,"to":170}} {"id":100031526,"name":"printContext","signature":"func printContext(name string, context *clientcmdapi.Context, w io.Writer, nameOnly, current bool) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/get_contexts.go","code":"func printContext(name string, context *clientcmdapi.Context, w io.Writer, nameOnly, current bool) error {\n\tif nameOnly {\n\t\t_, err := fmt.Fprintf(w, \"%s\\n\", name)\n\t\treturn err\n\t}\n\tprefix := \" \"\n\tif current {\n\t\tprefix = \"*\"\n\t}\n\t_, err := fmt.Fprintf(w, \"%s\\t%s\\t%s\\t%s\\t%s\\n\", prefix, name, context.Cluster, context.AuthInfo, context.Namespace)\n\treturn err\n}","line":{"from":172,"to":183}} {"id":100031527,"name":"NewGetUsersOptions","signature":"func NewGetUsersOptions(ioStreams genericclioptions.IOStreams, configAccess clientcmd.ConfigAccess) *GetUsersOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/get_users.go","code":"// NewGetUsersOptions creates the options for the command\nfunc NewGetUsersOptions(ioStreams genericclioptions.IOStreams, configAccess clientcmd.ConfigAccess) *GetUsersOptions {\n\treturn \u0026GetUsersOptions{\n\t\tconfigAccess: configAccess,\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":45,"to":51}} {"id":100031528,"name":"NewCmdConfigGetUsers","signature":"func NewCmdConfigGetUsers(streams genericclioptions.IOStreams, configAccess clientcmd.ConfigAccess) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/get_users.go","code":"// NewCmdConfigGetUsers creates a command object for the \"get-users\" action, which\n// lists all users defined in the kubeconfig.\nfunc NewCmdConfigGetUsers(streams genericclioptions.IOStreams, configAccess clientcmd.ConfigAccess) *cobra.Command {\n\to := NewGetUsersOptions(streams, configAccess)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"get-users\",\n\t\tShort: i18n.T(\"Display users defined in the kubeconfig\"),\n\t\tLong: i18n.T(\"Display users defined in the kubeconfig.\"),\n\t\tExample: getUsersExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\treturn cmd\n}","line":{"from":53,"to":69}} {"id":100031529,"name":"Run","signature":"func (o *GetUsersOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/get_users.go","code":"// Run performs the command\nfunc (o *GetUsersOptions) Run() error {\n\tconfig, err := o.configAccess.GetStartingConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tusers := make([]string, 0, len(config.AuthInfos))\n\tfor user := range config.AuthInfos {\n\t\tusers = append(users, user)\n\t}\n\tsort.Strings(users)\n\n\tfmt.Fprintf(o.Out, \"NAME\\n\")\n\tfor _, user := range users {\n\t\tfmt.Fprintf(o.Out, \"%s\\n\", user)\n\t}\n\n\treturn nil\n}","line":{"from":71,"to":90}} {"id":100031530,"name":"newNavigationSteps","signature":"func newNavigationSteps(path string) (*navigationSteps, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/navigation_step_parser.go","code":"func newNavigationSteps(path string) (*navigationSteps, error) {\n\tsteps := []navigationStep{}\n\tindividualParts := strings.Split(path, \".\")\n\n\tcurrType := reflect.TypeOf(clientcmdapi.Config{})\n\tcurrPartIndex := 0\n\tfor currPartIndex \u003c len(individualParts) {\n\t\tswitch currType.Kind() {\n\t\tcase reflect.Map:\n\t\t\t// if we're in a map, we need to locate a name. That name may contain dots, so we need to know what tokens are legal for the map's value type\n\t\t\t// for example, we could have a set request like: `set clusters.10.10.12.56.insecure-skip-tls-verify true`. We enter this case with\n\t\t\t// steps representing 10, 10, 12, 56, insecure-skip-tls-verify. The name is \"10.10.12.56\", so we want to collect all those parts together and\n\t\t\t// store them as a single step. In order to do that, we need to determine what set of tokens is a legal step AFTER the name of the map key\n\t\t\t// This set of reflective code pulls the type of the map values, uses that type to look up the set of legal tags. Those legal tags are used to\n\t\t\t// walk the list of remaining parts until we find a match to a legal tag or the end of the string. That name is used to burn all the used parts.\n\t\t\tmapValueType := currType.Elem().Elem()\n\t\t\tmapValueOptions, err := getPotentialTypeValues(mapValueType)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tnextPart := findNameStep(individualParts[currPartIndex:], sets.StringKeySet(mapValueOptions))\n\n\t\t\tsteps = append(steps, navigationStep{nextPart, mapValueType})\n\t\t\tcurrPartIndex += len(strings.Split(nextPart, \".\"))\n\t\t\tcurrType = mapValueType\n\n\t\tcase reflect.Struct:\n\t\t\tnextPart := individualParts[currPartIndex]\n\n\t\t\toptions, err := getPotentialTypeValues(currType)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfieldType, exists := options[nextPart]\n\t\t\tif !exists {\n\t\t\t\treturn nil, fmt.Errorf(\"unable to parse %v after %v at %v\", path, steps, currType)\n\t\t\t}\n\n\t\t\tsteps = append(steps, navigationStep{nextPart, fieldType})\n\t\t\tcurrPartIndex += len(strings.Split(nextPart, \".\"))\n\t\t\tcurrType = fieldType\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unable to parse one or more field values of %v\", path)\n\t\t}\n\t}\n\n\treturn \u0026navigationSteps{steps, 0}, nil\n}","line":{"from":38,"to":85}} {"id":100031531,"name":"pop","signature":"func (s *navigationSteps) pop() navigationStep","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/navigation_step_parser.go","code":"func (s *navigationSteps) pop() navigationStep {\n\tif s.moreStepsRemaining() {\n\t\ts.currentStepIndex++\n\t\treturn s.steps[s.currentStepIndex-1]\n\t}\n\treturn navigationStep{}\n}","line":{"from":87,"to":93}} {"id":100031532,"name":"moreStepsRemaining","signature":"func (s *navigationSteps) moreStepsRemaining() bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/navigation_step_parser.go","code":"func (s *navigationSteps) moreStepsRemaining() bool {\n\treturn len(s.steps) \u003e s.currentStepIndex\n}","line":{"from":95,"to":97}} {"id":100031533,"name":"findNameStep","signature":"func findNameStep(parts []string, typeOptions sets.String) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/navigation_step_parser.go","code":"// findNameStep takes the list of parts and a set of valid tags that can be used after the name. It then walks the list of parts\n// until it find a valid \"next\" tag or until it reaches the end of the parts and then builds the name back up out of the individual parts\nfunc findNameStep(parts []string, typeOptions sets.String) string {\n\tif len(parts) == 0 {\n\t\treturn \"\"\n\t}\n\n\tnumberOfPartsInStep := findKnownValue(parts[1:], typeOptions) + 1\n\t// if we didn't find a known value, then the entire thing must be a name\n\tif numberOfPartsInStep == 0 {\n\t\tnumberOfPartsInStep = len(parts)\n\t}\n\tnextParts := parts[0:numberOfPartsInStep]\n\n\treturn strings.Join(nextParts, \".\")\n}","line":{"from":99,"to":114}} {"id":100031534,"name":"getPotentialTypeValues","signature":"func getPotentialTypeValues(typeValue reflect.Type) (map[string]reflect.Type, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/navigation_step_parser.go","code":"// getPotentialTypeValues takes a type and looks up the tags used to represent its fields when serialized.\nfunc getPotentialTypeValues(typeValue reflect.Type) (map[string]reflect.Type, error) {\n\tif typeValue.Kind() == reflect.Pointer {\n\t\ttypeValue = typeValue.Elem()\n\t}\n\n\tif typeValue.Kind() != reflect.Struct {\n\t\treturn nil, fmt.Errorf(\"%v is not of type struct\", typeValue)\n\t}\n\n\tret := make(map[string]reflect.Type)\n\n\tfor fieldIndex := 0; fieldIndex \u003c typeValue.NumField(); fieldIndex++ {\n\t\tfieldType := typeValue.Field(fieldIndex)\n\t\tyamlTag := fieldType.Tag.Get(\"json\")\n\t\tyamlTagName := strings.Split(yamlTag, \",\")[0]\n\n\t\tret[yamlTagName] = fieldType.Type\n\t}\n\n\treturn ret, nil\n}","line":{"from":116,"to":137}} {"id":100031535,"name":"findKnownValue","signature":"func findKnownValue(parts []string, valueOptions sets.String) int","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/navigation_step_parser.go","code":"func findKnownValue(parts []string, valueOptions sets.String) int {\n\tfor i := range parts {\n\t\tif valueOptions.Has(parts[i]) {\n\t\t\treturn i\n\t\t}\n\t}\n\n\treturn -1\n}","line":{"from":139,"to":147}} {"id":100031536,"name":"NewCmdConfigRenameContext","signature":"func NewCmdConfigRenameContext(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/rename_context.go","code":"// NewCmdConfigRenameContext creates a command object for the \"rename-context\" action\nfunc NewCmdConfigRenameContext(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {\n\toptions := \u0026RenameContextOptions{configAccess: configAccess}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: renameContextUse,\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: renameContextShort,\n\t\tLong: renameContextLong,\n\t\tExample: renameContextExample,\n\t\tValidArgsFunction: completion.ContextCompletionFunc,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(options.Complete(cmd, args, out))\n\t\t\tcmdutil.CheckErr(options.Validate())\n\t\t\tcmdutil.CheckErr(options.RunRenameContext(out))\n\t\t},\n\t}\n\treturn cmd\n}","line":{"from":61,"to":79}} {"id":100031537,"name":"Complete","signature":"func (o *RenameContextOptions) Complete(cmd *cobra.Command, args []string, out io.Writer) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/rename_context.go","code":"// Complete assigns RenameContextOptions from the args.\nfunc (o *RenameContextOptions) Complete(cmd *cobra.Command, args []string, out io.Writer) error {\n\tif len(args) != 2 {\n\t\treturn helpErrorf(cmd, \"Unexpected args: %v\", args)\n\t}\n\n\to.contextName = args[0]\n\to.newName = args[1]\n\treturn nil\n}","line":{"from":81,"to":90}} {"id":100031538,"name":"Validate","signature":"func (o RenameContextOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/rename_context.go","code":"// Validate makes sure that provided values for command-line options are valid\nfunc (o RenameContextOptions) Validate() error {\n\tif len(o.newName) == 0 {\n\t\treturn errors.New(\"You must specify a new non-empty context name\")\n\t}\n\treturn nil\n}","line":{"from":92,"to":98}} {"id":100031539,"name":"RunRenameContext","signature":"func (o RenameContextOptions) RunRenameContext(out io.Writer) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/rename_context.go","code":"// RunRenameContext performs the execution for 'config rename-context' sub command\nfunc (o RenameContextOptions) RunRenameContext(out io.Writer) error {\n\tconfig, err := o.configAccess.GetStartingConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconfigFile := o.configAccess.GetDefaultFilename()\n\tif o.configAccess.IsExplicitFile() {\n\t\tconfigFile = o.configAccess.GetExplicitFile()\n\t}\n\n\tcontext, exists := config.Contexts[o.contextName]\n\tif !exists {\n\t\treturn fmt.Errorf(\"cannot rename the context %q, it's not in %s\", o.contextName, configFile)\n\t}\n\n\t_, newExists := config.Contexts[o.newName]\n\tif newExists {\n\t\treturn fmt.Errorf(\"cannot rename the context %q, the context %q already exists in %s\", o.contextName, o.newName, configFile)\n\t}\n\n\tconfig.Contexts[o.newName] = context\n\tdelete(config.Contexts, o.contextName)\n\n\tif config.CurrentContext == o.contextName {\n\t\tconfig.CurrentContext = o.newName\n\t}\n\n\tif err := clientcmd.ModifyConfig(o.configAccess, *config, true); err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Fprintf(out, \"Context %q renamed to %q.\\n\", o.contextName, o.newName)\n\treturn nil\n}","line":{"from":100,"to":135}} {"id":100031540,"name":"NewCmdConfigSet","signature":"func NewCmdConfigSet(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/set.go","code":"// NewCmdConfigSet returns a Command instance for 'config set' sub command\nfunc NewCmdConfigSet(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {\n\toptions := \u0026setOptions{configAccess: configAccess}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"set PROPERTY_NAME PROPERTY_VALUE\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Set an individual value in a kubeconfig file\"),\n\t\tLong: setLong,\n\t\tExample: setExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(options.complete(cmd))\n\t\t\tcmdutil.CheckErr(options.run())\n\t\t\tfmt.Fprintf(out, \"Property %q set.\\n\", options.propertyName)\n\t\t},\n\t}\n\n\tf := cmd.Flags().VarPF(\u0026options.setRawBytes, \"set-raw-bytes\", \"\", \"When writing a []byte PROPERTY_VALUE, write the given string directly without base64 decoding.\")\n\tf.NoOptDefVal = \"true\"\n\treturn cmd\n}","line":{"from":67,"to":87}} {"id":100031541,"name":"run","signature":"func (o setOptions) run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/set.go","code":"func (o setOptions) run() error {\n\terr := o.validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconfig, err := o.configAccess.GetStartingConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\tsteps, err := newNavigationSteps(o.propertyName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsetRawBytes := false\n\tif o.setRawBytes.Provided() {\n\t\tsetRawBytes = o.setRawBytes.Value()\n\t}\n\n\terr = modifyConfig(reflect.ValueOf(config), steps, o.propertyValue, false, setRawBytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := clientcmd.ModifyConfig(o.configAccess, *config, false); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":89,"to":119}} {"id":100031542,"name":"complete","signature":"func (o *setOptions) complete(cmd *cobra.Command) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/set.go","code":"func (o *setOptions) complete(cmd *cobra.Command) error {\n\tendingArgs := cmd.Flags().Args()\n\tif len(endingArgs) != 2 {\n\t\treturn helpErrorf(cmd, \"Unexpected args: %v\", endingArgs)\n\t}\n\n\to.propertyValue = endingArgs[1]\n\to.propertyName = endingArgs[0]\n\treturn nil\n}","line":{"from":121,"to":130}} {"id":100031543,"name":"validate","signature":"func (o setOptions) validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/set.go","code":"func (o setOptions) validate() error {\n\tif len(o.propertyValue) == 0 {\n\t\treturn errors.New(\"you cannot use set to unset a property\")\n\t}\n\n\tif len(o.propertyName) == 0 {\n\t\treturn errors.New(\"you must specify a property\")\n\t}\n\n\treturn nil\n}","line":{"from":132,"to":142}} {"id":100031544,"name":"modifyConfig","signature":"func modifyConfig(curr reflect.Value, steps *navigationSteps, propertyValue string, unset bool, setRawBytes bool) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/set.go","code":"func modifyConfig(curr reflect.Value, steps *navigationSteps, propertyValue string, unset bool, setRawBytes bool) error {\n\tcurrStep := steps.pop()\n\n\tactualCurrValue := curr\n\tif curr.Kind() == reflect.Pointer {\n\t\tactualCurrValue = curr.Elem()\n\t}\n\n\tswitch actualCurrValue.Kind() {\n\tcase reflect.Map:\n\t\tif !steps.moreStepsRemaining() \u0026\u0026 !unset {\n\t\t\treturn fmt.Errorf(\"can't set a map to a value: %v\", actualCurrValue)\n\t\t}\n\n\t\tmapKey := reflect.ValueOf(currStep.stepValue)\n\t\tmapValueType := curr.Type().Elem().Elem()\n\n\t\tif !steps.moreStepsRemaining() \u0026\u0026 unset {\n\t\t\tactualCurrValue.SetMapIndex(mapKey, reflect.Value{})\n\t\t\treturn nil\n\t\t}\n\n\t\tcurrMapValue := actualCurrValue.MapIndex(mapKey)\n\n\t\tneedToSetNewMapValue := currMapValue.Kind() == reflect.Invalid\n\t\tif needToSetNewMapValue {\n\t\t\tif unset {\n\t\t\t\treturn fmt.Errorf(\"current map key `%v` is invalid\", mapKey.Interface())\n\t\t\t}\n\t\t\tcurrMapValue = reflect.New(mapValueType.Elem()).Elem().Addr()\n\t\t\tactualCurrValue.SetMapIndex(mapKey, currMapValue)\n\t\t}\n\n\t\terr := modifyConfig(currMapValue, steps, propertyValue, unset, setRawBytes)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\n\tcase reflect.String:\n\t\tif steps.moreStepsRemaining() {\n\t\t\treturn fmt.Errorf(\"can't have more steps after a string. %v\", steps)\n\t\t}\n\t\tactualCurrValue.SetString(propertyValue)\n\t\treturn nil\n\n\tcase reflect.Slice:\n\t\tif steps.moreStepsRemaining() {\n\t\t\treturn fmt.Errorf(\"can't have more steps after bytes. %v\", steps)\n\t\t}\n\t\tinnerKind := actualCurrValue.Type().Elem().Kind()\n\t\tif innerKind != reflect.Uint8 {\n\t\t\treturn fmt.Errorf(\"unrecognized slice type. %v\", innerKind)\n\t\t}\n\n\t\tif unset {\n\t\t\tactualCurrValue.Set(reflect.Zero(actualCurrValue.Type()))\n\t\t\treturn nil\n\t\t}\n\n\t\tif setRawBytes {\n\t\t\tactualCurrValue.SetBytes([]byte(propertyValue))\n\t\t} else {\n\t\t\tval, err := base64.StdEncoding.DecodeString(propertyValue)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error decoding input value: %v\", err)\n\t\t\t}\n\t\t\tactualCurrValue.SetBytes(val)\n\t\t}\n\t\treturn nil\n\n\tcase reflect.Bool:\n\t\tif steps.moreStepsRemaining() {\n\t\t\treturn fmt.Errorf(\"can't have more steps after a bool. %v\", steps)\n\t\t}\n\t\tboolValue, err := toBool(propertyValue)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tactualCurrValue.SetBool(boolValue)\n\t\treturn nil\n\n\tcase reflect.Struct:\n\t\tfor fieldIndex := 0; fieldIndex \u003c actualCurrValue.NumField(); fieldIndex++ {\n\t\t\tcurrFieldValue := actualCurrValue.Field(fieldIndex)\n\t\t\tcurrFieldType := actualCurrValue.Type().Field(fieldIndex)\n\t\t\tcurrYamlTag := currFieldType.Tag.Get(\"json\")\n\t\t\tcurrFieldTypeYamlName := strings.Split(currYamlTag, \",\")[0]\n\n\t\t\tif currFieldTypeYamlName == currStep.stepValue {\n\t\t\t\tthisMapHasNoValue := (currFieldValue.Kind() == reflect.Map \u0026\u0026 currFieldValue.IsNil())\n\n\t\t\t\tif thisMapHasNoValue {\n\t\t\t\t\tnewValue := reflect.MakeMap(currFieldValue.Type())\n\t\t\t\t\tcurrFieldValue.Set(newValue)\n\n\t\t\t\t\tif !steps.moreStepsRemaining() \u0026\u0026 unset {\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif !steps.moreStepsRemaining() \u0026\u0026 unset {\n\t\t\t\t\t// if we're supposed to unset the value or if the value is a map that doesn't exist, create a new value and overwrite\n\t\t\t\t\tnewValue := reflect.New(currFieldValue.Type()).Elem()\n\t\t\t\t\tcurrFieldValue.Set(newValue)\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\treturn modifyConfig(currFieldValue.Addr(), steps, propertyValue, unset, setRawBytes)\n\t\t\t}\n\t\t}\n\n\t\treturn fmt.Errorf(\"unable to locate path %#v under %v\", currStep, actualCurrValue)\n\n\t}\n\n\tpanic(fmt.Errorf(\"unrecognized type: %v\", actualCurrValue))\n}","line":{"from":144,"to":262}} {"id":100031545,"name":"NewCmdConfigSetCluster","signature":"func NewCmdConfigSetCluster(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/set_cluster.go","code":"// NewCmdConfigSetCluster returns a Command instance for 'config set-cluster' sub command\nfunc NewCmdConfigSetCluster(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {\n\toptions := \u0026setClusterOptions{configAccess: configAccess}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: fmt.Sprintf(\"set-cluster NAME [--%v=server] [--%v=path/to/certificate/authority] [--%v=true] [--%v=example.com]\", clientcmd.FlagAPIServer, clientcmd.FlagCAFile, clientcmd.FlagInsecure, clientcmd.FlagTLSServerName),\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Set a cluster entry in kubeconfig\"),\n\t\tLong: setClusterLong,\n\t\tExample: setClusterExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(options.complete(cmd))\n\t\t\tcmdutil.CheckErr(options.run())\n\t\t\tfmt.Fprintf(out, \"Cluster %q set.\\n\", options.name)\n\t\t},\n\t}\n\n\toptions.insecureSkipTLSVerify.Default(false)\n\n\tcmd.Flags().Var(\u0026options.server, clientcmd.FlagAPIServer, clientcmd.FlagAPIServer+\" for the cluster entry in kubeconfig\")\n\tcmd.Flags().Var(\u0026options.tlsServerName, clientcmd.FlagTLSServerName, clientcmd.FlagTLSServerName+\" for the cluster entry in kubeconfig\")\n\tf := cmd.Flags().VarPF(\u0026options.insecureSkipTLSVerify, clientcmd.FlagInsecure, \"\", clientcmd.FlagInsecure+\" for the cluster entry in kubeconfig\")\n\tf.NoOptDefVal = \"true\"\n\tcmd.Flags().Var(\u0026options.certificateAuthority, clientcmd.FlagCAFile, \"Path to \"+clientcmd.FlagCAFile+\" file for the cluster entry in kubeconfig\")\n\tcmd.MarkFlagFilename(clientcmd.FlagCAFile)\n\tf = cmd.Flags().VarPF(\u0026options.embedCAData, clientcmd.FlagEmbedCerts, \"\", clientcmd.FlagEmbedCerts+\" for the cluster entry in kubeconfig\")\n\tf.NoOptDefVal = \"true\"\n\tcmd.Flags().Var(\u0026options.proxyURL, clientcmd.FlagProxyURL, clientcmd.FlagProxyURL+\" for the cluster entry in kubeconfig\")\n\n\treturn cmd\n}","line":{"from":69,"to":99}} {"id":100031546,"name":"run","signature":"func (o setClusterOptions) run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/set_cluster.go","code":"func (o setClusterOptions) run() error {\n\terr := o.validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconfig, err := o.configAccess.GetStartingConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstartingStanza, exists := config.Clusters[o.name]\n\tif !exists {\n\t\tstartingStanza = clientcmdapi.NewCluster()\n\t}\n\tcluster := o.modifyCluster(*startingStanza)\n\tconfig.Clusters[o.name] = \u0026cluster\n\n\tif err := clientcmd.ModifyConfig(o.configAccess, *config, true); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":101,"to":124}} {"id":100031547,"name":"modifyCluster","signature":"func (o *setClusterOptions) modifyCluster(existingCluster clientcmdapi.Cluster) clientcmdapi.Cluster","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/set_cluster.go","code":"func (o *setClusterOptions) modifyCluster(existingCluster clientcmdapi.Cluster) clientcmdapi.Cluster {\n\tmodifiedCluster := existingCluster\n\n\tif o.server.Provided() {\n\t\tmodifiedCluster.Server = o.server.Value()\n\t\t// specifying a --server on the command line, overrides the TLSServerName that was specified in the kubeconfig file.\n\t\t// if both are specified, then the next if block will write the new TLSServerName.\n\t\tmodifiedCluster.TLSServerName = \"\"\n\t}\n\tif o.tlsServerName.Provided() {\n\t\tmodifiedCluster.TLSServerName = o.tlsServerName.Value()\n\t}\n\tif o.insecureSkipTLSVerify.Provided() {\n\t\tmodifiedCluster.InsecureSkipTLSVerify = o.insecureSkipTLSVerify.Value()\n\t\t// Specifying insecure mode clears any certificate authority\n\t\tif modifiedCluster.InsecureSkipTLSVerify {\n\t\t\tmodifiedCluster.CertificateAuthority = \"\"\n\t\t\tmodifiedCluster.CertificateAuthorityData = nil\n\t\t}\n\t}\n\tif o.certificateAuthority.Provided() {\n\t\tcaPath := o.certificateAuthority.Value()\n\t\tif o.embedCAData.Value() {\n\t\t\tmodifiedCluster.CertificateAuthorityData, _ = os.ReadFile(caPath)\n\t\t\tmodifiedCluster.InsecureSkipTLSVerify = false\n\t\t\tmodifiedCluster.CertificateAuthority = \"\"\n\t\t} else {\n\t\t\tcaPath, _ = filepath.Abs(caPath)\n\t\t\tmodifiedCluster.CertificateAuthority = caPath\n\t\t\t// Specifying a certificate authority file clears certificate authority data and insecure mode\n\t\t\tif caPath != \"\" {\n\t\t\t\tmodifiedCluster.InsecureSkipTLSVerify = false\n\t\t\t\tmodifiedCluster.CertificateAuthorityData = nil\n\t\t\t}\n\t\t}\n\t}\n\n\tif o.proxyURL.Provided() {\n\t\tmodifiedCluster.ProxyURL = o.proxyURL.Value()\n\t}\n\n\treturn modifiedCluster\n}","line":{"from":126,"to":168}} {"id":100031548,"name":"complete","signature":"func (o *setClusterOptions) complete(cmd *cobra.Command) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/set_cluster.go","code":"func (o *setClusterOptions) complete(cmd *cobra.Command) error {\n\targs := cmd.Flags().Args()\n\tif len(args) != 1 {\n\t\treturn helpErrorf(cmd, \"Unexpected args: %v\", args)\n\t}\n\n\to.name = args[0]\n\treturn nil\n}","line":{"from":170,"to":178}} {"id":100031549,"name":"validate","signature":"func (o setClusterOptions) validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/set_cluster.go","code":"func (o setClusterOptions) validate() error {\n\tif len(o.name) == 0 {\n\t\treturn errors.New(\"you must specify a non-empty cluster name\")\n\t}\n\tif o.insecureSkipTLSVerify.Value() \u0026\u0026 o.certificateAuthority.Value() != \"\" {\n\t\treturn errors.New(\"you cannot specify a certificate authority and insecure mode at the same time\")\n\t}\n\tif o.embedCAData.Value() {\n\t\tcaPath := o.certificateAuthority.Value()\n\t\tif caPath == \"\" {\n\t\t\treturn fmt.Errorf(\"you must specify a --%s to embed\", clientcmd.FlagCAFile)\n\t\t}\n\t\tif _, err := os.Stat(caPath); err != nil {\n\t\t\treturn fmt.Errorf(\"could not stat %s file %s: %v\", clientcmd.FlagCAFile, caPath, err)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":180,"to":198}} {"id":100031550,"name":"NewCmdConfigSetContext","signature":"func NewCmdConfigSetContext(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/set_context.go","code":"// NewCmdConfigSetContext returns a Command instance for 'config set-context' sub command\nfunc NewCmdConfigSetContext(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {\n\toptions := \u0026setContextOptions{configAccess: configAccess}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: fmt.Sprintf(\"set-context [NAME | --current] [--%v=cluster_nickname] [--%v=user_nickname] [--%v=namespace]\", clientcmd.FlagClusterName, clientcmd.FlagAuthInfoName, clientcmd.FlagNamespace),\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Set a context entry in kubeconfig\"),\n\t\tLong: setContextLong,\n\t\tExample: setContextExample,\n\t\tValidArgsFunction: completion.ContextCompletionFunc,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(options.complete(cmd))\n\t\t\tname, exists, err := options.run()\n\t\t\tcmdutil.CheckErr(err)\n\t\t\tif exists {\n\t\t\t\tfmt.Fprintf(out, \"Context %q modified.\\n\", name)\n\t\t\t} else {\n\t\t\t\tfmt.Fprintf(out, \"Context %q created.\\n\", name)\n\t\t\t}\n\t\t},\n\t}\n\n\tcmd.Flags().BoolVar(\u0026options.currContext, \"current\", options.currContext, \"Modify the current context\")\n\tcmd.Flags().Var(\u0026options.cluster, clientcmd.FlagClusterName, clientcmd.FlagClusterName+\" for the context entry in kubeconfig\")\n\tcmd.Flags().Var(\u0026options.authInfo, clientcmd.FlagAuthInfoName, clientcmd.FlagAuthInfoName+\" for the context entry in kubeconfig\")\n\tcmd.Flags().Var(\u0026options.namespace, clientcmd.FlagNamespace, clientcmd.FlagNamespace+\" for the context entry in kubeconfig\")\n\n\treturn cmd\n}","line":{"from":55,"to":84}} {"id":100031551,"name":"run","signature":"func (o setContextOptions) run() (string, bool, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/set_context.go","code":"func (o setContextOptions) run() (string, bool, error) {\n\terr := o.validate()\n\tif err != nil {\n\t\treturn \"\", false, err\n\t}\n\n\tconfig, err := o.configAccess.GetStartingConfig()\n\tif err != nil {\n\t\treturn \"\", false, err\n\t}\n\n\tname := o.name\n\tif o.currContext {\n\t\tif len(config.CurrentContext) == 0 {\n\t\t\treturn \"\", false, errors.New(\"no current context is set\")\n\t\t}\n\t\tname = config.CurrentContext\n\t}\n\n\tstartingStanza, exists := config.Contexts[name]\n\tif !exists {\n\t\tstartingStanza = clientcmdapi.NewContext()\n\t}\n\tcontext := o.modifyContext(*startingStanza)\n\tconfig.Contexts[name] = \u0026context\n\n\tif err := clientcmd.ModifyConfig(o.configAccess, *config, true); err != nil {\n\t\treturn name, exists, err\n\t}\n\n\treturn name, exists, nil\n}","line":{"from":86,"to":117}} {"id":100031552,"name":"modifyContext","signature":"func (o *setContextOptions) modifyContext(existingContext clientcmdapi.Context) clientcmdapi.Context","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/set_context.go","code":"func (o *setContextOptions) modifyContext(existingContext clientcmdapi.Context) clientcmdapi.Context {\n\tmodifiedContext := existingContext\n\n\tif o.cluster.Provided() {\n\t\tmodifiedContext.Cluster = o.cluster.Value()\n\t}\n\tif o.authInfo.Provided() {\n\t\tmodifiedContext.AuthInfo = o.authInfo.Value()\n\t}\n\tif o.namespace.Provided() {\n\t\tmodifiedContext.Namespace = o.namespace.Value()\n\t}\n\n\treturn modifiedContext\n}","line":{"from":119,"to":133}} {"id":100031553,"name":"complete","signature":"func (o *setContextOptions) complete(cmd *cobra.Command) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/set_context.go","code":"func (o *setContextOptions) complete(cmd *cobra.Command) error {\n\targs := cmd.Flags().Args()\n\tif len(args) \u003e 1 {\n\t\treturn helpErrorf(cmd, \"Unexpected args: %v\", args)\n\t}\n\tif len(args) == 1 {\n\t\to.name = args[0]\n\t}\n\treturn nil\n}","line":{"from":135,"to":144}} {"id":100031554,"name":"validate","signature":"func (o setContextOptions) validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/set_context.go","code":"func (o setContextOptions) validate() error {\n\tif len(o.name) == 0 \u0026\u0026 !o.currContext {\n\t\treturn errors.New(\"you must specify a non-empty context name or --current\")\n\t}\n\tif len(o.name) \u003e 0 \u0026\u0026 o.currContext {\n\t\treturn errors.New(\"you cannot specify both a context name and --current\")\n\t}\n\n\treturn nil\n}","line":{"from":146,"to":155}} {"id":100031555,"name":"NewCmdConfigSetCredentials","signature":"func NewCmdConfigSetCredentials(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/set_credentials.go","code":"// NewCmdConfigSetCredentials returns a Command instance for 'config set-credentials' sub command\nfunc NewCmdConfigSetCredentials(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {\n\toptions := \u0026setCredentialsOptions{configAccess: configAccess}\n\treturn newCmdConfigSetCredentials(out, options)\n}","line":{"from":118,"to":122}} {"id":100031556,"name":"NewCmdConfigSetAuthInfo","signature":"func NewCmdConfigSetAuthInfo(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/set_credentials.go","code":"// NewCmdConfigSetAuthInfo returns a Command instance for 'config set-credentials' sub command\n// DEPRECATED: Use NewCmdConfigSetCredentials instead\nfunc NewCmdConfigSetAuthInfo(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {\n\treturn NewCmdConfigSetCredentials(out, configAccess)\n}","line":{"from":124,"to":128}} {"id":100031557,"name":"newCmdConfigSetCredentials","signature":"func newCmdConfigSetCredentials(out io.Writer, options *setCredentialsOptions) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/set_credentials.go","code":"func newCmdConfigSetCredentials(out io.Writer, options *setCredentialsOptions) *cobra.Command {\n\tcmd := \u0026cobra.Command{\n\t\tUse: fmt.Sprintf(\n\t\t\t\"set-credentials NAME [--%v=path/to/certfile] \"+\n\t\t\t\t\"[--%v=path/to/keyfile] \"+\n\t\t\t\t\"[--%v=bearer_token] \"+\n\t\t\t\t\"[--%v=basic_user] \"+\n\t\t\t\t\"[--%v=basic_password] \"+\n\t\t\t\t\"[--%v=provider_name] \"+\n\t\t\t\t\"[--%v=key=value] \"+\n\t\t\t\t\"[--%v=exec_command] \"+\n\t\t\t\t\"[--%v=exec_api_version] \"+\n\t\t\t\t\"[--%v=arg] \"+\n\t\t\t\t\"[--%v=key=value]\",\n\t\t\tclientcmd.FlagCertFile,\n\t\t\tclientcmd.FlagKeyFile,\n\t\t\tclientcmd.FlagBearerToken,\n\t\t\tclientcmd.FlagUsername,\n\t\t\tclientcmd.FlagPassword,\n\t\t\tflagAuthProvider,\n\t\t\tflagAuthProviderArg,\n\t\t\tflagExecCommand,\n\t\t\tflagExecAPIVersion,\n\t\t\tflagExecArg,\n\t\t\tflagExecEnv,\n\t\t),\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Set a user entry in kubeconfig\"),\n\t\tLong: setCredentialsLong,\n\t\tExample: setCredentialsExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\terr := options.complete(cmd)\n\t\t\tif err != nil {\n\t\t\t\tcmd.Help()\n\t\t\t\tcmdutil.CheckErr(err)\n\t\t\t}\n\t\t\tcmdutil.CheckErr(options.run())\n\t\t\tfmt.Fprintf(out, \"User %q set.\\n\", options.name)\n\t\t},\n\t}\n\n\tcmd.Flags().Var(\u0026options.clientCertificate, clientcmd.FlagCertFile, \"Path to \"+clientcmd.FlagCertFile+\" file for the user entry in kubeconfig\")\n\tcmd.MarkFlagFilename(clientcmd.FlagCertFile)\n\tcmd.Flags().Var(\u0026options.clientKey, clientcmd.FlagKeyFile, \"Path to \"+clientcmd.FlagKeyFile+\" file for the user entry in kubeconfig\")\n\tcmd.MarkFlagFilename(clientcmd.FlagKeyFile)\n\tcmd.Flags().Var(\u0026options.token, clientcmd.FlagBearerToken, clientcmd.FlagBearerToken+\" for the user entry in kubeconfig\")\n\tcmd.Flags().Var(\u0026options.username, clientcmd.FlagUsername, clientcmd.FlagUsername+\" for the user entry in kubeconfig\")\n\tcmd.Flags().Var(\u0026options.password, clientcmd.FlagPassword, clientcmd.FlagPassword+\" for the user entry in kubeconfig\")\n\tcmd.Flags().Var(\u0026options.authProvider, flagAuthProvider, \"Auth provider for the user entry in kubeconfig\")\n\tcmd.Flags().StringSlice(flagAuthProviderArg, nil, \"'key=value' arguments for the auth provider\")\n\tcmd.Flags().Var(\u0026options.execCommand, flagExecCommand, \"Command for the exec credential plugin for the user entry in kubeconfig\")\n\tcmd.Flags().Var(\u0026options.execAPIVersion, flagExecAPIVersion, \"API version of the exec credential plugin for the user entry in kubeconfig\")\n\tcmd.Flags().StringSlice(flagExecArg, nil, \"New arguments for the exec credential plugin command for the user entry in kubeconfig\")\n\tcmd.Flags().StringArray(flagExecEnv, nil, \"'key=value' environment values for the exec credential plugin\")\n\tf := cmd.Flags().VarPF(\u0026options.embedCertData, clientcmd.FlagEmbedCerts, \"\", \"Embed client cert/key for the user entry in kubeconfig\")\n\tf.NoOptDefVal = \"true\"\n\n\treturn cmd\n}","line":{"from":130,"to":188}} {"id":100031558,"name":"run","signature":"func (o setCredentialsOptions) run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/set_credentials.go","code":"func (o setCredentialsOptions) run() error {\n\terr := o.validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconfig, err := o.configAccess.GetStartingConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstartingStanza, exists := config.AuthInfos[o.name]\n\tif !exists {\n\t\tstartingStanza = clientcmdapi.NewAuthInfo()\n\t}\n\tauthInfo := o.modifyAuthInfo(*startingStanza)\n\tconfig.AuthInfos[o.name] = \u0026authInfo\n\n\tif err := clientcmd.ModifyConfig(o.configAccess, *config, true); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":190,"to":213}} {"id":100031559,"name":"modifyAuthInfo","signature":"func (o *setCredentialsOptions) modifyAuthInfo(existingAuthInfo clientcmdapi.AuthInfo) clientcmdapi.AuthInfo","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/set_credentials.go","code":"func (o *setCredentialsOptions) modifyAuthInfo(existingAuthInfo clientcmdapi.AuthInfo) clientcmdapi.AuthInfo {\n\tmodifiedAuthInfo := existingAuthInfo\n\n\tvar setToken, setBasic bool\n\n\tif o.clientCertificate.Provided() {\n\t\tcertPath := o.clientCertificate.Value()\n\t\tif o.embedCertData.Value() {\n\t\t\tmodifiedAuthInfo.ClientCertificateData, _ = os.ReadFile(certPath)\n\t\t\tmodifiedAuthInfo.ClientCertificate = \"\"\n\t\t} else {\n\t\t\tcertPath, _ = filepath.Abs(certPath)\n\t\t\tmodifiedAuthInfo.ClientCertificate = certPath\n\t\t\tif len(modifiedAuthInfo.ClientCertificate) \u003e 0 {\n\t\t\t\tmodifiedAuthInfo.ClientCertificateData = nil\n\t\t\t}\n\t\t}\n\t}\n\tif o.clientKey.Provided() {\n\t\tkeyPath := o.clientKey.Value()\n\t\tif o.embedCertData.Value() {\n\t\t\tmodifiedAuthInfo.ClientKeyData, _ = os.ReadFile(keyPath)\n\t\t\tmodifiedAuthInfo.ClientKey = \"\"\n\t\t} else {\n\t\t\tkeyPath, _ = filepath.Abs(keyPath)\n\t\t\tmodifiedAuthInfo.ClientKey = keyPath\n\t\t\tif len(modifiedAuthInfo.ClientKey) \u003e 0 {\n\t\t\t\tmodifiedAuthInfo.ClientKeyData = nil\n\t\t\t}\n\t\t}\n\t}\n\n\tif o.token.Provided() {\n\t\tmodifiedAuthInfo.Token = o.token.Value()\n\t\tsetToken = len(modifiedAuthInfo.Token) \u003e 0\n\t}\n\n\tif o.username.Provided() {\n\t\tmodifiedAuthInfo.Username = o.username.Value()\n\t\tsetBasic = setBasic || len(modifiedAuthInfo.Username) \u003e 0\n\t}\n\tif o.password.Provided() {\n\t\tmodifiedAuthInfo.Password = o.password.Value()\n\t\tsetBasic = setBasic || len(modifiedAuthInfo.Password) \u003e 0\n\t}\n\tif o.authProvider.Provided() {\n\t\tnewName := o.authProvider.Value()\n\n\t\t// Only overwrite if the existing auth-provider is nil, or different than the newly specified one.\n\t\tif modifiedAuthInfo.AuthProvider == nil || modifiedAuthInfo.AuthProvider.Name != newName {\n\t\t\tmodifiedAuthInfo.AuthProvider = \u0026clientcmdapi.AuthProviderConfig{\n\t\t\t\tName: newName,\n\t\t\t}\n\t\t}\n\t}\n\n\tif modifiedAuthInfo.AuthProvider != nil {\n\t\tif modifiedAuthInfo.AuthProvider.Config == nil {\n\t\t\tmodifiedAuthInfo.AuthProvider.Config = make(map[string]string)\n\t\t}\n\t\tfor _, toRemove := range o.authProviderArgsToRemove {\n\t\t\tdelete(modifiedAuthInfo.AuthProvider.Config, toRemove)\n\t\t}\n\t\tfor key, value := range o.authProviderArgs {\n\t\t\tmodifiedAuthInfo.AuthProvider.Config[key] = value\n\t\t}\n\t}\n\n\tif o.execCommand.Provided() {\n\t\tnewExecCommand := o.execCommand.Value()\n\n\t\t// create new Exec if doesn't exist, otherwise just modify the command\n\t\tif modifiedAuthInfo.Exec == nil {\n\t\t\tmodifiedAuthInfo.Exec = \u0026clientcmdapi.ExecConfig{\n\t\t\t\tCommand: newExecCommand,\n\t\t\t}\n\t\t} else {\n\t\t\tmodifiedAuthInfo.Exec.Command = newExecCommand\n\t\t\t// explicitly reset exec arguments\n\t\t\tmodifiedAuthInfo.Exec.Args = nil\n\t\t}\n\t}\n\n\t// modify next values only if Exec exists, ignore these changes otherwise\n\tif modifiedAuthInfo.Exec != nil {\n\t\tif o.execAPIVersion.Provided() {\n\t\t\tmodifiedAuthInfo.Exec.APIVersion = o.execAPIVersion.Value()\n\t\t}\n\n\t\t// rewrite exec arguments list with new values\n\t\tif o.execArgs != nil {\n\t\t\tmodifiedAuthInfo.Exec.Args = o.execArgs\n\t\t}\n\n\t\t// iterate over the existing exec env values and remove the specified\n\t\tif o.execEnvToRemove != nil {\n\t\t\tnewExecEnv := []clientcmdapi.ExecEnvVar{}\n\t\t\tfor _, value := range modifiedAuthInfo.Exec.Env {\n\t\t\t\tneedToRemove := false\n\t\t\t\tfor _, elemToRemove := range o.execEnvToRemove {\n\t\t\t\t\tif value.Name == elemToRemove {\n\t\t\t\t\t\tneedToRemove = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !needToRemove {\n\t\t\t\t\tnewExecEnv = append(newExecEnv, value)\n\t\t\t\t}\n\t\t\t}\n\t\t\tmodifiedAuthInfo.Exec.Env = newExecEnv\n\t\t}\n\n\t\t// update or create specified environment variables for the exec plugin\n\t\tif o.execEnv != nil {\n\t\t\tnewEnv := []clientcmdapi.ExecEnvVar{}\n\t\t\tfor newEnvName, newEnvValue := range o.execEnv {\n\t\t\t\tneedToCreate := true\n\t\t\t\tfor i := 0; i \u003c len(modifiedAuthInfo.Exec.Env); i++ {\n\t\t\t\t\tif modifiedAuthInfo.Exec.Env[i].Name == newEnvName {\n\t\t\t\t\t\t// update the existing value\n\t\t\t\t\t\tneedToCreate = false\n\t\t\t\t\t\tmodifiedAuthInfo.Exec.Env[i].Value = newEnvValue\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif needToCreate {\n\t\t\t\t\t// create a new env value\n\t\t\t\t\tnewEnv = append(newEnv, clientcmdapi.ExecEnvVar{Name: newEnvName, Value: newEnvValue})\n\t\t\t\t}\n\t\t\t}\n\t\t\tmodifiedAuthInfo.Exec.Env = append(modifiedAuthInfo.Exec.Env, newEnv...)\n\t\t}\n\t}\n\n\t// If any auth info was set, make sure any other existing auth types are cleared\n\tif setToken || setBasic {\n\t\tif !setToken {\n\t\t\tmodifiedAuthInfo.Token = \"\"\n\t\t}\n\t\tif !setBasic {\n\t\t\tmodifiedAuthInfo.Username = \"\"\n\t\t\tmodifiedAuthInfo.Password = \"\"\n\t\t}\n\t}\n\n\treturn modifiedAuthInfo\n}","line":{"from":215,"to":361}} {"id":100031560,"name":"complete","signature":"func (o *setCredentialsOptions) complete(cmd *cobra.Command) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/set_credentials.go","code":"func (o *setCredentialsOptions) complete(cmd *cobra.Command) error {\n\targs := cmd.Flags().Args()\n\tif len(args) != 1 {\n\t\treturn fmt.Errorf(\"unexpected args: %v\", args)\n\t}\n\n\tauthProviderArgs, err := cmd.Flags().GetStringSlice(flagAuthProviderArg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(authProviderArgs) \u003e 0 {\n\t\tnewPairs, removePairs, err := cmdutil.ParsePairs(authProviderArgs, flagAuthProviderArg, true)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\to.authProviderArgs = newPairs\n\t\to.authProviderArgsToRemove = removePairs\n\t}\n\n\texecArgs, err := cmd.Flags().GetStringSlice(flagExecArg)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(execArgs) \u003e 0 {\n\t\to.execArgs = execArgs\n\t}\n\n\texecEnv, err := cmd.Flags().GetStringArray(flagExecEnv)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(execEnv) \u003e 0 {\n\t\tnewPairs, removePairs, err := cmdutil.ParsePairs(execEnv, flagExecEnv, true)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\to.execEnv = newPairs\n\t\to.execEnvToRemove = removePairs\n\t}\n\n\to.name = args[0]\n\treturn nil\n}","line":{"from":363,"to":406}} {"id":100031561,"name":"validate","signature":"func (o setCredentialsOptions) validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/set_credentials.go","code":"func (o setCredentialsOptions) validate() error {\n\tif len(o.name) == 0 {\n\t\treturn errors.New(\"you must specify a non-empty user name\")\n\t}\n\tmethods := []string{}\n\tif len(o.token.Value()) \u003e 0 {\n\t\tmethods = append(methods, fmt.Sprintf(\"--%v\", clientcmd.FlagBearerToken))\n\t}\n\tif len(o.username.Value()) \u003e 0 || len(o.password.Value()) \u003e 0 {\n\t\tmethods = append(methods, fmt.Sprintf(\"--%v/--%v\", clientcmd.FlagUsername, clientcmd.FlagPassword))\n\t}\n\tif len(methods) \u003e 1 {\n\t\treturn fmt.Errorf(\"you cannot specify more than one authentication method at the same time: %v\", strings.Join(methods, \", \"))\n\t}\n\tif o.embedCertData.Value() {\n\t\tcertPath := o.clientCertificate.Value()\n\t\tkeyPath := o.clientKey.Value()\n\t\tif certPath == \"\" \u0026\u0026 keyPath == \"\" {\n\t\t\treturn fmt.Errorf(\"you must specify a --%s or --%s to embed\", clientcmd.FlagCertFile, clientcmd.FlagKeyFile)\n\t\t}\n\t\tif certPath != \"\" {\n\t\t\tif _, err := os.Stat(certPath); err != nil {\n\t\t\t\treturn fmt.Errorf(\"could not stat %s file %s: %v\", clientcmd.FlagCertFile, certPath, err)\n\t\t\t}\n\t\t}\n\t\tif keyPath != \"\" {\n\t\t\tif _, err := os.Stat(keyPath); err != nil {\n\t\t\t\treturn fmt.Errorf(\"could not stat %s file %s: %v\", clientcmd.FlagKeyFile, keyPath, err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":408,"to":441}} {"id":100031562,"name":"NewCmdConfigUnset","signature":"func NewCmdConfigUnset(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/unset.go","code":"// NewCmdConfigUnset returns a Command instance for 'config unset' sub command\nfunc NewCmdConfigUnset(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {\n\toptions := \u0026unsetOptions{configAccess: configAccess}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"unset PROPERTY_NAME\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Unset an individual value in a kubeconfig file\"),\n\t\tLong: unsetLong,\n\t\tExample: unsetExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(options.complete(cmd, args))\n\t\t\tcmdutil.CheckErr(options.run(out))\n\n\t\t},\n\t}\n\n\treturn cmd\n}","line":{"from":52,"to":70}} {"id":100031563,"name":"run","signature":"func (o unsetOptions) run(out io.Writer) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/unset.go","code":"func (o unsetOptions) run(out io.Writer) error {\n\terr := o.validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconfig, err := o.configAccess.GetStartingConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsteps, err := newNavigationSteps(o.propertyName)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = modifyConfig(reflect.ValueOf(config), steps, \"\", true, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := clientcmd.ModifyConfig(o.configAccess, *config, false); err != nil {\n\t\treturn err\n\t}\n\tif _, err := fmt.Fprintf(out, \"Property %q unset.\\n\", o.propertyName); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":72,"to":99}} {"id":100031564,"name":"complete","signature":"func (o *unsetOptions) complete(cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/unset.go","code":"func (o *unsetOptions) complete(cmd *cobra.Command, args []string) error {\n\tif len(args) != 1 {\n\t\treturn helpErrorf(cmd, \"Unexpected args: %v\", args)\n\t}\n\n\to.propertyName = args[0]\n\treturn nil\n}","line":{"from":101,"to":108}} {"id":100031565,"name":"validate","signature":"func (o unsetOptions) validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/unset.go","code":"func (o unsetOptions) validate() error {\n\tif len(o.propertyName) == 0 {\n\t\treturn errors.New(\"you must specify a property\")\n\t}\n\n\treturn nil\n}","line":{"from":110,"to":116}} {"id":100031566,"name":"NewCmdConfigUseContext","signature":"func NewCmdConfigUseContext(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/use_context.go","code":"// NewCmdConfigUseContext returns a Command instance for 'config use-context' sub command\nfunc NewCmdConfigUseContext(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {\n\toptions := \u0026useContextOptions{configAccess: configAccess}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"use-context CONTEXT_NAME\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Set the current-context in a kubeconfig file\"),\n\t\tAliases: []string{\"use\"},\n\t\tLong: `Set the current-context in a kubeconfig file.`,\n\t\tExample: useContextExample,\n\t\tValidArgsFunction: completion.ContextCompletionFunc,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(options.complete(cmd))\n\t\t\tcmdutil.CheckErr(options.run())\n\t\t\tfmt.Fprintf(out, \"Switched to context %q.\\n\", options.contextName)\n\t\t},\n\t}\n\n\treturn cmd\n}","line":{"from":45,"to":65}} {"id":100031567,"name":"run","signature":"func (o useContextOptions) run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/use_context.go","code":"func (o useContextOptions) run() error {\n\tconfig, err := o.configAccess.GetStartingConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = o.validate(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconfig.CurrentContext = o.contextName\n\n\treturn clientcmd.ModifyConfig(o.configAccess, *config, true)\n}","line":{"from":67,"to":81}} {"id":100031568,"name":"complete","signature":"func (o *useContextOptions) complete(cmd *cobra.Command) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/use_context.go","code":"func (o *useContextOptions) complete(cmd *cobra.Command) error {\n\tendingArgs := cmd.Flags().Args()\n\tif len(endingArgs) != 1 {\n\t\treturn helpErrorf(cmd, \"Unexpected args: %v\", endingArgs)\n\t}\n\n\to.contextName = endingArgs[0]\n\treturn nil\n}","line":{"from":83,"to":91}} {"id":100031569,"name":"validate","signature":"func (o useContextOptions) validate(config *clientcmdapi.Config) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/use_context.go","code":"func (o useContextOptions) validate(config *clientcmdapi.Config) error {\n\tif len(o.contextName) == 0 {\n\t\treturn errors.New(\"empty context names are not allowed\")\n\t}\n\n\tfor name := range config.Contexts {\n\t\tif name == o.contextName {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"no context exists with the name: %q\", o.contextName)\n}","line":{"from":93,"to":105}} {"id":100031570,"name":"NewCmdConfigView","signature":"func NewCmdConfigView(streams genericclioptions.IOStreams, ConfigAccess clientcmd.ConfigAccess) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/view.go","code":"// NewCmdConfigView returns a Command instance for 'config view' sub command\nfunc NewCmdConfigView(streams genericclioptions.IOStreams, ConfigAccess clientcmd.ConfigAccess) *cobra.Command {\n\to := \u0026ViewOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"\").WithTypeSetter(scheme.Scheme).WithDefaultOutput(\"yaml\"),\n\t\tConfigAccess: ConfigAccess,\n\n\t\tIOStreams: streams,\n\t}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"view\",\n\t\tShort: i18n.T(\"Display merged kubeconfig settings or a specified kubeconfig file\"),\n\t\tLong: viewLong,\n\t\tExample: viewExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\to.Merge.Default(true)\n\tmergeFlag := cmd.Flags().VarPF(\u0026o.Merge, \"merge\", \"\", \"Merge the full hierarchy of kubeconfig files\")\n\tmergeFlag.NoOptDefVal = \"true\"\n\tcmd.Flags().BoolVar(\u0026o.RawByteData, \"raw\", o.RawByteData, \"Display raw byte data and sensitive data\")\n\tcmd.Flags().BoolVar(\u0026o.Flatten, \"flatten\", o.Flatten, \"Flatten the resulting kubeconfig file into self-contained output (useful for creating portable kubeconfig files)\")\n\tcmd.Flags().BoolVar(\u0026o.Minify, \"minify\", o.Minify, \"Remove all information not used by current-context from the output\")\n\treturn cmd\n}","line":{"from":68,"to":98}} {"id":100031571,"name":"Complete","signature":"func (o *ViewOptions) Complete(cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/view.go","code":"// Complete completes the required command-line options\nfunc (o *ViewOptions) Complete(cmd *cobra.Command, args []string) error {\n\tif len(args) != 0 {\n\t\treturn cmdutil.UsageErrorf(cmd, \"unexpected arguments: %v\", args)\n\t}\n\tif o.ConfigAccess.IsExplicitFile() {\n\t\tif !o.Merge.Provided() {\n\t\t\to.Merge.Set(\"false\")\n\t\t}\n\t}\n\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.PrintObject = printer.PrintObj\n\to.Context = cmdutil.GetFlagString(cmd, \"context\")\n\n\treturn nil\n}","line":{"from":100,"to":119}} {"id":100031572,"name":"Validate","signature":"func (o ViewOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/view.go","code":"// Validate makes sure that provided values for command-line options are valid\nfunc (o ViewOptions) Validate() error {\n\tif !o.Merge.Value() \u0026\u0026 !o.ConfigAccess.IsExplicitFile() {\n\t\treturn errors.New(\"if merge==false a precise file must be specified\")\n\t}\n\n\treturn nil\n}","line":{"from":121,"to":128}} {"id":100031573,"name":"Run","signature":"func (o ViewOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/view.go","code":"// Run performs the execution of 'config view' sub command\nfunc (o ViewOptions) Run() error {\n\tconfig, err := o.loadConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif o.Minify {\n\t\tif len(o.Context) \u003e 0 {\n\t\t\tconfig.CurrentContext = o.Context\n\t\t}\n\t\tif err := clientcmdapi.MinifyConfig(config); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif o.Flatten {\n\t\tif err := clientcmdapi.FlattenConfig(config); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else if !o.RawByteData {\n\t\tif err := clientcmdapi.RedactSecrets(config); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tclientcmdapi.ShortenConfig(config)\n\t}\n\n\tconvertedObj, err := latest.Scheme.ConvertToVersion(config, latest.ExternalVersion)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn o.PrintObject(convertedObj, o.Out)\n}","line":{"from":130,"to":163}} {"id":100031574,"name":"loadConfig","signature":"func (o ViewOptions) loadConfig() (*clientcmdapi.Config, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/view.go","code":"func (o ViewOptions) loadConfig() (*clientcmdapi.Config, error) {\n\terr := o.Validate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig, err := o.getStartingConfig()\n\treturn config, err\n}","line":{"from":165,"to":173}} {"id":100031575,"name":"getStartingConfig","signature":"func (o *ViewOptions) getStartingConfig() (*clientcmdapi.Config, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/config/view.go","code":"// getStartingConfig returns the Config object built from the sources specified by the options, the filename read (only if it was a single file), and an error if something goes wrong\nfunc (o *ViewOptions) getStartingConfig() (*clientcmdapi.Config, error) {\n\tswitch {\n\tcase !o.Merge.Value():\n\t\treturn clientcmd.LoadFromFile(o.ConfigAccess.GetExplicitFile())\n\n\tdefault:\n\t\treturn o.ConfigAccess.GetStartingConfig()\n\t}\n}","line":{"from":175,"to":184}} {"id":100031576,"name":"NewCopyOptions","signature":"func NewCopyOptions(ioStreams genericclioptions.IOStreams) *CopyOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/cp.go","code":"// NewCopyOptions creates the options for copy\nfunc NewCopyOptions(ioStreams genericclioptions.IOStreams) *CopyOptions {\n\treturn \u0026CopyOptions{\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":84,"to":89}} {"id":100031577,"name":"NewCmdCp","signature":"func NewCmdCp(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/cp.go","code":"// NewCmdCp creates a new Copy command.\nfunc NewCmdCp(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewCopyOptions(ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"cp \u003cfile-spec-src\u003e \u003cfile-spec-dest\u003e\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Copy files and directories to and from containers\"),\n\t\tLong: i18n.T(\"Copy files and directories to and from containers.\"),\n\t\tExample: cpExample,\n\t\tValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\t\t\tvar comps []string\n\t\t\tif len(args) == 0 {\n\t\t\t\tif strings.IndexAny(toComplete, \"/.~\") == 0 {\n\t\t\t\t\t// Looks like a path, do nothing\n\t\t\t\t} else if strings.Contains(toComplete, \":\") {\n\t\t\t\t\t// TODO: complete remote files in the pod\n\t\t\t\t} else if idx := strings.Index(toComplete, \"/\"); idx \u003e 0 {\n\t\t\t\t\t// complete \u003cnamespace\u003e/\u003cpod\u003e\n\t\t\t\t\tnamespace := toComplete[:idx]\n\t\t\t\t\ttemplate := \"{{ range .items }}{{ .metadata.namespace }}/{{ .metadata.name }}: {{ end }}\"\n\t\t\t\t\tcomps = completion.CompGetFromTemplate(\u0026template, f, namespace, []string{\"pod\"}, toComplete)\n\t\t\t\t} else {\n\t\t\t\t\t// Complete namespaces followed by a /\n\t\t\t\t\tfor _, ns := range completion.CompGetResource(f, \"namespace\", toComplete) {\n\t\t\t\t\t\tcomps = append(comps, fmt.Sprintf(\"%s/\", ns))\n\t\t\t\t\t}\n\t\t\t\t\t// Complete pod names followed by a :\n\t\t\t\t\tfor _, pod := range completion.CompGetResource(f, \"pod\", toComplete) {\n\t\t\t\t\t\tcomps = append(comps, fmt.Sprintf(\"%s:\", pod))\n\t\t\t\t\t}\n\n\t\t\t\t\t// Finally, provide file completion if we need to.\n\t\t\t\t\t// We only do this if:\n\t\t\t\t\t// 1- There are other completions found (if there are no completions,\n\t\t\t\t\t// the shell will do file completion itself)\n\t\t\t\t\t// 2- If there is some input from the user (or else we will end up\n\t\t\t\t\t// listing the entire content of the current directory which could\n\t\t\t\t\t// be too many choices for the user)\n\t\t\t\t\tif len(comps) \u003e 0 \u0026\u0026 len(toComplete) \u003e 0 {\n\t\t\t\t\t\tif files, err := os.ReadDir(\".\"); err == nil {\n\t\t\t\t\t\t\tfor _, file := range files {\n\t\t\t\t\t\t\t\tfilename := file.Name()\n\t\t\t\t\t\t\t\tif strings.HasPrefix(filename, toComplete) {\n\t\t\t\t\t\t\t\t\tif file.IsDir() {\n\t\t\t\t\t\t\t\t\t\tfilename = fmt.Sprintf(\"%s/\", filename)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t// We are completing a file prefix\n\t\t\t\t\t\t\t\t\tcomps = append(comps, filename)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if len(toComplete) == 0 {\n\t\t\t\t\t\t// If the user didn't provide any input to complete,\n\t\t\t\t\t\t// we provide a hint that a path can also be used\n\t\t\t\t\t\tcomps = append(comps, \"./\", \"/\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn comps, cobra.ShellCompDirectiveNoSpace\n\t\t},\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\tcmdutil.AddContainerVarFlags(cmd, \u0026o.Container, o.Container)\n\tcmd.Flags().BoolVarP(\u0026o.NoPreserve, \"no-preserve\", \"\", false, \"The copied file/directory's ownership and permissions will not be preserved in the container\")\n\tcmd.Flags().IntVarP(\u0026o.MaxTries, \"retries\", \"\", 0, \"Set number of retries to complete a copy operation from a container. Specify 0 to disable or any negative value for infinite retrying. The default is 0 (no retry).\")\n\n\treturn cmd\n}","line":{"from":91,"to":163}} {"id":100031578,"name":"extractFileSpec","signature":"func extractFileSpec(arg string) (fileSpec, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/cp.go","code":"func extractFileSpec(arg string) (fileSpec, error) {\n\ti := strings.Index(arg, \":\")\n\n\t// filespec starting with a semicolon is invalid\n\tif i == 0 {\n\t\treturn fileSpec{}, errFileSpecDoesntMatchFormat\n\t}\n\tif i == -1 {\n\t\treturn fileSpec{\n\t\t\tFile: newLocalPath(arg),\n\t\t}, nil\n\t}\n\n\tpod, file := arg[:i], arg[i+1:]\n\tpieces := strings.Split(pod, \"/\")\n\tswitch len(pieces) {\n\tcase 1:\n\t\treturn fileSpec{\n\t\t\tPodName: pieces[0],\n\t\t\tFile: newRemotePath(file),\n\t\t}, nil\n\tcase 2:\n\t\treturn fileSpec{\n\t\t\tPodNamespace: pieces[0],\n\t\t\tPodName: pieces[1],\n\t\t\tFile: newRemotePath(file),\n\t\t}, nil\n\tdefault:\n\t\treturn fileSpec{}, errFileSpecDoesntMatchFormat\n\t}\n}","line":{"from":169,"to":199}} {"id":100031579,"name":"Complete","signature":"func (o *CopyOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/cp.go","code":"// Complete completes all the required options\nfunc (o *CopyOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tif cmd.Parent() != nil {\n\t\to.ExecParentCmdName = cmd.Parent().CommandPath()\n\t}\n\n\tvar err error\n\to.Namespace, _, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Clientset, err = f.KubernetesClientSet()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.ClientConfig, err = f.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.args = args\n\treturn nil\n}","line":{"from":201,"to":225}} {"id":100031580,"name":"Validate","signature":"func (o *CopyOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/cp.go","code":"// Validate makes sure provided values for CopyOptions are valid\nfunc (o *CopyOptions) Validate() error {\n\tif len(o.args) != 2 {\n\t\treturn fmt.Errorf(\"source and destination are required\")\n\t}\n\treturn nil\n}","line":{"from":227,"to":233}} {"id":100031581,"name":"Run","signature":"func (o *CopyOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/cp.go","code":"// Run performs the execution\nfunc (o *CopyOptions) Run() error {\n\tsrcSpec, err := extractFileSpec(o.args[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\tdestSpec, err := extractFileSpec(o.args[1])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(srcSpec.PodName) != 0 \u0026\u0026 len(destSpec.PodName) != 0 {\n\t\treturn fmt.Errorf(\"one of src or dest must be a local file specification\")\n\t}\n\tif len(srcSpec.File.String()) == 0 || len(destSpec.File.String()) == 0 {\n\t\treturn errors.New(\"filepath can not be empty\")\n\t}\n\n\tif len(srcSpec.PodName) != 0 {\n\t\treturn o.copyFromPod(srcSpec, destSpec)\n\t}\n\tif len(destSpec.PodName) != 0 {\n\t\treturn o.copyToPod(srcSpec, destSpec, \u0026exec.ExecOptions{})\n\t}\n\treturn fmt.Errorf(\"one of src or dest must be a remote file specification\")\n}","line":{"from":235,"to":260}} {"id":100031582,"name":"checkDestinationIsDir","signature":"func (o *CopyOptions) checkDestinationIsDir(dest fileSpec) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/cp.go","code":"// checkDestinationIsDir receives a destination fileSpec and\n// determines if the provided destination path exists on the\n// pod. If the destination path does not exist or is _not_ a\n// directory, an error is returned with the exit code received.\nfunc (o *CopyOptions) checkDestinationIsDir(dest fileSpec) error {\n\toptions := \u0026exec.ExecOptions{\n\t\tStreamOptions: exec.StreamOptions{\n\t\t\tIOStreams: genericclioptions.IOStreams{\n\t\t\t\tOut: bytes.NewBuffer([]byte{}),\n\t\t\t\tErrOut: bytes.NewBuffer([]byte{}),\n\t\t\t},\n\n\t\t\tNamespace: dest.PodNamespace,\n\t\t\tPodName: dest.PodName,\n\t\t},\n\n\t\tCommand: []string{\"test\", \"-d\", dest.File.String()},\n\t\tExecutor: \u0026exec.DefaultRemoteExecutor{},\n\t}\n\n\treturn o.execute(options)\n}","line":{"from":262,"to":283}} {"id":100031583,"name":"copyToPod","signature":"func (o *CopyOptions) copyToPod(src, dest fileSpec, options *exec.ExecOptions) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/cp.go","code":"func (o *CopyOptions) copyToPod(src, dest fileSpec, options *exec.ExecOptions) error {\n\tif _, err := os.Stat(src.File.String()); err != nil {\n\t\treturn fmt.Errorf(\"%s doesn't exist in local filesystem\", src.File)\n\t}\n\treader, writer := io.Pipe()\n\n\tsrcFile := src.File.(localPath)\n\tdestFile := dest.File.(remotePath)\n\n\tif err := o.checkDestinationIsDir(dest); err == nil {\n\t\t// If no error, dest.File was found to be a directory.\n\t\t// Copy specified src into it\n\t\tdestFile = destFile.Join(srcFile.Base())\n\t}\n\n\tgo func(src localPath, dest remotePath, writer io.WriteCloser) {\n\t\tdefer writer.Close()\n\t\tcmdutil.CheckErr(makeTar(src, dest, writer))\n\t}(srcFile, destFile, writer)\n\tvar cmdArr []string\n\n\tif o.NoPreserve {\n\t\tcmdArr = []string{\"tar\", \"--no-same-permissions\", \"--no-same-owner\", \"-xmf\", \"-\"}\n\t} else {\n\t\tcmdArr = []string{\"tar\", \"-xmf\", \"-\"}\n\t}\n\tdestFileDir := destFile.Dir().String()\n\tif len(destFileDir) \u003e 0 {\n\t\tcmdArr = append(cmdArr, \"-C\", destFileDir)\n\t}\n\n\toptions.StreamOptions = exec.StreamOptions{\n\t\tIOStreams: genericclioptions.IOStreams{\n\t\t\tIn: reader,\n\t\t\tOut: o.Out,\n\t\t\tErrOut: o.ErrOut,\n\t\t},\n\t\tStdin: true,\n\n\t\tNamespace: dest.PodNamespace,\n\t\tPodName: dest.PodName,\n\t}\n\n\toptions.Command = cmdArr\n\toptions.Executor = \u0026exec.DefaultRemoteExecutor{}\n\treturn o.execute(options)\n}","line":{"from":285,"to":331}} {"id":100031584,"name":"copyFromPod","signature":"func (o *CopyOptions) copyFromPod(src, dest fileSpec) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/cp.go","code":"func (o *CopyOptions) copyFromPod(src, dest fileSpec) error {\n\treader := newTarPipe(src, o)\n\tsrcFile := src.File.(remotePath)\n\tdestFile := dest.File.(localPath)\n\t// remove extraneous path shortcuts - these could occur if a path contained extra \"../\"\n\t// and attempted to navigate beyond \"/\" in a remote filesystem\n\tprefix := stripPathShortcuts(srcFile.StripSlashes().Clean().String())\n\treturn o.untarAll(src.PodNamespace, src.PodName, prefix, srcFile, destFile, reader)\n}","line":{"from":333,"to":341}} {"id":100031585,"name":"newTarPipe","signature":"func newTarPipe(src fileSpec, o *CopyOptions) *TarPipe","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/cp.go","code":"func newTarPipe(src fileSpec, o *CopyOptions) *TarPipe {\n\tt := new(TarPipe)\n\tt.src = src\n\tt.o = o\n\tt.initReadFrom(0)\n\treturn t\n}","line":{"from":352,"to":358}} {"id":100031586,"name":"initReadFrom","signature":"func (t *TarPipe) initReadFrom(n uint64)","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/cp.go","code":"func (t *TarPipe) initReadFrom(n uint64) {\n\tt.reader, t.outStream = io.Pipe()\n\toptions := \u0026exec.ExecOptions{\n\t\tStreamOptions: exec.StreamOptions{\n\t\t\tIOStreams: genericclioptions.IOStreams{\n\t\t\t\tIn: nil,\n\t\t\t\tOut: t.outStream,\n\t\t\t\tErrOut: t.o.Out,\n\t\t\t},\n\n\t\t\tNamespace: t.src.PodNamespace,\n\t\t\tPodName: t.src.PodName,\n\t\t},\n\n\t\tCommand: []string{\"tar\", \"cf\", \"-\", t.src.File.String()},\n\t\tExecutor: \u0026exec.DefaultRemoteExecutor{},\n\t}\n\tif t.o.MaxTries != 0 {\n\t\toptions.Command = []string{\"sh\", \"-c\", fmt.Sprintf(\"tar cf - %s | tail -c+%d\", t.src.File, n)}\n\t}\n\n\tgo func() {\n\t\tdefer t.outStream.Close()\n\t\tcmdutil.CheckErr(t.o.execute(options))\n\t}()\n}","line":{"from":360,"to":385}} {"id":100031587,"name":"Read","signature":"func (t *TarPipe) Read(p []byte) (n int, err error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/cp.go","code":"func (t *TarPipe) Read(p []byte) (n int, err error) {\n\tn, err = t.reader.Read(p)\n\tif err != nil {\n\t\tif t.o.MaxTries \u003c 0 || t.retries \u003c t.o.MaxTries {\n\t\t\tt.retries++\n\t\t\tfmt.Printf(\"Resuming copy at %d bytes, retry %d/%d\\n\", t.bytesRead, t.retries, t.o.MaxTries)\n\t\t\tt.initReadFrom(t.bytesRead + 1)\n\t\t\terr = nil\n\t\t} else {\n\t\t\tfmt.Printf(\"Dropping out copy after %d retries\\n\", t.retries)\n\t\t}\n\t} else {\n\t\tt.bytesRead += uint64(n)\n\t}\n\treturn\n}","line":{"from":387,"to":402}} {"id":100031588,"name":"makeTar","signature":"func makeTar(src localPath, dest remotePath, writer io.Writer) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/cp.go","code":"func makeTar(src localPath, dest remotePath, writer io.Writer) error {\n\t// TODO: use compression here?\n\ttarWriter := tar.NewWriter(writer)\n\tdefer tarWriter.Close()\n\n\tsrcPath := src.Clean()\n\tdestPath := dest.Clean()\n\treturn recursiveTar(srcPath.Dir(), srcPath.Base(), destPath.Dir(), destPath.Base(), tarWriter)\n}","line":{"from":404,"to":412}} {"id":100031589,"name":"recursiveTar","signature":"func recursiveTar(srcDir, srcFile localPath, destDir, destFile remotePath, tw *tar.Writer) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/cp.go","code":"func recursiveTar(srcDir, srcFile localPath, destDir, destFile remotePath, tw *tar.Writer) error {\n\tmatchedPaths, err := srcDir.Join(srcFile).Glob()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, fpath := range matchedPaths {\n\t\tstat, err := os.Lstat(fpath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif stat.IsDir() {\n\t\t\tfiles, err := os.ReadDir(fpath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif len(files) == 0 {\n\t\t\t\t//case empty directory\n\t\t\t\thdr, _ := tar.FileInfoHeader(stat, fpath)\n\t\t\t\thdr.Name = destFile.String()\n\t\t\t\tif err := tw.WriteHeader(hdr); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, f := range files {\n\t\t\t\tif err := recursiveTar(srcDir, srcFile.Join(newLocalPath(f.Name())),\n\t\t\t\t\tdestDir, destFile.Join(newRemotePath(f.Name())), tw); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t} else if stat.Mode()\u0026os.ModeSymlink != 0 {\n\t\t\t//case soft link\n\t\t\thdr, _ := tar.FileInfoHeader(stat, fpath)\n\t\t\ttarget, err := os.Readlink(fpath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\thdr.Linkname = target\n\t\t\thdr.Name = destFile.String()\n\t\t\tif err := tw.WriteHeader(hdr); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\t//case regular file or other file type like pipe\n\t\t\thdr, err := tar.FileInfoHeader(stat, fpath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thdr.Name = destFile.String()\n\n\t\t\tif err := tw.WriteHeader(hdr); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tf, err := os.Open(fpath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer f.Close()\n\n\t\t\tif _, err := io.Copy(tw, f); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn f.Close()\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":414,"to":482}} {"id":100031590,"name":"untarAll","signature":"func (o *CopyOptions) untarAll(ns, pod string, prefix string, src remotePath, dest localPath, reader io.Reader) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/cp.go","code":"func (o *CopyOptions) untarAll(ns, pod string, prefix string, src remotePath, dest localPath, reader io.Reader) error {\n\tsymlinkWarningPrinted := false\n\t// TODO: use compression here?\n\ttarReader := tar.NewReader(reader)\n\tfor {\n\t\theader, err := tarReader.Next()\n\t\tif err != nil {\n\t\t\tif err != io.EOF {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\t// All the files will start with the prefix, which is the directory where\n\t\t// they were located on the pod, we need to strip down that prefix, but\n\t\t// if the prefix is missing it means the tar was tempered with.\n\t\t// For the case where prefix is empty we need to ensure that the path\n\t\t// is not absolute, which also indicates the tar file was tempered with.\n\t\tif !strings.HasPrefix(header.Name, prefix) {\n\t\t\treturn fmt.Errorf(\"tar contents corrupted\")\n\t\t}\n\n\t\t// basic file information\n\t\tmode := header.FileInfo().Mode()\n\t\t// header.Name is a name of the REMOTE file, so we need to create\n\t\t// a remotePath so that it goes through appropriate processing related\n\t\t// with cleaning remote paths\n\t\tdestFileName := dest.Join(newRemotePath(header.Name[len(prefix):]))\n\n\t\tif !isRelative(dest, destFileName) {\n\t\t\tfmt.Fprintf(o.IOStreams.ErrOut, \"warning: file %q is outside target destination, skipping\\n\", destFileName)\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := os.MkdirAll(destFileName.Dir().String(), 0755); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif header.FileInfo().IsDir() {\n\t\t\tif err := os.MkdirAll(destFileName.String(), 0755); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif mode\u0026os.ModeSymlink != 0 {\n\t\t\tif !symlinkWarningPrinted \u0026\u0026 len(o.ExecParentCmdName) \u003e 0 {\n\t\t\t\tfmt.Fprintf(o.IOStreams.ErrOut,\n\t\t\t\t\t\"warning: skipping symlink: %q -\u003e %q (consider using \\\"%s exec -n %q %q -- tar cf - %q | tar xf -\\\")\\n\",\n\t\t\t\t\tdestFileName, header.Linkname, o.ExecParentCmdName, ns, pod, src)\n\t\t\t\tsymlinkWarningPrinted = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfmt.Fprintf(o.IOStreams.ErrOut, \"warning: skipping symlink: %q -\u003e %q\\n\", destFileName, header.Linkname)\n\t\t\tcontinue\n\t\t}\n\t\toutFile, err := os.Create(destFileName.String())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer outFile.Close()\n\t\tif _, err := io.Copy(outFile, tarReader); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := outFile.Close(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":484,"to":553}} {"id":100031591,"name":"execute","signature":"func (o *CopyOptions) execute(options *exec.ExecOptions) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/cp.go","code":"func (o *CopyOptions) execute(options *exec.ExecOptions) error {\n\tif len(options.Namespace) == 0 {\n\t\toptions.Namespace = o.Namespace\n\t}\n\n\tif len(o.Container) \u003e 0 {\n\t\toptions.ContainerName = o.Container\n\t}\n\n\toptions.Config = o.ClientConfig\n\toptions.PodClient = o.Clientset.CoreV1()\n\n\tif err := options.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := options.Run(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":555,"to":575}} {"id":100031592,"name":"newLocalPath","signature":"func newLocalPath(fileName string) localPath","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/filespec.go","code":"func newLocalPath(fileName string) localPath {\n\tfile := stripTrailingSlash(fileName)\n\treturn localPath{file: file}\n}","line":{"from":42,"to":45}} {"id":100031593,"name":"String","signature":"func (p localPath) String() string","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/filespec.go","code":"func (p localPath) String() string {\n\treturn p.file\n}","line":{"from":47,"to":49}} {"id":100031594,"name":"Dir","signature":"func (p localPath) Dir() localPath","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/filespec.go","code":"func (p localPath) Dir() localPath {\n\treturn newLocalPath(filepath.Dir(p.file))\n}","line":{"from":51,"to":53}} {"id":100031595,"name":"Base","signature":"func (p localPath) Base() localPath","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/filespec.go","code":"func (p localPath) Base() localPath {\n\treturn newLocalPath(filepath.Base(p.file))\n}","line":{"from":55,"to":57}} {"id":100031596,"name":"Clean","signature":"func (p localPath) Clean() localPath","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/filespec.go","code":"func (p localPath) Clean() localPath {\n\treturn newLocalPath(filepath.Clean(p.file))\n}","line":{"from":59,"to":61}} {"id":100031597,"name":"Join","signature":"func (p localPath) Join(elem pathSpec) localPath","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/filespec.go","code":"func (p localPath) Join(elem pathSpec) localPath {\n\treturn newLocalPath(filepath.Join(p.file, elem.String()))\n}","line":{"from":63,"to":65}} {"id":100031598,"name":"Glob","signature":"func (p localPath) Glob() (matches []string, err error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/filespec.go","code":"func (p localPath) Glob() (matches []string, err error) {\n\treturn filepath.Glob(p.file)\n}","line":{"from":67,"to":69}} {"id":100031599,"name":"StripSlashes","signature":"func (p localPath) StripSlashes() localPath","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/filespec.go","code":"func (p localPath) StripSlashes() localPath {\n\treturn newLocalPath(stripLeadingSlash(p.file))\n}","line":{"from":71,"to":73}} {"id":100031600,"name":"isRelative","signature":"func isRelative(base, target localPath) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/filespec.go","code":"func isRelative(base, target localPath) bool {\n\trelative, err := filepath.Rel(base.String(), target.String())\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn relative == \".\" || relative == stripPathShortcuts(relative)\n}","line":{"from":75,"to":81}} {"id":100031601,"name":"newRemotePath","signature":"func newRemotePath(fileName string) remotePath","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/filespec.go","code":"func newRemotePath(fileName string) remotePath {\n\t// we assume remote file is a linux container but we need to convert\n\t// windows path separators to unix style for consistent processing\n\tfile := strings.ReplaceAll(stripTrailingSlash(fileName), `\\`, \"/\")\n\treturn remotePath{file: file}\n}","line":{"from":89,"to":94}} {"id":100031602,"name":"String","signature":"func (p remotePath) String() string","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/filespec.go","code":"func (p remotePath) String() string {\n\treturn p.file\n}","line":{"from":96,"to":98}} {"id":100031603,"name":"Dir","signature":"func (p remotePath) Dir() remotePath","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/filespec.go","code":"func (p remotePath) Dir() remotePath {\n\treturn newRemotePath(path.Dir(p.file))\n}","line":{"from":100,"to":102}} {"id":100031604,"name":"Base","signature":"func (p remotePath) Base() remotePath","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/filespec.go","code":"func (p remotePath) Base() remotePath {\n\treturn newRemotePath(path.Base(p.file))\n}","line":{"from":104,"to":106}} {"id":100031605,"name":"Clean","signature":"func (p remotePath) Clean() remotePath","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/filespec.go","code":"func (p remotePath) Clean() remotePath {\n\treturn newRemotePath(path.Clean(p.file))\n}","line":{"from":108,"to":110}} {"id":100031606,"name":"Join","signature":"func (p remotePath) Join(elem pathSpec) remotePath","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/filespec.go","code":"func (p remotePath) Join(elem pathSpec) remotePath {\n\treturn newRemotePath(path.Join(p.file, elem.String()))\n}","line":{"from":112,"to":114}} {"id":100031607,"name":"StripShortcuts","signature":"func (p remotePath) StripShortcuts() remotePath","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/filespec.go","code":"func (p remotePath) StripShortcuts() remotePath {\n\tp = p.Clean()\n\treturn newRemotePath(stripPathShortcuts(p.file))\n}","line":{"from":116,"to":119}} {"id":100031608,"name":"StripSlashes","signature":"func (p remotePath) StripSlashes() remotePath","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/filespec.go","code":"func (p remotePath) StripSlashes() remotePath {\n\treturn newRemotePath(stripLeadingSlash(p.file))\n}","line":{"from":121,"to":123}} {"id":100031609,"name":"stripTrailingSlash","signature":"func stripTrailingSlash(file string) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/filespec.go","code":"// strips trailing slash (if any) both unix and windows style\nfunc stripTrailingSlash(file string) string {\n\tif len(file) == 0 {\n\t\treturn file\n\t}\n\tif file != \"/\" \u0026\u0026 strings.HasSuffix(string(file[len(file)-1]), \"/\") {\n\t\treturn file[:len(file)-1]\n\t}\n\treturn file\n}","line":{"from":125,"to":134}} {"id":100031610,"name":"stripLeadingSlash","signature":"func stripLeadingSlash(file string) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/filespec.go","code":"func stripLeadingSlash(file string) string {\n\t// tar strips the leading '/' and '\\' if it's there, so we will too\n\treturn strings.TrimLeft(file, `/\\`)\n}","line":{"from":136,"to":139}} {"id":100031611,"name":"stripPathShortcuts","signature":"func stripPathShortcuts(p string) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/cp/filespec.go","code":"// stripPathShortcuts removes any leading or trailing \"../\" from a given path\nfunc stripPathShortcuts(p string) string {\n\tnewPath := p\n\ttrimmed := strings.TrimPrefix(newPath, \"../\")\n\n\tfor trimmed != newPath {\n\t\tnewPath = trimmed\n\t\ttrimmed = strings.TrimPrefix(newPath, \"../\")\n\t}\n\n\t// trim leftover {\".\", \"..\"}\n\tif newPath == \".\" || newPath == \"..\" {\n\t\tnewPath = \"\"\n\t}\n\n\tif len(newPath) \u003e 0 \u0026\u0026 string(newPath[0]) == \"/\" {\n\t\treturn newPath[1:]\n\t}\n\n\treturn newPath\n}","line":{"from":141,"to":161}} {"id":100031612,"name":"NewCreateOptions","signature":"func NewCreateOptions(ioStreams genericclioptions.IOStreams) *CreateOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create.go","code":"// NewCreateOptions returns an initialized CreateOptions instance\nfunc NewCreateOptions(ioStreams genericclioptions.IOStreams) *CreateOptions {\n\treturn \u0026CreateOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"created\").WithTypeSetter(scheme.Scheme),\n\t\tRecordFlags: genericclioptions.NewRecordFlags(),\n\n\t\tRecorder: genericclioptions.NoopRecorder{},\n\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":88,"to":98}} {"id":100031613,"name":"NewCmdCreate","signature":"func NewCmdCreate(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create.go","code":"// NewCmdCreate returns new initialized instance of create sub command\nfunc NewCmdCreate(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewCreateOptions(ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"create -f FILENAME\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Create a resource from a file or from stdin\"),\n\t\tLong: createLong,\n\t\tExample: createExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tif cmdutil.IsFilenameSliceEmpty(o.FilenameOptions.Filenames, o.FilenameOptions.Kustomize) {\n\t\t\t\tioStreams.ErrOut.Write([]byte(\"Error: must specify one of -f and -k\\n\\n\"))\n\t\t\t\tdefaultRunFunc := cmdutil.DefaultSubCommandRun(ioStreams.ErrOut)\n\t\t\t\tdefaultRunFunc(cmd, args)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.RunCreate(f, cmd))\n\t\t},\n\t}\n\n\t// bind flag structs\n\to.RecordFlags.AddFlags(cmd)\n\n\tusage := \"to use to create the resource\"\n\tcmdutil.AddFilenameOptionFlags(cmd, \u0026o.FilenameOptions, usage)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmd.Flags().BoolVar(\u0026o.EditBeforeCreate, \"edit\", o.EditBeforeCreate, \"Edit the API resource before creating\")\n\tcmd.Flags().Bool(\"windows-line-endings\", runtime.GOOS == \"windows\",\n\t\t\"Only relevant if --edit=true. Defaults to the line ending native to your platform.\")\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmdutil.AddLabelSelectorFlagVar(cmd, \u0026o.Selector)\n\tcmd.Flags().StringVar(\u0026o.Raw, \"raw\", o.Raw, \"Raw URI to POST to the server. Uses the transport specified by the kubeconfig file.\")\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.fieldManager, \"kubectl-create\")\n\n\to.PrintFlags.AddFlags(cmd)\n\n\t// create subcommands\n\tcmd.AddCommand(NewCmdCreateNamespace(f, ioStreams))\n\tcmd.AddCommand(NewCmdCreateQuota(f, ioStreams))\n\tcmd.AddCommand(NewCmdCreateSecret(f, ioStreams))\n\tcmd.AddCommand(NewCmdCreateConfigMap(f, ioStreams))\n\tcmd.AddCommand(NewCmdCreateServiceAccount(f, ioStreams))\n\tcmd.AddCommand(NewCmdCreateService(f, ioStreams))\n\tcmd.AddCommand(NewCmdCreateDeployment(f, ioStreams))\n\tcmd.AddCommand(NewCmdCreateClusterRole(f, ioStreams))\n\tcmd.AddCommand(NewCmdCreateClusterRoleBinding(f, ioStreams))\n\tcmd.AddCommand(NewCmdCreateRole(f, ioStreams))\n\tcmd.AddCommand(NewCmdCreateRoleBinding(f, ioStreams))\n\tcmd.AddCommand(NewCmdCreatePodDisruptionBudget(f, ioStreams))\n\tcmd.AddCommand(NewCmdCreatePriorityClass(f, ioStreams))\n\tcmd.AddCommand(NewCmdCreateJob(f, ioStreams))\n\tcmd.AddCommand(NewCmdCreateCronJob(f, ioStreams))\n\tcmd.AddCommand(NewCmdCreateIngress(f, ioStreams))\n\tcmd.AddCommand(NewCmdCreateToken(f, ioStreams))\n\treturn cmd\n}","line":{"from":100,"to":159}} {"id":100031614,"name":"Validate","signature":"func (o *CreateOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create.go","code":"// Validate makes sure there is no discrepency in command options\nfunc (o *CreateOptions) Validate() error {\n\tif len(o.Raw) \u003e 0 {\n\t\tif o.EditBeforeCreate {\n\t\t\treturn fmt.Errorf(\"--raw and --edit are mutually exclusive\")\n\t\t}\n\t\tif len(o.FilenameOptions.Filenames) != 1 {\n\t\t\treturn fmt.Errorf(\"--raw can only use a single local file or stdin\")\n\t\t}\n\t\tif strings.Index(o.FilenameOptions.Filenames[0], \"http://\") == 0 || strings.Index(o.FilenameOptions.Filenames[0], \"https://\") == 0 {\n\t\t\treturn fmt.Errorf(\"--raw cannot read from a url\")\n\t\t}\n\t\tif o.FilenameOptions.Recursive {\n\t\t\treturn fmt.Errorf(\"--raw and --recursive are mutually exclusive\")\n\t\t}\n\t\tif len(o.Selector) \u003e 0 {\n\t\t\treturn fmt.Errorf(\"--raw and --selector (-l) are mutually exclusive\")\n\t\t}\n\t\tif o.PrintFlags.OutputFormat != nil \u0026\u0026 len(*o.PrintFlags.OutputFormat) \u003e 0 {\n\t\t\treturn fmt.Errorf(\"--raw and --output are mutually exclusive\")\n\t\t}\n\t\tif _, err := url.ParseRequestURI(o.Raw); err != nil {\n\t\t\treturn fmt.Errorf(\"--raw must be a valid URL path: %v\", err)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":161,"to":188}} {"id":100031615,"name":"Complete","signature":"func (o *CreateOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create.go","code":"// Complete completes all the required options\nfunc (o *CreateOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tif len(args) != 0 {\n\t\treturn cmdutil.UsageErrorf(cmd, \"Unexpected args: %v\", args)\n\t}\n\tvar err error\n\to.RecordFlags.Complete(cmd)\n\to.Recorder, err = o.RecordFlags.ToRecorder()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\n\to.ValidationDirective, err = cmdutil.GetValidationDirective(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.PrintObj = func(obj kruntime.Object) error {\n\t\treturn printer.PrintObj(obj, o.Out)\n\t}\n\n\treturn nil\n}","line":{"from":190,"to":223}} {"id":100031616,"name":"RunCreate","signature":"func (o *CreateOptions) RunCreate(f cmdutil.Factory, cmd *cobra.Command) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create.go","code":"// RunCreate performs the creation\nfunc (o *CreateOptions) RunCreate(f cmdutil.Factory, cmd *cobra.Command) error {\n\t// raw only makes sense for a single file resource multiple objects aren't likely to do what you want.\n\t// the validator enforces this, so\n\tif len(o.Raw) \u003e 0 {\n\t\trestClient, err := f.RESTClient()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn rawhttp.RawPost(restClient, o.IOStreams, o.Raw, o.FilenameOptions.Filenames[0])\n\t}\n\n\tif o.EditBeforeCreate {\n\t\treturn RunEditOnCreate(f, o.PrintFlags, o.RecordFlags, o.IOStreams, cmd, \u0026o.FilenameOptions, o.fieldManager)\n\t}\n\n\tschema, err := f.Validator(o.ValidationDirective)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmdNamespace, enforceNamespace, err := f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr := f.NewBuilder().\n\t\tUnstructured().\n\t\tSchema(schema).\n\t\tContinueOnError().\n\t\tNamespaceParam(cmdNamespace).DefaultNamespace().\n\t\tFilenameParam(enforceNamespace, \u0026o.FilenameOptions).\n\t\tLabelSelectorParam(o.Selector).\n\t\tFlatten().\n\t\tDo()\n\terr = r.Err()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcount := 0\n\terr = r.Visit(func(info *resource.Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := util.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), info.Object, scheme.DefaultJSONEncoder()); err != nil {\n\t\t\treturn cmdutil.AddSourceToErr(\"creating\", info.Source, err)\n\t\t}\n\n\t\tif err := o.Recorder.Record(info.Object); err != nil {\n\t\t\tklog.V(4).Infof(\"error recording current command: %v\", err)\n\t\t}\n\n\t\tif o.DryRunStrategy != cmdutil.DryRunClient {\n\t\t\tobj, err := resource.\n\t\t\t\tNewHelper(info.Client, info.Mapping).\n\t\t\t\tDryRun(o.DryRunStrategy == cmdutil.DryRunServer).\n\t\t\t\tWithFieldManager(o.fieldManager).\n\t\t\t\tWithFieldValidation(o.ValidationDirective).\n\t\t\t\tCreate(info.Namespace, true, info.Object)\n\t\t\tif err != nil {\n\t\t\t\treturn cmdutil.AddSourceToErr(\"creating\", info.Source, err)\n\t\t\t}\n\t\t\tinfo.Refresh(obj, true)\n\t\t}\n\n\t\tcount++\n\n\t\treturn o.PrintObj(info.Object)\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tif count == 0 {\n\t\treturn fmt.Errorf(\"no objects passed to create\")\n\t}\n\treturn nil\n}","line":{"from":225,"to":302}} {"id":100031617,"name":"RunEditOnCreate","signature":"func RunEditOnCreate(f cmdutil.Factory, printFlags *genericclioptions.PrintFlags, recordFlags *genericclioptions.RecordFlags, ioStreams genericclioptions.IOStreams, cmd *cobra.Command, options *resource.FilenameOptions, fieldManager string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create.go","code":"// RunEditOnCreate performs edit on creation\nfunc RunEditOnCreate(f cmdutil.Factory, printFlags *genericclioptions.PrintFlags, recordFlags *genericclioptions.RecordFlags, ioStreams genericclioptions.IOStreams, cmd *cobra.Command, options *resource.FilenameOptions, fieldManager string) error {\n\teditOptions := editor.NewEditOptions(editor.EditBeforeCreateMode, ioStreams)\n\teditOptions.FilenameOptions = *options\n\tvalidationDirective, err := cmdutil.GetValidationDirective(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\teditOptions.ValidateOptions = cmdutil.ValidateOptions{\n\t\tValidationDirective: string(validationDirective),\n\t}\n\teditOptions.PrintFlags = printFlags\n\teditOptions.ApplyAnnotation = cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag)\n\teditOptions.RecordFlags = recordFlags\n\teditOptions.FieldManager = \"kubectl-create\"\n\n\terr = editOptions.Complete(f, []string{}, cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn editOptions.Run()\n}","line":{"from":304,"to":325}} {"id":100031618,"name":"NameFromCommandArgs","signature":"func NameFromCommandArgs(cmd *cobra.Command, args []string) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create.go","code":"// NameFromCommandArgs is a utility function for commands that assume the first argument is a resource name\nfunc NameFromCommandArgs(cmd *cobra.Command, args []string) (string, error) {\n\targsLen := cmd.ArgsLenAtDash()\n\t// ArgsLenAtDash returns -1 when -- was not specified\n\tif argsLen == -1 {\n\t\targsLen = len(args)\n\t}\n\tif argsLen != 1 {\n\t\treturn \"\", cmdutil.UsageErrorf(cmd, \"exactly one NAME is required, got %d\", argsLen)\n\t}\n\treturn args[0], nil\n}","line":{"from":327,"to":338}} {"id":100031619,"name":"NewCreateSubcommandOptions","signature":"func NewCreateSubcommandOptions(ioStreams genericclioptions.IOStreams) *CreateSubcommandOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create.go","code":"// NewCreateSubcommandOptions returns initialized CreateSubcommandOptions\nfunc NewCreateSubcommandOptions(ioStreams genericclioptions.IOStreams) *CreateSubcommandOptions {\n\treturn \u0026CreateSubcommandOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"created\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":364,"to":370}} {"id":100031620,"name":"Complete","signature":"func (o *CreateSubcommandOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string, generator generate.StructuredGenerator) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create.go","code":"// Complete completes all the required options\nfunc (o *CreateSubcommandOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string, generator generate.StructuredGenerator) error {\n\tname, err := NameFromCommandArgs(cmd, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Name = name\n\to.StructuredGenerator = generator\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\to.CreateAnnotation = cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag)\n\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.ValidationDirective, err = cmdutil.GetValidationDirective(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.PrintObj = func(obj kruntime.Object, out io.Writer) error {\n\t\treturn printer.PrintObj(obj, out)\n\t}\n\n\to.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.DynamicClient, err = f.DynamicClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Mapper, err = f.ToRESTMapper()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":372,"to":418}} {"id":100031621,"name":"Run","signature":"func (o *CreateSubcommandOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create.go","code":"// Run executes a create subcommand using the specified options\nfunc (o *CreateSubcommandOptions) Run() error {\n\tobj, err := o.StructuredGenerator.StructuredGenerate()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := util.CreateOrUpdateAnnotation(o.CreateAnnotation, obj, scheme.DefaultJSONEncoder()); err != nil {\n\t\treturn err\n\t}\n\tif o.DryRunStrategy != cmdutil.DryRunClient {\n\t\t// create subcommands have compiled knowledge of things they create, so type them directly\n\t\tgvks, _, err := scheme.Scheme.ObjectKinds(obj)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgvk := gvks[0]\n\t\tmapping, err := o.Mapper.RESTMapping(schema.GroupKind{Group: gvk.Group, Kind: gvk.Kind}, gvk.Version)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tasUnstructured := \u0026unstructured.Unstructured{}\n\t\tif err := scheme.Scheme.Convert(obj, asUnstructured, nil); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif mapping.Scope.Name() == meta.RESTScopeNameRoot {\n\t\t\to.Namespace = \"\"\n\t\t}\n\t\tcreateOptions := metav1.CreateOptions{}\n\t\tif o.FieldManager != \"\" {\n\t\t\tcreateOptions.FieldManager = o.FieldManager\n\t\t}\n\t\tcreateOptions.FieldValidation = o.ValidationDirective\n\n\t\tif o.DryRunStrategy == cmdutil.DryRunServer {\n\t\t\tcreateOptions.DryRun = []string{metav1.DryRunAll}\n\t\t}\n\t\tactualObject, err := o.DynamicClient.Resource(mapping.Resource).Namespace(o.Namespace).Create(context.TODO(), asUnstructured, createOptions)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// ensure we pass a versioned object to the printer\n\t\tobj = actualObject\n\t} else {\n\t\tif meta, err := meta.Accessor(obj); err == nil \u0026\u0026 o.EnforceNamespace {\n\t\t\tmeta.SetNamespace(o.Namespace)\n\t\t}\n\t}\n\n\treturn o.PrintObj(obj, o.Out)\n}","line":{"from":420,"to":471}} {"id":100031622,"name":"NewCmdCreateClusterRole","signature":"func NewCmdCreateClusterRole(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_clusterrole.go","code":"// NewCmdCreateClusterRole initializes and returns new ClusterRoles command\nfunc NewCmdCreateClusterRole(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\tc := \u0026CreateClusterRoleOptions{\n\t\tCreateRoleOptions: NewCreateRoleOptions(ioStreams),\n\t\tAggregationRule: map[string]string{},\n\t}\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"clusterrole NAME --verb=verb --resource=resource.group [--resource-name=resourcename] [--dry-run=server|client|none]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Create a cluster role\"),\n\t\tLong: clusterRoleLong,\n\t\tExample: clusterRoleExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(c.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(c.Validate())\n\t\t\tcmdutil.CheckErr(c.RunCreateRole())\n\t\t},\n\t}\n\n\tc.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmd.Flags().StringSliceVar(\u0026c.Verbs, \"verb\", c.Verbs, \"Verb that applies to the resources contained in the rule\")\n\tcmd.Flags().StringSliceVar(\u0026c.NonResourceURLs, \"non-resource-url\", c.NonResourceURLs, \"A partial url that user should have access to.\")\n\tcmd.Flags().StringSlice(\"resource\", []string{}, \"Resource that the rule applies to\")\n\tcmd.Flags().StringArrayVar(\u0026c.ResourceNames, \"resource-name\", c.ResourceNames, \"Resource in the white list that the rule applies to, repeat this flag for multiple items\")\n\tcmd.Flags().Var(cliflag.NewMapStringString(\u0026c.AggregationRule), \"aggregation-rule\", \"An aggregation label selector for combining ClusterRoles.\")\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026c.FieldManager, \"kubectl-create\")\n\n\treturn cmd\n}","line":{"from":72,"to":104}} {"id":100031623,"name":"Complete","signature":"func (c *CreateClusterRoleOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_clusterrole.go","code":"// Complete completes all the required options\nfunc (c *CreateClusterRoleOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\t// Remove duplicate nonResourceURLs\n\tnonResourceURLs := []string{}\n\tfor _, n := range c.NonResourceURLs {\n\t\tif !arrayContains(nonResourceURLs, n) {\n\t\t\tnonResourceURLs = append(nonResourceURLs, n)\n\t\t}\n\t}\n\tc.NonResourceURLs = nonResourceURLs\n\n\treturn c.CreateRoleOptions.Complete(f, cmd, args)\n}","line":{"from":106,"to":118}} {"id":100031624,"name":"Validate","signature":"func (c *CreateClusterRoleOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_clusterrole.go","code":"// Validate makes sure there is no discrepency in CreateClusterRoleOptions\nfunc (c *CreateClusterRoleOptions) Validate() error {\n\tif c.Name == \"\" {\n\t\treturn fmt.Errorf(\"name must be specified\")\n\t}\n\n\tif len(c.AggregationRule) \u003e 0 {\n\t\tif len(c.NonResourceURLs) \u003e 0 || len(c.Verbs) \u003e 0 || len(c.Resources) \u003e 0 || len(c.ResourceNames) \u003e 0 {\n\t\t\treturn fmt.Errorf(\"aggregation rule must be specified without nonResourceURLs, verbs, resources or resourceNames\")\n\t\t}\n\t\treturn nil\n\t}\n\n\t// validate verbs.\n\tif len(c.Verbs) == 0 {\n\t\treturn fmt.Errorf(\"at least one verb must be specified\")\n\t}\n\n\tif len(c.Resources) == 0 \u0026\u0026 len(c.NonResourceURLs) == 0 {\n\t\treturn fmt.Errorf(\"one of resource or nonResourceURL must be specified\")\n\t}\n\n\t// validate resources\n\tif len(c.Resources) \u003e 0 {\n\t\tfor _, v := range c.Verbs {\n\t\t\tif !arrayContains(validResourceVerbs, v) {\n\t\t\t\tfmt.Fprintf(c.ErrOut, \"Warning: '%s' is not a standard resource verb\\n\", v)\n\t\t\t}\n\t\t}\n\t\tif err := c.validateResource(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t//validate non-resource-url\n\tif len(c.NonResourceURLs) \u003e 0 {\n\t\tfor _, v := range c.Verbs {\n\t\t\tif !arrayContains(validNonResourceVerbs, v) {\n\t\t\t\treturn fmt.Errorf(\"invalid verb: '%s' for nonResourceURL\", v)\n\t\t\t}\n\t\t}\n\n\t\tfor _, nonResourceURL := range c.NonResourceURLs {\n\t\t\tif nonResourceURL == \"*\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif nonResourceURL == \"\" || !strings.HasPrefix(nonResourceURL, \"/\") {\n\t\t\t\treturn fmt.Errorf(\"nonResourceURL should start with /\")\n\t\t\t}\n\n\t\t\tif strings.ContainsRune(nonResourceURL[:len(nonResourceURL)-1], '*') {\n\t\t\t\treturn fmt.Errorf(\"nonResourceURL only supports wildcard matches when '*' is at the end\")\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n\n}","line":{"from":120,"to":179}} {"id":100031625,"name":"RunCreateRole","signature":"func (c *CreateClusterRoleOptions) RunCreateRole() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_clusterrole.go","code":"// RunCreateRole creates a new clusterRole\nfunc (c *CreateClusterRoleOptions) RunCreateRole() error {\n\tclusterRole := \u0026rbacv1.ClusterRole{\n\t\t// this is ok because we know exactly how we want to be serialized\n\t\tTypeMeta: metav1.TypeMeta{APIVersion: rbacv1.SchemeGroupVersion.String(), Kind: \"ClusterRole\"},\n\t}\n\tclusterRole.Name = c.Name\n\n\tvar err error\n\tif len(c.AggregationRule) == 0 {\n\t\trules, err := generateResourcePolicyRules(c.Mapper, c.Verbs, c.Resources, c.ResourceNames, c.NonResourceURLs)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tclusterRole.Rules = rules\n\t} else {\n\t\tclusterRole.AggregationRule = \u0026rbacv1.AggregationRule{\n\t\t\tClusterRoleSelectors: []metav1.LabelSelector{\n\t\t\t\t{\n\t\t\t\t\tMatchLabels: c.AggregationRule,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\tif err := util.CreateOrUpdateAnnotation(c.CreateAnnotation, clusterRole, scheme.DefaultJSONEncoder()); err != nil {\n\t\treturn err\n\t}\n\n\t// Create ClusterRole.\n\tif c.DryRunStrategy != cmdutil.DryRunClient {\n\t\tcreateOptions := metav1.CreateOptions{}\n\t\tif c.FieldManager != \"\" {\n\t\t\tcreateOptions.FieldManager = c.FieldManager\n\t\t}\n\t\tcreateOptions.FieldValidation = c.ValidationDirective\n\t\tif c.DryRunStrategy == cmdutil.DryRunServer {\n\t\t\tcreateOptions.DryRun = []string{metav1.DryRunAll}\n\t\t}\n\t\tclusterRole, err = c.Client.ClusterRoles().Create(context.TODO(), clusterRole, createOptions)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn c.PrintObj(clusterRole)\n}","line":{"from":181,"to":227}} {"id":100031626,"name":"NewClusterRoleBindingOptions","signature":"func NewClusterRoleBindingOptions(ioStreams genericclioptions.IOStreams) *ClusterRoleBindingOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_clusterrolebinding.go","code":"// NewClusterRoleBindingOptions creates a new *ClusterRoleBindingOptions with sane defaults\nfunc NewClusterRoleBindingOptions(ioStreams genericclioptions.IOStreams) *ClusterRoleBindingOptions {\n\treturn \u0026ClusterRoleBindingOptions{\n\t\tUsers: []string{},\n\t\tGroups: []string{},\n\t\tServiceAccounts: []string{},\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"created\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":68,"to":77}} {"id":100031627,"name":"NewCmdCreateClusterRoleBinding","signature":"func NewCmdCreateClusterRoleBinding(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_clusterrolebinding.go","code":"// NewCmdCreateClusterRoleBinding returns an initialized command instance of ClusterRoleBinding\nfunc NewCmdCreateClusterRoleBinding(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewClusterRoleBindingOptions(ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"clusterrolebinding NAME --clusterrole=NAME [--user=username] [--group=groupname] [--serviceaccount=namespace:serviceaccountname] [--dry-run=server|client|none]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Create a cluster role binding for a particular cluster role\"),\n\t\tLong: clusterRoleBindingLong,\n\t\tExample: clusterRoleBindingExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmd.Flags().StringVar(\u0026o.ClusterRole, \"clusterrole\", \"\", i18n.T(\"ClusterRole this ClusterRoleBinding should reference\"))\n\tcmd.MarkFlagRequired(\"clusterrole\")\n\tcmd.Flags().StringArrayVar(\u0026o.Users, \"user\", o.Users, \"Usernames to bind to the clusterrole. The flag can be repeated to add multiple users.\")\n\tcmd.Flags().StringArrayVar(\u0026o.Groups, \"group\", o.Groups, \"Groups to bind to the clusterrole. The flag can be repeated to add multiple groups.\")\n\tcmd.Flags().StringArrayVar(\u0026o.ServiceAccounts, \"serviceaccount\", o.ServiceAccounts, \"Service accounts to bind to the clusterrole, in the format \u003cnamespace\u003e:\u003cname\u003e. The flag can be repeated to add multiple service accounts.\")\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.FieldManager, \"kubectl-create\")\n\n\t// Completion for relevant flags\n\tcmdutil.CheckErr(cmd.RegisterFlagCompletionFunc(\n\t\t\"clusterrole\",\n\t\tfunc(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\t\t\treturn completion.CompGetResource(f, \"clusterrole\", toComplete), cobra.ShellCompDirectiveNoFileComp\n\t\t}))\n\n\treturn cmd\n}","line":{"from":79,"to":115}} {"id":100031628,"name":"Complete","signature":"func (o *ClusterRoleBindingOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_clusterrolebinding.go","code":"// Complete completes all the required options\nfunc (o *ClusterRoleBindingOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\to.Name, err = NameFromCommandArgs(cmd, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcs, err := f.KubernetesClientSet()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.Client = cs.RbacV1()\n\n\to.CreateAnnotation = cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag)\n\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.PrintObj = func(obj runtime.Object) error {\n\t\treturn printer.PrintObj(obj, o.Out)\n\t}\n\to.ValidationDirective, err = cmdutil.GetValidationDirective(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":117,"to":152}} {"id":100031629,"name":"Run","signature":"func (o *ClusterRoleBindingOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_clusterrolebinding.go","code":"// Run calls the CreateSubcommandOptions.Run in ClusterRoleBindingOptions instance\nfunc (o *ClusterRoleBindingOptions) Run() error {\n\tclusterRoleBinding, err := o.createClusterRoleBinding()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := util.CreateOrUpdateAnnotation(o.CreateAnnotation, clusterRoleBinding, scheme.DefaultJSONEncoder()); err != nil {\n\t\treturn err\n\t}\n\n\tif o.DryRunStrategy != cmdutil.DryRunClient {\n\t\tcreateOptions := metav1.CreateOptions{}\n\t\tif o.FieldManager != \"\" {\n\t\t\tcreateOptions.FieldManager = o.FieldManager\n\t\t}\n\t\tcreateOptions.FieldValidation = o.ValidationDirective\n\t\tif o.DryRunStrategy == cmdutil.DryRunServer {\n\t\t\tcreateOptions.DryRun = []string{metav1.DryRunAll}\n\t\t}\n\t\tvar err error\n\t\tclusterRoleBinding, err = o.Client.ClusterRoleBindings().Create(context.TODO(), clusterRoleBinding, createOptions)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create clusterrolebinding: %v\", err)\n\t\t}\n\t}\n\n\treturn o.PrintObj(clusterRoleBinding)\n}","line":{"from":154,"to":182}} {"id":100031630,"name":"createClusterRoleBinding","signature":"func (o *ClusterRoleBindingOptions) createClusterRoleBinding() (*rbacv1.ClusterRoleBinding, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_clusterrolebinding.go","code":"func (o *ClusterRoleBindingOptions) createClusterRoleBinding() (*rbacv1.ClusterRoleBinding, error) {\n\tclusterRoleBinding := \u0026rbacv1.ClusterRoleBinding{\n\t\tTypeMeta: metav1.TypeMeta{APIVersion: rbacv1.SchemeGroupVersion.String(), Kind: \"ClusterRoleBinding\"},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: o.Name,\n\t\t},\n\t\tRoleRef: rbacv1.RoleRef{\n\t\t\tAPIGroup: rbacv1.GroupName,\n\t\t\tKind: \"ClusterRole\",\n\t\t\tName: o.ClusterRole,\n\t\t},\n\t}\n\n\tfor _, user := range o.Users {\n\t\tclusterRoleBinding.Subjects = append(clusterRoleBinding.Subjects, rbacv1.Subject{\n\t\t\tKind: rbacv1.UserKind,\n\t\t\tAPIGroup: rbacv1.GroupName,\n\t\t\tName: user,\n\t\t})\n\t}\n\n\tfor _, group := range o.Groups {\n\t\tclusterRoleBinding.Subjects = append(clusterRoleBinding.Subjects, rbacv1.Subject{\n\t\t\tKind: rbacv1.GroupKind,\n\t\t\tAPIGroup: rbacv1.GroupName,\n\t\t\tName: group,\n\t\t})\n\t}\n\n\tfor _, sa := range o.ServiceAccounts {\n\t\ttokens := strings.Split(sa, \":\")\n\t\tif len(tokens) != 2 || tokens[0] == \"\" || tokens[1] == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"serviceaccount must be \u003cnamespace\u003e:\u003cname\u003e\")\n\t\t}\n\t\tclusterRoleBinding.Subjects = append(clusterRoleBinding.Subjects, rbacv1.Subject{\n\t\t\tKind: rbacv1.ServiceAccountKind,\n\t\t\tAPIGroup: \"\",\n\t\t\tNamespace: tokens[0],\n\t\t\tName: tokens[1],\n\t\t})\n\t}\n\n\treturn clusterRoleBinding, nil\n}","line":{"from":184,"to":227}} {"id":100031631,"name":"NewConfigMapOptions","signature":"func NewConfigMapOptions(ioStreams genericclioptions.IOStreams) *ConfigMapOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_configmap.go","code":"// NewConfigMapOptions creates a new *ConfigMapOptions with default value\nfunc NewConfigMapOptions(ioStreams genericclioptions.IOStreams) *ConfigMapOptions {\n\treturn \u0026ConfigMapOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"created\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":104,"to":110}} {"id":100031632,"name":"NewCmdCreateConfigMap","signature":"func NewCmdCreateConfigMap(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_configmap.go","code":"// NewCmdCreateConfigMap creates the `create configmap` Cobra command\nfunc NewCmdCreateConfigMap(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewConfigMapOptions(ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"configmap NAME [--from-file=[key=]source] [--from-literal=key1=value1] [--dry-run=server|client|none]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tAliases: []string{\"cm\"},\n\t\tShort: i18n.T(\"Create a config map from a local file, directory or literal value\"),\n\t\tLong: configMapLong,\n\t\tExample: configMapExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmdutil.AddDryRunFlag(cmd)\n\n\tcmd.Flags().StringSliceVar(\u0026o.FileSources, \"from-file\", o.FileSources, \"Key file can be specified using its file path, in which case file basename will be used as configmap key, or optionally with a key and file path, in which case the given key will be used. Specifying a directory will iterate each named file in the directory whose basename is a valid configmap key.\")\n\tcmd.Flags().StringArrayVar(\u0026o.LiteralSources, \"from-literal\", o.LiteralSources, \"Specify a key and literal value to insert in configmap (i.e. mykey=somevalue)\")\n\tcmd.Flags().StringSliceVar(\u0026o.EnvFileSources, \"from-env-file\", o.EnvFileSources, \"Specify the path to a file to read lines of key=val pairs to create a configmap.\")\n\tcmd.Flags().BoolVar(\u0026o.AppendHash, \"append-hash\", o.AppendHash, \"Append a hash of the configmap to its name.\")\n\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.FieldManager, \"kubectl-create\")\n\n\treturn cmd\n}","line":{"from":112,"to":143}} {"id":100031633,"name":"Complete","signature":"func (o *ConfigMapOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_configmap.go","code":"// Complete loads data from the command line environment\nfunc (o *ConfigMapOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\to.Name, err = NameFromCommandArgs(cmd, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trestConfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Client, err = corev1client.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.CreateAnnotation = cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag)\n\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.PrintObj = func(obj runtime.Object) error {\n\t\treturn printer.PrintObj(obj, o.Out)\n\t}\n\n\to.ValidationDirective, err = cmdutil.GetValidationDirective(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":145,"to":190}} {"id":100031634,"name":"Validate","signature":"func (o *ConfigMapOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_configmap.go","code":"// Validate checks if ConfigMapOptions has sufficient value to run\nfunc (o *ConfigMapOptions) Validate() error {\n\tif len(o.Name) == 0 {\n\t\treturn fmt.Errorf(\"name must be specified\")\n\t}\n\tif len(o.EnvFileSources) \u003e 0 \u0026\u0026 (len(o.FileSources) \u003e 0 || len(o.LiteralSources) \u003e 0) {\n\t\treturn fmt.Errorf(\"from-env-file cannot be combined with from-file or from-literal\")\n\t}\n\treturn nil\n}","line":{"from":192,"to":201}} {"id":100031635,"name":"Run","signature":"func (o *ConfigMapOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_configmap.go","code":"// Run calls createConfigMap and filled in value for configMap object\nfunc (o *ConfigMapOptions) Run() error {\n\tconfigMap, err := o.createConfigMap()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := util.CreateOrUpdateAnnotation(o.CreateAnnotation, configMap, scheme.DefaultJSONEncoder()); err != nil {\n\t\treturn err\n\t}\n\tif o.DryRunStrategy != cmdutil.DryRunClient {\n\t\tcreateOptions := metav1.CreateOptions{}\n\t\tif o.FieldManager != \"\" {\n\t\t\tcreateOptions.FieldManager = o.FieldManager\n\t\t}\n\t\tcreateOptions.FieldValidation = o.ValidationDirective\n\t\tif o.DryRunStrategy == cmdutil.DryRunServer {\n\t\t\tcreateOptions.DryRun = []string{metav1.DryRunAll}\n\t\t}\n\t\tconfigMap, err = o.Client.ConfigMaps(o.Namespace).Create(context.TODO(), configMap, createOptions)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create configmap: %v\", err)\n\t\t}\n\t}\n\n\treturn o.PrintObj(configMap)\n}","line":{"from":203,"to":228}} {"id":100031636,"name":"createConfigMap","signature":"func (o *ConfigMapOptions) createConfigMap() (*corev1.ConfigMap, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_configmap.go","code":"// createConfigMap fills in key value pair from the information given in\n// ConfigMapOptions into *corev1.ConfigMap\nfunc (o *ConfigMapOptions) createConfigMap() (*corev1.ConfigMap, error) {\n\tnamespace := \"\"\n\tif o.EnforceNamespace {\n\t\tnamespace = o.Namespace\n\t}\n\n\tconfigMap := \u0026corev1.ConfigMap{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: corev1.SchemeGroupVersion.String(),\n\t\t\tKind: \"ConfigMap\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: o.Name,\n\t\t\tNamespace: namespace,\n\t\t},\n\t}\n\tconfigMap.Name = o.Name\n\tconfigMap.Data = map[string]string{}\n\tconfigMap.BinaryData = map[string][]byte{}\n\n\tif len(o.FileSources) \u003e 0 {\n\t\tif err := handleConfigMapFromFileSources(configMap, o.FileSources); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif len(o.LiteralSources) \u003e 0 {\n\t\tif err := handleConfigMapFromLiteralSources(configMap, o.LiteralSources); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif len(o.EnvFileSources) \u003e 0 {\n\t\tif err := handleConfigMapFromEnvFileSources(configMap, o.EnvFileSources); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif o.AppendHash {\n\t\thash, err := hash.ConfigMapHash(configMap)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tconfigMap.Name = fmt.Sprintf(\"%s-%s\", configMap.Name, hash)\n\t}\n\n\treturn configMap, nil\n}","line":{"from":230,"to":276}} {"id":100031637,"name":"handleConfigMapFromLiteralSources","signature":"func handleConfigMapFromLiteralSources(configMap *corev1.ConfigMap, literalSources []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_configmap.go","code":"// handleConfigMapFromLiteralSources adds the specified literal source\n// information into the provided configMap.\nfunc handleConfigMapFromLiteralSources(configMap *corev1.ConfigMap, literalSources []string) error {\n\tfor _, literalSource := range literalSources {\n\t\tkeyName, value, err := util.ParseLiteralSource(literalSource)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = addKeyFromLiteralToConfigMap(configMap, keyName, value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":278,"to":293}} {"id":100031638,"name":"handleConfigMapFromFileSources","signature":"func handleConfigMapFromFileSources(configMap *corev1.ConfigMap, fileSources []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_configmap.go","code":"// handleConfigMapFromFileSources adds the specified file source information\n// into the provided configMap\nfunc handleConfigMapFromFileSources(configMap *corev1.ConfigMap, fileSources []string) error {\n\tfor _, fileSource := range fileSources {\n\t\tkeyName, filePath, err := util.ParseFileSource(fileSource)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tinfo, err := os.Stat(filePath)\n\t\tif err != nil {\n\t\t\tswitch err := err.(type) {\n\t\t\tcase *os.PathError:\n\t\t\t\treturn fmt.Errorf(\"error reading %s: %v\", filePath, err.Err)\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"error reading %s: %v\", filePath, err)\n\t\t\t}\n\n\t\t}\n\t\tif info.IsDir() {\n\t\t\tif strings.Contains(fileSource, \"=\") {\n\t\t\t\treturn fmt.Errorf(\"cannot give a key name for a directory path\")\n\t\t\t}\n\t\t\tfileList, err := os.ReadDir(filePath)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error listing files in %s: %v\", filePath, err)\n\t\t\t}\n\t\t\tfor _, item := range fileList {\n\t\t\t\titemPath := path.Join(filePath, item.Name())\n\t\t\t\tif item.Type().IsRegular() {\n\t\t\t\t\tkeyName = item.Name()\n\t\t\t\t\terr = addKeyFromFileToConfigMap(configMap, keyName, itemPath)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif err := addKeyFromFileToConfigMap(configMap, keyName, filePath); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":295,"to":339}} {"id":100031639,"name":"handleConfigMapFromEnvFileSources","signature":"func handleConfigMapFromEnvFileSources(configMap *corev1.ConfigMap, envFileSources []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_configmap.go","code":"// handleConfigMapFromEnvFileSources adds the specified env file source information\n// into the provided configMap\nfunc handleConfigMapFromEnvFileSources(configMap *corev1.ConfigMap, envFileSources []string) error {\n\tfor _, envFileSource := range envFileSources {\n\t\tinfo, err := os.Stat(envFileSource)\n\t\tif err != nil {\n\t\t\tswitch err := err.(type) {\n\t\t\tcase *os.PathError:\n\t\t\t\treturn fmt.Errorf(\"error reading %s: %v\", envFileSource, err.Err)\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"error reading %s: %v\", envFileSource, err)\n\t\t\t}\n\t\t}\n\t\tif info.IsDir() {\n\t\t\treturn fmt.Errorf(\"env config file cannot be a directory\")\n\t\t}\n\t\terr = cmdutil.AddFromEnvFile(envFileSource, func(key, value string) error {\n\t\t\treturn addKeyFromLiteralToConfigMap(configMap, key, value)\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":341,"to":366}} {"id":100031640,"name":"addKeyFromFileToConfigMap","signature":"func addKeyFromFileToConfigMap(configMap *corev1.ConfigMap, keyName, filePath string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_configmap.go","code":"// addKeyFromFileToConfigMap adds a key with the given name to a ConfigMap, populating\n// the value with the content of the given file path, or returns an error.\nfunc addKeyFromFileToConfigMap(configMap *corev1.ConfigMap, keyName, filePath string) error {\n\tdata, err := os.ReadFile(filePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif utf8.Valid(data) {\n\t\treturn addKeyFromLiteralToConfigMap(configMap, keyName, string(data))\n\t}\n\terr = validateNewConfigMap(configMap, keyName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfigMap.BinaryData[keyName] = data\n\n\treturn nil\n}","line":{"from":368,"to":385}} {"id":100031641,"name":"addKeyFromLiteralToConfigMap","signature":"func addKeyFromLiteralToConfigMap(configMap *corev1.ConfigMap, keyName, data string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_configmap.go","code":"// addKeyFromLiteralToConfigMap adds the given key and data to the given config map,\n// returning an error if the key is not valid or if the key already exists.\nfunc addKeyFromLiteralToConfigMap(configMap *corev1.ConfigMap, keyName, data string) error {\n\terr := validateNewConfigMap(configMap, keyName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfigMap.Data[keyName] = data\n\n\treturn nil\n}","line":{"from":387,"to":397}} {"id":100031642,"name":"validateNewConfigMap","signature":"func validateNewConfigMap(configMap *corev1.ConfigMap, keyName string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_configmap.go","code":"// validateNewConfigMap checks whether the keyname is valid\n// Note, the rules for ConfigMap keys are the exact same as the ones for SecretKeys.\nfunc validateNewConfigMap(configMap *corev1.ConfigMap, keyName string) error {\n\tif errs := validation.IsConfigMapKey(keyName); len(errs) \u003e 0 {\n\t\treturn fmt.Errorf(\"%q is not a valid key name for a ConfigMap: %s\", keyName, strings.Join(errs, \",\"))\n\t}\n\tif _, exists := configMap.Data[keyName]; exists {\n\t\treturn fmt.Errorf(\"cannot add key %q, another key by that name already exists in Data for ConfigMap %q\", keyName, configMap.Name)\n\t}\n\tif _, exists := configMap.BinaryData[keyName]; exists {\n\t\treturn fmt.Errorf(\"cannot add key %q, another key by that name already exists in BinaryData for ConfigMap %q\", keyName, configMap.Name)\n\t}\n\n\treturn nil\n}","line":{"from":399,"to":413}} {"id":100031643,"name":"NewCreateCronJobOptions","signature":"func NewCreateCronJobOptions(ioStreams genericclioptions.IOStreams) *CreateCronJobOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_cronjob.go","code":"// NewCreateCronJobOptions returns an initialized CreateCronJobOptions instance\nfunc NewCreateCronJobOptions(ioStreams genericclioptions.IOStreams) *CreateCronJobOptions {\n\treturn \u0026CreateCronJobOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"created\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":75,"to":81}} {"id":100031644,"name":"NewCmdCreateCronJob","signature":"func NewCmdCreateCronJob(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_cronjob.go","code":"// NewCmdCreateCronJob is a command to create CronJobs.\nfunc NewCmdCreateCronJob(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewCreateCronJobOptions(ioStreams)\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"cronjob NAME --image=image --schedule='0/5 * * * ?' -- [COMMAND] [args...]\",\n\t\tDisableFlagsInUseLine: false,\n\t\tAliases: []string{\"cj\"},\n\t\tShort: i18n.T(\"Create a cron job with the specified name\"),\n\t\tLong: cronjobLong,\n\t\tExample: cronjobExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmd.Flags().StringVar(\u0026o.Image, \"image\", o.Image, \"Image name to run.\")\n\tcmd.MarkFlagRequired(\"image\")\n\tcmd.Flags().StringVar(\u0026o.Schedule, \"schedule\", o.Schedule, \"A schedule in the Cron format the job should be run with.\")\n\tcmd.MarkFlagRequired(\"schedule\")\n\tcmd.Flags().StringVar(\u0026o.Restart, \"restart\", o.Restart, \"job's restart policy. supported values: OnFailure, Never\")\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.FieldManager, \"kubectl-create\")\n\n\treturn cmd\n}","line":{"from":83,"to":112}} {"id":100031645,"name":"Complete","signature":"func (o *CreateCronJobOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_cronjob.go","code":"// Complete completes all the required options\nfunc (o *CreateCronJobOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tname, err := NameFromCommandArgs(cmd, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\to.Name = name\n\tif len(args) \u003e 1 {\n\t\to.Command = args[1:]\n\t}\n\tif len(o.Restart) == 0 {\n\t\to.Restart = \"OnFailure\"\n\t}\n\n\tclientConfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.Client, err = batchv1client.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.Builder = f.NewBuilder()\n\n\to.CreateAnnotation = cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag)\n\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.PrintObj = func(obj runtime.Object) error {\n\t\treturn printer.PrintObj(obj, o.Out)\n\t}\n\n\to.ValidationDirective, err = cmdutil.GetValidationDirective(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":114,"to":164}} {"id":100031646,"name":"Run","signature":"func (o *CreateCronJobOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_cronjob.go","code":"// Run performs the execution of 'create cronjob' sub command\nfunc (o *CreateCronJobOptions) Run() error {\n\tcronJob := o.createCronJob()\n\tif err := util.CreateOrUpdateAnnotation(o.CreateAnnotation, cronJob, scheme.DefaultJSONEncoder()); err != nil {\n\t\treturn err\n\t}\n\n\tif o.DryRunStrategy != cmdutil.DryRunClient {\n\t\tcreateOptions := metav1.CreateOptions{}\n\t\tif o.FieldManager != \"\" {\n\t\t\tcreateOptions.FieldManager = o.FieldManager\n\t\t}\n\t\tcreateOptions.FieldValidation = o.ValidationDirective\n\t\tif o.DryRunStrategy == cmdutil.DryRunServer {\n\t\t\tcreateOptions.DryRun = []string{metav1.DryRunAll}\n\t\t}\n\t\tvar err error\n\t\tcronJob, err = o.Client.CronJobs(o.Namespace).Create(context.TODO(), cronJob, createOptions)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create cronjob: %v\", err)\n\t\t}\n\t}\n\n\treturn o.PrintObj(cronJob)\n}","line":{"from":166,"to":190}} {"id":100031647,"name":"createCronJob","signature":"func (o *CreateCronJobOptions) createCronJob() *batchv1.CronJob","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_cronjob.go","code":"func (o *CreateCronJobOptions) createCronJob() *batchv1.CronJob {\n\tcronjob := \u0026batchv1.CronJob{\n\t\tTypeMeta: metav1.TypeMeta{APIVersion: batchv1.SchemeGroupVersion.String(), Kind: \"CronJob\"},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: o.Name,\n\t\t},\n\t\tSpec: batchv1.CronJobSpec{\n\t\t\tSchedule: o.Schedule,\n\t\t\tJobTemplate: batchv1.JobTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: o.Name,\n\t\t\t\t},\n\t\t\t\tSpec: batchv1.JobSpec{\n\t\t\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\t\t\tContainers: []corev1.Container{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tName: o.Name,\n\t\t\t\t\t\t\t\t\tImage: o.Image,\n\t\t\t\t\t\t\t\t\tCommand: o.Command,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tRestartPolicy: corev1.RestartPolicy(o.Restart),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tif o.EnforceNamespace {\n\t\tcronjob.Namespace = o.Namespace\n\t}\n\treturn cronjob\n}","line":{"from":192,"to":225}} {"id":100031648,"name":"NewCreateDeploymentOptions","signature":"func NewCreateDeploymentOptions(ioStreams genericclioptions.IOStreams) *CreateDeploymentOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_deployment.go","code":"// NewCreateDeploymentOptions returns an initialized CreateDeploymentOptions instance\nfunc NewCreateDeploymentOptions(ioStreams genericclioptions.IOStreams) *CreateDeploymentOptions {\n\treturn \u0026CreateDeploymentOptions{\n\t\tPort: -1,\n\t\tReplicas: 1,\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"created\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":81,"to":89}} {"id":100031649,"name":"NewCmdCreateDeployment","signature":"func NewCmdCreateDeployment(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_deployment.go","code":"// NewCmdCreateDeployment is a macro command to create a new deployment.\n// This command is better known to users as `kubectl create deployment`.\nfunc NewCmdCreateDeployment(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewCreateDeploymentOptions(ioStreams)\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"deployment NAME --image=image -- [COMMAND] [args...]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tAliases: []string{\"deploy\"},\n\t\tShort: i18n.T(\"Create a deployment with the specified name\"),\n\t\tLong: deploymentLong,\n\t\tExample: deploymentExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmd.Flags().StringSliceVar(\u0026o.Images, \"image\", o.Images, \"Image names to run.\")\n\tcmd.MarkFlagRequired(\"image\")\n\tcmd.Flags().Int32Var(\u0026o.Port, \"port\", o.Port, \"The port that this container exposes.\")\n\tcmd.Flags().Int32VarP(\u0026o.Replicas, \"replicas\", \"r\", o.Replicas, \"Number of replicas to create. Default is 1.\")\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.FieldManager, \"kubectl-create\")\n\n\treturn cmd\n}","line":{"from":91,"to":121}} {"id":100031650,"name":"Complete","signature":"func (o *CreateDeploymentOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_deployment.go","code":"// Complete completes all the options\nfunc (o *CreateDeploymentOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tname, err := NameFromCommandArgs(cmd, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\to.Name = name\n\tif len(args) \u003e 1 {\n\t\to.Command = args[1:]\n\t}\n\n\tclientConfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.Client, err = appsv1client.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.CreateAnnotation = cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag)\n\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.PrintObj = func(obj runtime.Object) error {\n\t\treturn printer.PrintObj(obj, o.Out)\n\t}\n\n\to.ValidationDirective, err = cmdutil.GetValidationDirective(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":123,"to":170}} {"id":100031651,"name":"Validate","signature":"func (o *CreateDeploymentOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_deployment.go","code":"// Validate makes sure there is no discrepency in provided option values\nfunc (o *CreateDeploymentOptions) Validate() error {\n\tif len(o.Images) \u003e 1 \u0026\u0026 len(o.Command) \u003e 0 {\n\t\treturn fmt.Errorf(\"cannot specify multiple --image options and command\")\n\t}\n\treturn nil\n}","line":{"from":172,"to":178}} {"id":100031652,"name":"Run","signature":"func (o *CreateDeploymentOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_deployment.go","code":"// Run performs the execution of 'create deployment' sub command\nfunc (o *CreateDeploymentOptions) Run() error {\n\tdeploy := o.createDeployment()\n\n\tif err := util.CreateOrUpdateAnnotation(o.CreateAnnotation, deploy, scheme.DefaultJSONEncoder()); err != nil {\n\t\treturn err\n\t}\n\n\tif o.DryRunStrategy != cmdutil.DryRunClient {\n\t\tcreateOptions := metav1.CreateOptions{}\n\t\tif o.FieldManager != \"\" {\n\t\t\tcreateOptions.FieldManager = o.FieldManager\n\t\t}\n\t\tcreateOptions.FieldValidation = o.ValidationDirective\n\t\tif o.DryRunStrategy == cmdutil.DryRunServer {\n\t\t\tcreateOptions.DryRun = []string{metav1.DryRunAll}\n\t\t}\n\t\tvar err error\n\t\tdeploy, err = o.Client.Deployments(o.Namespace).Create(context.TODO(), deploy, createOptions)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create deployment: %v\", err)\n\t\t}\n\t}\n\n\treturn o.PrintObj(deploy)\n}","line":{"from":180,"to":205}} {"id":100031653,"name":"createDeployment","signature":"func (o *CreateDeploymentOptions) createDeployment() *appsv1.Deployment","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_deployment.go","code":"func (o *CreateDeploymentOptions) createDeployment() *appsv1.Deployment {\n\tlabels := map[string]string{\"app\": o.Name}\n\tselector := metav1.LabelSelector{MatchLabels: labels}\n\tnamespace := \"\"\n\tif o.EnforceNamespace {\n\t\tnamespace = o.Namespace\n\t}\n\n\tdeploy := \u0026appsv1.Deployment{\n\t\tTypeMeta: metav1.TypeMeta{APIVersion: appsv1.SchemeGroupVersion.String(), Kind: \"Deployment\"},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: o.Name,\n\t\t\tLabels: labels,\n\t\t\tNamespace: namespace,\n\t\t},\n\t\tSpec: appsv1.DeploymentSpec{\n\t\t\tReplicas: \u0026o.Replicas,\n\t\t\tSelector: \u0026selector,\n\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: labels,\n\t\t\t\t},\n\t\t\t\tSpec: o.buildPodSpec(),\n\t\t\t},\n\t\t},\n\t}\n\n\tif o.Port \u003e= 0 \u0026\u0026 len(deploy.Spec.Template.Spec.Containers) \u003e 0 {\n\t\tdeploy.Spec.Template.Spec.Containers[0].Ports = []corev1.ContainerPort{{ContainerPort: o.Port}}\n\t}\n\treturn deploy\n}","line":{"from":207,"to":238}} {"id":100031654,"name":"buildPodSpec","signature":"func (o *CreateDeploymentOptions) buildPodSpec() corev1.PodSpec","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_deployment.go","code":"// buildPodSpec parses the image strings and assemble them into the Containers\n// of a PodSpec. This is all you need to create the PodSpec for a deployment.\nfunc (o *CreateDeploymentOptions) buildPodSpec() corev1.PodSpec {\n\tpodSpec := corev1.PodSpec{Containers: []corev1.Container{}}\n\tfor _, imageString := range o.Images {\n\t\t// Retain just the image name\n\t\timageSplit := strings.Split(imageString, \"/\")\n\t\tname := imageSplit[len(imageSplit)-1]\n\t\t// Remove any tag or hash\n\t\tif strings.Contains(name, \":\") {\n\t\t\tname = strings.Split(name, \":\")[0]\n\t\t}\n\t\tif strings.Contains(name, \"@\") {\n\t\t\tname = strings.Split(name, \"@\")[0]\n\t\t}\n\t\tname = sanitizeAndUniquify(name)\n\t\tpodSpec.Containers = append(podSpec.Containers, corev1.Container{\n\t\t\tName: name,\n\t\t\tImage: imageString,\n\t\t\tCommand: o.Command,\n\t\t})\n\t}\n\treturn podSpec\n}","line":{"from":240,"to":263}} {"id":100031655,"name":"sanitizeAndUniquify","signature":"func sanitizeAndUniquify(name string) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_deployment.go","code":"// sanitizeAndUniquify replaces characters like \".\" or \"_\" into \"-\" to follow DNS1123 rules.\n// Then add random suffix to make it uniquified.\nfunc sanitizeAndUniquify(name string) string {\n\tif strings.ContainsAny(name, \"_.\") {\n\t\tname = strings.Replace(name, \"_\", \"-\", -1)\n\t\tname = strings.Replace(name, \".\", \"-\", -1)\n\t\tname = fmt.Sprintf(\"%s-%s\", name, utilrand.String(5))\n\t}\n\treturn name\n}","line":{"from":265,"to":274}} {"id":100031656,"name":"NewCreateIngressOptions","signature":"func NewCreateIngressOptions(ioStreams genericclioptions.IOStreams) *CreateIngressOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_ingress.go","code":"// NewCreateIngressOptions creates the CreateIngressOptions to be used later\nfunc NewCreateIngressOptions(ioStreams genericclioptions.IOStreams) *CreateIngressOptions {\n\treturn \u0026CreateIngressOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"created\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":127,"to":133}} {"id":100031657,"name":"NewCmdCreateIngress","signature":"func NewCmdCreateIngress(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_ingress.go","code":"// NewCmdCreateIngress is a macro command to create a new ingress.\n// This command is better known to users as `kubectl create ingress`.\nfunc NewCmdCreateIngress(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewCreateIngressOptions(ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"ingress NAME --rule=host/path=service:port[,tls[=secret]] \",\n\t\tDisableFlagsInUseLine: true,\n\t\tAliases: []string{\"ing\"},\n\t\tShort: i18n.T(\"Create an ingress with the specified name\"),\n\t\tLong: ingressLong,\n\t\tExample: ingressExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmd.Flags().StringVar(\u0026o.IngressClass, \"class\", o.IngressClass, \"Ingress Class to be used\")\n\tcmd.Flags().StringArrayVar(\u0026o.Rules, \"rule\", o.Rules, \"Rule in format host/path=service:port[,tls=secretname]. Paths containing the leading character '*' are considered pathType=Prefix. tls argument is optional.\")\n\tcmd.Flags().StringVar(\u0026o.DefaultBackend, \"default-backend\", o.DefaultBackend, \"Default service for backend, in format of svcname:port\")\n\tcmd.Flags().StringArrayVar(\u0026o.Annotations, \"annotation\", o.Annotations, \"Annotation to insert in the ingress object, in the format annotation=value\")\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.FieldManager, \"kubectl-create\")\n\n\treturn cmd\n}","line":{"from":135,"to":166}} {"id":100031658,"name":"Complete","signature":"func (o *CreateIngressOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_ingress.go","code":"// Complete completes all the options\nfunc (o *CreateIngressOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tname, err := NameFromCommandArgs(cmd, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\to.Name = name\n\n\tclientConfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.Client, err = networkingv1client.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.CreateAnnotation = cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag)\n\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.PrintObj = func(obj runtime.Object) error {\n\t\treturn printer.PrintObj(obj, o.Out)\n\t}\n\n\to.ValidationDirective, err = cmdutil.GetValidationDirective(cmd)\n\treturn err\n}","line":{"from":168,"to":208}} {"id":100031659,"name":"Validate","signature":"func (o *CreateIngressOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_ingress.go","code":"// Validate validates the Ingress object to be created\nfunc (o *CreateIngressOptions) Validate() error {\n\tif len(o.DefaultBackend) == 0 \u0026\u0026 len(o.Rules) == 0 {\n\t\treturn fmt.Errorf(\"not enough information provided: every ingress has to either specify a default-backend (which catches all traffic) or a list of rules (which catch specific paths)\")\n\t}\n\n\trulevalidation, err := regexp.Compile(ruleRegex)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to compile the regex\")\n\t}\n\n\tfor _, rule := range o.Rules {\n\t\tif match := rulevalidation.MatchString(rule); !match {\n\t\t\treturn fmt.Errorf(\"rule %s is invalid and should be in format host/path=svcname:svcport[,tls[=secret]]\", rule)\n\t\t}\n\t}\n\n\tfor _, annotation := range o.Annotations {\n\t\tif an := strings.SplitN(annotation, \"=\", 2); len(an) != 2 {\n\t\t\treturn fmt.Errorf(\"annotation %s is invalid and should be in format key=[value]\", annotation)\n\t\t}\n\t}\n\n\tif len(o.DefaultBackend) \u003e 0 \u0026\u0026 len(strings.Split(o.DefaultBackend, \":\")) != 2 {\n\t\treturn fmt.Errorf(\"default-backend should be in format servicename:serviceport\")\n\t}\n\n\treturn nil\n}","line":{"from":210,"to":238}} {"id":100031660,"name":"Run","signature":"func (o *CreateIngressOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_ingress.go","code":"// Run performs the execution of 'create ingress' sub command\nfunc (o *CreateIngressOptions) Run() error {\n\tingress := o.createIngress()\n\n\tif err := util.CreateOrUpdateAnnotation(o.CreateAnnotation, ingress, scheme.DefaultJSONEncoder()); err != nil {\n\t\treturn err\n\t}\n\n\tif o.DryRunStrategy != cmdutil.DryRunClient {\n\t\tcreateOptions := metav1.CreateOptions{}\n\t\tif o.FieldManager != \"\" {\n\t\t\tcreateOptions.FieldManager = o.FieldManager\n\t\t}\n\t\tcreateOptions.FieldValidation = o.ValidationDirective\n\t\tif o.DryRunStrategy == cmdutil.DryRunServer {\n\t\t\tcreateOptions.DryRun = []string{metav1.DryRunAll}\n\t\t}\n\t\tvar err error\n\t\tingress, err = o.Client.Ingresses(o.Namespace).Create(context.TODO(), ingress, createOptions)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create ingress: %v\", err)\n\t\t}\n\t}\n\treturn o.PrintObj(ingress)\n}","line":{"from":240,"to":264}} {"id":100031661,"name":"createIngress","signature":"func (o *CreateIngressOptions) createIngress() *networkingv1.Ingress","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_ingress.go","code":"func (o *CreateIngressOptions) createIngress() *networkingv1.Ingress {\n\tnamespace := \"\"\n\tif o.EnforceNamespace {\n\t\tnamespace = o.Namespace\n\t}\n\n\tannotations := o.buildAnnotations()\n\tspec := o.buildIngressSpec()\n\n\tingress := \u0026networkingv1.Ingress{\n\t\tTypeMeta: metav1.TypeMeta{APIVersion: networkingv1.SchemeGroupVersion.String(), Kind: \"Ingress\"},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: o.Name,\n\t\t\tNamespace: namespace,\n\t\t\tAnnotations: annotations,\n\t\t},\n\t\tSpec: spec,\n\t}\n\treturn ingress\n}","line":{"from":266,"to":285}} {"id":100031662,"name":"buildAnnotations","signature":"func (o *CreateIngressOptions) buildAnnotations() map[string]string","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_ingress.go","code":"func (o *CreateIngressOptions) buildAnnotations() map[string]string {\n\n\tvar annotations = make(map[string]string)\n\n\tfor _, annotation := range o.Annotations {\n\t\tan := strings.SplitN(annotation, \"=\", 2)\n\t\tannotations[an[0]] = an[1]\n\t}\n\treturn annotations\n}","line":{"from":287,"to":296}} {"id":100031663,"name":"buildIngressSpec","signature":"func (o *CreateIngressOptions) buildIngressSpec() networkingv1.IngressSpec","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_ingress.go","code":"// buildIngressSpec builds the .spec from the diverse arguments passed to kubectl\nfunc (o *CreateIngressOptions) buildIngressSpec() networkingv1.IngressSpec {\n\tvar ingressSpec networkingv1.IngressSpec\n\n\tif len(o.IngressClass) \u003e 0 {\n\t\tingressSpec.IngressClassName = \u0026o.IngressClass\n\t}\n\n\tif len(o.DefaultBackend) \u003e 0 {\n\t\tdefaultbackend := buildIngressBackendSvc(o.DefaultBackend)\n\t\tingressSpec.DefaultBackend = \u0026defaultbackend\n\t}\n\tingressSpec.TLS = o.buildTLSRules()\n\tingressSpec.Rules = o.buildIngressRules()\n\n\treturn ingressSpec\n}","line":{"from":298,"to":314}} {"id":100031664,"name":"buildTLSRules","signature":"func (o *CreateIngressOptions) buildTLSRules() []networkingv1.IngressTLS","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_ingress.go","code":"func (o *CreateIngressOptions) buildTLSRules() []networkingv1.IngressTLS {\n\thostAlreadyPresent := make(map[string]struct{})\n\n\tingressTLSs := []networkingv1.IngressTLS{}\n\tvar secret string\n\n\tfor _, rule := range o.Rules {\n\t\ttls := strings.Split(rule, \",\")\n\n\t\tif len(tls) == 2 {\n\t\t\tingressTLS := networkingv1.IngressTLS{}\n\t\t\thost := strings.SplitN(rule, \"/\", 2)[0]\n\t\t\tsecret = \"\"\n\t\t\tsecretName := strings.Split(tls[1], \"=\")\n\n\t\t\tif len(secretName) \u003e 1 {\n\t\t\t\tsecret = secretName[1]\n\t\t\t}\n\n\t\t\tidxSecret := getIndexSecret(secret, ingressTLSs)\n\t\t\t// We accept the same host into TLS secrets only once\n\t\t\tif _, ok := hostAlreadyPresent[host]; !ok {\n\t\t\t\tif idxSecret \u003e -1 {\n\t\t\t\t\tingressTLSs[idxSecret].Hosts = append(ingressTLSs[idxSecret].Hosts, host)\n\t\t\t\t\thostAlreadyPresent[host] = struct{}{}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif host != \"\" {\n\t\t\t\t\tingressTLS.Hosts = append(ingressTLS.Hosts, host)\n\t\t\t\t}\n\t\t\t\tif secret != \"\" {\n\t\t\t\t\tingressTLS.SecretName = secret\n\t\t\t\t}\n\t\t\t\tif len(ingressTLS.SecretName) \u003e 0 || len(ingressTLS.Hosts) \u003e 0 {\n\t\t\t\t\tingressTLSs = append(ingressTLSs, ingressTLS)\n\t\t\t\t}\n\t\t\t\thostAlreadyPresent[host] = struct{}{}\n\t\t\t}\n\t\t}\n\t}\n\treturn ingressTLSs\n}","line":{"from":316,"to":357}} {"id":100031665,"name":"buildIngressRules","signature":"func (o *CreateIngressOptions) buildIngressRules() []networkingv1.IngressRule","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_ingress.go","code":"// buildIngressRules builds the .spec.rules for an ingress object.\nfunc (o *CreateIngressOptions) buildIngressRules() []networkingv1.IngressRule {\n\tingressRules := []networkingv1.IngressRule{}\n\n\tfor _, rule := range o.Rules {\n\t\tremoveTLS := strings.Split(rule, \",\")[0]\n\t\thostSplit := strings.SplitN(removeTLS, \"/\", 2)\n\t\thost := hostSplit[0]\n\t\tingressPath := buildHTTPIngressPath(hostSplit[1])\n\t\tingressRule := networkingv1.IngressRule{}\n\n\t\tif host != \"\" {\n\t\t\tingressRule.Host = host\n\t\t}\n\n\t\tidxHost := getIndexHost(ingressRule.Host, ingressRules)\n\t\tif idxHost \u003e -1 {\n\t\t\tingressRules[idxHost].IngressRuleValue.HTTP.Paths = append(ingressRules[idxHost].IngressRuleValue.HTTP.Paths, ingressPath)\n\t\t\tcontinue\n\t\t}\n\n\t\tingressRule.IngressRuleValue = networkingv1.IngressRuleValue{\n\t\t\tHTTP: \u0026networkingv1.HTTPIngressRuleValue{\n\t\t\t\tPaths: []networkingv1.HTTPIngressPath{\n\t\t\t\t\tingressPath,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\tingressRules = append(ingressRules, ingressRule)\n\t}\n\treturn ingressRules\n}","line":{"from":359,"to":390}} {"id":100031666,"name":"buildHTTPIngressPath","signature":"func buildHTTPIngressPath(pathsvc string) networkingv1.HTTPIngressPath","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_ingress.go","code":"func buildHTTPIngressPath(pathsvc string) networkingv1.HTTPIngressPath {\n\tpathsvcsplit := strings.Split(pathsvc, \"=\")\n\tpath := \"/\" + pathsvcsplit[0]\n\tservice := pathsvcsplit[1]\n\n\tvar pathType networkingv1.PathType\n\tpathType = \"Exact\"\n\n\t// If * in the End, turn pathType=Prefix but remove the * from the end\n\tif path[len(path)-1:] == \"*\" {\n\t\tpathType = \"Prefix\"\n\t\tpath = path[0 : len(path)-1]\n\t}\n\n\thttpIngressPath := networkingv1.HTTPIngressPath{\n\t\tPath: path,\n\t\tPathType: \u0026pathType,\n\t\tBackend: buildIngressBackendSvc(service),\n\t}\n\treturn httpIngressPath\n}","line":{"from":392,"to":412}} {"id":100031667,"name":"buildIngressBackendSvc","signature":"func buildIngressBackendSvc(service string) networkingv1.IngressBackend","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_ingress.go","code":"func buildIngressBackendSvc(service string) networkingv1.IngressBackend {\n\tsvcname := strings.Split(service, \":\")[0]\n\tsvcport := strings.Split(service, \":\")[1]\n\n\tingressBackend := networkingv1.IngressBackend{\n\t\tService: \u0026networkingv1.IngressServiceBackend{\n\t\t\tName: svcname,\n\t\t\tPort: parseServiceBackendPort(svcport),\n\t\t},\n\t}\n\treturn ingressBackend\n}","line":{"from":414,"to":425}} {"id":100031668,"name":"parseServiceBackendPort","signature":"func parseServiceBackendPort(port string) networkingv1.ServiceBackendPort","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_ingress.go","code":"func parseServiceBackendPort(port string) networkingv1.ServiceBackendPort {\n\tvar backendPort networkingv1.ServiceBackendPort\n\tportIntOrStr := intstr.Parse(port)\n\n\tif portIntOrStr.Type == intstr.Int {\n\t\tbackendPort.Number = portIntOrStr.IntVal\n\t}\n\n\tif portIntOrStr.Type == intstr.String {\n\t\tbackendPort.Name = portIntOrStr.StrVal\n\t}\n\treturn backendPort\n}","line":{"from":427,"to":439}} {"id":100031669,"name":"getIndexHost","signature":"func getIndexHost(host string, rules []networkingv1.IngressRule) int","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_ingress.go","code":"func getIndexHost(host string, rules []networkingv1.IngressRule) int {\n\tfor index, v := range rules {\n\t\tif v.Host == host {\n\t\t\treturn index\n\t\t}\n\t}\n\treturn -1\n}","line":{"from":441,"to":448}} {"id":100031670,"name":"getIndexSecret","signature":"func getIndexSecret(secretname string, tls []networkingv1.IngressTLS) int","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_ingress.go","code":"func getIndexSecret(secretname string, tls []networkingv1.IngressTLS) int {\n\tfor index, v := range tls {\n\t\tif v.SecretName == secretname {\n\t\t\treturn index\n\t\t}\n\t}\n\treturn -1\n}","line":{"from":450,"to":457}} {"id":100031671,"name":"NewCreateJobOptions","signature":"func NewCreateJobOptions(ioStreams genericclioptions.IOStreams) *CreateJobOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_job.go","code":"// NewCreateJobOptions initializes and returns new CreateJobOptions instance\nfunc NewCreateJobOptions(ioStreams genericclioptions.IOStreams) *CreateJobOptions {\n\treturn \u0026CreateJobOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"created\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":77,"to":83}} {"id":100031672,"name":"NewCmdCreateJob","signature":"func NewCmdCreateJob(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_job.go","code":"// NewCmdCreateJob is a command to ease creating Jobs from CronJobs.\nfunc NewCmdCreateJob(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewCreateJobOptions(ioStreams)\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"job NAME --image=image [--from=cronjob/name] -- [COMMAND] [args...]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Create a job with the specified name\"),\n\t\tLong: jobLong,\n\t\tExample: jobExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmd.Flags().StringVar(\u0026o.Image, \"image\", o.Image, \"Image name to run.\")\n\tcmd.Flags().StringVar(\u0026o.From, \"from\", o.From, \"The name of the resource to create a Job from (only cronjob is supported).\")\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.FieldManager, \"kubectl-create\")\n\treturn cmd\n}","line":{"from":85,"to":110}} {"id":100031673,"name":"Complete","signature":"func (o *CreateJobOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_job.go","code":"// Complete completes all the required options\nfunc (o *CreateJobOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tname, err := NameFromCommandArgs(cmd, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\to.Name = name\n\tif len(args) \u003e 1 {\n\t\to.Command = args[1:]\n\t}\n\n\tclientConfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.Client, err = batchv1client.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.CreateAnnotation = cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag)\n\n\to.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.Builder = f.NewBuilder()\n\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.PrintObj = func(obj runtime.Object) error {\n\t\treturn printer.PrintObj(obj, o.Out)\n\t}\n\n\to.ValidationDirective, err = cmdutil.GetValidationDirective(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":112,"to":159}} {"id":100031674,"name":"Validate","signature":"func (o *CreateJobOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_job.go","code":"// Validate makes sure provided values and valid Job options\nfunc (o *CreateJobOptions) Validate() error {\n\tif (len(o.Image) == 0 \u0026\u0026 len(o.From) == 0) || (len(o.Image) != 0 \u0026\u0026 len(o.From) != 0) {\n\t\treturn fmt.Errorf(\"either --image or --from must be specified\")\n\t}\n\tif o.Command != nil \u0026\u0026 len(o.Command) != 0 \u0026\u0026 len(o.From) != 0 {\n\t\treturn fmt.Errorf(\"cannot specify --from and command\")\n\t}\n\treturn nil\n}","line":{"from":161,"to":170}} {"id":100031675,"name":"Run","signature":"func (o *CreateJobOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_job.go","code":"// Run performs the execution of 'create job' sub command\nfunc (o *CreateJobOptions) Run() error {\n\tvar job *batchv1.Job\n\tif len(o.Image) \u003e 0 {\n\t\tjob = o.createJob()\n\t} else {\n\t\tinfos, err := o.Builder.\n\t\t\tWithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).\n\t\t\tNamespaceParam(o.Namespace).DefaultNamespace().\n\t\t\tResourceTypeOrNameArgs(false, o.From).\n\t\t\tFlatten().\n\t\t\tLatest().\n\t\t\tDo().\n\t\t\tInfos()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(infos) != 1 {\n\t\t\treturn fmt.Errorf(\"from must be an existing cronjob\")\n\t\t}\n\n\t\tswitch obj := infos[0].Object.(type) {\n\t\tcase *batchv1.CronJob:\n\t\t\tjob = o.createJobFromCronJob(obj)\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"unknown object type %T\", obj)\n\t\t}\n\t}\n\n\tif err := util.CreateOrUpdateAnnotation(o.CreateAnnotation, job, scheme.DefaultJSONEncoder()); err != nil {\n\t\treturn err\n\t}\n\n\tif o.DryRunStrategy != cmdutil.DryRunClient {\n\t\tcreateOptions := metav1.CreateOptions{}\n\t\tif o.FieldManager != \"\" {\n\t\t\tcreateOptions.FieldManager = o.FieldManager\n\t\t}\n\t\tcreateOptions.FieldValidation = o.ValidationDirective\n\t\tif o.DryRunStrategy == cmdutil.DryRunServer {\n\t\t\tcreateOptions.DryRun = []string{metav1.DryRunAll}\n\t\t}\n\t\tvar err error\n\t\tjob, err = o.Client.Jobs(o.Namespace).Create(context.TODO(), job, createOptions)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create job: %v\", err)\n\t\t}\n\t}\n\n\treturn o.PrintObj(job)\n}","line":{"from":172,"to":222}} {"id":100031676,"name":"createJob","signature":"func (o *CreateJobOptions) createJob() *batchv1.Job","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_job.go","code":"func (o *CreateJobOptions) createJob() *batchv1.Job {\n\tjob := \u0026batchv1.Job{\n\t\t// this is ok because we know exactly how we want to be serialized\n\t\tTypeMeta: metav1.TypeMeta{APIVersion: batchv1.SchemeGroupVersion.String(), Kind: \"Job\"},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: o.Name,\n\t\t},\n\t\tSpec: batchv1.JobSpec{\n\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tContainers: []corev1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: o.Name,\n\t\t\t\t\t\t\tImage: o.Image,\n\t\t\t\t\t\t\tCommand: o.Command,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tRestartPolicy: corev1.RestartPolicyNever,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tif o.EnforceNamespace {\n\t\tjob.Namespace = o.Namespace\n\t}\n\treturn job\n}","line":{"from":224,"to":250}} {"id":100031677,"name":"createJobFromCronJob","signature":"func (o *CreateJobOptions) createJobFromCronJob(cronJob *batchv1.CronJob) *batchv1.Job","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_job.go","code":"func (o *CreateJobOptions) createJobFromCronJob(cronJob *batchv1.CronJob) *batchv1.Job {\n\tannotations := make(map[string]string)\n\tannotations[\"cronjob.kubernetes.io/instantiate\"] = \"manual\"\n\tfor k, v := range cronJob.Spec.JobTemplate.Annotations {\n\t\tannotations[k] = v\n\t}\n\n\tjob := \u0026batchv1.Job{\n\t\t// this is ok because we know exactly how we want to be serialized\n\t\tTypeMeta: metav1.TypeMeta{APIVersion: batchv1.SchemeGroupVersion.String(), Kind: \"Job\"},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: o.Name,\n\t\t\tAnnotations: annotations,\n\t\t\tLabels: cronJob.Spec.JobTemplate.Labels,\n\t\t\tOwnerReferences: []metav1.OwnerReference{\n\t\t\t\t{\n\t\t\t\t\tAPIVersion: batchv1.SchemeGroupVersion.String(),\n\t\t\t\t\tKind: \"CronJob\",\n\t\t\t\t\tName: cronJob.GetName(),\n\t\t\t\t\tUID: cronJob.GetUID(),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tSpec: cronJob.Spec.JobTemplate.Spec,\n\t}\n\tif o.EnforceNamespace {\n\t\tjob.Namespace = o.Namespace\n\t}\n\treturn job\n}","line":{"from":252,"to":281}} {"id":100031678,"name":"NewNamespaceOptions","signature":"func NewNamespaceOptions(ioStreams genericclioptions.IOStreams) *NamespaceOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_namespace.go","code":"// NewNamespaceOptions creates a new *NamespaceOptions with sane defaults\nfunc NewNamespaceOptions(ioStreams genericclioptions.IOStreams) *NamespaceOptions {\n\treturn \u0026NamespaceOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"created\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":66,"to":72}} {"id":100031679,"name":"NewCmdCreateNamespace","signature":"func NewCmdCreateNamespace(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_namespace.go","code":"// NewCmdCreateNamespace is a macro command to create a new namespace\nfunc NewCmdCreateNamespace(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\n\to := NewNamespaceOptions(ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"namespace NAME [--dry-run=server|client|none]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tAliases: []string{\"ns\"},\n\t\tShort: i18n.T(\"Create a namespace with the specified name\"),\n\t\tLong: namespaceLong,\n\t\tExample: namespaceExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.FieldManager, \"kubectl-create\")\n\n\treturn cmd\n}","line":{"from":74,"to":101}} {"id":100031680,"name":"Complete","signature":"func (o *NamespaceOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_namespace.go","code":"// Complete completes all the required options\nfunc (o *NamespaceOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tname, err := NameFromCommandArgs(cmd, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trestConfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.Client, err = coreclient.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Name = name\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\to.CreateAnnotation = cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag)\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.PrintObj = func(obj runtime.Object) error {\n\t\treturn printer.PrintObj(obj, o.Out)\n\t}\n\n\to.ValidationDirective, err = cmdutil.GetValidationDirective(cmd)\n\treturn err\n}","line":{"from":103,"to":136}} {"id":100031681,"name":"Run","signature":"func (o *NamespaceOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_namespace.go","code":"// Run calls the CreateSubcommandOptions.Run in NamespaceOpts instance\nfunc (o *NamespaceOptions) Run() error {\n\tnamespace := o.createNamespace()\n\tif err := util.CreateOrUpdateAnnotation(o.CreateAnnotation, namespace, scheme.DefaultJSONEncoder()); err != nil {\n\t\treturn err\n\t}\n\n\tif o.DryRunStrategy != cmdutil.DryRunClient {\n\t\tcreateOptions := metav1.CreateOptions{}\n\t\tif o.FieldManager != \"\" {\n\t\t\tcreateOptions.FieldManager = o.FieldManager\n\t\t}\n\t\tcreateOptions.FieldValidation = o.ValidationDirective\n\t\tif o.DryRunStrategy == cmdutil.DryRunServer {\n\t\t\tcreateOptions.DryRun = []string{metav1.DryRunAll}\n\t\t}\n\t\tvar err error\n\t\tnamespace, err = o.Client.Namespaces().Create(context.TODO(), namespace, createOptions)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn o.PrintObj(namespace)\n}","line":{"from":138,"to":161}} {"id":100031682,"name":"createNamespace","signature":"func (o *NamespaceOptions) createNamespace() *corev1.Namespace","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_namespace.go","code":"// createNamespace outputs a namespace object using the configured fields\nfunc (o *NamespaceOptions) createNamespace() *corev1.Namespace {\n\tnamespace := \u0026corev1.Namespace{\n\t\tTypeMeta: metav1.TypeMeta{APIVersion: corev1.SchemeGroupVersion.String(), Kind: \"Namespace\"},\n\t\tObjectMeta: metav1.ObjectMeta{Name: o.Name},\n\t}\n\treturn namespace\n}","line":{"from":163,"to":170}} {"id":100031683,"name":"Validate","signature":"func (o *NamespaceOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_namespace.go","code":"// Validate validates required fields are set to support structured generation\nfunc (o *NamespaceOptions) Validate() error {\n\tif len(o.Name) == 0 {\n\t\treturn fmt.Errorf(\"name must be specified\")\n\t}\n\treturn nil\n}","line":{"from":172,"to":178}} {"id":100031684,"name":"NewPodDisruptionBudgetOpts","signature":"func NewPodDisruptionBudgetOpts(ioStreams genericclioptions.IOStreams) *PodDisruptionBudgetOpts","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_pdb.go","code":"// NewPodDisruptionBudgetOpts creates a new *PodDisruptionBudgetOpts with sane defaults\nfunc NewPodDisruptionBudgetOpts(ioStreams genericclioptions.IOStreams) *PodDisruptionBudgetOpts {\n\treturn \u0026PodDisruptionBudgetOpts{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"created\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":78,"to":84}} {"id":100031685,"name":"NewCmdCreatePodDisruptionBudget","signature":"func NewCmdCreatePodDisruptionBudget(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_pdb.go","code":"// NewCmdCreatePodDisruptionBudget is a macro command to create a new pod disruption budget.\nfunc NewCmdCreatePodDisruptionBudget(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewPodDisruptionBudgetOpts(ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"poddisruptionbudget NAME --selector=SELECTOR --min-available=N [--dry-run=server|client|none]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tAliases: []string{\"pdb\"},\n\t\tShort: i18n.T(\"Create a pod disruption budget with the specified name\"),\n\t\tLong: pdbLong,\n\t\tExample: pdbExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmdutil.AddDryRunFlag(cmd)\n\n\tcmd.Flags().StringVar(\u0026o.MinAvailable, \"min-available\", o.MinAvailable, i18n.T(\"The minimum number or percentage of available pods this budget requires.\"))\n\tcmd.Flags().StringVar(\u0026o.MaxUnavailable, \"max-unavailable\", o.MaxUnavailable, i18n.T(\"The maximum number or percentage of unavailable pods this budget requires.\"))\n\tcmd.Flags().StringVar(\u0026o.Selector, \"selector\", o.Selector, i18n.T(\"A label selector to use for this budget. Only equality-based selector requirements are supported.\"))\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.FieldManager, \"kubectl-create\")\n\treturn cmd\n}","line":{"from":86,"to":115}} {"id":100031686,"name":"Complete","signature":"func (o *PodDisruptionBudgetOpts) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_pdb.go","code":"// Complete completes all the required options\nfunc (o *PodDisruptionBudgetOpts) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\to.Name, err = NameFromCommandArgs(cmd, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trestConfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.Client, err = policyv1client.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.CreateAnnotation = cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag)\n\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.PrintObj = func(obj runtime.Object) error {\n\t\treturn printer.PrintObj(obj, o.Out)\n\t}\n\n\to.ValidationDirective, err = cmdutil.GetValidationDirective(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":117,"to":163}} {"id":100031687,"name":"Validate","signature":"func (o *PodDisruptionBudgetOpts) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_pdb.go","code":"// Validate checks to the PodDisruptionBudgetOpts to see if there is sufficient information run the command\nfunc (o *PodDisruptionBudgetOpts) Validate() error {\n\tif len(o.Name) == 0 {\n\t\treturn fmt.Errorf(\"name must be specified\")\n\t}\n\n\tif len(o.Selector) == 0 {\n\t\treturn fmt.Errorf(\"a selector must be specified\")\n\t}\n\n\tif len(o.MaxUnavailable) == 0 \u0026\u0026 len(o.MinAvailable) == 0 {\n\t\treturn fmt.Errorf(\"one of min-available or max-unavailable must be specified\")\n\t}\n\n\tif len(o.MaxUnavailable) \u003e 0 \u0026\u0026 len(o.MinAvailable) \u003e 0 {\n\t\treturn fmt.Errorf(\"min-available and max-unavailable cannot be both specified\")\n\t}\n\n\t// The following regex matches the following values:\n\t// 10, 20, 30%, 50% (number and percentage)\n\t// but not 10Gb, 20Mb\n\tre := regexp.MustCompile(`^[0-9]+%?$`)\n\n\tswitch {\n\tcase len(o.MinAvailable) \u003e 0 \u0026\u0026 !re.MatchString(o.MinAvailable):\n\t\treturn fmt.Errorf(\"invalid format specified for min-available\")\n\tcase len(o.MaxUnavailable) \u003e 0 \u0026\u0026 !re.MatchString(o.MaxUnavailable):\n\t\treturn fmt.Errorf(\"invalid format specified for max-unavailable\")\n\t}\n\n\treturn nil\n}","line":{"from":165,"to":196}} {"id":100031688,"name":"Run","signature":"func (o *PodDisruptionBudgetOpts) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_pdb.go","code":"// Run calls the CreateSubcommandOptions.Run in PodDisruptionBudgetOpts instance\nfunc (o *PodDisruptionBudgetOpts) Run() error {\n\tpodDisruptionBudget, err := o.createPodDisruptionBudgets()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := util.CreateOrUpdateAnnotation(o.CreateAnnotation, podDisruptionBudget, scheme.DefaultJSONEncoder()); err != nil {\n\t\treturn err\n\t}\n\n\tif o.DryRunStrategy != cmdutil.DryRunClient {\n\t\tcreateOptions := metav1.CreateOptions{}\n\t\tif o.FieldManager != \"\" {\n\t\t\tcreateOptions.FieldManager = o.FieldManager\n\t\t}\n\t\tcreateOptions.FieldValidation = o.ValidationDirective\n\t\tif o.DryRunStrategy == cmdutil.DryRunServer {\n\t\t\tcreateOptions.DryRun = []string{metav1.DryRunAll}\n\t\t}\n\t\tpodDisruptionBudget, err = o.Client.PodDisruptionBudgets(o.Namespace).Create(context.TODO(), podDisruptionBudget, createOptions)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create poddisruptionbudgets: %v\", err)\n\t\t}\n\t}\n\treturn o.PrintObj(podDisruptionBudget)\n}","line":{"from":198,"to":224}} {"id":100031689,"name":"createPodDisruptionBudgets","signature":"func (o *PodDisruptionBudgetOpts) createPodDisruptionBudgets() (*policyv1.PodDisruptionBudget, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_pdb.go","code":"func (o *PodDisruptionBudgetOpts) createPodDisruptionBudgets() (*policyv1.PodDisruptionBudget, error) {\n\tnamespace := \"\"\n\tif o.EnforceNamespace {\n\t\tnamespace = o.Namespace\n\t}\n\n\tpodDisruptionBudget := \u0026policyv1.PodDisruptionBudget{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: policyv1.SchemeGroupVersion.String(),\n\t\t\tKind: \"PodDisruptionBudget\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: o.Name,\n\t\t\tNamespace: namespace,\n\t\t},\n\t}\n\n\tselector, err := metav1.ParseToLabelSelector(o.Selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpodDisruptionBudget.Spec.Selector = selector\n\n\tswitch {\n\tcase len(o.MinAvailable) \u003e 0:\n\t\tminAvailable := intstr.Parse(o.MinAvailable)\n\t\tpodDisruptionBudget.Spec.MinAvailable = \u0026minAvailable\n\tcase len(o.MaxUnavailable) \u003e 0:\n\t\tmaxUnavailable := intstr.Parse(o.MaxUnavailable)\n\t\tpodDisruptionBudget.Spec.MaxUnavailable = \u0026maxUnavailable\n\t}\n\n\treturn podDisruptionBudget, nil\n}","line":{"from":226,"to":260}} {"id":100031690,"name":"NewPriorityClassOptions","signature":"func NewPriorityClassOptions(ioStreams genericclioptions.IOStreams) *PriorityClassOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_priorityclass.go","code":"// NewPriorityClassOptions returns an initialized PriorityClassOptions instance\nfunc NewPriorityClassOptions(ioStreams genericclioptions.IOStreams) *PriorityClassOptions {\n\treturn \u0026PriorityClassOptions{\n\t\tValue: 0,\n\t\tPreemptionPolicy: \"PreemptLowerPriority\",\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"created\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":73,"to":81}} {"id":100031691,"name":"NewCmdCreatePriorityClass","signature":"func NewCmdCreatePriorityClass(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_priorityclass.go","code":"// NewCmdCreatePriorityClass is a macro command to create a new priorityClass.\nfunc NewCmdCreatePriorityClass(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewPriorityClassOptions(ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"priorityclass NAME --value=VALUE --global-default=BOOL [--dry-run=server|client|none]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tAliases: []string{\"pc\"},\n\t\tShort: i18n.T(\"Create a priority class with the specified name\"),\n\t\tLong: pcLong,\n\t\tExample: pcExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmd.Flags().Int32Var(\u0026o.Value, \"value\", o.Value, i18n.T(\"the value of this priority class.\"))\n\tcmd.Flags().BoolVar(\u0026o.GlobalDefault, \"global-default\", o.GlobalDefault, i18n.T(\"global-default specifies whether this PriorityClass should be considered as the default priority.\"))\n\tcmd.Flags().StringVar(\u0026o.Description, \"description\", o.Description, i18n.T(\"description is an arbitrary string that usually provides guidelines on when this priority class should be used.\"))\n\tcmd.Flags().StringVar(\u0026o.PreemptionPolicy, \"preemption-policy\", o.PreemptionPolicy, i18n.T(\"preemption-policy is the policy for preempting pods with lower priority.\"))\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.FieldManager, \"kubectl-create\")\n\treturn cmd\n}","line":{"from":83,"to":111}} {"id":100031692,"name":"Complete","signature":"func (o *PriorityClassOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_priorityclass.go","code":"// Complete completes all the required options\nfunc (o *PriorityClassOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\to.Name, err = NameFromCommandArgs(cmd, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trestConfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.Client, err = schedulingv1client.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.CreateAnnotation = cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag)\n\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.PrintObj = func(obj runtime.Object) error {\n\t\treturn printer.PrintObj(obj, o.Out)\n\t}\n\n\to.ValidationDirective, err = cmdutil.GetValidationDirective(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":113,"to":152}} {"id":100031693,"name":"Run","signature":"func (o *PriorityClassOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_priorityclass.go","code":"// Run calls the CreateSubcommandOptions.Run in the PriorityClassOptions instance\nfunc (o *PriorityClassOptions) Run() error {\n\tpriorityClass, err := o.createPriorityClass()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := util.CreateOrUpdateAnnotation(o.CreateAnnotation, priorityClass, scheme.DefaultJSONEncoder()); err != nil {\n\t\treturn err\n\t}\n\n\tif o.DryRunStrategy != cmdutil.DryRunClient {\n\t\tcreateOptions := metav1.CreateOptions{}\n\t\tif o.FieldManager != \"\" {\n\t\t\tcreateOptions.FieldManager = o.FieldManager\n\t\t}\n\t\tcreateOptions.FieldValidation = o.ValidationDirective\n\t\tif o.DryRunStrategy == cmdutil.DryRunServer {\n\t\t\tcreateOptions.DryRun = []string{metav1.DryRunAll}\n\t\t}\n\t\tvar err error\n\t\tpriorityClass, err = o.Client.PriorityClasses().Create(context.TODO(), priorityClass, createOptions)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create priorityclass: %v\", err)\n\t\t}\n\t}\n\n\treturn o.PrintObj(priorityClass)\n}","line":{"from":154,"to":182}} {"id":100031694,"name":"createPriorityClass","signature":"func (o *PriorityClassOptions) createPriorityClass() (*schedulingv1.PriorityClass, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_priorityclass.go","code":"func (o *PriorityClassOptions) createPriorityClass() (*schedulingv1.PriorityClass, error) {\n\tpreemptionPolicy := corev1.PreemptionPolicy(o.PreemptionPolicy)\n\treturn \u0026schedulingv1.PriorityClass{\n\t\t// this is ok because we know exactly how we want to be serialized\n\t\tTypeMeta: metav1.TypeMeta{APIVersion: schedulingv1.SchemeGroupVersion.String(), Kind: \"PriorityClass\"},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: o.Name,\n\t\t},\n\t\tValue: o.Value,\n\t\tGlobalDefault: o.GlobalDefault,\n\t\tDescription: o.Description,\n\t\tPreemptionPolicy: \u0026preemptionPolicy,\n\t}, nil\n}","line":{"from":184,"to":197}} {"id":100031695,"name":"NewQuotaOpts","signature":"func NewQuotaOpts(ioStreams genericclioptions.IOStreams) *QuotaOpts","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_quota.go","code":"// NewQuotaOpts creates a new *QuotaOpts with sane defaults\nfunc NewQuotaOpts(ioStreams genericclioptions.IOStreams) *QuotaOpts {\n\treturn \u0026QuotaOpts{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"created\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":74,"to":80}} {"id":100031696,"name":"NewCmdCreateQuota","signature":"func NewCmdCreateQuota(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_quota.go","code":"// NewCmdCreateQuota is a macro command to create a new quota\nfunc NewCmdCreateQuota(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewQuotaOpts(ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"quota NAME [--hard=key1=value1,key2=value2] [--scopes=Scope1,Scope2] [--dry-run=server|client|none]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tAliases: []string{\"resourcequota\"},\n\t\tShort: i18n.T(\"Create a quota with the specified name\"),\n\t\tLong: quotaLong,\n\t\tExample: quotaExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmd.Flags().StringVar(\u0026o.Hard, \"hard\", o.Hard, i18n.T(\"A comma-delimited set of resource=quantity pairs that define a hard limit.\"))\n\tcmd.Flags().StringVar(\u0026o.Scopes, \"scopes\", o.Scopes, i18n.T(\"A comma-delimited set of quota scopes that must all match each object tracked by the quota.\"))\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.FieldManager, \"kubectl-create\")\n\treturn cmd\n}","line":{"from":82,"to":109}} {"id":100031697,"name":"Complete","signature":"func (o *QuotaOpts) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_quota.go","code":"// Complete completes all the required options\nfunc (o *QuotaOpts) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\to.Name, err = NameFromCommandArgs(cmd, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trestConfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.Client, err = coreclient.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.CreateAnnotation = cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag)\n\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.PrintObj = func(obj runtime.Object) error {\n\t\treturn printer.PrintObj(obj, o.Out)\n\t}\n\n\to.ValidationDirective, err = cmdutil.GetValidationDirective(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":111,"to":157}} {"id":100031698,"name":"Validate","signature":"func (o *QuotaOpts) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_quota.go","code":"// Validate checks to the QuotaOpts to see if there is sufficient information run the command.\nfunc (o *QuotaOpts) Validate() error {\n\tif len(o.Name) == 0 {\n\t\treturn fmt.Errorf(\"name must be specified\")\n\t}\n\treturn nil\n}","line":{"from":159,"to":165}} {"id":100031699,"name":"Run","signature":"func (o *QuotaOpts) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_quota.go","code":"// Run does the work\nfunc (o *QuotaOpts) Run() error {\n\tresourceQuota, err := o.createQuota()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := util.CreateOrUpdateAnnotation(o.CreateAnnotation, resourceQuota, scheme.DefaultJSONEncoder()); err != nil {\n\t\treturn err\n\t}\n\n\tif o.DryRunStrategy != cmdutil.DryRunClient {\n\t\tcreateOptions := metav1.CreateOptions{}\n\t\tif o.FieldManager != \"\" {\n\t\t\tcreateOptions.FieldManager = o.FieldManager\n\t\t}\n\t\tcreateOptions.FieldValidation = o.ValidationDirective\n\t\tif o.DryRunStrategy == cmdutil.DryRunServer {\n\t\t\tcreateOptions.DryRun = []string{metav1.DryRunAll}\n\t\t}\n\t\tresourceQuota, err = o.Client.ResourceQuotas(o.Namespace).Create(context.TODO(), resourceQuota, createOptions)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create quota: %v\", err)\n\t\t}\n\t}\n\treturn o.PrintObj(resourceQuota)\n}","line":{"from":167,"to":193}} {"id":100031700,"name":"createQuota","signature":"func (o *QuotaOpts) createQuota() (*corev1.ResourceQuota, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_quota.go","code":"func (o *QuotaOpts) createQuota() (*corev1.ResourceQuota, error) {\n\tnamespace := \"\"\n\tif o.EnforceNamespace {\n\t\tnamespace = o.Namespace\n\t}\n\tresourceQuota := \u0026corev1.ResourceQuota{\n\t\tTypeMeta: metav1.TypeMeta{APIVersion: corev1.SchemeGroupVersion.String(), Kind: \"ResourceQuota\"},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: o.Name,\n\t\t\tNamespace: namespace,\n\t\t},\n\t}\n\n\tresourceList, err := populateResourceListV1(o.Hard)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tscopes, err := parseScopes(o.Scopes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresourceQuota.Spec.Hard = resourceList\n\tresourceQuota.Spec.Scopes = scopes\n\n\treturn resourceQuota, nil\n}","line":{"from":195,"to":222}} {"id":100031701,"name":"populateResourceListV1","signature":"func populateResourceListV1(spec string) (corev1.ResourceList, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_quota.go","code":"// populateResourceListV1 takes strings of form \u003cresourceName1\u003e=\u003cvalue1\u003e,\u003cresourceName1\u003e=\u003cvalue2\u003e\n// and returns ResourceList.\nfunc populateResourceListV1(spec string) (corev1.ResourceList, error) {\n\t// empty input gets a nil response to preserve generator test expected behaviors\n\tif spec == \"\" {\n\t\treturn nil, nil\n\t}\n\n\tresult := corev1.ResourceList{}\n\tresourceStatements := strings.Split(spec, \",\")\n\tfor _, resourceStatement := range resourceStatements {\n\t\tparts := strings.Split(resourceStatement, \"=\")\n\t\tif len(parts) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"Invalid argument syntax %v, expected \u003cresource\u003e=\u003cvalue\u003e\", resourceStatement)\n\t\t}\n\t\tresourceName := corev1.ResourceName(parts[0])\n\t\tresourceQuantity, err := resourceapi.ParseQuantity(parts[1])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult[resourceName] = resourceQuantity\n\t}\n\treturn result, nil\n}","line":{"from":224,"to":247}} {"id":100031702,"name":"parseScopes","signature":"func parseScopes(spec string) ([]corev1.ResourceQuotaScope, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_quota.go","code":"func parseScopes(spec string) ([]corev1.ResourceQuotaScope, error) {\n\t// empty input gets a nil response to preserve test expected behaviors\n\tif spec == \"\" {\n\t\treturn nil, nil\n\t}\n\n\tscopes := strings.Split(spec, \",\")\n\tresult := make([]corev1.ResourceQuotaScope, 0, len(scopes))\n\tfor _, scope := range scopes {\n\t\t// intentionally do not verify the scope against the valid scope list. This is done by the apiserver anyway.\n\n\t\tif scope == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"invalid resource quota scope \\\"\\\"\")\n\t\t}\n\n\t\tresult = append(result, corev1.ResourceQuotaScope(scope))\n\t}\n\treturn result, nil\n}","line":{"from":249,"to":267}} {"id":100031703,"name":"AddSpecialVerb","signature":"func AddSpecialVerb(verb string, gr schema.GroupResource)","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_role.go","code":"// AddSpecialVerb allows the addition of items to the `specialVerbs` map for non-k8s native resources.\nfunc AddSpecialVerb(verb string, gr schema.GroupResource) {\n\tresources, ok := specialVerbs[verb]\n\tif !ok {\n\t\tresources = make([]schema.GroupResource, 1)\n\t}\n\tresources = append(resources, gr)\n\tspecialVerbs[verb] = resources\n}","line":{"from":114,"to":122}} {"id":100031704,"name":"NewCreateRoleOptions","signature":"func NewCreateRoleOptions(ioStreams genericclioptions.IOStreams) *CreateRoleOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_role.go","code":"// NewCreateRoleOptions returns an initialized CreateRoleOptions instance\nfunc NewCreateRoleOptions(ioStreams genericclioptions.IOStreams) *CreateRoleOptions {\n\treturn \u0026CreateRoleOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"created\").WithTypeSetter(scheme.Scheme),\n\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":154,"to":161}} {"id":100031705,"name":"NewCmdCreateRole","signature":"func NewCmdCreateRole(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_role.go","code":"// NewCmdCreateRole returnns an initialized Command instance for 'create role' sub command\nfunc NewCmdCreateRole(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewCreateRoleOptions(ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"role NAME --verb=verb --resource=resource.group/subresource [--resource-name=resourcename] [--dry-run=server|client|none]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Create a role with single rule\"),\n\t\tLong: roleLong,\n\t\tExample: roleExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.RunCreateRole())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmd.Flags().StringSliceVar(\u0026o.Verbs, \"verb\", o.Verbs, \"Verb that applies to the resources contained in the rule\")\n\tcmd.Flags().StringSlice(\"resource\", []string{}, \"Resource that the rule applies to\")\n\tcmd.Flags().StringArrayVar(\u0026o.ResourceNames, \"resource-name\", o.ResourceNames, \"Resource in the white list that the rule applies to, repeat this flag for multiple items\")\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.FieldManager, \"kubectl-create\")\n\treturn cmd\n}","line":{"from":163,"to":190}} {"id":100031706,"name":"Complete","signature":"func (o *CreateRoleOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_role.go","code":"// Complete completes all the required options\nfunc (o *CreateRoleOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tname, err := NameFromCommandArgs(cmd, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\to.Name = name\n\n\t// Remove duplicate verbs.\n\tverbs := []string{}\n\tfor _, v := range o.Verbs {\n\t\t// VerbAll respresents all kinds of verbs.\n\t\tif v == \"*\" {\n\t\t\tverbs = []string{\"*\"}\n\t\t\tbreak\n\t\t}\n\t\tif !arrayContains(verbs, v) {\n\t\t\tverbs = append(verbs, v)\n\t\t}\n\t}\n\to.Verbs = verbs\n\n\t// Support resource.group pattern. If no API Group specified, use \"\" as core API Group.\n\t// e.g. --resource=pods,deployments.extensions\n\tresources := cmdutil.GetFlagStringSlice(cmd, \"resource\")\n\tfor _, r := range resources {\n\t\tsections := strings.SplitN(r, \"/\", 2)\n\n\t\tresource := \u0026ResourceOptions{}\n\t\tif len(sections) == 2 {\n\t\t\tresource.SubResource = sections[1]\n\t\t}\n\n\t\tparts := strings.SplitN(sections[0], \".\", 2)\n\t\tif len(parts) == 2 {\n\t\t\tresource.Group = parts[1]\n\t\t}\n\t\tresource.Resource = parts[0]\n\n\t\tif resource.Resource == \"*\" \u0026\u0026 len(parts) == 1 \u0026\u0026 len(sections) == 1 {\n\t\t\to.Resources = []ResourceOptions{*resource}\n\t\t\tbreak\n\t\t}\n\n\t\to.Resources = append(o.Resources, *resource)\n\t}\n\n\t// Remove duplicate resource names.\n\tresourceNames := []string{}\n\tfor _, n := range o.ResourceNames {\n\t\tif !arrayContains(resourceNames, n) {\n\t\t\tresourceNames = append(resourceNames, n)\n\t\t}\n\t}\n\to.ResourceNames = resourceNames\n\n\t// Complete other options for Run.\n\to.Mapper, err = f.ToRESTMapper()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\to.OutputFormat = cmdutil.GetFlagString(cmd, \"output\")\n\to.CreateAnnotation = cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag)\n\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.PrintObj = func(obj runtime.Object) error {\n\t\treturn printer.PrintObj(obj, o.Out)\n\t}\n\n\to.ValidationDirective, err = cmdutil.GetValidationDirective(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclientset, err := f.KubernetesClientSet()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.Client = clientset.RbacV1()\n\n\treturn nil\n}","line":{"from":192,"to":287}} {"id":100031707,"name":"Validate","signature":"func (o *CreateRoleOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_role.go","code":"// Validate makes sure there is no discrepency in provided option values\nfunc (o *CreateRoleOptions) Validate() error {\n\tif o.Name == \"\" {\n\t\treturn fmt.Errorf(\"name must be specified\")\n\t}\n\n\t// validate verbs.\n\tif len(o.Verbs) == 0 {\n\t\treturn fmt.Errorf(\"at least one verb must be specified\")\n\t}\n\n\tfor _, v := range o.Verbs {\n\t\tif !arrayContains(validResourceVerbs, v) {\n\t\t\tfmt.Fprintf(o.ErrOut, \"Warning: '%s' is not a standard resource verb\\n\", v)\n\t\t}\n\t}\n\n\t// validate resources.\n\tif len(o.Resources) == 0 {\n\t\treturn fmt.Errorf(\"at least one resource must be specified\")\n\t}\n\n\treturn o.validateResource()\n}","line":{"from":289,"to":312}} {"id":100031708,"name":"validateResource","signature":"func (o *CreateRoleOptions) validateResource() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_role.go","code":"func (o *CreateRoleOptions) validateResource() error {\n\tfor _, r := range o.Resources {\n\t\tif len(r.Resource) == 0 {\n\t\t\treturn fmt.Errorf(\"resource must be specified if apiGroup/subresource specified\")\n\t\t}\n\t\tif r.Resource == \"*\" {\n\t\t\treturn nil\n\t\t}\n\n\t\tresource := schema.GroupVersionResource{Resource: r.Resource, Group: r.Group}\n\t\tgroupVersionResource, err := o.Mapper.ResourceFor(schema.GroupVersionResource{Resource: r.Resource, Group: r.Group})\n\t\tif err == nil {\n\t\t\tresource = groupVersionResource\n\t\t}\n\n\t\tfor _, v := range o.Verbs {\n\t\t\tif groupResources, ok := specialVerbs[v]; ok {\n\t\t\t\tmatch := false\n\t\t\t\tfor _, extra := range groupResources {\n\t\t\t\t\tif resource.Resource == extra.Resource \u0026\u0026 resource.Group == extra.Group {\n\t\t\t\t\t\tmatch = true\n\t\t\t\t\t\terr = nil\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !match {\n\t\t\t\t\treturn fmt.Errorf(\"can not perform '%s' on '%s' in group '%s'\", v, resource.Resource, resource.Group)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":314,"to":350}} {"id":100031709,"name":"RunCreateRole","signature":"func (o *CreateRoleOptions) RunCreateRole() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_role.go","code":"// RunCreateRole performs the execution of 'create role' sub command\nfunc (o *CreateRoleOptions) RunCreateRole() error {\n\trole := \u0026rbacv1.Role{\n\t\t// this is ok because we know exactly how we want to be serialized\n\t\tTypeMeta: metav1.TypeMeta{APIVersion: rbacv1.SchemeGroupVersion.String(), Kind: \"Role\"},\n\t}\n\trole.Name = o.Name\n\trules, err := generateResourcePolicyRules(o.Mapper, o.Verbs, o.Resources, o.ResourceNames, []string{})\n\tif err != nil {\n\t\treturn err\n\t}\n\trole.Rules = rules\n\tif o.EnforceNamespace {\n\t\trole.Namespace = o.Namespace\n\t}\n\n\tif err := util.CreateOrUpdateAnnotation(o.CreateAnnotation, role, scheme.DefaultJSONEncoder()); err != nil {\n\t\treturn err\n\t}\n\n\t// Create role.\n\tif o.DryRunStrategy != cmdutil.DryRunClient {\n\t\tcreateOptions := metav1.CreateOptions{}\n\t\tif o.FieldManager != \"\" {\n\t\t\tcreateOptions.FieldManager = o.FieldManager\n\t\t}\n\t\tcreateOptions.FieldValidation = o.ValidationDirective\n\t\tif o.DryRunStrategy == cmdutil.DryRunServer {\n\t\t\tcreateOptions.DryRun = []string{metav1.DryRunAll}\n\t\t}\n\t\trole, err = o.Client.Roles(o.Namespace).Create(context.TODO(), role, createOptions)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn o.PrintObj(role)\n}","line":{"from":352,"to":389}} {"id":100031710,"name":"arrayContains","signature":"func arrayContains(s []string, e string) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_role.go","code":"func arrayContains(s []string, e string) bool {\n\tfor _, a := range s {\n\t\tif a == e {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":391,"to":398}} {"id":100031711,"name":"generateResourcePolicyRules","signature":"func generateResourcePolicyRules(mapper meta.RESTMapper, verbs []string, resources []ResourceOptions, resourceNames []string, nonResourceURLs []string) ([]rbacv1.PolicyRule, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_role.go","code":"func generateResourcePolicyRules(mapper meta.RESTMapper, verbs []string, resources []ResourceOptions, resourceNames []string, nonResourceURLs []string) ([]rbacv1.PolicyRule, error) {\n\t// groupResourceMapping is a apigroup-resource map. The key of this map is api group, while the value\n\t// is a string array of resources under this api group.\n\t// E.g. groupResourceMapping = {\"extensions\": [\"replicasets\", \"deployments\"], \"batch\":[\"jobs\"]}\n\tgroupResourceMapping := map[string][]string{}\n\n\t// This loop does the following work:\n\t// 1. Constructs groupResourceMapping based on input resources.\n\t// 2. Prevents pointing to non-existent resources.\n\t// 3. Transfers resource short name to long name. E.g. rs.extensions is transferred to replicasets.extensions\n\tfor _, r := range resources {\n\t\tresource := schema.GroupVersionResource{Resource: r.Resource, Group: r.Group}\n\t\tgroupVersionResource, err := mapper.ResourceFor(schema.GroupVersionResource{Resource: r.Resource, Group: r.Group})\n\t\tif err == nil {\n\t\t\tresource = groupVersionResource\n\t\t}\n\n\t\tif len(r.SubResource) \u003e 0 {\n\t\t\tresource.Resource = resource.Resource + \"/\" + r.SubResource\n\t\t}\n\t\tif !arrayContains(groupResourceMapping[resource.Group], resource.Resource) {\n\t\t\tgroupResourceMapping[resource.Group] = append(groupResourceMapping[resource.Group], resource.Resource)\n\t\t}\n\t}\n\n\t// Create separate rule for each of the api group.\n\trules := []rbacv1.PolicyRule{}\n\tfor _, g := range sets.StringKeySet(groupResourceMapping).List() {\n\t\trule := rbacv1.PolicyRule{}\n\t\trule.Verbs = verbs\n\t\trule.Resources = groupResourceMapping[g]\n\t\trule.APIGroups = []string{g}\n\t\trule.ResourceNames = resourceNames\n\t\trules = append(rules, rule)\n\t}\n\n\tif len(nonResourceURLs) \u003e 0 {\n\t\trule := rbacv1.PolicyRule{}\n\t\trule.Verbs = verbs\n\t\trule.NonResourceURLs = nonResourceURLs\n\t\trules = append(rules, rule)\n\t}\n\n\treturn rules, nil\n}","line":{"from":400,"to":444}} {"id":100031712,"name":"NewRoleBindingOptions","signature":"func NewRoleBindingOptions(ioStreams genericclioptions.IOStreams) *RoleBindingOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_rolebinding.go","code":"// NewRoleBindingOptions creates a new *RoleBindingOptions with sane defaults\nfunc NewRoleBindingOptions(ioStreams genericclioptions.IOStreams) *RoleBindingOptions {\n\treturn \u0026RoleBindingOptions{\n\t\tUsers: []string{},\n\t\tGroups: []string{},\n\t\tServiceAccounts: []string{},\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"created\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":73,"to":82}} {"id":100031713,"name":"NewCmdCreateRoleBinding","signature":"func NewCmdCreateRoleBinding(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_rolebinding.go","code":"// NewCmdCreateRoleBinding returns an initialized Command instance for 'create rolebinding' sub command\nfunc NewCmdCreateRoleBinding(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewRoleBindingOptions(ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"rolebinding NAME --clusterrole=NAME|--role=NAME [--user=username] [--group=groupname] [--serviceaccount=namespace:serviceaccountname] [--dry-run=server|client|none]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Create a role binding for a particular role or cluster role\"),\n\t\tLong: roleBindingLong,\n\t\tExample: roleBindingExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmd.Flags().StringVar(\u0026o.ClusterRole, \"clusterrole\", \"\", i18n.T(\"ClusterRole this RoleBinding should reference\"))\n\tcmd.Flags().StringVar(\u0026o.Role, \"role\", \"\", i18n.T(\"Role this RoleBinding should reference\"))\n\tcmd.Flags().StringArrayVar(\u0026o.Users, \"user\", o.Users, \"Usernames to bind to the role. The flag can be repeated to add multiple users.\")\n\tcmd.Flags().StringArrayVar(\u0026o.Groups, \"group\", o.Groups, \"Groups to bind to the role. The flag can be repeated to add multiple groups.\")\n\tcmd.Flags().StringArrayVar(\u0026o.ServiceAccounts, \"serviceaccount\", o.ServiceAccounts, \"Service accounts to bind to the role, in the format \u003cnamespace\u003e:\u003cname\u003e. The flag can be repeated to add multiple service accounts.\")\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.FieldManager, \"kubectl-create\")\n\treturn cmd\n}","line":{"from":84,"to":113}} {"id":100031714,"name":"Complete","signature":"func (o *RoleBindingOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_rolebinding.go","code":"// Complete completes all the required options\nfunc (o *RoleBindingOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\to.Name, err = NameFromCommandArgs(cmd, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\tclientConfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.Client, err = rbacclientv1.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.CreateAnnotation = cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag)\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.PrintObj = func(obj runtime.Object) error {\n\t\treturn printer.PrintObj(obj, o.Out)\n\t}\n\n\to.ValidationDirective, err = cmdutil.GetValidationDirective(cmd)\n\treturn err\n}","line":{"from":115,"to":152}} {"id":100031715,"name":"Validate","signature":"func (o *RoleBindingOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_rolebinding.go","code":"// Validate validates required fields are set\nfunc (o *RoleBindingOptions) Validate() error {\n\tif len(o.Name) == 0 {\n\t\treturn fmt.Errorf(\"name must be specified\")\n\t}\n\tif (len(o.ClusterRole) == 0) == (len(o.Role) == 0) {\n\t\treturn fmt.Errorf(\"exactly one of clusterrole or role must be specified\")\n\t}\n\treturn nil\n}","line":{"from":154,"to":163}} {"id":100031716,"name":"Run","signature":"func (o *RoleBindingOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_rolebinding.go","code":"// Run performs the execution of 'create rolebinding' sub command\nfunc (o *RoleBindingOptions) Run() error {\n\troleBinding, err := o.createRoleBinding()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := util.CreateOrUpdateAnnotation(o.CreateAnnotation, roleBinding, scheme.DefaultJSONEncoder()); err != nil {\n\t\treturn err\n\t}\n\n\tif o.DryRunStrategy != cmdutil.DryRunClient {\n\t\tcreateOptions := metav1.CreateOptions{}\n\t\tif o.FieldManager != \"\" {\n\t\t\tcreateOptions.FieldManager = o.FieldManager\n\t\t}\n\t\tcreateOptions.FieldValidation = o.ValidationDirective\n\t\tif o.DryRunStrategy == cmdutil.DryRunServer {\n\t\t\tcreateOptions.DryRun = []string{metav1.DryRunAll}\n\t\t}\n\t\troleBinding, err = o.Client.RoleBindings(o.Namespace).Create(context.TODO(), roleBinding, createOptions)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create rolebinding: %v\", err)\n\t\t}\n\t}\n\treturn o.PrintObj(roleBinding)\n}","line":{"from":165,"to":190}} {"id":100031717,"name":"createRoleBinding","signature":"func (o *RoleBindingOptions) createRoleBinding() (*rbacv1.RoleBinding, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_rolebinding.go","code":"func (o *RoleBindingOptions) createRoleBinding() (*rbacv1.RoleBinding, error) {\n\tnamespace := \"\"\n\tif o.EnforceNamespace {\n\t\tnamespace = o.Namespace\n\t}\n\n\troleBinding := \u0026rbacv1.RoleBinding{\n\t\tTypeMeta: metav1.TypeMeta{APIVersion: rbacv1.SchemeGroupVersion.String(), Kind: \"RoleBinding\"},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: o.Name,\n\t\t\tNamespace: namespace,\n\t\t},\n\t}\n\n\tswitch {\n\tcase len(o.Role) \u003e 0:\n\t\troleBinding.RoleRef = rbacv1.RoleRef{\n\t\t\tAPIGroup: rbacv1.GroupName,\n\t\t\tKind: \"Role\",\n\t\t\tName: o.Role,\n\t\t}\n\tcase len(o.ClusterRole) \u003e 0:\n\t\troleBinding.RoleRef = rbacv1.RoleRef{\n\t\t\tAPIGroup: rbacv1.GroupName,\n\t\t\tKind: \"ClusterRole\",\n\t\t\tName: o.ClusterRole,\n\t\t}\n\t}\n\n\tfor _, user := range o.Users {\n\t\troleBinding.Subjects = append(roleBinding.Subjects, rbacv1.Subject{\n\t\t\tKind: rbacv1.UserKind,\n\t\t\tAPIGroup: rbacv1.GroupName,\n\t\t\tName: user,\n\t\t})\n\t}\n\n\tfor _, group := range o.Groups {\n\t\troleBinding.Subjects = append(roleBinding.Subjects, rbacv1.Subject{\n\t\t\tKind: rbacv1.GroupKind,\n\t\t\tAPIGroup: rbacv1.GroupName,\n\t\t\tName: group,\n\t\t})\n\t}\n\n\tfor _, sa := range o.ServiceAccounts {\n\t\ttokens := strings.Split(sa, \":\")\n\t\tif len(tokens) != 2 || tokens[0] == \"\" || tokens[1] == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"serviceaccount must be \u003cnamespace\u003e:\u003cname\u003e\")\n\t\t}\n\t\troleBinding.Subjects = append(roleBinding.Subjects, rbacv1.Subject{\n\t\t\tKind: rbacv1.ServiceAccountKind,\n\t\t\tAPIGroup: \"\",\n\t\t\tNamespace: tokens[0],\n\t\t\tName: tokens[1],\n\t\t})\n\t}\n\treturn roleBinding, nil\n}","line":{"from":192,"to":250}} {"id":100031718,"name":"NewCmdCreateSecret","signature":"func NewCmdCreateSecret(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret.go","code":"// NewCmdCreateSecret groups subcommands to create various types of secrets.\n// This is the entry point of create_secret.go which will be called by create.go\nfunc NewCmdCreateSecret(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"secret\",\n\t\tShort: i18n.T(\"Create a secret using specified subcommand\"),\n\t\tLong: i18n.T(\"Create a secret using specified subcommand.\"),\n\t\tRun: cmdutil.DefaultSubCommandRun(ioStreams.ErrOut),\n\t}\n\tcmd.AddCommand(NewCmdCreateSecretDockerRegistry(f, ioStreams))\n\tcmd.AddCommand(NewCmdCreateSecretTLS(f, ioStreams))\n\tcmd.AddCommand(NewCmdCreateSecretGeneric(f, ioStreams))\n\n\treturn cmd\n}","line":{"from":42,"to":56}} {"id":100031719,"name":"NewSecretOptions","signature":"func NewSecretOptions(ioStreams genericclioptions.IOStreams) *CreateSecretOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret.go","code":"// NewSecretOptions creates a new *CreateSecretOptions with default value\nfunc NewSecretOptions(ioStreams genericclioptions.IOStreams) *CreateSecretOptions {\n\treturn \u0026CreateSecretOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"created\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":120,"to":126}} {"id":100031720,"name":"NewCmdCreateSecretGeneric","signature":"func NewCmdCreateSecretGeneric(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret.go","code":"// NewCmdCreateSecretGeneric is a command to create generic secrets from files, directories, or literal values\nfunc NewCmdCreateSecretGeneric(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewSecretOptions(ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"generic NAME [--type=string] [--from-file=[key=]source] [--from-literal=key1=value1] [--dry-run=server|client|none]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Create a secret from a local file, directory, or literal value\"),\n\t\tLong: secretLong,\n\t\tExample: secretExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmdutil.AddDryRunFlag(cmd)\n\n\tcmd.Flags().StringSliceVar(\u0026o.FileSources, \"from-file\", o.FileSources, \"Key files can be specified using their file path, in which case a default name will be given to them, or optionally with a name and file path, in which case the given name will be used. Specifying a directory will iterate each named file in the directory that is a valid secret key.\")\n\tcmd.Flags().StringArrayVar(\u0026o.LiteralSources, \"from-literal\", o.LiteralSources, \"Specify a key and literal value to insert in secret (i.e. mykey=somevalue)\")\n\tcmd.Flags().StringSliceVar(\u0026o.EnvFileSources, \"from-env-file\", o.EnvFileSources, \"Specify the path to a file to read lines of key=val pairs to create a secret.\")\n\tcmd.Flags().StringVar(\u0026o.Type, \"type\", o.Type, i18n.T(\"The type of secret to create\"))\n\tcmd.Flags().BoolVar(\u0026o.AppendHash, \"append-hash\", o.AppendHash, \"Append a hash of the secret to its name.\")\n\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.FieldManager, \"kubectl-create\")\n\n\treturn cmd\n}","line":{"from":128,"to":159}} {"id":100031721,"name":"Complete","signature":"func (o *CreateSecretOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret.go","code":"// Complete loads data from the command line environment\nfunc (o *CreateSecretOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\to.Name, err = NameFromCommandArgs(cmd, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trestConfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Client, err = corev1client.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.CreateAnnotation = cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag)\n\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.PrintObj = func(obj runtime.Object) error {\n\t\treturn printer.PrintObj(obj, o.Out)\n\t}\n\n\to.ValidationDirective, err = cmdutil.GetValidationDirective(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":161,"to":207}} {"id":100031722,"name":"Validate","signature":"func (o *CreateSecretOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret.go","code":"// Validate checks if CreateSecretOptions has sufficient value to run\nfunc (o *CreateSecretOptions) Validate() error {\n\tif len(o.Name) == 0 {\n\t\treturn fmt.Errorf(\"name must be specified\")\n\t}\n\tif len(o.EnvFileSources) \u003e 0 \u0026\u0026 (len(o.FileSources) \u003e 0 || len(o.LiteralSources) \u003e 0) {\n\t\treturn fmt.Errorf(\"from-env-file cannot be combined with from-file or from-literal\")\n\t}\n\treturn nil\n}","line":{"from":209,"to":218}} {"id":100031723,"name":"Run","signature":"func (o *CreateSecretOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret.go","code":"// Run calls createSecret which will create secret based on CreateSecretOptions\n// and makes an API call to the server\nfunc (o *CreateSecretOptions) Run() error {\n\tsecret, err := o.createSecret()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = util.CreateOrUpdateAnnotation(o.CreateAnnotation, secret, scheme.DefaultJSONEncoder())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif o.DryRunStrategy != cmdutil.DryRunClient {\n\t\tcreateOptions := metav1.CreateOptions{}\n\t\tif o.FieldManager != \"\" {\n\t\t\tcreateOptions.FieldManager = o.FieldManager\n\t\t}\n\t\tcreateOptions.FieldValidation = o.ValidationDirective\n\t\tif o.DryRunStrategy == cmdutil.DryRunServer {\n\t\t\tcreateOptions.DryRun = []string{metav1.DryRunAll}\n\t\t}\n\t\tsecret, err = o.Client.Secrets(o.Namespace).Create(context.TODO(), secret, createOptions)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create secret %v\", err)\n\t\t}\n\t}\n\n\treturn o.PrintObj(secret)\n}","line":{"from":220,"to":247}} {"id":100031724,"name":"createSecret","signature":"func (o *CreateSecretOptions) createSecret() (*corev1.Secret, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret.go","code":"// createSecret fills in key value pair from the information given in\n// CreateSecretOptions into *corev1.Secret\nfunc (o *CreateSecretOptions) createSecret() (*corev1.Secret, error) {\n\tnamespace := \"\"\n\tif o.EnforceNamespace {\n\t\tnamespace = o.Namespace\n\t}\n\tsecret := newSecretObj(o.Name, namespace, corev1.SecretType(o.Type))\n\tif len(o.LiteralSources) \u003e 0 {\n\t\tif err := handleSecretFromLiteralSources(secret, o.LiteralSources); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif len(o.FileSources) \u003e 0 {\n\t\tif err := handleSecretFromFileSources(secret, o.FileSources); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif len(o.EnvFileSources) \u003e 0 {\n\t\tif err := handleSecretFromEnvFileSources(secret, o.EnvFileSources); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif o.AppendHash {\n\t\thash, err := hash.SecretHash(secret)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsecret.Name = fmt.Sprintf(\"%s-%s\", secret.Name, hash)\n\t}\n\n\treturn secret, nil\n}","line":{"from":249,"to":281}} {"id":100031725,"name":"newSecretObj","signature":"func newSecretObj(name, namespace string, secretType corev1.SecretType) *corev1.Secret","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret.go","code":"// newSecretObj will create a new Secret Object given name, namespace and secretType\nfunc newSecretObj(name, namespace string, secretType corev1.SecretType) *corev1.Secret {\n\treturn \u0026corev1.Secret{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: corev1.SchemeGroupVersion.String(),\n\t\t\tKind: \"Secret\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t},\n\t\tType: secretType,\n\t\tData: map[string][]byte{},\n\t}\n}","line":{"from":283,"to":297}} {"id":100031726,"name":"handleSecretFromLiteralSources","signature":"func handleSecretFromLiteralSources(secret *corev1.Secret, literalSources []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret.go","code":"// handleSecretFromLiteralSources adds the specified literal source\n// information into the provided secret\nfunc handleSecretFromLiteralSources(secret *corev1.Secret, literalSources []string) error {\n\tfor _, literalSource := range literalSources {\n\t\tkeyName, value, err := util.ParseLiteralSource(literalSource)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err = addKeyFromLiteralToSecret(secret, keyName, []byte(value)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":299,"to":313}} {"id":100031727,"name":"handleSecretFromFileSources","signature":"func handleSecretFromFileSources(secret *corev1.Secret, fileSources []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret.go","code":"// handleSecretFromFileSources adds the specified file source information into the provided secret\nfunc handleSecretFromFileSources(secret *corev1.Secret, fileSources []string) error {\n\tfor _, fileSource := range fileSources {\n\t\tkeyName, filePath, err := util.ParseFileSource(fileSource)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfileInfo, err := os.Stat(filePath)\n\t\tif err != nil {\n\t\t\tswitch err := err.(type) {\n\t\t\tcase *os.PathError:\n\t\t\t\treturn fmt.Errorf(\"error reading %s: %v\", filePath, err.Err)\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"error reading %s: %v\", filePath, err)\n\t\t\t}\n\t\t}\n\t\t// if the filePath is a directory\n\t\tif fileInfo.IsDir() {\n\t\t\tif strings.Contains(fileSource, \"=\") {\n\t\t\t\treturn fmt.Errorf(\"cannot give a key name for a directory path\")\n\t\t\t}\n\t\t\tfileList, err := os.ReadDir(filePath)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error listing files in %s: %v\", filePath, err)\n\t\t\t}\n\t\t\tfor _, item := range fileList {\n\t\t\t\titemPath := path.Join(filePath, item.Name())\n\t\t\t\tif item.Type().IsRegular() {\n\t\t\t\t\tkeyName = item.Name()\n\t\t\t\t\tif err := addKeyFromFileToSecret(secret, keyName, itemPath); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// if the filepath is a file\n\t\t} else {\n\t\t\tif err := addKeyFromFileToSecret(secret, keyName, filePath); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn nil\n}","line":{"from":315,"to":359}} {"id":100031728,"name":"handleSecretFromEnvFileSources","signature":"func handleSecretFromEnvFileSources(secret *corev1.Secret, envFileSources []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret.go","code":"// handleSecretFromEnvFileSources adds the specified env files source information\n// into the provided secret\nfunc handleSecretFromEnvFileSources(secret *corev1.Secret, envFileSources []string) error {\n\tfor _, envFileSource := range envFileSources {\n\t\tinfo, err := os.Stat(envFileSource)\n\t\tif err != nil {\n\t\t\tswitch err := err.(type) {\n\t\t\tcase *os.PathError:\n\t\t\t\treturn fmt.Errorf(\"error reading %s: %v\", envFileSource, err.Err)\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"error reading %s: %v\", envFileSource, err)\n\t\t\t}\n\t\t}\n\t\tif info.IsDir() {\n\t\t\treturn fmt.Errorf(\"env secret file cannot be a directory\")\n\t\t}\n\t\terr = cmdutil.AddFromEnvFile(envFileSource, func(key, value string) error {\n\t\t\treturn addKeyFromLiteralToSecret(secret, key, []byte(value))\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":361,"to":386}} {"id":100031729,"name":"addKeyFromFileToSecret","signature":"func addKeyFromFileToSecret(secret *corev1.Secret, keyName, filePath string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret.go","code":"// addKeyFromFileToSecret adds a key with the given name to a Secret, populating\n// the value with the content of the given file path, or returns an error.\nfunc addKeyFromFileToSecret(secret *corev1.Secret, keyName, filePath string) error {\n\tdata, err := os.ReadFile(filePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn addKeyFromLiteralToSecret(secret, keyName, data)\n}","line":{"from":388,"to":396}} {"id":100031730,"name":"addKeyFromLiteralToSecret","signature":"func addKeyFromLiteralToSecret(secret *corev1.Secret, keyName string, data []byte) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret.go","code":"// addKeyFromLiteralToSecret adds the given key and data to the given secret,\n// returning an error if the key is not valid or if the key already exists.\nfunc addKeyFromLiteralToSecret(secret *corev1.Secret, keyName string, data []byte) error {\n\tif errs := validation.IsConfigMapKey(keyName); len(errs) != 0 {\n\t\treturn fmt.Errorf(\"%q is not valid key name for a Secret %s\", keyName, strings.Join(errs, \";\"))\n\t}\n\tif _, entryExists := secret.Data[keyName]; entryExists {\n\t\treturn fmt.Errorf(\"cannot add key %s, another key by that name already exists\", keyName)\n\t}\n\tsecret.Data[keyName] = data\n\n\treturn nil\n}","line":{"from":398,"to":410}} {"id":100031731,"name":"NewSecretDockerRegistryOptions","signature":"func NewSecretDockerRegistryOptions(ioStreams genericclioptions.IOStreams) *CreateSecretDockerRegistryOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret_docker.go","code":"// NewSecretDockerRegistryOptions creates a new *CreateSecretDockerRegistryOptions with default value\nfunc NewSecretDockerRegistryOptions(ioStreams genericclioptions.IOStreams) *CreateSecretDockerRegistryOptions {\n\treturn \u0026CreateSecretDockerRegistryOptions{\n\t\tServer: \"https://index.docker.io/v1/\",\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"created\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":117,"to":124}} {"id":100031732,"name":"NewCmdCreateSecretDockerRegistry","signature":"func NewCmdCreateSecretDockerRegistry(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret_docker.go","code":"// NewCmdCreateSecretDockerRegistry is a macro command for creating secrets to work with Docker registries\nfunc NewCmdCreateSecretDockerRegistry(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewSecretDockerRegistryOptions(ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"docker-registry NAME --docker-username=user --docker-password=password --docker-email=email [--docker-server=string] [--from-file=[key=]source] [--dry-run=server|client|none]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Create a secret for use with a Docker registry\"),\n\t\tLong: secretForDockerRegistryLong,\n\t\tExample: secretForDockerRegistryExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmdutil.AddDryRunFlag(cmd)\n\n\tcmd.Flags().StringVar(\u0026o.Username, \"docker-username\", o.Username, i18n.T(\"Username for Docker registry authentication\"))\n\tcmd.Flags().StringVar(\u0026o.Password, \"docker-password\", o.Password, i18n.T(\"Password for Docker registry authentication\"))\n\tcmd.Flags().StringVar(\u0026o.Email, \"docker-email\", o.Email, i18n.T(\"Email for Docker registry\"))\n\tcmd.Flags().StringVar(\u0026o.Server, \"docker-server\", o.Server, i18n.T(\"Server location for Docker registry\"))\n\tcmd.Flags().BoolVar(\u0026o.AppendHash, \"append-hash\", o.AppendHash, \"Append a hash of the secret to its name.\")\n\tcmd.Flags().StringSliceVar(\u0026o.FileSources, \"from-file\", o.FileSources, \"Key files can be specified using their file path, in which case a default name will be given to them, or optionally with a name and file path, in which case the given name will be used. Specifying a directory will iterate each named file in the directory that is a valid secret key.\")\n\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.FieldManager, \"kubectl-create\")\n\n\treturn cmd\n}","line":{"from":126,"to":159}} {"id":100031733,"name":"Complete","signature":"func (o *CreateSecretDockerRegistryOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret_docker.go","code":"// Complete loads data from the command line environment\nfunc (o *CreateSecretDockerRegistryOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\to.Name, err = NameFromCommandArgs(cmd, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trestConfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Client, err = corev1client.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.CreateAnnotation = cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag)\n\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.PrintObj = func(obj runtime.Object) error {\n\t\treturn printer.PrintObj(obj, o.Out)\n\t}\n\n\to.ValidationDirective, err = cmdutil.GetValidationDirective(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":161,"to":207}} {"id":100031734,"name":"Validate","signature":"func (o *CreateSecretDockerRegistryOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret_docker.go","code":"// Validate checks if CreateSecretDockerRegistryOptions has sufficient value to run\nfunc (o *CreateSecretDockerRegistryOptions) Validate() error {\n\tif len(o.Name) == 0 {\n\t\treturn fmt.Errorf(\"name must be specified\")\n\t}\n\tif len(o.FileSources) == 0 \u0026\u0026 (len(o.Username) == 0 || len(o.Password) == 0 || len(o.Server) == 0) {\n\t\treturn fmt.Errorf(\"either --from-file or the combination of --docker-username, --docker-password and --docker-server is required\")\n\t}\n\treturn nil\n}","line":{"from":209,"to":218}} {"id":100031735,"name":"Run","signature":"func (o *CreateSecretDockerRegistryOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret_docker.go","code":"// Run calls createSecretDockerRegistry which will create secretDockerRegistry based on CreateSecretDockerRegistryOptions\n// and makes an API call to the server\nfunc (o *CreateSecretDockerRegistryOptions) Run() error {\n\tsecretDockerRegistry, err := o.createSecretDockerRegistry()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = util.CreateOrUpdateAnnotation(o.CreateAnnotation, secretDockerRegistry, scheme.DefaultJSONEncoder())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif o.DryRunStrategy != cmdutil.DryRunClient {\n\t\tcreateOptions := metav1.CreateOptions{}\n\t\tif o.FieldManager != \"\" {\n\t\t\tcreateOptions.FieldManager = o.FieldManager\n\t\t}\n\t\tcreateOptions.FieldValidation = o.ValidationDirective\n\t\tif o.DryRunStrategy == cmdutil.DryRunServer {\n\t\t\tcreateOptions.DryRun = []string{metav1.DryRunAll}\n\t\t}\n\t\tsecretDockerRegistry, err = o.Client.Secrets(o.Namespace).Create(context.TODO(), secretDockerRegistry, createOptions)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create secret %v\", err)\n\t\t}\n\t}\n\n\treturn o.PrintObj(secretDockerRegistry)\n}","line":{"from":220,"to":247}} {"id":100031736,"name":"createSecretDockerRegistry","signature":"func (o *CreateSecretDockerRegistryOptions) createSecretDockerRegistry() (*corev1.Secret, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret_docker.go","code":"// createSecretDockerRegistry fills in key value pair from the information given in\n// CreateSecretDockerRegistryOptions into *corev1.Secret\nfunc (o *CreateSecretDockerRegistryOptions) createSecretDockerRegistry() (*corev1.Secret, error) {\n\tnamespace := \"\"\n\tif o.EnforceNamespace {\n\t\tnamespace = o.Namespace\n\t}\n\tsecretDockerRegistry := newSecretObj(o.Name, namespace, corev1.SecretTypeDockerConfigJson)\n\tif len(o.FileSources) \u003e 0 {\n\t\tif err := handleSecretFromFileSources(secretDockerRegistry, o.FileSources); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tdockerConfigJSONContent, err := handleDockerCfgJSONContent(o.Username, o.Password, o.Email, o.Server)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsecretDockerRegistry.Data[corev1.DockerConfigJsonKey] = dockerConfigJSONContent\n\t}\n\tif o.AppendHash {\n\t\thash, err := hash.SecretHash(secretDockerRegistry)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsecretDockerRegistry.Name = fmt.Sprintf(\"%s-%s\", secretDockerRegistry.Name, hash)\n\t}\n\treturn secretDockerRegistry, nil\n}","line":{"from":249,"to":276}} {"id":100031737,"name":"handleDockerCfgJSONContent","signature":"func handleDockerCfgJSONContent(username, password, email, server string) ([]byte, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret_docker.go","code":"// handleDockerCfgJSONContent serializes a ~/.docker/config.json file\nfunc handleDockerCfgJSONContent(username, password, email, server string) ([]byte, error) {\n\tdockerConfigAuth := DockerConfigEntry{\n\t\tUsername: username,\n\t\tPassword: password,\n\t\tEmail: email,\n\t\tAuth: encodeDockerConfigFieldAuth(username, password),\n\t}\n\tdockerConfigJSON := DockerConfigJSON{\n\t\tAuths: map[string]DockerConfigEntry{server: dockerConfigAuth},\n\t}\n\n\treturn json.Marshal(dockerConfigJSON)\n}","line":{"from":278,"to":291}} {"id":100031738,"name":"encodeDockerConfigFieldAuth","signature":"func encodeDockerConfigFieldAuth(username, password string) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret_docker.go","code":"// encodeDockerConfigFieldAuth returns base64 encoding of the username and password string\nfunc encodeDockerConfigFieldAuth(username, password string) string {\n\tfieldValue := username + \":\" + password\n\treturn base64.StdEncoding.EncodeToString([]byte(fieldValue))\n}","line":{"from":293,"to":297}} {"id":100031739,"name":"NewSecretTLSOptions","signature":"func NewSecretTLSOptions(ioStrems genericclioptions.IOStreams) *CreateSecretTLSOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret_tls.go","code":"// NewSecretTLSOptions creates a new *CreateSecretTLSOptions with default value\nfunc NewSecretTLSOptions(ioStrems genericclioptions.IOStreams) *CreateSecretTLSOptions {\n\treturn \u0026CreateSecretTLSOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"created\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: ioStrems,\n\t}\n}","line":{"from":78,"to":84}} {"id":100031740,"name":"NewCmdCreateSecretTLS","signature":"func NewCmdCreateSecretTLS(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret_tls.go","code":"// NewCmdCreateSecretTLS is a macro command for creating secrets to work with TLS client or server\nfunc NewCmdCreateSecretTLS(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewSecretTLSOptions(ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"tls NAME --cert=path/to/cert/file --key=path/to/key/file [--dry-run=server|client|none]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Create a TLS secret\"),\n\t\tLong: secretForTLSLong,\n\t\tExample: secretForTLSExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmdutil.AddDryRunFlag(cmd)\n\n\tcmd.Flags().StringVar(\u0026o.Cert, \"cert\", o.Cert, i18n.T(\"Path to PEM encoded public key certificate.\"))\n\tcmd.Flags().StringVar(\u0026o.Key, \"key\", o.Key, i18n.T(\"Path to private key associated with given certificate.\"))\n\tcmd.Flags().BoolVar(\u0026o.AppendHash, \"append-hash\", o.AppendHash, \"Append a hash of the secret to its name.\")\n\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.FieldManager, \"kubectl-create\")\n\n\treturn cmd\n}","line":{"from":86,"to":116}} {"id":100031741,"name":"Complete","signature":"func (o *CreateSecretTLSOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret_tls.go","code":"// Complete loads data from the command line environment\nfunc (o *CreateSecretTLSOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\to.Name, err = NameFromCommandArgs(cmd, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trestConfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Client, err = corev1client.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.CreateAnnotation = cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag)\n\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.PrintObj = func(obj runtime.Object) error {\n\t\treturn printer.PrintObj(obj, o.Out)\n\t}\n\n\to.ValidationDirective, err = cmdutil.GetValidationDirective(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":118,"to":164}} {"id":100031742,"name":"Validate","signature":"func (o *CreateSecretTLSOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret_tls.go","code":"// Validate checks if CreateSecretTLSOptions hass sufficient value to run\nfunc (o *CreateSecretTLSOptions) Validate() error {\n\t// TODO: This is not strictly necessary. We can generate a self signed cert\n\t// if no key/cert is given. The only requirement is that we either get both\n\t// or none. See test/e2e/ingress_utils for self signed cert generation.\n\tif len(o.Key) == 0 || len(o.Cert) == 0 {\n\t\treturn fmt.Errorf(\"key and cert must be specified\")\n\t}\n\treturn nil\n}","line":{"from":166,"to":175}} {"id":100031743,"name":"Run","signature":"func (o *CreateSecretTLSOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret_tls.go","code":"// Run calls createSecretTLS which will create secretTLS based on CreateSecretTLSOptions\n// and makes an API call to the server\nfunc (o *CreateSecretTLSOptions) Run() error {\n\tsecretTLS, err := o.createSecretTLS()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = util.CreateOrUpdateAnnotation(o.CreateAnnotation, secretTLS, scheme.DefaultJSONEncoder())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif o.DryRunStrategy != cmdutil.DryRunClient {\n\t\tcreateOptions := metav1.CreateOptions{}\n\t\tif o.FieldManager != \"\" {\n\t\t\tcreateOptions.FieldManager = o.FieldManager\n\t\t}\n\t\tcreateOptions.FieldValidation = o.ValidationDirective\n\t\tif o.DryRunStrategy == cmdutil.DryRunServer {\n\t\t\tcreateOptions.DryRun = []string{metav1.DryRunAll}\n\t\t}\n\t\tsecretTLS, err = o.Client.Secrets(o.Namespace).Create(context.TODO(), secretTLS, createOptions)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create secret %v\", err)\n\t\t}\n\t}\n\treturn o.PrintObj(secretTLS)\n}","line":{"from":177,"to":203}} {"id":100031744,"name":"createSecretTLS","signature":"func (o *CreateSecretTLSOptions) createSecretTLS() (*corev1.Secret, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret_tls.go","code":"// createSecretTLS fills in key value pair from the information given in\n// CreateSecretTLSOptions into *corev1.Secret\nfunc (o *CreateSecretTLSOptions) createSecretTLS() (*corev1.Secret, error) {\n\tnamespace := \"\"\n\tif o.EnforceNamespace {\n\t\tnamespace = o.Namespace\n\t}\n\ttlsCert, err := readFile(o.Cert)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttlsKey, err := readFile(o.Key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif _, err := tls.X509KeyPair(tlsCert, tlsKey); err != nil {\n\t\treturn nil, err\n\t}\n\t// TODO: Add more validation.\n\t// 1. If the certificate contains intermediates, it is a valid chain.\n\t// 2. Format etc.\n\n\tsecretTLS := newSecretObj(o.Name, namespace, corev1.SecretTypeTLS)\n\tsecretTLS.Data[corev1.TLSCertKey] = []byte(tlsCert)\n\tsecretTLS.Data[corev1.TLSPrivateKeyKey] = []byte(tlsKey)\n\tif o.AppendHash {\n\t\thash, err := hash.SecretHash(secretTLS)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsecretTLS.Name = fmt.Sprintf(\"%s-%s\", secretTLS.Name, hash)\n\t}\n\n\treturn secretTLS, nil\n}","line":{"from":205,"to":239}} {"id":100031745,"name":"readFile","signature":"func readFile(file string) ([]byte, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_secret_tls.go","code":"// readFile just reads a file into a byte array.\nfunc readFile(file string) ([]byte, error) {\n\tb, err := os.ReadFile(file)\n\tif err != nil {\n\t\treturn []byte{}, fmt.Errorf(\"Cannot read file %v, %v\", file, err)\n\t}\n\treturn b, nil\n}","line":{"from":241,"to":248}} {"id":100031746,"name":"NewCmdCreateService","signature":"func NewCmdCreateService(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_service.go","code":"// NewCmdCreateService is a macro command to create a new service\nfunc NewCmdCreateService(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"service\",\n\t\tAliases: []string{\"svc\"},\n\t\tShort: i18n.T(\"Create a service using a specified subcommand\"),\n\t\tLong: i18n.T(\"Create a service using a specified subcommand.\"),\n\t\tRun: cmdutil.DefaultSubCommandRun(ioStreams.ErrOut),\n\t}\n\tcmd.AddCommand(NewCmdCreateServiceClusterIP(f, ioStreams))\n\tcmd.AddCommand(NewCmdCreateServiceNodePort(f, ioStreams))\n\tcmd.AddCommand(NewCmdCreateServiceLoadBalancer(f, ioStreams))\n\tcmd.AddCommand(NewCmdCreateServiceExternalName(f, ioStreams))\n\n\treturn cmd\n}","line":{"from":42,"to":57}} {"id":100031747,"name":"NewServiceOptions","signature":"func NewServiceOptions(ioStreams genericclioptions.IOStreams, serviceType corev1.ServiceType) *ServiceOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_service.go","code":"// NewServiceOptions creates a ServiceOptions struct\nfunc NewServiceOptions(ioStreams genericclioptions.IOStreams, serviceType corev1.ServiceType) *ServiceOptions {\n\treturn \u0026ServiceOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"created\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: ioStreams,\n\t\tType: serviceType,\n\t}\n}","line":{"from":82,"to":89}} {"id":100031748,"name":"Complete","signature":"func (o *ServiceOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_service.go","code":"// Complete completes all the required options\nfunc (o *ServiceOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tname, err := NameFromCommandArgs(cmd, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\to.Name = name\n\n\tclientConfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.Client, err = corev1client.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.PrintObj = func(obj runtime.Object) error {\n\t\treturn printer.PrintObj(obj, o.Out)\n\t}\n\n\to.ValidationDirective, err = cmdutil.GetValidationDirective(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":91,"to":134}} {"id":100031749,"name":"Validate","signature":"func (o *ServiceOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_service.go","code":"// Validate if the options are valid\nfunc (o *ServiceOptions) Validate() error {\n\tif o.ClusterIP == corev1.ClusterIPNone \u0026\u0026 o.Type != corev1.ServiceTypeClusterIP {\n\t\treturn fmt.Errorf(\"ClusterIP=None can only be used with ClusterIP service type\")\n\t}\n\tif o.ClusterIP != corev1.ClusterIPNone \u0026\u0026 len(o.TCP) == 0 \u0026\u0026 o.Type != corev1.ServiceTypeExternalName {\n\t\treturn fmt.Errorf(\"at least one tcp port specifier must be provided\")\n\t}\n\tif o.Type == corev1.ServiceTypeExternalName {\n\t\tif errs := validation.IsDNS1123Subdomain(o.ExternalName); len(errs) != 0 {\n\t\t\treturn fmt.Errorf(\"invalid service external name %s\", o.ExternalName)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":136,"to":150}} {"id":100031750,"name":"createService","signature":"func (o *ServiceOptions) createService() (*corev1.Service, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_service.go","code":"func (o *ServiceOptions) createService() (*corev1.Service, error) {\n\tports := []corev1.ServicePort{}\n\tfor _, tcpString := range o.TCP {\n\t\tport, targetPort, err := parsePorts(tcpString)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tportName := strings.Replace(tcpString, \":\", \"-\", -1)\n\t\tports = append(ports, corev1.ServicePort{\n\t\t\tName: portName,\n\t\t\tPort: port,\n\t\t\tTargetPort: targetPort,\n\t\t\tProtocol: corev1.Protocol(\"TCP\"),\n\t\t\tNodePort: int32(o.NodePort),\n\t\t})\n\t}\n\n\t// setup default label and selector\n\tlabels := map[string]string{}\n\tlabels[\"app\"] = o.Name\n\tselector := map[string]string{}\n\tselector[\"app\"] = o.Name\n\n\tnamespace := \"\"\n\tif o.EnforceNamespace {\n\t\tnamespace = o.Namespace\n\t}\n\n\tservice := corev1.Service{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: o.Name,\n\t\t\tLabels: labels,\n\t\t\tNamespace: namespace,\n\t\t},\n\t\tSpec: corev1.ServiceSpec{\n\t\t\tType: o.Type,\n\t\t\tSelector: selector,\n\t\t\tPorts: ports,\n\t\t\tExternalName: o.ExternalName,\n\t\t},\n\t}\n\tif len(o.ClusterIP) \u003e 0 {\n\t\tservice.Spec.ClusterIP = o.ClusterIP\n\t}\n\treturn \u0026service, nil\n}","line":{"from":152,"to":198}} {"id":100031751,"name":"Run","signature":"func (o *ServiceOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_service.go","code":"// Run the service command\nfunc (o *ServiceOptions) Run() error {\n\tservice, err := o.createService()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := util.CreateOrUpdateAnnotation(o.CreateAnnotation, service, scheme.DefaultJSONEncoder()); err != nil {\n\t\treturn err\n\t}\n\n\tif o.DryRunStrategy != cmdutil.DryRunClient {\n\t\tcreateOptions := metav1.CreateOptions{}\n\t\tif o.FieldManager != \"\" {\n\t\t\tcreateOptions.FieldManager = o.FieldManager\n\t\t}\n\t\tcreateOptions.FieldValidation = o.ValidationDirective\n\t\tif o.DryRunStrategy == cmdutil.DryRunServer {\n\t\t\tcreateOptions.DryRun = []string{metav1.DryRunAll}\n\t\t}\n\t\tvar err error\n\t\tservice, err = o.Client.Services(o.Namespace).Create(context.TODO(), service, createOptions)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create %s service: %v\", o.Type, err)\n\t\t}\n\t}\n\treturn o.PrintObj(service)\n}","line":{"from":200,"to":227}} {"id":100031752,"name":"NewCmdCreateServiceClusterIP","signature":"func NewCmdCreateServiceClusterIP(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_service.go","code":"// NewCmdCreateServiceClusterIP is a command to create a ClusterIP service\nfunc NewCmdCreateServiceClusterIP(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewServiceOptions(ioStreams, corev1.ServiceTypeClusterIP)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"clusterip NAME [--tcp=\u003cport\u003e:\u003ctargetPort\u003e] [--dry-run=server|client|none]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Create a ClusterIP service\"),\n\t\tLong: serviceClusterIPLong,\n\t\tExample: serviceClusterIPExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmd.Flags().StringSliceVar(\u0026o.TCP, \"tcp\", o.TCP, \"Port pairs can be specified as '\u003cport\u003e:\u003ctargetPort\u003e'.\")\n\tcmd.Flags().StringVar(\u0026o.ClusterIP, \"clusterip\", o.ClusterIP, i18n.T(\"Assign your own ClusterIP or set to 'None' for a 'headless' service (no loadbalancing).\"))\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.FieldManager, \"kubectl-create\")\n\tcmdutil.AddDryRunFlag(cmd)\n\n\treturn cmd\n}","line":{"from":241,"to":268}} {"id":100031753,"name":"NewCmdCreateServiceNodePort","signature":"func NewCmdCreateServiceNodePort(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_service.go","code":"// NewCmdCreateServiceNodePort is a macro command for creating a NodePort service\nfunc NewCmdCreateServiceNodePort(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewServiceOptions(ioStreams, corev1.ServiceTypeNodePort)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"nodeport NAME [--tcp=port:targetPort] [--dry-run=server|client|none]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Create a NodePort service\"),\n\t\tLong: serviceNodePortLong,\n\t\tExample: serviceNodePortExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmd.Flags().IntVar(\u0026o.NodePort, \"node-port\", o.NodePort, \"Port used to expose the service on each node in a cluster.\")\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.FieldManager, \"kubectl-create\")\n\tcmd.Flags().StringSliceVar(\u0026o.TCP, \"tcp\", o.TCP, \"Port pairs can be specified as '\u003cport\u003e:\u003ctargetPort\u003e'.\")\n\tcmdutil.AddDryRunFlag(cmd)\n\treturn cmd\n}","line":{"from":279,"to":305}} {"id":100031754,"name":"NewCmdCreateServiceLoadBalancer","signature":"func NewCmdCreateServiceLoadBalancer(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_service.go","code":"// NewCmdCreateServiceLoadBalancer is a macro command for creating a LoadBalancer service\nfunc NewCmdCreateServiceLoadBalancer(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewServiceOptions(ioStreams, corev1.ServiceTypeLoadBalancer)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"loadbalancer NAME [--tcp=port:targetPort] [--dry-run=server|client|none]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Create a LoadBalancer service\"),\n\t\tLong: serviceLoadBalancerLong,\n\t\tExample: serviceLoadBalancerExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmd.Flags().StringSliceVar(\u0026o.TCP, \"tcp\", o.TCP, \"Port pairs can be specified as '\u003cport\u003e:\u003ctargetPort\u003e'.\")\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.FieldManager, \"kubectl-create\")\n\tcmdutil.AddDryRunFlag(cmd)\n\treturn cmd\n}","line":{"from":316,"to":341}} {"id":100031755,"name":"NewCmdCreateServiceExternalName","signature":"func NewCmdCreateServiceExternalName(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_service.go","code":"// NewCmdCreateServiceExternalName is a macro command for creating an ExternalName service\nfunc NewCmdCreateServiceExternalName(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewServiceOptions(ioStreams, corev1.ServiceTypeExternalName)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"externalname NAME --external-name external.name [--dry-run=server|client|none]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Create an ExternalName service\"),\n\t\tLong: serviceExternalNameLong,\n\t\tExample: serviceExternalNameExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmd.Flags().StringSliceVar(\u0026o.TCP, \"tcp\", o.TCP, \"Port pairs can be specified as '\u003cport\u003e:\u003ctargetPort\u003e'.\")\n\tcmd.Flags().StringVar(\u0026o.ExternalName, \"external-name\", o.ExternalName, i18n.T(\"External name of service\"))\n\tcmd.MarkFlagRequired(\"external-name\")\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.FieldManager, \"kubectl-create\")\n\tcmdutil.AddDryRunFlag(cmd)\n\treturn cmd\n}","line":{"from":356,"to":383}} {"id":100031756,"name":"parsePorts","signature":"func parsePorts(portString string) (int32, intstr.IntOrString, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_service.go","code":"func parsePorts(portString string) (int32, intstr.IntOrString, error) {\n\tportStringSlice := strings.Split(portString, \":\")\n\n\tport, err := utilsnet.ParsePort(portStringSlice[0], true)\n\tif err != nil {\n\t\treturn 0, intstr.FromInt(0), err\n\t}\n\n\tif len(portStringSlice) == 1 {\n\t\treturn int32(port), intstr.FromInt(int(port)), nil\n\t}\n\n\tvar targetPort intstr.IntOrString\n\tif portNum, err := strconv.Atoi(portStringSlice[1]); err != nil {\n\t\tif errs := validation.IsValidPortName(portStringSlice[1]); len(errs) != 0 {\n\t\t\treturn 0, intstr.FromInt(0), fmt.Errorf(strings.Join(errs, \",\"))\n\t\t}\n\t\ttargetPort = intstr.FromString(portStringSlice[1])\n\t} else {\n\t\tif errs := validation.IsValidPortNum(portNum); len(errs) != 0 {\n\t\t\treturn 0, intstr.FromInt(0), fmt.Errorf(strings.Join(errs, \",\"))\n\t\t}\n\t\ttargetPort = intstr.FromInt(portNum)\n\t}\n\treturn int32(port), targetPort, nil\n}","line":{"from":385,"to":410}} {"id":100031757,"name":"NewServiceAccountOpts","signature":"func NewServiceAccountOpts(ioStreams genericclioptions.IOStreams) *ServiceAccountOpts","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_serviceaccount.go","code":"// NewServiceAccountOpts creates a new *ServiceAccountOpts with sane defaults\nfunc NewServiceAccountOpts(ioStreams genericclioptions.IOStreams) *ServiceAccountOpts {\n\treturn \u0026ServiceAccountOpts{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"created\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":68,"to":74}} {"id":100031758,"name":"NewCmdCreateServiceAccount","signature":"func NewCmdCreateServiceAccount(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_serviceaccount.go","code":"// NewCmdCreateServiceAccount is a macro command to create a new service account\nfunc NewCmdCreateServiceAccount(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewServiceAccountOpts(ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"serviceaccount NAME [--dry-run=server|client|none]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tAliases: []string{\"sa\"},\n\t\tShort: i18n.T(\"Create a service account with the specified name\"),\n\t\tLong: serviceAccountLong,\n\t\tExample: serviceAccountExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.FieldManager, \"kubectl-create\")\n\treturn cmd\n}","line":{"from":76,"to":101}} {"id":100031759,"name":"Complete","signature":"func (o *ServiceAccountOpts) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_serviceaccount.go","code":"// Complete completes all the required options\nfunc (o *ServiceAccountOpts) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\to.Name, err = NameFromCommandArgs(cmd, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trestConfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.Client, err = coreclient.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.CreateAnnotation = cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag)\n\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.PrintObj = func(obj runtime.Object) error {\n\t\treturn printer.PrintObj(obj, o.Out)\n\t}\n\n\to.ValidationDirective, err = cmdutil.GetValidationDirective(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":103,"to":149}} {"id":100031760,"name":"Validate","signature":"func (o *ServiceAccountOpts) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_serviceaccount.go","code":"// Validate checks ServiceAccountOpts to see if there is sufficient information run the command.\nfunc (o *ServiceAccountOpts) Validate() error {\n\tif len(o.Name) == 0 {\n\t\treturn fmt.Errorf(\"name must be specified\")\n\t}\n\treturn nil\n}","line":{"from":151,"to":157}} {"id":100031761,"name":"Run","signature":"func (o *ServiceAccountOpts) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_serviceaccount.go","code":"// Run makes the api call to the server\nfunc (o *ServiceAccountOpts) Run() error {\n\tserviceAccount, err := o.createServiceAccount()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := util.CreateOrUpdateAnnotation(o.CreateAnnotation, serviceAccount, scheme.DefaultJSONEncoder()); err != nil {\n\t\treturn err\n\t}\n\n\tif o.DryRunStrategy != cmdutil.DryRunClient {\n\t\tcreateOptions := metav1.CreateOptions{}\n\t\tif o.FieldManager != \"\" {\n\t\t\tcreateOptions.FieldManager = o.FieldManager\n\t\t}\n\t\tcreateOptions.FieldValidation = o.ValidationDirective\n\t\tif o.DryRunStrategy == cmdutil.DryRunServer {\n\t\t\tcreateOptions.DryRun = []string{metav1.DryRunAll}\n\t\t}\n\t\tserviceAccount, err = o.Client.ServiceAccounts(o.Namespace).Create(context.TODO(), serviceAccount, createOptions)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create serviceaccount: %v\", err)\n\t\t}\n\t}\n\treturn o.PrintObj(serviceAccount)\n}","line":{"from":159,"to":185}} {"id":100031762,"name":"createServiceAccount","signature":"func (o *ServiceAccountOpts) createServiceAccount() (*corev1.ServiceAccount, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_serviceaccount.go","code":"func (o *ServiceAccountOpts) createServiceAccount() (*corev1.ServiceAccount, error) {\n\tnamespace := \"\"\n\tif o.EnforceNamespace {\n\t\tnamespace = o.Namespace\n\t}\n\tserviceAccount := \u0026corev1.ServiceAccount{\n\t\tTypeMeta: metav1.TypeMeta{APIVersion: corev1.SchemeGroupVersion.String(), Kind: \"ServiceAccount\"},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: o.Name,\n\t\t\tNamespace: namespace,\n\t\t},\n\t}\n\tserviceAccount.Name = o.Name\n\treturn serviceAccount, nil\n}","line":{"from":187,"to":201}} {"id":100031763,"name":"NewTokenOpts","signature":"func NewTokenOpts(ioStreams genericclioptions.IOStreams) *TokenOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_token.go","code":"func NewTokenOpts(ioStreams genericclioptions.IOStreams) *TokenOptions {\n\treturn \u0026TokenOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"created\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":101,"to":106}} {"id":100031764,"name":"NewCmdCreateToken","signature":"func NewCmdCreateToken(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_token.go","code":"// NewCmdCreateToken returns an initialized Command for 'create token' sub command\nfunc NewCmdCreateToken(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewTokenOpts(ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"token SERVICE_ACCOUNT_NAME\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: \"Request a service account token\",\n\t\tLong: tokenLong,\n\t\tExample: tokenExample,\n\t\tValidArgsFunction: completion.ResourceNameCompletionFunc(f, \"serviceaccount\"),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tif err := o.Complete(f, cmd, args); err != nil {\n\t\t\t\tcmdutil.CheckErr(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err := o.Validate(); err != nil {\n\t\t\t\tcmdutil.CheckErr(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err := o.Run(); err != nil {\n\t\t\t\tcmdutil.CheckErr(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmd.Flags().StringArrayVar(\u0026o.Audiences, \"audience\", o.Audiences, \"Audience of the requested token. If unset, defaults to requesting a token for use with the Kubernetes API server. May be repeated to request a token valid for multiple audiences.\")\n\n\tcmd.Flags().DurationVar(\u0026o.Duration, \"duration\", o.Duration, \"Requested lifetime of the issued token. The server may return a token with a longer or shorter lifetime.\")\n\n\tcmd.Flags().StringVar(\u0026o.BoundObjectKind, \"bound-object-kind\", o.BoundObjectKind, \"Kind of an object to bind the token to. \"+\n\t\t\"Supported kinds are \"+strings.Join(sets.StringKeySet(boundObjectKindToAPIVersion).List(), \", \")+\". \"+\n\t\t\"If set, --bound-object-name must be provided.\")\n\tcmd.Flags().StringVar(\u0026o.BoundObjectName, \"bound-object-name\", o.BoundObjectName, \"Name of an object to bind the token to. \"+\n\t\t\"The token will expire when the object is deleted. \"+\n\t\t\"Requires --bound-object-kind.\")\n\tcmd.Flags().StringVar(\u0026o.BoundObjectUID, \"bound-object-uid\", o.BoundObjectUID, \"UID of an object to bind the token to. \"+\n\t\t\"Requires --bound-object-kind and --bound-object-name. \"+\n\t\t\"If unset, the UID of the existing object is used.\")\n\n\treturn cmd\n}","line":{"from":108,"to":152}} {"id":100031765,"name":"Complete","signature":"func (o *TokenOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_token.go","code":"// Complete completes all the required options\nfunc (o *TokenOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\n\to.Name, err = NameFromCommandArgs(cmd, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Namespace, _, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient, err := f.KubernetesClientSet()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.CoreClient = client.CoreV1()\n\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.PrintObj = func(obj runtime.Object) error {\n\t\treturn printer.PrintObj(obj, o.Out)\n\t}\n\n\treturn nil\n}","line":{"from":154,"to":184}} {"id":100031766,"name":"Validate","signature":"func (o *TokenOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_token.go","code":"// Validate makes sure provided values for TokenOptions are valid\nfunc (o *TokenOptions) Validate() error {\n\tif o.CoreClient == nil {\n\t\treturn fmt.Errorf(\"no client provided\")\n\t}\n\tif len(o.Name) == 0 {\n\t\treturn fmt.Errorf(\"service account name is required\")\n\t}\n\tif len(o.Namespace) == 0 {\n\t\treturn fmt.Errorf(\"--namespace is required\")\n\t}\n\tif o.Duration \u003c 0 {\n\t\treturn fmt.Errorf(\"--duration must be positive\")\n\t}\n\tif o.Duration%time.Second != 0 {\n\t\treturn fmt.Errorf(\"--duration cannot be expressed in units less than seconds\")\n\t}\n\tfor _, aud := range o.Audiences {\n\t\tif len(aud) == 0 {\n\t\t\treturn fmt.Errorf(\"--audience must not be an empty string\")\n\t\t}\n\t}\n\n\tif len(o.BoundObjectKind) == 0 {\n\t\tif len(o.BoundObjectName) \u003e 0 {\n\t\t\treturn fmt.Errorf(\"--bound-object-name can only be set if --bound-object-kind is provided\")\n\t\t}\n\t\tif len(o.BoundObjectUID) \u003e 0 {\n\t\t\treturn fmt.Errorf(\"--bound-object-uid can only be set if --bound-object-kind is provided\")\n\t\t}\n\t} else {\n\t\tif _, ok := boundObjectKindToAPIVersion[o.BoundObjectKind]; !ok {\n\t\t\treturn fmt.Errorf(\"supported --bound-object-kind values are %s\", strings.Join(sets.StringKeySet(boundObjectKindToAPIVersion).List(), \", \"))\n\t\t}\n\t\tif len(o.BoundObjectName) == 0 {\n\t\t\treturn fmt.Errorf(\"--bound-object-name is required if --bound-object-kind is provided\")\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":186,"to":226}} {"id":100031767,"name":"Run","signature":"func (o *TokenOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/create/create_token.go","code":"// Run requests a token\nfunc (o *TokenOptions) Run() error {\n\trequest := \u0026authenticationv1.TokenRequest{\n\t\tSpec: authenticationv1.TokenRequestSpec{\n\t\t\tAudiences: o.Audiences,\n\t\t},\n\t}\n\tif o.Duration \u003e 0 {\n\t\trequest.Spec.ExpirationSeconds = pointer.Int64(int64(o.Duration / time.Second))\n\t}\n\tif len(o.BoundObjectKind) \u003e 0 {\n\t\trequest.Spec.BoundObjectRef = \u0026authenticationv1.BoundObjectReference{\n\t\t\tKind: o.BoundObjectKind,\n\t\t\tAPIVersion: boundObjectKindToAPIVersion[o.BoundObjectKind],\n\t\t\tName: o.BoundObjectName,\n\t\t\tUID: types.UID(o.BoundObjectUID),\n\t\t}\n\t}\n\n\tresponse, err := o.CoreClient.ServiceAccounts(o.Namespace).CreateToken(context.TODO(), o.Name, request, metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create token: %v\", err)\n\t}\n\tif len(response.Status.Token) == 0 {\n\t\treturn fmt.Errorf(\"failed to create token: no token in server response\")\n\t}\n\n\tif o.PrintFlags.OutputFlagSpecified() {\n\t\treturn o.PrintObj(response)\n\t}\n\n\tif term.IsTerminal(o.Out) {\n\t\t// include a newline when printing interactively\n\t\tfmt.Fprintf(o.Out, \"%s\\n\", response.Status.Token)\n\t} else {\n\t\t// otherwise just print the token\n\t\tfmt.Fprintf(o.Out, \"%s\", response.Status.Token)\n\t}\n\n\treturn nil\n}","line":{"from":228,"to":268}} {"id":100031768,"name":"NewDebugOptions","signature":"func NewDebugOptions(streams genericclioptions.IOStreams) *DebugOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/debug.go","code":"// NewDebugOptions returns a DebugOptions initialized with default values.\nfunc NewDebugOptions(streams genericclioptions.IOStreams) *DebugOptions {\n\treturn \u0026DebugOptions{\n\t\tArgs: []string{},\n\t\tIOStreams: streams,\n\t\tTargetNames: []string{},\n\t\tShareProcesses: true,\n\t}\n}","line":{"from":144,"to":152}} {"id":100031769,"name":"NewCmdDebug","signature":"func NewCmdDebug(restClientGetter genericclioptions.RESTClientGetter, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/debug.go","code":"// NewCmdDebug returns a cobra command that runs kubectl debug.\nfunc NewCmdDebug(restClientGetter genericclioptions.RESTClientGetter, streams genericclioptions.IOStreams) *cobra.Command {\n\to := NewDebugOptions(streams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"debug (POD | TYPE[[.VERSION].GROUP]/NAME) [ -- COMMAND [args...] ]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Create debugging sessions for troubleshooting workloads and nodes\"),\n\t\tLong: debugLong,\n\t\tExample: debugExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(restClientGetter, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run(restClientGetter, cmd))\n\t\t},\n\t}\n\n\to.AddFlags(cmd)\n\treturn cmd\n}","line":{"from":154,"to":173}} {"id":100031770,"name":"AddFlags","signature":"func (o *DebugOptions) AddFlags(cmd *cobra.Command)","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/debug.go","code":"func (o *DebugOptions) AddFlags(cmd *cobra.Command) {\n\tcmdutil.AddJsonFilenameFlag(cmd.Flags(), \u0026o.FilenameOptions.Filenames, \"identifying the resource to debug\")\n\n\tcmd.Flags().BoolVar(\u0026o.ArgsOnly, \"arguments-only\", o.ArgsOnly, i18n.T(\"If specified, everything after -- will be passed to the new container as Args instead of Command.\"))\n\tcmd.Flags().BoolVar(\u0026o.Attach, \"attach\", o.Attach, i18n.T(\"If true, wait for the container to start running, and then attach as if 'kubectl attach ...' were called. Default false, unless '-i/--stdin' is set, in which case the default is true.\"))\n\tcmd.Flags().StringVarP(\u0026o.Container, \"container\", \"c\", o.Container, i18n.T(\"Container name to use for debug container.\"))\n\tcmd.Flags().StringVar(\u0026o.CopyTo, \"copy-to\", o.CopyTo, i18n.T(\"Create a copy of the target Pod with this name.\"))\n\tcmd.Flags().BoolVar(\u0026o.Replace, \"replace\", o.Replace, i18n.T(\"When used with '--copy-to', delete the original Pod.\"))\n\tcmd.Flags().StringToString(\"env\", nil, i18n.T(\"Environment variables to set in the container.\"))\n\tcmd.Flags().StringVar(\u0026o.Image, \"image\", o.Image, i18n.T(\"Container image to use for debug container.\"))\n\tcmd.Flags().StringToStringVar(\u0026o.SetImages, \"set-image\", o.SetImages, i18n.T(\"When used with '--copy-to', a list of name=image pairs for changing container images, similar to how 'kubectl set image' works.\"))\n\tcmd.Flags().String(\"image-pull-policy\", \"\", i18n.T(\"The image pull policy for the container. If left empty, this value will not be specified by the client and defaulted by the server.\"))\n\tcmd.Flags().BoolVarP(\u0026o.Interactive, \"stdin\", \"i\", o.Interactive, i18n.T(\"Keep stdin open on the container(s) in the pod, even if nothing is attached.\"))\n\tcmd.Flags().BoolVarP(\u0026o.Quiet, \"quiet\", \"q\", o.Quiet, i18n.T(\"If true, suppress informational messages.\"))\n\tcmd.Flags().BoolVar(\u0026o.SameNode, \"same-node\", o.SameNode, i18n.T(\"When used with '--copy-to', schedule the copy of target Pod on the same node.\"))\n\tcmd.Flags().BoolVar(\u0026o.ShareProcesses, \"share-processes\", o.ShareProcesses, i18n.T(\"When used with '--copy-to', enable process namespace sharing in the copy.\"))\n\tcmd.Flags().StringVar(\u0026o.TargetContainer, \"target\", \"\", i18n.T(\"When using an ephemeral container, target processes in this container name.\"))\n\tcmd.Flags().BoolVarP(\u0026o.TTY, \"tty\", \"t\", o.TTY, i18n.T(\"Allocate a TTY for the debugging container.\"))\n\tcmd.Flags().StringVar(\u0026o.Profile, \"profile\", ProfileLegacy, i18n.T(`Debugging profile. Options are \"legacy\", \"general\", \"baseline\", \"netadmin\", or \"restricted\".`))\n}","line":{"from":175,"to":194}} {"id":100031771,"name":"Complete","signature":"func (o *DebugOptions) Complete(restClientGetter genericclioptions.RESTClientGetter, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/debug.go","code":"// Complete finishes run-time initialization of debug.DebugOptions.\nfunc (o *DebugOptions) Complete(restClientGetter genericclioptions.RESTClientGetter, cmd *cobra.Command, args []string) error {\n\tvar err error\n\n\to.PullPolicy = corev1.PullPolicy(cmdutil.GetFlagString(cmd, \"image-pull-policy\"))\n\n\t// Arguments\n\targsLen := cmd.ArgsLenAtDash()\n\to.TargetNames = args\n\t// If there is a dash and there are args after the dash, extract the args.\n\tif argsLen \u003e= 0 \u0026\u0026 len(args) \u003e argsLen {\n\t\to.TargetNames, o.Args = args[:argsLen], args[argsLen:]\n\t}\n\n\t// Attach\n\tattachFlag := cmd.Flags().Lookup(\"attach\")\n\tif !attachFlag.Changed \u0026\u0026 o.Interactive {\n\t\to.Attach = true\n\t}\n\n\t// Environment\n\tenvStrings, err := cmd.Flags().GetStringToString(\"env\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"internal error getting env flag: %v\", err)\n\t}\n\tfor k, v := range envStrings {\n\t\to.Env = append(o.Env, corev1.EnvVar{Name: k, Value: v})\n\t}\n\n\t// Namespace\n\to.Namespace, o.explicitNamespace, err = restClientGetter.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Record flags that the user explicitly changed from their defaults\n\to.attachChanged = cmd.Flags().Changed(\"attach\")\n\to.shareProcessedChanged = cmd.Flags().Changed(\"share-processes\")\n\n\t// Set default WarningPrinter\n\tif o.WarningPrinter == nil {\n\t\to.WarningPrinter = printers.NewWarningPrinter(o.ErrOut, printers.WarningPrinterOptions{Color: term.AllowsColorOutput(o.ErrOut)})\n\t}\n\n\tif o.Applier == nil {\n\t\tapplier, err := NewProfileApplier(o.Profile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\to.Applier = applier\n\t}\n\n\tclientConfig, err := restClientGetter.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient, err := kubernetes.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.podClient = client.CoreV1()\n\n\to.Builder = resource.NewBuilder(restClientGetter)\n\n\treturn nil\n}","line":{"from":196,"to":263}} {"id":100031772,"name":"Validate","signature":"func (o *DebugOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/debug.go","code":"// Validate checks that the provided debug options are specified.\nfunc (o *DebugOptions) Validate() error {\n\t// Attach\n\tif o.Attach \u0026\u0026 o.attachChanged \u0026\u0026 len(o.Image) == 0 \u0026\u0026 len(o.Container) == 0 {\n\t\treturn fmt.Errorf(\"you must specify --container or create a new container using --image in order to attach.\")\n\t}\n\n\t// CopyTo\n\tif len(o.CopyTo) \u003e 0 {\n\t\tif len(o.Image) == 0 \u0026\u0026 len(o.SetImages) == 0 \u0026\u0026 len(o.Args) == 0 {\n\t\t\treturn fmt.Errorf(\"you must specify --image, --set-image or command arguments.\")\n\t\t}\n\t\tif len(o.Args) \u003e 0 \u0026\u0026 len(o.Container) == 0 \u0026\u0026 len(o.Image) == 0 {\n\t\t\treturn fmt.Errorf(\"you must specify an existing container or a new image when specifying args.\")\n\t\t}\n\t} else {\n\t\t// These flags are exclusive to --copy-to\n\t\tswitch {\n\t\tcase o.Replace:\n\t\t\treturn fmt.Errorf(\"--replace may only be used with --copy-to.\")\n\t\tcase o.SameNode:\n\t\t\treturn fmt.Errorf(\"--same-node may only be used with --copy-to.\")\n\t\tcase len(o.SetImages) \u003e 0:\n\t\t\treturn fmt.Errorf(\"--set-image may only be used with --copy-to.\")\n\t\tcase len(o.Image) == 0:\n\t\t\treturn fmt.Errorf(\"you must specify --image when not using --copy-to.\")\n\t\t}\n\t}\n\n\t// Image\n\tif len(o.Image) \u003e 0 \u0026\u0026 !reference.ReferenceRegexp.MatchString(o.Image) {\n\t\treturn fmt.Errorf(\"invalid image name %q: %v\", o.Image, reference.ErrReferenceInvalidFormat)\n\t}\n\n\t// Name\n\tif len(o.TargetNames) == 0 \u0026\u0026 len(o.FilenameOptions.Filenames) == 0 {\n\t\treturn fmt.Errorf(\"NAME or filename is required for debug\")\n\t}\n\n\t// Pull Policy\n\tswitch o.PullPolicy {\n\tcase corev1.PullAlways, corev1.PullIfNotPresent, corev1.PullNever, \"\":\n\t\t// continue\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid image pull policy: %s\", o.PullPolicy)\n\t}\n\n\t// SetImages\n\tfor name, image := range o.SetImages {\n\t\tif !reference.ReferenceRegexp.MatchString(image) {\n\t\t\treturn fmt.Errorf(\"invalid image name %q for container %q: %v\", image, name, reference.ErrReferenceInvalidFormat)\n\t\t}\n\t}\n\n\t// TargetContainer\n\tif len(o.TargetContainer) \u003e 0 {\n\t\tif len(o.CopyTo) \u003e 0 {\n\t\t\treturn fmt.Errorf(\"--target is incompatible with --copy-to. Use --share-processes instead.\")\n\t\t}\n\t\tif !o.Quiet {\n\t\t\tfmt.Fprintf(o.Out, \"Targeting container %q. If you don't see processes from this container it may be because the container runtime doesn't support this feature.\\n\", o.TargetContainer)\n\t\t\t// TODO(verb): Add a list of supported container runtimes to https://kubernetes.io/docs/concepts/workloads/pods/ephemeral-containers/ and then link here.\n\t\t}\n\t}\n\n\t// TTY\n\tif o.TTY \u0026\u0026 !o.Interactive {\n\t\treturn fmt.Errorf(\"-i/--stdin is required for containers with -t/--tty=true\")\n\t}\n\n\t// WarningPrinter\n\tif o.WarningPrinter == nil {\n\t\treturn fmt.Errorf(\"WarningPrinter can not be used without initialization\")\n\t}\n\n\treturn nil\n}","line":{"from":265,"to":341}} {"id":100031773,"name":"Run","signature":"func (o *DebugOptions) Run(restClientGetter genericclioptions.RESTClientGetter, cmd *cobra.Command) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/debug.go","code":"// Run executes a kubectl debug.\nfunc (o *DebugOptions) Run(restClientGetter genericclioptions.RESTClientGetter, cmd *cobra.Command) error {\n\tctx := context.Background()\n\n\tr := o.Builder.\n\t\tWithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).\n\t\tFilenameParam(o.explicitNamespace, \u0026o.FilenameOptions).\n\t\tNamespaceParam(o.Namespace).DefaultNamespace().ResourceNames(\"pods\", o.TargetNames...).\n\t\tDo()\n\tif err := r.Err(); err != nil {\n\t\treturn err\n\t}\n\n\terr := r.Visit(func(info *resource.Info, err error) error {\n\t\tif err != nil {\n\t\t\t// TODO(verb): configurable early return\n\t\t\treturn err\n\t\t}\n\n\t\tvar (\n\t\t\tdebugPod *corev1.Pod\n\t\t\tcontainerName string\n\t\t\tvisitErr error\n\t\t)\n\t\tswitch obj := info.Object.(type) {\n\t\tcase *corev1.Node:\n\t\t\tdebugPod, containerName, visitErr = o.visitNode(ctx, obj)\n\t\tcase *corev1.Pod:\n\t\t\tdebugPod, containerName, visitErr = o.visitPod(ctx, obj)\n\t\tdefault:\n\t\t\tvisitErr = fmt.Errorf(\"%q not supported by debug\", info.Mapping.GroupVersionKind)\n\t\t}\n\t\tif visitErr != nil {\n\t\t\treturn visitErr\n\t\t}\n\n\t\tif o.Attach \u0026\u0026 len(containerName) \u003e 0 {\n\t\t\topts := \u0026attach.AttachOptions{\n\t\t\t\tStreamOptions: exec.StreamOptions{\n\t\t\t\t\tIOStreams: o.IOStreams,\n\t\t\t\t\tStdin: o.Interactive,\n\t\t\t\t\tTTY: o.TTY,\n\t\t\t\t\tQuiet: o.Quiet,\n\t\t\t\t},\n\t\t\t\tCommandName: cmd.Parent().CommandPath() + \" attach\",\n\n\t\t\t\tAttach: \u0026attach.DefaultRemoteAttach{},\n\t\t\t}\n\t\t\tconfig, err := restClientGetter.ToRESTConfig()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\topts.Config = config\n\t\t\topts.AttachFunc = attach.DefaultAttachFunc\n\n\t\t\tif err := o.handleAttachPod(ctx, restClientGetter, debugPod.Namespace, debugPod.Name, containerName, opts); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\n\treturn err\n}","line":{"from":343,"to":407}} {"id":100031774,"name":"visitNode","signature":"func (o *DebugOptions) visitNode(ctx context.Context, node *corev1.Node) (*corev1.Pod, string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/debug.go","code":"// visitNode handles debugging for node targets by creating a privileged pod running in the host namespaces.\n// Returns an already created pod and container name for subsequent attach, if applicable.\nfunc (o *DebugOptions) visitNode(ctx context.Context, node *corev1.Node) (*corev1.Pod, string, error) {\n\tpods := o.podClient.Pods(o.Namespace)\n\tdebugPod, err := o.generateNodeDebugPod(node)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tnewPod, err := pods.Create(ctx, debugPod, metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\treturn newPod, newPod.Spec.Containers[0].Name, nil\n}","line":{"from":409,"to":423}} {"id":100031775,"name":"visitPod","signature":"func (o *DebugOptions) visitPod(ctx context.Context, pod *corev1.Pod) (*corev1.Pod, string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/debug.go","code":"// visitPod handles debugging for pod targets by (depending on options):\n// 1. Creating an ephemeral debug container in an existing pod, OR\n// 2. Making a copy of pod with certain attributes changed\n//\n// visitPod returns a pod and debug container name for subsequent attach, if applicable.\nfunc (o *DebugOptions) visitPod(ctx context.Context, pod *corev1.Pod) (*corev1.Pod, string, error) {\n\tif len(o.CopyTo) \u003e 0 {\n\t\treturn o.debugByCopy(ctx, pod)\n\t}\n\treturn o.debugByEphemeralContainer(ctx, pod)\n}","line":{"from":425,"to":435}} {"id":100031776,"name":"debugByEphemeralContainer","signature":"func (o *DebugOptions) debugByEphemeralContainer(ctx context.Context, pod *corev1.Pod) (*corev1.Pod, string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/debug.go","code":"// debugByEphemeralContainer runs an EphemeralContainer in the target Pod for use as a debug container\nfunc (o *DebugOptions) debugByEphemeralContainer(ctx context.Context, pod *corev1.Pod) (*corev1.Pod, string, error) {\n\tklog.V(2).Infof(\"existing ephemeral containers: %v\", pod.Spec.EphemeralContainers)\n\tpodJS, err := json.Marshal(pod)\n\tif err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"error creating JSON for pod: %v\", err)\n\t}\n\n\tdebugPod, debugContainer, err := o.generateDebugContainer(pod)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tklog.V(2).Infof(\"new ephemeral container: %#v\", debugContainer)\n\n\tdebugJS, err := json.Marshal(debugPod)\n\tif err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"error creating JSON for debug container: %v\", err)\n\t}\n\n\tpatch, err := strategicpatch.CreateTwoWayMergePatch(podJS, debugJS, pod)\n\tif err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"error creating patch to add debug container: %v\", err)\n\t}\n\tklog.V(2).Infof(\"generated strategic merge patch for debug container: %s\", patch)\n\n\tpods := o.podClient.Pods(pod.Namespace)\n\tresult, err := pods.Patch(ctx, pod.Name, types.StrategicMergePatchType, patch, metav1.PatchOptions{}, \"ephemeralcontainers\")\n\tif err != nil {\n\t\t// The apiserver will return a 404 when the EphemeralContainers feature is disabled because the `/ephemeralcontainers` subresource\n\t\t// is missing. Unlike the 404 returned by a missing pod, the status details will be empty.\n\t\tif serr, ok := err.(*errors.StatusError); ok \u0026\u0026 serr.Status().Reason == metav1.StatusReasonNotFound \u0026\u0026 serr.ErrStatus.Details.Name == \"\" {\n\t\t\treturn nil, \"\", fmt.Errorf(\"ephemeral containers are disabled for this cluster (error from server: %q)\", err)\n\t\t}\n\n\t\t// The Kind used for the /ephemeralcontainers subresource changed in 1.22. When presented with an unexpected\n\t\t// Kind the api server will respond with a not-registered error. When this happens we can optimistically try\n\t\t// using the old API.\n\t\tif runtime.IsNotRegisteredError(err) {\n\t\t\tklog.V(1).Infof(\"Falling back to legacy API because server returned error: %v\", err)\n\t\t\treturn o.debugByEphemeralContainerLegacy(ctx, pod, debugContainer)\n\t\t}\n\n\t\treturn nil, \"\", err\n\t}\n\n\treturn result, debugContainer.Name, nil\n}","line":{"from":437,"to":483}} {"id":100031777,"name":"debugByEphemeralContainerLegacy","signature":"func (o *DebugOptions) debugByEphemeralContainerLegacy(ctx context.Context, pod *corev1.Pod, debugContainer *corev1.EphemeralContainer) (*corev1.Pod, string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/debug.go","code":"// debugByEphemeralContainerLegacy adds debugContainer as an ephemeral container using the pre-1.22 /ephemeralcontainers API\n// This may be removed when we no longer wish to support releases prior to 1.22.\nfunc (o *DebugOptions) debugByEphemeralContainerLegacy(ctx context.Context, pod *corev1.Pod, debugContainer *corev1.EphemeralContainer) (*corev1.Pod, string, error) {\n\t// We no longer have the v1.EphemeralContainers Kind since it was removed in 1.22, but\n\t// we can present a JSON 6902 patch that the api server will apply.\n\tpatch, err := json.Marshal([]map[string]interface{}{{\n\t\t\"op\": \"add\",\n\t\t\"path\": \"/ephemeralContainers/-\",\n\t\t\"value\": debugContainer,\n\t}})\n\tif err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"error creating JSON 6902 patch for old /ephemeralcontainers API: %s\", err)\n\t}\n\n\tresult := o.podClient.RESTClient().Patch(types.JSONPatchType).\n\t\tNamespace(pod.Namespace).\n\t\tResource(\"pods\").\n\t\tName(pod.Name).\n\t\tSubResource(\"ephemeralcontainers\").\n\t\tBody(patch).\n\t\tDo(ctx)\n\tif err := result.Error(); err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\tnewPod, err := o.podClient.Pods(pod.Namespace).Get(ctx, pod.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\treturn newPod, debugContainer.Name, nil\n}","line":{"from":485,"to":516}} {"id":100031778,"name":"debugByCopy","signature":"func (o *DebugOptions) debugByCopy(ctx context.Context, pod *corev1.Pod) (*corev1.Pod, string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/debug.go","code":"// debugByCopy runs a copy of the target Pod with a debug container added or an original container modified\nfunc (o *DebugOptions) debugByCopy(ctx context.Context, pod *corev1.Pod) (*corev1.Pod, string, error) {\n\tcopied, dc, err := o.generatePodCopyWithDebugContainer(pod)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tcreated, err := o.podClient.Pods(copied.Namespace).Create(ctx, copied, metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tif o.Replace {\n\t\terr := o.podClient.Pods(pod.Namespace).Delete(ctx, pod.Name, *metav1.NewDeleteOptions(0))\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t}\n\treturn created, dc, nil\n}","line":{"from":518,"to":535}} {"id":100031779,"name":"generateDebugContainer","signature":"func (o *DebugOptions) generateDebugContainer(pod *corev1.Pod) (*corev1.Pod, *corev1.EphemeralContainer, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/debug.go","code":"// generateDebugContainer returns a debugging pod and an EphemeralContainer suitable for use as a debug container\n// in the given pod.\nfunc (o *DebugOptions) generateDebugContainer(pod *corev1.Pod) (*corev1.Pod, *corev1.EphemeralContainer, error) {\n\tname := o.computeDebugContainerName(pod)\n\tec := \u0026corev1.EphemeralContainer{\n\t\tEphemeralContainerCommon: corev1.EphemeralContainerCommon{\n\t\t\tName: name,\n\t\t\tEnv: o.Env,\n\t\t\tImage: o.Image,\n\t\t\tImagePullPolicy: o.PullPolicy,\n\t\t\tStdin: o.Interactive,\n\t\t\tTerminationMessagePolicy: corev1.TerminationMessageReadFile,\n\t\t\tTTY: o.TTY,\n\t\t},\n\t\tTargetContainerName: o.TargetContainer,\n\t}\n\n\tif o.ArgsOnly {\n\t\tec.Args = o.Args\n\t} else {\n\t\tec.Command = o.Args\n\t}\n\n\tcopied := pod.DeepCopy()\n\tcopied.Spec.EphemeralContainers = append(copied.Spec.EphemeralContainers, *ec)\n\tif err := o.Applier.Apply(copied, name, copied); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tec = \u0026copied.Spec.EphemeralContainers[len(copied.Spec.EphemeralContainers)-1]\n\n\treturn copied, ec, nil\n}","line":{"from":537,"to":569}} {"id":100031780,"name":"generateNodeDebugPod","signature":"func (o *DebugOptions) generateNodeDebugPod(node *corev1.Node) (*corev1.Pod, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/debug.go","code":"// generateNodeDebugPod generates a debugging pod that schedules on the specified node.\n// The generated pod will run in the host PID, Network \u0026 IPC namespaces, and it will have the node's filesystem mounted at /host.\nfunc (o *DebugOptions) generateNodeDebugPod(node *corev1.Node) (*corev1.Pod, error) {\n\tcn := \"debugger\"\n\t// Setting a user-specified container name doesn't make much difference when there's only one container,\n\t// but the argument exists for pod debugging so it might be confusing if it didn't work here.\n\tif len(o.Container) \u003e 0 {\n\t\tcn = o.Container\n\t}\n\n\t// The name of the debugging pod is based on the target node, and it's not configurable to\n\t// limit the number of command line flags. There may be a collision on the name, but this\n\t// should be rare enough that it's not worth the API round trip to check.\n\tpn := fmt.Sprintf(\"node-debugger-%s-%s\", node.Name, nameSuffixFunc(5))\n\tif !o.Quiet {\n\t\tfmt.Fprintf(o.Out, \"Creating debugging pod %s with container %s on node %s.\\n\", pn, cn, node.Name)\n\t}\n\n\tp := \u0026corev1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: pn,\n\t\t},\n\t\tSpec: corev1.PodSpec{\n\t\t\tContainers: []corev1.Container{\n\t\t\t\t{\n\t\t\t\t\tName: cn,\n\t\t\t\t\tEnv: o.Env,\n\t\t\t\t\tImage: o.Image,\n\t\t\t\t\tImagePullPolicy: o.PullPolicy,\n\t\t\t\t\tStdin: o.Interactive,\n\t\t\t\t\tTerminationMessagePolicy: corev1.TerminationMessageReadFile,\n\t\t\t\t\tTTY: o.TTY,\n\t\t\t\t},\n\t\t\t},\n\t\t\tNodeName: node.Name,\n\t\t\tRestartPolicy: corev1.RestartPolicyNever,\n\t\t\tTolerations: []corev1.Toleration{\n\t\t\t\t{\n\t\t\t\t\tOperator: corev1.TolerationOpExists,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tif o.ArgsOnly {\n\t\tp.Spec.Containers[0].Args = o.Args\n\t} else {\n\t\tp.Spec.Containers[0].Command = o.Args\n\t}\n\n\tif err := o.Applier.Apply(p, cn, node); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn p, nil\n}","line":{"from":571,"to":626}} {"id":100031781,"name":"generatePodCopyWithDebugContainer","signature":"func (o *DebugOptions) generatePodCopyWithDebugContainer(pod *corev1.Pod) (*corev1.Pod, string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/debug.go","code":"// generatePodCopyWithDebugContainer takes a Pod and returns a copy and the debug container name of that copy\nfunc (o *DebugOptions) generatePodCopyWithDebugContainer(pod *corev1.Pod) (*corev1.Pod, string, error) {\n\tcopied := \u0026corev1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: o.CopyTo,\n\t\t\tNamespace: pod.Namespace,\n\t\t\tAnnotations: pod.Annotations,\n\t\t},\n\t\tSpec: *pod.Spec.DeepCopy(),\n\t}\n\t// set EphemeralContainers to nil so that the copy of pod can be created\n\tcopied.Spec.EphemeralContainers = nil\n\t// change ShareProcessNamespace configuration only when commanded explicitly\n\tif o.shareProcessedChanged {\n\t\tcopied.Spec.ShareProcessNamespace = pointer.Bool(o.ShareProcesses)\n\t}\n\tif !o.SameNode {\n\t\tcopied.Spec.NodeName = \"\"\n\t}\n\n\t// Apply image mutations\n\tfor i, c := range copied.Spec.Containers {\n\t\toverride := o.SetImages[\"*\"]\n\t\tif img, ok := o.SetImages[c.Name]; ok {\n\t\t\toverride = img\n\t\t}\n\t\tif len(override) \u003e 0 {\n\t\t\tcopied.Spec.Containers[i].Image = override\n\t\t}\n\t}\n\n\tname, containerByName := o.Container, containerNameToRef(copied)\n\n\tc, ok := containerByName[name]\n\tif !ok {\n\t\t// Adding a new debug container\n\t\tif len(o.Image) == 0 {\n\t\t\tif len(o.SetImages) \u003e 0 {\n\t\t\t\t// This was a --set-image only invocation\n\t\t\t\treturn copied, \"\", nil\n\t\t\t}\n\t\t\treturn nil, \"\", fmt.Errorf(\"you must specify image when creating new container\")\n\t\t}\n\n\t\tif len(name) == 0 {\n\t\t\tname = o.computeDebugContainerName(copied)\n\t\t}\n\t\tcopied.Spec.Containers = append(copied.Spec.Containers, corev1.Container{\n\t\t\tName: name,\n\t\t\tTerminationMessagePolicy: corev1.TerminationMessageReadFile,\n\t\t})\n\t\tc = \u0026copied.Spec.Containers[len(copied.Spec.Containers)-1]\n\t}\n\n\tif len(o.Args) \u003e 0 {\n\t\tif o.ArgsOnly {\n\t\t\tc.Args = o.Args\n\t\t} else {\n\t\t\tc.Command = o.Args\n\t\t\tc.Args = nil\n\t\t}\n\t}\n\tif len(o.Env) \u003e 0 {\n\t\tc.Env = o.Env\n\t}\n\tif len(o.Image) \u003e 0 {\n\t\tc.Image = o.Image\n\t}\n\tif len(o.PullPolicy) \u003e 0 {\n\t\tc.ImagePullPolicy = o.PullPolicy\n\t}\n\tc.Stdin = o.Interactive\n\tc.TTY = o.TTY\n\n\terr := o.Applier.Apply(copied, c.Name, pod)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\treturn copied, name, nil\n}","line":{"from":628,"to":708}} {"id":100031782,"name":"computeDebugContainerName","signature":"func (o *DebugOptions) computeDebugContainerName(pod *corev1.Pod) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/debug.go","code":"func (o *DebugOptions) computeDebugContainerName(pod *corev1.Pod) string {\n\tif len(o.Container) \u003e 0 {\n\t\treturn o.Container\n\t}\n\n\tcn, containerByName := \"\", containerNameToRef(pod)\n\tfor len(cn) == 0 || (containerByName[cn] != nil) {\n\t\tcn = fmt.Sprintf(\"debugger-%s\", nameSuffixFunc(5))\n\t}\n\tif !o.Quiet {\n\t\tfmt.Fprintf(o.Out, \"Defaulting debug container name to %s.\\n\", cn)\n\t}\n\treturn cn\n}","line":{"from":710,"to":723}} {"id":100031783,"name":"containerNameToRef","signature":"func containerNameToRef(pod *corev1.Pod) map[string]*corev1.Container","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/debug.go","code":"func containerNameToRef(pod *corev1.Pod) map[string]*corev1.Container {\n\tnames := map[string]*corev1.Container{}\n\tfor i := range pod.Spec.Containers {\n\t\tref := \u0026pod.Spec.Containers[i]\n\t\tnames[ref.Name] = ref\n\t}\n\tfor i := range pod.Spec.InitContainers {\n\t\tref := \u0026pod.Spec.InitContainers[i]\n\t\tnames[ref.Name] = ref\n\t}\n\tfor i := range pod.Spec.EphemeralContainers {\n\t\tref := (*corev1.Container)(\u0026pod.Spec.EphemeralContainers[i].EphemeralContainerCommon)\n\t\tnames[ref.Name] = ref\n\t}\n\treturn names\n}","line":{"from":725,"to":740}} {"id":100031784,"name":"waitForContainer","signature":"func (o *DebugOptions) waitForContainer(ctx context.Context, ns, podName, containerName string) (*corev1.Pod, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/debug.go","code":"// waitForContainer watches the given pod until the container is running\nfunc (o *DebugOptions) waitForContainer(ctx context.Context, ns, podName, containerName string) (*corev1.Pod, error) {\n\t// TODO: expose the timeout\n\tctx, cancel := watchtools.ContextWithOptionalTimeout(ctx, 0*time.Second)\n\tdefer cancel()\n\n\tfieldSelector := fields.OneTermEqualSelector(\"metadata.name\", podName).String()\n\tlw := \u0026cache.ListWatch{\n\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\toptions.FieldSelector = fieldSelector\n\t\t\treturn o.podClient.Pods(ns).List(ctx, options)\n\t\t},\n\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\toptions.FieldSelector = fieldSelector\n\t\t\treturn o.podClient.Pods(ns).Watch(ctx, options)\n\t\t},\n\t}\n\n\tintr := interrupt.New(nil, cancel)\n\tvar result *corev1.Pod\n\terr := intr.Run(func() error {\n\t\tev, err := watchtools.UntilWithSync(ctx, lw, \u0026corev1.Pod{}, nil, func(ev watch.Event) (bool, error) {\n\t\t\tklog.V(2).Infof(\"watch received event %q with object %T\", ev.Type, ev.Object)\n\t\t\tswitch ev.Type {\n\t\t\tcase watch.Deleted:\n\t\t\t\treturn false, errors.NewNotFound(schema.GroupResource{Resource: \"pods\"}, \"\")\n\t\t\t}\n\n\t\t\tp, ok := ev.Object.(*corev1.Pod)\n\t\t\tif !ok {\n\t\t\t\treturn false, fmt.Errorf(\"watch did not return a pod: %v\", ev.Object)\n\t\t\t}\n\n\t\t\ts := getContainerStatusByName(p, containerName)\n\t\t\tif s == nil {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\tklog.V(2).Infof(\"debug container status is %v\", s)\n\t\t\tif s.State.Running != nil || s.State.Terminated != nil {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\tif !o.Quiet \u0026\u0026 s.State.Waiting != nil \u0026\u0026 s.State.Waiting.Message != \"\" {\n\t\t\t\to.WarningPrinter.Print(fmt.Sprintf(\"container %s: %s\", containerName, s.State.Waiting.Message))\n\t\t\t}\n\t\t\treturn false, nil\n\t\t})\n\t\tif ev != nil {\n\t\t\tresult = ev.Object.(*corev1.Pod)\n\t\t}\n\t\treturn err\n\t})\n\n\treturn result, err\n}","line":{"from":742,"to":795}} {"id":100031785,"name":"handleAttachPod","signature":"func (o *DebugOptions) handleAttachPod(ctx context.Context, restClientGetter genericclioptions.RESTClientGetter, ns, podName, containerName string, opts *attach.AttachOptions) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/debug.go","code":"func (o *DebugOptions) handleAttachPod(ctx context.Context, restClientGetter genericclioptions.RESTClientGetter, ns, podName, containerName string, opts *attach.AttachOptions) error {\n\tpod, err := o.waitForContainer(ctx, ns, podName, containerName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\topts.Namespace = ns\n\topts.Pod = pod\n\topts.PodName = podName\n\topts.ContainerName = containerName\n\tif opts.AttachFunc == nil {\n\t\topts.AttachFunc = attach.DefaultAttachFunc\n\t}\n\n\tstatus := getContainerStatusByName(pod, containerName)\n\tif status == nil {\n\t\t// impossible path\n\t\treturn fmt.Errorf(\"error getting container status of container name %q: %+v\", containerName, err)\n\t}\n\tif status.State.Terminated != nil {\n\t\tklog.V(1).Info(\"Ephemeral container terminated, falling back to logs\")\n\t\treturn logOpts(restClientGetter, pod, opts)\n\t}\n\n\tif err := opts.Run(); err != nil {\n\t\tfmt.Fprintf(opts.ErrOut, \"warning: couldn't attach to pod/%s, falling back to streaming logs: %v\\n\", podName, err)\n\t\treturn logOpts(restClientGetter, pod, opts)\n\t}\n\treturn nil\n}","line":{"from":797,"to":826}} {"id":100031786,"name":"getContainerStatusByName","signature":"func getContainerStatusByName(pod *corev1.Pod, containerName string) *corev1.ContainerStatus","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/debug.go","code":"func getContainerStatusByName(pod *corev1.Pod, containerName string) *corev1.ContainerStatus {\n\tallContainerStatus := [][]corev1.ContainerStatus{pod.Status.InitContainerStatuses, pod.Status.ContainerStatuses, pod.Status.EphemeralContainerStatuses}\n\tfor _, statusSlice := range allContainerStatus {\n\t\tfor i := range statusSlice {\n\t\t\tif statusSlice[i].Name == containerName {\n\t\t\t\treturn \u0026statusSlice[i]\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":828,"to":838}} {"id":100031787,"name":"logOpts","signature":"func logOpts(restClientGetter genericclioptions.RESTClientGetter, pod *corev1.Pod, opts *attach.AttachOptions) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/debug.go","code":"// logOpts logs output from opts to the pods log.\nfunc logOpts(restClientGetter genericclioptions.RESTClientGetter, pod *corev1.Pod, opts *attach.AttachOptions) error {\n\tctrName, err := opts.GetContainerName(pod)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trequests, err := polymorphichelpers.LogsForObjectFn(restClientGetter, pod, \u0026corev1.PodLogOptions{Container: ctrName}, opts.GetPodTimeout, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, request := range requests {\n\t\tif err := logs.DefaultConsumeRequest(request, opts.Out); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":840,"to":858}} {"id":100031788,"name":"NewProfileApplier","signature":"func NewProfileApplier(profile string) (ProfileApplier, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/profiles.go","code":"// NewProfileApplier returns a new Options for the given profile name.\nfunc NewProfileApplier(profile string) (ProfileApplier, error) {\n\tswitch profile {\n\tcase ProfileLegacy:\n\t\treturn \u0026legacyProfile{}, nil\n\tcase ProfileGeneral:\n\t\treturn \u0026generalProfile{}, nil\n\tcase ProfileBaseline:\n\t\treturn \u0026baselineProfile{}, nil\n\tcase ProfileRestricted:\n\t\treturn \u0026restrictedProfile{}, nil\n\tcase ProfileNetadmin:\n\t\treturn \u0026netadminProfile{}, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"unknown profile: %s\", profile)\n}","line":{"from":64,"to":80}} {"id":100031789,"name":"Apply","signature":"func (p *legacyProfile) Apply(pod *corev1.Pod, containerName string, target runtime.Object) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/profiles.go","code":"func (p *legacyProfile) Apply(pod *corev1.Pod, containerName string, target runtime.Object) error {\n\tswitch target.(type) {\n\tcase *corev1.Pod:\n\t\t// do nothing to the copied pod\n\t\treturn nil\n\tcase *corev1.Node:\n\t\tmountRootPartition(pod, containerName)\n\t\tuseHostNamespaces(pod)\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"the %s profile doesn't support objects of type %T\", ProfileLegacy, target)\n\t}\n}","line":{"from":97,"to":109}} {"id":100031790,"name":"getDebugStyle","signature":"func getDebugStyle(pod *corev1.Pod, target runtime.Object) (debugStyle, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/profiles.go","code":"func getDebugStyle(pod *corev1.Pod, target runtime.Object) (debugStyle, error) {\n\tswitch target.(type) {\n\tcase *corev1.Pod:\n\t\tif asserted, ok := target.(*corev1.Pod); ok {\n\t\t\tif pod != asserted { // comparing addresses\n\t\t\t\treturn podCopy, nil\n\t\t\t}\n\t\t}\n\t\treturn ephemeral, nil\n\tcase *corev1.Node:\n\t\treturn node, nil\n\t}\n\treturn unsupported, fmt.Errorf(\"objects of type %T are not supported\", target)\n}","line":{"from":111,"to":124}} {"id":100031791,"name":"Apply","signature":"func (p *generalProfile) Apply(pod *corev1.Pod, containerName string, target runtime.Object) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/profiles.go","code":"func (p *generalProfile) Apply(pod *corev1.Pod, containerName string, target runtime.Object) error {\n\tstyle, err := getDebugStyle(pod, target)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"general profile: %s\", err)\n\t}\n\n\tswitch style {\n\tcase node:\n\t\tmountRootPartition(pod, containerName)\n\t\tclearSecurityContext(pod, containerName)\n\t\tuseHostNamespaces(pod)\n\n\tcase podCopy:\n\t\tremoveLabelsAndProbes(pod)\n\t\tallowProcessTracing(pod, containerName)\n\t\tshareProcessNamespace(pod)\n\n\tcase ephemeral:\n\t\tallowProcessTracing(pod, containerName)\n\t}\n\n\treturn nil\n}","line":{"from":126,"to":148}} {"id":100031792,"name":"Apply","signature":"func (p *baselineProfile) Apply(pod *corev1.Pod, containerName string, target runtime.Object) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/profiles.go","code":"func (p *baselineProfile) Apply(pod *corev1.Pod, containerName string, target runtime.Object) error {\n\tstyle, err := getDebugStyle(pod, target)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"baseline profile: %s\", err)\n\t}\n\n\tclearSecurityContext(pod, containerName)\n\n\tswitch style {\n\tcase podCopy:\n\t\tremoveLabelsAndProbes(pod)\n\t\tshareProcessNamespace(pod)\n\n\tcase ephemeral, node:\n\t\t// no additional modifications needed\n\t}\n\n\treturn nil\n}","line":{"from":150,"to":168}} {"id":100031793,"name":"Apply","signature":"func (p *restrictedProfile) Apply(pod *corev1.Pod, containerName string, target runtime.Object) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/profiles.go","code":"func (p *restrictedProfile) Apply(pod *corev1.Pod, containerName string, target runtime.Object) error {\n\tstyle, err := getDebugStyle(pod, target)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"restricted profile: %s\", err)\n\t}\n\n\tclearSecurityContext(pod, containerName)\n\tdisallowRoot(pod, containerName)\n\tdropCapabilities(pod, containerName)\n\n\tswitch style {\n\tcase podCopy:\n\t\tshareProcessNamespace(pod)\n\n\tcase ephemeral, node:\n\t\t// no additional modifications needed\n\t}\n\n\treturn nil\n}","line":{"from":170,"to":189}} {"id":100031794,"name":"Apply","signature":"func (p *netadminProfile) Apply(pod *corev1.Pod, containerName string, target runtime.Object) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/profiles.go","code":"func (p *netadminProfile) Apply(pod *corev1.Pod, containerName string, target runtime.Object) error {\n\tstyle, err := getDebugStyle(pod, target)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"netadmin profile: %s\", err)\n\t}\n\n\tallowNetadminCapability(pod, containerName)\n\n\tswitch style {\n\tcase node:\n\t\tuseHostNamespaces(pod)\n\t\tsetPrivileged(pod, containerName)\n\n\tcase podCopy, ephemeral:\n\t\t// no additional modifications needed\n\t}\n\n\treturn nil\n}","line":{"from":191,"to":209}} {"id":100031795,"name":"removeLabelsAndProbes","signature":"func removeLabelsAndProbes(p *corev1.Pod)","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/profiles.go","code":"// removeLabelsAndProbes removes labels from the pod and remove probes\n// from all containers of the pod.\nfunc removeLabelsAndProbes(p *corev1.Pod) {\n\tp.Labels = nil\n\tfor i := range p.Spec.Containers {\n\t\tp.Spec.Containers[i].LivenessProbe = nil\n\t\tp.Spec.Containers[i].ReadinessProbe = nil\n\t}\n}","line":{"from":211,"to":219}} {"id":100031796,"name":"mountRootPartition","signature":"func mountRootPartition(p *corev1.Pod, containerName string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/profiles.go","code":"// mountRootPartition mounts the host's root path at \"/host\" in the container.\nfunc mountRootPartition(p *corev1.Pod, containerName string) {\n\tconst volumeName = \"host-root\"\n\tp.Spec.Volumes = append(p.Spec.Volumes, corev1.Volume{\n\t\tName: volumeName,\n\t\tVolumeSource: corev1.VolumeSource{\n\t\t\tHostPath: \u0026corev1.HostPathVolumeSource{Path: \"/\"},\n\t\t},\n\t})\n\tpodutils.VisitContainers(\u0026p.Spec, podutils.Containers, func(c *corev1.Container, _ podutils.ContainerType) bool {\n\t\tif c.Name != containerName {\n\t\t\treturn true\n\t\t}\n\t\tc.VolumeMounts = append(c.VolumeMounts, corev1.VolumeMount{\n\t\t\tMountPath: \"/host\",\n\t\t\tName: volumeName,\n\t\t})\n\t\treturn false\n\t})\n}","line":{"from":221,"to":240}} {"id":100031797,"name":"useHostNamespaces","signature":"func useHostNamespaces(p *corev1.Pod)","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/profiles.go","code":"// useHostNamespaces configures the pod to use the host's network, PID, and IPC\n// namespaces.\nfunc useHostNamespaces(p *corev1.Pod) {\n\tp.Spec.HostNetwork = true\n\tp.Spec.HostPID = true\n\tp.Spec.HostIPC = true\n}","line":{"from":242,"to":248}} {"id":100031798,"name":"shareProcessNamespace","signature":"func shareProcessNamespace(p *corev1.Pod)","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/profiles.go","code":"// shareProcessNamespace configures all containers in the pod to share the\n// process namespace.\nfunc shareProcessNamespace(p *corev1.Pod) {\n\tif p.Spec.ShareProcessNamespace == nil {\n\t\tp.Spec.ShareProcessNamespace = pointer.Bool(true)\n\t}\n}","line":{"from":250,"to":256}} {"id":100031799,"name":"clearSecurityContext","signature":"func clearSecurityContext(p *corev1.Pod, containerName string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/profiles.go","code":"// clearSecurityContext clears the security context for the container.\nfunc clearSecurityContext(p *corev1.Pod, containerName string) {\n\tpodutils.VisitContainers(\u0026p.Spec, podutils.AllContainers, func(c *corev1.Container, _ podutils.ContainerType) bool {\n\t\tif c.Name != containerName {\n\t\t\treturn true\n\t\t}\n\t\tc.SecurityContext = nil\n\t\treturn false\n\t})\n}","line":{"from":258,"to":267}} {"id":100031800,"name":"setPrivileged","signature":"func setPrivileged(p *corev1.Pod, containerName string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/profiles.go","code":"// setPrivileged configures the containers as privileged.\nfunc setPrivileged(p *corev1.Pod, containerName string) {\n\tpodutils.VisitContainers(\u0026p.Spec, podutils.AllContainers, func(c *corev1.Container, _ podutils.ContainerType) bool {\n\t\tif c.Name != containerName {\n\t\t\treturn true\n\t\t}\n\t\tif c.SecurityContext == nil {\n\t\t\tc.SecurityContext = \u0026corev1.SecurityContext{}\n\t\t}\n\t\tc.SecurityContext.Privileged = pointer.Bool(true)\n\t\treturn false\n\t})\n}","line":{"from":269,"to":281}} {"id":100031801,"name":"disallowRoot","signature":"func disallowRoot(p *corev1.Pod, containerName string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/profiles.go","code":"// disallowRoot configures the container to run as a non-root user.\nfunc disallowRoot(p *corev1.Pod, containerName string) {\n\tpodutils.VisitContainers(\u0026p.Spec, podutils.AllContainers, func(c *corev1.Container, _ podutils.ContainerType) bool {\n\t\tif c.Name != containerName {\n\t\t\treturn true\n\t\t}\n\t\tif c.SecurityContext == nil {\n\t\t\tc.SecurityContext = \u0026corev1.SecurityContext{}\n\t\t}\n\t\tc.SecurityContext.RunAsNonRoot = pointer.Bool(true)\n\t\treturn false\n\t})\n}","line":{"from":283,"to":295}} {"id":100031802,"name":"dropCapabilities","signature":"func dropCapabilities(p *corev1.Pod, containerName string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/profiles.go","code":"// dropCapabilities drops all Capabilities for the container\nfunc dropCapabilities(p *corev1.Pod, containerName string) {\n\tpodutils.VisitContainers(\u0026p.Spec, podutils.AllContainers, func(c *corev1.Container, _ podutils.ContainerType) bool {\n\t\tif c.Name != containerName {\n\t\t\treturn true\n\t\t}\n\t\tif c.SecurityContext == nil {\n\t\t\tc.SecurityContext = \u0026corev1.SecurityContext{}\n\t\t}\n\t\tif c.SecurityContext.Capabilities == nil {\n\t\t\tc.SecurityContext.Capabilities = \u0026corev1.Capabilities{}\n\t\t}\n\t\tc.SecurityContext.Capabilities.Drop = []corev1.Capability{\"ALL\"}\n\t\tc.SecurityContext.Capabilities.Add = nil\n\t\treturn false\n\t})\n}","line":{"from":297,"to":313}} {"id":100031803,"name":"allowProcessTracing","signature":"func allowProcessTracing(p *corev1.Pod, containerName string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/profiles.go","code":"// allowProcessTracing grants the SYS_PTRACE capability to the container.\nfunc allowProcessTracing(p *corev1.Pod, containerName string) {\n\tpodutils.VisitContainers(\u0026p.Spec, podutils.AllContainers, func(c *corev1.Container, _ podutils.ContainerType) bool {\n\t\tif c.Name != containerName {\n\t\t\treturn true\n\t\t}\n\t\taddCapability(c, \"SYS_PTRACE\")\n\t\treturn false\n\t})\n}","line":{"from":315,"to":324}} {"id":100031804,"name":"allowNetadminCapability","signature":"func allowNetadminCapability(p *corev1.Pod, containerName string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/profiles.go","code":"// allowNetadminCapability grants NET_ADMIN capability to the container.\nfunc allowNetadminCapability(p *corev1.Pod, containerName string) {\n\tpodutils.VisitContainers(\u0026p.Spec, podutils.AllContainers, func(c *corev1.Container, _ podutils.ContainerType) bool {\n\t\tif c.Name != containerName {\n\t\t\treturn true\n\t\t}\n\t\taddCapability(c, \"NET_ADMIN\")\n\t\treturn false\n\t})\n}","line":{"from":326,"to":335}} {"id":100031805,"name":"addCapability","signature":"func addCapability(c *corev1.Container, capability corev1.Capability)","file":"staging/src/k8s.io/kubectl/pkg/cmd/debug/profiles.go","code":"func addCapability(c *corev1.Container, capability corev1.Capability) {\n\tif c.SecurityContext == nil {\n\t\tc.SecurityContext = \u0026corev1.SecurityContext{}\n\t}\n\tif c.SecurityContext.Capabilities == nil {\n\t\tc.SecurityContext.Capabilities = \u0026corev1.Capabilities{}\n\t}\n\tc.SecurityContext.Capabilities.Add = append(c.SecurityContext.Capabilities.Add, capability)\n}","line":{"from":337,"to":345}} {"id":100031806,"name":"NewCmdDelete","signature":"func NewCmdDelete(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/delete/delete.go","code":"func NewCmdDelete(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\tdeleteFlags := NewDeleteCommandFlags(\"containing the resource to delete.\")\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"delete ([-f FILENAME] | [-k DIRECTORY] | TYPE [(NAME | -l label | --all)])\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Delete resources by file names, stdin, resources and names, or by resources and label selector\"),\n\t\tLong: deleteLong,\n\t\tExample: deleteExample,\n\t\tValidArgsFunction: completion.ResourceTypeAndNameCompletionFunc(f),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\to, err := deleteFlags.ToOptions(nil, streams)\n\t\t\tcmdutil.CheckErr(err)\n\t\t\tcmdutil.CheckErr(o.Complete(f, args, cmd))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.RunDelete(f))\n\t\t},\n\t\tSuggestFor: []string{\"rm\"},\n\t}\n\n\tdeleteFlags.AddFlags(cmd)\n\tcmdutil.AddDryRunFlag(cmd)\n\n\treturn cmd\n}","line":{"from":139,"to":163}} {"id":100031807,"name":"Complete","signature":"func (o *DeleteOptions) Complete(f cmdutil.Factory, args []string, cmd *cobra.Command) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/delete/delete.go","code":"func (o *DeleteOptions) Complete(f cmdutil.Factory, args []string, cmd *cobra.Command) error {\n\tcmdNamespace, enforceNamespace, err := f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.WarnClusterScope = enforceNamespace \u0026\u0026 !o.DeleteAllNamespaces\n\n\tif o.DeleteAll || len(o.LabelSelector) \u003e 0 || len(o.FieldSelector) \u003e 0 {\n\t\tif f := cmd.Flags().Lookup(\"ignore-not-found\"); f != nil \u0026\u0026 !f.Changed {\n\t\t\t// If the user didn't explicitly set the option, default to ignoring NotFound errors when used with --all, -l, or --field-selector\n\t\t\to.IgnoreNotFound = true\n\t\t}\n\t}\n\tif o.DeleteNow {\n\t\tif o.GracePeriod != -1 {\n\t\t\treturn fmt.Errorf(\"--now and --grace-period cannot be specified together\")\n\t\t}\n\t\to.GracePeriod = 1\n\t}\n\tif o.GracePeriod == 0 \u0026\u0026 !o.ForceDeletion {\n\t\t// To preserve backwards compatibility, but prevent accidental data loss, we convert --grace-period=0\n\t\t// into --grace-period=1. Users may provide --force to bypass this conversion.\n\t\to.GracePeriod = 1\n\t}\n\tif o.ForceDeletion \u0026\u0026 o.GracePeriod \u003c 0 {\n\t\to.GracePeriod = 0\n\t}\n\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(o.Raw) == 0 {\n\t\tr := f.NewBuilder().\n\t\t\tUnstructured().\n\t\t\tContinueOnError().\n\t\t\tNamespaceParam(cmdNamespace).DefaultNamespace().\n\t\t\tFilenameParam(enforceNamespace, \u0026o.FilenameOptions).\n\t\t\tLabelSelectorParam(o.LabelSelector).\n\t\t\tFieldSelectorParam(o.FieldSelector).\n\t\t\tSelectAllParam(o.DeleteAll).\n\t\t\tAllNamespaces(o.DeleteAllNamespaces).\n\t\t\tResourceTypeOrNameArgs(false, args...).RequireObject(false).\n\t\t\tFlatten().\n\t\t\tDo()\n\t\terr = r.Err()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\to.Result = r\n\n\t\to.Mapper, err = f.ToRESTMapper()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\to.DynamicClient, err = f.DynamicClient()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Set default WarningPrinter if not already set.\n\tif o.WarningPrinter == nil {\n\t\to.WarningPrinter = printers.NewWarningPrinter(o.ErrOut, printers.WarningPrinterOptions{Color: term.AllowsColorOutput(o.ErrOut)})\n\t}\n\n\treturn nil\n}","line":{"from":165,"to":235}} {"id":100031808,"name":"Validate","signature":"func (o *DeleteOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/delete/delete.go","code":"func (o *DeleteOptions) Validate() error {\n\tif o.Output != \"\" \u0026\u0026 o.Output != \"name\" {\n\t\treturn fmt.Errorf(\"unexpected -o output mode: %v. We only support '-o name'\", o.Output)\n\t}\n\n\tif o.DeleteAll \u0026\u0026 len(o.LabelSelector) \u003e 0 {\n\t\treturn fmt.Errorf(\"cannot set --all and --selector at the same time\")\n\t}\n\tif o.DeleteAll \u0026\u0026 len(o.FieldSelector) \u003e 0 {\n\t\treturn fmt.Errorf(\"cannot set --all and --field-selector at the same time\")\n\t}\n\tif o.WarningPrinter == nil {\n\t\treturn fmt.Errorf(\"WarningPrinter can not be used without initialization\")\n\t}\n\n\tswitch {\n\tcase o.GracePeriod == 0 \u0026\u0026 o.ForceDeletion:\n\t\to.WarningPrinter.Print(\"Immediate deletion does not wait for confirmation that the running resource has been terminated. The resource may continue to run on the cluster indefinitely.\")\n\tcase o.GracePeriod \u003e 0 \u0026\u0026 o.ForceDeletion:\n\t\treturn fmt.Errorf(\"--force and --grace-period greater than 0 cannot be specified together\")\n\t}\n\n\tif len(o.Raw) \u003e 0 {\n\t\tif len(o.FilenameOptions.Filenames) \u003e 1 {\n\t\t\treturn fmt.Errorf(\"--raw can only use a single local file or stdin\")\n\t\t} else if len(o.FilenameOptions.Filenames) == 1 {\n\t\t\tif strings.Index(o.FilenameOptions.Filenames[0], \"http://\") == 0 || strings.Index(o.FilenameOptions.Filenames[0], \"https://\") == 0 {\n\t\t\t\treturn fmt.Errorf(\"--raw cannot read from a url\")\n\t\t\t}\n\t\t}\n\n\t\tif o.FilenameOptions.Recursive {\n\t\t\treturn fmt.Errorf(\"--raw and --recursive are mutually exclusive\")\n\t\t}\n\t\tif len(o.Output) \u003e 0 {\n\t\t\treturn fmt.Errorf(\"--raw and --output are mutually exclusive\")\n\t\t}\n\t\tif _, err := url.ParseRequestURI(o.Raw); err != nil {\n\t\t\treturn fmt.Errorf(\"--raw must be a valid URL path: %v\", err)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":237,"to":280}} {"id":100031809,"name":"RunDelete","signature":"func (o *DeleteOptions) RunDelete(f cmdutil.Factory) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/delete/delete.go","code":"func (o *DeleteOptions) RunDelete(f cmdutil.Factory) error {\n\tif len(o.Raw) \u003e 0 {\n\t\trestClient, err := f.RESTClient()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(o.Filenames) == 0 {\n\t\t\treturn rawhttp.RawDelete(restClient, o.IOStreams, o.Raw, \"\")\n\t\t}\n\t\treturn rawhttp.RawDelete(restClient, o.IOStreams, o.Raw, o.Filenames[0])\n\t}\n\treturn o.DeleteResult(o.Result)\n}","line":{"from":282,"to":294}} {"id":100031810,"name":"DeleteResult","signature":"func (o *DeleteOptions) DeleteResult(r *resource.Result) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/delete/delete.go","code":"func (o *DeleteOptions) DeleteResult(r *resource.Result) error {\n\tfound := 0\n\tif o.IgnoreNotFound {\n\t\tr = r.IgnoreErrors(errors.IsNotFound)\n\t}\n\twarnClusterScope := o.WarnClusterScope\n\tdeletedInfos := []*resource.Info{}\n\tuidMap := cmdwait.UIDMap{}\n\terr := r.Visit(func(info *resource.Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdeletedInfos = append(deletedInfos, info)\n\t\tfound++\n\n\t\toptions := \u0026metav1.DeleteOptions{}\n\t\tif o.GracePeriod \u003e= 0 {\n\t\t\toptions = metav1.NewDeleteOptions(int64(o.GracePeriod))\n\t\t}\n\t\toptions.PropagationPolicy = \u0026o.CascadingStrategy\n\n\t\tif warnClusterScope \u0026\u0026 info.Mapping.Scope.Name() == meta.RESTScopeNameRoot {\n\t\t\to.WarningPrinter.Print(\"deleting cluster-scoped resources, not scoped to the provided namespace\")\n\t\t\twarnClusterScope = false\n\t\t}\n\n\t\tif o.DryRunStrategy == cmdutil.DryRunClient {\n\t\t\tif !o.Quiet {\n\t\t\t\to.PrintObj(info)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\tresponse, err := o.deleteResource(info, options)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresourceLocation := cmdwait.ResourceLocation{\n\t\t\tGroupResource: info.Mapping.Resource.GroupResource(),\n\t\t\tNamespace: info.Namespace,\n\t\t\tName: info.Name,\n\t\t}\n\t\tif status, ok := response.(*metav1.Status); ok \u0026\u0026 status.Details != nil {\n\t\t\tuidMap[resourceLocation] = status.Details.UID\n\t\t\treturn nil\n\t\t}\n\t\tresponseMetadata, err := meta.Accessor(response)\n\t\tif err != nil {\n\t\t\t// we don't have UID, but we didn't fail the delete, next best thing is just skipping the UID\n\t\t\tklog.V(1).Info(err)\n\t\t\treturn nil\n\t\t}\n\t\tuidMap[resourceLocation] = responseMetadata.GetUID()\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tif found == 0 {\n\t\tfmt.Fprintf(o.Out, \"No resources found\\n\")\n\t\treturn nil\n\t}\n\tif !o.WaitForDeletion {\n\t\treturn nil\n\t}\n\t// if we don't have a dynamic client, we don't want to wait. Eventually when delete is cleaned up, this will likely\n\t// drop out.\n\tif o.DynamicClient == nil {\n\t\treturn nil\n\t}\n\n\t// If we are dry-running, then we don't want to wait\n\tif o.DryRunStrategy != cmdutil.DryRunNone {\n\t\treturn nil\n\t}\n\n\teffectiveTimeout := o.Timeout\n\tif effectiveTimeout == 0 {\n\t\t// if we requested to wait forever, set it to a week.\n\t\teffectiveTimeout = 168 * time.Hour\n\t}\n\twaitOptions := cmdwait.WaitOptions{\n\t\tResourceFinder: genericclioptions.ResourceFinderForResult(resource.InfoListVisitor(deletedInfos)),\n\t\tUIDMap: uidMap,\n\t\tDynamicClient: o.DynamicClient,\n\t\tTimeout: effectiveTimeout,\n\n\t\tPrinter: printers.NewDiscardingPrinter(),\n\t\tConditionFn: cmdwait.IsDeleted,\n\t\tIOStreams: o.IOStreams,\n\t}\n\terr = waitOptions.RunWait()\n\tif errors.IsForbidden(err) || errors.IsMethodNotSupported(err) {\n\t\t// if we're forbidden from waiting, we shouldn't fail.\n\t\t// if the resource doesn't support a verb we need, we shouldn't fail.\n\t\tklog.V(1).Info(err)\n\t\treturn nil\n\t}\n\treturn err\n}","line":{"from":296,"to":395}} {"id":100031811,"name":"deleteResource","signature":"func (o *DeleteOptions) deleteResource(info *resource.Info, deleteOptions *metav1.DeleteOptions) (runtime.Object, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/delete/delete.go","code":"func (o *DeleteOptions) deleteResource(info *resource.Info, deleteOptions *metav1.DeleteOptions) (runtime.Object, error) {\n\tdeleteResponse, err := resource.\n\t\tNewHelper(info.Client, info.Mapping).\n\t\tDryRun(o.DryRunStrategy == cmdutil.DryRunServer).\n\t\tDeleteWithOptions(info.Namespace, info.Name, deleteOptions)\n\tif err != nil {\n\t\treturn nil, cmdutil.AddSourceToErr(\"deleting\", info.Source, err)\n\t}\n\n\tif !o.Quiet {\n\t\to.PrintObj(info)\n\t}\n\treturn deleteResponse, nil\n}","line":{"from":397,"to":410}} {"id":100031812,"name":"PrintObj","signature":"func (o *DeleteOptions) PrintObj(info *resource.Info)","file":"staging/src/k8s.io/kubectl/pkg/cmd/delete/delete.go","code":"// PrintObj for deleted objects is special because we do not have an object to print.\n// This mirrors name printer behavior\nfunc (o *DeleteOptions) PrintObj(info *resource.Info) {\n\toperation := \"deleted\"\n\tgroupKind := info.Mapping.GroupVersionKind\n\tkindString := fmt.Sprintf(\"%s.%s\", strings.ToLower(groupKind.Kind), groupKind.Group)\n\tif len(groupKind.Group) == 0 {\n\t\tkindString = strings.ToLower(groupKind.Kind)\n\t}\n\n\tif o.GracePeriod == 0 {\n\t\toperation = \"force deleted\"\n\t}\n\n\tswitch o.DryRunStrategy {\n\tcase cmdutil.DryRunClient:\n\t\toperation = fmt.Sprintf(\"%s (dry run)\", operation)\n\tcase cmdutil.DryRunServer:\n\t\toperation = fmt.Sprintf(\"%s (server dry run)\", operation)\n\t}\n\n\tif o.Output == \"name\" {\n\t\t// -o name: prints resource/name\n\t\tfmt.Fprintf(o.Out, \"%s/%s\\n\", kindString, info.Name)\n\t\treturn\n\t}\n\n\t// understandable output by default\n\tfmt.Fprintf(o.Out, \"%s \\\"%s\\\" %s\\n\", kindString, info.Name, operation)\n}","line":{"from":412,"to":441}} {"id":100031813,"name":"ToOptions","signature":"func (f *DeleteFlags) ToOptions(dynamicClient dynamic.Interface, streams genericclioptions.IOStreams) (*DeleteOptions, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/delete/delete_flags.go","code":"func (f *DeleteFlags) ToOptions(dynamicClient dynamic.Interface, streams genericclioptions.IOStreams) (*DeleteOptions, error) {\n\toptions := \u0026DeleteOptions{\n\t\tDynamicClient: dynamicClient,\n\t\tIOStreams: streams,\n\t}\n\n\t// add filename options\n\tif f.FileNameFlags != nil {\n\t\toptions.FilenameOptions = f.FileNameFlags.ToOptions()\n\t}\n\tif f.LabelSelector != nil {\n\t\toptions.LabelSelector = *f.LabelSelector\n\t}\n\tif f.FieldSelector != nil {\n\t\toptions.FieldSelector = *f.FieldSelector\n\t}\n\n\t// add output format\n\tif f.Output != nil {\n\t\toptions.Output = *f.Output\n\t}\n\n\tif f.All != nil {\n\t\toptions.DeleteAll = *f.All\n\t}\n\tif f.AllNamespaces != nil {\n\t\toptions.DeleteAllNamespaces = *f.AllNamespaces\n\t}\n\tif f.CascadingStrategy != nil {\n\t\tvar err error\n\t\toptions.CascadingStrategy, err = parseCascadingFlag(streams, *f.CascadingStrategy)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif f.Force != nil {\n\t\toptions.ForceDeletion = *f.Force\n\t}\n\tif f.GracePeriod != nil {\n\t\toptions.GracePeriod = *f.GracePeriod\n\t}\n\tif f.IgnoreNotFound != nil {\n\t\toptions.IgnoreNotFound = *f.IgnoreNotFound\n\t}\n\tif f.Now != nil {\n\t\toptions.DeleteNow = *f.Now\n\t}\n\tif f.Timeout != nil {\n\t\toptions.Timeout = *f.Timeout\n\t}\n\tif f.Wait != nil {\n\t\toptions.WaitForDeletion = *f.Wait\n\t}\n\tif f.Raw != nil {\n\t\toptions.Raw = *f.Raw\n\t}\n\n\treturn options, nil\n}","line":{"from":52,"to":110}} {"id":100031814,"name":"AddFlags","signature":"func (f *DeleteFlags) AddFlags(cmd *cobra.Command)","file":"staging/src/k8s.io/kubectl/pkg/cmd/delete/delete_flags.go","code":"func (f *DeleteFlags) AddFlags(cmd *cobra.Command) {\n\tf.FileNameFlags.AddFlags(cmd.Flags())\n\tif f.LabelSelector != nil {\n\t\tcmdutil.AddLabelSelectorFlagVar(cmd, f.LabelSelector)\n\t}\n\tif f.FieldSelector != nil {\n\t\tcmd.Flags().StringVarP(f.FieldSelector, \"field-selector\", \"\", *f.FieldSelector, \"Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector key1=value1,key2=value2). The server only supports a limited number of field queries per type.\")\n\t}\n\tif f.All != nil {\n\t\tcmd.Flags().BoolVar(f.All, \"all\", *f.All, \"Delete all resources, in the namespace of the specified resource types.\")\n\t}\n\tif f.AllNamespaces != nil {\n\t\tcmd.Flags().BoolVarP(f.AllNamespaces, \"all-namespaces\", \"A\", *f.AllNamespaces, \"If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace.\")\n\t}\n\tif f.Force != nil {\n\t\tcmd.Flags().BoolVar(f.Force, \"force\", *f.Force, \"If true, immediately remove resources from API and bypass graceful deletion. Note that immediate deletion of some resources may result in inconsistency or data loss and requires confirmation.\")\n\t}\n\tif f.CascadingStrategy != nil {\n\t\tcmd.Flags().StringVar(\n\t\t\tf.CascadingStrategy,\n\t\t\t\"cascade\",\n\t\t\t*f.CascadingStrategy,\n\t\t\t`Must be \"background\", \"orphan\", or \"foreground\". Selects the deletion cascading strategy for the dependents (e.g. Pods created by a ReplicationController). Defaults to background.`)\n\t\tcmd.Flags().Lookup(\"cascade\").NoOptDefVal = \"background\"\n\t}\n\tif f.Now != nil {\n\t\tcmd.Flags().BoolVar(f.Now, \"now\", *f.Now, \"If true, resources are signaled for immediate shutdown (same as --grace-period=1).\")\n\t}\n\tif f.GracePeriod != nil {\n\t\tcmd.Flags().IntVar(f.GracePeriod, \"grace-period\", *f.GracePeriod, \"Period of time in seconds given to the resource to terminate gracefully. Ignored if negative. Set to 1 for immediate shutdown. Can only be set to 0 when --force is true (force deletion).\")\n\t}\n\tif f.Timeout != nil {\n\t\tcmd.Flags().DurationVar(f.Timeout, \"timeout\", *f.Timeout, \"The length of time to wait before giving up on a delete, zero means determine a timeout from the size of the object\")\n\t}\n\tif f.IgnoreNotFound != nil {\n\t\tcmd.Flags().BoolVar(f.IgnoreNotFound, \"ignore-not-found\", *f.IgnoreNotFound, \"Treat \\\"resource not found\\\" as a successful delete. Defaults to \\\"true\\\" when --all is specified.\")\n\t}\n\tif f.Wait != nil {\n\t\tcmd.Flags().BoolVar(f.Wait, \"wait\", *f.Wait, \"If true, wait for resources to be gone before returning. This waits for finalizers.\")\n\t}\n\tif f.Output != nil {\n\t\tcmd.Flags().StringVarP(f.Output, \"output\", \"o\", *f.Output, \"Output mode. Use \\\"-o name\\\" for shorter output (resource/name).\")\n\t}\n\tif f.Raw != nil {\n\t\tcmd.Flags().StringVar(f.Raw, \"raw\", *f.Raw, \"Raw URI to DELETE to the server. Uses the transport specified by the kubeconfig file.\")\n\t}\n}","line":{"from":112,"to":158}} {"id":100031815,"name":"NewDeleteCommandFlags","signature":"func NewDeleteCommandFlags(usage string) *DeleteFlags","file":"staging/src/k8s.io/kubectl/pkg/cmd/delete/delete_flags.go","code":"// NewDeleteCommandFlags provides default flags and values for use with the \"delete\" command\nfunc NewDeleteCommandFlags(usage string) *DeleteFlags {\n\tcascadingStrategy := \"background\"\n\tgracePeriod := -1\n\n\t// setup command defaults\n\tall := false\n\tallNamespaces := false\n\tforce := false\n\tignoreNotFound := false\n\tnow := false\n\toutput := \"\"\n\tlabelSelector := \"\"\n\tfieldSelector := \"\"\n\ttimeout := time.Duration(0)\n\twait := true\n\traw := \"\"\n\n\tfilenames := []string{}\n\trecursive := false\n\tkustomize := \"\"\n\n\treturn \u0026DeleteFlags{\n\t\t// Not using helpers.go since it provides function to add '-k' for FileNameOptions, but not FileNameFlags\n\t\tFileNameFlags: \u0026genericclioptions.FileNameFlags{Usage: usage, Filenames: \u0026filenames, Kustomize: \u0026kustomize, Recursive: \u0026recursive},\n\t\tLabelSelector: \u0026labelSelector,\n\t\tFieldSelector: \u0026fieldSelector,\n\n\t\tCascadingStrategy: \u0026cascadingStrategy,\n\t\tGracePeriod: \u0026gracePeriod,\n\n\t\tAll: \u0026all,\n\t\tAllNamespaces: \u0026allNamespaces,\n\t\tForce: \u0026force,\n\t\tIgnoreNotFound: \u0026ignoreNotFound,\n\t\tNow: \u0026now,\n\t\tTimeout: \u0026timeout,\n\t\tWait: \u0026wait,\n\t\tOutput: \u0026output,\n\t\tRaw: \u0026raw,\n\t}\n}","line":{"from":160,"to":201}} {"id":100031816,"name":"NewDeleteFlags","signature":"func NewDeleteFlags(usage string) *DeleteFlags","file":"staging/src/k8s.io/kubectl/pkg/cmd/delete/delete_flags.go","code":"// NewDeleteFlags provides default flags and values for use in commands outside of \"delete\"\nfunc NewDeleteFlags(usage string) *DeleteFlags {\n\tcascadingStrategy := \"background\"\n\tgracePeriod := -1\n\n\tforce := false\n\ttimeout := time.Duration(0)\n\twait := false\n\n\tfilenames := []string{}\n\tkustomize := \"\"\n\trecursive := false\n\n\treturn \u0026DeleteFlags{\n\t\tFileNameFlags: \u0026genericclioptions.FileNameFlags{Usage: usage, Filenames: \u0026filenames, Kustomize: \u0026kustomize, Recursive: \u0026recursive},\n\n\t\tCascadingStrategy: \u0026cascadingStrategy,\n\t\tGracePeriod: \u0026gracePeriod,\n\n\t\t// add non-defaults\n\t\tForce: \u0026force,\n\t\tTimeout: \u0026timeout,\n\t\tWait: \u0026wait,\n\t}\n}","line":{"from":203,"to":227}} {"id":100031817,"name":"parseCascadingFlag","signature":"func parseCascadingFlag(streams genericclioptions.IOStreams, cascadingFlag string) (metav1.DeletionPropagation, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/delete/delete_flags.go","code":"func parseCascadingFlag(streams genericclioptions.IOStreams, cascadingFlag string) (metav1.DeletionPropagation, error) {\n\tboolValue, err := strconv.ParseBool(cascadingFlag)\n\t// The flag is not a boolean\n\tif err != nil {\n\t\tswitch cascadingFlag {\n\t\tcase \"orphan\":\n\t\t\treturn metav1.DeletePropagationOrphan, nil\n\t\tcase \"foreground\":\n\t\t\treturn metav1.DeletePropagationForeground, nil\n\t\tcase \"background\":\n\t\t\treturn metav1.DeletePropagationBackground, nil\n\t\tdefault:\n\t\t\treturn metav1.DeletePropagationBackground, fmt.Errorf(`invalid cascade value (%v). Must be \"background\", \"foreground\", or \"orphan\"`, cascadingFlag)\n\t\t}\n\t}\n\t// The flag was a boolean\n\tif boolValue {\n\t\tfmt.Fprintf(streams.ErrOut, \"warning: --cascade=%v is deprecated (boolean value) and can be replaced with --cascade=%s.\\n\", cascadingFlag, \"background\")\n\t\treturn metav1.DeletePropagationBackground, nil\n\t}\n\tfmt.Fprintf(streams.ErrOut, \"warning: --cascade=%v is deprecated (boolean value) and can be replaced with --cascade=%s.\\n\", cascadingFlag, \"orphan\")\n\treturn metav1.DeletePropagationOrphan, nil\n}","line":{"from":229,"to":251}} {"id":100031818,"name":"NewDescribeFlags","signature":"func NewDescribeFlags(f cmdutil.Factory, streams genericclioptions.IOStreams) *DescribeFlags","file":"staging/src/k8s.io/kubectl/pkg/cmd/describe/describe.go","code":"// NewDescribeFlags returns a default DescribeFlags\nfunc NewDescribeFlags(f cmdutil.Factory, streams genericclioptions.IOStreams) *DescribeFlags {\n\treturn \u0026DescribeFlags{\n\t\tFactory: f,\n\t\tFilenameOptions: \u0026resource.FilenameOptions{},\n\t\tDescriberSettings: \u0026describe.DescriberSettings{\n\t\t\tShowEvents: true,\n\t\t\tChunkSize: cmdutil.DefaultChunkSize,\n\t\t},\n\t\tIOStreams: streams,\n\t}\n}","line":{"from":83,"to":94}} {"id":100031819,"name":"AddFlags","signature":"func (flags *DescribeFlags) AddFlags(cmd *cobra.Command)","file":"staging/src/k8s.io/kubectl/pkg/cmd/describe/describe.go","code":"// AddFlags registers flags for a cli\nfunc (flags *DescribeFlags) AddFlags(cmd *cobra.Command) {\n\tcmdutil.AddFilenameOptionFlags(cmd, flags.FilenameOptions, \"containing the resource to describe\")\n\tcmdutil.AddLabelSelectorFlagVar(cmd, \u0026flags.Selector)\n\tcmd.Flags().BoolVarP(\u0026flags.AllNamespaces, \"all-namespaces\", \"A\", flags.AllNamespaces, \"If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace.\")\n\tcmd.Flags().BoolVar(\u0026flags.DescriberSettings.ShowEvents, \"show-events\", flags.DescriberSettings.ShowEvents, \"If true, display events related to the described object.\")\n\tcmdutil.AddChunkSizeFlag(cmd, \u0026flags.DescriberSettings.ChunkSize)\n}","line":{"from":96,"to":103}} {"id":100031820,"name":"ToOptions","signature":"func (flags *DescribeFlags) ToOptions(parent string, args []string) (*DescribeOptions, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/describe/describe.go","code":"// ToOptions converts from CLI inputs to runtime input\nfunc (flags *DescribeFlags) ToOptions(parent string, args []string) (*DescribeOptions, error) {\n\n\tvar err error\n\tnamespace, enforceNamespace, err := flags.Factory.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif flags.AllNamespaces {\n\t\tenforceNamespace = false\n\t}\n\n\tif len(args) == 0 \u0026\u0026 cmdutil.IsFilenameSliceEmpty(flags.FilenameOptions.Filenames, flags.FilenameOptions.Kustomize) {\n\t\treturn nil, fmt.Errorf(\"You must specify the type of resource to describe. %s\\n\", cmdutil.SuggestAPIResources(parent))\n\t}\n\n\tbuilderArgs := args\n\n\tdescriber := func(mapping *meta.RESTMapping) (describe.ResourceDescriber, error) {\n\t\treturn describe.DescriberFn(flags.Factory, mapping)\n\t}\n\n\to := \u0026DescribeOptions{\n\t\tSelector: flags.Selector,\n\t\tNamespace: namespace,\n\t\tDescriber: describer,\n\t\tNewBuilder: flags.Factory.NewBuilder,\n\t\tBuilderArgs: builderArgs,\n\t\tEnforceNamespace: enforceNamespace,\n\t\tAllNamespaces: flags.AllNamespaces,\n\t\tFilenameOptions: flags.FilenameOptions,\n\t\tDescriberSettings: flags.DescriberSettings,\n\t\tIOStreams: flags.IOStreams,\n\t}\n\n\treturn o, nil\n}","line":{"from":105,"to":142}} {"id":100031821,"name":"NewCmdDescribe","signature":"func NewCmdDescribe(parent string, f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/describe/describe.go","code":"func NewCmdDescribe(parent string, f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\tflags := NewDescribeFlags(f, streams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"describe (-f FILENAME | TYPE [NAME_PREFIX | -l label] | TYPE/NAME)\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Show details of a specific resource or group of resources\"),\n\t\tLong: describeLong + \"\\n\\n\" + cmdutil.SuggestAPIResources(parent),\n\t\tExample: describeExample,\n\t\tValidArgsFunction: completion.ResourceTypeAndNameCompletionFunc(f),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\to, err := flags.ToOptions(parent, args)\n\t\t\tcmdutil.CheckErr(err)\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\tflags.AddFlags(cmd)\n\n\treturn cmd\n}","line":{"from":144,"to":165}} {"id":100031822,"name":"Validate","signature":"func (o *DescribeOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/describe/describe.go","code":"func (o *DescribeOptions) Validate() error {\n\treturn nil\n}","line":{"from":167,"to":169}} {"id":100031823,"name":"Run","signature":"func (o *DescribeOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/describe/describe.go","code":"func (o *DescribeOptions) Run() error {\n\tr := o.NewBuilder().\n\t\tUnstructured().\n\t\tContinueOnError().\n\t\tNamespaceParam(o.Namespace).DefaultNamespace().AllNamespaces(o.AllNamespaces).\n\t\tFilenameParam(o.EnforceNamespace, o.FilenameOptions).\n\t\tLabelSelectorParam(o.Selector).\n\t\tResourceTypeOrNameArgs(true, o.BuilderArgs...).\n\t\tRequestChunksOf(o.DescriberSettings.ChunkSize).\n\t\tFlatten().\n\t\tDo()\n\terr := r.Err()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tallErrs := []error{}\n\tinfos, err := r.Infos()\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) \u0026\u0026 len(o.BuilderArgs) == 2 {\n\t\t\treturn o.DescribeMatchingResources(err, o.BuilderArgs[0], o.BuilderArgs[1])\n\t\t}\n\t\tallErrs = append(allErrs, err)\n\t}\n\n\terrs := sets.NewString()\n\tfirst := true\n\tfor _, info := range infos {\n\t\tmapping := info.ResourceMapping()\n\t\tdescriber, err := o.Describer(mapping)\n\t\tif err != nil {\n\t\t\tif errs.Has(err.Error()) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tallErrs = append(allErrs, err)\n\t\t\terrs.Insert(err.Error())\n\t\t\tcontinue\n\t\t}\n\t\ts, err := describer.Describe(info.Namespace, info.Name, *o.DescriberSettings)\n\t\tif err != nil {\n\t\t\tif errs.Has(err.Error()) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tallErrs = append(allErrs, err)\n\t\t\terrs.Insert(err.Error())\n\t\t\tcontinue\n\t\t}\n\t\tif first {\n\t\t\tfirst = false\n\t\t\tfmt.Fprint(o.Out, s)\n\t\t} else {\n\t\t\tfmt.Fprintf(o.Out, \"\\n\\n%s\", s)\n\t\t}\n\t}\n\n\tif len(infos) == 0 \u0026\u0026 len(allErrs) == 0 {\n\t\t// if we wrote no output, and had no errors, be sure we output something.\n\t\tif o.AllNamespaces {\n\t\t\tfmt.Fprintln(o.ErrOut, \"No resources found\")\n\t\t} else {\n\t\t\tfmt.Fprintf(o.ErrOut, \"No resources found in %s namespace.\\n\", o.Namespace)\n\t\t}\n\t}\n\n\treturn utilerrors.NewAggregate(allErrs)\n}","line":{"from":171,"to":236}} {"id":100031824,"name":"DescribeMatchingResources","signature":"func (o *DescribeOptions) DescribeMatchingResources(originalError error, resource, prefix string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/describe/describe.go","code":"func (o *DescribeOptions) DescribeMatchingResources(originalError error, resource, prefix string) error {\n\tr := o.NewBuilder().\n\t\tUnstructured().\n\t\tNamespaceParam(o.Namespace).DefaultNamespace().\n\t\tResourceTypeOrNameArgs(true, resource).\n\t\tSingleResourceType().\n\t\tRequestChunksOf(o.DescriberSettings.ChunkSize).\n\t\tFlatten().\n\t\tDo()\n\tmapping, err := r.ResourceMapping()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdescriber, err := o.Describer(mapping)\n\tif err != nil {\n\t\treturn err\n\t}\n\tinfos, err := r.Infos()\n\tif err != nil {\n\t\treturn err\n\t}\n\tisFound := false\n\tfor ix := range infos {\n\t\tinfo := infos[ix]\n\t\tif strings.HasPrefix(info.Name, prefix) {\n\t\t\tisFound = true\n\t\t\ts, err := describer.Describe(info.Namespace, info.Name, *o.DescriberSettings)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfmt.Fprintf(o.Out, \"%s\\n\", s)\n\t\t}\n\t}\n\tif !isFound {\n\t\treturn originalError\n\t}\n\treturn nil\n}","line":{"from":238,"to":275}} {"id":100031825,"name":"diffError","signature":"func diffError(err error) exec.ExitError","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"// diffError returns the ExitError if the status code is less than 1,\n// nil otherwise.\nfunc diffError(err error) exec.ExitError {\n\tif err, ok := err.(exec.ExitError); ok \u0026\u0026 err.ExitStatus() \u003c= 1 {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":93,"to":100}} {"id":100031826,"name":"NewDiffOptions","signature":"func NewDiffOptions(ioStreams genericclioptions.IOStreams) *DiffOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"func NewDiffOptions(ioStreams genericclioptions.IOStreams) *DiffOptions {\n\treturn \u0026DiffOptions{\n\t\tDiff: \u0026DiffProgram{\n\t\t\tExec: exec.New(),\n\t\t\tIOStreams: ioStreams,\n\t\t},\n\t}\n}","line":{"from":122,"to":129}} {"id":100031827,"name":"NewCmdDiff","signature":"func NewCmdDiff(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"func NewCmdDiff(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\toptions := NewDiffOptions(streams)\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"diff -f FILENAME\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Diff the live version against a would-be applied version\"),\n\t\tLong: diffLong,\n\t\tExample: diffExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckDiffErr(options.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckDiffErr(options.Validate())\n\t\t\t// `kubectl diff` propagates the error code from\n\t\t\t// diff or `KUBECTL_EXTERNAL_DIFF`. Also, we\n\t\t\t// don't want to print an error if diff returns\n\t\t\t// error code 1, which simply means that changes\n\t\t\t// were found. We also don't want kubectl to\n\t\t\t// return 1 if there was a problem.\n\t\t\tif err := options.Run(); err != nil {\n\t\t\t\tif exitErr := diffError(err); exitErr != nil {\n\t\t\t\t\tcmdutil.CheckErr(cmdutil.ErrExit)\n\t\t\t\t}\n\t\t\t\tcmdutil.CheckDiffErr(err)\n\t\t\t}\n\t\t},\n\t}\n\n\t// Flag errors exit with code 1, however according to the diff\n\t// command it means changes were found.\n\t// Thus, it should return status code greater than 1.\n\tcmd.SetFlagErrorFunc(func(command *cobra.Command, err error) error {\n\t\tcmdutil.CheckDiffErr(cmdutil.UsageErrorf(cmd, err.Error()))\n\t\treturn nil\n\t})\n\n\tusage := \"contains the configuration to diff\"\n\tcmd.Flags().StringArray(\"prune-allowlist\", []string{}, \"Overwrite the default whitelist with \u003cgroup/version/kind\u003e for --prune\")\n\tcmd.Flags().Bool(\"prune\", false, \"Include resources that would be deleted by pruning. Can be used with -l and default shows all resources would be pruned\")\n\tcmd.Flags().BoolVar(\u0026options.ShowManagedFields, \"show-managed-fields\", options.ShowManagedFields, \"If true, include managed fields in the diff.\")\n\tcmdutil.AddFilenameOptionFlags(cmd, \u0026options.FilenameOptions, usage)\n\tcmdutil.AddServerSideApplyFlags(cmd)\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026options.FieldManager, apply.FieldManagerClientSideApply)\n\tcmdutil.AddLabelSelectorFlagVar(cmd, \u0026options.Selector)\n\n\treturn cmd\n}","line":{"from":131,"to":175}} {"id":100031828,"name":"getCommand","signature":"func (d *DiffProgram) getCommand(args ...string) (string, exec.Cmd)","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"func (d *DiffProgram) getCommand(args ...string) (string, exec.Cmd) {\n\tdiff := \"\"\n\tif envDiff := os.Getenv(\"KUBECTL_EXTERNAL_DIFF\"); envDiff != \"\" {\n\t\tdiffCommand := strings.Split(envDiff, \" \")\n\t\tdiff = diffCommand[0]\n\n\t\tif len(diffCommand) \u003e 1 {\n\t\t\t// Regex accepts: Alphanumeric (case-insensitive), dash and equal\n\t\t\tisValidChar := regexp.MustCompile(`^[a-zA-Z0-9-=]+$`).MatchString\n\t\t\tfor i := 1; i \u003c len(diffCommand); i++ {\n\t\t\t\tif isValidChar(diffCommand[i]) {\n\t\t\t\t\targs = append(args, diffCommand[i])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tdiff = \"diff\"\n\t\targs = append([]string{\"-u\", \"-N\"}, args...)\n\t}\n\n\tcmd := d.Exec.Command(diff, args...)\n\tcmd.SetStdout(d.Out)\n\tcmd.SetStderr(d.ErrOut)\n\n\treturn diff, cmd\n}","line":{"from":185,"to":210}} {"id":100031829,"name":"Run","signature":"func (d *DiffProgram) Run(from, to string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"// Run runs the detected diff program. `from` and `to` are the directory to diff.\nfunc (d *DiffProgram) Run(from, to string) error {\n\tdiff, cmd := d.getCommand(from, to)\n\tif err := cmd.Run(); err != nil {\n\t\t// Let's not wrap diff errors, or we won't be able to\n\t\t// differentiate them later.\n\t\tif diffErr := diffError(err); diffErr != nil {\n\t\t\treturn diffErr\n\t\t}\n\t\treturn fmt.Errorf(\"failed to run %q: %v\", diff, err)\n\t}\n\treturn nil\n}","line":{"from":212,"to":224}} {"id":100031830,"name":"Print","signature":"func (p *Printer) Print(obj runtime.Object, w io.Writer) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"// Print the object inside the writer w.\nfunc (p *Printer) Print(obj runtime.Object, w io.Writer) error {\n\tif obj == nil {\n\t\treturn nil\n\t}\n\tdata, err := yaml.Marshal(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = w.Write(data)\n\treturn err\n\n}","line":{"from":229,"to":241}} {"id":100031831,"name":"NewDiffVersion","signature":"func NewDiffVersion(name string) (*DiffVersion, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"// NewDiffVersion creates a new DiffVersion with the named version.\nfunc NewDiffVersion(name string) (*DiffVersion, error) {\n\tdir, err := CreateDirectory(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026DiffVersion{\n\t\tDir: dir,\n\t\tName: name,\n\t}, nil\n}","line":{"from":249,"to":259}} {"id":100031832,"name":"getObject","signature":"func (v *DiffVersion) getObject(obj Object) (runtime.Object, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"func (v *DiffVersion) getObject(obj Object) (runtime.Object, error) {\n\tswitch v.Name {\n\tcase \"LIVE\":\n\t\treturn obj.Live(), nil\n\tcase \"MERGED\":\n\t\treturn obj.Merged()\n\t}\n\treturn nil, fmt.Errorf(\"Unknown version: %v\", v.Name)\n}","line":{"from":261,"to":269}} {"id":100031833,"name":"Print","signature":"func (v *DiffVersion) Print(name string, obj runtime.Object, printer Printer) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"// Print prints the object using the printer into a new file in the directory.\nfunc (v *DiffVersion) Print(name string, obj runtime.Object, printer Printer) error {\n\tf, err := v.Dir.NewFile(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\treturn printer.Print(obj, f)\n}","line":{"from":271,"to":279}} {"id":100031834,"name":"CreateDirectory","signature":"func CreateDirectory(prefix string) (*Directory, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"// CreateDirectory does create the actual disk directory, and return a\n// new representation of it.\nfunc CreateDirectory(prefix string) (*Directory, error) {\n\tname, err := os.MkdirTemp(\"\", prefix+\"-\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026Directory{\n\t\tName: name,\n\t}, nil\n}","line":{"from":286,"to":297}} {"id":100031835,"name":"NewFile","signature":"func (d *Directory) NewFile(name string) (*os.File, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"// NewFile creates a new file in the directory.\nfunc (d *Directory) NewFile(name string) (*os.File, error) {\n\treturn os.OpenFile(filepath.Join(d.Name, name), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0700)\n}","line":{"from":299,"to":302}} {"id":100031836,"name":"Delete","signature":"func (d *Directory) Delete() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"// Delete removes the directory recursively.\nfunc (d *Directory) Delete() error {\n\treturn os.RemoveAll(d.Name)\n}","line":{"from":304,"to":307}} {"id":100031837,"name":"Live","signature":"func (obj InfoObject) Live() runtime.Object","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"// Returns the live version of the object\nfunc (obj InfoObject) Live() runtime.Object {\n\treturn obj.Info.Object\n}","line":{"from":334,"to":337}} {"id":100031838,"name":"Merged","signature":"func (obj InfoObject) Merged() (runtime.Object, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"// Returns the \"merged\" object, as it would look like if applied or\n// created.\nfunc (obj InfoObject) Merged() (runtime.Object, error) {\n\thelper := resource.NewHelper(obj.Info.Client, obj.Info.Mapping).\n\t\tDryRun(true).\n\t\tWithFieldManager(obj.FieldManager)\n\tif obj.ServerSideApply {\n\t\tdata, err := runtime.Encode(unstructured.UnstructuredJSONScheme, obj.LocalObj)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\toptions := metav1.PatchOptions{\n\t\t\tForce: \u0026obj.ForceConflicts,\n\t\t\tFieldManager: obj.FieldManager,\n\t\t}\n\t\treturn helper.Patch(\n\t\t\tobj.Info.Namespace,\n\t\t\tobj.Info.Name,\n\t\t\ttypes.ApplyPatchType,\n\t\t\tdata,\n\t\t\t\u0026options,\n\t\t)\n\t}\n\n\t// Build the patcher, and then apply the patch with dry-run, unless the object doesn't exist, in which case we need to create it.\n\tif obj.Live() == nil {\n\t\t// Dry-run create if the object doesn't exist.\n\t\treturn helper.CreateWithOptions(\n\t\t\tobj.Info.Namespace,\n\t\t\ttrue,\n\t\t\tobj.LocalObj,\n\t\t\t\u0026metav1.CreateOptions{},\n\t\t)\n\t}\n\n\tvar resourceVersion *string\n\tif !obj.Force {\n\t\taccessor, err := meta.Accessor(obj.Info.Object)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstr := accessor.GetResourceVersion()\n\t\tresourceVersion = \u0026str\n\t}\n\n\tmodified, err := util.GetModifiedConfiguration(obj.LocalObj, false, unstructured.UnstructuredJSONScheme)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// This is using the patcher from apply, to keep the same behavior.\n\t// We plan on replacing this with server-side apply when it becomes available.\n\tpatcher := \u0026apply.Patcher{\n\t\tMapping: obj.Info.Mapping,\n\t\tHelper: helper,\n\t\tOverwrite: true,\n\t\tBackOff: clockwork.NewRealClock(),\n\t\tOpenapiSchema: obj.OpenAPI,\n\t\tResourceVersion: resourceVersion,\n\t}\n\n\t_, result, err := patcher.Patch(obj.Info.Object, modified, obj.Info.Source, obj.Info.Namespace, obj.Info.Name, obj.ErrOut)\n\treturn result, err\n}","line":{"from":339,"to":402}} {"id":100031839,"name":"Name","signature":"func (obj InfoObject) Name() string","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"func (obj InfoObject) Name() string {\n\tgroup := \"\"\n\tif obj.Info.Mapping.GroupVersionKind.Group != \"\" {\n\t\tgroup = fmt.Sprintf(\"%v.\", obj.Info.Mapping.GroupVersionKind.Group)\n\t}\n\treturn group + fmt.Sprintf(\n\t\t\"%v.%v.%v.%v\",\n\t\tobj.Info.Mapping.GroupVersionKind.Version,\n\t\tobj.Info.Mapping.GroupVersionKind.Kind,\n\t\tobj.Info.Namespace,\n\t\tobj.Info.Name,\n\t)\n}","line":{"from":404,"to":416}} {"id":100031840,"name":"toUnstructured","signature":"func toUnstructured(obj runtime.Object) (*unstructured.Unstructured, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"// toUnstructured converts a runtime.Object into an unstructured.Unstructured object.\nfunc toUnstructured(obj runtime.Object) (*unstructured.Unstructured, error) {\n\tif obj == nil {\n\t\treturn nil, nil\n\t}\n\tc, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj.DeepCopyObject())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"convert to unstructured: %w\", err)\n\t}\n\tu := \u0026unstructured.Unstructured{}\n\tu.SetUnstructuredContent(c)\n\treturn u, nil\n}","line":{"from":418,"to":430}} {"id":100031841,"name":"NewMasker","signature":"func NewMasker(from, to runtime.Object) (*Masker, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"func NewMasker(from, to runtime.Object) (*Masker, error) {\n\t// Convert objects to unstructured\n\tf, err := toUnstructured(from)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"convert to unstructured: %w\", err)\n\t}\n\tt, err := toUnstructured(to)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"convert to unstructured: %w\", err)\n\t}\n\n\t// Run masker\n\tm := \u0026Masker{\n\t\tfrom: f,\n\t\tto: t,\n\t}\n\tif err := m.run(); err != nil {\n\t\treturn nil, fmt.Errorf(\"run masker: %w\", err)\n\t}\n\treturn m, nil\n}","line":{"from":443,"to":463}} {"id":100031842,"name":"dataFromUnstructured","signature":"func (m Masker) dataFromUnstructured(u *unstructured.Unstructured) (map[string]interface{}, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"// dataFromUnstructured returns the underlying nested map in the data key.\nfunc (m Masker) dataFromUnstructured(u *unstructured.Unstructured) (map[string]interface{}, error) {\n\tif u == nil {\n\t\treturn nil, nil\n\t}\n\tdata, found, err := unstructured.NestedMap(u.UnstructuredContent(), \"data\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"get nested map: %w\", err)\n\t}\n\tif !found {\n\t\treturn nil, nil\n\t}\n\treturn data, nil\n}","line":{"from":465,"to":478}} {"id":100031843,"name":"run","signature":"func (m *Masker) run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"// run compares and patches sensitive values.\nfunc (m *Masker) run() error {\n\t// Extract nested map object\n\tfrom, err := m.dataFromUnstructured(m.from)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"extract 'data' field: %w\", err)\n\t}\n\tto, err := m.dataFromUnstructured(m.to)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"extract 'data' field: %w\", err)\n\t}\n\n\tfor k := range from {\n\t\t// Add before/after suffix when key exists on both\n\t\t// objects and are not equal, so that it will be\n\t\t// visible in diffs.\n\t\tif _, ok := to[k]; ok {\n\t\t\tif from[k] != to[k] {\n\t\t\t\tfrom[k] = sensitiveMaskBefore\n\t\t\t\tto[k] = sensitiveMaskAfter\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tto[k] = sensitiveMaskDefault\n\t\t}\n\t\tfrom[k] = sensitiveMaskDefault\n\t}\n\tfor k := range to {\n\t\t// Mask remaining keys that were not in 'from'\n\t\tif _, ok := from[k]; !ok {\n\t\t\tto[k] = sensitiveMaskDefault\n\t\t}\n\t}\n\n\t// Patch objects with masked data\n\tif m.from != nil \u0026\u0026 from != nil {\n\t\tif err := unstructured.SetNestedMap(m.from.UnstructuredContent(), from, \"data\"); err != nil {\n\t\t\treturn fmt.Errorf(\"patch masked data: %w\", err)\n\t\t}\n\t}\n\tif m.to != nil \u0026\u0026 to != nil {\n\t\tif err := unstructured.SetNestedMap(m.to.UnstructuredContent(), to, \"data\"); err != nil {\n\t\t\treturn fmt.Errorf(\"patch masked data: %w\", err)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":480,"to":525}} {"id":100031844,"name":"From","signature":"func (m *Masker) From() runtime.Object","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"// From returns the masked version of the 'from' object.\nfunc (m *Masker) From() runtime.Object {\n\treturn m.from\n}","line":{"from":527,"to":530}} {"id":100031845,"name":"To","signature":"func (m *Masker) To() runtime.Object","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"// To returns the masked version of the 'to' object.\nfunc (m *Masker) To() runtime.Object {\n\treturn m.to\n}","line":{"from":532,"to":535}} {"id":100031846,"name":"NewDiffer","signature":"func NewDiffer(from, to string) (*Differ, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"func NewDiffer(from, to string) (*Differ, error) {\n\tdiffer := Differ{}\n\tvar err error\n\tdiffer.From, err = NewDiffVersion(from)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdiffer.To, err = NewDiffVersion(to)\n\tif err != nil {\n\t\tdiffer.From.Dir.Delete()\n\t\treturn nil, err\n\t}\n\n\treturn \u0026differ, nil\n}","line":{"from":543,"to":557}} {"id":100031847,"name":"Diff","signature":"func (d *Differ) Diff(obj Object, printer Printer, showManagedFields bool) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"// Diff diffs to versions of a specific object, and print both versions to directories.\nfunc (d *Differ) Diff(obj Object, printer Printer, showManagedFields bool) error {\n\tfrom, err := d.From.getObject(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\tto, err := d.To.getObject(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !showManagedFields {\n\t\tfrom = omitManagedFields(from)\n\t\tto = omitManagedFields(to)\n\t}\n\n\t// Mask secret values if object is V1Secret\n\tif gvk := to.GetObjectKind().GroupVersionKind(); gvk.Version == \"v1\" \u0026\u0026 gvk.Kind == \"Secret\" {\n\t\tm, err := NewMasker(from, to)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfrom, to = m.From(), m.To()\n\t}\n\n\tif err := d.From.Print(obj.Name(), from, printer); err != nil {\n\t\treturn err\n\t}\n\tif err := d.To.Print(obj.Name(), to, printer); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":559,"to":591}} {"id":100031848,"name":"omitManagedFields","signature":"func omitManagedFields(o runtime.Object) runtime.Object","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"func omitManagedFields(o runtime.Object) runtime.Object {\n\ta, err := meta.Accessor(o)\n\tif err != nil {\n\t\t// The object is not a `metav1.Object`, ignore it.\n\t\treturn o\n\t}\n\ta.SetManagedFields(nil)\n\treturn o\n}","line":{"from":593,"to":601}} {"id":100031849,"name":"Run","signature":"func (d *Differ) Run(diff *DiffProgram) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"// Run runs the diff program against both directories.\nfunc (d *Differ) Run(diff *DiffProgram) error {\n\treturn diff.Run(d.From.Dir.Name, d.To.Dir.Name)\n}","line":{"from":603,"to":606}} {"id":100031850,"name":"TearDown","signature":"func (d *Differ) TearDown()","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"// TearDown removes both temporary directories recursively.\nfunc (d *Differ) TearDown() {\n\td.From.Dir.Delete() // Ignore error\n\td.To.Dir.Delete() // Ignore error\n}","line":{"from":608,"to":612}} {"id":100031851,"name":"isConflict","signature":"func isConflict(err error) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"func isConflict(err error) bool {\n\treturn err != nil \u0026\u0026 errors.IsConflict(err)\n}","line":{"from":614,"to":616}} {"id":100031852,"name":"Complete","signature":"func (o *DiffOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"func (o *DiffOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tif len(args) != 0 {\n\t\treturn cmdutil.UsageErrorf(cmd, \"Unexpected args: %v\", args)\n\t}\n\n\tvar err error\n\n\terr = o.FilenameOptions.RequireFilenameOrKustomize()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.ServerSideApply = cmdutil.GetServerSideApplyFlag(cmd)\n\to.FieldManager = apply.GetApplyFieldManagerFlag(cmd, o.ServerSideApply)\n\to.ForceConflicts = cmdutil.GetForceConflictsFlag(cmd)\n\tif o.ForceConflicts \u0026\u0026 !o.ServerSideApply {\n\t\treturn fmt.Errorf(\"--force-conflicts only works with --server-side\")\n\t}\n\n\tif !o.ServerSideApply {\n\t\to.OpenAPISchema, err = f.OpenAPISchema()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\to.DynamicClient, err = f.DynamicClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.CmdNamespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif cmdutil.GetFlagBool(cmd, \"prune\") {\n\t\tmapper, err := f.ToRESTMapper()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tresources, err := prune.ParseResources(mapper, cmdutil.GetFlagStringArray(cmd, \"prune-allowlist\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\to.tracker = newTracker()\n\t\to.pruner = newPruner(o.DynamicClient, mapper, resources, o.Selector)\n\t}\n\n\to.Builder = f.NewBuilder()\n\treturn nil\n}","line":{"from":618,"to":670}} {"id":100031853,"name":"Run","signature":"func (o *DiffOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"// Run uses the factory to parse file arguments, find the version to\n// diff, and find each Info object for each files, and runs against the\n// differ.\nfunc (o *DiffOptions) Run() error {\n\tdiffer, err := NewDiffer(\"LIVE\", \"MERGED\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer differ.TearDown()\n\n\tprinter := Printer{}\n\n\tr := o.Builder.\n\t\tUnstructured().\n\t\tNamespaceParam(o.CmdNamespace).DefaultNamespace().\n\t\tFilenameParam(o.EnforceNamespace, \u0026o.FilenameOptions).\n\t\tLabelSelectorParam(o.Selector).\n\t\tFlatten().\n\t\tDo()\n\tif err := r.Err(); err != nil {\n\t\treturn err\n\t}\n\n\terr = r.Visit(func(info *resource.Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlocal := info.Object.DeepCopyObject()\n\t\tfor i := 1; i \u003c= maxRetries; i++ {\n\t\t\tif err = info.Get(); err != nil {\n\t\t\t\tif !errors.IsNotFound(err) {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tinfo.Object = nil\n\t\t\t}\n\n\t\t\tforce := i == maxRetries\n\t\t\tif force {\n\t\t\t\tklog.Warningf(\n\t\t\t\t\t\"Object (%v: %v) keeps changing, diffing without lock\",\n\t\t\t\t\tinfo.Object.GetObjectKind().GroupVersionKind(),\n\t\t\t\t\tinfo.Name,\n\t\t\t\t)\n\t\t\t}\n\t\t\tobj := InfoObject{\n\t\t\t\tLocalObj: local,\n\t\t\t\tInfo: info,\n\t\t\t\tEncoder: scheme.DefaultJSONEncoder(),\n\t\t\t\tOpenAPI: o.OpenAPISchema,\n\t\t\t\tForce: force,\n\t\t\t\tServerSideApply: o.ServerSideApply,\n\t\t\t\tFieldManager: o.FieldManager,\n\t\t\t\tForceConflicts: o.ForceConflicts,\n\t\t\t\tIOStreams: o.Diff.IOStreams,\n\t\t\t}\n\n\t\t\tif o.tracker != nil {\n\t\t\t\to.tracker.MarkVisited(info)\n\t\t\t}\n\n\t\t\terr = differ.Diff(obj, printer, o.ShowManagedFields)\n\t\t\tif !isConflict(err) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tapply.WarnIfDeleting(info.Object, o.Diff.ErrOut)\n\n\t\treturn err\n\t})\n\n\tif o.pruner != nil {\n\t\tprunedObjs, err := o.pruner.pruneAll(o.tracker, o.CmdNamespace != \"\")\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"pruning failed and could not be evaluated err: %v\", err)\n\t\t}\n\n\t\t// Print pruned objects into old file and thus, diff\n\t\t// command will show them as pruned.\n\t\tfor _, p := range prunedObjs {\n\t\t\tname, err := getObjectName(p)\n\t\t\tif err != nil {\n\t\t\t\tklog.Warningf(\"pruning failed and object name could not be retrieved: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := differ.From.Print(name, p, printer); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn differ.Run(o.Diff)\n}","line":{"from":672,"to":769}} {"id":100031854,"name":"Validate","signature":"func (o *DiffOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"// Validate makes sure provided values for DiffOptions are valid\nfunc (o *DiffOptions) Validate() error {\n\treturn nil\n}","line":{"from":771,"to":774}} {"id":100031855,"name":"getObjectName","signature":"func getObjectName(obj runtime.Object) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/diff.go","code":"func getObjectName(obj runtime.Object) (string, error) {\n\tgvk := obj.GetObjectKind().GroupVersionKind()\n\tmetadata, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tname := metadata.GetName()\n\tns := metadata.GetNamespace()\n\n\tgroup := \"\"\n\tif gvk.Group != \"\" {\n\t\tgroup = fmt.Sprintf(\"%v.\", gvk.Group)\n\t}\n\treturn group + fmt.Sprintf(\n\t\t\"%v.%v.%v.%v\",\n\t\tgvk.Version,\n\t\tgvk.Kind,\n\t\tns,\n\t\tname,\n\t), nil\n}","line":{"from":776,"to":796}} {"id":100031856,"name":"newTracker","signature":"func newTracker() *tracker","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/prune.go","code":"func newTracker() *tracker {\n\treturn \u0026tracker{\n\t\tvisitedUids: sets.New[types.UID](),\n\t\tvisitedNamespaces: sets.New[string](),\n\t}\n}","line":{"from":39,"to":44}} {"id":100031857,"name":"newPruner","signature":"func newPruner(dc dynamic.Interface, m meta.RESTMapper, r []prune.Resource, selector string) *pruner","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/prune.go","code":"func newPruner(dc dynamic.Interface, m meta.RESTMapper, r []prune.Resource, selector string) *pruner {\n\treturn \u0026pruner{\n\t\tdynamicClient: dc,\n\t\tmapper: m,\n\t\tresources: r,\n\t\tlabelSelector: selector,\n\t}\n}","line":{"from":54,"to":61}} {"id":100031858,"name":"pruneAll","signature":"func (p *pruner) pruneAll(tracker *tracker, namespaceSpecified bool) ([]runtime.Object, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/prune.go","code":"func (p *pruner) pruneAll(tracker *tracker, namespaceSpecified bool) ([]runtime.Object, error) {\n\tvar allPruned []runtime.Object\n\tnamespacedRESTMappings, nonNamespacedRESTMappings, err := prune.GetRESTMappings(p.mapper, p.resources, namespaceSpecified)\n\tif err != nil {\n\t\treturn allPruned, fmt.Errorf(\"error retrieving RESTMappings to prune: %v\", err)\n\t}\n\n\tfor n := range tracker.visitedNamespaces {\n\t\tfor _, m := range namespacedRESTMappings {\n\t\t\tif pobjs, err := p.prune(tracker, n, m); err != nil {\n\t\t\t\treturn pobjs, fmt.Errorf(\"error pruning namespaced object %v: %v\", m.GroupVersionKind, err)\n\t\t\t} else {\n\t\t\t\tallPruned = append(allPruned, pobjs...)\n\t\t\t}\n\t\t}\n\t}\n\tfor _, m := range nonNamespacedRESTMappings {\n\t\tif pobjs, err := p.prune(tracker, metav1.NamespaceNone, m); err != nil {\n\t\t\treturn allPruned, fmt.Errorf(\"error pruning nonNamespaced object %v: %v\", m.GroupVersionKind, err)\n\t\t} else {\n\t\t\tallPruned = append(allPruned, pobjs...)\n\t\t}\n\t}\n\n\treturn allPruned, nil\n}","line":{"from":63,"to":88}} {"id":100031859,"name":"prune","signature":"func (p *pruner) prune(tracker *tracker, namespace string, mapping *meta.RESTMapping) ([]runtime.Object, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/prune.go","code":"func (p *pruner) prune(tracker *tracker, namespace string, mapping *meta.RESTMapping) ([]runtime.Object, error) {\n\tobjList, err := p.dynamicClient.Resource(mapping.Resource).\n\t\tNamespace(namespace).\n\t\tList(context.TODO(), metav1.ListOptions{\n\t\t\tLabelSelector: p.labelSelector,\n\t\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tobjs, err := meta.ExtractList(objList)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar pobjs []runtime.Object\n\tfor _, obj := range objs {\n\t\tmetadata, err := meta.Accessor(obj)\n\t\tif err != nil {\n\t\t\treturn pobjs, err\n\t\t}\n\t\tannots := metadata.GetAnnotations()\n\t\tif _, ok := annots[corev1.LastAppliedConfigAnnotation]; !ok {\n\t\t\tcontinue\n\t\t}\n\t\tuid := metadata.GetUID()\n\t\tif tracker.visitedUids.Has(uid) {\n\t\t\tcontinue\n\t\t}\n\n\t\tpobjs = append(pobjs, obj)\n\t}\n\treturn pobjs, nil\n}","line":{"from":90,"to":123}} {"id":100031860,"name":"MarkVisited","signature":"func (t *tracker) MarkVisited(info *resource.Info)","file":"staging/src/k8s.io/kubectl/pkg/cmd/diff/prune.go","code":"// MarkVisited marks visited namespaces and uids\nfunc (t *tracker) MarkVisited(info *resource.Info) {\n\tif info.Namespaced() {\n\t\tt.visitedNamespaces.Insert(info.Namespace)\n\t}\n\n\tmetadata, err := meta.Accessor(info.Object)\n\tif err != nil {\n\t\treturn\n\t}\n\tt.visitedUids.Insert(metadata.GetUID())\n}","line":{"from":125,"to":136}} {"id":100031861,"name":"NewCmdCordon","signature":"func NewCmdCordon(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/drain/drain.go","code":"func NewCmdCordon(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewDrainCmdOptions(f, ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"cordon NODE\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Mark node as unschedulable\"),\n\t\tLong: cordonLong,\n\t\tExample: cordonExample,\n\t\tValidArgsFunction: completion.ResourceNameCompletionFunc(f, \"node\"),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.RunCordonOrUncordon(true))\n\t\t},\n\t}\n\tcmdutil.AddLabelSelectorFlagVar(cmd, \u0026o.drainer.Selector)\n\tcmdutil.AddDryRunFlag(cmd)\n\treturn cmd\n}","line":{"from":64,"to":82}} {"id":100031862,"name":"NewCmdUncordon","signature":"func NewCmdUncordon(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/drain/drain.go","code":"func NewCmdUncordon(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewDrainCmdOptions(f, ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"uncordon NODE\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Mark node as schedulable\"),\n\t\tLong: uncordonLong,\n\t\tExample: uncordonExample,\n\t\tValidArgsFunction: completion.ResourceNameCompletionFunc(f, \"node\"),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.RunCordonOrUncordon(false))\n\t\t},\n\t}\n\tcmdutil.AddLabelSelectorFlagVar(cmd, \u0026o.drainer.Selector)\n\tcmdutil.AddDryRunFlag(cmd)\n\treturn cmd\n}","line":{"from":93,"to":111}} {"id":100031863,"name":"NewDrainCmdOptions","signature":"func NewDrainCmdOptions(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *DrainCmdOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/drain/drain.go","code":"func NewDrainCmdOptions(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *DrainCmdOptions {\n\to := \u0026DrainCmdOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"drained\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: ioStreams,\n\t\tdrainer: \u0026drain.Helper{\n\t\t\tGracePeriodSeconds: -1,\n\t\t\tOut: ioStreams.Out,\n\t\t\tErrOut: ioStreams.ErrOut,\n\t\t\tChunkSize: cmdutil.DefaultChunkSize,\n\t\t},\n\t}\n\to.drainer.OnPodDeletedOrEvicted = o.onPodDeletedOrEvicted\n\treturn o\n}","line":{"from":147,"to":160}} {"id":100031864,"name":"onPodDeletedOrEvicted","signature":"func (o *DrainCmdOptions) onPodDeletedOrEvicted(pod *corev1.Pod, usingEviction bool)","file":"staging/src/k8s.io/kubectl/pkg/cmd/drain/drain.go","code":"// onPodDeletedOrEvicted is called by drain.Helper, when the pod has been deleted or evicted\nfunc (o *DrainCmdOptions) onPodDeletedOrEvicted(pod *corev1.Pod, usingEviction bool) {\n\tvar verbStr string\n\tif usingEviction {\n\t\tverbStr = \"evicted\"\n\t} else {\n\t\tverbStr = \"deleted\"\n\t}\n\tprintObj, err := o.ToPrinter(verbStr)\n\tif err != nil {\n\t\tfmt.Fprintf(o.ErrOut, \"error building printer: %v\\n\", err)\n\t\tfmt.Fprintf(o.Out, \"pod %s/%s %s\\n\", pod.Namespace, pod.Name, verbStr)\n\t} else {\n\t\tprintObj(pod, o.Out)\n\t}\n}","line":{"from":162,"to":177}} {"id":100031865,"name":"NewCmdDrain","signature":"func NewCmdDrain(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/drain/drain.go","code":"func NewCmdDrain(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewDrainCmdOptions(f, ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"drain NODE\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Drain node in preparation for maintenance\"),\n\t\tLong: drainLong,\n\t\tExample: drainExample,\n\t\tValidArgsFunction: completion.ResourceNameCompletionFunc(f, \"node\"),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.RunDrain())\n\t\t},\n\t}\n\tcmd.Flags().BoolVar(\u0026o.drainer.Force, \"force\", o.drainer.Force, \"Continue even if there are pods that do not declare a controller.\")\n\tcmd.Flags().BoolVar(\u0026o.drainer.IgnoreAllDaemonSets, \"ignore-daemonsets\", o.drainer.IgnoreAllDaemonSets, \"Ignore DaemonSet-managed pods.\")\n\tcmd.Flags().BoolVar(\u0026o.drainer.DeleteEmptyDirData, \"delete-local-data\", o.drainer.DeleteEmptyDirData, \"Continue even if there are pods using emptyDir (local data that will be deleted when the node is drained).\")\n\tcmd.Flags().MarkDeprecated(\"delete-local-data\", \"This option is deprecated and will be deleted. Use --delete-emptydir-data.\")\n\tcmd.Flags().BoolVar(\u0026o.drainer.DeleteEmptyDirData, \"delete-emptydir-data\", o.drainer.DeleteEmptyDirData, \"Continue even if there are pods using emptyDir (local data that will be deleted when the node is drained).\")\n\tcmd.Flags().IntVar(\u0026o.drainer.GracePeriodSeconds, \"grace-period\", o.drainer.GracePeriodSeconds, \"Period of time in seconds given to each pod to terminate gracefully. If negative, the default value specified in the pod will be used.\")\n\tcmd.Flags().DurationVar(\u0026o.drainer.Timeout, \"timeout\", o.drainer.Timeout, \"The length of time to wait before giving up, zero means infinite\")\n\tcmd.Flags().StringVarP(\u0026o.drainer.PodSelector, \"pod-selector\", \"\", o.drainer.PodSelector, \"Label selector to filter pods on the node\")\n\tcmd.Flags().BoolVar(\u0026o.drainer.DisableEviction, \"disable-eviction\", o.drainer.DisableEviction, \"Force drain to use delete, even if eviction is supported. This will bypass checking PodDisruptionBudgets, use with caution.\")\n\tcmd.Flags().IntVar(\u0026o.drainer.SkipWaitForDeleteTimeoutSeconds, \"skip-wait-for-delete-timeout\", o.drainer.SkipWaitForDeleteTimeoutSeconds, \"If pod DeletionTimestamp older than N seconds, skip waiting for the pod. Seconds must be greater than 0 to skip.\")\n\n\tcmdutil.AddChunkSizeFlag(cmd, \u0026o.drainer.ChunkSize)\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmdutil.AddLabelSelectorFlagVar(cmd, \u0026o.drainer.Selector)\n\treturn cmd\n}","line":{"from":179,"to":209}} {"id":100031866,"name":"Complete","signature":"func (o *DrainCmdOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/drain/drain.go","code":"// Complete populates some fields from the factory, grabs command line\n// arguments and looks up the node using Builder\nfunc (o *DrainCmdOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\n\tif len(args) == 0 \u0026\u0026 !cmd.Flags().Changed(\"selector\") {\n\t\treturn cmdutil.UsageErrorf(cmd, fmt.Sprintf(\"USAGE: %s [flags]\", cmd.Use))\n\t}\n\tif len(args) \u003e 0 \u0026\u0026 len(o.drainer.Selector) \u003e 0 {\n\t\treturn cmdutil.UsageErrorf(cmd, \"error: cannot specify both a node name and a --selector option\")\n\t}\n\n\to.drainer.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif o.drainer.Client, err = f.KubernetesClientSet(); err != nil {\n\t\treturn err\n\t}\n\n\tif len(o.drainer.PodSelector) \u003e 0 {\n\t\tif _, err := labels.Parse(o.drainer.PodSelector); err != nil {\n\t\t\treturn errors.New(\"--pod-selector=\u003cpod_selector\u003e must be a valid label selector\")\n\t\t}\n\t}\n\n\to.nodeInfos = []*resource.Info{}\n\n\to.Namespace, _, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.ToPrinter = func(operation string) (printers.ResourcePrinterFunc, error) {\n\t\to.PrintFlags.NamePrintFlags.Operation = operation\n\t\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.drainer.DryRunStrategy)\n\n\t\tprinter, err := o.PrintFlags.ToPrinter()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn printer.PrintObj, nil\n\t}\n\n\t// Set default WarningPrinter if not already set.\n\tif o.WarningPrinter == nil {\n\t\to.WarningPrinter = printers.NewWarningPrinter(o.ErrOut, printers.WarningPrinterOptions{Color: term.AllowsColorOutput(o.ErrOut)})\n\t}\n\n\tbuilder := f.NewBuilder().\n\t\tWithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).\n\t\tNamespaceParam(o.Namespace).DefaultNamespace().\n\t\tRequestChunksOf(o.drainer.ChunkSize).\n\t\tResourceNames(\"nodes\", args...).\n\t\tSingleResourceType().\n\t\tFlatten()\n\n\tif len(o.drainer.Selector) \u003e 0 {\n\t\tbuilder = builder.LabelSelectorParam(o.drainer.Selector).\n\t\t\tResourceTypes(\"nodes\")\n\t}\n\n\tr := builder.Do()\n\n\tif err = r.Err(); err != nil {\n\t\treturn err\n\t}\n\n\treturn r.Visit(func(info *resource.Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif info.Mapping.Resource.GroupResource() != (schema.GroupResource{Group: \"\", Resource: \"nodes\"}) {\n\t\t\treturn fmt.Errorf(\"error: expected resource of type node, got %q\", info.Mapping.Resource)\n\t\t}\n\n\t\to.nodeInfos = append(o.nodeInfos, info)\n\t\treturn nil\n\t})\n}","line":{"from":211,"to":292}} {"id":100031867,"name":"RunDrain","signature":"func (o *DrainCmdOptions) RunDrain() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/drain/drain.go","code":"// RunDrain runs the 'drain' command\nfunc (o *DrainCmdOptions) RunDrain() error {\n\tif err := o.RunCordonOrUncordon(true); err != nil {\n\t\treturn err\n\t}\n\n\tdrainedNodes := sets.NewString()\n\tvar fatal []error\n\n\tremainingNodes := []string{}\n\tfor _, info := range o.nodeInfos {\n\t\tif err := o.deleteOrEvictPodsSimple(info); err == nil {\n\t\t\tdrainedNodes.Insert(info.Name)\n\n\t\t\tprintObj, err := o.ToPrinter(\"drained\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tprintObj(info.Object, o.Out)\n\t\t} else {\n\t\t\tfmt.Fprintf(o.ErrOut, \"error: unable to drain node %q due to error:%s, continuing command...\\n\", info.Name, err)\n\n\t\t\tif !drainedNodes.Has(info.Name) {\n\t\t\t\tfatal = append(fatal, err)\n\t\t\t\tremainingNodes = append(remainingNodes, info.Name)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\t}\n\n\tif len(remainingNodes) \u003e 0 {\n\t\tfmt.Fprintf(o.ErrOut, \"There are pending nodes to be drained:\\n\")\n\t\tfor _, nodeName := range remainingNodes {\n\t\t\tfmt.Fprintf(o.ErrOut, \" %s\\n\", nodeName)\n\t\t}\n\t}\n\n\treturn utilerrors.NewAggregate(fatal)\n}","line":{"from":294,"to":334}} {"id":100031868,"name":"deleteOrEvictPodsSimple","signature":"func (o *DrainCmdOptions) deleteOrEvictPodsSimple(nodeInfo *resource.Info) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/drain/drain.go","code":"func (o *DrainCmdOptions) deleteOrEvictPodsSimple(nodeInfo *resource.Info) error {\n\tlist, errs := o.drainer.GetPodsForDeletion(nodeInfo.Name)\n\tif errs != nil {\n\t\treturn utilerrors.NewAggregate(errs)\n\t}\n\tif warnings := list.Warnings(); warnings != \"\" {\n\t\to.WarningPrinter.Print(warnings)\n\t}\n\tif o.drainer.DryRunStrategy == cmdutil.DryRunClient {\n\t\tfor _, pod := range list.Pods() {\n\t\t\tfmt.Fprintf(o.Out, \"evicting pod %s/%s (dry run)\\n\", pod.Namespace, pod.Name)\n\t\t}\n\t\treturn nil\n\t}\n\n\tif err := o.drainer.DeleteOrEvictPods(list.Pods()); err != nil {\n\t\tpendingList, newErrs := o.drainer.GetPodsForDeletion(nodeInfo.Name)\n\t\tif pendingList != nil {\n\t\t\tpods := pendingList.Pods()\n\t\t\tif len(pods) != 0 {\n\t\t\t\tfmt.Fprintf(o.ErrOut, \"There are pending pods in node %q when an error occurred: %v\\n\", nodeInfo.Name, err)\n\t\t\t\tfor _, pendingPod := range pods {\n\t\t\t\t\tfmt.Fprintf(o.ErrOut, \"%s/%s\\n\", \"pod\", pendingPod.Name)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif newErrs != nil {\n\t\t\tfmt.Fprintf(o.ErrOut, \"Following errors occurred while getting the list of pods to delete:\\n%s\", utilerrors.NewAggregate(newErrs))\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":336,"to":368}} {"id":100031869,"name":"RunCordonOrUncordon","signature":"func (o *DrainCmdOptions) RunCordonOrUncordon(desired bool) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/drain/drain.go","code":"// RunCordonOrUncordon runs either Cordon or Uncordon. The desired value for\n// \"Unschedulable\" is passed as the first arg.\nfunc (o *DrainCmdOptions) RunCordonOrUncordon(desired bool) error {\n\tcordonOrUncordon := \"cordon\"\n\tif !desired {\n\t\tcordonOrUncordon = \"un\" + cordonOrUncordon\n\t}\n\n\tfor _, nodeInfo := range o.nodeInfos {\n\n\t\tprintError := func(err error) {\n\t\t\tfmt.Fprintf(o.ErrOut, \"error: unable to %s node %q: %v\\n\", cordonOrUncordon, nodeInfo.Name, err)\n\t\t}\n\n\t\tgvk := nodeInfo.ResourceMapping().GroupVersionKind\n\t\tif gvk.Kind == \"Node\" {\n\t\t\tc, err := drain.NewCordonHelperFromRuntimeObject(nodeInfo.Object, scheme.Scheme, gvk)\n\t\t\tif err != nil {\n\t\t\t\tprintError(err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif updateRequired := c.UpdateIfRequired(desired); !updateRequired {\n\t\t\t\tprintObj, err := o.ToPrinter(already(desired))\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Fprintf(o.ErrOut, \"error: %v\\n\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tprintObj(nodeInfo.Object, o.Out)\n\t\t\t} else {\n\t\t\t\tif o.drainer.DryRunStrategy != cmdutil.DryRunClient {\n\t\t\t\t\terr, patchErr := c.PatchOrReplace(o.drainer.Client, o.drainer.DryRunStrategy == cmdutil.DryRunServer)\n\t\t\t\t\tif patchErr != nil {\n\t\t\t\t\t\tprintError(patchErr)\n\t\t\t\t\t}\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tprintError(err)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tprintObj, err := o.ToPrinter(changed(desired))\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Fprintf(o.ErrOut, \"%v\\n\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tprintObj(nodeInfo.Object, o.Out)\n\t\t\t}\n\t\t} else {\n\t\t\tprintObj, err := o.ToPrinter(\"skipped\")\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(o.ErrOut, \"%v\\n\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tprintObj(nodeInfo.Object, o.Out)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":370,"to":428}} {"id":100031870,"name":"already","signature":"func already(desired bool) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/drain/drain.go","code":"func already(desired bool) string {\n\tif desired {\n\t\treturn \"already cordoned\"\n\t}\n\treturn \"already uncordoned\"\n}","line":{"from":432,"to":437}} {"id":100031871,"name":"changed","signature":"func changed(desired bool) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/drain/drain.go","code":"func changed(desired bool) string {\n\tif desired {\n\t\treturn \"cordoned\"\n\t}\n\treturn \"uncordoned\"\n}","line":{"from":439,"to":444}} {"id":100031872,"name":"NewCmdEdit","signature":"func NewCmdEdit(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/edit/edit.go","code":"// NewCmdEdit creates the `edit` command\nfunc NewCmdEdit(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := editor.NewEditOptions(editor.NormalEditMode, ioStreams)\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"edit (RESOURCE/NAME | -f FILENAME)\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Edit a resource on the server\"),\n\t\tLong: editLong,\n\t\tExample: editExample,\n\t\tValidArgsFunction: completion.ResourceTypeAndNameCompletionFunc(f),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, args, cmd))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\t// bind flag structs\n\to.RecordFlags.AddFlags(cmd)\n\to.PrintFlags.AddFlags(cmd)\n\n\tusage := \"to use to edit the resource\"\n\tcmdutil.AddFilenameOptionFlags(cmd, \u0026o.FilenameOptions, usage)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmd.Flags().BoolVarP(\u0026o.OutputPatch, \"output-patch\", \"\", o.OutputPatch, \"Output the patch if the resource is edited.\")\n\tcmd.Flags().BoolVar(\u0026o.WindowsLineEndings, \"windows-line-endings\", o.WindowsLineEndings,\n\t\t\"Defaults to the line ending native to your platform.\")\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.FieldManager, \"kubectl-edit\")\n\tcmdutil.AddApplyAnnotationVarFlags(cmd, \u0026o.ApplyAnnotation)\n\tcmdutil.AddSubresourceFlags(cmd, \u0026o.Subresource, \"If specified, edit will operate on the subresource of the requested object.\", editor.SupportedSubresources...)\n\treturn cmd\n}","line":{"from":72,"to":103}} {"id":100031873,"name":"PrintObj","signature":"func (ep *EventPrinter) PrintObj(obj runtime.Object, out io.Writer) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/events/event_printer.go","code":"// PrintObj prints different type of event objects.\nfunc (ep *EventPrinter) PrintObj(obj runtime.Object, out io.Writer) error {\n\tif !ep.NoHeaders \u0026\u0026 !ep.headersPrinted {\n\t\tep.printHeadings(out)\n\t\tep.headersPrinted = true\n\t}\n\n\tswitch t := obj.(type) {\n\tcase *corev1.EventList:\n\t\tfor _, e := range t.Items {\n\t\t\tep.printOneEvent(out, e)\n\t\t}\n\tcase *corev1.Event:\n\t\tep.printOneEvent(out, *t)\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown event type %t\", t)\n\t}\n\n\treturn nil\n}","line":{"from":41,"to":60}} {"id":100031874,"name":"printHeadings","signature":"func (ep *EventPrinter) printHeadings(w io.Writer)","file":"staging/src/k8s.io/kubectl/pkg/cmd/events/event_printer.go","code":"func (ep *EventPrinter) printHeadings(w io.Writer) {\n\tif ep.AllNamespaces {\n\t\tfmt.Fprintf(w, \"NAMESPACE\\t\")\n\t}\n\tfmt.Fprintf(w, \"LAST SEEN\\tTYPE\\tREASON\\tOBJECT\\tMESSAGE\\n\")\n}","line":{"from":62,"to":67}} {"id":100031875,"name":"printOneEvent","signature":"func (ep *EventPrinter) printOneEvent(w io.Writer, e corev1.Event)","file":"staging/src/k8s.io/kubectl/pkg/cmd/events/event_printer.go","code":"func (ep *EventPrinter) printOneEvent(w io.Writer, e corev1.Event) {\n\tinterval := getInterval(e)\n\tif ep.AllNamespaces {\n\t\tfmt.Fprintf(w, \"%v\\t\", e.Namespace)\n\t}\n\tfmt.Fprintf(w, \"%s\\t%s\\t%s\\t%s/%s\\t%v\\n\",\n\t\tinterval,\n\t\tprinters.EscapeTerminal(e.Type),\n\t\tprinters.EscapeTerminal(e.Reason),\n\t\tprinters.EscapeTerminal(e.InvolvedObject.Kind),\n\t\tprinters.EscapeTerminal(e.InvolvedObject.Name),\n\t\tprinters.EscapeTerminal(strings.TrimSpace(e.Message)),\n\t)\n}","line":{"from":69,"to":82}} {"id":100031876,"name":"getInterval","signature":"func getInterval(e corev1.Event) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/events/event_printer.go","code":"func getInterval(e corev1.Event) string {\n\tvar interval string\n\tfirstTimestampSince := translateMicroTimestampSince(e.EventTime)\n\tif e.EventTime.IsZero() {\n\t\tfirstTimestampSince = translateTimestampSince(e.FirstTimestamp)\n\t}\n\tif e.Series != nil {\n\t\tinterval = fmt.Sprintf(\"%s (x%d over %s)\", translateMicroTimestampSince(e.Series.LastObservedTime), e.Series.Count, firstTimestampSince)\n\t} else if e.Count \u003e 1 {\n\t\tinterval = fmt.Sprintf(\"%s (x%d over %s)\", translateTimestampSince(e.LastTimestamp), e.Count, firstTimestampSince)\n\t} else {\n\t\tinterval = firstTimestampSince\n\t}\n\n\treturn interval\n}","line":{"from":84,"to":99}} {"id":100031877,"name":"translateMicroTimestampSince","signature":"func translateMicroTimestampSince(timestamp metav1.MicroTime) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/events/event_printer.go","code":"// translateMicroTimestampSince returns the elapsed time since timestamp in\n// human-readable approximation.\nfunc translateMicroTimestampSince(timestamp metav1.MicroTime) string {\n\tif timestamp.IsZero() {\n\t\treturn \"\u003cunknown\u003e\"\n\t}\n\n\treturn duration.HumanDuration(time.Since(timestamp.Time))\n}","line":{"from":101,"to":109}} {"id":100031878,"name":"translateTimestampSince","signature":"func translateTimestampSince(timestamp metav1.Time) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/events/event_printer.go","code":"// translateTimestampSince returns the elapsed time since timestamp in\n// human-readable approximation.\nfunc translateTimestampSince(timestamp metav1.Time) string {\n\tif timestamp.IsZero() {\n\t\treturn \"\u003cunknown\u003e\"\n\t}\n\n\treturn duration.HumanDuration(time.Since(timestamp.Time))\n}","line":{"from":111,"to":119}} {"id":100031879,"name":"NewEventPrinter","signature":"func NewEventPrinter(noHeader, allNamespaces bool) *EventPrinter","file":"staging/src/k8s.io/kubectl/pkg/cmd/events/event_printer.go","code":"func NewEventPrinter(noHeader, allNamespaces bool) *EventPrinter {\n\treturn \u0026EventPrinter{\n\t\tNoHeaders: noHeader,\n\t\tAllNamespaces: allNamespaces,\n\t}\n}","line":{"from":121,"to":126}} {"id":100031880,"name":"NewEventsFlags","signature":"func NewEventsFlags(restClientGetter genericclioptions.RESTClientGetter, streams genericclioptions.IOStreams) *EventsFlags","file":"staging/src/k8s.io/kubectl/pkg/cmd/events/events.go","code":"// NewEventsFlags returns a default EventsFlags\nfunc NewEventsFlags(restClientGetter genericclioptions.RESTClientGetter, streams genericclioptions.IOStreams) *EventsFlags {\n\treturn \u0026EventsFlags{\n\t\tRESTClientGetter: restClientGetter,\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"events\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: streams,\n\t\tChunkSize: cmdutil.DefaultChunkSize,\n\t}\n}","line":{"from":90,"to":98}} {"id":100031881,"name":"NewCmdEvents","signature":"func NewCmdEvents(restClientGetter genericclioptions.RESTClientGetter, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/events/events.go","code":"// NewCmdEvents creates a new events command\nfunc NewCmdEvents(restClientGetter genericclioptions.RESTClientGetter, streams genericclioptions.IOStreams) *cobra.Command {\n\tflags := NewEventsFlags(restClientGetter, streams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: fmt.Sprintf(\"events [(-o|--output=)%s] [--for TYPE/NAME] [--watch] [--event=Normal,Warning]\", strings.Join(flags.PrintFlags.AllowedFormats(), \"|\")),\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"List events\"),\n\t\tLong: eventsLong,\n\t\tExample: eventsExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\to, err := flags.ToOptions()\n\t\t\tcmdutil.CheckErr(err)\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\tflags.AddFlags(cmd)\n\tflags.PrintFlags.AddFlags(cmd)\n\treturn cmd\n}","line":{"from":118,"to":138}} {"id":100031882,"name":"AddFlags","signature":"func (flags *EventsFlags) AddFlags(cmd *cobra.Command)","file":"staging/src/k8s.io/kubectl/pkg/cmd/events/events.go","code":"// AddFlags registers flags for a cli.\nfunc (flags *EventsFlags) AddFlags(cmd *cobra.Command) {\n\tcmd.Flags().BoolVarP(\u0026flags.Watch, \"watch\", \"w\", flags.Watch, \"After listing the requested events, watch for more events.\")\n\tcmd.Flags().BoolVarP(\u0026flags.AllNamespaces, \"all-namespaces\", \"A\", flags.AllNamespaces, \"If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace.\")\n\tcmd.Flags().StringVar(\u0026flags.ForObject, \"for\", flags.ForObject, \"Filter events to only those pertaining to the specified resource.\")\n\tcmd.Flags().StringSliceVar(\u0026flags.FilterTypes, \"types\", flags.FilterTypes, \"Output only events of given types.\")\n\tcmd.Flags().BoolVar(\u0026flags.NoHeaders, \"no-headers\", flags.NoHeaders, \"When using the default output format, don't print headers.\")\n\tcmdutil.AddChunkSizeFlag(cmd, \u0026flags.ChunkSize)\n}","line":{"from":140,"to":148}} {"id":100031883,"name":"ToOptions","signature":"func (flags *EventsFlags) ToOptions() (*EventsOptions, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/events/events.go","code":"// ToOptions converts from CLI inputs to runtime inputs.\nfunc (flags *EventsFlags) ToOptions() (*EventsOptions, error) {\n\to := \u0026EventsOptions{\n\t\tAllNamespaces: flags.AllNamespaces,\n\t\tWatch: flags.Watch,\n\t\tFilterTypes: flags.FilterTypes,\n\t\tIOStreams: flags.IOStreams,\n\t}\n\tvar err error\n\to.Namespace, _, err = flags.RESTClientGetter.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif flags.ForObject != \"\" {\n\t\tmapper, err := flags.RESTClientGetter.ToRESTMapper()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar found bool\n\t\to.forGVK, o.forName, found, err = decodeResourceTypeName(mapper, flags.ForObject)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"--for must be in resource/name form\")\n\t\t}\n\t}\n\n\tclientConfig, err := flags.RESTClientGetter.ToRESTConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\to.client, err = kubernetes.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(o.FilterTypes) \u003e 0 {\n\t\to.FilterTypes = sets.NewString(o.FilterTypes...).List()\n\t}\n\n\tvar printer printers.ResourcePrinter\n\tif flags.PrintFlags.OutputFormat != nil \u0026\u0026 len(*flags.PrintFlags.OutputFormat) \u003e 0 {\n\t\tprinter, err = flags.PrintFlags.ToPrinter()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tprinter = NewEventPrinter(flags.NoHeaders, flags.AllNamespaces)\n\t}\n\n\to.PrintObj = func(object runtime.Object, writer io.Writer) error {\n\t\treturn printer.PrintObj(object, writer)\n\t}\n\n\treturn o, nil\n}","line":{"from":150,"to":208}} {"id":100031884,"name":"Validate","signature":"func (o *EventsOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/events/events.go","code":"func (o *EventsOptions) Validate() error {\n\tfor _, val := range o.FilterTypes {\n\t\tif !strings.EqualFold(val, \"Normal\") \u0026\u0026 !strings.EqualFold(val, \"Warning\") {\n\t\t\treturn fmt.Errorf(\"valid --types are Normal or Warning\")\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":210,"to":218}} {"id":100031885,"name":"Run","signature":"func (o *EventsOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/events/events.go","code":"// Run retrieves events\nfunc (o *EventsOptions) Run() error {\n\tctx := context.TODO()\n\tnamespace := o.Namespace\n\tif o.AllNamespaces {\n\t\tnamespace = \"\"\n\t}\n\tlistOptions := metav1.ListOptions{Limit: cmdutil.DefaultChunkSize}\n\tif o.forName != \"\" {\n\t\tlistOptions.FieldSelector = fields.AndSelectors(\n\t\t\tfields.OneTermEqualSelector(\"involvedObject.kind\", o.forGVK.Kind),\n\t\t\tfields.OneTermEqualSelector(\"involvedObject.name\", o.forName)).String()\n\t}\n\tif o.Watch {\n\t\treturn o.runWatch(ctx, namespace, listOptions)\n\t}\n\n\te := o.client.CoreV1().Events(namespace)\n\tel := \u0026corev1.EventList{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"EventList\",\n\t\t\tAPIVersion: \"v1\",\n\t\t},\n\t}\n\terr := runtimeresource.FollowContinue(\u0026listOptions,\n\t\tfunc(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\tnewEvents, err := e.List(ctx, options)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, runtimeresource.EnhanceListError(err, options, \"events\")\n\t\t\t}\n\t\t\tel.Items = append(el.Items, newEvents.Items...)\n\t\t\treturn newEvents, nil\n\t\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar filteredEvents []corev1.Event\n\tfor _, e := range el.Items {\n\t\tif !o.filteredEventType(e.Type) {\n\t\t\tcontinue\n\t\t}\n\t\tif e.GetObjectKind().GroupVersionKind().Empty() {\n\t\t\te.SetGroupVersionKind(schema.GroupVersionKind{\n\t\t\t\tVersion: \"v1\",\n\t\t\t\tKind: \"Event\",\n\t\t\t})\n\t\t}\n\t\tfilteredEvents = append(filteredEvents, e)\n\t}\n\n\tel.Items = filteredEvents\n\n\tif len(el.Items) == 0 {\n\t\tif o.AllNamespaces {\n\t\t\tfmt.Fprintln(o.ErrOut, \"No events found.\")\n\t\t} else {\n\t\t\tfmt.Fprintf(o.ErrOut, \"No events found in %s namespace.\\n\", o.Namespace)\n\t\t}\n\t\treturn nil\n\t}\n\n\tw := printers.GetNewTabWriter(o.Out)\n\n\tsort.Sort(SortableEvents(el.Items))\n\n\to.PrintObj(el, w)\n\tw.Flush()\n\treturn nil\n}","line":{"from":220,"to":290}} {"id":100031886,"name":"runWatch","signature":"func (o *EventsOptions) runWatch(ctx context.Context, namespace string, listOptions metav1.ListOptions) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/events/events.go","code":"func (o *EventsOptions) runWatch(ctx context.Context, namespace string, listOptions metav1.ListOptions) error {\n\teventWatch, err := o.client.CoreV1().Events(namespace).Watch(ctx, listOptions)\n\tif err != nil {\n\t\treturn err\n\t}\n\tw := printers.GetNewTabWriter(o.Out)\n\n\tcctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\tintr := interrupt.New(nil, cancel)\n\tintr.Run(func() error {\n\t\t_, err := watchtools.UntilWithoutRetry(cctx, eventWatch, func(e watch.Event) (bool, error) {\n\t\t\tif e.Type == watch.Deleted { // events are deleted after 1 hour; don't print that\n\t\t\t\treturn false, nil\n\t\t\t}\n\n\t\t\tif ev, ok := e.Object.(*corev1.Event); !ok || !o.filteredEventType(ev.Type) {\n\t\t\t\treturn false, nil\n\t\t\t}\n\n\t\t\tif e.Object.GetObjectKind().GroupVersionKind().Empty() {\n\t\t\t\te.Object.GetObjectKind().SetGroupVersionKind(schema.GroupVersionKind{\n\t\t\t\t\tVersion: \"v1\",\n\t\t\t\t\tKind: \"Event\",\n\t\t\t\t})\n\t\t\t}\n\n\t\t\to.PrintObj(e.Object, w)\n\t\t\tw.Flush()\n\t\t\treturn false, nil\n\t\t})\n\t\treturn err\n\t})\n\n\treturn nil\n}","line":{"from":292,"to":327}} {"id":100031887,"name":"filteredEventType","signature":"func (o *EventsOptions) filteredEventType(et string) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/events/events.go","code":"// filteredEventType checks given event can be printed\n// by comparing it in filtered event flag.\n// If --event flag is not set by user, this function allows\n// all events to be printed.\nfunc (o *EventsOptions) filteredEventType(et string) bool {\n\tif len(o.FilterTypes) == 0 {\n\t\treturn true\n\t}\n\n\tfor _, t := range o.FilterTypes {\n\t\tif strings.EqualFold(t, et) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":329,"to":345}} {"id":100031888,"name":"Len","signature":"func (list SortableEvents) Len() int","file":"staging/src/k8s.io/kubectl/pkg/cmd/events/events.go","code":"func (list SortableEvents) Len() int {\n\treturn len(list)\n}","line":{"from":350,"to":352}} {"id":100031889,"name":"Swap","signature":"func (list SortableEvents) Swap(i, j int)","file":"staging/src/k8s.io/kubectl/pkg/cmd/events/events.go","code":"func (list SortableEvents) Swap(i, j int) {\n\tlist[i], list[j] = list[j], list[i]\n}","line":{"from":354,"to":356}} {"id":100031890,"name":"Less","signature":"func (list SortableEvents) Less(i, j int) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/events/events.go","code":"func (list SortableEvents) Less(i, j int) bool {\n\treturn eventTime(list[i]).Before(eventTime(list[j]))\n}","line":{"from":358,"to":360}} {"id":100031891,"name":"eventTime","signature":"func eventTime(event corev1.Event) time.Time","file":"staging/src/k8s.io/kubectl/pkg/cmd/events/events.go","code":"// Return the time that should be used for sorting, which can come from\n// various places in corev1.Event.\nfunc eventTime(event corev1.Event) time.Time {\n\tif event.Series != nil {\n\t\treturn event.Series.LastObservedTime.Time\n\t}\n\tif !event.LastTimestamp.Time.IsZero() {\n\t\treturn event.LastTimestamp.Time\n\t}\n\treturn event.EventTime.Time\n}","line":{"from":362,"to":372}} {"id":100031892,"name":"decodeResourceTypeName","signature":"func decodeResourceTypeName(mapper meta.RESTMapper, s string) (gvk schema.GroupVersionKind, name string, found bool, err error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/events/events.go","code":"// decodeResourceTypeName handles type/name resource formats and returns a resource tuple\n// (empty or not), whether it successfully found one, and an error\nfunc decodeResourceTypeName(mapper meta.RESTMapper, s string) (gvk schema.GroupVersionKind, name string, found bool, err error) {\n\tif !strings.Contains(s, \"/\") {\n\t\treturn\n\t}\n\tseg := strings.Split(s, \"/\")\n\tif len(seg) != 2 {\n\t\terr = fmt.Errorf(\"arguments in resource/name form may not have more than one slash\")\n\t\treturn\n\t}\n\tresource, name := seg[0], seg[1]\n\n\tvar gvr schema.GroupVersionResource\n\tgvr, err = mapper.ResourceFor(schema.GroupVersionResource{Resource: resource})\n\tif err != nil {\n\t\treturn\n\t}\n\tgvk, err = mapper.KindFor(gvr)\n\tif err != nil {\n\t\treturn\n\t}\n\tfound = true\n\n\treturn\n}","line":{"from":376,"to":401}} {"id":100031893,"name":"NewCmdExec","signature":"func NewCmdExec(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/exec/exec.go","code":"func NewCmdExec(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\toptions := \u0026ExecOptions{\n\t\tStreamOptions: StreamOptions{\n\t\t\tIOStreams: streams,\n\t\t},\n\n\t\tExecutor: \u0026DefaultRemoteExecutor{},\n\t}\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"exec (POD | TYPE/NAME) [-c CONTAINER] [flags] -- COMMAND [args...]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Execute a command in a container\"),\n\t\tLong: i18n.T(\"Execute a command in a container.\"),\n\t\tExample: execExample,\n\t\tValidArgsFunction: completion.PodResourceNameCompletionFunc(f),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\targsLenAtDash := cmd.ArgsLenAtDash()\n\t\t\tcmdutil.CheckErr(options.Complete(f, cmd, args, argsLenAtDash))\n\t\t\tcmdutil.CheckErr(options.Validate())\n\t\t\tcmdutil.CheckErr(options.Run())\n\t\t},\n\t}\n\tcmdutil.AddPodRunningTimeoutFlag(cmd, defaultPodExecTimeout)\n\tcmdutil.AddJsonFilenameFlag(cmd.Flags(), \u0026options.FilenameOptions.Filenames, \"to use to exec into the resource\")\n\t// TODO support UID\n\tcmdutil.AddContainerVarFlags(cmd, \u0026options.ContainerName, options.ContainerName)\n\tcmdutil.CheckErr(cmd.RegisterFlagCompletionFunc(\"container\", completion.ContainerCompletionFunc(f)))\n\n\tcmd.Flags().BoolVarP(\u0026options.Stdin, \"stdin\", \"i\", options.Stdin, \"Pass stdin to the container\")\n\tcmd.Flags().BoolVarP(\u0026options.TTY, \"tty\", \"t\", options.TTY, \"Stdin is a TTY\")\n\tcmd.Flags().BoolVarP(\u0026options.Quiet, \"quiet\", \"q\", options.Quiet, \"Only print output from the remote session\")\n\treturn cmd\n}","line":{"from":79,"to":111}} {"id":100031894,"name":"Execute","signature":"func (*DefaultRemoteExecutor) Execute(method string, url *url.URL, config *restclient.Config, stdin io.Reader, stdout, stderr io.Writer, tty bool, terminalSizeQueue remotecommand.TerminalSizeQueue) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/exec/exec.go","code":"func (*DefaultRemoteExecutor) Execute(method string, url *url.URL, config *restclient.Config, stdin io.Reader, stdout, stderr io.Writer, tty bool, terminalSizeQueue remotecommand.TerminalSizeQueue) error {\n\texec, err := remotecommand.NewSPDYExecutor(config, method, url)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn exec.StreamWithContext(context.Background(), remotecommand.StreamOptions{\n\t\tStdin: stdin,\n\t\tStdout: stdout,\n\t\tStderr: stderr,\n\t\tTty: tty,\n\t\tTerminalSizeQueue: terminalSizeQueue,\n\t})\n}","line":{"from":121,"to":133}} {"id":100031895,"name":"Complete","signature":"func (p *ExecOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, argsIn []string, argsLenAtDash int) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/exec/exec.go","code":"// Complete verifies command line arguments and loads data from the command environment\nfunc (p *ExecOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, argsIn []string, argsLenAtDash int) error {\n\tif len(argsIn) \u003e 0 \u0026\u0026 argsLenAtDash != 0 {\n\t\tp.ResourceName = argsIn[0]\n\t}\n\tif argsLenAtDash \u003e -1 {\n\t\tp.Command = argsIn[argsLenAtDash:]\n\t} else if len(argsIn) \u003e 1 {\n\t\tif !p.Quiet {\n\t\t\tfmt.Fprint(p.ErrOut, \"kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.\\n\")\n\t\t}\n\t\tp.Command = argsIn[1:]\n\t} else if len(argsIn) \u003e 0 \u0026\u0026 len(p.FilenameOptions.Filenames) != 0 {\n\t\tif !p.Quiet {\n\t\t\tfmt.Fprint(p.ErrOut, \"kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.\\n\")\n\t\t}\n\t\tp.Command = argsIn[0:]\n\t\tp.ResourceName = \"\"\n\t}\n\n\tvar err error\n\tp.Namespace, p.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp.ExecutablePodFn = polymorphichelpers.AttachablePodForObjectFn\n\n\tp.GetPodTimeout, err = cmdutil.GetPodRunningTimeoutFlag(cmd)\n\tif err != nil {\n\t\treturn cmdutil.UsageErrorf(cmd, err.Error())\n\t}\n\n\tp.Builder = f.NewBuilder\n\tp.restClientGetter = f\n\n\tp.Config, err = f.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclientset, err := f.KubernetesClientSet()\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.PodClient = clientset.CoreV1()\n\n\treturn nil\n}","line":{"from":173,"to":221}} {"id":100031896,"name":"Validate","signature":"func (p *ExecOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/exec/exec.go","code":"// Validate checks that the provided exec options are specified.\nfunc (p *ExecOptions) Validate() error {\n\tif len(p.PodName) == 0 \u0026\u0026 len(p.ResourceName) == 0 \u0026\u0026 len(p.FilenameOptions.Filenames) == 0 {\n\t\treturn fmt.Errorf(\"pod, type/name or --filename must be specified\")\n\t}\n\tif len(p.Command) == 0 {\n\t\treturn fmt.Errorf(\"you must specify at least one command for the container\")\n\t}\n\tif p.Out == nil || p.ErrOut == nil {\n\t\treturn fmt.Errorf(\"both output and error output must be provided\")\n\t}\n\treturn nil\n}","line":{"from":223,"to":235}} {"id":100031897,"name":"SetupTTY","signature":"func (o *StreamOptions) SetupTTY() term.TTY","file":"staging/src/k8s.io/kubectl/pkg/cmd/exec/exec.go","code":"func (o *StreamOptions) SetupTTY() term.TTY {\n\tt := term.TTY{\n\t\tParent: o.InterruptParent,\n\t\tOut: o.Out,\n\t}\n\n\tif !o.Stdin {\n\t\t// need to nil out o.In to make sure we don't create a stream for stdin\n\t\to.In = nil\n\t\to.TTY = false\n\t\treturn t\n\t}\n\n\tt.In = o.In\n\tif !o.TTY {\n\t\treturn t\n\t}\n\n\tif o.isTerminalIn == nil {\n\t\to.isTerminalIn = func(tty term.TTY) bool {\n\t\t\treturn tty.IsTerminalIn()\n\t\t}\n\t}\n\tif !o.isTerminalIn(t) {\n\t\to.TTY = false\n\n\t\tif !o.Quiet \u0026\u0026 o.ErrOut != nil {\n\t\t\tfmt.Fprintln(o.ErrOut, \"Unable to use a TTY - input is not a terminal or the right kind of file\")\n\t\t}\n\n\t\treturn t\n\t}\n\n\t// if we get to here, the user wants to attach stdin, wants a TTY, and o.In is a terminal, so we\n\t// can safely set t.Raw to true\n\tt.Raw = true\n\n\tif o.overrideStreams == nil {\n\t\t// use dockerterm.StdStreams() to get the right I/O handles on Windows\n\t\to.overrideStreams = dockerterm.StdStreams\n\t}\n\tstdin, stdout, _ := o.overrideStreams()\n\to.In = stdin\n\tt.In = stdin\n\tif o.Out != nil {\n\t\to.Out = stdout\n\t\tt.Out = stdout\n\t}\n\n\treturn t\n}","line":{"from":237,"to":287}} {"id":100031898,"name":"Run","signature":"func (p *ExecOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/exec/exec.go","code":"// Run executes a validated remote execution against a pod.\nfunc (p *ExecOptions) Run() error {\n\tvar err error\n\t// we still need legacy pod getter when PodName in ExecOptions struct is provided,\n\t// since there are any other command run this function by providing Podname with PodsGetter\n\t// and without resource builder, eg: `kubectl cp`.\n\tif len(p.PodName) != 0 {\n\t\tp.Pod, err = p.PodClient.Pods(p.Namespace).Get(context.TODO(), p.PodName, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tbuilder := p.Builder().\n\t\t\tWithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).\n\t\t\tFilenameParam(p.EnforceNamespace, \u0026p.FilenameOptions).\n\t\t\tNamespaceParam(p.Namespace).DefaultNamespace()\n\t\tif len(p.ResourceName) \u003e 0 {\n\t\t\tbuilder = builder.ResourceNames(\"pods\", p.ResourceName)\n\t\t}\n\n\t\tobj, err := builder.Do().Object()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif meta.IsListType(obj) {\n\t\t\treturn fmt.Errorf(\"cannot exec into multiple objects at a time\")\n\t\t}\n\n\t\tp.Pod, err = p.ExecutablePodFn(p.restClientGetter, obj, p.GetPodTimeout)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tpod := p.Pod\n\n\tif pod.Status.Phase == corev1.PodSucceeded || pod.Status.Phase == corev1.PodFailed {\n\t\treturn fmt.Errorf(\"cannot exec into a container in a completed pod; current phase is %s\", pod.Status.Phase)\n\t}\n\n\tcontainerName := p.ContainerName\n\tif len(containerName) == 0 {\n\t\tcontainer, err := podcmd.FindOrDefaultContainerByName(pod, containerName, p.Quiet, p.ErrOut)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcontainerName = container.Name\n\t}\n\n\t// ensure we can recover the terminal while attached\n\tt := p.SetupTTY()\n\n\tvar sizeQueue remotecommand.TerminalSizeQueue\n\tif t.Raw {\n\t\t// this call spawns a goroutine to monitor/update the terminal size\n\t\tsizeQueue = t.MonitorSize(t.GetSize())\n\n\t\t// unset p.Err if it was previously set because both stdout and stderr go over p.Out when tty is\n\t\t// true\n\t\tp.ErrOut = nil\n\t}\n\n\tfn := func() error {\n\t\trestClient, err := restclient.RESTClientFor(p.Config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// TODO: consider abstracting into a client invocation or client helper\n\t\treq := restClient.Post().\n\t\t\tResource(\"pods\").\n\t\t\tName(pod.Name).\n\t\t\tNamespace(pod.Namespace).\n\t\t\tSubResource(\"exec\")\n\t\treq.VersionedParams(\u0026corev1.PodExecOptions{\n\t\t\tContainer: containerName,\n\t\t\tCommand: p.Command,\n\t\t\tStdin: p.Stdin,\n\t\t\tStdout: p.Out != nil,\n\t\t\tStderr: p.ErrOut != nil,\n\t\t\tTTY: t.Raw,\n\t\t}, scheme.ParameterCodec)\n\n\t\treturn p.Executor.Execute(\"POST\", req.URL(), p.Config, p.In, p.Out, p.ErrOut, t.Raw, sizeQueue)\n\t}\n\n\tif err := t.Safe(fn); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":289,"to":381}} {"id":100031899,"name":"NewExplainOptions","signature":"func NewExplainOptions(parent string, streams genericclioptions.IOStreams) *ExplainOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/explain/explain.go","code":"func NewExplainOptions(parent string, streams genericclioptions.IOStreams) *ExplainOptions {\n\treturn \u0026ExplainOptions{\n\t\tIOStreams: streams,\n\t\tCmdParent: parent,\n\t\tOutputFormat: plaintextTemplateName,\n\t}\n}","line":{"from":79,"to":85}} {"id":100031900,"name":"NewCmdExplain","signature":"func NewCmdExplain(parent string, f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/explain/explain.go","code":"// NewCmdExplain returns a cobra command for swagger docs\nfunc NewCmdExplain(parent string, f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\to := NewExplainOptions(parent, streams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"explain RESOURCE\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Get documentation for a resource\"),\n\t\tLong: explainLong + \"\\n\\n\" + cmdutil.SuggestAPIResources(parent),\n\t\tExample: explainExamples,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\tcmd.Flags().BoolVar(\u0026o.Recursive, \"recursive\", o.Recursive, \"Print the fields of fields (Currently only 1 level deep)\")\n\tcmd.Flags().StringVar(\u0026o.APIVersion, \"api-version\", o.APIVersion, \"Get different explanations for particular API version (API group/version)\")\n\n\t// Only enable --output as a valid flag if the feature is enabled\n\tcmd.Flags().StringVar(\u0026o.OutputFormat, \"output\", plaintextTemplateName, \"Format in which to render the schema (plaintext, plaintext-openapiv2)\")\n\n\treturn cmd\n}","line":{"from":87,"to":110}} {"id":100031901,"name":"Complete","signature":"func (o *ExplainOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/explain/explain.go","code":"func (o *ExplainOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\to.Mapper, err = f.ToRESTMapper()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Schema, err = f.OpenAPISchema()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Only openapi v3 needs the discovery client.\n\to.OpenAPIV3Client, err = f.OpenAPIV3Client()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.args = args\n\treturn nil\n}","line":{"from":112,"to":132}} {"id":100031902,"name":"Validate","signature":"func (o *ExplainOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/explain/explain.go","code":"func (o *ExplainOptions) Validate() error {\n\tif len(o.args) == 0 {\n\t\treturn fmt.Errorf(\"You must specify the type of resource to explain. %s\\n\", cmdutil.SuggestAPIResources(o.CmdParent))\n\t}\n\tif len(o.args) \u003e 1 {\n\t\treturn fmt.Errorf(\"We accept only this format: explain RESOURCE\\n\")\n\t}\n\n\treturn nil\n}","line":{"from":134,"to":143}} {"id":100031903,"name":"Run","signature":"func (o *ExplainOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/explain/explain.go","code":"// Run executes the appropriate steps to print a model's documentation\nfunc (o *ExplainOptions) Run() error {\n\tvar fullySpecifiedGVR schema.GroupVersionResource\n\tvar fieldsPath []string\n\tvar err error\n\tif len(o.APIVersion) == 0 {\n\t\tfullySpecifiedGVR, fieldsPath, err = explain.SplitAndParseResourceRequestWithMatchingPrefix(o.args[0], o.Mapper)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t// TODO: After we figured out the new syntax to separate group and resource, allow\n\t\t// the users to use it in explain (kubectl explain \u003cgroup\u003e\u003csyntax\u003e\u003cresource\u003e).\n\t\t// Refer to issue #16039 for why we do this. Refer to PR #15808 that used \"/\" syntax.\n\t\tfullySpecifiedGVR, fieldsPath, err = explain.SplitAndParseResourceRequest(o.args[0], o.Mapper)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Fallback to openapiv2 implementation using special template name\n\tswitch o.OutputFormat {\n\tcase plaintextOpenAPIV2TemplateName:\n\t\treturn o.renderOpenAPIV2(fullySpecifiedGVR, fieldsPath)\n\tcase plaintextTemplateName:\n\t\t// Check whether the server reponds to OpenAPIV3.\n\t\tif _, err := o.OpenAPIV3Client.Paths(); err != nil {\n\t\t\t// Use v2 renderer if server does not support v3\n\t\t\treturn o.renderOpenAPIV2(fullySpecifiedGVR, fieldsPath)\n\t\t}\n\n\t\tfallthrough\n\tdefault:\n\t\tif len(o.APIVersion) \u003e 0 {\n\t\t\tapiVersion, err := schema.ParseGroupVersion(o.APIVersion)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfullySpecifiedGVR.Group = apiVersion.Group\n\t\t\tfullySpecifiedGVR.Version = apiVersion.Version\n\t\t}\n\n\t\treturn openapiv3explain.PrintModelDescription(\n\t\t\tfieldsPath,\n\t\t\to.Out,\n\t\t\to.OpenAPIV3Client,\n\t\t\tfullySpecifiedGVR,\n\t\t\to.Recursive,\n\t\t\to.OutputFormat,\n\t\t)\n\t}\n}","line":{"from":145,"to":196}} {"id":100031904,"name":"renderOpenAPIV2","signature":"func (o *ExplainOptions) renderOpenAPIV2(","file":"staging/src/k8s.io/kubectl/pkg/cmd/explain/explain.go","code":"func (o *ExplainOptions) renderOpenAPIV2(\n\tfullySpecifiedGVR schema.GroupVersionResource,\n\tfieldsPath []string,\n) error {\n\tvar err error\n\n\tgvk, _ := o.Mapper.KindFor(fullySpecifiedGVR)\n\tif gvk.Empty() {\n\t\tgvk, err = o.Mapper.KindFor(fullySpecifiedGVR.GroupResource().WithVersion(\"\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif len(o.APIVersion) != 0 {\n\t\tapiVersion, err := schema.ParseGroupVersion(o.APIVersion)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgvk = apiVersion.WithKind(gvk.Kind)\n\t}\n\n\tschema := o.Schema.LookupResource(gvk)\n\tif schema == nil {\n\t\treturn fmt.Errorf(\"couldn't find resource for %q\", gvk)\n\t}\n\n\treturn explain.PrintModelDescription(fieldsPath, o.Out, schema, gvk, o.Recursive)\n}","line":{"from":198,"to":226}} {"id":100031905,"name":"NewExposeServiceOptions","signature":"func NewExposeServiceOptions(ioStreams genericclioptions.IOStreams) *ExposeServiceOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/expose/expose.go","code":"// NewExposeServiceOptions creates a new ExposeServiceOptions and return a pointer to the\n// struct\nfunc NewExposeServiceOptions(ioStreams genericclioptions.IOStreams) *ExposeServiceOptions {\n\treturn \u0026ExposeServiceOptions{\n\t\tRecordFlags: genericclioptions.NewRecordFlags(),\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"exposed\").WithTypeSetter(scheme.Scheme),\n\n\t\tRecorder: genericclioptions.NoopRecorder{},\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":137,"to":147}} {"id":100031906,"name":"NewCmdExposeService","signature":"func NewCmdExposeService(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/expose/expose.go","code":"// NewCmdExposeService is a command to expose the service from user's input\nfunc NewCmdExposeService(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\to := NewExposeServiceOptions(streams)\n\n\tvalidArgs := []string{}\n\tresources := regexp.MustCompile(`\\s*,`).Split(exposeResources, -1)\n\tfor _, r := range resources {\n\t\tvalidArgs = append(validArgs, strings.Fields(r)[0])\n\t}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"expose (-f FILENAME | TYPE NAME) [--port=port] [--protocol=TCP|UDP|SCTP] [--target-port=number-or-name] [--name=name] [--external-ip=external-ip-of-service] [--type=type]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Take a replication controller, service, deployment or pod and expose it as a new Kubernetes service\"),\n\t\tLong: exposeLong,\n\t\tExample: exposeExample,\n\t\tValidArgsFunction: completion.SpecifiedResourceTypeAndNameCompletionFunc(f, validArgs),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd))\n\t\t\tcmdutil.CheckErr(o.RunExpose(cmd, args))\n\t\t},\n\t}\n\n\to.RecordFlags.AddFlags(cmd)\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmd.Flags().StringVar(\u0026o.Protocol, \"protocol\", o.Protocol, i18n.T(\"The network protocol for the service to be created. Default is 'TCP'.\"))\n\tcmd.Flags().StringVar(\u0026o.Port, \"port\", o.Port, i18n.T(\"The port that the service should serve on. Copied from the resource being exposed, if unspecified\"))\n\tcmd.Flags().StringVar(\u0026o.Type, \"type\", o.Type, i18n.T(\"Type for this service: ClusterIP, NodePort, LoadBalancer, or ExternalName. Default is 'ClusterIP'.\"))\n\tcmd.Flags().StringVar(\u0026o.LoadBalancerIP, \"load-balancer-ip\", o.LoadBalancerIP, i18n.T(\"IP to assign to the LoadBalancer. If empty, an ephemeral IP will be created and used (cloud-provider specific).\"))\n\tcmd.Flags().StringVar(\u0026o.Selector, \"selector\", o.Selector, i18n.T(\"A label selector to use for this service. Only equality-based selector requirements are supported. If empty (the default) infer the selector from the replication controller or replica set.)\"))\n\tcmd.Flags().StringVarP(\u0026o.Labels, \"labels\", \"l\", o.Labels, \"Labels to apply to the service created by this call.\")\n\tcmd.Flags().StringVar(\u0026o.TargetPort, \"target-port\", o.TargetPort, i18n.T(\"Name or number for the port on the container that the service should direct traffic to. Optional.\"))\n\tcmd.Flags().StringVar(\u0026o.ExternalIP, \"external-ip\", o.ExternalIP, i18n.T(\"Additional external IP address (not managed by Kubernetes) to accept for the service. If this IP is routed to a node, the service can be accessed by this IP in addition to its generated service IP.\"))\n\tcmd.Flags().StringVar(\u0026o.Name, \"name\", o.Name, i18n.T(\"The name for the newly created object.\"))\n\tcmd.Flags().StringVar(\u0026o.SessionAffinity, \"session-affinity\", o.SessionAffinity, i18n.T(\"If non-empty, set the session affinity for the service to this; legal values: 'None', 'ClientIP'\"))\n\tcmd.Flags().StringVar(\u0026o.ClusterIP, \"cluster-ip\", o.ClusterIP, i18n.T(\"ClusterIP to be assigned to the service. Leave empty to auto-allocate, or set to 'None' to create a headless service.\"))\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.fieldManager, \"kubectl-expose\")\n\to.AddOverrideFlags(cmd)\n\n\tusage := \"identifying the resource to expose a service\"\n\tcmdutil.AddFilenameOptionFlags(cmd, \u0026o.FilenameOptions, usage)\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\treturn cmd\n}","line":{"from":149,"to":194}} {"id":100031907,"name":"Complete","signature":"func (o *ExposeServiceOptions) Complete(f cmdutil.Factory, cmd *cobra.Command) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/expose/expose.go","code":"// Complete loads data from the command line environment\nfunc (o *ExposeServiceOptions) Complete(f cmdutil.Factory, cmd *cobra.Command) error {\n\tvar err error\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.PrintObj = printer.PrintObj\n\n\to.RecordFlags.Complete(cmd)\n\to.Recorder, err = o.RecordFlags.ToRecorder()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Builder = f.NewBuilder()\n\to.ClientForMapping = f.ClientForMapping\n\to.CanBeExposed = polymorphichelpers.CanBeExposedFn\n\to.MapBasedSelectorForObject = polymorphichelpers.MapBasedSelectorForObjectFn\n\to.ProtocolsForObject = polymorphichelpers.ProtocolsForObjectFn\n\to.PortsForObject = polymorphichelpers.PortsForObjectFn\n\n\to.Mapper, err = f.ToRESTMapper()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn err\n}","line":{"from":196,"to":235}} {"id":100031908,"name":"RunExpose","signature":"func (o *ExposeServiceOptions) RunExpose(cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/expose/expose.go","code":"// RunExpose retrieves the Kubernetes Object from the API server and expose it to a\n// Kubernetes Service\nfunc (o *ExposeServiceOptions) RunExpose(cmd *cobra.Command, args []string) error {\n\tr := o.Builder.\n\t\tWithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).\n\t\tContinueOnError().\n\t\tNamespaceParam(o.Namespace).DefaultNamespace().\n\t\tFilenameParam(o.EnforceNamespace, \u0026o.FilenameOptions).\n\t\tResourceTypeOrNameArgs(false, args...).\n\t\tFlatten().\n\t\tDo()\n\terr := r.Err()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = r.Visit(func(info *resource.Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tmapping := info.ResourceMapping()\n\t\tif err := o.CanBeExposed(mapping.GroupVersionKind.GroupKind()); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tname := info.Name\n\t\tif len(name) \u003e validation.DNS1035LabelMaxLength {\n\t\t\tname = name[:validation.DNS1035LabelMaxLength]\n\t\t}\n\t\to.DefaultName = name\n\n\t\t// For objects that need a pod selector, derive it from the exposed object in case a user\n\t\t// didn't explicitly specify one via --selector\n\t\tif len(o.Selector) == 0 {\n\t\t\ts, err := o.MapBasedSelectorForObject(info.Object)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"couldn't retrieve selectors via --selector flag or introspection: %v\", err)\n\t\t\t}\n\t\t\to.Selector = s\n\t\t}\n\n\t\tisHeadlessService := o.ClusterIP == \"None\"\n\n\t\t// For objects that need a port, derive it from the exposed object in case a user\n\t\t// didn't explicitly specify one via --port\n\t\tif len(o.Port) == 0 {\n\t\t\tports, err := o.PortsForObject(info.Object)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"couldn't find port via --port flag or introspection: %v\", err)\n\t\t\t}\n\t\t\tswitch len(ports) {\n\t\t\tcase 0:\n\t\t\t\tif !isHeadlessService {\n\t\t\t\t\treturn fmt.Errorf(\"couldn't find port via --port flag or introspection\")\n\t\t\t\t}\n\t\t\tcase 1:\n\t\t\t\to.Port = ports[0]\n\t\t\tdefault:\n\t\t\t\to.Ports = strings.Join(ports, \",\")\n\t\t\t}\n\t\t}\n\n\t\t// Always try to derive protocols from the exposed object, may use\n\t\t// different protocols for different ports.\n\t\tprotocolsMap, err := o.ProtocolsForObject(info.Object)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't find protocol via introspection: %v\", err)\n\t\t}\n\t\tif protocols := generate.MakeProtocols(protocolsMap); !generate.IsZero(protocols) {\n\t\t\to.Protocols = protocols\n\t\t}\n\n\t\tif len(o.Labels) == 0 {\n\t\t\tlabels, err := meta.NewAccessor().Labels(info.Object)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\to.Labels = polymorphichelpers.MakeLabels(labels)\n\t\t}\n\n\t\t// Generate new object\n\t\tservice, err := o.createService()\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\toverrideService, err := o.NewOverrider(\u0026corev1.Service{}).Apply(service)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := o.Recorder.Record(overrideService); err != nil {\n\t\t\tklog.V(4).Infof(\"error recording current command: %v\", err)\n\t\t}\n\n\t\tif o.DryRunStrategy == cmdutil.DryRunClient {\n\t\t\tif meta, err := meta.Accessor(overrideService); err == nil \u0026\u0026 o.EnforceNamespace {\n\t\t\t\tmeta.SetNamespace(o.Namespace)\n\t\t\t}\n\t\t\treturn o.PrintObj(overrideService, o.Out)\n\t\t}\n\t\tif err := util.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), overrideService, scheme.DefaultJSONEncoder()); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tasUnstructured := \u0026unstructured.Unstructured{}\n\t\tif err := scheme.Scheme.Convert(overrideService, asUnstructured, nil); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgvks, _, err := unstructuredscheme.NewUnstructuredObjectTyper().ObjectKinds(asUnstructured)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tobjMapping, err := o.Mapper.RESTMapping(gvks[0].GroupKind(), gvks[0].Version)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Serialize the object with the annotation applied.\n\t\tclient, err := o.ClientForMapping(objMapping)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tactualObject, err := resource.\n\t\t\tNewHelper(client, objMapping).\n\t\t\tDryRun(o.DryRunStrategy == cmdutil.DryRunServer).\n\t\t\tWithFieldManager(o.fieldManager).\n\t\t\tCreate(o.Namespace, false, asUnstructured)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn o.PrintObj(actualObject, o.Out)\n\t})\n\treturn err\n}","line":{"from":237,"to":374}} {"id":100031909,"name":"createService","signature":"func (o *ExposeServiceOptions) createService() (*corev1.Service, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/expose/expose.go","code":"func (o *ExposeServiceOptions) createService() (*corev1.Service, error) {\n\tif len(o.Selector) == 0 {\n\t\treturn nil, fmt.Errorf(\"selector must be specified\")\n\t}\n\tselector, err := parseLabels(o.Selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar labels map[string]string\n\tif len(o.Labels) \u003e 0 {\n\t\tlabels, err = parseLabels(o.Labels)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tname := o.Name\n\tif len(name) == 0 {\n\t\tname = o.DefaultName\n\t\tif len(name) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"name must be specified\")\n\t\t}\n\t}\n\n\tvar portProtocolMap map[string]string\n\tif o.Protocols != \"\" {\n\t\tportProtocolMap, err = parseProtocols(o.Protocols)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// ports takes precedence over port since it will be\n\t// specified only when the user hasn't specified a port\n\t// via --port and the exposed object has multiple ports.\n\tvar portString string\n\tportString = o.Ports\n\tif len(o.Ports) == 0 {\n\t\tportString = o.Port\n\t}\n\n\tports := []corev1.ServicePort{}\n\tif len(portString) != 0 {\n\t\tportStringSlice := strings.Split(portString, \",\")\n\t\tservicePortName := o.PortName\n\t\tfor i, stillPortString := range portStringSlice {\n\t\t\tport, err := strconv.Atoi(stillPortString)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tname := servicePortName\n\t\t\t// If we are going to assign multiple ports to a service, we need to\n\t\t\t// generate a different name for each one.\n\t\t\tif len(portStringSlice) \u003e 1 {\n\t\t\t\tname = fmt.Sprintf(\"port-%d\", i+1)\n\t\t\t}\n\t\t\tprotocol := o.Protocol\n\n\t\t\tswitch {\n\t\t\tcase len(protocol) == 0 \u0026\u0026 len(portProtocolMap) == 0:\n\t\t\t\t// Default to TCP, what the flag was doing previously.\n\t\t\t\tprotocol = \"TCP\"\n\t\t\tcase len(protocol) \u003e 0 \u0026\u0026 len(portProtocolMap) \u003e 0:\n\t\t\t\t// User has specified the --protocol while exposing a multiprotocol resource\n\t\t\t\t// We should stomp multiple protocols with the one specified ie. do nothing\n\t\t\tcase len(protocol) == 0 \u0026\u0026 len(portProtocolMap) \u003e 0:\n\t\t\t\t// no --protocol and we expose a multiprotocol resource\n\t\t\t\tprotocol = \"TCP\" // have the default so we can stay sane\n\t\t\t\tif exposeProtocol, found := portProtocolMap[stillPortString]; found {\n\t\t\t\t\tprotocol = exposeProtocol\n\t\t\t\t}\n\t\t\t}\n\t\t\tports = append(ports, corev1.ServicePort{\n\t\t\t\tName: name,\n\t\t\t\tPort: int32(port),\n\t\t\t\tProtocol: corev1.Protocol(protocol),\n\t\t\t})\n\t\t}\n\t}\n\n\tservice := corev1.Service{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tLabels: labels,\n\t\t},\n\t\tSpec: corev1.ServiceSpec{\n\t\t\tSelector: selector,\n\t\t\tPorts: ports,\n\t\t},\n\t}\n\ttargetPortString := o.TargetPort\n\tif len(targetPortString) \u003e 0 {\n\t\tvar targetPort intstr.IntOrString\n\t\tif portNum, err := strconv.Atoi(targetPortString); err != nil {\n\t\t\ttargetPort = intstr.FromString(targetPortString)\n\t\t} else {\n\t\t\ttargetPort = intstr.FromInt(portNum)\n\t\t}\n\t\t// Use the same target-port for every port\n\t\tfor i := range service.Spec.Ports {\n\t\t\tservice.Spec.Ports[i].TargetPort = targetPort\n\t\t}\n\t} else {\n\t\t// If --target-port or --container-port haven't been specified, this\n\t\t// should be the same as Port\n\t\tfor i := range service.Spec.Ports {\n\t\t\tport := service.Spec.Ports[i].Port\n\t\t\tservice.Spec.Ports[i].TargetPort = intstr.FromInt(int(port))\n\t\t}\n\t}\n\tif len(o.ExternalIP) \u003e 0 {\n\t\tservice.Spec.ExternalIPs = []string{o.ExternalIP}\n\t}\n\tif len(o.Type) != 0 {\n\t\tservice.Spec.Type = corev1.ServiceType(o.Type)\n\t}\n\tif service.Spec.Type == corev1.ServiceTypeLoadBalancer {\n\t\tservice.Spec.LoadBalancerIP = o.LoadBalancerIP\n\t}\n\tif len(o.SessionAffinity) != 0 {\n\t\tswitch corev1.ServiceAffinity(o.SessionAffinity) {\n\t\tcase corev1.ServiceAffinityNone:\n\t\t\tservice.Spec.SessionAffinity = corev1.ServiceAffinityNone\n\t\tcase corev1.ServiceAffinityClientIP:\n\t\t\tservice.Spec.SessionAffinity = corev1.ServiceAffinityClientIP\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown session affinity: %s\", o.SessionAffinity)\n\t\t}\n\t}\n\tif len(o.ClusterIP) != 0 {\n\t\tif o.ClusterIP == \"None\" {\n\t\t\tservice.Spec.ClusterIP = corev1.ClusterIPNone\n\t\t} else {\n\t\t\tservice.Spec.ClusterIP = o.ClusterIP\n\t\t}\n\t}\n\treturn \u0026service, nil\n}","line":{"from":376,"to":514}} {"id":100031910,"name":"parseLabels","signature":"func parseLabels(labelSpec string) (map[string]string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/expose/expose.go","code":"// parseLabels turns a string representation of a label set into a map[string]string\nfunc parseLabels(labelSpec string) (map[string]string, error) {\n\tif len(labelSpec) == 0 {\n\t\treturn nil, fmt.Errorf(\"no label spec passed\")\n\t}\n\tlabels := map[string]string{}\n\tlabelSpecs := strings.Split(labelSpec, \",\")\n\tfor ix := range labelSpecs {\n\t\tlabelSpec := strings.Split(labelSpecs[ix], \"=\")\n\t\tif len(labelSpec) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"unexpected label spec: %s\", labelSpecs[ix])\n\t\t}\n\t\tif len(labelSpec[0]) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"unexpected empty label key\")\n\t\t}\n\t\tlabels[labelSpec[0]] = labelSpec[1]\n\t}\n\treturn labels, nil\n}","line":{"from":516,"to":534}} {"id":100031911,"name":"parseProtocols","signature":"func parseProtocols(protocols string) (map[string]string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/expose/expose.go","code":"// parseProtocols turns a string representation of a protocols set into a map[string]string\nfunc parseProtocols(protocols string) (map[string]string, error) {\n\tif len(protocols) == 0 {\n\t\treturn nil, fmt.Errorf(\"no protocols passed\")\n\t}\n\tportProtocolMap := map[string]string{}\n\tprotocolsSlice := strings.Split(protocols, \",\")\n\tfor ix := range protocolsSlice {\n\t\tportProtocol := strings.Split(protocolsSlice[ix], \"/\")\n\t\tif len(portProtocol) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"unexpected port protocol mapping: %s\", protocolsSlice[ix])\n\t\t}\n\t\tif len(portProtocol[0]) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"unexpected empty port\")\n\t\t}\n\t\tif len(portProtocol[1]) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"unexpected empty protocol\")\n\t\t}\n\t\tportProtocolMap[portProtocol[0]] = portProtocol[1]\n\t}\n\treturn portProtocolMap, nil\n}","line":{"from":536,"to":557}} {"id":100031912,"name":"RelaxedJSONPathExpression","signature":"func RelaxedJSONPathExpression(pathExpression string) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/customcolumn.go","code":"// RelaxedJSONPathExpression attempts to be flexible with JSONPath expressions, it accepts:\n// - metadata.name (no leading '.' or curly braces '{...}'\n// - {metadata.name} (no leading '.')\n// - .metadata.name (no curly braces '{...}')\n// - {.metadata.name} (complete expression)\n//\n// And transforms them all into a valid jsonpath expression:\n//\n//\t{.metadata.name}\nfunc RelaxedJSONPathExpression(pathExpression string) (string, error) {\n\tif len(pathExpression) == 0 {\n\t\treturn pathExpression, nil\n\t}\n\tsubmatches := jsonRegexp.FindStringSubmatch(pathExpression)\n\tif submatches == nil {\n\t\treturn \"\", fmt.Errorf(\"unexpected path string, expected a 'name1.name2' or '.name1.name2' or '{name1.name2}' or '{.name1.name2}'\")\n\t}\n\tif len(submatches) != 3 {\n\t\treturn \"\", fmt.Errorf(\"unexpected submatch list: %v\", submatches)\n\t}\n\tvar fieldSpec string\n\tif len(submatches[1]) != 0 {\n\t\tfieldSpec = submatches[1]\n\t} else {\n\t\tfieldSpec = submatches[2]\n\t}\n\treturn fmt.Sprintf(\"{.%s}\", fieldSpec), nil\n}","line":{"from":40,"to":67}} {"id":100031913,"name":"NewCustomColumnsPrinterFromSpec","signature":"func NewCustomColumnsPrinterFromSpec(spec string, decoder runtime.Decoder, noHeaders bool) (*CustomColumnsPrinter, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/customcolumn.go","code":"// NewCustomColumnsPrinterFromSpec creates a custom columns printer from a comma separated list of \u003cheader\u003e:\u003cjsonpath-field-spec\u003e pairs.\n// e.g. NAME:metadata.name,API_VERSION:apiVersion creates a printer that prints:\n//\n//\tNAME API_VERSION\n//\tfoo bar\nfunc NewCustomColumnsPrinterFromSpec(spec string, decoder runtime.Decoder, noHeaders bool) (*CustomColumnsPrinter, error) {\n\tif len(spec) == 0 {\n\t\treturn nil, fmt.Errorf(\"custom-columns format specified but no custom columns given\")\n\t}\n\tparts := strings.Split(spec, \",\")\n\tcolumns := make([]Column, len(parts))\n\tfor ix := range parts {\n\t\tcolSpec := strings.SplitN(parts[ix], \":\", 2)\n\t\tif len(colSpec) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"unexpected custom-columns spec: %s, expected \u003cheader\u003e:\u003cjson-path-expr\u003e\", parts[ix])\n\t\t}\n\t\tspec, err := RelaxedJSONPathExpression(colSpec[1])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcolumns[ix] = Column{Header: colSpec[0], FieldSpec: spec}\n\t}\n\treturn \u0026CustomColumnsPrinter{Columns: columns, Decoder: decoder, NoHeaders: noHeaders}, nil\n}","line":{"from":69,"to":92}} {"id":100031914,"name":"splitOnWhitespace","signature":"func splitOnWhitespace(line string) []string","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/customcolumn.go","code":"func splitOnWhitespace(line string) []string {\n\tlineScanner := bufio.NewScanner(bytes.NewBufferString(line))\n\tlineScanner.Split(bufio.ScanWords)\n\tresult := []string{}\n\tfor lineScanner.Scan() {\n\t\tresult = append(result, lineScanner.Text())\n\t}\n\treturn result\n}","line":{"from":94,"to":102}} {"id":100031915,"name":"NewCustomColumnsPrinterFromTemplate","signature":"func NewCustomColumnsPrinterFromTemplate(templateReader io.Reader, decoder runtime.Decoder) (*CustomColumnsPrinter, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/customcolumn.go","code":"// NewCustomColumnsPrinterFromTemplate creates a custom columns printer from a template stream. The template is expected\n// to consist of two lines, whitespace separated. The first line is the header line, the second line is the jsonpath field spec\n// For example, the template below:\n// NAME API_VERSION\n// {metadata.name} {apiVersion}\nfunc NewCustomColumnsPrinterFromTemplate(templateReader io.Reader, decoder runtime.Decoder) (*CustomColumnsPrinter, error) {\n\tscanner := bufio.NewScanner(templateReader)\n\tif !scanner.Scan() {\n\t\treturn nil, fmt.Errorf(\"invalid template, missing header line. Expected format is one line of space separated headers, one line of space separated column specs.\")\n\t}\n\theaders := splitOnWhitespace(scanner.Text())\n\n\tif !scanner.Scan() {\n\t\treturn nil, fmt.Errorf(\"invalid template, missing spec line. Expected format is one line of space separated headers, one line of space separated column specs.\")\n\t}\n\tspecs := splitOnWhitespace(scanner.Text())\n\n\tif len(headers) != len(specs) {\n\t\treturn nil, fmt.Errorf(\"number of headers (%d) and field specifications (%d) don't match\", len(headers), len(specs))\n\t}\n\n\tcolumns := make([]Column, len(headers))\n\tfor ix := range headers {\n\t\tspec, err := RelaxedJSONPathExpression(specs[ix])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcolumns[ix] = Column{\n\t\t\tHeader: headers[ix],\n\t\t\tFieldSpec: spec,\n\t\t}\n\t}\n\treturn \u0026CustomColumnsPrinter{Columns: columns, Decoder: decoder, NoHeaders: false}, nil\n}","line":{"from":104,"to":137}} {"id":100031916,"name":"PrintObj","signature":"func (s *CustomColumnsPrinter) PrintObj(obj runtime.Object, out io.Writer) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/customcolumn.go","code":"func (s *CustomColumnsPrinter) PrintObj(obj runtime.Object, out io.Writer) error {\n\t// we use reflect.Indirect here in order to obtain the actual value from a pointer.\n\t// we need an actual value in order to retrieve the package path for an object.\n\t// using reflect.Indirect indiscriminately is valid here, as all runtime.Objects are supposed to be pointers.\n\tif printers.InternalObjectPreventer.IsForbidden(reflect.Indirect(reflect.ValueOf(obj)).Type().PkgPath()) {\n\t\treturn fmt.Errorf(printers.InternalObjectPrinterErr)\n\t}\n\n\tif _, found := out.(*tabwriter.Writer); !found {\n\t\tw := printers.GetNewTabWriter(out)\n\t\tout = w\n\t\tdefer w.Flush()\n\t}\n\n\tt := reflect.TypeOf(obj)\n\tif !s.NoHeaders \u0026\u0026 t != s.lastType {\n\t\theaders := make([]string, len(s.Columns))\n\t\tfor ix := range s.Columns {\n\t\t\theaders[ix] = s.Columns[ix].Header\n\t\t}\n\t\tfmt.Fprintln(out, strings.Join(headers, \"\\t\"))\n\t\ts.lastType = t\n\t}\n\tparsers := make([]*jsonpath.JSONPath, len(s.Columns))\n\tfor ix := range s.Columns {\n\t\tparsers[ix] = jsonpath.New(fmt.Sprintf(\"column%d\", ix)).AllowMissingKeys(true)\n\t\tif err := parsers[ix].Parse(s.Columns[ix].FieldSpec); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif meta.IsListType(obj) {\n\t\tobjs, err := meta.ExtractList(obj)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor ix := range objs {\n\t\t\tif err := s.printOneObject(objs[ix], parsers, out); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif err := s.printOneObject(obj, parsers, out); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":159,"to":206}} {"id":100031917,"name":"printOneObject","signature":"func (s *CustomColumnsPrinter) printOneObject(obj runtime.Object, parsers []*jsonpath.JSONPath, out io.Writer) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/customcolumn.go","code":"func (s *CustomColumnsPrinter) printOneObject(obj runtime.Object, parsers []*jsonpath.JSONPath, out io.Writer) error {\n\tcolumns := make([]string, len(parsers))\n\tswitch u := obj.(type) {\n\tcase *metav1.WatchEvent:\n\t\tif printers.InternalObjectPreventer.IsForbidden(reflect.Indirect(reflect.ValueOf(u.Object.Object)).Type().PkgPath()) {\n\t\t\treturn fmt.Errorf(printers.InternalObjectPrinterErr)\n\t\t}\n\t\tunstructuredObject, err := runtime.DefaultUnstructuredConverter.ToUnstructured(u.Object.Object)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tobj = \u0026unstructured.Unstructured{\n\t\t\tObject: map[string]interface{}{\n\t\t\t\t\"type\": u.Type,\n\t\t\t\t\"object\": unstructuredObject,\n\t\t\t},\n\t\t}\n\n\tcase *runtime.Unknown:\n\t\tif len(u.Raw) \u003e 0 {\n\t\t\tvar err error\n\t\t\tif obj, err = runtime.Decode(s.Decoder, u.Raw); err != nil {\n\t\t\t\treturn fmt.Errorf(\"can't decode object for printing: %v (%s)\", err, u.Raw)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor ix := range parsers {\n\t\tparser := parsers[ix]\n\n\t\tvar values [][]reflect.Value\n\t\tvar err error\n\t\tif unstructured, ok := obj.(runtime.Unstructured); ok {\n\t\t\tvalues, err = parser.FindResults(unstructured.UnstructuredContent())\n\t\t} else {\n\t\t\tvalues, err = parser.FindResults(reflect.ValueOf(obj).Elem().Interface())\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvalueStrings := []string{}\n\t\tif len(values) == 0 || len(values[0]) == 0 {\n\t\t\tvalueStrings = append(valueStrings, \"\u003cnone\u003e\")\n\t\t}\n\t\tfor arrIx := range values {\n\t\t\tfor valIx := range values[arrIx] {\n\t\t\t\tvalueStrings = append(valueStrings, printers.EscapeTerminal(fmt.Sprint(values[arrIx][valIx].Interface())))\n\t\t\t}\n\t\t}\n\t\tcolumns[ix] = strings.Join(valueStrings, \",\")\n\t}\n\tfmt.Fprintln(out, strings.Join(columns, \"\\t\"))\n\treturn nil\n}","line":{"from":208,"to":262}} {"id":100031918,"name":"AllowedFormats","signature":"func (f *CustomColumnsPrintFlags) AllowedFormats() []string","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/customcolumn_flags.go","code":"func (f *CustomColumnsPrintFlags) AllowedFormats() []string {\n\tformats := make([]string, 0, len(columnsFormats))\n\tfor format := range columnsFormats {\n\t\tformats = append(formats, format)\n\t}\n\tsort.Strings(formats)\n\treturn formats\n}","line":{"from":44,"to":51}} {"id":100031919,"name":"ToPrinter","signature":"func (f *CustomColumnsPrintFlags) ToPrinter(templateFormat string) (printers.ResourcePrinter, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/customcolumn_flags.go","code":"// ToPrinter receives an templateFormat and returns a printer capable of\n// handling custom-column printing.\n// Returns false if the specified templateFormat does not match a supported format.\n// Supported format types can be found in pkg/printers/printers.go\nfunc (f *CustomColumnsPrintFlags) ToPrinter(templateFormat string) (printers.ResourcePrinter, error) {\n\tif len(templateFormat) == 0 {\n\t\treturn nil, genericclioptions.NoCompatiblePrinterError{}\n\t}\n\n\ttemplateValue := \"\"\n\n\tif len(f.TemplateArgument) == 0 {\n\t\tfor format := range columnsFormats {\n\t\t\tformat = format + \"=\"\n\t\t\tif strings.HasPrefix(templateFormat, format) {\n\t\t\t\ttemplateValue = templateFormat[len(format):]\n\t\t\t\ttemplateFormat = format[:len(format)-1]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t} else {\n\t\ttemplateValue = f.TemplateArgument\n\t}\n\n\tif _, supportedFormat := columnsFormats[templateFormat]; !supportedFormat {\n\t\treturn nil, genericclioptions.NoCompatiblePrinterError{OutputFormat: \u0026templateFormat, AllowedFormats: f.AllowedFormats()}\n\t}\n\n\tif len(templateValue) == 0 {\n\t\treturn nil, fmt.Errorf(\"custom-columns format specified but no custom columns given\")\n\t}\n\n\t// UniversalDecoder call must specify parameter versions; otherwise it will decode to internal versions.\n\tdecoder := scheme.Codecs.UniversalDecoder(scheme.Scheme.PrioritizedVersionsAllGroups()...)\n\n\tif templateFormat == \"custom-columns-file\" {\n\t\tfile, err := os.Open(templateValue)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error reading template %s, %v\\n\", templateValue, err)\n\t\t}\n\t\tdefer file.Close()\n\t\tp, err := NewCustomColumnsPrinterFromTemplate(file, decoder)\n\t\treturn p, err\n\t}\n\n\treturn NewCustomColumnsPrinterFromSpec(templateValue, decoder, f.NoHeaders)\n}","line":{"from":53,"to":99}} {"id":100031920,"name":"AddFlags","signature":"func (f *CustomColumnsPrintFlags) AddFlags(c *cobra.Command) {}","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/customcolumn_flags.go","code":"// AddFlags receives a *cobra.Command reference and binds\n// flags related to custom-columns printing\nfunc (f *CustomColumnsPrintFlags) AddFlags(c *cobra.Command) {}","line":{"from":101,"to":103}} {"id":100031921,"name":"NewCustomColumnsPrintFlags","signature":"func NewCustomColumnsPrintFlags() *CustomColumnsPrintFlags","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/customcolumn_flags.go","code":"// NewCustomColumnsPrintFlags returns flags associated with\n// custom-column printing, with default values set.\n// NoHeaders and TemplateArgument should be set by callers.\nfunc NewCustomColumnsPrintFlags() *CustomColumnsPrintFlags {\n\treturn \u0026CustomColumnsPrintFlags{\n\t\tNoHeaders: false,\n\t\tTemplateArgument: \"\",\n\t}\n}","line":{"from":105,"to":113}} {"id":100031922,"name":"NewGetOptions","signature":"func NewGetOptions(parent string, streams genericclioptions.IOStreams) *GetOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get.go","code":"// NewGetOptions returns a GetOptions with default chunk size 500.\nfunc NewGetOptions(parent string, streams genericclioptions.IOStreams) *GetOptions {\n\treturn \u0026GetOptions{\n\t\tPrintFlags: NewGetPrintFlags(),\n\t\tCmdParent: parent,\n\n\t\tIOStreams: streams,\n\t\tChunkSize: cmdutil.DefaultChunkSize,\n\t\tServerPrint: true,\n\t}\n}","line":{"from":144,"to":154}} {"id":100031923,"name":"NewCmdGet","signature":"func NewCmdGet(parent string, f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get.go","code":"// NewCmdGet creates a command object for the generic \"get\" action, which\n// retrieves one or more resources from a server.\nfunc NewCmdGet(parent string, f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\to := NewGetOptions(parent, streams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: fmt.Sprintf(\"get [(-o|--output=)%s] (TYPE[.VERSION][.GROUP] [NAME | -l label] | TYPE[.VERSION][.GROUP]/NAME ...) [flags]\", strings.Join(o.PrintFlags.AllowedFormats(), \"|\")),\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Display one or many resources\"),\n\t\tLong: getLong + \"\\n\\n\" + cmdutil.SuggestAPIResources(parent),\n\t\tExample: getExample,\n\t\t// ValidArgsFunction is set when this function is called so that we have access to the util package\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run(f, args))\n\t\t},\n\t\tSuggestFor: []string{\"list\", \"ps\"},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmd.Flags().StringVar(\u0026o.Raw, \"raw\", o.Raw, \"Raw URI to request from the server. Uses the transport specified by the kubeconfig file.\")\n\tcmd.Flags().BoolVarP(\u0026o.Watch, \"watch\", \"w\", o.Watch, \"After listing/getting the requested object, watch for changes.\")\n\tcmd.Flags().BoolVar(\u0026o.WatchOnly, \"watch-only\", o.WatchOnly, \"Watch for changes to the requested object(s), without listing/getting first.\")\n\tcmd.Flags().BoolVar(\u0026o.OutputWatchEvents, \"output-watch-events\", o.OutputWatchEvents, \"Output watch event objects when --watch or --watch-only is used. Existing objects are output as initial ADDED events.\")\n\tcmd.Flags().BoolVar(\u0026o.IgnoreNotFound, \"ignore-not-found\", o.IgnoreNotFound, \"If the requested object does not exist the command will return exit code 0.\")\n\tcmd.Flags().StringVar(\u0026o.FieldSelector, \"field-selector\", o.FieldSelector, \"Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector key1=value1,key2=value2). The server only supports a limited number of field queries per type.\")\n\tcmd.Flags().BoolVarP(\u0026o.AllNamespaces, \"all-namespaces\", \"A\", o.AllNamespaces, \"If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace.\")\n\taddServerPrintColumnFlags(cmd, o)\n\tcmdutil.AddFilenameOptionFlags(cmd, \u0026o.FilenameOptions, \"identifying the resource to get from a server.\")\n\tcmdutil.AddChunkSizeFlag(cmd, \u0026o.ChunkSize)\n\tcmdutil.AddLabelSelectorFlagVar(cmd, \u0026o.LabelSelector)\n\tcmdutil.AddSubresourceFlags(cmd, \u0026o.Subresource, \"If specified, gets the subresource of the requested object.\", supportedSubresources...)\n\treturn cmd\n}","line":{"from":156,"to":191}} {"id":100031924,"name":"Complete","signature":"func (o *GetOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get.go","code":"// Complete takes the command arguments and factory and infers any remaining options.\nfunc (o *GetOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tif len(o.Raw) \u003e 0 {\n\t\tif len(args) \u003e 0 {\n\t\t\treturn fmt.Errorf(\"arguments may not be passed when --raw is specified\")\n\t\t}\n\t\treturn nil\n\t}\n\n\tvar err error\n\to.Namespace, o.ExplicitNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif o.AllNamespaces {\n\t\to.ExplicitNamespace = false\n\t}\n\n\tif o.PrintFlags.HumanReadableFlags.SortBy != nil {\n\t\to.SortBy = *o.PrintFlags.HumanReadableFlags.SortBy\n\t}\n\n\to.NoHeaders = cmdutil.GetFlagBool(cmd, \"no-headers\")\n\n\t// TODO (soltysh): currently we don't support custom columns\n\t// with server side print. So in these cases force the old behavior.\n\toutputOption := cmd.Flags().Lookup(\"output\").Value.String()\n\tif strings.Contains(outputOption, \"custom-columns\") || outputOption == \"yaml\" || strings.Contains(outputOption, \"json\") {\n\t\to.ServerPrint = false\n\t}\n\n\ttemplateArg := \"\"\n\tif o.PrintFlags.TemplateFlags != nil \u0026\u0026 o.PrintFlags.TemplateFlags.TemplateArgument != nil {\n\t\ttemplateArg = *o.PrintFlags.TemplateFlags.TemplateArgument\n\t}\n\n\t// human readable printers have special conversion rules, so we determine if we're using one.\n\tif (len(*o.PrintFlags.OutputFormat) == 0 \u0026\u0026 len(templateArg) == 0) || *o.PrintFlags.OutputFormat == \"wide\" {\n\t\to.IsHumanReadablePrinter = true\n\t}\n\n\to.ToPrinter = func(mapping *meta.RESTMapping, outputObjects *bool, withNamespace bool, withKind bool) (printers.ResourcePrinterFunc, error) {\n\t\t// make a new copy of current flags / opts before mutating\n\t\tprintFlags := o.PrintFlags.Copy()\n\n\t\tif mapping != nil {\n\t\t\tprintFlags.SetKind(mapping.GroupVersionKind.GroupKind())\n\t\t}\n\t\tif withNamespace {\n\t\t\tprintFlags.EnsureWithNamespace()\n\t\t}\n\t\tif withKind {\n\t\t\tprintFlags.EnsureWithKind()\n\t\t}\n\n\t\tprinter, err := printFlags.ToPrinter()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tprinter, err = printers.NewTypeSetter(scheme.Scheme).WrapToPrinter(printer, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif len(o.SortBy) \u003e 0 {\n\t\t\tprinter = \u0026SortingPrinter{Delegate: printer, SortField: o.SortBy}\n\t\t}\n\t\tif outputObjects != nil {\n\t\t\tprinter = \u0026skipPrinter{delegate: printer, output: outputObjects}\n\t\t}\n\t\tif o.ServerPrint {\n\t\t\tprinter = \u0026TablePrinter{Delegate: printer}\n\t\t}\n\t\treturn printer.PrintObj, nil\n\t}\n\n\tswitch {\n\tcase o.Watch || o.WatchOnly:\n\t\tif len(o.SortBy) \u003e 0 {\n\t\t\tfmt.Fprintf(o.IOStreams.ErrOut, \"warning: --watch or --watch-only requested, --sort-by will be ignored\\n\")\n\t\t}\n\tdefault:\n\t\tif len(args) == 0 \u0026\u0026 cmdutil.IsFilenameSliceEmpty(o.Filenames, o.Kustomize) {\n\t\t\tfmt.Fprintf(o.ErrOut, \"You must specify the type of resource to get. %s\\n\\n\", cmdutil.SuggestAPIResources(o.CmdParent))\n\t\t\tfullCmdName := cmd.Parent().CommandPath()\n\t\t\tusageString := \"Required resource not specified.\"\n\t\t\tif len(fullCmdName) \u003e 0 \u0026\u0026 cmdutil.IsSiblingCommandExists(cmd, \"explain\") {\n\t\t\t\tusageString = fmt.Sprintf(\"%s\\nUse \\\"%s explain \u003cresource\u003e\\\" for a detailed description of that resource (e.g. %[2]s explain pods).\", usageString, fullCmdName)\n\t\t\t}\n\n\t\t\treturn cmdutil.UsageErrorf(cmd, usageString)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":193,"to":288}} {"id":100031925,"name":"Validate","signature":"func (o *GetOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get.go","code":"// Validate checks the set of flags provided by the user.\nfunc (o *GetOptions) Validate() error {\n\tif len(o.Raw) \u003e 0 {\n\t\tif o.Watch || o.WatchOnly || len(o.LabelSelector) \u003e 0 {\n\t\t\treturn fmt.Errorf(\"--raw may not be specified with other flags that filter the server request or alter the output\")\n\t\t}\n\t\tif o.PrintFlags.OutputFormat != nil \u0026\u0026 len(*o.PrintFlags.OutputFormat) \u003e 0 {\n\t\t\treturn fmt.Errorf(\"--raw and --output are mutually exclusive\")\n\t\t}\n\t\tif _, err := url.ParseRequestURI(o.Raw); err != nil {\n\t\t\treturn fmt.Errorf(\"--raw must be a valid URL path: %v\", err)\n\t\t}\n\t}\n\tif o.PrintFlags.HumanReadableFlags.ShowLabels != nil \u0026\u0026 *o.PrintFlags.HumanReadableFlags.ShowLabels \u0026\u0026 o.PrintFlags.OutputFormat != nil {\n\t\toutputOption := *o.PrintFlags.OutputFormat\n\t\tif outputOption != \"\" \u0026\u0026 outputOption != \"wide\" {\n\t\t\treturn fmt.Errorf(\"--show-labels option cannot be used with %s printer\", outputOption)\n\t\t}\n\t}\n\tif o.OutputWatchEvents \u0026\u0026 !(o.Watch || o.WatchOnly) {\n\t\treturn fmt.Errorf(\"--output-watch-events option can only be used with --watch or --watch-only\")\n\t}\n\tif len(o.Subresource) \u003e 0 \u0026\u0026 !slice.ContainsString(supportedSubresources, o.Subresource, nil) {\n\t\treturn fmt.Errorf(\"invalid subresource value: %q. Must be one of %v\", o.Subresource, supportedSubresources)\n\t}\n\treturn nil\n}","line":{"from":290,"to":316}} {"id":100031926,"name":"OriginalPosition","signature":"func (t *NopPositioner) OriginalPosition(ix int) int","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get.go","code":"// OriginalPosition returns the original position from NopPositioner object\nfunc (t *NopPositioner) OriginalPosition(ix int) int {\n\treturn ix\n}","line":{"from":326,"to":329}} {"id":100031927,"name":"Sort","signature":"func (r *RuntimeSorter) Sort() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get.go","code":"// Sort performs the sorting of runtime objects\nfunc (r *RuntimeSorter) Sort() error {\n\t// a list is only considered \"sorted\" if there are 0 or 1 items in it\n\t// AND (if 1 item) the item is not a Table object\n\tif len(r.objects) == 0 {\n\t\treturn nil\n\t}\n\tif len(r.objects) == 1 {\n\t\t_, isTable := r.objects[0].(*metav1.Table)\n\t\tif !isTable {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tincludesTable := false\n\tincludesRuntimeObjs := false\n\n\tfor _, obj := range r.objects {\n\t\tswitch t := obj.(type) {\n\t\tcase *metav1.Table:\n\t\t\tincludesTable = true\n\n\t\t\tif sorter, err := NewTableSorter(t, r.field); err != nil {\n\t\t\t\treturn err\n\t\t\t} else if err := sorter.Sort(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tincludesRuntimeObjs = true\n\t\t}\n\t}\n\n\t// we use a NopPositioner when dealing with Table objects\n\t// because the objects themselves are not swapped, but rather\n\t// the rows in each object are swapped / sorted.\n\tr.positioner = \u0026NopPositioner{}\n\n\tif includesRuntimeObjs \u0026\u0026 includesTable {\n\t\treturn fmt.Errorf(\"sorting is not supported on mixed Table and non-Table object lists\")\n\t}\n\tif includesTable {\n\t\treturn nil\n\t}\n\n\t// if not dealing with a Table response from the server, assume\n\t// all objects are runtime.Object as usual, and sort using old method.\n\tvar err error\n\tif r.positioner, err = SortObjects(r.decoder, r.objects, r.field); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":339,"to":390}} {"id":100031928,"name":"OriginalPosition","signature":"func (r *RuntimeSorter) OriginalPosition(ix int) int","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get.go","code":"// OriginalPosition returns the original position of a runtime object\nfunc (r *RuntimeSorter) OriginalPosition(ix int) int {\n\tif r.positioner == nil {\n\t\treturn 0\n\t}\n\treturn r.positioner.OriginalPosition(ix)\n}","line":{"from":392,"to":398}} {"id":100031929,"name":"WithDecoder","signature":"func (r *RuntimeSorter) WithDecoder(decoder runtime.Decoder) *RuntimeSorter","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get.go","code":"// WithDecoder allows custom decoder to be set for testing\nfunc (r *RuntimeSorter) WithDecoder(decoder runtime.Decoder) *RuntimeSorter {\n\tr.decoder = decoder\n\treturn r\n}","line":{"from":400,"to":404}} {"id":100031930,"name":"NewRuntimeSorter","signature":"func NewRuntimeSorter(objects []runtime.Object, sortBy string) *RuntimeSorter","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get.go","code":"// NewRuntimeSorter returns a new instance of RuntimeSorter\nfunc NewRuntimeSorter(objects []runtime.Object, sortBy string) *RuntimeSorter {\n\tparsedField, err := RelaxedJSONPathExpression(sortBy)\n\tif err != nil {\n\t\tparsedField = sortBy\n\t}\n\n\treturn \u0026RuntimeSorter{\n\t\tfield: parsedField,\n\t\tdecoder: kubernetesscheme.Codecs.UniversalDecoder(),\n\t\tobjects: objects,\n\t}\n}","line":{"from":406,"to":418}} {"id":100031931,"name":"transformRequests","signature":"func (o *GetOptions) transformRequests(req *rest.Request)","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get.go","code":"func (o *GetOptions) transformRequests(req *rest.Request) {\n\tif !o.ServerPrint || !o.IsHumanReadablePrinter {\n\t\treturn\n\t}\n\n\treq.SetHeader(\"Accept\", strings.Join([]string{\n\t\tfmt.Sprintf(\"application/json;as=Table;v=%s;g=%s\", metav1.SchemeGroupVersion.Version, metav1.GroupName),\n\t\tfmt.Sprintf(\"application/json;as=Table;v=%s;g=%s\", metav1beta1.SchemeGroupVersion.Version, metav1beta1.GroupName),\n\t\t\"application/json\",\n\t}, \",\"))\n\n\t// if sorting, ensure we receive the full object in order to introspect its fields via jsonpath\n\tif len(o.SortBy) \u003e 0 {\n\t\treq.Param(\"includeObject\", \"Object\")\n\t}\n}","line":{"from":420,"to":435}} {"id":100031932,"name":"Run","signature":"func (o *GetOptions) Run(f cmdutil.Factory, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get.go","code":"// Run performs the get operation.\n// TODO: remove the need to pass these arguments, like other commands.\nfunc (o *GetOptions) Run(f cmdutil.Factory, args []string) error {\n\tif len(o.Raw) \u003e 0 {\n\t\trestClient, err := f.RESTClient()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn rawhttp.RawGet(restClient, o.IOStreams, o.Raw)\n\t}\n\tif o.Watch || o.WatchOnly {\n\t\treturn o.watch(f, args)\n\t}\n\n\tchunkSize := o.ChunkSize\n\tif len(o.SortBy) \u003e 0 {\n\t\t// TODO(juanvallejo): in the future, we could have the client use chunking\n\t\t// to gather all results, then sort them all at the end to reduce server load.\n\t\tchunkSize = 0\n\t}\n\n\tr := f.NewBuilder().\n\t\tUnstructured().\n\t\tNamespaceParam(o.Namespace).DefaultNamespace().AllNamespaces(o.AllNamespaces).\n\t\tFilenameParam(o.ExplicitNamespace, \u0026o.FilenameOptions).\n\t\tLabelSelectorParam(o.LabelSelector).\n\t\tFieldSelectorParam(o.FieldSelector).\n\t\tSubresource(o.Subresource).\n\t\tRequestChunksOf(chunkSize).\n\t\tResourceTypeOrNameArgs(true, args...).\n\t\tContinueOnError().\n\t\tLatest().\n\t\tFlatten().\n\t\tTransformRequests(o.transformRequests).\n\t\tDo()\n\n\tif o.IgnoreNotFound {\n\t\tr.IgnoreErrors(apierrors.IsNotFound)\n\t}\n\tif err := r.Err(); err != nil {\n\t\treturn err\n\t}\n\n\tif !o.IsHumanReadablePrinter {\n\t\treturn o.printGeneric(r)\n\t}\n\n\tallErrs := []error{}\n\terrs := sets.NewString()\n\tinfos, err := r.Infos()\n\tif err != nil {\n\t\tallErrs = append(allErrs, err)\n\t}\n\tprintWithKind := multipleGVKsRequested(infos)\n\n\tobjs := make([]runtime.Object, len(infos))\n\tfor ix := range infos {\n\t\tobjs[ix] = infos[ix].Object\n\t}\n\n\tvar positioner OriginalPositioner\n\tif len(o.SortBy) \u003e 0 {\n\t\tsorter := NewRuntimeSorter(objs, o.SortBy)\n\t\tif err := sorter.Sort(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpositioner = sorter\n\t}\n\n\tvar printer printers.ResourcePrinter\n\tvar lastMapping *meta.RESTMapping\n\n\t// track if we write any output\n\ttrackingWriter := \u0026trackingWriterWrapper{Delegate: o.Out}\n\t// output an empty line separating output\n\tseparatorWriter := \u0026separatorWriterWrapper{Delegate: trackingWriter}\n\n\tw := printers.GetNewTabWriter(separatorWriter)\n\tallResourcesNamespaced := !o.AllNamespaces\n\tfor ix := range objs {\n\t\tvar mapping *meta.RESTMapping\n\t\tvar info *resource.Info\n\t\tif positioner != nil {\n\t\t\tinfo = infos[positioner.OriginalPosition(ix)]\n\t\t\tmapping = info.Mapping\n\t\t} else {\n\t\t\tinfo = infos[ix]\n\t\t\tmapping = info.Mapping\n\t\t}\n\n\t\tallResourcesNamespaced = allResourcesNamespaced \u0026\u0026 info.Namespaced()\n\t\tprintWithNamespace := o.AllNamespaces\n\n\t\tif mapping != nil \u0026\u0026 mapping.Scope.Name() == meta.RESTScopeNameRoot {\n\t\t\tprintWithNamespace = false\n\t\t}\n\n\t\tif shouldGetNewPrinterForMapping(printer, lastMapping, mapping) {\n\t\t\tw.Flush()\n\t\t\tw.SetRememberedWidths(nil)\n\n\t\t\t// add linebreaks between resource groups (if there is more than one)\n\t\t\t// when it satisfies all following 3 conditions:\n\t\t\t// 1) it's not the first resource group\n\t\t\t// 2) it has row header\n\t\t\t// 3) we've written output since the last time we started a new set of headers\n\t\t\tif lastMapping != nil \u0026\u0026 !o.NoHeaders \u0026\u0026 trackingWriter.Written \u003e 0 {\n\t\t\t\tseparatorWriter.SetReady(true)\n\t\t\t}\n\n\t\t\tprinter, err = o.ToPrinter(mapping, nil, printWithNamespace, printWithKind)\n\t\t\tif err != nil {\n\t\t\t\tif !errs.Has(err.Error()) {\n\t\t\t\t\terrs.Insert(err.Error())\n\t\t\t\t\tallErrs = append(allErrs, err)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlastMapping = mapping\n\t\t}\n\n\t\tprinter.PrintObj(info.Object, w)\n\t}\n\tw.Flush()\n\tif trackingWriter.Written == 0 \u0026\u0026 !o.IgnoreNotFound \u0026\u0026 len(allErrs) == 0 {\n\t\t// if we wrote no output, and had no errors, and are not ignoring NotFound, be sure we output something\n\t\tif allResourcesNamespaced {\n\t\t\tfmt.Fprintf(o.ErrOut, \"No resources found in %s namespace.\\n\", o.Namespace)\n\t\t} else {\n\t\t\tfmt.Fprintln(o.ErrOut, \"No resources found\")\n\t\t}\n\t}\n\treturn utilerrors.NewAggregate(allErrs)\n}","line":{"from":437,"to":571}} {"id":100031933,"name":"Write","signature":"func (t *trackingWriterWrapper) Write(p []byte) (n int, err error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get.go","code":"func (t *trackingWriterWrapper) Write(p []byte) (n int, err error) {\n\tt.Written += len(p)\n\treturn t.Delegate.Write(p)\n}","line":{"from":578,"to":581}} {"id":100031934,"name":"Write","signature":"func (s *separatorWriterWrapper) Write(p []byte) (n int, err error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get.go","code":"func (s *separatorWriterWrapper) Write(p []byte) (n int, err error) {\n\t// If we're about to write non-empty bytes and `s` is ready,\n\t// we prepend an empty line to `p` and reset `s.Read`.\n\tif len(p) != 0 \u0026\u0026 s.Ready {\n\t\tfmt.Fprintln(s.Delegate)\n\t\ts.Ready = false\n\t}\n\treturn s.Delegate.Write(p)\n}","line":{"from":588,"to":596}} {"id":100031935,"name":"SetReady","signature":"func (s *separatorWriterWrapper) SetReady(state bool)","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get.go","code":"func (s *separatorWriterWrapper) SetReady(state bool) {\n\ts.Ready = state\n}","line":{"from":598,"to":600}} {"id":100031936,"name":"watch","signature":"func (o *GetOptions) watch(f cmdutil.Factory, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get.go","code":"// watch starts a client-side watch of one or more resources.\n// TODO: remove the need for arguments here.\nfunc (o *GetOptions) watch(f cmdutil.Factory, args []string) error {\n\tr := f.NewBuilder().\n\t\tUnstructured().\n\t\tNamespaceParam(o.Namespace).DefaultNamespace().AllNamespaces(o.AllNamespaces).\n\t\tFilenameParam(o.ExplicitNamespace, \u0026o.FilenameOptions).\n\t\tLabelSelectorParam(o.LabelSelector).\n\t\tFieldSelectorParam(o.FieldSelector).\n\t\tRequestChunksOf(o.ChunkSize).\n\t\tResourceTypeOrNameArgs(true, args...).\n\t\tSingleResourceType().\n\t\tLatest().\n\t\tTransformRequests(o.transformRequests).\n\t\tDo()\n\tif err := r.Err(); err != nil {\n\t\treturn err\n\t}\n\tinfos, err := r.Infos()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif multipleGVKsRequested(infos) {\n\t\treturn i18n.Errorf(\"watch is only supported on individual resources and resource collections - more than 1 resource was found\")\n\t}\n\n\tinfo := infos[0]\n\tmapping := info.ResourceMapping()\n\toutputObjects := utilpointer.BoolPtr(!o.WatchOnly)\n\tprinter, err := o.ToPrinter(mapping, outputObjects, o.AllNamespaces, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\tobj, err := r.Object()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// watching from resourceVersion 0, starts the watch at ~now and\n\t// will return an initial watch event. Starting form ~now, rather\n\t// the rv of the object will insure that we start the watch from\n\t// inside the watch window, which the rv of the object might not be.\n\trv := \"0\"\n\tisList := meta.IsListType(obj)\n\tif isList {\n\t\t// the resourceVersion of list objects is ~now but won't return\n\t\t// an initial watch event\n\t\trv, err = meta.NewAccessor().ResourceVersion(obj)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\twriter := printers.GetNewTabWriter(o.Out)\n\n\t// print the current object\n\tvar objsToPrint []runtime.Object\n\tif isList {\n\t\tobjsToPrint, _ = meta.ExtractList(obj)\n\t} else {\n\t\tobjsToPrint = append(objsToPrint, obj)\n\t}\n\tfor _, objToPrint := range objsToPrint {\n\t\tif o.OutputWatchEvents {\n\t\t\tobjToPrint = \u0026metav1.WatchEvent{Type: string(watch.Added), Object: runtime.RawExtension{Object: objToPrint}}\n\t\t}\n\t\tif err := printer.PrintObj(objToPrint, writer); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to output the provided object: %v\", err)\n\t\t}\n\t}\n\twriter.Flush()\n\tif isList {\n\t\t// we can start outputting objects now, watches started from lists don't emit synthetic added events\n\t\t*outputObjects = true\n\t} else {\n\t\t// suppress output, since watches started for individual items emit a synthetic ADDED event first\n\t\t*outputObjects = false\n\t}\n\n\t// print watched changes\n\tw, err := r.Watch(rv)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tintr := interrupt.New(nil, cancel)\n\tintr.Run(func() error {\n\t\t_, err := watchtools.UntilWithoutRetry(ctx, w, func(e watch.Event) (bool, error) {\n\t\t\tobjToPrint := e.Object\n\t\t\tif o.OutputWatchEvents {\n\t\t\t\tobjToPrint = \u0026metav1.WatchEvent{Type: string(e.Type), Object: runtime.RawExtension{Object: objToPrint}}\n\t\t\t}\n\t\t\tif err := printer.PrintObj(objToPrint, writer); err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\twriter.Flush()\n\t\t\t// after processing at least one event, start outputting objects\n\t\t\t*outputObjects = true\n\t\t\treturn false, nil\n\t\t})\n\t\treturn err\n\t})\n\treturn nil\n}","line":{"from":602,"to":707}} {"id":100031937,"name":"printGeneric","signature":"func (o *GetOptions) printGeneric(r *resource.Result) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get.go","code":"func (o *GetOptions) printGeneric(r *resource.Result) error {\n\t// we flattened the data from the builder, so we have individual items, but now we'd like to either:\n\t// 1. if there is more than one item, combine them all into a single list\n\t// 2. if there is a single item and that item is a list, leave it as its specific list\n\t// 3. if there is a single item and it is not a list, leave it as a single item\n\tvar errs []error\n\tsingleItemImplied := false\n\tinfos, err := r.IntoSingleItemImplied(\u0026singleItemImplied).Infos()\n\tif err != nil {\n\t\tif singleItemImplied {\n\t\t\treturn err\n\t\t}\n\t\terrs = append(errs, err)\n\t}\n\n\tif len(infos) == 0 \u0026\u0026 o.IgnoreNotFound {\n\t\treturn utilerrors.Reduce(utilerrors.Flatten(utilerrors.NewAggregate(errs)))\n\t}\n\n\tprinter, err := o.ToPrinter(nil, nil, false, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar obj runtime.Object\n\tif !singleItemImplied || len(infos) != 1 {\n\t\t// we have zero or multple items, so coerce all items into a list.\n\t\t// we don't want an *unstructured.Unstructured list yet, as we\n\t\t// may be dealing with non-unstructured objects. Compose all items\n\t\t// into an corev1.List, and then decode using an unstructured scheme.\n\t\tlist := corev1.List{\n\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\tKind: \"List\",\n\t\t\t\tAPIVersion: \"v1\",\n\t\t\t},\n\t\t\tListMeta: metav1.ListMeta{},\n\t\t}\n\t\tfor _, info := range infos {\n\t\t\tlist.Items = append(list.Items, runtime.RawExtension{Object: info.Object})\n\t\t}\n\n\t\tlistData, err := json.Marshal(list)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tconverted, err := runtime.Decode(unstructured.UnstructuredJSONScheme, listData)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tobj = converted\n\t} else {\n\t\tobj = infos[0].Object\n\t}\n\n\tisList := meta.IsListType(obj)\n\tif isList {\n\t\titems, err := meta.ExtractList(obj)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// take the items and create a new list for display\n\t\tlist := \u0026unstructured.UnstructuredList{\n\t\t\tObject: map[string]interface{}{\n\t\t\t\t\"kind\": \"List\",\n\t\t\t\t\"apiVersion\": \"v1\",\n\t\t\t\t\"metadata\": map[string]interface{}{},\n\t\t\t},\n\t\t}\n\t\tif listMeta, err := meta.ListAccessor(obj); err == nil {\n\t\t\tlist.Object[\"metadata\"] = map[string]interface{}{\n\t\t\t\t\"resourceVersion\": listMeta.GetResourceVersion(),\n\t\t\t}\n\t\t}\n\n\t\tfor _, item := range items {\n\t\t\tlist.Items = append(list.Items, *item.(*unstructured.Unstructured))\n\t\t}\n\t\tif err := printer.PrintObj(list, o.Out); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t\treturn utilerrors.Reduce(utilerrors.Flatten(utilerrors.NewAggregate(errs)))\n\t}\n\n\tif printErr := printer.PrintObj(obj, o.Out); printErr != nil {\n\t\terrs = append(errs, printErr)\n\t}\n\n\treturn utilerrors.Reduce(utilerrors.Flatten(utilerrors.NewAggregate(errs)))\n}","line":{"from":709,"to":800}} {"id":100031938,"name":"addServerPrintColumnFlags","signature":"func addServerPrintColumnFlags(cmd *cobra.Command, opt *GetOptions)","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get.go","code":"func addServerPrintColumnFlags(cmd *cobra.Command, opt *GetOptions) {\n\tcmd.Flags().BoolVar(\u0026opt.ServerPrint, useServerPrintColumns, opt.ServerPrint, \"If true, have the server return the appropriate table output. Supports extension APIs and CRDs.\")\n}","line":{"from":802,"to":804}} {"id":100031939,"name":"shouldGetNewPrinterForMapping","signature":"func shouldGetNewPrinterForMapping(printer printers.ResourcePrinter, lastMapping, mapping *meta.RESTMapping) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get.go","code":"func shouldGetNewPrinterForMapping(printer printers.ResourcePrinter, lastMapping, mapping *meta.RESTMapping) bool {\n\treturn printer == nil || lastMapping == nil || mapping == nil || mapping.Resource != lastMapping.Resource\n}","line":{"from":806,"to":808}} {"id":100031940,"name":"multipleGVKsRequested","signature":"func multipleGVKsRequested(infos []*resource.Info) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get.go","code":"func multipleGVKsRequested(infos []*resource.Info) bool {\n\tif len(infos) \u003c 2 {\n\t\treturn false\n\t}\n\tgvk := infos[0].Mapping.GroupVersionKind\n\tfor _, info := range infos {\n\t\tif info.Mapping.GroupVersionKind != gvk {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":810,"to":821}} {"id":100031941,"name":"SetKind","signature":"func (f *PrintFlags) SetKind(kind schema.GroupKind)","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get_flags.go","code":"// SetKind sets the Kind option of humanreadable flags\nfunc (f *PrintFlags) SetKind(kind schema.GroupKind) {\n\tf.HumanReadableFlags.SetKind(kind)\n}","line":{"from":44,"to":47}} {"id":100031942,"name":"EnsureWithNamespace","signature":"func (f *PrintFlags) EnsureWithNamespace() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get_flags.go","code":"// EnsureWithNamespace ensures that humanreadable flags return\n// a printer capable of printing with a \"namespace\" column.\nfunc (f *PrintFlags) EnsureWithNamespace() error {\n\treturn f.HumanReadableFlags.EnsureWithNamespace()\n}","line":{"from":49,"to":53}} {"id":100031943,"name":"EnsureWithKind","signature":"func (f *PrintFlags) EnsureWithKind() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get_flags.go","code":"// EnsureWithKind ensures that humanreadable flags return\n// a printer capable of including resource kinds.\nfunc (f *PrintFlags) EnsureWithKind() error {\n\treturn f.HumanReadableFlags.EnsureWithKind()\n}","line":{"from":55,"to":59}} {"id":100031944,"name":"Copy","signature":"func (f *PrintFlags) Copy() PrintFlags","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get_flags.go","code":"// Copy returns a copy of PrintFlags for mutation\nfunc (f *PrintFlags) Copy() PrintFlags {\n\tprintFlags := *f\n\treturn printFlags\n}","line":{"from":61,"to":65}} {"id":100031945,"name":"AllowedFormats","signature":"func (f *PrintFlags) AllowedFormats() []string","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get_flags.go","code":"// AllowedFormats is the list of formats in which data can be displayed\nfunc (f *PrintFlags) AllowedFormats() []string {\n\tformats := f.JSONYamlPrintFlags.AllowedFormats()\n\tformats = append(formats, f.NamePrintFlags.AllowedFormats()...)\n\tformats = append(formats, f.TemplateFlags.AllowedFormats()...)\n\tformats = append(formats, f.CustomColumnsFlags.AllowedFormats()...)\n\tformats = append(formats, f.HumanReadableFlags.AllowedFormats()...)\n\treturn formats\n}","line":{"from":67,"to":75}} {"id":100031946,"name":"ToPrinter","signature":"func (f *PrintFlags) ToPrinter() (printers.ResourcePrinter, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get_flags.go","code":"// ToPrinter attempts to find a composed set of PrintFlags suitable for\n// returning a printer based on current flag values.\nfunc (f *PrintFlags) ToPrinter() (printers.ResourcePrinter, error) {\n\toutputFormat := \"\"\n\tif f.OutputFormat != nil {\n\t\toutputFormat = *f.OutputFormat\n\t}\n\n\tnoHeaders := false\n\tif f.NoHeaders != nil {\n\t\tnoHeaders = *f.NoHeaders\n\t}\n\tf.HumanReadableFlags.NoHeaders = noHeaders\n\tf.CustomColumnsFlags.NoHeaders = noHeaders\n\n\t// for \"get.go\" we want to support a --template argument given, even when no --output format is provided\n\tif f.TemplateFlags.TemplateArgument != nil \u0026\u0026 len(*f.TemplateFlags.TemplateArgument) \u003e 0 \u0026\u0026 len(outputFormat) == 0 {\n\t\toutputFormat = \"go-template\"\n\t}\n\n\tif p, err := f.TemplateFlags.ToPrinter(outputFormat); !genericclioptions.IsNoCompatiblePrinterError(err) {\n\t\treturn p, err\n\t}\n\n\tif f.TemplateFlags.TemplateArgument != nil {\n\t\tf.CustomColumnsFlags.TemplateArgument = *f.TemplateFlags.TemplateArgument\n\t}\n\n\tif p, err := f.JSONYamlPrintFlags.ToPrinter(outputFormat); !genericclioptions.IsNoCompatiblePrinterError(err) {\n\t\treturn p, err\n\t}\n\n\tif p, err := f.HumanReadableFlags.ToPrinter(outputFormat); !genericclioptions.IsNoCompatiblePrinterError(err) {\n\t\treturn p, err\n\t}\n\n\tif p, err := f.CustomColumnsFlags.ToPrinter(outputFormat); !genericclioptions.IsNoCompatiblePrinterError(err) {\n\t\treturn p, err\n\t}\n\n\tif p, err := f.NamePrintFlags.ToPrinter(outputFormat); !genericclioptions.IsNoCompatiblePrinterError(err) {\n\t\treturn p, err\n\t}\n\n\treturn nil, genericclioptions.NoCompatiblePrinterError{OutputFormat: \u0026outputFormat, AllowedFormats: f.AllowedFormats()}\n}","line":{"from":77,"to":122}} {"id":100031947,"name":"AddFlags","signature":"func (f *PrintFlags) AddFlags(cmd *cobra.Command)","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get_flags.go","code":"// AddFlags receives a *cobra.Command reference and binds\n// flags related to humanreadable and template printing.\nfunc (f *PrintFlags) AddFlags(cmd *cobra.Command) {\n\tf.JSONYamlPrintFlags.AddFlags(cmd)\n\tf.NamePrintFlags.AddFlags(cmd)\n\tf.TemplateFlags.AddFlags(cmd)\n\tf.HumanReadableFlags.AddFlags(cmd)\n\tf.CustomColumnsFlags.AddFlags(cmd)\n\n\tif f.OutputFormat != nil {\n\t\tcmd.Flags().StringVarP(f.OutputFormat, \"output\", \"o\", *f.OutputFormat, fmt.Sprintf(`Output format. One of: (%s). See custom columns [https://kubernetes.io/docs/reference/kubectl/#custom-columns], golang template [http://golang.org/pkg/text/template/#pkg-overview] and jsonpath template [https://kubernetes.io/docs/reference/kubectl/jsonpath/].`, strings.Join(f.AllowedFormats(), \", \")))\n\t\tutil.CheckErr(cmd.RegisterFlagCompletionFunc(\n\t\t\t\"output\",\n\t\t\tfunc(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\t\t\t\tvar comps []string\n\t\t\t\tfor _, format := range f.AllowedFormats() {\n\t\t\t\t\tif strings.HasPrefix(format, toComplete) {\n\t\t\t\t\t\tcomps = append(comps, format)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn comps, cobra.ShellCompDirectiveNoFileComp\n\t\t\t},\n\t\t))\n\t}\n\tif f.NoHeaders != nil {\n\t\tcmd.Flags().BoolVar(f.NoHeaders, \"no-headers\", *f.NoHeaders, \"When using the default or custom-column output format, don't print headers (default print headers).\")\n\t}\n}","line":{"from":124,"to":151}} {"id":100031948,"name":"NewGetPrintFlags","signature":"func NewGetPrintFlags() *PrintFlags","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/get_flags.go","code":"// NewGetPrintFlags returns flags associated with humanreadable,\n// template, and \"name\" printing, with default values set.\nfunc NewGetPrintFlags() *PrintFlags {\n\toutputFormat := \"\"\n\tnoHeaders := false\n\n\treturn \u0026PrintFlags{\n\t\tOutputFormat: \u0026outputFormat,\n\t\tNoHeaders: \u0026noHeaders,\n\n\t\tJSONYamlPrintFlags: genericclioptions.NewJSONYamlPrintFlags(),\n\t\tNamePrintFlags: genericclioptions.NewNamePrintFlags(\"\"),\n\t\tTemplateFlags: genericclioptions.NewKubeTemplatePrintFlags(),\n\n\t\tHumanReadableFlags: NewHumanPrintFlags(),\n\t\tCustomColumnsFlags: NewCustomColumnsPrintFlags(),\n\t}\n}","line":{"from":153,"to":170}} {"id":100031949,"name":"SetKind","signature":"func (f *HumanPrintFlags) SetKind(kind schema.GroupKind)","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/humanreadable_flags.go","code":"// SetKind sets the Kind option\nfunc (f *HumanPrintFlags) SetKind(kind schema.GroupKind) {\n\tf.Kind = kind\n}","line":{"from":43,"to":46}} {"id":100031950,"name":"EnsureWithKind","signature":"func (f *HumanPrintFlags) EnsureWithKind() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/humanreadable_flags.go","code":"// EnsureWithKind sets the \"Showkind\" humanreadable option to true.\nfunc (f *HumanPrintFlags) EnsureWithKind() error {\n\tshowKind := true\n\tf.ShowKind = \u0026showKind\n\treturn nil\n}","line":{"from":48,"to":53}} {"id":100031951,"name":"EnsureWithNamespace","signature":"func (f *HumanPrintFlags) EnsureWithNamespace() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/humanreadable_flags.go","code":"// EnsureWithNamespace sets the \"WithNamespace\" humanreadable option to true.\nfunc (f *HumanPrintFlags) EnsureWithNamespace() error {\n\tf.WithNamespace = true\n\treturn nil\n}","line":{"from":55,"to":59}} {"id":100031952,"name":"AllowedFormats","signature":"func (f *HumanPrintFlags) AllowedFormats() []string","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/humanreadable_flags.go","code":"// AllowedFormats returns more customized formating options\nfunc (f *HumanPrintFlags) AllowedFormats() []string {\n\treturn []string{\"wide\"}\n}","line":{"from":61,"to":64}} {"id":100031953,"name":"ToPrinter","signature":"func (f *HumanPrintFlags) ToPrinter(outputFormat string) (printers.ResourcePrinter, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/humanreadable_flags.go","code":"// ToPrinter receives an outputFormat and returns a printer capable of\n// handling human-readable output.\nfunc (f *HumanPrintFlags) ToPrinter(outputFormat string) (printers.ResourcePrinter, error) {\n\tif len(outputFormat) \u003e 0 \u0026\u0026 outputFormat != \"wide\" {\n\t\treturn nil, genericclioptions.NoCompatiblePrinterError{Options: f, AllowedFormats: f.AllowedFormats()}\n\t}\n\n\tshowKind := false\n\tif f.ShowKind != nil {\n\t\tshowKind = *f.ShowKind\n\t}\n\n\tshowLabels := false\n\tif f.ShowLabels != nil {\n\t\tshowLabels = *f.ShowLabels\n\t}\n\n\tcolumnLabels := []string{}\n\tif f.ColumnLabels != nil {\n\t\tcolumnLabels = *f.ColumnLabels\n\t}\n\n\tp := printers.NewTablePrinter(printers.PrintOptions{\n\t\tKind: f.Kind,\n\t\tWithKind: showKind,\n\t\tNoHeaders: f.NoHeaders,\n\t\tWide: outputFormat == \"wide\",\n\t\tWithNamespace: f.WithNamespace,\n\t\tColumnLabels: columnLabels,\n\t\tShowLabels: showLabels,\n\t})\n\n\t// TODO(juanvallejo): handle sorting here\n\n\treturn p, nil\n}","line":{"from":66,"to":101}} {"id":100031954,"name":"AddFlags","signature":"func (f *HumanPrintFlags) AddFlags(c *cobra.Command)","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/humanreadable_flags.go","code":"// AddFlags receives a *cobra.Command reference and binds\n// flags related to human-readable printing to it\nfunc (f *HumanPrintFlags) AddFlags(c *cobra.Command) {\n\tif f.ShowLabels != nil {\n\t\tc.Flags().BoolVar(f.ShowLabels, \"show-labels\", *f.ShowLabels, \"When printing, show all labels as the last column (default hide labels column)\")\n\t}\n\tif f.SortBy != nil {\n\t\tc.Flags().StringVar(f.SortBy, \"sort-by\", *f.SortBy, \"If non-empty, sort list types using this field specification. The field specification is expressed as a JSONPath expression (e.g. '{.metadata.name}'). The field in the API resource specified by this JSONPath expression must be an integer or a string.\")\n\t}\n\tif f.ColumnLabels != nil {\n\t\tc.Flags().StringSliceVarP(f.ColumnLabels, \"label-columns\", \"L\", *f.ColumnLabels, \"Accepts a comma separated list of labels that are going to be presented as columns. Names are case-sensitive. You can also use multiple flag options like -L label1 -L label2...\")\n\t}\n\tif f.ShowKind != nil {\n\t\tc.Flags().BoolVar(f.ShowKind, \"show-kind\", *f.ShowKind, \"If present, list the resource type for the requested object(s).\")\n\t}\n}","line":{"from":103,"to":118}} {"id":100031955,"name":"NewHumanPrintFlags","signature":"func NewHumanPrintFlags() *HumanPrintFlags","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/humanreadable_flags.go","code":"// NewHumanPrintFlags returns flags associated with\n// human-readable printing, with default values set.\nfunc NewHumanPrintFlags() *HumanPrintFlags {\n\tshowLabels := false\n\tsortBy := \"\"\n\tshowKind := false\n\tcolumnLabels := []string{}\n\n\treturn \u0026HumanPrintFlags{\n\t\tNoHeaders: false,\n\t\tWithNamespace: false,\n\t\tColumnLabels: \u0026columnLabels,\n\n\t\tKind: schema.GroupKind{},\n\t\tShowLabels: \u0026showLabels,\n\t\tSortBy: \u0026sortBy,\n\t\tShowKind: \u0026showKind,\n\t}\n}","line":{"from":120,"to":138}} {"id":100031956,"name":"PrintObj","signature":"func (p *skipPrinter) PrintObj(obj runtime.Object, writer io.Writer) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/skip_printer.go","code":"func (p *skipPrinter) PrintObj(obj runtime.Object, writer io.Writer) error {\n\tif *p.output {\n\t\treturn p.delegate.PrintObj(obj, writer)\n\t}\n\n\ttable, isTable := obj.(*metav1.Table)\n\tif !isTable {\n\t\treturn nil\n\t}\n\n\ttable = table.DeepCopy()\n\ttable.Rows = nil\n\treturn p.delegate.PrintObj(table, writer)\n}","line":{"from":35,"to":48}} {"id":100031957,"name":"PrintObj","signature":"func (s *SortingPrinter) PrintObj(obj runtime.Object, out io.Writer) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/sorter.go","code":"func (s *SortingPrinter) PrintObj(obj runtime.Object, out io.Writer) error {\n\tif table, isTable := obj.(*metav1.Table); isTable \u0026\u0026 len(table.Rows) \u003e 1 {\n\t\tparsedField, err := RelaxedJSONPathExpression(s.SortField)\n\t\tif err != nil {\n\t\t\tparsedField = s.SortField\n\t\t}\n\n\t\tif sorter, err := NewTableSorter(table, parsedField); err != nil {\n\t\t\treturn err\n\t\t} else if err := sorter.Sort(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn s.Delegate.PrintObj(table, out)\n\t}\n\n\tif meta.IsListType(obj) {\n\t\tif err := s.sortObj(obj); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn s.Delegate.PrintObj(obj, out)\n\t}\n\n\treturn s.Delegate.PrintObj(obj, out)\n}","line":{"from":48,"to":71}} {"id":100031958,"name":"sortObj","signature":"func (s *SortingPrinter) sortObj(obj runtime.Object) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/sorter.go","code":"func (s *SortingPrinter) sortObj(obj runtime.Object) error {\n\tobjs, err := meta.ExtractList(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(objs) == 0 {\n\t\treturn nil\n\t}\n\n\tsorter, err := SortObjects(s.Decoder, objs, s.SortField)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch list := obj.(type) {\n\tcase *corev1.List:\n\t\toutputList := make([]runtime.RawExtension, len(objs))\n\t\tfor ix := range objs {\n\t\t\toutputList[ix] = list.Items[sorter.OriginalPosition(ix)]\n\t\t}\n\t\tlist.Items = outputList\n\t\treturn nil\n\t}\n\treturn meta.SetList(obj, objs)\n}","line":{"from":73,"to":97}} {"id":100031959,"name":"SortObjects","signature":"func SortObjects(decoder runtime.Decoder, objs []runtime.Object, fieldInput string) (*RuntimeSort, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/sorter.go","code":"// SortObjects sorts the runtime.Object based on fieldInput and returns RuntimeSort that implements\n// the golang sort interface\nfunc SortObjects(decoder runtime.Decoder, objs []runtime.Object, fieldInput string) (*RuntimeSort, error) {\n\tfor ix := range objs {\n\t\titem := objs[ix]\n\t\tswitch u := item.(type) {\n\t\tcase *runtime.Unknown:\n\t\t\tvar err error\n\t\t\t// decode runtime.Unknown to runtime.Unstructured for sorting.\n\t\t\t// we don't actually want the internal versions of known types.\n\t\t\tif objs[ix], _, err = decoder.Decode(u.Raw, nil, \u0026unstructured.Unstructured{}); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\tfield, err := RelaxedJSONPathExpression(fieldInput)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparser := jsonpath.New(\"sorting\").AllowMissingKeys(true)\n\tif err := parser.Parse(field); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// We don't do any model validation here, so we traverse all objects to be sorted\n\t// and, if the field is valid to at least one of them, we consider it to be a\n\t// valid field; otherwise error out.\n\t// Note that this requires empty fields to be considered later, when sorting.\n\tvar fieldFoundOnce bool\n\tfor _, obj := range objs {\n\t\tvalues, err := findJSONPathResults(parser, obj)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(values) \u003e 0 \u0026\u0026 len(values[0]) \u003e 0 {\n\t\t\tfieldFoundOnce = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !fieldFoundOnce {\n\t\treturn nil, fmt.Errorf(\"couldn't find any field with path %q in the list of objects\", field)\n\t}\n\n\tsorter := NewRuntimeSort(field, objs)\n\tsort.Sort(sorter)\n\treturn sorter, nil\n}","line":{"from":99,"to":147}} {"id":100031960,"name":"NewRuntimeSort","signature":"func NewRuntimeSort(field string, objs []runtime.Object) *RuntimeSort","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/sorter.go","code":"// NewRuntimeSort creates a new RuntimeSort struct that implements golang sort interface\nfunc NewRuntimeSort(field string, objs []runtime.Object) *RuntimeSort {\n\tsorter := \u0026RuntimeSort{field: field, objs: objs, origPosition: make([]int, len(objs))}\n\tfor ix := range objs {\n\t\tsorter.origPosition[ix] = ix\n\t}\n\treturn sorter\n}","line":{"from":157,"to":164}} {"id":100031961,"name":"Len","signature":"func (r *RuntimeSort) Len() int","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/sorter.go","code":"func (r *RuntimeSort) Len() int {\n\treturn len(r.objs)\n}","line":{"from":166,"to":168}} {"id":100031962,"name":"Swap","signature":"func (r *RuntimeSort) Swap(i, j int)","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/sorter.go","code":"func (r *RuntimeSort) Swap(i, j int) {\n\tr.objs[i], r.objs[j] = r.objs[j], r.objs[i]\n\tr.origPosition[i], r.origPosition[j] = r.origPosition[j], r.origPosition[i]\n}","line":{"from":170,"to":173}} {"id":100031963,"name":"isLess","signature":"func isLess(i, j reflect.Value) (bool, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/sorter.go","code":"func isLess(i, j reflect.Value) (bool, error) {\n\tswitch i.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\treturn i.Int() \u003c j.Int(), nil\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\treturn i.Uint() \u003c j.Uint(), nil\n\tcase reflect.Float32, reflect.Float64:\n\t\treturn i.Float() \u003c j.Float(), nil\n\tcase reflect.String:\n\t\treturn sortorder.NaturalLess(i.String(), j.String()), nil\n\tcase reflect.Pointer:\n\t\treturn isLess(i.Elem(), j.Elem())\n\tcase reflect.Struct:\n\t\t// sort metav1.Time\n\t\tin := i.Interface()\n\t\tif t, ok := in.(metav1.Time); ok {\n\t\t\ttime := j.Interface().(metav1.Time)\n\t\t\treturn t.Before(\u0026time), nil\n\t\t}\n\t\t// sort resource.Quantity\n\t\tif iQuantity, ok := in.(resource.Quantity); ok {\n\t\t\tjQuantity := j.Interface().(resource.Quantity)\n\t\t\treturn iQuantity.Cmp(jQuantity) \u003c 0, nil\n\t\t}\n\t\t// fallback to the fields comparison\n\t\tfor idx := 0; idx \u003c i.NumField(); idx++ {\n\t\t\tless, err := isLess(i.Field(idx), j.Field(idx))\n\t\t\tif err != nil || !less {\n\t\t\t\treturn less, err\n\t\t\t}\n\t\t}\n\t\treturn true, nil\n\tcase reflect.Array, reflect.Slice:\n\t\t// note: the length of i and j may be different\n\t\tfor idx := 0; idx \u003c integer.IntMin(i.Len(), j.Len()); idx++ {\n\t\t\tless, err := isLess(i.Index(idx), j.Index(idx))\n\t\t\tif err != nil || !less {\n\t\t\t\treturn less, err\n\t\t\t}\n\t\t}\n\t\treturn true, nil\n\tcase reflect.Interface:\n\t\tif i.IsNil() \u0026\u0026 j.IsNil() {\n\t\t\treturn false, nil\n\t\t} else if i.IsNil() {\n\t\t\treturn true, nil\n\t\t} else if j.IsNil() {\n\t\t\treturn false, nil\n\t\t}\n\t\tswitch itype := i.Interface().(type) {\n\t\tcase uint8:\n\t\t\tif jtype, ok := j.Interface().(uint8); ok {\n\t\t\t\treturn itype \u003c jtype, nil\n\t\t\t}\n\t\tcase uint16:\n\t\t\tif jtype, ok := j.Interface().(uint16); ok {\n\t\t\t\treturn itype \u003c jtype, nil\n\t\t\t}\n\t\tcase uint32:\n\t\t\tif jtype, ok := j.Interface().(uint32); ok {\n\t\t\t\treturn itype \u003c jtype, nil\n\t\t\t}\n\t\tcase uint64:\n\t\t\tif jtype, ok := j.Interface().(uint64); ok {\n\t\t\t\treturn itype \u003c jtype, nil\n\t\t\t}\n\t\tcase int8:\n\t\t\tif jtype, ok := j.Interface().(int8); ok {\n\t\t\t\treturn itype \u003c jtype, nil\n\t\t\t}\n\t\tcase int16:\n\t\t\tif jtype, ok := j.Interface().(int16); ok {\n\t\t\t\treturn itype \u003c jtype, nil\n\t\t\t}\n\t\tcase int32:\n\t\t\tif jtype, ok := j.Interface().(int32); ok {\n\t\t\t\treturn itype \u003c jtype, nil\n\t\t\t}\n\t\tcase int64:\n\t\t\tif jtype, ok := j.Interface().(int64); ok {\n\t\t\t\treturn itype \u003c jtype, nil\n\t\t\t}\n\t\tcase uint:\n\t\t\tif jtype, ok := j.Interface().(uint); ok {\n\t\t\t\treturn itype \u003c jtype, nil\n\t\t\t}\n\t\tcase int:\n\t\t\tif jtype, ok := j.Interface().(int); ok {\n\t\t\t\treturn itype \u003c jtype, nil\n\t\t\t}\n\t\tcase float32:\n\t\t\tif jtype, ok := j.Interface().(float32); ok {\n\t\t\t\treturn itype \u003c jtype, nil\n\t\t\t}\n\t\tcase float64:\n\t\t\tif jtype, ok := j.Interface().(float64); ok {\n\t\t\t\treturn itype \u003c jtype, nil\n\t\t\t}\n\t\tcase string:\n\t\t\tif jtype, ok := j.Interface().(string); ok {\n\t\t\t\t// check if it's a Quantity\n\t\t\t\titypeQuantity, err := resource.ParseQuantity(itype)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn sortorder.NaturalLess(itype, jtype), nil\n\t\t\t\t}\n\t\t\t\tjtypeQuantity, err := resource.ParseQuantity(jtype)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn sortorder.NaturalLess(itype, jtype), nil\n\t\t\t\t}\n\t\t\t\t// Both strings are quantity\n\t\t\t\treturn itypeQuantity.Cmp(jtypeQuantity) \u003c 0, nil\n\t\t\t}\n\t\tdefault:\n\t\t\treturn false, fmt.Errorf(\"unsortable type: %T\", itype)\n\t\t}\n\t\treturn false, fmt.Errorf(\"unsortable interface: %v\", i.Kind())\n\n\tdefault:\n\t\treturn false, fmt.Errorf(\"unsortable type: %v\", i.Kind())\n\t}\n}","line":{"from":175,"to":295}} {"id":100031964,"name":"Less","signature":"func (r *RuntimeSort) Less(i, j int) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/sorter.go","code":"func (r *RuntimeSort) Less(i, j int) bool {\n\tiObj := r.objs[i]\n\tjObj := r.objs[j]\n\n\tvar iValues [][]reflect.Value\n\tvar jValues [][]reflect.Value\n\tvar err error\n\n\tparser := jsonpath.New(\"sorting\").AllowMissingKeys(true)\n\terr = parser.Parse(r.field)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tiValues, err = findJSONPathResults(parser, iObj)\n\tif err != nil {\n\t\tklog.Fatalf(\"Failed to get i values for %#v using %s (%#v)\", iObj, r.field, err)\n\t}\n\n\tjValues, err = findJSONPathResults(parser, jObj)\n\tif err != nil {\n\t\tklog.Fatalf(\"Failed to get j values for %#v using %s (%v)\", jObj, r.field, err)\n\t}\n\n\tif len(iValues) == 0 || len(iValues[0]) == 0 {\n\t\treturn true\n\t}\n\tif len(jValues) == 0 || len(jValues[0]) == 0 {\n\t\treturn false\n\t}\n\tiField := iValues[0][0]\n\tjField := jValues[0][0]\n\n\tless, err := isLess(iField, jField)\n\tif err != nil {\n\t\tklog.Exitf(\"Field %s in %T is an unsortable type: %s, err: %v\", r.field, iObj, iField.Kind().String(), err)\n\t}\n\treturn less\n}","line":{"from":297,"to":335}} {"id":100031965,"name":"OriginalPosition","signature":"func (r *RuntimeSort) OriginalPosition(ix int) int","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/sorter.go","code":"// OriginalPosition returns the starting (original) position of a particular index.\n// e.g. If OriginalPosition(0) returns 5 than the\n// item currently at position 0 was at position 5 in the original unsorted array.\nfunc (r *RuntimeSort) OriginalPosition(ix int) int {\n\tif ix \u003c 0 || ix \u003e len(r.origPosition) {\n\t\treturn -1\n\t}\n\treturn r.origPosition[ix]\n}","line":{"from":337,"to":345}} {"id":100031966,"name":"Len","signature":"func (t *TableSorter) Len() int","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/sorter.go","code":"func (t *TableSorter) Len() int {\n\treturn len(t.obj.Rows)\n}","line":{"from":353,"to":355}} {"id":100031967,"name":"Swap","signature":"func (t *TableSorter) Swap(i, j int)","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/sorter.go","code":"func (t *TableSorter) Swap(i, j int) {\n\tt.obj.Rows[i], t.obj.Rows[j] = t.obj.Rows[j], t.obj.Rows[i]\n\tt.parsedRows[i], t.parsedRows[j] = t.parsedRows[j], t.parsedRows[i]\n}","line":{"from":357,"to":360}} {"id":100031968,"name":"Less","signature":"func (t *TableSorter) Less(i, j int) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/sorter.go","code":"func (t *TableSorter) Less(i, j int) bool {\n\tiValues := t.parsedRows[i]\n\tjValues := t.parsedRows[j]\n\n\tif len(iValues) == 0 || len(iValues[0]) == 0 {\n\t\treturn true\n\t}\n\tif len(jValues) == 0 || len(jValues[0]) == 0 {\n\t\treturn false\n\t}\n\n\tiField := iValues[0][0]\n\tjField := jValues[0][0]\n\n\tless, err := isLess(iField, jField)\n\tif err != nil {\n\t\tklog.Exitf(\"Field %s in %T is an unsortable type: %s, err: %v\", t.field, t.parsedRows, iField.Kind().String(), err)\n\t}\n\treturn less\n}","line":{"from":362,"to":381}} {"id":100031969,"name":"Sort","signature":"func (t *TableSorter) Sort() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/sorter.go","code":"func (t *TableSorter) Sort() error {\n\tsort.Sort(t)\n\treturn nil\n}","line":{"from":383,"to":386}} {"id":100031970,"name":"NewTableSorter","signature":"func NewTableSorter(table *metav1.Table, field string) (*TableSorter, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/sorter.go","code":"func NewTableSorter(table *metav1.Table, field string) (*TableSorter, error) {\n\tvar parsedRows [][][]reflect.Value\n\n\tparser := jsonpath.New(\"sorting\").AllowMissingKeys(true)\n\terr := parser.Parse(field)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"sorting error: %v\", err)\n\t}\n\n\tfieldFoundOnce := false\n\tfor i := range table.Rows {\n\t\tparsedRow, err := findJSONPathResults(parser, table.Rows[i].Object.Object)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to get values for %#v using %s (%#v)\", parsedRow, field, err)\n\t\t}\n\t\tparsedRows = append(parsedRows, parsedRow)\n\t\tif len(parsedRow) \u003e 0 \u0026\u0026 len(parsedRow[0]) \u003e 0 {\n\t\t\tfieldFoundOnce = true\n\t\t}\n\t}\n\n\tif len(table.Rows) \u003e 0 \u0026\u0026 !fieldFoundOnce {\n\t\treturn nil, fmt.Errorf(\"couldn't find any field with path %q in the list of objects\", field)\n\t}\n\n\treturn \u0026TableSorter{\n\t\tobj: table,\n\t\tfield: field,\n\t\tparsedRows: parsedRows,\n\t}, nil\n}","line":{"from":388,"to":418}} {"id":100031971,"name":"findJSONPathResults","signature":"func findJSONPathResults(parser *jsonpath.JSONPath, from runtime.Object) ([][]reflect.Value, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/sorter.go","code":"func findJSONPathResults(parser *jsonpath.JSONPath, from runtime.Object) ([][]reflect.Value, error) {\n\tif unstructuredObj, ok := from.(*unstructured.Unstructured); ok {\n\t\treturn parser.FindResults(unstructuredObj.Object)\n\t}\n\treturn parser.FindResults(reflect.ValueOf(from).Elem().Interface())\n}","line":{"from":419,"to":424}} {"id":100031972,"name":"PrintObj","signature":"func (t *TablePrinter) PrintObj(obj runtime.Object, writer io.Writer) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/table_printer.go","code":"func (t *TablePrinter) PrintObj(obj runtime.Object, writer io.Writer) error {\n\ttable, err := decodeIntoTable(obj)\n\tif err == nil {\n\t\treturn t.Delegate.PrintObj(table, writer)\n\t}\n\t// if we are unable to decode server response into a v1beta1.Table,\n\t// fallback to client-side printing with whatever info the server returned.\n\tklog.V(2).Infof(\"Unable to decode server response into a Table. Falling back to hardcoded types: %v\", err)\n\treturn t.Delegate.PrintObj(obj, writer)\n}","line":{"from":38,"to":47}} {"id":100031973,"name":"decodeIntoTable","signature":"func decodeIntoTable(obj runtime.Object) (runtime.Object, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/get/table_printer.go","code":"func decodeIntoTable(obj runtime.Object) (runtime.Object, error) {\n\tevent, isEvent := obj.(*metav1.WatchEvent)\n\tif isEvent {\n\t\tobj = event.Object.Object\n\t}\n\n\tif !recognizedTableVersions[obj.GetObjectKind().GroupVersionKind()] {\n\t\treturn nil, fmt.Errorf(\"attempt to decode non-Table object\")\n\t}\n\n\tunstr, ok := obj.(*unstructured.Unstructured)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"attempt to decode non-Unstructured object\")\n\t}\n\ttable := \u0026metav1.Table{}\n\tif err := runtime.DefaultUnstructuredConverter.FromUnstructured(unstr.Object, table); err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor i := range table.Rows {\n\t\trow := \u0026table.Rows[i]\n\t\tif row.Object.Raw == nil || row.Object.Object != nil {\n\t\t\tcontinue\n\t\t}\n\t\tconverted, err := runtime.Decode(unstructured.UnstructuredJSONScheme, row.Object.Raw)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trow.Object.Object = converted\n\t}\n\n\tif isEvent {\n\t\tevent.Object.Object = table\n\t\treturn event, nil\n\t}\n\treturn table, nil\n}","line":{"from":58,"to":94}} {"id":100031974,"name":"NewCmdHelp","signature":"func NewCmdHelp() *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/help/help.go","code":"// NewCmdHelp returns the help Cobra command\nfunc NewCmdHelp() *cobra.Command {\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"help [command] | STRING_TO_SEARCH\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Help about any command\"),\n\t\tLong: helpLong,\n\n\t\tRun: RunHelp,\n\t}\n\n\treturn cmd\n}","line":{"from":32,"to":44}} {"id":100031975,"name":"RunHelp","signature":"func RunHelp(cmd *cobra.Command, args []string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/help/help.go","code":"// RunHelp checks given arguments and executes command\nfunc RunHelp(cmd *cobra.Command, args []string) {\n\tfoundCmd, _, err := cmd.Root().Find(args)\n\n\t// NOTE(andreykurilin): actually, I did not find any cases when foundCmd can be nil,\n\t// but let's make this check since it is included in original code of initHelpCmd\n\t// from github.com/spf13/cobra\n\tif foundCmd == nil {\n\t\tcmd.Printf(\"Unknown help topic %#q.\\n\", args)\n\t\tcmd.Root().Usage()\n\t} else if err != nil {\n\t\t// print error message at first, since it can contain suggestions\n\t\tcmd.Println(err)\n\n\t\targsString := strings.Join(args, \" \")\n\t\tvar matchedMsgIsPrinted = false\n\t\tfor _, foundCmd := range foundCmd.Commands() {\n\t\t\tif strings.Contains(foundCmd.Short, argsString) {\n\t\t\t\tif !matchedMsgIsPrinted {\n\t\t\t\t\tcmd.Printf(\"Matchers of string '%s' in short descriptions of commands: \\n\", argsString)\n\t\t\t\t\tmatchedMsgIsPrinted = true\n\t\t\t\t}\n\t\t\t\tcmd.Printf(\" %-14s %s\\n\", foundCmd.Name(), foundCmd.Short)\n\t\t\t}\n\t\t}\n\n\t\tif !matchedMsgIsPrinted {\n\t\t\t// if nothing is found, just print usage\n\t\t\tcmd.Root().Usage()\n\t\t}\n\t} else {\n\t\tif len(args) == 0 {\n\t\t\t// help message for help command :)\n\t\t\tfoundCmd = cmd\n\t\t}\n\t\thelpFunc := foundCmd.HelpFunc()\n\t\thelpFunc(foundCmd, args)\n\t}\n}","line":{"from":46,"to":84}} {"id":100031976,"name":"NewCmdKustomize","signature":"func NewCmdKustomize(streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/kustomize/kustomize.go","code":"// NewCmdKustomize returns an adapted kustomize build command.\nfunc NewCmdKustomize(streams genericclioptions.IOStreams) *cobra.Command {\n\th := build.MakeHelp(\"kubectl\", \"kustomize\")\n\treturn build.NewCmdBuild(\n\t\tfilesys.MakeFsOnDisk(),\n\t\t\u0026build.Help{\n\t\t\tUse: h.Use,\n\t\t\tShort: i18n.T(h.Short),\n\t\t\tLong: templates.LongDesc(i18n.T(h.Long)),\n\t\t\tExample: templates.Examples(i18n.T(h.Example)),\n\t\t},\n\t\tstreams.Out)\n}","line":{"from":28,"to":40}} {"id":100031977,"name":"NewLabelOptions","signature":"func NewLabelOptions(ioStreams genericclioptions.IOStreams) *LabelOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/label/label.go","code":"func NewLabelOptions(ioStreams genericclioptions.IOStreams) *LabelOptions {\n\treturn \u0026LabelOptions{\n\t\tRecordFlags: genericclioptions.NewRecordFlags(),\n\t\tRecorder: genericclioptions.NoopRecorder{},\n\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"labeled\").WithTypeSetter(scheme.Scheme),\n\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":121,"to":130}} {"id":100031978,"name":"NewCmdLabel","signature":"func NewCmdLabel(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/label/label.go","code":"func NewCmdLabel(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewLabelOptions(ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"label [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Update the labels on a resource\"),\n\t\tLong: fmt.Sprintf(labelLong, validation.LabelValueMaxLength),\n\t\tExample: labelExample,\n\t\tValidArgsFunction: completion.ResourceTypeAndNameCompletionFunc(f),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.RunLabel())\n\t\t},\n\t}\n\n\to.RecordFlags.AddFlags(cmd)\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmd.Flags().BoolVar(\u0026o.overwrite, \"overwrite\", o.overwrite, \"If true, allow labels to be overwritten, otherwise reject label updates that overwrite existing labels.\")\n\tcmd.Flags().BoolVar(\u0026o.list, \"list\", o.list, \"If true, display the labels for a given resource.\")\n\tcmd.Flags().BoolVar(\u0026o.local, \"local\", o.local, \"If true, label will NOT contact api-server but run locally.\")\n\tcmd.Flags().StringVar(\u0026o.fieldSelector, \"field-selector\", o.fieldSelector, \"Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector key1=value1,key2=value2). The server only supports a limited number of field queries per type.\")\n\tcmd.Flags().BoolVar(\u0026o.all, \"all\", o.all, \"Select all resources, in the namespace of the specified resource types\")\n\tcmd.Flags().BoolVarP(\u0026o.allNamespaces, \"all-namespaces\", \"A\", o.allNamespaces, \"If true, check the specified action in all namespaces.\")\n\tcmd.Flags().StringVar(\u0026o.resourceVersion, \"resource-version\", o.resourceVersion, i18n.T(\"If non-empty, the labels update will only succeed if this is the current resource-version for the object. Only valid when specifying a single resource.\"))\n\tusage := \"identifying the resource to update the labels\"\n\tcmdutil.AddFilenameOptionFlags(cmd, \u0026o.FilenameOptions, usage)\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.fieldManager, \"kubectl-label\")\n\tcmdutil.AddLabelSelectorFlagVar(cmd, \u0026o.selector)\n\n\treturn cmd\n}","line":{"from":132,"to":166}} {"id":100031979,"name":"Complete","signature":"func (o *LabelOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/label/label.go","code":"// Complete adapts from the command line args and factory to the data required.\nfunc (o *LabelOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\n\to.RecordFlags.Complete(cmd)\n\to.Recorder, err = o.RecordFlags.ToRecorder()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.outputFormat = cmdutil.GetFlagString(cmd, \"output\")\n\to.dryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.ToPrinter = func(operation string) (printers.ResourcePrinter, error) {\n\t\to.PrintFlags.NamePrintFlags.Operation = operation\n\t\t// PrintFlagsWithDryRunStrategy must be done after NamePrintFlags.Operation is set\n\t\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.dryRunStrategy)\n\t\treturn o.PrintFlags.ToPrinter()\n\t}\n\n\tresources, labelArgs, err := cmdutil.GetResourcesAndPairs(args, \"label\")\n\tif err != nil {\n\t\treturn err\n\t}\n\to.resources = resources\n\to.newLabels, o.removeLabels, err = parseLabels(labelArgs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif o.list \u0026\u0026 len(o.outputFormat) \u003e 0 {\n\t\treturn fmt.Errorf(\"--list and --output may not be specified together\")\n\t}\n\n\to.namespace, o.enforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.builder = f.NewBuilder()\n\to.unstructuredClientForMapping = f.UnstructuredClientForMapping\n\n\treturn nil\n}","line":{"from":168,"to":213}} {"id":100031980,"name":"Validate","signature":"func (o *LabelOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/label/label.go","code":"// Validate checks to the LabelOptions to see if there is sufficient information run the command.\nfunc (o *LabelOptions) Validate() error {\n\tif o.all \u0026\u0026 len(o.selector) \u003e 0 {\n\t\treturn fmt.Errorf(\"cannot set --all and --selector at the same time\")\n\t}\n\tif o.all \u0026\u0026 len(o.fieldSelector) \u003e 0 {\n\t\treturn fmt.Errorf(\"cannot set --all and --field-selector at the same time\")\n\t}\n\tif o.local {\n\t\tif o.dryRunStrategy == cmdutil.DryRunServer {\n\t\t\treturn fmt.Errorf(\"cannot specify --local and --dry-run=server - did you mean --dry-run=client?\")\n\t\t}\n\t\tif len(o.resources) \u003e 0 {\n\t\t\treturn fmt.Errorf(\"can only use local files by -f pod.yaml or --filename=pod.json when --local=true is set\")\n\t\t}\n\t\tif cmdutil.IsFilenameSliceEmpty(o.FilenameOptions.Filenames, o.FilenameOptions.Kustomize) {\n\t\t\treturn fmt.Errorf(\"one or more files must be specified as -f pod.yaml or --filename=pod.json\")\n\t\t}\n\t} else {\n\t\tif len(o.resources) \u003c 1 \u0026\u0026 cmdutil.IsFilenameSliceEmpty(o.FilenameOptions.Filenames, o.FilenameOptions.Kustomize) {\n\t\t\treturn fmt.Errorf(\"one or more resources must be specified as \u003cresource\u003e \u003cname\u003e or \u003cresource\u003e/\u003cname\u003e\")\n\t\t}\n\t}\n\tif len(o.newLabels) \u003c 1 \u0026\u0026 len(o.removeLabels) \u003c 1 \u0026\u0026 !o.list {\n\t\treturn fmt.Errorf(\"at least one label update is required\")\n\t}\n\treturn nil\n}","line":{"from":215,"to":242}} {"id":100031981,"name":"RunLabel","signature":"func (o *LabelOptions) RunLabel() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/label/label.go","code":"// RunLabel does the work\nfunc (o *LabelOptions) RunLabel() error {\n\tb := o.builder.\n\t\tUnstructured().\n\t\tLocalParam(o.local).\n\t\tContinueOnError().\n\t\tNamespaceParam(o.namespace).DefaultNamespace().\n\t\tFilenameParam(o.enforceNamespace, \u0026o.FilenameOptions).\n\t\tFlatten()\n\n\tif !o.local {\n\t\tb = b.LabelSelectorParam(o.selector).\n\t\t\tFieldSelectorParam(o.fieldSelector).\n\t\t\tAllNamespaces(o.allNamespaces).\n\t\t\tResourceTypeOrNameArgs(o.all, o.resources...).\n\t\t\tLatest()\n\t}\n\n\tone := false\n\tr := b.Do().IntoSingleItemImplied(\u0026one)\n\tif err := r.Err(); err != nil {\n\t\treturn err\n\t}\n\n\t// only apply resource version locking on a single resource\n\tif !one \u0026\u0026 len(o.resourceVersion) \u003e 0 {\n\t\treturn fmt.Errorf(\"--resource-version may only be used with a single resource\")\n\t}\n\n\t// TODO: support bulk generic output a la Get\n\treturn r.Visit(func(info *resource.Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar outputObj runtime.Object\n\t\tvar dataChangeMsg string\n\t\tobj := info.Object\n\n\t\tif len(o.resourceVersion) != 0 {\n\t\t\t// ensure resourceVersion is always sent in the patch by clearing it from the starting JSON\n\t\t\taccessor, err := meta.Accessor(obj)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\taccessor.SetResourceVersion(\"\")\n\t\t}\n\n\t\toldData, err := json.Marshal(obj)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif o.dryRunStrategy == cmdutil.DryRunClient || o.local || o.list {\n\t\t\terr = labelFunc(obj, o.overwrite, o.resourceVersion, o.newLabels, o.removeLabels)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tnewObj, err := json.Marshal(obj)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdataChangeMsg = updateDataChangeMsg(oldData, newObj, o.overwrite)\n\t\t\toutputObj = info.Object\n\t\t} else {\n\t\t\tname, namespace := info.Name, info.Namespace\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\taccessor, err := meta.Accessor(obj)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfor _, label := range o.removeLabels {\n\t\t\t\tif _, ok := accessor.GetLabels()[label]; !ok {\n\t\t\t\t\tfmt.Fprintf(o.Out, \"label %q not found.\\n\", label)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif err := labelFunc(obj, o.overwrite, o.resourceVersion, o.newLabels, o.removeLabels); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := o.Recorder.Record(obj); err != nil {\n\t\t\t\tklog.V(4).Infof(\"error recording current command: %v\", err)\n\t\t\t}\n\t\t\tnewObj, err := json.Marshal(obj)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdataChangeMsg = updateDataChangeMsg(oldData, newObj, o.overwrite)\n\t\t\tpatchBytes, err := jsonpatch.CreateMergePatch(oldData, newObj)\n\t\t\tcreatedPatch := err == nil\n\t\t\tif err != nil {\n\t\t\t\tklog.V(2).Infof(\"couldn't compute patch: %v\", err)\n\t\t\t}\n\n\t\t\tmapping := info.ResourceMapping()\n\t\t\tclient, err := o.unstructuredClientForMapping(mapping)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thelper := resource.NewHelper(client, mapping).\n\t\t\t\tDryRun(o.dryRunStrategy == cmdutil.DryRunServer).\n\t\t\t\tWithFieldManager(o.fieldManager)\n\n\t\t\tif createdPatch {\n\t\t\t\toutputObj, err = helper.Patch(namespace, name, types.MergePatchType, patchBytes, nil)\n\t\t\t} else {\n\t\t\t\toutputObj, err = helper.Replace(namespace, name, false, obj)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tif o.list {\n\t\t\taccessor, err := meta.Accessor(outputObj)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tindent := \"\"\n\t\t\tif !one {\n\t\t\t\tindent = \" \"\n\t\t\t\tgvks, _, err := unstructuredscheme.NewUnstructuredObjectTyper().ObjectKinds(info.Object)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfmt.Fprintf(o.Out, \"Listing labels for %s.%s/%s:\\n\", gvks[0].Kind, gvks[0].Group, info.Name)\n\t\t\t}\n\t\t\tfor k, v := range accessor.GetLabels() {\n\t\t\t\tfmt.Fprintf(o.Out, \"%s%s=%s\\n\", indent, k, v)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\n\t\tprinter, err := o.ToPrinter(dataChangeMsg)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn printer.PrintObj(info.Object, o.Out)\n\t})\n}","line":{"from":244,"to":386}} {"id":100031982,"name":"updateDataChangeMsg","signature":"func updateDataChangeMsg(oldObj []byte, newObj []byte, overwrite bool) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/label/label.go","code":"func updateDataChangeMsg(oldObj []byte, newObj []byte, overwrite bool) string {\n\tmsg := MsgNotLabeled\n\tif !reflect.DeepEqual(oldObj, newObj) {\n\t\tmsg = MsgLabeled\n\t\tif !overwrite \u0026\u0026 len(newObj) \u003c len(oldObj) {\n\t\t\tmsg = MsgUnLabeled\n\t\t}\n\t}\n\treturn msg\n}","line":{"from":388,"to":397}} {"id":100031983,"name":"validateNoOverwrites","signature":"func validateNoOverwrites(accessor metav1.Object, labels map[string]string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/label/label.go","code":"func validateNoOverwrites(accessor metav1.Object, labels map[string]string) error {\n\tallErrs := []error{}\n\tfor key, value := range labels {\n\t\tif currValue, found := accessor.GetLabels()[key]; found \u0026\u0026 currValue != value {\n\t\t\tallErrs = append(allErrs, fmt.Errorf(\"'%s' already has a value (%s), and --overwrite is false\", key, currValue))\n\t\t}\n\t}\n\treturn utilerrors.NewAggregate(allErrs)\n}","line":{"from":399,"to":407}} {"id":100031984,"name":"parseLabels","signature":"func parseLabels(spec []string) (map[string]string, []string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/label/label.go","code":"func parseLabels(spec []string) (map[string]string, []string, error) {\n\tlabels := map[string]string{}\n\tvar remove []string\n\tfor _, labelSpec := range spec {\n\t\tif strings.Contains(labelSpec, \"=\") {\n\t\t\tparts := strings.Split(labelSpec, \"=\")\n\t\t\tif len(parts) != 2 {\n\t\t\t\treturn nil, nil, fmt.Errorf(\"invalid label spec: %v\", labelSpec)\n\t\t\t}\n\t\t\tif errs := validation.IsValidLabelValue(parts[1]); len(errs) != 0 {\n\t\t\t\treturn nil, nil, fmt.Errorf(\"invalid label value: %q: %s\", labelSpec, strings.Join(errs, \";\"))\n\t\t\t}\n\t\t\tlabels[parts[0]] = parts[1]\n\t\t} else if strings.HasSuffix(labelSpec, \"-\") {\n\t\t\tremove = append(remove, labelSpec[:len(labelSpec)-1])\n\t\t} else {\n\t\t\treturn nil, nil, fmt.Errorf(\"unknown label spec: %v\", labelSpec)\n\t\t}\n\t}\n\tfor _, removeLabel := range remove {\n\t\tif _, found := labels[removeLabel]; found {\n\t\t\treturn nil, nil, fmt.Errorf(\"can not both modify and remove a label in the same command\")\n\t\t}\n\t}\n\treturn labels, remove, nil\n}","line":{"from":409,"to":434}} {"id":100031985,"name":"labelFunc","signature":"func labelFunc(obj runtime.Object, overwrite bool, resourceVersion string, labels map[string]string, remove []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/label/label.go","code":"func labelFunc(obj runtime.Object, overwrite bool, resourceVersion string, labels map[string]string, remove []string) error {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !overwrite {\n\t\tif err := validateNoOverwrites(accessor, labels); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tobjLabels := accessor.GetLabels()\n\tif objLabels == nil {\n\t\tobjLabels = make(map[string]string)\n\t}\n\n\tfor key, value := range labels {\n\t\tobjLabels[key] = value\n\t}\n\tfor _, label := range remove {\n\t\tdelete(objLabels, label)\n\t}\n\taccessor.SetLabels(objLabels)\n\n\tif len(resourceVersion) != 0 {\n\t\taccessor.SetResourceVersion(resourceVersion)\n\t}\n\treturn nil\n}","line":{"from":436,"to":464}} {"id":100031986,"name":"NewLogsOptions","signature":"func NewLogsOptions(streams genericclioptions.IOStreams, allContainers bool) *LogsOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/logs/logs.go","code":"func NewLogsOptions(streams genericclioptions.IOStreams, allContainers bool) *LogsOptions {\n\treturn \u0026LogsOptions{\n\t\tIOStreams: streams,\n\t\tAllContainers: allContainers,\n\t\tTail: -1,\n\t\tMaxFollowConcurrency: 5,\n\n\t\tcontainerNameFromRefSpecRegexp: regexp.MustCompile(`spec\\.(?:initContainers|containers|ephemeralContainers){(.+)}`),\n\t}\n}","line":{"from":135,"to":144}} {"id":100031987,"name":"NewCmdLogs","signature":"func NewCmdLogs(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/logs/logs.go","code":"// NewCmdLogs creates a new pod logs command\nfunc NewCmdLogs(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\to := NewLogsOptions(streams, false)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: logsUsageStr,\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Print the logs for a container in a pod\"),\n\t\tLong: logsLong,\n\t\tExample: logsExample,\n\t\tValidArgsFunction: completion.PodResourceNameAndContainerCompletionFunc(f),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.RunLogs())\n\t\t},\n\t}\n\to.AddFlags(cmd)\n\treturn cmd\n}","line":{"from":146,"to":165}} {"id":100031988,"name":"AddFlags","signature":"func (o *LogsOptions) AddFlags(cmd *cobra.Command)","file":"staging/src/k8s.io/kubectl/pkg/cmd/logs/logs.go","code":"func (o *LogsOptions) AddFlags(cmd *cobra.Command) {\n\tcmd.Flags().BoolVar(\u0026o.AllContainers, \"all-containers\", o.AllContainers, \"Get all containers' logs in the pod(s).\")\n\tcmd.Flags().BoolVarP(\u0026o.Follow, \"follow\", \"f\", o.Follow, \"Specify if the logs should be streamed.\")\n\tcmd.Flags().BoolVar(\u0026o.Timestamps, \"timestamps\", o.Timestamps, \"Include timestamps on each line in the log output\")\n\tcmd.Flags().Int64Var(\u0026o.LimitBytes, \"limit-bytes\", o.LimitBytes, \"Maximum bytes of logs to return. Defaults to no limit.\")\n\tcmd.Flags().BoolVarP(\u0026o.Previous, \"previous\", \"p\", o.Previous, \"If true, print the logs for the previous instance of the container in a pod if it exists.\")\n\tcmd.Flags().Int64Var(\u0026o.Tail, \"tail\", o.Tail, \"Lines of recent log file to display. Defaults to -1 with no selector, showing all log lines otherwise 10, if a selector is provided.\")\n\tcmd.Flags().BoolVar(\u0026o.IgnoreLogErrors, \"ignore-errors\", o.IgnoreLogErrors, \"If watching / following pod logs, allow for any errors that occur to be non-fatal\")\n\tcmd.Flags().StringVar(\u0026o.SinceTime, \"since-time\", o.SinceTime, i18n.T(\"Only return logs after a specific date (RFC3339). Defaults to all logs. Only one of since-time / since may be used.\"))\n\tcmd.Flags().DurationVar(\u0026o.SinceSeconds, \"since\", o.SinceSeconds, \"Only return logs newer than a relative duration like 5s, 2m, or 3h. Defaults to all logs. Only one of since-time / since may be used.\")\n\tcmd.Flags().StringVarP(\u0026o.Container, \"container\", \"c\", o.Container, \"Print the logs of this container\")\n\tcmd.Flags().BoolVar(\u0026o.InsecureSkipTLSVerifyBackend, \"insecure-skip-tls-verify-backend\", o.InsecureSkipTLSVerifyBackend,\n\t\t\"Skip verifying the identity of the kubelet that logs are requested from. In theory, an attacker could provide invalid log content back. You might want to use this if your kubelet serving certificates have expired.\")\n\tcmdutil.AddPodRunningTimeoutFlag(cmd, defaultPodLogsTimeout)\n\tcmdutil.AddLabelSelectorFlagVar(cmd, \u0026o.Selector)\n\tcmd.Flags().IntVar(\u0026o.MaxFollowConcurrency, \"max-log-requests\", o.MaxFollowConcurrency, \"Specify maximum number of concurrent logs to follow when using by a selector. Defaults to 5.\")\n\tcmd.Flags().BoolVar(\u0026o.Prefix, \"prefix\", o.Prefix, \"Prefix each log line with the log source (pod name and container name)\")\n}","line":{"from":167,"to":184}} {"id":100031989,"name":"ToLogOptions","signature":"func (o *LogsOptions) ToLogOptions() (*corev1.PodLogOptions, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/logs/logs.go","code":"func (o *LogsOptions) ToLogOptions() (*corev1.PodLogOptions, error) {\n\tlogOptions := \u0026corev1.PodLogOptions{\n\t\tContainer: o.Container,\n\t\tFollow: o.Follow,\n\t\tPrevious: o.Previous,\n\t\tTimestamps: o.Timestamps,\n\t\tInsecureSkipTLSVerifyBackend: o.InsecureSkipTLSVerifyBackend,\n\t}\n\n\tif len(o.SinceTime) \u003e 0 {\n\t\tt, err := util.ParseRFC3339(o.SinceTime, metav1.Now)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tlogOptions.SinceTime = \u0026t\n\t}\n\n\tif o.LimitBytes != 0 {\n\t\tlogOptions.LimitBytes = \u0026o.LimitBytes\n\t}\n\n\tif o.SinceSeconds != 0 {\n\t\t// round up to the nearest second\n\t\tsec := int64(o.SinceSeconds.Round(time.Second).Seconds())\n\t\tlogOptions.SinceSeconds = \u0026sec\n\t}\n\n\tif len(o.Selector) \u003e 0 \u0026\u0026 o.Tail == -1 \u0026\u0026 !o.TailSpecified {\n\t\tlogOptions.TailLines = \u0026selectorTail\n\t} else if o.Tail != -1 {\n\t\tlogOptions.TailLines = \u0026o.Tail\n\t}\n\n\treturn logOptions, nil\n}","line":{"from":186,"to":221}} {"id":100031990,"name":"Complete","signature":"func (o *LogsOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/logs/logs.go","code":"func (o *LogsOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\to.ContainerNameSpecified = cmd.Flag(\"container\").Changed\n\to.TailSpecified = cmd.Flag(\"tail\").Changed\n\to.Resources = args\n\n\tswitch len(args) {\n\tcase 0:\n\t\tif len(o.Selector) == 0 {\n\t\t\treturn cmdutil.UsageErrorf(cmd, \"%s\", logsUsageErrStr)\n\t\t}\n\tcase 1:\n\t\to.ResourceArg = args[0]\n\t\tif len(o.Selector) != 0 {\n\t\t\treturn cmdutil.UsageErrorf(cmd, \"only a selector (-l) or a POD name is allowed\")\n\t\t}\n\tcase 2:\n\t\to.ResourceArg = args[0]\n\t\to.Container = args[1]\n\tdefault:\n\t\treturn cmdutil.UsageErrorf(cmd, \"%s\", logsUsageErrStr)\n\t}\n\tvar err error\n\to.Namespace, _, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.ConsumeRequestFn = DefaultConsumeRequest\n\n\to.GetPodTimeout, err = cmdutil.GetPodRunningTimeoutFlag(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Options, err = o.ToLogOptions()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.RESTClientGetter = f\n\to.LogsForObject = polymorphichelpers.LogsForObjectFn\n\n\tif o.Object == nil {\n\t\tbuilder := f.NewBuilder().\n\t\t\tWithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).\n\t\t\tNamespaceParam(o.Namespace).DefaultNamespace().\n\t\t\tSingleResourceType()\n\t\tif o.ResourceArg != \"\" {\n\t\t\tbuilder.ResourceNames(\"pods\", o.ResourceArg)\n\t\t}\n\t\tif o.Selector != \"\" {\n\t\t\tbuilder.ResourceTypes(\"pods\").LabelSelectorParam(o.Selector)\n\t\t}\n\t\tinfos, err := builder.Do().Infos()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif o.Selector == \"\" \u0026\u0026 len(infos) != 1 {\n\t\t\treturn errors.New(\"expected a resource\")\n\t\t}\n\t\to.Object = infos[0].Object\n\t\tif o.Selector != \"\" \u0026\u0026 len(o.Object.(*corev1.PodList).Items) == 0 {\n\t\t\tfmt.Fprintf(o.ErrOut, \"No resources found in %s namespace.\\n\", o.Namespace)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":223,"to":290}} {"id":100031991,"name":"Validate","signature":"func (o LogsOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/logs/logs.go","code":"func (o LogsOptions) Validate() error {\n\tif len(o.SinceTime) \u003e 0 \u0026\u0026 o.SinceSeconds != 0 {\n\t\treturn fmt.Errorf(\"at most one of `sinceTime` or `sinceSeconds` may be specified\")\n\t}\n\n\tlogsOptions, ok := o.Options.(*corev1.PodLogOptions)\n\tif !ok {\n\t\treturn errors.New(\"unexpected logs options object\")\n\t}\n\tif o.AllContainers \u0026\u0026 len(logsOptions.Container) \u003e 0 {\n\t\treturn fmt.Errorf(\"--all-containers=true should not be specified with container name %s\", logsOptions.Container)\n\t}\n\n\tif o.ContainerNameSpecified \u0026\u0026 len(o.Resources) == 2 {\n\t\treturn fmt.Errorf(\"only one of -c or an inline [CONTAINER] arg is allowed\")\n\t}\n\n\tif o.LimitBytes \u003c 0 {\n\t\treturn fmt.Errorf(\"--limit-bytes must be greater than 0\")\n\t}\n\n\tif logsOptions.SinceSeconds != nil \u0026\u0026 *logsOptions.SinceSeconds \u003c int64(0) {\n\t\treturn fmt.Errorf(\"--since must be greater than 0\")\n\t}\n\n\tif logsOptions.TailLines != nil \u0026\u0026 *logsOptions.TailLines \u003c -1 {\n\t\treturn fmt.Errorf(\"--tail must be greater than or equal to -1\")\n\t}\n\n\treturn nil\n}","line":{"from":292,"to":322}} {"id":100031992,"name":"RunLogs","signature":"func (o LogsOptions) RunLogs() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/logs/logs.go","code":"// RunLogs retrieves a pod log\nfunc (o LogsOptions) RunLogs() error {\n\trequests, err := o.LogsForObject(o.RESTClientGetter, o.Object, o.Options, o.GetPodTimeout, o.AllContainers)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif o.Follow \u0026\u0026 len(requests) \u003e 1 {\n\t\tif len(requests) \u003e o.MaxFollowConcurrency {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"you are attempting to follow %d log streams, but maximum allowed concurrency is %d, use --max-log-requests to increase the limit\",\n\t\t\t\tlen(requests), o.MaxFollowConcurrency,\n\t\t\t)\n\t\t}\n\n\t\treturn o.parallelConsumeRequest(requests)\n\t}\n\n\treturn o.sequentialConsumeRequest(requests)\n}","line":{"from":324,"to":343}} {"id":100031993,"name":"parallelConsumeRequest","signature":"func (o LogsOptions) parallelConsumeRequest(requests map[corev1.ObjectReference]rest.ResponseWrapper) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/logs/logs.go","code":"func (o LogsOptions) parallelConsumeRequest(requests map[corev1.ObjectReference]rest.ResponseWrapper) error {\n\treader, writer := io.Pipe()\n\twg := \u0026sync.WaitGroup{}\n\twg.Add(len(requests))\n\tfor objRef, request := range requests {\n\t\tgo func(objRef corev1.ObjectReference, request rest.ResponseWrapper) {\n\t\t\tdefer wg.Done()\n\t\t\tout := o.addPrefixIfNeeded(objRef, writer)\n\t\t\tif err := o.ConsumeRequestFn(request, out); err != nil {\n\t\t\t\tif !o.IgnoreLogErrors {\n\t\t\t\t\twriter.CloseWithError(err)\n\n\t\t\t\t\t// It's important to return here to propagate the error via the pipe\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tfmt.Fprintf(writer, \"error: %v\\n\", err)\n\t\t\t}\n\n\t\t}(objRef, request)\n\t}\n\n\tgo func() {\n\t\twg.Wait()\n\t\twriter.Close()\n\t}()\n\n\t_, err := io.Copy(o.Out, reader)\n\treturn err\n}","line":{"from":345,"to":374}} {"id":100031994,"name":"sequentialConsumeRequest","signature":"func (o LogsOptions) sequentialConsumeRequest(requests map[corev1.ObjectReference]rest.ResponseWrapper) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/logs/logs.go","code":"func (o LogsOptions) sequentialConsumeRequest(requests map[corev1.ObjectReference]rest.ResponseWrapper) error {\n\tfor objRef, request := range requests {\n\t\tout := o.addPrefixIfNeeded(objRef, o.Out)\n\t\tif err := o.ConsumeRequestFn(request, out); err != nil {\n\t\t\tif !o.IgnoreLogErrors {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tfmt.Fprintf(o.Out, \"error: %v\\n\", err)\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":376,"to":389}} {"id":100031995,"name":"addPrefixIfNeeded","signature":"func (o LogsOptions) addPrefixIfNeeded(ref corev1.ObjectReference, writer io.Writer) io.Writer","file":"staging/src/k8s.io/kubectl/pkg/cmd/logs/logs.go","code":"func (o LogsOptions) addPrefixIfNeeded(ref corev1.ObjectReference, writer io.Writer) io.Writer {\n\tif !o.Prefix || ref.FieldPath == \"\" || ref.Name == \"\" {\n\t\treturn writer\n\t}\n\n\t// We rely on ref.FieldPath to contain a reference to a container\n\t// including a container name (not an index) so we can get a container name\n\t// without making an extra API request.\n\tvar containerName string\n\tcontainerNameMatches := o.containerNameFromRefSpecRegexp.FindStringSubmatch(ref.FieldPath)\n\tif len(containerNameMatches) == 2 {\n\t\tcontainerName = containerNameMatches[1]\n\t}\n\n\tprefix := fmt.Sprintf(\"[pod/%s/%s] \", ref.Name, containerName)\n\treturn \u0026prefixingWriter{\n\t\tprefix: []byte(prefix),\n\t\twriter: writer,\n\t}\n}","line":{"from":391,"to":410}} {"id":100031996,"name":"DefaultConsumeRequest","signature":"func DefaultConsumeRequest(request rest.ResponseWrapper, out io.Writer) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/logs/logs.go","code":"// DefaultConsumeRequest reads the data from request and writes into\n// the out writer. It buffers data from requests until the newline or io.EOF\n// occurs in the data, so it doesn't interleave logs sub-line\n// when running concurrently.\n//\n// A successful read returns err == nil, not err == io.EOF.\n// Because the function is defined to read from request until io.EOF, it does\n// not treat an io.EOF as an error to be reported.\nfunc DefaultConsumeRequest(request rest.ResponseWrapper, out io.Writer) error {\n\treadCloser, err := request.Stream(context.TODO())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer readCloser.Close()\n\n\tr := bufio.NewReader(readCloser)\n\tfor {\n\t\tbytes, err := r.ReadBytes('\\n')\n\t\tif _, err := out.Write(bytes); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err != nil {\n\t\t\tif err != io.EOF {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n}","line":{"from":412,"to":441}} {"id":100031997,"name":"Write","signature":"func (pw *prefixingWriter) Write(p []byte) (int, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/logs/logs.go","code":"func (pw *prefixingWriter) Write(p []byte) (int, error) {\n\tif len(p) == 0 {\n\t\treturn 0, nil\n\t}\n\n\t// Perform an \"atomic\" write of a prefix and p to make sure that it doesn't interleave\n\t// sub-line when used concurrently with io.PipeWrite.\n\tn, err := pw.writer.Write(append(pw.prefix, p...))\n\tif n \u003e len(p) {\n\t\t// To comply with the io.Writer interface requirements we must\n\t\t// return a number of bytes written from p (0 \u003c= n \u003c= len(p)),\n\t\t// so we are ignoring the length of the prefix here.\n\t\treturn len(p), err\n\t}\n\treturn n, err\n}","line":{"from":448,"to":463}} {"id":100031998,"name":"NewCmdOptions","signature":"func NewCmdOptions(out io.Writer) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/options/options.go","code":"// NewCmdOptions implements the options command\nfunc NewCmdOptions(out io.Writer) *cobra.Command {\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"options\",\n\t\tShort: i18n.T(\"Print the list of flags inherited by all commands\"),\n\t\tLong: i18n.T(\"Print the list of flags inherited by all commands\"),\n\t\tExample: optionsExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmd.Usage()\n\t\t},\n\t}\n\n\t// The `options` command needs write its output to the `out` stream\n\t// (typically stdout). Without calling SetOutput here, the Usage()\n\t// function call will fall back to stderr.\n\t//\n\t// See https://github.com/kubernetes/kubernetes/pull/46394 for details.\n\tcmd.SetOut(out)\n\tcmd.SetErr(out)\n\n\ttemplates.UseOptionsTemplates(cmd)\n\treturn cmd\n}","line":{"from":34,"to":56}} {"id":100031999,"name":"NewPatchOptions","signature":"func NewPatchOptions(ioStreams genericclioptions.IOStreams) *PatchOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/patch/patch.go","code":"func NewPatchOptions(ioStreams genericclioptions.IOStreams) *PatchOptions {\n\treturn \u0026PatchOptions{\n\t\tRecordFlags: genericclioptions.NewRecordFlags(),\n\t\tRecorder: genericclioptions.NoopRecorder{},\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"patched\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":110,"to":117}} {"id":100032000,"name":"NewCmdPatch","signature":"func NewCmdPatch(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/patch/patch.go","code":"func NewCmdPatch(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewPatchOptions(ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"patch (-f FILENAME | TYPE NAME) [-p PATCH|--patch-file FILE]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Update fields of a resource\"),\n\t\tLong: patchLong,\n\t\tExample: patchExample,\n\t\tValidArgsFunction: completion.ResourceTypeAndNameCompletionFunc(f),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.RunPatch())\n\t\t},\n\t}\n\n\to.RecordFlags.AddFlags(cmd)\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmd.Flags().StringVarP(\u0026o.Patch, \"patch\", \"p\", \"\", \"The patch to be applied to the resource JSON file.\")\n\tcmd.Flags().StringVar(\u0026o.PatchFile, \"patch-file\", \"\", \"A file containing a patch to be applied to the resource.\")\n\tcmd.Flags().StringVar(\u0026o.PatchType, \"type\", \"strategic\", fmt.Sprintf(\"The type of patch being provided; one of %v\", sets.StringKeySet(patchTypes).List()))\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmdutil.AddFilenameOptionFlags(cmd, \u0026o.FilenameOptions, \"identifying the resource to update\")\n\tcmd.Flags().BoolVar(\u0026o.Local, \"local\", o.Local, \"If true, patch will operate on the content of the file, not the server-side resource.\")\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.fieldManager, \"kubectl-patch\")\n\tcmdutil.AddSubresourceFlags(cmd, \u0026o.Subresource, \"If specified, patch will operate on the subresource of the requested object.\", supportedSubresources...)\n\n\treturn cmd\n}","line":{"from":119,"to":149}} {"id":100032001,"name":"Complete","signature":"func (o *PatchOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/patch/patch.go","code":"func (o *PatchOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\to.RecordFlags.Complete(cmd)\n\to.Recorder, err = o.RecordFlags.ToRecorder()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.outputFormat = cmdutil.GetFlagString(cmd, \"output\")\n\to.dryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.dryRunStrategy)\n\to.ToPrinter = func(operation string) (printers.ResourcePrinter, error) {\n\t\to.PrintFlags.NamePrintFlags.Operation = operation\n\n\t\treturn o.PrintFlags.ToPrinter()\n\t}\n\n\to.namespace, o.enforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.args = args\n\to.builder = f.NewBuilder()\n\to.unstructuredClientForMapping = f.UnstructuredClientForMapping\n\n\treturn nil\n}","line":{"from":151,"to":181}} {"id":100032002,"name":"Validate","signature":"func (o *PatchOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/patch/patch.go","code":"func (o *PatchOptions) Validate() error {\n\tif len(o.Patch) \u003e 0 \u0026\u0026 len(o.PatchFile) \u003e 0 {\n\t\treturn fmt.Errorf(\"cannot specify --patch and --patch-file together\")\n\t}\n\tif len(o.Patch) == 0 \u0026\u0026 len(o.PatchFile) == 0 {\n\t\treturn fmt.Errorf(\"must specify --patch or --patch-file containing the contents of the patch\")\n\t}\n\tif o.Local \u0026\u0026 len(o.args) != 0 {\n\t\treturn fmt.Errorf(\"cannot specify --local and server resources\")\n\t}\n\tif o.Local \u0026\u0026 o.dryRunStrategy == cmdutil.DryRunServer {\n\t\treturn fmt.Errorf(\"cannot specify --local and --dry-run=server - did you mean --dry-run=client?\")\n\t}\n\tif len(o.PatchType) != 0 {\n\t\tif _, ok := patchTypes[strings.ToLower(o.PatchType)]; !ok {\n\t\t\treturn fmt.Errorf(\"--type must be one of %v, not %q\", sets.StringKeySet(patchTypes).List(), o.PatchType)\n\t\t}\n\t}\n\tif len(o.Subresource) \u003e 0 \u0026\u0026 !slice.ContainsString(supportedSubresources, o.Subresource, nil) {\n\t\treturn fmt.Errorf(\"invalid subresource value: %q. Must be one of %v\", o.Subresource, supportedSubresources)\n\t}\n\treturn nil\n}","line":{"from":183,"to":205}} {"id":100032003,"name":"RunPatch","signature":"func (o *PatchOptions) RunPatch() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/patch/patch.go","code":"func (o *PatchOptions) RunPatch() error {\n\tpatchType := types.StrategicMergePatchType\n\tif len(o.PatchType) != 0 {\n\t\tpatchType = patchTypes[strings.ToLower(o.PatchType)]\n\t}\n\n\tvar patchBytes []byte\n\tif len(o.PatchFile) \u003e 0 {\n\t\tvar err error\n\t\tpatchBytes, err = os.ReadFile(o.PatchFile)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to read patch file: %v\", err)\n\t\t}\n\t} else {\n\t\tpatchBytes = []byte(o.Patch)\n\t}\n\n\tpatchBytes, err := yaml.ToJSON(patchBytes)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to parse %q: %v\", o.Patch, err)\n\t}\n\n\tr := o.builder.\n\t\tUnstructured().\n\t\tContinueOnError().\n\t\tLocalParam(o.Local).\n\t\tNamespaceParam(o.namespace).DefaultNamespace().\n\t\tFilenameParam(o.enforceNamespace, \u0026o.FilenameOptions).\n\t\tSubresource(o.Subresource).\n\t\tResourceTypeOrNameArgs(false, o.args...).\n\t\tFlatten().\n\t\tDo()\n\terr = r.Err()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcount := 0\n\terr = r.Visit(func(info *resource.Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcount++\n\t\tname, namespace := info.Name, info.Namespace\n\n\t\tif !o.Local \u0026\u0026 o.dryRunStrategy != cmdutil.DryRunClient {\n\t\t\tmapping := info.ResourceMapping()\n\t\t\tclient, err := o.unstructuredClientForMapping(mapping)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\thelper := resource.\n\t\t\t\tNewHelper(client, mapping).\n\t\t\t\tDryRun(o.dryRunStrategy == cmdutil.DryRunServer).\n\t\t\t\tWithFieldManager(o.fieldManager).\n\t\t\t\tWithSubresource(o.Subresource)\n\t\t\tpatchedObj, err := helper.Patch(namespace, name, patchType, patchBytes, nil)\n\t\t\tif err != nil {\n\t\t\t\tif apierrors.IsUnsupportedMediaType(err) {\n\t\t\t\t\treturn errors.Wrap(err, fmt.Sprintf(\"%s is not supported by %s\", patchType, mapping.GroupVersionKind))\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tdidPatch := !reflect.DeepEqual(info.Object, patchedObj)\n\n\t\t\t// if the recorder makes a change, compute and create another patch\n\t\t\tif mergePatch, err := o.Recorder.MakeRecordMergePatch(patchedObj); err != nil {\n\t\t\t\tklog.V(4).Infof(\"error recording current command: %v\", err)\n\t\t\t} else if len(mergePatch) \u003e 0 {\n\t\t\t\tif recordedObj, err := helper.Patch(namespace, name, types.MergePatchType, mergePatch, nil); err != nil {\n\t\t\t\t\tklog.V(4).Infof(\"error recording reason: %v\", err)\n\t\t\t\t} else {\n\t\t\t\t\tpatchedObj = recordedObj\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprinter, err := o.ToPrinter(patchOperation(didPatch))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn printer.PrintObj(patchedObj, o.Out)\n\t\t}\n\n\t\toriginalObjJS, err := runtime.Encode(unstructured.UnstructuredJSONScheme, info.Object)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\toriginalPatchedObjJS, err := getPatchedJSON(patchType, originalObjJS, patchBytes, info.Object.GetObjectKind().GroupVersionKind(), scheme.Scheme)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttargetObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, originalPatchedObjJS)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdidPatch := !reflect.DeepEqual(info.Object, targetObj)\n\t\tprinter, err := o.ToPrinter(patchOperation(didPatch))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn printer.PrintObj(targetObj, o.Out)\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tif count == 0 {\n\t\treturn fmt.Errorf(\"no objects passed to patch\")\n\t}\n\treturn nil\n}","line":{"from":207,"to":321}} {"id":100032004,"name":"getPatchedJSON","signature":"func getPatchedJSON(patchType types.PatchType, originalJS, patchJS []byte, gvk schema.GroupVersionKind, creater runtime.ObjectCreater) ([]byte, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/patch/patch.go","code":"func getPatchedJSON(patchType types.PatchType, originalJS, patchJS []byte, gvk schema.GroupVersionKind, creater runtime.ObjectCreater) ([]byte, error) {\n\tswitch patchType {\n\tcase types.JSONPatchType:\n\t\tpatchObj, err := jsonpatch.DecodePatch(patchJS)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbytes, err := patchObj.Apply(originalJS)\n\t\t// TODO: This is pretty hacky, we need a better structured error from the json-patch\n\t\tif err != nil \u0026\u0026 strings.Contains(err.Error(), \"doc is missing key\") {\n\t\t\tmsg := err.Error()\n\t\t\tix := strings.Index(msg, \"key:\")\n\t\t\tkey := msg[ix+5:]\n\t\t\treturn bytes, fmt.Errorf(\"Object to be patched is missing field (%s)\", key)\n\t\t}\n\t\treturn bytes, err\n\n\tcase types.MergePatchType:\n\t\treturn jsonpatch.MergePatch(originalJS, patchJS)\n\n\tcase types.StrategicMergePatchType:\n\t\t// get a typed object for this GVK if we need to apply a strategic merge patch\n\t\tobj, err := creater.New(gvk)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"strategic merge patch is not supported for %s locally, try --type merge\", gvk.String())\n\t\t}\n\t\treturn strategicpatch.StrategicMergePatch(originalJS, patchJS, obj)\n\n\tdefault:\n\t\t// only here as a safety net - go-restful filters content-type\n\t\treturn nil, fmt.Errorf(\"unknown Content-Type header for patch: %v\", patchType)\n\t}\n}","line":{"from":323,"to":355}} {"id":100032005,"name":"patchOperation","signature":"func patchOperation(didPatch bool) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/patch/patch.go","code":"func patchOperation(didPatch bool) string {\n\tif didPatch {\n\t\treturn \"patched\"\n\t}\n\treturn \"patched (no change)\"\n}","line":{"from":357,"to":362}} {"id":100032006,"name":"NewCmdPlugin","signature":"func NewCmdPlugin(streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/plugin/plugin.go","code":"func NewCmdPlugin(streams genericclioptions.IOStreams) *cobra.Command {\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"plugin [flags]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Provides utilities for interacting with plugins\"),\n\t\tLong: pluginLong,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.DefaultSubCommandRun(streams.ErrOut)(cmd, args)\n\t\t},\n\t}\n\n\tcmd.AddCommand(NewCmdPluginList(streams))\n\treturn cmd\n}","line":{"from":61,"to":74}} {"id":100032007,"name":"NewCmdPluginList","signature":"func NewCmdPluginList(streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/plugin/plugin.go","code":"// NewCmdPluginList provides a way to list all plugin executables visible to kubectl\nfunc NewCmdPluginList(streams genericclioptions.IOStreams) *cobra.Command {\n\to := \u0026PluginListOptions{\n\t\tIOStreams: streams,\n\t}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: i18n.T(\"List all visible plugin executables on a user's PATH\"),\n\t\tExample: pluginExample,\n\t\tLong: pluginListLong,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(cmd))\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\tcmd.Flags().BoolVar(\u0026o.NameOnly, \"name-only\", o.NameOnly, \"If true, display only the binary name of each plugin, rather than its full path\")\n\treturn cmd\n}","line":{"from":85,"to":104}} {"id":100032008,"name":"Complete","signature":"func (o *PluginListOptions) Complete(cmd *cobra.Command) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/plugin/plugin.go","code":"func (o *PluginListOptions) Complete(cmd *cobra.Command) error {\n\to.Verifier = \u0026CommandOverrideVerifier{\n\t\troot: cmd.Root(),\n\t\tseenPlugins: make(map[string]string),\n\t}\n\n\to.PluginPaths = filepath.SplitList(os.Getenv(\"PATH\"))\n\treturn nil\n}","line":{"from":106,"to":114}} {"id":100032009,"name":"Run","signature":"func (o *PluginListOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/plugin/plugin.go","code":"func (o *PluginListOptions) Run() error {\n\tplugins, pluginErrors := o.ListPlugins()\n\n\tif len(plugins) \u003e 0 {\n\t\tfmt.Fprintf(o.Out, \"The following compatible plugins are available:\\n\\n\")\n\t} else {\n\t\tpluginErrors = append(pluginErrors, fmt.Errorf(\"error: unable to find any kubectl plugins in your PATH\"))\n\t}\n\n\tpluginWarnings := 0\n\tfor _, pluginPath := range plugins {\n\t\tif o.NameOnly {\n\t\t\tfmt.Fprintf(o.Out, \"%s\\n\", filepath.Base(pluginPath))\n\t\t} else {\n\t\t\tfmt.Fprintf(o.Out, \"%s\\n\", pluginPath)\n\t\t}\n\t\tif errs := o.Verifier.Verify(pluginPath); len(errs) != 0 {\n\t\t\tfor _, err := range errs {\n\t\t\t\tfmt.Fprintf(o.ErrOut, \" - %s\\n\", err)\n\t\t\t\tpluginWarnings++\n\t\t\t}\n\t\t}\n\t}\n\n\tif pluginWarnings \u003e 0 {\n\t\tif pluginWarnings == 1 {\n\t\t\tpluginErrors = append(pluginErrors, fmt.Errorf(\"error: one plugin warning was found\"))\n\t\t} else {\n\t\t\tpluginErrors = append(pluginErrors, fmt.Errorf(\"error: %v plugin warnings were found\", pluginWarnings))\n\t\t}\n\t}\n\tif len(pluginErrors) \u003e 0 {\n\t\terrs := bytes.NewBuffer(nil)\n\t\tfor _, e := range pluginErrors {\n\t\t\tfmt.Fprintln(errs, e)\n\t\t}\n\t\treturn fmt.Errorf(\"%s\", errs.String())\n\t}\n\n\treturn nil\n}","line":{"from":116,"to":156}} {"id":100032010,"name":"ListPlugins","signature":"func (o *PluginListOptions) ListPlugins() ([]string, []error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/plugin/plugin.go","code":"// ListPlugins returns list of plugin paths.\nfunc (o *PluginListOptions) ListPlugins() ([]string, []error) {\n\tplugins := []string{}\n\terrors := []error{}\n\n\tfor _, dir := range uniquePathsList(o.PluginPaths) {\n\t\tif len(strings.TrimSpace(dir)) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tfiles, err := os.ReadDir(dir)\n\t\tif err != nil {\n\t\t\tif _, ok := err.(*os.PathError); ok {\n\t\t\t\tfmt.Fprintf(o.ErrOut, \"Unable to read directory %q from your PATH: %v. Skipping...\\n\", dir, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\terrors = append(errors, fmt.Errorf(\"error: unable to read directory %q in your PATH: %v\", dir, err))\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, f := range files {\n\t\t\tif f.IsDir() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !hasValidPrefix(f.Name(), ValidPluginFilenamePrefixes) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tplugins = append(plugins, filepath.Join(dir, f.Name()))\n\t\t}\n\t}\n\n\treturn plugins, errors\n}","line":{"from":158,"to":192}} {"id":100032011,"name":"Verify","signature":"func (v *CommandOverrideVerifier) Verify(path string) []error","file":"staging/src/k8s.io/kubectl/pkg/cmd/plugin/plugin.go","code":"// Verify implements PathVerifier and determines if a given path\n// is valid depending on whether or not it overwrites an existing\n// kubectl command path, or a previously seen plugin.\nfunc (v *CommandOverrideVerifier) Verify(path string) []error {\n\tif v.root == nil {\n\t\treturn []error{fmt.Errorf(\"unable to verify path with nil root\")}\n\t}\n\n\t// extract the plugin binary name\n\tsegs := strings.Split(path, \"/\")\n\tbinName := segs[len(segs)-1]\n\n\tcmdPath := strings.Split(binName, \"-\")\n\tif len(cmdPath) \u003e 1 {\n\t\t// the first argument is always \"kubectl\" for a plugin binary\n\t\tcmdPath = cmdPath[1:]\n\t}\n\n\terrors := []error{}\n\n\tif isExec, err := isExecutable(path); err == nil \u0026\u0026 !isExec {\n\t\terrors = append(errors, fmt.Errorf(\"warning: %s identified as a kubectl plugin, but it is not executable\", path))\n\t} else if err != nil {\n\t\terrors = append(errors, fmt.Errorf(\"error: unable to identify %s as an executable file: %v\", path, err))\n\t}\n\n\tif existingPath, ok := v.seenPlugins[binName]; ok {\n\t\terrors = append(errors, fmt.Errorf(\"warning: %s is overshadowed by a similarly named plugin: %s\", path, existingPath))\n\t} else {\n\t\tv.seenPlugins[binName] = path\n\t}\n\n\tif cmd, _, err := v.root.Find(cmdPath); err == nil {\n\t\terrors = append(errors, fmt.Errorf(\"warning: %s overwrites existing command: %q\", binName, cmd.CommandPath()))\n\t}\n\n\treturn errors\n}","line":{"from":205,"to":242}} {"id":100032012,"name":"isExecutable","signature":"func isExecutable(fullPath string) (bool, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/plugin/plugin.go","code":"func isExecutable(fullPath string) (bool, error) {\n\tinfo, err := os.Stat(fullPath)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif runtime.GOOS == \"windows\" {\n\t\tfileExt := strings.ToLower(filepath.Ext(fullPath))\n\n\t\tswitch fileExt {\n\t\tcase \".bat\", \".cmd\", \".com\", \".exe\", \".ps1\":\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t}\n\n\tif m := info.Mode(); !m.IsDir() \u0026\u0026 m\u00260111 != 0 {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}","line":{"from":244,"to":265}} {"id":100032013,"name":"uniquePathsList","signature":"func uniquePathsList(paths []string) []string","file":"staging/src/k8s.io/kubectl/pkg/cmd/plugin/plugin.go","code":"// uniquePathsList deduplicates a given slice of strings without\n// sorting or otherwise altering its order in any way.\nfunc uniquePathsList(paths []string) []string {\n\tseen := map[string]bool{}\n\tnewPaths := []string{}\n\tfor _, p := range paths {\n\t\tif seen[p] {\n\t\t\tcontinue\n\t\t}\n\t\tseen[p] = true\n\t\tnewPaths = append(newPaths, p)\n\t}\n\treturn newPaths\n}","line":{"from":267,"to":280}} {"id":100032014,"name":"hasValidPrefix","signature":"func hasValidPrefix(filepath string, validPrefixes []string) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/plugin/plugin.go","code":"func hasValidPrefix(filepath string, validPrefixes []string) bool {\n\tfor _, prefix := range validPrefixes {\n\t\tif !strings.HasPrefix(filepath, prefix+\"-\") {\n\t\t\tcontinue\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":282,"to":290}} {"id":100032015,"name":"SetupPluginCompletion","signature":"func SetupPluginCompletion(cmd *cobra.Command, args []string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/plugin/plugin_completion.go","code":"// SetupPluginCompletion adds a Cobra command to the command tree for each\n// plugin. This is only done when performing shell completion that relate\n// to plugins.\nfunc SetupPluginCompletion(cmd *cobra.Command, args []string) {\n\tif len(args) \u003e 0 {\n\t\tif strings.HasPrefix(args[0], \"-\") {\n\t\t\t// Plugins are not supported if the first argument is a flag,\n\t\t\t// so no need to add them in that case.\n\t\t\treturn\n\t\t}\n\n\t\tif len(args) == 1 {\n\t\t\t// We are completing a subcommand at the first level so\n\t\t\t// we should include all plugins names.\n\t\t\taddPluginCommands(cmd)\n\t\t\treturn\n\t\t}\n\n\t\t// We have more than one argument.\n\t\t// Check if we know the first level subcommand.\n\t\t// If we don't it could be a plugin and we'll need to add\n\t\t// the plugin commands for completion to work.\n\t\tfound := false\n\t\tfor _, subCmd := range cmd.Root().Commands() {\n\t\t\tif args[0] == subCmd.Name() {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\t// We don't know the subcommand for which completion\n\t\t\t// is being called: it could be a plugin.\n\t\t\t//\n\t\t\t// When using a plugin, the kubectl global flags are not supported.\n\t\t\t// Therefore, when doing completion, we need to remove these flags\n\t\t\t// to avoid them being included in the completion choices.\n\t\t\t// This must be done *before* adding the plugin commands so that\n\t\t\t// when creating those plugin commands, the flags don't exist.\n\t\t\tcmd.Root().ResetFlags()\n\t\t\tcobra.CompDebugln(\"Cleared global flags for plugin completion\", true)\n\n\t\t\taddPluginCommands(cmd)\n\t\t}\n\t}\n}","line":{"from":33,"to":78}} {"id":100032016,"name":"addPluginCommands","signature":"func addPluginCommands(cmd *cobra.Command)","file":"staging/src/k8s.io/kubectl/pkg/cmd/plugin/plugin_completion.go","code":"// addPluginCommand adds a Cobra command to the command tree\n// for each plugin so that the completion logic knows about the plugins\nfunc addPluginCommands(cmd *cobra.Command) {\n\tkubectl := cmd.Root()\n\tstreams := genericclioptions.IOStreams{\n\t\tIn: \u0026bytes.Buffer{},\n\t\tOut: io.Discard,\n\t\tErrOut: io.Discard,\n\t}\n\n\to := \u0026PluginListOptions{IOStreams: streams}\n\to.Complete(kubectl)\n\tplugins, _ := o.ListPlugins()\n\n\tfor _, plugin := range plugins {\n\t\tplugin = filepath.Base(plugin)\n\t\targs := []string{}\n\n\t\t// Plugins are named \"kubectl-\u003cname\u003e\" or with more - such as\n\t\t// \"kubectl-\u003cname\u003e-\u003csubcmd1\u003e...\"\n\t\tfor _, arg := range strings.Split(plugin, \"-\")[1:] {\n\t\t\t// Underscores (_) in plugin's filename are replaced with dashes(-)\n\t\t\t// e.g. foo_bar -\u003e foo-bar\n\t\t\targs = append(args, strings.Replace(arg, \"_\", \"-\", -1))\n\t\t}\n\n\t\t// In order to avoid that the same plugin command is added more than once,\n\t\t// find the lowest command given args from the root command\n\t\tparentCmd, remainingArgs, _ := kubectl.Find(args)\n\t\tif parentCmd == nil {\n\t\t\tparentCmd = kubectl\n\t\t}\n\n\t\tfor _, remainingArg := range remainingArgs {\n\t\t\tcmd := \u0026cobra.Command{\n\t\t\t\tUse: remainingArg,\n\t\t\t\t// Add a description that will be shown with completion choices.\n\t\t\t\t// Make each one different by including the plugin name to avoid\n\t\t\t\t// all plugins being grouped in a single line during completion for zsh.\n\t\t\t\tShort: fmt.Sprintf(\"The command %s is a plugin installed by the user\", remainingArg),\n\t\t\t\tDisableFlagParsing: true,\n\t\t\t\t// Allow plugins to provide their own completion choices\n\t\t\t\tValidArgsFunction: pluginCompletion,\n\t\t\t\t// A Run is required for it to be a valid command\n\t\t\t\tRun: func(cmd *cobra.Command, args []string) {},\n\t\t\t}\n\t\t\tparentCmd.AddCommand(cmd)\n\t\t\tparentCmd = cmd\n\t\t}\n\t}\n}","line":{"from":80,"to":130}} {"id":100032017,"name":"pluginCompletion","signature":"func pluginCompletion(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)","file":"staging/src/k8s.io/kubectl/pkg/cmd/plugin/plugin_completion.go","code":"// pluginCompletion deals with shell completion beyond the plugin name, it allows to complete\n// plugin arguments and flags.\n// It will look on $PATH for a specific executable file that will provide completions\n// for the plugin in question.\n//\n// When called, this completion executable should print the completion choices to stdout.\n// The arguments passed to the executable file will be the arguments for the plugin currently\n// on the command-line. For example, if a user types:\n//\n//\tkubectl myplugin arg1 arg2 a\u003cTAB\u003e\n//\n// the completion executable will be called with arguments: \"arg1\" \"arg2\" \"a\".\n// And if a user types:\n//\n//\tkubectl myplugin arg1 arg2 \u003cTAB\u003e\n//\n// the completion executable will be called with arguments: \"arg1\" \"arg2\" \"\". Notice the empty\n// last argument which indicates that a new word should be completed but that the user has not\n// typed anything for it yet.\n//\n// Kubectl's plugin completion logic supports Cobra's ShellCompDirective system. This means a plugin\n// can optionally print :\u003cvalue of a shell completion directive\u003e as its very last line to provide\n// directives to the shell on how to perform completion. If this directive is not present, the\n// cobra.ShellCompDirectiveDefault will be used. Please see Cobra's documentation for more details:\n// https://github.com/spf13/cobra/blob/master/shell_completions.md#dynamic-completion-of-nouns\n//\n// The completion executable should be named kubectl_complete-\u003cplugin\u003e. For example, for a plugin\n// named kubectl-get_all, the completion file should be named kubectl_complete-get_all. The completion\n// executable must have executable permissions set on it and must be on $PATH.\nfunc pluginCompletion(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\t// Recreate the plugin name from the commandPath\n\tpluginName := strings.Replace(strings.Replace(cmd.CommandPath(), \"-\", \"_\", -1), \" \", \"-\", -1)\n\n\tpath, found := lookupCompletionExec(pluginName)\n\tif !found {\n\t\tcobra.CompDebugln(fmt.Sprintf(\"Plugin %s does not provide a matching completion executable\", pluginName), true)\n\t\treturn nil, cobra.ShellCompDirectiveDefault\n\t}\n\n\targs = append(args, toComplete)\n\tcobra.CompDebugln(fmt.Sprintf(\"About to call: %s %s\", path, strings.Join(args, \" \")), true)\n\treturn getPluginCompletions(path, args, os.Environ())\n}","line":{"from":132,"to":174}} {"id":100032018,"name":"lookupCompletionExec","signature":"func lookupCompletionExec(pluginName string) (string, bool)","file":"staging/src/k8s.io/kubectl/pkg/cmd/plugin/plugin_completion.go","code":"// lookupCompletionExec will look for the existence of an executable\n// that can provide completion for the given plugin name.\n// The first filepath to match is returned, or a boolean false if\n// such an executable is not found.\nfunc lookupCompletionExec(pluginName string) (string, bool) {\n\t// Convert the plugin name into the plugin completion name by inserting \"_complete\" before the first -.\n\t// For example, convert kubectl-get_all to kubectl_complete-get_all\n\tpluginCompExec := strings.Replace(pluginName, \"-\", \"_complete-\", 1)\n\tcobra.CompDebugln(fmt.Sprintf(\"About to look for: %s\", pluginCompExec), true)\n\tpath, err := exec.LookPath(pluginCompExec)\n\tif err != nil || len(path) == 0 {\n\t\treturn \"\", false\n\t}\n\treturn path, true\n}","line":{"from":176,"to":190}} {"id":100032019,"name":"getPluginCompletions","signature":"func getPluginCompletions(executablePath string, cmdArgs, environment []string) ([]string, cobra.ShellCompDirective)","file":"staging/src/k8s.io/kubectl/pkg/cmd/plugin/plugin_completion.go","code":"// getPluginCompletions receives an executable's filepath, a slice\n// of arguments, and a slice of environment variables\n// to relay to the executable.\n// The executable is responsible for printing the completions of the\n// plugin for the current set of arguments.\nfunc getPluginCompletions(executablePath string, cmdArgs, environment []string) ([]string, cobra.ShellCompDirective) {\n\tbuf := new(bytes.Buffer)\n\n\tprog := exec.Command(executablePath, cmdArgs...)\n\tprog.Stdin = os.Stdin\n\tprog.Stdout = buf\n\tprog.Stderr = os.Stderr\n\tprog.Env = environment\n\n\tvar comps []string\n\tdirective := cobra.ShellCompDirectiveDefault\n\tif err := prog.Run(); err == nil {\n\t\tfor _, comp := range strings.Split(buf.String(), \"\\n\") {\n\t\t\t// Remove any empty lines\n\t\t\tif len(comp) \u003e 0 {\n\t\t\t\tcomps = append(comps, comp)\n\t\t\t}\n\t\t}\n\n\t\t// Check if the last line of output is of the form :\u003cinteger\u003e, which\n\t\t// indicates a Cobra ShellCompDirective. We do this for plugins\n\t\t// that use Cobra or the ones that wish to use this directive to\n\t\t// communicate a special behavior for the shell.\n\t\tif len(comps) \u003e 0 {\n\t\t\tlastLine := comps[len(comps)-1]\n\t\t\tif len(lastLine) \u003e 1 \u0026\u0026 lastLine[0] == ':' {\n\t\t\t\tif strInt, err := strconv.Atoi(lastLine[1:]); err == nil {\n\t\t\t\t\tdirective = cobra.ShellCompDirective(strInt)\n\t\t\t\t\tcomps = comps[:len(comps)-1]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn comps, directive\n}","line":{"from":192,"to":231}} {"id":100032020,"name":"NewCmdPortForward","signature":"func NewCmdPortForward(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/portforward/portforward.go","code":"func NewCmdPortForward(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\topts := \u0026PortForwardOptions{\n\t\tPortForwarder: \u0026defaultPortForwarder{\n\t\t\tIOStreams: streams,\n\t\t},\n\t}\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"port-forward TYPE/NAME [options] [LOCAL_PORT:]REMOTE_PORT [...[LOCAL_PORT_N:]REMOTE_PORT_N]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Forward one or more local ports to a pod\"),\n\t\tLong: portforwardLong,\n\t\tExample: portforwardExample,\n\t\tValidArgsFunction: completion.PodResourceNameCompletionFunc(f),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(opts.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(opts.Validate())\n\t\t\tcmdutil.CheckErr(opts.RunPortForward())\n\t\t},\n\t}\n\tcmdutil.AddPodRunningTimeoutFlag(cmd, defaultPodPortForwardWaitTimeout)\n\tcmd.Flags().StringSliceVar(\u0026opts.Address, \"address\", []string{\"localhost\"}, \"Addresses to listen on (comma separated). Only accepts IP addresses or localhost as a value. When localhost is supplied, kubectl will try to bind on both 127.0.0.1 and ::1 and will fail if neither of these addresses are available to bind.\")\n\t// TODO support UID\n\treturn cmd\n}","line":{"from":101,"to":124}} {"id":100032021,"name":"ForwardPorts","signature":"func (f *defaultPortForwarder) ForwardPorts(method string, url *url.URL, opts PortForwardOptions) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/portforward/portforward.go","code":"func (f *defaultPortForwarder) ForwardPorts(method string, url *url.URL, opts PortForwardOptions) error {\n\ttransport, upgrader, err := spdy.RoundTripperFor(opts.Config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdialer := spdy.NewDialer(upgrader, \u0026http.Client{Transport: transport}, method, url)\n\tfw, err := portforward.NewOnAddresses(dialer, opts.Address, opts.Ports, opts.StopChannel, opts.ReadyChannel, f.Out, f.ErrOut)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn fw.ForwardPorts()\n}","line":{"from":134,"to":145}} {"id":100032022,"name":"splitPort","signature":"func splitPort(port string) (local, remote string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/portforward/portforward.go","code":"// splitPort splits port string which is in form of [LOCAL PORT]:REMOTE PORT\n// and returns local and remote ports separately\nfunc splitPort(port string) (local, remote string) {\n\tparts := strings.Split(port, \":\")\n\tif len(parts) == 2 {\n\t\treturn parts[0], parts[1]\n\t}\n\n\treturn parts[0], parts[0]\n}","line":{"from":147,"to":156}} {"id":100032023,"name":"translateServicePortToTargetPort","signature":"func translateServicePortToTargetPort(ports []string, svc corev1.Service, pod corev1.Pod) ([]string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/portforward/portforward.go","code":"// Translates service port to target port\n// It rewrites ports as needed if the Service port declares targetPort.\n// It returns an error when a named targetPort can't find a match in the pod, or the Service did not declare\n// the port.\nfunc translateServicePortToTargetPort(ports []string, svc corev1.Service, pod corev1.Pod) ([]string, error) {\n\tvar translated []string\n\tfor _, port := range ports {\n\t\tlocalPort, remotePort := splitPort(port)\n\n\t\tportnum, err := strconv.Atoi(remotePort)\n\t\tif err != nil {\n\t\t\tsvcPort, err := util.LookupServicePortNumberByName(svc, remotePort)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tportnum = int(svcPort)\n\n\t\t\tif localPort == remotePort {\n\t\t\t\tlocalPort = strconv.Itoa(portnum)\n\t\t\t}\n\t\t}\n\t\tcontainerPort, err := util.LookupContainerPortNumberByServicePort(svc, pod, int32(portnum))\n\t\tif err != nil {\n\t\t\t// can't resolve a named port, or Service did not declare this port, return an error\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// convert the resolved target port back to a string\n\t\tremotePort = strconv.Itoa(int(containerPort))\n\n\t\tif localPort != remotePort {\n\t\t\ttranslated = append(translated, fmt.Sprintf(\"%s:%s\", localPort, remotePort))\n\t\t} else {\n\t\t\ttranslated = append(translated, remotePort)\n\t\t}\n\t}\n\treturn translated, nil\n}","line":{"from":158,"to":195}} {"id":100032024,"name":"convertPodNamedPortToNumber","signature":"func convertPodNamedPortToNumber(ports []string, pod corev1.Pod) ([]string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/portforward/portforward.go","code":"// convertPodNamedPortToNumber converts named ports into port numbers\n// It returns an error when a named port can't be found in the pod containers\nfunc convertPodNamedPortToNumber(ports []string, pod corev1.Pod) ([]string, error) {\n\tvar converted []string\n\tfor _, port := range ports {\n\t\tlocalPort, remotePort := splitPort(port)\n\n\t\tcontainerPortStr := remotePort\n\t\t_, err := strconv.Atoi(remotePort)\n\t\tif err != nil {\n\t\t\tcontainerPort, err := util.LookupContainerPortNumberByName(pod, remotePort)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tcontainerPortStr = strconv.Itoa(int(containerPort))\n\t\t}\n\n\t\tif localPort != remotePort {\n\t\t\tconverted = append(converted, fmt.Sprintf(\"%s:%s\", localPort, containerPortStr))\n\t\t} else {\n\t\t\tconverted = append(converted, containerPortStr)\n\t\t}\n\t}\n\n\treturn converted, nil\n}","line":{"from":197,"to":223}} {"id":100032025,"name":"checkUDPPorts","signature":"func checkUDPPorts(udpOnlyPorts sets.Int, ports []string, obj metav1.Object) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/portforward/portforward.go","code":"func checkUDPPorts(udpOnlyPorts sets.Int, ports []string, obj metav1.Object) error {\n\tfor _, port := range ports {\n\t\t_, remotePort := splitPort(port)\n\t\tportNum, err := strconv.Atoi(remotePort)\n\t\tif err != nil {\n\t\t\tswitch v := obj.(type) {\n\t\t\tcase *corev1.Service:\n\t\t\t\tsvcPort, err := util.LookupServicePortNumberByName(*v, remotePort)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tportNum = int(svcPort)\n\n\t\t\tcase *corev1.Pod:\n\t\t\t\tctPort, err := util.LookupContainerPortNumberByName(*v, remotePort)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tportNum = int(ctPort)\n\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"unknown object: %v\", obj)\n\t\t\t}\n\t\t}\n\t\tif udpOnlyPorts.Has(portNum) {\n\t\t\treturn fmt.Errorf(\"UDP protocol is not supported for %s\", remotePort)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":225,"to":254}} {"id":100032026,"name":"checkUDPPortInService","signature":"func checkUDPPortInService(ports []string, svc *corev1.Service) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/portforward/portforward.go","code":"// checkUDPPortInService returns an error if remote port in Service is a UDP port\n// TODO: remove this check after #47862 is solved\nfunc checkUDPPortInService(ports []string, svc *corev1.Service) error {\n\tudpPorts := sets.NewInt()\n\ttcpPorts := sets.NewInt()\n\tfor _, port := range svc.Spec.Ports {\n\t\tportNum := int(port.Port)\n\t\tswitch port.Protocol {\n\t\tcase corev1.ProtocolUDP:\n\t\t\tudpPorts.Insert(portNum)\n\t\tcase corev1.ProtocolTCP:\n\t\t\ttcpPorts.Insert(portNum)\n\t\t}\n\t}\n\treturn checkUDPPorts(udpPorts.Difference(tcpPorts), ports, svc)\n}","line":{"from":256,"to":271}} {"id":100032027,"name":"checkUDPPortInPod","signature":"func checkUDPPortInPod(ports []string, pod *corev1.Pod) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/portforward/portforward.go","code":"// checkUDPPortInPod returns an error if remote port in Pod is a UDP port\n// TODO: remove this check after #47862 is solved\nfunc checkUDPPortInPod(ports []string, pod *corev1.Pod) error {\n\tudpPorts := sets.NewInt()\n\ttcpPorts := sets.NewInt()\n\tfor _, ct := range pod.Spec.Containers {\n\t\tfor _, ctPort := range ct.Ports {\n\t\t\tportNum := int(ctPort.ContainerPort)\n\t\t\tswitch ctPort.Protocol {\n\t\t\tcase corev1.ProtocolUDP:\n\t\t\t\tudpPorts.Insert(portNum)\n\t\t\tcase corev1.ProtocolTCP:\n\t\t\t\ttcpPorts.Insert(portNum)\n\t\t\t}\n\t\t}\n\t}\n\treturn checkUDPPorts(udpPorts.Difference(tcpPorts), ports, pod)\n}","line":{"from":273,"to":290}} {"id":100032028,"name":"Complete","signature":"func (o *PortForwardOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/portforward/portforward.go","code":"// Complete completes all the required options for port-forward cmd.\nfunc (o *PortForwardOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\tif len(args) \u003c 2 {\n\t\treturn cmdutil.UsageErrorf(cmd, \"TYPE/NAME and list of ports are required for port-forward\")\n\t}\n\n\to.Namespace, _, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbuilder := f.NewBuilder().\n\t\tWithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).\n\t\tContinueOnError().\n\t\tNamespaceParam(o.Namespace).DefaultNamespace()\n\n\tgetPodTimeout, err := cmdutil.GetPodRunningTimeoutFlag(cmd)\n\tif err != nil {\n\t\treturn cmdutil.UsageErrorf(cmd, err.Error())\n\t}\n\n\tresourceName := args[0]\n\tbuilder.ResourceNames(\"pods\", resourceName)\n\n\tobj, err := builder.Do().Object()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tforwardablePod, err := polymorphichelpers.AttachablePodForObjectFn(f, obj, getPodTimeout)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.PodName = forwardablePod.Name\n\n\t// handle service port mapping to target port if needed\n\tswitch t := obj.(type) {\n\tcase *corev1.Service:\n\t\terr = checkUDPPortInService(args[1:], t)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\to.Ports, err = translateServicePortToTargetPort(args[1:], *t, *forwardablePod)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\terr = checkUDPPortInPod(args[1:], forwardablePod)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\to.Ports, err = convertPodNamedPortToNumber(args[1:], *forwardablePod)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tclientset, err := f.KubernetesClientSet()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.PodClient = clientset.CoreV1()\n\n\to.Config, err = f.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.RESTClient, err = f.RESTClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.StopChannel = make(chan struct{}, 1)\n\to.ReadyChannel = make(chan struct{})\n\treturn nil\n}","line":{"from":292,"to":370}} {"id":100032029,"name":"Validate","signature":"func (o PortForwardOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/portforward/portforward.go","code":"// Validate validates all the required options for port-forward cmd.\nfunc (o PortForwardOptions) Validate() error {\n\tif len(o.PodName) == 0 {\n\t\treturn fmt.Errorf(\"pod name or resource type/name must be specified\")\n\t}\n\n\tif len(o.Ports) \u003c 1 {\n\t\treturn fmt.Errorf(\"at least 1 PORT is required for port-forward\")\n\t}\n\n\tif o.PortForwarder == nil || o.PodClient == nil || o.RESTClient == nil || o.Config == nil {\n\t\treturn fmt.Errorf(\"client, client config, restClient, and portforwarder must be provided\")\n\t}\n\treturn nil\n}","line":{"from":372,"to":386}} {"id":100032030,"name":"RunPortForward","signature":"func (o PortForwardOptions) RunPortForward() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/portforward/portforward.go","code":"// RunPortForward implements all the necessary functionality for port-forward cmd.\nfunc (o PortForwardOptions) RunPortForward() error {\n\tpod, err := o.PodClient.Pods(o.Namespace).Get(context.TODO(), o.PodName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif pod.Status.Phase != corev1.PodRunning {\n\t\treturn fmt.Errorf(\"unable to forward port because pod is not running. Current status=%v\", pod.Status.Phase)\n\t}\n\n\tsignals := make(chan os.Signal, 1)\n\tsignal.Notify(signals, os.Interrupt)\n\tdefer signal.Stop(signals)\n\n\tgo func() {\n\t\t\u003c-signals\n\t\tif o.StopChannel != nil {\n\t\t\tclose(o.StopChannel)\n\t\t}\n\t}()\n\n\treq := o.RESTClient.Post().\n\t\tResource(\"pods\").\n\t\tNamespace(o.Namespace).\n\t\tName(pod.Name).\n\t\tSubResource(\"portforward\")\n\n\treturn o.PortForwarder.ForwardPorts(\"POST\", req.URL(), o)\n}","line":{"from":388,"to":417}} {"id":100032031,"name":"addProfilingFlags","signature":"func addProfilingFlags(flags *pflag.FlagSet)","file":"staging/src/k8s.io/kubectl/pkg/cmd/profiling.go","code":"func addProfilingFlags(flags *pflag.FlagSet) {\n\tflags.StringVar(\u0026profileName, \"profile\", \"none\", \"Name of profile to capture. One of (none|cpu|heap|goroutine|threadcreate|block|mutex)\")\n\tflags.StringVar(\u0026profileOutput, \"profile-output\", \"profile.pprof\", \"Name of the file to write the profile to\")\n}","line":{"from":34,"to":37}} {"id":100032032,"name":"initProfiling","signature":"func initProfiling() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/profiling.go","code":"func initProfiling() error {\n\tvar (\n\t\tf *os.File\n\t\terr error\n\t)\n\tswitch profileName {\n\tcase \"none\":\n\t\treturn nil\n\tcase \"cpu\":\n\t\tf, err = os.Create(profileOutput)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = pprof.StartCPUProfile(f)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t// Block and mutex profiles need a call to Set{Block,Mutex}ProfileRate to\n\t// output anything. We choose to sample all events.\n\tcase \"block\":\n\t\truntime.SetBlockProfileRate(1)\n\tcase \"mutex\":\n\t\truntime.SetMutexProfileFraction(1)\n\tdefault:\n\t\t// Check the profile name is valid.\n\t\tif profile := pprof.Lookup(profileName); profile == nil {\n\t\t\treturn fmt.Errorf(\"unknown profile '%s'\", profileName)\n\t\t}\n\t}\n\n\t// If the command is interrupted before the end (ctrl-c), flush the\n\t// profiling files\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\tgo func() {\n\t\t\u003c-c\n\t\tf.Close()\n\t\tflushProfiling()\n\t\tos.Exit(0)\n\t}()\n\n\treturn nil\n}","line":{"from":39,"to":81}} {"id":100032033,"name":"flushProfiling","signature":"func flushProfiling() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/profiling.go","code":"func flushProfiling() error {\n\tswitch profileName {\n\tcase \"none\":\n\t\treturn nil\n\tcase \"cpu\":\n\t\tpprof.StopCPUProfile()\n\tcase \"heap\":\n\t\truntime.GC()\n\t\tfallthrough\n\tdefault:\n\t\tprofile := pprof.Lookup(profileName)\n\t\tif profile == nil {\n\t\t\treturn nil\n\t\t}\n\t\tf, err := os.Create(profileOutput)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\t\tprofile.WriteTo(f, 0)\n\t}\n\n\treturn nil\n}","line":{"from":83,"to":106}} {"id":100032034,"name":"NewProxyOptions","signature":"func NewProxyOptions(ioStreams genericclioptions.IOStreams) *ProxyOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/proxy/proxy.go","code":"// NewProxyOptions creates the options for proxy\nfunc NewProxyOptions(ioStreams genericclioptions.IOStreams) *ProxyOptions {\n\treturn \u0026ProxyOptions{\n\t\tIOStreams: ioStreams,\n\t\tstaticPrefix: defaultStaticPrefix,\n\t\tapiPrefix: defaultAPIPrefix,\n\t\tacceptPaths: proxy.DefaultPathAcceptRE,\n\t\trejectPaths: proxy.DefaultPathRejectRE,\n\t\tacceptHosts: proxy.DefaultHostAcceptRE,\n\t\trejectMethods: proxy.DefaultMethodRejectRE,\n\t\tport: defaultPort,\n\t\taddress: defaultAddress,\n\t}\n}","line":{"from":100,"to":113}} {"id":100032035,"name":"NewCmdProxy","signature":"func NewCmdProxy(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/proxy/proxy.go","code":"// NewCmdProxy returns the proxy Cobra command\nfunc NewCmdProxy(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewProxyOptions(ioStreams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"proxy [--port=PORT] [--www=static-dir] [--www-prefix=prefix] [--api-prefix=prefix]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Run a proxy to the Kubernetes API server\"),\n\t\tLong: proxyLong,\n\t\tExample: proxyExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.RunProxy())\n\t\t},\n\t}\n\n\tcmd.Flags().StringVarP(\u0026o.staticDir, \"www\", \"w\", o.staticDir, \"Also serve static files from the given directory under the specified prefix.\")\n\tcmd.Flags().StringVarP(\u0026o.staticPrefix, \"www-prefix\", \"P\", o.staticPrefix, \"Prefix to serve static files under, if static file directory is specified.\")\n\tcmd.Flags().StringVar(\u0026o.apiPrefix, \"api-prefix\", o.apiPrefix, \"Prefix to serve the proxied API under.\")\n\tcmd.Flags().StringVar(\u0026o.acceptPaths, \"accept-paths\", o.acceptPaths, \"Regular expression for paths that the proxy should accept.\")\n\tcmd.Flags().StringVar(\u0026o.rejectPaths, \"reject-paths\", o.rejectPaths, \"Regular expression for paths that the proxy should reject. Paths specified here will be rejected even accepted by --accept-paths.\")\n\tcmd.Flags().StringVar(\u0026o.acceptHosts, \"accept-hosts\", o.acceptHosts, \"Regular expression for hosts that the proxy should accept.\")\n\tcmd.Flags().StringVar(\u0026o.rejectMethods, \"reject-methods\", o.rejectMethods, \"Regular expression for HTTP methods that the proxy should reject (example --reject-methods='POST,PUT,PATCH'). \")\n\tcmd.Flags().IntVarP(\u0026o.port, \"port\", \"p\", o.port, \"The port on which to run the proxy. Set to 0 to pick a random port.\")\n\tcmd.Flags().StringVar(\u0026o.address, \"address\", o.address, \"The IP address on which to serve on.\")\n\tcmd.Flags().BoolVar(\u0026o.disableFilter, \"disable-filter\", o.disableFilter, \"If true, disable request filtering in the proxy. This is dangerous, and can leave you vulnerable to XSRF attacks, when used with an accessible port.\")\n\tcmd.Flags().StringVarP(\u0026o.unixSocket, \"unix-socket\", \"u\", o.unixSocket, \"Unix socket on which to run the proxy.\")\n\tcmd.Flags().DurationVar(\u0026o.keepalive, \"keepalive\", o.keepalive, \"keepalive specifies the keep-alive period for an active network connection. Set to 0 to disable keepalive.\")\n\tcmd.Flags().BoolVar(\u0026o.appendServerPath, \"append-server-path\", o.appendServerPath, \"If true, enables automatic path appending of the kube context server path to each request.\")\n\treturn cmd\n}","line":{"from":115,"to":146}} {"id":100032036,"name":"Complete","signature":"func (o *ProxyOptions) Complete(f cmdutil.Factory) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/proxy/proxy.go","code":"// Complete adapts from the command line args and factory to the data required.\nfunc (o *ProxyOptions) Complete(f cmdutil.Factory) error {\n\tclientConfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.clientConfig = clientConfig\n\n\tif !strings.HasSuffix(o.staticPrefix, \"/\") {\n\t\to.staticPrefix += \"/\"\n\t}\n\n\tif !strings.HasSuffix(o.apiPrefix, \"/\") {\n\t\to.apiPrefix += \"/\"\n\t}\n\n\tif o.appendServerPath == false {\n\t\ttarget, err := url.Parse(clientConfig.Host)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif target.Path != \"\" \u0026\u0026 target.Path != \"/\" {\n\t\t\tklog.Warning(\"Your kube context contains a server path \" + target.Path + \", use --append-server-path to automatically append the path to each request\")\n\t\t}\n\t}\n\tif o.disableFilter {\n\t\tif o.unixSocket == \"\" {\n\t\t\tklog.Warning(\"Request filter disabled, your proxy is vulnerable to XSRF attacks, please be cautious\")\n\t\t}\n\t\to.filter = nil\n\t} else {\n\t\to.filter = \u0026proxy.FilterServer{\n\t\t\tAcceptPaths: proxy.MakeRegexpArrayOrDie(o.acceptPaths),\n\t\t\tRejectPaths: proxy.MakeRegexpArrayOrDie(o.rejectPaths),\n\t\t\tAcceptHosts: proxy.MakeRegexpArrayOrDie(o.acceptHosts),\n\t\t\tRejectMethods: proxy.MakeRegexpArrayOrDie(o.rejectMethods),\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":148,"to":187}} {"id":100032037,"name":"Validate","signature":"func (o ProxyOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/proxy/proxy.go","code":"// Validate checks to the ProxyOptions to see if there is sufficient information to run the command.\nfunc (o ProxyOptions) Validate() error {\n\tif o.port != defaultPort \u0026\u0026 o.unixSocket != \"\" {\n\t\treturn errors.New(\"cannot set --unix-socket and --port at the same time\")\n\t}\n\n\tif o.staticDir != \"\" {\n\t\tfileInfo, err := os.Stat(o.staticDir)\n\t\tif err != nil {\n\t\t\tklog.Warning(\"Failed to stat static file directory \"+o.staticDir+\": \", err)\n\t\t} else if !fileInfo.IsDir() {\n\t\t\tklog.Warning(\"Static file directory \" + o.staticDir + \" is not a directory\")\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":189,"to":205}} {"id":100032038,"name":"RunProxy","signature":"func (o ProxyOptions) RunProxy() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/proxy/proxy.go","code":"// RunProxy checks given arguments and executes command\nfunc (o ProxyOptions) RunProxy() error {\n\tserver, err := proxy.NewServer(o.staticDir, o.apiPrefix, o.staticPrefix, o.filter, o.clientConfig, o.keepalive, o.appendServerPath)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Separate listening from serving so we can report the bound port\n\t// when it is chosen by os (eg: port == 0)\n\tvar l net.Listener\n\tif o.unixSocket == \"\" {\n\t\tl, err = server.Listen(o.address, o.port)\n\t} else {\n\t\tl, err = server.ListenUnix(o.unixSocket)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Fprintf(o.IOStreams.Out, \"Starting to serve on %s\\n\", l.Addr().String())\n\treturn server.ServeOnListener(l)\n}","line":{"from":207,"to":228}} {"id":100032039,"name":"NewReplaceOptions","signature":"func NewReplaceOptions(streams genericclioptions.IOStreams) *ReplaceOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/replace/replace.go","code":"func NewReplaceOptions(streams genericclioptions.IOStreams) *ReplaceOptions {\n\treturn \u0026ReplaceOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"replaced\"),\n\t\tDeleteFlags: delete.NewDeleteFlags(\"The files that contain the configurations to replace.\"),\n\n\t\tIOStreams: streams,\n\t}\n}","line":{"from":103,"to":110}} {"id":100032040,"name":"NewCmdReplace","signature":"func NewCmdReplace(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/replace/replace.go","code":"func NewCmdReplace(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\to := NewReplaceOptions(streams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"replace -f FILENAME\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Replace a resource by file name or stdin\"),\n\t\tLong: replaceLong,\n\t\tExample: replaceExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run(f))\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\to.DeleteFlags.AddFlags(cmd)\n\to.RecordFlags.AddFlags(cmd)\n\n\tcmdutil.AddValidateFlags(cmd)\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddDryRunFlag(cmd)\n\n\tcmd.Flags().StringVar(\u0026o.Raw, \"raw\", o.Raw, \"Raw URI to PUT to the server. Uses the transport specified by the kubeconfig file.\")\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.fieldManager, \"kubectl-replace\")\n\tcmdutil.AddSubresourceFlags(cmd, \u0026o.Subresource, \"If specified, replace will operate on the subresource of the requested object.\", supportedSubresources...)\n\n\treturn cmd\n}","line":{"from":112,"to":141}} {"id":100032041,"name":"Complete","signature":"func (o *ReplaceOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/replace/replace.go","code":"func (o *ReplaceOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\n\to.RecordFlags.Complete(cmd)\n\to.Recorder, err = o.RecordFlags.ToRecorder()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.validationDirective, err = cmdutil.GetValidationDirective(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\to.createAnnotation = cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag)\n\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdynamicClient, err := f.DynamicClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.PrintObj = func(obj runtime.Object) error {\n\t\treturn printer.PrintObj(obj, o.Out)\n\t}\n\n\tdeleteOpts, err := o.DeleteFlags.ToOptions(dynamicClient, o.IOStreams)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t//Replace will create a resource if it doesn't exist already, so ignore not found error\n\tdeleteOpts.IgnoreNotFound = true\n\tif o.PrintFlags.OutputFormat != nil {\n\t\tdeleteOpts.Output = *o.PrintFlags.OutputFormat\n\t}\n\tif deleteOpts.GracePeriod == 0 {\n\t\t// To preserve backwards compatibility, but prevent accidental data loss, we convert --grace-period=0\n\t\t// into --grace-period=1 and wait until the object is successfully deleted.\n\t\tdeleteOpts.GracePeriod = 1\n\t\tdeleteOpts.WaitForDeletion = true\n\t}\n\to.DeleteOptions = deleteOpts\n\n\terr = o.DeleteOptions.FilenameOptions.RequireFilenameOrKustomize()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tschema, err := f.Validator(o.validationDirective)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Schema = schema\n\to.Builder = f.NewBuilder\n\to.BuilderArgs = args\n\n\to.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":143,"to":214}} {"id":100032042,"name":"Validate","signature":"func (o *ReplaceOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/replace/replace.go","code":"func (o *ReplaceOptions) Validate() error {\n\tif o.DeleteOptions.GracePeriod \u003e= 0 \u0026\u0026 !o.DeleteOptions.ForceDeletion {\n\t\treturn fmt.Errorf(\"--grace-period must have --force specified\")\n\t}\n\n\tif o.DeleteOptions.Timeout != 0 \u0026\u0026 !o.DeleteOptions.ForceDeletion {\n\t\treturn fmt.Errorf(\"--timeout must have --force specified\")\n\t}\n\n\tif o.DeleteOptions.ForceDeletion \u0026\u0026 o.DryRunStrategy != cmdutil.DryRunNone {\n\t\treturn fmt.Errorf(\"--dry-run can not be used when --force is set\")\n\t}\n\n\tif cmdutil.IsFilenameSliceEmpty(o.DeleteOptions.FilenameOptions.Filenames, o.DeleteOptions.FilenameOptions.Kustomize) {\n\t\treturn fmt.Errorf(\"must specify --filename to replace\")\n\t}\n\n\tif len(o.Raw) \u003e 0 {\n\t\tif len(o.DeleteOptions.FilenameOptions.Filenames) != 1 {\n\t\t\treturn fmt.Errorf(\"--raw can only use a single local file or stdin\")\n\t\t}\n\t\tif strings.Index(o.DeleteOptions.FilenameOptions.Filenames[0], \"http://\") == 0 || strings.Index(o.DeleteOptions.FilenameOptions.Filenames[0], \"https://\") == 0 {\n\t\t\treturn fmt.Errorf(\"--raw cannot read from a url\")\n\t\t}\n\t\tif o.DeleteOptions.FilenameOptions.Recursive {\n\t\t\treturn fmt.Errorf(\"--raw and --recursive are mutually exclusive\")\n\t\t}\n\t\tif o.PrintFlags.OutputFormat != nil \u0026\u0026 len(*o.PrintFlags.OutputFormat) \u003e 0 {\n\t\t\treturn fmt.Errorf(\"--raw and --output are mutually exclusive\")\n\t\t}\n\t\tif _, err := url.ParseRequestURI(o.Raw); err != nil {\n\t\t\treturn fmt.Errorf(\"--raw must be a valid URL path: %v\", err)\n\t\t}\n\t}\n\n\tif len(o.Subresource) \u003e 0 \u0026\u0026 !slice.ContainsString(supportedSubresources, o.Subresource, nil) {\n\t\treturn fmt.Errorf(\"invalid subresource value: %q. Must be one of %v\", o.Subresource, supportedSubresources)\n\t}\n\n\treturn nil\n}","line":{"from":216,"to":256}} {"id":100032043,"name":"Run","signature":"func (o *ReplaceOptions) Run(f cmdutil.Factory) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/replace/replace.go","code":"func (o *ReplaceOptions) Run(f cmdutil.Factory) error {\n\t// raw only makes sense for a single file resource multiple objects aren't likely to do what you want.\n\t// the validator enforces this, so\n\tif len(o.Raw) \u003e 0 {\n\t\trestClient, err := f.RESTClient()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn rawhttp.RawPut(restClient, o.IOStreams, o.Raw, o.DeleteOptions.Filenames[0])\n\t}\n\n\tif o.DeleteOptions.ForceDeletion {\n\t\treturn o.forceReplace()\n\t}\n\n\tr := o.Builder().\n\t\tUnstructured().\n\t\tSchema(o.Schema).\n\t\tContinueOnError().\n\t\tNamespaceParam(o.Namespace).DefaultNamespace().\n\t\tFilenameParam(o.EnforceNamespace, \u0026o.DeleteOptions.FilenameOptions).\n\t\tSubresource(o.Subresource).\n\t\tFlatten().\n\t\tDo()\n\tif err := r.Err(); err != nil {\n\t\treturn err\n\t}\n\n\treturn r.Visit(func(info *resource.Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := util.CreateOrUpdateAnnotation(o.createAnnotation, info.Object, scheme.DefaultJSONEncoder()); err != nil {\n\t\t\treturn cmdutil.AddSourceToErr(\"replacing\", info.Source, err)\n\t\t}\n\n\t\tif err := o.Recorder.Record(info.Object); err != nil {\n\t\t\tklog.V(4).Infof(\"error recording current command: %v\", err)\n\t\t}\n\n\t\tif o.DryRunStrategy == cmdutil.DryRunClient {\n\t\t\treturn o.PrintObj(info.Object)\n\t\t}\n\n\t\t// Serialize the object with the annotation applied.\n\t\tobj, err := resource.\n\t\t\tNewHelper(info.Client, info.Mapping).\n\t\t\tDryRun(o.DryRunStrategy == cmdutil.DryRunServer).\n\t\t\tWithFieldManager(o.fieldManager).\n\t\t\tWithFieldValidation(o.validationDirective).\n\t\t\tWithSubresource(o.Subresource).\n\t\t\tReplace(info.Namespace, info.Name, true, info.Object)\n\t\tif err != nil {\n\t\t\treturn cmdutil.AddSourceToErr(\"replacing\", info.Source, err)\n\t\t}\n\n\t\tinfo.Refresh(obj, true)\n\t\treturn o.PrintObj(info.Object)\n\t})\n}","line":{"from":258,"to":318}} {"id":100032044,"name":"forceReplace","signature":"func (o *ReplaceOptions) forceReplace() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/replace/replace.go","code":"func (o *ReplaceOptions) forceReplace() error {\n\tstdinInUse := false\n\tfor i, filename := range o.DeleteOptions.FilenameOptions.Filenames {\n\t\tif filename == \"-\" {\n\t\t\ttempDir, err := os.MkdirTemp(\"\", \"kubectl_replace_\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer os.RemoveAll(tempDir)\n\t\t\ttempFilename := filepath.Join(tempDir, \"resource.stdin\")\n\t\t\terr = cmdutil.DumpReaderToFile(os.Stdin, tempFilename)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\to.DeleteOptions.FilenameOptions.Filenames[i] = tempFilename\n\t\t\tstdinInUse = true\n\t\t}\n\t}\n\n\tb := o.Builder().\n\t\tUnstructured().\n\t\tContinueOnError().\n\t\tNamespaceParam(o.Namespace).DefaultNamespace().\n\t\tResourceTypeOrNameArgs(false, o.BuilderArgs...).RequireObject(false).\n\t\tFilenameParam(o.EnforceNamespace, \u0026o.DeleteOptions.FilenameOptions).\n\t\tSubresource(o.Subresource).\n\t\tFlatten()\n\tif stdinInUse {\n\t\tb = b.StdinInUse()\n\t}\n\tr := b.Do()\n\tif err := r.Err(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := o.DeleteOptions.DeleteResult(r); err != nil {\n\t\treturn err\n\t}\n\n\ttimeout := o.DeleteOptions.Timeout\n\tif timeout == 0 {\n\t\ttimeout = 5 * time.Minute\n\t}\n\terr := r.Visit(func(info *resource.Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn wait.PollImmediate(1*time.Second, timeout, func() (bool, error) {\n\t\t\tif err := info.Get(); !errors.IsNotFound(err) {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\treturn true, nil\n\t\t})\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tb = o.Builder().\n\t\tUnstructured().\n\t\tSchema(o.Schema).\n\t\tContinueOnError().\n\t\tNamespaceParam(o.Namespace).DefaultNamespace().\n\t\tFilenameParam(o.EnforceNamespace, \u0026o.DeleteOptions.FilenameOptions).\n\t\tSubresource(o.Subresource).\n\t\tFlatten()\n\tif stdinInUse {\n\t\tb = b.StdinInUse()\n\t}\n\tr = b.Do()\n\terr = r.Err()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcount := 0\n\terr = r.Visit(func(info *resource.Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := util.CreateOrUpdateAnnotation(o.createAnnotation, info.Object, scheme.DefaultJSONEncoder()); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := o.Recorder.Record(info.Object); err != nil {\n\t\t\tklog.V(4).Infof(\"error recording current command: %v\", err)\n\t\t}\n\n\t\tobj, err := resource.NewHelper(info.Client, info.Mapping).\n\t\t\tWithFieldManager(o.fieldManager).\n\t\t\tWithFieldValidation(o.validationDirective).\n\t\t\tCreate(info.Namespace, true, info.Object)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcount++\n\t\tinfo.Refresh(obj, true)\n\t\treturn o.PrintObj(info.Object)\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tif count == 0 {\n\t\treturn fmt.Errorf(\"no objects passed to replace\")\n\t}\n\treturn nil\n}","line":{"from":320,"to":429}} {"id":100032045,"name":"NewCmdRollout","signature":"func NewCmdRollout(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout.go","code":"// NewCmdRollout returns a Command instance for 'rollout' sub command\nfunc NewCmdRollout(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"rollout SUBCOMMAND\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Manage the rollout of a resource\"),\n\t\tLong: rolloutLong,\n\t\tExample: rolloutExample,\n\t\tRun: cmdutil.DefaultSubCommandRun(streams.Out),\n\t}\n\t// subcommands\n\tcmd.AddCommand(NewCmdRolloutHistory(f, streams))\n\tcmd.AddCommand(NewCmdRolloutPause(f, streams))\n\tcmd.AddCommand(NewCmdRolloutResume(f, streams))\n\tcmd.AddCommand(NewCmdRolloutUndo(f, streams))\n\tcmd.AddCommand(NewCmdRolloutStatus(f, streams))\n\tcmd.AddCommand(NewCmdRolloutRestart(f, streams))\n\n\treturn cmd\n}","line":{"from":55,"to":74}} {"id":100032046,"name":"NewRolloutHistoryOptions","signature":"func NewRolloutHistoryOptions(streams genericclioptions.IOStreams) *RolloutHistoryOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_history.go","code":"// NewRolloutHistoryOptions returns an initialized RolloutHistoryOptions instance\nfunc NewRolloutHistoryOptions(streams genericclioptions.IOStreams) *RolloutHistoryOptions {\n\treturn \u0026RolloutHistoryOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: streams,\n\t}\n}","line":{"from":68,"to":74}} {"id":100032047,"name":"NewCmdRolloutHistory","signature":"func NewCmdRolloutHistory(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_history.go","code":"// NewCmdRolloutHistory returns a Command instance for RolloutHistory sub command\nfunc NewCmdRolloutHistory(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\to := NewRolloutHistoryOptions(streams)\n\n\tvalidArgs := []string{\"deployment\", \"daemonset\", \"statefulset\"}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"history (TYPE NAME | TYPE/NAME) [flags]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"View rollout history\"),\n\t\tLong: historyLong,\n\t\tExample: historyExample,\n\t\tValidArgsFunction: completion.SpecifiedResourceTypeAndNameCompletionFunc(f, validArgs),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\tcmd.Flags().Int64Var(\u0026o.Revision, \"revision\", o.Revision, \"See the details, including podTemplate of the revision specified\")\n\tcmdutil.AddLabelSelectorFlagVar(cmd, \u0026o.LabelSelector)\n\n\tusage := \"identifying the resource to get from a server.\"\n\tcmdutil.AddFilenameOptionFlags(cmd, \u0026o.FilenameOptions, usage)\n\n\to.PrintFlags.AddFlags(cmd)\n\n\treturn cmd\n}","line":{"from":76,"to":105}} {"id":100032048,"name":"Complete","signature":"func (o *RolloutHistoryOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_history.go","code":"// Complete completes al the required options\nfunc (o *RolloutHistoryOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\to.Resources = args\n\n\tvar err error\n\tif o.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace(); err != nil {\n\t\treturn err\n\t}\n\n\to.ToPrinter = func(operation string) (printers.ResourcePrinter, error) {\n\t\to.PrintFlags.NamePrintFlags.Operation = operation\n\t\treturn o.PrintFlags.ToPrinter()\n\t}\n\n\to.HistoryViewer = polymorphichelpers.HistoryViewerFn\n\to.RESTClientGetter = f\n\to.Builder = f.NewBuilder\n\n\treturn nil\n}","line":{"from":107,"to":126}} {"id":100032049,"name":"Validate","signature":"func (o *RolloutHistoryOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_history.go","code":"// Validate makes sure all the provided values for command-line options are valid\nfunc (o *RolloutHistoryOptions) Validate() error {\n\tif len(o.Resources) == 0 \u0026\u0026 cmdutil.IsFilenameSliceEmpty(o.Filenames, o.Kustomize) {\n\t\treturn fmt.Errorf(\"required resource not specified\")\n\t}\n\tif o.Revision \u003c 0 {\n\t\treturn fmt.Errorf(\"revision must be a positive integer: %v\", o.Revision)\n\t}\n\n\treturn nil\n}","line":{"from":128,"to":138}} {"id":100032050,"name":"Run","signature":"func (o *RolloutHistoryOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_history.go","code":"// Run performs the execution of 'rollout history' sub command\nfunc (o *RolloutHistoryOptions) Run() error {\n\n\tr := o.Builder().\n\t\tWithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).\n\t\tNamespaceParam(o.Namespace).DefaultNamespace().\n\t\tFilenameParam(o.EnforceNamespace, \u0026o.FilenameOptions).\n\t\tLabelSelectorParam(o.LabelSelector).\n\t\tResourceTypeOrNameArgs(true, o.Resources...).\n\t\tContinueOnError().\n\t\tLatest().\n\t\tFlatten().\n\t\tDo()\n\tif err := r.Err(); err != nil {\n\t\treturn err\n\t}\n\n\tif o.PrintFlags.OutputFlagSpecified() {\n\t\tprinter, err := o.PrintFlags.ToPrinter()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn r.Visit(func(info *resource.Info, err error) error {\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tmapping := info.ResourceMapping()\n\t\t\thistoryViewer, err := o.HistoryViewer(o.RESTClientGetter, mapping)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thistoryInfo, err := historyViewer.GetHistory(info.Namespace, info.Name)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif o.Revision \u003e 0 {\n\t\t\t\tprinter.PrintObj(historyInfo[o.Revision], o.Out)\n\t\t\t} else {\n\t\t\t\tsortedKeys := make([]int64, 0, len(historyInfo))\n\t\t\t\tfor k := range historyInfo {\n\t\t\t\t\tsortedKeys = append(sortedKeys, k)\n\t\t\t\t}\n\t\t\t\tsort.Slice(sortedKeys, func(i, j int) bool { return sortedKeys[i] \u003c sortedKeys[j] })\n\t\t\t\tfor _, k := range sortedKeys {\n\t\t\t\t\tprinter.PrintObj(historyInfo[k], o.Out)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t}\n\n\treturn r.Visit(func(info *resource.Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tmapping := info.ResourceMapping()\n\t\thistoryViewer, err := o.HistoryViewer(o.RESTClientGetter, mapping)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thistoryInfo, err := historyViewer.ViewHistory(info.Namespace, info.Name, o.Revision)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\twithRevision := \"\"\n\t\tif o.Revision \u003e 0 {\n\t\t\twithRevision = fmt.Sprintf(\"with revision #%d\", o.Revision)\n\t\t}\n\n\t\tprinter, err := o.ToPrinter(fmt.Sprintf(\"%s\\n%s\", withRevision, historyInfo))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn printer.PrintObj(info.Object, o.Out)\n\t})\n}","line":{"from":140,"to":222}} {"id":100032051,"name":"NewCmdRolloutPause","signature":"func NewCmdRolloutPause(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_pause.go","code":"// NewCmdRolloutPause returns a Command instance for 'rollout pause' sub command\nfunc NewCmdRolloutPause(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\to := \u0026PauseOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"paused\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: streams,\n\t}\n\n\tvalidArgs := []string{\"deployment\"}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"pause RESOURCE\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Mark the provided resource as paused\"),\n\t\tLong: pauseLong,\n\t\tExample: pauseExample,\n\t\tValidArgsFunction: completion.SpecifiedResourceTypeAndNameCompletionFunc(f, validArgs),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.RunPause())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tusage := \"identifying the resource to get from a server.\"\n\tcmdutil.AddFilenameOptionFlags(cmd, \u0026o.FilenameOptions, usage)\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.fieldManager, \"kubectl-rollout\")\n\tcmdutil.AddLabelSelectorFlagVar(cmd, \u0026o.LabelSelector)\n\treturn cmd\n}","line":{"from":72,"to":102}} {"id":100032052,"name":"Complete","signature":"func (o *PauseOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_pause.go","code":"// Complete completes all the required options\nfunc (o *PauseOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\to.Pauser = polymorphichelpers.ObjectPauserFn\n\n\tvar err error\n\to.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Resources = args\n\to.Builder = f.NewBuilder\n\n\to.ToPrinter = func(operation string) (printers.ResourcePrinter, error) {\n\t\to.PrintFlags.NamePrintFlags.Operation = operation\n\t\treturn o.PrintFlags.ToPrinter()\n\t}\n\n\treturn nil\n}","line":{"from":104,"to":123}} {"id":100032053,"name":"Validate","signature":"func (o *PauseOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_pause.go","code":"func (o *PauseOptions) Validate() error {\n\tif len(o.Resources) == 0 \u0026\u0026 cmdutil.IsFilenameSliceEmpty(o.Filenames, o.Kustomize) {\n\t\treturn fmt.Errorf(\"required resource not specified\")\n\t}\n\treturn nil\n}","line":{"from":125,"to":130}} {"id":100032054,"name":"RunPause","signature":"func (o *PauseOptions) RunPause() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_pause.go","code":"// RunPause performs the execution of 'rollout pause' sub command\nfunc (o *PauseOptions) RunPause() error {\n\tr := o.Builder().\n\t\tWithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).\n\t\tNamespaceParam(o.Namespace).DefaultNamespace().\n\t\tLabelSelectorParam(o.LabelSelector).\n\t\tFilenameParam(o.EnforceNamespace, \u0026o.FilenameOptions).\n\t\tResourceTypeOrNameArgs(true, o.Resources...).\n\t\tContinueOnError().\n\t\tLatest().\n\t\tFlatten().\n\t\tDo()\n\tif err := r.Err(); err != nil {\n\t\treturn err\n\t}\n\n\tallErrs := []error{}\n\tinfos, err := r.Infos()\n\tif err != nil {\n\t\t// restore previous command behavior where\n\t\t// an error caused by retrieving infos due to\n\t\t// at least a single broken object did not result\n\t\t// in an immediate return, but rather an overall\n\t\t// aggregation of errors.\n\t\tallErrs = append(allErrs, err)\n\t}\n\n\tpatches := set.CalculatePatches(infos, scheme.DefaultJSONEncoder(), set.PatchFn(o.Pauser))\n\n\tif len(patches) == 0 \u0026\u0026 len(allErrs) == 0 {\n\t\tfmt.Fprintf(o.ErrOut, \"No resources found in %s namespace.\\n\", o.Namespace)\n\t\treturn nil\n\t}\n\n\tfor _, patch := range patches {\n\t\tinfo := patch.Info\n\n\t\tif patch.Err != nil {\n\t\t\tresourceString := info.Mapping.Resource.Resource\n\t\t\tif len(info.Mapping.Resource.Group) \u003e 0 {\n\t\t\t\tresourceString = resourceString + \".\" + info.Mapping.Resource.Group\n\t\t\t}\n\t\t\tallErrs = append(allErrs, fmt.Errorf(\"error: %s %q %v\", resourceString, info.Name, patch.Err))\n\t\t\tcontinue\n\t\t}\n\n\t\tif string(patch.Patch) == \"{}\" || len(patch.Patch) == 0 {\n\t\t\tprinter, err := o.ToPrinter(\"already paused\")\n\t\t\tif err != nil {\n\t\t\t\tallErrs = append(allErrs, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err = printer.PrintObj(info.Object, o.Out); err != nil {\n\t\t\t\tallErrs = append(allErrs, err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tobj, err := resource.NewHelper(info.Client, info.Mapping).\n\t\t\tWithFieldManager(o.fieldManager).\n\t\t\tPatch(info.Namespace, info.Name, types.StrategicMergePatchType, patch.Patch, nil)\n\t\tif err != nil {\n\t\t\tallErrs = append(allErrs, fmt.Errorf(\"failed to patch: %v\", err))\n\t\t\tcontinue\n\t\t}\n\n\t\tinfo.Refresh(obj, true)\n\t\tprinter, err := o.ToPrinter(\"paused\")\n\t\tif err != nil {\n\t\t\tallErrs = append(allErrs, err)\n\t\t\tcontinue\n\t\t}\n\t\tif err = printer.PrintObj(info.Object, o.Out); err != nil {\n\t\t\tallErrs = append(allErrs, err)\n\t\t}\n\t}\n\n\treturn utilerrors.NewAggregate(allErrs)\n}","line":{"from":132,"to":210}} {"id":100032055,"name":"NewRolloutRestartOptions","signature":"func NewRolloutRestartOptions(streams genericclioptions.IOStreams) *RestartOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_restart.go","code":"// NewRolloutRestartOptions returns an initialized RestartOptions instance\nfunc NewRolloutRestartOptions(streams genericclioptions.IOStreams) *RestartOptions {\n\treturn \u0026RestartOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"restarted\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: streams,\n\t}\n}","line":{"from":73,"to":79}} {"id":100032056,"name":"NewCmdRolloutRestart","signature":"func NewCmdRolloutRestart(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_restart.go","code":"// NewCmdRolloutRestart returns a Command instance for 'rollout restart' sub command\nfunc NewCmdRolloutRestart(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\to := NewRolloutRestartOptions(streams)\n\n\tvalidArgs := []string{\"deployment\", \"daemonset\", \"statefulset\"}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"restart RESOURCE\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Restart a resource\"),\n\t\tLong: restartLong,\n\t\tExample: restartExample,\n\t\tValidArgsFunction: completion.SpecifiedResourceTypeAndNameCompletionFunc(f, validArgs),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.RunRestart())\n\t\t},\n\t}\n\n\tusage := \"identifying the resource to get from a server.\"\n\tcmdutil.AddFilenameOptionFlags(cmd, \u0026o.FilenameOptions, usage)\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.fieldManager, \"kubectl-rollout\")\n\tcmdutil.AddLabelSelectorFlagVar(cmd, \u0026o.LabelSelector)\n\to.PrintFlags.AddFlags(cmd)\n\treturn cmd\n}","line":{"from":81,"to":107}} {"id":100032057,"name":"Complete","signature":"func (o *RestartOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_restart.go","code":"// Complete completes all the required options\nfunc (o *RestartOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\to.Resources = args\n\n\to.Restarter = polymorphichelpers.ObjectRestarterFn\n\n\tvar err error\n\to.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.ToPrinter = func(operation string) (printers.ResourcePrinter, error) {\n\t\to.PrintFlags.NamePrintFlags.Operation = operation\n\t\treturn o.PrintFlags.ToPrinter()\n\t}\n\n\to.Builder = f.NewBuilder\n\n\treturn nil\n}","line":{"from":109,"to":129}} {"id":100032058,"name":"Validate","signature":"func (o *RestartOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_restart.go","code":"func (o *RestartOptions) Validate() error {\n\tif len(o.Resources) == 0 \u0026\u0026 cmdutil.IsFilenameSliceEmpty(o.Filenames, o.Kustomize) {\n\t\treturn fmt.Errorf(\"required resource not specified\")\n\t}\n\treturn nil\n}","line":{"from":131,"to":136}} {"id":100032059,"name":"RunRestart","signature":"func (o RestartOptions) RunRestart() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_restart.go","code":"// RunRestart performs the execution of 'rollout restart' sub command\nfunc (o RestartOptions) RunRestart() error {\n\tr := o.Builder().\n\t\tWithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).\n\t\tNamespaceParam(o.Namespace).DefaultNamespace().\n\t\tFilenameParam(o.EnforceNamespace, \u0026o.FilenameOptions).\n\t\tLabelSelectorParam(o.LabelSelector).\n\t\tResourceTypeOrNameArgs(true, o.Resources...).\n\t\tContinueOnError().\n\t\tLatest().\n\t\tFlatten().\n\t\tDo()\n\tif err := r.Err(); err != nil {\n\t\treturn err\n\t}\n\n\tallErrs := []error{}\n\tinfos, err := r.Infos()\n\tif err != nil {\n\t\t// restore previous command behavior where\n\t\t// an error caused by retrieving infos due to\n\t\t// at least a single broken object did not result\n\t\t// in an immediate return, but rather an overall\n\t\t// aggregation of errors.\n\t\tallErrs = append(allErrs, err)\n\t}\n\n\tpatches := set.CalculatePatches(infos, scheme.DefaultJSONEncoder(), set.PatchFn(o.Restarter))\n\n\tif len(patches) == 0 \u0026\u0026 len(allErrs) == 0 {\n\t\tfmt.Fprintf(o.ErrOut, \"No resources found in %s namespace.\\n\", o.Namespace)\n\t\treturn nil\n\t}\n\n\tfor _, patch := range patches {\n\t\tinfo := patch.Info\n\n\t\tif patch.Err != nil {\n\t\t\tresourceString := info.Mapping.Resource.Resource\n\t\t\tif len(info.Mapping.Resource.Group) \u003e 0 {\n\t\t\t\tresourceString = resourceString + \".\" + info.Mapping.Resource.Group\n\t\t\t}\n\t\t\tallErrs = append(allErrs, fmt.Errorf(\"error: %s %q %v\", resourceString, info.Name, patch.Err))\n\t\t\tcontinue\n\t\t}\n\n\t\tif string(patch.Patch) == \"{}\" || len(patch.Patch) == 0 {\n\t\t\tallErrs = append(allErrs, fmt.Errorf(\"failed to create patch for %v: if restart has already been triggered within the past second, please wait before attempting to trigger another\", info.Name))\n\t\t\tcontinue\n\t\t}\n\n\t\tobj, err := resource.NewHelper(info.Client, info.Mapping).\n\t\t\tWithFieldManager(o.fieldManager).\n\t\t\tPatch(info.Namespace, info.Name, types.StrategicMergePatchType, patch.Patch, nil)\n\t\tif err != nil {\n\t\t\tallErrs = append(allErrs, fmt.Errorf(\"failed to patch: %v\", err))\n\t\t\tcontinue\n\t\t}\n\n\t\tinfo.Refresh(obj, true)\n\t\tprinter, err := o.ToPrinter(\"restarted\")\n\t\tif err != nil {\n\t\t\tallErrs = append(allErrs, err)\n\t\t\tcontinue\n\t\t}\n\t\tif err = printer.PrintObj(info.Object, o.Out); err != nil {\n\t\t\tallErrs = append(allErrs, err)\n\t\t}\n\t}\n\n\treturn utilerrors.NewAggregate(allErrs)\n}","line":{"from":138,"to":209}} {"id":100032060,"name":"NewRolloutResumeOptions","signature":"func NewRolloutResumeOptions(streams genericclioptions.IOStreams) *ResumeOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_resume.go","code":"// NewRolloutResumeOptions returns an initialized ResumeOptions instance\nfunc NewRolloutResumeOptions(streams genericclioptions.IOStreams) *ResumeOptions {\n\treturn \u0026ResumeOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"resumed\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: streams,\n\t}\n}","line":{"from":71,"to":77}} {"id":100032061,"name":"NewCmdRolloutResume","signature":"func NewCmdRolloutResume(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_resume.go","code":"// NewCmdRolloutResume returns a Command instance for 'rollout resume' sub command\nfunc NewCmdRolloutResume(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\to := NewRolloutResumeOptions(streams)\n\n\tvalidArgs := []string{\"deployment\"}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"resume RESOURCE\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Resume a paused resource\"),\n\t\tLong: resumeLong,\n\t\tExample: resumeExample,\n\t\tValidArgsFunction: completion.SpecifiedResourceTypeAndNameCompletionFunc(f, validArgs),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.RunResume())\n\t\t},\n\t}\n\n\tusage := \"identifying the resource to get from a server.\"\n\tcmdutil.AddFilenameOptionFlags(cmd, \u0026o.FilenameOptions, usage)\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.fieldManager, \"kubectl-rollout\")\n\tcmdutil.AddLabelSelectorFlagVar(cmd, \u0026o.LabelSelector)\n\to.PrintFlags.AddFlags(cmd)\n\treturn cmd\n}","line":{"from":79,"to":105}} {"id":100032062,"name":"Complete","signature":"func (o *ResumeOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_resume.go","code":"// Complete completes all the required options\nfunc (o *ResumeOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\to.Resources = args\n\n\to.Resumer = polymorphichelpers.ObjectResumerFn\n\n\tvar err error\n\to.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.ToPrinter = func(operation string) (printers.ResourcePrinter, error) {\n\t\to.PrintFlags.NamePrintFlags.Operation = operation\n\t\treturn o.PrintFlags.ToPrinter()\n\t}\n\n\to.Builder = f.NewBuilder\n\n\treturn nil\n}","line":{"from":107,"to":127}} {"id":100032063,"name":"Validate","signature":"func (o *ResumeOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_resume.go","code":"func (o *ResumeOptions) Validate() error {\n\tif len(o.Resources) == 0 \u0026\u0026 cmdutil.IsFilenameSliceEmpty(o.Filenames, o.Kustomize) {\n\t\treturn fmt.Errorf(\"required resource not specified\")\n\t}\n\treturn nil\n}","line":{"from":129,"to":134}} {"id":100032064,"name":"RunResume","signature":"func (o ResumeOptions) RunResume() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_resume.go","code":"// RunResume performs the execution of 'rollout resume' sub command\nfunc (o ResumeOptions) RunResume() error {\n\tr := o.Builder().\n\t\tWithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).\n\t\tNamespaceParam(o.Namespace).DefaultNamespace().\n\t\tLabelSelectorParam(o.LabelSelector).\n\t\tFilenameParam(o.EnforceNamespace, \u0026o.FilenameOptions).\n\t\tResourceTypeOrNameArgs(true, o.Resources...).\n\t\tContinueOnError().\n\t\tLatest().\n\t\tFlatten().\n\t\tDo()\n\tif err := r.Err(); err != nil {\n\t\treturn err\n\t}\n\n\tallErrs := []error{}\n\tinfos, err := r.Infos()\n\tif err != nil {\n\t\t// restore previous command behavior where\n\t\t// an error caused by retrieving infos due to\n\t\t// at least a single broken object did not result\n\t\t// in an immediate return, but rather an overall\n\t\t// aggregation of errors.\n\t\tallErrs = append(allErrs, err)\n\t}\n\n\tpatches := set.CalculatePatches(infos, scheme.DefaultJSONEncoder(), set.PatchFn(o.Resumer))\n\n\tif len(patches) == 0 \u0026\u0026 len(allErrs) == 0 {\n\t\tfmt.Fprintf(o.ErrOut, \"No resources found in %s namespace.\\n\", o.Namespace)\n\t\treturn nil\n\t}\n\n\tfor _, patch := range patches {\n\t\tinfo := patch.Info\n\n\t\tif patch.Err != nil {\n\t\t\tresourceString := info.Mapping.Resource.Resource\n\t\t\tif len(info.Mapping.Resource.Group) \u003e 0 {\n\t\t\t\tresourceString = resourceString + \".\" + info.Mapping.Resource.Group\n\t\t\t}\n\t\t\tallErrs = append(allErrs, fmt.Errorf(\"error: %s %q %v\", resourceString, info.Name, patch.Err))\n\t\t\tcontinue\n\t\t}\n\n\t\tif string(patch.Patch) == \"{}\" || len(patch.Patch) == 0 {\n\t\t\tprinter, err := o.ToPrinter(\"already resumed\")\n\t\t\tif err != nil {\n\t\t\t\tallErrs = append(allErrs, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err = printer.PrintObj(info.Object, o.Out); err != nil {\n\t\t\t\tallErrs = append(allErrs, err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tobj, err := resource.NewHelper(info.Client, info.Mapping).\n\t\t\tWithFieldManager(o.fieldManager).\n\t\t\tPatch(info.Namespace, info.Name, types.StrategicMergePatchType, patch.Patch, nil)\n\t\tif err != nil {\n\t\t\tallErrs = append(allErrs, fmt.Errorf(\"failed to patch: %v\", err))\n\t\t\tcontinue\n\t\t}\n\n\t\tinfo.Refresh(obj, true)\n\t\tprinter, err := o.ToPrinter(\"resumed\")\n\t\tif err != nil {\n\t\t\tallErrs = append(allErrs, err)\n\t\t\tcontinue\n\t\t}\n\t\tif err = printer.PrintObj(info.Object, o.Out); err != nil {\n\t\t\tallErrs = append(allErrs, err)\n\t\t}\n\t}\n\n\treturn utilerrors.NewAggregate(allErrs)\n}","line":{"from":136,"to":214}} {"id":100032065,"name":"NewRolloutStatusOptions","signature":"func NewRolloutStatusOptions(streams genericclioptions.IOStreams) *RolloutStatusOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_status.go","code":"// NewRolloutStatusOptions returns an initialized RolloutStatusOptions instance\nfunc NewRolloutStatusOptions(streams genericclioptions.IOStreams) *RolloutStatusOptions {\n\treturn \u0026RolloutStatusOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"\").WithTypeSetter(scheme.Scheme),\n\t\tFilenameOptions: \u0026resource.FilenameOptions{},\n\t\tIOStreams: streams,\n\t\tWatch: true,\n\t\tTimeout: 0,\n\t}\n}","line":{"from":83,"to":92}} {"id":100032066,"name":"NewCmdRolloutStatus","signature":"func NewCmdRolloutStatus(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_status.go","code":"// NewCmdRolloutStatus returns a Command instance for the 'rollout status' sub command\nfunc NewCmdRolloutStatus(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\to := NewRolloutStatusOptions(streams)\n\n\tvalidArgs := []string{\"deployment\", \"daemonset\", \"statefulset\"}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"status (TYPE NAME | TYPE/NAME) [flags]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Show the status of the rollout\"),\n\t\tLong: statusLong,\n\t\tExample: statusExample,\n\t\tValidArgsFunction: completion.SpecifiedResourceTypeAndNameNoRepeatCompletionFunc(f, validArgs),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\tusage := \"identifying the resource to get from a server.\"\n\tcmdutil.AddFilenameOptionFlags(cmd, o.FilenameOptions, usage)\n\tcmd.Flags().BoolVarP(\u0026o.Watch, \"watch\", \"w\", o.Watch, \"Watch the status of the rollout until it's done.\")\n\tcmd.Flags().Int64Var(\u0026o.Revision, \"revision\", o.Revision, \"Pin to a specific revision for showing its status. Defaults to 0 (last revision).\")\n\tcmd.Flags().DurationVar(\u0026o.Timeout, \"timeout\", o.Timeout, \"The length of time to wait before ending watch, zero means never. Any other values should contain a corresponding time unit (e.g. 1s, 2m, 3h).\")\n\tcmdutil.AddLabelSelectorFlagVar(cmd, \u0026o.LabelSelector)\n\n\treturn cmd\n}","line":{"from":94,"to":122}} {"id":100032067,"name":"Complete","signature":"func (o *RolloutStatusOptions) Complete(f cmdutil.Factory, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_status.go","code":"// Complete completes all the required options\nfunc (o *RolloutStatusOptions) Complete(f cmdutil.Factory, args []string) error {\n\to.Builder = f.NewBuilder\n\n\tvar err error\n\to.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.BuilderArgs = args\n\to.StatusViewerFn = polymorphichelpers.StatusViewerFn\n\n\to.DynamicClient, err = f.DynamicClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":124,"to":143}} {"id":100032068,"name":"Validate","signature":"func (o *RolloutStatusOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_status.go","code":"// Validate makes sure all the provided values for command-line options are valid\nfunc (o *RolloutStatusOptions) Validate() error {\n\tif len(o.BuilderArgs) == 0 \u0026\u0026 cmdutil.IsFilenameSliceEmpty(o.FilenameOptions.Filenames, o.FilenameOptions.Kustomize) {\n\t\treturn fmt.Errorf(\"required resource not specified\")\n\t}\n\n\tif o.Revision \u003c 0 {\n\t\treturn fmt.Errorf(\"revision must be a positive integer: %v\", o.Revision)\n\t}\n\n\treturn nil\n}","line":{"from":145,"to":156}} {"id":100032069,"name":"Run","signature":"func (o *RolloutStatusOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_status.go","code":"// Run performs the execution of 'rollout status' sub command\nfunc (o *RolloutStatusOptions) Run() error {\n\tr := o.Builder().\n\t\tWithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).\n\t\tNamespaceParam(o.Namespace).DefaultNamespace().\n\t\tLabelSelectorParam(o.LabelSelector).\n\t\tFilenameParam(o.EnforceNamespace, o.FilenameOptions).\n\t\tResourceTypeOrNameArgs(true, o.BuilderArgs...).\n\t\tContinueOnError().\n\t\tLatest().\n\t\tFlatten().\n\t\tDo()\n\n\terr := r.Err()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn r.Visit(func(info *resource.Info, _ error) error {\n\t\tmapping := info.ResourceMapping()\n\t\tstatusViewer, err := o.StatusViewerFn(mapping)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfieldSelector := fields.OneTermEqualSelector(\"metadata.name\", info.Name).String()\n\t\tlw := \u0026cache.ListWatch{\n\t\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\toptions.FieldSelector = fieldSelector\n\t\t\t\treturn o.DynamicClient.Resource(info.Mapping.Resource).Namespace(info.Namespace).List(context.TODO(), options)\n\t\t\t},\n\t\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\toptions.FieldSelector = fieldSelector\n\t\t\t\treturn o.DynamicClient.Resource(info.Mapping.Resource).Namespace(info.Namespace).Watch(context.TODO(), options)\n\t\t\t},\n\t\t}\n\n\t\t// if the rollout isn't done yet, keep watching deployment status\n\t\tctx, cancel := watchtools.ContextWithOptionalTimeout(context.Background(), o.Timeout)\n\t\tintr := interrupt.New(nil, cancel)\n\t\treturn intr.Run(func() error {\n\t\t\t_, err = watchtools.UntilWithSync(ctx, lw, \u0026unstructured.Unstructured{}, nil, func(e watch.Event) (bool, error) {\n\t\t\t\tswitch t := e.Type; t {\n\t\t\t\tcase watch.Added, watch.Modified:\n\t\t\t\t\tstatus, done, err := statusViewer.Status(e.Object.(runtime.Unstructured), o.Revision)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn false, err\n\t\t\t\t\t}\n\t\t\t\t\tfmt.Fprintf(o.Out, \"%s\", status)\n\t\t\t\t\t// Quit waiting if the rollout is done\n\t\t\t\t\tif done {\n\t\t\t\t\t\treturn true, nil\n\t\t\t\t\t}\n\n\t\t\t\t\tshouldWatch := o.Watch\n\t\t\t\t\tif !shouldWatch {\n\t\t\t\t\t\treturn true, nil\n\t\t\t\t\t}\n\n\t\t\t\t\treturn false, nil\n\n\t\t\t\tcase watch.Deleted:\n\t\t\t\t\t// We need to abort to avoid cases of recreation and not to silently watch the wrong (new) object\n\t\t\t\t\treturn true, fmt.Errorf(\"object has been deleted\")\n\n\t\t\t\tdefault:\n\t\t\t\t\treturn true, fmt.Errorf(\"internal error: unexpected event %#v\", e)\n\t\t\t\t}\n\t\t\t})\n\t\t\treturn err\n\t\t})\n\t})\n}","line":{"from":158,"to":230}} {"id":100032070,"name":"NewRolloutUndoOptions","signature":"func NewRolloutUndoOptions(streams genericclioptions.IOStreams) *UndoOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_undo.go","code":"// NewRolloutUndoOptions returns an initialized UndoOptions instance\nfunc NewRolloutUndoOptions(streams genericclioptions.IOStreams) *UndoOptions {\n\treturn \u0026UndoOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"rolled back\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: streams,\n\t\tToRevision: int64(0),\n\t}\n}","line":{"from":69,"to":76}} {"id":100032071,"name":"NewCmdRolloutUndo","signature":"func NewCmdRolloutUndo(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_undo.go","code":"// NewCmdRolloutUndo returns a Command instance for the 'rollout undo' sub command\nfunc NewCmdRolloutUndo(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\to := NewRolloutUndoOptions(streams)\n\n\tvalidArgs := []string{\"deployment\", \"daemonset\", \"statefulset\"}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"undo (TYPE NAME | TYPE/NAME) [flags]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Undo a previous rollout\"),\n\t\tLong: undoLong,\n\t\tExample: undoExample,\n\t\tValidArgsFunction: completion.SpecifiedResourceTypeAndNameCompletionFunc(f, validArgs),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.RunUndo())\n\t\t},\n\t}\n\n\tcmd.Flags().Int64Var(\u0026o.ToRevision, \"to-revision\", o.ToRevision, \"The revision to rollback to. Default to 0 (last revision).\")\n\tusage := \"identifying the resource to get from a server.\"\n\tcmdutil.AddFilenameOptionFlags(cmd, \u0026o.FilenameOptions, usage)\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmdutil.AddLabelSelectorFlagVar(cmd, \u0026o.LabelSelector)\n\to.PrintFlags.AddFlags(cmd)\n\treturn cmd\n}","line":{"from":78,"to":105}} {"id":100032072,"name":"Complete","signature":"func (o *UndoOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_undo.go","code":"// Complete completes all the required options\nfunc (o *UndoOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\to.Resources = args\n\tvar err error\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif o.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace(); err != nil {\n\t\treturn err\n\t}\n\n\to.ToPrinter = func(operation string) (printers.ResourcePrinter, error) {\n\t\to.PrintFlags.NamePrintFlags.Operation = operation\n\t\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\t\treturn o.PrintFlags.ToPrinter()\n\t}\n\n\to.RESTClientGetter = f\n\to.Builder = f.NewBuilder\n\n\treturn err\n}","line":{"from":107,"to":130}} {"id":100032073,"name":"Validate","signature":"func (o *UndoOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_undo.go","code":"func (o *UndoOptions) Validate() error {\n\tif len(o.Resources) == 0 \u0026\u0026 cmdutil.IsFilenameSliceEmpty(o.Filenames, o.Kustomize) {\n\t\treturn fmt.Errorf(\"required resource not specified\")\n\t}\n\treturn nil\n}","line":{"from":132,"to":137}} {"id":100032074,"name":"RunUndo","signature":"func (o *UndoOptions) RunUndo() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/rollout/rollout_undo.go","code":"// RunUndo performs the execution of 'rollout undo' sub command\nfunc (o *UndoOptions) RunUndo() error {\n\tr := o.Builder().\n\t\tWithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).\n\t\tNamespaceParam(o.Namespace).DefaultNamespace().\n\t\tLabelSelectorParam(o.LabelSelector).\n\t\tFilenameParam(o.EnforceNamespace, \u0026o.FilenameOptions).\n\t\tResourceTypeOrNameArgs(true, o.Resources...).\n\t\tContinueOnError().\n\t\tLatest().\n\t\tFlatten().\n\t\tDo()\n\tif err := r.Err(); err != nil {\n\t\treturn err\n\t}\n\n\terr := r.Visit(func(info *resource.Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\trollbacker, err := polymorphichelpers.RollbackerFn(o.RESTClientGetter, info.ResourceMapping())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tresult, err := rollbacker.Rollback(info.Object, nil, o.ToRevision, o.DryRunStrategy)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tprinter, err := o.ToPrinter(result)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn printer.PrintObj(info.Object, o.Out)\n\t})\n\n\treturn err\n}","line":{"from":139,"to":178}} {"id":100032075,"name":"NewRunOptions","signature":"func NewRunOptions(streams genericclioptions.IOStreams) *RunOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/run/run.go","code":"func NewRunOptions(streams genericclioptions.IOStreams) *RunOptions {\n\treturn \u0026RunOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"created\").WithTypeSetter(scheme.Scheme),\n\t\tDeleteFlags: cmddelete.NewDeleteFlags(\"to use to replace the resource.\"),\n\t\tRecordFlags: genericclioptions.NewRecordFlags(),\n\n\t\tRecorder: genericclioptions.NoopRecorder{},\n\n\t\tIOStreams: streams,\n\t}\n}","line":{"from":134,"to":144}} {"id":100032076,"name":"NewCmdRun","signature":"func NewCmdRun(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/run/run.go","code":"func NewCmdRun(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\to := NewRunOptions(streams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"run NAME --image=image [--env=\\\"key=value\\\"] [--port=port] [--dry-run=server|client] [--overrides=inline-json] [--command] -- [COMMAND] [args...]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Run a particular image on the cluster\"),\n\t\tLong: runLong,\n\t\tExample: runExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd))\n\t\t\tcmdutil.CheckErr(o.Run(f, cmd, args))\n\t\t},\n\t}\n\n\to.DeleteFlags.AddFlags(cmd)\n\to.PrintFlags.AddFlags(cmd)\n\to.RecordFlags.AddFlags(cmd)\n\n\taddRunFlags(cmd, o)\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddPodRunningTimeoutFlag(cmd, defaultPodAttachTimeout)\n\n\t// Deprecate the cascade flag. If set, it has no practical effect since the created pod has no dependents.\n\t// TODO: Remove the cascade flag from the run command in kubectl 1.29\n\tcmd.Flags().MarkDeprecated(\"cascade\", \"because it is not relevant for this command. It will be removed in version 1.29.\")\n\n\t// Deprecate and hide unused flags.\n\t// These flags are being added to the run command by DeleteFlags to support pod deletion after attach,\n\t// but they are not used if set, so they effectively do nothing.\n\t// TODO: Remove these flags from the run command in kubectl 1.29\n\tcmd.Flags().MarkDeprecated(\"filename\", \"because it is not used by this command. It will be removed in version 1.29.\")\n\tcmd.Flags().MarkDeprecated(\"force\", \"because it is not used by this command. It will be removed in version 1.29.\")\n\tcmd.Flags().MarkDeprecated(\"grace-period\", \"because it is not used by this command. It will be removed in version 1.29.\")\n\tcmd.Flags().MarkDeprecated(\"kustomize\", \"because it is not used by this command. It will be removed in version 1.29.\")\n\tcmd.Flags().MarkDeprecated(\"recursive\", \"because it is not used by this command. It will be removed in version 1.29.\")\n\tcmd.Flags().MarkDeprecated(\"timeout\", \"because it is not used by this command. It will be removed in version 1.29.\")\n\tcmd.Flags().MarkDeprecated(\"wait\", \"because it is not used by this command. It will be removed in version 1.29.\")\n\n\treturn cmd\n}","line":{"from":146,"to":186}} {"id":100032077,"name":"addRunFlags","signature":"func addRunFlags(cmd *cobra.Command, opt *RunOptions)","file":"staging/src/k8s.io/kubectl/pkg/cmd/run/run.go","code":"func addRunFlags(cmd *cobra.Command, opt *RunOptions) {\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmd.Flags().StringArray(\"annotations\", []string{}, i18n.T(\"Annotations to apply to the pod.\"))\n\tcmd.Flags().StringVar(\u0026opt.Image, \"image\", opt.Image, i18n.T(\"The image for the container to run.\"))\n\tcmd.MarkFlagRequired(\"image\")\n\tcmd.Flags().String(\"image-pull-policy\", \"\", i18n.T(\"The image pull policy for the container. If left empty, this value will not be specified by the client and defaulted by the server.\"))\n\tcmd.Flags().Bool(\"rm\", false, \"If true, delete the pod after it exits. Only valid when attaching to the container, e.g. with '--attach' or with '-i/--stdin'.\")\n\tcmd.Flags().StringArray(\"env\", []string{}, \"Environment variables to set in the container.\")\n\tcmd.Flags().StringVar(\u0026opt.Port, \"port\", opt.Port, i18n.T(\"The port that this container exposes.\"))\n\tcmd.Flags().StringP(\"labels\", \"l\", \"\", \"Comma separated labels to apply to the pod. Will override previous values.\")\n\tcmd.Flags().BoolVarP(\u0026opt.Interactive, \"stdin\", \"i\", opt.Interactive, \"Keep stdin open on the container in the pod, even if nothing is attached.\")\n\tcmd.Flags().BoolVarP(\u0026opt.TTY, \"tty\", \"t\", opt.TTY, \"Allocate a TTY for the container in the pod.\")\n\tcmd.Flags().BoolVar(\u0026opt.Attach, \"attach\", opt.Attach, \"If true, wait for the Pod to start running, and then attach to the Pod as if 'kubectl attach ...' were called. Default false, unless '-i/--stdin' is set, in which case the default is true. With '--restart=Never' the exit code of the container process is returned.\")\n\tcmd.Flags().BoolVar(\u0026opt.LeaveStdinOpen, \"leave-stdin-open\", opt.LeaveStdinOpen, \"If the pod is started in interactive mode or with stdin, leave stdin open after the first attach completes. By default, stdin will be closed after the first attach completes.\")\n\tcmd.Flags().String(\"restart\", \"Always\", i18n.T(\"The restart policy for this Pod. Legal values [Always, OnFailure, Never].\"))\n\tcmd.Flags().Bool(\"command\", false, \"If true and extra arguments are present, use them as the 'command' field in the container, rather than the 'args' field which is the default.\")\n\tcmd.Flags().BoolVar(\u0026opt.Expose, \"expose\", opt.Expose, \"If true, create a ClusterIP service associated with the pod. Requires `--port`.\")\n\tcmd.Flags().BoolVarP(\u0026opt.Quiet, \"quiet\", \"q\", opt.Quiet, \"If true, suppress prompt messages.\")\n\tcmd.Flags().BoolVar(\u0026opt.Privileged, \"privileged\", opt.Privileged, i18n.T(\"If true, run the container in privileged mode.\"))\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026opt.fieldManager, \"kubectl-run\")\n\topt.AddOverrideFlags(cmd)\n}","line":{"from":188,"to":209}} {"id":100032078,"name":"Complete","signature":"func (o *RunOptions) Complete(f cmdutil.Factory, cmd *cobra.Command) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/run/run.go","code":"func (o *RunOptions) Complete(f cmdutil.Factory, cmd *cobra.Command) error {\n\tvar err error\n\n\to.RecordFlags.Complete(cmd)\n\to.Recorder, err = o.RecordFlags.ToRecorder()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.ArgsLenAtDash = cmd.ArgsLenAtDash()\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdynamicClient, err := f.DynamicClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tattachFlag := cmd.Flags().Lookup(\"attach\")\n\tif !attachFlag.Changed \u0026\u0026 o.Interactive {\n\t\to.Attach = true\n\t}\n\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.PrintObj = func(obj runtime.Object) error {\n\t\treturn printer.PrintObj(obj, o.Out)\n\t}\n\n\tdeleteOpts, err := o.DeleteFlags.ToOptions(dynamicClient, o.IOStreams)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdeleteOpts.IgnoreNotFound = true\n\tdeleteOpts.WaitForDeletion = false\n\tdeleteOpts.GracePeriod = -1\n\tdeleteOpts.Quiet = o.Quiet\n\n\to.DeleteOptions = deleteOpts\n\n\treturn nil\n}","line":{"from":211,"to":257}} {"id":100032079,"name":"Run","signature":"func (o *RunOptions) Run(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/run/run.go","code":"func (o *RunOptions) Run(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\t// Let kubectl run follow rules for `--`, see #13004 issue\n\tif len(args) == 0 || o.ArgsLenAtDash == 0 {\n\t\treturn cmdutil.UsageErrorf(cmd, \"NAME is required for run\")\n\t}\n\n\ttimeout, err := cmdutil.GetPodRunningTimeoutFlag(cmd)\n\tif err != nil {\n\t\treturn cmdutil.UsageErrorf(cmd, \"%v\", err)\n\t}\n\n\t// validate image name\n\tif o.Image == \"\" {\n\t\treturn fmt.Errorf(\"--image is required\")\n\t}\n\n\tif !reference.ReferenceRegexp.MatchString(o.Image) {\n\t\treturn fmt.Errorf(\"Invalid image name %q: %v\", o.Image, reference.ErrReferenceInvalidFormat)\n\t}\n\n\tif o.TTY \u0026\u0026 !o.Interactive {\n\t\treturn cmdutil.UsageErrorf(cmd, \"-i/--stdin is required for containers with -t/--tty=true\")\n\t}\n\tif o.Expose \u0026\u0026 len(o.Port) == 0 {\n\t\treturn cmdutil.UsageErrorf(cmd, \"--port must be set when exposing a service\")\n\t}\n\n\to.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\trestartPolicy, err := getRestartPolicy(cmd, o.Interactive)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tremove := cmdutil.GetFlagBool(cmd, \"rm\")\n\tif !o.Attach \u0026\u0026 remove {\n\t\treturn cmdutil.UsageErrorf(cmd, \"--rm should only be used for attached containers\")\n\t}\n\n\tif o.Attach \u0026\u0026 o.DryRunStrategy != cmdutil.DryRunNone {\n\t\treturn cmdutil.UsageErrorf(cmd, \"--dry-run=[server|client] can't be used with attached containers options (--attach, --stdin, or --tty)\")\n\t}\n\n\tif err := verifyImagePullPolicy(cmd); err != nil {\n\t\treturn err\n\t}\n\n\tgenerators := generateversioned.GeneratorFn(\"run\")\n\tgenerator, found := generators[generateversioned.RunPodV1GeneratorName]\n\tif !found {\n\t\treturn cmdutil.UsageErrorf(cmd, \"generator %q not found\", generateversioned.RunPodV1GeneratorName)\n\t}\n\n\tnames := generator.ParamNames()\n\tparams := generate.MakeParams(cmd, names)\n\tparams[\"name\"] = args[0]\n\tif len(args) \u003e 1 {\n\t\tparams[\"args\"] = args[1:]\n\t}\n\n\tparams[\"annotations\"] = cmdutil.GetFlagStringArray(cmd, \"annotations\")\n\tparams[\"env\"] = cmdutil.GetFlagStringArray(cmd, \"env\")\n\n\tvar createdObjects = []*RunObject{}\n\trunObject, err := o.createGeneratedObject(f, cmd, generator, names, params, o.NewOverrider(\u0026corev1.Pod{}))\n\tif err != nil {\n\t\treturn err\n\t}\n\tcreatedObjects = append(createdObjects, runObject)\n\n\tallErrs := []error{}\n\tif o.Expose {\n\t\tserviceRunObject, err := o.generateService(f, cmd, params)\n\t\tif err != nil {\n\t\t\tallErrs = append(allErrs, err)\n\t\t} else {\n\t\t\tcreatedObjects = append(createdObjects, serviceRunObject)\n\t\t}\n\t}\n\n\tif o.Attach {\n\t\tif remove {\n\t\t\tdefer o.removeCreatedObjects(f, createdObjects)\n\t\t}\n\n\t\topts := \u0026attach.AttachOptions{\n\t\t\tStreamOptions: exec.StreamOptions{\n\t\t\t\tIOStreams: o.IOStreams,\n\t\t\t\tStdin: o.Interactive,\n\t\t\t\tTTY: o.TTY,\n\t\t\t\tQuiet: o.Quiet,\n\t\t\t},\n\t\t\tGetPodTimeout: timeout,\n\t\t\tCommandName: cmd.Parent().CommandPath() + \" attach\",\n\n\t\t\tAttach: \u0026attach.DefaultRemoteAttach{},\n\t\t}\n\t\tconfig, err := f.ToRESTConfig()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\topts.Config = config\n\t\topts.AttachFunc = attach.DefaultAttachFunc\n\n\t\tclientset, err := kubernetes.NewForConfig(config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tattachablePod, err := polymorphichelpers.AttachablePodForObjectFn(f, runObject.Object, opts.GetPodTimeout)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = handleAttachPod(f, clientset.CoreV1(), attachablePod.Namespace, attachablePod.Name, opts)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar pod *corev1.Pod\n\t\twaitForExitCode := !o.LeaveStdinOpen \u0026\u0026 (restartPolicy == corev1.RestartPolicyNever || restartPolicy == corev1.RestartPolicyOnFailure)\n\t\tif waitForExitCode {\n\t\t\t// we need different exit condition depending on restart policy\n\t\t\t// for Never it can either fail or succeed, for OnFailure only\n\t\t\t// success matters\n\t\t\texitCondition := podCompleted\n\t\t\tif restartPolicy == corev1.RestartPolicyOnFailure {\n\t\t\t\texitCondition = podSucceeded\n\t\t\t}\n\t\t\tpod, err = waitForPod(clientset.CoreV1(), attachablePod.Namespace, attachablePod.Name, opts.GetPodTimeout, exitCondition)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\t// after removal is done, return successfully if we are not interested in the exit code\n\t\t\treturn nil\n\t\t}\n\n\t\tswitch pod.Status.Phase {\n\t\tcase corev1.PodSucceeded:\n\t\t\treturn nil\n\t\tcase corev1.PodFailed:\n\t\t\tunknownRcErr := fmt.Errorf(\"pod %s/%s failed with unknown exit code\", pod.Namespace, pod.Name)\n\t\t\tif len(pod.Status.ContainerStatuses) == 0 || pod.Status.ContainerStatuses[0].State.Terminated == nil {\n\t\t\t\treturn unknownRcErr\n\t\t\t}\n\t\t\t// assume here that we have at most one status because kubectl-run only creates one container per pod\n\t\t\trc := pod.Status.ContainerStatuses[0].State.Terminated.ExitCode\n\t\t\tif rc == 0 {\n\t\t\t\treturn unknownRcErr\n\t\t\t}\n\t\t\treturn uexec.CodeExitError{\n\t\t\t\tErr: fmt.Errorf(\"pod %s/%s terminated (%s)\\n%s\", pod.Namespace, pod.Name, pod.Status.ContainerStatuses[0].State.Terminated.Reason, pod.Status.ContainerStatuses[0].State.Terminated.Message),\n\t\t\t\tCode: int(rc),\n\t\t\t}\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"pod %s/%s left in phase %s\", pod.Namespace, pod.Name, pod.Status.Phase)\n\t\t}\n\n\t}\n\tif runObject != nil {\n\t\tif err := o.PrintObj(runObject.Object); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn utilerrors.NewAggregate(allErrs)\n}","line":{"from":259,"to":427}} {"id":100032080,"name":"removeCreatedObjects","signature":"func (o *RunOptions) removeCreatedObjects(f cmdutil.Factory, createdObjects []*RunObject) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/run/run.go","code":"func (o *RunOptions) removeCreatedObjects(f cmdutil.Factory, createdObjects []*RunObject) error {\n\tfor _, obj := range createdObjects {\n\t\tnamespace, err := metadataAccessor.Namespace(obj.Object)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar name string\n\t\tname, err = metadataAccessor.Name(obj.Object)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tr := f.NewBuilder().\n\t\t\tWithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).\n\t\t\tContinueOnError().\n\t\t\tNamespaceParam(namespace).DefaultNamespace().\n\t\t\tResourceNames(obj.Mapping.Resource.Resource+\".\"+obj.Mapping.Resource.Group, name).\n\t\t\tFlatten().\n\t\t\tDo()\n\t\tif err := o.DeleteOptions.DeleteResult(r); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":429,"to":453}} {"id":100032081,"name":"waitForPod","signature":"func waitForPod(podClient corev1client.PodsGetter, ns, name string, timeout time.Duration, exitCondition watchtools.ConditionFunc) (*corev1.Pod, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/run/run.go","code":"// waitForPod watches the given pod until the exitCondition is true\nfunc waitForPod(podClient corev1client.PodsGetter, ns, name string, timeout time.Duration, exitCondition watchtools.ConditionFunc) (*corev1.Pod, error) {\n\tctx, cancel := watchtools.ContextWithOptionalTimeout(context.Background(), timeout)\n\tdefer cancel()\n\n\tfieldSelector := fields.OneTermEqualSelector(\"metadata.name\", name).String()\n\tlw := \u0026cache.ListWatch{\n\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\toptions.FieldSelector = fieldSelector\n\t\t\treturn podClient.Pods(ns).List(context.TODO(), options)\n\t\t},\n\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\toptions.FieldSelector = fieldSelector\n\t\t\treturn podClient.Pods(ns).Watch(context.TODO(), options)\n\t\t},\n\t}\n\n\tintr := interrupt.New(nil, cancel)\n\tvar result *corev1.Pod\n\terr := intr.Run(func() error {\n\t\tev, err := watchtools.UntilWithSync(ctx, lw, \u0026corev1.Pod{}, nil, exitCondition)\n\t\tif ev != nil {\n\t\t\tresult = ev.Object.(*corev1.Pod)\n\t\t}\n\t\treturn err\n\t})\n\n\treturn result, err\n}","line":{"from":455,"to":483}} {"id":100032082,"name":"handleAttachPod","signature":"func handleAttachPod(f cmdutil.Factory, podClient corev1client.PodsGetter, ns, name string, opts *attach.AttachOptions) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/run/run.go","code":"func handleAttachPod(f cmdutil.Factory, podClient corev1client.PodsGetter, ns, name string, opts *attach.AttachOptions) error {\n\tpod, err := waitForPod(podClient, ns, name, opts.GetPodTimeout, podRunningAndReady)\n\tif err != nil \u0026\u0026 err != ErrPodCompleted {\n\t\treturn err\n\t}\n\n\tif pod.Status.Phase == corev1.PodSucceeded || pod.Status.Phase == corev1.PodFailed {\n\t\treturn logOpts(f, pod, opts)\n\t}\n\n\topts.Pod = pod\n\topts.PodName = name\n\topts.Namespace = ns\n\n\tif opts.AttachFunc == nil {\n\t\topts.AttachFunc = attach.DefaultAttachFunc\n\t}\n\n\tif err := opts.Run(); err != nil {\n\t\tfmt.Fprintf(opts.ErrOut, \"warning: couldn't attach to pod/%s, falling back to streaming logs: %v\\n\", name, err)\n\t\treturn logOpts(f, pod, opts)\n\t}\n\treturn nil\n}","line":{"from":485,"to":508}} {"id":100032083,"name":"logOpts","signature":"func logOpts(restClientGetter genericclioptions.RESTClientGetter, pod *corev1.Pod, opts *attach.AttachOptions) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/run/run.go","code":"// logOpts logs output from opts to the pods log.\nfunc logOpts(restClientGetter genericclioptions.RESTClientGetter, pod *corev1.Pod, opts *attach.AttachOptions) error {\n\tctrName, err := opts.GetContainerName(pod)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trequests, err := polymorphichelpers.LogsForObjectFn(restClientGetter, pod, \u0026corev1.PodLogOptions{Container: ctrName}, opts.GetPodTimeout, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, request := range requests {\n\t\tif err := logs.DefaultConsumeRequest(request, opts.Out); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":510,"to":528}} {"id":100032084,"name":"getRestartPolicy","signature":"func getRestartPolicy(cmd *cobra.Command, interactive bool) (corev1.RestartPolicy, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/run/run.go","code":"func getRestartPolicy(cmd *cobra.Command, interactive bool) (corev1.RestartPolicy, error) {\n\trestart := cmdutil.GetFlagString(cmd, \"restart\")\n\tif len(restart) == 0 {\n\t\tif interactive {\n\t\t\treturn corev1.RestartPolicyOnFailure, nil\n\t\t}\n\t\treturn corev1.RestartPolicyAlways, nil\n\t}\n\tswitch corev1.RestartPolicy(restart) {\n\tcase corev1.RestartPolicyAlways:\n\t\treturn corev1.RestartPolicyAlways, nil\n\tcase corev1.RestartPolicyOnFailure:\n\t\treturn corev1.RestartPolicyOnFailure, nil\n\tcase corev1.RestartPolicyNever:\n\t\treturn corev1.RestartPolicyNever, nil\n\t}\n\treturn \"\", cmdutil.UsageErrorf(cmd, \"invalid restart policy: %s\", restart)\n}","line":{"from":530,"to":547}} {"id":100032085,"name":"verifyImagePullPolicy","signature":"func verifyImagePullPolicy(cmd *cobra.Command) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/run/run.go","code":"func verifyImagePullPolicy(cmd *cobra.Command) error {\n\tpullPolicy := cmdutil.GetFlagString(cmd, \"image-pull-policy\")\n\tswitch corev1.PullPolicy(pullPolicy) {\n\tcase corev1.PullAlways, corev1.PullIfNotPresent, corev1.PullNever:\n\t\treturn nil\n\tcase \"\":\n\t\treturn nil\n\t}\n\treturn cmdutil.UsageErrorf(cmd, \"invalid image pull policy: %s\", pullPolicy)\n}","line":{"from":549,"to":558}} {"id":100032086,"name":"generateService","signature":"func (o *RunOptions) generateService(f cmdutil.Factory, cmd *cobra.Command, paramsIn map[string]interface{}) (*RunObject, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/run/run.go","code":"func (o *RunOptions) generateService(f cmdutil.Factory, cmd *cobra.Command, paramsIn map[string]interface{}) (*RunObject, error) {\n\tgenerators := generateversioned.GeneratorFn(\"expose\")\n\tgenerator, found := generators[generateversioned.ServiceV2GeneratorName]\n\tif !found {\n\t\treturn nil, fmt.Errorf(\"missing service generator: %s\", generateversioned.ServiceV2GeneratorName)\n\t}\n\tnames := generator.ParamNames()\n\n\tparams := map[string]interface{}{}\n\tfor key, value := range paramsIn {\n\t\t_, isString := value.(string)\n\t\tif isString {\n\t\t\tparams[key] = value\n\t\t}\n\t}\n\n\tname, found := params[\"name\"]\n\tif !found || len(name.(string)) == 0 {\n\t\treturn nil, fmt.Errorf(\"name is a required parameter\")\n\t}\n\tselector, found := params[\"labels\"]\n\tif !found || len(selector.(string)) == 0 {\n\t\tselector = fmt.Sprintf(\"run=%s\", name.(string))\n\t}\n\tparams[\"selector\"] = selector\n\n\tif defaultName, found := params[\"default-name\"]; !found || len(defaultName.(string)) == 0 {\n\t\tparams[\"default-name\"] = name\n\t}\n\n\trunObject, err := o.createGeneratedObject(f, cmd, generator, names, params, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := o.PrintObj(runObject.Object); err != nil {\n\t\treturn nil, err\n\t}\n\t// separate yaml objects\n\tif o.PrintFlags.OutputFormat != nil \u0026\u0026 *o.PrintFlags.OutputFormat == \"yaml\" {\n\t\tfmt.Fprintln(o.Out, \"---\")\n\t}\n\n\treturn runObject, nil\n}","line":{"from":560,"to":604}} {"id":100032087,"name":"createGeneratedObject","signature":"func (o *RunOptions) createGeneratedObject(f cmdutil.Factory, cmd *cobra.Command, generator generate.Generator, names []generate.GeneratorParam, params map[string]interface{}, overrider *cmdutil.Overrider) (*RunObject, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/run/run.go","code":"func (o *RunOptions) createGeneratedObject(f cmdutil.Factory, cmd *cobra.Command, generator generate.Generator, names []generate.GeneratorParam, params map[string]interface{}, overrider *cmdutil.Overrider) (*RunObject, error) {\n\terr := generate.ValidateParams(names, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// TODO: Validate flag usage against selected generator. More tricky since --expose was added.\n\tobj, err := generator.Generate(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmapper, err := f.ToRESTMapper()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// run has compiled knowledge of the thing is creating\n\tgvks, _, err := scheme.Scheme.ObjectKinds(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmapping, err := mapper.RESTMapping(gvks[0].GroupKind(), gvks[0].Version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif overrider != nil {\n\t\tobj, err = overrider.Apply(obj)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif err := o.Recorder.Record(obj); err != nil {\n\t\tklog.V(4).Infof(\"error recording current command: %v\", err)\n\t}\n\n\tactualObj := obj\n\tif o.DryRunStrategy != cmdutil.DryRunClient {\n\t\tif err := util.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), obj, scheme.DefaultJSONEncoder()); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tclient, err := f.ClientForMapping(mapping)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tactualObj, err = resource.\n\t\t\tNewHelper(client, mapping).\n\t\t\tDryRun(o.DryRunStrategy == cmdutil.DryRunServer).\n\t\t\tWithFieldManager(o.fieldManager).\n\t\t\tCreate(o.Namespace, false, obj)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tif meta, err := meta.Accessor(actualObj); err == nil \u0026\u0026 o.EnforceNamespace {\n\t\t\tmeta.SetNamespace(o.Namespace)\n\t\t}\n\t}\n\n\treturn \u0026RunObject{\n\t\tObject: actualObj,\n\t\tMapping: mapping,\n\t}, nil\n}","line":{"from":606,"to":670}} {"id":100032088,"name":"podCompleted","signature":"func podCompleted(event watch.Event) (bool, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/run/run.go","code":"// podCompleted returns true if the pod has run to completion, false if the pod has not yet\n// reached running state, or an error in any other case.\nfunc podCompleted(event watch.Event) (bool, error) {\n\tswitch event.Type {\n\tcase watch.Deleted:\n\t\treturn false, errors.NewNotFound(schema.GroupResource{Resource: \"pods\"}, \"\")\n\t}\n\tswitch t := event.Object.(type) {\n\tcase *corev1.Pod:\n\t\tswitch t.Status.Phase {\n\t\tcase corev1.PodFailed, corev1.PodSucceeded:\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}","line":{"from":676,"to":691}} {"id":100032089,"name":"podSucceeded","signature":"func podSucceeded(event watch.Event) (bool, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/run/run.go","code":"// podSucceeded returns true if the pod has run to completion, false if the pod has not yet\n// reached running state, or an error in any other case.\nfunc podSucceeded(event watch.Event) (bool, error) {\n\tswitch event.Type {\n\tcase watch.Deleted:\n\t\treturn false, errors.NewNotFound(schema.GroupResource{Resource: \"pods\"}, \"\")\n\t}\n\tswitch t := event.Object.(type) {\n\tcase *corev1.Pod:\n\t\treturn t.Status.Phase == corev1.PodSucceeded, nil\n\t}\n\treturn false, nil\n}","line":{"from":693,"to":705}} {"id":100032090,"name":"podRunningAndReady","signature":"func podRunningAndReady(event watch.Event) (bool, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/run/run.go","code":"// podRunningAndReady returns true if the pod is running and ready, false if the pod has not\n// yet reached those states, returns ErrPodCompleted if the pod has run to completion, or\n// an error in any other case.\nfunc podRunningAndReady(event watch.Event) (bool, error) {\n\tswitch event.Type {\n\tcase watch.Deleted:\n\t\treturn false, errors.NewNotFound(schema.GroupResource{Resource: \"pods\"}, \"\")\n\t}\n\tswitch t := event.Object.(type) {\n\tcase *corev1.Pod:\n\t\tswitch t.Status.Phase {\n\t\tcase corev1.PodFailed, corev1.PodSucceeded:\n\t\t\treturn false, ErrPodCompleted\n\t\tcase corev1.PodRunning:\n\t\t\tconditions := t.Status.Conditions\n\t\t\tif conditions == nil {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\tfor i := range conditions {\n\t\t\t\tif conditions[i].Type == corev1.PodReady \u0026\u0026\n\t\t\t\t\tconditions[i].Status == corev1.ConditionTrue {\n\t\t\t\t\treturn true, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false, nil\n}","line":{"from":707,"to":734}} {"id":100032091,"name":"NewScaleOptions","signature":"func NewScaleOptions(ioStreams genericclioptions.IOStreams) *ScaleOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/scale/scale.go","code":"func NewScaleOptions(ioStreams genericclioptions.IOStreams) *ScaleOptions {\n\treturn \u0026ScaleOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"scaled\"),\n\t\tRecordFlags: genericclioptions.NewRecordFlags(),\n\t\tCurrentReplicas: -1,\n\t\tRecorder: genericclioptions.NoopRecorder{},\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":94,"to":102}} {"id":100032092,"name":"NewCmdScale","signature":"func NewCmdScale(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/scale/scale.go","code":"// NewCmdScale returns a cobra command with the appropriate configuration and flags to run scale\nfunc NewCmdScale(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewScaleOptions(ioStreams)\n\n\tvalidArgs := []string{\"deployment\", \"replicaset\", \"replicationcontroller\", \"statefulset\"}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"scale [--resource-version=version] [--current-replicas=count] --replicas=COUNT (-f FILENAME | TYPE NAME)\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Set a new size for a deployment, replica set, or replication controller\"),\n\t\tLong: scaleLong,\n\t\tExample: scaleExample,\n\t\tValidArgsFunction: completion.SpecifiedResourceTypeAndNameCompletionFunc(f, validArgs),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.RunScale())\n\t\t},\n\t}\n\n\to.RecordFlags.AddFlags(cmd)\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmd.Flags().BoolVar(\u0026o.All, \"all\", o.All, \"Select all resources in the namespace of the specified resource types\")\n\tcmd.Flags().StringVar(\u0026o.ResourceVersion, \"resource-version\", o.ResourceVersion, i18n.T(\"Precondition for resource version. Requires that the current resource version match this value in order to scale.\"))\n\tcmd.Flags().IntVar(\u0026o.CurrentReplicas, \"current-replicas\", o.CurrentReplicas, \"Precondition for current size. Requires that the current size of the resource match this value in order to scale. -1 (default) for no condition.\")\n\tcmd.Flags().IntVar(\u0026o.Replicas, \"replicas\", o.Replicas, \"The new desired number of replicas. Required.\")\n\tcmd.MarkFlagRequired(\"replicas\")\n\tcmd.Flags().DurationVar(\u0026o.Timeout, \"timeout\", 0, \"The length of time to wait before giving up on a scale operation, zero means don't wait. Any other values should contain a corresponding time unit (e.g. 1s, 2m, 3h).\")\n\tcmdutil.AddFilenameOptionFlags(cmd, \u0026o.FilenameOptions, \"identifying the resource to set a new size\")\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmdutil.AddLabelSelectorFlagVar(cmd, \u0026o.Selector)\n\treturn cmd\n}","line":{"from":104,"to":137}} {"id":100032093,"name":"Complete","signature":"func (o *ScaleOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/scale/scale.go","code":"func (o *ScaleOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\to.RecordFlags.Complete(cmd)\n\to.Recorder, err = o.RecordFlags.ToRecorder()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.dryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.dryRunStrategy)\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.PrintObj = printer.PrintObj\n\n\to.namespace, o.enforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.builder = f.NewBuilder()\n\to.args = args\n\to.shortOutput = cmdutil.GetFlagString(cmd, \"output\") == \"name\"\n\to.clientSet, err = f.KubernetesClientSet()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.scaler, err = scaler(f)\n\tif err != nil {\n\t\treturn err\n\t}\n\to.unstructuredClientForMapping = f.UnstructuredClientForMapping\n\to.parent = cmd.Parent().Name()\n\n\treturn nil\n}","line":{"from":139,"to":177}} {"id":100032094,"name":"Validate","signature":"func (o *ScaleOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/scale/scale.go","code":"func (o *ScaleOptions) Validate() error {\n\tif o.Replicas \u003c 0 {\n\t\treturn fmt.Errorf(\"The --replicas=COUNT flag is required, and COUNT must be greater than or equal to 0\")\n\t}\n\n\tif o.CurrentReplicas \u003c -1 {\n\t\treturn fmt.Errorf(\"The --current-replicas must specify an integer of -1 or greater\")\n\t}\n\n\treturn nil\n}","line":{"from":179,"to":189}} {"id":100032095,"name":"RunScale","signature":"func (o *ScaleOptions) RunScale() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/scale/scale.go","code":"// RunScale executes the scaling\nfunc (o *ScaleOptions) RunScale() error {\n\tr := o.builder.\n\t\tUnstructured().\n\t\tContinueOnError().\n\t\tNamespaceParam(o.namespace).DefaultNamespace().\n\t\tFilenameParam(o.enforceNamespace, \u0026o.FilenameOptions).\n\t\tResourceTypeOrNameArgs(o.All, o.args...).\n\t\tFlatten().\n\t\tLabelSelectorParam(o.Selector).\n\t\tDo()\n\terr := r.Err()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// We don't immediately return infoErr if it is not nil.\n\t// Because we want to proceed for other valid resources and\n\t// at the end of the function, we'll return this\n\t// to show invalid resources to the user.\n\tinfos, infoErr := r.Infos()\n\n\tif len(o.ResourceVersion) != 0 \u0026\u0026 len(infos) \u003e 1 {\n\t\treturn fmt.Errorf(\"cannot use --resource-version with multiple resources\")\n\t}\n\n\t// only set a precondition if the user has requested one. A nil precondition means we can do a blind update, so\n\t// we avoid a Scale GET that may or may not succeed\n\tvar precondition *scale.ScalePrecondition\n\tif o.CurrentReplicas != -1 || len(o.ResourceVersion) \u003e 0 {\n\t\tprecondition = \u0026scale.ScalePrecondition{Size: o.CurrentReplicas, ResourceVersion: o.ResourceVersion}\n\t}\n\tretry := scale.NewRetryParams(1*time.Second, 5*time.Minute)\n\n\tvar waitForReplicas *scale.RetryParams\n\tif o.Timeout != 0 \u0026\u0026 o.dryRunStrategy == cmdutil.DryRunNone {\n\t\twaitForReplicas = scale.NewRetryParams(1*time.Second, o.Timeout)\n\t}\n\n\tif len(infos) == 0 {\n\t\treturn fmt.Errorf(\"no objects passed to scale\")\n\t}\n\n\tfor _, info := range infos {\n\t\tmapping := info.ResourceMapping()\n\t\tif o.dryRunStrategy == cmdutil.DryRunClient {\n\t\t\tif err := o.PrintObj(info.Object, o.Out); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := o.scaler.Scale(info.Namespace, info.Name, uint(o.Replicas), precondition, retry, waitForReplicas, mapping.Resource, o.dryRunStrategy == cmdutil.DryRunServer); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// if the recorder makes a change, compute and create another patch\n\t\tif mergePatch, err := o.Recorder.MakeRecordMergePatch(info.Object); err != nil {\n\t\t\tklog.V(4).Infof(\"error recording current command: %v\", err)\n\t\t} else if len(mergePatch) \u003e 0 {\n\t\t\tclient, err := o.unstructuredClientForMapping(mapping)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thelper := resource.NewHelper(client, mapping)\n\t\t\tif _, err := helper.Patch(info.Namespace, info.Name, types.MergePatchType, mergePatch, nil); err != nil {\n\t\t\t\tklog.V(4).Infof(\"error recording reason: %v\", err)\n\t\t\t}\n\t\t}\n\n\t\terr := o.PrintObj(info.Object, o.Out)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn infoErr\n}","line":{"from":191,"to":268}} {"id":100032096,"name":"scaler","signature":"func scaler(f cmdutil.Factory) (scale.Scaler, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/scale/scale.go","code":"func scaler(f cmdutil.Factory) (scale.Scaler, error) {\n\tscalesGetter, err := cmdutil.ScaleClientFn(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn scale.NewScaler(scalesGetter), nil\n}","line":{"from":270,"to":277}} {"id":100032097,"name":"IsEnvironmentArgument","signature":"func IsEnvironmentArgument(s string) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/env/env_parse.go","code":"// IsEnvironmentArgument checks whether a string is an environment argument, that is, whether it matches the \"anycharacters=anycharacters\" pattern.\nfunc IsEnvironmentArgument(s string) bool {\n\treturn argumentEnvironment.MatchString(s)\n}","line":{"from":33,"to":36}} {"id":100032098,"name":"SplitEnvironmentFromResources","signature":"func SplitEnvironmentFromResources(args []string) (resources, envArgs []string, ok bool)","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/env/env_parse.go","code":"// SplitEnvironmentFromResources separates resources from environment arguments.\n// Resources must come first. Arguments may have the \"DASH-\" syntax.\nfunc SplitEnvironmentFromResources(args []string) (resources, envArgs []string, ok bool) {\n\tfirst := true\n\tfor _, s := range args {\n\t\t// this method also has to understand env removal syntax, i.e. KEY-\n\t\tisEnv := IsEnvironmentArgument(s) || strings.HasSuffix(s, \"-\")\n\t\tswitch {\n\t\tcase first \u0026\u0026 isEnv:\n\t\t\tfirst = false\n\t\t\tfallthrough\n\t\tcase !first \u0026\u0026 isEnv:\n\t\t\tenvArgs = append(envArgs, s)\n\t\tcase first \u0026\u0026 !isEnv:\n\t\t\tresources = append(resources, s)\n\t\tcase !first \u0026\u0026 !isEnv:\n\t\t\treturn nil, nil, false\n\t\t}\n\t}\n\treturn resources, envArgs, true\n}","line":{"from":38,"to":58}} {"id":100032099,"name":"parseIntoEnvVar","signature":"func parseIntoEnvVar(spec []string, defaultReader io.Reader, envVarType string) ([]v1.EnvVar, []string, bool, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/env/env_parse.go","code":"// parseIntoEnvVar parses the list of key-value pairs into kubernetes EnvVar.\n// envVarType is for making errors more specific to user intentions.\nfunc parseIntoEnvVar(spec []string, defaultReader io.Reader, envVarType string) ([]v1.EnvVar, []string, bool, error) {\n\tenv := []v1.EnvVar{}\n\texists := sets.NewString()\n\tvar remove []string\n\tusedStdin := false\n\tfor _, envSpec := range spec {\n\t\tswitch {\n\t\tcase envSpec == \"-\":\n\t\t\tif defaultReader == nil {\n\t\t\t\treturn nil, nil, usedStdin, fmt.Errorf(\"when '-' is used, STDIN must be open\")\n\t\t\t}\n\t\t\tfileEnv, err := readEnv(defaultReader, envVarType)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, usedStdin, err\n\t\t\t}\n\t\t\tenv = append(env, fileEnv...)\n\t\t\tusedStdin = true\n\t\tcase strings.Contains(envSpec, \"=\"):\n\t\t\tparts := strings.SplitN(envSpec, \"=\", 2)\n\t\t\tif len(parts) != 2 {\n\t\t\t\treturn nil, nil, usedStdin, fmt.Errorf(\"invalid %s: %v\", envVarType, envSpec)\n\t\t\t}\n\t\t\tif errs := validation.IsEnvVarName(parts[0]); len(errs) != 0 {\n\t\t\t\treturn nil, nil, usedStdin, fmt.Errorf(\"%q is not a valid key name: %s\", parts[0], strings.Join(errs, \";\"))\n\t\t\t}\n\t\t\texists.Insert(parts[0])\n\t\t\tenv = append(env, v1.EnvVar{\n\t\t\t\tName: parts[0],\n\t\t\t\tValue: parts[1],\n\t\t\t})\n\t\tcase strings.HasSuffix(envSpec, \"-\"):\n\t\t\tremove = append(remove, envSpec[:len(envSpec)-1])\n\t\tdefault:\n\t\t\treturn nil, nil, usedStdin, fmt.Errorf(\"unknown %s: %v\", envVarType, envSpec)\n\t\t}\n\t}\n\tfor _, removeLabel := range remove {\n\t\tif _, found := exists[removeLabel]; found {\n\t\t\treturn nil, nil, usedStdin, fmt.Errorf(\"can not both modify and remove the same %s in the same command\", envVarType)\n\t\t}\n\t}\n\treturn env, remove, usedStdin, nil\n}","line":{"from":60,"to":104}} {"id":100032100,"name":"ParseEnv","signature":"func ParseEnv(spec []string, defaultReader io.Reader) ([]v1.EnvVar, []string, bool, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/env/env_parse.go","code":"// ParseEnv parses the elements of the first argument looking for environment variables in key=value form and, if one of those values is \"-\", it also scans the reader and returns true for its third return value.\n// The same environment variable cannot be both modified and removed in the same command.\nfunc ParseEnv(spec []string, defaultReader io.Reader) ([]v1.EnvVar, []string, bool, error) {\n\treturn parseIntoEnvVar(spec, defaultReader, \"environment variable\")\n}","line":{"from":106,"to":110}} {"id":100032101,"name":"readEnv","signature":"func readEnv(r io.Reader, envVarType string) ([]v1.EnvVar, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/env/env_parse.go","code":"func readEnv(r io.Reader, envVarType string) ([]v1.EnvVar, error) {\n\tenv := []v1.EnvVar{}\n\tscanner := bufio.NewScanner(r)\n\tfor scanner.Scan() {\n\t\tenvSpec := scanner.Text()\n\t\tif pos := strings.Index(envSpec, \"#\"); pos != -1 {\n\t\t\tenvSpec = envSpec[:pos]\n\t\t}\n\n\t\tif strings.Contains(envSpec, \"=\") {\n\t\t\tparts := strings.SplitN(envSpec, \"=\", 2)\n\t\t\tif len(parts) != 2 {\n\t\t\t\treturn nil, fmt.Errorf(\"invalid %s: %v\", envVarType, envSpec)\n\t\t\t}\n\t\t\tenv = append(env, v1.EnvVar{\n\t\t\t\tName: parts[0],\n\t\t\t\tValue: parts[1],\n\t\t\t})\n\t\t}\n\t}\n\n\tif err := scanner.Err(); err != nil \u0026\u0026 err != io.EOF {\n\t\treturn nil, err\n\t}\n\n\treturn env, nil\n}","line":{"from":112,"to":138}} {"id":100032102,"name":"NewResourceStore","signature":"func NewResourceStore() *ResourceStore","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/env/env_resolve.go","code":"// NewResourceStore returns a pointer to a new resource store data structure.\nfunc NewResourceStore() *ResourceStore {\n\treturn \u0026ResourceStore{\n\t\tSecretStore: make(map[string]*corev1.Secret),\n\t\tConfigMapStore: make(map[string]*corev1.ConfigMap),\n\t}\n}","line":{"from":42,"to":48}} {"id":100032103,"name":"getSecretRefValue","signature":"func getSecretRefValue(client kubernetes.Interface, namespace string, store *ResourceStore, secretSelector *corev1.SecretKeySelector) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/env/env_resolve.go","code":"// getSecretRefValue returns the value of a secret in the supplied namespace\nfunc getSecretRefValue(client kubernetes.Interface, namespace string, store *ResourceStore, secretSelector *corev1.SecretKeySelector) (string, error) {\n\tsecret, ok := store.SecretStore[secretSelector.Name]\n\tif !ok {\n\t\tvar err error\n\t\tsecret, err = client.CoreV1().Secrets(namespace).Get(context.TODO(), secretSelector.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tstore.SecretStore[secretSelector.Name] = secret\n\t}\n\tif data, ok := secret.Data[secretSelector.Key]; ok {\n\t\treturn string(data), nil\n\t}\n\treturn \"\", fmt.Errorf(\"key %s not found in secret %s\", secretSelector.Key, secretSelector.Name)\n\n}","line":{"from":50,"to":66}} {"id":100032104,"name":"getConfigMapRefValue","signature":"func getConfigMapRefValue(client kubernetes.Interface, namespace string, store *ResourceStore, configMapSelector *corev1.ConfigMapKeySelector) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/env/env_resolve.go","code":"// getConfigMapRefValue returns the value of a configmap in the supplied namespace\nfunc getConfigMapRefValue(client kubernetes.Interface, namespace string, store *ResourceStore, configMapSelector *corev1.ConfigMapKeySelector) (string, error) {\n\tconfigMap, ok := store.ConfigMapStore[configMapSelector.Name]\n\tif !ok {\n\t\tvar err error\n\t\tconfigMap, err = client.CoreV1().ConfigMaps(namespace).Get(context.TODO(), configMapSelector.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tstore.ConfigMapStore[configMapSelector.Name] = configMap\n\t}\n\tif data, ok := configMap.Data[configMapSelector.Key]; ok {\n\t\treturn string(data), nil\n\t}\n\treturn \"\", fmt.Errorf(\"key %s not found in config map %s\", configMapSelector.Key, configMapSelector.Name)\n}","line":{"from":68,"to":83}} {"id":100032105,"name":"getFieldRef","signature":"func getFieldRef(obj runtime.Object, from *corev1.EnvVarSource) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/env/env_resolve.go","code":"// getFieldRef returns the value of the supplied path in the given object\nfunc getFieldRef(obj runtime.Object, from *corev1.EnvVarSource) (string, error) {\n\treturn extractFieldPathAsString(obj, from.FieldRef.FieldPath)\n}","line":{"from":85,"to":88}} {"id":100032106,"name":"extractFieldPathAsString","signature":"func extractFieldPathAsString(obj interface{}, fieldPath string) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/env/env_resolve.go","code":"// extractFieldPathAsString extracts the field from the given object\n// and returns it as a string. The object must be a pointer to an\n// API type.\nfunc extractFieldPathAsString(obj interface{}, fieldPath string) (string, error) {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn \"\", nil\n\t}\n\n\tif path, subscript, ok := splitMaybeSubscriptedPath(fieldPath); ok {\n\t\tswitch path {\n\t\tcase \"metadata.annotations\":\n\t\t\tif errs := validation.IsQualifiedName(strings.ToLower(subscript)); len(errs) != 0 {\n\t\t\t\treturn \"\", fmt.Errorf(\"invalid key subscript in %s: %s\", fieldPath, strings.Join(errs, \";\"))\n\t\t\t}\n\t\t\treturn accessor.GetAnnotations()[subscript], nil\n\t\tcase \"metadata.labels\":\n\t\t\tif errs := validation.IsQualifiedName(subscript); len(errs) != 0 {\n\t\t\t\treturn \"\", fmt.Errorf(\"invalid key subscript in %s: %s\", fieldPath, strings.Join(errs, \";\"))\n\t\t\t}\n\t\t\treturn accessor.GetLabels()[subscript], nil\n\t\tdefault:\n\t\t\treturn \"\", fmt.Errorf(\"fieldPath %q does not support subscript\", fieldPath)\n\t\t}\n\t}\n\n\tswitch fieldPath {\n\tcase \"metadata.annotations\":\n\t\treturn formatMap(accessor.GetAnnotations()), nil\n\tcase \"metadata.labels\":\n\t\treturn formatMap(accessor.GetLabels()), nil\n\tcase \"metadata.name\":\n\t\treturn accessor.GetName(), nil\n\tcase \"metadata.namespace\":\n\t\treturn accessor.GetNamespace(), nil\n\tcase \"metadata.uid\":\n\t\treturn string(accessor.GetUID()), nil\n\t}\n\n\treturn \"\", fmt.Errorf(\"unsupported fieldPath: %v\", fieldPath)\n}","line":{"from":90,"to":130}} {"id":100032107,"name":"splitMaybeSubscriptedPath","signature":"func splitMaybeSubscriptedPath(fieldPath string) (string, string, bool)","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/env/env_resolve.go","code":"// splitMaybeSubscriptedPath checks whether the specified fieldPath is\n// subscripted, and\n// - if yes, this function splits the fieldPath into path and subscript, and\n// returns (path, subscript, true).\n// - if no, this function returns (fieldPath, \"\", false).\n//\n// Example inputs and outputs:\n// - \"metadata.annotations['myKey']\" --\u003e (\"metadata.annotations\", \"myKey\", true)\n// - \"metadata.annotations['a[b]c']\" --\u003e (\"metadata.annotations\", \"a[b]c\", true)\n// - \"metadata.labels[”]\" --\u003e (\"metadata.labels\", \"\", true)\n// - \"metadata.labels\" --\u003e (\"metadata.labels\", \"\", false)\nfunc splitMaybeSubscriptedPath(fieldPath string) (string, string, bool) {\n\tif !strings.HasSuffix(fieldPath, \"']\") {\n\t\treturn fieldPath, \"\", false\n\t}\n\ts := strings.TrimSuffix(fieldPath, \"']\")\n\tparts := strings.SplitN(s, \"['\", 2)\n\tif len(parts) \u003c 2 {\n\t\treturn fieldPath, \"\", false\n\t}\n\tif len(parts[0]) == 0 {\n\t\treturn fieldPath, \"\", false\n\t}\n\treturn parts[0], parts[1], true\n}","line":{"from":132,"to":156}} {"id":100032108,"name":"formatMap","signature":"func formatMap(m map[string]string) (fmtStr string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/env/env_resolve.go","code":"// formatMap formats map[string]string to a string.\nfunc formatMap(m map[string]string) (fmtStr string) {\n\t// output with keys in sorted order to provide stable output\n\tkeys := sets.NewString()\n\tfor key := range m {\n\t\tkeys.Insert(key)\n\t}\n\tfor _, key := range keys.List() {\n\t\tfmtStr += fmt.Sprintf(\"%v=%q\\n\", key, m[key])\n\t}\n\tfmtStr = strings.TrimSuffix(fmtStr, \"\\n\")\n\n\treturn\n}","line":{"from":158,"to":171}} {"id":100032109,"name":"getResourceFieldRef","signature":"func getResourceFieldRef(from *corev1.EnvVarSource, container *corev1.Container) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/env/env_resolve.go","code":"// getResourceFieldRef returns the value of a resource in the given container\nfunc getResourceFieldRef(from *corev1.EnvVarSource, container *corev1.Container) (string, error) {\n\treturn extractContainerResourceValue(from.ResourceFieldRef, container)\n}","line":{"from":173,"to":176}} {"id":100032110,"name":"extractContainerResourceValue","signature":"func extractContainerResourceValue(fs *corev1.ResourceFieldSelector, container *corev1.Container) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/env/env_resolve.go","code":"// ExtractContainerResourceValue extracts the value of a resource\n// in an already known container\nfunc extractContainerResourceValue(fs *corev1.ResourceFieldSelector, container *corev1.Container) (string, error) {\n\tdivisor := resource.Quantity{}\n\tif divisor.Cmp(fs.Divisor) == 0 {\n\t\tdivisor = resource.MustParse(\"1\")\n\t} else {\n\t\tdivisor = fs.Divisor\n\t}\n\n\tswitch fs.Resource {\n\tcase \"limits.cpu\":\n\t\treturn convertResourceCPUToString(container.Resources.Limits.Cpu(), divisor)\n\tcase \"limits.memory\":\n\t\treturn convertResourceMemoryToString(container.Resources.Limits.Memory(), divisor)\n\tcase \"limits.ephemeral-storage\":\n\t\treturn convertResourceEphemeralStorageToString(container.Resources.Limits.StorageEphemeral(), divisor)\n\tcase \"requests.cpu\":\n\t\treturn convertResourceCPUToString(container.Resources.Requests.Cpu(), divisor)\n\tcase \"requests.memory\":\n\t\treturn convertResourceMemoryToString(container.Resources.Requests.Memory(), divisor)\n\tcase \"requests.ephemeral-storage\":\n\t\treturn convertResourceEphemeralStorageToString(container.Resources.Requests.StorageEphemeral(), divisor)\n\t}\n\t// handle extended standard resources with dynamic names\n\t// example: requests.hugepages-\u003cpageSize\u003e or limits.hugepages-\u003cpageSize\u003e\n\tif strings.HasPrefix(fs.Resource, \"requests.\") {\n\t\tresourceName := corev1.ResourceName(strings.TrimPrefix(fs.Resource, \"requests.\"))\n\t\tif IsHugePageResourceName(resourceName) {\n\t\t\treturn convertResourceHugePagesToString(container.Resources.Requests.Name(resourceName, resource.BinarySI), divisor)\n\t\t}\n\t}\n\tif strings.HasPrefix(fs.Resource, \"limits.\") {\n\t\tresourceName := corev1.ResourceName(strings.TrimPrefix(fs.Resource, \"limits.\"))\n\t\tif IsHugePageResourceName(resourceName) {\n\t\t\treturn convertResourceHugePagesToString(container.Resources.Limits.Name(resourceName, resource.BinarySI), divisor)\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"Unsupported container resource : %v\", fs.Resource)\n}","line":{"from":178,"to":217}} {"id":100032111,"name":"convertResourceCPUToString","signature":"func convertResourceCPUToString(cpu *resource.Quantity, divisor resource.Quantity) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/env/env_resolve.go","code":"// convertResourceCPUToString converts cpu value to the format of divisor and returns\n// ceiling of the value.\nfunc convertResourceCPUToString(cpu *resource.Quantity, divisor resource.Quantity) (string, error) {\n\tc := int64(math.Ceil(float64(cpu.MilliValue()) / float64(divisor.MilliValue())))\n\treturn strconv.FormatInt(c, 10), nil\n}","line":{"from":219,"to":224}} {"id":100032112,"name":"convertResourceMemoryToString","signature":"func convertResourceMemoryToString(memory *resource.Quantity, divisor resource.Quantity) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/env/env_resolve.go","code":"// convertResourceMemoryToString converts memory value to the format of divisor and returns\n// ceiling of the value.\nfunc convertResourceMemoryToString(memory *resource.Quantity, divisor resource.Quantity) (string, error) {\n\tm := int64(math.Ceil(float64(memory.Value()) / float64(divisor.Value())))\n\treturn strconv.FormatInt(m, 10), nil\n}","line":{"from":226,"to":231}} {"id":100032113,"name":"convertResourceHugePagesToString","signature":"func convertResourceHugePagesToString(hugePages *resource.Quantity, divisor resource.Quantity) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/env/env_resolve.go","code":"// convertResourceHugePagesToString converts hugepages value to the format of divisor and returns\n// ceiling of the value.\nfunc convertResourceHugePagesToString(hugePages *resource.Quantity, divisor resource.Quantity) (string, error) {\n\tm := int64(math.Ceil(float64(hugePages.Value()) / float64(divisor.Value())))\n\treturn strconv.FormatInt(m, 10), nil\n}","line":{"from":233,"to":238}} {"id":100032114,"name":"convertResourceEphemeralStorageToString","signature":"func convertResourceEphemeralStorageToString(ephemeralStorage *resource.Quantity, divisor resource.Quantity) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/env/env_resolve.go","code":"// convertResourceEphemeralStorageToString converts ephemeral storage value to the format of divisor and returns\n// ceiling of the value.\nfunc convertResourceEphemeralStorageToString(ephemeralStorage *resource.Quantity, divisor resource.Quantity) (string, error) {\n\tm := int64(math.Ceil(float64(ephemeralStorage.Value()) / float64(divisor.Value())))\n\treturn strconv.FormatInt(m, 10), nil\n}","line":{"from":240,"to":245}} {"id":100032115,"name":"GetEnvVarRefValue","signature":"func GetEnvVarRefValue(kc kubernetes.Interface, ns string, store *ResourceStore, from *corev1.EnvVarSource, obj runtime.Object, c *corev1.Container) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/env/env_resolve.go","code":"// GetEnvVarRefValue returns the value referenced by the supplied EnvVarSource given the other supplied information.\nfunc GetEnvVarRefValue(kc kubernetes.Interface, ns string, store *ResourceStore, from *corev1.EnvVarSource, obj runtime.Object, c *corev1.Container) (string, error) {\n\tif from.SecretKeyRef != nil {\n\t\treturn getSecretRefValue(kc, ns, store, from.SecretKeyRef)\n\t}\n\n\tif from.ConfigMapKeyRef != nil {\n\t\treturn getConfigMapRefValue(kc, ns, store, from.ConfigMapKeyRef)\n\t}\n\n\tif from.FieldRef != nil {\n\t\treturn getFieldRef(obj, from)\n\t}\n\n\tif from.ResourceFieldRef != nil {\n\t\treturn getResourceFieldRef(from, c)\n\t}\n\n\treturn \"\", fmt.Errorf(\"invalid valueFrom\")\n}","line":{"from":247,"to":266}} {"id":100032116,"name":"GetEnvVarRefString","signature":"func GetEnvVarRefString(from *corev1.EnvVarSource) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/env/env_resolve.go","code":"// GetEnvVarRefString returns a text description of whichever field is set within the supplied EnvVarSource argument.\nfunc GetEnvVarRefString(from *corev1.EnvVarSource) string {\n\tif from.ConfigMapKeyRef != nil {\n\t\treturn fmt.Sprintf(\"configmap %s, key %s\", from.ConfigMapKeyRef.Name, from.ConfigMapKeyRef.Key)\n\t}\n\n\tif from.SecretKeyRef != nil {\n\t\treturn fmt.Sprintf(\"secret %s, key %s\", from.SecretKeyRef.Name, from.SecretKeyRef.Key)\n\t}\n\n\tif from.FieldRef != nil {\n\t\treturn fmt.Sprintf(\"field path %s\", from.FieldRef.FieldPath)\n\t}\n\n\tif from.ResourceFieldRef != nil {\n\t\tcontainerPrefix := \"\"\n\t\tif from.ResourceFieldRef.ContainerName != \"\" {\n\t\t\tcontainerPrefix = fmt.Sprintf(\"%s/\", from.ResourceFieldRef.ContainerName)\n\t\t}\n\t\treturn fmt.Sprintf(\"resource field %s%s\", containerPrefix, from.ResourceFieldRef.Resource)\n\t}\n\n\treturn \"invalid valueFrom\"\n}","line":{"from":268,"to":291}} {"id":100032117,"name":"IsHugePageResourceName","signature":"func IsHugePageResourceName(name corev1.ResourceName) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/env/env_resolve.go","code":"// IsHugePageResourceName returns true if the resource name has the huge page\n// resource prefix.\nfunc IsHugePageResourceName(name corev1.ResourceName) bool {\n\treturn strings.HasPrefix(string(name), corev1.ResourceHugePagesPrefix)\n}","line":{"from":293,"to":297}} {"id":100032118,"name":"selectContainers","signature":"func selectContainers(containers []v1.Container, spec string) ([]*v1.Container, []*v1.Container)","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/helper.go","code":"// selectContainers allows one or more containers to be matched against a string or wildcard\nfunc selectContainers(containers []v1.Container, spec string) ([]*v1.Container, []*v1.Container) {\n\tout := []*v1.Container{}\n\tskipped := []*v1.Container{}\n\tfor i, c := range containers {\n\t\tif selectString(c.Name, spec) {\n\t\t\tout = append(out, \u0026containers[i])\n\t\t} else {\n\t\t\tskipped = append(skipped, \u0026containers[i])\n\t\t}\n\t}\n\treturn out, skipped\n}","line":{"from":29,"to":41}} {"id":100032119,"name":"selectString","signature":"func selectString(s, spec string) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/helper.go","code":"// selectString returns true if the provided string matches spec, where spec is a string with\n// a non-greedy '*' wildcard operator.\n// TODO: turn into a regex and handle greedy matches and backtracking.\nfunc selectString(s, spec string) bool {\n\tif spec == \"*\" {\n\t\treturn true\n\t}\n\tif !strings.Contains(spec, \"*\") {\n\t\treturn s == spec\n\t}\n\n\tpos := 0\n\tmatch := true\n\tparts := strings.Split(spec, \"*\")\nLoop:\n\tfor i, part := range parts {\n\t\tif len(part) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tnext := strings.Index(s[pos:], part)\n\t\tswitch {\n\t\t// next part not in string\n\t\tcase next \u003c pos:\n\t\t\tfallthrough\n\t\t// first part does not match start of string\n\t\tcase i == 0 \u0026\u0026 pos != 0:\n\t\t\tfallthrough\n\t\t// last part does not exactly match remaining part of string\n\t\tcase i == (len(parts)-1) \u0026\u0026 len(s) != (len(part)+next):\n\t\t\tmatch = false\n\t\t\tbreak Loop\n\t\tdefault:\n\t\t\tpos = next\n\t\t}\n\t}\n\treturn match\n}","line":{"from":43,"to":79}} {"id":100032120,"name":"CalculatePatch","signature":"func CalculatePatch(patch *Patch, encoder runtime.Encoder, mutateFn PatchFn) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/helper.go","code":"// CalculatePatch calls the mutation function on the provided info object, and generates a strategic merge patch for\n// the changes in the object. Encoder must be able to encode the info into the appropriate destination type.\n// This function returns whether the mutation function made any change in the original object.\nfunc CalculatePatch(patch *Patch, encoder runtime.Encoder, mutateFn PatchFn) bool {\n\tpatch.Before, patch.Err = runtime.Encode(encoder, patch.Info.Object)\n\tpatch.After, patch.Err = mutateFn(patch.Info.Object)\n\tif patch.Err != nil {\n\t\treturn true\n\t}\n\tif patch.After == nil {\n\t\treturn false\n\t}\n\n\tpatch.Patch, patch.Err = strategicpatch.CreateTwoWayMergePatch(patch.Before, patch.After, patch.Info.Object)\n\treturn true\n}","line":{"from":95,"to":110}} {"id":100032121,"name":"CalculatePatches","signature":"func CalculatePatches(infos []*resource.Info, encoder runtime.Encoder, mutateFn PatchFn) []*Patch","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/helper.go","code":"// CalculatePatches calculates patches on each provided info object. If the provided mutateFn\n// makes no change in an object, the object is not included in the final list of patches.\nfunc CalculatePatches(infos []*resource.Info, encoder runtime.Encoder, mutateFn PatchFn) []*Patch {\n\tvar patches []*Patch\n\tfor _, info := range infos {\n\t\tpatch := \u0026Patch{Info: info}\n\t\tif CalculatePatch(patch, encoder, mutateFn) {\n\t\t\tpatches = append(patches, patch)\n\t\t}\n\t}\n\treturn patches\n}","line":{"from":112,"to":123}} {"id":100032122,"name":"findEnv","signature":"func findEnv(env []v1.EnvVar, name string) (v1.EnvVar, bool)","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/helper.go","code":"func findEnv(env []v1.EnvVar, name string) (v1.EnvVar, bool) {\n\tfor _, e := range env {\n\t\tif e.Name == name {\n\t\t\treturn e, true\n\t\t}\n\t}\n\treturn v1.EnvVar{}, false\n}","line":{"from":125,"to":132}} {"id":100032123,"name":"updateEnv","signature":"func updateEnv(existing []v1.EnvVar, env []v1.EnvVar, remove []string) []v1.EnvVar","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/helper.go","code":"// updateEnv adds and deletes specified environment variables from existing environment variables.\n// An added variable replaces all existing variables with the same name.\n// Removing a variable removes all existing variables with the same name.\n// If the existing list contains duplicates that are unrelated to the variables being added and removed,\n// those duplicates are left intact in the result.\n// If a variable is both added and removed, the removal takes precedence.\nfunc updateEnv(existing []v1.EnvVar, env []v1.EnvVar, remove []string) []v1.EnvVar {\n\tout := []v1.EnvVar{}\n\tcovered := sets.NewString(remove...)\n\tfor _, e := range existing {\n\t\tif covered.Has(e.Name) {\n\t\t\tcontinue\n\t\t}\n\t\tnewer, ok := findEnv(env, e.Name)\n\t\tif ok {\n\t\t\tcovered.Insert(e.Name)\n\t\t\tout = append(out, newer)\n\t\t\tcontinue\n\t\t}\n\t\tout = append(out, e)\n\t}\n\tfor _, e := range env {\n\t\tif covered.Has(e.Name) {\n\t\t\tcontinue\n\t\t}\n\t\tcovered.Insert(e.Name)\n\t\tout = append(out, e)\n\t}\n\treturn out\n}","line":{"from":134,"to":163}} {"id":100032124,"name":"NewCmdSet","signature":"func NewCmdSet(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set.go","code":"// NewCmdSet returns an initialized Command instance for 'set' sub command\nfunc NewCmdSet(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"set SUBCOMMAND\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Set specific features on objects\"),\n\t\tLong: setLong,\n\t\tRun: cmdutil.DefaultSubCommandRun(streams.ErrOut),\n\t}\n\n\t// add subcommands\n\tcmd.AddCommand(NewCmdImage(f, streams))\n\tcmd.AddCommand(NewCmdResources(f, streams))\n\tcmd.AddCommand(NewCmdSelector(f, streams))\n\tcmd.AddCommand(NewCmdSubject(f, streams))\n\tcmd.AddCommand(NewCmdServiceAccount(f, streams))\n\tcmd.AddCommand(NewCmdEnv(f, streams))\n\n\treturn cmd\n}","line":{"from":34,"to":53}} {"id":100032125,"name":"NewEnvOptions","signature":"func NewEnvOptions(streams genericclioptions.IOStreams) *EnvOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_env.go","code":"// NewEnvOptions returns an EnvOptions indicating all containers in the selected\n// pod templates are selected by default and allowing environment to be overwritten\nfunc NewEnvOptions(streams genericclioptions.IOStreams) *EnvOptions {\n\treturn \u0026EnvOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"env updated\").WithTypeSetter(scheme.Scheme),\n\n\t\tContainerSelector: \"*\",\n\t\tOverwrite: true,\n\t\tIOStreams: streams,\n\t}\n}","line":{"from":136,"to":146}} {"id":100032126,"name":"NewCmdEnv","signature":"func NewCmdEnv(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_env.go","code":"// NewCmdEnv implements the OpenShift cli env command\nfunc NewCmdEnv(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\to := NewEnvOptions(streams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"env RESOURCE/NAME KEY_1=VAL_1 ... KEY_N=VAL_N\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Update environment variables on a pod template\"),\n\t\tLong: envLong,\n\t\tExample: envExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.RunEnv())\n\t\t},\n\t}\n\tusage := \"the resource to update the env\"\n\tcmdutil.AddFilenameOptionFlags(cmd, \u0026o.FilenameOptions, usage)\n\tcmd.Flags().StringVarP(\u0026o.ContainerSelector, \"containers\", \"c\", o.ContainerSelector, \"The names of containers in the selected pod templates to change - may use wildcards\")\n\tcmd.Flags().StringVarP(\u0026o.From, \"from\", \"\", \"\", \"The name of a resource from which to inject environment variables\")\n\tcmd.Flags().StringVarP(\u0026o.Prefix, \"prefix\", \"\", \"\", \"Prefix to append to variable names\")\n\tcmd.Flags().StringArrayVarP(\u0026o.EnvParams, \"env\", \"e\", o.EnvParams, \"Specify a key-value pair for an environment variable to set into each container.\")\n\tcmd.Flags().StringSliceVarP(\u0026o.Keys, \"keys\", \"\", o.Keys, \"Comma-separated list of keys to import from specified resource\")\n\tcmd.Flags().BoolVar(\u0026o.List, \"list\", o.List, \"If true, display the environment and any changes in the standard format. this flag will removed when we have kubectl view env.\")\n\tcmd.Flags().BoolVar(\u0026o.Resolve, \"resolve\", o.Resolve, \"If true, show secret or configmap references when listing variables\")\n\tcmd.Flags().BoolVar(\u0026o.Local, \"local\", o.Local, \"If true, set env will NOT contact api-server but run locally.\")\n\tcmd.Flags().BoolVar(\u0026o.All, \"all\", o.All, \"If true, select all resources in the namespace of the specified resource types\")\n\tcmd.Flags().BoolVar(\u0026o.Overwrite, \"overwrite\", o.Overwrite, \"If true, allow environment to be overwritten, otherwise reject updates that overwrite existing environment.\")\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.fieldManager, \"kubectl-set\")\n\tcmdutil.AddLabelSelectorFlagVar(cmd, \u0026o.Selector)\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddDryRunFlag(cmd)\n\treturn cmd\n}","line":{"from":148,"to":183}} {"id":100032127,"name":"validateNoOverwrites","signature":"func validateNoOverwrites(existing []v1.EnvVar, env []v1.EnvVar) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_env.go","code":"func validateNoOverwrites(existing []v1.EnvVar, env []v1.EnvVar) error {\n\tfor _, e := range env {\n\t\tif current, exists := findEnv(existing, e.Name); exists \u0026\u0026 current.Value != e.Value {\n\t\t\treturn fmt.Errorf(\"'%s' already has a value (%s), and --overwrite is false\", current.Name, current.Value)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":185,"to":192}} {"id":100032128,"name":"contains","signature":"func contains(key string, keyList []string) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_env.go","code":"func contains(key string, keyList []string) bool {\n\tif len(keyList) == 0 {\n\t\treturn true\n\t}\n\n\tfor _, k := range keyList {\n\t\tif k == key {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":194,"to":205}} {"id":100032129,"name":"keyToEnvName","signature":"func (o *EnvOptions) keyToEnvName(key string) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_env.go","code":"func (o *EnvOptions) keyToEnvName(key string) string {\n\tenvName := strings.ToUpper(validEnvNameRegexp.ReplaceAllString(key, \"_\"))\n\tif envName != key {\n\t\to.WarningPrinter.Print(fmt.Sprintf(\"key %s transferred to %s\", key, envName))\n\t}\n\treturn envName\n}","line":{"from":207,"to":213}} {"id":100032130,"name":"Complete","signature":"func (o *EnvOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_env.go","code":"// Complete completes all required options\nfunc (o *EnvOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tif o.All \u0026\u0026 len(o.Selector) \u003e 0 {\n\t\treturn fmt.Errorf(\"cannot set --all and --selector at the same time\")\n\t}\n\tok := false\n\to.resources, o.envArgs, ok = envutil.SplitEnvironmentFromResources(args)\n\tif !ok {\n\t\treturn fmt.Errorf(\"all resources must be specified before environment changes: %s\", strings.Join(args, \" \"))\n\t}\n\n\to.updatePodSpecForObject = polymorphichelpers.UpdatePodSpecForObjectFn\n\to.output = cmdutil.GetFlagString(cmd, \"output\")\n\tvar err error\n\to.dryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.dryRunStrategy)\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.PrintObj = printer.PrintObj\n\n\to.clientset, err = f.KubernetesClientSet()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.namespace, o.enforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.builder = f.NewBuilder\n\t// Set default WarningPrinter if not already set.\n\tif o.WarningPrinter == nil {\n\t\to.WarningPrinter = printers.NewWarningPrinter(o.ErrOut, printers.WarningPrinterOptions{Color: term.AllowsColorOutput(o.ErrOut)})\n\t}\n\n\treturn nil\n}","line":{"from":215,"to":256}} {"id":100032131,"name":"Validate","signature":"func (o *EnvOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_env.go","code":"// Validate makes sure provided values for EnvOptions are valid\nfunc (o *EnvOptions) Validate() error {\n\tif o.Local \u0026\u0026 o.dryRunStrategy == cmdutil.DryRunServer {\n\t\treturn fmt.Errorf(\"cannot specify --local and --dry-run=server - did you mean --dry-run=client?\")\n\t}\n\tif len(o.Filenames) == 0 \u0026\u0026 len(o.resources) \u003c 1 {\n\t\treturn fmt.Errorf(\"one or more resources must be specified as \u003cresource\u003e \u003cname\u003e or \u003cresource\u003e/\u003cname\u003e\")\n\t}\n\tif o.List \u0026\u0026 len(o.output) \u003e 0 {\n\t\treturn fmt.Errorf(\"--list and --output may not be specified together\")\n\t}\n\tif len(o.Keys) \u003e 0 \u0026\u0026 len(o.From) == 0 {\n\t\treturn fmt.Errorf(\"when specifying --keys, a configmap or secret must be provided with --from\")\n\t}\n\tif o.WarningPrinter == nil {\n\t\treturn fmt.Errorf(\"WarningPrinter can not be used without initialization\")\n\t}\n\treturn nil\n}","line":{"from":258,"to":276}} {"id":100032132,"name":"RunEnv","signature":"func (o *EnvOptions) RunEnv() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_env.go","code":"// RunEnv contains all the necessary functionality for the OpenShift cli env command\nfunc (o *EnvOptions) RunEnv() error {\n\tenv, remove, envFromStdin, err := envutil.ParseEnv(append(o.EnvParams, o.envArgs...), o.In)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(o.From) != 0 {\n\t\tb := o.builder().\n\t\t\tWithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).\n\t\t\tLocalParam(o.Local).\n\t\t\tContinueOnError().\n\t\t\tNamespaceParam(o.namespace).DefaultNamespace().\n\t\t\tFilenameParam(o.enforceNamespace, \u0026o.FilenameOptions).\n\t\t\tFlatten()\n\n\t\tif !o.Local {\n\t\t\tb = b.\n\t\t\t\tLabelSelectorParam(o.Selector).\n\t\t\t\tResourceTypeOrNameArgs(o.All, o.From).\n\t\t\t\tLatest()\n\t\t}\n\n\t\tif envFromStdin {\n\t\t\tb = b.StdinInUse()\n\t\t}\n\n\t\tinfos, err := b.Do().Infos()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor _, info := range infos {\n\t\t\tswitch from := info.Object.(type) {\n\t\t\tcase *v1.Secret:\n\t\t\t\tfor key := range from.Data {\n\t\t\t\t\tif contains(key, o.Keys) {\n\t\t\t\t\t\tenvVar := v1.EnvVar{\n\t\t\t\t\t\t\tName: o.keyToEnvName(key),\n\t\t\t\t\t\t\tValueFrom: \u0026v1.EnvVarSource{\n\t\t\t\t\t\t\t\tSecretKeyRef: \u0026v1.SecretKeySelector{\n\t\t\t\t\t\t\t\t\tLocalObjectReference: v1.LocalObjectReference{\n\t\t\t\t\t\t\t\t\t\tName: from.Name,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tKey: key,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenv = append(env, envVar)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase *v1.ConfigMap:\n\t\t\t\tfor key := range from.Data {\n\t\t\t\t\tif contains(key, o.Keys) {\n\t\t\t\t\t\tenvVar := v1.EnvVar{\n\t\t\t\t\t\t\tName: o.keyToEnvName(key),\n\t\t\t\t\t\t\tValueFrom: \u0026v1.EnvVarSource{\n\t\t\t\t\t\t\t\tConfigMapKeyRef: \u0026v1.ConfigMapKeySelector{\n\t\t\t\t\t\t\t\t\tLocalObjectReference: v1.LocalObjectReference{\n\t\t\t\t\t\t\t\t\t\tName: from.Name,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tKey: key,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenv = append(env, envVar)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"unsupported resource specified in --from\")\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(o.Prefix) != 0 {\n\t\tfor i := range env {\n\t\t\tenv[i].Name = fmt.Sprintf(\"%s%s\", o.Prefix, env[i].Name)\n\t\t}\n\t}\n\n\tb := o.builder().\n\t\tWithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).\n\t\tLocalParam(o.Local).\n\t\tContinueOnError().\n\t\tNamespaceParam(o.namespace).DefaultNamespace().\n\t\tFilenameParam(o.enforceNamespace, \u0026o.FilenameOptions).\n\t\tFlatten()\n\n\tif !o.Local {\n\t\tb.LabelSelectorParam(o.Selector).\n\t\t\tResourceTypeOrNameArgs(o.All, o.resources...).\n\t\t\tLatest()\n\t}\n\n\tif envFromStdin {\n\t\tb = b.StdinInUse()\n\t}\n\n\tinfos, err := b.Do().Infos()\n\tif err != nil {\n\t\treturn err\n\t}\n\tpatches := CalculatePatches(infos, scheme.DefaultJSONEncoder(), func(obj runtime.Object) ([]byte, error) {\n\t\t_, err := o.updatePodSpecForObject(obj, func(spec *v1.PodSpec) error {\n\t\t\tresolutionErrorsEncountered := false\n\t\t\tinitContainers, _ := selectContainers(spec.InitContainers, o.ContainerSelector)\n\t\t\tcontainers, _ := selectContainers(spec.Containers, o.ContainerSelector)\n\t\t\tcontainers = append(containers, initContainers...)\n\t\t\tobjName, err := meta.NewAccessor().Name(obj)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tgvks, _, err := scheme.Scheme.ObjectKinds(obj)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tobjKind := obj.GetObjectKind().GroupVersionKind().Kind\n\t\t\tif len(objKind) == 0 {\n\t\t\t\tfor _, gvk := range gvks {\n\t\t\t\t\tif len(gvk.Kind) == 0 {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif len(gvk.Version) == 0 || gvk.Version == runtime.APIVersionInternal {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tobjKind = gvk.Kind\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(containers) == 0 {\n\t\t\t\tif gvks, _, err := scheme.Scheme.ObjectKinds(obj); err == nil {\n\t\t\t\t\tobjKind := obj.GetObjectKind().GroupVersionKind().Kind\n\t\t\t\t\tif len(objKind) == 0 {\n\t\t\t\t\t\tfor _, gvk := range gvks {\n\t\t\t\t\t\t\tif len(gvk.Kind) == 0 {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif len(gvk.Version) == 0 || gvk.Version == runtime.APIVersionInternal {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tobjKind = gvk.Kind\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\to.WarningPrinter.Print(fmt.Sprintf(\"%s/%s does not have any containers matching %q\", objKind, objName, o.ContainerSelector))\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tfor _, c := range containers {\n\t\t\t\tif !o.Overwrite {\n\t\t\t\t\tif err := validateNoOverwrites(c.Env, env); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tc.Env = updateEnv(c.Env, env, remove)\n\t\t\t\tif o.List {\n\t\t\t\t\tresolveErrors := map[string][]string{}\n\t\t\t\t\tstore := envutil.NewResourceStore()\n\n\t\t\t\t\tfmt.Fprintf(o.Out, \"# %s %s, container %s\\n\", objKind, objName, c.Name)\n\t\t\t\t\tfor _, env := range c.Env {\n\t\t\t\t\t\t// Print the simple value\n\t\t\t\t\t\tif env.ValueFrom == nil {\n\t\t\t\t\t\t\tfmt.Fprintf(o.Out, \"%s=%s\\n\", env.Name, env.Value)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Print the reference version\n\t\t\t\t\t\tif !o.Resolve {\n\t\t\t\t\t\t\tfmt.Fprintf(o.Out, \"# %s from %s\\n\", env.Name, envutil.GetEnvVarRefString(env.ValueFrom))\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tvalue, err := envutil.GetEnvVarRefValue(o.clientset, o.namespace, store, env.ValueFrom, obj, c)\n\t\t\t\t\t\t// Print the resolved value\n\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\tfmt.Fprintf(o.Out, \"%s=%s\\n\", env.Name, value)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Print the reference version and save the resolve error\n\t\t\t\t\t\tfmt.Fprintf(o.Out, \"# %s from %s\\n\", env.Name, envutil.GetEnvVarRefString(env.ValueFrom))\n\t\t\t\t\t\terrString := err.Error()\n\t\t\t\t\t\tresolveErrors[errString] = append(resolveErrors[errString], env.Name)\n\t\t\t\t\t\tresolutionErrorsEncountered = true\n\t\t\t\t\t}\n\n\t\t\t\t\t// Print any resolution errors\n\t\t\t\t\terrs := []string{}\n\t\t\t\t\tfor err, vars := range resolveErrors {\n\t\t\t\t\t\tsort.Strings(vars)\n\t\t\t\t\t\terrs = append(errs, fmt.Sprintf(\"error retrieving reference for %s: %v\", strings.Join(vars, \", \"), err))\n\t\t\t\t\t}\n\t\t\t\t\tsort.Strings(errs)\n\t\t\t\t\tfor _, err := range errs {\n\t\t\t\t\t\tfmt.Fprintln(o.ErrOut, err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif resolutionErrorsEncountered {\n\t\t\t\treturn errors.New(\"failed to retrieve valueFrom references\")\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\n\t\tif err == nil {\n\t\t\treturn runtime.Encode(scheme.DefaultJSONEncoder(), obj)\n\t\t}\n\t\treturn nil, err\n\t})\n\n\tif o.List {\n\t\treturn nil\n\t}\n\n\tallErrs := []error{}\n\n\tfor _, patch := range patches {\n\t\tinfo := patch.Info\n\t\tif patch.Err != nil {\n\t\t\tname := info.ObjectName()\n\t\t\tallErrs = append(allErrs, fmt.Errorf(\"error: %s %v\\n\", name, patch.Err))\n\t\t\tcontinue\n\t\t}\n\n\t\t// no changes\n\t\tif string(patch.Patch) == \"{}\" || len(patch.Patch) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif o.Local || o.dryRunStrategy == cmdutil.DryRunClient {\n\t\t\tif err := o.PrintObj(info.Object, o.Out); err != nil {\n\t\t\t\tallErrs = append(allErrs, err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tactual, err := resource.\n\t\t\tNewHelper(info.Client, info.Mapping).\n\t\t\tDryRun(o.dryRunStrategy == cmdutil.DryRunServer).\n\t\t\tWithFieldManager(o.fieldManager).\n\t\t\tPatch(info.Namespace, info.Name, types.StrategicMergePatchType, patch.Patch, nil)\n\t\tif err != nil {\n\t\t\tallErrs = append(allErrs, fmt.Errorf(\"failed to patch env update to pod template: %v\", err))\n\t\t\tcontinue\n\t\t}\n\n\t\t// make sure arguments to set or replace environment variables are set\n\t\t// before returning a successful message\n\t\tif len(env) == 0 \u0026\u0026 len(o.envArgs) == 0 {\n\t\t\treturn fmt.Errorf(\"at least one environment variable must be provided\")\n\t\t}\n\n\t\tif err := o.PrintObj(actual, o.Out); err != nil {\n\t\t\tallErrs = append(allErrs, err)\n\t\t}\n\t}\n\treturn utilerrors.NewAggregate(allErrs)\n}","line":{"from":278,"to":542}} {"id":100032133,"name":"NewImageOptions","signature":"func NewImageOptions(streams genericclioptions.IOStreams) *SetImageOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_image.go","code":"// NewImageOptions returns an initialized SetImageOptions instance\nfunc NewImageOptions(streams genericclioptions.IOStreams) *SetImageOptions {\n\treturn \u0026SetImageOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"image updated\").WithTypeSetter(scheme.Scheme),\n\t\tRecordFlags: genericclioptions.NewRecordFlags(),\n\n\t\tRecorder: genericclioptions.NoopRecorder{},\n\n\t\tIOStreams: streams,\n\t}\n}","line":{"from":98,"to":108}} {"id":100032134,"name":"NewCmdImage","signature":"func NewCmdImage(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_image.go","code":"// NewCmdImage returns an initialized Command instance for the 'set image' sub command\nfunc NewCmdImage(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\to := NewImageOptions(streams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"image (-f FILENAME | TYPE NAME) CONTAINER_NAME_1=CONTAINER_IMAGE_1 ... CONTAINER_NAME_N=CONTAINER_IMAGE_N\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Update the image of a pod template\"),\n\t\tLong: imageLong,\n\t\tExample: imageExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\to.RecordFlags.AddFlags(cmd)\n\n\tusage := \"identifying the resource to get from a server.\"\n\tcmdutil.AddFilenameOptionFlags(cmd, \u0026o.FilenameOptions, usage)\n\tcmd.Flags().BoolVar(\u0026o.All, \"all\", o.All, \"Select all resources, in the namespace of the specified resource types\")\n\tcmd.Flags().BoolVar(\u0026o.Local, \"local\", o.Local, \"If true, set image will NOT contact api-server but run locally.\")\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.fieldManager, \"kubectl-set\")\n\tcmdutil.AddLabelSelectorFlagVar(cmd, \u0026o.Selector)\n\n\treturn cmd\n}","line":{"from":110,"to":139}} {"id":100032135,"name":"Complete","signature":"func (o *SetImageOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_image.go","code":"// Complete completes all required options\nfunc (o *SetImageOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\n\to.RecordFlags.Complete(cmd)\n\to.Recorder, err = o.RecordFlags.ToRecorder()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.UpdatePodSpecForObject = polymorphichelpers.UpdatePodSpecForObjectFn\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Output = cmdutil.GetFlagString(cmd, \"output\")\n\to.ResolveImage = ImageResolver\n\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.PrintObj = printer.PrintObj\n\n\tcmdNamespace, enforceNamespace, err := f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Resources, o.ContainerImages, err = getResourcesAndImages(args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbuilder := f.NewBuilder().\n\t\tWithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).\n\t\tLocalParam(o.Local).\n\t\tContinueOnError().\n\t\tNamespaceParam(cmdNamespace).DefaultNamespace().\n\t\tFilenameParam(enforceNamespace, \u0026o.FilenameOptions).\n\t\tFlatten()\n\n\tif !o.Local {\n\t\tbuilder.LabelSelectorParam(o.Selector).\n\t\t\tResourceTypeOrNameArgs(o.All, o.Resources...).\n\t\t\tLatest()\n\t} else {\n\t\t// if a --local flag was provided, and a resource was specified in the form\n\t\t// \u003cresource\u003e/\u003cname\u003e, fail immediately as --local cannot query the api server\n\t\t// for the specified resource.\n\t\tif len(o.Resources) \u003e 0 {\n\t\t\treturn resource.LocalResourceError\n\t\t}\n\t}\n\n\to.Infos, err = builder.Do().Infos()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":141,"to":205}} {"id":100032136,"name":"Validate","signature":"func (o *SetImageOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_image.go","code":"// Validate makes sure provided values in SetImageOptions are valid\nfunc (o *SetImageOptions) Validate() error {\n\terrors := []error{}\n\tif o.All \u0026\u0026 len(o.Selector) \u003e 0 {\n\t\terrors = append(errors, fmt.Errorf(\"cannot set --all and --selector at the same time\"))\n\t}\n\tif len(o.Resources) \u003c 1 \u0026\u0026 cmdutil.IsFilenameSliceEmpty(o.Filenames, o.Kustomize) {\n\t\terrors = append(errors, fmt.Errorf(\"one or more resources must be specified as \u003cresource\u003e \u003cname\u003e or \u003cresource\u003e/\u003cname\u003e\"))\n\t}\n\tif len(o.ContainerImages) \u003c 1 {\n\t\terrors = append(errors, fmt.Errorf(\"at least one image update is required\"))\n\t} else if len(o.ContainerImages) \u003e 1 \u0026\u0026 hasWildcardKey(o.ContainerImages) {\n\t\terrors = append(errors, fmt.Errorf(\"all containers are already specified by *, but saw more than one container_name=container_image pairs\"))\n\t}\n\tif o.Local \u0026\u0026 o.DryRunStrategy == cmdutil.DryRunServer {\n\t\terrors = append(errors, fmt.Errorf(\"cannot specify --local and --dry-run=server - did you mean --dry-run=client?\"))\n\t}\n\treturn utilerrors.NewAggregate(errors)\n}","line":{"from":207,"to":225}} {"id":100032137,"name":"Run","signature":"func (o *SetImageOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_image.go","code":"// Run performs the execution of 'set image' sub command\nfunc (o *SetImageOptions) Run() error {\n\tallErrs := []error{}\n\n\tpatches := CalculatePatches(o.Infos, scheme.DefaultJSONEncoder(), func(obj runtime.Object) ([]byte, error) {\n\t\t_, err := o.UpdatePodSpecForObject(obj, func(spec *v1.PodSpec) error {\n\t\t\tfor name, image := range o.ContainerImages {\n\t\t\t\tresolvedImageName, err := o.ResolveImage(image)\n\t\t\t\tif err != nil {\n\t\t\t\t\tallErrs = append(allErrs, fmt.Errorf(\"error: unable to resolve image %q for container %q: %v\", image, name, err))\n\t\t\t\t\tif name == \"*\" {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tinitContainerFound := setImage(spec.InitContainers, name, resolvedImageName)\n\t\t\t\tcontainerFound := setImage(spec.Containers, name, resolvedImageName)\n\t\t\t\tif !containerFound \u0026\u0026 !initContainerFound {\n\t\t\t\t\tallErrs = append(allErrs, fmt.Errorf(\"error: unable to find container named %q\", name))\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// record this change (for rollout history)\n\t\tif err := o.Recorder.Record(obj); err != nil {\n\t\t\tklog.V(4).Infof(\"error recording current command: %v\", err)\n\t\t}\n\n\t\treturn runtime.Encode(scheme.DefaultJSONEncoder(), obj)\n\t})\n\n\tfor _, patch := range patches {\n\t\tinfo := patch.Info\n\t\tif patch.Err != nil {\n\t\t\tname := info.ObjectName()\n\t\t\tallErrs = append(allErrs, fmt.Errorf(\"error: %s %v\\n\", name, patch.Err))\n\t\t\tcontinue\n\t\t}\n\n\t\t// no changes\n\t\tif string(patch.Patch) == \"{}\" || len(patch.Patch) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif o.Local || o.DryRunStrategy == cmdutil.DryRunClient {\n\t\t\tif err := o.PrintObj(info.Object, o.Out); err != nil {\n\t\t\t\tallErrs = append(allErrs, err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// patch the change\n\t\tactual, err := resource.\n\t\t\tNewHelper(info.Client, info.Mapping).\n\t\t\tDryRun(o.DryRunStrategy == cmdutil.DryRunServer).\n\t\t\tWithFieldManager(o.fieldManager).\n\t\t\tPatch(info.Namespace, info.Name, types.StrategicMergePatchType, patch.Patch, nil)\n\t\tif err != nil {\n\t\t\tallErrs = append(allErrs, fmt.Errorf(\"failed to patch image update to pod template: %v\", err))\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := o.PrintObj(actual, o.Out); err != nil {\n\t\t\tallErrs = append(allErrs, err)\n\t\t}\n\t}\n\treturn utilerrors.NewAggregate(allErrs)\n}","line":{"from":227,"to":298}} {"id":100032138,"name":"setImage","signature":"func setImage(containers []v1.Container, containerName string, image string) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_image.go","code":"func setImage(containers []v1.Container, containerName string, image string) bool {\n\tcontainerFound := false\n\t// Find the container to update, and update its image\n\tfor i, c := range containers {\n\t\tif c.Name == containerName || containerName == \"*\" {\n\t\t\tcontainerFound = true\n\t\t\tcontainers[i].Image = image\n\t\t}\n\t}\n\treturn containerFound\n}","line":{"from":300,"to":310}} {"id":100032139,"name":"getResourcesAndImages","signature":"func getResourcesAndImages(args []string) (resources []string, containerImages map[string]string, err error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_image.go","code":"// getResourcesAndImages retrieves resources and container name:images pair from given args\nfunc getResourcesAndImages(args []string) (resources []string, containerImages map[string]string, err error) {\n\tpairType := \"image\"\n\tresources, imageArgs, err := cmdutil.GetResourcesAndPairs(args, pairType)\n\tif err != nil {\n\t\treturn\n\t}\n\tcontainerImages, _, err = cmdutil.ParsePairs(imageArgs, pairType, false)\n\treturn\n}","line":{"from":312,"to":321}} {"id":100032140,"name":"hasWildcardKey","signature":"func hasWildcardKey(containerImages map[string]string) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_image.go","code":"func hasWildcardKey(containerImages map[string]string) bool {\n\t_, ok := containerImages[\"*\"]\n\treturn ok\n}","line":{"from":323,"to":326}} {"id":100032141,"name":"resolveImageFunc","signature":"func resolveImageFunc(in string) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_image.go","code":"// implements ImageResolver\nfunc resolveImageFunc(in string) (string, error) {\n\treturn in, nil\n}","line":{"from":328,"to":331}} {"id":100032142,"name":"NewResourcesOptions","signature":"func NewResourcesOptions(streams genericclioptions.IOStreams) *SetResourcesOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_resources.go","code":"// NewResourcesOptions returns a ResourcesOptions indicating all containers in the selected\n// pod templates are selected by default.\nfunc NewResourcesOptions(streams genericclioptions.IOStreams) *SetResourcesOptions {\n\treturn \u0026SetResourcesOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"resource requirements updated\").WithTypeSetter(scheme.Scheme),\n\t\tRecordFlags: genericclioptions.NewRecordFlags(),\n\n\t\tRecorder: genericclioptions.NoopRecorder{},\n\n\t\tContainerSelector: \"*\",\n\n\t\tIOStreams: streams,\n\t}\n}","line":{"from":93,"to":106}} {"id":100032143,"name":"NewCmdResources","signature":"func NewCmdResources(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_resources.go","code":"// NewCmdResources returns initialized Command instance for the 'set resources' sub command\nfunc NewCmdResources(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\to := NewResourcesOptions(streams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"resources (-f FILENAME | TYPE NAME) ([--limits=LIMITS \u0026 --requests=REQUESTS]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Update resource requests/limits on objects with pod templates\"),\n\t\tLong: fmt.Sprintf(resourcesLong, cmdutil.SuggestAPIResources(\"kubectl\")),\n\t\tExample: resourcesExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\to.RecordFlags.AddFlags(cmd)\n\n\t//usage := \"Filename, directory, or URL to a file identifying the resource to get from the server\"\n\t//kubectl.AddJsonFilenameFlag(cmd, \u0026options.Filenames, usage)\n\tusage := \"identifying the resource to get from a server.\"\n\tcmdutil.AddFilenameOptionFlags(cmd, \u0026o.FilenameOptions, usage)\n\tcmd.Flags().BoolVar(\u0026o.All, \"all\", o.All, \"Select all resources, in the namespace of the specified resource types\")\n\tcmdutil.AddLabelSelectorFlagVar(cmd, \u0026o.Selector)\n\tcmd.Flags().StringVarP(\u0026o.ContainerSelector, \"containers\", \"c\", o.ContainerSelector, \"The names of containers in the selected pod templates to change, all containers are selected by default - may use wildcards\")\n\tcmd.Flags().BoolVar(\u0026o.Local, \"local\", o.Local, \"If true, set resources will NOT contact api-server but run locally.\")\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmd.Flags().StringVar(\u0026o.Limits, \"limits\", o.Limits, \"The resource requirement requests for this container. For example, 'cpu=100m,memory=256Mi'. Note that server side components may assign requests depending on the server configuration, such as limit ranges.\")\n\tcmd.Flags().StringVar(\u0026o.Requests, \"requests\", o.Requests, \"The resource requirement requests for this container. For example, 'cpu=100m,memory=256Mi'. Note that server side components may assign requests depending on the server configuration, such as limit ranges.\")\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.fieldManager, \"kubectl-set\")\n\treturn cmd\n}","line":{"from":108,"to":141}} {"id":100032144,"name":"Complete","signature":"func (o *SetResourcesOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_resources.go","code":"// Complete completes all required options\nfunc (o *SetResourcesOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\n\to.RecordFlags.Complete(cmd)\n\to.Recorder, err = o.RecordFlags.ToRecorder()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.UpdatePodSpecForObject = polymorphichelpers.UpdatePodSpecForObjectFn\n\to.Output = cmdutil.GetFlagString(cmd, \"output\")\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.PrintObj = printer.PrintObj\n\n\tcmdNamespace, enforceNamespace, err := f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbuilder := f.NewBuilder().\n\t\tWithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).\n\t\tLocalParam(o.Local).\n\t\tContinueOnError().\n\t\tNamespaceParam(cmdNamespace).DefaultNamespace().\n\t\tFilenameParam(enforceNamespace, \u0026o.FilenameOptions).\n\t\tFlatten()\n\n\tif !o.Local {\n\t\tbuilder.LabelSelectorParam(o.Selector).\n\t\t\tResourceTypeOrNameArgs(o.All, args...).\n\t\t\tLatest()\n\t} else {\n\t\t// if a --local flag was provided, and a resource was specified in the form\n\t\t// \u003cresource\u003e/\u003cname\u003e, fail immediately as --local cannot query the api server\n\t\t// for the specified resource.\n\t\t// TODO: this should be in the builder - if someone specifies tuples, fail when\n\t\t// local is true\n\t\tif len(args) \u003e 0 {\n\t\t\treturn resource.LocalResourceError\n\t\t}\n\t}\n\n\to.Infos, err = builder.Do().Infos()\n\treturn err\n}","line":{"from":143,"to":197}} {"id":100032145,"name":"Validate","signature":"func (o *SetResourcesOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_resources.go","code":"// Validate makes sure that provided values in ResourcesOptions are valid\nfunc (o *SetResourcesOptions) Validate() error {\n\tvar err error\n\tif o.Local \u0026\u0026 o.DryRunStrategy == cmdutil.DryRunServer {\n\t\treturn fmt.Errorf(\"cannot specify --local and --dry-run=server - did you mean --dry-run=client?\")\n\t}\n\tif o.All \u0026\u0026 len(o.Selector) \u003e 0 {\n\t\treturn fmt.Errorf(\"cannot set --all and --selector at the same time\")\n\t}\n\tif len(o.Limits) == 0 \u0026\u0026 len(o.Requests) == 0 {\n\t\treturn fmt.Errorf(\"you must specify an update to requests or limits (in the form of --requests/--limits)\")\n\t}\n\n\to.ResourceRequirements, err = generateversioned.HandleResourceRequirementsV1(map[string]string{\"limits\": o.Limits, \"requests\": o.Requests})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":199,"to":218}} {"id":100032146,"name":"Run","signature":"func (o *SetResourcesOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_resources.go","code":"// Run performs the execution of 'set resources' sub command\nfunc (o *SetResourcesOptions) Run() error {\n\tallErrs := []error{}\n\tpatches := CalculatePatches(o.Infos, scheme.DefaultJSONEncoder(), func(obj runtime.Object) ([]byte, error) {\n\t\ttransformed := false\n\t\t_, err := o.UpdatePodSpecForObject(obj, func(spec *v1.PodSpec) error {\n\t\t\tinitContainers, _ := selectContainers(spec.InitContainers, o.ContainerSelector)\n\t\t\tcontainers, _ := selectContainers(spec.Containers, o.ContainerSelector)\n\t\t\tcontainers = append(containers, initContainers...)\n\t\t\tif len(containers) != 0 {\n\t\t\t\tfor i := range containers {\n\t\t\t\t\tif len(o.Limits) != 0 \u0026\u0026 len(containers[i].Resources.Limits) == 0 {\n\t\t\t\t\t\tcontainers[i].Resources.Limits = make(v1.ResourceList)\n\t\t\t\t\t}\n\t\t\t\t\tfor key, value := range o.ResourceRequirements.Limits {\n\t\t\t\t\t\tcontainers[i].Resources.Limits[key] = value\n\t\t\t\t\t}\n\n\t\t\t\t\tif len(o.Requests) != 0 \u0026\u0026 len(containers[i].Resources.Requests) == 0 {\n\t\t\t\t\t\tcontainers[i].Resources.Requests = make(v1.ResourceList)\n\t\t\t\t\t}\n\t\t\t\t\tfor key, value := range o.ResourceRequirements.Requests {\n\t\t\t\t\t\tcontainers[i].Resources.Requests[key] = value\n\t\t\t\t\t}\n\t\t\t\t\ttransformed = true\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tallErrs = append(allErrs, fmt.Errorf(\"error: unable to find container named %s\", o.ContainerSelector))\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !transformed {\n\t\t\treturn nil, nil\n\t\t}\n\t\t// record this change (for rollout history)\n\t\tif err := o.Recorder.Record(obj); err != nil {\n\t\t\tklog.V(4).Infof(\"error recording current command: %v\", err)\n\t\t}\n\n\t\treturn runtime.Encode(scheme.DefaultJSONEncoder(), obj)\n\t})\n\n\tfor _, patch := range patches {\n\t\tinfo := patch.Info\n\t\tname := info.ObjectName()\n\t\tif patch.Err != nil {\n\t\t\tallErrs = append(allErrs, fmt.Errorf(\"error: %s %v\\n\", name, patch.Err))\n\t\t\tcontinue\n\t\t}\n\n\t\t//no changes\n\t\tif string(patch.Patch) == \"{}\" || len(patch.Patch) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif o.Local || o.DryRunStrategy == cmdutil.DryRunClient {\n\t\t\tif err := o.PrintObj(info.Object, o.Out); err != nil {\n\t\t\t\tallErrs = append(allErrs, err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tactual, err := resource.\n\t\t\tNewHelper(info.Client, info.Mapping).\n\t\t\tDryRun(o.DryRunStrategy == cmdutil.DryRunServer).\n\t\t\tWithFieldManager(o.fieldManager).\n\t\t\tPatch(info.Namespace, info.Name, types.StrategicMergePatchType, patch.Patch, nil)\n\t\tif err != nil {\n\t\t\tallErrs = append(allErrs, fmt.Errorf(\"failed to patch resources update to pod template %v\", err))\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := o.PrintObj(actual, o.Out); err != nil {\n\t\t\tallErrs = append(allErrs, err)\n\t\t}\n\t}\n\treturn utilerrors.NewAggregate(allErrs)\n}","line":{"from":220,"to":300}} {"id":100032147,"name":"NewSelectorOptions","signature":"func NewSelectorOptions(streams genericclioptions.IOStreams) *SetSelectorOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_selector.go","code":"// NewSelectorOptions returns an initialized SelectorOptions instance\nfunc NewSelectorOptions(streams genericclioptions.IOStreams) *SetSelectorOptions {\n\treturn \u0026SetSelectorOptions{\n\t\tResourceBuilderFlags: genericclioptions.NewResourceBuilderFlags().\n\t\t\tWithScheme(scheme.Scheme).\n\t\t\tWithAll(false).\n\t\t\tWithLocal(false).\n\t\t\tWithLatest(),\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"selector updated\").WithTypeSetter(scheme.Scheme),\n\t\tRecordFlags: genericclioptions.NewRecordFlags(),\n\n\t\tRecorder: genericclioptions.NoopRecorder{},\n\n\t\tIOStreams: streams,\n\t}\n}","line":{"from":79,"to":94}} {"id":100032148,"name":"NewCmdSelector","signature":"func NewCmdSelector(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_selector.go","code":"// NewCmdSelector is the \"set selector\" command.\nfunc NewCmdSelector(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\to := NewSelectorOptions(streams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"selector (-f FILENAME | TYPE NAME) EXPRESSIONS [--resource-version=version]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Set the selector on a resource\"),\n\t\tLong: fmt.Sprintf(selectorLong, validation.LabelValueMaxLength),\n\t\tExample: selectorExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.RunSelector())\n\t\t},\n\t}\n\n\to.ResourceBuilderFlags.AddFlags(cmd.Flags())\n\to.PrintFlags.AddFlags(cmd)\n\to.RecordFlags.AddFlags(cmd)\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.fieldManager, \"kubectl-set\")\n\n\tcmd.Flags().StringVarP(\u0026o.resourceVersion, \"resource-version\", \"\", o.resourceVersion, \"If non-empty, the selectors update will only succeed if this is the current resource-version for the object. Only valid when specifying a single resource.\")\n\tcmdutil.AddDryRunFlag(cmd)\n\n\treturn cmd\n}","line":{"from":96,"to":122}} {"id":100032149,"name":"Complete","signature":"func (o *SetSelectorOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_selector.go","code":"// Complete assigns the SelectorOptions from args.\nfunc (o *SetSelectorOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\n\to.RecordFlags.Complete(cmd)\n\to.Recorder, err = o.RecordFlags.ToRecorder()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.dryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.resources, o.selector, err = getResourcesAndSelector(args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.ResourceFinder = o.ResourceBuilderFlags.ToBuilder(f, o.resources)\n\to.WriteToServer = !(*o.ResourceBuilderFlags.Local || o.dryRunStrategy == cmdutil.DryRunClient)\n\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.dryRunStrategy)\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.PrintObj = printer.PrintObj\n\n\treturn err\n}","line":{"from":124,"to":155}} {"id":100032150,"name":"Validate","signature":"func (o *SetSelectorOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_selector.go","code":"// Validate basic inputs\nfunc (o *SetSelectorOptions) Validate() error {\n\tif o.selector == nil {\n\t\treturn fmt.Errorf(\"one selector is required\")\n\t}\n\treturn nil\n}","line":{"from":157,"to":163}} {"id":100032151,"name":"RunSelector","signature":"func (o *SetSelectorOptions) RunSelector() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_selector.go","code":"// RunSelector executes the command.\nfunc (o *SetSelectorOptions) RunSelector() error {\n\tr := o.ResourceFinder.Do()\n\n\treturn r.Visit(func(info *resource.Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpatch := \u0026Patch{Info: info}\n\n\t\tif len(o.resourceVersion) != 0 {\n\t\t\t// ensure resourceVersion is always sent in the patch by clearing it from the starting JSON\n\t\t\taccessor, err := meta.Accessor(info.Object)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\taccessor.SetResourceVersion(\"\")\n\t\t}\n\n\t\tCalculatePatch(patch, scheme.DefaultJSONEncoder(), func(obj runtime.Object) ([]byte, error) {\n\n\t\t\tif len(o.resourceVersion) != 0 {\n\t\t\t\taccessor, err := meta.Accessor(info.Object)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\taccessor.SetResourceVersion(o.resourceVersion)\n\t\t\t}\n\n\t\t\tselectErr := updateSelectorForObject(info.Object, *o.selector)\n\t\t\tif selectErr != nil {\n\t\t\t\treturn nil, selectErr\n\t\t\t}\n\n\t\t\t// record this change (for rollout history)\n\t\t\tif err := o.Recorder.Record(patch.Info.Object); err != nil {\n\t\t\t\tklog.V(4).Infof(\"error recording current command: %v\", err)\n\t\t\t}\n\n\t\t\treturn runtime.Encode(scheme.DefaultJSONEncoder(), info.Object)\n\t\t})\n\n\t\tif patch.Err != nil {\n\t\t\treturn patch.Err\n\t\t}\n\t\tif !o.WriteToServer {\n\t\t\treturn o.PrintObj(info.Object, o.Out)\n\t\t}\n\n\t\tactual, err := resource.\n\t\t\tNewHelper(info.Client, info.Mapping).\n\t\t\tDryRun(o.dryRunStrategy == cmdutil.DryRunServer).\n\t\t\tWithFieldManager(o.fieldManager).\n\t\t\tPatch(info.Namespace, info.Name, types.StrategicMergePatchType, patch.Patch, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn o.PrintObj(actual, o.Out)\n\t})\n}","line":{"from":165,"to":225}} {"id":100032152,"name":"updateSelectorForObject","signature":"func updateSelectorForObject(obj runtime.Object, selector metav1.LabelSelector) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_selector.go","code":"func updateSelectorForObject(obj runtime.Object, selector metav1.LabelSelector) error {\n\tcopyOldSelector := func() (map[string]string, error) {\n\t\tif len(selector.MatchExpressions) \u003e 0 {\n\t\t\treturn nil, fmt.Errorf(\"match expression %v not supported on this object\", selector.MatchExpressions)\n\t\t}\n\t\tdst := make(map[string]string)\n\t\tfor label, value := range selector.MatchLabels {\n\t\t\tdst[label] = value\n\t\t}\n\t\treturn dst, nil\n\t}\n\tvar err error\n\tswitch t := obj.(type) {\n\tcase *v1.Service:\n\t\tt.Spec.Selector, err = copyOldSelector()\n\tdefault:\n\t\terr = fmt.Errorf(\"setting a selector is only supported for Services\")\n\t}\n\treturn err\n}","line":{"from":227,"to":246}} {"id":100032153,"name":"getResourcesAndSelector","signature":"func getResourcesAndSelector(args []string) (resources []string, selector *metav1.LabelSelector, err error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_selector.go","code":"// getResourcesAndSelector retrieves resources and the selector expression from the given args (assuming selectors the last arg)\nfunc getResourcesAndSelector(args []string) (resources []string, selector *metav1.LabelSelector, err error) {\n\tif len(args) == 0 {\n\t\treturn []string{}, nil, nil\n\t}\n\tresources = args[:len(args)-1]\n\tselector, err = metav1.ParseToLabelSelector(args[len(args)-1])\n\treturn resources, selector, err\n}","line":{"from":248,"to":256}} {"id":100032154,"name":"NewSetServiceAccountOptions","signature":"func NewSetServiceAccountOptions(streams genericclioptions.IOStreams) *SetServiceAccountOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_serviceaccount.go","code":"// NewSetServiceAccountOptions returns an initialized SetServiceAccountOptions instance\nfunc NewSetServiceAccountOptions(streams genericclioptions.IOStreams) *SetServiceAccountOptions {\n\treturn \u0026SetServiceAccountOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"serviceaccount updated\").WithTypeSetter(scheme.Scheme),\n\t\tRecordFlags: genericclioptions.NewRecordFlags(),\n\n\t\tRecorder: genericclioptions.NoopRecorder{},\n\n\t\tIOStreams: streams,\n\t}\n}","line":{"from":81,"to":91}} {"id":100032155,"name":"NewCmdServiceAccount","signature":"func NewCmdServiceAccount(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_serviceaccount.go","code":"// NewCmdServiceAccount returns the \"set serviceaccount\" command.\nfunc NewCmdServiceAccount(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\to := NewSetServiceAccountOptions(streams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"serviceaccount (-f FILENAME | TYPE NAME) SERVICE_ACCOUNT\",\n\t\tDisableFlagsInUseLine: true,\n\t\tAliases: []string{\"sa\"},\n\t\tShort: i18n.T(\"Update the service account of a resource\"),\n\t\tLong: serviceaccountLong,\n\t\tExample: serviceaccountExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\to.RecordFlags.AddFlags(cmd)\n\n\tusage := \"identifying the resource to get from a server.\"\n\tcmdutil.AddFilenameOptionFlags(cmd, \u0026o.fileNameOptions, usage)\n\tcmd.Flags().BoolVar(\u0026o.all, \"all\", o.all, \"Select all resources, in the namespace of the specified resource types\")\n\tcmd.Flags().BoolVar(\u0026o.local, \"local\", o.local, \"If true, set serviceaccount will NOT contact api-server but run locally.\")\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.fieldManager, \"kubectl-set\")\n\treturn cmd\n}","line":{"from":93,"to":120}} {"id":100032156,"name":"Complete","signature":"func (o *SetServiceAccountOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_serviceaccount.go","code":"// Complete configures serviceAccountConfig from command line args.\nfunc (o *SetServiceAccountOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\n\to.RecordFlags.Complete(cmd)\n\to.Recorder, err = o.RecordFlags.ToRecorder()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.shortOutput = cmdutil.GetFlagString(cmd, \"output\") == \"name\"\n\to.dryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif o.local \u0026\u0026 o.dryRunStrategy == cmdutil.DryRunServer {\n\t\treturn fmt.Errorf(\"cannot specify --local and --dry-run=server - did you mean --dry-run=client?\")\n\t}\n\to.output = cmdutil.GetFlagString(cmd, \"output\")\n\to.updatePodSpecForObject = polymorphichelpers.UpdatePodSpecForObjectFn\n\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.dryRunStrategy)\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.PrintObj = printer.PrintObj\n\n\tcmdNamespace, enforceNamespace, err := f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(args) == 0 {\n\t\treturn errors.New(\"serviceaccount is required\")\n\t}\n\to.serviceAccountName = args[len(args)-1]\n\tresources := args[:len(args)-1]\n\tbuilder := f.NewBuilder().\n\t\tWithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).\n\t\tLocalParam(o.local).\n\t\tContinueOnError().\n\t\tNamespaceParam(cmdNamespace).DefaultNamespace().\n\t\tFilenameParam(enforceNamespace, \u0026o.fileNameOptions).\n\t\tFlatten()\n\tif !o.local {\n\t\tbuilder.ResourceTypeOrNameArgs(o.all, resources...).\n\t\t\tLatest()\n\t}\n\to.infos, err = builder.Do().Infos()\n\treturn err\n}","line":{"from":122,"to":172}} {"id":100032157,"name":"Run","signature":"func (o *SetServiceAccountOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_serviceaccount.go","code":"// Run creates and applies the patch either locally or calling apiserver.\nfunc (o *SetServiceAccountOptions) Run() error {\n\tpatchErrs := []error{}\n\tpatchFn := func(obj runtime.Object) ([]byte, error) {\n\t\t_, err := o.updatePodSpecForObject(obj, func(podSpec *v1.PodSpec) error {\n\t\t\tpodSpec.ServiceAccountName = o.serviceAccountName\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// record this change (for rollout history)\n\t\tif err := o.Recorder.Record(obj); err != nil {\n\t\t\tklog.V(4).Infof(\"error recording current command: %v\", err)\n\t\t}\n\n\t\treturn runtime.Encode(scheme.DefaultJSONEncoder(), obj)\n\t}\n\n\tpatches := CalculatePatches(o.infos, scheme.DefaultJSONEncoder(), patchFn)\n\tfor _, patch := range patches {\n\t\tinfo := patch.Info\n\t\tname := info.ObjectName()\n\t\tif patch.Err != nil {\n\t\t\tpatchErrs = append(patchErrs, fmt.Errorf(\"error: %s %v\\n\", name, patch.Err))\n\t\t\tcontinue\n\t\t}\n\t\tif o.local || o.dryRunStrategy == cmdutil.DryRunClient {\n\t\t\tif err := o.PrintObj(info.Object, o.Out); err != nil {\n\t\t\t\tpatchErrs = append(patchErrs, err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tactual, err := resource.\n\t\t\tNewHelper(info.Client, info.Mapping).\n\t\t\tDryRun(o.dryRunStrategy == cmdutil.DryRunServer).\n\t\t\tWithFieldManager(o.fieldManager).\n\t\t\tPatch(info.Namespace, info.Name, types.StrategicMergePatchType, patch.Patch, nil)\n\t\tif err != nil {\n\t\t\tpatchErrs = append(patchErrs, fmt.Errorf(\"failed to patch ServiceAccountName %v\", err))\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := o.PrintObj(actual, o.Out); err != nil {\n\t\t\tpatchErrs = append(patchErrs, err)\n\t\t}\n\t}\n\treturn utilerrors.NewAggregate(patchErrs)\n}","line":{"from":174,"to":222}} {"id":100032158,"name":"NewSubjectOptions","signature":"func NewSubjectOptions(streams genericclioptions.IOStreams) *SubjectOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_subject.go","code":"// NewSubjectOptions returns an initialized SubjectOptions instance\nfunc NewSubjectOptions(streams genericclioptions.IOStreams) *SubjectOptions {\n\treturn \u0026SubjectOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"subjects updated\").WithTypeSetter(scheme.Scheme),\n\n\t\tIOStreams: streams,\n\t}\n}","line":{"from":83,"to":90}} {"id":100032159,"name":"NewCmdSubject","signature":"func NewCmdSubject(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_subject.go","code":"// NewCmdSubject returns the \"new subject\" sub command\nfunc NewCmdSubject(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\to := NewSubjectOptions(streams)\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"subject (-f FILENAME | TYPE NAME) [--user=username] [--group=groupname] [--serviceaccount=namespace:serviceaccountname] [--dry-run=server|client|none]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Update the user, group, or service account in a role binding or cluster role binding\"),\n\t\tLong: subjectLong,\n\t\tExample: subjectExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run(addSubjects))\n\t\t},\n\t}\n\n\to.PrintFlags.AddFlags(cmd)\n\n\tcmdutil.AddFilenameOptionFlags(cmd, \u0026o.FilenameOptions, \"the resource to update the subjects\")\n\tcmd.Flags().BoolVar(\u0026o.All, \"all\", o.All, \"Select all resources, in the namespace of the specified resource types\")\n\tcmdutil.AddLabelSelectorFlagVar(cmd, \u0026o.Selector)\n\tcmd.Flags().BoolVar(\u0026o.Local, \"local\", o.Local, \"If true, set subject will NOT contact api-server but run locally.\")\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmd.Flags().StringArrayVar(\u0026o.Users, \"user\", o.Users, \"Usernames to bind to the role\")\n\tcmd.Flags().StringArrayVar(\u0026o.Groups, \"group\", o.Groups, \"Groups to bind to the role\")\n\tcmd.Flags().StringArrayVar(\u0026o.ServiceAccounts, \"serviceaccount\", o.ServiceAccounts, \"Service accounts to bind to the role\")\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026o.fieldManager, \"kubectl-set\")\n\treturn cmd\n}","line":{"from":92,"to":120}} {"id":100032160,"name":"Complete","signature":"func (o *SubjectOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_subject.go","code":"// Complete completes all required options\nfunc (o *SubjectOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\to.Output = cmdutil.GetFlagString(cmd, \"output\")\n\tvar err error\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.PrintObj = printer.PrintObj\n\n\tvar enforceNamespace bool\n\to.namespace, enforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbuilder := f.NewBuilder().\n\t\tWithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).\n\t\tLocalParam(o.Local).\n\t\tContinueOnError().\n\t\tNamespaceParam(o.namespace).DefaultNamespace().\n\t\tFilenameParam(enforceNamespace, \u0026o.FilenameOptions).\n\t\tFlatten()\n\n\tif o.Local {\n\t\t// if a --local flag was provided, and a resource was specified in the form\n\t\t// \u003cresource\u003e/\u003cname\u003e, fail immediately as --local cannot query the api server\n\t\t// for the specified resource.\n\t\tif len(args) \u003e 0 {\n\t\t\treturn resource.LocalResourceError\n\t\t}\n\t} else {\n\t\tbuilder = builder.\n\t\t\tLabelSelectorParam(o.Selector).\n\t\t\tResourceTypeOrNameArgs(o.All, args...).\n\t\t\tLatest()\n\t}\n\n\to.Infos, err = builder.Do().Infos()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":122,"to":172}} {"id":100032161,"name":"Validate","signature":"func (o *SubjectOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_subject.go","code":"// Validate makes sure provided values in SubjectOptions are valid\nfunc (o *SubjectOptions) Validate() error {\n\tif o.Local \u0026\u0026 o.DryRunStrategy == cmdutil.DryRunServer {\n\t\treturn fmt.Errorf(\"cannot specify --local and --dry-run=server - did you mean --dry-run=client?\")\n\t}\n\tif o.All \u0026\u0026 len(o.Selector) \u003e 0 {\n\t\treturn fmt.Errorf(\"cannot set --all and --selector at the same time\")\n\t}\n\tif len(o.Users) == 0 \u0026\u0026 len(o.Groups) == 0 \u0026\u0026 len(o.ServiceAccounts) == 0 {\n\t\treturn fmt.Errorf(\"you must specify at least one value of user, group or serviceaccount\")\n\t}\n\n\tfor _, sa := range o.ServiceAccounts {\n\t\ttokens := strings.Split(sa, \":\")\n\t\tif len(tokens) != 2 || tokens[1] == \"\" {\n\t\t\treturn fmt.Errorf(\"serviceaccount must be \u003cnamespace\u003e:\u003cname\u003e\")\n\t\t}\n\n\t\tfor _, info := range o.Infos {\n\t\t\t_, ok := info.Object.(*rbacv1.ClusterRoleBinding)\n\t\t\tif ok \u0026\u0026 tokens[0] == \"\" {\n\t\t\t\treturn fmt.Errorf(\"serviceaccount must be \u003cnamespace\u003e:\u003cname\u003e, namespace must be specified\")\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":174,"to":201}} {"id":100032162,"name":"Run","signature":"func (o *SubjectOptions) Run(fn updateSubjects) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_subject.go","code":"// Run performs the execution of \"set subject\" sub command\nfunc (o *SubjectOptions) Run(fn updateSubjects) error {\n\tpatches := CalculatePatches(o.Infos, scheme.DefaultJSONEncoder(), func(obj runtime.Object) ([]byte, error) {\n\t\tsubjects := []rbacv1.Subject{}\n\t\tfor _, user := range sets.NewString(o.Users...).List() {\n\t\t\tsubject := rbacv1.Subject{\n\t\t\t\tKind: rbacv1.UserKind,\n\t\t\t\tAPIGroup: rbacv1.GroupName,\n\t\t\t\tName: user,\n\t\t\t}\n\t\t\tsubjects = append(subjects, subject)\n\t\t}\n\t\tfor _, group := range sets.NewString(o.Groups...).List() {\n\t\t\tsubject := rbacv1.Subject{\n\t\t\t\tKind: rbacv1.GroupKind,\n\t\t\t\tAPIGroup: rbacv1.GroupName,\n\t\t\t\tName: group,\n\t\t\t}\n\t\t\tsubjects = append(subjects, subject)\n\t\t}\n\t\tfor _, sa := range sets.NewString(o.ServiceAccounts...).List() {\n\t\t\ttokens := strings.Split(sa, \":\")\n\t\t\tnamespace := tokens[0]\n\t\t\tname := tokens[1]\n\t\t\tif len(namespace) == 0 {\n\t\t\t\tnamespace = o.namespace\n\t\t\t}\n\t\t\tsubject := rbacv1.Subject{\n\t\t\t\tKind: rbacv1.ServiceAccountKind,\n\t\t\t\tNamespace: namespace,\n\t\t\t\tName: name,\n\t\t\t}\n\t\t\tsubjects = append(subjects, subject)\n\t\t}\n\n\t\ttransformed, err := updateSubjectForObject(obj, subjects, fn)\n\t\tif transformed \u0026\u0026 err == nil {\n\t\t\t// TODO: switch UpdatePodSpecForObject to work on v1.PodSpec\n\t\t\treturn runtime.Encode(scheme.DefaultJSONEncoder(), obj)\n\t\t}\n\t\treturn nil, err\n\t})\n\n\tallErrs := []error{}\n\tfor _, patch := range patches {\n\t\tinfo := patch.Info\n\t\tname := info.ObjectName()\n\t\tif patch.Err != nil {\n\t\t\tallErrs = append(allErrs, fmt.Errorf(\"error: %s %v\\n\", name, patch.Err))\n\t\t\tcontinue\n\t\t}\n\n\t\t//no changes\n\t\tif string(patch.Patch) == \"{}\" || len(patch.Patch) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif o.Local || o.DryRunStrategy == cmdutil.DryRunClient {\n\t\t\tif err := o.PrintObj(info.Object, o.Out); err != nil {\n\t\t\t\tallErrs = append(allErrs, err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tactual, err := resource.\n\t\t\tNewHelper(info.Client, info.Mapping).\n\t\t\tDryRun(o.DryRunStrategy == cmdutil.DryRunServer).\n\t\t\tWithFieldManager(o.fieldManager).\n\t\t\tPatch(info.Namespace, info.Name, types.StrategicMergePatchType, patch.Patch, nil)\n\t\tif err != nil {\n\t\t\tallErrs = append(allErrs, fmt.Errorf(\"failed to patch subjects to rolebinding: %v\", err))\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := o.PrintObj(actual, o.Out); err != nil {\n\t\t\tallErrs = append(allErrs, err)\n\t\t}\n\t}\n\treturn utilerrors.NewAggregate(allErrs)\n}","line":{"from":203,"to":282}} {"id":100032163,"name":"updateSubjectForObject","signature":"func updateSubjectForObject(obj runtime.Object, subjects []rbacv1.Subject, fn updateSubjects) (bool, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_subject.go","code":"// Note: the obj mutates in the function\nfunc updateSubjectForObject(obj runtime.Object, subjects []rbacv1.Subject, fn updateSubjects) (bool, error) {\n\tswitch t := obj.(type) {\n\tcase *rbacv1.RoleBinding:\n\t\ttransformed, result := fn(t.Subjects, subjects)\n\t\tt.Subjects = result\n\t\treturn transformed, nil\n\tcase *rbacv1.ClusterRoleBinding:\n\t\ttransformed, result := fn(t.Subjects, subjects)\n\t\tt.Subjects = result\n\t\treturn transformed, nil\n\tdefault:\n\t\treturn false, fmt.Errorf(\"setting subjects is only supported for RoleBinding/ClusterRoleBinding\")\n\t}\n}","line":{"from":284,"to":298}} {"id":100032164,"name":"addSubjects","signature":"func addSubjects(existings []rbacv1.Subject, targets []rbacv1.Subject) (bool, []rbacv1.Subject)","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_subject.go","code":"func addSubjects(existings []rbacv1.Subject, targets []rbacv1.Subject) (bool, []rbacv1.Subject) {\n\ttransformed := false\n\tupdated := existings\n\tfor _, item := range targets {\n\t\tif !contain(existings, item) {\n\t\t\tupdated = append(updated, item)\n\t\t\ttransformed = true\n\t\t}\n\t}\n\treturn transformed, updated\n}","line":{"from":300,"to":310}} {"id":100032165,"name":"contain","signature":"func contain(slice []rbacv1.Subject, item rbacv1.Subject) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/set/set_subject.go","code":"func contain(slice []rbacv1.Subject, item rbacv1.Subject) bool {\n\tfor _, v := range slice {\n\t\tif v == item {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":312,"to":319}} {"id":100032166,"name":"shouldSkipOnLookPathErr","signature":"func shouldSkipOnLookPathErr(err error) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/skiplookerr_go118.go","code":"func shouldSkipOnLookPathErr(err error) bool {\n\treturn err != nil\n}","line":{"from":22,"to":24}} {"id":100032167,"name":"shouldSkipOnLookPathErr","signature":"func shouldSkipOnLookPathErr(err error) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/skiplookerr_go119.go","code":"func shouldSkipOnLookPathErr(err error) bool {\n\treturn err != nil \u0026\u0026 !errors.Is(err, exec.ErrDot)\n}","line":{"from":27,"to":29}} {"id":100032168,"name":"NewCmdTaint","signature":"func NewCmdTaint(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/taint/taint.go","code":"func NewCmdTaint(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\toptions := \u0026TaintOptions{\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"tainted\").WithTypeSetter(scheme.Scheme),\n\t\tIOStreams: streams,\n\t}\n\n\tvalidArgs := []string{\"node\"}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"taint NODE NAME KEY_1=VAL_1:TAINT_EFFECT_1 ... KEY_N=VAL_N:TAINT_EFFECT_N\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Update the taints on one or more nodes\"),\n\t\tLong: fmt.Sprintf(taintLong, validation.DNS1123SubdomainMaxLength, validation.LabelValueMaxLength),\n\t\tExample: taintExample,\n\t\tValidArgsFunction: completion.SpecifiedResourceTypeAndNameCompletionFunc(f, validArgs),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(options.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(options.Validate())\n\t\t\tcmdutil.CheckErr(options.RunTaint())\n\t\t},\n\t}\n\n\toptions.PrintFlags.AddFlags(cmd)\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmdutil.AddLabelSelectorFlagVar(cmd, \u0026options.selector)\n\tcmd.Flags().BoolVar(\u0026options.overwrite, \"overwrite\", options.overwrite, \"If true, allow taints to be overwritten, otherwise reject taint updates that overwrite existing taints.\")\n\tcmd.Flags().BoolVar(\u0026options.all, \"all\", options.all, \"Select all nodes in the cluster\")\n\tcmdutil.AddFieldManagerFlagVar(cmd, \u0026options.fieldManager, \"kubectl-taint\")\n\treturn cmd\n}","line":{"from":98,"to":128}} {"id":100032169,"name":"Complete","signature":"func (o *TaintOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) (err error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/taint/taint.go","code":"// Complete adapts from the command line args and factory to the data required.\nfunc (o *TaintOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) (err error) {\n\tnamespace, _, err := f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Mapper, err = f.ToRESTMapper()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)\n\n\to.ValidationDirective, err = cmdutil.GetValidationDirective(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// retrieves resource and taint args from args\n\t// also checks args to verify that all resources are specified before taints\n\ttaintArgs := []string{}\n\tmetTaintArg := false\n\tfor _, s := range args {\n\t\tisTaint := strings.Contains(s, \"=\") || strings.Contains(s, \":\") || strings.HasSuffix(s, \"-\")\n\t\tswitch {\n\t\tcase !metTaintArg \u0026\u0026 isTaint:\n\t\t\tmetTaintArg = true\n\t\t\tfallthrough\n\t\tcase metTaintArg \u0026\u0026 isTaint:\n\t\t\ttaintArgs = append(taintArgs, s)\n\t\tcase !metTaintArg \u0026\u0026 !isTaint:\n\t\t\to.resources = append(o.resources, s)\n\t\tcase metTaintArg \u0026\u0026 !isTaint:\n\t\t\treturn fmt.Errorf(\"all resources must be specified before taint changes: %s\", s)\n\t\t}\n\t}\n\n\to.ToPrinter = func(operation string) (printers.ResourcePrinter, error) {\n\t\to.PrintFlags.NamePrintFlags.Operation = operation\n\t\treturn o.PrintFlags.ToPrinter()\n\t}\n\n\tif len(o.resources) \u003c 1 {\n\t\treturn fmt.Errorf(\"one or more resources must be specified as \u003cresource\u003e \u003cname\u003e\")\n\t}\n\tif len(taintArgs) \u003c 1 {\n\t\treturn fmt.Errorf(\"at least one taint update is required\")\n\t}\n\n\tif o.taintsToAdd, o.taintsToRemove, err = parseTaints(taintArgs); err != nil {\n\t\treturn cmdutil.UsageErrorf(cmd, err.Error())\n\t}\n\to.builder = f.NewBuilder().\n\t\tWithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).\n\t\tContinueOnError().\n\t\tNamespaceParam(namespace).DefaultNamespace()\n\tif o.selector != \"\" {\n\t\to.builder = o.builder.LabelSelectorParam(o.selector).ResourceTypes(\"node\")\n\t}\n\tif o.all {\n\t\to.builder = o.builder.SelectAllParam(o.all).ResourceTypes(\"node\").Flatten().Latest()\n\t}\n\tif !o.all \u0026\u0026 o.selector == \"\" \u0026\u0026 len(o.resources) \u003e= 2 {\n\t\to.builder = o.builder.ResourceNames(\"node\", o.resources[1:]...)\n\t}\n\to.builder = o.builder.LabelSelectorParam(o.selector).\n\t\tFlatten().\n\t\tLatest()\n\n\to.ClientForMapping = f.ClientForMapping\n\treturn nil\n}","line":{"from":130,"to":206}} {"id":100032170,"name":"validateFlags","signature":"func (o TaintOptions) validateFlags() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/taint/taint.go","code":"// validateFlags checks for the validation of flags for kubectl taints.\nfunc (o TaintOptions) validateFlags() error {\n\t// Cannot have a non-empty selector and all flag set. They are mutually exclusive.\n\tif o.all \u0026\u0026 o.selector != \"\" {\n\t\treturn fmt.Errorf(\"setting 'all' parameter with a non empty selector is prohibited\")\n\t}\n\t// If both selector and all are not set.\n\tif !o.all \u0026\u0026 o.selector == \"\" {\n\t\tif len(o.resources) \u003c 2 {\n\t\t\treturn fmt.Errorf(\"at least one resource name must be specified since 'all' parameter is not set\")\n\t\t} else {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":208,"to":223}} {"id":100032171,"name":"Validate","signature":"func (o TaintOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/taint/taint.go","code":"// Validate checks to the TaintOptions to see if there is sufficient information run the command.\nfunc (o TaintOptions) Validate() error {\n\tresourceType := strings.ToLower(o.resources[0])\n\tfullySpecifiedGVR, _, err := explain.SplitAndParseResourceRequest(resourceType, o.Mapper)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgvk, err := o.Mapper.KindFor(fullySpecifiedGVR)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif gvk.Kind != \"Node\" {\n\t\treturn fmt.Errorf(\"invalid resource type %s, only node types are supported\", resourceType)\n\t}\n\n\t// check the format of taint args and checks removed taints aren't in the new taints list\n\tvar conflictTaints []string\n\tfor _, taintAdd := range o.taintsToAdd {\n\t\tfor _, taintRemove := range o.taintsToRemove {\n\t\t\tif taintAdd.Key != taintRemove.Key {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(taintRemove.Effect) == 0 || taintAdd.Effect == taintRemove.Effect {\n\t\t\t\tconflictTaint := fmt.Sprintf(\"%s=%s\", taintRemove.Key, taintRemove.Effect)\n\t\t\t\tconflictTaints = append(conflictTaints, conflictTaint)\n\t\t\t}\n\t\t}\n\t}\n\tif len(conflictTaints) \u003e 0 {\n\t\treturn fmt.Errorf(\"can not both modify and remove the following taint(s) in the same command: %s\", strings.Join(conflictTaints, \", \"))\n\t}\n\treturn o.validateFlags()\n}","line":{"from":225,"to":259}} {"id":100032172,"name":"RunTaint","signature":"func (o TaintOptions) RunTaint() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/taint/taint.go","code":"// RunTaint does the work\nfunc (o TaintOptions) RunTaint() error {\n\tr := o.builder.Do()\n\tif err := r.Err(); err != nil {\n\t\treturn err\n\t}\n\n\treturn r.Visit(func(info *resource.Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tobj := info.Object\n\t\tname, namespace := info.Name, info.Namespace\n\t\toldData, err := json.Marshal(obj)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\toperation, err := o.updateTaints(obj)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnewData, err := json.Marshal(obj)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpatchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, obj)\n\t\tcreatedPatch := err == nil\n\t\tif err != nil {\n\t\t\tklog.V(2).Infof(\"couldn't compute patch: %v\", err)\n\t\t}\n\n\t\tprinter, err := o.ToPrinter(operation)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif o.DryRunStrategy == cmdutil.DryRunClient {\n\t\t\tif createdPatch {\n\t\t\t\ttypedObj, err := scheme.Scheme.ConvertToVersion(info.Object, info.Mapping.GroupVersionKind.GroupVersion())\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tnodeObj, ok := typedObj.(*v1.Node)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn fmt.Errorf(\"unexpected type %T\", typedObj)\n\t\t\t\t}\n\n\t\t\t\toriginalObjJS, err := json.Marshal(nodeObj)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\toriginalPatchedObjJS, err := strategicpatch.StrategicMergePatch(originalObjJS, patchBytes, nodeObj)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\ttargetObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, originalPatchedObjJS)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn printer.PrintObj(targetObj, o.Out)\n\t\t\t}\n\t\t\treturn printer.PrintObj(obj, o.Out)\n\t\t}\n\n\t\tmapping := info.ResourceMapping()\n\t\tclient, err := o.ClientForMapping(mapping)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thelper := resource.\n\t\t\tNewHelper(client, mapping).\n\t\t\tDryRun(o.DryRunStrategy == cmdutil.DryRunServer).\n\t\t\tWithFieldManager(o.fieldManager).\n\t\t\tWithFieldValidation(o.ValidationDirective)\n\n\t\tvar outputObj runtime.Object\n\t\tif createdPatch {\n\t\t\toutputObj, err = helper.Patch(namespace, name, types.StrategicMergePatchType, patchBytes, nil)\n\t\t} else {\n\t\t\toutputObj, err = helper.Replace(namespace, name, false, obj)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn printer.PrintObj(outputObj, o.Out)\n\t})\n}","line":{"from":261,"to":351}} {"id":100032173,"name":"updateTaints","signature":"func (o TaintOptions) updateTaints(obj runtime.Object) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/taint/taint.go","code":"// updateTaints applies a taint option(o) to a node in cluster after computing the net effect of operation(i.e. does it result in an overwrite?), it reports back the end result in a way that user can easily interpret.\nfunc (o TaintOptions) updateTaints(obj runtime.Object) (string, error) {\n\tnode, ok := obj.(*v1.Node)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"unexpected type %T, expected Node\", obj)\n\t}\n\tif !o.overwrite {\n\t\tif exists := checkIfTaintsAlreadyExists(node.Spec.Taints, o.taintsToAdd); len(exists) != 0 {\n\t\t\treturn \"\", fmt.Errorf(\"node %s already has %v taint(s) with same effect(s) and --overwrite is false\", node.Name, exists)\n\t\t}\n\t}\n\toperation, newTaints, err := reorganizeTaints(node, o.overwrite, o.taintsToAdd, o.taintsToRemove)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tnode.Spec.Taints = newTaints\n\treturn operation, nil\n}","line":{"from":353,"to":370}} {"id":100032174,"name":"parseTaints","signature":"func parseTaints(spec []string) ([]corev1.Taint, []corev1.Taint, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/taint/utils.go","code":"// parseTaints takes a spec which is an array and creates slices for new taints to be added, taints to be deleted.\n// It also validates the spec. For example, the form `\u003ckey\u003e` may be used to remove a taint, but not to add one.\nfunc parseTaints(spec []string) ([]corev1.Taint, []corev1.Taint, error) {\n\tvar taints, taintsToRemove []corev1.Taint\n\tuniqueTaints := map[corev1.TaintEffect]sets.String{}\n\n\tfor _, taintSpec := range spec {\n\t\tif strings.HasSuffix(taintSpec, \"-\") {\n\t\t\ttaintToRemove, err := parseTaint(strings.TrimSuffix(taintSpec, \"-\"))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\ttaintsToRemove = append(taintsToRemove, corev1.Taint{Key: taintToRemove.Key, Effect: taintToRemove.Effect})\n\t\t} else {\n\t\t\tnewTaint, err := parseTaint(taintSpec)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\t// validate that the taint has an effect, which is required to add the taint\n\t\t\tif len(newTaint.Effect) == 0 {\n\t\t\t\treturn nil, nil, fmt.Errorf(\"invalid taint spec: %v\", taintSpec)\n\t\t\t}\n\t\t\t// validate if taint is unique by \u003ckey, effect\u003e\n\t\t\tif len(uniqueTaints[newTaint.Effect]) \u003e 0 \u0026\u0026 uniqueTaints[newTaint.Effect].Has(newTaint.Key) {\n\t\t\t\treturn nil, nil, fmt.Errorf(\"duplicated taints with the same key and effect: %v\", newTaint)\n\t\t\t}\n\t\t\t// add taint to existingTaints for uniqueness check\n\t\t\tif len(uniqueTaints[newTaint.Effect]) == 0 {\n\t\t\t\tuniqueTaints[newTaint.Effect] = sets.String{}\n\t\t\t}\n\t\t\tuniqueTaints[newTaint.Effect].Insert(newTaint.Key)\n\n\t\t\ttaints = append(taints, newTaint)\n\t\t}\n\t}\n\treturn taints, taintsToRemove, nil\n}","line":{"from":37,"to":73}} {"id":100032175,"name":"parseTaint","signature":"func parseTaint(st string) (corev1.Taint, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/taint/utils.go","code":"// parseTaint parses a taint from a string, whose form must be either\n// '\u003ckey\u003e=\u003cvalue\u003e:\u003ceffect\u003e', '\u003ckey\u003e:\u003ceffect\u003e', or '\u003ckey\u003e'.\nfunc parseTaint(st string) (corev1.Taint, error) {\n\tvar taint corev1.Taint\n\n\tvar key string\n\tvar value string\n\tvar effect corev1.TaintEffect\n\n\tparts := strings.Split(st, \":\")\n\tswitch len(parts) {\n\tcase 1:\n\t\tkey = parts[0]\n\tcase 2:\n\t\teffect = corev1.TaintEffect(parts[1])\n\t\tif err := validateTaintEffect(effect); err != nil {\n\t\t\treturn taint, err\n\t\t}\n\n\t\tpartsKV := strings.Split(parts[0], \"=\")\n\t\tif len(partsKV) \u003e 2 {\n\t\t\treturn taint, fmt.Errorf(\"invalid taint spec: %v\", st)\n\t\t}\n\t\tkey = partsKV[0]\n\t\tif len(partsKV) == 2 {\n\t\t\tvalue = partsKV[1]\n\t\t\tif errs := validation.IsValidLabelValue(value); len(errs) \u003e 0 {\n\t\t\t\treturn taint, fmt.Errorf(\"invalid taint spec: %v, %s\", st, strings.Join(errs, \"; \"))\n\t\t\t}\n\t\t}\n\tdefault:\n\t\treturn taint, fmt.Errorf(\"invalid taint spec: %v\", st)\n\t}\n\n\tif errs := validation.IsQualifiedName(key); len(errs) \u003e 0 {\n\t\treturn taint, fmt.Errorf(\"invalid taint spec: %v, %s\", st, strings.Join(errs, \"; \"))\n\t}\n\n\ttaint.Key = key\n\ttaint.Value = value\n\ttaint.Effect = effect\n\n\treturn taint, nil\n}","line":{"from":75,"to":118}} {"id":100032176,"name":"validateTaintEffect","signature":"func validateTaintEffect(effect corev1.TaintEffect) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/taint/utils.go","code":"func validateTaintEffect(effect corev1.TaintEffect) error {\n\tif effect != corev1.TaintEffectNoSchedule \u0026\u0026 effect != corev1.TaintEffectPreferNoSchedule \u0026\u0026 effect != corev1.TaintEffectNoExecute {\n\t\treturn fmt.Errorf(\"invalid taint effect: %v, unsupported taint effect\", effect)\n\t}\n\n\treturn nil\n}","line":{"from":120,"to":126}} {"id":100032177,"name":"reorganizeTaints","signature":"func reorganizeTaints(node *corev1.Node, overwrite bool, taintsToAdd []corev1.Taint, taintsToRemove []corev1.Taint) (string, []corev1.Taint, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/taint/utils.go","code":"// reorganizeTaints returns the updated set of taints, taking into account old taints that were not updated,\n// old taints that were updated, old taints that were deleted, and new taints.\nfunc reorganizeTaints(node *corev1.Node, overwrite bool, taintsToAdd []corev1.Taint, taintsToRemove []corev1.Taint) (string, []corev1.Taint, error) {\n\tnewTaints := append([]corev1.Taint{}, taintsToAdd...)\n\toldTaints := node.Spec.Taints\n\t// add taints that already existing but not updated to newTaints\n\tadded := addTaints(oldTaints, \u0026newTaints)\n\tallErrs, deleted := deleteTaints(taintsToRemove, \u0026newTaints)\n\tif (added \u0026\u0026 deleted) || overwrite {\n\t\treturn MODIFIED, newTaints, utilerrors.NewAggregate(allErrs)\n\t} else if added {\n\t\treturn TAINTED, newTaints, utilerrors.NewAggregate(allErrs)\n\t}\n\treturn UNTAINTED, newTaints, utilerrors.NewAggregate(allErrs)\n}","line":{"from":128,"to":142}} {"id":100032178,"name":"deleteTaints","signature":"func deleteTaints(taintsToRemove []corev1.Taint, newTaints *[]corev1.Taint) ([]error, bool)","file":"staging/src/k8s.io/kubectl/pkg/cmd/taint/utils.go","code":"// deleteTaints deletes the given taints from the node's taintlist.\nfunc deleteTaints(taintsToRemove []corev1.Taint, newTaints *[]corev1.Taint) ([]error, bool) {\n\tallErrs := []error{}\n\tvar removed bool\n\tfor _, taintToRemove := range taintsToRemove {\n\t\tif len(taintToRemove.Effect) \u003e 0 {\n\t\t\t*newTaints, removed = deleteTaint(*newTaints, \u0026taintToRemove)\n\t\t} else {\n\t\t\t*newTaints, removed = deleteTaintsByKey(*newTaints, taintToRemove.Key)\n\t\t}\n\t\tif !removed {\n\t\t\tallErrs = append(allErrs, fmt.Errorf(\"taint %q not found\", taintToRemove.ToString()))\n\t\t}\n\t}\n\treturn allErrs, removed\n}","line":{"from":144,"to":159}} {"id":100032179,"name":"addTaints","signature":"func addTaints(oldTaints []corev1.Taint, newTaints *[]corev1.Taint) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/taint/utils.go","code":"// addTaints adds the newTaints list to existing ones and updates the newTaints List.\n// TODO: This needs a rewrite to take only the new values instead of appended newTaints list to be consistent.\nfunc addTaints(oldTaints []corev1.Taint, newTaints *[]corev1.Taint) bool {\n\tfor _, oldTaint := range oldTaints {\n\t\texistsInNew := false\n\t\tfor _, taint := range *newTaints {\n\t\t\tif taint.MatchTaint(\u0026oldTaint) {\n\t\t\t\texistsInNew = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !existsInNew {\n\t\t\t*newTaints = append(*newTaints, oldTaint)\n\t\t}\n\t}\n\treturn len(oldTaints) != len(*newTaints)\n}","line":{"from":161,"to":177}} {"id":100032180,"name":"checkIfTaintsAlreadyExists","signature":"func checkIfTaintsAlreadyExists(oldTaints []corev1.Taint, taints []corev1.Taint) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/taint/utils.go","code":"// checkIfTaintsAlreadyExists checks if the node already has taints that we want to add and returns a string with taint keys.\nfunc checkIfTaintsAlreadyExists(oldTaints []corev1.Taint, taints []corev1.Taint) string {\n\tvar existingTaintList = make([]string, 0)\n\tfor _, taint := range taints {\n\t\tfor _, oldTaint := range oldTaints {\n\t\t\tif taint.Key == oldTaint.Key \u0026\u0026 taint.Effect == oldTaint.Effect {\n\t\t\t\texistingTaintList = append(existingTaintList, taint.Key)\n\t\t\t}\n\t\t}\n\t}\n\treturn strings.Join(existingTaintList, \",\")\n}","line":{"from":179,"to":190}} {"id":100032181,"name":"deleteTaintsByKey","signature":"func deleteTaintsByKey(taints []corev1.Taint, taintKey string) ([]corev1.Taint, bool)","file":"staging/src/k8s.io/kubectl/pkg/cmd/taint/utils.go","code":"// deleteTaintsByKey removes all the taints that have the same key to given taintKey\nfunc deleteTaintsByKey(taints []corev1.Taint, taintKey string) ([]corev1.Taint, bool) {\n\tnewTaints := []corev1.Taint{}\n\tfor i := range taints {\n\t\tif taintKey == taints[i].Key {\n\t\t\tcontinue\n\t\t}\n\t\tnewTaints = append(newTaints, taints[i])\n\t}\n\treturn newTaints, len(taints) != len(newTaints)\n}","line":{"from":192,"to":202}} {"id":100032182,"name":"deleteTaint","signature":"func deleteTaint(taints []corev1.Taint, taintToDelete *corev1.Taint) ([]corev1.Taint, bool)","file":"staging/src/k8s.io/kubectl/pkg/cmd/taint/utils.go","code":"// deleteTaint removes all the taints that have the same key and effect to given taintToDelete.\nfunc deleteTaint(taints []corev1.Taint, taintToDelete *corev1.Taint) ([]corev1.Taint, bool) {\n\tnewTaints := []corev1.Taint{}\n\tfor i := range taints {\n\t\tif taintToDelete.MatchTaint(\u0026taints[i]) {\n\t\t\tcontinue\n\t\t}\n\t\tnewTaints = append(newTaints, taints[i])\n\t}\n\treturn newTaints, len(taints) != len(newTaints)\n}","line":{"from":204,"to":214}} {"id":100032183,"name":"NewCmdTop","signature":"func NewCmdTop(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/top/top.go","code":"func NewCmdTop(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"top\",\n\t\tShort: i18n.T(\"Display resource (CPU/memory) usage\"),\n\t\tLong: topLong,\n\t\tRun: cmdutil.DefaultSubCommandRun(streams.ErrOut),\n\t}\n\n\t// create subcommands\n\tcmd.AddCommand(NewCmdTopNode(f, nil, streams))\n\tcmd.AddCommand(NewCmdTopPod(f, nil, streams))\n\n\treturn cmd\n}","line":{"from":47,"to":60}} {"id":100032184,"name":"SupportedMetricsAPIVersionAvailable","signature":"func SupportedMetricsAPIVersionAvailable(discoveredAPIGroups *metav1.APIGroupList) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/top/top.go","code":"func SupportedMetricsAPIVersionAvailable(discoveredAPIGroups *metav1.APIGroupList) bool {\n\tfor _, discoveredAPIGroup := range discoveredAPIGroups.Groups {\n\t\tif discoveredAPIGroup.Name != metricsapi.GroupName {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, version := range discoveredAPIGroup.Versions {\n\t\t\tfor _, supportedVersion := range supportedMetricsAPIVersions {\n\t\t\t\tif version.Version == supportedVersion {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":62,"to":76}} {"id":100032185,"name":"NewCmdTopNode","signature":"func NewCmdTopNode(f cmdutil.Factory, o *TopNodeOptions, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/top/top_node.go","code":"func NewCmdTopNode(f cmdutil.Factory, o *TopNodeOptions, streams genericclioptions.IOStreams) *cobra.Command {\n\tif o == nil {\n\t\to = \u0026TopNodeOptions{\n\t\t\tIOStreams: streams,\n\t\t\tUseProtocolBuffers: true,\n\t\t}\n\t}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"node [NAME | -l label]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Display resource (CPU/memory) usage of nodes\"),\n\t\tLong: topNodeLong,\n\t\tExample: topNodeExample,\n\t\tValidArgsFunction: completion.ResourceNameCompletionFunc(f, \"node\"),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.RunTopNode())\n\t\t},\n\t\tAliases: []string{\"nodes\", \"no\"},\n\t}\n\tcmdutil.AddLabelSelectorFlagVar(cmd, \u0026o.Selector)\n\tcmd.Flags().StringVar(\u0026o.SortBy, \"sort-by\", o.SortBy, \"If non-empty, sort nodes list using specified field. The field can be either 'cpu' or 'memory'.\")\n\tcmd.Flags().BoolVar(\u0026o.NoHeaders, \"no-headers\", o.NoHeaders, \"If present, print output without headers\")\n\tcmd.Flags().BoolVar(\u0026o.UseProtocolBuffers, \"use-protocol-buffers\", o.UseProtocolBuffers, \"Enables using protocol-buffers to access Metrics API.\")\n\tcmd.Flags().BoolVar(\u0026o.ShowCapacity, \"show-capacity\", o.ShowCapacity, \"Print node resources based on Capacity instead of Allocatable(default) of the nodes.\")\n\n\treturn cmd\n}","line":{"from":71,"to":100}} {"id":100032186,"name":"Complete","signature":"func (o *TopNodeOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/top/top_node.go","code":"func (o *TopNodeOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tif len(args) == 1 {\n\t\to.ResourceName = args[0]\n\t} else if len(args) \u003e 1 {\n\t\treturn cmdutil.UsageErrorf(cmd, \"%s\", cmd.Use)\n\t}\n\n\tclientset, err := f.KubernetesClientSet()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.DiscoveryClient = clientset.DiscoveryClient\n\n\tconfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif o.UseProtocolBuffers {\n\t\tconfig.ContentType = \"application/vnd.kubernetes.protobuf\"\n\t}\n\to.MetricsClient, err = metricsclientset.NewForConfig(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.NodeClient = clientset.CoreV1()\n\n\to.Printer = metricsutil.NewTopCmdPrinter(o.Out)\n\treturn nil\n}","line":{"from":102,"to":132}} {"id":100032187,"name":"Validate","signature":"func (o *TopNodeOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/top/top_node.go","code":"func (o *TopNodeOptions) Validate() error {\n\tif len(o.SortBy) \u003e 0 {\n\t\tif o.SortBy != sortByCPU \u0026\u0026 o.SortBy != sortByMemory {\n\t\t\treturn errors.New(\"--sort-by accepts only cpu or memory\")\n\t\t}\n\t}\n\tif len(o.ResourceName) \u003e 0 \u0026\u0026 len(o.Selector) \u003e 0 {\n\t\treturn errors.New(\"only one of NAME or --selector can be provided\")\n\t}\n\treturn nil\n}","line":{"from":134,"to":144}} {"id":100032188,"name":"RunTopNode","signature":"func (o TopNodeOptions) RunTopNode() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/top/top_node.go","code":"func (o TopNodeOptions) RunTopNode() error {\n\tvar err error\n\tselector := labels.Everything()\n\tif len(o.Selector) \u003e 0 {\n\t\tselector, err = labels.Parse(o.Selector)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tapiGroups, err := o.DiscoveryClient.ServerGroups()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmetricsAPIAvailable := SupportedMetricsAPIVersionAvailable(apiGroups)\n\n\tif !metricsAPIAvailable {\n\t\treturn errors.New(\"Metrics API not available\")\n\t}\n\n\tmetrics, err := getNodeMetricsFromMetricsAPI(o.MetricsClient, o.ResourceName, selector)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(metrics.Items) == 0 {\n\t\treturn errors.New(\"metrics not available yet\")\n\t}\n\n\tvar nodes []v1.Node\n\tif len(o.ResourceName) \u003e 0 {\n\t\tnode, err := o.NodeClient.Nodes().Get(context.TODO(), o.ResourceName, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnodes = append(nodes, *node)\n\t} else {\n\t\tnodeList, err := o.NodeClient.Nodes().List(context.TODO(), metav1.ListOptions{\n\t\t\tLabelSelector: selector.String(),\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnodes = append(nodes, nodeList.Items...)\n\t}\n\n\tavailableResources := make(map[string]v1.ResourceList)\n\n\tfor _, n := range nodes {\n\t\tif !o.ShowCapacity {\n\t\t\tavailableResources[n.Name] = n.Status.Allocatable\n\t\t} else {\n\t\t\tavailableResources[n.Name] = n.Status.Capacity\n\t\t}\n\t}\n\n\treturn o.Printer.PrintNodeMetrics(metrics.Items, availableResources, o.NoHeaders, o.SortBy)\n}","line":{"from":146,"to":204}} {"id":100032189,"name":"getNodeMetricsFromMetricsAPI","signature":"func getNodeMetricsFromMetricsAPI(metricsClient metricsclientset.Interface, resourceName string, selector labels.Selector) (*metricsapi.NodeMetricsList, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/top/top_node.go","code":"func getNodeMetricsFromMetricsAPI(metricsClient metricsclientset.Interface, resourceName string, selector labels.Selector) (*metricsapi.NodeMetricsList, error) {\n\tvar err error\n\tversionedMetrics := \u0026metricsV1beta1api.NodeMetricsList{}\n\tmc := metricsClient.MetricsV1beta1()\n\tnm := mc.NodeMetricses()\n\tif resourceName != \"\" {\n\t\tm, err := nm.Get(context.TODO(), resourceName, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tversionedMetrics.Items = []metricsV1beta1api.NodeMetrics{*m}\n\t} else {\n\t\tversionedMetrics, err = nm.List(context.TODO(), metav1.ListOptions{LabelSelector: selector.String()})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tmetrics := \u0026metricsapi.NodeMetricsList{}\n\terr = metricsV1beta1api.Convert_v1beta1_NodeMetricsList_To_metrics_NodeMetricsList(versionedMetrics, metrics, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn metrics, nil\n}","line":{"from":206,"to":229}} {"id":100032190,"name":"NewCmdTopPod","signature":"func NewCmdTopPod(f cmdutil.Factory, o *TopPodOptions, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/top/top_pod.go","code":"func NewCmdTopPod(f cmdutil.Factory, o *TopPodOptions, streams genericclioptions.IOStreams) *cobra.Command {\n\tif o == nil {\n\t\to = \u0026TopPodOptions{\n\t\t\tIOStreams: streams,\n\t\t\tUseProtocolBuffers: true,\n\t\t}\n\t}\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"pod [NAME | -l label]\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Display resource (CPU/memory) usage of pods\"),\n\t\tLong: topPodLong,\n\t\tExample: topPodExample,\n\t\tValidArgsFunction: completion.ResourceNameCompletionFunc(f, \"pod\"),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.RunTopPod())\n\t\t},\n\t\tAliases: []string{\"pods\", \"po\"},\n\t}\n\tcmdutil.AddLabelSelectorFlagVar(cmd, \u0026o.LabelSelector)\n\tcmd.Flags().StringVar(\u0026o.FieldSelector, \"field-selector\", o.FieldSelector, \"Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector key1=value1,key2=value2). The server only supports a limited number of field queries per type.\")\n\tcmd.Flags().StringVar(\u0026o.SortBy, \"sort-by\", o.SortBy, \"If non-empty, sort pods list using specified field. The field can be either 'cpu' or 'memory'.\")\n\tcmd.Flags().BoolVar(\u0026o.PrintContainers, \"containers\", o.PrintContainers, \"If present, print usage of containers within a pod.\")\n\tcmd.Flags().BoolVarP(\u0026o.AllNamespaces, \"all-namespaces\", \"A\", o.AllNamespaces, \"If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace.\")\n\tcmd.Flags().BoolVar(\u0026o.NoHeaders, \"no-headers\", o.NoHeaders, \"If present, print output without headers.\")\n\tcmd.Flags().BoolVar(\u0026o.UseProtocolBuffers, \"use-protocol-buffers\", o.UseProtocolBuffers, \"Enables using protocol-buffers to access Metrics API.\")\n\tcmd.Flags().BoolVar(\u0026o.Sum, \"sum\", o.Sum, \"Print the sum of the resource usage\")\n\treturn cmd\n}","line":{"from":90,"to":121}} {"id":100032191,"name":"Complete","signature":"func (o *TopPodOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/top/top_pod.go","code":"func (o *TopPodOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\tif len(args) == 1 {\n\t\to.ResourceName = args[0]\n\t} else if len(args) \u003e 1 {\n\t\treturn cmdutil.UsageErrorf(cmd, \"%s\", cmd.Use)\n\t}\n\n\to.Namespace, _, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\tclientset, err := f.KubernetesClientSet()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.DiscoveryClient = clientset.DiscoveryClient\n\tconfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif o.UseProtocolBuffers {\n\t\tconfig.ContentType = \"application/vnd.kubernetes.protobuf\"\n\t}\n\to.MetricsClient, err = metricsclientset.NewForConfig(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.PodClient = clientset.CoreV1()\n\n\to.Printer = metricsutil.NewTopCmdPrinter(o.Out)\n\treturn nil\n}","line":{"from":123,"to":157}} {"id":100032192,"name":"Validate","signature":"func (o *TopPodOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/top/top_pod.go","code":"func (o *TopPodOptions) Validate() error {\n\tif len(o.SortBy) \u003e 0 {\n\t\tif o.SortBy != sortByCPU \u0026\u0026 o.SortBy != sortByMemory {\n\t\t\treturn errors.New(\"--sort-by accepts only cpu or memory\")\n\t\t}\n\t}\n\tif len(o.ResourceName) \u003e 0 \u0026\u0026 (len(o.LabelSelector) \u003e 0 || len(o.FieldSelector) \u003e 0) {\n\t\treturn errors.New(\"only one of NAME or selector can be provided\")\n\t}\n\treturn nil\n}","line":{"from":159,"to":169}} {"id":100032193,"name":"RunTopPod","signature":"func (o TopPodOptions) RunTopPod() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/top/top_pod.go","code":"func (o TopPodOptions) RunTopPod() error {\n\tvar err error\n\tlabelSelector := labels.Everything()\n\tif len(o.LabelSelector) \u003e 0 {\n\t\tlabelSelector, err = labels.Parse(o.LabelSelector)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfieldSelector := fields.Everything()\n\tif len(o.FieldSelector) \u003e 0 {\n\t\tfieldSelector, err = fields.ParseSelector(o.FieldSelector)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tapiGroups, err := o.DiscoveryClient.ServerGroups()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmetricsAPIAvailable := SupportedMetricsAPIVersionAvailable(apiGroups)\n\n\tif !metricsAPIAvailable {\n\t\treturn errors.New(\"Metrics API not available\")\n\t}\n\tmetrics, err := getMetricsFromMetricsAPI(o.MetricsClient, o.Namespace, o.ResourceName, o.AllNamespaces, labelSelector, fieldSelector)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// First we check why no metrics have been received.\n\tif len(metrics.Items) == 0 {\n\t\t// If the API server query is successful but all the pods are newly created,\n\t\t// the metrics are probably not ready yet, so we return the error here in the first place.\n\t\terr := verifyEmptyMetrics(o, labelSelector, fieldSelector)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// if we had no errors, be sure we output something.\n\t\tif o.AllNamespaces {\n\t\t\tfmt.Fprintln(o.ErrOut, \"No resources found\")\n\t\t} else {\n\t\t\tfmt.Fprintf(o.ErrOut, \"No resources found in %s namespace.\\n\", o.Namespace)\n\t\t}\n\t}\n\n\treturn o.Printer.PrintPodMetrics(metrics.Items, o.PrintContainers, o.AllNamespaces, o.NoHeaders, o.SortBy, o.Sum)\n}","line":{"from":171,"to":221}} {"id":100032194,"name":"getMetricsFromMetricsAPI","signature":"func getMetricsFromMetricsAPI(metricsClient metricsclientset.Interface, namespace, resourceName string, allNamespaces bool, labelSelector labels.Selector, fieldSelector fields.Selector) (*metricsapi.PodMetricsList, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/top/top_pod.go","code":"func getMetricsFromMetricsAPI(metricsClient metricsclientset.Interface, namespace, resourceName string, allNamespaces bool, labelSelector labels.Selector, fieldSelector fields.Selector) (*metricsapi.PodMetricsList, error) {\n\tvar err error\n\tns := metav1.NamespaceAll\n\tif !allNamespaces {\n\t\tns = namespace\n\t}\n\tversionedMetrics := \u0026metricsv1beta1api.PodMetricsList{}\n\tif resourceName != \"\" {\n\t\tm, err := metricsClient.MetricsV1beta1().PodMetricses(ns).Get(context.TODO(), resourceName, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tversionedMetrics.Items = []metricsv1beta1api.PodMetrics{*m}\n\t} else {\n\t\tversionedMetrics, err = metricsClient.MetricsV1beta1().PodMetricses(ns).List(context.TODO(), metav1.ListOptions{LabelSelector: labelSelector.String(), FieldSelector: fieldSelector.String()})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tmetrics := \u0026metricsapi.PodMetricsList{}\n\terr = metricsv1beta1api.Convert_v1beta1_PodMetricsList_To_metrics_PodMetricsList(versionedMetrics, metrics, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn metrics, nil\n}","line":{"from":223,"to":248}} {"id":100032195,"name":"verifyEmptyMetrics","signature":"func verifyEmptyMetrics(o TopPodOptions, labelSelector labels.Selector, fieldSelector fields.Selector) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/top/top_pod.go","code":"func verifyEmptyMetrics(o TopPodOptions, labelSelector labels.Selector, fieldSelector fields.Selector) error {\n\tif len(o.ResourceName) \u003e 0 {\n\t\tpod, err := o.PodClient.Pods(o.Namespace).Get(context.TODO(), o.ResourceName, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := checkPodAge(pod); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tpods, err := o.PodClient.Pods(o.Namespace).List(context.TODO(), metav1.ListOptions{\n\t\t\tLabelSelector: labelSelector.String(),\n\t\t\tFieldSelector: fieldSelector.String(),\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(pods.Items) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\tfor _, pod := range pods.Items {\n\t\t\tif err := checkPodAge(\u0026pod); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn errors.New(\"metrics not available yet\")\n}","line":{"from":250,"to":277}} {"id":100032196,"name":"checkPodAge","signature":"func checkPodAge(pod *corev1.Pod) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/top/top_pod.go","code":"func checkPodAge(pod *corev1.Pod) error {\n\tage := time.Since(pod.CreationTimestamp.Time)\n\tif age \u003e metricsCreationDelay {\n\t\tmessage := fmt.Sprintf(\"Metrics not available for pod %s/%s, age: %s\", pod.Namespace, pod.Name, age.String())\n\t\treturn errors.New(message)\n\t} else {\n\t\tklog.V(2).Infof(\"Metrics not yet available for pod %s/%s, age: %s\", pod.Namespace, pod.Name, age.String())\n\t\treturn nil\n\t}\n}","line":{"from":279,"to":288}} {"id":100032197,"name":"NewCRLFWriter","signature":"func NewCRLFWriter(w io.Writer) io.Writer","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/crlf/crlf.go","code":"// NewCRLFWriter implements a CR/LF line ending writer used for normalizing\n// text for Windows platforms.\nfunc NewCRLFWriter(w io.Writer) io.Writer {\n\treturn crlfWriter{w}\n}","line":{"from":28,"to":32}} {"id":100032198,"name":"Write","signature":"func (w crlfWriter) Write(b []byte) (n int, err error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/crlf/crlf.go","code":"func (w crlfWriter) Write(b []byte) (n int, err error) {\n\tfor i, written := 0, 0; ; {\n\t\tnext := bytes.Index(b[i:], []byte(\"\\n\"))\n\t\tif next == -1 {\n\t\t\tn, err := w.Writer.Write(b[i:])\n\t\t\treturn written + n, err\n\t\t}\n\t\tnext = next + i\n\t\tn, err := w.Writer.Write(b[i:next])\n\t\tif err != nil {\n\t\t\treturn written + n, err\n\t\t}\n\t\twritten += n\n\t\tn, err = w.Writer.Write([]byte(\"\\r\\n\"))\n\t\tif err != nil {\n\t\t\tif n \u003e 1 {\n\t\t\t\tn = 1\n\t\t\t}\n\t\t\treturn written + n, err\n\t\t}\n\t\twritten++\n\t\ti = next + 1\n\t}\n}","line":{"from":34,"to":57}} {"id":100032199,"name":"NewEditOptions","signature":"func NewEditOptions(editMode EditMode, ioStreams genericclioptions.IOStreams) *EditOptions","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editoptions.go","code":"// NewEditOptions returns an initialized EditOptions instance\nfunc NewEditOptions(editMode EditMode, ioStreams genericclioptions.IOStreams) *EditOptions {\n\treturn \u0026EditOptions{\n\t\tRecordFlags: genericclioptions.NewRecordFlags(),\n\n\t\tEditMode: editMode,\n\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"edited\").WithTypeSetter(scheme.Scheme),\n\n\t\teditPrinterOptions: \u0026editPrinterOptions{\n\t\t\t// create new editor-specific PrintFlags, with all\n\t\t\t// output flags disabled, except json / yaml\n\t\t\tprintFlags: (\u0026genericclioptions.PrintFlags{\n\t\t\t\tJSONYamlPrintFlags: genericclioptions.NewJSONYamlPrintFlags(),\n\t\t\t}).WithDefaultOutput(\"yaml\"),\n\t\t\text: \".yaml\",\n\t\t\taddHeader: true,\n\t\t},\n\n\t\tWindowsLineEndings: goruntime.GOOS == \"windows\",\n\n\t\tRecorder: genericclioptions.NoopRecorder{},\n\n\t\tIOStreams: ioStreams,\n\t}\n}","line":{"from":95,"to":120}} {"id":100032200,"name":"Complete","signature":"func (e *editPrinterOptions) Complete(fromPrintFlags *genericclioptions.PrintFlags) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editoptions.go","code":"func (e *editPrinterOptions) Complete(fromPrintFlags *genericclioptions.PrintFlags) error {\n\tif e.printFlags == nil {\n\t\treturn fmt.Errorf(\"missing PrintFlags in editor printer options\")\n\t}\n\n\t// bind output format from existing printflags\n\tif fromPrintFlags != nil \u0026\u0026 len(*fromPrintFlags.OutputFormat) \u003e 0 {\n\t\te.printFlags.OutputFormat = fromPrintFlags.OutputFormat\n\t}\n\n\t// prevent a commented header at the top of the user's\n\t// default editor if presenting contents as json.\n\tif *e.printFlags.OutputFormat == \"json\" {\n\t\te.addHeader = false\n\t\te.ext = \".json\"\n\t\treturn nil\n\t}\n\n\t// we default to yaml if check above is false, as only json or yaml are supported\n\te.addHeader = true\n\te.ext = \".yaml\"\n\treturn nil\n}","line":{"from":128,"to":150}} {"id":100032201,"name":"PrintObj","signature":"func (e *editPrinterOptions) PrintObj(obj runtime.Object, out io.Writer) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editoptions.go","code":"func (e *editPrinterOptions) PrintObj(obj runtime.Object, out io.Writer) error {\n\tp, err := e.printFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn p.PrintObj(obj, out)\n}","line":{"from":152,"to":159}} {"id":100032202,"name":"Complete","signature":"func (o *EditOptions) Complete(f cmdutil.Factory, args []string, cmd *cobra.Command) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editoptions.go","code":"// Complete completes all the required options\nfunc (o *EditOptions) Complete(f cmdutil.Factory, args []string, cmd *cobra.Command) error {\n\tvar err error\n\n\to.RecordFlags.Complete(cmd)\n\to.Recorder, err = o.RecordFlags.ToRecorder()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif o.EditMode != NormalEditMode \u0026\u0026 o.EditMode != EditBeforeCreateMode \u0026\u0026 o.EditMode != ApplyEditMode {\n\t\treturn fmt.Errorf(\"unsupported edit mode %q\", o.EditMode)\n\t}\n\n\to.editPrinterOptions.Complete(o.PrintFlags)\n\n\tif o.OutputPatch \u0026\u0026 o.EditMode != NormalEditMode {\n\t\treturn fmt.Errorf(\"the edit mode doesn't support output the patch\")\n\t}\n\n\tcmdNamespace, enforceNamespace, err := f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\tb := f.NewBuilder().\n\t\tUnstructured()\n\tif o.EditMode == NormalEditMode || o.EditMode == ApplyEditMode {\n\t\t// when do normal edit or apply edit we need to always retrieve the latest resource from server\n\t\tb = b.ResourceTypeOrNameArgs(true, args...).Latest()\n\t}\n\tr := b.NamespaceParam(cmdNamespace).DefaultNamespace().\n\t\tFilenameParam(enforceNamespace, \u0026o.FilenameOptions).\n\t\tSubresource(o.Subresource).\n\t\tContinueOnError().\n\t\tFlatten().\n\t\tDo()\n\terr = r.Err()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.OriginalResult = r\n\n\to.updatedResultGetter = func(data []byte) *resource.Result {\n\t\t// resource builder to read objects from edited data\n\t\treturn f.NewBuilder().\n\t\t\tUnstructured().\n\t\t\tStream(bytes.NewReader(data), \"edited-file\").\n\t\t\tSubresource(o.Subresource).\n\t\t\tContinueOnError().\n\t\t\tFlatten().\n\t\t\tDo()\n\t}\n\n\to.ToPrinter = func(operation string) (printers.ResourcePrinter, error) {\n\t\to.PrintFlags.NamePrintFlags.Operation = operation\n\t\treturn o.PrintFlags.ToPrinter()\n\t}\n\n\to.ValidationDirective, err = cmdutil.GetValidationDirective(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.CmdNamespace = cmdNamespace\n\to.f = f\n\n\treturn nil\n}","line":{"from":161,"to":228}} {"id":100032203,"name":"Validate","signature":"func (o *EditOptions) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editoptions.go","code":"// Validate checks the EditOptions to see if there is sufficient information to run the command.\nfunc (o *EditOptions) Validate() error {\n\tif len(o.Subresource) \u003e 0 \u0026\u0026 !slice.ContainsString(SupportedSubresources, o.Subresource, nil) {\n\t\treturn fmt.Errorf(\"invalid subresource value: %q. Must be one of %v\", o.Subresource, SupportedSubresources)\n\t}\n\treturn nil\n}","line":{"from":230,"to":236}} {"id":100032204,"name":"Run","signature":"func (o *EditOptions) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editoptions.go","code":"// Run performs the execution\nfunc (o *EditOptions) Run() error {\n\tedit := NewDefaultEditor(editorEnvs())\n\t// editFn is invoked for each edit session (once with a list for normal edit, once for each individual resource in a edit-on-create invocation)\n\teditFn := func(infos []*resource.Info) error {\n\t\tvar (\n\t\t\tresults = editResults{}\n\t\t\toriginal = []byte{}\n\t\t\tedited = []byte{}\n\t\t\tfile string\n\t\t\terr error\n\t\t)\n\n\t\tcontainsError := false\n\t\t// loop until we succeed or cancel editing\n\t\tfor {\n\t\t\t// get the object we're going to serialize as input to the editor\n\t\t\tvar originalObj runtime.Object\n\t\t\tswitch len(infos) {\n\t\t\tcase 1:\n\t\t\t\toriginalObj = infos[0].Object\n\t\t\tdefault:\n\t\t\t\tl := \u0026unstructured.UnstructuredList{\n\t\t\t\t\tObject: map[string]interface{}{\n\t\t\t\t\t\t\"kind\": \"List\",\n\t\t\t\t\t\t\"apiVersion\": \"v1\",\n\t\t\t\t\t\t\"metadata\": map[string]interface{}{},\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tfor _, info := range infos {\n\t\t\t\t\tl.Items = append(l.Items, *info.Object.(*unstructured.Unstructured))\n\t\t\t\t}\n\t\t\t\toriginalObj = l\n\t\t\t}\n\n\t\t\t// generate the file to edit\n\t\t\tbuf := \u0026bytes.Buffer{}\n\t\t\tvar w io.Writer = buf\n\t\t\tif o.WindowsLineEndings {\n\t\t\t\tw = crlf.NewCRLFWriter(w)\n\t\t\t}\n\n\t\t\tif o.editPrinterOptions.addHeader {\n\t\t\t\tresults.header.writeTo(w, o.EditMode)\n\t\t\t}\n\n\t\t\tif !containsError {\n\t\t\t\tif err := o.extractManagedFields(originalObj); err != nil {\n\t\t\t\t\treturn preservedFile(err, results.file, o.ErrOut)\n\t\t\t\t}\n\n\t\t\t\tif err := o.editPrinterOptions.PrintObj(originalObj, w); err != nil {\n\t\t\t\t\treturn preservedFile(err, results.file, o.ErrOut)\n\t\t\t\t}\n\t\t\t\toriginal = buf.Bytes()\n\t\t\t} else {\n\t\t\t\t// In case of an error, preserve the edited file.\n\t\t\t\t// Remove the comments (header) from it since we already\n\t\t\t\t// have included the latest header in the buffer above.\n\t\t\t\tbuf.Write(cmdutil.ManualStrip(edited))\n\t\t\t}\n\n\t\t\t// launch the editor\n\t\t\teditedDiff := edited\n\t\t\tedited, file, err = edit.LaunchTempFile(fmt.Sprintf(\"%s-edit-\", filepath.Base(os.Args[0])), o.editPrinterOptions.ext, buf)\n\t\t\tif err != nil {\n\t\t\t\treturn preservedFile(err, results.file, o.ErrOut)\n\t\t\t}\n\n\t\t\t// If we're retrying the loop because of an error, and no change was made in the file, short-circuit\n\t\t\tif containsError \u0026\u0026 bytes.Equal(cmdutil.StripComments(editedDiff), cmdutil.StripComments(edited)) {\n\t\t\t\treturn preservedFile(fmt.Errorf(\"%s\", \"Edit cancelled, no valid changes were saved.\"), file, o.ErrOut)\n\t\t\t}\n\t\t\t// cleanup any file from the previous pass\n\t\t\tif len(results.file) \u003e 0 {\n\t\t\t\tos.Remove(results.file)\n\t\t\t}\n\t\t\tklog.V(4).Infof(\"User edited:\\n%s\", string(edited))\n\n\t\t\t// Apply validation\n\t\t\tschema, err := o.f.Validator(o.ValidationDirective)\n\t\t\tif err != nil {\n\t\t\t\treturn preservedFile(err, file, o.ErrOut)\n\t\t\t}\n\t\t\terr = schema.ValidateBytes(cmdutil.StripComments(edited))\n\t\t\tif err != nil {\n\t\t\t\tresults = editResults{\n\t\t\t\t\tfile: file,\n\t\t\t\t}\n\t\t\t\tcontainsError = true\n\t\t\t\tfmt.Fprintln(o.ErrOut, results.addError(apierrors.NewInvalid(corev1.SchemeGroupVersion.WithKind(\"\").GroupKind(),\n\t\t\t\t\t\"\", field.ErrorList{field.Invalid(nil, \"The edited file failed validation\", fmt.Sprintf(\"%v\", err))}), infos[0]))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Compare content without comments\n\t\t\tif bytes.Equal(cmdutil.StripComments(original), cmdutil.StripComments(edited)) {\n\t\t\t\tos.Remove(file)\n\t\t\t\tfmt.Fprintln(o.ErrOut, \"Edit cancelled, no changes made.\")\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tlines, err := hasLines(bytes.NewBuffer(edited))\n\t\t\tif err != nil {\n\t\t\t\treturn preservedFile(err, file, o.ErrOut)\n\t\t\t}\n\t\t\tif !lines {\n\t\t\t\tos.Remove(file)\n\t\t\t\tfmt.Fprintln(o.ErrOut, \"Edit cancelled, saved file was empty.\")\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tresults = editResults{\n\t\t\t\tfile: file,\n\t\t\t}\n\n\t\t\t// parse the edited file\n\t\t\tupdatedInfos, err := o.updatedResultGetter(edited).Infos()\n\t\t\tif err != nil {\n\t\t\t\t// syntax error\n\t\t\t\tcontainsError = true\n\t\t\t\tresults.header.reasons = append(results.header.reasons, editReason{head: fmt.Sprintf(\"The edited file had a syntax error: %v\", err)})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// not a syntax error as it turns out...\n\t\t\tcontainsError = false\n\t\t\tupdatedVisitor := resource.InfoListVisitor(updatedInfos)\n\n\t\t\t// we need to add back managedFields to both updated and original object\n\t\t\tif err := o.restoreManagedFields(updatedInfos); err != nil {\n\t\t\t\treturn preservedFile(err, file, o.ErrOut)\n\t\t\t}\n\t\t\tif err := o.restoreManagedFields(infos); err != nil {\n\t\t\t\treturn preservedFile(err, file, o.ErrOut)\n\t\t\t}\n\n\t\t\t// need to make sure the original namespace wasn't changed while editing\n\t\t\tif err := updatedVisitor.Visit(resource.RequireNamespace(o.CmdNamespace)); err != nil {\n\t\t\t\treturn preservedFile(err, file, o.ErrOut)\n\t\t\t}\n\n\t\t\t// iterate through all items to apply annotations\n\t\t\tif err := o.visitAnnotation(updatedVisitor); err != nil {\n\t\t\t\treturn preservedFile(err, file, o.ErrOut)\n\t\t\t}\n\n\t\t\tswitch o.EditMode {\n\t\t\tcase NormalEditMode:\n\t\t\t\terr = o.visitToPatch(infos, updatedVisitor, \u0026results)\n\t\t\tcase ApplyEditMode:\n\t\t\t\terr = o.visitToApplyEditPatch(infos, updatedVisitor)\n\t\t\tcase EditBeforeCreateMode:\n\t\t\t\terr = o.visitToCreate(updatedVisitor)\n\t\t\tdefault:\n\t\t\t\terr = fmt.Errorf(\"unsupported edit mode %q\", o.EditMode)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn preservedFile(err, results.file, o.ErrOut)\n\t\t\t}\n\n\t\t\t// Handle all possible errors\n\t\t\t//\n\t\t\t// 1. retryable: propose kubectl replace -f\n\t\t\t// 2. notfound: indicate the location of the saved configuration of the deleted resource\n\t\t\t// 3. invalid: retry those on the spot by looping ie. reloading the editor\n\t\t\tif results.retryable \u003e 0 {\n\t\t\t\tfmt.Fprintf(o.ErrOut, \"You can run `%s replace -f %s` to try this update again.\\n\", filepath.Base(os.Args[0]), file)\n\t\t\t\treturn cmdutil.ErrExit\n\t\t\t}\n\t\t\tif results.notfound \u003e 0 {\n\t\t\t\tfmt.Fprintf(o.ErrOut, \"The edits you made on deleted resources have been saved to %q\\n\", file)\n\t\t\t\treturn cmdutil.ErrExit\n\t\t\t}\n\n\t\t\tif len(results.edit) == 0 {\n\t\t\t\tif results.notfound == 0 {\n\t\t\t\t\tos.Remove(file)\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Fprintf(o.Out, \"The edits you made on deleted resources have been saved to %q\\n\", file)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif len(results.header.reasons) \u003e 0 {\n\t\t\t\tcontainsError = true\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch o.EditMode {\n\t// If doing normal edit we cannot use Visit because we need to edit a list for convenience. Ref: #20519\n\tcase NormalEditMode:\n\t\tinfos, err := o.OriginalResult.Infos()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(infos) == 0 {\n\t\t\treturn errors.New(\"edit cancelled, no objects found\")\n\t\t}\n\t\treturn editFn(infos)\n\tcase ApplyEditMode:\n\t\tinfos, err := o.OriginalResult.Infos()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar annotationInfos []*resource.Info\n\t\tfor i := range infos {\n\t\t\tdata, err := util.GetOriginalConfiguration(infos[i].Object)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif data == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ttempInfos, err := o.updatedResultGetter(data).Infos()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tannotationInfos = append(annotationInfos, tempInfos[0])\n\t\t}\n\t\tif len(annotationInfos) == 0 {\n\t\t\treturn errors.New(\"no last-applied-configuration annotation found on resources, to create the annotation, use command `kubectl apply set-last-applied --create-annotation`\")\n\t\t}\n\t\treturn editFn(annotationInfos)\n\t// If doing an edit before created, we don't want a list and instead want the normal behavior as kubectl create.\n\tcase EditBeforeCreateMode:\n\t\treturn o.OriginalResult.Visit(func(info *resource.Info, err error) error {\n\t\t\treturn editFn([]*resource.Info{info})\n\t\t})\n\tdefault:\n\t\treturn fmt.Errorf(\"unsupported edit mode %q\", o.EditMode)\n\t}\n}","line":{"from":238,"to":472}} {"id":100032205,"name":"extractManagedFields","signature":"func (o *EditOptions) extractManagedFields(obj runtime.Object) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editoptions.go","code":"func (o *EditOptions) extractManagedFields(obj runtime.Object) error {\n\to.managedFields = make(map[types.UID][]metav1.ManagedFieldsEntry)\n\tif meta.IsListType(obj) {\n\t\terr := meta.EachListItem(obj, func(obj runtime.Object) error {\n\t\t\tuid, mf, err := clearManagedFields(obj)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\to.managedFields[uid] = mf\n\t\t\treturn nil\n\t\t})\n\t\treturn err\n\t}\n\tuid, mf, err := clearManagedFields(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\to.managedFields[uid] = mf\n\treturn nil\n}","line":{"from":474,"to":493}} {"id":100032206,"name":"clearManagedFields","signature":"func clearManagedFields(obj runtime.Object) (types.UID, []metav1.ManagedFieldsEntry, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editoptions.go","code":"func clearManagedFields(obj runtime.Object) (types.UID, []metav1.ManagedFieldsEntry, error) {\n\tmetaObjs, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\tmf := metaObjs.GetManagedFields()\n\tmetaObjs.SetManagedFields(nil)\n\treturn metaObjs.GetUID(), mf, nil\n}","line":{"from":495,"to":503}} {"id":100032207,"name":"restoreManagedFields","signature":"func (o *EditOptions) restoreManagedFields(infos []*resource.Info) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editoptions.go","code":"func (o *EditOptions) restoreManagedFields(infos []*resource.Info) error {\n\tfor _, info := range infos {\n\t\tmetaObjs, err := meta.Accessor(info.Object)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmf := o.managedFields[metaObjs.GetUID()]\n\t\tmetaObjs.SetManagedFields(mf)\n\t}\n\treturn nil\n}","line":{"from":505,"to":515}} {"id":100032208,"name":"visitToApplyEditPatch","signature":"func (o *EditOptions) visitToApplyEditPatch(originalInfos []*resource.Info, patchVisitor resource.Visitor) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editoptions.go","code":"func (o *EditOptions) visitToApplyEditPatch(originalInfos []*resource.Info, patchVisitor resource.Visitor) error {\n\terr := patchVisitor.Visit(func(info *resource.Info, incomingErr error) error {\n\t\teditObjUID, err := meta.NewAccessor().UID(info.Object)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar originalInfo *resource.Info\n\t\tfor _, i := range originalInfos {\n\t\t\toriginalObjUID, err := meta.NewAccessor().UID(i.Object)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif editObjUID == originalObjUID {\n\t\t\t\toriginalInfo = i\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif originalInfo == nil {\n\t\t\treturn fmt.Errorf(\"no original object found for %#v\", info.Object)\n\t\t}\n\n\t\toriginalJS, err := encodeToJSON(originalInfo.Object.(runtime.Unstructured))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\teditedJS, err := encodeToJSON(info.Object.(runtime.Unstructured))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif reflect.DeepEqual(originalJS, editedJS) {\n\t\t\tprinter, err := o.ToPrinter(\"skipped\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn printer.PrintObj(info.Object, o.Out)\n\t\t}\n\t\terr = o.annotationPatch(info)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tprinter, err := o.ToPrinter(\"edited\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn printer.PrintObj(info.Object, o.Out)\n\t})\n\treturn err\n}","line":{"from":517,"to":568}} {"id":100032209,"name":"annotationPatch","signature":"func (o *EditOptions) annotationPatch(update *resource.Info) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editoptions.go","code":"func (o *EditOptions) annotationPatch(update *resource.Info) error {\n\tpatch, _, patchType, err := GetApplyPatch(update.Object.(runtime.Unstructured))\n\tif err != nil {\n\t\treturn err\n\t}\n\tmapping := update.ResourceMapping()\n\tclient, err := o.f.UnstructuredClientForMapping(mapping)\n\tif err != nil {\n\t\treturn err\n\t}\n\thelper := resource.NewHelper(client, mapping).\n\t\tWithFieldManager(o.FieldManager).\n\t\tWithFieldValidation(o.ValidationDirective).\n\t\tWithSubresource(o.Subresource)\n\t_, err = helper.Patch(o.CmdNamespace, update.Name, patchType, patch, nil)\n\treturn err\n}","line":{"from":570,"to":586}} {"id":100032210,"name":"GetApplyPatch","signature":"func GetApplyPatch(obj runtime.Unstructured) ([]byte, []byte, types.PatchType, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editoptions.go","code":"// GetApplyPatch is used to get and apply patches\nfunc GetApplyPatch(obj runtime.Unstructured) ([]byte, []byte, types.PatchType, error) {\n\tbeforeJSON, err := encodeToJSON(obj)\n\tif err != nil {\n\t\treturn nil, []byte(\"\"), types.MergePatchType, err\n\t}\n\tobjCopy := obj.DeepCopyObject()\n\taccessor := meta.NewAccessor()\n\tannotations, err := accessor.Annotations(objCopy)\n\tif err != nil {\n\t\treturn nil, beforeJSON, types.MergePatchType, err\n\t}\n\tif annotations == nil {\n\t\tannotations = map[string]string{}\n\t}\n\tannotations[corev1.LastAppliedConfigAnnotation] = string(beforeJSON)\n\taccessor.SetAnnotations(objCopy, annotations)\n\tafterJSON, err := encodeToJSON(objCopy.(runtime.Unstructured))\n\tif err != nil {\n\t\treturn nil, beforeJSON, types.MergePatchType, err\n\t}\n\tpatch, err := jsonpatch.CreateMergePatch(beforeJSON, afterJSON)\n\treturn patch, beforeJSON, types.MergePatchType, err\n}","line":{"from":588,"to":611}} {"id":100032211,"name":"encodeToJSON","signature":"func encodeToJSON(obj runtime.Unstructured) ([]byte, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editoptions.go","code":"func encodeToJSON(obj runtime.Unstructured) ([]byte, error) {\n\tserialization, err := runtime.Encode(unstructured.UnstructuredJSONScheme, obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tjs, err := yaml.ToJSON(serialization)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn js, nil\n}","line":{"from":613,"to":623}} {"id":100032212,"name":"visitToPatch","signature":"func (o *EditOptions) visitToPatch(originalInfos []*resource.Info, patchVisitor resource.Visitor, results *editResults) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editoptions.go","code":"func (o *EditOptions) visitToPatch(originalInfos []*resource.Info, patchVisitor resource.Visitor, results *editResults) error {\n\terr := patchVisitor.Visit(func(info *resource.Info, incomingErr error) error {\n\t\teditObjUID, err := meta.NewAccessor().UID(info.Object)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar originalInfo *resource.Info\n\t\tfor _, i := range originalInfos {\n\t\t\toriginalObjUID, err := meta.NewAccessor().UID(i.Object)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif editObjUID == originalObjUID {\n\t\t\t\toriginalInfo = i\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif originalInfo == nil {\n\t\t\treturn fmt.Errorf(\"no original object found for %#v\", info.Object)\n\t\t}\n\n\t\toriginalJS, err := encodeToJSON(originalInfo.Object.(runtime.Unstructured))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\teditedJS, err := encodeToJSON(info.Object.(runtime.Unstructured))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif reflect.DeepEqual(originalJS, editedJS) {\n\t\t\t// no edit, so just skip it.\n\t\t\tprinter, err := o.ToPrinter(\"skipped\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn printer.PrintObj(info.Object, o.Out)\n\t\t}\n\n\t\tpreconditions := []mergepatch.PreconditionFunc{\n\t\t\tmergepatch.RequireKeyUnchanged(\"apiVersion\"),\n\t\t\tmergepatch.RequireKeyUnchanged(\"kind\"),\n\t\t\tmergepatch.RequireMetadataKeyUnchanged(\"name\"),\n\t\t\tmergepatch.RequireKeyUnchanged(\"managedFields\"),\n\t\t}\n\n\t\t// Create the versioned struct from the type defined in the mapping\n\t\t// (which is the API version we'll be submitting the patch to)\n\t\tversionedObject, err := scheme.Scheme.New(info.Mapping.GroupVersionKind)\n\t\tvar patchType types.PatchType\n\t\tvar patch []byte\n\t\tswitch {\n\t\tcase runtime.IsNotRegisteredError(err):\n\t\t\t// fall back to generic JSON merge patch\n\t\t\tpatchType = types.MergePatchType\n\t\t\tpatch, err = jsonpatch.CreateMergePatch(originalJS, editedJS)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Unable to calculate diff, no merge is possible: %v\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tvar patchMap map[string]interface{}\n\t\t\terr = json.Unmarshal(patch, \u0026patchMap)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Unable to calculate diff, no merge is possible: %v\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfor _, precondition := range preconditions {\n\t\t\t\tif !precondition(patchMap) {\n\t\t\t\t\tklog.V(4).Infof(\"Unable to calculate diff, no merge is possible: %v\", err)\n\t\t\t\t\treturn fmt.Errorf(\"%s\", \"At least one of apiVersion, kind and name was changed\")\n\t\t\t\t}\n\t\t\t}\n\t\tcase err != nil:\n\t\t\treturn err\n\t\tdefault:\n\t\t\tpatchType = types.StrategicMergePatchType\n\t\t\tpatch, err = strategicpatch.CreateTwoWayMergePatch(originalJS, editedJS, versionedObject, preconditions...)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Unable to calculate diff, no merge is possible: %v\", err)\n\t\t\t\tif mergepatch.IsPreconditionFailed(err) {\n\t\t\t\t\treturn fmt.Errorf(\"%s\", \"At least one of apiVersion, kind and name was changed\")\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tif o.OutputPatch {\n\t\t\tfmt.Fprintf(o.Out, \"Patch: %s\\n\", string(patch))\n\t\t}\n\n\t\tpatched, err := resource.NewHelper(info.Client, info.Mapping).\n\t\t\tWithFieldManager(o.FieldManager).\n\t\t\tWithFieldValidation(o.ValidationDirective).\n\t\t\tWithSubresource(o.Subresource).\n\t\t\tPatch(info.Namespace, info.Name, patchType, patch, nil)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(o.ErrOut, results.addError(err, info))\n\t\t\treturn nil\n\t\t}\n\t\tinfo.Refresh(patched, true)\n\t\tprinter, err := o.ToPrinter(\"edited\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn printer.PrintObj(info.Object, o.Out)\n\t})\n\treturn err\n}","line":{"from":625,"to":734}} {"id":100032213,"name":"visitToCreate","signature":"func (o *EditOptions) visitToCreate(createVisitor resource.Visitor) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editoptions.go","code":"func (o *EditOptions) visitToCreate(createVisitor resource.Visitor) error {\n\terr := createVisitor.Visit(func(info *resource.Info, incomingErr error) error {\n\t\tobj, err := resource.NewHelper(info.Client, info.Mapping).\n\t\t\tWithFieldManager(o.FieldManager).\n\t\t\tWithFieldValidation(o.ValidationDirective).\n\t\t\tCreate(info.Namespace, true, info.Object)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tinfo.Refresh(obj, true)\n\t\tprinter, err := o.ToPrinter(\"created\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn printer.PrintObj(info.Object, o.Out)\n\t})\n\treturn err\n}","line":{"from":736,"to":753}} {"id":100032214,"name":"visitAnnotation","signature":"func (o *EditOptions) visitAnnotation(annotationVisitor resource.Visitor) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editoptions.go","code":"func (o *EditOptions) visitAnnotation(annotationVisitor resource.Visitor) error {\n\t// iterate through all items to apply annotations\n\terr := annotationVisitor.Visit(func(info *resource.Info, incomingErr error) error {\n\t\t// put configuration annotation in \"updates\"\n\t\tif o.ApplyAnnotation {\n\t\t\tif err := util.CreateOrUpdateAnnotation(true, info.Object, scheme.DefaultJSONEncoder()); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif err := o.Recorder.Record(info.Object); err != nil {\n\t\t\tklog.V(4).Infof(\"error recording current command: %v\", err)\n\t\t}\n\n\t\treturn nil\n\n\t})\n\treturn err\n}","line":{"from":755,"to":772}} {"id":100032215,"name":"writeTo","signature":"func (h *editHeader) writeTo(w io.Writer, editMode EditMode) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editoptions.go","code":"// writeTo outputs the current header information into a stream\nfunc (h *editHeader) writeTo(w io.Writer, editMode EditMode) error {\n\tif editMode == ApplyEditMode {\n\t\tfmt.Fprint(w, `# Please edit the 'last-applied-configuration' annotations below.\n# Lines beginning with a '#' will be ignored, and an empty file will abort the edit.\n#\n`)\n\t} else {\n\t\tfmt.Fprint(w, `# Please edit the object below. Lines beginning with a '#' will be ignored,\n# and an empty file will abort the edit. If an error occurs while saving this file will be\n# reopened with the relevant failures.\n#\n`)\n\t}\n\n\tfor _, r := range h.reasons {\n\t\tif len(r.other) \u003e 0 {\n\t\t\tfmt.Fprintf(w, \"# %s:\\n\", hashOnLineBreak(r.head))\n\t\t} else {\n\t\t\tfmt.Fprintf(w, \"# %s\\n\", hashOnLineBreak(r.head))\n\t\t}\n\t\tfor _, o := range r.other {\n\t\t\tfmt.Fprintf(w, \"# * %s\\n\", hashOnLineBreak(o))\n\t\t}\n\t\tfmt.Fprintln(w, \"#\")\n\t}\n\treturn nil\n}","line":{"from":799,"to":826}} {"id":100032216,"name":"addError","signature":"func (r *editResults) addError(err error, info *resource.Info) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editoptions.go","code":"func (r *editResults) addError(err error, info *resource.Info) string {\n\tresourceString := info.Mapping.Resource.Resource\n\tif len(info.Mapping.Resource.Group) \u003e 0 {\n\t\tresourceString = resourceString + \".\" + info.Mapping.Resource.Group\n\t}\n\n\tswitch {\n\tcase apierrors.IsInvalid(err):\n\t\tr.edit = append(r.edit, info)\n\t\treason := editReason{\n\t\t\thead: fmt.Sprintf(\"%s %q was not valid\", resourceString, info.Name),\n\t\t}\n\t\tif err, ok := err.(apierrors.APIStatus); ok {\n\t\t\tif details := err.Status().Details; details != nil {\n\t\t\t\tfor _, cause := range details.Causes {\n\t\t\t\t\treason.other = append(reason.other, fmt.Sprintf(\"%s: %s\", cause.Field, cause.Message))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tr.header.reasons = append(r.header.reasons, reason)\n\t\treturn fmt.Sprintf(\"error: %s %q is invalid\", resourceString, info.Name)\n\tcase apierrors.IsNotFound(err):\n\t\tr.notfound++\n\t\treturn fmt.Sprintf(\"error: %s %q could not be found on the server\", resourceString, info.Name)\n\tdefault:\n\t\tr.retryable++\n\t\treturn fmt.Sprintf(\"error: %s %q could not be patched: %v\", resourceString, info.Name, err)\n\t}\n}","line":{"from":837,"to":865}} {"id":100032217,"name":"preservedFile","signature":"func preservedFile(err error, path string, out io.Writer) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editoptions.go","code":"// preservedFile writes out a message about the provided file if it exists to the\n// provided output stream when an error happens. Used to notify the user where\n// their updates were preserved.\nfunc preservedFile(err error, path string, out io.Writer) error {\n\tif len(path) \u003e 0 {\n\t\tif _, err := os.Stat(path); !os.IsNotExist(err) {\n\t\t\tfmt.Fprintf(out, \"A copy of your changes has been stored to %q\\n\", path)\n\t\t}\n\t}\n\treturn err\n}","line":{"from":867,"to":877}} {"id":100032218,"name":"hasLines","signature":"func hasLines(r io.Reader) (bool, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editoptions.go","code":"// hasLines returns true if any line in the provided stream is non empty - has non-whitespace\n// characters, or the first non-whitespace character is a '#' indicating a comment. Returns\n// any errors encountered reading the stream.\nfunc hasLines(r io.Reader) (bool, error) {\n\t// TODO: if any files we read have \u003e 64KB lines, we'll need to switch to bytes.ReadLine\n\t// TODO: probably going to be secrets\n\ts := bufio.NewScanner(r)\n\tfor s.Scan() {\n\t\tif line := strings.TrimSpace(s.Text()); len(line) \u003e 0 \u0026\u0026 line[0] != '#' {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\tif err := s.Err(); err != nil \u0026\u0026 err != io.EOF {\n\t\treturn false, err\n\t}\n\treturn false, nil\n}","line":{"from":879,"to":895}} {"id":100032219,"name":"hashOnLineBreak","signature":"func hashOnLineBreak(s string) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editoptions.go","code":"// hashOnLineBreak returns a string built from the provided string by inserting any necessary '#'\n// characters after '\\n' characters, indicating a comment.\nfunc hashOnLineBreak(s string) string {\n\tr := \"\"\n\tfor i, ch := range s {\n\t\tj := i + 1\n\t\tif j \u003c len(s) \u0026\u0026 ch == '\\n' \u0026\u0026 s[j] != '#' {\n\t\t\tr += \"\\n# \"\n\t\t} else {\n\t\t\tr += string(ch)\n\t\t}\n\t}\n\treturn r\n}","line":{"from":897,"to":910}} {"id":100032220,"name":"editorEnvs","signature":"func editorEnvs() []string","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editoptions.go","code":"// editorEnvs returns an ordered list of env vars to check for editor preferences.\nfunc editorEnvs() []string {\n\treturn []string{\n\t\t\"KUBE_EDITOR\",\n\t\t\"EDITOR\",\n\t}\n}","line":{"from":912,"to":918}} {"id":100032221,"name":"NewDefaultEditor","signature":"func NewDefaultEditor(envs []string) Editor","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editor.go","code":"// NewDefaultEditor creates a struct Editor that uses the OS environment to\n// locate the editor program, looking at EDITOR environment variable to find\n// the proper command line. If the provided editor has no spaces, or no quotes,\n// it is treated as a bare command to be loaded. Otherwise, the string will\n// be passed to the user's shell for execution.\nfunc NewDefaultEditor(envs []string) Editor {\n\targs, shell := defaultEnvEditor(envs)\n\treturn Editor{\n\t\tArgs: args,\n\t\tShell: shell,\n\t}\n}","line":{"from":50,"to":61}} {"id":100032222,"name":"defaultEnvShell","signature":"func defaultEnvShell() []string","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editor.go","code":"func defaultEnvShell() []string {\n\tshell := os.Getenv(\"SHELL\")\n\tif len(shell) == 0 {\n\t\tshell = platformize(defaultShell, windowsShell)\n\t}\n\tflag := \"-c\"\n\tif shell == windowsShell {\n\t\tflag = \"/C\"\n\t}\n\treturn []string{shell, flag}\n}","line":{"from":63,"to":73}} {"id":100032223,"name":"defaultEnvEditor","signature":"func defaultEnvEditor(envs []string) ([]string, bool)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editor.go","code":"func defaultEnvEditor(envs []string) ([]string, bool) {\n\tvar editor string\n\tfor _, env := range envs {\n\t\tif len(env) \u003e 0 {\n\t\t\teditor = os.Getenv(env)\n\t\t}\n\t\tif len(editor) \u003e 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(editor) == 0 {\n\t\teditor = platformize(defaultEditor, windowsEditor)\n\t}\n\tif !strings.Contains(editor, \" \") {\n\t\treturn []string{editor}, false\n\t}\n\tif !strings.ContainsAny(editor, \"\\\"'\\\\\") {\n\t\treturn strings.Split(editor, \" \"), false\n\t}\n\t// rather than parse the shell arguments ourselves, punt to the shell\n\tshell := defaultEnvShell()\n\treturn append(shell, editor), true\n}","line":{"from":75,"to":97}} {"id":100032224,"name":"args","signature":"func (e Editor) args(path string) []string","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editor.go","code":"func (e Editor) args(path string) []string {\n\targs := make([]string, len(e.Args))\n\tcopy(args, e.Args)\n\tif e.Shell {\n\t\tlast := args[len(args)-1]\n\t\targs[len(args)-1] = fmt.Sprintf(\"%s %q\", last, path)\n\t} else {\n\t\targs = append(args, path)\n\t}\n\treturn args\n}","line":{"from":99,"to":109}} {"id":100032225,"name":"Launch","signature":"func (e Editor) Launch(path string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editor.go","code":"// Launch opens the described or returns an error. The TTY will be protected, and\n// SIGQUIT, SIGTERM, and SIGINT will all be trapped.\nfunc (e Editor) Launch(path string) error {\n\tif len(e.Args) == 0 {\n\t\treturn fmt.Errorf(\"no editor defined, can't open %s\", path)\n\t}\n\tabs, err := filepath.Abs(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\targs := e.args(abs)\n\tcmd := exec.Command(args[0], args[1:]...)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tcmd.Stdin = os.Stdin\n\tklog.V(5).Infof(\"Opening file with editor %v\", args)\n\tif err := (term.TTY{In: os.Stdin, TryDev: true}).Safe(cmd.Run); err != nil {\n\t\tif err, ok := err.(*exec.Error); ok {\n\t\t\tif err.Err == exec.ErrNotFound {\n\t\t\t\treturn fmt.Errorf(\"unable to launch the editor %q\", strings.Join(e.Args, \" \"))\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"there was a problem with the editor %q\", strings.Join(e.Args, \" \"))\n\t}\n\treturn nil\n}","line":{"from":111,"to":136}} {"id":100032226,"name":"LaunchTempFile","signature":"func (e Editor) LaunchTempFile(prefix, suffix string, r io.Reader) ([]byte, string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editor.go","code":"// LaunchTempFile reads the provided stream into a temporary file in the given directory\n// and file prefix, and then invokes Launch with the path of that file. It will return\n// the contents of the file after launch, any errors that occur, and the path of the\n// temporary file so the caller can clean it up as needed.\nfunc (e Editor) LaunchTempFile(prefix, suffix string, r io.Reader) ([]byte, string, error) {\n\tf, err := os.CreateTemp(\"\", prefix+\"*\"+suffix)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tdefer f.Close()\n\tpath := f.Name()\n\tif _, err := io.Copy(f, r); err != nil {\n\t\tos.Remove(path)\n\t\treturn nil, path, err\n\t}\n\t// This file descriptor needs to close so the next process (Launch) can claim it.\n\tf.Close()\n\tif err := e.Launch(path); err != nil {\n\t\treturn nil, path, err\n\t}\n\tbytes, err := os.ReadFile(path)\n\treturn bytes, path, err\n}","line":{"from":138,"to":160}} {"id":100032227,"name":"platformize","signature":"func platformize(linux, windows string) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editor.go","code":"func platformize(linux, windows string) string {\n\tif runtime.GOOS == \"windows\" {\n\t\treturn windows\n\t}\n\treturn linux\n}","line":{"from":162,"to":167}} {"id":100032228,"name":"processEnvFileLine","signature":"func processEnvFileLine(line []byte, filePath string,","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/env_file.go","code":"// processEnvFileLine returns a blank key if the line is empty or a comment.\n// The value will be retrieved from the environment if necessary.\nfunc processEnvFileLine(line []byte, filePath string,\n\tcurrentLine int) (key, value string, err error) {\n\n\tif !utf8.Valid(line) {\n\t\treturn ``, ``, fmt.Errorf(\"env file %s contains invalid utf8 bytes at line %d: %v\",\n\t\t\tfilePath, currentLine+1, line)\n\t}\n\n\t// We trim UTF8 BOM from the first line of the file but no others\n\tif currentLine == 0 {\n\t\tline = bytes.TrimPrefix(line, utf8bom)\n\t}\n\n\t// trim the line from all leading whitespace first\n\tline = bytes.TrimLeftFunc(line, unicode.IsSpace)\n\n\t// If the line is empty or a comment, we return a blank key/value pair.\n\tif len(line) == 0 || line[0] == '#' {\n\t\treturn ``, ``, nil\n\t}\n\n\tdata := strings.SplitN(string(line), \"=\", 2)\n\tkey = data[0]\n\tif errs := validation.IsEnvVarName(key); len(errs) != 0 {\n\t\treturn ``, ``, fmt.Errorf(\"%q is not a valid key name: %s\", key, strings.Join(errs, \";\"))\n\t}\n\n\tif len(data) == 2 {\n\t\tvalue = data[1]\n\t} else {\n\t\t// No value (no `=` in the line) is a signal to obtain the value\n\t\t// from the environment.\n\t\tvalue = os.Getenv(key)\n\t}\n\treturn\n}","line":{"from":33,"to":70}} {"id":100032229,"name":"AddFromEnvFile","signature":"func AddFromEnvFile(filePath string, addTo func(key, value string) error) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/env_file.go","code":"// AddFromEnvFile processes an env file allows a generic addTo to handle the\n// collection of key value pairs or returns an error.\nfunc AddFromEnvFile(filePath string, addTo func(key, value string) error) error {\n\tf, err := os.Open(filePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tscanner := bufio.NewScanner(f)\n\tcurrentLine := 0\n\tfor scanner.Scan() {\n\t\t// Process the current line, retrieving a key/value pair if\n\t\t// possible.\n\t\tscannedBytes := scanner.Bytes()\n\t\tkey, value, err := processEnvFileLine(scannedBytes, filePath, currentLine)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcurrentLine++\n\n\t\tif len(key) == 0 {\n\t\t\t// no key means line was empty or a comment\n\t\t\tcontinue\n\t\t}\n\n\t\tif err = addTo(key, value); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":72,"to":103}} {"id":100032230,"name":"NewFactory","signature":"func NewFactory(clientGetter genericclioptions.RESTClientGetter) Factory","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/factory_client_access.go","code":"func NewFactory(clientGetter genericclioptions.RESTClientGetter) Factory {\n\tif clientGetter == nil {\n\t\tpanic(\"attempt to instantiate client_access_factory with nil clientGetter\")\n\t}\n\tf := \u0026factoryImpl{\n\t\tclientGetter: clientGetter,\n\t}\n\n\treturn f\n}","line":{"from":51,"to":60}} {"id":100032231,"name":"ToRESTConfig","signature":"func (f *factoryImpl) ToRESTConfig() (*restclient.Config, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/factory_client_access.go","code":"func (f *factoryImpl) ToRESTConfig() (*restclient.Config, error) {\n\treturn f.clientGetter.ToRESTConfig()\n}","line":{"from":62,"to":64}} {"id":100032232,"name":"ToRESTMapper","signature":"func (f *factoryImpl) ToRESTMapper() (meta.RESTMapper, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/factory_client_access.go","code":"func (f *factoryImpl) ToRESTMapper() (meta.RESTMapper, error) {\n\treturn f.clientGetter.ToRESTMapper()\n}","line":{"from":66,"to":68}} {"id":100032233,"name":"ToDiscoveryClient","signature":"func (f *factoryImpl) ToDiscoveryClient() (discovery.CachedDiscoveryInterface, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/factory_client_access.go","code":"func (f *factoryImpl) ToDiscoveryClient() (discovery.CachedDiscoveryInterface, error) {\n\treturn f.clientGetter.ToDiscoveryClient()\n}","line":{"from":70,"to":72}} {"id":100032234,"name":"ToRawKubeConfigLoader","signature":"func (f *factoryImpl) ToRawKubeConfigLoader() clientcmd.ClientConfig","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/factory_client_access.go","code":"func (f *factoryImpl) ToRawKubeConfigLoader() clientcmd.ClientConfig {\n\treturn f.clientGetter.ToRawKubeConfigLoader()\n}","line":{"from":74,"to":76}} {"id":100032235,"name":"KubernetesClientSet","signature":"func (f *factoryImpl) KubernetesClientSet() (*kubernetes.Clientset, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/factory_client_access.go","code":"func (f *factoryImpl) KubernetesClientSet() (*kubernetes.Clientset, error) {\n\tclientConfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn kubernetes.NewForConfig(clientConfig)\n}","line":{"from":78,"to":84}} {"id":100032236,"name":"DynamicClient","signature":"func (f *factoryImpl) DynamicClient() (dynamic.Interface, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/factory_client_access.go","code":"func (f *factoryImpl) DynamicClient() (dynamic.Interface, error) {\n\tclientConfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn dynamic.NewForConfig(clientConfig)\n}","line":{"from":86,"to":92}} {"id":100032237,"name":"NewBuilder","signature":"func (f *factoryImpl) NewBuilder() *resource.Builder","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/factory_client_access.go","code":"// NewBuilder returns a new resource builder for structured api objects.\nfunc (f *factoryImpl) NewBuilder() *resource.Builder {\n\treturn resource.NewBuilder(f.clientGetter)\n}","line":{"from":94,"to":97}} {"id":100032238,"name":"RESTClient","signature":"func (f *factoryImpl) RESTClient() (*restclient.RESTClient, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/factory_client_access.go","code":"func (f *factoryImpl) RESTClient() (*restclient.RESTClient, error) {\n\tclientConfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsetKubernetesDefaults(clientConfig)\n\treturn restclient.RESTClientFor(clientConfig)\n}","line":{"from":99,"to":106}} {"id":100032239,"name":"ClientForMapping","signature":"func (f *factoryImpl) ClientForMapping(mapping *meta.RESTMapping) (resource.RESTClient, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/factory_client_access.go","code":"func (f *factoryImpl) ClientForMapping(mapping *meta.RESTMapping) (resource.RESTClient, error) {\n\tcfg, err := f.clientGetter.ToRESTConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := setKubernetesDefaults(cfg); err != nil {\n\t\treturn nil, err\n\t}\n\tgvk := mapping.GroupVersionKind\n\tswitch gvk.Group {\n\tcase corev1.GroupName:\n\t\tcfg.APIPath = \"/api\"\n\tdefault:\n\t\tcfg.APIPath = \"/apis\"\n\t}\n\tgv := gvk.GroupVersion()\n\tcfg.GroupVersion = \u0026gv\n\treturn restclient.RESTClientFor(cfg)\n}","line":{"from":108,"to":126}} {"id":100032240,"name":"UnstructuredClientForMapping","signature":"func (f *factoryImpl) UnstructuredClientForMapping(mapping *meta.RESTMapping) (resource.RESTClient, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/factory_client_access.go","code":"func (f *factoryImpl) UnstructuredClientForMapping(mapping *meta.RESTMapping) (resource.RESTClient, error) {\n\tcfg, err := f.clientGetter.ToRESTConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := restclient.SetKubernetesDefaults(cfg); err != nil {\n\t\treturn nil, err\n\t}\n\tcfg.APIPath = \"/apis\"\n\tif mapping.GroupVersionKind.Group == corev1.GroupName {\n\t\tcfg.APIPath = \"/api\"\n\t}\n\tgv := mapping.GroupVersionKind.GroupVersion()\n\tcfg.ContentConfig = resource.UnstructuredPlusDefaultContentConfig()\n\tcfg.GroupVersion = \u0026gv\n\treturn restclient.RESTClientFor(cfg)\n}","line":{"from":128,"to":144}} {"id":100032241,"name":"Validator","signature":"func (f *factoryImpl) Validator(validationDirective string) (validation.Schema, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/factory_client_access.go","code":"func (f *factoryImpl) Validator(validationDirective string) (validation.Schema, error) {\n\t// client-side schema validation is only performed\n\t// when the validationDirective is strict.\n\t// If the directive is warn, we rely on the ParamVerifyingSchema\n\t// to ignore the client-side validation and provide a warning\n\t// to the user that attempting warn validation when SS validation\n\t// is unsupported is inert.\n\tif validationDirective == metav1.FieldValidationIgnore {\n\t\treturn validation.NullSchema{}, nil\n\t}\n\n\tresources, err := f.OpenAPISchema()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tschema := validation.ConjunctiveSchema{\n\t\tvalidation.NewSchemaValidation(resources),\n\t\tvalidation.NoDoubleKeySchema{},\n\t}\n\n\tdynamicClient, err := f.DynamicClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Create the FieldValidationVerifier for use in the ParamVerifyingSchema.\n\tdiscoveryClient, err := f.ToDiscoveryClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Memory-cache the OpenAPI V3 responses. The disk cache behavior is determined by\n\t// the discovery client.\n\toapiV3Client := cached.NewClient(discoveryClient.OpenAPIV3())\n\tqueryParam := resource.QueryParamFieldValidation\n\tprimary := resource.NewQueryParamVerifierV3(dynamicClient, oapiV3Client, queryParam)\n\tsecondary := resource.NewQueryParamVerifier(dynamicClient, f.openAPIGetter(), queryParam)\n\tfallback := resource.NewFallbackQueryParamVerifier(primary, secondary)\n\treturn validation.NewParamVerifyingSchema(schema, fallback, string(validationDirective)), nil\n}","line":{"from":146,"to":184}} {"id":100032242,"name":"OpenAPISchema","signature":"func (f *factoryImpl) OpenAPISchema() (openapi.Resources, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/factory_client_access.go","code":"// OpenAPISchema returns metadata and structural information about\n// Kubernetes object definitions.\nfunc (f *factoryImpl) OpenAPISchema() (openapi.Resources, error) {\n\topenAPIGetter := f.openAPIGetter()\n\tif openAPIGetter == nil {\n\t\treturn nil, errors.New(\"no openapi getter\")\n\t}\n\n\t// Lazily initialize the OpenAPIParser once\n\tf.parser.Do(func() {\n\t\t// Create the caching OpenAPIParser\n\t\tf.openAPIParser = openapi.NewOpenAPIParser(f.openAPIGetter())\n\t})\n\n\t// Delegate to the OpenAPIPArser\n\treturn f.openAPIParser.Parse()\n}","line":{"from":186,"to":202}} {"id":100032243,"name":"openAPIGetter","signature":"func (f *factoryImpl) openAPIGetter() discovery.OpenAPISchemaInterface","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/factory_client_access.go","code":"func (f *factoryImpl) openAPIGetter() discovery.OpenAPISchemaInterface {\n\tdiscovery, err := f.clientGetter.ToDiscoveryClient()\n\tif err != nil {\n\t\treturn nil\n\t}\n\tf.getter.Do(func() {\n\t\tf.oapi = openapi.NewOpenAPIGetter(discovery)\n\t})\n\n\treturn f.oapi\n}","line":{"from":204,"to":214}} {"id":100032244,"name":"OpenAPIV3Client","signature":"func (f *factoryImpl) OpenAPIV3Client() (openapiclient.Client, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/factory_client_access.go","code":"func (f *factoryImpl) OpenAPIV3Client() (openapiclient.Client, error) {\n\tdiscovery, err := f.clientGetter.ToDiscoveryClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn discovery.OpenAPIV3(), nil\n}","line":{"from":216,"to":223}} {"id":100032245,"name":"AddSourceToErr","signature":"func AddSourceToErr(verb string, source string, err error) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// AddSourceToErr adds handleResourcePrefix and source string to error message.\n// verb is the string like \"creating\", \"deleting\" etc.\n// source is the filename or URL to the template file(*.json or *.yaml), or stdin to use to handle the resource.\nfunc AddSourceToErr(verb string, source string, err error) error {\n\tif source != \"\" {\n\t\tif statusError, ok := err.(apierrors.APIStatus); ok {\n\t\t\tstatus := statusError.Status()\n\t\t\tstatus.Message = fmt.Sprintf(\"error when %s %q: %v\", verb, source, status.Message)\n\t\t\treturn \u0026apierrors.StatusError{ErrStatus: status}\n\t\t}\n\t\treturn fmt.Errorf(\"error when %s %q: %v\", verb, source, err)\n\t}\n\treturn err\n}","line":{"from":62,"to":75}} {"id":100032246,"name":"BehaviorOnFatal","signature":"func BehaviorOnFatal(f func(string, int))","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// BehaviorOnFatal allows you to override the default behavior when a fatal\n// error occurs, which is to call os.Exit(code). You can pass 'panic' as a function\n// here if you prefer the panic() over os.Exit(1).\nfunc BehaviorOnFatal(f func(string, int)) {\n\tfatalErrHandler = f\n}","line":{"from":79,"to":84}} {"id":100032247,"name":"DefaultBehaviorOnFatal","signature":"func DefaultBehaviorOnFatal()","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// DefaultBehaviorOnFatal allows you to undo any previous override. Useful in\n// tests.\nfunc DefaultBehaviorOnFatal() {\n\tfatalErrHandler = fatal\n}","line":{"from":86,"to":90}} {"id":100032248,"name":"fatal","signature":"func fatal(msg string, code int)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// fatal prints the message (if provided) and then exits. If V(99) or greater,\n// klog.Fatal is invoked for extended information. This is intended for maintainer\n// debugging and out of a reasonable range for users.\nfunc fatal(msg string, code int) {\n\t// nolint:logcheck // Not using the result of klog.V(99) inside the if\n\t// branch is okay, we just use it to determine how to terminate.\n\tif klog.V(99).Enabled() {\n\t\tklog.FatalDepth(2, msg)\n\t}\n\tif len(msg) \u003e 0 {\n\t\t// add newline if needed\n\t\tif !strings.HasSuffix(msg, \"\\n\") {\n\t\t\tmsg += \"\\n\"\n\t\t}\n\t\tfmt.Fprint(os.Stderr, msg)\n\t}\n\tos.Exit(code)\n}","line":{"from":92,"to":109}} {"id":100032249,"name":"CheckErr","signature":"func CheckErr(err error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// CheckErr prints a user friendly error to STDERR and exits with a non-zero\n// exit code. Unrecognized errors will be printed with an \"error: \" prefix.\n//\n// This method is generic to the command in use and may be used by non-Kubectl\n// commands.\nfunc CheckErr(err error) {\n\tcheckErr(err, fatalErrHandler)\n}","line":{"from":115,"to":122}} {"id":100032250,"name":"CheckDiffErr","signature":"func CheckDiffErr(err error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// CheckDiffErr prints a user friendly error to STDERR and exits with a\n// non-zero and non-one exit code. Unrecognized errors will be printed\n// with an \"error: \" prefix.\n//\n// This method is meant specifically for `kubectl diff` and may be used\n// by other commands.\nfunc CheckDiffErr(err error) {\n\tcheckErr(err, func(msg string, code int) {\n\t\tfatalErrHandler(msg, code+1)\n\t})\n}","line":{"from":124,"to":134}} {"id":100032251,"name":"isInvalidReasonStatusError","signature":"func isInvalidReasonStatusError(err error) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// isInvalidReasonStatusError returns true if this is an API Status error with reason=Invalid.\n// This is distinct from generic 422 errors we want to fall back to generic error handling.\nfunc isInvalidReasonStatusError(err error) bool {\n\tif !apierrors.IsInvalid(err) {\n\t\treturn false\n\t}\n\tstatusError, isStatusError := err.(*apierrors.StatusError)\n\tif !isStatusError {\n\t\treturn false\n\t}\n\tstatus := statusError.Status()\n\treturn status.Reason == metav1.StatusReasonInvalid\n}","line":{"from":136,"to":148}} {"id":100032252,"name":"checkErr","signature":"func checkErr(err error, handleErr func(string, int))","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// checkErr formats a given error as a string and calls the passed handleErr\n// func with that string and an kubectl exit code.\nfunc checkErr(err error, handleErr func(string, int)) {\n\t// unwrap aggregates of 1\n\tif agg, ok := err.(utilerrors.Aggregate); ok \u0026\u0026 len(agg.Errors()) == 1 {\n\t\terr = agg.Errors()[0]\n\t}\n\n\tif err == nil {\n\t\treturn\n\t}\n\n\tswitch {\n\tcase err == ErrExit:\n\t\thandleErr(\"\", DefaultErrorExitCode)\n\tcase isInvalidReasonStatusError(err):\n\t\tstatus := err.(*apierrors.StatusError).Status()\n\t\tdetails := status.Details\n\t\ts := \"The request is invalid\"\n\t\tif details == nil {\n\t\t\t// if we have no other details, include the message from the server if present\n\t\t\tif len(status.Message) \u003e 0 {\n\t\t\t\ts += \": \" + status.Message\n\t\t\t}\n\t\t\thandleErr(s, DefaultErrorExitCode)\n\t\t\treturn\n\t\t}\n\t\tif len(details.Kind) != 0 || len(details.Name) != 0 {\n\t\t\ts = fmt.Sprintf(\"The %s %q is invalid\", details.Kind, details.Name)\n\t\t} else if len(status.Message) \u003e 0 \u0026\u0026 len(details.Causes) == 0 {\n\t\t\t// only append the message if we have no kind/name details and no causes,\n\t\t\t// since default invalid error constructors duplicate that information in the message\n\t\t\ts += \": \" + status.Message\n\t\t}\n\n\t\tif len(details.Causes) \u003e 0 {\n\t\t\terrs := statusCausesToAggrError(details.Causes)\n\t\t\thandleErr(MultilineError(s+\": \", errs), DefaultErrorExitCode)\n\t\t} else {\n\t\t\thandleErr(s, DefaultErrorExitCode)\n\t\t}\n\tcase clientcmd.IsConfigurationInvalid(err):\n\t\thandleErr(MultilineError(\"Error in configuration: \", err), DefaultErrorExitCode)\n\tdefault:\n\t\tswitch err := err.(type) {\n\t\tcase *meta.NoResourceMatchError:\n\t\t\tswitch {\n\t\t\tcase len(err.PartialResource.Group) \u003e 0 \u0026\u0026 len(err.PartialResource.Version) \u003e 0:\n\t\t\t\thandleErr(fmt.Sprintf(\"the server doesn't have a resource type %q in group %q and version %q\", err.PartialResource.Resource, err.PartialResource.Group, err.PartialResource.Version), DefaultErrorExitCode)\n\t\t\tcase len(err.PartialResource.Group) \u003e 0:\n\t\t\t\thandleErr(fmt.Sprintf(\"the server doesn't have a resource type %q in group %q\", err.PartialResource.Resource, err.PartialResource.Group), DefaultErrorExitCode)\n\t\t\tcase len(err.PartialResource.Version) \u003e 0:\n\t\t\t\thandleErr(fmt.Sprintf(\"the server doesn't have a resource type %q in version %q\", err.PartialResource.Resource, err.PartialResource.Version), DefaultErrorExitCode)\n\t\t\tdefault:\n\t\t\t\thandleErr(fmt.Sprintf(\"the server doesn't have a resource type %q\", err.PartialResource.Resource), DefaultErrorExitCode)\n\t\t\t}\n\t\tcase utilerrors.Aggregate:\n\t\t\thandleErr(MultipleErrors(``, err.Errors()), DefaultErrorExitCode)\n\t\tcase utilexec.ExitError:\n\t\t\thandleErr(err.Error(), err.ExitStatus())\n\t\tdefault: // for any other error type\n\t\t\tmsg, ok := StandardErrorMessage(err)\n\t\t\tif !ok {\n\t\t\t\tmsg = err.Error()\n\t\t\t\tif !strings.HasPrefix(msg, \"error: \") {\n\t\t\t\t\tmsg = fmt.Sprintf(\"error: %s\", msg)\n\t\t\t\t}\n\t\t\t}\n\t\t\thandleErr(msg, DefaultErrorExitCode)\n\t\t}\n\t}\n}","line":{"from":150,"to":221}} {"id":100032253,"name":"statusCausesToAggrError","signature":"func statusCausesToAggrError(scs []metav1.StatusCause) utilerrors.Aggregate","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func statusCausesToAggrError(scs []metav1.StatusCause) utilerrors.Aggregate {\n\terrs := make([]error, 0, len(scs))\n\terrorMsgs := sets.NewString()\n\tfor _, sc := range scs {\n\t\t// check for duplicate error messages and skip them\n\t\tmsg := fmt.Sprintf(\"%s: %s\", sc.Field, sc.Message)\n\t\tif errorMsgs.Has(msg) {\n\t\t\tcontinue\n\t\t}\n\t\terrorMsgs.Insert(msg)\n\t\terrs = append(errs, errors.New(msg))\n\t}\n\treturn utilerrors.NewAggregate(errs)\n}","line":{"from":223,"to":236}} {"id":100032254,"name":"StandardErrorMessage","signature":"func StandardErrorMessage(err error) (string, bool)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// StandardErrorMessage translates common errors into a human readable message, or returns\n// false if the error is not one of the recognized types. It may also log extended\n// information to klog.\n//\n// This method is generic to the command in use and may be used by non-Kubectl\n// commands.\nfunc StandardErrorMessage(err error) (string, bool) {\n\tif debugErr, ok := err.(debugError); ok {\n\t\tklog.V(4).Infof(debugErr.DebugError())\n\t}\n\tstatus, isStatus := err.(apierrors.APIStatus)\n\tswitch {\n\tcase isStatus:\n\t\tswitch s := status.Status(); {\n\t\tcase s.Reason == metav1.StatusReasonUnauthorized:\n\t\t\treturn fmt.Sprintf(\"error: You must be logged in to the server (%s)\", s.Message), true\n\t\tcase len(s.Reason) \u003e 0:\n\t\t\treturn fmt.Sprintf(\"Error from server (%s): %s\", s.Reason, err.Error()), true\n\t\tdefault:\n\t\t\treturn fmt.Sprintf(\"Error from server: %s\", err.Error()), true\n\t\t}\n\tcase apierrors.IsUnexpectedObjectError(err):\n\t\treturn fmt.Sprintf(\"Server returned an unexpected response: %s\", err.Error()), true\n\t}\n\tswitch t := err.(type) {\n\tcase *url.Error:\n\t\tklog.V(4).Infof(\"Connection error: %s %s: %v\", t.Op, t.URL, t.Err)\n\t\tswitch {\n\t\tcase strings.Contains(t.Err.Error(), \"connection refused\"):\n\t\t\thost := t.URL\n\t\t\tif server, err := url.Parse(t.URL); err == nil {\n\t\t\t\thost = server.Host\n\t\t\t}\n\t\t\treturn fmt.Sprintf(\"The connection to the server %s was refused - did you specify the right host or port?\", host), true\n\t\t}\n\t\treturn fmt.Sprintf(\"Unable to connect to the server: %v\", t.Err), true\n\t}\n\treturn \"\", false\n}","line":{"from":238,"to":276}} {"id":100032255,"name":"MultilineError","signature":"func MultilineError(prefix string, err error) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// MultilineError returns a string representing an error that splits sub errors into their own\n// lines. The returned string will end with a newline.\nfunc MultilineError(prefix string, err error) string {\n\tif agg, ok := err.(utilerrors.Aggregate); ok {\n\t\terrs := utilerrors.Flatten(agg).Errors()\n\t\tbuf := \u0026bytes.Buffer{}\n\t\tswitch len(errs) {\n\t\tcase 0:\n\t\t\treturn fmt.Sprintf(\"%s%v\\n\", prefix, err)\n\t\tcase 1:\n\t\t\treturn fmt.Sprintf(\"%s%v\\n\", prefix, messageForError(errs[0]))\n\t\tdefault:\n\t\t\tfmt.Fprintln(buf, prefix)\n\t\t\tfor _, err := range errs {\n\t\t\t\tfmt.Fprintf(buf, \"* %v\\n\", messageForError(err))\n\t\t\t}\n\t\t\treturn buf.String()\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"%s%s\\n\", prefix, err)\n}","line":{"from":278,"to":298}} {"id":100032256,"name":"PrintErrorWithCauses","signature":"func PrintErrorWithCauses(err error, errOut io.Writer) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// PrintErrorWithCauses prints an error's kind, name, and each of the error's causes in a new line.\n// The returned string will end with a newline.\n// Returns true if a case exists to handle the error type, or false otherwise.\nfunc PrintErrorWithCauses(err error, errOut io.Writer) bool {\n\tswitch t := err.(type) {\n\tcase *apierrors.StatusError:\n\t\terrorDetails := t.Status().Details\n\t\tif errorDetails != nil {\n\t\t\tfmt.Fprintf(errOut, \"error: %s %q is invalid\\n\\n\", errorDetails.Kind, errorDetails.Name)\n\t\t\tfor _, cause := range errorDetails.Causes {\n\t\t\t\tfmt.Fprintf(errOut, \"* %s: %s\\n\", cause.Field, cause.Message)\n\t\t\t}\n\t\t\treturn true\n\t\t}\n\t}\n\n\tfmt.Fprintf(errOut, \"error: %v\\n\", err)\n\treturn false\n}","line":{"from":300,"to":318}} {"id":100032257,"name":"MultipleErrors","signature":"func MultipleErrors(prefix string, errs []error) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// MultipleErrors returns a newline delimited string containing\n// the prefix and referenced errors in standard form.\nfunc MultipleErrors(prefix string, errs []error) string {\n\tbuf := \u0026bytes.Buffer{}\n\tfor _, err := range errs {\n\t\tfmt.Fprintf(buf, \"%s%v\\n\", prefix, messageForError(err))\n\t}\n\treturn buf.String()\n}","line":{"from":320,"to":328}} {"id":100032258,"name":"messageForError","signature":"func messageForError(err error) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// messageForError returns the string representing the error.\nfunc messageForError(err error) string {\n\tmsg, ok := StandardErrorMessage(err)\n\tif !ok {\n\t\tmsg = err.Error()\n\t}\n\treturn msg\n}","line":{"from":330,"to":337}} {"id":100032259,"name":"UsageErrorf","signature":"func UsageErrorf(cmd *cobra.Command, format string, args ...interface{}) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func UsageErrorf(cmd *cobra.Command, format string, args ...interface{}) error {\n\tmsg := fmt.Sprintf(format, args...)\n\treturn fmt.Errorf(\"%s\\nSee '%s -h' for help and examples\", msg, cmd.CommandPath())\n}","line":{"from":339,"to":342}} {"id":100032260,"name":"IsFilenameSliceEmpty","signature":"func IsFilenameSliceEmpty(filenames []string, directory string) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func IsFilenameSliceEmpty(filenames []string, directory string) bool {\n\treturn len(filenames) == 0 \u0026\u0026 directory == \"\"\n}","line":{"from":344,"to":346}} {"id":100032261,"name":"GetFlagString","signature":"func GetFlagString(cmd *cobra.Command, flag string) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func GetFlagString(cmd *cobra.Command, flag string) string {\n\ts, err := cmd.Flags().GetString(flag)\n\tif err != nil {\n\t\tklog.Fatalf(\"error accessing flag %s for command %s: %v\", flag, cmd.Name(), err)\n\t}\n\treturn s\n}","line":{"from":348,"to":354}} {"id":100032262,"name":"GetFlagStringSlice","signature":"func GetFlagStringSlice(cmd *cobra.Command, flag string) []string","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// GetFlagStringSlice can be used to accept multiple argument with flag repetition (e.g. -f arg1,arg2 -f arg3 ...)\nfunc GetFlagStringSlice(cmd *cobra.Command, flag string) []string {\n\ts, err := cmd.Flags().GetStringSlice(flag)\n\tif err != nil {\n\t\tklog.Fatalf(\"error accessing flag %s for command %s: %v\", flag, cmd.Name(), err)\n\t}\n\treturn s\n}","line":{"from":356,"to":363}} {"id":100032263,"name":"GetFlagStringArray","signature":"func GetFlagStringArray(cmd *cobra.Command, flag string) []string","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// GetFlagStringArray can be used to accept multiple argument with flag repetition (e.g. -f arg1 -f arg2 ...)\nfunc GetFlagStringArray(cmd *cobra.Command, flag string) []string {\n\ts, err := cmd.Flags().GetStringArray(flag)\n\tif err != nil {\n\t\tklog.Fatalf(\"error accessing flag %s for command %s: %v\", flag, cmd.Name(), err)\n\t}\n\treturn s\n}","line":{"from":365,"to":372}} {"id":100032264,"name":"GetFlagBool","signature":"func GetFlagBool(cmd *cobra.Command, flag string) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func GetFlagBool(cmd *cobra.Command, flag string) bool {\n\tb, err := cmd.Flags().GetBool(flag)\n\tif err != nil {\n\t\tklog.Fatalf(\"error accessing flag %s for command %s: %v\", flag, cmd.Name(), err)\n\t}\n\treturn b\n}","line":{"from":374,"to":380}} {"id":100032265,"name":"GetFlagInt","signature":"func GetFlagInt(cmd *cobra.Command, flag string) int","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// Assumes the flag has a default value.\nfunc GetFlagInt(cmd *cobra.Command, flag string) int {\n\ti, err := cmd.Flags().GetInt(flag)\n\tif err != nil {\n\t\tklog.Fatalf(\"error accessing flag %s for command %s: %v\", flag, cmd.Name(), err)\n\t}\n\treturn i\n}","line":{"from":382,"to":389}} {"id":100032266,"name":"GetFlagInt32","signature":"func GetFlagInt32(cmd *cobra.Command, flag string) int32","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// Assumes the flag has a default value.\nfunc GetFlagInt32(cmd *cobra.Command, flag string) int32 {\n\ti, err := cmd.Flags().GetInt32(flag)\n\tif err != nil {\n\t\tklog.Fatalf(\"error accessing flag %s for command %s: %v\", flag, cmd.Name(), err)\n\t}\n\treturn i\n}","line":{"from":391,"to":398}} {"id":100032267,"name":"GetFlagInt64","signature":"func GetFlagInt64(cmd *cobra.Command, flag string) int64","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// Assumes the flag has a default value.\nfunc GetFlagInt64(cmd *cobra.Command, flag string) int64 {\n\ti, err := cmd.Flags().GetInt64(flag)\n\tif err != nil {\n\t\tklog.Fatalf(\"error accessing flag %s for command %s: %v\", flag, cmd.Name(), err)\n\t}\n\treturn i\n}","line":{"from":400,"to":407}} {"id":100032268,"name":"GetFlagDuration","signature":"func GetFlagDuration(cmd *cobra.Command, flag string) time.Duration","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func GetFlagDuration(cmd *cobra.Command, flag string) time.Duration {\n\td, err := cmd.Flags().GetDuration(flag)\n\tif err != nil {\n\t\tklog.Fatalf(\"error accessing flag %s for command %s: %v\", flag, cmd.Name(), err)\n\t}\n\treturn d\n}","line":{"from":409,"to":415}} {"id":100032269,"name":"GetPodRunningTimeoutFlag","signature":"func GetPodRunningTimeoutFlag(cmd *cobra.Command) (time.Duration, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func GetPodRunningTimeoutFlag(cmd *cobra.Command) (time.Duration, error) {\n\ttimeout := GetFlagDuration(cmd, \"pod-running-timeout\")\n\tif timeout \u003c= 0 {\n\t\treturn timeout, fmt.Errorf(\"--pod-running-timeout must be higher than zero\")\n\t}\n\treturn timeout, nil\n}","line":{"from":417,"to":423}} {"id":100032270,"name":"IsEnabled","signature":"func (f FeatureGate) IsEnabled() bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func (f FeatureGate) IsEnabled() bool {\n\treturn os.Getenv(string(f)) == \"true\"\n}","line":{"from":433,"to":435}} {"id":100032271,"name":"AddValidateFlags","signature":"func AddValidateFlags(cmd *cobra.Command)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func AddValidateFlags(cmd *cobra.Command) {\n\tcmd.Flags().String(\n\t\t\"validate\",\n\t\t\"strict\",\n\t\t`Must be one of: strict (or true), warn, ignore (or false).\n\t\t\"true\" or \"strict\" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not.\n\t\t\"warn\" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as \"ignore\" otherwise.\n\t\t\"false\" or \"ignore\" will not perform any schema validation, silently dropping any unknown or duplicate fields.`,\n\t)\n\n\tcmd.Flags().Lookup(\"validate\").NoOptDefVal = \"strict\"\n}","line":{"from":437,"to":448}} {"id":100032272,"name":"AddFilenameOptionFlags","signature":"func AddFilenameOptionFlags(cmd *cobra.Command, options *resource.FilenameOptions, usage string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func AddFilenameOptionFlags(cmd *cobra.Command, options *resource.FilenameOptions, usage string) {\n\tAddJsonFilenameFlag(cmd.Flags(), \u0026options.Filenames, \"Filename, directory, or URL to files \"+usage)\n\tAddKustomizeFlag(cmd.Flags(), \u0026options.Kustomize)\n\tcmd.Flags().BoolVarP(\u0026options.Recursive, \"recursive\", \"R\", options.Recursive, \"Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.\")\n}","line":{"from":450,"to":454}} {"id":100032273,"name":"AddJsonFilenameFlag","signature":"func AddJsonFilenameFlag(flags *pflag.FlagSet, value *[]string, usage string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func AddJsonFilenameFlag(flags *pflag.FlagSet, value *[]string, usage string) {\n\tflags.StringSliceVarP(value, \"filename\", \"f\", *value, usage)\n\tannotations := make([]string, 0, len(resource.FileExtensions))\n\tfor _, ext := range resource.FileExtensions {\n\t\tannotations = append(annotations, strings.TrimLeft(ext, \".\"))\n\t}\n\tflags.SetAnnotation(\"filename\", cobra.BashCompFilenameExt, annotations)\n}","line":{"from":456,"to":463}} {"id":100032274,"name":"AddKustomizeFlag","signature":"func AddKustomizeFlag(flags *pflag.FlagSet, value *string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// AddKustomizeFlag adds kustomize flag to a command\nfunc AddKustomizeFlag(flags *pflag.FlagSet, value *string) {\n\tflags.StringVarP(value, \"kustomize\", \"k\", *value, \"Process the kustomization directory. This flag can't be used together with -f or -R.\")\n}","line":{"from":465,"to":468}} {"id":100032275,"name":"AddDryRunFlag","signature":"func AddDryRunFlag(cmd *cobra.Command)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// AddDryRunFlag adds dry-run flag to a command. Usually used by mutations.\nfunc AddDryRunFlag(cmd *cobra.Command) {\n\tcmd.Flags().String(\n\t\t\"dry-run\",\n\t\t\"none\",\n\t\t`Must be \"none\", \"server\", or \"client\". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource.`,\n\t)\n\tcmd.Flags().Lookup(\"dry-run\").NoOptDefVal = \"unchanged\"\n}","line":{"from":470,"to":478}} {"id":100032276,"name":"AddFieldManagerFlagVar","signature":"func AddFieldManagerFlagVar(cmd *cobra.Command, p *string, defaultFieldManager string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func AddFieldManagerFlagVar(cmd *cobra.Command, p *string, defaultFieldManager string) {\n\tcmd.Flags().StringVar(p, \"field-manager\", defaultFieldManager, \"Name of the manager used to track field ownership.\")\n}","line":{"from":480,"to":482}} {"id":100032277,"name":"AddContainerVarFlags","signature":"func AddContainerVarFlags(cmd *cobra.Command, p *string, containerName string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func AddContainerVarFlags(cmd *cobra.Command, p *string, containerName string) {\n\tcmd.Flags().StringVarP(p, \"container\", \"c\", containerName, \"Container name. If omitted, use the kubectl.kubernetes.io/default-container annotation for selecting the container to be attached or the first container in the pod will be chosen\")\n}","line":{"from":484,"to":486}} {"id":100032278,"name":"AddServerSideApplyFlags","signature":"func AddServerSideApplyFlags(cmd *cobra.Command)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func AddServerSideApplyFlags(cmd *cobra.Command) {\n\tcmd.Flags().Bool(\"server-side\", false, \"If true, apply runs in the server instead of the client.\")\n\tcmd.Flags().Bool(\"force-conflicts\", false, \"If true, server-side apply will force the changes against conflicts.\")\n}","line":{"from":488,"to":491}} {"id":100032279,"name":"AddPodRunningTimeoutFlag","signature":"func AddPodRunningTimeoutFlag(cmd *cobra.Command, defaultTimeout time.Duration)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func AddPodRunningTimeoutFlag(cmd *cobra.Command, defaultTimeout time.Duration) {\n\tcmd.Flags().Duration(\"pod-running-timeout\", defaultTimeout, \"The length of time (like 5s, 2m, or 3h, higher than zero) to wait until at least one pod is running\")\n}","line":{"from":493,"to":495}} {"id":100032280,"name":"AddApplyAnnotationFlags","signature":"func AddApplyAnnotationFlags(cmd *cobra.Command)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func AddApplyAnnotationFlags(cmd *cobra.Command) {\n\tcmd.Flags().Bool(ApplyAnnotationsFlag, false, \"If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.\")\n}","line":{"from":497,"to":499}} {"id":100032281,"name":"AddApplyAnnotationVarFlags","signature":"func AddApplyAnnotationVarFlags(cmd *cobra.Command, applyAnnotation *bool)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func AddApplyAnnotationVarFlags(cmd *cobra.Command, applyAnnotation *bool) {\n\tcmd.Flags().BoolVar(applyAnnotation, ApplyAnnotationsFlag, *applyAnnotation, \"If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.\")\n}","line":{"from":501,"to":503}} {"id":100032282,"name":"AddChunkSizeFlag","signature":"func AddChunkSizeFlag(cmd *cobra.Command, value *int64)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func AddChunkSizeFlag(cmd *cobra.Command, value *int64) {\n\tcmd.Flags().Int64Var(value, \"chunk-size\", *value,\n\t\t\"Return large lists in chunks rather than all at once. Pass 0 to disable. This flag is beta and may change in the future.\")\n}","line":{"from":505,"to":508}} {"id":100032283,"name":"AddLabelSelectorFlagVar","signature":"func AddLabelSelectorFlagVar(cmd *cobra.Command, p *string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func AddLabelSelectorFlagVar(cmd *cobra.Command, p *string) {\n\tcmd.Flags().StringVarP(p, \"selector\", \"l\", *p, \"Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2). Matching objects must satisfy all of the specified label constraints.\")\n}","line":{"from":510,"to":512}} {"id":100032284,"name":"AddPruningFlags","signature":"func AddPruningFlags(cmd *cobra.Command, prune *bool, pruneAllowlist *[]string, pruneWhitelist *[]string, all *bool, applySetRef *string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func AddPruningFlags(cmd *cobra.Command, prune *bool, pruneAllowlist *[]string, pruneWhitelist *[]string, all *bool, applySetRef *string) {\n\t// Flags associated with the original allowlist-based alpha\n\tcmd.Flags().StringArrayVar(pruneAllowlist, \"prune-allowlist\", *pruneAllowlist, \"Overwrite the default allowlist with \u003cgroup/version/kind\u003e for --prune\")\n\tcmd.Flags().StringArrayVar(pruneWhitelist, \"prune-whitelist\", *pruneWhitelist, \"Overwrite the default whitelist with \u003cgroup/version/kind\u003e for --prune\") // TODO: Remove this in kubectl 1.28 or later\n\t_ = cmd.Flags().MarkDeprecated(\"prune-whitelist\", \"Use --prune-allowlist instead.\")\n\tcmd.Flags().BoolVar(all, \"all\", *all, \"Select all resources in the namespace of the specified resource types.\")\n\n\t// Flags associated with the new ApplySet-based alpha\n\tif ApplySet.IsEnabled() {\n\t\tcmd.Flags().StringVar(applySetRef, \"applyset\", *applySetRef, \"[alpha] The name of the ApplySet that tracks which resources are being managed, for the purposes of determining what to prune. Live resources that are part of the ApplySet but have been removed from the provided configs will be deleted. Format: [RESOURCE][.GROUP]/NAME. A Secret will be used if no resource or group is specified.\")\n\t\tcmd.Flags().BoolVar(prune, \"prune\", *prune, \"Automatically delete previously applied resource objects that do not appear in the provided configs. For alpha1, use with either -l or --all. For alpha2, use with --applyset.\")\n\t} else {\n\t\t// different docs for the shared --prune flag if only alpha1 is enabled\n\t\tcmd.Flags().BoolVar(prune, \"prune\", *prune, \"Automatically delete resource objects, that do not appear in the configs and are created by either apply or create --save-config. Should be used with either -l or --all.\")\n\t}\n}","line":{"from":514,"to":529}} {"id":100032285,"name":"AddSubresourceFlags","signature":"func AddSubresourceFlags(cmd *cobra.Command, subresource *string, usage string, allowedSubresources ...string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func AddSubresourceFlags(cmd *cobra.Command, subresource *string, usage string, allowedSubresources ...string) {\n\tcmd.Flags().StringVar(subresource, \"subresource\", \"\", fmt.Sprintf(\"%s Must be one of %v. This flag is beta and may change in the future.\", usage, allowedSubresources))\n\tCheckErr(cmd.RegisterFlagCompletionFunc(\"subresource\", func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {\n\t\treturn allowedSubresources, cobra.ShellCompDirectiveNoFileComp\n\t}))\n}","line":{"from":531,"to":536}} {"id":100032286,"name":"Merge","signature":"func Merge(codec runtime.Codec, dst runtime.Object, fragment string) (runtime.Object, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// Merge converts the passed in object to JSON, merges the fragment into it using an RFC7396 JSON Merge Patch,\n// and returns the resulting object\n// TODO: merge assumes JSON serialization, and does not properly abstract API retrieval\nfunc Merge(codec runtime.Codec, dst runtime.Object, fragment string) (runtime.Object, error) {\n\t// encode dst into versioned json and apply fragment directly too it\n\ttarget, err := runtime.Encode(codec, dst)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpatched, err := jsonpatch.MergePatch(target, []byte(fragment))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tout, err := runtime.Decode(codec, patched)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}","line":{"from":542,"to":560}} {"id":100032287,"name":"StrategicMerge","signature":"func StrategicMerge(codec runtime.Codec, dst runtime.Object, fragment string, dataStruct runtime.Object) (runtime.Object, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// StrategicMerge converts the passed in object to JSON, merges the fragment into it using a Strategic Merge Patch,\n// and returns the resulting object\nfunc StrategicMerge(codec runtime.Codec, dst runtime.Object, fragment string, dataStruct runtime.Object) (runtime.Object, error) {\n\ttarget, err := runtime.Encode(codec, dst)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpatched, err := strategicpatch.StrategicMergePatch(target, []byte(fragment), dataStruct)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tout, err := runtime.Decode(codec, patched)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}","line":{"from":562,"to":578}} {"id":100032288,"name":"JSONPatch","signature":"func JSONPatch(codec runtime.Codec, dst runtime.Object, fragment string) (runtime.Object, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// JSONPatch converts the passed in object to JSON, performs an RFC6902 JSON Patch using operations specified in the\n// fragment, and returns the resulting object\nfunc JSONPatch(codec runtime.Codec, dst runtime.Object, fragment string) (runtime.Object, error) {\n\ttarget, err := runtime.Encode(codec, dst)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpatch, err := jsonpatch.DecodePatch([]byte(fragment))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpatched, err := patch.Apply(target)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tout, err := runtime.Decode(codec, patched)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}","line":{"from":580,"to":600}} {"id":100032289,"name":"DumpReaderToFile","signature":"func DumpReaderToFile(reader io.Reader, filename string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// DumpReaderToFile writes all data from the given io.Reader to the specified file\n// (usually for temporary use).\nfunc DumpReaderToFile(reader io.Reader, filename string) error {\n\tf, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tbuffer := make([]byte, 1024)\n\tfor {\n\t\tcount, err := reader.Read(buffer)\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = f.Write(buffer[:count])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":602,"to":626}} {"id":100032290,"name":"GetServerSideApplyFlag","signature":"func GetServerSideApplyFlag(cmd *cobra.Command) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func GetServerSideApplyFlag(cmd *cobra.Command) bool {\n\treturn GetFlagBool(cmd, \"server-side\")\n}","line":{"from":628,"to":630}} {"id":100032291,"name":"GetForceConflictsFlag","signature":"func GetForceConflictsFlag(cmd *cobra.Command) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func GetForceConflictsFlag(cmd *cobra.Command) bool {\n\treturn GetFlagBool(cmd, \"force-conflicts\")\n}","line":{"from":632,"to":634}} {"id":100032292,"name":"GetFieldManagerFlag","signature":"func GetFieldManagerFlag(cmd *cobra.Command) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func GetFieldManagerFlag(cmd *cobra.Command) string {\n\treturn GetFlagString(cmd, \"field-manager\")\n}","line":{"from":636,"to":638}} {"id":100032293,"name":"GetValidationDirective","signature":"func GetValidationDirective(cmd *cobra.Command) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func GetValidationDirective(cmd *cobra.Command) (string, error) {\n\tvar validateFlag = GetFlagString(cmd, \"validate\")\n\tb, err := strconv.ParseBool(validateFlag)\n\tif err != nil {\n\t\tswitch validateFlag {\n\t\tcase \"strict\":\n\t\t\treturn metav1.FieldValidationStrict, nil\n\t\tcase \"warn\":\n\t\t\treturn metav1.FieldValidationWarn, nil\n\t\tcase \"ignore\":\n\t\t\treturn metav1.FieldValidationIgnore, nil\n\t\tdefault:\n\t\t\treturn metav1.FieldValidationStrict, fmt.Errorf(`invalid - validate option %q; must be one of: strict (or true), warn, ignore (or false)`, validateFlag)\n\t\t}\n\t}\n\t// The flag was a boolean\n\tif b {\n\t\treturn metav1.FieldValidationStrict, nil\n\t}\n\treturn metav1.FieldValidationIgnore, nil\n}","line":{"from":640,"to":660}} {"id":100032294,"name":"GetDryRunStrategy","signature":"func GetDryRunStrategy(cmd *cobra.Command) (DryRunStrategy, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func GetDryRunStrategy(cmd *cobra.Command) (DryRunStrategy, error) {\n\tvar dryRunFlag = GetFlagString(cmd, \"dry-run\")\n\tb, err := strconv.ParseBool(dryRunFlag)\n\t// The flag is not a boolean\n\tif err != nil {\n\t\tswitch dryRunFlag {\n\t\tcase cmd.Flag(\"dry-run\").NoOptDefVal:\n\t\t\tklog.Warning(`--dry-run is deprecated and can be replaced with --dry-run=client.`)\n\t\t\treturn DryRunClient, nil\n\t\tcase \"client\":\n\t\t\treturn DryRunClient, nil\n\t\tcase \"server\":\n\t\t\treturn DryRunServer, nil\n\t\tcase \"none\":\n\t\t\treturn DryRunNone, nil\n\t\tdefault:\n\t\t\treturn DryRunNone, fmt.Errorf(`Invalid dry-run value (%v). Must be \"none\", \"server\", or \"client\".`, dryRunFlag)\n\t\t}\n\t}\n\t// The flag was a boolean\n\tif b {\n\t\tklog.Warningf(`--dry-run=%v is deprecated (boolean value) and can be replaced with --dry-run=%s.`, dryRunFlag, \"client\")\n\t\treturn DryRunClient, nil\n\t}\n\tklog.Warningf(`--dry-run=%v is deprecated (boolean value) and can be replaced with --dry-run=%s.`, dryRunFlag, \"none\")\n\treturn DryRunNone, nil\n}","line":{"from":685,"to":711}} {"id":100032295,"name":"PrintFlagsWithDryRunStrategy","signature":"func PrintFlagsWithDryRunStrategy(printFlags *genericclioptions.PrintFlags, dryRunStrategy DryRunStrategy) *genericclioptions.PrintFlags","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// PrintFlagsWithDryRunStrategy sets a success message at print time for the dry run strategy\n//\n// TODO(juanvallejo): This can be cleaned up even further by creating\n// a PrintFlags struct that binds the --dry-run flag, and whose\n// ToPrinter method returns a printer that understands how to print\n// this success message.\nfunc PrintFlagsWithDryRunStrategy(printFlags *genericclioptions.PrintFlags, dryRunStrategy DryRunStrategy) *genericclioptions.PrintFlags {\n\tswitch dryRunStrategy {\n\tcase DryRunClient:\n\t\tprintFlags.Complete(\"%s (dry run)\")\n\tcase DryRunServer:\n\t\tprintFlags.Complete(\"%s (server dry run)\")\n\t}\n\treturn printFlags\n}","line":{"from":713,"to":727}} {"id":100032296,"name":"GetResourcesAndPairs","signature":"func GetResourcesAndPairs(args []string, pairType string) (resources []string, pairArgs []string, err error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// GetResourcesAndPairs retrieves resources and \"KEY=VALUE or KEY-\" pair args from given args\nfunc GetResourcesAndPairs(args []string, pairType string) (resources []string, pairArgs []string, err error) {\n\tfoundPair := false\n\tfor _, s := range args {\n\t\tnonResource := (strings.Contains(s, \"=\") \u0026\u0026 s[0] != '=') || (strings.HasSuffix(s, \"-\") \u0026\u0026 s != \"-\")\n\t\tswitch {\n\t\tcase !foundPair \u0026\u0026 nonResource:\n\t\t\tfoundPair = true\n\t\t\tfallthrough\n\t\tcase foundPair \u0026\u0026 nonResource:\n\t\t\tpairArgs = append(pairArgs, s)\n\t\tcase !foundPair \u0026\u0026 !nonResource:\n\t\t\tresources = append(resources, s)\n\t\tcase foundPair \u0026\u0026 !nonResource:\n\t\t\terr = fmt.Errorf(\"all resources must be specified before %s changes: %s\", pairType, s)\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}","line":{"from":729,"to":748}} {"id":100032297,"name":"ParsePairs","signature":"func ParsePairs(pairArgs []string, pairType string, supportRemove bool) (newPairs map[string]string, removePairs []string, err error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// ParsePairs retrieves new and remove pairs (if supportRemove is true) from \"KEY=VALUE or KEY-\" pair args\nfunc ParsePairs(pairArgs []string, pairType string, supportRemove bool) (newPairs map[string]string, removePairs []string, err error) {\n\tnewPairs = map[string]string{}\n\tif supportRemove {\n\t\tremovePairs = []string{}\n\t}\n\tvar invalidBuf bytes.Buffer\n\tvar invalidBufNonEmpty bool\n\tfor _, pairArg := range pairArgs {\n\t\tif strings.Contains(pairArg, \"=\") \u0026\u0026 pairArg[0] != '=' {\n\t\t\tparts := strings.SplitN(pairArg, \"=\", 2)\n\t\t\tif len(parts) != 2 {\n\t\t\t\tif invalidBufNonEmpty {\n\t\t\t\t\tinvalidBuf.WriteString(\", \")\n\t\t\t\t}\n\t\t\t\tinvalidBuf.WriteString(pairArg)\n\t\t\t\tinvalidBufNonEmpty = true\n\t\t\t} else {\n\t\t\t\tnewPairs[parts[0]] = parts[1]\n\t\t\t}\n\t\t} else if supportRemove \u0026\u0026 strings.HasSuffix(pairArg, \"-\") \u0026\u0026 pairArg != \"-\" {\n\t\t\tremovePairs = append(removePairs, pairArg[:len(pairArg)-1])\n\t\t} else {\n\t\t\tif invalidBufNonEmpty {\n\t\t\t\tinvalidBuf.WriteString(\", \")\n\t\t\t}\n\t\t\tinvalidBuf.WriteString(pairArg)\n\t\t\tinvalidBufNonEmpty = true\n\t\t}\n\t}\n\tif invalidBufNonEmpty {\n\t\terr = fmt.Errorf(\"invalid %s format: %s\", pairType, invalidBuf.String())\n\t\treturn\n\t}\n\n\treturn\n}","line":{"from":750,"to":786}} {"id":100032298,"name":"IsSiblingCommandExists","signature":"func IsSiblingCommandExists(cmd *cobra.Command, targetCmdName string) bool","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// IsSiblingCommandExists receives a pointer to a cobra command and a target string.\n// Returns true if the target string is found in the list of sibling commands.\nfunc IsSiblingCommandExists(cmd *cobra.Command, targetCmdName string) bool {\n\tfor _, c := range cmd.Parent().Commands() {\n\t\tif c.Name() == targetCmdName {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":788,"to":798}} {"id":100032299,"name":"DefaultSubCommandRun","signature":"func DefaultSubCommandRun(out io.Writer) func(c *cobra.Command, args []string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// DefaultSubCommandRun prints a command's help string to the specified output if no\n// arguments (sub-commands) are provided, or a usage error otherwise.\nfunc DefaultSubCommandRun(out io.Writer) func(c *cobra.Command, args []string) {\n\treturn func(c *cobra.Command, args []string) {\n\t\tc.SetOut(out)\n\t\tc.SetErr(out)\n\t\tRequireNoArguments(c, args)\n\t\tc.Help()\n\t\tCheckErr(ErrExit)\n\t}\n}","line":{"from":800,"to":810}} {"id":100032300,"name":"RequireNoArguments","signature":"func RequireNoArguments(c *cobra.Command, args []string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// RequireNoArguments exits with a usage error if extra arguments are provided.\nfunc RequireNoArguments(c *cobra.Command, args []string) {\n\tif len(args) \u003e 0 {\n\t\tCheckErr(UsageErrorf(c, \"unknown command %q\", strings.Join(args, \" \")))\n\t}\n}","line":{"from":812,"to":817}} {"id":100032301,"name":"StripComments","signature":"func StripComments(file []byte) []byte","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// StripComments will transform a YAML file into JSON, thus dropping any comments\n// in it. Note that if the given file has a syntax error, the transformation will\n// fail and we will manually drop all comments from the file.\nfunc StripComments(file []byte) []byte {\n\tstripped := file\n\tstripped, err := yaml.ToJSON(stripped)\n\tif err != nil {\n\t\tstripped = ManualStrip(file)\n\t}\n\treturn stripped\n}","line":{"from":819,"to":829}} {"id":100032302,"name":"ManualStrip","signature":"func ManualStrip(file []byte) []byte","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// ManualStrip is used for dropping comments from a YAML file\nfunc ManualStrip(file []byte) []byte {\n\tstripped := []byte{}\n\tlines := bytes.Split(file, []byte(\"\\n\"))\n\tfor i, line := range lines {\n\t\ttrimline := bytes.TrimSpace(line)\n\n\t\tif bytes.HasPrefix(trimline, []byte(\"#\")) \u0026\u0026 !bytes.HasPrefix(trimline, []byte(\"#!\")) {\n\t\t\tcontinue\n\t\t}\n\t\tstripped = append(stripped, line...)\n\t\tif i \u003c len(lines)-1 {\n\t\t\tstripped = append(stripped, '\\n')\n\t\t}\n\t}\n\treturn stripped\n}","line":{"from":831,"to":847}} {"id":100032303,"name":"scaleClient","signature":"func scaleClient(restClientGetter genericclioptions.RESTClientGetter) (scale.ScalesGetter, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// scaleClient gives you back scale getter\nfunc scaleClient(restClientGetter genericclioptions.RESTClientGetter) (scale.ScalesGetter, error) {\n\tdiscoveryClient, err := restClientGetter.ToDiscoveryClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclientConfig, err := restClientGetter.ToRESTConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsetKubernetesDefaults(clientConfig)\n\trestClient, err := rest.RESTClientFor(clientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresolver := scale.NewDiscoveryScaleKindResolver(discoveryClient)\n\tmapper, err := restClientGetter.ToRESTMapper()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn scale.New(restClient, mapper, dynamic.LegacyAPIPathResolverFunc, resolver), nil\n}","line":{"from":855,"to":879}} {"id":100032304,"name":"Warning","signature":"func Warning(cmdErr io.Writer, newGeneratorName, oldGeneratorName string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"func Warning(cmdErr io.Writer, newGeneratorName, oldGeneratorName string) {\n\tfmt.Fprintf(cmdErr, \"WARNING: New generator %q specified, \"+\n\t\t\"but it isn't available. \"+\n\t\t\"Falling back to %q.\\n\",\n\t\tnewGeneratorName,\n\t\toldGeneratorName,\n\t)\n}","line":{"from":881,"to":888}} {"id":100032305,"name":"Difference","signature":"func Difference(fullArray []string, subArray []string) []string","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/helpers.go","code":"// Difference removes any elements of subArray from fullArray and returns the result\nfunc Difference(fullArray []string, subArray []string) []string {\n\texclude := make(map[string]bool, len(subArray))\n\tfor _, elem := range subArray {\n\t\texclude[elem] = true\n\t}\n\tvar result []string\n\tfor _, elem := range fullArray {\n\t\tif _, found := exclude[elem]; !found {\n\t\t\tresult = append(result, elem)\n\t\t}\n\t}\n\treturn result\n}","line":{"from":890,"to":903}} {"id":100032306,"name":"checkMatchingServerVersion","signature":"func (f *MatchVersionFlags) checkMatchingServerVersion() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/kubectl_match_version.go","code":"func (f *MatchVersionFlags) checkMatchingServerVersion() error {\n\tf.checkServerVersion.Do(func() {\n\t\tif !f.RequireMatchedServerVersion {\n\t\t\treturn\n\t\t}\n\t\tdiscoveryClient, err := f.Delegate.ToDiscoveryClient()\n\t\tif err != nil {\n\t\t\tf.matchesServerVersionErr = err\n\t\t\treturn\n\t\t}\n\t\tf.matchesServerVersionErr = discovery.MatchesServerVersion(version.Get(), discoveryClient)\n\t})\n\n\treturn f.matchesServerVersionErr\n}","line":{"from":50,"to":64}} {"id":100032307,"name":"ToRESTConfig","signature":"func (f *MatchVersionFlags) ToRESTConfig() (*rest.Config, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/kubectl_match_version.go","code":"// ToRESTConfig implements RESTClientGetter.\n// Returns a REST client configuration based on a provided path\n// to a .kubeconfig file, loading rules, and config flag overrides.\n// Expects the AddFlags method to have been called.\nfunc (f *MatchVersionFlags) ToRESTConfig() (*rest.Config, error) {\n\tif err := f.checkMatchingServerVersion(); err != nil {\n\t\treturn nil, err\n\t}\n\tclientConfig, err := f.Delegate.ToRESTConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// TODO we should not have to do this. It smacks of something going wrong.\n\tsetKubernetesDefaults(clientConfig)\n\treturn clientConfig, nil\n}","line":{"from":66,"to":81}} {"id":100032308,"name":"ToRawKubeConfigLoader","signature":"func (f *MatchVersionFlags) ToRawKubeConfigLoader() clientcmd.ClientConfig","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/kubectl_match_version.go","code":"func (f *MatchVersionFlags) ToRawKubeConfigLoader() clientcmd.ClientConfig {\n\treturn f.Delegate.ToRawKubeConfigLoader()\n}","line":{"from":83,"to":85}} {"id":100032309,"name":"ToDiscoveryClient","signature":"func (f *MatchVersionFlags) ToDiscoveryClient() (discovery.CachedDiscoveryInterface, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/kubectl_match_version.go","code":"func (f *MatchVersionFlags) ToDiscoveryClient() (discovery.CachedDiscoveryInterface, error) {\n\tif err := f.checkMatchingServerVersion(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.Delegate.ToDiscoveryClient()\n}","line":{"from":87,"to":92}} {"id":100032310,"name":"ToRESTMapper","signature":"func (f *MatchVersionFlags) ToRESTMapper() (meta.RESTMapper, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/kubectl_match_version.go","code":"// ToRESTMapper returns a mapper.\nfunc (f *MatchVersionFlags) ToRESTMapper() (meta.RESTMapper, error) {\n\tif err := f.checkMatchingServerVersion(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.Delegate.ToRESTMapper()\n}","line":{"from":94,"to":100}} {"id":100032311,"name":"AddFlags","signature":"func (f *MatchVersionFlags) AddFlags(flags *pflag.FlagSet)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/kubectl_match_version.go","code":"func (f *MatchVersionFlags) AddFlags(flags *pflag.FlagSet) {\n\tflags.BoolVar(\u0026f.RequireMatchedServerVersion, flagMatchBinaryVersion, f.RequireMatchedServerVersion, \"Require server version to match client version\")\n}","line":{"from":102,"to":104}} {"id":100032312,"name":"NewMatchVersionFlags","signature":"func NewMatchVersionFlags(delegate genericclioptions.RESTClientGetter) *MatchVersionFlags","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/kubectl_match_version.go","code":"func NewMatchVersionFlags(delegate genericclioptions.RESTClientGetter) *MatchVersionFlags {\n\treturn \u0026MatchVersionFlags{\n\t\tDelegate: delegate,\n\t}\n}","line":{"from":106,"to":110}} {"id":100032313,"name":"setKubernetesDefaults","signature":"func setKubernetesDefaults(config *rest.Config) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/kubectl_match_version.go","code":"// setKubernetesDefaults sets default values on the provided client config for accessing the\n// Kubernetes API or returns an error if any of the defaults are impossible or invalid.\n// TODO this isn't what we want. Each clientset should be setting defaults as it sees fit.\nfunc setKubernetesDefaults(config *rest.Config) error {\n\t// TODO remove this hack. This is allowing the GetOptions to be serialized.\n\tconfig.GroupVersion = \u0026schema.GroupVersion{Group: \"\", Version: \"v1\"}\n\n\tif config.APIPath == \"\" {\n\t\tconfig.APIPath = \"/api\"\n\t}\n\tif config.NegotiatedSerializer == nil {\n\t\t// This codec factory ensures the resources are not converted. Therefore, resources\n\t\t// will not be round-tripped through internal versions. Defaulting does not happen\n\t\t// on the client.\n\t\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\t}\n\treturn rest.SetKubernetesDefaults(config)\n}","line":{"from":112,"to":129}} {"id":100032314,"name":"AddOverrideFlags","signature":"func (o *OverrideOptions) AddOverrideFlags(cmd *cobra.Command)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/override_options.go","code":"func (o *OverrideOptions) AddOverrideFlags(cmd *cobra.Command) {\n\tcmd.Flags().StringVar(\u0026o.Overrides, \"overrides\", \"\", i18n.T(\"An inline JSON override for the generated object. If this is non-empty, it is used to override the generated object. Requires that the object supply a valid apiVersion field.\"))\n\tcmd.Flags().StringVar((*string)(\u0026o.OverrideType), \"override-type\", string(DefaultOverrideType), fmt.Sprintf(\"The method used to override the generated object: %s, %s, or %s.\", OverrideTypeJSON, OverrideTypeMerge, OverrideTypeStrategic))\n}","line":{"from":49,"to":52}} {"id":100032315,"name":"NewOverrider","signature":"func (o *OverrideOptions) NewOverrider(dataStruct runtime.Object) *Overrider","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/override_options.go","code":"func (o *OverrideOptions) NewOverrider(dataStruct runtime.Object) *Overrider {\n\treturn \u0026Overrider{\n\t\tOptions: o,\n\t\tDataStruct: dataStruct,\n\t}\n}","line":{"from":54,"to":59}} {"id":100032316,"name":"Apply","signature":"func (o *Overrider) Apply(obj runtime.Object) (runtime.Object, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/override_options.go","code":"func (o *Overrider) Apply(obj runtime.Object) (runtime.Object, error) {\n\tif len(o.Options.Overrides) == 0 {\n\t\treturn obj, nil\n\t}\n\n\tcodec := runtime.NewCodec(scheme.DefaultJSONEncoder(), scheme.Codecs.UniversalDecoder(scheme.Scheme.PrioritizedVersionsAllGroups()...))\n\n\tvar overrideType OverrideType\n\tif len(o.Options.OverrideType) == 0 {\n\t\toverrideType = DefaultOverrideType\n\t} else {\n\t\toverrideType = o.Options.OverrideType\n\t}\n\n\tswitch overrideType {\n\tcase OverrideTypeJSON:\n\t\treturn JSONPatch(codec, obj, o.Options.Overrides)\n\tcase OverrideTypeMerge:\n\t\treturn Merge(codec, obj, o.Options.Overrides)\n\tcase OverrideTypeStrategic:\n\t\treturn StrategicMerge(codec, obj, o.Options.Overrides, o.DataStruct)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid override type: %v\", overrideType)\n\t}\n}","line":{"from":66,"to":90}} {"id":100032317,"name":"FindContainerByName","signature":"func FindContainerByName(pod *v1.Pod, name string) (*v1.Container, string)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/podcmd/podcmd.go","code":"// FindContainerByName selects the named container from the spec of\n// the provided pod or return nil if no such container exists.\nfunc FindContainerByName(pod *v1.Pod, name string) (*v1.Container, string) {\n\tfor i := range pod.Spec.Containers {\n\t\tif pod.Spec.Containers[i].Name == name {\n\t\t\treturn \u0026pod.Spec.Containers[i], fmt.Sprintf(\"spec.containers{%s}\", name)\n\t\t}\n\t}\n\tfor i := range pod.Spec.InitContainers {\n\t\tif pod.Spec.InitContainers[i].Name == name {\n\t\t\treturn \u0026pod.Spec.InitContainers[i], fmt.Sprintf(\"spec.initContainers{%s}\", name)\n\t\t}\n\t}\n\tfor i := range pod.Spec.EphemeralContainers {\n\t\tif pod.Spec.EphemeralContainers[i].Name == name {\n\t\t\treturn (*v1.Container)(\u0026pod.Spec.EphemeralContainers[i].EphemeralContainerCommon), fmt.Sprintf(\"spec.ephemeralContainers{%s}\", name)\n\t\t}\n\t}\n\treturn nil, \"\"\n}","line":{"from":32,"to":51}} {"id":100032318,"name":"FindOrDefaultContainerByName","signature":"func FindOrDefaultContainerByName(pod *v1.Pod, name string, quiet bool, warn io.Writer) (*v1.Container, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/podcmd/podcmd.go","code":"// FindOrDefaultContainerByName defaults a container for a pod to the first container if any\n// exists, or returns an error. It will print a message to the user indicating a default was\n// selected if there was more than one container.\nfunc FindOrDefaultContainerByName(pod *v1.Pod, name string, quiet bool, warn io.Writer) (*v1.Container, error) {\n\tvar container *v1.Container\n\n\tif len(name) \u003e 0 {\n\t\tcontainer, _ = FindContainerByName(pod, name)\n\t\tif container == nil {\n\t\t\treturn nil, fmt.Errorf(\"container %s not found in pod %s\", name, pod.Name)\n\t\t}\n\t\treturn container, nil\n\t}\n\n\t// this should never happen, but just in case\n\tif len(pod.Spec.Containers) == 0 {\n\t\treturn nil, fmt.Errorf(\"pod %s/%s does not have any containers\", pod.Namespace, pod.Name)\n\t}\n\n\t// read the default container the annotation as per\n\t// https://github.com/kubernetes/enhancements/tree/master/keps/sig-cli/2227-kubectl-default-container\n\tif name := pod.Annotations[DefaultContainerAnnotationName]; len(name) \u003e 0 {\n\t\tif container, _ = FindContainerByName(pod, name); container != nil {\n\t\t\tklog.V(4).Infof(\"Defaulting container name from annotation %s\", container.Name)\n\t\t\treturn container, nil\n\t\t}\n\t\tklog.V(4).Infof(\"Default container name from annotation %s was not found in the pod\", name)\n\t}\n\n\t// pick the first container as per existing behavior\n\tcontainer = \u0026pod.Spec.Containers[0]\n\tif !quiet \u0026\u0026 (len(pod.Spec.Containers) \u003e 1 || len(pod.Spec.InitContainers) \u003e 0 || len(pod.Spec.EphemeralContainers) \u003e 0) {\n\t\tfmt.Fprintf(warn, \"Defaulted container %q out of: %s\\n\", container.Name, AllContainerNames(pod))\n\t}\n\n\tklog.V(4).Infof(\"Defaulting container name to %s\", container.Name)\n\treturn \u0026pod.Spec.Containers[0], nil\n}","line":{"from":53,"to":90}} {"id":100032319,"name":"AllContainerNames","signature":"func AllContainerNames(pod *v1.Pod) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/podcmd/podcmd.go","code":"func AllContainerNames(pod *v1.Pod) string {\n\tvar containers []string\n\tfor _, container := range pod.Spec.Containers {\n\t\tcontainers = append(containers, container.Name)\n\t}\n\tfor _, container := range pod.Spec.EphemeralContainers {\n\t\tcontainers = append(containers, fmt.Sprintf(\"%s (ephem)\", container.Name))\n\t}\n\tfor _, container := range pod.Spec.InitContainers {\n\t\tcontainers = append(containers, fmt.Sprintf(\"%s (init)\", container.Name))\n\t}\n\treturn strings.Join(containers, \", \")\n}","line":{"from":92,"to":104}} {"id":100032320,"name":"SuggestAPIResources","signature":"func SuggestAPIResources(parent string) string","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/printing.go","code":"// SuggestAPIResources returns a suggestion to use the \"api-resources\" command\n// to retrieve a supported list of resources\nfunc SuggestAPIResources(parent string) string {\n\treturn templates.LongDesc(fmt.Sprintf(\"Use \\\"%s api-resources\\\" for a complete list of supported resources.\", parent))\n}","line":{"from":25,"to":29}} {"id":100032321,"name":"RunGlobalChecks","signature":"func RunGlobalChecks(globalChecks []GlobalCheck) []error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/sanity/cmd_sanity.go","code":"// RunGlobalChecks runs all the GlobalCheck functions passed and checks for error\nfunc RunGlobalChecks(globalChecks []GlobalCheck) []error {\n\tfmt.Fprint(os.Stdout, \"---+ RUNNING GLOBAL CHECKS\\n\")\n\terrors := []error{}\n\tfor _, check := range globalChecks {\n\t\terrors = append(errors, check()...)\n\t}\n\treturn errors\n}","line":{"from":51,"to":59}} {"id":100032322,"name":"RunCmdChecks","signature":"func RunCmdChecks(cmd *cobra.Command, cmdChecks []CmdCheck, skipCmd []string) []error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/sanity/cmd_sanity.go","code":"// RunCmdChecks runs all the CmdCheck functions passed, skipping skippable commands and looks for error\nfunc RunCmdChecks(cmd *cobra.Command, cmdChecks []CmdCheck, skipCmd []string) []error {\n\tcmdPath := cmd.CommandPath()\n\n\tfor _, skipCmdPath := range skipCmd {\n\t\tif cmdPath == skipCmdPath {\n\t\t\tfmt.Fprintf(os.Stdout, \"---+ skipping command %s\\n\", cmdPath)\n\t\t\treturn []error{}\n\t\t}\n\t}\n\n\terrors := []error{}\n\n\tif cmd.HasSubCommands() {\n\t\tfor _, subCmd := range cmd.Commands() {\n\t\t\terrors = append(errors, RunCmdChecks(subCmd, cmdChecks, skipCmd)...)\n\t\t}\n\t}\n\n\tfmt.Fprintf(os.Stdout, \"---+ RUNNING COMMAND CHECKS on %q\\n\", cmdPath)\n\n\tfor _, check := range cmdChecks {\n\t\tif err := check(cmd); len(err) \u003e 0 {\n\t\t\terrors = append(errors, err...)\n\t\t}\n\t}\n\n\treturn errors\n}","line":{"from":61,"to":89}} {"id":100032323,"name":"CheckLongDesc","signature":"func CheckLongDesc(cmd *cobra.Command) []error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/sanity/cmd_sanity.go","code":"// CheckLongDesc checks if the long description is valid\nfunc CheckLongDesc(cmd *cobra.Command) []error {\n\tfmt.Fprint(os.Stdout, \" ↳ checking long description\\n\")\n\tcmdPath := cmd.CommandPath()\n\tlong := cmd.Long\n\tif len(long) \u003e 0 {\n\t\tif strings.Trim(long, \" \\t\\n\") != long {\n\t\t\treturn []error{fmt.Errorf(`command %q: long description is not normalized, make sure you are calling templates.LongDesc (from pkg/cmd/templates) before assigning cmd.Long`, cmdPath)}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":91,"to":102}} {"id":100032324,"name":"CheckExamples","signature":"func CheckExamples(cmd *cobra.Command) []error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/sanity/cmd_sanity.go","code":"// CheckExamples checks if the command examples are valid\nfunc CheckExamples(cmd *cobra.Command) []error {\n\tfmt.Fprint(os.Stdout, \" ↳ checking examples\\n\")\n\tcmdPath := cmd.CommandPath()\n\texamples := cmd.Example\n\terrors := []error{}\n\tif len(examples) \u003e 0 {\n\t\tfor _, line := range strings.Split(examples, \"\\n\") {\n\t\t\tif !strings.HasPrefix(line, templates.Indentation) {\n\t\t\t\terrors = append(errors, fmt.Errorf(`command %q: examples are not normalized, make sure you are calling templates.Examples (from pkg/cmd/templates) before assigning cmd.Example`, cmdPath))\n\t\t\t}\n\t\t\tif trimmed := strings.TrimSpace(line); strings.HasPrefix(trimmed, \"//\") {\n\t\t\t\terrors = append(errors, fmt.Errorf(`command %q: we use # to start comments in examples instead of //`, cmdPath))\n\t\t\t}\n\t\t}\n\t}\n\treturn errors\n}","line":{"from":104,"to":121}} {"id":100032325,"name":"CheckFlags","signature":"func CheckFlags(cmd *cobra.Command) []error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/sanity/cmd_sanity.go","code":"// CheckFlags checks if the command-line flags are valid\nfunc CheckFlags(cmd *cobra.Command) []error {\n\tallFlagsSlice := []*pflag.Flag{}\n\n\tcmd.Flags().VisitAll(func(f *pflag.Flag) {\n\t\tallFlagsSlice = append(allFlagsSlice, f)\n\t})\n\tcmd.PersistentFlags().VisitAll(func(f *pflag.Flag) {\n\t\tallFlagsSlice = append(allFlagsSlice, f)\n\t})\n\n\tfmt.Fprintf(os.Stdout, \" ↳ checking %d flags\\n\", len(allFlagsSlice))\n\n\terrors := []error{}\n\n\t// check flags long names\n\tregex, err := regexp.Compile(`^[a-z]+[a-z\\-]*$`)\n\tif err != nil {\n\t\terrors = append(errors, fmt.Errorf(\"command %q: unable to compile regex to check flags\", cmd.CommandPath()))\n\t\treturn errors\n\t}\n\tfor _, flag := range allFlagsSlice {\n\t\tname := flag.Name\n\t\tif !regex.MatchString(name) {\n\t\t\terrors = append(errors, fmt.Errorf(\"command %q: flag name %q is invalid, long form of flag names can only contain lowercase characters or dash (must match %v)\", cmd.CommandPath(), name, regex))\n\t\t}\n\t}\n\n\treturn errors\n}","line":{"from":123,"to":152}} {"id":100032326,"name":"CheckGlobalVarFlags","signature":"func CheckGlobalVarFlags() []error","file":"staging/src/k8s.io/kubectl/pkg/cmd/util/sanity/cmd_sanity.go","code":"// CheckGlobalVarFlags checks if the global flags are valid\nfunc CheckGlobalVarFlags() []error {\n\tfmt.Fprint(os.Stdout, \" ↳ checking flags from global vars\\n\")\n\terrors := []error{}\n\tpflag.CommandLine.VisitAll(func(f *pflag.Flag) {\n\t\terrors = append(errors, fmt.Errorf(\"flag %q is invalid, please don't register any flag under the global variable \\\"CommandLine\\\"\", f.Name))\n\t})\n\treturn errors\n}","line":{"from":154,"to":162}} {"id":100032327,"name":"printVersionSkewWarning","signature":"func printVersionSkewWarning(w io.Writer, clientVersion, serverVersion apimachineryversion.Info) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/version/skew_warning.go","code":"// printVersionSkewWarning prints a warning message if the difference between the client and version is greater than\n// the supported version skew.\nfunc printVersionSkewWarning(w io.Writer, clientVersion, serverVersion apimachineryversion.Info) error {\n\tparsedClientVersion, err := version.ParseSemantic(clientVersion.GitVersion)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tparsedServerVersion, err := version.ParseSemantic(serverVersion.GitVersion)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmajorVersionDifference := math.Abs(float64(parsedClientVersion.Major()) - float64(parsedServerVersion.Major()))\n\tminorVersionDifference := math.Abs(float64(parsedClientVersion.Minor()) - float64(parsedServerVersion.Minor()))\n\n\tif majorVersionDifference \u003e 0 || minorVersionDifference \u003e supportedMinorVersionSkew {\n\t\tfmt.Fprintf(w, \"WARNING: version difference between client (%d.%d) and server (%d.%d) exceeds the supported minor version skew of +/-%d\\n\",\n\t\t\tparsedClientVersion.Major(), parsedClientVersion.Minor(), parsedServerVersion.Major(), parsedServerVersion.Minor(), supportedMinorVersionSkew)\n\t}\n\n\treturn nil\n}","line":{"from":32,"to":54}} {"id":100032328,"name":"NewOptions","signature":"func NewOptions(ioStreams genericclioptions.IOStreams) *Options","file":"staging/src/k8s.io/kubectl/pkg/cmd/version/version.go","code":"// NewOptions returns initialized Options\nfunc NewOptions(ioStreams genericclioptions.IOStreams) *Options {\n\treturn \u0026Options{\n\t\tIOStreams: ioStreams,\n\t}\n\n}","line":{"from":67,"to":73}} {"id":100032329,"name":"NewCmdVersion","signature":"func NewCmdVersion(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/version/version.go","code":"// NewCmdVersion returns a cobra command for fetching versions\nfunc NewCmdVersion(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {\n\to := NewOptions(ioStreams)\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"version\",\n\t\tShort: i18n.T(\"Print the client and server version information\"),\n\t\tLong: i18n.T(\"Print the client and server version information for the current context.\"),\n\t\tExample: versionExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(f, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate())\n\t\t\tcmdutil.CheckErr(o.Run())\n\t\t},\n\t}\n\tcmd.Flags().BoolVar(\u0026o.ClientOnly, \"client\", o.ClientOnly, \"If true, shows client version only (no server required).\")\n\tcmd.Flags().BoolVar(\u0026o.Short, \"short\", o.Short, \"If true, print just the version number.\")\n\tcmd.Flags().MarkDeprecated(\"short\", \"and will be removed in the future. The --short output will become the default.\")\n\tcmd.Flags().StringVarP(\u0026o.Output, \"output\", \"o\", o.Output, \"One of 'yaml' or 'json'.\")\n\treturn cmd\n}","line":{"from":75,"to":94}} {"id":100032330,"name":"Complete","signature":"func (o *Options) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/version/version.go","code":"// Complete completes all the required options\nfunc (o *Options) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\tif o.ClientOnly {\n\t\treturn nil\n\t}\n\to.discoveryClient, err = f.ToDiscoveryClient()\n\t// if we had an empty rest.Config, continue and just print out client information.\n\t// if we had an error other than being unable to build a rest.Config, fail.\n\tif err != nil \u0026\u0026 !clientcmd.IsEmptyConfig(err) {\n\t\treturn err\n\t}\n\n\to.args = args\n\treturn nil\n}","line":{"from":96,"to":111}} {"id":100032331,"name":"Validate","signature":"func (o *Options) Validate() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/version/version.go","code":"// Validate validates the provided options\nfunc (o *Options) Validate() error {\n\tif len(o.args) != 0 {\n\t\treturn errors.New(fmt.Sprintf(\"extra arguments: %v\", o.args))\n\t}\n\n\tif o.Output != \"\" \u0026\u0026 o.Output != \"yaml\" \u0026\u0026 o.Output != \"json\" {\n\t\treturn errors.New(`--output must be 'yaml' or 'json'`)\n\t}\n\n\treturn nil\n}","line":{"from":113,"to":124}} {"id":100032332,"name":"Run","signature":"func (o *Options) Run() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/version/version.go","code":"// Run executes version command\nfunc (o *Options) Run() error {\n\tvar (\n\t\tserverErr error\n\t\tversionInfo Version\n\t)\n\n\tversionInfo.ClientVersion = func() *apimachineryversion.Info { v := version.Get(); return \u0026v }()\n\tversionInfo.KustomizeVersion = getKustomizeVersion()\n\n\tif !o.ClientOnly \u0026\u0026 o.discoveryClient != nil {\n\t\t// Always request fresh data from the server\n\t\to.discoveryClient.Invalidate()\n\t\tversionInfo.ServerVersion, serverErr = o.discoveryClient.ServerVersion()\n\t}\n\n\tswitch o.Output {\n\tcase \"\":\n\t\tif o.Short {\n\t\t\tfmt.Fprintf(o.Out, \"Client Version: %s\\n\", versionInfo.ClientVersion.GitVersion)\n\t\t\tfmt.Fprintf(o.Out, \"Kustomize Version: %s\\n\", versionInfo.KustomizeVersion)\n\t\t\tif versionInfo.ServerVersion != nil {\n\t\t\t\tfmt.Fprintf(o.Out, \"Server Version: %s\\n\", versionInfo.ServerVersion.GitVersion)\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Fprintf(o.ErrOut, \"WARNING: This version information is deprecated and will be replaced with the output from kubectl version --short. Use --output=yaml|json to get the full version.\\n\")\n\t\t\tfmt.Fprintf(o.Out, \"Client Version: %#v\\n\", *versionInfo.ClientVersion)\n\t\t\tfmt.Fprintf(o.Out, \"Kustomize Version: %s\\n\", versionInfo.KustomizeVersion)\n\t\t\tif versionInfo.ServerVersion != nil {\n\t\t\t\tfmt.Fprintf(o.Out, \"Server Version: %#v\\n\", *versionInfo.ServerVersion)\n\t\t\t}\n\t\t}\n\tcase \"yaml\":\n\t\tmarshalled, err := yaml.Marshal(\u0026versionInfo)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Fprintln(o.Out, string(marshalled))\n\tcase \"json\":\n\t\tmarshalled, err := json.MarshalIndent(\u0026versionInfo, \"\", \" \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Fprintln(o.Out, string(marshalled))\n\tdefault:\n\t\t// There is a bug in the program if we hit this case.\n\t\t// However, we follow a policy of never panicking.\n\t\treturn fmt.Errorf(\"VersionOptions were not validated: --output=%q should have been rejected\", o.Output)\n\t}\n\n\tif versionInfo.ServerVersion != nil {\n\t\tif err := printVersionSkewWarning(o.ErrOut, *versionInfo.ClientVersion, *versionInfo.ServerVersion); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn serverErr\n}","line":{"from":126,"to":183}} {"id":100032333,"name":"getKustomizeVersion","signature":"func getKustomizeVersion() string","file":"staging/src/k8s.io/kubectl/pkg/cmd/version/version.go","code":"func getKustomizeVersion() string {\n\tif modVersion, ok := GetKustomizeModVersion(); ok {\n\t\treturn modVersion\n\t}\n\treturn kustomizeVersion // other clients should provide their own fallback\n}","line":{"from":185,"to":190}} {"id":100032334,"name":"GetKustomizeModVersion","signature":"func GetKustomizeModVersion() (string, bool)","file":"staging/src/k8s.io/kubectl/pkg/cmd/version/version.go","code":"func GetKustomizeModVersion() (string, bool) {\n\tinfo, ok := debug.ReadBuildInfo()\n\tif !ok {\n\t\treturn \"\", false\n\t}\n\tfor _, dep := range info.Deps {\n\t\tif dep.Path == \"sigs.k8s.io/kustomize/kustomize/v4\" || dep.Path == \"sigs.k8s.io/kustomize/kustomize/v5\" {\n\t\t\treturn dep.Version, true\n\t\t}\n\t}\n\treturn \"\", false\n}","line":{"from":192,"to":203}} {"id":100032335,"name":"NewWaitFlags","signature":"func NewWaitFlags(restClientGetter genericclioptions.RESTClientGetter, streams genericclioptions.IOStreams) *WaitFlags","file":"staging/src/k8s.io/kubectl/pkg/cmd/wait/wait.go","code":"// NewWaitFlags returns a default WaitFlags\nfunc NewWaitFlags(restClientGetter genericclioptions.RESTClientGetter, streams genericclioptions.IOStreams) *WaitFlags {\n\treturn \u0026WaitFlags{\n\t\tRESTClientGetter: restClientGetter,\n\t\tPrintFlags: genericclioptions.NewPrintFlags(\"condition met\"),\n\t\tResourceBuilderFlags: genericclioptions.NewResourceBuilderFlags().\n\t\t\tWithLabelSelector(\"\").\n\t\t\tWithFieldSelector(\"\").\n\t\t\tWithAll(false).\n\t\t\tWithAllNamespaces(false).\n\t\t\tWithLocal(false).\n\t\t\tWithLatest(),\n\n\t\tTimeout: 30 * time.Second,\n\n\t\tIOStreams: streams,\n\t}\n}","line":{"from":98,"to":115}} {"id":100032336,"name":"NewCmdWait","signature":"func NewCmdWait(restClientGetter genericclioptions.RESTClientGetter, streams genericclioptions.IOStreams) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/cmd/wait/wait.go","code":"// NewCmdWait returns a cobra command for waiting\nfunc NewCmdWait(restClientGetter genericclioptions.RESTClientGetter, streams genericclioptions.IOStreams) *cobra.Command {\n\tflags := NewWaitFlags(restClientGetter, streams)\n\n\tcmd := \u0026cobra.Command{\n\t\tUse: \"wait ([-f FILENAME] | resource.group/resource.name | resource.group [(-l label | --all)]) [--for=delete|--for condition=available|--for=jsonpath='{}'=value]\",\n\t\tShort: i18n.T(\"Experimental: Wait for a specific condition on one or many resources\"),\n\t\tLong: waitLong,\n\t\tExample: waitExample,\n\n\t\tDisableFlagsInUseLine: true,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\to, err := flags.ToOptions(args)\n\t\t\tcmdutil.CheckErr(err)\n\t\t\tcmdutil.CheckErr(o.RunWait())\n\t\t},\n\t\tSuggestFor: []string{\"list\", \"ps\"},\n\t}\n\n\tflags.AddFlags(cmd)\n\n\treturn cmd\n}","line":{"from":117,"to":139}} {"id":100032337,"name":"AddFlags","signature":"func (flags *WaitFlags) AddFlags(cmd *cobra.Command)","file":"staging/src/k8s.io/kubectl/pkg/cmd/wait/wait.go","code":"// AddFlags registers flags for a cli\nfunc (flags *WaitFlags) AddFlags(cmd *cobra.Command) {\n\tflags.PrintFlags.AddFlags(cmd)\n\tflags.ResourceBuilderFlags.AddFlags(cmd.Flags())\n\n\tcmd.Flags().DurationVar(\u0026flags.Timeout, \"timeout\", flags.Timeout, \"The length of time to wait before giving up. Zero means check once and don't wait, negative means wait for a week.\")\n\tcmd.Flags().StringVar(\u0026flags.ForCondition, \"for\", flags.ForCondition, \"The condition to wait on: [delete|condition=condition-name[=condition-value]|jsonpath='{JSONPath expression}'=JSONPath Condition]. The default condition-value is true. Condition values are compared after Unicode simple case folding, which is a more general form of case-insensitivity.\")\n}","line":{"from":141,"to":148}} {"id":100032338,"name":"ToOptions","signature":"func (flags *WaitFlags) ToOptions(args []string) (*WaitOptions, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/wait/wait.go","code":"// ToOptions converts from CLI inputs to runtime inputs\nfunc (flags *WaitFlags) ToOptions(args []string) (*WaitOptions, error) {\n\tprinter, err := flags.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbuilder := flags.ResourceBuilderFlags.ToBuilder(flags.RESTClientGetter, args)\n\tclientConfig, err := flags.RESTClientGetter.ToRESTConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdynamicClient, err := dynamic.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconditionFn, err := conditionFuncFor(flags.ForCondition, flags.ErrOut)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\teffectiveTimeout := flags.Timeout\n\tif effectiveTimeout \u003c 0 {\n\t\teffectiveTimeout = 168 * time.Hour\n\t}\n\n\to := \u0026WaitOptions{\n\t\tResourceFinder: builder,\n\t\tDynamicClient: dynamicClient,\n\t\tTimeout: effectiveTimeout,\n\t\tForCondition: flags.ForCondition,\n\n\t\tPrinter: printer,\n\t\tConditionFn: conditionFn,\n\t\tIOStreams: flags.IOStreams,\n\t}\n\n\treturn o, nil\n}","line":{"from":150,"to":187}} {"id":100032339,"name":"conditionFuncFor","signature":"func conditionFuncFor(condition string, errOut io.Writer) (ConditionFunc, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/wait/wait.go","code":"func conditionFuncFor(condition string, errOut io.Writer) (ConditionFunc, error) {\n\tif strings.ToLower(condition) == \"delete\" {\n\t\treturn IsDeleted, nil\n\t}\n\tif strings.HasPrefix(condition, \"condition=\") {\n\t\tconditionName := condition[len(\"condition=\"):]\n\t\tconditionValue := \"true\"\n\t\tif equalsIndex := strings.Index(conditionName, \"=\"); equalsIndex != -1 {\n\t\t\tconditionValue = conditionName[equalsIndex+1:]\n\t\t\tconditionName = conditionName[0:equalsIndex]\n\t\t}\n\n\t\treturn ConditionalWait{\n\t\t\tconditionName: conditionName,\n\t\t\tconditionStatus: conditionValue,\n\t\t\terrOut: errOut,\n\t\t}.IsConditionMet, nil\n\t}\n\tif strings.HasPrefix(condition, \"jsonpath=\") {\n\t\tsplitStr := strings.Split(condition, \"=\")\n\t\tif len(splitStr) != 3 {\n\t\t\treturn nil, fmt.Errorf(\"jsonpath wait format must be --for=jsonpath='{.status.readyReplicas}'=3\")\n\t\t}\n\t\tjsonPathExp, jsonPathCond, err := processJSONPathInput(splitStr[1], splitStr[2])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tj, err := newJSONPathParser(jsonPathExp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn JSONPathWait{\n\t\t\tjsonPathCondition: jsonPathCond,\n\t\t\tjsonPathParser: j,\n\t\t\terrOut: errOut,\n\t\t}.IsJSONPathConditionMet, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"unrecognized condition: %q\", condition)\n}","line":{"from":189,"to":228}} {"id":100032340,"name":"newJSONPathParser","signature":"func newJSONPathParser(jsonPathExpression string) (*jsonpath.JSONPath, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/wait/wait.go","code":"// newJSONPathParser will create a new JSONPath parser based on the jsonPathExpression\nfunc newJSONPathParser(jsonPathExpression string) (*jsonpath.JSONPath, error) {\n\tj := jsonpath.New(\"wait\").AllowMissingKeys(true)\n\tif jsonPathExpression == \"\" {\n\t\treturn nil, errors.New(\"jsonpath expression cannot be empty\")\n\t}\n\tif err := j.Parse(jsonPathExpression); err != nil {\n\t\treturn nil, err\n\t}\n\treturn j, nil\n}","line":{"from":230,"to":240}} {"id":100032341,"name":"processJSONPathInput","signature":"func processJSONPathInput(jsonPathExpression, jsonPathCond string) (string, string, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/wait/wait.go","code":"// processJSONPathInput will parses the user's JSONPath input and process the string\nfunc processJSONPathInput(jsonPathExpression, jsonPathCond string) (string, string, error) {\n\trelaxedJSONPathExp, err := cmdget.RelaxedJSONPathExpression(jsonPathExpression)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tif jsonPathCond == \"\" {\n\t\treturn \"\", \"\", errors.New(\"jsonpath wait condition cannot be empty\")\n\t}\n\tjsonPathCond = strings.Trim(jsonPathCond, `'\"`)\n\n\treturn relaxedJSONPathExp, jsonPathCond, nil\n}","line":{"from":242,"to":254}} {"id":100032342,"name":"RunWait","signature":"func (o *WaitOptions) RunWait() error","file":"staging/src/k8s.io/kubectl/pkg/cmd/wait/wait.go","code":"// RunWait runs the waiting logic\nfunc (o *WaitOptions) RunWait() error {\n\tctx, cancel := watchtools.ContextWithOptionalTimeout(context.Background(), o.Timeout)\n\tdefer cancel()\n\n\tvisitCount := 0\n\tvisitFunc := func(info *resource.Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvisitCount++\n\t\tfinalObject, success, err := o.ConditionFn(ctx, info, o)\n\t\tif success {\n\t\t\to.Printer.PrintObj(finalObject, o.Out)\n\t\t\treturn nil\n\t\t}\n\t\tif err == nil {\n\t\t\treturn fmt.Errorf(\"%v unsatisified for unknown reason\", finalObject)\n\t\t}\n\t\treturn err\n\t}\n\tvisitor := o.ResourceFinder.Do()\n\tisForDelete := strings.ToLower(o.ForCondition) == \"delete\"\n\tif visitor, ok := visitor.(*resource.Result); ok \u0026\u0026 isForDelete {\n\t\tvisitor.IgnoreErrors(apierrors.IsNotFound)\n\t}\n\n\terr := visitor.Visit(visitFunc)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif visitCount == 0 \u0026\u0026 !isForDelete {\n\t\treturn errNoMatchingResources\n\t}\n\treturn err\n}","line":{"from":285,"to":321}} {"id":100032343,"name":"IsDeleted","signature":"func IsDeleted(ctx context.Context, info *resource.Info, o *WaitOptions) (runtime.Object, bool, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/wait/wait.go","code":"// IsDeleted is a condition func for waiting for something to be deleted\nfunc IsDeleted(ctx context.Context, info *resource.Info, o *WaitOptions) (runtime.Object, bool, error) {\n\tif len(info.Name) == 0 {\n\t\treturn info.Object, false, fmt.Errorf(\"resource name must be provided\")\n\t}\n\n\tgottenObj, initObjGetErr := o.DynamicClient.Resource(info.Mapping.Resource).Namespace(info.Namespace).Get(context.Background(), info.Name, metav1.GetOptions{})\n\tif apierrors.IsNotFound(initObjGetErr) {\n\t\treturn info.Object, true, nil\n\t}\n\tif initObjGetErr != nil {\n\t\t// TODO this could do something slightly fancier if we wish\n\t\treturn info.Object, false, initObjGetErr\n\t}\n\tresourceLocation := ResourceLocation{\n\t\tGroupResource: info.Mapping.Resource.GroupResource(),\n\t\tNamespace: gottenObj.GetNamespace(),\n\t\tName: gottenObj.GetName(),\n\t}\n\tif uid, ok := o.UIDMap[resourceLocation]; ok {\n\t\tif gottenObj.GetUID() != uid {\n\t\t\treturn gottenObj, true, nil\n\t\t}\n\t}\n\n\tendTime := time.Now().Add(o.Timeout)\n\ttimeout := time.Until(endTime)\n\terrWaitTimeoutWithName := extendErrWaitTimeout(wait.ErrWaitTimeout, info)\n\tif o.Timeout == 0 {\n\t\t// If timeout is zero check if the object exists once only\n\t\tif gottenObj == nil {\n\t\t\treturn nil, true, nil\n\t\t}\n\t\treturn gottenObj, false, fmt.Errorf(\"condition not met for %s\", info.ObjectName())\n\t}\n\tif timeout \u003c 0 {\n\t\t// we're out of time\n\t\treturn info.Object, false, errWaitTimeoutWithName\n\t}\n\n\tfieldSelector := fields.OneTermEqualSelector(\"metadata.name\", info.Name).String()\n\tlw := \u0026cache.ListWatch{\n\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\toptions.FieldSelector = fieldSelector\n\t\t\treturn o.DynamicClient.Resource(info.Mapping.Resource).Namespace(info.Namespace).List(context.TODO(), options)\n\t\t},\n\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\toptions.FieldSelector = fieldSelector\n\t\t\treturn o.DynamicClient.Resource(info.Mapping.Resource).Namespace(info.Namespace).Watch(context.TODO(), options)\n\t\t},\n\t}\n\n\t// this function is used to refresh the cache to prevent timeout waits on resources that have disappeared\n\tpreconditionFunc := func(store cache.Store) (bool, error) {\n\t\t_, exists, err := store.Get(\u0026metav1.ObjectMeta{Namespace: info.Namespace, Name: info.Name})\n\t\tif err != nil {\n\t\t\treturn true, err\n\t\t}\n\t\tif !exists {\n\t\t\t// since we're looking for it to disappear we just return here if it no longer exists\n\t\t\treturn true, nil\n\t\t}\n\n\t\treturn false, nil\n\t}\n\n\tintrCtx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\tintr := interrupt.New(nil, cancel)\n\terr := intr.Run(func() error {\n\t\t_, err := watchtools.UntilWithSync(intrCtx, lw, \u0026unstructured.Unstructured{}, preconditionFunc, Wait{errOut: o.ErrOut}.IsDeleted)\n\t\tif errors.Is(err, context.DeadlineExceeded) {\n\t\t\treturn errWaitTimeoutWithName\n\t\t}\n\t\treturn err\n\t})\n\tif err != nil {\n\t\tif err == wait.ErrWaitTimeout {\n\t\t\treturn gottenObj, false, errWaitTimeoutWithName\n\t\t}\n\t\treturn gottenObj, false, err\n\t}\n\n\treturn gottenObj, true, nil\n}","line":{"from":323,"to":407}} {"id":100032344,"name":"IsDeleted","signature":"func (w Wait) IsDeleted(event watch.Event) (bool, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/wait/wait.go","code":"// IsDeleted returns true if the object is deleted. It prints any errors it encounters.\nfunc (w Wait) IsDeleted(event watch.Event) (bool, error) {\n\tswitch event.Type {\n\tcase watch.Error:\n\t\t// keep waiting in the event we see an error - we expect the watch to be closed by\n\t\t// the server if the error is unrecoverable.\n\t\terr := apierrors.FromObject(event.Object)\n\t\tfmt.Fprintf(w.errOut, \"error: An error occurred while waiting for the object to be deleted: %v\", err)\n\t\treturn false, nil\n\tcase watch.Deleted:\n\t\treturn true, nil\n\tdefault:\n\t\treturn false, nil\n\t}\n}","line":{"from":414,"to":428}} {"id":100032345,"name":"getObjAndCheckCondition","signature":"func getObjAndCheckCondition(ctx context.Context, info *resource.Info, o *WaitOptions, condMet isCondMetFunc, check checkCondFunc) (runtime.Object, bool, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/wait/wait.go","code":"// getObjAndCheckCondition will make a List query to the API server to get the object and check if the condition is met using check function.\n// If the condition is not met, it will make a Watch query to the server and pass in the condMet function\nfunc getObjAndCheckCondition(ctx context.Context, info *resource.Info, o *WaitOptions, condMet isCondMetFunc, check checkCondFunc) (runtime.Object, bool, error) {\n\tif len(info.Name) == 0 {\n\t\treturn info.Object, false, fmt.Errorf(\"resource name must be provided\")\n\t}\n\n\tendTime := time.Now().Add(o.Timeout)\n\ttimeout := time.Until(endTime)\n\terrWaitTimeoutWithName := extendErrWaitTimeout(wait.ErrWaitTimeout, info)\n\tif o.Timeout == 0 {\n\t\t// If timeout is zero we will fetch the object(s) once only and check\n\t\tgottenObj, initObjGetErr := o.DynamicClient.Resource(info.Mapping.Resource).Namespace(info.Namespace).Get(context.Background(), info.Name, metav1.GetOptions{})\n\t\tif initObjGetErr != nil {\n\t\t\treturn nil, false, initObjGetErr\n\t\t}\n\t\tif gottenObj == nil {\n\t\t\treturn nil, false, fmt.Errorf(\"condition not met for %s\", info.ObjectName())\n\t\t}\n\t\tconditionCheck, err := check(gottenObj)\n\t\tif err != nil {\n\t\t\treturn gottenObj, false, err\n\t\t}\n\t\tif conditionCheck == false {\n\t\t\treturn gottenObj, false, fmt.Errorf(\"condition not met for %s\", info.ObjectName())\n\t\t}\n\t\treturn gottenObj, true, nil\n\t}\n\tif timeout \u003c 0 {\n\t\t// we're out of time\n\t\treturn info.Object, false, errWaitTimeoutWithName\n\t}\n\n\tmapping := info.ResourceMapping() // used to pass back meaningful errors if object disappears\n\tfieldSelector := fields.OneTermEqualSelector(\"metadata.name\", info.Name).String()\n\tlw := \u0026cache.ListWatch{\n\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\toptions.FieldSelector = fieldSelector\n\t\t\treturn o.DynamicClient.Resource(info.Mapping.Resource).Namespace(info.Namespace).List(context.TODO(), options)\n\t\t},\n\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\toptions.FieldSelector = fieldSelector\n\t\t\treturn o.DynamicClient.Resource(info.Mapping.Resource).Namespace(info.Namespace).Watch(context.TODO(), options)\n\t\t},\n\t}\n\n\t// this function is used to refresh the cache to prevent timeout waits on resources that have disappeared\n\tpreconditionFunc := func(store cache.Store) (bool, error) {\n\t\t_, exists, err := store.Get(\u0026metav1.ObjectMeta{Namespace: info.Namespace, Name: info.Name})\n\t\tif err != nil {\n\t\t\treturn true, err\n\t\t}\n\t\tif !exists {\n\t\t\treturn true, apierrors.NewNotFound(mapping.Resource.GroupResource(), info.Name)\n\t\t}\n\n\t\treturn false, nil\n\t}\n\n\tintrCtx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\tvar result runtime.Object\n\tintr := interrupt.New(nil, cancel)\n\terr := intr.Run(func() error {\n\t\tev, err := watchtools.UntilWithSync(intrCtx, lw, \u0026unstructured.Unstructured{}, preconditionFunc, watchtools.ConditionFunc(condMet))\n\t\tif ev != nil {\n\t\t\tresult = ev.Object\n\t\t}\n\t\tif errors.Is(err, context.DeadlineExceeded) {\n\t\t\treturn errWaitTimeoutWithName\n\t\t}\n\t\treturn err\n\t})\n\tif err != nil {\n\t\tif err == wait.ErrWaitTimeout {\n\t\t\treturn result, false, errWaitTimeoutWithName\n\t\t}\n\t\treturn result, false, err\n\t}\n\n\treturn result, true, nil\n}","line":{"from":433,"to":514}} {"id":100032346,"name":"IsConditionMet","signature":"func (w ConditionalWait) IsConditionMet(ctx context.Context, info *resource.Info, o *WaitOptions) (runtime.Object, bool, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/wait/wait.go","code":"// IsConditionMet is a conditionfunc for waiting on an API condition to be met\nfunc (w ConditionalWait) IsConditionMet(ctx context.Context, info *resource.Info, o *WaitOptions) (runtime.Object, bool, error) {\n\treturn getObjAndCheckCondition(ctx, info, o, w.isConditionMet, w.checkCondition)\n}","line":{"from":524,"to":527}} {"id":100032347,"name":"checkCondition","signature":"func (w ConditionalWait) checkCondition(obj *unstructured.Unstructured) (bool, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/wait/wait.go","code":"func (w ConditionalWait) checkCondition(obj *unstructured.Unstructured) (bool, error) {\n\tconditions, found, err := unstructured.NestedSlice(obj.Object, \"status\", \"conditions\")\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif !found {\n\t\treturn false, nil\n\t}\n\tfor _, conditionUncast := range conditions {\n\t\tcondition := conditionUncast.(map[string]interface{})\n\t\tname, found, err := unstructured.NestedString(condition, \"type\")\n\t\tif !found || err != nil || !strings.EqualFold(name, w.conditionName) {\n\t\t\tcontinue\n\t\t}\n\t\tstatus, found, err := unstructured.NestedString(condition, \"status\")\n\t\tif !found || err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tgeneration, found, _ := unstructured.NestedInt64(obj.Object, \"metadata\", \"generation\")\n\t\tif found {\n\t\t\tobservedGeneration, found := getObservedGeneration(obj, condition)\n\t\t\tif found \u0026\u0026 observedGeneration \u003c generation {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t}\n\t\treturn strings.EqualFold(status, w.conditionStatus), nil\n\t}\n\n\treturn false, nil\n}","line":{"from":529,"to":558}} {"id":100032348,"name":"isConditionMet","signature":"func (w ConditionalWait) isConditionMet(event watch.Event) (bool, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/wait/wait.go","code":"func (w ConditionalWait) isConditionMet(event watch.Event) (bool, error) {\n\tif event.Type == watch.Error {\n\t\t// keep waiting in the event we see an error - we expect the watch to be closed by\n\t\t// the server\n\t\terr := apierrors.FromObject(event.Object)\n\t\tfmt.Fprintf(w.errOut, \"error: An error occurred while waiting for the condition to be satisfied: %v\", err)\n\t\treturn false, nil\n\t}\n\tif event.Type == watch.Deleted {\n\t\t// this will chain back out, result in another get and an return false back up the chain\n\t\treturn false, nil\n\t}\n\tobj := event.Object.(*unstructured.Unstructured)\n\treturn w.checkCondition(obj)\n}","line":{"from":560,"to":574}} {"id":100032349,"name":"extendErrWaitTimeout","signature":"func extendErrWaitTimeout(err error, info *resource.Info) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/wait/wait.go","code":"func extendErrWaitTimeout(err error, info *resource.Info) error {\n\treturn fmt.Errorf(\"%s on %s/%s\", err.Error(), info.Mapping.Resource.Resource, info.Name)\n}","line":{"from":576,"to":578}} {"id":100032350,"name":"getObservedGeneration","signature":"func getObservedGeneration(obj *unstructured.Unstructured, condition map[string]interface{}) (int64, bool)","file":"staging/src/k8s.io/kubectl/pkg/cmd/wait/wait.go","code":"func getObservedGeneration(obj *unstructured.Unstructured, condition map[string]interface{}) (int64, bool) {\n\tconditionObservedGeneration, found, _ := unstructured.NestedInt64(condition, \"observedGeneration\")\n\tif found {\n\t\treturn conditionObservedGeneration, true\n\t}\n\tstatusObservedGeneration, found, _ := unstructured.NestedInt64(obj.Object, \"status\", \"observedGeneration\")\n\treturn statusObservedGeneration, found\n}","line":{"from":580,"to":587}} {"id":100032351,"name":"IsJSONPathConditionMet","signature":"func (j JSONPathWait) IsJSONPathConditionMet(ctx context.Context, info *resource.Info, o *WaitOptions) (runtime.Object, bool, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/wait/wait.go","code":"// IsJSONPathConditionMet fulfills the requirements of the interface ConditionFunc which provides condition check\nfunc (j JSONPathWait) IsJSONPathConditionMet(ctx context.Context, info *resource.Info, o *WaitOptions) (runtime.Object, bool, error) {\n\treturn getObjAndCheckCondition(ctx, info, o, j.isJSONPathConditionMet, j.checkCondition)\n}","line":{"from":598,"to":601}} {"id":100032352,"name":"isJSONPathConditionMet","signature":"func (j JSONPathWait) isJSONPathConditionMet(event watch.Event) (bool, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/wait/wait.go","code":"// isJSONPathConditionMet is a helper function of IsJSONPathConditionMet\n// which check the watch event and check if a JSONPathWait condition is met\nfunc (j JSONPathWait) isJSONPathConditionMet(event watch.Event) (bool, error) {\n\tif event.Type == watch.Error {\n\t\t// keep waiting in the event we see an error - we expect the watch to be closed by\n\t\t// the server\n\t\terr := apierrors.FromObject(event.Object)\n\t\tfmt.Fprintf(j.errOut, \"error: An error occurred while waiting for the condition to be satisfied: %v\", err)\n\t\treturn false, nil\n\t}\n\tif event.Type == watch.Deleted {\n\t\t// this will chain back out, result in another get and an return false back up the chain\n\t\treturn false, nil\n\t}\n\t// event runtime Object can be safely asserted to Unstructed\n\t// because we are working with dynamic client\n\tobj := event.Object.(*unstructured.Unstructured)\n\treturn j.checkCondition(obj)\n}","line":{"from":603,"to":621}} {"id":100032353,"name":"checkCondition","signature":"func (j JSONPathWait) checkCondition(obj *unstructured.Unstructured) (bool, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/wait/wait.go","code":"// checkCondition uses JSONPath parser to parse the JSON received from the API server\n// and check if it matches the desired condition\nfunc (j JSONPathWait) checkCondition(obj *unstructured.Unstructured) (bool, error) {\n\tqueryObj := obj.UnstructuredContent()\n\tparseResults, err := j.jsonPathParser.FindResults(queryObj)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif len(parseResults) == 0 || len(parseResults[0]) == 0 {\n\t\treturn false, nil\n\t}\n\tif err := verifyParsedJSONPath(parseResults); err != nil {\n\t\treturn false, err\n\t}\n\tisConditionMet, err := compareResults(parseResults[0][0], j.jsonPathCondition)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn isConditionMet, nil\n}","line":{"from":623,"to":642}} {"id":100032354,"name":"verifyParsedJSONPath","signature":"func verifyParsedJSONPath(results [][]reflect.Value) error","file":"staging/src/k8s.io/kubectl/pkg/cmd/wait/wait.go","code":"// verifyParsedJSONPath verifies the JSON received from the API server is valid.\n// It will only accept a single JSON\nfunc verifyParsedJSONPath(results [][]reflect.Value) error {\n\tif len(results) \u003e 1 {\n\t\treturn errors.New(\"given jsonpath expression matches more than one list\")\n\t}\n\tif len(results[0]) \u003e 1 {\n\t\treturn errors.New(\"given jsonpath expression matches more than one value\")\n\t}\n\treturn nil\n}","line":{"from":644,"to":654}} {"id":100032355,"name":"compareResults","signature":"func compareResults(r reflect.Value, expectedVal string) (bool, error)","file":"staging/src/k8s.io/kubectl/pkg/cmd/wait/wait.go","code":"// compareResults will compare the reflect.Value from the result parsed by the\n// JSONPath parser with the expected value given by the value\n//\n// Since this is coming from an unstructured this can only ever be a primitive,\n// map[string]interface{}, or []interface{}.\n// We do not support the last two and rely on fmt to handle conversion to string\n// and compare the result with user input\nfunc compareResults(r reflect.Value, expectedVal string) (bool, error) {\n\tswitch r.Interface().(type) {\n\tcase map[string]interface{}, []interface{}:\n\t\treturn false, errors.New(\"jsonpath leads to a nested object or list which is not supported\")\n\t}\n\ts := fmt.Sprintf(\"%v\", r.Interface())\n\treturn strings.TrimSpace(s) == strings.TrimSpace(expectedVal), nil\n}","line":{"from":656,"to":670}} {"id":100032356,"name":"Describer","signature":"func Describer(restClientGetter genericclioptions.RESTClientGetter, mapping *meta.RESTMapping) (ResourceDescriber, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// Describer returns a Describer for displaying the specified RESTMapping type or an error.\nfunc Describer(restClientGetter genericclioptions.RESTClientGetter, mapping *meta.RESTMapping) (ResourceDescriber, error) {\n\tclientConfig, err := restClientGetter.ToRESTConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// try to get a describer\n\tif describer, ok := DescriberFor(mapping.GroupVersionKind.GroupKind(), clientConfig); ok {\n\t\treturn describer, nil\n\t}\n\t// if this is a kind we don't have a describer for yet, go generic if possible\n\tif genericDescriber, ok := GenericDescriberFor(mapping, clientConfig); ok {\n\t\treturn genericDescriber, nil\n\t}\n\t// otherwise return an unregistered error\n\treturn nil, fmt.Errorf(\"no description has been implemented for %s\", mapping.GroupVersionKind.String())\n}","line":{"from":106,"to":122}} {"id":100032357,"name":"NewPrefixWriter","signature":"func NewPrefixWriter(out io.Writer) PrefixWriter","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// NewPrefixWriter creates a new PrefixWriter.\nfunc NewPrefixWriter(out io.Writer) PrefixWriter {\n\treturn \u0026prefixWriter{out: out}\n}","line":{"from":141,"to":144}} {"id":100032358,"name":"Write","signature":"func (pw *prefixWriter) Write(level int, format string, a ...interface{})","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (pw *prefixWriter) Write(level int, format string, a ...interface{}) {\n\tlevelSpace := \" \"\n\tprefix := \"\"\n\tfor i := 0; i \u003c level; i++ {\n\t\tprefix += levelSpace\n\t}\n\toutput := fmt.Sprintf(prefix+format, a...)\n\tprinters.WriteEscaped(pw.out, output)\n}","line":{"from":146,"to":154}} {"id":100032359,"name":"WriteLine","signature":"func (pw *prefixWriter) WriteLine(a ...interface{})","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (pw *prefixWriter) WriteLine(a ...interface{}) {\n\toutput := fmt.Sprintln(a...)\n\tprinters.WriteEscaped(pw.out, output)\n}","line":{"from":156,"to":159}} {"id":100032360,"name":"Flush","signature":"func (pw *prefixWriter) Flush()","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (pw *prefixWriter) Flush() {\n\tif f, ok := pw.out.(flusher); ok {\n\t\tf.Flush()\n\t}\n}","line":{"from":161,"to":165}} {"id":100032361,"name":"NewNestedPrefixWriter","signature":"func NewNestedPrefixWriter(out PrefixWriter, indent int) PrefixWriter","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// NewPrefixWriter creates a new PrefixWriter.\nfunc NewNestedPrefixWriter(out PrefixWriter, indent int) PrefixWriter {\n\treturn \u0026nestedPrefixWriter{PrefixWriter: out, indent: indent}\n}","line":{"from":176,"to":179}} {"id":100032362,"name":"Write","signature":"func (npw *nestedPrefixWriter) Write(level int, format string, a ...interface{})","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (npw *nestedPrefixWriter) Write(level int, format string, a ...interface{}) {\n\tnpw.PrefixWriter.Write(level+npw.indent, format, a...)\n}","line":{"from":181,"to":183}} {"id":100032363,"name":"WriteLine","signature":"func (npw *nestedPrefixWriter) WriteLine(a ...interface{})","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (npw *nestedPrefixWriter) WriteLine(a ...interface{}) {\n\tnpw.PrefixWriter.Write(npw.indent, \"%s\", fmt.Sprintln(a...))\n}","line":{"from":185,"to":187}} {"id":100032364,"name":"describerMap","signature":"func describerMap(clientConfig *rest.Config) (map[schema.GroupKind]ResourceDescriber, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describerMap(clientConfig *rest.Config) (map[schema.GroupKind]ResourceDescriber, error) {\n\tc, err := clientset.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tm := map[schema.GroupKind]ResourceDescriber{\n\t\t{Group: corev1.GroupName, Kind: \"Pod\"}: \u0026PodDescriber{c},\n\t\t{Group: corev1.GroupName, Kind: \"ReplicationController\"}: \u0026ReplicationControllerDescriber{c},\n\t\t{Group: corev1.GroupName, Kind: \"Secret\"}: \u0026SecretDescriber{c},\n\t\t{Group: corev1.GroupName, Kind: \"Service\"}: \u0026ServiceDescriber{c},\n\t\t{Group: corev1.GroupName, Kind: \"ServiceAccount\"}: \u0026ServiceAccountDescriber{c},\n\t\t{Group: corev1.GroupName, Kind: \"Node\"}: \u0026NodeDescriber{c},\n\t\t{Group: corev1.GroupName, Kind: \"LimitRange\"}: \u0026LimitRangeDescriber{c},\n\t\t{Group: corev1.GroupName, Kind: \"ResourceQuota\"}: \u0026ResourceQuotaDescriber{c},\n\t\t{Group: corev1.GroupName, Kind: \"PersistentVolume\"}: \u0026PersistentVolumeDescriber{c},\n\t\t{Group: corev1.GroupName, Kind: \"PersistentVolumeClaim\"}: \u0026PersistentVolumeClaimDescriber{c},\n\t\t{Group: corev1.GroupName, Kind: \"Namespace\"}: \u0026NamespaceDescriber{c},\n\t\t{Group: corev1.GroupName, Kind: \"Endpoints\"}: \u0026EndpointsDescriber{c},\n\t\t{Group: corev1.GroupName, Kind: \"ConfigMap\"}: \u0026ConfigMapDescriber{c},\n\t\t{Group: corev1.GroupName, Kind: \"PriorityClass\"}: \u0026PriorityClassDescriber{c},\n\t\t{Group: discoveryv1beta1.GroupName, Kind: \"EndpointSlice\"}: \u0026EndpointSliceDescriber{c},\n\t\t{Group: discoveryv1.GroupName, Kind: \"EndpointSlice\"}: \u0026EndpointSliceDescriber{c},\n\t\t{Group: autoscalingv2.GroupName, Kind: \"HorizontalPodAutoscaler\"}: \u0026HorizontalPodAutoscalerDescriber{c},\n\t\t{Group: extensionsv1beta1.GroupName, Kind: \"Ingress\"}: \u0026IngressDescriber{c},\n\t\t{Group: networkingv1beta1.GroupName, Kind: \"Ingress\"}: \u0026IngressDescriber{c},\n\t\t{Group: networkingv1beta1.GroupName, Kind: \"IngressClass\"}: \u0026IngressClassDescriber{c},\n\t\t{Group: networkingv1.GroupName, Kind: \"Ingress\"}: \u0026IngressDescriber{c},\n\t\t{Group: networkingv1.GroupName, Kind: \"IngressClass\"}: \u0026IngressClassDescriber{c},\n\t\t{Group: networkingv1alpha1.GroupName, Kind: \"ClusterCIDR\"}: \u0026ClusterCIDRDescriber{c},\n\t\t{Group: networkingv1alpha1.GroupName, Kind: \"IPAddress\"}: \u0026IPAddressDescriber{c},\n\t\t{Group: batchv1.GroupName, Kind: \"Job\"}: \u0026JobDescriber{c},\n\t\t{Group: batchv1.GroupName, Kind: \"CronJob\"}: \u0026CronJobDescriber{c},\n\t\t{Group: batchv1beta1.GroupName, Kind: \"CronJob\"}: \u0026CronJobDescriber{c},\n\t\t{Group: appsv1.GroupName, Kind: \"StatefulSet\"}: \u0026StatefulSetDescriber{c},\n\t\t{Group: appsv1.GroupName, Kind: \"Deployment\"}: \u0026DeploymentDescriber{c},\n\t\t{Group: appsv1.GroupName, Kind: \"DaemonSet\"}: \u0026DaemonSetDescriber{c},\n\t\t{Group: appsv1.GroupName, Kind: \"ReplicaSet\"}: \u0026ReplicaSetDescriber{c},\n\t\t{Group: certificatesv1beta1.GroupName, Kind: \"CertificateSigningRequest\"}: \u0026CertificateSigningRequestDescriber{c},\n\t\t{Group: storagev1.GroupName, Kind: \"StorageClass\"}: \u0026StorageClassDescriber{c},\n\t\t{Group: storagev1.GroupName, Kind: \"CSINode\"}: \u0026CSINodeDescriber{c},\n\t\t{Group: policyv1beta1.GroupName, Kind: \"PodDisruptionBudget\"}: \u0026PodDisruptionBudgetDescriber{c},\n\t\t{Group: policyv1.GroupName, Kind: \"PodDisruptionBudget\"}: \u0026PodDisruptionBudgetDescriber{c},\n\t\t{Group: rbacv1.GroupName, Kind: \"Role\"}: \u0026RoleDescriber{c},\n\t\t{Group: rbacv1.GroupName, Kind: \"ClusterRole\"}: \u0026ClusterRoleDescriber{c},\n\t\t{Group: rbacv1.GroupName, Kind: \"RoleBinding\"}: \u0026RoleBindingDescriber{c},\n\t\t{Group: rbacv1.GroupName, Kind: \"ClusterRoleBinding\"}: \u0026ClusterRoleBindingDescriber{c},\n\t\t{Group: networkingv1.GroupName, Kind: \"NetworkPolicy\"}: \u0026NetworkPolicyDescriber{c},\n\t\t{Group: schedulingv1.GroupName, Kind: \"PriorityClass\"}: \u0026PriorityClassDescriber{c},\n\t}\n\n\treturn m, nil\n}","line":{"from":189,"to":241}} {"id":100032365,"name":"DescriberFor","signature":"func DescriberFor(kind schema.GroupKind, clientConfig *rest.Config) (ResourceDescriber, bool)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// DescriberFor returns the default describe functions for each of the standard\n// Kubernetes types.\nfunc DescriberFor(kind schema.GroupKind, clientConfig *rest.Config) (ResourceDescriber, bool) {\n\tdescribers, err := describerMap(clientConfig)\n\tif err != nil {\n\t\tklog.V(1).Info(err)\n\t\treturn nil, false\n\t}\n\n\tf, ok := describers[kind]\n\treturn f, ok\n}","line":{"from":243,"to":254}} {"id":100032366,"name":"GenericDescriberFor","signature":"func GenericDescriberFor(mapping *meta.RESTMapping, clientConfig *rest.Config) (ResourceDescriber, bool)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// GenericDescriberFor returns a generic describer for the specified mapping\n// that uses only information available from runtime.Unstructured\nfunc GenericDescriberFor(mapping *meta.RESTMapping, clientConfig *rest.Config) (ResourceDescriber, bool) {\n\t// used to fetch the resource\n\tdynamicClient, err := dynamic.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn nil, false\n\t}\n\n\t// used to get events for the resource\n\tclientSet, err := clientset.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn nil, false\n\t}\n\teventsClient := clientSet.CoreV1()\n\n\treturn \u0026genericDescriber{mapping, dynamicClient, eventsClient}, true\n}","line":{"from":256,"to":273}} {"id":100032367,"name":"Describe","signature":"func (g *genericDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (output string, err error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (g *genericDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (output string, err error) {\n\tobj, err := g.dynamic.Resource(g.mapping.Resource).Namespace(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar events *corev1.EventList\n\tif describerSettings.ShowEvents {\n\t\tevents, _ = searchEvents(g.events, obj, describerSettings.ChunkSize)\n\t}\n\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", obj.GetName())\n\t\tw.Write(LEVEL_0, \"Namespace:\\t%s\\n\", obj.GetNamespace())\n\t\tprintLabelsMultiline(w, \"Labels\", obj.GetLabels())\n\t\tprintAnnotationsMultiline(w, \"Annotations\", obj.GetAnnotations())\n\t\tprintUnstructuredContent(w, LEVEL_0, obj.UnstructuredContent(), \"\", \".metadata.managedFields\", \".metadata.name\",\n\t\t\t\".metadata.namespace\", \".metadata.labels\", \".metadata.annotations\")\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":281,"to":305}} {"id":100032368,"name":"printUnstructuredContent","signature":"func printUnstructuredContent(w PrefixWriter, level int, content map[string]interface{}, skipPrefix string, skip ...string)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printUnstructuredContent(w PrefixWriter, level int, content map[string]interface{}, skipPrefix string, skip ...string) {\n\tfields := []string{}\n\tfor field := range content {\n\t\tfields = append(fields, field)\n\t}\n\tsort.Strings(fields)\n\n\tfor _, field := range fields {\n\t\tvalue := content[field]\n\t\tswitch typedValue := value.(type) {\n\t\tcase map[string]interface{}:\n\t\t\tskipExpr := fmt.Sprintf(\"%s.%s\", skipPrefix, field)\n\t\t\tif slice.ContainsString(skip, skipExpr, nil) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tw.Write(level, \"%s:\\n\", smartLabelFor(field))\n\t\t\tprintUnstructuredContent(w, level+1, typedValue, skipExpr, skip...)\n\n\t\tcase []interface{}:\n\t\t\tskipExpr := fmt.Sprintf(\"%s.%s\", skipPrefix, field)\n\t\t\tif slice.ContainsString(skip, skipExpr, nil) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tw.Write(level, \"%s:\\n\", smartLabelFor(field))\n\t\t\tfor _, child := range typedValue {\n\t\t\t\tswitch typedChild := child.(type) {\n\t\t\t\tcase map[string]interface{}:\n\t\t\t\t\tprintUnstructuredContent(w, level+1, typedChild, skipExpr, skip...)\n\t\t\t\tdefault:\n\t\t\t\t\tw.Write(level+1, \"%v\\n\", typedChild)\n\t\t\t\t}\n\t\t\t}\n\n\t\tdefault:\n\t\t\tskipExpr := fmt.Sprintf(\"%s.%s\", skipPrefix, field)\n\t\t\tif slice.ContainsString(skip, skipExpr, nil) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tw.Write(level, \"%s:\\t%v\\n\", smartLabelFor(field), typedValue)\n\t\t}\n\t}\n}","line":{"from":307,"to":348}} {"id":100032369,"name":"smartLabelFor","signature":"func smartLabelFor(field string) string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func smartLabelFor(field string) string {\n\t// skip creating smart label if field name contains\n\t// special characters other than '-'\n\tif strings.IndexFunc(field, func(r rune) bool {\n\t\treturn !unicode.IsLetter(r) \u0026\u0026 r != '-'\n\t}) != -1 {\n\t\treturn field\n\t}\n\n\tcommonAcronyms := []string{\"API\", \"URL\", \"UID\", \"OSB\", \"GUID\"}\n\tparts := camelcase.Split(field)\n\tresult := make([]string, 0, len(parts))\n\tfor _, part := range parts {\n\t\tif part == \"_\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tif slice.ContainsString(commonAcronyms, strings.ToUpper(part), nil) {\n\t\t\tpart = strings.ToUpper(part)\n\t\t} else {\n\t\t\tpart = strings.Title(part)\n\t\t}\n\t\tresult = append(result, part)\n\t}\n\n\treturn strings.Join(result, \" \")\n}","line":{"from":350,"to":376}} {"id":100032370,"name":"init","signature":"func init()","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func init() {\n\td := \u0026Describers{}\n\terr := d.Add(\n\t\tdescribeLimitRange,\n\t\tdescribeQuota,\n\t\tdescribePod,\n\t\tdescribeService,\n\t\tdescribeReplicationController,\n\t\tdescribeDaemonSet,\n\t\tdescribeNode,\n\t\tdescribeNamespace,\n\t)\n\tif err != nil {\n\t\tklog.Fatalf(\"Cannot register describers: %v\", err)\n\t}\n\tDefaultObjectDescriber = d\n}","line":{"from":381,"to":397}} {"id":100032371,"name":"Describe","signature":"func (d *NamespaceDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (d *NamespaceDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tns, err := d.CoreV1().Namespaces().Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tresourceQuotaList := \u0026corev1.ResourceQuotaList{}\n\terr = runtimeresource.FollowContinue(\u0026metav1.ListOptions{Limit: describerSettings.ChunkSize},\n\t\tfunc(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\tnewList, err := d.CoreV1().ResourceQuotas(name).List(context.TODO(), options)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, runtimeresource.EnhanceListError(err, options, corev1.ResourceQuotas.String())\n\t\t\t}\n\t\t\tresourceQuotaList.Items = append(resourceQuotaList.Items, newList.Items...)\n\t\t\treturn newList, nil\n\t\t})\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\t// Server does not support resource quotas.\n\t\t\t// Not an error, will not show resource quotas information.\n\t\t\tresourceQuotaList = nil\n\t\t} else {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tlimitRangeList := \u0026corev1.LimitRangeList{}\n\terr = runtimeresource.FollowContinue(\u0026metav1.ListOptions{Limit: describerSettings.ChunkSize},\n\t\tfunc(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\tnewList, err := d.CoreV1().LimitRanges(name).List(context.TODO(), options)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, runtimeresource.EnhanceListError(err, options, \"limitranges\")\n\t\t\t}\n\t\t\tlimitRangeList.Items = append(limitRangeList.Items, newList.Items...)\n\t\t\treturn newList, nil\n\t\t})\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\t// Server does not support limit ranges.\n\t\t\t// Not an error, will not show limit ranges information.\n\t\t\tlimitRangeList = nil\n\t\t} else {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\treturn describeNamespace(ns, resourceQuotaList, limitRangeList)\n}","line":{"from":404,"to":450}} {"id":100032372,"name":"describeNamespace","signature":"func describeNamespace(namespace *corev1.Namespace, resourceQuotaList *corev1.ResourceQuotaList, limitRangeList *corev1.LimitRangeList) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeNamespace(namespace *corev1.Namespace, resourceQuotaList *corev1.ResourceQuotaList, limitRangeList *corev1.LimitRangeList) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", namespace.Name)\n\t\tprintLabelsMultiline(w, \"Labels\", namespace.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", namespace.Annotations)\n\t\tw.Write(LEVEL_0, \"Status:\\t%s\\n\", string(namespace.Status.Phase))\n\n\t\tif len(namespace.Status.Conditions) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"Conditions:\\n\")\n\t\t\tw.Write(LEVEL_1, \"Type\\tStatus\\tLastTransitionTime\\tReason\\tMessage\\n\")\n\t\t\tw.Write(LEVEL_1, \"----\\t------\\t------------------\\t------\\t-------\\n\")\n\t\t\tfor _, c := range namespace.Status.Conditions {\n\t\t\t\tw.Write(LEVEL_1, \"%v\\t%v\\t%s\\t%v\\t%v\\n\",\n\t\t\t\t\tc.Type,\n\t\t\t\t\tc.Status,\n\t\t\t\t\tc.LastTransitionTime.Time.Format(time.RFC1123Z),\n\t\t\t\t\tc.Reason,\n\t\t\t\t\tc.Message)\n\t\t\t}\n\t\t}\n\n\t\tif resourceQuotaList != nil {\n\t\t\tw.Write(LEVEL_0, \"\\n\")\n\t\t\tDescribeResourceQuotas(resourceQuotaList, w)\n\t\t}\n\n\t\tif limitRangeList != nil {\n\t\t\tw.Write(LEVEL_0, \"\\n\")\n\t\t\tDescribeLimitRanges(limitRangeList, w)\n\t\t}\n\n\t\treturn nil\n\t})\n}","line":{"from":452,"to":486}} {"id":100032373,"name":"describeLimitRangeSpec","signature":"func describeLimitRangeSpec(spec corev1.LimitRangeSpec, prefix string, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeLimitRangeSpec(spec corev1.LimitRangeSpec, prefix string, w PrefixWriter) {\n\tfor i := range spec.Limits {\n\t\titem := spec.Limits[i]\n\t\tmaxResources := item.Max\n\t\tminResources := item.Min\n\t\tdefaultLimitResources := item.Default\n\t\tdefaultRequestResources := item.DefaultRequest\n\t\tratio := item.MaxLimitRequestRatio\n\n\t\tset := map[corev1.ResourceName]bool{}\n\t\tfor k := range maxResources {\n\t\t\tset[k] = true\n\t\t}\n\t\tfor k := range minResources {\n\t\t\tset[k] = true\n\t\t}\n\t\tfor k := range defaultLimitResources {\n\t\t\tset[k] = true\n\t\t}\n\t\tfor k := range defaultRequestResources {\n\t\t\tset[k] = true\n\t\t}\n\t\tfor k := range ratio {\n\t\t\tset[k] = true\n\t\t}\n\n\t\tfor k := range set {\n\t\t\t// if no value is set, we output -\n\t\t\tmaxValue := \"-\"\n\t\t\tminValue := \"-\"\n\t\t\tdefaultLimitValue := \"-\"\n\t\t\tdefaultRequestValue := \"-\"\n\t\t\tratioValue := \"-\"\n\n\t\t\tmaxQuantity, maxQuantityFound := maxResources[k]\n\t\t\tif maxQuantityFound {\n\t\t\t\tmaxValue = maxQuantity.String()\n\t\t\t}\n\n\t\t\tminQuantity, minQuantityFound := minResources[k]\n\t\t\tif minQuantityFound {\n\t\t\t\tminValue = minQuantity.String()\n\t\t\t}\n\n\t\t\tdefaultLimitQuantity, defaultLimitQuantityFound := defaultLimitResources[k]\n\t\t\tif defaultLimitQuantityFound {\n\t\t\t\tdefaultLimitValue = defaultLimitQuantity.String()\n\t\t\t}\n\n\t\t\tdefaultRequestQuantity, defaultRequestQuantityFound := defaultRequestResources[k]\n\t\t\tif defaultRequestQuantityFound {\n\t\t\t\tdefaultRequestValue = defaultRequestQuantity.String()\n\t\t\t}\n\n\t\t\tratioQuantity, ratioQuantityFound := ratio[k]\n\t\t\tif ratioQuantityFound {\n\t\t\t\tratioValue = ratioQuantity.String()\n\t\t\t}\n\n\t\t\tmsg := \"%s%s\\t%v\\t%v\\t%v\\t%v\\t%v\\t%v\\n\"\n\t\t\tw.Write(LEVEL_0, msg, prefix, item.Type, k, minValue, maxValue, defaultRequestValue, defaultLimitValue, ratioValue)\n\t\t}\n\t}\n}","line":{"from":488,"to":551}} {"id":100032374,"name":"DescribeLimitRanges","signature":"func DescribeLimitRanges(limitRanges *corev1.LimitRangeList, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// DescribeLimitRanges merges a set of limit range items into a single tabular description\nfunc DescribeLimitRanges(limitRanges *corev1.LimitRangeList, w PrefixWriter) {\n\tif len(limitRanges.Items) == 0 {\n\t\tw.Write(LEVEL_0, \"No LimitRange resource.\\n\")\n\t\treturn\n\t}\n\tw.Write(LEVEL_0, \"Resource Limits\\n Type\\tResource\\tMin\\tMax\\tDefault Request\\tDefault Limit\\tMax Limit/Request Ratio\\n\")\n\tw.Write(LEVEL_0, \" ----\\t--------\\t---\\t---\\t---------------\\t-------------\\t-----------------------\\n\")\n\tfor _, limitRange := range limitRanges.Items {\n\t\tdescribeLimitRangeSpec(limitRange.Spec, \" \", w)\n\t}\n}","line":{"from":553,"to":564}} {"id":100032375,"name":"DescribeResourceQuotas","signature":"func DescribeResourceQuotas(quotas *corev1.ResourceQuotaList, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// DescribeResourceQuotas merges a set of quota items into a single tabular description of all quotas\nfunc DescribeResourceQuotas(quotas *corev1.ResourceQuotaList, w PrefixWriter) {\n\tif len(quotas.Items) == 0 {\n\t\tw.Write(LEVEL_0, \"No resource quota.\\n\")\n\t\treturn\n\t}\n\tsort.Sort(SortableResourceQuotas(quotas.Items))\n\n\tw.Write(LEVEL_0, \"Resource Quotas\\n\")\n\tfor _, q := range quotas.Items {\n\t\tw.Write(LEVEL_1, \"Name:\\t%s\\n\", q.Name)\n\t\tif len(q.Spec.Scopes) \u003e 0 {\n\t\t\tscopes := make([]string, 0, len(q.Spec.Scopes))\n\t\t\tfor _, scope := range q.Spec.Scopes {\n\t\t\t\tscopes = append(scopes, string(scope))\n\t\t\t}\n\t\t\tsort.Strings(scopes)\n\t\t\tw.Write(LEVEL_1, \"Scopes:\\t%s\\n\", strings.Join(scopes, \", \"))\n\t\t\tfor _, scope := range scopes {\n\t\t\t\thelpText := helpTextForResourceQuotaScope(corev1.ResourceQuotaScope(scope))\n\t\t\t\tif len(helpText) \u003e 0 {\n\t\t\t\t\tw.Write(LEVEL_1, \"* %s\\n\", helpText)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tw.Write(LEVEL_1, \"Resource\\tUsed\\tHard\\n\")\n\t\tw.Write(LEVEL_1, \"--------\\t---\\t---\\n\")\n\n\t\tresources := make([]corev1.ResourceName, 0, len(q.Status.Hard))\n\t\tfor resource := range q.Status.Hard {\n\t\t\tresources = append(resources, resource)\n\t\t}\n\t\tsort.Sort(SortableResourceNames(resources))\n\n\t\tfor _, resource := range resources {\n\t\t\thardQuantity := q.Status.Hard[resource]\n\t\t\tusedQuantity := q.Status.Used[resource]\n\t\t\tw.Write(LEVEL_1, \"%s\\t%s\\t%s\\n\", string(resource), usedQuantity.String(), hardQuantity.String())\n\t\t}\n\t}\n}","line":{"from":566,"to":607}} {"id":100032376,"name":"Describe","signature":"func (d *LimitRangeDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (d *LimitRangeDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tlr := d.CoreV1().LimitRanges(namespace)\n\n\tlimitRange, err := lr.Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn describeLimitRange(limitRange)\n}","line":{"from":614,"to":622}} {"id":100032377,"name":"describeLimitRange","signature":"func describeLimitRange(limitRange *corev1.LimitRange) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeLimitRange(limitRange *corev1.LimitRange) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", limitRange.Name)\n\t\tw.Write(LEVEL_0, \"Namespace:\\t%s\\n\", limitRange.Namespace)\n\t\tw.Write(LEVEL_0, \"Type\\tResource\\tMin\\tMax\\tDefault Request\\tDefault Limit\\tMax Limit/Request Ratio\\n\")\n\t\tw.Write(LEVEL_0, \"----\\t--------\\t---\\t---\\t---------------\\t-------------\\t-----------------------\\n\")\n\t\tdescribeLimitRangeSpec(limitRange.Spec, \"\", w)\n\t\treturn nil\n\t})\n}","line":{"from":624,"to":634}} {"id":100032378,"name":"Describe","signature":"func (d *ResourceQuotaDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (d *ResourceQuotaDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\trq := d.CoreV1().ResourceQuotas(namespace)\n\n\tresourceQuota, err := rq.Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn describeQuota(resourceQuota)\n}","line":{"from":641,"to":650}} {"id":100032379,"name":"helpTextForResourceQuotaScope","signature":"func helpTextForResourceQuotaScope(scope corev1.ResourceQuotaScope) string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func helpTextForResourceQuotaScope(scope corev1.ResourceQuotaScope) string {\n\tswitch scope {\n\tcase corev1.ResourceQuotaScopeTerminating:\n\t\treturn \"Matches all pods that have an active deadline. These pods have a limited lifespan on a node before being actively terminated by the system.\"\n\tcase corev1.ResourceQuotaScopeNotTerminating:\n\t\treturn \"Matches all pods that do not have an active deadline. These pods usually include long running pods whose container command is not expected to terminate.\"\n\tcase corev1.ResourceQuotaScopeBestEffort:\n\t\treturn \"Matches all pods that do not have resource requirements set. These pods have a best effort quality of service.\"\n\tcase corev1.ResourceQuotaScopeNotBestEffort:\n\t\treturn \"Matches all pods that have at least one resource requirement set. These pods have a burstable or guaranteed quality of service.\"\n\tdefault:\n\t\treturn \"\"\n\t}\n}","line":{"from":652,"to":665}} {"id":100032380,"name":"describeQuota","signature":"func describeQuota(resourceQuota *corev1.ResourceQuota) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeQuota(resourceQuota *corev1.ResourceQuota) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", resourceQuota.Name)\n\t\tw.Write(LEVEL_0, \"Namespace:\\t%s\\n\", resourceQuota.Namespace)\n\t\tif len(resourceQuota.Spec.Scopes) \u003e 0 {\n\t\t\tscopes := make([]string, 0, len(resourceQuota.Spec.Scopes))\n\t\t\tfor _, scope := range resourceQuota.Spec.Scopes {\n\t\t\t\tscopes = append(scopes, string(scope))\n\t\t\t}\n\t\t\tsort.Strings(scopes)\n\t\t\tw.Write(LEVEL_0, \"Scopes:\\t%s\\n\", strings.Join(scopes, \", \"))\n\t\t\tfor _, scope := range scopes {\n\t\t\t\thelpText := helpTextForResourceQuotaScope(corev1.ResourceQuotaScope(scope))\n\t\t\t\tif len(helpText) \u003e 0 {\n\t\t\t\t\tw.Write(LEVEL_0, \" * %s\\n\", helpText)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tw.Write(LEVEL_0, \"Resource\\tUsed\\tHard\\n\")\n\t\tw.Write(LEVEL_0, \"--------\\t----\\t----\\n\")\n\n\t\tresources := make([]corev1.ResourceName, 0, len(resourceQuota.Status.Hard))\n\t\tfor resource := range resourceQuota.Status.Hard {\n\t\t\tresources = append(resources, resource)\n\t\t}\n\t\tsort.Sort(SortableResourceNames(resources))\n\n\t\tmsg := \"%v\\t%v\\t%v\\n\"\n\t\tfor i := range resources {\n\t\t\tresourceName := resources[i]\n\t\t\thardQuantity := resourceQuota.Status.Hard[resourceName]\n\t\t\tusedQuantity := resourceQuota.Status.Used[resourceName]\n\t\t\tif hardQuantity.Format != usedQuantity.Format {\n\t\t\t\tusedQuantity = *resource.NewQuantity(usedQuantity.Value(), hardQuantity.Format)\n\t\t\t}\n\t\t\tw.Write(LEVEL_0, msg, resourceName, usedQuantity.String(), hardQuantity.String())\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":666,"to":706}} {"id":100032381,"name":"Describe","signature":"func (d *PodDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (d *PodDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tpod, err := d.CoreV1().Pods(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\tif describerSettings.ShowEvents {\n\t\t\teventsInterface := d.CoreV1().Events(namespace)\n\t\t\tselector := eventsInterface.GetFieldSelector(\u0026name, \u0026namespace, nil, nil)\n\t\t\tinitialOpts := metav1.ListOptions{\n\t\t\t\tFieldSelector: selector.String(),\n\t\t\t\tLimit: describerSettings.ChunkSize,\n\t\t\t}\n\t\t\tevents := \u0026corev1.EventList{}\n\t\t\terr2 := runtimeresource.FollowContinue(\u0026initialOpts,\n\t\t\t\tfunc(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\t\tnewList, err := eventsInterface.List(context.TODO(), options)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, runtimeresource.EnhanceListError(err, options, \"events\")\n\t\t\t\t\t}\n\t\t\t\t\tevents.Items = append(events.Items, newList.Items...)\n\t\t\t\t\treturn newList, nil\n\t\t\t\t})\n\n\t\t\tif err2 == nil \u0026\u0026 len(events.Items) \u003e 0 {\n\t\t\t\treturn tabbedString(func(out io.Writer) error {\n\t\t\t\t\tw := NewPrefixWriter(out)\n\t\t\t\t\tw.Write(LEVEL_0, \"Pod '%v': error '%v', but found events.\\n\", name, err)\n\t\t\t\t\tDescribeEvents(events, w)\n\t\t\t\t\treturn nil\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\treturn \"\", err\n\t}\n\n\tvar events *corev1.EventList\n\tif describerSettings.ShowEvents {\n\t\tif ref, err := reference.GetReference(scheme.Scheme, pod); err != nil {\n\t\t\tklog.Errorf(\"Unable to construct reference to '%#v': %v\", pod, err)\n\t\t} else {\n\t\t\tref.Kind = \"\"\n\t\t\tif _, isMirrorPod := pod.Annotations[corev1.MirrorPodAnnotationKey]; isMirrorPod {\n\t\t\t\tref.UID = types.UID(pod.Annotations[corev1.MirrorPodAnnotationKey])\n\t\t\t}\n\t\t\tevents, _ = searchEvents(d.CoreV1(), ref, describerSettings.ChunkSize)\n\t\t}\n\t}\n\n\treturn describePod(pod, events)\n}","line":{"from":714,"to":761}} {"id":100032382,"name":"describePod","signature":"func describePod(pod *corev1.Pod, events *corev1.EventList) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describePod(pod *corev1.Pod, events *corev1.EventList) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", pod.Name)\n\t\tw.Write(LEVEL_0, \"Namespace:\\t%s\\n\", pod.Namespace)\n\t\tif pod.Spec.Priority != nil {\n\t\t\tw.Write(LEVEL_0, \"Priority:\\t%d\\n\", *pod.Spec.Priority)\n\t\t}\n\t\tif len(pod.Spec.PriorityClassName) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"Priority Class Name:\\t%s\\n\", pod.Spec.PriorityClassName)\n\t\t}\n\t\tif pod.Spec.RuntimeClassName != nil \u0026\u0026 len(*pod.Spec.RuntimeClassName) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"Runtime Class Name:\\t%s\\n\", *pod.Spec.RuntimeClassName)\n\t\t}\n\t\tif len(pod.Spec.ServiceAccountName) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"Service Account:\\t%s\\n\", pod.Spec.ServiceAccountName)\n\t\t}\n\t\tif pod.Spec.NodeName == \"\" {\n\t\t\tw.Write(LEVEL_0, \"Node:\\t\u003cnone\u003e\\n\")\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"Node:\\t%s\\n\", pod.Spec.NodeName+\"/\"+pod.Status.HostIP)\n\t\t}\n\t\tif pod.Status.StartTime != nil {\n\t\t\tw.Write(LEVEL_0, \"Start Time:\\t%s\\n\", pod.Status.StartTime.Time.Format(time.RFC1123Z))\n\t\t}\n\t\tprintLabelsMultiline(w, \"Labels\", pod.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", pod.Annotations)\n\t\tif pod.DeletionTimestamp != nil {\n\t\t\tw.Write(LEVEL_0, \"Status:\\tTerminating (lasts %s)\\n\", translateTimestampSince(*pod.DeletionTimestamp))\n\t\t\tw.Write(LEVEL_0, \"Termination Grace Period:\\t%ds\\n\", *pod.DeletionGracePeriodSeconds)\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"Status:\\t%s\\n\", string(pod.Status.Phase))\n\t\t}\n\t\tif len(pod.Status.Reason) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"Reason:\\t%s\\n\", pod.Status.Reason)\n\t\t}\n\t\tif len(pod.Status.Message) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"Message:\\t%s\\n\", pod.Status.Message)\n\t\t}\n\t\tif pod.Spec.SecurityContext != nil \u0026\u0026 pod.Spec.SecurityContext.SeccompProfile != nil {\n\t\t\tw.Write(LEVEL_0, \"SeccompProfile:\\t%s\\n\", pod.Spec.SecurityContext.SeccompProfile.Type)\n\t\t\tif pod.Spec.SecurityContext.SeccompProfile.Type == corev1.SeccompProfileTypeLocalhost {\n\t\t\t\tw.Write(LEVEL_0, \"LocalhostProfile:\\t%s\\n\", *pod.Spec.SecurityContext.SeccompProfile.LocalhostProfile)\n\t\t\t}\n\t\t}\n\t\t// remove when .IP field is depreciated\n\t\tw.Write(LEVEL_0, \"IP:\\t%s\\n\", pod.Status.PodIP)\n\t\tdescribePodIPs(pod, w, \"\")\n\t\tif controlledBy := printController(pod); len(controlledBy) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"Controlled By:\\t%s\\n\", controlledBy)\n\t\t}\n\t\tif len(pod.Status.NominatedNodeName) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"NominatedNodeName:\\t%s\\n\", pod.Status.NominatedNodeName)\n\t\t}\n\n\t\tif len(pod.Spec.InitContainers) \u003e 0 {\n\t\t\tdescribeContainers(\"Init Containers\", pod.Spec.InitContainers, pod.Status.InitContainerStatuses, EnvValueRetriever(pod), w, \"\")\n\t\t}\n\t\tdescribeContainers(\"Containers\", pod.Spec.Containers, pod.Status.ContainerStatuses, EnvValueRetriever(pod), w, \"\")\n\t\tif len(pod.Spec.EphemeralContainers) \u003e 0 {\n\t\t\tvar ec []corev1.Container\n\t\t\tfor i := range pod.Spec.EphemeralContainers {\n\t\t\t\tec = append(ec, corev1.Container(pod.Spec.EphemeralContainers[i].EphemeralContainerCommon))\n\t\t\t}\n\t\t\tdescribeContainers(\"Ephemeral Containers\", ec, pod.Status.EphemeralContainerStatuses, EnvValueRetriever(pod), w, \"\")\n\t\t}\n\t\tif len(pod.Spec.ReadinessGates) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"Readiness Gates:\\n Type\\tStatus\\n\")\n\t\t\tfor _, g := range pod.Spec.ReadinessGates {\n\t\t\t\tstatus := \"\u003cnone\u003e\"\n\t\t\t\tfor _, c := range pod.Status.Conditions {\n\t\t\t\t\tif c.Type == g.ConditionType {\n\t\t\t\t\t\tstatus = fmt.Sprintf(\"%v\", c.Status)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tw.Write(LEVEL_1, \"%v \\t%v \\n\",\n\t\t\t\t\tg.ConditionType,\n\t\t\t\t\tstatus)\n\t\t\t}\n\t\t}\n\t\tif len(pod.Status.Conditions) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"Conditions:\\n Type\\tStatus\\n\")\n\t\t\tfor _, c := range pod.Status.Conditions {\n\t\t\t\tw.Write(LEVEL_1, \"%v \\t%v \\n\",\n\t\t\t\t\tc.Type,\n\t\t\t\t\tc.Status)\n\t\t\t}\n\t\t}\n\t\tdescribeVolumes(pod.Spec.Volumes, w, \"\")\n\t\tif pod.Status.QOSClass != \"\" {\n\t\t\tw.Write(LEVEL_0, \"QoS Class:\\t%s\\n\", pod.Status.QOSClass)\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"QoS Class:\\t%s\\n\", qos.GetPodQOS(pod))\n\t\t}\n\t\tprintLabelsMultiline(w, \"Node-Selectors\", pod.Spec.NodeSelector)\n\t\tprintPodTolerationsMultiline(w, \"Tolerations\", pod.Spec.Tolerations)\n\t\tdescribeTopologySpreadConstraints(pod.Spec.TopologySpreadConstraints, w, \"\")\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":763,"to":866}} {"id":100032383,"name":"printController","signature":"func printController(controllee metav1.Object) string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printController(controllee metav1.Object) string {\n\tif controllerRef := metav1.GetControllerOf(controllee); controllerRef != nil {\n\t\treturn fmt.Sprintf(\"%s/%s\", controllerRef.Kind, controllerRef.Name)\n\t}\n\treturn \"\"\n}","line":{"from":868,"to":873}} {"id":100032384,"name":"describePodIPs","signature":"func describePodIPs(pod *corev1.Pod, w PrefixWriter, space string)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describePodIPs(pod *corev1.Pod, w PrefixWriter, space string) {\n\tif len(pod.Status.PodIPs) == 0 {\n\t\tw.Write(LEVEL_0, \"%sIPs:\\t\u003cnone\u003e\\n\", space)\n\t\treturn\n\t}\n\tw.Write(LEVEL_0, \"%sIPs:\\n\", space)\n\tfor _, ipInfo := range pod.Status.PodIPs {\n\t\tw.Write(LEVEL_1, \"IP:\\t%s\\n\", ipInfo.IP)\n\t}\n}","line":{"from":875,"to":884}} {"id":100032385,"name":"describeTopologySpreadConstraints","signature":"func describeTopologySpreadConstraints(tscs []corev1.TopologySpreadConstraint, w PrefixWriter, space string)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeTopologySpreadConstraints(tscs []corev1.TopologySpreadConstraint, w PrefixWriter, space string) {\n\tif len(tscs) == 0 {\n\t\treturn\n\t}\n\n\tsort.Slice(tscs, func(i, j int) bool {\n\t\treturn tscs[i].TopologyKey \u003c tscs[j].TopologyKey\n\t})\n\n\tw.Write(LEVEL_0, \"%sTopology Spread Constraints:\\t\", space)\n\tfor i, tsc := range tscs {\n\t\tif i != 0 {\n\t\t\tw.Write(LEVEL_0, \"%s\", space)\n\t\t\tw.Write(LEVEL_0, \"%s\", \"\\t\")\n\t\t}\n\n\t\tw.Write(LEVEL_0, \"%s:\", tsc.TopologyKey)\n\t\tw.Write(LEVEL_0, \"%v\", tsc.WhenUnsatisfiable)\n\t\tw.Write(LEVEL_0, \" when max skew %d is exceeded\", tsc.MaxSkew)\n\t\tif tsc.LabelSelector != nil {\n\t\t\tw.Write(LEVEL_0, \" for selector %s\", metav1.FormatLabelSelector(tsc.LabelSelector))\n\t\t}\n\t\tw.Write(LEVEL_0, \"\\n\")\n\t}\n}","line":{"from":886,"to":910}} {"id":100032386,"name":"describeVolumes","signature":"func describeVolumes(volumes []corev1.Volume, w PrefixWriter, space string)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeVolumes(volumes []corev1.Volume, w PrefixWriter, space string) {\n\tif len(volumes) == 0 {\n\t\tw.Write(LEVEL_0, \"%sVolumes:\\t\u003cnone\u003e\\n\", space)\n\t\treturn\n\t}\n\n\tw.Write(LEVEL_0, \"%sVolumes:\\n\", space)\n\tfor _, volume := range volumes {\n\t\tnameIndent := \"\"\n\t\tif len(space) \u003e 0 {\n\t\t\tnameIndent = \" \"\n\t\t}\n\t\tw.Write(LEVEL_1, \"%s%v:\\n\", nameIndent, volume.Name)\n\t\tswitch {\n\t\tcase volume.VolumeSource.HostPath != nil:\n\t\t\tprintHostPathVolumeSource(volume.VolumeSource.HostPath, w)\n\t\tcase volume.VolumeSource.EmptyDir != nil:\n\t\t\tprintEmptyDirVolumeSource(volume.VolumeSource.EmptyDir, w)\n\t\tcase volume.VolumeSource.GCEPersistentDisk != nil:\n\t\t\tprintGCEPersistentDiskVolumeSource(volume.VolumeSource.GCEPersistentDisk, w)\n\t\tcase volume.VolumeSource.AWSElasticBlockStore != nil:\n\t\t\tprintAWSElasticBlockStoreVolumeSource(volume.VolumeSource.AWSElasticBlockStore, w)\n\t\tcase volume.VolumeSource.GitRepo != nil:\n\t\t\tprintGitRepoVolumeSource(volume.VolumeSource.GitRepo, w)\n\t\tcase volume.VolumeSource.Secret != nil:\n\t\t\tprintSecretVolumeSource(volume.VolumeSource.Secret, w)\n\t\tcase volume.VolumeSource.ConfigMap != nil:\n\t\t\tprintConfigMapVolumeSource(volume.VolumeSource.ConfigMap, w)\n\t\tcase volume.VolumeSource.NFS != nil:\n\t\t\tprintNFSVolumeSource(volume.VolumeSource.NFS, w)\n\t\tcase volume.VolumeSource.ISCSI != nil:\n\t\t\tprintISCSIVolumeSource(volume.VolumeSource.ISCSI, w)\n\t\tcase volume.VolumeSource.Glusterfs != nil:\n\t\t\tprintGlusterfsVolumeSource(volume.VolumeSource.Glusterfs, w)\n\t\tcase volume.VolumeSource.PersistentVolumeClaim != nil:\n\t\t\tprintPersistentVolumeClaimVolumeSource(volume.VolumeSource.PersistentVolumeClaim, w)\n\t\tcase volume.VolumeSource.Ephemeral != nil:\n\t\t\tprintEphemeralVolumeSource(volume.VolumeSource.Ephemeral, w)\n\t\tcase volume.VolumeSource.RBD != nil:\n\t\t\tprintRBDVolumeSource(volume.VolumeSource.RBD, w)\n\t\tcase volume.VolumeSource.Quobyte != nil:\n\t\t\tprintQuobyteVolumeSource(volume.VolumeSource.Quobyte, w)\n\t\tcase volume.VolumeSource.DownwardAPI != nil:\n\t\t\tprintDownwardAPIVolumeSource(volume.VolumeSource.DownwardAPI, w)\n\t\tcase volume.VolumeSource.AzureDisk != nil:\n\t\t\tprintAzureDiskVolumeSource(volume.VolumeSource.AzureDisk, w)\n\t\tcase volume.VolumeSource.VsphereVolume != nil:\n\t\t\tprintVsphereVolumeSource(volume.VolumeSource.VsphereVolume, w)\n\t\tcase volume.VolumeSource.Cinder != nil:\n\t\t\tprintCinderVolumeSource(volume.VolumeSource.Cinder, w)\n\t\tcase volume.VolumeSource.PhotonPersistentDisk != nil:\n\t\t\tprintPhotonPersistentDiskVolumeSource(volume.VolumeSource.PhotonPersistentDisk, w)\n\t\tcase volume.VolumeSource.PortworxVolume != nil:\n\t\t\tprintPortworxVolumeSource(volume.VolumeSource.PortworxVolume, w)\n\t\tcase volume.VolumeSource.ScaleIO != nil:\n\t\t\tprintScaleIOVolumeSource(volume.VolumeSource.ScaleIO, w)\n\t\tcase volume.VolumeSource.CephFS != nil:\n\t\t\tprintCephFSVolumeSource(volume.VolumeSource.CephFS, w)\n\t\tcase volume.VolumeSource.StorageOS != nil:\n\t\t\tprintStorageOSVolumeSource(volume.VolumeSource.StorageOS, w)\n\t\tcase volume.VolumeSource.FC != nil:\n\t\t\tprintFCVolumeSource(volume.VolumeSource.FC, w)\n\t\tcase volume.VolumeSource.AzureFile != nil:\n\t\t\tprintAzureFileVolumeSource(volume.VolumeSource.AzureFile, w)\n\t\tcase volume.VolumeSource.FlexVolume != nil:\n\t\t\tprintFlexVolumeSource(volume.VolumeSource.FlexVolume, w)\n\t\tcase volume.VolumeSource.Flocker != nil:\n\t\t\tprintFlockerVolumeSource(volume.VolumeSource.Flocker, w)\n\t\tcase volume.VolumeSource.Projected != nil:\n\t\t\tprintProjectedVolumeSource(volume.VolumeSource.Projected, w)\n\t\tcase volume.VolumeSource.CSI != nil:\n\t\t\tprintCSIVolumeSource(volume.VolumeSource.CSI, w)\n\t\tdefault:\n\t\t\tw.Write(LEVEL_1, \"\u003cunknown\u003e\\n\")\n\t\t}\n\t}\n}","line":{"from":912,"to":988}} {"id":100032387,"name":"printHostPathVolumeSource","signature":"func printHostPathVolumeSource(hostPath *corev1.HostPathVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printHostPathVolumeSource(hostPath *corev1.HostPathVolumeSource, w PrefixWriter) {\n\thostPathType := \"\u003cnone\u003e\"\n\tif hostPath.Type != nil {\n\t\thostPathType = string(*hostPath.Type)\n\t}\n\tw.Write(LEVEL_2, \"Type:\\tHostPath (bare host directory volume)\\n\"+\n\t\t\" Path:\\t%v\\n\"+\n\t\t\" HostPathType:\\t%v\\n\",\n\t\thostPath.Path, hostPathType)\n}","line":{"from":990,"to":999}} {"id":100032388,"name":"printEmptyDirVolumeSource","signature":"func printEmptyDirVolumeSource(emptyDir *corev1.EmptyDirVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printEmptyDirVolumeSource(emptyDir *corev1.EmptyDirVolumeSource, w PrefixWriter) {\n\tvar sizeLimit string\n\tif emptyDir.SizeLimit != nil \u0026\u0026 emptyDir.SizeLimit.Cmp(resource.Quantity{}) \u003e 0 {\n\t\tsizeLimit = fmt.Sprintf(\"%v\", emptyDir.SizeLimit)\n\t} else {\n\t\tsizeLimit = \"\u003cunset\u003e\"\n\t}\n\tw.Write(LEVEL_2, \"Type:\\tEmptyDir (a temporary directory that shares a pod's lifetime)\\n\"+\n\t\t\" Medium:\\t%v\\n\"+\n\t\t\" SizeLimit:\\t%v\\n\",\n\t\temptyDir.Medium, sizeLimit)\n}","line":{"from":1001,"to":1012}} {"id":100032389,"name":"printGCEPersistentDiskVolumeSource","signature":"func printGCEPersistentDiskVolumeSource(gce *corev1.GCEPersistentDiskVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printGCEPersistentDiskVolumeSource(gce *corev1.GCEPersistentDiskVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tGCEPersistentDisk (a Persistent Disk resource in Google Compute Engine)\\n\"+\n\t\t\" PDName:\\t%v\\n\"+\n\t\t\" FSType:\\t%v\\n\"+\n\t\t\" Partition:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\",\n\t\tgce.PDName, gce.FSType, gce.Partition, gce.ReadOnly)\n}","line":{"from":1014,"to":1021}} {"id":100032390,"name":"printAWSElasticBlockStoreVolumeSource","signature":"func printAWSElasticBlockStoreVolumeSource(aws *corev1.AWSElasticBlockStoreVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printAWSElasticBlockStoreVolumeSource(aws *corev1.AWSElasticBlockStoreVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tAWSElasticBlockStore (a Persistent Disk resource in AWS)\\n\"+\n\t\t\" VolumeID:\\t%v\\n\"+\n\t\t\" FSType:\\t%v\\n\"+\n\t\t\" Partition:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\",\n\t\taws.VolumeID, aws.FSType, aws.Partition, aws.ReadOnly)\n}","line":{"from":1023,"to":1030}} {"id":100032391,"name":"printGitRepoVolumeSource","signature":"func printGitRepoVolumeSource(git *corev1.GitRepoVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printGitRepoVolumeSource(git *corev1.GitRepoVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tGitRepo (a volume that is pulled from git when the pod is created)\\n\"+\n\t\t\" Repository:\\t%v\\n\"+\n\t\t\" Revision:\\t%v\\n\",\n\t\tgit.Repository, git.Revision)\n}","line":{"from":1032,"to":1037}} {"id":100032392,"name":"printSecretVolumeSource","signature":"func printSecretVolumeSource(secret *corev1.SecretVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printSecretVolumeSource(secret *corev1.SecretVolumeSource, w PrefixWriter) {\n\toptional := secret.Optional != nil \u0026\u0026 *secret.Optional\n\tw.Write(LEVEL_2, \"Type:\\tSecret (a volume populated by a Secret)\\n\"+\n\t\t\" SecretName:\\t%v\\n\"+\n\t\t\" Optional:\\t%v\\n\",\n\t\tsecret.SecretName, optional)\n}","line":{"from":1039,"to":1045}} {"id":100032393,"name":"printConfigMapVolumeSource","signature":"func printConfigMapVolumeSource(configMap *corev1.ConfigMapVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printConfigMapVolumeSource(configMap *corev1.ConfigMapVolumeSource, w PrefixWriter) {\n\toptional := configMap.Optional != nil \u0026\u0026 *configMap.Optional\n\tw.Write(LEVEL_2, \"Type:\\tConfigMap (a volume populated by a ConfigMap)\\n\"+\n\t\t\" Name:\\t%v\\n\"+\n\t\t\" Optional:\\t%v\\n\",\n\t\tconfigMap.Name, optional)\n}","line":{"from":1047,"to":1053}} {"id":100032394,"name":"printProjectedVolumeSource","signature":"func printProjectedVolumeSource(projected *corev1.ProjectedVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printProjectedVolumeSource(projected *corev1.ProjectedVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tProjected (a volume that contains injected data from multiple sources)\\n\")\n\tfor _, source := range projected.Sources {\n\t\tif source.Secret != nil {\n\t\t\tw.Write(LEVEL_2, \"SecretName:\\t%v\\n\"+\n\t\t\t\t\" SecretOptionalName:\\t%v\\n\",\n\t\t\t\tsource.Secret.Name, source.Secret.Optional)\n\t\t} else if source.DownwardAPI != nil {\n\t\t\tw.Write(LEVEL_2, \"DownwardAPI:\\ttrue\\n\")\n\t\t} else if source.ConfigMap != nil {\n\t\t\tw.Write(LEVEL_2, \"ConfigMapName:\\t%v\\n\"+\n\t\t\t\t\" ConfigMapOptional:\\t%v\\n\",\n\t\t\t\tsource.ConfigMap.Name, source.ConfigMap.Optional)\n\t\t} else if source.ServiceAccountToken != nil {\n\t\t\tw.Write(LEVEL_2, \"TokenExpirationSeconds:\\t%d\\n\",\n\t\t\t\t*source.ServiceAccountToken.ExpirationSeconds)\n\t\t}\n\t}\n}","line":{"from":1055,"to":1073}} {"id":100032395,"name":"printNFSVolumeSource","signature":"func printNFSVolumeSource(nfs *corev1.NFSVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printNFSVolumeSource(nfs *corev1.NFSVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tNFS (an NFS mount that lasts the lifetime of a pod)\\n\"+\n\t\t\" Server:\\t%v\\n\"+\n\t\t\" Path:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\",\n\t\tnfs.Server, nfs.Path, nfs.ReadOnly)\n}","line":{"from":1075,"to":1081}} {"id":100032396,"name":"printQuobyteVolumeSource","signature":"func printQuobyteVolumeSource(quobyte *corev1.QuobyteVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printQuobyteVolumeSource(quobyte *corev1.QuobyteVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tQuobyte (a Quobyte mount on the host that shares a pod's lifetime)\\n\"+\n\t\t\" Registry:\\t%v\\n\"+\n\t\t\" Volume:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\",\n\t\tquobyte.Registry, quobyte.Volume, quobyte.ReadOnly)\n}","line":{"from":1083,"to":1089}} {"id":100032397,"name":"printPortworxVolumeSource","signature":"func printPortworxVolumeSource(pwxVolume *corev1.PortworxVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printPortworxVolumeSource(pwxVolume *corev1.PortworxVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tPortworxVolume (a Portworx Volume resource)\\n\"+\n\t\t\" VolumeID:\\t%v\\n\",\n\t\tpwxVolume.VolumeID)\n}","line":{"from":1091,"to":1095}} {"id":100032398,"name":"printISCSIVolumeSource","signature":"func printISCSIVolumeSource(iscsi *corev1.ISCSIVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printISCSIVolumeSource(iscsi *corev1.ISCSIVolumeSource, w PrefixWriter) {\n\tinitiator := \"\u003cnone\u003e\"\n\tif iscsi.InitiatorName != nil {\n\t\tinitiator = *iscsi.InitiatorName\n\t}\n\tw.Write(LEVEL_2, \"Type:\\tISCSI (an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod)\\n\"+\n\t\t\" TargetPortal:\\t%v\\n\"+\n\t\t\" IQN:\\t%v\\n\"+\n\t\t\" Lun:\\t%v\\n\"+\n\t\t\" ISCSIInterface\\t%v\\n\"+\n\t\t\" FSType:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\"+\n\t\t\" Portals:\\t%v\\n\"+\n\t\t\" DiscoveryCHAPAuth:\\t%v\\n\"+\n\t\t\" SessionCHAPAuth:\\t%v\\n\"+\n\t\t\" SecretRef:\\t%v\\n\"+\n\t\t\" InitiatorName:\\t%v\\n\",\n\t\tiscsi.TargetPortal, iscsi.IQN, iscsi.Lun, iscsi.ISCSIInterface, iscsi.FSType, iscsi.ReadOnly, iscsi.Portals, iscsi.DiscoveryCHAPAuth, iscsi.SessionCHAPAuth, iscsi.SecretRef, initiator)\n}","line":{"from":1097,"to":1115}} {"id":100032399,"name":"printISCSIPersistentVolumeSource","signature":"func printISCSIPersistentVolumeSource(iscsi *corev1.ISCSIPersistentVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printISCSIPersistentVolumeSource(iscsi *corev1.ISCSIPersistentVolumeSource, w PrefixWriter) {\n\tinitiatorName := \"\u003cnone\u003e\"\n\tif iscsi.InitiatorName != nil {\n\t\tinitiatorName = *iscsi.InitiatorName\n\t}\n\tw.Write(LEVEL_2, \"Type:\\tISCSI (an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod)\\n\"+\n\t\t\" TargetPortal:\\t%v\\n\"+\n\t\t\" IQN:\\t%v\\n\"+\n\t\t\" Lun:\\t%v\\n\"+\n\t\t\" ISCSIInterface\\t%v\\n\"+\n\t\t\" FSType:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\"+\n\t\t\" Portals:\\t%v\\n\"+\n\t\t\" DiscoveryCHAPAuth:\\t%v\\n\"+\n\t\t\" SessionCHAPAuth:\\t%v\\n\"+\n\t\t\" SecretRef:\\t%v\\n\"+\n\t\t\" InitiatorName:\\t%v\\n\",\n\t\tiscsi.TargetPortal, iscsi.IQN, iscsi.Lun, iscsi.ISCSIInterface, iscsi.FSType, iscsi.ReadOnly, iscsi.Portals, iscsi.DiscoveryCHAPAuth, iscsi.SessionCHAPAuth, iscsi.SecretRef, initiatorName)\n}","line":{"from":1117,"to":1135}} {"id":100032400,"name":"printGlusterfsVolumeSource","signature":"func printGlusterfsVolumeSource(glusterfs *corev1.GlusterfsVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printGlusterfsVolumeSource(glusterfs *corev1.GlusterfsVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tGlusterfs (a Glusterfs mount on the host that shares a pod's lifetime)\\n\"+\n\t\t\" EndpointsName:\\t%v\\n\"+\n\t\t\" Path:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\",\n\t\tglusterfs.EndpointsName, glusterfs.Path, glusterfs.ReadOnly)\n}","line":{"from":1137,"to":1143}} {"id":100032401,"name":"printGlusterfsPersistentVolumeSource","signature":"func printGlusterfsPersistentVolumeSource(glusterfs *corev1.GlusterfsPersistentVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printGlusterfsPersistentVolumeSource(glusterfs *corev1.GlusterfsPersistentVolumeSource, w PrefixWriter) {\n\tendpointsNamespace := \"\u003cunset\u003e\"\n\tif glusterfs.EndpointsNamespace != nil {\n\t\tendpointsNamespace = *glusterfs.EndpointsNamespace\n\t}\n\tw.Write(LEVEL_2, \"Type:\\tGlusterfs (a Glusterfs mount on the host that shares a pod's lifetime)\\n\"+\n\t\t\" EndpointsName:\\t%v\\n\"+\n\t\t\" EndpointsNamespace:\\t%v\\n\"+\n\t\t\" Path:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\",\n\t\tglusterfs.EndpointsName, endpointsNamespace, glusterfs.Path, glusterfs.ReadOnly)\n}","line":{"from":1145,"to":1156}} {"id":100032402,"name":"printPersistentVolumeClaimVolumeSource","signature":"func printPersistentVolumeClaimVolumeSource(claim *corev1.PersistentVolumeClaimVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printPersistentVolumeClaimVolumeSource(claim *corev1.PersistentVolumeClaimVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tPersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)\\n\"+\n\t\t\" ClaimName:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\",\n\t\tclaim.ClaimName, claim.ReadOnly)\n}","line":{"from":1158,"to":1163}} {"id":100032403,"name":"printEphemeralVolumeSource","signature":"func printEphemeralVolumeSource(ephemeral *corev1.EphemeralVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printEphemeralVolumeSource(ephemeral *corev1.EphemeralVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tEphemeralVolume (an inline specification for a volume that gets created and deleted with the pod)\\n\")\n\tif ephemeral.VolumeClaimTemplate != nil {\n\t\tprintPersistentVolumeClaim(NewNestedPrefixWriter(w, LEVEL_2),\n\t\t\t\u0026corev1.PersistentVolumeClaim{\n\t\t\t\tObjectMeta: ephemeral.VolumeClaimTemplate.ObjectMeta,\n\t\t\t\tSpec: ephemeral.VolumeClaimTemplate.Spec,\n\t\t\t}, false /* not a full PVC */)\n\t}\n}","line":{"from":1165,"to":1174}} {"id":100032404,"name":"printRBDVolumeSource","signature":"func printRBDVolumeSource(rbd *corev1.RBDVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printRBDVolumeSource(rbd *corev1.RBDVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tRBD (a Rados Block Device mount on the host that shares a pod's lifetime)\\n\"+\n\t\t\" CephMonitors:\\t%v\\n\"+\n\t\t\" RBDImage:\\t%v\\n\"+\n\t\t\" FSType:\\t%v\\n\"+\n\t\t\" RBDPool:\\t%v\\n\"+\n\t\t\" RadosUser:\\t%v\\n\"+\n\t\t\" Keyring:\\t%v\\n\"+\n\t\t\" SecretRef:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\",\n\t\trbd.CephMonitors, rbd.RBDImage, rbd.FSType, rbd.RBDPool, rbd.RadosUser, rbd.Keyring, rbd.SecretRef, rbd.ReadOnly)\n}","line":{"from":1176,"to":1187}} {"id":100032405,"name":"printRBDPersistentVolumeSource","signature":"func printRBDPersistentVolumeSource(rbd *corev1.RBDPersistentVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printRBDPersistentVolumeSource(rbd *corev1.RBDPersistentVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tRBD (a Rados Block Device mount on the host that shares a pod's lifetime)\\n\"+\n\t\t\" CephMonitors:\\t%v\\n\"+\n\t\t\" RBDImage:\\t%v\\n\"+\n\t\t\" FSType:\\t%v\\n\"+\n\t\t\" RBDPool:\\t%v\\n\"+\n\t\t\" RadosUser:\\t%v\\n\"+\n\t\t\" Keyring:\\t%v\\n\"+\n\t\t\" SecretRef:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\",\n\t\trbd.CephMonitors, rbd.RBDImage, rbd.FSType, rbd.RBDPool, rbd.RadosUser, rbd.Keyring, rbd.SecretRef, rbd.ReadOnly)\n}","line":{"from":1189,"to":1200}} {"id":100032406,"name":"printDownwardAPIVolumeSource","signature":"func printDownwardAPIVolumeSource(d *corev1.DownwardAPIVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printDownwardAPIVolumeSource(d *corev1.DownwardAPIVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tDownwardAPI (a volume populated by information about the pod)\\n Items:\\n\")\n\tfor _, mapping := range d.Items {\n\t\tif mapping.FieldRef != nil {\n\t\t\tw.Write(LEVEL_3, \"%v -\u003e %v\\n\", mapping.FieldRef.FieldPath, mapping.Path)\n\t\t}\n\t\tif mapping.ResourceFieldRef != nil {\n\t\t\tw.Write(LEVEL_3, \"%v -\u003e %v\\n\", mapping.ResourceFieldRef.Resource, mapping.Path)\n\t\t}\n\t}\n}","line":{"from":1202,"to":1212}} {"id":100032407,"name":"printAzureDiskVolumeSource","signature":"func printAzureDiskVolumeSource(d *corev1.AzureDiskVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printAzureDiskVolumeSource(d *corev1.AzureDiskVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tAzureDisk (an Azure Data Disk mount on the host and bind mount to the pod)\\n\"+\n\t\t\" DiskName:\\t%v\\n\"+\n\t\t\" DiskURI:\\t%v\\n\"+\n\t\t\" Kind: \\t%v\\n\"+\n\t\t\" FSType:\\t%v\\n\"+\n\t\t\" CachingMode:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\",\n\t\td.DiskName, d.DataDiskURI, *d.Kind, *d.FSType, *d.CachingMode, *d.ReadOnly)\n}","line":{"from":1214,"to":1223}} {"id":100032408,"name":"printVsphereVolumeSource","signature":"func printVsphereVolumeSource(vsphere *corev1.VsphereVirtualDiskVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printVsphereVolumeSource(vsphere *corev1.VsphereVirtualDiskVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tvSphereVolume (a Persistent Disk resource in vSphere)\\n\"+\n\t\t\" VolumePath:\\t%v\\n\"+\n\t\t\" FSType:\\t%v\\n\"+\n\t\t\" StoragePolicyName:\\t%v\\n\",\n\t\tvsphere.VolumePath, vsphere.FSType, vsphere.StoragePolicyName)\n}","line":{"from":1225,"to":1231}} {"id":100032409,"name":"printPhotonPersistentDiskVolumeSource","signature":"func printPhotonPersistentDiskVolumeSource(photon *corev1.PhotonPersistentDiskVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printPhotonPersistentDiskVolumeSource(photon *corev1.PhotonPersistentDiskVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tPhotonPersistentDisk (a Persistent Disk resource in photon platform)\\n\"+\n\t\t\" PdID:\\t%v\\n\"+\n\t\t\" FSType:\\t%v\\n\",\n\t\tphoton.PdID, photon.FSType)\n}","line":{"from":1233,"to":1238}} {"id":100032410,"name":"printCinderVolumeSource","signature":"func printCinderVolumeSource(cinder *corev1.CinderVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printCinderVolumeSource(cinder *corev1.CinderVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tCinder (a Persistent Disk resource in OpenStack)\\n\"+\n\t\t\" VolumeID:\\t%v\\n\"+\n\t\t\" FSType:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\"+\n\t\t\" SecretRef:\\t%v\\n\",\n\t\tcinder.VolumeID, cinder.FSType, cinder.ReadOnly, cinder.SecretRef)\n}","line":{"from":1240,"to":1247}} {"id":100032411,"name":"printCinderPersistentVolumeSource","signature":"func printCinderPersistentVolumeSource(cinder *corev1.CinderPersistentVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printCinderPersistentVolumeSource(cinder *corev1.CinderPersistentVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tCinder (a Persistent Disk resource in OpenStack)\\n\"+\n\t\t\" VolumeID:\\t%v\\n\"+\n\t\t\" FSType:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\"+\n\t\t\" SecretRef:\\t%v\\n\",\n\t\tcinder.VolumeID, cinder.FSType, cinder.ReadOnly, cinder.SecretRef)\n}","line":{"from":1249,"to":1256}} {"id":100032412,"name":"printScaleIOVolumeSource","signature":"func printScaleIOVolumeSource(sio *corev1.ScaleIOVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printScaleIOVolumeSource(sio *corev1.ScaleIOVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tScaleIO (a persistent volume backed by a block device in ScaleIO)\\n\"+\n\t\t\" Gateway:\\t%v\\n\"+\n\t\t\" System:\\t%v\\n\"+\n\t\t\" Protection Domain:\\t%v\\n\"+\n\t\t\" Storage Pool:\\t%v\\n\"+\n\t\t\" Storage Mode:\\t%v\\n\"+\n\t\t\" VolumeName:\\t%v\\n\"+\n\t\t\" FSType:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\",\n\t\tsio.Gateway, sio.System, sio.ProtectionDomain, sio.StoragePool, sio.StorageMode, sio.VolumeName, sio.FSType, sio.ReadOnly)\n}","line":{"from":1258,"to":1269}} {"id":100032413,"name":"printScaleIOPersistentVolumeSource","signature":"func printScaleIOPersistentVolumeSource(sio *corev1.ScaleIOPersistentVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printScaleIOPersistentVolumeSource(sio *corev1.ScaleIOPersistentVolumeSource, w PrefixWriter) {\n\tvar secretNS, secretName string\n\tif sio.SecretRef != nil {\n\t\tsecretName = sio.SecretRef.Name\n\t\tsecretNS = sio.SecretRef.Namespace\n\t}\n\tw.Write(LEVEL_2, \"Type:\\tScaleIO (a persistent volume backed by a block device in ScaleIO)\\n\"+\n\t\t\" Gateway:\\t%v\\n\"+\n\t\t\" System:\\t%v\\n\"+\n\t\t\" Protection Domain:\\t%v\\n\"+\n\t\t\" Storage Pool:\\t%v\\n\"+\n\t\t\" Storage Mode:\\t%v\\n\"+\n\t\t\" VolumeName:\\t%v\\n\"+\n\t\t\" SecretName:\\t%v\\n\"+\n\t\t\" SecretNamespace:\\t%v\\n\"+\n\t\t\" FSType:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\",\n\t\tsio.Gateway, sio.System, sio.ProtectionDomain, sio.StoragePool, sio.StorageMode, sio.VolumeName, secretName, secretNS, sio.FSType, sio.ReadOnly)\n}","line":{"from":1271,"to":1289}} {"id":100032414,"name":"printLocalVolumeSource","signature":"func printLocalVolumeSource(ls *corev1.LocalVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printLocalVolumeSource(ls *corev1.LocalVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tLocalVolume (a persistent volume backed by local storage on a node)\\n\"+\n\t\t\" Path:\\t%v\\n\",\n\t\tls.Path)\n}","line":{"from":1291,"to":1295}} {"id":100032415,"name":"printCephFSVolumeSource","signature":"func printCephFSVolumeSource(cephfs *corev1.CephFSVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printCephFSVolumeSource(cephfs *corev1.CephFSVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tCephFS (a CephFS mount on the host that shares a pod's lifetime)\\n\"+\n\t\t\" Monitors:\\t%v\\n\"+\n\t\t\" Path:\\t%v\\n\"+\n\t\t\" User:\\t%v\\n\"+\n\t\t\" SecretFile:\\t%v\\n\"+\n\t\t\" SecretRef:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\",\n\t\tcephfs.Monitors, cephfs.Path, cephfs.User, cephfs.SecretFile, cephfs.SecretRef, cephfs.ReadOnly)\n}","line":{"from":1297,"to":1306}} {"id":100032416,"name":"printCephFSPersistentVolumeSource","signature":"func printCephFSPersistentVolumeSource(cephfs *corev1.CephFSPersistentVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printCephFSPersistentVolumeSource(cephfs *corev1.CephFSPersistentVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tCephFS (a CephFS mount on the host that shares a pod's lifetime)\\n\"+\n\t\t\" Monitors:\\t%v\\n\"+\n\t\t\" Path:\\t%v\\n\"+\n\t\t\" User:\\t%v\\n\"+\n\t\t\" SecretFile:\\t%v\\n\"+\n\t\t\" SecretRef:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\",\n\t\tcephfs.Monitors, cephfs.Path, cephfs.User, cephfs.SecretFile, cephfs.SecretRef, cephfs.ReadOnly)\n}","line":{"from":1308,"to":1317}} {"id":100032417,"name":"printStorageOSVolumeSource","signature":"func printStorageOSVolumeSource(storageos *corev1.StorageOSVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printStorageOSVolumeSource(storageos *corev1.StorageOSVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tStorageOS (a StorageOS Persistent Disk resource)\\n\"+\n\t\t\" VolumeName:\\t%v\\n\"+\n\t\t\" VolumeNamespace:\\t%v\\n\"+\n\t\t\" FSType:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\",\n\t\tstorageos.VolumeName, storageos.VolumeNamespace, storageos.FSType, storageos.ReadOnly)\n}","line":{"from":1319,"to":1326}} {"id":100032418,"name":"printStorageOSPersistentVolumeSource","signature":"func printStorageOSPersistentVolumeSource(storageos *corev1.StorageOSPersistentVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printStorageOSPersistentVolumeSource(storageos *corev1.StorageOSPersistentVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tStorageOS (a StorageOS Persistent Disk resource)\\n\"+\n\t\t\" VolumeName:\\t%v\\n\"+\n\t\t\" VolumeNamespace:\\t%v\\n\"+\n\t\t\" FSType:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\",\n\t\tstorageos.VolumeName, storageos.VolumeNamespace, storageos.FSType, storageos.ReadOnly)\n}","line":{"from":1328,"to":1335}} {"id":100032419,"name":"printFCVolumeSource","signature":"func printFCVolumeSource(fc *corev1.FCVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printFCVolumeSource(fc *corev1.FCVolumeSource, w PrefixWriter) {\n\tlun := \"\u003cnone\u003e\"\n\tif fc.Lun != nil {\n\t\tlun = strconv.Itoa(int(*fc.Lun))\n\t}\n\tw.Write(LEVEL_2, \"Type:\\tFC (a Fibre Channel disk)\\n\"+\n\t\t\" TargetWWNs:\\t%v\\n\"+\n\t\t\" LUN:\\t%v\\n\"+\n\t\t\" FSType:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\",\n\t\tstrings.Join(fc.TargetWWNs, \", \"), lun, fc.FSType, fc.ReadOnly)\n}","line":{"from":1337,"to":1348}} {"id":100032420,"name":"printAzureFileVolumeSource","signature":"func printAzureFileVolumeSource(azureFile *corev1.AzureFileVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printAzureFileVolumeSource(azureFile *corev1.AzureFileVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tAzureFile (an Azure File Service mount on the host and bind mount to the pod)\\n\"+\n\t\t\" SecretName:\\t%v\\n\"+\n\t\t\" ShareName:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\",\n\t\tazureFile.SecretName, azureFile.ShareName, azureFile.ReadOnly)\n}","line":{"from":1350,"to":1356}} {"id":100032421,"name":"printAzureFilePersistentVolumeSource","signature":"func printAzureFilePersistentVolumeSource(azureFile *corev1.AzureFilePersistentVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printAzureFilePersistentVolumeSource(azureFile *corev1.AzureFilePersistentVolumeSource, w PrefixWriter) {\n\tns := \"\"\n\tif azureFile.SecretNamespace != nil {\n\t\tns = *azureFile.SecretNamespace\n\t}\n\tw.Write(LEVEL_2, \"Type:\\tAzureFile (an Azure File Service mount on the host and bind mount to the pod)\\n\"+\n\t\t\" SecretName:\\t%v\\n\"+\n\t\t\" SecretNamespace:\\t%v\\n\"+\n\t\t\" ShareName:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\",\n\t\tazureFile.SecretName, ns, azureFile.ShareName, azureFile.ReadOnly)\n}","line":{"from":1358,"to":1369}} {"id":100032422,"name":"printFlexPersistentVolumeSource","signature":"func printFlexPersistentVolumeSource(flex *corev1.FlexPersistentVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printFlexPersistentVolumeSource(flex *corev1.FlexPersistentVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tFlexVolume (a generic volume resource that is provisioned/attached using an exec based plugin)\\n\"+\n\t\t\" Driver:\\t%v\\n\"+\n\t\t\" FSType:\\t%v\\n\"+\n\t\t\" SecretRef:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\"+\n\t\t\" Options:\\t%v\\n\",\n\t\tflex.Driver, flex.FSType, flex.SecretRef, flex.ReadOnly, flex.Options)\n}","line":{"from":1371,"to":1379}} {"id":100032423,"name":"printFlexVolumeSource","signature":"func printFlexVolumeSource(flex *corev1.FlexVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printFlexVolumeSource(flex *corev1.FlexVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tFlexVolume (a generic volume resource that is provisioned/attached using an exec based plugin)\\n\"+\n\t\t\" Driver:\\t%v\\n\"+\n\t\t\" FSType:\\t%v\\n\"+\n\t\t\" SecretRef:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\"+\n\t\t\" Options:\\t%v\\n\",\n\t\tflex.Driver, flex.FSType, flex.SecretRef, flex.ReadOnly, flex.Options)\n}","line":{"from":1381,"to":1389}} {"id":100032424,"name":"printFlockerVolumeSource","signature":"func printFlockerVolumeSource(flocker *corev1.FlockerVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printFlockerVolumeSource(flocker *corev1.FlockerVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tFlocker (a Flocker volume mounted by the Flocker agent)\\n\"+\n\t\t\" DatasetName:\\t%v\\n\"+\n\t\t\" DatasetUUID:\\t%v\\n\",\n\t\tflocker.DatasetName, flocker.DatasetUUID)\n}","line":{"from":1391,"to":1396}} {"id":100032425,"name":"printCSIVolumeSource","signature":"func printCSIVolumeSource(csi *corev1.CSIVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printCSIVolumeSource(csi *corev1.CSIVolumeSource, w PrefixWriter) {\n\tvar readOnly bool\n\tvar fsType string\n\tif csi.ReadOnly != nil \u0026\u0026 *csi.ReadOnly {\n\t\treadOnly = true\n\t}\n\tif csi.FSType != nil {\n\t\tfsType = *csi.FSType\n\t}\n\tw.Write(LEVEL_2, \"Type:\\tCSI (a Container Storage Interface (CSI) volume source)\\n\"+\n\t\t\" Driver:\\t%v\\n\"+\n\t\t\" FSType:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\",\n\t\tcsi.Driver, fsType, readOnly)\n\tprintCSIPersistentVolumeAttributesMultiline(w, \"VolumeAttributes\", csi.VolumeAttributes)\n}","line":{"from":1398,"to":1413}} {"id":100032426,"name":"printCSIPersistentVolumeSource","signature":"func printCSIPersistentVolumeSource(csi *corev1.CSIPersistentVolumeSource, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printCSIPersistentVolumeSource(csi *corev1.CSIPersistentVolumeSource, w PrefixWriter) {\n\tw.Write(LEVEL_2, \"Type:\\tCSI (a Container Storage Interface (CSI) volume source)\\n\"+\n\t\t\" Driver:\\t%v\\n\"+\n\t\t\" FSType:\\t%v\\n\"+\n\t\t\" VolumeHandle:\\t%v\\n\"+\n\t\t\" ReadOnly:\\t%v\\n\",\n\t\tcsi.Driver, csi.FSType, csi.VolumeHandle, csi.ReadOnly)\n\tprintCSIPersistentVolumeAttributesMultiline(w, \"VolumeAttributes\", csi.VolumeAttributes)\n}","line":{"from":1415,"to":1423}} {"id":100032427,"name":"printCSIPersistentVolumeAttributesMultiline","signature":"func printCSIPersistentVolumeAttributesMultiline(w PrefixWriter, title string, annotations map[string]string)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printCSIPersistentVolumeAttributesMultiline(w PrefixWriter, title string, annotations map[string]string) {\n\tprintCSIPersistentVolumeAttributesMultilineIndent(w, \"\", title, \"\\t\", annotations, sets.NewString())\n}","line":{"from":1425,"to":1427}} {"id":100032428,"name":"printCSIPersistentVolumeAttributesMultilineIndent","signature":"func printCSIPersistentVolumeAttributesMultilineIndent(w PrefixWriter, initialIndent, title, innerIndent string, attributes map[string]string, skip sets.String)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printCSIPersistentVolumeAttributesMultilineIndent(w PrefixWriter, initialIndent, title, innerIndent string, attributes map[string]string, skip sets.String) {\n\tw.Write(LEVEL_2, \"%s%s:%s\", initialIndent, title, innerIndent)\n\n\tif len(attributes) == 0 {\n\t\tw.WriteLine(\"\u003cnone\u003e\")\n\t\treturn\n\t}\n\n\t// to print labels in the sorted order\n\tkeys := make([]string, 0, len(attributes))\n\tfor key := range attributes {\n\t\tif skip.Has(key) {\n\t\t\tcontinue\n\t\t}\n\t\tkeys = append(keys, key)\n\t}\n\tif len(attributes) == 0 {\n\t\tw.WriteLine(\"\u003cnone\u003e\")\n\t\treturn\n\t}\n\tsort.Strings(keys)\n\n\tfor i, key := range keys {\n\t\tif i != 0 {\n\t\t\tw.Write(LEVEL_2, initialIndent)\n\t\t\tw.Write(LEVEL_2, innerIndent)\n\t\t}\n\t\tline := fmt.Sprintf(\"%s=%s\", key, attributes[key])\n\t\tif len(line) \u003e maxAnnotationLen {\n\t\t\tw.Write(LEVEL_2, \"%s...\\n\", line[:maxAnnotationLen])\n\t\t} else {\n\t\t\tw.Write(LEVEL_2, \"%s\\n\", line)\n\t\t}\n\t}\n}","line":{"from":1429,"to":1463}} {"id":100032429,"name":"Describe","signature":"func (d *PersistentVolumeDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (d *PersistentVolumeDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tc := d.CoreV1().PersistentVolumes()\n\n\tpv, err := c.Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar events *corev1.EventList\n\tif describerSettings.ShowEvents {\n\t\tevents, _ = searchEvents(d.CoreV1(), pv, describerSettings.ChunkSize)\n\t}\n\n\treturn describePersistentVolume(pv, events)\n}","line":{"from":1469,"to":1483}} {"id":100032430,"name":"printVolumeNodeAffinity","signature":"func printVolumeNodeAffinity(w PrefixWriter, affinity *corev1.VolumeNodeAffinity)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printVolumeNodeAffinity(w PrefixWriter, affinity *corev1.VolumeNodeAffinity) {\n\tw.Write(LEVEL_0, \"Node Affinity:\\t\")\n\tif affinity == nil || affinity.Required == nil {\n\t\tw.WriteLine(\"\u003cnone\u003e\")\n\t\treturn\n\t}\n\tw.WriteLine(\"\")\n\n\tif affinity.Required != nil {\n\t\tw.Write(LEVEL_1, \"Required Terms:\\t\")\n\t\tif len(affinity.Required.NodeSelectorTerms) == 0 {\n\t\t\tw.WriteLine(\"\u003cnone\u003e\")\n\t\t} else {\n\t\t\tw.WriteLine(\"\")\n\t\t\tfor i, term := range affinity.Required.NodeSelectorTerms {\n\t\t\t\tprintNodeSelectorTermsMultilineWithIndent(w, LEVEL_2, fmt.Sprintf(\"Term %v\", i), \"\\t\", term.MatchExpressions)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":1485,"to":1504}} {"id":100032431,"name":"printNodeSelectorTermsMultilineWithIndent","signature":"func printNodeSelectorTermsMultilineWithIndent(w PrefixWriter, indentLevel int, title, innerIndent string, reqs []corev1.NodeSelectorRequirement)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// printLabelsMultiline prints multiple labels with a user-defined alignment.\nfunc printNodeSelectorTermsMultilineWithIndent(w PrefixWriter, indentLevel int, title, innerIndent string, reqs []corev1.NodeSelectorRequirement) {\n\tw.Write(indentLevel, \"%s:%s\", title, innerIndent)\n\n\tif len(reqs) == 0 {\n\t\tw.WriteLine(\"\u003cnone\u003e\")\n\t\treturn\n\t}\n\n\tfor i, req := range reqs {\n\t\tif i != 0 {\n\t\t\tw.Write(indentLevel, \"%s\", innerIndent)\n\t\t}\n\t\texprStr := fmt.Sprintf(\"%s %s\", req.Key, strings.ToLower(string(req.Operator)))\n\t\tif len(req.Values) \u003e 0 {\n\t\t\texprStr = fmt.Sprintf(\"%s [%s]\", exprStr, strings.Join(req.Values, \", \"))\n\t\t}\n\t\tw.Write(LEVEL_0, \"%s\\n\", exprStr)\n\t}\n}","line":{"from":1506,"to":1525}} {"id":100032432,"name":"describePersistentVolume","signature":"func describePersistentVolume(pv *corev1.PersistentVolume, events *corev1.EventList) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describePersistentVolume(pv *corev1.PersistentVolume, events *corev1.EventList) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", pv.Name)\n\t\tprintLabelsMultiline(w, \"Labels\", pv.ObjectMeta.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", pv.ObjectMeta.Annotations)\n\t\tw.Write(LEVEL_0, \"Finalizers:\\t%v\\n\", pv.ObjectMeta.Finalizers)\n\t\tw.Write(LEVEL_0, \"StorageClass:\\t%s\\n\", storageutil.GetPersistentVolumeClass(pv))\n\t\tif pv.ObjectMeta.DeletionTimestamp != nil {\n\t\t\tw.Write(LEVEL_0, \"Status:\\tTerminating (lasts %s)\\n\", translateTimestampSince(*pv.ObjectMeta.DeletionTimestamp))\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"Status:\\t%v\\n\", pv.Status.Phase)\n\t\t}\n\t\tif pv.Spec.ClaimRef != nil {\n\t\t\tw.Write(LEVEL_0, \"Claim:\\t%s\\n\", pv.Spec.ClaimRef.Namespace+\"/\"+pv.Spec.ClaimRef.Name)\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"Claim:\\t%s\\n\", \"\")\n\t\t}\n\t\tw.Write(LEVEL_0, \"Reclaim Policy:\\t%v\\n\", pv.Spec.PersistentVolumeReclaimPolicy)\n\t\tw.Write(LEVEL_0, \"Access Modes:\\t%s\\n\", storageutil.GetAccessModesAsString(pv.Spec.AccessModes))\n\t\tif pv.Spec.VolumeMode != nil {\n\t\t\tw.Write(LEVEL_0, \"VolumeMode:\\t%v\\n\", *pv.Spec.VolumeMode)\n\t\t}\n\t\tstorage := pv.Spec.Capacity[corev1.ResourceStorage]\n\t\tw.Write(LEVEL_0, \"Capacity:\\t%s\\n\", storage.String())\n\t\tprintVolumeNodeAffinity(w, pv.Spec.NodeAffinity)\n\t\tw.Write(LEVEL_0, \"Message:\\t%s\\n\", pv.Status.Message)\n\t\tw.Write(LEVEL_0, \"Source:\\n\")\n\n\t\tswitch {\n\t\tcase pv.Spec.HostPath != nil:\n\t\t\tprintHostPathVolumeSource(pv.Spec.HostPath, w)\n\t\tcase pv.Spec.GCEPersistentDisk != nil:\n\t\t\tprintGCEPersistentDiskVolumeSource(pv.Spec.GCEPersistentDisk, w)\n\t\tcase pv.Spec.AWSElasticBlockStore != nil:\n\t\t\tprintAWSElasticBlockStoreVolumeSource(pv.Spec.AWSElasticBlockStore, w)\n\t\tcase pv.Spec.NFS != nil:\n\t\t\tprintNFSVolumeSource(pv.Spec.NFS, w)\n\t\tcase pv.Spec.ISCSI != nil:\n\t\t\tprintISCSIPersistentVolumeSource(pv.Spec.ISCSI, w)\n\t\tcase pv.Spec.Glusterfs != nil:\n\t\t\tprintGlusterfsPersistentVolumeSource(pv.Spec.Glusterfs, w)\n\t\tcase pv.Spec.RBD != nil:\n\t\t\tprintRBDPersistentVolumeSource(pv.Spec.RBD, w)\n\t\tcase pv.Spec.Quobyte != nil:\n\t\t\tprintQuobyteVolumeSource(pv.Spec.Quobyte, w)\n\t\tcase pv.Spec.VsphereVolume != nil:\n\t\t\tprintVsphereVolumeSource(pv.Spec.VsphereVolume, w)\n\t\tcase pv.Spec.Cinder != nil:\n\t\t\tprintCinderPersistentVolumeSource(pv.Spec.Cinder, w)\n\t\tcase pv.Spec.AzureDisk != nil:\n\t\t\tprintAzureDiskVolumeSource(pv.Spec.AzureDisk, w)\n\t\tcase pv.Spec.PhotonPersistentDisk != nil:\n\t\t\tprintPhotonPersistentDiskVolumeSource(pv.Spec.PhotonPersistentDisk, w)\n\t\tcase pv.Spec.PortworxVolume != nil:\n\t\t\tprintPortworxVolumeSource(pv.Spec.PortworxVolume, w)\n\t\tcase pv.Spec.ScaleIO != nil:\n\t\t\tprintScaleIOPersistentVolumeSource(pv.Spec.ScaleIO, w)\n\t\tcase pv.Spec.Local != nil:\n\t\t\tprintLocalVolumeSource(pv.Spec.Local, w)\n\t\tcase pv.Spec.CephFS != nil:\n\t\t\tprintCephFSPersistentVolumeSource(pv.Spec.CephFS, w)\n\t\tcase pv.Spec.StorageOS != nil:\n\t\t\tprintStorageOSPersistentVolumeSource(pv.Spec.StorageOS, w)\n\t\tcase pv.Spec.FC != nil:\n\t\t\tprintFCVolumeSource(pv.Spec.FC, w)\n\t\tcase pv.Spec.AzureFile != nil:\n\t\t\tprintAzureFilePersistentVolumeSource(pv.Spec.AzureFile, w)\n\t\tcase pv.Spec.FlexVolume != nil:\n\t\t\tprintFlexPersistentVolumeSource(pv.Spec.FlexVolume, w)\n\t\tcase pv.Spec.Flocker != nil:\n\t\t\tprintFlockerVolumeSource(pv.Spec.Flocker, w)\n\t\tcase pv.Spec.CSI != nil:\n\t\t\tprintCSIPersistentVolumeSource(pv.Spec.CSI, w)\n\t\tdefault:\n\t\t\tw.Write(LEVEL_1, \"\u003cunknown\u003e\\n\")\n\t\t}\n\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\n\t\treturn nil\n\t})\n}","line":{"from":1527,"to":1611}} {"id":100032433,"name":"Describe","signature":"func (d *PersistentVolumeClaimDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (d *PersistentVolumeClaimDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tc := d.CoreV1().PersistentVolumeClaims(namespace)\n\n\tpvc, err := c.Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tpc := d.CoreV1().Pods(namespace)\n\n\tpods, err := getPodsForPVC(pc, pvc.Name, describerSettings)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tevents, _ := searchEvents(d.CoreV1(), pvc, describerSettings.ChunkSize)\n\n\treturn describePersistentVolumeClaim(pvc, events, pods)\n}","line":{"from":1617,"to":1635}} {"id":100032434,"name":"getPodsForPVC","signature":"func getPodsForPVC(c corev1client.PodInterface, pvcName string, settings DescriberSettings) ([]corev1.Pod, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func getPodsForPVC(c corev1client.PodInterface, pvcName string, settings DescriberSettings) ([]corev1.Pod, error) {\n\tnsPods, err := getPodsInChunks(c, metav1.ListOptions{Limit: settings.ChunkSize})\n\tif err != nil {\n\t\treturn []corev1.Pod{}, err\n\t}\n\n\tvar pods []corev1.Pod\n\n\tfor _, pod := range nsPods.Items {\n\t\tfor _, volume := range pod.Spec.Volumes {\n\t\t\tif volume.VolumeSource.PersistentVolumeClaim != nil \u0026\u0026 volume.VolumeSource.PersistentVolumeClaim.ClaimName == pvcName {\n\t\t\t\tpods = append(pods, pod)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn pods, nil\n}","line":{"from":1637,"to":1654}} {"id":100032435,"name":"describePersistentVolumeClaim","signature":"func describePersistentVolumeClaim(pvc *corev1.PersistentVolumeClaim, events *corev1.EventList, pods []corev1.Pod) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describePersistentVolumeClaim(pvc *corev1.PersistentVolumeClaim, events *corev1.EventList, pods []corev1.Pod) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tprintPersistentVolumeClaim(w, pvc, true)\n\t\tprintPodsMultiline(w, \"Used By\", pods)\n\n\t\tif len(pvc.Status.Conditions) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"Conditions:\\n\")\n\t\t\tw.Write(LEVEL_1, \"Type\\tStatus\\tLastProbeTime\\tLastTransitionTime\\tReason\\tMessage\\n\")\n\t\t\tw.Write(LEVEL_1, \"----\\t------\\t-----------------\\t------------------\\t------\\t-------\\n\")\n\t\t\tfor _, c := range pvc.Status.Conditions {\n\t\t\t\tw.Write(LEVEL_1, \"%v \\t%v \\t%s \\t%s \\t%v \\t%v\\n\",\n\t\t\t\t\tc.Type,\n\t\t\t\t\tc.Status,\n\t\t\t\t\tc.LastProbeTime.Time.Format(time.RFC1123Z),\n\t\t\t\t\tc.LastTransitionTime.Time.Format(time.RFC1123Z),\n\t\t\t\t\tc.Reason,\n\t\t\t\t\tc.Message)\n\t\t\t}\n\t\t}\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\n\t\treturn nil\n\t})\n}","line":{"from":1656,"to":1682}} {"id":100032436,"name":"printPersistentVolumeClaim","signature":"func printPersistentVolumeClaim(w PrefixWriter, pvc *corev1.PersistentVolumeClaim, isFullPVC bool)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// printPersistentVolumeClaim is used for both PVCs and PersistentVolumeClaimTemplate. For the latter,\n// we need to skip some fields which have no meaning.\nfunc printPersistentVolumeClaim(w PrefixWriter, pvc *corev1.PersistentVolumeClaim, isFullPVC bool) {\n\tif isFullPVC {\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", pvc.Name)\n\t\tw.Write(LEVEL_0, \"Namespace:\\t%s\\n\", pvc.Namespace)\n\t}\n\tw.Write(LEVEL_0, \"StorageClass:\\t%s\\n\", storageutil.GetPersistentVolumeClaimClass(pvc))\n\tif isFullPVC {\n\t\tif pvc.ObjectMeta.DeletionTimestamp != nil {\n\t\t\tw.Write(LEVEL_0, \"Status:\\tTerminating (lasts %s)\\n\", translateTimestampSince(*pvc.ObjectMeta.DeletionTimestamp))\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"Status:\\t%v\\n\", pvc.Status.Phase)\n\t\t}\n\t}\n\tw.Write(LEVEL_0, \"Volume:\\t%s\\n\", pvc.Spec.VolumeName)\n\tprintLabelsMultiline(w, \"Labels\", pvc.Labels)\n\tprintAnnotationsMultiline(w, \"Annotations\", pvc.Annotations)\n\tif isFullPVC {\n\t\tw.Write(LEVEL_0, \"Finalizers:\\t%v\\n\", pvc.ObjectMeta.Finalizers)\n\t}\n\tstorage := pvc.Spec.Resources.Requests[corev1.ResourceStorage]\n\tcapacity := \"\"\n\taccessModes := \"\"\n\tif pvc.Spec.VolumeName != \"\" {\n\t\taccessModes = storageutil.GetAccessModesAsString(pvc.Status.AccessModes)\n\t\tstorage = pvc.Status.Capacity[corev1.ResourceStorage]\n\t\tcapacity = storage.String()\n\t}\n\tw.Write(LEVEL_0, \"Capacity:\\t%s\\n\", capacity)\n\tw.Write(LEVEL_0, \"Access Modes:\\t%s\\n\", accessModes)\n\tif pvc.Spec.VolumeMode != nil {\n\t\tw.Write(LEVEL_0, \"VolumeMode:\\t%v\\n\", *pvc.Spec.VolumeMode)\n\t}\n\tif pvc.Spec.DataSource != nil {\n\t\tw.Write(LEVEL_0, \"DataSource:\\n\")\n\t\tif pvc.Spec.DataSource.APIGroup != nil {\n\t\t\tw.Write(LEVEL_1, \"APIGroup:\\t%v\\n\", *pvc.Spec.DataSource.APIGroup)\n\t\t}\n\t\tw.Write(LEVEL_1, \"Kind:\\t%v\\n\", pvc.Spec.DataSource.Kind)\n\t\tw.Write(LEVEL_1, \"Name:\\t%v\\n\", pvc.Spec.DataSource.Name)\n\t}\n}","line":{"from":1684,"to":1726}} {"id":100032437,"name":"describeContainers","signature":"func describeContainers(label string, containers []corev1.Container, containerStatuses []corev1.ContainerStatus,","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeContainers(label string, containers []corev1.Container, containerStatuses []corev1.ContainerStatus,\n\tresolverFn EnvVarResolverFunc, w PrefixWriter, space string) {\n\tstatuses := map[string]corev1.ContainerStatus{}\n\tfor _, status := range containerStatuses {\n\t\tstatuses[status.Name] = status\n\t}\n\n\tdescribeContainersLabel(containers, label, space, w)\n\n\tfor _, container := range containers {\n\t\tstatus, ok := statuses[container.Name]\n\t\tdescribeContainerBasicInfo(container, status, ok, space, w)\n\t\tdescribeContainerCommand(container, w)\n\t\tif ok {\n\t\t\tdescribeContainerState(status, w)\n\t\t}\n\t\tdescribeContainerResource(container, w)\n\t\tdescribeContainerProbe(container, w)\n\t\tif len(container.EnvFrom) \u003e 0 {\n\t\t\tdescribeContainerEnvFrom(container, resolverFn, w)\n\t\t}\n\t\tdescribeContainerEnvVars(container, resolverFn, w)\n\t\tdescribeContainerVolumes(container, w)\n\t}\n}","line":{"from":1728,"to":1752}} {"id":100032438,"name":"describeContainersLabel","signature":"func describeContainersLabel(containers []corev1.Container, label, space string, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeContainersLabel(containers []corev1.Container, label, space string, w PrefixWriter) {\n\tnone := \"\"\n\tif len(containers) == 0 {\n\t\tnone = \" \u003cnone\u003e\"\n\t}\n\tw.Write(LEVEL_0, \"%s%s:%s\\n\", space, label, none)\n}","line":{"from":1754,"to":1760}} {"id":100032439,"name":"describeContainerBasicInfo","signature":"func describeContainerBasicInfo(container corev1.Container, status corev1.ContainerStatus, ok bool, space string, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeContainerBasicInfo(container corev1.Container, status corev1.ContainerStatus, ok bool, space string, w PrefixWriter) {\n\tnameIndent := \"\"\n\tif len(space) \u003e 0 {\n\t\tnameIndent = \" \"\n\t}\n\tw.Write(LEVEL_1, \"%s%v:\\n\", nameIndent, container.Name)\n\tif ok {\n\t\tw.Write(LEVEL_2, \"Container ID:\\t%s\\n\", status.ContainerID)\n\t}\n\tw.Write(LEVEL_2, \"Image:\\t%s\\n\", container.Image)\n\tif ok {\n\t\tw.Write(LEVEL_2, \"Image ID:\\t%s\\n\", status.ImageID)\n\t}\n\tportString := describeContainerPorts(container.Ports)\n\tif strings.Contains(portString, \",\") {\n\t\tw.Write(LEVEL_2, \"Ports:\\t%s\\n\", portString)\n\t} else {\n\t\tw.Write(LEVEL_2, \"Port:\\t%s\\n\", stringOrNone(portString))\n\t}\n\thostPortString := describeContainerHostPorts(container.Ports)\n\tif strings.Contains(hostPortString, \",\") {\n\t\tw.Write(LEVEL_2, \"Host Ports:\\t%s\\n\", hostPortString)\n\t} else {\n\t\tw.Write(LEVEL_2, \"Host Port:\\t%s\\n\", stringOrNone(hostPortString))\n\t}\n\tif container.SecurityContext != nil \u0026\u0026 container.SecurityContext.SeccompProfile != nil {\n\t\tw.Write(LEVEL_2, \"SeccompProfile:\\t%s\\n\", container.SecurityContext.SeccompProfile.Type)\n\t\tif container.SecurityContext.SeccompProfile.Type == corev1.SeccompProfileTypeLocalhost {\n\t\t\tw.Write(LEVEL_3, \"LocalhostProfile:\\t%s\\n\", *container.SecurityContext.SeccompProfile.LocalhostProfile)\n\t\t}\n\t}\n}","line":{"from":1762,"to":1793}} {"id":100032440,"name":"describeContainerPorts","signature":"func describeContainerPorts(cPorts []corev1.ContainerPort) string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeContainerPorts(cPorts []corev1.ContainerPort) string {\n\tports := make([]string, 0, len(cPorts))\n\tfor _, cPort := range cPorts {\n\t\tports = append(ports, fmt.Sprintf(\"%d/%s\", cPort.ContainerPort, cPort.Protocol))\n\t}\n\treturn strings.Join(ports, \", \")\n}","line":{"from":1795,"to":1801}} {"id":100032441,"name":"describeContainerHostPorts","signature":"func describeContainerHostPorts(cPorts []corev1.ContainerPort) string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeContainerHostPorts(cPorts []corev1.ContainerPort) string {\n\tports := make([]string, 0, len(cPorts))\n\tfor _, cPort := range cPorts {\n\t\tports = append(ports, fmt.Sprintf(\"%d/%s\", cPort.HostPort, cPort.Protocol))\n\t}\n\treturn strings.Join(ports, \", \")\n}","line":{"from":1803,"to":1809}} {"id":100032442,"name":"describeContainerCommand","signature":"func describeContainerCommand(container corev1.Container, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeContainerCommand(container corev1.Container, w PrefixWriter) {\n\tif len(container.Command) \u003e 0 {\n\t\tw.Write(LEVEL_2, \"Command:\\n\")\n\t\tfor _, c := range container.Command {\n\t\t\tfor _, s := range strings.Split(c, \"\\n\") {\n\t\t\t\tw.Write(LEVEL_3, \"%s\\n\", s)\n\t\t\t}\n\t\t}\n\t}\n\tif len(container.Args) \u003e 0 {\n\t\tw.Write(LEVEL_2, \"Args:\\n\")\n\t\tfor _, arg := range container.Args {\n\t\t\tfor _, s := range strings.Split(arg, \"\\n\") {\n\t\t\t\tw.Write(LEVEL_3, \"%s\\n\", s)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":1811,"to":1828}} {"id":100032443,"name":"describeContainerResource","signature":"func describeContainerResource(container corev1.Container, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeContainerResource(container corev1.Container, w PrefixWriter) {\n\tresources := container.Resources\n\tif len(resources.Limits) \u003e 0 {\n\t\tw.Write(LEVEL_2, \"Limits:\\n\")\n\t}\n\tfor _, name := range SortedResourceNames(resources.Limits) {\n\t\tquantity := resources.Limits[name]\n\t\tw.Write(LEVEL_3, \"%s:\\t%s\\n\", name, quantity.String())\n\t}\n\n\tif len(resources.Requests) \u003e 0 {\n\t\tw.Write(LEVEL_2, \"Requests:\\n\")\n\t}\n\tfor _, name := range SortedResourceNames(resources.Requests) {\n\t\tquantity := resources.Requests[name]\n\t\tw.Write(LEVEL_3, \"%s:\\t%s\\n\", name, quantity.String())\n\t}\n}","line":{"from":1830,"to":1847}} {"id":100032444,"name":"describeContainerState","signature":"func describeContainerState(status corev1.ContainerStatus, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeContainerState(status corev1.ContainerStatus, w PrefixWriter) {\n\tdescribeStatus(\"State\", status.State, w)\n\tif status.LastTerminationState.Terminated != nil {\n\t\tdescribeStatus(\"Last State\", status.LastTerminationState, w)\n\t}\n\tw.Write(LEVEL_2, \"Ready:\\t%v\\n\", printBool(status.Ready))\n\tw.Write(LEVEL_2, \"Restart Count:\\t%d\\n\", status.RestartCount)\n}","line":{"from":1849,"to":1856}} {"id":100032445,"name":"describeContainerProbe","signature":"func describeContainerProbe(container corev1.Container, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeContainerProbe(container corev1.Container, w PrefixWriter) {\n\tif container.LivenessProbe != nil {\n\t\tprobe := DescribeProbe(container.LivenessProbe)\n\t\tw.Write(LEVEL_2, \"Liveness:\\t%s\\n\", probe)\n\t}\n\tif container.ReadinessProbe != nil {\n\t\tprobe := DescribeProbe(container.ReadinessProbe)\n\t\tw.Write(LEVEL_2, \"Readiness:\\t%s\\n\", probe)\n\t}\n\tif container.StartupProbe != nil {\n\t\tprobe := DescribeProbe(container.StartupProbe)\n\t\tw.Write(LEVEL_2, \"Startup:\\t%s\\n\", probe)\n\t}\n}","line":{"from":1858,"to":1871}} {"id":100032446,"name":"describeContainerVolumes","signature":"func describeContainerVolumes(container corev1.Container, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeContainerVolumes(container corev1.Container, w PrefixWriter) {\n\t// Show volumeMounts\n\tnone := \"\"\n\tif len(container.VolumeMounts) == 0 {\n\t\tnone = \"\\t\u003cnone\u003e\"\n\t}\n\tw.Write(LEVEL_2, \"Mounts:%s\\n\", none)\n\tsort.Sort(SortableVolumeMounts(container.VolumeMounts))\n\tfor _, mount := range container.VolumeMounts {\n\t\tflags := []string{}\n\t\tif mount.ReadOnly {\n\t\t\tflags = append(flags, \"ro\")\n\t\t} else {\n\t\t\tflags = append(flags, \"rw\")\n\t\t}\n\t\tif len(mount.SubPath) \u003e 0 {\n\t\t\tflags = append(flags, fmt.Sprintf(\"path=%q\", mount.SubPath))\n\t\t}\n\t\tw.Write(LEVEL_3, \"%s from %s (%s)\\n\", mount.MountPath, mount.Name, strings.Join(flags, \",\"))\n\t}\n\t// Show volumeDevices if exists\n\tif len(container.VolumeDevices) \u003e 0 {\n\t\tw.Write(LEVEL_2, \"Devices:%s\\n\", none)\n\t\tsort.Sort(SortableVolumeDevices(container.VolumeDevices))\n\t\tfor _, device := range container.VolumeDevices {\n\t\t\tw.Write(LEVEL_3, \"%s from %s\\n\", device.DevicePath, device.Name)\n\t\t}\n\t}\n}","line":{"from":1873,"to":1901}} {"id":100032447,"name":"describeContainerEnvVars","signature":"func describeContainerEnvVars(container corev1.Container, resolverFn EnvVarResolverFunc, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeContainerEnvVars(container corev1.Container, resolverFn EnvVarResolverFunc, w PrefixWriter) {\n\tnone := \"\"\n\tif len(container.Env) == 0 {\n\t\tnone = \"\\t\u003cnone\u003e\"\n\t}\n\tw.Write(LEVEL_2, \"Environment:%s\\n\", none)\n\n\tfor _, e := range container.Env {\n\t\tif e.ValueFrom == nil {\n\t\t\tfor i, s := range strings.Split(e.Value, \"\\n\") {\n\t\t\t\tif i == 0 {\n\t\t\t\t\tw.Write(LEVEL_3, \"%s:\\t%s\\n\", e.Name, s)\n\t\t\t\t} else {\n\t\t\t\t\tw.Write(LEVEL_3, \"\\t%s\\n\", s)\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch {\n\t\tcase e.ValueFrom.FieldRef != nil:\n\t\t\tvar valueFrom string\n\t\t\tif resolverFn != nil {\n\t\t\t\tvalueFrom = resolverFn(e)\n\t\t\t}\n\t\t\tw.Write(LEVEL_3, \"%s:\\t%s (%s:%s)\\n\", e.Name, valueFrom, e.ValueFrom.FieldRef.APIVersion, e.ValueFrom.FieldRef.FieldPath)\n\t\tcase e.ValueFrom.ResourceFieldRef != nil:\n\t\t\tvalueFrom, err := resourcehelper.ExtractContainerResourceValue(e.ValueFrom.ResourceFieldRef, \u0026container)\n\t\t\tif err != nil {\n\t\t\t\tvalueFrom = \"\"\n\t\t\t}\n\t\t\tresource := e.ValueFrom.ResourceFieldRef.Resource\n\t\t\tif valueFrom == \"0\" \u0026\u0026 (resource == \"limits.cpu\" || resource == \"limits.memory\") {\n\t\t\t\tvalueFrom = \"node allocatable\"\n\t\t\t}\n\t\t\tw.Write(LEVEL_3, \"%s:\\t%s (%s)\\n\", e.Name, valueFrom, resource)\n\t\tcase e.ValueFrom.SecretKeyRef != nil:\n\t\t\toptional := e.ValueFrom.SecretKeyRef.Optional != nil \u0026\u0026 *e.ValueFrom.SecretKeyRef.Optional\n\t\t\tw.Write(LEVEL_3, \"%s:\\t\u003cset to the key '%s' in secret '%s'\u003e\\tOptional: %t\\n\", e.Name, e.ValueFrom.SecretKeyRef.Key, e.ValueFrom.SecretKeyRef.Name, optional)\n\t\tcase e.ValueFrom.ConfigMapKeyRef != nil:\n\t\t\toptional := e.ValueFrom.ConfigMapKeyRef.Optional != nil \u0026\u0026 *e.ValueFrom.ConfigMapKeyRef.Optional\n\t\t\tw.Write(LEVEL_3, \"%s:\\t\u003cset to the key '%s' of config map '%s'\u003e\\tOptional: %t\\n\", e.Name, e.ValueFrom.ConfigMapKeyRef.Key, e.ValueFrom.ConfigMapKeyRef.Name, optional)\n\t\t}\n\t}\n}","line":{"from":1903,"to":1947}} {"id":100032448,"name":"describeContainerEnvFrom","signature":"func describeContainerEnvFrom(container corev1.Container, resolverFn EnvVarResolverFunc, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeContainerEnvFrom(container corev1.Container, resolverFn EnvVarResolverFunc, w PrefixWriter) {\n\tnone := \"\"\n\tif len(container.EnvFrom) == 0 {\n\t\tnone = \"\\t\u003cnone\u003e\"\n\t}\n\tw.Write(LEVEL_2, \"Environment Variables from:%s\\n\", none)\n\n\tfor _, e := range container.EnvFrom {\n\t\tfrom := \"\"\n\t\tname := \"\"\n\t\toptional := false\n\t\tif e.ConfigMapRef != nil {\n\t\t\tfrom = \"ConfigMap\"\n\t\t\tname = e.ConfigMapRef.Name\n\t\t\toptional = e.ConfigMapRef.Optional != nil \u0026\u0026 *e.ConfigMapRef.Optional\n\t\t} else if e.SecretRef != nil {\n\t\t\tfrom = \"Secret\"\n\t\t\tname = e.SecretRef.Name\n\t\t\toptional = e.SecretRef.Optional != nil \u0026\u0026 *e.SecretRef.Optional\n\t\t}\n\t\tif len(e.Prefix) == 0 {\n\t\t\tw.Write(LEVEL_3, \"%s\\t%s\\tOptional: %t\\n\", name, from, optional)\n\t\t} else {\n\t\t\tw.Write(LEVEL_3, \"%s\\t%s with prefix '%s'\\tOptional: %t\\n\", name, from, e.Prefix, optional)\n\t\t}\n\t}\n}","line":{"from":1949,"to":1975}} {"id":100032449,"name":"DescribeProbe","signature":"func DescribeProbe(probe *corev1.Probe) string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// DescribeProbe is exported for consumers in other API groups that have probes\nfunc DescribeProbe(probe *corev1.Probe) string {\n\tattrs := fmt.Sprintf(\"delay=%ds timeout=%ds period=%ds #success=%d #failure=%d\", probe.InitialDelaySeconds, probe.TimeoutSeconds, probe.PeriodSeconds, probe.SuccessThreshold, probe.FailureThreshold)\n\tswitch {\n\tcase probe.Exec != nil:\n\t\treturn fmt.Sprintf(\"exec %v %s\", probe.Exec.Command, attrs)\n\tcase probe.HTTPGet != nil:\n\t\turl := \u0026url.URL{}\n\t\turl.Scheme = strings.ToLower(string(probe.HTTPGet.Scheme))\n\t\tif len(probe.HTTPGet.Port.String()) \u003e 0 {\n\t\t\turl.Host = net.JoinHostPort(probe.HTTPGet.Host, probe.HTTPGet.Port.String())\n\t\t} else {\n\t\t\turl.Host = probe.HTTPGet.Host\n\t\t}\n\t\turl.Path = probe.HTTPGet.Path\n\t\treturn fmt.Sprintf(\"http-get %s %s\", url.String(), attrs)\n\tcase probe.TCPSocket != nil:\n\t\treturn fmt.Sprintf(\"tcp-socket %s:%s %s\", probe.TCPSocket.Host, probe.TCPSocket.Port.String(), attrs)\n\n\tcase probe.GRPC != nil:\n\t\treturn fmt.Sprintf(\"grpc \u003cpod\u003e:%d %s %s\", probe.GRPC.Port, *(probe.GRPC.Service), attrs)\n\t}\n\treturn fmt.Sprintf(\"unknown %s\", attrs)\n}","line":{"from":1977,"to":2000}} {"id":100032450,"name":"EnvValueRetriever","signature":"func EnvValueRetriever(pod *corev1.Pod) EnvVarResolverFunc","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// EnvValueFrom is exported for use by describers in other packages\nfunc EnvValueRetriever(pod *corev1.Pod) EnvVarResolverFunc {\n\treturn func(e corev1.EnvVar) string {\n\t\tgv, err := schema.ParseGroupVersion(e.ValueFrom.FieldRef.APIVersion)\n\t\tif err != nil {\n\t\t\treturn \"\"\n\t\t}\n\t\tgvk := gv.WithKind(\"Pod\")\n\t\tinternalFieldPath, _, err := scheme.Scheme.ConvertFieldLabel(gvk, e.ValueFrom.FieldRef.FieldPath, \"\")\n\t\tif err != nil {\n\t\t\treturn \"\" // pod validation should catch this on create\n\t\t}\n\n\t\tvalueFrom, err := fieldpath.ExtractFieldPathAsString(pod, internalFieldPath)\n\t\tif err != nil {\n\t\t\treturn \"\" // pod validation should catch this on create\n\t\t}\n\n\t\treturn valueFrom\n\t}\n}","line":{"from":2004,"to":2024}} {"id":100032451,"name":"describeStatus","signature":"func describeStatus(stateName string, state corev1.ContainerState, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeStatus(stateName string, state corev1.ContainerState, w PrefixWriter) {\n\tswitch {\n\tcase state.Running != nil:\n\t\tw.Write(LEVEL_2, \"%s:\\tRunning\\n\", stateName)\n\t\tw.Write(LEVEL_3, \"Started:\\t%v\\n\", state.Running.StartedAt.Time.Format(time.RFC1123Z))\n\tcase state.Waiting != nil:\n\t\tw.Write(LEVEL_2, \"%s:\\tWaiting\\n\", stateName)\n\t\tif state.Waiting.Reason != \"\" {\n\t\t\tw.Write(LEVEL_3, \"Reason:\\t%s\\n\", state.Waiting.Reason)\n\t\t}\n\tcase state.Terminated != nil:\n\t\tw.Write(LEVEL_2, \"%s:\\tTerminated\\n\", stateName)\n\t\tif state.Terminated.Reason != \"\" {\n\t\t\tw.Write(LEVEL_3, \"Reason:\\t%s\\n\", state.Terminated.Reason)\n\t\t}\n\t\tif state.Terminated.Message != \"\" {\n\t\t\tw.Write(LEVEL_3, \"Message:\\t%s\\n\", state.Terminated.Message)\n\t\t}\n\t\tw.Write(LEVEL_3, \"Exit Code:\\t%d\\n\", state.Terminated.ExitCode)\n\t\tif state.Terminated.Signal \u003e 0 {\n\t\t\tw.Write(LEVEL_3, \"Signal:\\t%d\\n\", state.Terminated.Signal)\n\t\t}\n\t\tw.Write(LEVEL_3, \"Started:\\t%s\\n\", state.Terminated.StartedAt.Time.Format(time.RFC1123Z))\n\t\tw.Write(LEVEL_3, \"Finished:\\t%s\\n\", state.Terminated.FinishedAt.Time.Format(time.RFC1123Z))\n\tdefault:\n\t\tw.Write(LEVEL_2, \"%s:\\tWaiting\\n\", stateName)\n\t}\n}","line":{"from":2026,"to":2053}} {"id":100032452,"name":"describeVolumeClaimTemplates","signature":"func describeVolumeClaimTemplates(templates []corev1.PersistentVolumeClaim, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeVolumeClaimTemplates(templates []corev1.PersistentVolumeClaim, w PrefixWriter) {\n\tif len(templates) == 0 {\n\t\tw.Write(LEVEL_0, \"Volume Claims:\\t\u003cnone\u003e\\n\")\n\t\treturn\n\t}\n\tw.Write(LEVEL_0, \"Volume Claims:\\n\")\n\tfor _, pvc := range templates {\n\t\tw.Write(LEVEL_1, \"Name:\\t%s\\n\", pvc.Name)\n\t\tw.Write(LEVEL_1, \"StorageClass:\\t%s\\n\", storageutil.GetPersistentVolumeClaimClass(\u0026pvc))\n\t\tprintLabelsMultilineWithIndent(w, \" \", \"Labels\", \"\\t\", pvc.Labels, sets.NewString())\n\t\tprintLabelsMultilineWithIndent(w, \" \", \"Annotations\", \"\\t\", pvc.Annotations, sets.NewString())\n\t\tif capacity, ok := pvc.Spec.Resources.Requests[corev1.ResourceStorage]; ok {\n\t\t\tw.Write(LEVEL_1, \"Capacity:\\t%s\\n\", capacity.String())\n\t\t} else {\n\t\t\tw.Write(LEVEL_1, \"Capacity:\\t%s\\n\", \"\u003cdefault\u003e\")\n\t\t}\n\t\tw.Write(LEVEL_1, \"Access Modes:\\t%s\\n\", pvc.Spec.AccessModes)\n\t}\n}","line":{"from":2055,"to":2073}} {"id":100032453,"name":"printBoolPtr","signature":"func printBoolPtr(value *bool) string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printBoolPtr(value *bool) string {\n\tif value != nil {\n\t\treturn printBool(*value)\n\t}\n\n\treturn \"\u003cunset\u003e\"\n}","line":{"from":2075,"to":2081}} {"id":100032454,"name":"printBool","signature":"func printBool(value bool) string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printBool(value bool) string {\n\tif value {\n\t\treturn \"True\"\n\t}\n\n\treturn \"False\"\n}","line":{"from":2083,"to":2089}} {"id":100032455,"name":"Describe","signature":"func (d *ReplicationControllerDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (d *ReplicationControllerDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\trc := d.CoreV1().ReplicationControllers(namespace)\n\tpc := d.CoreV1().Pods(namespace)\n\n\tcontroller, err := rc.Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tselector := labels.SelectorFromSet(controller.Spec.Selector)\n\trunning, waiting, succeeded, failed, err := getPodStatusForController(pc, selector, controller.UID, describerSettings)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar events *corev1.EventList\n\tif describerSettings.ShowEvents {\n\t\tevents, _ = searchEvents(d.CoreV1(), controller, describerSettings.ChunkSize)\n\t}\n\n\treturn describeReplicationController(controller, events, running, waiting, succeeded, failed)\n}","line":{"from":2097,"to":2118}} {"id":100032456,"name":"describeReplicationController","signature":"func describeReplicationController(controller *corev1.ReplicationController, events *corev1.EventList, running, waiting, succeeded, failed int) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeReplicationController(controller *corev1.ReplicationController, events *corev1.EventList, running, waiting, succeeded, failed int) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", controller.Name)\n\t\tw.Write(LEVEL_0, \"Namespace:\\t%s\\n\", controller.Namespace)\n\t\tw.Write(LEVEL_0, \"Selector:\\t%s\\n\", labels.FormatLabels(controller.Spec.Selector))\n\t\tprintLabelsMultiline(w, \"Labels\", controller.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", controller.Annotations)\n\t\tw.Write(LEVEL_0, \"Replicas:\\t%d current / %d desired\\n\", controller.Status.Replicas, *controller.Spec.Replicas)\n\t\tw.Write(LEVEL_0, \"Pods Status:\\t%d Running / %d Waiting / %d Succeeded / %d Failed\\n\", running, waiting, succeeded, failed)\n\t\tDescribePodTemplate(controller.Spec.Template, w)\n\t\tif len(controller.Status.Conditions) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"Conditions:\\n Type\\tStatus\\tReason\\n\")\n\t\t\tw.Write(LEVEL_1, \"----\\t------\\t------\\n\")\n\t\t\tfor _, c := range controller.Status.Conditions {\n\t\t\t\tw.Write(LEVEL_1, \"%v \\t%v\\t%v\\n\", c.Type, c.Status, c.Reason)\n\t\t\t}\n\t\t}\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":2120,"to":2143}} {"id":100032457,"name":"DescribePodTemplate","signature":"func DescribePodTemplate(template *corev1.PodTemplateSpec, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func DescribePodTemplate(template *corev1.PodTemplateSpec, w PrefixWriter) {\n\tw.Write(LEVEL_0, \"Pod Template:\\n\")\n\tif template == nil {\n\t\tw.Write(LEVEL_1, \"\u003cunset\u003e\")\n\t\treturn\n\t}\n\tprintLabelsMultiline(w, \" Labels\", template.Labels)\n\tif len(template.Annotations) \u003e 0 {\n\t\tprintAnnotationsMultiline(w, \" Annotations\", template.Annotations)\n\t}\n\tif len(template.Spec.ServiceAccountName) \u003e 0 {\n\t\tw.Write(LEVEL_1, \"Service Account:\\t%s\\n\", template.Spec.ServiceAccountName)\n\t}\n\tif len(template.Spec.InitContainers) \u003e 0 {\n\t\tdescribeContainers(\"Init Containers\", template.Spec.InitContainers, nil, nil, w, \" \")\n\t}\n\tdescribeContainers(\"Containers\", template.Spec.Containers, nil, nil, w, \" \")\n\tdescribeVolumes(template.Spec.Volumes, w, \" \")\n\tdescribeTopologySpreadConstraints(template.Spec.TopologySpreadConstraints, w, \" \")\n\tif len(template.Spec.PriorityClassName) \u003e 0 {\n\t\tw.Write(LEVEL_1, \"Priority Class Name:\\t%s\\n\", template.Spec.PriorityClassName)\n\t}\n}","line":{"from":2145,"to":2167}} {"id":100032458,"name":"Describe","signature":"func (d *ReplicaSetDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (d *ReplicaSetDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\trsc := d.AppsV1().ReplicaSets(namespace)\n\tpc := d.CoreV1().Pods(namespace)\n\n\trs, err := rsc.Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tselector, err := metav1.LabelSelectorAsSelector(rs.Spec.Selector)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\trunning, waiting, succeeded, failed, getPodErr := getPodStatusForController(pc, selector, rs.UID, describerSettings)\n\n\tvar events *corev1.EventList\n\tif describerSettings.ShowEvents {\n\t\tevents, _ = searchEvents(d.CoreV1(), rs, describerSettings.ChunkSize)\n\t}\n\n\treturn describeReplicaSet(rs, events, running, waiting, succeeded, failed, getPodErr)\n}","line":{"from":2174,"to":2196}} {"id":100032459,"name":"describeReplicaSet","signature":"func describeReplicaSet(rs *appsv1.ReplicaSet, events *corev1.EventList, running, waiting, succeeded, failed int, getPodErr error) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeReplicaSet(rs *appsv1.ReplicaSet, events *corev1.EventList, running, waiting, succeeded, failed int, getPodErr error) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", rs.Name)\n\t\tw.Write(LEVEL_0, \"Namespace:\\t%s\\n\", rs.Namespace)\n\t\tw.Write(LEVEL_0, \"Selector:\\t%s\\n\", metav1.FormatLabelSelector(rs.Spec.Selector))\n\t\tprintLabelsMultiline(w, \"Labels\", rs.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", rs.Annotations)\n\t\tif controlledBy := printController(rs); len(controlledBy) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"Controlled By:\\t%s\\n\", controlledBy)\n\t\t}\n\t\tw.Write(LEVEL_0, \"Replicas:\\t%d current / %d desired\\n\", rs.Status.Replicas, *rs.Spec.Replicas)\n\t\tw.Write(LEVEL_0, \"Pods Status:\\t\")\n\t\tif getPodErr != nil {\n\t\t\tw.Write(LEVEL_0, \"error in fetching pods: %s\\n\", getPodErr)\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"%d Running / %d Waiting / %d Succeeded / %d Failed\\n\", running, waiting, succeeded, failed)\n\t\t}\n\t\tDescribePodTemplate(\u0026rs.Spec.Template, w)\n\t\tif len(rs.Status.Conditions) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"Conditions:\\n Type\\tStatus\\tReason\\n\")\n\t\t\tw.Write(LEVEL_1, \"----\\t------\\t------\\n\")\n\t\t\tfor _, c := range rs.Status.Conditions {\n\t\t\t\tw.Write(LEVEL_1, \"%v \\t%v\\t%v\\n\", c.Type, c.Status, c.Reason)\n\t\t\t}\n\t\t}\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":2198,"to":2229}} {"id":100032460,"name":"Describe","signature":"func (d *JobDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (d *JobDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tjob, err := d.BatchV1().Jobs(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar events *corev1.EventList\n\tif describerSettings.ShowEvents {\n\t\tevents, _ = searchEvents(d.CoreV1(), job, describerSettings.ChunkSize)\n\t}\n\n\treturn describeJob(job, events)\n}","line":{"from":2236,"to":2248}} {"id":100032461,"name":"describeJob","signature":"func describeJob(job *batchv1.Job, events *corev1.EventList) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeJob(job *batchv1.Job, events *corev1.EventList) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", job.Name)\n\t\tw.Write(LEVEL_0, \"Namespace:\\t%s\\n\", job.Namespace)\n\t\tif selector, err := metav1.LabelSelectorAsSelector(job.Spec.Selector); err == nil {\n\t\t\tw.Write(LEVEL_0, \"Selector:\\t%s\\n\", selector)\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"Selector:\\tFailed to get selector: %s\\n\", err)\n\t\t}\n\t\tprintLabelsMultiline(w, \"Labels\", job.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", job.Annotations)\n\t\tif controlledBy := printController(job); len(controlledBy) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"Controlled By:\\t%s\\n\", controlledBy)\n\t\t}\n\t\tif job.Spec.Parallelism != nil {\n\t\t\tw.Write(LEVEL_0, \"Parallelism:\\t%d\\n\", *job.Spec.Parallelism)\n\t\t}\n\t\tif job.Spec.Completions != nil {\n\t\t\tw.Write(LEVEL_0, \"Completions:\\t%d\\n\", *job.Spec.Completions)\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"Completions:\\t\u003cunset\u003e\\n\")\n\t\t}\n\t\tif job.Spec.CompletionMode != nil {\n\t\t\tw.Write(LEVEL_0, \"Completion Mode:\\t%s\\n\", *job.Spec.CompletionMode)\n\t\t}\n\t\tif job.Status.StartTime != nil {\n\t\t\tw.Write(LEVEL_0, \"Start Time:\\t%s\\n\", job.Status.StartTime.Time.Format(time.RFC1123Z))\n\t\t}\n\t\tif job.Status.CompletionTime != nil {\n\t\t\tw.Write(LEVEL_0, \"Completed At:\\t%s\\n\", job.Status.CompletionTime.Time.Format(time.RFC1123Z))\n\t\t}\n\t\tif job.Status.StartTime != nil \u0026\u0026 job.Status.CompletionTime != nil {\n\t\t\tw.Write(LEVEL_0, \"Duration:\\t%s\\n\", duration.HumanDuration(job.Status.CompletionTime.Sub(job.Status.StartTime.Time)))\n\t\t}\n\t\tif job.Spec.ActiveDeadlineSeconds != nil {\n\t\t\tw.Write(LEVEL_0, \"Active Deadline Seconds:\\t%ds\\n\", *job.Spec.ActiveDeadlineSeconds)\n\t\t}\n\t\tif job.Status.Ready == nil {\n\t\t\tw.Write(LEVEL_0, \"Pods Statuses:\\t%d Active / %d Succeeded / %d Failed\\n\", job.Status.Active, job.Status.Succeeded, job.Status.Failed)\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"Pods Statuses:\\t%d Active (%d Ready) / %d Succeeded / %d Failed\\n\", job.Status.Active, *job.Status.Ready, job.Status.Succeeded, job.Status.Failed)\n\t\t}\n\t\tif job.Spec.CompletionMode != nil \u0026\u0026 *job.Spec.CompletionMode == batchv1.IndexedCompletion {\n\t\t\tw.Write(LEVEL_0, \"Completed Indexes:\\t%s\\n\", capIndexesListOrNone(job.Status.CompletedIndexes, 50))\n\t\t}\n\t\tDescribePodTemplate(\u0026job.Spec.Template, w)\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":2250,"to":2302}} {"id":100032462,"name":"capIndexesListOrNone","signature":"func capIndexesListOrNone(indexes string, softLimit int) string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func capIndexesListOrNone(indexes string, softLimit int) string {\n\tif len(indexes) == 0 {\n\t\treturn \"\u003cnone\u003e\"\n\t}\n\tix := softLimit\n\tfor ; ix \u003c len(indexes); ix++ {\n\t\tif indexes[ix] == ',' {\n\t\t\tbreak\n\t\t}\n\t}\n\tif ix \u003e= len(indexes) {\n\t\treturn indexes\n\t}\n\treturn indexes[:ix+1] + \"...\"\n}","line":{"from":2304,"to":2318}} {"id":100032463,"name":"Describe","signature":"func (d *CronJobDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (d *CronJobDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tvar events *corev1.EventList\n\n\tcronJob, err := d.client.BatchV1().CronJobs(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif describerSettings.ShowEvents {\n\t\tevents, _ = searchEvents(d.client.CoreV1(), cronJob, describerSettings.ChunkSize)\n\t}\n\treturn describeCronJob(cronJob, events)\n}","line":{"from":2325,"to":2337}} {"id":100032464,"name":"describeCronJob","signature":"func describeCronJob(cronJob *batchv1.CronJob, events *corev1.EventList) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeCronJob(cronJob *batchv1.CronJob, events *corev1.EventList) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", cronJob.Name)\n\t\tw.Write(LEVEL_0, \"Namespace:\\t%s\\n\", cronJob.Namespace)\n\t\tprintLabelsMultiline(w, \"Labels\", cronJob.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", cronJob.Annotations)\n\t\tw.Write(LEVEL_0, \"Schedule:\\t%s\\n\", cronJob.Spec.Schedule)\n\t\tw.Write(LEVEL_0, \"Concurrency Policy:\\t%s\\n\", cronJob.Spec.ConcurrencyPolicy)\n\t\tw.Write(LEVEL_0, \"Suspend:\\t%s\\n\", printBoolPtr(cronJob.Spec.Suspend))\n\t\tif cronJob.Spec.SuccessfulJobsHistoryLimit != nil {\n\t\t\tw.Write(LEVEL_0, \"Successful Job History Limit:\\t%d\\n\", *cronJob.Spec.SuccessfulJobsHistoryLimit)\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"Successful Job History Limit:\\t\u003cunset\u003e\\n\")\n\t\t}\n\t\tif cronJob.Spec.FailedJobsHistoryLimit != nil {\n\t\t\tw.Write(LEVEL_0, \"Failed Job History Limit:\\t%d\\n\", *cronJob.Spec.FailedJobsHistoryLimit)\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"Failed Job History Limit:\\t\u003cunset\u003e\\n\")\n\t\t}\n\t\tif cronJob.Spec.StartingDeadlineSeconds != nil {\n\t\t\tw.Write(LEVEL_0, \"Starting Deadline Seconds:\\t%ds\\n\", *cronJob.Spec.StartingDeadlineSeconds)\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"Starting Deadline Seconds:\\t\u003cunset\u003e\\n\")\n\t\t}\n\t\tdescribeJobTemplate(cronJob.Spec.JobTemplate, w)\n\t\tif cronJob.Status.LastScheduleTime != nil {\n\t\t\tw.Write(LEVEL_0, \"Last Schedule Time:\\t%s\\n\", cronJob.Status.LastScheduleTime.Time.Format(time.RFC1123Z))\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"Last Schedule Time:\\t\u003cunset\u003e\\n\")\n\t\t}\n\t\tprintActiveJobs(w, \"Active Jobs\", cronJob.Status.Active)\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":2339,"to":2376}} {"id":100032465,"name":"describeJobTemplate","signature":"func describeJobTemplate(jobTemplate batchv1.JobTemplateSpec, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeJobTemplate(jobTemplate batchv1.JobTemplateSpec, w PrefixWriter) {\n\tif jobTemplate.Spec.Selector != nil {\n\t\tif selector, err := metav1.LabelSelectorAsSelector(jobTemplate.Spec.Selector); err == nil {\n\t\t\tw.Write(LEVEL_0, \"Selector:\\t%s\\n\", selector)\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"Selector:\\tFailed to get selector: %s\\n\", err)\n\t\t}\n\t} else {\n\t\tw.Write(LEVEL_0, \"Selector:\\t\u003cunset\u003e\\n\")\n\t}\n\tif jobTemplate.Spec.Parallelism != nil {\n\t\tw.Write(LEVEL_0, \"Parallelism:\\t%d\\n\", *jobTemplate.Spec.Parallelism)\n\t} else {\n\t\tw.Write(LEVEL_0, \"Parallelism:\\t\u003cunset\u003e\\n\")\n\t}\n\tif jobTemplate.Spec.Completions != nil {\n\t\tw.Write(LEVEL_0, \"Completions:\\t%d\\n\", *jobTemplate.Spec.Completions)\n\t} else {\n\t\tw.Write(LEVEL_0, \"Completions:\\t\u003cunset\u003e\\n\")\n\t}\n\tif jobTemplate.Spec.ActiveDeadlineSeconds != nil {\n\t\tw.Write(LEVEL_0, \"Active Deadline Seconds:\\t%ds\\n\", *jobTemplate.Spec.ActiveDeadlineSeconds)\n\t}\n\tDescribePodTemplate(\u0026jobTemplate.Spec.Template, w)\n}","line":{"from":2378,"to":2402}} {"id":100032466,"name":"printActiveJobs","signature":"func printActiveJobs(w PrefixWriter, title string, jobs []corev1.ObjectReference)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printActiveJobs(w PrefixWriter, title string, jobs []corev1.ObjectReference) {\n\tw.Write(LEVEL_0, \"%s:\\t\", title)\n\tif len(jobs) == 0 {\n\t\tw.WriteLine(\"\u003cnone\u003e\")\n\t\treturn\n\t}\n\n\tfor i, job := range jobs {\n\t\tif i != 0 {\n\t\t\tw.Write(LEVEL_0, \", \")\n\t\t}\n\t\tw.Write(LEVEL_0, \"%s\", job.Name)\n\t}\n\tw.WriteLine(\"\")\n}","line":{"from":2404,"to":2418}} {"id":100032467,"name":"Describe","signature":"func (d *DaemonSetDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (d *DaemonSetDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tdc := d.AppsV1().DaemonSets(namespace)\n\tpc := d.CoreV1().Pods(namespace)\n\n\tdaemon, err := dc.Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tselector, err := metav1.LabelSelectorAsSelector(daemon.Spec.Selector)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\trunning, waiting, succeeded, failed, err := getPodStatusForController(pc, selector, daemon.UID, describerSettings)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar events *corev1.EventList\n\tif describerSettings.ShowEvents {\n\t\tevents, _ = searchEvents(d.CoreV1(), daemon, describerSettings.ChunkSize)\n\t}\n\n\treturn describeDaemonSet(daemon, events, running, waiting, succeeded, failed)\n}","line":{"from":2425,"to":2449}} {"id":100032468,"name":"describeDaemonSet","signature":"func describeDaemonSet(daemon *appsv1.DaemonSet, events *corev1.EventList, running, waiting, succeeded, failed int) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeDaemonSet(daemon *appsv1.DaemonSet, events *corev1.EventList, running, waiting, succeeded, failed int) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", daemon.Name)\n\t\tselector, err := metav1.LabelSelectorAsSelector(daemon.Spec.Selector)\n\t\tif err != nil {\n\t\t\t// this shouldn't happen if LabelSelector passed validation\n\t\t\treturn err\n\t\t}\n\t\tw.Write(LEVEL_0, \"Selector:\\t%s\\n\", selector)\n\t\tw.Write(LEVEL_0, \"Node-Selector:\\t%s\\n\", labels.FormatLabels(daemon.Spec.Template.Spec.NodeSelector))\n\t\tprintLabelsMultiline(w, \"Labels\", daemon.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", daemon.Annotations)\n\t\tw.Write(LEVEL_0, \"Desired Number of Nodes Scheduled: %d\\n\", daemon.Status.DesiredNumberScheduled)\n\t\tw.Write(LEVEL_0, \"Current Number of Nodes Scheduled: %d\\n\", daemon.Status.CurrentNumberScheduled)\n\t\tw.Write(LEVEL_0, \"Number of Nodes Scheduled with Up-to-date Pods: %d\\n\", daemon.Status.UpdatedNumberScheduled)\n\t\tw.Write(LEVEL_0, \"Number of Nodes Scheduled with Available Pods: %d\\n\", daemon.Status.NumberAvailable)\n\t\tw.Write(LEVEL_0, \"Number of Nodes Misscheduled: %d\\n\", daemon.Status.NumberMisscheduled)\n\t\tw.Write(LEVEL_0, \"Pods Status:\\t%d Running / %d Waiting / %d Succeeded / %d Failed\\n\", running, waiting, succeeded, failed)\n\t\tDescribePodTemplate(\u0026daemon.Spec.Template, w)\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":2451,"to":2476}} {"id":100032469,"name":"Describe","signature":"func (d *SecretDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (d *SecretDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tc := d.CoreV1().Secrets(namespace)\n\n\tsecret, err := c.Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn describeSecret(secret)\n}","line":{"from":2483,"to":2492}} {"id":100032470,"name":"describeSecret","signature":"func describeSecret(secret *corev1.Secret) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeSecret(secret *corev1.Secret) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", secret.Name)\n\t\tw.Write(LEVEL_0, \"Namespace:\\t%s\\n\", secret.Namespace)\n\t\tprintLabelsMultiline(w, \"Labels\", secret.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", secret.Annotations)\n\n\t\tw.Write(LEVEL_0, \"\\nType:\\t%s\\n\", secret.Type)\n\n\t\tw.Write(LEVEL_0, \"\\nData\\n====\\n\")\n\t\tfor k, v := range secret.Data {\n\t\t\tswitch {\n\t\t\tcase k == corev1.ServiceAccountTokenKey \u0026\u0026 secret.Type == corev1.SecretTypeServiceAccountToken:\n\t\t\t\tw.Write(LEVEL_0, \"%s:\\t%s\\n\", k, string(v))\n\t\t\tdefault:\n\t\t\t\tw.Write(LEVEL_0, \"%s:\\t%d bytes\\n\", k, len(v))\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n}","line":{"from":2494,"to":2516}} {"id":100032471,"name":"Describe","signature":"func (i *IngressDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (i *IngressDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tvar events *corev1.EventList\n\n\t// try ingress/v1 first (v1.19) and fallback to ingress/v1beta if an err occurs\n\tnetV1, err := i.client.NetworkingV1().Ingresses(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\tif err == nil {\n\t\tif describerSettings.ShowEvents {\n\t\t\tevents, _ = searchEvents(i.client.CoreV1(), netV1, describerSettings.ChunkSize)\n\t\t}\n\t\treturn i.describeIngressV1(netV1, events)\n\t}\n\tnetV1beta1, err := i.client.NetworkingV1beta1().Ingresses(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\tif err == nil {\n\t\tif describerSettings.ShowEvents {\n\t\t\tevents, _ = searchEvents(i.client.CoreV1(), netV1beta1, describerSettings.ChunkSize)\n\t\t}\n\t\treturn i.describeIngressV1beta1(netV1beta1, events)\n\t}\n\treturn \"\", err\n}","line":{"from":2522,"to":2541}} {"id":100032472,"name":"describeBackendV1beta1","signature":"func (i *IngressDescriber) describeBackendV1beta1(ns string, backend *networkingv1beta1.IngressBackend) string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (i *IngressDescriber) describeBackendV1beta1(ns string, backend *networkingv1beta1.IngressBackend) string {\n\tendpoints, err := i.client.CoreV1().Endpoints(ns).Get(context.TODO(), backend.ServiceName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"\u003cerror: %v\u003e\", err)\n\t}\n\tservice, err := i.client.CoreV1().Services(ns).Get(context.TODO(), backend.ServiceName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"\u003cerror: %v\u003e\", err)\n\t}\n\tspName := \"\"\n\tfor i := range service.Spec.Ports {\n\t\tsp := \u0026service.Spec.Ports[i]\n\t\tswitch backend.ServicePort.Type {\n\t\tcase intstr.String:\n\t\t\tif backend.ServicePort.StrVal == sp.Name {\n\t\t\t\tspName = sp.Name\n\t\t\t}\n\t\tcase intstr.Int:\n\t\t\tif int32(backend.ServicePort.IntVal) == sp.Port {\n\t\t\t\tspName = sp.Name\n\t\t\t}\n\t\t}\n\t}\n\treturn formatEndpoints(endpoints, sets.NewString(spName))\n}","line":{"from":2543,"to":2567}} {"id":100032473,"name":"describeBackendV1","signature":"func (i *IngressDescriber) describeBackendV1(ns string, backend *networkingv1.IngressBackend) string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (i *IngressDescriber) describeBackendV1(ns string, backend *networkingv1.IngressBackend) string {\n\n\tif backend.Service != nil {\n\t\tsb := serviceBackendStringer(backend.Service)\n\t\tendpoints, err := i.client.CoreV1().Endpoints(ns).Get(context.TODO(), backend.Service.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn fmt.Sprintf(\"%v (\u003cerror: %v\u003e)\", sb, err)\n\t\t}\n\t\tservice, err := i.client.CoreV1().Services(ns).Get(context.TODO(), backend.Service.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn fmt.Sprintf(\"%v(\u003cerror: %v\u003e)\", sb, err)\n\t\t}\n\t\tspName := \"\"\n\t\tfor i := range service.Spec.Ports {\n\t\t\tsp := \u0026service.Spec.Ports[i]\n\t\t\tif backend.Service.Port.Number != 0 \u0026\u0026 backend.Service.Port.Number == sp.Port {\n\t\t\t\tspName = sp.Name\n\t\t\t} else if len(backend.Service.Port.Name) \u003e 0 \u0026\u0026 backend.Service.Port.Name == sp.Name {\n\t\t\t\tspName = sp.Name\n\t\t\t}\n\t\t}\n\t\tep := formatEndpoints(endpoints, sets.NewString(spName))\n\t\treturn fmt.Sprintf(\"%s (%s)\", sb, ep)\n\t}\n\tif backend.Resource != nil {\n\t\tic := backend.Resource\n\t\tapiGroup := \"\u003cnone\u003e\"\n\t\tif ic.APIGroup != nil {\n\t\t\tapiGroup = fmt.Sprintf(\"%v\", *ic.APIGroup)\n\t\t}\n\t\treturn fmt.Sprintf(\"APIGroup: %v, Kind: %v, Name: %v\", apiGroup, ic.Kind, ic.Name)\n\t}\n\treturn \"\"\n}","line":{"from":2569,"to":2602}} {"id":100032474,"name":"describeIngressV1","signature":"func (i *IngressDescriber) describeIngressV1(ing *networkingv1.Ingress, events *corev1.EventList) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (i *IngressDescriber) describeIngressV1(ing *networkingv1.Ingress, events *corev1.EventList) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%v\\n\", ing.Name)\n\t\tprintLabelsMultiline(w, \"Labels\", ing.Labels)\n\t\tw.Write(LEVEL_0, \"Namespace:\\t%v\\n\", ing.Namespace)\n\t\tw.Write(LEVEL_0, \"Address:\\t%v\\n\", ingressLoadBalancerStatusStringerV1(ing.Status.LoadBalancer, true))\n\t\tingressClassName := \"\u003cnone\u003e\"\n\t\tif ing.Spec.IngressClassName != nil {\n\t\t\tingressClassName = *ing.Spec.IngressClassName\n\t\t}\n\t\tw.Write(LEVEL_0, \"Ingress Class:\\t%v\\n\", ingressClassName)\n\t\tdef := ing.Spec.DefaultBackend\n\t\tns := ing.Namespace\n\t\tdefaultBackendDescribe := \"\u003cdefault\u003e\"\n\t\tif def != nil {\n\t\t\tdefaultBackendDescribe = i.describeBackendV1(ns, def)\n\t\t}\n\t\tw.Write(LEVEL_0, \"Default backend:\\t%s\\n\", defaultBackendDescribe)\n\t\tif len(ing.Spec.TLS) != 0 {\n\t\t\tdescribeIngressTLSV1(w, ing.Spec.TLS)\n\t\t}\n\t\tw.Write(LEVEL_0, \"Rules:\\n Host\\tPath\\tBackends\\n\")\n\t\tw.Write(LEVEL_1, \"----\\t----\\t--------\\n\")\n\t\tcount := 0\n\t\tfor _, rules := range ing.Spec.Rules {\n\n\t\t\tif rules.HTTP == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcount++\n\t\t\thost := rules.Host\n\t\t\tif len(host) == 0 {\n\t\t\t\thost = \"*\"\n\t\t\t}\n\t\t\tw.Write(LEVEL_1, \"%s\\t\\n\", host)\n\t\t\tfor _, path := range rules.HTTP.Paths {\n\t\t\t\tw.Write(LEVEL_2, \"\\t%s \\t%s\\n\", path.Path, i.describeBackendV1(ing.Namespace, \u0026path.Backend))\n\t\t\t}\n\t\t}\n\t\tif count == 0 {\n\t\t\tw.Write(LEVEL_1, \"%s\\t%s\\t%s\\n\", \"*\", \"*\", defaultBackendDescribe)\n\t\t}\n\t\tprintAnnotationsMultiline(w, \"Annotations\", ing.Annotations)\n\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":2604,"to":2654}} {"id":100032475,"name":"describeIngressV1beta1","signature":"func (i *IngressDescriber) describeIngressV1beta1(ing *networkingv1beta1.Ingress, events *corev1.EventList) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (i *IngressDescriber) describeIngressV1beta1(ing *networkingv1beta1.Ingress, events *corev1.EventList) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%v\\n\", ing.Name)\n\t\tprintLabelsMultiline(w, \"Labels\", ing.Labels)\n\t\tw.Write(LEVEL_0, \"Namespace:\\t%v\\n\", ing.Namespace)\n\t\tw.Write(LEVEL_0, \"Address:\\t%v\\n\", ingressLoadBalancerStatusStringerV1beta1(ing.Status.LoadBalancer, true))\n\t\tingressClassName := \"\u003cnone\u003e\"\n\t\tif ing.Spec.IngressClassName != nil {\n\t\t\tingressClassName = *ing.Spec.IngressClassName\n\t\t}\n\t\tw.Write(LEVEL_0, \"Ingress Class:\\t%v\\n\", ingressClassName)\n\t\tdef := ing.Spec.Backend\n\t\tns := ing.Namespace\n\t\tif def == nil {\n\t\t\tw.Write(LEVEL_0, \"Default backend:\\t\u003cdefault\u003e\\n\")\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"Default backend:\\t%s\\n\", i.describeBackendV1beta1(ns, def))\n\t\t}\n\t\tif len(ing.Spec.TLS) != 0 {\n\t\t\tdescribeIngressTLSV1beta1(w, ing.Spec.TLS)\n\t\t}\n\t\tw.Write(LEVEL_0, \"Rules:\\n Host\\tPath\\tBackends\\n\")\n\t\tw.Write(LEVEL_1, \"----\\t----\\t--------\\n\")\n\t\tcount := 0\n\t\tfor _, rules := range ing.Spec.Rules {\n\n\t\t\tif rules.HTTP == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcount++\n\t\t\thost := rules.Host\n\t\t\tif len(host) == 0 {\n\t\t\t\thost = \"*\"\n\t\t\t}\n\t\t\tw.Write(LEVEL_1, \"%s\\t\\n\", host)\n\t\t\tfor _, path := range rules.HTTP.Paths {\n\t\t\t\tw.Write(LEVEL_2, \"\\t%s \\t%s (%s)\\n\", path.Path, backendStringer(\u0026path.Backend), i.describeBackendV1beta1(ing.Namespace, \u0026path.Backend))\n\t\t\t}\n\t\t}\n\t\tif count == 0 {\n\t\t\tw.Write(LEVEL_1, \"%s\\t%s \\t\u003cdefault\u003e\\n\", \"*\", \"*\")\n\t\t}\n\t\tprintAnnotationsMultiline(w, \"Annotations\", ing.Annotations)\n\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":2656,"to":2706}} {"id":100032476,"name":"describeIngressTLSV1beta1","signature":"func describeIngressTLSV1beta1(w PrefixWriter, ingTLS []networkingv1beta1.IngressTLS)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeIngressTLSV1beta1(w PrefixWriter, ingTLS []networkingv1beta1.IngressTLS) {\n\tw.Write(LEVEL_0, \"TLS:\\n\")\n\tfor _, t := range ingTLS {\n\t\tif t.SecretName == \"\" {\n\t\t\tw.Write(LEVEL_1, \"SNI routes %v\\n\", strings.Join(t.Hosts, \",\"))\n\t\t} else {\n\t\t\tw.Write(LEVEL_1, \"%v terminates %v\\n\", t.SecretName, strings.Join(t.Hosts, \",\"))\n\t\t}\n\t}\n}","line":{"from":2708,"to":2717}} {"id":100032477,"name":"describeIngressTLSV1","signature":"func describeIngressTLSV1(w PrefixWriter, ingTLS []networkingv1.IngressTLS)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeIngressTLSV1(w PrefixWriter, ingTLS []networkingv1.IngressTLS) {\n\tw.Write(LEVEL_0, \"TLS:\\n\")\n\tfor _, t := range ingTLS {\n\t\tif t.SecretName == \"\" {\n\t\t\tw.Write(LEVEL_1, \"SNI routes %v\\n\", strings.Join(t.Hosts, \",\"))\n\t\t} else {\n\t\t\tw.Write(LEVEL_1, \"%v terminates %v\\n\", t.SecretName, strings.Join(t.Hosts, \",\"))\n\t\t}\n\t}\n}","line":{"from":2719,"to":2728}} {"id":100032478,"name":"Describe","signature":"func (i *IngressClassDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (i *IngressClassDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tvar events *corev1.EventList\n\t// try IngressClass/v1 first (v1.19) and fallback to IngressClass/v1beta if an err occurs\n\tnetV1, err := i.client.NetworkingV1().IngressClasses().Get(context.TODO(), name, metav1.GetOptions{})\n\tif err == nil {\n\t\tif describerSettings.ShowEvents {\n\t\t\tevents, _ = searchEvents(i.client.CoreV1(), netV1, describerSettings.ChunkSize)\n\t\t}\n\t\treturn i.describeIngressClassV1(netV1, events)\n\t}\n\tnetV1beta1, err := i.client.NetworkingV1beta1().IngressClasses().Get(context.TODO(), name, metav1.GetOptions{})\n\tif err == nil {\n\t\tif describerSettings.ShowEvents {\n\t\t\tevents, _ = searchEvents(i.client.CoreV1(), netV1beta1, describerSettings.ChunkSize)\n\t\t}\n\t\treturn i.describeIngressClassV1beta1(netV1beta1, events)\n\t}\n\treturn \"\", err\n}","line":{"from":2734,"to":2752}} {"id":100032479,"name":"describeIngressClassV1beta1","signature":"func (i *IngressClassDescriber) describeIngressClassV1beta1(ic *networkingv1beta1.IngressClass, events *corev1.EventList) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (i *IngressClassDescriber) describeIngressClassV1beta1(ic *networkingv1beta1.IngressClass, events *corev1.EventList) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", ic.Name)\n\t\tprintLabelsMultiline(w, \"Labels\", ic.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", ic.Annotations)\n\t\tw.Write(LEVEL_0, \"Controller:\\t%v\\n\", ic.Spec.Controller)\n\n\t\tif ic.Spec.Parameters != nil {\n\t\t\tw.Write(LEVEL_0, \"Parameters:\\n\")\n\t\t\tif ic.Spec.Parameters.APIGroup != nil {\n\t\t\t\tw.Write(LEVEL_1, \"APIGroup:\\t%v\\n\", *ic.Spec.Parameters.APIGroup)\n\t\t\t}\n\t\t\tw.Write(LEVEL_1, \"Kind:\\t%v\\n\", ic.Spec.Parameters.Kind)\n\t\t\tw.Write(LEVEL_1, \"Name:\\t%v\\n\", ic.Spec.Parameters.Name)\n\t\t}\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":2754,"to":2775}} {"id":100032480,"name":"describeIngressClassV1","signature":"func (i *IngressClassDescriber) describeIngressClassV1(ic *networkingv1.IngressClass, events *corev1.EventList) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (i *IngressClassDescriber) describeIngressClassV1(ic *networkingv1.IngressClass, events *corev1.EventList) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", ic.Name)\n\t\tprintLabelsMultiline(w, \"Labels\", ic.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", ic.Annotations)\n\t\tw.Write(LEVEL_0, \"Controller:\\t%v\\n\", ic.Spec.Controller)\n\n\t\tif ic.Spec.Parameters != nil {\n\t\t\tw.Write(LEVEL_0, \"Parameters:\\n\")\n\t\t\tif ic.Spec.Parameters.APIGroup != nil {\n\t\t\t\tw.Write(LEVEL_1, \"APIGroup:\\t%v\\n\", *ic.Spec.Parameters.APIGroup)\n\t\t\t}\n\t\t\tw.Write(LEVEL_1, \"Kind:\\t%v\\n\", ic.Spec.Parameters.Kind)\n\t\t\tw.Write(LEVEL_1, \"Name:\\t%v\\n\", ic.Spec.Parameters.Name)\n\t\t}\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":2777,"to":2798}} {"id":100032481,"name":"Describe","signature":"func (c *ClusterCIDRDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (c *ClusterCIDRDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tvar events *corev1.EventList\n\n\tccV1alpha1, err := c.client.NetworkingV1alpha1().ClusterCIDRs().Get(context.TODO(), name, metav1.GetOptions{})\n\tif err == nil {\n\t\tif describerSettings.ShowEvents {\n\t\t\tevents, _ = searchEvents(c.client.CoreV1(), ccV1alpha1, describerSettings.ChunkSize)\n\t\t}\n\t\treturn c.describeClusterCIDRV1alpha1(ccV1alpha1, events)\n\t}\n\treturn \"\", err\n}","line":{"from":2805,"to":2816}} {"id":100032482,"name":"describeClusterCIDRV1alpha1","signature":"func (c *ClusterCIDRDescriber) describeClusterCIDRV1alpha1(cc *networkingv1alpha1.ClusterCIDR, events *corev1.EventList) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (c *ClusterCIDRDescriber) describeClusterCIDRV1alpha1(cc *networkingv1alpha1.ClusterCIDR, events *corev1.EventList) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%v\\n\", cc.Name)\n\t\tprintLabelsMultiline(w, \"Labels\", cc.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", cc.Annotations)\n\n\t\tw.Write(LEVEL_0, \"NodeSelector:\\n\")\n\t\tif cc.Spec.NodeSelector != nil {\n\t\t\tw.Write(LEVEL_1, \"NodeSelector Terms:\")\n\t\t\tif len(cc.Spec.NodeSelector.NodeSelectorTerms) == 0 {\n\t\t\t\tw.WriteLine(\"\u003cnone\u003e\")\n\t\t\t} else {\n\t\t\t\tw.WriteLine(\"\")\n\t\t\t\tfor i, term := range cc.Spec.NodeSelector.NodeSelectorTerms {\n\t\t\t\t\tprintNodeSelectorTermsMultilineWithIndent(w, LEVEL_2, fmt.Sprintf(\"Term %v\", i), \"\\t\", term.MatchExpressions)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif cc.Spec.PerNodeHostBits != 0 {\n\t\t\tw.Write(LEVEL_0, \"PerNodeHostBits:\\t%s\\n\", fmt.Sprint(cc.Spec.PerNodeHostBits))\n\t\t}\n\n\t\tif cc.Spec.IPv4 != \"\" {\n\t\t\tw.Write(LEVEL_0, \"IPv4:\\t%s\\n\", cc.Spec.IPv4)\n\t\t}\n\n\t\tif cc.Spec.IPv6 != \"\" {\n\t\t\tw.Write(LEVEL_0, \"IPv6:\\t%s\\n\", cc.Spec.IPv6)\n\t\t}\n\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":2818,"to":2855}} {"id":100032483,"name":"Describe","signature":"func (c *IPAddressDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (c *IPAddressDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tvar events *corev1.EventList\n\n\tipV1alpha1, err := c.client.NetworkingV1alpha1().IPAddresses().Get(context.TODO(), name, metav1.GetOptions{})\n\tif err == nil {\n\t\tif describerSettings.ShowEvents {\n\t\t\tevents, _ = searchEvents(c.client.CoreV1(), ipV1alpha1, describerSettings.ChunkSize)\n\t\t}\n\t\treturn c.describeIPAddressV1alpha1(ipV1alpha1, events)\n\t}\n\treturn \"\", err\n}","line":{"from":2862,"to":2873}} {"id":100032484,"name":"describeIPAddressV1alpha1","signature":"func (c *IPAddressDescriber) describeIPAddressV1alpha1(ip *networkingv1alpha1.IPAddress, events *corev1.EventList) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (c *IPAddressDescriber) describeIPAddressV1alpha1(ip *networkingv1alpha1.IPAddress, events *corev1.EventList) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%v\\n\", ip.Name)\n\t\tprintLabelsMultiline(w, \"Labels\", ip.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", ip.Annotations)\n\n\t\tif ip.Spec.ParentRef != nil {\n\t\t\tw.Write(LEVEL_0, \"Parent Reference:\\n\")\n\t\t\tw.Write(LEVEL_1, \"Group:\\t%v\\n\", ip.Spec.ParentRef.Group)\n\t\t\tw.Write(LEVEL_1, \"Resource:\\t%v\\n\", ip.Spec.ParentRef.Resource)\n\t\t\tw.Write(LEVEL_1, \"Namespace:\\t%v\\n\", ip.Spec.ParentRef.Namespace)\n\t\t\tw.Write(LEVEL_1, \"Name:\\t%v\\n\", ip.Spec.ParentRef.Name)\n\t\t}\n\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":2875,"to":2895}} {"id":100032485,"name":"Describe","signature":"func (d *ServiceDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (d *ServiceDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tc := d.CoreV1().Services(namespace)\n\n\tservice, err := c.Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tendpoints, _ := d.CoreV1().Endpoints(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\tvar events *corev1.EventList\n\tif describerSettings.ShowEvents {\n\t\tevents, _ = searchEvents(d.CoreV1(), service, describerSettings.ChunkSize)\n\t}\n\treturn describeService(service, endpoints, events)\n}","line":{"from":2902,"to":2916}} {"id":100032486,"name":"buildIngressString","signature":"func buildIngressString(ingress []corev1.LoadBalancerIngress) string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func buildIngressString(ingress []corev1.LoadBalancerIngress) string {\n\tvar buffer bytes.Buffer\n\n\tfor i := range ingress {\n\t\tif i != 0 {\n\t\t\tbuffer.WriteString(\", \")\n\t\t}\n\t\tif ingress[i].IP != \"\" {\n\t\t\tbuffer.WriteString(ingress[i].IP)\n\t\t} else {\n\t\t\tbuffer.WriteString(ingress[i].Hostname)\n\t\t}\n\t}\n\treturn buffer.String()\n}","line":{"from":2918,"to":2932}} {"id":100032487,"name":"describeService","signature":"func describeService(service *corev1.Service, endpoints *corev1.Endpoints, events *corev1.EventList) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeService(service *corev1.Service, endpoints *corev1.Endpoints, events *corev1.EventList) (string, error) {\n\tif endpoints == nil {\n\t\tendpoints = \u0026corev1.Endpoints{}\n\t}\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", service.Name)\n\t\tw.Write(LEVEL_0, \"Namespace:\\t%s\\n\", service.Namespace)\n\t\tprintLabelsMultiline(w, \"Labels\", service.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", service.Annotations)\n\t\tw.Write(LEVEL_0, \"Selector:\\t%s\\n\", labels.FormatLabels(service.Spec.Selector))\n\t\tw.Write(LEVEL_0, \"Type:\\t%s\\n\", service.Spec.Type)\n\n\t\tif service.Spec.IPFamilyPolicy != nil {\n\t\t\tw.Write(LEVEL_0, \"IP Family Policy:\\t%s\\n\", *(service.Spec.IPFamilyPolicy))\n\t\t}\n\n\t\tif len(service.Spec.IPFamilies) \u003e 0 {\n\t\t\tipfamiliesStrings := make([]string, 0, len(service.Spec.IPFamilies))\n\t\t\tfor _, family := range service.Spec.IPFamilies {\n\t\t\t\tipfamiliesStrings = append(ipfamiliesStrings, string(family))\n\t\t\t}\n\n\t\t\tw.Write(LEVEL_0, \"IP Families:\\t%s\\n\", strings.Join(ipfamiliesStrings, \",\"))\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"IP Families:\\t%s\\n\", \"\u003cnone\u003e\")\n\t\t}\n\n\t\tw.Write(LEVEL_0, \"IP:\\t%s\\n\", service.Spec.ClusterIP)\n\t\tif len(service.Spec.ClusterIPs) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"IPs:\\t%s\\n\", strings.Join(service.Spec.ClusterIPs, \",\"))\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"IPs:\\t%s\\n\", \"\u003cnone\u003e\")\n\t\t}\n\n\t\tif len(service.Spec.ExternalIPs) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"External IPs:\\t%v\\n\", strings.Join(service.Spec.ExternalIPs, \",\"))\n\t\t}\n\t\tif service.Spec.LoadBalancerIP != \"\" {\n\t\t\tw.Write(LEVEL_0, \"IP:\\t%s\\n\", service.Spec.LoadBalancerIP)\n\t\t}\n\t\tif service.Spec.ExternalName != \"\" {\n\t\t\tw.Write(LEVEL_0, \"External Name:\\t%s\\n\", service.Spec.ExternalName)\n\t\t}\n\t\tif len(service.Status.LoadBalancer.Ingress) \u003e 0 {\n\t\t\tlist := buildIngressString(service.Status.LoadBalancer.Ingress)\n\t\t\tw.Write(LEVEL_0, \"LoadBalancer Ingress:\\t%s\\n\", list)\n\t\t}\n\t\tfor i := range service.Spec.Ports {\n\t\t\tsp := \u0026service.Spec.Ports[i]\n\n\t\t\tname := sp.Name\n\t\t\tif name == \"\" {\n\t\t\t\tname = \"\u003cunset\u003e\"\n\t\t\t}\n\t\t\tw.Write(LEVEL_0, \"Port:\\t%s\\t%d/%s\\n\", name, sp.Port, sp.Protocol)\n\t\t\tif sp.TargetPort.Type == intstr.Type(intstr.Int) {\n\t\t\t\tw.Write(LEVEL_0, \"TargetPort:\\t%d/%s\\n\", sp.TargetPort.IntVal, sp.Protocol)\n\t\t\t} else {\n\t\t\t\tw.Write(LEVEL_0, \"TargetPort:\\t%s/%s\\n\", sp.TargetPort.StrVal, sp.Protocol)\n\t\t\t}\n\t\t\tif sp.NodePort != 0 {\n\t\t\t\tw.Write(LEVEL_0, \"NodePort:\\t%s\\t%d/%s\\n\", name, sp.NodePort, sp.Protocol)\n\t\t\t}\n\t\t\tw.Write(LEVEL_0, \"Endpoints:\\t%s\\n\", formatEndpoints(endpoints, sets.NewString(sp.Name)))\n\t\t}\n\t\tw.Write(LEVEL_0, \"Session Affinity:\\t%s\\n\", service.Spec.SessionAffinity)\n\t\tif service.Spec.ExternalTrafficPolicy != \"\" {\n\t\t\tw.Write(LEVEL_0, \"External Traffic Policy:\\t%s\\n\", service.Spec.ExternalTrafficPolicy)\n\t\t}\n\t\tif service.Spec.HealthCheckNodePort != 0 {\n\t\t\tw.Write(LEVEL_0, \"HealthCheck NodePort:\\t%d\\n\", service.Spec.HealthCheckNodePort)\n\t\t}\n\t\tif len(service.Spec.LoadBalancerSourceRanges) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"LoadBalancer Source Ranges:\\t%v\\n\", strings.Join(service.Spec.LoadBalancerSourceRanges, \",\"))\n\t\t}\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":2934,"to":3015}} {"id":100032488,"name":"Describe","signature":"func (d *EndpointsDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (d *EndpointsDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tc := d.CoreV1().Endpoints(namespace)\n\n\tep, err := c.Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar events *corev1.EventList\n\tif describerSettings.ShowEvents {\n\t\tevents, _ = searchEvents(d.CoreV1(), ep, describerSettings.ChunkSize)\n\t}\n\n\treturn describeEndpoints(ep, events)\n}","line":{"from":3022,"to":3036}} {"id":100032489,"name":"describeEndpoints","signature":"func describeEndpoints(ep *corev1.Endpoints, events *corev1.EventList) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeEndpoints(ep *corev1.Endpoints, events *corev1.EventList) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", ep.Name)\n\t\tw.Write(LEVEL_0, \"Namespace:\\t%s\\n\", ep.Namespace)\n\t\tprintLabelsMultiline(w, \"Labels\", ep.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", ep.Annotations)\n\n\t\tw.Write(LEVEL_0, \"Subsets:\\n\")\n\t\tfor i := range ep.Subsets {\n\t\t\tsubset := \u0026ep.Subsets[i]\n\n\t\t\taddresses := make([]string, 0, len(subset.Addresses))\n\t\t\tfor _, addr := range subset.Addresses {\n\t\t\t\taddresses = append(addresses, addr.IP)\n\t\t\t}\n\t\t\taddressesString := strings.Join(addresses, \",\")\n\t\t\tif len(addressesString) == 0 {\n\t\t\t\taddressesString = \"\u003cnone\u003e\"\n\t\t\t}\n\t\t\tw.Write(LEVEL_1, \"Addresses:\\t%s\\n\", addressesString)\n\n\t\t\tnotReadyAddresses := make([]string, 0, len(subset.NotReadyAddresses))\n\t\t\tfor _, addr := range subset.NotReadyAddresses {\n\t\t\t\tnotReadyAddresses = append(notReadyAddresses, addr.IP)\n\t\t\t}\n\t\t\tnotReadyAddressesString := strings.Join(notReadyAddresses, \",\")\n\t\t\tif len(notReadyAddressesString) == 0 {\n\t\t\t\tnotReadyAddressesString = \"\u003cnone\u003e\"\n\t\t\t}\n\t\t\tw.Write(LEVEL_1, \"NotReadyAddresses:\\t%s\\n\", notReadyAddressesString)\n\n\t\t\tif len(subset.Ports) \u003e 0 {\n\t\t\t\tw.Write(LEVEL_1, \"Ports:\\n\")\n\t\t\t\tw.Write(LEVEL_2, \"Name\\tPort\\tProtocol\\n\")\n\t\t\t\tw.Write(LEVEL_2, \"----\\t----\\t--------\\n\")\n\t\t\t\tfor _, port := range subset.Ports {\n\t\t\t\t\tname := port.Name\n\t\t\t\t\tif len(name) == 0 {\n\t\t\t\t\t\tname = \"\u003cunset\u003e\"\n\t\t\t\t\t}\n\t\t\t\t\tw.Write(LEVEL_2, \"%s\\t%d\\t%s\\n\", name, port.Port, port.Protocol)\n\t\t\t\t}\n\t\t\t}\n\t\t\tw.Write(LEVEL_0, \"\\n\")\n\t\t}\n\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":3038,"to":3090}} {"id":100032490,"name":"Describe","signature":"func (d *EndpointSliceDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (d *EndpointSliceDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tvar events *corev1.EventList\n\t// try endpointslice/v1 first (v1.21) and fallback to v1beta1 if error occurs\n\n\tepsV1, err := d.DiscoveryV1().EndpointSlices(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\tif err == nil {\n\t\tif describerSettings.ShowEvents {\n\t\t\tevents, _ = searchEvents(d.CoreV1(), epsV1, describerSettings.ChunkSize)\n\t\t}\n\t\treturn describeEndpointSliceV1(epsV1, events)\n\t}\n\n\tepsV1beta1, err := d.DiscoveryV1beta1().EndpointSlices(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif describerSettings.ShowEvents {\n\t\tevents, _ = searchEvents(d.CoreV1(), epsV1beta1, describerSettings.ChunkSize)\n\t}\n\n\treturn describeEndpointSliceV1beta1(epsV1beta1, events)\n}","line":{"from":3097,"to":3119}} {"id":100032491,"name":"describeEndpointSliceV1","signature":"func describeEndpointSliceV1(eps *discoveryv1.EndpointSlice, events *corev1.EventList) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeEndpointSliceV1(eps *discoveryv1.EndpointSlice, events *corev1.EventList) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", eps.Name)\n\t\tw.Write(LEVEL_0, \"Namespace:\\t%s\\n\", eps.Namespace)\n\t\tprintLabelsMultiline(w, \"Labels\", eps.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", eps.Annotations)\n\n\t\tw.Write(LEVEL_0, \"AddressType:\\t%s\\n\", string(eps.AddressType))\n\n\t\tif len(eps.Ports) == 0 {\n\t\t\tw.Write(LEVEL_0, \"Ports: \u003cunset\u003e\\n\")\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"Ports:\\n\")\n\t\t\tw.Write(LEVEL_1, \"Name\\tPort\\tProtocol\\n\")\n\t\t\tw.Write(LEVEL_1, \"----\\t----\\t--------\\n\")\n\t\t\tfor _, port := range eps.Ports {\n\t\t\t\tportName := \"\u003cunset\u003e\"\n\t\t\t\tif port.Name != nil \u0026\u0026 len(*port.Name) \u003e 0 {\n\t\t\t\t\tportName = *port.Name\n\t\t\t\t}\n\n\t\t\t\tportNum := \"\u003cunset\u003e\"\n\t\t\t\tif port.Port != nil {\n\t\t\t\t\tportNum = strconv.Itoa(int(*port.Port))\n\t\t\t\t}\n\n\t\t\t\tw.Write(LEVEL_1, \"%s\\t%s\\t%s\\n\", portName, portNum, *port.Protocol)\n\t\t\t}\n\t\t}\n\n\t\tif len(eps.Endpoints) == 0 {\n\t\t\tw.Write(LEVEL_0, \"Endpoints: \u003cnone\u003e\\n\")\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"Endpoints:\\n\")\n\t\t\tfor i := range eps.Endpoints {\n\t\t\t\tendpoint := \u0026eps.Endpoints[i]\n\n\t\t\t\taddressesString := strings.Join(endpoint.Addresses, \", \")\n\t\t\t\tif len(addressesString) == 0 {\n\t\t\t\t\taddressesString = \"\u003cnone\u003e\"\n\t\t\t\t}\n\t\t\t\tw.Write(LEVEL_1, \"- Addresses:\\t%s\\n\", addressesString)\n\n\t\t\t\tw.Write(LEVEL_2, \"Conditions:\\n\")\n\t\t\t\treadyText := \"\u003cunset\u003e\"\n\t\t\t\tif endpoint.Conditions.Ready != nil {\n\t\t\t\t\treadyText = strconv.FormatBool(*endpoint.Conditions.Ready)\n\t\t\t\t}\n\t\t\t\tw.Write(LEVEL_3, \"Ready:\\t%s\\n\", readyText)\n\n\t\t\t\thostnameText := \"\u003cunset\u003e\"\n\t\t\t\tif endpoint.Hostname != nil {\n\t\t\t\t\thostnameText = *endpoint.Hostname\n\t\t\t\t}\n\t\t\t\tw.Write(LEVEL_2, \"Hostname:\\t%s\\n\", hostnameText)\n\n\t\t\t\tif endpoint.TargetRef != nil {\n\t\t\t\t\tw.Write(LEVEL_2, \"TargetRef:\\t%s/%s\\n\", endpoint.TargetRef.Kind, endpoint.TargetRef.Name)\n\t\t\t\t}\n\n\t\t\t\tnodeNameText := \"\u003cunset\u003e\"\n\t\t\t\tif endpoint.NodeName != nil {\n\t\t\t\t\tnodeNameText = *endpoint.NodeName\n\t\t\t\t}\n\t\t\t\tw.Write(LEVEL_2, \"NodeName:\\t%s\\n\", nodeNameText)\n\n\t\t\t\tzoneText := \"\u003cunset\u003e\"\n\t\t\t\tif endpoint.Zone != nil {\n\t\t\t\t\tzoneText = *endpoint.Zone\n\t\t\t\t}\n\t\t\t\tw.Write(LEVEL_2, \"Zone:\\t%s\\n\", zoneText)\n\t\t\t}\n\t\t}\n\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":3121,"to":3201}} {"id":100032492,"name":"describeEndpointSliceV1beta1","signature":"func describeEndpointSliceV1beta1(eps *discoveryv1beta1.EndpointSlice, events *corev1.EventList) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeEndpointSliceV1beta1(eps *discoveryv1beta1.EndpointSlice, events *corev1.EventList) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", eps.Name)\n\t\tw.Write(LEVEL_0, \"Namespace:\\t%s\\n\", eps.Namespace)\n\t\tprintLabelsMultiline(w, \"Labels\", eps.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", eps.Annotations)\n\n\t\tw.Write(LEVEL_0, \"AddressType:\\t%s\\n\", string(eps.AddressType))\n\n\t\tif len(eps.Ports) == 0 {\n\t\t\tw.Write(LEVEL_0, \"Ports: \u003cunset\u003e\\n\")\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"Ports:\\n\")\n\t\t\tw.Write(LEVEL_1, \"Name\\tPort\\tProtocol\\n\")\n\t\t\tw.Write(LEVEL_1, \"----\\t----\\t--------\\n\")\n\t\t\tfor _, port := range eps.Ports {\n\t\t\t\tportName := \"\u003cunset\u003e\"\n\t\t\t\tif port.Name != nil \u0026\u0026 len(*port.Name) \u003e 0 {\n\t\t\t\t\tportName = *port.Name\n\t\t\t\t}\n\n\t\t\t\tportNum := \"\u003cunset\u003e\"\n\t\t\t\tif port.Port != nil {\n\t\t\t\t\tportNum = strconv.Itoa(int(*port.Port))\n\t\t\t\t}\n\n\t\t\t\tw.Write(LEVEL_1, \"%s\\t%s\\t%s\\n\", portName, portNum, *port.Protocol)\n\t\t\t}\n\t\t}\n\n\t\tif len(eps.Endpoints) == 0 {\n\t\t\tw.Write(LEVEL_0, \"Endpoints: \u003cnone\u003e\\n\")\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"Endpoints:\\n\")\n\t\t\tfor i := range eps.Endpoints {\n\t\t\t\tendpoint := \u0026eps.Endpoints[i]\n\n\t\t\t\taddressesString := strings.Join(endpoint.Addresses, \",\")\n\t\t\t\tif len(addressesString) == 0 {\n\t\t\t\t\taddressesString = \"\u003cnone\u003e\"\n\t\t\t\t}\n\t\t\t\tw.Write(LEVEL_1, \"- Addresses:\\t%s\\n\", addressesString)\n\n\t\t\t\tw.Write(LEVEL_2, \"Conditions:\\n\")\n\t\t\t\treadyText := \"\u003cunset\u003e\"\n\t\t\t\tif endpoint.Conditions.Ready != nil {\n\t\t\t\t\treadyText = strconv.FormatBool(*endpoint.Conditions.Ready)\n\t\t\t\t}\n\t\t\t\tw.Write(LEVEL_3, \"Ready:\\t%s\\n\", readyText)\n\n\t\t\t\thostnameText := \"\u003cunset\u003e\"\n\t\t\t\tif endpoint.Hostname != nil {\n\t\t\t\t\thostnameText = *endpoint.Hostname\n\t\t\t\t}\n\t\t\t\tw.Write(LEVEL_2, \"Hostname:\\t%s\\n\", hostnameText)\n\n\t\t\t\tif endpoint.TargetRef != nil {\n\t\t\t\t\tw.Write(LEVEL_2, \"TargetRef:\\t%s/%s\\n\", endpoint.TargetRef.Kind, endpoint.TargetRef.Name)\n\t\t\t\t}\n\n\t\t\t\tprintLabelsMultilineWithIndent(w, \" \", \"Topology\", \"\\t\", endpoint.Topology, sets.NewString())\n\t\t\t}\n\t\t}\n\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":3203,"to":3273}} {"id":100032493,"name":"Describe","signature":"func (d *ServiceAccountDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (d *ServiceAccountDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tc := d.CoreV1().ServiceAccounts(namespace)\n\n\tserviceAccount, err := c.Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ttokens := []corev1.Secret{}\n\n\t// missingSecrets is the set of all secrets present in the\n\t// serviceAccount but not present in the set of existing secrets.\n\tmissingSecrets := sets.NewString()\n\tsecrets := corev1.SecretList{}\n\terr = runtimeresource.FollowContinue(\u0026metav1.ListOptions{Limit: describerSettings.ChunkSize},\n\t\tfunc(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\tnewList, err := d.CoreV1().Secrets(namespace).List(context.TODO(), options)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, runtimeresource.EnhanceListError(err, options, corev1.ResourceSecrets.String())\n\t\t\t}\n\t\t\tsecrets.Items = append(secrets.Items, newList.Items...)\n\t\t\treturn newList, nil\n\t\t})\n\n\t// errors are tolerated here in order to describe the serviceAccount with all\n\t// of the secrets that it references, even if those secrets cannot be fetched.\n\tif err == nil {\n\t\t// existingSecrets is the set of all secrets remaining on a\n\t\t// service account that are not present in the \"tokens\" slice.\n\t\texistingSecrets := sets.NewString()\n\n\t\tfor _, s := range secrets.Items {\n\t\t\tif s.Type == corev1.SecretTypeServiceAccountToken {\n\t\t\t\tname := s.Annotations[corev1.ServiceAccountNameKey]\n\t\t\t\tuid := s.Annotations[corev1.ServiceAccountUIDKey]\n\t\t\t\tif name == serviceAccount.Name \u0026\u0026 uid == string(serviceAccount.UID) {\n\t\t\t\t\ttokens = append(tokens, s)\n\t\t\t\t}\n\t\t\t}\n\t\t\texistingSecrets.Insert(s.Name)\n\t\t}\n\n\t\tfor _, s := range serviceAccount.Secrets {\n\t\t\tif !existingSecrets.Has(s.Name) {\n\t\t\t\tmissingSecrets.Insert(s.Name)\n\t\t\t}\n\t\t}\n\t\tfor _, s := range serviceAccount.ImagePullSecrets {\n\t\t\tif !existingSecrets.Has(s.Name) {\n\t\t\t\tmissingSecrets.Insert(s.Name)\n\t\t\t}\n\t\t}\n\t}\n\n\tvar events *corev1.EventList\n\tif describerSettings.ShowEvents {\n\t\tevents, _ = searchEvents(d.CoreV1(), serviceAccount, describerSettings.ChunkSize)\n\t}\n\n\treturn describeServiceAccount(serviceAccount, tokens, missingSecrets, events)\n}","line":{"from":3280,"to":3340}} {"id":100032494,"name":"describeServiceAccount","signature":"func describeServiceAccount(serviceAccount *corev1.ServiceAccount, tokens []corev1.Secret, missingSecrets sets.String, events *corev1.EventList) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeServiceAccount(serviceAccount *corev1.ServiceAccount, tokens []corev1.Secret, missingSecrets sets.String, events *corev1.EventList) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", serviceAccount.Name)\n\t\tw.Write(LEVEL_0, \"Namespace:\\t%s\\n\", serviceAccount.Namespace)\n\t\tprintLabelsMultiline(w, \"Labels\", serviceAccount.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", serviceAccount.Annotations)\n\n\t\tvar (\n\t\t\temptyHeader = \" \"\n\t\t\tpullHeader = \"Image pull secrets:\"\n\t\t\tmountHeader = \"Mountable secrets: \"\n\t\t\ttokenHeader = \"Tokens: \"\n\n\t\t\tpullSecretNames = []string{}\n\t\t\tmountSecretNames = []string{}\n\t\t\ttokenSecretNames = []string{}\n\t\t)\n\n\t\tfor _, s := range serviceAccount.ImagePullSecrets {\n\t\t\tpullSecretNames = append(pullSecretNames, s.Name)\n\t\t}\n\t\tfor _, s := range serviceAccount.Secrets {\n\t\t\tmountSecretNames = append(mountSecretNames, s.Name)\n\t\t}\n\t\tfor _, s := range tokens {\n\t\t\ttokenSecretNames = append(tokenSecretNames, s.Name)\n\t\t}\n\n\t\ttypes := map[string][]string{\n\t\t\tpullHeader: pullSecretNames,\n\t\t\tmountHeader: mountSecretNames,\n\t\t\ttokenHeader: tokenSecretNames,\n\t\t}\n\t\tfor _, header := range sets.StringKeySet(types).List() {\n\t\t\tnames := types[header]\n\t\t\tif len(names) == 0 {\n\t\t\t\tw.Write(LEVEL_0, \"%s\\t\u003cnone\u003e\\n\", header)\n\t\t\t} else {\n\t\t\t\tprefix := header\n\t\t\t\tfor _, name := range names {\n\t\t\t\t\tif missingSecrets.Has(name) {\n\t\t\t\t\t\tw.Write(LEVEL_0, \"%s\\t%s (not found)\\n\", prefix, name)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tw.Write(LEVEL_0, \"%s\\t%s\\n\", prefix, name)\n\t\t\t\t\t}\n\t\t\t\t\tprefix = emptyHeader\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\n\t\treturn nil\n\t})\n}","line":{"from":3342,"to":3399}} {"id":100032495,"name":"Describe","signature":"func (d *RoleDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (d *RoleDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\trole, err := d.RbacV1().Roles(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tbreakdownRules := []rbacv1.PolicyRule{}\n\tfor _, rule := range role.Rules {\n\t\tbreakdownRules = append(breakdownRules, rbac.BreakdownRule(rule)...)\n\t}\n\n\tcompactRules, err := rbac.CompactRules(breakdownRules)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tsort.Stable(rbac.SortableRuleSlice(compactRules))\n\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", role.Name)\n\t\tprintLabelsMultiline(w, \"Labels\", role.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", role.Annotations)\n\n\t\tw.Write(LEVEL_0, \"PolicyRule:\\n\")\n\t\tw.Write(LEVEL_1, \"Resources\\tNon-Resource URLs\\tResource Names\\tVerbs\\n\")\n\t\tw.Write(LEVEL_1, \"---------\\t-----------------\\t--------------\\t-----\\n\")\n\t\tfor _, r := range compactRules {\n\t\t\tw.Write(LEVEL_1, \"%s\\t%v\\t%v\\t%v\\n\", CombineResourceGroup(r.Resources, r.APIGroups), r.NonResourceURLs, r.ResourceNames, r.Verbs)\n\t\t}\n\n\t\treturn nil\n\t})\n}","line":{"from":3406,"to":3438}} {"id":100032496,"name":"Describe","signature":"func (d *ClusterRoleDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (d *ClusterRoleDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\trole, err := d.RbacV1().ClusterRoles().Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tbreakdownRules := []rbacv1.PolicyRule{}\n\tfor _, rule := range role.Rules {\n\t\tbreakdownRules = append(breakdownRules, rbac.BreakdownRule(rule)...)\n\t}\n\n\tcompactRules, err := rbac.CompactRules(breakdownRules)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tsort.Stable(rbac.SortableRuleSlice(compactRules))\n\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", role.Name)\n\t\tprintLabelsMultiline(w, \"Labels\", role.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", role.Annotations)\n\n\t\tw.Write(LEVEL_0, \"PolicyRule:\\n\")\n\t\tw.Write(LEVEL_1, \"Resources\\tNon-Resource URLs\\tResource Names\\tVerbs\\n\")\n\t\tw.Write(LEVEL_1, \"---------\\t-----------------\\t--------------\\t-----\\n\")\n\t\tfor _, r := range compactRules {\n\t\t\tw.Write(LEVEL_1, \"%s\\t%v\\t%v\\t%v\\n\", CombineResourceGroup(r.Resources, r.APIGroups), r.NonResourceURLs, r.ResourceNames, r.Verbs)\n\t\t}\n\n\t\treturn nil\n\t})\n}","line":{"from":3445,"to":3477}} {"id":100032497,"name":"CombineResourceGroup","signature":"func CombineResourceGroup(resource, group []string) string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func CombineResourceGroup(resource, group []string) string {\n\tif len(resource) == 0 {\n\t\treturn \"\"\n\t}\n\tparts := strings.SplitN(resource[0], \"/\", 2)\n\tcombine := parts[0]\n\n\tif len(group) \u003e 0 \u0026\u0026 group[0] != \"\" {\n\t\tcombine = combine + \".\" + group[0]\n\t}\n\n\tif len(parts) == 2 {\n\t\tcombine = combine + \"/\" + parts[1]\n\t}\n\treturn combine\n}","line":{"from":3479,"to":3494}} {"id":100032498,"name":"Describe","signature":"func (d *RoleBindingDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (d *RoleBindingDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tbinding, err := d.RbacV1().RoleBindings(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", binding.Name)\n\t\tprintLabelsMultiline(w, \"Labels\", binding.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", binding.Annotations)\n\n\t\tw.Write(LEVEL_0, \"Role:\\n\")\n\t\tw.Write(LEVEL_1, \"Kind:\\t%s\\n\", binding.RoleRef.Kind)\n\t\tw.Write(LEVEL_1, \"Name:\\t%s\\n\", binding.RoleRef.Name)\n\n\t\tw.Write(LEVEL_0, \"Subjects:\\n\")\n\t\tw.Write(LEVEL_1, \"Kind\\tName\\tNamespace\\n\")\n\t\tw.Write(LEVEL_1, \"----\\t----\\t---------\\n\")\n\t\tfor _, s := range binding.Subjects {\n\t\t\tw.Write(LEVEL_1, \"%s\\t%s\\t%s\\n\", s.Kind, s.Name, s.Namespace)\n\t\t}\n\n\t\treturn nil\n\t})\n}","line":{"from":3501,"to":3526}} {"id":100032499,"name":"Describe","signature":"func (d *ClusterRoleBindingDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (d *ClusterRoleBindingDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tbinding, err := d.RbacV1().ClusterRoleBindings().Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", binding.Name)\n\t\tprintLabelsMultiline(w, \"Labels\", binding.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", binding.Annotations)\n\n\t\tw.Write(LEVEL_0, \"Role:\\n\")\n\t\tw.Write(LEVEL_1, \"Kind:\\t%s\\n\", binding.RoleRef.Kind)\n\t\tw.Write(LEVEL_1, \"Name:\\t%s\\n\", binding.RoleRef.Name)\n\n\t\tw.Write(LEVEL_0, \"Subjects:\\n\")\n\t\tw.Write(LEVEL_1, \"Kind\\tName\\tNamespace\\n\")\n\t\tw.Write(LEVEL_1, \"----\\t----\\t---------\\n\")\n\t\tfor _, s := range binding.Subjects {\n\t\t\tw.Write(LEVEL_1, \"%s\\t%s\\t%s\\n\", s.Kind, s.Name, s.Namespace)\n\t\t}\n\n\t\treturn nil\n\t})\n}","line":{"from":3533,"to":3558}} {"id":100032500,"name":"Describe","signature":"func (d *NodeDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (d *NodeDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tmc := d.CoreV1().Nodes()\n\tnode, err := mc.Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfieldSelector, err := fields.ParseSelector(\"spec.nodeName=\" + name + \",status.phase!=\" + string(corev1.PodSucceeded) + \",status.phase!=\" + string(corev1.PodFailed))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// in a policy aware setting, users may have access to a node, but not all pods\n\t// in that case, we note that the user does not have access to the pods\n\tcanViewPods := true\n\tinitialOpts := metav1.ListOptions{\n\t\tFieldSelector: fieldSelector.String(),\n\t\tLimit: describerSettings.ChunkSize,\n\t}\n\tnodeNonTerminatedPodsList, err := getPodsInChunks(d.CoreV1().Pods(namespace), initialOpts)\n\tif err != nil {\n\t\tif !apierrors.IsForbidden(err) {\n\t\t\treturn \"\", err\n\t\t}\n\t\tcanViewPods = false\n\t}\n\n\tvar events *corev1.EventList\n\tif describerSettings.ShowEvents {\n\t\tif ref, err := reference.GetReference(scheme.Scheme, node); err != nil {\n\t\t\tklog.Errorf(\"Unable to construct reference to '%#v': %v\", node, err)\n\t\t} else {\n\t\t\t// TODO: We haven't decided the namespace for Node object yet.\n\t\t\t// there are two UIDs for host events:\n\t\t\t// controller use node.uid\n\t\t\t// kubelet use node.name\n\t\t\t// TODO: Uniform use of UID\n\t\t\tevents, _ = searchEvents(d.CoreV1(), ref, describerSettings.ChunkSize)\n\n\t\t\tref.UID = types.UID(ref.Name)\n\t\t\teventsInvName, _ := searchEvents(d.CoreV1(), ref, describerSettings.ChunkSize)\n\n\t\t\t// Merge the results of two queries\n\t\t\tevents.Items = append(events.Items, eventsInvName.Items...)\n\t\t}\n\t}\n\n\treturn describeNode(node, nodeNonTerminatedPodsList, events, canViewPods, \u0026LeaseDescriber{d})\n}","line":{"from":3565,"to":3612}} {"id":100032501,"name":"describeNode","signature":"func describeNode(node *corev1.Node, nodeNonTerminatedPodsList *corev1.PodList, events *corev1.EventList,","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeNode(node *corev1.Node, nodeNonTerminatedPodsList *corev1.PodList, events *corev1.EventList,\n\tcanViewPods bool, ld *LeaseDescriber) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", node.Name)\n\t\tif roles := findNodeRoles(node); len(roles) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"Roles:\\t%s\\n\", strings.Join(roles, \",\"))\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"Roles:\\t%s\\n\", \"\u003cnone\u003e\")\n\t\t}\n\t\tprintLabelsMultiline(w, \"Labels\", node.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", node.Annotations)\n\t\tw.Write(LEVEL_0, \"CreationTimestamp:\\t%s\\n\", node.CreationTimestamp.Time.Format(time.RFC1123Z))\n\t\tprintNodeTaintsMultiline(w, \"Taints\", node.Spec.Taints)\n\t\tw.Write(LEVEL_0, \"Unschedulable:\\t%v\\n\", node.Spec.Unschedulable)\n\n\t\tif ld != nil {\n\t\t\tif lease, err := ld.client.CoordinationV1().Leases(corev1.NamespaceNodeLease).Get(context.TODO(), node.Name, metav1.GetOptions{}); err == nil {\n\t\t\t\tdescribeNodeLease(lease, w)\n\t\t\t} else {\n\t\t\t\tw.Write(LEVEL_0, \"Lease:\\tFailed to get lease: %s\\n\", err)\n\t\t\t}\n\t\t}\n\n\t\tif len(node.Status.Conditions) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"Conditions:\\n Type\\tStatus\\tLastHeartbeatTime\\tLastTransitionTime\\tReason\\tMessage\\n\")\n\t\t\tw.Write(LEVEL_1, \"----\\t------\\t-----------------\\t------------------\\t------\\t-------\\n\")\n\t\t\tfor _, c := range node.Status.Conditions {\n\t\t\t\tw.Write(LEVEL_1, \"%v \\t%v \\t%s \\t%s \\t%v \\t%v\\n\",\n\t\t\t\t\tc.Type,\n\t\t\t\t\tc.Status,\n\t\t\t\t\tc.LastHeartbeatTime.Time.Format(time.RFC1123Z),\n\t\t\t\t\tc.LastTransitionTime.Time.Format(time.RFC1123Z),\n\t\t\t\t\tc.Reason,\n\t\t\t\t\tc.Message)\n\t\t\t}\n\t\t}\n\n\t\tw.Write(LEVEL_0, \"Addresses:\\n\")\n\t\tfor _, address := range node.Status.Addresses {\n\t\t\tw.Write(LEVEL_1, \"%s:\\t%s\\n\", address.Type, address.Address)\n\t\t}\n\n\t\tprintResourceList := func(resourceList corev1.ResourceList) {\n\t\t\tresources := make([]corev1.ResourceName, 0, len(resourceList))\n\t\t\tfor resource := range resourceList {\n\t\t\t\tresources = append(resources, resource)\n\t\t\t}\n\t\t\tsort.Sort(SortableResourceNames(resources))\n\t\t\tfor _, resource := range resources {\n\t\t\t\tvalue := resourceList[resource]\n\t\t\t\tw.Write(LEVEL_0, \" %s:\\t%s\\n\", resource, value.String())\n\t\t\t}\n\t\t}\n\n\t\tif len(node.Status.Capacity) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"Capacity:\\n\")\n\t\t\tprintResourceList(node.Status.Capacity)\n\t\t}\n\t\tif len(node.Status.Allocatable) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"Allocatable:\\n\")\n\t\t\tprintResourceList(node.Status.Allocatable)\n\t\t}\n\n\t\tw.Write(LEVEL_0, \"System Info:\\n\")\n\t\tw.Write(LEVEL_0, \" Machine ID:\\t%s\\n\", node.Status.NodeInfo.MachineID)\n\t\tw.Write(LEVEL_0, \" System UUID:\\t%s\\n\", node.Status.NodeInfo.SystemUUID)\n\t\tw.Write(LEVEL_0, \" Boot ID:\\t%s\\n\", node.Status.NodeInfo.BootID)\n\t\tw.Write(LEVEL_0, \" Kernel Version:\\t%s\\n\", node.Status.NodeInfo.KernelVersion)\n\t\tw.Write(LEVEL_0, \" OS Image:\\t%s\\n\", node.Status.NodeInfo.OSImage)\n\t\tw.Write(LEVEL_0, \" Operating System:\\t%s\\n\", node.Status.NodeInfo.OperatingSystem)\n\t\tw.Write(LEVEL_0, \" Architecture:\\t%s\\n\", node.Status.NodeInfo.Architecture)\n\t\tw.Write(LEVEL_0, \" Container Runtime Version:\\t%s\\n\", node.Status.NodeInfo.ContainerRuntimeVersion)\n\t\tw.Write(LEVEL_0, \" Kubelet Version:\\t%s\\n\", node.Status.NodeInfo.KubeletVersion)\n\t\tw.Write(LEVEL_0, \" Kube-Proxy Version:\\t%s\\n\", node.Status.NodeInfo.KubeProxyVersion)\n\n\t\t// remove when .PodCIDR is depreciated\n\t\tif len(node.Spec.PodCIDR) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"PodCIDR:\\t%s\\n\", node.Spec.PodCIDR)\n\t\t}\n\n\t\tif len(node.Spec.PodCIDRs) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"PodCIDRs:\\t%s\\n\", strings.Join(node.Spec.PodCIDRs, \",\"))\n\t\t}\n\t\tif len(node.Spec.ProviderID) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"ProviderID:\\t%s\\n\", node.Spec.ProviderID)\n\t\t}\n\t\tif canViewPods \u0026\u0026 nodeNonTerminatedPodsList != nil {\n\t\t\tdescribeNodeResource(nodeNonTerminatedPodsList, node, w)\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"Pods:\\tnot authorized\\n\")\n\t\t}\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":3618,"to":3715}} {"id":100032502,"name":"describeNodeLease","signature":"func describeNodeLease(lease *coordinationv1.Lease, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeNodeLease(lease *coordinationv1.Lease, w PrefixWriter) {\n\tw.Write(LEVEL_0, \"Lease:\\n\")\n\tholderIdentity := \"\u003cunset\u003e\"\n\tif lease != nil \u0026\u0026 lease.Spec.HolderIdentity != nil {\n\t\tholderIdentity = *lease.Spec.HolderIdentity\n\t}\n\tw.Write(LEVEL_1, \"HolderIdentity:\\t%s\\n\", holderIdentity)\n\tacquireTime := \"\u003cunset\u003e\"\n\tif lease != nil \u0026\u0026 lease.Spec.AcquireTime != nil {\n\t\tacquireTime = lease.Spec.AcquireTime.Time.Format(time.RFC1123Z)\n\t}\n\tw.Write(LEVEL_1, \"AcquireTime:\\t%s\\n\", acquireTime)\n\trenewTime := \"\u003cunset\u003e\"\n\tif lease != nil \u0026\u0026 lease.Spec.RenewTime != nil {\n\t\trenewTime = lease.Spec.RenewTime.Time.Format(time.RFC1123Z)\n\t}\n\tw.Write(LEVEL_1, \"RenewTime:\\t%s\\n\", renewTime)\n}","line":{"from":3717,"to":3734}} {"id":100032503,"name":"Describe","signature":"func (p *StatefulSetDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (p *StatefulSetDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tps, err := p.client.AppsV1().StatefulSets(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tpc := p.client.CoreV1().Pods(namespace)\n\n\tselector, err := metav1.LabelSelectorAsSelector(ps.Spec.Selector)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\trunning, waiting, succeeded, failed, err := getPodStatusForController(pc, selector, ps.UID, describerSettings)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar events *corev1.EventList\n\tif describerSettings.ShowEvents {\n\t\tevents, _ = searchEvents(p.client.CoreV1(), ps, describerSettings.ChunkSize)\n\t}\n\n\treturn describeStatefulSet(ps, selector, events, running, waiting, succeeded, failed)\n}","line":{"from":3740,"to":3763}} {"id":100032504,"name":"describeStatefulSet","signature":"func describeStatefulSet(ps *appsv1.StatefulSet, selector labels.Selector, events *corev1.EventList, running, waiting, succeeded, failed int) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeStatefulSet(ps *appsv1.StatefulSet, selector labels.Selector, events *corev1.EventList, running, waiting, succeeded, failed int) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", ps.ObjectMeta.Name)\n\t\tw.Write(LEVEL_0, \"Namespace:\\t%s\\n\", ps.ObjectMeta.Namespace)\n\t\tw.Write(LEVEL_0, \"CreationTimestamp:\\t%s\\n\", ps.CreationTimestamp.Time.Format(time.RFC1123Z))\n\t\tw.Write(LEVEL_0, \"Selector:\\t%s\\n\", selector)\n\t\tprintLabelsMultiline(w, \"Labels\", ps.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", ps.Annotations)\n\t\tw.Write(LEVEL_0, \"Replicas:\\t%d desired | %d total\\n\", *ps.Spec.Replicas, ps.Status.Replicas)\n\t\tw.Write(LEVEL_0, \"Update Strategy:\\t%s\\n\", ps.Spec.UpdateStrategy.Type)\n\t\tif ps.Spec.UpdateStrategy.RollingUpdate != nil {\n\t\t\tru := ps.Spec.UpdateStrategy.RollingUpdate\n\t\t\tif ru.Partition != nil {\n\t\t\t\tw.Write(LEVEL_1, \"Partition:\\t%d\\n\", *ru.Partition)\n\t\t\t\tif ru.MaxUnavailable != nil {\n\t\t\t\t\tw.Write(LEVEL_1, \"MaxUnavailable:\\t%s\\n\", ru.MaxUnavailable.String())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tw.Write(LEVEL_0, \"Pods Status:\\t%d Running / %d Waiting / %d Succeeded / %d Failed\\n\", running, waiting, succeeded, failed)\n\t\tDescribePodTemplate(\u0026ps.Spec.Template, w)\n\t\tdescribeVolumeClaimTemplates(ps.Spec.VolumeClaimTemplates, w)\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\n\t\treturn nil\n\t})\n}","line":{"from":3765,"to":3795}} {"id":100032505,"name":"Describe","signature":"func (p *CertificateSigningRequestDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (p *CertificateSigningRequestDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\n\tvar (\n\t\tcrBytes []byte\n\t\tmetadata metav1.ObjectMeta\n\t\tstatus string\n\t\tsignerName string\n\t\texpirationSeconds *int32\n\t\tusername string\n\t\tevents *corev1.EventList\n\t)\n\n\tif csr, err := p.client.CertificatesV1().CertificateSigningRequests().Get(context.TODO(), name, metav1.GetOptions{}); err == nil {\n\t\tcrBytes = csr.Spec.Request\n\t\tmetadata = csr.ObjectMeta\n\t\tconditionTypes := []string{}\n\t\tfor _, c := range csr.Status.Conditions {\n\t\t\tconditionTypes = append(conditionTypes, string(c.Type))\n\t\t}\n\t\tstatus = extractCSRStatus(conditionTypes, csr.Status.Certificate)\n\t\tsignerName = csr.Spec.SignerName\n\t\texpirationSeconds = csr.Spec.ExpirationSeconds\n\t\tusername = csr.Spec.Username\n\t\tif describerSettings.ShowEvents {\n\t\t\tevents, _ = searchEvents(p.client.CoreV1(), csr, describerSettings.ChunkSize)\n\t\t}\n\t} else if csr, err := p.client.CertificatesV1beta1().CertificateSigningRequests().Get(context.TODO(), name, metav1.GetOptions{}); err == nil {\n\t\tcrBytes = csr.Spec.Request\n\t\tmetadata = csr.ObjectMeta\n\t\tconditionTypes := []string{}\n\t\tfor _, c := range csr.Status.Conditions {\n\t\t\tconditionTypes = append(conditionTypes, string(c.Type))\n\t\t}\n\t\tstatus = extractCSRStatus(conditionTypes, csr.Status.Certificate)\n\t\tif csr.Spec.SignerName != nil {\n\t\t\tsignerName = *csr.Spec.SignerName\n\t\t}\n\t\texpirationSeconds = csr.Spec.ExpirationSeconds\n\t\tusername = csr.Spec.Username\n\t\tif describerSettings.ShowEvents {\n\t\t\tevents, _ = searchEvents(p.client.CoreV1(), csr, describerSettings.ChunkSize)\n\t\t}\n\t} else {\n\t\treturn \"\", err\n\t}\n\n\tcr, err := certificate.ParseCSR(crBytes)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Error parsing CSR: %v\", err)\n\t}\n\n\treturn describeCertificateSigningRequest(metadata, signerName, expirationSeconds, username, cr, status, events)\n}","line":{"from":3801,"to":3853}} {"id":100032506,"name":"describeCertificateSigningRequest","signature":"func describeCertificateSigningRequest(csr metav1.ObjectMeta, signerName string, expirationSeconds *int32, username string, cr *x509.CertificateRequest, status string, events *corev1.EventList) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeCertificateSigningRequest(csr metav1.ObjectMeta, signerName string, expirationSeconds *int32, username string, cr *x509.CertificateRequest, status string, events *corev1.EventList) (string, error) {\n\tprintListHelper := func(w PrefixWriter, prefix, name string, values []string) {\n\t\tif len(values) == 0 {\n\t\t\treturn\n\t\t}\n\t\tw.Write(LEVEL_0, prefix+name+\":\\t\")\n\t\tw.Write(LEVEL_0, strings.Join(values, \"\\n\"+prefix+\"\\t\"))\n\t\tw.Write(LEVEL_0, \"\\n\")\n\t}\n\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", csr.Name)\n\t\tw.Write(LEVEL_0, \"Labels:\\t%s\\n\", labels.FormatLabels(csr.Labels))\n\t\tw.Write(LEVEL_0, \"Annotations:\\t%s\\n\", labels.FormatLabels(csr.Annotations))\n\t\tw.Write(LEVEL_0, \"CreationTimestamp:\\t%s\\n\", csr.CreationTimestamp.Time.Format(time.RFC1123Z))\n\t\tw.Write(LEVEL_0, \"Requesting User:\\t%s\\n\", username)\n\t\tif len(signerName) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"Signer:\\t%s\\n\", signerName)\n\t\t}\n\t\tif expirationSeconds != nil {\n\t\t\tw.Write(LEVEL_0, \"Requested Duration:\\t%s\\n\", duration.HumanDuration(utilcsr.ExpirationSecondsToDuration(*expirationSeconds)))\n\t\t}\n\t\tw.Write(LEVEL_0, \"Status:\\t%s\\n\", status)\n\n\t\tw.Write(LEVEL_0, \"Subject:\\n\")\n\t\tw.Write(LEVEL_0, \"\\tCommon Name:\\t%s\\n\", cr.Subject.CommonName)\n\t\tw.Write(LEVEL_0, \"\\tSerial Number:\\t%s\\n\", cr.Subject.SerialNumber)\n\t\tprintListHelper(w, \"\\t\", \"Organization\", cr.Subject.Organization)\n\t\tprintListHelper(w, \"\\t\", \"Organizational Unit\", cr.Subject.OrganizationalUnit)\n\t\tprintListHelper(w, \"\\t\", \"Country\", cr.Subject.Country)\n\t\tprintListHelper(w, \"\\t\", \"Locality\", cr.Subject.Locality)\n\t\tprintListHelper(w, \"\\t\", \"Province\", cr.Subject.Province)\n\t\tprintListHelper(w, \"\\t\", \"StreetAddress\", cr.Subject.StreetAddress)\n\t\tprintListHelper(w, \"\\t\", \"PostalCode\", cr.Subject.PostalCode)\n\n\t\tif len(cr.DNSNames)+len(cr.EmailAddresses)+len(cr.IPAddresses)+len(cr.URIs) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"Subject Alternative Names:\\n\")\n\t\t\tprintListHelper(w, \"\\t\", \"DNS Names\", cr.DNSNames)\n\t\t\tprintListHelper(w, \"\\t\", \"Email Addresses\", cr.EmailAddresses)\n\t\t\tvar uris []string\n\t\t\tfor _, uri := range cr.URIs {\n\t\t\t\turis = append(uris, uri.String())\n\t\t\t}\n\t\t\tprintListHelper(w, \"\\t\", \"URIs\", uris)\n\t\t\tvar ipaddrs []string\n\t\t\tfor _, ipaddr := range cr.IPAddresses {\n\t\t\t\tipaddrs = append(ipaddrs, ipaddr.String())\n\t\t\t}\n\t\t\tprintListHelper(w, \"\\t\", \"IP Addresses\", ipaddrs)\n\t\t}\n\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\n\t\treturn nil\n\t})\n}","line":{"from":3855,"to":3913}} {"id":100032507,"name":"Describe","signature":"func (d *HorizontalPodAutoscalerDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (d *HorizontalPodAutoscalerDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tvar events *corev1.EventList\n\n\t// autoscaling/v2 is introduced since v1.23 and autoscaling/v1 does not have full backward compatibility\n\t// with autoscaling/v2, so describer will try to get and describe hpa v2 object firstly, if it fails,\n\t// describer will fall back to do with hpa v1 object\n\thpaV2, err := d.client.AutoscalingV2().HorizontalPodAutoscalers(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\tif err == nil {\n\t\tif describerSettings.ShowEvents {\n\t\t\tevents, _ = searchEvents(d.client.CoreV1(), hpaV2, describerSettings.ChunkSize)\n\t\t}\n\t\treturn describeHorizontalPodAutoscalerV2(hpaV2, events, d)\n\t}\n\n\thpaV1, err := d.client.AutoscalingV1().HorizontalPodAutoscalers(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\tif err == nil {\n\t\tif describerSettings.ShowEvents {\n\t\t\tevents, _ = searchEvents(d.client.CoreV1(), hpaV1, describerSettings.ChunkSize)\n\t\t}\n\t\treturn describeHorizontalPodAutoscalerV1(hpaV1, events, d)\n\t}\n\n\treturn \"\", err\n}","line":{"from":3920,"to":3943}} {"id":100032508,"name":"describeHorizontalPodAutoscalerV2","signature":"func describeHorizontalPodAutoscalerV2(hpa *autoscalingv2.HorizontalPodAutoscaler, events *corev1.EventList, d *HorizontalPodAutoscalerDescriber) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeHorizontalPodAutoscalerV2(hpa *autoscalingv2.HorizontalPodAutoscaler, events *corev1.EventList, d *HorizontalPodAutoscalerDescriber) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", hpa.Name)\n\t\tw.Write(LEVEL_0, \"Namespace:\\t%s\\n\", hpa.Namespace)\n\t\tprintLabelsMultiline(w, \"Labels\", hpa.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", hpa.Annotations)\n\t\tw.Write(LEVEL_0, \"CreationTimestamp:\\t%s\\n\", hpa.CreationTimestamp.Time.Format(time.RFC1123Z))\n\t\tw.Write(LEVEL_0, \"Reference:\\t%s/%s\\n\",\n\t\t\thpa.Spec.ScaleTargetRef.Kind,\n\t\t\thpa.Spec.ScaleTargetRef.Name)\n\t\tw.Write(LEVEL_0, \"Metrics:\\t( current / target )\\n\")\n\t\tfor i, metric := range hpa.Spec.Metrics {\n\t\t\tswitch metric.Type {\n\t\t\tcase autoscalingv2.ExternalMetricSourceType:\n\t\t\t\tif metric.External.Target.AverageValue != nil {\n\t\t\t\t\tcurrent := \"\u003cunknown\u003e\"\n\t\t\t\t\tif len(hpa.Status.CurrentMetrics) \u003e i \u0026\u0026 hpa.Status.CurrentMetrics[i].External != nil \u0026\u0026\n\t\t\t\t\t\thpa.Status.CurrentMetrics[i].External.Current.AverageValue != nil {\n\t\t\t\t\t\tcurrent = hpa.Status.CurrentMetrics[i].External.Current.AverageValue.String()\n\t\t\t\t\t}\n\t\t\t\t\tw.Write(LEVEL_1, \"%q (target average value):\\t%s / %s\\n\", metric.External.Metric.Name, current, metric.External.Target.AverageValue.String())\n\t\t\t\t} else {\n\t\t\t\t\tcurrent := \"\u003cunknown\u003e\"\n\t\t\t\t\tif len(hpa.Status.CurrentMetrics) \u003e i \u0026\u0026 hpa.Status.CurrentMetrics[i].External != nil {\n\t\t\t\t\t\tcurrent = hpa.Status.CurrentMetrics[i].External.Current.Value.String()\n\t\t\t\t\t}\n\t\t\t\t\tw.Write(LEVEL_1, \"%q (target value):\\t%s / %s\\n\", metric.External.Metric.Name, current, metric.External.Target.Value.String())\n\n\t\t\t\t}\n\t\t\tcase autoscalingv2.PodsMetricSourceType:\n\t\t\t\tcurrent := \"\u003cunknown\u003e\"\n\t\t\t\tif len(hpa.Status.CurrentMetrics) \u003e i \u0026\u0026 hpa.Status.CurrentMetrics[i].Pods != nil {\n\t\t\t\t\tcurrent = hpa.Status.CurrentMetrics[i].Pods.Current.AverageValue.String()\n\t\t\t\t}\n\t\t\t\tw.Write(LEVEL_1, \"%q on pods:\\t%s / %s\\n\", metric.Pods.Metric.Name, current, metric.Pods.Target.AverageValue.String())\n\t\t\tcase autoscalingv2.ObjectMetricSourceType:\n\t\t\t\tw.Write(LEVEL_1, \"\\\"%s\\\" on %s/%s \", metric.Object.Metric.Name, metric.Object.DescribedObject.Kind, metric.Object.DescribedObject.Name)\n\t\t\t\tif metric.Object.Target.Type == autoscalingv2.AverageValueMetricType {\n\t\t\t\t\tcurrent := \"\u003cunknown\u003e\"\n\t\t\t\t\tif len(hpa.Status.CurrentMetrics) \u003e i \u0026\u0026 hpa.Status.CurrentMetrics[i].Object != nil {\n\t\t\t\t\t\tcurrent = hpa.Status.CurrentMetrics[i].Object.Current.AverageValue.String()\n\t\t\t\t\t}\n\t\t\t\t\tw.Write(LEVEL_0, \"(target average value):\\t%s / %s\\n\", current, metric.Object.Target.AverageValue.String())\n\t\t\t\t} else {\n\t\t\t\t\tcurrent := \"\u003cunknown\u003e\"\n\t\t\t\t\tif len(hpa.Status.CurrentMetrics) \u003e i \u0026\u0026 hpa.Status.CurrentMetrics[i].Object != nil {\n\t\t\t\t\t\tcurrent = hpa.Status.CurrentMetrics[i].Object.Current.Value.String()\n\t\t\t\t\t}\n\t\t\t\t\tw.Write(LEVEL_0, \"(target value):\\t%s / %s\\n\", current, metric.Object.Target.Value.String())\n\t\t\t\t}\n\t\t\tcase autoscalingv2.ResourceMetricSourceType:\n\t\t\t\tw.Write(LEVEL_1, \"resource %s on pods\", string(metric.Resource.Name))\n\t\t\t\tif metric.Resource.Target.AverageValue != nil {\n\t\t\t\t\tcurrent := \"\u003cunknown\u003e\"\n\t\t\t\t\tif len(hpa.Status.CurrentMetrics) \u003e i \u0026\u0026 hpa.Status.CurrentMetrics[i].Resource != nil {\n\t\t\t\t\t\tcurrent = hpa.Status.CurrentMetrics[i].Resource.Current.AverageValue.String()\n\t\t\t\t\t}\n\t\t\t\t\tw.Write(LEVEL_0, \":\\t%s / %s\\n\", current, metric.Resource.Target.AverageValue.String())\n\t\t\t\t} else {\n\t\t\t\t\tcurrent := \"\u003cunknown\u003e\"\n\t\t\t\t\tif len(hpa.Status.CurrentMetrics) \u003e i \u0026\u0026 hpa.Status.CurrentMetrics[i].Resource != nil \u0026\u0026 hpa.Status.CurrentMetrics[i].Resource.Current.AverageUtilization != nil {\n\t\t\t\t\t\tcurrent = fmt.Sprintf(\"%d%% (%s)\", *hpa.Status.CurrentMetrics[i].Resource.Current.AverageUtilization, hpa.Status.CurrentMetrics[i].Resource.Current.AverageValue.String())\n\t\t\t\t\t}\n\n\t\t\t\t\ttarget := \"\u003cauto\u003e\"\n\t\t\t\t\tif metric.Resource.Target.AverageUtilization != nil {\n\t\t\t\t\t\ttarget = fmt.Sprintf(\"%d%%\", *metric.Resource.Target.AverageUtilization)\n\t\t\t\t\t}\n\t\t\t\t\tw.Write(LEVEL_1, \"(as a percentage of request):\\t%s / %s\\n\", current, target)\n\t\t\t\t}\n\t\t\tcase autoscalingv2.ContainerResourceMetricSourceType:\n\t\t\t\tw.Write(LEVEL_1, \"resource %s of container \\\"%s\\\" on pods\", string(metric.ContainerResource.Name), metric.ContainerResource.Container)\n\t\t\t\tif metric.ContainerResource.Target.AverageValue != nil {\n\t\t\t\t\tcurrent := \"\u003cunknown\u003e\"\n\t\t\t\t\tif len(hpa.Status.CurrentMetrics) \u003e i \u0026\u0026 hpa.Status.CurrentMetrics[i].ContainerResource != nil {\n\t\t\t\t\t\tcurrent = hpa.Status.CurrentMetrics[i].ContainerResource.Current.AverageValue.String()\n\t\t\t\t\t}\n\t\t\t\t\tw.Write(LEVEL_0, \":\\t%s / %s\\n\", current, metric.ContainerResource.Target.AverageValue.String())\n\t\t\t\t} else {\n\t\t\t\t\tcurrent := \"\u003cunknown\u003e\"\n\t\t\t\t\tif len(hpa.Status.CurrentMetrics) \u003e i \u0026\u0026 hpa.Status.CurrentMetrics[i].ContainerResource != nil \u0026\u0026 hpa.Status.CurrentMetrics[i].ContainerResource.Current.AverageUtilization != nil {\n\t\t\t\t\t\tcurrent = fmt.Sprintf(\"%d%% (%s)\", *hpa.Status.CurrentMetrics[i].ContainerResource.Current.AverageUtilization, hpa.Status.CurrentMetrics[i].ContainerResource.Current.AverageValue.String())\n\t\t\t\t\t}\n\n\t\t\t\t\ttarget := \"\u003cauto\u003e\"\n\t\t\t\t\tif metric.ContainerResource.Target.AverageUtilization != nil {\n\t\t\t\t\t\ttarget = fmt.Sprintf(\"%d%%\", *metric.ContainerResource.Target.AverageUtilization)\n\t\t\t\t\t}\n\t\t\t\t\tw.Write(LEVEL_1, \"(as a percentage of request):\\t%s / %s\\n\", current, target)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tw.Write(LEVEL_1, \"\u003cunknown metric type %q\u003e\\n\", string(metric.Type))\n\t\t\t}\n\t\t}\n\t\tminReplicas := \"\u003cunset\u003e\"\n\t\tif hpa.Spec.MinReplicas != nil {\n\t\t\tminReplicas = fmt.Sprintf(\"%d\", *hpa.Spec.MinReplicas)\n\t\t}\n\t\tw.Write(LEVEL_0, \"Min replicas:\\t%s\\n\", minReplicas)\n\t\tw.Write(LEVEL_0, \"Max replicas:\\t%d\\n\", hpa.Spec.MaxReplicas)\n\t\t// only print the hpa behavior if present\n\t\tif hpa.Spec.Behavior != nil {\n\t\t\tw.Write(LEVEL_0, \"Behavior:\\n\")\n\t\t\tprintDirectionBehavior(w, \"Scale Up\", hpa.Spec.Behavior.ScaleUp)\n\t\t\tprintDirectionBehavior(w, \"Scale Down\", hpa.Spec.Behavior.ScaleDown)\n\t\t}\n\t\tw.Write(LEVEL_0, \"%s pods:\\t\", hpa.Spec.ScaleTargetRef.Kind)\n\t\tw.Write(LEVEL_0, \"%d current / %d desired\\n\", hpa.Status.CurrentReplicas, hpa.Status.DesiredReplicas)\n\n\t\tif len(hpa.Status.Conditions) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"Conditions:\\n\")\n\t\t\tw.Write(LEVEL_1, \"Type\\tStatus\\tReason\\tMessage\\n\")\n\t\t\tw.Write(LEVEL_1, \"----\\t------\\t------\\t-------\\n\")\n\t\t\tfor _, c := range hpa.Status.Conditions {\n\t\t\t\tw.Write(LEVEL_1, \"%v\\t%v\\t%v\\t%v\\n\", c.Type, c.Status, c.Reason, c.Message)\n\t\t\t}\n\t\t}\n\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\n\t\treturn nil\n\t})\n}","line":{"from":3945,"to":4070}} {"id":100032509,"name":"printDirectionBehavior","signature":"func printDirectionBehavior(w PrefixWriter, direction string, rules *autoscalingv2.HPAScalingRules)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printDirectionBehavior(w PrefixWriter, direction string, rules *autoscalingv2.HPAScalingRules) {\n\tif rules != nil {\n\t\tw.Write(LEVEL_1, \"%s:\\n\", direction)\n\t\tif rules.StabilizationWindowSeconds != nil {\n\t\t\tw.Write(LEVEL_2, \"Stabilization Window: %d seconds\\n\", *rules.StabilizationWindowSeconds)\n\t\t}\n\t\tif len(rules.Policies) \u003e 0 {\n\t\t\tif rules.SelectPolicy != nil {\n\t\t\t\tw.Write(LEVEL_2, \"Select Policy: %s\\n\", *rules.SelectPolicy)\n\t\t\t} else {\n\t\t\t\tw.Write(LEVEL_2, \"Select Policy: %s\\n\", autoscalingv2.MaxChangePolicySelect)\n\t\t\t}\n\t\t\tw.Write(LEVEL_2, \"Policies:\\n\")\n\t\t\tfor _, p := range rules.Policies {\n\t\t\t\tw.Write(LEVEL_3, \"- Type: %s\\tValue: %d\\tPeriod: %d seconds\\n\", p.Type, p.Value, p.PeriodSeconds)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":4072,"to":4090}} {"id":100032510,"name":"describeHorizontalPodAutoscalerV1","signature":"func describeHorizontalPodAutoscalerV1(hpa *autoscalingv1.HorizontalPodAutoscaler, events *corev1.EventList, d *HorizontalPodAutoscalerDescriber) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeHorizontalPodAutoscalerV1(hpa *autoscalingv1.HorizontalPodAutoscaler, events *corev1.EventList, d *HorizontalPodAutoscalerDescriber) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", hpa.Name)\n\t\tw.Write(LEVEL_0, \"Namespace:\\t%s\\n\", hpa.Namespace)\n\t\tprintLabelsMultiline(w, \"Labels\", hpa.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", hpa.Annotations)\n\t\tw.Write(LEVEL_0, \"CreationTimestamp:\\t%s\\n\", hpa.CreationTimestamp.Time.Format(time.RFC1123Z))\n\t\tw.Write(LEVEL_0, \"Reference:\\t%s/%s\\n\",\n\t\t\thpa.Spec.ScaleTargetRef.Kind,\n\t\t\thpa.Spec.ScaleTargetRef.Name)\n\n\t\tif hpa.Spec.TargetCPUUtilizationPercentage != nil {\n\t\t\tw.Write(LEVEL_0, \"Target CPU utilization:\\t%d%%\\n\", *hpa.Spec.TargetCPUUtilizationPercentage)\n\t\t\tcurrent := \"\u003cunknown\u003e\"\n\t\t\tif hpa.Status.CurrentCPUUtilizationPercentage != nil {\n\t\t\t\tcurrent = fmt.Sprintf(\"%d\", *hpa.Status.CurrentCPUUtilizationPercentage)\n\t\t\t}\n\t\t\tw.Write(LEVEL_0, \"Current CPU utilization:\\t%s%%\\n\", current)\n\t\t}\n\n\t\tminReplicas := \"\u003cunset\u003e\"\n\t\tif hpa.Spec.MinReplicas != nil {\n\t\t\tminReplicas = fmt.Sprintf(\"%d\", *hpa.Spec.MinReplicas)\n\t\t}\n\t\tw.Write(LEVEL_0, \"Min replicas:\\t%s\\n\", minReplicas)\n\t\tw.Write(LEVEL_0, \"Max replicas:\\t%d\\n\", hpa.Spec.MaxReplicas)\n\t\tw.Write(LEVEL_0, \"%s pods:\\t\", hpa.Spec.ScaleTargetRef.Kind)\n\t\tw.Write(LEVEL_0, \"%d current / %d desired\\n\", hpa.Status.CurrentReplicas, hpa.Status.DesiredReplicas)\n\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\n\t\treturn nil\n\t})\n}","line":{"from":4092,"to":4128}} {"id":100032511,"name":"describeNodeResource","signature":"func describeNodeResource(nodeNonTerminatedPodsList *corev1.PodList, node *corev1.Node, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeNodeResource(nodeNonTerminatedPodsList *corev1.PodList, node *corev1.Node, w PrefixWriter) {\n\tw.Write(LEVEL_0, \"Non-terminated Pods:\\t(%d in total)\\n\", len(nodeNonTerminatedPodsList.Items))\n\tw.Write(LEVEL_1, \"Namespace\\tName\\t\\tCPU Requests\\tCPU Limits\\tMemory Requests\\tMemory Limits\\tAge\\n\")\n\tw.Write(LEVEL_1, \"---------\\t----\\t\\t------------\\t----------\\t---------------\\t-------------\\t---\\n\")\n\tallocatable := node.Status.Capacity\n\tif len(node.Status.Allocatable) \u003e 0 {\n\t\tallocatable = node.Status.Allocatable\n\t}\n\n\tfor _, pod := range nodeNonTerminatedPodsList.Items {\n\t\treq, limit := resourcehelper.PodRequestsAndLimits(\u0026pod)\n\t\tcpuReq, cpuLimit, memoryReq, memoryLimit := req[corev1.ResourceCPU], limit[corev1.ResourceCPU], req[corev1.ResourceMemory], limit[corev1.ResourceMemory]\n\t\tfractionCpuReq := float64(cpuReq.MilliValue()) / float64(allocatable.Cpu().MilliValue()) * 100\n\t\tfractionCpuLimit := float64(cpuLimit.MilliValue()) / float64(allocatable.Cpu().MilliValue()) * 100\n\t\tfractionMemoryReq := float64(memoryReq.Value()) / float64(allocatable.Memory().Value()) * 100\n\t\tfractionMemoryLimit := float64(memoryLimit.Value()) / float64(allocatable.Memory().Value()) * 100\n\t\tw.Write(LEVEL_1, \"%s\\t%s\\t\\t%s (%d%%)\\t%s (%d%%)\\t%s (%d%%)\\t%s (%d%%)\\t%s\\n\", pod.Namespace, pod.Name,\n\t\t\tcpuReq.String(), int64(fractionCpuReq), cpuLimit.String(), int64(fractionCpuLimit),\n\t\t\tmemoryReq.String(), int64(fractionMemoryReq), memoryLimit.String(), int64(fractionMemoryLimit), translateTimestampSince(pod.CreationTimestamp))\n\t}\n\n\tw.Write(LEVEL_0, \"Allocated resources:\\n (Total limits may be over 100 percent, i.e., overcommitted.)\\n\")\n\tw.Write(LEVEL_1, \"Resource\\tRequests\\tLimits\\n\")\n\tw.Write(LEVEL_1, \"--------\\t--------\\t------\\n\")\n\treqs, limits := getPodsTotalRequestsAndLimits(nodeNonTerminatedPodsList)\n\tcpuReqs, cpuLimits, memoryReqs, memoryLimits, ephemeralstorageReqs, ephemeralstorageLimits :=\n\t\treqs[corev1.ResourceCPU], limits[corev1.ResourceCPU], reqs[corev1.ResourceMemory], limits[corev1.ResourceMemory], reqs[corev1.ResourceEphemeralStorage], limits[corev1.ResourceEphemeralStorage]\n\tfractionCpuReqs := float64(0)\n\tfractionCpuLimits := float64(0)\n\tif allocatable.Cpu().MilliValue() != 0 {\n\t\tfractionCpuReqs = float64(cpuReqs.MilliValue()) / float64(allocatable.Cpu().MilliValue()) * 100\n\t\tfractionCpuLimits = float64(cpuLimits.MilliValue()) / float64(allocatable.Cpu().MilliValue()) * 100\n\t}\n\tfractionMemoryReqs := float64(0)\n\tfractionMemoryLimits := float64(0)\n\tif allocatable.Memory().Value() != 0 {\n\t\tfractionMemoryReqs = float64(memoryReqs.Value()) / float64(allocatable.Memory().Value()) * 100\n\t\tfractionMemoryLimits = float64(memoryLimits.Value()) / float64(allocatable.Memory().Value()) * 100\n\t}\n\tfractionEphemeralStorageReqs := float64(0)\n\tfractionEphemeralStorageLimits := float64(0)\n\tif allocatable.StorageEphemeral().Value() != 0 {\n\t\tfractionEphemeralStorageReqs = float64(ephemeralstorageReqs.Value()) / float64(allocatable.StorageEphemeral().Value()) * 100\n\t\tfractionEphemeralStorageLimits = float64(ephemeralstorageLimits.Value()) / float64(allocatable.StorageEphemeral().Value()) * 100\n\t}\n\tw.Write(LEVEL_1, \"%s\\t%s (%d%%)\\t%s (%d%%)\\n\",\n\t\tcorev1.ResourceCPU, cpuReqs.String(), int64(fractionCpuReqs), cpuLimits.String(), int64(fractionCpuLimits))\n\tw.Write(LEVEL_1, \"%s\\t%s (%d%%)\\t%s (%d%%)\\n\",\n\t\tcorev1.ResourceMemory, memoryReqs.String(), int64(fractionMemoryReqs), memoryLimits.String(), int64(fractionMemoryLimits))\n\tw.Write(LEVEL_1, \"%s\\t%s (%d%%)\\t%s (%d%%)\\n\",\n\t\tcorev1.ResourceEphemeralStorage, ephemeralstorageReqs.String(), int64(fractionEphemeralStorageReqs), ephemeralstorageLimits.String(), int64(fractionEphemeralStorageLimits))\n\n\textResources := make([]string, 0, len(allocatable))\n\thugePageResources := make([]string, 0, len(allocatable))\n\tfor resource := range allocatable {\n\t\tif resourcehelper.IsHugePageResourceName(resource) {\n\t\t\thugePageResources = append(hugePageResources, string(resource))\n\t\t} else if !resourcehelper.IsStandardContainerResourceName(string(resource)) \u0026\u0026 resource != corev1.ResourcePods {\n\t\t\textResources = append(extResources, string(resource))\n\t\t}\n\t}\n\n\tsort.Strings(extResources)\n\tsort.Strings(hugePageResources)\n\n\tfor _, resource := range hugePageResources {\n\t\thugePageSizeRequests, hugePageSizeLimits, hugePageSizeAllocable := reqs[corev1.ResourceName(resource)], limits[corev1.ResourceName(resource)], allocatable[corev1.ResourceName(resource)]\n\t\tfractionHugePageSizeRequests := float64(0)\n\t\tfractionHugePageSizeLimits := float64(0)\n\t\tif hugePageSizeAllocable.Value() != 0 {\n\t\t\tfractionHugePageSizeRequests = float64(hugePageSizeRequests.Value()) / float64(hugePageSizeAllocable.Value()) * 100\n\t\t\tfractionHugePageSizeLimits = float64(hugePageSizeLimits.Value()) / float64(hugePageSizeAllocable.Value()) * 100\n\t\t}\n\t\tw.Write(LEVEL_1, \"%s\\t%s (%d%%)\\t%s (%d%%)\\n\",\n\t\t\tresource, hugePageSizeRequests.String(), int64(fractionHugePageSizeRequests), hugePageSizeLimits.String(), int64(fractionHugePageSizeLimits))\n\t}\n\n\tfor _, ext := range extResources {\n\t\textRequests, extLimits := reqs[corev1.ResourceName(ext)], limits[corev1.ResourceName(ext)]\n\t\tw.Write(LEVEL_1, \"%s\\t%s\\t%s\\n\", ext, extRequests.String(), extLimits.String())\n\t}\n}","line":{"from":4130,"to":4211}} {"id":100032512,"name":"getPodsTotalRequestsAndLimits","signature":"func getPodsTotalRequestsAndLimits(podList *corev1.PodList) (reqs map[corev1.ResourceName]resource.Quantity, limits map[corev1.ResourceName]resource.Quantity)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func getPodsTotalRequestsAndLimits(podList *corev1.PodList) (reqs map[corev1.ResourceName]resource.Quantity, limits map[corev1.ResourceName]resource.Quantity) {\n\treqs, limits = map[corev1.ResourceName]resource.Quantity{}, map[corev1.ResourceName]resource.Quantity{}\n\tfor _, pod := range podList.Items {\n\t\tpodReqs, podLimits := resourcehelper.PodRequestsAndLimits(\u0026pod)\n\t\tfor podReqName, podReqValue := range podReqs {\n\t\t\tif value, ok := reqs[podReqName]; !ok {\n\t\t\t\treqs[podReqName] = podReqValue.DeepCopy()\n\t\t\t} else {\n\t\t\t\tvalue.Add(podReqValue)\n\t\t\t\treqs[podReqName] = value\n\t\t\t}\n\t\t}\n\t\tfor podLimitName, podLimitValue := range podLimits {\n\t\t\tif value, ok := limits[podLimitName]; !ok {\n\t\t\t\tlimits[podLimitName] = podLimitValue.DeepCopy()\n\t\t\t} else {\n\t\t\t\tvalue.Add(podLimitValue)\n\t\t\t\tlimits[podLimitName] = value\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}","line":{"from":4213,"to":4235}} {"id":100032513,"name":"DescribeEvents","signature":"func DescribeEvents(el *corev1.EventList, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func DescribeEvents(el *corev1.EventList, w PrefixWriter) {\n\tif len(el.Items) == 0 {\n\t\tw.Write(LEVEL_0, \"Events:\\t\u003cnone\u003e\\n\")\n\t\treturn\n\t}\n\tw.Flush()\n\tsort.Sort(event.SortableEvents(el.Items))\n\tw.Write(LEVEL_0, \"Events:\\n Type\\tReason\\tAge\\tFrom\\tMessage\\n\")\n\tw.Write(LEVEL_1, \"----\\t------\\t----\\t----\\t-------\\n\")\n\tfor _, e := range el.Items {\n\t\tvar interval string\n\t\tfirstTimestampSince := translateMicroTimestampSince(e.EventTime)\n\t\tif e.EventTime.IsZero() {\n\t\t\tfirstTimestampSince = translateTimestampSince(e.FirstTimestamp)\n\t\t}\n\t\tif e.Series != nil {\n\t\t\tinterval = fmt.Sprintf(\"%s (x%d over %s)\", translateMicroTimestampSince(e.Series.LastObservedTime), e.Series.Count, firstTimestampSince)\n\t\t} else if e.Count \u003e 1 {\n\t\t\tinterval = fmt.Sprintf(\"%s (x%d over %s)\", translateTimestampSince(e.LastTimestamp), e.Count, firstTimestampSince)\n\t\t} else {\n\t\t\tinterval = firstTimestampSince\n\t\t}\n\t\tsource := e.Source.Component\n\t\tif source == \"\" {\n\t\t\tsource = e.ReportingController\n\t\t}\n\t\tw.Write(LEVEL_1, \"%v\\t%v\\t%s\\t%v\\t%v\\n\",\n\t\t\te.Type,\n\t\t\te.Reason,\n\t\t\tinterval,\n\t\t\tsource,\n\t\t\tstrings.TrimSpace(e.Message),\n\t\t)\n\t}\n}","line":{"from":4237,"to":4271}} {"id":100032514,"name":"Describe","signature":"func (dd *DeploymentDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (dd *DeploymentDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\td, err := dd.client.AppsV1().Deployments(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar events *corev1.EventList\n\tif describerSettings.ShowEvents {\n\t\tevents, _ = searchEvents(dd.client.CoreV1(), d, describerSettings.ChunkSize)\n\t}\n\n\tvar oldRSs, newRSs []*appsv1.ReplicaSet\n\tif _, oldResult, newResult, err := deploymentutil.GetAllReplicaSetsInChunks(d, dd.client.AppsV1(), describerSettings.ChunkSize); err == nil {\n\t\toldRSs = oldResult\n\t\tif newResult != nil {\n\t\t\tnewRSs = append(newRSs, newResult)\n\t\t}\n\t}\n\n\treturn describeDeployment(d, oldRSs, newRSs, events)\n}","line":{"from":4278,"to":4298}} {"id":100032515,"name":"describeDeployment","signature":"func describeDeployment(d *appsv1.Deployment, oldRSs []*appsv1.ReplicaSet, newRSs []*appsv1.ReplicaSet, events *corev1.EventList) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeDeployment(d *appsv1.Deployment, oldRSs []*appsv1.ReplicaSet, newRSs []*appsv1.ReplicaSet, events *corev1.EventList) (string, error) {\n\tselector, err := metav1.LabelSelectorAsSelector(d.Spec.Selector)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", d.ObjectMeta.Name)\n\t\tw.Write(LEVEL_0, \"Namespace:\\t%s\\n\", d.ObjectMeta.Namespace)\n\t\tw.Write(LEVEL_0, \"CreationTimestamp:\\t%s\\n\", d.CreationTimestamp.Time.Format(time.RFC1123Z))\n\t\tprintLabelsMultiline(w, \"Labels\", d.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", d.Annotations)\n\t\tw.Write(LEVEL_0, \"Selector:\\t%s\\n\", selector)\n\t\tw.Write(LEVEL_0, \"Replicas:\\t%d desired | %d updated | %d total | %d available | %d unavailable\\n\", *(d.Spec.Replicas), d.Status.UpdatedReplicas, d.Status.Replicas, d.Status.AvailableReplicas, d.Status.UnavailableReplicas)\n\t\tw.Write(LEVEL_0, \"StrategyType:\\t%s\\n\", d.Spec.Strategy.Type)\n\t\tw.Write(LEVEL_0, \"MinReadySeconds:\\t%d\\n\", d.Spec.MinReadySeconds)\n\t\tif d.Spec.Strategy.RollingUpdate != nil {\n\t\t\tru := d.Spec.Strategy.RollingUpdate\n\t\t\tw.Write(LEVEL_0, \"RollingUpdateStrategy:\\t%s max unavailable, %s max surge\\n\", ru.MaxUnavailable.String(), ru.MaxSurge.String())\n\t\t}\n\t\tDescribePodTemplate(\u0026d.Spec.Template, w)\n\t\tif len(d.Status.Conditions) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"Conditions:\\n Type\\tStatus\\tReason\\n\")\n\t\t\tw.Write(LEVEL_1, \"----\\t------\\t------\\n\")\n\t\t\tfor _, c := range d.Status.Conditions {\n\t\t\t\tw.Write(LEVEL_1, \"%v \\t%v\\t%v\\n\", c.Type, c.Status, c.Reason)\n\t\t\t}\n\t\t}\n\n\t\tif len(oldRSs) \u003e 0 || len(newRSs) \u003e 0 {\n\t\t\tw.Write(LEVEL_0, \"OldReplicaSets:\\t%s\\n\", printReplicaSetsByLabels(oldRSs))\n\t\t\tw.Write(LEVEL_0, \"NewReplicaSet:\\t%s\\n\", printReplicaSetsByLabels(newRSs))\n\t\t}\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\n\t\treturn nil\n\t})\n}","line":{"from":4300,"to":4339}} {"id":100032516,"name":"printReplicaSetsByLabels","signature":"func printReplicaSetsByLabels(matchingRSs []*appsv1.ReplicaSet) string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printReplicaSetsByLabels(matchingRSs []*appsv1.ReplicaSet) string {\n\t// Format the matching ReplicaSets into strings.\n\trsStrings := make([]string, 0, len(matchingRSs))\n\tfor _, rs := range matchingRSs {\n\t\trsStrings = append(rsStrings, fmt.Sprintf(\"%s (%d/%d replicas created)\", rs.Name, rs.Status.Replicas, *rs.Spec.Replicas))\n\t}\n\n\tlist := strings.Join(rsStrings, \", \")\n\tif list == \"\" {\n\t\treturn \"\u003cnone\u003e\"\n\t}\n\treturn list\n}","line":{"from":4341,"to":4353}} {"id":100032517,"name":"getPodStatusForController","signature":"func getPodStatusForController(c corev1client.PodInterface, selector labels.Selector, uid types.UID, settings DescriberSettings) (","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func getPodStatusForController(c corev1client.PodInterface, selector labels.Selector, uid types.UID, settings DescriberSettings) (\n\trunning, waiting, succeeded, failed int, err error) {\n\tinitialOpts := metav1.ListOptions{LabelSelector: selector.String(), Limit: settings.ChunkSize}\n\trcPods, err := getPodsInChunks(c, initialOpts)\n\tif err != nil {\n\t\treturn\n\t}\n\tfor _, pod := range rcPods.Items {\n\t\tcontrollerRef := metav1.GetControllerOf(\u0026pod)\n\t\t// Skip pods that are orphans or owned by other controllers.\n\t\tif controllerRef == nil || controllerRef.UID != uid {\n\t\t\tcontinue\n\t\t}\n\t\tswitch pod.Status.Phase {\n\t\tcase corev1.PodRunning:\n\t\t\trunning++\n\t\tcase corev1.PodPending:\n\t\t\twaiting++\n\t\tcase corev1.PodSucceeded:\n\t\t\tsucceeded++\n\t\tcase corev1.PodFailed:\n\t\t\tfailed++\n\t\t}\n\t}\n\treturn\n}","line":{"from":4355,"to":4380}} {"id":100032518,"name":"getPodsInChunks","signature":"func getPodsInChunks(c corev1client.PodInterface, initialOpts metav1.ListOptions) (*corev1.PodList, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func getPodsInChunks(c corev1client.PodInterface, initialOpts metav1.ListOptions) (*corev1.PodList, error) {\n\tpodList := \u0026corev1.PodList{}\n\terr := runtimeresource.FollowContinue(\u0026initialOpts,\n\t\tfunc(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\tnewList, err := c.List(context.TODO(), options)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, runtimeresource.EnhanceListError(err, options, corev1.ResourcePods.String())\n\t\t\t}\n\t\t\tpodList.Items = append(podList.Items, newList.Items...)\n\t\t\treturn newList, nil\n\t\t})\n\treturn podList, err\n}","line":{"from":4382,"to":4394}} {"id":100032519,"name":"Describe","signature":"func (d *ConfigMapDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (d *ConfigMapDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tc := d.CoreV1().ConfigMaps(namespace)\n\n\tconfigMap, err := c.Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", configMap.Name)\n\t\tw.Write(LEVEL_0, \"Namespace:\\t%s\\n\", configMap.Namespace)\n\t\tprintLabelsMultiline(w, \"Labels\", configMap.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", configMap.Annotations)\n\n\t\tw.Write(LEVEL_0, \"\\nData\\n====\\n\")\n\t\tfor k, v := range configMap.Data {\n\t\t\tw.Write(LEVEL_0, \"%s:\\n----\\n\", k)\n\t\t\tw.Write(LEVEL_0, \"%s\\n\", string(v))\n\t\t}\n\t\tw.Write(LEVEL_0, \"\\nBinaryData\\n====\\n\")\n\t\tfor k, v := range configMap.BinaryData {\n\t\t\tw.Write(LEVEL_0, \"%s: %s bytes\\n\", k, strconv.Itoa(len(v)))\n\t\t}\n\t\tw.Write(LEVEL_0, \"\\n\")\n\n\t\tif describerSettings.ShowEvents {\n\t\t\tevents, err := searchEvents(d.CoreV1(), configMap, describerSettings.ChunkSize)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif events != nil {\n\t\t\t\tDescribeEvents(events, w)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":4401,"to":4438}} {"id":100032520,"name":"Describe","signature":"func (d *NetworkPolicyDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (d *NetworkPolicyDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tc := d.NetworkingV1().NetworkPolicies(namespace)\n\n\tnetworkPolicy, err := c.Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn describeNetworkPolicy(networkPolicy)\n}","line":{"from":4445,"to":4454}} {"id":100032521,"name":"describeNetworkPolicy","signature":"func describeNetworkPolicy(networkPolicy *networkingv1.NetworkPolicy) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeNetworkPolicy(networkPolicy *networkingv1.NetworkPolicy) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", networkPolicy.Name)\n\t\tw.Write(LEVEL_0, \"Namespace:\\t%s\\n\", networkPolicy.Namespace)\n\t\tw.Write(LEVEL_0, \"Created on:\\t%s\\n\", networkPolicy.CreationTimestamp)\n\t\tprintLabelsMultiline(w, \"Labels\", networkPolicy.Labels)\n\t\tprintAnnotationsMultiline(w, \"Annotations\", networkPolicy.Annotations)\n\t\tdescribeNetworkPolicySpec(networkPolicy.Spec, w)\n\t\treturn nil\n\t})\n}","line":{"from":4456,"to":4467}} {"id":100032522,"name":"describeNetworkPolicySpec","signature":"func describeNetworkPolicySpec(nps networkingv1.NetworkPolicySpec, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeNetworkPolicySpec(nps networkingv1.NetworkPolicySpec, w PrefixWriter) {\n\tw.Write(LEVEL_0, \"Spec:\\n\")\n\tw.Write(LEVEL_1, \"PodSelector: \")\n\tif len(nps.PodSelector.MatchLabels) == 0 \u0026\u0026 len(nps.PodSelector.MatchExpressions) == 0 {\n\t\tw.Write(LEVEL_2, \"\u003cnone\u003e (Allowing the specific traffic to all pods in this namespace)\\n\")\n\t} else {\n\t\tw.Write(LEVEL_2, \"%s\\n\", metav1.FormatLabelSelector(\u0026nps.PodSelector))\n\t}\n\n\tingressEnabled, egressEnabled := getPolicyType(nps)\n\tif ingressEnabled {\n\t\tw.Write(LEVEL_1, \"Allowing ingress traffic:\\n\")\n\t\tprintNetworkPolicySpecIngressFrom(nps.Ingress, \" \", w)\n\t} else {\n\t\tw.Write(LEVEL_1, \"Not affecting ingress traffic\\n\")\n\t}\n\tif egressEnabled {\n\t\tw.Write(LEVEL_1, \"Allowing egress traffic:\\n\")\n\t\tprintNetworkPolicySpecEgressTo(nps.Egress, \" \", w)\n\t} else {\n\t\tw.Write(LEVEL_1, \"Not affecting egress traffic\\n\")\n\n\t}\n\tw.Write(LEVEL_1, \"Policy Types: %v\\n\", policyTypesToString(nps.PolicyTypes))\n}","line":{"from":4469,"to":4493}} {"id":100032523,"name":"getPolicyType","signature":"func getPolicyType(nps networkingv1.NetworkPolicySpec) (bool, bool)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func getPolicyType(nps networkingv1.NetworkPolicySpec) (bool, bool) {\n\tvar ingress, egress bool\n\tfor _, pt := range nps.PolicyTypes {\n\t\tswitch pt {\n\t\tcase networkingv1.PolicyTypeIngress:\n\t\t\tingress = true\n\t\tcase networkingv1.PolicyTypeEgress:\n\t\t\tegress = true\n\t\t}\n\t}\n\n\treturn ingress, egress\n}","line":{"from":4495,"to":4507}} {"id":100032524,"name":"printNetworkPolicySpecIngressFrom","signature":"func printNetworkPolicySpecIngressFrom(npirs []networkingv1.NetworkPolicyIngressRule, initialIndent string, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printNetworkPolicySpecIngressFrom(npirs []networkingv1.NetworkPolicyIngressRule, initialIndent string, w PrefixWriter) {\n\tif len(npirs) == 0 {\n\t\tw.Write(LEVEL_0, \"%s%s\\n\", initialIndent, \"\u003cnone\u003e (Selected pods are isolated for ingress connectivity)\")\n\t\treturn\n\t}\n\tfor i, npir := range npirs {\n\t\tif len(npir.Ports) == 0 {\n\t\t\tw.Write(LEVEL_0, \"%s%s\\n\", initialIndent, \"To Port: \u003cany\u003e (traffic allowed to all ports)\")\n\t\t} else {\n\t\t\tfor _, port := range npir.Ports {\n\t\t\t\tvar proto corev1.Protocol\n\t\t\t\tif port.Protocol != nil {\n\t\t\t\t\tproto = *port.Protocol\n\t\t\t\t} else {\n\t\t\t\t\tproto = corev1.ProtocolTCP\n\t\t\t\t}\n\t\t\t\tw.Write(LEVEL_0, \"%s%s: %s/%s\\n\", initialIndent, \"To Port\", port.Port, proto)\n\t\t\t}\n\t\t}\n\t\tif len(npir.From) == 0 {\n\t\t\tw.Write(LEVEL_0, \"%s%s\\n\", initialIndent, \"From: \u003cany\u003e (traffic not restricted by source)\")\n\t\t} else {\n\t\t\tfor _, from := range npir.From {\n\t\t\t\tw.Write(LEVEL_0, \"%s%s\\n\", initialIndent, \"From:\")\n\t\t\t\tif from.PodSelector != nil \u0026\u0026 from.NamespaceSelector != nil {\n\t\t\t\t\tw.Write(LEVEL_1, \"%s%s: %s\\n\", initialIndent, \"NamespaceSelector\", metav1.FormatLabelSelector(from.NamespaceSelector))\n\t\t\t\t\tw.Write(LEVEL_1, \"%s%s: %s\\n\", initialIndent, \"PodSelector\", metav1.FormatLabelSelector(from.PodSelector))\n\t\t\t\t} else if from.PodSelector != nil {\n\t\t\t\t\tw.Write(LEVEL_1, \"%s%s: %s\\n\", initialIndent, \"PodSelector\", metav1.FormatLabelSelector(from.PodSelector))\n\t\t\t\t} else if from.NamespaceSelector != nil {\n\t\t\t\t\tw.Write(LEVEL_1, \"%s%s: %s\\n\", initialIndent, \"NamespaceSelector\", metav1.FormatLabelSelector(from.NamespaceSelector))\n\t\t\t\t} else if from.IPBlock != nil {\n\t\t\t\t\tw.Write(LEVEL_1, \"%sIPBlock:\\n\", initialIndent)\n\t\t\t\t\tw.Write(LEVEL_2, \"%sCIDR: %s\\n\", initialIndent, from.IPBlock.CIDR)\n\t\t\t\t\tw.Write(LEVEL_2, \"%sExcept: %v\\n\", initialIndent, strings.Join(from.IPBlock.Except, \", \"))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif i != len(npirs)-1 {\n\t\t\tw.Write(LEVEL_0, \"%s%s\\n\", initialIndent, \"----------\")\n\t\t}\n\t}\n}","line":{"from":4509,"to":4551}} {"id":100032525,"name":"printNetworkPolicySpecEgressTo","signature":"func printNetworkPolicySpecEgressTo(npers []networkingv1.NetworkPolicyEgressRule, initialIndent string, w PrefixWriter)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printNetworkPolicySpecEgressTo(npers []networkingv1.NetworkPolicyEgressRule, initialIndent string, w PrefixWriter) {\n\tif len(npers) == 0 {\n\t\tw.Write(LEVEL_0, \"%s%s\\n\", initialIndent, \"\u003cnone\u003e (Selected pods are isolated for egress connectivity)\")\n\t\treturn\n\t}\n\tfor i, nper := range npers {\n\t\tif len(nper.Ports) == 0 {\n\t\t\tw.Write(LEVEL_0, \"%s%s\\n\", initialIndent, \"To Port: \u003cany\u003e (traffic allowed to all ports)\")\n\t\t} else {\n\t\t\tfor _, port := range nper.Ports {\n\t\t\t\tvar proto corev1.Protocol\n\t\t\t\tif port.Protocol != nil {\n\t\t\t\t\tproto = *port.Protocol\n\t\t\t\t} else {\n\t\t\t\t\tproto = corev1.ProtocolTCP\n\t\t\t\t}\n\t\t\t\tw.Write(LEVEL_0, \"%s%s: %s/%s\\n\", initialIndent, \"To Port\", port.Port, proto)\n\t\t\t}\n\t\t}\n\t\tif len(nper.To) == 0 {\n\t\t\tw.Write(LEVEL_0, \"%s%s\\n\", initialIndent, \"To: \u003cany\u003e (traffic not restricted by destination)\")\n\t\t} else {\n\t\t\tfor _, to := range nper.To {\n\t\t\t\tw.Write(LEVEL_0, \"%s%s\\n\", initialIndent, \"To:\")\n\t\t\t\tif to.PodSelector != nil \u0026\u0026 to.NamespaceSelector != nil {\n\t\t\t\t\tw.Write(LEVEL_1, \"%s%s: %s\\n\", initialIndent, \"NamespaceSelector\", metav1.FormatLabelSelector(to.NamespaceSelector))\n\t\t\t\t\tw.Write(LEVEL_1, \"%s%s: %s\\n\", initialIndent, \"PodSelector\", metav1.FormatLabelSelector(to.PodSelector))\n\t\t\t\t} else if to.PodSelector != nil {\n\t\t\t\t\tw.Write(LEVEL_1, \"%s%s: %s\\n\", initialIndent, \"PodSelector\", metav1.FormatLabelSelector(to.PodSelector))\n\t\t\t\t} else if to.NamespaceSelector != nil {\n\t\t\t\t\tw.Write(LEVEL_1, \"%s%s: %s\\n\", initialIndent, \"NamespaceSelector\", metav1.FormatLabelSelector(to.NamespaceSelector))\n\t\t\t\t} else if to.IPBlock != nil {\n\t\t\t\t\tw.Write(LEVEL_1, \"%sIPBlock:\\n\", initialIndent)\n\t\t\t\t\tw.Write(LEVEL_2, \"%sCIDR: %s\\n\", initialIndent, to.IPBlock.CIDR)\n\t\t\t\t\tw.Write(LEVEL_2, \"%sExcept: %v\\n\", initialIndent, strings.Join(to.IPBlock.Except, \", \"))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif i != len(npers)-1 {\n\t\t\tw.Write(LEVEL_0, \"%s%s\\n\", initialIndent, \"----------\")\n\t\t}\n\t}\n}","line":{"from":4553,"to":4595}} {"id":100032526,"name":"Describe","signature":"func (s *StorageClassDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (s *StorageClassDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tsc, err := s.StorageV1().StorageClasses().Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar events *corev1.EventList\n\tif describerSettings.ShowEvents {\n\t\tevents, _ = searchEvents(s.CoreV1(), sc, describerSettings.ChunkSize)\n\t}\n\n\treturn describeStorageClass(sc, events)\n}","line":{"from":4601,"to":4613}} {"id":100032527,"name":"describeStorageClass","signature":"func describeStorageClass(sc *storagev1.StorageClass, events *corev1.EventList) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeStorageClass(sc *storagev1.StorageClass, events *corev1.EventList) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", sc.Name)\n\t\tw.Write(LEVEL_0, \"IsDefaultClass:\\t%s\\n\", storageutil.IsDefaultAnnotationText(sc.ObjectMeta))\n\t\tw.Write(LEVEL_0, \"Annotations:\\t%s\\n\", labels.FormatLabels(sc.Annotations))\n\t\tw.Write(LEVEL_0, \"Provisioner:\\t%s\\n\", sc.Provisioner)\n\t\tw.Write(LEVEL_0, \"Parameters:\\t%s\\n\", labels.FormatLabels(sc.Parameters))\n\t\tw.Write(LEVEL_0, \"AllowVolumeExpansion:\\t%s\\n\", printBoolPtr(sc.AllowVolumeExpansion))\n\t\tif len(sc.MountOptions) == 0 {\n\t\t\tw.Write(LEVEL_0, \"MountOptions:\\t\u003cnone\u003e\\n\")\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"MountOptions:\\n\")\n\t\t\tfor _, option := range sc.MountOptions {\n\t\t\t\tw.Write(LEVEL_1, \"%s\\n\", option)\n\t\t\t}\n\t\t}\n\t\tif sc.ReclaimPolicy != nil {\n\t\t\tw.Write(LEVEL_0, \"ReclaimPolicy:\\t%s\\n\", *sc.ReclaimPolicy)\n\t\t}\n\t\tif sc.VolumeBindingMode != nil {\n\t\t\tw.Write(LEVEL_0, \"VolumeBindingMode:\\t%s\\n\", *sc.VolumeBindingMode)\n\t\t}\n\t\tif sc.AllowedTopologies != nil {\n\t\t\tprintAllowedTopologies(w, sc.AllowedTopologies)\n\t\t}\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\n\t\treturn nil\n\t})\n}","line":{"from":4615,"to":4647}} {"id":100032528,"name":"Describe","signature":"func (c *CSINodeDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (c *CSINodeDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tcsi, err := c.StorageV1().CSINodes().Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar events *corev1.EventList\n\tif describerSettings.ShowEvents {\n\t\tevents, _ = searchEvents(c.CoreV1(), csi, describerSettings.ChunkSize)\n\t}\n\n\treturn describeCSINode(csi, events)\n}","line":{"from":4653,"to":4665}} {"id":100032529,"name":"describeCSINode","signature":"func describeCSINode(csi *storagev1.CSINode, events *corev1.EventList) (output string, err error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describeCSINode(csi *storagev1.CSINode, events *corev1.EventList) (output string, err error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", csi.GetName())\n\t\tprintLabelsMultiline(w, \"Labels\", csi.GetLabels())\n\t\tprintAnnotationsMultiline(w, \"Annotations\", csi.GetAnnotations())\n\t\tw.Write(LEVEL_0, \"CreationTimestamp:\\t%s\\n\", csi.CreationTimestamp.Time.Format(time.RFC1123Z))\n\t\tw.Write(LEVEL_0, \"Spec:\\n\")\n\t\tif csi.Spec.Drivers != nil {\n\t\t\tw.Write(LEVEL_1, \"Drivers:\\n\")\n\t\t\tfor _, driver := range csi.Spec.Drivers {\n\t\t\t\tw.Write(LEVEL_2, \"%s:\\n\", driver.Name)\n\t\t\t\tw.Write(LEVEL_3, \"Node ID:\\t%s\\n\", driver.NodeID)\n\t\t\t\tif driver.Allocatable != nil \u0026\u0026 driver.Allocatable.Count != nil {\n\t\t\t\t\tw.Write(LEVEL_3, \"Allocatables:\\n\")\n\t\t\t\t\tw.Write(LEVEL_4, \"Count:\\t%d\\n\", *driver.Allocatable.Count)\n\t\t\t\t}\n\t\t\t\tif driver.TopologyKeys != nil {\n\t\t\t\t\tw.Write(LEVEL_3, \"Topology Keys:\\t%s\\n\", driver.TopologyKeys)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":4667,"to":4694}} {"id":100032530,"name":"printAllowedTopologies","signature":"func printAllowedTopologies(w PrefixWriter, topologies []corev1.TopologySelectorTerm)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printAllowedTopologies(w PrefixWriter, topologies []corev1.TopologySelectorTerm) {\n\tw.Write(LEVEL_0, \"AllowedTopologies:\\t\")\n\tif len(topologies) == 0 {\n\t\tw.WriteLine(\"\u003cnone\u003e\")\n\t\treturn\n\t}\n\tw.WriteLine(\"\")\n\tfor i, term := range topologies {\n\t\tprintTopologySelectorTermsMultilineWithIndent(w, LEVEL_1, fmt.Sprintf(\"Term %d\", i), \"\\t\", term.MatchLabelExpressions)\n\t}\n}","line":{"from":4696,"to":4706}} {"id":100032531,"name":"printTopologySelectorTermsMultilineWithIndent","signature":"func printTopologySelectorTermsMultilineWithIndent(w PrefixWriter, indentLevel int, title, innerIndent string, reqs []corev1.TopologySelectorLabelRequirement)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func printTopologySelectorTermsMultilineWithIndent(w PrefixWriter, indentLevel int, title, innerIndent string, reqs []corev1.TopologySelectorLabelRequirement) {\n\tw.Write(indentLevel, \"%s:%s\", title, innerIndent)\n\n\tif len(reqs) == 0 {\n\t\tw.WriteLine(\"\u003cnone\u003e\")\n\t\treturn\n\t}\n\n\tfor i, req := range reqs {\n\t\tif i != 0 {\n\t\t\tw.Write(indentLevel, \"%s\", innerIndent)\n\t\t}\n\t\texprStr := fmt.Sprintf(\"%s %s\", req.Key, \"in\")\n\t\tif len(req.Values) \u003e 0 {\n\t\t\texprStr = fmt.Sprintf(\"%s [%s]\", exprStr, strings.Join(req.Values, \", \"))\n\t\t}\n\t\tw.Write(LEVEL_0, \"%s\\n\", exprStr)\n\t}\n}","line":{"from":4708,"to":4726}} {"id":100032532,"name":"Describe","signature":"func (p *PodDisruptionBudgetDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (p *PodDisruptionBudgetDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tvar (\n\t\tpdbv1 *policyv1.PodDisruptionBudget\n\t\tpdbv1beta1 *policyv1beta1.PodDisruptionBudget\n\t\terr error\n\t)\n\n\tpdbv1, err = p.PolicyV1().PodDisruptionBudgets(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\tif err == nil {\n\t\tvar events *corev1.EventList\n\t\tif describerSettings.ShowEvents {\n\t\t\tevents, _ = searchEvents(p.CoreV1(), pdbv1, describerSettings.ChunkSize)\n\t\t}\n\t\treturn describePodDisruptionBudgetV1(pdbv1, events)\n\t}\n\n\t// try falling back to v1beta1 in NotFound error cases\n\tif apierrors.IsNotFound(err) {\n\t\tpdbv1beta1, err = p.PolicyV1beta1().PodDisruptionBudgets(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\t}\n\tif err == nil {\n\t\tvar events *corev1.EventList\n\t\tif describerSettings.ShowEvents {\n\t\t\tevents, _ = searchEvents(p.CoreV1(), pdbv1beta1, describerSettings.ChunkSize)\n\t\t}\n\t\treturn describePodDisruptionBudgetV1beta1(pdbv1beta1, events)\n\t}\n\n\treturn \"\", err\n}","line":{"from":4732,"to":4761}} {"id":100032533,"name":"describePodDisruptionBudgetV1","signature":"func describePodDisruptionBudgetV1(pdb *policyv1.PodDisruptionBudget, events *corev1.EventList) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describePodDisruptionBudgetV1(pdb *policyv1.PodDisruptionBudget, events *corev1.EventList) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", pdb.Name)\n\t\tw.Write(LEVEL_0, \"Namespace:\\t%s\\n\", pdb.Namespace)\n\n\t\tif pdb.Spec.MinAvailable != nil {\n\t\t\tw.Write(LEVEL_0, \"Min available:\\t%s\\n\", pdb.Spec.MinAvailable.String())\n\t\t} else if pdb.Spec.MaxUnavailable != nil {\n\t\t\tw.Write(LEVEL_0, \"Max unavailable:\\t%s\\n\", pdb.Spec.MaxUnavailable.String())\n\t\t}\n\n\t\tif pdb.Spec.Selector != nil {\n\t\t\tw.Write(LEVEL_0, \"Selector:\\t%s\\n\", metav1.FormatLabelSelector(pdb.Spec.Selector))\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"Selector:\\t\u003cunset\u003e\\n\")\n\t\t}\n\t\tw.Write(LEVEL_0, \"Status:\\n\")\n\t\tw.Write(LEVEL_2, \"Allowed disruptions:\\t%d\\n\", pdb.Status.DisruptionsAllowed)\n\t\tw.Write(LEVEL_2, \"Current:\\t%d\\n\", pdb.Status.CurrentHealthy)\n\t\tw.Write(LEVEL_2, \"Desired:\\t%d\\n\", pdb.Status.DesiredHealthy)\n\t\tw.Write(LEVEL_2, \"Total:\\t%d\\n\", pdb.Status.ExpectedPods)\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\n\t\treturn nil\n\t})\n}","line":{"from":4763,"to":4791}} {"id":100032534,"name":"describePodDisruptionBudgetV1beta1","signature":"func describePodDisruptionBudgetV1beta1(pdb *policyv1beta1.PodDisruptionBudget, events *corev1.EventList) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describePodDisruptionBudgetV1beta1(pdb *policyv1beta1.PodDisruptionBudget, events *corev1.EventList) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", pdb.Name)\n\t\tw.Write(LEVEL_0, \"Namespace:\\t%s\\n\", pdb.Namespace)\n\n\t\tif pdb.Spec.MinAvailable != nil {\n\t\t\tw.Write(LEVEL_0, \"Min available:\\t%s\\n\", pdb.Spec.MinAvailable.String())\n\t\t} else if pdb.Spec.MaxUnavailable != nil {\n\t\t\tw.Write(LEVEL_0, \"Max unavailable:\\t%s\\n\", pdb.Spec.MaxUnavailable.String())\n\t\t}\n\n\t\tif pdb.Spec.Selector != nil {\n\t\t\tw.Write(LEVEL_0, \"Selector:\\t%s\\n\", metav1.FormatLabelSelector(pdb.Spec.Selector))\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"Selector:\\t\u003cunset\u003e\\n\")\n\t\t}\n\t\tw.Write(LEVEL_0, \"Status:\\n\")\n\t\tw.Write(LEVEL_2, \"Allowed disruptions:\\t%d\\n\", pdb.Status.DisruptionsAllowed)\n\t\tw.Write(LEVEL_2, \"Current:\\t%d\\n\", pdb.Status.CurrentHealthy)\n\t\tw.Write(LEVEL_2, \"Desired:\\t%d\\n\", pdb.Status.DesiredHealthy)\n\t\tw.Write(LEVEL_2, \"Total:\\t%d\\n\", pdb.Status.ExpectedPods)\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\n\t\treturn nil\n\t})\n}","line":{"from":4793,"to":4821}} {"id":100032535,"name":"Describe","signature":"func (s *PriorityClassDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (s *PriorityClassDescriber) Describe(namespace, name string, describerSettings DescriberSettings) (string, error) {\n\tpc, err := s.SchedulingV1().PriorityClasses().Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar events *corev1.EventList\n\tif describerSettings.ShowEvents {\n\t\tevents, _ = searchEvents(s.CoreV1(), pc, describerSettings.ChunkSize)\n\t}\n\n\treturn describePriorityClass(pc, events)\n}","line":{"from":4828,"to":4840}} {"id":100032536,"name":"describePriorityClass","signature":"func describePriorityClass(pc *schedulingv1.PriorityClass, events *corev1.EventList) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func describePriorityClass(pc *schedulingv1.PriorityClass, events *corev1.EventList) (string, error) {\n\treturn tabbedString(func(out io.Writer) error {\n\t\tw := NewPrefixWriter(out)\n\t\tw.Write(LEVEL_0, \"Name:\\t%s\\n\", pc.Name)\n\t\tw.Write(LEVEL_0, \"Value:\\t%v\\n\", pc.Value)\n\t\tw.Write(LEVEL_0, \"GlobalDefault:\\t%v\\n\", pc.GlobalDefault)\n\t\tw.Write(LEVEL_0, \"PreemptionPolicy:\\t%s\\n\", *pc.PreemptionPolicy)\n\t\tw.Write(LEVEL_0, \"Description:\\t%s\\n\", pc.Description)\n\n\t\tw.Write(LEVEL_0, \"Annotations:\\t%s\\n\", labels.FormatLabels(pc.Annotations))\n\t\tif events != nil {\n\t\t\tDescribeEvents(events, w)\n\t\t}\n\n\t\treturn nil\n\t})\n}","line":{"from":4842,"to":4858}} {"id":100032537,"name":"stringOrNone","signature":"func stringOrNone(s string) string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func stringOrNone(s string) string {\n\treturn stringOrDefaultValue(s, \"\u003cnone\u003e\")\n}","line":{"from":4860,"to":4862}} {"id":100032538,"name":"stringOrDefaultValue","signature":"func stringOrDefaultValue(s, defaultValue string) string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func stringOrDefaultValue(s, defaultValue string) string {\n\tif len(s) \u003e 0 {\n\t\treturn s\n\t}\n\treturn defaultValue\n}","line":{"from":4864,"to":4869}} {"id":100032539,"name":"policyTypesToString","signature":"func policyTypesToString(pts []networkingv1.PolicyType) string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func policyTypesToString(pts []networkingv1.PolicyType) string {\n\tformattedString := \"\"\n\tif pts != nil {\n\t\tstrPts := []string{}\n\t\tfor _, p := range pts {\n\t\t\tstrPts = append(strPts, string(p))\n\t\t}\n\t\tformattedString = strings.Join(strPts, \", \")\n\t}\n\treturn stringOrNone(formattedString)\n}","line":{"from":4871,"to":4881}} {"id":100032540,"name":"newErrNoDescriber","signature":"func newErrNoDescriber(types ...reflect.Type) error","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// newErrNoDescriber creates a new ErrNoDescriber with the names of the provided types.\nfunc newErrNoDescriber(types ...reflect.Type) error {\n\tnames := make([]string, 0, len(types))\n\tfor _, t := range types {\n\t\tnames = append(names, t.String())\n\t}\n\treturn ErrNoDescriber{Types: names}\n}","line":{"from":4883,"to":4890}} {"id":100032541,"name":"DescribeObject","signature":"func (d *Describers) DescribeObject(exact interface{}, extra ...interface{}) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// DescribeObject implements ObjectDescriber and will attempt to print the provided object to a string,\n// if at least one describer function has been registered with the exact types passed, or if any\n// describer can print the exact object in its first argument (the remainder will be provided empty\n// values). If no function registered with Add can satisfy the passed objects, an ErrNoDescriber will\n// be returned\n// TODO: reorder and partial match extra.\nfunc (d *Describers) DescribeObject(exact interface{}, extra ...interface{}) (string, error) {\n\texactType := reflect.TypeOf(exact)\n\tfns, ok := d.searchFns[exactType]\n\tif !ok {\n\t\treturn \"\", newErrNoDescriber(exactType)\n\t}\n\tif len(extra) == 0 {\n\t\tfor _, typeFn := range fns {\n\t\t\tif len(typeFn.Extra) == 0 {\n\t\t\t\treturn typeFn.Describe(exact, extra...)\n\t\t\t}\n\t\t}\n\t\ttypeFn := fns[0]\n\t\tfor _, t := range typeFn.Extra {\n\t\t\tv := reflect.New(t).Elem()\n\t\t\textra = append(extra, v.Interface())\n\t\t}\n\t\treturn fns[0].Describe(exact, extra...)\n\t}\n\n\ttypes := make([]reflect.Type, 0, len(extra))\n\tfor _, obj := range extra {\n\t\ttypes = append(types, reflect.TypeOf(obj))\n\t}\n\tfor _, typeFn := range fns {\n\t\tif typeFn.Matches(types) {\n\t\t\treturn typeFn.Describe(exact, extra...)\n\t\t}\n\t}\n\treturn \"\", newErrNoDescriber(append([]reflect.Type{exactType}, types...)...)\n}","line":{"from":4898,"to":4934}} {"id":100032542,"name":"Add","signature":"func (d *Describers) Add(fns ...interface{}) error","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// Add adds one or more describer functions to the Describer. The passed function must\n// match the signature:\n//\n//\tfunc(...) (string, error)\n//\n// Any number of arguments may be provided.\nfunc (d *Describers) Add(fns ...interface{}) error {\n\tfor _, fn := range fns {\n\t\tfv := reflect.ValueOf(fn)\n\t\tft := fv.Type()\n\t\tif ft.Kind() != reflect.Func {\n\t\t\treturn fmt.Errorf(\"expected func, got: %v\", ft)\n\t\t}\n\t\tnumIn := ft.NumIn()\n\t\tif numIn == 0 {\n\t\t\treturn fmt.Errorf(\"expected at least one 'in' params, got: %v\", ft)\n\t\t}\n\t\tif ft.NumOut() != 2 {\n\t\t\treturn fmt.Errorf(\"expected two 'out' params - (string, error), got: %v\", ft)\n\t\t}\n\t\ttypes := make([]reflect.Type, 0, numIn)\n\t\tfor i := 0; i \u003c numIn; i++ {\n\t\t\ttypes = append(types, ft.In(i))\n\t\t}\n\t\tif ft.Out(0) != reflect.TypeOf(string(\"\")) {\n\t\t\treturn fmt.Errorf(\"expected string return, got: %v\", ft)\n\t\t}\n\t\tvar forErrorType error\n\t\t// This convolution is necessary, otherwise TypeOf picks up on the fact\n\t\t// that forErrorType is nil.\n\t\terrorType := reflect.TypeOf(\u0026forErrorType).Elem()\n\t\tif ft.Out(1) != errorType {\n\t\t\treturn fmt.Errorf(\"expected error return, got: %v\", ft)\n\t\t}\n\n\t\texact := types[0]\n\t\textra := types[1:]\n\t\tif d.searchFns == nil {\n\t\t\td.searchFns = make(map[reflect.Type][]typeFunc)\n\t\t}\n\t\tfns := d.searchFns[exact]\n\t\tfn := typeFunc{Extra: extra, Fn: fv}\n\t\tfns = append(fns, fn)\n\t\td.searchFns[exact] = fns\n\t}\n\treturn nil\n}","line":{"from":4936,"to":4982}} {"id":100032543,"name":"Matches","signature":"func (fn typeFunc) Matches(types []reflect.Type) bool","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// Matches returns true when the passed types exactly match the Extra list.\nfunc (fn typeFunc) Matches(types []reflect.Type) bool {\n\tif len(fn.Extra) != len(types) {\n\t\treturn false\n\t}\n\t// reorder the items in array types and fn.Extra\n\t// convert the type into string and sort them, check if they are matched\n\tvarMap := make(map[reflect.Type]bool)\n\tfor i := range fn.Extra {\n\t\tvarMap[fn.Extra[i]] = true\n\t}\n\tfor i := range types {\n\t\tif _, found := varMap[types[i]]; !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":4990,"to":5007}} {"id":100032544,"name":"Describe","signature":"func (fn typeFunc) Describe(exact interface{}, extra ...interface{}) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// Describe invokes the nested function with the exact number of arguments.\nfunc (fn typeFunc) Describe(exact interface{}, extra ...interface{}) (string, error) {\n\tvalues := []reflect.Value{reflect.ValueOf(exact)}\n\tfor _, obj := range extra {\n\t\tvalues = append(values, reflect.ValueOf(obj))\n\t}\n\tout := fn.Fn.Call(values)\n\ts := out[0].Interface().(string)\n\tvar err error\n\tif !out[1].IsNil() {\n\t\terr = out[1].Interface().(error)\n\t}\n\treturn s, err\n}","line":{"from":5009,"to":5022}} {"id":100032545,"name":"printLabelsMultiline","signature":"func printLabelsMultiline(w PrefixWriter, title string, labels map[string]string)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// printLabelsMultiline prints multiple labels with a proper alignment.\nfunc printLabelsMultiline(w PrefixWriter, title string, labels map[string]string) {\n\tprintLabelsMultilineWithIndent(w, \"\", title, \"\\t\", labels, sets.NewString())\n}","line":{"from":5024,"to":5027}} {"id":100032546,"name":"printLabelsMultilineWithIndent","signature":"func printLabelsMultilineWithIndent(w PrefixWriter, initialIndent, title, innerIndent string, labels map[string]string, skip sets.String)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// printLabelsMultiline prints multiple labels with a user-defined alignment.\nfunc printLabelsMultilineWithIndent(w PrefixWriter, initialIndent, title, innerIndent string, labels map[string]string, skip sets.String) {\n\tw.Write(LEVEL_0, \"%s%s:%s\", initialIndent, title, innerIndent)\n\n\tif len(labels) == 0 {\n\t\tw.WriteLine(\"\u003cnone\u003e\")\n\t\treturn\n\t}\n\n\t// to print labels in the sorted order\n\tkeys := make([]string, 0, len(labels))\n\tfor key := range labels {\n\t\tif skip.Has(key) {\n\t\t\tcontinue\n\t\t}\n\t\tkeys = append(keys, key)\n\t}\n\tif len(keys) == 0 {\n\t\tw.WriteLine(\"\u003cnone\u003e\")\n\t\treturn\n\t}\n\tsort.Strings(keys)\n\n\tfor i, key := range keys {\n\t\tif i != 0 {\n\t\t\tw.Write(LEVEL_0, \"%s\", initialIndent)\n\t\t\tw.Write(LEVEL_0, \"%s\", innerIndent)\n\t\t}\n\t\tw.Write(LEVEL_0, \"%s=%s\\n\", key, labels[key])\n\t}\n}","line":{"from":5029,"to":5059}} {"id":100032547,"name":"printNodeTaintsMultiline","signature":"func printNodeTaintsMultiline(w PrefixWriter, title string, taints []corev1.Taint)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// printTaintsMultiline prints multiple taints with a proper alignment.\nfunc printNodeTaintsMultiline(w PrefixWriter, title string, taints []corev1.Taint) {\n\tprintTaintsMultilineWithIndent(w, \"\", title, \"\\t\", taints)\n}","line":{"from":5061,"to":5064}} {"id":100032548,"name":"printTaintsMultilineWithIndent","signature":"func printTaintsMultilineWithIndent(w PrefixWriter, initialIndent, title, innerIndent string, taints []corev1.Taint)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// printTaintsMultilineWithIndent prints multiple taints with a user-defined alignment.\nfunc printTaintsMultilineWithIndent(w PrefixWriter, initialIndent, title, innerIndent string, taints []corev1.Taint) {\n\tw.Write(LEVEL_0, \"%s%s:%s\", initialIndent, title, innerIndent)\n\n\tif len(taints) == 0 {\n\t\tw.WriteLine(\"\u003cnone\u003e\")\n\t\treturn\n\t}\n\n\t// to print taints in the sorted order\n\tsort.Slice(taints, func(i, j int) bool {\n\t\tcmpKey := func(taint corev1.Taint) string {\n\t\t\treturn string(taint.Effect) + \",\" + taint.Key\n\t\t}\n\t\treturn cmpKey(taints[i]) \u003c cmpKey(taints[j])\n\t})\n\n\tfor i, taint := range taints {\n\t\tif i != 0 {\n\t\t\tw.Write(LEVEL_0, \"%s\", initialIndent)\n\t\t\tw.Write(LEVEL_0, \"%s\", innerIndent)\n\t\t}\n\t\tw.Write(LEVEL_0, \"%s\\n\", taint.ToString())\n\t}\n}","line":{"from":5066,"to":5090}} {"id":100032549,"name":"printPodsMultiline","signature":"func printPodsMultiline(w PrefixWriter, title string, pods []corev1.Pod)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// printPodsMultiline prints multiple pods with a proper alignment.\nfunc printPodsMultiline(w PrefixWriter, title string, pods []corev1.Pod) {\n\tprintPodsMultilineWithIndent(w, \"\", title, \"\\t\", pods)\n}","line":{"from":5092,"to":5095}} {"id":100032550,"name":"printPodsMultilineWithIndent","signature":"func printPodsMultilineWithIndent(w PrefixWriter, initialIndent, title, innerIndent string, pods []corev1.Pod)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// printPodsMultilineWithIndent prints multiple pods with a user-defined alignment.\nfunc printPodsMultilineWithIndent(w PrefixWriter, initialIndent, title, innerIndent string, pods []corev1.Pod) {\n\tw.Write(LEVEL_0, \"%s%s:%s\", initialIndent, title, innerIndent)\n\n\tif len(pods) == 0 {\n\t\tw.WriteLine(\"\u003cnone\u003e\")\n\t\treturn\n\t}\n\n\t// to print pods in the sorted order\n\tsort.Slice(pods, func(i, j int) bool {\n\t\tcmpKey := func(pod corev1.Pod) string {\n\t\t\treturn pod.Name\n\t\t}\n\t\treturn cmpKey(pods[i]) \u003c cmpKey(pods[j])\n\t})\n\n\tfor i, pod := range pods {\n\t\tif i != 0 {\n\t\t\tw.Write(LEVEL_0, \"%s\", initialIndent)\n\t\t\tw.Write(LEVEL_0, \"%s\", innerIndent)\n\t\t}\n\t\tw.Write(LEVEL_0, \"%s\\n\", pod.Name)\n\t}\n}","line":{"from":5097,"to":5121}} {"id":100032551,"name":"printPodTolerationsMultiline","signature":"func printPodTolerationsMultiline(w PrefixWriter, title string, tolerations []corev1.Toleration)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// printPodTolerationsMultiline prints multiple tolerations with a proper alignment.\nfunc printPodTolerationsMultiline(w PrefixWriter, title string, tolerations []corev1.Toleration) {\n\tprintTolerationsMultilineWithIndent(w, \"\", title, \"\\t\", tolerations)\n}","line":{"from":5123,"to":5126}} {"id":100032552,"name":"printTolerationsMultilineWithIndent","signature":"func printTolerationsMultilineWithIndent(w PrefixWriter, initialIndent, title, innerIndent string, tolerations []corev1.Toleration)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// printTolerationsMultilineWithIndent prints multiple tolerations with a user-defined alignment.\nfunc printTolerationsMultilineWithIndent(w PrefixWriter, initialIndent, title, innerIndent string, tolerations []corev1.Toleration) {\n\tw.Write(LEVEL_0, \"%s%s:%s\", initialIndent, title, innerIndent)\n\n\tif len(tolerations) == 0 {\n\t\tw.WriteLine(\"\u003cnone\u003e\")\n\t\treturn\n\t}\n\n\t// to print tolerations in the sorted order\n\tsort.Slice(tolerations, func(i, j int) bool {\n\t\treturn tolerations[i].Key \u003c tolerations[j].Key\n\t})\n\n\tfor i, toleration := range tolerations {\n\t\tif i != 0 {\n\t\t\tw.Write(LEVEL_0, \"%s\", initialIndent)\n\t\t\tw.Write(LEVEL_0, \"%s\", innerIndent)\n\t\t}\n\t\tw.Write(LEVEL_0, \"%s\", toleration.Key)\n\t\tif len(toleration.Value) != 0 {\n\t\t\tw.Write(LEVEL_0, \"=%s\", toleration.Value)\n\t\t}\n\t\tif len(toleration.Effect) != 0 {\n\t\t\tw.Write(LEVEL_0, \":%s\", toleration.Effect)\n\t\t}\n\t\t// tolerations:\n\t\t// - operator: \"Exists\"\n\t\t// is a special case which tolerates everything\n\t\tif toleration.Operator == corev1.TolerationOpExists \u0026\u0026 len(toleration.Value) == 0 {\n\t\t\tif len(toleration.Key) != 0 || len(toleration.Effect) != 0 {\n\t\t\t\tw.Write(LEVEL_0, \" op=Exists\")\n\t\t\t} else {\n\t\t\t\tw.Write(LEVEL_0, \"op=Exists\")\n\t\t\t}\n\t\t}\n\n\t\tif toleration.TolerationSeconds != nil {\n\t\t\tw.Write(LEVEL_0, \" for %ds\", *toleration.TolerationSeconds)\n\t\t}\n\t\tw.Write(LEVEL_0, \"\\n\")\n\t}\n}","line":{"from":5128,"to":5170}} {"id":100032553,"name":"tabbedString","signature":"func tabbedString(f func(io.Writer) error) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func tabbedString(f func(io.Writer) error) (string, error) {\n\tout := new(tabwriter.Writer)\n\tbuf := \u0026bytes.Buffer{}\n\tout.Init(buf, 0, 8, 2, ' ', 0)\n\n\terr := f(out)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tout.Flush()\n\tstr := string(buf.String())\n\treturn str, nil\n}","line":{"from":5176,"to":5189}} {"id":100032554,"name":"Len","signature":"func (list SortableResourceNames) Len() int","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (list SortableResourceNames) Len() int {\n\treturn len(list)\n}","line":{"from":5193,"to":5195}} {"id":100032555,"name":"Swap","signature":"func (list SortableResourceNames) Swap(i, j int)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (list SortableResourceNames) Swap(i, j int) {\n\tlist[i], list[j] = list[j], list[i]\n}","line":{"from":5197,"to":5199}} {"id":100032556,"name":"Less","signature":"func (list SortableResourceNames) Less(i, j int) bool","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (list SortableResourceNames) Less(i, j int) bool {\n\treturn list[i] \u003c list[j]\n}","line":{"from":5201,"to":5203}} {"id":100032557,"name":"SortedResourceNames","signature":"func SortedResourceNames(list corev1.ResourceList) []corev1.ResourceName","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// SortedResourceNames returns the sorted resource names of a resource list.\nfunc SortedResourceNames(list corev1.ResourceList) []corev1.ResourceName {\n\tresources := make([]corev1.ResourceName, 0, len(list))\n\tfor res := range list {\n\t\tresources = append(resources, res)\n\t}\n\tsort.Sort(SortableResourceNames(resources))\n\treturn resources\n}","line":{"from":5205,"to":5213}} {"id":100032558,"name":"Len","signature":"func (list SortableResourceQuotas) Len() int","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (list SortableResourceQuotas) Len() int {\n\treturn len(list)\n}","line":{"from":5217,"to":5219}} {"id":100032559,"name":"Swap","signature":"func (list SortableResourceQuotas) Swap(i, j int)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (list SortableResourceQuotas) Swap(i, j int) {\n\tlist[i], list[j] = list[j], list[i]\n}","line":{"from":5221,"to":5223}} {"id":100032560,"name":"Less","signature":"func (list SortableResourceQuotas) Less(i, j int) bool","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (list SortableResourceQuotas) Less(i, j int) bool {\n\treturn list[i].Name \u003c list[j].Name\n}","line":{"from":5225,"to":5227}} {"id":100032561,"name":"Len","signature":"func (list SortableVolumeMounts) Len() int","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (list SortableVolumeMounts) Len() int {\n\treturn len(list)\n}","line":{"from":5231,"to":5233}} {"id":100032562,"name":"Swap","signature":"func (list SortableVolumeMounts) Swap(i, j int)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (list SortableVolumeMounts) Swap(i, j int) {\n\tlist[i], list[j] = list[j], list[i]\n}","line":{"from":5235,"to":5237}} {"id":100032563,"name":"Less","signature":"func (list SortableVolumeMounts) Less(i, j int) bool","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (list SortableVolumeMounts) Less(i, j int) bool {\n\treturn list[i].MountPath \u003c list[j].MountPath\n}","line":{"from":5239,"to":5241}} {"id":100032564,"name":"Len","signature":"func (list SortableVolumeDevices) Len() int","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (list SortableVolumeDevices) Len() int {\n\treturn len(list)\n}","line":{"from":5245,"to":5247}} {"id":100032565,"name":"Swap","signature":"func (list SortableVolumeDevices) Swap(i, j int)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (list SortableVolumeDevices) Swap(i, j int) {\n\tlist[i], list[j] = list[j], list[i]\n}","line":{"from":5249,"to":5251}} {"id":100032566,"name":"Less","signature":"func (list SortableVolumeDevices) Less(i, j int) bool","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func (list SortableVolumeDevices) Less(i, j int) bool {\n\treturn list[i].DevicePath \u003c list[j].DevicePath\n}","line":{"from":5253,"to":5255}} {"id":100032567,"name":"printAnnotationsMultiline","signature":"func printAnnotationsMultiline(w PrefixWriter, title string, annotations map[string]string)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// printAnnotationsMultiline prints multiple annotations with a proper alignment.\n// If annotation string is too long, we omit chars more than 200 length.\nfunc printAnnotationsMultiline(w PrefixWriter, title string, annotations map[string]string) {\n\tw.Write(LEVEL_0, \"%s:\\t\", title)\n\n\t// to print labels in the sorted order\n\tkeys := make([]string, 0, len(annotations))\n\tfor key := range annotations {\n\t\tif skipAnnotations.Has(key) {\n\t\t\tcontinue\n\t\t}\n\t\tkeys = append(keys, key)\n\t}\n\tif len(keys) == 0 {\n\t\tw.WriteLine(\"\u003cnone\u003e\")\n\t\treturn\n\t}\n\tsort.Strings(keys)\n\tindent := \"\\t\"\n\tfor i, key := range keys {\n\t\tif i != 0 {\n\t\t\tw.Write(LEVEL_0, indent)\n\t\t}\n\t\tvalue := strings.TrimSuffix(annotations[key], \"\\n\")\n\t\tif (len(value)+len(key)+2) \u003e maxAnnotationLen || strings.Contains(value, \"\\n\") {\n\t\t\tw.Write(LEVEL_0, \"%s:\\n\", key)\n\t\t\tfor _, s := range strings.Split(value, \"\\n\") {\n\t\t\t\tw.Write(LEVEL_0, \"%s %s\\n\", indent, shorten(s, maxAnnotationLen-2))\n\t\t\t}\n\t\t} else {\n\t\t\tw.Write(LEVEL_0, \"%s: %s\\n\", key, value)\n\t\t}\n\t}\n}","line":{"from":5259,"to":5292}} {"id":100032568,"name":"shorten","signature":"func shorten(s string, maxLength int) string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func shorten(s string, maxLength int) string {\n\tif len(s) \u003e maxLength {\n\t\treturn s[:maxLength] + \"...\"\n\t}\n\treturn s\n}","line":{"from":5294,"to":5299}} {"id":100032569,"name":"translateMicroTimestampSince","signature":"func translateMicroTimestampSince(timestamp metav1.MicroTime) string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// translateMicroTimestampSince returns the elapsed time since timestamp in\n// human-readable approximation.\nfunc translateMicroTimestampSince(timestamp metav1.MicroTime) string {\n\tif timestamp.IsZero() {\n\t\treturn \"\u003cunknown\u003e\"\n\t}\n\n\treturn duration.HumanDuration(time.Since(timestamp.Time))\n}","line":{"from":5301,"to":5309}} {"id":100032570,"name":"translateTimestampSince","signature":"func translateTimestampSince(timestamp metav1.Time) string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// translateTimestampSince returns the elapsed time since timestamp in\n// human-readable approximation.\nfunc translateTimestampSince(timestamp metav1.Time) string {\n\tif timestamp.IsZero() {\n\t\treturn \"\u003cunknown\u003e\"\n\t}\n\n\treturn duration.HumanDuration(time.Since(timestamp.Time))\n}","line":{"from":5311,"to":5319}} {"id":100032571,"name":"formatEndpoints","signature":"func formatEndpoints(endpoints *corev1.Endpoints, ports sets.String) string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// Pass ports=nil for all ports.\nfunc formatEndpoints(endpoints *corev1.Endpoints, ports sets.String) string {\n\tif len(endpoints.Subsets) == 0 {\n\t\treturn \"\u003cnone\u003e\"\n\t}\n\tlist := []string{}\n\tmax := 3\n\tmore := false\n\tcount := 0\n\tfor i := range endpoints.Subsets {\n\t\tss := \u0026endpoints.Subsets[i]\n\t\tif len(ss.Ports) == 0 {\n\t\t\t// It's possible to have headless services with no ports.\n\t\t\tfor i := range ss.Addresses {\n\t\t\t\tif len(list) == max {\n\t\t\t\t\tmore = true\n\t\t\t\t}\n\t\t\t\tif !more {\n\t\t\t\t\tlist = append(list, ss.Addresses[i].IP)\n\t\t\t\t}\n\t\t\t\tcount++\n\t\t\t}\n\t\t} else {\n\t\t\t// \"Normal\" services with ports defined.\n\t\t\tfor i := range ss.Ports {\n\t\t\t\tport := \u0026ss.Ports[i]\n\t\t\t\tif ports == nil || ports.Has(port.Name) {\n\t\t\t\t\tfor i := range ss.Addresses {\n\t\t\t\t\t\tif len(list) == max {\n\t\t\t\t\t\t\tmore = true\n\t\t\t\t\t\t}\n\t\t\t\t\t\taddr := \u0026ss.Addresses[i]\n\t\t\t\t\t\tif !more {\n\t\t\t\t\t\t\thostPort := net.JoinHostPort(addr.IP, strconv.Itoa(int(port.Port)))\n\t\t\t\t\t\t\tlist = append(list, hostPort)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcount++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tret := strings.Join(list, \",\")\n\tif more {\n\t\treturn fmt.Sprintf(\"%s + %d more...\", ret, count-max)\n\t}\n\treturn ret\n}","line":{"from":5321,"to":5368}} {"id":100032572,"name":"extractCSRStatus","signature":"func extractCSRStatus(conditions []string, certificateBytes []byte) string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"func extractCSRStatus(conditions []string, certificateBytes []byte) string {\n\tvar approved, denied, failed bool\n\tfor _, c := range conditions {\n\t\tswitch c {\n\t\tcase string(certificatesv1beta1.CertificateApproved):\n\t\t\tapproved = true\n\t\tcase string(certificatesv1beta1.CertificateDenied):\n\t\t\tdenied = true\n\t\tcase string(certificatesv1beta1.CertificateFailed):\n\t\t\tfailed = true\n\t\t}\n\t}\n\tvar status string\n\t// must be in order of precedence\n\tif denied {\n\t\tstatus += \"Denied\"\n\t} else if approved {\n\t\tstatus += \"Approved\"\n\t} else {\n\t\tstatus += \"Pending\"\n\t}\n\tif failed {\n\t\tstatus += \",Failed\"\n\t}\n\tif len(certificateBytes) \u003e 0 {\n\t\tstatus += \",Issued\"\n\t}\n\treturn status\n}","line":{"from":5370,"to":5398}} {"id":100032573,"name":"serviceBackendStringer","signature":"func serviceBackendStringer(backend *networkingv1.IngressServiceBackend) string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// backendStringer behaves just like a string interface and converts the given backend to a string.\nfunc serviceBackendStringer(backend *networkingv1.IngressServiceBackend) string {\n\tif backend == nil {\n\t\treturn \"\"\n\t}\n\tvar bPort string\n\tif backend.Port.Number != 0 {\n\t\tsNum := int64(backend.Port.Number)\n\t\tbPort = strconv.FormatInt(sNum, 10)\n\t} else {\n\t\tbPort = backend.Port.Name\n\t}\n\treturn fmt.Sprintf(\"%v:%v\", backend.Name, bPort)\n}","line":{"from":5400,"to":5413}} {"id":100032574,"name":"backendStringer","signature":"func backendStringer(backend *networkingv1beta1.IngressBackend) string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// backendStringer behaves just like a string interface and converts the given backend to a string.\nfunc backendStringer(backend *networkingv1beta1.IngressBackend) string {\n\tif backend == nil {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(\"%v:%v\", backend.ServiceName, backend.ServicePort.String())\n}","line":{"from":5415,"to":5421}} {"id":100032575,"name":"findNodeRoles","signature":"func findNodeRoles(node *corev1.Node) []string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// findNodeRoles returns the roles of a given node.\n// The roles are determined by looking for:\n// * a node-role.kubernetes.io/\u003crole\u003e=\"\" label\n// * a kubernetes.io/role=\"\u003crole\u003e\" label\nfunc findNodeRoles(node *corev1.Node) []string {\n\troles := sets.NewString()\n\tfor k, v := range node.Labels {\n\t\tswitch {\n\t\tcase strings.HasPrefix(k, LabelNodeRolePrefix):\n\t\t\tif role := strings.TrimPrefix(k, LabelNodeRolePrefix); len(role) \u003e 0 {\n\t\t\t\troles.Insert(role)\n\t\t\t}\n\n\t\tcase k == NodeLabelRole \u0026\u0026 v != \"\":\n\t\t\troles.Insert(v)\n\t\t}\n\t}\n\treturn roles.List()\n}","line":{"from":5423,"to":5441}} {"id":100032576,"name":"ingressLoadBalancerStatusStringerV1","signature":"func ingressLoadBalancerStatusStringerV1(s networkingv1.IngressLoadBalancerStatus, wide bool) string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// ingressLoadBalancerStatusStringerV1 behaves mostly like a string interface and converts the given status to a string.\n// `wide` indicates whether the returned value is meant for --o=wide output. If not, it's clipped to 16 bytes.\nfunc ingressLoadBalancerStatusStringerV1(s networkingv1.IngressLoadBalancerStatus, wide bool) string {\n\tingress := s.Ingress\n\tresult := sets.NewString()\n\tfor i := range ingress {\n\t\tif ingress[i].IP != \"\" {\n\t\t\tresult.Insert(ingress[i].IP)\n\t\t} else if ingress[i].Hostname != \"\" {\n\t\t\tresult.Insert(ingress[i].Hostname)\n\t\t}\n\t}\n\n\tr := strings.Join(result.List(), \",\")\n\tif !wide \u0026\u0026 len(r) \u003e LoadBalancerWidth {\n\t\tr = r[0:(LoadBalancerWidth-3)] + \"...\"\n\t}\n\treturn r\n}","line":{"from":5443,"to":5461}} {"id":100032577,"name":"ingressLoadBalancerStatusStringerV1beta1","signature":"func ingressLoadBalancerStatusStringerV1beta1(s networkingv1beta1.IngressLoadBalancerStatus, wide bool) string","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// ingressLoadBalancerStatusStringerV1beta1 behaves mostly like a string interface and converts the given status to a string.\n// `wide` indicates whether the returned value is meant for --o=wide output. If not, it's clipped to 16 bytes.\nfunc ingressLoadBalancerStatusStringerV1beta1(s networkingv1beta1.IngressLoadBalancerStatus, wide bool) string {\n\tingress := s.Ingress\n\tresult := sets.NewString()\n\tfor i := range ingress {\n\t\tif ingress[i].IP != \"\" {\n\t\t\tresult.Insert(ingress[i].IP)\n\t\t} else if ingress[i].Hostname != \"\" {\n\t\t\tresult.Insert(ingress[i].Hostname)\n\t\t}\n\t}\n\n\tr := strings.Join(result.List(), \",\")\n\tif !wide \u0026\u0026 len(r) \u003e LoadBalancerWidth {\n\t\tr = r[0:(LoadBalancerWidth-3)] + \"...\"\n\t}\n\treturn r\n}","line":{"from":5463,"to":5481}} {"id":100032578,"name":"searchEvents","signature":"func searchEvents(client corev1client.EventsGetter, objOrRef runtime.Object, limit int64) (*corev1.EventList, error)","file":"staging/src/k8s.io/kubectl/pkg/describe/describe.go","code":"// searchEvents finds events about the specified object.\n// It is very similar to CoreV1.Events.Search, but supports the Limit parameter.\nfunc searchEvents(client corev1client.EventsGetter, objOrRef runtime.Object, limit int64) (*corev1.EventList, error) {\n\tref, err := reference.GetReference(scheme.Scheme, objOrRef)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstringRefKind := string(ref.Kind)\n\tvar refKind *string\n\tif len(stringRefKind) \u003e 0 {\n\t\trefKind = \u0026stringRefKind\n\t}\n\tstringRefUID := string(ref.UID)\n\tvar refUID *string\n\tif len(stringRefUID) \u003e 0 {\n\t\trefUID = \u0026stringRefUID\n\t}\n\n\te := client.Events(ref.Namespace)\n\tfieldSelector := e.GetFieldSelector(\u0026ref.Name, \u0026ref.Namespace, refKind, refUID)\n\tinitialOpts := metav1.ListOptions{FieldSelector: fieldSelector.String(), Limit: limit}\n\teventList := \u0026corev1.EventList{}\n\terr = runtimeresource.FollowContinue(\u0026initialOpts,\n\t\tfunc(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\tnewEvents, err := e.List(context.TODO(), options)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, runtimeresource.EnhanceListError(err, options, \"events\")\n\t\t\t}\n\t\t\teventList.Items = append(eventList.Items, newEvents.Items...)\n\t\t\treturn newEvents, nil\n\t\t})\n\treturn eventList, err\n}","line":{"from":5483,"to":5515}} {"id":100032579,"name":"Error","signature":"func (e ErrNoDescriber) Error() string","file":"staging/src/k8s.io/kubectl/pkg/describe/interface.go","code":"// Error implements the error interface.\nfunc (e ErrNoDescriber) Error() string {\n\treturn fmt.Sprintf(\"no describer has been defined for %v\", e.Types)\n}","line":{"from":69,"to":72}} {"id":100032580,"name":"NewCordonHelper","signature":"func NewCordonHelper(node *corev1.Node) *CordonHelper","file":"staging/src/k8s.io/kubectl/pkg/drain/cordon.go","code":"// NewCordonHelper returns a new CordonHelper\nfunc NewCordonHelper(node *corev1.Node) *CordonHelper {\n\treturn \u0026CordonHelper{\n\t\tnode: node,\n\t}\n}","line":{"from":40,"to":45}} {"id":100032581,"name":"NewCordonHelperFromRuntimeObject","signature":"func NewCordonHelperFromRuntimeObject(nodeObject runtime.Object, scheme *runtime.Scheme, gvk schema.GroupVersionKind) (*CordonHelper, error)","file":"staging/src/k8s.io/kubectl/pkg/drain/cordon.go","code":"// NewCordonHelperFromRuntimeObject returns a new CordonHelper, or an error if given object is not a\n// node or cannot be encoded as JSON\nfunc NewCordonHelperFromRuntimeObject(nodeObject runtime.Object, scheme *runtime.Scheme, gvk schema.GroupVersionKind) (*CordonHelper, error) {\n\tnodeObject, err := scheme.ConvertToVersion(nodeObject, gvk.GroupVersion())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnode, ok := nodeObject.(*corev1.Node)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unexpected type %T\", nodeObject)\n\t}\n\n\treturn NewCordonHelper(node), nil\n}","line":{"from":47,"to":61}} {"id":100032582,"name":"UpdateIfRequired","signature":"func (c *CordonHelper) UpdateIfRequired(desired bool) bool","file":"staging/src/k8s.io/kubectl/pkg/drain/cordon.go","code":"// UpdateIfRequired returns true if c.node.Spec.Unschedulable isn't already set,\n// or false when no change is needed\nfunc (c *CordonHelper) UpdateIfRequired(desired bool) bool {\n\tc.desired = desired\n\n\treturn c.node.Spec.Unschedulable != c.desired\n}","line":{"from":63,"to":69}} {"id":100032583,"name":"PatchOrReplace","signature":"func (c *CordonHelper) PatchOrReplace(clientset kubernetes.Interface, serverDryRun bool) (error, error)","file":"staging/src/k8s.io/kubectl/pkg/drain/cordon.go","code":"// PatchOrReplace uses given clientset to update the node status, either by patching or\n// updating the given node object; it may return error if the object cannot be encoded as\n// JSON, or if either patch or update calls fail; it will also return a second error\n// whenever creating a patch has failed\nfunc (c *CordonHelper) PatchOrReplace(clientset kubernetes.Interface, serverDryRun bool) (error, error) {\n\treturn c.PatchOrReplaceWithContext(context.TODO(), clientset, serverDryRun)\n}","line":{"from":71,"to":77}} {"id":100032584,"name":"PatchOrReplaceWithContext","signature":"func (c *CordonHelper) PatchOrReplaceWithContext(clientCtx context.Context, clientset kubernetes.Interface, serverDryRun bool) (error, error)","file":"staging/src/k8s.io/kubectl/pkg/drain/cordon.go","code":"// PatchOrReplaceWithContext provides the option to pass a custom context while updating\n// the node status\nfunc (c *CordonHelper) PatchOrReplaceWithContext(clientCtx context.Context, clientset kubernetes.Interface, serverDryRun bool) (error, error) {\n\tclient := clientset.CoreV1().Nodes()\n\n\toldData, err := json.Marshal(c.node)\n\tif err != nil {\n\t\treturn err, nil\n\t}\n\n\tc.node.Spec.Unschedulable = c.desired\n\n\tnewData, err := json.Marshal(c.node)\n\tif err != nil {\n\t\treturn err, nil\n\t}\n\n\tpatchBytes, patchErr := strategicpatch.CreateTwoWayMergePatch(oldData, newData, c.node)\n\tif patchErr == nil {\n\t\tpatchOptions := metav1.PatchOptions{}\n\t\tif serverDryRun {\n\t\t\tpatchOptions.DryRun = []string{metav1.DryRunAll}\n\t\t}\n\t\t_, err = client.Patch(clientCtx, c.node.Name, types.StrategicMergePatchType, patchBytes, patchOptions)\n\t} else {\n\t\tupdateOptions := metav1.UpdateOptions{}\n\t\tif serverDryRun {\n\t\t\tupdateOptions.DryRun = []string{metav1.DryRunAll}\n\t\t}\n\t\t_, err = client.Update(clientCtx, c.node, updateOptions)\n\t}\n\treturn err, patchErr\n}","line":{"from":79,"to":111}} {"id":100032585,"name":"RunNodeDrain","signature":"func RunNodeDrain(drainer *Helper, nodeName string) error","file":"staging/src/k8s.io/kubectl/pkg/drain/default.go","code":"// RunNodeDrain shows the canonical way to drain a node.\n// You should first cordon the node, e.g. using RunCordonOrUncordon\nfunc RunNodeDrain(drainer *Helper, nodeName string) error {\n\t// TODO(justinsb): Ensure we have adequate e2e coverage of this function in library consumers\n\tlist, errs := drainer.GetPodsForDeletion(nodeName)\n\tif errs != nil {\n\t\treturn utilerrors.NewAggregate(errs)\n\t}\n\tif warnings := list.Warnings(); warnings != \"\" {\n\t\tfmt.Fprintf(drainer.ErrOut, \"WARNING: %s\\n\", warnings)\n\t}\n\n\tif err := drainer.DeleteOrEvictPods(list.Pods()); err != nil {\n\t\t// Maybe warn about non-deleted pods here\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":31,"to":48}} {"id":100032586,"name":"RunCordonOrUncordon","signature":"func RunCordonOrUncordon(drainer *Helper, node *corev1.Node, desired bool) error","file":"staging/src/k8s.io/kubectl/pkg/drain/default.go","code":"// RunCordonOrUncordon demonstrates the canonical way to cordon or uncordon a Node\nfunc RunCordonOrUncordon(drainer *Helper, node *corev1.Node, desired bool) error {\n\tif drainer.Ctx == nil {\n\t\treturn fmt.Errorf(\"RunCordonOrUncordon error: drainer.Ctx can't be nil\")\n\t}\n\tif drainer.Client == nil {\n\t\treturn fmt.Errorf(\"RunCordonOrUncordon error: drainer.Client can't be nil\")\n\t}\n\t// TODO(justinsb): Ensure we have adequate e2e coverage of this function in library consumers\n\tc := NewCordonHelper(node)\n\n\tif updateRequired := c.UpdateIfRequired(desired); !updateRequired {\n\t\t// Already done\n\t\treturn nil\n\t}\n\n\terr, patchErr := c.PatchOrReplaceWithContext(drainer.Ctx, drainer.Client, false)\n\tif err != nil {\n\t\tif patchErr != nil {\n\t\t\treturn fmt.Errorf(\"cordon error: %s; merge patch error: %w\", err.Error(), patchErr)\n\t\t}\n\t\treturn fmt.Errorf(\"cordon error: %w\", err)\n\t}\n\n\treturn nil\n}","line":{"from":50,"to":75}} {"id":100032587,"name":"CheckEvictionSupport","signature":"func CheckEvictionSupport(clientset kubernetes.Interface) (schema.GroupVersion, error)","file":"staging/src/k8s.io/kubectl/pkg/drain/drain.go","code":"// CheckEvictionSupport uses Discovery API to find out if the server support\n// eviction subresource If support, it will return its groupVersion; Otherwise,\n// it will return an empty GroupVersion\nfunc CheckEvictionSupport(clientset kubernetes.Interface) (schema.GroupVersion, error) {\n\tdiscoveryClient := clientset.Discovery()\n\n\t// version info available in subresources since v1.8.0 in https://github.com/kubernetes/kubernetes/pull/49971\n\tresourceList, err := discoveryClient.ServerResourcesForGroupVersion(\"v1\")\n\tif err != nil {\n\t\treturn schema.GroupVersion{}, err\n\t}\n\tfor _, resource := range resourceList.APIResources {\n\t\tif resource.Name == EvictionSubresource \u0026\u0026 resource.Kind == EvictionKind \u0026\u0026 len(resource.Group) \u003e 0 \u0026\u0026 len(resource.Version) \u003e 0 {\n\t\t\treturn schema.GroupVersion{Group: resource.Group, Version: resource.Version}, nil\n\t\t}\n\t}\n\treturn schema.GroupVersion{}, nil\n}","line":{"from":104,"to":121}} {"id":100032588,"name":"makeDeleteOptions","signature":"func (d *Helper) makeDeleteOptions() metav1.DeleteOptions","file":"staging/src/k8s.io/kubectl/pkg/drain/drain.go","code":"func (d *Helper) makeDeleteOptions() metav1.DeleteOptions {\n\tdeleteOptions := metav1.DeleteOptions{}\n\tif d.GracePeriodSeconds \u003e= 0 {\n\t\tgracePeriodSeconds := int64(d.GracePeriodSeconds)\n\t\tdeleteOptions.GracePeriodSeconds = \u0026gracePeriodSeconds\n\t}\n\tif d.DryRunStrategy == cmdutil.DryRunServer {\n\t\tdeleteOptions.DryRun = []string{metav1.DryRunAll}\n\t}\n\treturn deleteOptions\n}","line":{"from":123,"to":133}} {"id":100032589,"name":"DeletePod","signature":"func (d *Helper) DeletePod(pod corev1.Pod) error","file":"staging/src/k8s.io/kubectl/pkg/drain/drain.go","code":"// DeletePod will delete the given pod, or return an error if it couldn't\nfunc (d *Helper) DeletePod(pod corev1.Pod) error {\n\treturn d.Client.CoreV1().Pods(pod.Namespace).Delete(d.getContext(), pod.Name, d.makeDeleteOptions())\n}","line":{"from":135,"to":138}} {"id":100032590,"name":"EvictPod","signature":"func (d *Helper) EvictPod(pod corev1.Pod, evictionGroupVersion schema.GroupVersion) error","file":"staging/src/k8s.io/kubectl/pkg/drain/drain.go","code":"// EvictPod will evict the given pod, or return an error if it couldn't\nfunc (d *Helper) EvictPod(pod corev1.Pod, evictionGroupVersion schema.GroupVersion) error {\n\tdelOpts := d.makeDeleteOptions()\n\n\tswitch evictionGroupVersion {\n\tcase policyv1.SchemeGroupVersion:\n\t\t// send policy/v1 if the server supports it\n\t\teviction := \u0026policyv1.Eviction{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: pod.Name,\n\t\t\t\tNamespace: pod.Namespace,\n\t\t\t},\n\t\t\tDeleteOptions: \u0026delOpts,\n\t\t}\n\t\treturn d.Client.PolicyV1().Evictions(eviction.Namespace).Evict(context.TODO(), eviction)\n\n\tdefault:\n\t\t// otherwise, fall back to policy/v1beta1, supported by all servers that support the eviction subresource\n\t\teviction := \u0026policyv1beta1.Eviction{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: pod.Name,\n\t\t\t\tNamespace: pod.Namespace,\n\t\t\t},\n\t\t\tDeleteOptions: \u0026delOpts,\n\t\t}\n\t\treturn d.Client.PolicyV1beta1().Evictions(eviction.Namespace).Evict(context.TODO(), eviction)\n\t}\n}","line":{"from":140,"to":167}} {"id":100032591,"name":"GetPodsForDeletion","signature":"func (d *Helper) GetPodsForDeletion(nodeName string) (*PodDeleteList, []error)","file":"staging/src/k8s.io/kubectl/pkg/drain/drain.go","code":"// GetPodsForDeletion receives resource info for a node, and returns those pods as PodDeleteList,\n// or error if it cannot list pods. All pods that are ready to be deleted can be obtained with .Pods(),\n// and string with all warning can be obtained with .Warnings(), and .Errors() for all errors that\n// occurred during deletion.\nfunc (d *Helper) GetPodsForDeletion(nodeName string) (*PodDeleteList, []error) {\n\tlabelSelector, err := labels.Parse(d.PodSelector)\n\tif err != nil {\n\t\treturn nil, []error{err}\n\t}\n\n\tpodList := \u0026corev1.PodList{}\n\tinitialOpts := \u0026metav1.ListOptions{\n\t\tLabelSelector: labelSelector.String(),\n\t\tFieldSelector: fields.SelectorFromSet(fields.Set{\"spec.nodeName\": nodeName}).String(),\n\t\tLimit: d.ChunkSize,\n\t}\n\n\terr = resource.FollowContinue(initialOpts, func(options metav1.ListOptions) (runtime.Object, error) {\n\t\tnewPods, err := d.Client.CoreV1().Pods(metav1.NamespaceAll).List(d.getContext(), options)\n\t\tif err != nil {\n\t\t\tpodR := corev1.SchemeGroupVersion.WithResource(corev1.ResourcePods.String())\n\t\t\treturn nil, resource.EnhanceListError(err, options, podR.String())\n\t\t}\n\t\tpodList.Items = append(podList.Items, newPods.Items...)\n\t\treturn newPods, nil\n\t})\n\n\tif err != nil {\n\t\treturn nil, []error{err}\n\t}\n\n\tlist := filterPods(podList, d.makeFilters())\n\tif errs := list.errors(); len(errs) \u003e 0 {\n\t\treturn list, errs\n\t}\n\n\treturn list, nil\n}","line":{"from":169,"to":206}} {"id":100032592,"name":"filterPods","signature":"func filterPods(podList *corev1.PodList, filters []PodFilter) *PodDeleteList","file":"staging/src/k8s.io/kubectl/pkg/drain/drain.go","code":"func filterPods(podList *corev1.PodList, filters []PodFilter) *PodDeleteList {\n\tpods := []PodDelete{}\n\tfor _, pod := range podList.Items {\n\t\tvar status PodDeleteStatus\n\t\tfor _, filter := range filters {\n\t\t\tstatus = filter(pod)\n\t\t\tif !status.Delete {\n\t\t\t\t// short-circuit as soon as pod is filtered out\n\t\t\t\t// at that point, there is no reason to run pod\n\t\t\t\t// through any additional filters\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\t// Add the pod to PodDeleteList no matter what PodDeleteStatus is,\n\t\t// those pods whose PodDeleteStatus is false like DaemonSet will\n\t\t// be catched by list.errors()\n\t\tpod.Kind = \"Pod\"\n\t\tpod.APIVersion = \"v1\"\n\t\tpods = append(pods, PodDelete{\n\t\t\tPod: pod,\n\t\t\tStatus: status,\n\t\t})\n\t}\n\tlist := \u0026PodDeleteList{items: pods}\n\treturn list\n}","line":{"from":208,"to":233}} {"id":100032593,"name":"DeleteOrEvictPods","signature":"func (d *Helper) DeleteOrEvictPods(pods []corev1.Pod) error","file":"staging/src/k8s.io/kubectl/pkg/drain/drain.go","code":"// DeleteOrEvictPods deletes or evicts the pods on the api server\nfunc (d *Helper) DeleteOrEvictPods(pods []corev1.Pod) error {\n\tif len(pods) == 0 {\n\t\treturn nil\n\t}\n\n\t// TODO(justinsb): unnecessary?\n\tgetPodFn := func(namespace, name string) (*corev1.Pod, error) {\n\t\treturn d.Client.CoreV1().Pods(namespace).Get(d.getContext(), name, metav1.GetOptions{})\n\t}\n\n\tif !d.DisableEviction {\n\t\tevictionGroupVersion, err := CheckEvictionSupport(d.Client)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif !evictionGroupVersion.Empty() {\n\t\t\treturn d.evictPods(pods, evictionGroupVersion, getPodFn)\n\t\t}\n\t}\n\n\treturn d.deletePods(pods, getPodFn)\n}","line":{"from":235,"to":258}} {"id":100032594,"name":"evictPods","signature":"func (d *Helper) evictPods(pods []corev1.Pod, evictionGroupVersion schema.GroupVersion, getPodFn func(namespace, name string) (*corev1.Pod, error)) error","file":"staging/src/k8s.io/kubectl/pkg/drain/drain.go","code":"func (d *Helper) evictPods(pods []corev1.Pod, evictionGroupVersion schema.GroupVersion, getPodFn func(namespace, name string) (*corev1.Pod, error)) error {\n\treturnCh := make(chan error, 1)\n\t// 0 timeout means infinite, we use MaxInt64 to represent it.\n\tvar globalTimeout time.Duration\n\tif d.Timeout == 0 {\n\t\tglobalTimeout = time.Duration(math.MaxInt64)\n\t} else {\n\t\tglobalTimeout = d.Timeout\n\t}\n\tctx, cancel := context.WithTimeout(d.getContext(), globalTimeout)\n\tdefer cancel()\n\tfor _, pod := range pods {\n\t\tgo func(pod corev1.Pod, returnCh chan error) {\n\t\t\trefreshPod := false\n\t\t\tfor {\n\t\t\t\tswitch d.DryRunStrategy {\n\t\t\t\tcase cmdutil.DryRunServer:\n\t\t\t\t\tfmt.Fprintf(d.Out, \"evicting pod %s/%s (server dry run)\\n\", pod.Namespace, pod.Name)\n\t\t\t\tdefault:\n\t\t\t\t\tfmt.Fprintf(d.Out, \"evicting pod %s/%s\\n\", pod.Namespace, pod.Name)\n\t\t\t\t}\n\t\t\t\tselect {\n\t\t\t\tcase \u003c-ctx.Done():\n\t\t\t\t\t// return here or we'll leak a goroutine.\n\t\t\t\t\treturnCh \u003c- fmt.Errorf(\"error when evicting pods/%q -n %q: global timeout reached: %v\", pod.Name, pod.Namespace, globalTimeout)\n\t\t\t\t\treturn\n\t\t\t\tdefault:\n\t\t\t\t}\n\n\t\t\t\t// Create a temporary pod so we don't mutate the pod in the loop.\n\t\t\t\tactivePod := pod\n\t\t\t\tif refreshPod {\n\t\t\t\t\tfreshPod, err := getPodFn(pod.Namespace, pod.Name)\n\t\t\t\t\t// We ignore errors and let eviction sort it out with\n\t\t\t\t\t// the original pod.\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tactivePod = *freshPod\n\t\t\t\t\t}\n\t\t\t\t\trefreshPod = false\n\t\t\t\t}\n\n\t\t\t\terr := d.EvictPod(activePod, evictionGroupVersion)\n\t\t\t\tif err == nil {\n\t\t\t\t\tbreak\n\t\t\t\t} else if apierrors.IsNotFound(err) {\n\t\t\t\t\treturnCh \u003c- nil\n\t\t\t\t\treturn\n\t\t\t\t} else if apierrors.IsTooManyRequests(err) {\n\t\t\t\t\tfmt.Fprintf(d.ErrOut, \"error when evicting pods/%q -n %q (will retry after 5s): %v\\n\", activePod.Name, activePod.Namespace, err)\n\t\t\t\t\ttime.Sleep(5 * time.Second)\n\t\t\t\t} else if !activePod.ObjectMeta.DeletionTimestamp.IsZero() \u0026\u0026 apierrors.IsForbidden(err) \u0026\u0026 apierrors.HasStatusCause(err, corev1.NamespaceTerminatingCause) {\n\t\t\t\t\t// an eviction request in a deleting namespace will throw a forbidden error,\n\t\t\t\t\t// if the pod is already marked deleted, we can ignore this error, an eviction\n\t\t\t\t\t// request will never succeed, but we will waitForDelete for this pod.\n\t\t\t\t\tbreak\n\t\t\t\t} else if apierrors.IsForbidden(err) \u0026\u0026 apierrors.HasStatusCause(err, corev1.NamespaceTerminatingCause) {\n\t\t\t\t\t// an eviction request in a deleting namespace will throw a forbidden error,\n\t\t\t\t\t// if the pod is not marked deleted, we retry until it is.\n\t\t\t\t\tfmt.Fprintf(d.ErrOut, \"error when evicting pod %q from terminating namespace %q (will retry after 5s): %v\\n\", activePod.Name, activePod.Namespace, err)\n\t\t\t\t\ttime.Sleep(5 * time.Second)\n\t\t\t\t} else {\n\t\t\t\t\treturnCh \u003c- fmt.Errorf(\"error when evicting pods/%q -n %q: %v\", activePod.Name, activePod.Namespace, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tif d.DryRunStrategy == cmdutil.DryRunServer {\n\t\t\t\treturnCh \u003c- nil\n\t\t\t\treturn\n\t\t\t}\n\t\t\tparams := waitForDeleteParams{\n\t\t\t\tctx: ctx,\n\t\t\t\tpods: []corev1.Pod{pod},\n\t\t\t\tinterval: 1 * time.Second,\n\t\t\t\ttimeout: time.Duration(math.MaxInt64),\n\t\t\t\tusingEviction: true,\n\t\t\t\tgetPodFn: getPodFn,\n\t\t\t\tonDoneFn: d.OnPodDeletedOrEvicted,\n\t\t\t\tglobalTimeout: globalTimeout,\n\t\t\t\tskipWaitForDeleteTimeoutSeconds: d.SkipWaitForDeleteTimeoutSeconds,\n\t\t\t\tout: d.Out,\n\t\t\t}\n\t\t\t_, err := waitForDelete(params)\n\t\t\tif err == nil {\n\t\t\t\treturnCh \u003c- nil\n\t\t\t} else {\n\t\t\t\treturnCh \u003c- fmt.Errorf(\"error when waiting for pod %q in namespace %q to terminate: %v\", pod.Name, pod.Namespace, err)\n\t\t\t}\n\t\t}(pod, returnCh)\n\t}\n\n\tdoneCount := 0\n\tvar errors []error\n\n\tnumPods := len(pods)\n\tfor doneCount \u003c numPods {\n\t\tselect {\n\t\tcase err := \u003c-returnCh:\n\t\t\tdoneCount++\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn utilerrors.NewAggregate(errors)\n}","line":{"from":260,"to":365}} {"id":100032595,"name":"deletePods","signature":"func (d *Helper) deletePods(pods []corev1.Pod, getPodFn func(namespace, name string) (*corev1.Pod, error)) error","file":"staging/src/k8s.io/kubectl/pkg/drain/drain.go","code":"func (d *Helper) deletePods(pods []corev1.Pod, getPodFn func(namespace, name string) (*corev1.Pod, error)) error {\n\t// 0 timeout means infinite, we use MaxInt64 to represent it.\n\tvar globalTimeout time.Duration\n\tif d.Timeout == 0 {\n\t\tglobalTimeout = time.Duration(math.MaxInt64)\n\t} else {\n\t\tglobalTimeout = d.Timeout\n\t}\n\tfor _, pod := range pods {\n\t\terr := d.DeletePod(pod)\n\t\tif err != nil \u0026\u0026 !apierrors.IsNotFound(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\tctx := d.getContext()\n\tparams := waitForDeleteParams{\n\t\tctx: ctx,\n\t\tpods: pods,\n\t\tinterval: 1 * time.Second,\n\t\ttimeout: globalTimeout,\n\t\tusingEviction: false,\n\t\tgetPodFn: getPodFn,\n\t\tonDoneFn: d.OnPodDeletedOrEvicted,\n\t\tglobalTimeout: globalTimeout,\n\t\tskipWaitForDeleteTimeoutSeconds: d.SkipWaitForDeleteTimeoutSeconds,\n\t\tout: d.Out,\n\t}\n\t_, err := waitForDelete(params)\n\treturn err\n}","line":{"from":367,"to":396}} {"id":100032596,"name":"waitForDelete","signature":"func waitForDelete(params waitForDeleteParams) ([]corev1.Pod, error)","file":"staging/src/k8s.io/kubectl/pkg/drain/drain.go","code":"func waitForDelete(params waitForDeleteParams) ([]corev1.Pod, error) {\n\tpods := params.pods\n\terr := wait.PollImmediate(params.interval, params.timeout, func() (bool, error) {\n\t\tpendingPods := []corev1.Pod{}\n\t\tfor i, pod := range pods {\n\t\t\tp, err := params.getPodFn(pod.Namespace, pod.Name)\n\t\t\tif apierrors.IsNotFound(err) || (p != nil \u0026\u0026 p.ObjectMeta.UID != pod.ObjectMeta.UID) {\n\t\t\t\tif params.onDoneFn != nil {\n\t\t\t\t\tparams.onDoneFn(\u0026pod, params.usingEviction)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t} else if err != nil {\n\t\t\t\treturn false, err\n\t\t\t} else {\n\t\t\t\tif shouldSkipPod(*p, params.skipWaitForDeleteTimeoutSeconds) {\n\t\t\t\t\tfmt.Fprintf(params.out, podSkipMsgTemplate, pod.Name, params.skipWaitForDeleteTimeoutSeconds)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tpendingPods = append(pendingPods, pods[i])\n\t\t\t}\n\t\t}\n\t\tpods = pendingPods\n\t\tif len(pendingPods) \u003e 0 {\n\t\t\tselect {\n\t\t\tcase \u003c-params.ctx.Done():\n\t\t\t\treturn false, fmt.Errorf(\"global timeout reached: %v\", params.globalTimeout)\n\t\t\tdefault:\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t}\n\t\treturn true, nil\n\t})\n\treturn pods, err\n}","line":{"from":398,"to":431}} {"id":100032597,"name":"getContext","signature":"func (d *Helper) getContext() context.Context","file":"staging/src/k8s.io/kubectl/pkg/drain/drain.go","code":"// Since Helper does not have a constructor, we can't enforce Helper.Ctx != nil\n// Multiple public methods prevent us from initializing the context in a single\n// place as well.\nfunc (d *Helper) getContext() context.Context {\n\tif d.Ctx != nil {\n\t\treturn d.Ctx\n\t}\n\treturn context.Background()\n}","line":{"from":433,"to":441}} {"id":100032598,"name":"Pods","signature":"func (l *PodDeleteList) Pods() []corev1.Pod","file":"staging/src/k8s.io/kubectl/pkg/drain/filters.go","code":"// Pods returns a list of all pods marked for deletion after filtering.\nfunc (l *PodDeleteList) Pods() []corev1.Pod {\n\tpods := []corev1.Pod{}\n\tfor _, i := range l.items {\n\t\tif i.Status.Delete {\n\t\t\tpods = append(pods, i.Pod)\n\t\t}\n\t}\n\treturn pods\n}","line":{"from":51,"to":60}} {"id":100032599,"name":"Warnings","signature":"func (l *PodDeleteList) Warnings() string","file":"staging/src/k8s.io/kubectl/pkg/drain/filters.go","code":"// Warnings returns all warning messages concatenated into a string.\nfunc (l *PodDeleteList) Warnings() string {\n\tps := make(map[string][]string)\n\tfor _, i := range l.items {\n\t\tif i.Status.Reason == PodDeleteStatusTypeWarning {\n\t\t\tps[i.Status.Message] = append(ps[i.Status.Message], fmt.Sprintf(\"%s/%s\", i.Pod.Namespace, i.Pod.Name))\n\t\t}\n\t}\n\n\tmsgs := []string{}\n\tfor key, pods := range ps {\n\t\tmsgs = append(msgs, fmt.Sprintf(\"%s: %s\", key, strings.Join(pods, \", \")))\n\t}\n\treturn strings.Join(msgs, \"; \")\n}","line":{"from":62,"to":76}} {"id":100032600,"name":"errors","signature":"func (l *PodDeleteList) errors() []error","file":"staging/src/k8s.io/kubectl/pkg/drain/filters.go","code":"func (l *PodDeleteList) errors() []error {\n\tfailedPods := make(map[string][]string)\n\tfor _, i := range l.items {\n\t\tif i.Status.Reason == PodDeleteStatusTypeError {\n\t\t\tmsg := i.Status.Message\n\t\t\tif msg == \"\" {\n\t\t\t\tmsg = \"unexpected error\"\n\t\t\t}\n\t\t\tfailedPods[msg] = append(failedPods[msg], fmt.Sprintf(\"%s/%s\", i.Pod.Namespace, i.Pod.Name))\n\t\t}\n\t}\n\terrs := make([]error, 0, len(failedPods))\n\tfor msg, pods := range failedPods {\n\t\terrs = append(errs, fmt.Errorf(\"cannot delete %s: %s\", msg, strings.Join(pods, \", \")))\n\t}\n\treturn errs\n}","line":{"from":78,"to":94}} {"id":100032601,"name":"MakePodDeleteStatusOkay","signature":"func MakePodDeleteStatusOkay() PodDeleteStatus","file":"staging/src/k8s.io/kubectl/pkg/drain/filters.go","code":"// MakePodDeleteStatusOkay is a helper method to return the corresponding PodDeleteStatus\nfunc MakePodDeleteStatusOkay() PodDeleteStatus {\n\treturn PodDeleteStatus{\n\t\tDelete: true,\n\t\tReason: PodDeleteStatusTypeOkay,\n\t}\n}","line":{"from":117,"to":123}} {"id":100032602,"name":"MakePodDeleteStatusSkip","signature":"func MakePodDeleteStatusSkip() PodDeleteStatus","file":"staging/src/k8s.io/kubectl/pkg/drain/filters.go","code":"// MakePodDeleteStatusSkip is a helper method to return the corresponding PodDeleteStatus\nfunc MakePodDeleteStatusSkip() PodDeleteStatus {\n\treturn PodDeleteStatus{\n\t\tDelete: false,\n\t\tReason: PodDeleteStatusTypeSkip,\n\t}\n}","line":{"from":125,"to":131}} {"id":100032603,"name":"MakePodDeleteStatusWithWarning","signature":"func MakePodDeleteStatusWithWarning(delete bool, message string) PodDeleteStatus","file":"staging/src/k8s.io/kubectl/pkg/drain/filters.go","code":"// MakePodDeleteStatusWithWarning is a helper method to return the corresponding PodDeleteStatus\nfunc MakePodDeleteStatusWithWarning(delete bool, message string) PodDeleteStatus {\n\treturn PodDeleteStatus{\n\t\tDelete: delete,\n\t\tReason: PodDeleteStatusTypeWarning,\n\t\tMessage: message,\n\t}\n}","line":{"from":133,"to":140}} {"id":100032604,"name":"MakePodDeleteStatusWithError","signature":"func MakePodDeleteStatusWithError(message string) PodDeleteStatus","file":"staging/src/k8s.io/kubectl/pkg/drain/filters.go","code":"// MakePodDeleteStatusWithError is a helper method to return the corresponding PodDeleteStatus\nfunc MakePodDeleteStatusWithError(message string) PodDeleteStatus {\n\treturn PodDeleteStatus{\n\t\tDelete: false,\n\t\tReason: PodDeleteStatusTypeError,\n\t\tMessage: message,\n\t}\n}","line":{"from":142,"to":149}} {"id":100032605,"name":"makeFilters","signature":"func (d *Helper) makeFilters() []PodFilter","file":"staging/src/k8s.io/kubectl/pkg/drain/filters.go","code":"// The filters are applied in a specific order, only the last filter's\n// message will be retained if there are any warnings.\nfunc (d *Helper) makeFilters() []PodFilter {\n\tbaseFilters := []PodFilter{\n\t\td.skipDeletedFilter,\n\t\td.daemonSetFilter,\n\t\td.mirrorPodFilter,\n\t\td.localStorageFilter,\n\t\td.unreplicatedFilter,\n\t}\n\treturn append(baseFilters, d.AdditionalFilters...)\n}","line":{"from":151,"to":162}} {"id":100032606,"name":"hasLocalStorage","signature":"func hasLocalStorage(pod corev1.Pod) bool","file":"staging/src/k8s.io/kubectl/pkg/drain/filters.go","code":"func hasLocalStorage(pod corev1.Pod) bool {\n\tfor _, volume := range pod.Spec.Volumes {\n\t\tif volume.EmptyDir != nil {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":164,"to":172}} {"id":100032607,"name":"daemonSetFilter","signature":"func (d *Helper) daemonSetFilter(pod corev1.Pod) PodDeleteStatus","file":"staging/src/k8s.io/kubectl/pkg/drain/filters.go","code":"func (d *Helper) daemonSetFilter(pod corev1.Pod) PodDeleteStatus {\n\t// Note that we return false in cases where the pod is DaemonSet managed,\n\t// regardless of flags.\n\t//\n\t// The exception is for pods that are orphaned (the referencing\n\t// management resource - including DaemonSet - is not found).\n\t// Such pods will be deleted if --force is used.\n\tcontrollerRef := metav1.GetControllerOf(\u0026pod)\n\tif controllerRef == nil || controllerRef.Kind != appsv1.SchemeGroupVersion.WithKind(\"DaemonSet\").Kind {\n\t\treturn MakePodDeleteStatusOkay()\n\t}\n\t// Any finished pod can be removed.\n\tif pod.Status.Phase == corev1.PodSucceeded || pod.Status.Phase == corev1.PodFailed {\n\t\treturn MakePodDeleteStatusOkay()\n\t}\n\n\tif _, err := d.Client.AppsV1().DaemonSets(pod.Namespace).Get(context.TODO(), controllerRef.Name, metav1.GetOptions{}); err != nil {\n\t\t// remove orphaned pods with a warning if --force is used\n\t\tif apierrors.IsNotFound(err) \u0026\u0026 d.Force {\n\t\t\treturn MakePodDeleteStatusWithWarning(true, err.Error())\n\t\t}\n\n\t\treturn MakePodDeleteStatusWithError(err.Error())\n\t}\n\n\tif !d.IgnoreAllDaemonSets {\n\t\treturn MakePodDeleteStatusWithError(daemonSetFatal)\n\t}\n\n\treturn MakePodDeleteStatusWithWarning(false, daemonSetWarning)\n}","line":{"from":174,"to":204}} {"id":100032608,"name":"mirrorPodFilter","signature":"func (d *Helper) mirrorPodFilter(pod corev1.Pod) PodDeleteStatus","file":"staging/src/k8s.io/kubectl/pkg/drain/filters.go","code":"func (d *Helper) mirrorPodFilter(pod corev1.Pod) PodDeleteStatus {\n\tif _, found := pod.ObjectMeta.Annotations[corev1.MirrorPodAnnotationKey]; found {\n\t\treturn MakePodDeleteStatusSkip()\n\t}\n\treturn MakePodDeleteStatusOkay()\n}","line":{"from":206,"to":211}} {"id":100032609,"name":"localStorageFilter","signature":"func (d *Helper) localStorageFilter(pod corev1.Pod) PodDeleteStatus","file":"staging/src/k8s.io/kubectl/pkg/drain/filters.go","code":"func (d *Helper) localStorageFilter(pod corev1.Pod) PodDeleteStatus {\n\tif !hasLocalStorage(pod) {\n\t\treturn MakePodDeleteStatusOkay()\n\t}\n\t// Any finished pod can be removed.\n\tif pod.Status.Phase == corev1.PodSucceeded || pod.Status.Phase == corev1.PodFailed {\n\t\treturn MakePodDeleteStatusOkay()\n\t}\n\tif !d.DeleteEmptyDirData {\n\t\treturn MakePodDeleteStatusWithError(localStorageFatal)\n\t}\n\n\t// TODO: this warning gets dropped by subsequent filters;\n\t// consider accounting for multiple warning conditions or at least\n\t// preserving the last warning message.\n\treturn MakePodDeleteStatusWithWarning(true, localStorageWarning)\n}","line":{"from":213,"to":229}} {"id":100032610,"name":"unreplicatedFilter","signature":"func (d *Helper) unreplicatedFilter(pod corev1.Pod) PodDeleteStatus","file":"staging/src/k8s.io/kubectl/pkg/drain/filters.go","code":"func (d *Helper) unreplicatedFilter(pod corev1.Pod) PodDeleteStatus {\n\t// any finished pod can be removed\n\tif pod.Status.Phase == corev1.PodSucceeded || pod.Status.Phase == corev1.PodFailed {\n\t\treturn MakePodDeleteStatusOkay()\n\t}\n\n\tcontrollerRef := metav1.GetControllerOf(\u0026pod)\n\tif controllerRef != nil {\n\t\treturn MakePodDeleteStatusOkay()\n\t}\n\tif d.Force {\n\t\treturn MakePodDeleteStatusWithWarning(true, unmanagedWarning)\n\t}\n\treturn MakePodDeleteStatusWithError(unmanagedFatal)\n}","line":{"from":231,"to":245}} {"id":100032611,"name":"shouldSkipPod","signature":"func shouldSkipPod(pod corev1.Pod, skipDeletedTimeoutSeconds int) bool","file":"staging/src/k8s.io/kubectl/pkg/drain/filters.go","code":"func shouldSkipPod(pod corev1.Pod, skipDeletedTimeoutSeconds int) bool {\n\treturn skipDeletedTimeoutSeconds \u003e 0 \u0026\u0026\n\t\t!pod.ObjectMeta.DeletionTimestamp.IsZero() \u0026\u0026\n\t\tint(time.Now().Sub(pod.ObjectMeta.GetDeletionTimestamp().Time).Seconds()) \u003e skipDeletedTimeoutSeconds\n}","line":{"from":247,"to":251}} {"id":100032612,"name":"skipDeletedFilter","signature":"func (d *Helper) skipDeletedFilter(pod corev1.Pod) PodDeleteStatus","file":"staging/src/k8s.io/kubectl/pkg/drain/filters.go","code":"func (d *Helper) skipDeletedFilter(pod corev1.Pod) PodDeleteStatus {\n\tif shouldSkipPod(pod, d.SkipWaitForDeleteTimeoutSeconds) {\n\t\treturn MakePodDeleteStatusSkip()\n\t}\n\treturn MakePodDeleteStatusOkay()\n}","line":{"from":253,"to":258}} {"id":100032613,"name":"splitDotNotation","signature":"func splitDotNotation(model string) (string, []string)","file":"staging/src/k8s.io/kubectl/pkg/explain/explain.go","code":"func splitDotNotation(model string) (string, []string) {\n\tvar fieldsPath []string\n\n\t// ignore trailing period\n\tmodel = strings.TrimSuffix(model, \".\")\n\n\tdotModel := strings.Split(model, \".\")\n\tif len(dotModel) \u003e= 1 {\n\t\tfieldsPath = dotModel[1:]\n\t}\n\treturn dotModel[0], fieldsPath\n}","line":{"from":33,"to":44}} {"id":100032614,"name":"SplitAndParseResourceRequest","signature":"func SplitAndParseResourceRequest(inResource string, mapper meta.RESTMapper) (schema.GroupVersionResource, []string, error)","file":"staging/src/k8s.io/kubectl/pkg/explain/explain.go","code":"// SplitAndParseResourceRequest separates the users input into a model and fields\nfunc SplitAndParseResourceRequest(inResource string, mapper meta.RESTMapper) (schema.GroupVersionResource, []string, error) {\n\tinResource, fieldsPath := splitDotNotation(inResource)\n\tgvr, err := mapper.ResourceFor(schema.GroupVersionResource{Resource: inResource})\n\tif err != nil {\n\t\treturn schema.GroupVersionResource{}, nil, err\n\t}\n\n\treturn gvr, fieldsPath, nil\n}","line":{"from":46,"to":55}} {"id":100032615,"name":"SplitAndParseResourceRequestWithMatchingPrefix","signature":"func SplitAndParseResourceRequestWithMatchingPrefix(inResource string, mapper meta.RESTMapper) (gvr schema.GroupVersionResource, fieldsPath []string, err error)","file":"staging/src/k8s.io/kubectl/pkg/explain/explain.go","code":"// SplitAndParseResourceRequestWithMatchingPrefix separates the users input into a model and fields\n// while selecting gvr whose (resource, group) prefix matches the resource\nfunc SplitAndParseResourceRequestWithMatchingPrefix(inResource string, mapper meta.RESTMapper) (gvr schema.GroupVersionResource, fieldsPath []string, err error) {\n\t// ignore trailing period\n\tinResource = strings.TrimSuffix(inResource, \".\")\n\tdotParts := strings.Split(inResource, \".\")\n\n\tgvrs, err := mapper.ResourcesFor(schema.GroupVersionResource{Resource: dotParts[0]})\n\tif err != nil {\n\t\treturn schema.GroupVersionResource{}, nil, err\n\t}\n\n\tfor _, gvrItem := range gvrs {\n\t\t// Find first gvr whose gr prefixes requested resource\n\t\tgroupResource := gvrItem.GroupResource().String()\n\t\tif strings.HasPrefix(inResource, groupResource) {\n\t\t\tresourceSuffix := inResource[len(groupResource):]\n\t\t\tif len(resourceSuffix) \u003e 0 {\n\t\t\t\tdotParts := strings.Split(resourceSuffix, \".\")\n\t\t\t\tif len(dotParts) \u003e 0 {\n\t\t\t\t\tfieldsPath = dotParts[1:]\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn gvrItem, fieldsPath, nil\n\t\t}\n\t}\n\n\t// If no match, take the first (the highest priority) gvr\n\tif len(gvrs) \u003e 0 {\n\t\tgvr = gvrs[0]\n\t\t_, fieldsPath = splitDotNotation(inResource)\n\t}\n\n\treturn gvr, fieldsPath, nil\n}","line":{"from":57,"to":91}} {"id":100032616,"name":"PrintModelDescription","signature":"func PrintModelDescription(fieldsPath []string, w io.Writer, schema proto.Schema, gvk schema.GroupVersionKind, recursive bool) error","file":"staging/src/k8s.io/kubectl/pkg/explain/explain.go","code":"// PrintModelDescription prints the description of a specific model or dot path.\n// If recursive, all components nested within the fields of the schema will be\n// printed.\nfunc PrintModelDescription(fieldsPath []string, w io.Writer, schema proto.Schema, gvk schema.GroupVersionKind, recursive bool) error {\n\tfieldName := \"\"\n\tif len(fieldsPath) != 0 {\n\t\tfieldName = fieldsPath[len(fieldsPath)-1]\n\t}\n\n\t// Go down the fieldsPath to find what we're trying to explain\n\tschema, err := LookupSchemaForField(schema, fieldsPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tb := fieldsPrinterBuilder{Recursive: recursive}\n\tf := \u0026Formatter{Writer: w, Wrap: 80}\n\treturn PrintModel(fieldName, f, b, schema, gvk)\n}","line":{"from":93,"to":110}} {"id":100032617,"name":"SaveLeafSchema","signature":"func (f *fieldLookup) SaveLeafSchema(schema proto.Schema) bool","file":"staging/src/k8s.io/kubectl/pkg/explain/field_lookup.go","code":"// SaveLeafSchema is used to detect if we are done walking the path, and\n// saves the schema as a match.\nfunc (f *fieldLookup) SaveLeafSchema(schema proto.Schema) bool {\n\tif len(f.Path) != 0 {\n\t\treturn false\n\t}\n\n\tf.Schema = schema\n\n\treturn true\n}","line":{"from":36,"to":46}} {"id":100032618,"name":"VisitArray","signature":"func (f *fieldLookup) VisitArray(a *proto.Array)","file":"staging/src/k8s.io/kubectl/pkg/explain/field_lookup.go","code":"// VisitArray is mostly a passthrough.\nfunc (f *fieldLookup) VisitArray(a *proto.Array) {\n\tif f.SaveLeafSchema(a) {\n\t\treturn\n\t}\n\n\t// Passthrough arrays.\n\ta.SubType.Accept(f)\n}","line":{"from":48,"to":56}} {"id":100032619,"name":"VisitMap","signature":"func (f *fieldLookup) VisitMap(m *proto.Map)","file":"staging/src/k8s.io/kubectl/pkg/explain/field_lookup.go","code":"// VisitMap is mostly a passthrough.\nfunc (f *fieldLookup) VisitMap(m *proto.Map) {\n\tif f.SaveLeafSchema(m) {\n\t\treturn\n\t}\n\n\t// Passthrough maps.\n\tm.SubType.Accept(f)\n}","line":{"from":58,"to":66}} {"id":100032620,"name":"VisitPrimitive","signature":"func (f *fieldLookup) VisitPrimitive(p *proto.Primitive)","file":"staging/src/k8s.io/kubectl/pkg/explain/field_lookup.go","code":"// VisitPrimitive stops the operation and returns itself as the found\n// schema, even if it had more path to walk.\nfunc (f *fieldLookup) VisitPrimitive(p *proto.Primitive) {\n\t// Even if Path is not empty (we're not expecting a leaf),\n\t// return that primitive.\n\tf.Schema = p\n}","line":{"from":68,"to":74}} {"id":100032621,"name":"VisitKind","signature":"func (f *fieldLookup) VisitKind(k *proto.Kind)","file":"staging/src/k8s.io/kubectl/pkg/explain/field_lookup.go","code":"// VisitKind unstacks fields as it finds them.\nfunc (f *fieldLookup) VisitKind(k *proto.Kind) {\n\tif f.SaveLeafSchema(k) {\n\t\treturn\n\t}\n\n\tsubSchema, ok := k.Fields[f.Path[0]]\n\tif !ok {\n\t\tf.Error = fmt.Errorf(\"field %q does not exist\", f.Path[0])\n\t\treturn\n\t}\n\n\tf.Path = f.Path[1:]\n\tsubSchema.Accept(f)\n}","line":{"from":76,"to":90}} {"id":100032622,"name":"VisitArbitrary","signature":"func (f *fieldLookup) VisitArbitrary(a *proto.Arbitrary)","file":"staging/src/k8s.io/kubectl/pkg/explain/field_lookup.go","code":"func (f *fieldLookup) VisitArbitrary(a *proto.Arbitrary) {\n\tf.Schema = a\n}","line":{"from":92,"to":94}} {"id":100032623,"name":"VisitReference","signature":"func (f *fieldLookup) VisitReference(r proto.Reference)","file":"staging/src/k8s.io/kubectl/pkg/explain/field_lookup.go","code":"// VisitReference is mostly a passthrough.\nfunc (f *fieldLookup) VisitReference(r proto.Reference) {\n\tif f.SaveLeafSchema(r) {\n\t\treturn\n\t}\n\n\t// Passthrough references.\n\tr.SubSchema().Accept(f)\n}","line":{"from":96,"to":104}} {"id":100032624,"name":"LookupSchemaForField","signature":"func LookupSchemaForField(schema proto.Schema, path []string) (proto.Schema, error)","file":"staging/src/k8s.io/kubectl/pkg/explain/field_lookup.go","code":"// LookupSchemaForField looks for the schema of a given path in a base schema.\nfunc LookupSchemaForField(schema proto.Schema, path []string) (proto.Schema, error) {\n\tf := \u0026fieldLookup{Path: path}\n\tschema.Accept(f)\n\treturn f.Schema, f.Error\n}","line":{"from":106,"to":111}} {"id":100032625,"name":"VisitArray","signature":"func (f *regularFieldsPrinter) VisitArray(a *proto.Array)","file":"staging/src/k8s.io/kubectl/pkg/explain/fields_printer.go","code":"// VisitArray prints a Array type. It is just a passthrough.\nfunc (f *regularFieldsPrinter) VisitArray(a *proto.Array) {\n\ta.SubType.Accept(f)\n}","line":{"from":33,"to":36}} {"id":100032626,"name":"VisitKind","signature":"func (f *regularFieldsPrinter) VisitKind(k *proto.Kind)","file":"staging/src/k8s.io/kubectl/pkg/explain/fields_printer.go","code":"// VisitKind prints a Kind type. It prints each key in the kind, with\n// the type, the required flag, and the description.\nfunc (f *regularFieldsPrinter) VisitKind(k *proto.Kind) {\n\tfor _, key := range k.Keys() {\n\t\tv := k.Fields[key]\n\t\trequired := \"\"\n\t\tif k.IsRequired(key) {\n\t\t\trequired = \" -required-\"\n\t\t}\n\n\t\tif err := f.Writer.Write(\"%s\\t\u003c%s\u003e%s\", key, GetTypeName(v), required); err != nil {\n\t\t\tf.Error = err\n\t\t\treturn\n\t\t}\n\t\tif err := f.Writer.Indent(indentDesc).WriteWrapped(\"%s\", v.GetDescription()); err != nil {\n\t\t\tf.Error = err\n\t\t\treturn\n\t\t}\n\t\tif err := f.Writer.Write(\"\"); err != nil {\n\t\t\tf.Error = err\n\t\t\treturn\n\t\t}\n\t}\n}","line":{"from":38,"to":61}} {"id":100032627,"name":"VisitMap","signature":"func (f *regularFieldsPrinter) VisitMap(m *proto.Map)","file":"staging/src/k8s.io/kubectl/pkg/explain/fields_printer.go","code":"// VisitMap prints a Map type. It is just a passthrough.\nfunc (f *regularFieldsPrinter) VisitMap(m *proto.Map) {\n\tm.SubType.Accept(f)\n}","line":{"from":63,"to":66}} {"id":100032628,"name":"VisitPrimitive","signature":"func (f *regularFieldsPrinter) VisitPrimitive(p *proto.Primitive)","file":"staging/src/k8s.io/kubectl/pkg/explain/fields_printer.go","code":"// VisitPrimitive prints a Primitive type. It stops the recursion.\nfunc (f *regularFieldsPrinter) VisitPrimitive(p *proto.Primitive) {\n\t// Nothing to do. Shouldn't really happen.\n}","line":{"from":68,"to":71}} {"id":100032629,"name":"VisitReference","signature":"func (f *regularFieldsPrinter) VisitReference(r proto.Reference)","file":"staging/src/k8s.io/kubectl/pkg/explain/fields_printer.go","code":"// VisitReference prints a Reference type. It is just a passthrough.\nfunc (f *regularFieldsPrinter) VisitReference(r proto.Reference) {\n\tr.SubSchema().Accept(f)\n}","line":{"from":73,"to":76}} {"id":100032630,"name":"PrintFields","signature":"func (f *regularFieldsPrinter) PrintFields(schema proto.Schema) error","file":"staging/src/k8s.io/kubectl/pkg/explain/fields_printer.go","code":"// PrintFields will write the types from schema.\nfunc (f *regularFieldsPrinter) PrintFields(schema proto.Schema) error {\n\tschema.Accept(f)\n\treturn f.Error\n}","line":{"from":78,"to":82}} {"id":100032631,"name":"BuildFieldsPrinter","signature":"func (f fieldsPrinterBuilder) BuildFieldsPrinter(writer *Formatter) fieldsPrinter","file":"staging/src/k8s.io/kubectl/pkg/explain/fields_printer_builder.go","code":"// BuildFieldsPrinter builds the appropriate fieldsPrinter.\nfunc (f fieldsPrinterBuilder) BuildFieldsPrinter(writer *Formatter) fieldsPrinter {\n\tif f.Recursive {\n\t\treturn \u0026recursiveFieldsPrinter{\n\t\t\tWriter: writer,\n\t\t}\n\t}\n\n\treturn \u0026regularFieldsPrinter{\n\t\tWriter: writer,\n\t}\n}","line":{"from":25,"to":36}} {"id":100032632,"name":"Indent","signature":"func (f Formatter) Indent(indent int) *Formatter","file":"staging/src/k8s.io/kubectl/pkg/explain/formatter.go","code":"// Indent creates a new Formatter that will indent the code by that much more.\nfunc (f Formatter) Indent(indent int) *Formatter {\n\tf.IndentLevel = f.IndentLevel + indent\n\treturn \u0026f\n}","line":{"from":33,"to":37}} {"id":100032633,"name":"Write","signature":"func (f *Formatter) Write(str string, a ...interface{}) error","file":"staging/src/k8s.io/kubectl/pkg/explain/formatter.go","code":"// Write writes a string with the indentation set for the\n// Formatter. This is not wrapping text.\nfunc (f *Formatter) Write(str string, a ...interface{}) error {\n\t// Don't indent empty lines\n\tif str == \"\" {\n\t\t_, err := io.WriteString(f.Writer, \"\\n\")\n\t\treturn err\n\t}\n\n\tindent := \"\"\n\tfor i := 0; i \u003c f.IndentLevel; i++ {\n\t\tindent = indent + \" \"\n\t}\n\n\tif len(a) \u003e 0 {\n\t\tstr = fmt.Sprintf(str, a...)\n\t}\n\t_, err := io.WriteString(f.Writer, indent+str+\"\\n\")\n\treturn err\n}","line":{"from":39,"to":58}} {"id":100032634,"name":"WriteWrapped","signature":"func (f *Formatter) WriteWrapped(str string, a ...interface{}) error","file":"staging/src/k8s.io/kubectl/pkg/explain/formatter.go","code":"// WriteWrapped writes a string with the indentation set for the\n// Formatter, and wraps as needed.\nfunc (f *Formatter) WriteWrapped(str string, a ...interface{}) error {\n\tif f.Wrap == 0 {\n\t\treturn f.Write(str, a...)\n\t}\n\ttext := fmt.Sprintf(str, a...)\n\tstrs := wrapString(text, f.Wrap-f.IndentLevel)\n\tfor _, substr := range strs {\n\t\tif err := f.Write(substr); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":60,"to":74}} {"id":100032635,"name":"String","signature":"func (l *line) String() string","file":"staging/src/k8s.io/kubectl/pkg/explain/formatter.go","code":"func (l *line) String() string {\n\treturn strings.Join(l.words, \" \")\n}","line":{"from":81,"to":83}} {"id":100032636,"name":"Empty","signature":"func (l *line) Empty() bool","file":"staging/src/k8s.io/kubectl/pkg/explain/formatter.go","code":"func (l *line) Empty() bool {\n\treturn len(l.words) == 0\n}","line":{"from":85,"to":87}} {"id":100032637,"name":"Len","signature":"func (l *line) Len() int","file":"staging/src/k8s.io/kubectl/pkg/explain/formatter.go","code":"func (l *line) Len() int {\n\treturn len(l.String())\n}","line":{"from":89,"to":91}} {"id":100032638,"name":"Add","signature":"func (l *line) Add(word string) bool","file":"staging/src/k8s.io/kubectl/pkg/explain/formatter.go","code":"// Add adds the word to the line, returns true if we could, false if we\n// didn't have enough room. It's always possible to add to an empty line.\nfunc (l *line) Add(word string) bool {\n\tnewLine := line{\n\t\twrap: l.wrap,\n\t\twords: append(l.words, word),\n\t}\n\tif newLine.Len() \u003c= l.wrap || len(l.words) == 0 {\n\t\tl.words = newLine.words\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":93,"to":105}} {"id":100032639,"name":"shouldStartNewLine","signature":"func shouldStartNewLine(lastWord, str string) bool","file":"staging/src/k8s.io/kubectl/pkg/explain/formatter.go","code":"func shouldStartNewLine(lastWord, str string) bool {\n\t// preserve line breaks ending in :\n\tif strings.HasSuffix(lastWord, \":\") {\n\t\treturn true\n\t}\n\n\t// preserve code blocks\n\tif strings.HasPrefix(str, \" \") {\n\t\treturn true\n\t}\n\tstr = strings.TrimSpace(str)\n\t// preserve empty lines\n\tif len(str) == 0 {\n\t\treturn true\n\t}\n\t// preserve lines that look like they're starting lists\n\tif bullet.MatchString(str) {\n\t\treturn true\n\t}\n\t// otherwise combine\n\treturn false\n}","line":{"from":109,"to":130}} {"id":100032640,"name":"wrapString","signature":"func wrapString(str string, wrap int) []string","file":"staging/src/k8s.io/kubectl/pkg/explain/formatter.go","code":"func wrapString(str string, wrap int) []string {\n\twrapped := []string{}\n\tl := line{wrap: wrap}\n\t// track the last word added to the current line\n\tlastWord := \"\"\n\tflush := func() {\n\t\tif !l.Empty() {\n\t\t\tlastWord = \"\"\n\t\t\twrapped = append(wrapped, l.String())\n\t\t\tl = line{wrap: wrap}\n\t\t}\n\t}\n\n\t// iterate over the lines in the original description\n\tfor _, str := range strings.Split(str, \"\\n\") {\n\t\t// preserve code blocks and blockquotes as-is\n\t\tif strings.HasPrefix(str, \" \") {\n\t\t\tflush()\n\t\t\twrapped = append(wrapped, str)\n\t\t\tcontinue\n\t\t}\n\n\t\t// preserve empty lines after the first line, since they can separate logical sections\n\t\tif len(wrapped) \u003e 0 \u0026\u0026 len(strings.TrimSpace(str)) == 0 {\n\t\t\tflush()\n\t\t\twrapped = append(wrapped, \"\")\n\t\t\tcontinue\n\t\t}\n\n\t\t// flush if we should start a new line\n\t\tif shouldStartNewLine(lastWord, str) {\n\t\t\tflush()\n\t\t}\n\t\twords := strings.Fields(str)\n\t\tfor _, word := range words {\n\t\t\tlastWord = word\n\t\t\tif !l.Add(word) {\n\t\t\t\tflush()\n\t\t\t\tif !l.Add(word) {\n\t\t\t\t\tpanic(\"Couldn't add to empty line.\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tflush()\n\treturn wrapped\n}","line":{"from":132,"to":178}} {"id":100032641,"name":"PrintKindAndVersion","signature":"func (m *modelPrinter) PrintKindAndVersion() error","file":"staging/src/k8s.io/kubectl/pkg/explain/model_printer.go","code":"func (m *modelPrinter) PrintKindAndVersion() error {\n\tif err := m.Writer.Write(\"KIND: %s\", m.GVK.Kind); err != nil {\n\t\treturn err\n\t}\n\treturn m.Writer.Write(\"VERSION: %s\\n\", m.GVK.GroupVersion())\n}","line":{"from":46,"to":51}} {"id":100032642,"name":"PrintDescription","signature":"func (m *modelPrinter) PrintDescription(schema proto.Schema) error","file":"staging/src/k8s.io/kubectl/pkg/explain/model_printer.go","code":"// PrintDescription prints the description for a given schema. There\n// might be multiple description, since we collect descriptions when we\n// go through references, arrays and maps.\nfunc (m *modelPrinter) PrintDescription(schema proto.Schema) error {\n\tif err := m.Writer.Write(\"DESCRIPTION:\"); err != nil {\n\t\treturn err\n\t}\n\tempty := true\n\tfor i, desc := range append(m.Descriptions, schema.GetDescription()) {\n\t\tif desc == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tempty = false\n\t\tif i != 0 {\n\t\t\tif err := m.Writer.Write(\"\"); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif err := m.Writer.Indent(descriptionIndentLevel).WriteWrapped(\"%s\", desc); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif empty {\n\t\treturn m.Writer.Indent(descriptionIndentLevel).WriteWrapped(\"\u003cempty\u003e\")\n\t}\n\treturn nil\n}","line":{"from":53,"to":79}} {"id":100032643,"name":"VisitArray","signature":"func (m *modelPrinter) VisitArray(a *proto.Array)","file":"staging/src/k8s.io/kubectl/pkg/explain/model_printer.go","code":"// VisitArray recurses inside the subtype, while collecting the type if\n// not done yet, and the description.\nfunc (m *modelPrinter) VisitArray(a *proto.Array) {\n\tm.Descriptions = append(m.Descriptions, a.GetDescription())\n\tif m.Type == \"\" {\n\t\tm.Type = GetTypeName(a)\n\t}\n\ta.SubType.Accept(m)\n}","line":{"from":81,"to":89}} {"id":100032644,"name":"VisitKind","signature":"func (m *modelPrinter) VisitKind(k *proto.Kind)","file":"staging/src/k8s.io/kubectl/pkg/explain/model_printer.go","code":"// VisitKind prints a full resource with its fields.\nfunc (m *modelPrinter) VisitKind(k *proto.Kind) {\n\tif err := m.PrintKindAndVersion(); err != nil {\n\t\tm.Error = err\n\t\treturn\n\t}\n\n\tif m.Type == \"\" {\n\t\tm.Type = GetTypeName(k)\n\t}\n\tif m.Name != \"\" {\n\t\tm.Writer.Write(\"RESOURCE: %s \u003c%s\u003e\\n\", m.Name, m.Type)\n\t}\n\n\tif err := m.PrintDescription(k); err != nil {\n\t\tm.Error = err\n\t\treturn\n\t}\n\tif err := m.Writer.Write(\"\\nFIELDS:\"); err != nil {\n\t\tm.Error = err\n\t\treturn\n\t}\n\tm.Error = m.Builder.BuildFieldsPrinter(m.Writer.Indent(fieldIndentLevel)).PrintFields(k)\n}","line":{"from":91,"to":114}} {"id":100032645,"name":"VisitMap","signature":"func (m *modelPrinter) VisitMap(om *proto.Map)","file":"staging/src/k8s.io/kubectl/pkg/explain/model_printer.go","code":"// VisitMap recurses inside the subtype, while collecting the type if\n// not done yet, and the description.\nfunc (m *modelPrinter) VisitMap(om *proto.Map) {\n\tm.Descriptions = append(m.Descriptions, om.GetDescription())\n\tif m.Type == \"\" {\n\t\tm.Type = GetTypeName(om)\n\t}\n\tom.SubType.Accept(m)\n}","line":{"from":116,"to":124}} {"id":100032646,"name":"VisitPrimitive","signature":"func (m *modelPrinter) VisitPrimitive(p *proto.Primitive)","file":"staging/src/k8s.io/kubectl/pkg/explain/model_printer.go","code":"// VisitPrimitive prints a field type and its description.\nfunc (m *modelPrinter) VisitPrimitive(p *proto.Primitive) {\n\tif err := m.PrintKindAndVersion(); err != nil {\n\t\tm.Error = err\n\t\treturn\n\t}\n\n\tif m.Type == \"\" {\n\t\tm.Type = GetTypeName(p)\n\t}\n\tif err := m.Writer.Write(\"FIELD: %s \u003c%s\u003e\\n\", m.Name, m.Type); err != nil {\n\t\tm.Error = err\n\t\treturn\n\t}\n\tm.Error = m.PrintDescription(p)\n}","line":{"from":126,"to":141}} {"id":100032647,"name":"VisitArbitrary","signature":"func (m *modelPrinter) VisitArbitrary(a *proto.Arbitrary)","file":"staging/src/k8s.io/kubectl/pkg/explain/model_printer.go","code":"func (m *modelPrinter) VisitArbitrary(a *proto.Arbitrary) {\n\tif err := m.PrintKindAndVersion(); err != nil {\n\t\tm.Error = err\n\t\treturn\n\t}\n\n\tm.Error = m.PrintDescription(a)\n}","line":{"from":143,"to":150}} {"id":100032648,"name":"VisitReference","signature":"func (m *modelPrinter) VisitReference(r proto.Reference)","file":"staging/src/k8s.io/kubectl/pkg/explain/model_printer.go","code":"// VisitReference recurses inside the subtype, while collecting the description.\nfunc (m *modelPrinter) VisitReference(r proto.Reference) {\n\tm.Descriptions = append(m.Descriptions, r.GetDescription())\n\tr.SubSchema().Accept(m)\n}","line":{"from":152,"to":156}} {"id":100032649,"name":"PrintModel","signature":"func PrintModel(name string, writer *Formatter, builder fieldsPrinterBuilder, schema proto.Schema, gvk schema.GroupVersionKind) error","file":"staging/src/k8s.io/kubectl/pkg/explain/model_printer.go","code":"// PrintModel prints the description of a schema in writer.\nfunc PrintModel(name string, writer *Formatter, builder fieldsPrinterBuilder, schema proto.Schema, gvk schema.GroupVersionKind) error {\n\tm := \u0026modelPrinter{Name: name, Writer: writer, Builder: builder, GVK: gvk}\n\tschema.Accept(m)\n\treturn m.Error\n}","line":{"from":158,"to":163}} {"id":100032650,"name":"VisitArray","signature":"func (f *recursiveFieldsPrinter) VisitArray(a *proto.Array)","file":"staging/src/k8s.io/kubectl/pkg/explain/recursive_fields_printer.go","code":"// VisitArray is just a passthrough.\nfunc (f *recursiveFieldsPrinter) VisitArray(a *proto.Array) {\n\ta.SubType.Accept(f)\n}","line":{"from":35,"to":38}} {"id":100032651,"name":"VisitKind","signature":"func (f *recursiveFieldsPrinter) VisitKind(k *proto.Kind)","file":"staging/src/k8s.io/kubectl/pkg/explain/recursive_fields_printer.go","code":"// VisitKind prints all its fields with their type, and then recurses\n// inside each of these (pre-order).\nfunc (f *recursiveFieldsPrinter) VisitKind(k *proto.Kind) {\n\tfor _, key := range k.Keys() {\n\t\tv := k.Fields[key]\n\t\tf.Writer.Write(\"%s\\t\u003c%s\u003e\", key, GetTypeName(v))\n\t\tsubFields := \u0026recursiveFieldsPrinter{\n\t\t\tWriter: f.Writer.Indent(indentPerLevel),\n\t\t}\n\t\tif err := subFields.PrintFields(v); err != nil {\n\t\t\tf.Error = err\n\t\t\treturn\n\t\t}\n\t}\n}","line":{"from":40,"to":54}} {"id":100032652,"name":"VisitMap","signature":"func (f *recursiveFieldsPrinter) VisitMap(m *proto.Map)","file":"staging/src/k8s.io/kubectl/pkg/explain/recursive_fields_printer.go","code":"// VisitMap is just a passthrough.\nfunc (f *recursiveFieldsPrinter) VisitMap(m *proto.Map) {\n\tm.SubType.Accept(f)\n}","line":{"from":56,"to":59}} {"id":100032653,"name":"VisitPrimitive","signature":"func (f *recursiveFieldsPrinter) VisitPrimitive(p *proto.Primitive)","file":"staging/src/k8s.io/kubectl/pkg/explain/recursive_fields_printer.go","code":"// VisitPrimitive does nothing, since it doesn't have sub-fields.\nfunc (f *recursiveFieldsPrinter) VisitPrimitive(p *proto.Primitive) {\n\t// Nothing to do.\n}","line":{"from":61,"to":64}} {"id":100032654,"name":"VisitReference","signature":"func (f *recursiveFieldsPrinter) VisitReference(r proto.Reference)","file":"staging/src/k8s.io/kubectl/pkg/explain/recursive_fields_printer.go","code":"// VisitReference is just a passthrough.\nfunc (f *recursiveFieldsPrinter) VisitReference(r proto.Reference) {\n\tif _, ok := visitedReferences[r.Reference()]; ok {\n\t\treturn\n\t}\n\tvisitedReferences[r.Reference()] = struct{}{}\n\tr.SubSchema().Accept(f)\n\tdelete(visitedReferences, r.Reference())\n}","line":{"from":66,"to":74}} {"id":100032655,"name":"PrintFields","signature":"func (f *recursiveFieldsPrinter) PrintFields(schema proto.Schema) error","file":"staging/src/k8s.io/kubectl/pkg/explain/recursive_fields_printer.go","code":"// PrintFields will recursively print all the fields for the given\n// schema.\nfunc (f *recursiveFieldsPrinter) PrintFields(schema proto.Schema) error {\n\tschema.Accept(f)\n\treturn f.Error\n}","line":{"from":76,"to":81}} {"id":100032656,"name":"VisitArray","signature":"func (t *typeName) VisitArray(a *proto.Array)","file":"staging/src/k8s.io/kubectl/pkg/explain/typename.go","code":"// VisitArray adds the [] prefix and recurses.\nfunc (t *typeName) VisitArray(a *proto.Array) {\n\ts := \u0026typeName{}\n\ta.SubType.Accept(s)\n\tt.Name = fmt.Sprintf(\"[]%s\", s.Name)\n}","line":{"from":32,"to":37}} {"id":100032657,"name":"VisitKind","signature":"func (t *typeName) VisitKind(k *proto.Kind)","file":"staging/src/k8s.io/kubectl/pkg/explain/typename.go","code":"// VisitKind just returns \"Object\".\nfunc (t *typeName) VisitKind(k *proto.Kind) {\n\tt.Name = \"Object\"\n}","line":{"from":39,"to":42}} {"id":100032658,"name":"VisitMap","signature":"func (t *typeName) VisitMap(m *proto.Map)","file":"staging/src/k8s.io/kubectl/pkg/explain/typename.go","code":"// VisitMap adds the map[string] prefix and recurses.\nfunc (t *typeName) VisitMap(m *proto.Map) {\n\ts := \u0026typeName{}\n\tm.SubType.Accept(s)\n\tt.Name = fmt.Sprintf(\"map[string]%s\", s.Name)\n}","line":{"from":44,"to":49}} {"id":100032659,"name":"VisitPrimitive","signature":"func (t *typeName) VisitPrimitive(p *proto.Primitive)","file":"staging/src/k8s.io/kubectl/pkg/explain/typename.go","code":"// VisitPrimitive returns the name of the primitive.\nfunc (t *typeName) VisitPrimitive(p *proto.Primitive) {\n\tt.Name = p.Type\n}","line":{"from":51,"to":54}} {"id":100032660,"name":"VisitReference","signature":"func (t *typeName) VisitReference(r proto.Reference)","file":"staging/src/k8s.io/kubectl/pkg/explain/typename.go","code":"// VisitReference is just a passthrough.\nfunc (t *typeName) VisitReference(r proto.Reference) {\n\tr.SubSchema().Accept(t)\n}","line":{"from":56,"to":59}} {"id":100032661,"name":"GetTypeName","signature":"func GetTypeName(schema proto.Schema) string","file":"staging/src/k8s.io/kubectl/pkg/explain/typename.go","code":"// GetTypeName returns the type of a schema.\nfunc GetTypeName(schema proto.Schema) string {\n\tt := \u0026typeName{}\n\tschema.Accept(t)\n\treturn t.Name\n}","line":{"from":61,"to":66}} {"id":100032662,"name":"PrintModelDescription","signature":"func PrintModelDescription(","file":"staging/src/k8s.io/kubectl/pkg/explain/v2/explain.go","code":"// PrintModelDescription prints the description of a specific model or dot path.\n// If recursive, all components nested within the fields of the schema will be\n// printed.\nfunc PrintModelDescription(\n\tfieldsPath []string,\n\tw io.Writer,\n\tclient openapi.Client,\n\tgvr schema.GroupVersionResource,\n\trecursive bool,\n\toutputFormat string,\n) error {\n\tgenerator := NewGenerator()\n\tif err := registerBuiltinTemplates(generator); err != nil {\n\t\treturn fmt.Errorf(\"error parsing builtin templates. Please file a bug on GitHub: %w\", err)\n\t}\n\n\treturn printModelDescriptionWithGenerator(\n\t\tgenerator, fieldsPath, w, client, gvr, recursive, outputFormat)\n}","line":{"from":30,"to":48}} {"id":100032663,"name":"printModelDescriptionWithGenerator","signature":"func printModelDescriptionWithGenerator(","file":"staging/src/k8s.io/kubectl/pkg/explain/v2/explain.go","code":"// Factored out for testability\nfunc printModelDescriptionWithGenerator(\n\tgenerator Generator,\n\tfieldsPath []string,\n\tw io.Writer,\n\tclient openapi.Client,\n\tgvr schema.GroupVersionResource,\n\trecursive bool,\n\toutputFormat string,\n) error {\n\tpaths, err := client.Paths()\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to fetch list of groupVersions: %w\", err)\n\t}\n\n\tvar resourcePath string\n\tif len(gvr.Group) == 0 {\n\t\tresourcePath = fmt.Sprintf(\"api/%s\", gvr.Version)\n\t} else {\n\t\tresourcePath = fmt.Sprintf(\"apis/%s/%s\", gvr.Group, gvr.Version)\n\t}\n\n\tgv, exists := paths[resourcePath]\n\n\tif !exists {\n\t\treturn fmt.Errorf(\"couldn't find resource for \\\"%v\\\"\", gvr)\n\t}\n\n\topenAPISchemaBytes, err := gv.Schema(runtime.ContentTypeJSON)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to fetch openapi schema for %s: %w\", resourcePath, err)\n\t}\n\n\tvar parsedV3Schema map[string]interface{}\n\tif err := json.Unmarshal(openAPISchemaBytes, \u0026parsedV3Schema); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse openapi schema for %s: %w\", resourcePath, err)\n\t}\n\n\terr = generator.Render(outputFormat, parsedV3Schema, gvr, fieldsPath, recursive, w)\n\n\texplainErr := explainError(\"\")\n\tif errors.As(err, \u0026explainErr) {\n\t\treturn explainErr\n\t}\n\n\treturn err\n}","line":{"from":50,"to":97}} {"id":100032664,"name":"Error","signature":"func (e explainError) Error() string","file":"staging/src/k8s.io/kubectl/pkg/explain/v2/funcs.go","code":"func (e explainError) Error() string {\n\treturn string(e)\n}","line":{"from":34,"to":36}} {"id":100032665,"name":"WithBuiltinTemplateFuncs","signature":"func WithBuiltinTemplateFuncs(tmpl *template.Template) *template.Template","file":"staging/src/k8s.io/kubectl/pkg/explain/v2/funcs.go","code":"func WithBuiltinTemplateFuncs(tmpl *template.Template) *template.Template {\n\treturn tmpl.Funcs(map[string]interface{}{\n\t\t\"throw\": func(e string, args ...any) (string, error) {\n\t\t\terrString := fmt.Sprintf(e, args...)\n\t\t\treturn \"\", explainError(errString)\n\t\t},\n\t\t\"toJson\": func(obj any) (string, error) {\n\t\t\tres, err := json.Marshal(obj)\n\t\t\treturn string(res), err\n\t\t},\n\t\t\"toPrettyJson\": func(obj any) (string, error) {\n\t\t\tres, err := json.MarshalIndent(obj, \"\", \" \")\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\treturn string(res), err\n\t\t},\n\t\t\"fail\": func(message string) (string, error) {\n\t\t\treturn \"\", errors.New(message)\n\t\t},\n\t\t\"wrap\": func(l int, s string) (string, error) {\n\t\t\tbuf := bytes.NewBuffer(nil)\n\t\t\twriter := term.NewWordWrapWriter(buf, uint(l))\n\t\t\t_, err := writer.Write([]byte(s))\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\treturn buf.String(), nil\n\t\t},\n\t\t\"split\": func(s string, sep string) []string {\n\t\t\treturn strings.Split(s, sep)\n\t\t},\n\t\t\"join\": func(sep string, strs ...string) string {\n\t\t\treturn strings.Join(strs, sep)\n\t\t},\n\t\t\"include\": func(name string, data interface{}) (string, error) {\n\t\t\tbuf := bytes.NewBuffer(nil)\n\t\t\tif err := tmpl.ExecuteTemplate(buf, name, data); err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\treturn buf.String(), nil\n\t\t},\n\t\t\"ternary\": func(a, b any, condition bool) any {\n\t\t\tif condition {\n\t\t\t\treturn a\n\t\t\t}\n\t\t\treturn b\n\t\t},\n\t\t\"first\": func(list any) (any, error) {\n\t\t\tif list == nil {\n\t\t\t\treturn nil, errors.New(\"list is empty\")\n\t\t\t}\n\n\t\t\ttp := reflect.TypeOf(list).Kind()\n\t\t\tswitch tp {\n\t\t\tcase reflect.Slice, reflect.Array:\n\t\t\t\tl2 := reflect.ValueOf(list)\n\n\t\t\t\tl := l2.Len()\n\t\t\t\tif l == 0 {\n\t\t\t\t\treturn nil, errors.New(\"list is empty\")\n\t\t\t\t}\n\n\t\t\t\treturn l2.Index(0).Interface(), nil\n\t\t\tdefault:\n\t\t\t\treturn nil, fmt.Errorf(\"first cannot be used on type: %T\", list)\n\t\t\t}\n\t\t},\n\t\t\"last\": func(list any) (any, error) {\n\t\t\tif list == nil {\n\t\t\t\treturn nil, errors.New(\"list is empty\")\n\t\t\t}\n\n\t\t\ttp := reflect.TypeOf(list).Kind()\n\t\t\tswitch tp {\n\t\t\tcase reflect.Slice, reflect.Array:\n\t\t\t\tl2 := reflect.ValueOf(list)\n\n\t\t\t\tl := l2.Len()\n\t\t\t\tif l == 0 {\n\t\t\t\t\treturn nil, errors.New(\"list is empty\")\n\t\t\t\t}\n\n\t\t\t\treturn l2.Index(l - 1).Interface(), nil\n\t\t\tdefault:\n\t\t\t\treturn nil, fmt.Errorf(\"last cannot be used on type: %T\", list)\n\t\t\t}\n\t\t},\n\t\t\"indent\": func(amount int, str string) string {\n\t\t\tpad := strings.Repeat(\" \", amount)\n\t\t\treturn pad + strings.Replace(str, \"\\n\", \"\\n\"+pad, -1)\n\t\t},\n\t\t\"dict\": func(keysAndValues ...any) (map[string]any, error) {\n\t\t\tif len(keysAndValues)%2 != 0 {\n\t\t\t\treturn nil, errors.New(\"expected even # of arguments\")\n\t\t\t}\n\n\t\t\tres := map[string]any{}\n\t\t\tfor i := 0; i+1 \u003c len(keysAndValues); i = i + 2 {\n\t\t\t\tif key, ok := keysAndValues[i].(string); ok {\n\t\t\t\t\tres[key] = keysAndValues[i+1]\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, fmt.Errorf(\"key of type %T is not a string as expected\", key)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn res, nil\n\t\t},\n\t\t\"contains\": func(list any, value any) bool {\n\t\t\tif list == nil {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tval := reflect.ValueOf(list)\n\t\t\tswitch val.Kind() {\n\t\t\tcase reflect.Array:\n\t\t\tcase reflect.Slice:\n\t\t\t\tfor i := 0; i \u003c val.Len(); i++ {\n\t\t\t\t\tcur := val.Index(i)\n\t\t\t\t\tif cur.CanInterface() \u0026\u0026 reflect.DeepEqual(cur.Interface(), value) {\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\tdefault:\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn false\n\t\t},\n\t\t\"set\": func(dict map[string]any, keysAndValues ...any) (any, error) {\n\t\t\tif len(keysAndValues)%2 != 0 {\n\t\t\t\treturn nil, errors.New(\"expected even number of arguments\")\n\t\t\t}\n\n\t\t\tcopyDict := make(map[string]any, len(dict))\n\t\t\tfor k, v := range dict {\n\t\t\t\tcopyDict[k] = v\n\t\t\t}\n\n\t\t\tfor i := 0; i \u003c len(keysAndValues); i += 2 {\n\t\t\t\tkey, ok := keysAndValues[i].(string)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, errors.New(\"keys must be strings\")\n\t\t\t\t}\n\n\t\t\t\tcopyDict[key] = keysAndValues[i+1]\n\t\t\t}\n\n\t\t\treturn copyDict, nil\n\t\t},\n\t\t\"list\": func(values ...any) ([]any, error) {\n\t\t\treturn values, nil\n\t\t},\n\t\t\"add\": func(value, operand int) int {\n\t\t\treturn value + operand\n\t\t},\n\t\t\"sub\": func(value, operand int) int {\n\t\t\treturn value - operand\n\t\t},\n\t\t\"mul\": func(value, operand int) int {\n\t\t\treturn value * operand\n\t\t},\n\t\t\"resolveRef\": func(refAny any, document map[string]any) map[string]any {\n\t\t\trefString, ok := refAny.(string)\n\t\t\tif !ok {\n\t\t\t\t// if passed nil, or wrong type just treat the same\n\t\t\t\t// way as unresolved reference (makes for easier templates)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\t// Resolve field path encoded by the ref\n\t\t\tref, err := jsonreference.New(refString)\n\t\t\tif err != nil {\n\t\t\t\t// Unrecognized ref format.\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif !ref.HasFragmentOnly {\n\t\t\t\t// Downloading is not supported. Treat as not found\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tfragment := ref.GetURL().Fragment\n\t\t\tcomponents := strings.Split(fragment, \"/\")\n\t\t\tcur := document\n\n\t\t\tfor _, k := range components {\n\t\t\t\tif len(k) == 0 {\n\t\t\t\t\t// first component is usually empty (#/components/) , etc\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tnext, ok := cur[k].(map[string]any)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\tcur = next\n\t\t\t}\n\t\t\treturn cur\n\t\t},\n\t})\n}","line":{"from":38,"to":240}} {"id":100032666,"name":"NewGenerator","signature":"func NewGenerator() Generator","file":"staging/src/k8s.io/kubectl/pkg/explain/v2/generator.go","code":"func NewGenerator() Generator {\n\treturn \u0026generator{\n\t\ttemplates: make(map[string]*template.Template),\n\t}\n}","line":{"from":58,"to":62}} {"id":100032667,"name":"AddTemplate","signature":"func (g *generator) AddTemplate(name string, contents string) error","file":"staging/src/k8s.io/kubectl/pkg/explain/v2/generator.go","code":"func (g *generator) AddTemplate(name string, contents string) error {\n\tcompiled, err := WithBuiltinTemplateFuncs(template.New(name)).Parse(contents)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tg.templates[name] = compiled\n\treturn nil\n}","line":{"from":64,"to":73}} {"id":100032668,"name":"Render","signature":"func (g *generator) Render(","file":"staging/src/k8s.io/kubectl/pkg/explain/v2/generator.go","code":"func (g *generator) Render(\n\t// Template to use for rendering\n\ttemplateName string,\n\t// Self-Contained OpenAPI Document Containing all schemas used by $ref\n\t// Only OpenAPI V3 documents are supported\n\tdocument map[string]interface{},\n\t// Resource within OpenAPI document for which to render explain schema\n\tgvr schema.GroupVersionResource,\n\t// Field path of child of resource to focus output onto\n\tfieldSelector []string,\n\t// Boolean indicating whether the fields should be rendered recursively/deeply\n\trecursive bool,\n\t// Output writer\n\twriter io.Writer,\n) error {\n\tcompiledTemplate, ok := g.templates[templateName]\n\tif !ok {\n\t\treturn fmt.Errorf(\"unrecognized format: %s\", templateName)\n\t}\n\n\terr := compiledTemplate.Execute(writer, TemplateContext{\n\t\tDocument: document,\n\t\tRecursive: recursive,\n\t\tFieldPath: fieldSelector,\n\t\tGVR: gvr,\n\t})\n\treturn err\n}","line":{"from":75,"to":102}} {"id":100032669,"name":"registerBuiltinTemplates","signature":"func registerBuiltinTemplates(gen Generator) error","file":"staging/src/k8s.io/kubectl/pkg/explain/v2/template.go","code":"func registerBuiltinTemplates(gen Generator) error {\n\tfiles, err := rawBuiltinTemplates.ReadDir(\"templates\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, entry := range files {\n\t\tcontents, err := rawBuiltinTemplates.ReadFile(\"templates/\" + entry.Name())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = gen.AddTemplate(\n\t\t\tstrings.TrimSuffix(entry.Name(), filepath.Ext(entry.Name())),\n\t\t\tstring(contents))\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":28,"to":50}} {"id":100032670,"name":"IsZero","signature":"func IsZero(i interface{}) bool","file":"staging/src/k8s.io/kubectl/pkg/generate/generate.go","code":"func IsZero(i interface{}) bool {\n\tif i == nil {\n\t\treturn true\n\t}\n\treturn reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface())\n}","line":{"from":58,"to":63}} {"id":100032671,"name":"ValidateParams","signature":"func ValidateParams(paramSpec []GeneratorParam, params map[string]interface{}) error","file":"staging/src/k8s.io/kubectl/pkg/generate/generate.go","code":"// ValidateParams ensures that all required params are present in the params map\nfunc ValidateParams(paramSpec []GeneratorParam, params map[string]interface{}) error {\n\tallErrs := []error{}\n\tfor ix := range paramSpec {\n\t\tif paramSpec[ix].Required {\n\t\t\tvalue, found := params[paramSpec[ix].Name]\n\t\t\tif !found || IsZero(value) {\n\t\t\t\tallErrs = append(allErrs, fmt.Errorf(\"Parameter: %s is required\", paramSpec[ix].Name))\n\t\t\t}\n\t\t}\n\t}\n\treturn utilerrors.NewAggregate(allErrs)\n}","line":{"from":65,"to":77}} {"id":100032672,"name":"AnnotateFlags","signature":"func AnnotateFlags(cmd *cobra.Command, generators map[string]Generator)","file":"staging/src/k8s.io/kubectl/pkg/generate/generate.go","code":"// AnnotateFlags annotates all flags that are used by generators.\nfunc AnnotateFlags(cmd *cobra.Command, generators map[string]Generator) {\n\t// Iterate over all generators and mark any flags used by them.\n\tfor name, generator := range generators {\n\t\tgeneratorParams := map[string]struct{}{}\n\t\tfor _, param := range generator.ParamNames() {\n\t\t\tgeneratorParams[param.Name] = struct{}{}\n\t\t}\n\n\t\tcmd.Flags().VisitAll(func(flag *pflag.Flag) {\n\t\t\tif _, found := generatorParams[flag.Name]; !found {\n\t\t\t\t// This flag is not used by the current generator\n\t\t\t\t// so skip it.\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif flag.Annotations == nil {\n\t\t\t\tflag.Annotations = map[string][]string{}\n\t\t\t}\n\t\t\tif annotations := flag.Annotations[\"generator\"]; annotations == nil {\n\t\t\t\tflag.Annotations[\"generator\"] = []string{}\n\t\t\t}\n\t\t\tflag.Annotations[\"generator\"] = append(flag.Annotations[\"generator\"], name)\n\t\t})\n\t}\n}","line":{"from":79,"to":103}} {"id":100032673,"name":"EnsureFlagsValid","signature":"func EnsureFlagsValid(cmd *cobra.Command, generators map[string]Generator, generatorInUse string) error","file":"staging/src/k8s.io/kubectl/pkg/generate/generate.go","code":"// EnsureFlagsValid ensures that no invalid flags are being used against a\nfunc EnsureFlagsValid(cmd *cobra.Command, generators map[string]Generator, generatorInUse string) error {\n\tAnnotateFlags(cmd, generators)\n\n\tallErrs := []error{}\n\tcmd.Flags().VisitAll(func(flag *pflag.Flag) {\n\t\t// If the flag hasn't changed, don't validate it.\n\t\tif !flag.Changed {\n\t\t\treturn\n\t\t}\n\t\t// Look into the flag annotations for the generators that can use it.\n\t\tif annotations := flag.Annotations[\"generator\"]; len(annotations) \u003e 0 {\n\t\t\tannotationMap := map[string]struct{}{}\n\t\t\tfor _, ann := range annotations {\n\t\t\t\tannotationMap[ann] = struct{}{}\n\t\t\t}\n\t\t\t// If the current generator is not annotated, then this flag shouldn't\n\t\t\t// be used with it.\n\t\t\tif _, found := annotationMap[generatorInUse]; !found {\n\t\t\t\tallErrs = append(allErrs, fmt.Errorf(\"cannot use --%s with --generator=%s\", flag.Name, generatorInUse))\n\t\t\t}\n\t\t}\n\t})\n\treturn utilerrors.NewAggregate(allErrs)\n}","line":{"from":105,"to":129}} {"id":100032674,"name":"MakeParams","signature":"func MakeParams(cmd *cobra.Command, params []GeneratorParam) map[string]interface{}","file":"staging/src/k8s.io/kubectl/pkg/generate/generate.go","code":"// MakeParams is a utility that creates generator parameters from a command line\nfunc MakeParams(cmd *cobra.Command, params []GeneratorParam) map[string]interface{} {\n\tresult := map[string]interface{}{}\n\tfor ix := range params {\n\t\tf := cmd.Flags().Lookup(params[ix].Name)\n\t\tif f != nil {\n\t\t\tresult[params[ix].Name] = f.Value.String()\n\t\t}\n\t}\n\treturn result\n}","line":{"from":131,"to":141}} {"id":100032675,"name":"MakeProtocols","signature":"func MakeProtocols(protocols map[string]string) string","file":"staging/src/k8s.io/kubectl/pkg/generate/generate.go","code":"func MakeProtocols(protocols map[string]string) string {\n\tout := []string{}\n\tfor key, value := range protocols {\n\t\tout = append(out, fmt.Sprintf(\"%s/%s\", key, value))\n\t}\n\treturn strings.Join(out, \",\")\n}","line":{"from":143,"to":149}} {"id":100032676,"name":"ParseProtocols","signature":"func ParseProtocols(protocols interface{}) (map[string]string, error)","file":"staging/src/k8s.io/kubectl/pkg/generate/generate.go","code":"func ParseProtocols(protocols interface{}) (map[string]string, error) {\n\tprotocolsString, isString := protocols.(string)\n\tif !isString {\n\t\treturn nil, fmt.Errorf(\"expected string, found %v\", protocols)\n\t}\n\tif len(protocolsString) == 0 {\n\t\treturn nil, fmt.Errorf(\"no protocols passed\")\n\t}\n\tportProtocolMap := map[string]string{}\n\tprotocolsSlice := strings.Split(protocolsString, \",\")\n\tfor ix := range protocolsSlice {\n\t\tportProtocol := strings.Split(protocolsSlice[ix], \"/\")\n\t\tif len(portProtocol) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"unexpected port protocol mapping: %s\", protocolsSlice[ix])\n\t\t}\n\t\tif len(portProtocol[0]) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"unexpected empty port\")\n\t\t}\n\t\tif len(portProtocol[1]) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"unexpected empty protocol\")\n\t\t}\n\t\tportProtocolMap[portProtocol[0]] = portProtocol[1]\n\t}\n\treturn portProtocolMap, nil\n}","line":{"from":151,"to":175}} {"id":100032677,"name":"ParseLabels","signature":"func ParseLabels(labelSpec interface{}) (map[string]string, error)","file":"staging/src/k8s.io/kubectl/pkg/generate/generate.go","code":"// ParseLabels turns a string representation of a label set into a map[string]string\nfunc ParseLabels(labelSpec interface{}) (map[string]string, error) {\n\tlabelString, isString := labelSpec.(string)\n\tif !isString {\n\t\treturn nil, fmt.Errorf(\"expected string, found %v\", labelSpec)\n\t}\n\tif len(labelString) == 0 {\n\t\treturn nil, fmt.Errorf(\"no label spec passed\")\n\t}\n\tlabels := map[string]string{}\n\tlabelSpecs := strings.Split(labelString, \",\")\n\tfor ix := range labelSpecs {\n\t\tlabelSpec := strings.Split(labelSpecs[ix], \"=\")\n\t\tif len(labelSpec) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"unexpected label spec: %s\", labelSpecs[ix])\n\t\t}\n\t\tif len(labelSpec[0]) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"unexpected empty label key\")\n\t\t}\n\t\tlabels[labelSpec[0]] = labelSpec[1]\n\t}\n\treturn labels, nil\n}","line":{"from":177,"to":199}} {"id":100032678,"name":"GetBool","signature":"func GetBool(params map[string]string, key string, defValue bool) (bool, error)","file":"staging/src/k8s.io/kubectl/pkg/generate/generate.go","code":"func GetBool(params map[string]string, key string, defValue bool) (bool, error) {\n\tif val, found := params[key]; !found {\n\t\treturn defValue, nil\n\t} else {\n\t\treturn strconv.ParseBool(val)\n\t}\n}","line":{"from":201,"to":207}} {"id":100032679,"name":"DefaultGenerators","signature":"func DefaultGenerators(cmdName string) map[string]generate.Generator","file":"staging/src/k8s.io/kubectl/pkg/generate/versioned/generator.go","code":"// DefaultGenerators returns the set of default generators for use in Factory instances\nfunc DefaultGenerators(cmdName string) map[string]generate.Generator {\n\tvar generator map[string]generate.Generator\n\tswitch cmdName {\n\tcase \"expose\":\n\t\tgenerator = map[string]generate.Generator{\n\t\t\tServiceV2GeneratorName: ServiceGeneratorV2{},\n\t\t}\n\tcase \"run\":\n\t\tgenerator = map[string]generate.Generator{\n\t\t\tRunPodV1GeneratorName: BasicPod{},\n\t\t}\n\t}\n\n\treturn generator\n}","line":{"from":34,"to":49}} {"id":100032680,"name":"getLabels","signature":"func getLabels(params map[string]string, name string) (map[string]string, error)","file":"staging/src/k8s.io/kubectl/pkg/generate/versioned/run.go","code":"// getLabels returns map of labels.\nfunc getLabels(params map[string]string, name string) (map[string]string, error) {\n\tlabelString, found := params[\"labels\"]\n\tvar labels map[string]string\n\tvar err error\n\tif found \u0026\u0026 len(labelString) \u003e 0 {\n\t\tlabels, err = generate.ParseLabels(labelString)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tlabels = map[string]string{\n\t\t\t\"run\": name,\n\t\t}\n\t}\n\treturn labels, nil\n}","line":{"from":33,"to":49}} {"id":100032681,"name":"getName","signature":"func getName(params map[string]string) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/generate/versioned/run.go","code":"// getName returns the name of newly created resource.\nfunc getName(params map[string]string) (string, error) {\n\tname, found := params[\"name\"]\n\tif !found || len(name) == 0 {\n\t\tname, found = params[\"default-name\"]\n\t\tif !found || len(name) == 0 {\n\t\t\treturn \"\", fmt.Errorf(\"'name' is a required parameter\")\n\t\t}\n\t}\n\treturn name, nil\n}","line":{"from":51,"to":61}} {"id":100032682,"name":"getParams","signature":"func getParams(genericParams map[string]interface{}) (map[string]string, error)","file":"staging/src/k8s.io/kubectl/pkg/generate/versioned/run.go","code":"// getParams returns map of generic parameters.\nfunc getParams(genericParams map[string]interface{}) (map[string]string, error) {\n\tparams := map[string]string{}\n\tfor key, value := range genericParams {\n\t\tstrVal, isString := value.(string)\n\t\tif !isString {\n\t\t\treturn nil, fmt.Errorf(\"expected string, saw %v for '%s'\", value, key)\n\t\t}\n\t\tparams[key] = strVal\n\t}\n\treturn params, nil\n}","line":{"from":63,"to":74}} {"id":100032683,"name":"getArgs","signature":"func getArgs(genericParams map[string]interface{}) ([]string, error)","file":"staging/src/k8s.io/kubectl/pkg/generate/versioned/run.go","code":"// getArgs returns arguments for the container command.\nfunc getArgs(genericParams map[string]interface{}) ([]string, error) {\n\targs := []string{}\n\tval, found := genericParams[\"args\"]\n\tif found {\n\t\tvar isArray bool\n\t\targs, isArray = val.([]string)\n\t\tif !isArray {\n\t\t\treturn nil, fmt.Errorf(\"expected []string, found: %v\", val)\n\t\t}\n\t\tdelete(genericParams, \"args\")\n\t}\n\treturn args, nil\n}","line":{"from":76,"to":89}} {"id":100032684,"name":"getAnnotations","signature":"func getAnnotations(genericParams map[string]interface{}) (map[string]string, error)","file":"staging/src/k8s.io/kubectl/pkg/generate/versioned/run.go","code":"// getAnnotations returns map of annotations.\nfunc getAnnotations(genericParams map[string]interface{}) (map[string]string, error) {\n\tannotationStrings, ok := genericParams[\"annotations\"]\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\n\tannotationStringArray, ok := annotationStrings.([]string)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"expected []string, found: %v\", annotationStrings)\n\t}\n\n\tannotations, _, err := cmdutil.ParsePairs(annotationStringArray, \"annotations\", false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelete(genericParams, \"annotations\")\n\treturn annotations, nil\n}","line":{"from":91,"to":110}} {"id":100032685,"name":"getEnvs","signature":"func getEnvs(genericParams map[string]interface{}) ([]v1.EnvVar, error)","file":"staging/src/k8s.io/kubectl/pkg/generate/versioned/run.go","code":"// getEnvs returns environment variables.\nfunc getEnvs(genericParams map[string]interface{}) ([]v1.EnvVar, error) {\n\tvar envs []v1.EnvVar\n\tenvStrings, found := genericParams[\"env\"]\n\tif found {\n\t\tif envStringArray, isArray := envStrings.([]string); isArray {\n\t\t\tvar err error\n\t\t\tenvs, err = parseEnvs(envStringArray)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelete(genericParams, \"env\")\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"expected []string, found: %v\", envStrings)\n\t\t}\n\t}\n\treturn envs, nil\n}","line":{"from":112,"to":129}} {"id":100032686,"name":"populateResourceListV1","signature":"func populateResourceListV1(spec string) (v1.ResourceList, error)","file":"staging/src/k8s.io/kubectl/pkg/generate/versioned/run.go","code":"// populateResourceListV1 takes strings of form \u003cresourceName1\u003e=\u003cvalue1\u003e,\u003cresourceName1\u003e=\u003cvalue2\u003e\n// and returns ResourceList.\nfunc populateResourceListV1(spec string) (v1.ResourceList, error) {\n\t// empty input gets a nil response to preserve generator test expected behaviors\n\tif spec == \"\" {\n\t\treturn nil, nil\n\t}\n\n\tresult := v1.ResourceList{}\n\tresourceStatements := strings.Split(spec, \",\")\n\tfor _, resourceStatement := range resourceStatements {\n\t\tparts := strings.Split(resourceStatement, \"=\")\n\t\tif len(parts) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"Invalid argument syntax %v, expected \u003cresource\u003e=\u003cvalue\u003e\", resourceStatement)\n\t\t}\n\t\tresourceName := v1.ResourceName(parts[0])\n\t\tresourceQuantity, err := resource.ParseQuantity(parts[1])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult[resourceName] = resourceQuantity\n\t}\n\treturn result, nil\n}","line":{"from":131,"to":154}} {"id":100032687,"name":"HandleResourceRequirementsV1","signature":"func HandleResourceRequirementsV1(params map[string]string) (v1.ResourceRequirements, error)","file":"staging/src/k8s.io/kubectl/pkg/generate/versioned/run.go","code":"// HandleResourceRequirementsV1 parses the limits and requests parameters if specified\n// and returns ResourceRequirements.\nfunc HandleResourceRequirementsV1(params map[string]string) (v1.ResourceRequirements, error) {\n\tresult := v1.ResourceRequirements{}\n\tlimits, err := populateResourceListV1(params[\"limits\"])\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tresult.Limits = limits\n\trequests, err := populateResourceListV1(params[\"requests\"])\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tresult.Requests = requests\n\treturn result, nil\n}","line":{"from":156,"to":171}} {"id":100032688,"name":"updatePodContainers","signature":"func updatePodContainers(params map[string]string, args []string, envs []v1.EnvVar, imagePullPolicy v1.PullPolicy, podSpec *v1.PodSpec) error","file":"staging/src/k8s.io/kubectl/pkg/generate/versioned/run.go","code":"// updatePodContainers updates PodSpec.Containers with passed parameters.\nfunc updatePodContainers(params map[string]string, args []string, envs []v1.EnvVar, imagePullPolicy v1.PullPolicy, podSpec *v1.PodSpec) error {\n\tif len(args) \u003e 0 {\n\t\tcommand, err := generate.GetBool(params, \"command\", false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif command {\n\t\t\tpodSpec.Containers[0].Command = args\n\t\t} else {\n\t\t\tpodSpec.Containers[0].Args = args\n\t\t}\n\t}\n\n\tif len(envs) \u003e 0 {\n\t\tpodSpec.Containers[0].Env = envs\n\t}\n\n\tif len(imagePullPolicy) \u003e 0 {\n\t\t// imagePullPolicy should be valid here since we have verified it before.\n\t\tpodSpec.Containers[0].ImagePullPolicy = imagePullPolicy\n\t}\n\treturn nil\n}","line":{"from":173,"to":196}} {"id":100032689,"name":"updatePodPorts","signature":"func updatePodPorts(params map[string]string, podSpec *v1.PodSpec) (err error)","file":"staging/src/k8s.io/kubectl/pkg/generate/versioned/run.go","code":"// updatePodContainers updates PodSpec.Containers.Ports with passed parameters.\nfunc updatePodPorts(params map[string]string, podSpec *v1.PodSpec) (err error) {\n\tport := -1\n\thostPort := -1\n\tif len(params[\"port\"]) \u003e 0 {\n\t\tport, err = strconv.Atoi(params[\"port\"])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif len(params[\"hostport\"]) \u003e 0 {\n\t\thostPort, err = strconv.Atoi(params[\"hostport\"])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif hostPort \u003e 0 \u0026\u0026 port \u003c 0 {\n\t\t\treturn fmt.Errorf(\"--hostport requires --port to be specified\")\n\t\t}\n\t}\n\n\t// Don't include the port if it was not specified.\n\tif len(params[\"port\"]) \u003e 0 {\n\t\tpodSpec.Containers[0].Ports = []v1.ContainerPort{\n\t\t\t{\n\t\t\t\tContainerPort: int32(port),\n\t\t\t},\n\t\t}\n\t\tif hostPort \u003e 0 {\n\t\t\tpodSpec.Containers[0].Ports[0].HostPort = int32(hostPort)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":198,"to":231}} {"id":100032690,"name":"ParamNames","signature":"func (BasicPod) ParamNames() []generate.GeneratorParam","file":"staging/src/k8s.io/kubectl/pkg/generate/versioned/run.go","code":"func (BasicPod) ParamNames() []generate.GeneratorParam {\n\treturn []generate.GeneratorParam{\n\t\t{Name: \"labels\", Required: false},\n\t\t{Name: \"annotations\", Required: false},\n\t\t{Name: \"default-name\", Required: false},\n\t\t{Name: \"name\", Required: true},\n\t\t{Name: \"image\", Required: true},\n\t\t{Name: \"image-pull-policy\", Required: false},\n\t\t{Name: \"port\", Required: false},\n\t\t{Name: \"hostport\", Required: false},\n\t\t{Name: \"stdin\", Required: false},\n\t\t{Name: \"leave-stdin-open\", Required: false},\n\t\t{Name: \"tty\", Required: false},\n\t\t{Name: \"restart\", Required: false},\n\t\t{Name: \"command\", Required: false},\n\t\t{Name: \"args\", Required: false},\n\t\t{Name: \"env\", Required: false},\n\t\t{Name: \"requests\", Required: false},\n\t\t{Name: \"limits\", Required: false},\n\t\t{Name: \"serviceaccount\", Required: false},\n\t\t{Name: \"privileged\", Required: false},\n\t}\n}","line":{"from":235,"to":257}} {"id":100032691,"name":"Generate","signature":"func (BasicPod) Generate(genericParams map[string]interface{}) (runtime.Object, error)","file":"staging/src/k8s.io/kubectl/pkg/generate/versioned/run.go","code":"func (BasicPod) Generate(genericParams map[string]interface{}) (runtime.Object, error) {\n\targs, err := getArgs(genericParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tenvs, err := getEnvs(genericParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tannotations, err := getAnnotations(genericParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparams, err := getParams(genericParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tname, err := getName(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlabels, err := getLabels(params, name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstdin, err := generate.GetBool(params, \"stdin\", false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tleaveStdinOpen, err := generate.GetBool(params, \"leave-stdin-open\", false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttty, err := generate.GetBool(params, \"tty\", false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresourceRequirements, err := HandleResourceRequirementsV1(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trestartPolicy := v1.RestartPolicy(params[\"restart\"])\n\tif len(restartPolicy) == 0 {\n\t\trestartPolicy = v1.RestartPolicyAlways\n\t}\n\n\tprivileged, err := generate.GetBool(params, \"privileged\", false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar securityContext *v1.SecurityContext\n\tif privileged {\n\t\tsecurityContext = \u0026v1.SecurityContext{\n\t\t\tPrivileged: \u0026privileged,\n\t\t}\n\t}\n\n\tpod := v1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tLabels: labels,\n\t\t\tAnnotations: annotations,\n\t\t},\n\t\tSpec: v1.PodSpec{\n\t\t\tServiceAccountName: params[\"serviceaccount\"],\n\t\t\tContainers: []v1.Container{\n\t\t\t\t{\n\t\t\t\t\tName: name,\n\t\t\t\t\tImage: params[\"image\"],\n\t\t\t\t\tStdin: stdin,\n\t\t\t\t\tStdinOnce: !leaveStdinOpen \u0026\u0026 stdin,\n\t\t\t\t\tTTY: tty,\n\t\t\t\t\tResources: resourceRequirements,\n\t\t\t\t\tSecurityContext: securityContext,\n\t\t\t\t},\n\t\t\t},\n\t\t\tDNSPolicy: v1.DNSClusterFirst,\n\t\t\tRestartPolicy: restartPolicy,\n\t\t},\n\t}\n\timagePullPolicy := v1.PullPolicy(params[\"image-pull-policy\"])\n\tif err = updatePodContainers(params, args, envs, imagePullPolicy, \u0026pod.Spec); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := updatePodPorts(params, \u0026pod.Spec); err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026pod, nil\n}","line":{"from":259,"to":357}} {"id":100032692,"name":"parseEnvs","signature":"func parseEnvs(envArray []string) ([]v1.EnvVar, error)","file":"staging/src/k8s.io/kubectl/pkg/generate/versioned/run.go","code":"// parseEnvs converts string into EnvVar objects.\nfunc parseEnvs(envArray []string) ([]v1.EnvVar, error) {\n\tenvs := make([]v1.EnvVar, 0, len(envArray))\n\tfor _, env := range envArray {\n\t\tpos := strings.Index(env, \"=\")\n\t\tif pos == -1 {\n\t\t\treturn nil, fmt.Errorf(\"invalid env: %v\", env)\n\t\t}\n\t\tname := env[:pos]\n\t\tvalue := env[pos+1:]\n\t\tif len(name) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"invalid env: %v\", env)\n\t\t}\n\t\tif len(validation.IsEnvVarName(name)) != 0 {\n\t\t\treturn nil, fmt.Errorf(\"invalid env: %v\", env)\n\t\t}\n\t\tenvVar := v1.EnvVar{Name: name, Value: value}\n\t\tenvs = append(envs, envVar)\n\t}\n\treturn envs, nil\n}","line":{"from":359,"to":379}} {"id":100032693,"name":"ParamNames","signature":"func (ServiceGeneratorV1) ParamNames() []generate.GeneratorParam","file":"staging/src/k8s.io/kubectl/pkg/generate/versioned/service.go","code":"func (ServiceGeneratorV1) ParamNames() []generate.GeneratorParam {\n\treturn paramNames()\n}","line":{"from":34,"to":36}} {"id":100032694,"name":"Generate","signature":"func (ServiceGeneratorV1) Generate(params map[string]interface{}) (runtime.Object, error)","file":"staging/src/k8s.io/kubectl/pkg/generate/versioned/service.go","code":"func (ServiceGeneratorV1) Generate(params map[string]interface{}) (runtime.Object, error) {\n\tparams[\"port-name\"] = \"default\"\n\treturn generateService(params)\n}","line":{"from":38,"to":41}} {"id":100032695,"name":"ParamNames","signature":"func (ServiceGeneratorV2) ParamNames() []generate.GeneratorParam","file":"staging/src/k8s.io/kubectl/pkg/generate/versioned/service.go","code":"func (ServiceGeneratorV2) ParamNames() []generate.GeneratorParam {\n\treturn paramNames()\n}","line":{"from":45,"to":47}} {"id":100032696,"name":"Generate","signature":"func (ServiceGeneratorV2) Generate(params map[string]interface{}) (runtime.Object, error)","file":"staging/src/k8s.io/kubectl/pkg/generate/versioned/service.go","code":"func (ServiceGeneratorV2) Generate(params map[string]interface{}) (runtime.Object, error) {\n\treturn generateService(params)\n}","line":{"from":49,"to":51}} {"id":100032697,"name":"paramNames","signature":"func paramNames() []generate.GeneratorParam","file":"staging/src/k8s.io/kubectl/pkg/generate/versioned/service.go","code":"func paramNames() []generate.GeneratorParam {\n\treturn []generate.GeneratorParam{\n\t\t{Name: \"default-name\", Required: true},\n\t\t{Name: \"name\", Required: false},\n\t\t{Name: \"selector\", Required: true},\n\t\t// port will be used if a user specifies --port OR the exposed object\n\t\t// has one port\n\t\t{Name: \"port\", Required: false},\n\t\t// ports will be used iff a user doesn't specify --port AND the\n\t\t// exposed object has multiple ports\n\t\t{Name: \"ports\", Required: false},\n\t\t{Name: \"labels\", Required: false},\n\t\t{Name: \"external-ip\", Required: false},\n\t\t{Name: \"load-balancer-ip\", Required: false},\n\t\t{Name: \"type\", Required: false},\n\t\t{Name: \"protocol\", Required: false},\n\t\t// protocols will be used to keep port-protocol mapping derived from\n\t\t// exposed object\n\t\t{Name: \"protocols\", Required: false},\n\t\t{Name: \"container-port\", Required: false}, // alias of target-port\n\t\t{Name: \"target-port\", Required: false},\n\t\t{Name: \"port-name\", Required: false},\n\t\t{Name: \"session-affinity\", Required: false},\n\t\t{Name: \"cluster-ip\", Required: false},\n\t}\n}","line":{"from":53,"to":78}} {"id":100032698,"name":"generateService","signature":"func generateService(genericParams map[string]interface{}) (runtime.Object, error)","file":"staging/src/k8s.io/kubectl/pkg/generate/versioned/service.go","code":"func generateService(genericParams map[string]interface{}) (runtime.Object, error) {\n\tparams := map[string]string{}\n\tfor key, value := range genericParams {\n\t\tstrVal, isString := value.(string)\n\t\tif !isString {\n\t\t\treturn nil, fmt.Errorf(\"expected string, saw %v for '%s'\", value, key)\n\t\t}\n\t\tparams[key] = strVal\n\t}\n\tselectorString, found := params[\"selector\"]\n\tif !found || len(selectorString) == 0 {\n\t\treturn nil, fmt.Errorf(\"'selector' is a required parameter\")\n\t}\n\tselector, err := generate.ParseLabels(selectorString)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlabelsString, found := params[\"labels\"]\n\tvar labels map[string]string\n\tif found \u0026\u0026 len(labelsString) \u003e 0 {\n\t\tlabels, err = generate.ParseLabels(labelsString)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tname, found := params[\"name\"]\n\tif !found || len(name) == 0 {\n\t\tname, found = params[\"default-name\"]\n\t\tif !found || len(name) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"'name' is a required parameter\")\n\t\t}\n\t}\n\n\tisHeadlessService := params[\"cluster-ip\"] == \"None\"\n\n\tports := []v1.ServicePort{}\n\tservicePortName, found := params[\"port-name\"]\n\tif !found {\n\t\t// Leave the port unnamed.\n\t\tservicePortName = \"\"\n\t}\n\n\tprotocolsString, found := params[\"protocols\"]\n\tvar portProtocolMap map[string]string\n\tif found \u0026\u0026 len(protocolsString) \u003e 0 {\n\t\tportProtocolMap, err = generate.ParseProtocols(protocolsString)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\t// ports takes precedence over port since it will be\n\t// specified only when the user hasn't specified a port\n\t// via --port and the exposed object has multiple ports.\n\tvar portString string\n\tif portString, found = params[\"ports\"]; !found {\n\t\tportString, found = params[\"port\"]\n\t\tif !found \u0026\u0026 !isHeadlessService {\n\t\t\treturn nil, fmt.Errorf(\"'ports' or 'port' is a required parameter\")\n\t\t}\n\t}\n\n\tif portString != \"\" {\n\t\tportStringSlice := strings.Split(portString, \",\")\n\t\tfor i, stillPortString := range portStringSlice {\n\t\t\tport, err := strconv.Atoi(stillPortString)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tname := servicePortName\n\t\t\t// If we are going to assign multiple ports to a service, we need to\n\t\t\t// generate a different name for each one.\n\t\t\tif len(portStringSlice) \u003e 1 {\n\t\t\t\tname = fmt.Sprintf(\"port-%d\", i+1)\n\t\t\t}\n\t\t\tprotocol := params[\"protocol\"]\n\n\t\t\tswitch {\n\t\t\tcase len(protocol) == 0 \u0026\u0026 len(portProtocolMap) == 0:\n\t\t\t\t// Default to TCP, what the flag was doing previously.\n\t\t\t\tprotocol = \"TCP\"\n\t\t\tcase len(protocol) \u003e 0 \u0026\u0026 len(portProtocolMap) \u003e 0:\n\t\t\t\t// User has specified the --protocol while exposing a multiprotocol resource\n\t\t\t\t// We should stomp multiple protocols with the one specified ie. do nothing\n\t\t\tcase len(protocol) == 0 \u0026\u0026 len(portProtocolMap) \u003e 0:\n\t\t\t\t// no --protocol and we expose a multiprotocol resource\n\t\t\t\tprotocol = \"TCP\" // have the default so we can stay sane\n\t\t\t\tif exposeProtocol, found := portProtocolMap[stillPortString]; found {\n\t\t\t\t\tprotocol = exposeProtocol\n\t\t\t\t}\n\t\t\t}\n\t\t\tports = append(ports, v1.ServicePort{\n\t\t\t\tName: name,\n\t\t\t\tPort: int32(port),\n\t\t\t\tProtocol: v1.Protocol(protocol),\n\t\t\t})\n\t\t}\n\t}\n\n\tservice := v1.Service{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tLabels: labels,\n\t\t},\n\t\tSpec: v1.ServiceSpec{\n\t\t\tSelector: selector,\n\t\t\tPorts: ports,\n\t\t},\n\t}\n\ttargetPortString := params[\"target-port\"]\n\tif len(targetPortString) == 0 {\n\t\ttargetPortString = params[\"container-port\"]\n\t}\n\tif len(targetPortString) \u003e 0 {\n\t\tvar targetPort intstr.IntOrString\n\t\tif portNum, err := strconv.Atoi(targetPortString); err != nil {\n\t\t\ttargetPort = intstr.FromString(targetPortString)\n\t\t} else {\n\t\t\ttargetPort = intstr.FromInt(portNum)\n\t\t}\n\t\t// Use the same target-port for every port\n\t\tfor i := range service.Spec.Ports {\n\t\t\tservice.Spec.Ports[i].TargetPort = targetPort\n\t\t}\n\t} else {\n\t\t// If --target-port or --container-port haven't been specified, this\n\t\t// should be the same as Port\n\t\tfor i := range service.Spec.Ports {\n\t\t\tport := service.Spec.Ports[i].Port\n\t\t\tservice.Spec.Ports[i].TargetPort = intstr.FromInt(int(port))\n\t\t}\n\t}\n\tif len(params[\"external-ip\"]) \u003e 0 {\n\t\tservice.Spec.ExternalIPs = []string{params[\"external-ip\"]}\n\t}\n\tif len(params[\"type\"]) != 0 {\n\t\tservice.Spec.Type = v1.ServiceType(params[\"type\"])\n\t}\n\tif service.Spec.Type == v1.ServiceTypeLoadBalancer {\n\t\tservice.Spec.LoadBalancerIP = params[\"load-balancer-ip\"]\n\t}\n\tif len(params[\"session-affinity\"]) != 0 {\n\t\tswitch v1.ServiceAffinity(params[\"session-affinity\"]) {\n\t\tcase v1.ServiceAffinityNone:\n\t\t\tservice.Spec.SessionAffinity = v1.ServiceAffinityNone\n\t\tcase v1.ServiceAffinityClientIP:\n\t\t\tservice.Spec.SessionAffinity = v1.ServiceAffinityClientIP\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown session affinity: %s\", params[\"session-affinity\"])\n\t\t}\n\t}\n\tif len(params[\"cluster-ip\"]) != 0 {\n\t\tif params[\"cluster-ip\"] == \"None\" {\n\t\t\tservice.Spec.ClusterIP = v1.ClusterIPNone\n\t\t} else {\n\t\t\tservice.Spec.ClusterIP = params[\"cluster-ip\"]\n\t\t}\n\t}\n\treturn \u0026service, nil\n}","line":{"from":80,"to":240}} {"id":100032699,"name":"NewTopCmdPrinter","signature":"func NewTopCmdPrinter(out io.Writer) *TopCmdPrinter","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_printer.go","code":"func NewTopCmdPrinter(out io.Writer) *TopCmdPrinter {\n\treturn \u0026TopCmdPrinter{out: out}\n}","line":{"from":51,"to":53}} {"id":100032700,"name":"PrintNodeMetrics","signature":"func (printer *TopCmdPrinter) PrintNodeMetrics(metrics []metricsapi.NodeMetrics, availableResources map[string]v1.ResourceList, noHeaders bool, sortBy string) error","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_printer.go","code":"func (printer *TopCmdPrinter) PrintNodeMetrics(metrics []metricsapi.NodeMetrics, availableResources map[string]v1.ResourceList, noHeaders bool, sortBy string) error {\n\tif len(metrics) == 0 {\n\t\treturn nil\n\t}\n\tw := printers.GetNewTabWriter(printer.out)\n\tdefer w.Flush()\n\n\tsort.Sort(NewNodeMetricsSorter(metrics, sortBy))\n\n\tif !noHeaders {\n\t\tprintColumnNames(w, NodeColumns)\n\t}\n\tvar usage v1.ResourceList\n\tfor _, m := range metrics {\n\t\tm.Usage.DeepCopyInto(\u0026usage)\n\t\tprintMetricsLine(w, \u0026ResourceMetricsInfo{\n\t\t\tName: m.Name,\n\t\t\tMetrics: usage,\n\t\t\tAvailable: availableResources[m.Name],\n\t\t})\n\t\tdelete(availableResources, m.Name)\n\t}\n\n\t// print lines for nodes of which the metrics is unreachable.\n\tfor nodeName := range availableResources {\n\t\tprintMissingMetricsNodeLine(w, nodeName)\n\t}\n\treturn nil\n}","line":{"from":55,"to":83}} {"id":100032701,"name":"PrintPodMetrics","signature":"func (printer *TopCmdPrinter) PrintPodMetrics(metrics []metricsapi.PodMetrics, printContainers bool, withNamespace bool, noHeaders bool, sortBy string, sum bool) error","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_printer.go","code":"func (printer *TopCmdPrinter) PrintPodMetrics(metrics []metricsapi.PodMetrics, printContainers bool, withNamespace bool, noHeaders bool, sortBy string, sum bool) error {\n\tif len(metrics) == 0 {\n\t\treturn nil\n\t}\n\tw := printers.GetNewTabWriter(printer.out)\n\tdefer w.Flush()\n\n\tcolumnWidth := len(PodColumns)\n\tif !noHeaders {\n\t\tif withNamespace {\n\t\t\tprintValue(w, NamespaceColumn)\n\t\t\tcolumnWidth++\n\t\t}\n\t\tif printContainers {\n\t\t\tprintValue(w, PodColumn)\n\t\t\tcolumnWidth++\n\t\t}\n\t\tprintColumnNames(w, PodColumns)\n\t}\n\n\tsort.Sort(NewPodMetricsSorter(metrics, withNamespace, sortBy))\n\n\tfor _, m := range metrics {\n\t\tif printContainers {\n\t\t\tsort.Sort(NewContainerMetricsSorter(m.Containers, sortBy))\n\t\t\tprintSinglePodContainerMetrics(w, \u0026m, withNamespace)\n\t\t} else {\n\t\t\tprintSinglePodMetrics(w, \u0026m, withNamespace)\n\t\t}\n\n\t}\n\n\tif sum {\n\t\tadder := NewResourceAdder(MeasuredResources)\n\t\tfor _, m := range metrics {\n\t\t\tadder.AddPodMetrics(\u0026m)\n\t\t}\n\t\tprintPodResourcesSum(w, adder.total, columnWidth)\n\t}\n\n\treturn nil\n}","line":{"from":85,"to":126}} {"id":100032702,"name":"printColumnNames","signature":"func printColumnNames(out io.Writer, names []string)","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_printer.go","code":"func printColumnNames(out io.Writer, names []string) {\n\tfor _, name := range names {\n\t\tprintValue(out, name)\n\t}\n\tfmt.Fprint(out, \"\\n\")\n}","line":{"from":128,"to":133}} {"id":100032703,"name":"printSinglePodMetrics","signature":"func printSinglePodMetrics(out io.Writer, m *metricsapi.PodMetrics, withNamespace bool)","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_printer.go","code":"func printSinglePodMetrics(out io.Writer, m *metricsapi.PodMetrics, withNamespace bool) {\n\tpodMetrics := getPodMetrics(m)\n\tif withNamespace {\n\t\tprintValue(out, m.Namespace)\n\t}\n\tprintMetricsLine(out, \u0026ResourceMetricsInfo{\n\t\tName: m.Name,\n\t\tMetrics: podMetrics,\n\t\tAvailable: v1.ResourceList{},\n\t})\n}","line":{"from":135,"to":145}} {"id":100032704,"name":"printSinglePodContainerMetrics","signature":"func printSinglePodContainerMetrics(out io.Writer, m *metricsapi.PodMetrics, withNamespace bool)","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_printer.go","code":"func printSinglePodContainerMetrics(out io.Writer, m *metricsapi.PodMetrics, withNamespace bool) {\n\tfor _, c := range m.Containers {\n\t\tif withNamespace {\n\t\t\tprintValue(out, m.Namespace)\n\t\t}\n\t\tprintValue(out, m.Name)\n\t\tprintMetricsLine(out, \u0026ResourceMetricsInfo{\n\t\t\tName: c.Name,\n\t\t\tMetrics: c.Usage,\n\t\t\tAvailable: v1.ResourceList{},\n\t\t})\n\t}\n}","line":{"from":147,"to":159}} {"id":100032705,"name":"getPodMetrics","signature":"func getPodMetrics(m *metricsapi.PodMetrics) v1.ResourceList","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_printer.go","code":"func getPodMetrics(m *metricsapi.PodMetrics) v1.ResourceList {\n\tpodMetrics := make(v1.ResourceList)\n\tfor _, res := range MeasuredResources {\n\t\tpodMetrics[res], _ = resource.ParseQuantity(\"0\")\n\t}\n\n\tfor _, c := range m.Containers {\n\t\tfor _, res := range MeasuredResources {\n\t\t\tquantity := podMetrics[res]\n\t\t\tquantity.Add(c.Usage[res])\n\t\t\tpodMetrics[res] = quantity\n\t\t}\n\t}\n\treturn podMetrics\n}","line":{"from":161,"to":175}} {"id":100032706,"name":"printMetricsLine","signature":"func printMetricsLine(out io.Writer, metrics *ResourceMetricsInfo)","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_printer.go","code":"func printMetricsLine(out io.Writer, metrics *ResourceMetricsInfo) {\n\tprintValue(out, metrics.Name)\n\tprintAllResourceUsages(out, metrics)\n\tfmt.Fprint(out, \"\\n\")\n}","line":{"from":177,"to":181}} {"id":100032707,"name":"printMissingMetricsNodeLine","signature":"func printMissingMetricsNodeLine(out io.Writer, nodeName string)","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_printer.go","code":"func printMissingMetricsNodeLine(out io.Writer, nodeName string) {\n\tprintValue(out, nodeName)\n\tunknownMetricsStatus := \"\u003cunknown\u003e\"\n\tfor i := 0; i \u003c len(MeasuredResources); i++ {\n\t\tprintValue(out, unknownMetricsStatus)\n\t\tprintValue(out, unknownMetricsStatus)\n\t}\n\tfmt.Fprint(out, \"\\n\")\n}","line":{"from":183,"to":191}} {"id":100032708,"name":"printValue","signature":"func printValue(out io.Writer, value interface{})","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_printer.go","code":"func printValue(out io.Writer, value interface{}) {\n\tfmt.Fprintf(out, \"%v\\t\", value)\n}","line":{"from":193,"to":195}} {"id":100032709,"name":"printAllResourceUsages","signature":"func printAllResourceUsages(out io.Writer, metrics *ResourceMetricsInfo)","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_printer.go","code":"func printAllResourceUsages(out io.Writer, metrics *ResourceMetricsInfo) {\n\tfor _, res := range MeasuredResources {\n\t\tquantity := metrics.Metrics[res]\n\t\tprintSingleResourceUsage(out, res, quantity)\n\t\tfmt.Fprint(out, \"\\t\")\n\t\tif available, found := metrics.Available[res]; found {\n\t\t\tfraction := float64(quantity.MilliValue()) / float64(available.MilliValue()) * 100\n\t\t\tfmt.Fprintf(out, \"%d%%\\t\", int64(fraction))\n\t\t}\n\t}\n}","line":{"from":197,"to":207}} {"id":100032710,"name":"printSingleResourceUsage","signature":"func printSingleResourceUsage(out io.Writer, resourceType v1.ResourceName, quantity resource.Quantity)","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_printer.go","code":"func printSingleResourceUsage(out io.Writer, resourceType v1.ResourceName, quantity resource.Quantity) {\n\tswitch resourceType {\n\tcase v1.ResourceCPU:\n\t\tfmt.Fprintf(out, \"%vm\", quantity.MilliValue())\n\tcase v1.ResourceMemory:\n\t\tfmt.Fprintf(out, \"%vMi\", quantity.Value()/(1024*1024))\n\tdefault:\n\t\tfmt.Fprintf(out, \"%v\", quantity.Value())\n\t}\n}","line":{"from":209,"to":218}} {"id":100032711,"name":"printPodResourcesSum","signature":"func printPodResourcesSum(out io.Writer, total v1.ResourceList, columnWidth int)","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_printer.go","code":"func printPodResourcesSum(out io.Writer, total v1.ResourceList, columnWidth int) {\n\tfor i := 0; i \u003c columnWidth-2; i++ {\n\t\tprintValue(out, \"\")\n\t}\n\tprintValue(out, \"________\")\n\tprintValue(out, \"________\")\n\tfmt.Fprintf(out, \"\\n\")\n\tfor i := 0; i \u003c columnWidth-3; i++ {\n\t\tprintValue(out, \"\")\n\t}\n\tprintMetricsLine(out, \u0026ResourceMetricsInfo{\n\t\tName: \"\",\n\t\tMetrics: total,\n\t\tAvailable: v1.ResourceList{},\n\t})\n\n}","line":{"from":220,"to":236}} {"id":100032712,"name":"NewResourceAdder","signature":"func NewResourceAdder(resources []corev1.ResourceName) *ResourceAdder","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_resource_adder.go","code":"func NewResourceAdder(resources []corev1.ResourceName) *ResourceAdder {\n\treturn \u0026ResourceAdder{\n\t\tresources: resources,\n\t\ttotal: make(corev1.ResourceList),\n\t}\n}","line":{"from":29,"to":34}} {"id":100032713,"name":"AddPodMetrics","signature":"func (adder *ResourceAdder) AddPodMetrics(m *metricsapi.PodMetrics)","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_resource_adder.go","code":"// AddPodMetrics adds each pod metric to the total\nfunc (adder *ResourceAdder) AddPodMetrics(m *metricsapi.PodMetrics) {\n\tfor _, c := range m.Containers {\n\t\tfor _, res := range adder.resources {\n\t\t\ttotal := adder.total[res]\n\t\t\ttotal.Add(c.Usage[res])\n\t\t\tadder.total[res] = total\n\t\t}\n\t}\n}","line":{"from":36,"to":45}} {"id":100032714,"name":"Len","signature":"func (n *NodeMetricsSorter) Len() int","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_sorter.go","code":"func (n *NodeMetricsSorter) Len() int {\n\treturn len(n.metrics)\n}","line":{"from":29,"to":31}} {"id":100032715,"name":"Swap","signature":"func (n *NodeMetricsSorter) Swap(i, j int)","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_sorter.go","code":"func (n *NodeMetricsSorter) Swap(i, j int) {\n\tn.metrics[i], n.metrics[j] = n.metrics[j], n.metrics[i]\n}","line":{"from":33,"to":35}} {"id":100032716,"name":"Less","signature":"func (n *NodeMetricsSorter) Less(i, j int) bool","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_sorter.go","code":"func (n *NodeMetricsSorter) Less(i, j int) bool {\n\tswitch n.sortBy {\n\tcase \"cpu\":\n\t\treturn n.metrics[i].Usage.Cpu().MilliValue() \u003e n.metrics[j].Usage.Cpu().MilliValue()\n\tcase \"memory\":\n\t\treturn n.metrics[i].Usage.Memory().Value() \u003e n.metrics[j].Usage.Memory().Value()\n\tdefault:\n\t\treturn n.metrics[i].Name \u003c n.metrics[j].Name\n\t}\n}","line":{"from":37,"to":46}} {"id":100032717,"name":"NewNodeMetricsSorter","signature":"func NewNodeMetricsSorter(metrics []metricsapi.NodeMetrics, sortBy string) *NodeMetricsSorter","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_sorter.go","code":"func NewNodeMetricsSorter(metrics []metricsapi.NodeMetrics, sortBy string) *NodeMetricsSorter {\n\treturn \u0026NodeMetricsSorter{\n\t\tmetrics: metrics,\n\t\tsortBy: sortBy,\n\t}\n}","line":{"from":48,"to":53}} {"id":100032718,"name":"Len","signature":"func (p *PodMetricsSorter) Len() int","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_sorter.go","code":"func (p *PodMetricsSorter) Len() int {\n\treturn len(p.metrics)\n}","line":{"from":62,"to":64}} {"id":100032719,"name":"Swap","signature":"func (p *PodMetricsSorter) Swap(i, j int)","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_sorter.go","code":"func (p *PodMetricsSorter) Swap(i, j int) {\n\tp.metrics[i], p.metrics[j] = p.metrics[j], p.metrics[i]\n\tp.podMetrics[i], p.podMetrics[j] = p.podMetrics[j], p.podMetrics[i]\n}","line":{"from":66,"to":69}} {"id":100032720,"name":"Less","signature":"func (p *PodMetricsSorter) Less(i, j int) bool","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_sorter.go","code":"func (p *PodMetricsSorter) Less(i, j int) bool {\n\tswitch p.sortBy {\n\tcase \"cpu\":\n\t\treturn p.podMetrics[i].Cpu().MilliValue() \u003e p.podMetrics[j].Cpu().MilliValue()\n\tcase \"memory\":\n\t\treturn p.podMetrics[i].Memory().Value() \u003e p.podMetrics[j].Memory().Value()\n\tdefault:\n\t\tif p.withNamespace \u0026\u0026 p.metrics[i].Namespace != p.metrics[j].Namespace {\n\t\t\treturn p.metrics[i].Namespace \u003c p.metrics[j].Namespace\n\t\t}\n\t\treturn p.metrics[i].Name \u003c p.metrics[j].Name\n\t}\n}","line":{"from":71,"to":83}} {"id":100032721,"name":"NewPodMetricsSorter","signature":"func NewPodMetricsSorter(metrics []metricsapi.PodMetrics, withNamespace bool, sortBy string) *PodMetricsSorter","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_sorter.go","code":"func NewPodMetricsSorter(metrics []metricsapi.PodMetrics, withNamespace bool, sortBy string) *PodMetricsSorter {\n\tvar podMetrics = make([]v1.ResourceList, len(metrics))\n\tif len(sortBy) \u003e 0 {\n\t\tfor i, v := range metrics {\n\t\t\tpodMetrics[i] = getPodMetrics(\u0026v)\n\t\t}\n\t}\n\n\treturn \u0026PodMetricsSorter{\n\t\tmetrics: metrics,\n\t\tsortBy: sortBy,\n\t\twithNamespace: withNamespace,\n\t\tpodMetrics: podMetrics,\n\t}\n}","line":{"from":85,"to":99}} {"id":100032722,"name":"Len","signature":"func (s *ContainerMetricsSorter) Len() int","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_sorter.go","code":"func (s *ContainerMetricsSorter) Len() int {\n\treturn len(s.metrics)\n}","line":{"from":106,"to":108}} {"id":100032723,"name":"Swap","signature":"func (s *ContainerMetricsSorter) Swap(i, j int)","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_sorter.go","code":"func (s *ContainerMetricsSorter) Swap(i, j int) {\n\ts.metrics[i], s.metrics[j] = s.metrics[j], s.metrics[i]\n}","line":{"from":110,"to":112}} {"id":100032724,"name":"Less","signature":"func (s *ContainerMetricsSorter) Less(i, j int) bool","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_sorter.go","code":"func (s *ContainerMetricsSorter) Less(i, j int) bool {\n\tswitch s.sortBy {\n\tcase \"cpu\":\n\t\treturn s.metrics[i].Usage.Cpu().MilliValue() \u003e s.metrics[j].Usage.Cpu().MilliValue()\n\tcase \"memory\":\n\t\treturn s.metrics[i].Usage.Memory().Value() \u003e s.metrics[j].Usage.Memory().Value()\n\tdefault:\n\t\treturn s.metrics[i].Name \u003c s.metrics[j].Name\n\t}\n}","line":{"from":114,"to":123}} {"id":100032725,"name":"NewContainerMetricsSorter","signature":"func NewContainerMetricsSorter(metrics []metricsapi.ContainerMetrics, sortBy string) *ContainerMetricsSorter","file":"staging/src/k8s.io/kubectl/pkg/metricsutil/metrics_sorter.go","code":"func NewContainerMetricsSorter(metrics []metricsapi.ContainerMetrics, sortBy string) *ContainerMetricsSorter {\n\treturn \u0026ContainerMetricsSorter{\n\t\tmetrics: metrics,\n\t\tsortBy: sortBy,\n\t}\n}","line":{"from":125,"to":130}} {"id":100032726,"name":"attachablePodForObject","signature":"func attachablePodForObject(restClientGetter genericclioptions.RESTClientGetter, object runtime.Object, timeout time.Duration) (*corev1.Pod, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/attachablepodforobject.go","code":"// attachablePodForObject returns the pod to which to attach given an object.\nfunc attachablePodForObject(restClientGetter genericclioptions.RESTClientGetter, object runtime.Object, timeout time.Duration) (*corev1.Pod, error) {\n\tswitch t := object.(type) {\n\tcase *corev1.Pod:\n\t\treturn t, nil\n\t}\n\n\tclientConfig, err := restClientGetter.ToRESTConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclientset, err := corev1client.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnamespace, selector, err := SelectorsForObject(object)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot attach to %T: %v\", object, err)\n\t}\n\tsortBy := func(pods []*corev1.Pod) sort.Interface { return sort.Reverse(podutils.ActivePods(pods)) }\n\tpod, _, err := GetFirstPod(clientset, namespace, selector.String(), timeout, sortBy)\n\treturn pod, err\n}","line":{"from":31,"to":54}} {"id":100032727,"name":"canBeExposed","signature":"func canBeExposed(kind schema.GroupKind) error","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/canbeexposed.go","code":"// Check whether the kind of resources could be exposed\nfunc canBeExposed(kind schema.GroupKind) error {\n\tswitch kind {\n\tcase\n\t\tcorev1.SchemeGroupVersion.WithKind(\"ReplicationController\").GroupKind(),\n\t\tcorev1.SchemeGroupVersion.WithKind(\"Service\").GroupKind(),\n\t\tcorev1.SchemeGroupVersion.WithKind(\"Pod\").GroupKind(),\n\t\tappsv1.SchemeGroupVersion.WithKind(\"Deployment\").GroupKind(),\n\t\tappsv1.SchemeGroupVersion.WithKind(\"ReplicaSet\").GroupKind(),\n\t\textensionsv1beta1.SchemeGroupVersion.WithKind(\"Deployment\").GroupKind(),\n\t\textensionsv1beta1.SchemeGroupVersion.WithKind(\"ReplicaSet\").GroupKind():\n\t\t// nothing to do here\n\tdefault:\n\t\treturn fmt.Errorf(\"cannot expose a %s\", kind)\n\t}\n\treturn nil\n}","line":{"from":28,"to":44}} {"id":100032728,"name":"GetFirstPod","signature":"func GetFirstPod(client coreclient.PodsGetter, namespace string, selector string, timeout time.Duration, sortBy func([]*corev1.Pod) sort.Interface) (*corev1.Pod, int, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/helpers.go","code":"// GetFirstPod returns a pod matching the namespace and label selector\n// and the number of all pods that match the label selector.\nfunc GetFirstPod(client coreclient.PodsGetter, namespace string, selector string, timeout time.Duration, sortBy func([]*corev1.Pod) sort.Interface) (*corev1.Pod, int, error) {\n\toptions := metav1.ListOptions{LabelSelector: selector}\n\n\tpodList, err := client.Pods(namespace).List(context.TODO(), options)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tpods := []*corev1.Pod{}\n\tfor i := range podList.Items {\n\t\tpod := podList.Items[i]\n\t\tpods = append(pods, \u0026pod)\n\t}\n\tif len(pods) \u003e 0 {\n\t\tsort.Sort(sortBy(pods))\n\t\treturn pods[0], len(podList.Items), nil\n\t}\n\n\t// Watch until we observe a pod\n\toptions.ResourceVersion = podList.ResourceVersion\n\tw, err := client.Pods(namespace).Watch(context.TODO(), options)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tdefer w.Stop()\n\n\tcondition := func(event watch.Event) (bool, error) {\n\t\treturn event.Type == watch.Added || event.Type == watch.Modified, nil\n\t}\n\n\tctx, cancel := watchtools.ContextWithOptionalTimeout(context.Background(), timeout)\n\tdefer cancel()\n\tevent, err := watchtools.UntilWithoutRetry(ctx, w, condition)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tpod, ok := event.Object.(*corev1.Pod)\n\tif !ok {\n\t\treturn nil, 0, fmt.Errorf(\"%#v is not a pod event\", event)\n\t}\n\treturn pod, 1, nil\n}","line":{"from":39,"to":81}} {"id":100032729,"name":"SelectorsForObject","signature":"func SelectorsForObject(object runtime.Object) (namespace string, selector labels.Selector, err error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/helpers.go","code":"// SelectorsForObject returns the pod label selector for a given object\nfunc SelectorsForObject(object runtime.Object) (namespace string, selector labels.Selector, err error) {\n\tswitch t := object.(type) {\n\tcase *extensionsv1beta1.ReplicaSet:\n\t\tnamespace = t.Namespace\n\t\tselector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)\n\t\tif err != nil {\n\t\t\treturn \"\", nil, fmt.Errorf(\"invalid label selector: %v\", err)\n\t\t}\n\tcase *appsv1.ReplicaSet:\n\t\tnamespace = t.Namespace\n\t\tselector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)\n\t\tif err != nil {\n\t\t\treturn \"\", nil, fmt.Errorf(\"invalid label selector: %v\", err)\n\t\t}\n\tcase *appsv1beta2.ReplicaSet:\n\t\tnamespace = t.Namespace\n\t\tselector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)\n\t\tif err != nil {\n\t\t\treturn \"\", nil, fmt.Errorf(\"invalid label selector: %v\", err)\n\t\t}\n\n\tcase *corev1.ReplicationController:\n\t\tnamespace = t.Namespace\n\t\tselector = labels.SelectorFromSet(t.Spec.Selector)\n\n\tcase *appsv1.StatefulSet:\n\t\tnamespace = t.Namespace\n\t\tselector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)\n\t\tif err != nil {\n\t\t\treturn \"\", nil, fmt.Errorf(\"invalid label selector: %v\", err)\n\t\t}\n\tcase *appsv1beta1.StatefulSet:\n\t\tnamespace = t.Namespace\n\t\tselector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)\n\t\tif err != nil {\n\t\t\treturn \"\", nil, fmt.Errorf(\"invalid label selector: %v\", err)\n\t\t}\n\tcase *appsv1beta2.StatefulSet:\n\t\tnamespace = t.Namespace\n\t\tselector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)\n\t\tif err != nil {\n\t\t\treturn \"\", nil, fmt.Errorf(\"invalid label selector: %v\", err)\n\t\t}\n\n\tcase *extensionsv1beta1.DaemonSet:\n\t\tnamespace = t.Namespace\n\t\tselector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)\n\t\tif err != nil {\n\t\t\treturn \"\", nil, fmt.Errorf(\"invalid label selector: %v\", err)\n\t\t}\n\tcase *appsv1.DaemonSet:\n\t\tnamespace = t.Namespace\n\t\tselector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)\n\t\tif err != nil {\n\t\t\treturn \"\", nil, fmt.Errorf(\"invalid label selector: %v\", err)\n\t\t}\n\tcase *appsv1beta2.DaemonSet:\n\t\tnamespace = t.Namespace\n\t\tselector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)\n\t\tif err != nil {\n\t\t\treturn \"\", nil, fmt.Errorf(\"invalid label selector: %v\", err)\n\t\t}\n\n\tcase *extensionsv1beta1.Deployment:\n\t\tnamespace = t.Namespace\n\t\tselector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)\n\t\tif err != nil {\n\t\t\treturn \"\", nil, fmt.Errorf(\"invalid label selector: %v\", err)\n\t\t}\n\tcase *appsv1.Deployment:\n\t\tnamespace = t.Namespace\n\t\tselector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)\n\t\tif err != nil {\n\t\t\treturn \"\", nil, fmt.Errorf(\"invalid label selector: %v\", err)\n\t\t}\n\tcase *appsv1beta1.Deployment:\n\t\tnamespace = t.Namespace\n\t\tselector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)\n\t\tif err != nil {\n\t\t\treturn \"\", nil, fmt.Errorf(\"invalid label selector: %v\", err)\n\t\t}\n\tcase *appsv1beta2.Deployment:\n\t\tnamespace = t.Namespace\n\t\tselector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)\n\t\tif err != nil {\n\t\t\treturn \"\", nil, fmt.Errorf(\"invalid label selector: %v\", err)\n\t\t}\n\n\tcase *batchv1.Job:\n\t\tnamespace = t.Namespace\n\t\tselector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)\n\t\tif err != nil {\n\t\t\treturn \"\", nil, fmt.Errorf(\"invalid label selector: %v\", err)\n\t\t}\n\n\tcase *corev1.Service:\n\t\tnamespace = t.Namespace\n\t\tif t.Spec.Selector == nil || len(t.Spec.Selector) == 0 {\n\t\t\treturn \"\", nil, fmt.Errorf(\"invalid service '%s': Service is defined without a selector\", t.Name)\n\t\t}\n\t\tselector = labels.SelectorFromSet(t.Spec.Selector)\n\n\tdefault:\n\t\treturn \"\", nil, fmt.Errorf(\"selector for %T not implemented\", object)\n\t}\n\n\treturn namespace, selector, nil\n}","line":{"from":83,"to":191}} {"id":100032730,"name":"VisitDeployment","signature":"func (v *HistoryVisitor) VisitDeployment(elem apps.GroupKindElement)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history.go","code":"func (v *HistoryVisitor) VisitDeployment(elem apps.GroupKindElement) {\n\tv.result = \u0026DeploymentHistoryViewer{v.clientset}\n}","line":{"from":59,"to":61}} {"id":100032731,"name":"VisitStatefulSet","signature":"func (v *HistoryVisitor) VisitStatefulSet(kind apps.GroupKindElement)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history.go","code":"func (v *HistoryVisitor) VisitStatefulSet(kind apps.GroupKindElement) {\n\tv.result = \u0026StatefulSetHistoryViewer{v.clientset}\n}","line":{"from":63,"to":65}} {"id":100032732,"name":"VisitDaemonSet","signature":"func (v *HistoryVisitor) VisitDaemonSet(kind apps.GroupKindElement)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history.go","code":"func (v *HistoryVisitor) VisitDaemonSet(kind apps.GroupKindElement) {\n\tv.result = \u0026DaemonSetHistoryViewer{v.clientset}\n}","line":{"from":67,"to":69}} {"id":100032733,"name":"VisitJob","signature":"func (v *HistoryVisitor) VisitJob(kind apps.GroupKindElement) {}","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history.go","code":"func (v *HistoryVisitor) VisitJob(kind apps.GroupKindElement) {}","line":{"from":71,"to":71}} {"id":100032734,"name":"VisitPod","signature":"func (v *HistoryVisitor) VisitPod(kind apps.GroupKindElement) {}","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history.go","code":"func (v *HistoryVisitor) VisitPod(kind apps.GroupKindElement) {}","line":{"from":72,"to":72}} {"id":100032735,"name":"VisitReplicaSet","signature":"func (v *HistoryVisitor) VisitReplicaSet(kind apps.GroupKindElement) {}","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history.go","code":"func (v *HistoryVisitor) VisitReplicaSet(kind apps.GroupKindElement) {}","line":{"from":73,"to":73}} {"id":100032736,"name":"VisitReplicationController","signature":"func (v *HistoryVisitor) VisitReplicationController(kind apps.GroupKindElement) {}","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history.go","code":"func (v *HistoryVisitor) VisitReplicationController(kind apps.GroupKindElement) {}","line":{"from":74,"to":74}} {"id":100032737,"name":"VisitCronJob","signature":"func (v *HistoryVisitor) VisitCronJob(kind apps.GroupKindElement) {}","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history.go","code":"func (v *HistoryVisitor) VisitCronJob(kind apps.GroupKindElement) {}","line":{"from":75,"to":75}} {"id":100032738,"name":"HistoryViewerFor","signature":"func HistoryViewerFor(kind schema.GroupKind, c kubernetes.Interface) (HistoryViewer, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history.go","code":"// HistoryViewerFor returns an implementation of HistoryViewer interface for the given schema kind\nfunc HistoryViewerFor(kind schema.GroupKind, c kubernetes.Interface) (HistoryViewer, error) {\n\telem := apps.GroupKindElement(kind)\n\tvisitor := \u0026HistoryVisitor{\n\t\tclientset: c,\n\t}\n\n\t// Determine which HistoryViewer we need here\n\terr := elem.Accept(visitor)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error retrieving history for %q, %v\", kind.String(), err)\n\t}\n\n\tif visitor.result == nil {\n\t\treturn nil, fmt.Errorf(\"no history viewer has been implemented for %q\", kind.String())\n\t}\n\n\treturn visitor.result, nil\n}","line":{"from":77,"to":96}} {"id":100032739,"name":"ViewHistory","signature":"func (h *DeploymentHistoryViewer) ViewHistory(namespace, name string, revision int64) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history.go","code":"// ViewHistory returns a revision-to-replicaset map as the revision history of a deployment\n// TODO: this should be a describer\nfunc (h *DeploymentHistoryViewer) ViewHistory(namespace, name string, revision int64) (string, error) {\n\tallRSs, err := getDeploymentReplicaSets(h.c.AppsV1(), namespace, name)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\thistoryInfo := make(map[int64]*corev1.PodTemplateSpec)\n\tfor _, rs := range allRSs {\n\t\tv, err := deploymentutil.Revision(rs)\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"unable to get revision from replicaset %s for deployment %s in namespace %s: %v\", rs.Name, name, namespace, err)\n\t\t\tcontinue\n\t\t}\n\t\thistoryInfo[v] = \u0026rs.Spec.Template\n\t\tchangeCause := getChangeCause(rs)\n\t\tif historyInfo[v].Annotations == nil {\n\t\t\thistoryInfo[v].Annotations = make(map[string]string)\n\t\t}\n\t\tif len(changeCause) \u003e 0 {\n\t\t\thistoryInfo[v].Annotations[ChangeCauseAnnotation] = changeCause\n\t\t}\n\t}\n\n\tif len(historyInfo) == 0 {\n\t\treturn \"No rollout history found.\", nil\n\t}\n\n\tif revision \u003e 0 {\n\t\t// Print details of a specific revision\n\t\ttemplate, ok := historyInfo[revision]\n\t\tif !ok {\n\t\t\treturn \"\", fmt.Errorf(\"unable to find the specified revision\")\n\t\t}\n\t\treturn printTemplate(template)\n\t}\n\n\t// Sort the revisionToChangeCause map by revision\n\trevisions := make([]int64, 0, len(historyInfo))\n\tfor r := range historyInfo {\n\t\trevisions = append(revisions, r)\n\t}\n\tsliceutil.SortInts64(revisions)\n\n\treturn tabbedString(func(out io.Writer) error {\n\t\tfmt.Fprintf(out, \"REVISION\\tCHANGE-CAUSE\\n\")\n\t\tfor _, r := range revisions {\n\t\t\t// Find the change-cause of revision r\n\t\t\tchangeCause := historyInfo[r].Annotations[ChangeCauseAnnotation]\n\t\t\tif len(changeCause) == 0 {\n\t\t\t\tchangeCause = \"\u003cnone\u003e\"\n\t\t\t}\n\t\t\tfmt.Fprintf(out, \"%d\\t%s\\n\", r, changeCause)\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":102,"to":159}} {"id":100032740,"name":"GetHistory","signature":"func (h *DeploymentHistoryViewer) GetHistory(namespace, name string) (map[int64]runtime.Object, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history.go","code":"// GetHistory returns the ReplicaSet revisions associated with a Deployment\nfunc (h *DeploymentHistoryViewer) GetHistory(namespace, name string) (map[int64]runtime.Object, error) {\n\tallRSs, err := getDeploymentReplicaSets(h.c.AppsV1(), namespace, name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := make(map[int64]runtime.Object)\n\tfor _, rs := range allRSs {\n\t\tv, err := deploymentutil.Revision(rs)\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"unable to get revision from replicaset %s for deployment %s in namespace %s: %v\", rs.Name, name, namespace, err)\n\t\t\tcontinue\n\t\t}\n\t\tresult[v] = rs\n\t}\n\n\treturn result, nil\n}","line":{"from":161,"to":179}} {"id":100032741,"name":"printTemplate","signature":"func printTemplate(template *corev1.PodTemplateSpec) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history.go","code":"func printTemplate(template *corev1.PodTemplateSpec) (string, error) {\n\tbuf := bytes.NewBuffer([]byte{})\n\tw := describe.NewPrefixWriter(buf)\n\tdescribe.DescribePodTemplate(template, w)\n\treturn buf.String(), nil\n}","line":{"from":181,"to":186}} {"id":100032742,"name":"ViewHistory","signature":"func (h *DaemonSetHistoryViewer) ViewHistory(namespace, name string, revision int64) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history.go","code":"// ViewHistory returns a revision-to-history map as the revision history of a deployment\n// TODO: this should be a describer\nfunc (h *DaemonSetHistoryViewer) ViewHistory(namespace, name string, revision int64) (string, error) {\n\tds, history, err := daemonSetHistory(h.c.AppsV1(), namespace, name)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn printHistory(history, revision, func(history *appsv1.ControllerRevision) (*corev1.PodTemplateSpec, error) {\n\t\tdsOfHistory, err := applyDaemonSetHistory(ds, history)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn \u0026dsOfHistory.Spec.Template, err\n\t})\n}","line":{"from":192,"to":206}} {"id":100032743,"name":"GetHistory","signature":"func (h *DaemonSetHistoryViewer) GetHistory(namespace, name string) (map[int64]runtime.Object, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history.go","code":"// GetHistory returns the revisions associated with a DaemonSet\nfunc (h *DaemonSetHistoryViewer) GetHistory(namespace, name string) (map[int64]runtime.Object, error) {\n\tds, history, err := daemonSetHistory(h.c.AppsV1(), namespace, name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := make(map[int64]runtime.Object)\n\tfor _, h := range history {\n\t\tapplied, err := applyDaemonSetHistory(ds, h)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult[h.Revision] = applied\n\t}\n\n\treturn result, nil\n}","line":{"from":208,"to":225}} {"id":100032744,"name":"printHistory","signature":"func printHistory(history []*appsv1.ControllerRevision, revision int64, getPodTemplate func(history *appsv1.ControllerRevision) (*corev1.PodTemplateSpec, error)) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history.go","code":"// printHistory returns the podTemplate of the given revision if it is non-zero\n// else returns the overall revisions\nfunc printHistory(history []*appsv1.ControllerRevision, revision int64, getPodTemplate func(history *appsv1.ControllerRevision) (*corev1.PodTemplateSpec, error)) (string, error) {\n\thistoryInfo := make(map[int64]*appsv1.ControllerRevision)\n\tfor _, history := range history {\n\t\t// TODO: for now we assume revisions don't overlap, we may need to handle it\n\t\thistoryInfo[history.Revision] = history\n\t}\n\tif len(historyInfo) == 0 {\n\t\treturn \"No rollout history found.\", nil\n\t}\n\n\t// Print details of a specific revision\n\tif revision \u003e 0 {\n\t\thistory, ok := historyInfo[revision]\n\t\tif !ok {\n\t\t\treturn \"\", fmt.Errorf(\"unable to find the specified revision\")\n\t\t}\n\t\tpodTemplate, err := getPodTemplate(history)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"unable to parse history %s\", history.Name)\n\t\t}\n\t\treturn printTemplate(podTemplate)\n\t}\n\n\t// Print an overview of all Revisions\n\t// Sort the revisionToChangeCause map by revision\n\trevisions := make([]int64, 0, len(historyInfo))\n\tfor r := range historyInfo {\n\t\trevisions = append(revisions, r)\n\t}\n\tsliceutil.SortInts64(revisions)\n\n\treturn tabbedString(func(out io.Writer) error {\n\t\tfmt.Fprintf(out, \"REVISION\\tCHANGE-CAUSE\\n\")\n\t\tfor _, r := range revisions {\n\t\t\t// Find the change-cause of revision r\n\t\t\tchangeCause := historyInfo[r].Annotations[ChangeCauseAnnotation]\n\t\t\tif len(changeCause) == 0 {\n\t\t\t\tchangeCause = \"\u003cnone\u003e\"\n\t\t\t}\n\t\t\tfmt.Fprintf(out, \"%d\\t%s\\n\", r, changeCause)\n\t\t}\n\t\treturn nil\n\t})\n}","line":{"from":227,"to":272}} {"id":100032745,"name":"ViewHistory","signature":"func (h *StatefulSetHistoryViewer) ViewHistory(namespace, name string, revision int64) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history.go","code":"// ViewHistory returns a list of the revision history of a statefulset\n// TODO: this should be a describer\nfunc (h *StatefulSetHistoryViewer) ViewHistory(namespace, name string, revision int64) (string, error) {\n\tsts, history, err := statefulSetHistory(h.c.AppsV1(), namespace, name)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn printHistory(history, revision, func(history *appsv1.ControllerRevision) (*corev1.PodTemplateSpec, error) {\n\t\tstsOfHistory, err := applyStatefulSetHistory(sts, history)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn \u0026stsOfHistory.Spec.Template, err\n\t})\n}","line":{"from":278,"to":292}} {"id":100032746,"name":"GetHistory","signature":"func (h *StatefulSetHistoryViewer) GetHistory(namespace, name string) (map[int64]runtime.Object, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history.go","code":"// GetHistory returns the revisions associated with a StatefulSet\nfunc (h *StatefulSetHistoryViewer) GetHistory(namespace, name string) (map[int64]runtime.Object, error) {\n\tsts, history, err := statefulSetHistory(h.c.AppsV1(), namespace, name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := make(map[int64]runtime.Object)\n\tfor _, h := range history {\n\t\tapplied, err := applyStatefulSetHistory(sts, h)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult[h.Revision] = applied\n\t}\n\n\treturn result, nil\n}","line":{"from":294,"to":311}} {"id":100032747,"name":"getDeploymentReplicaSets","signature":"func getDeploymentReplicaSets(apps clientappsv1.AppsV1Interface, namespace, name string) ([]*appsv1.ReplicaSet, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history.go","code":"func getDeploymentReplicaSets(apps clientappsv1.AppsV1Interface, namespace, name string) ([]*appsv1.ReplicaSet, error) {\n\tdeployment, err := apps.Deployments(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to retrieve deployment %s: %v\", name, err)\n\t}\n\n\t_, oldRSs, newRS, err := deploymentutil.GetAllReplicaSets(deployment, apps)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to retrieve replica sets from deployment %s: %v\", name, err)\n\t}\n\n\tif newRS == nil {\n\t\treturn oldRSs, nil\n\t}\n\treturn append(oldRSs, newRS), nil\n}","line":{"from":313,"to":328}} {"id":100032748,"name":"controlledHistoryV1","signature":"func controlledHistoryV1(","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history.go","code":"// controlledHistories returns all ControllerRevisions in namespace that selected by selector and owned by accessor\n// TODO: Rename this to controllerHistory when other controllers have been upgraded\nfunc controlledHistoryV1(\n\tapps clientappsv1.AppsV1Interface,\n\tnamespace string,\n\tselector labels.Selector,\n\taccessor metav1.Object) ([]*appsv1.ControllerRevision, error) {\n\tvar result []*appsv1.ControllerRevision\n\thistoryList, err := apps.ControllerRevisions(namespace).List(context.TODO(), metav1.ListOptions{LabelSelector: selector.String()})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor i := range historyList.Items {\n\t\thistory := historyList.Items[i]\n\t\t// Only add history that belongs to the API object\n\t\tif metav1.IsControlledBy(\u0026history, accessor) {\n\t\t\tresult = append(result, \u0026history)\n\t\t}\n\t}\n\treturn result, nil\n}","line":{"from":330,"to":350}} {"id":100032749,"name":"controlledHistory","signature":"func controlledHistory(","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history.go","code":"// controlledHistories returns all ControllerRevisions in namespace that selected by selector and owned by accessor\nfunc controlledHistory(\n\tapps clientappsv1.AppsV1Interface,\n\tnamespace string,\n\tselector labels.Selector,\n\taccessor metav1.Object) ([]*appsv1.ControllerRevision, error) {\n\tvar result []*appsv1.ControllerRevision\n\thistoryList, err := apps.ControllerRevisions(namespace).List(context.TODO(), metav1.ListOptions{LabelSelector: selector.String()})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor i := range historyList.Items {\n\t\thistory := historyList.Items[i]\n\t\t// Only add history that belongs to the API object\n\t\tif metav1.IsControlledBy(\u0026history, accessor) {\n\t\t\tresult = append(result, \u0026history)\n\t\t}\n\t}\n\treturn result, nil\n}","line":{"from":352,"to":371}} {"id":100032750,"name":"daemonSetHistory","signature":"func daemonSetHistory(","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history.go","code":"// daemonSetHistory returns the DaemonSet named name in namespace and all ControllerRevisions in its history.\nfunc daemonSetHistory(\n\tapps clientappsv1.AppsV1Interface,\n\tnamespace, name string) (*appsv1.DaemonSet, []*appsv1.ControllerRevision, error) {\n\tds, err := apps.DaemonSets(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to retrieve DaemonSet %s: %v\", name, err)\n\t}\n\tselector, err := metav1.LabelSelectorAsSelector(ds.Spec.Selector)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to create selector for DaemonSet %s: %v\", ds.Name, err)\n\t}\n\taccessor, err := meta.Accessor(ds)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to create accessor for DaemonSet %s: %v\", ds.Name, err)\n\t}\n\thistory, err := controlledHistory(apps, ds.Namespace, selector, accessor)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"unable to find history controlled by DaemonSet %s: %v\", ds.Name, err)\n\t}\n\treturn ds, history, nil\n}","line":{"from":373,"to":394}} {"id":100032751,"name":"statefulSetHistory","signature":"func statefulSetHistory(","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history.go","code":"// statefulSetHistory returns the StatefulSet named name in namespace and all ControllerRevisions in its history.\nfunc statefulSetHistory(\n\tapps clientappsv1.AppsV1Interface,\n\tnamespace, name string) (*appsv1.StatefulSet, []*appsv1.ControllerRevision, error) {\n\tsts, err := apps.StatefulSets(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to retrieve Statefulset %s: %s\", name, err.Error())\n\t}\n\tselector, err := metav1.LabelSelectorAsSelector(sts.Spec.Selector)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to create selector for StatefulSet %s: %s\", name, err.Error())\n\t}\n\taccessor, err := meta.Accessor(sts)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to obtain accessor for StatefulSet %s: %s\", name, err.Error())\n\t}\n\thistory, err := controlledHistoryV1(apps, namespace, selector, accessor)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"unable to find history controlled by StatefulSet %s: %v\", name, err)\n\t}\n\treturn sts, history, nil\n}","line":{"from":396,"to":417}} {"id":100032752,"name":"applyDaemonSetHistory","signature":"func applyDaemonSetHistory(ds *appsv1.DaemonSet, history *appsv1.ControllerRevision) (*appsv1.DaemonSet, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history.go","code":"// applyDaemonSetHistory returns a specific revision of DaemonSet by applying the given history to a copy of the given DaemonSet\nfunc applyDaemonSetHistory(ds *appsv1.DaemonSet, history *appsv1.ControllerRevision) (*appsv1.DaemonSet, error) {\n\tdsBytes, err := json.Marshal(ds)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpatched, err := strategicpatch.StrategicMergePatch(dsBytes, history.Data.Raw, ds)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := \u0026appsv1.DaemonSet{}\n\terr = json.Unmarshal(patched, result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}","line":{"from":419,"to":435}} {"id":100032753,"name":"applyStatefulSetHistory","signature":"func applyStatefulSetHistory(sts *appsv1.StatefulSet, history *appsv1.ControllerRevision) (*appsv1.StatefulSet, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history.go","code":"// applyStatefulSetHistory returns a specific revision of StatefulSet by applying the given history to a copy of the given StatefulSet\nfunc applyStatefulSetHistory(sts *appsv1.StatefulSet, history *appsv1.ControllerRevision) (*appsv1.StatefulSet, error) {\n\tstsBytes, err := json.Marshal(sts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpatched, err := strategicpatch.StrategicMergePatch(stsBytes, history.Data.Raw, sts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := \u0026appsv1.StatefulSet{}\n\terr = json.Unmarshal(patched, result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}","line":{"from":437,"to":453}} {"id":100032754,"name":"tabbedString","signature":"func tabbedString(f func(io.Writer) error) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history.go","code":"// TODO: copied here until this becomes a describer\nfunc tabbedString(f func(io.Writer) error) (string, error) {\n\tout := new(tabwriter.Writer)\n\tbuf := \u0026bytes.Buffer{}\n\tout.Init(buf, 0, 8, 2, ' ', 0)\n\n\terr := f(out)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tout.Flush()\n\tstr := string(buf.String())\n\treturn str, nil\n}","line":{"from":455,"to":469}} {"id":100032755,"name":"getChangeCause","signature":"func getChangeCause(obj runtime.Object) string","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history.go","code":"// getChangeCause returns the change-cause annotation of the input object\nfunc getChangeCause(obj runtime.Object) string {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn accessor.GetAnnotations()[ChangeCauseAnnotation]\n}","line":{"from":471,"to":478}} {"id":100032756,"name":"historyViewer","signature":"func historyViewer(restClientGetter genericclioptions.RESTClientGetter, mapping *meta.RESTMapping) (HistoryViewer, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/historyviewer.go","code":"// historyViewer Returns a HistoryViewer for viewing change history\nfunc historyViewer(restClientGetter genericclioptions.RESTClientGetter, mapping *meta.RESTMapping) (HistoryViewer, error) {\n\tclientConfig, err := restClientGetter.ToRESTConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\texternal, err := kubernetes.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn HistoryViewerFor(mapping.GroupVersionKind.GroupKind(), external)\n}","line":{"from":25,"to":37}} {"id":100032757,"name":"logsForObject","signature":"func logsForObject(restClientGetter genericclioptions.RESTClientGetter, object, options runtime.Object, timeout time.Duration, allContainers bool) (map[corev1.ObjectReference]rest.ResponseWrapper, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/logsforobject.go","code":"func logsForObject(restClientGetter genericclioptions.RESTClientGetter, object, options runtime.Object, timeout time.Duration, allContainers bool) (map[corev1.ObjectReference]rest.ResponseWrapper, error) {\n\tclientConfig, err := restClientGetter.ToRESTConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclientset, err := corev1client.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn logsForObjectWithClient(clientset, object, options, timeout, allContainers)\n}","line":{"from":37,"to":48}} {"id":100032758,"name":"logsForObjectWithClient","signature":"func logsForObjectWithClient(clientset corev1client.CoreV1Interface, object, options runtime.Object, timeout time.Duration, allContainers bool) (map[corev1.ObjectReference]rest.ResponseWrapper, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/logsforobject.go","code":"// this is split for easy test-ability\nfunc logsForObjectWithClient(clientset corev1client.CoreV1Interface, object, options runtime.Object, timeout time.Duration, allContainers bool) (map[corev1.ObjectReference]rest.ResponseWrapper, error) {\n\topts, ok := options.(*corev1.PodLogOptions)\n\tif !ok {\n\t\treturn nil, errors.New(\"provided options object is not a PodLogOptions\")\n\t}\n\n\tswitch t := object.(type) {\n\tcase *corev1.PodList:\n\t\tret := make(map[corev1.ObjectReference]rest.ResponseWrapper)\n\t\tfor i := range t.Items {\n\t\t\tcurrRet, err := logsForObjectWithClient(clientset, \u0026t.Items[i], options, timeout, allContainers)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfor k, v := range currRet {\n\t\t\t\tret[k] = v\n\t\t\t}\n\t\t}\n\t\treturn ret, nil\n\n\tcase *corev1.Pod:\n\t\t// if allContainers is true, then we're going to locate all containers and then iterate through them. At that point, \"allContainers\" is false\n\t\tif !allContainers {\n\t\t\tcurrOpts := new(corev1.PodLogOptions)\n\t\t\tif opts != nil {\n\t\t\t\topts.DeepCopyInto(currOpts)\n\t\t\t}\n\t\t\t// in case the \"kubectl.kubernetes.io/default-container\" annotation is present, we preset the opts.Containers to default to selected\n\t\t\t// container. This gives users ability to preselect the most interesting container in pod.\n\t\t\tif annotations := t.GetAnnotations(); annotations != nil \u0026\u0026 currOpts.Container == \"\" {\n\t\t\t\tvar defaultContainer string\n\t\t\t\tif len(annotations[podcmd.DefaultContainerAnnotationName]) \u003e 0 {\n\t\t\t\t\tdefaultContainer = annotations[podcmd.DefaultContainerAnnotationName]\n\t\t\t\t}\n\t\t\t\tif len(defaultContainer) \u003e 0 {\n\t\t\t\t\tif exists, _ := podcmd.FindContainerByName(t, defaultContainer); exists == nil {\n\t\t\t\t\t\tfmt.Fprintf(os.Stderr, \"Default container name %q not found in pod %s\\n\", defaultContainer, t.Name)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcurrOpts.Container = defaultContainer\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif currOpts.Container == \"\" {\n\t\t\t\t// Default to the first container name(aligning behavior with `kubectl exec').\n\t\t\t\tcurrOpts.Container = t.Spec.Containers[0].Name\n\t\t\t\tif len(t.Spec.Containers) \u003e 1 || len(t.Spec.InitContainers) \u003e 0 || len(t.Spec.EphemeralContainers) \u003e 0 {\n\t\t\t\t\tfmt.Fprintf(os.Stderr, \"Defaulted container %q out of: %s\\n\", currOpts.Container, podcmd.AllContainerNames(t))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcontainer, fieldPath := podcmd.FindContainerByName(t, currOpts.Container)\n\t\t\tif container == nil {\n\t\t\t\treturn nil, fmt.Errorf(\"container %s is not valid for pod %s\", currOpts.Container, t.Name)\n\t\t\t}\n\t\t\tref, err := reference.GetPartialReference(scheme.Scheme, t, fieldPath)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"Unable to construct reference to '%#v': %v\", t, err)\n\t\t\t}\n\n\t\t\tret := make(map[corev1.ObjectReference]rest.ResponseWrapper, 1)\n\t\t\tret[*ref] = clientset.Pods(t.Namespace).GetLogs(t.Name, currOpts)\n\t\t\treturn ret, nil\n\t\t}\n\n\t\tret := make(map[corev1.ObjectReference]rest.ResponseWrapper)\n\t\tfor _, c := range t.Spec.InitContainers {\n\t\t\tcurrOpts := opts.DeepCopy()\n\t\t\tcurrOpts.Container = c.Name\n\t\t\tcurrRet, err := logsForObjectWithClient(clientset, t, currOpts, timeout, false)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfor k, v := range currRet {\n\t\t\t\tret[k] = v\n\t\t\t}\n\t\t}\n\t\tfor _, c := range t.Spec.Containers {\n\t\t\tcurrOpts := opts.DeepCopy()\n\t\t\tcurrOpts.Container = c.Name\n\t\t\tcurrRet, err := logsForObjectWithClient(clientset, t, currOpts, timeout, false)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfor k, v := range currRet {\n\t\t\t\tret[k] = v\n\t\t\t}\n\t\t}\n\t\tfor _, c := range t.Spec.EphemeralContainers {\n\t\t\tcurrOpts := opts.DeepCopy()\n\t\t\tcurrOpts.Container = c.Name\n\t\t\tcurrRet, err := logsForObjectWithClient(clientset, t, currOpts, timeout, false)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfor k, v := range currRet {\n\t\t\t\tret[k] = v\n\t\t\t}\n\t\t}\n\n\t\treturn ret, nil\n\t}\n\n\tnamespace, selector, err := SelectorsForObject(object)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot get the logs from %T: %v\", object, err)\n\t}\n\n\tsortBy := func(pods []*corev1.Pod) sort.Interface { return podutils.ByLogging(pods) }\n\tpod, numPods, err := GetFirstPod(clientset, namespace, selector.String(), timeout, sortBy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif numPods \u003e 1 {\n\t\tfmt.Fprintf(os.Stderr, \"Found %v pods, using pod/%v\\n\", numPods, pod.Name)\n\t}\n\n\treturn logsForObjectWithClient(clientset, pod, options, timeout, allContainers)\n}","line":{"from":50,"to":169}} {"id":100032759,"name":"mapBasedSelectorForObject","signature":"func mapBasedSelectorForObject(object runtime.Object) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/mapbasedselectorforobject.go","code":"// mapBasedSelectorForObject returns the map-based selector associated with the provided object. If a\n// new set-based selector is provided, an error is returned if the selector cannot be converted to a\n// map-based selector\nfunc mapBasedSelectorForObject(object runtime.Object) (string, error) {\n\t// TODO: replace with a swagger schema based approach (identify pod selector via schema introspection)\n\tswitch t := object.(type) {\n\tcase *corev1.ReplicationController:\n\t\treturn MakeLabels(t.Spec.Selector), nil\n\n\tcase *corev1.Pod:\n\t\tif len(t.Labels) == 0 {\n\t\t\treturn \"\", fmt.Errorf(\"the pod has no labels and cannot be exposed\")\n\t\t}\n\t\treturn MakeLabels(t.Labels), nil\n\n\tcase *corev1.Service:\n\t\tif t.Spec.Selector == nil {\n\t\t\treturn \"\", fmt.Errorf(\"the service has no pod selector set\")\n\t\t}\n\t\treturn MakeLabels(t.Spec.Selector), nil\n\n\tcase *extensionsv1beta1.Deployment:\n\t\t// \"extensions\" deployments use pod template labels if selector is not set.\n\t\tvar labels map[string]string\n\t\tif t.Spec.Selector != nil {\n\t\t\t// TODO(madhusudancs): Make this smarter by admitting MatchExpressions with Equals\n\t\t\t// operator, DoubleEquals operator and In operator with only one element in the set.\n\t\t\tif len(t.Spec.Selector.MatchExpressions) \u003e 0 {\n\t\t\t\treturn \"\", fmt.Errorf(\"couldn't convert expressions - \\\"%+v\\\" to map-based selector format\", t.Spec.Selector.MatchExpressions)\n\t\t\t}\n\t\t\tlabels = t.Spec.Selector.MatchLabels\n\t\t} else {\n\t\t\tlabels = t.Spec.Template.Labels\n\t\t}\n\t\tif len(labels) == 0 {\n\t\t\treturn \"\", fmt.Errorf(\"the deployment has no labels or selectors and cannot be exposed\")\n\t\t}\n\t\treturn MakeLabels(labels), nil\n\n\tcase *appsv1.Deployment:\n\t\t// \"apps\" deployments must have the selector set.\n\t\tif t.Spec.Selector == nil || len(t.Spec.Selector.MatchLabels) == 0 {\n\t\t\treturn \"\", fmt.Errorf(\"invalid deployment: no selectors, therefore cannot be exposed\")\n\t\t}\n\t\t// TODO(madhusudancs): Make this smarter by admitting MatchExpressions with Equals\n\t\t// operator, DoubleEquals operator and In operator with only one element in the set.\n\t\tif len(t.Spec.Selector.MatchExpressions) \u003e 0 {\n\t\t\treturn \"\", fmt.Errorf(\"couldn't convert expressions - \\\"%+v\\\" to map-based selector format\", t.Spec.Selector.MatchExpressions)\n\t\t}\n\t\treturn MakeLabels(t.Spec.Selector.MatchLabels), nil\n\n\tcase *appsv1beta2.Deployment:\n\t\t// \"apps\" deployments must have the selector set.\n\t\tif t.Spec.Selector == nil || len(t.Spec.Selector.MatchLabels) == 0 {\n\t\t\treturn \"\", fmt.Errorf(\"invalid deployment: no selectors, therefore cannot be exposed\")\n\t\t}\n\t\t// TODO(madhusudancs): Make this smarter by admitting MatchExpressions with Equals\n\t\t// operator, DoubleEquals operator and In operator with only one element in the set.\n\t\tif len(t.Spec.Selector.MatchExpressions) \u003e 0 {\n\t\t\treturn \"\", fmt.Errorf(\"couldn't convert expressions - \\\"%+v\\\" to map-based selector format\", t.Spec.Selector.MatchExpressions)\n\t\t}\n\t\treturn MakeLabels(t.Spec.Selector.MatchLabels), nil\n\n\tcase *appsv1beta1.Deployment:\n\t\t// \"apps\" deployments must have the selector set.\n\t\tif t.Spec.Selector == nil || len(t.Spec.Selector.MatchLabels) == 0 {\n\t\t\treturn \"\", fmt.Errorf(\"invalid deployment: no selectors, therefore cannot be exposed\")\n\t\t}\n\t\t// TODO(madhusudancs): Make this smarter by admitting MatchExpressions with Equals\n\t\t// operator, DoubleEquals operator and In operator with only one element in the set.\n\t\tif len(t.Spec.Selector.MatchExpressions) \u003e 0 {\n\t\t\treturn \"\", fmt.Errorf(\"couldn't convert expressions - \\\"%+v\\\" to map-based selector format\", t.Spec.Selector.MatchExpressions)\n\t\t}\n\t\treturn MakeLabels(t.Spec.Selector.MatchLabels), nil\n\n\tcase *extensionsv1beta1.ReplicaSet:\n\t\t// \"extensions\" replicasets use pod template labels if selector is not set.\n\t\tvar labels map[string]string\n\t\tif t.Spec.Selector != nil {\n\t\t\t// TODO(madhusudancs): Make this smarter by admitting MatchExpressions with Equals\n\t\t\t// operator, DoubleEquals operator and In operator with only one element in the set.\n\t\t\tif len(t.Spec.Selector.MatchExpressions) \u003e 0 {\n\t\t\t\treturn \"\", fmt.Errorf(\"couldn't convert expressions - \\\"%+v\\\" to map-based selector format\", t.Spec.Selector.MatchExpressions)\n\t\t\t}\n\t\t\tlabels = t.Spec.Selector.MatchLabels\n\t\t} else {\n\t\t\tlabels = t.Spec.Template.Labels\n\t\t}\n\t\tif len(labels) == 0 {\n\t\t\treturn \"\", fmt.Errorf(\"the replica set has no labels or selectors and cannot be exposed\")\n\t\t}\n\t\treturn MakeLabels(labels), nil\n\n\tcase *appsv1.ReplicaSet:\n\t\t// \"apps\" replicasets must have the selector set.\n\t\tif t.Spec.Selector == nil || len(t.Spec.Selector.MatchLabels) == 0 {\n\t\t\treturn \"\", fmt.Errorf(\"invalid replicaset: no selectors, therefore cannot be exposed\")\n\t\t}\n\t\t// TODO(madhusudancs): Make this smarter by admitting MatchExpressions with Equals\n\t\t// operator, DoubleEquals operator and In operator with only one element in the set.\n\t\tif len(t.Spec.Selector.MatchExpressions) \u003e 0 {\n\t\t\treturn \"\", fmt.Errorf(\"couldn't convert expressions - \\\"%+v\\\" to map-based selector format\", t.Spec.Selector.MatchExpressions)\n\t\t}\n\t\treturn MakeLabels(t.Spec.Selector.MatchLabels), nil\n\n\tcase *appsv1beta2.ReplicaSet:\n\t\t// \"apps\" replicasets must have the selector set.\n\t\tif t.Spec.Selector == nil || len(t.Spec.Selector.MatchLabels) == 0 {\n\t\t\treturn \"\", fmt.Errorf(\"invalid replicaset: no selectors, therefore cannot be exposed\")\n\t\t}\n\t\t// TODO(madhusudancs): Make this smarter by admitting MatchExpressions with Equals\n\t\t// operator, DoubleEquals operator and In operator with only one element in the set.\n\t\tif len(t.Spec.Selector.MatchExpressions) \u003e 0 {\n\t\t\treturn \"\", fmt.Errorf(\"couldn't convert expressions - \\\"%+v\\\" to map-based selector format\", t.Spec.Selector.MatchExpressions)\n\t\t}\n\t\treturn MakeLabels(t.Spec.Selector.MatchLabels), nil\n\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"cannot extract pod selector from %T\", object)\n\t}\n\n}","line":{"from":31,"to":152}} {"id":100032760,"name":"MakeLabels","signature":"func MakeLabels(labels map[string]string) string","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/mapbasedselectorforobject.go","code":"func MakeLabels(labels map[string]string) string {\n\tout := []string{}\n\tfor key, value := range labels {\n\t\tout = append(out, fmt.Sprintf(\"%s=%s\", key, value))\n\t}\n\treturn strings.Join(out, \",\")\n}","line":{"from":154,"to":160}} {"id":100032761,"name":"defaultObjectPauser","signature":"func defaultObjectPauser(obj runtime.Object) ([]byte, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/objectpauser.go","code":"// Currently only supports Deployments.\nfunc defaultObjectPauser(obj runtime.Object) ([]byte, error) {\n\tswitch obj := obj.(type) {\n\tcase *extensionsv1beta1.Deployment:\n\t\tif obj.Spec.Paused {\n\t\t\treturn nil, errors.New(\"is already paused\")\n\t\t}\n\t\tobj.Spec.Paused = true\n\t\treturn runtime.Encode(scheme.Codecs.LegacyCodec(extensionsv1beta1.SchemeGroupVersion), obj)\n\n\tcase *appsv1.Deployment:\n\t\tif obj.Spec.Paused {\n\t\t\treturn nil, errors.New(\"is already paused\")\n\t\t}\n\t\tobj.Spec.Paused = true\n\t\treturn runtime.Encode(scheme.Codecs.LegacyCodec(appsv1.SchemeGroupVersion), obj)\n\n\tcase *appsv1beta2.Deployment:\n\t\tif obj.Spec.Paused {\n\t\t\treturn nil, errors.New(\"is already paused\")\n\t\t}\n\t\tobj.Spec.Paused = true\n\t\treturn runtime.Encode(scheme.Codecs.LegacyCodec(appsv1beta2.SchemeGroupVersion), obj)\n\n\tcase *appsv1beta1.Deployment:\n\t\tif obj.Spec.Paused {\n\t\t\treturn nil, errors.New(\"is already paused\")\n\t\t}\n\t\tobj.Spec.Paused = true\n\t\treturn runtime.Encode(scheme.Codecs.LegacyCodec(appsv1beta1.SchemeGroupVersion), obj)\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"pausing is not supported\")\n\t}\n}","line":{"from":31,"to":65}} {"id":100032762,"name":"defaultObjectRestarter","signature":"func defaultObjectRestarter(obj runtime.Object) ([]byte, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/objectrestarter.go","code":"func defaultObjectRestarter(obj runtime.Object) ([]byte, error) {\n\tswitch obj := obj.(type) {\n\tcase *extensionsv1beta1.Deployment:\n\t\tif obj.Spec.Paused {\n\t\t\treturn nil, errors.New(\"can't restart paused deployment (run rollout resume first)\")\n\t\t}\n\t\tif obj.Spec.Template.ObjectMeta.Annotations == nil {\n\t\t\tobj.Spec.Template.ObjectMeta.Annotations = make(map[string]string)\n\t\t}\n\t\tobj.Spec.Template.ObjectMeta.Annotations[\"kubectl.kubernetes.io/restartedAt\"] = time.Now().Format(time.RFC3339)\n\t\treturn runtime.Encode(scheme.Codecs.LegacyCodec(extensionsv1beta1.SchemeGroupVersion), obj)\n\n\tcase *appsv1.Deployment:\n\t\tif obj.Spec.Paused {\n\t\t\treturn nil, errors.New(\"can't restart paused deployment (run rollout resume first)\")\n\t\t}\n\t\tif obj.Spec.Template.ObjectMeta.Annotations == nil {\n\t\t\tobj.Spec.Template.ObjectMeta.Annotations = make(map[string]string)\n\t\t}\n\t\tobj.Spec.Template.ObjectMeta.Annotations[\"kubectl.kubernetes.io/restartedAt\"] = time.Now().Format(time.RFC3339)\n\t\treturn runtime.Encode(scheme.Codecs.LegacyCodec(appsv1.SchemeGroupVersion), obj)\n\n\tcase *appsv1beta2.Deployment:\n\t\tif obj.Spec.Paused {\n\t\t\treturn nil, errors.New(\"can't restart paused deployment (run rollout resume first)\")\n\t\t}\n\t\tif obj.Spec.Template.ObjectMeta.Annotations == nil {\n\t\t\tobj.Spec.Template.ObjectMeta.Annotations = make(map[string]string)\n\t\t}\n\t\tobj.Spec.Template.ObjectMeta.Annotations[\"kubectl.kubernetes.io/restartedAt\"] = time.Now().Format(time.RFC3339)\n\t\treturn runtime.Encode(scheme.Codecs.LegacyCodec(appsv1beta2.SchemeGroupVersion), obj)\n\n\tcase *appsv1beta1.Deployment:\n\t\tif obj.Spec.Paused {\n\t\t\treturn nil, errors.New(\"can't restart paused deployment (run rollout resume first)\")\n\t\t}\n\t\tif obj.Spec.Template.ObjectMeta.Annotations == nil {\n\t\t\tobj.Spec.Template.ObjectMeta.Annotations = make(map[string]string)\n\t\t}\n\t\tobj.Spec.Template.ObjectMeta.Annotations[\"kubectl.kubernetes.io/restartedAt\"] = time.Now().Format(time.RFC3339)\n\t\treturn runtime.Encode(scheme.Codecs.LegacyCodec(appsv1beta1.SchemeGroupVersion), obj)\n\n\tcase *extensionsv1beta1.DaemonSet:\n\t\tif obj.Spec.Template.ObjectMeta.Annotations == nil {\n\t\t\tobj.Spec.Template.ObjectMeta.Annotations = make(map[string]string)\n\t\t}\n\t\tobj.Spec.Template.ObjectMeta.Annotations[\"kubectl.kubernetes.io/restartedAt\"] = time.Now().Format(time.RFC3339)\n\t\treturn runtime.Encode(scheme.Codecs.LegacyCodec(extensionsv1beta1.SchemeGroupVersion), obj)\n\n\tcase *appsv1.DaemonSet:\n\t\tif obj.Spec.Template.ObjectMeta.Annotations == nil {\n\t\t\tobj.Spec.Template.ObjectMeta.Annotations = make(map[string]string)\n\t\t}\n\t\tobj.Spec.Template.ObjectMeta.Annotations[\"kubectl.kubernetes.io/restartedAt\"] = time.Now().Format(time.RFC3339)\n\t\treturn runtime.Encode(scheme.Codecs.LegacyCodec(appsv1.SchemeGroupVersion), obj)\n\n\tcase *appsv1beta2.DaemonSet:\n\t\tif obj.Spec.Template.ObjectMeta.Annotations == nil {\n\t\t\tobj.Spec.Template.ObjectMeta.Annotations = make(map[string]string)\n\t\t}\n\t\tobj.Spec.Template.ObjectMeta.Annotations[\"kubectl.kubernetes.io/restartedAt\"] = time.Now().Format(time.RFC3339)\n\t\treturn runtime.Encode(scheme.Codecs.LegacyCodec(appsv1beta2.SchemeGroupVersion), obj)\n\n\tcase *appsv1.StatefulSet:\n\t\tif obj.Spec.Template.ObjectMeta.Annotations == nil {\n\t\t\tobj.Spec.Template.ObjectMeta.Annotations = make(map[string]string)\n\t\t}\n\t\tobj.Spec.Template.ObjectMeta.Annotations[\"kubectl.kubernetes.io/restartedAt\"] = time.Now().Format(time.RFC3339)\n\t\treturn runtime.Encode(scheme.Codecs.LegacyCodec(appsv1.SchemeGroupVersion), obj)\n\n\tcase *appsv1beta1.StatefulSet:\n\t\tif obj.Spec.Template.ObjectMeta.Annotations == nil {\n\t\t\tobj.Spec.Template.ObjectMeta.Annotations = make(map[string]string)\n\t\t}\n\t\tobj.Spec.Template.ObjectMeta.Annotations[\"kubectl.kubernetes.io/restartedAt\"] = time.Now().Format(time.RFC3339)\n\t\treturn runtime.Encode(scheme.Codecs.LegacyCodec(appsv1beta1.SchemeGroupVersion), obj)\n\n\tcase *appsv1beta2.StatefulSet:\n\t\tif obj.Spec.Template.ObjectMeta.Annotations == nil {\n\t\t\tobj.Spec.Template.ObjectMeta.Annotations = make(map[string]string)\n\t\t}\n\t\tobj.Spec.Template.ObjectMeta.Annotations[\"kubectl.kubernetes.io/restartedAt\"] = time.Now().Format(time.RFC3339)\n\t\treturn runtime.Encode(scheme.Codecs.LegacyCodec(appsv1beta2.SchemeGroupVersion), obj)\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"restarting is not supported\")\n\t}\n}","line":{"from":32,"to":119}} {"id":100032763,"name":"defaultObjectResumer","signature":"func defaultObjectResumer(obj runtime.Object) ([]byte, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/objectresumer.go","code":"func defaultObjectResumer(obj runtime.Object) ([]byte, error) {\n\tswitch obj := obj.(type) {\n\tcase *extensionsv1beta1.Deployment:\n\t\tif !obj.Spec.Paused {\n\t\t\treturn nil, errors.New(\"is not paused\")\n\t\t}\n\t\tobj.Spec.Paused = false\n\t\treturn runtime.Encode(scheme.Codecs.LegacyCodec(extensionsv1beta1.SchemeGroupVersion), obj)\n\n\tcase *appsv1.Deployment:\n\t\tif !obj.Spec.Paused {\n\t\t\treturn nil, errors.New(\"is not paused\")\n\t\t}\n\t\tobj.Spec.Paused = false\n\t\treturn runtime.Encode(scheme.Codecs.LegacyCodec(appsv1.SchemeGroupVersion), obj)\n\n\tcase *appsv1beta2.Deployment:\n\t\tif !obj.Spec.Paused {\n\t\t\treturn nil, errors.New(\"is not paused\")\n\t\t}\n\t\tobj.Spec.Paused = false\n\t\treturn runtime.Encode(scheme.Codecs.LegacyCodec(appsv1beta2.SchemeGroupVersion), obj)\n\n\tcase *appsv1beta1.Deployment:\n\t\tif !obj.Spec.Paused {\n\t\t\treturn nil, errors.New(\"is not paused\")\n\t\t}\n\t\tobj.Spec.Paused = false\n\t\treturn runtime.Encode(scheme.Codecs.LegacyCodec(appsv1beta1.SchemeGroupVersion), obj)\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"resuming is not supported\")\n\t}\n}","line":{"from":31,"to":64}} {"id":100032764,"name":"portsForObject","signature":"func portsForObject(object runtime.Object) ([]string, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/portsforobject.go","code":"func portsForObject(object runtime.Object) ([]string, error) {\n\tswitch t := object.(type) {\n\tcase *corev1.ReplicationController:\n\t\treturn getPorts(t.Spec.Template.Spec), nil\n\n\tcase *corev1.Pod:\n\t\treturn getPorts(t.Spec), nil\n\n\tcase *corev1.Service:\n\t\treturn getServicePorts(t.Spec), nil\n\n\tcase *extensionsv1beta1.Deployment:\n\t\treturn getPorts(t.Spec.Template.Spec), nil\n\tcase *appsv1.Deployment:\n\t\treturn getPorts(t.Spec.Template.Spec), nil\n\tcase *appsv1beta2.Deployment:\n\t\treturn getPorts(t.Spec.Template.Spec), nil\n\tcase *appsv1beta1.Deployment:\n\t\treturn getPorts(t.Spec.Template.Spec), nil\n\n\tcase *extensionsv1beta1.ReplicaSet:\n\t\treturn getPorts(t.Spec.Template.Spec), nil\n\tcase *appsv1.ReplicaSet:\n\t\treturn getPorts(t.Spec.Template.Spec), nil\n\tcase *appsv1beta2.ReplicaSet:\n\t\treturn getPorts(t.Spec.Template.Spec), nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"cannot extract ports from %T\", object)\n\t}\n}","line":{"from":31,"to":60}} {"id":100032765,"name":"getPorts","signature":"func getPorts(spec corev1.PodSpec) []string","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/portsforobject.go","code":"func getPorts(spec corev1.PodSpec) []string {\n\tresult := []string{}\n\tfor _, container := range spec.Containers {\n\t\tfor _, port := range container.Ports {\n\t\t\tresult = append(result, strconv.Itoa(int(port.ContainerPort)))\n\t\t}\n\t}\n\treturn result\n}","line":{"from":62,"to":70}} {"id":100032766,"name":"getServicePorts","signature":"func getServicePorts(spec corev1.ServiceSpec) []string","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/portsforobject.go","code":"func getServicePorts(spec corev1.ServiceSpec) []string {\n\tresult := []string{}\n\tfor _, servicePort := range spec.Ports {\n\t\tresult = append(result, strconv.Itoa(int(servicePort.Port)))\n\t}\n\treturn result\n}","line":{"from":72,"to":78}} {"id":100032767,"name":"protocolsForObject","signature":"func protocolsForObject(object runtime.Object) (map[string]string, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/protocolsforobject.go","code":"func protocolsForObject(object runtime.Object) (map[string]string, error) {\n\t// TODO: replace with a swagger schema based approach (identify pod selector via schema introspection)\n\tswitch t := object.(type) {\n\tcase *corev1.ReplicationController:\n\t\treturn getProtocols(t.Spec.Template.Spec), nil\n\n\tcase *corev1.Pod:\n\t\treturn getProtocols(t.Spec), nil\n\n\tcase *corev1.Service:\n\t\treturn getServiceProtocols(t.Spec), nil\n\n\tcase *extensionsv1beta1.Deployment:\n\t\treturn getProtocols(t.Spec.Template.Spec), nil\n\tcase *appsv1.Deployment:\n\t\treturn getProtocols(t.Spec.Template.Spec), nil\n\tcase *appsv1beta2.Deployment:\n\t\treturn getProtocols(t.Spec.Template.Spec), nil\n\tcase *appsv1beta1.Deployment:\n\t\treturn getProtocols(t.Spec.Template.Spec), nil\n\n\tcase *extensionsv1beta1.ReplicaSet:\n\t\treturn getProtocols(t.Spec.Template.Spec), nil\n\tcase *appsv1.ReplicaSet:\n\t\treturn getProtocols(t.Spec.Template.Spec), nil\n\tcase *appsv1beta2.ReplicaSet:\n\t\treturn getProtocols(t.Spec.Template.Spec), nil\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"cannot extract protocols from %T\", object)\n\t}\n}","line":{"from":31,"to":62}} {"id":100032768,"name":"getProtocols","signature":"func getProtocols(spec corev1.PodSpec) map[string]string","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/protocolsforobject.go","code":"func getProtocols(spec corev1.PodSpec) map[string]string {\n\tresult := make(map[string]string)\n\tfor _, container := range spec.Containers {\n\t\tfor _, port := range container.Ports {\n\t\t\t// Empty protocol must be defaulted (TCP)\n\t\t\tif len(port.Protocol) == 0 {\n\t\t\t\tport.Protocol = corev1.ProtocolTCP\n\t\t\t}\n\t\t\tresult[strconv.Itoa(int(port.ContainerPort))] = string(port.Protocol)\n\t\t}\n\t}\n\treturn result\n}","line":{"from":64,"to":76}} {"id":100032769,"name":"getServiceProtocols","signature":"func getServiceProtocols(spec corev1.ServiceSpec) map[string]string","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/protocolsforobject.go","code":"// Extracts the protocols exposed by a service from the given service spec.\nfunc getServiceProtocols(spec corev1.ServiceSpec) map[string]string {\n\tresult := make(map[string]string)\n\tfor _, servicePort := range spec.Ports {\n\t\t// Empty protocol must be defaulted (TCP)\n\t\tif len(servicePort.Protocol) == 0 {\n\t\t\tservicePort.Protocol = corev1.ProtocolTCP\n\t\t}\n\t\tresult[strconv.Itoa(int(servicePort.Port))] = string(servicePort.Protocol)\n\t}\n\treturn result\n}","line":{"from":78,"to":89}} {"id":100032770,"name":"VisitDeployment","signature":"func (v *RollbackVisitor) VisitDeployment(elem apps.GroupKindElement)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollback.go","code":"func (v *RollbackVisitor) VisitDeployment(elem apps.GroupKindElement) {\n\tv.result = \u0026DeploymentRollbacker{v.clientset}\n}","line":{"from":57,"to":59}} {"id":100032771,"name":"VisitStatefulSet","signature":"func (v *RollbackVisitor) VisitStatefulSet(kind apps.GroupKindElement)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollback.go","code":"func (v *RollbackVisitor) VisitStatefulSet(kind apps.GroupKindElement) {\n\tv.result = \u0026StatefulSetRollbacker{v.clientset}\n}","line":{"from":61,"to":63}} {"id":100032772,"name":"VisitDaemonSet","signature":"func (v *RollbackVisitor) VisitDaemonSet(kind apps.GroupKindElement)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollback.go","code":"func (v *RollbackVisitor) VisitDaemonSet(kind apps.GroupKindElement) {\n\tv.result = \u0026DaemonSetRollbacker{v.clientset}\n}","line":{"from":65,"to":67}} {"id":100032773,"name":"VisitJob","signature":"func (v *RollbackVisitor) VisitJob(kind apps.GroupKindElement) {}","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollback.go","code":"func (v *RollbackVisitor) VisitJob(kind apps.GroupKindElement) {}","line":{"from":69,"to":69}} {"id":100032774,"name":"VisitPod","signature":"func (v *RollbackVisitor) VisitPod(kind apps.GroupKindElement) {}","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollback.go","code":"func (v *RollbackVisitor) VisitPod(kind apps.GroupKindElement) {}","line":{"from":70,"to":70}} {"id":100032775,"name":"VisitReplicaSet","signature":"func (v *RollbackVisitor) VisitReplicaSet(kind apps.GroupKindElement) {}","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollback.go","code":"func (v *RollbackVisitor) VisitReplicaSet(kind apps.GroupKindElement) {}","line":{"from":71,"to":71}} {"id":100032776,"name":"VisitReplicationController","signature":"func (v *RollbackVisitor) VisitReplicationController(kind apps.GroupKindElement) {}","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollback.go","code":"func (v *RollbackVisitor) VisitReplicationController(kind apps.GroupKindElement) {}","line":{"from":72,"to":72}} {"id":100032777,"name":"VisitCronJob","signature":"func (v *RollbackVisitor) VisitCronJob(kind apps.GroupKindElement) {}","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollback.go","code":"func (v *RollbackVisitor) VisitCronJob(kind apps.GroupKindElement) {}","line":{"from":73,"to":73}} {"id":100032778,"name":"RollbackerFor","signature":"func RollbackerFor(kind schema.GroupKind, c kubernetes.Interface) (Rollbacker, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollback.go","code":"// RollbackerFor returns an implementation of Rollbacker interface for the given schema kind\nfunc RollbackerFor(kind schema.GroupKind, c kubernetes.Interface) (Rollbacker, error) {\n\telem := apps.GroupKindElement(kind)\n\tvisitor := \u0026RollbackVisitor{\n\t\tclientset: c,\n\t}\n\n\terr := elem.Accept(visitor)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error retrieving rollbacker for %q, %v\", kind.String(), err)\n\t}\n\n\tif visitor.result == nil {\n\t\treturn nil, fmt.Errorf(\"no rollbacker has been implemented for %q\", kind)\n\t}\n\n\treturn visitor.result, nil\n}","line":{"from":75,"to":93}} {"id":100032779,"name":"Rollback","signature":"func (r *DeploymentRollbacker) Rollback(obj runtime.Object, updatedAnnotations map[string]string, toRevision int64, dryRunStrategy cmdutil.DryRunStrategy) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollback.go","code":"func (r *DeploymentRollbacker) Rollback(obj runtime.Object, updatedAnnotations map[string]string, toRevision int64, dryRunStrategy cmdutil.DryRunStrategy) (string, error) {\n\tif toRevision \u003c 0 {\n\t\treturn \"\", revisionNotFoundErr(toRevision)\n\t}\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to create accessor for kind %v: %s\", obj.GetObjectKind(), err.Error())\n\t}\n\tname := accessor.GetName()\n\tnamespace := accessor.GetNamespace()\n\n\t// TODO: Fix this after kubectl has been removed from core. It is not possible to convert the runtime.Object\n\t// to the external appsv1 Deployment without round-tripping through an internal version of Deployment. We're\n\t// currently getting rid of all internal versions of resources. So we specifically request the appsv1 version\n\t// here. This follows the same pattern as for DaemonSet and StatefulSet.\n\tdeployment, err := r.c.AppsV1().Deployments(namespace).Get(context.TODO(), name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to retrieve Deployment %s: %v\", name, err)\n\t}\n\n\trsForRevision, err := deploymentRevision(deployment, r.c, toRevision)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif dryRunStrategy == cmdutil.DryRunClient {\n\t\treturn printTemplate(\u0026rsForRevision.Spec.Template)\n\t}\n\tif deployment.Spec.Paused {\n\t\treturn \"\", fmt.Errorf(\"you cannot rollback a paused deployment; resume it first with 'kubectl rollout resume' and try again\")\n\t}\n\n\t// Skip if the revision already matches current Deployment\n\tif equalIgnoreHash(\u0026rsForRevision.Spec.Template, \u0026deployment.Spec.Template) {\n\t\treturn fmt.Sprintf(\"%s (current template already matches revision %d)\", rollbackSkipped, toRevision), nil\n\t}\n\n\t// remove hash label before patching back into the deployment\n\tdelete(rsForRevision.Spec.Template.Labels, appsv1.DefaultDeploymentUniqueLabelKey)\n\n\t// compute deployment annotations\n\tannotations := map[string]string{}\n\tfor k := range annotationsToSkip {\n\t\tif v, ok := deployment.Annotations[k]; ok {\n\t\t\tannotations[k] = v\n\t\t}\n\t}\n\tfor k, v := range rsForRevision.Annotations {\n\t\tif !annotationsToSkip[k] {\n\t\t\tannotations[k] = v\n\t\t}\n\t}\n\n\t// make patch to restore\n\tpatchType, patch, err := getDeploymentPatch(\u0026rsForRevision.Spec.Template, annotations)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed restoring revision %d: %v\", toRevision, err)\n\t}\n\n\tpatchOptions := metav1.PatchOptions{}\n\tif dryRunStrategy == cmdutil.DryRunServer {\n\t\tpatchOptions.DryRun = []string{metav1.DryRunAll}\n\t}\n\t// Restore revision\n\tif _, err = r.c.AppsV1().Deployments(namespace).Patch(context.TODO(), name, patchType, patch, patchOptions); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed restoring revision %d: %v\", toRevision, err)\n\t}\n\treturn rollbackSuccess, nil\n}","line":{"from":99,"to":166}} {"id":100032780,"name":"equalIgnoreHash","signature":"func equalIgnoreHash(template1, template2 *corev1.PodTemplateSpec) bool","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollback.go","code":"// equalIgnoreHash returns true if two given podTemplateSpec are equal, ignoring the diff in value of Labels[pod-template-hash]\n// We ignore pod-template-hash because:\n// 1. The hash result would be different upon podTemplateSpec API changes\n// (e.g. the addition of a new field will cause the hash code to change)\n// 2. The deployment template won't have hash labels\nfunc equalIgnoreHash(template1, template2 *corev1.PodTemplateSpec) bool {\n\tt1Copy := template1.DeepCopy()\n\tt2Copy := template2.DeepCopy()\n\t// Remove hash labels from template.Labels before comparing\n\tdelete(t1Copy.Labels, appsv1.DefaultDeploymentUniqueLabelKey)\n\tdelete(t2Copy.Labels, appsv1.DefaultDeploymentUniqueLabelKey)\n\treturn apiequality.Semantic.DeepEqual(t1Copy, t2Copy)\n}","line":{"from":168,"to":180}} {"id":100032781,"name":"getDeploymentPatch","signature":"func getDeploymentPatch(podTemplate *corev1.PodTemplateSpec, annotations map[string]string) (types.PatchType, []byte, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollback.go","code":"// getPatch returns a patch that can be applied to restore a Deployment to a\n// previous version. If the returned error is nil the patch is valid.\nfunc getDeploymentPatch(podTemplate *corev1.PodTemplateSpec, annotations map[string]string) (types.PatchType, []byte, error) {\n\t// Create a patch of the Deployment that replaces spec.template\n\tpatch, err := json.Marshal([]interface{}{\n\t\tmap[string]interface{}{\n\t\t\t\"op\": \"replace\",\n\t\t\t\"path\": \"/spec/template\",\n\t\t\t\"value\": podTemplate,\n\t\t},\n\t\tmap[string]interface{}{\n\t\t\t\"op\": \"replace\",\n\t\t\t\"path\": \"/metadata/annotations\",\n\t\t\t\"value\": annotations,\n\t\t},\n\t})\n\treturn types.JSONPatchType, patch, err\n}","line":{"from":193,"to":210}} {"id":100032782,"name":"deploymentRevision","signature":"func deploymentRevision(deployment *appsv1.Deployment, c kubernetes.Interface, toRevision int64) (revision *appsv1.ReplicaSet, err error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollback.go","code":"func deploymentRevision(deployment *appsv1.Deployment, c kubernetes.Interface, toRevision int64) (revision *appsv1.ReplicaSet, err error) {\n\n\t_, allOldRSs, newRS, err := deploymentutil.GetAllReplicaSets(deployment, c.AppsV1())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to retrieve replica sets from deployment %s: %v\", deployment.Name, err)\n\t}\n\tallRSs := allOldRSs\n\tif newRS != nil {\n\t\tallRSs = append(allRSs, newRS)\n\t}\n\n\tvar (\n\t\tlatestReplicaSet *appsv1.ReplicaSet\n\t\tlatestRevision = int64(-1)\n\t\tpreviousReplicaSet *appsv1.ReplicaSet\n\t\tpreviousRevision = int64(-1)\n\t)\n\tfor _, rs := range allRSs {\n\t\tif v, err := deploymentutil.Revision(rs); err == nil {\n\t\t\tif toRevision == 0 {\n\t\t\t\tif latestRevision \u003c v {\n\t\t\t\t\t// newest one we've seen so far\n\t\t\t\t\tpreviousRevision = latestRevision\n\t\t\t\t\tpreviousReplicaSet = latestReplicaSet\n\t\t\t\t\tlatestRevision = v\n\t\t\t\t\tlatestReplicaSet = rs\n\t\t\t\t} else if previousRevision \u003c v {\n\t\t\t\t\t// second newest one we've seen so far\n\t\t\t\t\tpreviousRevision = v\n\t\t\t\t\tpreviousReplicaSet = rs\n\t\t\t\t}\n\t\t\t} else if toRevision == v {\n\t\t\t\treturn rs, nil\n\t\t\t}\n\t\t}\n\t}\n\n\tif toRevision \u003e 0 {\n\t\treturn nil, revisionNotFoundErr(toRevision)\n\t}\n\n\tif previousReplicaSet == nil {\n\t\treturn nil, fmt.Errorf(\"no rollout history found for deployment %q\", deployment.Name)\n\t}\n\treturn previousReplicaSet, nil\n}","line":{"from":212,"to":257}} {"id":100032783,"name":"Rollback","signature":"func (r *DaemonSetRollbacker) Rollback(obj runtime.Object, updatedAnnotations map[string]string, toRevision int64, dryRunStrategy cmdutil.DryRunStrategy) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollback.go","code":"func (r *DaemonSetRollbacker) Rollback(obj runtime.Object, updatedAnnotations map[string]string, toRevision int64, dryRunStrategy cmdutil.DryRunStrategy) (string, error) {\n\tif toRevision \u003c 0 {\n\t\treturn \"\", revisionNotFoundErr(toRevision)\n\t}\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to create accessor for kind %v: %s\", obj.GetObjectKind(), err.Error())\n\t}\n\tds, history, err := daemonSetHistory(r.c.AppsV1(), accessor.GetNamespace(), accessor.GetName())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif toRevision == 0 \u0026\u0026 len(history) \u003c= 1 {\n\t\treturn \"\", fmt.Errorf(\"no last revision to roll back to\")\n\t}\n\n\ttoHistory := findHistory(toRevision, history)\n\tif toHistory == nil {\n\t\treturn \"\", revisionNotFoundErr(toRevision)\n\t}\n\n\tif dryRunStrategy == cmdutil.DryRunClient {\n\t\tappliedDS, err := applyDaemonSetHistory(ds, toHistory)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn printPodTemplate(\u0026appliedDS.Spec.Template)\n\t}\n\n\t// Skip if the revision already matches current DaemonSet\n\tdone, err := daemonSetMatch(ds, toHistory)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif done {\n\t\treturn fmt.Sprintf(\"%s (current template already matches revision %d)\", rollbackSkipped, toRevision), nil\n\t}\n\n\tpatchOptions := metav1.PatchOptions{}\n\tif dryRunStrategy == cmdutil.DryRunServer {\n\t\tpatchOptions.DryRun = []string{metav1.DryRunAll}\n\t}\n\t// Restore revision\n\tif _, err = r.c.AppsV1().DaemonSets(accessor.GetNamespace()).Patch(context.TODO(), accessor.GetName(), types.StrategicMergePatchType, toHistory.Data.Raw, patchOptions); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed restoring revision %d: %v\", toRevision, err)\n\t}\n\n\treturn rollbackSuccess, nil\n}","line":{"from":263,"to":311}} {"id":100032784,"name":"daemonSetMatch","signature":"func daemonSetMatch(ds *appsv1.DaemonSet, history *appsv1.ControllerRevision) (bool, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollback.go","code":"// daemonMatch check if the given DaemonSet's template matches the template stored in the given history.\nfunc daemonSetMatch(ds *appsv1.DaemonSet, history *appsv1.ControllerRevision) (bool, error) {\n\tpatch, err := getDaemonSetPatch(ds)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn bytes.Equal(patch, history.Data.Raw), nil\n}","line":{"from":313,"to":320}} {"id":100032785,"name":"getDaemonSetPatch","signature":"func getDaemonSetPatch(ds *appsv1.DaemonSet) ([]byte, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollback.go","code":"// getPatch returns a strategic merge patch that can be applied to restore a Daemonset to a\n// previous version. If the returned error is nil the patch is valid. The current state that we save is just the\n// PodSpecTemplate. We can modify this later to encompass more state (or less) and remain compatible with previously\n// recorded patches.\nfunc getDaemonSetPatch(ds *appsv1.DaemonSet) ([]byte, error) {\n\tdsBytes, err := json.Marshal(ds)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar raw map[string]interface{}\n\terr = json.Unmarshal(dsBytes, \u0026raw)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tobjCopy := make(map[string]interface{})\n\tspecCopy := make(map[string]interface{})\n\n\t// Create a patch of the DaemonSet that replaces spec.template\n\tspec := raw[\"spec\"].(map[string]interface{})\n\ttemplate := spec[\"template\"].(map[string]interface{})\n\tspecCopy[\"template\"] = template\n\ttemplate[\"$patch\"] = \"replace\"\n\tobjCopy[\"spec\"] = specCopy\n\tpatch, err := json.Marshal(objCopy)\n\treturn patch, err\n}","line":{"from":322,"to":347}} {"id":100032786,"name":"Rollback","signature":"func (r *StatefulSetRollbacker) Rollback(obj runtime.Object, updatedAnnotations map[string]string, toRevision int64, dryRunStrategy cmdutil.DryRunStrategy) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollback.go","code":"// toRevision is a non-negative integer, with 0 being reserved to indicate rolling back to previous configuration\nfunc (r *StatefulSetRollbacker) Rollback(obj runtime.Object, updatedAnnotations map[string]string, toRevision int64, dryRunStrategy cmdutil.DryRunStrategy) (string, error) {\n\tif toRevision \u003c 0 {\n\t\treturn \"\", revisionNotFoundErr(toRevision)\n\t}\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to create accessor for kind %v: %s\", obj.GetObjectKind(), err.Error())\n\t}\n\tsts, history, err := statefulSetHistory(r.c.AppsV1(), accessor.GetNamespace(), accessor.GetName())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif toRevision == 0 \u0026\u0026 len(history) \u003c= 1 {\n\t\treturn \"\", fmt.Errorf(\"no last revision to roll back to\")\n\t}\n\n\ttoHistory := findHistory(toRevision, history)\n\tif toHistory == nil {\n\t\treturn \"\", revisionNotFoundErr(toRevision)\n\t}\n\n\tif dryRunStrategy == cmdutil.DryRunClient {\n\t\tappliedSS, err := applyRevision(sts, toHistory)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn printPodTemplate(\u0026appliedSS.Spec.Template)\n\t}\n\n\t// Skip if the revision already matches current StatefulSet\n\tdone, err := statefulsetMatch(sts, toHistory)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif done {\n\t\treturn fmt.Sprintf(\"%s (current template already matches revision %d)\", rollbackSkipped, toRevision), nil\n\t}\n\n\tpatchOptions := metav1.PatchOptions{}\n\tif dryRunStrategy == cmdutil.DryRunServer {\n\t\tpatchOptions.DryRun = []string{metav1.DryRunAll}\n\t}\n\t// Restore revision\n\tif _, err = r.c.AppsV1().StatefulSets(sts.Namespace).Patch(context.TODO(), sts.Name, types.StrategicMergePatchType, toHistory.Data.Raw, patchOptions); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed restoring revision %d: %v\", toRevision, err)\n\t}\n\n\treturn rollbackSuccess, nil\n}","line":{"from":353,"to":402}} {"id":100032787,"name":"applyRevision","signature":"func applyRevision(set *appsv1.StatefulSet, revision *appsv1.ControllerRevision) (*appsv1.StatefulSet, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollback.go","code":"// applyRevision returns a new StatefulSet constructed by restoring the state in revision to set. If the returned error\n// is nil, the returned StatefulSet is valid.\nfunc applyRevision(set *appsv1.StatefulSet, revision *appsv1.ControllerRevision) (*appsv1.StatefulSet, error) {\n\tpatched, err := strategicpatch.StrategicMergePatch([]byte(runtime.EncodeOrDie(appsCodec, set)), revision.Data.Raw, set)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := \u0026appsv1.StatefulSet{}\n\terr = json.Unmarshal(patched, result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}","line":{"from":406,"to":419}} {"id":100032788,"name":"statefulsetMatch","signature":"func statefulsetMatch(ss *appsv1.StatefulSet, history *appsv1.ControllerRevision) (bool, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollback.go","code":"// statefulsetMatch check if the given StatefulSet's template matches the template stored in the given history.\nfunc statefulsetMatch(ss *appsv1.StatefulSet, history *appsv1.ControllerRevision) (bool, error) {\n\tpatch, err := getStatefulSetPatch(ss)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn bytes.Equal(patch, history.Data.Raw), nil\n}","line":{"from":421,"to":428}} {"id":100032789,"name":"getStatefulSetPatch","signature":"func getStatefulSetPatch(set *appsv1.StatefulSet) ([]byte, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollback.go","code":"// getStatefulSetPatch returns a strategic merge patch that can be applied to restore a StatefulSet to a\n// previous version. If the returned error is nil the patch is valid. The current state that we save is just the\n// PodSpecTemplate. We can modify this later to encompass more state (or less) and remain compatible with previously\n// recorded patches.\nfunc getStatefulSetPatch(set *appsv1.StatefulSet) ([]byte, error) {\n\tstr, err := runtime.Encode(appsCodec, set)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar raw map[string]interface{}\n\tif err := json.Unmarshal([]byte(str), \u0026raw); err != nil {\n\t\treturn nil, err\n\t}\n\tobjCopy := make(map[string]interface{})\n\tspecCopy := make(map[string]interface{})\n\tspec := raw[\"spec\"].(map[string]interface{})\n\ttemplate := spec[\"template\"].(map[string]interface{})\n\tspecCopy[\"template\"] = template\n\ttemplate[\"$patch\"] = \"replace\"\n\tobjCopy[\"spec\"] = specCopy\n\tpatch, err := json.Marshal(objCopy)\n\treturn patch, err\n}","line":{"from":430,"to":452}} {"id":100032790,"name":"findHistory","signature":"func findHistory(toRevision int64, allHistory []*appsv1.ControllerRevision) *appsv1.ControllerRevision","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollback.go","code":"// findHistory returns a controllerrevision of a specific revision from the given controllerrevisions.\n// It returns nil if no such controllerrevision exists.\n// If toRevision is 0, the last previously used history is returned.\nfunc findHistory(toRevision int64, allHistory []*appsv1.ControllerRevision) *appsv1.ControllerRevision {\n\tif toRevision == 0 \u0026\u0026 len(allHistory) \u003c= 1 {\n\t\treturn nil\n\t}\n\n\t// Find the history to rollback to\n\tvar toHistory *appsv1.ControllerRevision\n\tif toRevision == 0 {\n\t\t// If toRevision == 0, find the latest revision (2nd max)\n\t\tsort.Sort(historiesByRevision(allHistory))\n\t\ttoHistory = allHistory[len(allHistory)-2]\n\t} else {\n\t\tfor _, h := range allHistory {\n\t\t\tif h.Revision == toRevision {\n\t\t\t\t// If toRevision != 0, find the history with matching revision\n\t\t\t\treturn h\n\t\t\t}\n\t\t}\n\t}\n\n\treturn toHistory\n}","line":{"from":454,"to":478}} {"id":100032791,"name":"printPodTemplate","signature":"func printPodTemplate(specTemplate *corev1.PodTemplateSpec) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollback.go","code":"// printPodTemplate converts a given pod template into a human-readable string.\nfunc printPodTemplate(specTemplate *corev1.PodTemplateSpec) (string, error) {\n\tpodSpec, err := printTemplate(specTemplate)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"will roll back to %s\", podSpec), nil\n}","line":{"from":480,"to":487}} {"id":100032792,"name":"revisionNotFoundErr","signature":"func revisionNotFoundErr(r int64) error","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollback.go","code":"func revisionNotFoundErr(r int64) error {\n\treturn fmt.Errorf(\"unable to find specified revision %v in history\", r)\n}","line":{"from":489,"to":491}} {"id":100032793,"name":"Len","signature":"func (h historiesByRevision) Len() int { return len(h) }","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollback.go","code":"func (h historiesByRevision) Len() int { return len(h) }","line":{"from":496,"to":496}} {"id":100032794,"name":"Swap","signature":"func (h historiesByRevision) Swap(i, j int) { h[i], h[j] = h[j], h[i] }","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollback.go","code":"func (h historiesByRevision) Swap(i, j int) { h[i], h[j] = h[j], h[i] }","line":{"from":497,"to":497}} {"id":100032795,"name":"Less","signature":"func (h historiesByRevision) Less(i, j int) bool","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollback.go","code":"func (h historiesByRevision) Less(i, j int) bool {\n\treturn h[i].Revision \u003c h[j].Revision\n}","line":{"from":498,"to":500}} {"id":100032796,"name":"rollbacker","signature":"func rollbacker(restClientGetter genericclioptions.RESTClientGetter, mapping *meta.RESTMapping) (Rollbacker, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollbacker.go","code":"// Returns a Rollbacker for changing the rollback version of the specified RESTMapping type or an error\nfunc rollbacker(restClientGetter genericclioptions.RESTClientGetter, mapping *meta.RESTMapping) (Rollbacker, error) {\n\tclientConfig, err := restClientGetter.ToRESTConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\texternal, err := kubernetes.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn RollbackerFor(mapping.GroupVersionKind.GroupKind(), external)\n}","line":{"from":25,"to":37}} {"id":100032797,"name":"StatusViewerFor","signature":"func StatusViewerFor(kind schema.GroupKind) (StatusViewer, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollout_status.go","code":"// StatusViewerFor returns a StatusViewer for the resource specified by kind.\nfunc StatusViewerFor(kind schema.GroupKind) (StatusViewer, error) {\n\tswitch kind {\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"Deployment\").GroupKind(),\n\t\tappsv1.SchemeGroupVersion.WithKind(\"Deployment\").GroupKind():\n\t\treturn \u0026DeploymentStatusViewer{}, nil\n\tcase extensionsv1beta1.SchemeGroupVersion.WithKind(\"DaemonSet\").GroupKind(),\n\t\tappsv1.SchemeGroupVersion.WithKind(\"DaemonSet\").GroupKind():\n\t\treturn \u0026DaemonSetStatusViewer{}, nil\n\tcase appsv1.SchemeGroupVersion.WithKind(\"StatefulSet\").GroupKind():\n\t\treturn \u0026StatefulSetStatusViewer{}, nil\n\t}\n\treturn nil, fmt.Errorf(\"no status viewer has been implemented for %v\", kind)\n}","line":{"from":34,"to":47}} {"id":100032798,"name":"Status","signature":"func (s *DeploymentStatusViewer) Status(obj runtime.Unstructured, revision int64) (string, bool, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollout_status.go","code":"// Status returns a message describing deployment status, and a bool value indicating if the status is considered done.\nfunc (s *DeploymentStatusViewer) Status(obj runtime.Unstructured, revision int64) (string, bool, error) {\n\tdeployment := \u0026appsv1.Deployment{}\n\terr := runtime.DefaultUnstructuredConverter.FromUnstructured(obj.UnstructuredContent(), deployment)\n\tif err != nil {\n\t\treturn \"\", false, fmt.Errorf(\"failed to convert %T to %T: %v\", obj, deployment, err)\n\t}\n\n\tif revision \u003e 0 {\n\t\tdeploymentRev, err := deploymentutil.Revision(deployment)\n\t\tif err != nil {\n\t\t\treturn \"\", false, fmt.Errorf(\"cannot get the revision of deployment %q: %v\", deployment.Name, err)\n\t\t}\n\t\tif revision != deploymentRev {\n\t\t\treturn \"\", false, fmt.Errorf(\"desired revision (%d) is different from the running revision (%d)\", revision, deploymentRev)\n\t\t}\n\t}\n\tif deployment.Generation \u003c= deployment.Status.ObservedGeneration {\n\t\tcond := deploymentutil.GetDeploymentCondition(deployment.Status, appsv1.DeploymentProgressing)\n\t\tif cond != nil \u0026\u0026 cond.Reason == deploymentutil.TimedOutReason {\n\t\t\treturn \"\", false, fmt.Errorf(\"deployment %q exceeded its progress deadline\", deployment.Name)\n\t\t}\n\t\tif deployment.Spec.Replicas != nil \u0026\u0026 deployment.Status.UpdatedReplicas \u003c *deployment.Spec.Replicas {\n\t\t\treturn fmt.Sprintf(\"Waiting for deployment %q rollout to finish: %d out of %d new replicas have been updated...\\n\", deployment.Name, deployment.Status.UpdatedReplicas, *deployment.Spec.Replicas), false, nil\n\t\t}\n\t\tif deployment.Status.Replicas \u003e deployment.Status.UpdatedReplicas {\n\t\t\treturn fmt.Sprintf(\"Waiting for deployment %q rollout to finish: %d old replicas are pending termination...\\n\", deployment.Name, deployment.Status.Replicas-deployment.Status.UpdatedReplicas), false, nil\n\t\t}\n\t\tif deployment.Status.AvailableReplicas \u003c deployment.Status.UpdatedReplicas {\n\t\t\treturn fmt.Sprintf(\"Waiting for deployment %q rollout to finish: %d of %d updated replicas are available...\\n\", deployment.Name, deployment.Status.AvailableReplicas, deployment.Status.UpdatedReplicas), false, nil\n\t\t}\n\t\treturn fmt.Sprintf(\"deployment %q successfully rolled out\\n\", deployment.Name), true, nil\n\t}\n\treturn fmt.Sprintf(\"Waiting for deployment spec update to be observed...\\n\"), false, nil\n}","line":{"from":58,"to":92}} {"id":100032799,"name":"Status","signature":"func (s *DaemonSetStatusViewer) Status(obj runtime.Unstructured, revision int64) (string, bool, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollout_status.go","code":"// Status returns a message describing daemon set status, and a bool value indicating if the status is considered done.\nfunc (s *DaemonSetStatusViewer) Status(obj runtime.Unstructured, revision int64) (string, bool, error) {\n\t//ignoring revision as DaemonSets does not have history yet\n\n\tdaemon := \u0026appsv1.DaemonSet{}\n\terr := runtime.DefaultUnstructuredConverter.FromUnstructured(obj.UnstructuredContent(), daemon)\n\tif err != nil {\n\t\treturn \"\", false, fmt.Errorf(\"failed to convert %T to %T: %v\", obj, daemon, err)\n\t}\n\n\tif daemon.Spec.UpdateStrategy.Type != appsv1.RollingUpdateDaemonSetStrategyType {\n\t\treturn \"\", true, fmt.Errorf(\"rollout status is only available for %s strategy type\", appsv1.RollingUpdateStatefulSetStrategyType)\n\t}\n\tif daemon.Generation \u003c= daemon.Status.ObservedGeneration {\n\t\tif daemon.Status.UpdatedNumberScheduled \u003c daemon.Status.DesiredNumberScheduled {\n\t\t\treturn fmt.Sprintf(\"Waiting for daemon set %q rollout to finish: %d out of %d new pods have been updated...\\n\", daemon.Name, daemon.Status.UpdatedNumberScheduled, daemon.Status.DesiredNumberScheduled), false, nil\n\t\t}\n\t\tif daemon.Status.NumberAvailable \u003c daemon.Status.DesiredNumberScheduled {\n\t\t\treturn fmt.Sprintf(\"Waiting for daemon set %q rollout to finish: %d of %d updated pods are available...\\n\", daemon.Name, daemon.Status.NumberAvailable, daemon.Status.DesiredNumberScheduled), false, nil\n\t\t}\n\t\treturn fmt.Sprintf(\"daemon set %q successfully rolled out\\n\", daemon.Name), true, nil\n\t}\n\treturn fmt.Sprintf(\"Waiting for daemon set spec update to be observed...\\n\"), false, nil\n}","line":{"from":94,"to":117}} {"id":100032800,"name":"Status","signature":"func (s *StatefulSetStatusViewer) Status(obj runtime.Unstructured, revision int64) (string, bool, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/rollout_status.go","code":"// Status returns a message describing statefulset status, and a bool value indicating if the status is considered done.\nfunc (s *StatefulSetStatusViewer) Status(obj runtime.Unstructured, revision int64) (string, bool, error) {\n\tsts := \u0026appsv1.StatefulSet{}\n\terr := runtime.DefaultUnstructuredConverter.FromUnstructured(obj.UnstructuredContent(), sts)\n\tif err != nil {\n\t\treturn \"\", false, fmt.Errorf(\"failed to convert %T to %T: %v\", obj, sts, err)\n\t}\n\n\tif sts.Spec.UpdateStrategy.Type != appsv1.RollingUpdateStatefulSetStrategyType {\n\t\treturn \"\", true, fmt.Errorf(\"rollout status is only available for %s strategy type\", appsv1.RollingUpdateStatefulSetStrategyType)\n\t}\n\tif sts.Status.ObservedGeneration == 0 || sts.Generation \u003e sts.Status.ObservedGeneration {\n\t\treturn \"Waiting for statefulset spec update to be observed...\\n\", false, nil\n\t}\n\tif sts.Spec.Replicas != nil \u0026\u0026 sts.Status.ReadyReplicas \u003c *sts.Spec.Replicas {\n\t\treturn fmt.Sprintf(\"Waiting for %d pods to be ready...\\n\", *sts.Spec.Replicas-sts.Status.ReadyReplicas), false, nil\n\t}\n\tif sts.Spec.UpdateStrategy.Type == appsv1.RollingUpdateStatefulSetStrategyType \u0026\u0026 sts.Spec.UpdateStrategy.RollingUpdate != nil {\n\t\tif sts.Spec.Replicas != nil \u0026\u0026 sts.Spec.UpdateStrategy.RollingUpdate.Partition != nil {\n\t\t\tif sts.Status.UpdatedReplicas \u003c (*sts.Spec.Replicas - *sts.Spec.UpdateStrategy.RollingUpdate.Partition) {\n\t\t\t\treturn fmt.Sprintf(\"Waiting for partitioned roll out to finish: %d out of %d new pods have been updated...\\n\",\n\t\t\t\t\tsts.Status.UpdatedReplicas, *sts.Spec.Replicas-*sts.Spec.UpdateStrategy.RollingUpdate.Partition), false, nil\n\t\t\t}\n\t\t}\n\t\treturn fmt.Sprintf(\"partitioned roll out complete: %d new pods have been updated...\\n\",\n\t\t\tsts.Status.UpdatedReplicas), true, nil\n\t}\n\tif sts.Status.UpdateRevision != sts.Status.CurrentRevision {\n\t\treturn fmt.Sprintf(\"waiting for statefulset rolling update to complete %d pods at revision %s...\\n\",\n\t\t\tsts.Status.UpdatedReplicas, sts.Status.UpdateRevision), false, nil\n\t}\n\treturn fmt.Sprintf(\"statefulset rolling update complete %d pods at revision %s...\\n\", sts.Status.CurrentReplicas, sts.Status.CurrentRevision), true, nil\n\n}","line":{"from":119,"to":152}} {"id":100032801,"name":"statusViewer","signature":"func statusViewer(mapping *meta.RESTMapping) (StatusViewer, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/statusviewer.go","code":"// statusViewer returns a StatusViewer for printing rollout status.\nfunc statusViewer(mapping *meta.RESTMapping) (StatusViewer, error) {\n\treturn StatusViewerFor(mapping.GroupVersionKind.GroupKind())\n}","line":{"from":23,"to":26}} {"id":100032802,"name":"updatePodSpecForObject","signature":"func updatePodSpecForObject(obj runtime.Object, fn func(*v1.PodSpec) error) (bool, error)","file":"staging/src/k8s.io/kubectl/pkg/polymorphichelpers/updatepodspec.go","code":"func updatePodSpecForObject(obj runtime.Object, fn func(*v1.PodSpec) error) (bool, error) {\n\tswitch t := obj.(type) {\n\tcase *v1.Pod:\n\t\treturn true, fn(\u0026t.Spec)\n\t\t// ReplicationController\n\tcase *v1.ReplicationController:\n\t\tif t.Spec.Template == nil {\n\t\t\tt.Spec.Template = \u0026v1.PodTemplateSpec{}\n\t\t}\n\t\treturn true, fn(\u0026t.Spec.Template.Spec)\n\n\t\t// Deployment\n\tcase *extensionsv1beta1.Deployment:\n\t\treturn true, fn(\u0026t.Spec.Template.Spec)\n\tcase *appsv1beta1.Deployment:\n\t\treturn true, fn(\u0026t.Spec.Template.Spec)\n\tcase *appsv1beta2.Deployment:\n\t\treturn true, fn(\u0026t.Spec.Template.Spec)\n\tcase *appsv1.Deployment:\n\t\treturn true, fn(\u0026t.Spec.Template.Spec)\n\n\t\t// DaemonSet\n\tcase *extensionsv1beta1.DaemonSet:\n\t\treturn true, fn(\u0026t.Spec.Template.Spec)\n\tcase *appsv1beta2.DaemonSet:\n\t\treturn true, fn(\u0026t.Spec.Template.Spec)\n\tcase *appsv1.DaemonSet:\n\t\treturn true, fn(\u0026t.Spec.Template.Spec)\n\n\t\t// ReplicaSet\n\tcase *extensionsv1beta1.ReplicaSet:\n\t\treturn true, fn(\u0026t.Spec.Template.Spec)\n\tcase *appsv1beta2.ReplicaSet:\n\t\treturn true, fn(\u0026t.Spec.Template.Spec)\n\tcase *appsv1.ReplicaSet:\n\t\treturn true, fn(\u0026t.Spec.Template.Spec)\n\n\t\t// StatefulSet\n\tcase *appsv1beta1.StatefulSet:\n\t\treturn true, fn(\u0026t.Spec.Template.Spec)\n\tcase *appsv1beta2.StatefulSet:\n\t\treturn true, fn(\u0026t.Spec.Template.Spec)\n\tcase *appsv1.StatefulSet:\n\t\treturn true, fn(\u0026t.Spec.Template.Spec)\n\n\t\t// Job\n\tcase *batchv1.Job:\n\t\treturn true, fn(\u0026t.Spec.Template.Spec)\n\n\t\t// CronJob\n\tcase *batchv1beta1.CronJob:\n\t\treturn true, fn(\u0026t.Spec.JobTemplate.Spec.Template.Spec)\n\tcase *batchv1.CronJob:\n\t\treturn true, fn(\u0026t.Spec.JobTemplate.Spec.Template.Spec)\n\n\tdefault:\n\t\treturn false, fmt.Errorf(\"the object is not a pod or does not have a pod template: %T\", t)\n\t}\n}","line":{"from":32,"to":90}} {"id":100032803,"name":"MakeRegexpArray","signature":"func MakeRegexpArray(str string) ([]*regexp.Regexp, error)","file":"staging/src/k8s.io/kubectl/pkg/proxy/proxy_server.go","code":"// MakeRegexpArray splits a comma separated list of regexps into an array of Regexp objects.\nfunc MakeRegexpArray(str string) ([]*regexp.Regexp, error) {\n\tif str == \"\" {\n\t\treturn []*regexp.Regexp{}, nil\n\t}\n\tparts := strings.Split(str, \",\")\n\tresult := make([]*regexp.Regexp, len(parts))\n\tfor ix := range parts {\n\t\tre, err := regexp.Compile(parts[ix])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult[ix] = re\n\t}\n\treturn result, nil\n}","line":{"from":62,"to":77}} {"id":100032804,"name":"MakeRegexpArrayOrDie","signature":"func MakeRegexpArrayOrDie(str string) []*regexp.Regexp","file":"staging/src/k8s.io/kubectl/pkg/proxy/proxy_server.go","code":"// MakeRegexpArrayOrDie creates an array of regular expression objects from a string or exits.\nfunc MakeRegexpArrayOrDie(str string) []*regexp.Regexp {\n\tresult, err := MakeRegexpArray(str)\n\tif err != nil {\n\t\tklog.Fatalf(\"Error compiling re: %v\", err)\n\t}\n\treturn result\n}","line":{"from":79,"to":86}} {"id":100032805,"name":"matchesRegexp","signature":"func matchesRegexp(str string, regexps []*regexp.Regexp) bool","file":"staging/src/k8s.io/kubectl/pkg/proxy/proxy_server.go","code":"func matchesRegexp(str string, regexps []*regexp.Regexp) bool {\n\tfor _, re := range regexps {\n\t\tif re.MatchString(str) {\n\t\t\tklog.V(6).Infof(\"%v matched %s\", str, re)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":88,"to":96}} {"id":100032806,"name":"accept","signature":"func (f *FilterServer) accept(method, path, host string) bool","file":"staging/src/k8s.io/kubectl/pkg/proxy/proxy_server.go","code":"func (f *FilterServer) accept(method, path, host string) bool {\n\tif matchesRegexp(path, f.RejectPaths) {\n\t\treturn false\n\t}\n\tif matchesRegexp(method, f.RejectMethods) {\n\t\treturn false\n\t}\n\tif matchesRegexp(path, f.AcceptPaths) \u0026\u0026 matchesRegexp(host, f.AcceptHosts) {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":98,"to":109}} {"id":100032807,"name":"HandlerFor","signature":"func (f *FilterServer) HandlerFor(delegate http.Handler) *FilterServer","file":"staging/src/k8s.io/kubectl/pkg/proxy/proxy_server.go","code":"// HandlerFor makes a shallow copy of f which passes its requests along to the\n// new delegate.\nfunc (f *FilterServer) HandlerFor(delegate http.Handler) *FilterServer {\n\tf2 := *f\n\tf2.delegate = delegate\n\treturn \u0026f2\n}","line":{"from":111,"to":117}} {"id":100032808,"name":"extractHost","signature":"func extractHost(header string) (host string)","file":"staging/src/k8s.io/kubectl/pkg/proxy/proxy_server.go","code":"// Get host from a host header value like \"localhost\" or \"localhost:8080\"\nfunc extractHost(header string) (host string) {\n\thost, _, err := net.SplitHostPort(header)\n\tif err != nil {\n\t\thost = header\n\t}\n\treturn host\n}","line":{"from":119,"to":126}} {"id":100032809,"name":"ServeHTTP","signature":"func (f *FilterServer) ServeHTTP(rw http.ResponseWriter, req *http.Request)","file":"staging/src/k8s.io/kubectl/pkg/proxy/proxy_server.go","code":"func (f *FilterServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\thost := extractHost(req.Host)\n\tif f.accept(req.Method, req.URL.Path, host) {\n\t\tklog.V(3).Infof(\"Filter accepting %v %v %v\", req.Method, req.URL.Path, host)\n\t\tf.delegate.ServeHTTP(rw, req)\n\t\treturn\n\t}\n\tklog.V(3).Infof(\"Filter rejecting %v %v %v\", req.Method, req.URL.Path, host)\n\thttp.Error(rw, http.StatusText(http.StatusForbidden), http.StatusForbidden)\n}","line":{"from":128,"to":137}} {"id":100032810,"name":"Error","signature":"func (r *responder) Error(w http.ResponseWriter, req *http.Request, err error)","file":"staging/src/k8s.io/kubectl/pkg/proxy/proxy_server.go","code":"func (r *responder) Error(w http.ResponseWriter, req *http.Request, err error) {\n\tklog.Errorf(\"Error while proxying request: %v\", err)\n\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n}","line":{"from":146,"to":149}} {"id":100032811,"name":"makeUpgradeTransport","signature":"func makeUpgradeTransport(config *rest.Config, keepalive time.Duration) (proxy.UpgradeRequestRoundTripper, error)","file":"staging/src/k8s.io/kubectl/pkg/proxy/proxy_server.go","code":"// makeUpgradeTransport creates a transport that explicitly bypasses HTTP2 support\n// for proxy connections that must upgrade.\nfunc makeUpgradeTransport(config *rest.Config, keepalive time.Duration) (proxy.UpgradeRequestRoundTripper, error) {\n\ttransportConfig, err := config.TransportConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttlsConfig, err := transport.TLSConfigFor(transportConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trt := utilnet.SetOldTransportDefaults(\u0026http.Transport{\n\t\tTLSClientConfig: tlsConfig,\n\t\tDialContext: (\u0026net.Dialer{\n\t\t\tTimeout: 30 * time.Second,\n\t\t\tKeepAlive: keepalive,\n\t\t}).DialContext,\n\t})\n\n\tupgrader, err := transport.HTTPWrappersForConfig(transportConfig, proxy.MirrorRequest)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn proxy.NewUpgradeRequestRoundTripper(rt, upgrader), nil\n}","line":{"from":151,"to":175}} {"id":100032812,"name":"NewServer","signature":"func NewServer(filebase string, apiProxyPrefix string, staticPrefix string, filter *FilterServer, cfg *rest.Config, keepalive time.Duration, appendLocationPath bool) (*Server, error)","file":"staging/src/k8s.io/kubectl/pkg/proxy/proxy_server.go","code":"// NewServer creates and installs a new Server.\n// 'filter', if non-nil, protects requests to the api only.\nfunc NewServer(filebase string, apiProxyPrefix string, staticPrefix string, filter *FilterServer, cfg *rest.Config, keepalive time.Duration, appendLocationPath bool) (*Server, error) {\n\tproxyHandler, err := NewProxyHandler(apiProxyPrefix, filter, cfg, keepalive, appendLocationPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmux := http.NewServeMux()\n\tmux.Handle(apiProxyPrefix, proxyHandler)\n\tif filebase != \"\" {\n\t\t// Require user to explicitly request this behavior rather than\n\t\t// serving their working directory by default.\n\t\tmux.Handle(staticPrefix, newFileHandler(staticPrefix, filebase))\n\t}\n\treturn \u0026Server{handler: mux}, nil\n}","line":{"from":177,"to":192}} {"id":100032813,"name":"NewProxyHandler","signature":"func NewProxyHandler(apiProxyPrefix string, filter *FilterServer, cfg *rest.Config, keepalive time.Duration, appendLocationPath bool) (http.Handler, error)","file":"staging/src/k8s.io/kubectl/pkg/proxy/proxy_server.go","code":"// NewProxyHandler creates an api proxy handler for the cluster\nfunc NewProxyHandler(apiProxyPrefix string, filter *FilterServer, cfg *rest.Config, keepalive time.Duration, appendLocationPath bool) (http.Handler, error) {\n\thost := cfg.Host\n\tif !strings.HasSuffix(host, \"/\") {\n\t\thost = host + \"/\"\n\t}\n\ttarget, err := url.Parse(host)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponder := \u0026responder{}\n\ttransport, err := rest.TransportFor(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tupgradeTransport, err := makeUpgradeTransport(cfg, keepalive)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tproxy := proxy.NewUpgradeAwareHandler(target, transport, false, false, responder)\n\tproxy.UpgradeTransport = upgradeTransport\n\tproxy.UseRequestLocation = true\n\tproxy.UseLocationHost = true\n\tproxy.AppendLocationPath = appendLocationPath\n\n\tproxyServer := http.Handler(proxy)\n\tif filter != nil {\n\t\tproxyServer = filter.HandlerFor(proxyServer)\n\t}\n\n\tif !strings.HasPrefix(apiProxyPrefix, \"/api\") {\n\t\tproxyServer = stripLeaveSlash(apiProxyPrefix, proxyServer)\n\t}\n\treturn proxyServer, nil\n}","line":{"from":194,"to":229}} {"id":100032814,"name":"Listen","signature":"func (s *Server) Listen(address string, port int) (net.Listener, error)","file":"staging/src/k8s.io/kubectl/pkg/proxy/proxy_server.go","code":"// Listen is a simple wrapper around net.Listen.\nfunc (s *Server) Listen(address string, port int) (net.Listener, error) {\n\treturn net.Listen(\"tcp\", fmt.Sprintf(\"%s:%d\", address, port))\n}","line":{"from":231,"to":234}} {"id":100032815,"name":"ListenUnix","signature":"func (s *Server) ListenUnix(path string) (net.Listener, error)","file":"staging/src/k8s.io/kubectl/pkg/proxy/proxy_server.go","code":"// ListenUnix does net.Listen for a unix socket\nfunc (s *Server) ListenUnix(path string) (net.Listener, error) {\n\t// Remove any socket, stale or not, but fall through for other files\n\tfi, err := os.Stat(path)\n\tif err == nil \u0026\u0026 (fi.Mode()\u0026os.ModeSocket) != 0 {\n\t\tos.Remove(path)\n\t}\n\t// Default to only user accessible socket, caller can open up later if desired\n\toldmask, _ := util.Umask(0077)\n\tl, err := net.Listen(\"unix\", path)\n\tutil.Umask(oldmask)\n\treturn l, err\n}","line":{"from":236,"to":248}} {"id":100032816,"name":"ServeOnListener","signature":"func (s *Server) ServeOnListener(l net.Listener) error","file":"staging/src/k8s.io/kubectl/pkg/proxy/proxy_server.go","code":"// ServeOnListener starts the server using given listener, loops forever.\nfunc (s *Server) ServeOnListener(l net.Listener) error {\n\tserver := http.Server{\n\t\tHandler: s.handler,\n\t}\n\treturn server.Serve(l)\n}","line":{"from":250,"to":256}} {"id":100032817,"name":"newFileHandler","signature":"func newFileHandler(prefix, base string) http.Handler","file":"staging/src/k8s.io/kubectl/pkg/proxy/proxy_server.go","code":"func newFileHandler(prefix, base string) http.Handler {\n\treturn http.StripPrefix(prefix, http.FileServer(http.Dir(base)))\n}","line":{"from":258,"to":260}} {"id":100032818,"name":"stripLeaveSlash","signature":"func stripLeaveSlash(prefix string, h http.Handler) http.Handler","file":"staging/src/k8s.io/kubectl/pkg/proxy/proxy_server.go","code":"// like http.StripPrefix, but always leaves an initial slash. (so that our\n// regexps will work.)\nfunc stripLeaveSlash(prefix string, h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tp := strings.TrimPrefix(req.URL.Path, prefix)\n\t\tif len(p) \u003e= len(req.URL.Path) {\n\t\t\thttp.NotFound(w, req)\n\t\t\treturn\n\t\t}\n\t\tif len(p) \u003e 0 \u0026\u0026 p[:1] != \"/\" {\n\t\t\tp = \"/\" + p\n\t\t}\n\t\treq.URL.Path = p\n\t\th.ServeHTTP(w, req)\n\t})\n}","line":{"from":262,"to":277}} {"id":100032819,"name":"RawPost","signature":"func RawPost(restClient *rest.RESTClient, streams genericclioptions.IOStreams, url, filename string) error","file":"staging/src/k8s.io/kubectl/pkg/rawhttp/raw.go","code":"// RawPost uses the REST client to POST content\nfunc RawPost(restClient *rest.RESTClient, streams genericclioptions.IOStreams, url, filename string) error {\n\treturn raw(restClient, streams, url, filename, \"POST\")\n}","line":{"from":30,"to":33}} {"id":100032820,"name":"RawPut","signature":"func RawPut(restClient *rest.RESTClient, streams genericclioptions.IOStreams, url, filename string) error","file":"staging/src/k8s.io/kubectl/pkg/rawhttp/raw.go","code":"// RawPut uses the REST client to PUT content\nfunc RawPut(restClient *rest.RESTClient, streams genericclioptions.IOStreams, url, filename string) error {\n\treturn raw(restClient, streams, url, filename, \"PUT\")\n}","line":{"from":35,"to":38}} {"id":100032821,"name":"RawGet","signature":"func RawGet(restClient *rest.RESTClient, streams genericclioptions.IOStreams, url string) error","file":"staging/src/k8s.io/kubectl/pkg/rawhttp/raw.go","code":"// RawGet uses the REST client to GET content\nfunc RawGet(restClient *rest.RESTClient, streams genericclioptions.IOStreams, url string) error {\n\treturn raw(restClient, streams, url, \"\", \"GET\")\n}","line":{"from":40,"to":43}} {"id":100032822,"name":"RawDelete","signature":"func RawDelete(restClient *rest.RESTClient, streams genericclioptions.IOStreams, url, filename string) error","file":"staging/src/k8s.io/kubectl/pkg/rawhttp/raw.go","code":"// RawDelete uses the REST client to DELETE content\nfunc RawDelete(restClient *rest.RESTClient, streams genericclioptions.IOStreams, url, filename string) error {\n\treturn raw(restClient, streams, url, filename, \"DELETE\")\n}","line":{"from":45,"to":48}} {"id":100032823,"name":"raw","signature":"func raw(restClient *rest.RESTClient, streams genericclioptions.IOStreams, url, filename, requestType string) error","file":"staging/src/k8s.io/kubectl/pkg/rawhttp/raw.go","code":"// raw makes a simple HTTP request to the provided path on the server using the default credentials.\nfunc raw(restClient *rest.RESTClient, streams genericclioptions.IOStreams, url, filename, requestType string) error {\n\tvar data io.Reader\n\tswitch {\n\tcase len(filename) == 0:\n\t\tdata = bytes.NewBuffer([]byte{})\n\n\tcase filename == \"-\":\n\t\tdata = streams.In\n\n\tdefault:\n\t\tf, err := os.Open(filename)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\t\tdata = f\n\t}\n\n\tvar request *rest.Request\n\tswitch requestType {\n\tcase \"GET\":\n\t\trequest = restClient.Get().RequestURI(url)\n\tcase \"PUT\":\n\t\trequest = restClient.Put().RequestURI(url).Body(data)\n\tcase \"POST\":\n\t\trequest = restClient.Post().RequestURI(url).Body(data)\n\tcase \"DELETE\":\n\t\trequest = restClient.Delete().RequestURI(url).Body(data)\n\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown requestType: %q\", requestType)\n\t}\n\n\tstream, err := request.Stream(context.TODO())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stream.Close()\n\n\t_, err = io.Copy(streams.Out, stream)\n\tif err != nil \u0026\u0026 err != io.EOF {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":50,"to":95}} {"id":100032824,"name":"NewScaler","signature":"func NewScaler(scalesGetter scaleclient.ScalesGetter) Scaler","file":"staging/src/k8s.io/kubectl/pkg/scale/scale.go","code":"// NewScaler get a scaler for a given resource\nfunc NewScaler(scalesGetter scaleclient.ScalesGetter) Scaler {\n\treturn \u0026genericScaler{scalesGetter}\n}","line":{"from":47,"to":50}} {"id":100032825,"name":"Error","signature":"func (pe PreconditionError) Error() string","file":"staging/src/k8s.io/kubectl/pkg/scale/scale.go","code":"func (pe PreconditionError) Error() string {\n\treturn fmt.Sprintf(\"Expected %s to be %s, was %s\", pe.Precondition, pe.ExpectedValue, pe.ActualValue)\n}","line":{"from":69,"to":71}} {"id":100032826,"name":"NewRetryParams","signature":"func NewRetryParams(interval, timeout time.Duration) *RetryParams","file":"staging/src/k8s.io/kubectl/pkg/scale/scale.go","code":"func NewRetryParams(interval, timeout time.Duration) *RetryParams {\n\treturn \u0026RetryParams{interval, timeout}\n}","line":{"from":78,"to":80}} {"id":100032827,"name":"ScaleCondition","signature":"func ScaleCondition(r Scaler, precondition *ScalePrecondition, namespace, name string, count uint, updatedResourceVersion *string, gvr schema.GroupVersionResource, dryRun bool) wait.ConditionFunc","file":"staging/src/k8s.io/kubectl/pkg/scale/scale.go","code":"// ScaleCondition is a closure around Scale that facilitates retries via util.wait\nfunc ScaleCondition(r Scaler, precondition *ScalePrecondition, namespace, name string, count uint, updatedResourceVersion *string, gvr schema.GroupVersionResource, dryRun bool) wait.ConditionFunc {\n\treturn func() (bool, error) {\n\t\trv, err := r.ScaleSimple(namespace, name, precondition, count, gvr, dryRun)\n\t\tif updatedResourceVersion != nil {\n\t\t\t*updatedResourceVersion = rv\n\t\t}\n\t\t// Retry only on update conflicts.\n\t\tif errors.IsConflict(err) {\n\t\t\treturn false, nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\treturn true, nil\n\t}\n}","line":{"from":82,"to":98}} {"id":100032828,"name":"validate","signature":"func (precondition *ScalePrecondition) validate(scale *autoscalingv1.Scale) error","file":"staging/src/k8s.io/kubectl/pkg/scale/scale.go","code":"// validateGeneric ensures that the preconditions match. Returns nil if they are valid, otherwise an error\nfunc (precondition *ScalePrecondition) validate(scale *autoscalingv1.Scale) error {\n\tif precondition.Size != -1 \u0026\u0026 int(scale.Spec.Replicas) != precondition.Size {\n\t\treturn PreconditionError{\"replicas\", strconv.Itoa(precondition.Size), strconv.Itoa(int(scale.Spec.Replicas))}\n\t}\n\tif len(precondition.ResourceVersion) \u003e 0 \u0026\u0026 scale.ResourceVersion != precondition.ResourceVersion {\n\t\treturn PreconditionError{\"resource version\", precondition.ResourceVersion, scale.ResourceVersion}\n\t}\n\treturn nil\n}","line":{"from":100,"to":109}} {"id":100032829,"name":"ScaleSimple","signature":"func (s *genericScaler) ScaleSimple(namespace, name string, preconditions *ScalePrecondition, newSize uint, gvr schema.GroupVersionResource, dryRun bool) (updatedResourceVersion string, err error)","file":"staging/src/k8s.io/kubectl/pkg/scale/scale.go","code":"// ScaleSimple updates a scale of a given resource. It returns the resourceVersion of the scale if the update was successful.\nfunc (s *genericScaler) ScaleSimple(namespace, name string, preconditions *ScalePrecondition, newSize uint, gvr schema.GroupVersionResource, dryRun bool) (updatedResourceVersion string, err error) {\n\tif preconditions != nil {\n\t\tscale, err := s.scaleNamespacer.Scales(namespace).Get(context.TODO(), gvr.GroupResource(), name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif err = preconditions.validate(scale); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tscale.Spec.Replicas = int32(newSize)\n\t\tupdateOptions := metav1.UpdateOptions{}\n\t\tif dryRun {\n\t\t\tupdateOptions.DryRun = []string{metav1.DryRunAll}\n\t\t}\n\t\tupdatedScale, err := s.scaleNamespacer.Scales(namespace).Update(context.TODO(), gvr.GroupResource(), scale, updateOptions)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn updatedScale.ResourceVersion, nil\n\t}\n\n\t// objectForReplicas is used for encoding scale patch\n\ttype objectForReplicas struct {\n\t\tReplicas uint `json:\"replicas\"`\n\t}\n\t// objectForSpec is used for encoding scale patch\n\ttype objectForSpec struct {\n\t\tSpec objectForReplicas `json:\"spec\"`\n\t}\n\tspec := objectForSpec{\n\t\tSpec: objectForReplicas{Replicas: newSize},\n\t}\n\tpatch, err := json.Marshal(\u0026spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tpatchOptions := metav1.PatchOptions{}\n\tif dryRun {\n\t\tpatchOptions.DryRun = []string{metav1.DryRunAll}\n\t}\n\tupdatedScale, err := s.scaleNamespacer.Scales(namespace).Patch(context.TODO(), gvr, name, types.MergePatchType, patch, patchOptions)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn updatedScale.ResourceVersion, nil\n}","line":{"from":118,"to":164}} {"id":100032830,"name":"Scale","signature":"func (s *genericScaler) Scale(namespace, resourceName string, newSize uint, preconditions *ScalePrecondition, retry, waitForReplicas *RetryParams, gvr schema.GroupVersionResource, dryRun bool) error","file":"staging/src/k8s.io/kubectl/pkg/scale/scale.go","code":"// Scale updates a scale of a given resource to a new size, with optional precondition check (if preconditions is not nil),\n// optional retries (if retry is not nil), and then optionally waits for the status to reach desired count.\nfunc (s *genericScaler) Scale(namespace, resourceName string, newSize uint, preconditions *ScalePrecondition, retry, waitForReplicas *RetryParams, gvr schema.GroupVersionResource, dryRun bool) error {\n\tif retry == nil {\n\t\t// make it try only once, immediately\n\t\tretry = \u0026RetryParams{Interval: time.Millisecond, Timeout: time.Millisecond}\n\t}\n\tcond := ScaleCondition(s, preconditions, namespace, resourceName, newSize, nil, gvr, dryRun)\n\tif err := wait.PollImmediate(retry.Interval, retry.Timeout, cond); err != nil {\n\t\treturn err\n\t}\n\tif waitForReplicas != nil {\n\t\treturn WaitForScaleHasDesiredReplicas(s.scaleNamespacer, gvr.GroupResource(), resourceName, namespace, newSize, waitForReplicas)\n\t}\n\treturn nil\n}","line":{"from":166,"to":181}} {"id":100032831,"name":"scaleHasDesiredReplicas","signature":"func scaleHasDesiredReplicas(sClient scaleclient.ScalesGetter, gr schema.GroupResource, resourceName string, namespace string, desiredReplicas int32) wait.ConditionFunc","file":"staging/src/k8s.io/kubectl/pkg/scale/scale.go","code":"// scaleHasDesiredReplicas returns a condition that will be true if and only if the desired replica\n// count for a scale (Spec) equals its updated replicas count (Status)\nfunc scaleHasDesiredReplicas(sClient scaleclient.ScalesGetter, gr schema.GroupResource, resourceName string, namespace string, desiredReplicas int32) wait.ConditionFunc {\n\treturn func() (bool, error) {\n\t\tactualScale, err := sClient.Scales(namespace).Get(context.TODO(), gr, resourceName, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\t// this means the desired scale target has been reset by something else\n\t\tif actualScale.Spec.Replicas != desiredReplicas {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn actualScale.Spec.Replicas == actualScale.Status.Replicas \u0026\u0026\n\t\t\tdesiredReplicas == actualScale.Status.Replicas, nil\n\t}\n}","line":{"from":183,"to":198}} {"id":100032832,"name":"WaitForScaleHasDesiredReplicas","signature":"func WaitForScaleHasDesiredReplicas(sClient scaleclient.ScalesGetter, gr schema.GroupResource, resourceName string, namespace string, newSize uint, waitForReplicas *RetryParams) error","file":"staging/src/k8s.io/kubectl/pkg/scale/scale.go","code":"// WaitForScaleHasDesiredReplicas waits until condition scaleHasDesiredReplicas is satisfied\n// or returns error when timeout happens\nfunc WaitForScaleHasDesiredReplicas(sClient scaleclient.ScalesGetter, gr schema.GroupResource, resourceName string, namespace string, newSize uint, waitForReplicas *RetryParams) error {\n\tif waitForReplicas == nil {\n\t\treturn fmt.Errorf(\"waitForReplicas parameter cannot be nil\")\n\t}\n\terr := wait.PollImmediate(\n\t\twaitForReplicas.Interval,\n\t\twaitForReplicas.Timeout,\n\t\tscaleHasDesiredReplicas(sClient, gr, resourceName, namespace, int32(newSize)))\n\tif err == wait.ErrWaitTimeout {\n\t\treturn fmt.Errorf(\"timed out waiting for %q to be synced\", resourceName)\n\t}\n\treturn err\n}","line":{"from":200,"to":214}} {"id":100032833,"name":"init","signature":"func init()","file":"staging/src/k8s.io/kubectl/pkg/scheme/install.go","code":"// Register all groups in the kubectl's registry, but no componentconfig group since it's not in k8s.io/api\n// The code in this file mostly duplicate the install under k8s.io/kubernetes/pkg/api and k8s.io/kubernetes/pkg/apis,\n// but does NOT register the internal types.\nfunc init() {\n\t// Register external types for Scheme\n\tmetav1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: \"v1\"})\n\tutilruntime.Must(metav1beta1.AddMetaToScheme(Scheme))\n\tutilruntime.Must(metav1.AddMetaToScheme(Scheme))\n\tutilruntime.Must(scheme.AddToScheme(Scheme))\n\n\tutilruntime.Must(Scheme.SetVersionPriority(corev1.SchemeGroupVersion))\n\tutilruntime.Must(Scheme.SetVersionPriority(admissionv1beta1.SchemeGroupVersion, admissionv1.SchemeGroupVersion))\n\tutilruntime.Must(Scheme.SetVersionPriority(admissionregistrationv1beta1.SchemeGroupVersion, admissionregistrationv1.SchemeGroupVersion))\n\tutilruntime.Must(Scheme.SetVersionPriority(appsv1beta1.SchemeGroupVersion, appsv1beta2.SchemeGroupVersion, appsv1.SchemeGroupVersion))\n\tutilruntime.Must(Scheme.SetVersionPriority(authenticationv1.SchemeGroupVersion, authenticationv1beta1.SchemeGroupVersion))\n\tutilruntime.Must(Scheme.SetVersionPriority(authorizationv1.SchemeGroupVersion, authorizationv1beta1.SchemeGroupVersion))\n\tutilruntime.Must(Scheme.SetVersionPriority(autoscalingv1.SchemeGroupVersion, autoscalingv2.SchemeGroupVersion))\n\tutilruntime.Must(Scheme.SetVersionPriority(batchv1.SchemeGroupVersion, batchv1beta1.SchemeGroupVersion))\n\tutilruntime.Must(Scheme.SetVersionPriority(certificatesv1.SchemeGroupVersion, certificatesv1beta1.SchemeGroupVersion))\n\tutilruntime.Must(Scheme.SetVersionPriority(extensionsv1beta1.SchemeGroupVersion))\n\tutilruntime.Must(Scheme.SetVersionPriority(imagepolicyv1alpha1.SchemeGroupVersion))\n\tutilruntime.Must(Scheme.SetVersionPriority(networkingv1.SchemeGroupVersion))\n\tutilruntime.Must(Scheme.SetVersionPriority(policyv1beta1.SchemeGroupVersion, policyv1.SchemeGroupVersion))\n\tutilruntime.Must(Scheme.SetVersionPriority(rbacv1.SchemeGroupVersion, rbacv1beta1.SchemeGroupVersion, rbacv1alpha1.SchemeGroupVersion))\n\tutilruntime.Must(Scheme.SetVersionPriority(schedulingv1alpha1.SchemeGroupVersion))\n\tutilruntime.Must(Scheme.SetVersionPriority(storagev1.SchemeGroupVersion, storagev1beta1.SchemeGroupVersion))\n}","line":{"from":56,"to":82}} {"id":100032834,"name":"DefaultJSONEncoder","signature":"func DefaultJSONEncoder() runtime.Encoder","file":"staging/src/k8s.io/kubectl/pkg/scheme/scheme.go","code":"// DefaultJSONEncoder returns a default encoder for our scheme\nfunc DefaultJSONEncoder() runtime.Encoder {\n\treturn unstructured.NewJSONFallbackEncoder(Codecs.LegacyCodec(Scheme.PrioritizedVersionsAllGroups()...))\n}","line":{"from":36,"to":39}} {"id":100032835,"name":"GetOriginalConfiguration","signature":"func GetOriginalConfiguration(obj runtime.Object) ([]byte, error)","file":"staging/src/k8s.io/kubectl/pkg/util/apply.go","code":"// GetOriginalConfiguration retrieves the original configuration of the object\n// from the annotation, or nil if no annotation was found.\nfunc GetOriginalConfiguration(obj runtime.Object) ([]byte, error) {\n\tannots, err := metadataAccessor.Annotations(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif annots == nil {\n\t\treturn nil, nil\n\t}\n\n\toriginal, ok := annots[v1.LastAppliedConfigAnnotation]\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\n\treturn []byte(original), nil\n}","line":{"from":27,"to":45}} {"id":100032836,"name":"setOriginalConfiguration","signature":"func setOriginalConfiguration(obj runtime.Object, original []byte) error","file":"staging/src/k8s.io/kubectl/pkg/util/apply.go","code":"// SetOriginalConfiguration sets the original configuration of the object\n// as the annotation on the object for later use in computing a three way patch.\nfunc setOriginalConfiguration(obj runtime.Object, original []byte) error {\n\tif len(original) \u003c 1 {\n\t\treturn nil\n\t}\n\n\tannots, err := metadataAccessor.Annotations(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif annots == nil {\n\t\tannots = map[string]string{}\n\t}\n\n\tannots[v1.LastAppliedConfigAnnotation] = string(original)\n\treturn metadataAccessor.SetAnnotations(obj, annots)\n}","line":{"from":47,"to":65}} {"id":100032837,"name":"GetModifiedConfiguration","signature":"func GetModifiedConfiguration(obj runtime.Object, annotate bool, codec runtime.Encoder) ([]byte, error)","file":"staging/src/k8s.io/kubectl/pkg/util/apply.go","code":"// GetModifiedConfiguration retrieves the modified configuration of the object.\n// If annotate is true, it embeds the result as an annotation in the modified\n// configuration. If an object was read from the command input, it will use that\n// version of the object. Otherwise, it will use the version from the server.\nfunc GetModifiedConfiguration(obj runtime.Object, annotate bool, codec runtime.Encoder) ([]byte, error) {\n\t// First serialize the object without the annotation to prevent recursion,\n\t// then add that serialization to it as the annotation and serialize it again.\n\tvar modified []byte\n\n\t// Otherwise, use the server side version of the object.\n\t// Get the current annotations from the object.\n\tannots, err := metadataAccessor.Annotations(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif annots == nil {\n\t\tannots = map[string]string{}\n\t}\n\n\toriginal := annots[v1.LastAppliedConfigAnnotation]\n\tdelete(annots, v1.LastAppliedConfigAnnotation)\n\tif err := metadataAccessor.SetAnnotations(obj, annots); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmodified, err = runtime.Encode(codec, obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif annotate {\n\t\tannots[v1.LastAppliedConfigAnnotation] = string(modified)\n\t\tif err := metadataAccessor.SetAnnotations(obj, annots); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tmodified, err = runtime.Encode(codec, obj)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Restore the object to its original condition.\n\tannots[v1.LastAppliedConfigAnnotation] = original\n\tif err := metadataAccessor.SetAnnotations(obj, annots); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn modified, nil\n}","line":{"from":67,"to":117}} {"id":100032838,"name":"updateApplyAnnotation","signature":"func updateApplyAnnotation(obj runtime.Object, codec runtime.Encoder) error","file":"staging/src/k8s.io/kubectl/pkg/util/apply.go","code":"// updateApplyAnnotation calls CreateApplyAnnotation if the last applied\n// configuration annotation is already present. Otherwise, it does nothing.\nfunc updateApplyAnnotation(obj runtime.Object, codec runtime.Encoder) error {\n\tif original, err := GetOriginalConfiguration(obj); err != nil || len(original) \u003c= 0 {\n\t\treturn err\n\t}\n\treturn CreateApplyAnnotation(obj, codec)\n}","line":{"from":119,"to":126}} {"id":100032839,"name":"CreateApplyAnnotation","signature":"func CreateApplyAnnotation(obj runtime.Object, codec runtime.Encoder) error","file":"staging/src/k8s.io/kubectl/pkg/util/apply.go","code":"// CreateApplyAnnotation gets the modified configuration of the object,\n// without embedding it again, and then sets it on the object as the annotation.\nfunc CreateApplyAnnotation(obj runtime.Object, codec runtime.Encoder) error {\n\tmodified, err := GetModifiedConfiguration(obj, false, codec)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn setOriginalConfiguration(obj, modified)\n}","line":{"from":128,"to":136}} {"id":100032840,"name":"CreateOrUpdateAnnotation","signature":"func CreateOrUpdateAnnotation(createAnnotation bool, obj runtime.Object, codec runtime.Encoder) error","file":"staging/src/k8s.io/kubectl/pkg/util/apply.go","code":"// CreateOrUpdateAnnotation creates the annotation used by\n// kubectl apply only when createAnnotation is true\n// Otherwise, only update the annotation when it already exists\nfunc CreateOrUpdateAnnotation(createAnnotation bool, obj runtime.Object, codec runtime.Encoder) error {\n\tif createAnnotation {\n\t\treturn CreateApplyAnnotation(obj, codec)\n\t}\n\treturn updateApplyAnnotation(obj, codec)\n}","line":{"from":138,"to":146}} {"id":100032841,"name":"ParseCSR","signature":"func ParseCSR(pemBytes []byte) (*x509.CertificateRequest, error)","file":"staging/src/k8s.io/kubectl/pkg/util/certificate/certificate.go","code":"// ParseCSR extracts the CSR from the API object and decodes it.\nfunc ParseCSR(pemBytes []byte) (*x509.CertificateRequest, error) {\n\tblock, _ := pem.Decode(pemBytes)\n\tif block == nil || block.Type != \"CERTIFICATE REQUEST\" {\n\t\treturn nil, errors.New(\"PEM block type must be CERTIFICATE REQUEST\")\n\t}\n\tcsr, err := x509.ParseCertificateRequest(block.Bytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn csr, nil\n}","line":{"from":27,"to":38}} {"id":100032842,"name":"SetFactoryForCompletion","signature":"func SetFactoryForCompletion(f cmdutil.Factory)","file":"staging/src/k8s.io/kubectl/pkg/util/completion/completion.go","code":"// SetFactoryForCompletion Store the factory which is needed by the completion functions.\n// Not all commands have access to the factory, so cannot pass it to the completion functions.\nfunc SetFactoryForCompletion(f cmdutil.Factory) {\n\tfactory = f\n}","line":{"from":41,"to":45}} {"id":100032843,"name":"ResourceTypeAndNameCompletionFunc","signature":"func ResourceTypeAndNameCompletionFunc(f cmdutil.Factory) func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective)","file":"staging/src/k8s.io/kubectl/pkg/util/completion/completion.go","code":"// ResourceTypeAndNameCompletionFunc Returns a completion function that completes resource types\n// and resource names that match the toComplete prefix. It supports the \u003ctype\u003e/\u003cname\u003e form.\nfunc ResourceTypeAndNameCompletionFunc(f cmdutil.Factory) func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {\n\treturn resourceTypeAndNameCompletionFunc(f, nil, true)\n}","line":{"from":47,"to":51}} {"id":100032844,"name":"SpecifiedResourceTypeAndNameCompletionFunc","signature":"func SpecifiedResourceTypeAndNameCompletionFunc(f cmdutil.Factory, allowedTypes []string) func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective)","file":"staging/src/k8s.io/kubectl/pkg/util/completion/completion.go","code":"// SpecifiedResourceTypeAndNameCompletionFunc Returns a completion function that completes resource\n// types limited to the specified allowedTypes, and resource names that match the toComplete prefix.\n// It allows for multiple resources. It supports the \u003ctype\u003e/\u003cname\u003e form.\nfunc SpecifiedResourceTypeAndNameCompletionFunc(f cmdutil.Factory, allowedTypes []string) func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {\n\treturn resourceTypeAndNameCompletionFunc(f, allowedTypes, true)\n}","line":{"from":53,"to":58}} {"id":100032845,"name":"SpecifiedResourceTypeAndNameNoRepeatCompletionFunc","signature":"func SpecifiedResourceTypeAndNameNoRepeatCompletionFunc(f cmdutil.Factory, allowedTypes []string) func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective)","file":"staging/src/k8s.io/kubectl/pkg/util/completion/completion.go","code":"// SpecifiedResourceTypeAndNameNoRepeatCompletionFunc Returns a completion function that completes resource\n// types limited to the specified allowedTypes, and resource names that match the toComplete prefix.\n// It only allows for one resource. It supports the \u003ctype\u003e/\u003cname\u003e form.\nfunc SpecifiedResourceTypeAndNameNoRepeatCompletionFunc(f cmdutil.Factory, allowedTypes []string) func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {\n\treturn resourceTypeAndNameCompletionFunc(f, allowedTypes, false)\n}","line":{"from":60,"to":65}} {"id":100032846,"name":"ResourceNameCompletionFunc","signature":"func ResourceNameCompletionFunc(f cmdutil.Factory, resourceType string) func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective)","file":"staging/src/k8s.io/kubectl/pkg/util/completion/completion.go","code":"// ResourceNameCompletionFunc Returns a completion function that completes as a first argument\n// the resource names specified by the resourceType parameter, and which match the toComplete prefix.\n// This function does NOT support the \u003ctype\u003e/\u003cname\u003e form: it is meant to be used by commands\n// that don't support that form. For commands that apply to pods and that support the \u003ctype\u003e/\u003cname\u003e\n// form, please use PodResourceNameCompletionFunc()\nfunc ResourceNameCompletionFunc(f cmdutil.Factory, resourceType string) func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {\n\treturn func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\t\tvar comps []string\n\t\tif len(args) == 0 {\n\t\t\tcomps = CompGetResource(f, resourceType, toComplete)\n\t\t}\n\t\treturn comps, cobra.ShellCompDirectiveNoFileComp\n\t}\n}","line":{"from":67,"to":80}} {"id":100032847,"name":"PodResourceNameCompletionFunc","signature":"func PodResourceNameCompletionFunc(f cmdutil.Factory) func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective)","file":"staging/src/k8s.io/kubectl/pkg/util/completion/completion.go","code":"// PodResourceNameCompletionFunc Returns a completion function that completes:\n// 1- pod names that match the toComplete prefix\n// 2- resource types containing pods which match the toComplete prefix\nfunc PodResourceNameCompletionFunc(f cmdutil.Factory) func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {\n\treturn func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\t\tvar comps []string\n\t\tdirective := cobra.ShellCompDirectiveNoFileComp\n\t\tif len(args) == 0 {\n\t\t\tcomps, directive = doPodResourceCompletion(f, toComplete)\n\t\t}\n\t\treturn comps, directive\n\t}\n}","line":{"from":82,"to":94}} {"id":100032848,"name":"PodResourceNameAndContainerCompletionFunc","signature":"func PodResourceNameAndContainerCompletionFunc(f cmdutil.Factory) func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective)","file":"staging/src/k8s.io/kubectl/pkg/util/completion/completion.go","code":"// PodResourceNameAndContainerCompletionFunc Returns a completion function that completes, as a first argument:\n// 1- pod names that match the toComplete prefix\n// 2- resource types containing pods which match the toComplete prefix\n// and as a second argument the containers within the specified pod.\nfunc PodResourceNameAndContainerCompletionFunc(f cmdutil.Factory) func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {\n\treturn func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\t\tvar comps []string\n\t\tdirective := cobra.ShellCompDirectiveNoFileComp\n\t\tif len(args) == 0 {\n\t\t\tcomps, directive = doPodResourceCompletion(f, toComplete)\n\t\t} else if len(args) == 1 {\n\t\t\tpodName := convertResourceNameToPodName(f, args[0])\n\t\t\tcomps = CompGetContainers(f, podName, toComplete)\n\t\t}\n\t\treturn comps, directive\n\t}\n}","line":{"from":96,"to":112}} {"id":100032849,"name":"ContainerCompletionFunc","signature":"func ContainerCompletionFunc(f cmdutil.Factory) func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective)","file":"staging/src/k8s.io/kubectl/pkg/util/completion/completion.go","code":"// ContainerCompletionFunc Returns a completion function that completes the containers within the\n// pod specified by the first argument. The resource containing the pod can be specified in\n// the \u003ctype\u003e/\u003cname\u003e form.\nfunc ContainerCompletionFunc(f cmdutil.Factory) func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {\n\treturn func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\t\tvar comps []string\n\t\t// We need the pod name to be able to complete the container names, it must be in args[0].\n\t\t// That first argument can also be of the form \u003ctype\u003e/\u003cname\u003e so we need to convert it.\n\t\tif len(args) \u003e 0 {\n\t\t\tpodName := convertResourceNameToPodName(f, args[0])\n\t\t\tcomps = CompGetContainers(f, podName, toComplete)\n\t\t}\n\t\treturn comps, cobra.ShellCompDirectiveNoFileComp\n\t}\n}","line":{"from":114,"to":128}} {"id":100032850,"name":"ContextCompletionFunc","signature":"func ContextCompletionFunc(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)","file":"staging/src/k8s.io/kubectl/pkg/util/completion/completion.go","code":"// ContextCompletionFunc is a completion function that completes as a first argument the\n// context names that match the toComplete prefix\nfunc ContextCompletionFunc(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\tif len(args) == 0 {\n\t\treturn ListContextsInConfig(toComplete), cobra.ShellCompDirectiveNoFileComp\n\t}\n\treturn nil, cobra.ShellCompDirectiveNoFileComp\n}","line":{"from":130,"to":137}} {"id":100032851,"name":"ClusterCompletionFunc","signature":"func ClusterCompletionFunc(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)","file":"staging/src/k8s.io/kubectl/pkg/util/completion/completion.go","code":"// ClusterCompletionFunc is a completion function that completes as a first argument the\n// cluster names that match the toComplete prefix\nfunc ClusterCompletionFunc(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\tif len(args) == 0 {\n\t\treturn ListClustersInConfig(toComplete), cobra.ShellCompDirectiveNoFileComp\n\t}\n\treturn nil, cobra.ShellCompDirectiveNoFileComp\n}","line":{"from":139,"to":146}} {"id":100032852,"name":"UserCompletionFunc","signature":"func UserCompletionFunc(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)","file":"staging/src/k8s.io/kubectl/pkg/util/completion/completion.go","code":"// UserCompletionFunc is a completion function that completes as a first argument the\n// user names that match the toComplete prefix\nfunc UserCompletionFunc(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\tif len(args) == 0 {\n\t\treturn ListUsersInConfig(toComplete), cobra.ShellCompDirectiveNoFileComp\n\t}\n\treturn nil, cobra.ShellCompDirectiveNoFileComp\n}","line":{"from":148,"to":155}} {"id":100032853,"name":"CompGetResource","signature":"func CompGetResource(f cmdutil.Factory, resourceName string, toComplete string) []string","file":"staging/src/k8s.io/kubectl/pkg/util/completion/completion.go","code":"// CompGetResource gets the list of the resource specified which begin with `toComplete`.\nfunc CompGetResource(f cmdutil.Factory, resourceName string, toComplete string) []string {\n\ttemplate := \"{{ range .items }}{{ .metadata.name }} {{ end }}\"\n\treturn CompGetFromTemplate(\u0026template, f, \"\", []string{resourceName}, toComplete)\n}","line":{"from":157,"to":161}} {"id":100032854,"name":"CompGetContainers","signature":"func CompGetContainers(f cmdutil.Factory, podName string, toComplete string) []string","file":"staging/src/k8s.io/kubectl/pkg/util/completion/completion.go","code":"// CompGetContainers gets the list of containers of the specified pod which begin with `toComplete`.\nfunc CompGetContainers(f cmdutil.Factory, podName string, toComplete string) []string {\n\ttemplate := \"{{ range .spec.initContainers }}{{ .name }} {{end}}{{ range .spec.containers }}{{ .name }} {{ end }}\"\n\treturn CompGetFromTemplate(\u0026template, f, \"\", []string{\"pod\", podName}, toComplete)\n}","line":{"from":163,"to":167}} {"id":100032855,"name":"CompGetFromTemplate","signature":"func CompGetFromTemplate(template *string, f cmdutil.Factory, namespace string, args []string, toComplete string) []string","file":"staging/src/k8s.io/kubectl/pkg/util/completion/completion.go","code":"// CompGetFromTemplate executes a Get operation using the specified template and args and returns the results\n// which begin with `toComplete`.\nfunc CompGetFromTemplate(template *string, f cmdutil.Factory, namespace string, args []string, toComplete string) []string {\n\tbuf := new(bytes.Buffer)\n\tstreams := genericclioptions.IOStreams{In: os.Stdin, Out: buf, ErrOut: io.Discard}\n\to := get.NewGetOptions(\"kubectl\", streams)\n\n\t// Get the list of names of the specified resource\n\to.PrintFlags.TemplateFlags.GoTemplatePrintFlags.TemplateArgument = template\n\tformat := \"go-template\"\n\to.PrintFlags.OutputFormat = \u0026format\n\n\t// Do the steps Complete() would have done.\n\t// We cannot actually call Complete() or Validate() as these function check for\n\t// the presence of flags, which, in our case won't be there\n\tif namespace != \"\" {\n\t\to.Namespace = namespace\n\t\to.ExplicitNamespace = true\n\t} else {\n\t\tvar err error\n\t\to.Namespace, o.ExplicitNamespace, err = f.ToRawKubeConfigLoader().Namespace()\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\to.ToPrinter = func(mapping *meta.RESTMapping, outputObjects *bool, withNamespace bool, withKind bool) (printers.ResourcePrinterFunc, error) {\n\t\tprinter, err := o.PrintFlags.ToPrinter()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn printer.PrintObj, nil\n\t}\n\n\to.Run(f, args)\n\n\tvar comps []string\n\tresources := strings.Split(buf.String(), \" \")\n\tfor _, res := range resources {\n\t\tif res != \"\" \u0026\u0026 strings.HasPrefix(res, toComplete) {\n\t\t\tcomps = append(comps, res)\n\t\t}\n\t}\n\treturn comps\n}","line":{"from":169,"to":213}} {"id":100032856,"name":"ListContextsInConfig","signature":"func ListContextsInConfig(toComplete string) []string","file":"staging/src/k8s.io/kubectl/pkg/util/completion/completion.go","code":"// ListContextsInConfig returns a list of context names which begin with `toComplete`\nfunc ListContextsInConfig(toComplete string) []string {\n\tconfig, err := factory.ToRawKubeConfigLoader().RawConfig()\n\tif err != nil {\n\t\treturn nil\n\t}\n\tvar ret []string\n\tfor name := range config.Contexts {\n\t\tif strings.HasPrefix(name, toComplete) {\n\t\t\tret = append(ret, name)\n\t\t}\n\t}\n\treturn ret\n}","line":{"from":215,"to":228}} {"id":100032857,"name":"ListClustersInConfig","signature":"func ListClustersInConfig(toComplete string) []string","file":"staging/src/k8s.io/kubectl/pkg/util/completion/completion.go","code":"// ListClustersInConfig returns a list of cluster names which begin with `toComplete`\nfunc ListClustersInConfig(toComplete string) []string {\n\tconfig, err := factory.ToRawKubeConfigLoader().RawConfig()\n\tif err != nil {\n\t\treturn nil\n\t}\n\tvar ret []string\n\tfor name := range config.Clusters {\n\t\tif strings.HasPrefix(name, toComplete) {\n\t\t\tret = append(ret, name)\n\t\t}\n\t}\n\treturn ret\n}","line":{"from":230,"to":243}} {"id":100032858,"name":"ListUsersInConfig","signature":"func ListUsersInConfig(toComplete string) []string","file":"staging/src/k8s.io/kubectl/pkg/util/completion/completion.go","code":"// ListUsersInConfig returns a list of user names which begin with `toComplete`\nfunc ListUsersInConfig(toComplete string) []string {\n\tconfig, err := factory.ToRawKubeConfigLoader().RawConfig()\n\tif err != nil {\n\t\treturn nil\n\t}\n\tvar ret []string\n\tfor name := range config.AuthInfos {\n\t\tif strings.HasPrefix(name, toComplete) {\n\t\t\tret = append(ret, name)\n\t\t}\n\t}\n\treturn ret\n}","line":{"from":245,"to":258}} {"id":100032859,"name":"compGetResourceList","signature":"func compGetResourceList(restClientGetter genericclioptions.RESTClientGetter, cmd *cobra.Command, toComplete string) []string","file":"staging/src/k8s.io/kubectl/pkg/util/completion/completion.go","code":"// compGetResourceList returns the list of api resources which begin with `toComplete`.\nfunc compGetResourceList(restClientGetter genericclioptions.RESTClientGetter, cmd *cobra.Command, toComplete string) []string {\n\tbuf := new(bytes.Buffer)\n\tstreams := genericclioptions.IOStreams{In: os.Stdin, Out: buf, ErrOut: io.Discard}\n\to := apiresources.NewAPIResourceOptions(streams)\n\n\to.Complete(restClientGetter, cmd, nil)\n\n\t// Get the list of resources\n\to.Output = \"name\"\n\to.Cached = true\n\to.Verbs = []string{\"get\"}\n\t// TODO:Should set --request-timeout=5s\n\n\t// Ignore errors as the output may still be valid\n\to.RunAPIResources()\n\n\t// Resources can be a comma-separated list. The last element is then\n\t// the one we should complete. For example if toComplete==\"pods,secre\"\n\t// we should return \"pods,secrets\"\n\tprefix := \"\"\n\tsuffix := toComplete\n\tlastIdx := strings.LastIndex(toComplete, \",\")\n\tif lastIdx != -1 {\n\t\tprefix = toComplete[0 : lastIdx+1]\n\t\tsuffix = toComplete[lastIdx+1:]\n\t}\n\tvar comps []string\n\tresources := strings.Split(buf.String(), \"\\n\")\n\tfor _, res := range resources {\n\t\tif res != \"\" \u0026\u0026 strings.HasPrefix(res, suffix) {\n\t\t\tcomps = append(comps, fmt.Sprintf(\"%s%s\", prefix, res))\n\t\t}\n\t}\n\treturn comps\n}","line":{"from":260,"to":295}} {"id":100032860,"name":"resourceTypeAndNameCompletionFunc","signature":"func resourceTypeAndNameCompletionFunc(f cmdutil.Factory, allowedTypes []string, allowRepeat bool) func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective)","file":"staging/src/k8s.io/kubectl/pkg/util/completion/completion.go","code":"// resourceTypeAndNameCompletionFunc Returns a completion function that completes resource types\n// and resource names that match the toComplete prefix. It supports the \u003ctype\u003e/\u003cname\u003e form.\nfunc resourceTypeAndNameCompletionFunc(f cmdutil.Factory, allowedTypes []string, allowRepeat bool) func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {\n\treturn func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\t\tvar comps []string\n\t\tdirective := cobra.ShellCompDirectiveNoFileComp\n\n\t\tif len(args) \u003e 0 \u0026\u0026 !strings.Contains(args[0], \"/\") {\n\t\t\t// The first argument is of the form \u003ctype\u003e (e.g., pods)\n\t\t\t// All following arguments should be a resource name.\n\t\t\tif allowRepeat || len(args) == 1 {\n\t\t\t\tcomps = CompGetResource(f, args[0], toComplete)\n\n\t\t\t\t// Remove choices already on the command-line\n\t\t\t\tif len(args) \u003e 1 {\n\t\t\t\t\tcomps = cmdutil.Difference(comps, args[1:])\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tslashIdx := strings.Index(toComplete, \"/\")\n\t\t\tif slashIdx == -1 {\n\t\t\t\tif len(args) == 0 {\n\t\t\t\t\t// We are completing the first argument. We default to the normal\n\t\t\t\t\t// \u003ctype\u003e form (not the form \u003ctype\u003e/\u003cname\u003e).\n\t\t\t\t\t// So we suggest resource types and let the shell add a space after\n\t\t\t\t\t// the completion.\n\t\t\t\t\tif len(allowedTypes) == 0 {\n\t\t\t\t\t\tcomps = compGetResourceList(f, cmd, toComplete)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfor _, c := range allowedTypes {\n\t\t\t\t\t\t\tif strings.HasPrefix(c, toComplete) {\n\t\t\t\t\t\t\t\tcomps = append(comps, c)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Here we know the first argument contains a / (\u003ctype\u003e/\u003cname\u003e).\n\t\t\t\t\t// All other arguments must also use that form.\n\t\t\t\t\tif allowRepeat {\n\t\t\t\t\t\t// Since toComplete does not already contain a / we know we are completing a\n\t\t\t\t\t\t// resource type. Disable adding a space after the completion, and add the /\n\t\t\t\t\t\tdirective |= cobra.ShellCompDirectiveNoSpace\n\n\t\t\t\t\t\tif len(allowedTypes) == 0 {\n\t\t\t\t\t\t\ttypeComps := compGetResourceList(f, cmd, toComplete)\n\t\t\t\t\t\t\tfor _, c := range typeComps {\n\t\t\t\t\t\t\t\tcomps = append(comps, fmt.Sprintf(\"%s/\", c))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfor _, c := range allowedTypes {\n\t\t\t\t\t\t\t\tif strings.HasPrefix(c, toComplete) {\n\t\t\t\t\t\t\t\t\tcomps = append(comps, fmt.Sprintf(\"%s/\", c))\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// We are completing an argument of the form \u003ctype\u003e/\u003cname\u003e\n\t\t\t\t// and since the / is already present, we are completing the resource name.\n\t\t\t\tif allowRepeat || len(args) == 0 {\n\t\t\t\t\tresourceType := toComplete[:slashIdx]\n\t\t\t\t\ttoComplete = toComplete[slashIdx+1:]\n\t\t\t\t\tnameComps := CompGetResource(f, resourceType, toComplete)\n\t\t\t\t\tfor _, c := range nameComps {\n\t\t\t\t\t\tcomps = append(comps, fmt.Sprintf(\"%s/%s\", resourceType, c))\n\t\t\t\t\t}\n\n\t\t\t\t\t// Remove choices already on the command-line.\n\t\t\t\t\tif len(args) \u003e 0 {\n\t\t\t\t\t\tcomps = cmdutil.Difference(comps, args[0:])\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn comps, directive\n\t}\n}","line":{"from":297,"to":374}} {"id":100032861,"name":"doPodResourceCompletion","signature":"func doPodResourceCompletion(f cmdutil.Factory, toComplete string) ([]string, cobra.ShellCompDirective)","file":"staging/src/k8s.io/kubectl/pkg/util/completion/completion.go","code":"// doPodResourceCompletion Returns completions of:\n// 1- pod names that match the toComplete prefix\n// 2- resource types containing pods which match the toComplete prefix\nfunc doPodResourceCompletion(f cmdutil.Factory, toComplete string) ([]string, cobra.ShellCompDirective) {\n\tvar comps []string\n\tdirective := cobra.ShellCompDirectiveNoFileComp\n\tslashIdx := strings.Index(toComplete, \"/\")\n\tif slashIdx == -1 {\n\t\t// Standard case, complete pod names\n\t\tcomps = CompGetResource(f, \"pod\", toComplete)\n\n\t\t// Also include resource choices for the \u003ctype\u003e/\u003cname\u003e form,\n\t\t// but only for resources that contain pods\n\t\tresourcesWithPods := []string{\n\t\t\t\"daemonsets\",\n\t\t\t\"deployments\",\n\t\t\t\"pods\",\n\t\t\t\"jobs\",\n\t\t\t\"replicasets\",\n\t\t\t\"replicationcontrollers\",\n\t\t\t\"services\",\n\t\t\t\"statefulsets\"}\n\n\t\tif len(comps) == 0 {\n\t\t\t// If there are no pods to complete, we will only be completing\n\t\t\t// \u003ctype\u003e/. We should disable adding a space after the /.\n\t\t\tdirective |= cobra.ShellCompDirectiveNoSpace\n\t\t}\n\n\t\tfor _, resource := range resourcesWithPods {\n\t\t\tif strings.HasPrefix(resource, toComplete) {\n\t\t\t\tcomps = append(comps, fmt.Sprintf(\"%s/\", resource))\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Dealing with the \u003ctype\u003e/\u003cname\u003e form, use the specified resource type\n\t\tresourceType := toComplete[:slashIdx]\n\t\ttoComplete = toComplete[slashIdx+1:]\n\t\tnameComps := CompGetResource(f, resourceType, toComplete)\n\t\tfor _, c := range nameComps {\n\t\t\tcomps = append(comps, fmt.Sprintf(\"%s/%s\", resourceType, c))\n\t\t}\n\t}\n\treturn comps, directive\n}","line":{"from":376,"to":420}} {"id":100032862,"name":"convertResourceNameToPodName","signature":"func convertResourceNameToPodName(f cmdutil.Factory, resourceName string) string","file":"staging/src/k8s.io/kubectl/pkg/util/completion/completion.go","code":"// convertResourceNameToPodName Converts a resource name to a pod name.\n// If the resource name is of the form \u003ctype\u003e/\u003cname\u003e, we use\n// polymorphichelpers.AttachablePodForObjectFn(), if not, the resource name\n// is already a pod name.\nfunc convertResourceNameToPodName(f cmdutil.Factory, resourceName string) string {\n\tvar podName string\n\tif !strings.Contains(resourceName, \"/\") {\n\t\t// When we don't have the \u003ctype\u003e/\u003cname\u003e form, the resource name is the pod name\n\t\tpodName = resourceName\n\t} else {\n\t\t// if the resource name is of the form \u003ctype\u003e/\u003cname\u003e, we need to convert it to a pod name\n\t\tns, _, err := f.ToRawKubeConfigLoader().Namespace()\n\t\tif err != nil {\n\t\t\treturn \"\"\n\t\t}\n\n\t\tresourceWithPod, err := f.NewBuilder().\n\t\t\tWithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).\n\t\t\tContinueOnError().\n\t\t\tNamespaceParam(ns).DefaultNamespace().\n\t\t\tResourceNames(\"pods\", resourceName).\n\t\t\tDo().Object()\n\t\tif err != nil {\n\t\t\treturn \"\"\n\t\t}\n\n\t\t// For shell completion, use a short timeout\n\t\tforwardablePod, err := polymorphichelpers.AttachablePodForObjectFn(f, resourceWithPod, 100*time.Millisecond)\n\t\tif err != nil {\n\t\t\treturn \"\"\n\t\t}\n\t\tpodName = forwardablePod.Name\n\t}\n\treturn podName\n}","line":{"from":422,"to":456}} {"id":100032863,"name":"GetDeploymentCondition","signature":"func GetDeploymentCondition(status appsv1.DeploymentStatus, condType appsv1.DeploymentConditionType) *appsv1.DeploymentCondition","file":"staging/src/k8s.io/kubectl/pkg/util/deployment/deployment.go","code":"// GetDeploymentCondition returns the condition with the provided type.\nfunc GetDeploymentCondition(status appsv1.DeploymentStatus, condType appsv1.DeploymentConditionType) *appsv1.DeploymentCondition {\n\tfor i := range status.Conditions {\n\t\tc := status.Conditions[i]\n\t\tif c.Type == condType {\n\t\t\treturn \u0026c\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":59,"to":68}} {"id":100032864,"name":"Revision","signature":"func Revision(obj runtime.Object) (int64, error)","file":"staging/src/k8s.io/kubectl/pkg/util/deployment/deployment.go","code":"// Revision returns the revision number of the input object.\nfunc Revision(obj runtime.Object) (int64, error) {\n\tacc, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tv, ok := acc.GetAnnotations()[RevisionAnnotation]\n\tif !ok {\n\t\treturn 0, nil\n\t}\n\treturn strconv.ParseInt(v, 10, 64)\n}","line":{"from":70,"to":81}} {"id":100032865,"name":"GetAllReplicaSets","signature":"func GetAllReplicaSets(deployment *appsv1.Deployment, c appsclient.AppsV1Interface) ([]*appsv1.ReplicaSet, []*appsv1.ReplicaSet, *appsv1.ReplicaSet, error)","file":"staging/src/k8s.io/kubectl/pkg/util/deployment/deployment.go","code":"// GetAllReplicaSets returns the old and new replica sets targeted by the given Deployment. It gets PodList and\n// ReplicaSetList from client interface. Note that the first set of old replica sets doesn't include the ones\n// with no pods, and the second set of old replica sets include all old replica sets. The third returned value\n// is the new replica set, and it may be nil if it doesn't exist yet.\nfunc GetAllReplicaSets(deployment *appsv1.Deployment, c appsclient.AppsV1Interface) ([]*appsv1.ReplicaSet, []*appsv1.ReplicaSet, *appsv1.ReplicaSet, error) {\n\trsList, err := listReplicaSets(deployment, rsListFromClient(c), nil)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tnewRS := findNewReplicaSet(deployment, rsList)\n\toldRSes, allOldRSes := findOldReplicaSets(deployment, rsList, newRS)\n\treturn oldRSes, allOldRSes, newRS, nil\n}","line":{"from":83,"to":95}} {"id":100032866,"name":"GetAllReplicaSetsInChunks","signature":"func GetAllReplicaSetsInChunks(deployment *appsv1.Deployment, c appsclient.AppsV1Interface, chunkSize int64) ([]*appsv1.ReplicaSet, []*appsv1.ReplicaSet, *appsv1.ReplicaSet, error)","file":"staging/src/k8s.io/kubectl/pkg/util/deployment/deployment.go","code":"// GetAllReplicaSetsInChunks is the same as GetAllReplicaSets, but accepts a chunk size argument.\n// It returns the old and new replica sets targeted by the given Deployment. It gets PodList and\n// ReplicaSetList from client interface. Note that the first set of old replica sets doesn't include the ones\n// with no pods, and the second set of old replica sets include all old replica sets. The third returned value\n// is the new replica set, and it may be nil if it doesn't exist yet.\nfunc GetAllReplicaSetsInChunks(deployment *appsv1.Deployment, c appsclient.AppsV1Interface, chunkSize int64) ([]*appsv1.ReplicaSet, []*appsv1.ReplicaSet, *appsv1.ReplicaSet, error) {\n\trsList, err := listReplicaSets(deployment, rsListFromClient(c), \u0026chunkSize)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tnewRS := findNewReplicaSet(deployment, rsList)\n\toldRSes, allOldRSes := findOldReplicaSets(deployment, rsList, newRS)\n\treturn oldRSes, allOldRSes, newRS, nil\n}","line":{"from":97,"to":110}} {"id":100032867,"name":"rsListFromClient","signature":"func rsListFromClient(c appsclient.AppsV1Interface) rsListFunc","file":"staging/src/k8s.io/kubectl/pkg/util/deployment/deployment.go","code":"// RsListFromClient returns an rsListFunc that wraps the given client.\nfunc rsListFromClient(c appsclient.AppsV1Interface) rsListFunc {\n\treturn func(namespace string, initialOpts metav1.ListOptions) ([]*appsv1.ReplicaSet, error) {\n\t\trsList := \u0026appsv1.ReplicaSetList{}\n\t\terr := runtimeresource.FollowContinue(\u0026initialOpts,\n\t\t\tfunc(opts metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\tnewRs, err := c.ReplicaSets(namespace).List(context.TODO(), opts)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, runtimeresource.EnhanceListError(err, opts, \"replicasets\")\n\t\t\t\t}\n\t\t\t\trsList.Items = append(rsList.Items, newRs.Items...)\n\t\t\t\treturn newRs, nil\n\t\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar ret []*appsv1.ReplicaSet\n\t\tfor i := range rsList.Items {\n\t\t\tret = append(ret, \u0026rsList.Items[i])\n\t\t}\n\t\treturn ret, err\n\t}\n}","line":{"from":112,"to":134}} {"id":100032868,"name":"listReplicaSets","signature":"func listReplicaSets(deployment *appsv1.Deployment, getRSList rsListFunc, chunkSize *int64) ([]*appsv1.ReplicaSet, error)","file":"staging/src/k8s.io/kubectl/pkg/util/deployment/deployment.go","code":"// listReplicaSets returns a slice of RSes the given deployment targets.\n// Note that this does NOT attempt to reconcile ControllerRef (adopt/orphan),\n// because only the controller itself should do that.\n// However, it does filter out anything whose ControllerRef doesn't match.\nfunc listReplicaSets(deployment *appsv1.Deployment, getRSList rsListFunc, chunkSize *int64) ([]*appsv1.ReplicaSet, error) {\n\t// TODO: Right now we list replica sets by their labels. We should list them by selector, i.e. the replica set's selector\n\t// should be a superset of the deployment's selector, see https://github.com/kubernetes/kubernetes/issues/19830.\n\tnamespace := deployment.Namespace\n\tselector, err := metav1.LabelSelectorAsSelector(deployment.Spec.Selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\toptions := metav1.ListOptions{LabelSelector: selector.String()}\n\tif chunkSize != nil {\n\t\toptions.Limit = *chunkSize\n\t}\n\tall, err := getRSList(namespace, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Only include those whose ControllerRef matches the Deployment.\n\towned := make([]*appsv1.ReplicaSet, 0, len(all))\n\tfor _, rs := range all {\n\t\tif metav1.IsControlledBy(rs, deployment) {\n\t\t\towned = append(owned, rs)\n\t\t}\n\t}\n\treturn owned, nil\n}","line":{"from":139,"to":167}} {"id":100032869,"name":"equalIgnoreHash","signature":"func equalIgnoreHash(template1, template2 *corev1.PodTemplateSpec) bool","file":"staging/src/k8s.io/kubectl/pkg/util/deployment/deployment.go","code":"// EqualIgnoreHash returns true if two given podTemplateSpec are equal, ignoring the diff in value of Labels[pod-template-hash]\n// We ignore pod-template-hash because:\n// 1. The hash result would be different upon podTemplateSpec API changes\n// (e.g. the addition of a new field will cause the hash code to change)\n// 2. The deployment template won't have hash labels\nfunc equalIgnoreHash(template1, template2 *corev1.PodTemplateSpec) bool {\n\tt1Copy := template1.DeepCopy()\n\tt2Copy := template2.DeepCopy()\n\t// Remove hash labels from template.Labels before comparing\n\tdelete(t1Copy.Labels, appsv1.DefaultDeploymentUniqueLabelKey)\n\tdelete(t2Copy.Labels, appsv1.DefaultDeploymentUniqueLabelKey)\n\treturn apiequality.Semantic.DeepEqual(t1Copy, t2Copy)\n}","line":{"from":169,"to":181}} {"id":100032870,"name":"findNewReplicaSet","signature":"func findNewReplicaSet(deployment *appsv1.Deployment, rsList []*appsv1.ReplicaSet) *appsv1.ReplicaSet","file":"staging/src/k8s.io/kubectl/pkg/util/deployment/deployment.go","code":"// FindNewReplicaSet returns the new RS this given deployment targets (the one with the same pod template).\nfunc findNewReplicaSet(deployment *appsv1.Deployment, rsList []*appsv1.ReplicaSet) *appsv1.ReplicaSet {\n\tsort.Sort(replicaSetsByCreationTimestamp(rsList))\n\tfor i := range rsList {\n\t\tif equalIgnoreHash(\u0026rsList[i].Spec.Template, \u0026deployment.Spec.Template) {\n\t\t\t// In rare cases, such as after cluster upgrades, Deployment may end up with\n\t\t\t// having more than one new ReplicaSets that have the same template as its template,\n\t\t\t// see https://github.com/kubernetes/kubernetes/issues/40415\n\t\t\t// We deterministically choose the oldest new ReplicaSet.\n\t\t\treturn rsList[i]\n\t\t}\n\t}\n\t// new ReplicaSet does not exist.\n\treturn nil\n}","line":{"from":183,"to":197}} {"id":100032871,"name":"Len","signature":"func (o replicaSetsByCreationTimestamp) Len() int { return len(o) }","file":"staging/src/k8s.io/kubectl/pkg/util/deployment/deployment.go","code":"func (o replicaSetsByCreationTimestamp) Len() int { return len(o) }","line":{"from":202,"to":202}} {"id":100032872,"name":"Swap","signature":"func (o replicaSetsByCreationTimestamp) Swap(i, j int) { o[i], o[j] = o[j], o[i] }","file":"staging/src/k8s.io/kubectl/pkg/util/deployment/deployment.go","code":"func (o replicaSetsByCreationTimestamp) Swap(i, j int) { o[i], o[j] = o[j], o[i] }","line":{"from":203,"to":203}} {"id":100032873,"name":"Less","signature":"func (o replicaSetsByCreationTimestamp) Less(i, j int) bool","file":"staging/src/k8s.io/kubectl/pkg/util/deployment/deployment.go","code":"func (o replicaSetsByCreationTimestamp) Less(i, j int) bool {\n\tif o[i].CreationTimestamp.Equal(\u0026o[j].CreationTimestamp) {\n\t\treturn o[i].Name \u003c o[j].Name\n\t}\n\treturn o[i].CreationTimestamp.Before(\u0026o[j].CreationTimestamp)\n}","line":{"from":204,"to":209}} {"id":100032874,"name":"findOldReplicaSets","signature":"func findOldReplicaSets(deployment *appsv1.Deployment, rsList []*appsv1.ReplicaSet, newRS *appsv1.ReplicaSet) ([]*appsv1.ReplicaSet, []*appsv1.ReplicaSet)","file":"staging/src/k8s.io/kubectl/pkg/util/deployment/deployment.go","code":"// // FindOldReplicaSets returns the old replica sets targeted by the given Deployment, with the given slice of RSes.\n// // Note that the first set of old replica sets doesn't include the ones with no pods, and the second set of old replica sets include all old replica sets.\nfunc findOldReplicaSets(deployment *appsv1.Deployment, rsList []*appsv1.ReplicaSet, newRS *appsv1.ReplicaSet) ([]*appsv1.ReplicaSet, []*appsv1.ReplicaSet) {\n\tvar requiredRSs []*appsv1.ReplicaSet\n\tvar allRSs []*appsv1.ReplicaSet\n\tfor _, rs := range rsList {\n\t\t// Filter out new replica set\n\t\tif newRS != nil \u0026\u0026 rs.UID == newRS.UID {\n\t\t\tcontinue\n\t\t}\n\t\tallRSs = append(allRSs, rs)\n\t\tif *(rs.Spec.Replicas) != 0 {\n\t\t\trequiredRSs = append(requiredRSs, rs)\n\t\t}\n\t}\n\treturn requiredRSs, allRSs\n}","line":{"from":211,"to":227}} {"id":100032875,"name":"ResolveFenceposts","signature":"func ResolveFenceposts(maxSurge, maxUnavailable *intstrutil.IntOrString, desired int32) (int32, int32, error)","file":"staging/src/k8s.io/kubectl/pkg/util/deployment/deployment.go","code":"// ResolveFenceposts resolves both maxSurge and maxUnavailable. This needs to happen in one\n// step. For example:\n//\n// 2 desired, max unavailable 1%, surge 0% - should scale old(-1), then new(+1), then old(-1), then new(+1)\n// 1 desired, max unavailable 1%, surge 0% - should scale old(-1), then new(+1)\n// 2 desired, max unavailable 25%, surge 1% - should scale new(+1), then old(-1), then new(+1), then old(-1)\n// 1 desired, max unavailable 25%, surge 1% - should scale new(+1), then old(-1)\n// 2 desired, max unavailable 0%, surge 1% - should scale new(+1), then old(-1), then new(+1), then old(-1)\n// 1 desired, max unavailable 0%, surge 1% - should scale new(+1), then old(-1)\nfunc ResolveFenceposts(maxSurge, maxUnavailable *intstrutil.IntOrString, desired int32) (int32, int32, error) {\n\tsurge, err := intstrutil.GetScaledValueFromIntOrPercent(intstrutil.ValueOrDefault(maxSurge, intstrutil.FromInt(0)), int(desired), true)\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\tunavailable, err := intstrutil.GetScaledValueFromIntOrPercent(intstrutil.ValueOrDefault(maxUnavailable, intstrutil.FromInt(0)), int(desired), false)\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\n\tif surge == 0 \u0026\u0026 unavailable == 0 {\n\t\t// Validation should never allow the user to explicitly use zero values for both maxSurge\n\t\t// maxUnavailable. Due to rounding down maxUnavailable though, it may resolve to zero.\n\t\t// If both fenceposts resolve to zero, then we should set maxUnavailable to 1 on the\n\t\t// theory that surge might not work due to quota.\n\t\tunavailable = 1\n\t}\n\n\treturn int32(surge), int32(unavailable), nil\n}","line":{"from":229,"to":257}} {"id":100032876,"name":"Len","signature":"func (list SortableEvents) Len() int","file":"staging/src/k8s.io/kubectl/pkg/util/event/sorted_event_list.go","code":"func (list SortableEvents) Len() int {\n\treturn len(list)\n}","line":{"from":26,"to":28}} {"id":100032877,"name":"Swap","signature":"func (list SortableEvents) Swap(i, j int)","file":"staging/src/k8s.io/kubectl/pkg/util/event/sorted_event_list.go","code":"func (list SortableEvents) Swap(i, j int) {\n\tlist[i], list[j] = list[j], list[i]\n}","line":{"from":30,"to":32}} {"id":100032878,"name":"Less","signature":"func (list SortableEvents) Less(i, j int) bool","file":"staging/src/k8s.io/kubectl/pkg/util/event/sorted_event_list.go","code":"func (list SortableEvents) Less(i, j int) bool {\n\treturn list[i].LastTimestamp.Time.Before(list[j].LastTimestamp.Time)\n}","line":{"from":34,"to":36}} {"id":100032879,"name":"FormatMap","signature":"func FormatMap(m map[string]string) (fmtStr string)","file":"staging/src/k8s.io/kubectl/pkg/util/fieldpath/fieldpath.go","code":"// FormatMap formats map[string]string to a string.\nfunc FormatMap(m map[string]string) (fmtStr string) {\n\t// output with keys in sorted order to provide stable output\n\tkeys := sets.NewString()\n\tfor key := range m {\n\t\tkeys.Insert(key)\n\t}\n\tfor _, key := range keys.List() {\n\t\tfmtStr += fmt.Sprintf(\"%v=%q\\n\", key, m[key])\n\t}\n\tfmtStr = strings.TrimSuffix(fmtStr, \"\\n\")\n\n\treturn\n}","line":{"from":30,"to":43}} {"id":100032880,"name":"ExtractFieldPathAsString","signature":"func ExtractFieldPathAsString(obj interface{}, fieldPath string) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/util/fieldpath/fieldpath.go","code":"// ExtractFieldPathAsString extracts the field from the given object\n// and returns it as a string. The object must be a pointer to an\n// API type.\nfunc ExtractFieldPathAsString(obj interface{}, fieldPath string) (string, error) {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn \"\", nil\n\t}\n\n\tif path, subscript, ok := SplitMaybeSubscriptedPath(fieldPath); ok {\n\t\tswitch path {\n\t\tcase \"metadata.annotations\":\n\t\t\tif errs := validation.IsQualifiedName(strings.ToLower(subscript)); len(errs) != 0 {\n\t\t\t\treturn \"\", fmt.Errorf(\"invalid key subscript in %s: %s\", fieldPath, strings.Join(errs, \";\"))\n\t\t\t}\n\t\t\treturn accessor.GetAnnotations()[subscript], nil\n\t\tcase \"metadata.labels\":\n\t\t\tif errs := validation.IsQualifiedName(subscript); len(errs) != 0 {\n\t\t\t\treturn \"\", fmt.Errorf(\"invalid key subscript in %s: %s\", fieldPath, strings.Join(errs, \";\"))\n\t\t\t}\n\t\t\treturn accessor.GetLabels()[subscript], nil\n\t\tdefault:\n\t\t\treturn \"\", fmt.Errorf(\"fieldPath %q does not support subscript\", fieldPath)\n\t\t}\n\t}\n\n\tswitch fieldPath {\n\tcase \"metadata.annotations\":\n\t\treturn FormatMap(accessor.GetAnnotations()), nil\n\tcase \"metadata.labels\":\n\t\treturn FormatMap(accessor.GetLabels()), nil\n\tcase \"metadata.name\":\n\t\treturn accessor.GetName(), nil\n\tcase \"metadata.namespace\":\n\t\treturn accessor.GetNamespace(), nil\n\tcase \"metadata.uid\":\n\t\treturn string(accessor.GetUID()), nil\n\t}\n\n\treturn \"\", fmt.Errorf(\"unsupported fieldPath: %v\", fieldPath)\n}","line":{"from":45,"to":85}} {"id":100032881,"name":"SplitMaybeSubscriptedPath","signature":"func SplitMaybeSubscriptedPath(fieldPath string) (string, string, bool)","file":"staging/src/k8s.io/kubectl/pkg/util/fieldpath/fieldpath.go","code":"// SplitMaybeSubscriptedPath checks whether the specified fieldPath is\n// subscripted, and\n// - if yes, this function splits the fieldPath into path and subscript, and\n// returns (path, subscript, true).\n// - if no, this function returns (fieldPath, \"\", false).\n//\n// Example inputs and outputs:\n//\n//\t\"metadata.annotations['myKey']\" --\u003e (\"metadata.annotations\", \"myKey\", true)\n//\t\"metadata.annotations['a[b]c']\" --\u003e (\"metadata.annotations\", \"a[b]c\", true)\n//\t\"metadata.labels['']\" --\u003e (\"metadata.labels\", \"\", true)\n//\t\"metadata.labels\" --\u003e (\"metadata.labels\", \"\", false)\nfunc SplitMaybeSubscriptedPath(fieldPath string) (string, string, bool) {\n\tif !strings.HasSuffix(fieldPath, \"']\") {\n\t\treturn fieldPath, \"\", false\n\t}\n\ts := strings.TrimSuffix(fieldPath, \"']\")\n\tparts := strings.SplitN(s, \"['\", 2)\n\tif len(parts) \u003c 2 {\n\t\treturn fieldPath, \"\", false\n\t}\n\tif len(parts[0]) == 0 {\n\t\treturn fieldPath, \"\", false\n\t}\n\treturn parts[0], parts[1], true\n}","line":{"from":87,"to":112}} {"id":100032882,"name":"ConfigMapHash","signature":"func ConfigMapHash(cm *v1.ConfigMap) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/util/hash/hash.go","code":"// ConfigMapHash returns a hash of the ConfigMap.\n// The Data, Kind, and Name are taken into account.\nfunc ConfigMapHash(cm *v1.ConfigMap) (string, error) {\n\tencoded, err := encodeConfigMap(cm)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\th, err := encodeHash(hash(encoded))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn h, nil\n}","line":{"from":27,"to":39}} {"id":100032883,"name":"SecretHash","signature":"func SecretHash(sec *v1.Secret) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/util/hash/hash.go","code":"// SecretHash returns a hash of the Secret.\n// The Data, Kind, Name, and Type are taken into account.\nfunc SecretHash(sec *v1.Secret) (string, error) {\n\tencoded, err := encodeSecret(sec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\th, err := encodeHash(hash(encoded))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn h, nil\n}","line":{"from":41,"to":53}} {"id":100032884,"name":"encodeConfigMap","signature":"func encodeConfigMap(cm *v1.ConfigMap) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/util/hash/hash.go","code":"// encodeConfigMap encodes a ConfigMap.\n// Data, Kind, and Name are taken into account.\nfunc encodeConfigMap(cm *v1.ConfigMap) (string, error) {\n\t// json.Marshal sorts the keys in a stable order in the encoding\n\tm := map[string]interface{}{\n\t\t\"kind\": \"ConfigMap\",\n\t\t\"name\": cm.Name,\n\t\t\"data\": cm.Data,\n\t}\n\tif cm.Immutable != nil {\n\t\tm[\"immutable\"] = *cm.Immutable\n\t}\n\tif len(cm.BinaryData) \u003e 0 {\n\t\tm[\"binaryData\"] = cm.BinaryData\n\t}\n\tdata, err := json.Marshal(m)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(data), nil\n}","line":{"from":55,"to":75}} {"id":100032885,"name":"encodeSecret","signature":"func encodeSecret(sec *v1.Secret) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/util/hash/hash.go","code":"// encodeSecret encodes a Secret.\n// Data, Kind, Name, and Type are taken into account.\nfunc encodeSecret(sec *v1.Secret) (string, error) {\n\tm := map[string]interface{}{\n\t\t\"kind\": \"Secret\",\n\t\t\"type\": sec.Type,\n\t\t\"name\": sec.Name,\n\t\t\"data\": sec.Data,\n\t}\n\tif sec.Immutable != nil {\n\t\tm[\"immutable\"] = *sec.Immutable\n\t}\n\t// json.Marshal sorts the keys in a stable order in the encoding\n\tdata, err := json.Marshal(m)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(data), nil\n}","line":{"from":77,"to":95}} {"id":100032886,"name":"encodeHash","signature":"func encodeHash(hex string) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/util/hash/hash.go","code":"// encodeHash extracts the first 40 bits of the hash from the hex string\n// (1 hex char represents 4 bits), and then maps vowels and vowel-like hex\n// characters to consonants to prevent bad words from being formed (the theory\n// is that no vowels makes it really hard to make bad words). Since the string\n// is hex, the only vowels it can contain are 'a' and 'e'.\n// We picked some arbitrary consonants to map to from the same character set as GenerateName.\n// See: https://github.com/kubernetes/apimachinery/blob/dc1f89aff9a7509782bde3b68824c8043a3e58cc/pkg/util/rand/rand.go#L75\n// If the hex string contains fewer than ten characters, returns an error.\nfunc encodeHash(hex string) (string, error) {\n\tif len(hex) \u003c 10 {\n\t\treturn \"\", fmt.Errorf(\"the hex string must contain at least 10 characters\")\n\t}\n\tenc := []rune(hex[:10])\n\tfor i := range enc {\n\t\tswitch enc[i] {\n\t\tcase '0':\n\t\t\tenc[i] = 'g'\n\t\tcase '1':\n\t\t\tenc[i] = 'h'\n\t\tcase '3':\n\t\t\tenc[i] = 'k'\n\t\tcase 'a':\n\t\t\tenc[i] = 'm'\n\t\tcase 'e':\n\t\t\tenc[i] = 't'\n\t\t}\n\t}\n\treturn string(enc), nil\n}","line":{"from":97,"to":125}} {"id":100032887,"name":"hash","signature":"func hash(data string) string","file":"staging/src/k8s.io/kubectl/pkg/util/hash/hash.go","code":"// hash hashes `data` with sha256 and returns the hex string\nfunc hash(data string) string {\n\treturn fmt.Sprintf(\"%x\", sha256.Sum256([]byte(data)))\n}","line":{"from":127,"to":130}} {"id":100032888,"name":"SetLoadTranslationsFunc","signature":"func SetLoadTranslationsFunc(f func() error) error","file":"staging/src/k8s.io/kubectl/pkg/util/i18n/i18n.go","code":"// SetLoadTranslationsFunc sets the function called to lazy load translations.\n// It must be called in an init() func that occurs BEFORE any i18n.T() calls are made by any package. You can\n// accomplish this by creating a separate package containing your init() func, and then importing that package BEFORE\n// any other packages that call i18n.T().\n//\n// Example Usage:\n//\n//\tpackage myi18n\n//\n//\timport \"k8s.io/kubectl/pkg/util/i18n\"\n//\n//\tfunc init() {\n//\t\tif err := i18n.SetLoadTranslationsFunc(loadCustomTranslations); err != nil {\n//\t\t\tpanic(err)\n//\t\t}\n//\t}\n//\n//\tfunc loadCustomTranslations() error {\n//\t\t// Load your custom translations here...\n//\t}\n//\n// And then in your main or root command package, import your custom package like this:\n//\n//\timport (\n//\t\t// Other imports that don't need i18n...\n//\t\t_ \"example.com/myapp/myi18n\"\n//\t\t// Other imports that do need i18n...\n//\t)\nfunc SetLoadTranslationsFunc(f func() error) error {\n\tif translationsLoaded {\n\t\treturn errors.New(\"translations have already been loaded\")\n\t}\n\tLoadTranslationsFunc = func() error {\n\t\tif err := f(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttranslationsLoaded = true\n\t\treturn nil\n\t}\n\treturn nil\n}","line":{"from":65,"to":105}} {"id":100032889,"name":"loadSystemLanguage","signature":"func loadSystemLanguage() string","file":"staging/src/k8s.io/kubectl/pkg/util/i18n/i18n.go","code":"func loadSystemLanguage() string {\n\t// Implements the following locale priority order: LC_ALL, LC_MESSAGES, LANG\n\t// Similarly to: https://www.gnu.org/software/gettext/manual/html_node/Locale-Environment-Variables.html\n\tlangStr := os.Getenv(\"LC_ALL\")\n\tif langStr == \"\" {\n\t\tlangStr = os.Getenv(\"LC_MESSAGES\")\n\t}\n\tif langStr == \"\" {\n\t\tlangStr = os.Getenv(\"LANG\")\n\t}\n\n\tif langStr == \"\" {\n\t\tklog.V(3).Infof(\"Couldn't find the LC_ALL, LC_MESSAGES or LANG environment variables, defaulting to en_US\")\n\t\treturn \"default\"\n\t}\n\tpieces := strings.Split(langStr, \".\")\n\tif len(pieces) != 2 {\n\t\tklog.V(3).Infof(\"Unexpected system language (%s), defaulting to en_US\", langStr)\n\t\treturn \"default\"\n\t}\n\treturn pieces[0]\n}","line":{"from":107,"to":128}} {"id":100032890,"name":"findLanguage","signature":"func findLanguage(root string, getLanguageFn func() string) string","file":"staging/src/k8s.io/kubectl/pkg/util/i18n/i18n.go","code":"func findLanguage(root string, getLanguageFn func() string) string {\n\tlangStr := getLanguageFn()\n\n\ttranslations := knownTranslations[root]\n\tfor ix := range translations {\n\t\tif translations[ix] == langStr {\n\t\t\treturn langStr\n\t\t}\n\t}\n\tklog.V(3).Infof(\"Couldn't find translations for %s, using default\", langStr)\n\treturn \"default\"\n}","line":{"from":130,"to":141}} {"id":100032891,"name":"LoadTranslations","signature":"func LoadTranslations(root string, getLanguageFn func() string) error","file":"staging/src/k8s.io/kubectl/pkg/util/i18n/i18n.go","code":"// LoadTranslations loads translation files. getLanguageFn should return a language\n// string (e.g. 'en-US'). If getLanguageFn is nil, then the loadSystemLanguage function\n// is used, which uses the 'LANG' environment variable.\nfunc LoadTranslations(root string, getLanguageFn func() string) error {\n\tif getLanguageFn == nil {\n\t\tgetLanguageFn = loadSystemLanguage\n\t}\n\n\tlangStr := findLanguage(root, getLanguageFn)\n\ttranslationFiles := []string{\n\t\tfmt.Sprintf(\"%s/%s/LC_MESSAGES/k8s.po\", root, langStr),\n\t\tfmt.Sprintf(\"%s/%s/LC_MESSAGES/k8s.mo\", root, langStr),\n\t}\n\n\tklog.V(3).Infof(\"Setting language to %s\", langStr)\n\t// TODO: list the directory and load all files.\n\tbuf := new(bytes.Buffer)\n\tw := zip.NewWriter(buf)\n\n\t// Make sure to check the error on Close.\n\tfor _, file := range translationFiles {\n\t\tfilename := \"translations/\" + file\n\t\tf, err := w.Create(file)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdata, err := translations.ReadFile(filename)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, err := f.Write(data); err != nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\tif err := w.Close(); err != nil {\n\t\treturn err\n\t}\n\tgettext.BindLocale(gettext.New(\"k8s\", root+\".zip\", buf.Bytes()))\n\tgettext.SetDomain(\"k8s\")\n\tgettext.SetLanguage(langStr)\n\ttranslationsLoaded = true\n\treturn nil\n}","line":{"from":143,"to":185}} {"id":100032892,"name":"lazyLoadTranslations","signature":"func lazyLoadTranslations()","file":"staging/src/k8s.io/kubectl/pkg/util/i18n/i18n.go","code":"func lazyLoadTranslations() {\n\tlazyLoadTranslationsOnce.Do(func() {\n\t\tif translationsLoaded {\n\t\t\treturn\n\t\t}\n\t\tif err := LoadTranslationsFunc(); err != nil {\n\t\t\tklog.Warning(\"Failed to load translations\")\n\t\t}\n\t})\n}","line":{"from":187,"to":196}} {"id":100032893,"name":"T","signature":"func T(defaultValue string, args ...int) string","file":"staging/src/k8s.io/kubectl/pkg/util/i18n/i18n.go","code":"// T translates a string, possibly substituting arguments into it along\n// the way. If len(args) is \u003e 0, args1 is assumed to be the plural value\n// and plural translation is used.\nfunc T(defaultValue string, args ...int) string {\n\tlazyLoadTranslations()\n\tif len(args) == 0 {\n\t\treturn gettext.PGettext(\"\", defaultValue)\n\t}\n\treturn fmt.Sprintf(gettext.PNGettext(\"\", defaultValue, defaultValue+\".plural\", args[0]),\n\t\targs[0])\n}","line":{"from":198,"to":208}} {"id":100032894,"name":"Errorf","signature":"func Errorf(defaultValue string, args ...int) error","file":"staging/src/k8s.io/kubectl/pkg/util/i18n/i18n.go","code":"// Errorf produces an error with a translated error string.\n// Substitution is performed via the `T` function above, following\n// the same rules.\nfunc Errorf(defaultValue string, args ...int) error {\n\treturn errors.New(T(defaultValue, args...))\n}","line":{"from":210,"to":215}} {"id":100032895,"name":"Chain","signature":"func Chain(handler *Handler, notify ...func()) *Handler","file":"staging/src/k8s.io/kubectl/pkg/util/interrupt/interrupt.go","code":"// Chain creates a new handler that invokes all notify functions when the critical section exits\n// and then invokes the optional handler's notifications. This allows critical sections to be\n// nested without losing exactly once invocations. Notify functions can invoke any cleanup needed\n// but should not exit (which is the responsibility of the parent handler).\nfunc Chain(handler *Handler, notify ...func()) *Handler {\n\tif handler == nil {\n\t\treturn New(nil, notify...)\n\t}\n\treturn New(handler.Signal, append(notify, handler.Close)...)\n}","line":{"from":39,"to":48}} {"id":100032896,"name":"New","signature":"func New(final func(os.Signal), notify ...func()) *Handler","file":"staging/src/k8s.io/kubectl/pkg/util/interrupt/interrupt.go","code":"// New creates a new handler that guarantees all notify functions are run after the critical\n// section exits (or is interrupted by the OS), then invokes the final handler. If no final\n// handler is specified, the default final is `os.Exit(1)`. A handler can only be used for\n// one critical section.\nfunc New(final func(os.Signal), notify ...func()) *Handler {\n\treturn \u0026Handler{\n\t\tfinal: final,\n\t\tnotify: notify,\n\t}\n}","line":{"from":50,"to":59}} {"id":100032897,"name":"Close","signature":"func (h *Handler) Close()","file":"staging/src/k8s.io/kubectl/pkg/util/interrupt/interrupt.go","code":"// Close executes all the notification handlers if they have not yet been executed.\nfunc (h *Handler) Close() {\n\th.once.Do(func() {\n\t\tfor _, fn := range h.notify {\n\t\t\tfn()\n\t\t}\n\t})\n}","line":{"from":61,"to":68}} {"id":100032898,"name":"Signal","signature":"func (h *Handler) Signal(s os.Signal)","file":"staging/src/k8s.io/kubectl/pkg/util/interrupt/interrupt.go","code":"// Signal is called when an os.Signal is received, and guarantees that all notifications\n// are executed, then the final handler is executed. This function should only be called once\n// per Handler instance.\nfunc (h *Handler) Signal(s os.Signal) {\n\th.once.Do(func() {\n\t\tfor _, fn := range h.notify {\n\t\t\tfn()\n\t\t}\n\t\tif h.final == nil {\n\t\t\tos.Exit(1)\n\t\t}\n\t\th.final(s)\n\t})\n}","line":{"from":70,"to":83}} {"id":100032899,"name":"Run","signature":"func (h *Handler) Run(fn func() error) error","file":"staging/src/k8s.io/kubectl/pkg/util/interrupt/interrupt.go","code":"// Run ensures that any notifications are invoked after the provided fn exits (even if the\n// process is interrupted by an OS termination signal). Notifications are only invoked once\n// per Handler instance, so calling Run more than once will not behave as the user expects.\nfunc (h *Handler) Run(fn func() error) error {\n\tch := make(chan os.Signal, 1)\n\tsignal.Notify(ch, terminationSignals...)\n\tdefer func() {\n\t\tsignal.Stop(ch)\n\t\tclose(ch)\n\t}()\n\tgo func() {\n\t\tsig, ok := \u003c-ch\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\t\th.Signal(sig)\n\t}()\n\tdefer h.Close()\n\treturn fn()\n}","line":{"from":85,"to":104}} {"id":100032900,"name":"NewOpenAPIData","signature":"func NewOpenAPIData(doc *openapi_v2.Document) (Resources, error)","file":"staging/src/k8s.io/kubectl/pkg/util/openapi/openapi.go","code":"// NewOpenAPIData creates a new `Resources` out of the openapi document\nfunc NewOpenAPIData(doc *openapi_v2.Document) (Resources, error) {\n\tmodels, err := proto.NewOpenAPIData(doc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresources := map[schema.GroupVersionKind]string{}\n\tfor _, modelName := range models.ListModels() {\n\t\tmodel := models.LookupModel(modelName)\n\t\tif model == nil {\n\t\t\tpanic(\"ListModels returns a model that can't be looked-up.\")\n\t\t}\n\t\tgvkList := parseGroupVersionKind(model)\n\t\tfor _, gvk := range gvkList {\n\t\t\tif len(gvk.Kind) \u003e 0 {\n\t\t\t\tresources[gvk] = modelName\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \u0026document{\n\t\tresources: resources,\n\t\tmodels: models,\n\t\tdoc: doc,\n\t}, nil\n}","line":{"from":50,"to":76}} {"id":100032901,"name":"LookupResource","signature":"func (d *document) LookupResource(gvk schema.GroupVersionKind) proto.Schema","file":"staging/src/k8s.io/kubectl/pkg/util/openapi/openapi.go","code":"func (d *document) LookupResource(gvk schema.GroupVersionKind) proto.Schema {\n\tmodelName, found := d.resources[gvk]\n\tif !found {\n\t\treturn nil\n\t}\n\treturn d.models.LookupModel(modelName)\n}","line":{"from":78,"to":84}} {"id":100032902,"name":"GetConsumes","signature":"func (d *document) GetConsumes(gvk schema.GroupVersionKind, operation string) []string","file":"staging/src/k8s.io/kubectl/pkg/util/openapi/openapi.go","code":"func (d *document) GetConsumes(gvk schema.GroupVersionKind, operation string) []string {\n\tfor _, path := range d.doc.GetPaths().GetPath() {\n\t\tfor _, ex := range path.GetValue().GetPatch().GetVendorExtension() {\n\t\t\tif ex.GetValue().GetYaml() == \"\" ||\n\t\t\t\tex.GetName() != \"x-kubernetes-group-version-kind\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar value map[string]string\n\t\t\terr := yaml.Unmarshal([]byte(ex.GetValue().GetYaml()), \u0026value)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif value[\"group\"] == gvk.Group \u0026\u0026 value[\"kind\"] == gvk.Kind \u0026\u0026 value[\"version\"] == gvk.Version {\n\t\t\t\tswitch operation {\n\t\t\t\tcase \"GET\":\n\t\t\t\t\treturn path.GetValue().GetGet().GetConsumes()\n\t\t\t\tcase \"PATCH\":\n\t\t\t\t\treturn path.GetValue().GetPatch().GetConsumes()\n\t\t\t\tcase \"HEAD\":\n\t\t\t\t\treturn path.GetValue().GetHead().GetConsumes()\n\t\t\t\tcase \"PUT\":\n\t\t\t\t\treturn path.GetValue().GetPut().GetConsumes()\n\t\t\t\tcase \"POST\":\n\t\t\t\t\treturn path.GetValue().GetPost().GetConsumes()\n\t\t\t\tcase \"OPTIONS\":\n\t\t\t\t\treturn path.GetValue().GetOptions().GetConsumes()\n\t\t\t\tcase \"DELETE\":\n\t\t\t\t\treturn path.GetValue().GetDelete().GetConsumes()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":86,"to":122}} {"id":100032903,"name":"parseGroupVersionKind","signature":"func parseGroupVersionKind(s proto.Schema) []schema.GroupVersionKind","file":"staging/src/k8s.io/kubectl/pkg/util/openapi/openapi.go","code":"// Get and parse GroupVersionKind from the extension. Returns empty if it doesn't have one.\nfunc parseGroupVersionKind(s proto.Schema) []schema.GroupVersionKind {\n\textensions := s.GetExtensions()\n\n\tgvkListResult := []schema.GroupVersionKind{}\n\n\t// Get the extensions\n\tgvkExtension, ok := extensions[groupVersionKindExtensionKey]\n\tif !ok {\n\t\treturn []schema.GroupVersionKind{}\n\t}\n\n\t// gvk extension must be a list of at least 1 element.\n\tgvkList, ok := gvkExtension.([]interface{})\n\tif !ok {\n\t\treturn []schema.GroupVersionKind{}\n\t}\n\n\tfor _, gvk := range gvkList {\n\t\t// gvk extension list must be a map with group, version, and\n\t\t// kind fields\n\t\tgvkMap, ok := gvk.(map[interface{}]interface{})\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tgroup, ok := gvkMap[\"group\"].(string)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tversion, ok := gvkMap[\"version\"].(string)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tkind, ok := gvkMap[\"kind\"].(string)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tgvkListResult = append(gvkListResult, schema.GroupVersionKind{\n\t\t\tGroup: group,\n\t\t\tVersion: version,\n\t\t\tKind: kind,\n\t\t})\n\t}\n\n\treturn gvkListResult\n}","line":{"from":124,"to":170}} {"id":100032904,"name":"NewOpenAPIGetter","signature":"func NewOpenAPIGetter(openAPIClient discovery.OpenAPISchemaInterface) *CachedOpenAPIGetter","file":"staging/src/k8s.io/kubectl/pkg/util/openapi/openapi_getter.go","code":"// NewOpenAPIGetter returns an object to return OpenAPIDatas which reads\n// from a server, and then stores in memory for subsequent invocations\nfunc NewOpenAPIGetter(openAPIClient discovery.OpenAPISchemaInterface) *CachedOpenAPIGetter {\n\treturn \u0026CachedOpenAPIGetter{\n\t\topenAPIClient: openAPIClient,\n\t}\n}","line":{"from":38,"to":44}} {"id":100032905,"name":"OpenAPISchema","signature":"func (g *CachedOpenAPIGetter) OpenAPISchema() (*openapi_v2.Document, error)","file":"staging/src/k8s.io/kubectl/pkg/util/openapi/openapi_getter.go","code":"// OpenAPISchema implements OpenAPISchemaInterface.\nfunc (g *CachedOpenAPIGetter) OpenAPISchema() (*openapi_v2.Document, error) {\n\tg.Do(func() {\n\t\tg.openAPISchema, g.err = g.openAPIClient.OpenAPISchema()\n\t})\n\n\t// Return the saved result.\n\treturn g.openAPISchema, g.err\n}","line":{"from":46,"to":54}} {"id":100032906,"name":"NewOpenAPIParser","signature":"func NewOpenAPIParser(openAPIClient discovery.OpenAPISchemaInterface) *CachedOpenAPIParser","file":"staging/src/k8s.io/kubectl/pkg/util/openapi/openapi_getter.go","code":"func NewOpenAPIParser(openAPIClient discovery.OpenAPISchemaInterface) *CachedOpenAPIParser {\n\treturn \u0026CachedOpenAPIParser{\n\t\topenAPIClient: openAPIClient,\n\t}\n}","line":{"from":65,"to":69}} {"id":100032907,"name":"Parse","signature":"func (p *CachedOpenAPIParser) Parse() (Resources, error)","file":"staging/src/k8s.io/kubectl/pkg/util/openapi/openapi_getter.go","code":"func (p *CachedOpenAPIParser) Parse() (Resources, error) {\n\tp.Do(func() {\n\t\toapi, err := p.openAPIClient.OpenAPISchema()\n\t\tif err != nil {\n\t\t\tp.err = err\n\t\t\treturn\n\t\t}\n\t\tp.openAPIResources, p.err = NewOpenAPIData(oapi)\n\t})\n\n\treturn p.openAPIResources, p.err\n}","line":{"from":71,"to":82}} {"id":100032908,"name":"LookupContainerPortNumberByName","signature":"func LookupContainerPortNumberByName(pod v1.Pod, name string) (int32, error)","file":"staging/src/k8s.io/kubectl/pkg/util/pod_port.go","code":"// LookupContainerPortNumberByName find containerPort number by its named port name\nfunc LookupContainerPortNumberByName(pod v1.Pod, name string) (int32, error) {\n\tfor _, ctr := range pod.Spec.Containers {\n\t\tfor _, ctrportspec := range ctr.Ports {\n\t\t\tif ctrportspec.Name == name {\n\t\t\t\treturn ctrportspec.ContainerPort, nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn int32(-1), fmt.Errorf(\"Pod '%s' does not have a named port '%s'\", pod.Name, name)\n}","line":{"from":25,"to":36}} {"id":100032909,"name":"IsPodAvailable","signature":"func IsPodAvailable(pod *corev1.Pod, minReadySeconds int32, now metav1.Time) bool","file":"staging/src/k8s.io/kubectl/pkg/util/podutils/podutils.go","code":"// IsPodAvailable returns true if a pod is available; false otherwise.\n// Precondition for an available pod is that it must be ready. On top\n// of that, there are two cases when a pod can be considered available:\n// 1. minReadySeconds == 0, or\n// 2. LastTransitionTime (is set) + minReadySeconds \u003c current time\nfunc IsPodAvailable(pod *corev1.Pod, minReadySeconds int32, now metav1.Time) bool {\n\tif !IsPodReady(pod) {\n\t\treturn false\n\t}\n\n\tc := getPodReadyCondition(pod.Status)\n\tminReadySecondsDuration := time.Duration(minReadySeconds) * time.Second\n\tif minReadySeconds == 0 || !c.LastTransitionTime.IsZero() \u0026\u0026 c.LastTransitionTime.Add(minReadySecondsDuration).Before(now.Time) {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":27,"to":43}} {"id":100032910,"name":"IsPodReady","signature":"func IsPodReady(pod *corev1.Pod) bool","file":"staging/src/k8s.io/kubectl/pkg/util/podutils/podutils.go","code":"// IsPodReady returns true if a pod is ready; false otherwise.\nfunc IsPodReady(pod *corev1.Pod) bool {\n\treturn isPodReadyConditionTrue(pod.Status)\n}","line":{"from":45,"to":48}} {"id":100032911,"name":"isPodReadyConditionTrue","signature":"func isPodReadyConditionTrue(status corev1.PodStatus) bool","file":"staging/src/k8s.io/kubectl/pkg/util/podutils/podutils.go","code":"// IsPodReadyConditionTrue returns true if a pod is ready; false otherwise.\nfunc isPodReadyConditionTrue(status corev1.PodStatus) bool {\n\tcondition := getPodReadyCondition(status)\n\treturn condition != nil \u0026\u0026 condition.Status == corev1.ConditionTrue\n}","line":{"from":50,"to":54}} {"id":100032912,"name":"getPodReadyCondition","signature":"func getPodReadyCondition(status corev1.PodStatus) *corev1.PodCondition","file":"staging/src/k8s.io/kubectl/pkg/util/podutils/podutils.go","code":"// GetPodReadyCondition extracts the pod ready condition from the given status and returns that.\n// Returns nil if the condition is not present.\nfunc getPodReadyCondition(status corev1.PodStatus) *corev1.PodCondition {\n\t_, condition := getPodCondition(\u0026status, corev1.PodReady)\n\treturn condition\n}","line":{"from":56,"to":61}} {"id":100032913,"name":"getPodCondition","signature":"func getPodCondition(status *corev1.PodStatus, conditionType corev1.PodConditionType) (int, *corev1.PodCondition)","file":"staging/src/k8s.io/kubectl/pkg/util/podutils/podutils.go","code":"// GetPodCondition extracts the provided condition from the given status and returns that.\n// Returns nil and -1 if the condition is not present, and the index of the located condition.\nfunc getPodCondition(status *corev1.PodStatus, conditionType corev1.PodConditionType) (int, *corev1.PodCondition) {\n\tif status == nil {\n\t\treturn -1, nil\n\t}\n\treturn getPodConditionFromList(status.Conditions, conditionType)\n}","line":{"from":63,"to":70}} {"id":100032914,"name":"getPodConditionFromList","signature":"func getPodConditionFromList(conditions []corev1.PodCondition, conditionType corev1.PodConditionType) (int, *corev1.PodCondition)","file":"staging/src/k8s.io/kubectl/pkg/util/podutils/podutils.go","code":"// GetPodConditionFromList extracts the provided condition from the given list of condition and\n// returns the index of the condition and the condition. Returns -1 and nil if the condition is not present.\nfunc getPodConditionFromList(conditions []corev1.PodCondition, conditionType corev1.PodConditionType) (int, *corev1.PodCondition) {\n\tif conditions == nil {\n\t\treturn -1, nil\n\t}\n\tfor i := range conditions {\n\t\tif conditions[i].Type == conditionType {\n\t\t\treturn i, \u0026conditions[i]\n\t\t}\n\t}\n\treturn -1, nil\n}","line":{"from":72,"to":84}} {"id":100032915,"name":"Len","signature":"func (s ByLogging) Len() int { return len(s) }","file":"staging/src/k8s.io/kubectl/pkg/util/podutils/podutils.go","code":"func (s ByLogging) Len() int { return len(s) }","line":{"from":89,"to":89}} {"id":100032916,"name":"Swap","signature":"func (s ByLogging) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","file":"staging/src/k8s.io/kubectl/pkg/util/podutils/podutils.go","code":"func (s ByLogging) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","line":{"from":90,"to":90}} {"id":100032917,"name":"Less","signature":"func (s ByLogging) Less(i, j int) bool","file":"staging/src/k8s.io/kubectl/pkg/util/podutils/podutils.go","code":"func (s ByLogging) Less(i, j int) bool {\n\t// 1. assigned \u003c unassigned\n\tif s[i].Spec.NodeName != s[j].Spec.NodeName \u0026\u0026 (len(s[i].Spec.NodeName) == 0 || len(s[j].Spec.NodeName) == 0) {\n\t\treturn len(s[i].Spec.NodeName) \u003e 0\n\t}\n\t// 2. PodRunning \u003c PodUnknown \u003c PodPending\n\tm := map[corev1.PodPhase]int{corev1.PodRunning: 0, corev1.PodUnknown: 1, corev1.PodPending: 2}\n\tif m[s[i].Status.Phase] != m[s[j].Status.Phase] {\n\t\treturn m[s[i].Status.Phase] \u003c m[s[j].Status.Phase]\n\t}\n\t// 3. ready \u003c not ready\n\tif IsPodReady(s[i]) != IsPodReady(s[j]) {\n\t\treturn IsPodReady(s[i])\n\t}\n\t// TODO: take availability into account when we push minReadySeconds information from deployment into pods,\n\t// see https://github.com/kubernetes/kubernetes/issues/22065\n\t// 4. Been ready for more time \u003c less time \u003c empty time\n\tif IsPodReady(s[i]) \u0026\u0026 IsPodReady(s[j]) \u0026\u0026 !podReadyTime(s[i]).Equal(podReadyTime(s[j])) {\n\t\treturn afterOrZero(podReadyTime(s[j]), podReadyTime(s[i]))\n\t}\n\t// 5. Pods with containers with higher restart counts \u003c lower restart counts\n\tif maxContainerRestarts(s[i]) != maxContainerRestarts(s[j]) {\n\t\treturn maxContainerRestarts(s[i]) \u003e maxContainerRestarts(s[j])\n\t}\n\t// 6. older pods \u003c newer pods \u003c empty timestamp pods\n\tif !s[i].CreationTimestamp.Equal(\u0026s[j].CreationTimestamp) {\n\t\treturn afterOrZero(\u0026s[j].CreationTimestamp, \u0026s[i].CreationTimestamp)\n\t}\n\treturn false\n}","line":{"from":92,"to":121}} {"id":100032918,"name":"Len","signature":"func (s ActivePods) Len() int { return len(s) }","file":"staging/src/k8s.io/kubectl/pkg/util/podutils/podutils.go","code":"func (s ActivePods) Len() int { return len(s) }","line":{"from":126,"to":126}} {"id":100032919,"name":"Swap","signature":"func (s ActivePods) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","file":"staging/src/k8s.io/kubectl/pkg/util/podutils/podutils.go","code":"func (s ActivePods) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","line":{"from":127,"to":127}} {"id":100032920,"name":"Less","signature":"func (s ActivePods) Less(i, j int) bool","file":"staging/src/k8s.io/kubectl/pkg/util/podutils/podutils.go","code":"func (s ActivePods) Less(i, j int) bool {\n\t// 1. Unassigned \u003c assigned\n\t// If only one of the pods is unassigned, the unassigned one is smaller\n\tif s[i].Spec.NodeName != s[j].Spec.NodeName \u0026\u0026 (len(s[i].Spec.NodeName) == 0 || len(s[j].Spec.NodeName) == 0) {\n\t\treturn len(s[i].Spec.NodeName) == 0\n\t}\n\t// 2. PodPending \u003c PodUnknown \u003c PodRunning\n\tm := map[corev1.PodPhase]int{corev1.PodPending: 0, corev1.PodUnknown: 1, corev1.PodRunning: 2}\n\tif m[s[i].Status.Phase] != m[s[j].Status.Phase] {\n\t\treturn m[s[i].Status.Phase] \u003c m[s[j].Status.Phase]\n\t}\n\t// 3. Not ready \u003c ready\n\t// If only one of the pods is not ready, the not ready one is smaller\n\tif IsPodReady(s[i]) != IsPodReady(s[j]) {\n\t\treturn !IsPodReady(s[i])\n\t}\n\t// TODO: take availability into account when we push minReadySeconds information from deployment into pods,\n\t// see https://github.com/kubernetes/kubernetes/issues/22065\n\t// 4. Been ready for empty time \u003c less time \u003c more time\n\t// If both pods are ready, the latest ready one is smaller\n\tif IsPodReady(s[i]) \u0026\u0026 IsPodReady(s[j]) \u0026\u0026 !podReadyTime(s[i]).Equal(podReadyTime(s[j])) {\n\t\treturn afterOrZero(podReadyTime(s[i]), podReadyTime(s[j]))\n\t}\n\t// 5. Pods with containers with higher restart counts \u003c lower restart counts\n\tif maxContainerRestarts(s[i]) != maxContainerRestarts(s[j]) {\n\t\treturn maxContainerRestarts(s[i]) \u003e maxContainerRestarts(s[j])\n\t}\n\t// 6. Empty creation time pods \u003c newer pods \u003c older pods\n\tif !s[i].CreationTimestamp.Equal(\u0026s[j].CreationTimestamp) {\n\t\treturn afterOrZero(\u0026s[i].CreationTimestamp, \u0026s[j].CreationTimestamp)\n\t}\n\treturn false\n}","line":{"from":129,"to":161}} {"id":100032921,"name":"afterOrZero","signature":"func afterOrZero(t1, t2 *metav1.Time) bool","file":"staging/src/k8s.io/kubectl/pkg/util/podutils/podutils.go","code":"// afterOrZero checks if time t1 is after time t2; if one of them\n// is zero, the zero time is seen as after non-zero time.\nfunc afterOrZero(t1, t2 *metav1.Time) bool {\n\tif t1.Time.IsZero() || t2.Time.IsZero() {\n\t\treturn t1.Time.IsZero()\n\t}\n\treturn t1.After(t2.Time)\n}","line":{"from":163,"to":170}} {"id":100032922,"name":"podReadyTime","signature":"func podReadyTime(pod *corev1.Pod) *metav1.Time","file":"staging/src/k8s.io/kubectl/pkg/util/podutils/podutils.go","code":"func podReadyTime(pod *corev1.Pod) *metav1.Time {\n\tfor _, c := range pod.Status.Conditions {\n\t\t// we only care about pod ready conditions\n\t\tif c.Type == corev1.PodReady \u0026\u0026 c.Status == corev1.ConditionTrue {\n\t\t\treturn \u0026c.LastTransitionTime\n\t\t}\n\t}\n\treturn \u0026metav1.Time{}\n}","line":{"from":172,"to":180}} {"id":100032923,"name":"maxContainerRestarts","signature":"func maxContainerRestarts(pod *corev1.Pod) int","file":"staging/src/k8s.io/kubectl/pkg/util/podutils/podutils.go","code":"func maxContainerRestarts(pod *corev1.Pod) int {\n\tmaxRestarts := 0\n\tfor _, c := range pod.Status.ContainerStatuses {\n\t\tmaxRestarts = integer.IntMax(maxRestarts, int(c.RestartCount))\n\t}\n\treturn maxRestarts\n}","line":{"from":182,"to":188}} {"id":100032924,"name":"VisitContainers","signature":"func VisitContainers(podSpec *corev1.PodSpec, mask ContainerType, visitor ContainerVisitor) bool","file":"staging/src/k8s.io/kubectl/pkg/util/podutils/podutils.go","code":"// VisitContainers invokes the visitor function with a pointer to every container\n// spec in the given pod spec with type set in mask. If visitor returns false,\n// visiting is short-circuited. VisitContainers returns true if visiting completes,\n// false if visiting was short-circuited.\nfunc VisitContainers(podSpec *corev1.PodSpec, mask ContainerType, visitor ContainerVisitor) bool {\n\tif mask\u0026InitContainers != 0 {\n\t\tfor i := range podSpec.InitContainers {\n\t\t\tif !visitor(\u0026podSpec.InitContainers[i], InitContainers) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\tif mask\u0026Containers != 0 {\n\t\tfor i := range podSpec.Containers {\n\t\t\tif !visitor(\u0026podSpec.Containers[i], Containers) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\tif mask\u0026EphemeralContainers != 0 {\n\t\tfor i := range podSpec.EphemeralContainers {\n\t\t\tif !visitor((*corev1.Container)(\u0026podSpec.EphemeralContainers[i].EphemeralContainerCommon), EphemeralContainers) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}","line":{"from":213,"to":240}} {"id":100032925,"name":"String","signature":"func (pr Resource) String() string","file":"staging/src/k8s.io/kubectl/pkg/util/prune/prune.go","code":"func (pr Resource) String() string {\n\treturn fmt.Sprintf(\"%v/%v, Kind=%v, Namespaced=%v\", pr.group, pr.version, pr.kind, pr.namespaced)\n}","line":{"from":59,"to":61}} {"id":100032926,"name":"GetRESTMappings","signature":"func GetRESTMappings(mapper meta.RESTMapper, pruneResources []Resource, namespaceSpecified bool) (namespaced, nonNamespaced []*meta.RESTMapping, err error)","file":"staging/src/k8s.io/kubectl/pkg/util/prune/prune.go","code":"// if namespace is explicitly specified, the default allow list should not include non-namespaced resources.\n// if pruneResources is specified by user, respect the user setting.\nfunc GetRESTMappings(mapper meta.RESTMapper, pruneResources []Resource, namespaceSpecified bool) (namespaced, nonNamespaced []*meta.RESTMapping, err error) {\n\tif len(pruneResources) == 0 {\n\t\tpruneResources = defaultNamespacedPruneResources\n\t\t// TODO in kubectl v1.29, add back non-namespaced resource only if namespace is not specified\n\t\tpruneResources = append(pruneResources, defaultNonNamespacedPruneResources...)\n\t\tif namespaceSpecified {\n\t\t\tklog.Warning(\"Deprecated: kubectl apply will no longer prune non-namespaced resources by default when used with the --namespace flag in a future release. To preserve the current behaviour, list the resources you want to target explicitly in the --prune-allowlist flag.\")\n\t\t}\n\t}\n\n\tfor _, resource := range pruneResources {\n\t\taddedMapping, err := mapper.RESTMapping(schema.GroupKind{Group: resource.group, Kind: resource.kind}, resource.version)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"invalid resource %v: %v\", resource, err)\n\t\t}\n\t\tif resource.namespaced {\n\t\t\tnamespaced = append(namespaced, addedMapping)\n\t\t} else {\n\t\t\tnonNamespaced = append(nonNamespaced, addedMapping)\n\t\t}\n\t}\n\n\treturn namespaced, nonNamespaced, nil\n}","line":{"from":63,"to":88}} {"id":100032927,"name":"ParseResources","signature":"func ParseResources(mapper meta.RESTMapper, gvks []string) ([]Resource, error)","file":"staging/src/k8s.io/kubectl/pkg/util/prune/prune.go","code":"func ParseResources(mapper meta.RESTMapper, gvks []string) ([]Resource, error) {\n\tpruneResources := []Resource{}\n\tfor _, groupVersionKind := range gvks {\n\t\tgvk := strings.Split(groupVersionKind, \"/\")\n\t\tif len(gvk) != 3 {\n\t\t\treturn nil, fmt.Errorf(\"invalid GroupVersionKind format: %v, please follow \u003cgroup/version/kind\u003e\", groupVersionKind)\n\t\t}\n\n\t\tif gvk[0] == \"core\" {\n\t\t\tgvk[0] = \"\"\n\t\t}\n\t\tmapping, err := mapper.RESTMapping(schema.GroupKind{Group: gvk[0], Kind: gvk[2]}, gvk[1])\n\t\tif err != nil {\n\t\t\treturn pruneResources, err\n\t\t}\n\t\tvar namespaced bool\n\t\tnamespaceScope := mapping.Scope.Name()\n\t\tswitch namespaceScope {\n\t\tcase meta.RESTScopeNameNamespace:\n\t\t\tnamespaced = true\n\t\tcase meta.RESTScopeNameRoot:\n\t\t\tnamespaced = false\n\t\tdefault:\n\t\t\treturn pruneResources, fmt.Errorf(\"Unknown namespace scope: %q\", namespaceScope)\n\t\t}\n\n\t\tpruneResources = append(pruneResources, Resource{gvk[0], gvk[1], gvk[2], namespaced})\n\t}\n\treturn pruneResources, nil\n}","line":{"from":90,"to":119}} {"id":100032928,"name":"isSupportedQoSComputeResource","signature":"func isSupportedQoSComputeResource(name core.ResourceName) bool","file":"staging/src/k8s.io/kubectl/pkg/util/qos/qos.go","code":"func isSupportedQoSComputeResource(name core.ResourceName) bool {\n\treturn supportedQoSComputeResources.Has(string(name))\n}","line":{"from":27,"to":29}} {"id":100032929,"name":"GetPodQOS","signature":"func GetPodQOS(pod *core.Pod) core.PodQOSClass","file":"staging/src/k8s.io/kubectl/pkg/util/qos/qos.go","code":"// GetPodQOS returns the QoS class of a pod.\n// A pod is besteffort if none of its containers have specified any requests or limits.\n// A pod is guaranteed only when requests and limits are specified for all the containers and they are equal.\n// A pod is burstable if limits and requests do not match across all containers.\nfunc GetPodQOS(pod *core.Pod) core.PodQOSClass {\n\trequests := core.ResourceList{}\n\tlimits := core.ResourceList{}\n\tzeroQuantity := resource.MustParse(\"0\")\n\tisGuaranteed := true\n\t// note, ephemeral containers are not considered for QoS as they cannot define resources\n\tallContainers := []core.Container{}\n\tallContainers = append(allContainers, pod.Spec.Containers...)\n\tallContainers = append(allContainers, pod.Spec.InitContainers...)\n\tfor _, container := range allContainers {\n\t\t// process requests\n\t\tfor name, quantity := range container.Resources.Requests {\n\t\t\tif !isSupportedQoSComputeResource(name) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif quantity.Cmp(zeroQuantity) == 1 {\n\t\t\t\tdelta := quantity.DeepCopy()\n\t\t\t\tif _, exists := requests[name]; !exists {\n\t\t\t\t\trequests[name] = delta\n\t\t\t\t} else {\n\t\t\t\t\tdelta.Add(requests[name])\n\t\t\t\t\trequests[name] = delta\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// process limits\n\t\tqosLimitsFound := sets.NewString()\n\t\tfor name, quantity := range container.Resources.Limits {\n\t\t\tif !isSupportedQoSComputeResource(name) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif quantity.Cmp(zeroQuantity) == 1 {\n\t\t\t\tqosLimitsFound.Insert(string(name))\n\t\t\t\tdelta := quantity.DeepCopy()\n\t\t\t\tif _, exists := limits[name]; !exists {\n\t\t\t\t\tlimits[name] = delta\n\t\t\t\t} else {\n\t\t\t\t\tdelta.Add(limits[name])\n\t\t\t\t\tlimits[name] = delta\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif !qosLimitsFound.HasAll(string(core.ResourceMemory), string(core.ResourceCPU)) {\n\t\t\tisGuaranteed = false\n\t\t}\n\t}\n\tif len(requests) == 0 \u0026\u0026 len(limits) == 0 {\n\t\treturn core.PodQOSBestEffort\n\t}\n\t// Check is requests match limits for all resources.\n\tif isGuaranteed {\n\t\tfor name, req := range requests {\n\t\t\tif lim, exists := limits[name]; !exists || lim.Cmp(req) != 0 {\n\t\t\t\tisGuaranteed = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif isGuaranteed \u0026\u0026\n\t\tlen(requests) == len(limits) {\n\t\treturn core.PodQOSGuaranteed\n\t}\n\treturn core.PodQOSBurstable\n}","line":{"from":31,"to":99}} {"id":100032930,"name":"CompactRules","signature":"func CompactRules(rules []rbacv1.PolicyRule) ([]rbacv1.PolicyRule, error)","file":"staging/src/k8s.io/kubectl/pkg/util/rbac/rbac.go","code":"// CompactRules combines rules that contain a single APIGroup/Resource, differ only by verb, and contain no other attributes.\n// this is a fast check, and works well with the decomposed \"missing rules\" list from a Covers check.\nfunc CompactRules(rules []rbacv1.PolicyRule) ([]rbacv1.PolicyRule, error) {\n\tcompacted := make([]rbacv1.PolicyRule, 0, len(rules))\n\n\tsimpleRules := map[simpleResource]*rbacv1.PolicyRule{}\n\tfor _, rule := range rules {\n\t\tif resource, isSimple := isSimpleResourceRule(\u0026rule); isSimple {\n\t\t\tif existingRule, ok := simpleRules[resource]; ok {\n\t\t\t\t// Add the new verbs to the existing simple resource rule\n\t\t\t\tif existingRule.Verbs == nil {\n\t\t\t\t\texistingRule.Verbs = []string{}\n\t\t\t\t}\n\t\t\t\texistingVerbs := sets.NewString(existingRule.Verbs...)\n\t\t\t\tfor _, verb := range rule.Verbs {\n\t\t\t\t\tif !existingVerbs.Has(verb) {\n\t\t\t\t\t\texistingRule.Verbs = append(existingRule.Verbs, verb)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\t// Copy the rule to accumulate matching simple resource rules into\n\t\t\t\tsimpleRules[resource] = rule.DeepCopy()\n\t\t\t}\n\t\t} else {\n\t\t\tcompacted = append(compacted, rule)\n\t\t}\n\t}\n\n\t// Once we've consolidated the simple resource rules, add them to the compacted list\n\tfor _, simpleRule := range simpleRules {\n\t\tcompacted = append(compacted, *simpleRule)\n\t}\n\n\treturn compacted, nil\n}","line":{"from":33,"to":68}} {"id":100032931,"name":"isSimpleResourceRule","signature":"func isSimpleResourceRule(rule *rbacv1.PolicyRule) (simpleResource, bool)","file":"staging/src/k8s.io/kubectl/pkg/util/rbac/rbac.go","code":"// isSimpleResourceRule returns true if the given rule contains verbs, a single resource, a single API group, at most one Resource Name, and no other values\nfunc isSimpleResourceRule(rule *rbacv1.PolicyRule) (simpleResource, bool) {\n\tresource := simpleResource{}\n\n\t// If we have \"complex\" rule attributes, return early without allocations or expensive comparisons\n\tif len(rule.ResourceNames) \u003e 1 || len(rule.NonResourceURLs) \u003e 0 {\n\t\treturn resource, false\n\t}\n\t// If we have multiple api groups or resources, return early\n\tif len(rule.APIGroups) != 1 || len(rule.Resources) != 1 {\n\t\treturn resource, false\n\t}\n\n\t// Test if this rule only contains APIGroups/Resources/Verbs/ResourceNames\n\tsimpleRule := \u0026rbacv1.PolicyRule{APIGroups: rule.APIGroups, Resources: rule.Resources, Verbs: rule.Verbs, ResourceNames: rule.ResourceNames}\n\tif !reflect.DeepEqual(simpleRule, rule) {\n\t\treturn resource, false\n\t}\n\n\tif len(rule.ResourceNames) == 0 {\n\t\tresource = simpleResource{Group: rule.APIGroups[0], Resource: rule.Resources[0], ResourceNameExist: false}\n\t} else {\n\t\tresource = simpleResource{Group: rule.APIGroups[0], Resource: rule.Resources[0], ResourceNameExist: true, ResourceName: rule.ResourceNames[0]}\n\t}\n\n\treturn resource, true\n}","line":{"from":70,"to":96}} {"id":100032932,"name":"BreakdownRule","signature":"func BreakdownRule(rule rbacv1.PolicyRule) []rbacv1.PolicyRule","file":"staging/src/k8s.io/kubectl/pkg/util/rbac/rbac.go","code":"// BreakdownRule takes a rule and builds an equivalent list of rules that each have at most one verb, one\n// resource, and one resource name\nfunc BreakdownRule(rule rbacv1.PolicyRule) []rbacv1.PolicyRule {\n\tsubrules := []rbacv1.PolicyRule{}\n\tfor _, group := range rule.APIGroups {\n\t\tfor _, resource := range rule.Resources {\n\t\t\tfor _, verb := range rule.Verbs {\n\t\t\t\tif len(rule.ResourceNames) \u003e 0 {\n\t\t\t\t\tfor _, resourceName := range rule.ResourceNames {\n\t\t\t\t\t\tsubrules = append(subrules, rbacv1.PolicyRule{APIGroups: []string{group}, Resources: []string{resource}, Verbs: []string{verb}, ResourceNames: []string{resourceName}})\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\tsubrules = append(subrules, rbacv1.PolicyRule{APIGroups: []string{group}, Resources: []string{resource}, Verbs: []string{verb}})\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\n\t// Non-resource URLs are unique because they only combine with verbs.\n\tfor _, nonResourceURL := range rule.NonResourceURLs {\n\t\tfor _, verb := range rule.Verbs {\n\t\t\tsubrules = append(subrules, rbacv1.PolicyRule{NonResourceURLs: []string{nonResourceURL}, Verbs: []string{verb}})\n\t\t}\n\t}\n\n\treturn subrules\n}","line":{"from":98,"to":126}} {"id":100032933,"name":"Len","signature":"func (s SortableRuleSlice) Len() int { return len(s) }","file":"staging/src/k8s.io/kubectl/pkg/util/rbac/rbac.go","code":"func (s SortableRuleSlice) Len() int { return len(s) }","line":{"from":131,"to":131}} {"id":100032934,"name":"Swap","signature":"func (s SortableRuleSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","file":"staging/src/k8s.io/kubectl/pkg/util/rbac/rbac.go","code":"func (s SortableRuleSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }","line":{"from":132,"to":132}} {"id":100032935,"name":"Less","signature":"func (s SortableRuleSlice) Less(i, j int) bool","file":"staging/src/k8s.io/kubectl/pkg/util/rbac/rbac.go","code":"func (s SortableRuleSlice) Less(i, j int) bool {\n\treturn strings.Compare(s[i].String(), s[j].String()) \u003c 0\n}","line":{"from":133,"to":135}} {"id":100032936,"name":"PodRequestsAndLimits","signature":"func PodRequestsAndLimits(pod *corev1.Pod) (reqs, limits corev1.ResourceList)","file":"staging/src/k8s.io/kubectl/pkg/util/resource/resource.go","code":"// PodRequestsAndLimits returns a dictionary of all defined resources summed up for all\n// containers of the pod. If pod overhead is non-nil, the pod overhead is added to the\n// total container resource requests and to the total container limits which have a\n// non-zero quantity.\nfunc PodRequestsAndLimits(pod *corev1.Pod) (reqs, limits corev1.ResourceList) {\n\treqs, limits = corev1.ResourceList{}, corev1.ResourceList{}\n\tfor _, container := range pod.Spec.Containers {\n\t\taddResourceList(reqs, container.Resources.Requests)\n\t\taddResourceList(limits, container.Resources.Limits)\n\t}\n\t// init containers define the minimum of any resource\n\tfor _, container := range pod.Spec.InitContainers {\n\t\tmaxResourceList(reqs, container.Resources.Requests)\n\t\tmaxResourceList(limits, container.Resources.Limits)\n\t}\n\n\t// Add overhead for running a pod to the sum of requests and to non-zero limits:\n\tif pod.Spec.Overhead != nil {\n\t\taddResourceList(reqs, pod.Spec.Overhead)\n\n\t\tfor name, quantity := range pod.Spec.Overhead {\n\t\t\tif value, ok := limits[name]; ok \u0026\u0026 !value.IsZero() {\n\t\t\t\tvalue.Add(quantity)\n\t\t\t\tlimits[name] = value\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}","line":{"from":30,"to":58}} {"id":100032937,"name":"addResourceList","signature":"func addResourceList(list, new corev1.ResourceList)","file":"staging/src/k8s.io/kubectl/pkg/util/resource/resource.go","code":"// addResourceList adds the resources in newList to list\nfunc addResourceList(list, new corev1.ResourceList) {\n\tfor name, quantity := range new {\n\t\tif value, ok := list[name]; !ok {\n\t\t\tlist[name] = quantity.DeepCopy()\n\t\t} else {\n\t\t\tvalue.Add(quantity)\n\t\t\tlist[name] = value\n\t\t}\n\t}\n}","line":{"from":60,"to":70}} {"id":100032938,"name":"maxResourceList","signature":"func maxResourceList(list, new corev1.ResourceList)","file":"staging/src/k8s.io/kubectl/pkg/util/resource/resource.go","code":"// maxResourceList sets list to the greater of list/newList for every resource\n// either list\nfunc maxResourceList(list, new corev1.ResourceList) {\n\tfor name, quantity := range new {\n\t\tif value, ok := list[name]; !ok {\n\t\t\tlist[name] = quantity.DeepCopy()\n\t\t\tcontinue\n\t\t} else {\n\t\t\tif quantity.Cmp(value) \u003e 0 {\n\t\t\t\tlist[name] = quantity.DeepCopy()\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":72,"to":85}} {"id":100032939,"name":"ExtractContainerResourceValue","signature":"func ExtractContainerResourceValue(fs *corev1.ResourceFieldSelector, container *corev1.Container) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/util/resource/resource.go","code":"// ExtractContainerResourceValue extracts the value of a resource\n// in an already known container\nfunc ExtractContainerResourceValue(fs *corev1.ResourceFieldSelector, container *corev1.Container) (string, error) {\n\tdivisor := resource.Quantity{}\n\tif divisor.Cmp(fs.Divisor) == 0 {\n\t\tdivisor = resource.MustParse(\"1\")\n\t} else {\n\t\tdivisor = fs.Divisor\n\t}\n\n\tswitch fs.Resource {\n\tcase \"limits.cpu\":\n\t\treturn convertResourceCPUToString(container.Resources.Limits.Cpu(), divisor)\n\tcase \"limits.memory\":\n\t\treturn convertResourceMemoryToString(container.Resources.Limits.Memory(), divisor)\n\tcase \"limits.ephemeral-storage\":\n\t\treturn convertResourceEphemeralStorageToString(container.Resources.Limits.StorageEphemeral(), divisor)\n\tcase \"requests.cpu\":\n\t\treturn convertResourceCPUToString(container.Resources.Requests.Cpu(), divisor)\n\tcase \"requests.memory\":\n\t\treturn convertResourceMemoryToString(container.Resources.Requests.Memory(), divisor)\n\tcase \"requests.ephemeral-storage\":\n\t\treturn convertResourceEphemeralStorageToString(container.Resources.Requests.StorageEphemeral(), divisor)\n\t}\n\t// handle extended standard resources with dynamic names\n\t// example: requests.hugepages-\u003cpageSize\u003e or limits.hugepages-\u003cpageSize\u003e\n\tif strings.HasPrefix(fs.Resource, \"requests.\") {\n\t\tresourceName := corev1.ResourceName(strings.TrimPrefix(fs.Resource, \"requests.\"))\n\t\tif IsHugePageResourceName(resourceName) {\n\t\t\treturn convertResourceHugePagesToString(container.Resources.Requests.Name(resourceName, resource.BinarySI), divisor)\n\t\t}\n\t}\n\tif strings.HasPrefix(fs.Resource, \"limits.\") {\n\t\tresourceName := corev1.ResourceName(strings.TrimPrefix(fs.Resource, \"limits.\"))\n\t\tif IsHugePageResourceName(resourceName) {\n\t\t\treturn convertResourceHugePagesToString(container.Resources.Limits.Name(resourceName, resource.BinarySI), divisor)\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"Unsupported container resource : %v\", fs.Resource)\n}","line":{"from":87,"to":126}} {"id":100032940,"name":"convertResourceCPUToString","signature":"func convertResourceCPUToString(cpu *resource.Quantity, divisor resource.Quantity) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/util/resource/resource.go","code":"// convertResourceCPUToString converts cpu value to the format of divisor and returns\n// ceiling of the value.\nfunc convertResourceCPUToString(cpu *resource.Quantity, divisor resource.Quantity) (string, error) {\n\tc := int64(math.Ceil(float64(cpu.MilliValue()) / float64(divisor.MilliValue())))\n\treturn strconv.FormatInt(c, 10), nil\n}","line":{"from":128,"to":133}} {"id":100032941,"name":"convertResourceMemoryToString","signature":"func convertResourceMemoryToString(memory *resource.Quantity, divisor resource.Quantity) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/util/resource/resource.go","code":"// convertResourceMemoryToString converts memory value to the format of divisor and returns\n// ceiling of the value.\nfunc convertResourceMemoryToString(memory *resource.Quantity, divisor resource.Quantity) (string, error) {\n\tm := int64(math.Ceil(float64(memory.Value()) / float64(divisor.Value())))\n\treturn strconv.FormatInt(m, 10), nil\n}","line":{"from":135,"to":140}} {"id":100032942,"name":"convertResourceHugePagesToString","signature":"func convertResourceHugePagesToString(hugePages *resource.Quantity, divisor resource.Quantity) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/util/resource/resource.go","code":"// convertResourceHugePagesToString converts hugepages value to the format of divisor and returns\n// ceiling of the value.\nfunc convertResourceHugePagesToString(hugePages *resource.Quantity, divisor resource.Quantity) (string, error) {\n\tm := int64(math.Ceil(float64(hugePages.Value()) / float64(divisor.Value())))\n\treturn strconv.FormatInt(m, 10), nil\n}","line":{"from":142,"to":147}} {"id":100032943,"name":"convertResourceEphemeralStorageToString","signature":"func convertResourceEphemeralStorageToString(ephemeralStorage *resource.Quantity, divisor resource.Quantity) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/util/resource/resource.go","code":"// convertResourceEphemeralStorageToString converts ephemeral storage value to the format of divisor and returns\n// ceiling of the value.\nfunc convertResourceEphemeralStorageToString(ephemeralStorage *resource.Quantity, divisor resource.Quantity) (string, error) {\n\tm := int64(math.Ceil(float64(ephemeralStorage.Value()) / float64(divisor.Value())))\n\treturn strconv.FormatInt(m, 10), nil\n}","line":{"from":149,"to":154}} {"id":100032944,"name":"IsStandardContainerResourceName","signature":"func IsStandardContainerResourceName(str string) bool","file":"staging/src/k8s.io/kubectl/pkg/util/resource/resource.go","code":"// IsStandardContainerResourceName returns true if the container can make a resource request\n// for the specified resource\nfunc IsStandardContainerResourceName(str string) bool {\n\treturn standardContainerResources.Has(str) || IsHugePageResourceName(corev1.ResourceName(str))\n}","line":{"from":162,"to":166}} {"id":100032945,"name":"IsHugePageResourceName","signature":"func IsHugePageResourceName(name corev1.ResourceName) bool","file":"staging/src/k8s.io/kubectl/pkg/util/resource/resource.go","code":"// IsHugePageResourceName returns true if the resource name has the huge page\n// resource prefix.\nfunc IsHugePageResourceName(name corev1.ResourceName) bool {\n\treturn strings.HasPrefix(string(name), corev1.ResourceHugePagesPrefix)\n}","line":{"from":168,"to":172}} {"id":100032946,"name":"LookupContainerPortNumberByServicePort","signature":"func LookupContainerPortNumberByServicePort(svc v1.Service, pod v1.Pod, port int32) (int32, error)","file":"staging/src/k8s.io/kubectl/pkg/util/service_port.go","code":"// LookupContainerPortNumberByServicePort implements\n// the handling of resolving container named port, as well as ignoring targetPort when clusterIP=None\n// It returns an error when a named port can't find a match (with -1 returned), or when the service does not\n// declare such port (with the input port number returned).\nfunc LookupContainerPortNumberByServicePort(svc v1.Service, pod v1.Pod, port int32) (int32, error) {\n\tfor _, svcportspec := range svc.Spec.Ports {\n\t\tif svcportspec.Port != port {\n\t\t\tcontinue\n\t\t}\n\t\tif svc.Spec.ClusterIP == v1.ClusterIPNone {\n\t\t\treturn port, nil\n\t\t}\n\t\tif svcportspec.TargetPort.Type == intstr.Int {\n\t\t\tif svcportspec.TargetPort.IntValue() == 0 {\n\t\t\t\t// targetPort is omitted, and the IntValue() would be zero\n\t\t\t\treturn svcportspec.Port, nil\n\t\t\t}\n\t\t\treturn int32(svcportspec.TargetPort.IntValue()), nil\n\t\t}\n\t\treturn LookupContainerPortNumberByName(pod, svcportspec.TargetPort.String())\n\t}\n\treturn port, fmt.Errorf(\"Service %s does not have a service port %d\", svc.Name, port)\n}","line":{"from":26,"to":48}} {"id":100032947,"name":"LookupServicePortNumberByName","signature":"func LookupServicePortNumberByName(svc v1.Service, name string) (int32, error)","file":"staging/src/k8s.io/kubectl/pkg/util/service_port.go","code":"// LookupServicePortNumberByName find service port number by its named port name\nfunc LookupServicePortNumberByName(svc v1.Service, name string) (int32, error) {\n\tfor _, svcportspec := range svc.Spec.Ports {\n\t\tif svcportspec.Name == name {\n\t\t\treturn svcportspec.Port, nil\n\t\t}\n\t}\n\n\treturn int32(-1), fmt.Errorf(\"Service '%s' does not have a named port '%s'\", svc.Name, name)\n}","line":{"from":50,"to":59}} {"id":100032948,"name":"SortInts64","signature":"func SortInts64(a []int64) { sort.Slice(a, func(i, j int) bool { return a[i] \u003c a[j] }) }","file":"staging/src/k8s.io/kubectl/pkg/util/slice/slice.go","code":"// SortInts64 sorts []int64 in increasing order\nfunc SortInts64(a []int64) { sort.Slice(a, func(i, j int) bool { return a[i] \u003c a[j] }) }","line":{"from":23,"to":24}} {"id":100032949,"name":"ContainsString","signature":"func ContainsString(slice []string, s string, modifier func(s string) string) bool","file":"staging/src/k8s.io/kubectl/pkg/util/slice/slice.go","code":"// ContainsString checks if a given slice of strings contains the provided string.\n// If a modifier func is provided, it is called with the slice item before the comparation.\nfunc ContainsString(slice []string, s string, modifier func(s string) string) bool {\n\tfor _, item := range slice {\n\t\tif item == s {\n\t\t\treturn true\n\t\t}\n\t\tif modifier != nil \u0026\u0026 modifier(item) == s {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":26,"to":38}} {"id":100032950,"name":"ToSet","signature":"func ToSet[T comparable](slices ...[]T) []T","file":"staging/src/k8s.io/kubectl/pkg/util/slice/slice.go","code":"// ToSet returns a single slice containing the unique values from one or more slices. The order of the items in the\n// result is not guaranteed.\nfunc ToSet[T comparable](slices ...[]T) []T {\n\tif len(slices) == 0 {\n\t\treturn nil\n\t}\n\tm := map[T]struct{}{}\n\tfor _, slice := range slices {\n\t\tfor _, value := range slice {\n\t\t\tm[value] = struct{}{}\n\t\t}\n\t}\n\tresult := []T{}\n\tfor k := range m {\n\t\tresult = append(result, k)\n\t}\n\treturn result\n}","line":{"from":40,"to":57}} {"id":100032951,"name":"IsDefaultAnnotationText","signature":"func IsDefaultAnnotationText(obj metav1.ObjectMeta) string","file":"staging/src/k8s.io/kubectl/pkg/util/storage/storage.go","code":"// IsDefaultAnnotationText returns a pretty Yes/No String if\n// the annotation is set\nfunc IsDefaultAnnotationText(obj metav1.ObjectMeta) string {\n\tif obj.Annotations[IsDefaultStorageClassAnnotation] == \"true\" {\n\t\treturn \"Yes\"\n\t}\n\tif obj.Annotations[BetaIsDefaultStorageClassAnnotation] == \"true\" {\n\t\treturn \"Yes\"\n\t}\n\n\treturn \"No\"\n}","line":{"from":34,"to":45}} {"id":100032952,"name":"GetAccessModesAsString","signature":"func GetAccessModesAsString(modes []v1.PersistentVolumeAccessMode) string","file":"staging/src/k8s.io/kubectl/pkg/util/storage/storage.go","code":"// GetAccessModesAsString returns a string representation of an array of access modes.\n// modes, when present, are always in the same order: RWO,ROX,RWX,RWOP.\nfunc GetAccessModesAsString(modes []v1.PersistentVolumeAccessMode) string {\n\tmodes = removeDuplicateAccessModes(modes)\n\tmodesStr := []string{}\n\tif ContainsAccessMode(modes, v1.ReadWriteOnce) {\n\t\tmodesStr = append(modesStr, \"RWO\")\n\t}\n\tif ContainsAccessMode(modes, v1.ReadOnlyMany) {\n\t\tmodesStr = append(modesStr, \"ROX\")\n\t}\n\tif ContainsAccessMode(modes, v1.ReadWriteMany) {\n\t\tmodesStr = append(modesStr, \"RWX\")\n\t}\n\tif ContainsAccessMode(modes, v1.ReadWriteOncePod) {\n\t\tmodesStr = append(modesStr, \"RWOP\")\n\t}\n\treturn strings.Join(modesStr, \",\")\n}","line":{"from":47,"to":65}} {"id":100032953,"name":"removeDuplicateAccessModes","signature":"func removeDuplicateAccessModes(modes []v1.PersistentVolumeAccessMode) []v1.PersistentVolumeAccessMode","file":"staging/src/k8s.io/kubectl/pkg/util/storage/storage.go","code":"// removeDuplicateAccessModes returns an array of access modes without any duplicates\nfunc removeDuplicateAccessModes(modes []v1.PersistentVolumeAccessMode) []v1.PersistentVolumeAccessMode {\n\taccessModes := []v1.PersistentVolumeAccessMode{}\n\tfor _, m := range modes {\n\t\tif !ContainsAccessMode(accessModes, m) {\n\t\t\taccessModes = append(accessModes, m)\n\t\t}\n\t}\n\treturn accessModes\n}","line":{"from":67,"to":76}} {"id":100032954,"name":"ContainsAccessMode","signature":"func ContainsAccessMode(modes []v1.PersistentVolumeAccessMode, mode v1.PersistentVolumeAccessMode) bool","file":"staging/src/k8s.io/kubectl/pkg/util/storage/storage.go","code":"func ContainsAccessMode(modes []v1.PersistentVolumeAccessMode, mode v1.PersistentVolumeAccessMode) bool {\n\tfor _, m := range modes {\n\t\tif m == mode {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":78,"to":85}} {"id":100032955,"name":"GetPersistentVolumeClass","signature":"func GetPersistentVolumeClass(volume *v1.PersistentVolume) string","file":"staging/src/k8s.io/kubectl/pkg/util/storage/storage.go","code":"// GetPersistentVolumeClass returns StorageClassName.\nfunc GetPersistentVolumeClass(volume *v1.PersistentVolume) string {\n\t// Use beta annotation first\n\tif class, found := volume.Annotations[v1.BetaStorageClassAnnotation]; found {\n\t\treturn class\n\t}\n\n\treturn volume.Spec.StorageClassName\n}","line":{"from":87,"to":95}} {"id":100032956,"name":"GetPersistentVolumeClaimClass","signature":"func GetPersistentVolumeClaimClass(claim *v1.PersistentVolumeClaim) string","file":"staging/src/k8s.io/kubectl/pkg/util/storage/storage.go","code":"// GetPersistentVolumeClaimClass returns StorageClassName. If no storage class was\n// requested, it returns \"\".\nfunc GetPersistentVolumeClaimClass(claim *v1.PersistentVolumeClaim) string {\n\t// Use beta annotation first\n\tif class, found := claim.Annotations[v1.BetaStorageClassAnnotation]; found {\n\t\treturn class\n\t}\n\n\tif claim.Spec.StorageClassName != nil {\n\t\treturn *claim.Spec.StorageClassName\n\t}\n\n\treturn \"\"\n}","line":{"from":97,"to":110}} {"id":100032957,"name":"Add","signature":"func (g CommandGroups) Add(c *cobra.Command)","file":"staging/src/k8s.io/kubectl/pkg/util/templates/command_groups.go","code":"func (g CommandGroups) Add(c *cobra.Command) {\n\tfor _, group := range g {\n\t\tc.AddCommand(group.Commands...)\n\t}\n}","line":{"from":30,"to":34}} {"id":100032958,"name":"Has","signature":"func (g CommandGroups) Has(c *cobra.Command) bool","file":"staging/src/k8s.io/kubectl/pkg/util/templates/command_groups.go","code":"func (g CommandGroups) Has(c *cobra.Command) bool {\n\tfor _, group := range g {\n\t\tfor _, command := range group.Commands {\n\t\t\tif command == c {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}","line":{"from":36,"to":45}} {"id":100032959,"name":"AddAdditionalCommands","signature":"func AddAdditionalCommands(g CommandGroups, message string, cmds []*cobra.Command) CommandGroups","file":"staging/src/k8s.io/kubectl/pkg/util/templates/command_groups.go","code":"func AddAdditionalCommands(g CommandGroups, message string, cmds []*cobra.Command) CommandGroups {\n\tgroup := CommandGroup{Message: message}\n\tfor _, c := range cmds {\n\t\t// Don't show commands that have no short description\n\t\tif !g.Has(c) \u0026\u0026 len(c.Short) != 0 {\n\t\t\tgroup.Commands = append(group.Commands, c)\n\t\t}\n\t}\n\tif len(group.Commands) == 0 {\n\t\treturn g\n\t}\n\treturn append(g, group)\n}","line":{"from":47,"to":59}} {"id":100032960,"name":"NewHelpFlagPrinter","signature":"func NewHelpFlagPrinter(out io.Writer, wrapLimit uint) *HelpFlagPrinter","file":"staging/src/k8s.io/kubectl/pkg/util/templates/help_flags_printer.go","code":"// NewHelpFlagPrinter will initialize a HelpFlagPrinter given the\n// i/o writer\nfunc NewHelpFlagPrinter(out io.Writer, wrapLimit uint) *HelpFlagPrinter {\n\treturn \u0026HelpFlagPrinter{\n\t\twrapLimit: wrapLimit,\n\t\tout: out,\n\t}\n}","line":{"from":39,"to":46}} {"id":100032961,"name":"PrintHelpFlag","signature":"func (p *HelpFlagPrinter) PrintHelpFlag(flag *flag.Flag)","file":"staging/src/k8s.io/kubectl/pkg/util/templates/help_flags_printer.go","code":"// PrintHelpFlag will beautify the help flags and print it out to p.out\nfunc (p *HelpFlagPrinter) PrintHelpFlag(flag *flag.Flag) {\n\tformatBuf := new(bytes.Buffer)\n\twriteFlag(formatBuf, flag)\n\n\twrappedStr := formatBuf.String()\n\tflagAndUsage := strings.Split(formatBuf.String(), \"\\n\")\n\tflagStr := flagAndUsage[0]\n\n\t// if the flag usage is longer than one line, wrap it again\n\tif len(flagAndUsage) \u003e 1 {\n\t\tnextLines := strings.Join(flagAndUsage[1:], \" \")\n\t\twrappedUsages := wordwrap.WrapString(nextLines, p.wrapLimit-offset)\n\t\twrappedStr = flagStr + \"\\n\" + wrappedUsages\n\t}\n\tappendTabStr := strings.ReplaceAll(wrappedStr, \"\\n\", \"\\n\\t\")\n\n\tfmt.Fprintf(p.out, appendTabStr+\"\\n\\n\")\n}","line":{"from":48,"to":66}} {"id":100032962,"name":"writeFlag","signature":"func writeFlag(out io.Writer, f *flag.Flag)","file":"staging/src/k8s.io/kubectl/pkg/util/templates/help_flags_printer.go","code":"// writeFlag will output the help flag based\n// on the format provided by getFlagFormat to i/o writer\nfunc writeFlag(out io.Writer, f *flag.Flag) {\n\tdeprecated := \"\"\n\tif f.Deprecated != \"\" {\n\t\tdeprecated = fmt.Sprintf(\" (DEPRECATED: %s)\", f.Deprecated)\n\t}\n\tfmt.Fprintf(out, getFlagFormat(f), f.Shorthand, f.Name, f.DefValue, f.Usage, deprecated)\n}","line":{"from":68,"to":76}} {"id":100032963,"name":"RenderNode","signature":"func (r *ASCIIRenderer) RenderNode(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus","file":"staging/src/k8s.io/kubectl/pkg/util/templates/markdown.go","code":"// render markdown to text\nfunc (r *ASCIIRenderer) RenderNode(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus {\n\tswitch node.Type {\n\tcase blackfriday.Text:\n\t\traw := string(node.Literal)\n\t\tlines := strings.Split(raw, linebreak)\n\t\tfor _, line := range lines {\n\t\t\ttrimmed := strings.Trim(line, \" \\n\\t\")\n\t\t\tif len(trimmed) \u003e 0 \u0026\u0026 trimmed[0] != '_' {\n\t\t\t\tw.Write([]byte(\" \"))\n\t\t\t}\n\t\t\tw.Write([]byte(trimmed))\n\t\t}\n\tcase blackfriday.HorizontalRule, blackfriday.Hardbreak:\n\t\tw.Write([]byte(linebreak + \"----------\" + linebreak))\n\tcase blackfriday.Code, blackfriday.CodeBlock:\n\t\tw.Write([]byte(linebreak))\n\t\tlines := []string{}\n\t\tfor _, line := range strings.Split(string(node.Literal), linebreak) {\n\t\t\ttrimmed := strings.Trim(line, \" \\t\")\n\t\t\tindented := r.Indentation + trimmed\n\t\t\tlines = append(lines, indented)\n\t\t}\n\t\tw.Write([]byte(strings.Join(lines, linebreak)))\n\tcase blackfriday.Image:\n\t\tw.Write(node.LinkData.Destination)\n\tcase blackfriday.Link:\n\t\tw.Write([]byte(\" \"))\n\t\tw.Write(node.LinkData.Destination)\n\tcase blackfriday.Paragraph:\n\t\tif r.listLevel == 0 {\n\t\t\tw.Write([]byte(linebreak))\n\t\t}\n\tcase blackfriday.List:\n\t\tif entering {\n\t\t\tw.Write([]byte(linebreak))\n\t\t\tr.listLevel++\n\t\t} else {\n\t\t\tr.listLevel--\n\t\t\tr.listItemCount = 0\n\t\t}\n\tcase blackfriday.Item:\n\t\tif entering {\n\t\t\tr.listItemCount++\n\t\t\tfor i := 0; uint(i) \u003c r.listLevel; i++ {\n\t\t\t\tw.Write([]byte(r.Indentation))\n\t\t\t}\n\t\t\tif node.ListFlags\u0026blackfriday.ListTypeOrdered != 0 {\n\t\t\t\tw.Write([]byte(fmt.Sprintf(\"%d. \", r.listItemCount)))\n\t\t\t} else {\n\t\t\t\tw.Write([]byte(\"* \"))\n\t\t\t}\n\t\t} else {\n\t\t\tw.Write([]byte(linebreak))\n\t\t}\n\tdefault:\n\t\tnormalText(w, node.Literal)\n\t}\n\treturn blackfriday.GoToNext\n}","line":{"from":41,"to":100}} {"id":100032964,"name":"normalText","signature":"func normalText(w io.Writer, text []byte)","file":"staging/src/k8s.io/kubectl/pkg/util/templates/markdown.go","code":"func normalText(w io.Writer, text []byte) {\n\tw.Write([]byte(strings.Trim(string(text), \" \\n\\t\")))\n}","line":{"from":102,"to":104}} {"id":100032965,"name":"RenderHeader","signature":"func (r *ASCIIRenderer) RenderHeader(w io.Writer, ast *blackfriday.Node)","file":"staging/src/k8s.io/kubectl/pkg/util/templates/markdown.go","code":"// RenderHeader writes document preamble and TOC if requested.\nfunc (r *ASCIIRenderer) RenderHeader(w io.Writer, ast *blackfriday.Node) {\n\n}","line":{"from":106,"to":109}} {"id":100032966,"name":"RenderFooter","signature":"func (r *ASCIIRenderer) RenderFooter(w io.Writer, ast *blackfriday.Node)","file":"staging/src/k8s.io/kubectl/pkg/util/templates/markdown.go","code":"// RenderFooter writes document footer.\nfunc (r *ASCIIRenderer) RenderFooter(w io.Writer, ast *blackfriday.Node) {\n\tio.WriteString(w, \"\\n\")\n}","line":{"from":111,"to":114}} {"id":100032967,"name":"LongDesc","signature":"func LongDesc(s string) string","file":"staging/src/k8s.io/kubectl/pkg/util/templates/normalizers.go","code":"// LongDesc normalizes a command's long description to follow the conventions.\nfunc LongDesc(s string) string {\n\tif len(s) == 0 {\n\t\treturn s\n\t}\n\treturn normalizer{s}.heredoc().markdown().trim().string\n}","line":{"from":29,"to":35}} {"id":100032968,"name":"Examples","signature":"func Examples(s string) string","file":"staging/src/k8s.io/kubectl/pkg/util/templates/normalizers.go","code":"// Examples normalizes a command's examples to follow the conventions.\nfunc Examples(s string) string {\n\tif len(s) == 0 {\n\t\treturn s\n\t}\n\treturn normalizer{s}.trim().indent().string\n}","line":{"from":37,"to":43}} {"id":100032969,"name":"Normalize","signature":"func Normalize(cmd *cobra.Command) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/util/templates/normalizers.go","code":"// Normalize perform all required normalizations on a given command.\nfunc Normalize(cmd *cobra.Command) *cobra.Command {\n\tif len(cmd.Long) \u003e 0 {\n\t\tcmd.Long = LongDesc(cmd.Long)\n\t}\n\tif len(cmd.Example) \u003e 0 {\n\t\tcmd.Example = Examples(cmd.Example)\n\t}\n\treturn cmd\n}","line":{"from":45,"to":54}} {"id":100032970,"name":"NormalizeAll","signature":"func NormalizeAll(cmd *cobra.Command) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/util/templates/normalizers.go","code":"// NormalizeAll perform all required normalizations in the entire command tree.\nfunc NormalizeAll(cmd *cobra.Command) *cobra.Command {\n\tif cmd.HasSubCommands() {\n\t\tfor _, subCmd := range cmd.Commands() {\n\t\t\tNormalizeAll(subCmd)\n\t\t}\n\t}\n\tNormalize(cmd)\n\treturn cmd\n}","line":{"from":56,"to":65}} {"id":100032971,"name":"markdown","signature":"func (s normalizer) markdown() normalizer","file":"staging/src/k8s.io/kubectl/pkg/util/templates/normalizers.go","code":"func (s normalizer) markdown() normalizer {\n\tbytes := []byte(s.string)\n\tformatted := blackfriday.Run(bytes, blackfriday.WithExtensions(blackfriday.NoIntraEmphasis), blackfriday.WithRenderer(\u0026ASCIIRenderer{Indentation: Indentation}))\n\ts.string = string(formatted)\n\treturn s\n}","line":{"from":71,"to":76}} {"id":100032972,"name":"heredoc","signature":"func (s normalizer) heredoc() normalizer","file":"staging/src/k8s.io/kubectl/pkg/util/templates/normalizers.go","code":"func (s normalizer) heredoc() normalizer {\n\ts.string = heredoc.Doc(s.string)\n\treturn s\n}","line":{"from":78,"to":81}} {"id":100032973,"name":"trim","signature":"func (s normalizer) trim() normalizer","file":"staging/src/k8s.io/kubectl/pkg/util/templates/normalizers.go","code":"func (s normalizer) trim() normalizer {\n\ts.string = strings.TrimSpace(s.string)\n\treturn s\n}","line":{"from":83,"to":86}} {"id":100032974,"name":"indent","signature":"func (s normalizer) indent() normalizer","file":"staging/src/k8s.io/kubectl/pkg/util/templates/normalizers.go","code":"func (s normalizer) indent() normalizer {\n\tindentedLines := []string{}\n\tfor _, line := range strings.Split(s.string, \"\\n\") {\n\t\ttrimmed := strings.TrimSpace(line)\n\t\tindented := Indentation + trimmed\n\t\tindentedLines = append(indentedLines, indented)\n\t}\n\ts.string = strings.Join(indentedLines, \"\\n\")\n\treturn s\n}","line":{"from":88,"to":97}} {"id":100032975,"name":"ActsAsRootCommand","signature":"func ActsAsRootCommand(cmd *cobra.Command, filters []string, groups ...CommandGroup) FlagExposer","file":"staging/src/k8s.io/kubectl/pkg/util/templates/templater.go","code":"func ActsAsRootCommand(cmd *cobra.Command, filters []string, groups ...CommandGroup) FlagExposer {\n\tif cmd == nil {\n\t\tpanic(\"nil root command\")\n\t}\n\ttemplater := \u0026templater{\n\t\tRootCmd: cmd,\n\t\tUsageTemplate: MainUsageTemplate(),\n\t\tHelpTemplate: MainHelpTemplate(),\n\t\tCommandGroups: groups,\n\t\tFiltered: filters,\n\t}\n\tcmd.SetFlagErrorFunc(templater.FlagErrorFunc())\n\tcmd.SilenceUsage = true\n\tcmd.SetUsageFunc(templater.UsageFunc())\n\tcmd.SetHelpFunc(templater.HelpFunc())\n\treturn templater\n}","line":{"from":36,"to":52}} {"id":100032976,"name":"UseOptionsTemplates","signature":"func UseOptionsTemplates(cmd *cobra.Command)","file":"staging/src/k8s.io/kubectl/pkg/util/templates/templater.go","code":"func UseOptionsTemplates(cmd *cobra.Command) {\n\ttemplater := \u0026templater{\n\t\tUsageTemplate: OptionsUsageTemplate(),\n\t\tHelpTemplate: OptionsHelpTemplate(),\n\t}\n\tcmd.SetUsageFunc(templater.UsageFunc())\n\tcmd.SetHelpFunc(templater.HelpFunc())\n}","line":{"from":54,"to":61}} {"id":100032977,"name":"FlagErrorFunc","signature":"func (templater *templater) FlagErrorFunc(exposedFlags ...string) func(*cobra.Command, error) error","file":"staging/src/k8s.io/kubectl/pkg/util/templates/templater.go","code":"func (templater *templater) FlagErrorFunc(exposedFlags ...string) func(*cobra.Command, error) error {\n\treturn func(c *cobra.Command, err error) error {\n\t\tc.SilenceUsage = true\n\t\tswitch c.CalledAs() {\n\t\tcase \"options\":\n\t\t\treturn fmt.Errorf(\"%s\\nRun '%s' without flags.\", err, c.CommandPath())\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"%s\\nSee '%s --help' for usage.\", err, c.CommandPath())\n\t\t}\n\t}\n}","line":{"from":71,"to":81}} {"id":100032978,"name":"ExposeFlags","signature":"func (templater *templater) ExposeFlags(cmd *cobra.Command, flags ...string) FlagExposer","file":"staging/src/k8s.io/kubectl/pkg/util/templates/templater.go","code":"func (templater *templater) ExposeFlags(cmd *cobra.Command, flags ...string) FlagExposer {\n\tcmd.SetUsageFunc(templater.UsageFunc(flags...))\n\treturn templater\n}","line":{"from":83,"to":86}} {"id":100032979,"name":"HelpFunc","signature":"func (templater *templater) HelpFunc() func(*cobra.Command, []string)","file":"staging/src/k8s.io/kubectl/pkg/util/templates/templater.go","code":"func (templater *templater) HelpFunc() func(*cobra.Command, []string) {\n\treturn func(c *cobra.Command, s []string) {\n\t\tt := template.New(\"help\")\n\t\tt.Funcs(templater.templateFuncs())\n\t\ttemplate.Must(t.Parse(templater.HelpTemplate))\n\t\tout := term.NewResponsiveWriter(c.OutOrStdout())\n\t\terr := t.Execute(out, c)\n\t\tif err != nil {\n\t\t\tc.Println(err)\n\t\t}\n\t}\n}","line":{"from":88,"to":99}} {"id":100032980,"name":"UsageFunc","signature":"func (templater *templater) UsageFunc(exposedFlags ...string) func(*cobra.Command) error","file":"staging/src/k8s.io/kubectl/pkg/util/templates/templater.go","code":"func (templater *templater) UsageFunc(exposedFlags ...string) func(*cobra.Command) error {\n\treturn func(c *cobra.Command) error {\n\t\tt := template.New(\"usage\")\n\t\tt.Funcs(templater.templateFuncs(exposedFlags...))\n\t\ttemplate.Must(t.Parse(templater.UsageTemplate))\n\t\tout := term.NewResponsiveWriter(c.OutOrStderr())\n\t\treturn t.Execute(out, c)\n\t}\n}","line":{"from":101,"to":109}} {"id":100032981,"name":"templateFuncs","signature":"func (templater *templater) templateFuncs(exposedFlags ...string) template.FuncMap","file":"staging/src/k8s.io/kubectl/pkg/util/templates/templater.go","code":"func (templater *templater) templateFuncs(exposedFlags ...string) template.FuncMap {\n\treturn template.FuncMap{\n\t\t\"trim\": strings.TrimSpace,\n\t\t\"trimRight\": func(s string) string { return strings.TrimRightFunc(s, unicode.IsSpace) },\n\t\t\"trimLeft\": func(s string) string { return strings.TrimLeftFunc(s, unicode.IsSpace) },\n\t\t\"gt\": cobra.Gt,\n\t\t\"eq\": cobra.Eq,\n\t\t\"rpad\": rpad,\n\t\t\"appendIfNotPresent\": appendIfNotPresent,\n\t\t\"flagsNotIntersected\": flagsNotIntersected,\n\t\t\"visibleFlags\": visibleFlags,\n\t\t\"flagsUsages\": flagsUsages,\n\t\t\"cmdGroups\": templater.cmdGroups,\n\t\t\"cmdGroupsString\": templater.cmdGroupsString,\n\t\t\"rootCmd\": templater.rootCmdName,\n\t\t\"isRootCmd\": templater.isRootCmd,\n\t\t\"optionsCmdFor\": templater.optionsCmdFor,\n\t\t\"usageLine\": templater.usageLine,\n\t\t\"exposed\": func(c *cobra.Command) *flag.FlagSet {\n\t\t\texposed := flag.NewFlagSet(\"exposed\", flag.ContinueOnError)\n\t\t\tif len(exposedFlags) \u003e 0 {\n\t\t\t\tfor _, name := range exposedFlags {\n\t\t\t\t\tif flag := c.Flags().Lookup(name); flag != nil {\n\t\t\t\t\t\texposed.AddFlag(flag)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn exposed\n\t\t},\n\t}\n}","line":{"from":111,"to":141}} {"id":100032982,"name":"cmdGroups","signature":"func (templater *templater) cmdGroups(c *cobra.Command, all []*cobra.Command) []CommandGroup","file":"staging/src/k8s.io/kubectl/pkg/util/templates/templater.go","code":"func (templater *templater) cmdGroups(c *cobra.Command, all []*cobra.Command) []CommandGroup {\n\tif len(templater.CommandGroups) \u003e 0 \u0026\u0026 c == templater.RootCmd {\n\t\tall = filter(all, templater.Filtered...)\n\t\treturn AddAdditionalCommands(templater.CommandGroups, \"Other Commands:\", all)\n\t}\n\tall = filter(all, \"options\")\n\treturn []CommandGroup{\n\t\t{\n\t\t\tMessage: \"Available Commands:\",\n\t\t\tCommands: all,\n\t\t},\n\t}\n}","line":{"from":143,"to":155}} {"id":100032983,"name":"cmdGroupsString","signature":"func (t *templater) cmdGroupsString(c *cobra.Command) string","file":"staging/src/k8s.io/kubectl/pkg/util/templates/templater.go","code":"func (t *templater) cmdGroupsString(c *cobra.Command) string {\n\tgroups := []string{}\n\tfor _, cmdGroup := range t.cmdGroups(c, c.Commands()) {\n\t\tcmds := []string{cmdGroup.Message}\n\t\tfor _, cmd := range cmdGroup.Commands {\n\t\t\tif cmd.IsAvailableCommand() {\n\t\t\t\tcmds = append(cmds, \" \"+rpad(cmd.Name(), cmd.NamePadding())+\" \"+cmd.Short)\n\t\t\t}\n\t\t}\n\t\tgroups = append(groups, strings.Join(cmds, \"\\n\"))\n\t}\n\treturn strings.Join(groups, \"\\n\\n\")\n}","line":{"from":157,"to":169}} {"id":100032984,"name":"rootCmdName","signature":"func (t *templater) rootCmdName(c *cobra.Command) string","file":"staging/src/k8s.io/kubectl/pkg/util/templates/templater.go","code":"func (t *templater) rootCmdName(c *cobra.Command) string {\n\treturn t.rootCmd(c).CommandPath()\n}","line":{"from":171,"to":173}} {"id":100032985,"name":"isRootCmd","signature":"func (t *templater) isRootCmd(c *cobra.Command) bool","file":"staging/src/k8s.io/kubectl/pkg/util/templates/templater.go","code":"func (t *templater) isRootCmd(c *cobra.Command) bool {\n\treturn t.rootCmd(c) == c\n}","line":{"from":175,"to":177}} {"id":100032986,"name":"parents","signature":"func (t *templater) parents(c *cobra.Command) []*cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/util/templates/templater.go","code":"func (t *templater) parents(c *cobra.Command) []*cobra.Command {\n\tparents := []*cobra.Command{c}\n\tfor current := c; !t.isRootCmd(current) \u0026\u0026 current.HasParent(); {\n\t\tcurrent = current.Parent()\n\t\tparents = append(parents, current)\n\t}\n\treturn parents\n}","line":{"from":179,"to":186}} {"id":100032987,"name":"rootCmd","signature":"func (t *templater) rootCmd(c *cobra.Command) *cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/util/templates/templater.go","code":"func (t *templater) rootCmd(c *cobra.Command) *cobra.Command {\n\tif c != nil \u0026\u0026 !c.HasParent() {\n\t\treturn c\n\t}\n\tif t.RootCmd == nil {\n\t\tpanic(\"nil root cmd\")\n\t}\n\treturn t.RootCmd\n}","line":{"from":188,"to":196}} {"id":100032988,"name":"optionsCmdFor","signature":"func (t *templater) optionsCmdFor(c *cobra.Command) string","file":"staging/src/k8s.io/kubectl/pkg/util/templates/templater.go","code":"func (t *templater) optionsCmdFor(c *cobra.Command) string {\n\tif !c.Runnable() {\n\t\treturn \"\"\n\t}\n\trootCmdStructure := t.parents(c)\n\tfor i := len(rootCmdStructure) - 1; i \u003e= 0; i-- {\n\t\tcmd := rootCmdStructure[i]\n\t\tif _, _, err := cmd.Find([]string{\"options\"}); err == nil {\n\t\t\treturn cmd.CommandPath() + \" options\"\n\t\t}\n\t}\n\treturn \"\"\n}","line":{"from":198,"to":210}} {"id":100032989,"name":"usageLine","signature":"func (t *templater) usageLine(c *cobra.Command) string","file":"staging/src/k8s.io/kubectl/pkg/util/templates/templater.go","code":"func (t *templater) usageLine(c *cobra.Command) string {\n\tusage := c.UseLine()\n\tsuffix := \"[options]\"\n\tif c.HasFlags() \u0026\u0026 !strings.Contains(usage, suffix) {\n\t\tusage += \" \" + suffix\n\t}\n\treturn usage\n}","line":{"from":212,"to":219}} {"id":100032990,"name":"flagsUsages","signature":"func flagsUsages(f *flag.FlagSet) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/util/templates/templater.go","code":"// flagsUsages will print out the kubectl help flags\nfunc flagsUsages(f *flag.FlagSet) (string, error) {\n\tflagBuf := new(bytes.Buffer)\n\twrapLimit, err := term.GetWordWrapperLimit()\n\tif err != nil {\n\t\twrapLimit = 0\n\t}\n\tprinter := NewHelpFlagPrinter(flagBuf, wrapLimit)\n\n\tf.VisitAll(func(flag *flag.Flag) {\n\t\tif flag.Hidden {\n\t\t\treturn\n\t\t}\n\t\tprinter.PrintHelpFlag(flag)\n\t})\n\n\treturn flagBuf.String(), nil\n}","line":{"from":221,"to":238}} {"id":100032991,"name":"getFlagFormat","signature":"func getFlagFormat(f *flag.Flag) string","file":"staging/src/k8s.io/kubectl/pkg/util/templates/templater.go","code":"// getFlagFormat will output the flag format\nfunc getFlagFormat(f *flag.Flag) string {\n\tvar format string\n\tformat = \"--%s=%s:\\n%s%s\"\n\tif f.Value.Type() == \"string\" {\n\t\tformat = \"--%s='%s':\\n%s%s\"\n\t}\n\n\tif len(f.Shorthand) \u003e 0 {\n\t\tformat = \" -%s, \" + format\n\t} else {\n\t\tformat = \" %s\" + format\n\t}\n\n\treturn format\n}","line":{"from":240,"to":255}} {"id":100032992,"name":"rpad","signature":"func rpad(s string, padding int) string","file":"staging/src/k8s.io/kubectl/pkg/util/templates/templater.go","code":"func rpad(s string, padding int) string {\n\ttemplate := fmt.Sprintf(\"%%-%ds\", padding)\n\treturn fmt.Sprintf(template, s)\n}","line":{"from":257,"to":260}} {"id":100032993,"name":"appendIfNotPresent","signature":"func appendIfNotPresent(s, stringToAppend string) string","file":"staging/src/k8s.io/kubectl/pkg/util/templates/templater.go","code":"func appendIfNotPresent(s, stringToAppend string) string {\n\tif strings.Contains(s, stringToAppend) {\n\t\treturn s\n\t}\n\treturn s + \" \" + stringToAppend\n}","line":{"from":262,"to":267}} {"id":100032994,"name":"flagsNotIntersected","signature":"func flagsNotIntersected(l *flag.FlagSet, r *flag.FlagSet) *flag.FlagSet","file":"staging/src/k8s.io/kubectl/pkg/util/templates/templater.go","code":"func flagsNotIntersected(l *flag.FlagSet, r *flag.FlagSet) *flag.FlagSet {\n\tf := flag.NewFlagSet(\"notIntersected\", flag.ContinueOnError)\n\tl.VisitAll(func(flag *flag.Flag) {\n\t\tif r.Lookup(flag.Name) == nil {\n\t\t\tf.AddFlag(flag)\n\t\t}\n\t})\n\treturn f\n}","line":{"from":269,"to":277}} {"id":100032995,"name":"visibleFlags","signature":"func visibleFlags(l *flag.FlagSet) *flag.FlagSet","file":"staging/src/k8s.io/kubectl/pkg/util/templates/templater.go","code":"func visibleFlags(l *flag.FlagSet) *flag.FlagSet {\n\thidden := \"help\"\n\tf := flag.NewFlagSet(\"visible\", flag.ContinueOnError)\n\tl.VisitAll(func(flag *flag.Flag) {\n\t\tif flag.Name != hidden {\n\t\t\tf.AddFlag(flag)\n\t\t}\n\t})\n\treturn f\n}","line":{"from":279,"to":288}} {"id":100032996,"name":"filter","signature":"func filter(cmds []*cobra.Command, names ...string) []*cobra.Command","file":"staging/src/k8s.io/kubectl/pkg/util/templates/templater.go","code":"func filter(cmds []*cobra.Command, names ...string) []*cobra.Command {\n\tout := []*cobra.Command{}\n\tfor _, c := range cmds {\n\t\tif c.Hidden {\n\t\t\tcontinue\n\t\t}\n\t\tskip := false\n\t\tfor _, name := range names {\n\t\t\tif name == c.Name() {\n\t\t\t\tskip = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif skip {\n\t\t\tcontinue\n\t\t}\n\t\tout = append(out, c)\n\t}\n\treturn out\n}","line":{"from":290,"to":309}} {"id":100032997,"name":"MainHelpTemplate","signature":"func MainHelpTemplate() string","file":"staging/src/k8s.io/kubectl/pkg/util/templates/templates.go","code":"// MainHelpTemplate if the template for 'help' used by most commands.\nfunc MainHelpTemplate() string {\n\treturn `{{with or .Long .Short }}{{. | trim}}{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`\n}","line":{"from":72,"to":75}} {"id":100032998,"name":"MainUsageTemplate","signature":"func MainUsageTemplate() string","file":"staging/src/k8s.io/kubectl/pkg/util/templates/templates.go","code":"// MainUsageTemplate if the template for 'usage' used by most commands.\nfunc MainUsageTemplate() string {\n\tsections := []string{\n\t\t\"\\n\\n\",\n\t\tSectionVars,\n\t\tSectionAliases,\n\t\tSectionExamples,\n\t\tSectionSubcommands,\n\t\tSectionFlags,\n\t\tSectionUsage,\n\t\tSectionTipsHelp,\n\t\tSectionTipsGlobalOptions,\n\t}\n\treturn strings.TrimRightFunc(strings.Join(sections, \"\"), unicode.IsSpace)\n}","line":{"from":77,"to":91}} {"id":100032999,"name":"OptionsHelpTemplate","signature":"func OptionsHelpTemplate() string","file":"staging/src/k8s.io/kubectl/pkg/util/templates/templates.go","code":"// OptionsHelpTemplate if the template for 'help' used by the 'options' command.\nfunc OptionsHelpTemplate() string {\n\treturn \"\"\n}","line":{"from":93,"to":96}} {"id":100033000,"name":"OptionsUsageTemplate","signature":"func OptionsUsageTemplate() string","file":"staging/src/k8s.io/kubectl/pkg/util/templates/templates.go","code":"// OptionsUsageTemplate if the template for 'usage' used by the 'options' command.\nfunc OptionsUsageTemplate() string {\n\treturn `{{ if .HasInheritedFlags}}The following options can be passed to any command:\n\n{{flagsUsages .InheritedFlags}}{{end}}`\n}","line":{"from":98,"to":103}} {"id":100033001,"name":"GetSize","signature":"func (t TTY) GetSize() *remotecommand.TerminalSize","file":"staging/src/k8s.io/kubectl/pkg/util/term/resize.go","code":"// GetSize returns the current size of the user's terminal. If it isn't a terminal,\n// nil is returned.\nfunc (t TTY) GetSize() *remotecommand.TerminalSize {\n\toutFd, isTerminal := term.GetFdInfo(t.Out)\n\tif !isTerminal {\n\t\treturn nil\n\t}\n\treturn GetSize(outFd)\n}","line":{"from":27,"to":35}} {"id":100033002,"name":"GetSize","signature":"func GetSize(fd uintptr) *remotecommand.TerminalSize","file":"staging/src/k8s.io/kubectl/pkg/util/term/resize.go","code":"// GetSize returns the current size of the terminal associated with fd.\nfunc GetSize(fd uintptr) *remotecommand.TerminalSize {\n\twinsize, err := term.GetWinsize(fd)\n\tif err != nil {\n\t\truntime.HandleError(fmt.Errorf(\"unable to get terminal size: %v\", err))\n\t\treturn nil\n\t}\n\n\treturn \u0026remotecommand.TerminalSize{Width: winsize.Width, Height: winsize.Height}\n}","line":{"from":37,"to":46}} {"id":100033003,"name":"MonitorSize","signature":"func (t *TTY) MonitorSize(initialSizes ...*remotecommand.TerminalSize) remotecommand.TerminalSizeQueue","file":"staging/src/k8s.io/kubectl/pkg/util/term/resize.go","code":"// MonitorSize monitors the terminal's size. It returns a TerminalSizeQueue primed with\n// initialSizes, or nil if there's no TTY present.\nfunc (t *TTY) MonitorSize(initialSizes ...*remotecommand.TerminalSize) remotecommand.TerminalSizeQueue {\n\toutFd, isTerminal := term.GetFdInfo(t.Out)\n\tif !isTerminal {\n\t\treturn nil\n\t}\n\n\tt.sizeQueue = \u0026sizeQueue{\n\t\tt: *t,\n\t\t// make it buffered so we can send the initial terminal sizes without blocking, prior to starting\n\t\t// the streaming below\n\t\tresizeChan: make(chan remotecommand.TerminalSize, len(initialSizes)),\n\t\tstopResizing: make(chan struct{}),\n\t}\n\n\tt.sizeQueue.monitorSize(outFd, initialSizes...)\n\n\treturn t.sizeQueue\n}","line":{"from":48,"to":67}} {"id":100033004,"name":"monitorSize","signature":"func (s *sizeQueue) monitorSize(outFd uintptr, initialSizes ...*remotecommand.TerminalSize)","file":"staging/src/k8s.io/kubectl/pkg/util/term/resize.go","code":"// monitorSize primes resizeChan with initialSizes and then monitors for resize events. With each\n// new event, it sends the current terminal size to resizeChan.\nfunc (s *sizeQueue) monitorSize(outFd uintptr, initialSizes ...*remotecommand.TerminalSize) {\n\t// send the initial sizes\n\tfor i := range initialSizes {\n\t\tif initialSizes[i] != nil {\n\t\t\ts.resizeChan \u003c- *initialSizes[i]\n\t\t}\n\t}\n\n\tresizeEvents := make(chan remotecommand.TerminalSize, 1)\n\n\tmonitorResizeEvents(outFd, resizeEvents, s.stopResizing)\n\n\t// listen for resize events in the background\n\tgo func() {\n\t\tdefer runtime.HandleCrash()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase size, ok := \u003c-resizeEvents:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tselect {\n\t\t\t\t// try to send the size to resizeChan, but don't block\n\t\t\t\tcase s.resizeChan \u003c- size:\n\t\t\t\t\t// send successful\n\t\t\t\tdefault:\n\t\t\t\t\t// unable to send / no-op\n\t\t\t\t}\n\t\t\tcase \u003c-s.stopResizing:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}","line":{"from":80,"to":117}} {"id":100033005,"name":"Next","signature":"func (s *sizeQueue) Next() *remotecommand.TerminalSize","file":"staging/src/k8s.io/kubectl/pkg/util/term/resize.go","code":"// Next returns the new terminal size after the terminal has been resized. It returns nil when\n// monitoring has been stopped.\nfunc (s *sizeQueue) Next() *remotecommand.TerminalSize {\n\tsize, ok := \u003c-s.resizeChan\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn \u0026size\n}","line":{"from":119,"to":127}} {"id":100033006,"name":"stop","signature":"func (s *sizeQueue) stop()","file":"staging/src/k8s.io/kubectl/pkg/util/term/resize.go","code":"// stop stops the background goroutine that is monitoring for terminal resizes.\nfunc (s *sizeQueue) stop() {\n\tclose(s.stopResizing)\n}","line":{"from":129,"to":132}} {"id":100033007,"name":"monitorResizeEvents","signature":"func monitorResizeEvents(fd uintptr, resizeEvents chan\u003c- remotecommand.TerminalSize, stop chan struct{})","file":"staging/src/k8s.io/kubectl/pkg/util/term/resizeevents.go","code":"// monitorResizeEvents spawns a goroutine that waits for SIGWINCH signals (these indicate the\n// terminal has resized). After receiving a SIGWINCH, this gets the terminal size and tries to send\n// it to the resizeEvents channel. The goroutine stops when the stop channel is closed.\nfunc monitorResizeEvents(fd uintptr, resizeEvents chan\u003c- remotecommand.TerminalSize, stop chan struct{}) {\n\tgo func() {\n\t\tdefer runtime.HandleCrash()\n\n\t\twinch := make(chan os.Signal, 1)\n\t\tsignal.Notify(winch, unix.SIGWINCH)\n\t\tdefer signal.Stop(winch)\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase \u003c-winch:\n\t\t\t\tsize := GetSize(fd)\n\t\t\t\tif size == nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// try to send size\n\t\t\t\tselect {\n\t\t\t\tcase resizeEvents \u003c- *size:\n\t\t\t\t\t// success\n\t\t\t\tdefault:\n\t\t\t\t\t// not sent\n\t\t\t\t}\n\t\t\tcase \u003c-stop:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}","line":{"from":31,"to":62}} {"id":100033008,"name":"monitorResizeEvents","signature":"func monitorResizeEvents(fd uintptr, resizeEvents chan\u003c- remotecommand.TerminalSize, stop chan struct{})","file":"staging/src/k8s.io/kubectl/pkg/util/term/resizeevents_windows.go","code":"// monitorResizeEvents spawns a goroutine that periodically gets the terminal size and tries to send\n// it to the resizeEvents channel if the size has changed. The goroutine stops when the stop channel\n// is closed.\nfunc monitorResizeEvents(fd uintptr, resizeEvents chan\u003c- remotecommand.TerminalSize, stop chan struct{}) {\n\tgo func() {\n\t\tdefer runtime.HandleCrash()\n\n\t\tsize := GetSize(fd)\n\t\tif size == nil {\n\t\t\treturn\n\t\t}\n\t\tlastSize := *size\n\n\t\tfor {\n\t\t\t// see if we need to stop running\n\t\t\tselect {\n\t\t\tcase \u003c-stop:\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t}\n\n\t\t\tsize := GetSize(fd)\n\t\t\tif size == nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif size.Height != lastSize.Height || size.Width != lastSize.Width {\n\t\t\t\tlastSize.Height = size.Height\n\t\t\t\tlastSize.Width = size.Width\n\t\t\t\tresizeEvents \u003c- *size\n\t\t\t}\n\n\t\t\t// sleep to avoid hot looping\n\t\t\ttime.Sleep(250 * time.Millisecond)\n\t\t}\n\t}()\n}","line":{"from":26,"to":62}} {"id":100033009,"name":"IsTerminalIn","signature":"func (t TTY) IsTerminalIn() bool","file":"staging/src/k8s.io/kubectl/pkg/util/term/term.go","code":"// IsTerminalIn returns true if t.In is a terminal. Does not check /dev/tty\n// even if TryDev is set.\nfunc (t TTY) IsTerminalIn() bool {\n\treturn IsTerminal(t.In)\n}","line":{"from":56,"to":60}} {"id":100033010,"name":"IsTerminalOut","signature":"func (t TTY) IsTerminalOut() bool","file":"staging/src/k8s.io/kubectl/pkg/util/term/term.go","code":"// IsTerminalOut returns true if t.Out is a terminal. Does not check /dev/tty\n// even if TryDev is set.\nfunc (t TTY) IsTerminalOut() bool {\n\treturn IsTerminal(t.Out)\n}","line":{"from":62,"to":66}} {"id":100033011,"name":"IsTerminal","signature":"func IsTerminal(i interface{}) bool","file":"staging/src/k8s.io/kubectl/pkg/util/term/term.go","code":"// IsTerminal returns whether the passed object is a terminal or not\nfunc IsTerminal(i interface{}) bool {\n\t_, terminal := term.GetFdInfo(i)\n\treturn terminal\n}","line":{"from":68,"to":72}} {"id":100033012,"name":"AllowsColorOutput","signature":"func AllowsColorOutput(w io.Writer) bool","file":"staging/src/k8s.io/kubectl/pkg/util/term/term.go","code":"// AllowsColorOutput returns true if the specified writer is a terminal and\n// the process environment indicates color output is supported and desired.\nfunc AllowsColorOutput(w io.Writer) bool {\n\tif !IsTerminal(w) {\n\t\treturn false\n\t}\n\n\t// https://en.wikipedia.org/wiki/Computer_terminal#Dumb_terminals\n\tif os.Getenv(\"TERM\") == \"dumb\" {\n\t\treturn false\n\t}\n\n\t// https://no-color.org/\n\tif _, nocolor := os.LookupEnv(\"NO_COLOR\"); nocolor {\n\t\treturn false\n\t}\n\n\t// On Windows WT_SESSION is set by the modern terminal component.\n\t// Older terminals have poor support for UTF-8, VT escape codes, etc.\n\tif runtime.GOOS == \"windows\" \u0026\u0026 os.Getenv(\"WT_SESSION\") == \"\" {\n\t\treturn false\n\t}\n\n\treturn true\n}","line":{"from":74,"to":98}} {"id":100033013,"name":"Safe","signature":"func (t TTY) Safe(fn SafeFunc) error","file":"staging/src/k8s.io/kubectl/pkg/util/term/term.go","code":"// Safe invokes the provided function and will attempt to ensure that when the\n// function returns (or a termination signal is sent) that the terminal state\n// is reset to the condition it was in prior to the function being invoked. If\n// t.Raw is true the terminal will be put into raw mode prior to calling the function.\n// If the input file descriptor is not a TTY and TryDev is true, the /dev/tty file\n// will be opened (if available).\nfunc (t TTY) Safe(fn SafeFunc) error {\n\tinFd, isTerminal := term.GetFdInfo(t.In)\n\n\tif !isTerminal \u0026\u0026 t.TryDev {\n\t\tif f, err := os.Open(\"/dev/tty\"); err == nil {\n\t\t\tdefer f.Close()\n\t\t\tinFd = f.Fd()\n\t\t\tisTerminal = term.IsTerminal(inFd)\n\t\t}\n\t}\n\tif !isTerminal {\n\t\treturn fn()\n\t}\n\n\tvar state *term.State\n\tvar err error\n\tif t.Raw {\n\t\tstate, err = term.MakeRaw(inFd)\n\t} else {\n\t\tstate, err = term.SaveState(inFd)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn interrupt.Chain(t.Parent, func() {\n\t\tif t.sizeQueue != nil {\n\t\t\tt.sizeQueue.stop()\n\t\t}\n\n\t\tterm.RestoreTerminal(inFd, state)\n\t}).Run(fn)\n}","line":{"from":100,"to":137}} {"id":100033014,"name":"NewResponsiveWriter","signature":"func NewResponsiveWriter(w io.Writer) io.Writer","file":"staging/src/k8s.io/kubectl/pkg/util/term/term_writer.go","code":"// NewResponsiveWriter creates a Writer that detects the column width of the\n// terminal we are in, and adjusts every line width to fit and use recommended\n// terminal sizes for better readability. Does proper word wrapping automatically.\n//\n//\tif terminal width \u003e= 120 columns\t\tuse 120 columns\n//\tif terminal width \u003e= 100 columns\t\tuse 100 columns\n//\tif terminal width \u003e= 80 columns\t\tuse 80 columns\n//\n// In case we're not in a terminal or if it's smaller than 80 columns width,\n// doesn't do any wrapping.\nfunc NewResponsiveWriter(w io.Writer) io.Writer {\n\tfile, ok := w.(*os.File)\n\tif !ok {\n\t\treturn w\n\t}\n\tfd := file.Fd()\n\tif !term.IsTerminal(fd) {\n\t\treturn w\n\t}\n\n\tterminalSize := GetSize(fd)\n\tif terminalSize == nil {\n\t\treturn w\n\t}\n\tlimit := getTerminalLimitWidth(terminalSize)\n\n\treturn NewWordWrapWriter(w, limit)\n}","line":{"from":35,"to":62}} {"id":100033015,"name":"NewWordWrapWriter","signature":"func NewWordWrapWriter(w io.Writer, limit uint) io.Writer","file":"staging/src/k8s.io/kubectl/pkg/util/term/term_writer.go","code":"// NewWordWrapWriter is a Writer that supports a limit of characters on every line\n// and does auto word wrapping that respects that limit.\nfunc NewWordWrapWriter(w io.Writer, limit uint) io.Writer {\n\treturn \u0026wordWrapWriter{\n\t\tlimit: limit,\n\t\twriter: w,\n\t}\n}","line":{"from":64,"to":71}} {"id":100033016,"name":"getTerminalLimitWidth","signature":"func getTerminalLimitWidth(terminalSize *remotecommand.TerminalSize) uint","file":"staging/src/k8s.io/kubectl/pkg/util/term/term_writer.go","code":"func getTerminalLimitWidth(terminalSize *remotecommand.TerminalSize) uint {\n\tvar limit uint\n\tswitch {\n\tcase terminalSize.Width \u003e= 120:\n\t\tlimit = 120\n\tcase terminalSize.Width \u003e= 100:\n\t\tlimit = 100\n\tcase terminalSize.Width \u003e= 80:\n\t\tlimit = 80\n\t}\n\treturn limit\n}","line":{"from":73,"to":84}} {"id":100033017,"name":"GetWordWrapperLimit","signature":"func GetWordWrapperLimit() (uint, error)","file":"staging/src/k8s.io/kubectl/pkg/util/term/term_writer.go","code":"func GetWordWrapperLimit() (uint, error) {\n\tstdout := os.Stdout\n\tfd := stdout.Fd()\n\tif !term.IsTerminal(fd) {\n\t\treturn 0, errors.New(\"file descriptor is not a terminal\")\n\t}\n\tterminalSize := GetSize(fd)\n\tif terminalSize == nil {\n\t\treturn 0, errors.New(\"terminal size is nil\")\n\t}\n\treturn getTerminalLimitWidth(terminalSize), nil\n}","line":{"from":86,"to":97}} {"id":100033018,"name":"Write","signature":"func (w wordWrapWriter) Write(p []byte) (nn int, err error)","file":"staging/src/k8s.io/kubectl/pkg/util/term/term_writer.go","code":"func (w wordWrapWriter) Write(p []byte) (nn int, err error) {\n\tif w.limit == 0 {\n\t\treturn w.writer.Write(p)\n\t}\n\toriginal := string(p)\n\twrapped := wordwrap.WrapString(original, w.limit)\n\treturn w.writer.Write([]byte(wrapped))\n}","line":{"from":99,"to":106}} {"id":100033019,"name":"NewPunchCardWriter","signature":"func NewPunchCardWriter(w io.Writer) io.Writer","file":"staging/src/k8s.io/kubectl/pkg/util/term/term_writer.go","code":"// NewPunchCardWriter is a NewWordWrapWriter that limits the line width to 80 columns.\nfunc NewPunchCardWriter(w io.Writer) io.Writer {\n\treturn NewWordWrapWriter(w, 80)\n}","line":{"from":108,"to":111}} {"id":100033020,"name":"NewMaxWidthWriter","signature":"func NewMaxWidthWriter(w io.Writer, maxWidth uint) io.Writer","file":"staging/src/k8s.io/kubectl/pkg/util/term/term_writer.go","code":"// NewMaxWidthWriter is a Writer that supports a limit of characters on every\n// line, but doesn't do any word wrapping automatically.\nfunc NewMaxWidthWriter(w io.Writer, maxWidth uint) io.Writer {\n\treturn \u0026maxWidthWriter{\n\t\tmaxWidth: maxWidth,\n\t\twriter: w,\n\t}\n}","line":{"from":120,"to":127}} {"id":100033021,"name":"Write","signature":"func (m maxWidthWriter) Write(p []byte) (nn int, err error)","file":"staging/src/k8s.io/kubectl/pkg/util/term/term_writer.go","code":"func (m maxWidthWriter) Write(p []byte) (nn int, err error) {\n\tfor _, b := range p {\n\t\tif m.currentWidth == m.maxWidth {\n\t\t\tm.writer.Write([]byte{'\\n'})\n\t\t\tm.currentWidth = 0\n\t\t}\n\t\tif b == '\\n' {\n\t\t\tm.currentWidth = 0\n\t\t}\n\t\t_, err := m.writer.Write([]byte{b})\n\t\tif err != nil {\n\t\t\treturn int(m.written), err\n\t\t}\n\t\tm.written++\n\t\tm.currentWidth++\n\t}\n\treturn len(p), nil\n}","line":{"from":129,"to":146}} {"id":100033022,"name":"Umask","signature":"func Umask(mask int) (old int, err error)","file":"staging/src/k8s.io/kubectl/pkg/util/umask.go","code":"// Umask is a wrapper for `unix.Umask()` on non-Windows platforms\nfunc Umask(mask int) (old int, err error) {\n\treturn unix.Umask(mask), nil\n}","line":{"from":26,"to":29}} {"id":100033023,"name":"Umask","signature":"func Umask(mask int) (int, error)","file":"staging/src/k8s.io/kubectl/pkg/util/umask_windows.go","code":"// Umask returns an error on Windows\nfunc Umask(mask int) (int, error) {\n\treturn 0, errors.New(\"platform and architecture is not supported\")\n}","line":{"from":26,"to":29}} {"id":100033024,"name":"ParseRFC3339","signature":"func ParseRFC3339(s string, nowFn func() metav1.Time) (metav1.Time, error)","file":"staging/src/k8s.io/kubectl/pkg/util/util.go","code":"// ParseRFC3339 parses an RFC3339 date in either RFC3339Nano or RFC3339 format.\nfunc ParseRFC3339(s string, nowFn func() metav1.Time) (metav1.Time, error) {\n\tif t, timeErr := time.Parse(time.RFC3339Nano, s); timeErr == nil {\n\t\treturn metav1.Time{Time: t}, nil\n\t}\n\tt, err := time.Parse(time.RFC3339, s)\n\tif err != nil {\n\t\treturn metav1.Time{}, err\n\t}\n\treturn metav1.Time{Time: t}, nil\n}","line":{"from":32,"to":42}} {"id":100033025,"name":"HashObject","signature":"func HashObject(obj runtime.Object, codec runtime.Codec) (string, error)","file":"staging/src/k8s.io/kubectl/pkg/util/util.go","code":"// HashObject returns the hash of a Object hash by a Codec\nfunc HashObject(obj runtime.Object, codec runtime.Codec) (string, error) {\n\tdata, err := runtime.Encode(codec, obj)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"%x\", md5.Sum(data)), nil\n}","line":{"from":44,"to":51}} {"id":100033026,"name":"ParseFileSource","signature":"func ParseFileSource(source string) (keyName, filePath string, err error)","file":"staging/src/k8s.io/kubectl/pkg/util/util.go","code":"// ParseFileSource parses the source given.\n//\n//\tAcceptable formats include:\n//\t 1. source-path: the basename will become the key name\n//\t 2. source-name=source-path: the source-name will become the key name and\n//\t source-path is the path to the key file.\n//\n// Key names cannot include '='.\nfunc ParseFileSource(source string) (keyName, filePath string, err error) {\n\tnumSeparators := strings.Count(source, \"=\")\n\tswitch {\n\tcase numSeparators == 0:\n\t\treturn path.Base(filepath.ToSlash(source)), source, nil\n\tcase numSeparators == 1 \u0026\u0026 strings.HasPrefix(source, \"=\"):\n\t\treturn \"\", \"\", fmt.Errorf(\"key name for file path %v missing\", strings.TrimPrefix(source, \"=\"))\n\tcase numSeparators == 1 \u0026\u0026 strings.HasSuffix(source, \"=\"):\n\t\treturn \"\", \"\", fmt.Errorf(\"file path for key name %v missing\", strings.TrimSuffix(source, \"=\"))\n\tcase numSeparators \u003e 1:\n\t\treturn \"\", \"\", errors.New(\"key names or file paths cannot contain '='\")\n\tdefault:\n\t\tcomponents := strings.Split(source, \"=\")\n\t\treturn components[0], components[1], nil\n\t}\n}","line":{"from":53,"to":76}} {"id":100033027,"name":"ParseLiteralSource","signature":"func ParseLiteralSource(source string) (keyName, value string, err error)","file":"staging/src/k8s.io/kubectl/pkg/util/util.go","code":"// ParseLiteralSource parses the source key=val pair into its component pieces.\n// This functionality is distinguished from strings.SplitN(source, \"=\", 2) since\n// it returns an error in the case of empty keys, values, or a missing equals sign.\nfunc ParseLiteralSource(source string) (keyName, value string, err error) {\n\t// leading equal is invalid\n\tif strings.Index(source, \"=\") == 0 {\n\t\treturn \"\", \"\", fmt.Errorf(\"invalid literal source %v, expected key=value\", source)\n\t}\n\t// split after the first equal (so values can have the = character)\n\titems := strings.SplitN(source, \"=\", 2)\n\tif len(items) != 2 {\n\t\treturn \"\", \"\", fmt.Errorf(\"invalid literal source %v, expected key=value\", source)\n\t}\n\n\treturn items[0], items[1], nil\n}","line":{"from":78,"to":93}} {"id":100033028,"name":"ValidateBytes","signature":"func (NullSchema) ValidateBytes(data []byte) error { return nil }","file":"staging/src/k8s.io/kubectl/pkg/validation/schema.go","code":"// ValidateBytes never fails for NullSchema.\nfunc (NullSchema) ValidateBytes(data []byte) error { return nil }","line":{"from":39,"to":40}} {"id":100033029,"name":"ValidateBytes","signature":"func (NoDoubleKeySchema) ValidateBytes(data []byte) error","file":"staging/src/k8s.io/kubectl/pkg/validation/schema.go","code":"// ValidateBytes validates bytes.\nfunc (NoDoubleKeySchema) ValidateBytes(data []byte) error {\n\tvar list []error\n\tif err := validateNoDuplicateKeys(data, \"metadata\", \"labels\"); err != nil {\n\t\tlist = append(list, err)\n\t}\n\tif err := validateNoDuplicateKeys(data, \"metadata\", \"annotations\"); err != nil {\n\t\tlist = append(list, err)\n\t}\n\treturn utilerrors.NewAggregate(list)\n}","line":{"from":45,"to":55}} {"id":100033030,"name":"validateNoDuplicateKeys","signature":"func validateNoDuplicateKeys(data []byte, path ...string) error","file":"staging/src/k8s.io/kubectl/pkg/validation/schema.go","code":"func validateNoDuplicateKeys(data []byte, path ...string) error {\n\tr := ejson.NewDecoder(bytes.NewReader(data))\n\t// This is Go being unfriendly. The 'path ...string' comes in as a\n\t// []string, and SeekTo takes ...interface{}, so we can't just pass\n\t// the path straight in, we have to copy it. *sigh*\n\tifacePath := []interface{}{}\n\tfor ix := range path {\n\t\tifacePath = append(ifacePath, path[ix])\n\t}\n\tfound, err := r.SeekTo(ifacePath...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !found {\n\t\treturn nil\n\t}\n\tseen := map[string]bool{}\n\tfor {\n\t\ttok, err := r.Token()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch t := tok.(type) {\n\t\tcase json.Delim:\n\t\t\tif t.String() == \"}\" {\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase ejson.KeyString:\n\t\t\tif seen[string(t)] {\n\t\t\t\treturn fmt.Errorf(\"duplicate key: %s\", string(t))\n\t\t\t}\n\t\t\tseen[string(t)] = true\n\t\t}\n\t}\n}","line":{"from":57,"to":91}} {"id":100033031,"name":"ValidateBytes","signature":"func (c ConjunctiveSchema) ValidateBytes(data []byte) error","file":"staging/src/k8s.io/kubectl/pkg/validation/schema.go","code":"// ValidateBytes validates bytes per a ConjunctiveSchema.\nfunc (c ConjunctiveSchema) ValidateBytes(data []byte) error {\n\tvar list []error\n\tschemas := []Schema(c)\n\tfor ix := range schemas {\n\t\tif err := schemas[ix].ValidateBytes(data); err != nil {\n\t\t\tlist = append(list, err)\n\t\t}\n\t}\n\treturn utilerrors.NewAggregate(list)\n}","line":{"from":96,"to":106}} {"id":100033032,"name":"NewParamVerifyingSchema","signature":"func NewParamVerifyingSchema(s Schema, verifier resource.Verifier, directive string) Schema","file":"staging/src/k8s.io/kubectl/pkg/validation/schema.go","code":"func NewParamVerifyingSchema(s Schema, verifier resource.Verifier, directive string) Schema {\n\treturn \u0026paramVerifyingSchema{\n\t\tschema: s,\n\t\tverifier: verifier,\n\t\tdirective: directive,\n\t}\n}","line":{"from":108,"to":114}} {"id":100033033,"name":"ValidateBytes","signature":"func (c *paramVerifyingSchema) ValidateBytes(data []byte) error","file":"staging/src/k8s.io/kubectl/pkg/validation/schema.go","code":"// ValidateBytes validates bytes per a ParamVerifyingSchema\nfunc (c *paramVerifyingSchema) ValidateBytes(data []byte) error {\n\tobj, err := parse(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgvk, errs := getObjectKind(obj)\n\tif errs != nil {\n\t\treturn utilerrors.NewAggregate(errs)\n\t}\n\n\terr = c.verifier.HasSupport(gvk)\n\tif resource.IsParamUnsupportedError(err) {\n\t\tswitch c.directive {\n\t\tcase metav1.FieldValidationStrict:\n\t\t\treturn c.schema.ValidateBytes(data)\n\t\tcase metav1.FieldValidationWarn:\n\t\t\tklog.Warningf(\"cannot perform warn validation if server-side field validation is unsupported, skipping validation\")\n\t\tdefault:\n\t\t\t// can't be reached\n\t\t\tklog.Warningf(\"unexpected field validation directive: %s, skipping validation\", c.directive)\n\t\t}\n\t\treturn nil\n\t}\n\treturn err\n}","line":{"from":127,"to":153}} {"id":100033034,"name":"NewSchemaValidation","signature":"func NewSchemaValidation(resources openapi.Resources) Schema","file":"staging/src/k8s.io/kubectl/pkg/validation/validation.go","code":"// NewSchemaValidation creates a new Schema that can be used\n// to validate objects.\nfunc NewSchemaValidation(resources openapi.Resources) Schema {\n\treturn \u0026schemaValidation{\n\t\tresources: resources,\n\t}\n}","line":{"from":35,"to":41}} {"id":100033035,"name":"ValidateBytes","signature":"func (v *schemaValidation) ValidateBytes(data []byte) error","file":"staging/src/k8s.io/kubectl/pkg/validation/validation.go","code":"// ValidateBytes will validates the object against using the Resources\n// object.\nfunc (v *schemaValidation) ValidateBytes(data []byte) error {\n\tobj, err := parse(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgvk, errs := getObjectKind(obj)\n\tif errs != nil {\n\t\treturn utilerrors.NewAggregate(errs)\n\t}\n\n\tif (gvk == schema.GroupVersionKind{Version: \"v1\", Kind: \"List\"}) {\n\t\treturn utilerrors.NewAggregate(v.validateList(obj))\n\t}\n\n\treturn utilerrors.NewAggregate(v.validateResource(obj, gvk))\n}","line":{"from":43,"to":61}} {"id":100033036,"name":"validateList","signature":"func (v *schemaValidation) validateList(object interface{}) []error","file":"staging/src/k8s.io/kubectl/pkg/validation/validation.go","code":"func (v *schemaValidation) validateList(object interface{}) []error {\n\tfields, ok := object.(map[string]interface{})\n\tif !ok || fields == nil {\n\t\treturn []error{errors.New(\"invalid object to validate\")}\n\t}\n\n\tallErrors := []error{}\n\tif _, ok := fields[\"items\"].([]interface{}); !ok {\n\t\treturn []error{errors.New(\"invalid object to validate\")}\n\t}\n\tfor _, item := range fields[\"items\"].([]interface{}) {\n\t\tif gvk, errs := getObjectKind(item); errs != nil {\n\t\t\tallErrors = append(allErrors, errs...)\n\t\t} else {\n\t\t\tallErrors = append(allErrors, v.validateResource(item, gvk)...)\n\t\t}\n\t}\n\treturn allErrors\n}","line":{"from":63,"to":81}} {"id":100033037,"name":"validateResource","signature":"func (v *schemaValidation) validateResource(obj interface{}, gvk schema.GroupVersionKind) []error","file":"staging/src/k8s.io/kubectl/pkg/validation/validation.go","code":"func (v *schemaValidation) validateResource(obj interface{}, gvk schema.GroupVersionKind) []error {\n\tresource := v.resources.LookupResource(gvk)\n\tif resource == nil {\n\t\t// resource is not present, let's just skip validation.\n\t\treturn nil\n\t}\n\n\treturn validation.ValidateModel(obj, resource, gvk.Kind)\n}","line":{"from":83,"to":91}} {"id":100033038,"name":"parse","signature":"func parse(data []byte) (interface{}, error)","file":"staging/src/k8s.io/kubectl/pkg/validation/validation.go","code":"func parse(data []byte) (interface{}, error) {\n\tvar obj interface{}\n\tout, err := yaml.ToJSON(data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := json.Unmarshal(out, \u0026obj); err != nil {\n\t\treturn nil, err\n\t}\n\treturn obj, nil\n}","line":{"from":93,"to":103}} {"id":100033039,"name":"getObjectKind","signature":"func getObjectKind(object interface{}) (schema.GroupVersionKind, []error)","file":"staging/src/k8s.io/kubectl/pkg/validation/validation.go","code":"func getObjectKind(object interface{}) (schema.GroupVersionKind, []error) {\n\tvar listErrors []error\n\tfields, ok := object.(map[string]interface{})\n\tif !ok || fields == nil {\n\t\tlistErrors = append(listErrors, errors.New(\"invalid object to validate\"))\n\t\treturn schema.GroupVersionKind{}, listErrors\n\t}\n\n\tvar group string\n\tvar version string\n\tapiVersion := fields[\"apiVersion\"]\n\tif apiVersion == nil {\n\t\tlistErrors = append(listErrors, errors.New(\"apiVersion not set\"))\n\t} else if _, ok := apiVersion.(string); !ok {\n\t\tlistErrors = append(listErrors, errors.New(\"apiVersion isn't string type\"))\n\t} else {\n\t\tgv, err := schema.ParseGroupVersion(apiVersion.(string))\n\t\tif err != nil {\n\t\t\tlistErrors = append(listErrors, err)\n\t\t} else {\n\t\t\tgroup = gv.Group\n\t\t\tversion = gv.Version\n\t\t}\n\t}\n\tkind := fields[\"kind\"]\n\tif kind == nil {\n\t\tlistErrors = append(listErrors, errors.New(\"kind not set\"))\n\t} else if _, ok := kind.(string); !ok {\n\t\tlistErrors = append(listErrors, errors.New(\"kind isn't string type\"))\n\t}\n\tif listErrors != nil {\n\t\treturn schema.GroupVersionKind{}, listErrors\n\t}\n\n\treturn schema.GroupVersionKind{Group: group, Version: version, Kind: kind.(string)}, nil\n}","line":{"from":105,"to":140}} {"id":100033040,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/kubelet/config/v1/register.go","code":"// addKnownTypes registers known types to the given scheme\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026CredentialProviderConfig{},\n\t)\n\treturn nil\n}","line":{"from":37,"to":43}} {"id":100033041,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/kubelet/config/v1alpha1/register.go","code":"// addKnownTypes registers known types to the given scheme\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026CredentialProviderConfig{},\n\t)\n\treturn nil\n}","line":{"from":37,"to":43}} {"id":100033042,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/kubelet/config/v1beta1/register.go","code":"// addKnownTypes registers known types to the given scheme\nfunc addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026KubeletConfiguration{},\n\t\t\u0026SerializedNodeConfigSource{},\n\t\t\u0026CredentialProviderConfig{},\n\t)\n\treturn nil\n}","line":{"from":37,"to":45}} {"id":100033043,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"staging/src/k8s.io/kubelet/pkg/apis/credentialprovider/install/install.go","code":"// Install registers the credentialprovider.kubelet.k8s.io APIs into the given scheme.\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(credentialprovider.AddToScheme(scheme))\n\tutilruntime.Must(v1alpha1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1alpha1.SchemeGroupVersion))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1beta1.SchemeGroupVersion))\n\tutilruntime.Must(v1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1.SchemeGroupVersion))\n}","line":{"from":28,"to":37}} {"id":100033044,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/kubelet/pkg/apis/credentialprovider/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026CredentialProviderRequest{},\n\t\t\u0026CredentialProviderResponse{},\n\t)\n\treturn nil\n}","line":{"from":35,"to":41}} {"id":100033045,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/kubelet/pkg/apis/credentialprovider/v1/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026CredentialProviderRequest{},\n\t\t\u0026CredentialProviderResponse{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":39,"to":46}} {"id":100033046,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/kubelet/pkg/apis/credentialprovider/v1alpha1/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026CredentialProviderRequest{},\n\t\t\u0026CredentialProviderResponse{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":39,"to":46}} {"id":100033047,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/kubelet/pkg/apis/credentialprovider/v1beta1/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026CredentialProviderRequest{},\n\t\t\u0026CredentialProviderResponse{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":39,"to":46}} {"id":100033048,"name":"KubeletLabels","signature":"func KubeletLabels() []string","file":"staging/src/k8s.io/kubelet/pkg/apis/well_known_labels.go","code":"// KubeletLabels returns the list of label keys kubelets are allowed to set on their own Node objects\nfunc KubeletLabels() []string {\n\treturn kubeletLabels.List()\n}","line":{"from":55,"to":58}} {"id":100033049,"name":"KubeletLabelNamespaces","signature":"func KubeletLabelNamespaces() []string","file":"staging/src/k8s.io/kubelet/pkg/apis/well_known_labels.go","code":"// KubeletLabelNamespaces returns the list of label key namespaces kubelets are allowed to set on their own Node objects\nfunc KubeletLabelNamespaces() []string {\n\treturn kubeletLabelNamespaces.List()\n}","line":{"from":60,"to":63}} {"id":100033050,"name":"IsKubeletLabel","signature":"func IsKubeletLabel(key string) bool","file":"staging/src/k8s.io/kubelet/pkg/apis/well_known_labels.go","code":"// IsKubeletLabel returns true if the label key is one that kubelets are allowed to set on their own Node object.\n// This checks if the key is in the KubeletLabels() list, or has a namespace in the KubeletLabelNamespaces() list.\nfunc IsKubeletLabel(key string) bool {\n\tif kubeletLabels.Has(key) {\n\t\treturn true\n\t}\n\n\tnamespace := getLabelNamespace(key)\n\tfor allowedNamespace := range kubeletLabelNamespaces {\n\t\tif namespace == allowedNamespace || strings.HasSuffix(namespace, \".\"+allowedNamespace) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":65,"to":80}} {"id":100033051,"name":"getLabelNamespace","signature":"func getLabelNamespace(key string) string","file":"staging/src/k8s.io/kubelet/pkg/apis/well_known_labels.go","code":"func getLabelNamespace(key string) string {\n\tif parts := strings.SplitN(key, \"/\", 2); len(parts) == 2 {\n\t\treturn parts[0]\n\t}\n\treturn \"\"\n}","line":{"from":82,"to":87}} {"id":100033052,"name":"GetServicePrincipalToken","signature":"func GetServicePrincipalToken(config *AzureAuthConfig, env *azure.Environment) (*adal.ServicePrincipalToken, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/auth/azure_auth.go","code":"// GetServicePrincipalToken creates a new service principal token based on the configuration.\n//\n// By default, the cluster and its network resources are deployed in the same AAD Tenant and Subscription,\n// and all azure clients use this method to fetch Service Principal Token.\n//\n// If NetworkResourceTenantID and NetworkResourceSubscriptionID are specified to have different values than TenantID and SubscriptionID, network resources are deployed in different AAD Tenant and Subscription than those for the cluster,\n// than only azure clients except VM/VMSS and network resource ones use this method to fetch Token.\n// For tokens for VM/VMSS and network resource ones, please check GetMultiTenantServicePrincipalToken and GetNetworkResourceServicePrincipalToken.\nfunc GetServicePrincipalToken(config *AzureAuthConfig, env *azure.Environment) (*adal.ServicePrincipalToken, error) {\n\tvar tenantID string\n\tif strings.EqualFold(config.IdentitySystem, ADFSIdentitySystem) {\n\t\ttenantID = ADFSIdentitySystem\n\t} else {\n\t\ttenantID = config.TenantID\n\t}\n\n\tif config.UseManagedIdentityExtension {\n\t\tklog.V(2).Infoln(\"azure: using managed identity extension to retrieve access token\")\n\t\tmsiEndpoint, err := adal.GetMSIVMEndpoint()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Getting the managed service identity endpoint: %v\", err)\n\t\t}\n\t\tif len(config.UserAssignedIdentityID) \u003e 0 {\n\t\t\tklog.V(4).Info(\"azure: using User Assigned MSI ID to retrieve access token\")\n\t\t\treturn adal.NewServicePrincipalTokenFromMSIWithUserAssignedID(msiEndpoint,\n\t\t\t\tenv.ServiceManagementEndpoint,\n\t\t\t\tconfig.UserAssignedIdentityID)\n\t\t}\n\t\tklog.V(4).Info(\"azure: using System Assigned MSI to retrieve access token\")\n\t\treturn adal.NewServicePrincipalTokenFromMSI(\n\t\t\tmsiEndpoint,\n\t\t\tenv.ServiceManagementEndpoint)\n\t}\n\n\toauthConfig, err := adal.NewOAuthConfigWithAPIVersion(env.ActiveDirectoryEndpoint, tenantID, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"creating the OAuth config: %v\", err)\n\t}\n\n\tif len(config.AADClientSecret) \u003e 0 {\n\t\tklog.V(2).Infoln(\"azure: using client_id+client_secret to retrieve access token\")\n\t\treturn adal.NewServicePrincipalToken(\n\t\t\t*oauthConfig,\n\t\t\tconfig.AADClientID,\n\t\t\tconfig.AADClientSecret,\n\t\t\tenv.ServiceManagementEndpoint)\n\t}\n\n\tif len(config.AADClientCertPath) \u003e 0 \u0026\u0026 len(config.AADClientCertPassword) \u003e 0 {\n\t\tklog.V(2).Infoln(\"azure: using jwt client_assertion (client_cert+client_private_key) to retrieve access token\")\n\t\tcertData, err := ioutil.ReadFile(config.AADClientCertPath)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"reading the client certificate from file %s: %v\", config.AADClientCertPath, err)\n\t\t}\n\t\tcertificate, privateKey, err := decodePkcs12(certData, config.AADClientCertPassword)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"decoding the client certificate: %v\", err)\n\t\t}\n\t\treturn adal.NewServicePrincipalTokenFromCertificate(\n\t\t\t*oauthConfig,\n\t\t\tconfig.AADClientID,\n\t\t\tcertificate,\n\t\t\tprivateKey,\n\t\t\tenv.ServiceManagementEndpoint)\n\t}\n\n\treturn nil, ErrorNoAuth\n}","line":{"from":77,"to":144}} {"id":100033053,"name":"GetMultiTenantServicePrincipalToken","signature":"func GetMultiTenantServicePrincipalToken(config *AzureAuthConfig, env *azure.Environment) (*adal.MultiTenantServicePrincipalToken, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/auth/azure_auth.go","code":"// GetMultiTenantServicePrincipalToken is used when (and only when) NetworkResourceTenantID and NetworkResourceSubscriptionID are specified to have different values than TenantID and SubscriptionID.\n//\n// In that scenario, network resources are deployed in different AAD Tenant and Subscription than those for the cluster,\n// and this method creates a new multi-tenant service principal token based on the configuration.\n//\n// PrimaryToken of the returned multi-tenant token is for the AAD Tenant specified by TenantID, and AuxiliaryToken of the returned multi-tenant token is for the AAD Tenant specified by NetworkResourceTenantID.\n//\n// Azure VM/VMSS clients use this multi-tenant token, in order to operate those VM/VMSS in AAD Tenant specified by TenantID, and meanwhile in their payload they are referencing network resources (e.g. Load Balancer, Network Security Group, etc.) in AAD Tenant specified by NetworkResourceTenantID.\nfunc GetMultiTenantServicePrincipalToken(config *AzureAuthConfig, env *azure.Environment) (*adal.MultiTenantServicePrincipalToken, error) {\n\terr := config.checkConfigWhenNetworkResourceInDifferentTenant()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"got error(%v) in getting multi-tenant service principal token\", err)\n\t}\n\n\tmultiTenantOAuthConfig, err := adal.NewMultiTenantOAuthConfig(\n\t\tenv.ActiveDirectoryEndpoint, config.TenantID, []string{config.NetworkResourceTenantID}, adal.OAuthOptions{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"creating the multi-tenant OAuth config: %v\", err)\n\t}\n\n\tif len(config.AADClientSecret) \u003e 0 {\n\t\tklog.V(2).Infoln(\"azure: using client_id+client_secret to retrieve multi-tenant access token\")\n\t\treturn adal.NewMultiTenantServicePrincipalToken(\n\t\t\tmultiTenantOAuthConfig,\n\t\t\tconfig.AADClientID,\n\t\t\tconfig.AADClientSecret,\n\t\t\tenv.ServiceManagementEndpoint)\n\t}\n\n\tif len(config.AADClientCertPath) \u003e 0 \u0026\u0026 len(config.AADClientCertPassword) \u003e 0 {\n\t\treturn nil, fmt.Errorf(\"AAD Application client certificate authentication is not supported in getting multi-tenant service principal token\")\n\t}\n\n\treturn nil, ErrorNoAuth\n}","line":{"from":146,"to":180}} {"id":100033054,"name":"GetNetworkResourceServicePrincipalToken","signature":"func GetNetworkResourceServicePrincipalToken(config *AzureAuthConfig, env *azure.Environment) (*adal.ServicePrincipalToken, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/auth/azure_auth.go","code":"// GetNetworkResourceServicePrincipalToken is used when (and only when) NetworkResourceTenantID and NetworkResourceSubscriptionID are specified to have different values than TenantID and SubscriptionID.\n//\n// In that scenario, network resources are deployed in different AAD Tenant and Subscription than those for the cluster,\n// and this method creates a new service principal token for network resources tenant based on the configuration.\n//\n// Azure network resource (Load Balancer, Public IP, Route Table, Network Security Group and their sub level resources) clients use this multi-tenant token, in order to operate resources in AAD Tenant specified by NetworkResourceTenantID.\nfunc GetNetworkResourceServicePrincipalToken(config *AzureAuthConfig, env *azure.Environment) (*adal.ServicePrincipalToken, error) {\n\terr := config.checkConfigWhenNetworkResourceInDifferentTenant()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"got error(%v) in getting network resources service principal token\", err)\n\t}\n\n\toauthConfig, err := adal.NewOAuthConfigWithAPIVersion(env.ActiveDirectoryEndpoint, config.NetworkResourceTenantID, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"creating the OAuth config for network resources tenant: %v\", err)\n\t}\n\n\tif len(config.AADClientSecret) \u003e 0 {\n\t\tklog.V(2).Infoln(\"azure: using client_id+client_secret to retrieve access token for network resources tenant\")\n\t\treturn adal.NewServicePrincipalToken(\n\t\t\t*oauthConfig,\n\t\t\tconfig.AADClientID,\n\t\t\tconfig.AADClientSecret,\n\t\t\tenv.ServiceManagementEndpoint)\n\t}\n\n\tif len(config.AADClientCertPath) \u003e 0 \u0026\u0026 len(config.AADClientCertPassword) \u003e 0 {\n\t\treturn nil, fmt.Errorf(\"AAD Application client certificate authentication is not supported in getting network resources service principal token\")\n\t}\n\n\treturn nil, ErrorNoAuth\n}","line":{"from":182,"to":213}} {"id":100033055,"name":"ParseAzureEnvironment","signature":"func ParseAzureEnvironment(cloudName, resourceManagerEndpoint, identitySystem string) (*azure.Environment, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/auth/azure_auth.go","code":"// ParseAzureEnvironment returns the azure environment.\n// If 'resourceManagerEndpoint' is set, the environment is computed by querying the cloud's resource manager endpoint.\n// Otherwise, a pre-defined Environment is looked up by name.\nfunc ParseAzureEnvironment(cloudName, resourceManagerEndpoint, identitySystem string) (*azure.Environment, error) {\n\tvar env azure.Environment\n\tvar err error\n\tif resourceManagerEndpoint != \"\" {\n\t\tklog.V(4).Infof(\"Loading environment from resource manager endpoint: %s\", resourceManagerEndpoint)\n\t\tnameOverride := azure.OverrideProperty{Key: azure.EnvironmentName, Value: cloudName}\n\t\tenv, err = azure.EnvironmentFromURL(resourceManagerEndpoint, nameOverride)\n\t\tif err == nil {\n\t\t\tazureStackOverrides(\u0026env, resourceManagerEndpoint, identitySystem)\n\t\t}\n\t} else if cloudName == \"\" {\n\t\tklog.V(4).Info(\"Using public cloud environment\")\n\t\tenv = azure.PublicCloud\n\t} else {\n\t\tklog.V(4).Infof(\"Using %s environment\", cloudName)\n\t\tenv, err = azure.EnvironmentFromName(cloudName)\n\t}\n\treturn \u0026env, err\n}","line":{"from":215,"to":236}} {"id":100033056,"name":"UsesNetworkResourceInDifferentTenant","signature":"func (config *AzureAuthConfig) UsesNetworkResourceInDifferentTenant() bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/auth/azure_auth.go","code":"// UsesNetworkResourceInDifferentTenant determines whether the AzureAuthConfig indicates to use network resources in different AAD Tenant and Subscription than those for the cluster\n// Return true only when both NetworkResourceTenantID and NetworkResourceSubscriptionID are specified\n// and they are not equals to TenantID and SubscriptionID\nfunc (config *AzureAuthConfig) UsesNetworkResourceInDifferentTenant() bool {\n\treturn len(config.NetworkResourceTenantID) \u003e 0 \u0026\u0026\n\t\tlen(config.NetworkResourceSubscriptionID) \u003e 0 \u0026\u0026\n\t\t!strings.EqualFold(config.NetworkResourceTenantID, config.TenantID) \u0026\u0026\n\t\t!strings.EqualFold(config.NetworkResourceSubscriptionID, config.SubscriptionID)\n}","line":{"from":238,"to":246}} {"id":100033057,"name":"decodePkcs12","signature":"func decodePkcs12(pkcs []byte, password string) (*x509.Certificate, *rsa.PrivateKey, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/auth/azure_auth.go","code":"// decodePkcs12 decodes a PKCS#12 client certificate by extracting the public certificate and\n// the private RSA key\nfunc decodePkcs12(pkcs []byte, password string) (*x509.Certificate, *rsa.PrivateKey, error) {\n\tprivateKey, certificate, err := pkcs12.Decode(pkcs, password)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"decoding the PKCS#12 client certificate: %v\", err)\n\t}\n\trsaPrivateKey, isRsaKey := privateKey.(*rsa.PrivateKey)\n\tif !isRsaKey {\n\t\treturn nil, nil, fmt.Errorf(\"PKCS#12 certificate must contain a RSA private key\")\n\t}\n\n\treturn certificate, rsaPrivateKey, nil\n}","line":{"from":248,"to":261}} {"id":100033058,"name":"azureStackOverrides","signature":"func azureStackOverrides(env *azure.Environment, resourceManagerEndpoint, identitySystem string)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/auth/azure_auth.go","code":"// azureStackOverrides ensures that the Environment matches what AKSe currently generates for Azure Stack\nfunc azureStackOverrides(env *azure.Environment, resourceManagerEndpoint, identitySystem string) {\n\tenv.ManagementPortalURL = strings.Replace(resourceManagerEndpoint, \"https://management.\", \"https://portal.\", -1)\n\tenv.ServiceManagementEndpoint = env.TokenAudience\n\tenv.ResourceManagerVMDNSSuffix = strings.Replace(resourceManagerEndpoint, \"https://management.\", \"cloudapp.\", -1)\n\tenv.ResourceManagerVMDNSSuffix = strings.TrimSuffix(env.ResourceManagerVMDNSSuffix, \"/\")\n\tif strings.EqualFold(identitySystem, ADFSIdentitySystem) {\n\t\tenv.ActiveDirectoryEndpoint = strings.TrimSuffix(env.ActiveDirectoryEndpoint, \"/\")\n\t\tenv.ActiveDirectoryEndpoint = strings.TrimSuffix(env.ActiveDirectoryEndpoint, \"adfs\")\n\t}\n}","line":{"from":263,"to":273}} {"id":100033059,"name":"checkConfigWhenNetworkResourceInDifferentTenant","signature":"func (config *AzureAuthConfig) checkConfigWhenNetworkResourceInDifferentTenant() error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/auth/azure_auth.go","code":"// checkConfigWhenNetworkResourceInDifferentTenant checks configuration for the scenario of using network resource in different tenant\nfunc (config *AzureAuthConfig) checkConfigWhenNetworkResourceInDifferentTenant() error {\n\tif !config.UsesNetworkResourceInDifferentTenant() {\n\t\treturn fmt.Errorf(\"NetworkResourceTenantID and NetworkResourceSubscriptionID must be configured\")\n\t}\n\n\tif strings.EqualFold(config.IdentitySystem, ADFSIdentitySystem) {\n\t\treturn fmt.Errorf(\"ADFS identity system is not supported\")\n\t}\n\n\tif config.UseManagedIdentityExtension {\n\t\treturn fmt.Errorf(\"managed identity is not supported\")\n\t}\n\n\treturn nil\n}","line":{"from":275,"to":290}} {"id":100033060,"name":"init","signature":"func init()","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"func init() {\n\t// In go-autorest SDK https://github.com/Azure/go-autorest/blob/master/autorest/sender.go#L258-L287,\n\t// if ARM returns http.StatusTooManyRequests, the sender doesn't increase the retry attempt count,\n\t// hence the Azure clients will keep retrying forever until it get a status code other than 429.\n\t// So we explicitly removes http.StatusTooManyRequests from autorest.StatusCodesForRetry.\n\t// Refer https://github.com/Azure/go-autorest/issues/398.\n\t// TODO(feiskyer): Use autorest.SendDecorator to customize the retry policy when new Azure SDK is available.\n\tstatusCodesForRetry := make([]int, 0)\n\tfor _, code := range autorest.StatusCodesForRetry {\n\t\tif code != http.StatusTooManyRequests {\n\t\t\tstatusCodesForRetry = append(statusCodesForRetry, code)\n\t\t}\n\t}\n\tautorest.StatusCodesForRetry = statusCodesForRetry\n\n\tcloudprovider.RegisterCloudProvider(CloudProviderName, NewCloud)\n}","line":{"from":306,"to":322}} {"id":100033061,"name":"NewCloud","signature":"func NewCloud(configReader io.Reader) (cloudprovider.Interface, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"// NewCloud returns a Cloud with initialized clients\nfunc NewCloud(configReader io.Reader) (cloudprovider.Interface, error) {\n\taz, err := NewCloudWithoutFeatureGates(configReader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taz.ipv6DualStackEnabled = true\n\n\treturn az, nil\n}","line":{"from":324,"to":333}} {"id":100033062,"name":"NewCloudWithoutFeatureGates","signature":"func NewCloudWithoutFeatureGates(configReader io.Reader) (*Cloud, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"// NewCloudWithoutFeatureGates returns a Cloud without trying to wire the feature gates. This is used by the unit tests\n// that don't load the actual features being used in the cluster.\nfunc NewCloudWithoutFeatureGates(configReader io.Reader) (*Cloud, error) {\n\tconfig, err := parseConfig(configReader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taz := \u0026Cloud{\n\t\tnodeNames: sets.NewString(),\n\t\tnodeZones: map[string]sets.String{},\n\t\tnodeResourceGroups: map[string]string{},\n\t\tunmanagedNodes: sets.NewString(),\n\t\texcludeLoadBalancerNodes: sets.NewString(),\n\t\trouteCIDRs: map[string]string{},\n\t}\n\n\terr = az.InitializeCloudFromConfig(config, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn az, nil\n}","line":{"from":335,"to":358}} {"id":100033063,"name":"InitializeCloudFromConfig","signature":"func (az *Cloud) InitializeCloudFromConfig(config *Config, fromSecret bool) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"// InitializeCloudFromConfig initializes the Cloud from config.\nfunc (az *Cloud) InitializeCloudFromConfig(config *Config, fromSecret bool) error {\n\t// cloud-config not set, return nil so that it would be initialized from secret.\n\tif config == nil {\n\t\tklog.Warning(\"cloud-config is not provided, Azure cloud provider would be initialized from secret\")\n\t\treturn nil\n\t}\n\n\tif config.RouteTableResourceGroup == \"\" {\n\t\tconfig.RouteTableResourceGroup = config.ResourceGroup\n\t}\n\n\tif config.SecurityGroupResourceGroup == \"\" {\n\t\tconfig.SecurityGroupResourceGroup = config.ResourceGroup\n\t}\n\n\tif config.VMType == \"\" {\n\t\t// default to standard vmType if not set.\n\t\tconfig.VMType = vmTypeStandard\n\t}\n\n\tif config.DisableAvailabilitySetNodes \u0026\u0026 config.VMType != vmTypeVMSS {\n\t\treturn fmt.Errorf(\"disableAvailabilitySetNodes %v is only supported when vmType is 'vmss'\", config.DisableAvailabilitySetNodes)\n\t}\n\n\tif config.CloudConfigType == \"\" {\n\t\t// The default cloud config type is cloudConfigTypeMerge.\n\t\tconfig.CloudConfigType = cloudConfigTypeMerge\n\t} else {\n\t\tsupportedCloudConfigTypes := sets.NewString(\n\t\t\tstring(cloudConfigTypeMerge),\n\t\t\tstring(cloudConfigTypeFile),\n\t\t\tstring(cloudConfigTypeSecret))\n\t\tif !supportedCloudConfigTypes.Has(string(config.CloudConfigType)) {\n\t\t\treturn fmt.Errorf(\"cloudConfigType %v is not supported, supported values are %v\", config.CloudConfigType, supportedCloudConfigTypes.List())\n\t\t}\n\t}\n\n\tenv, err := auth.ParseAzureEnvironment(config.Cloud, config.ResourceManagerEndpoint, config.IdentitySystem)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tservicePrincipalToken, err := auth.GetServicePrincipalToken(\u0026config.AzureAuthConfig, env)\n\tif err == auth.ErrorNoAuth {\n\t\t// Only controller-manager would lazy-initialize from secret, and credentials are required for such case.\n\t\tif fromSecret {\n\t\t\terr := fmt.Errorf(\"no credentials provided for Azure cloud provider\")\n\t\t\tklog.Fatalf(\"%v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t// No credentials provided, useInstanceMetadata should be enabled for Kubelet.\n\t\t// TODO(feiskyer): print different error message for Kubelet and controller-manager, as they're\n\t\t// requiring different credential settings.\n\t\tif !config.UseInstanceMetadata \u0026\u0026 config.CloudConfigType == cloudConfigTypeFile {\n\t\t\treturn fmt.Errorf(\"useInstanceMetadata must be enabled without Azure credentials\")\n\t\t}\n\n\t\tklog.V(2).Infof(\"Azure cloud provider is starting without credentials\")\n\t} else if err != nil {\n\t\treturn err\n\t}\n\n\t// Initialize rate limiting config options.\n\tInitializeCloudProviderRateLimitConfig(\u0026config.CloudProviderRateLimitConfig)\n\n\t// Conditionally configure resource request backoff\n\tresourceRequestBackoff := wait.Backoff{\n\t\tSteps: 1,\n\t}\n\tif config.CloudProviderBackoff {\n\t\t// Assign backoff defaults if no configuration was passed in\n\t\tif config.CloudProviderBackoffRetries == 0 {\n\t\t\tconfig.CloudProviderBackoffRetries = backoffRetriesDefault\n\t\t}\n\t\tif config.CloudProviderBackoffDuration == 0 {\n\t\t\tconfig.CloudProviderBackoffDuration = backoffDurationDefault\n\t\t}\n\t\tif config.CloudProviderBackoffExponent == 0 {\n\t\t\tconfig.CloudProviderBackoffExponent = backoffExponentDefault\n\t\t}\n\n\t\tif config.CloudProviderBackoffJitter == 0 {\n\t\t\tconfig.CloudProviderBackoffJitter = backoffJitterDefault\n\t\t}\n\n\t\tresourceRequestBackoff = wait.Backoff{\n\t\t\tSteps: config.CloudProviderBackoffRetries,\n\t\t\tFactor: config.CloudProviderBackoffExponent,\n\t\t\tDuration: time.Duration(config.CloudProviderBackoffDuration) * time.Second,\n\t\t\tJitter: config.CloudProviderBackoffJitter,\n\t\t}\n\t\tklog.V(2).Infof(\"Azure cloudprovider using try backoff: retries=%d, exponent=%f, duration=%d, jitter=%f\",\n\t\t\tconfig.CloudProviderBackoffRetries,\n\t\t\tconfig.CloudProviderBackoffExponent,\n\t\t\tconfig.CloudProviderBackoffDuration,\n\t\t\tconfig.CloudProviderBackoffJitter)\n\t} else {\n\t\t// CloudProviderBackoffRetries will be set to 1 by default as the requirements of Azure SDK.\n\t\tconfig.CloudProviderBackoffRetries = 1\n\t\tconfig.CloudProviderBackoffDuration = backoffDurationDefault\n\t}\n\n\tif strings.EqualFold(config.LoadBalancerSku, loadBalancerSkuStandard) {\n\t\t// Do not add master nodes to standard LB by default.\n\t\tif config.ExcludeMasterFromStandardLB == nil {\n\t\t\tconfig.ExcludeMasterFromStandardLB = \u0026defaultExcludeMasterFromStandardLB\n\t\t}\n\n\t\t// Enable outbound SNAT by default.\n\t\tif config.DisableOutboundSNAT == nil {\n\t\t\tconfig.DisableOutboundSNAT = \u0026defaultDisableOutboundSNAT\n\t\t}\n\t} else {\n\t\tif config.DisableOutboundSNAT != nil \u0026\u0026 *config.DisableOutboundSNAT {\n\t\t\treturn fmt.Errorf(\"disableOutboundSNAT should only set when loadBalancerSku is standard\")\n\t\t}\n\t}\n\n\taz.Config = *config\n\taz.Environment = *env\n\taz.ResourceRequestBackoff = resourceRequestBackoff\n\taz.metadata, err = NewInstanceMetadataService(imdsServer)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// No credentials provided, InstanceMetadataService would be used for getting Azure resources.\n\t// Note that this only applies to Kubelet, controller-manager should configure credentials for managing Azure resources.\n\tif servicePrincipalToken == nil {\n\t\treturn nil\n\t}\n\n\t// If uses network resources in different AAD Tenant, then prepare corresponding Service Principal Token for VM/VMSS client and network resources client\n\tvar multiTenantServicePrincipalToken *adal.MultiTenantServicePrincipalToken\n\tvar networkResourceServicePrincipalToken *adal.ServicePrincipalToken\n\tif az.Config.UsesNetworkResourceInDifferentTenant() {\n\t\tmultiTenantServicePrincipalToken, err = auth.GetMultiTenantServicePrincipalToken(\u0026az.Config.AzureAuthConfig, \u0026az.Environment)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnetworkResourceServicePrincipalToken, err = auth.GetNetworkResourceServicePrincipalToken(\u0026az.Config.AzureAuthConfig, \u0026az.Environment)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\taz.configAzureClients(servicePrincipalToken, multiTenantServicePrincipalToken, networkResourceServicePrincipalToken)\n\n\tif az.MaximumLoadBalancerRuleCount == 0 {\n\t\taz.MaximumLoadBalancerRuleCount = maximumLoadBalancerRuleCount\n\t}\n\n\tif strings.EqualFold(vmTypeVMSS, az.Config.VMType) {\n\t\taz.VMSet, err = newScaleSet(az)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\taz.VMSet = newAvailabilitySet(az)\n\t}\n\n\taz.vmCache, err = az.newVMCache()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\taz.lbCache, err = az.newLBCache()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\taz.nsgCache, err = az.newNSGCache()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\taz.rtCache, err = az.newRouteTableCache()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := initDiskControllers(az); err != nil {\n\t\treturn err\n\t}\n\n\t// start delayed route updater.\n\taz.routeUpdater = newDelayedRouteUpdater(az, routeUpdateInterval)\n\tgo az.routeUpdater.run()\n\n\treturn nil\n}","line":{"from":360,"to":552}} {"id":100033064,"name":"configAzureClients","signature":"func (az *Cloud) configAzureClients(","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"func (az *Cloud) configAzureClients(\n\tservicePrincipalToken *adal.ServicePrincipalToken,\n\tmultiTenantServicePrincipalToken *adal.MultiTenantServicePrincipalToken,\n\tnetworkResourceServicePrincipalToken *adal.ServicePrincipalToken) {\n\tazClientConfig := az.getAzureClientConfig(servicePrincipalToken)\n\n\t// Prepare AzureClientConfig for all azure clients\n\tinterfaceClientConfig := azClientConfig.WithRateLimiter(az.Config.InterfaceRateLimit)\n\tvmSizeClientConfig := azClientConfig.WithRateLimiter(az.Config.VirtualMachineSizeRateLimit)\n\tsnapshotClientConfig := azClientConfig.WithRateLimiter(az.Config.SnapshotRateLimit)\n\tstorageAccountClientConfig := azClientConfig.WithRateLimiter(az.Config.StorageAccountRateLimit)\n\tdiskClientConfig := azClientConfig.WithRateLimiter(az.Config.DiskRateLimit)\n\tvmClientConfig := azClientConfig.WithRateLimiter(az.Config.VirtualMachineRateLimit)\n\tvmssClientConfig := azClientConfig.WithRateLimiter(az.Config.VirtualMachineScaleSetRateLimit)\n\t// Error \"not an active Virtual Machine Scale Set VM\" is not retriable for VMSS VM.\n\t// But http.StatusNotFound is retriable because of ARM replication latency.\n\tvmssVMClientConfig := azClientConfig.WithRateLimiter(az.Config.VirtualMachineScaleSetRateLimit)\n\tvmssVMClientConfig.Backoff = vmssVMClientConfig.Backoff.WithNonRetriableErrors([]string{vmssVMNotActiveErrorMessage}).WithRetriableHTTPStatusCodes([]int{http.StatusNotFound})\n\trouteClientConfig := azClientConfig.WithRateLimiter(az.Config.RouteRateLimit)\n\tsubnetClientConfig := azClientConfig.WithRateLimiter(az.Config.SubnetsRateLimit)\n\trouteTableClientConfig := azClientConfig.WithRateLimiter(az.Config.RouteTableRateLimit)\n\tloadBalancerClientConfig := azClientConfig.WithRateLimiter(az.Config.LoadBalancerRateLimit)\n\tsecurityGroupClientConfig := azClientConfig.WithRateLimiter(az.Config.SecurityGroupRateLimit)\n\tpublicIPClientConfig := azClientConfig.WithRateLimiter(az.Config.PublicIPAddressRateLimit)\n\t// TODO(ZeroMagic): add azurefileRateLimit\n\tfileClientConfig := azClientConfig.WithRateLimiter(nil)\n\n\t// If uses network resources in different AAD Tenant, update Authorizer for VM/VMSS client config\n\tif multiTenantServicePrincipalToken != nil {\n\t\tmultiTenantServicePrincipalTokenAuthorizer := autorest.NewMultiTenantServicePrincipalTokenAuthorizer(multiTenantServicePrincipalToken)\n\t\tvmClientConfig.Authorizer = multiTenantServicePrincipalTokenAuthorizer\n\t\tvmssClientConfig.Authorizer = multiTenantServicePrincipalTokenAuthorizer\n\t\tvmssVMClientConfig.Authorizer = multiTenantServicePrincipalTokenAuthorizer\n\t}\n\n\t// If uses network resources in different AAD Tenant, update SubscriptionID and Authorizer for network resources client config\n\tif networkResourceServicePrincipalToken != nil {\n\t\tnetworkResourceServicePrincipalTokenAuthorizer := autorest.NewBearerAuthorizer(networkResourceServicePrincipalToken)\n\t\trouteClientConfig.Authorizer = networkResourceServicePrincipalTokenAuthorizer\n\t\tsubnetClientConfig.Authorizer = networkResourceServicePrincipalTokenAuthorizer\n\t\trouteTableClientConfig.Authorizer = networkResourceServicePrincipalTokenAuthorizer\n\t\tloadBalancerClientConfig.Authorizer = networkResourceServicePrincipalTokenAuthorizer\n\t\tsecurityGroupClientConfig.Authorizer = networkResourceServicePrincipalTokenAuthorizer\n\t\tpublicIPClientConfig.Authorizer = networkResourceServicePrincipalTokenAuthorizer\n\n\t\trouteClientConfig.SubscriptionID = az.Config.NetworkResourceSubscriptionID\n\t\tsubnetClientConfig.SubscriptionID = az.Config.NetworkResourceSubscriptionID\n\t\trouteTableClientConfig.SubscriptionID = az.Config.NetworkResourceSubscriptionID\n\t\tloadBalancerClientConfig.SubscriptionID = az.Config.NetworkResourceSubscriptionID\n\t\tsecurityGroupClientConfig.SubscriptionID = az.Config.NetworkResourceSubscriptionID\n\t\tpublicIPClientConfig.SubscriptionID = az.Config.NetworkResourceSubscriptionID\n\t}\n\n\t// Initialize all azure clients based on client config\n\taz.InterfacesClient = interfaceclient.New(interfaceClientConfig)\n\taz.VirtualMachineSizesClient = vmsizeclient.New(vmSizeClientConfig)\n\taz.SnapshotsClient = snapshotclient.New(snapshotClientConfig)\n\taz.StorageAccountClient = storageaccountclient.New(storageAccountClientConfig)\n\taz.DisksClient = diskclient.New(diskClientConfig)\n\taz.VirtualMachinesClient = vmclient.New(vmClientConfig)\n\taz.VirtualMachineScaleSetsClient = vmssclient.New(vmssClientConfig)\n\taz.VirtualMachineScaleSetVMsClient = vmssvmclient.New(vmssVMClientConfig)\n\taz.RoutesClient = routeclient.New(routeClientConfig)\n\taz.SubnetsClient = subnetclient.New(subnetClientConfig)\n\taz.RouteTablesClient = routetableclient.New(routeTableClientConfig)\n\taz.LoadBalancerClient = loadbalancerclient.New(loadBalancerClientConfig)\n\taz.SecurityGroupsClient = securitygroupclient.New(securityGroupClientConfig)\n\taz.PublicIPAddressesClient = publicipclient.New(publicIPClientConfig)\n\taz.FileClient = fileclient.New(fileClientConfig)\n}","line":{"from":554,"to":623}} {"id":100033065,"name":"getAzureClientConfig","signature":"func (az *Cloud) getAzureClientConfig(servicePrincipalToken *adal.ServicePrincipalToken) *azclients.ClientConfig","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"func (az *Cloud) getAzureClientConfig(servicePrincipalToken *adal.ServicePrincipalToken) *azclients.ClientConfig {\n\tazClientConfig := \u0026azclients.ClientConfig{\n\t\tCloudName: az.Config.Cloud,\n\t\tLocation: az.Config.Location,\n\t\tSubscriptionID: az.Config.SubscriptionID,\n\t\tResourceManagerEndpoint: az.Environment.ResourceManagerEndpoint,\n\t\tAuthorizer: autorest.NewBearerAuthorizer(servicePrincipalToken),\n\t\tBackoff: \u0026retry.Backoff{Steps: 1},\n\t}\n\n\tif az.Config.CloudProviderBackoff {\n\t\tazClientConfig.Backoff = \u0026retry.Backoff{\n\t\t\tSteps: az.Config.CloudProviderBackoffRetries,\n\t\t\tFactor: az.Config.CloudProviderBackoffExponent,\n\t\t\tDuration: time.Duration(az.Config.CloudProviderBackoffDuration) * time.Second,\n\t\t\tJitter: az.Config.CloudProviderBackoffJitter,\n\t\t}\n\t}\n\n\treturn azClientConfig\n}","line":{"from":625,"to":645}} {"id":100033066,"name":"parseConfig","signature":"func parseConfig(configReader io.Reader) (*Config, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"// parseConfig returns a parsed configuration for an Azure cloudprovider config file\nfunc parseConfig(configReader io.Reader) (*Config, error) {\n\tvar config Config\n\tif configReader == nil {\n\t\treturn nil, nil\n\t}\n\n\tconfigContents, err := ioutil.ReadAll(configReader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = yaml.Unmarshal(configContents, \u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// The resource group name may be in different cases from different Azure APIs, hence it is converted to lower here.\n\t// See more context at https://github.com/kubernetes/kubernetes/issues/71994.\n\tconfig.ResourceGroup = strings.ToLower(config.ResourceGroup)\n\treturn \u0026config, nil\n}","line":{"from":647,"to":668}} {"id":100033067,"name":"Initialize","signature":"func (az *Cloud) Initialize(clientBuilder cloudprovider.ControllerClientBuilder, stop \u003c-chan struct{})","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"// Initialize passes a Kubernetes clientBuilder interface to the cloud provider\nfunc (az *Cloud) Initialize(clientBuilder cloudprovider.ControllerClientBuilder, stop \u003c-chan struct{}) {\n\taz.KubeClient = clientBuilder.ClientOrDie(\"azure-cloud-provider\")\n\taz.eventBroadcaster = record.NewBroadcaster()\n\taz.eventBroadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: az.KubeClient.CoreV1().Events(\"\")})\n\taz.eventRecorder = az.eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"azure-cloud-provider\"})\n\taz.InitializeCloudFromSecret()\n}","line":{"from":670,"to":677}} {"id":100033068,"name":"LoadBalancer","signature":"func (az *Cloud) LoadBalancer() (cloudprovider.LoadBalancer, bool)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"// LoadBalancer returns a balancer interface. Also returns true if the interface is supported, false otherwise.\nfunc (az *Cloud) LoadBalancer() (cloudprovider.LoadBalancer, bool) {\n\treturn az, true\n}","line":{"from":679,"to":682}} {"id":100033069,"name":"Instances","signature":"func (az *Cloud) Instances() (cloudprovider.Instances, bool)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"// Instances returns an instances interface. Also returns true if the interface is supported, false otherwise.\nfunc (az *Cloud) Instances() (cloudprovider.Instances, bool) {\n\treturn az, true\n}","line":{"from":684,"to":687}} {"id":100033070,"name":"InstancesV2","signature":"func (az *Cloud) InstancesV2() (cloudprovider.InstancesV2, bool)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"// InstancesV2 returns an instancesV2 interface. Also returns true if the interface is supported, false otherwise.\n// TODO: implement ONLY for external cloud provider\nfunc (az *Cloud) InstancesV2() (cloudprovider.InstancesV2, bool) {\n\treturn nil, false\n}","line":{"from":689,"to":693}} {"id":100033071,"name":"Zones","signature":"func (az *Cloud) Zones() (cloudprovider.Zones, bool)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"// Zones returns a zones interface. Also returns true if the interface is supported, false otherwise.\nfunc (az *Cloud) Zones() (cloudprovider.Zones, bool) {\n\treturn az, true\n}","line":{"from":695,"to":698}} {"id":100033072,"name":"Clusters","signature":"func (az *Cloud) Clusters() (cloudprovider.Clusters, bool)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"// Clusters returns a clusters interface. Also returns true if the interface is supported, false otherwise.\nfunc (az *Cloud) Clusters() (cloudprovider.Clusters, bool) {\n\treturn nil, false\n}","line":{"from":700,"to":703}} {"id":100033073,"name":"Routes","signature":"func (az *Cloud) Routes() (cloudprovider.Routes, bool)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"// Routes returns a routes interface along with whether the interface is supported.\nfunc (az *Cloud) Routes() (cloudprovider.Routes, bool) {\n\treturn az, true\n}","line":{"from":705,"to":708}} {"id":100033074,"name":"HasClusterID","signature":"func (az *Cloud) HasClusterID() bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"// HasClusterID returns true if the cluster has a clusterID\nfunc (az *Cloud) HasClusterID() bool {\n\treturn true\n}","line":{"from":710,"to":713}} {"id":100033075,"name":"ProviderName","signature":"func (az *Cloud) ProviderName() string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"// ProviderName returns the cloud provider ID.\nfunc (az *Cloud) ProviderName() string {\n\treturn CloudProviderName\n}","line":{"from":715,"to":718}} {"id":100033076,"name":"initDiskControllers","signature":"func initDiskControllers(az *Cloud) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"func initDiskControllers(az *Cloud) error {\n\t// Common controller contains the function\n\t// needed by both blob disk and managed disk controllers\n\n\tcommon := \u0026controllerCommon{\n\t\tlocation: az.Location,\n\t\tstorageEndpointSuffix: az.Environment.StorageEndpointSuffix,\n\t\tresourceGroup: az.ResourceGroup,\n\t\tsubscriptionID: az.SubscriptionID,\n\t\tcloud: az,\n\t\tvmLockMap: newLockMap(),\n\t}\n\n\taz.BlobDiskController = \u0026BlobDiskController{common: common}\n\taz.ManagedDiskController = \u0026ManagedDiskController{common: common}\n\taz.controllerCommon = common\n\n\treturn nil\n}","line":{"from":720,"to":738}} {"id":100033077,"name":"SetInformers","signature":"func (az *Cloud) SetInformers(informerFactory informers.SharedInformerFactory)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"// SetInformers sets informers for Azure cloud provider.\nfunc (az *Cloud) SetInformers(informerFactory informers.SharedInformerFactory) {\n\tklog.Infof(\"Setting up informers for Azure cloud provider\")\n\tnodeInformer := informerFactory.Core().V1().Nodes().Informer()\n\tnodeInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tnode := obj.(*v1.Node)\n\t\t\taz.updateNodeCaches(nil, node)\n\t\t},\n\t\tUpdateFunc: func(prev, obj interface{}) {\n\t\t\tprevNode := prev.(*v1.Node)\n\t\t\tnewNode := obj.(*v1.Node)\n\t\t\taz.updateNodeCaches(prevNode, newNode)\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tnode, isNode := obj.(*v1.Node)\n\t\t\t// We can get DeletedFinalStateUnknown instead of *v1.Node here\n\t\t\t// and we need to handle that correctly.\n\t\t\tif !isNode {\n\t\t\t\tdeletedState, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\t\t\tif !ok {\n\t\t\t\t\tklog.Errorf(\"Received unexpected object: %v\", obj)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tnode, ok = deletedState.Obj.(*v1.Node)\n\t\t\t\tif !ok {\n\t\t\t\t\tklog.Errorf(\"DeletedFinalStateUnknown contained non-Node object: %v\", deletedState.Obj)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\taz.updateNodeCaches(node, nil)\n\t\t},\n\t})\n\taz.nodeInformerSynced = nodeInformer.HasSynced\n}","line":{"from":740,"to":774}} {"id":100033078,"name":"updateNodeCaches","signature":"func (az *Cloud) updateNodeCaches(prevNode, newNode *v1.Node)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"// updateNodeCaches updates local cache for node's zones and external resource groups.\nfunc (az *Cloud) updateNodeCaches(prevNode, newNode *v1.Node) {\n\taz.nodeCachesLock.Lock()\n\tdefer az.nodeCachesLock.Unlock()\n\n\tif prevNode != nil {\n\n\t\t// Remove from nodeNames cache.\n\t\taz.nodeNames.Delete(prevNode.ObjectMeta.Name)\n\n\t\t// Remove from nodeZones cache\n\t\tprevZone, ok := prevNode.ObjectMeta.Labels[v1.LabelTopologyZone]\n\n\t\tif ok \u0026\u0026 az.isAvailabilityZone(prevZone) {\n\t\t\taz.nodeZones[prevZone].Delete(prevNode.ObjectMeta.Name)\n\t\t\tif az.nodeZones[prevZone].Len() == 0 {\n\t\t\t\taz.nodeZones[prevZone] = nil\n\t\t\t}\n\t\t}\n\n\t\t// Remove from nodeZones cache if using deprecated LabelFailureDomainBetaZone\n\t\tprevZoneFailureDomain, ok := prevNode.ObjectMeta.Labels[v1.LabelFailureDomainBetaZone]\n\t\tif ok \u0026\u0026 az.isAvailabilityZone(prevZoneFailureDomain) {\n\t\t\taz.nodeZones[prevZone].Delete(prevNode.ObjectMeta.Name)\n\t\t\tif az.nodeZones[prevZone].Len() == 0 {\n\t\t\t\taz.nodeZones[prevZone] = nil\n\t\t\t}\n\t\t}\n\n\t\t// Remove from nodeResourceGroups cache.\n\t\t_, ok = prevNode.ObjectMeta.Labels[externalResourceGroupLabel]\n\t\tif ok {\n\t\t\tdelete(az.nodeResourceGroups, prevNode.ObjectMeta.Name)\n\t\t}\n\n\t\tmanaged, ok := prevNode.ObjectMeta.Labels[managedByAzureLabel]\n\t\tisNodeManagedByCloudProvider := !ok || managed != \"false\"\n\n\t\t// Remove from unmanagedNodes cache\n\t\tif !isNodeManagedByCloudProvider {\n\t\t\taz.unmanagedNodes.Delete(prevNode.ObjectMeta.Name)\n\t\t}\n\n\t\t// if the node is being deleted from the cluster, exclude it from load balancers\n\t\tif newNode == nil {\n\t\t\taz.excludeLoadBalancerNodes.Insert(prevNode.ObjectMeta.Name)\n\t\t}\n\t}\n\n\tif newNode != nil {\n\t\t// Add to nodeNames cache.\n\t\taz.nodeNames.Insert(newNode.ObjectMeta.Name)\n\n\t\t// Add to nodeZones cache.\n\t\tnewZone, ok := newNode.ObjectMeta.Labels[v1.LabelTopologyZone]\n\t\tif ok \u0026\u0026 az.isAvailabilityZone(newZone) {\n\t\t\tif az.nodeZones[newZone] == nil {\n\t\t\t\taz.nodeZones[newZone] = sets.NewString()\n\t\t\t}\n\t\t\taz.nodeZones[newZone].Insert(newNode.ObjectMeta.Name)\n\t\t}\n\n\t\t// Add to nodeResourceGroups cache.\n\t\tnewRG, ok := newNode.ObjectMeta.Labels[externalResourceGroupLabel]\n\t\tif ok \u0026\u0026 len(newRG) \u003e 0 {\n\t\t\taz.nodeResourceGroups[newNode.ObjectMeta.Name] = strings.ToLower(newRG)\n\t\t}\n\n\t\t_, hasExcludeBalancerLabel := newNode.ObjectMeta.Labels[v1.LabelNodeExcludeBalancers]\n\t\tmanaged, ok := newNode.ObjectMeta.Labels[managedByAzureLabel]\n\t\tisNodeManagedByCloudProvider := !ok || managed != \"false\"\n\n\t\t// Update unmanagedNodes cache\n\t\tif !isNodeManagedByCloudProvider {\n\t\t\taz.unmanagedNodes.Insert(newNode.ObjectMeta.Name)\n\t\t}\n\n\t\t// Update excludeLoadBalancerNodes cache\n\t\tswitch {\n\t\tcase !isNodeManagedByCloudProvider:\n\t\t\taz.excludeLoadBalancerNodes.Insert(newNode.ObjectMeta.Name)\n\n\t\tcase hasExcludeBalancerLabel:\n\t\t\taz.excludeLoadBalancerNodes.Insert(newNode.ObjectMeta.Name)\n\n\t\tcase !isNodeReady(newNode) \u0026\u0026 getCloudTaint(newNode.Spec.Taints) == nil:\n\t\t\t// If not in ready state and not a newly created node, add to excludeLoadBalancerNodes cache.\n\t\t\t// New nodes (tainted with \"node.cloudprovider.kubernetes.io/uninitialized\") should not be\n\t\t\t// excluded from load balancers regardless of their state, so as to reduce the number of\n\t\t\t// VMSS API calls and not provoke VMScaleSetActiveModelsCountLimitReached.\n\t\t\t// (https://github.com/kubernetes-sigs/cloud-provider-azure/issues/851)\n\t\t\taz.excludeLoadBalancerNodes.Insert(newNode.ObjectMeta.Name)\n\n\t\tdefault:\n\t\t\t// Nodes not falling into the three cases above are valid backends and\n\t\t\t// should not appear in excludeLoadBalancerNodes cache.\n\t\t\taz.excludeLoadBalancerNodes.Delete(newNode.ObjectMeta.Name)\n\t\t}\n\t}\n}","line":{"from":776,"to":875}} {"id":100033079,"name":"GetActiveZones","signature":"func (az *Cloud) GetActiveZones() (sets.String, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"// GetActiveZones returns all the zones in which k8s nodes are currently running.\nfunc (az *Cloud) GetActiveZones() (sets.String, error) {\n\tif az.nodeInformerSynced == nil {\n\t\treturn nil, fmt.Errorf(\"azure cloud provider doesn't have informers set\")\n\t}\n\n\taz.nodeCachesLock.RLock()\n\tdefer az.nodeCachesLock.RUnlock()\n\tif !az.nodeInformerSynced() {\n\t\treturn nil, fmt.Errorf(\"node informer is not synced when trying to GetActiveZones\")\n\t}\n\n\tzones := sets.NewString()\n\tfor zone, nodes := range az.nodeZones {\n\t\tif len(nodes) \u003e 0 {\n\t\t\tzones.Insert(zone)\n\t\t}\n\t}\n\treturn zones, nil\n}","line":{"from":877,"to":896}} {"id":100033080,"name":"GetLocation","signature":"func (az *Cloud) GetLocation() string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"// GetLocation returns the location in which k8s cluster is currently running.\nfunc (az *Cloud) GetLocation() string {\n\treturn az.Location\n}","line":{"from":898,"to":901}} {"id":100033081,"name":"GetNodeResourceGroup","signature":"func (az *Cloud) GetNodeResourceGroup(nodeName string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"// GetNodeResourceGroup gets resource group for given node.\nfunc (az *Cloud) GetNodeResourceGroup(nodeName string) (string, error) {\n\t// Kubelet won't set az.nodeInformerSynced, always return configured resourceGroup.\n\tif az.nodeInformerSynced == nil {\n\t\treturn az.ResourceGroup, nil\n\t}\n\n\taz.nodeCachesLock.RLock()\n\tdefer az.nodeCachesLock.RUnlock()\n\tif !az.nodeInformerSynced() {\n\t\treturn \"\", fmt.Errorf(\"node informer is not synced when trying to GetNodeResourceGroup\")\n\t}\n\n\t// Return external resource group if it has been cached.\n\tif cachedRG, ok := az.nodeResourceGroups[nodeName]; ok {\n\t\treturn cachedRG, nil\n\t}\n\n\t// Return resource group from cloud provider options.\n\treturn az.ResourceGroup, nil\n}","line":{"from":903,"to":923}} {"id":100033082,"name":"GetNodeNames","signature":"func (az *Cloud) GetNodeNames() (sets.String, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"// GetNodeNames returns a set of all node names in the k8s cluster.\nfunc (az *Cloud) GetNodeNames() (sets.String, error) {\n\t// Kubelet won't set az.nodeInformerSynced, return nil.\n\tif az.nodeInformerSynced == nil {\n\t\treturn nil, nil\n\t}\n\n\taz.nodeCachesLock.RLock()\n\tdefer az.nodeCachesLock.RUnlock()\n\tif !az.nodeInformerSynced() {\n\t\treturn nil, fmt.Errorf(\"node informer is not synced when trying to GetNodeNames\")\n\t}\n\n\treturn sets.NewString(az.nodeNames.List()...), nil\n}","line":{"from":925,"to":939}} {"id":100033083,"name":"GetResourceGroups","signature":"func (az *Cloud) GetResourceGroups() (sets.String, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"// GetResourceGroups returns a set of resource groups that all nodes are running on.\nfunc (az *Cloud) GetResourceGroups() (sets.String, error) {\n\t// Kubelet won't set az.nodeInformerSynced, always return configured resourceGroup.\n\tif az.nodeInformerSynced == nil {\n\t\treturn sets.NewString(az.ResourceGroup), nil\n\t}\n\n\taz.nodeCachesLock.RLock()\n\tdefer az.nodeCachesLock.RUnlock()\n\tif !az.nodeInformerSynced() {\n\t\treturn nil, fmt.Errorf(\"node informer is not synced when trying to GetResourceGroups\")\n\t}\n\n\tresourceGroups := sets.NewString(az.ResourceGroup)\n\tfor _, rg := range az.nodeResourceGroups {\n\t\tresourceGroups.Insert(rg)\n\t}\n\n\treturn resourceGroups, nil\n}","line":{"from":941,"to":960}} {"id":100033084,"name":"GetUnmanagedNodes","signature":"func (az *Cloud) GetUnmanagedNodes() (sets.String, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"// GetUnmanagedNodes returns a list of nodes not managed by Azure cloud provider (e.g. on-prem nodes).\nfunc (az *Cloud) GetUnmanagedNodes() (sets.String, error) {\n\t// Kubelet won't set az.nodeInformerSynced, always return nil.\n\tif az.nodeInformerSynced == nil {\n\t\treturn nil, nil\n\t}\n\n\taz.nodeCachesLock.RLock()\n\tdefer az.nodeCachesLock.RUnlock()\n\tif !az.nodeInformerSynced() {\n\t\treturn nil, fmt.Errorf(\"node informer is not synced when trying to GetUnmanagedNodes\")\n\t}\n\n\treturn sets.NewString(az.unmanagedNodes.List()...), nil\n}","line":{"from":962,"to":976}} {"id":100033085,"name":"ShouldNodeExcludedFromLoadBalancer","signature":"func (az *Cloud) ShouldNodeExcludedFromLoadBalancer(nodeName string) (bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"// ShouldNodeExcludedFromLoadBalancer returns true if node is unmanaged, in external resource group or labeled with \"node.kubernetes.io/exclude-from-external-load-balancers\".\nfunc (az *Cloud) ShouldNodeExcludedFromLoadBalancer(nodeName string) (bool, error) {\n\t// Kubelet won't set az.nodeInformerSynced, always return nil.\n\tif az.nodeInformerSynced == nil {\n\t\treturn false, nil\n\t}\n\n\taz.nodeCachesLock.RLock()\n\tdefer az.nodeCachesLock.RUnlock()\n\tif !az.nodeInformerSynced() {\n\t\treturn false, fmt.Errorf(\"node informer is not synced when trying to fetch node caches\")\n\t}\n\n\t// Return true if the node is in external resource group.\n\tif cachedRG, ok := az.nodeResourceGroups[nodeName]; ok \u0026\u0026 !strings.EqualFold(cachedRG, az.ResourceGroup) {\n\t\treturn true, nil\n\t}\n\n\treturn az.excludeLoadBalancerNodes.Has(nodeName), nil\n}","line":{"from":978,"to":997}} {"id":100033086,"name":"isNodeReady","signature":"func isNodeReady(node *v1.Node) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"func isNodeReady(node *v1.Node) bool {\n\tfor _, cond := range node.Status.Conditions {\n\t\tif cond.Type == v1.NodeReady \u0026\u0026 cond.Status == v1.ConditionTrue {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":999,"to":1006}} {"id":100033087,"name":"getCloudTaint","signature":"func getCloudTaint(taints []v1.Taint) *v1.Taint","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure.go","code":"func getCloudTaint(taints []v1.Taint) *v1.Taint {\n\tfor _, taint := range taints {\n\t\tif taint.Key == cloudproviderapi.TaintExternalCloudProvider {\n\t\t\treturn \u0026taint\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":1008,"to":1015}} {"id":100033088,"name":"RequestBackoff","signature":"func (az *Cloud) RequestBackoff() (resourceRequestBackoff wait.Backoff)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_backoff.go","code":"// RequestBackoff if backoff is disabled in cloud provider it\n// returns a new Backoff object steps = 1\n// This is to make sure that the requested command executes\n// at least once\nfunc (az *Cloud) RequestBackoff() (resourceRequestBackoff wait.Backoff) {\n\tif az.CloudProviderBackoff {\n\t\treturn az.ResourceRequestBackoff\n\t}\n\tresourceRequestBackoff = wait.Backoff{\n\t\tSteps: 1,\n\t}\n\treturn resourceRequestBackoff\n}","line":{"from":57,"to":69}} {"id":100033089,"name":"Event","signature":"func (az *Cloud) Event(obj runtime.Object, eventType, reason, message string)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_backoff.go","code":"// Event creates a event for the specified object.\nfunc (az *Cloud) Event(obj runtime.Object, eventType, reason, message string) {\n\tif obj != nil \u0026\u0026 reason != \"\" {\n\t\taz.eventRecorder.Event(obj, eventType, reason, message)\n\t}\n}","line":{"from":71,"to":76}} {"id":100033090,"name":"GetVirtualMachineWithRetry","signature":"func (az *Cloud) GetVirtualMachineWithRetry(name types.NodeName, crt azcache.AzureCacheReadType) (compute.VirtualMachine, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_backoff.go","code":"// GetVirtualMachineWithRetry invokes az.getVirtualMachine with exponential backoff retry\nfunc (az *Cloud) GetVirtualMachineWithRetry(name types.NodeName, crt azcache.AzureCacheReadType) (compute.VirtualMachine, error) {\n\tvar machine compute.VirtualMachine\n\tvar retryErr error\n\terr := wait.ExponentialBackoff(az.RequestBackoff(), func() (bool, error) {\n\t\tmachine, retryErr = az.getVirtualMachine(name, crt)\n\t\tif retryErr == cloudprovider.InstanceNotFound {\n\t\t\treturn true, cloudprovider.InstanceNotFound\n\t\t}\n\t\tif retryErr != nil {\n\t\t\tklog.Errorf(\"GetVirtualMachineWithRetry(%s): backoff failure, will retry, err=%v\", name, retryErr)\n\t\t\treturn false, nil\n\t\t}\n\t\tklog.V(2).Infof(\"GetVirtualMachineWithRetry(%s): backoff success\", name)\n\t\treturn true, nil\n\t})\n\tif err == wait.ErrWaitTimeout {\n\t\terr = retryErr\n\t}\n\treturn machine, err\n}","line":{"from":78,"to":98}} {"id":100033091,"name":"ListVirtualMachines","signature":"func (az *Cloud) ListVirtualMachines(resourceGroup string) ([]compute.VirtualMachine, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_backoff.go","code":"// ListVirtualMachines invokes az.VirtualMachinesClient.List with exponential backoff retry\nfunc (az *Cloud) ListVirtualMachines(resourceGroup string) ([]compute.VirtualMachine, error) {\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\n\tallNodes, rerr := az.VirtualMachinesClient.List(ctx, resourceGroup)\n\tif rerr != nil {\n\t\tklog.Errorf(\"VirtualMachinesClient.List(%v) failure with err=%v\", resourceGroup, rerr)\n\t\treturn nil, rerr.Error()\n\t}\n\tklog.V(2).Infof(\"VirtualMachinesClient.List(%v) success\", resourceGroup)\n\treturn allNodes, nil\n}","line":{"from":100,"to":112}} {"id":100033092,"name":"getPrivateIPsForMachine","signature":"func (az *Cloud) getPrivateIPsForMachine(nodeName types.NodeName) ([]string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_backoff.go","code":"// getPrivateIPsForMachine is wrapper for optional backoff getting private ips\n// list of a node by name\nfunc (az *Cloud) getPrivateIPsForMachine(nodeName types.NodeName) ([]string, error) {\n\treturn az.getPrivateIPsForMachineWithRetry(nodeName)\n}","line":{"from":114,"to":118}} {"id":100033093,"name":"getPrivateIPsForMachineWithRetry","signature":"func (az *Cloud) getPrivateIPsForMachineWithRetry(nodeName types.NodeName) ([]string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_backoff.go","code":"func (az *Cloud) getPrivateIPsForMachineWithRetry(nodeName types.NodeName) ([]string, error) {\n\tvar privateIPs []string\n\terr := wait.ExponentialBackoff(az.RequestBackoff(), func() (bool, error) {\n\t\tvar retryErr error\n\t\tprivateIPs, retryErr = az.VMSet.GetPrivateIPsByNodeName(string(nodeName))\n\t\tif retryErr != nil {\n\t\t\t// won't retry since the instance doesn't exist on Azure.\n\t\t\tif retryErr == cloudprovider.InstanceNotFound {\n\t\t\t\treturn true, retryErr\n\t\t\t}\n\t\t\tklog.Errorf(\"GetPrivateIPsByNodeName(%s): backoff failure, will retry,err=%v\", nodeName, retryErr)\n\t\t\treturn false, nil\n\t\t}\n\t\tklog.V(3).Infof(\"GetPrivateIPsByNodeName(%s): backoff success\", nodeName)\n\t\treturn true, nil\n\t})\n\treturn privateIPs, err\n}","line":{"from":120,"to":137}} {"id":100033094,"name":"getIPForMachine","signature":"func (az *Cloud) getIPForMachine(nodeName types.NodeName) (string, string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_backoff.go","code":"func (az *Cloud) getIPForMachine(nodeName types.NodeName) (string, string, error) {\n\treturn az.GetIPForMachineWithRetry(nodeName)\n}","line":{"from":139,"to":141}} {"id":100033095,"name":"GetIPForMachineWithRetry","signature":"func (az *Cloud) GetIPForMachineWithRetry(name types.NodeName) (string, string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_backoff.go","code":"// GetIPForMachineWithRetry invokes az.getIPForMachine with exponential backoff retry\nfunc (az *Cloud) GetIPForMachineWithRetry(name types.NodeName) (string, string, error) {\n\tvar ip, publicIP string\n\terr := wait.ExponentialBackoff(az.RequestBackoff(), func() (bool, error) {\n\t\tvar retryErr error\n\t\tip, publicIP, retryErr = az.VMSet.GetIPByNodeName(string(name))\n\t\tif retryErr != nil {\n\t\t\tklog.Errorf(\"GetIPForMachineWithRetry(%s): backoff failure, will retry,err=%v\", name, retryErr)\n\t\t\treturn false, nil\n\t\t}\n\t\tklog.V(3).Infof(\"GetIPForMachineWithRetry(%s): backoff success\", name)\n\t\treturn true, nil\n\t})\n\treturn ip, publicIP, err\n}","line":{"from":143,"to":157}} {"id":100033096,"name":"CreateOrUpdateSecurityGroup","signature":"func (az *Cloud) CreateOrUpdateSecurityGroup(sg network.SecurityGroup) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_backoff.go","code":"// CreateOrUpdateSecurityGroup invokes az.SecurityGroupsClient.CreateOrUpdate with exponential backoff retry\nfunc (az *Cloud) CreateOrUpdateSecurityGroup(sg network.SecurityGroup) error {\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\n\trerr := az.SecurityGroupsClient.CreateOrUpdate(ctx, az.SecurityGroupResourceGroup, *sg.Name, sg, pointer.StringDeref(sg.Etag, \"\"))\n\tklog.V(10).Infof(\"SecurityGroupsClient.CreateOrUpdate(%s): end\", *sg.Name)\n\tif rerr == nil {\n\t\t// Invalidate the cache right after updating\n\t\taz.nsgCache.Delete(*sg.Name)\n\t\treturn nil\n\t}\n\n\t// Invalidate the cache because ETAG precondition mismatch.\n\tif rerr.HTTPStatusCode == http.StatusPreconditionFailed {\n\t\tklog.V(3).Infof(\"SecurityGroup cache for %s is cleanup because of http.StatusPreconditionFailed\", *sg.Name)\n\t\taz.nsgCache.Delete(*sg.Name)\n\t}\n\n\t// Invalidate the cache because another new operation has canceled the current request.\n\tif strings.Contains(strings.ToLower(rerr.Error().Error()), operationCanceledErrorMessage) {\n\t\tklog.V(3).Infof(\"SecurityGroup cache for %s is cleanup because CreateOrUpdateSecurityGroup is canceled by another operation\", *sg.Name)\n\t\taz.nsgCache.Delete(*sg.Name)\n\t}\n\n\treturn rerr.Error()\n}","line":{"from":159,"to":185}} {"id":100033097,"name":"cleanupSubnetInFrontendIPConfigurations","signature":"func cleanupSubnetInFrontendIPConfigurations(lb *network.LoadBalancer) network.LoadBalancer","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_backoff.go","code":"func cleanupSubnetInFrontendIPConfigurations(lb *network.LoadBalancer) network.LoadBalancer {\n\tif lb.LoadBalancerPropertiesFormat == nil || lb.FrontendIPConfigurations == nil {\n\t\treturn *lb\n\t}\n\n\tfrontendIPConfigurations := *lb.FrontendIPConfigurations\n\tfor i := range frontendIPConfigurations {\n\t\tconfig := frontendIPConfigurations[i]\n\t\tif config.FrontendIPConfigurationPropertiesFormat != nil \u0026\u0026\n\t\t\tconfig.Subnet != nil \u0026\u0026\n\t\t\tconfig.Subnet.ID != nil {\n\t\t\tsubnet := network.Subnet{\n\t\t\t\tID: config.Subnet.ID,\n\t\t\t}\n\t\t\tif config.Subnet.Name != nil {\n\t\t\t\tsubnet.Name = config.FrontendIPConfigurationPropertiesFormat.Subnet.Name\n\t\t\t}\n\t\t\tconfig.FrontendIPConfigurationPropertiesFormat.Subnet = \u0026subnet\n\t\t\tfrontendIPConfigurations[i] = config\n\t\t\tcontinue\n\t\t}\n\t}\n\n\tlb.FrontendIPConfigurations = \u0026frontendIPConfigurations\n\treturn *lb\n}","line":{"from":187,"to":212}} {"id":100033098,"name":"CreateOrUpdateLB","signature":"func (az *Cloud) CreateOrUpdateLB(service *v1.Service, lb network.LoadBalancer) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_backoff.go","code":"// CreateOrUpdateLB invokes az.LoadBalancerClient.CreateOrUpdate with exponential backoff retry\nfunc (az *Cloud) CreateOrUpdateLB(service *v1.Service, lb network.LoadBalancer) error {\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\n\tlb = cleanupSubnetInFrontendIPConfigurations(\u0026lb)\n\n\trgName := az.getLoadBalancerResourceGroup()\n\trerr := az.LoadBalancerClient.CreateOrUpdate(ctx, rgName, pointer.StringDeref(lb.Name, \"\"), lb, pointer.StringDeref(lb.Etag, \"\"))\n\tklog.V(10).Infof(\"LoadBalancerClient.CreateOrUpdate(%s): end\", *lb.Name)\n\tif rerr == nil {\n\t\t// Invalidate the cache right after updating\n\t\taz.lbCache.Delete(*lb.Name)\n\t\treturn nil\n\t}\n\n\t// Invalidate the cache because ETAG precondition mismatch.\n\tif rerr.HTTPStatusCode == http.StatusPreconditionFailed {\n\t\tklog.V(3).Infof(\"LoadBalancer cache for %s is cleanup because of http.StatusPreconditionFailed\", pointer.StringDeref(lb.Name, \"\"))\n\t\taz.lbCache.Delete(*lb.Name)\n\t}\n\n\tretryErrorMessage := rerr.Error().Error()\n\t// Invalidate the cache because another new operation has canceled the current request.\n\tif strings.Contains(strings.ToLower(retryErrorMessage), operationCanceledErrorMessage) {\n\t\tklog.V(3).Infof(\"LoadBalancer cache for %s is cleanup because CreateOrUpdate is canceled by another operation\", pointer.StringDeref(lb.Name, \"\"))\n\t\taz.lbCache.Delete(*lb.Name)\n\t}\n\n\t// The LB update may fail because the referenced PIP is not in the Succeeded provisioning state\n\tif strings.Contains(strings.ToLower(retryErrorMessage), strings.ToLower(referencedResourceNotProvisionedMessageCode)) {\n\t\tmatches := pipErrorMessageRE.FindStringSubmatch(retryErrorMessage)\n\t\tif len(matches) != 3 {\n\t\t\tklog.Warningf(\"Failed to parse the retry error message %s\", retryErrorMessage)\n\t\t\treturn rerr.Error()\n\t\t}\n\t\tpipRG, pipName := matches[1], matches[2]\n\t\tklog.V(3).Infof(\"The public IP %s referenced by load balancer %s is not in Succeeded provisioning state, will try to update it\", pipName, pointer.StringDeref(lb.Name, \"\"))\n\t\tpip, _, err := az.getPublicIPAddress(pipRG, pipName)\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"Failed to get the public IP %s in resource group %s: %v\", pipName, pipRG, err)\n\t\t\treturn rerr.Error()\n\t\t}\n\t\t// Perform a dummy update to fix the provisioning state\n\t\terr = az.CreateOrUpdatePIP(service, pipRG, pip)\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"Failed to update the public IP %s in resource group %s: %v\", pipName, pipRG, err)\n\t\t\treturn rerr.Error()\n\t\t}\n\t\t// Invalidate the LB cache, return the error, and the controller manager\n\t\t// would retry the LB update in the next reconcile loop\n\t\taz.lbCache.Delete(*lb.Name)\n\t}\n\n\treturn rerr.Error()\n}","line":{"from":214,"to":269}} {"id":100033099,"name":"ListLB","signature":"func (az *Cloud) ListLB(service *v1.Service) ([]network.LoadBalancer, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_backoff.go","code":"// ListLB invokes az.LoadBalancerClient.List with exponential backoff retry\nfunc (az *Cloud) ListLB(service *v1.Service) ([]network.LoadBalancer, error) {\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\n\trgName := az.getLoadBalancerResourceGroup()\n\tallLBs, rerr := az.LoadBalancerClient.List(ctx, rgName)\n\tif rerr != nil {\n\t\tif rerr.IsNotFound() {\n\t\t\treturn nil, nil\n\t\t}\n\t\taz.Event(service, v1.EventTypeWarning, \"ListLoadBalancers\", rerr.Error().Error())\n\t\tklog.Errorf(\"LoadBalancerClient.List(%v) failure with err=%v\", rgName, rerr)\n\t\treturn nil, rerr.Error()\n\t}\n\tklog.V(2).Infof(\"LoadBalancerClient.List(%v) success\", rgName)\n\treturn allLBs, nil\n}","line":{"from":271,"to":288}} {"id":100033100,"name":"ListPIP","signature":"func (az *Cloud) ListPIP(service *v1.Service, pipResourceGroup string) ([]network.PublicIPAddress, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_backoff.go","code":"// ListPIP list the PIP resources in the given resource group\nfunc (az *Cloud) ListPIP(service *v1.Service, pipResourceGroup string) ([]network.PublicIPAddress, error) {\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\n\tallPIPs, rerr := az.PublicIPAddressesClient.List(ctx, pipResourceGroup)\n\tif rerr != nil {\n\t\tif rerr.IsNotFound() {\n\t\t\treturn nil, nil\n\t\t}\n\t\taz.Event(service, v1.EventTypeWarning, \"ListPublicIPs\", rerr.Error().Error())\n\t\tklog.Errorf(\"PublicIPAddressesClient.List(%v) failure with err=%v\", pipResourceGroup, rerr)\n\t\treturn nil, rerr.Error()\n\t}\n\n\tklog.V(2).Infof(\"PublicIPAddressesClient.List(%v) success\", pipResourceGroup)\n\treturn allPIPs, nil\n}","line":{"from":290,"to":307}} {"id":100033101,"name":"CreateOrUpdatePIP","signature":"func (az *Cloud) CreateOrUpdatePIP(service *v1.Service, pipResourceGroup string, pip network.PublicIPAddress) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_backoff.go","code":"// CreateOrUpdatePIP invokes az.PublicIPAddressesClient.CreateOrUpdate with exponential backoff retry\nfunc (az *Cloud) CreateOrUpdatePIP(service *v1.Service, pipResourceGroup string, pip network.PublicIPAddress) error {\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\n\trerr := az.PublicIPAddressesClient.CreateOrUpdate(ctx, pipResourceGroup, pointer.StringDeref(pip.Name, \"\"), pip)\n\tklog.V(10).Infof(\"PublicIPAddressesClient.CreateOrUpdate(%s, %s): end\", pipResourceGroup, pointer.StringDeref(pip.Name, \"\"))\n\tif rerr != nil {\n\t\tklog.Errorf(\"PublicIPAddressesClient.CreateOrUpdate(%s, %s) failed: %s\", pipResourceGroup, pointer.StringDeref(pip.Name, \"\"), rerr.Error().Error())\n\t\taz.Event(service, v1.EventTypeWarning, \"CreateOrUpdatePublicIPAddress\", rerr.Error().Error())\n\t\treturn rerr.Error()\n\t}\n\n\treturn nil\n}","line":{"from":309,"to":323}} {"id":100033102,"name":"CreateOrUpdateInterface","signature":"func (az *Cloud) CreateOrUpdateInterface(service *v1.Service, nic network.Interface) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_backoff.go","code":"// CreateOrUpdateInterface invokes az.PublicIPAddressesClient.CreateOrUpdate with exponential backoff retry\nfunc (az *Cloud) CreateOrUpdateInterface(service *v1.Service, nic network.Interface) error {\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\n\trerr := az.InterfacesClient.CreateOrUpdate(ctx, az.ResourceGroup, *nic.Name, nic)\n\tklog.V(10).Infof(\"InterfacesClient.CreateOrUpdate(%s): end\", *nic.Name)\n\tif rerr != nil {\n\t\tklog.Errorf(\"InterfacesClient.CreateOrUpdate(%s) failed: %s\", *nic.Name, rerr.Error().Error())\n\t\taz.Event(service, v1.EventTypeWarning, \"CreateOrUpdateInterface\", rerr.Error().Error())\n\t\treturn rerr.Error()\n\t}\n\n\treturn nil\n}","line":{"from":325,"to":339}} {"id":100033103,"name":"DeletePublicIP","signature":"func (az *Cloud) DeletePublicIP(service *v1.Service, pipResourceGroup string, pipName string) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_backoff.go","code":"// DeletePublicIP invokes az.PublicIPAddressesClient.Delete with exponential backoff retry\nfunc (az *Cloud) DeletePublicIP(service *v1.Service, pipResourceGroup string, pipName string) error {\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\n\trerr := az.PublicIPAddressesClient.Delete(ctx, pipResourceGroup, pipName)\n\tif rerr != nil {\n\t\tklog.Errorf(\"PublicIPAddressesClient.Delete(%s) failed: %s\", pipName, rerr.Error().Error())\n\t\taz.Event(service, v1.EventTypeWarning, \"DeletePublicIPAddress\", rerr.Error().Error())\n\n\t\tif strings.Contains(rerr.Error().Error(), cannotDeletePublicIPErrorMessageCode) {\n\t\t\tklog.Warningf(\"DeletePublicIP for public IP %s failed with error %v, this is because other resources are referencing the public IP. The deletion of the service will continue.\", pipName, rerr.Error())\n\t\t\treturn nil\n\t\t}\n\t\treturn rerr.Error()\n\t}\n\n\treturn nil\n}","line":{"from":341,"to":359}} {"id":100033104,"name":"DeleteLB","signature":"func (az *Cloud) DeleteLB(service *v1.Service, lbName string) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_backoff.go","code":"// DeleteLB invokes az.LoadBalancerClient.Delete with exponential backoff retry\nfunc (az *Cloud) DeleteLB(service *v1.Service, lbName string) error {\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\n\trgName := az.getLoadBalancerResourceGroup()\n\trerr := az.LoadBalancerClient.Delete(ctx, rgName, lbName)\n\tif rerr == nil {\n\t\t// Invalidate the cache right after updating\n\t\taz.lbCache.Delete(lbName)\n\t\treturn nil\n\t}\n\n\tklog.Errorf(\"LoadBalancerClient.Delete(%s) failed: %s\", lbName, rerr.Error().Error())\n\taz.Event(service, v1.EventTypeWarning, \"DeleteLoadBalancer\", rerr.Error().Error())\n\treturn rerr.Error()\n}","line":{"from":361,"to":377}} {"id":100033105,"name":"CreateOrUpdateRouteTable","signature":"func (az *Cloud) CreateOrUpdateRouteTable(routeTable network.RouteTable) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_backoff.go","code":"// CreateOrUpdateRouteTable invokes az.RouteTablesClient.CreateOrUpdate with exponential backoff retry\nfunc (az *Cloud) CreateOrUpdateRouteTable(routeTable network.RouteTable) error {\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\n\trerr := az.RouteTablesClient.CreateOrUpdate(ctx, az.RouteTableResourceGroup, az.RouteTableName, routeTable, pointer.StringDeref(routeTable.Etag, \"\"))\n\tif rerr == nil {\n\t\t// Invalidate the cache right after updating\n\t\taz.rtCache.Delete(*routeTable.Name)\n\t\treturn nil\n\t}\n\n\t// Invalidate the cache because etag mismatch.\n\tif rerr.HTTPStatusCode == http.StatusPreconditionFailed {\n\t\tklog.V(3).Infof(\"Route table cache for %s is cleanup because of http.StatusPreconditionFailed\", *routeTable.Name)\n\t\taz.rtCache.Delete(*routeTable.Name)\n\t}\n\t// Invalidate the cache because another new operation has canceled the current request.\n\tif strings.Contains(strings.ToLower(rerr.Error().Error()), operationCanceledErrorMessage) {\n\t\tklog.V(3).Infof(\"Route table cache for %s is cleanup because CreateOrUpdateRouteTable is canceled by another operation\", *routeTable.Name)\n\t\taz.rtCache.Delete(*routeTable.Name)\n\t}\n\tklog.Errorf(\"RouteTablesClient.CreateOrUpdate(%s) failed: %v\", az.RouteTableName, rerr.Error())\n\treturn rerr.Error()\n}","line":{"from":379,"to":403}} {"id":100033106,"name":"CreateOrUpdateRoute","signature":"func (az *Cloud) CreateOrUpdateRoute(route network.Route) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_backoff.go","code":"// CreateOrUpdateRoute invokes az.RoutesClient.CreateOrUpdate with exponential backoff retry\nfunc (az *Cloud) CreateOrUpdateRoute(route network.Route) error {\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\n\trerr := az.RoutesClient.CreateOrUpdate(ctx, az.RouteTableResourceGroup, az.RouteTableName, *route.Name, route, pointer.StringDeref(route.Etag, \"\"))\n\tklog.V(10).Infof(\"RoutesClient.CreateOrUpdate(%s): end\", *route.Name)\n\tif rerr == nil {\n\t\taz.rtCache.Delete(az.RouteTableName)\n\t\treturn nil\n\t}\n\n\tif rerr.HTTPStatusCode == http.StatusPreconditionFailed {\n\t\tklog.V(3).Infof(\"Route cache for %s is cleanup because of http.StatusPreconditionFailed\", *route.Name)\n\t\taz.rtCache.Delete(az.RouteTableName)\n\t}\n\t// Invalidate the cache because another new operation has canceled the current request.\n\tif strings.Contains(strings.ToLower(rerr.Error().Error()), operationCanceledErrorMessage) {\n\t\tklog.V(3).Infof(\"Route cache for %s is cleanup because CreateOrUpdateRouteTable is canceled by another operation\", *route.Name)\n\t\taz.rtCache.Delete(az.RouteTableName)\n\t}\n\treturn rerr.Error()\n}","line":{"from":405,"to":427}} {"id":100033107,"name":"DeleteRouteWithName","signature":"func (az *Cloud) DeleteRouteWithName(routeName string) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_backoff.go","code":"// DeleteRouteWithName invokes az.RoutesClient.CreateOrUpdate with exponential backoff retry\nfunc (az *Cloud) DeleteRouteWithName(routeName string) error {\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\n\trerr := az.RoutesClient.Delete(ctx, az.RouteTableResourceGroup, az.RouteTableName, routeName)\n\tklog.V(10).Infof(\"RoutesClient.Delete(%s,%s): end\", az.RouteTableName, routeName)\n\tif rerr == nil {\n\t\treturn nil\n\t}\n\n\tklog.Errorf(\"RoutesClient.Delete(%s, %s) failed: %v\", az.RouteTableName, routeName, rerr.Error())\n\treturn rerr.Error()\n}","line":{"from":429,"to":442}} {"id":100033108,"name":"CreateOrUpdateVMSS","signature":"func (az *Cloud) CreateOrUpdateVMSS(resourceGroupName string, VMScaleSetName string, parameters compute.VirtualMachineScaleSet) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_backoff.go","code":"// CreateOrUpdateVMSS invokes az.VirtualMachineScaleSetsClient.Update().\nfunc (az *Cloud) CreateOrUpdateVMSS(resourceGroupName string, VMScaleSetName string, parameters compute.VirtualMachineScaleSet) *retry.Error {\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\n\t// When vmss is being deleted, CreateOrUpdate API would report \"the vmss is being deleted\" error.\n\t// Since it is being deleted, we shouldn't send more CreateOrUpdate requests for it.\n\tklog.V(3).Infof(\"CreateOrUpdateVMSS: verify the status of the vmss being created or updated\")\n\tvmss, rerr := az.VirtualMachineScaleSetsClient.Get(ctx, resourceGroupName, VMScaleSetName)\n\tif rerr != nil {\n\t\tklog.Errorf(\"CreateOrUpdateVMSS: error getting vmss(%s): %v\", VMScaleSetName, rerr)\n\t\treturn rerr\n\t}\n\tif vmss.ProvisioningState != nil \u0026\u0026 strings.EqualFold(*vmss.ProvisioningState, virtualMachineScaleSetsDeallocating) {\n\t\tklog.V(3).Infof(\"CreateOrUpdateVMSS: found vmss %s being deleted, skipping\", VMScaleSetName)\n\t\treturn nil\n\t}\n\n\trerr = az.VirtualMachineScaleSetsClient.CreateOrUpdate(ctx, resourceGroupName, VMScaleSetName, parameters)\n\tklog.V(10).Infof(\"UpdateVmssVMWithRetry: VirtualMachineScaleSetsClient.CreateOrUpdate(%s): end\", VMScaleSetName)\n\tif rerr != nil {\n\t\tklog.Errorf(\"CreateOrUpdateVMSS: error CreateOrUpdate vmss(%s): %v\", VMScaleSetName, rerr)\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":444,"to":470}} {"id":100033109,"name":"initStorageAccounts","signature":"func (c *BlobDiskController) initStorageAccounts()","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_blobDiskController.go","code":"func (c *BlobDiskController) initStorageAccounts() {\n\taccountsLock.Lock()\n\tdefer accountsLock.Unlock()\n\n\tif c.accounts == nil {\n\t\t// get accounts\n\t\taccounts, err := c.getAllStorageAccounts()\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"azureDisk - getAllStorageAccounts error: %v\", err)\n\t\t\tc.accounts = make(map[string]*storageAccountState)\n\t\t}\n\t\tc.accounts = accounts\n\t}\n}","line":{"from":70,"to":83}} {"id":100033110,"name":"CreateVolume","signature":"func (c *BlobDiskController) CreateVolume(blobName, accountName, accountType, location string, requestGB int) (string, string, int, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_blobDiskController.go","code":"// CreateVolume creates a VHD blob in a storage account that has storageType and location using the given storage account.\n// If no storage account is given, search all the storage accounts associated with the resource group and pick one that\n// fits storage type and location.\nfunc (c *BlobDiskController) CreateVolume(blobName, accountName, accountType, location string, requestGB int) (string, string, int, error) {\n\taccountOptions := \u0026AccountOptions{\n\t\tName: accountName,\n\t\tType: accountType,\n\t\tKind: string(defaultStorageAccountKind),\n\t\tResourceGroup: c.common.resourceGroup,\n\t\tLocation: location,\n\t\tEnableHTTPSTrafficOnly: true,\n\t}\n\taccount, key, err := c.common.cloud.EnsureStorageAccount(accountOptions, dedicatedDiskAccountNamePrefix)\n\tif err != nil {\n\t\treturn \"\", \"\", 0, fmt.Errorf(\"could not get storage key for storage account %s: %v\", accountName, err)\n\t}\n\n\tclient, err := azstorage.NewBasicClientOnSovereignCloud(account, key, c.common.cloud.Environment)\n\tif err != nil {\n\t\treturn \"\", \"\", 0, err\n\t}\n\tblobClient := client.GetBlobService()\n\n\t// create a page blob in this account's vhd container\n\tdiskName, diskURI, err := c.createVHDBlobDisk(blobClient, account, blobName, vhdContainerName, int64(requestGB))\n\tif err != nil {\n\t\treturn \"\", \"\", 0, err\n\t}\n\n\tklog.V(4).Infof(\"azureDisk - created vhd blob uri: %s\", diskURI)\n\treturn diskName, diskURI, requestGB, err\n}","line":{"from":85,"to":116}} {"id":100033111,"name":"DeleteVolume","signature":"func (c *BlobDiskController) DeleteVolume(diskURI string) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_blobDiskController.go","code":"// DeleteVolume deletes a VHD blob\nfunc (c *BlobDiskController) DeleteVolume(diskURI string) error {\n\tklog.V(4).Infof(\"azureDisk - begin to delete volume %s\", diskURI)\n\taccountName, blob, err := c.common.cloud.getBlobNameAndAccountFromURI(diskURI)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse vhd URI %v\", err)\n\t}\n\tkey, err := c.common.cloud.GetStorageAccesskey(accountName, c.common.resourceGroup)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"no key for storage account %s, err %v\", accountName, err)\n\t}\n\terr = c.common.cloud.deleteVhdBlob(accountName, key, blob)\n\tif err != nil {\n\t\tklog.Warningf(\"azureDisk - failed to delete blob %s err: %v\", diskURI, err)\n\t\tdetail := err.Error()\n\t\tif strings.Contains(detail, errLeaseIDMissing) {\n\t\t\t// disk is still being used\n\t\t\t// see https://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storage.blob.protocol.bloberrorcodestrings.leaseidmissing.aspx\n\t\t\treturn volerr.NewDeletedVolumeInUseError(fmt.Sprintf(\"disk %q is still in use while being deleted\", diskURI))\n\t\t}\n\t\treturn fmt.Errorf(\"failed to delete vhd %v, account %s, blob %s, err: %v\", diskURI, accountName, blob, err)\n\t}\n\tklog.V(4).Infof(\"azureDisk - blob %s deleted\", diskURI)\n\treturn nil\n\n}","line":{"from":118,"to":143}} {"id":100033112,"name":"getBlobNameAndAccountFromURI","signature":"func (c *BlobDiskController) getBlobNameAndAccountFromURI(diskURI string) (string, string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_blobDiskController.go","code":"// get diskURI https://foo.blob.core.windows.net/vhds/bar.vhd and return foo (account) and bar.vhd (blob name)\nfunc (c *BlobDiskController) getBlobNameAndAccountFromURI(diskURI string) (string, string, error) {\n\tscheme := \"http\"\n\tif useHTTPSForBlobBasedDisk {\n\t\tscheme = \"https\"\n\t}\n\thost := fmt.Sprintf(\"%s://(.*).%s.%s\", scheme, blobServiceName, c.common.storageEndpointSuffix)\n\treStr := fmt.Sprintf(\"%s/%s/(.*)\", host, vhdContainerName)\n\tre := regexp.MustCompile(reStr)\n\tres := re.FindSubmatch([]byte(diskURI))\n\tif len(res) \u003c 3 {\n\t\treturn \"\", \"\", fmt.Errorf(\"invalid vhd URI for regex %s: %s\", reStr, diskURI)\n\t}\n\treturn string(res[1]), string(res[2]), nil\n}","line":{"from":145,"to":159}} {"id":100033113,"name":"createVHDBlobDisk","signature":"func (c *BlobDiskController) createVHDBlobDisk(blobClient azstorage.BlobStorageClient, accountName, vhdName, containerName string, sizeGB int64) (string, string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_blobDiskController.go","code":"func (c *BlobDiskController) createVHDBlobDisk(blobClient azstorage.BlobStorageClient, accountName, vhdName, containerName string, sizeGB int64) (string, string, error) {\n\tcontainer := blobClient.GetContainerReference(containerName)\n\tsize := 1024 * 1024 * 1024 * sizeGB\n\tvhdSize := size + vhd.VHD_HEADER_SIZE /* header size */\n\t// Blob name in URL must end with '.vhd' extension.\n\tvhdName = vhdName + \".vhd\"\n\n\ttags := make(map[string]string)\n\ttags[\"createdby\"] = \"k8sAzureDataDisk\"\n\tklog.V(4).Infof(\"azureDisk - creating page blob %s in container %s account %s\", vhdName, containerName, accountName)\n\n\tblob := container.GetBlobReference(vhdName)\n\tblob.Properties.ContentLength = vhdSize\n\tblob.Metadata = tags\n\terr := blob.PutPageBlob(nil)\n\tif err != nil {\n\t\t// if container doesn't exist, create one and retry PutPageBlob\n\t\tdetail := err.Error()\n\t\tif strings.Contains(detail, errContainerNotFound) {\n\t\t\terr = container.Create(\u0026azstorage.CreateContainerOptions{Access: azstorage.ContainerAccessTypePrivate})\n\t\t\tif err == nil {\n\t\t\t\terr = blob.PutPageBlob(nil)\n\t\t\t}\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"failed to put page blob %s in container %s: %v\", vhdName, containerName, err)\n\t}\n\n\t// add VHD signature to the blob\n\th, err := createVHDHeader(uint64(size))\n\tif err != nil {\n\t\tblob.DeleteIfExists(nil)\n\t\treturn \"\", \"\", fmt.Errorf(\"failed to create vhd header, err: %v\", err)\n\t}\n\n\tblobRange := azstorage.BlobRange{\n\t\tStart: uint64(size),\n\t\tEnd: uint64(vhdSize - 1),\n\t}\n\tif err = blob.WriteRange(blobRange, bytes.NewBuffer(h[:vhd.VHD_HEADER_SIZE]), nil); err != nil {\n\t\tklog.Infof(\"azureDisk - failed to put header page for data disk %s in container %s account %s, error was %s\\n\",\n\t\t\tvhdName, containerName, accountName, err.Error())\n\t\treturn \"\", \"\", err\n\t}\n\n\tscheme := \"http\"\n\tif useHTTPSForBlobBasedDisk {\n\t\tscheme = \"https\"\n\t}\n\n\thost := fmt.Sprintf(\"%s://%s.%s.%s\", scheme, accountName, blobServiceName, c.common.storageEndpointSuffix)\n\turi := fmt.Sprintf(\"%s/%s/%s\", host, containerName, vhdName)\n\treturn vhdName, uri, nil\n}","line":{"from":161,"to":215}} {"id":100033114,"name":"deleteVhdBlob","signature":"func (c *BlobDiskController) deleteVhdBlob(accountName, accountKey, blobName string) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_blobDiskController.go","code":"// delete a vhd blob\nfunc (c *BlobDiskController) deleteVhdBlob(accountName, accountKey, blobName string) error {\n\tclient, err := azstorage.NewBasicClientOnSovereignCloud(accountName, accountKey, c.common.cloud.Environment)\n\tif err != nil {\n\t\treturn err\n\t}\n\tblobSvc := client.GetBlobService()\n\n\tcontainer := blobSvc.GetContainerReference(vhdContainerName)\n\tblob := container.GetBlobReference(blobName)\n\treturn blob.Delete(nil)\n}","line":{"from":217,"to":228}} {"id":100033115,"name":"CreateBlobDisk","signature":"func (c *BlobDiskController) CreateBlobDisk(dataDiskName string, storageAccountType storage.SkuName, sizeGB int) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_blobDiskController.go","code":"// CreateBlobDisk : create a blob disk in a node\nfunc (c *BlobDiskController) CreateBlobDisk(dataDiskName string, storageAccountType storage.SkuName, sizeGB int) (string, error) {\n\tklog.V(4).Infof(\"azureDisk - creating blob data disk named:%s on StorageAccountType:%s\", dataDiskName, storageAccountType)\n\n\tc.initStorageAccounts()\n\n\tstorageAccountName, err := c.findSANameForDisk(storageAccountType)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tblobClient, err := c.getBlobSvcClient(storageAccountName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t_, diskURI, err := c.createVHDBlobDisk(blobClient, storageAccountName, dataDiskName, vhdContainerName, int64(sizeGB))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tatomic.AddInt32(\u0026c.accounts[storageAccountName].diskCount, 1)\n\n\treturn diskURI, nil\n}","line":{"from":230,"to":254}} {"id":100033116,"name":"DeleteBlobDisk","signature":"func (c *BlobDiskController) DeleteBlobDisk(diskURI string) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_blobDiskController.go","code":"// DeleteBlobDisk : delete a blob disk from a node\nfunc (c *BlobDiskController) DeleteBlobDisk(diskURI string) error {\n\tstorageAccountName, vhdName, err := diskNameAndSANameFromURI(diskURI)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, ok := c.accounts[storageAccountName]\n\tif !ok {\n\t\t// the storage account is specified by user\n\t\tklog.V(4).Infof(\"azureDisk - deleting volume %s\", diskURI)\n\t\treturn c.DeleteVolume(diskURI)\n\t}\n\n\tblobSvc, err := c.getBlobSvcClient(storageAccountName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tklog.V(4).Infof(\"azureDisk - About to delete vhd file %s on storage account %s container %s\", vhdName, storageAccountName, vhdContainerName)\n\n\tcontainer := blobSvc.GetContainerReference(vhdContainerName)\n\tblob := container.GetBlobReference(vhdName)\n\t_, err = blob.DeleteIfExists(nil)\n\n\tif c.accounts[storageAccountName].diskCount == -1 {\n\t\tif diskCount, err := c.getDiskCount(storageAccountName); err != nil {\n\t\t\tc.accounts[storageAccountName].diskCount = int32(diskCount)\n\t\t} else {\n\t\t\tklog.Warningf(\"azureDisk - failed to get disk count for %s however the delete disk operation was ok\", storageAccountName)\n\t\t\treturn nil // we have failed to acquire a new count. not an error condition\n\t\t}\n\t}\n\tatomic.AddInt32(\u0026c.accounts[storageAccountName].diskCount, -1)\n\treturn err\n}","line":{"from":256,"to":291}} {"id":100033117,"name":"getStorageAccountKey","signature":"func (c *BlobDiskController) getStorageAccountKey(SAName string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_blobDiskController.go","code":"func (c *BlobDiskController) getStorageAccountKey(SAName string) (string, error) {\n\tif account, exists := c.accounts[SAName]; exists \u0026\u0026 account.key != \"\" {\n\t\treturn c.accounts[SAName].key, nil\n\t}\n\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\tlistKeysResult, rerr := c.common.cloud.StorageAccountClient.ListKeys(ctx, c.common.resourceGroup, SAName)\n\tif rerr != nil {\n\t\treturn \"\", rerr.Error()\n\t}\n\tif listKeysResult.Keys == nil {\n\t\treturn \"\", fmt.Errorf(\"azureDisk - empty listKeysResult in storage account:%s keys\", SAName)\n\t}\n\tfor _, v := range *listKeysResult.Keys {\n\t\tif v.Value != nil \u0026\u0026 *v.Value == \"key1\" {\n\t\t\tif _, ok := c.accounts[SAName]; !ok {\n\t\t\t\tklog.Warningf(\"azureDisk - account %s was not cached while getting keys\", SAName)\n\t\t\t\treturn *v.Value, nil\n\t\t\t}\n\t\t\tc.accounts[SAName].key = *v.Value\n\t\t\treturn c.accounts[SAName].key, nil\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"couldn't find key named key1 in storage account:%s keys\", SAName)\n}","line":{"from":293,"to":319}} {"id":100033118,"name":"getBlobSvcClient","signature":"func (c *BlobDiskController) getBlobSvcClient(SAName string) (azstorage.BlobStorageClient, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_blobDiskController.go","code":"func (c *BlobDiskController) getBlobSvcClient(SAName string) (azstorage.BlobStorageClient, error) {\n\tkey := \"\"\n\tvar client azstorage.Client\n\tvar blobSvc azstorage.BlobStorageClient\n\tvar err error\n\tif key, err = c.getStorageAccountKey(SAName); err != nil {\n\t\treturn blobSvc, err\n\t}\n\n\tif client, err = azstorage.NewBasicClientOnSovereignCloud(SAName, key, c.common.cloud.Environment); err != nil {\n\t\treturn blobSvc, err\n\t}\n\n\tblobSvc = client.GetBlobService()\n\treturn blobSvc, nil\n}","line":{"from":321,"to":336}} {"id":100033119,"name":"ensureDefaultContainer","signature":"func (c *BlobDiskController) ensureDefaultContainer(storageAccountName string) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_blobDiskController.go","code":"func (c *BlobDiskController) ensureDefaultContainer(storageAccountName string) error {\n\tvar err error\n\tvar blobSvc azstorage.BlobStorageClient\n\n\t// short circuit the check via local cache\n\t// we are forgiving the fact that account may not be in cache yet\n\tif v, ok := c.accounts[storageAccountName]; ok \u0026\u0026 v.defaultContainerCreated {\n\t\treturn nil\n\t}\n\n\t// not cached, check existence and readiness\n\tbExist, provisionState, _ := c.getStorageAccountState(storageAccountName)\n\n\t// account does not exist\n\tif !bExist {\n\t\treturn fmt.Errorf(\"azureDisk - account %s does not exist while trying to create/ensure default container\", storageAccountName)\n\t}\n\n\t// account exists but not ready yet\n\tif provisionState != storage.Succeeded {\n\t\t// we don't want many attempts to validate the account readiness\n\t\t// here hence we are locking\n\t\tcounter := 1\n\t\tfor swapped := atomic.CompareAndSwapInt32(\u0026c.accounts[storageAccountName].isValidating, 0, 1); swapped != true; {\n\t\t\ttime.Sleep(3 * time.Second)\n\t\t\tcounter = counter + 1\n\t\t\t// check if we passed the max sleep\n\t\t\tif counter \u003e= 20 {\n\t\t\t\treturn fmt.Errorf(\"azureDisk - timeout waiting to acquire lock to validate account:%s readiness\", storageAccountName)\n\t\t\t}\n\t\t}\n\n\t\t// swapped\n\t\tdefer func() {\n\t\t\tc.accounts[storageAccountName].isValidating = 0\n\t\t}()\n\n\t\t// short circuit the check again.\n\t\tif v, ok := c.accounts[storageAccountName]; ok \u0026\u0026 v.defaultContainerCreated {\n\t\t\treturn nil\n\t\t}\n\n\t\terr = kwait.ExponentialBackoff(defaultBackOff, func() (bool, error) {\n\t\t\t_, provisionState, err := c.getStorageAccountState(storageAccountName)\n\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"azureDisk - GetStorageAccount:%s err %s\", storageAccountName, err.Error())\n\t\t\t\treturn false, nil // error performing the query - retryable\n\t\t\t}\n\n\t\t\tif provisionState == storage.Succeeded {\n\t\t\t\treturn true, nil\n\t\t\t}\n\n\t\t\tklog.V(4).Infof(\"azureDisk - GetStorageAccount:%s not ready yet (not flagged Succeeded by ARM)\", storageAccountName)\n\t\t\treturn false, nil // back off and see if the account becomes ready on next retry\n\t\t})\n\t\t// we have failed to ensure that account is ready for us to create\n\t\t// the default vhd container\n\t\tif err != nil {\n\t\t\tif err == kwait.ErrWaitTimeout {\n\t\t\t\treturn fmt.Errorf(\"azureDisk - timed out waiting for storage account %s to become ready\", storageAccountName)\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif blobSvc, err = c.getBlobSvcClient(storageAccountName); err != nil {\n\t\treturn err\n\t}\n\n\tcontainer := blobSvc.GetContainerReference(vhdContainerName)\n\tbCreated, err := container.CreateIfNotExists(\u0026azstorage.CreateContainerOptions{Access: azstorage.ContainerAccessTypePrivate})\n\tif err != nil {\n\t\treturn err\n\t}\n\tif bCreated {\n\t\tklog.V(2).Infof(\"azureDisk - storage account:%s had no default container(%s) and it was created \\n\", storageAccountName, vhdContainerName)\n\t}\n\n\t// flag so we no longer have to check on ARM\n\tc.accounts[storageAccountName].defaultContainerCreated = true\n\treturn nil\n}","line":{"from":338,"to":421}} {"id":100033120,"name":"getDiskCount","signature":"func (c *BlobDiskController) getDiskCount(SAName string) (int, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_blobDiskController.go","code":"// Gets Disk counts per storage account\nfunc (c *BlobDiskController) getDiskCount(SAName string) (int, error) {\n\t// if we have it in cache\n\tif c.accounts[SAName].diskCount != -1 {\n\t\treturn int(c.accounts[SAName].diskCount), nil\n\t}\n\n\tvar err error\n\tvar blobSvc azstorage.BlobStorageClient\n\n\tif err = c.ensureDefaultContainer(SAName); err != nil {\n\t\treturn 0, err\n\t}\n\n\tif blobSvc, err = c.getBlobSvcClient(SAName); err != nil {\n\t\treturn 0, err\n\t}\n\tparams := azstorage.ListBlobsParameters{}\n\n\tcontainer := blobSvc.GetContainerReference(vhdContainerName)\n\tresponse, err := container.ListBlobs(params)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tklog.V(4).Infof(\"azure-Disk - refreshed data count for account %s and found %v\", SAName, len(response.Blobs))\n\tc.accounts[SAName].diskCount = int32(len(response.Blobs))\n\n\treturn int(c.accounts[SAName].diskCount), nil\n}","line":{"from":423,"to":451}} {"id":100033121,"name":"getAllStorageAccounts","signature":"func (c *BlobDiskController) getAllStorageAccounts() (map[string]*storageAccountState, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_blobDiskController.go","code":"func (c *BlobDiskController) getAllStorageAccounts() (map[string]*storageAccountState, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)\n\tdefer cancel()\n\taccountList, rerr := c.common.cloud.StorageAccountClient.ListByResourceGroup(ctx, c.common.resourceGroup)\n\tif rerr != nil {\n\t\treturn nil, rerr.Error()\n\t}\n\n\taccounts := make(map[string]*storageAccountState)\n\tfor _, v := range accountList {\n\t\tif v.Name == nil || v.Sku == nil {\n\t\t\tklog.Info(\"azureDisk - accountListResult Name or Sku is nil\")\n\t\t\tcontinue\n\t\t}\n\t\tif !strings.HasPrefix(*v.Name, sharedDiskAccountNamePrefix) {\n\t\t\tcontinue\n\t\t}\n\t\tklog.Infof(\"azureDisk - identified account %s as part of shared PVC accounts\", *v.Name)\n\n\t\tsaState := \u0026storageAccountState{\n\t\t\tname: *v.Name,\n\t\t\tsaType: (*v.Sku).Name,\n\t\t\tdiskCount: -1,\n\t\t}\n\n\t\taccounts[*v.Name] = saState\n\t}\n\n\treturn accounts, nil\n}","line":{"from":453,"to":482}} {"id":100033122,"name":"createStorageAccount","signature":"func (c *BlobDiskController) createStorageAccount(storageAccountName string, storageAccountType storage.SkuName, location string, checkMaxAccounts bool) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_blobDiskController.go","code":"func (c *BlobDiskController) createStorageAccount(storageAccountName string, storageAccountType storage.SkuName, location string, checkMaxAccounts bool) error {\n\tbExist, _, _ := c.getStorageAccountState(storageAccountName)\n\tif bExist {\n\t\tnewAccountState := \u0026storageAccountState{\n\t\t\tdiskCount: -1,\n\t\t\tsaType: storageAccountType,\n\t\t\tname: storageAccountName,\n\t\t}\n\n\t\tc.addAccountState(storageAccountName, newAccountState)\n\t}\n\t// Account Does not exist\n\tif !bExist {\n\t\tif len(c.accounts) == maxStorageAccounts \u0026\u0026 checkMaxAccounts {\n\t\t\treturn fmt.Errorf(\"azureDisk - can not create new storage account, current storage accounts count:%v Max is:%v\", len(c.accounts), maxStorageAccounts)\n\t\t}\n\n\t\tklog.V(2).Infof(\"azureDisk - Creating storage account %s type %s\", storageAccountName, string(storageAccountType))\n\n\t\tcp := storage.AccountCreateParameters{\n\t\t\tSku: \u0026storage.Sku{Name: storageAccountType},\n\t\t\t// switch to use StorageV2 as it's recommended according to https://docs.microsoft.com/en-us/azure/storage/common/storage-account-options\n\t\t\tKind: defaultStorageAccountKind,\n\t\t\tTags: map[string]*string{\"created-by\": pointer.String(\"azure-dd\")},\n\t\t\tLocation: \u0026location}\n\t\tctx, cancel := getContextWithCancel()\n\t\tdefer cancel()\n\n\t\terr := c.common.cloud.StorageAccountClient.Create(ctx, c.common.resourceGroup, storageAccountName, cp)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Create Storage Account: %s, error: %v\", storageAccountName, err)\n\t\t}\n\n\t\tnewAccountState := \u0026storageAccountState{\n\t\t\tdiskCount: -1,\n\t\t\tsaType: storageAccountType,\n\t\t\tname: storageAccountName,\n\t\t}\n\n\t\tc.addAccountState(storageAccountName, newAccountState)\n\t}\n\n\t// finally, make sure that we default container is created\n\t// before handing it back over\n\treturn c.ensureDefaultContainer(storageAccountName)\n}","line":{"from":484,"to":529}} {"id":100033123,"name":"findSANameForDisk","signature":"func (c *BlobDiskController) findSANameForDisk(storageAccountType storage.SkuName) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_blobDiskController.go","code":"// finds a new suitable storageAccount for this disk\nfunc (c *BlobDiskController) findSANameForDisk(storageAccountType storage.SkuName) (string, error) {\n\tmaxDiskCount := maxDisksPerStorageAccounts\n\tSAName := \"\"\n\ttotalDiskCounts := 0\n\tcountAccounts := 0 // account of this type.\n\tfor _, v := range c.accounts {\n\t\t// filter out any stand-alone disks/accounts\n\t\tif !strings.HasPrefix(v.name, sharedDiskAccountNamePrefix) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// note: we compute avg stratified by type.\n\t\t// this is to enable user to grow per SA type to avoid low\n\t\t// avg utilization on one account type skewing all data.\n\n\t\tif v.saType == storageAccountType {\n\t\t\t// compute average\n\t\t\tdCount, err := c.getDiskCount(v.name)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\ttotalDiskCounts = totalDiskCounts + dCount\n\t\t\tcountAccounts = countAccounts + 1\n\t\t\t// empty account\n\t\t\tif dCount == 0 {\n\t\t\t\tklog.V(2).Infof(\"azureDisk - account %s identified for a new disk is because it has 0 allocated disks\", v.name)\n\t\t\t\treturn v.name, nil // short circuit, avg is good and no need to adjust\n\t\t\t}\n\t\t\t// if this account is less allocated\n\t\t\tif dCount \u003c maxDiskCount {\n\t\t\t\tmaxDiskCount = dCount\n\t\t\t\tSAName = v.name\n\t\t\t}\n\t\t}\n\t}\n\n\t// if we failed to find storageaccount\n\tif SAName == \"\" {\n\t\tklog.V(2).Infof(\"azureDisk - failed to identify a suitable account for new disk and will attempt to create new account\")\n\t\tSAName = generateStorageAccountName(sharedDiskAccountNamePrefix)\n\t\terr := c.createStorageAccount(SAName, storageAccountType, c.common.location, true)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn SAName, nil\n\t}\n\n\tdisksAfter := totalDiskCounts + 1 // with the new one!\n\n\tavgUtilization := float64(disksAfter) / float64(countAccounts*maxDisksPerStorageAccounts)\n\taboveAvg := avgUtilization \u003e storageAccountUtilizationBeforeGrowing\n\n\t// avg are not create and we should create more accounts if we can\n\tif aboveAvg \u0026\u0026 countAccounts \u003c maxStorageAccounts {\n\t\tklog.V(2).Infof(\"azureDisk - shared storageAccounts utilization(%v) \u003e grow-at-avg-utilization (%v). New storage account will be created\", avgUtilization, storageAccountUtilizationBeforeGrowing)\n\t\tSAName = generateStorageAccountName(sharedDiskAccountNamePrefix)\n\t\terr := c.createStorageAccount(SAName, storageAccountType, c.common.location, true)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn SAName, nil\n\t}\n\n\t// averages are not ok and we are at capacity (max storage accounts allowed)\n\tif aboveAvg \u0026\u0026 countAccounts == maxStorageAccounts {\n\t\tklog.Infof(\"azureDisk - shared storageAccounts utilization(%v) \u003e grow-at-avg-utilization (%v). But k8s maxed on SAs for PVC(%v). k8s will now exceed grow-at-avg-utilization without adding accounts\",\n\t\t\tavgUtilization, storageAccountUtilizationBeforeGrowing, maxStorageAccounts)\n\t}\n\n\t// we found a storage accounts \u0026\u0026 [ avg are ok || we reached max sa count ]\n\treturn SAName, nil\n}","line":{"from":531,"to":603}} {"id":100033124,"name":"getStorageAccountState","signature":"func (c *BlobDiskController) getStorageAccountState(storageAccountName string) (bool, storage.ProvisioningState, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_blobDiskController.go","code":"// Gets storage account exist, provisionStatus, Error if any\nfunc (c *BlobDiskController) getStorageAccountState(storageAccountName string) (bool, storage.ProvisioningState, error) {\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\taccount, rerr := c.common.cloud.StorageAccountClient.GetProperties(ctx, c.common.resourceGroup, storageAccountName)\n\tif rerr != nil {\n\t\treturn false, \"\", rerr.Error()\n\t}\n\treturn true, account.AccountProperties.ProvisioningState, nil\n}","line":{"from":605,"to":614}} {"id":100033125,"name":"addAccountState","signature":"func (c *BlobDiskController) addAccountState(key string, state *storageAccountState)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_blobDiskController.go","code":"func (c *BlobDiskController) addAccountState(key string, state *storageAccountState) {\n\taccountsLock.Lock()\n\tdefer accountsLock.Unlock()\n\n\tif _, ok := c.accounts[key]; !ok {\n\t\tc.accounts[key] = state\n\t}\n}","line":{"from":616,"to":623}} {"id":100033126,"name":"createVHDHeader","signature":"func createVHDHeader(size uint64) ([]byte, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_blobDiskController.go","code":"func createVHDHeader(size uint64) ([]byte, error) {\n\th := vhd.CreateFixedHeader(size, \u0026vhd.VHDOptions{})\n\tb := new(bytes.Buffer)\n\terr := binary.Write(b, binary.BigEndian, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn b.Bytes(), nil\n}","line":{"from":625,"to":633}} {"id":100033127,"name":"diskNameAndSANameFromURI","signature":"func diskNameAndSANameFromURI(diskURI string) (string, string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_blobDiskController.go","code":"func diskNameAndSANameFromURI(diskURI string) (string, string, error) {\n\turi, err := url.Parse(diskURI)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\thostName := uri.Host\n\tstorageAccountName := strings.Split(hostName, \".\")[0]\n\n\tsegments := strings.Split(uri.Path, \"/\")\n\tdiskNameVhd := segments[len(segments)-1]\n\n\treturn storageAccountName, diskNameVhd, nil\n}","line":{"from":635,"to":648}} {"id":100033128,"name":"InitializeCloudFromSecret","signature":"func (az *Cloud) InitializeCloudFromSecret()","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_config.go","code":"// InitializeCloudFromSecret initializes Azure cloud provider from Kubernetes secret.\nfunc (az *Cloud) InitializeCloudFromSecret() {\n\tconfig, err := az.getConfigFromSecret()\n\tif err != nil {\n\t\tklog.Warningf(\"Failed to get cloud-config from secret: %v, skip initializing from secret\", err)\n\t\treturn\n\t}\n\n\tif config == nil {\n\t\t// Skip re-initialization if the config is not override.\n\t\treturn\n\t}\n\n\tif err := az.InitializeCloudFromConfig(config, true); err != nil {\n\t\tklog.Errorf(\"Failed to initialize Azure cloud provider: %v\", err)\n\t}\n}","line":{"from":49,"to":65}} {"id":100033129,"name":"getConfigFromSecret","signature":"func (az *Cloud) getConfigFromSecret() (*Config, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_config.go","code":"func (az *Cloud) getConfigFromSecret() (*Config, error) {\n\t// Read config from file and no override, return nil.\n\tif az.Config.CloudConfigType == cloudConfigTypeFile {\n\t\treturn nil, nil\n\t}\n\n\tsecret, err := az.KubeClient.CoreV1().Secrets(cloudConfigNamespace).Get(context.TODO(), cloudConfigSecretName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get secret %s: %v\", cloudConfigSecretName, err)\n\t}\n\n\tcloudConfigData, ok := secret.Data[cloudConfigKey]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"cloud-config is not set in the secret (%s)\", cloudConfigSecretName)\n\t}\n\n\tconfig := Config{}\n\tif az.Config.CloudConfigType == \"\" || az.Config.CloudConfigType == cloudConfigTypeMerge {\n\t\t// Merge cloud config, set default value to existing config.\n\t\tconfig = az.Config\n\t}\n\n\terr = yaml.Unmarshal(cloudConfigData, \u0026config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse Azure cloud-config: %v\", err)\n\t}\n\n\treturn \u0026config, nil\n}","line":{"from":67,"to":95}} {"id":100033130,"name":"getNodeVMSet","signature":"func (c *controllerCommon) getNodeVMSet(nodeName types.NodeName, crt azcache.AzureCacheReadType) (VMSet, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_controller_common.go","code":"// getNodeVMSet gets the VMSet interface based on config.VMType and the real virtual machine type.\nfunc (c *controllerCommon) getNodeVMSet(nodeName types.NodeName, crt azcache.AzureCacheReadType) (VMSet, error) {\n\t// 1. vmType is standard, return cloud.VMSet directly.\n\tif c.cloud.VMType == vmTypeStandard {\n\t\treturn c.cloud.VMSet, nil\n\t}\n\n\t// 2. vmType is Virtual Machine Scale Set (vmss), convert vmSet to scaleSet.\n\tss, ok := c.cloud.VMSet.(*scaleSet)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"error of converting vmSet (%q) to scaleSet with vmType %q\", c.cloud.VMSet, c.cloud.VMType)\n\t}\n\n\t// 3. If the node is managed by availability set, then return ss.availabilitySet.\n\tmanagedByAS, err := ss.isNodeManagedByAvailabilitySet(mapNodeNameToVMName(nodeName), crt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif managedByAS {\n\t\t// vm is managed by availability set.\n\t\treturn ss.availabilitySet, nil\n\t}\n\n\t// 4. Node is managed by vmss\n\treturn ss, nil\n}","line":{"from":96,"to":121}} {"id":100033131,"name":"AttachDisk","signature":"func (c *controllerCommon) AttachDisk(isManagedDisk bool, diskName, diskURI string, nodeName types.NodeName, cachingMode compute.CachingTypes) (int32, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_controller_common.go","code":"// AttachDisk attaches a vhd to vm. The vhd must exist, can be identified by diskName, diskURI.\n// return (lun, error)\nfunc (c *controllerCommon) AttachDisk(isManagedDisk bool, diskName, diskURI string, nodeName types.NodeName, cachingMode compute.CachingTypes) (int32, error) {\n\tdiskEncryptionSetID := \"\"\n\twriteAcceleratorEnabled := false\n\n\tvmset, err := c.getNodeVMSet(nodeName, azcache.CacheReadTypeUnsafe)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\tif isManagedDisk {\n\t\tdiskName := path.Base(diskURI)\n\t\tresourceGroup, err := getResourceGroupFromDiskURI(diskURI)\n\t\tif err != nil {\n\t\t\treturn -1, err\n\t\t}\n\n\t\tctx, cancel := getContextWithCancel()\n\t\tdefer cancel()\n\n\t\tdisk, rerr := c.cloud.DisksClient.Get(ctx, resourceGroup, diskName)\n\t\tif rerr != nil {\n\t\t\treturn -1, rerr.Error()\n\t\t}\n\n\t\tif disk.ManagedBy != nil \u0026\u0026 (disk.MaxShares == nil || *disk.MaxShares \u003c= 1) {\n\t\t\tattachErr := fmt.Sprintf(\n\t\t\t\t\"disk(%s) already attached to node(%s), could not be attached to node(%s)\",\n\t\t\t\tdiskURI, *disk.ManagedBy, nodeName)\n\t\t\tattachedNode, err := vmset.GetNodeNameByProviderID(*disk.ManagedBy)\n\t\t\tif err != nil {\n\t\t\t\treturn -1, err\n\t\t\t}\n\t\t\tklog.V(2).Infof(\"found dangling volume %s attached to node %s\", diskURI, attachedNode)\n\t\t\tdanglingErr := volerr.NewDanglingError(attachErr, attachedNode, \"\")\n\t\t\treturn -1, danglingErr\n\t\t}\n\n\t\tif disk.DiskProperties != nil {\n\t\t\tif disk.DiskProperties.DiskSizeGB != nil \u0026\u0026 *disk.DiskProperties.DiskSizeGB \u003e= diskCachingLimit \u0026\u0026 cachingMode != compute.CachingTypesNone {\n\t\t\t\t// Disk Caching is not supported for disks 4 TiB and larger\n\t\t\t\t// https://docs.microsoft.com/en-us/azure/virtual-machines/premium-storage-performance#disk-caching\n\t\t\t\tcachingMode = compute.CachingTypesNone\n\t\t\t\tklog.Warningf(\"size of disk(%s) is %dGB which is bigger than limit(%dGB), set cacheMode as None\",\n\t\t\t\t\tdiskURI, *disk.DiskProperties.DiskSizeGB, diskCachingLimit)\n\t\t\t}\n\n\t\t\tif disk.DiskProperties.Encryption != nil \u0026\u0026\n\t\t\t\tdisk.DiskProperties.Encryption.DiskEncryptionSetID != nil {\n\t\t\t\tdiskEncryptionSetID = *disk.DiskProperties.Encryption.DiskEncryptionSetID\n\t\t\t}\n\t\t}\n\n\t\tif v, ok := disk.Tags[WriteAcceleratorEnabled]; ok {\n\t\t\tif v != nil \u0026\u0026 strings.EqualFold(*v, \"true\") {\n\t\t\t\twriteAcceleratorEnabled = true\n\t\t\t}\n\t\t}\n\t}\n\n\tinstanceid, err := c.cloud.InstanceID(context.TODO(), nodeName)\n\tif err != nil {\n\t\tklog.Warningf(\"failed to get azure instance id (%v) for node %s\", err, nodeName)\n\t\treturn -1, fmt.Errorf(\"failed to get azure instance id for node %q (%v)\", nodeName, err)\n\t}\n\n\tc.vmLockMap.LockEntry(strings.ToLower(string(nodeName)))\n\tdefer c.vmLockMap.UnlockEntry(strings.ToLower(string(nodeName)))\n\n\tlun, err := c.GetNextDiskLun(nodeName)\n\tif err != nil {\n\t\tklog.Warningf(\"no LUN available for instance %q (%v)\", nodeName, err)\n\t\treturn -1, fmt.Errorf(\"all LUNs are used, cannot attach volume (%s, %s) to instance %q (%v)\", diskName, diskURI, instanceid, err)\n\t}\n\n\tklog.V(2).Infof(\"Trying to attach volume %q lun %d to node %q.\", diskURI, lun, nodeName)\n\tc.diskAttachDetachMap.Store(strings.ToLower(diskURI), \"attaching\")\n\tdefer c.diskAttachDetachMap.Delete(strings.ToLower(diskURI))\n\treturn lun, vmset.AttachDisk(isManagedDisk, diskName, diskURI, nodeName, lun, cachingMode, diskEncryptionSetID, writeAcceleratorEnabled)\n}","line":{"from":123,"to":203}} {"id":100033132,"name":"DetachDisk","signature":"func (c *controllerCommon) DetachDisk(diskName, diskURI string, nodeName types.NodeName) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_controller_common.go","code":"// DetachDisk detaches a disk from host. The vhd can be identified by diskName or diskURI.\nfunc (c *controllerCommon) DetachDisk(diskName, diskURI string, nodeName types.NodeName) error {\n\t_, err := c.cloud.InstanceID(context.TODO(), nodeName)\n\tif err != nil {\n\t\tif err == cloudprovider.InstanceNotFound {\n\t\t\t// if host doesn't exist, no need to detach\n\t\t\tklog.Warningf(\"azureDisk - failed to get azure instance id(%q), DetachDisk(%s) will assume disk is already detached\",\n\t\t\t\tnodeName, diskURI)\n\t\t\treturn nil\n\t\t}\n\t\tklog.Warningf(\"failed to get azure instance id (%v)\", err)\n\t\treturn fmt.Errorf(\"failed to get azure instance id for node %q (%v)\", nodeName, err)\n\t}\n\n\tvmset, err := c.getNodeVMSet(nodeName, azcache.CacheReadTypeUnsafe)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tklog.V(2).Infof(\"detach %v from node %q\", diskURI, nodeName)\n\n\t// make the lock here as small as possible\n\tc.vmLockMap.LockEntry(strings.ToLower(string(nodeName)))\n\tc.diskAttachDetachMap.Store(strings.ToLower(diskURI), \"detaching\")\n\terr = vmset.DetachDisk(diskName, diskURI, nodeName)\n\tc.diskAttachDetachMap.Delete(strings.ToLower(diskURI))\n\tc.vmLockMap.UnlockEntry(strings.ToLower(string(nodeName)))\n\n\tif err != nil {\n\t\tif isInstanceNotFoundError(err) {\n\t\t\t// if host doesn't exist, no need to detach\n\t\t\tklog.Warningf(\"azureDisk - got InstanceNotFoundError(%v), DetachDisk(%s) will assume disk is already detached\",\n\t\t\t\terr, diskURI)\n\t\t\treturn nil\n\t\t}\n\t\tif retry.IsErrorRetriable(err) \u0026\u0026 c.cloud.CloudProviderBackoff {\n\t\t\tklog.Warningf(\"azureDisk - update backing off: detach disk(%s, %s), err: %v\", diskName, diskURI, err)\n\t\t\tretryErr := kwait.ExponentialBackoff(c.cloud.RequestBackoff(), func() (bool, error) {\n\t\t\t\tc.vmLockMap.LockEntry(strings.ToLower(string(nodeName)))\n\t\t\t\tc.diskAttachDetachMap.Store(strings.ToLower(diskURI), \"detaching\")\n\t\t\t\terr := vmset.DetachDisk(diskName, diskURI, nodeName)\n\t\t\t\tc.diskAttachDetachMap.Delete(strings.ToLower(diskURI))\n\t\t\t\tc.vmLockMap.UnlockEntry(strings.ToLower(string(nodeName)))\n\n\t\t\t\tretriable := false\n\t\t\t\tif err != nil \u0026\u0026 retry.IsErrorRetriable(err) {\n\t\t\t\t\tretriable = true\n\t\t\t\t}\n\t\t\t\treturn !retriable, err\n\t\t\t})\n\t\t\tif retryErr != nil {\n\t\t\t\terr = retryErr\n\t\t\t\tklog.V(2).Infof(\"azureDisk - update abort backoff: detach disk(%s, %s), err: %v\", diskName, diskURI, err)\n\t\t\t}\n\t\t}\n\t}\n\tif err != nil {\n\t\tklog.Errorf(\"azureDisk - detach disk(%s, %s) failed, err: %v\", diskName, diskURI, err)\n\t\treturn err\n\t}\n\n\tklog.V(2).Infof(\"azureDisk - detach disk(%s, %s) succeeded\", diskName, diskURI)\n\treturn nil\n}","line":{"from":205,"to":268}} {"id":100033133,"name":"getNodeDataDisks","signature":"func (c *controllerCommon) getNodeDataDisks(nodeName types.NodeName, crt azcache.AzureCacheReadType) ([]compute.DataDisk, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_controller_common.go","code":"// getNodeDataDisks invokes vmSet interfaces to get data disks for the node.\nfunc (c *controllerCommon) getNodeDataDisks(nodeName types.NodeName, crt azcache.AzureCacheReadType) ([]compute.DataDisk, error) {\n\tvmset, err := c.getNodeVMSet(nodeName, crt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn vmset.GetDataDisks(nodeName, crt)\n}","line":{"from":270,"to":278}} {"id":100033134,"name":"GetDiskLun","signature":"func (c *controllerCommon) GetDiskLun(diskName, diskURI string, nodeName types.NodeName) (int32, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_controller_common.go","code":"// GetDiskLun finds the lun on the host that the vhd is attached to, given a vhd's diskName and diskURI.\nfunc (c *controllerCommon) GetDiskLun(diskName, diskURI string, nodeName types.NodeName) (int32, error) {\n\t// getNodeDataDisks need to fetch the cached data/fresh data if cache expired here\n\t// to ensure we get LUN based on latest entry.\n\tdisks, err := c.getNodeDataDisks(nodeName, azcache.CacheReadTypeDefault)\n\tif err != nil {\n\t\tklog.Errorf(\"error of getting data disks for node %q: %v\", nodeName, err)\n\t\treturn -1, err\n\t}\n\n\tfor _, disk := range disks {\n\t\tif disk.Lun != nil \u0026\u0026 (disk.Name != nil \u0026\u0026 diskName != \"\" \u0026\u0026 strings.EqualFold(*disk.Name, diskName)) ||\n\t\t\t(disk.Vhd != nil \u0026\u0026 disk.Vhd.URI != nil \u0026\u0026 diskURI != \"\" \u0026\u0026 strings.EqualFold(*disk.Vhd.URI, diskURI)) ||\n\t\t\t(disk.ManagedDisk != nil \u0026\u0026 strings.EqualFold(*disk.ManagedDisk.ID, diskURI)) {\n\t\t\tif disk.ToBeDetached != nil \u0026\u0026 *disk.ToBeDetached {\n\t\t\t\tklog.Warningf(\"azureDisk - find disk(ToBeDetached): lun %d name %q uri %q\", *disk.Lun, diskName, diskURI)\n\t\t\t} else {\n\t\t\t\t// found the disk\n\t\t\t\tklog.V(2).Infof(\"azureDisk - find disk: lun %d name %q uri %q\", *disk.Lun, diskName, diskURI)\n\t\t\t\treturn *disk.Lun, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn -1, fmt.Errorf(\"cannot find Lun for disk %s\", diskName)\n}","line":{"from":280,"to":304}} {"id":100033135,"name":"GetNextDiskLun","signature":"func (c *controllerCommon) GetNextDiskLun(nodeName types.NodeName) (int32, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_controller_common.go","code":"// GetNextDiskLun searches all vhd attachment on the host and find unused lun. Return -1 if all luns are used.\nfunc (c *controllerCommon) GetNextDiskLun(nodeName types.NodeName) (int32, error) {\n\tdisks, err := c.getNodeDataDisks(nodeName, azcache.CacheReadTypeDefault)\n\tif err != nil {\n\t\tklog.Errorf(\"error of getting data disks for node %q: %v\", nodeName, err)\n\t\treturn -1, err\n\t}\n\n\tused := make([]bool, maxLUN)\n\tfor _, disk := range disks {\n\t\tif disk.Lun != nil {\n\t\t\tused[*disk.Lun] = true\n\t\t}\n\t}\n\tfor k, v := range used {\n\t\tif !v {\n\t\t\treturn int32(k), nil\n\t\t}\n\t}\n\treturn -1, fmt.Errorf(\"all luns are used\")\n}","line":{"from":306,"to":326}} {"id":100033136,"name":"DisksAreAttached","signature":"func (c *controllerCommon) DisksAreAttached(diskNames []string, nodeName types.NodeName) (map[string]bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_controller_common.go","code":"// DisksAreAttached checks if a list of volumes are attached to the node with the specified NodeName.\nfunc (c *controllerCommon) DisksAreAttached(diskNames []string, nodeName types.NodeName) (map[string]bool, error) {\n\tattached := make(map[string]bool)\n\tfor _, diskName := range diskNames {\n\t\tattached[diskName] = false\n\t}\n\n\t// doing stalled read for getNodeDataDisks to ensure we don't call ARM\n\t// for every reconcile call. The cache is invalidated after Attach/Detach\n\t// disk. So the new entry will be fetched and cached the first time reconcile\n\t// loop runs after the Attach/Disk OP which will reflect the latest model.\n\tdisks, err := c.getNodeDataDisks(nodeName, azcache.CacheReadTypeUnsafe)\n\tif err != nil {\n\t\tif err == cloudprovider.InstanceNotFound {\n\t\t\t// if host doesn't exist, no need to detach\n\t\t\tklog.Warningf(\"azureDisk - Cannot find node %q, DisksAreAttached will assume disks %v are not attached to it.\",\n\t\t\t\tnodeName, diskNames)\n\t\t\treturn attached, nil\n\t\t}\n\n\t\treturn attached, err\n\t}\n\n\tfor _, disk := range disks {\n\t\tfor _, diskName := range diskNames {\n\t\t\tif disk.Name != nil \u0026\u0026 diskName != \"\" \u0026\u0026 strings.EqualFold(*disk.Name, diskName) {\n\t\t\t\tattached[diskName] = true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn attached, nil\n}","line":{"from":328,"to":360}} {"id":100033137,"name":"filterDetachingDisks","signature":"func filterDetachingDisks(unfilteredDisks []compute.DataDisk) []compute.DataDisk","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_controller_common.go","code":"func filterDetachingDisks(unfilteredDisks []compute.DataDisk) []compute.DataDisk {\n\tfilteredDisks := []compute.DataDisk{}\n\tfor _, disk := range unfilteredDisks {\n\t\tif disk.ToBeDetached != nil \u0026\u0026 *disk.ToBeDetached {\n\t\t\tif disk.Name != nil {\n\t\t\t\tklog.V(2).Infof(\"Filtering disk: %s with ToBeDetached flag set.\", *disk.Name)\n\t\t\t}\n\t\t} else {\n\t\t\tfilteredDisks = append(filteredDisks, disk)\n\t\t}\n\t}\n\treturn filteredDisks\n}","line":{"from":362,"to":374}} {"id":100033138,"name":"filterNonExistingDisks","signature":"func (c *controllerCommon) filterNonExistingDisks(ctx context.Context, unfilteredDisks []compute.DataDisk) []compute.DataDisk","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_controller_common.go","code":"func (c *controllerCommon) filterNonExistingDisks(ctx context.Context, unfilteredDisks []compute.DataDisk) []compute.DataDisk {\n\tfilteredDisks := []compute.DataDisk{}\n\tfor _, disk := range unfilteredDisks {\n\t\tfilter := false\n\t\tif disk.ManagedDisk != nil \u0026\u0026 disk.ManagedDisk.ID != nil {\n\t\t\tdiskURI := *disk.ManagedDisk.ID\n\t\t\texist, err := c.cloud.checkDiskExists(ctx, diskURI)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"checkDiskExists(%s) failed with error: %v\", diskURI, err)\n\t\t\t} else {\n\t\t\t\t// only filter disk when checkDiskExists returns \u003cfalse, nil\u003e\n\t\t\t\tfilter = !exist\n\t\t\t\tif filter {\n\t\t\t\t\tklog.Errorf(\"disk(%s) does not exist, removed from data disk list\", diskURI)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif !filter {\n\t\t\tfilteredDisks = append(filteredDisks, disk)\n\t\t}\n\t}\n\treturn filteredDisks\n}","line":{"from":376,"to":399}} {"id":100033139,"name":"checkDiskExists","signature":"func (c *controllerCommon) checkDiskExists(ctx context.Context, diskURI string) (bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_controller_common.go","code":"func (c *controllerCommon) checkDiskExists(ctx context.Context, diskURI string) (bool, error) {\n\tdiskName := path.Base(diskURI)\n\tresourceGroup, err := getResourceGroupFromDiskURI(diskURI)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif _, rerr := c.cloud.DisksClient.Get(ctx, resourceGroup, diskName); rerr != nil {\n\t\tif rerr.HTTPStatusCode == http.StatusNotFound {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn false, rerr.Error()\n\t}\n\n\treturn true, nil\n}","line":{"from":401,"to":416}} {"id":100033140,"name":"getValidCreationData","signature":"func getValidCreationData(subscriptionID, resourceGroup, sourceResourceID, sourceType string) (compute.CreationData, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_controller_common.go","code":"func getValidCreationData(subscriptionID, resourceGroup, sourceResourceID, sourceType string) (compute.CreationData, error) {\n\tif sourceResourceID == \"\" {\n\t\treturn compute.CreationData{\n\t\t\tCreateOption: compute.Empty,\n\t\t}, nil\n\t}\n\n\tswitch sourceType {\n\tcase sourceSnapshot:\n\t\tif match := diskSnapshotPathRE.FindString(sourceResourceID); match == \"\" {\n\t\t\tsourceResourceID = fmt.Sprintf(diskSnapshotPath, subscriptionID, resourceGroup, sourceResourceID)\n\t\t}\n\n\tcase sourceVolume:\n\t\tif match := managedDiskPathRE.FindString(sourceResourceID); match == \"\" {\n\t\t\tsourceResourceID = fmt.Sprintf(managedDiskPath, subscriptionID, resourceGroup, sourceResourceID)\n\t\t}\n\tdefault:\n\t\treturn compute.CreationData{\n\t\t\tCreateOption: compute.Empty,\n\t\t}, nil\n\t}\n\n\tsplits := strings.Split(sourceResourceID, \"/\")\n\tif len(splits) \u003e 9 {\n\t\tif sourceType == sourceSnapshot {\n\t\t\treturn compute.CreationData{}, fmt.Errorf(\"sourceResourceID(%s) is invalid, correct format: %s\", sourceResourceID, diskSnapshotPathRE)\n\t\t}\n\t\treturn compute.CreationData{}, fmt.Errorf(\"sourceResourceID(%s) is invalid, correct format: %s\", sourceResourceID, managedDiskPathRE)\n\t}\n\treturn compute.CreationData{\n\t\tCreateOption: compute.Copy,\n\t\tSourceResourceID: \u0026sourceResourceID,\n\t}, nil\n}","line":{"from":418,"to":452}} {"id":100033141,"name":"isInstanceNotFoundError","signature":"func isInstanceNotFoundError(err error) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_controller_common.go","code":"func isInstanceNotFoundError(err error) bool {\n\terrMsg := strings.ToLower(err.Error())\n\tif strings.Contains(errMsg, strings.ToLower(vmssVMNotActiveErrorMessage)) {\n\t\treturn true\n\t}\n\treturn strings.Contains(errMsg, errStatusCode400) \u0026\u0026 strings.Contains(errMsg, errInvalidParameter) \u0026\u0026 strings.Contains(errMsg, errTargetInstanceIds)\n}","line":{"from":454,"to":460}} {"id":100033142,"name":"AttachDisk","signature":"func (as *availabilitySet) AttachDisk(isManagedDisk bool, diskName, diskURI string, nodeName types.NodeName, lun int32, cachingMode compute.CachingTypes, diskEncryptionSetID string, writeAcceleratorEnabled bool) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_controller_standard.go","code":"// AttachDisk attaches a vhd to vm\n// the vhd must exist, can be identified by diskName, diskURI, and lun.\nfunc (as *availabilitySet) AttachDisk(isManagedDisk bool, diskName, diskURI string, nodeName types.NodeName, lun int32, cachingMode compute.CachingTypes, diskEncryptionSetID string, writeAcceleratorEnabled bool) error {\n\tvm, err := as.getVirtualMachine(nodeName, azcache.CacheReadTypeDefault)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvmName := mapNodeNameToVMName(nodeName)\n\tnodeResourceGroup, err := as.GetNodeResourceGroup(vmName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdisks := make([]compute.DataDisk, len(*vm.StorageProfile.DataDisks))\n\tcopy(disks, *vm.StorageProfile.DataDisks)\n\n\tif isManagedDisk {\n\t\tmanagedDisk := \u0026compute.ManagedDiskParameters{ID: \u0026diskURI}\n\t\tif diskEncryptionSetID == \"\" {\n\t\t\tif vm.StorageProfile.OsDisk != nil \u0026\u0026\n\t\t\t\tvm.StorageProfile.OsDisk.ManagedDisk != nil \u0026\u0026\n\t\t\t\tvm.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet != nil \u0026\u0026\n\t\t\t\tvm.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet.ID != nil {\n\t\t\t\t// set diskEncryptionSet as value of os disk by default\n\t\t\t\tdiskEncryptionSetID = *vm.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet.ID\n\t\t\t}\n\t\t}\n\t\tif diskEncryptionSetID != \"\" {\n\t\t\tmanagedDisk.DiskEncryptionSet = \u0026compute.DiskEncryptionSetParameters{ID: \u0026diskEncryptionSetID}\n\t\t}\n\t\tdisks = append(disks,\n\t\t\tcompute.DataDisk{\n\t\t\t\tName: \u0026diskName,\n\t\t\t\tLun: \u0026lun,\n\t\t\t\tCaching: cachingMode,\n\t\t\t\tCreateOption: \"attach\",\n\t\t\t\tManagedDisk: managedDisk,\n\t\t\t\tWriteAcceleratorEnabled: pointer.Bool(writeAcceleratorEnabled),\n\t\t\t})\n\t} else {\n\t\tdisks = append(disks,\n\t\t\tcompute.DataDisk{\n\t\t\t\tName: \u0026diskName,\n\t\t\t\tVhd: \u0026compute.VirtualHardDisk{\n\t\t\t\t\tURI: \u0026diskURI,\n\t\t\t\t},\n\t\t\t\tLun: \u0026lun,\n\t\t\t\tCaching: cachingMode,\n\t\t\t\tCreateOption: \"attach\",\n\t\t\t})\n\t}\n\n\tnewVM := compute.VirtualMachineUpdate{\n\t\tVirtualMachineProperties: \u0026compute.VirtualMachineProperties{\n\t\t\tStorageProfile: \u0026compute.StorageProfile{\n\t\t\t\tDataDisks: \u0026disks,\n\t\t\t},\n\t\t},\n\t}\n\tklog.V(2).Infof(\"azureDisk - update(%s): vm(%s) - attach disk(%s, %s) with DiskEncryptionSetID(%s)\", nodeResourceGroup, vmName, diskName, diskURI, diskEncryptionSetID)\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\n\t// Invalidate the cache right after updating\n\tdefer as.cloud.vmCache.Delete(vmName)\n\n\trerr := as.VirtualMachinesClient.Update(ctx, nodeResourceGroup, vmName, newVM, \"attach_disk\")\n\tif rerr != nil {\n\t\tklog.Errorf(\"azureDisk - attach disk(%s, %s) on rg(%s) vm(%s) failed, err: %v\", diskName, diskURI, nodeResourceGroup, vmName, rerr)\n\t\tif rerr.HTTPStatusCode == http.StatusNotFound {\n\t\t\tklog.Errorf(\"azureDisk - begin to filterNonExistingDisks(%s, %s) on rg(%s) vm(%s)\", diskName, diskURI, nodeResourceGroup, vmName)\n\t\t\tdisks := as.filterNonExistingDisks(ctx, *newVM.VirtualMachineProperties.StorageProfile.DataDisks)\n\t\t\tnewVM.VirtualMachineProperties.StorageProfile.DataDisks = \u0026disks\n\t\t\trerr = as.VirtualMachinesClient.Update(ctx, nodeResourceGroup, vmName, newVM, \"attach_disk\")\n\t\t}\n\t}\n\n\tklog.V(2).Infof(\"azureDisk - update(%s): vm(%s) - attach disk(%s, %s) returned with %v\", nodeResourceGroup, vmName, diskName, diskURI, rerr)\n\tif rerr != nil {\n\t\treturn rerr.Error()\n\t}\n\treturn nil\n}","line":{"from":34,"to":117}} {"id":100033143,"name":"DetachDisk","signature":"func (as *availabilitySet) DetachDisk(diskName, diskURI string, nodeName types.NodeName) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_controller_standard.go","code":"// DetachDisk detaches a disk from host\n// the vhd can be identified by diskName or diskURI\nfunc (as *availabilitySet) DetachDisk(diskName, diskURI string, nodeName types.NodeName) error {\n\tvm, err := as.getVirtualMachine(nodeName, azcache.CacheReadTypeDefault)\n\tif err != nil {\n\t\t// if host doesn't exist, no need to detach\n\t\tklog.Warningf(\"azureDisk - cannot find node %s, skip detaching disk(%s, %s)\", nodeName, diskName, diskURI)\n\t\treturn nil\n\t}\n\n\tvmName := mapNodeNameToVMName(nodeName)\n\tnodeResourceGroup, err := as.GetNodeResourceGroup(vmName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdisks := make([]compute.DataDisk, len(*vm.StorageProfile.DataDisks))\n\tcopy(disks, *vm.StorageProfile.DataDisks)\n\n\tbFoundDisk := false\n\tfor i, disk := range disks {\n\t\tif disk.Lun != nil \u0026\u0026 (disk.Name != nil \u0026\u0026 diskName != \"\" \u0026\u0026 strings.EqualFold(*disk.Name, diskName)) ||\n\t\t\t(disk.Vhd != nil \u0026\u0026 disk.Vhd.URI != nil \u0026\u0026 diskURI != \"\" \u0026\u0026 strings.EqualFold(*disk.Vhd.URI, diskURI)) ||\n\t\t\t(disk.ManagedDisk != nil \u0026\u0026 diskURI != \"\" \u0026\u0026 strings.EqualFold(*disk.ManagedDisk.ID, diskURI)) {\n\t\t\t// found the disk\n\t\t\tklog.V(2).Infof(\"azureDisk - detach disk: name %q uri %q\", diskName, diskURI)\n\t\t\tif strings.EqualFold(as.cloud.Environment.Name, AzureStackCloudName) {\n\t\t\t\tdisks = append(disks[:i], disks[i+1:]...)\n\t\t\t} else {\n\t\t\t\tdisks[i].ToBeDetached = pointer.Bool(true)\n\t\t\t}\n\t\t\tbFoundDisk = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !bFoundDisk {\n\t\t// only log here, next action is to update VM status with original meta data\n\t\tklog.Errorf(\"detach azure disk: disk %s not found, diskURI: %s\", diskName, diskURI)\n\t}\n\n\tnewVM := compute.VirtualMachineUpdate{\n\t\tVirtualMachineProperties: \u0026compute.VirtualMachineProperties{\n\t\t\tStorageProfile: \u0026compute.StorageProfile{\n\t\t\t\tDataDisks: \u0026disks,\n\t\t\t},\n\t\t},\n\t}\n\tklog.V(2).Infof(\"azureDisk - update(%s): vm(%s) - detach disk(%s, %s)\", nodeResourceGroup, vmName, diskName, diskURI)\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\n\t// Invalidate the cache right after updating\n\tdefer as.cloud.vmCache.Delete(vmName)\n\n\trerr := as.VirtualMachinesClient.Update(ctx, nodeResourceGroup, vmName, newVM, \"detach_disk\")\n\tif rerr != nil {\n\t\tklog.Errorf(\"azureDisk - detach disk(%s, %s) on rg(%s) vm(%s) failed, err: %v\", diskName, diskURI, nodeResourceGroup, vmName, rerr)\n\t\tif rerr.HTTPStatusCode == http.StatusNotFound {\n\t\t\tklog.Errorf(\"azureDisk - begin to filterNonExistingDisks(%s, %s) on rg(%s) vm(%s)\", diskName, diskURI, nodeResourceGroup, vmName)\n\t\t\tdisks := as.filterNonExistingDisks(ctx, *vm.StorageProfile.DataDisks)\n\t\t\tnewVM.VirtualMachineProperties.StorageProfile.DataDisks = \u0026disks\n\t\t\trerr = as.VirtualMachinesClient.Update(ctx, nodeResourceGroup, vmName, newVM, \"detach_disk\")\n\t\t}\n\t}\n\n\tklog.V(2).Infof(\"azureDisk - update(%s): vm(%s) - detach disk(%s, %s) returned with %v\", nodeResourceGroup, vmName, diskName, diskURI, rerr)\n\tif rerr != nil {\n\t\treturn rerr.Error()\n\t}\n\treturn nil\n}","line":{"from":119,"to":190}} {"id":100033144,"name":"GetDataDisks","signature":"func (as *availabilitySet) GetDataDisks(nodeName types.NodeName, crt azcache.AzureCacheReadType) ([]compute.DataDisk, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_controller_standard.go","code":"// GetDataDisks gets a list of data disks attached to the node.\nfunc (as *availabilitySet) GetDataDisks(nodeName types.NodeName, crt azcache.AzureCacheReadType) ([]compute.DataDisk, error) {\n\tvm, err := as.getVirtualMachine(nodeName, crt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif vm.StorageProfile.DataDisks == nil {\n\t\treturn nil, nil\n\t}\n\n\treturn *vm.StorageProfile.DataDisks, nil\n}","line":{"from":192,"to":204}} {"id":100033145,"name":"AttachDisk","signature":"func (ss *scaleSet) AttachDisk(isManagedDisk bool, diskName, diskURI string, nodeName types.NodeName, lun int32, cachingMode compute.CachingTypes, diskEncryptionSetID string, writeAcceleratorEnabled bool) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_controller_vmss.go","code":"// AttachDisk attaches a vhd to vm\n// the vhd must exist, can be identified by diskName, diskURI, and lun.\nfunc (ss *scaleSet) AttachDisk(isManagedDisk bool, diskName, diskURI string, nodeName types.NodeName, lun int32, cachingMode compute.CachingTypes, diskEncryptionSetID string, writeAcceleratorEnabled bool) error {\n\tvmName := mapNodeNameToVMName(nodeName)\n\tssName, instanceID, vm, err := ss.getVmssVM(vmName, azcache.CacheReadTypeDefault)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnodeResourceGroup, err := ss.GetNodeResourceGroup(vmName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdisks := []compute.DataDisk{}\n\tif vm.StorageProfile != nil \u0026\u0026 vm.StorageProfile.DataDisks != nil {\n\t\tdisks = make([]compute.DataDisk, len(*vm.StorageProfile.DataDisks))\n\t\tcopy(disks, *vm.StorageProfile.DataDisks)\n\t}\n\tif isManagedDisk {\n\t\tmanagedDisk := \u0026compute.ManagedDiskParameters{ID: \u0026diskURI}\n\t\tif diskEncryptionSetID == \"\" {\n\t\t\tif vm.StorageProfile.OsDisk != nil \u0026\u0026\n\t\t\t\tvm.StorageProfile.OsDisk.ManagedDisk != nil \u0026\u0026\n\t\t\t\tvm.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet != nil \u0026\u0026\n\t\t\t\tvm.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet.ID != nil {\n\t\t\t\t// set diskEncryptionSet as value of os disk by default\n\t\t\t\tdiskEncryptionSetID = *vm.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet.ID\n\t\t\t}\n\t\t}\n\t\tif diskEncryptionSetID != \"\" {\n\t\t\tmanagedDisk.DiskEncryptionSet = \u0026compute.DiskEncryptionSetParameters{ID: \u0026diskEncryptionSetID}\n\t\t}\n\t\tdisks = append(disks,\n\t\t\tcompute.DataDisk{\n\t\t\t\tName: \u0026diskName,\n\t\t\t\tLun: \u0026lun,\n\t\t\t\tCaching: compute.CachingTypes(cachingMode),\n\t\t\t\tCreateOption: \"attach\",\n\t\t\t\tManagedDisk: managedDisk,\n\t\t\t\tWriteAcceleratorEnabled: pointer.Bool(writeAcceleratorEnabled),\n\t\t\t})\n\t} else {\n\t\tdisks = append(disks,\n\t\t\tcompute.DataDisk{\n\t\t\t\tName: \u0026diskName,\n\t\t\t\tVhd: \u0026compute.VirtualHardDisk{\n\t\t\t\t\tURI: \u0026diskURI,\n\t\t\t\t},\n\t\t\t\tLun: \u0026lun,\n\t\t\t\tCaching: compute.CachingTypes(cachingMode),\n\t\t\t\tCreateOption: \"attach\",\n\t\t\t})\n\t}\n\tnewVM := compute.VirtualMachineScaleSetVM{\n\t\tVirtualMachineScaleSetVMProperties: \u0026compute.VirtualMachineScaleSetVMProperties{\n\t\t\tStorageProfile: \u0026compute.StorageProfile{\n\t\t\t\tDataDisks: \u0026disks,\n\t\t\t},\n\t\t},\n\t}\n\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\n\t// Invalidate the cache right after updating\n\tdefer ss.deleteCacheForNode(vmName)\n\n\tklog.V(2).Infof(\"azureDisk - update(%s): vm(%s) - attach disk(%s, %s) with DiskEncryptionSetID(%s)\", nodeResourceGroup, nodeName, diskName, diskURI, diskEncryptionSetID)\n\trerr := ss.VirtualMachineScaleSetVMsClient.Update(ctx, nodeResourceGroup, ssName, instanceID, newVM, \"attach_disk\")\n\tif rerr != nil {\n\t\tklog.Errorf(\"azureDisk - attach disk(%s, %s) on rg(%s) vm(%s) failed, err: %v\", diskName, diskURI, nodeResourceGroup, nodeName, rerr)\n\t\tif rerr.HTTPStatusCode == http.StatusNotFound {\n\t\t\tklog.Errorf(\"azureDisk - begin to filterNonExistingDisks(%s, %s) on rg(%s) vm(%s)\", diskName, diskURI, nodeResourceGroup, nodeName)\n\t\t\tdisks := ss.filterNonExistingDisks(ctx, *newVM.VirtualMachineScaleSetVMProperties.StorageProfile.DataDisks)\n\t\t\tnewVM.VirtualMachineScaleSetVMProperties.StorageProfile.DataDisks = \u0026disks\n\t\t\trerr = ss.VirtualMachineScaleSetVMsClient.Update(ctx, nodeResourceGroup, ssName, instanceID, newVM, \"attach_disk\")\n\t\t}\n\t}\n\n\tklog.V(2).Infof(\"azureDisk - update(%s): vm(%s) - attach disk(%s, %s) returned with %v\", nodeResourceGroup, nodeName, diskName, diskURI, rerr)\n\tif rerr != nil {\n\t\treturn rerr.Error()\n\t}\n\treturn nil\n}","line":{"from":34,"to":119}} {"id":100033146,"name":"DetachDisk","signature":"func (ss *scaleSet) DetachDisk(diskName, diskURI string, nodeName types.NodeName) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_controller_vmss.go","code":"// DetachDisk detaches a disk from host\n// the vhd can be identified by diskName or diskURI\nfunc (ss *scaleSet) DetachDisk(diskName, diskURI string, nodeName types.NodeName) error {\n\tvmName := mapNodeNameToVMName(nodeName)\n\tssName, instanceID, vm, err := ss.getVmssVM(vmName, azcache.CacheReadTypeDefault)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnodeResourceGroup, err := ss.GetNodeResourceGroup(vmName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdisks := []compute.DataDisk{}\n\tif vm.StorageProfile != nil \u0026\u0026 vm.StorageProfile.DataDisks != nil {\n\t\tdisks = make([]compute.DataDisk, len(*vm.StorageProfile.DataDisks))\n\t\tcopy(disks, *vm.StorageProfile.DataDisks)\n\t}\n\tbFoundDisk := false\n\tfor i, disk := range disks {\n\t\tif disk.Lun != nil \u0026\u0026 (disk.Name != nil \u0026\u0026 diskName != \"\" \u0026\u0026 strings.EqualFold(*disk.Name, diskName)) ||\n\t\t\t(disk.Vhd != nil \u0026\u0026 disk.Vhd.URI != nil \u0026\u0026 diskURI != \"\" \u0026\u0026 strings.EqualFold(*disk.Vhd.URI, diskURI)) ||\n\t\t\t(disk.ManagedDisk != nil \u0026\u0026 diskURI != \"\" \u0026\u0026 strings.EqualFold(*disk.ManagedDisk.ID, diskURI)) {\n\t\t\t// found the disk\n\t\t\tklog.V(2).Infof(\"azureDisk - detach disk: name %q uri %q\", diskName, diskURI)\n\t\t\tif strings.EqualFold(ss.cloud.Environment.Name, AzureStackCloudName) {\n\t\t\t\tdisks = append(disks[:i], disks[i+1:]...)\n\t\t\t} else {\n\t\t\t\tdisks[i].ToBeDetached = pointer.Bool(true)\n\t\t\t}\n\t\t\tbFoundDisk = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !bFoundDisk {\n\t\t// only log here, next action is to update VM status with original meta data\n\t\tklog.Errorf(\"detach azure disk: disk %s not found, diskURI: %s\", diskName, diskURI)\n\t}\n\n\tnewVM := compute.VirtualMachineScaleSetVM{\n\t\tVirtualMachineScaleSetVMProperties: \u0026compute.VirtualMachineScaleSetVMProperties{\n\t\t\tStorageProfile: \u0026compute.StorageProfile{\n\t\t\t\tDataDisks: \u0026disks,\n\t\t\t},\n\t\t},\n\t}\n\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\n\t// Invalidate the cache right after updating\n\tdefer ss.deleteCacheForNode(vmName)\n\n\tklog.V(2).Infof(\"azureDisk - update(%s): vm(%s) - detach disk(%s, %s)\", nodeResourceGroup, nodeName, diskName, diskURI)\n\trerr := ss.VirtualMachineScaleSetVMsClient.Update(ctx, nodeResourceGroup, ssName, instanceID, newVM, \"detach_disk\")\n\tif rerr != nil {\n\t\tklog.Errorf(\"azureDisk - detach disk(%s, %s) on rg(%s) vm(%s) failed, err: %v\", diskName, diskURI, nodeResourceGroup, nodeName, rerr)\n\t\tif rerr.HTTPStatusCode == http.StatusNotFound {\n\t\t\tklog.Errorf(\"azureDisk - begin to filterNonExistingDisks(%s, %s) on rg(%s) vm(%s)\", diskName, diskURI, nodeResourceGroup, nodeName)\n\t\t\tdisks := ss.filterNonExistingDisks(ctx, *newVM.VirtualMachineScaleSetVMProperties.StorageProfile.DataDisks)\n\t\t\tnewVM.VirtualMachineScaleSetVMProperties.StorageProfile.DataDisks = \u0026disks\n\t\t\trerr = ss.VirtualMachineScaleSetVMsClient.Update(ctx, nodeResourceGroup, ssName, instanceID, newVM, \"detach_disk\")\n\t\t}\n\t}\n\n\tklog.V(2).Infof(\"azureDisk - update(%s): vm(%s) - detach disk(%s, %s) returned with %v\", nodeResourceGroup, nodeName, diskName, diskURI, rerr)\n\tif rerr != nil {\n\t\treturn rerr.Error()\n\t}\n\treturn nil\n}","line":{"from":121,"to":193}} {"id":100033147,"name":"GetDataDisks","signature":"func (ss *scaleSet) GetDataDisks(nodeName types.NodeName, crt azcache.AzureCacheReadType) ([]compute.DataDisk, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_controller_vmss.go","code":"// GetDataDisks gets a list of data disks attached to the node.\nfunc (ss *scaleSet) GetDataDisks(nodeName types.NodeName, crt azcache.AzureCacheReadType) ([]compute.DataDisk, error) {\n\t_, _, vm, err := ss.getVmssVM(string(nodeName), crt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif vm.StorageProfile == nil || vm.StorageProfile.DataDisks == nil {\n\t\treturn nil, nil\n\t}\n\n\treturn *vm.StorageProfile.DataDisks, nil\n}","line":{"from":195,"to":207}} {"id":100033148,"name":"createFileShare","signature":"func (az *Cloud) createFileShare(resourceGroupName, accountName string, shareOptions *fileclient.ShareOptions) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_file.go","code":"// create file share\nfunc (az *Cloud) createFileShare(resourceGroupName, accountName string, shareOptions *fileclient.ShareOptions) error {\n\treturn az.FileClient.CreateFileShare(resourceGroupName, accountName, shareOptions)\n}","line":{"from":27,"to":30}} {"id":100033149,"name":"deleteFileShare","signature":"func (az *Cloud) deleteFileShare(resourceGroupName, accountName, name string) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_file.go","code":"func (az *Cloud) deleteFileShare(resourceGroupName, accountName, name string) error {\n\treturn az.FileClient.DeleteFileShare(resourceGroupName, accountName, name)\n}","line":{"from":32,"to":34}} {"id":100033150,"name":"resizeFileShare","signature":"func (az *Cloud) resizeFileShare(resourceGroupName, accountName, name string, sizeGiB int) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_file.go","code":"func (az *Cloud) resizeFileShare(resourceGroupName, accountName, name string, sizeGiB int) error {\n\treturn az.FileClient.ResizeFileShare(resourceGroupName, accountName, name, sizeGiB)\n}","line":{"from":36,"to":38}} {"id":100033151,"name":"getFileShare","signature":"func (az *Cloud) getFileShare(resourceGroupName, accountName, name string) (storage.FileShare, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_file.go","code":"func (az *Cloud) getFileShare(resourceGroupName, accountName, name string) (storage.FileShare, error) {\n\treturn az.FileClient.GetFileShare(resourceGroupName, accountName, name)\n}","line":{"from":40,"to":42}} {"id":100033152,"name":"NewInstanceMetadataService","signature":"func NewInstanceMetadataService(imdsServer string) (*InstanceMetadataService, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_instance_metadata.go","code":"// NewInstanceMetadataService creates an instance of the InstanceMetadataService accessor object.\nfunc NewInstanceMetadataService(imdsServer string) (*InstanceMetadataService, error) {\n\tims := \u0026InstanceMetadataService{\n\t\timdsServer: imdsServer,\n\t}\n\n\timsCache, err := azcache.NewTimedcache(metadataCacheTTL, ims.getMetadata)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tims.imsCache = imsCache\n\treturn ims, nil\n}","line":{"from":117,"to":130}} {"id":100033153,"name":"getMetadata","signature":"func (ims *InstanceMetadataService) getMetadata(key string) (interface{}, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_instance_metadata.go","code":"func (ims *InstanceMetadataService) getMetadata(key string) (interface{}, error) {\n\tinstanceMetadata, err := ims.getInstanceMetadata(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif instanceMetadata.Network != nil \u0026\u0026 len(instanceMetadata.Network.Interface) \u003e 0 {\n\t\tnetInterface := instanceMetadata.Network.Interface[0]\n\t\tif (len(netInterface.IPV4.IPAddress) \u003e 0 \u0026\u0026 len(netInterface.IPV4.IPAddress[0].PublicIP) \u003e 0) ||\n\t\t\t(len(netInterface.IPV6.IPAddress) \u003e 0 \u0026\u0026 len(netInterface.IPV6.IPAddress[0].PublicIP) \u003e 0) {\n\t\t\t// Return if public IP address has already part of instance metadata.\n\t\t\treturn instanceMetadata, nil\n\t\t}\n\n\t\tloadBalancerMetadata, err := ims.getLoadBalancerMetadata()\n\t\tif err != nil || loadBalancerMetadata == nil || loadBalancerMetadata.LoadBalancer == nil {\n\t\t\t// Log a warning since loadbalancer metadata may not be available when the VM\n\t\t\t// is not in standard LoadBalancer backend address pool.\n\t\t\tklog.V(4).Infof(\"Warning: failed to get loadbalancer metadata: %v\", err)\n\t\t\treturn instanceMetadata, nil\n\t\t}\n\n\t\tpublicIPs := loadBalancerMetadata.LoadBalancer.PublicIPAddresses\n\t\tif len(netInterface.IPV4.IPAddress) \u003e 0 \u0026\u0026 len(netInterface.IPV4.IPAddress[0].PrivateIP) \u003e 0 {\n\t\t\tfor _, pip := range publicIPs {\n\t\t\t\tif pip.PrivateIPAddress == netInterface.IPV4.IPAddress[0].PrivateIP {\n\t\t\t\t\tnetInterface.IPV4.IPAddress[0].PublicIP = pip.FrontendIPAddress\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif len(netInterface.IPV6.IPAddress) \u003e 0 \u0026\u0026 len(netInterface.IPV6.IPAddress[0].PrivateIP) \u003e 0 {\n\t\t\tfor _, pip := range publicIPs {\n\t\t\t\tif pip.PrivateIPAddress == netInterface.IPV6.IPAddress[0].PrivateIP {\n\t\t\t\t\tnetInterface.IPV6.IPAddress[0].PublicIP = pip.FrontendIPAddress\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn instanceMetadata, nil\n}","line":{"from":132,"to":174}} {"id":100033154,"name":"getInstanceMetadata","signature":"func (ims *InstanceMetadataService) getInstanceMetadata(key string) (*InstanceMetadata, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_instance_metadata.go","code":"func (ims *InstanceMetadataService) getInstanceMetadata(key string) (*InstanceMetadata, error) {\n\treq, err := http.NewRequest(\"GET\", ims.imdsServer+imdsInstanceURI, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Add(\"Metadata\", \"True\")\n\treq.Header.Add(\"User-Agent\", \"golang/kubernetes-cloud-provider\")\n\n\tq := req.URL.Query()\n\tq.Add(\"format\", \"json\")\n\tq.Add(\"api-version\", imdsInstanceAPIVersion)\n\treq.URL.RawQuery = q.Encode()\n\n\tclient := \u0026http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"failure of getting instance metadata with response %q\", resp.Status)\n\t}\n\n\tdata, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tobj := InstanceMetadata{}\n\terr = json.Unmarshal(data, \u0026obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026obj, nil\n}","line":{"from":176,"to":212}} {"id":100033155,"name":"getLoadBalancerMetadata","signature":"func (ims *InstanceMetadataService) getLoadBalancerMetadata() (*LoadBalancerMetadata, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_instance_metadata.go","code":"func (ims *InstanceMetadataService) getLoadBalancerMetadata() (*LoadBalancerMetadata, error) {\n\treq, err := http.NewRequest(\"GET\", ims.imdsServer+imdsLoadBalancerURI, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Add(\"Metadata\", \"True\")\n\treq.Header.Add(\"User-Agent\", \"golang/kubernetes-cloud-provider\")\n\n\tq := req.URL.Query()\n\tq.Add(\"format\", \"json\")\n\tq.Add(\"api-version\", imdsLoadBalancerAPIVersion)\n\treq.URL.RawQuery = q.Encode()\n\n\tclient := \u0026http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"failure of getting loadbalancer metadata with response %q\", resp.Status)\n\t}\n\n\tdata, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tobj := LoadBalancerMetadata{}\n\terr = json.Unmarshal(data, \u0026obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026obj, nil\n}","line":{"from":214,"to":250}} {"id":100033156,"name":"GetMetadata","signature":"func (ims *InstanceMetadataService) GetMetadata(crt azcache.AzureCacheReadType) (*InstanceMetadata, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_instance_metadata.go","code":"// GetMetadata gets instance metadata from cache.\n// crt determines if we can get data from stalled cache/need fresh if cache expired.\nfunc (ims *InstanceMetadataService) GetMetadata(crt azcache.AzureCacheReadType) (*InstanceMetadata, error) {\n\tcache, err := ims.imsCache.Get(metadataCacheKey, crt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Cache shouldn't be nil, but added a check in case something is wrong.\n\tif cache == nil {\n\t\treturn nil, fmt.Errorf(\"failure of getting instance metadata\")\n\t}\n\n\tif metadata, ok := cache.(*InstanceMetadata); ok {\n\t\treturn metadata, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"failure of getting instance metadata\")\n}","line":{"from":252,"to":270}} {"id":100033157,"name":"addressGetter","signature":"func (az *Cloud) addressGetter(nodeName types.NodeName) ([]v1.NodeAddress, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_instances.go","code":"func (az *Cloud) addressGetter(nodeName types.NodeName) ([]v1.NodeAddress, error) {\n\tip, publicIP, err := az.getIPForMachine(nodeName)\n\tif err != nil {\n\t\tklog.V(2).Infof(\"NodeAddresses(%s) abort backoff: %v\", nodeName, err)\n\t\treturn nil, err\n\t}\n\n\taddresses := []v1.NodeAddress{\n\t\t{Type: v1.NodeInternalIP, Address: ip},\n\t\t{Type: v1.NodeHostName, Address: string(nodeName)},\n\t}\n\tif len(publicIP) \u003e 0 {\n\t\taddresses = append(addresses, v1.NodeAddress{\n\t\t\tType: v1.NodeExternalIP,\n\t\t\tAddress: publicIP,\n\t\t})\n\t}\n\treturn addresses, nil\n}","line":{"from":53,"to":71}} {"id":100033158,"name":"NodeAddresses","signature":"func (az *Cloud) NodeAddresses(ctx context.Context, name types.NodeName) ([]v1.NodeAddress, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_instances.go","code":"// NodeAddresses returns the addresses of the specified instance.\nfunc (az *Cloud) NodeAddresses(ctx context.Context, name types.NodeName) ([]v1.NodeAddress, error) {\n\t// Returns nil for unmanaged nodes because azure cloud provider couldn't fetch information for them.\n\tunmanaged, err := az.IsNodeUnmanaged(string(name))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif unmanaged {\n\t\tklog.V(4).Infof(\"NodeAddresses: omitting unmanaged node %q\", name)\n\t\treturn nil, nil\n\t}\n\n\tif az.UseInstanceMetadata {\n\t\tmetadata, err := az.metadata.GetMetadata(azcache.CacheReadTypeDefault)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif metadata.Compute == nil || metadata.Network == nil {\n\t\t\treturn nil, fmt.Errorf(\"failure of getting instance metadata\")\n\t\t}\n\n\t\tisLocalInstance, err := az.isCurrentInstance(name, metadata.Compute.Name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Not local instance, get addresses from Azure ARM API.\n\t\tif !isLocalInstance {\n\t\t\tif az.VMSet != nil {\n\t\t\t\treturn az.addressGetter(name)\n\t\t\t}\n\n\t\t\t// vmSet == nil indicates credentials are not provided.\n\t\t\treturn nil, fmt.Errorf(\"no credentials provided for Azure cloud provider\")\n\t\t}\n\n\t\treturn az.getLocalInstanceNodeAddresses(metadata.Network.Interface, string(name))\n\t}\n\n\treturn az.addressGetter(name)\n}","line":{"from":73,"to":114}} {"id":100033159,"name":"getLocalInstanceNodeAddresses","signature":"func (az *Cloud) getLocalInstanceNodeAddresses(netInterfaces []NetworkInterface, nodeName string) ([]v1.NodeAddress, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_instances.go","code":"func (az *Cloud) getLocalInstanceNodeAddresses(netInterfaces []NetworkInterface, nodeName string) ([]v1.NodeAddress, error) {\n\tif len(netInterfaces) == 0 {\n\t\treturn nil, fmt.Errorf(\"no interface is found for the instance\")\n\t}\n\n\t// Use ip address got from instance metadata.\n\tnetInterface := netInterfaces[0]\n\taddresses := []v1.NodeAddress{\n\t\t{Type: v1.NodeHostName, Address: nodeName},\n\t}\n\tif len(netInterface.IPV4.IPAddress) \u003e 0 \u0026\u0026 len(netInterface.IPV4.IPAddress[0].PrivateIP) \u003e 0 {\n\t\taddress := netInterface.IPV4.IPAddress[0]\n\t\taddresses = append(addresses, v1.NodeAddress{\n\t\t\tType: v1.NodeInternalIP,\n\t\t\tAddress: address.PrivateIP,\n\t\t})\n\t\tif len(address.PublicIP) \u003e 0 {\n\t\t\taddresses = append(addresses, v1.NodeAddress{\n\t\t\t\tType: v1.NodeExternalIP,\n\t\t\t\tAddress: address.PublicIP,\n\t\t\t})\n\t\t}\n\t}\n\tif len(netInterface.IPV6.IPAddress) \u003e 0 \u0026\u0026 len(netInterface.IPV6.IPAddress[0].PrivateIP) \u003e 0 {\n\t\taddress := netInterface.IPV6.IPAddress[0]\n\t\taddresses = append(addresses, v1.NodeAddress{\n\t\t\tType: v1.NodeInternalIP,\n\t\t\tAddress: address.PrivateIP,\n\t\t})\n\t\tif len(address.PublicIP) \u003e 0 {\n\t\t\taddresses = append(addresses, v1.NodeAddress{\n\t\t\t\tType: v1.NodeExternalIP,\n\t\t\t\tAddress: address.PublicIP,\n\t\t\t})\n\t\t}\n\t}\n\n\tif len(addresses) == 1 {\n\t\t// No IP addresses is got from instance metadata service, clean up cache and report errors.\n\t\taz.metadata.imsCache.Delete(metadataCacheKey)\n\t\treturn nil, fmt.Errorf(\"get empty IP addresses from instance metadata service\")\n\t}\n\treturn addresses, nil\n}","line":{"from":116,"to":159}} {"id":100033160,"name":"NodeAddressesByProviderID","signature":"func (az *Cloud) NodeAddressesByProviderID(ctx context.Context, providerID string) ([]v1.NodeAddress, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_instances.go","code":"// NodeAddressesByProviderID returns the node addresses of an instances with the specified unique providerID\n// This method will not be called from the node that is requesting this ID. i.e. metadata service\n// and other local methods cannot be used here\nfunc (az *Cloud) NodeAddressesByProviderID(ctx context.Context, providerID string) ([]v1.NodeAddress, error) {\n\tif providerID == \"\" {\n\t\treturn nil, errNodeNotInitialized\n\t}\n\n\t// Returns nil for unmanaged nodes because azure cloud provider couldn't fetch information for them.\n\tif az.IsNodeUnmanagedByProviderID(providerID) {\n\t\tklog.V(4).Infof(\"NodeAddressesByProviderID: omitting unmanaged node %q\", providerID)\n\t\treturn nil, nil\n\t}\n\n\tname, err := az.VMSet.GetNodeNameByProviderID(providerID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn az.NodeAddresses(ctx, name)\n}","line":{"from":161,"to":181}} {"id":100033161,"name":"InstanceExistsByProviderID","signature":"func (az *Cloud) InstanceExistsByProviderID(ctx context.Context, providerID string) (bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_instances.go","code":"// InstanceExistsByProviderID returns true if the instance with the given provider id still exists and is running.\n// If false is returned with no error, the instance will be immediately deleted by the cloud controller manager.\nfunc (az *Cloud) InstanceExistsByProviderID(ctx context.Context, providerID string) (bool, error) {\n\tif providerID == \"\" {\n\t\treturn false, errNodeNotInitialized\n\t}\n\n\t// Returns true for unmanaged nodes because azure cloud provider always assumes them exists.\n\tif az.IsNodeUnmanagedByProviderID(providerID) {\n\t\tklog.V(4).Infof(\"InstanceExistsByProviderID: assuming unmanaged node %q exists\", providerID)\n\t\treturn true, nil\n\t}\n\n\tname, err := az.VMSet.GetNodeNameByProviderID(providerID)\n\tif err != nil {\n\t\tif err == cloudprovider.InstanceNotFound {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn false, err\n\t}\n\n\t_, err = az.InstanceID(ctx, name)\n\tif err != nil {\n\t\tif err == cloudprovider.InstanceNotFound {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn false, err\n\t}\n\n\treturn true, nil\n}","line":{"from":183,"to":213}} {"id":100033162,"name":"InstanceShutdownByProviderID","signature":"func (az *Cloud) InstanceShutdownByProviderID(ctx context.Context, providerID string) (bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_instances.go","code":"// InstanceShutdownByProviderID returns true if the instance is in safe state to detach volumes\nfunc (az *Cloud) InstanceShutdownByProviderID(ctx context.Context, providerID string) (bool, error) {\n\tif providerID == \"\" {\n\t\treturn false, nil\n\t}\n\n\tnodeName, err := az.VMSet.GetNodeNameByProviderID(providerID)\n\tif err != nil {\n\t\t// Returns false, so the controller manager will continue to check InstanceExistsByProviderID().\n\t\tif err == cloudprovider.InstanceNotFound {\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn false, err\n\t}\n\n\tpowerStatus, err := az.VMSet.GetPowerStatusByNodeName(string(nodeName))\n\tif err != nil {\n\t\t// Returns false, so the controller manager will continue to check InstanceExistsByProviderID().\n\t\tif err == cloudprovider.InstanceNotFound {\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn false, err\n\t}\n\tklog.V(3).Infof(\"InstanceShutdownByProviderID gets power status %q for node %q\", powerStatus, nodeName)\n\n\tprovisioningState, err := az.VMSet.GetProvisioningStateByNodeName(string(nodeName))\n\tif err != nil {\n\t\t// Returns false, so the controller manager will continue to check InstanceExistsByProviderID().\n\t\tif errors.Is(err, cloudprovider.InstanceNotFound) {\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn false, err\n\t}\n\tklog.V(3).Infof(\"InstanceShutdownByProviderID gets provisioning state %q for node %q\", provisioningState, nodeName)\n\n\tstatus := strings.ToLower(powerStatus)\n\tprovisioningSucceeded := strings.EqualFold(strings.ToLower(provisioningState), strings.ToLower(string(compute.ProvisioningStateSucceeded)))\n\treturn provisioningSucceeded \u0026\u0026 (status == vmPowerStateStopped || status == vmPowerStateDeallocated || status == vmPowerStateDeallocating), nil\n}","line":{"from":215,"to":256}} {"id":100033163,"name":"isCurrentInstance","signature":"func (az *Cloud) isCurrentInstance(name types.NodeName, metadataVMName string) (bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_instances.go","code":"func (az *Cloud) isCurrentInstance(name types.NodeName, metadataVMName string) (bool, error) {\n\tvar err error\n\tnodeName := mapNodeNameToVMName(name)\n\n\t// VMSS vmName is not same with hostname, use hostname instead.\n\tif az.VMType == vmTypeVMSS {\n\t\tmetadataVMName, err = os.Hostname()\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\t// Use name from env variable \"NODE_NAME\" if it is set.\n\t\tnodeNameEnv := os.Getenv(nodeNameEnvironmentName)\n\t\tif nodeNameEnv != \"\" {\n\t\t\tmetadataVMName = nodeNameEnv\n\t\t}\n\t}\n\n\tmetadataVMName = strings.ToLower(metadataVMName)\n\treturn metadataVMName == nodeName, nil\n}","line":{"from":258,"to":278}} {"id":100033164,"name":"InstanceID","signature":"func (az *Cloud) InstanceID(ctx context.Context, name types.NodeName) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_instances.go","code":"// InstanceID returns the cloud provider ID of the specified instance.\n// Note that if the instance does not exist or is no longer running, we must return (\"\", cloudprovider.InstanceNotFound)\nfunc (az *Cloud) InstanceID(ctx context.Context, name types.NodeName) (string, error) {\n\tnodeName := mapNodeNameToVMName(name)\n\tunmanaged, err := az.IsNodeUnmanaged(nodeName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif unmanaged {\n\t\t// InstanceID is same with nodeName for unmanaged nodes.\n\t\tklog.V(4).Infof(\"InstanceID: getting ID %q for unmanaged node %q\", name, name)\n\t\treturn nodeName, nil\n\t}\n\n\tif az.UseInstanceMetadata {\n\t\tmetadata, err := az.metadata.GetMetadata(azcache.CacheReadTypeDefault)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tif metadata.Compute == nil {\n\t\t\treturn \"\", fmt.Errorf(\"failure of getting instance metadata\")\n\t\t}\n\n\t\tisLocalInstance, err := az.isCurrentInstance(name, metadata.Compute.Name)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\t// Not local instance, get instanceID from Azure ARM API.\n\t\tif !isLocalInstance {\n\t\t\tif az.VMSet != nil {\n\t\t\t\treturn az.VMSet.GetInstanceIDByNodeName(nodeName)\n\t\t\t}\n\n\t\t\t// vmSet == nil indicates credentials are not provided.\n\t\t\treturn \"\", fmt.Errorf(\"no credentials provided for Azure cloud provider\")\n\t\t}\n\t\treturn az.getLocalInstanceProviderID(metadata, nodeName)\n\t}\n\n\treturn az.VMSet.GetInstanceIDByNodeName(nodeName)\n}","line":{"from":280,"to":322}} {"id":100033165,"name":"getLocalInstanceProviderID","signature":"func (az *Cloud) getLocalInstanceProviderID(metadata *InstanceMetadata, nodeName string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_instances.go","code":"func (az *Cloud) getLocalInstanceProviderID(metadata *InstanceMetadata, nodeName string) (string, error) {\n\t// Get resource group name and subscription ID.\n\tresourceGroup := strings.ToLower(metadata.Compute.ResourceGroup)\n\tsubscriptionID := strings.ToLower(metadata.Compute.SubscriptionID)\n\n\t// Compose instanceID based on nodeName for standard instance.\n\tif metadata.Compute.VMScaleSetName == \"\" {\n\t\treturn az.getStandardMachineID(subscriptionID, resourceGroup, nodeName), nil\n\t}\n\n\t// Get scale set name and instanceID from vmName for vmss.\n\tssName, instanceID, err := extractVmssVMName(metadata.Compute.Name)\n\tif err != nil {\n\t\tif err == ErrorNotVmssInstance {\n\t\t\t// Compose machineID for standard Node.\n\t\t\treturn az.getStandardMachineID(subscriptionID, resourceGroup, nodeName), nil\n\t\t}\n\t\treturn \"\", err\n\t}\n\t// Compose instanceID based on ssName and instanceID for vmss instance.\n\treturn az.getVmssMachineID(subscriptionID, resourceGroup, ssName, instanceID), nil\n}","line":{"from":324,"to":345}} {"id":100033166,"name":"InstanceTypeByProviderID","signature":"func (az *Cloud) InstanceTypeByProviderID(ctx context.Context, providerID string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_instances.go","code":"// InstanceTypeByProviderID returns the cloudprovider instance type of the node with the specified unique providerID\n// This method will not be called from the node that is requesting this ID. i.e. metadata service\n// and other local methods cannot be used here\nfunc (az *Cloud) InstanceTypeByProviderID(ctx context.Context, providerID string) (string, error) {\n\tif providerID == \"\" {\n\t\treturn \"\", errNodeNotInitialized\n\t}\n\n\t// Returns \"\" for unmanaged nodes because azure cloud provider couldn't fetch information for them.\n\tif az.IsNodeUnmanagedByProviderID(providerID) {\n\t\tklog.V(4).Infof(\"InstanceTypeByProviderID: omitting unmanaged node %q\", providerID)\n\t\treturn \"\", nil\n\t}\n\n\tname, err := az.VMSet.GetNodeNameByProviderID(providerID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn az.InstanceType(ctx, name)\n}","line":{"from":347,"to":367}} {"id":100033167,"name":"InstanceType","signature":"func (az *Cloud) InstanceType(ctx context.Context, name types.NodeName) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_instances.go","code":"// InstanceType returns the type of the specified instance.\n// Note that if the instance does not exist or is no longer running, we must return (\"\", cloudprovider.InstanceNotFound)\n// (Implementer Note): This is used by kubelet. Kubelet will label the node. Real log from kubelet:\n//\n//\tAdding node label from cloud provider: beta.kubernetes.io/instance-type=[value]\nfunc (az *Cloud) InstanceType(ctx context.Context, name types.NodeName) (string, error) {\n\t// Returns \"\" for unmanaged nodes because azure cloud provider couldn't fetch information for them.\n\tunmanaged, err := az.IsNodeUnmanaged(string(name))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif unmanaged {\n\t\tklog.V(4).Infof(\"InstanceType: omitting unmanaged node %q\", name)\n\t\treturn \"\", nil\n\t}\n\n\tif az.UseInstanceMetadata {\n\t\tmetadata, err := az.metadata.GetMetadata(azcache.CacheReadTypeDefault)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tif metadata.Compute == nil {\n\t\t\treturn \"\", fmt.Errorf(\"failure of getting instance metadata\")\n\t\t}\n\n\t\tisLocalInstance, err := az.isCurrentInstance(name, metadata.Compute.Name)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif !isLocalInstance {\n\t\t\tif az.VMSet != nil {\n\t\t\t\treturn az.VMSet.GetInstanceTypeByNodeName(string(name))\n\t\t\t}\n\n\t\t\t// vmSet == nil indicates credentials are not provided.\n\t\t\treturn \"\", fmt.Errorf(\"no credentials provided for Azure cloud provider\")\n\t\t}\n\n\t\tif metadata.Compute.VMSize != \"\" {\n\t\t\treturn metadata.Compute.VMSize, nil\n\t\t}\n\t}\n\n\treturn az.VMSet.GetInstanceTypeByNodeName(string(name))\n}","line":{"from":369,"to":414}} {"id":100033168,"name":"AddSSHKeyToAllInstances","signature":"func (az *Cloud) AddSSHKeyToAllInstances(ctx context.Context, user string, keyData []byte) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_instances.go","code":"// AddSSHKeyToAllInstances adds an SSH public key as a legal identity for all instances\n// expected format for the key is standard ssh-keygen format: \u003cprotocol\u003e \u003cblob\u003e\nfunc (az *Cloud) AddSSHKeyToAllInstances(ctx context.Context, user string, keyData []byte) error {\n\treturn cloudprovider.NotImplemented\n}","line":{"from":416,"to":420}} {"id":100033169,"name":"CurrentNodeName","signature":"func (az *Cloud) CurrentNodeName(ctx context.Context, hostname string) (types.NodeName, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_instances.go","code":"// CurrentNodeName returns the name of the node we are currently running on.\n// On Azure this is the hostname, so we just return the hostname.\nfunc (az *Cloud) CurrentNodeName(ctx context.Context, hostname string) (types.NodeName, error) {\n\treturn types.NodeName(hostname), nil\n}","line":{"from":422,"to":426}} {"id":100033170,"name":"mapNodeNameToVMName","signature":"func mapNodeNameToVMName(nodeName types.NodeName) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_instances.go","code":"// mapNodeNameToVMName maps a k8s NodeName to an Azure VM Name\n// This is a simple string cast.\nfunc mapNodeNameToVMName(nodeName types.NodeName) string {\n\treturn string(nodeName)\n}","line":{"from":428,"to":432}} {"id":100033171,"name":"GetLoadBalancer","signature":"func (az *Cloud) GetLoadBalancer(ctx context.Context, clusterName string, service *v1.Service) (status *v1.LoadBalancerStatus, exists bool, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"// GetLoadBalancer returns whether the specified load balancer and its components exist, and\n// if so, what its status is.\nfunc (az *Cloud) GetLoadBalancer(ctx context.Context, clusterName string, service *v1.Service) (status *v1.LoadBalancerStatus, exists bool, err error) {\n\t// Since public IP is not a part of the load balancer on Azure,\n\t// there is a chance that we could orphan public IP resources while we delete the load blanacer (kubernetes/kubernetes#80571).\n\t// We need to make sure the existence of the load balancer depends on the load balancer resource and public IP resource on Azure.\n\texistsPip := func() bool {\n\t\tpipName, _, err := az.determinePublicIPName(clusterName, service)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\tpipResourceGroup := az.getPublicIPAddressResourceGroup(service)\n\t\t_, existsPip, err := az.getPublicIPAddress(pipResourceGroup, pipName)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\treturn existsPip\n\t}()\n\n\t_, status, existsLb, err := az.getServiceLoadBalancer(service, clusterName, nil, false)\n\tif err != nil {\n\t\treturn nil, existsPip, err\n\t}\n\n\t// Return exists = false only if the load balancer and the public IP are not found on Azure\n\tif !existsLb \u0026\u0026 !existsPip {\n\t\tserviceName := getServiceName(service)\n\t\tklog.V(5).Infof(\"getloadbalancer (cluster:%s) (service:%s) - doesn't exist\", clusterName, serviceName)\n\t\treturn nil, false, nil\n\t}\n\n\t// Return exists = true if either the load balancer or the public IP (or both) exists\n\treturn status, true, nil\n}","line":{"from":128,"to":161}} {"id":100033172,"name":"getPublicIPDomainNameLabel","signature":"func getPublicIPDomainNameLabel(service *v1.Service) (string, bool)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func getPublicIPDomainNameLabel(service *v1.Service) (string, bool) {\n\tif labelName, found := service.Annotations[ServiceAnnotationDNSLabelName]; found {\n\t\treturn labelName, found\n\t}\n\treturn \"\", false\n}","line":{"from":163,"to":168}} {"id":100033173,"name":"EnsureLoadBalancer","signature":"func (az *Cloud) EnsureLoadBalancer(ctx context.Context, clusterName string, service *v1.Service, nodes []*v1.Node) (*v1.LoadBalancerStatus, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"// EnsureLoadBalancer creates a new load balancer 'name', or updates the existing one. Returns the status of the balancer\nfunc (az *Cloud) EnsureLoadBalancer(ctx context.Context, clusterName string, service *v1.Service, nodes []*v1.Node) (*v1.LoadBalancerStatus, error) {\n\t// When a client updates the internal load balancer annotation,\n\t// the service may be switched from an internal LB to a public one, or vise versa.\n\t// Here we'll firstly ensure service do not lie in the opposite LB.\n\tserviceName := getServiceName(service)\n\tklog.V(5).Infof(\"ensureloadbalancer(%s): START clusterName=%q\", serviceName, clusterName)\n\n\tmc := metrics.NewMetricContext(\"services\", \"ensure_loadbalancer\", az.ResourceGroup, az.SubscriptionID, serviceName)\n\tisOperationSucceeded := false\n\tdefer func() {\n\t\tmc.ObserveOperationWithResult(isOperationSucceeded)\n\t}()\n\n\tlb, err := az.reconcileLoadBalancer(clusterName, service, nodes, true /* wantLb */)\n\tif err != nil {\n\t\tklog.Errorf(\"reconcileLoadBalancer(%s) failed: %v\", serviceName, err)\n\t\treturn nil, err\n\t}\n\n\tlbStatus, err := az.getServiceLoadBalancerStatus(service, lb)\n\tif err != nil {\n\t\tklog.Errorf(\"getServiceLoadBalancerStatus(%s) failed: %v\", serviceName, err)\n\t\tif err != cloudprovider.InstanceNotFound {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tvar serviceIP *string\n\tif lbStatus != nil \u0026\u0026 len(lbStatus.Ingress) \u003e 0 {\n\t\tserviceIP = \u0026lbStatus.Ingress[0].IP\n\t}\n\tklog.V(2).Infof(\"EnsureLoadBalancer: reconciling security group for service %q with IP %q, wantLb = true\", serviceName, logSafe(serviceIP))\n\tif _, err := az.reconcileSecurityGroup(clusterName, service, serviceIP, true /* wantLb */); err != nil {\n\t\tklog.Errorf(\"reconcileSecurityGroup(%s) failed: %#v\", serviceName, err)\n\t\treturn nil, err\n\t}\n\n\tupdateService := updateServiceLoadBalancerIP(service, pointer.StringDeref(serviceIP, \"\"))\n\tflippedService := flipServiceInternalAnnotation(updateService)\n\tif _, err := az.reconcileLoadBalancer(clusterName, flippedService, nil, false /* wantLb */); err != nil {\n\t\tklog.Errorf(\"reconcileLoadBalancer(%s) failed: %#v\", serviceName, err)\n\t\treturn nil, err\n\t}\n\n\t// lb is not reused here because the ETAG may be changed in above operations, hence reconcilePublicIP() would get lb again from cache.\n\tklog.V(2).Infof(\"EnsureLoadBalancer: reconciling pip\")\n\tif _, err := az.reconcilePublicIP(clusterName, updateService, pointer.StringDeref(lb.Name, \"\"), true /* wantLb */); err != nil {\n\t\tklog.Errorf(\"reconcilePublicIP(%s) failed: %#v\", serviceName, err)\n\t\treturn nil, err\n\t}\n\n\tisOperationSucceeded = true\n\treturn lbStatus, nil\n}","line":{"from":170,"to":224}} {"id":100033174,"name":"UpdateLoadBalancer","signature":"func (az *Cloud) UpdateLoadBalancer(ctx context.Context, clusterName string, service *v1.Service, nodes []*v1.Node) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"// UpdateLoadBalancer updates hosts under the specified load balancer.\nfunc (az *Cloud) UpdateLoadBalancer(ctx context.Context, clusterName string, service *v1.Service, nodes []*v1.Node) error {\n\tif !az.shouldUpdateLoadBalancer(clusterName, service) {\n\t\tklog.V(2).Infof(\"UpdateLoadBalancer: skipping service %s because it is either being deleted or does not exist anymore\", service.Name)\n\t\treturn nil\n\t}\n\t_, err := az.EnsureLoadBalancer(ctx, clusterName, service, nodes)\n\treturn err\n}","line":{"from":226,"to":234}} {"id":100033175,"name":"EnsureLoadBalancerDeleted","signature":"func (az *Cloud) EnsureLoadBalancerDeleted(ctx context.Context, clusterName string, service *v1.Service) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"// EnsureLoadBalancerDeleted deletes the specified load balancer if it\n// exists, returning nil if the load balancer specified either didn't exist or\n// was successfully deleted.\n// This construction is useful because many cloud providers' load balancers\n// have multiple underlying components, meaning a Get could say that the LB\n// doesn't exist even if some part of it is still laying around.\nfunc (az *Cloud) EnsureLoadBalancerDeleted(ctx context.Context, clusterName string, service *v1.Service) error {\n\tisInternal := requiresInternalLoadBalancer(service)\n\tserviceName := getServiceName(service)\n\tklog.V(5).Infof(\"Delete service (%s): START clusterName=%q\", serviceName, clusterName)\n\n\tmc := metrics.NewMetricContext(\"services\", \"ensure_loadbalancer_deleted\", az.ResourceGroup, az.SubscriptionID, serviceName)\n\tisOperationSucceeded := false\n\tdefer func() {\n\t\tmc.ObserveOperationWithResult(isOperationSucceeded)\n\t}()\n\n\tserviceIPToCleanup, err := az.findServiceIPAddress(ctx, clusterName, service, isInternal)\n\tif err != nil \u0026\u0026 !retry.HasStatusForbiddenOrIgnoredError(err) {\n\t\treturn err\n\t}\n\n\tklog.V(2).Infof(\"EnsureLoadBalancerDeleted: reconciling security group for service %q with IP %q, wantLb = false\", serviceName, serviceIPToCleanup)\n\tif _, err := az.reconcileSecurityGroup(clusterName, service, \u0026serviceIPToCleanup, false /* wantLb */); err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := az.reconcileLoadBalancer(clusterName, service, nil, false /* wantLb */); err != nil \u0026\u0026 !retry.HasStatusForbiddenOrIgnoredError(err) {\n\t\treturn err\n\t}\n\n\tif _, err := az.reconcilePublicIP(clusterName, service, \"\", false /* wantLb */); err != nil {\n\t\treturn err\n\t}\n\n\tklog.V(2).Infof(\"Delete service (%s): FINISH\", serviceName)\n\tisOperationSucceeded = true\n\n\treturn nil\n}","line":{"from":236,"to":275}} {"id":100033176,"name":"GetLoadBalancerName","signature":"func (az *Cloud) GetLoadBalancerName(ctx context.Context, clusterName string, service *v1.Service) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"// GetLoadBalancerName returns the LoadBalancer name.\nfunc (az *Cloud) GetLoadBalancerName(ctx context.Context, clusterName string, service *v1.Service) string {\n\treturn cloudprovider.DefaultLoadBalancerName(service)\n}","line":{"from":277,"to":280}} {"id":100033177,"name":"getLoadBalancerResourceGroup","signature":"func (az *Cloud) getLoadBalancerResourceGroup() string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func (az *Cloud) getLoadBalancerResourceGroup() string {\n\tif az.LoadBalancerResourceGroup != \"\" {\n\t\treturn az.LoadBalancerResourceGroup\n\t}\n\n\treturn az.ResourceGroup\n}","line":{"from":282,"to":288}} {"id":100033178,"name":"cleanBackendpoolForPrimarySLB","signature":"func (az *Cloud) cleanBackendpoolForPrimarySLB(primarySLB *network.LoadBalancer, service *v1.Service, clusterName string) (*network.LoadBalancer, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"// cleanBackendpoolForPrimarySLB decouples the unwanted nodes from the standard load balancer.\n// This is needed because when migrating from single SLB to multiple SLBs, The existing\n// SLB's backend pool contains nodes from different agent pools, while we only want the\n// nodes from the primary agent pool to join the backend pool.\nfunc (az *Cloud) cleanBackendpoolForPrimarySLB(primarySLB *network.LoadBalancer, service *v1.Service, clusterName string) (*network.LoadBalancer, error) {\n\tlbBackendPoolName := getBackendPoolName(clusterName, service)\n\tlbResourceGroup := az.getLoadBalancerResourceGroup()\n\tlbBackendPoolID := az.getBackendPoolID(pointer.StringDeref(primarySLB.Name, \"\"), lbResourceGroup, lbBackendPoolName)\n\tnewBackendPools := make([]network.BackendAddressPool, 0)\n\tif primarySLB.LoadBalancerPropertiesFormat != nil \u0026\u0026 primarySLB.BackendAddressPools != nil {\n\t\tnewBackendPools = *primarySLB.BackendAddressPools\n\t}\n\tvmSetNameToBackendIPConfigurationsToBeDeleted := make(map[string][]network.InterfaceIPConfiguration)\n\tfor j, bp := range newBackendPools {\n\t\tif strings.EqualFold(pointer.StringDeref(bp.Name, \"\"), lbBackendPoolName) {\n\t\t\tklog.V(2).Infof(\"cleanBackendpoolForPrimarySLB: checking the backend pool %s from standard load balancer %s\", pointer.StringDeref(bp.Name, \"\"), pointer.StringDeref(primarySLB.Name, \"\"))\n\t\t\tif bp.BackendAddressPoolPropertiesFormat != nil \u0026\u0026 bp.BackendIPConfigurations != nil {\n\t\t\t\tfor i := len(*bp.BackendIPConfigurations) - 1; i \u003e= 0; i-- {\n\t\t\t\t\tipConf := (*bp.BackendIPConfigurations)[i]\n\t\t\t\t\tipConfigID := pointer.StringDeref(ipConf.ID, \"\")\n\t\t\t\t\t_, vmSetName, err := az.VMSet.GetNodeNameByIPConfigurationID(ipConfigID)\n\t\t\t\t\tif err != nil \u0026\u0026 !errors.Is(err, cloudprovider.InstanceNotFound) {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tprimaryVMSetName := az.VMSet.GetPrimaryVMSetName()\n\t\t\t\t\tif !strings.EqualFold(primaryVMSetName, vmSetName) \u0026\u0026 vmSetName != \"\" {\n\t\t\t\t\t\tklog.V(2).Infof(\"cleanBackendpoolForPrimarySLB: found unwanted vmSet %s, decouple it from the LB\", vmSetName)\n\t\t\t\t\t\t// construct a backendPool that only contains the IP config of the node to be deleted\n\t\t\t\t\t\tinterfaceIPConfigToBeDeleted := network.InterfaceIPConfiguration{\n\t\t\t\t\t\t\tID: pointer.String(ipConfigID),\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvmSetNameToBackendIPConfigurationsToBeDeleted[vmSetName] = append(vmSetNameToBackendIPConfigurationsToBeDeleted[vmSetName], interfaceIPConfigToBeDeleted)\n\t\t\t\t\t\t*bp.BackendIPConfigurations = append((*bp.BackendIPConfigurations)[:i], (*bp.BackendIPConfigurations)[i+1:]...)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tnewBackendPools[j] = bp\n\t\t\tbreak\n\t\t}\n\t}\n\tfor vmSetName, backendIPConfigurationsToBeDeleted := range vmSetNameToBackendIPConfigurationsToBeDeleted {\n\t\tbackendpoolToBeDeleted := \u0026[]network.BackendAddressPool{\n\t\t\t{\n\t\t\t\tID: pointer.String(lbBackendPoolID),\n\t\t\t\tBackendAddressPoolPropertiesFormat: \u0026network.BackendAddressPoolPropertiesFormat{\n\t\t\t\t\tBackendIPConfigurations: \u0026backendIPConfigurationsToBeDeleted,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\t// decouple the backendPool from the node\n\t\terr := az.VMSet.EnsureBackendPoolDeleted(service, lbBackendPoolID, vmSetName, backendpoolToBeDeleted, true)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tprimarySLB.BackendAddressPools = \u0026newBackendPools\n\t}\n\treturn primarySLB, nil\n}","line":{"from":290,"to":347}} {"id":100033179,"name":"getServiceLoadBalancer","signature":"func (az *Cloud) getServiceLoadBalancer(service *v1.Service, clusterName string, nodes []*v1.Node, wantLb bool) (lb *network.LoadBalancer, status *v1.LoadBalancerStatus, exists bool, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"// getServiceLoadBalancer gets the loadbalancer for the service if it already exists.\n// If wantLb is TRUE then -it selects a new load balancer.\n// In case the selected load balancer does not exist it returns network.LoadBalancer struct\n// with added metadata (such as name, location) and existsLB set to FALSE.\n// By default - cluster default LB is returned.\nfunc (az *Cloud) getServiceLoadBalancer(service *v1.Service, clusterName string, nodes []*v1.Node, wantLb bool) (lb *network.LoadBalancer, status *v1.LoadBalancerStatus, exists bool, err error) {\n\tisInternal := requiresInternalLoadBalancer(service)\n\tvar defaultLB *network.LoadBalancer\n\tprimaryVMSetName := az.VMSet.GetPrimaryVMSetName()\n\tdefaultLBName := az.getAzureLoadBalancerName(clusterName, primaryVMSetName, isInternal)\n\tuseMultipleSLBs := az.useStandardLoadBalancer() \u0026\u0026 az.EnableMultipleStandardLoadBalancers\n\n\texistingLBs, err := az.ListLB(service)\n\tif err != nil {\n\t\treturn nil, nil, false, err\n\t}\n\n\t// check if the service already has a load balancer\n\tfor i := range existingLBs {\n\t\texistingLB := existingLBs[i]\n\t\tif strings.EqualFold(pointer.StringDeref(existingLB.Name, \"\"), clusterName) \u0026\u0026 useMultipleSLBs {\n\t\t\tcleanedLB, err := az.cleanBackendpoolForPrimarySLB(\u0026existingLB, service, clusterName)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, false, err\n\t\t\t}\n\t\t\texistingLB = *cleanedLB\n\t\t}\n\t\tif strings.EqualFold(*existingLB.Name, defaultLBName) {\n\t\t\tdefaultLB = \u0026existingLB\n\t\t}\n\t\tif isInternalLoadBalancer(\u0026existingLB) != isInternal {\n\t\t\tcontinue\n\t\t}\n\t\tstatus, err = az.getServiceLoadBalancerStatus(service, \u0026existingLB)\n\t\tif err != nil {\n\t\t\treturn nil, nil, false, err\n\t\t}\n\t\tif status == nil {\n\t\t\t// service is not on this load balancer\n\t\t\tcontinue\n\t\t}\n\n\t\treturn \u0026existingLB, status, true, nil\n\t}\n\n\thasMode, _, _ := getServiceLoadBalancerMode(service)\n\tuseSingleSLB := az.useStandardLoadBalancer() \u0026\u0026 !az.EnableMultipleStandardLoadBalancers\n\tif useSingleSLB \u0026\u0026 hasMode {\n\t\tklog.Warningf(\"single standard load balancer doesn't work with annotation %q, would ignore it\", ServiceAnnotationLoadBalancerMode)\n\t}\n\n\t// Service does not have a load balancer, select one.\n\t// Single standard load balancer doesn't need this because\n\t// all backends nodes should be added to same LB.\n\tif wantLb \u0026\u0026 !useSingleSLB {\n\t\t// select new load balancer for service\n\t\tselectedLB, exists, err := az.selectLoadBalancer(clusterName, service, \u0026existingLBs, nodes)\n\t\tif err != nil {\n\t\t\treturn nil, nil, false, err\n\t\t}\n\n\t\treturn selectedLB, nil, exists, err\n\t}\n\n\t// create a default LB with meta data if not present\n\tif defaultLB == nil {\n\t\tdefaultLB = \u0026network.LoadBalancer{\n\t\t\tName: \u0026defaultLBName,\n\t\t\tLocation: \u0026az.Location,\n\t\t\tLoadBalancerPropertiesFormat: \u0026network.LoadBalancerPropertiesFormat{},\n\t\t}\n\t\tif az.useStandardLoadBalancer() {\n\t\t\tdefaultLB.Sku = \u0026network.LoadBalancerSku{\n\t\t\t\tName: network.LoadBalancerSkuNameStandard,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn defaultLB, nil, false, nil\n}","line":{"from":349,"to":428}} {"id":100033180,"name":"selectLoadBalancer","signature":"func (az *Cloud) selectLoadBalancer(clusterName string, service *v1.Service, existingLBs *[]network.LoadBalancer, nodes []*v1.Node) (selectedLB *network.LoadBalancer, existsLb bool, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"// selectLoadBalancer selects load balancer for the service in the cluster.\n// The selection algorithm selects the load balancer which currently has\n// the minimum lb rules. If there are multiple LBs with same number of rules,\n// then selects the first one (sorted based on name).\nfunc (az *Cloud) selectLoadBalancer(clusterName string, service *v1.Service, existingLBs *[]network.LoadBalancer, nodes []*v1.Node) (selectedLB *network.LoadBalancer, existsLb bool, err error) {\n\tisInternal := requiresInternalLoadBalancer(service)\n\tserviceName := getServiceName(service)\n\tklog.V(2).Infof(\"selectLoadBalancer for service (%s): isInternal(%v) - start\", serviceName, isInternal)\n\tvmSetNames, err := az.VMSet.GetVMSetNames(service, nodes)\n\tif err != nil {\n\t\tklog.Errorf(\"az.selectLoadBalancer: cluster(%s) service(%s) isInternal(%t) - az.GetVMSetNames failed, err=(%v)\", clusterName, serviceName, isInternal, err)\n\t\treturn nil, false, err\n\t}\n\tklog.V(2).Infof(\"selectLoadBalancer: cluster(%s) service(%s) isInternal(%t) - vmSetNames %v\", clusterName, serviceName, isInternal, *vmSetNames)\n\n\tmapExistingLBs := map[string]network.LoadBalancer{}\n\tfor _, lb := range *existingLBs {\n\t\tmapExistingLBs[*lb.Name] = lb\n\t}\n\tselectedLBRuleCount := math.MaxInt32\n\tfor _, currASName := range *vmSetNames {\n\t\tcurrLBName := az.getAzureLoadBalancerName(clusterName, currASName, isInternal)\n\t\tlb, exists := mapExistingLBs[currLBName]\n\t\tif !exists {\n\t\t\t// select this LB as this is a new LB and will have minimum rules\n\t\t\t// create tmp lb struct to hold metadata for the new load-balancer\n\t\t\tvar loadBalancerSKU network.LoadBalancerSkuName\n\t\t\tif az.useStandardLoadBalancer() {\n\t\t\t\tloadBalancerSKU = network.LoadBalancerSkuNameStandard\n\t\t\t} else {\n\t\t\t\tloadBalancerSKU = network.LoadBalancerSkuNameBasic\n\t\t\t}\n\t\t\tselectedLB = \u0026network.LoadBalancer{\n\t\t\t\tName: \u0026currLBName,\n\t\t\t\tLocation: \u0026az.Location,\n\t\t\t\tSku: \u0026network.LoadBalancerSku{Name: loadBalancerSKU},\n\t\t\t\tLoadBalancerPropertiesFormat: \u0026network.LoadBalancerPropertiesFormat{},\n\t\t\t}\n\n\t\t\treturn selectedLB, false, nil\n\t\t}\n\n\t\tlbRules := *lb.LoadBalancingRules\n\t\tcurrLBRuleCount := 0\n\t\tif lbRules != nil {\n\t\t\tcurrLBRuleCount = len(lbRules)\n\t\t}\n\t\tif currLBRuleCount \u003c selectedLBRuleCount {\n\t\t\tselectedLBRuleCount = currLBRuleCount\n\t\t\tselectedLB = \u0026lb\n\t\t}\n\t}\n\n\tif selectedLB == nil {\n\t\terr = fmt.Errorf(\"selectLoadBalancer: cluster(%s) service(%s) isInternal(%t) - unable to find load balancer for selected VM sets %v\", clusterName, serviceName, isInternal, *vmSetNames)\n\t\tklog.Error(err)\n\t\treturn nil, false, err\n\t}\n\t// validate if the selected LB has not exceeded the MaximumLoadBalancerRuleCount\n\tif az.Config.MaximumLoadBalancerRuleCount != 0 \u0026\u0026 selectedLBRuleCount \u003e= az.Config.MaximumLoadBalancerRuleCount {\n\t\terr = fmt.Errorf(\"selectLoadBalancer: cluster(%s) service(%s) isInternal(%t) - all available load balancers have exceeded maximum rule limit %d, vmSetNames (%v)\", clusterName, serviceName, isInternal, selectedLBRuleCount, *vmSetNames)\n\t\tklog.Error(err)\n\t\treturn selectedLB, existsLb, err\n\t}\n\n\treturn selectedLB, existsLb, nil\n}","line":{"from":430,"to":496}} {"id":100033181,"name":"getServiceLoadBalancerStatus","signature":"func (az *Cloud) getServiceLoadBalancerStatus(service *v1.Service, lb *network.LoadBalancer) (status *v1.LoadBalancerStatus, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func (az *Cloud) getServiceLoadBalancerStatus(service *v1.Service, lb *network.LoadBalancer) (status *v1.LoadBalancerStatus, err error) {\n\tif lb == nil {\n\t\tklog.V(10).Info(\"getServiceLoadBalancerStatus: lb is nil\")\n\t\treturn nil, nil\n\t}\n\tif lb.FrontendIPConfigurations == nil || *lb.FrontendIPConfigurations == nil {\n\t\tklog.V(10).Info(\"getServiceLoadBalancerStatus: lb.FrontendIPConfigurations is nil\")\n\t\treturn nil, nil\n\t}\n\tisInternal := requiresInternalLoadBalancer(service)\n\tserviceName := getServiceName(service)\n\tfor _, ipConfiguration := range *lb.FrontendIPConfigurations {\n\t\towns, isPrimaryService, err := az.serviceOwnsFrontendIP(ipConfiguration, service)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"get(%s): lb(%s) - failed to filter frontend IP configs with error: %v\", serviceName, pointer.StringDeref(lb.Name, \"\"), err)\n\t\t}\n\t\tif owns {\n\t\t\tklog.V(2).Infof(\"get(%s): lb(%s) - found frontend IP config, primary service: %v\", serviceName, pointer.StringDeref(lb.Name, \"\"), isPrimaryService)\n\n\t\t\tvar lbIP *string\n\t\t\tif isInternal {\n\t\t\t\tlbIP = ipConfiguration.PrivateIPAddress\n\t\t\t} else {\n\t\t\t\tif ipConfiguration.PublicIPAddress == nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"get(%s): lb(%s) - failed to get LB PublicIPAddress is Nil\", serviceName, *lb.Name)\n\t\t\t\t}\n\t\t\t\tpipID := ipConfiguration.PublicIPAddress.ID\n\t\t\t\tif pipID == nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"get(%s): lb(%s) - failed to get LB PublicIPAddress ID is Nil\", serviceName, *lb.Name)\n\t\t\t\t}\n\t\t\t\tpipName, err := getLastSegment(*pipID, \"/\")\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"get(%s): lb(%s) - failed to get LB PublicIPAddress Name from ID(%s)\", serviceName, *lb.Name, *pipID)\n\t\t\t\t}\n\t\t\t\tpip, existsPip, err := az.getPublicIPAddress(az.getPublicIPAddressResourceGroup(service), pipName)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif existsPip {\n\t\t\t\t\tlbIP = pip.IPAddress\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tklog.V(2).Infof(\"getServiceLoadBalancerStatus gets ingress IP %q from frontendIPConfiguration %q for service %q\", pointer.StringDeref(lbIP, \"\"), pointer.StringDeref(ipConfiguration.Name, \"\"), serviceName)\n\t\t\treturn \u0026v1.LoadBalancerStatus{Ingress: []v1.LoadBalancerIngress{{IP: pointer.StringDeref(lbIP, \"\")}}}, nil\n\t\t}\n\t}\n\n\treturn nil, nil\n}","line":{"from":498,"to":547}} {"id":100033182,"name":"determinePublicIPName","signature":"func (az *Cloud) determinePublicIPName(clusterName string, service *v1.Service) (string, bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func (az *Cloud) determinePublicIPName(clusterName string, service *v1.Service) (string, bool, error) {\n\tvar shouldPIPExisted bool\n\tif name, found := service.Annotations[ServiceAnnotationPIPName]; found \u0026\u0026 name != \"\" {\n\t\tshouldPIPExisted = true\n\t\treturn name, shouldPIPExisted, nil\n\t}\n\n\tpipResourceGroup := az.getPublicIPAddressResourceGroup(service)\n\tloadBalancerIP := service.Spec.LoadBalancerIP\n\n\t// Assume that the service without loadBalancerIP set is a primary service.\n\t// If a secondary service doesn't set the loadBalancerIP, it is not allowed to share the IP.\n\tif len(loadBalancerIP) == 0 {\n\t\treturn az.getPublicIPName(clusterName, service), shouldPIPExisted, nil\n\t}\n\n\t// For the services with loadBalancerIP set, an existing public IP is required, primary\n\t// or secondary, or a public IP not found error would be reported.\n\tpip, err := az.findMatchedPIPByLoadBalancerIP(service, loadBalancerIP, pipResourceGroup)\n\tif err != nil {\n\t\treturn \"\", shouldPIPExisted, err\n\t}\n\n\tif pip != nil \u0026\u0026 pip.Name != nil {\n\t\treturn *pip.Name, shouldPIPExisted, nil\n\t}\n\n\treturn \"\", shouldPIPExisted, fmt.Errorf(\"user supplied IP Address %s was not found in resource group %s\", loadBalancerIP, pipResourceGroup)\n}","line":{"from":549,"to":577}} {"id":100033183,"name":"findMatchedPIPByLoadBalancerIP","signature":"func (az *Cloud) findMatchedPIPByLoadBalancerIP(service *v1.Service, loadBalancerIP, pipResourceGroup string) (*network.PublicIPAddress, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func (az *Cloud) findMatchedPIPByLoadBalancerIP(service *v1.Service, loadBalancerIP, pipResourceGroup string) (*network.PublicIPAddress, error) {\n\tpips, err := az.ListPIP(service, pipResourceGroup)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, pip := range pips {\n\t\tif pip.PublicIPAddressPropertiesFormat.IPAddress != nil \u0026\u0026\n\t\t\t*pip.PublicIPAddressPropertiesFormat.IPAddress == loadBalancerIP {\n\t\t\treturn \u0026pip, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"findMatchedPIPByLoadBalancerIP: cannot find public IP with IP address %s in resource group %s\", loadBalancerIP, pipResourceGroup)\n}","line":{"from":579,"to":593}} {"id":100033184,"name":"flipServiceInternalAnnotation","signature":"func flipServiceInternalAnnotation(service *v1.Service) *v1.Service","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func flipServiceInternalAnnotation(service *v1.Service) *v1.Service {\n\tcopyService := service.DeepCopy()\n\tif copyService.Annotations == nil {\n\t\tcopyService.Annotations = map[string]string{}\n\t}\n\tif v, ok := copyService.Annotations[ServiceAnnotationLoadBalancerInternal]; ok \u0026\u0026 v == \"true\" {\n\t\t// If it is internal now, we make it external by remove the annotation\n\t\tdelete(copyService.Annotations, ServiceAnnotationLoadBalancerInternal)\n\t} else {\n\t\t// If it is external now, we make it internal\n\t\tcopyService.Annotations[ServiceAnnotationLoadBalancerInternal] = \"true\"\n\t}\n\treturn copyService\n}","line":{"from":595,"to":608}} {"id":100033185,"name":"updateServiceLoadBalancerIP","signature":"func updateServiceLoadBalancerIP(service *v1.Service, serviceIP string) *v1.Service","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func updateServiceLoadBalancerIP(service *v1.Service, serviceIP string) *v1.Service {\n\tcopyService := service.DeepCopy()\n\tif len(serviceIP) \u003e 0 \u0026\u0026 copyService != nil {\n\t\tcopyService.Spec.LoadBalancerIP = serviceIP\n\t}\n\treturn copyService\n}","line":{"from":610,"to":616}} {"id":100033186,"name":"findServiceIPAddress","signature":"func (az *Cloud) findServiceIPAddress(ctx context.Context, clusterName string, service *v1.Service, isInternalLb bool) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func (az *Cloud) findServiceIPAddress(ctx context.Context, clusterName string, service *v1.Service, isInternalLb bool) (string, error) {\n\tif len(service.Spec.LoadBalancerIP) \u003e 0 {\n\t\treturn service.Spec.LoadBalancerIP, nil\n\t}\n\n\tif len(service.Status.LoadBalancer.Ingress) \u003e 0 \u0026\u0026 len(service.Status.LoadBalancer.Ingress[0].IP) \u003e 0 {\n\t\treturn service.Status.LoadBalancer.Ingress[0].IP, nil\n\t}\n\n\t_, lbStatus, existsLb, err := az.getServiceLoadBalancer(service, clusterName, nil, false)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif !existsLb {\n\t\tklog.V(2).Infof(\"Expected to find an IP address for service %s but did not. Assuming it has been removed\", service.Name)\n\t\treturn \"\", nil\n\t}\n\tif len(lbStatus.Ingress) \u003c 1 {\n\t\tklog.V(2).Infof(\"Expected to find an IP address for service %s but it had no ingresses. Assuming it has been removed\", service.Name)\n\t\treturn \"\", nil\n\t}\n\n\treturn lbStatus.Ingress[0].IP, nil\n}","line":{"from":618,"to":641}} {"id":100033187,"name":"ensurePublicIPExists","signature":"func (az *Cloud) ensurePublicIPExists(service *v1.Service, pipName string, domainNameLabel, clusterName string, shouldPIPExisted, foundDNSLabelAnnotation bool) (*network.PublicIPAddress, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func (az *Cloud) ensurePublicIPExists(service *v1.Service, pipName string, domainNameLabel, clusterName string, shouldPIPExisted, foundDNSLabelAnnotation bool) (*network.PublicIPAddress, error) {\n\tpipResourceGroup := az.getPublicIPAddressResourceGroup(service)\n\tpip, existsPip, err := az.getPublicIPAddress(pipResourceGroup, pipName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tserviceName := getServiceName(service)\n\n\tvar changed bool\n\tif existsPip {\n\t\t// ensure that the service tag is good for managed pips\n\t\towns, isUserAssignedPIP := serviceOwnsPublicIP(service, \u0026pip, clusterName)\n\t\tif owns \u0026\u0026 !isUserAssignedPIP {\n\t\t\tchanged, err = bindServicesToPIP(\u0026pip, []string{serviceName}, false)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\tif pip.Tags == nil {\n\t\t\tpip.Tags = make(map[string]*string)\n\t\t}\n\n\t\t// return if pip exist and dns label is the same\n\t\tif strings.EqualFold(getDomainNameLabel(\u0026pip), domainNameLabel) {\n\t\t\tif existingServiceName, ok := pip.Tags[serviceUsingDNSKey]; ok \u0026\u0026\n\t\t\t\tstrings.EqualFold(*existingServiceName, serviceName) {\n\t\t\t\tklog.V(6).Infof(\"ensurePublicIPExists for service(%s): pip(%s) - \"+\n\t\t\t\t\t\"the service is using the DNS label on the public IP\", serviceName, pipName)\n\n\t\t\t\tvar rerr *retry.Error\n\t\t\t\tif changed {\n\t\t\t\t\tklog.V(2).Infof(\"ensurePublicIPExists: updating the PIP %s for the incoming service %s\", pipName, serviceName)\n\t\t\t\t\terr = az.CreateOrUpdatePIP(service, pipResourceGroup, pip)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\n\t\t\t\t\tctx, cancel := getContextWithCancel()\n\t\t\t\t\tdefer cancel()\n\t\t\t\t\tpip, rerr = az.PublicIPAddressesClient.Get(ctx, pipResourceGroup, *pip.Name, \"\")\n\t\t\t\t\tif rerr != nil {\n\t\t\t\t\t\treturn nil, rerr.Error()\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn \u0026pip, nil\n\t\t\t}\n\t\t}\n\n\t\tklog.V(2).Infof(\"ensurePublicIPExists for service(%s): pip(%s) - updating\", serviceName, *pip.Name)\n\t\tif pip.PublicIPAddressPropertiesFormat == nil {\n\t\t\tpip.PublicIPAddressPropertiesFormat = \u0026network.PublicIPAddressPropertiesFormat{\n\t\t\t\tPublicIPAllocationMethod: network.Static,\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif shouldPIPExisted {\n\t\t\treturn nil, fmt.Errorf(\"PublicIP from annotation azure-pip-name=%s for service %s doesn't exist\", pipName, serviceName)\n\t\t}\n\t\tpip.Name = pointer.String(pipName)\n\t\tpip.Location = pointer.String(az.Location)\n\t\tpip.PublicIPAddressPropertiesFormat = \u0026network.PublicIPAddressPropertiesFormat{\n\t\t\tPublicIPAllocationMethod: network.Static,\n\t\t\tIPTags: getServiceIPTagRequestForPublicIP(service).IPTags,\n\t\t}\n\t\tpip.Tags = map[string]*string{\n\t\t\tserviceTagKey: pointer.String(\"\"),\n\t\t\tclusterNameKey: \u0026clusterName,\n\t\t}\n\t\tif _, err = bindServicesToPIP(\u0026pip, []string{serviceName}, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif az.useStandardLoadBalancer() {\n\t\t\tpip.Sku = \u0026network.PublicIPAddressSku{\n\t\t\t\tName: network.PublicIPAddressSkuNameStandard,\n\t\t\t}\n\t\t}\n\t\tklog.V(2).Infof(\"ensurePublicIPExists for service(%s): pip(%s) - creating\", serviceName, *pip.Name)\n\t}\n\tif foundDNSLabelAnnotation {\n\t\tif existingServiceName, ok := pip.Tags[serviceUsingDNSKey]; ok {\n\t\t\tif !strings.EqualFold(pointer.StringDeref(existingServiceName, \"\"), serviceName) {\n\t\t\t\treturn nil, fmt.Errorf(\"ensurePublicIPExists for service(%s): pip(%s) - there is an existing service %s consuming the DNS label on the public IP, so the service cannot set the DNS label annotation with this value\", serviceName, pipName, *existingServiceName)\n\t\t\t}\n\t\t}\n\n\t\tif len(domainNameLabel) == 0 {\n\t\t\tpip.PublicIPAddressPropertiesFormat.DNSSettings = nil\n\t\t} else {\n\t\t\tif pip.PublicIPAddressPropertiesFormat.DNSSettings == nil ||\n\t\t\t\tpip.PublicIPAddressPropertiesFormat.DNSSettings.DomainNameLabel == nil {\n\t\t\t\tklog.V(6).Infof(\"ensurePublicIPExists for service(%s): pip(%s) - no existing DNS label on the public IP, create one\", serviceName, pipName)\n\t\t\t\tpip.PublicIPAddressPropertiesFormat.DNSSettings = \u0026network.PublicIPAddressDNSSettings{\n\t\t\t\t\tDomainNameLabel: \u0026domainNameLabel,\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\texistingDNSLabel := pip.PublicIPAddressPropertiesFormat.DNSSettings.DomainNameLabel\n\t\t\t\tif !strings.EqualFold(pointer.StringDeref(existingDNSLabel, \"\"), domainNameLabel) {\n\t\t\t\t\treturn nil, fmt.Errorf(\"ensurePublicIPExists for service(%s): pip(%s) - there is an existing DNS label %s on the public IP\", serviceName, pipName, *existingDNSLabel)\n\t\t\t\t}\n\t\t\t}\n\t\t\tpip.Tags[serviceUsingDNSKey] = \u0026serviceName\n\t\t}\n\t}\n\n\t// use the same family as the clusterIP as we support IPv6 single stack as well\n\t// as dual-stack clusters\n\tipv6 := utilnet.IsIPv6String(service.Spec.ClusterIP)\n\tif ipv6 {\n\t\tpip.PublicIPAddressVersion = network.IPv6\n\t\tklog.V(2).Infof(\"service(%s): pip(%s) - creating as ipv6 for clusterIP:%v\", serviceName, *pip.Name, service.Spec.ClusterIP)\n\n\t\tpip.PublicIPAddressPropertiesFormat.PublicIPAllocationMethod = network.Dynamic\n\t\tif az.useStandardLoadBalancer() {\n\t\t\t// standard sku must have static allocation method for ipv6\n\t\t\tpip.PublicIPAddressPropertiesFormat.PublicIPAllocationMethod = network.Static\n\t\t}\n\t} else {\n\t\tpip.PublicIPAddressVersion = network.IPv4\n\t\tklog.V(2).Infof(\"service(%s): pip(%s) - creating as ipv4 for clusterIP:%v\", serviceName, *pip.Name, service.Spec.ClusterIP)\n\t}\n\n\tklog.V(2).Infof(\"CreateOrUpdatePIP(%s, %q): start\", pipResourceGroup, *pip.Name)\n\terr = az.CreateOrUpdatePIP(service, pipResourceGroup, pip)\n\tif err != nil {\n\t\tklog.V(2).Infof(\"ensure(%s) abort backoff: pip(%s)\", serviceName, *pip.Name)\n\t\treturn nil, err\n\t}\n\tklog.V(10).Infof(\"CreateOrUpdatePIP(%s, %q): end\", pipResourceGroup, *pip.Name)\n\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\tpip, rerr := az.PublicIPAddressesClient.Get(ctx, pipResourceGroup, *pip.Name, \"\")\n\tif rerr != nil {\n\t\treturn nil, rerr.Error()\n\t}\n\treturn \u0026pip, nil\n}","line":{"from":643,"to":783}} {"id":100033188,"name":"getServiceIPTagRequestForPublicIP","signature":"func getServiceIPTagRequestForPublicIP(service *v1.Service) serviceIPTagRequest","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"// Get the ip tag Request for the public ip from service annotations.\nfunc getServiceIPTagRequestForPublicIP(service *v1.Service) serviceIPTagRequest {\n\tif service != nil {\n\t\tif ipTagString, found := service.Annotations[ServiceAnnotationIPTagsForPublicIP]; found {\n\t\t\treturn serviceIPTagRequest{\n\t\t\t\tIPTagsRequestedByAnnotation: true,\n\t\t\t\tIPTags: convertIPTagMapToSlice(getIPTagMap(ipTagString)),\n\t\t\t}\n\t\t}\n\t}\n\n\treturn serviceIPTagRequest{\n\t\tIPTagsRequestedByAnnotation: false,\n\t\tIPTags: nil,\n\t}\n}","line":{"from":790,"to":805}} {"id":100033189,"name":"getIPTagMap","signature":"func getIPTagMap(ipTagString string) map[string]string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func getIPTagMap(ipTagString string) map[string]string {\n\toutputMap := make(map[string]string)\n\tcommaDelimitedPairs := strings.Split(strings.TrimSpace(ipTagString), \",\")\n\tfor _, commaDelimitedPair := range commaDelimitedPairs {\n\t\tsplitKeyValue := strings.Split(commaDelimitedPair, \"=\")\n\n\t\t// Include only valid pairs in the return value\n\t\t// Last Write wins.\n\t\tif len(splitKeyValue) == 2 {\n\t\t\ttagKey := strings.TrimSpace(splitKeyValue[0])\n\t\t\ttagValue := strings.TrimSpace(splitKeyValue[1])\n\n\t\t\toutputMap[tagKey] = tagValue\n\t\t}\n\t}\n\n\treturn outputMap\n}","line":{"from":807,"to":824}} {"id":100033190,"name":"sortIPTags","signature":"func sortIPTags(ipTags *[]network.IPTag)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func sortIPTags(ipTags *[]network.IPTag) {\n\tif ipTags != nil {\n\t\tsort.Slice(*ipTags, func(i, j int) bool {\n\t\t\tipTag := *ipTags\n\t\t\treturn pointer.StringDeref(ipTag[i].IPTagType, \"\") \u003c pointer.StringDeref(ipTag[j].IPTagType, \"\") ||\n\t\t\t\tpointer.StringDeref(ipTag[i].Tag, \"\") \u003c pointer.StringDeref(ipTag[j].Tag, \"\")\n\t\t})\n\t}\n}","line":{"from":826,"to":834}} {"id":100033191,"name":"areIPTagsEquivalent","signature":"func areIPTagsEquivalent(ipTags1 *[]network.IPTag, ipTags2 *[]network.IPTag) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func areIPTagsEquivalent(ipTags1 *[]network.IPTag, ipTags2 *[]network.IPTag) bool {\n\tsortIPTags(ipTags1)\n\tsortIPTags(ipTags2)\n\n\tif ipTags1 == nil {\n\t\tipTags1 = \u0026[]network.IPTag{}\n\t}\n\n\tif ipTags2 == nil {\n\t\tipTags2 = \u0026[]network.IPTag{}\n\t}\n\n\treturn reflect.DeepEqual(ipTags1, ipTags2)\n}","line":{"from":836,"to":849}} {"id":100033192,"name":"convertIPTagMapToSlice","signature":"func convertIPTagMapToSlice(ipTagMap map[string]string) *[]network.IPTag","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func convertIPTagMapToSlice(ipTagMap map[string]string) *[]network.IPTag {\n\tif ipTagMap == nil {\n\t\treturn nil\n\t}\n\n\tif len(ipTagMap) == 0 {\n\t\treturn \u0026[]network.IPTag{}\n\t}\n\n\toutputTags := []network.IPTag{}\n\tfor k, v := range ipTagMap {\n\t\tipTag := network.IPTag{\n\t\t\tIPTagType: pointer.String(k),\n\t\t\tTag: pointer.String(v),\n\t\t}\n\t\toutputTags = append(outputTags, ipTag)\n\t}\n\n\treturn \u0026outputTags\n}","line":{"from":851,"to":870}} {"id":100033193,"name":"getDomainNameLabel","signature":"func getDomainNameLabel(pip *network.PublicIPAddress) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func getDomainNameLabel(pip *network.PublicIPAddress) string {\n\tif pip == nil || pip.PublicIPAddressPropertiesFormat == nil || pip.PublicIPAddressPropertiesFormat.DNSSettings == nil {\n\t\treturn \"\"\n\t}\n\treturn pointer.StringDeref(pip.PublicIPAddressPropertiesFormat.DNSSettings.DomainNameLabel, \"\")\n}","line":{"from":872,"to":877}} {"id":100033194,"name":"getIdleTimeout","signature":"func getIdleTimeout(s *v1.Service) (*int32, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func getIdleTimeout(s *v1.Service) (*int32, error) {\n\tconst (\n\t\tmin = 4\n\t\tmax = 30\n\t)\n\n\tval, ok := s.Annotations[ServiceAnnotationLoadBalancerIdleTimeout]\n\tif !ok {\n\t\t// Return a nil here as this will set the value to the azure default\n\t\treturn nil, nil\n\t}\n\n\terrInvalidTimeout := fmt.Errorf(\"idle timeout value must be a whole number representing minutes between %d and %d\", min, max)\n\tto, err := strconv.Atoi(val)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing idle timeout value: %v: %v\", err, errInvalidTimeout)\n\t}\n\tto32 := int32(to)\n\n\tif to32 \u003c min || to32 \u003e max {\n\t\treturn nil, errInvalidTimeout\n\t}\n\treturn \u0026to32, nil\n}","line":{"from":879,"to":902}} {"id":100033195,"name":"isFrontendIPChanged","signature":"func (az *Cloud) isFrontendIPChanged(clusterName string, config network.FrontendIPConfiguration, service *v1.Service, lbFrontendIPConfigName string) (bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func (az *Cloud) isFrontendIPChanged(clusterName string, config network.FrontendIPConfiguration, service *v1.Service, lbFrontendIPConfigName string) (bool, error) {\n\tisServiceOwnsFrontendIP, isPrimaryService, err := az.serviceOwnsFrontendIP(config, service)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif isServiceOwnsFrontendIP \u0026\u0026 isPrimaryService \u0026\u0026 !strings.EqualFold(pointer.StringDeref(config.Name, \"\"), lbFrontendIPConfigName) {\n\t\treturn true, nil\n\t}\n\tif !strings.EqualFold(pointer.StringDeref(config.Name, \"\"), lbFrontendIPConfigName) {\n\t\treturn false, nil\n\t}\n\tloadBalancerIP := service.Spec.LoadBalancerIP\n\tisInternal := requiresInternalLoadBalancer(service)\n\tif isInternal {\n\t\t// Judge subnet\n\t\tsubnetName := subnet(service)\n\t\tif subnetName != nil {\n\t\t\tsubnet, existsSubnet, err := az.getSubnet(az.VnetName, *subnetName)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tif !existsSubnet {\n\t\t\t\treturn false, fmt.Errorf(\"failed to get subnet\")\n\t\t\t}\n\t\t\tif config.Subnet != nil \u0026\u0026 !strings.EqualFold(pointer.StringDeref(config.Subnet.Name, \"\"), pointer.StringDeref(subnet.Name, \"\")) {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\t\tif loadBalancerIP == \"\" {\n\t\t\treturn config.PrivateIPAllocationMethod == network.Static, nil\n\t\t}\n\t\treturn config.PrivateIPAllocationMethod != network.Static || !strings.EqualFold(loadBalancerIP, pointer.StringDeref(config.PrivateIPAddress, \"\")), nil\n\t}\n\tpipName, _, err := az.determinePublicIPName(clusterName, service)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tpipResourceGroup := az.getPublicIPAddressResourceGroup(service)\n\tpip, existsPip, err := az.getPublicIPAddress(pipResourceGroup, pipName)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif !existsPip {\n\t\treturn true, nil\n\t}\n\treturn config.PublicIPAddress != nil \u0026\u0026 !strings.EqualFold(pointer.StringDeref(pip.ID, \"\"), pointer.StringDeref(config.PublicIPAddress.ID, \"\")), nil\n}","line":{"from":904,"to":950}} {"id":100033196,"name":"isFrontendIPConfigUnsafeToDelete","signature":"func (az *Cloud) isFrontendIPConfigUnsafeToDelete(","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"// isFrontendIPConfigUnsafeToDelete checks if a frontend IP config is safe to be deleted.\n// It is safe to be deleted if and only if there is no reference from other\n// loadBalancing resources, including loadBalancing rules, outbound rules, inbound NAT rules\n// and inbound NAT pools.\nfunc (az *Cloud) isFrontendIPConfigUnsafeToDelete(\n\tlb *network.LoadBalancer,\n\tservice *v1.Service,\n\tfipConfigID *string,\n) (bool, error) {\n\tif lb == nil || fipConfigID == nil || *fipConfigID == \"\" {\n\t\treturn false, fmt.Errorf(\"isFrontendIPConfigUnsafeToDelete: incorrect parameters\")\n\t}\n\n\tvar (\n\t\tlbRules []network.LoadBalancingRule\n\t\toutboundRules []network.OutboundRule\n\t\tinboundNatRules []network.InboundNatRule\n\t\tinboundNatPools []network.InboundNatPool\n\t\tunsafe bool\n\t)\n\n\tif lb.LoadBalancerPropertiesFormat != nil {\n\t\tif lb.LoadBalancingRules != nil {\n\t\t\tlbRules = *lb.LoadBalancingRules\n\t\t}\n\t\tif lb.OutboundRules != nil {\n\t\t\toutboundRules = *lb.OutboundRules\n\t\t}\n\t\tif lb.InboundNatRules != nil {\n\t\t\tinboundNatRules = *lb.InboundNatRules\n\t\t}\n\t\tif lb.InboundNatPools != nil {\n\t\t\tinboundNatPools = *lb.InboundNatPools\n\t\t}\n\t}\n\n\t// check if there are load balancing rules from other services\n\t// referencing this frontend IP configuration\n\tfor _, lbRule := range lbRules {\n\t\tif lbRule.LoadBalancingRulePropertiesFormat != nil \u0026\u0026\n\t\t\tlbRule.FrontendIPConfiguration != nil \u0026\u0026\n\t\t\tlbRule.FrontendIPConfiguration.ID != nil \u0026\u0026\n\t\t\tstrings.EqualFold(*lbRule.FrontendIPConfiguration.ID, *fipConfigID) {\n\t\t\tif !az.serviceOwnsRule(service, *lbRule.Name) {\n\t\t\t\twarningMsg := fmt.Sprintf(\"isFrontendIPConfigUnsafeToDelete: frontend IP configuration with ID %s on LB %s cannot be deleted because it is being referenced by load balancing rules of other services\", *fipConfigID, *lb.Name)\n\t\t\t\tklog.Warning(warningMsg)\n\t\t\t\taz.Event(service, v1.EventTypeWarning, \"DeletingFrontendIPConfiguration\", warningMsg)\n\t\t\t\tunsafe = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// check if there are outbound rules\n\t// referencing this frontend IP configuration\n\tfor _, outboundRule := range outboundRules {\n\t\tif outboundRule.OutboundRulePropertiesFormat != nil \u0026\u0026 outboundRule.FrontendIPConfigurations != nil {\n\t\t\toutboundRuleFIPConfigs := *outboundRule.FrontendIPConfigurations\n\t\t\tif found := findMatchedOutboundRuleFIPConfig(fipConfigID, outboundRuleFIPConfigs); found {\n\t\t\t\twarningMsg := fmt.Sprintf(\"isFrontendIPConfigUnsafeToDelete: frontend IP configuration with ID %s on LB %s cannot be deleted because it is being referenced by the outbound rule %s\", *fipConfigID, *lb.Name, *outboundRule.Name)\n\t\t\t\tklog.Warning(warningMsg)\n\t\t\t\taz.Event(service, v1.EventTypeWarning, \"DeletingFrontendIPConfiguration\", warningMsg)\n\t\t\t\tunsafe = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// check if there are inbound NAT rules\n\t// referencing this frontend IP configuration\n\tfor _, inboundNatRule := range inboundNatRules {\n\t\tif inboundNatRule.InboundNatRulePropertiesFormat != nil \u0026\u0026\n\t\t\tinboundNatRule.FrontendIPConfiguration != nil \u0026\u0026\n\t\t\tinboundNatRule.FrontendIPConfiguration.ID != nil \u0026\u0026\n\t\t\tstrings.EqualFold(*inboundNatRule.FrontendIPConfiguration.ID, *fipConfigID) {\n\t\t\twarningMsg := fmt.Sprintf(\"isFrontendIPConfigUnsafeToDelete: frontend IP configuration with ID %s on LB %s cannot be deleted because it is being referenced by the inbound NAT rule %s\", *fipConfigID, *lb.Name, *inboundNatRule.Name)\n\t\t\tklog.Warning(warningMsg)\n\t\t\taz.Event(service, v1.EventTypeWarning, \"DeletingFrontendIPConfiguration\", warningMsg)\n\t\t\tunsafe = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// check if there are inbound NAT pools\n\t// referencing this frontend IP configuration\n\tfor _, inboundNatPool := range inboundNatPools {\n\t\tif inboundNatPool.InboundNatPoolPropertiesFormat != nil \u0026\u0026\n\t\t\tinboundNatPool.FrontendIPConfiguration != nil \u0026\u0026\n\t\t\tinboundNatPool.FrontendIPConfiguration.ID != nil \u0026\u0026\n\t\t\tstrings.EqualFold(*inboundNatPool.FrontendIPConfiguration.ID, *fipConfigID) {\n\t\t\twarningMsg := fmt.Sprintf(\"isFrontendIPConfigUnsafeToDelete: frontend IP configuration with ID %s on LB %s cannot be deleted because it is being referenced by the inbound NAT pool %s\", *fipConfigID, *lb.Name, *inboundNatPool.Name)\n\t\t\tklog.Warning(warningMsg)\n\t\t\taz.Event(service, v1.EventTypeWarning, \"DeletingFrontendIPConfiguration\", warningMsg)\n\t\t\tunsafe = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn unsafe, nil\n}","line":{"from":952,"to":1051}} {"id":100033197,"name":"findMatchedOutboundRuleFIPConfig","signature":"func findMatchedOutboundRuleFIPConfig(fipConfigID *string, outboundRuleFIPConfigs []network.SubResource) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func findMatchedOutboundRuleFIPConfig(fipConfigID *string, outboundRuleFIPConfigs []network.SubResource) bool {\n\tvar found bool\n\tfor _, config := range outboundRuleFIPConfigs {\n\t\tif config.ID != nil \u0026\u0026 strings.EqualFold(*config.ID, *fipConfigID) {\n\t\t\tfound = true\n\t\t}\n\t}\n\treturn found\n}","line":{"from":1053,"to":1061}} {"id":100033198,"name":"findFrontendIPConfigOfService","signature":"func (az *Cloud) findFrontendIPConfigOfService(","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func (az *Cloud) findFrontendIPConfigOfService(\n\tfipConfigs *[]network.FrontendIPConfiguration,\n\tservice *v1.Service,\n) (*network.FrontendIPConfiguration, bool, error) {\n\tfor _, config := range *fipConfigs {\n\t\towns, isPrimaryService, err := az.serviceOwnsFrontendIP(config, service)\n\t\tif err != nil {\n\t\t\treturn nil, false, err\n\t\t}\n\t\tif owns {\n\t\t\treturn \u0026config, isPrimaryService, nil\n\t\t}\n\t}\n\n\treturn nil, false, nil\n}","line":{"from":1063,"to":1078}} {"id":100033199,"name":"reconcileLoadBalancer","signature":"func (az *Cloud) reconcileLoadBalancer(clusterName string, service *v1.Service, nodes []*v1.Node, wantLb bool) (*network.LoadBalancer, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"// reconcileLoadBalancer ensures load balancer exists and the frontend ip config is setup.\n// This also reconciles the Service's Ports with the LoadBalancer config.\n// This entails adding rules/probes for expected Ports and removing stale rules/ports.\n// nodes only used if wantLb is true\nfunc (az *Cloud) reconcileLoadBalancer(clusterName string, service *v1.Service, nodes []*v1.Node, wantLb bool) (*network.LoadBalancer, error) {\n\tisInternal := requiresInternalLoadBalancer(service)\n\tisBackendPoolPreConfigured := az.isBackendPoolPreConfigured(service)\n\tserviceName := getServiceName(service)\n\tklog.V(2).Infof(\"reconcileLoadBalancer for service(%s) - wantLb(%t): started\", serviceName, wantLb)\n\tlb, _, _, err := az.getServiceLoadBalancer(service, clusterName, nodes, wantLb)\n\tif err != nil {\n\t\tklog.Errorf(\"reconcileLoadBalancer: failed to get load balancer for service %q, error: %v\", serviceName, err)\n\t\treturn nil, err\n\t}\n\tlbName := *lb.Name\n\tlbResourceGroup := az.getLoadBalancerResourceGroup()\n\tklog.V(2).Infof(\"reconcileLoadBalancer for service(%s): lb(%s/%s) wantLb(%t) resolved load balancer name\", serviceName, lbResourceGroup, lbName, wantLb)\n\tdefaultLBFrontendIPConfigName := az.getDefaultFrontendIPConfigName(service)\n\tdefaultLBFrontendIPConfigID := az.getFrontendIPConfigID(lbName, lbResourceGroup, defaultLBFrontendIPConfigName)\n\tlbBackendPoolName := getBackendPoolName(clusterName, service)\n\tlbBackendPoolID := az.getBackendPoolID(lbName, lbResourceGroup, lbBackendPoolName)\n\n\tlbIdleTimeout, err := getIdleTimeout(service)\n\tif wantLb \u0026\u0026 err != nil {\n\t\treturn nil, err\n\t}\n\n\tdirtyLb := false\n\n\t// Ensure LoadBalancer's Backend Pool Configuration\n\tif wantLb {\n\t\tnewBackendPools := []network.BackendAddressPool{}\n\t\tif lb.BackendAddressPools != nil {\n\t\t\tnewBackendPools = *lb.BackendAddressPools\n\t\t}\n\n\t\tfoundBackendPool := false\n\t\tfor _, bp := range newBackendPools {\n\t\t\tif strings.EqualFold(*bp.Name, lbBackendPoolName) {\n\t\t\t\tklog.V(10).Infof(\"reconcileLoadBalancer for service (%s)(%t): lb backendpool - found wanted backendpool. not adding anything\", serviceName, wantLb)\n\t\t\t\tfoundBackendPool = true\n\n\t\t\t\tvar backendIPConfigurationsToBeDeleted []network.InterfaceIPConfiguration\n\t\t\t\tif bp.BackendAddressPoolPropertiesFormat != nil \u0026\u0026 bp.BackendIPConfigurations != nil {\n\t\t\t\t\tfor _, ipConf := range *bp.BackendIPConfigurations {\n\t\t\t\t\t\tipConfID := pointer.StringDeref(ipConf.ID, \"\")\n\t\t\t\t\t\tnodeName, _, err := az.VMSet.GetNodeNameByIPConfigurationID(ipConfID)\n\t\t\t\t\t\tif err != nil \u0026\u0026 !errors.Is(err, cloudprovider.InstanceNotFound) {\n\t\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// If the node appears in the local cache of nodes to exclude,\n\t\t\t\t\t\t// delete it from the load balancer backend pool.\n\t\t\t\t\t\tshouldExcludeLoadBalancer, err := az.ShouldNodeExcludedFromLoadBalancer(nodeName)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tklog.Errorf(\"ShouldNodeExcludedFromLoadBalancer(%s) failed with error: %v\", nodeName, err)\n\t\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif shouldExcludeLoadBalancer {\n\t\t\t\t\t\t\tklog.V(2).Infof(\"reconcileLoadBalancer for service (%s)(%t): lb backendpool - found unwanted node %s, decouple it from the LB\", serviceName, wantLb, nodeName)\n\t\t\t\t\t\t\t// construct a backendPool that only contains the IP config of the node to be deleted\n\t\t\t\t\t\t\tbackendIPConfigurationsToBeDeleted = append(backendIPConfigurationsToBeDeleted, network.InterfaceIPConfiguration{ID: pointer.String(ipConfID)})\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif len(backendIPConfigurationsToBeDeleted) \u003e 0 {\n\t\t\t\t\t\tbackendpoolToBeDeleted := \u0026[]network.BackendAddressPool{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tID: pointer.String(lbBackendPoolID),\n\t\t\t\t\t\t\t\tBackendAddressPoolPropertiesFormat: \u0026network.BackendAddressPoolPropertiesFormat{\n\t\t\t\t\t\t\t\t\tBackendIPConfigurations: \u0026backendIPConfigurationsToBeDeleted,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvmSetName := az.mapLoadBalancerNameToVMSet(lbName, clusterName)\n\t\t\t\t\t\t// decouple the backendPool from the node\n\t\t\t\t\t\terr = az.VMSet.EnsureBackendPoolDeleted(service, lbBackendPoolID, vmSetName, backendpoolToBeDeleted, false)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tklog.V(10).Infof(\"reconcileLoadBalancer for service (%s)(%t): lb backendpool - found other backendpool %s\", serviceName, wantLb, *bp.Name)\n\t\t\t}\n\t\t}\n\t\tif !foundBackendPool {\n\t\t\tif isBackendPoolPreConfigured {\n\t\t\t\tklog.V(2).Infof(\"reconcileLoadBalancer for service (%s)(%t): lb backendpool - PreConfiguredBackendPoolLoadBalancerTypes %s has been set but can not find corresponding backend pool, ignoring it\",\n\t\t\t\t\tserviceName,\n\t\t\t\t\twantLb,\n\t\t\t\t\taz.PreConfiguredBackendPoolLoadBalancerTypes)\n\t\t\t\tisBackendPoolPreConfigured = false\n\t\t\t}\n\n\t\t\tnewBackendPools = append(newBackendPools, network.BackendAddressPool{\n\t\t\t\tName: pointer.String(lbBackendPoolName),\n\t\t\t})\n\t\t\tklog.V(10).Infof(\"reconcileLoadBalancer for service (%s)(%t): lb backendpool - adding backendpool\", serviceName, wantLb)\n\n\t\t\tdirtyLb = true\n\t\t\tlb.BackendAddressPools = \u0026newBackendPools\n\t\t}\n\t}\n\n\t// Ensure LoadBalancer's Frontend IP Configurations\n\tdirtyConfigs := false\n\tnewConfigs := []network.FrontendIPConfiguration{}\n\tif lb.FrontendIPConfigurations != nil {\n\t\tnewConfigs = *lb.FrontendIPConfigurations\n\t}\n\n\tvar ownedFIPConfig *network.FrontendIPConfiguration\n\tif !wantLb {\n\t\tfor i := len(newConfigs) - 1; i \u003e= 0; i-- {\n\t\t\tconfig := newConfigs[i]\n\t\t\tisServiceOwnsFrontendIP, _, err := az.serviceOwnsFrontendIP(config, service)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif isServiceOwnsFrontendIP {\n\t\t\t\tunsafe, err := az.isFrontendIPConfigUnsafeToDelete(lb, service, config.ID)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\t// If the frontend IP configuration is not being referenced by:\n\t\t\t\t// 1. loadBalancing rules of other services with different ports;\n\t\t\t\t// 2. outbound rules;\n\t\t\t\t// 3. inbound NAT rules;\n\t\t\t\t// 4. inbound NAT pools,\n\t\t\t\t// do the deletion, or skip it.\n\t\t\t\tif !unsafe {\n\t\t\t\t\tvar configNameToBeDeleted string\n\t\t\t\t\tif newConfigs[i].Name != nil {\n\t\t\t\t\t\tconfigNameToBeDeleted = *newConfigs[i].Name\n\t\t\t\t\t\tklog.V(2).Infof(\"reconcileLoadBalancer for service (%s)(%t): lb frontendconfig(%s) - dropping\", serviceName, wantLb, configNameToBeDeleted)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tklog.V(2).Infof(\"reconcileLoadBalancer for service (%s)(%t): nil name of lb frontendconfig\", serviceName, wantLb)\n\t\t\t\t\t}\n\n\t\t\t\t\tnewConfigs = append(newConfigs[:i], newConfigs[i+1:]...)\n\t\t\t\t\tdirtyConfigs = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor i := len(newConfigs) - 1; i \u003e= 0; i-- {\n\t\t\tconfig := newConfigs[i]\n\t\t\tisFipChanged, err := az.isFrontendIPChanged(clusterName, config, service, defaultLBFrontendIPConfigName)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif isFipChanged {\n\t\t\t\tklog.V(2).Infof(\"reconcileLoadBalancer for service (%s)(%t): lb frontendconfig(%s) - dropping\", serviceName, wantLb, *config.Name)\n\t\t\t\tnewConfigs = append(newConfigs[:i], newConfigs[i+1:]...)\n\t\t\t\tdirtyConfigs = true\n\t\t\t}\n\t\t}\n\n\t\townedFIPConfig, _, err = az.findFrontendIPConfigOfService(\u0026newConfigs, service)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif ownedFIPConfig == nil {\n\t\t\tklog.V(4).Infof(\"ensure(%s): lb(%s) - creating a new frontend IP config\", serviceName, lbName)\n\n\t\t\t// construct FrontendIPConfigurationPropertiesFormat\n\t\t\tvar fipConfigurationProperties *network.FrontendIPConfigurationPropertiesFormat\n\t\t\tif isInternal {\n\t\t\t\tsubnetName := subnet(service)\n\t\t\t\tif subnetName == nil {\n\t\t\t\t\tsubnetName = \u0026az.SubnetName\n\t\t\t\t}\n\t\t\t\tsubnet, existsSubnet, err := az.getSubnet(az.VnetName, *subnetName)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\tif !existsSubnet {\n\t\t\t\t\treturn nil, fmt.Errorf(\"ensure(%s): lb(%s) - failed to get subnet: %s/%s\", serviceName, lbName, az.VnetName, az.SubnetName)\n\t\t\t\t}\n\n\t\t\t\tconfigProperties := network.FrontendIPConfigurationPropertiesFormat{\n\t\t\t\t\tSubnet: \u0026subnet,\n\t\t\t\t}\n\n\t\t\t\tif utilnet.IsIPv6String(service.Spec.ClusterIP) {\n\t\t\t\t\tconfigProperties.PrivateIPAddressVersion = network.IPv6\n\t\t\t\t}\n\n\t\t\t\tloadBalancerIP := service.Spec.LoadBalancerIP\n\t\t\t\tif loadBalancerIP != \"\" {\n\t\t\t\t\tconfigProperties.PrivateIPAllocationMethod = network.Static\n\t\t\t\t\tconfigProperties.PrivateIPAddress = \u0026loadBalancerIP\n\t\t\t\t} else {\n\t\t\t\t\t// We'll need to call GetLoadBalancer later to retrieve allocated IP.\n\t\t\t\t\tconfigProperties.PrivateIPAllocationMethod = network.Dynamic\n\t\t\t\t}\n\n\t\t\t\tfipConfigurationProperties = \u0026configProperties\n\t\t\t} else {\n\t\t\t\tpipName, shouldPIPExisted, err := az.determinePublicIPName(clusterName, service)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tdomainNameLabel, found := getPublicIPDomainNameLabel(service)\n\t\t\t\tpip, err := az.ensurePublicIPExists(service, pipName, domainNameLabel, clusterName, shouldPIPExisted, found)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tfipConfigurationProperties = \u0026network.FrontendIPConfigurationPropertiesFormat{\n\t\t\t\t\tPublicIPAddress: \u0026network.PublicIPAddress{ID: pip.ID},\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnewConfigs = append(newConfigs,\n\t\t\t\tnetwork.FrontendIPConfiguration{\n\t\t\t\t\tName: pointer.String(defaultLBFrontendIPConfigName),\n\t\t\t\t\tID: pointer.String(fmt.Sprintf(frontendIPConfigIDTemplate, az.SubscriptionID, az.ResourceGroup, *lb.Name, defaultLBFrontendIPConfigName)),\n\t\t\t\t\tFrontendIPConfigurationPropertiesFormat: fipConfigurationProperties,\n\t\t\t\t})\n\t\t\tklog.V(2).Infof(\"reconcileLoadBalancer for service (%s)(%t): lb frontendconfig(%s) - adding\", serviceName, wantLb, defaultLBFrontendIPConfigName)\n\t\t\tdirtyConfigs = true\n\t\t}\n\t}\n\tif dirtyConfigs {\n\t\tdirtyLb = true\n\t\tlb.FrontendIPConfigurations = \u0026newConfigs\n\t}\n\n\t// update probes/rules\n\tif ownedFIPConfig != nil {\n\t\tif ownedFIPConfig.ID != nil {\n\t\t\tdefaultLBFrontendIPConfigID = *ownedFIPConfig.ID\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"reconcileLoadBalancer for service (%s)(%t): nil ID for frontend IP config\", serviceName, wantLb)\n\t\t}\n\t}\n\n\tif wantLb {\n\t\terr = az.checkLoadBalancerResourcesConflicted(lb, defaultLBFrontendIPConfigID, service)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\texpectedProbes, expectedRules, err := az.reconcileLoadBalancerRule(service, wantLb, defaultLBFrontendIPConfigID, lbBackendPoolID, lbName, lbIdleTimeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// remove unwanted probes\n\tdirtyProbes := false\n\tvar updatedProbes []network.Probe\n\tif lb.Probes != nil {\n\t\tupdatedProbes = *lb.Probes\n\t}\n\tfor i := len(updatedProbes) - 1; i \u003e= 0; i-- {\n\t\texistingProbe := updatedProbes[i]\n\t\tif az.serviceOwnsRule(service, *existingProbe.Name) {\n\t\t\tklog.V(10).Infof(\"reconcileLoadBalancer for service (%s)(%t): lb probe(%s) - considering evicting\", serviceName, wantLb, *existingProbe.Name)\n\t\t\tkeepProbe := false\n\t\t\tif findProbe(expectedProbes, existingProbe) {\n\t\t\t\tklog.V(10).Infof(\"reconcileLoadBalancer for service (%s)(%t): lb probe(%s) - keeping\", serviceName, wantLb, *existingProbe.Name)\n\t\t\t\tkeepProbe = true\n\t\t\t}\n\t\t\tif !keepProbe {\n\t\t\t\tupdatedProbes = append(updatedProbes[:i], updatedProbes[i+1:]...)\n\t\t\t\tklog.V(10).Infof(\"reconcileLoadBalancer for service (%s)(%t): lb probe(%s) - dropping\", serviceName, wantLb, *existingProbe.Name)\n\t\t\t\tdirtyProbes = true\n\t\t\t}\n\t\t}\n\t}\n\t// add missing, wanted probes\n\tfor _, expectedProbe := range expectedProbes {\n\t\tfoundProbe := false\n\t\tif findProbe(updatedProbes, expectedProbe) {\n\t\t\tklog.V(10).Infof(\"reconcileLoadBalancer for service (%s)(%t): lb probe(%s) - already exists\", serviceName, wantLb, *expectedProbe.Name)\n\t\t\tfoundProbe = true\n\t\t}\n\t\tif !foundProbe {\n\t\t\tklog.V(10).Infof(\"reconcileLoadBalancer for service (%s)(%t): lb probe(%s) - adding\", serviceName, wantLb, *expectedProbe.Name)\n\t\t\tupdatedProbes = append(updatedProbes, expectedProbe)\n\t\t\tdirtyProbes = true\n\t\t}\n\t}\n\tif dirtyProbes {\n\t\tdirtyLb = true\n\t\tlb.Probes = \u0026updatedProbes\n\t}\n\n\t// update rules\n\tdirtyRules := false\n\tvar updatedRules []network.LoadBalancingRule\n\tif lb.LoadBalancingRules != nil {\n\t\tupdatedRules = *lb.LoadBalancingRules\n\t}\n\n\t// update rules: remove unwanted\n\tfor i := len(updatedRules) - 1; i \u003e= 0; i-- {\n\t\texistingRule := updatedRules[i]\n\t\tif az.serviceOwnsRule(service, *existingRule.Name) {\n\t\t\tkeepRule := false\n\t\t\tklog.V(10).Infof(\"reconcileLoadBalancer for service (%s)(%t): lb rule(%s) - considering evicting\", serviceName, wantLb, *existingRule.Name)\n\t\t\tif findRule(expectedRules, existingRule, wantLb) {\n\t\t\t\tklog.V(10).Infof(\"reconcileLoadBalancer for service (%s)(%t): lb rule(%s) - keeping\", serviceName, wantLb, *existingRule.Name)\n\t\t\t\tkeepRule = true\n\t\t\t}\n\t\t\tif !keepRule {\n\t\t\t\tklog.V(2).Infof(\"reconcileLoadBalancer for service (%s)(%t): lb rule(%s) - dropping\", serviceName, wantLb, *existingRule.Name)\n\t\t\t\tupdatedRules = append(updatedRules[:i], updatedRules[i+1:]...)\n\t\t\t\tdirtyRules = true\n\t\t\t}\n\t\t}\n\t}\n\t// update rules: add needed\n\tfor _, expectedRule := range expectedRules {\n\t\tfoundRule := false\n\t\tif findRule(updatedRules, expectedRule, wantLb) {\n\t\t\tklog.V(10).Infof(\"reconcileLoadBalancer for service (%s)(%t): lb rule(%s) - already exists\", serviceName, wantLb, *expectedRule.Name)\n\t\t\tfoundRule = true\n\t\t}\n\t\tif !foundRule {\n\t\t\tklog.V(10).Infof(\"reconcileLoadBalancer for service (%s)(%t): lb rule(%s) adding\", serviceName, wantLb, *expectedRule.Name)\n\t\t\tupdatedRules = append(updatedRules, expectedRule)\n\t\t\tdirtyRules = true\n\t\t}\n\t}\n\tif dirtyRules {\n\t\tdirtyLb = true\n\t\tlb.LoadBalancingRules = \u0026updatedRules\n\t}\n\n\tchanged := az.ensureLoadBalancerTagged(lb)\n\tif changed {\n\t\tdirtyLb = true\n\t}\n\n\t// We don't care if the LB exists or not\n\t// We only care about if there is any change in the LB, which means dirtyLB\n\t// If it is not exist, and no change to that, we don't CreateOrUpdate LB\n\tif dirtyLb {\n\t\tif lb.FrontendIPConfigurations == nil || len(*lb.FrontendIPConfigurations) == 0 {\n\t\t\tif isBackendPoolPreConfigured {\n\t\t\t\tklog.V(2).Infof(\"reconcileLoadBalancer for service(%s): lb(%s) - ignore cleanup of dirty lb because the lb is pre-configured\", serviceName, lbName)\n\t\t\t} else {\n\t\t\t\t// When FrontendIPConfigurations is empty, we need to delete the Azure load balancer resource itself,\n\t\t\t\t// because an Azure load balancer cannot have an empty FrontendIPConfigurations collection\n\t\t\t\tklog.V(2).Infof(\"reconcileLoadBalancer for service(%s): lb(%s) - deleting; no remaining frontendIPConfigurations\", serviceName, lbName)\n\n\t\t\t\t// Remove backend pools from vmSets. This is required for virtual machine scale sets before removing the LB.\n\t\t\t\tvmSetName := az.mapLoadBalancerNameToVMSet(lbName, clusterName)\n\t\t\t\tklog.V(10).Infof(\"EnsureBackendPoolDeleted(%s,%s) for service %s: start\", lbBackendPoolID, vmSetName, serviceName)\n\t\t\t\tif _, ok := az.VMSet.(*availabilitySet); ok {\n\t\t\t\t\t// do nothing for availability set\n\t\t\t\t\tlb.BackendAddressPools = nil\n\t\t\t\t}\n\t\t\t\terr := az.VMSet.EnsureBackendPoolDeleted(service, lbBackendPoolID, vmSetName, lb.BackendAddressPools, true)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Errorf(\"EnsureBackendPoolDeleted(%s) for service %s failed: %v\", lbBackendPoolID, serviceName, err)\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tklog.V(10).Infof(\"EnsureBackendPoolDeleted(%s) for service %s: end\", lbBackendPoolID, serviceName)\n\n\t\t\t\texistingLBs, err := az.ListLB(service)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Errorf(\"reconcileLoadBalancer: failed to list load balancer for servcie %q: %s\", serviceName, err.Error())\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\tfoundLB := false\n\t\t\t\tfor _, existingLB := range existingLBs {\n\t\t\t\t\tif strings.EqualFold(lbName, pointer.StringDeref(existingLB.Name, \"\")) {\n\t\t\t\t\t\tfoundLB = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Remove the LB if it exists.\n\t\t\t\tif foundLB {\n\t\t\t\t\tklog.V(10).Infof(\"reconcileLoadBalancer: az.DeleteLB(%q): start\", lbName)\n\t\t\t\t\terr = az.DeleteLB(service, lbName)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tklog.V(2).Infof(\"reconcileLoadBalancer for service(%s) abort backoff: lb(%s) - deleting; no remaining frontendIPConfigurations\", serviceName, lbName)\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tklog.V(10).Infof(\"az.DeleteLB(%q): end\", lbName)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tklog.V(2).Infof(\"reconcileLoadBalancer: reconcileLoadBalancer for service(%s): lb(%s) - updating\", serviceName, lbName)\n\t\t\terr := az.CreateOrUpdateLB(service, *lb)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(2).Infof(\"reconcileLoadBalancer for service(%s) abort backoff: lb(%s) - updating\", serviceName, lbName)\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif isInternal {\n\t\t\t\t// Refresh updated lb which will be used later in other places.\n\t\t\t\tnewLB, exist, err := az.getAzureLoadBalancer(lbName, azcache.CacheReadTypeDefault)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.V(2).Infof(\"reconcileLoadBalancer for service(%s): getAzureLoadBalancer(%s) failed: %v\", serviceName, lbName, err)\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif !exist {\n\t\t\t\t\treturn nil, fmt.Errorf(\"load balancer %q not found\", lbName)\n\t\t\t\t}\n\t\t\t\tlb = \u0026newLB\n\t\t\t}\n\t\t}\n\t}\n\n\tif wantLb \u0026\u0026 nodes != nil \u0026\u0026 !isBackendPoolPreConfigured {\n\t\t// Add the machines to the backend pool if they're not already\n\t\tvmSetName := az.mapLoadBalancerNameToVMSet(lbName, clusterName)\n\t\t// Etag would be changed when updating backend pools, so invalidate lbCache after it.\n\t\tdefer az.lbCache.Delete(lbName)\n\t\terr := az.VMSet.EnsureHostsInPool(service, nodes, lbBackendPoolID, vmSetName, isInternal)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tklog.V(2).Infof(\"reconcileLoadBalancer for service(%s): lb(%s) finished\", serviceName, lbName)\n\treturn lb, nil\n}","line":{"from":1080,"to":1505}} {"id":100033200,"name":"checkLoadBalancerResourcesConflicted","signature":"func (az *Cloud) checkLoadBalancerResourcesConflicted(","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"// checkLoadBalancerResourcesConflicted checks if the service is consuming\n// ports which are conflicted with the existing loadBalancer resources,\n// including inbound NAT rule, inbound NAT pools and loadBalancing rules\nfunc (az *Cloud) checkLoadBalancerResourcesConflicted(\n\tlb *network.LoadBalancer,\n\tfrontendIPConfigID string,\n\tservice *v1.Service,\n) error {\n\tif service.Spec.Ports == nil {\n\t\treturn nil\n\t}\n\tports := service.Spec.Ports\n\n\tfor _, port := range ports {\n\t\tif lb.LoadBalancingRules != nil {\n\t\t\tfor _, rule := range *lb.LoadBalancingRules {\n\t\t\t\tif rule.LoadBalancingRulePropertiesFormat != nil \u0026\u0026\n\t\t\t\t\trule.FrontendIPConfiguration != nil \u0026\u0026\n\t\t\t\t\trule.FrontendIPConfiguration.ID != nil \u0026\u0026\n\t\t\t\t\tstrings.EqualFold(*rule.FrontendIPConfiguration.ID, frontendIPConfigID) \u0026\u0026\n\t\t\t\t\tstrings.EqualFold(string(rule.Protocol), string(port.Protocol)) \u0026\u0026\n\t\t\t\t\trule.FrontendPort != nil \u0026\u0026\n\t\t\t\t\t*rule.FrontendPort == port.Port {\n\t\t\t\t\t// ignore self-owned rules for unit test\n\t\t\t\t\tif rule.Name != nil \u0026\u0026 az.serviceOwnsRule(service, *rule.Name) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\treturn fmt.Errorf(\"checkLoadBalancerResourcesConflicted: service port %s is trying to \"+\n\t\t\t\t\t\t\"consume the port %d which is being referenced by an existing loadBalancing rule %s with \"+\n\t\t\t\t\t\t\"the same protocol %s and frontend IP config with ID %s\",\n\t\t\t\t\t\tport.Name,\n\t\t\t\t\t\t*rule.FrontendPort,\n\t\t\t\t\t\t*rule.Name,\n\t\t\t\t\t\trule.Protocol,\n\t\t\t\t\t\t*rule.FrontendIPConfiguration.ID)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif lb.InboundNatRules != nil {\n\t\t\tfor _, inboundNatRule := range *lb.InboundNatRules {\n\t\t\t\tif inboundNatRule.InboundNatRulePropertiesFormat != nil \u0026\u0026\n\t\t\t\t\tinboundNatRule.FrontendIPConfiguration != nil \u0026\u0026\n\t\t\t\t\tinboundNatRule.FrontendIPConfiguration.ID != nil \u0026\u0026\n\t\t\t\t\tstrings.EqualFold(*inboundNatRule.FrontendIPConfiguration.ID, frontendIPConfigID) \u0026\u0026\n\t\t\t\t\tstrings.EqualFold(string(inboundNatRule.Protocol), string(port.Protocol)) \u0026\u0026\n\t\t\t\t\tinboundNatRule.FrontendPort != nil \u0026\u0026\n\t\t\t\t\t*inboundNatRule.FrontendPort == port.Port {\n\t\t\t\t\treturn fmt.Errorf(\"checkLoadBalancerResourcesConflicted: service port %s is trying to \"+\n\t\t\t\t\t\t\"consume the port %d which is being referenced by an existing inbound NAT rule %s with \"+\n\t\t\t\t\t\t\"the same protocol %s and frontend IP config with ID %s\",\n\t\t\t\t\t\tport.Name,\n\t\t\t\t\t\t*inboundNatRule.FrontendPort,\n\t\t\t\t\t\t*inboundNatRule.Name,\n\t\t\t\t\t\tinboundNatRule.Protocol,\n\t\t\t\t\t\t*inboundNatRule.FrontendIPConfiguration.ID)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif lb.InboundNatPools != nil {\n\t\t\tfor _, pool := range *lb.InboundNatPools {\n\t\t\t\tif pool.InboundNatPoolPropertiesFormat != nil \u0026\u0026\n\t\t\t\t\tpool.FrontendIPConfiguration != nil \u0026\u0026\n\t\t\t\t\tpool.FrontendIPConfiguration.ID != nil \u0026\u0026\n\t\t\t\t\tstrings.EqualFold(*pool.FrontendIPConfiguration.ID, frontendIPConfigID) \u0026\u0026\n\t\t\t\t\tstrings.EqualFold(string(pool.Protocol), string(port.Protocol)) \u0026\u0026\n\t\t\t\t\tpool.FrontendPortRangeStart != nil \u0026\u0026\n\t\t\t\t\tpool.FrontendPortRangeEnd != nil \u0026\u0026\n\t\t\t\t\t*pool.FrontendPortRangeStart \u003c= port.Port \u0026\u0026\n\t\t\t\t\t*pool.FrontendPortRangeEnd \u003e= port.Port {\n\t\t\t\t\treturn fmt.Errorf(\"checkLoadBalancerResourcesConflicted: service port %s is trying to \"+\n\t\t\t\t\t\t\"consume the port %d which is being in the range (%d-%d) of an existing \"+\n\t\t\t\t\t\t\"inbound NAT pool %s with the same protocol %s and frontend IP config with ID %s\",\n\t\t\t\t\t\tport.Name,\n\t\t\t\t\t\tport.Port,\n\t\t\t\t\t\t*pool.FrontendPortRangeStart,\n\t\t\t\t\t\t*pool.FrontendPortRangeEnd,\n\t\t\t\t\t\t*pool.Name,\n\t\t\t\t\t\tpool.Protocol,\n\t\t\t\t\t\t*pool.FrontendIPConfiguration.ID)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":1507,"to":1594}} {"id":100033201,"name":"parseHealthProbeProtocolAndPath","signature":"func parseHealthProbeProtocolAndPath(service *v1.Service) (string, string)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func parseHealthProbeProtocolAndPath(service *v1.Service) (string, string) {\n\tvar protocol, path string\n\tif v, ok := service.Annotations[ServiceAnnotationLoadBalancerHealthProbeProtocol]; ok {\n\t\tprotocol = v\n\t} else {\n\t\treturn protocol, path\n\t}\n\t// ignore the request path if using TCP\n\tif strings.EqualFold(protocol, string(network.ProbeProtocolHTTP)) ||\n\t\tstrings.EqualFold(protocol, string(network.ProbeProtocolHTTPS)) {\n\t\tif v, ok := service.Annotations[ServiceAnnotationLoadBalancerHealthProbeRequestPath]; ok {\n\t\t\tpath = v\n\t\t}\n\t}\n\treturn protocol, path\n}","line":{"from":1596,"to":1611}} {"id":100033202,"name":"reconcileLoadBalancerRule","signature":"func (az *Cloud) reconcileLoadBalancerRule(","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func (az *Cloud) reconcileLoadBalancerRule(\n\tservice *v1.Service,\n\twantLb bool,\n\tlbFrontendIPConfigID string,\n\tlbBackendPoolID string,\n\tlbName string,\n\tlbIdleTimeout *int32) ([]network.Probe, []network.LoadBalancingRule, error) {\n\n\tvar ports []v1.ServicePort\n\tif wantLb {\n\t\tports = service.Spec.Ports\n\t} else {\n\t\tports = []v1.ServicePort{}\n\t}\n\n\tvar enableTCPReset *bool\n\tif az.useStandardLoadBalancer() {\n\t\tenableTCPReset = pointer.Bool(true)\n\t}\n\n\tvar expectedProbes []network.Probe\n\tvar expectedRules []network.LoadBalancingRule\n\thighAvailabilityPortsEnabled := false\n\tfor _, port := range ports {\n\t\tif highAvailabilityPortsEnabled {\n\t\t\t// Since the port is always 0 when enabling HA, only one rule should be configured.\n\t\t\tbreak\n\t\t}\n\n\t\tlbRuleName := az.getLoadBalancerRuleName(service, port.Protocol, port.Port)\n\t\tklog.V(2).Infof(\"reconcileLoadBalancerRule lb name (%s) rule name (%s)\", lbName, lbRuleName)\n\n\t\ttransportProto, _, probeProto, err := getProtocolsFromKubernetesProtocol(port.Protocol)\n\t\tif err != nil {\n\t\t\treturn expectedProbes, expectedRules, err\n\t\t}\n\n\t\tprobeProtocol, requestPath := parseHealthProbeProtocolAndPath(service)\n\t\tif servicehelpers.NeedsHealthCheck(service) {\n\t\t\tpodPresencePath, podPresencePort := servicehelpers.GetServiceHealthCheckPathPort(service)\n\t\t\tif probeProtocol == \"\" {\n\t\t\t\tprobeProtocol = string(network.ProbeProtocolHTTP)\n\t\t\t}\n\n\t\t\tneedRequestPath := strings.EqualFold(probeProtocol, string(network.ProbeProtocolHTTP)) || strings.EqualFold(probeProtocol, string(network.ProbeProtocolHTTPS))\n\t\t\tif requestPath == \"\" \u0026\u0026 needRequestPath {\n\t\t\t\trequestPath = podPresencePath\n\t\t\t}\n\n\t\t\texpectedProbes = append(expectedProbes, network.Probe{\n\t\t\t\tName: \u0026lbRuleName,\n\t\t\t\tProbePropertiesFormat: \u0026network.ProbePropertiesFormat{\n\t\t\t\t\tRequestPath: pointer.String(requestPath),\n\t\t\t\t\tProtocol: network.ProbeProtocol(probeProtocol),\n\t\t\t\t\tPort: pointer.Int32(podPresencePort),\n\t\t\t\t\tIntervalInSeconds: pointer.Int32(5),\n\t\t\t\t\tNumberOfProbes: pointer.Int32(2),\n\t\t\t\t},\n\t\t\t})\n\t\t} else if port.Protocol != v1.ProtocolUDP \u0026\u0026 port.Protocol != v1.ProtocolSCTP {\n\t\t\t// we only add the expected probe if we're doing TCP\n\t\t\tif probeProtocol == \"\" {\n\t\t\t\tprobeProtocol = string(*probeProto)\n\t\t\t}\n\t\t\tvar actualPath *string\n\t\t\tif !strings.EqualFold(probeProtocol, string(network.ProbeProtocolTCP)) {\n\t\t\t\tif requestPath != \"\" {\n\t\t\t\t\tactualPath = pointer.String(requestPath)\n\t\t\t\t} else {\n\t\t\t\t\tactualPath = pointer.String(\"/healthz\")\n\t\t\t\t}\n\t\t\t}\n\t\t\texpectedProbes = append(expectedProbes, network.Probe{\n\t\t\t\tName: \u0026lbRuleName,\n\t\t\t\tProbePropertiesFormat: \u0026network.ProbePropertiesFormat{\n\t\t\t\t\tProtocol: network.ProbeProtocol(probeProtocol),\n\t\t\t\t\tRequestPath: actualPath,\n\t\t\t\t\tPort: pointer.Int32(port.NodePort),\n\t\t\t\t\tIntervalInSeconds: pointer.Int32(5),\n\t\t\t\t\tNumberOfProbes: pointer.Int32(2),\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\n\t\tloadDistribution := network.LoadDistributionDefault\n\t\tif service.Spec.SessionAffinity == v1.ServiceAffinityClientIP {\n\t\t\tloadDistribution = network.LoadDistributionSourceIP\n\t\t}\n\n\t\ttcpReset := enableTCPReset\n\t\tif port.Protocol != v1.ProtocolTCP {\n\t\t\ttcpReset = nil\n\t\t}\n\t\texpectedRule := network.LoadBalancingRule{\n\t\t\tName: \u0026lbRuleName,\n\t\t\tLoadBalancingRulePropertiesFormat: \u0026network.LoadBalancingRulePropertiesFormat{\n\t\t\t\tProtocol: *transportProto,\n\t\t\t\tFrontendIPConfiguration: \u0026network.SubResource{\n\t\t\t\t\tID: pointer.String(lbFrontendIPConfigID),\n\t\t\t\t},\n\t\t\t\tBackendAddressPool: \u0026network.SubResource{\n\t\t\t\t\tID: pointer.String(lbBackendPoolID),\n\t\t\t\t},\n\t\t\t\tLoadDistribution: loadDistribution,\n\t\t\t\tFrontendPort: pointer.Int32(port.Port),\n\t\t\t\tBackendPort: pointer.Int32(port.Port),\n\t\t\t\tDisableOutboundSnat: pointer.Bool(az.disableLoadBalancerOutboundSNAT()),\n\t\t\t\tEnableTCPReset: tcpReset,\n\t\t\t\tEnableFloatingIP: pointer.Bool(true),\n\t\t\t},\n\t\t}\n\n\t\tif port.Protocol == v1.ProtocolTCP {\n\t\t\texpectedRule.LoadBalancingRulePropertiesFormat.IdleTimeoutInMinutes = lbIdleTimeout\n\t\t}\n\n\t\tif requiresInternalLoadBalancer(service) \u0026\u0026\n\t\t\tstrings.EqualFold(az.LoadBalancerSku, loadBalancerSkuStandard) \u0026\u0026\n\t\t\tstrings.EqualFold(service.Annotations[ServiceAnnotationLoadBalancerEnableHighAvailabilityPorts], \"true\") {\n\t\t\texpectedRule.FrontendPort = pointer.Int32(0)\n\t\t\texpectedRule.BackendPort = pointer.Int32(0)\n\t\t\texpectedRule.Protocol = network.TransportProtocolAll\n\t\t\thighAvailabilityPortsEnabled = true\n\t\t}\n\n\t\t// we didn't construct the probe objects for UDP or SCTP because they're not allowed on Azure.\n\t\t// However, when externalTrafficPolicy is Local, Kubernetes HTTP health check would be used for probing.\n\t\tif servicehelpers.NeedsHealthCheck(service) || (port.Protocol != v1.ProtocolUDP \u0026\u0026 port.Protocol != v1.ProtocolSCTP) {\n\t\t\texpectedRule.Probe = \u0026network.SubResource{\n\t\t\t\tID: pointer.String(az.getLoadBalancerProbeID(lbName, az.getLoadBalancerResourceGroup(), lbRuleName)),\n\t\t\t}\n\t\t}\n\n\t\texpectedRules = append(expectedRules, expectedRule)\n\t}\n\n\treturn expectedProbes, expectedRules, nil\n}","line":{"from":1613,"to":1750}} {"id":100033203,"name":"reconcileSecurityGroup","signature":"func (az *Cloud) reconcileSecurityGroup(clusterName string, service *v1.Service, lbIP *string, wantLb bool) (*network.SecurityGroup, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"// This reconciles the Network Security Group similar to how the LB is reconciled.\n// This entails adding required, missing SecurityRules and removing stale rules.\nfunc (az *Cloud) reconcileSecurityGroup(clusterName string, service *v1.Service, lbIP *string, wantLb bool) (*network.SecurityGroup, error) {\n\tserviceName := getServiceName(service)\n\tklog.V(5).Infof(\"reconcileSecurityGroup(%s): START clusterName=%q\", serviceName, clusterName)\n\n\tports := service.Spec.Ports\n\tif ports == nil {\n\t\tif useSharedSecurityRule(service) {\n\t\t\tklog.V(2).Infof(\"Attempting to reconcile security group for service %s, but service uses shared rule and we don't know which port it's for\", service.Name)\n\t\t\treturn nil, fmt.Errorf(\"no port info for reconciling shared rule for service %s\", service.Name)\n\t\t}\n\t\tports = []v1.ServicePort{}\n\t}\n\n\tsg, err := az.getSecurityGroup(azcache.CacheReadTypeDefault)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdestinationIPAddress := \"\"\n\tif wantLb \u0026\u0026 lbIP == nil {\n\t\treturn nil, fmt.Errorf(\"no load balancer IP for setting up security rules for service %s\", service.Name)\n\t}\n\tif lbIP != nil {\n\t\tdestinationIPAddress = *lbIP\n\t}\n\n\tif destinationIPAddress == \"\" {\n\t\tdestinationIPAddress = \"*\"\n\t}\n\n\tsourceRanges, err := servicehelpers.GetLoadBalancerSourceRanges(service)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tserviceTags := getServiceTags(service)\n\tif len(serviceTags) != 0 {\n\t\tif _, ok := sourceRanges[defaultLoadBalancerSourceRanges]; ok {\n\t\t\tdelete(sourceRanges, defaultLoadBalancerSourceRanges)\n\t\t}\n\t}\n\n\tvar sourceAddressPrefixes []string\n\tif (sourceRanges == nil || servicehelpers.IsAllowAll(sourceRanges)) \u0026\u0026 len(serviceTags) == 0 {\n\t\tif !requiresInternalLoadBalancer(service) {\n\t\t\tsourceAddressPrefixes = []string{\"Internet\"}\n\t\t}\n\t} else {\n\t\tfor _, ip := range sourceRanges {\n\t\t\tsourceAddressPrefixes = append(sourceAddressPrefixes, ip.String())\n\t\t}\n\t\tsourceAddressPrefixes = append(sourceAddressPrefixes, serviceTags...)\n\t}\n\texpectedSecurityRules := []network.SecurityRule{}\n\n\tif wantLb {\n\t\texpectedSecurityRules = make([]network.SecurityRule, len(ports)*len(sourceAddressPrefixes))\n\n\t\tfor i, port := range ports {\n\t\t\t_, securityProto, _, err := getProtocolsFromKubernetesProtocol(port.Protocol)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfor j := range sourceAddressPrefixes {\n\t\t\t\tix := i*len(sourceAddressPrefixes) + j\n\t\t\t\tsecurityRuleName := az.getSecurityRuleName(service, port, sourceAddressPrefixes[j])\n\t\t\t\texpectedSecurityRules[ix] = network.SecurityRule{\n\t\t\t\t\tName: pointer.String(securityRuleName),\n\t\t\t\t\tSecurityRulePropertiesFormat: \u0026network.SecurityRulePropertiesFormat{\n\t\t\t\t\t\tProtocol: *securityProto,\n\t\t\t\t\t\tSourcePortRange: pointer.String(\"*\"),\n\t\t\t\t\t\tDestinationPortRange: pointer.String(strconv.Itoa(int(port.Port))),\n\t\t\t\t\t\tSourceAddressPrefix: pointer.String(sourceAddressPrefixes[j]),\n\t\t\t\t\t\tDestinationAddressPrefix: pointer.String(destinationIPAddress),\n\t\t\t\t\t\tAccess: network.SecurityRuleAccessAllow,\n\t\t\t\t\t\tDirection: network.SecurityRuleDirectionInbound,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, r := range expectedSecurityRules {\n\t\tklog.V(10).Infof(\"Expecting security rule for %s: %s:%s -\u003e %s:%s\", service.Name, *r.SourceAddressPrefix, *r.SourcePortRange, *r.DestinationAddressPrefix, *r.DestinationPortRange)\n\t}\n\n\t// update security rules\n\tdirtySg := false\n\tvar updatedRules []network.SecurityRule\n\tif sg.SecurityGroupPropertiesFormat != nil \u0026\u0026 sg.SecurityGroupPropertiesFormat.SecurityRules != nil {\n\t\tupdatedRules = *sg.SecurityGroupPropertiesFormat.SecurityRules\n\t}\n\n\tfor _, r := range updatedRules {\n\t\tklog.V(10).Infof(\"Existing security rule while processing %s: %s:%s -\u003e %s:%s\", service.Name, logSafe(r.SourceAddressPrefix), logSafe(r.SourcePortRange), logSafeCollection(r.DestinationAddressPrefix, r.DestinationAddressPrefixes), logSafe(r.DestinationPortRange))\n\t}\n\n\t// update security rules: remove unwanted rules that belong privately\n\t// to this service\n\tfor i := len(updatedRules) - 1; i \u003e= 0; i-- {\n\t\texistingRule := updatedRules[i]\n\t\tif az.serviceOwnsRule(service, *existingRule.Name) {\n\t\t\tklog.V(10).Infof(\"reconcile(%s)(%t): sg rule(%s) - considering evicting\", serviceName, wantLb, *existingRule.Name)\n\t\t\tkeepRule := false\n\t\t\tif findSecurityRule(expectedSecurityRules, existingRule) {\n\t\t\t\tklog.V(10).Infof(\"reconcile(%s)(%t): sg rule(%s) - keeping\", serviceName, wantLb, *existingRule.Name)\n\t\t\t\tkeepRule = true\n\t\t\t}\n\t\t\tif !keepRule {\n\t\t\t\tklog.V(10).Infof(\"reconcile(%s)(%t): sg rule(%s) - dropping\", serviceName, wantLb, *existingRule.Name)\n\t\t\t\tupdatedRules = append(updatedRules[:i], updatedRules[i+1:]...)\n\t\t\t\tdirtySg = true\n\t\t\t}\n\t\t}\n\t}\n\t// update security rules: if the service uses a shared rule and is being deleted,\n\t// then remove it from the shared rule\n\tif useSharedSecurityRule(service) \u0026\u0026 !wantLb {\n\t\tfor _, port := range ports {\n\t\t\tfor _, sourceAddressPrefix := range sourceAddressPrefixes {\n\t\t\t\tsharedRuleName := az.getSecurityRuleName(service, port, sourceAddressPrefix)\n\t\t\t\tsharedIndex, sharedRule, sharedRuleFound := findSecurityRuleByName(updatedRules, sharedRuleName)\n\t\t\t\tif !sharedRuleFound {\n\t\t\t\t\tklog.V(4).Infof(\"Didn't find shared rule %s for service %s\", sharedRuleName, service.Name)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif sharedRule.DestinationAddressPrefixes == nil {\n\t\t\t\t\tklog.V(4).Infof(\"Didn't find DestinationAddressPrefixes in shared rule for service %s\", service.Name)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\texistingPrefixes := *sharedRule.DestinationAddressPrefixes\n\t\t\t\taddressIndex, found := findIndex(existingPrefixes, destinationIPAddress)\n\t\t\t\tif !found {\n\t\t\t\t\tklog.V(4).Infof(\"Didn't find destination address %v in shared rule %s for service %s\", destinationIPAddress, sharedRuleName, service.Name)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif len(existingPrefixes) == 1 {\n\t\t\t\t\tupdatedRules = append(updatedRules[:sharedIndex], updatedRules[sharedIndex+1:]...)\n\t\t\t\t} else {\n\t\t\t\t\tnewDestinations := append(existingPrefixes[:addressIndex], existingPrefixes[addressIndex+1:]...)\n\t\t\t\t\tsharedRule.DestinationAddressPrefixes = \u0026newDestinations\n\t\t\t\t\tupdatedRules[sharedIndex] = sharedRule\n\t\t\t\t}\n\t\t\t\tdirtySg = true\n\t\t\t}\n\t\t}\n\t}\n\n\t// update security rules: prepare rules for consolidation\n\tfor index, rule := range updatedRules {\n\t\tif allowsConsolidation(rule) {\n\t\t\tupdatedRules[index] = makeConsolidatable(rule)\n\t\t}\n\t}\n\tfor index, rule := range expectedSecurityRules {\n\t\tif allowsConsolidation(rule) {\n\t\t\texpectedSecurityRules[index] = makeConsolidatable(rule)\n\t\t}\n\t}\n\t// update security rules: add needed\n\tfor _, expectedRule := range expectedSecurityRules {\n\t\tfoundRule := false\n\t\tif findSecurityRule(updatedRules, expectedRule) {\n\t\t\tklog.V(10).Infof(\"reconcile(%s)(%t): sg rule(%s) - already exists\", serviceName, wantLb, *expectedRule.Name)\n\t\t\tfoundRule = true\n\t\t}\n\t\tif foundRule \u0026\u0026 allowsConsolidation(expectedRule) {\n\t\t\tindex, _ := findConsolidationCandidate(updatedRules, expectedRule)\n\t\t\tupdatedRules[index] = consolidate(updatedRules[index], expectedRule)\n\t\t\tdirtySg = true\n\t\t}\n\t\tif !foundRule {\n\t\t\tklog.V(10).Infof(\"reconcile(%s)(%t): sg rule(%s) - adding\", serviceName, wantLb, *expectedRule.Name)\n\n\t\t\tnextAvailablePriority, err := getNextAvailablePriority(updatedRules)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\texpectedRule.Priority = pointer.Int32(nextAvailablePriority)\n\t\t\tupdatedRules = append(updatedRules, expectedRule)\n\t\t\tdirtySg = true\n\t\t}\n\t}\n\n\tfor _, r := range updatedRules {\n\t\tklog.V(10).Infof(\"Updated security rule while processing %s: %s:%s -\u003e %s:%s\", service.Name, logSafe(r.SourceAddressPrefix), logSafe(r.SourcePortRange), logSafeCollection(r.DestinationAddressPrefix, r.DestinationAddressPrefixes), logSafe(r.DestinationPortRange))\n\t}\n\n\tchanged := az.ensureSecurityGroupTagged(\u0026sg)\n\tif changed {\n\t\tdirtySg = true\n\t}\n\n\tif dirtySg {\n\t\tsg.SecurityRules = \u0026updatedRules\n\t\tklog.V(2).Infof(\"reconcileSecurityGroup for service(%s): sg(%s) - updating\", serviceName, *sg.Name)\n\t\tklog.V(10).Infof(\"CreateOrUpdateSecurityGroup(%q): start\", *sg.Name)\n\t\terr := az.CreateOrUpdateSecurityGroup(sg)\n\t\tif err != nil {\n\t\t\tklog.V(2).Infof(\"ensure(%s) abort backoff: sg(%s) - updating\", serviceName, *sg.Name)\n\t\t\treturn nil, err\n\t\t}\n\t\tklog.V(10).Infof(\"CreateOrUpdateSecurityGroup(%q): end\", *sg.Name)\n\t\taz.nsgCache.Delete(pointer.StringDeref(sg.Name, \"\"))\n\t}\n\treturn \u0026sg, nil\n}","line":{"from":1752,"to":1960}} {"id":100033204,"name":"shouldUpdateLoadBalancer","signature":"func (az *Cloud) shouldUpdateLoadBalancer(clusterName string, service *v1.Service) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func (az *Cloud) shouldUpdateLoadBalancer(clusterName string, service *v1.Service) bool {\n\t_, _, existsLb, _ := az.getServiceLoadBalancer(service, clusterName, nil, false)\n\treturn existsLb \u0026\u0026 service.ObjectMeta.DeletionTimestamp == nil\n}","line":{"from":1962,"to":1965}} {"id":100033205,"name":"logSafe","signature":"func logSafe(s *string) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func logSafe(s *string) string {\n\tif s == nil {\n\t\treturn \"(nil)\"\n\t}\n\treturn *s\n}","line":{"from":1967,"to":1972}} {"id":100033206,"name":"logSafeCollection","signature":"func logSafeCollection(s *string, strs *[]string) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func logSafeCollection(s *string, strs *[]string) string {\n\tif s == nil {\n\t\tif strs == nil {\n\t\t\treturn \"(nil)\"\n\t\t}\n\t\treturn \"[\" + strings.Join(*strs, \",\") + \"]\"\n\t}\n\treturn *s\n}","line":{"from":1974,"to":1982}} {"id":100033207,"name":"findSecurityRuleByName","signature":"func findSecurityRuleByName(rules []network.SecurityRule, ruleName string) (int, network.SecurityRule, bool)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func findSecurityRuleByName(rules []network.SecurityRule, ruleName string) (int, network.SecurityRule, bool) {\n\tfor index, rule := range rules {\n\t\tif rule.Name != nil \u0026\u0026 strings.EqualFold(*rule.Name, ruleName) {\n\t\t\treturn index, rule, true\n\t\t}\n\t}\n\treturn 0, network.SecurityRule{}, false\n}","line":{"from":1984,"to":1991}} {"id":100033208,"name":"findIndex","signature":"func findIndex(strs []string, s string) (int, bool)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func findIndex(strs []string, s string) (int, bool) {\n\tfor index, str := range strs {\n\t\tif strings.EqualFold(str, s) {\n\t\t\treturn index, true\n\t\t}\n\t}\n\treturn 0, false\n}","line":{"from":1993,"to":2000}} {"id":100033209,"name":"allowsConsolidation","signature":"func allowsConsolidation(rule network.SecurityRule) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func allowsConsolidation(rule network.SecurityRule) bool {\n\treturn strings.HasPrefix(pointer.StringDeref(rule.Name, \"\"), \"shared\")\n}","line":{"from":2002,"to":2004}} {"id":100033210,"name":"findConsolidationCandidate","signature":"func findConsolidationCandidate(rules []network.SecurityRule, rule network.SecurityRule) (int, bool)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func findConsolidationCandidate(rules []network.SecurityRule, rule network.SecurityRule) (int, bool) {\n\tfor index, r := range rules {\n\t\tif allowsConsolidation(r) {\n\t\t\tif strings.EqualFold(pointer.StringDeref(r.Name, \"\"), pointer.StringDeref(rule.Name, \"\")) {\n\t\t\t\treturn index, true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0, false\n}","line":{"from":2006,"to":2016}} {"id":100033211,"name":"makeConsolidatable","signature":"func makeConsolidatable(rule network.SecurityRule) network.SecurityRule","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func makeConsolidatable(rule network.SecurityRule) network.SecurityRule {\n\treturn network.SecurityRule{\n\t\tName: rule.Name,\n\t\tSecurityRulePropertiesFormat: \u0026network.SecurityRulePropertiesFormat{\n\t\t\tPriority: rule.Priority,\n\t\t\tProtocol: rule.Protocol,\n\t\t\tSourcePortRange: rule.SourcePortRange,\n\t\t\tSourcePortRanges: rule.SourcePortRanges,\n\t\t\tDestinationPortRange: rule.DestinationPortRange,\n\t\t\tDestinationPortRanges: rule.DestinationPortRanges,\n\t\t\tSourceAddressPrefix: rule.SourceAddressPrefix,\n\t\t\tSourceAddressPrefixes: rule.SourceAddressPrefixes,\n\t\t\tDestinationAddressPrefixes: collectionOrSingle(rule.DestinationAddressPrefixes, rule.DestinationAddressPrefix),\n\t\t\tAccess: rule.Access,\n\t\t\tDirection: rule.Direction,\n\t\t},\n\t}\n}","line":{"from":2018,"to":2035}} {"id":100033212,"name":"consolidate","signature":"func consolidate(existingRule network.SecurityRule, newRule network.SecurityRule) network.SecurityRule","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func consolidate(existingRule network.SecurityRule, newRule network.SecurityRule) network.SecurityRule {\n\tdestinations := appendElements(existingRule.SecurityRulePropertiesFormat.DestinationAddressPrefixes, newRule.DestinationAddressPrefix, newRule.DestinationAddressPrefixes)\n\tdestinations = deduplicate(destinations) // there are transient conditions during controller startup where it tries to add a service that is already added\n\n\treturn network.SecurityRule{\n\t\tName: existingRule.Name,\n\t\tSecurityRulePropertiesFormat: \u0026network.SecurityRulePropertiesFormat{\n\t\t\tPriority: existingRule.Priority,\n\t\t\tProtocol: existingRule.Protocol,\n\t\t\tSourcePortRange: existingRule.SourcePortRange,\n\t\t\tSourcePortRanges: existingRule.SourcePortRanges,\n\t\t\tDestinationPortRange: existingRule.DestinationPortRange,\n\t\t\tDestinationPortRanges: existingRule.DestinationPortRanges,\n\t\t\tSourceAddressPrefix: existingRule.SourceAddressPrefix,\n\t\t\tSourceAddressPrefixes: existingRule.SourceAddressPrefixes,\n\t\t\tDestinationAddressPrefixes: destinations,\n\t\t\tAccess: existingRule.Access,\n\t\t\tDirection: existingRule.Direction,\n\t\t},\n\t}\n}","line":{"from":2037,"to":2057}} {"id":100033213,"name":"collectionOrSingle","signature":"func collectionOrSingle(collection *[]string, s *string) *[]string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func collectionOrSingle(collection *[]string, s *string) *[]string {\n\tif collection != nil \u0026\u0026 len(*collection) \u003e 0 {\n\t\treturn collection\n\t}\n\tif s == nil {\n\t\treturn \u0026[]string{}\n\t}\n\treturn \u0026[]string{*s}\n}","line":{"from":2059,"to":2067}} {"id":100033214,"name":"appendElements","signature":"func appendElements(collection *[]string, appendString *string, appendStrings *[]string) *[]string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func appendElements(collection *[]string, appendString *string, appendStrings *[]string) *[]string {\n\tnewCollection := []string{}\n\n\tif collection != nil {\n\t\tnewCollection = append(newCollection, *collection...)\n\t}\n\tif appendString != nil {\n\t\tnewCollection = append(newCollection, *appendString)\n\t}\n\tif appendStrings != nil {\n\t\tnewCollection = append(newCollection, *appendStrings...)\n\t}\n\n\treturn \u0026newCollection\n}","line":{"from":2069,"to":2083}} {"id":100033215,"name":"deduplicate","signature":"func deduplicate(collection *[]string) *[]string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func deduplicate(collection *[]string) *[]string {\n\tif collection == nil {\n\t\treturn nil\n\t}\n\n\tseen := map[string]bool{}\n\tresult := make([]string, 0, len(*collection))\n\n\tfor _, v := range *collection {\n\t\tif seen[v] == true {\n\t\t\t// skip this element\n\t\t} else {\n\t\t\tseen[v] = true\n\t\t\tresult = append(result, v)\n\t\t}\n\t}\n\n\treturn \u0026result\n}","line":{"from":2085,"to":2103}} {"id":100033216,"name":"shouldReleaseExistingOwnedPublicIP","signature":"func shouldReleaseExistingOwnedPublicIP(existingPip *network.PublicIPAddress, lbShouldExist, lbIsInternal, isUserAssignedPIP bool, desiredPipName string, ipTagRequest serviceIPTagRequest) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"// Determine if we should release existing owned public IPs\nfunc shouldReleaseExistingOwnedPublicIP(existingPip *network.PublicIPAddress, lbShouldExist, lbIsInternal, isUserAssignedPIP bool, desiredPipName string, ipTagRequest serviceIPTagRequest) bool {\n\t// skip deleting user created pip\n\tif isUserAssignedPIP {\n\t\treturn false\n\t}\n\n\t// Latch some variables for readability purposes.\n\tpipName := *(*existingPip).Name\n\n\t// Assume the current IP Tags are empty by default unless properties specify otherwise.\n\tcurrentIPTags := \u0026[]network.IPTag{}\n\tpipPropertiesFormat := (*existingPip).PublicIPAddressPropertiesFormat\n\tif pipPropertiesFormat != nil {\n\t\tcurrentIPTags = (*pipPropertiesFormat).IPTags\n\t}\n\n\t// Check whether the public IP is being referenced by other service.\n\t// The owned public IP can be released only when there is not other service using it.\n\tif existingPip.Tags[serviceTagKey] != nil {\n\t\t// case 1: there is at least one reference when deleting the PIP\n\t\tif !lbShouldExist \u0026\u0026 len(parsePIPServiceTag(existingPip.Tags[serviceTagKey])) \u003e 0 {\n\t\t\treturn false\n\t\t}\n\n\t\t// case 2: there is at least one reference from other service\n\t\tif lbShouldExist \u0026\u0026 len(parsePIPServiceTag(existingPip.Tags[serviceTagKey])) \u003e 1 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// Release the ip under the following criteria -\n\t// #1 - If we don't actually want a load balancer,\n\treturn !lbShouldExist ||\n\t\t// #2 - If the load balancer is internal, and thus doesn't require public exposure\n\t\tlbIsInternal ||\n\t\t// #3 - If the name of this public ip does not match the desired name,\n\t\t(pipName != desiredPipName) ||\n\t\t// #4 If the service annotations have specified the ip tags that the public ip must have, but they do not match the ip tags of the existing instance\n\t\t(ipTagRequest.IPTagsRequestedByAnnotation \u0026\u0026 !areIPTagsEquivalent(currentIPTags, ipTagRequest.IPTags))\n}","line":{"from":2105,"to":2145}} {"id":100033217,"name":"ensurePIPTagged","signature":"func (az *Cloud) ensurePIPTagged(service *v1.Service, pip *network.PublicIPAddress) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"// ensurePIPTagged ensures the public IP of the service is tagged as configured\nfunc (az *Cloud) ensurePIPTagged(service *v1.Service, pip *network.PublicIPAddress) bool {\n\tconfigTags := parseTags(az.Tags)\n\tannotationTags := make(map[string]*string)\n\tif _, ok := service.Annotations[ServiceAnnotationAzurePIPTags]; ok {\n\t\tannotationTags = parseTags(service.Annotations[ServiceAnnotationAzurePIPTags])\n\t}\n\tconfigTags, _ = reconcileTags(configTags, annotationTags)\n\n\t// include the cluster name and service names tags when comparing\n\tvar clusterName, serviceNames *string\n\tif v, ok := pip.Tags[clusterNameKey]; ok {\n\t\tclusterName = v\n\t}\n\tif v, ok := pip.Tags[serviceTagKey]; ok {\n\t\tserviceNames = v\n\t}\n\tif clusterName != nil {\n\t\tconfigTags[clusterNameKey] = clusterName\n\t}\n\tif serviceNames != nil {\n\t\tconfigTags[serviceTagKey] = serviceNames\n\t}\n\n\ttags, changed := reconcileTags(pip.Tags, configTags)\n\tpip.Tags = tags\n\n\treturn changed\n}","line":{"from":2147,"to":2175}} {"id":100033218,"name":"reconcilePublicIP","signature":"func (az *Cloud) reconcilePublicIP(clusterName string, service *v1.Service, lbName string, wantLb bool) (*network.PublicIPAddress, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"// This reconciles the PublicIP resources similar to how the LB is reconciled.\nfunc (az *Cloud) reconcilePublicIP(clusterName string, service *v1.Service, lbName string, wantLb bool) (*network.PublicIPAddress, error) {\n\tisInternal := requiresInternalLoadBalancer(service)\n\tserviceName := getServiceName(service)\n\tserviceIPTagRequest := getServiceIPTagRequestForPublicIP(service)\n\n\tvar (\n\t\tlb *network.LoadBalancer\n\t\tdesiredPipName string\n\t\terr error\n\t\tshouldPIPExisted bool\n\t)\n\n\tif !isInternal \u0026\u0026 wantLb {\n\t\tdesiredPipName, shouldPIPExisted, err = az.determinePublicIPName(clusterName, service)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif lbName != \"\" {\n\t\tloadBalancer, _, err := az.getAzureLoadBalancer(lbName, azcache.CacheReadTypeDefault)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlb = \u0026loadBalancer\n\t}\n\n\tpipResourceGroup := az.getPublicIPAddressResourceGroup(service)\n\n\tpips, err := az.ListPIP(service, pipResourceGroup)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar (\n\t\tserviceAnnotationRequestsNamedPublicIP = shouldPIPExisted\n\t\tdiscoveredDesiredPublicIP bool\n\t\tdeletedDesiredPublicIP bool\n\t\tpipsToBeDeleted []*network.PublicIPAddress\n\t\tpipsToBeUpdated []*network.PublicIPAddress\n\t)\n\n\tfor i := range pips {\n\t\tpip := pips[i]\n\t\tpipName := *pip.Name\n\n\t\t// If we've been told to use a specific public ip by the client, let's track whether or not it actually existed\n\t\t// when we inspect the set in Azure.\n\t\tdiscoveredDesiredPublicIP = discoveredDesiredPublicIP || wantLb \u0026\u0026 !isInternal \u0026\u0026 pipName == desiredPipName\n\n\t\t// Now, let's perform additional analysis to determine if we should release the public ips we have found.\n\t\t// We can only let them go if (a) they are owned by this service and (b) they meet the criteria for deletion.\n\t\towns, isUserAssignedPIP := serviceOwnsPublicIP(service, \u0026pip, clusterName)\n\t\tif owns {\n\t\t\tvar dirtyPIP, toBeDeleted bool\n\t\t\tif !wantLb \u0026\u0026 !isUserAssignedPIP {\n\t\t\t\tklog.V(2).Infof(\"reconcilePublicIP for service(%s): unbinding the service from pip %s\", serviceName, *pip.Name)\n\t\t\t\terr = unbindServiceFromPIP(\u0026pip, serviceName)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tdirtyPIP = true\n\t\t\t}\n\t\t\tif !isUserAssignedPIP {\n\t\t\t\tchanged := az.ensurePIPTagged(service, \u0026pip)\n\t\t\t\tif changed {\n\t\t\t\t\tdirtyPIP = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif shouldReleaseExistingOwnedPublicIP(\u0026pip, wantLb, isInternal, isUserAssignedPIP, desiredPipName, serviceIPTagRequest) {\n\t\t\t\t// Then, release the public ip\n\t\t\t\tpipsToBeDeleted = append(pipsToBeDeleted, \u0026pip)\n\n\t\t\t\t// Flag if we deleted the desired public ip\n\t\t\t\tdeletedDesiredPublicIP = deletedDesiredPublicIP || pipName == desiredPipName\n\n\t\t\t\t// An aside: It would be unusual, but possible, for us to delete a public ip referred to explicitly by name\n\t\t\t\t// in Service annotations (which is usually reserved for non-service-owned externals), if that IP is tagged as\n\t\t\t\t// having been owned by a particular Kubernetes cluster.\n\n\t\t\t\t// If the pip is going to be deleted, we do not need to update it\n\t\t\t\ttoBeDeleted = true\n\t\t\t}\n\n\t\t\t// Update tags of PIP only instead of deleting it.\n\t\t\tif !toBeDeleted \u0026\u0026 dirtyPIP {\n\t\t\t\tpipsToBeUpdated = append(pipsToBeUpdated, \u0026pip)\n\t\t\t}\n\t\t}\n\t}\n\n\tif !isInternal \u0026\u0026 serviceAnnotationRequestsNamedPublicIP \u0026\u0026 !discoveredDesiredPublicIP \u0026\u0026 wantLb {\n\t\treturn nil, fmt.Errorf(\"reconcilePublicIP for service(%s): pip(%s) not found\", serviceName, desiredPipName)\n\t}\n\n\tvar deleteFuncs, updateFuncs []func() error\n\tfor _, pip := range pipsToBeUpdated {\n\t\tpipCopy := *pip\n\t\tupdateFuncs = append(updateFuncs, func() error {\n\t\t\tklog.V(2).Infof(\"reconcilePublicIP for service(%s): pip(%s) - updating\", serviceName, *pip.Name)\n\t\t\treturn az.CreateOrUpdatePIP(service, pipResourceGroup, pipCopy)\n\t\t})\n\t}\n\terrs := utilerrors.AggregateGoroutines(updateFuncs...)\n\tif errs != nil {\n\t\treturn nil, utilerrors.Flatten(errs)\n\t}\n\n\tfor _, pip := range pipsToBeDeleted {\n\t\tpipCopy := *pip\n\t\tdeleteFuncs = append(deleteFuncs, func() error {\n\t\t\tklog.V(2).Infof(\"reconcilePublicIP for service(%s): pip(%s) - deleting\", serviceName, *pip.Name)\n\t\t\treturn az.safeDeletePublicIP(service, pipResourceGroup, \u0026pipCopy, lb)\n\t\t})\n\t}\n\terrs = utilerrors.AggregateGoroutines(deleteFuncs...)\n\tif errs != nil {\n\t\treturn nil, utilerrors.Flatten(errs)\n\t}\n\n\tif !isInternal \u0026\u0026 wantLb {\n\t\t// Confirm desired public ip resource exists\n\t\tvar pip *network.PublicIPAddress\n\t\tdomainNameLabel, found := getPublicIPDomainNameLabel(service)\n\t\terrorIfPublicIPDoesNotExist := serviceAnnotationRequestsNamedPublicIP \u0026\u0026 discoveredDesiredPublicIP \u0026\u0026 !deletedDesiredPublicIP\n\t\tif pip, err = az.ensurePublicIPExists(service, desiredPipName, domainNameLabel, clusterName, errorIfPublicIPDoesNotExist, found); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn pip, nil\n\t}\n\treturn nil, nil\n}","line":{"from":2177,"to":2309}} {"id":100033219,"name":"safeDeletePublicIP","signature":"func (az *Cloud) safeDeletePublicIP(service *v1.Service, pipResourceGroup string, pip *network.PublicIPAddress, lb *network.LoadBalancer) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"// safeDeletePublicIP deletes public IP by removing its reference first.\nfunc (az *Cloud) safeDeletePublicIP(service *v1.Service, pipResourceGroup string, pip *network.PublicIPAddress, lb *network.LoadBalancer) error {\n\t// Remove references if pip.IPConfiguration is not nil.\n\tif pip.PublicIPAddressPropertiesFormat != nil \u0026\u0026\n\t\tpip.PublicIPAddressPropertiesFormat.IPConfiguration != nil \u0026\u0026\n\t\tlb != nil \u0026\u0026 lb.LoadBalancerPropertiesFormat != nil \u0026\u0026\n\t\tlb.LoadBalancerPropertiesFormat.FrontendIPConfigurations != nil {\n\t\treferencedLBRules := []network.SubResource{}\n\t\tfrontendIPConfigUpdated := false\n\t\tloadBalancerRuleUpdated := false\n\n\t\t// Check whether there are still frontend IP configurations referring to it.\n\t\tipConfigurationID := pointer.StringDeref(pip.PublicIPAddressPropertiesFormat.IPConfiguration.ID, \"\")\n\t\tif ipConfigurationID != \"\" {\n\t\t\tlbFrontendIPConfigs := *lb.LoadBalancerPropertiesFormat.FrontendIPConfigurations\n\t\t\tfor i := len(lbFrontendIPConfigs) - 1; i \u003e= 0; i-- {\n\t\t\t\tconfig := lbFrontendIPConfigs[i]\n\t\t\t\tif strings.EqualFold(ipConfigurationID, pointer.StringDeref(config.ID, \"\")) {\n\t\t\t\t\tif config.FrontendIPConfigurationPropertiesFormat != nil \u0026\u0026\n\t\t\t\t\t\tconfig.FrontendIPConfigurationPropertiesFormat.LoadBalancingRules != nil {\n\t\t\t\t\t\treferencedLBRules = *config.FrontendIPConfigurationPropertiesFormat.LoadBalancingRules\n\t\t\t\t\t}\n\n\t\t\t\t\tfrontendIPConfigUpdated = true\n\t\t\t\t\tlbFrontendIPConfigs = append(lbFrontendIPConfigs[:i], lbFrontendIPConfigs[i+1:]...)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif frontendIPConfigUpdated {\n\t\t\t\tlb.LoadBalancerPropertiesFormat.FrontendIPConfigurations = \u0026lbFrontendIPConfigs\n\t\t\t}\n\t\t}\n\n\t\t// Check whether there are still load balancer rules referring to it.\n\t\tif len(referencedLBRules) \u003e 0 {\n\t\t\treferencedLBRuleIDs := sets.NewString()\n\t\t\tfor _, refer := range referencedLBRules {\n\t\t\t\treferencedLBRuleIDs.Insert(pointer.StringDeref(refer.ID, \"\"))\n\t\t\t}\n\n\t\t\tif lb.LoadBalancerPropertiesFormat.LoadBalancingRules != nil {\n\t\t\t\tlbRules := *lb.LoadBalancerPropertiesFormat.LoadBalancingRules\n\t\t\t\tfor i := len(lbRules) - 1; i \u003e= 0; i-- {\n\t\t\t\t\truleID := pointer.StringDeref(lbRules[i].ID, \"\")\n\t\t\t\t\tif ruleID != \"\" \u0026\u0026 referencedLBRuleIDs.Has(ruleID) {\n\t\t\t\t\t\tloadBalancerRuleUpdated = true\n\t\t\t\t\t\tlbRules = append(lbRules[:i], lbRules[i+1:]...)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif loadBalancerRuleUpdated {\n\t\t\t\t\tlb.LoadBalancerPropertiesFormat.LoadBalancingRules = \u0026lbRules\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Update load balancer when frontendIPConfigUpdated or loadBalancerRuleUpdated.\n\t\tif frontendIPConfigUpdated || loadBalancerRuleUpdated {\n\t\t\terr := az.CreateOrUpdateLB(service, *lb)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"safeDeletePublicIP for service(%s) failed with error: %v\", getServiceName(service), err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tpipName := pointer.StringDeref(pip.Name, \"\")\n\tklog.V(10).Infof(\"DeletePublicIP(%s, %q): start\", pipResourceGroup, pipName)\n\terr := az.DeletePublicIP(service, pipResourceGroup, pipName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tklog.V(10).Infof(\"DeletePublicIP(%s, %q): end\", pipResourceGroup, pipName)\n\n\treturn nil\n}","line":{"from":2311,"to":2387}} {"id":100033220,"name":"findProbe","signature":"func findProbe(probes []network.Probe, probe network.Probe) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func findProbe(probes []network.Probe, probe network.Probe) bool {\n\tfor _, existingProbe := range probes {\n\t\tif strings.EqualFold(pointer.StringDeref(existingProbe.Name, \"\"), pointer.StringDeref(probe.Name, \"\")) \u0026\u0026 pointer.Int32Deref(existingProbe.Port, 0) == pointer.Int32Deref(probe.Port, 0) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":2389,"to":2396}} {"id":100033221,"name":"findRule","signature":"func findRule(rules []network.LoadBalancingRule, rule network.LoadBalancingRule, wantLB bool) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func findRule(rules []network.LoadBalancingRule, rule network.LoadBalancingRule, wantLB bool) bool {\n\tfor _, existingRule := range rules {\n\t\tif strings.EqualFold(pointer.StringDeref(existingRule.Name, \"\"), pointer.StringDeref(rule.Name, \"\")) \u0026\u0026\n\t\t\tequalLoadBalancingRulePropertiesFormat(existingRule.LoadBalancingRulePropertiesFormat, rule.LoadBalancingRulePropertiesFormat, wantLB) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":2398,"to":2406}} {"id":100033222,"name":"equalLoadBalancingRulePropertiesFormat","signature":"func equalLoadBalancingRulePropertiesFormat(s *network.LoadBalancingRulePropertiesFormat, t *network.LoadBalancingRulePropertiesFormat, wantLB bool) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"// equalLoadBalancingRulePropertiesFormat checks whether the provided LoadBalancingRulePropertiesFormat are equal.\n// Note: only fields used in reconcileLoadBalancer are considered.\nfunc equalLoadBalancingRulePropertiesFormat(s *network.LoadBalancingRulePropertiesFormat, t *network.LoadBalancingRulePropertiesFormat, wantLB bool) bool {\n\tif s == nil || t == nil {\n\t\treturn false\n\t}\n\n\tproperties := reflect.DeepEqual(s.Protocol, t.Protocol)\n\tif !properties {\n\t\treturn false\n\t}\n\n\tif reflect.DeepEqual(s.Protocol, network.TransportProtocolTCP) {\n\t\tproperties = properties \u0026\u0026 reflect.DeepEqual(pointer.BoolDeref(s.EnableTCPReset, false), pointer.BoolDeref(t.EnableTCPReset, false))\n\t}\n\n\tproperties = properties \u0026\u0026 reflect.DeepEqual(s.FrontendIPConfiguration, t.FrontendIPConfiguration) \u0026\u0026\n\t\treflect.DeepEqual(s.BackendAddressPool, t.BackendAddressPool) \u0026\u0026\n\t\treflect.DeepEqual(s.LoadDistribution, t.LoadDistribution) \u0026\u0026\n\t\treflect.DeepEqual(s.FrontendPort, t.FrontendPort) \u0026\u0026\n\t\treflect.DeepEqual(s.BackendPort, t.BackendPort) \u0026\u0026\n\t\treflect.DeepEqual(s.EnableFloatingIP, t.EnableFloatingIP) \u0026\u0026\n\t\treflect.DeepEqual(pointer.BoolDeref(s.DisableOutboundSnat, false), pointer.BoolDeref(t.DisableOutboundSnat, false))\n\n\tif wantLB \u0026\u0026 s.IdleTimeoutInMinutes != nil \u0026\u0026 t.IdleTimeoutInMinutes != nil {\n\t\treturn properties \u0026\u0026 reflect.DeepEqual(s.IdleTimeoutInMinutes, t.IdleTimeoutInMinutes)\n\t}\n\treturn properties\n}","line":{"from":2408,"to":2436}} {"id":100033223,"name":"findSecurityRule","signature":"func findSecurityRule(rules []network.SecurityRule, rule network.SecurityRule) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"// This compares rule's Name, Protocol, SourcePortRange, DestinationPortRange, SourceAddressPrefix, Access, and Direction.\n// Note that it compares rule's DestinationAddressPrefix only when it's not consolidated rule as such rule does not have DestinationAddressPrefix defined.\n// We intentionally do not compare DestinationAddressPrefixes in consolidated case because reconcileSecurityRule has to consider the two rules equal,\n// despite different DestinationAddressPrefixes, in order to give it a chance to consolidate the two rules.\nfunc findSecurityRule(rules []network.SecurityRule, rule network.SecurityRule) bool {\n\tfor _, existingRule := range rules {\n\t\tif !strings.EqualFold(pointer.StringDeref(existingRule.Name, \"\"), pointer.StringDeref(rule.Name, \"\")) {\n\t\t\tcontinue\n\t\t}\n\t\tif !strings.EqualFold(string(existingRule.Protocol), string(rule.Protocol)) {\n\t\t\tcontinue\n\t\t}\n\t\tif !strings.EqualFold(pointer.StringDeref(existingRule.SourcePortRange, \"\"), pointer.StringDeref(rule.SourcePortRange, \"\")) {\n\t\t\tcontinue\n\t\t}\n\t\tif !strings.EqualFold(pointer.StringDeref(existingRule.DestinationPortRange, \"\"), pointer.StringDeref(rule.DestinationPortRange, \"\")) {\n\t\t\tcontinue\n\t\t}\n\t\tif !strings.EqualFold(pointer.StringDeref(existingRule.SourceAddressPrefix, \"\"), pointer.StringDeref(rule.SourceAddressPrefix, \"\")) {\n\t\t\tcontinue\n\t\t}\n\t\tif !allowsConsolidation(existingRule) \u0026\u0026 !allowsConsolidation(rule) {\n\t\t\tif !strings.EqualFold(pointer.StringDeref(existingRule.DestinationAddressPrefix, \"\"), pointer.StringDeref(rule.DestinationAddressPrefix, \"\")) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif !strings.EqualFold(string(existingRule.Access), string(rule.Access)) {\n\t\t\tcontinue\n\t\t}\n\t\tif !strings.EqualFold(string(existingRule.Direction), string(rule.Direction)) {\n\t\t\tcontinue\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":2438,"to":2473}} {"id":100033224,"name":"getPublicIPAddressResourceGroup","signature":"func (az *Cloud) getPublicIPAddressResourceGroup(service *v1.Service) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func (az *Cloud) getPublicIPAddressResourceGroup(service *v1.Service) string {\n\tif resourceGroup, found := service.Annotations[ServiceAnnotationLoadBalancerResourceGroup]; found {\n\t\tresourceGroupName := strings.TrimSpace(resourceGroup)\n\t\tif len(resourceGroupName) \u003e 0 {\n\t\t\treturn resourceGroupName\n\t\t}\n\t}\n\n\treturn az.ResourceGroup\n}","line":{"from":2475,"to":2484}} {"id":100033225,"name":"isBackendPoolPreConfigured","signature":"func (az *Cloud) isBackendPoolPreConfigured(service *v1.Service) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func (az *Cloud) isBackendPoolPreConfigured(service *v1.Service) bool {\n\tpreConfigured := false\n\tisInternal := requiresInternalLoadBalancer(service)\n\n\tif az.PreConfiguredBackendPoolLoadBalancerTypes == PreConfiguredBackendPoolLoadBalancerTypesAll {\n\t\tpreConfigured = true\n\t}\n\tif (az.PreConfiguredBackendPoolLoadBalancerTypes == PreConfiguredBackendPoolLoadBalancerTypesInternal) \u0026\u0026 isInternal {\n\t\tpreConfigured = true\n\t}\n\tif (az.PreConfiguredBackendPoolLoadBalancerTypes == PreConfiguredBackendPoolLoadBalancerTypesExternal) \u0026\u0026 !isInternal {\n\t\tpreConfigured = true\n\t}\n\n\treturn preConfigured\n}","line":{"from":2486,"to":2501}} {"id":100033226,"name":"requiresInternalLoadBalancer","signature":"func requiresInternalLoadBalancer(service *v1.Service) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"// Check if service requires an internal load balancer.\nfunc requiresInternalLoadBalancer(service *v1.Service) bool {\n\tif l, found := service.Annotations[ServiceAnnotationLoadBalancerInternal]; found {\n\t\treturn l == \"true\"\n\t}\n\n\treturn false\n}","line":{"from":2503,"to":2510}} {"id":100033227,"name":"subnet","signature":"func subnet(service *v1.Service) *string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func subnet(service *v1.Service) *string {\n\tif requiresInternalLoadBalancer(service) {\n\t\tif l, found := service.Annotations[ServiceAnnotationLoadBalancerInternalSubnet]; found \u0026\u0026 strings.TrimSpace(l) != \"\" {\n\t\t\treturn \u0026l\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":2512,"to":2520}} {"id":100033228,"name":"getServiceLoadBalancerMode","signature":"func getServiceLoadBalancerMode(service *v1.Service) (hasMode bool, isAuto bool, vmSetNames []string)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"// getServiceLoadBalancerMode parses the mode value.\n// if the value is __auto__ it returns isAuto = TRUE.\n// if anything else it returns the unique VM set names after trimming spaces.\nfunc getServiceLoadBalancerMode(service *v1.Service) (hasMode bool, isAuto bool, vmSetNames []string) {\n\tmode, hasMode := service.Annotations[ServiceAnnotationLoadBalancerMode]\n\tmode = strings.TrimSpace(mode)\n\tisAuto = strings.EqualFold(mode, ServiceAnnotationLoadBalancerAutoModeValue)\n\tif !isAuto {\n\t\t// Break up list of \"AS1,AS2\"\n\t\tvmSetParsedList := strings.Split(mode, \",\")\n\n\t\t// Trim the VM set names and remove duplicates\n\t\t// e.g. {\"AS1\",\" AS2\", \"AS3\", \"AS3\"} =\u003e {\"AS1\", \"AS2\", \"AS3\"}\n\t\tvmSetNameSet := sets.NewString()\n\t\tfor _, v := range vmSetParsedList {\n\t\t\tvmSetNameSet.Insert(strings.TrimSpace(v))\n\t\t}\n\n\t\tvmSetNames = vmSetNameSet.List()\n\t}\n\n\treturn hasMode, isAuto, vmSetNames\n}","line":{"from":2522,"to":2544}} {"id":100033229,"name":"useSharedSecurityRule","signature":"func useSharedSecurityRule(service *v1.Service) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func useSharedSecurityRule(service *v1.Service) bool {\n\tif l, ok := service.Annotations[ServiceAnnotationSharedSecurityRule]; ok {\n\t\treturn l == \"true\"\n\t}\n\n\treturn false\n}","line":{"from":2546,"to":2552}} {"id":100033230,"name":"getServiceTags","signature":"func getServiceTags(service *v1.Service) []string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func getServiceTags(service *v1.Service) []string {\n\tif service == nil {\n\t\treturn nil\n\t}\n\n\tif serviceTags, found := service.Annotations[ServiceAnnotationAllowedServiceTag]; found {\n\t\tresult := []string{}\n\t\ttags := strings.Split(strings.TrimSpace(serviceTags), \",\")\n\t\tfor _, tag := range tags {\n\t\t\tserviceTag := strings.TrimSpace(tag)\n\t\t\tif serviceTag != \"\" {\n\t\t\t\tresult = append(result, serviceTag)\n\t\t\t}\n\t\t}\n\n\t\treturn result\n\t}\n\n\treturn nil\n}","line":{"from":2554,"to":2573}} {"id":100033231,"name":"serviceOwnsPublicIP","signature":"func serviceOwnsPublicIP(service *v1.Service, pip *network.PublicIPAddress, clusterName string) (bool, bool)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"// serviceOwnsPublicIP checks if the service owns the pip and if the pip is user-created.\n// The pip is user-created if and only if there is no service tags.\n// The service owns the pip if:\n// 1. The serviceName is included in the service tags of a system-created pip.\n// 2. The service.Spec.LoadBalancerIP matches the IP address of a user-created pip.\nfunc serviceOwnsPublicIP(service *v1.Service, pip *network.PublicIPAddress, clusterName string) (bool, bool) {\n\tif service == nil || pip == nil {\n\t\tklog.Warningf(\"serviceOwnsPublicIP: nil service or public IP\")\n\t\treturn false, false\n\t}\n\n\tif pip.PublicIPAddressPropertiesFormat == nil || pointer.StringDeref(pip.IPAddress, \"\") == \"\" {\n\t\tklog.Warningf(\"serviceOwnsPublicIP: empty pip.IPAddress\")\n\t\treturn false, false\n\t}\n\n\tserviceName := getServiceName(service)\n\n\tif pip.Tags != nil {\n\t\tserviceTag := pip.Tags[serviceTagKey]\n\t\tclusterTag := pip.Tags[clusterNameKey]\n\n\t\t// if there is no service tag on the pip, it is user-created pip\n\t\tif pointer.StringDeref(serviceTag, \"\") == \"\" {\n\t\t\treturn strings.EqualFold(pointer.StringDeref(pip.IPAddress, \"\"), service.Spec.LoadBalancerIP), true\n\t\t}\n\n\t\tif serviceTag != nil {\n\t\t\t// if there is service tag on the pip, it is system-created pip\n\t\t\tif isSVCNameInPIPTag(*serviceTag, serviceName) {\n\t\t\t\t// Backward compatible for clusters upgraded from old releases.\n\t\t\t\t// In such case, only \"service\" tag is set.\n\t\t\t\tif clusterTag == nil {\n\t\t\t\t\treturn true, false\n\t\t\t\t}\n\n\t\t\t\t// If cluster name tag is set, then return true if it matches.\n\t\t\t\tif *clusterTag == clusterName {\n\t\t\t\t\treturn true, false\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// if the service is not included in te tags of the system-created pip, check the ip address\n\t\t\t\t// this could happen for secondary services\n\t\t\t\treturn strings.EqualFold(pointer.StringDeref(pip.IPAddress, \"\"), service.Spec.LoadBalancerIP), false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false, false\n}","line":{"from":2575,"to":2624}} {"id":100033232,"name":"isSVCNameInPIPTag","signature":"func isSVCNameInPIPTag(tag, svcName string) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func isSVCNameInPIPTag(tag, svcName string) bool {\n\tsvcNames := parsePIPServiceTag(\u0026tag)\n\n\tfor _, name := range svcNames {\n\t\tif strings.EqualFold(name, svcName) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":2626,"to":2636}} {"id":100033233,"name":"parsePIPServiceTag","signature":"func parsePIPServiceTag(serviceTag *string) []string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func parsePIPServiceTag(serviceTag *string) []string {\n\tif serviceTag == nil {\n\t\treturn []string{}\n\t}\n\n\tserviceNames := strings.FieldsFunc(*serviceTag, func(r rune) bool {\n\t\treturn r == ','\n\t})\n\tfor i, name := range serviceNames {\n\t\tserviceNames[i] = strings.TrimSpace(name)\n\t}\n\n\treturn serviceNames\n}","line":{"from":2638,"to":2651}} {"id":100033234,"name":"bindServicesToPIP","signature":"func bindServicesToPIP(pip *network.PublicIPAddress, incomingServiceNames []string, replace bool) (bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"// bindServicesToPIP add the incoming service name to the PIP's tag\n// parameters: public IP address to be updated and incoming service names\n// return values:\n// 1. a bool flag to indicate if there is a new service added\n// 2. an error when the pip is nil\n// example:\n// \"ns1/svc1\" + [\"ns1/svc1\", \"ns2/svc2\"] = \"ns1/svc1,ns2/svc2\"\nfunc bindServicesToPIP(pip *network.PublicIPAddress, incomingServiceNames []string, replace bool) (bool, error) {\n\tif pip == nil {\n\t\treturn false, fmt.Errorf(\"nil public IP\")\n\t}\n\n\tif pip.Tags == nil {\n\t\tpip.Tags = map[string]*string{serviceTagKey: pointer.String(\"\")}\n\t}\n\n\tserviceTagValue := pip.Tags[serviceTagKey]\n\tserviceTagValueSet := make(map[string]struct{})\n\texistingServiceNames := parsePIPServiceTag(serviceTagValue)\n\taddedNew := false\n\n\t// replace is used when unbinding the service from PIP so addedNew remains false all the time\n\tif replace {\n\t\tserviceTagValue = pointer.String(strings.Join(incomingServiceNames, \",\"))\n\t\tpip.Tags[serviceTagKey] = serviceTagValue\n\n\t\treturn false, nil\n\t}\n\n\tfor _, name := range existingServiceNames {\n\t\tif _, ok := serviceTagValueSet[name]; !ok {\n\t\t\tserviceTagValueSet[name] = struct{}{}\n\t\t}\n\t}\n\n\tfor _, serviceName := range incomingServiceNames {\n\t\tif serviceTagValue == nil || *serviceTagValue == \"\" {\n\t\t\tserviceTagValue = pointer.String(serviceName)\n\t\t\taddedNew = true\n\t\t} else {\n\t\t\t// detect duplicates\n\t\t\tif _, ok := serviceTagValueSet[serviceName]; !ok {\n\t\t\t\t*serviceTagValue += fmt.Sprintf(\",%s\", serviceName)\n\t\t\t\taddedNew = true\n\t\t\t} else {\n\t\t\t\tklog.V(10).Infof(\"service %s has been bound to the pip already\", serviceName)\n\t\t\t}\n\t\t}\n\t}\n\tpip.Tags[serviceTagKey] = serviceTagValue\n\n\treturn addedNew, nil\n}","line":{"from":2653,"to":2705}} {"id":100033235,"name":"unbindServiceFromPIP","signature":"func unbindServiceFromPIP(pip *network.PublicIPAddress, serviceName string) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"func unbindServiceFromPIP(pip *network.PublicIPAddress, serviceName string) error {\n\tif pip == nil || pip.Tags == nil {\n\t\treturn fmt.Errorf(\"nil public IP or tags\")\n\t}\n\n\tserviceTagValue := pip.Tags[serviceTagKey]\n\texistingServiceNames := parsePIPServiceTag(serviceTagValue)\n\tvar found bool\n\tfor i := len(existingServiceNames) - 1; i \u003e= 0; i-- {\n\t\tif strings.EqualFold(existingServiceNames[i], serviceName) {\n\t\t\texistingServiceNames = append(existingServiceNames[:i], existingServiceNames[i+1:]...)\n\t\t\tfound = true\n\t\t}\n\t}\n\tif !found {\n\t\tklog.Warningf(\"cannot find the service %s in the corresponding PIP\", serviceName)\n\t}\n\n\t_, err := bindServicesToPIP(pip, existingServiceNames, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif existingServiceName, ok := pip.Tags[serviceUsingDNSKey]; ok {\n\t\tif strings.EqualFold(*existingServiceName, serviceName) {\n\t\t\tpip.Tags[serviceUsingDNSKey] = pointer.String(\"\")\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":2707,"to":2737}} {"id":100033236,"name":"ensureLoadBalancerTagged","signature":"func (az *Cloud) ensureLoadBalancerTagged(lb *network.LoadBalancer) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"// ensureLoadBalancerTagged ensures every load balancer in the resource group is tagged as configured\nfunc (az *Cloud) ensureLoadBalancerTagged(lb *network.LoadBalancer) bool {\n\tif az.Tags == \"\" {\n\t\treturn false\n\t}\n\ttags := parseTags(az.Tags)\n\tif lb.Tags == nil {\n\t\tlb.Tags = make(map[string]*string)\n\t}\n\n\ttags, changed := reconcileTags(lb.Tags, tags)\n\tlb.Tags = tags\n\n\treturn changed\n}","line":{"from":2739,"to":2753}} {"id":100033237,"name":"ensureSecurityGroupTagged","signature":"func (az *Cloud) ensureSecurityGroupTagged(sg *network.SecurityGroup) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_loadbalancer.go","code":"// ensureSecurityGroupTagged ensures the security group is tagged as configured\nfunc (az *Cloud) ensureSecurityGroupTagged(sg *network.SecurityGroup) bool {\n\tif az.Tags == \"\" {\n\t\treturn false\n\t}\n\ttags := parseTags(az.Tags)\n\tif sg.Tags == nil {\n\t\tsg.Tags = make(map[string]*string)\n\t}\n\n\ttags, changed := reconcileTags(sg.Tags, tags)\n\tsg.Tags = tags\n\n\treturn changed\n}","line":{"from":2755,"to":2769}} {"id":100033238,"name":"CreateManagedDisk","signature":"func (c *ManagedDiskController) CreateManagedDisk(options *ManagedDiskOptions) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_managedDiskController.go","code":"// CreateManagedDisk : create managed disk\nfunc (c *ManagedDiskController) CreateManagedDisk(options *ManagedDiskOptions) (string, error) {\n\tvar err error\n\tklog.V(4).Infof(\"azureDisk - creating new managed Name:%s StorageAccountType:%s Size:%v\", options.DiskName, options.StorageAccountType, options.SizeGB)\n\n\tvar createZones []string\n\tif len(options.AvailabilityZone) \u003e 0 {\n\t\trequestedZone := c.common.cloud.GetZoneID(options.AvailabilityZone)\n\t\tif requestedZone != \"\" {\n\t\t\tcreateZones = append(createZones, requestedZone)\n\t\t}\n\t}\n\n\t// insert original tags to newTags\n\tnewTags := make(map[string]*string)\n\tazureDDTag := \"kubernetes-azure-dd\"\n\tnewTags[\"created-by\"] = \u0026azureDDTag\n\tif options.Tags != nil {\n\t\tfor k, v := range options.Tags {\n\t\t\t// Azure won't allow / (forward slash) in tags\n\t\t\tnewKey := strings.Replace(k, \"/\", \"-\", -1)\n\t\t\tnewValue := strings.Replace(v, \"/\", \"-\", -1)\n\t\t\tnewTags[newKey] = \u0026newValue\n\t\t}\n\t}\n\n\tdiskSizeGB := int32(options.SizeGB)\n\tdiskSku := compute.DiskStorageAccountTypes(options.StorageAccountType)\n\n\tcreationData, err := getValidCreationData(c.common.subscriptionID, options.ResourceGroup, options.SourceResourceID, options.SourceType)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdiskProperties := compute.DiskProperties{\n\t\tDiskSizeGB: \u0026diskSizeGB,\n\t\tCreationData: \u0026creationData,\n\t}\n\n\tif diskSku == compute.UltraSSDLRS {\n\t\tdiskIOPSReadWrite := int64(defaultDiskIOPSReadWrite)\n\t\tif options.DiskIOPSReadWrite != \"\" {\n\t\t\tv, err := strconv.Atoi(options.DiskIOPSReadWrite)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", fmt.Errorf(\"AzureDisk - failed to parse DiskIOPSReadWrite: %v\", err)\n\t\t\t}\n\t\t\tdiskIOPSReadWrite = int64(v)\n\t\t}\n\t\tdiskProperties.DiskIOPSReadWrite = pointer.Int64(diskIOPSReadWrite)\n\n\t\tdiskMBpsReadWrite := int64(defaultDiskMBpsReadWrite)\n\t\tif options.DiskMBpsReadWrite != \"\" {\n\t\t\tv, err := strconv.Atoi(options.DiskMBpsReadWrite)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", fmt.Errorf(\"AzureDisk - failed to parse DiskMBpsReadWrite: %v\", err)\n\t\t\t}\n\t\t\tdiskMBpsReadWrite = int64(v)\n\t\t}\n\t\tdiskProperties.DiskMBpsReadWrite = pointer.Int64(diskMBpsReadWrite)\n\t} else {\n\t\tif options.DiskIOPSReadWrite != \"\" {\n\t\t\treturn \"\", fmt.Errorf(\"AzureDisk - DiskIOPSReadWrite parameter is only applicable in UltraSSD_LRS disk type\")\n\t\t}\n\t\tif options.DiskMBpsReadWrite != \"\" {\n\t\t\treturn \"\", fmt.Errorf(\"AzureDisk - DiskMBpsReadWrite parameter is only applicable in UltraSSD_LRS disk type\")\n\t\t}\n\t}\n\n\tif options.DiskEncryptionSetID != \"\" {\n\t\tif strings.Index(strings.ToLower(options.DiskEncryptionSetID), \"/subscriptions/\") != 0 {\n\t\t\treturn \"\", fmt.Errorf(\"AzureDisk - format of DiskEncryptionSetID(%s) is incorrect, correct format: %s\", options.DiskEncryptionSetID, diskEncryptionSetIDFormat)\n\t\t}\n\t\tdiskProperties.Encryption = \u0026compute.Encryption{\n\t\t\tDiskEncryptionSetID: \u0026options.DiskEncryptionSetID,\n\t\t\tType: compute.EncryptionAtRestWithCustomerKey,\n\t\t}\n\t}\n\n\tif options.MaxShares \u003e 1 {\n\t\tdiskProperties.MaxShares = \u0026options.MaxShares\n\t}\n\n\tmodel := compute.Disk{\n\t\tLocation: \u0026c.common.location,\n\t\tTags: newTags,\n\t\tSku: \u0026compute.DiskSku{\n\t\t\tName: diskSku,\n\t\t},\n\t\tDiskProperties: \u0026diskProperties,\n\t}\n\n\tif len(createZones) \u003e 0 {\n\t\tmodel.Zones = \u0026createZones\n\t}\n\n\tif options.ResourceGroup == \"\" {\n\t\toptions.ResourceGroup = c.common.resourceGroup\n\t}\n\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\trerr := c.common.cloud.DisksClient.CreateOrUpdate(ctx, options.ResourceGroup, options.DiskName, model)\n\tif rerr != nil {\n\t\treturn \"\", rerr.Error()\n\t}\n\n\tdiskID := \"\"\n\n\terr = kwait.ExponentialBackoff(defaultBackOff, func() (bool, error) {\n\t\tprovisionState, id, err := c.GetDisk(options.ResourceGroup, options.DiskName)\n\t\tdiskID = id\n\t\t// We are waiting for provisioningState==Succeeded\n\t\t// We don't want to hand-off managed disks to k8s while they are\n\t\t//still being provisioned, this is to avoid some race conditions\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif strings.ToLower(provisionState) == \"succeeded\" {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n\n\tif err != nil {\n\t\tklog.V(2).Infof(\"azureDisk - created new MD Name:%s StorageAccountType:%s Size:%v but was unable to confirm provisioningState in poll process\", options.DiskName, options.StorageAccountType, options.SizeGB)\n\t} else {\n\t\tklog.V(2).Infof(\"azureDisk - created new MD Name:%s StorageAccountType:%s Size:%v\", options.DiskName, options.StorageAccountType, options.SizeGB)\n\t}\n\n\treturn diskID, nil\n}","line":{"from":84,"to":213}} {"id":100033239,"name":"DeleteManagedDisk","signature":"func (c *ManagedDiskController) DeleteManagedDisk(diskURI string) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_managedDiskController.go","code":"// DeleteManagedDisk : delete managed disk\nfunc (c *ManagedDiskController) DeleteManagedDisk(diskURI string) error {\n\tdiskName := path.Base(diskURI)\n\tresourceGroup, err := getResourceGroupFromDiskURI(diskURI)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\n\tif _, ok := c.common.diskAttachDetachMap.Load(strings.ToLower(diskURI)); ok {\n\t\treturn fmt.Errorf(\"failed to delete disk(%s) since it's in attaching or detaching state\", diskURI)\n\t}\n\n\tdisk, rerr := c.common.cloud.DisksClient.Get(ctx, resourceGroup, diskName)\n\tif rerr != nil {\n\t\tif rerr.HTTPStatusCode == http.StatusNotFound {\n\t\t\tklog.V(2).Infof(\"azureDisk - disk(%s) is already deleted\", diskURI)\n\t\t\treturn nil\n\t\t}\n\t\treturn rerr.Error()\n\t}\n\n\tif disk.ManagedBy != nil {\n\t\treturn fmt.Errorf(\"disk(%s) already attached to node(%s), could not be deleted\", diskURI, *disk.ManagedBy)\n\t}\n\n\trerr = c.common.cloud.DisksClient.Delete(ctx, resourceGroup, diskName)\n\tif rerr != nil {\n\t\tif rerr.HTTPStatusCode == http.StatusNotFound {\n\t\t\tklog.V(2).Infof(\"azureDisk - disk(%s) is already deleted\", diskURI)\n\t\t\treturn nil\n\t\t}\n\t\treturn rerr.Error()\n\t}\n\t// We don't need poll here, k8s will immediately stop referencing the disk\n\t// the disk will be eventually deleted - cleanly - by ARM\n\n\tklog.V(2).Infof(\"azureDisk - deleted a managed disk: %s\", diskURI)\n\n\treturn nil\n}","line":{"from":215,"to":257}} {"id":100033240,"name":"GetDisk","signature":"func (c *ManagedDiskController) GetDisk(resourceGroup, diskName string) (string, string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_managedDiskController.go","code":"// GetDisk return: disk provisionState, diskID, error\nfunc (c *ManagedDiskController) GetDisk(resourceGroup, diskName string) (string, string, error) {\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\n\tresult, rerr := c.common.cloud.DisksClient.Get(ctx, resourceGroup, diskName)\n\tif rerr != nil {\n\t\treturn \"\", \"\", rerr.Error()\n\t}\n\n\tif result.DiskProperties != nil \u0026\u0026 (*result.DiskProperties).ProvisioningState != nil {\n\t\treturn *(*result.DiskProperties).ProvisioningState, *result.ID, nil\n\t}\n\n\treturn \"\", \"\", nil\n}","line":{"from":259,"to":274}} {"id":100033241,"name":"ResizeDisk","signature":"func (c *ManagedDiskController) ResizeDisk(diskURI string, oldSize resource.Quantity, newSize resource.Quantity) (resource.Quantity, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_managedDiskController.go","code":"// ResizeDisk Expand the disk to new size\nfunc (c *ManagedDiskController) ResizeDisk(diskURI string, oldSize resource.Quantity, newSize resource.Quantity) (resource.Quantity, error) {\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\n\tdiskName := path.Base(diskURI)\n\tresourceGroup, err := getResourceGroupFromDiskURI(diskURI)\n\tif err != nil {\n\t\treturn oldSize, err\n\t}\n\n\tresult, rerr := c.common.cloud.DisksClient.Get(ctx, resourceGroup, diskName)\n\tif rerr != nil {\n\t\treturn oldSize, rerr.Error()\n\t}\n\n\tif result.DiskProperties == nil || result.DiskProperties.DiskSizeGB == nil {\n\t\treturn oldSize, fmt.Errorf(\"DiskProperties of disk(%s) is nil\", diskName)\n\t}\n\n\t// Azure resizes in chunks of GiB (not GB)\n\trequestGiB, err := volumehelpers.RoundUpToGiBInt32(newSize)\n\tif err != nil {\n\t\treturn oldSize, err\n\t}\n\n\tnewSizeQuant := resource.MustParse(fmt.Sprintf(\"%dGi\", requestGiB))\n\n\tklog.V(2).Infof(\"azureDisk - begin to resize disk(%s) with new size(%d), old size(%v)\", diskName, requestGiB, oldSize)\n\t// If disk already of greater or equal size than requested we return\n\tif *result.DiskProperties.DiskSizeGB \u003e= requestGiB {\n\t\treturn newSizeQuant, nil\n\t}\n\n\tif result.DiskProperties.DiskState != compute.Unattached {\n\t\treturn oldSize, fmt.Errorf(\"azureDisk - disk resize is only supported on Unattached disk, current disk state: %s, already attached to %s\", result.DiskProperties.DiskState, pointer.StringDeref(result.ManagedBy, \"\"))\n\t}\n\n\tdiskParameter := compute.DiskUpdate{\n\t\tDiskUpdateProperties: \u0026compute.DiskUpdateProperties{\n\t\t\tDiskSizeGB: \u0026requestGiB,\n\t\t},\n\t}\n\n\tctx, cancel = getContextWithCancel()\n\tdefer cancel()\n\tif rerr := c.common.cloud.DisksClient.Update(ctx, resourceGroup, diskName, diskParameter); rerr != nil {\n\t\treturn oldSize, rerr.Error()\n\t}\n\n\tklog.V(2).Infof(\"azureDisk - resize disk(%s) with new size(%d) completed\", diskName, requestGiB)\n\n\treturn newSizeQuant, nil\n}","line":{"from":276,"to":329}} {"id":100033242,"name":"getResourceGroupFromDiskURI","signature":"func getResourceGroupFromDiskURI(diskURI string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_managedDiskController.go","code":"// get resource group name from a managed disk URI, e.g. return {group-name} according to\n// /subscriptions/{sub-id}/resourcegroups/{group-name}/providers/microsoft.compute/disks/{disk-id}\n// according to https://docs.microsoft.com/en-us/rest/api/compute/disks/get\nfunc getResourceGroupFromDiskURI(diskURI string) (string, error) {\n\tfields := strings.Split(diskURI, \"/\")\n\tif len(fields) != 9 || strings.ToLower(fields[3]) != \"resourcegroups\" {\n\t\treturn \"\", fmt.Errorf(\"invalid disk URI: %s\", diskURI)\n\t}\n\treturn fields[4], nil\n}","line":{"from":331,"to":340}} {"id":100033243,"name":"GetLabelsForVolume","signature":"func (c *Cloud) GetLabelsForVolume(ctx context.Context, pv *v1.PersistentVolume) (map[string]string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_managedDiskController.go","code":"// GetLabelsForVolume implements PVLabeler.GetLabelsForVolume\nfunc (c *Cloud) GetLabelsForVolume(ctx context.Context, pv *v1.PersistentVolume) (map[string]string, error) {\n\t// Ignore if not AzureDisk.\n\tif pv.Spec.AzureDisk == nil {\n\t\treturn nil, nil\n\t}\n\n\t// Ignore any volumes that are being provisioned\n\tif pv.Spec.AzureDisk.DiskName == cloudvolume.ProvisionedVolumeName {\n\t\treturn nil, nil\n\t}\n\n\treturn c.GetAzureDiskLabels(pv.Spec.AzureDisk.DataDiskURI)\n}","line":{"from":342,"to":355}} {"id":100033244,"name":"GetAzureDiskLabels","signature":"func (c *Cloud) GetAzureDiskLabels(diskURI string) (map[string]string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_managedDiskController.go","code":"// GetAzureDiskLabels gets availability zone labels for Azuredisk.\nfunc (c *Cloud) GetAzureDiskLabels(diskURI string) (map[string]string, error) {\n\t// Get disk's resource group.\n\tdiskName := path.Base(diskURI)\n\tresourceGroup, err := getResourceGroupFromDiskURI(diskURI)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get resource group for AzureDisk %q: %v\", diskName, err)\n\t\treturn nil, err\n\t}\n\n\tlabels := map[string]string{\n\t\tv1.LabelTopologyRegion: c.Location,\n\t}\n\t// no azure credential is set, return nil\n\tif c.DisksClient == nil {\n\t\treturn labels, nil\n\t}\n\t// Get information of the disk.\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\tdisk, rerr := c.DisksClient.Get(ctx, resourceGroup, diskName)\n\tif rerr != nil {\n\t\tklog.Errorf(\"Failed to get information for AzureDisk %q: %v\", diskName, rerr)\n\t\treturn nil, rerr.Error()\n\t}\n\n\t// Check whether availability zone is specified.\n\tif disk.Zones == nil || len(*disk.Zones) == 0 {\n\t\tklog.V(4).Infof(\"Azure disk %q is not zoned\", diskName)\n\t\treturn labels, nil\n\t}\n\n\tzones := *disk.Zones\n\tzoneID, err := strconv.Atoi(zones[0])\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse zone %v for AzureDisk %v: %v\", zones, diskName, err)\n\t}\n\n\tzone := c.makeZone(c.Location, zoneID)\n\tklog.V(4).Infof(\"Got zone %q for Azure disk %q\", zone, diskName)\n\tlabels[v1.LabelTopologyZone] = zone\n\treturn labels, nil\n}","line":{"from":357,"to":399}} {"id":100033245,"name":"InitializeCloudProviderRateLimitConfig","signature":"func InitializeCloudProviderRateLimitConfig(config *CloudProviderRateLimitConfig)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_ratelimit.go","code":"// InitializeCloudProviderRateLimitConfig initializes rate limit configs.\nfunc InitializeCloudProviderRateLimitConfig(config *CloudProviderRateLimitConfig) {\n\tif config == nil {\n\t\treturn\n\t}\n\n\t// Assign read rate limit defaults if no configuration was passed in.\n\tif config.CloudProviderRateLimitQPS == 0 {\n\t\tconfig.CloudProviderRateLimitQPS = rateLimitQPSDefault\n\t}\n\tif config.CloudProviderRateLimitBucket == 0 {\n\t\tconfig.CloudProviderRateLimitBucket = rateLimitBucketDefault\n\t}\n\t// Assign write rate limit defaults if no configuration was passed in.\n\tif config.CloudProviderRateLimitQPSWrite == 0 {\n\t\tconfig.CloudProviderRateLimitQPSWrite = config.CloudProviderRateLimitQPS\n\t}\n\tif config.CloudProviderRateLimitBucketWrite == 0 {\n\t\tconfig.CloudProviderRateLimitBucketWrite = config.CloudProviderRateLimitBucket\n\t}\n\n\tconfig.RouteRateLimit = overrideDefaultRateLimitConfig(\u0026config.RateLimitConfig, config.RouteRateLimit)\n\tconfig.SubnetsRateLimit = overrideDefaultRateLimitConfig(\u0026config.RateLimitConfig, config.SubnetsRateLimit)\n\tconfig.InterfaceRateLimit = overrideDefaultRateLimitConfig(\u0026config.RateLimitConfig, config.InterfaceRateLimit)\n\tconfig.RouteTableRateLimit = overrideDefaultRateLimitConfig(\u0026config.RateLimitConfig, config.RouteTableRateLimit)\n\tconfig.LoadBalancerRateLimit = overrideDefaultRateLimitConfig(\u0026config.RateLimitConfig, config.LoadBalancerRateLimit)\n\tconfig.PublicIPAddressRateLimit = overrideDefaultRateLimitConfig(\u0026config.RateLimitConfig, config.PublicIPAddressRateLimit)\n\tconfig.SecurityGroupRateLimit = overrideDefaultRateLimitConfig(\u0026config.RateLimitConfig, config.SecurityGroupRateLimit)\n\tconfig.VirtualMachineRateLimit = overrideDefaultRateLimitConfig(\u0026config.RateLimitConfig, config.VirtualMachineRateLimit)\n\tconfig.StorageAccountRateLimit = overrideDefaultRateLimitConfig(\u0026config.RateLimitConfig, config.StorageAccountRateLimit)\n\tconfig.DiskRateLimit = overrideDefaultRateLimitConfig(\u0026config.RateLimitConfig, config.DiskRateLimit)\n\tconfig.SnapshotRateLimit = overrideDefaultRateLimitConfig(\u0026config.RateLimitConfig, config.SnapshotRateLimit)\n\tconfig.VirtualMachineScaleSetRateLimit = overrideDefaultRateLimitConfig(\u0026config.RateLimitConfig, config.VirtualMachineScaleSetRateLimit)\n\tconfig.VirtualMachineSizeRateLimit = overrideDefaultRateLimitConfig(\u0026config.RateLimitConfig, config.VirtualMachineSizeRateLimit)\n}","line":{"from":47,"to":81}} {"id":100033246,"name":"overrideDefaultRateLimitConfig","signature":"func overrideDefaultRateLimitConfig(defaults, config *azclients.RateLimitConfig) *azclients.RateLimitConfig","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_ratelimit.go","code":"// overrideDefaultRateLimitConfig overrides the default CloudProviderRateLimitConfig.\nfunc overrideDefaultRateLimitConfig(defaults, config *azclients.RateLimitConfig) *azclients.RateLimitConfig {\n\t// If config not set, apply defaults.\n\tif config == nil {\n\t\treturn defaults\n\t}\n\n\t// Remain disabled if it's set explicitly.\n\tif !config.CloudProviderRateLimit {\n\t\treturn \u0026azclients.RateLimitConfig{CloudProviderRateLimit: false}\n\t}\n\n\t// Apply default values.\n\tif config.CloudProviderRateLimitQPS == 0 {\n\t\tconfig.CloudProviderRateLimitQPS = defaults.CloudProviderRateLimitQPS\n\t}\n\tif config.CloudProviderRateLimitBucket == 0 {\n\t\tconfig.CloudProviderRateLimitBucket = defaults.CloudProviderRateLimitBucket\n\t}\n\tif config.CloudProviderRateLimitQPSWrite == 0 {\n\t\tconfig.CloudProviderRateLimitQPSWrite = defaults.CloudProviderRateLimitQPSWrite\n\t}\n\tif config.CloudProviderRateLimitBucketWrite == 0 {\n\t\tconfig.CloudProviderRateLimitBucketWrite = defaults.CloudProviderRateLimitBucketWrite\n\t}\n\n\treturn config\n}","line":{"from":83,"to":110}} {"id":100033247,"name":"wait","signature":"func (op *delayedRouteOperation) wait() error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_routes.go","code":"// wait waits for the operation completion and returns the result.\nfunc (op *delayedRouteOperation) wait() error {\n\treturn \u003c-op.result\n}","line":{"from":69,"to":72}} {"id":100033248,"name":"newDelayedRouteUpdater","signature":"func newDelayedRouteUpdater(az *Cloud, interval time.Duration) *delayedRouteUpdater","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_routes.go","code":"// newDelayedRouteUpdater creates a new delayedRouteUpdater.\nfunc newDelayedRouteUpdater(az *Cloud, interval time.Duration) *delayedRouteUpdater {\n\treturn \u0026delayedRouteUpdater{\n\t\taz: az,\n\t\tinterval: interval,\n\t\troutesToUpdate: make([]*delayedRouteOperation, 0),\n\t}\n}","line":{"from":88,"to":95}} {"id":100033249,"name":"run","signature":"func (d *delayedRouteUpdater) run()","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_routes.go","code":"// run starts the updater reconciling loop.\nfunc (d *delayedRouteUpdater) run() {\n\terr := wait.PollImmediateInfinite(d.interval, func() (bool, error) {\n\t\td.updateRoutes()\n\t\treturn false, nil\n\t})\n\tif err != nil { // this should never happen, if it does, panic\n\t\tpanic(err)\n\t}\n}","line":{"from":97,"to":106}} {"id":100033250,"name":"updateRoutes","signature":"func (d *delayedRouteUpdater) updateRoutes()","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_routes.go","code":"// updateRoutes invokes route table client to update all routes.\nfunc (d *delayedRouteUpdater) updateRoutes() {\n\td.lock.Lock()\n\tdefer d.lock.Unlock()\n\n\t// No need to do any updating.\n\tif len(d.routesToUpdate) == 0 {\n\t\tklog.V(6).Info(\"updateRoutes: nothing to update, returning\")\n\t\treturn\n\t}\n\n\tvar err error\n\tdefer func() {\n\t\t// Notify all the goroutines.\n\t\tfor _, rt := range d.routesToUpdate {\n\t\t\trt.result \u003c- err\n\t\t}\n\t\t// Clear all the jobs.\n\t\td.routesToUpdate = make([]*delayedRouteOperation, 0)\n\t}()\n\n\tvar (\n\t\trouteTable network.RouteTable\n\t\texistsRouteTable bool\n\t)\n\trouteTable, existsRouteTable, err = d.az.getRouteTable(azcache.CacheReadTypeDefault)\n\tif err != nil {\n\t\tklog.Errorf(\"getRouteTable() failed with error: %v\", err)\n\t\treturn\n\t}\n\n\t// create route table if it doesn't exists yet.\n\tif !existsRouteTable {\n\t\terr = d.az.createRouteTable()\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"createRouteTable() failed with error: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\trouteTable, _, err = d.az.getRouteTable(azcache.CacheReadTypeDefault)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"getRouteTable() failed with error: %v\", err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// reconcile routes.\n\tdirty, onlyUpdateTags := false, true\n\troutes := []network.Route{}\n\tif routeTable.Routes != nil {\n\t\troutes = *routeTable.Routes\n\t}\n\n\troutes, dirty = d.cleanupOutdatedRoutes(routes)\n\tif dirty {\n\t\tonlyUpdateTags = false\n\t}\n\n\tfor _, rt := range d.routesToUpdate {\n\t\tif rt.operation == routeTableOperationUpdateTags {\n\t\t\trouteTable.Tags = rt.routeTableTags\n\t\t\tdirty = true\n\t\t\tcontinue\n\t\t}\n\n\t\trouteMatch := false\n\t\tonlyUpdateTags = false\n\t\tfor i, existingRoute := range routes {\n\t\t\tif strings.EqualFold(pointer.StringDeref(existingRoute.Name, \"\"), pointer.StringDeref(rt.route.Name, \"\")) {\n\t\t\t\t// delete the name-matched routes here (missing routes would be added later if the operation is add).\n\t\t\t\troutes = append(routes[:i], routes[i+1:]...)\n\t\t\t\tif existingRoute.RoutePropertiesFormat != nil \u0026\u0026\n\t\t\t\t\trt.route.RoutePropertiesFormat != nil \u0026\u0026\n\t\t\t\t\tstrings.EqualFold(pointer.StringDeref(existingRoute.AddressPrefix, \"\"), pointer.StringDeref(rt.route.AddressPrefix, \"\")) \u0026\u0026\n\t\t\t\t\tstrings.EqualFold(pointer.StringDeref(existingRoute.NextHopIPAddress, \"\"), pointer.StringDeref(rt.route.NextHopIPAddress, \"\")) {\n\t\t\t\t\trouteMatch = true\n\t\t\t\t}\n\t\t\t\tif rt.operation == routeOperationDelete {\n\t\t\t\t\tdirty = true\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// Add missing routes if the operation is add.\n\t\tif rt.operation == routeOperationAdd {\n\t\t\troutes = append(routes, rt.route)\n\t\t\tif !routeMatch {\n\t\t\t\tdirty = true\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t}\n\n\tif dirty {\n\t\tif !onlyUpdateTags {\n\t\t\tklog.V(2).Infof(\"updateRoutes: updating routes\")\n\t\t\trouteTable.Routes = \u0026routes\n\t\t}\n\t\terr = d.az.CreateOrUpdateRouteTable(routeTable)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"CreateOrUpdateRouteTable() failed with error: %v\", err)\n\t\t\treturn\n\t\t}\n\t}\n}","line":{"from":108,"to":213}} {"id":100033251,"name":"cleanupOutdatedRoutes","signature":"func (d *delayedRouteUpdater) cleanupOutdatedRoutes(existingRoutes []network.Route) (routes []network.Route, changed bool)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_routes.go","code":"// cleanupOutdatedRoutes deletes all non-dualstack routes when dualstack is enabled,\n// and deletes all dualstack routes when dualstack is not enabled.\nfunc (d *delayedRouteUpdater) cleanupOutdatedRoutes(existingRoutes []network.Route) (routes []network.Route, changed bool) {\n\tfor i := len(existingRoutes) - 1; i \u003e= 0; i-- {\n\t\texistingRouteName := pointer.StringDeref(existingRoutes[i].Name, \"\")\n\t\tsplit := strings.Split(existingRouteName, routeNameSeparator)\n\n\t\tklog.V(4).Infof(\"cleanupOutdatedRoutes: checking route %s\", existingRouteName)\n\n\t\t// filter out unmanaged routes\n\t\tdeleteRoute := false\n\t\tif d.az.nodeNames.Has(split[0]) {\n\t\t\tif d.az.ipv6DualStackEnabled \u0026\u0026 len(split) == 1 {\n\t\t\t\tklog.V(2).Infof(\"cleanupOutdatedRoutes: deleting outdated non-dualstack route %s\", existingRouteName)\n\t\t\t\tdeleteRoute = true\n\t\t\t} else if !d.az.ipv6DualStackEnabled \u0026\u0026 len(split) == 2 {\n\t\t\t\tklog.V(2).Infof(\"cleanupOutdatedRoutes: deleting outdated dualstack route %s\", existingRouteName)\n\t\t\t\tdeleteRoute = true\n\t\t\t}\n\n\t\t\tif deleteRoute {\n\t\t\t\texistingRoutes = append(existingRoutes[:i], existingRoutes[i+1:]...)\n\t\t\t\tchanged = true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn existingRoutes, changed\n}","line":{"from":215,"to":243}} {"id":100033252,"name":"addRouteOperation","signature":"func (d *delayedRouteUpdater) addRouteOperation(operation routeOperation, route network.Route) (*delayedRouteOperation, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_routes.go","code":"// addRouteOperation adds the routeOperation to delayedRouteUpdater and returns a delayedRouteOperation.\nfunc (d *delayedRouteUpdater) addRouteOperation(operation routeOperation, route network.Route) (*delayedRouteOperation, error) {\n\td.lock.Lock()\n\tdefer d.lock.Unlock()\n\n\top := \u0026delayedRouteOperation{\n\t\troute: route,\n\t\toperation: operation,\n\t\tresult: make(chan error),\n\t}\n\td.routesToUpdate = append(d.routesToUpdate, op)\n\treturn op, nil\n}","line":{"from":245,"to":257}} {"id":100033253,"name":"addUpdateRouteTableTagsOperation","signature":"func (d *delayedRouteUpdater) addUpdateRouteTableTagsOperation(operation routeOperation, tags map[string]*string) (*delayedRouteOperation, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_routes.go","code":"// addUpdateRouteTableTagsOperation adds a update route table tags operation to delayedRouteUpdater and returns a delayedRouteOperation.\nfunc (d *delayedRouteUpdater) addUpdateRouteTableTagsOperation(operation routeOperation, tags map[string]*string) (*delayedRouteOperation, error) {\n\td.lock.Lock()\n\tdefer d.lock.Unlock()\n\n\top := \u0026delayedRouteOperation{\n\t\trouteTableTags: tags,\n\t\toperation: operation,\n\t\tresult: make(chan error),\n\t}\n\td.routesToUpdate = append(d.routesToUpdate, op)\n\treturn op, nil\n}","line":{"from":259,"to":271}} {"id":100033254,"name":"ListRoutes","signature":"func (az *Cloud) ListRoutes(ctx context.Context, clusterName string) ([]*cloudprovider.Route, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_routes.go","code":"// ListRoutes lists all managed routes that belong to the specified clusterName\nfunc (az *Cloud) ListRoutes(ctx context.Context, clusterName string) ([]*cloudprovider.Route, error) {\n\tklog.V(10).Infof(\"ListRoutes: START clusterName=%q\", clusterName)\n\trouteTable, existsRouteTable, err := az.getRouteTable(azcache.CacheReadTypeDefault)\n\troutes, err := processRoutes(az.ipv6DualStackEnabled, routeTable, existsRouteTable, err)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Compose routes for unmanaged routes so that node controller won't retry creating routes for them.\n\tunmanagedNodes, err := az.GetUnmanagedNodes()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taz.routeCIDRsLock.Lock()\n\tdefer az.routeCIDRsLock.Unlock()\n\tfor _, nodeName := range unmanagedNodes.List() {\n\t\tif cidr, ok := az.routeCIDRs[nodeName]; ok {\n\t\t\troutes = append(routes, \u0026cloudprovider.Route{\n\t\t\t\tName: nodeName,\n\t\t\t\tTargetNode: mapRouteNameToNodeName(az.ipv6DualStackEnabled, nodeName),\n\t\t\t\tDestinationCIDR: cidr,\n\t\t\t})\n\t\t}\n\t}\n\n\t// ensure the route table is tagged as configured\n\ttags, changed := az.ensureRouteTableTagged(\u0026routeTable)\n\tif changed {\n\t\tklog.V(2).Infof(\"ListRoutes: updating tags on route table %s\", pointer.StringDeref(routeTable.Name, \"\"))\n\t\top, err := az.routeUpdater.addUpdateRouteTableTagsOperation(routeTableOperationUpdateTags, tags)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"ListRoutes: failed to add route table operation with error: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Wait for operation complete.\n\t\terr = op.wait()\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"ListRoutes: failed to update route table tags with error: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn routes, nil\n}","line":{"from":273,"to":318}} {"id":100033255,"name":"processRoutes","signature":"func processRoutes(ipv6DualStackEnabled bool, routeTable network.RouteTable, exists bool, err error) ([]*cloudprovider.Route, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_routes.go","code":"// Injectable for testing\nfunc processRoutes(ipv6DualStackEnabled bool, routeTable network.RouteTable, exists bool, err error) ([]*cloudprovider.Route, error) {\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn []*cloudprovider.Route{}, nil\n\t}\n\n\tvar kubeRoutes []*cloudprovider.Route\n\tif routeTable.RouteTablePropertiesFormat != nil \u0026\u0026 routeTable.Routes != nil {\n\t\tkubeRoutes = make([]*cloudprovider.Route, len(*routeTable.Routes))\n\t\tfor i, route := range *routeTable.Routes {\n\t\t\tinstance := mapRouteNameToNodeName(ipv6DualStackEnabled, *route.Name)\n\t\t\tcidr := *route.AddressPrefix\n\t\t\tklog.V(10).Infof(\"ListRoutes: * instance=%q, cidr=%q\", instance, cidr)\n\n\t\t\tkubeRoutes[i] = \u0026cloudprovider.Route{\n\t\t\t\tName: *route.Name,\n\t\t\t\tTargetNode: instance,\n\t\t\t\tDestinationCIDR: cidr,\n\t\t\t}\n\t\t}\n\t}\n\n\tklog.V(10).Info(\"ListRoutes: FINISH\")\n\treturn kubeRoutes, nil\n}","line":{"from":320,"to":347}} {"id":100033256,"name":"createRouteTable","signature":"func (az *Cloud) createRouteTable() error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_routes.go","code":"func (az *Cloud) createRouteTable() error {\n\trouteTable := network.RouteTable{\n\t\tName: pointer.String(az.RouteTableName),\n\t\tLocation: pointer.String(az.Location),\n\t\tRouteTablePropertiesFormat: \u0026network.RouteTablePropertiesFormat{},\n\t}\n\n\tklog.V(3).Infof(\"createRouteTableIfNotExists: creating routetable. routeTableName=%q\", az.RouteTableName)\n\terr := az.CreateOrUpdateRouteTable(routeTable)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Invalidate the cache right after updating\n\taz.rtCache.Delete(az.RouteTableName)\n\treturn nil\n}","line":{"from":349,"to":365}} {"id":100033257,"name":"CreateRoute","signature":"func (az *Cloud) CreateRoute(ctx context.Context, clusterName string, nameHint string, kubeRoute *cloudprovider.Route) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_routes.go","code":"// CreateRoute creates the described managed route\n// route.Name will be ignored, although the cloud-provider may use nameHint\n// to create a more user-meaningful name.\nfunc (az *Cloud) CreateRoute(ctx context.Context, clusterName string, nameHint string, kubeRoute *cloudprovider.Route) error {\n\tmc := metrics.NewMetricContext(\"routes\", \"create_route\", az.ResourceGroup, az.SubscriptionID, \"\")\n\tisOperationSucceeded := false\n\tdefer func() {\n\t\tmc.ObserveOperationWithResult(isOperationSucceeded)\n\t}()\n\n\t// Returns for unmanaged nodes because azure cloud provider couldn't fetch information for them.\n\tvar targetIP string\n\tnodeName := string(kubeRoute.TargetNode)\n\tunmanaged, err := az.IsNodeUnmanaged(nodeName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif unmanaged {\n\t\tif az.ipv6DualStackEnabled {\n\t\t\t//TODO (khenidak) add support for unmanaged nodes when the feature reaches beta\n\t\t\treturn fmt.Errorf(\"unmanaged nodes are not supported in dual stack mode\")\n\t\t}\n\t\tklog.V(2).Infof(\"CreateRoute: omitting unmanaged node %q\", kubeRoute.TargetNode)\n\t\taz.routeCIDRsLock.Lock()\n\t\tdefer az.routeCIDRsLock.Unlock()\n\t\taz.routeCIDRs[nodeName] = kubeRoute.DestinationCIDR\n\t\treturn nil\n\t}\n\n\tCIDRv6 := utilnet.IsIPv6CIDRString(string(kubeRoute.DestinationCIDR))\n\t// if single stack IPv4 then get the IP for the primary ip config\n\t// single stack IPv6 is supported on dual stack host. So the IPv6 IP is secondary IP for both single stack IPv6 and dual stack\n\t// Get all private IPs for the machine and find the first one that matches the IPv6 family\n\tif !az.ipv6DualStackEnabled \u0026\u0026 !CIDRv6 {\n\t\ttargetIP, _, err = az.getIPForMachine(kubeRoute.TargetNode)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t// for dual stack and single stack IPv6 we need to select\n\t\t// a private ip that matches family of the cidr\n\t\tklog.V(4).Infof(\"CreateRoute: create route instance=%q cidr=%q is in dual stack mode\", kubeRoute.TargetNode, kubeRoute.DestinationCIDR)\n\t\tnodePrivateIPs, err := az.getPrivateIPsForMachine(kubeRoute.TargetNode)\n\t\tif nil != err {\n\t\t\tklog.V(3).Infof(\"CreateRoute: create route: failed(GetPrivateIPsByNodeName) instance=%q cidr=%q with error=%v\", kubeRoute.TargetNode, kubeRoute.DestinationCIDR, err)\n\t\t\treturn err\n\t\t}\n\n\t\ttargetIP, err = findFirstIPByFamily(nodePrivateIPs, CIDRv6)\n\t\tif nil != err {\n\t\t\tklog.V(3).Infof(\"CreateRoute: create route: failed(findFirstIpByFamily) instance=%q cidr=%q with error=%v\", kubeRoute.TargetNode, kubeRoute.DestinationCIDR, err)\n\t\t\treturn err\n\t\t}\n\t}\n\trouteName := mapNodeNameToRouteName(az.ipv6DualStackEnabled, kubeRoute.TargetNode, string(kubeRoute.DestinationCIDR))\n\troute := network.Route{\n\t\tName: pointer.String(routeName),\n\t\tRoutePropertiesFormat: \u0026network.RoutePropertiesFormat{\n\t\t\tAddressPrefix: pointer.String(kubeRoute.DestinationCIDR),\n\t\t\tNextHopType: network.RouteNextHopTypeVirtualAppliance,\n\t\t\tNextHopIPAddress: pointer.String(targetIP),\n\t\t},\n\t}\n\n\tklog.V(2).Infof(\"CreateRoute: creating route for clusterName=%q instance=%q cidr=%q\", clusterName, kubeRoute.TargetNode, kubeRoute.DestinationCIDR)\n\top, err := az.routeUpdater.addRouteOperation(routeOperationAdd, route)\n\tif err != nil {\n\t\tklog.Errorf(\"CreateRoute failed for node %q with error: %v\", kubeRoute.TargetNode, err)\n\t\treturn err\n\t}\n\n\t// Wait for operation complete.\n\terr = op.wait()\n\tif err != nil {\n\t\tklog.Errorf(\"CreateRoute failed for node %q with error: %v\", kubeRoute.TargetNode, err)\n\t\treturn err\n\t}\n\n\tklog.V(2).Infof(\"CreateRoute: route created. clusterName=%q instance=%q cidr=%q\", clusterName, kubeRoute.TargetNode, kubeRoute.DestinationCIDR)\n\tisOperationSucceeded = true\n\n\treturn nil\n}","line":{"from":367,"to":449}} {"id":100033258,"name":"DeleteRoute","signature":"func (az *Cloud) DeleteRoute(ctx context.Context, clusterName string, kubeRoute *cloudprovider.Route) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_routes.go","code":"// DeleteRoute deletes the specified managed route\n// Route should be as returned by ListRoutes\nfunc (az *Cloud) DeleteRoute(ctx context.Context, clusterName string, kubeRoute *cloudprovider.Route) error {\n\tmc := metrics.NewMetricContext(\"routes\", \"delete_route\", az.ResourceGroup, az.SubscriptionID, \"\")\n\tisOperationSucceeded := false\n\tdefer func() {\n\t\tmc.ObserveOperationWithResult(isOperationSucceeded)\n\t}()\n\n\t// Returns for unmanaged nodes because azure cloud provider couldn't fetch information for them.\n\tnodeName := string(kubeRoute.TargetNode)\n\tunmanaged, err := az.IsNodeUnmanaged(nodeName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif unmanaged {\n\t\tklog.V(2).Infof(\"DeleteRoute: omitting unmanaged node %q\", kubeRoute.TargetNode)\n\t\taz.routeCIDRsLock.Lock()\n\t\tdefer az.routeCIDRsLock.Unlock()\n\t\tdelete(az.routeCIDRs, nodeName)\n\t\treturn nil\n\t}\n\n\trouteName := mapNodeNameToRouteName(az.ipv6DualStackEnabled, kubeRoute.TargetNode, string(kubeRoute.DestinationCIDR))\n\tklog.V(2).Infof(\"DeleteRoute: deleting route. clusterName=%q instance=%q cidr=%q routeName=%q\", clusterName, kubeRoute.TargetNode, kubeRoute.DestinationCIDR, routeName)\n\troute := network.Route{\n\t\tName: pointer.String(routeName),\n\t\tRoutePropertiesFormat: \u0026network.RoutePropertiesFormat{},\n\t}\n\top, err := az.routeUpdater.addRouteOperation(routeOperationDelete, route)\n\tif err != nil {\n\t\tklog.Errorf(\"DeleteRoute failed for node %q with error: %v\", kubeRoute.TargetNode, err)\n\t\treturn err\n\t}\n\n\t// Wait for operation complete.\n\terr = op.wait()\n\tif err != nil {\n\t\tklog.Errorf(\"DeleteRoute failed for node %q with error: %v\", kubeRoute.TargetNode, err)\n\t\treturn err\n\t}\n\n\t// Remove outdated ipv4 routes as well\n\tif az.ipv6DualStackEnabled {\n\t\trouteNameWithoutIPV6Suffix := strings.Split(routeName, routeNameSeparator)[0]\n\t\tklog.V(2).Infof(\"DeleteRoute: deleting route. clusterName=%q instance=%q cidr=%q routeName=%q\", clusterName, kubeRoute.TargetNode, kubeRoute.DestinationCIDR, routeNameWithoutIPV6Suffix)\n\t\troute := network.Route{\n\t\t\tName: pointer.String(routeNameWithoutIPV6Suffix),\n\t\t\tRoutePropertiesFormat: \u0026network.RoutePropertiesFormat{},\n\t\t}\n\t\top, err := az.routeUpdater.addRouteOperation(routeOperationDelete, route)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"DeleteRoute failed for node %q with error: %v\", kubeRoute.TargetNode, err)\n\t\t\treturn err\n\t\t}\n\n\t\t// Wait for operation complete.\n\t\terr = op.wait()\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"DeleteRoute failed for node %q with error: %v\", kubeRoute.TargetNode, err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tklog.V(2).Infof(\"DeleteRoute: route deleted. clusterName=%q instance=%q cidr=%q\", clusterName, kubeRoute.TargetNode, kubeRoute.DestinationCIDR)\n\tisOperationSucceeded = true\n\n\treturn nil\n}","line":{"from":451,"to":519}} {"id":100033259,"name":"mapNodeNameToRouteName","signature":"func mapNodeNameToRouteName(ipv6DualStackEnabled bool, nodeName types.NodeName, cidr string) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_routes.go","code":"// This must be kept in sync with mapRouteNameToNodeName.\n// These two functions enable stashing the instance name in the route\n// and then retrieving it later when listing. This is needed because\n// Azure does not let you put tags/descriptions on the Route itself.\nfunc mapNodeNameToRouteName(ipv6DualStackEnabled bool, nodeName types.NodeName, cidr string) string {\n\tif !ipv6DualStackEnabled {\n\t\treturn fmt.Sprintf(\"%s\", nodeName)\n\t}\n\treturn fmt.Sprintf(routeNameFmt, nodeName, cidrtoRfc1035(cidr))\n}","line":{"from":521,"to":530}} {"id":100033260,"name":"mapRouteNameToNodeName","signature":"func mapRouteNameToNodeName(ipv6DualStackEnabled bool, routeName string) types.NodeName","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_routes.go","code":"// Used with mapNodeNameToRouteName. See comment on mapNodeNameToRouteName.\nfunc mapRouteNameToNodeName(ipv6DualStackEnabled bool, routeName string) types.NodeName {\n\tif !ipv6DualStackEnabled {\n\t\treturn types.NodeName(routeName)\n\t}\n\tparts := strings.Split(routeName, routeNameSeparator)\n\tnodeName := parts[0]\n\treturn types.NodeName(nodeName)\n\n}","line":{"from":532,"to":541}} {"id":100033261,"name":"findFirstIPByFamily","signature":"func findFirstIPByFamily(ips []string, v6 bool) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_routes.go","code":"// given a list of ips, return the first one\n// that matches the family requested\n// error if no match, or failure to parse\n// any of the ips\nfunc findFirstIPByFamily(ips []string, v6 bool) (string, error) {\n\tfor _, ip := range ips {\n\t\tbIPv6 := utilnet.IsIPv6String(ip)\n\t\tif v6 == bIPv6 {\n\t\t\treturn ip, nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"no match found matching the ipfamily requested\")\n}","line":{"from":543,"to":555}} {"id":100033262,"name":"cidrtoRfc1035","signature":"func cidrtoRfc1035(cidr string) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_routes.go","code":"// strips : . /\nfunc cidrtoRfc1035(cidr string) string {\n\tcidr = strings.ReplaceAll(cidr, \":\", \"\")\n\tcidr = strings.ReplaceAll(cidr, \".\", \"\")\n\tcidr = strings.ReplaceAll(cidr, \"/\", \"\")\n\treturn cidr\n}","line":{"from":557,"to":563}} {"id":100033263,"name":"ensureRouteTableTagged","signature":"func (az *Cloud) ensureRouteTableTagged(rt *network.RouteTable) (map[string]*string, bool)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_routes.go","code":"// ensureRouteTableTagged ensures the route table is tagged as configured\nfunc (az *Cloud) ensureRouteTableTagged(rt *network.RouteTable) (map[string]*string, bool) {\n\tif az.Tags == \"\" {\n\t\treturn nil, false\n\t}\n\ttags := parseTags(az.Tags)\n\tif rt.Tags == nil {\n\t\trt.Tags = make(map[string]*string)\n\t}\n\n\ttags, changed := reconcileTags(rt.Tags, tags)\n\trt.Tags = tags\n\n\treturn rt.Tags, changed\n}","line":{"from":565,"to":579}} {"id":100033264,"name":"getStandardMachineID","signature":"func (az *Cloud) getStandardMachineID(subscriptionID, resourceGroup, machineName string) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// getStandardMachineID returns the full identifier of a virtual machine.\nfunc (az *Cloud) getStandardMachineID(subscriptionID, resourceGroup, machineName string) string {\n\treturn fmt.Sprintf(\n\t\tmachineIDTemplate,\n\t\tsubscriptionID,\n\t\tstrings.ToLower(resourceGroup),\n\t\tmachineName)\n}","line":{"from":80,"to":87}} {"id":100033265,"name":"getAvailabilitySetID","signature":"func (az *Cloud) getAvailabilitySetID(resourceGroup, availabilitySetName string) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// returns the full identifier of an availabilitySet\nfunc (az *Cloud) getAvailabilitySetID(resourceGroup, availabilitySetName string) string {\n\treturn fmt.Sprintf(\n\t\tavailabilitySetIDTemplate,\n\t\taz.SubscriptionID,\n\t\tresourceGroup,\n\t\tavailabilitySetName)\n}","line":{"from":89,"to":96}} {"id":100033266,"name":"getFrontendIPConfigID","signature":"func (az *Cloud) getFrontendIPConfigID(lbName, rgName, fipConfigName string) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// returns the full identifier of a loadbalancer frontendipconfiguration.\nfunc (az *Cloud) getFrontendIPConfigID(lbName, rgName, fipConfigName string) string {\n\treturn fmt.Sprintf(\n\t\tfrontendIPConfigIDTemplate,\n\t\taz.getNetworkResourceSubscriptionID(),\n\t\trgName,\n\t\tlbName,\n\t\tfipConfigName)\n}","line":{"from":98,"to":106}} {"id":100033267,"name":"getBackendPoolID","signature":"func (az *Cloud) getBackendPoolID(lbName, rgName, backendPoolName string) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// returns the full identifier of a loadbalancer backendpool.\nfunc (az *Cloud) getBackendPoolID(lbName, rgName, backendPoolName string) string {\n\treturn fmt.Sprintf(\n\t\tbackendPoolIDTemplate,\n\t\taz.getNetworkResourceSubscriptionID(),\n\t\trgName,\n\t\tlbName,\n\t\tbackendPoolName)\n}","line":{"from":108,"to":116}} {"id":100033268,"name":"getLoadBalancerProbeID","signature":"func (az *Cloud) getLoadBalancerProbeID(lbName, rgName, lbRuleName string) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// returns the full identifier of a loadbalancer probe.\nfunc (az *Cloud) getLoadBalancerProbeID(lbName, rgName, lbRuleName string) string {\n\treturn fmt.Sprintf(\n\t\tloadBalancerProbeIDTemplate,\n\t\taz.getNetworkResourceSubscriptionID(),\n\t\trgName,\n\t\tlbName,\n\t\tlbRuleName)\n}","line":{"from":118,"to":126}} {"id":100033269,"name":"getNetworkResourceSubscriptionID","signature":"func (az *Cloud) getNetworkResourceSubscriptionID() string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// getNetworkResourceSubscriptionID returns the subscription id which hosts network resources\nfunc (az *Cloud) getNetworkResourceSubscriptionID() string {\n\tif az.Config.UsesNetworkResourceInDifferentTenant() {\n\t\treturn az.NetworkResourceSubscriptionID\n\t}\n\treturn az.SubscriptionID\n}","line":{"from":128,"to":134}} {"id":100033270,"name":"mapLoadBalancerNameToVMSet","signature":"func (az *Cloud) mapLoadBalancerNameToVMSet(lbName string, clusterName string) (vmSetName string)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"func (az *Cloud) mapLoadBalancerNameToVMSet(lbName string, clusterName string) (vmSetName string) {\n\tvmSetName = strings.TrimSuffix(lbName, InternalLoadBalancerNameSuffix)\n\tif strings.EqualFold(clusterName, vmSetName) {\n\t\tvmSetName = az.VMSet.GetPrimaryVMSetName()\n\t}\n\n\treturn vmSetName\n}","line":{"from":136,"to":143}} {"id":100033271,"name":"getAzureLoadBalancerName","signature":"func (az *Cloud) getAzureLoadBalancerName(clusterName string, vmSetName string, isInternal bool) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// For a load balancer, all frontend ip should reference either a subnet or publicIpAddress.\n// Thus Azure do not allow mixed type (public and internal) load balancer.\n// So we'd have a separate name for internal load balancer.\n// This would be the name for Azure LoadBalancer resource.\nfunc (az *Cloud) getAzureLoadBalancerName(clusterName string, vmSetName string, isInternal bool) string {\n\tif az.LoadBalancerName != \"\" {\n\t\tclusterName = az.LoadBalancerName\n\t}\n\tlbNamePrefix := vmSetName\n\t// The LB name prefix is set to the name of the cluster when:\n\t// 1. the LB belongs to the primary agent pool.\n\t// 2. using the single SLB;\n\tuseSingleSLB := az.useStandardLoadBalancer() \u0026\u0026 !az.EnableMultipleStandardLoadBalancers\n\tif strings.EqualFold(vmSetName, az.VMSet.GetPrimaryVMSetName()) || useSingleSLB {\n\t\tlbNamePrefix = clusterName\n\t}\n\tif isInternal {\n\t\treturn fmt.Sprintf(\"%s%s\", lbNamePrefix, InternalLoadBalancerNameSuffix)\n\t}\n\treturn lbNamePrefix\n}","line":{"from":145,"to":165}} {"id":100033272,"name":"isMasterNode","signature":"func isMasterNode(node *v1.Node) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// isMasterNode returns true if the node has a master role label.\n// The master role is determined by looking for:\n// * a kubernetes.io/role=\"master\" label\nfunc isMasterNode(node *v1.Node) bool {\n\tif val, ok := node.Labels[nodeLabelRole]; ok \u0026\u0026 val == \"master\" {\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":167,"to":176}} {"id":100033273,"name":"getLastSegment","signature":"func getLastSegment(ID, separator string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// returns the deepest child's identifier from a full identifier string.\nfunc getLastSegment(ID, separator string) (string, error) {\n\tparts := strings.Split(ID, separator)\n\tname := parts[len(parts)-1]\n\tif len(name) == 0 {\n\t\treturn \"\", fmt.Errorf(\"resource name was missing from identifier\")\n\t}\n\n\treturn name, nil\n}","line":{"from":178,"to":187}} {"id":100033274,"name":"getProtocolsFromKubernetesProtocol","signature":"func getProtocolsFromKubernetesProtocol(protocol v1.Protocol) (*network.TransportProtocol, *network.SecurityRuleProtocol, *network.ProbeProtocol, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// returns the equivalent LoadBalancerRule, SecurityRule and LoadBalancerProbe\n// protocol types for the given Kubernetes protocol type.\nfunc getProtocolsFromKubernetesProtocol(protocol v1.Protocol) (*network.TransportProtocol, *network.SecurityRuleProtocol, *network.ProbeProtocol, error) {\n\tvar transportProto network.TransportProtocol\n\tvar securityProto network.SecurityRuleProtocol\n\tvar probeProto network.ProbeProtocol\n\n\tswitch protocol {\n\tcase v1.ProtocolTCP:\n\t\ttransportProto = network.TransportProtocolTCP\n\t\tsecurityProto = network.SecurityRuleProtocolTCP\n\t\tprobeProto = network.ProbeProtocolTCP\n\t\treturn \u0026transportProto, \u0026securityProto, \u0026probeProto, nil\n\tcase v1.ProtocolUDP:\n\t\ttransportProto = network.TransportProtocolUDP\n\t\tsecurityProto = network.SecurityRuleProtocolUDP\n\t\treturn \u0026transportProto, \u0026securityProto, nil, nil\n\tdefault:\n\t\treturn \u0026transportProto, \u0026securityProto, \u0026probeProto, fmt.Errorf(\"only TCP and UDP are supported for Azure LoadBalancers\")\n\t}\n\n}","line":{"from":189,"to":210}} {"id":100033275,"name":"getPrimaryInterfaceID","signature":"func getPrimaryInterfaceID(machine compute.VirtualMachine) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// This returns the full identifier of the primary NIC for the given VM.\nfunc getPrimaryInterfaceID(machine compute.VirtualMachine) (string, error) {\n\tif len(*machine.NetworkProfile.NetworkInterfaces) == 1 {\n\t\treturn *(*machine.NetworkProfile.NetworkInterfaces)[0].ID, nil\n\t}\n\n\tfor _, ref := range *machine.NetworkProfile.NetworkInterfaces {\n\t\tif pointer.BoolDeref(ref.Primary, false) {\n\t\t\treturn *ref.ID, nil\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"failed to find a primary nic for the vm. vmname=%q\", *machine.Name)\n}","line":{"from":212,"to":225}} {"id":100033276,"name":"getPrimaryIPConfig","signature":"func getPrimaryIPConfig(nic network.Interface) (*network.InterfaceIPConfiguration, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"func getPrimaryIPConfig(nic network.Interface) (*network.InterfaceIPConfiguration, error) {\n\tif nic.IPConfigurations == nil {\n\t\treturn nil, fmt.Errorf(\"nic.IPConfigurations for nic (nicname=%q) is nil\", *nic.Name)\n\t}\n\n\tif len(*nic.IPConfigurations) == 1 {\n\t\treturn \u0026((*nic.IPConfigurations)[0]), nil\n\t}\n\n\tfor _, ref := range *nic.IPConfigurations {\n\t\tif *ref.Primary {\n\t\t\treturn \u0026ref, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"failed to determine the primary ipconfig. nicname=%q\", *nic.Name)\n}","line":{"from":227,"to":243}} {"id":100033277,"name":"getIPConfigByIPFamily","signature":"func getIPConfigByIPFamily(nic network.Interface, IPv6 bool) (*network.InterfaceIPConfiguration, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// returns first ip configuration on a nic by family\nfunc getIPConfigByIPFamily(nic network.Interface, IPv6 bool) (*network.InterfaceIPConfiguration, error) {\n\tif nic.IPConfigurations == nil {\n\t\treturn nil, fmt.Errorf(\"nic.IPConfigurations for nic (nicname=%q) is nil\", *nic.Name)\n\t}\n\n\tvar ipVersion network.IPVersion\n\tif IPv6 {\n\t\tipVersion = network.IPv6\n\t} else {\n\t\tipVersion = network.IPv4\n\t}\n\tfor _, ref := range *nic.IPConfigurations {\n\t\tif ref.PrivateIPAddress != nil \u0026\u0026 ref.PrivateIPAddressVersion == ipVersion {\n\t\t\treturn \u0026ref, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"failed to determine the ipconfig(IPv6=%v). nicname=%q\", IPv6, pointer.StringDeref(nic.Name, \"\"))\n}","line":{"from":245,"to":263}} {"id":100033278,"name":"isInternalLoadBalancer","signature":"func isInternalLoadBalancer(lb *network.LoadBalancer) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"func isInternalLoadBalancer(lb *network.LoadBalancer) bool {\n\treturn strings.HasSuffix(*lb.Name, InternalLoadBalancerNameSuffix)\n}","line":{"from":265,"to":267}} {"id":100033279,"name":"getBackendPoolName","signature":"func getBackendPoolName(clusterName string, service *v1.Service) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// getBackendPoolName the LB BackendPool name for a service.\n// to ensure backward and forward compat:\n// SingleStack -v4 (pre v1.16) =\u003e BackendPool name == clusterName\n// SingleStack -v6 =\u003e BackendPool name == \u003cclusterName\u003e-IPv6 (all cluster bootstrap uses this name)\n// DualStack\n//\n//\t\t=\u003e IPv4 BackendPool name == clusterName\n//\t =\u003e IPv6 BackendPool name == \u003cclusterName\u003e-IPv6\n//\n// This means:\n// clusters moving from IPv4 to dualstack will require no changes\n// clusters moving from IPv6 to dualstack will require no changes as the IPv4 backend pool will created with \u003cclusterName\u003e\nfunc getBackendPoolName(clusterName string, service *v1.Service) string {\n\tIPv6 := utilnet.IsIPv6String(service.Spec.ClusterIP)\n\tif IPv6 {\n\t\treturn fmt.Sprintf(\"%v-IPv6\", clusterName)\n\t}\n\n\treturn clusterName\n}","line":{"from":269,"to":288}} {"id":100033280,"name":"getLoadBalancerRuleName","signature":"func (az *Cloud) getLoadBalancerRuleName(service *v1.Service, protocol v1.Protocol, port int32) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"func (az *Cloud) getLoadBalancerRuleName(service *v1.Service, protocol v1.Protocol, port int32) string {\n\tprefix := az.getRulePrefix(service)\n\truleName := fmt.Sprintf(\"%s-%s-%d\", prefix, protocol, port)\n\tsubnet := subnet(service)\n\tif subnet == nil {\n\t\treturn ruleName\n\t}\n\n\t// Load balancer rule name must be less or equal to 80 characters, so excluding the hyphen two segments cannot exceed 79\n\tsubnetSegment := *subnet\n\tif len(ruleName)+len(subnetSegment)+1 \u003e loadBalancerRuleNameMaxLength {\n\t\tsubnetSegment = subnetSegment[:loadBalancerRuleNameMaxLength-len(ruleName)-1]\n\t}\n\n\treturn fmt.Sprintf(\"%s-%s-%s-%d\", prefix, subnetSegment, protocol, port)\n}","line":{"from":290,"to":305}} {"id":100033281,"name":"getSecurityRuleName","signature":"func (az *Cloud) getSecurityRuleName(service *v1.Service, port v1.ServicePort, sourceAddrPrefix string) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"func (az *Cloud) getSecurityRuleName(service *v1.Service, port v1.ServicePort, sourceAddrPrefix string) string {\n\tif useSharedSecurityRule(service) {\n\t\tsafePrefix := strings.Replace(sourceAddrPrefix, \"/\", \"_\", -1)\n\t\treturn fmt.Sprintf(\"shared-%s-%d-%s\", port.Protocol, port.Port, safePrefix)\n\t}\n\tsafePrefix := strings.Replace(sourceAddrPrefix, \"/\", \"_\", -1)\n\trulePrefix := az.getRulePrefix(service)\n\treturn fmt.Sprintf(\"%s-%s-%d-%s\", rulePrefix, port.Protocol, port.Port, safePrefix)\n}","line":{"from":307,"to":315}} {"id":100033282,"name":"getServiceName","signature":"func getServiceName(service *v1.Service) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// This returns a human-readable version of the Service used to tag some resources.\n// This is only used for human-readable convenience, and not to filter.\nfunc getServiceName(service *v1.Service) string {\n\treturn fmt.Sprintf(\"%s/%s\", service.Namespace, service.Name)\n}","line":{"from":317,"to":321}} {"id":100033283,"name":"getRulePrefix","signature":"func (az *Cloud) getRulePrefix(service *v1.Service) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// This returns a prefix for loadbalancer/security rules.\nfunc (az *Cloud) getRulePrefix(service *v1.Service) string {\n\treturn az.GetLoadBalancerName(context.TODO(), \"\", service)\n}","line":{"from":323,"to":326}} {"id":100033284,"name":"getPublicIPName","signature":"func (az *Cloud) getPublicIPName(clusterName string, service *v1.Service) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"func (az *Cloud) getPublicIPName(clusterName string, service *v1.Service) string {\n\treturn fmt.Sprintf(\"%s-%s\", clusterName, az.GetLoadBalancerName(context.TODO(), clusterName, service))\n}","line":{"from":328,"to":330}} {"id":100033285,"name":"serviceOwnsRule","signature":"func (az *Cloud) serviceOwnsRule(service *v1.Service, rule string) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"func (az *Cloud) serviceOwnsRule(service *v1.Service, rule string) bool {\n\tprefix := az.getRulePrefix(service)\n\treturn strings.HasPrefix(strings.ToUpper(rule), strings.ToUpper(prefix))\n}","line":{"from":332,"to":335}} {"id":100033286,"name":"serviceOwnsFrontendIP","signature":"func (az *Cloud) serviceOwnsFrontendIP(fip network.FrontendIPConfiguration, service *v1.Service) (bool, bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// There are two cases when a service owns the frontend IP config:\n// 1. The primary service, which means the frontend IP config is created after the creation of the service.\n// This means the name of the config can be tracked by the service UID.\n// 2. The secondary services must have their loadBalancer IP set if they want to share the same config as the primary\n// service. Hence, it can be tracked by the loadBalancer IP.\nfunc (az *Cloud) serviceOwnsFrontendIP(fip network.FrontendIPConfiguration, service *v1.Service) (bool, bool, error) {\n\tvar isPrimaryService bool\n\tbaseName := az.GetLoadBalancerName(context.TODO(), \"\", service)\n\tif strings.HasPrefix(pointer.StringDeref(fip.Name, \"\"), baseName) {\n\t\tklog.V(6).Infof(\"serviceOwnsFrontendIP: found primary service %s of the \"+\n\t\t\t\"frontend IP config %s\", service.Name, *fip.Name)\n\t\tisPrimaryService = true\n\t\treturn true, isPrimaryService, nil\n\t}\n\n\tloadBalancerIP := service.Spec.LoadBalancerIP\n\tif loadBalancerIP == \"\" {\n\t\t// it is a must that the secondary services set the loadBalancer IP\n\t\treturn false, isPrimaryService, nil\n\t}\n\n\t// for external secondary service the public IP address should be checked\n\tif !requiresInternalLoadBalancer(service) {\n\t\tpipResourceGroup := az.getPublicIPAddressResourceGroup(service)\n\t\tpip, err := az.findMatchedPIPByLoadBalancerIP(service, loadBalancerIP, pipResourceGroup)\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"serviceOwnsFrontendIP: unexpected error when finding match public IP of the service %s with loadBalancerLP %s: %v\", service.Name, loadBalancerIP, err)\n\t\t\treturn false, isPrimaryService, nil\n\t\t}\n\t\tif pip != nil \u0026\u0026\n\t\t\tpip.ID != nil \u0026\u0026\n\t\t\tpip.PublicIPAddressPropertiesFormat != nil \u0026\u0026\n\t\t\tpip.IPAddress != nil \u0026\u0026\n\t\t\tfip.FrontendIPConfigurationPropertiesFormat != nil \u0026\u0026\n\t\t\tfip.FrontendIPConfigurationPropertiesFormat.PublicIPAddress != nil {\n\t\t\tif strings.EqualFold(pointer.StringDeref(pip.ID, \"\"), pointer.StringDeref(fip.PublicIPAddress.ID, \"\")) {\n\t\t\t\tklog.V(4).Infof(\"serviceOwnsFrontendIP: found secondary service %s of the frontend IP config %s\", service.Name, *fip.Name)\n\n\t\t\t\treturn true, isPrimaryService, nil\n\t\t\t}\n\t\t\tklog.V(4).Infof(\"serviceOwnsFrontendIP: the public IP with ID %s is being referenced by other service with public IP address %s\", *pip.ID, *pip.IPAddress)\n\n\t\t\treturn false, isPrimaryService, nil\n\t\t}\n\n\t\treturn false, isPrimaryService, nil\n\t}\n\n\t// for internal secondary service the private IP address on the frontend IP config should be checked\n\tif fip.PrivateIPAddress == nil {\n\t\treturn false, isPrimaryService, nil\n\t}\n\n\treturn strings.EqualFold(*fip.PrivateIPAddress, loadBalancerIP), isPrimaryService, nil\n}","line":{"from":337,"to":391}} {"id":100033287,"name":"getDefaultFrontendIPConfigName","signature":"func (az *Cloud) getDefaultFrontendIPConfigName(service *v1.Service) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"func (az *Cloud) getDefaultFrontendIPConfigName(service *v1.Service) string {\n\tbaseName := az.GetLoadBalancerName(context.TODO(), \"\", service)\n\tsubnetName := subnet(service)\n\tif subnetName != nil {\n\t\tipcName := fmt.Sprintf(\"%s-%s\", baseName, *subnetName)\n\n\t\t// Azure lb front end configuration name must not exceed 80 characters\n\t\tif len(ipcName) \u003e frontendIPConfigNameMaxLength {\n\t\t\tipcName = ipcName[:frontendIPConfigNameMaxLength]\n\t\t}\n\t\treturn ipcName\n\t}\n\treturn baseName\n}","line":{"from":393,"to":406}} {"id":100033288,"name":"getNextAvailablePriority","signature":"func getNextAvailablePriority(rules []network.SecurityRule) (int32, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// This returns the next available rule priority level for a given set of security rules.\nfunc getNextAvailablePriority(rules []network.SecurityRule) (int32, error) {\n\tvar smallest int32 = loadBalancerMinimumPriority\n\tvar spread int32 = 1\n\nouter:\n\tfor smallest \u003c loadBalancerMaximumPriority {\n\t\tfor _, rule := range rules {\n\t\t\tif *rule.Priority == smallest {\n\t\t\t\tsmallest += spread\n\t\t\t\tcontinue outer\n\t\t\t}\n\t\t}\n\t\t// no one else had it\n\t\treturn smallest, nil\n\t}\n\n\treturn -1, fmt.Errorf(\"securityGroup priorities are exhausted\")\n}","line":{"from":408,"to":426}} {"id":100033289,"name":"MakeCRC32","signature":"func MakeCRC32(str string) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// MakeCRC32 : convert string to CRC32 format\nfunc MakeCRC32(str string) string {\n\tcrc := crc32.New(polyTable)\n\tcrc.Write([]byte(str))\n\thash := crc.Sum32()\n\treturn strconv.FormatUint(uint64(hash), 10)\n}","line":{"from":430,"to":436}} {"id":100033290,"name":"newAvailabilitySet","signature":"func newAvailabilitySet(az *Cloud) VMSet","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// newStandardSet creates a new availabilitySet.\nfunc newAvailabilitySet(az *Cloud) VMSet {\n\treturn \u0026availabilitySet{\n\t\tCloud: az,\n\t}\n}","line":{"from":443,"to":448}} {"id":100033291,"name":"GetInstanceIDByNodeName","signature":"func (as *availabilitySet) GetInstanceIDByNodeName(name string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// GetInstanceIDByNodeName gets the cloud provider ID by node name.\n// It must return (\"\", cloudprovider.InstanceNotFound) if the instance does\n// not exist or is no longer running.\nfunc (as *availabilitySet) GetInstanceIDByNodeName(name string) (string, error) {\n\tvar machine compute.VirtualMachine\n\tvar err error\n\n\tmachine, err = as.getVirtualMachine(types.NodeName(name), azcache.CacheReadTypeUnsafe)\n\tif err == cloudprovider.InstanceNotFound {\n\t\tklog.Warningf(\"Unable to find node %s: %v\", name, cloudprovider.InstanceNotFound)\n\t\treturn \"\", cloudprovider.InstanceNotFound\n\t}\n\tif err != nil {\n\t\tif as.CloudProviderBackoff {\n\t\t\tklog.V(2).Infof(\"GetInstanceIDByNodeName(%s) backing off\", name)\n\t\t\tmachine, err = as.GetVirtualMachineWithRetry(types.NodeName(name), azcache.CacheReadTypeUnsafe)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(2).Infof(\"GetInstanceIDByNodeName(%s) abort backoff\", name)\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t} else {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tresourceID := *machine.ID\n\tconvertedResourceID, err := convertResourceGroupNameToLower(resourceID)\n\tif err != nil {\n\t\tklog.Errorf(\"convertResourceGroupNameToLower failed with error: %v\", err)\n\t\treturn \"\", err\n\t}\n\treturn convertedResourceID, nil\n}","line":{"from":450,"to":482}} {"id":100033292,"name":"GetPowerStatusByNodeName","signature":"func (as *availabilitySet) GetPowerStatusByNodeName(name string) (powerState string, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// GetPowerStatusByNodeName returns the power state of the specified node.\nfunc (as *availabilitySet) GetPowerStatusByNodeName(name string) (powerState string, err error) {\n\tvm, err := as.getVirtualMachine(types.NodeName(name), azcache.CacheReadTypeDefault)\n\tif err != nil {\n\t\treturn powerState, err\n\t}\n\n\tif vm.InstanceView != nil \u0026\u0026 vm.InstanceView.Statuses != nil {\n\t\tstatuses := *vm.InstanceView.Statuses\n\t\tfor _, status := range statuses {\n\t\t\tstate := pointer.StringDeref(status.Code, \"\")\n\t\t\tif strings.HasPrefix(state, vmPowerStatePrefix) {\n\t\t\t\treturn strings.TrimPrefix(state, vmPowerStatePrefix), nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// vm.InstanceView or vm.InstanceView.Statuses are nil when the VM is under deleting.\n\tklog.V(3).Infof(\"InstanceView for node %q is nil, assuming it's stopped\", name)\n\treturn vmPowerStateStopped, nil\n}","line":{"from":484,"to":504}} {"id":100033293,"name":"GetProvisioningStateByNodeName","signature":"func (as *availabilitySet) GetProvisioningStateByNodeName(name string) (provisioningState string, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// GetProvisioningStateByNodeName returns the provisioningState for the specified node.\nfunc (as *availabilitySet) GetProvisioningStateByNodeName(name string) (provisioningState string, err error) {\n\tvm, err := as.getVirtualMachine(types.NodeName(name), azcache.CacheReadTypeDefault)\n\tif err != nil {\n\t\treturn provisioningState, err\n\t}\n\n\tif vm.VirtualMachineProperties == nil || vm.VirtualMachineProperties.ProvisioningState == nil {\n\t\treturn provisioningState, nil\n\t}\n\n\treturn pointer.StringDeref(vm.VirtualMachineProperties.ProvisioningState, \"\"), nil\n}","line":{"from":506,"to":518}} {"id":100033294,"name":"GetNodeNameByProviderID","signature":"func (as *availabilitySet) GetNodeNameByProviderID(providerID string) (types.NodeName, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// GetNodeNameByProviderID gets the node name by provider ID.\nfunc (as *availabilitySet) GetNodeNameByProviderID(providerID string) (types.NodeName, error) {\n\t// NodeName is part of providerID for standard instances.\n\tmatches := providerIDRE.FindStringSubmatch(providerID)\n\tif len(matches) != 2 {\n\t\treturn \"\", errors.New(\"error splitting providerID\")\n\t}\n\n\treturn types.NodeName(matches[1]), nil\n}","line":{"from":520,"to":529}} {"id":100033295,"name":"GetInstanceTypeByNodeName","signature":"func (as *availabilitySet) GetInstanceTypeByNodeName(name string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// GetInstanceTypeByNodeName gets the instance type by node name.\nfunc (as *availabilitySet) GetInstanceTypeByNodeName(name string) (string, error) {\n\tmachine, err := as.getVirtualMachine(types.NodeName(name), azcache.CacheReadTypeUnsafe)\n\tif err != nil {\n\t\tklog.Errorf(\"as.GetInstanceTypeByNodeName(%s) failed: as.getVirtualMachine(%s) err=%v\", name, name, err)\n\t\treturn \"\", err\n\t}\n\n\treturn string(machine.HardwareProfile.VMSize), nil\n}","line":{"from":531,"to":540}} {"id":100033296,"name":"GetZoneByNodeName","signature":"func (as *availabilitySet) GetZoneByNodeName(name string) (cloudprovider.Zone, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// GetZoneByNodeName gets availability zone for the specified node. If the node is not running\n// with availability zone, then it returns fault domain.\nfunc (as *availabilitySet) GetZoneByNodeName(name string) (cloudprovider.Zone, error) {\n\tvm, err := as.getVirtualMachine(types.NodeName(name), azcache.CacheReadTypeUnsafe)\n\tif err != nil {\n\t\treturn cloudprovider.Zone{}, err\n\t}\n\n\tvar failureDomain string\n\tif vm.Zones != nil \u0026\u0026 len(*vm.Zones) \u003e 0 {\n\t\t// Get availability zone for the node.\n\t\tzones := *vm.Zones\n\t\tzoneID, err := strconv.Atoi(zones[0])\n\t\tif err != nil {\n\t\t\treturn cloudprovider.Zone{}, fmt.Errorf(\"failed to parse zone %q: %v\", zones, err)\n\t\t}\n\n\t\tfailureDomain = as.makeZone(pointer.StringDeref(vm.Location, \"\"), zoneID)\n\t} else {\n\t\t// Availability zone is not used for the node, falling back to fault domain.\n\t\tfailureDomain = strconv.Itoa(int(pointer.Int32Deref(vm.VirtualMachineProperties.InstanceView.PlatformFaultDomain, 0)))\n\t}\n\n\tzone := cloudprovider.Zone{\n\t\tFailureDomain: strings.ToLower(failureDomain),\n\t\tRegion: strings.ToLower(pointer.StringDeref(vm.Location, \"\")),\n\t}\n\treturn zone, nil\n}","line":{"from":542,"to":570}} {"id":100033297,"name":"GetPrimaryVMSetName","signature":"func (as *availabilitySet) GetPrimaryVMSetName() string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// GetPrimaryVMSetName returns the VM set name depending on the configured vmType.\n// It returns config.PrimaryScaleSetName for vmss and config.PrimaryAvailabilitySetName for standard vmType.\nfunc (as *availabilitySet) GetPrimaryVMSetName() string {\n\treturn as.Config.PrimaryAvailabilitySetName\n}","line":{"from":572,"to":576}} {"id":100033298,"name":"GetIPByNodeName","signature":"func (as *availabilitySet) GetIPByNodeName(name string) (string, string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// GetIPByNodeName gets machine private IP and public IP by node name.\nfunc (as *availabilitySet) GetIPByNodeName(name string) (string, string, error) {\n\tnic, err := as.GetPrimaryInterface(name)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\tipConfig, err := getPrimaryIPConfig(nic)\n\tif err != nil {\n\t\tklog.Errorf(\"as.GetIPByNodeName(%s) failed: getPrimaryIPConfig(%v), err=%v\", name, nic, err)\n\t\treturn \"\", \"\", err\n\t}\n\n\tprivateIP := *ipConfig.PrivateIPAddress\n\tpublicIP := \"\"\n\tif ipConfig.PublicIPAddress != nil \u0026\u0026 ipConfig.PublicIPAddress.ID != nil {\n\t\tpipID := *ipConfig.PublicIPAddress.ID\n\t\tpipName, err := getLastSegment(pipID, \"/\")\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", fmt.Errorf(\"failed to publicIP name for node %q with pipID %q\", name, pipID)\n\t\t}\n\t\tpip, existsPip, err := as.getPublicIPAddress(as.ResourceGroup, pipName)\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", err\n\t\t}\n\t\tif existsPip {\n\t\t\tpublicIP = *pip.IPAddress\n\t\t}\n\t}\n\n\treturn privateIP, publicIP, nil\n}","line":{"from":578,"to":609}} {"id":100033299,"name":"GetPrivateIPsByNodeName","signature":"func (as *availabilitySet) GetPrivateIPsByNodeName(name string) ([]string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// returns a list of private ips assigned to node\n// TODO (khenidak): This should read all nics, not just the primary\n// allowing users to split ipv4/v6 on multiple nics\nfunc (as *availabilitySet) GetPrivateIPsByNodeName(name string) ([]string, error) {\n\tips := make([]string, 0)\n\tnic, err := as.GetPrimaryInterface(name)\n\tif err != nil {\n\t\treturn ips, err\n\t}\n\n\tif nic.IPConfigurations == nil {\n\t\treturn ips, fmt.Errorf(\"nic.IPConfigurations for nic (nicname=%q) is nil\", *nic.Name)\n\t}\n\n\tfor _, ipConfig := range *(nic.IPConfigurations) {\n\t\tif ipConfig.PrivateIPAddress != nil {\n\t\t\tips = append(ips, *(ipConfig.PrivateIPAddress))\n\t\t}\n\t}\n\n\treturn ips, nil\n}","line":{"from":611,"to":632}} {"id":100033300,"name":"getAgentPoolAvailabilitySets","signature":"func (as *availabilitySet) getAgentPoolAvailabilitySets(nodes []*v1.Node) (agentPoolAvailabilitySets *[]string, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// getAgentPoolAvailabilitySets lists the virtual machines for the resource group and then builds\n// a list of availability sets that match the nodes available to k8s.\nfunc (as *availabilitySet) getAgentPoolAvailabilitySets(nodes []*v1.Node) (agentPoolAvailabilitySets *[]string, err error) {\n\tvms, err := as.ListVirtualMachines(as.ResourceGroup)\n\tif err != nil {\n\t\tklog.Errorf(\"as.getNodeAvailabilitySet - ListVirtualMachines failed, err=%v\", err)\n\t\treturn nil, err\n\t}\n\tvmNameToAvailabilitySetID := make(map[string]string, len(vms))\n\tfor vmx := range vms {\n\t\tvm := vms[vmx]\n\t\tif vm.AvailabilitySet != nil {\n\t\t\tvmNameToAvailabilitySetID[*vm.Name] = *vm.AvailabilitySet.ID\n\t\t}\n\t}\n\tavailabilitySetIDs := sets.NewString()\n\tagentPoolAvailabilitySets = \u0026[]string{}\n\tfor nx := range nodes {\n\t\tnodeName := (*nodes[nx]).Name\n\t\tif isMasterNode(nodes[nx]) {\n\t\t\tcontinue\n\t\t}\n\t\tasID, ok := vmNameToAvailabilitySetID[nodeName]\n\t\tif !ok {\n\t\t\tklog.Errorf(\"as.getNodeAvailabilitySet - Node(%s) has no availability sets\", nodeName)\n\t\t\treturn nil, fmt.Errorf(\"node (%s) - has no availability sets\", nodeName)\n\t\t}\n\t\tif availabilitySetIDs.Has(asID) {\n\t\t\t// already added in the list\n\t\t\tcontinue\n\t\t}\n\t\tasName, err := getLastSegment(asID, \"/\")\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"as.getNodeAvailabilitySet - Node (%s)- getLastSegment(%s), err=%v\", nodeName, asID, err)\n\t\t\treturn nil, err\n\t\t}\n\t\t// AvailabilitySet ID is currently upper cased in a non-deterministic way\n\t\t// We want to keep it lower case, before the ID get fixed\n\t\tasName = strings.ToLower(asName)\n\n\t\t*agentPoolAvailabilitySets = append(*agentPoolAvailabilitySets, asName)\n\t}\n\n\treturn agentPoolAvailabilitySets, nil\n}","line":{"from":634,"to":678}} {"id":100033301,"name":"GetVMSetNames","signature":"func (as *availabilitySet) GetVMSetNames(service *v1.Service, nodes []*v1.Node) (availabilitySetNames *[]string, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// GetVMSetNames selects all possible availability sets or scale sets\n// (depending vmType configured) for service load balancer, if the service has\n// no loadbalancer mode annotation returns the primary VMSet. If service annotation\n// for loadbalancer exists then returns the eligible VMSet. The mode selection\n// annotation would be ignored when using one SLB per cluster.\nfunc (as *availabilitySet) GetVMSetNames(service *v1.Service, nodes []*v1.Node) (availabilitySetNames *[]string, err error) {\n\thasMode, isAuto, serviceAvailabilitySetNames := getServiceLoadBalancerMode(service)\n\tuseSingleSLB := as.useStandardLoadBalancer() \u0026\u0026 !as.EnableMultipleStandardLoadBalancers\n\tif !hasMode || useSingleSLB {\n\t\t// no mode specified in service annotation or use single SLB mode\n\t\t// default to PrimaryAvailabilitySetName\n\t\tavailabilitySetNames = \u0026[]string{as.Config.PrimaryAvailabilitySetName}\n\t\treturn availabilitySetNames, nil\n\t}\n\tavailabilitySetNames, err = as.getAgentPoolAvailabilitySets(nodes)\n\tif err != nil {\n\t\tklog.Errorf(\"as.GetVMSetNames - getAgentPoolAvailabilitySets failed err=(%v)\", err)\n\t\treturn nil, err\n\t}\n\tif len(*availabilitySetNames) == 0 {\n\t\tklog.Errorf(\"as.GetVMSetNames - No availability sets found for nodes in the cluster, node count(%d)\", len(nodes))\n\t\treturn nil, fmt.Errorf(\"no availability sets found for nodes, node count(%d)\", len(nodes))\n\t}\n\t// sort the list to have deterministic selection\n\tsort.Strings(*availabilitySetNames)\n\tif !isAuto {\n\t\tif serviceAvailabilitySetNames == nil || len(serviceAvailabilitySetNames) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"service annotation for LoadBalancerMode is empty, it should have __auto__ or availability sets value\")\n\t\t}\n\t\t// validate availability set exists\n\t\tvar found bool\n\t\tfor sasx := range serviceAvailabilitySetNames {\n\t\t\tfor asx := range *availabilitySetNames {\n\t\t\t\tif strings.EqualFold((*availabilitySetNames)[asx], serviceAvailabilitySetNames[sasx]) {\n\t\t\t\t\tfound = true\n\t\t\t\t\tserviceAvailabilitySetNames[sasx] = (*availabilitySetNames)[asx]\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\tklog.Errorf(\"as.GetVMSetNames - Availability set (%s) in service annotation not found\", serviceAvailabilitySetNames[sasx])\n\t\t\t\treturn nil, fmt.Errorf(\"availability set (%s) - not found\", serviceAvailabilitySetNames[sasx])\n\t\t\t}\n\t\t}\n\t\tavailabilitySetNames = \u0026serviceAvailabilitySetNames\n\t}\n\n\treturn availabilitySetNames, nil\n}","line":{"from":680,"to":728}} {"id":100033302,"name":"GetPrimaryInterface","signature":"func (as *availabilitySet) GetPrimaryInterface(nodeName string) (network.Interface, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// GetPrimaryInterface gets machine primary network interface by node name.\nfunc (as *availabilitySet) GetPrimaryInterface(nodeName string) (network.Interface, error) {\n\tnic, _, err := as.getPrimaryInterfaceWithVMSet(nodeName, \"\")\n\treturn nic, err\n}","line":{"from":730,"to":734}} {"id":100033303,"name":"extractResourceGroupByNicID","signature":"func extractResourceGroupByNicID(nicID string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// extractResourceGroupByNicID extracts the resource group name by nicID.\nfunc extractResourceGroupByNicID(nicID string) (string, error) {\n\tmatches := nicResourceGroupRE.FindStringSubmatch(nicID)\n\tif len(matches) != 2 {\n\t\treturn \"\", fmt.Errorf(\"error of extracting resourceGroup from nicID %q\", nicID)\n\t}\n\n\treturn matches[1], nil\n}","line":{"from":736,"to":744}} {"id":100033304,"name":"getPrimaryInterfaceWithVMSet","signature":"func (as *availabilitySet) getPrimaryInterfaceWithVMSet(nodeName, vmSetName string) (network.Interface, string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// getPrimaryInterfaceWithVMSet gets machine primary network interface by node name and vmSet.\nfunc (as *availabilitySet) getPrimaryInterfaceWithVMSet(nodeName, vmSetName string) (network.Interface, string, error) {\n\tvar machine compute.VirtualMachine\n\n\tmachine, err := as.GetVirtualMachineWithRetry(types.NodeName(nodeName), azcache.CacheReadTypeDefault)\n\tif err != nil {\n\t\tklog.V(2).Infof(\"GetPrimaryInterface(%s, %s) abort backoff\", nodeName, vmSetName)\n\t\treturn network.Interface{}, \"\", err\n\t}\n\n\tprimaryNicID, err := getPrimaryInterfaceID(machine)\n\tif err != nil {\n\t\treturn network.Interface{}, \"\", err\n\t}\n\tnicName, err := getLastSegment(primaryNicID, \"/\")\n\tif err != nil {\n\t\treturn network.Interface{}, \"\", err\n\t}\n\tnodeResourceGroup, err := as.GetNodeResourceGroup(nodeName)\n\tif err != nil {\n\t\treturn network.Interface{}, \"\", err\n\t}\n\n\t// Check availability set name. Note that vmSetName is empty string when getting\n\t// the Node's IP address. While vmSetName is not empty, it should be checked with\n\t// Node's real availability set name:\n\t// - For basic SKU load balancer, errNotInVMSet should be returned if the node's\n\t// availability set is mismatched with vmSetName.\n\t// - For single standard SKU load balancer, backend could belong to multiple VMAS, so we\n\t// don't check vmSet for it.\n\t// - For multiple standard SKU load balancers, the behavior is similar to the basic LB.\n\tneedCheck := false\n\tif !as.useStandardLoadBalancer() {\n\t\t// need to check the vmSet name when using the basic LB\n\t\tneedCheck = true\n\t} else if as.EnableMultipleStandardLoadBalancers {\n\t\t// need to check the vmSet name when using multiple standard LBs\n\t\tneedCheck = true\n\t}\n\tif vmSetName != \"\" \u0026\u0026 needCheck {\n\t\texpectedAvailabilitySetID := as.getAvailabilitySetID(nodeResourceGroup, vmSetName)\n\t\tif machine.AvailabilitySet == nil || !strings.EqualFold(*machine.AvailabilitySet.ID, expectedAvailabilitySetID) {\n\t\t\tklog.V(3).Infof(\n\t\t\t\t\"GetPrimaryInterface: nic (%s) is not in the availabilitySet(%s)\", nicName, vmSetName)\n\t\t\treturn network.Interface{}, \"\", errNotInVMSet\n\t\t}\n\t}\n\n\tnicResourceGroup, err := extractResourceGroupByNicID(primaryNicID)\n\tif err != nil {\n\t\treturn network.Interface{}, \"\", err\n\t}\n\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\tnic, rerr := as.InterfacesClient.Get(ctx, nicResourceGroup, nicName, \"\")\n\tif rerr != nil {\n\t\treturn network.Interface{}, \"\", rerr.Error()\n\t}\n\n\tvar availabilitySetID string\n\tif machine.VirtualMachineProperties != nil \u0026\u0026 machine.AvailabilitySet != nil {\n\t\tavailabilitySetID = pointer.StringDeref(machine.AvailabilitySet.ID, \"\")\n\t}\n\treturn nic, availabilitySetID, nil\n}","line":{"from":746,"to":811}} {"id":100033305,"name":"EnsureHostInPool","signature":"func (as *availabilitySet) EnsureHostInPool(service *v1.Service, nodeName types.NodeName, backendPoolID string, vmSetName string, isInternal bool) (string, string, string, *compute.VirtualMachineScaleSetVM, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// EnsureHostInPool ensures the given VM's Primary NIC's Primary IP Configuration is\n// participating in the specified LoadBalancer Backend Pool.\nfunc (as *availabilitySet) EnsureHostInPool(service *v1.Service, nodeName types.NodeName, backendPoolID string, vmSetName string, isInternal bool) (string, string, string, *compute.VirtualMachineScaleSetVM, error) {\n\tvmName := mapNodeNameToVMName(nodeName)\n\tserviceName := getServiceName(service)\n\tnic, _, err := as.getPrimaryInterfaceWithVMSet(vmName, vmSetName)\n\tif err != nil {\n\t\tif err == errNotInVMSet {\n\t\t\tklog.V(3).Infof(\"EnsureHostInPool skips node %s because it is not in the vmSet %s\", nodeName, vmSetName)\n\t\t\treturn \"\", \"\", \"\", nil, nil\n\t\t}\n\n\t\tklog.Errorf(\"error: az.EnsureHostInPool(%s), az.VMSet.GetPrimaryInterface.Get(%s, %s), err=%v\", nodeName, vmName, vmSetName, err)\n\t\tif err != cloudprovider.InstanceNotFound {\n\t\t\treturn \"\", \"\", \"\", nil, err\n\t\t}\n\t}\n\n\tif nic.ProvisioningState != nil \u0026\u0026 *nic.ProvisioningState == nicFailedState {\n\t\tklog.Warningf(\"EnsureHostInPool skips node %s because its primary nic %s is in Failed state\", nodeName, *nic.Name)\n\t\treturn \"\", \"\", \"\", nil, nil\n\t}\n\n\tvar primaryIPConfig *network.InterfaceIPConfiguration\n\tipv6 := utilnet.IsIPv6String(service.Spec.ClusterIP)\n\tif !as.Cloud.ipv6DualStackEnabled \u0026\u0026 !ipv6 {\n\t\tprimaryIPConfig, err = getPrimaryIPConfig(nic)\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", \"\", nil, err\n\t\t}\n\t} else {\n\t\tprimaryIPConfig, err = getIPConfigByIPFamily(nic, ipv6)\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", \"\", nil, err\n\t\t}\n\t}\n\n\tfoundPool := false\n\tnewBackendPools := []network.BackendAddressPool{}\n\tif primaryIPConfig.LoadBalancerBackendAddressPools != nil {\n\t\tnewBackendPools = *primaryIPConfig.LoadBalancerBackendAddressPools\n\t}\n\tfor _, existingPool := range newBackendPools {\n\t\tif strings.EqualFold(backendPoolID, *existingPool.ID) {\n\t\t\tfoundPool = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !foundPool {\n\t\tif as.useStandardLoadBalancer() \u0026\u0026 len(newBackendPools) \u003e 0 {\n\t\t\t// Although standard load balancer supports backends from multiple availability\n\t\t\t// sets, the same network interface couldn't be added to more than one load balancer of\n\t\t\t// the same type. Omit those nodes (e.g. masters) so Azure ARM won't complain\n\t\t\t// about this.\n\t\t\tnewBackendPoolsIDs := make([]string, 0, len(newBackendPools))\n\t\t\tfor _, pool := range newBackendPools {\n\t\t\t\tif pool.ID != nil {\n\t\t\t\t\tnewBackendPoolsIDs = append(newBackendPoolsIDs, *pool.ID)\n\t\t\t\t}\n\t\t\t}\n\t\t\tisSameLB, oldLBName, err := isBackendPoolOnSameLB(backendPoolID, newBackendPoolsIDs)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", \"\", \"\", nil, err\n\t\t\t}\n\t\t\tif !isSameLB {\n\t\t\t\tklog.V(4).Infof(\"Node %q has already been added to LB %q, omit adding it to a new one\", nodeName, oldLBName)\n\t\t\t\treturn \"\", \"\", \"\", nil, nil\n\t\t\t}\n\t\t}\n\n\t\tnewBackendPools = append(newBackendPools,\n\t\t\tnetwork.BackendAddressPool{\n\t\t\t\tID: pointer.String(backendPoolID),\n\t\t\t})\n\n\t\tprimaryIPConfig.LoadBalancerBackendAddressPools = \u0026newBackendPools\n\n\t\tnicName := *nic.Name\n\t\tklog.V(3).Infof(\"nicupdate(%s): nic(%s) - updating\", serviceName, nicName)\n\t\terr := as.CreateOrUpdateInterface(service, nic)\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", \"\", nil, err\n\t\t}\n\t}\n\treturn \"\", \"\", \"\", nil, nil\n}","line":{"from":813,"to":898}} {"id":100033306,"name":"EnsureHostsInPool","signature":"func (as *availabilitySet) EnsureHostsInPool(service *v1.Service, nodes []*v1.Node, backendPoolID string, vmSetName string, isInternal bool) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// EnsureHostsInPool ensures the given Node's primary IP configurations are\n// participating in the specified LoadBalancer Backend Pool.\nfunc (as *availabilitySet) EnsureHostsInPool(service *v1.Service, nodes []*v1.Node, backendPoolID string, vmSetName string, isInternal bool) error {\n\tmc := metrics.NewMetricContext(\"services\", \"vmas_ensure_hosts_in_pool\", as.ResourceGroup, as.SubscriptionID, service.Name)\n\tisOperationSucceeded := false\n\tdefer func() {\n\t\tmc.ObserveOperationWithResult(isOperationSucceeded)\n\t}()\n\n\thostUpdates := make([]func() error, 0, len(nodes))\n\tfor _, node := range nodes {\n\t\tlocalNodeName := node.Name\n\t\tif as.useStandardLoadBalancer() \u0026\u0026 as.excludeMasterNodesFromStandardLB() \u0026\u0026 isMasterNode(node) {\n\t\t\tklog.V(4).Infof(\"Excluding master node %q from load balancer backendpool %q\", localNodeName, backendPoolID)\n\t\t\tcontinue\n\t\t}\n\n\t\tshouldExcludeLoadBalancer, err := as.ShouldNodeExcludedFromLoadBalancer(localNodeName)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"ShouldNodeExcludedFromLoadBalancer(%s) failed with error: %v\", localNodeName, err)\n\t\t\treturn err\n\t\t}\n\t\tif shouldExcludeLoadBalancer {\n\t\t\tklog.V(4).Infof(\"Excluding unmanaged/external-resource-group node %q\", localNodeName)\n\t\t\tcontinue\n\t\t}\n\n\t\tf := func() error {\n\t\t\t_, _, _, _, err := as.EnsureHostInPool(service, types.NodeName(localNodeName), backendPoolID, vmSetName, isInternal)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"ensure(%s): backendPoolID(%s) - failed to ensure host in pool: %q\", getServiceName(service), backendPoolID, err)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\thostUpdates = append(hostUpdates, f)\n\t}\n\n\terrs := utilerrors.AggregateGoroutines(hostUpdates...)\n\tif errs != nil {\n\t\treturn utilerrors.Flatten(errs)\n\t}\n\n\tisOperationSucceeded = true\n\treturn nil\n}","line":{"from":900,"to":944}} {"id":100033307,"name":"EnsureBackendPoolDeleted","signature":"func (as *availabilitySet) EnsureBackendPoolDeleted(service *v1.Service, backendPoolID, vmSetName string, backendAddressPools *[]network.BackendAddressPool, deleteFromVMSet bool) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// EnsureBackendPoolDeleted ensures the loadBalancer backendAddressPools deleted from the specified nodes.\nfunc (as *availabilitySet) EnsureBackendPoolDeleted(service *v1.Service, backendPoolID, vmSetName string, backendAddressPools *[]network.BackendAddressPool, deleteFromVMSet bool) error {\n\t// Returns nil if backend address pools already deleted.\n\tif backendAddressPools == nil {\n\t\treturn nil\n\t}\n\n\tmc := metrics.NewMetricContext(\"services\", \"vmas_ensure_backend_pool_deleted\", as.ResourceGroup, as.SubscriptionID, service.Name)\n\tisOperationSucceeded := false\n\tdefer func() {\n\t\tmc.ObserveOperationWithResult(isOperationSucceeded)\n\t}()\n\n\tipConfigurationIDs := []string{}\n\tfor _, backendPool := range *backendAddressPools {\n\t\tif strings.EqualFold(pointer.StringDeref(backendPool.ID, \"\"), backendPoolID) \u0026\u0026\n\t\t\tbackendPool.BackendAddressPoolPropertiesFormat != nil \u0026\u0026\n\t\t\tbackendPool.BackendIPConfigurations != nil {\n\t\t\tfor _, ipConf := range *backendPool.BackendIPConfigurations {\n\t\t\t\tif ipConf.ID == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tipConfigurationIDs = append(ipConfigurationIDs, *ipConf.ID)\n\t\t\t}\n\t\t}\n\t}\n\tnicUpdaters := make([]func() error, 0)\n\tallErrs := make([]error, 0)\n\tfor i := range ipConfigurationIDs {\n\t\tipConfigurationID := ipConfigurationIDs[i]\n\t\tnodeName, _, err := as.GetNodeNameByIPConfigurationID(ipConfigurationID)\n\t\tif err != nil \u0026\u0026 !errors.Is(err, cloudprovider.InstanceNotFound) {\n\t\t\tklog.Errorf(\"Failed to GetNodeNameByIPConfigurationID(%s): %v\", ipConfigurationID, err)\n\t\t\tallErrs = append(allErrs, err)\n\t\t\tcontinue\n\t\t}\n\t\tif nodeName == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tvmName := mapNodeNameToVMName(types.NodeName(nodeName))\n\t\tnic, vmasID, err := as.getPrimaryInterfaceWithVMSet(vmName, vmSetName)\n\t\tif err != nil {\n\t\t\tif err == errNotInVMSet {\n\t\t\t\tklog.V(3).Infof(\"EnsureBackendPoolDeleted skips node %s because it is not in the vmSet %s\", nodeName, vmSetName)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tklog.Errorf(\"error: az.EnsureBackendPoolDeleted(%s), az.VMSet.GetPrimaryInterface.Get(%s, %s), err=%v\", nodeName, vmName, vmSetName, err)\n\t\t\treturn err\n\t\t}\n\t\tvmasName, err := getAvailabilitySetNameByID(vmasID)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"EnsureBackendPoolDeleted: failed to parse the VMAS ID %s: %v\", vmasID, err)\n\t\t}\n\t\t// Only remove nodes belonging to specified vmSet to basic LB backends.\n\t\tif !strings.EqualFold(vmasName, vmSetName) {\n\t\t\tklog.V(2).Infof(\"EnsureBackendPoolDeleted: skipping the node %s belonging to another vm set %s\", nodeName, vmasName)\n\t\t\tcontinue\n\t\t}\n\n\t\tif nic.ProvisioningState != nil \u0026\u0026 *nic.ProvisioningState == nicFailedState {\n\t\t\tklog.Warningf(\"EnsureBackendPoolDeleted skips node %s because its primary nic %s is in Failed state\", nodeName, *nic.Name)\n\t\t\treturn nil\n\t\t}\n\n\t\tif nic.InterfacePropertiesFormat != nil \u0026\u0026 nic.InterfacePropertiesFormat.IPConfigurations != nil {\n\t\t\tnewIPConfigs := *nic.IPConfigurations\n\t\t\tfor j, ipConf := range newIPConfigs {\n\t\t\t\tif !pointer.BoolDeref(ipConf.Primary, false) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// found primary ip configuration\n\t\t\t\tif ipConf.LoadBalancerBackendAddressPools != nil {\n\t\t\t\t\tnewLBAddressPools := *ipConf.LoadBalancerBackendAddressPools\n\t\t\t\t\tfor k := len(newLBAddressPools) - 1; k \u003e= 0; k-- {\n\t\t\t\t\t\tpool := newLBAddressPools[k]\n\t\t\t\t\t\tif strings.EqualFold(pointer.StringDeref(pool.ID, \"\"), backendPoolID) {\n\t\t\t\t\t\t\tnewLBAddressPools = append(newLBAddressPools[:k], newLBAddressPools[k+1:]...)\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tnewIPConfigs[j].LoadBalancerBackendAddressPools = \u0026newLBAddressPools\n\t\t\t\t}\n\t\t\t}\n\t\t\tnic.IPConfigurations = \u0026newIPConfigs\n\t\t\tnicUpdaters = append(nicUpdaters, func() error {\n\t\t\t\tctx, cancel := getContextWithCancel()\n\t\t\t\tdefer cancel()\n\t\t\t\tklog.V(2).Infof(\"EnsureBackendPoolDeleted begins to CreateOrUpdate for NIC(%s, %s) with backendPoolID %s\", as.resourceGroup, pointer.StringDeref(nic.Name, \"\"), backendPoolID)\n\t\t\t\trerr := as.InterfacesClient.CreateOrUpdate(ctx, as.ResourceGroup, pointer.StringDeref(nic.Name, \"\"), nic)\n\t\t\t\tif rerr != nil {\n\t\t\t\t\tklog.Errorf(\"EnsureBackendPoolDeleted CreateOrUpdate for NIC(%s, %s) failed with error %v\", as.resourceGroup, pointer.StringDeref(nic.Name, \"\"), rerr.Error())\n\t\t\t\t\treturn rerr.Error()\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t})\n\t\t}\n\t}\n\terrs := utilerrors.AggregateGoroutines(nicUpdaters...)\n\tif errs != nil {\n\t\treturn utilerrors.Flatten(errs)\n\t}\n\t// Fail if there are other allErrs.\n\tif len(allErrs) \u003e 0 {\n\t\treturn utilerrors.Flatten(utilerrors.NewAggregate(allErrs))\n\t}\n\n\tisOperationSucceeded = true\n\treturn nil\n}","line":{"from":946,"to":1057}} {"id":100033308,"name":"getAvailabilitySetNameByID","signature":"func getAvailabilitySetNameByID(asID string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"func getAvailabilitySetNameByID(asID string) (string, error) {\n\t// for standalone VM\n\tif asID == \"\" {\n\t\treturn \"\", nil\n\t}\n\n\tmatches := vmasIDRE.FindStringSubmatch(asID)\n\tif len(matches) != 2 {\n\t\treturn \"\", fmt.Errorf(\"getAvailabilitySetNameByID: failed to parse the VMAS ID %s\", asID)\n\t}\n\tvmasName := matches[1]\n\treturn vmasName, nil\n}","line":{"from":1059,"to":1071}} {"id":100033309,"name":"generateStorageAccountName","signature":"func generateStorageAccountName(accountNamePrefix string) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// get a storage account by UUID\nfunc generateStorageAccountName(accountNamePrefix string) string {\n\tuniqueID := strings.Replace(string(uuid.NewUUID()), \"-\", \"\", -1)\n\taccountName := strings.ToLower(accountNamePrefix + uniqueID)\n\tif len(accountName) \u003e storageAccountNameMaxLength {\n\t\treturn accountName[:storageAccountNameMaxLength-1]\n\t}\n\treturn accountName\n}","line":{"from":1073,"to":1081}} {"id":100033310,"name":"GetNodeNameByIPConfigurationID","signature":"func (as *availabilitySet) GetNodeNameByIPConfigurationID(ipConfigurationID string) (string, string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_standard.go","code":"// GetNodeNameByIPConfigurationID gets the node name and the availabilitySet name by IP configuration ID.\nfunc (as *availabilitySet) GetNodeNameByIPConfigurationID(ipConfigurationID string) (string, string, error) {\n\tmatches := nicIDRE.FindStringSubmatch(ipConfigurationID)\n\tif len(matches) != 3 {\n\t\tklog.V(4).Infof(\"Can not extract VM name from ipConfigurationID (%s)\", ipConfigurationID)\n\t\treturn \"\", \"\", fmt.Errorf(\"invalid ip config ID %s\", ipConfigurationID)\n\t}\n\n\tnicResourceGroup, nicName := matches[1], matches[2]\n\tif nicResourceGroup == \"\" || nicName == \"\" {\n\t\treturn \"\", \"\", fmt.Errorf(\"invalid ip config ID %s\", ipConfigurationID)\n\t}\n\tnic, rerr := as.InterfacesClient.Get(context.Background(), nicResourceGroup, nicName, \"\")\n\tif rerr != nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"GetNodeNameByIPConfigurationID(%s): failed to get interface of name %s: %s\", ipConfigurationID, nicName, rerr.Error().Error())\n\t}\n\tvmID := \"\"\n\tif nic.InterfacePropertiesFormat != nil \u0026\u0026 nic.VirtualMachine != nil {\n\t\tvmID = pointer.StringDeref(nic.VirtualMachine.ID, \"\")\n\t}\n\tif vmID == \"\" {\n\t\tklog.V(2).Infof(\"GetNodeNameByIPConfigurationID(%s): empty vmID\", ipConfigurationID)\n\t\treturn \"\", \"\", nil\n\t}\n\n\tmatches = vmIDRE.FindStringSubmatch(vmID)\n\tif len(matches) != 2 {\n\t\treturn \"\", \"\", fmt.Errorf(\"invalid virtual machine ID %s\", vmID)\n\t}\n\tvmName := matches[1]\n\n\tvm, err := as.getVirtualMachine(types.NodeName(vmName), azcache.CacheReadTypeDefault)\n\tif err != nil {\n\t\tklog.Errorf(\"Unable to get the virtual machine by node name %s: %v\", vmName, err)\n\t\treturn \"\", \"\", err\n\t}\n\tasID := \"\"\n\tif vm.VirtualMachineProperties != nil \u0026\u0026 vm.AvailabilitySet != nil {\n\t\tasID = pointer.StringDeref(vm.AvailabilitySet.ID, \"\")\n\t}\n\tif asID == \"\" {\n\t\treturn vmName, \"\", nil\n\t}\n\n\tasName, err := getAvailabilitySetNameByID(asID)\n\tif err != nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"cannot get the availability set name by the availability set ID %s: %v\", asID, err)\n\t}\n\treturn vmName, strings.ToLower(asName), nil\n}","line":{"from":1083,"to":1132}} {"id":100033311,"name":"CreateFileShare","signature":"func (az *Cloud) CreateFileShare(accountOptions *AccountOptions, shareOptions *fileclient.ShareOptions) (string, string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_storage.go","code":"// CreateFileShare creates a file share, using a matching storage account type, account kind, etc.\n// storage account will be created if specified account is not found\nfunc (az *Cloud) CreateFileShare(accountOptions *AccountOptions, shareOptions *fileclient.ShareOptions) (string, string, error) {\n\tif accountOptions == nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"account options is nil\")\n\t}\n\tif shareOptions == nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"share options is nil\")\n\t}\n\tif accountOptions.ResourceGroup == \"\" {\n\t\taccountOptions.ResourceGroup = az.resourceGroup\n\t}\n\n\taccountOptions.EnableHTTPSTrafficOnly = true\n\tif shareOptions.Protocol == storage.NFS {\n\t\taccountOptions.EnableHTTPSTrafficOnly = false\n\t}\n\n\taccountName, accountKey, err := az.EnsureStorageAccount(accountOptions, fileShareAccountNamePrefix)\n\tif err != nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"could not get storage key for storage account %s: %v\", accountOptions.Name, err)\n\t}\n\n\tif err := az.createFileShare(accountOptions.ResourceGroup, accountName, shareOptions); err != nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"failed to create share %s in account %s: %v\", shareOptions.Name, accountName, err)\n\t}\n\tklog.V(4).Infof(\"created share %s in account %s\", shareOptions.Name, accountOptions.Name)\n\treturn accountName, accountKey, nil\n}","line":{"from":39,"to":67}} {"id":100033312,"name":"DeleteFileShare","signature":"func (az *Cloud) DeleteFileShare(resourceGroup, accountName, shareName string) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_storage.go","code":"// DeleteFileShare deletes a file share using storage account name and key\nfunc (az *Cloud) DeleteFileShare(resourceGroup, accountName, shareName string) error {\n\tif err := az.deleteFileShare(resourceGroup, accountName, shareName); err != nil {\n\t\treturn err\n\t}\n\tklog.V(4).Infof(\"share %s deleted\", shareName)\n\treturn nil\n}","line":{"from":69,"to":76}} {"id":100033313,"name":"ResizeFileShare","signature":"func (az *Cloud) ResizeFileShare(resourceGroup, accountName, name string, sizeGiB int) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_storage.go","code":"// ResizeFileShare resizes a file share\nfunc (az *Cloud) ResizeFileShare(resourceGroup, accountName, name string, sizeGiB int) error {\n\treturn az.resizeFileShare(resourceGroup, accountName, name, sizeGiB)\n}","line":{"from":78,"to":81}} {"id":100033314,"name":"GetFileShare","signature":"func (az *Cloud) GetFileShare(resourceGroupName, accountName, name string) (storage.FileShare, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_storage.go","code":"// GetFileShare gets a file share\nfunc (az *Cloud) GetFileShare(resourceGroupName, accountName, name string) (storage.FileShare, error) {\n\treturn az.getFileShare(resourceGroupName, accountName, name)\n}","line":{"from":83,"to":86}} {"id":100033315,"name":"getStorageAccounts","signature":"func (az *Cloud) getStorageAccounts(accountOptions *AccountOptions) ([]accountWithLocation, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_storageaccount.go","code":"// getStorageAccounts get matching storage accounts\nfunc (az *Cloud) getStorageAccounts(accountOptions *AccountOptions) ([]accountWithLocation, error) {\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\tresult, rerr := az.StorageAccountClient.ListByResourceGroup(ctx, accountOptions.ResourceGroup)\n\tif rerr != nil {\n\t\treturn nil, rerr.Error()\n\t}\n\n\taccounts := []accountWithLocation{}\n\tfor _, acct := range result {\n\t\tif acct.Name != nil \u0026\u0026 acct.Location != nil \u0026\u0026 acct.Sku != nil {\n\t\t\tstorageType := string((*acct.Sku).Name)\n\t\t\tif accountOptions.Type != \"\" \u0026\u0026 !strings.EqualFold(accountOptions.Type, storageType) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif accountOptions.Kind != \"\" \u0026\u0026 !strings.EqualFold(accountOptions.Kind, string(acct.Kind)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlocation := *acct.Location\n\t\t\tif accountOptions.Location != \"\" \u0026\u0026 !strings.EqualFold(accountOptions.Location, location) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif len(accountOptions.VirtualNetworkResourceIDs) \u003e 0 {\n\t\t\t\tif acct.AccountProperties == nil || acct.AccountProperties.NetworkRuleSet == nil ||\n\t\t\t\t\tacct.AccountProperties.NetworkRuleSet.VirtualNetworkRules == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tfound := false\n\t\t\t\tfor _, subnetID := range accountOptions.VirtualNetworkResourceIDs {\n\t\t\t\t\tfor _, rule := range *acct.AccountProperties.NetworkRuleSet.VirtualNetworkRules {\n\t\t\t\t\t\tif strings.EqualFold(pointer.StringDeref(rule.VirtualNetworkResourceID, \"\"), subnetID) \u0026\u0026 rule.Action == storage.Allow {\n\t\t\t\t\t\t\tfound = true\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !found {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\taccounts = append(accounts, accountWithLocation{Name: *acct.Name, StorageType: storageType, Location: location})\n\t\t}\n\t}\n\n\treturn accounts, nil\n}","line":{"from":44,"to":95}} {"id":100033316,"name":"GetStorageAccesskey","signature":"func (az *Cloud) GetStorageAccesskey(account, resourceGroup string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_storageaccount.go","code":"// GetStorageAccesskey gets the storage account access key\nfunc (az *Cloud) GetStorageAccesskey(account, resourceGroup string) (string, error) {\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\n\tresult, rerr := az.StorageAccountClient.ListKeys(ctx, resourceGroup, account)\n\tif rerr != nil {\n\t\treturn \"\", rerr.Error()\n\t}\n\tif result.Keys == nil {\n\t\treturn \"\", fmt.Errorf(\"empty keys\")\n\t}\n\n\tfor _, k := range *result.Keys {\n\t\tif k.Value != nil \u0026\u0026 *k.Value != \"\" {\n\t\t\tv := *k.Value\n\t\t\tif ind := strings.LastIndex(v, \" \"); ind \u003e= 0 {\n\t\t\t\tv = v[(ind + 1):]\n\t\t\t}\n\t\t\treturn v, nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"no valid keys\")\n}","line":{"from":97,"to":120}} {"id":100033317,"name":"EnsureStorageAccount","signature":"func (az *Cloud) EnsureStorageAccount(accountOptions *AccountOptions, genAccountNamePrefix string) (string, string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_storageaccount.go","code":"// EnsureStorageAccount search storage account, create one storage account(with genAccountNamePrefix) if not found, return accountName, accountKey\nfunc (az *Cloud) EnsureStorageAccount(accountOptions *AccountOptions, genAccountNamePrefix string) (string, string, error) {\n\tif accountOptions == nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"account options is nil\")\n\t}\n\taccountName := accountOptions.Name\n\taccountType := accountOptions.Type\n\taccountKind := accountOptions.Kind\n\tresourceGroup := accountOptions.ResourceGroup\n\tlocation := accountOptions.Location\n\tenableHTTPSTrafficOnly := accountOptions.EnableHTTPSTrafficOnly\n\n\tif len(accountName) == 0 {\n\t\t// find a storage account that matches accountType\n\t\taccounts, err := az.getStorageAccounts(accountOptions)\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", fmt.Errorf(\"could not list storage accounts for account type %s: %v\", accountType, err)\n\t\t}\n\n\t\tif len(accounts) \u003e 0 {\n\t\t\taccountName = accounts[0].Name\n\t\t\tklog.V(4).Infof(\"found a matching account %s type %s location %s\", accounts[0].Name, accounts[0].StorageType, accounts[0].Location)\n\t\t}\n\n\t\tif len(accountName) == 0 {\n\t\t\t// set network rules for storage account\n\t\t\tvar networkRuleSet *storage.NetworkRuleSet\n\t\t\tvirtualNetworkRules := []storage.VirtualNetworkRule{}\n\t\t\tfor _, subnetID := range accountOptions.VirtualNetworkResourceIDs {\n\t\t\t\tvnetRule := storage.VirtualNetworkRule{\n\t\t\t\t\tVirtualNetworkResourceID: \u0026subnetID,\n\t\t\t\t\tAction: storage.Allow,\n\t\t\t\t}\n\t\t\t\tvirtualNetworkRules = append(virtualNetworkRules, vnetRule)\n\t\t\t\tklog.V(4).Infof(\"subnetID(%s) has been set\", subnetID)\n\t\t\t}\n\t\t\tif len(virtualNetworkRules) \u003e 0 {\n\t\t\t\tnetworkRuleSet = \u0026storage.NetworkRuleSet{\n\t\t\t\t\tVirtualNetworkRules: \u0026virtualNetworkRules,\n\t\t\t\t\tDefaultAction: storage.DefaultActionDeny,\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// not found a matching account, now create a new account in current resource group\n\t\t\taccountName = generateStorageAccountName(genAccountNamePrefix)\n\t\t\tif location == \"\" {\n\t\t\t\tlocation = az.Location\n\t\t\t}\n\t\t\tif accountType == \"\" {\n\t\t\t\taccountType = defaultStorageAccountType\n\t\t\t}\n\n\t\t\t// use StorageV2 by default per https://docs.microsoft.com/en-us/azure/storage/common/storage-account-options\n\t\t\tkind := defaultStorageAccountKind\n\t\t\tif accountKind != \"\" {\n\t\t\t\tkind = storage.Kind(accountKind)\n\t\t\t}\n\t\t\tif len(accountOptions.Tags) == 0 {\n\t\t\t\taccountOptions.Tags = make(map[string]string)\n\t\t\t}\n\t\t\taccountOptions.Tags[\"created-by\"] = \"azure\"\n\t\t\ttags := convertMapToMapPointer(accountOptions.Tags)\n\n\t\t\tklog.V(2).Infof(\"azure - no matching account found, begin to create a new account %s in resource group %s, location: %s, accountType: %s, accountKind: %s, tags: %+v\",\n\t\t\t\taccountName, resourceGroup, location, accountType, kind, accountOptions.Tags)\n\n\t\t\tcp := storage.AccountCreateParameters{\n\t\t\t\tSku: \u0026storage.Sku{Name: storage.SkuName(accountType)},\n\t\t\t\tKind: kind,\n\t\t\t\tAccountPropertiesCreateParameters: \u0026storage.AccountPropertiesCreateParameters{\n\t\t\t\t\tEnableHTTPSTrafficOnly: \u0026enableHTTPSTrafficOnly,\n\t\t\t\t\tNetworkRuleSet: networkRuleSet,\n\t\t\t\t},\n\t\t\t\tTags: tags,\n\t\t\t\tLocation: \u0026location}\n\n\t\t\tctx, cancel := getContextWithCancel()\n\t\t\tdefer cancel()\n\t\t\trerr := az.StorageAccountClient.Create(ctx, resourceGroup, accountName, cp)\n\t\t\tif rerr != nil {\n\t\t\t\treturn \"\", \"\", fmt.Errorf(\"failed to create storage account %s, error: %v\", accountName, rerr)\n\t\t\t}\n\t\t}\n\t}\n\n\t// find the access key with this account\n\taccountKey, err := az.GetStorageAccesskey(accountName, resourceGroup)\n\tif err != nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"could not get storage key for storage account %s: %v\", accountName, err)\n\t}\n\n\treturn accountName, accountKey, nil\n}","line":{"from":122,"to":214}} {"id":100033318,"name":"newLockMap","signature":"func newLockMap() *lockMap","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_utils.go","code":"// NewLockMap returns a new lock map\nfunc newLockMap() *lockMap {\n\treturn \u0026lockMap{\n\t\tmutexMap: make(map[string]*sync.Mutex),\n\t}\n}","line":{"from":43,"to":48}} {"id":100033319,"name":"LockEntry","signature":"func (lm *lockMap) LockEntry(entry string)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_utils.go","code":"// LockEntry acquires a lock associated with the specific entry\nfunc (lm *lockMap) LockEntry(entry string) {\n\tlm.Lock()\n\t// check if entry does not exists, then add entry\n\tif _, exists := lm.mutexMap[entry]; !exists {\n\t\tlm.addEntry(entry)\n\t}\n\n\tlm.Unlock()\n\tlm.lockEntry(entry)\n}","line":{"from":50,"to":60}} {"id":100033320,"name":"UnlockEntry","signature":"func (lm *lockMap) UnlockEntry(entry string)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_utils.go","code":"// UnlockEntry release the lock associated with the specific entry\nfunc (lm *lockMap) UnlockEntry(entry string) {\n\tlm.Lock()\n\tdefer lm.Unlock()\n\n\tif _, exists := lm.mutexMap[entry]; !exists {\n\t\treturn\n\t}\n\tlm.unlockEntry(entry)\n}","line":{"from":62,"to":71}} {"id":100033321,"name":"addEntry","signature":"func (lm *lockMap) addEntry(entry string)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_utils.go","code":"func (lm *lockMap) addEntry(entry string) {\n\tlm.mutexMap[entry] = \u0026sync.Mutex{}\n}","line":{"from":73,"to":75}} {"id":100033322,"name":"lockEntry","signature":"func (lm *lockMap) lockEntry(entry string)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_utils.go","code":"func (lm *lockMap) lockEntry(entry string) {\n\tlm.mutexMap[entry].Lock()\n}","line":{"from":77,"to":79}} {"id":100033323,"name":"unlockEntry","signature":"func (lm *lockMap) unlockEntry(entry string)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_utils.go","code":"func (lm *lockMap) unlockEntry(entry string) {\n\tlm.mutexMap[entry].Unlock()\n}","line":{"from":81,"to":83}} {"id":100033324,"name":"getContextWithCancel","signature":"func getContextWithCancel() (context.Context, context.CancelFunc)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_utils.go","code":"func getContextWithCancel() (context.Context, context.CancelFunc) {\n\treturn context.WithCancel(context.Background())\n}","line":{"from":85,"to":87}} {"id":100033325,"name":"ConvertTagsToMap","signature":"func ConvertTagsToMap(tags string) (map[string]string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_utils.go","code":"// ConvertTagsToMap convert the tags from string to map\n// the valid tags format is \"key1=value1,key2=value2\", which could be converted to\n// {\"key1\": \"value1\", \"key2\": \"value2\"}\nfunc ConvertTagsToMap(tags string) (map[string]string, error) {\n\tm := make(map[string]string)\n\tif tags == \"\" {\n\t\treturn m, nil\n\t}\n\ts := strings.Split(tags, tagsDelimiter)\n\tfor _, tag := range s {\n\t\tkv := strings.Split(tag, tagKeyValueDelimiter)\n\t\tif len(kv) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"Tags '%s' are invalid, the format should like: 'key1=value1,key2=value2'\", tags)\n\t\t}\n\t\tkey := strings.TrimSpace(kv[0])\n\t\tif key == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"Tags '%s' are invalid, the format should like: 'key1=value1,key2=value2'\", tags)\n\t\t}\n\t\tvalue := strings.TrimSpace(kv[1])\n\t\tm[key] = value\n\t}\n\n\treturn m, nil\n}","line":{"from":89,"to":112}} {"id":100033326,"name":"convertMapToMapPointer","signature":"func convertMapToMapPointer(origin map[string]string) map[string]*string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_utils.go","code":"func convertMapToMapPointer(origin map[string]string) map[string]*string {\n\tnewly := make(map[string]*string)\n\tfor k, v := range origin {\n\t\tvalue := v\n\t\tnewly[k] = \u0026value\n\t}\n\treturn newly\n}","line":{"from":114,"to":121}} {"id":100033327,"name":"parseTags","signature":"func parseTags(tags string) map[string]*string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_utils.go","code":"func parseTags(tags string) map[string]*string {\n\tkvs := strings.Split(tags, \",\")\n\tformatted := make(map[string]*string)\n\tfor _, kv := range kvs {\n\t\tres := strings.Split(kv, \"=\")\n\t\tif len(res) != 2 {\n\t\t\tklog.Warningf(\"parseTags: error when parsing key-value pair %s, would ignore this one\", kv)\n\t\t\tcontinue\n\t\t}\n\t\tk, v := strings.TrimSpace(res[0]), strings.TrimSpace(res[1])\n\t\tif k == \"\" || v == \"\" {\n\t\t\tklog.Warningf(\"parseTags: error when parsing key-value pair %s-%s, would ignore this one\", k, v)\n\t\t\tcontinue\n\t\t}\n\t\tformatted[strings.ToLower(k)] = pointer.String(v)\n\t}\n\treturn formatted\n}","line":{"from":123,"to":140}} {"id":100033328,"name":"findKeyInMapCaseInsensitive","signature":"func findKeyInMapCaseInsensitive(targetMap map[string]*string, key string) (bool, string)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_utils.go","code":"func findKeyInMapCaseInsensitive(targetMap map[string]*string, key string) (bool, string) {\n\tfor k := range targetMap {\n\t\tif strings.EqualFold(k, key) {\n\t\t\treturn true, k\n\t\t}\n\t}\n\n\treturn false, \"\"\n}","line":{"from":142,"to":150}} {"id":100033329,"name":"reconcileTags","signature":"func reconcileTags(currentTagsOnResource, newTags map[string]*string) (reconciledTags map[string]*string, changed bool)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_utils.go","code":"func reconcileTags(currentTagsOnResource, newTags map[string]*string) (reconciledTags map[string]*string, changed bool) {\n\tfor k, v := range newTags {\n\t\tfound, key := findKeyInMapCaseInsensitive(currentTagsOnResource, k)\n\t\tif !found {\n\t\t\tcurrentTagsOnResource[k] = v\n\t\t\tchanged = true\n\t\t} else if !strings.EqualFold(pointer.StringDeref(v, \"\"), pointer.StringDeref(currentTagsOnResource[key], \"\")) {\n\t\t\tcurrentTagsOnResource[key] = v\n\t\t\tchanged = true\n\t\t}\n\t}\n\n\treturn currentTagsOnResource, changed\n}","line":{"from":152,"to":165}} {"id":100033330,"name":"newScaleSet","signature":"func newScaleSet(az *Cloud) (VMSet, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// newScaleSet creates a new scaleSet.\nfunc newScaleSet(az *Cloud) (VMSet, error) {\n\tif az.Config.VmssVirtualMachinesCacheTTLInSeconds == 0 {\n\t\taz.Config.VmssVirtualMachinesCacheTTLInSeconds = vmssVirtualMachinesCacheTTLDefaultInSeconds\n\t}\n\tss := \u0026scaleSet{\n\t\tCloud: az,\n\t\tavailabilitySet: newAvailabilitySet(az),\n\t\tvmssVMCache: \u0026sync.Map{},\n\t}\n\n\tvar err error\n\tif !ss.DisableAvailabilitySetNodes {\n\t\tss.availabilitySetNodesCache, err = ss.newAvailabilitySetNodesCache()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tss.vmssCache, err = ss.newVMSSCache()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ss, nil\n}","line":{"from":87,"to":112}} {"id":100033331,"name":"getVMSS","signature":"func (ss *scaleSet) getVMSS(vmssName string, crt azcache.AzureCacheReadType) (*compute.VirtualMachineScaleSet, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"func (ss *scaleSet) getVMSS(vmssName string, crt azcache.AzureCacheReadType) (*compute.VirtualMachineScaleSet, error) {\n\tgetter := func(vmssName string) (*compute.VirtualMachineScaleSet, error) {\n\t\tcached, err := ss.vmssCache.Get(vmssKey, crt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvmsses := cached.(*sync.Map)\n\t\tif vmss, ok := vmsses.Load(vmssName); ok {\n\t\t\tresult := vmss.(*vmssEntry)\n\t\t\treturn result.vmss, nil\n\t\t}\n\n\t\treturn nil, nil\n\t}\n\n\tvmss, err := getter(vmssName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif vmss != nil {\n\t\treturn vmss, nil\n\t}\n\n\tklog.V(2).Infof(\"Couldn't find VMSS with name %s, refreshing the cache\", vmssName)\n\tss.vmssCache.Delete(vmssKey)\n\tvmss, err = getter(vmssName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif vmss == nil {\n\t\treturn nil, cloudprovider.InstanceNotFound\n\t}\n\treturn vmss, nil\n}","line":{"from":114,"to":149}} {"id":100033332,"name":"getVmssVMByNodeIdentity","signature":"func (ss *scaleSet) getVmssVMByNodeIdentity(node *nodeIdentity, crt azcache.AzureCacheReadType) (string, string, *compute.VirtualMachineScaleSetVM, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// getVmssVMByNodeIdentity find virtualMachineScaleSetVM by nodeIdentity, using node's parent VMSS cache.\n// Returns cloudprovider.InstanceNotFound if the node does not belong to the scale set named in nodeIdentity.\nfunc (ss *scaleSet) getVmssVMByNodeIdentity(node *nodeIdentity, crt azcache.AzureCacheReadType) (string, string, *compute.VirtualMachineScaleSetVM, error) {\n\tcacheKey, cache, err := ss.getVMSSVMCache(node.resourceGroup, node.vmssName)\n\tif err != nil {\n\t\treturn \"\", \"\", nil, err\n\t}\n\n\tgetter := func(nodeName string, crt azcache.AzureCacheReadType) (string, string, *compute.VirtualMachineScaleSetVM, bool, error) {\n\t\tvar found bool\n\t\tcached, err := cache.Get(cacheKey, crt)\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", nil, found, err\n\t\t}\n\n\t\tvirtualMachines := cached.(*sync.Map)\n\t\tif vm, ok := virtualMachines.Load(nodeName); ok {\n\t\t\tresult := vm.(*vmssVirtualMachinesEntry)\n\t\t\tfound = true\n\t\t\treturn result.vmssName, result.instanceID, result.virtualMachine, found, nil\n\t\t}\n\n\t\treturn \"\", \"\", nil, found, nil\n\t}\n\n\t_, err = getScaleSetVMInstanceID(node.nodeName)\n\tif err != nil {\n\t\treturn \"\", \"\", nil, err\n\t}\n\n\tvmssName, instanceID, vm, found, err := getter(node.nodeName, crt)\n\tif err != nil {\n\t\treturn \"\", \"\", nil, err\n\t}\n\n\tif !found {\n\t\tklog.V(2).Infof(\"Couldn't find VMSS VM with nodeName %s, refreshing the cache\", node.nodeName)\n\t\tvmssName, instanceID, vm, found, err = getter(node.nodeName, azcache.CacheReadTypeForceRefresh)\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", nil, err\n\t\t}\n\t}\n\n\tif found \u0026\u0026 vm != nil {\n\t\treturn vmssName, instanceID, vm, nil\n\t}\n\n\tif !found || vm == nil {\n\t\tklog.Warningf(\"Unable to find node %s: %v\", node.nodeName, cloudprovider.InstanceNotFound)\n\t\treturn \"\", \"\", nil, cloudprovider.InstanceNotFound\n\t}\n\treturn vmssName, instanceID, vm, nil\n}","line":{"from":151,"to":203}} {"id":100033333,"name":"getVmssVM","signature":"func (ss *scaleSet) getVmssVM(nodeName string, crt azcache.AzureCacheReadType) (string, string, *compute.VirtualMachineScaleSetVM, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// getVmssVM gets virtualMachineScaleSetVM by nodeName from cache.\n// Returns cloudprovider.InstanceNotFound if nodeName does not belong to any scale set.\nfunc (ss *scaleSet) getVmssVM(nodeName string, crt azcache.AzureCacheReadType) (string, string, *compute.VirtualMachineScaleSetVM, error) {\n\tnode, err := ss.getNodeIdentityByNodeName(nodeName, crt)\n\tif err != nil {\n\t\treturn \"\", \"\", nil, err\n\t}\n\n\treturn ss.getVmssVMByNodeIdentity(node, crt)\n}","line":{"from":205,"to":214}} {"id":100033334,"name":"GetPowerStatusByNodeName","signature":"func (ss *scaleSet) GetPowerStatusByNodeName(name string) (powerState string, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// GetPowerStatusByNodeName returns the power state of the specified node.\nfunc (ss *scaleSet) GetPowerStatusByNodeName(name string) (powerState string, err error) {\n\tmanagedByAS, err := ss.isNodeManagedByAvailabilitySet(name, azcache.CacheReadTypeUnsafe)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to check isNodeManagedByAvailabilitySet: %v\", err)\n\t\treturn \"\", err\n\t}\n\tif managedByAS {\n\t\t// vm is managed by availability set.\n\t\treturn ss.availabilitySet.GetPowerStatusByNodeName(name)\n\t}\n\n\t_, _, vm, err := ss.getVmssVM(name, azcache.CacheReadTypeDefault)\n\tif err != nil {\n\t\treturn powerState, err\n\t}\n\n\tif vm.InstanceView != nil \u0026\u0026 vm.InstanceView.Statuses != nil {\n\t\tstatuses := *vm.InstanceView.Statuses\n\t\tfor _, status := range statuses {\n\t\t\tstate := pointer.StringDeref(status.Code, \"\")\n\t\t\tif strings.HasPrefix(state, vmPowerStatePrefix) {\n\t\t\t\treturn strings.TrimPrefix(state, vmPowerStatePrefix), nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// vm.InstanceView or vm.InstanceView.Statuses are nil when the VM is under deleting.\n\tklog.V(3).Infof(\"InstanceView for node %q is nil, assuming it's stopped\", name)\n\treturn vmPowerStateStopped, nil\n}","line":{"from":216,"to":246}} {"id":100033335,"name":"GetProvisioningStateByNodeName","signature":"func (ss *scaleSet) GetProvisioningStateByNodeName(name string) (provisioningState string, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// GetProvisioningStateByNodeName returns the provisioningState for the specified node.\nfunc (ss *scaleSet) GetProvisioningStateByNodeName(name string) (provisioningState string, err error) {\n\tmanagedByAS, err := ss.isNodeManagedByAvailabilitySet(name, azcache.CacheReadTypeUnsafe)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to check isNodeManagedByAvailabilitySet: %v\", err)\n\t\treturn \"\", err\n\t}\n\tif managedByAS {\n\t\t// vm is managed by availability set.\n\t\treturn ss.availabilitySet.GetProvisioningStateByNodeName(name)\n\t}\n\n\t_, _, vm, err := ss.getVmssVM(name, azcache.CacheReadTypeDefault)\n\tif err != nil {\n\t\treturn provisioningState, err\n\t}\n\n\tif vm.VirtualMachineScaleSetVMProperties == nil || vm.VirtualMachineScaleSetVMProperties.ProvisioningState == nil {\n\t\treturn provisioningState, nil\n\t}\n\n\treturn pointer.StringDeref(vm.VirtualMachineScaleSetVMProperties.ProvisioningState, \"\"), nil\n}","line":{"from":248,"to":270}} {"id":100033336,"name":"getVmssVMByInstanceID","signature":"func (ss *scaleSet) getVmssVMByInstanceID(resourceGroup, scaleSetName, instanceID string, crt azcache.AzureCacheReadType) (*compute.VirtualMachineScaleSetVM, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// getCachedVirtualMachineByInstanceID gets scaleSetVMInfo from cache.\n// The node must belong to one of scale sets.\nfunc (ss *scaleSet) getVmssVMByInstanceID(resourceGroup, scaleSetName, instanceID string, crt azcache.AzureCacheReadType) (*compute.VirtualMachineScaleSetVM, error) {\n\tcacheKey, cache, err := ss.getVMSSVMCache(resourceGroup, scaleSetName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgetter := func(crt azcache.AzureCacheReadType) (vm *compute.VirtualMachineScaleSetVM, found bool, err error) {\n\t\tcached, err := cache.Get(cacheKey, crt)\n\t\tif err != nil {\n\t\t\treturn nil, false, err\n\t\t}\n\n\t\tvirtualMachines := cached.(*sync.Map)\n\t\tvirtualMachines.Range(func(key, value interface{}) bool {\n\t\t\tvmEntry := value.(*vmssVirtualMachinesEntry)\n\t\t\tif strings.EqualFold(vmEntry.resourceGroup, resourceGroup) \u0026\u0026\n\t\t\t\tstrings.EqualFold(vmEntry.vmssName, scaleSetName) \u0026\u0026\n\t\t\t\tstrings.EqualFold(vmEntry.instanceID, instanceID) {\n\t\t\t\tvm = vmEntry.virtualMachine\n\t\t\t\tfound = true\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\treturn true\n\t\t})\n\n\t\treturn vm, found, nil\n\t}\n\n\tvm, found, err := getter(crt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !found {\n\t\tklog.V(2).Infof(\"Couldn't find VMSS VM with scaleSetName %q and instanceID %q, refreshing the cache\", scaleSetName, instanceID)\n\t\tvm, found, err = getter(azcache.CacheReadTypeForceRefresh)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif found \u0026\u0026 vm != nil {\n\t\treturn vm, nil\n\t}\n\tif found \u0026\u0026 vm == nil {\n\t\tklog.V(2).Infof(\"Couldn't find VMSS VM with scaleSetName %q and instanceID %q, refreshing the cache if it is expired\", scaleSetName, instanceID)\n\t\tvm, found, err = getter(azcache.CacheReadTypeDefault)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif !found || vm == nil {\n\t\treturn nil, cloudprovider.InstanceNotFound\n\t}\n\n\treturn vm, nil\n}","line":{"from":272,"to":329}} {"id":100033337,"name":"GetInstanceIDByNodeName","signature":"func (ss *scaleSet) GetInstanceIDByNodeName(name string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// GetInstanceIDByNodeName gets the cloud provider ID by node name.\n// It must return (\"\", cloudprovider.InstanceNotFound) if the instance does\n// not exist or is no longer running.\nfunc (ss *scaleSet) GetInstanceIDByNodeName(name string) (string, error) {\n\tmanagedByAS, err := ss.isNodeManagedByAvailabilitySet(name, azcache.CacheReadTypeUnsafe)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to check isNodeManagedByAvailabilitySet: %v\", err)\n\t\treturn \"\", err\n\t}\n\tif managedByAS {\n\t\t// vm is managed by availability set.\n\t\treturn ss.availabilitySet.GetInstanceIDByNodeName(name)\n\t}\n\n\t_, _, vm, err := ss.getVmssVM(name, azcache.CacheReadTypeUnsafe)\n\tif err != nil {\n\t\tklog.Errorf(\"Unable to find node %s: %v\", name, err)\n\t\treturn \"\", err\n\t}\n\n\tresourceID := *vm.ID\n\tconvertedResourceID, err := convertResourceGroupNameToLower(resourceID)\n\tif err != nil {\n\t\tklog.Errorf(\"convertResourceGroupNameToLower failed with error: %v\", err)\n\t\treturn \"\", err\n\t}\n\treturn convertedResourceID, nil\n}","line":{"from":331,"to":358}} {"id":100033338,"name":"GetNodeNameByProviderID","signature":"func (ss *scaleSet) GetNodeNameByProviderID(providerID string) (types.NodeName, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// GetNodeNameByProviderID gets the node name by provider ID.\n// providerID example:\n// 1. vmas providerID: azure:///subscriptions/subsid/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/aks-nodepool1-27053986-0\n// 2. vmss providerID:\n// azure:///subscriptions/subsid/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/aks-agentpool-22126781-vmss/virtualMachines/1\n// /subscriptions/subsid/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/aks-agentpool-22126781-vmss/virtualMachines/k8s-agentpool-36841236-vmss_1\nfunc (ss *scaleSet) GetNodeNameByProviderID(providerID string) (types.NodeName, error) {\n\t// NodeName is not part of providerID for vmss instances.\n\tscaleSetName, err := extractScaleSetNameByProviderID(providerID)\n\tif err != nil {\n\t\tklog.V(4).Infof(\"Can not extract scale set name from providerID (%s), assuming it is managed by availability set: %v\", providerID, err)\n\t\treturn ss.availabilitySet.GetNodeNameByProviderID(providerID)\n\t}\n\n\tresourceGroup, err := extractResourceGroupByProviderID(providerID)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error of extracting resource group for node %q\", providerID)\n\t}\n\n\tinstanceID, err := getLastSegment(providerID, \"/\")\n\tif err != nil {\n\t\tklog.V(4).Infof(\"Can not extract instanceID from providerID (%s), assuming it is managed by availability set: %v\", providerID, err)\n\t\treturn ss.availabilitySet.GetNodeNameByProviderID(providerID)\n\t}\n\n\t// instanceID contains scaleSetName (returned by disk.ManagedBy), e.g. k8s-agentpool-36841236-vmss_1\n\tif strings.HasPrefix(strings.ToLower(instanceID), strings.ToLower(scaleSetName)) {\n\t\tinstanceID, err = getLastSegment(instanceID, \"_\")\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tvm, err := ss.getVmssVMByInstanceID(resourceGroup, scaleSetName, instanceID, azcache.CacheReadTypeUnsafe)\n\tif err != nil {\n\t\tklog.Errorf(\"Unable to find node by providerID %s: %v\", providerID, err)\n\t\treturn \"\", err\n\t}\n\n\tif vm.OsProfile != nil \u0026\u0026 vm.OsProfile.ComputerName != nil {\n\t\tnodeName := strings.ToLower(*vm.OsProfile.ComputerName)\n\t\treturn types.NodeName(nodeName), nil\n\t}\n\n\treturn \"\", nil\n}","line":{"from":360,"to":405}} {"id":100033339,"name":"GetInstanceTypeByNodeName","signature":"func (ss *scaleSet) GetInstanceTypeByNodeName(name string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// GetInstanceTypeByNodeName gets the instance type by node name.\nfunc (ss *scaleSet) GetInstanceTypeByNodeName(name string) (string, error) {\n\tmanagedByAS, err := ss.isNodeManagedByAvailabilitySet(name, azcache.CacheReadTypeUnsafe)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to check isNodeManagedByAvailabilitySet: %v\", err)\n\t\treturn \"\", err\n\t}\n\tif managedByAS {\n\t\t// vm is managed by availability set.\n\t\treturn ss.availabilitySet.GetInstanceTypeByNodeName(name)\n\t}\n\n\t_, _, vm, err := ss.getVmssVM(name, azcache.CacheReadTypeUnsafe)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif vm.Sku != nil \u0026\u0026 vm.Sku.Name != nil {\n\t\treturn *vm.Sku.Name, nil\n\t}\n\n\treturn \"\", nil\n}","line":{"from":407,"to":429}} {"id":100033340,"name":"GetZoneByNodeName","signature":"func (ss *scaleSet) GetZoneByNodeName(name string) (cloudprovider.Zone, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// GetZoneByNodeName gets availability zone for the specified node. If the node is not running\n// with availability zone, then it returns fault domain.\nfunc (ss *scaleSet) GetZoneByNodeName(name string) (cloudprovider.Zone, error) {\n\tmanagedByAS, err := ss.isNodeManagedByAvailabilitySet(name, azcache.CacheReadTypeUnsafe)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to check isNodeManagedByAvailabilitySet: %v\", err)\n\t\treturn cloudprovider.Zone{}, err\n\t}\n\tif managedByAS {\n\t\t// vm is managed by availability set.\n\t\treturn ss.availabilitySet.GetZoneByNodeName(name)\n\t}\n\n\t_, _, vm, err := ss.getVmssVM(name, azcache.CacheReadTypeUnsafe)\n\tif err != nil {\n\t\treturn cloudprovider.Zone{}, err\n\t}\n\n\tvar failureDomain string\n\tif vm.Zones != nil \u0026\u0026 len(*vm.Zones) \u003e 0 {\n\t\t// Get availability zone for the node.\n\t\tzones := *vm.Zones\n\t\tzoneID, err := strconv.Atoi(zones[0])\n\t\tif err != nil {\n\t\t\treturn cloudprovider.Zone{}, fmt.Errorf(\"failed to parse zone %q: %v\", zones, err)\n\t\t}\n\n\t\tfailureDomain = ss.makeZone(pointer.StringDeref(vm.Location, \"\"), zoneID)\n\t} else if vm.InstanceView != nil \u0026\u0026 vm.InstanceView.PlatformFaultDomain != nil {\n\t\t// Availability zone is not used for the node, falling back to fault domain.\n\t\tfailureDomain = strconv.Itoa(int(*vm.InstanceView.PlatformFaultDomain))\n\t} else {\n\t\terr = fmt.Errorf(\"failed to get zone info\")\n\t\tklog.Errorf(\"GetZoneByNodeName: got unexpected error %v\", err)\n\t\tss.deleteCacheForNode(name)\n\t\treturn cloudprovider.Zone{}, err\n\t}\n\n\treturn cloudprovider.Zone{\n\t\tFailureDomain: strings.ToLower(failureDomain),\n\t\tRegion: strings.ToLower(pointer.StringDeref(vm.Location, \"\")),\n\t}, nil\n}","line":{"from":431,"to":473}} {"id":100033341,"name":"GetPrimaryVMSetName","signature":"func (ss *scaleSet) GetPrimaryVMSetName() string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// GetPrimaryVMSetName returns the VM set name depending on the configured vmType.\n// It returns config.PrimaryScaleSetName for vmss and config.PrimaryAvailabilitySetName for standard vmType.\nfunc (ss *scaleSet) GetPrimaryVMSetName() string {\n\treturn ss.Config.PrimaryScaleSetName\n}","line":{"from":475,"to":479}} {"id":100033342,"name":"GetIPByNodeName","signature":"func (ss *scaleSet) GetIPByNodeName(nodeName string) (string, string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// GetIPByNodeName gets machine private IP and public IP by node name.\nfunc (ss *scaleSet) GetIPByNodeName(nodeName string) (string, string, error) {\n\tnic, err := ss.GetPrimaryInterface(nodeName)\n\tif err != nil {\n\t\tklog.Errorf(\"error: ss.GetIPByNodeName(%s), GetPrimaryInterface(%q), err=%v\", nodeName, nodeName, err)\n\t\treturn \"\", \"\", err\n\t}\n\n\tipConfig, err := getPrimaryIPConfig(nic)\n\tif err != nil {\n\t\tklog.Errorf(\"error: ss.GetIPByNodeName(%s), getPrimaryIPConfig(%v), err=%v\", nodeName, nic, err)\n\t\treturn \"\", \"\", err\n\t}\n\n\tinternalIP := *ipConfig.PrivateIPAddress\n\tpublicIP := \"\"\n\tif ipConfig.PublicIPAddress != nil \u0026\u0026 ipConfig.PublicIPAddress.ID != nil {\n\t\tpipID := *ipConfig.PublicIPAddress.ID\n\t\tmatches := vmssPIPConfigurationRE.FindStringSubmatch(pipID)\n\t\tif len(matches) == 7 {\n\t\t\tresourceGroupName := matches[1]\n\t\t\tvirtualMachineScaleSetName := matches[2]\n\t\t\tvirtualMachineIndex := matches[3]\n\t\t\tnetworkInterfaceName := matches[4]\n\t\t\tIPConfigurationName := matches[5]\n\t\t\tpublicIPAddressName := matches[6]\n\t\t\tpip, existsPip, err := ss.getVMSSPublicIPAddress(resourceGroupName, virtualMachineScaleSetName, virtualMachineIndex, networkInterfaceName, IPConfigurationName, publicIPAddressName)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"ss.getVMSSPublicIPAddress() failed with error: %v\", err)\n\t\t\t\treturn \"\", \"\", err\n\t\t\t}\n\t\t\tif existsPip \u0026\u0026 pip.IPAddress != nil {\n\t\t\t\tpublicIP = *pip.IPAddress\n\t\t\t}\n\t\t} else {\n\t\t\tklog.Warningf(\"Failed to get VMSS Public IP with ID %s\", pipID)\n\t\t}\n\t}\n\n\treturn internalIP, publicIP, nil\n}","line":{"from":481,"to":521}} {"id":100033343,"name":"getVMSSPublicIPAddress","signature":"func (ss *scaleSet) getVMSSPublicIPAddress(resourceGroupName string, virtualMachineScaleSetName string, virtualMachineIndex string, networkInterfaceName string, IPConfigurationName string, publicIPAddressName string) (network.PublicIPAddress, bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"func (ss *scaleSet) getVMSSPublicIPAddress(resourceGroupName string, virtualMachineScaleSetName string, virtualMachineIndex string, networkInterfaceName string, IPConfigurationName string, publicIPAddressName string) (network.PublicIPAddress, bool, error) {\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\n\tpip, err := ss.PublicIPAddressesClient.GetVirtualMachineScaleSetPublicIPAddress(ctx, resourceGroupName, virtualMachineScaleSetName, virtualMachineIndex, networkInterfaceName, IPConfigurationName, publicIPAddressName, \"\")\n\texists, rerr := checkResourceExistsFromError(err)\n\tif rerr != nil {\n\t\treturn pip, false, rerr.Error()\n\t}\n\n\tif !exists {\n\t\tklog.V(2).Infof(\"Public IP %q not found\", publicIPAddressName)\n\t\treturn pip, false, nil\n\t}\n\n\treturn pip, exists, nil\n}","line":{"from":523,"to":539}} {"id":100033344,"name":"GetPrivateIPsByNodeName","signature":"func (ss *scaleSet) GetPrivateIPsByNodeName(nodeName string) ([]string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// returns a list of private ips assigned to node\n// TODO (khenidak): This should read all nics, not just the primary\n// allowing users to split ipv4/v6 on multiple nics\nfunc (ss *scaleSet) GetPrivateIPsByNodeName(nodeName string) ([]string, error) {\n\tips := make([]string, 0)\n\tnic, err := ss.GetPrimaryInterface(nodeName)\n\tif err != nil {\n\t\tklog.Errorf(\"error: ss.GetIPByNodeName(%s), GetPrimaryInterface(%q), err=%v\", nodeName, nodeName, err)\n\t\treturn ips, err\n\t}\n\n\tif nic.IPConfigurations == nil {\n\t\treturn ips, fmt.Errorf(\"nic.IPConfigurations for nic (nicname=%q) is nil\", *nic.Name)\n\t}\n\n\tfor _, ipConfig := range *(nic.IPConfigurations) {\n\t\tif ipConfig.PrivateIPAddress != nil {\n\t\t\tips = append(ips, *(ipConfig.PrivateIPAddress))\n\t\t}\n\t}\n\n\treturn ips, nil\n}","line":{"from":541,"to":563}} {"id":100033345,"name":"getPrimaryInterfaceID","signature":"func (ss *scaleSet) getPrimaryInterfaceID(machine compute.VirtualMachineScaleSetVM) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// This returns the full identifier of the primary NIC for the given VM.\nfunc (ss *scaleSet) getPrimaryInterfaceID(machine compute.VirtualMachineScaleSetVM) (string, error) {\n\tif machine.NetworkProfile == nil || machine.NetworkProfile.NetworkInterfaces == nil {\n\t\treturn \"\", fmt.Errorf(\"failed to find the network interfaces for vm %s\", pointer.StringDeref(machine.Name, \"\"))\n\t}\n\n\tif len(*machine.NetworkProfile.NetworkInterfaces) == 1 {\n\t\treturn *(*machine.NetworkProfile.NetworkInterfaces)[0].ID, nil\n\t}\n\n\tfor _, ref := range *machine.NetworkProfile.NetworkInterfaces {\n\t\tif pointer.BoolDeref(ref.Primary, false) {\n\t\t\treturn *ref.ID, nil\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"failed to find a primary nic for the vm. vmname=%q\", pointer.StringDeref(machine.Name, \"\"))\n}","line":{"from":565,"to":582}} {"id":100033346,"name":"getVmssMachineID","signature":"func (az *Cloud) getVmssMachineID(subscriptionID, resourceGroup, scaleSetName, instanceID string) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// getVmssMachineID returns the full identifier of a vmss virtual machine.\nfunc (az *Cloud) getVmssMachineID(subscriptionID, resourceGroup, scaleSetName, instanceID string) string {\n\treturn fmt.Sprintf(\n\t\tvmssMachineIDTemplate,\n\t\tsubscriptionID,\n\t\tstrings.ToLower(resourceGroup),\n\t\tscaleSetName,\n\t\tinstanceID)\n}","line":{"from":584,"to":592}} {"id":100033347,"name":"getScaleSetVMInstanceID","signature":"func getScaleSetVMInstanceID(machineName string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// machineName is composed of computerNamePrefix and 36-based instanceID.\n// And instanceID part if in fixed length of 6 characters.\n// Refer https://msftstack.wordpress.com/2017/05/10/figuring-out-azure-vm-scale-set-machine-names/.\nfunc getScaleSetVMInstanceID(machineName string) (string, error) {\n\tnameLength := len(machineName)\n\tif nameLength \u003c 6 {\n\t\treturn \"\", ErrorNotVmssInstance\n\t}\n\n\tinstanceID, err := strconv.ParseUint(machineName[nameLength-6:], 36, 64)\n\tif err != nil {\n\t\treturn \"\", ErrorNotVmssInstance\n\t}\n\n\treturn fmt.Sprintf(\"%d\", instanceID), nil\n}","line":{"from":594,"to":609}} {"id":100033348,"name":"extractScaleSetNameByProviderID","signature":"func extractScaleSetNameByProviderID(providerID string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// extractScaleSetNameByProviderID extracts the scaleset name by vmss node's ProviderID.\nfunc extractScaleSetNameByProviderID(providerID string) (string, error) {\n\tmatches := scaleSetNameRE.FindStringSubmatch(providerID)\n\tif len(matches) != 2 {\n\t\treturn \"\", ErrorNotVmssInstance\n\t}\n\n\treturn matches[1], nil\n}","line":{"from":611,"to":619}} {"id":100033349,"name":"extractResourceGroupByProviderID","signature":"func extractResourceGroupByProviderID(providerID string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// extractResourceGroupByProviderID extracts the resource group name by vmss node's ProviderID.\nfunc extractResourceGroupByProviderID(providerID string) (string, error) {\n\tmatches := resourceGroupRE.FindStringSubmatch(providerID)\n\tif len(matches) != 2 {\n\t\treturn \"\", ErrorNotVmssInstance\n\t}\n\n\treturn matches[1], nil\n}","line":{"from":621,"to":629}} {"id":100033350,"name":"listScaleSets","signature":"func (ss *scaleSet) listScaleSets(resourceGroup string) ([]string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// listScaleSets lists all scale sets with orchestrationMode ScaleSetVM.\nfunc (ss *scaleSet) listScaleSets(resourceGroup string) ([]string, error) {\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\n\tallScaleSets, rerr := ss.VirtualMachineScaleSetsClient.List(ctx, resourceGroup)\n\tif rerr != nil {\n\t\tklog.Errorf(\"VirtualMachineScaleSetsClient.List failed: %v\", rerr)\n\t\treturn nil, rerr.Error()\n\t}\n\n\tssNames := make([]string, 0)\n\tfor _, vmss := range allScaleSets {\n\t\tname := *vmss.Name\n\t\tif vmss.Sku != nil \u0026\u0026 pointer.Int64Deref(vmss.Sku.Capacity, 0) == 0 {\n\t\t\tklog.V(3).Infof(\"Capacity of VMSS %q is 0, skipping\", name)\n\t\t\tcontinue\n\t\t}\n\n\t\tif vmss.VirtualMachineScaleSetProperties == nil || vmss.VirtualMachineScaleSetProperties.VirtualMachineProfile == nil {\n\t\t\tklog.V(3).Infof(\"VMSS %q orchestrationMode is VirtualMachine, skipping\", name)\n\t\t\tcontinue\n\t\t}\n\n\t\tssNames = append(ssNames, name)\n\t}\n\n\treturn ssNames, nil\n}","line":{"from":631,"to":659}} {"id":100033351,"name":"getNodeIdentityByNodeName","signature":"func (ss *scaleSet) getNodeIdentityByNodeName(nodeName string, crt azcache.AzureCacheReadType) (*nodeIdentity, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// getNodeIdentityByNodeName use the VMSS cache to find a node's resourcegroup and vmss, returned in a nodeIdentity.\nfunc (ss *scaleSet) getNodeIdentityByNodeName(nodeName string, crt azcache.AzureCacheReadType) (*nodeIdentity, error) {\n\tgetter := func(nodeName string, crt azcache.AzureCacheReadType) (*nodeIdentity, error) {\n\t\tnode := \u0026nodeIdentity{\n\t\t\tnodeName: nodeName,\n\t\t}\n\n\t\tcached, err := ss.vmssCache.Get(vmssKey, crt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvmsses := cached.(*sync.Map)\n\t\tvmsses.Range(func(key, value interface{}) bool {\n\t\t\tv := value.(*vmssEntry)\n\t\t\tif v.vmss.Name == nil {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tvmssPrefix := *v.vmss.Name\n\t\t\tif v.vmss.VirtualMachineProfile != nil \u0026\u0026\n\t\t\t\tv.vmss.VirtualMachineProfile.OsProfile != nil \u0026\u0026\n\t\t\t\tv.vmss.VirtualMachineProfile.OsProfile.ComputerNamePrefix != nil {\n\t\t\t\tvmssPrefix = *v.vmss.VirtualMachineProfile.OsProfile.ComputerNamePrefix\n\t\t\t}\n\n\t\t\tif strings.EqualFold(vmssPrefix, nodeName[:len(nodeName)-6]) {\n\t\t\t\tnode.vmssName = *v.vmss.Name\n\t\t\t\tnode.resourceGroup = v.resourceGroup\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\treturn true\n\t\t})\n\t\treturn node, nil\n\t}\n\n\tif _, err := getScaleSetVMInstanceID(nodeName); err != nil {\n\t\treturn nil, err\n\t}\n\n\tnode, err := getter(nodeName, crt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif node.vmssName != \"\" {\n\t\treturn node, nil\n\t}\n\n\tklog.V(2).Infof(\"Couldn't find VMSS for node %s, refreshing the cache\", nodeName)\n\tnode, err = getter(nodeName, azcache.CacheReadTypeForceRefresh)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif node.vmssName == \"\" {\n\t\tklog.Warningf(\"Unable to find node %s: %v\", nodeName, cloudprovider.InstanceNotFound)\n\t\treturn nil, cloudprovider.InstanceNotFound\n\t}\n\treturn node, nil\n}","line":{"from":661,"to":720}} {"id":100033352,"name":"listScaleSetVMs","signature":"func (ss *scaleSet) listScaleSetVMs(scaleSetName, resourceGroup string) ([]compute.VirtualMachineScaleSetVM, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// listScaleSetVMs lists VMs belonging to the specified scale set.\nfunc (ss *scaleSet) listScaleSetVMs(scaleSetName, resourceGroup string) ([]compute.VirtualMachineScaleSetVM, error) {\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\n\tallVMs, rerr := ss.VirtualMachineScaleSetVMsClient.List(ctx, resourceGroup, scaleSetName, string(compute.InstanceView))\n\tif rerr != nil {\n\t\tklog.Errorf(\"VirtualMachineScaleSetVMsClient.List(%s, %s) failed: %v\", resourceGroup, scaleSetName, rerr)\n\t\tif rerr.IsNotFound() {\n\t\t\treturn nil, cloudprovider.InstanceNotFound\n\t\t}\n\t\treturn nil, rerr.Error()\n\t}\n\n\treturn allVMs, nil\n}","line":{"from":722,"to":737}} {"id":100033353,"name":"getAgentPoolScaleSets","signature":"func (ss *scaleSet) getAgentPoolScaleSets(nodes []*v1.Node) (*[]string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// getAgentPoolScaleSets lists the virtual machines for the resource group and then builds\n// a list of scale sets that match the nodes available to k8s.\nfunc (ss *scaleSet) getAgentPoolScaleSets(nodes []*v1.Node) (*[]string, error) {\n\tagentPoolScaleSets := \u0026[]string{}\n\tfor nx := range nodes {\n\t\tif isMasterNode(nodes[nx]) {\n\t\t\tcontinue\n\t\t}\n\n\t\tnodeName := nodes[nx].Name\n\t\tshouldExcludeLoadBalancer, err := ss.ShouldNodeExcludedFromLoadBalancer(nodeName)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"ShouldNodeExcludedFromLoadBalancer(%s) failed with error: %v\", nodeName, err)\n\t\t\treturn nil, err\n\t\t}\n\t\tif shouldExcludeLoadBalancer {\n\t\t\tcontinue\n\t\t}\n\n\t\tssName, _, _, err := ss.getVmssVM(nodeName, azcache.CacheReadTypeDefault)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif ssName == \"\" {\n\t\t\tklog.V(3).Infof(\"Node %q is not belonging to any known scale sets\", nodeName)\n\t\t\tcontinue\n\t\t}\n\n\t\t*agentPoolScaleSets = append(*agentPoolScaleSets, ssName)\n\t}\n\n\treturn agentPoolScaleSets, nil\n}","line":{"from":739,"to":772}} {"id":100033354,"name":"GetVMSetNames","signature":"func (ss *scaleSet) GetVMSetNames(service *v1.Service, nodes []*v1.Node) (*[]string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// GetVMSetNames selects all possible availability sets or scale sets\n// (depending vmType configured) for service load balancer. If the service has\n// no loadbalancer mode annotation returns the primary VMSet. If service annotation\n// for loadbalancer exists then return the eligible VMSet.\nfunc (ss *scaleSet) GetVMSetNames(service *v1.Service, nodes []*v1.Node) (*[]string, error) {\n\thasMode, isAuto, serviceVMSetNames := getServiceLoadBalancerMode(service)\n\tuseSingleSLB := ss.useStandardLoadBalancer() \u0026\u0026 !ss.EnableMultipleStandardLoadBalancers\n\tif !hasMode || useSingleSLB {\n\t\t// no mode specified in service annotation or use single SLB mode\n\t\t// default to PrimaryScaleSetName\n\t\tscaleSetNames := \u0026[]string{ss.Config.PrimaryScaleSetName}\n\t\treturn scaleSetNames, nil\n\t}\n\n\tscaleSetNames, err := ss.getAgentPoolScaleSets(nodes)\n\tif err != nil {\n\t\tklog.Errorf(\"ss.GetVMSetNames - getAgentPoolScaleSets failed err=(%v)\", err)\n\t\treturn nil, err\n\t}\n\tif len(*scaleSetNames) == 0 {\n\t\tklog.Errorf(\"ss.GetVMSetNames - No scale sets found for nodes in the cluster, node count(%d)\", len(nodes))\n\t\treturn nil, fmt.Errorf(\"no scale sets found for nodes, node count(%d)\", len(nodes))\n\t}\n\n\t// sort the list to have deterministic selection\n\tsort.Strings(*scaleSetNames)\n\n\tif !isAuto {\n\t\tif len(serviceVMSetNames) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"service annotation for LoadBalancerMode is empty, it should have __auto__ or availability sets value\")\n\t\t}\n\t\t// validate scale set exists\n\t\tvar found bool\n\t\tfor sasx := range serviceVMSetNames {\n\t\t\tfor asx := range *scaleSetNames {\n\t\t\t\tif strings.EqualFold((*scaleSetNames)[asx], serviceVMSetNames[sasx]) {\n\t\t\t\t\tfound = true\n\t\t\t\t\tserviceVMSetNames[sasx] = (*scaleSetNames)[asx]\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\tklog.Errorf(\"ss.GetVMSetNames - scale set (%s) in service annotation not found\", serviceVMSetNames[sasx])\n\t\t\t\treturn nil, fmt.Errorf(\"scale set (%s) - not found\", serviceVMSetNames[sasx])\n\t\t\t}\n\t\t}\n\t\tscaleSetNames = \u0026serviceVMSetNames\n\t}\n\n\treturn scaleSetNames, nil\n}","line":{"from":774,"to":824}} {"id":100033355,"name":"extractResourceGroupByVMSSNicID","signature":"func extractResourceGroupByVMSSNicID(nicID string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// extractResourceGroupByVMSSNicID extracts the resource group name by vmss nicID.\nfunc extractResourceGroupByVMSSNicID(nicID string) (string, error) {\n\tmatches := vmssIPConfigurationRE.FindStringSubmatch(nicID)\n\tif len(matches) != 4 {\n\t\treturn \"\", fmt.Errorf(\"error of extracting resourceGroup from nicID %q\", nicID)\n\t}\n\n\treturn matches[1], nil\n}","line":{"from":826,"to":834}} {"id":100033356,"name":"GetPrimaryInterface","signature":"func (ss *scaleSet) GetPrimaryInterface(nodeName string) (network.Interface, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// GetPrimaryInterface gets machine primary network interface by node name and vmSet.\nfunc (ss *scaleSet) GetPrimaryInterface(nodeName string) (network.Interface, error) {\n\tmanagedByAS, err := ss.isNodeManagedByAvailabilitySet(nodeName, azcache.CacheReadTypeDefault)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to check isNodeManagedByAvailabilitySet: %v\", err)\n\t\treturn network.Interface{}, err\n\t}\n\tif managedByAS {\n\t\t// vm is managed by availability set.\n\t\treturn ss.availabilitySet.GetPrimaryInterface(nodeName)\n\t}\n\n\tssName, instanceID, vm, err := ss.getVmssVM(nodeName, azcache.CacheReadTypeDefault)\n\tif err != nil {\n\t\t// VM is availability set, but not cached yet in availabilitySetNodesCache.\n\t\tif err == ErrorNotVmssInstance {\n\t\t\treturn ss.availabilitySet.GetPrimaryInterface(nodeName)\n\t\t}\n\n\t\tklog.Errorf(\"error: ss.GetPrimaryInterface(%s), ss.getVmssVM(%s), err=%v\", nodeName, nodeName, err)\n\t\treturn network.Interface{}, err\n\t}\n\n\tprimaryInterfaceID, err := ss.getPrimaryInterfaceID(*vm)\n\tif err != nil {\n\t\tklog.Errorf(\"error: ss.GetPrimaryInterface(%s), ss.getPrimaryInterfaceID(), err=%v\", nodeName, err)\n\t\treturn network.Interface{}, err\n\t}\n\n\tnicName, err := getLastSegment(primaryInterfaceID, \"/\")\n\tif err != nil {\n\t\tklog.Errorf(\"error: ss.GetPrimaryInterface(%s), getLastSegment(%s), err=%v\", nodeName, primaryInterfaceID, err)\n\t\treturn network.Interface{}, err\n\t}\n\tresourceGroup, err := extractResourceGroupByVMSSNicID(primaryInterfaceID)\n\tif err != nil {\n\t\treturn network.Interface{}, err\n\t}\n\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\tnic, rerr := ss.InterfacesClient.GetVirtualMachineScaleSetNetworkInterface(ctx, resourceGroup, ssName, instanceID, nicName, \"\")\n\tif rerr != nil {\n\t\texists, realErr := checkResourceExistsFromError(rerr)\n\t\tif realErr != nil {\n\t\t\tklog.Errorf(\"error: ss.GetPrimaryInterface(%s), ss.GetVirtualMachineScaleSetNetworkInterface.Get(%s, %s, %s), err=%v\", nodeName, resourceGroup, ssName, nicName, realErr)\n\t\t\treturn network.Interface{}, realErr.Error()\n\t\t}\n\n\t\tif !exists {\n\t\t\treturn network.Interface{}, cloudprovider.InstanceNotFound\n\t\t}\n\t}\n\n\t// Fix interface's location, which is required when updating the interface.\n\t// TODO: is this a bug of azure SDK?\n\tif nic.Location == nil || *nic.Location == \"\" {\n\t\tnic.Location = vm.Location\n\t}\n\n\treturn nic, nil\n}","line":{"from":836,"to":897}} {"id":100033357,"name":"getPrimaryNetworkInterfaceConfiguration","signature":"func (ss *scaleSet) getPrimaryNetworkInterfaceConfiguration(networkConfigurations []compute.VirtualMachineScaleSetNetworkConfiguration, nodeName string) (*compute.VirtualMachineScaleSetNetworkConfiguration, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// getPrimaryNetworkInterfaceConfiguration gets primary network interface configuration for scale set virtual machine.\nfunc (ss *scaleSet) getPrimaryNetworkInterfaceConfiguration(networkConfigurations []compute.VirtualMachineScaleSetNetworkConfiguration, nodeName string) (*compute.VirtualMachineScaleSetNetworkConfiguration, error) {\n\tif len(networkConfigurations) == 1 {\n\t\treturn \u0026networkConfigurations[0], nil\n\t}\n\n\tfor idx := range networkConfigurations {\n\t\tnetworkConfig := \u0026networkConfigurations[idx]\n\t\tif networkConfig.Primary != nil \u0026\u0026 *networkConfig.Primary == true {\n\t\t\treturn networkConfig, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"failed to find a primary network configuration for the scale set VM %q\", nodeName)\n}","line":{"from":899,"to":913}} {"id":100033358,"name":"getPrimaryNetworkInterfaceConfigurationForScaleSet","signature":"func (ss *scaleSet) getPrimaryNetworkInterfaceConfigurationForScaleSet(networkConfigurations []compute.VirtualMachineScaleSetNetworkConfiguration, vmssName string) (*compute.VirtualMachineScaleSetNetworkConfiguration, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// getPrimaryNetworkInterfaceConfigurationForScaleSet gets primary network interface configuration for scale set.\nfunc (ss *scaleSet) getPrimaryNetworkInterfaceConfigurationForScaleSet(networkConfigurations []compute.VirtualMachineScaleSetNetworkConfiguration, vmssName string) (*compute.VirtualMachineScaleSetNetworkConfiguration, error) {\n\tif len(networkConfigurations) == 1 {\n\t\treturn \u0026networkConfigurations[0], nil\n\t}\n\n\tfor idx := range networkConfigurations {\n\t\tnetworkConfig := \u0026networkConfigurations[idx]\n\t\tif networkConfig.Primary != nil \u0026\u0026 *networkConfig.Primary == true {\n\t\t\treturn networkConfig, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"failed to find a primary network configuration for the scale set %q\", vmssName)\n}","line":{"from":915,"to":929}} {"id":100033359,"name":"getPrimaryIPConfigFromVMSSNetworkConfig","signature":"func getPrimaryIPConfigFromVMSSNetworkConfig(config *compute.VirtualMachineScaleSetNetworkConfiguration) (*compute.VirtualMachineScaleSetIPConfiguration, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"func getPrimaryIPConfigFromVMSSNetworkConfig(config *compute.VirtualMachineScaleSetNetworkConfiguration) (*compute.VirtualMachineScaleSetIPConfiguration, error) {\n\tipConfigurations := *config.IPConfigurations\n\tif len(ipConfigurations) == 1 {\n\t\treturn \u0026ipConfigurations[0], nil\n\t}\n\n\tfor idx := range ipConfigurations {\n\t\tipConfig := \u0026ipConfigurations[idx]\n\t\tif ipConfig.Primary != nil \u0026\u0026 *ipConfig.Primary == true {\n\t\t\treturn ipConfig, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"failed to find a primary IP configuration\")\n}","line":{"from":931,"to":945}} {"id":100033360,"name":"getConfigForScaleSetByIPFamily","signature":"func (ss *scaleSet) getConfigForScaleSetByIPFamily(config *compute.VirtualMachineScaleSetNetworkConfiguration, nodeName string, IPv6 bool) (*compute.VirtualMachineScaleSetIPConfiguration, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"func (ss *scaleSet) getConfigForScaleSetByIPFamily(config *compute.VirtualMachineScaleSetNetworkConfiguration, nodeName string, IPv6 bool) (*compute.VirtualMachineScaleSetIPConfiguration, error) {\n\tipConfigurations := *config.IPConfigurations\n\n\tvar ipVersion compute.IPVersion\n\tif IPv6 {\n\t\tipVersion = compute.IPv6\n\t} else {\n\t\tipVersion = compute.IPv4\n\t}\n\tfor idx := range ipConfigurations {\n\t\tipConfig := \u0026ipConfigurations[idx]\n\t\tif ipConfig.PrivateIPAddressVersion == ipVersion {\n\t\t\treturn ipConfig, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"failed to find a IPconfiguration(IPv6=%v) for the scale set VM %q\", IPv6, nodeName)\n}","line":{"from":947,"to":964}} {"id":100033361,"name":"EnsureHostInPool","signature":"func (ss *scaleSet) EnsureHostInPool(service *v1.Service, nodeName types.NodeName, backendPoolID string, vmSetName string, isInternal bool) (string, string, string, *compute.VirtualMachineScaleSetVM, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// EnsureHostInPool ensures the given VM's Primary NIC's Primary IP Configuration is\n// participating in the specified LoadBalancer Backend Pool, which returns (resourceGroup, vmssName, instanceID, vmssVM, error).\nfunc (ss *scaleSet) EnsureHostInPool(service *v1.Service, nodeName types.NodeName, backendPoolID string, vmSetName string, isInternal bool) (string, string, string, *compute.VirtualMachineScaleSetVM, error) {\n\tklog.V(3).Infof(\"ensuring node %q of scaleset %q in LB backendpool %q\", nodeName, vmSetName, backendPoolID)\n\tvmName := mapNodeNameToVMName(nodeName)\n\tssName, instanceID, vm, err := ss.getVmssVM(vmName, azcache.CacheReadTypeDefault)\n\tif err != nil {\n\t\tif errors.Is(err, cloudprovider.InstanceNotFound) {\n\t\t\tklog.Infof(\"EnsureHostInPool: skipping node %s because it is not found\", vmName)\n\t\t\treturn \"\", \"\", \"\", nil, nil\n\t\t}\n\n\t\treturn \"\", \"\", \"\", nil, err\n\t}\n\n\t// Check scale set name:\n\t// - For basic SKU load balancer, return nil if the node's scale set is mismatched with vmSetName.\n\t// - For single standard SKU load balancer, backend could belong to multiple VMSS, so we\n\t// don't check vmSet for it.\n\t// - For multiple standard SKU load balancers, the behavior is similar to the basic load balancer\n\tneedCheck := false\n\tif !ss.useStandardLoadBalancer() {\n\t\t// need to check the vmSet name when using the basic LB\n\t\tneedCheck = true\n\t} else if ss.EnableMultipleStandardLoadBalancers {\n\t\t// need to check the vmSet name when using multiple standard LBs\n\t\tneedCheck = true\n\t}\n\tif vmSetName != \"\" \u0026\u0026 needCheck \u0026\u0026 !strings.EqualFold(vmSetName, ssName) {\n\t\tklog.V(3).Infof(\"EnsureHostInPool skips node %s because it is not in the scaleSet %s\", vmName, vmSetName)\n\t\treturn \"\", \"\", \"\", nil, nil\n\t}\n\n\t// Find primary network interface configuration.\n\tif vm.NetworkProfileConfiguration.NetworkInterfaceConfigurations == nil {\n\t\tklog.V(4).Infof(\"EnsureHostInPool: cannot obtain the primary network interface configuration, of vm %s, probably because the vm's being deleted\", vmName)\n\t\treturn \"\", \"\", \"\", nil, nil\n\t}\n\n\tnetworkInterfaceConfigurations := *vm.NetworkProfileConfiguration.NetworkInterfaceConfigurations\n\tprimaryNetworkInterfaceConfiguration, err := ss.getPrimaryNetworkInterfaceConfiguration(networkInterfaceConfigurations, vmName)\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", nil, err\n\t}\n\n\tvar primaryIPConfiguration *compute.VirtualMachineScaleSetIPConfiguration\n\tipv6 := utilnet.IsIPv6String(service.Spec.ClusterIP)\n\t// Find primary network interface configuration.\n\tif !ss.Cloud.ipv6DualStackEnabled \u0026\u0026 !ipv6 {\n\t\t// Find primary IP configuration.\n\t\tprimaryIPConfiguration, err = getPrimaryIPConfigFromVMSSNetworkConfig(primaryNetworkInterfaceConfiguration)\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", \"\", nil, err\n\t\t}\n\t} else {\n\t\t// For IPv6 or dualstack service, we need to pick the right IP configuration based on the cluster ip family\n\t\t// IPv6 configuration is only supported as non-primary, so we need to fetch the ip configuration where the\n\t\t// privateIPAddressVersion matches the clusterIP family\n\t\tprimaryIPConfiguration, err = ss.getConfigForScaleSetByIPFamily(primaryNetworkInterfaceConfiguration, vmName, ipv6)\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", \"\", nil, err\n\t\t}\n\t}\n\n\t// Update primary IP configuration's LoadBalancerBackendAddressPools.\n\tfoundPool := false\n\tnewBackendPools := []compute.SubResource{}\n\tif primaryIPConfiguration.LoadBalancerBackendAddressPools != nil {\n\t\tnewBackendPools = *primaryIPConfiguration.LoadBalancerBackendAddressPools\n\t}\n\tfor _, existingPool := range newBackendPools {\n\t\tif strings.EqualFold(backendPoolID, *existingPool.ID) {\n\t\t\tfoundPool = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// The backendPoolID has already been found from existing LoadBalancerBackendAddressPools.\n\tif foundPool {\n\t\treturn \"\", \"\", \"\", nil, nil\n\t}\n\n\tif ss.useStandardLoadBalancer() \u0026\u0026 len(newBackendPools) \u003e 0 {\n\t\t// Although standard load balancer supports backends from multiple scale\n\t\t// sets, the same network interface couldn't be added to more than one load balancer of\n\t\t// the same type. Omit those nodes (e.g. masters) so Azure ARM won't complain\n\t\t// about this.\n\t\tnewBackendPoolsIDs := make([]string, 0, len(newBackendPools))\n\t\tfor _, pool := range newBackendPools {\n\t\t\tif pool.ID != nil {\n\t\t\t\tnewBackendPoolsIDs = append(newBackendPoolsIDs, *pool.ID)\n\t\t\t}\n\t\t}\n\t\tisSameLB, oldLBName, err := isBackendPoolOnSameLB(backendPoolID, newBackendPoolsIDs)\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", \"\", nil, err\n\t\t}\n\t\tif !isSameLB {\n\t\t\tklog.V(4).Infof(\"Node %q has already been added to LB %q, omit adding it to a new one\", nodeName, oldLBName)\n\t\t\treturn \"\", \"\", \"\", nil, nil\n\t\t}\n\t}\n\n\t// Compose a new vmssVM with added backendPoolID.\n\tnewBackendPools = append(newBackendPools,\n\t\tcompute.SubResource{\n\t\t\tID: pointer.String(backendPoolID),\n\t\t})\n\tprimaryIPConfiguration.LoadBalancerBackendAddressPools = \u0026newBackendPools\n\tnewVM := \u0026compute.VirtualMachineScaleSetVM{\n\t\tLocation: vm.Location,\n\t\tVirtualMachineScaleSetVMProperties: \u0026compute.VirtualMachineScaleSetVMProperties{\n\t\t\tHardwareProfile: vm.HardwareProfile,\n\t\t\tNetworkProfileConfiguration: \u0026compute.VirtualMachineScaleSetVMNetworkProfileConfiguration{\n\t\t\t\tNetworkInterfaceConfigurations: \u0026networkInterfaceConfigurations,\n\t\t\t},\n\t\t},\n\t}\n\n\t// Get the node resource group.\n\tnodeResourceGroup, err := ss.GetNodeResourceGroup(vmName)\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", nil, err\n\t}\n\n\treturn nodeResourceGroup, ssName, instanceID, newVM, nil\n}","line":{"from":966,"to":1092}} {"id":100033362,"name":"getVmssAndResourceGroupNameByVMProviderID","signature":"func getVmssAndResourceGroupNameByVMProviderID(providerID string) (string, string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"func getVmssAndResourceGroupNameByVMProviderID(providerID string) (string, string, error) {\n\tmatches := vmssVMProviderIDRE.FindStringSubmatch(providerID)\n\tif len(matches) != 3 {\n\t\treturn \"\", \"\", ErrorNotVmssInstance\n\t}\n\treturn matches[1], matches[2], nil\n}","line":{"from":1094,"to":1100}} {"id":100033363,"name":"ensureVMSSInPool","signature":"func (ss *scaleSet) ensureVMSSInPool(service *v1.Service, nodes []*v1.Node, backendPoolID string, vmSetName string) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"func (ss *scaleSet) ensureVMSSInPool(service *v1.Service, nodes []*v1.Node, backendPoolID string, vmSetName string) error {\n\tklog.V(2).Infof(\"ensureVMSSInPool: ensuring VMSS with backendPoolID %s\", backendPoolID)\n\tvmssNamesMap := make(map[string]bool)\n\n\t// the single standard load balancer supports multiple vmss in its backend while\n\t// multiple standard load balancers and the basic load balancer doesn't\n\tif ss.useStandardLoadBalancer() \u0026\u0026 !ss.EnableMultipleStandardLoadBalancers {\n\t\tfor _, node := range nodes {\n\t\t\tif ss.excludeMasterNodesFromStandardLB() \u0026\u0026 isMasterNode(node) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tshouldExcludeLoadBalancer, err := ss.ShouldNodeExcludedFromLoadBalancer(node.Name)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"ShouldNodeExcludedFromLoadBalancer(%s) failed with error: %v\", node.Name, err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif shouldExcludeLoadBalancer {\n\t\t\t\tklog.V(4).Infof(\"Excluding unmanaged/external-resource-group node %q\", node.Name)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// in this scenario the vmSetName is an empty string and the name of vmss should be obtained from the provider IDs of nodes\n\t\t\tresourceGroupName, vmssName, err := getVmssAndResourceGroupNameByVMProviderID(node.Spec.ProviderID)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"ensureVMSSInPool: found VMAS node %s, will skip checking and continue\", node.Name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// only vmsses in the resource group same as it's in azure config are included\n\t\t\tif strings.EqualFold(resourceGroupName, ss.ResourceGroup) {\n\t\t\t\tvmssNamesMap[vmssName] = true\n\t\t\t}\n\t\t}\n\t} else {\n\t\tvmssNamesMap[vmSetName] = true\n\t}\n\n\tklog.V(2).Infof(\"ensureVMSSInPool begins to update VMSS %v with backendPoolID %s\", vmssNamesMap, backendPoolID)\n\tfor vmssName := range vmssNamesMap {\n\t\tvmss, err := ss.getVMSS(vmssName, azcache.CacheReadTypeDefault)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// When vmss is being deleted, CreateOrUpdate API would report \"the vmss is being deleted\" error.\n\t\t// Since it is being deleted, we shouldn't send more CreateOrUpdate requests for it.\n\t\tif vmss.ProvisioningState != nil \u0026\u0026 strings.EqualFold(*vmss.ProvisioningState, virtualMachineScaleSetsDeallocating) {\n\t\t\tklog.V(3).Infof(\"ensureVMSSInPool: found vmss %s being deleted, skipping\", vmssName)\n\t\t\tcontinue\n\t\t}\n\n\t\tif vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations == nil {\n\t\t\tklog.V(4).Infof(\"EnsureHostInPool: cannot obtain the primary network interface configuration of vmss %s\", vmssName)\n\t\t\tcontinue\n\t\t}\n\t\tvmssNIC := *vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations\n\t\tprimaryNIC, err := ss.getPrimaryNetworkInterfaceConfigurationForScaleSet(vmssNIC, vmssName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar primaryIPConfig *compute.VirtualMachineScaleSetIPConfiguration\n\t\tipv6 := utilnet.IsIPv6String(service.Spec.ClusterIP)\n\t\t// Find primary network interface configuration.\n\t\tif !ss.Cloud.ipv6DualStackEnabled \u0026\u0026 !ipv6 {\n\t\t\t// Find primary IP configuration.\n\t\t\tprimaryIPConfig, err = getPrimaryIPConfigFromVMSSNetworkConfig(primaryNIC)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tprimaryIPConfig, err = ss.getConfigForScaleSetByIPFamily(primaryNIC, \"\", ipv6)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tloadBalancerBackendAddressPools := []compute.SubResource{}\n\t\tif primaryIPConfig.LoadBalancerBackendAddressPools != nil {\n\t\t\tloadBalancerBackendAddressPools = *primaryIPConfig.LoadBalancerBackendAddressPools\n\t\t}\n\n\t\tvar found bool\n\t\tfor _, loadBalancerBackendAddressPool := range loadBalancerBackendAddressPools {\n\t\t\tif strings.EqualFold(*loadBalancerBackendAddressPool.ID, backendPoolID) {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif found {\n\t\t\tcontinue\n\t\t}\n\n\t\tif ss.useStandardLoadBalancer() \u0026\u0026 len(loadBalancerBackendAddressPools) \u003e 0 {\n\t\t\t// Although standard load balancer supports backends from multiple scale\n\t\t\t// sets, the same network interface couldn't be added to more than one load balancer of\n\t\t\t// the same type. Omit those nodes (e.g. masters) so Azure ARM won't complain\n\t\t\t// about this.\n\t\t\tnewBackendPoolsIDs := make([]string, 0, len(loadBalancerBackendAddressPools))\n\t\t\tfor _, pool := range loadBalancerBackendAddressPools {\n\t\t\t\tif pool.ID != nil {\n\t\t\t\t\tnewBackendPoolsIDs = append(newBackendPoolsIDs, *pool.ID)\n\t\t\t\t}\n\t\t\t}\n\t\t\tisSameLB, oldLBName, err := isBackendPoolOnSameLB(backendPoolID, newBackendPoolsIDs)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !isSameLB {\n\t\t\t\tklog.V(4).Infof(\"VMSS %q has already been added to LB %q, omit adding it to a new one\", vmssName, oldLBName)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\t// Compose a new vmss with added backendPoolID.\n\t\tloadBalancerBackendAddressPools = append(loadBalancerBackendAddressPools,\n\t\t\tcompute.SubResource{\n\t\t\t\tID: pointer.String(backendPoolID),\n\t\t\t})\n\t\tprimaryIPConfig.LoadBalancerBackendAddressPools = \u0026loadBalancerBackendAddressPools\n\t\tnewVMSS := compute.VirtualMachineScaleSet{\n\t\t\tLocation: vmss.Location,\n\t\t\tVirtualMachineScaleSetProperties: \u0026compute.VirtualMachineScaleSetProperties{\n\t\t\t\tVirtualMachineProfile: \u0026compute.VirtualMachineScaleSetVMProfile{\n\t\t\t\t\tNetworkProfile: \u0026compute.VirtualMachineScaleSetNetworkProfile{\n\t\t\t\t\t\tNetworkInterfaceConfigurations: \u0026vmssNIC,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\n\t\tklog.V(2).Infof(\"ensureVMSSInPool begins to update vmss(%s) with new backendPoolID %s\", vmssName, backendPoolID)\n\t\trerr := ss.CreateOrUpdateVMSS(ss.ResourceGroup, vmssName, newVMSS)\n\t\tif rerr != nil {\n\t\t\tklog.Errorf(\"ensureVMSSInPool CreateOrUpdateVMSS(%s) with new backendPoolID %s, err: %v\", vmssName, backendPoolID, err)\n\t\t\treturn rerr.Error()\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":1102,"to":1240}} {"id":100033364,"name":"EnsureHostsInPool","signature":"func (ss *scaleSet) EnsureHostsInPool(service *v1.Service, nodes []*v1.Node, backendPoolID string, vmSetName string, isInternal bool) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// EnsureHostsInPool ensures the given Node's primary IP configurations are\n// participating in the specified LoadBalancer Backend Pool.\nfunc (ss *scaleSet) EnsureHostsInPool(service *v1.Service, nodes []*v1.Node, backendPoolID string, vmSetName string, isInternal bool) error {\n\tmc := metrics.NewMetricContext(\"services\", \"vmss_ensure_hosts_in_pool\", ss.ResourceGroup, ss.SubscriptionID, service.Name)\n\tisOperationSucceeded := false\n\tdefer func() {\n\t\tmc.ObserveOperationWithResult(isOperationSucceeded)\n\t}()\n\n\thostUpdates := make([]func() error, 0, len(nodes))\n\tnodeUpdates := make(map[vmssMetaInfo]map[string]compute.VirtualMachineScaleSetVM)\n\terrors := make([]error, 0)\n\tfor _, node := range nodes {\n\t\tlocalNodeName := node.Name\n\n\t\tif ss.useStandardLoadBalancer() \u0026\u0026 ss.excludeMasterNodesFromStandardLB() \u0026\u0026 isMasterNode(node) {\n\t\t\tklog.V(4).Infof(\"Excluding master node %q from load balancer backendpool %q\", localNodeName, backendPoolID)\n\t\t\tcontinue\n\t\t}\n\n\t\tshouldExcludeLoadBalancer, err := ss.ShouldNodeExcludedFromLoadBalancer(localNodeName)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"ShouldNodeExcludedFromLoadBalancer(%s) failed with error: %v\", localNodeName, err)\n\t\t\treturn err\n\t\t}\n\t\tif shouldExcludeLoadBalancer {\n\t\t\tklog.V(4).Infof(\"Excluding unmanaged/external-resource-group node %q\", localNodeName)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Check whether the node is VMAS virtual machine.\n\t\tmanagedByAS, err := ss.isNodeManagedByAvailabilitySet(localNodeName, azcache.CacheReadTypeDefault)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to check isNodeManagedByAvailabilitySet(%s): %v\", localNodeName, err)\n\t\t\terrors = append(errors, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif managedByAS {\n\t\t\t// VMAS nodes should also be added to the SLB backends.\n\t\t\tif ss.useStandardLoadBalancer() {\n\t\t\t\thostUpdates = append(hostUpdates, func() error {\n\t\t\t\t\t_, _, _, _, err := ss.availabilitySet.EnsureHostInPool(service, types.NodeName(localNodeName), backendPoolID, vmSetName, isInternal)\n\t\t\t\t\treturn err\n\t\t\t\t})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tklog.V(3).Infof(\"EnsureHostsInPool skips node %s because VMAS nodes couldn't be added to basic LB with VMSS backends\", localNodeName)\n\t\t\tcontinue\n\t\t}\n\n\t\tnodeResourceGroup, nodeVMSS, nodeInstanceID, nodeVMSSVM, err := ss.EnsureHostInPool(service, types.NodeName(localNodeName), backendPoolID, vmSetName, isInternal)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"EnsureHostInPool(%s): backendPoolID(%s) - failed to ensure host in pool: %q\", getServiceName(service), backendPoolID, err)\n\t\t\terrors = append(errors, err)\n\t\t\tcontinue\n\t\t}\n\n\t\t// No need to update if nodeVMSSVM is nil.\n\t\tif nodeVMSSVM == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tnodeVMSSMetaInfo := vmssMetaInfo{vmssName: nodeVMSS, resourceGroup: nodeResourceGroup}\n\t\tif v, ok := nodeUpdates[nodeVMSSMetaInfo]; ok {\n\t\t\tv[nodeInstanceID] = *nodeVMSSVM\n\t\t} else {\n\t\t\tnodeUpdates[nodeVMSSMetaInfo] = map[string]compute.VirtualMachineScaleSetVM{\n\t\t\t\tnodeInstanceID: *nodeVMSSVM,\n\t\t\t}\n\t\t}\n\n\t\t// Invalidate the cache since the VMSS VM would be updated.\n\t\tdefer ss.deleteCacheForNode(localNodeName)\n\t}\n\n\t// Update VMs with best effort that have already been added to nodeUpdates.\n\tfor meta, update := range nodeUpdates {\n\t\t// create new instance of meta and update for passing to anonymous function\n\t\tmeta := meta\n\t\tupdate := update\n\t\thostUpdates = append(hostUpdates, func() error {\n\t\t\tctx, cancel := getContextWithCancel()\n\t\t\tdefer cancel()\n\t\t\tklog.V(2).Infof(\"EnsureHostInPool begins to UpdateVMs for VMSS(%s, %s) with new backendPoolID %s\", meta.resourceGroup, meta.vmssName, backendPoolID)\n\t\t\trerr := ss.VirtualMachineScaleSetVMsClient.UpdateVMs(ctx, meta.resourceGroup, meta.vmssName, update, \"network_update\")\n\t\t\tif rerr != nil {\n\t\t\t\tklog.Errorf(\"EnsureHostInPool UpdateVMs for VMSS(%s, %s) failed with error %v\", meta.resourceGroup, meta.vmssName, rerr.Error())\n\t\t\t\treturn rerr.Error()\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t}\n\terrs := utilerrors.AggregateGoroutines(hostUpdates...)\n\tif errs != nil {\n\t\treturn utilerrors.Flatten(errs)\n\t}\n\n\t// Fail if there are other errors.\n\tif len(errors) \u003e 0 {\n\t\treturn utilerrors.Flatten(utilerrors.NewAggregate(errors))\n\t}\n\n\t// Ensure the backendPoolID is also added on VMSS itself.\n\t// Refer to issue kubernetes/kubernetes#80365 for detailed information\n\terr := ss.ensureVMSSInPool(service, nodes, backendPoolID, vmSetName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tisOperationSucceeded = true\n\treturn nil\n}","line":{"from":1242,"to":1356}} {"id":100033365,"name":"ensureBackendPoolDeletedFromNode","signature":"func (ss *scaleSet) ensureBackendPoolDeletedFromNode(nodeName, backendPoolID string) (string, string, string, *compute.VirtualMachineScaleSetVM, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// ensureBackendPoolDeletedFromNode ensures the loadBalancer backendAddressPools deleted\n// from the specified node, which returns (resourceGroup, vmssName, instanceID, vmssVM, error).\nfunc (ss *scaleSet) ensureBackendPoolDeletedFromNode(nodeName, backendPoolID string) (string, string, string, *compute.VirtualMachineScaleSetVM, error) {\n\tssName, instanceID, vm, err := ss.getVmssVM(nodeName, azcache.CacheReadTypeDefault)\n\tif err != nil {\n\t\tif errors.Is(err, cloudprovider.InstanceNotFound) {\n\t\t\tklog.Infof(\"ensureBackendPoolDeletedFromNode: skipping node %s because it is not found\", nodeName)\n\t\t\treturn \"\", \"\", \"\", nil, nil\n\t\t}\n\n\t\treturn \"\", \"\", \"\", nil, err\n\t}\n\n\t// Find primary network interface configuration.\n\tif vm.NetworkProfileConfiguration.NetworkInterfaceConfigurations == nil {\n\t\tklog.V(4).Infof(\"EnsureHostInPool: cannot obtain the primary network interface configuration, of vm %s, probably because the vm's being deleted\", nodeName)\n\t\treturn \"\", \"\", \"\", nil, nil\n\t}\n\tnetworkInterfaceConfigurations := *vm.NetworkProfileConfiguration.NetworkInterfaceConfigurations\n\tprimaryNetworkInterfaceConfiguration, err := ss.getPrimaryNetworkInterfaceConfiguration(networkInterfaceConfigurations, nodeName)\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", nil, err\n\t}\n\n\t// Find primary IP configuration.\n\tprimaryIPConfiguration, err := getPrimaryIPConfigFromVMSSNetworkConfig(primaryNetworkInterfaceConfiguration)\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", nil, err\n\t}\n\tif primaryIPConfiguration.LoadBalancerBackendAddressPools == nil || len(*primaryIPConfiguration.LoadBalancerBackendAddressPools) == 0 {\n\t\treturn \"\", \"\", \"\", nil, nil\n\t}\n\n\t// Construct new loadBalancerBackendAddressPools and remove backendAddressPools from primary IP configuration.\n\texistingBackendPools := *primaryIPConfiguration.LoadBalancerBackendAddressPools\n\tnewBackendPools := []compute.SubResource{}\n\tfoundPool := false\n\tfor i := len(existingBackendPools) - 1; i \u003e= 0; i-- {\n\t\tcurPool := existingBackendPools[i]\n\t\tif strings.EqualFold(backendPoolID, *curPool.ID) {\n\t\t\tklog.V(10).Infof(\"ensureBackendPoolDeletedFromNode gets unwanted backend pool %q for node %s\", backendPoolID, nodeName)\n\t\t\tfoundPool = true\n\t\t\tnewBackendPools = append(existingBackendPools[:i], existingBackendPools[i+1:]...)\n\t\t}\n\t}\n\n\t// Pool not found, assume it has been already removed.\n\tif !foundPool {\n\t\treturn \"\", \"\", \"\", nil, nil\n\t}\n\n\t// Compose a new vmssVM with added backendPoolID.\n\tprimaryIPConfiguration.LoadBalancerBackendAddressPools = \u0026newBackendPools\n\tnewVM := \u0026compute.VirtualMachineScaleSetVM{\n\t\tLocation: vm.Location,\n\t\tVirtualMachineScaleSetVMProperties: \u0026compute.VirtualMachineScaleSetVMProperties{\n\t\t\tHardwareProfile: vm.HardwareProfile,\n\t\t\tNetworkProfileConfiguration: \u0026compute.VirtualMachineScaleSetVMNetworkProfileConfiguration{\n\t\t\t\tNetworkInterfaceConfigurations: \u0026networkInterfaceConfigurations,\n\t\t\t},\n\t\t},\n\t}\n\n\t// Get the node resource group.\n\tnodeResourceGroup, err := ss.GetNodeResourceGroup(nodeName)\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", nil, err\n\t}\n\n\treturn nodeResourceGroup, ssName, instanceID, newVM, nil\n}","line":{"from":1358,"to":1428}} {"id":100033366,"name":"GetNodeNameByIPConfigurationID","signature":"func (ss *scaleSet) GetNodeNameByIPConfigurationID(ipConfigurationID string) (string, string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// GetNodeNameByIPConfigurationID gets the node name and the VMSS name by IP configuration ID.\nfunc (ss *scaleSet) GetNodeNameByIPConfigurationID(ipConfigurationID string) (string, string, error) {\n\tmatches := vmssIPConfigurationRE.FindStringSubmatch(ipConfigurationID)\n\tif len(matches) != 4 {\n\t\tif ss.DisableAvailabilitySetNodes {\n\t\t\treturn \"\", \"\", ErrorNotVmssInstance\n\t\t}\n\n\t\tklog.V(4).Infof(\"Can not extract scale set name from ipConfigurationID (%s), assuming it is managed by availability set\", ipConfigurationID)\n\t\tname, rg, err := ss.availabilitySet.GetNodeNameByIPConfigurationID(ipConfigurationID)\n\t\tif err != nil \u0026\u0026 !errors.Is(err, cloudprovider.InstanceNotFound) {\n\t\t\tklog.Errorf(\"GetNodeNameByIPConfigurationID: failed to invoke availabilitySet.GetNodeNameByIPConfigurationID: %s\", err.Error())\n\t\t\treturn \"\", \"\", err\n\t\t}\n\t\treturn name, rg, nil\n\t}\n\n\tresourceGroup := matches[1]\n\tscaleSetName := matches[2]\n\tinstanceID := matches[3]\n\tvm, err := ss.getVmssVMByInstanceID(resourceGroup, scaleSetName, instanceID, azcache.CacheReadTypeUnsafe)\n\tif err != nil {\n\t\tklog.Errorf(\"Unable to find node by ipConfigurationID %s: %v\", ipConfigurationID, err)\n\t\treturn \"\", \"\", err\n\t}\n\n\tif vm.OsProfile != nil \u0026\u0026 vm.OsProfile.ComputerName != nil {\n\t\treturn strings.ToLower(*vm.OsProfile.ComputerName), scaleSetName, nil\n\t}\n\n\treturn \"\", \"\", nil\n}","line":{"from":1430,"to":1461}} {"id":100033367,"name":"getScaleSetAndResourceGroupNameByIPConfigurationID","signature":"func getScaleSetAndResourceGroupNameByIPConfigurationID(ipConfigurationID string) (string, string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"func getScaleSetAndResourceGroupNameByIPConfigurationID(ipConfigurationID string) (string, string, error) {\n\tmatches := vmssIPConfigurationRE.FindStringSubmatch(ipConfigurationID)\n\tif len(matches) != 4 {\n\t\tklog.V(4).Infof(\"Can not extract scale set name from ipConfigurationID (%s), assuming it is managed by availability set\", ipConfigurationID)\n\t\treturn \"\", \"\", ErrorNotVmssInstance\n\t}\n\n\tresourceGroup := matches[1]\n\tscaleSetName := matches[2]\n\treturn scaleSetName, resourceGroup, nil\n}","line":{"from":1463,"to":1473}} {"id":100033368,"name":"ensureBackendPoolDeletedFromVMSS","signature":"func (ss *scaleSet) ensureBackendPoolDeletedFromVMSS(service *v1.Service, backendPoolID, vmSetName string, ipConfigurationIDs []string) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"func (ss *scaleSet) ensureBackendPoolDeletedFromVMSS(service *v1.Service, backendPoolID, vmSetName string, ipConfigurationIDs []string) error {\n\tvmssNamesMap := make(map[string]bool)\n\n\t// the standard load balancer supports multiple vmss in its backend while the basic sku doesn't\n\tif ss.useStandardLoadBalancer() {\n\t\tfor _, ipConfigurationID := range ipConfigurationIDs {\n\t\t\t// in this scenario the vmSetName is an empty string and the name of vmss should be obtained from the provider IDs of nodes\n\t\t\tvmssName, resourceGroupName, err := getScaleSetAndResourceGroupNameByIPConfigurationID(ipConfigurationID)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"ensureBackendPoolDeletedFromVMSS: found VMAS ipcConfigurationID %s, will skip checking and continue\", ipConfigurationID)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// only vmsses in the resource group same as it's in azure config are included\n\t\t\tif strings.EqualFold(resourceGroupName, ss.ResourceGroup) {\n\t\t\t\tvmssNamesMap[vmssName] = true\n\t\t\t}\n\t\t}\n\t} else {\n\t\tvmssNamesMap[vmSetName] = true\n\t}\n\n\tvmssUpdaters := make([]func() error, 0, len(vmssNamesMap))\n\terrors := make([]error, 0, len(vmssNamesMap))\n\tfor vmssName := range vmssNamesMap {\n\t\tvmssName := vmssName\n\t\tvmss, err := ss.getVMSS(vmssName, azcache.CacheReadTypeDefault)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"ensureBackendPoolDeletedFromVMSS: failed to get VMSS %s: %v\", vmssName, err)\n\t\t\terrors = append(errors, err)\n\t\t\tcontinue\n\t\t}\n\n\t\t// When vmss is being deleted, CreateOrUpdate API would report \"the vmss is being deleted\" error.\n\t\t// Since it is being deleted, we shouldn't send more CreateOrUpdate requests for it.\n\t\tif vmss.ProvisioningState != nil \u0026\u0026 strings.EqualFold(*vmss.ProvisioningState, virtualMachineScaleSetsDeallocating) {\n\t\t\tklog.V(3).Infof(\"ensureBackendPoolDeletedFromVMSS: found vmss %s being deleted, skipping\", vmssName)\n\t\t\tcontinue\n\t\t}\n\t\tif vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations == nil {\n\t\t\tklog.V(4).Infof(\"ensureBackendPoolDeletedFromVMSS: cannot obtain the primary network interface configuration, of vmss %s\", vmssName)\n\t\t\tcontinue\n\t\t}\n\t\tvmssNIC := *vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations\n\t\tprimaryNIC, err := ss.getPrimaryNetworkInterfaceConfigurationForScaleSet(vmssNIC, vmssName)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"ensureBackendPoolDeletedFromVMSS: failed to get the primary network interface config of the VMSS %s: %v\", vmssName, err)\n\t\t\terrors = append(errors, err)\n\t\t\tcontinue\n\t\t}\n\t\tprimaryIPConfig, err := getPrimaryIPConfigFromVMSSNetworkConfig(primaryNIC)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"ensureBackendPoolDeletedFromVMSS: failed to the primary IP config from the VMSS %s's network config : %v\", vmssName, err)\n\t\t\terrors = append(errors, err)\n\t\t\tcontinue\n\t\t}\n\t\tloadBalancerBackendAddressPools := []compute.SubResource{}\n\t\tif primaryIPConfig.LoadBalancerBackendAddressPools != nil {\n\t\t\tloadBalancerBackendAddressPools = *primaryIPConfig.LoadBalancerBackendAddressPools\n\t\t}\n\n\t\tvar found bool\n\t\tvar newBackendPools []compute.SubResource\n\t\tfor i := len(loadBalancerBackendAddressPools) - 1; i \u003e= 0; i-- {\n\t\t\tcurPool := loadBalancerBackendAddressPools[i]\n\t\t\tif strings.EqualFold(backendPoolID, *curPool.ID) {\n\t\t\t\tklog.V(10).Infof(\"ensureBackendPoolDeletedFromVMSS gets unwanted backend pool %q for VMSS %s\", backendPoolID, vmssName)\n\t\t\t\tfound = true\n\t\t\t\tnewBackendPools = append(loadBalancerBackendAddressPools[:i], loadBalancerBackendAddressPools[i+1:]...)\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tcontinue\n\t\t}\n\n\t\tvmssUpdaters = append(vmssUpdaters, func() error {\n\t\t\t// Compose a new vmss with added backendPoolID.\n\t\t\tprimaryIPConfig.LoadBalancerBackendAddressPools = \u0026newBackendPools\n\t\t\tnewVMSS := compute.VirtualMachineScaleSet{\n\t\t\t\tLocation: vmss.Location,\n\t\t\t\tVirtualMachineScaleSetProperties: \u0026compute.VirtualMachineScaleSetProperties{\n\t\t\t\t\tVirtualMachineProfile: \u0026compute.VirtualMachineScaleSetVMProfile{\n\t\t\t\t\t\tNetworkProfile: \u0026compute.VirtualMachineScaleSetNetworkProfile{\n\t\t\t\t\t\t\tNetworkInterfaceConfigurations: \u0026vmssNIC,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tklog.V(2).Infof(\"ensureBackendPoolDeletedFromVMSS begins to update vmss(%s) with backendPoolID %s\", vmssName, backendPoolID)\n\t\t\trerr := ss.CreateOrUpdateVMSS(ss.ResourceGroup, vmssName, newVMSS)\n\t\t\tif rerr != nil {\n\t\t\t\tklog.Errorf(\"ensureBackendPoolDeletedFromVMSS CreateOrUpdateVMSS(%s) with new backendPoolID %s, err: %v\", vmssName, backendPoolID, rerr)\n\t\t\t\treturn rerr.Error()\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t}\n\n\terrs := utilerrors.AggregateGoroutines(vmssUpdaters...)\n\tif errs != nil {\n\t\treturn utilerrors.Flatten(errs)\n\t}\n\t// Fail if there are other errors.\n\tif len(errors) \u003e 0 {\n\t\treturn utilerrors.Flatten(utilerrors.NewAggregate(errors))\n\t}\n\n\treturn nil\n}","line":{"from":1475,"to":1584}} {"id":100033369,"name":"EnsureBackendPoolDeleted","signature":"func (ss *scaleSet) EnsureBackendPoolDeleted(service *v1.Service, backendPoolID, vmSetName string, backendAddressPools *[]network.BackendAddressPool, deleteFromVMSet bool) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss.go","code":"// EnsureBackendPoolDeleted ensures the loadBalancer backendAddressPools deleted from the specified nodes.\nfunc (ss *scaleSet) EnsureBackendPoolDeleted(service *v1.Service, backendPoolID, vmSetName string, backendAddressPools *[]network.BackendAddressPool, deleteFromVMSet bool) error {\n\t// Returns nil if backend address pools already deleted.\n\tif backendAddressPools == nil {\n\t\treturn nil\n\t}\n\n\tmc := metrics.NewMetricContext(\"services\", \"vmss_ensure_backend_pool_deleted\", ss.ResourceGroup, ss.SubscriptionID, service.Name)\n\tisOperationSucceeded := false\n\tdefer func() {\n\t\tmc.ObserveOperationWithResult(isOperationSucceeded)\n\t}()\n\n\tipConfigurationIDs := []string{}\n\tfor _, backendPool := range *backendAddressPools {\n\t\tif strings.EqualFold(*backendPool.ID, backendPoolID) \u0026\u0026 backendPool.BackendIPConfigurations != nil {\n\t\t\tfor _, ipConf := range *backendPool.BackendIPConfigurations {\n\t\t\t\tif ipConf.ID == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tipConfigurationIDs = append(ipConfigurationIDs, *ipConf.ID)\n\t\t\t}\n\t\t}\n\t}\n\n\thostUpdates := make([]func() error, 0, len(ipConfigurationIDs))\n\tnodeUpdates := make(map[vmssMetaInfo]map[string]compute.VirtualMachineScaleSetVM)\n\tallErrs := make([]error, 0)\n\tfor i := range ipConfigurationIDs {\n\t\tipConfigurationID := ipConfigurationIDs[i]\n\n\t\tvar scaleSetName string\n\t\tvar err error\n\t\tif scaleSetName, err = extractScaleSetNameByProviderID(ipConfigurationID); err == nil {\n\t\t\t// Only remove nodes belonging to specified vmSet to basic LB backends.\n\t\t\tif !ss.useStandardLoadBalancer() \u0026\u0026 !strings.EqualFold(scaleSetName, vmSetName) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tnodeName, _, err := ss.GetNodeNameByIPConfigurationID(ipConfigurationID)\n\t\tif err != nil {\n\t\t\tif err == ErrorNotVmssInstance { // Do nothing for the VMAS nodes.\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif errors.Is(err, cloudprovider.InstanceNotFound) {\n\t\t\t\tklog.Infof(\"EnsureBackendPoolDeleted(%s): skipping ip config %s because the corresponding vmss vm is not found\", getServiceName(service), ipConfigurationID)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tklog.Errorf(\"Failed to GetNodeNameByIPConfigurationID(%s): %v\", ipConfigurationID, err)\n\t\t\tallErrs = append(allErrs, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tnodeResourceGroup, nodeVMSS, nodeInstanceID, nodeVMSSVM, err := ss.ensureBackendPoolDeletedFromNode(nodeName, backendPoolID)\n\t\tif err != nil {\n\t\t\tif !errors.Is(err, ErrorNotVmssInstance) { // Do nothing for the VMAS nodes.\n\t\t\t\tklog.Errorf(\"EnsureBackendPoolDeleted(%s): backendPoolID(%s) - failed with error %v\", getServiceName(service), backendPoolID, err)\n\t\t\t\tallErrs = append(allErrs, err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// No need to update if nodeVMSSVM is nil.\n\t\tif nodeVMSSVM == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tnodeVMSSMetaInfo := vmssMetaInfo{vmssName: nodeVMSS, resourceGroup: nodeResourceGroup}\n\t\tif v, ok := nodeUpdates[nodeVMSSMetaInfo]; ok {\n\t\t\tv[nodeInstanceID] = *nodeVMSSVM\n\t\t} else {\n\t\t\tnodeUpdates[nodeVMSSMetaInfo] = map[string]compute.VirtualMachineScaleSetVM{\n\t\t\t\tnodeInstanceID: *nodeVMSSVM,\n\t\t\t}\n\t\t}\n\n\t\t// Invalidate the cache since the VMSS VM would be updated.\n\t\tdefer ss.deleteCacheForNode(nodeName)\n\t}\n\n\t// Update VMs with best effort that have already been added to nodeUpdates.\n\tfor meta, update := range nodeUpdates {\n\t\t// create new instance of meta and update for passing to anonymous function\n\t\tmeta := meta\n\t\tupdate := update\n\t\thostUpdates = append(hostUpdates, func() error {\n\t\t\tctx, cancel := getContextWithCancel()\n\t\t\tdefer cancel()\n\t\t\tklog.V(2).Infof(\"EnsureBackendPoolDeleted begins to UpdateVMs for VMSS(%s, %s) with backendPoolID %s\", meta.resourceGroup, meta.vmssName, backendPoolID)\n\t\t\trerr := ss.VirtualMachineScaleSetVMsClient.UpdateVMs(ctx, meta.resourceGroup, meta.vmssName, update, \"network_update\")\n\t\t\tif rerr != nil {\n\t\t\t\tklog.Errorf(\"EnsureBackendPoolDeleted UpdateVMs for VMSS(%s, %s) failed with error %v\", meta.resourceGroup, meta.vmssName, rerr.Error())\n\t\t\t\treturn rerr.Error()\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t}\n\terrs := utilerrors.AggregateGoroutines(hostUpdates...)\n\tif errs != nil {\n\t\treturn utilerrors.Flatten(errs)\n\t}\n\n\t// Fail if there are other errors.\n\tif len(allErrs) \u003e 0 {\n\t\treturn utilerrors.Flatten(utilerrors.NewAggregate(allErrs))\n\t}\n\n\t// Ensure the backendPoolID is also deleted on VMSS itself.\n\tif deleteFromVMSet {\n\t\terr := ss.ensureBackendPoolDeletedFromVMSS(service, backendPoolID, vmSetName, ipConfigurationIDs)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tisOperationSucceeded = true\n\treturn nil\n}","line":{"from":1586,"to":1708}} {"id":100033370,"name":"newVMSSCache","signature":"func (ss *scaleSet) newVMSSCache() (*azcache.TimedCache, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss_cache.go","code":"func (ss *scaleSet) newVMSSCache() (*azcache.TimedCache, error) {\n\tgetter := func(key string) (interface{}, error) {\n\t\tlocalCache := \u0026sync.Map{} // [vmssName]*vmssEntry\n\n\t\tallResourceGroups, err := ss.GetResourceGroups()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, resourceGroup := range allResourceGroups.List() {\n\t\t\tallScaleSets, rerr := ss.VirtualMachineScaleSetsClient.List(context.Background(), resourceGroup)\n\t\t\tif rerr != nil {\n\t\t\t\tklog.Errorf(\"VirtualMachineScaleSetsClient.List failed: %v\", rerr)\n\t\t\t\treturn nil, rerr.Error()\n\t\t\t}\n\n\t\t\tfor i := range allScaleSets {\n\t\t\t\tscaleSet := allScaleSets[i]\n\t\t\t\tif scaleSet.Name == nil || *scaleSet.Name == \"\" {\n\t\t\t\t\tklog.Warning(\"failed to get the name of VMSS\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tlocalCache.Store(*scaleSet.Name, \u0026vmssEntry{\n\t\t\t\t\tvmss: \u0026scaleSet,\n\t\t\t\t\tresourceGroup: resourceGroup,\n\t\t\t\t\tlastUpdate: time.Now().UTC(),\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\treturn localCache, nil\n\t}\n\n\tif ss.Config.VmssCacheTTLInSeconds == 0 {\n\t\tss.Config.VmssCacheTTLInSeconds = vmssCacheTTLDefaultInSeconds\n\t}\n\treturn azcache.NewTimedcache(time.Duration(ss.Config.VmssCacheTTLInSeconds)*time.Second, getter)\n}","line":{"from":67,"to":104}} {"id":100033371,"name":"extractVmssVMName","signature":"func extractVmssVMName(name string) (string, string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss_cache.go","code":"func extractVmssVMName(name string) (string, string, error) {\n\tsplit := strings.SplitAfter(name, vmssNameSeparator)\n\tif len(split) \u003c 2 {\n\t\tklog.V(3).Infof(\"Failed to extract vmssVMName %q\", name)\n\t\treturn \"\", \"\", ErrorNotVmssInstance\n\t}\n\n\tssName := strings.Join(split[0:len(split)-1], \"\")\n\t// removing the trailing `vmssNameSeparator` since we used SplitAfter\n\tssName = ssName[:len(ssName)-1]\n\tinstanceID := split[len(split)-1]\n\treturn ssName, instanceID, nil\n}","line":{"from":106,"to":118}} {"id":100033372,"name":"getVMSSVMCache","signature":"func (ss *scaleSet) getVMSSVMCache(resourceGroup, vmssName string) (string, *azcache.TimedCache, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss_cache.go","code":"// getVMSSVMCache returns an *azcache.TimedCache and cache key for a VMSS (creating that cache if new).\nfunc (ss *scaleSet) getVMSSVMCache(resourceGroup, vmssName string) (string, *azcache.TimedCache, error) {\n\tcacheKey := strings.ToLower(fmt.Sprintf(\"%s/%s\", resourceGroup, vmssName))\n\tif entry, ok := ss.vmssVMCache.Load(cacheKey); ok {\n\t\tcache := entry.(*azcache.TimedCache)\n\t\treturn cacheKey, cache, nil\n\t}\n\n\tcache, err := ss.newVMSSVirtualMachinesCache(resourceGroup, vmssName, cacheKey)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\tss.vmssVMCache.Store(cacheKey, cache)\n\treturn cacheKey, cache, nil\n}","line":{"from":120,"to":134}} {"id":100033373,"name":"gcVMSSVMCache","signature":"func (ss *scaleSet) gcVMSSVMCache() error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss_cache.go","code":"// gcVMSSVMCache delete stale VMSS VMs caches from deleted VMSSes.\nfunc (ss *scaleSet) gcVMSSVMCache() error {\n\tcached, err := ss.vmssCache.Get(vmssKey, azcache.CacheReadTypeUnsafe)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvmsses := cached.(*sync.Map)\n\tremoved := map[string]bool{}\n\tss.vmssVMCache.Range(func(key, value interface{}) bool {\n\t\tcacheKey := key.(string)\n\t\tvlistIdx := cacheKey[strings.LastIndex(cacheKey, \"/\")+1:]\n\t\tif _, ok := vmsses.Load(vlistIdx); !ok {\n\t\t\tremoved[cacheKey] = true\n\t\t}\n\t\treturn true\n\t})\n\n\tfor key := range removed {\n\t\tss.vmssVMCache.Delete(key)\n\t}\n\n\treturn nil\n}","line":{"from":136,"to":159}} {"id":100033374,"name":"newVMSSVirtualMachinesCache","signature":"func (ss *scaleSet) newVMSSVirtualMachinesCache(resourceGroupName, vmssName, cacheKey string) (*azcache.TimedCache, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss_cache.go","code":"// newVMSSVirtualMachinesCache instantiates a new VMs cache for VMs belonging to the provided VMSS.\nfunc (ss *scaleSet) newVMSSVirtualMachinesCache(resourceGroupName, vmssName, cacheKey string) (*azcache.TimedCache, error) {\n\tvmssVirtualMachinesCacheTTL := time.Duration(ss.Config.VmssVirtualMachinesCacheTTLInSeconds) * time.Second\n\n\tgetter := func(key string) (interface{}, error) {\n\t\tlocalCache := \u0026sync.Map{} // [nodeName]*vmssVirtualMachinesEntry\n\n\t\toldCache := make(map[string]vmssVirtualMachinesEntry)\n\n\t\tif vmssCache, ok := ss.vmssVMCache.Load(cacheKey); ok {\n\t\t\t// get old cache before refreshing the cache\n\t\t\tcache := vmssCache.(*azcache.TimedCache)\n\t\t\tentry, exists, err := cache.Store.GetByKey(cacheKey)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif exists {\n\t\t\t\tcached := entry.(*azcache.AzureCacheEntry).Data\n\t\t\t\tif cached != nil {\n\t\t\t\t\tvirtualMachines := cached.(*sync.Map)\n\t\t\t\t\tvirtualMachines.Range(func(key, value interface{}) bool {\n\t\t\t\t\t\toldCache[key.(string)] = *value.(*vmssVirtualMachinesEntry)\n\t\t\t\t\t\treturn true\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvms, err := ss.listScaleSetVMs(vmssName, resourceGroupName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor i := range vms {\n\t\t\tvm := vms[i]\n\t\t\tif vm.OsProfile == nil || vm.OsProfile.ComputerName == nil {\n\t\t\t\tklog.Warningf(\"failed to get computerName for vmssVM (%q)\", vmssName)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcomputerName := strings.ToLower(*vm.OsProfile.ComputerName)\n\t\t\tif vm.NetworkProfile == nil || vm.NetworkProfile.NetworkInterfaces == nil {\n\t\t\t\tklog.Warningf(\"skip caching vmssVM %s since its network profile hasn't initialized yet (probably still under creating)\", computerName)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvmssVMCacheEntry := \u0026vmssVirtualMachinesEntry{\n\t\t\t\tresourceGroup: resourceGroupName,\n\t\t\t\tvmssName: vmssName,\n\t\t\t\tinstanceID: pointer.StringDeref(vm.InstanceID, \"\"),\n\t\t\t\tvirtualMachine: \u0026vm,\n\t\t\t\tlastUpdate: time.Now().UTC(),\n\t\t\t}\n\t\t\t// set cache entry to nil when the VM is under deleting.\n\t\t\tif vm.VirtualMachineScaleSetVMProperties != nil \u0026\u0026\n\t\t\t\tstrings.EqualFold(pointer.StringDeref(vm.VirtualMachineScaleSetVMProperties.ProvisioningState, \"\"), string(compute.ProvisioningStateDeleting)) {\n\t\t\t\tklog.V(4).Infof(\"VMSS virtualMachine %q is under deleting, setting its cache to nil\", computerName)\n\t\t\t\tvmssVMCacheEntry.virtualMachine = nil\n\t\t\t}\n\t\t\tlocalCache.Store(computerName, vmssVMCacheEntry)\n\n\t\t\tdelete(oldCache, computerName)\n\t\t}\n\n\t\t// add old missing cache data with nil entries to prevent aggressive\n\t\t// ARM calls during cache invalidation\n\t\tfor name, vmEntry := range oldCache {\n\t\t\t// if the nil cache entry has existed for vmssVirtualMachinesCacheTTL in the cache\n\t\t\t// then it should not be added back to the cache\n\t\t\tif vmEntry.virtualMachine == nil \u0026\u0026 time.Since(vmEntry.lastUpdate) \u003e vmssVirtualMachinesCacheTTL {\n\t\t\t\tklog.V(5).Infof(\"ignoring expired entries from old cache for %s\", name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlastUpdate := time.Now().UTC()\n\t\t\tif vmEntry.virtualMachine == nil {\n\t\t\t\t// if this is already a nil entry then keep the time the nil\n\t\t\t\t// entry was first created, so we can cleanup unwanted entries\n\t\t\t\tlastUpdate = vmEntry.lastUpdate\n\t\t\t}\n\n\t\t\tklog.V(5).Infof(\"adding old entries to new cache for %s\", name)\n\t\t\tlocalCache.Store(name, \u0026vmssVirtualMachinesEntry{\n\t\t\t\tresourceGroup: vmEntry.resourceGroup,\n\t\t\t\tvmssName: vmEntry.vmssName,\n\t\t\t\tinstanceID: vmEntry.instanceID,\n\t\t\t\tvirtualMachine: nil,\n\t\t\t\tlastUpdate: lastUpdate,\n\t\t\t})\n\t\t}\n\n\t\treturn localCache, nil\n\t}\n\n\treturn azcache.NewTimedcache(vmssVirtualMachinesCacheTTL, getter)\n}","line":{"from":161,"to":255}} {"id":100033375,"name":"deleteCacheForNode","signature":"func (ss *scaleSet) deleteCacheForNode(nodeName string) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss_cache.go","code":"func (ss *scaleSet) deleteCacheForNode(nodeName string) error {\n\tnode, err := ss.getNodeIdentityByNodeName(nodeName, azcache.CacheReadTypeUnsafe)\n\tif err != nil {\n\t\tklog.Errorf(\"deleteCacheForNode(%s) failed with error: %v\", nodeName, err)\n\t\treturn err\n\t}\n\n\tcacheKey, timedcache, err := ss.getVMSSVMCache(node.resourceGroup, node.vmssName)\n\tif err != nil {\n\t\tklog.Errorf(\"deleteCacheForNode(%s) failed with error: %v\", nodeName, err)\n\t\treturn err\n\t}\n\n\tvmcache, err := timedcache.Get(cacheKey, azcache.CacheReadTypeUnsafe)\n\tif err != nil {\n\t\tklog.Errorf(\"deleteCacheForNode(%s) failed with error: %v\", nodeName, err)\n\t\treturn err\n\t}\n\tvirtualMachines := vmcache.(*sync.Map)\n\tvirtualMachines.Delete(nodeName)\n\n\tif err := ss.gcVMSSVMCache(); err != nil {\n\t\tklog.Errorf(\"deleteCacheForNode(%s) failed to gc stale vmss caches: %v\", nodeName, err)\n\t}\n\n\treturn nil\n}","line":{"from":257,"to":283}} {"id":100033376,"name":"newAvailabilitySetNodesCache","signature":"func (ss *scaleSet) newAvailabilitySetNodesCache() (*azcache.TimedCache, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss_cache.go","code":"func (ss *scaleSet) newAvailabilitySetNodesCache() (*azcache.TimedCache, error) {\n\tgetter := func(key string) (interface{}, error) {\n\t\tvmNames := sets.NewString()\n\t\tresourceGroups, err := ss.GetResourceGroups()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, resourceGroup := range resourceGroups.List() {\n\t\t\tvmList, err := ss.Cloud.ListVirtualMachines(resourceGroup)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tfor _, vm := range vmList {\n\t\t\t\tif vm.Name != nil {\n\t\t\t\t\tvmNames.Insert(*vm.Name)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// store all the node names in the cluster when the cache data was created.\n\t\tnodeNames, err := ss.GetNodeNames()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tlocalCache := availabilitySetEntry{\n\t\t\tvmNames: vmNames,\n\t\t\tnodeNames: nodeNames,\n\t\t}\n\n\t\treturn localCache, nil\n\t}\n\n\tif ss.Config.AvailabilitySetNodesCacheTTLInSeconds == 0 {\n\t\tss.Config.AvailabilitySetNodesCacheTTLInSeconds = availabilitySetNodesCacheTTLDefaultInSeconds\n\t}\n\treturn azcache.NewTimedcache(time.Duration(ss.Config.AvailabilitySetNodesCacheTTLInSeconds)*time.Second, getter)\n}","line":{"from":285,"to":324}} {"id":100033377,"name":"isNodeManagedByAvailabilitySet","signature":"func (ss *scaleSet) isNodeManagedByAvailabilitySet(nodeName string, crt azcache.AzureCacheReadType) (bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_vmss_cache.go","code":"func (ss *scaleSet) isNodeManagedByAvailabilitySet(nodeName string, crt azcache.AzureCacheReadType) (bool, error) {\n\t// Assume all nodes are managed by VMSS when DisableAvailabilitySetNodes is enabled.\n\tif ss.DisableAvailabilitySetNodes {\n\t\tklog.V(2).Infof(\"Assuming node %q is managed by VMSS since DisableAvailabilitySetNodes is set to true\", nodeName)\n\t\treturn false, nil\n\t}\n\n\tcached, err := ss.availabilitySetNodesCache.Get(availabilitySetNodesKey, crt)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tcachedNodes := cached.(availabilitySetEntry).nodeNames\n\t// if the node is not in the cache, assume the node has joined after the last cache refresh and attempt to refresh the cache.\n\tif !cachedNodes.Has(nodeName) {\n\t\tklog.V(2).Infof(\"Node %s has joined the cluster since the last VM cache refresh, refreshing the cache\", nodeName)\n\t\tcached, err = ss.availabilitySetNodesCache.Get(availabilitySetNodesKey, azcache.CacheReadTypeForceRefresh)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\tcachedVMs := cached.(availabilitySetEntry).vmNames\n\treturn cachedVMs.Has(nodeName), nil\n}","line":{"from":326,"to":350}} {"id":100033378,"name":"checkResourceExistsFromError","signature":"func checkResourceExistsFromError(err *retry.Error) (bool, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_wrap.go","code":"// checkExistsFromError inspects an error and returns a true if err is nil,\n// false if error is an autorest.Error with StatusCode=404 and will return the\n// error back if error is another status code or another type of error.\nfunc checkResourceExistsFromError(err *retry.Error) (bool, *retry.Error) {\n\tif err == nil {\n\t\treturn true, nil\n\t}\n\n\tif err.HTTPStatusCode == http.StatusNotFound {\n\t\treturn false, nil\n\t}\n\n\treturn false, err\n}","line":{"from":50,"to":63}} {"id":100033379,"name":"getVirtualMachine","signature":"func (az *Cloud) getVirtualMachine(nodeName types.NodeName, crt azcache.AzureCacheReadType) (vm compute.VirtualMachine, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_wrap.go","code":"// / getVirtualMachine calls 'VirtualMachinesClient.Get' with a timed cache\n// / The service side has throttling control that delays responses if there are multiple requests onto certain vm\n// / resource request in short period.\nfunc (az *Cloud) getVirtualMachine(nodeName types.NodeName, crt azcache.AzureCacheReadType) (vm compute.VirtualMachine, err error) {\n\tvmName := string(nodeName)\n\tcachedVM, err := az.vmCache.Get(vmName, crt)\n\tif err != nil {\n\t\treturn vm, err\n\t}\n\n\tif cachedVM == nil {\n\t\treturn vm, cloudprovider.InstanceNotFound\n\t}\n\n\treturn *(cachedVM.(*compute.VirtualMachine)), nil\n}","line":{"from":65,"to":80}} {"id":100033380,"name":"getRouteTable","signature":"func (az *Cloud) getRouteTable(crt azcache.AzureCacheReadType) (routeTable network.RouteTable, exists bool, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_wrap.go","code":"func (az *Cloud) getRouteTable(crt azcache.AzureCacheReadType) (routeTable network.RouteTable, exists bool, err error) {\n\tcachedRt, err := az.rtCache.Get(az.RouteTableName, crt)\n\tif err != nil {\n\t\treturn routeTable, false, err\n\t}\n\n\tif cachedRt == nil {\n\t\treturn routeTable, false, nil\n\t}\n\n\treturn *(cachedRt.(*network.RouteTable)), true, nil\n}","line":{"from":82,"to":93}} {"id":100033381,"name":"getPublicIPAddress","signature":"func (az *Cloud) getPublicIPAddress(pipResourceGroup string, pipName string) (network.PublicIPAddress, bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_wrap.go","code":"func (az *Cloud) getPublicIPAddress(pipResourceGroup string, pipName string) (network.PublicIPAddress, bool, error) {\n\tresourceGroup := az.ResourceGroup\n\tif pipResourceGroup != \"\" {\n\t\tresourceGroup = pipResourceGroup\n\t}\n\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\tpip, err := az.PublicIPAddressesClient.Get(ctx, resourceGroup, pipName, \"\")\n\texists, rerr := checkResourceExistsFromError(err)\n\tif rerr != nil {\n\t\treturn pip, false, rerr.Error()\n\t}\n\n\tif !exists {\n\t\tklog.V(2).Infof(\"Public IP %q not found\", pipName)\n\t\treturn pip, false, nil\n\t}\n\n\treturn pip, exists, nil\n}","line":{"from":95,"to":115}} {"id":100033382,"name":"getSubnet","signature":"func (az *Cloud) getSubnet(virtualNetworkName string, subnetName string) (network.Subnet, bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_wrap.go","code":"func (az *Cloud) getSubnet(virtualNetworkName string, subnetName string) (network.Subnet, bool, error) {\n\tvar rg string\n\tif len(az.VnetResourceGroup) \u003e 0 {\n\t\trg = az.VnetResourceGroup\n\t} else {\n\t\trg = az.ResourceGroup\n\t}\n\n\tctx, cancel := getContextWithCancel()\n\tdefer cancel()\n\tsubnet, err := az.SubnetsClient.Get(ctx, rg, virtualNetworkName, subnetName, \"\")\n\texists, rerr := checkResourceExistsFromError(err)\n\tif rerr != nil {\n\t\treturn subnet, false, rerr.Error()\n\t}\n\n\tif !exists {\n\t\tklog.V(2).Infof(\"Subnet %q not found\", subnetName)\n\t\treturn subnet, false, nil\n\t}\n\n\treturn subnet, exists, nil\n}","line":{"from":117,"to":139}} {"id":100033383,"name":"getAzureLoadBalancer","signature":"func (az *Cloud) getAzureLoadBalancer(name string, crt azcache.AzureCacheReadType) (lb network.LoadBalancer, exists bool, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_wrap.go","code":"func (az *Cloud) getAzureLoadBalancer(name string, crt azcache.AzureCacheReadType) (lb network.LoadBalancer, exists bool, err error) {\n\tcachedLB, err := az.lbCache.Get(name, crt)\n\tif err != nil {\n\t\treturn lb, false, err\n\t}\n\n\tif cachedLB == nil {\n\t\treturn lb, false, nil\n\t}\n\n\treturn *(cachedLB.(*network.LoadBalancer)), true, nil\n}","line":{"from":141,"to":152}} {"id":100033384,"name":"getSecurityGroup","signature":"func (az *Cloud) getSecurityGroup(crt azcache.AzureCacheReadType) (network.SecurityGroup, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_wrap.go","code":"func (az *Cloud) getSecurityGroup(crt azcache.AzureCacheReadType) (network.SecurityGroup, error) {\n\tnsg := network.SecurityGroup{}\n\tif az.SecurityGroupName == \"\" {\n\t\treturn nsg, fmt.Errorf(\"securityGroupName is not configured\")\n\t}\n\n\tsecurityGroup, err := az.nsgCache.Get(az.SecurityGroupName, crt)\n\tif err != nil {\n\t\treturn nsg, err\n\t}\n\n\tif securityGroup == nil {\n\t\treturn nsg, fmt.Errorf(\"nsg %q not found\", az.SecurityGroupName)\n\t}\n\n\treturn *(securityGroup.(*network.SecurityGroup)), nil\n}","line":{"from":154,"to":170}} {"id":100033385,"name":"newVMCache","signature":"func (az *Cloud) newVMCache() (*azcache.TimedCache, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_wrap.go","code":"func (az *Cloud) newVMCache() (*azcache.TimedCache, error) {\n\tgetter := func(key string) (interface{}, error) {\n\t\t// Currently InstanceView request are used by azure_zones, while the calls come after non-InstanceView\n\t\t// request. If we first send an InstanceView request and then a non InstanceView request, the second\n\t\t// request will still hit throttling. This is what happens now for cloud controller manager: In this\n\t\t// case we do get instance view every time to fulfill the azure_zones requirement without hitting\n\t\t// throttling.\n\t\t// Consider adding separate parameter for controlling 'InstanceView' once node update issue #56276 is fixed\n\t\tctx, cancel := getContextWithCancel()\n\t\tdefer cancel()\n\n\t\tresourceGroup, err := az.GetNodeResourceGroup(key)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvm, verr := az.VirtualMachinesClient.Get(ctx, resourceGroup, key, compute.InstanceView)\n\t\texists, rerr := checkResourceExistsFromError(verr)\n\t\tif rerr != nil {\n\t\t\treturn nil, rerr.Error()\n\t\t}\n\n\t\tif !exists {\n\t\t\tklog.V(2).Infof(\"Virtual machine %q not found\", key)\n\t\t\treturn nil, nil\n\t\t}\n\n\t\tif vm.VirtualMachineProperties != nil \u0026\u0026\n\t\t\tstrings.EqualFold(pointer.StringDeref(vm.VirtualMachineProperties.ProvisioningState, \"\"), string(compute.ProvisioningStateDeleting)) {\n\t\t\tklog.V(2).Infof(\"Virtual machine %q is under deleting\", key)\n\t\t\treturn nil, nil\n\t\t}\n\n\t\treturn \u0026vm, nil\n\t}\n\n\tif az.VMCacheTTLInSeconds == 0 {\n\t\taz.VMCacheTTLInSeconds = vmCacheTTLDefaultInSeconds\n\t}\n\treturn azcache.NewTimedcache(time.Duration(az.VMCacheTTLInSeconds)*time.Second, getter)\n}","line":{"from":172,"to":212}} {"id":100033386,"name":"newLBCache","signature":"func (az *Cloud) newLBCache() (*azcache.TimedCache, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_wrap.go","code":"func (az *Cloud) newLBCache() (*azcache.TimedCache, error) {\n\tgetter := func(key string) (interface{}, error) {\n\t\tctx, cancel := getContextWithCancel()\n\t\tdefer cancel()\n\n\t\tlb, err := az.LoadBalancerClient.Get(ctx, az.getLoadBalancerResourceGroup(), key, \"\")\n\t\texists, rerr := checkResourceExistsFromError(err)\n\t\tif rerr != nil {\n\t\t\treturn nil, rerr.Error()\n\t\t}\n\n\t\tif !exists {\n\t\t\tklog.V(2).Infof(\"Load balancer %q not found\", key)\n\t\t\treturn nil, nil\n\t\t}\n\n\t\treturn \u0026lb, nil\n\t}\n\n\tif az.LoadBalancerCacheTTLInSeconds == 0 {\n\t\taz.LoadBalancerCacheTTLInSeconds = loadBalancerCacheTTLDefaultInSeconds\n\t}\n\treturn azcache.NewTimedcache(time.Duration(az.LoadBalancerCacheTTLInSeconds)*time.Second, getter)\n}","line":{"from":214,"to":237}} {"id":100033387,"name":"newNSGCache","signature":"func (az *Cloud) newNSGCache() (*azcache.TimedCache, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_wrap.go","code":"func (az *Cloud) newNSGCache() (*azcache.TimedCache, error) {\n\tgetter := func(key string) (interface{}, error) {\n\t\tctx, cancel := getContextWithCancel()\n\t\tdefer cancel()\n\t\tnsg, err := az.SecurityGroupsClient.Get(ctx, az.SecurityGroupResourceGroup, key, \"\")\n\t\texists, rerr := checkResourceExistsFromError(err)\n\t\tif rerr != nil {\n\t\t\treturn nil, rerr.Error()\n\t\t}\n\n\t\tif !exists {\n\t\t\tklog.V(2).Infof(\"Security group %q not found\", key)\n\t\t\treturn nil, nil\n\t\t}\n\n\t\treturn \u0026nsg, nil\n\t}\n\n\tif az.NsgCacheTTLInSeconds == 0 {\n\t\taz.NsgCacheTTLInSeconds = nsgCacheTTLDefaultInSeconds\n\t}\n\treturn azcache.NewTimedcache(time.Duration(az.NsgCacheTTLInSeconds)*time.Second, getter)\n}","line":{"from":239,"to":261}} {"id":100033388,"name":"newRouteTableCache","signature":"func (az *Cloud) newRouteTableCache() (*azcache.TimedCache, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_wrap.go","code":"func (az *Cloud) newRouteTableCache() (*azcache.TimedCache, error) {\n\tgetter := func(key string) (interface{}, error) {\n\t\tctx, cancel := getContextWithCancel()\n\t\tdefer cancel()\n\t\trt, err := az.RouteTablesClient.Get(ctx, az.RouteTableResourceGroup, key, \"\")\n\t\texists, rerr := checkResourceExistsFromError(err)\n\t\tif rerr != nil {\n\t\t\treturn nil, rerr.Error()\n\t\t}\n\n\t\tif !exists {\n\t\t\tklog.V(2).Infof(\"Route table %q not found\", key)\n\t\t\treturn nil, nil\n\t\t}\n\n\t\treturn \u0026rt, nil\n\t}\n\n\tif az.RouteTableCacheTTLInSeconds == 0 {\n\t\taz.RouteTableCacheTTLInSeconds = routeTableCacheTTLDefaultInSeconds\n\t}\n\treturn azcache.NewTimedcache(time.Duration(az.RouteTableCacheTTLInSeconds)*time.Second, getter)\n}","line":{"from":263,"to":285}} {"id":100033389,"name":"useStandardLoadBalancer","signature":"func (az *Cloud) useStandardLoadBalancer() bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_wrap.go","code":"func (az *Cloud) useStandardLoadBalancer() bool {\n\treturn strings.EqualFold(az.LoadBalancerSku, loadBalancerSkuStandard)\n}","line":{"from":287,"to":289}} {"id":100033390,"name":"excludeMasterNodesFromStandardLB","signature":"func (az *Cloud) excludeMasterNodesFromStandardLB() bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_wrap.go","code":"func (az *Cloud) excludeMasterNodesFromStandardLB() bool {\n\treturn az.ExcludeMasterFromStandardLB != nil \u0026\u0026 *az.ExcludeMasterFromStandardLB\n}","line":{"from":291,"to":293}} {"id":100033391,"name":"disableLoadBalancerOutboundSNAT","signature":"func (az *Cloud) disableLoadBalancerOutboundSNAT() bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_wrap.go","code":"func (az *Cloud) disableLoadBalancerOutboundSNAT() bool {\n\tif !az.useStandardLoadBalancer() || az.DisableOutboundSNAT == nil {\n\t\treturn false\n\t}\n\n\treturn *az.DisableOutboundSNAT\n}","line":{"from":295,"to":301}} {"id":100033392,"name":"IsNodeUnmanaged","signature":"func (az *Cloud) IsNodeUnmanaged(nodeName string) (bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_wrap.go","code":"// IsNodeUnmanaged returns true if the node is not managed by Azure cloud provider.\n// Those nodes includes on-prem or VMs from other clouds. They will not be added to load balancer\n// backends. Azure routes and managed disks are also not supported for them.\nfunc (az *Cloud) IsNodeUnmanaged(nodeName string) (bool, error) {\n\tunmanagedNodes, err := az.GetUnmanagedNodes()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn unmanagedNodes.Has(nodeName), nil\n}","line":{"from":303,"to":313}} {"id":100033393,"name":"IsNodeUnmanagedByProviderID","signature":"func (az *Cloud) IsNodeUnmanagedByProviderID(providerID string) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_wrap.go","code":"// IsNodeUnmanagedByProviderID returns true if the node is not managed by Azure cloud provider.\n// All managed node's providerIDs are in format 'azure:///subscriptions/\u003cid\u003e/resourceGroups/\u003crg\u003e/providers/Microsoft.Compute/.*'\nfunc (az *Cloud) IsNodeUnmanagedByProviderID(providerID string) bool {\n\treturn !azureNodeProviderIDRE.Match([]byte(providerID))\n}","line":{"from":315,"to":319}} {"id":100033394,"name":"convertResourceGroupNameToLower","signature":"func convertResourceGroupNameToLower(resourceID string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_wrap.go","code":"// convertResourceGroupNameToLower converts the resource group name in the resource ID to be lowered.\nfunc convertResourceGroupNameToLower(resourceID string) (string, error) {\n\tmatches := azureResourceGroupNameRE.FindStringSubmatch(resourceID)\n\tif len(matches) != 2 {\n\t\treturn \"\", fmt.Errorf(\"%q isn't in Azure resource ID format %q\", resourceID, azureResourceGroupNameRE.String())\n\t}\n\n\tresourceGroup := matches[1]\n\treturn strings.Replace(resourceID, resourceGroup, strings.ToLower(resourceGroup), 1), nil\n}","line":{"from":321,"to":330}} {"id":100033395,"name":"isBackendPoolOnSameLB","signature":"func isBackendPoolOnSameLB(newBackendPoolID string, existingBackendPools []string) (bool, string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_wrap.go","code":"// isBackendPoolOnSameLB checks whether newBackendPoolID is on the same load balancer as existingBackendPools.\n// Since both public and internal LBs are supported, lbName and lbName-internal are treated as same.\n// If not same, the lbName for existingBackendPools would also be returned.\nfunc isBackendPoolOnSameLB(newBackendPoolID string, existingBackendPools []string) (bool, string, error) {\n\tmatches := backendPoolIDRE.FindStringSubmatch(newBackendPoolID)\n\tif len(matches) != 2 {\n\t\treturn false, \"\", fmt.Errorf(\"new backendPoolID %q is in wrong format\", newBackendPoolID)\n\t}\n\n\tnewLBName := matches[1]\n\tnewLBNameTrimmed := strings.TrimSuffix(newLBName, InternalLoadBalancerNameSuffix)\n\tfor _, backendPool := range existingBackendPools {\n\t\tmatches := backendPoolIDRE.FindStringSubmatch(backendPool)\n\t\tif len(matches) != 2 {\n\t\t\treturn false, \"\", fmt.Errorf(\"existing backendPoolID %q is in wrong format\", backendPool)\n\t\t}\n\n\t\tlbName := matches[1]\n\t\tif !strings.EqualFold(strings.TrimSuffix(lbName, InternalLoadBalancerNameSuffix), newLBNameTrimmed) {\n\t\t\treturn false, lbName, nil\n\t\t}\n\t}\n\n\treturn true, \"\", nil\n}","line":{"from":332,"to":356}} {"id":100033396,"name":"makeZone","signature":"func (az *Cloud) makeZone(location string, zoneID int) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_zones.go","code":"// makeZone returns the zone value in format of \u003cregion\u003e-\u003czone-id\u003e.\nfunc (az *Cloud) makeZone(location string, zoneID int) string {\n\treturn fmt.Sprintf(\"%s-%d\", strings.ToLower(location), zoneID)\n}","line":{"from":35,"to":38}} {"id":100033397,"name":"isAvailabilityZone","signature":"func (az *Cloud) isAvailabilityZone(zone string) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_zones.go","code":"// isAvailabilityZone returns true if the zone is in format of \u003cregion\u003e-\u003czone-id\u003e.\nfunc (az *Cloud) isAvailabilityZone(zone string) bool {\n\treturn strings.HasPrefix(zone, fmt.Sprintf(\"%s-\", az.Location))\n}","line":{"from":40,"to":43}} {"id":100033398,"name":"GetZoneID","signature":"func (az *Cloud) GetZoneID(zoneLabel string) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_zones.go","code":"// GetZoneID returns the ID of zone from node's zone label.\nfunc (az *Cloud) GetZoneID(zoneLabel string) string {\n\tif !az.isAvailabilityZone(zoneLabel) {\n\t\treturn \"\"\n\t}\n\n\treturn strings.TrimPrefix(zoneLabel, fmt.Sprintf(\"%s-\", az.Location))\n}","line":{"from":45,"to":52}} {"id":100033399,"name":"GetZone","signature":"func (az *Cloud) GetZone(ctx context.Context) (cloudprovider.Zone, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_zones.go","code":"// GetZone returns the Zone containing the current availability zone and locality region that the program is running in.\n// If the node is not running with availability zones, then it will fall back to fault domain.\nfunc (az *Cloud) GetZone(ctx context.Context) (cloudprovider.Zone, error) {\n\tif az.UseInstanceMetadata {\n\t\tmetadata, err := az.metadata.GetMetadata(azcache.CacheReadTypeUnsafe)\n\t\tif err != nil {\n\t\t\treturn cloudprovider.Zone{}, err\n\t\t}\n\n\t\tif metadata.Compute == nil {\n\t\t\taz.metadata.imsCache.Delete(metadataCacheKey)\n\t\t\treturn cloudprovider.Zone{}, fmt.Errorf(\"failure of getting compute information from instance metadata\")\n\t\t}\n\n\t\tzone := \"\"\n\t\tlocation := metadata.Compute.Location\n\t\tif metadata.Compute.Zone != \"\" {\n\t\t\tzoneID, err := strconv.Atoi(metadata.Compute.Zone)\n\t\t\tif err != nil {\n\t\t\t\treturn cloudprovider.Zone{}, fmt.Errorf(\"failed to parse zone ID %q: %v\", metadata.Compute.Zone, err)\n\t\t\t}\n\t\t\tzone = az.makeZone(location, zoneID)\n\t\t} else {\n\t\t\tklog.V(3).Infof(\"Availability zone is not enabled for the node, falling back to fault domain\")\n\t\t\tzone = metadata.Compute.FaultDomain\n\t\t}\n\n\t\treturn cloudprovider.Zone{\n\t\t\tFailureDomain: strings.ToLower(zone),\n\t\t\tRegion: strings.ToLower(location),\n\t\t}, nil\n\t}\n\t// if UseInstanceMetadata is false, get Zone name by calling ARM\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\treturn cloudprovider.Zone{}, fmt.Errorf(\"failure getting hostname from kernel\")\n\t}\n\treturn az.VMSet.GetZoneByNodeName(strings.ToLower(hostname))\n}","line":{"from":54,"to":92}} {"id":100033400,"name":"GetZoneByProviderID","signature":"func (az *Cloud) GetZoneByProviderID(ctx context.Context, providerID string) (cloudprovider.Zone, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_zones.go","code":"// GetZoneByProviderID implements Zones.GetZoneByProviderID\n// This is particularly useful in external cloud providers where the kubelet\n// does not initialize node data.\nfunc (az *Cloud) GetZoneByProviderID(ctx context.Context, providerID string) (cloudprovider.Zone, error) {\n\tif providerID == \"\" {\n\t\treturn cloudprovider.Zone{}, errNodeNotInitialized\n\t}\n\n\t// Returns nil for unmanaged nodes because azure cloud provider couldn't fetch information for them.\n\tif az.IsNodeUnmanagedByProviderID(providerID) {\n\t\tklog.V(2).Infof(\"GetZoneByProviderID: omitting unmanaged node %q\", providerID)\n\t\treturn cloudprovider.Zone{}, nil\n\t}\n\n\tnodeName, err := az.VMSet.GetNodeNameByProviderID(providerID)\n\tif err != nil {\n\t\treturn cloudprovider.Zone{}, err\n\t}\n\n\treturn az.GetZoneByNodeName(ctx, nodeName)\n}","line":{"from":94,"to":114}} {"id":100033401,"name":"GetZoneByNodeName","signature":"func (az *Cloud) GetZoneByNodeName(ctx context.Context, nodeName types.NodeName) (cloudprovider.Zone, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/azure_zones.go","code":"// GetZoneByNodeName implements Zones.GetZoneByNodeName\n// This is particularly useful in external cloud providers where the kubelet\n// does not initialize node data.\nfunc (az *Cloud) GetZoneByNodeName(ctx context.Context, nodeName types.NodeName) (cloudprovider.Zone, error) {\n\t// Returns \"\" for unmanaged nodes because azure cloud provider couldn't fetch information for them.\n\tunmanaged, err := az.IsNodeUnmanaged(string(nodeName))\n\tif err != nil {\n\t\treturn cloudprovider.Zone{}, err\n\t}\n\tif unmanaged {\n\t\tklog.V(2).Infof(\"GetZoneByNodeName: omitting unmanaged node %q\", nodeName)\n\t\treturn cloudprovider.Zone{}, nil\n\t}\n\n\treturn az.VMSet.GetZoneByNodeName(string(nodeName))\n}","line":{"from":116,"to":131}} {"id":100033402,"name":"cacheKeyFunc","signature":"func cacheKeyFunc(obj interface{}) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/cache/azure_cache.go","code":"// cacheKeyFunc defines the key function required in TTLStore.\nfunc cacheKeyFunc(obj interface{}) (string, error) {\n\treturn obj.(*AzureCacheEntry).Key, nil\n}","line":{"from":61,"to":64}} {"id":100033403,"name":"NewTimedcache","signature":"func NewTimedcache(ttl time.Duration, getter GetFunc) (*TimedCache, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/cache/azure_cache.go","code":"// NewTimedcache creates a new TimedCache.\nfunc NewTimedcache(ttl time.Duration, getter GetFunc) (*TimedCache, error) {\n\tif getter == nil {\n\t\treturn nil, fmt.Errorf(\"getter is not provided\")\n\t}\n\n\treturn \u0026TimedCache{\n\t\tGetter: getter,\n\t\t// switch to using NewStore instead of NewTTLStore so that we can\n\t\t// reuse entries for calls that are fine with reading expired/stalled data.\n\t\t// with NewTTLStore, entries are not returned if they have already expired.\n\t\tStore: cache.NewStore(cacheKeyFunc),\n\t\tTTL: ttl,\n\t}, nil\n}","line":{"from":74,"to":88}} {"id":100033404,"name":"getInternal","signature":"func (t *TimedCache) getInternal(key string) (*AzureCacheEntry, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/cache/azure_cache.go","code":"// getInternal returns AzureCacheEntry by key. If the key is not cached yet,\n// it returns a AzureCacheEntry with nil data.\nfunc (t *TimedCache) getInternal(key string) (*AzureCacheEntry, error) {\n\tentry, exists, err := t.Store.GetByKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// if entry exists, return the entry\n\tif exists {\n\t\treturn entry.(*AzureCacheEntry), nil\n\t}\n\n\t// lock here to ensure if entry doesn't exist, we add a new entry\n\t// avoiding overwrites\n\tt.Lock.Lock()\n\tdefer t.Lock.Unlock()\n\n\t// Another goroutine might have written the same key.\n\tentry, exists, err = t.Store.GetByKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif exists {\n\t\treturn entry.(*AzureCacheEntry), nil\n\t}\n\n\t// Still not found, add new entry with nil data.\n\t// Note the data will be filled later by getter.\n\tnewEntry := \u0026AzureCacheEntry{\n\t\tKey: key,\n\t\tData: nil,\n\t}\n\tt.Store.Add(newEntry)\n\treturn newEntry, nil\n}","line":{"from":90,"to":124}} {"id":100033405,"name":"Get","signature":"func (t *TimedCache) Get(key string, crt AzureCacheReadType) (interface{}, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/cache/azure_cache.go","code":"// Get returns the requested item by key.\nfunc (t *TimedCache) Get(key string, crt AzureCacheReadType) (interface{}, error) {\n\tentry, err := t.getInternal(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tentry.Lock.Lock()\n\tdefer entry.Lock.Unlock()\n\n\t// entry exists and if cache is not force refreshed\n\tif entry.Data != nil \u0026\u0026 crt != CacheReadTypeForceRefresh {\n\t\t// allow unsafe read, so return data even if expired\n\t\tif crt == CacheReadTypeUnsafe {\n\t\t\treturn entry.Data, nil\n\t\t}\n\t\t// if cached data is not expired, return cached data\n\t\tif crt == CacheReadTypeDefault \u0026\u0026 time.Since(entry.CreatedOn) \u003c t.TTL {\n\t\t\treturn entry.Data, nil\n\t\t}\n\t}\n\t// Data is not cached yet, cache data is expired or requested force refresh\n\t// cache it by getter. entry is locked before getting to ensure concurrent\n\t// gets don't result in multiple ARM calls.\n\tdata, err := t.Getter(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// set the data in cache and also set the last update time\n\t// to now as the data was recently fetched\n\tentry.Data = data\n\tentry.CreatedOn = time.Now().UTC()\n\n\treturn entry.Data, nil\n}","line":{"from":126,"to":161}} {"id":100033406,"name":"Delete","signature":"func (t *TimedCache) Delete(key string) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/cache/azure_cache.go","code":"// Delete removes an item from the cache.\nfunc (t *TimedCache) Delete(key string) error {\n\treturn t.Store.Delete(\u0026AzureCacheEntry{\n\t\tKey: key,\n\t})\n}","line":{"from":163,"to":168}} {"id":100033407,"name":"Set","signature":"func (t *TimedCache) Set(key string, data interface{})","file":"staging/src/k8s.io/legacy-cloud-providers/azure/cache/azure_cache.go","code":"// Set sets the data cache for the key.\n// It is only used for testing.\nfunc (t *TimedCache) Set(key string, data interface{}) {\n\tt.Store.Add(\u0026AzureCacheEntry{\n\t\tKey: key,\n\t\tData: data,\n\t\tCreatedOn: time.Now().UTC(),\n\t})\n}","line":{"from":170,"to":178}} {"id":100033408,"name":"New","signature":"func New(authorizer autorest.Authorizer, baseURI, userAgent, apiVersion, clientRegion string, clientBackoff *retry.Backoff) *Client","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// New creates a ARM client\nfunc New(authorizer autorest.Authorizer, baseURI, userAgent, apiVersion, clientRegion string, clientBackoff *retry.Backoff) *Client {\n\trestClient := autorest.NewClientWithUserAgent(userAgent)\n\trestClient.PollingDelay = 5 * time.Second\n\trestClient.RetryAttempts = 3\n\trestClient.RetryDuration = time.Second * 1\n\trestClient.Authorizer = authorizer\n\n\tif userAgent == \"\" {\n\t\trestClient.UserAgent = GetUserAgent(restClient)\n\t}\n\n\tbackoff := clientBackoff\n\tif backoff == nil {\n\t\tbackoff = \u0026retry.Backoff{}\n\t}\n\tif backoff.Steps == 0 {\n\t\t// 1 steps means no retry.\n\t\tbackoff.Steps = 1\n\t}\n\n\treturn \u0026Client{\n\t\tclient: restClient,\n\t\tbaseURI: baseURI,\n\t\tbackoff: backoff,\n\t\tapiVersion: apiVersion,\n\t\tclientRegion: NormalizeAzureRegion(clientRegion),\n\t}\n}","line":{"from":54,"to":82}} {"id":100033409,"name":"GetUserAgent","signature":"func GetUserAgent(client autorest.Client) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// GetUserAgent gets the autorest client with a user agent that\n// includes \"kubernetes\" and the full kubernetes git version string\n// example:\n// Azure-SDK-for-Go/7.0.1 arm-network/2016-09-01; kubernetes-cloudprovider/v1.17.0;\nfunc GetUserAgent(client autorest.Client) string {\n\tk8sVersion := version.Get().GitVersion\n\treturn fmt.Sprintf(\"%s; kubernetes-cloudprovider/%s\", client.UserAgent, k8sVersion)\n}","line":{"from":84,"to":91}} {"id":100033410,"name":"NormalizeAzureRegion","signature":"func NormalizeAzureRegion(name string) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// NormalizeAzureRegion returns a normalized Azure region with white spaces removed and converted to lower case\nfunc NormalizeAzureRegion(name string) string {\n\tregion := \"\"\n\tfor _, runeValue := range name {\n\t\tif !unicode.IsSpace(runeValue) {\n\t\t\tregion += string(runeValue)\n\t\t}\n\t}\n\treturn strings.ToLower(region)\n}","line":{"from":93,"to":102}} {"id":100033411,"name":"sendRequest","signature":"func (c *Client) sendRequest(ctx context.Context, request *http.Request) (*http.Response, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// sendRequest sends a http request to ARM service.\n// Although Azure SDK supports retries per https://github.com/azure/azure-sdk-for-go#request-retry-policy, we\n// disable it since we want to fully control the retry policies.\nfunc (c *Client) sendRequest(ctx context.Context, request *http.Request) (*http.Response, *retry.Error) {\n\tsendBackoff := *c.backoff\n\tresponse, err := autorest.SendWithSender(\n\t\tc.client,\n\t\trequest,\n\t\tretry.DoExponentialBackoffRetry(\u0026sendBackoff),\n\t)\n\n\tif response == nil \u0026\u0026 err == nil {\n\t\treturn response, retry.NewError(false, fmt.Errorf(\"Empty response and no HTTP code\"))\n\t}\n\n\treturn response, retry.GetError(response, err)\n}","line":{"from":104,"to":120}} {"id":100033412,"name":"Send","signature":"func (c *Client) Send(ctx context.Context, request *http.Request) (*http.Response, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// Send sends a http request to ARM service with possible retry to regional ARM endpoint.\nfunc (c *Client) Send(ctx context.Context, request *http.Request) (*http.Response, *retry.Error) {\n\tresponse, rerr := c.sendRequest(ctx, request)\n\tif rerr != nil {\n\t\treturn response, rerr\n\t}\n\n\tif response.StatusCode != http.StatusNotFound || c.clientRegion == \"\" {\n\t\treturn response, rerr\n\t}\n\n\tbodyBytes, _ := ioutil.ReadAll(response.Body)\n\tdefer func() {\n\t\tresponse.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))\n\t}()\n\n\tbodyString := string(bodyBytes)\n\tklog.V(5).Infof(\"Send.sendRequest original error message: %s\", bodyString)\n\n\t// Hack: retry the regional ARM endpoint in case of ARM traffic split and arm resource group replication is too slow\n\tvar body map[string]interface{}\n\tif e := json.Unmarshal(bodyBytes, \u0026body); e != nil {\n\t\tklog.V(5).Infof(\"Send.sendRequest: error in parsing response body string: %s, Skip retrying regional host\", e)\n\t\treturn response, rerr\n\t}\n\n\tif err, ok := body[\"error\"].(map[string]interface{}); !ok ||\n\t\terr[\"code\"] == nil ||\n\t\t!strings.EqualFold(err[\"code\"].(string), \"ResourceGroupNotFound\") {\n\t\tklog.V(5).Infof(\"Send.sendRequest: response body does not contain ResourceGroupNotFound error code. Skip retrying regional host\")\n\t\treturn response, rerr\n\t}\n\n\tcurrentHost := request.URL.Host\n\tif request.Host != \"\" {\n\t\tcurrentHost = request.Host\n\t}\n\n\tif strings.HasPrefix(strings.ToLower(currentHost), c.clientRegion) {\n\t\tklog.V(5).Infof(\"Send.sendRequest: current host %s is regional host. Skip retrying regional host.\", currentHost)\n\t\treturn response, rerr\n\t}\n\n\trequest.Host = fmt.Sprintf(\"%s.%s\", c.clientRegion, strings.ToLower(currentHost))\n\tklog.V(5).Infof(\"Send.sendRegionalRequest on ResourceGroupNotFound error. Retrying regional host: %s\", request.Host)\n\tregionalResponse, regionalError := c.sendRequest(ctx, request)\n\n\t// only use the result if the regional request actually goes through and returns 2xx status code, for two reasons:\n\t// 1. the retry on regional ARM host approach is a hack.\n\t// 2. the concatenated regional uri could be wrong as the rule is not officially declared by ARM.\n\tif regionalResponse == nil || regionalResponse.StatusCode \u003e 299 {\n\t\tregionalErrStr := \"\"\n\t\tif regionalError != nil {\n\t\t\tregionalErrStr = regionalError.Error().Error()\n\t\t}\n\n\t\tklog.V(5).Infof(\"Send.sendRegionalRequest failed to get response from regional host, error: '%s'. Ignoring the result.\", regionalErrStr)\n\t\treturn response, rerr\n\t}\n\n\treturn regionalResponse, regionalError\n}","line":{"from":122,"to":183}} {"id":100033413,"name":"PreparePutRequest","signature":"func (c *Client) PreparePutRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// PreparePutRequest prepares put request\nfunc (c *Client) PreparePutRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) {\n\tdecorators = append(\n\t\t[]autorest.PrepareDecorator{\n\t\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\t\tautorest.AsPut(),\n\t\t\tautorest.WithBaseURL(c.baseURI)},\n\t\tdecorators...)\n\treturn c.prepareRequest(ctx, decorators...)\n}","line":{"from":185,"to":194}} {"id":100033414,"name":"PreparePatchRequest","signature":"func (c *Client) PreparePatchRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// PreparePatchRequest prepares patch request\nfunc (c *Client) PreparePatchRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) {\n\tdecorators = append(\n\t\t[]autorest.PrepareDecorator{\n\t\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\t\tautorest.AsPatch(),\n\t\t\tautorest.WithBaseURL(c.baseURI)},\n\t\tdecorators...)\n\treturn c.prepareRequest(ctx, decorators...)\n}","line":{"from":196,"to":205}} {"id":100033415,"name":"PreparePostRequest","signature":"func (c *Client) PreparePostRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// PreparePostRequest prepares post request\nfunc (c *Client) PreparePostRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) {\n\tdecorators = append(\n\t\t[]autorest.PrepareDecorator{\n\t\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\t\tautorest.AsPost(),\n\t\t\tautorest.WithBaseURL(c.baseURI)},\n\t\tdecorators...)\n\treturn c.prepareRequest(ctx, decorators...)\n}","line":{"from":207,"to":216}} {"id":100033416,"name":"PrepareGetRequest","signature":"func (c *Client) PrepareGetRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// PrepareGetRequest prepares get request\nfunc (c *Client) PrepareGetRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) {\n\tdecorators = append(\n\t\t[]autorest.PrepareDecorator{\n\t\t\tautorest.AsGet(),\n\t\t\tautorest.WithBaseURL(c.baseURI)},\n\t\tdecorators...)\n\treturn c.prepareRequest(ctx, decorators...)\n}","line":{"from":218,"to":226}} {"id":100033417,"name":"PrepareDeleteRequest","signature":"func (c *Client) PrepareDeleteRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// PrepareDeleteRequest preparse delete request\nfunc (c *Client) PrepareDeleteRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) {\n\tdecorators = append(\n\t\t[]autorest.PrepareDecorator{\n\t\t\tautorest.AsDelete(),\n\t\t\tautorest.WithBaseURL(c.baseURI)},\n\t\tdecorators...)\n\treturn c.prepareRequest(ctx, decorators...)\n}","line":{"from":228,"to":236}} {"id":100033418,"name":"PrepareHeadRequest","signature":"func (c *Client) PrepareHeadRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// PrepareHeadRequest prepares head request\nfunc (c *Client) PrepareHeadRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) {\n\tdecorators = append(\n\t\t[]autorest.PrepareDecorator{\n\t\t\tautorest.AsHead(),\n\t\t\tautorest.WithBaseURL(c.baseURI)},\n\t\tdecorators...)\n\treturn c.prepareRequest(ctx, decorators...)\n}","line":{"from":238,"to":246}} {"id":100033419,"name":"WaitForAsyncOperationCompletion","signature":"func (c *Client) WaitForAsyncOperationCompletion(ctx context.Context, future *azure.Future, asyncOperationName string) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// WaitForAsyncOperationCompletion waits for an operation completion\nfunc (c *Client) WaitForAsyncOperationCompletion(ctx context.Context, future *azure.Future, asyncOperationName string) error {\n\terr := future.WaitForCompletionRef(ctx, c.client)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in WaitForCompletionRef: '%v'\", err)\n\t\treturn err\n\t}\n\n\tvar done bool\n\tdone, err = future.DoneWithContext(ctx, c.client)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in DoneWithContext: '%v'\", err)\n\t\treturn autorest.NewErrorWithError(err, asyncOperationName, \"Result\", future.Response(), \"Polling failure\")\n\t}\n\tif !done {\n\t\treturn azure.NewAsyncOpIncompleteError(asyncOperationName)\n\t}\n\n\treturn nil\n}","line":{"from":248,"to":267}} {"id":100033420,"name":"WaitForAsyncOperationResult","signature":"func (c *Client) WaitForAsyncOperationResult(ctx context.Context, future *azure.Future, asyncOperationName string) (*http.Response, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// WaitForAsyncOperationResult waits for an operation result.\nfunc (c *Client) WaitForAsyncOperationResult(ctx context.Context, future *azure.Future, asyncOperationName string) (*http.Response, error) {\n\terr := c.WaitForAsyncOperationCompletion(ctx, future, asyncOperationName)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in WaitForAsyncOperationCompletion: '%v'\", err)\n\t\treturn nil, err\n\t}\n\n\tsendBackoff := *c.backoff\n\tsender := autorest.DecorateSender(\n\t\tc.client,\n\t\tretry.DoExponentialBackoffRetry(\u0026sendBackoff),\n\t)\n\treturn future.GetResult(sender)\n}","line":{"from":269,"to":283}} {"id":100033421,"name":"SendAsync","signature":"func (c *Client) SendAsync(ctx context.Context, request *http.Request) (*azure.Future, *http.Response, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// SendAsync send a request and return a future object representing the async result as well as the origin http response\nfunc (c *Client) SendAsync(ctx context.Context, request *http.Request) (*azure.Future, *http.Response, *retry.Error) {\n\tasyncResponse, rerr := c.Send(ctx, request)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"sendAsync.send\", request.URL.String(), rerr.Error())\n\t\treturn nil, nil, rerr\n\t}\n\n\tfuture, err := azure.NewFutureFromResponse(asyncResponse)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"sendAsync.respond\", request.URL.String(), err)\n\t\treturn nil, asyncResponse, retry.GetError(asyncResponse, err)\n\t}\n\n\treturn \u0026future, asyncResponse, nil\n}","line":{"from":285,"to":300}} {"id":100033422,"name":"GetResource","signature":"func (c *Client) GetResource(ctx context.Context, resourceID, expand string) (*http.Response, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// GetResource get a resource by resource ID\nfunc (c *Client) GetResource(ctx context.Context, resourceID, expand string) (*http.Response, *retry.Error) {\n\tdecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithPathParameters(\"{resourceID}\", map[string]interface{}{\"resourceID\": resourceID}),\n\t}\n\tif expand != \"\" {\n\t\tqueryParameters := map[string]interface{}{\n\t\t\t\"$expand\": autorest.Encode(\"query\", expand),\n\t\t}\n\t\tdecorators = append(decorators, autorest.WithQueryParameters(queryParameters))\n\t}\n\trequest, err := c.PrepareGetRequest(ctx, decorators...)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"get.prepare\", resourceID, err)\n\t\treturn nil, retry.NewError(false, err)\n\t}\n\n\treturn c.Send(ctx, request)\n}","line":{"from":302,"to":320}} {"id":100033423,"name":"GetResourceWithDecorators","signature":"func (c *Client) GetResourceWithDecorators(ctx context.Context, resourceID string, decorators []autorest.PrepareDecorator) (*http.Response, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// GetResourceWithDecorators get a resource with decorators by resource ID\nfunc (c *Client) GetResourceWithDecorators(ctx context.Context, resourceID string, decorators []autorest.PrepareDecorator) (*http.Response, *retry.Error) {\n\tgetDecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithPathParameters(\"{resourceID}\", map[string]interface{}{\"resourceID\": resourceID}),\n\t}\n\tgetDecorators = append(getDecorators, decorators...)\n\trequest, err := c.PrepareGetRequest(ctx, getDecorators...)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"get.prepare\", resourceID, err)\n\t\treturn nil, retry.NewError(false, err)\n\t}\n\n\treturn c.Send(ctx, request)\n}","line":{"from":322,"to":335}} {"id":100033424,"name":"PutResource","signature":"func (c *Client) PutResource(ctx context.Context, resourceID string, parameters interface{}) (*http.Response, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// PutResource puts a resource by resource ID\nfunc (c *Client) PutResource(ctx context.Context, resourceID string, parameters interface{}) (*http.Response, *retry.Error) {\n\tputDecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithPathParameters(\"{resourceID}\", map[string]interface{}{\"resourceID\": resourceID}),\n\t\tautorest.WithJSON(parameters),\n\t}\n\treturn c.PutResourceWithDecorators(ctx, resourceID, parameters, putDecorators)\n}","line":{"from":337,"to":344}} {"id":100033425,"name":"PutResources","signature":"func (c *Client) PutResources(ctx context.Context, resources map[string]interface{}) map[string]*PutResourcesResponse","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// PutResources puts a list of resources from resources map[resourceID]parameters.\n// Those resources sync requests are sequential while async requests are concurrent. It's especially\n// useful when the ARM API doesn't support concurrent requests.\nfunc (c *Client) PutResources(ctx context.Context, resources map[string]interface{}) map[string]*PutResourcesResponse {\n\tif len(resources) == 0 {\n\t\treturn nil\n\t}\n\n\t// Sequential sync requests.\n\tfutures := make(map[string]*azure.Future)\n\tresponses := make(map[string]*PutResourcesResponse)\n\tfor resourceID, parameters := range resources {\n\t\tdecorators := []autorest.PrepareDecorator{\n\t\t\tautorest.WithPathParameters(\"{resourceID}\", map[string]interface{}{\"resourceID\": resourceID}),\n\t\t\tautorest.WithJSON(parameters),\n\t\t}\n\t\trequest, err := c.PreparePutRequest(ctx, decorators...)\n\t\tif err != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"put.prepare\", resourceID, err)\n\t\t\tresponses[resourceID] = \u0026PutResourcesResponse{\n\t\t\t\tError: retry.NewError(false, err),\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tfuture, resp, clientErr := c.SendAsync(ctx, request)\n\t\tdefer c.CloseResponse(ctx, resp)\n\t\tif clientErr != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"put.send\", resourceID, clientErr.Error())\n\t\t\tresponses[resourceID] = \u0026PutResourcesResponse{\n\t\t\t\tError: clientErr,\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tfutures[resourceID] = future\n\t}\n\n\t// Concurrent async requests.\n\twg := sync.WaitGroup{}\n\tvar responseLock sync.Mutex\n\tfor resourceID, future := range futures {\n\t\twg.Add(1)\n\t\tgo func(resourceID string, future *azure.Future) {\n\t\t\tdefer wg.Done()\n\t\t\tresponse, err := c.WaitForAsyncOperationResult(ctx, future, \"armclient.PutResource\")\n\t\t\tif err != nil {\n\t\t\t\tif response != nil {\n\t\t\t\t\tklog.V(5).Infof(\"Received error in WaitForAsyncOperationResult: '%s', response code %d\", err.Error(), response.StatusCode)\n\t\t\t\t} else {\n\t\t\t\t\tklog.V(5).Infof(\"Received error in WaitForAsyncOperationResult: '%s', no response\", err.Error())\n\t\t\t\t}\n\n\t\t\t\tretriableErr := retry.GetError(response, err)\n\t\t\t\tif !retriableErr.Retriable \u0026\u0026\n\t\t\t\t\tstrings.Contains(strings.ToUpper(err.Error()), strings.ToUpper(\"InternalServerError\")) {\n\t\t\t\t\tklog.V(5).Infof(\"Received InternalServerError in WaitForAsyncOperationResult: '%s', setting error retriable\", err.Error())\n\t\t\t\t\tretriableErr.Retriable = true\n\t\t\t\t}\n\n\t\t\t\tresponseLock.Lock()\n\t\t\t\tresponses[resourceID] = \u0026PutResourcesResponse{\n\t\t\t\t\tError: retriableErr,\n\t\t\t\t}\n\t\t\t\tresponseLock.Unlock()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tresponseLock.Lock()\n\t\t\tresponses[resourceID] = \u0026PutResourcesResponse{\n\t\t\t\tResponse: response,\n\t\t\t}\n\t\t\tresponseLock.Unlock()\n\t\t}(resourceID, future)\n\t}\n\n\twg.Wait()\n\treturn responses\n}","line":{"from":346,"to":424}} {"id":100033426,"name":"PutResourceWithDecorators","signature":"func (c *Client) PutResourceWithDecorators(ctx context.Context, resourceID string, parameters interface{}, decorators []autorest.PrepareDecorator) (*http.Response, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// PutResourceWithDecorators puts a resource by resource ID\nfunc (c *Client) PutResourceWithDecorators(ctx context.Context, resourceID string, parameters interface{}, decorators []autorest.PrepareDecorator) (*http.Response, *retry.Error) {\n\trequest, err := c.PreparePutRequest(ctx, decorators...)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"put.prepare\", resourceID, err)\n\t\treturn nil, retry.NewError(false, err)\n\t}\n\n\tfuture, resp, clientErr := c.SendAsync(ctx, request)\n\tdefer c.CloseResponse(ctx, resp)\n\tif clientErr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"put.send\", resourceID, clientErr.Error())\n\t\treturn nil, clientErr\n\t}\n\n\tresponse, err := c.WaitForAsyncOperationResult(ctx, future, \"armclient.PutResource\")\n\tif err != nil {\n\t\tif response != nil {\n\t\t\tklog.V(5).Infof(\"Received error in WaitForAsyncOperationResult: '%s', response code %d\", err.Error(), response.StatusCode)\n\t\t} else {\n\t\t\tklog.V(5).Infof(\"Received error in WaitForAsyncOperationResult: '%s', no response\", err.Error())\n\t\t}\n\n\t\tretriableErr := retry.GetError(response, err)\n\t\tif !retriableErr.Retriable \u0026\u0026\n\t\t\tstrings.Contains(strings.ToUpper(err.Error()), strings.ToUpper(\"InternalServerError\")) {\n\t\t\tklog.V(5).Infof(\"Received InternalServerError in WaitForAsyncOperationResult: '%s', setting error retriable\", err.Error())\n\t\t\tretriableErr.Retriable = true\n\t\t}\n\t\treturn nil, retriableErr\n\t}\n\n\treturn response, nil\n}","line":{"from":426,"to":459}} {"id":100033427,"name":"PatchResource","signature":"func (c *Client) PatchResource(ctx context.Context, resourceID string, parameters interface{}) (*http.Response, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// PatchResource patches a resource by resource ID\nfunc (c *Client) PatchResource(ctx context.Context, resourceID string, parameters interface{}) (*http.Response, *retry.Error) {\n\tdecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithPathParameters(\"{resourceID}\", map[string]interface{}{\"resourceID\": resourceID}),\n\t\tautorest.WithJSON(parameters),\n\t}\n\n\trequest, err := c.PreparePatchRequest(ctx, decorators...)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"patch.prepare\", resourceID, err)\n\t\treturn nil, retry.NewError(false, err)\n\t}\n\n\tfuture, resp, clientErr := c.SendAsync(ctx, request)\n\tdefer c.CloseResponse(ctx, resp)\n\tif clientErr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"patch.send\", resourceID, clientErr.Error())\n\t\treturn nil, clientErr\n\t}\n\n\tresponse, err := c.WaitForAsyncOperationResult(ctx, future, \"armclient.PatchResource\")\n\tif err != nil {\n\t\tif response != nil {\n\t\t\tklog.V(5).Infof(\"Received error in WaitForAsyncOperationResult: '%s', response code %d\", err.Error(), response.StatusCode)\n\t\t} else {\n\t\t\tklog.V(5).Infof(\"Received error in WaitForAsyncOperationResult: '%s', no response\", err.Error())\n\t\t}\n\n\t\tretriableErr := retry.GetError(response, err)\n\t\tif !retriableErr.Retriable \u0026\u0026\n\t\t\tstrings.Contains(strings.ToUpper(err.Error()), strings.ToUpper(\"InternalServerError\")) {\n\t\t\tklog.V(5).Infof(\"Received InternalServerError in WaitForAsyncOperationResult: '%s', setting error retriable\", err.Error())\n\t\t\tretriableErr.Retriable = true\n\t\t}\n\t\treturn nil, retriableErr\n\t}\n\n\treturn response, nil\n}","line":{"from":461,"to":499}} {"id":100033428,"name":"PutResourceAsync","signature":"func (c *Client) PutResourceAsync(ctx context.Context, resourceID string, parameters interface{}) (*azure.Future, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// PutResourceAsync puts a resource by resource ID in async mode\nfunc (c *Client) PutResourceAsync(ctx context.Context, resourceID string, parameters interface{}) (*azure.Future, *retry.Error) {\n\tdecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithPathParameters(\"{resourceID}\", map[string]interface{}{\"resourceID\": resourceID}),\n\t\tautorest.WithJSON(parameters),\n\t}\n\n\trequest, err := c.PreparePutRequest(ctx, decorators...)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"put.prepare\", resourceID, err)\n\t\treturn nil, retry.NewError(false, err)\n\t}\n\n\tfuture, resp, rErr := c.SendAsync(ctx, request)\n\tdefer c.CloseResponse(ctx, resp)\n\tif rErr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"put.send\", resourceID, err)\n\t\treturn nil, rErr\n\t}\n\n\treturn future, nil\n}","line":{"from":501,"to":522}} {"id":100033429,"name":"PostResource","signature":"func (c *Client) PostResource(ctx context.Context, resourceID, action string, parameters interface{}) (*http.Response, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// PostResource posts a resource by resource ID\nfunc (c *Client) PostResource(ctx context.Context, resourceID, action string, parameters interface{}) (*http.Response, *retry.Error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"resourceID\": resourceID,\n\t\t\"action\": action,\n\t}\n\n\tdecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithPathParameters(\"{resourceID}/{action}\", pathParameters),\n\t\tautorest.WithJSON(parameters),\n\t}\n\trequest, err := c.PreparePostRequest(ctx, decorators...)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"post.prepare\", resourceID, err)\n\t\treturn nil, retry.NewError(false, err)\n\t}\n\n\treturn c.sendRequest(ctx, request)\n}","line":{"from":524,"to":542}} {"id":100033430,"name":"DeleteResource","signature":"func (c *Client) DeleteResource(ctx context.Context, resourceID, ifMatch string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// DeleteResource deletes a resource by resource ID\nfunc (c *Client) DeleteResource(ctx context.Context, resourceID, ifMatch string) *retry.Error {\n\tfuture, clientErr := c.DeleteResourceAsync(ctx, resourceID, ifMatch)\n\tif clientErr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"delete.request\", resourceID, clientErr.Error())\n\t\treturn clientErr\n\t}\n\n\tif future == nil {\n\t\treturn nil\n\t}\n\n\tif err := c.WaitForAsyncOperationCompletion(ctx, future, \"armclient.DeleteResource\"); err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"delete.wait\", resourceID, clientErr.Error())\n\t\treturn retry.NewError(true, err)\n\t}\n\n\treturn nil\n}","line":{"from":544,"to":562}} {"id":100033431,"name":"HeadResource","signature":"func (c *Client) HeadResource(ctx context.Context, resourceID string) (*http.Response, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// HeadResource heads a resource by resource ID\nfunc (c *Client) HeadResource(ctx context.Context, resourceID string) (*http.Response, *retry.Error) {\n\tdecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithPathParameters(\"{resourceID}\", map[string]interface{}{\"resourceID\": resourceID}),\n\t}\n\trequest, err := c.PrepareHeadRequest(ctx, decorators...)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"head.prepare\", resourceID, err)\n\t\treturn nil, retry.NewError(false, err)\n\t}\n\n\treturn c.sendRequest(ctx, request)\n}","line":{"from":564,"to":576}} {"id":100033432,"name":"DeleteResourceAsync","signature":"func (c *Client) DeleteResourceAsync(ctx context.Context, resourceID, ifMatch string) (*azure.Future, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// DeleteResourceAsync delete a resource by resource ID and returns a future representing the async result\nfunc (c *Client) DeleteResourceAsync(ctx context.Context, resourceID, ifMatch string) (*azure.Future, *retry.Error) {\n\tdecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithPathParameters(\"{resourceID}\", map[string]interface{}{\"resourceID\": resourceID}),\n\t}\n\tif len(ifMatch) \u003e 0 {\n\t\tdecorators = append(decorators, autorest.WithHeader(\"If-Match\", autorest.String(ifMatch)))\n\t}\n\n\tdeleteRequest, err := c.PrepareDeleteRequest(ctx, decorators...)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"deleteAsync.prepare\", resourceID, err)\n\t\treturn nil, retry.NewError(false, err)\n\t}\n\n\tresp, rerr := c.sendRequest(ctx, deleteRequest)\n\tdefer c.CloseResponse(ctx, resp)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"deleteAsync.send\", resourceID, rerr.Error())\n\t\treturn nil, rerr\n\t}\n\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent, http.StatusNotFound))\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"deleteAsync.respond\", resourceID, err)\n\t\treturn nil, retry.GetError(resp, err)\n\t}\n\n\tif resp.StatusCode == http.StatusNotFound {\n\t\treturn nil, nil\n\t}\n\n\tfuture, err := azure.NewFutureFromResponse(resp)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"deleteAsync.future\", resourceID, err)\n\t\treturn nil, retry.GetError(resp, err)\n\t}\n\n\treturn \u0026future, nil\n}","line":{"from":578,"to":619}} {"id":100033433,"name":"CloseResponse","signature":"func (c *Client) CloseResponse(ctx context.Context, response *http.Response)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// CloseResponse closes a response\nfunc (c *Client) CloseResponse(ctx context.Context, response *http.Response) {\n\tif response != nil \u0026\u0026 response.Body != nil {\n\t\tif err := response.Body.Close(); err != nil {\n\t\t\tklog.Errorf(\"Error closing the response body: %v\", err)\n\t\t}\n\t}\n}","line":{"from":621,"to":628}} {"id":100033434,"name":"prepareRequest","signature":"func (c *Client) prepareRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"func (c *Client) prepareRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) {\n\tdecorators = append(\n\t\tdecorators,\n\t\twithAPIVersion(c.apiVersion))\n\tpreparer := autorest.CreatePreparer(decorators...)\n\treturn preparer.Prepare((\u0026http.Request{}).WithContext(ctx))\n}","line":{"from":630,"to":636}} {"id":100033435,"name":"withAPIVersion","signature":"func withAPIVersion(apiVersion string) autorest.PrepareDecorator","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"func withAPIVersion(apiVersion string) autorest.PrepareDecorator {\n\tconst apiVersionKey = \"api-version\"\n\treturn func(p autorest.Preparer) autorest.Preparer {\n\t\treturn autorest.PreparerFunc(func(r *http.Request) (*http.Request, error) {\n\t\t\tr, err := p.Prepare(r)\n\t\t\tif err == nil {\n\t\t\t\tif r.URL == nil {\n\t\t\t\t\treturn r, fmt.Errorf(\"Error in withAPIVersion: Invoked with a nil URL\")\n\t\t\t\t}\n\n\t\t\t\tv := r.URL.Query()\n\t\t\t\tif len(v.Get(apiVersionKey)) \u003e 0 {\n\t\t\t\t\treturn r, nil\n\t\t\t\t}\n\n\t\t\t\tv.Add(apiVersionKey, apiVersion)\n\t\t\t\tr.URL.RawQuery = v.Encode()\n\t\t\t}\n\t\t\treturn r, err\n\t\t})\n\t}\n}","line":{"from":638,"to":659}} {"id":100033436,"name":"GetResourceID","signature":"func GetResourceID(subscriptionID, resourceGroupName, resourceType, resourceName string) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// GetResourceID gets Azure resource ID\nfunc GetResourceID(subscriptionID, resourceGroupName, resourceType, resourceName string) string {\n\treturn fmt.Sprintf(\"/subscriptions/%s/resourceGroups/%s/providers/%s/%s\",\n\t\tautorest.Encode(\"path\", subscriptionID),\n\t\tautorest.Encode(\"path\", resourceGroupName),\n\t\tresourceType,\n\t\tautorest.Encode(\"path\", resourceName))\n}","line":{"from":661,"to":668}} {"id":100033437,"name":"GetChildResourceID","signature":"func GetChildResourceID(subscriptionID, resourceGroupName, resourceType, resourceName, childResourceType, childResourceName string) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// GetChildResourceID gets Azure child resource ID\nfunc GetChildResourceID(subscriptionID, resourceGroupName, resourceType, resourceName, childResourceType, childResourceName string) string {\n\treturn fmt.Sprintf(\"/subscriptions/%s/resourceGroups/%s/providers/%s/%s/%s/%s\",\n\t\tautorest.Encode(\"path\", subscriptionID),\n\t\tautorest.Encode(\"path\", resourceGroupName),\n\t\tresourceType,\n\t\tautorest.Encode(\"path\", resourceName),\n\t\tchildResourceType,\n\t\tautorest.Encode(\"path\", childResourceName))\n}","line":{"from":670,"to":679}} {"id":100033438,"name":"GetChildResourcesListID","signature":"func GetChildResourcesListID(subscriptionID, resourceGroupName, resourceType, resourceName, childResourceType string) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// GetChildResourcesListID gets Azure child resources list ID\nfunc GetChildResourcesListID(subscriptionID, resourceGroupName, resourceType, resourceName, childResourceType string) string {\n\treturn fmt.Sprintf(\"/subscriptions/%s/resourceGroups/%s/providers/%s/%s/%s\",\n\t\tautorest.Encode(\"path\", subscriptionID),\n\t\tautorest.Encode(\"path\", resourceGroupName),\n\t\tresourceType,\n\t\tautorest.Encode(\"path\", resourceName),\n\t\tchildResourceType)\n}","line":{"from":681,"to":689}} {"id":100033439,"name":"GetProviderResourceID","signature":"func GetProviderResourceID(subscriptionID, providerNamespace string) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// GetProviderResourceID gets Azure RP resource ID\nfunc GetProviderResourceID(subscriptionID, providerNamespace string) string {\n\treturn fmt.Sprintf(\"/subscriptions/%s/providers/%s\",\n\t\tautorest.Encode(\"path\", subscriptionID),\n\t\tproviderNamespace)\n}","line":{"from":691,"to":696}} {"id":100033440,"name":"GetProviderResourcesListID","signature":"func GetProviderResourcesListID(subscriptionID string) string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/azure_armclient.go","code":"// GetProviderResourcesListID gets Azure RP resources list ID\nfunc GetProviderResourcesListID(subscriptionID string) string {\n\treturn fmt.Sprintf(\"/subscriptions/%s/providers\", autorest.Encode(\"path\", subscriptionID))\n}","line":{"from":698,"to":701}} {"id":100033441,"name":"NewMockInterface","signature":"func NewMockInterface(ctrl *gomock.Controller) *MockInterface","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// NewMockInterface creates a new mock instance.\nfunc NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := \u0026MockInterface{ctrl: ctrl}\n\tmock.recorder = \u0026MockInterfaceMockRecorder{mock}\n\treturn mock\n}","line":{"from":49,"to":54}} {"id":100033442,"name":"EXPECT","signature":"func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// EXPECT returns an object that allows the caller to indicate expected use.\nfunc (m *MockInterface) EXPECT() *MockInterfaceMockRecorder {\n\treturn m.recorder\n}","line":{"from":56,"to":59}} {"id":100033443,"name":"CloseResponse","signature":"func (m *MockInterface) CloseResponse(ctx context.Context, response *http.Response)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// CloseResponse mocks base method.\nfunc (m *MockInterface) CloseResponse(ctx context.Context, response *http.Response) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"CloseResponse\", ctx, response)\n}","line":{"from":61,"to":65}} {"id":100033444,"name":"CloseResponse","signature":"func (mr *MockInterfaceMockRecorder) CloseResponse(ctx, response interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// CloseResponse indicates an expected call of CloseResponse.\nfunc (mr *MockInterfaceMockRecorder) CloseResponse(ctx, response interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CloseResponse\", reflect.TypeOf((*MockInterface)(nil).CloseResponse), ctx, response)\n}","line":{"from":67,"to":71}} {"id":100033445,"name":"DeleteResource","signature":"func (m *MockInterface) DeleteResource(ctx context.Context, resourceID, ifMatch string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// DeleteResource mocks base method.\nfunc (m *MockInterface) DeleteResource(ctx context.Context, resourceID, ifMatch string) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteResource\", ctx, resourceID, ifMatch)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":73,"to":79}} {"id":100033446,"name":"DeleteResource","signature":"func (mr *MockInterfaceMockRecorder) DeleteResource(ctx, resourceID, ifMatch interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// DeleteResource indicates an expected call of DeleteResource.\nfunc (mr *MockInterfaceMockRecorder) DeleteResource(ctx, resourceID, ifMatch interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteResource\", reflect.TypeOf((*MockInterface)(nil).DeleteResource), ctx, resourceID, ifMatch)\n}","line":{"from":81,"to":85}} {"id":100033447,"name":"DeleteResourceAsync","signature":"func (m *MockInterface) DeleteResourceAsync(ctx context.Context, resourceID, ifMatch string) (*azure.Future, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// DeleteResourceAsync mocks base method.\nfunc (m *MockInterface) DeleteResourceAsync(ctx context.Context, resourceID, ifMatch string) (*azure.Future, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteResourceAsync\", ctx, resourceID, ifMatch)\n\tret0, _ := ret[0].(*azure.Future)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":87,"to":94}} {"id":100033448,"name":"DeleteResourceAsync","signature":"func (mr *MockInterfaceMockRecorder) DeleteResourceAsync(ctx, resourceID, ifMatch interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// DeleteResourceAsync indicates an expected call of DeleteResourceAsync.\nfunc (mr *MockInterfaceMockRecorder) DeleteResourceAsync(ctx, resourceID, ifMatch interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteResourceAsync\", reflect.TypeOf((*MockInterface)(nil).DeleteResourceAsync), ctx, resourceID, ifMatch)\n}","line":{"from":96,"to":100}} {"id":100033449,"name":"GetResource","signature":"func (m *MockInterface) GetResource(ctx context.Context, resourceID, expand string) (*http.Response, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// GetResource mocks base method.\nfunc (m *MockInterface) GetResource(ctx context.Context, resourceID, expand string) (*http.Response, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetResource\", ctx, resourceID, expand)\n\tret0, _ := ret[0].(*http.Response)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":102,"to":109}} {"id":100033450,"name":"GetResource","signature":"func (mr *MockInterfaceMockRecorder) GetResource(ctx, resourceID, expand interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// GetResource indicates an expected call of GetResource.\nfunc (mr *MockInterfaceMockRecorder) GetResource(ctx, resourceID, expand interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetResource\", reflect.TypeOf((*MockInterface)(nil).GetResource), ctx, resourceID, expand)\n}","line":{"from":111,"to":115}} {"id":100033451,"name":"GetResourceWithDecorators","signature":"func (m *MockInterface) GetResourceWithDecorators(ctx context.Context, resourceID string, decorators []autorest.PrepareDecorator) (*http.Response, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// GetResourceWithDecorators mocks base method.\nfunc (m *MockInterface) GetResourceWithDecorators(ctx context.Context, resourceID string, decorators []autorest.PrepareDecorator) (*http.Response, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetResourceWithDecorators\", ctx, resourceID, decorators)\n\tret0, _ := ret[0].(*http.Response)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":117,"to":124}} {"id":100033452,"name":"GetResourceWithDecorators","signature":"func (mr *MockInterfaceMockRecorder) GetResourceWithDecorators(ctx, resourceID, decorators interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// GetResourceWithDecorators indicates an expected call of GetResourceWithDecorators.\nfunc (mr *MockInterfaceMockRecorder) GetResourceWithDecorators(ctx, resourceID, decorators interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetResourceWithDecorators\", reflect.TypeOf((*MockInterface)(nil).GetResourceWithDecorators), ctx, resourceID, decorators)\n}","line":{"from":126,"to":130}} {"id":100033453,"name":"HeadResource","signature":"func (m *MockInterface) HeadResource(ctx context.Context, resourceID string) (*http.Response, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// HeadResource mocks base method.\nfunc (m *MockInterface) HeadResource(ctx context.Context, resourceID string) (*http.Response, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"HeadResource\", ctx, resourceID)\n\tret0, _ := ret[0].(*http.Response)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":132,"to":139}} {"id":100033454,"name":"HeadResource","signature":"func (mr *MockInterfaceMockRecorder) HeadResource(ctx, resourceID interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// HeadResource indicates an expected call of HeadResource.\nfunc (mr *MockInterfaceMockRecorder) HeadResource(ctx, resourceID interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"HeadResource\", reflect.TypeOf((*MockInterface)(nil).HeadResource), ctx, resourceID)\n}","line":{"from":141,"to":145}} {"id":100033455,"name":"PatchResource","signature":"func (m *MockInterface) PatchResource(ctx context.Context, resourceID string, parameters interface{}) (*http.Response, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// PatchResource mocks base method.\nfunc (m *MockInterface) PatchResource(ctx context.Context, resourceID string, parameters interface{}) (*http.Response, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PatchResource\", ctx, resourceID, parameters)\n\tret0, _ := ret[0].(*http.Response)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":147,"to":154}} {"id":100033456,"name":"PatchResource","signature":"func (mr *MockInterfaceMockRecorder) PatchResource(ctx, resourceID, parameters interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// PatchResource indicates an expected call of PatchResource.\nfunc (mr *MockInterfaceMockRecorder) PatchResource(ctx, resourceID, parameters interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"PatchResource\", reflect.TypeOf((*MockInterface)(nil).PatchResource), ctx, resourceID, parameters)\n}","line":{"from":156,"to":160}} {"id":100033457,"name":"PostResource","signature":"func (m *MockInterface) PostResource(ctx context.Context, resourceID, action string, parameters interface{}) (*http.Response, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// PostResource mocks base method.\nfunc (m *MockInterface) PostResource(ctx context.Context, resourceID, action string, parameters interface{}) (*http.Response, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PostResource\", ctx, resourceID, action, parameters)\n\tret0, _ := ret[0].(*http.Response)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":162,"to":169}} {"id":100033458,"name":"PostResource","signature":"func (mr *MockInterfaceMockRecorder) PostResource(ctx, resourceID, action, parameters interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// PostResource indicates an expected call of PostResource.\nfunc (mr *MockInterfaceMockRecorder) PostResource(ctx, resourceID, action, parameters interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"PostResource\", reflect.TypeOf((*MockInterface)(nil).PostResource), ctx, resourceID, action, parameters)\n}","line":{"from":171,"to":175}} {"id":100033459,"name":"PrepareDeleteRequest","signature":"func (m *MockInterface) PrepareDeleteRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// PrepareDeleteRequest mocks base method.\nfunc (m *MockInterface) PrepareDeleteRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx}\n\tfor _, a := range decorators {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"PrepareDeleteRequest\", varargs...)\n\tret0, _ := ret[0].(*http.Request)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}","line":{"from":177,"to":188}} {"id":100033460,"name":"PrepareDeleteRequest","signature":"func (mr *MockInterfaceMockRecorder) PrepareDeleteRequest(ctx interface{}, decorators ...interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// PrepareDeleteRequest indicates an expected call of PrepareDeleteRequest.\nfunc (mr *MockInterfaceMockRecorder) PrepareDeleteRequest(ctx interface{}, decorators ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{ctx}, decorators...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"PrepareDeleteRequest\", reflect.TypeOf((*MockInterface)(nil).PrepareDeleteRequest), varargs...)\n}","line":{"from":190,"to":195}} {"id":100033461,"name":"PrepareGetRequest","signature":"func (m *MockInterface) PrepareGetRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// PrepareGetRequest mocks base method.\nfunc (m *MockInterface) PrepareGetRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx}\n\tfor _, a := range decorators {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"PrepareGetRequest\", varargs...)\n\tret0, _ := ret[0].(*http.Request)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}","line":{"from":197,"to":208}} {"id":100033462,"name":"PrepareGetRequest","signature":"func (mr *MockInterfaceMockRecorder) PrepareGetRequest(ctx interface{}, decorators ...interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// PrepareGetRequest indicates an expected call of PrepareGetRequest.\nfunc (mr *MockInterfaceMockRecorder) PrepareGetRequest(ctx interface{}, decorators ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{ctx}, decorators...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"PrepareGetRequest\", reflect.TypeOf((*MockInterface)(nil).PrepareGetRequest), varargs...)\n}","line":{"from":210,"to":215}} {"id":100033463,"name":"PrepareHeadRequest","signature":"func (m *MockInterface) PrepareHeadRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// PrepareHeadRequest mocks base method.\nfunc (m *MockInterface) PrepareHeadRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx}\n\tfor _, a := range decorators {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"PrepareHeadRequest\", varargs...)\n\tret0, _ := ret[0].(*http.Request)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}","line":{"from":217,"to":228}} {"id":100033464,"name":"PrepareHeadRequest","signature":"func (mr *MockInterfaceMockRecorder) PrepareHeadRequest(ctx interface{}, decorators ...interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// PrepareHeadRequest indicates an expected call of PrepareHeadRequest.\nfunc (mr *MockInterfaceMockRecorder) PrepareHeadRequest(ctx interface{}, decorators ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{ctx}, decorators...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"PrepareHeadRequest\", reflect.TypeOf((*MockInterface)(nil).PrepareHeadRequest), varargs...)\n}","line":{"from":230,"to":235}} {"id":100033465,"name":"PreparePostRequest","signature":"func (m *MockInterface) PreparePostRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// PreparePostRequest mocks base method.\nfunc (m *MockInterface) PreparePostRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx}\n\tfor _, a := range decorators {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"PreparePostRequest\", varargs...)\n\tret0, _ := ret[0].(*http.Request)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}","line":{"from":237,"to":248}} {"id":100033466,"name":"PreparePostRequest","signature":"func (mr *MockInterfaceMockRecorder) PreparePostRequest(ctx interface{}, decorators ...interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// PreparePostRequest indicates an expected call of PreparePostRequest.\nfunc (mr *MockInterfaceMockRecorder) PreparePostRequest(ctx interface{}, decorators ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{ctx}, decorators...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"PreparePostRequest\", reflect.TypeOf((*MockInterface)(nil).PreparePostRequest), varargs...)\n}","line":{"from":250,"to":255}} {"id":100033467,"name":"PreparePutRequest","signature":"func (m *MockInterface) PreparePutRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// PreparePutRequest mocks base method.\nfunc (m *MockInterface) PreparePutRequest(ctx context.Context, decorators ...autorest.PrepareDecorator) (*http.Request, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx}\n\tfor _, a := range decorators {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"PreparePutRequest\", varargs...)\n\tret0, _ := ret[0].(*http.Request)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}","line":{"from":257,"to":268}} {"id":100033468,"name":"PreparePutRequest","signature":"func (mr *MockInterfaceMockRecorder) PreparePutRequest(ctx interface{}, decorators ...interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// PreparePutRequest indicates an expected call of PreparePutRequest.\nfunc (mr *MockInterfaceMockRecorder) PreparePutRequest(ctx interface{}, decorators ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{ctx}, decorators...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"PreparePutRequest\", reflect.TypeOf((*MockInterface)(nil).PreparePutRequest), varargs...)\n}","line":{"from":270,"to":275}} {"id":100033469,"name":"PutResource","signature":"func (m *MockInterface) PutResource(ctx context.Context, resourceID string, parameters interface{}) (*http.Response, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// PutResource mocks base method.\nfunc (m *MockInterface) PutResource(ctx context.Context, resourceID string, parameters interface{}) (*http.Response, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PutResource\", ctx, resourceID, parameters)\n\tret0, _ := ret[0].(*http.Response)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":277,"to":284}} {"id":100033470,"name":"PutResource","signature":"func (mr *MockInterfaceMockRecorder) PutResource(ctx, resourceID, parameters interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// PutResource indicates an expected call of PutResource.\nfunc (mr *MockInterfaceMockRecorder) PutResource(ctx, resourceID, parameters interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"PutResource\", reflect.TypeOf((*MockInterface)(nil).PutResource), ctx, resourceID, parameters)\n}","line":{"from":286,"to":290}} {"id":100033471,"name":"PutResourceAsync","signature":"func (m *MockInterface) PutResourceAsync(ctx context.Context, resourceID string, parameters interface{}) (*azure.Future, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// PutResourceAsync mocks base method.\nfunc (m *MockInterface) PutResourceAsync(ctx context.Context, resourceID string, parameters interface{}) (*azure.Future, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PutResourceAsync\", ctx, resourceID, parameters)\n\tret0, _ := ret[0].(*azure.Future)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":292,"to":299}} {"id":100033472,"name":"PutResourceAsync","signature":"func (mr *MockInterfaceMockRecorder) PutResourceAsync(ctx, resourceID, parameters interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// PutResourceAsync indicates an expected call of PutResourceAsync.\nfunc (mr *MockInterfaceMockRecorder) PutResourceAsync(ctx, resourceID, parameters interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"PutResourceAsync\", reflect.TypeOf((*MockInterface)(nil).PutResourceAsync), ctx, resourceID, parameters)\n}","line":{"from":301,"to":305}} {"id":100033473,"name":"PutResourceWithDecorators","signature":"func (m *MockInterface) PutResourceWithDecorators(ctx context.Context, resourceID string, parameters interface{}, decorators []autorest.PrepareDecorator) (*http.Response, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// PutResourceWithDecorators mocks base method.\nfunc (m *MockInterface) PutResourceWithDecorators(ctx context.Context, resourceID string, parameters interface{}, decorators []autorest.PrepareDecorator) (*http.Response, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PutResourceWithDecorators\", ctx, resourceID, parameters, decorators)\n\tret0, _ := ret[0].(*http.Response)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":307,"to":314}} {"id":100033474,"name":"PutResourceWithDecorators","signature":"func (mr *MockInterfaceMockRecorder) PutResourceWithDecorators(ctx, resourceID, parameters, decorators interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// PutResourceWithDecorators indicates an expected call of PutResourceWithDecorators.\nfunc (mr *MockInterfaceMockRecorder) PutResourceWithDecorators(ctx, resourceID, parameters, decorators interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"PutResourceWithDecorators\", reflect.TypeOf((*MockInterface)(nil).PutResourceWithDecorators), ctx, resourceID, parameters, decorators)\n}","line":{"from":316,"to":320}} {"id":100033475,"name":"PutResources","signature":"func (m *MockInterface) PutResources(ctx context.Context, resources map[string]interface{}) map[string]*armclient.PutResourcesResponse","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// PutResources mocks base method.\nfunc (m *MockInterface) PutResources(ctx context.Context, resources map[string]interface{}) map[string]*armclient.PutResourcesResponse {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PutResources\", ctx, resources)\n\tret0, _ := ret[0].(map[string]*armclient.PutResourcesResponse)\n\treturn ret0\n}","line":{"from":322,"to":328}} {"id":100033476,"name":"PutResources","signature":"func (mr *MockInterfaceMockRecorder) PutResources(ctx, resources interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// PutResources indicates an expected call of PutResources.\nfunc (mr *MockInterfaceMockRecorder) PutResources(ctx, resources interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"PutResources\", reflect.TypeOf((*MockInterface)(nil).PutResources), ctx, resources)\n}","line":{"from":330,"to":334}} {"id":100033477,"name":"Send","signature":"func (m *MockInterface) Send(ctx context.Context, request *http.Request) (*http.Response, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// Send mocks base method.\nfunc (m *MockInterface) Send(ctx context.Context, request *http.Request) (*http.Response, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Send\", ctx, request)\n\tret0, _ := ret[0].(*http.Response)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":336,"to":343}} {"id":100033478,"name":"Send","signature":"func (mr *MockInterfaceMockRecorder) Send(ctx, request interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// Send indicates an expected call of Send.\nfunc (mr *MockInterfaceMockRecorder) Send(ctx, request interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Send\", reflect.TypeOf((*MockInterface)(nil).Send), ctx, request)\n}","line":{"from":345,"to":349}} {"id":100033479,"name":"SendAsync","signature":"func (m *MockInterface) SendAsync(ctx context.Context, request *http.Request) (*azure.Future, *http.Response, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// SendAsync mocks base method.\nfunc (m *MockInterface) SendAsync(ctx context.Context, request *http.Request) (*azure.Future, *http.Response, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SendAsync\", ctx, request)\n\tret0, _ := ret[0].(*azure.Future)\n\tret1, _ := ret[1].(*http.Response)\n\tret2, _ := ret[2].(*retry.Error)\n\treturn ret0, ret1, ret2\n}","line":{"from":351,"to":359}} {"id":100033480,"name":"SendAsync","signature":"func (mr *MockInterfaceMockRecorder) SendAsync(ctx, request interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// SendAsync indicates an expected call of SendAsync.\nfunc (mr *MockInterfaceMockRecorder) SendAsync(ctx, request interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SendAsync\", reflect.TypeOf((*MockInterface)(nil).SendAsync), ctx, request)\n}","line":{"from":361,"to":365}} {"id":100033481,"name":"WaitForAsyncOperationCompletion","signature":"func (m *MockInterface) WaitForAsyncOperationCompletion(ctx context.Context, future *azure.Future, asyncOperationName string) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// WaitForAsyncOperationCompletion mocks base method.\nfunc (m *MockInterface) WaitForAsyncOperationCompletion(ctx context.Context, future *azure.Future, asyncOperationName string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"WaitForAsyncOperationCompletion\", ctx, future, asyncOperationName)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}","line":{"from":367,"to":373}} {"id":100033482,"name":"WaitForAsyncOperationCompletion","signature":"func (mr *MockInterfaceMockRecorder) WaitForAsyncOperationCompletion(ctx, future, asyncOperationName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// WaitForAsyncOperationCompletion indicates an expected call of WaitForAsyncOperationCompletion.\nfunc (mr *MockInterfaceMockRecorder) WaitForAsyncOperationCompletion(ctx, future, asyncOperationName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"WaitForAsyncOperationCompletion\", reflect.TypeOf((*MockInterface)(nil).WaitForAsyncOperationCompletion), ctx, future, asyncOperationName)\n}","line":{"from":375,"to":379}} {"id":100033483,"name":"WaitForAsyncOperationResult","signature":"func (m *MockInterface) WaitForAsyncOperationResult(ctx context.Context, future *azure.Future, asyncOperationName string) (*http.Response, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// WaitForAsyncOperationResult mocks base method.\nfunc (m *MockInterface) WaitForAsyncOperationResult(ctx context.Context, future *azure.Future, asyncOperationName string) (*http.Response, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"WaitForAsyncOperationResult\", ctx, future, asyncOperationName)\n\tret0, _ := ret[0].(*http.Response)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}","line":{"from":381,"to":388}} {"id":100033484,"name":"WaitForAsyncOperationResult","signature":"func (mr *MockInterfaceMockRecorder) WaitForAsyncOperationResult(ctx, future, asyncOperationName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient/interface.go","code":"// WaitForAsyncOperationResult indicates an expected call of WaitForAsyncOperationResult.\nfunc (mr *MockInterfaceMockRecorder) WaitForAsyncOperationResult(ctx, future, asyncOperationName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"WaitForAsyncOperationResult\", reflect.TypeOf((*MockInterface)(nil).WaitForAsyncOperationResult), ctx, future, asyncOperationName)\n}","line":{"from":390,"to":394}} {"id":100033485,"name":"WithRateLimiter","signature":"func (cfg *ClientConfig) WithRateLimiter(rl *RateLimitConfig) *ClientConfig","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/azure_client_config.go","code":"// WithRateLimiter returns a new ClientConfig with rateLimitConfig set.\nfunc (cfg *ClientConfig) WithRateLimiter(rl *RateLimitConfig) *ClientConfig {\n\tnewClientConfig := *cfg\n\tnewClientConfig.RateLimitConfig = rl\n\treturn \u0026newClientConfig\n}","line":{"from":40,"to":45}} {"id":100033486,"name":"RateLimitEnabled","signature":"func RateLimitEnabled(config *RateLimitConfig) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/azure_client_config.go","code":"// RateLimitEnabled returns true if CloudProviderRateLimit is set to true.\nfunc RateLimitEnabled(config *RateLimitConfig) bool {\n\treturn config != nil \u0026\u0026 config.CloudProviderRateLimit\n}","line":{"from":61,"to":64}} {"id":100033487,"name":"NewRateLimiter","signature":"func NewRateLimiter(config *RateLimitConfig) (flowcontrol.RateLimiter, flowcontrol.RateLimiter)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/azure_client_config.go","code":"// NewRateLimiter creates new read and write flowcontrol.RateLimiter from RateLimitConfig.\nfunc NewRateLimiter(config *RateLimitConfig) (flowcontrol.RateLimiter, flowcontrol.RateLimiter) {\n\treadLimiter := flowcontrol.NewFakeAlwaysRateLimiter()\n\twriteLimiter := flowcontrol.NewFakeAlwaysRateLimiter()\n\n\tif config != nil \u0026\u0026 config.CloudProviderRateLimit {\n\t\treadLimiter = flowcontrol.NewTokenBucketRateLimiter(\n\t\t\tconfig.CloudProviderRateLimitQPS,\n\t\t\tconfig.CloudProviderRateLimitBucket)\n\n\t\twriteLimiter = flowcontrol.NewTokenBucketRateLimiter(\n\t\t\tconfig.CloudProviderRateLimitQPSWrite,\n\t\t\tconfig.CloudProviderRateLimitBucketWrite)\n\t}\n\n\treturn readLimiter, writeLimiter\n}","line":{"from":66,"to":82}} {"id":100033488,"name":"New","signature":"func New(config *azclients.ClientConfig) *Client","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/azure_containerserviceclient.go","code":"// New creates a new ContainerServiceClient client with ratelimiting.\nfunc New(config *azclients.ClientConfig) *Client {\n\tbaseURI := config.ResourceManagerEndpoint\n\tauthorizer := config.Authorizer\n\tarmClient := armclient.New(authorizer, baseURI, config.UserAgent, APIVersion, config.Location, config.Backoff)\n\trateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig)\n\n\tklog.V(2).Infof(\"Azure ContainerServiceClient (read ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPS,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucket)\n\tklog.V(2).Infof(\"Azure ContainerServiceClient (write ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPSWrite,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucketWrite)\n\n\tclient := \u0026Client{\n\t\tarmClient: armClient,\n\t\trateLimiterReader: rateLimiterReader,\n\t\trateLimiterWriter: rateLimiterWriter,\n\t\tsubscriptionID: config.SubscriptionID,\n\t}\n\n\treturn client\n}","line":{"from":57,"to":79}} {"id":100033489,"name":"Get","signature":"func (c *Client) Get(ctx context.Context, resourceGroupName string, managedClusterName string) (containerservice.ManagedCluster, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/azure_containerserviceclient.go","code":"// Get gets a ManagedCluster.\nfunc (c *Client) Get(ctx context.Context, resourceGroupName string, managedClusterName string) (containerservice.ManagedCluster, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"managed_clusters\", \"get\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn containerservice.ManagedCluster{}, retry.GetRateLimitError(false, \"GetManagedCluster\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"GetManagedCluster\", \"client throttled\", c.RetryAfterReader)\n\t\treturn containerservice.ManagedCluster{}, rerr\n\t}\n\n\tresult, rerr := c.getManagedCluster(ctx, resourceGroupName, managedClusterName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":81,"to":110}} {"id":100033490,"name":"getManagedCluster","signature":"func (c *Client) getManagedCluster(ctx context.Context, resourceGroupName string, managedClusterName string) (containerservice.ManagedCluster, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/azure_containerserviceclient.go","code":"// getManagedCluster gets a ManagedCluster.\nfunc (c *Client) getManagedCluster(ctx context.Context, resourceGroupName string, managedClusterName string) (containerservice.ManagedCluster, *retry.Error) {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.ContainerService/managedClusters\",\n\t\tmanagedClusterName,\n\t)\n\tresult := containerservice.ManagedCluster{}\n\n\tresponse, rerr := c.armClient.GetResource(ctx, resourceID, \"\")\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"managedcluster.get.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\terr := autorest.Respond(\n\t\tresponse,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"managedcluster.get.respond\", resourceID, err)\n\t\treturn result, retry.GetError(response, err)\n\t}\n\n\tresult.Response = autorest.Response{Response: response}\n\treturn result, nil\n}","line":{"from":112,"to":140}} {"id":100033491,"name":"List","signature":"func (c *Client) List(ctx context.Context, resourceGroupName string) ([]containerservice.ManagedCluster, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/azure_containerserviceclient.go","code":"// List gets a list of ManagedClusters in the resource group.\nfunc (c *Client) List(ctx context.Context, resourceGroupName string) ([]containerservice.ManagedCluster, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"managed_clusters\", \"list\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn nil, retry.GetRateLimitError(false, \"ListManagedCluster\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"ListManagedCluster\", \"client throttled\", c.RetryAfterReader)\n\t\treturn nil, rerr\n\t}\n\n\tresult, rerr := c.listManagedCluster(ctx, resourceGroupName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":142,"to":171}} {"id":100033492,"name":"listManagedCluster","signature":"func (c *Client) listManagedCluster(ctx context.Context, resourceGroupName string) ([]containerservice.ManagedCluster, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/azure_containerserviceclient.go","code":"// listManagedCluster gets a list of ManagedClusters in the resource group.\nfunc (c *Client) listManagedCluster(ctx context.Context, resourceGroupName string) ([]containerservice.ManagedCluster, *retry.Error) {\n\tresourceID := fmt.Sprintf(\"/subscriptions/%s/resourceGroups/%s/providers/Microsoft.ContainerService/managedClusters\",\n\t\tautorest.Encode(\"path\", c.subscriptionID),\n\t\tautorest.Encode(\"path\", resourceGroupName))\n\tresult := make([]containerservice.ManagedCluster, 0)\n\tpage := \u0026ManagedClusterResultPage{}\n\tpage.fn = c.listNextResults\n\n\tresp, rerr := c.armClient.GetResource(ctx, resourceID, \"\")\n\tdefer c.armClient.CloseResponse(ctx, resp)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"managedcluster.list.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\tvar err error\n\tpage.mclr, err = c.listResponder(resp)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"managedcluster.list.respond\", resourceID, err)\n\t\treturn result, retry.GetError(resp, err)\n\t}\n\n\tfor {\n\t\tresult = append(result, page.Values()...)\n\n\t\t// Abort the loop when there's no nextLink in the response.\n\t\tif pointer.StringDeref(page.Response().NextLink, \"\") == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\tif err = page.NextWithContext(ctx); err != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"managedcluster.list.next\", resourceID, err)\n\t\t\treturn result, retry.GetError(page.Response().Response.Response, err)\n\t\t}\n\t}\n\n\treturn result, nil\n}","line":{"from":173,"to":211}} {"id":100033493,"name":"listResponder","signature":"func (c *Client) listResponder(resp *http.Response) (result containerservice.ManagedClusterListResult, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/azure_containerserviceclient.go","code":"func (c *Client) listResponder(resp *http.Response) (result containerservice.ManagedClusterListResult, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tautorest.ByIgnoring(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}","line":{"from":213,"to":221}} {"id":100033494,"name":"managedClusterListResultPreparer","signature":"func (c *Client) managedClusterListResultPreparer(ctx context.Context, mclr containerservice.ManagedClusterListResult) (*http.Request, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/azure_containerserviceclient.go","code":"// managedClusterListResultPreparer prepares a request to retrieve the next set of results.\n// It returns nil if no more results exist.\nfunc (c *Client) managedClusterListResultPreparer(ctx context.Context, mclr containerservice.ManagedClusterListResult) (*http.Request, error) {\n\tif mclr.NextLink == nil || len(pointer.StringDeref(mclr.NextLink, \"\")) \u003c 1 {\n\t\treturn nil, nil\n\t}\n\n\tdecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithBaseURL(pointer.StringDeref(mclr.NextLink, \"\")),\n\t}\n\treturn c.armClient.PrepareGetRequest(ctx, decorators...)\n}","line":{"from":223,"to":234}} {"id":100033495,"name":"listNextResults","signature":"func (c *Client) listNextResults(ctx context.Context, lastResults containerservice.ManagedClusterListResult) (result containerservice.ManagedClusterListResult, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/azure_containerserviceclient.go","code":"// listNextResults retrieves the next set of results, if any.\nfunc (c *Client) listNextResults(ctx context.Context, lastResults containerservice.ManagedClusterListResult) (result containerservice.ManagedClusterListResult, err error) {\n\treq, err := c.managedClusterListResultPreparer(ctx, lastResults)\n\tif err != nil {\n\t\treturn result, autorest.NewErrorWithError(err, \"managedclusterclient\", \"listNextResults\", nil, \"Failure preparing next results request\")\n\t}\n\tif req == nil {\n\t\treturn\n\t}\n\n\tresp, rerr := c.armClient.Send(ctx, req)\n\tdefer c.armClient.CloseResponse(ctx, resp)\n\tif rerr != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\treturn result, autorest.NewErrorWithError(rerr.Error(), \"managedclusterclient\", \"listNextResults\", resp, \"Failure sending next results request\")\n\t}\n\n\tresult, err = c.listResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"managedclusterclient\", \"listNextResults\", resp, \"Failure responding to next results request\")\n\t}\n\n\treturn\n}","line":{"from":236,"to":259}} {"id":100033496,"name":"NextWithContext","signature":"func (page *ManagedClusterResultPage) NextWithContext(ctx context.Context) (err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/azure_containerserviceclient.go","code":"// NextWithContext advances to the next page of values. If there was an error making\n// the request the page does not advance and the error is returned.\nfunc (page *ManagedClusterResultPage) NextWithContext(ctx context.Context) (err error) {\n\tnext, err := page.fn(ctx, page.mclr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.mclr = next\n\treturn nil\n}","line":{"from":267,"to":276}} {"id":100033497,"name":"Next","signature":"func (page *ManagedClusterResultPage) Next() error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/azure_containerserviceclient.go","code":"// Next advances to the next page of values. If there was an error making\n// the request the page does not advance and the error is returned.\n// Deprecated: Use NextWithContext() instead.\nfunc (page *ManagedClusterResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}","line":{"from":278,"to":283}} {"id":100033498,"name":"NotDone","signature":"func (page ManagedClusterResultPage) NotDone() bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/azure_containerserviceclient.go","code":"// NotDone returns true if the page enumeration should be started or is not yet complete.\nfunc (page ManagedClusterResultPage) NotDone() bool {\n\treturn !page.mclr.IsEmpty()\n}","line":{"from":285,"to":288}} {"id":100033499,"name":"Response","signature":"func (page ManagedClusterResultPage) Response() containerservice.ManagedClusterListResult","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/azure_containerserviceclient.go","code":"// Response returns the raw server response from the last page request.\nfunc (page ManagedClusterResultPage) Response() containerservice.ManagedClusterListResult {\n\treturn page.mclr\n}","line":{"from":290,"to":293}} {"id":100033500,"name":"Values","signature":"func (page ManagedClusterResultPage) Values() []containerservice.ManagedCluster","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/azure_containerserviceclient.go","code":"// Values returns the slice of values for the current page or nil if there are no values.\nfunc (page ManagedClusterResultPage) Values() []containerservice.ManagedCluster {\n\tif page.mclr.IsEmpty() {\n\t\treturn nil\n\t}\n\treturn *page.mclr.Value\n}","line":{"from":295,"to":301}} {"id":100033501,"name":"CreateOrUpdate","signature":"func (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, managedClusterName string, parameters containerservice.ManagedCluster, etag string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/azure_containerserviceclient.go","code":"// CreateOrUpdate creates or updates a ManagedCluster.\nfunc (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, managedClusterName string, parameters containerservice.ManagedCluster, etag string) *retry.Error {\n\tmc := metrics.NewMetricContext(\"managed_clusters\", \"create_or_update\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"CreateOrUpdateManagedCluster\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"CreateOrUpdateManagedCluster\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.createOrUpdateManagedCluster(ctx, resourceGroupName, managedClusterName, parameters, etag)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":303,"to":332}} {"id":100033502,"name":"createOrUpdateManagedCluster","signature":"func (c *Client) createOrUpdateManagedCluster(ctx context.Context, resourceGroupName string, managedClusterName string, parameters containerservice.ManagedCluster, etag string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/azure_containerserviceclient.go","code":"// createOrUpdateManagedCluster creates or updates a ManagedCluster.\nfunc (c *Client) createOrUpdateManagedCluster(ctx context.Context, resourceGroupName string, managedClusterName string, parameters containerservice.ManagedCluster, etag string) *retry.Error {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.ContainerService/managedClusters\",\n\t\tmanagedClusterName,\n\t)\n\tdecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithPathParameters(\"{resourceID}\", map[string]interface{}{\"resourceID\": resourceID}),\n\t\tautorest.WithJSON(parameters),\n\t}\n\tif etag != \"\" {\n\t\tdecorators = append(decorators, autorest.WithHeader(\"If-Match\", autorest.String(etag)))\n\t}\n\n\tresponse, rerr := c.armClient.PutResourceWithDecorators(ctx, resourceID, parameters, decorators)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"managedCluster.put.request\", resourceID, rerr.Error())\n\t\treturn rerr\n\t}\n\n\tif response != nil \u0026\u0026 response.StatusCode != http.StatusNoContent {\n\t\t_, rerr = c.createOrUpdateResponder(response)\n\t\tif rerr != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"managedCluster.put.respond\", resourceID, rerr.Error())\n\t\t\treturn rerr\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":334,"to":366}} {"id":100033503,"name":"createOrUpdateResponder","signature":"func (c *Client) createOrUpdateResponder(resp *http.Response) (*containerservice.ManagedCluster, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/azure_containerserviceclient.go","code":"func (c *Client) createOrUpdateResponder(resp *http.Response) (*containerservice.ManagedCluster, *retry.Error) {\n\tresult := \u0026containerservice.ManagedCluster{}\n\terr := autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tresult.Response = autorest.Response{Response: resp}\n\treturn result, retry.GetError(resp, err)\n}","line":{"from":368,"to":376}} {"id":100033504,"name":"Delete","signature":"func (c *Client) Delete(ctx context.Context, resourceGroupName string, managedClusterName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/azure_containerserviceclient.go","code":"// Delete deletes a ManagedCluster by name.\nfunc (c *Client) Delete(ctx context.Context, resourceGroupName string, managedClusterName string) *retry.Error {\n\tmc := metrics.NewMetricContext(\"managed_clusters\", \"delete\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"DeleteManagedCluster\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"DeleteManagedCluster\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.deleteManagedCluster(ctx, resourceGroupName, managedClusterName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":378,"to":407}} {"id":100033505,"name":"deleteManagedCluster","signature":"func (c *Client) deleteManagedCluster(ctx context.Context, resourceGroupName string, managedClusterName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/azure_containerserviceclient.go","code":"// deleteManagedCluster deletes a ManagedCluster by name.\nfunc (c *Client) deleteManagedCluster(ctx context.Context, resourceGroupName string, managedClusterName string) *retry.Error {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.ContainerService/managedClusters\",\n\t\tmanagedClusterName,\n\t)\n\n\treturn c.armClient.DeleteResource(ctx, resourceID, \"\")\n}","line":{"from":409,"to":419}} {"id":100033506,"name":"NewMockInterface","signature":"func NewMockInterface(ctrl *gomock.Controller) *MockInterface","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/mockcontainerserviceclient/interface.go","code":"// NewMockInterface creates a new mock instance.\nfunc NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := \u0026MockInterface{ctrl: ctrl}\n\tmock.recorder = \u0026MockInterfaceMockRecorder{mock}\n\treturn mock\n}","line":{"from":46,"to":51}} {"id":100033507,"name":"EXPECT","signature":"func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/mockcontainerserviceclient/interface.go","code":"// EXPECT returns an object that allows the caller to indicate expected use.\nfunc (m *MockInterface) EXPECT() *MockInterfaceMockRecorder {\n\treturn m.recorder\n}","line":{"from":53,"to":56}} {"id":100033508,"name":"CreateOrUpdate","signature":"func (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, managedClusterName string, parameters containerservice.ManagedCluster, etag string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/mockcontainerserviceclient/interface.go","code":"// CreateOrUpdate mocks base method.\nfunc (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, managedClusterName string, parameters containerservice.ManagedCluster, etag string) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateOrUpdate\", ctx, resourceGroupName, managedClusterName, parameters, etag)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":58,"to":64}} {"id":100033509,"name":"CreateOrUpdate","signature":"func (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, managedClusterName, parameters, etag interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/mockcontainerserviceclient/interface.go","code":"// CreateOrUpdate indicates an expected call of CreateOrUpdate.\nfunc (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, managedClusterName, parameters, etag interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateOrUpdate\", reflect.TypeOf((*MockInterface)(nil).CreateOrUpdate), ctx, resourceGroupName, managedClusterName, parameters, etag)\n}","line":{"from":66,"to":70}} {"id":100033510,"name":"Delete","signature":"func (m *MockInterface) Delete(ctx context.Context, resourceGroupName, managedClusterName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/mockcontainerserviceclient/interface.go","code":"// Delete mocks base method.\nfunc (m *MockInterface) Delete(ctx context.Context, resourceGroupName, managedClusterName string) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", ctx, resourceGroupName, managedClusterName)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":72,"to":78}} {"id":100033511,"name":"Delete","signature":"func (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, managedClusterName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/mockcontainerserviceclient/interface.go","code":"// Delete indicates an expected call of Delete.\nfunc (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, managedClusterName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Delete\", reflect.TypeOf((*MockInterface)(nil).Delete), ctx, resourceGroupName, managedClusterName)\n}","line":{"from":80,"to":84}} {"id":100033512,"name":"Get","signature":"func (m *MockInterface) Get(ctx context.Context, resourceGroupName, managedClusterName string) (containerservice.ManagedCluster, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/mockcontainerserviceclient/interface.go","code":"// Get mocks base method.\nfunc (m *MockInterface) Get(ctx context.Context, resourceGroupName, managedClusterName string) (containerservice.ManagedCluster, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", ctx, resourceGroupName, managedClusterName)\n\tret0, _ := ret[0].(containerservice.ManagedCluster)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":86,"to":93}} {"id":100033513,"name":"Get","signature":"func (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, managedClusterName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/mockcontainerserviceclient/interface.go","code":"// Get indicates an expected call of Get.\nfunc (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, managedClusterName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockInterface)(nil).Get), ctx, resourceGroupName, managedClusterName)\n}","line":{"from":95,"to":99}} {"id":100033514,"name":"List","signature":"func (m *MockInterface) List(ctx context.Context, resourceGroupName string) ([]containerservice.ManagedCluster, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/mockcontainerserviceclient/interface.go","code":"// List mocks base method.\nfunc (m *MockInterface) List(ctx context.Context, resourceGroupName string) ([]containerservice.ManagedCluster, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", ctx, resourceGroupName)\n\tret0, _ := ret[0].([]containerservice.ManagedCluster)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":101,"to":108}} {"id":100033515,"name":"List","signature":"func (mr *MockInterfaceMockRecorder) List(ctx, resourceGroupName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/containerserviceclient/mockcontainerserviceclient/interface.go","code":"// List indicates an expected call of List.\nfunc (mr *MockInterfaceMockRecorder) List(ctx, resourceGroupName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"List\", reflect.TypeOf((*MockInterface)(nil).List), ctx, resourceGroupName)\n}","line":{"from":110,"to":114}} {"id":100033516,"name":"New","signature":"func New(config *azclients.ClientConfig) *Client","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/azure_deploymentclient.go","code":"// New creates a new ContainerServiceClient client with ratelimiting.\nfunc New(config *azclients.ClientConfig) *Client {\n\tbaseURI := config.ResourceManagerEndpoint\n\tauthorizer := config.Authorizer\n\tarmClient := armclient.New(authorizer, baseURI, config.UserAgent, APIVersion, config.Location, config.Backoff)\n\trateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig)\n\n\tklog.V(2).Infof(\"Azure DeploymentClient (read ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPS,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucket)\n\tklog.V(2).Infof(\"Azure DeploymentClient (write ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPSWrite,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucketWrite)\n\n\tclient := \u0026Client{\n\t\tarmClient: armClient,\n\t\trateLimiterReader: rateLimiterReader,\n\t\trateLimiterWriter: rateLimiterWriter,\n\t\tsubscriptionID: config.SubscriptionID,\n\t}\n\n\treturn client\n}","line":{"from":57,"to":79}} {"id":100033517,"name":"Get","signature":"func (c *Client) Get(ctx context.Context, resourceGroupName string, deploymentName string) (resources.DeploymentExtended, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/azure_deploymentclient.go","code":"// Get gets a deployment\nfunc (c *Client) Get(ctx context.Context, resourceGroupName string, deploymentName string) (resources.DeploymentExtended, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"deployments\", \"get\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn resources.DeploymentExtended{}, retry.GetRateLimitError(false, \"GetDeployment\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"GetDeployment\", \"client throttled\", c.RetryAfterReader)\n\t\treturn resources.DeploymentExtended{}, rerr\n\t}\n\n\tresult, rerr := c.getDeployment(ctx, resourceGroupName, deploymentName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":81,"to":110}} {"id":100033518,"name":"getDeployment","signature":"func (c *Client) getDeployment(ctx context.Context, resourceGroupName string, deploymentName string) (resources.DeploymentExtended, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/azure_deploymentclient.go","code":"// getDeployment gets a deployment.\nfunc (c *Client) getDeployment(ctx context.Context, resourceGroupName string, deploymentName string) (resources.DeploymentExtended, *retry.Error) {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Resources/deployments\",\n\t\tdeploymentName,\n\t)\n\tresult := resources.DeploymentExtended{}\n\n\tresponse, rerr := c.armClient.GetResource(ctx, resourceID, \"\")\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"deployment.get.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\terr := autorest.Respond(\n\t\tresponse,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"deployment.get.respond\", resourceID, err)\n\t\treturn result, retry.GetError(response, err)\n\t}\n\n\tresult.Response = autorest.Response{Response: response}\n\treturn result, nil\n}","line":{"from":112,"to":140}} {"id":100033519,"name":"List","signature":"func (c *Client) List(ctx context.Context, resourceGroupName string) ([]resources.DeploymentExtended, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/azure_deploymentclient.go","code":"// List gets a list of deployments in the resource group.\nfunc (c *Client) List(ctx context.Context, resourceGroupName string) ([]resources.DeploymentExtended, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"deployments\", \"list\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn nil, retry.GetRateLimitError(false, \"ListDeployment\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"ListDeployment\", \"client throttled\", c.RetryAfterReader)\n\t\treturn nil, rerr\n\t}\n\n\tresult, rerr := c.listDeployment(ctx, resourceGroupName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":142,"to":171}} {"id":100033520,"name":"listDeployment","signature":"func (c *Client) listDeployment(ctx context.Context, resourceGroupName string) ([]resources.DeploymentExtended, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/azure_deploymentclient.go","code":"// listDeployment gets a list of deployments in the resource group.\nfunc (c *Client) listDeployment(ctx context.Context, resourceGroupName string) ([]resources.DeploymentExtended, *retry.Error) {\n\tresourceID := fmt.Sprintf(\"/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Resources/deployments\",\n\t\tautorest.Encode(\"path\", c.subscriptionID),\n\t\tautorest.Encode(\"path\", resourceGroupName))\n\tresult := make([]resources.DeploymentExtended, 0)\n\tpage := \u0026DeploymentResultPage{}\n\tpage.fn = c.listNextResults\n\n\tresp, rerr := c.armClient.GetResource(ctx, resourceID, \"\")\n\tdefer c.armClient.CloseResponse(ctx, resp)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"deployment.list.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\tvar err error\n\tpage.dplr, err = c.listResponder(resp)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"deployment.list.respond\", resourceID, err)\n\t\treturn result, retry.GetError(resp, err)\n\t}\n\n\tfor {\n\t\tresult = append(result, page.Values()...)\n\n\t\t// Abort the loop when there's no nextLink in the response.\n\t\tif pointer.StringDeref(page.Response().NextLink, \"\") == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\tif err = page.NextWithContext(ctx); err != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"deployment.list.next\", resourceID, err)\n\t\t\treturn result, retry.GetError(page.Response().Response.Response, err)\n\t\t}\n\t}\n\n\treturn result, nil\n}","line":{"from":173,"to":211}} {"id":100033521,"name":"listResponder","signature":"func (c *Client) listResponder(resp *http.Response) (result resources.DeploymentListResult, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/azure_deploymentclient.go","code":"func (c *Client) listResponder(resp *http.Response) (result resources.DeploymentListResult, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tautorest.ByIgnoring(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}","line":{"from":213,"to":221}} {"id":100033522,"name":"deploymentListResultPreparer","signature":"func (c *Client) deploymentListResultPreparer(ctx context.Context, dplr resources.DeploymentListResult) (*http.Request, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/azure_deploymentclient.go","code":"// deploymentListResultPreparer prepares a request to retrieve the next set of results.\n// It returns nil if no more results exist.\nfunc (c *Client) deploymentListResultPreparer(ctx context.Context, dplr resources.DeploymentListResult) (*http.Request, error) {\n\tif dplr.NextLink == nil || len(pointer.StringDeref(dplr.NextLink, \"\")) \u003c 1 {\n\t\treturn nil, nil\n\t}\n\n\tdecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithBaseURL(pointer.StringDeref(dplr.NextLink, \"\")),\n\t}\n\treturn c.armClient.PrepareGetRequest(ctx, decorators...)\n}","line":{"from":223,"to":234}} {"id":100033523,"name":"listNextResults","signature":"func (c *Client) listNextResults(ctx context.Context, lastResults resources.DeploymentListResult) (result resources.DeploymentListResult, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/azure_deploymentclient.go","code":"// listNextResults retrieves the next set of results, if any.\nfunc (c *Client) listNextResults(ctx context.Context, lastResults resources.DeploymentListResult) (result resources.DeploymentListResult, err error) {\n\treq, err := c.deploymentListResultPreparer(ctx, lastResults)\n\tif err != nil {\n\t\treturn result, autorest.NewErrorWithError(err, \"deploymentclient\", \"listNextResults\", nil, \"Failure preparing next results request\")\n\t}\n\tif req == nil {\n\t\treturn\n\t}\n\n\tresp, rerr := c.armClient.Send(ctx, req)\n\tdefer c.armClient.CloseResponse(ctx, resp)\n\tif rerr != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\treturn result, autorest.NewErrorWithError(rerr.Error(), \"deploymentclient\", \"listNextResults\", resp, \"Failure sending next results request\")\n\t}\n\n\tresult, err = c.listResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"deploymentclient\", \"listNextResults\", resp, \"Failure responding to next results request\")\n\t}\n\n\treturn\n}","line":{"from":236,"to":259}} {"id":100033524,"name":"NextWithContext","signature":"func (page *DeploymentResultPage) NextWithContext(ctx context.Context) (err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/azure_deploymentclient.go","code":"// NextWithContext advances to the next page of values. If there was an error making\n// the request the page does not advance and the error is returned.\nfunc (page *DeploymentResultPage) NextWithContext(ctx context.Context) (err error) {\n\tnext, err := page.fn(ctx, page.dplr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.dplr = next\n\treturn nil\n}","line":{"from":267,"to":276}} {"id":100033525,"name":"Next","signature":"func (page *DeploymentResultPage) Next() error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/azure_deploymentclient.go","code":"// Next advances to the next page of values. If there was an error making\n// the request the page does not advance and the error is returned.\n// Deprecated: Use NextWithContext() instead.\nfunc (page *DeploymentResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}","line":{"from":278,"to":283}} {"id":100033526,"name":"NotDone","signature":"func (page DeploymentResultPage) NotDone() bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/azure_deploymentclient.go","code":"// NotDone returns true if the page enumeration should be started or is not yet complete.\nfunc (page DeploymentResultPage) NotDone() bool {\n\treturn !page.dplr.IsEmpty()\n}","line":{"from":285,"to":288}} {"id":100033527,"name":"Response","signature":"func (page DeploymentResultPage) Response() resources.DeploymentListResult","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/azure_deploymentclient.go","code":"// Response returns the raw server response from the last page request.\nfunc (page DeploymentResultPage) Response() resources.DeploymentListResult {\n\treturn page.dplr\n}","line":{"from":290,"to":293}} {"id":100033528,"name":"Values","signature":"func (page DeploymentResultPage) Values() []resources.DeploymentExtended","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/azure_deploymentclient.go","code":"// Values returns the slice of values for the current page or nil if there are no values.\nfunc (page DeploymentResultPage) Values() []resources.DeploymentExtended {\n\tif page.dplr.IsEmpty() {\n\t\treturn nil\n\t}\n\treturn *page.dplr.Value\n}","line":{"from":295,"to":301}} {"id":100033529,"name":"CreateOrUpdate","signature":"func (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, deploymentName string, parameters resources.Deployment, etag string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/azure_deploymentclient.go","code":"// CreateOrUpdate creates or updates a deployment.\nfunc (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, deploymentName string, parameters resources.Deployment, etag string) *retry.Error {\n\tmc := metrics.NewMetricContext(\"deployments\", \"create_or_update\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"CreateOrUpdateDeployment\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"CreateOrUpdateDeployment\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.createOrUpdateDeployment(ctx, resourceGroupName, deploymentName, parameters, etag)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":303,"to":332}} {"id":100033530,"name":"createOrUpdateDeployment","signature":"func (c *Client) createOrUpdateDeployment(ctx context.Context, resourceGroupName string, deploymentName string, parameters resources.Deployment, etag string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/azure_deploymentclient.go","code":"func (c *Client) createOrUpdateDeployment(ctx context.Context, resourceGroupName string, deploymentName string, parameters resources.Deployment, etag string) *retry.Error {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Resources/deployments\",\n\t\tdeploymentName,\n\t)\n\tdecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithPathParameters(\"{resourceID}\", map[string]interface{}{\"resourceID\": resourceID}),\n\t\tautorest.WithJSON(parameters),\n\t}\n\tif etag != \"\" {\n\t\tdecorators = append(decorators, autorest.WithHeader(\"If-Match\", autorest.String(etag)))\n\t}\n\n\tresponse, rerr := c.armClient.PutResourceWithDecorators(ctx, resourceID, parameters, decorators)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"deployment.put.request\", resourceID, rerr.Error())\n\t\treturn rerr\n\t}\n\n\tif response != nil \u0026\u0026 response.StatusCode != http.StatusNoContent {\n\t\t_, rerr = c.createOrUpdateResponder(response)\n\t\tif rerr != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"deployment.put.respond\", resourceID, rerr.Error())\n\t\t\treturn rerr\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":334,"to":365}} {"id":100033531,"name":"createOrUpdateResponder","signature":"func (c *Client) createOrUpdateResponder(resp *http.Response) (*resources.DeploymentExtended, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/azure_deploymentclient.go","code":"func (c *Client) createOrUpdateResponder(resp *http.Response) (*resources.DeploymentExtended, *retry.Error) {\n\tresult := \u0026resources.DeploymentExtended{}\n\terr := autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tresult.Response = autorest.Response{Response: resp}\n\treturn result, retry.GetError(resp, err)\n}","line":{"from":367,"to":375}} {"id":100033532,"name":"Delete","signature":"func (c *Client) Delete(ctx context.Context, resourceGroupName string, deploymentName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/azure_deploymentclient.go","code":"// Delete deletes a deployment by name.\nfunc (c *Client) Delete(ctx context.Context, resourceGroupName string, deploymentName string) *retry.Error {\n\tmc := metrics.NewMetricContext(\"deployments\", \"delete\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"DeleteDeployment\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"DeleteDeployment\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.deleteDeployment(ctx, resourceGroupName, deploymentName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":377,"to":406}} {"id":100033533,"name":"deleteDeployment","signature":"func (c *Client) deleteDeployment(ctx context.Context, resourceGroupName string, deploymentName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/azure_deploymentclient.go","code":"// deleteDeployment deletes a deployment by name.\nfunc (c *Client) deleteDeployment(ctx context.Context, resourceGroupName string, deploymentName string) *retry.Error {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Resources/deployments\",\n\t\tdeploymentName,\n\t)\n\n\treturn c.armClient.DeleteResource(ctx, resourceID, \"\")\n}","line":{"from":408,"to":418}} {"id":100033534,"name":"ExportTemplate","signature":"func (c *Client) ExportTemplate(ctx context.Context, resourceGroupName string, deploymentName string) (result resources.DeploymentExportResult, rerr *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/azure_deploymentclient.go","code":"// ExportTemplate exports the template used for specified deployment\nfunc (c *Client) ExportTemplate(ctx context.Context, resourceGroupName string, deploymentName string) (result resources.DeploymentExportResult, rerr *retry.Error) {\n\tmc := metrics.NewMetricContext(\"deployments\", \"export_template\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn resources.DeploymentExportResult{}, retry.GetRateLimitError(true, \"ExportTemplateDeployment\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"CreateOrUpdateDeployment\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn resources.DeploymentExportResult{}, rerr\n\t}\n\n\tresourceID := fmt.Sprintf(\"/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Resources/deployments/%s/exportTemplate\",\n\t\tautorest.Encode(\"path\", c.subscriptionID),\n\t\tautorest.Encode(\"path\", resourceGroupName),\n\t\tautorest.Encode(\"path\", deploymentName))\n\tresponse, rerr := c.armClient.PostResource(ctx, resourceID, \"exportTemplate\", struct{}{})\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"deployment.exportTemplate.request\", resourceID, rerr.Error())\n\t\treturn\n\t}\n\n\terr := autorest.Respond(\n\t\tresponse,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"deployment.exportTemplate.respond\", resourceID, err)\n\t\treturn result, retry.GetError(response, err)\n\t}\n\n\tresult.Response = autorest.Response{Response: response}\n\treturn\n}","line":{"from":420,"to":459}} {"id":100033535,"name":"NewMockInterface","signature":"func NewMockInterface(ctrl *gomock.Controller) *MockInterface","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/mockdeploymentclient/interface.go","code":"// NewMockInterface creates a new mock instance.\nfunc NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := \u0026MockInterface{ctrl: ctrl}\n\tmock.recorder = \u0026MockInterfaceMockRecorder{mock}\n\treturn mock\n}","line":{"from":46,"to":51}} {"id":100033536,"name":"EXPECT","signature":"func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/mockdeploymentclient/interface.go","code":"// EXPECT returns an object that allows the caller to indicate expected use.\nfunc (m *MockInterface) EXPECT() *MockInterfaceMockRecorder {\n\treturn m.recorder\n}","line":{"from":53,"to":56}} {"id":100033537,"name":"CreateOrUpdate","signature":"func (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, managedClusterName string, parameters resources.Deployment, etag string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/mockdeploymentclient/interface.go","code":"// CreateOrUpdate mocks base method.\nfunc (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, managedClusterName string, parameters resources.Deployment, etag string) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateOrUpdate\", ctx, resourceGroupName, managedClusterName, parameters, etag)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":58,"to":64}} {"id":100033538,"name":"CreateOrUpdate","signature":"func (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, managedClusterName, parameters, etag interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/mockdeploymentclient/interface.go","code":"// CreateOrUpdate indicates an expected call of CreateOrUpdate.\nfunc (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, managedClusterName, parameters, etag interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateOrUpdate\", reflect.TypeOf((*MockInterface)(nil).CreateOrUpdate), ctx, resourceGroupName, managedClusterName, parameters, etag)\n}","line":{"from":66,"to":70}} {"id":100033539,"name":"Delete","signature":"func (m *MockInterface) Delete(ctx context.Context, resourceGroupName, deploymentName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/mockdeploymentclient/interface.go","code":"// Delete mocks base method.\nfunc (m *MockInterface) Delete(ctx context.Context, resourceGroupName, deploymentName string) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", ctx, resourceGroupName, deploymentName)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":72,"to":78}} {"id":100033540,"name":"Delete","signature":"func (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, deploymentName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/mockdeploymentclient/interface.go","code":"// Delete indicates an expected call of Delete.\nfunc (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, deploymentName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Delete\", reflect.TypeOf((*MockInterface)(nil).Delete), ctx, resourceGroupName, deploymentName)\n}","line":{"from":80,"to":84}} {"id":100033541,"name":"ExportTemplate","signature":"func (m *MockInterface) ExportTemplate(ctx context.Context, resourceGroupName, deploymentName string) (resources.DeploymentExportResult, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/mockdeploymentclient/interface.go","code":"// ExportTemplate mocks base method.\nfunc (m *MockInterface) ExportTemplate(ctx context.Context, resourceGroupName, deploymentName string) (resources.DeploymentExportResult, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ExportTemplate\", ctx, resourceGroupName, deploymentName)\n\tret0, _ := ret[0].(resources.DeploymentExportResult)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":86,"to":93}} {"id":100033542,"name":"ExportTemplate","signature":"func (mr *MockInterfaceMockRecorder) ExportTemplate(ctx, resourceGroupName, deploymentName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/mockdeploymentclient/interface.go","code":"// ExportTemplate indicates an expected call of ExportTemplate.\nfunc (mr *MockInterfaceMockRecorder) ExportTemplate(ctx, resourceGroupName, deploymentName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ExportTemplate\", reflect.TypeOf((*MockInterface)(nil).ExportTemplate), ctx, resourceGroupName, deploymentName)\n}","line":{"from":95,"to":99}} {"id":100033543,"name":"Get","signature":"func (m *MockInterface) Get(ctx context.Context, resourceGroupName, deploymentName string) (resources.DeploymentExtended, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/mockdeploymentclient/interface.go","code":"// Get mocks base method.\nfunc (m *MockInterface) Get(ctx context.Context, resourceGroupName, deploymentName string) (resources.DeploymentExtended, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", ctx, resourceGroupName, deploymentName)\n\tret0, _ := ret[0].(resources.DeploymentExtended)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":101,"to":108}} {"id":100033544,"name":"Get","signature":"func (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, deploymentName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/mockdeploymentclient/interface.go","code":"// Get indicates an expected call of Get.\nfunc (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, deploymentName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockInterface)(nil).Get), ctx, resourceGroupName, deploymentName)\n}","line":{"from":110,"to":114}} {"id":100033545,"name":"List","signature":"func (m *MockInterface) List(ctx context.Context, resourceGroupName string) ([]resources.DeploymentExtended, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/mockdeploymentclient/interface.go","code":"// List mocks base method.\nfunc (m *MockInterface) List(ctx context.Context, resourceGroupName string) ([]resources.DeploymentExtended, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", ctx, resourceGroupName)\n\tret0, _ := ret[0].([]resources.DeploymentExtended)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":116,"to":123}} {"id":100033546,"name":"List","signature":"func (mr *MockInterfaceMockRecorder) List(ctx, resourceGroupName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/deploymentclient/mockdeploymentclient/interface.go","code":"// List indicates an expected call of List.\nfunc (mr *MockInterfaceMockRecorder) List(ctx, resourceGroupName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"List\", reflect.TypeOf((*MockInterface)(nil).List), ctx, resourceGroupName)\n}","line":{"from":125,"to":129}} {"id":100033547,"name":"New","signature":"func New(config *azclients.ClientConfig) *Client","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/azure_diskclient.go","code":"// New creates a new Disk client with ratelimiting.\nfunc New(config *azclients.ClientConfig) *Client {\n\tbaseURI := config.ResourceManagerEndpoint\n\tauthorizer := config.Authorizer\n\tapiVersion := APIVersion\n\tif strings.EqualFold(config.CloudName, AzureStackCloudName) {\n\t\tapiVersion = AzureStackCloudAPIVersion\n\t}\n\tarmClient := armclient.New(authorizer, baseURI, config.UserAgent, apiVersion, config.Location, config.Backoff)\n\trateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig)\n\n\tklog.V(2).Infof(\"Azure DisksClient (read ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPS,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucket)\n\tklog.V(2).Infof(\"Azure DisksClient (write ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPSWrite,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucketWrite)\n\n\tclient := \u0026Client{\n\t\tarmClient: armClient,\n\t\trateLimiterReader: rateLimiterReader,\n\t\trateLimiterWriter: rateLimiterWriter,\n\t\tsubscriptionID: config.SubscriptionID,\n\t}\n\n\treturn client\n}","line":{"from":58,"to":84}} {"id":100033548,"name":"Get","signature":"func (c *Client) Get(ctx context.Context, resourceGroupName string, diskName string) (compute.Disk, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/azure_diskclient.go","code":"// Get gets a Disk.\nfunc (c *Client) Get(ctx context.Context, resourceGroupName string, diskName string) (compute.Disk, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"disks\", \"get\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn compute.Disk{}, retry.GetRateLimitError(false, \"GetDisk\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"GetDisk\", \"client throttled\", c.RetryAfterReader)\n\t\treturn compute.Disk{}, rerr\n\t}\n\n\tresult, rerr := c.getDisk(ctx, resourceGroupName, diskName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":86,"to":115}} {"id":100033549,"name":"getDisk","signature":"func (c *Client) getDisk(ctx context.Context, resourceGroupName string, diskName string) (compute.Disk, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/azure_diskclient.go","code":"// getDisk gets a Disk.\nfunc (c *Client) getDisk(ctx context.Context, resourceGroupName string, diskName string) (compute.Disk, *retry.Error) {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Compute/disks\",\n\t\tdiskName,\n\t)\n\tresult := compute.Disk{}\n\n\tresponse, rerr := c.armClient.GetResource(ctx, resourceID, \"\")\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"disk.get.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\terr := autorest.Respond(\n\t\tresponse,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"disk.get.respond\", resourceID, err)\n\t\treturn result, retry.GetError(response, err)\n\t}\n\n\tresult.Response = autorest.Response{Response: response}\n\treturn result, nil\n}","line":{"from":117,"to":145}} {"id":100033550,"name":"CreateOrUpdate","signature":"func (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, diskName string, diskParameter compute.Disk) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/azure_diskclient.go","code":"// CreateOrUpdate creates or updates a Disk.\nfunc (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, diskName string, diskParameter compute.Disk) *retry.Error {\n\tmc := metrics.NewMetricContext(\"disks\", \"create_or_update\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"DiskCreateOrUpdate\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"DiskCreateOrUpdate\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.createOrUpdateDisk(ctx, resourceGroupName, diskName, diskParameter)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":147,"to":176}} {"id":100033551,"name":"createOrUpdateDisk","signature":"func (c *Client) createOrUpdateDisk(ctx context.Context, resourceGroupName string, diskName string, diskParameter compute.Disk) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/azure_diskclient.go","code":"// createOrUpdateDisk creates or updates a Disk.\nfunc (c *Client) createOrUpdateDisk(ctx context.Context, resourceGroupName string, diskName string, diskParameter compute.Disk) *retry.Error {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Compute/disks\",\n\t\tdiskName,\n\t)\n\n\tresponse, rerr := c.armClient.PutResource(ctx, resourceID, diskParameter)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"disk.put.request\", resourceID, rerr.Error())\n\t\treturn rerr\n\t}\n\n\tif response != nil \u0026\u0026 response.StatusCode != http.StatusNoContent {\n\t\t_, rerr = c.createOrUpdateResponder(response)\n\t\tif rerr != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"disk.put.respond\", resourceID, rerr.Error())\n\t\t\treturn rerr\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":178,"to":203}} {"id":100033552,"name":"createOrUpdateResponder","signature":"func (c *Client) createOrUpdateResponder(resp *http.Response) (*compute.Disk, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/azure_diskclient.go","code":"func (c *Client) createOrUpdateResponder(resp *http.Response) (*compute.Disk, *retry.Error) {\n\tresult := \u0026compute.Disk{}\n\terr := autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tresult.Response = autorest.Response{Response: resp}\n\treturn result, retry.GetError(resp, err)\n}","line":{"from":205,"to":213}} {"id":100033553,"name":"Update","signature":"func (c *Client) Update(ctx context.Context, resourceGroupName string, diskName string, diskParameter compute.DiskUpdate) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/azure_diskclient.go","code":"// Update creates or updates a Disk.\nfunc (c *Client) Update(ctx context.Context, resourceGroupName string, diskName string, diskParameter compute.DiskUpdate) *retry.Error {\n\tmc := metrics.NewMetricContext(\"disks\", \"update\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"DiskUpdate\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"DiskUpdate\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.updateDisk(ctx, resourceGroupName, diskName, diskParameter)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":215,"to":244}} {"id":100033554,"name":"updateDisk","signature":"func (c *Client) updateDisk(ctx context.Context, resourceGroupName string, diskName string, diskParameter compute.DiskUpdate) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/azure_diskclient.go","code":"// updateDisk updates a Disk.\nfunc (c *Client) updateDisk(ctx context.Context, resourceGroupName string, diskName string, diskParameter compute.DiskUpdate) *retry.Error {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Compute/disks\",\n\t\tdiskName,\n\t)\n\n\tresponse, rerr := c.armClient.PatchResource(ctx, resourceID, diskParameter)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"disk.put.request\", resourceID, rerr.Error())\n\t\treturn rerr\n\t}\n\n\tif response != nil \u0026\u0026 response.StatusCode != http.StatusNoContent {\n\t\t_, rerr = c.updateResponder(response)\n\t\tif rerr != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"disk.put.respond\", resourceID, rerr.Error())\n\t\t\treturn rerr\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":246,"to":271}} {"id":100033555,"name":"updateResponder","signature":"func (c *Client) updateResponder(resp *http.Response) (*compute.Disk, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/azure_diskclient.go","code":"func (c *Client) updateResponder(resp *http.Response) (*compute.Disk, *retry.Error) {\n\tresult := \u0026compute.Disk{}\n\terr := autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tresult.Response = autorest.Response{Response: resp}\n\treturn result, retry.GetError(resp, err)\n}","line":{"from":273,"to":281}} {"id":100033556,"name":"Delete","signature":"func (c *Client) Delete(ctx context.Context, resourceGroupName string, diskName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/azure_diskclient.go","code":"// Delete deletes a Disk by name.\nfunc (c *Client) Delete(ctx context.Context, resourceGroupName string, diskName string) *retry.Error {\n\tmc := metrics.NewMetricContext(\"disks\", \"delete\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"DiskDelete\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"DiskDelete\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.deleteDisk(ctx, resourceGroupName, diskName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":283,"to":312}} {"id":100033557,"name":"deleteDisk","signature":"func (c *Client) deleteDisk(ctx context.Context, resourceGroupName string, diskName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/azure_diskclient.go","code":"// deleteDisk deletes a PublicIPAddress by name.\nfunc (c *Client) deleteDisk(ctx context.Context, resourceGroupName string, diskName string) *retry.Error {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Compute/disks\",\n\t\tdiskName,\n\t)\n\n\treturn c.armClient.DeleteResource(ctx, resourceID, \"\")\n}","line":{"from":314,"to":324}} {"id":100033558,"name":"ListByResourceGroup","signature":"func (c *Client) ListByResourceGroup(ctx context.Context, resourceGroupName string) ([]compute.Disk, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/azure_diskclient.go","code":"// ListByResourceGroup lists all the disks under a resource group.\nfunc (c *Client) ListByResourceGroup(ctx context.Context, resourceGroupName string) ([]compute.Disk, *retry.Error) {\n\tresourceID := fmt.Sprintf(\"/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/disks\",\n\t\tautorest.Encode(\"path\", c.subscriptionID),\n\t\tautorest.Encode(\"path\", resourceGroupName))\n\n\tresult := make([]compute.Disk, 0)\n\tpage := \u0026DiskListPage{}\n\tpage.fn = c.listNextResults\n\n\tresp, rerr := c.armClient.GetResource(ctx, resourceID, \"\")\n\tdefer c.armClient.CloseResponse(ctx, resp)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"disk.list.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\tvar err error\n\tpage.dl, err = c.listResponder(resp)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"disk.list.respond\", resourceID, err)\n\t\treturn result, retry.GetError(resp, err)\n\t}\n\n\tfor {\n\t\tresult = append(result, page.Values()...)\n\n\t\t// Abort the loop when there's no nextLink in the response.\n\t\tif pointer.StringDeref(page.Response().NextLink, \"\") == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\tif err = page.NextWithContext(ctx); err != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"disk.list.next\", resourceID, err)\n\t\t\treturn result, retry.GetError(page.Response().Response.Response, err)\n\t\t}\n\t}\n\n\treturn result, nil\n}","line":{"from":326,"to":365}} {"id":100033559,"name":"listNextResults","signature":"func (c *Client) listNextResults(ctx context.Context, lastResults compute.DiskList) (result compute.DiskList, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/azure_diskclient.go","code":"// listNextResults retrieves the next set of results, if any.\nfunc (c *Client) listNextResults(ctx context.Context, lastResults compute.DiskList) (result compute.DiskList, err error) {\n\treq, err := c.diskListPreparer(ctx, lastResults)\n\tif err != nil {\n\t\treturn result, autorest.NewErrorWithError(err, \"diskclient\", \"listNextResults\", nil, \"Failure preparing next results request\")\n\t}\n\tif req == nil {\n\t\treturn\n\t}\n\n\tresp, rerr := c.armClient.Send(ctx, req)\n\tdefer c.armClient.CloseResponse(ctx, resp)\n\tif rerr != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\treturn result, autorest.NewErrorWithError(rerr.Error(), \"diskclient\", \"listNextResults\", resp, \"Failure sending next results request\")\n\t}\n\n\tresult, err = c.listResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"diskclient\", \"listNextResults\", resp, \"Failure responding to next results request\")\n\t}\n\treturn\n}","line":{"from":367,"to":389}} {"id":100033560,"name":"listResponder","signature":"func (c *Client) listResponder(resp *http.Response) (result compute.DiskList, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/azure_diskclient.go","code":"// listResponder handles the response to the List request. The method always\n// closes the http.Response Body.\nfunc (c *Client) listResponder(resp *http.Response) (result compute.DiskList, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}","line":{"from":391,"to":401}} {"id":100033561,"name":"diskListPreparer","signature":"func (c *Client) diskListPreparer(ctx context.Context, lr compute.DiskList) (*http.Request, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/azure_diskclient.go","code":"func (c *Client) diskListPreparer(ctx context.Context, lr compute.DiskList) (*http.Request, error) {\n\tif lr.NextLink == nil || len(pointer.StringDeref(lr.NextLink, \"\")) \u003c 1 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare((\u0026http.Request{}).WithContext(ctx),\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(pointer.StringDeref(lr.NextLink, \"\")))\n}","line":{"from":403,"to":411}} {"id":100033562,"name":"NextWithContext","signature":"func (page *DiskListPage) NextWithContext(ctx context.Context) (err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/azure_diskclient.go","code":"// NextWithContext advances to the next page of values. If there was an error making\n// the request the page does not advance and the error is returned.\nfunc (page *DiskListPage) NextWithContext(ctx context.Context) (err error) {\n\tnext, err := page.fn(ctx, page.dl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.dl = next\n\treturn nil\n}","line":{"from":419,"to":428}} {"id":100033563,"name":"Next","signature":"func (page *DiskListPage) Next() error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/azure_diskclient.go","code":"// Next advances to the next page of values. If there was an error making\n// the request the page does not advance and the error is returned.\n// Deprecated: Use NextWithContext() instead.\nfunc (page *DiskListPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}","line":{"from":430,"to":435}} {"id":100033564,"name":"NotDone","signature":"func (page DiskListPage) NotDone() bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/azure_diskclient.go","code":"// NotDone returns true if the page enumeration should be started or is not yet complete.\nfunc (page DiskListPage) NotDone() bool {\n\treturn !page.dl.IsEmpty()\n}","line":{"from":437,"to":440}} {"id":100033565,"name":"Response","signature":"func (page DiskListPage) Response() compute.DiskList","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/azure_diskclient.go","code":"// Response returns the raw server response from the last page request.\nfunc (page DiskListPage) Response() compute.DiskList {\n\treturn page.dl\n}","line":{"from":442,"to":445}} {"id":100033566,"name":"Values","signature":"func (page DiskListPage) Values() []compute.Disk","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/azure_diskclient.go","code":"// Values returns the slice of values for the current page or nil if there are no values.\nfunc (page DiskListPage) Values() []compute.Disk {\n\tif page.dl.IsEmpty() {\n\t\treturn nil\n\t}\n\treturn *page.dl.Value\n}","line":{"from":447,"to":453}} {"id":100033567,"name":"NewMockInterface","signature":"func NewMockInterface(ctrl *gomock.Controller) *MockInterface","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/mockdiskclient/interface.go","code":"// NewMockInterface creates a new mock instance.\nfunc NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := \u0026MockInterface{ctrl: ctrl}\n\tmock.recorder = \u0026MockInterfaceMockRecorder{mock}\n\treturn mock\n}","line":{"from":46,"to":51}} {"id":100033568,"name":"EXPECT","signature":"func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/mockdiskclient/interface.go","code":"// EXPECT returns an object that allows the caller to indicate expected use.\nfunc (m *MockInterface) EXPECT() *MockInterfaceMockRecorder {\n\treturn m.recorder\n}","line":{"from":53,"to":56}} {"id":100033569,"name":"CreateOrUpdate","signature":"func (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, diskName string, diskParameter compute.Disk) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/mockdiskclient/interface.go","code":"// CreateOrUpdate mocks base method.\nfunc (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, diskName string, diskParameter compute.Disk) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateOrUpdate\", ctx, resourceGroupName, diskName, diskParameter)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":58,"to":64}} {"id":100033570,"name":"CreateOrUpdate","signature":"func (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, diskName, diskParameter interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/mockdiskclient/interface.go","code":"// CreateOrUpdate indicates an expected call of CreateOrUpdate.\nfunc (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, diskName, diskParameter interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateOrUpdate\", reflect.TypeOf((*MockInterface)(nil).CreateOrUpdate), ctx, resourceGroupName, diskName, diskParameter)\n}","line":{"from":66,"to":70}} {"id":100033571,"name":"Delete","signature":"func (m *MockInterface) Delete(ctx context.Context, resourceGroupName, diskName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/mockdiskclient/interface.go","code":"// Delete mocks base method.\nfunc (m *MockInterface) Delete(ctx context.Context, resourceGroupName, diskName string) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", ctx, resourceGroupName, diskName)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":72,"to":78}} {"id":100033572,"name":"Delete","signature":"func (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, diskName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/mockdiskclient/interface.go","code":"// Delete indicates an expected call of Delete.\nfunc (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, diskName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Delete\", reflect.TypeOf((*MockInterface)(nil).Delete), ctx, resourceGroupName, diskName)\n}","line":{"from":80,"to":84}} {"id":100033573,"name":"Get","signature":"func (m *MockInterface) Get(ctx context.Context, resourceGroupName, diskName string) (compute.Disk, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/mockdiskclient/interface.go","code":"// Get mocks base method.\nfunc (m *MockInterface) Get(ctx context.Context, resourceGroupName, diskName string) (compute.Disk, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", ctx, resourceGroupName, diskName)\n\tret0, _ := ret[0].(compute.Disk)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":86,"to":93}} {"id":100033574,"name":"Get","signature":"func (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, diskName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/mockdiskclient/interface.go","code":"// Get indicates an expected call of Get.\nfunc (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, diskName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockInterface)(nil).Get), ctx, resourceGroupName, diskName)\n}","line":{"from":95,"to":99}} {"id":100033575,"name":"ListByResourceGroup","signature":"func (m *MockInterface) ListByResourceGroup(ctx context.Context, resourceGroupName string) ([]compute.Disk, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/mockdiskclient/interface.go","code":"// ListByResourceGroup mocks base method.\nfunc (m *MockInterface) ListByResourceGroup(ctx context.Context, resourceGroupName string) ([]compute.Disk, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListByResourceGroup\", ctx, resourceGroupName)\n\tret0, _ := ret[0].([]compute.Disk)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":101,"to":108}} {"id":100033576,"name":"ListByResourceGroup","signature":"func (mr *MockInterfaceMockRecorder) ListByResourceGroup(ctx, resourceGroupName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/mockdiskclient/interface.go","code":"// ListByResourceGroup indicates an expected call of ListByResourceGroup.\nfunc (mr *MockInterfaceMockRecorder) ListByResourceGroup(ctx, resourceGroupName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ListByResourceGroup\", reflect.TypeOf((*MockInterface)(nil).ListByResourceGroup), ctx, resourceGroupName)\n}","line":{"from":110,"to":114}} {"id":100033577,"name":"Update","signature":"func (m *MockInterface) Update(ctx context.Context, resourceGroupName, diskName string, diskParameter compute.DiskUpdate) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/mockdiskclient/interface.go","code":"// Update mocks base method.\nfunc (m *MockInterface) Update(ctx context.Context, resourceGroupName, diskName string, diskParameter compute.DiskUpdate) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", ctx, resourceGroupName, diskName, diskParameter)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":116,"to":122}} {"id":100033578,"name":"Update","signature":"func (mr *MockInterfaceMockRecorder) Update(ctx, resourceGroupName, diskName, diskParameter interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/diskclient/mockdiskclient/interface.go","code":"// Update indicates an expected call of Update.\nfunc (mr *MockInterfaceMockRecorder) Update(ctx, resourceGroupName, diskName, diskParameter interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockInterface)(nil).Update), ctx, resourceGroupName, diskName, diskParameter)\n}","line":{"from":124,"to":128}} {"id":100033579,"name":"New","signature":"func New(config *azclients.ClientConfig) *Client","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/fileclient/azure_fileclient.go","code":"// New creates a azure file client\nfunc New(config *azclients.ClientConfig) *Client {\n\tclient := storage.NewFileSharesClientWithBaseURI(config.ResourceManagerEndpoint, config.SubscriptionID)\n\tclient.Authorizer = config.Authorizer\n\n\treturn \u0026Client{\n\t\tfileSharesClient: client,\n\t}\n}","line":{"from":46,"to":54}} {"id":100033580,"name":"CreateFileShare","signature":"func (c *Client) CreateFileShare(resourceGroupName, accountName string, shareOptions *ShareOptions) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/fileclient/azure_fileclient.go","code":"// CreateFileShare creates a file share\nfunc (c *Client) CreateFileShare(resourceGroupName, accountName string, shareOptions *ShareOptions) error {\n\tif shareOptions == nil {\n\t\treturn fmt.Errorf(\"share options is nil\")\n\t}\n\tresult, err := c.GetFileShare(resourceGroupName, accountName, shareOptions.Name)\n\tif err == nil {\n\t\tklog.V(2).Infof(\"file share(%s) under account(%s) rg(%s) already exists\", shareOptions.Name, accountName, resourceGroupName)\n\t\treturn nil\n\t} else if result.Response.Response == nil || (err != nil \u0026\u0026 result.Response.Response.StatusCode != http.StatusNotFound \u0026\u0026 !strings.Contains(err.Error(), \"ShareNotFound\")) {\n\t\treturn fmt.Errorf(\"failed to get file share(%s), err: %v\", shareOptions.Name, err)\n\t}\n\n\tquota := int32(shareOptions.RequestGiB)\n\tfileShareProperties := \u0026storage.FileShareProperties{\n\t\tShareQuota: \u0026quota,\n\t}\n\tif shareOptions.Protocol == storage.NFS {\n\t\tfileShareProperties.EnabledProtocols = shareOptions.Protocol\n\t}\n\tfileShare := storage.FileShare{\n\t\tName: \u0026shareOptions.Name,\n\t\tFileShareProperties: fileShareProperties,\n\t}\n\t_, err = c.fileSharesClient.Create(context.Background(), resourceGroupName, accountName, shareOptions.Name, fileShare)\n\n\treturn err\n}","line":{"from":56,"to":83}} {"id":100033581,"name":"DeleteFileShare","signature":"func (c *Client) DeleteFileShare(resourceGroupName, accountName, name string) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/fileclient/azure_fileclient.go","code":"// DeleteFileShare deletes a file share\nfunc (c *Client) DeleteFileShare(resourceGroupName, accountName, name string) error {\n\t_, err := c.fileSharesClient.Delete(context.Background(), resourceGroupName, accountName, name)\n\n\treturn err\n}","line":{"from":85,"to":90}} {"id":100033582,"name":"ResizeFileShare","signature":"func (c *Client) ResizeFileShare(resourceGroupName, accountName, name string, sizeGiB int) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/fileclient/azure_fileclient.go","code":"// ResizeFileShare resizes a file share\nfunc (c *Client) ResizeFileShare(resourceGroupName, accountName, name string, sizeGiB int) error {\n\tquota := int32(sizeGiB)\n\n\tshare, err := c.fileSharesClient.Get(context.Background(), resourceGroupName, accountName, name, storage.Stats)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get file share(%s), : %v\", name, err)\n\t}\n\tif *share.FileShareProperties.ShareQuota \u003e= quota {\n\t\tklog.Warningf(\"file share size(%dGi) is already greater or equal than requested size(%dGi), accountName: %s, shareName: %s\",\n\t\t\tshare.FileShareProperties.ShareQuota, sizeGiB, accountName, name)\n\t\treturn nil\n\n\t}\n\n\tshare.FileShareProperties.ShareQuota = \u0026quota\n\t_, err = c.fileSharesClient.Update(context.Background(), resourceGroupName, accountName, name, share)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to update quota on file share(%s), err: %v\", name, err)\n\t}\n\n\tklog.V(4).Infof(\"resize file share completed, resourceGroupName(%s), accountName: %s, shareName: %s, sizeGiB: %d\", resourceGroupName, accountName, name, sizeGiB)\n\n\treturn nil\n}","line":{"from":92,"to":116}} {"id":100033583,"name":"GetFileShare","signature":"func (c *Client) GetFileShare(resourceGroupName, accountName, name string) (storage.FileShare, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/fileclient/azure_fileclient.go","code":"// GetFileShare gets a file share\nfunc (c *Client) GetFileShare(resourceGroupName, accountName, name string) (storage.FileShare, error) {\n\treturn c.fileSharesClient.Get(context.Background(), resourceGroupName, accountName, name, storage.Stats)\n}","line":{"from":118,"to":121}} {"id":100033584,"name":"NewMockInterface","signature":"func NewMockInterface(ctrl *gomock.Controller) *MockInterface","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/fileclient/mockfileclient/interface.go","code":"// NewMockInterface creates a new mock instance\nfunc NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := \u0026MockInterface{ctrl: ctrl}\n\tmock.recorder = \u0026MockInterfaceMockRecorder{mock}\n\treturn mock\n}","line":{"from":40,"to":45}} {"id":100033585,"name":"EXPECT","signature":"func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/fileclient/mockfileclient/interface.go","code":"// EXPECT returns an object that allows the caller to indicate expected use\nfunc (m *MockInterface) EXPECT() *MockInterfaceMockRecorder {\n\treturn m.recorder\n}","line":{"from":47,"to":50}} {"id":100033586,"name":"CreateFileShare","signature":"func (m *MockInterface) CreateFileShare(resourceGroupName, accountName string, shareOptions *fileclient.ShareOptions) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/fileclient/mockfileclient/interface.go","code":"// CreateFileShare mocks base method\nfunc (m *MockInterface) CreateFileShare(resourceGroupName, accountName string, shareOptions *fileclient.ShareOptions) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateFileShare\", resourceGroupName, accountName, shareOptions)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}","line":{"from":52,"to":58}} {"id":100033587,"name":"CreateFileShare","signature":"func (mr *MockInterfaceMockRecorder) CreateFileShare(resourceGroupName, accountName, shareOptions interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/fileclient/mockfileclient/interface.go","code":"// CreateFileShare indicates an expected call of CreateFileShare\nfunc (mr *MockInterfaceMockRecorder) CreateFileShare(resourceGroupName, accountName, shareOptions interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateFileShare\", reflect.TypeOf((*MockInterface)(nil).CreateFileShare), resourceGroupName, accountName, shareOptions)\n}","line":{"from":60,"to":64}} {"id":100033588,"name":"DeleteFileShare","signature":"func (m *MockInterface) DeleteFileShare(resourceGroupName, accountName, name string) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/fileclient/mockfileclient/interface.go","code":"// DeleteFileShare mocks base method\nfunc (m *MockInterface) DeleteFileShare(resourceGroupName, accountName, name string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteFileShare\", resourceGroupName, accountName, name)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}","line":{"from":66,"to":72}} {"id":100033589,"name":"DeleteFileShare","signature":"func (mr *MockInterfaceMockRecorder) DeleteFileShare(resourceGroupName, accountName, name interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/fileclient/mockfileclient/interface.go","code":"// DeleteFileShare indicates an expected call of DeleteFileShare\nfunc (mr *MockInterfaceMockRecorder) DeleteFileShare(resourceGroupName, accountName, name interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteFileShare\", reflect.TypeOf((*MockInterface)(nil).DeleteFileShare), resourceGroupName, accountName, name)\n}","line":{"from":74,"to":78}} {"id":100033590,"name":"ResizeFileShare","signature":"func (m *MockInterface) ResizeFileShare(resourceGroupName, accountName, name string, sizeGiB int) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/fileclient/mockfileclient/interface.go","code":"// ResizeFileShare mocks base method\nfunc (m *MockInterface) ResizeFileShare(resourceGroupName, accountName, name string, sizeGiB int) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ResizeFileShare\", resourceGroupName, accountName, name, sizeGiB)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}","line":{"from":80,"to":86}} {"id":100033591,"name":"ResizeFileShare","signature":"func (mr *MockInterfaceMockRecorder) ResizeFileShare(resourceGroupName, accountName, name, sizeGiB interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/fileclient/mockfileclient/interface.go","code":"// ResizeFileShare indicates an expected call of ResizeFileShare\nfunc (mr *MockInterfaceMockRecorder) ResizeFileShare(resourceGroupName, accountName, name, sizeGiB interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ResizeFileShare\", reflect.TypeOf((*MockInterface)(nil).ResizeFileShare), resourceGroupName, accountName, name, sizeGiB)\n}","line":{"from":88,"to":92}} {"id":100033592,"name":"GetFileShare","signature":"func (m *MockInterface) GetFileShare(resourceGroupName, accountName, name string) (storage.FileShare, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/fileclient/mockfileclient/interface.go","code":"// GetFileShare mocks base method\nfunc (m *MockInterface) GetFileShare(resourceGroupName, accountName, name string) (storage.FileShare, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetFileShare\", resourceGroupName, accountName, name)\n\tret0, _ := ret[0].(storage.FileShare)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}","line":{"from":94,"to":101}} {"id":100033593,"name":"GetFileShare","signature":"func (mr *MockInterfaceMockRecorder) GetFileShare(resourceGroupName, accountName, name interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/fileclient/mockfileclient/interface.go","code":"// GetFileShare indicates an expected call of GetFileShare\nfunc (mr *MockInterfaceMockRecorder) GetFileShare(resourceGroupName, accountName, name interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetFileShare\", reflect.TypeOf((*MockInterface)(nil).GetFileShare), resourceGroupName, accountName, name)\n}","line":{"from":103,"to":107}} {"id":100033594,"name":"New","signature":"func New(config *azclients.ClientConfig) *Client","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/interfaceclient/azure_interfaceclient.go","code":"// New creates a new network interface client with ratelimiting.\nfunc New(config *azclients.ClientConfig) *Client {\n\tbaseURI := config.ResourceManagerEndpoint\n\tauthorizer := config.Authorizer\n\tarmClient := armclient.New(authorizer, baseURI, config.UserAgent, APIVersion, config.Location, config.Backoff)\n\trateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig)\n\n\tklog.V(2).Infof(\"Azure InterfacesClient (read ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPS,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucket)\n\tklog.V(2).Infof(\"Azure InterfacesClient (write ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPSWrite,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucketWrite)\n\n\tclient := \u0026Client{\n\t\tarmClient: armClient,\n\t\trateLimiterReader: rateLimiterReader,\n\t\trateLimiterWriter: rateLimiterWriter,\n\t\tsubscriptionID: config.SubscriptionID,\n\t}\n\n\treturn client\n}","line":{"from":56,"to":78}} {"id":100033595,"name":"Get","signature":"func (c *Client) Get(ctx context.Context, resourceGroupName string, networkInterfaceName string, expand string) (network.Interface, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/interfaceclient/azure_interfaceclient.go","code":"// Get gets a network.Interface.\nfunc (c *Client) Get(ctx context.Context, resourceGroupName string, networkInterfaceName string, expand string) (network.Interface, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"interfaces\", \"get\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn network.Interface{}, retry.GetRateLimitError(false, \"NicGet\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"NicGet\", \"client throttled\", c.RetryAfterReader)\n\t\treturn network.Interface{}, rerr\n\t}\n\n\tresult, rerr := c.getNetworkInterface(ctx, resourceGroupName, networkInterfaceName, expand)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":80,"to":109}} {"id":100033596,"name":"getNetworkInterface","signature":"func (c *Client) getNetworkInterface(ctx context.Context, resourceGroupName string, networkInterfaceName string, expand string) (network.Interface, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/interfaceclient/azure_interfaceclient.go","code":"// getNetworkInterface gets a network.Interface.\nfunc (c *Client) getNetworkInterface(ctx context.Context, resourceGroupName string, networkInterfaceName string, expand string) (network.Interface, *retry.Error) {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Network/networkInterfaces\",\n\t\tnetworkInterfaceName,\n\t)\n\tresult := network.Interface{}\n\n\tresponse, rerr := c.armClient.GetResource(ctx, resourceID, \"\")\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"nic.get.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\terr := autorest.Respond(\n\t\tresponse,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"nic.get.respond\", resourceID, err)\n\t\treturn result, retry.GetError(response, err)\n\t}\n\n\tresult.Response = autorest.Response{Response: response}\n\treturn result, nil\n}","line":{"from":111,"to":139}} {"id":100033597,"name":"GetVirtualMachineScaleSetNetworkInterface","signature":"func (c *Client) GetVirtualMachineScaleSetNetworkInterface(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, expand string) (network.Interface, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/interfaceclient/azure_interfaceclient.go","code":"// GetVirtualMachineScaleSetNetworkInterface gets a network.Interface of VMSS VM.\nfunc (c *Client) GetVirtualMachineScaleSetNetworkInterface(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, expand string) (network.Interface, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"interfaces\", \"get_vmss_nic\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn network.Interface{}, retry.GetRateLimitError(false, \"NicGetVirtualMachineScaleSetNetworkInterface\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"NicGetVirtualMachineScaleSetNetworkInterface\", \"client throttled\", c.RetryAfterReader)\n\t\treturn network.Interface{}, rerr\n\t}\n\n\tresult, rerr := c.getVMSSNetworkInterface(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":141,"to":170}} {"id":100033598,"name":"getVMSSNetworkInterface","signature":"func (c *Client) getVMSSNetworkInterface(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, expand string) (network.Interface, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/interfaceclient/azure_interfaceclient.go","code":"// getVMSSNetworkInterface gets a network.Interface of VMSS VM.\nfunc (c *Client) getVMSSNetworkInterface(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, expand string) (network.Interface, *retry.Error) {\n\tresourceID := fmt.Sprintf(\"/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/virtualMachineScaleSets/%s/virtualMachines/%s/networkInterfaces/%s\",\n\t\tautorest.Encode(\"path\", c.subscriptionID),\n\t\tautorest.Encode(\"path\", resourceGroupName),\n\t\tautorest.Encode(\"path\", virtualMachineScaleSetName),\n\t\tautorest.Encode(\"path\", virtualmachineIndex),\n\t\tautorest.Encode(\"path\", networkInterfaceName),\n\t)\n\n\tresult := network.Interface{}\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": ComputeAPIVersion,\n\t}\n\tif len(expand) \u003e 0 {\n\t\tqueryParameters[\"$expand\"] = autorest.Encode(\"query\", expand)\n\t}\n\tdecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithQueryParameters(queryParameters),\n\t}\n\tresponse, rerr := c.armClient.GetResourceWithDecorators(ctx, resourceID, decorators)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmssnic.get.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\terr := autorest.Respond(\n\t\tresponse,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmssnic.get.respond\", resourceID, err)\n\t\treturn result, retry.GetError(response, err)\n\t}\n\n\tresult.Response = autorest.Response{Response: response}\n\treturn result, nil\n}","line":{"from":172,"to":210}} {"id":100033599,"name":"CreateOrUpdate","signature":"func (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkInterfaceName string, parameters network.Interface) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/interfaceclient/azure_interfaceclient.go","code":"// CreateOrUpdate creates or updates a network.Interface.\nfunc (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkInterfaceName string, parameters network.Interface) *retry.Error {\n\tmc := metrics.NewMetricContext(\"interfaces\", \"create_or_update\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"NicCreateOrUpdate\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"NicCreateOrUpdate\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.createOrUpdateInterface(ctx, resourceGroupName, networkInterfaceName, parameters)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":212,"to":241}} {"id":100033600,"name":"createOrUpdateInterface","signature":"func (c *Client) createOrUpdateInterface(ctx context.Context, resourceGroupName string, networkInterfaceName string, parameters network.Interface) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/interfaceclient/azure_interfaceclient.go","code":"// createOrUpdateInterface creates or updates a network.Interface.\nfunc (c *Client) createOrUpdateInterface(ctx context.Context, resourceGroupName string, networkInterfaceName string, parameters network.Interface) *retry.Error {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Network/networkInterfaces\",\n\t\tnetworkInterfaceName,\n\t)\n\tresponse, rerr := c.armClient.PutResource(ctx, resourceID, parameters)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"nic.put.request\", resourceID, rerr.Error())\n\t\treturn rerr\n\t}\n\n\tif response != nil \u0026\u0026 response.StatusCode != http.StatusNoContent {\n\t\t_, rerr = c.createOrUpdateResponder(response)\n\t\tif rerr != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"nic.put.respond\", resourceID, rerr.Error())\n\t\t\treturn rerr\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":243,"to":267}} {"id":100033601,"name":"createOrUpdateResponder","signature":"func (c *Client) createOrUpdateResponder(resp *http.Response) (*network.Interface, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/interfaceclient/azure_interfaceclient.go","code":"func (c *Client) createOrUpdateResponder(resp *http.Response) (*network.Interface, *retry.Error) {\n\tresult := \u0026network.Interface{}\n\terr := autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tresult.Response = autorest.Response{Response: resp}\n\treturn result, retry.GetError(resp, err)\n}","line":{"from":269,"to":277}} {"id":100033602,"name":"Delete","signature":"func (c *Client) Delete(ctx context.Context, resourceGroupName string, networkInterfaceName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/interfaceclient/azure_interfaceclient.go","code":"// Delete deletes a network interface by name.\nfunc (c *Client) Delete(ctx context.Context, resourceGroupName string, networkInterfaceName string) *retry.Error {\n\tmc := metrics.NewMetricContext(\"interfaces\", \"delete\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"NicDelete\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"NicDelete\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.deleteInterface(ctx, resourceGroupName, networkInterfaceName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":279,"to":308}} {"id":100033603,"name":"deleteInterface","signature":"func (c *Client) deleteInterface(ctx context.Context, resourceGroupName string, networkInterfaceName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/interfaceclient/azure_interfaceclient.go","code":"// deleteInterface deletes a network interface by name.\nfunc (c *Client) deleteInterface(ctx context.Context, resourceGroupName string, networkInterfaceName string) *retry.Error {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Network/networkInterfaces\",\n\t\tnetworkInterfaceName,\n\t)\n\n\treturn c.armClient.DeleteResource(ctx, resourceID, \"\")\n}","line":{"from":310,"to":320}} {"id":100033604,"name":"NewMockInterface","signature":"func NewMockInterface(ctrl *gomock.Controller) *MockInterface","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/interfaceclient/mockinterfaceclient/interface.go","code":"// NewMockInterface creates a new mock instance.\nfunc NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := \u0026MockInterface{ctrl: ctrl}\n\tmock.recorder = \u0026MockInterfaceMockRecorder{mock}\n\treturn mock\n}","line":{"from":46,"to":51}} {"id":100033605,"name":"EXPECT","signature":"func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/interfaceclient/mockinterfaceclient/interface.go","code":"// EXPECT returns an object that allows the caller to indicate expected use.\nfunc (m *MockInterface) EXPECT() *MockInterfaceMockRecorder {\n\treturn m.recorder\n}","line":{"from":53,"to":56}} {"id":100033606,"name":"CreateOrUpdate","signature":"func (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, networkInterfaceName string, parameters network.Interface) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/interfaceclient/mockinterfaceclient/interface.go","code":"// CreateOrUpdate mocks base method.\nfunc (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, networkInterfaceName string, parameters network.Interface) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateOrUpdate\", ctx, resourceGroupName, networkInterfaceName, parameters)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":58,"to":64}} {"id":100033607,"name":"CreateOrUpdate","signature":"func (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, networkInterfaceName, parameters interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/interfaceclient/mockinterfaceclient/interface.go","code":"// CreateOrUpdate indicates an expected call of CreateOrUpdate.\nfunc (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, networkInterfaceName, parameters interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateOrUpdate\", reflect.TypeOf((*MockInterface)(nil).CreateOrUpdate), ctx, resourceGroupName, networkInterfaceName, parameters)\n}","line":{"from":66,"to":70}} {"id":100033608,"name":"Delete","signature":"func (m *MockInterface) Delete(ctx context.Context, resourceGroupName, networkInterfaceName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/interfaceclient/mockinterfaceclient/interface.go","code":"// Delete mocks base method.\nfunc (m *MockInterface) Delete(ctx context.Context, resourceGroupName, networkInterfaceName string) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", ctx, resourceGroupName, networkInterfaceName)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":72,"to":78}} {"id":100033609,"name":"Delete","signature":"func (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, networkInterfaceName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/interfaceclient/mockinterfaceclient/interface.go","code":"// Delete indicates an expected call of Delete.\nfunc (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, networkInterfaceName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Delete\", reflect.TypeOf((*MockInterface)(nil).Delete), ctx, resourceGroupName, networkInterfaceName)\n}","line":{"from":80,"to":84}} {"id":100033610,"name":"Get","signature":"func (m *MockInterface) Get(ctx context.Context, resourceGroupName, networkInterfaceName, expand string) (network.Interface, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/interfaceclient/mockinterfaceclient/interface.go","code":"// Get mocks base method.\nfunc (m *MockInterface) Get(ctx context.Context, resourceGroupName, networkInterfaceName, expand string) (network.Interface, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", ctx, resourceGroupName, networkInterfaceName, expand)\n\tret0, _ := ret[0].(network.Interface)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":86,"to":93}} {"id":100033611,"name":"Get","signature":"func (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, networkInterfaceName, expand interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/interfaceclient/mockinterfaceclient/interface.go","code":"// Get indicates an expected call of Get.\nfunc (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, networkInterfaceName, expand interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockInterface)(nil).Get), ctx, resourceGroupName, networkInterfaceName, expand)\n}","line":{"from":95,"to":99}} {"id":100033612,"name":"GetVirtualMachineScaleSetNetworkInterface","signature":"func (m *MockInterface) GetVirtualMachineScaleSetNetworkInterface(ctx context.Context, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand string) (network.Interface, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/interfaceclient/mockinterfaceclient/interface.go","code":"// GetVirtualMachineScaleSetNetworkInterface mocks base method.\nfunc (m *MockInterface) GetVirtualMachineScaleSetNetworkInterface(ctx context.Context, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand string) (network.Interface, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVirtualMachineScaleSetNetworkInterface\", ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand)\n\tret0, _ := ret[0].(network.Interface)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":101,"to":108}} {"id":100033613,"name":"GetVirtualMachineScaleSetNetworkInterface","signature":"func (mr *MockInterfaceMockRecorder) GetVirtualMachineScaleSetNetworkInterface(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/interfaceclient/mockinterfaceclient/interface.go","code":"// GetVirtualMachineScaleSetNetworkInterface indicates an expected call of GetVirtualMachineScaleSetNetworkInterface.\nfunc (mr *MockInterfaceMockRecorder) GetVirtualMachineScaleSetNetworkInterface(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetVirtualMachineScaleSetNetworkInterface\", reflect.TypeOf((*MockInterface)(nil).GetVirtualMachineScaleSetNetworkInterface), ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand)\n}","line":{"from":110,"to":114}} {"id":100033614,"name":"New","signature":"func New(config *azclients.ClientConfig) *Client","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/azure_loadbalancerclient.go","code":"// New creates a new LoadBalancer client with ratelimiting.\nfunc New(config *azclients.ClientConfig) *Client {\n\tbaseURI := config.ResourceManagerEndpoint\n\tauthorizer := config.Authorizer\n\tarmClient := armclient.New(authorizer, baseURI, config.UserAgent, APIVersion, config.Location, config.Backoff)\n\trateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig)\n\n\tklog.V(2).Infof(\"Azure LoadBalancersClient (read ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPS,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucket)\n\tklog.V(2).Infof(\"Azure LoadBalancersClient (write ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPSWrite,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucketWrite)\n\n\tclient := \u0026Client{\n\t\tarmClient: armClient,\n\t\trateLimiterReader: rateLimiterReader,\n\t\trateLimiterWriter: rateLimiterWriter,\n\t\tsubscriptionID: config.SubscriptionID,\n\t}\n\n\treturn client\n}","line":{"from":57,"to":79}} {"id":100033615,"name":"Get","signature":"func (c *Client) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, expand string) (network.LoadBalancer, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/azure_loadbalancerclient.go","code":"// Get gets a LoadBalancer.\nfunc (c *Client) Get(ctx context.Context, resourceGroupName string, loadBalancerName string, expand string) (network.LoadBalancer, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"load_balancers\", \"get\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn network.LoadBalancer{}, retry.GetRateLimitError(false, \"LBGet\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"LBGet\", \"client throttled\", c.RetryAfterReader)\n\t\treturn network.LoadBalancer{}, rerr\n\t}\n\n\tresult, rerr := c.getLB(ctx, resourceGroupName, loadBalancerName, expand)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":81,"to":110}} {"id":100033616,"name":"getLB","signature":"func (c *Client) getLB(ctx context.Context, resourceGroupName string, loadBalancerName string, expand string) (network.LoadBalancer, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/azure_loadbalancerclient.go","code":"// getLB gets a LoadBalancer.\nfunc (c *Client) getLB(ctx context.Context, resourceGroupName string, loadBalancerName string, expand string) (network.LoadBalancer, *retry.Error) {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Network/loadBalancers\",\n\t\tloadBalancerName,\n\t)\n\tresult := network.LoadBalancer{}\n\n\tresponse, rerr := c.armClient.GetResource(ctx, resourceID, expand)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"loadbalancer.get.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\terr := autorest.Respond(\n\t\tresponse,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"loadbalancer.get.respond\", resourceID, err)\n\t\treturn result, retry.GetError(response, err)\n\t}\n\n\tresult.Response = autorest.Response{Response: response}\n\treturn result, nil\n}","line":{"from":112,"to":140}} {"id":100033617,"name":"List","signature":"func (c *Client) List(ctx context.Context, resourceGroupName string) ([]network.LoadBalancer, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/azure_loadbalancerclient.go","code":"// List gets a list of LoadBalancer in the resource group.\nfunc (c *Client) List(ctx context.Context, resourceGroupName string) ([]network.LoadBalancer, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"load_balancers\", \"list\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn nil, retry.GetRateLimitError(false, \"LBList\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"LBList\", \"client throttled\", c.RetryAfterReader)\n\t\treturn nil, rerr\n\t}\n\n\tresult, rerr := c.listLB(ctx, resourceGroupName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":142,"to":171}} {"id":100033618,"name":"listLB","signature":"func (c *Client) listLB(ctx context.Context, resourceGroupName string) ([]network.LoadBalancer, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/azure_loadbalancerclient.go","code":"// listLB gets a list of LoadBalancers in the resource group.\nfunc (c *Client) listLB(ctx context.Context, resourceGroupName string) ([]network.LoadBalancer, *retry.Error) {\n\tresourceID := fmt.Sprintf(\"/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/loadBalancers\",\n\t\tautorest.Encode(\"path\", c.subscriptionID),\n\t\tautorest.Encode(\"path\", resourceGroupName))\n\tresult := make([]network.LoadBalancer, 0)\n\tpage := \u0026LoadBalancerListResultPage{}\n\tpage.fn = c.listNextResults\n\n\tresp, rerr := c.armClient.GetResource(ctx, resourceID, \"\")\n\tdefer c.armClient.CloseResponse(ctx, resp)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"loadbalancer.list.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\tvar err error\n\tpage.lblr, err = c.listResponder(resp)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"loadbalancer.list.respond\", resourceID, err)\n\t\treturn result, retry.GetError(resp, err)\n\t}\n\n\tfor {\n\t\tresult = append(result, page.Values()...)\n\n\t\t// Abort the loop when there's no nextLink in the response.\n\t\tif pointer.StringDeref(page.Response().NextLink, \"\") == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\tif err = page.NextWithContext(ctx); err != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"loadbalancer.list.next\", resourceID, err)\n\t\t\treturn result, retry.GetError(page.Response().Response.Response, err)\n\t\t}\n\t}\n\n\treturn result, nil\n}","line":{"from":173,"to":211}} {"id":100033619,"name":"CreateOrUpdate","signature":"func (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, loadBalancerName string, parameters network.LoadBalancer, etag string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/azure_loadbalancerclient.go","code":"// CreateOrUpdate creates or updates a LoadBalancer.\nfunc (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, loadBalancerName string, parameters network.LoadBalancer, etag string) *retry.Error {\n\tmc := metrics.NewMetricContext(\"load_balancers\", \"create_or_update\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"LBCreateOrUpdate\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"LBCreateOrUpdate\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.createOrUpdateLB(ctx, resourceGroupName, loadBalancerName, parameters, etag)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":213,"to":242}} {"id":100033620,"name":"createOrUpdateLB","signature":"func (c *Client) createOrUpdateLB(ctx context.Context, resourceGroupName string, loadBalancerName string, parameters network.LoadBalancer, etag string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/azure_loadbalancerclient.go","code":"// createOrUpdateLB creates or updates a LoadBalancer.\nfunc (c *Client) createOrUpdateLB(ctx context.Context, resourceGroupName string, loadBalancerName string, parameters network.LoadBalancer, etag string) *retry.Error {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Network/loadBalancers\",\n\t\tloadBalancerName,\n\t)\n\tdecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithPathParameters(\"{resourceID}\", map[string]interface{}{\"resourceID\": resourceID}),\n\t\tautorest.WithJSON(parameters),\n\t}\n\tif etag != \"\" {\n\t\tdecorators = append(decorators, autorest.WithHeader(\"If-Match\", autorest.String(etag)))\n\t}\n\n\tresponse, rerr := c.armClient.PutResourceWithDecorators(ctx, resourceID, parameters, decorators)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"loadbalancer.put.request\", resourceID, rerr.Error())\n\t\treturn rerr\n\t}\n\n\tif response != nil \u0026\u0026 response.StatusCode != http.StatusNoContent {\n\t\t_, rerr = c.createOrUpdateResponder(response)\n\t\tif rerr != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"loadbalancer.put.respond\", resourceID, rerr.Error())\n\t\t\treturn rerr\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":244,"to":276}} {"id":100033621,"name":"createOrUpdateResponder","signature":"func (c *Client) createOrUpdateResponder(resp *http.Response) (*network.LoadBalancer, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/azure_loadbalancerclient.go","code":"func (c *Client) createOrUpdateResponder(resp *http.Response) (*network.LoadBalancer, *retry.Error) {\n\tresult := \u0026network.LoadBalancer{}\n\terr := autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tresult.Response = autorest.Response{Response: resp}\n\treturn result, retry.GetError(resp, err)\n}","line":{"from":278,"to":286}} {"id":100033622,"name":"Delete","signature":"func (c *Client) Delete(ctx context.Context, resourceGroupName string, loadBalancerName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/azure_loadbalancerclient.go","code":"// Delete deletes a LoadBalancer by name.\nfunc (c *Client) Delete(ctx context.Context, resourceGroupName string, loadBalancerName string) *retry.Error {\n\tmc := metrics.NewMetricContext(\"load_balancers\", \"delete\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"LBDelete\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"LBDelete\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.deleteLB(ctx, resourceGroupName, loadBalancerName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":288,"to":317}} {"id":100033623,"name":"deleteLB","signature":"func (c *Client) deleteLB(ctx context.Context, resourceGroupName string, loadBalancerName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/azure_loadbalancerclient.go","code":"// deleteLB deletes a LoadBalancer by name.\nfunc (c *Client) deleteLB(ctx context.Context, resourceGroupName string, loadBalancerName string) *retry.Error {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Network/loadBalancers\",\n\t\tloadBalancerName,\n\t)\n\n\treturn c.armClient.DeleteResource(ctx, resourceID, \"\")\n}","line":{"from":319,"to":329}} {"id":100033624,"name":"listResponder","signature":"func (c *Client) listResponder(resp *http.Response) (result network.LoadBalancerListResult, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/azure_loadbalancerclient.go","code":"func (c *Client) listResponder(resp *http.Response) (result network.LoadBalancerListResult, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tautorest.ByIgnoring(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}","line":{"from":331,"to":339}} {"id":100033625,"name":"loadBalancerListResultPreparer","signature":"func (c *Client) loadBalancerListResultPreparer(ctx context.Context, lblr network.LoadBalancerListResult) (*http.Request, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/azure_loadbalancerclient.go","code":"// loadBalancerListResultPreparer prepares a request to retrieve the next set of results.\n// It returns nil if no more results exist.\nfunc (c *Client) loadBalancerListResultPreparer(ctx context.Context, lblr network.LoadBalancerListResult) (*http.Request, error) {\n\tif lblr.NextLink == nil || len(pointer.StringDeref(lblr.NextLink, \"\")) \u003c 1 {\n\t\treturn nil, nil\n\t}\n\n\tdecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithBaseURL(pointer.StringDeref(lblr.NextLink, \"\")),\n\t}\n\treturn c.armClient.PrepareGetRequest(ctx, decorators...)\n}","line":{"from":341,"to":352}} {"id":100033626,"name":"listNextResults","signature":"func (c *Client) listNextResults(ctx context.Context, lastResults network.LoadBalancerListResult) (result network.LoadBalancerListResult, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/azure_loadbalancerclient.go","code":"// listNextResults retrieves the next set of results, if any.\nfunc (c *Client) listNextResults(ctx context.Context, lastResults network.LoadBalancerListResult) (result network.LoadBalancerListResult, err error) {\n\treq, err := c.loadBalancerListResultPreparer(ctx, lastResults)\n\tif err != nil {\n\t\treturn result, autorest.NewErrorWithError(err, \"loadbalancerclient\", \"listNextResults\", nil, \"Failure preparing next results request\")\n\t}\n\tif req == nil {\n\t\treturn\n\t}\n\n\tresp, rerr := c.armClient.Send(ctx, req)\n\tdefer c.armClient.CloseResponse(ctx, resp)\n\tif rerr != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\treturn result, autorest.NewErrorWithError(rerr.Error(), \"loadbalancerclient\", \"listNextResults\", resp, \"Failure sending next results request\")\n\t}\n\n\tresult, err = c.listResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"loadbalancerclient\", \"listNextResults\", resp, \"Failure responding to next results request\")\n\t}\n\n\treturn\n}","line":{"from":354,"to":377}} {"id":100033627,"name":"NextWithContext","signature":"func (page *LoadBalancerListResultPage) NextWithContext(ctx context.Context) (err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/azure_loadbalancerclient.go","code":"// NextWithContext advances to the next page of values. If there was an error making\n// the request the page does not advance and the error is returned.\nfunc (page *LoadBalancerListResultPage) NextWithContext(ctx context.Context) (err error) {\n\tnext, err := page.fn(ctx, page.lblr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.lblr = next\n\treturn nil\n}","line":{"from":385,"to":394}} {"id":100033628,"name":"Next","signature":"func (page *LoadBalancerListResultPage) Next() error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/azure_loadbalancerclient.go","code":"// Next advances to the next page of values. If there was an error making\n// the request the page does not advance and the error is returned.\n// Deprecated: Use NextWithContext() instead.\nfunc (page *LoadBalancerListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}","line":{"from":396,"to":401}} {"id":100033629,"name":"NotDone","signature":"func (page LoadBalancerListResultPage) NotDone() bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/azure_loadbalancerclient.go","code":"// NotDone returns true if the page enumeration should be started or is not yet complete.\nfunc (page LoadBalancerListResultPage) NotDone() bool {\n\treturn !page.lblr.IsEmpty()\n}","line":{"from":403,"to":406}} {"id":100033630,"name":"Response","signature":"func (page LoadBalancerListResultPage) Response() network.LoadBalancerListResult","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/azure_loadbalancerclient.go","code":"// Response returns the raw server response from the last page request.\nfunc (page LoadBalancerListResultPage) Response() network.LoadBalancerListResult {\n\treturn page.lblr\n}","line":{"from":408,"to":411}} {"id":100033631,"name":"Values","signature":"func (page LoadBalancerListResultPage) Values() []network.LoadBalancer","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/azure_loadbalancerclient.go","code":"// Values returns the slice of values for the current page or nil if there are no values.\nfunc (page LoadBalancerListResultPage) Values() []network.LoadBalancer {\n\tif page.lblr.IsEmpty() {\n\t\treturn nil\n\t}\n\treturn *page.lblr.Value\n}","line":{"from":413,"to":419}} {"id":100033632,"name":"NewMockInterface","signature":"func NewMockInterface(ctrl *gomock.Controller) *MockInterface","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/mockloadbalancerclient/interface.go","code":"// NewMockInterface creates a new mock instance.\nfunc NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := \u0026MockInterface{ctrl: ctrl}\n\tmock.recorder = \u0026MockInterfaceMockRecorder{mock}\n\treturn mock\n}","line":{"from":46,"to":51}} {"id":100033633,"name":"EXPECT","signature":"func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/mockloadbalancerclient/interface.go","code":"// EXPECT returns an object that allows the caller to indicate expected use.\nfunc (m *MockInterface) EXPECT() *MockInterfaceMockRecorder {\n\treturn m.recorder\n}","line":{"from":53,"to":56}} {"id":100033634,"name":"CreateOrUpdate","signature":"func (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, loadBalancerName string, parameters network.LoadBalancer, etag string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/mockloadbalancerclient/interface.go","code":"// CreateOrUpdate mocks base method.\nfunc (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, loadBalancerName string, parameters network.LoadBalancer, etag string) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateOrUpdate\", ctx, resourceGroupName, loadBalancerName, parameters, etag)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":58,"to":64}} {"id":100033635,"name":"CreateOrUpdate","signature":"func (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, loadBalancerName, parameters, etag interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/mockloadbalancerclient/interface.go","code":"// CreateOrUpdate indicates an expected call of CreateOrUpdate.\nfunc (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, loadBalancerName, parameters, etag interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateOrUpdate\", reflect.TypeOf((*MockInterface)(nil).CreateOrUpdate), ctx, resourceGroupName, loadBalancerName, parameters, etag)\n}","line":{"from":66,"to":70}} {"id":100033636,"name":"Delete","signature":"func (m *MockInterface) Delete(ctx context.Context, resourceGroupName, loadBalancerName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/mockloadbalancerclient/interface.go","code":"// Delete mocks base method.\nfunc (m *MockInterface) Delete(ctx context.Context, resourceGroupName, loadBalancerName string) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", ctx, resourceGroupName, loadBalancerName)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":72,"to":78}} {"id":100033637,"name":"Delete","signature":"func (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, loadBalancerName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/mockloadbalancerclient/interface.go","code":"// Delete indicates an expected call of Delete.\nfunc (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, loadBalancerName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Delete\", reflect.TypeOf((*MockInterface)(nil).Delete), ctx, resourceGroupName, loadBalancerName)\n}","line":{"from":80,"to":84}} {"id":100033638,"name":"Get","signature":"func (m *MockInterface) Get(ctx context.Context, resourceGroupName, loadBalancerName, expand string) (network.LoadBalancer, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/mockloadbalancerclient/interface.go","code":"// Get mocks base method.\nfunc (m *MockInterface) Get(ctx context.Context, resourceGroupName, loadBalancerName, expand string) (network.LoadBalancer, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", ctx, resourceGroupName, loadBalancerName, expand)\n\tret0, _ := ret[0].(network.LoadBalancer)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":86,"to":93}} {"id":100033639,"name":"Get","signature":"func (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, loadBalancerName, expand interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/mockloadbalancerclient/interface.go","code":"// Get indicates an expected call of Get.\nfunc (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, loadBalancerName, expand interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockInterface)(nil).Get), ctx, resourceGroupName, loadBalancerName, expand)\n}","line":{"from":95,"to":99}} {"id":100033640,"name":"List","signature":"func (m *MockInterface) List(ctx context.Context, resourceGroupName string) ([]network.LoadBalancer, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/mockloadbalancerclient/interface.go","code":"// List mocks base method.\nfunc (m *MockInterface) List(ctx context.Context, resourceGroupName string) ([]network.LoadBalancer, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", ctx, resourceGroupName)\n\tret0, _ := ret[0].([]network.LoadBalancer)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":101,"to":108}} {"id":100033641,"name":"List","signature":"func (mr *MockInterfaceMockRecorder) List(ctx, resourceGroupName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/mockloadbalancerclient/interface.go","code":"// List indicates an expected call of List.\nfunc (mr *MockInterfaceMockRecorder) List(ctx, resourceGroupName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"List\", reflect.TypeOf((*MockInterface)(nil).List), ctx, resourceGroupName)\n}","line":{"from":110,"to":114}} {"id":100033642,"name":"New","signature":"func New(config *azclients.ClientConfig) *Client","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/azure_publicipclient.go","code":"// New creates a new PublicIPAddress client with ratelimiting.\nfunc New(config *azclients.ClientConfig) *Client {\n\tbaseURI := config.ResourceManagerEndpoint\n\tauthorizer := config.Authorizer\n\tarmClient := armclient.New(authorizer, baseURI, config.UserAgent, APIVersion, config.Location, config.Backoff)\n\trateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig)\n\n\tklog.V(2).Infof(\"Azure PublicIPAddressesClient (read ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPS,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucket)\n\tklog.V(2).Infof(\"Azure PublicIPAddressesClient (write ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPSWrite,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucketWrite)\n\n\tclient := \u0026Client{\n\t\tarmClient: armClient,\n\t\trateLimiterReader: rateLimiterReader,\n\t\trateLimiterWriter: rateLimiterWriter,\n\t\tsubscriptionID: config.SubscriptionID,\n\t}\n\n\treturn client\n}","line":{"from":57,"to":79}} {"id":100033643,"name":"Get","signature":"func (c *Client) Get(ctx context.Context, resourceGroupName string, publicIPAddressName string, expand string) (network.PublicIPAddress, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/azure_publicipclient.go","code":"// Get gets a PublicIPAddress.\nfunc (c *Client) Get(ctx context.Context, resourceGroupName string, publicIPAddressName string, expand string) (network.PublicIPAddress, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"public_ip_addresses\", \"get\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn network.PublicIPAddress{}, retry.GetRateLimitError(false, \"PublicIPGet\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"PublicIPGet\", \"client throttled\", c.RetryAfterReader)\n\t\treturn network.PublicIPAddress{}, rerr\n\t}\n\n\tresult, rerr := c.getPublicIPAddress(ctx, resourceGroupName, publicIPAddressName, expand)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":81,"to":110}} {"id":100033644,"name":"getPublicIPAddress","signature":"func (c *Client) getPublicIPAddress(ctx context.Context, resourceGroupName string, publicIPAddressName string, expand string) (network.PublicIPAddress, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/azure_publicipclient.go","code":"// getPublicIPAddress gets a PublicIPAddress.\nfunc (c *Client) getPublicIPAddress(ctx context.Context, resourceGroupName string, publicIPAddressName string, expand string) (network.PublicIPAddress, *retry.Error) {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Network/publicIPAddresses\",\n\t\tpublicIPAddressName,\n\t)\n\tresult := network.PublicIPAddress{}\n\n\tresponse, rerr := c.armClient.GetResource(ctx, resourceID, expand)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"publicip.get.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\terr := autorest.Respond(\n\t\tresponse,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"publicip.get.respond\", resourceID, err)\n\t\treturn result, retry.GetError(response, err)\n\t}\n\n\tresult.Response = autorest.Response{Response: response}\n\treturn result, nil\n}","line":{"from":112,"to":140}} {"id":100033645,"name":"GetVirtualMachineScaleSetPublicIPAddress","signature":"func (c *Client) GetVirtualMachineScaleSetPublicIPAddress(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, IPConfigurationName string, publicIPAddressName string, expand string) (network.PublicIPAddress, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/azure_publicipclient.go","code":"// GetVirtualMachineScaleSetPublicIPAddress gets a PublicIPAddress for VMSS VM.\nfunc (c *Client) GetVirtualMachineScaleSetPublicIPAddress(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, IPConfigurationName string, publicIPAddressName string, expand string) (network.PublicIPAddress, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"vmss_public_ip_addresses\", \"get\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn network.PublicIPAddress{}, retry.GetRateLimitError(false, \"VMSSPublicIPGet\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"VMSSPublicIPGet\", \"client throttled\", c.RetryAfterReader)\n\t\treturn network.PublicIPAddress{}, rerr\n\t}\n\n\tresult, rerr := c.getVMSSPublicIPAddress(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, IPConfigurationName, publicIPAddressName, expand)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":142,"to":171}} {"id":100033646,"name":"getVMSSPublicIPAddress","signature":"func (c *Client) getVMSSPublicIPAddress(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, IPConfigurationName string, publicIPAddressName string, expand string) (network.PublicIPAddress, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/azure_publicipclient.go","code":"// getVMSSPublicIPAddress gets a PublicIPAddress for VMSS VM.\nfunc (c *Client) getVMSSPublicIPAddress(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, IPConfigurationName string, publicIPAddressName string, expand string) (network.PublicIPAddress, *retry.Error) {\n\tresourceID := fmt.Sprintf(\"/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/virtualMachineScaleSets/%s/virtualMachines/%s/networkInterfaces/%s/ipconfigurations/%s/publicipaddresses/%s\",\n\t\tautorest.Encode(\"path\", c.subscriptionID),\n\t\tautorest.Encode(\"path\", resourceGroupName),\n\t\tautorest.Encode(\"path\", virtualMachineScaleSetName),\n\t\tautorest.Encode(\"path\", virtualmachineIndex),\n\t\tautorest.Encode(\"path\", networkInterfaceName),\n\t\tautorest.Encode(\"path\", IPConfigurationName),\n\t\tautorest.Encode(\"path\", publicIPAddressName),\n\t)\n\n\tresult := network.PublicIPAddress{}\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": ComputeAPIVersion,\n\t}\n\tif len(expand) \u003e 0 {\n\t\tqueryParameters[\"$expand\"] = autorest.Encode(\"query\", expand)\n\t}\n\tdecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithQueryParameters(queryParameters),\n\t}\n\tresponse, rerr := c.armClient.GetResourceWithDecorators(ctx, resourceID, decorators)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmsspublicip.get.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\terr := autorest.Respond(\n\t\tresponse,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmsspublicip.get.respond\", resourceID, err)\n\t\treturn result, retry.GetError(response, err)\n\t}\n\n\tresult.Response = autorest.Response{Response: response}\n\treturn result, nil\n}","line":{"from":173,"to":213}} {"id":100033647,"name":"List","signature":"func (c *Client) List(ctx context.Context, resourceGroupName string) ([]network.PublicIPAddress, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/azure_publicipclient.go","code":"// List gets a list of PublicIPAddress in the resource group.\nfunc (c *Client) List(ctx context.Context, resourceGroupName string) ([]network.PublicIPAddress, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"public_ip_addresses\", \"list\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn nil, retry.GetRateLimitError(false, \"PublicIPList\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"PublicIPList\", \"client throttled\", c.RetryAfterReader)\n\t\treturn nil, rerr\n\t}\n\n\tresult, rerr := c.listPublicIPAddress(ctx, resourceGroupName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":215,"to":244}} {"id":100033648,"name":"listPublicIPAddress","signature":"func (c *Client) listPublicIPAddress(ctx context.Context, resourceGroupName string) ([]network.PublicIPAddress, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/azure_publicipclient.go","code":"// listPublicIPAddress gets a list of PublicIPAddress in the resource group.\nfunc (c *Client) listPublicIPAddress(ctx context.Context, resourceGroupName string) ([]network.PublicIPAddress, *retry.Error) {\n\tresourceID := fmt.Sprintf(\"/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/publicIPAddresses\",\n\t\tautorest.Encode(\"path\", c.subscriptionID),\n\t\tautorest.Encode(\"path\", resourceGroupName))\n\tresult := make([]network.PublicIPAddress, 0)\n\tpage := \u0026PublicIPAddressListResultPage{}\n\tpage.fn = c.listNextResults\n\n\tresp, rerr := c.armClient.GetResource(ctx, resourceID, \"\")\n\tdefer c.armClient.CloseResponse(ctx, resp)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"publicip.list.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\tvar err error\n\tpage.pialr, err = c.listResponder(resp)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"publicip.list.respond\", resourceID, err)\n\t\treturn result, retry.GetError(resp, err)\n\t}\n\n\tfor {\n\t\tresult = append(result, page.Values()...)\n\n\t\t// Abort the loop when there's no nextLink in the response.\n\t\tif pointer.StringDeref(page.Response().NextLink, \"\") == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\tif err = page.NextWithContext(ctx); err != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"publicip.list.next\", resourceID, err)\n\t\t\treturn result, retry.GetError(page.Response().Response.Response, err)\n\t\t}\n\t}\n\n\treturn result, nil\n}","line":{"from":246,"to":284}} {"id":100033649,"name":"CreateOrUpdate","signature":"func (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, publicIPAddressName string, parameters network.PublicIPAddress) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/azure_publicipclient.go","code":"// CreateOrUpdate creates or updates a PublicIPAddress.\nfunc (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, publicIPAddressName string, parameters network.PublicIPAddress) *retry.Error {\n\tmc := metrics.NewMetricContext(\"public_ip_addresses\", \"create_or_update\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"PublicIPCreateOrUpdate\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"PublicIPCreateOrUpdate\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.createOrUpdatePublicIP(ctx, resourceGroupName, publicIPAddressName, parameters)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":286,"to":315}} {"id":100033650,"name":"createOrUpdatePublicIP","signature":"func (c *Client) createOrUpdatePublicIP(ctx context.Context, resourceGroupName string, publicIPAddressName string, parameters network.PublicIPAddress) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/azure_publicipclient.go","code":"// createOrUpdatePublicIP creates or updates a PublicIPAddress.\nfunc (c *Client) createOrUpdatePublicIP(ctx context.Context, resourceGroupName string, publicIPAddressName string, parameters network.PublicIPAddress) *retry.Error {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Network/publicIPAddresses\",\n\t\tpublicIPAddressName,\n\t)\n\n\tresponse, rerr := c.armClient.PutResource(ctx, resourceID, parameters)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"publicip.put.request\", resourceID, rerr.Error())\n\t\treturn rerr\n\t}\n\n\tif response != nil \u0026\u0026 response.StatusCode != http.StatusNoContent {\n\t\t_, rerr = c.createOrUpdateResponder(response)\n\t\tif rerr != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"publicip.put.respond\", resourceID, rerr.Error())\n\t\t\treturn rerr\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":317,"to":342}} {"id":100033651,"name":"createOrUpdateResponder","signature":"func (c *Client) createOrUpdateResponder(resp *http.Response) (*network.PublicIPAddress, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/azure_publicipclient.go","code":"func (c *Client) createOrUpdateResponder(resp *http.Response) (*network.PublicIPAddress, *retry.Error) {\n\tresult := \u0026network.PublicIPAddress{}\n\terr := autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tresult.Response = autorest.Response{Response: resp}\n\treturn result, retry.GetError(resp, err)\n}","line":{"from":344,"to":352}} {"id":100033652,"name":"Delete","signature":"func (c *Client) Delete(ctx context.Context, resourceGroupName string, publicIPAddressName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/azure_publicipclient.go","code":"// Delete deletes a PublicIPAddress by name.\nfunc (c *Client) Delete(ctx context.Context, resourceGroupName string, publicIPAddressName string) *retry.Error {\n\tmc := metrics.NewMetricContext(\"public_ip_addresses\", \"delete\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"PublicIPDelete\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"PublicIPDelete\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.deletePublicIP(ctx, resourceGroupName, publicIPAddressName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":354,"to":383}} {"id":100033653,"name":"deletePublicIP","signature":"func (c *Client) deletePublicIP(ctx context.Context, resourceGroupName string, publicIPAddressName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/azure_publicipclient.go","code":"// deletePublicIP deletes a PublicIPAddress by name.\nfunc (c *Client) deletePublicIP(ctx context.Context, resourceGroupName string, publicIPAddressName string) *retry.Error {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Network/publicIPAddresses\",\n\t\tpublicIPAddressName,\n\t)\n\n\treturn c.armClient.DeleteResource(ctx, resourceID, \"\")\n}","line":{"from":385,"to":395}} {"id":100033654,"name":"listResponder","signature":"func (c *Client) listResponder(resp *http.Response) (result network.PublicIPAddressListResult, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/azure_publicipclient.go","code":"func (c *Client) listResponder(resp *http.Response) (result network.PublicIPAddressListResult, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tautorest.ByIgnoring(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}","line":{"from":397,"to":405}} {"id":100033655,"name":"publicIPAddressListResultPreparer","signature":"func (c *Client) publicIPAddressListResultPreparer(ctx context.Context, lr network.PublicIPAddressListResult) (*http.Request, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/azure_publicipclient.go","code":"// publicIPAddressListResultPreparer prepares a request to retrieve the next set of results.\n// It returns nil if no more results exist.\nfunc (c *Client) publicIPAddressListResultPreparer(ctx context.Context, lr network.PublicIPAddressListResult) (*http.Request, error) {\n\tif lr.NextLink == nil || len(pointer.StringDeref(lr.NextLink, \"\")) \u003c 1 {\n\t\treturn nil, nil\n\t}\n\n\tdecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithBaseURL(pointer.StringDeref(lr.NextLink, \"\")),\n\t}\n\treturn c.armClient.PrepareGetRequest(ctx, decorators...)\n}","line":{"from":407,"to":418}} {"id":100033656,"name":"listNextResults","signature":"func (c *Client) listNextResults(ctx context.Context, lastResults network.PublicIPAddressListResult) (result network.PublicIPAddressListResult, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/azure_publicipclient.go","code":"// listNextResults retrieves the next set of results, if any.\nfunc (c *Client) listNextResults(ctx context.Context, lastResults network.PublicIPAddressListResult) (result network.PublicIPAddressListResult, err error) {\n\treq, err := c.publicIPAddressListResultPreparer(ctx, lastResults)\n\tif err != nil {\n\t\treturn result, autorest.NewErrorWithError(err, \"publicipclient\", \"listNextResults\", nil, \"Failure preparing next results request\")\n\t}\n\tif req == nil {\n\t\treturn\n\t}\n\n\tresp, rerr := c.armClient.Send(ctx, req)\n\tdefer c.armClient.CloseResponse(ctx, resp)\n\tif rerr != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\treturn result, autorest.NewErrorWithError(rerr.Error(), \"publicipclient\", \"listNextResults\", resp, \"Failure sending next results request\")\n\t}\n\n\tresult, err = c.listResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"publicipclient\", \"listNextResults\", resp, \"Failure responding to next results request\")\n\t}\n\n\treturn\n}","line":{"from":420,"to":443}} {"id":100033657,"name":"NextWithContext","signature":"func (page *PublicIPAddressListResultPage) NextWithContext(ctx context.Context) (err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/azure_publicipclient.go","code":"// NextWithContext advances to the next page of values. If there was an error making\n// the request the page does not advance and the error is returned.\nfunc (page *PublicIPAddressListResultPage) NextWithContext(ctx context.Context) (err error) {\n\tnext, err := page.fn(ctx, page.pialr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.pialr = next\n\treturn nil\n}","line":{"from":451,"to":460}} {"id":100033658,"name":"Next","signature":"func (page *PublicIPAddressListResultPage) Next() error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/azure_publicipclient.go","code":"// Next advances to the next page of values. If there was an error making\n// the request the page does not advance and the error is returned.\n// Deprecated: Use NextWithContext() instead.\nfunc (page *PublicIPAddressListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}","line":{"from":462,"to":467}} {"id":100033659,"name":"NotDone","signature":"func (page PublicIPAddressListResultPage) NotDone() bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/azure_publicipclient.go","code":"// NotDone returns true if the page enumeration should be started or is not yet complete.\nfunc (page PublicIPAddressListResultPage) NotDone() bool {\n\treturn !page.pialr.IsEmpty()\n}","line":{"from":469,"to":472}} {"id":100033660,"name":"Response","signature":"func (page PublicIPAddressListResultPage) Response() network.PublicIPAddressListResult","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/azure_publicipclient.go","code":"// Response returns the raw server response from the last page request.\nfunc (page PublicIPAddressListResultPage) Response() network.PublicIPAddressListResult {\n\treturn page.pialr\n}","line":{"from":474,"to":477}} {"id":100033661,"name":"Values","signature":"func (page PublicIPAddressListResultPage) Values() []network.PublicIPAddress","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/azure_publicipclient.go","code":"// Values returns the slice of values for the current page or nil if there are no values.\nfunc (page PublicIPAddressListResultPage) Values() []network.PublicIPAddress {\n\tif page.pialr.IsEmpty() {\n\t\treturn nil\n\t}\n\treturn *page.pialr.Value\n}","line":{"from":479,"to":485}} {"id":100033662,"name":"NewMockInterface","signature":"func NewMockInterface(ctrl *gomock.Controller) *MockInterface","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/mockpublicipclient/interface.go","code":"// NewMockInterface creates a new mock instance.\nfunc NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := \u0026MockInterface{ctrl: ctrl}\n\tmock.recorder = \u0026MockInterfaceMockRecorder{mock}\n\treturn mock\n}","line":{"from":46,"to":51}} {"id":100033663,"name":"EXPECT","signature":"func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/mockpublicipclient/interface.go","code":"// EXPECT returns an object that allows the caller to indicate expected use.\nfunc (m *MockInterface) EXPECT() *MockInterfaceMockRecorder {\n\treturn m.recorder\n}","line":{"from":53,"to":56}} {"id":100033664,"name":"CreateOrUpdate","signature":"func (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, publicIPAddressName string, parameters network.PublicIPAddress) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/mockpublicipclient/interface.go","code":"// CreateOrUpdate mocks base method.\nfunc (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, publicIPAddressName string, parameters network.PublicIPAddress) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateOrUpdate\", ctx, resourceGroupName, publicIPAddressName, parameters)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":58,"to":64}} {"id":100033665,"name":"CreateOrUpdate","signature":"func (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, publicIPAddressName, parameters interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/mockpublicipclient/interface.go","code":"// CreateOrUpdate indicates an expected call of CreateOrUpdate.\nfunc (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, publicIPAddressName, parameters interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateOrUpdate\", reflect.TypeOf((*MockInterface)(nil).CreateOrUpdate), ctx, resourceGroupName, publicIPAddressName, parameters)\n}","line":{"from":66,"to":70}} {"id":100033666,"name":"Delete","signature":"func (m *MockInterface) Delete(ctx context.Context, resourceGroupName, publicIPAddressName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/mockpublicipclient/interface.go","code":"// Delete mocks base method.\nfunc (m *MockInterface) Delete(ctx context.Context, resourceGroupName, publicIPAddressName string) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", ctx, resourceGroupName, publicIPAddressName)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":72,"to":78}} {"id":100033667,"name":"Delete","signature":"func (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, publicIPAddressName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/mockpublicipclient/interface.go","code":"// Delete indicates an expected call of Delete.\nfunc (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, publicIPAddressName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Delete\", reflect.TypeOf((*MockInterface)(nil).Delete), ctx, resourceGroupName, publicIPAddressName)\n}","line":{"from":80,"to":84}} {"id":100033668,"name":"Get","signature":"func (m *MockInterface) Get(ctx context.Context, resourceGroupName, publicIPAddressName, expand string) (network.PublicIPAddress, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/mockpublicipclient/interface.go","code":"// Get mocks base method.\nfunc (m *MockInterface) Get(ctx context.Context, resourceGroupName, publicIPAddressName, expand string) (network.PublicIPAddress, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", ctx, resourceGroupName, publicIPAddressName, expand)\n\tret0, _ := ret[0].(network.PublicIPAddress)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":86,"to":93}} {"id":100033669,"name":"Get","signature":"func (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, publicIPAddressName, expand interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/mockpublicipclient/interface.go","code":"// Get indicates an expected call of Get.\nfunc (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, publicIPAddressName, expand interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockInterface)(nil).Get), ctx, resourceGroupName, publicIPAddressName, expand)\n}","line":{"from":95,"to":99}} {"id":100033670,"name":"GetVirtualMachineScaleSetPublicIPAddress","signature":"func (m *MockInterface) GetVirtualMachineScaleSetPublicIPAddress(ctx context.Context, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, IPConfigurationName, publicIPAddressName, expand string) (network.PublicIPAddress, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/mockpublicipclient/interface.go","code":"// GetVirtualMachineScaleSetPublicIPAddress mocks base method.\nfunc (m *MockInterface) GetVirtualMachineScaleSetPublicIPAddress(ctx context.Context, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, IPConfigurationName, publicIPAddressName, expand string) (network.PublicIPAddress, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVirtualMachineScaleSetPublicIPAddress\", ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, IPConfigurationName, publicIPAddressName, expand)\n\tret0, _ := ret[0].(network.PublicIPAddress)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":101,"to":108}} {"id":100033671,"name":"GetVirtualMachineScaleSetPublicIPAddress","signature":"func (mr *MockInterfaceMockRecorder) GetVirtualMachineScaleSetPublicIPAddress(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, IPConfigurationName, publicIPAddressName, expand interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/mockpublicipclient/interface.go","code":"// GetVirtualMachineScaleSetPublicIPAddress indicates an expected call of GetVirtualMachineScaleSetPublicIPAddress.\nfunc (mr *MockInterfaceMockRecorder) GetVirtualMachineScaleSetPublicIPAddress(ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, IPConfigurationName, publicIPAddressName, expand interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetVirtualMachineScaleSetPublicIPAddress\", reflect.TypeOf((*MockInterface)(nil).GetVirtualMachineScaleSetPublicIPAddress), ctx, resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, IPConfigurationName, publicIPAddressName, expand)\n}","line":{"from":110,"to":114}} {"id":100033672,"name":"List","signature":"func (m *MockInterface) List(ctx context.Context, resourceGroupName string) ([]network.PublicIPAddress, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/mockpublicipclient/interface.go","code":"// List mocks base method.\nfunc (m *MockInterface) List(ctx context.Context, resourceGroupName string) ([]network.PublicIPAddress, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", ctx, resourceGroupName)\n\tret0, _ := ret[0].([]network.PublicIPAddress)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":116,"to":123}} {"id":100033673,"name":"List","signature":"func (mr *MockInterfaceMockRecorder) List(ctx, resourceGroupName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/publicipclient/mockpublicipclient/interface.go","code":"// List indicates an expected call of List.\nfunc (mr *MockInterfaceMockRecorder) List(ctx, resourceGroupName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"List\", reflect.TypeOf((*MockInterface)(nil).List), ctx, resourceGroupName)\n}","line":{"from":125,"to":129}} {"id":100033674,"name":"New","signature":"func New(config *azclients.ClientConfig) *Client","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/routeclient/azure_routeclient.go","code":"// New creates a new Route client with ratelimiting.\nfunc New(config *azclients.ClientConfig) *Client {\n\tbaseURI := config.ResourceManagerEndpoint\n\tauthorizer := config.Authorizer\n\tarmClient := armclient.New(authorizer, baseURI, config.UserAgent, APIVersion, config.Location, config.Backoff)\n\trateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig)\n\n\tklog.V(2).Infof(\"Azure RoutesClient (read ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPS,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucket)\n\tklog.V(2).Infof(\"Azure RoutesClient (write ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPSWrite,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucketWrite)\n\n\tclient := \u0026Client{\n\t\tarmClient: armClient,\n\t\trateLimiterReader: rateLimiterReader,\n\t\trateLimiterWriter: rateLimiterWriter,\n\t\tsubscriptionID: config.SubscriptionID,\n\t}\n\n\treturn client\n}","line":{"from":55,"to":77}} {"id":100033675,"name":"CreateOrUpdate","signature":"func (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, routeTableName string, routeName string, routeParameters network.Route, etag string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/routeclient/azure_routeclient.go","code":"// CreateOrUpdate creates or updates a Route.\nfunc (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, routeTableName string, routeName string, routeParameters network.Route, etag string) *retry.Error {\n\tmc := metrics.NewMetricContext(\"routes\", \"create_or_update\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"RouteCreateOrUpdate\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"RouteCreateOrUpdate\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.createOrUpdateRoute(ctx, resourceGroupName, routeTableName, routeName, routeParameters, etag)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":79,"to":108}} {"id":100033676,"name":"createOrUpdateRoute","signature":"func (c *Client) createOrUpdateRoute(ctx context.Context, resourceGroupName string, routeTableName string, routeName string, routeParameters network.Route, etag string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/routeclient/azure_routeclient.go","code":"// createOrUpdateRoute creates or updates a Route.\nfunc (c *Client) createOrUpdateRoute(ctx context.Context, resourceGroupName string, routeTableName string, routeName string, routeParameters network.Route, etag string) *retry.Error {\n\tresourceID := armclient.GetChildResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Network/routeTables\",\n\t\trouteTableName,\n\t\t\"routes\",\n\t\trouteName,\n\t)\n\tdecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithPathParameters(\"{resourceID}\", map[string]interface{}{\"resourceID\": resourceID}),\n\t\tautorest.WithJSON(routeParameters),\n\t}\n\tif etag != \"\" {\n\t\tdecorators = append(decorators, autorest.WithHeader(\"If-Match\", autorest.String(etag)))\n\t}\n\n\tresponse, rerr := c.armClient.PutResourceWithDecorators(ctx, resourceID, routeParameters, decorators)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"route.put.request\", resourceID, rerr.Error())\n\t\treturn rerr\n\t}\n\n\tif response != nil \u0026\u0026 response.StatusCode != http.StatusNoContent {\n\t\t_, rerr = c.createOrUpdateResponder(response)\n\t\tif rerr != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"route.put.respond\", resourceID, rerr.Error())\n\t\t\treturn rerr\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":110,"to":144}} {"id":100033677,"name":"createOrUpdateResponder","signature":"func (c *Client) createOrUpdateResponder(resp *http.Response) (*network.Route, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/routeclient/azure_routeclient.go","code":"func (c *Client) createOrUpdateResponder(resp *http.Response) (*network.Route, *retry.Error) {\n\tresult := \u0026network.Route{}\n\terr := autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tresult.Response = autorest.Response{Response: resp}\n\treturn result, retry.GetError(resp, err)\n}","line":{"from":146,"to":154}} {"id":100033678,"name":"Delete","signature":"func (c *Client) Delete(ctx context.Context, resourceGroupName string, routeTableName string, routeName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/routeclient/azure_routeclient.go","code":"// Delete deletes a Route by name.\nfunc (c *Client) Delete(ctx context.Context, resourceGroupName string, routeTableName string, routeName string) *retry.Error {\n\tmc := metrics.NewMetricContext(\"routes\", \"delete\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"RouteDelete\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"RouteDelete\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.deleteRoute(ctx, resourceGroupName, routeTableName, routeName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":156,"to":185}} {"id":100033679,"name":"deleteRoute","signature":"func (c *Client) deleteRoute(ctx context.Context, resourceGroupName string, routeTableName string, routeName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/routeclient/azure_routeclient.go","code":"// deleteRoute deletes a Route by name.\nfunc (c *Client) deleteRoute(ctx context.Context, resourceGroupName string, routeTableName string, routeName string) *retry.Error {\n\tresourceID := armclient.GetChildResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Network/routeTables\",\n\t\trouteTableName,\n\t\t\"routes\",\n\t\trouteName,\n\t)\n\n\treturn c.armClient.DeleteResource(ctx, resourceID, \"\")\n}","line":{"from":187,"to":199}} {"id":100033680,"name":"NewMockInterface","signature":"func NewMockInterface(ctrl *gomock.Controller) *MockInterface","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/routeclient/mockrouteclient/interface.go","code":"// NewMockInterface creates a new mock instance.\nfunc NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := \u0026MockInterface{ctrl: ctrl}\n\tmock.recorder = \u0026MockInterfaceMockRecorder{mock}\n\treturn mock\n}","line":{"from":46,"to":51}} {"id":100033681,"name":"EXPECT","signature":"func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/routeclient/mockrouteclient/interface.go","code":"// EXPECT returns an object that allows the caller to indicate expected use.\nfunc (m *MockInterface) EXPECT() *MockInterfaceMockRecorder {\n\treturn m.recorder\n}","line":{"from":53,"to":56}} {"id":100033682,"name":"CreateOrUpdate","signature":"func (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, routeTableName, routeName string, routeParameters network.Route, etag string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/routeclient/mockrouteclient/interface.go","code":"// CreateOrUpdate mocks base method.\nfunc (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, routeTableName, routeName string, routeParameters network.Route, etag string) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateOrUpdate\", ctx, resourceGroupName, routeTableName, routeName, routeParameters, etag)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":58,"to":64}} {"id":100033683,"name":"CreateOrUpdate","signature":"func (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, routeTableName, routeName, routeParameters, etag interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/routeclient/mockrouteclient/interface.go","code":"// CreateOrUpdate indicates an expected call of CreateOrUpdate.\nfunc (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, routeTableName, routeName, routeParameters, etag interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateOrUpdate\", reflect.TypeOf((*MockInterface)(nil).CreateOrUpdate), ctx, resourceGroupName, routeTableName, routeName, routeParameters, etag)\n}","line":{"from":66,"to":70}} {"id":100033684,"name":"Delete","signature":"func (m *MockInterface) Delete(ctx context.Context, resourceGroupName, routeTableName, routeName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/routeclient/mockrouteclient/interface.go","code":"// Delete mocks base method.\nfunc (m *MockInterface) Delete(ctx context.Context, resourceGroupName, routeTableName, routeName string) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", ctx, resourceGroupName, routeTableName, routeName)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":72,"to":78}} {"id":100033685,"name":"Delete","signature":"func (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, routeTableName, routeName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/routeclient/mockrouteclient/interface.go","code":"// Delete indicates an expected call of Delete.\nfunc (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, routeTableName, routeName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Delete\", reflect.TypeOf((*MockInterface)(nil).Delete), ctx, resourceGroupName, routeTableName, routeName)\n}","line":{"from":80,"to":84}} {"id":100033686,"name":"New","signature":"func New(config *azclients.ClientConfig) *Client","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/routetableclient/azure_routetableclient.go","code":"// New creates a new RouteTable client with ratelimiting.\nfunc New(config *azclients.ClientConfig) *Client {\n\tbaseURI := config.ResourceManagerEndpoint\n\tauthorizer := config.Authorizer\n\tarmClient := armclient.New(authorizer, baseURI, config.UserAgent, APIVersion, config.Location, config.Backoff)\n\trateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig)\n\n\tklog.V(2).Infof(\"Azure RouteTablesClient (read ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPS,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucket)\n\tklog.V(2).Infof(\"Azure RouteTablesClient (write ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPSWrite,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucketWrite)\n\n\tclient := \u0026Client{\n\t\tarmClient: armClient,\n\t\trateLimiterReader: rateLimiterReader,\n\t\trateLimiterWriter: rateLimiterWriter,\n\t\tsubscriptionID: config.SubscriptionID,\n\t}\n\n\treturn client\n}","line":{"from":55,"to":77}} {"id":100033687,"name":"Get","signature":"func (c *Client) Get(ctx context.Context, resourceGroupName string, routeTableName string, expand string) (network.RouteTable, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/routetableclient/azure_routetableclient.go","code":"// Get gets a RouteTable.\nfunc (c *Client) Get(ctx context.Context, resourceGroupName string, routeTableName string, expand string) (network.RouteTable, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"route_tables\", \"get\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn network.RouteTable{}, retry.GetRateLimitError(false, \"RouteTableGet\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"RouteTableGet\", \"client throttled\", c.RetryAfterReader)\n\t\treturn network.RouteTable{}, rerr\n\t}\n\n\tresult, rerr := c.getRouteTable(ctx, resourceGroupName, routeTableName, expand)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":79,"to":108}} {"id":100033688,"name":"getRouteTable","signature":"func (c *Client) getRouteTable(ctx context.Context, resourceGroupName string, routeTableName string, expand string) (network.RouteTable, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/routetableclient/azure_routetableclient.go","code":"// getRouteTable gets a RouteTable.\nfunc (c *Client) getRouteTable(ctx context.Context, resourceGroupName string, routeTableName string, expand string) (network.RouteTable, *retry.Error) {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Network/routeTables\",\n\t\trouteTableName,\n\t)\n\tresult := network.RouteTable{}\n\n\tresponse, rerr := c.armClient.GetResource(ctx, resourceID, expand)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"routetable.get.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\terr := autorest.Respond(\n\t\tresponse,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"routetable.get.respond\", resourceID, err)\n\t\treturn result, retry.GetError(response, err)\n\t}\n\n\tresult.Response = autorest.Response{Response: response}\n\treturn result, nil\n}","line":{"from":110,"to":138}} {"id":100033689,"name":"CreateOrUpdate","signature":"func (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, routeTableName string, parameters network.RouteTable, etag string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/routetableclient/azure_routetableclient.go","code":"// CreateOrUpdate creates or updates a RouteTable.\nfunc (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, routeTableName string, parameters network.RouteTable, etag string) *retry.Error {\n\tmc := metrics.NewMetricContext(\"route_tables\", \"create_or_update\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"RouteTableCreateOrUpdate\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"RouteTableCreateOrUpdate\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.createOrUpdateRouteTable(ctx, resourceGroupName, routeTableName, parameters, etag)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":140,"to":169}} {"id":100033690,"name":"createOrUpdateRouteTable","signature":"func (c *Client) createOrUpdateRouteTable(ctx context.Context, resourceGroupName string, routeTableName string, parameters network.RouteTable, etag string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/routetableclient/azure_routetableclient.go","code":"// createOrUpdateRouteTable creates or updates a RouteTable.\nfunc (c *Client) createOrUpdateRouteTable(ctx context.Context, resourceGroupName string, routeTableName string, parameters network.RouteTable, etag string) *retry.Error {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Network/routeTables\",\n\t\trouteTableName,\n\t)\n\tdecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithPathParameters(\"{resourceID}\", map[string]interface{}{\"resourceID\": resourceID}),\n\t\tautorest.WithJSON(parameters),\n\t}\n\tif etag != \"\" {\n\t\tdecorators = append(decorators, autorest.WithHeader(\"If-Match\", autorest.String(etag)))\n\t}\n\n\tresponse, rerr := c.armClient.PutResourceWithDecorators(ctx, resourceID, parameters, decorators)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"routetable.put.request\", resourceID, rerr.Error())\n\t\treturn rerr\n\t}\n\n\tif response != nil \u0026\u0026 response.StatusCode != http.StatusNoContent {\n\t\t_, rerr = c.createOrUpdateResponder(response)\n\t\tif rerr != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"routetable.put.respond\", resourceID, rerr.Error())\n\t\t\treturn rerr\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":171,"to":203}} {"id":100033691,"name":"createOrUpdateResponder","signature":"func (c *Client) createOrUpdateResponder(resp *http.Response) (*network.RouteTable, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/routetableclient/azure_routetableclient.go","code":"func (c *Client) createOrUpdateResponder(resp *http.Response) (*network.RouteTable, *retry.Error) {\n\tresult := \u0026network.RouteTable{}\n\terr := autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tresult.Response = autorest.Response{Response: resp}\n\treturn result, retry.GetError(resp, err)\n}","line":{"from":205,"to":213}} {"id":100033692,"name":"NewMockInterface","signature":"func NewMockInterface(ctrl *gomock.Controller) *MockInterface","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/routetableclient/mockroutetableclient/interface.go","code":"// NewMockInterface creates a new mock instance.\nfunc NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := \u0026MockInterface{ctrl: ctrl}\n\tmock.recorder = \u0026MockInterfaceMockRecorder{mock}\n\treturn mock\n}","line":{"from":46,"to":51}} {"id":100033693,"name":"EXPECT","signature":"func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/routetableclient/mockroutetableclient/interface.go","code":"// EXPECT returns an object that allows the caller to indicate expected use.\nfunc (m *MockInterface) EXPECT() *MockInterfaceMockRecorder {\n\treturn m.recorder\n}","line":{"from":53,"to":56}} {"id":100033694,"name":"CreateOrUpdate","signature":"func (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, routeTableName string, parameters network.RouteTable, etag string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/routetableclient/mockroutetableclient/interface.go","code":"// CreateOrUpdate mocks base method.\nfunc (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, routeTableName string, parameters network.RouteTable, etag string) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateOrUpdate\", ctx, resourceGroupName, routeTableName, parameters, etag)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":58,"to":64}} {"id":100033695,"name":"CreateOrUpdate","signature":"func (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, routeTableName, parameters, etag interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/routetableclient/mockroutetableclient/interface.go","code":"// CreateOrUpdate indicates an expected call of CreateOrUpdate.\nfunc (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, routeTableName, parameters, etag interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateOrUpdate\", reflect.TypeOf((*MockInterface)(nil).CreateOrUpdate), ctx, resourceGroupName, routeTableName, parameters, etag)\n}","line":{"from":66,"to":70}} {"id":100033696,"name":"Get","signature":"func (m *MockInterface) Get(ctx context.Context, resourceGroupName, routeTableName, expand string) (network.RouteTable, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/routetableclient/mockroutetableclient/interface.go","code":"// Get mocks base method.\nfunc (m *MockInterface) Get(ctx context.Context, resourceGroupName, routeTableName, expand string) (network.RouteTable, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", ctx, resourceGroupName, routeTableName, expand)\n\tret0, _ := ret[0].(network.RouteTable)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":72,"to":79}} {"id":100033697,"name":"Get","signature":"func (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, routeTableName, expand interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/routetableclient/mockroutetableclient/interface.go","code":"// Get indicates an expected call of Get.\nfunc (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, routeTableName, expand interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockInterface)(nil).Get), ctx, resourceGroupName, routeTableName, expand)\n}","line":{"from":81,"to":85}} {"id":100033698,"name":"New","signature":"func New(config *azclients.ClientConfig) *Client","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/azure_securitygroupclient.go","code":"// New creates a new SecurityGroup client with ratelimiting.\nfunc New(config *azclients.ClientConfig) *Client {\n\tbaseURI := config.ResourceManagerEndpoint\n\tauthorizer := config.Authorizer\n\tarmClient := armclient.New(authorizer, baseURI, config.UserAgent, APIVersion, config.Location, config.Backoff)\n\trateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig)\n\n\tklog.V(2).Infof(\"Azure SecurityGroupsClient (read ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPS,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucket)\n\tklog.V(2).Infof(\"Azure SecurityGroupsClient (write ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPSWrite,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucketWrite)\n\n\tclient := \u0026Client{\n\t\tarmClient: armClient,\n\t\trateLimiterReader: rateLimiterReader,\n\t\trateLimiterWriter: rateLimiterWriter,\n\t\tsubscriptionID: config.SubscriptionID,\n\t}\n\n\treturn client\n}","line":{"from":57,"to":79}} {"id":100033699,"name":"Get","signature":"func (c *Client) Get(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, expand string) (network.SecurityGroup, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/azure_securitygroupclient.go","code":"// Get gets a SecurityGroup.\nfunc (c *Client) Get(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, expand string) (network.SecurityGroup, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"security_groups\", \"get\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn network.SecurityGroup{}, retry.GetRateLimitError(false, \"NSGGet\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"NSGGet\", \"client throttled\", c.RetryAfterReader)\n\t\treturn network.SecurityGroup{}, rerr\n\t}\n\n\tresult, rerr := c.getSecurityGroup(ctx, resourceGroupName, networkSecurityGroupName, expand)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":81,"to":110}} {"id":100033700,"name":"getSecurityGroup","signature":"func (c *Client) getSecurityGroup(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, expand string) (network.SecurityGroup, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/azure_securitygroupclient.go","code":"// getSecurityGroup gets a SecurityGroup.\nfunc (c *Client) getSecurityGroup(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, expand string) (network.SecurityGroup, *retry.Error) {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Network/networkSecurityGroups\",\n\t\tnetworkSecurityGroupName,\n\t)\n\tresult := network.SecurityGroup{}\n\n\tresponse, rerr := c.armClient.GetResource(ctx, resourceID, expand)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"securitygroup.get.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\terr := autorest.Respond(\n\t\tresponse,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"securitygroup.get.respond\", resourceID, err)\n\t\treturn result, retry.GetError(response, err)\n\t}\n\n\tresult.Response = autorest.Response{Response: response}\n\treturn result, nil\n}","line":{"from":112,"to":140}} {"id":100033701,"name":"List","signature":"func (c *Client) List(ctx context.Context, resourceGroupName string) ([]network.SecurityGroup, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/azure_securitygroupclient.go","code":"// List gets a list of SecurityGroups in the resource group.\nfunc (c *Client) List(ctx context.Context, resourceGroupName string) ([]network.SecurityGroup, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"security_groups\", \"list\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn nil, retry.GetRateLimitError(false, \"NSGList\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"NSGList\", \"client throttled\", c.RetryAfterReader)\n\t\treturn nil, rerr\n\t}\n\n\tresult, rerr := c.listSecurityGroup(ctx, resourceGroupName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":142,"to":171}} {"id":100033702,"name":"listSecurityGroup","signature":"func (c *Client) listSecurityGroup(ctx context.Context, resourceGroupName string) ([]network.SecurityGroup, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/azure_securitygroupclient.go","code":"// listSecurityGroup gets a list of SecurityGroups in the resource group.\nfunc (c *Client) listSecurityGroup(ctx context.Context, resourceGroupName string) ([]network.SecurityGroup, *retry.Error) {\n\tresourceID := fmt.Sprintf(\"/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/networkSecurityGroups\",\n\t\tautorest.Encode(\"path\", c.subscriptionID),\n\t\tautorest.Encode(\"path\", resourceGroupName))\n\tresult := make([]network.SecurityGroup, 0)\n\tpage := \u0026SecurityGroupListResultPage{}\n\tpage.fn = c.listNextResults\n\n\tresp, rerr := c.armClient.GetResource(ctx, resourceID, \"\")\n\tdefer c.armClient.CloseResponse(ctx, resp)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"securitygroup.list.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\tvar err error\n\tpage.sglr, err = c.listResponder(resp)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"securitygroup.list.respond\", resourceID, err)\n\t\treturn result, retry.GetError(resp, err)\n\t}\n\n\tfor {\n\t\tresult = append(result, page.Values()...)\n\n\t\t// Abort the loop when there's no nextLink in the response.\n\t\tif pointer.StringDeref(page.Response().NextLink, \"\") == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\tif err = page.NextWithContext(ctx); err != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"securitygroup.list.next\", resourceID, err)\n\t\t\treturn result, retry.GetError(page.Response().Response.Response, err)\n\t\t}\n\t}\n\n\treturn result, nil\n}","line":{"from":173,"to":211}} {"id":100033703,"name":"CreateOrUpdate","signature":"func (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, parameters network.SecurityGroup, etag string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/azure_securitygroupclient.go","code":"// CreateOrUpdate creates or updates a SecurityGroup.\nfunc (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, parameters network.SecurityGroup, etag string) *retry.Error {\n\tmc := metrics.NewMetricContext(\"security_groups\", \"create_or_update\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"NSGCreateOrUpdate\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"NSGCreateOrUpdate\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.createOrUpdateNSG(ctx, resourceGroupName, networkSecurityGroupName, parameters, etag)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":213,"to":242}} {"id":100033704,"name":"createOrUpdateNSG","signature":"func (c *Client) createOrUpdateNSG(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, parameters network.SecurityGroup, etag string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/azure_securitygroupclient.go","code":"// createOrUpdateNSG creates or updates a SecurityGroup.\nfunc (c *Client) createOrUpdateNSG(ctx context.Context, resourceGroupName string, networkSecurityGroupName string, parameters network.SecurityGroup, etag string) *retry.Error {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Network/networkSecurityGroups\",\n\t\tnetworkSecurityGroupName,\n\t)\n\tdecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithPathParameters(\"{resourceID}\", map[string]interface{}{\"resourceID\": resourceID}),\n\t\tautorest.WithJSON(parameters),\n\t}\n\tif etag != \"\" {\n\t\tdecorators = append(decorators, autorest.WithHeader(\"If-Match\", autorest.String(etag)))\n\t}\n\n\tresponse, rerr := c.armClient.PutResourceWithDecorators(ctx, resourceID, parameters, decorators)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"securityGroup.put.request\", resourceID, rerr.Error())\n\t\treturn rerr\n\t}\n\n\tif response != nil \u0026\u0026 response.StatusCode != http.StatusNoContent {\n\t\t_, rerr = c.createOrUpdateResponder(response)\n\t\tif rerr != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"securityGroup.put.respond\", resourceID, rerr.Error())\n\t\t\treturn rerr\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":244,"to":276}} {"id":100033705,"name":"createOrUpdateResponder","signature":"func (c *Client) createOrUpdateResponder(resp *http.Response) (*network.SecurityGroup, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/azure_securitygroupclient.go","code":"func (c *Client) createOrUpdateResponder(resp *http.Response) (*network.SecurityGroup, *retry.Error) {\n\tresult := \u0026network.SecurityGroup{}\n\terr := autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tresult.Response = autorest.Response{Response: resp}\n\treturn result, retry.GetError(resp, err)\n}","line":{"from":278,"to":286}} {"id":100033706,"name":"Delete","signature":"func (c *Client) Delete(ctx context.Context, resourceGroupName string, networkSecurityGroupName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/azure_securitygroupclient.go","code":"// Delete deletes a SecurityGroup by name.\nfunc (c *Client) Delete(ctx context.Context, resourceGroupName string, networkSecurityGroupName string) *retry.Error {\n\tmc := metrics.NewMetricContext(\"security_groups\", \"delete\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"NSGDelete\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"NSGDelete\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.deleteNSG(ctx, resourceGroupName, networkSecurityGroupName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":288,"to":317}} {"id":100033707,"name":"deleteNSG","signature":"func (c *Client) deleteNSG(ctx context.Context, resourceGroupName string, networkSecurityGroupName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/azure_securitygroupclient.go","code":"// deleteNSG deletes a SecurityGroup by name.\nfunc (c *Client) deleteNSG(ctx context.Context, resourceGroupName string, networkSecurityGroupName string) *retry.Error {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Network/networkSecurityGroups\",\n\t\tnetworkSecurityGroupName,\n\t)\n\n\treturn c.armClient.DeleteResource(ctx, resourceID, \"\")\n}","line":{"from":319,"to":329}} {"id":100033708,"name":"listResponder","signature":"func (c *Client) listResponder(resp *http.Response) (result network.SecurityGroupListResult, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/azure_securitygroupclient.go","code":"func (c *Client) listResponder(resp *http.Response) (result network.SecurityGroupListResult, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tautorest.ByIgnoring(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}","line":{"from":331,"to":339}} {"id":100033709,"name":"securityGroupListResultPreparer","signature":"func (c *Client) securityGroupListResultPreparer(ctx context.Context, sglr network.SecurityGroupListResult) (*http.Request, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/azure_securitygroupclient.go","code":"// securityGroupListResultPreparer prepares a request to retrieve the next set of results.\n// It returns nil if no more results exist.\nfunc (c *Client) securityGroupListResultPreparer(ctx context.Context, sglr network.SecurityGroupListResult) (*http.Request, error) {\n\tif sglr.NextLink == nil || len(pointer.StringDeref(sglr.NextLink, \"\")) \u003c 1 {\n\t\treturn nil, nil\n\t}\n\n\tdecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithBaseURL(pointer.StringDeref(sglr.NextLink, \"\")),\n\t}\n\treturn c.armClient.PrepareGetRequest(ctx, decorators...)\n}","line":{"from":341,"to":352}} {"id":100033710,"name":"listNextResults","signature":"func (c *Client) listNextResults(ctx context.Context, lastResults network.SecurityGroupListResult) (result network.SecurityGroupListResult, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/azure_securitygroupclient.go","code":"// listNextResults retrieves the next set of results, if any.\nfunc (c *Client) listNextResults(ctx context.Context, lastResults network.SecurityGroupListResult) (result network.SecurityGroupListResult, err error) {\n\treq, err := c.securityGroupListResultPreparer(ctx, lastResults)\n\tif err != nil {\n\t\treturn result, autorest.NewErrorWithError(err, \"securitygroupclient\", \"listNextResults\", nil, \"Failure preparing next results request\")\n\t}\n\tif req == nil {\n\t\treturn\n\t}\n\n\tresp, rerr := c.armClient.Send(ctx, req)\n\tdefer c.armClient.CloseResponse(ctx, resp)\n\tif rerr != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\treturn result, autorest.NewErrorWithError(rerr.Error(), \"securitygroupclient\", \"listNextResults\", resp, \"Failure sending next results request\")\n\t}\n\n\tresult, err = c.listResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"securitygroupclient\", \"listNextResults\", resp, \"Failure responding to next results request\")\n\t}\n\n\treturn\n}","line":{"from":354,"to":377}} {"id":100033711,"name":"NextWithContext","signature":"func (page *SecurityGroupListResultPage) NextWithContext(ctx context.Context) (err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/azure_securitygroupclient.go","code":"// NextWithContext advances to the next page of values. If there was an error making\n// the request the page does not advance and the error is returned.\nfunc (page *SecurityGroupListResultPage) NextWithContext(ctx context.Context) (err error) {\n\tnext, err := page.fn(ctx, page.sglr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.sglr = next\n\treturn nil\n}","line":{"from":385,"to":394}} {"id":100033712,"name":"Next","signature":"func (page *SecurityGroupListResultPage) Next() error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/azure_securitygroupclient.go","code":"// Next advances to the next page of values. If there was an error making\n// the request the page does not advance and the error is returned.\n// Deprecated: Use NextWithContext() instead.\nfunc (page *SecurityGroupListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}","line":{"from":396,"to":401}} {"id":100033713,"name":"NotDone","signature":"func (page SecurityGroupListResultPage) NotDone() bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/azure_securitygroupclient.go","code":"// NotDone returns true if the page enumeration should be started or is not yet complete.\nfunc (page SecurityGroupListResultPage) NotDone() bool {\n\treturn !page.sglr.IsEmpty()\n}","line":{"from":403,"to":406}} {"id":100033714,"name":"Response","signature":"func (page SecurityGroupListResultPage) Response() network.SecurityGroupListResult","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/azure_securitygroupclient.go","code":"// Response returns the raw server response from the last page request.\nfunc (page SecurityGroupListResultPage) Response() network.SecurityGroupListResult {\n\treturn page.sglr\n}","line":{"from":408,"to":411}} {"id":100033715,"name":"Values","signature":"func (page SecurityGroupListResultPage) Values() []network.SecurityGroup","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/azure_securitygroupclient.go","code":"// Values returns the slice of values for the current page or nil if there are no values.\nfunc (page SecurityGroupListResultPage) Values() []network.SecurityGroup {\n\tif page.sglr.IsEmpty() {\n\t\treturn nil\n\t}\n\treturn *page.sglr.Value\n}","line":{"from":413,"to":419}} {"id":100033716,"name":"NewMockInterface","signature":"func NewMockInterface(ctrl *gomock.Controller) *MockInterface","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/mocksecuritygroupclient/interface.go","code":"// NewMockInterface creates a new mock instance.\nfunc NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := \u0026MockInterface{ctrl: ctrl}\n\tmock.recorder = \u0026MockInterfaceMockRecorder{mock}\n\treturn mock\n}","line":{"from":46,"to":51}} {"id":100033717,"name":"EXPECT","signature":"func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/mocksecuritygroupclient/interface.go","code":"// EXPECT returns an object that allows the caller to indicate expected use.\nfunc (m *MockInterface) EXPECT() *MockInterfaceMockRecorder {\n\treturn m.recorder\n}","line":{"from":53,"to":56}} {"id":100033718,"name":"CreateOrUpdate","signature":"func (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, networkSecurityGroupName string, parameters network.SecurityGroup, etag string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/mocksecuritygroupclient/interface.go","code":"// CreateOrUpdate mocks base method.\nfunc (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, networkSecurityGroupName string, parameters network.SecurityGroup, etag string) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateOrUpdate\", ctx, resourceGroupName, networkSecurityGroupName, parameters, etag)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":58,"to":64}} {"id":100033719,"name":"CreateOrUpdate","signature":"func (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, networkSecurityGroupName, parameters, etag interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/mocksecuritygroupclient/interface.go","code":"// CreateOrUpdate indicates an expected call of CreateOrUpdate.\nfunc (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, networkSecurityGroupName, parameters, etag interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateOrUpdate\", reflect.TypeOf((*MockInterface)(nil).CreateOrUpdate), ctx, resourceGroupName, networkSecurityGroupName, parameters, etag)\n}","line":{"from":66,"to":70}} {"id":100033720,"name":"Delete","signature":"func (m *MockInterface) Delete(ctx context.Context, resourceGroupName, networkSecurityGroupName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/mocksecuritygroupclient/interface.go","code":"// Delete mocks base method.\nfunc (m *MockInterface) Delete(ctx context.Context, resourceGroupName, networkSecurityGroupName string) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", ctx, resourceGroupName, networkSecurityGroupName)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":72,"to":78}} {"id":100033721,"name":"Delete","signature":"func (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, networkSecurityGroupName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/mocksecuritygroupclient/interface.go","code":"// Delete indicates an expected call of Delete.\nfunc (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, networkSecurityGroupName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Delete\", reflect.TypeOf((*MockInterface)(nil).Delete), ctx, resourceGroupName, networkSecurityGroupName)\n}","line":{"from":80,"to":84}} {"id":100033722,"name":"Get","signature":"func (m *MockInterface) Get(ctx context.Context, resourceGroupName, networkSecurityGroupName, expand string) (network.SecurityGroup, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/mocksecuritygroupclient/interface.go","code":"// Get mocks base method.\nfunc (m *MockInterface) Get(ctx context.Context, resourceGroupName, networkSecurityGroupName, expand string) (network.SecurityGroup, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", ctx, resourceGroupName, networkSecurityGroupName, expand)\n\tret0, _ := ret[0].(network.SecurityGroup)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":86,"to":93}} {"id":100033723,"name":"Get","signature":"func (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, networkSecurityGroupName, expand interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/mocksecuritygroupclient/interface.go","code":"// Get indicates an expected call of Get.\nfunc (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, networkSecurityGroupName, expand interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockInterface)(nil).Get), ctx, resourceGroupName, networkSecurityGroupName, expand)\n}","line":{"from":95,"to":99}} {"id":100033724,"name":"List","signature":"func (m *MockInterface) List(ctx context.Context, resourceGroupName string) ([]network.SecurityGroup, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/mocksecuritygroupclient/interface.go","code":"// List mocks base method.\nfunc (m *MockInterface) List(ctx context.Context, resourceGroupName string) ([]network.SecurityGroup, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", ctx, resourceGroupName)\n\tret0, _ := ret[0].([]network.SecurityGroup)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":101,"to":108}} {"id":100033725,"name":"List","signature":"func (mr *MockInterfaceMockRecorder) List(ctx, resourceGroupName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/mocksecuritygroupclient/interface.go","code":"// List indicates an expected call of List.\nfunc (mr *MockInterfaceMockRecorder) List(ctx, resourceGroupName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"List\", reflect.TypeOf((*MockInterface)(nil).List), ctx, resourceGroupName)\n}","line":{"from":110,"to":114}} {"id":100033726,"name":"New","signature":"func New(config *azclients.ClientConfig) *Client","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/azure_snapshotclient.go","code":"// New creates a new Snapshot client with ratelimiting.\nfunc New(config *azclients.ClientConfig) *Client {\n\tbaseURI := config.ResourceManagerEndpoint\n\tauthorizer := config.Authorizer\n\tarmClient := armclient.New(authorizer, baseURI, config.UserAgent, APIVersion, config.Location, config.Backoff)\n\trateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig)\n\n\tklog.V(2).Infof(\"Azure SnapshotClient (read ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPS,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucket)\n\tklog.V(2).Infof(\"Azure SnapshotClient (write ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPSWrite,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucketWrite)\n\n\tclient := \u0026Client{\n\t\tarmClient: armClient,\n\t\trateLimiterReader: rateLimiterReader,\n\t\trateLimiterWriter: rateLimiterWriter,\n\t\tsubscriptionID: config.SubscriptionID,\n\t}\n\n\treturn client\n}","line":{"from":57,"to":79}} {"id":100033727,"name":"Get","signature":"func (c *Client) Get(ctx context.Context, resourceGroupName string, snapshotName string) (compute.Snapshot, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/azure_snapshotclient.go","code":"// Get gets a Snapshot.\nfunc (c *Client) Get(ctx context.Context, resourceGroupName string, snapshotName string) (compute.Snapshot, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"snapshot\", \"get\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn compute.Snapshot{}, retry.GetRateLimitError(false, \"SnapshotGet\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"SnapshotGet\", \"client throttled\", c.RetryAfterReader)\n\t\treturn compute.Snapshot{}, rerr\n\t}\n\n\tresult, rerr := c.getSnapshot(ctx, resourceGroupName, snapshotName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":81,"to":110}} {"id":100033728,"name":"getSnapshot","signature":"func (c *Client) getSnapshot(ctx context.Context, resourceGroupName string, snapshotName string) (compute.Snapshot, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/azure_snapshotclient.go","code":"// getSnapshot gets a Snapshot.\nfunc (c *Client) getSnapshot(ctx context.Context, resourceGroupName string, snapshotName string) (compute.Snapshot, *retry.Error) {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Compute/snapshots\",\n\t\tsnapshotName,\n\t)\n\tresult := compute.Snapshot{}\n\n\tresponse, rerr := c.armClient.GetResource(ctx, resourceID, \"\")\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"snapshot.get.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\terr := autorest.Respond(\n\t\tresponse,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"snapshot.get.respond\", resourceID, err)\n\t\treturn result, retry.GetError(response, err)\n\t}\n\n\tresult.Response = autorest.Response{Response: response}\n\treturn result, nil\n}","line":{"from":112,"to":140}} {"id":100033729,"name":"Delete","signature":"func (c *Client) Delete(ctx context.Context, resourceGroupName string, snapshotName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/azure_snapshotclient.go","code":"// Delete deletes a Snapshot by name.\nfunc (c *Client) Delete(ctx context.Context, resourceGroupName string, snapshotName string) *retry.Error {\n\tmc := metrics.NewMetricContext(\"snapshot\", \"delete\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"SnapshotDelete\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"SnapshotDelete\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.deleteSnapshot(ctx, resourceGroupName, snapshotName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":142,"to":171}} {"id":100033730,"name":"deleteSnapshot","signature":"func (c *Client) deleteSnapshot(ctx context.Context, resourceGroupName string, snapshotName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/azure_snapshotclient.go","code":"// deleteSnapshot deletes a PublicIPAddress by name.\nfunc (c *Client) deleteSnapshot(ctx context.Context, resourceGroupName string, snapshotName string) *retry.Error {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Compute/snapshots\",\n\t\tsnapshotName,\n\t)\n\n\treturn c.armClient.DeleteResource(ctx, resourceID, \"\")\n}","line":{"from":173,"to":183}} {"id":100033731,"name":"CreateOrUpdate","signature":"func (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, snapshotName string, snapshot compute.Snapshot) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/azure_snapshotclient.go","code":"// CreateOrUpdate creates or updates a Snapshot.\nfunc (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, snapshotName string, snapshot compute.Snapshot) *retry.Error {\n\tmc := metrics.NewMetricContext(\"snapshot\", \"create_or_update\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"SnapshotCreateOrUpdate\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"SnapshotCreateOrUpdate\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.createOrUpdateSnapshot(ctx, resourceGroupName, snapshotName, snapshot)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":185,"to":214}} {"id":100033732,"name":"createOrUpdateSnapshot","signature":"func (c *Client) createOrUpdateSnapshot(ctx context.Context, resourceGroupName string, snapshotName string, snapshot compute.Snapshot) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/azure_snapshotclient.go","code":"// createOrUpdateSnapshot creates or updates a Snapshot.\nfunc (c *Client) createOrUpdateSnapshot(ctx context.Context, resourceGroupName string, snapshotName string, snapshot compute.Snapshot) *retry.Error {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Compute/snapshots\",\n\t\tsnapshotName,\n\t)\n\n\tresponse, rerr := c.armClient.PutResource(ctx, resourceID, snapshot)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"snapshot.put.request\", resourceID, rerr.Error())\n\t\treturn rerr\n\t}\n\n\tif response != nil \u0026\u0026 response.StatusCode != http.StatusNoContent {\n\t\t_, rerr = c.createOrUpdateResponder(response)\n\t\tif rerr != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"snapshot.put.respond\", resourceID, rerr.Error())\n\t\t\treturn rerr\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":216,"to":241}} {"id":100033733,"name":"createOrUpdateResponder","signature":"func (c *Client) createOrUpdateResponder(resp *http.Response) (*compute.Snapshot, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/azure_snapshotclient.go","code":"func (c *Client) createOrUpdateResponder(resp *http.Response) (*compute.Snapshot, *retry.Error) {\n\tresult := \u0026compute.Snapshot{}\n\terr := autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tresult.Response = autorest.Response{Response: resp}\n\treturn result, retry.GetError(resp, err)\n}","line":{"from":243,"to":251}} {"id":100033734,"name":"ListByResourceGroup","signature":"func (c *Client) ListByResourceGroup(ctx context.Context, resourceGroupName string) ([]compute.Snapshot, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/azure_snapshotclient.go","code":"// ListByResourceGroup get a list snapshots by resourceGroup.\nfunc (c *Client) ListByResourceGroup(ctx context.Context, resourceGroupName string) ([]compute.Snapshot, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"snapshot\", \"list_by_resource_group\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn nil, retry.GetRateLimitError(false, \"SnapshotListByResourceGroup\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"SnapshotListByResourceGroup\", \"client throttled\", c.RetryAfterReader)\n\t\treturn nil, rerr\n\t}\n\n\tresult, rerr := c.listSnapshotsByResourceGroup(ctx, resourceGroupName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":253,"to":282}} {"id":100033735,"name":"listSnapshotsByResourceGroup","signature":"func (c *Client) listSnapshotsByResourceGroup(ctx context.Context, resourceGroupName string) ([]compute.Snapshot, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/azure_snapshotclient.go","code":"// listSnapshotsByResourceGroup gets a list of snapshots in the resource group.\nfunc (c *Client) listSnapshotsByResourceGroup(ctx context.Context, resourceGroupName string) ([]compute.Snapshot, *retry.Error) {\n\tresourceID := fmt.Sprintf(\"/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/snapshots\",\n\t\tautorest.Encode(\"path\", c.subscriptionID),\n\t\tautorest.Encode(\"path\", resourceGroupName))\n\tresult := make([]compute.Snapshot, 0)\n\tpage := \u0026SnapshotListPage{}\n\tpage.fn = c.listNextResults\n\n\tresp, rerr := c.armClient.GetResource(ctx, resourceID, \"\")\n\tdefer c.armClient.CloseResponse(ctx, resp)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"snapshot.list.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\tvar err error\n\tpage.sl, err = c.listResponder(resp)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"snapshot.list.respond\", resourceID, err)\n\t\treturn result, retry.GetError(resp, err)\n\t}\n\n\tfor {\n\t\tresult = append(result, page.Values()...)\n\n\t\t// Abort the loop when there's no nextLink in the response.\n\t\tif pointer.StringDeref(page.Response().NextLink, \"\") == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\tif err = page.NextWithContext(ctx); err != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"snapshot.list.next\", resourceID, err)\n\t\t\treturn result, retry.GetError(page.Response().Response.Response, err)\n\t\t}\n\t}\n\n\treturn result, nil\n}","line":{"from":284,"to":322}} {"id":100033736,"name":"listResponder","signature":"func (c *Client) listResponder(resp *http.Response) (result compute.SnapshotList, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/azure_snapshotclient.go","code":"func (c *Client) listResponder(resp *http.Response) (result compute.SnapshotList, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tautorest.ByIgnoring(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}","line":{"from":324,"to":332}} {"id":100033737,"name":"SnapshotListResultPreparer","signature":"func (c *Client) SnapshotListResultPreparer(ctx context.Context, lr compute.SnapshotList) (*http.Request, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/azure_snapshotclient.go","code":"// SnapshotListResultPreparer prepares a request to retrieve the next set of results.\n// It returns nil if no more results exist.\nfunc (c *Client) SnapshotListResultPreparer(ctx context.Context, lr compute.SnapshotList) (*http.Request, error) {\n\tif lr.NextLink == nil || len(pointer.StringDeref(lr.NextLink, \"\")) \u003c 1 {\n\t\treturn nil, nil\n\t}\n\n\tdecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithBaseURL(pointer.StringDeref(lr.NextLink, \"\")),\n\t}\n\treturn c.armClient.PrepareGetRequest(ctx, decorators...)\n}","line":{"from":334,"to":345}} {"id":100033738,"name":"listNextResults","signature":"func (c *Client) listNextResults(ctx context.Context, lastResults compute.SnapshotList) (result compute.SnapshotList, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/azure_snapshotclient.go","code":"// listNextResults retrieves the next set of results, if any.\nfunc (c *Client) listNextResults(ctx context.Context, lastResults compute.SnapshotList) (result compute.SnapshotList, err error) {\n\treq, err := c.SnapshotListResultPreparer(ctx, lastResults)\n\tif err != nil {\n\t\treturn result, autorest.NewErrorWithError(err, \"snapshotclient\", \"listNextResults\", nil, \"Failure preparing next results request\")\n\t}\n\tif req == nil {\n\t\treturn\n\t}\n\n\tresp, rerr := c.armClient.Send(ctx, req)\n\tdefer c.armClient.CloseResponse(ctx, resp)\n\tif rerr != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\treturn result, autorest.NewErrorWithError(rerr.Error(), \"snapshotclient\", \"listNextResults\", resp, \"Failure sending next results request\")\n\t}\n\n\tresult, err = c.listResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"snapshotclient\", \"listNextResults\", resp, \"Failure responding to next results request\")\n\t}\n\n\treturn\n}","line":{"from":347,"to":370}} {"id":100033739,"name":"NextWithContext","signature":"func (page *SnapshotListPage) NextWithContext(ctx context.Context) (err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/azure_snapshotclient.go","code":"// NextWithContext advances to the next page of values. If there was an error making\n// the request the page does not advance and the error is returned.\nfunc (page *SnapshotListPage) NextWithContext(ctx context.Context) (err error) {\n\tnext, err := page.fn(ctx, page.sl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.sl = next\n\treturn nil\n}","line":{"from":378,"to":387}} {"id":100033740,"name":"Next","signature":"func (page *SnapshotListPage) Next() error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/azure_snapshotclient.go","code":"// Next advances to the next page of values. If there was an error making\n// the request the page does not advance and the error is returned.\n// Deprecated: Use NextWithContext() instead.\nfunc (page *SnapshotListPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}","line":{"from":389,"to":394}} {"id":100033741,"name":"NotDone","signature":"func (page SnapshotListPage) NotDone() bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/azure_snapshotclient.go","code":"// NotDone returns true if the page enumeration should be started or is not yet complete.\nfunc (page SnapshotListPage) NotDone() bool {\n\treturn !page.sl.IsEmpty()\n}","line":{"from":396,"to":399}} {"id":100033742,"name":"Response","signature":"func (page SnapshotListPage) Response() compute.SnapshotList","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/azure_snapshotclient.go","code":"// Response returns the raw server response from the last page request.\nfunc (page SnapshotListPage) Response() compute.SnapshotList {\n\treturn page.sl\n}","line":{"from":401,"to":404}} {"id":100033743,"name":"Values","signature":"func (page SnapshotListPage) Values() []compute.Snapshot","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/azure_snapshotclient.go","code":"// Values returns the slice of values for the current page or nil if there are no values.\nfunc (page SnapshotListPage) Values() []compute.Snapshot {\n\tif page.sl.IsEmpty() {\n\t\treturn nil\n\t}\n\treturn *page.sl.Value\n}","line":{"from":406,"to":412}} {"id":100033744,"name":"NewMockInterface","signature":"func NewMockInterface(ctrl *gomock.Controller) *MockInterface","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/mocksnapshotclient/interface.go","code":"// NewMockInterface creates a new mock instance.\nfunc NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := \u0026MockInterface{ctrl: ctrl}\n\tmock.recorder = \u0026MockInterfaceMockRecorder{mock}\n\treturn mock\n}","line":{"from":46,"to":51}} {"id":100033745,"name":"EXPECT","signature":"func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/mocksnapshotclient/interface.go","code":"// EXPECT returns an object that allows the caller to indicate expected use.\nfunc (m *MockInterface) EXPECT() *MockInterfaceMockRecorder {\n\treturn m.recorder\n}","line":{"from":53,"to":56}} {"id":100033746,"name":"CreateOrUpdate","signature":"func (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, snapshotName string, snapshot compute.Snapshot) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/mocksnapshotclient/interface.go","code":"// CreateOrUpdate mocks base method.\nfunc (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, snapshotName string, snapshot compute.Snapshot) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateOrUpdate\", ctx, resourceGroupName, snapshotName, snapshot)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":58,"to":64}} {"id":100033747,"name":"CreateOrUpdate","signature":"func (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, snapshotName, snapshot interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/mocksnapshotclient/interface.go","code":"// CreateOrUpdate indicates an expected call of CreateOrUpdate.\nfunc (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, snapshotName, snapshot interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateOrUpdate\", reflect.TypeOf((*MockInterface)(nil).CreateOrUpdate), ctx, resourceGroupName, snapshotName, snapshot)\n}","line":{"from":66,"to":70}} {"id":100033748,"name":"Delete","signature":"func (m *MockInterface) Delete(ctx context.Context, resourceGroupName, snapshotName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/mocksnapshotclient/interface.go","code":"// Delete mocks base method.\nfunc (m *MockInterface) Delete(ctx context.Context, resourceGroupName, snapshotName string) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", ctx, resourceGroupName, snapshotName)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":72,"to":78}} {"id":100033749,"name":"Delete","signature":"func (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, snapshotName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/mocksnapshotclient/interface.go","code":"// Delete indicates an expected call of Delete.\nfunc (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, snapshotName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Delete\", reflect.TypeOf((*MockInterface)(nil).Delete), ctx, resourceGroupName, snapshotName)\n}","line":{"from":80,"to":84}} {"id":100033750,"name":"Get","signature":"func (m *MockInterface) Get(ctx context.Context, resourceGroupName, snapshotName string) (compute.Snapshot, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/mocksnapshotclient/interface.go","code":"// Get mocks base method.\nfunc (m *MockInterface) Get(ctx context.Context, resourceGroupName, snapshotName string) (compute.Snapshot, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", ctx, resourceGroupName, snapshotName)\n\tret0, _ := ret[0].(compute.Snapshot)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":86,"to":93}} {"id":100033751,"name":"Get","signature":"func (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, snapshotName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/mocksnapshotclient/interface.go","code":"// Get indicates an expected call of Get.\nfunc (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, snapshotName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockInterface)(nil).Get), ctx, resourceGroupName, snapshotName)\n}","line":{"from":95,"to":99}} {"id":100033752,"name":"ListByResourceGroup","signature":"func (m *MockInterface) ListByResourceGroup(ctx context.Context, resourceGroupName string) ([]compute.Snapshot, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/mocksnapshotclient/interface.go","code":"// ListByResourceGroup mocks base method.\nfunc (m *MockInterface) ListByResourceGroup(ctx context.Context, resourceGroupName string) ([]compute.Snapshot, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListByResourceGroup\", ctx, resourceGroupName)\n\tret0, _ := ret[0].([]compute.Snapshot)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":101,"to":108}} {"id":100033753,"name":"ListByResourceGroup","signature":"func (mr *MockInterfaceMockRecorder) ListByResourceGroup(ctx, resourceGroupName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/snapshotclient/mocksnapshotclient/interface.go","code":"// ListByResourceGroup indicates an expected call of ListByResourceGroup.\nfunc (mr *MockInterfaceMockRecorder) ListByResourceGroup(ctx, resourceGroupName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ListByResourceGroup\", reflect.TypeOf((*MockInterface)(nil).ListByResourceGroup), ctx, resourceGroupName)\n}","line":{"from":110,"to":114}} {"id":100033754,"name":"New","signature":"func New(config *azclients.ClientConfig) *Client","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/azure_storageaccountclient.go","code":"// New creates a new StorageAccount client with ratelimiting.\nfunc New(config *azclients.ClientConfig) *Client {\n\tbaseURI := config.ResourceManagerEndpoint\n\tauthorizer := config.Authorizer\n\tapiVersion := APIVersion\n\tif strings.EqualFold(config.CloudName, AzureStackCloudName) {\n\t\tapiVersion = AzureStackCloudAPIVersion\n\t}\n\tarmClient := armclient.New(authorizer, baseURI, config.UserAgent, apiVersion, config.Location, config.Backoff)\n\trateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig)\n\n\tklog.V(2).Infof(\"Azure StorageAccountClient (read ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPS,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucket)\n\tklog.V(2).Infof(\"Azure StorageAccountClient (write ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPSWrite,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucketWrite)\n\n\tclient := \u0026Client{\n\t\tarmClient: armClient,\n\t\trateLimiterReader: rateLimiterReader,\n\t\trateLimiterWriter: rateLimiterWriter,\n\t\tsubscriptionID: config.SubscriptionID,\n\t}\n\n\treturn client\n}","line":{"from":58,"to":84}} {"id":100033755,"name":"GetProperties","signature":"func (c *Client) GetProperties(ctx context.Context, resourceGroupName string, accountName string) (storage.Account, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/azure_storageaccountclient.go","code":"// GetProperties gets properties of the StorageAccount.\nfunc (c *Client) GetProperties(ctx context.Context, resourceGroupName string, accountName string) (storage.Account, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"storage_account\", \"get\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn storage.Account{}, retry.GetRateLimitError(false, \"StorageAccountGet\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"StorageAccountGet\", \"client throttled\", c.RetryAfterReader)\n\t\treturn storage.Account{}, rerr\n\t}\n\n\tresult, rerr := c.getStorageAccount(ctx, resourceGroupName, accountName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":86,"to":115}} {"id":100033756,"name":"getStorageAccount","signature":"func (c *Client) getStorageAccount(ctx context.Context, resourceGroupName string, accountName string) (storage.Account, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/azure_storageaccountclient.go","code":"// getStorageAccount gets properties of the StorageAccount.\nfunc (c *Client) getStorageAccount(ctx context.Context, resourceGroupName string, accountName string) (storage.Account, *retry.Error) {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Storage/storageAccounts\",\n\t\taccountName,\n\t)\n\tresult := storage.Account{}\n\n\tresponse, rerr := c.armClient.GetResource(ctx, resourceID, \"\")\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"storageaccount.get.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\terr := autorest.Respond(\n\t\tresponse,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"storageaccount.get.respond\", resourceID, err)\n\t\treturn result, retry.GetError(response, err)\n\t}\n\n\tresult.Response = autorest.Response{Response: response}\n\treturn result, nil\n}","line":{"from":117,"to":145}} {"id":100033757,"name":"ListKeys","signature":"func (c *Client) ListKeys(ctx context.Context, resourceGroupName string, accountName string) (storage.AccountListKeysResult, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/azure_storageaccountclient.go","code":"// ListKeys get a list of storage account keys.\nfunc (c *Client) ListKeys(ctx context.Context, resourceGroupName string, accountName string) (storage.AccountListKeysResult, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"storage_account\", \"list_keys\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn storage.AccountListKeysResult{}, retry.GetRateLimitError(false, \"StorageAccountListKeys\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"StorageAccountListKeys\", \"client throttled\", c.RetryAfterReader)\n\t\treturn storage.AccountListKeysResult{}, rerr\n\t}\n\n\tresult, rerr := c.listStorageAccountKeys(ctx, resourceGroupName, accountName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":147,"to":176}} {"id":100033758,"name":"listStorageAccountKeys","signature":"func (c *Client) listStorageAccountKeys(ctx context.Context, resourceGroupName string, accountName string) (storage.AccountListKeysResult, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/azure_storageaccountclient.go","code":"// listStorageAccountKeys get a list of storage account keys.\nfunc (c *Client) listStorageAccountKeys(ctx context.Context, resourceGroupName string, accountName string) (storage.AccountListKeysResult, *retry.Error) {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Storage/storageAccounts\",\n\t\taccountName,\n\t)\n\n\tresult := storage.AccountListKeysResult{}\n\tresponse, rerr := c.armClient.PostResource(ctx, resourceID, \"listKeys\", struct{}{})\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"storageaccount.listkeys.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\terr := autorest.Respond(\n\t\tresponse,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"storageaccount.listkeys.respond\", resourceID, err)\n\t\treturn result, retry.GetError(response, err)\n\t}\n\n\tresult.Response = autorest.Response{Response: response}\n\treturn result, nil\n}","line":{"from":178,"to":206}} {"id":100033759,"name":"Create","signature":"func (c *Client) Create(ctx context.Context, resourceGroupName string, accountName string, parameters storage.AccountCreateParameters) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/azure_storageaccountclient.go","code":"// Create creates a StorageAccount.\nfunc (c *Client) Create(ctx context.Context, resourceGroupName string, accountName string, parameters storage.AccountCreateParameters) *retry.Error {\n\tmc := metrics.NewMetricContext(\"storage_account\", \"create\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"StorageAccountCreate\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"StorageAccountCreate\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.createStorageAccount(ctx, resourceGroupName, accountName, parameters)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":208,"to":237}} {"id":100033760,"name":"createStorageAccount","signature":"func (c *Client) createStorageAccount(ctx context.Context, resourceGroupName string, accountName string, parameters storage.AccountCreateParameters) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/azure_storageaccountclient.go","code":"// createStorageAccount creates or updates a StorageAccount.\nfunc (c *Client) createStorageAccount(ctx context.Context, resourceGroupName string, accountName string, parameters storage.AccountCreateParameters) *retry.Error {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Storage/storageAccounts\",\n\t\taccountName,\n\t)\n\n\tresponse, rerr := c.armClient.PutResource(ctx, resourceID, parameters)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"storageAccount.put.request\", resourceID, rerr.Error())\n\t\treturn rerr\n\t}\n\n\tif response != nil \u0026\u0026 response.StatusCode != http.StatusNoContent {\n\t\t_, rerr = c.createResponder(response)\n\t\tif rerr != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"storageAccount.put.respond\", resourceID, rerr.Error())\n\t\t\treturn rerr\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":239,"to":264}} {"id":100033761,"name":"createResponder","signature":"func (c *Client) createResponder(resp *http.Response) (*storage.Account, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/azure_storageaccountclient.go","code":"func (c *Client) createResponder(resp *http.Response) (*storage.Account, *retry.Error) {\n\tresult := \u0026storage.Account{}\n\terr := autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tresult.Response = autorest.Response{Response: resp}\n\treturn result, retry.GetError(resp, err)\n}","line":{"from":266,"to":274}} {"id":100033762,"name":"Delete","signature":"func (c *Client) Delete(ctx context.Context, resourceGroupName string, accountName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/azure_storageaccountclient.go","code":"// Delete deletes a StorageAccount by name.\nfunc (c *Client) Delete(ctx context.Context, resourceGroupName string, accountName string) *retry.Error {\n\tmc := metrics.NewMetricContext(\"storage_account\", \"delete\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"StorageAccountDelete\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"StorageAccountDelete\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.deleteStorageAccount(ctx, resourceGroupName, accountName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":276,"to":305}} {"id":100033763,"name":"deleteStorageAccount","signature":"func (c *Client) deleteStorageAccount(ctx context.Context, resourceGroupName string, accountName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/azure_storageaccountclient.go","code":"// deleteStorageAccount deletes a PublicIPAddress by name.\nfunc (c *Client) deleteStorageAccount(ctx context.Context, resourceGroupName string, accountName string) *retry.Error {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Storage/storageAccounts\",\n\t\taccountName,\n\t)\n\n\treturn c.armClient.DeleteResource(ctx, resourceID, \"\")\n}","line":{"from":307,"to":317}} {"id":100033764,"name":"ListByResourceGroup","signature":"func (c *Client) ListByResourceGroup(ctx context.Context, resourceGroupName string) ([]storage.Account, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/azure_storageaccountclient.go","code":"// ListByResourceGroup get a list storage accounts by resourceGroup.\nfunc (c *Client) ListByResourceGroup(ctx context.Context, resourceGroupName string) ([]storage.Account, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"storage_account\", \"list_by_resource_group\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn nil, retry.GetRateLimitError(false, \"StorageAccountListByResourceGroup\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"StorageAccountListByResourceGroup\", \"client throttled\", c.RetryAfterReader)\n\t\treturn nil, rerr\n\t}\n\n\tresult, rerr := c.ListStorageAccountByResourceGroup(ctx, resourceGroupName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":319,"to":348}} {"id":100033765,"name":"ListStorageAccountByResourceGroup","signature":"func (c *Client) ListStorageAccountByResourceGroup(ctx context.Context, resourceGroupName string) ([]storage.Account, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/azure_storageaccountclient.go","code":"// ListStorageAccountByResourceGroup get a list storage accounts by resourceGroup.\nfunc (c *Client) ListStorageAccountByResourceGroup(ctx context.Context, resourceGroupName string) ([]storage.Account, *retry.Error) {\n\tresourceID := fmt.Sprintf(\"/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Storage/storageAccounts\",\n\t\tautorest.Encode(\"path\", c.subscriptionID),\n\t\tautorest.Encode(\"path\", resourceGroupName))\n\tresult := make([]storage.Account, 0)\n\tpage := \u0026AccountListResultPage{}\n\tpage.fn = c.listNextResults\n\n\tresp, rerr := c.armClient.GetResource(ctx, resourceID, \"\")\n\tdefer c.armClient.CloseResponse(ctx, resp)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"storageAccount.list.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\tvar err error\n\tpage.alr, err = c.listResponder(resp)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"storageAccount.list.respond\", resourceID, err)\n\t\treturn result, retry.GetError(resp, err)\n\t}\n\n\tfor {\n\t\tresult = append(result, page.Values()...)\n\n\t\t// Abort the loop when there's no nextLink in the response.\n\t\tif pointer.StringDeref(page.Response().NextLink, \"\") == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\tif err = page.NextWithContext(ctx); err != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"storageAccount.list.next\", resourceID, err)\n\t\t\treturn result, retry.GetError(page.Response().Response.Response, err)\n\t\t}\n\t}\n\n\treturn result, nil\n}","line":{"from":350,"to":388}} {"id":100033766,"name":"listResponder","signature":"func (c *Client) listResponder(resp *http.Response) (result storage.AccountListResult, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/azure_storageaccountclient.go","code":"func (c *Client) listResponder(resp *http.Response) (result storage.AccountListResult, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tautorest.ByIgnoring(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}","line":{"from":390,"to":398}} {"id":100033767,"name":"StorageAccountResultPreparer","signature":"func (c *Client) StorageAccountResultPreparer(ctx context.Context, lr storage.AccountListResult) (*http.Request, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/azure_storageaccountclient.go","code":"// StorageAccountResultPreparer prepares a request to retrieve the next set of results.\n// It returns nil if no more results exist.\nfunc (c *Client) StorageAccountResultPreparer(ctx context.Context, lr storage.AccountListResult) (*http.Request, error) {\n\tif lr.NextLink == nil || len(pointer.StringDeref(lr.NextLink, \"\")) \u003c 1 {\n\t\treturn nil, nil\n\t}\n\n\tdecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithBaseURL(pointer.StringDeref(lr.NextLink, \"\")),\n\t}\n\treturn c.armClient.PrepareGetRequest(ctx, decorators...)\n}","line":{"from":400,"to":411}} {"id":100033768,"name":"listNextResults","signature":"func (c *Client) listNextResults(ctx context.Context, lastResults storage.AccountListResult) (result storage.AccountListResult, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/azure_storageaccountclient.go","code":"// listNextResults retrieves the next set of results, if any.\nfunc (c *Client) listNextResults(ctx context.Context, lastResults storage.AccountListResult) (result storage.AccountListResult, err error) {\n\treq, err := c.StorageAccountResultPreparer(ctx, lastResults)\n\tif err != nil {\n\t\treturn result, autorest.NewErrorWithError(err, \"storageaccount\", \"listNextResults\", nil, \"Failure preparing next results request\")\n\t}\n\tif req == nil {\n\t\treturn\n\t}\n\n\tresp, rerr := c.armClient.Send(ctx, req)\n\tdefer c.armClient.CloseResponse(ctx, resp)\n\tif rerr != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\treturn result, autorest.NewErrorWithError(rerr.Error(), \"storageaccount\", \"listNextResults\", resp, \"Failure sending next results request\")\n\t}\n\n\tresult, err = c.listResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"storageaccount\", \"listNextResults\", resp, \"Failure responding to next results request\")\n\t}\n\n\treturn\n}","line":{"from":413,"to":436}} {"id":100033769,"name":"NextWithContext","signature":"func (page *AccountListResultPage) NextWithContext(ctx context.Context) (err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/azure_storageaccountclient.go","code":"// NextWithContext advances to the next page of values. If there was an error making\n// the request the page does not advance and the error is returned.\nfunc (page *AccountListResultPage) NextWithContext(ctx context.Context) (err error) {\n\tnext, err := page.fn(ctx, page.alr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.alr = next\n\treturn nil\n}","line":{"from":444,"to":453}} {"id":100033770,"name":"Next","signature":"func (page *AccountListResultPage) Next() error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/azure_storageaccountclient.go","code":"// Next advances to the next page of values. If there was an error making\n// the request the page does not advance and the error is returned.\n// Deprecated: Use NextWithContext() instead.\nfunc (page *AccountListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}","line":{"from":455,"to":460}} {"id":100033771,"name":"NotDone","signature":"func (page AccountListResultPage) NotDone() bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/azure_storageaccountclient.go","code":"// NotDone returns true if the page enumeration should be started or is not yet complete.\nfunc (page AccountListResultPage) NotDone() bool {\n\treturn !page.alr.IsEmpty()\n}","line":{"from":462,"to":465}} {"id":100033772,"name":"Response","signature":"func (page AccountListResultPage) Response() storage.AccountListResult","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/azure_storageaccountclient.go","code":"// Response returns the raw server response from the last page request.\nfunc (page AccountListResultPage) Response() storage.AccountListResult {\n\treturn page.alr\n}","line":{"from":467,"to":470}} {"id":100033773,"name":"Values","signature":"func (page AccountListResultPage) Values() []storage.Account","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/azure_storageaccountclient.go","code":"// Values returns the slice of values for the current page or nil if there are no values.\nfunc (page AccountListResultPage) Values() []storage.Account {\n\tif page.alr.IsEmpty() {\n\t\treturn nil\n\t}\n\treturn *page.alr.Value\n}","line":{"from":472,"to":478}} {"id":100033774,"name":"NewMockInterface","signature":"func NewMockInterface(ctrl *gomock.Controller) *MockInterface","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/mockstorageaccountclient/interface.go","code":"// NewMockInterface creates a new mock instance.\nfunc NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := \u0026MockInterface{ctrl: ctrl}\n\tmock.recorder = \u0026MockInterfaceMockRecorder{mock}\n\treturn mock\n}","line":{"from":46,"to":51}} {"id":100033775,"name":"EXPECT","signature":"func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/mockstorageaccountclient/interface.go","code":"// EXPECT returns an object that allows the caller to indicate expected use.\nfunc (m *MockInterface) EXPECT() *MockInterfaceMockRecorder {\n\treturn m.recorder\n}","line":{"from":53,"to":56}} {"id":100033776,"name":"Create","signature":"func (m *MockInterface) Create(ctx context.Context, resourceGroupName, accountName string, parameters storage.AccountCreateParameters) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/mockstorageaccountclient/interface.go","code":"// Create mocks base method.\nfunc (m *MockInterface) Create(ctx context.Context, resourceGroupName, accountName string, parameters storage.AccountCreateParameters) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Create\", ctx, resourceGroupName, accountName, parameters)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":58,"to":64}} {"id":100033777,"name":"Create","signature":"func (mr *MockInterfaceMockRecorder) Create(ctx, resourceGroupName, accountName, parameters interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/mockstorageaccountclient/interface.go","code":"// Create indicates an expected call of Create.\nfunc (mr *MockInterfaceMockRecorder) Create(ctx, resourceGroupName, accountName, parameters interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Create\", reflect.TypeOf((*MockInterface)(nil).Create), ctx, resourceGroupName, accountName, parameters)\n}","line":{"from":66,"to":70}} {"id":100033778,"name":"Delete","signature":"func (m *MockInterface) Delete(ctx context.Context, resourceGroupName, accountName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/mockstorageaccountclient/interface.go","code":"// Delete mocks base method.\nfunc (m *MockInterface) Delete(ctx context.Context, resourceGroupName, accountName string) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", ctx, resourceGroupName, accountName)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":72,"to":78}} {"id":100033779,"name":"Delete","signature":"func (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, accountName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/mockstorageaccountclient/interface.go","code":"// Delete indicates an expected call of Delete.\nfunc (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, accountName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Delete\", reflect.TypeOf((*MockInterface)(nil).Delete), ctx, resourceGroupName, accountName)\n}","line":{"from":80,"to":84}} {"id":100033780,"name":"GetProperties","signature":"func (m *MockInterface) GetProperties(ctx context.Context, resourceGroupName, accountName string) (storage.Account, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/mockstorageaccountclient/interface.go","code":"// GetProperties mocks base method.\nfunc (m *MockInterface) GetProperties(ctx context.Context, resourceGroupName, accountName string) (storage.Account, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetProperties\", ctx, resourceGroupName, accountName)\n\tret0, _ := ret[0].(storage.Account)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":86,"to":93}} {"id":100033781,"name":"GetProperties","signature":"func (mr *MockInterfaceMockRecorder) GetProperties(ctx, resourceGroupName, accountName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/mockstorageaccountclient/interface.go","code":"// GetProperties indicates an expected call of GetProperties.\nfunc (mr *MockInterfaceMockRecorder) GetProperties(ctx, resourceGroupName, accountName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetProperties\", reflect.TypeOf((*MockInterface)(nil).GetProperties), ctx, resourceGroupName, accountName)\n}","line":{"from":95,"to":99}} {"id":100033782,"name":"ListByResourceGroup","signature":"func (m *MockInterface) ListByResourceGroup(ctx context.Context, resourceGroupName string) ([]storage.Account, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/mockstorageaccountclient/interface.go","code":"// ListByResourceGroup mocks base method.\nfunc (m *MockInterface) ListByResourceGroup(ctx context.Context, resourceGroupName string) ([]storage.Account, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListByResourceGroup\", ctx, resourceGroupName)\n\tret0, _ := ret[0].([]storage.Account)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":101,"to":108}} {"id":100033783,"name":"ListByResourceGroup","signature":"func (mr *MockInterfaceMockRecorder) ListByResourceGroup(ctx, resourceGroupName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/mockstorageaccountclient/interface.go","code":"// ListByResourceGroup indicates an expected call of ListByResourceGroup.\nfunc (mr *MockInterfaceMockRecorder) ListByResourceGroup(ctx, resourceGroupName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ListByResourceGroup\", reflect.TypeOf((*MockInterface)(nil).ListByResourceGroup), ctx, resourceGroupName)\n}","line":{"from":110,"to":114}} {"id":100033784,"name":"ListKeys","signature":"func (m *MockInterface) ListKeys(ctx context.Context, resourceGroupName, accountName string) (storage.AccountListKeysResult, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/mockstorageaccountclient/interface.go","code":"// ListKeys mocks base method.\nfunc (m *MockInterface) ListKeys(ctx context.Context, resourceGroupName, accountName string) (storage.AccountListKeysResult, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListKeys\", ctx, resourceGroupName, accountName)\n\tret0, _ := ret[0].(storage.AccountListKeysResult)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":116,"to":123}} {"id":100033785,"name":"ListKeys","signature":"func (mr *MockInterfaceMockRecorder) ListKeys(ctx, resourceGroupName, accountName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/mockstorageaccountclient/interface.go","code":"// ListKeys indicates an expected call of ListKeys.\nfunc (mr *MockInterfaceMockRecorder) ListKeys(ctx, resourceGroupName, accountName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ListKeys\", reflect.TypeOf((*MockInterface)(nil).ListKeys), ctx, resourceGroupName, accountName)\n}","line":{"from":125,"to":129}} {"id":100033786,"name":"New","signature":"func New(config *azclients.ClientConfig) *Client","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/azure_subnetclient.go","code":"// New creates a new Subnet client with ratelimiting.\nfunc New(config *azclients.ClientConfig) *Client {\n\tbaseURI := config.ResourceManagerEndpoint\n\tauthorizer := config.Authorizer\n\tarmClient := armclient.New(authorizer, baseURI, config.UserAgent, APIVersion, config.Location, config.Backoff)\n\trateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig)\n\n\tklog.V(2).Infof(\"Azure SubnetsClient (read ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPS,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucket)\n\tklog.V(2).Infof(\"Azure SubnetsClient (write ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPSWrite,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucketWrite)\n\n\tclient := \u0026Client{\n\t\tarmClient: armClient,\n\t\trateLimiterReader: rateLimiterReader,\n\t\trateLimiterWriter: rateLimiterWriter,\n\t\tsubscriptionID: config.SubscriptionID,\n\t}\n\n\treturn client\n}","line":{"from":56,"to":78}} {"id":100033787,"name":"Get","signature":"func (c *Client) Get(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, expand string) (network.Subnet, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/azure_subnetclient.go","code":"// Get gets a Subnet.\nfunc (c *Client) Get(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, expand string) (network.Subnet, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"subnets\", \"get\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn network.Subnet{}, retry.GetRateLimitError(false, \"SubnetGet\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"SubnetGet\", \"client throttled\", c.RetryAfterReader)\n\t\treturn network.Subnet{}, rerr\n\t}\n\n\tresult, rerr := c.getSubnet(ctx, resourceGroupName, virtualNetworkName, subnetName, expand)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":80,"to":109}} {"id":100033788,"name":"getSubnet","signature":"func (c *Client) getSubnet(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, expand string) (network.Subnet, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/azure_subnetclient.go","code":"// getSubnet gets a Subnet.\nfunc (c *Client) getSubnet(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, expand string) (network.Subnet, *retry.Error) {\n\tresourceID := armclient.GetChildResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Network/virtualNetworks\",\n\t\tvirtualNetworkName,\n\t\t\"subnets\",\n\t\tsubnetName,\n\t)\n\tresult := network.Subnet{}\n\n\tresponse, rerr := c.armClient.GetResource(ctx, resourceID, expand)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"subnet.get.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\terr := autorest.Respond(\n\t\tresponse,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"subnet.get.respond\", resourceID, err)\n\t\treturn result, retry.GetError(response, err)\n\t}\n\n\tresult.Response = autorest.Response{Response: response}\n\treturn result, nil\n}","line":{"from":111,"to":141}} {"id":100033789,"name":"List","signature":"func (c *Client) List(ctx context.Context, resourceGroupName string, virtualNetworkName string) ([]network.Subnet, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/azure_subnetclient.go","code":"// List gets a list of Subnets in the VNet.\nfunc (c *Client) List(ctx context.Context, resourceGroupName string, virtualNetworkName string) ([]network.Subnet, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"subnets\", \"list\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn nil, retry.GetRateLimitError(false, \"SubnetList\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"SubnetList\", \"client throttled\", c.RetryAfterReader)\n\t\treturn nil, rerr\n\t}\n\n\tresult, rerr := c.listSubnet(ctx, resourceGroupName, virtualNetworkName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":143,"to":172}} {"id":100033790,"name":"listSubnet","signature":"func (c *Client) listSubnet(ctx context.Context, resourceGroupName string, virtualNetworkName string) ([]network.Subnet, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/azure_subnetclient.go","code":"// listSubnet gets a list of Subnets in the VNet.\nfunc (c *Client) listSubnet(ctx context.Context, resourceGroupName string, virtualNetworkName string) ([]network.Subnet, *retry.Error) {\n\tresourceID := armclient.GetChildResourcesListID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Network/virtualNetworks\",\n\t\tvirtualNetworkName,\n\t\t\"subnets\")\n\n\tresult := make([]network.Subnet, 0)\n\tpage := \u0026SubnetListResultPage{}\n\tpage.fn = c.listNextResults\n\n\tresp, rerr := c.armClient.GetResource(ctx, resourceID, \"\")\n\tdefer c.armClient.CloseResponse(ctx, resp)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"subnet.list.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\tvar err error\n\tpage.slr, err = c.listResponder(resp)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"subnet.list.respond\", resourceID, err)\n\t\treturn result, retry.GetError(resp, err)\n\t}\n\n\tfor {\n\t\tresult = append(result, page.Values()...)\n\n\t\t// Abort the loop when there's no nextLink in the response.\n\t\tif pointer.StringDeref(page.Response().NextLink, \"\") == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\tif err = page.NextWithContext(ctx); err != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"subnet.list.next\", resourceID, err)\n\t\t\treturn result, retry.GetError(page.Response().Response.Response, err)\n\t\t}\n\t}\n\n\treturn result, nil\n}","line":{"from":174,"to":216}} {"id":100033791,"name":"CreateOrUpdate","signature":"func (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, subnetParameters network.Subnet) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/azure_subnetclient.go","code":"// CreateOrUpdate creates or updates a Subnet.\nfunc (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, subnetParameters network.Subnet) *retry.Error {\n\tmc := metrics.NewMetricContext(\"subnets\", \"create_or_update\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"SubnetCreateOrUpdate\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"SubnetCreateOrUpdate\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.createOrUpdateSubnet(ctx, resourceGroupName, virtualNetworkName, subnetName, subnetParameters)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":218,"to":247}} {"id":100033792,"name":"createOrUpdateSubnet","signature":"func (c *Client) createOrUpdateSubnet(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, subnetParameters network.Subnet) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/azure_subnetclient.go","code":"// createOrUpdateSubnet creates or updates a Subnet.\nfunc (c *Client) createOrUpdateSubnet(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string, subnetParameters network.Subnet) *retry.Error {\n\tresourceID := armclient.GetChildResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Network/virtualNetworks\",\n\t\tvirtualNetworkName,\n\t\t\"subnets\",\n\t\tsubnetName)\n\n\tresponse, rerr := c.armClient.PutResource(ctx, resourceID, subnetParameters)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"subnet.put.request\", resourceID, rerr.Error())\n\t\treturn rerr\n\t}\n\n\tif response != nil \u0026\u0026 response.StatusCode != http.StatusNoContent {\n\t\t_, rerr = c.createOrUpdateResponder(response)\n\t\tif rerr != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"subnet.put.respond\", resourceID, rerr.Error())\n\t\t\treturn rerr\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":249,"to":275}} {"id":100033793,"name":"createOrUpdateResponder","signature":"func (c *Client) createOrUpdateResponder(resp *http.Response) (*network.Subnet, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/azure_subnetclient.go","code":"func (c *Client) createOrUpdateResponder(resp *http.Response) (*network.Subnet, *retry.Error) {\n\tresult := \u0026network.Subnet{}\n\terr := autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tresult.Response = autorest.Response{Response: resp}\n\treturn result, retry.GetError(resp, err)\n}","line":{"from":277,"to":285}} {"id":100033794,"name":"Delete","signature":"func (c *Client) Delete(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/azure_subnetclient.go","code":"// Delete deletes a Subnet by name.\nfunc (c *Client) Delete(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string) *retry.Error {\n\tmc := metrics.NewMetricContext(\"subnets\", \"delete\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"SubnetDelete\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"SubnetDelete\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.deleteSubnet(ctx, resourceGroupName, virtualNetworkName, subnetName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":287,"to":316}} {"id":100033795,"name":"deleteSubnet","signature":"func (c *Client) deleteSubnet(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/azure_subnetclient.go","code":"// deleteSubnet deletes a PublicIPAddress by name.\nfunc (c *Client) deleteSubnet(ctx context.Context, resourceGroupName string, virtualNetworkName string, subnetName string) *retry.Error {\n\tresourceID := armclient.GetChildResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Network/virtualNetworks\",\n\t\tvirtualNetworkName,\n\t\t\"subnets\",\n\t\tsubnetName)\n\n\treturn c.armClient.DeleteResource(ctx, resourceID, \"\")\n}","line":{"from":318,"to":329}} {"id":100033796,"name":"listResponder","signature":"func (c *Client) listResponder(resp *http.Response) (result network.SubnetListResult, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/azure_subnetclient.go","code":"func (c *Client) listResponder(resp *http.Response) (result network.SubnetListResult, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tautorest.ByIgnoring(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}","line":{"from":331,"to":339}} {"id":100033797,"name":"subnetListResultPreparer","signature":"func (c *Client) subnetListResultPreparer(ctx context.Context, lblr network.SubnetListResult) (*http.Request, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/azure_subnetclient.go","code":"// subnetListResultPreparer prepares a request to retrieve the next set of results.\n// It returns nil if no more results exist.\nfunc (c *Client) subnetListResultPreparer(ctx context.Context, lblr network.SubnetListResult) (*http.Request, error) {\n\tif lblr.NextLink == nil || len(pointer.StringDeref(lblr.NextLink, \"\")) \u003c 1 {\n\t\treturn nil, nil\n\t}\n\n\tdecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithBaseURL(pointer.StringDeref(lblr.NextLink, \"\")),\n\t}\n\treturn c.armClient.PrepareGetRequest(ctx, decorators...)\n}","line":{"from":341,"to":352}} {"id":100033798,"name":"listNextResults","signature":"func (c *Client) listNextResults(ctx context.Context, lastResults network.SubnetListResult) (result network.SubnetListResult, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/azure_subnetclient.go","code":"// listNextResults retrieves the next set of results, if any.\nfunc (c *Client) listNextResults(ctx context.Context, lastResults network.SubnetListResult) (result network.SubnetListResult, err error) {\n\treq, err := c.subnetListResultPreparer(ctx, lastResults)\n\tif err != nil {\n\t\treturn result, autorest.NewErrorWithError(err, \"subnetclient\", \"listNextResults\", nil, \"Failure preparing next results request\")\n\t}\n\tif req == nil {\n\t\treturn\n\t}\n\n\tresp, rerr := c.armClient.Send(ctx, req)\n\tdefer c.armClient.CloseResponse(ctx, resp)\n\tif rerr != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\treturn result, autorest.NewErrorWithError(rerr.Error(), \"subnetclient\", \"listNextResults\", resp, \"Failure sending next results request\")\n\t}\n\n\tresult, err = c.listResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"subnetclient\", \"listNextResults\", resp, \"Failure responding to next results request\")\n\t}\n\n\treturn\n}","line":{"from":354,"to":377}} {"id":100033799,"name":"NextWithContext","signature":"func (page *SubnetListResultPage) NextWithContext(ctx context.Context) (err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/azure_subnetclient.go","code":"// NextWithContext advances to the next page of values. If there was an error making\n// the request the page does not advance and the error is returned.\nfunc (page *SubnetListResultPage) NextWithContext(ctx context.Context) (err error) {\n\tnext, err := page.fn(ctx, page.slr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.slr = next\n\treturn nil\n}","line":{"from":385,"to":394}} {"id":100033800,"name":"Next","signature":"func (page *SubnetListResultPage) Next() error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/azure_subnetclient.go","code":"// Next advances to the next page of values. If there was an error making\n// the request the page does not advance and the error is returned.\n// Deprecated: Use NextWithContext() instead.\nfunc (page *SubnetListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}","line":{"from":396,"to":401}} {"id":100033801,"name":"NotDone","signature":"func (page SubnetListResultPage) NotDone() bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/azure_subnetclient.go","code":"// NotDone returns true if the page enumeration should be started or is not yet complete.\nfunc (page SubnetListResultPage) NotDone() bool {\n\treturn !page.slr.IsEmpty()\n}","line":{"from":403,"to":406}} {"id":100033802,"name":"Response","signature":"func (page SubnetListResultPage) Response() network.SubnetListResult","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/azure_subnetclient.go","code":"// Response returns the raw server response from the last page request.\nfunc (page SubnetListResultPage) Response() network.SubnetListResult {\n\treturn page.slr\n}","line":{"from":408,"to":411}} {"id":100033803,"name":"Values","signature":"func (page SubnetListResultPage) Values() []network.Subnet","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/azure_subnetclient.go","code":"// Values returns the slice of values for the current page or nil if there are no values.\nfunc (page SubnetListResultPage) Values() []network.Subnet {\n\tif page.slr.IsEmpty() {\n\t\treturn nil\n\t}\n\treturn *page.slr.Value\n}","line":{"from":413,"to":419}} {"id":100033804,"name":"NewMockInterface","signature":"func NewMockInterface(ctrl *gomock.Controller) *MockInterface","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/mocksubnetclient/interface.go","code":"// NewMockInterface creates a new mock instance.\nfunc NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := \u0026MockInterface{ctrl: ctrl}\n\tmock.recorder = \u0026MockInterfaceMockRecorder{mock}\n\treturn mock\n}","line":{"from":46,"to":51}} {"id":100033805,"name":"EXPECT","signature":"func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/mocksubnetclient/interface.go","code":"// EXPECT returns an object that allows the caller to indicate expected use.\nfunc (m *MockInterface) EXPECT() *MockInterfaceMockRecorder {\n\treturn m.recorder\n}","line":{"from":53,"to":56}} {"id":100033806,"name":"CreateOrUpdate","signature":"func (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, virtualNetworkName, subnetName string, subnetParameters network.Subnet) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/mocksubnetclient/interface.go","code":"// CreateOrUpdate mocks base method.\nfunc (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, virtualNetworkName, subnetName string, subnetParameters network.Subnet) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateOrUpdate\", ctx, resourceGroupName, virtualNetworkName, subnetName, subnetParameters)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":58,"to":64}} {"id":100033807,"name":"CreateOrUpdate","signature":"func (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, virtualNetworkName, subnetName, subnetParameters interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/mocksubnetclient/interface.go","code":"// CreateOrUpdate indicates an expected call of CreateOrUpdate.\nfunc (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, virtualNetworkName, subnetName, subnetParameters interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateOrUpdate\", reflect.TypeOf((*MockInterface)(nil).CreateOrUpdate), ctx, resourceGroupName, virtualNetworkName, subnetName, subnetParameters)\n}","line":{"from":66,"to":70}} {"id":100033808,"name":"Delete","signature":"func (m *MockInterface) Delete(ctx context.Context, resourceGroupName, virtualNetworkName, subnetName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/mocksubnetclient/interface.go","code":"// Delete mocks base method.\nfunc (m *MockInterface) Delete(ctx context.Context, resourceGroupName, virtualNetworkName, subnetName string) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", ctx, resourceGroupName, virtualNetworkName, subnetName)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":72,"to":78}} {"id":100033809,"name":"Delete","signature":"func (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, virtualNetworkName, subnetName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/mocksubnetclient/interface.go","code":"// Delete indicates an expected call of Delete.\nfunc (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, virtualNetworkName, subnetName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Delete\", reflect.TypeOf((*MockInterface)(nil).Delete), ctx, resourceGroupName, virtualNetworkName, subnetName)\n}","line":{"from":80,"to":84}} {"id":100033810,"name":"Get","signature":"func (m *MockInterface) Get(ctx context.Context, resourceGroupName, virtualNetworkName, subnetName, expand string) (network.Subnet, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/mocksubnetclient/interface.go","code":"// Get mocks base method.\nfunc (m *MockInterface) Get(ctx context.Context, resourceGroupName, virtualNetworkName, subnetName, expand string) (network.Subnet, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", ctx, resourceGroupName, virtualNetworkName, subnetName, expand)\n\tret0, _ := ret[0].(network.Subnet)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":86,"to":93}} {"id":100033811,"name":"Get","signature":"func (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, virtualNetworkName, subnetName, expand interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/mocksubnetclient/interface.go","code":"// Get indicates an expected call of Get.\nfunc (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, virtualNetworkName, subnetName, expand interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockInterface)(nil).Get), ctx, resourceGroupName, virtualNetworkName, subnetName, expand)\n}","line":{"from":95,"to":99}} {"id":100033812,"name":"List","signature":"func (m *MockInterface) List(ctx context.Context, resourceGroupName, virtualNetworkName string) ([]network.Subnet, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/mocksubnetclient/interface.go","code":"// List mocks base method.\nfunc (m *MockInterface) List(ctx context.Context, resourceGroupName, virtualNetworkName string) ([]network.Subnet, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", ctx, resourceGroupName, virtualNetworkName)\n\tret0, _ := ret[0].([]network.Subnet)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":101,"to":108}} {"id":100033813,"name":"List","signature":"func (mr *MockInterfaceMockRecorder) List(ctx, resourceGroupName, virtualNetworkName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/subnetclient/mocksubnetclient/interface.go","code":"// List indicates an expected call of List.\nfunc (mr *MockInterfaceMockRecorder) List(ctx, resourceGroupName, virtualNetworkName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"List\", reflect.TypeOf((*MockInterface)(nil).List), ctx, resourceGroupName, virtualNetworkName)\n}","line":{"from":110,"to":114}} {"id":100033814,"name":"New","signature":"func New(config *azclients.ClientConfig) *Client","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/azure_vmclient.go","code":"// New creates a new VirtualMachine client with ratelimiting.\nfunc New(config *azclients.ClientConfig) *Client {\n\tbaseURI := config.ResourceManagerEndpoint\n\tauthorizer := config.Authorizer\n\tarmClient := armclient.New(authorizer, baseURI, config.UserAgent, APIVersion, config.Location, config.Backoff)\n\trateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig)\n\n\tklog.V(2).Infof(\"Azure VirtualMachine client (read ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPS,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucket)\n\tklog.V(2).Infof(\"Azure VirtualMachine client (write ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPSWrite,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucketWrite)\n\n\tclient := \u0026Client{\n\t\tarmClient: armClient,\n\t\trateLimiterReader: rateLimiterReader,\n\t\trateLimiterWriter: rateLimiterWriter,\n\t\tsubscriptionID: config.SubscriptionID,\n\t}\n\n\treturn client\n}","line":{"from":57,"to":79}} {"id":100033815,"name":"Get","signature":"func (c *Client) Get(ctx context.Context, resourceGroupName string, VMName string, expand compute.InstanceViewTypes) (compute.VirtualMachine, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/azure_vmclient.go","code":"// Get gets a VirtualMachine.\nfunc (c *Client) Get(ctx context.Context, resourceGroupName string, VMName string, expand compute.InstanceViewTypes) (compute.VirtualMachine, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"vm\", \"get\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn compute.VirtualMachine{}, retry.GetRateLimitError(false, \"VMGet\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"VMGet\", \"client throttled\", c.RetryAfterReader)\n\t\treturn compute.VirtualMachine{}, rerr\n\t}\n\n\tresult, rerr := c.getVM(ctx, resourceGroupName, VMName, expand)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":81,"to":110}} {"id":100033816,"name":"getVM","signature":"func (c *Client) getVM(ctx context.Context, resourceGroupName string, VMName string, expand compute.InstanceViewTypes) (compute.VirtualMachine, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/azure_vmclient.go","code":"// getVM gets a VirtualMachine.\nfunc (c *Client) getVM(ctx context.Context, resourceGroupName string, VMName string, expand compute.InstanceViewTypes) (compute.VirtualMachine, *retry.Error) {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Compute/virtualMachines\",\n\t\tVMName,\n\t)\n\tresult := compute.VirtualMachine{}\n\n\tresponse, rerr := c.armClient.GetResource(ctx, resourceID, string(expand))\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vm.get.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\terr := autorest.Respond(\n\t\tresponse,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vm.get.respond\", resourceID, err)\n\t\treturn result, retry.GetError(response, err)\n\t}\n\n\tresult.Response = autorest.Response{Response: response}\n\treturn result, nil\n}","line":{"from":112,"to":140}} {"id":100033817,"name":"List","signature":"func (c *Client) List(ctx context.Context, resourceGroupName string) ([]compute.VirtualMachine, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/azure_vmclient.go","code":"// List gets a list of VirtualMachine in the resourceGroupName.\nfunc (c *Client) List(ctx context.Context, resourceGroupName string) ([]compute.VirtualMachine, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"vm\", \"list\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn nil, retry.GetRateLimitError(false, \"VMList\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"VMList\", \"client throttled\", c.RetryAfterReader)\n\t\treturn nil, rerr\n\t}\n\n\tresult, rerr := c.listVM(ctx, resourceGroupName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":142,"to":171}} {"id":100033818,"name":"listVM","signature":"func (c *Client) listVM(ctx context.Context, resourceGroupName string) ([]compute.VirtualMachine, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/azure_vmclient.go","code":"// listVM gets a list of VirtualMachines in the resourceGroupName.\nfunc (c *Client) listVM(ctx context.Context, resourceGroupName string) ([]compute.VirtualMachine, *retry.Error) {\n\tresourceID := fmt.Sprintf(\"/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/virtualMachines\",\n\t\tautorest.Encode(\"path\", c.subscriptionID),\n\t\tautorest.Encode(\"path\", resourceGroupName),\n\t)\n\n\tresult := make([]compute.VirtualMachine, 0)\n\tpage := \u0026VirtualMachineListResultPage{}\n\tpage.fn = c.listNextResults\n\n\tresp, rerr := c.armClient.GetResource(ctx, resourceID, \"\")\n\tdefer c.armClient.CloseResponse(ctx, resp)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vm.list.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\tvar err error\n\tpage.vmlr, err = c.listResponder(resp)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vm.list.respond\", resourceID, err)\n\t\treturn result, retry.GetError(resp, err)\n\t}\n\n\tfor {\n\t\tresult = append(result, page.Values()...)\n\n\t\t// Abort the loop when there's no nextLink in the response.\n\t\tif pointer.StringDeref(page.Response().NextLink, \"\") == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\tif err = page.NextWithContext(ctx); err != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vm.list.next\", resourceID, err)\n\t\t\treturn result, retry.GetError(page.Response().Response.Response, err)\n\t\t}\n\t}\n\n\treturn result, nil\n}","line":{"from":173,"to":213}} {"id":100033819,"name":"Update","signature":"func (c *Client) Update(ctx context.Context, resourceGroupName string, VMName string, parameters compute.VirtualMachineUpdate, source string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/azure_vmclient.go","code":"// Update updates a VirtualMachine.\nfunc (c *Client) Update(ctx context.Context, resourceGroupName string, VMName string, parameters compute.VirtualMachineUpdate, source string) *retry.Error {\n\tmc := metrics.NewMetricContext(\"vm\", \"update\", resourceGroupName, c.subscriptionID, source)\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"VMUpdate\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"VMUpdate\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.updateVM(ctx, resourceGroupName, VMName, parameters, source)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":215,"to":244}} {"id":100033820,"name":"updateVM","signature":"func (c *Client) updateVM(ctx context.Context, resourceGroupName string, VMName string, parameters compute.VirtualMachineUpdate, source string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/azure_vmclient.go","code":"// updateVM updates a VirtualMachine.\nfunc (c *Client) updateVM(ctx context.Context, resourceGroupName string, VMName string, parameters compute.VirtualMachineUpdate, source string) *retry.Error {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Compute/virtualMachines\",\n\t\tVMName,\n\t)\n\n\tresponse, rerr := c.armClient.PatchResource(ctx, resourceID, parameters)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vm.put.request\", resourceID, rerr.Error())\n\t\treturn rerr\n\t}\n\n\tif response != nil \u0026\u0026 response.StatusCode != http.StatusNoContent {\n\t\t_, rerr = c.updateResponder(response)\n\t\tif rerr != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vm.put.respond\", resourceID, rerr.Error())\n\t\t\treturn rerr\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":246,"to":271}} {"id":100033821,"name":"updateResponder","signature":"func (c *Client) updateResponder(resp *http.Response) (*compute.VirtualMachine, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/azure_vmclient.go","code":"func (c *Client) updateResponder(resp *http.Response) (*compute.VirtualMachine, *retry.Error) {\n\tresult := \u0026compute.VirtualMachine{}\n\terr := autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),\n\t\tautorest.ByUnmarshallingJSON(\u0026result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn result, retry.GetError(resp, err)\n}","line":{"from":273,"to":282}} {"id":100033822,"name":"listResponder","signature":"func (c *Client) listResponder(resp *http.Response) (result compute.VirtualMachineListResult, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/azure_vmclient.go","code":"func (c *Client) listResponder(resp *http.Response) (result compute.VirtualMachineListResult, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tautorest.ByIgnoring(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result),\n\t\tautorest.ByClosing(),\n\t)\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}","line":{"from":284,"to":294}} {"id":100033823,"name":"vmListResultPreparer","signature":"func (c *Client) vmListResultPreparer(ctx context.Context, vmlr compute.VirtualMachineListResult) (*http.Request, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/azure_vmclient.go","code":"// vmListResultPreparer prepares a request to retrieve the next set of results.\n// It returns nil if no more results exist.\nfunc (c *Client) vmListResultPreparer(ctx context.Context, vmlr compute.VirtualMachineListResult) (*http.Request, error) {\n\tif vmlr.NextLink == nil || len(pointer.StringDeref(vmlr.NextLink, \"\")) \u003c 1 {\n\t\treturn nil, nil\n\t}\n\n\tdecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithBaseURL(pointer.StringDeref(vmlr.NextLink, \"\")),\n\t}\n\treturn c.armClient.PrepareGetRequest(ctx, decorators...)\n}","line":{"from":296,"to":307}} {"id":100033824,"name":"listNextResults","signature":"func (c *Client) listNextResults(ctx context.Context, lastResults compute.VirtualMachineListResult) (result compute.VirtualMachineListResult, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/azure_vmclient.go","code":"// listNextResults retrieves the next set of results, if any.\nfunc (c *Client) listNextResults(ctx context.Context, lastResults compute.VirtualMachineListResult) (result compute.VirtualMachineListResult, err error) {\n\treq, err := c.vmListResultPreparer(ctx, lastResults)\n\tif err != nil {\n\t\treturn result, autorest.NewErrorWithError(err, \"vmclient\", \"listNextResults\", nil, \"Failure preparing next results request\")\n\t}\n\tif req == nil {\n\t\treturn\n\t}\n\n\tresp, rerr := c.armClient.Send(ctx, req)\n\tdefer c.armClient.CloseResponse(ctx, resp)\n\tif rerr != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\treturn result, autorest.NewErrorWithError(rerr.Error(), \"vmclient\", \"listNextResults\", resp, \"Failure sending next results request\")\n\t}\n\n\tresult, err = c.listResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"vmclient\", \"listNextResults\", resp, \"Failure responding to next results request\")\n\t}\n\n\treturn\n}","line":{"from":309,"to":332}} {"id":100033825,"name":"NextWithContext","signature":"func (page *VirtualMachineListResultPage) NextWithContext(ctx context.Context) (err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/azure_vmclient.go","code":"// NextWithContext advances to the next page of values. If there was an error making\n// the request the page does not advance and the error is returned.\nfunc (page *VirtualMachineListResultPage) NextWithContext(ctx context.Context) (err error) {\n\tnext, err := page.fn(ctx, page.vmlr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.vmlr = next\n\treturn nil\n}","line":{"from":340,"to":349}} {"id":100033826,"name":"Next","signature":"func (page *VirtualMachineListResultPage) Next() error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/azure_vmclient.go","code":"// Next advances to the next page of values. If there was an error making\n// the request the page does not advance and the error is returned.\n// Deprecated: Use NextWithContext() instead.\nfunc (page *VirtualMachineListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}","line":{"from":351,"to":356}} {"id":100033827,"name":"NotDone","signature":"func (page VirtualMachineListResultPage) NotDone() bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/azure_vmclient.go","code":"// NotDone returns true if the page enumeration should be started or is not yet complete.\nfunc (page VirtualMachineListResultPage) NotDone() bool {\n\treturn !page.vmlr.IsEmpty()\n}","line":{"from":358,"to":361}} {"id":100033828,"name":"Response","signature":"func (page VirtualMachineListResultPage) Response() compute.VirtualMachineListResult","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/azure_vmclient.go","code":"// Response returns the raw server response from the last page request.\nfunc (page VirtualMachineListResultPage) Response() compute.VirtualMachineListResult {\n\treturn page.vmlr\n}","line":{"from":363,"to":366}} {"id":100033829,"name":"Values","signature":"func (page VirtualMachineListResultPage) Values() []compute.VirtualMachine","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/azure_vmclient.go","code":"// Values returns the slice of values for the current page or nil if there are no values.\nfunc (page VirtualMachineListResultPage) Values() []compute.VirtualMachine {\n\tif page.vmlr.IsEmpty() {\n\t\treturn nil\n\t}\n\treturn *page.vmlr.Value\n}","line":{"from":368,"to":374}} {"id":100033830,"name":"CreateOrUpdate","signature":"func (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, VMName string, parameters compute.VirtualMachine, source string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/azure_vmclient.go","code":"// CreateOrUpdate creates or updates a VirtualMachine.\nfunc (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, VMName string, parameters compute.VirtualMachine, source string) *retry.Error {\n\tmc := metrics.NewMetricContext(\"vm\", \"create_or_update\", resourceGroupName, c.subscriptionID, source)\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"VMCreateOrUpdate\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"VMCreateOrUpdate\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.createOrUpdateVM(ctx, resourceGroupName, VMName, parameters, source)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":376,"to":405}} {"id":100033831,"name":"createOrUpdateVM","signature":"func (c *Client) createOrUpdateVM(ctx context.Context, resourceGroupName string, VMName string, parameters compute.VirtualMachine, source string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/azure_vmclient.go","code":"// createOrUpdateVM creates or updates a VirtualMachine.\nfunc (c *Client) createOrUpdateVM(ctx context.Context, resourceGroupName string, VMName string, parameters compute.VirtualMachine, source string) *retry.Error {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Compute/virtualMachines\",\n\t\tVMName,\n\t)\n\n\tresponse, rerr := c.armClient.PutResource(ctx, resourceID, parameters)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vm.put.request\", resourceID, rerr.Error())\n\t\treturn rerr\n\t}\n\n\tif response != nil \u0026\u0026 response.StatusCode != http.StatusNoContent {\n\t\t_, rerr = c.createOrUpdateResponder(response)\n\t\tif rerr != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vm.put.respond\", resourceID, rerr.Error())\n\t\t\treturn rerr\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":407,"to":432}} {"id":100033832,"name":"createOrUpdateResponder","signature":"func (c *Client) createOrUpdateResponder(resp *http.Response) (*compute.VirtualMachine, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/azure_vmclient.go","code":"func (c *Client) createOrUpdateResponder(resp *http.Response) (*compute.VirtualMachine, *retry.Error) {\n\tresult := \u0026compute.VirtualMachine{}\n\terr := autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),\n\t\tautorest.ByUnmarshallingJSON(\u0026result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn result, retry.GetError(resp, err)\n}","line":{"from":434,"to":443}} {"id":100033833,"name":"Delete","signature":"func (c *Client) Delete(ctx context.Context, resourceGroupName string, VMName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/azure_vmclient.go","code":"// Delete deletes a VirtualMachine.\nfunc (c *Client) Delete(ctx context.Context, resourceGroupName string, VMName string) *retry.Error {\n\tmc := metrics.NewMetricContext(\"vm\", \"delete\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"VMDelete\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"VMDelete\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.deleteVM(ctx, resourceGroupName, VMName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":445,"to":474}} {"id":100033834,"name":"deleteVM","signature":"func (c *Client) deleteVM(ctx context.Context, resourceGroupName string, VMName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/azure_vmclient.go","code":"// deleteVM deletes a VirtualMachine.\nfunc (c *Client) deleteVM(ctx context.Context, resourceGroupName string, VMName string) *retry.Error {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Compute/virtualMachines\",\n\t\tVMName,\n\t)\n\n\treturn c.armClient.DeleteResource(ctx, resourceID, \"\")\n}","line":{"from":476,"to":486}} {"id":100033835,"name":"NewMockInterface","signature":"func NewMockInterface(ctrl *gomock.Controller) *MockInterface","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/mockvmclient/interface.go","code":"// NewMockInterface creates a new mock instance.\nfunc NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := \u0026MockInterface{ctrl: ctrl}\n\tmock.recorder = \u0026MockInterfaceMockRecorder{mock}\n\treturn mock\n}","line":{"from":46,"to":51}} {"id":100033836,"name":"EXPECT","signature":"func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/mockvmclient/interface.go","code":"// EXPECT returns an object that allows the caller to indicate expected use.\nfunc (m *MockInterface) EXPECT() *MockInterfaceMockRecorder {\n\treturn m.recorder\n}","line":{"from":53,"to":56}} {"id":100033837,"name":"CreateOrUpdate","signature":"func (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, VMName string, parameters compute.VirtualMachine, source string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/mockvmclient/interface.go","code":"// CreateOrUpdate mocks base method.\nfunc (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, VMName string, parameters compute.VirtualMachine, source string) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateOrUpdate\", ctx, resourceGroupName, VMName, parameters, source)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":58,"to":64}} {"id":100033838,"name":"CreateOrUpdate","signature":"func (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, VMName, parameters, source interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/mockvmclient/interface.go","code":"// CreateOrUpdate indicates an expected call of CreateOrUpdate.\nfunc (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, VMName, parameters, source interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateOrUpdate\", reflect.TypeOf((*MockInterface)(nil).CreateOrUpdate), ctx, resourceGroupName, VMName, parameters, source)\n}","line":{"from":66,"to":70}} {"id":100033839,"name":"Delete","signature":"func (m *MockInterface) Delete(ctx context.Context, resourceGroupName, VMName string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/mockvmclient/interface.go","code":"// Delete mocks base method.\nfunc (m *MockInterface) Delete(ctx context.Context, resourceGroupName, VMName string) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", ctx, resourceGroupName, VMName)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":72,"to":78}} {"id":100033840,"name":"Delete","signature":"func (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, VMName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/mockvmclient/interface.go","code":"// Delete indicates an expected call of Delete.\nfunc (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, VMName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Delete\", reflect.TypeOf((*MockInterface)(nil).Delete), ctx, resourceGroupName, VMName)\n}","line":{"from":80,"to":84}} {"id":100033841,"name":"Get","signature":"func (m *MockInterface) Get(ctx context.Context, resourceGroupName, VMName string, expand compute.InstanceViewTypes) (compute.VirtualMachine, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/mockvmclient/interface.go","code":"// Get mocks base method.\nfunc (m *MockInterface) Get(ctx context.Context, resourceGroupName, VMName string, expand compute.InstanceViewTypes) (compute.VirtualMachine, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", ctx, resourceGroupName, VMName, expand)\n\tret0, _ := ret[0].(compute.VirtualMachine)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":86,"to":93}} {"id":100033842,"name":"Get","signature":"func (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, VMName, expand interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/mockvmclient/interface.go","code":"// Get indicates an expected call of Get.\nfunc (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, VMName, expand interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockInterface)(nil).Get), ctx, resourceGroupName, VMName, expand)\n}","line":{"from":95,"to":99}} {"id":100033843,"name":"List","signature":"func (m *MockInterface) List(ctx context.Context, resourceGroupName string) ([]compute.VirtualMachine, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/mockvmclient/interface.go","code":"// List mocks base method.\nfunc (m *MockInterface) List(ctx context.Context, resourceGroupName string) ([]compute.VirtualMachine, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", ctx, resourceGroupName)\n\tret0, _ := ret[0].([]compute.VirtualMachine)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":101,"to":108}} {"id":100033844,"name":"List","signature":"func (mr *MockInterfaceMockRecorder) List(ctx, resourceGroupName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/mockvmclient/interface.go","code":"// List indicates an expected call of List.\nfunc (mr *MockInterfaceMockRecorder) List(ctx, resourceGroupName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"List\", reflect.TypeOf((*MockInterface)(nil).List), ctx, resourceGroupName)\n}","line":{"from":110,"to":114}} {"id":100033845,"name":"Update","signature":"func (m *MockInterface) Update(ctx context.Context, resourceGroupName, VMName string, parameters compute.VirtualMachineUpdate, source string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/mockvmclient/interface.go","code":"// Update mocks base method.\nfunc (m *MockInterface) Update(ctx context.Context, resourceGroupName, VMName string, parameters compute.VirtualMachineUpdate, source string) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", ctx, resourceGroupName, VMName, parameters, source)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":116,"to":122}} {"id":100033846,"name":"Update","signature":"func (mr *MockInterfaceMockRecorder) Update(ctx, resourceGroupName, VMName, parameters, source interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmclient/mockvmclient/interface.go","code":"// Update indicates an expected call of Update.\nfunc (mr *MockInterfaceMockRecorder) Update(ctx, resourceGroupName, VMName, parameters, source interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockInterface)(nil).Update), ctx, resourceGroupName, VMName, parameters, source)\n}","line":{"from":124,"to":128}} {"id":100033847,"name":"New","signature":"func New(config *azclients.ClientConfig) *Client","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmsizeclient/azure_vmsizeclient.go","code":"// New creates a new VirtualMachineSize client with ratelimiting.\nfunc New(config *azclients.ClientConfig) *Client {\n\tbaseURI := config.ResourceManagerEndpoint\n\tauthorizer := config.Authorizer\n\tarmClient := armclient.New(authorizer, baseURI, config.UserAgent, APIVersion, config.Location, config.Backoff)\n\trateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig)\n\n\tklog.V(2).Infof(\"Azure VirtualMachineSizesClient (read ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPS,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucket)\n\tklog.V(2).Infof(\"Azure VirtualMachineSizesClient (write ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPSWrite,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucketWrite)\n\n\tclient := \u0026Client{\n\t\tarmClient: armClient,\n\t\trateLimiterReader: rateLimiterReader,\n\t\trateLimiterWriter: rateLimiterWriter,\n\t\tsubscriptionID: config.SubscriptionID,\n\t}\n\n\treturn client\n}","line":{"from":56,"to":78}} {"id":100033848,"name":"List","signature":"func (c *Client) List(ctx context.Context, location string) (compute.VirtualMachineSizeListResult, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmsizeclient/azure_vmsizeclient.go","code":"// List gets compute.VirtualMachineSizeListResult.\nfunc (c *Client) List(ctx context.Context, location string) (compute.VirtualMachineSizeListResult, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"vmsizes\", \"list\", \"\", c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn compute.VirtualMachineSizeListResult{}, retry.GetRateLimitError(false, \"VMSizesList\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"VMSizesList\", \"client throttled\", c.RetryAfterReader)\n\t\treturn compute.VirtualMachineSizeListResult{}, rerr\n\t}\n\n\tresult, rerr := c.listVirtualMachineSizes(ctx, location)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":80,"to":109}} {"id":100033849,"name":"listVirtualMachineSizes","signature":"func (c *Client) listVirtualMachineSizes(ctx context.Context, location string) (compute.VirtualMachineSizeListResult, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmsizeclient/azure_vmsizeclient.go","code":"// listVirtualMachineSizes gets compute.VirtualMachineSizeListResult.\nfunc (c *Client) listVirtualMachineSizes(ctx context.Context, location string) (compute.VirtualMachineSizeListResult, *retry.Error) {\n\tresourceID := fmt.Sprintf(\"/subscriptions/%s/providers/Microsoft.Compute/locations/%s/vmSizes\",\n\t\tautorest.Encode(\"path\", c.subscriptionID),\n\t\tautorest.Encode(\"path\", location),\n\t)\n\n\tresult := compute.VirtualMachineSizeListResult{}\n\tresponse, rerr := c.armClient.GetResource(ctx, resourceID, \"\")\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmsize.list.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\terr := autorest.Respond(\n\t\tresponse,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmsize.list.respond\", resourceID, err)\n\t\treturn result, retry.GetError(response, err)\n\t}\n\n\tresult.Response = autorest.Response{Response: response}\n\treturn result, nil\n}","line":{"from":111,"to":137}} {"id":100033850,"name":"NewMockInterface","signature":"func NewMockInterface(ctrl *gomock.Controller) *MockInterface","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmsizeclient/mockvmsizeclient/interface.go","code":"// NewMockInterface creates a new mock instance.\nfunc NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := \u0026MockInterface{ctrl: ctrl}\n\tmock.recorder = \u0026MockInterfaceMockRecorder{mock}\n\treturn mock\n}","line":{"from":46,"to":51}} {"id":100033851,"name":"EXPECT","signature":"func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmsizeclient/mockvmsizeclient/interface.go","code":"// EXPECT returns an object that allows the caller to indicate expected use.\nfunc (m *MockInterface) EXPECT() *MockInterfaceMockRecorder {\n\treturn m.recorder\n}","line":{"from":53,"to":56}} {"id":100033852,"name":"List","signature":"func (m *MockInterface) List(ctx context.Context, location string) (compute.VirtualMachineSizeListResult, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmsizeclient/mockvmsizeclient/interface.go","code":"// List mocks base method.\nfunc (m *MockInterface) List(ctx context.Context, location string) (compute.VirtualMachineSizeListResult, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", ctx, location)\n\tret0, _ := ret[0].(compute.VirtualMachineSizeListResult)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":58,"to":65}} {"id":100033853,"name":"List","signature":"func (mr *MockInterfaceMockRecorder) List(ctx, location interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmsizeclient/mockvmsizeclient/interface.go","code":"// List indicates an expected call of List.\nfunc (mr *MockInterfaceMockRecorder) List(ctx, location interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"List\", reflect.TypeOf((*MockInterface)(nil).List), ctx, location)\n}","line":{"from":67,"to":71}} {"id":100033854,"name":"New","signature":"func New(config *azclients.ClientConfig) *Client","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"// New creates a new VMSS client with ratelimiting.\nfunc New(config *azclients.ClientConfig) *Client {\n\tbaseURI := config.ResourceManagerEndpoint\n\tauthorizer := config.Authorizer\n\tarmClient := armclient.New(authorizer, baseURI, config.UserAgent, APIVersion, config.Location, config.Backoff)\n\trateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig)\n\n\tklog.V(2).Infof(\"Azure VirtualMachineScaleSetClient (read ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPS,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucket)\n\tklog.V(2).Infof(\"Azure VirtualMachineScaleSetClient (write ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPSWrite,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucketWrite)\n\n\tclient := \u0026Client{\n\t\tarmClient: armClient,\n\t\trateLimiterReader: rateLimiterReader,\n\t\trateLimiterWriter: rateLimiterWriter,\n\t\tsubscriptionID: config.SubscriptionID,\n\t}\n\n\treturn client\n}","line":{"from":57,"to":79}} {"id":100033855,"name":"Get","signature":"func (c *Client) Get(ctx context.Context, resourceGroupName string, VMScaleSetName string) (compute.VirtualMachineScaleSet, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"// Get gets a VirtualMachineScaleSet.\nfunc (c *Client) Get(ctx context.Context, resourceGroupName string, VMScaleSetName string) (compute.VirtualMachineScaleSet, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"vmss\", \"get\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn compute.VirtualMachineScaleSet{}, retry.GetRateLimitError(false, \"VMSSGet\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"VMSSGet\", \"client throttled\", c.RetryAfterReader)\n\t\treturn compute.VirtualMachineScaleSet{}, rerr\n\t}\n\n\tresult, rerr := c.getVMSS(ctx, resourceGroupName, VMScaleSetName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":81,"to":110}} {"id":100033856,"name":"getVMSS","signature":"func (c *Client) getVMSS(ctx context.Context, resourceGroupName string, VMScaleSetName string) (compute.VirtualMachineScaleSet, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"// getVMSS gets a VirtualMachineScaleSet.\nfunc (c *Client) getVMSS(ctx context.Context, resourceGroupName string, VMScaleSetName string) (compute.VirtualMachineScaleSet, *retry.Error) {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Compute/virtualMachineScaleSets\",\n\t\tVMScaleSetName,\n\t)\n\tresult := compute.VirtualMachineScaleSet{}\n\n\tresponse, rerr := c.armClient.GetResource(ctx, resourceID, \"\")\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmss.get.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\terr := autorest.Respond(\n\t\tresponse,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmss.get.respond\", resourceID, err)\n\t\treturn result, retry.GetError(response, err)\n\t}\n\n\tresult.Response = autorest.Response{Response: response}\n\treturn result, nil\n}","line":{"from":112,"to":140}} {"id":100033857,"name":"List","signature":"func (c *Client) List(ctx context.Context, resourceGroupName string) ([]compute.VirtualMachineScaleSet, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"// List gets a list of VirtualMachineScaleSets in the resource group.\nfunc (c *Client) List(ctx context.Context, resourceGroupName string) ([]compute.VirtualMachineScaleSet, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"vmss\", \"list\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn nil, retry.GetRateLimitError(false, \"VMSSList\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"VMSSList\", \"client throttled\", c.RetryAfterReader)\n\t\treturn nil, rerr\n\t}\n\n\tresult, rerr := c.listVMSS(ctx, resourceGroupName)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":142,"to":171}} {"id":100033858,"name":"listVMSS","signature":"func (c *Client) listVMSS(ctx context.Context, resourceGroupName string) ([]compute.VirtualMachineScaleSet, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"// listVMSS gets a list of VirtualMachineScaleSets in the resource group.\nfunc (c *Client) listVMSS(ctx context.Context, resourceGroupName string) ([]compute.VirtualMachineScaleSet, *retry.Error) {\n\tresourceID := fmt.Sprintf(\"/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/virtualMachineScaleSets\",\n\t\tautorest.Encode(\"path\", c.subscriptionID),\n\t\tautorest.Encode(\"path\", resourceGroupName))\n\tresult := make([]compute.VirtualMachineScaleSet, 0)\n\tpage := \u0026VirtualMachineScaleSetListResultPage{}\n\tpage.fn = c.listNextResults\n\n\tresp, rerr := c.armClient.GetResource(ctx, resourceID, \"\")\n\tdefer c.armClient.CloseResponse(ctx, resp)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmss.list.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\tvar err error\n\tpage.vmsslr, err = c.listResponder(resp)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmss.list.respond\", resourceID, err)\n\t\treturn result, retry.GetError(resp, err)\n\t}\n\n\tfor {\n\t\tresult = append(result, page.Values()...)\n\n\t\t// Abort the loop when there's no nextLink in the response.\n\t\tif pointer.StringDeref(page.Response().NextLink, \"\") == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\tif err = page.NextWithContext(ctx); err != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmss.list.next\", resourceID, err)\n\t\t\treturn result, retry.GetError(page.Response().Response.Response, err)\n\t\t}\n\t}\n\n\treturn result, nil\n}","line":{"from":173,"to":211}} {"id":100033859,"name":"CreateOrUpdate","signature":"func (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, VMScaleSetName string, parameters compute.VirtualMachineScaleSet) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"// CreateOrUpdate creates or updates a VirtualMachineScaleSet.\nfunc (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, VMScaleSetName string, parameters compute.VirtualMachineScaleSet) *retry.Error {\n\tmc := metrics.NewMetricContext(\"vmss\", \"create_or_update\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"VMSSCreateOrUpdate\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"VMSSCreateOrUpdate\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.createOrUpdateVMSS(ctx, resourceGroupName, VMScaleSetName, parameters)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":213,"to":242}} {"id":100033860,"name":"CreateOrUpdateAsync","signature":"func (c *Client) CreateOrUpdateAsync(ctx context.Context, resourceGroupName string, VMScaleSetName string, parameters compute.VirtualMachineScaleSet) (*azure.Future, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"// CreateOrUpdateAsync sends the request to arm client and DO NOT wait for the response\nfunc (c *Client) CreateOrUpdateAsync(ctx context.Context, resourceGroupName string, VMScaleSetName string, parameters compute.VirtualMachineScaleSet) (*azure.Future, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"vmss\", \"create_or_update_async\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn nil, retry.GetRateLimitError(true, \"VMSSCreateOrUpdateAsync\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"VMSSCreateOrUpdateAsync\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn nil, rerr\n\t}\n\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Compute/virtualMachineScaleSets\",\n\t\tVMScaleSetName,\n\t)\n\n\tfuture, rerr := c.armClient.PutResourceAsync(ctx, resourceID, parameters)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn nil, rerr\n\t}\n\n\treturn future, nil\n}","line":{"from":244,"to":280}} {"id":100033861,"name":"WaitForCreateOrUpdateResult","signature":"func (c *Client) WaitForCreateOrUpdateResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"// WaitForCreateOrUpdateResult waits for the response of the create or update request\nfunc (c *Client) WaitForCreateOrUpdateResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error) {\n\tmc := metrics.NewMetricContext(\"vmss\", \"wait_for_create_or_update_result\", resourceGroupName, c.subscriptionID, \"\")\n\tres, err := c.armClient.WaitForAsyncOperationResult(ctx, future, \"VMSSWaitForCreateOrUpdateResult\")\n\tmc.Observe(err)\n\treturn res, err\n}","line":{"from":282,"to":288}} {"id":100033862,"name":"WaitForDeleteInstancesResult","signature":"func (c *Client) WaitForDeleteInstancesResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"// WaitForDeleteInstancesResult waits for the response of the delete instance request\nfunc (c *Client) WaitForDeleteInstancesResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error) {\n\tmc := metrics.NewMetricContext(\"vmss\", \"wait_for_delete_instances_result\", resourceGroupName, c.subscriptionID, \"\")\n\tres, err := c.armClient.WaitForAsyncOperationResult(ctx, future, \"VMSSWaitForDeleteInstancesResult\")\n\tmc.Observe(err)\n\treturn res, err\n}","line":{"from":290,"to":296}} {"id":100033863,"name":"WaitForDeallocateInstancesResult","signature":"func (c *Client) WaitForDeallocateInstancesResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"// WaitForDeallocateInstancesResult waits for the response of the delete instance request\nfunc (c *Client) WaitForDeallocateInstancesResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error) {\n\tmc := metrics.NewMetricContext(\"vmss\", \"wait_for_deallocate_instances_result\", resourceGroupName, c.subscriptionID, \"\")\n\tres, err := c.armClient.WaitForAsyncOperationResult(ctx, future, \"VMSSWaitForDeallocateInstancesResult\")\n\tmc.Observe(err)\n\treturn res, err\n}","line":{"from":298,"to":304}} {"id":100033864,"name":"WaitForStartInstancesResult","signature":"func (c *Client) WaitForStartInstancesResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"// WaitForStartInstancesResult waits for the response of the delete instance request\nfunc (c *Client) WaitForStartInstancesResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error) {\n\tmc := metrics.NewMetricContext(\"vmss\", \"wait_for_start_instances_result\", resourceGroupName, c.subscriptionID, \"\")\n\tres, err := c.armClient.WaitForAsyncOperationResult(ctx, future, \"VMSSWaitForStartInstancesResult\")\n\tmc.Observe(err)\n\treturn res, err\n}","line":{"from":306,"to":312}} {"id":100033865,"name":"WaitForAsyncOperationResult","signature":"func (c *Client) WaitForAsyncOperationResult(ctx context.Context, future *azure.Future) (*http.Response, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"// WaitForAsyncOperationResult waits for the response of the request\nfunc (c *Client) WaitForAsyncOperationResult(ctx context.Context, future *azure.Future) (*http.Response, error) {\n\treturn c.armClient.WaitForAsyncOperationResult(ctx, future, \"VMSSWaitForAsyncOperationResult\")\n}","line":{"from":314,"to":317}} {"id":100033866,"name":"createOrUpdateVMSS","signature":"func (c *Client) createOrUpdateVMSS(ctx context.Context, resourceGroupName string, VMScaleSetName string, parameters compute.VirtualMachineScaleSet) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"// createOrUpdateVMSS creates or updates a VirtualMachineScaleSet.\nfunc (c *Client) createOrUpdateVMSS(ctx context.Context, resourceGroupName string, VMScaleSetName string, parameters compute.VirtualMachineScaleSet) *retry.Error {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Compute/virtualMachineScaleSets\",\n\t\tVMScaleSetName,\n\t)\n\tresponse, rerr := c.armClient.PutResource(ctx, resourceID, parameters)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmss.put.request\", resourceID, rerr.Error())\n\t\treturn rerr\n\t}\n\n\tif response != nil \u0026\u0026 response.StatusCode != http.StatusNoContent {\n\t\t_, rerr = c.createOrUpdateResponder(response)\n\t\tif rerr != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmss.put.respond\", resourceID, rerr.Error())\n\t\t\treturn rerr\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":319,"to":343}} {"id":100033867,"name":"createOrUpdateResponder","signature":"func (c *Client) createOrUpdateResponder(resp *http.Response) (*compute.VirtualMachineScaleSet, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"func (c *Client) createOrUpdateResponder(resp *http.Response) (*compute.VirtualMachineScaleSet, *retry.Error) {\n\tresult := \u0026compute.VirtualMachineScaleSet{}\n\terr := autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tresult.Response = autorest.Response{Response: resp}\n\treturn result, retry.GetError(resp, err)\n}","line":{"from":345,"to":353}} {"id":100033868,"name":"listResponder","signature":"func (c *Client) listResponder(resp *http.Response) (result compute.VirtualMachineScaleSetListResult, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"func (c *Client) listResponder(resp *http.Response) (result compute.VirtualMachineScaleSetListResult, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tautorest.ByIgnoring(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}","line":{"from":355,"to":363}} {"id":100033869,"name":"virtualMachineScaleSetListResultPreparer","signature":"func (c *Client) virtualMachineScaleSetListResultPreparer(ctx context.Context, vmsslr compute.VirtualMachineScaleSetListResult) (*http.Request, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"// virtualMachineScaleSetListResultPreparer prepares a request to retrieve the next set of results.\n// It returns nil if no more results exist.\nfunc (c *Client) virtualMachineScaleSetListResultPreparer(ctx context.Context, vmsslr compute.VirtualMachineScaleSetListResult) (*http.Request, error) {\n\tif vmsslr.NextLink == nil || len(pointer.StringDeref(vmsslr.NextLink, \"\")) \u003c 1 {\n\t\treturn nil, nil\n\t}\n\n\tdecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithBaseURL(pointer.StringDeref(vmsslr.NextLink, \"\")),\n\t}\n\treturn c.armClient.PrepareGetRequest(ctx, decorators...)\n}","line":{"from":365,"to":376}} {"id":100033870,"name":"listNextResults","signature":"func (c *Client) listNextResults(ctx context.Context, lastResults compute.VirtualMachineScaleSetListResult) (result compute.VirtualMachineScaleSetListResult, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"// listNextResults retrieves the next set of results, if any.\nfunc (c *Client) listNextResults(ctx context.Context, lastResults compute.VirtualMachineScaleSetListResult) (result compute.VirtualMachineScaleSetListResult, err error) {\n\treq, err := c.virtualMachineScaleSetListResultPreparer(ctx, lastResults)\n\tif err != nil {\n\t\treturn result, autorest.NewErrorWithError(err, \"vmssclient\", \"listNextResults\", nil, \"Failure preparing next results request\")\n\t}\n\tif req == nil {\n\t\treturn\n\t}\n\n\tresp, rerr := c.armClient.Send(ctx, req)\n\tdefer c.armClient.CloseResponse(ctx, resp)\n\tif rerr != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\treturn result, autorest.NewErrorWithError(rerr.Error(), \"vmssclient\", \"listNextResults\", resp, \"Failure sending next results request\")\n\t}\n\n\tresult, err = c.listResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"vmssclient\", \"listNextResults\", resp, \"Failure responding to next results request\")\n\t}\n\n\treturn\n}","line":{"from":378,"to":401}} {"id":100033871,"name":"NextWithContext","signature":"func (page *VirtualMachineScaleSetListResultPage) NextWithContext(ctx context.Context) (err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"// NextWithContext advances to the next page of values. If there was an error making\n// the request the page does not advance and the error is returned.\nfunc (page *VirtualMachineScaleSetListResultPage) NextWithContext(ctx context.Context) (err error) {\n\tnext, err := page.fn(ctx, page.vmsslr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.vmsslr = next\n\treturn nil\n}","line":{"from":409,"to":418}} {"id":100033872,"name":"Next","signature":"func (page *VirtualMachineScaleSetListResultPage) Next() error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"// Next advances to the next page of values. If there was an error making\n// the request the page does not advance and the error is returned.\n// Deprecated: Use NextWithContext() instead.\nfunc (page *VirtualMachineScaleSetListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}","line":{"from":420,"to":425}} {"id":100033873,"name":"NotDone","signature":"func (page VirtualMachineScaleSetListResultPage) NotDone() bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"// NotDone returns true if the page enumeration should be started or is not yet complete.\nfunc (page VirtualMachineScaleSetListResultPage) NotDone() bool {\n\treturn !page.vmsslr.IsEmpty()\n}","line":{"from":427,"to":430}} {"id":100033874,"name":"Response","signature":"func (page VirtualMachineScaleSetListResultPage) Response() compute.VirtualMachineScaleSetListResult","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"// Response returns the raw server response from the last page request.\nfunc (page VirtualMachineScaleSetListResultPage) Response() compute.VirtualMachineScaleSetListResult {\n\treturn page.vmsslr\n}","line":{"from":432,"to":435}} {"id":100033875,"name":"Values","signature":"func (page VirtualMachineScaleSetListResultPage) Values() []compute.VirtualMachineScaleSet","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"// Values returns the slice of values for the current page or nil if there are no values.\nfunc (page VirtualMachineScaleSetListResultPage) Values() []compute.VirtualMachineScaleSet {\n\tif page.vmsslr.IsEmpty() {\n\t\treturn nil\n\t}\n\treturn *page.vmsslr.Value\n}","line":{"from":437,"to":443}} {"id":100033876,"name":"DeleteInstances","signature":"func (c *Client) DeleteInstances(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"// DeleteInstances deletes the instances for a VirtualMachineScaleSet.\nfunc (c *Client) DeleteInstances(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) *retry.Error {\n\tmc := metrics.NewMetricContext(\"vmss\", \"delete_instances\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"VMSSDeleteInstances\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"VMSSDeleteInstances\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.deleteVMSSInstances(ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":445,"to":474}} {"id":100033877,"name":"DeleteInstancesAsync","signature":"func (c *Client) DeleteInstancesAsync(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) (*azure.Future, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"// DeleteInstancesAsync sends the delete request to ARM client and DOEST NOT wait on the future\nfunc (c *Client) DeleteInstancesAsync(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) (*azure.Future, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"vmss\", \"delete_instances_async\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn nil, retry.GetRateLimitError(true, \"VMSSDeleteInstancesAsync\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"VMSSDeleteInstancesAsync\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn nil, rerr\n\t}\n\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Compute/virtualMachineScaleSets\",\n\t\tvmScaleSetName,\n\t)\n\n\tresponse, rerr := c.armClient.PostResource(ctx, resourceID, \"delete\", vmInstanceIDs)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmss.deletevms.request\", resourceID, rerr.Error())\n\t\treturn nil, rerr\n\t}\n\n\terr := autorest.Respond(response, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted))\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmss.deletevms.respond\", resourceID, rerr.Error())\n\t\treturn nil, retry.GetError(response, err)\n\t}\n\n\tfuture, err := azure.NewFutureFromResponse(response)\n\tmc.Observe(err)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmss.deletevms.future\", resourceID, rerr.Error())\n\t\treturn nil, retry.NewError(false, err)\n\t}\n\n\treturn \u0026future, nil\n}","line":{"from":476,"to":522}} {"id":100033878,"name":"DeallocateInstancesAsync","signature":"func (c *Client) DeallocateInstancesAsync(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) (*azure.Future, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"// DeallocateInstancesAsync sends the deallocate request to ARM client and DOEST NOT wait on the future\nfunc (c *Client) DeallocateInstancesAsync(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) (*azure.Future, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"vmss\", \"deallocate_instances_async\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn nil, retry.GetRateLimitError(true, \"VMSSDeallocateInstancesAsync\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"VMSSDeallocateInstancesAsync\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn nil, rerr\n\t}\n\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Compute/virtualMachineScaleSets\",\n\t\tvmScaleSetName,\n\t)\n\n\tresponse, rerr := c.armClient.PostResource(ctx, resourceID, \"deallocate\", vmInstanceIDs)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmss.deallocatevms.request\", resourceID, rerr.Error())\n\t\treturn nil, rerr\n\t}\n\n\terr := autorest.Respond(response, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted))\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmss.deallocatevms.respond\", resourceID, rerr.Error())\n\t\treturn nil, retry.GetError(response, err)\n\t}\n\n\tfuture, err := azure.NewFutureFromResponse(response)\n\tmc.Observe(err)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmss.deallocatevms.future\", resourceID, rerr.Error())\n\t\treturn nil, retry.NewError(false, err)\n\t}\n\n\treturn \u0026future, nil\n}","line":{"from":524,"to":570}} {"id":100033879,"name":"StartInstancesAsync","signature":"func (c *Client) StartInstancesAsync(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) (*azure.Future, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"// StartInstancesAsync sends the start request to ARM client and DOEST NOT wait on the future\nfunc (c *Client) StartInstancesAsync(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) (*azure.Future, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"vmss\", \"start_instances_async\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn nil, retry.GetRateLimitError(true, \"VMSSStartInstancesAsync\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"VMSSStartInstancesAsync\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn nil, rerr\n\t}\n\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Compute/virtualMachineScaleSets\",\n\t\tvmScaleSetName,\n\t)\n\n\tresponse, rerr := c.armClient.PostResource(ctx, resourceID, \"start\", vmInstanceIDs)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmss.startvms.request\", resourceID, rerr.Error())\n\t\treturn nil, rerr\n\t}\n\n\terr := autorest.Respond(response, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted))\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmss.startvms.respond\", resourceID, rerr.Error())\n\t\treturn nil, retry.GetError(response, err)\n\t}\n\n\tfuture, err := azure.NewFutureFromResponse(response)\n\tmc.Observe(err)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmss.startvms.future\", resourceID, rerr.Error())\n\t\treturn nil, retry.NewError(false, err)\n\t}\n\n\treturn \u0026future, nil\n}","line":{"from":572,"to":618}} {"id":100033880,"name":"deleteVMSSInstances","signature":"func (c *Client) deleteVMSSInstances(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/azure_vmssclient.go","code":"// deleteVMSSInstances deletes the instances for a VirtualMachineScaleSet.\nfunc (c *Client) deleteVMSSInstances(ctx context.Context, resourceGroupName string, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) *retry.Error {\n\tresourceID := armclient.GetResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Compute/virtualMachineScaleSets\",\n\t\tvmScaleSetName,\n\t)\n\tresponse, rerr := c.armClient.PostResource(ctx, resourceID, \"delete\", vmInstanceIDs)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmss.deletevms.request\", resourceID, rerr.Error())\n\t\treturn rerr\n\t}\n\n\terr := autorest.Respond(response, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted))\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmss.deletevms.respond\", resourceID, rerr.Error())\n\t\treturn retry.GetError(response, err)\n\t}\n\n\tfuture, err := azure.NewFutureFromResponse(response)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmss.deletevms.future\", resourceID, rerr.Error())\n\t\treturn retry.NewError(false, err)\n\t}\n\n\tif err := c.armClient.WaitForAsyncOperationCompletion(ctx, \u0026future, \"vmssclient.DeleteInstances\"); err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmss.deletevms.wait\", resourceID, rerr.Error())\n\t\treturn retry.NewError(false, err)\n\t}\n\n\treturn nil\n}","line":{"from":620,"to":653}} {"id":100033881,"name":"NewMockInterface","signature":"func NewMockInterface(ctrl *gomock.Controller) *MockInterface","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// NewMockInterface creates a new mock instance.\nfunc NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := \u0026MockInterface{ctrl: ctrl}\n\tmock.recorder = \u0026MockInterfaceMockRecorder{mock}\n\treturn mock\n}","line":{"from":48,"to":53}} {"id":100033882,"name":"EXPECT","signature":"func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// EXPECT returns an object that allows the caller to indicate expected use.\nfunc (m *MockInterface) EXPECT() *MockInterfaceMockRecorder {\n\treturn m.recorder\n}","line":{"from":55,"to":58}} {"id":100033883,"name":"CreateOrUpdate","signature":"func (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, VMScaleSetName string, parameters compute.VirtualMachineScaleSet) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// CreateOrUpdate mocks base method.\nfunc (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, VMScaleSetName string, parameters compute.VirtualMachineScaleSet) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateOrUpdate\", ctx, resourceGroupName, VMScaleSetName, parameters)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":60,"to":66}} {"id":100033884,"name":"CreateOrUpdate","signature":"func (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, VMScaleSetName, parameters interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// CreateOrUpdate indicates an expected call of CreateOrUpdate.\nfunc (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, VMScaleSetName, parameters interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateOrUpdate\", reflect.TypeOf((*MockInterface)(nil).CreateOrUpdate), ctx, resourceGroupName, VMScaleSetName, parameters)\n}","line":{"from":68,"to":72}} {"id":100033885,"name":"CreateOrUpdateAsync","signature":"func (m *MockInterface) CreateOrUpdateAsync(ctx context.Context, resourceGroupName, VMScaleSetName string, parameters compute.VirtualMachineScaleSet) (*azure.Future, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// CreateOrUpdateAsync mocks base method.\nfunc (m *MockInterface) CreateOrUpdateAsync(ctx context.Context, resourceGroupName, VMScaleSetName string, parameters compute.VirtualMachineScaleSet) (*azure.Future, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateOrUpdateAsync\", ctx, resourceGroupName, VMScaleSetName, parameters)\n\tret0, _ := ret[0].(*azure.Future)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":74,"to":81}} {"id":100033886,"name":"CreateOrUpdateAsync","signature":"func (mr *MockInterfaceMockRecorder) CreateOrUpdateAsync(ctx, resourceGroupName, VMScaleSetName, parameters interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// CreateOrUpdateAsync indicates an expected call of CreateOrUpdateAsync.\nfunc (mr *MockInterfaceMockRecorder) CreateOrUpdateAsync(ctx, resourceGroupName, VMScaleSetName, parameters interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateOrUpdateAsync\", reflect.TypeOf((*MockInterface)(nil).CreateOrUpdateAsync), ctx, resourceGroupName, VMScaleSetName, parameters)\n}","line":{"from":83,"to":87}} {"id":100033887,"name":"DeallocateInstancesAsync","signature":"func (m *MockInterface) DeallocateInstancesAsync(ctx context.Context, resourceGroupName, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) (*azure.Future, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// DeallocateInstancesAsync mocks base method.\nfunc (m *MockInterface) DeallocateInstancesAsync(ctx context.Context, resourceGroupName, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) (*azure.Future, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeallocateInstancesAsync\", ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs)\n\tret0, _ := ret[0].(*azure.Future)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":89,"to":96}} {"id":100033888,"name":"DeallocateInstancesAsync","signature":"func (mr *MockInterfaceMockRecorder) DeallocateInstancesAsync(ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// DeallocateInstancesAsync indicates an expected call of DeallocateInstancesAsync.\nfunc (mr *MockInterfaceMockRecorder) DeallocateInstancesAsync(ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeallocateInstancesAsync\", reflect.TypeOf((*MockInterface)(nil).DeallocateInstancesAsync), ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs)\n}","line":{"from":98,"to":102}} {"id":100033889,"name":"DeleteInstances","signature":"func (m *MockInterface) DeleteInstances(ctx context.Context, resourceGroupName, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// DeleteInstances mocks base method.\nfunc (m *MockInterface) DeleteInstances(ctx context.Context, resourceGroupName, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteInstances\", ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":104,"to":110}} {"id":100033890,"name":"DeleteInstances","signature":"func (mr *MockInterfaceMockRecorder) DeleteInstances(ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// DeleteInstances indicates an expected call of DeleteInstances.\nfunc (mr *MockInterfaceMockRecorder) DeleteInstances(ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteInstances\", reflect.TypeOf((*MockInterface)(nil).DeleteInstances), ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs)\n}","line":{"from":112,"to":116}} {"id":100033891,"name":"DeleteInstancesAsync","signature":"func (m *MockInterface) DeleteInstancesAsync(ctx context.Context, resourceGroupName, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) (*azure.Future, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// DeleteInstancesAsync mocks base method.\nfunc (m *MockInterface) DeleteInstancesAsync(ctx context.Context, resourceGroupName, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) (*azure.Future, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteInstancesAsync\", ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs)\n\tret0, _ := ret[0].(*azure.Future)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":118,"to":125}} {"id":100033892,"name":"DeleteInstancesAsync","signature":"func (mr *MockInterfaceMockRecorder) DeleteInstancesAsync(ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// DeleteInstancesAsync indicates an expected call of DeleteInstancesAsync.\nfunc (mr *MockInterfaceMockRecorder) DeleteInstancesAsync(ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteInstancesAsync\", reflect.TypeOf((*MockInterface)(nil).DeleteInstancesAsync), ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs)\n}","line":{"from":127,"to":131}} {"id":100033893,"name":"Get","signature":"func (m *MockInterface) Get(ctx context.Context, resourceGroupName, VMScaleSetName string) (compute.VirtualMachineScaleSet, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// Get mocks base method.\nfunc (m *MockInterface) Get(ctx context.Context, resourceGroupName, VMScaleSetName string) (compute.VirtualMachineScaleSet, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", ctx, resourceGroupName, VMScaleSetName)\n\tret0, _ := ret[0].(compute.VirtualMachineScaleSet)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":133,"to":140}} {"id":100033894,"name":"Get","signature":"func (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, VMScaleSetName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// Get indicates an expected call of Get.\nfunc (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, VMScaleSetName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockInterface)(nil).Get), ctx, resourceGroupName, VMScaleSetName)\n}","line":{"from":142,"to":146}} {"id":100033895,"name":"List","signature":"func (m *MockInterface) List(ctx context.Context, resourceGroupName string) ([]compute.VirtualMachineScaleSet, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// List mocks base method.\nfunc (m *MockInterface) List(ctx context.Context, resourceGroupName string) ([]compute.VirtualMachineScaleSet, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", ctx, resourceGroupName)\n\tret0, _ := ret[0].([]compute.VirtualMachineScaleSet)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":148,"to":155}} {"id":100033896,"name":"List","signature":"func (mr *MockInterfaceMockRecorder) List(ctx, resourceGroupName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// List indicates an expected call of List.\nfunc (mr *MockInterfaceMockRecorder) List(ctx, resourceGroupName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"List\", reflect.TypeOf((*MockInterface)(nil).List), ctx, resourceGroupName)\n}","line":{"from":157,"to":161}} {"id":100033897,"name":"StartInstancesAsync","signature":"func (m *MockInterface) StartInstancesAsync(ctx context.Context, resourceGroupName, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) (*azure.Future, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// StartInstancesAsync mocks base method.\nfunc (m *MockInterface) StartInstancesAsync(ctx context.Context, resourceGroupName, vmScaleSetName string, vmInstanceIDs compute.VirtualMachineScaleSetVMInstanceRequiredIDs) (*azure.Future, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"StartInstancesAsync\", ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs)\n\tret0, _ := ret[0].(*azure.Future)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":163,"to":170}} {"id":100033898,"name":"StartInstancesAsync","signature":"func (mr *MockInterfaceMockRecorder) StartInstancesAsync(ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// StartInstancesAsync indicates an expected call of StartInstancesAsync.\nfunc (mr *MockInterfaceMockRecorder) StartInstancesAsync(ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"StartInstancesAsync\", reflect.TypeOf((*MockInterface)(nil).StartInstancesAsync), ctx, resourceGroupName, vmScaleSetName, vmInstanceIDs)\n}","line":{"from":172,"to":176}} {"id":100033899,"name":"WaitForAsyncOperationResult","signature":"func (m *MockInterface) WaitForAsyncOperationResult(ctx context.Context, future *azure.Future) (*http.Response, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// WaitForAsyncOperationResult mocks base method.\nfunc (m *MockInterface) WaitForAsyncOperationResult(ctx context.Context, future *azure.Future) (*http.Response, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"WaitForAsyncOperationResult\", ctx, future)\n\tret0, _ := ret[0].(*http.Response)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}","line":{"from":178,"to":185}} {"id":100033900,"name":"WaitForAsyncOperationResult","signature":"func (mr *MockInterfaceMockRecorder) WaitForAsyncOperationResult(ctx, future interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// WaitForAsyncOperationResult indicates an expected call of WaitForAsyncOperationResult.\nfunc (mr *MockInterfaceMockRecorder) WaitForAsyncOperationResult(ctx, future interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"WaitForAsyncOperationResult\", reflect.TypeOf((*MockInterface)(nil).WaitForAsyncOperationResult), ctx, future)\n}","line":{"from":187,"to":191}} {"id":100033901,"name":"WaitForCreateOrUpdateResult","signature":"func (m *MockInterface) WaitForCreateOrUpdateResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// WaitForCreateOrUpdateResult mocks base method.\nfunc (m *MockInterface) WaitForCreateOrUpdateResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"WaitForCreateOrUpdateResult\", ctx, future, resourceGroupName)\n\tret0, _ := ret[0].(*http.Response)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}","line":{"from":193,"to":200}} {"id":100033902,"name":"WaitForCreateOrUpdateResult","signature":"func (mr *MockInterfaceMockRecorder) WaitForCreateOrUpdateResult(ctx, future, resourceGroupName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// WaitForCreateOrUpdateResult indicates an expected call of WaitForCreateOrUpdateResult.\nfunc (mr *MockInterfaceMockRecorder) WaitForCreateOrUpdateResult(ctx, future, resourceGroupName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"WaitForCreateOrUpdateResult\", reflect.TypeOf((*MockInterface)(nil).WaitForCreateOrUpdateResult), ctx, future, resourceGroupName)\n}","line":{"from":202,"to":206}} {"id":100033903,"name":"WaitForDeallocateInstancesResult","signature":"func (m *MockInterface) WaitForDeallocateInstancesResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// WaitForDeallocateInstancesResult mocks base method.\nfunc (m *MockInterface) WaitForDeallocateInstancesResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"WaitForDeallocateInstancesResult\", ctx, future, resourceGroupName)\n\tret0, _ := ret[0].(*http.Response)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}","line":{"from":208,"to":215}} {"id":100033904,"name":"WaitForDeallocateInstancesResult","signature":"func (mr *MockInterfaceMockRecorder) WaitForDeallocateInstancesResult(ctx, future, resourceGroupName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// WaitForDeallocateInstancesResult indicates an expected call of WaitForDeallocateInstancesResult.\nfunc (mr *MockInterfaceMockRecorder) WaitForDeallocateInstancesResult(ctx, future, resourceGroupName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"WaitForDeallocateInstancesResult\", reflect.TypeOf((*MockInterface)(nil).WaitForDeallocateInstancesResult), ctx, future, resourceGroupName)\n}","line":{"from":217,"to":221}} {"id":100033905,"name":"WaitForDeleteInstancesResult","signature":"func (m *MockInterface) WaitForDeleteInstancesResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// WaitForDeleteInstancesResult mocks base method.\nfunc (m *MockInterface) WaitForDeleteInstancesResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"WaitForDeleteInstancesResult\", ctx, future, resourceGroupName)\n\tret0, _ := ret[0].(*http.Response)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}","line":{"from":223,"to":230}} {"id":100033906,"name":"WaitForDeleteInstancesResult","signature":"func (mr *MockInterfaceMockRecorder) WaitForDeleteInstancesResult(ctx, future, resourceGroupName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// WaitForDeleteInstancesResult indicates an expected call of WaitForDeleteInstancesResult.\nfunc (mr *MockInterfaceMockRecorder) WaitForDeleteInstancesResult(ctx, future, resourceGroupName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"WaitForDeleteInstancesResult\", reflect.TypeOf((*MockInterface)(nil).WaitForDeleteInstancesResult), ctx, future, resourceGroupName)\n}","line":{"from":232,"to":236}} {"id":100033907,"name":"WaitForStartInstancesResult","signature":"func (m *MockInterface) WaitForStartInstancesResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// WaitForStartInstancesResult mocks base method.\nfunc (m *MockInterface) WaitForStartInstancesResult(ctx context.Context, future *azure.Future, resourceGroupName string) (*http.Response, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"WaitForStartInstancesResult\", ctx, future, resourceGroupName)\n\tret0, _ := ret[0].(*http.Response)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}","line":{"from":238,"to":245}} {"id":100033908,"name":"WaitForStartInstancesResult","signature":"func (mr *MockInterfaceMockRecorder) WaitForStartInstancesResult(ctx, future, resourceGroupName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient/interface.go","code":"// WaitForStartInstancesResult indicates an expected call of WaitForStartInstancesResult.\nfunc (mr *MockInterfaceMockRecorder) WaitForStartInstancesResult(ctx, future, resourceGroupName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"WaitForStartInstancesResult\", reflect.TypeOf((*MockInterface)(nil).WaitForStartInstancesResult), ctx, future, resourceGroupName)\n}","line":{"from":247,"to":251}} {"id":100033909,"name":"New","signature":"func New(config *azclients.ClientConfig) *Client","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/azure_vmssvmclient.go","code":"// New creates a new vmssVM client with ratelimiting.\nfunc New(config *azclients.ClientConfig) *Client {\n\tbaseURI := config.ResourceManagerEndpoint\n\tauthorizer := config.Authorizer\n\tarmClient := armclient.New(authorizer, baseURI, config.UserAgent, APIVersion, config.Location, config.Backoff)\n\trateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig)\n\n\tklog.V(2).Infof(\"Azure vmssVM client (read ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPS,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucket)\n\tklog.V(2).Infof(\"Azure vmssVM client (write ops) using rate limit config: QPS=%g, bucket=%d\",\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitQPSWrite,\n\t\tconfig.RateLimitConfig.CloudProviderRateLimitBucketWrite)\n\n\tclient := \u0026Client{\n\t\tarmClient: armClient,\n\t\trateLimiterReader: rateLimiterReader,\n\t\trateLimiterWriter: rateLimiterWriter,\n\t\tsubscriptionID: config.SubscriptionID,\n\t}\n\n\treturn client\n}","line":{"from":58,"to":80}} {"id":100033910,"name":"Get","signature":"func (c *Client) Get(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, expand compute.InstanceViewTypes) (compute.VirtualMachineScaleSetVM, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/azure_vmssvmclient.go","code":"// Get gets a VirtualMachineScaleSetVM.\nfunc (c *Client) Get(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, expand compute.InstanceViewTypes) (compute.VirtualMachineScaleSetVM, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"vmssvm\", \"get\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn compute.VirtualMachineScaleSetVM{}, retry.GetRateLimitError(false, \"VMSSVMGet\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"VMSSVMGet\", \"client throttled\", c.RetryAfterReader)\n\t\treturn compute.VirtualMachineScaleSetVM{}, rerr\n\t}\n\n\tresult, rerr := c.getVMSSVM(ctx, resourceGroupName, VMScaleSetName, instanceID, expand)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":82,"to":111}} {"id":100033911,"name":"getVMSSVM","signature":"func (c *Client) getVMSSVM(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, expand compute.InstanceViewTypes) (compute.VirtualMachineScaleSetVM, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/azure_vmssvmclient.go","code":"// getVMSSVM gets a VirtualMachineScaleSetVM.\nfunc (c *Client) getVMSSVM(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, expand compute.InstanceViewTypes) (compute.VirtualMachineScaleSetVM, *retry.Error) {\n\tresourceID := armclient.GetChildResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Compute/virtualMachineScaleSets\",\n\t\tVMScaleSetName,\n\t\t\"virtualMachines\",\n\t\tinstanceID,\n\t)\n\tresult := compute.VirtualMachineScaleSetVM{}\n\n\tresponse, rerr := c.armClient.GetResource(ctx, resourceID, string(expand))\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmssvm.get.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\terr := autorest.Respond(\n\t\tresponse,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmssvm.get.respond\", resourceID, err)\n\t\treturn result, retry.GetError(response, err)\n\t}\n\n\tresult.Response = autorest.Response{Response: response}\n\treturn result, nil\n}","line":{"from":113,"to":143}} {"id":100033912,"name":"List","signature":"func (c *Client) List(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, expand string) ([]compute.VirtualMachineScaleSetVM, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/azure_vmssvmclient.go","code":"// List gets a list of VirtualMachineScaleSetVMs in the virtualMachineScaleSet.\nfunc (c *Client) List(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, expand string) ([]compute.VirtualMachineScaleSetVM, *retry.Error) {\n\tmc := metrics.NewMetricContext(\"vmssvm\", \"list\", resourceGroupName, c.subscriptionID, \"\")\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterReader.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn nil, retry.GetRateLimitError(false, \"VMSSVMList\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterReader.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"VMSSVMList\", \"client throttled\", c.RetryAfterReader)\n\t\treturn nil, rerr\n\t}\n\n\tresult, rerr := c.listVMSSVM(ctx, resourceGroupName, virtualMachineScaleSetName, expand)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterReader = rerr.RetryAfter\n\t\t}\n\n\t\treturn result, rerr\n\t}\n\n\treturn result, nil\n}","line":{"from":145,"to":174}} {"id":100033913,"name":"listVMSSVM","signature":"func (c *Client) listVMSSVM(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, expand string) ([]compute.VirtualMachineScaleSetVM, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/azure_vmssvmclient.go","code":"// listVMSSVM gets a list of VirtualMachineScaleSetVMs in the virtualMachineScaleSet.\nfunc (c *Client) listVMSSVM(ctx context.Context, resourceGroupName string, virtualMachineScaleSetName string, expand string) ([]compute.VirtualMachineScaleSetVM, *retry.Error) {\n\tresourceID := fmt.Sprintf(\"/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/virtualMachineScaleSets/%s/virtualMachines\",\n\t\tautorest.Encode(\"path\", c.subscriptionID),\n\t\tautorest.Encode(\"path\", resourceGroupName),\n\t\tautorest.Encode(\"path\", virtualMachineScaleSetName),\n\t)\n\n\tresult := make([]compute.VirtualMachineScaleSetVM, 0)\n\tpage := \u0026VirtualMachineScaleSetVMListResultPage{}\n\tpage.fn = c.listNextResults\n\n\tresp, rerr := c.armClient.GetResource(ctx, resourceID, expand)\n\tdefer c.armClient.CloseResponse(ctx, resp)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmssvm.list.request\", resourceID, rerr.Error())\n\t\treturn result, rerr\n\t}\n\n\tvar err error\n\tpage.vmssvlr, err = c.listResponder(resp)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmssvm.list.respond\", resourceID, err)\n\t\treturn result, retry.GetError(resp, err)\n\t}\n\n\tfor {\n\t\tresult = append(result, page.Values()...)\n\n\t\t// Abort the loop when there's no nextLink in the response.\n\t\tif pointer.StringDeref(page.Response().NextLink, \"\") == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\tif err = page.NextWithContext(ctx); err != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmssvm.list.next\", resourceID, err)\n\t\t\treturn result, retry.GetError(page.Response().Response.Response, err)\n\t\t}\n\t}\n\n\treturn result, nil\n}","line":{"from":176,"to":217}} {"id":100033914,"name":"Update","signature":"func (c *Client) Update(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, parameters compute.VirtualMachineScaleSetVM, source string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/azure_vmssvmclient.go","code":"// Update updates a VirtualMachineScaleSetVM.\nfunc (c *Client) Update(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, parameters compute.VirtualMachineScaleSetVM, source string) *retry.Error {\n\tmc := metrics.NewMetricContext(\"vmssvm\", \"update\", resourceGroupName, c.subscriptionID, source)\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"VMSSVMUpdate\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"VMSSVMUpdate\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.updateVMSSVM(ctx, resourceGroupName, VMScaleSetName, instanceID, parameters)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":219,"to":248}} {"id":100033915,"name":"updateVMSSVM","signature":"func (c *Client) updateVMSSVM(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, parameters compute.VirtualMachineScaleSetVM) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/azure_vmssvmclient.go","code":"// updateVMSSVM updates a VirtualMachineScaleSetVM.\nfunc (c *Client) updateVMSSVM(ctx context.Context, resourceGroupName string, VMScaleSetName string, instanceID string, parameters compute.VirtualMachineScaleSetVM) *retry.Error {\n\tresourceID := armclient.GetChildResourceID(\n\t\tc.subscriptionID,\n\t\tresourceGroupName,\n\t\t\"Microsoft.Compute/virtualMachineScaleSets\",\n\t\tVMScaleSetName,\n\t\t\"virtualMachines\",\n\t\tinstanceID,\n\t)\n\n\tresponse, rerr := c.armClient.PutResource(ctx, resourceID, parameters)\n\tdefer c.armClient.CloseResponse(ctx, response)\n\tif rerr != nil {\n\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmssvm.put.request\", resourceID, rerr.Error())\n\t\treturn rerr\n\t}\n\n\tif response != nil \u0026\u0026 response.StatusCode != http.StatusNoContent {\n\t\t_, rerr = c.updateResponder(response)\n\t\tif rerr != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmssvm.put.respond\", resourceID, rerr.Error())\n\t\t\treturn rerr\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":250,"to":277}} {"id":100033916,"name":"updateResponder","signature":"func (c *Client) updateResponder(resp *http.Response) (*compute.VirtualMachineScaleSetVM, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/azure_vmssvmclient.go","code":"func (c *Client) updateResponder(resp *http.Response) (*compute.VirtualMachineScaleSetVM, *retry.Error) {\n\tresult := \u0026compute.VirtualMachineScaleSetVM{}\n\terr := autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tresult.Response = autorest.Response{Response: resp}\n\treturn result, retry.GetError(resp, err)\n}","line":{"from":279,"to":287}} {"id":100033917,"name":"listResponder","signature":"func (c *Client) listResponder(resp *http.Response) (result compute.VirtualMachineScaleSetVMListResult, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/azure_vmssvmclient.go","code":"func (c *Client) listResponder(resp *http.Response) (result compute.VirtualMachineScaleSetVMListResult, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tautorest.ByIgnoring(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(\u0026result))\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}","line":{"from":289,"to":297}} {"id":100033918,"name":"virtualMachineScaleSetVMListResultPreparer","signature":"func (c *Client) virtualMachineScaleSetVMListResultPreparer(ctx context.Context, vmssvmlr compute.VirtualMachineScaleSetVMListResult) (*http.Request, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/azure_vmssvmclient.go","code":"// virtualMachineScaleSetListResultPreparer prepares a request to retrieve the next set of results.\n// It returns nil if no more results exist.\nfunc (c *Client) virtualMachineScaleSetVMListResultPreparer(ctx context.Context, vmssvmlr compute.VirtualMachineScaleSetVMListResult) (*http.Request, error) {\n\tif vmssvmlr.NextLink == nil || len(pointer.StringDeref(vmssvmlr.NextLink, \"\")) \u003c 1 {\n\t\treturn nil, nil\n\t}\n\n\tdecorators := []autorest.PrepareDecorator{\n\t\tautorest.WithBaseURL(pointer.StringDeref(vmssvmlr.NextLink, \"\")),\n\t}\n\treturn c.armClient.PrepareGetRequest(ctx, decorators...)\n}","line":{"from":299,"to":310}} {"id":100033919,"name":"listNextResults","signature":"func (c *Client) listNextResults(ctx context.Context, lastResults compute.VirtualMachineScaleSetVMListResult) (result compute.VirtualMachineScaleSetVMListResult, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/azure_vmssvmclient.go","code":"// listNextResults retrieves the next set of results, if any.\nfunc (c *Client) listNextResults(ctx context.Context, lastResults compute.VirtualMachineScaleSetVMListResult) (result compute.VirtualMachineScaleSetVMListResult, err error) {\n\treq, err := c.virtualMachineScaleSetVMListResultPreparer(ctx, lastResults)\n\tif err != nil {\n\t\treturn result, autorest.NewErrorWithError(err, \"vmssvmclient\", \"listNextResults\", nil, \"Failure preparing next results request\")\n\t}\n\tif req == nil {\n\t\treturn\n\t}\n\n\tresp, rerr := c.armClient.Send(ctx, req)\n\tdefer c.armClient.CloseResponse(ctx, resp)\n\tif rerr != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\treturn result, autorest.NewErrorWithError(rerr.Error(), \"vmssvmclient\", \"listNextResults\", resp, \"Failure sending next results request\")\n\t}\n\n\tresult, err = c.listResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"vmssvmclient\", \"listNextResults\", resp, \"Failure responding to next results request\")\n\t}\n\n\treturn\n}","line":{"from":312,"to":335}} {"id":100033920,"name":"NextWithContext","signature":"func (page *VirtualMachineScaleSetVMListResultPage) NextWithContext(ctx context.Context) (err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/azure_vmssvmclient.go","code":"// NextWithContext advances to the next page of values. If there was an error making\n// the request the page does not advance and the error is returned.\nfunc (page *VirtualMachineScaleSetVMListResultPage) NextWithContext(ctx context.Context) (err error) {\n\tnext, err := page.fn(ctx, page.vmssvlr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.vmssvlr = next\n\treturn nil\n}","line":{"from":343,"to":352}} {"id":100033921,"name":"Next","signature":"func (page *VirtualMachineScaleSetVMListResultPage) Next() error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/azure_vmssvmclient.go","code":"// Next advances to the next page of values. If there was an error making\n// the request the page does not advance and the error is returned.\n// Deprecated: Use NextWithContext() instead.\nfunc (page *VirtualMachineScaleSetVMListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}","line":{"from":354,"to":359}} {"id":100033922,"name":"NotDone","signature":"func (page VirtualMachineScaleSetVMListResultPage) NotDone() bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/azure_vmssvmclient.go","code":"// NotDone returns true if the page enumeration should be started or is not yet complete.\nfunc (page VirtualMachineScaleSetVMListResultPage) NotDone() bool {\n\treturn !page.vmssvlr.IsEmpty()\n}","line":{"from":361,"to":364}} {"id":100033923,"name":"Response","signature":"func (page VirtualMachineScaleSetVMListResultPage) Response() compute.VirtualMachineScaleSetVMListResult","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/azure_vmssvmclient.go","code":"// Response returns the raw server response from the last page request.\nfunc (page VirtualMachineScaleSetVMListResultPage) Response() compute.VirtualMachineScaleSetVMListResult {\n\treturn page.vmssvlr\n}","line":{"from":366,"to":369}} {"id":100033924,"name":"Values","signature":"func (page VirtualMachineScaleSetVMListResultPage) Values() []compute.VirtualMachineScaleSetVM","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/azure_vmssvmclient.go","code":"// Values returns the slice of values for the current page or nil if there are no values.\nfunc (page VirtualMachineScaleSetVMListResultPage) Values() []compute.VirtualMachineScaleSetVM {\n\tif page.vmssvlr.IsEmpty() {\n\t\treturn nil\n\t}\n\treturn *page.vmssvlr.Value\n}","line":{"from":371,"to":377}} {"id":100033925,"name":"UpdateVMs","signature":"func (c *Client) UpdateVMs(ctx context.Context, resourceGroupName string, VMScaleSetName string, instances map[string]compute.VirtualMachineScaleSetVM, source string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/azure_vmssvmclient.go","code":"// UpdateVMs updates a list of VirtualMachineScaleSetVM from map[instanceID]compute.VirtualMachineScaleSetVM.\nfunc (c *Client) UpdateVMs(ctx context.Context, resourceGroupName string, VMScaleSetName string, instances map[string]compute.VirtualMachineScaleSetVM, source string) *retry.Error {\n\tmc := metrics.NewMetricContext(\"vmssvm\", \"update_vms\", resourceGroupName, c.subscriptionID, source)\n\n\t// Report errors if the client is rate limited.\n\tif !c.rateLimiterWriter.TryAccept() {\n\t\tmc.RateLimitedCount()\n\t\treturn retry.GetRateLimitError(true, \"VMSSVMUpdateVMs\")\n\t}\n\n\t// Report errors if the client is throttled.\n\tif c.RetryAfterWriter.After(time.Now()) {\n\t\tmc.ThrottledCount()\n\t\trerr := retry.GetThrottlingError(\"VMSSVMUpdateVMs\", \"client throttled\", c.RetryAfterWriter)\n\t\treturn rerr\n\t}\n\n\trerr := c.updateVMSSVMs(ctx, resourceGroupName, VMScaleSetName, instances)\n\tmc.Observe(rerr.Error())\n\tif rerr != nil {\n\t\tif rerr.IsThrottled() {\n\t\t\t// Update RetryAfterReader so that no more requests would be sent until RetryAfter expires.\n\t\t\tc.RetryAfterWriter = rerr.RetryAfter\n\t\t}\n\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":379,"to":408}} {"id":100033926,"name":"updateVMSSVMs","signature":"func (c *Client) updateVMSSVMs(ctx context.Context, resourceGroupName string, VMScaleSetName string, instances map[string]compute.VirtualMachineScaleSetVM) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/azure_vmssvmclient.go","code":"// updateVMSSVMs updates a list of VirtualMachineScaleSetVM from map[instanceID]compute.VirtualMachineScaleSetVM.\nfunc (c *Client) updateVMSSVMs(ctx context.Context, resourceGroupName string, VMScaleSetName string, instances map[string]compute.VirtualMachineScaleSetVM) *retry.Error {\n\tresources := make(map[string]interface{})\n\tfor instanceID, parameter := range instances {\n\t\tresourceID := armclient.GetChildResourceID(\n\t\t\tc.subscriptionID,\n\t\t\tresourceGroupName,\n\t\t\t\"Microsoft.Compute/virtualMachineScaleSets\",\n\t\t\tVMScaleSetName,\n\t\t\t\"virtualMachines\",\n\t\t\tinstanceID,\n\t\t)\n\t\tresources[resourceID] = parameter\n\t}\n\n\tresponses := c.armClient.PutResources(ctx, resources)\n\terrors := make([]*retry.Error, 0)\n\tfor resourceID, resp := range responses {\n\t\tif resp == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tdefer c.armClient.CloseResponse(ctx, resp.Response)\n\t\tif resp.Error != nil {\n\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmssvm.put.request\", resourceID, resp.Error.Error())\n\t\t\terrors = append(errors, resp.Error)\n\t\t\tcontinue\n\t\t}\n\n\t\tif resp.Response != nil \u0026\u0026 resp.Response.StatusCode != http.StatusNoContent {\n\t\t\t_, rerr := c.updateResponder(resp.Response)\n\t\t\tif rerr != nil {\n\t\t\t\tklog.V(5).Infof(\"Received error in %s: resourceID: %s, error: %s\", \"vmssvm.put.respond\", resourceID, rerr.Error())\n\t\t\t\terrors = append(errors, rerr)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Aggregate errors.\n\tif len(errors) \u003e 0 {\n\t\trerr := \u0026retry.Error{}\n\t\terrs := make([]error, 0)\n\t\tfor _, err := range errors {\n\t\t\tif err.IsThrottled() \u0026\u0026 err.RetryAfter.After(err.RetryAfter) {\n\t\t\t\trerr.RetryAfter = err.RetryAfter\n\t\t\t}\n\t\t\terrs = append(errs, err.Error())\n\t\t}\n\t\trerr.RawError = utilerrors.Flatten(utilerrors.NewAggregate(errs))\n\t\treturn rerr\n\t}\n\n\treturn nil\n}","line":{"from":410,"to":463}} {"id":100033927,"name":"NewMockInterface","signature":"func NewMockInterface(ctrl *gomock.Controller) *MockInterface","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/mockvmssvmclient/interface.go","code":"// NewMockInterface creates a new mock instance.\nfunc NewMockInterface(ctrl *gomock.Controller) *MockInterface {\n\tmock := \u0026MockInterface{ctrl: ctrl}\n\tmock.recorder = \u0026MockInterfaceMockRecorder{mock}\n\treturn mock\n}","line":{"from":46,"to":51}} {"id":100033928,"name":"EXPECT","signature":"func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/mockvmssvmclient/interface.go","code":"// EXPECT returns an object that allows the caller to indicate expected use.\nfunc (m *MockInterface) EXPECT() *MockInterfaceMockRecorder {\n\treturn m.recorder\n}","line":{"from":53,"to":56}} {"id":100033929,"name":"Get","signature":"func (m *MockInterface) Get(ctx context.Context, resourceGroupName, VMScaleSetName, instanceID string, expand compute.InstanceViewTypes) (compute.VirtualMachineScaleSetVM, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/mockvmssvmclient/interface.go","code":"// Get mocks base method.\nfunc (m *MockInterface) Get(ctx context.Context, resourceGroupName, VMScaleSetName, instanceID string, expand compute.InstanceViewTypes) (compute.VirtualMachineScaleSetVM, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", ctx, resourceGroupName, VMScaleSetName, instanceID, expand)\n\tret0, _ := ret[0].(compute.VirtualMachineScaleSetVM)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":58,"to":65}} {"id":100033930,"name":"Get","signature":"func (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, VMScaleSetName, instanceID, expand interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/mockvmssvmclient/interface.go","code":"// Get indicates an expected call of Get.\nfunc (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, VMScaleSetName, instanceID, expand interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Get\", reflect.TypeOf((*MockInterface)(nil).Get), ctx, resourceGroupName, VMScaleSetName, instanceID, expand)\n}","line":{"from":67,"to":71}} {"id":100033931,"name":"List","signature":"func (m *MockInterface) List(ctx context.Context, resourceGroupName, virtualMachineScaleSetName, expand string) ([]compute.VirtualMachineScaleSetVM, *retry.Error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/mockvmssvmclient/interface.go","code":"// List mocks base method.\nfunc (m *MockInterface) List(ctx context.Context, resourceGroupName, virtualMachineScaleSetName, expand string) ([]compute.VirtualMachineScaleSetVM, *retry.Error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", ctx, resourceGroupName, virtualMachineScaleSetName, expand)\n\tret0, _ := ret[0].([]compute.VirtualMachineScaleSetVM)\n\tret1, _ := ret[1].(*retry.Error)\n\treturn ret0, ret1\n}","line":{"from":73,"to":80}} {"id":100033932,"name":"List","signature":"func (mr *MockInterfaceMockRecorder) List(ctx, resourceGroupName, virtualMachineScaleSetName, expand interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/mockvmssvmclient/interface.go","code":"// List indicates an expected call of List.\nfunc (mr *MockInterfaceMockRecorder) List(ctx, resourceGroupName, virtualMachineScaleSetName, expand interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"List\", reflect.TypeOf((*MockInterface)(nil).List), ctx, resourceGroupName, virtualMachineScaleSetName, expand)\n}","line":{"from":82,"to":86}} {"id":100033933,"name":"Update","signature":"func (m *MockInterface) Update(ctx context.Context, resourceGroupName, VMScaleSetName, instanceID string, parameters compute.VirtualMachineScaleSetVM, source string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/mockvmssvmclient/interface.go","code":"// Update mocks base method.\nfunc (m *MockInterface) Update(ctx context.Context, resourceGroupName, VMScaleSetName, instanceID string, parameters compute.VirtualMachineScaleSetVM, source string) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", ctx, resourceGroupName, VMScaleSetName, instanceID, parameters, source)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":88,"to":94}} {"id":100033934,"name":"Update","signature":"func (mr *MockInterfaceMockRecorder) Update(ctx, resourceGroupName, VMScaleSetName, instanceID, parameters, source interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/mockvmssvmclient/interface.go","code":"// Update indicates an expected call of Update.\nfunc (mr *MockInterfaceMockRecorder) Update(ctx, resourceGroupName, VMScaleSetName, instanceID, parameters, source interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockInterface)(nil).Update), ctx, resourceGroupName, VMScaleSetName, instanceID, parameters, source)\n}","line":{"from":96,"to":100}} {"id":100033935,"name":"UpdateVMs","signature":"func (m *MockInterface) UpdateVMs(ctx context.Context, resourceGroupName, VMScaleSetName string, instances map[string]compute.VirtualMachineScaleSetVM, source string) *retry.Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/mockvmssvmclient/interface.go","code":"// UpdateVMs mocks base method.\nfunc (m *MockInterface) UpdateVMs(ctx context.Context, resourceGroupName, VMScaleSetName string, instances map[string]compute.VirtualMachineScaleSetVM, source string) *retry.Error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateVMs\", ctx, resourceGroupName, VMScaleSetName, instances, source)\n\tret0, _ := ret[0].(*retry.Error)\n\treturn ret0\n}","line":{"from":102,"to":108}} {"id":100033936,"name":"UpdateVMs","signature":"func (mr *MockInterfaceMockRecorder) UpdateVMs(ctx, resourceGroupName, VMScaleSetName, instances, source interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/mockvmssvmclient/interface.go","code":"// UpdateVMs indicates an expected call of UpdateVMs.\nfunc (mr *MockInterfaceMockRecorder) UpdateVMs(ctx, resourceGroupName, VMScaleSetName, instances, source interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateVMs\", reflect.TypeOf((*MockInterface)(nil).UpdateVMs), ctx, resourceGroupName, VMScaleSetName, instances, source)\n}","line":{"from":110,"to":114}} {"id":100033937,"name":"NewMetricContext","signature":"func NewMetricContext(prefix, request, resourceGroup, subscriptionID, source string) *MetricContext","file":"staging/src/k8s.io/legacy-cloud-providers/azure/metrics/azure_metrics.go","code":"// NewMetricContext creates a new MetricContext.\nfunc NewMetricContext(prefix, request, resourceGroup, subscriptionID, source string) *MetricContext {\n\treturn \u0026MetricContext{\n\t\tstart: time.Now(),\n\t\tattributes: []string{prefix + \"_\" + request, strings.ToLower(resourceGroup), subscriptionID, source},\n\t}\n}","line":{"from":68,"to":74}} {"id":100033938,"name":"RateLimitedCount","signature":"func (mc *MetricContext) RateLimitedCount()","file":"staging/src/k8s.io/legacy-cloud-providers/azure/metrics/azure_metrics.go","code":"// RateLimitedCount records the metrics for rate limited request count.\nfunc (mc *MetricContext) RateLimitedCount() {\n\tapiMetrics.rateLimitedCount.WithLabelValues(mc.attributes...).Inc()\n}","line":{"from":76,"to":79}} {"id":100033939,"name":"ThrottledCount","signature":"func (mc *MetricContext) ThrottledCount()","file":"staging/src/k8s.io/legacy-cloud-providers/azure/metrics/azure_metrics.go","code":"// ThrottledCount records the metrics for throttled request count.\nfunc (mc *MetricContext) ThrottledCount() {\n\tapiMetrics.throttledCount.WithLabelValues(mc.attributes...).Inc()\n}","line":{"from":81,"to":84}} {"id":100033940,"name":"Observe","signature":"func (mc *MetricContext) Observe(err error) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/metrics/azure_metrics.go","code":"// Observe observes the request latency and failed requests.\nfunc (mc *MetricContext) Observe(err error) error {\n\tapiMetrics.latency.WithLabelValues(mc.attributes...).Observe(\n\t\ttime.Since(mc.start).Seconds())\n\tif err != nil {\n\t\tapiMetrics.errors.WithLabelValues(mc.attributes...).Inc()\n\t}\n\n\treturn err\n}","line":{"from":86,"to":95}} {"id":100033941,"name":"ObserveOperationWithResult","signature":"func (mc *MetricContext) ObserveOperationWithResult(isOperationSucceeded bool)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/metrics/azure_metrics.go","code":"// ObserveOperationWithResult observes the request latency and failed requests of an operation.\nfunc (mc *MetricContext) ObserveOperationWithResult(isOperationSucceeded bool) {\n\toperationMetrics.operationLatency.WithLabelValues(mc.attributes...).Observe(\n\t\ttime.Since(mc.start).Seconds())\n\tif !isOperationSucceeded {\n\t\tmc.CountFailedOperation()\n\t}\n}","line":{"from":97,"to":104}} {"id":100033942,"name":"CountFailedOperation","signature":"func (mc *MetricContext) CountFailedOperation()","file":"staging/src/k8s.io/legacy-cloud-providers/azure/metrics/azure_metrics.go","code":"// CountFailedOperation increase the number of failed operations\nfunc (mc *MetricContext) CountFailedOperation() {\n\toperationMetrics.operationFailureCount.WithLabelValues(mc.attributes...).Inc()\n}","line":{"from":106,"to":109}} {"id":100033943,"name":"registerAPIMetrics","signature":"func registerAPIMetrics() *apiCallMetrics","file":"staging/src/k8s.io/legacy-cloud-providers/azure/metrics/azure_metrics.go","code":"// registerAPIMetrics registers the API metrics.\nfunc registerAPIMetrics() *apiCallMetrics {\n\tmetrics := \u0026apiCallMetrics{\n\t\tlatency: metrics.NewHistogramVec(\n\t\t\t\u0026metrics.HistogramOpts{\n\t\t\t\tNamespace: azureMetricsNamespace,\n\t\t\t\tName: \"api_request_duration_seconds\",\n\t\t\t\tHelp: \"Latency of an Azure API call\",\n\t\t\t\tBuckets: []float64{.1, .25, .5, 1, 2.5, 5, 10, 15, 25, 50, 120, 300, 600, 1200},\n\t\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t\t},\n\t\t\tmetricLabels,\n\t\t),\n\t\terrors: metrics.NewCounterVec(\n\t\t\t\u0026metrics.CounterOpts{\n\t\t\t\tNamespace: azureMetricsNamespace,\n\t\t\t\tName: \"api_request_errors\",\n\t\t\t\tHelp: \"Number of errors for an Azure API call\",\n\t\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t\t},\n\t\t\tmetricLabels,\n\t\t),\n\t\trateLimitedCount: metrics.NewCounterVec(\n\t\t\t\u0026metrics.CounterOpts{\n\t\t\t\tNamespace: azureMetricsNamespace,\n\t\t\t\tName: \"api_request_ratelimited_count\",\n\t\t\t\tHelp: \"Number of rate limited Azure API calls\",\n\t\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t\t},\n\t\t\tmetricLabels,\n\t\t),\n\t\tthrottledCount: metrics.NewCounterVec(\n\t\t\t\u0026metrics.CounterOpts{\n\t\t\t\tNamespace: azureMetricsNamespace,\n\t\t\t\tName: \"api_request_throttled_count\",\n\t\t\t\tHelp: \"Number of throttled Azure API calls\",\n\t\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t\t},\n\t\t\tmetricLabels,\n\t\t),\n\t}\n\n\tlegacyregistry.MustRegister(metrics.latency)\n\tlegacyregistry.MustRegister(metrics.errors)\n\tlegacyregistry.MustRegister(metrics.rateLimitedCount)\n\tlegacyregistry.MustRegister(metrics.throttledCount)\n\n\treturn metrics\n}","line":{"from":111,"to":159}} {"id":100033944,"name":"registerOperationMetrics","signature":"func registerOperationMetrics() *operationCallMetrics","file":"staging/src/k8s.io/legacy-cloud-providers/azure/metrics/azure_metrics.go","code":"// registerOperationMetrics registers the operation metrics.\nfunc registerOperationMetrics() *operationCallMetrics {\n\tmetrics := \u0026operationCallMetrics{\n\t\toperationLatency: metrics.NewHistogramVec(\n\t\t\t\u0026metrics.HistogramOpts{\n\t\t\t\tNamespace: azureMetricsNamespace,\n\t\t\t\tName: \"op_duration_seconds\",\n\t\t\t\tHelp: \"Latency of an Azure service operation\",\n\t\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t\t\tBuckets: []float64{0.1, 0.2, 0.5, 1, 10, 20, 30, 40, 50, 60, 100, 200, 300},\n\t\t\t},\n\t\t\tmetricLabels,\n\t\t),\n\t\toperationFailureCount: metrics.NewCounterVec(\n\t\t\t\u0026metrics.CounterOpts{\n\t\t\t\tNamespace: azureMetricsNamespace,\n\t\t\t\tName: \"op_failure_count\",\n\t\t\t\tHelp: \"Number of failed Azure service operations\",\n\t\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t\t},\n\t\t\tmetricLabels,\n\t\t),\n\t}\n\n\tlegacyregistry.MustRegister(metrics.operationLatency)\n\tlegacyregistry.MustRegister(metrics.operationFailureCount)\n\n\treturn metrics\n}","line":{"from":161,"to":189}} {"id":100033945,"name":"NewMockVMSet","signature":"func NewMockVMSet(ctrl *gomock.Controller) *MockVMSet","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// NewMockVMSet creates a new mock instance.\nfunc NewMockVMSet(ctrl *gomock.Controller) *MockVMSet {\n\tmock := \u0026MockVMSet{ctrl: ctrl}\n\tmock.recorder = \u0026MockVMSetMockRecorder{mock}\n\treturn mock\n}","line":{"from":49,"to":54}} {"id":100033946,"name":"EXPECT","signature":"func (m *MockVMSet) EXPECT() *MockVMSetMockRecorder","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// EXPECT returns an object that allows the caller to indicate expected use.\nfunc (m *MockVMSet) EXPECT() *MockVMSetMockRecorder {\n\treturn m.recorder\n}","line":{"from":56,"to":59}} {"id":100033947,"name":"AttachDisk","signature":"func (m *MockVMSet) AttachDisk(isManagedDisk bool, diskName, diskURI string, nodeName types.NodeName, lun int32, cachingMode compute.CachingTypes, diskEncryptionSetID string, writeAcceleratorEnabled bool) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// AttachDisk mocks base method.\nfunc (m *MockVMSet) AttachDisk(isManagedDisk bool, diskName, diskURI string, nodeName types.NodeName, lun int32, cachingMode compute.CachingTypes, diskEncryptionSetID string, writeAcceleratorEnabled bool) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AttachDisk\", isManagedDisk, diskName, diskURI, nodeName, lun, cachingMode, diskEncryptionSetID, writeAcceleratorEnabled)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}","line":{"from":61,"to":67}} {"id":100033948,"name":"AttachDisk","signature":"func (mr *MockVMSetMockRecorder) AttachDisk(isManagedDisk, diskName, diskURI, nodeName, lun, cachingMode, diskEncryptionSetID, writeAcceleratorEnabled interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// AttachDisk indicates an expected call of AttachDisk.\nfunc (mr *MockVMSetMockRecorder) AttachDisk(isManagedDisk, diskName, diskURI, nodeName, lun, cachingMode, diskEncryptionSetID, writeAcceleratorEnabled interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AttachDisk\", reflect.TypeOf((*MockVMSet)(nil).AttachDisk), isManagedDisk, diskName, diskURI, nodeName, lun, cachingMode, diskEncryptionSetID, writeAcceleratorEnabled)\n}","line":{"from":69,"to":73}} {"id":100033949,"name":"DetachDisk","signature":"func (m *MockVMSet) DetachDisk(diskName, diskURI string, nodeName types.NodeName) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// DetachDisk mocks base method.\nfunc (m *MockVMSet) DetachDisk(diskName, diskURI string, nodeName types.NodeName) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DetachDisk\", diskName, diskURI, nodeName)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}","line":{"from":75,"to":81}} {"id":100033950,"name":"DetachDisk","signature":"func (mr *MockVMSetMockRecorder) DetachDisk(diskName, diskURI, nodeName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// DetachDisk indicates an expected call of DetachDisk.\nfunc (mr *MockVMSetMockRecorder) DetachDisk(diskName, diskURI, nodeName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DetachDisk\", reflect.TypeOf((*MockVMSet)(nil).DetachDisk), diskName, diskURI, nodeName)\n}","line":{"from":83,"to":87}} {"id":100033951,"name":"EnsureBackendPoolDeleted","signature":"func (m *MockVMSet) EnsureBackendPoolDeleted(service *v1.Service, backendPoolID, vmSetName string, backendAddressPools *[]network.BackendAddressPool, deleteFromVMSet bool) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// EnsureBackendPoolDeleted mocks base method.\nfunc (m *MockVMSet) EnsureBackendPoolDeleted(service *v1.Service, backendPoolID, vmSetName string, backendAddressPools *[]network.BackendAddressPool, deleteFromVMSet bool) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"EnsureBackendPoolDeleted\", service, backendPoolID, vmSetName, backendAddressPools, deleteFromVMSet)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}","line":{"from":89,"to":95}} {"id":100033952,"name":"EnsureBackendPoolDeleted","signature":"func (mr *MockVMSetMockRecorder) EnsureBackendPoolDeleted(service, backendPoolID, vmSetName, backendAddressPools, deleteFromVMSet interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// EnsureBackendPoolDeleted indicates an expected call of EnsureBackendPoolDeleted.\nfunc (mr *MockVMSetMockRecorder) EnsureBackendPoolDeleted(service, backendPoolID, vmSetName, backendAddressPools, deleteFromVMSet interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"EnsureBackendPoolDeleted\", reflect.TypeOf((*MockVMSet)(nil).EnsureBackendPoolDeleted), service, backendPoolID, vmSetName, backendAddressPools, deleteFromVMSet)\n}","line":{"from":97,"to":101}} {"id":100033953,"name":"EnsureHostInPool","signature":"func (m *MockVMSet) EnsureHostInPool(service *v1.Service, nodeName types.NodeName, backendPoolID, vmSetName string, isInternal bool) (string, string, string, *compute.VirtualMachineScaleSetVM, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// EnsureHostInPool mocks base method.\nfunc (m *MockVMSet) EnsureHostInPool(service *v1.Service, nodeName types.NodeName, backendPoolID, vmSetName string, isInternal bool) (string, string, string, *compute.VirtualMachineScaleSetVM, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"EnsureHostInPool\", service, nodeName, backendPoolID, vmSetName, isInternal)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(string)\n\tret2, _ := ret[2].(string)\n\tret3, _ := ret[3].(*compute.VirtualMachineScaleSetVM)\n\tret4, _ := ret[4].(error)\n\treturn ret0, ret1, ret2, ret3, ret4\n}","line":{"from":103,"to":113}} {"id":100033954,"name":"EnsureHostInPool","signature":"func (mr *MockVMSetMockRecorder) EnsureHostInPool(service, nodeName, backendPoolID, vmSetName, isInternal interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// EnsureHostInPool indicates an expected call of EnsureHostInPool.\nfunc (mr *MockVMSetMockRecorder) EnsureHostInPool(service, nodeName, backendPoolID, vmSetName, isInternal interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"EnsureHostInPool\", reflect.TypeOf((*MockVMSet)(nil).EnsureHostInPool), service, nodeName, backendPoolID, vmSetName, isInternal)\n}","line":{"from":115,"to":119}} {"id":100033955,"name":"EnsureHostsInPool","signature":"func (m *MockVMSet) EnsureHostsInPool(service *v1.Service, nodes []*v1.Node, backendPoolID, vmSetName string, isInternal bool) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// EnsureHostsInPool mocks base method.\nfunc (m *MockVMSet) EnsureHostsInPool(service *v1.Service, nodes []*v1.Node, backendPoolID, vmSetName string, isInternal bool) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"EnsureHostsInPool\", service, nodes, backendPoolID, vmSetName, isInternal)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}","line":{"from":121,"to":127}} {"id":100033956,"name":"EnsureHostsInPool","signature":"func (mr *MockVMSetMockRecorder) EnsureHostsInPool(service, nodes, backendPoolID, vmSetName, isInternal interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// EnsureHostsInPool indicates an expected call of EnsureHostsInPool.\nfunc (mr *MockVMSetMockRecorder) EnsureHostsInPool(service, nodes, backendPoolID, vmSetName, isInternal interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"EnsureHostsInPool\", reflect.TypeOf((*MockVMSet)(nil).EnsureHostsInPool), service, nodes, backendPoolID, vmSetName, isInternal)\n}","line":{"from":129,"to":133}} {"id":100033957,"name":"GetDataDisks","signature":"func (m *MockVMSet) GetDataDisks(nodeName types.NodeName, crt cache.AzureCacheReadType) ([]compute.DataDisk, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// GetDataDisks mocks base method.\nfunc (m *MockVMSet) GetDataDisks(nodeName types.NodeName, crt cache.AzureCacheReadType) ([]compute.DataDisk, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetDataDisks\", nodeName, crt)\n\tret0, _ := ret[0].([]compute.DataDisk)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}","line":{"from":135,"to":142}} {"id":100033958,"name":"GetDataDisks","signature":"func (mr *MockVMSetMockRecorder) GetDataDisks(nodeName, crt interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// GetDataDisks indicates an expected call of GetDataDisks.\nfunc (mr *MockVMSetMockRecorder) GetDataDisks(nodeName, crt interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetDataDisks\", reflect.TypeOf((*MockVMSet)(nil).GetDataDisks), nodeName, crt)\n}","line":{"from":144,"to":148}} {"id":100033959,"name":"GetIPByNodeName","signature":"func (m *MockVMSet) GetIPByNodeName(name string) (string, string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// GetIPByNodeName mocks base method.\nfunc (m *MockVMSet) GetIPByNodeName(name string) (string, string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetIPByNodeName\", name)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(string)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}","line":{"from":150,"to":158}} {"id":100033960,"name":"GetIPByNodeName","signature":"func (mr *MockVMSetMockRecorder) GetIPByNodeName(name interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// GetIPByNodeName indicates an expected call of GetIPByNodeName.\nfunc (mr *MockVMSetMockRecorder) GetIPByNodeName(name interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetIPByNodeName\", reflect.TypeOf((*MockVMSet)(nil).GetIPByNodeName), name)\n}","line":{"from":160,"to":164}} {"id":100033961,"name":"GetInstanceIDByNodeName","signature":"func (m *MockVMSet) GetInstanceIDByNodeName(name string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// GetInstanceIDByNodeName mocks base method.\nfunc (m *MockVMSet) GetInstanceIDByNodeName(name string) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetInstanceIDByNodeName\", name)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}","line":{"from":166,"to":173}} {"id":100033962,"name":"GetInstanceIDByNodeName","signature":"func (mr *MockVMSetMockRecorder) GetInstanceIDByNodeName(name interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// GetInstanceIDByNodeName indicates an expected call of GetInstanceIDByNodeName.\nfunc (mr *MockVMSetMockRecorder) GetInstanceIDByNodeName(name interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetInstanceIDByNodeName\", reflect.TypeOf((*MockVMSet)(nil).GetInstanceIDByNodeName), name)\n}","line":{"from":175,"to":179}} {"id":100033963,"name":"GetInstanceTypeByNodeName","signature":"func (m *MockVMSet) GetInstanceTypeByNodeName(name string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// GetInstanceTypeByNodeName mocks base method.\nfunc (m *MockVMSet) GetInstanceTypeByNodeName(name string) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetInstanceTypeByNodeName\", name)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}","line":{"from":181,"to":188}} {"id":100033964,"name":"GetInstanceTypeByNodeName","signature":"func (mr *MockVMSetMockRecorder) GetInstanceTypeByNodeName(name interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// GetInstanceTypeByNodeName indicates an expected call of GetInstanceTypeByNodeName.\nfunc (mr *MockVMSetMockRecorder) GetInstanceTypeByNodeName(name interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetInstanceTypeByNodeName\", reflect.TypeOf((*MockVMSet)(nil).GetInstanceTypeByNodeName), name)\n}","line":{"from":190,"to":194}} {"id":100033965,"name":"GetNodeNameByIPConfigurationID","signature":"func (m *MockVMSet) GetNodeNameByIPConfigurationID(ipConfigurationID string) (string, string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// GetNodeNameByIPConfigurationID mocks base method.\nfunc (m *MockVMSet) GetNodeNameByIPConfigurationID(ipConfigurationID string) (string, string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetNodeNameByIPConfigurationID\", ipConfigurationID)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(string)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}","line":{"from":196,"to":204}} {"id":100033966,"name":"GetNodeNameByIPConfigurationID","signature":"func (mr *MockVMSetMockRecorder) GetNodeNameByIPConfigurationID(ipConfigurationID interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// GetNodeNameByIPConfigurationID indicates an expected call of GetNodeNameByIPConfigurationID.\nfunc (mr *MockVMSetMockRecorder) GetNodeNameByIPConfigurationID(ipConfigurationID interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetNodeNameByIPConfigurationID\", reflect.TypeOf((*MockVMSet)(nil).GetNodeNameByIPConfigurationID), ipConfigurationID)\n}","line":{"from":206,"to":210}} {"id":100033967,"name":"GetNodeNameByProviderID","signature":"func (m *MockVMSet) GetNodeNameByProviderID(providerID string) (types.NodeName, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// GetNodeNameByProviderID mocks base method.\nfunc (m *MockVMSet) GetNodeNameByProviderID(providerID string) (types.NodeName, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetNodeNameByProviderID\", providerID)\n\tret0, _ := ret[0].(types.NodeName)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}","line":{"from":212,"to":219}} {"id":100033968,"name":"GetNodeNameByProviderID","signature":"func (mr *MockVMSetMockRecorder) GetNodeNameByProviderID(providerID interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// GetNodeNameByProviderID indicates an expected call of GetNodeNameByProviderID.\nfunc (mr *MockVMSetMockRecorder) GetNodeNameByProviderID(providerID interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetNodeNameByProviderID\", reflect.TypeOf((*MockVMSet)(nil).GetNodeNameByProviderID), providerID)\n}","line":{"from":221,"to":225}} {"id":100033969,"name":"GetPowerStatusByNodeName","signature":"func (m *MockVMSet) GetPowerStatusByNodeName(name string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// GetPowerStatusByNodeName mocks base method.\nfunc (m *MockVMSet) GetPowerStatusByNodeName(name string) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetPowerStatusByNodeName\", name)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}","line":{"from":227,"to":234}} {"id":100033970,"name":"GetPowerStatusByNodeName","signature":"func (mr *MockVMSetMockRecorder) GetPowerStatusByNodeName(name interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// GetPowerStatusByNodeName indicates an expected call of GetPowerStatusByNodeName.\nfunc (mr *MockVMSetMockRecorder) GetPowerStatusByNodeName(name interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetPowerStatusByNodeName\", reflect.TypeOf((*MockVMSet)(nil).GetPowerStatusByNodeName), name)\n}","line":{"from":236,"to":240}} {"id":100033971,"name":"GetPrimaryInterface","signature":"func (m *MockVMSet) GetPrimaryInterface(nodeName string) (network.Interface, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// GetPrimaryInterface mocks base method.\nfunc (m *MockVMSet) GetPrimaryInterface(nodeName string) (network.Interface, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetPrimaryInterface\", nodeName)\n\tret0, _ := ret[0].(network.Interface)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}","line":{"from":242,"to":249}} {"id":100033972,"name":"GetPrimaryInterface","signature":"func (mr *MockVMSetMockRecorder) GetPrimaryInterface(nodeName interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// GetPrimaryInterface indicates an expected call of GetPrimaryInterface.\nfunc (mr *MockVMSetMockRecorder) GetPrimaryInterface(nodeName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetPrimaryInterface\", reflect.TypeOf((*MockVMSet)(nil).GetPrimaryInterface), nodeName)\n}","line":{"from":251,"to":255}} {"id":100033973,"name":"GetPrimaryVMSetName","signature":"func (m *MockVMSet) GetPrimaryVMSetName() string","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// GetPrimaryVMSetName mocks base method.\nfunc (m *MockVMSet) GetPrimaryVMSetName() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetPrimaryVMSetName\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}","line":{"from":257,"to":263}} {"id":100033974,"name":"GetPrimaryVMSetName","signature":"func (mr *MockVMSetMockRecorder) GetPrimaryVMSetName() *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// GetPrimaryVMSetName indicates an expected call of GetPrimaryVMSetName.\nfunc (mr *MockVMSetMockRecorder) GetPrimaryVMSetName() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetPrimaryVMSetName\", reflect.TypeOf((*MockVMSet)(nil).GetPrimaryVMSetName))\n}","line":{"from":265,"to":269}} {"id":100033975,"name":"GetPrivateIPsByNodeName","signature":"func (m *MockVMSet) GetPrivateIPsByNodeName(name string) ([]string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// GetPrivateIPsByNodeName mocks base method.\nfunc (m *MockVMSet) GetPrivateIPsByNodeName(name string) ([]string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetPrivateIPsByNodeName\", name)\n\tret0, _ := ret[0].([]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}","line":{"from":271,"to":278}} {"id":100033976,"name":"GetPrivateIPsByNodeName","signature":"func (mr *MockVMSetMockRecorder) GetPrivateIPsByNodeName(name interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// GetPrivateIPsByNodeName indicates an expected call of GetPrivateIPsByNodeName.\nfunc (mr *MockVMSetMockRecorder) GetPrivateIPsByNodeName(name interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetPrivateIPsByNodeName\", reflect.TypeOf((*MockVMSet)(nil).GetPrivateIPsByNodeName), name)\n}","line":{"from":280,"to":284}} {"id":100033977,"name":"GetProvisioningStateByNodeName","signature":"func (m *MockVMSet) GetProvisioningStateByNodeName(name string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// GetProvisioningStateByNodeName mocks base method.\nfunc (m *MockVMSet) GetProvisioningStateByNodeName(name string) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetProvisioningStateByNodeName\", name)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}","line":{"from":286,"to":293}} {"id":100033978,"name":"GetProvisioningStateByNodeName","signature":"func (mr *MockVMSetMockRecorder) GetProvisioningStateByNodeName(name interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// GetProvisioningStateByNodeName indicates an expected call of GetProvisioningStateByNodeName.\nfunc (mr *MockVMSetMockRecorder) GetProvisioningStateByNodeName(name interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetProvisioningStateByNodeName\", reflect.TypeOf((*MockVMSet)(nil).GetProvisioningStateByNodeName), name)\n}","line":{"from":295,"to":299}} {"id":100033979,"name":"GetVMSetNames","signature":"func (m *MockVMSet) GetVMSetNames(service *v1.Service, nodes []*v1.Node) (*[]string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// GetVMSetNames mocks base method.\nfunc (m *MockVMSet) GetVMSetNames(service *v1.Service, nodes []*v1.Node) (*[]string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVMSetNames\", service, nodes)\n\tret0, _ := ret[0].(*[]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}","line":{"from":301,"to":308}} {"id":100033980,"name":"GetVMSetNames","signature":"func (mr *MockVMSetMockRecorder) GetVMSetNames(service, nodes interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// GetVMSetNames indicates an expected call of GetVMSetNames.\nfunc (mr *MockVMSetMockRecorder) GetVMSetNames(service, nodes interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetVMSetNames\", reflect.TypeOf((*MockVMSet)(nil).GetVMSetNames), service, nodes)\n}","line":{"from":310,"to":314}} {"id":100033981,"name":"GetZoneByNodeName","signature":"func (m *MockVMSet) GetZoneByNodeName(name string) (cloudprovider.Zone, error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// GetZoneByNodeName mocks base method.\nfunc (m *MockVMSet) GetZoneByNodeName(name string) (cloudprovider.Zone, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetZoneByNodeName\", name)\n\tret0, _ := ret[0].(cloudprovider.Zone)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}","line":{"from":316,"to":323}} {"id":100033982,"name":"GetZoneByNodeName","signature":"func (mr *MockVMSetMockRecorder) GetZoneByNodeName(name interface{}) *gomock.Call","file":"staging/src/k8s.io/legacy-cloud-providers/azure/mockvmsets/azure_mock_vmsets.go","code":"// GetZoneByNodeName indicates an expected call of GetZoneByNodeName.\nfunc (mr *MockVMSetMockRecorder) GetZoneByNodeName(name interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetZoneByNodeName\", reflect.TypeOf((*MockVMSet)(nil).GetZoneByNodeName), name)\n}","line":{"from":325,"to":329}} {"id":100033983,"name":"Error","signature":"func (err *Error) Error() error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/retry/azure_error.go","code":"// Error returns the error.\n// Note that Error doesn't implement error interface because (nil *Error) != (nil error).\nfunc (err *Error) Error() error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\t// Convert time to seconds for better logging.\n\tretryAfterSeconds := 0\n\tcurTime := now()\n\tif err.RetryAfter.After(curTime) {\n\t\tretryAfterSeconds = int(err.RetryAfter.Sub(curTime) / time.Second)\n\t}\n\n\treturn fmt.Errorf(\"Retriable: %v, RetryAfter: %ds, HTTPStatusCode: %d, RawError: %w\",\n\t\terr.Retriable, retryAfterSeconds, err.HTTPStatusCode, err.RawError)\n}","line":{"from":66,"to":82}} {"id":100033984,"name":"IsThrottled","signature":"func (err *Error) IsThrottled() bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/retry/azure_error.go","code":"// IsThrottled returns true the if the request is being throttled.\nfunc (err *Error) IsThrottled() bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\n\treturn err.HTTPStatusCode == http.StatusTooManyRequests || err.RetryAfter.After(now())\n}","line":{"from":84,"to":91}} {"id":100033985,"name":"IsNotFound","signature":"func (err *Error) IsNotFound() bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/retry/azure_error.go","code":"// IsNotFound returns true the if the requested object wasn't found\nfunc (err *Error) IsNotFound() bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\n\treturn err.HTTPStatusCode == http.StatusNotFound\n}","line":{"from":93,"to":100}} {"id":100033986,"name":"NewError","signature":"func NewError(retriable bool, err error) *Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/retry/azure_error.go","code":"// NewError creates a new Error.\nfunc NewError(retriable bool, err error) *Error {\n\treturn \u0026Error{\n\t\tRetriable: retriable,\n\t\tRawError: err,\n\t}\n}","line":{"from":102,"to":108}} {"id":100033987,"name":"GetRetriableError","signature":"func GetRetriableError(err error) *Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/retry/azure_error.go","code":"// GetRetriableError gets new retriable Error.\nfunc GetRetriableError(err error) *Error {\n\treturn \u0026Error{\n\t\tRetriable: true,\n\t\tRawError: err,\n\t}\n}","line":{"from":110,"to":116}} {"id":100033988,"name":"GetRateLimitError","signature":"func GetRateLimitError(isWrite bool, opName string) *Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/retry/azure_error.go","code":"// GetRateLimitError creates a new error for rate limiting.\nfunc GetRateLimitError(isWrite bool, opName string) *Error {\n\topType := \"read\"\n\tif isWrite {\n\t\topType = \"write\"\n\t}\n\treturn GetRetriableError(fmt.Errorf(\"azure cloud provider rate limited(%s) for operation %q\", opType, opName))\n}","line":{"from":118,"to":125}} {"id":100033989,"name":"GetThrottlingError","signature":"func GetThrottlingError(operation, reason string, retryAfter time.Time) *Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/retry/azure_error.go","code":"// GetThrottlingError creates a new error for throttling.\nfunc GetThrottlingError(operation, reason string, retryAfter time.Time) *Error {\n\trawError := fmt.Errorf(\"azure cloud provider throttled for operation %s with reason %q\", operation, reason)\n\treturn \u0026Error{\n\t\tRetriable: true,\n\t\tRawError: rawError,\n\t\tRetryAfter: retryAfter,\n\t}\n}","line":{"from":127,"to":135}} {"id":100033990,"name":"GetError","signature":"func GetError(resp *http.Response, err error) *Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/retry/azure_error.go","code":"// GetError gets a new Error based on resp and error.\nfunc GetError(resp *http.Response, err error) *Error {\n\tif err == nil \u0026\u0026 resp == nil {\n\t\treturn nil\n\t}\n\n\tif err == nil \u0026\u0026 resp != nil \u0026\u0026 isSuccessHTTPResponse(resp) {\n\t\t// HTTP 2xx suggests a successful response\n\t\treturn nil\n\t}\n\n\tretryAfter := time.Time{}\n\tif retryAfterDuration := getRetryAfter(resp); retryAfterDuration != 0 {\n\t\tretryAfter = now().Add(retryAfterDuration)\n\t}\n\treturn \u0026Error{\n\t\tRawError: getRawError(resp, err),\n\t\tRetryAfter: retryAfter,\n\t\tRetriable: shouldRetryHTTPRequest(resp, err),\n\t\tHTTPStatusCode: getHTTPStatusCode(resp),\n\t}\n}","line":{"from":137,"to":158}} {"id":100033991,"name":"isSuccessHTTPResponse","signature":"func isSuccessHTTPResponse(resp *http.Response) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/retry/azure_error.go","code":"// isSuccessHTTPResponse determines if the response from an HTTP request suggests success\nfunc isSuccessHTTPResponse(resp *http.Response) bool {\n\tif resp == nil {\n\t\treturn false\n\t}\n\n\t// HTTP 2xx suggests a successful response\n\tif 199 \u003c resp.StatusCode \u0026\u0026 resp.StatusCode \u003c 300 {\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":160,"to":172}} {"id":100033992,"name":"getRawError","signature":"func getRawError(resp *http.Response, err error) error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/retry/azure_error.go","code":"func getRawError(resp *http.Response, err error) error {\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif resp == nil || resp.Body == nil {\n\t\treturn fmt.Errorf(\"empty HTTP response\")\n\t}\n\n\t// return the http status if it is unable to get response body.\n\tdefer resp.Body.Close()\n\trespBody, _ := ioutil.ReadAll(resp.Body)\n\tresp.Body = ioutil.NopCloser(bytes.NewReader(respBody))\n\tif len(respBody) == 0 {\n\t\treturn fmt.Errorf(\"HTTP status code (%d)\", resp.StatusCode)\n\t}\n\n\t// return the raw response body.\n\treturn fmt.Errorf(\"%s\", string(respBody))\n}","line":{"from":174,"to":193}} {"id":100033993,"name":"getHTTPStatusCode","signature":"func getHTTPStatusCode(resp *http.Response) int","file":"staging/src/k8s.io/legacy-cloud-providers/azure/retry/azure_error.go","code":"func getHTTPStatusCode(resp *http.Response) int {\n\tif resp == nil {\n\t\treturn -1\n\t}\n\n\treturn resp.StatusCode\n}","line":{"from":195,"to":201}} {"id":100033994,"name":"shouldRetryHTTPRequest","signature":"func shouldRetryHTTPRequest(resp *http.Response, err error) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/retry/azure_error.go","code":"// shouldRetryHTTPRequest determines if the request is retriable.\nfunc shouldRetryHTTPRequest(resp *http.Response, err error) bool {\n\tif resp != nil {\n\t\tfor _, code := range StatusCodesForRetry {\n\t\t\tif resp.StatusCode == code {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\t// should retry on \u003c200, error\u003e.\n\t\tif isSuccessHTTPResponse(resp) \u0026\u0026 err != nil {\n\t\t\treturn true\n\t\t}\n\n\t\treturn false\n\t}\n\n\t// should retry when error is not nil and no http.Response.\n\tif err != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":203,"to":226}} {"id":100033995,"name":"getRetryAfter","signature":"func getRetryAfter(resp *http.Response) time.Duration","file":"staging/src/k8s.io/legacy-cloud-providers/azure/retry/azure_error.go","code":"// getRetryAfter gets the retryAfter from http response.\n// The value of Retry-After can be either the number of seconds or a date in RFC1123 format.\nfunc getRetryAfter(resp *http.Response) time.Duration {\n\tif resp == nil {\n\t\treturn 0\n\t}\n\n\tra := resp.Header.Get(RetryAfterHeaderKey)\n\tif ra == \"\" {\n\t\treturn 0\n\t}\n\n\tvar dur time.Duration\n\tif retryAfter, _ := strconv.Atoi(ra); retryAfter \u003e 0 {\n\t\tdur = time.Duration(retryAfter) * time.Second\n\t} else if t, err := time.Parse(time.RFC1123, ra); err == nil {\n\t\tdur = t.Sub(now())\n\t}\n\treturn dur\n}","line":{"from":228,"to":247}} {"id":100033996,"name":"GetErrorWithRetriableHTTPStatusCodes","signature":"func GetErrorWithRetriableHTTPStatusCodes(resp *http.Response, err error, retriableHTTPStatusCodes []int) *Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/retry/azure_error.go","code":"// GetErrorWithRetriableHTTPStatusCodes gets an error with RetriableHTTPStatusCodes.\n// It is used to retry on some HTTPStatusCodes.\nfunc GetErrorWithRetriableHTTPStatusCodes(resp *http.Response, err error, retriableHTTPStatusCodes []int) *Error {\n\trerr := GetError(resp, err)\n\tif rerr == nil {\n\t\treturn nil\n\t}\n\n\tfor _, code := range retriableHTTPStatusCodes {\n\t\tif rerr.HTTPStatusCode == code {\n\t\t\trerr.Retriable = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn rerr\n}","line":{"from":249,"to":265}} {"id":100033997,"name":"GetStatusNotFoundAndForbiddenIgnoredError","signature":"func GetStatusNotFoundAndForbiddenIgnoredError(resp *http.Response, err error) *Error","file":"staging/src/k8s.io/legacy-cloud-providers/azure/retry/azure_error.go","code":"// GetStatusNotFoundAndForbiddenIgnoredError gets an error with StatusNotFound and StatusForbidden ignored.\n// It is only used in DELETE operations.\nfunc GetStatusNotFoundAndForbiddenIgnoredError(resp *http.Response, err error) *Error {\n\trerr := GetError(resp, err)\n\tif rerr == nil {\n\t\treturn nil\n\t}\n\n\t// Returns nil when it is StatusNotFound error.\n\tif rerr.HTTPStatusCode == http.StatusNotFound {\n\t\tklog.V(3).Infof(\"Ignoring StatusNotFound error: %v\", rerr)\n\t\treturn nil\n\t}\n\n\t// Returns nil if the status code is StatusForbidden.\n\t// This happens when AuthorizationFailed is reported from Azure API.\n\tif rerr.HTTPStatusCode == http.StatusForbidden {\n\t\tklog.V(3).Infof(\"Ignoring StatusForbidden error: %v\", rerr)\n\t\treturn nil\n\t}\n\n\treturn rerr\n}","line":{"from":267,"to":289}} {"id":100033998,"name":"IsErrorRetriable","signature":"func IsErrorRetriable(err error) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/retry/azure_error.go","code":"// IsErrorRetriable returns true if the error is retriable.\nfunc IsErrorRetriable(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\n\treturn strings.Contains(err.Error(), \"Retriable: true\")\n}","line":{"from":291,"to":298}} {"id":100033999,"name":"HasStatusForbiddenOrIgnoredError","signature":"func HasStatusForbiddenOrIgnoredError(err error) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/retry/azure_error.go","code":"// HasStatusForbiddenOrIgnoredError return true if the given error code is part of the error message\n// This should only be used when trying to delete resources\nfunc HasStatusForbiddenOrIgnoredError(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\n\tif strings.Contains(err.Error(), fmt.Sprintf(\"HTTPStatusCode: %d\", http.StatusNotFound)) {\n\t\treturn true\n\t}\n\n\tif strings.Contains(err.Error(), fmt.Sprintf(\"HTTPStatusCode: %d\", http.StatusForbidden)) {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":300,"to":315}} {"id":100034000,"name":"NewBackoff","signature":"func NewBackoff(duration time.Duration, factor float64, jitter float64, steps int, cap time.Duration) *Backoff","file":"staging/src/k8s.io/legacy-cloud-providers/azure/retry/azure_retry.go","code":"// NewBackoff creates a new Backoff.\nfunc NewBackoff(duration time.Duration, factor float64, jitter float64, steps int, cap time.Duration) *Backoff {\n\treturn \u0026Backoff{\n\t\tDuration: duration,\n\t\tFactor: factor,\n\t\tJitter: jitter,\n\t\tSteps: steps,\n\t\tCap: cap,\n\t}\n}","line":{"from":66,"to":75}} {"id":100034001,"name":"WithNonRetriableErrors","signature":"func (b *Backoff) WithNonRetriableErrors(errs []string) *Backoff","file":"staging/src/k8s.io/legacy-cloud-providers/azure/retry/azure_retry.go","code":"// WithNonRetriableErrors returns a new *Backoff with NonRetriableErrors assigned.\nfunc (b *Backoff) WithNonRetriableErrors(errs []string) *Backoff {\n\tnewBackoff := *b\n\tnewBackoff.NonRetriableErrors = errs\n\treturn \u0026newBackoff\n}","line":{"from":77,"to":82}} {"id":100034002,"name":"WithRetriableHTTPStatusCodes","signature":"func (b *Backoff) WithRetriableHTTPStatusCodes(httpStatusCodes []int) *Backoff","file":"staging/src/k8s.io/legacy-cloud-providers/azure/retry/azure_retry.go","code":"// WithRetriableHTTPStatusCodes returns a new *Backoff with RetriableHTTPStatusCode assigned.\nfunc (b *Backoff) WithRetriableHTTPStatusCodes(httpStatusCodes []int) *Backoff {\n\tnewBackoff := *b\n\tnewBackoff.RetriableHTTPStatusCodes = httpStatusCodes\n\treturn \u0026newBackoff\n}","line":{"from":84,"to":89}} {"id":100034003,"name":"isNonRetriableError","signature":"func (b *Backoff) isNonRetriableError(rerr *Error) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/retry/azure_retry.go","code":"// isNonRetriableError returns true if the Error is one of NonRetriableErrors.\nfunc (b *Backoff) isNonRetriableError(rerr *Error) bool {\n\tif rerr == nil {\n\t\treturn false\n\t}\n\n\tfor _, err := range b.NonRetriableErrors {\n\t\tif strings.Contains(rerr.RawError.Error(), err) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":91,"to":104}} {"id":100034004,"name":"Step","signature":"func (b *Backoff) Step() time.Duration","file":"staging/src/k8s.io/legacy-cloud-providers/azure/retry/azure_retry.go","code":"// Step (1) returns an amount of time to sleep determined by the\n// original Duration and Jitter and (2) mutates the provided Backoff\n// to update its Steps and Duration.\nfunc (b *Backoff) Step() time.Duration {\n\tif b.Steps \u003c 1 {\n\t\tif b.Jitter \u003e 0 {\n\t\t\treturn jitter(b.Duration, b.Jitter)\n\t\t}\n\t\treturn b.Duration\n\t}\n\tb.Steps--\n\n\tduration := b.Duration\n\n\t// calculate the next step\n\tif b.Factor != 0 {\n\t\tb.Duration = time.Duration(float64(b.Duration) * b.Factor)\n\t\tif b.Cap \u003e 0 \u0026\u0026 b.Duration \u003e b.Cap {\n\t\t\tb.Duration = b.Cap\n\t\t\tb.Steps = 0\n\t\t}\n\t}\n\n\tif b.Jitter \u003e 0 {\n\t\tduration = jitter(duration, b.Jitter)\n\t}\n\treturn duration\n}","line":{"from":106,"to":133}} {"id":100034005,"name":"jitter","signature":"func jitter(duration time.Duration, maxFactor float64) time.Duration","file":"staging/src/k8s.io/legacy-cloud-providers/azure/retry/azure_retry.go","code":"// Jitter returns a time.Duration between duration and duration + maxFactor *\n// duration.\n//\n// This allows clients to avoid converging on periodic behavior. If maxFactor\n// is 0.0, a suggested default value will be chosen.\nfunc jitter(duration time.Duration, maxFactor float64) time.Duration {\n\tif maxFactor \u003c= 0.0 {\n\t\tmaxFactor = 1.0\n\t}\n\twait := duration + time.Duration(rand.Float64()*maxFactor*float64(duration))\n\treturn wait\n}","line":{"from":135,"to":146}} {"id":100034006,"name":"DoExponentialBackoffRetry","signature":"func DoExponentialBackoffRetry(backoff *Backoff) autorest.SendDecorator","file":"staging/src/k8s.io/legacy-cloud-providers/azure/retry/azure_retry.go","code":"// DoExponentialBackoffRetry represents an autorest.SendDecorator with backoff retry.\nfunc DoExponentialBackoffRetry(backoff *Backoff) autorest.SendDecorator {\n\treturn func(s autorest.Sender) autorest.Sender {\n\t\treturn autorest.SenderFunc(func(r *http.Request) (*http.Response, error) {\n\t\t\treturn doBackoffRetry(s, r, backoff)\n\t\t})\n\t}\n}","line":{"from":148,"to":155}} {"id":100034007,"name":"doBackoffRetry","signature":"func doBackoffRetry(s autorest.Sender, r *http.Request, backoff *Backoff) (resp *http.Response, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/azure/retry/azure_retry.go","code":"// doBackoffRetry does the backoff retries for the request.\nfunc doBackoffRetry(s autorest.Sender, r *http.Request, backoff *Backoff) (resp *http.Response, err error) {\n\trr := autorest.NewRetriableRequest(r)\n\t// Increment to add the first call (attempts denotes number of retries)\n\tfor backoff.Steps \u003e 0 {\n\t\terr = rr.Prepare()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tresp, err = s.Do(rr.Request())\n\t\trerr := GetErrorWithRetriableHTTPStatusCodes(resp, err, backoff.RetriableHTTPStatusCodes)\n\t\t// Abort retries in the following scenarios:\n\t\t// 1) request succeed\n\t\t// 2) request is not retriable\n\t\t// 3) request has been throttled\n\t\t// 4) request contains non-retriable errors\n\t\t// 5) request has completed all the retry steps\n\t\tif rerr == nil || !rerr.Retriable || rerr.IsThrottled() || backoff.isNonRetriableError(rerr) || backoff.Steps == 1 {\n\t\t\treturn resp, rerr.Error()\n\t\t}\n\n\t\tif !delayForBackOff(backoff, r.Context().Done()) {\n\t\t\tif r.Context().Err() != nil {\n\t\t\t\treturn resp, r.Context().Err()\n\t\t\t}\n\t\t\treturn resp, rerr.Error()\n\t\t}\n\n\t\tklog.V(3).Infof(\"Backoff retrying %s %q with error %v\", r.Method, r.URL.String(), rerr)\n\t}\n\n\treturn resp, err\n}","line":{"from":157,"to":189}} {"id":100034008,"name":"delayForBackOff","signature":"func delayForBackOff(backoff *Backoff, cancel \u003c-chan struct{}) bool","file":"staging/src/k8s.io/legacy-cloud-providers/azure/retry/azure_retry.go","code":"// delayForBackOff invokes time.After for the supplied backoff duration.\n// The delay may be canceled by closing the passed channel. If terminated early, returns false.\nfunc delayForBackOff(backoff *Backoff, cancel \u003c-chan struct{}) bool {\n\td := backoff.Step()\n\tselect {\n\tcase \u003c-time.After(d):\n\t\treturn true\n\tcase \u003c-cancel:\n\t\treturn false\n\t}\n}","line":{"from":191,"to":201}} {"id":100034009,"name":"init","signature":"func init()","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"func init() {\n\tcloudprovider.RegisterCloudProvider(\n\t\tProviderName,\n\t\tfunc(config io.Reader) (cloudprovider.Interface, error) {\n\t\t\treturn newGCECloud(config)\n\t\t})\n}","line":{"from":244,"to":250}} {"id":100034010,"name":"ComputeServices","signature":"func (g *Cloud) ComputeServices() *Services","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// ComputeServices returns access to the internal compute services.\nfunc (g *Cloud) ComputeServices() *Services {\n\treturn \u0026Services{g.service, g.serviceAlpha, g.serviceBeta}\n}","line":{"from":260,"to":263}} {"id":100034011,"name":"Compute","signature":"func (g *Cloud) Compute() cloud.Cloud","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// Compute returns the generated stubs for the compute API.\nfunc (g *Cloud) Compute() cloud.Cloud {\n\treturn g.c\n}","line":{"from":265,"to":268}} {"id":100034012,"name":"ContainerService","signature":"func (g *Cloud) ContainerService() *container.Service","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// ContainerService returns the container service.\nfunc (g *Cloud) ContainerService() *container.Service {\n\treturn g.containerService\n}","line":{"from":270,"to":273}} {"id":100034013,"name":"newGCECloud","signature":"func newGCECloud(config io.Reader) (gceCloud *Cloud, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// newGCECloud creates a new instance of Cloud.\nfunc newGCECloud(config io.Reader) (gceCloud *Cloud, err error) {\n\tvar cloudConfig *CloudConfig\n\tvar configFile *ConfigFile\n\n\tif config != nil {\n\t\tconfigFile, err = readConfig(config)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tklog.Infof(\"Using GCE provider config %+v\", configFile)\n\t}\n\n\tcloudConfig, err = generateCloudConfig(configFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn CreateGCECloud(cloudConfig)\n}","line":{"from":275,"to":293}} {"id":100034014,"name":"readConfig","signature":"func readConfig(reader io.Reader) (*ConfigFile, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"func readConfig(reader io.Reader) (*ConfigFile, error) {\n\tcfg := \u0026ConfigFile{}\n\tif err := gcfg.FatalOnly(gcfg.ReadInto(cfg, reader)); err != nil {\n\t\tklog.Errorf(\"Couldn't read config: %v\", err)\n\t\treturn nil, err\n\t}\n\treturn cfg, nil\n}","line":{"from":295,"to":302}} {"id":100034015,"name":"generateCloudConfig","signature":"func generateCloudConfig(configFile *ConfigFile) (cloudConfig *CloudConfig, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"func generateCloudConfig(configFile *ConfigFile) (cloudConfig *CloudConfig, err error) {\n\tcloudConfig = \u0026CloudConfig{}\n\t// By default, fetch token from GCE metadata server\n\tcloudConfig.TokenSource = google.ComputeTokenSource(\"\")\n\tcloudConfig.UseMetadataServer = true\n\tcloudConfig.AlphaFeatureGate = NewAlphaFeatureGate([]string{})\n\tif configFile != nil {\n\t\tif configFile.Global.APIEndpoint != \"\" {\n\t\t\tcloudConfig.APIEndpoint = configFile.Global.APIEndpoint\n\t\t}\n\n\t\tif configFile.Global.ContainerAPIEndpoint != \"\" {\n\t\t\tcloudConfig.ContainerAPIEndpoint = configFile.Global.ContainerAPIEndpoint\n\t\t}\n\n\t\tif configFile.Global.TokenURL != \"\" {\n\t\t\t// if tokenURL is nil, set tokenSource to nil. This will force the OAuth client to fall\n\t\t\t// back to use DefaultTokenSource. This allows running gceCloud remotely.\n\t\t\tif configFile.Global.TokenURL == \"nil\" {\n\t\t\t\tcloudConfig.TokenSource = nil\n\t\t\t} else {\n\t\t\t\tcloudConfig.TokenSource = NewAltTokenSource(configFile.Global.TokenURL, configFile.Global.TokenBody)\n\t\t\t}\n\t\t}\n\n\t\tcloudConfig.NodeTags = configFile.Global.NodeTags\n\t\tcloudConfig.NodeInstancePrefix = configFile.Global.NodeInstancePrefix\n\t\tcloudConfig.AlphaFeatureGate = NewAlphaFeatureGate(configFile.Global.AlphaFeatures)\n\t}\n\n\t// retrieve projectID and zone\n\tif configFile == nil || configFile.Global.ProjectID == \"\" || configFile.Global.LocalZone == \"\" {\n\t\tcloudConfig.ProjectID, cloudConfig.Zone, err = getProjectAndZone()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif configFile != nil {\n\t\tif configFile.Global.ProjectID != \"\" {\n\t\t\tcloudConfig.ProjectID = configFile.Global.ProjectID\n\t\t}\n\t\tif configFile.Global.LocalZone != \"\" {\n\t\t\tcloudConfig.Zone = configFile.Global.LocalZone\n\t\t}\n\t\tif configFile.Global.NetworkProjectID != \"\" {\n\t\t\tcloudConfig.NetworkProjectID = configFile.Global.NetworkProjectID\n\t\t}\n\t}\n\n\t// retrieve region\n\tcloudConfig.Region, err = GetGCERegion(cloudConfig.Zone)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Determine if its a regional cluster\n\tif configFile != nil \u0026\u0026 configFile.Global.Regional {\n\t\tcloudConfig.Regional = true\n\t}\n\n\t// generate managedZones\n\tcloudConfig.ManagedZones = []string{cloudConfig.Zone}\n\tif configFile != nil \u0026\u0026 (configFile.Global.Multizone || configFile.Global.Regional) {\n\t\tcloudConfig.ManagedZones = nil // Use all zones in region\n\t}\n\n\t// Determine if network parameter is URL or Name\n\tif configFile != nil \u0026\u0026 configFile.Global.NetworkName != \"\" {\n\t\tif strings.Contains(configFile.Global.NetworkName, \"/\") {\n\t\t\tcloudConfig.NetworkURL = configFile.Global.NetworkName\n\t\t} else {\n\t\t\tcloudConfig.NetworkName = configFile.Global.NetworkName\n\t\t}\n\t} else {\n\t\tcloudConfig.NetworkName, err = getNetworkNameViaMetadata()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Determine if subnetwork parameter is URL or Name\n\t// If cluster is on a GCP network of mode=custom, then `SubnetName` must be specified in config file.\n\tif configFile != nil \u0026\u0026 configFile.Global.SubnetworkName != \"\" {\n\t\tif strings.Contains(configFile.Global.SubnetworkName, \"/\") {\n\t\t\tcloudConfig.SubnetworkURL = configFile.Global.SubnetworkName\n\t\t} else {\n\t\t\tcloudConfig.SubnetworkName = configFile.Global.SubnetworkName\n\t\t}\n\t}\n\n\tif configFile != nil {\n\t\tcloudConfig.SecondaryRangeName = configFile.Global.SecondaryRangeName\n\t}\n\n\treturn cloudConfig, err\n}","line":{"from":304,"to":400}} {"id":100034016,"name":"CreateGCECloud","signature":"func CreateGCECloud(config *CloudConfig) (*Cloud, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// CreateGCECloud creates a Cloud object using the specified parameters.\n// If no networkUrl is specified, loads networkName via rest call.\n// If no tokenSource is specified, uses oauth2.DefaultTokenSource.\n// If managedZones is nil / empty all zones in the region will be managed.\nfunc CreateGCECloud(config *CloudConfig) (*Cloud, error) {\n\t// Remove any pre-release version and build metadata from the semver,\n\t// leaving only the MAJOR.MINOR.PATCH portion. See http://semver.org/.\n\tversion := strings.TrimLeft(strings.Split(strings.Split(version.Get().GitVersion, \"-\")[0], \"+\")[0], \"v\")\n\n\t// Create a user-agent header append string to supply to the Google API\n\t// clients, to identify Kubernetes as the origin of the GCP API calls.\n\tuserAgent := fmt.Sprintf(\"Kubernetes/%s (%s %s)\", version, runtime.GOOS, runtime.GOARCH)\n\n\t// Use ProjectID for NetworkProjectID, if it wasn't explicitly set.\n\tif config.NetworkProjectID == \"\" {\n\t\tconfig.NetworkProjectID = config.ProjectID\n\t}\n\n\tservice, err := compute.NewService(context.Background(), option.WithTokenSource(config.TokenSource))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tservice.UserAgent = userAgent\n\n\tserviceBeta, err := computebeta.NewService(context.Background(), option.WithTokenSource(config.TokenSource))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tserviceBeta.UserAgent = userAgent\n\n\tserviceAlpha, err := computealpha.NewService(context.Background(), option.WithTokenSource(config.TokenSource))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tserviceAlpha.UserAgent = userAgent\n\n\tif config.APIEndpoint != \"\" {\n\t\tif strings.HasSuffix(service.BasePath, \"/projects/\") {\n\t\t\tservice.BasePath = getProjectsBasePath(config.APIEndpoint)\n\t\t\tserviceBeta.BasePath = getProjectsBasePath(strings.Replace(config.APIEndpoint, \"v1\", \"beta\", -1))\n\t\t\tserviceAlpha.BasePath = getProjectsBasePath(strings.Replace(config.APIEndpoint, \"v1\", \"alpha\", -1))\n\t\t} else {\n\t\t\tservice.BasePath = config.APIEndpoint\n\t\t\tserviceBeta.BasePath = strings.Replace(config.APIEndpoint, \"v1\", \"beta\", -1)\n\t\t\tserviceAlpha.BasePath = strings.Replace(config.APIEndpoint, \"v1\", \"alpha\", -1)\n\t\t}\n\t}\n\n\tcontainerService, err := container.NewService(context.Background(), option.WithTokenSource(config.TokenSource))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcontainerService.UserAgent = userAgent\n\tif config.ContainerAPIEndpoint != \"\" {\n\t\tcontainerService.BasePath = config.ContainerAPIEndpoint\n\t}\n\n\tclient, err := newOauthClient(config.TokenSource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttpuService, err := newTPUService(client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// ProjectID and.NetworkProjectID may be project number or name.\n\tprojID, netProjID := tryConvertToProjectNames(config.ProjectID, config.NetworkProjectID, service)\n\tonXPN := projID != netProjID\n\n\tvar networkURL string\n\tvar subnetURL string\n\tvar isLegacyNetwork bool\n\n\tif config.NetworkURL != \"\" {\n\t\tnetworkURL = config.NetworkURL\n\t} else if config.NetworkName != \"\" {\n\t\tnetworkURL = gceNetworkURL(config.APIEndpoint, netProjID, config.NetworkName)\n\t} else {\n\t\t// Other consumers may use the cloudprovider without utilizing the wrapped GCE API functions\n\t\t// or functions requiring network/subnetwork URLs (e.g. Kubelet).\n\t\tklog.Warningf(\"No network name or URL specified.\")\n\t}\n\n\tif config.SubnetworkURL != \"\" {\n\t\tsubnetURL = config.SubnetworkURL\n\t} else if config.SubnetworkName != \"\" {\n\t\tsubnetURL = gceSubnetworkURL(config.APIEndpoint, netProjID, config.Region, config.SubnetworkName)\n\t}\n\t// If neither SubnetworkURL nor SubnetworkName are provided, defer to\n\t// lazy initialization. Determining subnetURL and isLegacyNetwork requires\n\t// GCE API call. Given that it's not used in many cases and the fact that\n\t// the provider is initialized also for Kubelets (and there can be thousands\n\t// of them) we defer to lazy initialization here.\n\n\tif len(config.ManagedZones) == 0 {\n\t\tconfig.ManagedZones, err = getZonesForRegion(service, config.ProjectID, config.Region)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif len(config.ManagedZones) \u003e 1 {\n\t\tklog.Infof(\"managing multiple zones: %v\", config.ManagedZones)\n\t}\n\n\toperationPollRateLimiter := flowcontrol.NewTokenBucketRateLimiter(5, 5) // 5 qps, 5 burst.\n\n\tgce := \u0026Cloud{\n\t\tservice: service,\n\t\tserviceAlpha: serviceAlpha,\n\t\tserviceBeta: serviceBeta,\n\t\tcontainerService: containerService,\n\t\ttpuService: tpuService,\n\t\tprojectID: projID,\n\t\tnetworkProjectID: netProjID,\n\t\tonXPN: onXPN,\n\t\tregion: config.Region,\n\t\tregional: config.Regional,\n\t\tlocalZone: config.Zone,\n\t\tmanagedZones: config.ManagedZones,\n\t\tnetworkURL: networkURL,\n\t\tunsafeIsLegacyNetwork: isLegacyNetwork,\n\t\tunsafeSubnetworkURL: subnetURL,\n\t\tsecondaryRangeName: config.SecondaryRangeName,\n\t\tnodeTags: config.NodeTags,\n\t\tnodeInstancePrefix: config.NodeInstancePrefix,\n\t\tuseMetadataServer: config.UseMetadataServer,\n\t\toperationPollRateLimiter: operationPollRateLimiter,\n\t\tAlphaFeatureGate: config.AlphaFeatureGate,\n\t\tnodeZones: map[string]sets.String{},\n\t\tmetricsCollector: newLoadBalancerMetrics(),\n\t\tprojectsBasePath: getProjectsBasePath(service.BasePath),\n\t}\n\n\tgce.manager = \u0026gceServiceManager{gce}\n\tgce.s = \u0026cloud.Service{\n\t\tGA: service,\n\t\tAlpha: serviceAlpha,\n\t\tBeta: serviceBeta,\n\t\tProjectRouter: \u0026gceProjectRouter{gce},\n\t\tRateLimiter: \u0026gceRateLimiter{gce},\n\t}\n\tgce.c = cloud.NewGCE(gce.s)\n\n\treturn gce, nil\n}","line":{"from":402,"to":547}} {"id":100034017,"name":"initializeSubnetworkURLAndIsLegacyNetwork","signature":"func (g *Cloud) initializeSubnetworkURLAndIsLegacyNetwork()","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// initializeNetworkConfig() is supposed to be called under sync.Once()\n// for accessors to subnetworkURL and isLegacyNetwork fields.\nfunc (g *Cloud) initializeSubnetworkURLAndIsLegacyNetwork() {\n\tif g.unsafeSubnetworkURL != \"\" {\n\t\t// This has already been initialized via the config.\n\t\treturn\n\t}\n\n\tvar subnetURL string\n\tvar isLegacyNetwork bool\n\n\t// Determine the type of network and attempt to discover the correct subnet for AUTO mode.\n\t// Gracefully fail because kubelet calls CreateGCECloud without any config, and minions\n\t// lack the proper credentials for API calls.\n\tif networkName := lastComponent(g.NetworkURL()); networkName != \"\" {\n\t\tif n, err := getNetwork(g.service, g.NetworkProjectID(), networkName); err != nil {\n\t\t\tklog.Warningf(\"Could not retrieve network %q; err: %v\", networkName, err)\n\t\t} else {\n\t\t\tswitch typeOfNetwork(n) {\n\t\t\tcase netTypeLegacy:\n\t\t\t\tklog.Infof(\"Network %q is type legacy - no subnetwork\", networkName)\n\t\t\t\tisLegacyNetwork = true\n\t\t\tcase netTypeCustom:\n\t\t\t\tklog.Warningf(\"Network %q is type custom - cannot auto select a subnetwork\", networkName)\n\t\t\tcase netTypeAuto:\n\t\t\t\tsubnetURL, err = determineSubnetURL(g.service, g.NetworkProjectID(), networkName, g.Region())\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Warningf(\"Could not determine subnetwork for network %q and region %v; err: %v\", networkName, g.Region(), err)\n\t\t\t\t} else {\n\t\t\t\t\tklog.Infof(\"Auto selecting subnetwork %q\", subnetURL)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tg.unsafeSubnetworkURL = subnetURL\n\tg.unsafeIsLegacyNetwork = isLegacyNetwork\n}","line":{"from":549,"to":586}} {"id":100034018,"name":"SetRateLimiter","signature":"func (g *Cloud) SetRateLimiter(rl cloud.RateLimiter)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// SetRateLimiter adds a custom cloud.RateLimiter implementation.\n// WARNING: Calling this could have unexpected behavior if you have in-flight\n// requests. It is best to use this immediately after creating a Cloud.\nfunc (g *Cloud) SetRateLimiter(rl cloud.RateLimiter) {\n\tif rl != nil {\n\t\tg.s.RateLimiter = rl\n\t}\n}","line":{"from":588,"to":595}} {"id":100034019,"name":"determineSubnetURL","signature":"func determineSubnetURL(service *compute.Service, networkProjectID, networkName, region string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// determineSubnetURL queries for all subnetworks in a region for a given network and returns\n// the URL of the subnetwork which exists in the auto-subnet range.\nfunc determineSubnetURL(service *compute.Service, networkProjectID, networkName, region string) (string, error) {\n\tsubnets, err := listSubnetworksOfNetwork(service, networkProjectID, networkName, region)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tautoSubnets, err := subnetsInCIDR(subnets, autoSubnetIPRange)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif len(autoSubnets) == 0 {\n\t\treturn \"\", fmt.Errorf(\"no subnet exists in auto CIDR\")\n\t}\n\n\tif len(autoSubnets) \u003e 1 {\n\t\treturn \"\", fmt.Errorf(\"multiple subnetworks in the same region exist in auto CIDR\")\n\t}\n\n\treturn autoSubnets[0].SelfLink, nil\n}","line":{"from":597,"to":619}} {"id":100034020,"name":"tryConvertToProjectNames","signature":"func tryConvertToProjectNames(configProject, configNetworkProject string, service *compute.Service) (projID, netProjID string)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"func tryConvertToProjectNames(configProject, configNetworkProject string, service *compute.Service) (projID, netProjID string) {\n\tprojID = configProject\n\tif isProjectNumber(projID) {\n\t\tprojName, err := getProjectID(service, projID)\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"Failed to retrieve project %v while trying to retrieve its name. err %v\", projID, err)\n\t\t} else {\n\t\t\tprojID = projName\n\t\t}\n\t}\n\n\tnetProjID = projID\n\tif configNetworkProject != configProject {\n\t\tnetProjID = configNetworkProject\n\t}\n\tif isProjectNumber(netProjID) {\n\t\tnetProjName, err := getProjectID(service, netProjID)\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"Failed to retrieve network project %v while trying to retrieve its name. err %v\", netProjID, err)\n\t\t} else {\n\t\t\tnetProjID = netProjName\n\t\t}\n\t}\n\n\treturn projID, netProjID\n}","line":{"from":621,"to":646}} {"id":100034021,"name":"Initialize","signature":"func (g *Cloud) Initialize(clientBuilder cloudprovider.ControllerClientBuilder, stop \u003c-chan struct{})","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// Initialize takes in a clientBuilder and spawns a goroutine for watching the clusterid configmap.\n// This must be called before utilizing the funcs of gce.ClusterID\nfunc (g *Cloud) Initialize(clientBuilder cloudprovider.ControllerClientBuilder, stop \u003c-chan struct{}) {\n\tg.clientBuilder = clientBuilder\n\tg.client = clientBuilder.ClientOrDie(\"cloud-provider\")\n\n\tg.eventBroadcaster = record.NewBroadcaster()\n\tg.eventBroadcaster.StartRecordingToSink(\u0026v1core.EventSinkImpl{Interface: g.client.CoreV1().Events(\"\")})\n\tg.eventRecorder = g.eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: \"g-cloudprovider\"})\n\n\tgo g.watchClusterID(stop)\n\tgo g.metricsCollector.Run(stop)\n}","line":{"from":648,"to":660}} {"id":100034022,"name":"LoadBalancer","signature":"func (g *Cloud) LoadBalancer() (cloudprovider.LoadBalancer, bool)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// LoadBalancer returns an implementation of LoadBalancer for Google Compute Engine.\nfunc (g *Cloud) LoadBalancer() (cloudprovider.LoadBalancer, bool) {\n\treturn g, true\n}","line":{"from":662,"to":665}} {"id":100034023,"name":"Instances","signature":"func (g *Cloud) Instances() (cloudprovider.Instances, bool)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// Instances returns an implementation of Instances for Google Compute Engine.\nfunc (g *Cloud) Instances() (cloudprovider.Instances, bool) {\n\treturn g, true\n}","line":{"from":667,"to":670}} {"id":100034024,"name":"InstancesV2","signature":"func (g *Cloud) InstancesV2() (cloudprovider.InstancesV2, bool)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// InstancesV2 returns an implementation of InstancesV2 for Google Compute Engine.\n// Implement ONLY for external cloud provider\nfunc (g *Cloud) InstancesV2() (cloudprovider.InstancesV2, bool) {\n\treturn g, true\n}","line":{"from":672,"to":676}} {"id":100034025,"name":"Zones","signature":"func (g *Cloud) Zones() (cloudprovider.Zones, bool)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// Zones returns an implementation of Zones for Google Compute Engine.\nfunc (g *Cloud) Zones() (cloudprovider.Zones, bool) {\n\treturn g, true\n}","line":{"from":678,"to":681}} {"id":100034026,"name":"Clusters","signature":"func (g *Cloud) Clusters() (cloudprovider.Clusters, bool)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// Clusters returns an implementation of Clusters for Google Compute Engine.\nfunc (g *Cloud) Clusters() (cloudprovider.Clusters, bool) {\n\treturn g, true\n}","line":{"from":683,"to":686}} {"id":100034027,"name":"Routes","signature":"func (g *Cloud) Routes() (cloudprovider.Routes, bool)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// Routes returns an implementation of Routes for Google Compute Engine.\nfunc (g *Cloud) Routes() (cloudprovider.Routes, bool) {\n\treturn g, true\n}","line":{"from":688,"to":691}} {"id":100034028,"name":"ProviderName","signature":"func (g *Cloud) ProviderName() string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// ProviderName returns the cloud provider ID.\nfunc (g *Cloud) ProviderName() string {\n\treturn ProviderName\n}","line":{"from":693,"to":696}} {"id":100034029,"name":"ProjectID","signature":"func (g *Cloud) ProjectID() string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// ProjectID returns the ProjectID corresponding to the project this cloud is in.\nfunc (g *Cloud) ProjectID() string {\n\treturn g.projectID\n}","line":{"from":698,"to":701}} {"id":100034030,"name":"NetworkProjectID","signature":"func (g *Cloud) NetworkProjectID() string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// NetworkProjectID returns the ProjectID corresponding to the project this cluster's network is in.\nfunc (g *Cloud) NetworkProjectID() string {\n\treturn g.networkProjectID\n}","line":{"from":703,"to":706}} {"id":100034031,"name":"Region","signature":"func (g *Cloud) Region() string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// Region returns the region\nfunc (g *Cloud) Region() string {\n\treturn g.region\n}","line":{"from":708,"to":711}} {"id":100034032,"name":"OnXPN","signature":"func (g *Cloud) OnXPN() bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// OnXPN returns true if the cluster is running on a cross project network (XPN)\nfunc (g *Cloud) OnXPN() bool {\n\treturn g.onXPN\n}","line":{"from":713,"to":716}} {"id":100034033,"name":"NetworkURL","signature":"func (g *Cloud) NetworkURL() string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// NetworkURL returns the network url\nfunc (g *Cloud) NetworkURL() string {\n\treturn g.networkURL\n}","line":{"from":718,"to":721}} {"id":100034034,"name":"SubnetworkURL","signature":"func (g *Cloud) SubnetworkURL() string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// SubnetworkURL returns the subnetwork url\nfunc (g *Cloud) SubnetworkURL() string {\n\tg.subnetworkURLAndIsLegacyNetworkInitializer.Do(g.initializeSubnetworkURLAndIsLegacyNetwork)\n\treturn g.unsafeSubnetworkURL\n}","line":{"from":723,"to":727}} {"id":100034035,"name":"IsLegacyNetwork","signature":"func (g *Cloud) IsLegacyNetwork() bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// IsLegacyNetwork returns true if the cluster is still running a legacy network configuration.\nfunc (g *Cloud) IsLegacyNetwork() bool {\n\tg.subnetworkURLAndIsLegacyNetworkInitializer.Do(g.initializeSubnetworkURLAndIsLegacyNetwork)\n\treturn g.unsafeIsLegacyNetwork\n}","line":{"from":729,"to":733}} {"id":100034036,"name":"SetInformers","signature":"func (g *Cloud) SetInformers(informerFactory informers.SharedInformerFactory)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// SetInformers sets up the zone handlers we need watching for node changes.\nfunc (g *Cloud) SetInformers(informerFactory informers.SharedInformerFactory) {\n\tklog.Infof(\"Setting up informers for Cloud\")\n\tnodeInformer := informerFactory.Core().V1().Nodes().Informer()\n\tnodeInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tnode := obj.(*v1.Node)\n\t\t\tg.updateNodeZones(nil, node)\n\t\t},\n\t\tUpdateFunc: func(prev, obj interface{}) {\n\t\t\tprevNode := prev.(*v1.Node)\n\t\t\tnewNode := obj.(*v1.Node)\n\t\t\tif newNode.Labels[v1.LabelFailureDomainBetaZone] ==\n\t\t\t\tprevNode.Labels[v1.LabelFailureDomainBetaZone] {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tg.updateNodeZones(prevNode, newNode)\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tnode, isNode := obj.(*v1.Node)\n\t\t\t// We can get DeletedFinalStateUnknown instead of *v1.Node here\n\t\t\t// and we need to handle that correctly.\n\t\t\tif !isNode {\n\t\t\t\tdeletedState, ok := obj.(cache.DeletedFinalStateUnknown)\n\t\t\t\tif !ok {\n\t\t\t\t\tklog.Errorf(\"Received unexpected object: %v\", obj)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tnode, ok = deletedState.Obj.(*v1.Node)\n\t\t\t\tif !ok {\n\t\t\t\t\tklog.Errorf(\"DeletedFinalStateUnknown contained non-Node object: %v\", deletedState.Obj)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tg.updateNodeZones(node, nil)\n\t\t},\n\t})\n\tg.nodeInformerSynced = nodeInformer.HasSynced\n}","line":{"from":735,"to":773}} {"id":100034037,"name":"updateNodeZones","signature":"func (g *Cloud) updateNodeZones(prevNode, newNode *v1.Node)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"func (g *Cloud) updateNodeZones(prevNode, newNode *v1.Node) {\n\tg.nodeZonesLock.Lock()\n\tdefer g.nodeZonesLock.Unlock()\n\tif prevNode != nil {\n\t\tprevZone, ok := prevNode.ObjectMeta.Labels[v1.LabelFailureDomainBetaZone]\n\t\tif ok {\n\t\t\tg.nodeZones[prevZone].Delete(prevNode.ObjectMeta.Name)\n\t\t\tif g.nodeZones[prevZone].Len() == 0 {\n\t\t\t\tg.nodeZones[prevZone] = nil\n\t\t\t}\n\t\t}\n\t}\n\tif newNode != nil {\n\t\tnewZone, ok := newNode.ObjectMeta.Labels[v1.LabelFailureDomainBetaZone]\n\t\tif ok {\n\t\t\tif g.nodeZones[newZone] == nil {\n\t\t\t\tg.nodeZones[newZone] = sets.NewString()\n\t\t\t}\n\t\t\tg.nodeZones[newZone].Insert(newNode.ObjectMeta.Name)\n\t\t}\n\t}\n}","line":{"from":775,"to":796}} {"id":100034038,"name":"HasClusterID","signature":"func (g *Cloud) HasClusterID() bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// HasClusterID returns true if the cluster has a clusterID\nfunc (g *Cloud) HasClusterID() bool {\n\treturn true\n}","line":{"from":798,"to":801}} {"id":100034039,"name":"getProjectsBasePath","signature":"func getProjectsBasePath(basePath string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// getProjectsBasePath returns the compute API endpoint with the `projects/` element.\n// The suffix must be added when generating compute resource urls.\nfunc getProjectsBasePath(basePath string) string {\n\tif !strings.HasSuffix(basePath, \"/\") {\n\t\tbasePath += \"/\"\n\t}\n\tif !strings.HasSuffix(basePath, \"/projects/\") {\n\t\tbasePath += \"projects/\"\n\t}\n\treturn basePath\n}","line":{"from":803,"to":813}} {"id":100034040,"name":"isProjectNumber","signature":"func isProjectNumber(idOrNumber string) bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// Project IDs cannot have a digit for the first characeter. If the id contains a digit,\n// then it must be a project number.\nfunc isProjectNumber(idOrNumber string) bool {\n\t_, err := strconv.ParseUint(idOrNumber, 10, 64)\n\treturn err == nil\n}","line":{"from":815,"to":820}} {"id":100034041,"name":"gceNetworkURL","signature":"func gceNetworkURL(apiEndpoint, project, network string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"func gceNetworkURL(apiEndpoint, project, network string) string {\n\tif apiEndpoint == \"\" {\n\t\tapiEndpoint = gceComputeAPIEndpoint\n\t}\n\treturn apiEndpoint + strings.Join([]string{\"projects\", project, \"global\", \"networks\", network}, \"/\")\n}","line":{"from":822,"to":827}} {"id":100034042,"name":"gceSubnetworkURL","signature":"func gceSubnetworkURL(apiEndpoint, project, region, subnetwork string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"func gceSubnetworkURL(apiEndpoint, project, region, subnetwork string) string {\n\tif apiEndpoint == \"\" {\n\t\tapiEndpoint = gceComputeAPIEndpoint\n\t}\n\treturn apiEndpoint + strings.Join([]string{\"projects\", project, \"regions\", region, \"subnetworks\", subnetwork}, \"/\")\n}","line":{"from":829,"to":834}} {"id":100034043,"name":"getRegionInURL","signature":"func getRegionInURL(urlStr string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// getRegionInURL parses full resource URLS and shorter URLS\n// https://www.googleapis.com/compute/v1/projects/myproject/regions/us-central1/subnetworks/a\n// projects/myproject/regions/us-central1/subnetworks/a\n// All return \"us-central1\"\nfunc getRegionInURL(urlStr string) string {\n\tfields := strings.Split(urlStr, \"/\")\n\tfor i, v := range fields {\n\t\tif v == \"regions\" \u0026\u0026 i \u003c len(fields)-1 {\n\t\t\treturn fields[i+1]\n\t\t}\n\t}\n\treturn \"\"\n}","line":{"from":836,"to":848}} {"id":100034044,"name":"getNetworkNameViaMetadata","signature":"func getNetworkNameViaMetadata() (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"func getNetworkNameViaMetadata() (string, error) {\n\tresult, err := metadata.Get(\"instance/network-interfaces/0/network\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tparts := strings.Split(result, \"/\")\n\tif len(parts) != 4 {\n\t\treturn \"\", fmt.Errorf(\"unexpected response: %s\", result)\n\t}\n\treturn parts[3], nil\n}","line":{"from":850,"to":860}} {"id":100034045,"name":"getNetwork","signature":"func getNetwork(svc *compute.Service, networkProjectID, networkID string) (*compute.Network, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// getNetwork returns a GCP network\nfunc getNetwork(svc *compute.Service, networkProjectID, networkID string) (*compute.Network, error) {\n\treturn svc.Networks.Get(networkProjectID, networkID).Do()\n}","line":{"from":862,"to":865}} {"id":100034046,"name":"listSubnetworksOfNetwork","signature":"func listSubnetworksOfNetwork(svc *compute.Service, networkProjectID, networkID, region string) ([]*compute.Subnetwork, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// listSubnetworksOfNetwork returns a list of subnetworks for a particular region of a network.\nfunc listSubnetworksOfNetwork(svc *compute.Service, networkProjectID, networkID, region string) ([]*compute.Subnetwork, error) {\n\tvar subnets []*compute.Subnetwork\n\terr := svc.Subnetworks.List(networkProjectID, region).Filter(fmt.Sprintf(\"network eq .*/%v$\", networkID)).Pages(context.Background(), func(res *compute.SubnetworkList) error {\n\t\tsubnets = append(subnets, res.Items...)\n\t\treturn nil\n\t})\n\treturn subnets, err\n}","line":{"from":867,"to":875}} {"id":100034047,"name":"getProjectID","signature":"func getProjectID(svc *compute.Service, projectNumberOrID string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"// getProjectID returns the project's string ID given a project number or string\nfunc getProjectID(svc *compute.Service, projectNumberOrID string) (string, error) {\n\tproj, err := svc.Projects.Get(projectNumberOrID).Do()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn proj.Name, nil\n}","line":{"from":877,"to":885}} {"id":100034048,"name":"getZonesForRegion","signature":"func getZonesForRegion(svc *compute.Service, projectID, region string) ([]string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"func getZonesForRegion(svc *compute.Service, projectID, region string) ([]string, error) {\n\t// TODO: use PageToken to list all not just the first 500\n\tlistCall := svc.Zones.List(projectID)\n\n\t// Filtering by region doesn't seem to work\n\t// (tested in https://cloud.google.com/compute/docs/reference/latest/zones/list)\n\t// listCall = listCall.Filter(\"region eq \" + region)\n\n\tvar zones []string\n\tvar accumulator = func(response *compute.ZoneList) error {\n\t\tfor _, zone := range response.Items {\n\t\t\tregionName := lastComponent(zone.Region)\n\t\t\tif regionName == region {\n\t\t\t\tzones = append(zones, zone.Name)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\terr := listCall.Pages(context.TODO(), accumulator)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unexpected response listing zones: %v\", err)\n\t}\n\treturn zones, nil\n}","line":{"from":887,"to":910}} {"id":100034049,"name":"findSubnetForRegion","signature":"func findSubnetForRegion(subnetURLs []string, region string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"func findSubnetForRegion(subnetURLs []string, region string) string {\n\tfor _, url := range subnetURLs {\n\t\tif thisRegion := getRegionInURL(url); thisRegion == region {\n\t\t\treturn url\n\t\t}\n\t}\n\treturn \"\"\n}","line":{"from":912,"to":919}} {"id":100034050,"name":"newOauthClient","signature":"func newOauthClient(tokenSource oauth2.TokenSource) (*http.Client, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"func newOauthClient(tokenSource oauth2.TokenSource) (*http.Client, error) {\n\tif tokenSource == nil {\n\t\tvar err error\n\t\ttokenSource, err = google.DefaultTokenSource(\n\t\t\tcontext.Background(),\n\t\t\tcompute.CloudPlatformScope,\n\t\t\tcompute.ComputeScope)\n\t\tklog.Infof(\"Using DefaultTokenSource %#v\", tokenSource)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tklog.Infof(\"Using existing Token Source %#v\", tokenSource)\n\t}\n\n\tbackoff := wait.Backoff{\n\t\t// These values will add up to about a minute. See #56293 for background.\n\t\tDuration: time.Second,\n\t\tFactor: 1.4,\n\t\tSteps: 10,\n\t}\n\tif err := wait.ExponentialBackoff(backoff, func() (bool, error) {\n\t\tif _, err := tokenSource.Token(); err != nil {\n\t\t\tklog.Errorf(\"error fetching initial token: %v\", err)\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn oauth2.NewClient(context.Background(), tokenSource), nil\n}","line":{"from":921,"to":953}} {"id":100034051,"name":"getProjectsAPIEndpoint","signature":"func (manager *gceServiceManager) getProjectsAPIEndpoint() string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce.go","code":"func (manager *gceServiceManager) getProjectsAPIEndpoint() string {\n\tprojectsAPIEndpoint := gceComputeAPIEndpoint + \"projects/\"\n\tif manager.gce.service != nil {\n\t\tprojectsAPIEndpoint = manager.gce.projectsBasePath\n\t}\n\n\treturn projectsAPIEndpoint\n}","line":{"from":955,"to":962}} {"id":100034052,"name":"newAddressManager","signature":"func newAddressManager(svc CloudAddressService, serviceName, region, subnetURL, name, targetIP string, addressType cloud.LbScheme) *addressManager","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_address_manager.go","code":"func newAddressManager(svc CloudAddressService, serviceName, region, subnetURL, name, targetIP string, addressType cloud.LbScheme) *addressManager {\n\treturn \u0026addressManager{\n\t\tsvc: svc,\n\t\tlogPrefix: fmt.Sprintf(\"AddressManager(%q)\", name),\n\t\tregion: region,\n\t\tserviceName: serviceName,\n\t\tname: name,\n\t\ttargetIP: targetIP,\n\t\taddressType: addressType,\n\t\ttryRelease: true,\n\t\tsubnetURL: subnetURL,\n\t}\n}","line":{"from":44,"to":56}} {"id":100034053,"name":"HoldAddress","signature":"func (am *addressManager) HoldAddress() (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_address_manager.go","code":"// HoldAddress will ensure that the IP is reserved with an address - either owned by the controller\n// or by a user. If the address is not the addressManager.name, then it's assumed to be a user's address.\n// The string returned is the reserved IP address.\nfunc (am *addressManager) HoldAddress() (string, error) {\n\t// HoldAddress starts with retrieving the address that we use for this load balancer (by name).\n\t// Retrieving an address by IP will indicate if the IP is reserved and if reserved by the user\n\t// or the controller, but won't tell us the current state of the controller's IP. The address\n\t// could be reserving another address; therefore, it would need to be deleted. In the normal\n\t// case of using a controller address, retrieving the address by name results in the fewest API\n\t// calls since it indicates whether a Delete is necessary before Reserve.\n\tklog.V(4).Infof(\"%v: attempting hold of IP %q Type %q\", am.logPrefix, am.targetIP, am.addressType)\n\t// Get the address in case it was orphaned earlier\n\taddr, err := am.svc.GetRegionAddress(am.name, am.region)\n\tif err != nil \u0026\u0026 !isNotFound(err) {\n\t\treturn \"\", err\n\t}\n\n\tif addr != nil {\n\t\t// If address exists, check if the address had the expected attributes.\n\t\tvalidationError := am.validateAddress(addr)\n\t\tif validationError == nil {\n\t\t\tklog.V(4).Infof(\"%v: address %q already reserves IP %q Type %q. No further action required.\", am.logPrefix, addr.Name, addr.Address, addr.AddressType)\n\t\t\treturn addr.Address, nil\n\t\t}\n\n\t\tklog.V(2).Infof(\"%v: deleting existing address because %v\", am.logPrefix, validationError)\n\t\terr := am.svc.DeleteRegionAddress(addr.Name, am.region)\n\t\tif err != nil {\n\t\t\tif isNotFound(err) {\n\t\t\t\tklog.V(4).Infof(\"%v: address %q was not found. Ignoring.\", am.logPrefix, addr.Name)\n\t\t\t} else {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t} else {\n\t\t\tklog.V(4).Infof(\"%v: successfully deleted previous address %q\", am.logPrefix, addr.Name)\n\t\t}\n\t}\n\n\treturn am.ensureAddressReservation()\n}","line":{"from":58,"to":97}} {"id":100034054,"name":"ReleaseAddress","signature":"func (am *addressManager) ReleaseAddress() error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_address_manager.go","code":"// ReleaseAddress will release the address if it's owned by the controller.\nfunc (am *addressManager) ReleaseAddress() error {\n\tif !am.tryRelease {\n\t\tklog.V(4).Infof(\"%v: not attempting release of address %q.\", am.logPrefix, am.targetIP)\n\t\treturn nil\n\t}\n\n\tklog.V(4).Infof(\"%v: releasing address %q named %q\", am.logPrefix, am.targetIP, am.name)\n\t// Controller only ever tries to unreserve the address named with the load balancer's name.\n\terr := am.svc.DeleteRegionAddress(am.name, am.region)\n\tif err != nil {\n\t\tif isNotFound(err) {\n\t\t\tklog.Warningf(\"%v: address %q was not found. Ignoring.\", am.logPrefix, am.name)\n\t\t\treturn nil\n\t\t}\n\n\t\treturn err\n\t}\n\n\tklog.V(4).Infof(\"%v: successfully released IP %q named %q\", am.logPrefix, am.targetIP, am.name)\n\treturn nil\n}","line":{"from":99,"to":120}} {"id":100034055,"name":"ensureAddressReservation","signature":"func (am *addressManager) ensureAddressReservation() (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_address_manager.go","code":"func (am *addressManager) ensureAddressReservation() (string, error) {\n\t// Try reserving the IP with controller-owned address name\n\t// If am.targetIP is an empty string, a new IP will be created.\n\tnewAddr := \u0026compute.Address{\n\t\tName: am.name,\n\t\tDescription: fmt.Sprintf(`{\"kubernetes.io/service-name\":\"%s\"}`, am.serviceName),\n\t\tAddress: am.targetIP,\n\t\tAddressType: string(am.addressType),\n\t\tSubnetwork: am.subnetURL,\n\t}\n\n\treserveErr := am.svc.ReserveRegionAddress(newAddr, am.region)\n\tif reserveErr == nil {\n\t\tif newAddr.Address != \"\" {\n\t\t\tklog.V(4).Infof(\"%v: successfully reserved IP %q with name %q\", am.logPrefix, newAddr.Address, newAddr.Name)\n\t\t\treturn newAddr.Address, nil\n\t\t}\n\n\t\taddr, err := am.svc.GetRegionAddress(newAddr.Name, am.region)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tklog.V(4).Infof(\"%v: successfully created address %q which reserved IP %q\", am.logPrefix, addr.Name, addr.Address)\n\t\treturn addr.Address, nil\n\t} else if !isHTTPErrorCode(reserveErr, http.StatusConflict) \u0026\u0026 !isHTTPErrorCode(reserveErr, http.StatusBadRequest) {\n\t\t// If the IP is already reserved:\n\t\t// by an internal address: a StatusConflict is returned\n\t\t// by an external address: a BadRequest is returned\n\t\treturn \"\", reserveErr\n\t}\n\n\t// If the target IP was empty, we cannot try to find which IP caused a conflict.\n\t// If the name was already used, then the next sync will attempt deletion of that address.\n\tif am.targetIP == \"\" {\n\t\treturn \"\", fmt.Errorf(\"failed to reserve address %q with no specific IP, err: %v\", am.name, reserveErr)\n\t}\n\n\t// Reserving the address failed due to a conflict or bad request. The address manager just checked that no address\n\t// exists with the name, so it may belong to the user.\n\taddr, err := am.svc.GetRegionAddressByIP(am.region, am.targetIP)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to get address by IP %q after reservation attempt, err: %q, reservation err: %q\", am.targetIP, err, reserveErr)\n\t}\n\n\t// Check that the address attributes are as required.\n\tif err := am.validateAddress(addr); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif am.isManagedAddress(addr) {\n\t\t// The address with this name is checked at the beginning of 'HoldAddress()', but for some reason\n\t\t// it was re-created by this point. May be possible that two controllers are running.\n\t\tklog.Warningf(\"%v: address %q unexpectedly existed with IP %q.\", am.logPrefix, addr.Name, am.targetIP)\n\t} else {\n\t\t// If the retrieved address is not named with the loadbalancer name, then the controller does not own it, but will allow use of it.\n\t\tklog.V(4).Infof(\"%v: address %q was already reserved with name: %q, description: %q\", am.logPrefix, am.targetIP, addr.Name, addr.Description)\n\t\tam.tryRelease = false\n\t}\n\n\treturn addr.Address, nil\n}","line":{"from":122,"to":183}} {"id":100034056,"name":"validateAddress","signature":"func (am *addressManager) validateAddress(addr *compute.Address) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_address_manager.go","code":"func (am *addressManager) validateAddress(addr *compute.Address) error {\n\tif am.targetIP != \"\" \u0026\u0026 am.targetIP != addr.Address {\n\t\treturn fmt.Errorf(\"address %q does not have the expected IP %q, actual: %q\", addr.Name, am.targetIP, addr.Address)\n\t}\n\tif addr.AddressType != string(am.addressType) {\n\t\treturn fmt.Errorf(\"address %q does not have the expected address type %q, actual: %q\", addr.Name, am.addressType, addr.AddressType)\n\t}\n\n\treturn nil\n}","line":{"from":185,"to":194}} {"id":100034057,"name":"isManagedAddress","signature":"func (am *addressManager) isManagedAddress(addr *compute.Address) bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_address_manager.go","code":"func (am *addressManager) isManagedAddress(addr *compute.Address) bool {\n\treturn addr.Name == am.name\n}","line":{"from":196,"to":198}} {"id":100034058,"name":"ensureAddressDeleted","signature":"func ensureAddressDeleted(svc CloudAddressService, name, region string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_address_manager.go","code":"func ensureAddressDeleted(svc CloudAddressService, name, region string) error {\n\treturn ignoreNotFound(svc.DeleteRegionAddress(name, region))\n}","line":{"from":200,"to":202}} {"id":100034059,"name":"newAddressMetricContext","signature":"func newAddressMetricContext(request, region string) *metricContext","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_addresses.go","code":"func newAddressMetricContext(request, region string) *metricContext {\n\treturn newAddressMetricContextWithVersion(request, region, computeV1Version)\n}","line":{"from":35,"to":37}} {"id":100034060,"name":"newAddressMetricContextWithVersion","signature":"func newAddressMetricContextWithVersion(request, region, version string) *metricContext","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_addresses.go","code":"func newAddressMetricContextWithVersion(request, region, version string) *metricContext {\n\treturn newGenericMetricContext(\"address\", request, region, unusedMetricLabel, version)\n}","line":{"from":39,"to":41}} {"id":100034061,"name":"ReserveGlobalAddress","signature":"func (g *Cloud) ReserveGlobalAddress(addr *compute.Address) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_addresses.go","code":"// ReserveGlobalAddress creates a global address.\n// Caller is allocated a random IP if they do not specify an ipAddress. If an\n// ipAddress is specified, it must belong to the current project, eg: an\n// ephemeral IP associated with a global forwarding rule.\nfunc (g *Cloud) ReserveGlobalAddress(addr *compute.Address) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newAddressMetricContext(\"reserve\", \"\")\n\treturn mc.Observe(g.c.GlobalAddresses().Insert(ctx, meta.GlobalKey(addr.Name), addr))\n}","line":{"from":43,"to":53}} {"id":100034062,"name":"DeleteGlobalAddress","signature":"func (g *Cloud) DeleteGlobalAddress(name string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_addresses.go","code":"// DeleteGlobalAddress deletes a global address by name.\nfunc (g *Cloud) DeleteGlobalAddress(name string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newAddressMetricContext(\"delete\", \"\")\n\treturn mc.Observe(g.c.GlobalAddresses().Delete(ctx, meta.GlobalKey(name)))\n}","line":{"from":55,"to":62}} {"id":100034063,"name":"GetGlobalAddress","signature":"func (g *Cloud) GetGlobalAddress(name string) (*compute.Address, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_addresses.go","code":"// GetGlobalAddress returns the global address by name.\nfunc (g *Cloud) GetGlobalAddress(name string) (*compute.Address, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newAddressMetricContext(\"get\", \"\")\n\tv, err := g.c.GlobalAddresses().Get(ctx, meta.GlobalKey(name))\n\treturn v, mc.Observe(err)\n}","line":{"from":64,"to":72}} {"id":100034064,"name":"ReserveRegionAddress","signature":"func (g *Cloud) ReserveRegionAddress(addr *compute.Address, region string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_addresses.go","code":"// ReserveRegionAddress creates a region address\nfunc (g *Cloud) ReserveRegionAddress(addr *compute.Address, region string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newAddressMetricContext(\"reserve\", region)\n\treturn mc.Observe(g.c.Addresses().Insert(ctx, meta.RegionalKey(addr.Name, region), addr))\n}","line":{"from":74,"to":81}} {"id":100034065,"name":"ReserveBetaRegionAddress","signature":"func (g *Cloud) ReserveBetaRegionAddress(addr *computebeta.Address, region string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_addresses.go","code":"// ReserveBetaRegionAddress creates a beta region address\nfunc (g *Cloud) ReserveBetaRegionAddress(addr *computebeta.Address, region string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newAddressMetricContext(\"reserve\", region)\n\treturn mc.Observe(g.c.BetaAddresses().Insert(ctx, meta.RegionalKey(addr.Name, region), addr))\n}","line":{"from":83,"to":90}} {"id":100034066,"name":"DeleteRegionAddress","signature":"func (g *Cloud) DeleteRegionAddress(name, region string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_addresses.go","code":"// DeleteRegionAddress deletes a region address by name.\nfunc (g *Cloud) DeleteRegionAddress(name, region string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newAddressMetricContext(\"delete\", region)\n\treturn mc.Observe(g.c.Addresses().Delete(ctx, meta.RegionalKey(name, region)))\n}","line":{"from":92,"to":99}} {"id":100034067,"name":"GetRegionAddress","signature":"func (g *Cloud) GetRegionAddress(name, region string) (*compute.Address, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_addresses.go","code":"// GetRegionAddress returns the region address by name\nfunc (g *Cloud) GetRegionAddress(name, region string) (*compute.Address, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newAddressMetricContext(\"get\", region)\n\tv, err := g.c.Addresses().Get(ctx, meta.RegionalKey(name, region))\n\treturn v, mc.Observe(err)\n}","line":{"from":101,"to":109}} {"id":100034068,"name":"GetBetaRegionAddress","signature":"func (g *Cloud) GetBetaRegionAddress(name, region string) (*computebeta.Address, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_addresses.go","code":"// GetBetaRegionAddress returns the beta region address by name\nfunc (g *Cloud) GetBetaRegionAddress(name, region string) (*computebeta.Address, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newAddressMetricContext(\"get\", region)\n\tv, err := g.c.BetaAddresses().Get(ctx, meta.RegionalKey(name, region))\n\treturn v, mc.Observe(err)\n}","line":{"from":111,"to":119}} {"id":100034069,"name":"GetRegionAddressByIP","signature":"func (g *Cloud) GetRegionAddressByIP(region, ipAddress string) (*compute.Address, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_addresses.go","code":"// GetRegionAddressByIP returns the regional address matching the given IP address.\nfunc (g *Cloud) GetRegionAddressByIP(region, ipAddress string) (*compute.Address, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newAddressMetricContext(\"list\", region)\n\taddrs, err := g.c.Addresses().List(ctx, region, filter.Regexp(\"address\", ipAddress))\n\n\tmc.Observe(err)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(addrs) \u003e 1 {\n\t\tklog.Warningf(\"More than one addresses matching the IP %q: %v\", ipAddress, addrNames(addrs))\n\t}\n\tfor _, addr := range addrs {\n\t\tif addr.Address == ipAddress {\n\t\t\treturn addr, nil\n\t\t}\n\t}\n\treturn nil, makeGoogleAPINotFoundError(fmt.Sprintf(\"Address with IP %q was not found in region %q\", ipAddress, region))\n}","line":{"from":121,"to":143}} {"id":100034070,"name":"GetBetaRegionAddressByIP","signature":"func (g *Cloud) GetBetaRegionAddressByIP(region, ipAddress string) (*computebeta.Address, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_addresses.go","code":"// GetBetaRegionAddressByIP returns the beta regional address matching the given IP address.\nfunc (g *Cloud) GetBetaRegionAddressByIP(region, ipAddress string) (*computebeta.Address, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newAddressMetricContext(\"list\", region)\n\taddrs, err := g.c.BetaAddresses().List(ctx, region, filter.Regexp(\"address\", ipAddress))\n\n\tmc.Observe(err)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(addrs) \u003e 1 {\n\t\tklog.Warningf(\"More than one addresses matching the IP %q: %v\", ipAddress, addrNames(addrs))\n\t}\n\tfor _, addr := range addrs {\n\t\tif addr.Address == ipAddress {\n\t\t\treturn addr, nil\n\t\t}\n\t}\n\treturn nil, makeGoogleAPINotFoundError(fmt.Sprintf(\"Address with IP %q was not found in region %q\", ipAddress, region))\n}","line":{"from":145,"to":167}} {"id":100034071,"name":"getNetworkTierFromAddress","signature":"func (g *Cloud) getNetworkTierFromAddress(name, region string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_addresses.go","code":"func (g *Cloud) getNetworkTierFromAddress(name, region string) (string, error) {\n\n\taddr, err := g.GetRegionAddress(name, region)\n\tif err != nil {\n\t\t// Can't get the network tier, just return an error.\n\t\treturn \"\", err\n\t}\n\treturn addr.NetworkTier, nil\n}","line":{"from":169,"to":177}} {"id":100034072,"name":"addrNames","signature":"func addrNames(items interface{}) []string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_addresses.go","code":"func addrNames(items interface{}) []string {\n\tvar ret []string\n\tswitch items := items.(type) {\n\tcase []compute.Address:\n\t\tfor _, a := range items {\n\t\t\tret = append(ret, a.Name)\n\t\t}\n\tcase []computebeta.Address:\n\t\tfor _, a := range items {\n\t\t\tret = append(ret, a.Name)\n\t\t}\n\t}\n\treturn ret\n}","line":{"from":179,"to":192}} {"id":100034073,"name":"Enabled","signature":"func (af *AlphaFeatureGate) Enabled(key string) bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_alpha.go","code":"// Enabled returns true if the provided alpha feature is enabled\nfunc (af *AlphaFeatureGate) Enabled(key string) bool {\n\tif af == nil || af.features == nil {\n\t\treturn false\n\t}\n\treturn af.features[key]\n}","line":{"from":37,"to":43}} {"id":100034074,"name":"NewAlphaFeatureGate","signature":"func NewAlphaFeatureGate(features []string) *AlphaFeatureGate","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_alpha.go","code":"// NewAlphaFeatureGate marks the provided alpha features as enabled\nfunc NewAlphaFeatureGate(features []string) *AlphaFeatureGate {\n\tfeatureMap := make(map[string]bool)\n\tfor _, name := range features {\n\t\tfeatureMap[name] = true\n\t}\n\treturn \u0026AlphaFeatureGate{featureMap}\n}","line":{"from":45,"to":52}} {"id":100034075,"name":"GetLoadBalancerAnnotationType","signature":"func GetLoadBalancerAnnotationType(service *v1.Service) LoadBalancerType","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_annotations.go","code":"// GetLoadBalancerAnnotationType returns the type of GCP load balancer which should be assembled.\nfunc GetLoadBalancerAnnotationType(service *v1.Service) LoadBalancerType {\n\tvar lbType LoadBalancerType\n\tfor _, ann := range []string{\n\t\tServiceAnnotationLoadBalancerType,\n\t\tdeprecatedServiceAnnotationLoadBalancerType,\n\t} {\n\t\tif v, ok := service.Annotations[ann]; ok {\n\t\t\tlbType = LoadBalancerType(v)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tswitch lbType {\n\tcase LBTypeInternal, deprecatedTypeInternalLowerCase:\n\t\treturn LBTypeInternal\n\tdefault:\n\t\treturn lbType\n\t}\n}","line":{"from":86,"to":105}} {"id":100034076,"name":"GetLoadBalancerAnnotationBackendShare","signature":"func GetLoadBalancerAnnotationBackendShare(service *v1.Service) bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_annotations.go","code":"// GetLoadBalancerAnnotationBackendShare returns whether this service's backend service should be\n// shared with other load balancers. Health checks and the healthcheck firewall will be shared regardless.\nfunc GetLoadBalancerAnnotationBackendShare(service *v1.Service) bool {\n\tif l, exists := service.Annotations[ServiceAnnotationILBBackendShare]; exists \u0026\u0026 l == \"true\" {\n\t\treturn true\n\t}\n\n\t// Check for deprecated annotation key\n\tif l, exists := service.Annotations[deprecatedServiceAnnotationILBBackendShare]; exists \u0026\u0026 l == \"true\" {\n\t\tklog.Warningf(\"Annotation %q is deprecated and replaced with an alpha-specific key: %q\", deprecatedServiceAnnotationILBBackendShare, ServiceAnnotationILBBackendShare)\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":107,"to":121}} {"id":100034077,"name":"GetServiceNetworkTier","signature":"func GetServiceNetworkTier(service *v1.Service) (cloud.NetworkTier, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_annotations.go","code":"// GetServiceNetworkTier returns the network tier of GCP load balancer\n// which should be assembled, and an error if the specified tier is not\n// supported.\nfunc GetServiceNetworkTier(service *v1.Service) (cloud.NetworkTier, error) {\n\tl, ok := service.Annotations[NetworkTierAnnotationKey]\n\tif !ok {\n\t\treturn cloud.NetworkTierDefault, nil\n\t}\n\n\tv := cloud.NetworkTier(l)\n\tswitch v {\n\tcase cloud.NetworkTierStandard:\n\t\tfallthrough\n\tcase cloud.NetworkTierPremium:\n\t\treturn v, nil\n\tdefault:\n\t\treturn cloud.NetworkTierDefault, fmt.Errorf(\"unsupported network tier: %q\", v)\n\t}\n}","line":{"from":123,"to":141}} {"id":100034078,"name":"GetLoadBalancerAnnotationAllowGlobalAccess","signature":"func GetLoadBalancerAnnotationAllowGlobalAccess(service *v1.Service) bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_annotations.go","code":"// GetLoadBalancerAnnotationAllowGlobalAccess returns if global access is enabled\n// for the given loadbalancer service.\nfunc GetLoadBalancerAnnotationAllowGlobalAccess(service *v1.Service) bool {\n\treturn service.Annotations[ServiceAnnotationILBAllowGlobalAccess] == \"true\"\n}","line":{"from":152,"to":156}} {"id":100034079,"name":"GetLoadBalancerAnnotationSubnet","signature":"func GetLoadBalancerAnnotationSubnet(service *v1.Service) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_annotations.go","code":"// GetLoadBalancerAnnotationSubnet returns the configured subnet to assign LoadBalancer IP from.\nfunc GetLoadBalancerAnnotationSubnet(service *v1.Service) string {\n\tif val, exists := service.Annotations[ServiceAnnotationILBSubnet]; exists {\n\t\treturn val\n\t}\n\treturn \"\"\n}","line":{"from":158,"to":164}} {"id":100034080,"name":"newBackendServiceMetricContext","signature":"func newBackendServiceMetricContext(request, region string) *metricContext","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_backendservice.go","code":"func newBackendServiceMetricContext(request, region string) *metricContext {\n\treturn newBackendServiceMetricContextWithVersion(request, region, computeV1Version)\n}","line":{"from":32,"to":34}} {"id":100034081,"name":"newBackendServiceMetricContextWithVersion","signature":"func newBackendServiceMetricContextWithVersion(request, region, version string) *metricContext","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_backendservice.go","code":"func newBackendServiceMetricContextWithVersion(request, region, version string) *metricContext {\n\treturn newGenericMetricContext(\"backendservice\", request, region, unusedMetricLabel, version)\n}","line":{"from":36,"to":38}} {"id":100034082,"name":"GetGlobalBackendService","signature":"func (g *Cloud) GetGlobalBackendService(name string) (*compute.BackendService, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_backendservice.go","code":"// GetGlobalBackendService retrieves a backend by name.\nfunc (g *Cloud) GetGlobalBackendService(name string) (*compute.BackendService, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newBackendServiceMetricContext(\"get\", \"\")\n\tv, err := g.c.BackendServices().Get(ctx, meta.GlobalKey(name))\n\treturn v, mc.Observe(err)\n}","line":{"from":40,"to":48}} {"id":100034083,"name":"GetBetaGlobalBackendService","signature":"func (g *Cloud) GetBetaGlobalBackendService(name string) (*computebeta.BackendService, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_backendservice.go","code":"// GetBetaGlobalBackendService retrieves beta backend by name.\nfunc (g *Cloud) GetBetaGlobalBackendService(name string) (*computebeta.BackendService, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newBackendServiceMetricContextWithVersion(\"get\", \"\", computeBetaVersion)\n\tv, err := g.c.BetaBackendServices().Get(ctx, meta.GlobalKey(name))\n\treturn v, mc.Observe(err)\n}","line":{"from":50,"to":58}} {"id":100034084,"name":"GetAlphaGlobalBackendService","signature":"func (g *Cloud) GetAlphaGlobalBackendService(name string) (*computealpha.BackendService, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_backendservice.go","code":"// GetAlphaGlobalBackendService retrieves alpha backend by name.\nfunc (g *Cloud) GetAlphaGlobalBackendService(name string) (*computealpha.BackendService, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newBackendServiceMetricContextWithVersion(\"get\", \"\", computeAlphaVersion)\n\tv, err := g.c.AlphaBackendServices().Get(ctx, meta.GlobalKey(name))\n\treturn v, mc.Observe(err)\n}","line":{"from":60,"to":68}} {"id":100034085,"name":"UpdateGlobalBackendService","signature":"func (g *Cloud) UpdateGlobalBackendService(bg *compute.BackendService) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_backendservice.go","code":"// UpdateGlobalBackendService applies the given BackendService as an update to\n// an existing service.\nfunc (g *Cloud) UpdateGlobalBackendService(bg *compute.BackendService) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newBackendServiceMetricContext(\"update\", \"\")\n\treturn mc.Observe(g.c.BackendServices().Update(ctx, meta.GlobalKey(bg.Name), bg))\n}","line":{"from":70,"to":78}} {"id":100034086,"name":"UpdateBetaGlobalBackendService","signature":"func (g *Cloud) UpdateBetaGlobalBackendService(bg *computebeta.BackendService) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_backendservice.go","code":"// UpdateBetaGlobalBackendService applies the given beta BackendService as an\n// update to an existing service.\nfunc (g *Cloud) UpdateBetaGlobalBackendService(bg *computebeta.BackendService) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newBackendServiceMetricContextWithVersion(\"update\", \"\", computeBetaVersion)\n\treturn mc.Observe(g.c.BetaBackendServices().Update(ctx, meta.GlobalKey(bg.Name), bg))\n}","line":{"from":80,"to":88}} {"id":100034087,"name":"UpdateAlphaGlobalBackendService","signature":"func (g *Cloud) UpdateAlphaGlobalBackendService(bg *computealpha.BackendService) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_backendservice.go","code":"// UpdateAlphaGlobalBackendService applies the given alpha BackendService as an\n// update to an existing service.\nfunc (g *Cloud) UpdateAlphaGlobalBackendService(bg *computealpha.BackendService) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newBackendServiceMetricContextWithVersion(\"update\", \"\", computeAlphaVersion)\n\treturn mc.Observe(g.c.AlphaBackendServices().Update(ctx, meta.GlobalKey(bg.Name), bg))\n}","line":{"from":90,"to":98}} {"id":100034088,"name":"DeleteGlobalBackendService","signature":"func (g *Cloud) DeleteGlobalBackendService(name string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_backendservice.go","code":"// DeleteGlobalBackendService deletes the given BackendService by name.\nfunc (g *Cloud) DeleteGlobalBackendService(name string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newBackendServiceMetricContext(\"delete\", \"\")\n\treturn mc.Observe(g.c.BackendServices().Delete(ctx, meta.GlobalKey(name)))\n}","line":{"from":100,"to":107}} {"id":100034089,"name":"CreateGlobalBackendService","signature":"func (g *Cloud) CreateGlobalBackendService(bg *compute.BackendService) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_backendservice.go","code":"// CreateGlobalBackendService creates the given BackendService.\nfunc (g *Cloud) CreateGlobalBackendService(bg *compute.BackendService) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newBackendServiceMetricContext(\"create\", \"\")\n\treturn mc.Observe(g.c.BackendServices().Insert(ctx, meta.GlobalKey(bg.Name), bg))\n}","line":{"from":109,"to":116}} {"id":100034090,"name":"CreateBetaGlobalBackendService","signature":"func (g *Cloud) CreateBetaGlobalBackendService(bg *computebeta.BackendService) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_backendservice.go","code":"// CreateBetaGlobalBackendService creates the given beta BackendService.\nfunc (g *Cloud) CreateBetaGlobalBackendService(bg *computebeta.BackendService) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newBackendServiceMetricContextWithVersion(\"create\", \"\", computeBetaVersion)\n\treturn mc.Observe(g.c.BetaBackendServices().Insert(ctx, meta.GlobalKey(bg.Name), bg))\n}","line":{"from":118,"to":125}} {"id":100034091,"name":"CreateAlphaGlobalBackendService","signature":"func (g *Cloud) CreateAlphaGlobalBackendService(bg *computealpha.BackendService) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_backendservice.go","code":"// CreateAlphaGlobalBackendService creates the given alpha BackendService.\nfunc (g *Cloud) CreateAlphaGlobalBackendService(bg *computealpha.BackendService) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newBackendServiceMetricContextWithVersion(\"create\", \"\", computeAlphaVersion)\n\treturn mc.Observe(g.c.AlphaBackendServices().Insert(ctx, meta.GlobalKey(bg.Name), bg))\n}","line":{"from":127,"to":134}} {"id":100034092,"name":"ListGlobalBackendServices","signature":"func (g *Cloud) ListGlobalBackendServices() ([]*compute.BackendService, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_backendservice.go","code":"// ListGlobalBackendServices lists all backend services in the project.\nfunc (g *Cloud) ListGlobalBackendServices() ([]*compute.BackendService, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newBackendServiceMetricContext(\"list\", \"\")\n\tv, err := g.c.BackendServices().List(ctx, filter.None)\n\treturn v, mc.Observe(err)\n}","line":{"from":136,"to":144}} {"id":100034093,"name":"GetGlobalBackendServiceHealth","signature":"func (g *Cloud) GetGlobalBackendServiceHealth(name string, instanceGroupLink string) (*compute.BackendServiceGroupHealth, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_backendservice.go","code":"// GetGlobalBackendServiceHealth returns the health of the BackendService\n// identified by the given name, in the given instanceGroup. The\n// instanceGroupLink is the fully qualified self link of an instance group.\nfunc (g *Cloud) GetGlobalBackendServiceHealth(name string, instanceGroupLink string) (*compute.BackendServiceGroupHealth, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newBackendServiceMetricContext(\"get_health\", \"\")\n\tgroupRef := \u0026compute.ResourceGroupReference{Group: instanceGroupLink}\n\tv, err := g.c.BackendServices().GetHealth(ctx, meta.GlobalKey(name), groupRef)\n\treturn v, mc.Observe(err)\n}","line":{"from":146,"to":157}} {"id":100034094,"name":"GetRegionBackendService","signature":"func (g *Cloud) GetRegionBackendService(name, region string) (*compute.BackendService, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_backendservice.go","code":"// GetRegionBackendService retrieves a backend by name.\nfunc (g *Cloud) GetRegionBackendService(name, region string) (*compute.BackendService, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newBackendServiceMetricContext(\"get\", region)\n\tv, err := g.c.RegionBackendServices().Get(ctx, meta.RegionalKey(name, region))\n\treturn v, mc.Observe(err)\n}","line":{"from":159,"to":167}} {"id":100034095,"name":"UpdateRegionBackendService","signature":"func (g *Cloud) UpdateRegionBackendService(bg *compute.BackendService, region string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_backendservice.go","code":"// UpdateRegionBackendService applies the given BackendService as an update to\n// an existing service.\nfunc (g *Cloud) UpdateRegionBackendService(bg *compute.BackendService, region string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newBackendServiceMetricContext(\"update\", region)\n\treturn mc.Observe(g.c.RegionBackendServices().Update(ctx, meta.RegionalKey(bg.Name, region), bg))\n}","line":{"from":169,"to":177}} {"id":100034096,"name":"DeleteRegionBackendService","signature":"func (g *Cloud) DeleteRegionBackendService(name, region string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_backendservice.go","code":"// DeleteRegionBackendService deletes the given BackendService by name.\nfunc (g *Cloud) DeleteRegionBackendService(name, region string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newBackendServiceMetricContext(\"delete\", region)\n\treturn mc.Observe(g.c.RegionBackendServices().Delete(ctx, meta.RegionalKey(name, region)))\n}","line":{"from":179,"to":186}} {"id":100034097,"name":"CreateRegionBackendService","signature":"func (g *Cloud) CreateRegionBackendService(bg *compute.BackendService, region string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_backendservice.go","code":"// CreateRegionBackendService creates the given BackendService.\nfunc (g *Cloud) CreateRegionBackendService(bg *compute.BackendService, region string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newBackendServiceMetricContext(\"create\", region)\n\treturn mc.Observe(g.c.RegionBackendServices().Insert(ctx, meta.RegionalKey(bg.Name, region), bg))\n}","line":{"from":188,"to":195}} {"id":100034098,"name":"ListRegionBackendServices","signature":"func (g *Cloud) ListRegionBackendServices(region string) ([]*compute.BackendService, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_backendservice.go","code":"// ListRegionBackendServices lists all backend services in the project.\nfunc (g *Cloud) ListRegionBackendServices(region string) ([]*compute.BackendService, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newBackendServiceMetricContext(\"list\", region)\n\tv, err := g.c.RegionBackendServices().List(ctx, region, filter.None)\n\treturn v, mc.Observe(err)\n}","line":{"from":197,"to":205}} {"id":100034099,"name":"GetRegionalBackendServiceHealth","signature":"func (g *Cloud) GetRegionalBackendServiceHealth(name, region string, instanceGroupLink string) (*compute.BackendServiceGroupHealth, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_backendservice.go","code":"// GetRegionalBackendServiceHealth returns the health of the BackendService\n// identified by the given name, in the given instanceGroup. The\n// instanceGroupLink is the fully qualified self link of an instance group.\nfunc (g *Cloud) GetRegionalBackendServiceHealth(name, region string, instanceGroupLink string) (*compute.BackendServiceGroupHealth, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newBackendServiceMetricContext(\"get_health\", region)\n\tref := \u0026compute.ResourceGroupReference{Group: instanceGroupLink}\n\tv, err := g.c.RegionBackendServices().GetHealth(ctx, meta.RegionalKey(name, region), ref)\n\treturn v, mc.Observe(err)\n}","line":{"from":207,"to":218}} {"id":100034100,"name":"SetSecurityPolicyForBetaGlobalBackendService","signature":"func (g *Cloud) SetSecurityPolicyForBetaGlobalBackendService(backendServiceName string, securityPolicyReference *computebeta.SecurityPolicyReference) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_backendservice.go","code":"// SetSecurityPolicyForBetaGlobalBackendService sets the given\n// SecurityPolicyReference for the BackendService identified by the given name.\nfunc (g *Cloud) SetSecurityPolicyForBetaGlobalBackendService(backendServiceName string, securityPolicyReference *computebeta.SecurityPolicyReference) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newBackendServiceMetricContextWithVersion(\"set_security_policy\", \"\", computeBetaVersion)\n\treturn mc.Observe(g.c.BetaBackendServices().SetSecurityPolicy(ctx, meta.GlobalKey(backendServiceName), securityPolicyReference))\n}","line":{"from":220,"to":228}} {"id":100034101,"name":"SetSecurityPolicyForAlphaGlobalBackendService","signature":"func (g *Cloud) SetSecurityPolicyForAlphaGlobalBackendService(backendServiceName string, securityPolicyReference *computealpha.SecurityPolicyReference) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_backendservice.go","code":"// SetSecurityPolicyForAlphaGlobalBackendService sets the given\n// SecurityPolicyReference for the BackendService identified by the given name.\nfunc (g *Cloud) SetSecurityPolicyForAlphaGlobalBackendService(backendServiceName string, securityPolicyReference *computealpha.SecurityPolicyReference) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newBackendServiceMetricContextWithVersion(\"set_security_policy\", \"\", computeAlphaVersion)\n\treturn mc.Observe(g.c.AlphaBackendServices().SetSecurityPolicy(ctx, meta.GlobalKey(backendServiceName), securityPolicyReference))\n}","line":{"from":230,"to":238}} {"id":100034102,"name":"newCertMetricContext","signature":"func newCertMetricContext(request string) *metricContext","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_cert.go","code":"func newCertMetricContext(request string) *metricContext {\n\treturn newGenericMetricContext(\"cert\", request, unusedMetricLabel, unusedMetricLabel, computeV1Version)\n}","line":{"from":30,"to":32}} {"id":100034103,"name":"GetSslCertificate","signature":"func (g *Cloud) GetSslCertificate(name string) (*compute.SslCertificate, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_cert.go","code":"// GetSslCertificate returns the SslCertificate by name.\nfunc (g *Cloud) GetSslCertificate(name string) (*compute.SslCertificate, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newCertMetricContext(\"get\")\n\tv, err := g.c.SslCertificates().Get(ctx, meta.GlobalKey(name))\n\treturn v, mc.Observe(err)\n}","line":{"from":34,"to":42}} {"id":100034104,"name":"CreateSslCertificate","signature":"func (g *Cloud) CreateSslCertificate(sslCerts *compute.SslCertificate) (*compute.SslCertificate, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_cert.go","code":"// CreateSslCertificate creates and returns a SslCertificate.\nfunc (g *Cloud) CreateSslCertificate(sslCerts *compute.SslCertificate) (*compute.SslCertificate, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newCertMetricContext(\"create\")\n\terr := g.c.SslCertificates().Insert(ctx, meta.GlobalKey(sslCerts.Name), sslCerts)\n\tif err != nil {\n\t\treturn nil, mc.Observe(err)\n\t}\n\treturn g.GetSslCertificate(sslCerts.Name)\n}","line":{"from":44,"to":55}} {"id":100034105,"name":"DeleteSslCertificate","signature":"func (g *Cloud) DeleteSslCertificate(name string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_cert.go","code":"// DeleteSslCertificate deletes the SslCertificate by name.\nfunc (g *Cloud) DeleteSslCertificate(name string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newCertMetricContext(\"delete\")\n\treturn mc.Observe(g.c.SslCertificates().Delete(ctx, meta.GlobalKey(name)))\n}","line":{"from":57,"to":64}} {"id":100034106,"name":"ListSslCertificates","signature":"func (g *Cloud) ListSslCertificates() ([]*compute.SslCertificate, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_cert.go","code":"// ListSslCertificates lists all SslCertificates in the project.\nfunc (g *Cloud) ListSslCertificates() ([]*compute.SslCertificate, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newCertMetricContext(\"list\")\n\tv, err := g.c.SslCertificates().List(ctx, filter.None)\n\treturn v, mc.Observe(err)\n}","line":{"from":66,"to":74}} {"id":100034107,"name":"watchClusterID","signature":"func (g *Cloud) watchClusterID(stop \u003c-chan struct{})","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_clusterid.go","code":"// Continually watches for changes to the cluster id config map\nfunc (g *Cloud) watchClusterID(stop \u003c-chan struct{}) {\n\tg.ClusterID = ClusterID{\n\t\tcfgMapKey: fmt.Sprintf(\"%v/%v\", UIDNamespace, UIDConfigMapName),\n\t\tclient: g.client,\n\t}\n\n\tmapEventHandler := cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tm, ok := obj.(*v1.ConfigMap)\n\t\t\tif !ok || m == nil {\n\t\t\t\tklog.Errorf(\"Expected v1.ConfigMap, item=%+v, typeIsOk=%v\", obj, ok)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif m.Namespace != UIDNamespace ||\n\t\t\t\tm.Name != UIDConfigMapName {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tklog.V(4).Infof(\"Observed new configmap for clusteriD: %v, %v; setting local values\", m.Name, m.Data)\n\t\t\tg.ClusterID.update(m)\n\t\t},\n\t\tUpdateFunc: func(old, cur interface{}) {\n\t\t\tm, ok := cur.(*v1.ConfigMap)\n\t\t\tif !ok || m == nil {\n\t\t\t\tklog.Errorf(\"Expected v1.ConfigMap, item=%+v, typeIsOk=%v\", cur, ok)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif m.Namespace != UIDNamespace ||\n\t\t\t\tm.Name != UIDConfigMapName {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif reflect.DeepEqual(old, cur) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tklog.V(4).Infof(\"Observed updated configmap for clusteriD %v, %v; setting local values\", m.Name, m.Data)\n\t\t\tg.ClusterID.update(m)\n\t\t},\n\t}\n\n\tlisterWatcher := cache.NewListWatchFromClient(g.ClusterID.client.CoreV1().RESTClient(), \"configmaps\", UIDNamespace, fields.Everything())\n\tvar controller cache.Controller\n\tg.ClusterID.store, controller = cache.NewInformer(newSingleObjectListerWatcher(listerWatcher, UIDConfigMapName), \u0026v1.ConfigMap{}, updateFuncFrequency, mapEventHandler)\n\n\tcontroller.Run(stop)\n}","line":{"from":73,"to":121}} {"id":100034108,"name":"GetID","signature":"func (ci *ClusterID) GetID() (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_clusterid.go","code":"// GetID returns the id which is unique to this cluster\n// if federated, return the provider id (unique to the cluster)\n// if not federated, return the cluster id\nfunc (ci *ClusterID) GetID() (string, error) {\n\tif err := ci.getOrInitialize(); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tci.idLock.RLock()\n\tdefer ci.idLock.RUnlock()\n\tif ci.clusterID == nil {\n\t\treturn \"\", errors.New(\"Could not retrieve cluster id\")\n\t}\n\n\t// If provider ID is set, (Federation is enabled) use this field\n\tif ci.providerID != nil {\n\t\treturn *ci.providerID, nil\n\t}\n\n\t// providerID is not set, use the cluster id\n\treturn *ci.clusterID, nil\n}","line":{"from":123,"to":144}} {"id":100034109,"name":"GetFederationID","signature":"func (ci *ClusterID) GetFederationID() (string, bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_clusterid.go","code":"// GetFederationID returns the id which could represent the entire Federation\n// or just the cluster if not federated.\nfunc (ci *ClusterID) GetFederationID() (string, bool, error) {\n\tif err := ci.getOrInitialize(); err != nil {\n\t\treturn \"\", false, err\n\t}\n\n\tci.idLock.RLock()\n\tdefer ci.idLock.RUnlock()\n\tif ci.clusterID == nil {\n\t\treturn \"\", false, errors.New(\"could not retrieve cluster id\")\n\t}\n\n\t// If provider ID is not set, return false\n\tif ci.providerID == nil || *ci.clusterID == *ci.providerID {\n\t\treturn \"\", false, nil\n\t}\n\n\treturn *ci.clusterID, true, nil\n}","line":{"from":146,"to":165}} {"id":100034110,"name":"getOrInitialize","signature":"func (ci *ClusterID) getOrInitialize() error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_clusterid.go","code":"// getOrInitialize either grabs the configmaps current value or defines the value\n// and sets the configmap. This is for the case of the user calling GetClusterID()\n// before the watch has begun.\nfunc (ci *ClusterID) getOrInitialize() error {\n\tif ci.store == nil {\n\t\treturn errors.New(\"Cloud.ClusterID is not ready. Call Initialize() before using\")\n\t}\n\n\tif ci.clusterID != nil {\n\t\treturn nil\n\t}\n\n\texists, err := ci.getConfigMap()\n\tif err != nil {\n\t\treturn err\n\t} else if exists {\n\t\treturn nil\n\t}\n\n\t// The configmap does not exist - let's try creating one.\n\tnewID, err := makeUID()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tklog.V(4).Infof(\"Creating clusteriD: %v\", newID)\n\tcfg := \u0026v1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: UIDConfigMapName,\n\t\t\tNamespace: UIDNamespace,\n\t\t},\n\t}\n\tcfg.Data = map[string]string{\n\t\tUIDCluster: newID,\n\t\tUIDProvider: newID,\n\t}\n\n\tif _, err := ci.client.CoreV1().ConfigMaps(UIDNamespace).Create(context.TODO(), cfg, metav1.CreateOptions{}); err != nil {\n\t\tklog.Errorf(\"GCE cloud provider failed to create %v config map to store cluster id: %v\", ci.cfgMapKey, err)\n\t\treturn err\n\t}\n\n\tklog.V(2).Infof(\"Created a config map containing clusteriD: %v\", newID)\n\tci.update(cfg)\n\treturn nil\n}","line":{"from":167,"to":212}} {"id":100034111,"name":"getConfigMap","signature":"func (ci *ClusterID) getConfigMap() (bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_clusterid.go","code":"func (ci *ClusterID) getConfigMap() (bool, error) {\n\titem, exists, err := ci.store.GetByKey(ci.cfgMapKey)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif !exists {\n\t\treturn false, nil\n\t}\n\n\tm, ok := item.(*v1.ConfigMap)\n\tif !ok || m == nil {\n\t\terr = fmt.Errorf(\"Expected v1.ConfigMap, item=%+v, typeIsOk=%v\", item, ok)\n\t\tklog.Error(err)\n\t\treturn false, err\n\t}\n\tci.update(m)\n\treturn true, nil\n}","line":{"from":214,"to":231}} {"id":100034112,"name":"update","signature":"func (ci *ClusterID) update(m *v1.ConfigMap)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_clusterid.go","code":"func (ci *ClusterID) update(m *v1.ConfigMap) {\n\tci.idLock.Lock()\n\tdefer ci.idLock.Unlock()\n\tif clusterID, exists := m.Data[UIDCluster]; exists {\n\t\tci.clusterID = \u0026clusterID\n\t}\n\tif provID, exists := m.Data[UIDProvider]; exists {\n\t\tci.providerID = \u0026provID\n\t}\n}","line":{"from":233,"to":242}} {"id":100034113,"name":"makeUID","signature":"func makeUID() (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_clusterid.go","code":"func makeUID() (string, error) {\n\tb := make([]byte, UIDLengthBytes)\n\t_, err := rand.Read(b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn hex.EncodeToString(b), nil\n}","line":{"from":244,"to":251}} {"id":100034114,"name":"newSingleObjectListerWatcher","signature":"func newSingleObjectListerWatcher(lw cache.ListerWatcher, objectName string) *singleObjListerWatcher","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_clusterid.go","code":"func newSingleObjectListerWatcher(lw cache.ListerWatcher, objectName string) *singleObjListerWatcher {\n\treturn \u0026singleObjListerWatcher{lw: lw, objectName: objectName}\n}","line":{"from":253,"to":255}} {"id":100034115,"name":"List","signature":"func (sow *singleObjListerWatcher) List(options metav1.ListOptions) (runtime.Object, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_clusterid.go","code":"func (sow *singleObjListerWatcher) List(options metav1.ListOptions) (runtime.Object, error) {\n\toptions.FieldSelector = \"metadata.name=\" + sow.objectName\n\treturn sow.lw.List(options)\n}","line":{"from":262,"to":265}} {"id":100034116,"name":"Watch","signature":"func (sow *singleObjListerWatcher) Watch(options metav1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_clusterid.go","code":"func (sow *singleObjListerWatcher) Watch(options metav1.ListOptions) (watch.Interface, error) {\n\toptions.FieldSelector = \"metadata.name=\" + sow.objectName\n\treturn sow.lw.Watch(options)\n}","line":{"from":267,"to":270}} {"id":100034117,"name":"newClustersMetricContext","signature":"func newClustersMetricContext(request, zone string) *metricContext","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_clusters.go","code":"func newClustersMetricContext(request, zone string) *metricContext {\n\treturn newGenericMetricContext(\"clusters\", request, unusedMetricLabel, zone, computeV1Version)\n}","line":{"from":30,"to":32}} {"id":100034118,"name":"ListClusters","signature":"func (g *Cloud) ListClusters(ctx context.Context) ([]string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_clusters.go","code":"// ListClusters will return a list of cluster names for the associated project\nfunc (g *Cloud) ListClusters(ctx context.Context) ([]string, error) {\n\tallClusters := []string{}\n\n\tfor _, zone := range g.managedZones {\n\t\tclusters, err := g.listClustersInZone(zone)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// TODO: Scoping? Do we need to qualify the cluster name?\n\t\tallClusters = append(allClusters, clusters...)\n\t}\n\n\treturn allClusters, nil\n}","line":{"from":34,"to":48}} {"id":100034119,"name":"GetManagedClusters","signature":"func (g *Cloud) GetManagedClusters(ctx context.Context) ([]*container.Cluster, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_clusters.go","code":"// GetManagedClusters will return the cluster objects associated to this project\nfunc (g *Cloud) GetManagedClusters(ctx context.Context) ([]*container.Cluster, error) {\n\tmanagedClusters := []*container.Cluster{}\n\n\tif g.regional {\n\t\tvar err error\n\t\tmanagedClusters, err = g.getClustersInLocation(g.region)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else if len(g.managedZones) \u003e= 1 {\n\t\tfor _, zone := range g.managedZones {\n\t\t\tclusters, err := g.getClustersInLocation(zone)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tmanagedClusters = append(managedClusters, clusters...)\n\t\t}\n\t} else {\n\t\treturn nil, fmt.Errorf(\"no zones associated with this cluster(%s)\", g.ProjectID())\n\t}\n\n\treturn managedClusters, nil\n}","line":{"from":50,"to":73}} {"id":100034120,"name":"Master","signature":"func (g *Cloud) Master(ctx context.Context, clusterName string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_clusters.go","code":"// Master returned the dns address of the master\nfunc (g *Cloud) Master(ctx context.Context, clusterName string) (string, error) {\n\treturn \"k8s-\" + clusterName + \"-master.internal\", nil\n}","line":{"from":75,"to":78}} {"id":100034121,"name":"listClustersInZone","signature":"func (g *Cloud) listClustersInZone(zone string) ([]string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_clusters.go","code":"func (g *Cloud) listClustersInZone(zone string) ([]string, error) {\n\tclusters, err := g.getClustersInLocation(zone)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := []string{}\n\tfor _, cluster := range clusters {\n\t\tresult = append(result, cluster.Name)\n\t}\n\treturn result, nil\n}","line":{"from":80,"to":91}} {"id":100034122,"name":"getClustersInLocation","signature":"func (g *Cloud) getClustersInLocation(zoneOrRegion string) ([]*container.Cluster, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_clusters.go","code":"func (g *Cloud) getClustersInLocation(zoneOrRegion string) ([]*container.Cluster, error) {\n\t// TODO: Issue/68913 migrate metric to list_location instead of list_zone.\n\tmc := newClustersMetricContext(\"list_zone\", zoneOrRegion)\n\t// TODO: use PageToken to list all not just the first 500\n\tlocation := getLocationName(g.projectID, zoneOrRegion)\n\tlist, err := g.containerService.Projects.Locations.Clusters.List(location).Do()\n\tif err != nil {\n\t\treturn nil, mc.Observe(err)\n\t}\n\tif list.Header.Get(\"nextPageToken\") != \"\" {\n\t\tklog.Errorf(\"Failed to get all clusters for request, received next page token %s\", list.Header.Get(\"nextPageToken\"))\n\t}\n\n\treturn list.Clusters, mc.Observe(nil)\n}","line":{"from":93,"to":107}} {"id":100034123,"name":"CreateDiskOnCloudProvider","signature":"func (manager *gceServiceManager) CreateDiskOnCloudProvider(","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"func (manager *gceServiceManager) CreateDiskOnCloudProvider(\n\tname string,\n\tsizeGb int64,\n\ttagsStr string,\n\tdiskType string,\n\tzone string) (*Disk, error) {\n\tdiskTypeURI, err := manager.getDiskTypeURI(\n\t\tmanager.gce.region /* diskRegion */, singleZone{zone}, diskType)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdiskToCreateV1 := \u0026compute.Disk{\n\t\tName: name,\n\t\tSizeGb: sizeGb,\n\t\tDescription: tagsStr,\n\t\tType: diskTypeURI,\n\t}\n\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\tdisk := \u0026Disk{\n\t\tZoneInfo: singleZone{zone},\n\t\tRegion: manager.gce.region,\n\t\tKind: diskKind,\n\t\tType: diskTypeURI,\n\t\tSizeGb: sizeGb,\n\t}\n\treturn disk, manager.gce.c.Disks().Insert(ctx, meta.ZonalKey(name, zone), diskToCreateV1)\n}","line":{"from":121,"to":150}} {"id":100034124,"name":"CreateRegionalDiskOnCloudProvider","signature":"func (manager *gceServiceManager) CreateRegionalDiskOnCloudProvider(","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"func (manager *gceServiceManager) CreateRegionalDiskOnCloudProvider(\n\tname string,\n\tsizeGb int64,\n\ttagsStr string,\n\tdiskType string,\n\treplicaZones sets.String) (*Disk, error) {\n\n\tdiskTypeURI, err := manager.getDiskTypeURI(\n\t\tmanager.gce.region /* diskRegion */, multiZone{replicaZones}, diskType)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfullyQualifiedReplicaZones := []string{}\n\tfor _, replicaZone := range replicaZones.UnsortedList() {\n\t\tfullyQualifiedReplicaZones = append(\n\t\t\tfullyQualifiedReplicaZones, manager.getReplicaZoneURI(replicaZone))\n\t}\n\n\tdiskToCreate := \u0026compute.Disk{\n\t\tName: name,\n\t\tSizeGb: sizeGb,\n\t\tDescription: tagsStr,\n\t\tType: diskTypeURI,\n\t\tReplicaZones: fullyQualifiedReplicaZones,\n\t}\n\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\tdisk := \u0026Disk{\n\t\tZoneInfo: multiZone{replicaZones},\n\t\tRegion: manager.gce.region,\n\t\tName: name,\n\t\tKind: diskKind,\n\t\tType: diskTypeURI,\n\t\tSizeGb: sizeGb,\n\t}\n\treturn disk, manager.gce.c.RegionDisks().Insert(ctx, meta.RegionalKey(name, manager.gce.region), diskToCreate)\n}","line":{"from":152,"to":189}} {"id":100034125,"name":"AttachDiskOnCloudProvider","signature":"func (manager *gceServiceManager) AttachDiskOnCloudProvider(","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"func (manager *gceServiceManager) AttachDiskOnCloudProvider(\n\tdisk *Disk,\n\treadWrite string,\n\tinstanceZone string,\n\tinstanceName string) error {\n\tsource, err := manager.getDiskSourceURI(disk)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tattachedDiskV1 := \u0026compute.AttachedDisk{\n\t\tDeviceName: disk.Name,\n\t\tKind: disk.Kind,\n\t\tMode: readWrite,\n\t\tSource: source,\n\t\tType: diskTypePersistent,\n\t}\n\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\treturn manager.gce.c.Instances().AttachDisk(ctx, meta.ZonalKey(instanceName, instanceZone), attachedDiskV1)\n}","line":{"from":191,"to":212}} {"id":100034126,"name":"DetachDiskOnCloudProvider","signature":"func (manager *gceServiceManager) DetachDiskOnCloudProvider(","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"func (manager *gceServiceManager) DetachDiskOnCloudProvider(\n\tinstanceZone string,\n\tinstanceName string,\n\tdevicePath string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\treturn manager.gce.c.Instances().DetachDisk(ctx, meta.ZonalKey(instanceName, instanceZone), devicePath)\n}","line":{"from":214,"to":221}} {"id":100034127,"name":"GetDiskFromCloudProvider","signature":"func (manager *gceServiceManager) GetDiskFromCloudProvider(","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"func (manager *gceServiceManager) GetDiskFromCloudProvider(\n\tzone string,\n\tdiskName string) (*Disk, error) {\n\tif zone == \"\" {\n\t\treturn nil, fmt.Errorf(\"can not fetch disk %q, zone is empty\", diskName)\n\t}\n\n\tif diskName == \"\" {\n\t\treturn nil, fmt.Errorf(\"can not fetch disk, zone is specified (%q), but disk name is empty\", zone)\n\t}\n\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\tdiskStable, err := manager.gce.c.Disks().Get(ctx, meta.ZonalKey(diskName, zone))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tzoneInfo := singleZone{strings.TrimSpace(lastComponent(diskStable.Zone))}\n\tif zoneInfo.zone == \"\" {\n\t\tzoneInfo = singleZone{zone}\n\t}\n\n\tregion, err := manager.getRegionFromZone(zoneInfo)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to extract region from zone for %q/%q err=%v\", zone, diskName, err)\n\t}\n\n\treturn \u0026Disk{\n\t\tZoneInfo: zoneInfo,\n\t\tRegion: region,\n\t\tName: diskStable.Name,\n\t\tKind: diskStable.Kind,\n\t\tType: diskStable.Type,\n\t\tSizeGb: diskStable.SizeGb,\n\t}, nil\n}","line":{"from":223,"to":259}} {"id":100034128,"name":"GetRegionalDiskFromCloudProvider","signature":"func (manager *gceServiceManager) GetRegionalDiskFromCloudProvider(","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"func (manager *gceServiceManager) GetRegionalDiskFromCloudProvider(\n\tdiskName string) (*Disk, error) {\n\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\tdiskBeta, err := manager.gce.c.RegionDisks().Get(ctx, meta.RegionalKey(diskName, manager.gce.region))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tzones := sets.NewString()\n\tfor _, zoneURI := range diskBeta.ReplicaZones {\n\t\tzones.Insert(lastComponent(zoneURI))\n\t}\n\n\treturn \u0026Disk{\n\t\tZoneInfo: multiZone{zones},\n\t\tRegion: lastComponent(diskBeta.Region),\n\t\tName: diskBeta.Name,\n\t\tKind: diskBeta.Kind,\n\t\tType: diskBeta.Type,\n\t\tSizeGb: diskBeta.SizeGb,\n\t}, nil\n}","line":{"from":261,"to":284}} {"id":100034129,"name":"DeleteDiskOnCloudProvider","signature":"func (manager *gceServiceManager) DeleteDiskOnCloudProvider(","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"func (manager *gceServiceManager) DeleteDiskOnCloudProvider(\n\tzone string,\n\tdiskName string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\treturn manager.gce.c.Disks().Delete(ctx, meta.ZonalKey(diskName, zone))\n}","line":{"from":286,"to":292}} {"id":100034130,"name":"DeleteRegionalDiskOnCloudProvider","signature":"func (manager *gceServiceManager) DeleteRegionalDiskOnCloudProvider(","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"func (manager *gceServiceManager) DeleteRegionalDiskOnCloudProvider(\n\tdiskName string) error {\n\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\treturn manager.gce.c.RegionDisks().Delete(ctx, meta.RegionalKey(diskName, manager.gce.region))\n}","line":{"from":294,"to":300}} {"id":100034131,"name":"getDiskSourceURI","signature":"func (manager *gceServiceManager) getDiskSourceURI(disk *Disk) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"func (manager *gceServiceManager) getDiskSourceURI(disk *Disk) (string, error) {\n\tgetProjectsAPIEndpoint := manager.getProjectsAPIEndpoint()\n\n\tswitch zoneInfo := disk.ZoneInfo.(type) {\n\tcase singleZone:\n\t\tif zoneInfo.zone == \"\" || disk.Region == \"\" {\n\t\t\t// Unexpected, but sanity-check\n\t\t\treturn \"\", fmt.Errorf(\"PD does not have zone/region information: %#v\", disk)\n\t\t}\n\n\t\treturn getProjectsAPIEndpoint + fmt.Sprintf(\n\t\t\tdiskSourceURITemplateSingleZone,\n\t\t\tmanager.gce.projectID,\n\t\t\tzoneInfo.zone,\n\t\t\tdisk.Name), nil\n\tcase multiZone:\n\t\tif zoneInfo.replicaZones == nil || zoneInfo.replicaZones.Len() \u003c= 0 {\n\t\t\t// Unexpected, but sanity-check\n\t\t\treturn \"\", fmt.Errorf(\"PD is regional but does not have any replicaZones specified: %v\", disk)\n\t\t}\n\t\treturn getProjectsAPIEndpoint + fmt.Sprintf(\n\t\t\tdiskSourceURITemplateRegional,\n\t\t\tmanager.gce.projectID,\n\t\t\tdisk.Region,\n\t\t\tdisk.Name), nil\n\tcase nil:\n\t\t// Unexpected, but sanity-check\n\t\treturn \"\", fmt.Errorf(\"PD did not have ZoneInfo: %v\", disk)\n\tdefault:\n\t\t// Unexpected, but sanity-check\n\t\treturn \"\", fmt.Errorf(\"disk.ZoneInfo has unexpected type %T\", zoneInfo)\n\t}\n}","line":{"from":302,"to":334}} {"id":100034132,"name":"getDiskTypeURI","signature":"func (manager *gceServiceManager) getDiskTypeURI(","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"func (manager *gceServiceManager) getDiskTypeURI(\n\tdiskRegion string, diskZoneInfo zoneType, diskType string) (string, error) {\n\n\tgetProjectsAPIEndpoint := manager.getProjectsAPIEndpoint()\n\n\tswitch zoneInfo := diskZoneInfo.(type) {\n\tcase singleZone:\n\t\tif zoneInfo.zone == \"\" {\n\t\t\treturn \"\", fmt.Errorf(\"zone is empty: %v\", zoneInfo)\n\t\t}\n\n\t\treturn getProjectsAPIEndpoint + fmt.Sprintf(\n\t\t\tdiskTypeURITemplateSingleZone,\n\t\t\tmanager.gce.projectID,\n\t\t\tzoneInfo.zone,\n\t\t\tdiskType), nil\n\tcase multiZone:\n\t\tif zoneInfo.replicaZones == nil || zoneInfo.replicaZones.Len() \u003c= 0 {\n\t\t\treturn \"\", fmt.Errorf(\"zoneInfo is regional but does not have any replicaZones specified: %v\", zoneInfo)\n\t\t}\n\t\treturn getProjectsAPIEndpoint + fmt.Sprintf(\n\t\t\tdiskTypeURITemplateRegional,\n\t\t\tmanager.gce.projectID,\n\t\t\tdiskRegion,\n\t\t\tdiskType), nil\n\tcase nil:\n\t\treturn \"\", fmt.Errorf(\"zoneInfo nil\")\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"zoneInfo has unexpected type %T\", zoneInfo)\n\t}\n}","line":{"from":336,"to":366}} {"id":100034133,"name":"getReplicaZoneURI","signature":"func (manager *gceServiceManager) getReplicaZoneURI(zone string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"func (manager *gceServiceManager) getReplicaZoneURI(zone string) string {\n\treturn manager.getProjectsAPIEndpoint() + fmt.Sprintf(\n\t\treplicaZoneURITemplateSingleZone,\n\t\tmanager.gce.projectID,\n\t\tzone)\n}","line":{"from":368,"to":373}} {"id":100034134,"name":"getRegionFromZone","signature":"func (manager *gceServiceManager) getRegionFromZone(zoneInfo zoneType) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"func (manager *gceServiceManager) getRegionFromZone(zoneInfo zoneType) (string, error) {\n\tvar zone string\n\tswitch zoneInfo := zoneInfo.(type) {\n\tcase singleZone:\n\t\tif zoneInfo.zone == \"\" {\n\t\t\t// Unexpected, but sanity-check\n\t\t\treturn \"\", fmt.Errorf(\"PD is single zone, but zone is not specified: %#v\", zoneInfo)\n\t\t}\n\n\t\tzone = zoneInfo.zone\n\tcase multiZone:\n\t\tif zoneInfo.replicaZones == nil || zoneInfo.replicaZones.Len() \u003c= 0 {\n\t\t\t// Unexpected, but sanity-check\n\t\t\treturn \"\", fmt.Errorf(\"PD is regional but does not have any replicaZones specified: %v\", zoneInfo)\n\t\t}\n\n\t\tzone = zoneInfo.replicaZones.UnsortedList()[0]\n\tcase nil:\n\t\t// Unexpected, but sanity-check\n\t\treturn \"\", fmt.Errorf(\"zoneInfo is nil\")\n\tdefault:\n\t\t// Unexpected, but sanity-check\n\t\treturn \"\", fmt.Errorf(\"zoneInfo has unexpected type %T\", zoneInfo)\n\t}\n\n\tregion, err := GetGCERegion(zone)\n\tif err != nil {\n\t\tklog.Warningf(\"failed to parse GCE region from zone %q: %v\", zone, err)\n\t\tregion = manager.gce.region\n\t}\n\n\treturn region, nil\n}","line":{"from":375,"to":407}} {"id":100034135,"name":"ResizeDiskOnCloudProvider","signature":"func (manager *gceServiceManager) ResizeDiskOnCloudProvider(disk *Disk, sizeGb int64, zone string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"func (manager *gceServiceManager) ResizeDiskOnCloudProvider(disk *Disk, sizeGb int64, zone string) error {\n\tresizeServiceRequest := \u0026compute.DisksResizeRequest{\n\t\tSizeGb: sizeGb,\n\t}\n\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\treturn manager.gce.c.Disks().Resize(ctx, meta.ZonalKey(disk.Name, zone), resizeServiceRequest)\n}","line":{"from":409,"to":417}} {"id":100034136,"name":"RegionalResizeDiskOnCloudProvider","signature":"func (manager *gceServiceManager) RegionalResizeDiskOnCloudProvider(disk *Disk, sizeGb int64) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"func (manager *gceServiceManager) RegionalResizeDiskOnCloudProvider(disk *Disk, sizeGb int64) error {\n\n\tresizeServiceRequest := \u0026compute.RegionDisksResizeRequest{\n\t\tSizeGb: sizeGb,\n\t}\n\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\treturn manager.gce.c.RegionDisks().Resize(ctx, meta.RegionalKey(disk.Name, disk.Region), resizeServiceRequest)\n}","line":{"from":419,"to":428}} {"id":100034137,"name":"isZoneType","signature":"func (m multiZone) isZoneType() {}","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"func (m multiZone) isZoneType() {}","line":{"from":499,"to":499}} {"id":100034138,"name":"isZoneType","signature":"func (s singleZone) isZoneType() {}","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"func (s singleZone) isZoneType() {}","line":{"from":500,"to":500}} {"id":100034139,"name":"newDiskMetricContextZonal","signature":"func newDiskMetricContextZonal(request, region, zone string) *metricContext","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"func newDiskMetricContextZonal(request, region, zone string) *metricContext {\n\treturn newGenericMetricContext(\"disk\", request, region, zone, computeV1Version)\n}","line":{"from":502,"to":504}} {"id":100034140,"name":"newDiskMetricContextRegional","signature":"func newDiskMetricContextRegional(request, region string) *metricContext","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"func newDiskMetricContextRegional(request, region string) *metricContext {\n\treturn newGenericMetricContext(\"disk\", request, region, unusedMetricLabel, computeV1Version)\n}","line":{"from":506,"to":508}} {"id":100034141,"name":"GetLabelsForVolume","signature":"func (g *Cloud) GetLabelsForVolume(ctx context.Context, pv *v1.PersistentVolume) (map[string]string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"// GetLabelsForVolume retrieved the label info for the provided volume\nfunc (g *Cloud) GetLabelsForVolume(ctx context.Context, pv *v1.PersistentVolume) (map[string]string, error) {\n\t// Ignore any volumes that are being provisioned\n\tif pv.Spec.GCEPersistentDisk.PDName == cloudvolume.ProvisionedVolumeName {\n\t\treturn nil, nil\n\t}\n\n\t// If the zone is already labeled, honor the hint\n\tname := pv.Spec.GCEPersistentDisk.PDName\n\tzone := pv.Labels[v1.LabelTopologyZone]\n\tif zone == \"\" {\n\t\tzone = pv.Labels[v1.LabelFailureDomainBetaZone]\n\t}\n\n\tdisk, err := g.getDiskByNameAndOptionalLabelZones(name, zone)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlabels, err := g.GetAutoLabelsForPD(disk)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn labels, nil\n}","line":{"from":510,"to":534}} {"id":100034142,"name":"getDiskByNameAndOptionalLabelZones","signature":"func (g *Cloud) getDiskByNameAndOptionalLabelZones(name, labelZone string) (*Disk, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"// getDiskByNameAndOptionalZone returns a Disk object for a disk (zonal or regional) for given name and (optional) zone(s) label.\nfunc (g *Cloud) getDiskByNameAndOptionalLabelZones(name, labelZone string) (*Disk, error) {\n\tif labelZone == \"\" {\n\t\treturn g.GetDiskByNameUnknownZone(name)\n\t}\n\tzoneSet, err := volumehelpers.LabelZonesToSet(labelZone)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(zoneSet) \u003e 1 {\n\t\t// Regional PD\n\t\treturn g.getRegionalDiskByName(name)\n\t}\n\treturn g.getDiskByName(name, labelZone)\n}","line":{"from":536,"to":550}} {"id":100034143,"name":"AttachDisk","signature":"func (g *Cloud) AttachDisk(diskName string, nodeName types.NodeName, readOnly bool, regional bool) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"// AttachDisk attaches given disk to the node with the specified NodeName.\n// Current instance is used when instanceID is empty string.\nfunc (g *Cloud) AttachDisk(diskName string, nodeName types.NodeName, readOnly bool, regional bool) error {\n\tinstanceName := mapNodeNameToInstanceName(nodeName)\n\tinstance, err := g.getInstanceByName(instanceName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting instance %q\", instanceName)\n\t}\n\n\t// Try fetching as regional PD\n\tvar disk *Disk\n\tvar mc *metricContext\n\tif regional {\n\t\tdisk, err = g.getRegionalDiskByName(diskName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmc = newDiskMetricContextRegional(\"attach\", g.region)\n\t} else {\n\t\tdisk, err = g.getDiskByName(diskName, instance.Zone)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmc = newDiskMetricContextZonal(\"attach\", g.region, instance.Zone)\n\t}\n\n\treadWrite := \"READ_WRITE\"\n\tif readOnly {\n\t\treadWrite = \"READ_ONLY\"\n\t}\n\n\treturn mc.Observe(g.manager.AttachDiskOnCloudProvider(disk, readWrite, instance.Zone, instance.Name))\n}","line":{"from":552,"to":584}} {"id":100034144,"name":"DetachDisk","signature":"func (g *Cloud) DetachDisk(devicePath string, nodeName types.NodeName) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"// DetachDisk detaches given disk to the node with the specified NodeName.\n// Current instance is used when nodeName is empty string.\nfunc (g *Cloud) DetachDisk(devicePath string, nodeName types.NodeName) error {\n\tinstanceName := mapNodeNameToInstanceName(nodeName)\n\tinst, err := g.getInstanceByName(instanceName)\n\tif err != nil {\n\t\tif err == cloudprovider.InstanceNotFound {\n\t\t\t// If instance no longer exists, safe to assume volume is not attached.\n\t\t\tklog.Warningf(\n\t\t\t\t\"Instance %q does not exist. DetachDisk will assume PD %q is not attached to it.\",\n\t\t\t\tinstanceName,\n\t\t\t\tdevicePath)\n\t\t\treturn nil\n\t\t}\n\n\t\treturn fmt.Errorf(\"error getting instance %q\", instanceName)\n\t}\n\n\tmc := newDiskMetricContextZonal(\"detach\", g.region, inst.Zone)\n\treturn mc.Observe(g.manager.DetachDiskOnCloudProvider(inst.Zone, inst.Name, devicePath))\n}","line":{"from":586,"to":606}} {"id":100034145,"name":"DiskIsAttached","signature":"func (g *Cloud) DiskIsAttached(diskName string, nodeName types.NodeName) (bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"// DiskIsAttached checks if a disk is attached to the node with the specified NodeName.\nfunc (g *Cloud) DiskIsAttached(diskName string, nodeName types.NodeName) (bool, error) {\n\tinstanceName := mapNodeNameToInstanceName(nodeName)\n\tinstance, err := g.getInstanceByName(instanceName)\n\tif err != nil {\n\t\tif err == cloudprovider.InstanceNotFound {\n\t\t\t// If instance no longer exists, safe to assume volume is not attached.\n\t\t\tklog.Warningf(\n\t\t\t\t\"Instance %q does not exist. DiskIsAttached will assume PD %q is not attached to it.\",\n\t\t\t\tinstanceName,\n\t\t\t\tdiskName)\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn false, err\n\t}\n\n\tfor _, disk := range instance.Disks {\n\t\tif disk.DeviceName == diskName {\n\t\t\t// Disk is still attached to node\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, nil\n}","line":{"from":608,"to":633}} {"id":100034146,"name":"DisksAreAttached","signature":"func (g *Cloud) DisksAreAttached(diskNames []string, nodeName types.NodeName) (map[string]bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"// DisksAreAttached is a batch function to check if a list of disks are attached\n// to the node with the specified NodeName.\nfunc (g *Cloud) DisksAreAttached(diskNames []string, nodeName types.NodeName) (map[string]bool, error) {\n\tattached := make(map[string]bool)\n\tfor _, diskName := range diskNames {\n\t\tattached[diskName] = false\n\t}\n\tinstanceName := mapNodeNameToInstanceName(nodeName)\n\tinstance, err := g.getInstanceByName(instanceName)\n\tif err != nil {\n\t\tif err == cloudprovider.InstanceNotFound {\n\t\t\t// If instance no longer exists, safe to assume volume is not attached.\n\t\t\tklog.Warningf(\n\t\t\t\t\"Instance %q does not exist. DisksAreAttached will assume PD %v are not attached to it.\",\n\t\t\t\tinstanceName,\n\t\t\t\tdiskNames)\n\t\t\treturn attached, nil\n\t\t}\n\n\t\treturn attached, err\n\t}\n\n\tfor _, instanceDisk := range instance.Disks {\n\t\tfor _, diskName := range diskNames {\n\t\t\tif instanceDisk.DeviceName == diskName {\n\t\t\t\t// Disk is still attached to node\n\t\t\t\tattached[diskName] = true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn attached, nil\n}","line":{"from":635,"to":667}} {"id":100034147,"name":"BulkDisksAreAttached","signature":"func (g *Cloud) BulkDisksAreAttached(diskByNodes map[types.NodeName][]string) (map[types.NodeName]map[string]bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"// BulkDisksAreAttached is a batch function to check if all corresponding disks are attached to the\n// nodes specified with nodeName.\nfunc (g *Cloud) BulkDisksAreAttached(diskByNodes map[types.NodeName][]string) (map[types.NodeName]map[string]bool, error) {\n\tinstanceNames := []string{}\n\tfor nodeName := range diskByNodes {\n\t\tinstanceNames = append(instanceNames, mapNodeNameToInstanceName(nodeName))\n\t}\n\n\t// List all instances with the given instance names\n\t// Then for each instance listed, add the disks attached to that instance to a map\n\tlistedInstances, err := g.getFoundInstanceByNames(instanceNames)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error listing instances: %v\", err)\n\t}\n\tlistedInstanceNamesToDisks := make(map[string][]*compute.AttachedDisk)\n\tfor _, instance := range listedInstances {\n\t\tlistedInstanceNamesToDisks[instance.Name] = instance.Disks\n\t}\n\n\tverifyDisksAttached := make(map[types.NodeName]map[string]bool)\n\n\t// For each node and its desired attached disks that needs to be verified\n\tfor nodeName, disksToVerify := range diskByNodes {\n\t\tinstanceName := canonicalizeInstanceName(mapNodeNameToInstanceName(nodeName))\n\t\tdisksActuallyAttached := listedInstanceNamesToDisks[instanceName]\n\t\tverifyDisksAttached[nodeName] = verifyDisksAttachedToNode(disksToVerify, disksActuallyAttached)\n\t}\n\n\treturn verifyDisksAttached, nil\n}","line":{"from":669,"to":698}} {"id":100034148,"name":"CreateDisk","signature":"func (g *Cloud) CreateDisk(","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"// CreateDisk creates a new Persistent Disk, with the specified name \u0026\n// size, in the specified zone. It stores specified tags encoded in\n// JSON in Description field.\nfunc (g *Cloud) CreateDisk(\n\tname string, diskType string, zone string, sizeGb int64, tags map[string]string) (*Disk, error) {\n\t// Do not allow creation of PDs in zones that are do not have nodes. Such PDs\n\t// are not currently usable.\n\tcurZones, err := g.GetAllCurrentZones()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !curZones.Has(zone) {\n\t\treturn nil, fmt.Errorf(\"kubernetes does not have a node in zone %q\", zone)\n\t}\n\n\ttagsStr, err := g.encodeDiskTags(tags)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdiskType, err = getDiskType(diskType)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmc := newDiskMetricContextZonal(\"create\", g.region, zone)\n\tdisk, err := g.manager.CreateDiskOnCloudProvider(\n\t\tname, sizeGb, tagsStr, diskType, zone)\n\n\tmc.Observe(err)\n\tif err != nil {\n\t\tif isGCEError(err, \"alreadyExists\") {\n\t\t\tklog.Warningf(\"GCE PD %q already exists, reusing\", name)\n\t\t\treturn g.manager.GetDiskFromCloudProvider(zone, name)\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn disk, nil\n}","line":{"from":700,"to":738}} {"id":100034149,"name":"CreateRegionalDisk","signature":"func (g *Cloud) CreateRegionalDisk(","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"// CreateRegionalDisk creates a new Regional Persistent Disk, with the specified\n// name \u0026 size, replicated to the specified zones. It stores specified tags\n// encoded in JSON in Description field.\nfunc (g *Cloud) CreateRegionalDisk(\n\tname string, diskType string, replicaZones sets.String, sizeGb int64, tags map[string]string) (*Disk, error) {\n\n\t// Do not allow creation of PDs in zones that are do not have nodes. Such PDs\n\t// are not currently usable. This functionality should be reverted to checking\n\t// against managed zones if we want users to be able to create RegionalDisks\n\t// in zones where there are no nodes\n\tcurZones, err := g.GetAllCurrentZones()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !curZones.IsSuperset(replicaZones) {\n\t\treturn nil, fmt.Errorf(\"kubernetes does not have nodes in specified zones: %q. Zones that contain nodes: %q\", replicaZones.Difference(curZones), curZones)\n\t}\n\n\ttagsStr, err := g.encodeDiskTags(tags)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdiskType, err = getDiskType(diskType)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmc := newDiskMetricContextRegional(\"create\", g.region)\n\n\tdisk, err := g.manager.CreateRegionalDiskOnCloudProvider(\n\t\tname, sizeGb, tagsStr, diskType, replicaZones)\n\n\tmc.Observe(err)\n\tif err != nil {\n\t\tif isGCEError(err, \"alreadyExists\") {\n\t\t\tklog.Warningf(\"GCE PD %q already exists, reusing\", name)\n\t\t\treturn g.manager.GetRegionalDiskFromCloudProvider(name)\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn disk, nil\n}","line":{"from":740,"to":782}} {"id":100034150,"name":"getDiskType","signature":"func getDiskType(diskType string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"func getDiskType(diskType string) (string, error) {\n\tswitch diskType {\n\tcase DiskTypeSSD, DiskTypeStandard:\n\t\treturn diskType, nil\n\tcase \"\":\n\t\treturn diskTypeDefault, nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"invalid GCE disk type %q\", diskType)\n\t}\n}","line":{"from":784,"to":793}} {"id":100034151,"name":"DeleteDisk","signature":"func (g *Cloud) DeleteDisk(diskToDelete string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"// DeleteDisk deletes rgw referenced persistent disk.\nfunc (g *Cloud) DeleteDisk(diskToDelete string) error {\n\terr := g.doDeleteDisk(diskToDelete)\n\tif isGCEError(err, \"resourceInUseByAnotherResource\") {\n\t\treturn volerr.NewDeletedVolumeInUseError(err.Error())\n\t}\n\n\tif err == cloudprovider.DiskNotFound {\n\t\treturn nil\n\t}\n\treturn err\n}","line":{"from":795,"to":806}} {"id":100034152,"name":"ResizeDisk","signature":"func (g *Cloud) ResizeDisk(diskToResize string, oldSize resource.Quantity, newSize resource.Quantity) (resource.Quantity, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"// ResizeDisk expands given disk and returns new disk size\nfunc (g *Cloud) ResizeDisk(diskToResize string, oldSize resource.Quantity, newSize resource.Quantity) (resource.Quantity, error) {\n\tdisk, err := g.GetDiskByNameUnknownZone(diskToResize)\n\tif err != nil {\n\t\treturn oldSize, err\n\t}\n\n\t// GCE resizes in chunks of GiBs\n\trequestGIB, err := volumehelpers.RoundUpToGiB(newSize)\n\tif err != nil {\n\t\treturn oldSize, err\n\t}\n\n\tnewSizeQuant := resource.MustParse(fmt.Sprintf(\"%dGi\", requestGIB))\n\n\t// If disk is already of size equal or greater than requested size, we simply return\n\tif disk.SizeGb \u003e= requestGIB {\n\t\treturn newSizeQuant, nil\n\t}\n\n\tvar mc *metricContext\n\n\tswitch zoneInfo := disk.ZoneInfo.(type) {\n\tcase singleZone:\n\t\tmc = newDiskMetricContextZonal(\"resize\", disk.Region, zoneInfo.zone)\n\t\terr := g.manager.ResizeDiskOnCloudProvider(disk, requestGIB, zoneInfo.zone)\n\n\t\tif err != nil {\n\t\t\treturn oldSize, mc.Observe(err)\n\t\t}\n\t\treturn newSizeQuant, mc.Observe(err)\n\tcase multiZone:\n\t\tmc = newDiskMetricContextRegional(\"resize\", disk.Region)\n\t\terr := g.manager.RegionalResizeDiskOnCloudProvider(disk, requestGIB)\n\n\t\tif err != nil {\n\t\t\treturn oldSize, mc.Observe(err)\n\t\t}\n\t\treturn newSizeQuant, mc.Observe(err)\n\tcase nil:\n\t\treturn oldSize, fmt.Errorf(\"PD has nil ZoneInfo: %v\", disk)\n\tdefault:\n\t\treturn oldSize, fmt.Errorf(\"disk.ZoneInfo has unexpected type %T\", zoneInfo)\n\t}\n}","line":{"from":808,"to":852}} {"id":100034153,"name":"GetAutoLabelsForPD","signature":"func (g *Cloud) GetAutoLabelsForPD(disk *Disk) (map[string]string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"// GetAutoLabelsForPD builds the labels that should be automatically added to a PersistentVolume backed by a GCE PD\n// Specifically, this builds Topology (zone) and Region labels.\n// The PersistentVolumeLabel admission controller calls this and adds the labels when a PV is created.\nfunc (g *Cloud) GetAutoLabelsForPD(disk *Disk) (map[string]string, error) {\n\tlabels := make(map[string]string)\n\tswitch zoneInfo := disk.ZoneInfo.(type) {\n\tcase singleZone:\n\t\tif zoneInfo.zone == \"\" || disk.Region == \"\" {\n\t\t\t// Unexpected, but sanity-check\n\t\t\treturn nil, fmt.Errorf(\"PD did not have zone/region information: %v\", disk)\n\t\t}\n\t\tlabels[v1.LabelTopologyZone] = zoneInfo.zone\n\t\tlabels[v1.LabelTopologyRegion] = disk.Region\n\tcase multiZone:\n\t\tif zoneInfo.replicaZones == nil || zoneInfo.replicaZones.Len() \u003c= 0 {\n\t\t\t// Unexpected, but sanity-check\n\t\t\treturn nil, fmt.Errorf(\"PD is regional but does not have any replicaZones specified: %v\", disk)\n\t\t}\n\t\tlabels[v1.LabelTopologyZone] =\n\t\t\tvolumehelpers.ZonesSetToLabelValue(zoneInfo.replicaZones)\n\t\tlabels[v1.LabelTopologyRegion] = disk.Region\n\tcase nil:\n\t\t// Unexpected, but sanity-check\n\t\treturn nil, fmt.Errorf(\"PD did not have ZoneInfo: %v\", disk)\n\tdefault:\n\t\t// Unexpected, but sanity-check\n\t\treturn nil, fmt.Errorf(\"disk.ZoneInfo has unexpected type %T\", zoneInfo)\n\t}\n\n\treturn labels, nil\n}","line":{"from":854,"to":884}} {"id":100034154,"name":"findDiskByName","signature":"func (g *Cloud) findDiskByName(diskName string, zone string) (*Disk, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"// Returns a Disk for the disk, if it is found in the specified zone.\n// If not found, returns (nil, nil)\nfunc (g *Cloud) findDiskByName(diskName string, zone string) (*Disk, error) {\n\tmc := newDiskMetricContextZonal(\"get\", g.region, zone)\n\tdisk, err := g.manager.GetDiskFromCloudProvider(zone, diskName)\n\tif err == nil {\n\t\treturn disk, mc.Observe(nil)\n\t}\n\tif !isHTTPErrorCode(err, http.StatusNotFound) {\n\t\treturn nil, mc.Observe(err)\n\t}\n\treturn nil, mc.Observe(nil)\n}","line":{"from":886,"to":898}} {"id":100034155,"name":"getDiskByName","signature":"func (g *Cloud) getDiskByName(diskName string, zone string) (*Disk, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"// Like findDiskByName, but returns an error if the disk is not found\nfunc (g *Cloud) getDiskByName(diskName string, zone string) (*Disk, error) {\n\tdisk, err := g.findDiskByName(diskName, zone)\n\tif disk == nil \u0026\u0026 err == nil {\n\t\treturn nil, fmt.Errorf(\"GCE persistent disk not found: diskName=%q zone=%q\", diskName, zone)\n\t}\n\treturn disk, err\n}","line":{"from":900,"to":907}} {"id":100034156,"name":"findRegionalDiskByName","signature":"func (g *Cloud) findRegionalDiskByName(diskName string) (*Disk, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"// Returns a Disk for the regional disk, if it is found.\n// If not found, returns (nil, nil)\nfunc (g *Cloud) findRegionalDiskByName(diskName string) (*Disk, error) {\n\tmc := newDiskMetricContextRegional(\"get\", g.region)\n\tdisk, err := g.manager.GetRegionalDiskFromCloudProvider(diskName)\n\tif err == nil {\n\t\treturn disk, mc.Observe(nil)\n\t}\n\tif !isHTTPErrorCode(err, http.StatusNotFound) {\n\t\treturn nil, mc.Observe(err)\n\t}\n\treturn nil, mc.Observe(nil)\n}","line":{"from":909,"to":921}} {"id":100034157,"name":"getRegionalDiskByName","signature":"func (g *Cloud) getRegionalDiskByName(diskName string) (*Disk, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"// Like findRegionalDiskByName, but returns an error if the disk is not found\nfunc (g *Cloud) getRegionalDiskByName(diskName string) (*Disk, error) {\n\tdisk, err := g.findRegionalDiskByName(diskName)\n\tif disk == nil \u0026\u0026 err == nil {\n\t\treturn nil, fmt.Errorf(\"GCE regional persistent disk not found: diskName=%q\", diskName)\n\t}\n\treturn disk, err\n}","line":{"from":923,"to":930}} {"id":100034158,"name":"GetDiskByNameUnknownZone","signature":"func (g *Cloud) GetDiskByNameUnknownZone(diskName string) (*Disk, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"// GetDiskByNameUnknownZone scans all managed zones to return the GCE PD\n// Prefer getDiskByName, if the zone can be established\n// Return cloudprovider.DiskNotFound if the given disk cannot be found in any zone\nfunc (g *Cloud) GetDiskByNameUnknownZone(diskName string) (*Disk, error) {\n\tregionalDisk, err := g.getRegionalDiskByName(diskName)\n\tif err == nil {\n\t\treturn regionalDisk, err\n\t}\n\n\t// Note: this is the gotcha right now with GCE PD support:\n\t// disk names are not unique per-region.\n\t// (I can create two volumes with name \"myvol\" in e.g. us-central1-b \u0026 us-central1-f)\n\t// For now, this is simply undefined behaviour.\n\t//\n\t// In future, we will have to require users to qualify their disk\n\t// \"us-central1-a/mydisk\". We could do this for them as part of\n\t// admission control, but that might be a little weird (values changing\n\t// on create)\n\n\tvar found *Disk\n\tfor _, zone := range g.managedZones {\n\t\tdisk, err := g.findDiskByName(diskName, zone)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// findDiskByName returns (nil,nil) if the disk doesn't exist, so we can't\n\t\t// assume that a disk was found unless disk is non-nil.\n\t\tif disk == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif found != nil {\n\t\t\tswitch zoneInfo := disk.ZoneInfo.(type) {\n\t\t\tcase multiZone:\n\t\t\t\tif zoneInfo.replicaZones.Has(zone) {\n\t\t\t\t\tklog.Warningf(\"GCE PD name (%q) was found in multiple zones (%q), but ok because it is a RegionalDisk.\",\n\t\t\t\t\t\tdiskName, zoneInfo.replicaZones)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\treturn nil, fmt.Errorf(\"GCE PD name was found in multiple zones: %q\", diskName)\n\t\t\tdefault:\n\t\t\t\treturn nil, fmt.Errorf(\"GCE PD name was found in multiple zones: %q\", diskName)\n\t\t\t}\n\t\t}\n\t\tfound = disk\n\t}\n\tif found != nil {\n\t\treturn found, nil\n\t}\n\tklog.Warningf(\"GCE persistent disk %q not found in managed zones (%s)\",\n\t\tdiskName, strings.Join(g.managedZones, \",\"))\n\n\treturn nil, cloudprovider.DiskNotFound\n}","line":{"from":932,"to":984}} {"id":100034159,"name":"encodeDiskTags","signature":"func (g *Cloud) encodeDiskTags(tags map[string]string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"// encodeDiskTags encodes requested volume tags into JSON string, as GCE does\n// not support tags on GCE PDs and we use Description field as fallback.\nfunc (g *Cloud) encodeDiskTags(tags map[string]string) (string, error) {\n\tif len(tags) == 0 {\n\t\t// No tags -\u003e empty JSON\n\t\treturn \"\", nil\n\t}\n\n\tenc, err := json.Marshal(tags)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(enc), nil\n}","line":{"from":986,"to":999}} {"id":100034160,"name":"doDeleteDisk","signature":"func (g *Cloud) doDeleteDisk(diskToDelete string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"func (g *Cloud) doDeleteDisk(diskToDelete string) error {\n\tdisk, err := g.GetDiskByNameUnknownZone(diskToDelete)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar mc *metricContext\n\n\tswitch zoneInfo := disk.ZoneInfo.(type) {\n\tcase singleZone:\n\t\tmc = newDiskMetricContextZonal(\"delete\", disk.Region, zoneInfo.zone)\n\t\treturn mc.Observe(g.manager.DeleteDiskOnCloudProvider(zoneInfo.zone, disk.Name))\n\tcase multiZone:\n\t\tmc = newDiskMetricContextRegional(\"delete\", disk.Region)\n\t\treturn mc.Observe(g.manager.DeleteRegionalDiskOnCloudProvider(disk.Name))\n\tcase nil:\n\t\treturn fmt.Errorf(\"PD has nil ZoneInfo: %v\", disk)\n\tdefault:\n\t\treturn fmt.Errorf(\"disk.ZoneInfo has unexpected type %T\", zoneInfo)\n\t}\n}","line":{"from":1001,"to":1021}} {"id":100034161,"name":"isGCEError","signature":"func isGCEError(err error, reason string) bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"// isGCEError returns true if given error is a googleapi.Error with given\n// reason (e.g. \"resourceInUseByAnotherResource\")\nfunc isGCEError(err error, reason string) bool {\n\tapiErr, ok := err.(*googleapi.Error)\n\tif !ok {\n\t\treturn false\n\t}\n\n\tfor _, e := range apiErr.Errors {\n\t\tif e.Reason == reason {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":1023,"to":1037}} {"id":100034162,"name":"verifyDisksAttachedToNode","signature":"func verifyDisksAttachedToNode(disksToVerify []string, disksActuallyAttached []*compute.AttachedDisk) map[string]bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_disks.go","code":"// verifyDisksAttachedToNode takes in an slice of disks that should be attached to an instance, and the\n// slice of disks actually attached to it. It returns a map verifying if the disks are actually attached.\nfunc verifyDisksAttachedToNode(disksToVerify []string, disksActuallyAttached []*compute.AttachedDisk) map[string]bool {\n\tverifiedDisks := make(map[string]bool)\n\tdiskNamesActuallyAttached := sets.NewString()\n\tfor _, disk := range disksActuallyAttached {\n\t\tdiskNamesActuallyAttached.Insert(disk.DeviceName)\n\t}\n\n\t// For every disk that's supposed to be attached, verify that it is\n\tfor _, diskName := range disksToVerify {\n\t\tverifiedDisks[diskName] = diskNamesActuallyAttached.Has(diskName)\n\t}\n\n\treturn verifiedDisks\n}","line":{"from":1039,"to":1054}} {"id":100034163,"name":"newFirewallMetricContext","signature":"func newFirewallMetricContext(request string) *metricContext","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_firewall.go","code":"func newFirewallMetricContext(request string) *metricContext {\n\treturn newGenericMetricContext(\"firewall\", request, unusedMetricLabel, unusedMetricLabel, computeV1Version)\n}","line":{"from":29,"to":31}} {"id":100034164,"name":"GetFirewall","signature":"func (g *Cloud) GetFirewall(name string) (*compute.Firewall, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_firewall.go","code":"// GetFirewall returns the Firewall by name.\nfunc (g *Cloud) GetFirewall(name string) (*compute.Firewall, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newFirewallMetricContext(\"get\")\n\tv, err := g.c.Firewalls().Get(ctx, meta.GlobalKey(name))\n\treturn v, mc.Observe(err)\n}","line":{"from":33,"to":41}} {"id":100034165,"name":"CreateFirewall","signature":"func (g *Cloud) CreateFirewall(f *compute.Firewall) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_firewall.go","code":"// CreateFirewall creates the passed firewall\nfunc (g *Cloud) CreateFirewall(f *compute.Firewall) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newFirewallMetricContext(\"create\")\n\treturn mc.Observe(g.c.Firewalls().Insert(ctx, meta.GlobalKey(f.Name), f))\n}","line":{"from":43,"to":50}} {"id":100034166,"name":"DeleteFirewall","signature":"func (g *Cloud) DeleteFirewall(name string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_firewall.go","code":"// DeleteFirewall deletes the given firewall rule.\nfunc (g *Cloud) DeleteFirewall(name string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newFirewallMetricContext(\"delete\")\n\treturn mc.Observe(g.c.Firewalls().Delete(ctx, meta.GlobalKey(name)))\n}","line":{"from":52,"to":59}} {"id":100034167,"name":"UpdateFirewall","signature":"func (g *Cloud) UpdateFirewall(f *compute.Firewall) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_firewall.go","code":"// UpdateFirewall applies the given firewall as an update to an existing service.\nfunc (g *Cloud) UpdateFirewall(f *compute.Firewall) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newFirewallMetricContext(\"update\")\n\treturn mc.Observe(g.c.Firewalls().Update(ctx, meta.GlobalKey(f.Name), f))\n}","line":{"from":61,"to":68}} {"id":100034168,"name":"PatchFirewall","signature":"func (g *Cloud) PatchFirewall(f *compute.Firewall) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_firewall.go","code":"// PatchFirewall applies the given firewall as an update to an existing service.\nfunc (g *Cloud) PatchFirewall(f *compute.Firewall) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newFirewallMetricContext(\"Patch\")\n\treturn mc.Observe(g.c.Firewalls().Patch(ctx, meta.GlobalKey(f.Name), f))\n}","line":{"from":70,"to":77}} {"id":100034169,"name":"newForwardingRuleMetricContext","signature":"func newForwardingRuleMetricContext(request, region string) *metricContext","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_forwardingrule.go","code":"func newForwardingRuleMetricContext(request, region string) *metricContext {\n\treturn newForwardingRuleMetricContextWithVersion(request, region, computeV1Version)\n}","line":{"from":31,"to":33}} {"id":100034170,"name":"newForwardingRuleMetricContextWithVersion","signature":"func newForwardingRuleMetricContextWithVersion(request, region, version string) *metricContext","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_forwardingrule.go","code":"func newForwardingRuleMetricContextWithVersion(request, region, version string) *metricContext {\n\treturn newGenericMetricContext(\"forwardingrule\", request, region, unusedMetricLabel, version)\n}","line":{"from":34,"to":36}} {"id":100034171,"name":"CreateGlobalForwardingRule","signature":"func (g *Cloud) CreateGlobalForwardingRule(rule *compute.ForwardingRule) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_forwardingrule.go","code":"// CreateGlobalForwardingRule creates the passed GlobalForwardingRule\nfunc (g *Cloud) CreateGlobalForwardingRule(rule *compute.ForwardingRule) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newForwardingRuleMetricContext(\"create\", \"\")\n\treturn mc.Observe(g.c.GlobalForwardingRules().Insert(ctx, meta.GlobalKey(rule.Name), rule))\n}","line":{"from":38,"to":45}} {"id":100034172,"name":"SetProxyForGlobalForwardingRule","signature":"func (g *Cloud) SetProxyForGlobalForwardingRule(forwardingRuleName, targetProxyLink string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_forwardingrule.go","code":"// SetProxyForGlobalForwardingRule links the given TargetHttp(s)Proxy with the given GlobalForwardingRule.\n// targetProxyLink is the SelfLink of a TargetHttp(s)Proxy.\nfunc (g *Cloud) SetProxyForGlobalForwardingRule(forwardingRuleName, targetProxyLink string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newForwardingRuleMetricContext(\"set_proxy\", \"\")\n\ttarget := \u0026compute.TargetReference{Target: targetProxyLink}\n\treturn mc.Observe(g.c.GlobalForwardingRules().SetTarget(ctx, meta.GlobalKey(forwardingRuleName), target))\n}","line":{"from":47,"to":56}} {"id":100034173,"name":"DeleteGlobalForwardingRule","signature":"func (g *Cloud) DeleteGlobalForwardingRule(name string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_forwardingrule.go","code":"// DeleteGlobalForwardingRule deletes the GlobalForwardingRule by name.\nfunc (g *Cloud) DeleteGlobalForwardingRule(name string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newForwardingRuleMetricContext(\"delete\", \"\")\n\treturn mc.Observe(g.c.GlobalForwardingRules().Delete(ctx, meta.GlobalKey(name)))\n}","line":{"from":58,"to":65}} {"id":100034174,"name":"GetGlobalForwardingRule","signature":"func (g *Cloud) GetGlobalForwardingRule(name string) (*compute.ForwardingRule, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_forwardingrule.go","code":"// GetGlobalForwardingRule returns the GlobalForwardingRule by name.\nfunc (g *Cloud) GetGlobalForwardingRule(name string) (*compute.ForwardingRule, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newForwardingRuleMetricContext(\"get\", \"\")\n\tv, err := g.c.GlobalForwardingRules().Get(ctx, meta.GlobalKey(name))\n\treturn v, mc.Observe(err)\n}","line":{"from":67,"to":75}} {"id":100034175,"name":"ListGlobalForwardingRules","signature":"func (g *Cloud) ListGlobalForwardingRules() ([]*compute.ForwardingRule, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_forwardingrule.go","code":"// ListGlobalForwardingRules lists all GlobalForwardingRules in the project.\nfunc (g *Cloud) ListGlobalForwardingRules() ([]*compute.ForwardingRule, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newForwardingRuleMetricContext(\"list\", \"\")\n\tv, err := g.c.GlobalForwardingRules().List(ctx, filter.None)\n\treturn v, mc.Observe(err)\n}","line":{"from":77,"to":85}} {"id":100034176,"name":"GetRegionForwardingRule","signature":"func (g *Cloud) GetRegionForwardingRule(name, region string) (*compute.ForwardingRule, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_forwardingrule.go","code":"// GetRegionForwardingRule returns the RegionalForwardingRule by name \u0026 region.\nfunc (g *Cloud) GetRegionForwardingRule(name, region string) (*compute.ForwardingRule, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newForwardingRuleMetricContext(\"get\", region)\n\tv, err := g.c.ForwardingRules().Get(ctx, meta.RegionalKey(name, region))\n\treturn v, mc.Observe(err)\n}","line":{"from":87,"to":95}} {"id":100034177,"name":"GetAlphaRegionForwardingRule","signature":"func (g *Cloud) GetAlphaRegionForwardingRule(name, region string) (*computealpha.ForwardingRule, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_forwardingrule.go","code":"// GetAlphaRegionForwardingRule returns the Alpha forwarding rule by name \u0026 region.\nfunc (g *Cloud) GetAlphaRegionForwardingRule(name, region string) (*computealpha.ForwardingRule, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newForwardingRuleMetricContextWithVersion(\"get\", region, computeAlphaVersion)\n\tv, err := g.c.AlphaForwardingRules().Get(ctx, meta.RegionalKey(name, region))\n\treturn v, mc.Observe(err)\n}","line":{"from":97,"to":105}} {"id":100034178,"name":"GetBetaRegionForwardingRule","signature":"func (g *Cloud) GetBetaRegionForwardingRule(name, region string) (*computebeta.ForwardingRule, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_forwardingrule.go","code":"// GetBetaRegionForwardingRule returns the Beta forwarding rule by name \u0026 region.\nfunc (g *Cloud) GetBetaRegionForwardingRule(name, region string) (*computebeta.ForwardingRule, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newForwardingRuleMetricContextWithVersion(\"get\", region, computeBetaVersion)\n\tv, err := g.c.BetaForwardingRules().Get(ctx, meta.RegionalKey(name, region))\n\treturn v, mc.Observe(err)\n}","line":{"from":107,"to":115}} {"id":100034179,"name":"ListRegionForwardingRules","signature":"func (g *Cloud) ListRegionForwardingRules(region string) ([]*compute.ForwardingRule, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_forwardingrule.go","code":"// ListRegionForwardingRules lists all RegionalForwardingRules in the project \u0026 region.\nfunc (g *Cloud) ListRegionForwardingRules(region string) ([]*compute.ForwardingRule, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newForwardingRuleMetricContext(\"list\", region)\n\tv, err := g.c.ForwardingRules().List(ctx, region, filter.None)\n\treturn v, mc.Observe(err)\n}","line":{"from":117,"to":125}} {"id":100034180,"name":"ListAlphaRegionForwardingRules","signature":"func (g *Cloud) ListAlphaRegionForwardingRules(region string) ([]*computealpha.ForwardingRule, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_forwardingrule.go","code":"// ListAlphaRegionForwardingRules lists all RegionalForwardingRules in the project \u0026 region.\nfunc (g *Cloud) ListAlphaRegionForwardingRules(region string) ([]*computealpha.ForwardingRule, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newForwardingRuleMetricContextWithVersion(\"list\", region, computeAlphaVersion)\n\tv, err := g.c.AlphaForwardingRules().List(ctx, region, filter.None)\n\treturn v, mc.Observe(err)\n}","line":{"from":127,"to":135}} {"id":100034181,"name":"ListBetaRegionForwardingRules","signature":"func (g *Cloud) ListBetaRegionForwardingRules(region string) ([]*computebeta.ForwardingRule, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_forwardingrule.go","code":"// ListBetaRegionForwardingRules lists all RegionalForwardingRules in the project \u0026 region.\nfunc (g *Cloud) ListBetaRegionForwardingRules(region string) ([]*computebeta.ForwardingRule, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newForwardingRuleMetricContextWithVersion(\"list\", region, computeBetaVersion)\n\tv, err := g.c.BetaForwardingRules().List(ctx, region, filter.None)\n\treturn v, mc.Observe(err)\n}","line":{"from":137,"to":145}} {"id":100034182,"name":"CreateRegionForwardingRule","signature":"func (g *Cloud) CreateRegionForwardingRule(rule *compute.ForwardingRule, region string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_forwardingrule.go","code":"// CreateRegionForwardingRule creates and returns a\n// RegionalForwardingRule that points to the given BackendService\nfunc (g *Cloud) CreateRegionForwardingRule(rule *compute.ForwardingRule, region string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newForwardingRuleMetricContext(\"create\", region)\n\treturn mc.Observe(g.c.ForwardingRules().Insert(ctx, meta.RegionalKey(rule.Name, region), rule))\n}","line":{"from":147,"to":155}} {"id":100034183,"name":"CreateAlphaRegionForwardingRule","signature":"func (g *Cloud) CreateAlphaRegionForwardingRule(rule *computealpha.ForwardingRule, region string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_forwardingrule.go","code":"// CreateAlphaRegionForwardingRule creates and returns an Alpha\n// forwarding rule in the given region.\nfunc (g *Cloud) CreateAlphaRegionForwardingRule(rule *computealpha.ForwardingRule, region string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newForwardingRuleMetricContextWithVersion(\"create\", region, computeAlphaVersion)\n\treturn mc.Observe(g.c.AlphaForwardingRules().Insert(ctx, meta.RegionalKey(rule.Name, region), rule))\n}","line":{"from":157,"to":165}} {"id":100034184,"name":"CreateBetaRegionForwardingRule","signature":"func (g *Cloud) CreateBetaRegionForwardingRule(rule *computebeta.ForwardingRule, region string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_forwardingrule.go","code":"// CreateBetaRegionForwardingRule creates and returns a Beta\n// forwarding rule in the given region.\nfunc (g *Cloud) CreateBetaRegionForwardingRule(rule *computebeta.ForwardingRule, region string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newForwardingRuleMetricContextWithVersion(\"create\", region, computeBetaVersion)\n\treturn mc.Observe(g.c.BetaForwardingRules().Insert(ctx, meta.RegionalKey(rule.Name, region), rule))\n}","line":{"from":167,"to":175}} {"id":100034185,"name":"DeleteRegionForwardingRule","signature":"func (g *Cloud) DeleteRegionForwardingRule(name, region string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_forwardingrule.go","code":"// DeleteRegionForwardingRule deletes the RegionalForwardingRule by name \u0026 region.\nfunc (g *Cloud) DeleteRegionForwardingRule(name, region string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newForwardingRuleMetricContext(\"delete\", region)\n\treturn mc.Observe(g.c.ForwardingRules().Delete(ctx, meta.RegionalKey(name, region)))\n}","line":{"from":177,"to":184}} {"id":100034186,"name":"getNetworkTierFromForwardingRule","signature":"func (g *Cloud) getNetworkTierFromForwardingRule(name, region string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_forwardingrule.go","code":"func (g *Cloud) getNetworkTierFromForwardingRule(name, region string) (string, error) {\n\tfwdRule, err := g.GetRegionForwardingRule(name, region)\n\tif err != nil {\n\t\t// Can't get the network tier, just return an error.\n\t\treturn \"\", err\n\t}\n\treturn fwdRule.NetworkTier, nil\n}","line":{"from":186,"to":193}} {"id":100034187,"name":"init","signature":"func init()","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"func init() {\n\tif v, err := utilversion.ParseGeneric(\"1.7.2\"); err != nil {\n\t\tklog.Fatalf(\"Failed to parse version for minNodesHealthCheckVersion: %v\", err)\n\t} else {\n\t\tminNodesHealthCheckVersion = v\n\t}\n}","line":{"from":49,"to":55}} {"id":100034188,"name":"newHealthcheckMetricContext","signature":"func newHealthcheckMetricContext(request string) *metricContext","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"func newHealthcheckMetricContext(request string) *metricContext {\n\treturn newHealthcheckMetricContextWithVersion(request, computeV1Version)\n}","line":{"from":57,"to":59}} {"id":100034189,"name":"newHealthcheckMetricContextWithVersion","signature":"func newHealthcheckMetricContextWithVersion(request, version string) *metricContext","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"func newHealthcheckMetricContextWithVersion(request, version string) *metricContext {\n\treturn newGenericMetricContext(\"healthcheck\", request, unusedMetricLabel, unusedMetricLabel, version)\n}","line":{"from":61,"to":63}} {"id":100034190,"name":"GetHTTPHealthCheck","signature":"func (g *Cloud) GetHTTPHealthCheck(name string) (*compute.HttpHealthCheck, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"// GetHTTPHealthCheck returns the given HttpHealthCheck by name.\nfunc (g *Cloud) GetHTTPHealthCheck(name string) (*compute.HttpHealthCheck, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newHealthcheckMetricContext(\"get_legacy\")\n\tv, err := g.c.HttpHealthChecks().Get(ctx, meta.GlobalKey(name))\n\treturn v, mc.Observe(err)\n}","line":{"from":65,"to":73}} {"id":100034191,"name":"UpdateHTTPHealthCheck","signature":"func (g *Cloud) UpdateHTTPHealthCheck(hc *compute.HttpHealthCheck) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"// UpdateHTTPHealthCheck applies the given HttpHealthCheck as an update.\nfunc (g *Cloud) UpdateHTTPHealthCheck(hc *compute.HttpHealthCheck) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newHealthcheckMetricContext(\"update_legacy\")\n\treturn mc.Observe(g.c.HttpHealthChecks().Update(ctx, meta.GlobalKey(hc.Name), hc))\n}","line":{"from":75,"to":82}} {"id":100034192,"name":"DeleteHTTPHealthCheck","signature":"func (g *Cloud) DeleteHTTPHealthCheck(name string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"// DeleteHTTPHealthCheck deletes the given HttpHealthCheck by name.\nfunc (g *Cloud) DeleteHTTPHealthCheck(name string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newHealthcheckMetricContext(\"delete_legacy\")\n\treturn mc.Observe(g.c.HttpHealthChecks().Delete(ctx, meta.GlobalKey(name)))\n}","line":{"from":84,"to":91}} {"id":100034193,"name":"CreateHTTPHealthCheck","signature":"func (g *Cloud) CreateHTTPHealthCheck(hc *compute.HttpHealthCheck) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"// CreateHTTPHealthCheck creates the given HttpHealthCheck.\nfunc (g *Cloud) CreateHTTPHealthCheck(hc *compute.HttpHealthCheck) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newHealthcheckMetricContext(\"create_legacy\")\n\treturn mc.Observe(g.c.HttpHealthChecks().Insert(ctx, meta.GlobalKey(hc.Name), hc))\n}","line":{"from":93,"to":100}} {"id":100034194,"name":"ListHTTPHealthChecks","signature":"func (g *Cloud) ListHTTPHealthChecks() ([]*compute.HttpHealthCheck, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"// ListHTTPHealthChecks lists all HttpHealthChecks in the project.\nfunc (g *Cloud) ListHTTPHealthChecks() ([]*compute.HttpHealthCheck, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newHealthcheckMetricContext(\"list_legacy\")\n\tv, err := g.c.HttpHealthChecks().List(ctx, filter.None)\n\treturn v, mc.Observe(err)\n}","line":{"from":102,"to":110}} {"id":100034195,"name":"GetHTTPSHealthCheck","signature":"func (g *Cloud) GetHTTPSHealthCheck(name string) (*compute.HttpsHealthCheck, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"// GetHTTPSHealthCheck returns the given HttpsHealthCheck by name.\nfunc (g *Cloud) GetHTTPSHealthCheck(name string) (*compute.HttpsHealthCheck, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newHealthcheckMetricContext(\"get_legacy\")\n\tv, err := g.c.HttpsHealthChecks().Get(ctx, meta.GlobalKey(name))\n\treturn v, mc.Observe(err)\n}","line":{"from":114,"to":122}} {"id":100034196,"name":"UpdateHTTPSHealthCheck","signature":"func (g *Cloud) UpdateHTTPSHealthCheck(hc *compute.HttpsHealthCheck) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"// UpdateHTTPSHealthCheck applies the given HttpsHealthCheck as an update.\nfunc (g *Cloud) UpdateHTTPSHealthCheck(hc *compute.HttpsHealthCheck) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newHealthcheckMetricContext(\"update_legacy\")\n\treturn mc.Observe(g.c.HttpsHealthChecks().Update(ctx, meta.GlobalKey(hc.Name), hc))\n}","line":{"from":124,"to":131}} {"id":100034197,"name":"DeleteHTTPSHealthCheck","signature":"func (g *Cloud) DeleteHTTPSHealthCheck(name string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"// DeleteHTTPSHealthCheck deletes the given HttpsHealthCheck by name.\nfunc (g *Cloud) DeleteHTTPSHealthCheck(name string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newHealthcheckMetricContext(\"delete_legacy\")\n\treturn mc.Observe(g.c.HttpsHealthChecks().Delete(ctx, meta.GlobalKey(name)))\n}","line":{"from":133,"to":140}} {"id":100034198,"name":"CreateHTTPSHealthCheck","signature":"func (g *Cloud) CreateHTTPSHealthCheck(hc *compute.HttpsHealthCheck) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"// CreateHTTPSHealthCheck creates the given HttpsHealthCheck.\nfunc (g *Cloud) CreateHTTPSHealthCheck(hc *compute.HttpsHealthCheck) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newHealthcheckMetricContext(\"create_legacy\")\n\treturn mc.Observe(g.c.HttpsHealthChecks().Insert(ctx, meta.GlobalKey(hc.Name), hc))\n}","line":{"from":142,"to":149}} {"id":100034199,"name":"ListHTTPSHealthChecks","signature":"func (g *Cloud) ListHTTPSHealthChecks() ([]*compute.HttpsHealthCheck, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"// ListHTTPSHealthChecks lists all HttpsHealthChecks in the project.\nfunc (g *Cloud) ListHTTPSHealthChecks() ([]*compute.HttpsHealthCheck, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newHealthcheckMetricContext(\"list_legacy\")\n\tv, err := g.c.HttpsHealthChecks().List(ctx, filter.None)\n\treturn v, mc.Observe(err)\n}","line":{"from":151,"to":159}} {"id":100034200,"name":"GetHealthCheck","signature":"func (g *Cloud) GetHealthCheck(name string) (*compute.HealthCheck, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"// GetHealthCheck returns the given HealthCheck by name.\nfunc (g *Cloud) GetHealthCheck(name string) (*compute.HealthCheck, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newHealthcheckMetricContext(\"get\")\n\tv, err := g.c.HealthChecks().Get(ctx, meta.GlobalKey(name))\n\treturn v, mc.Observe(err)\n}","line":{"from":163,"to":171}} {"id":100034201,"name":"GetAlphaHealthCheck","signature":"func (g *Cloud) GetAlphaHealthCheck(name string) (*computealpha.HealthCheck, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"// GetAlphaHealthCheck returns the given alpha HealthCheck by name.\nfunc (g *Cloud) GetAlphaHealthCheck(name string) (*computealpha.HealthCheck, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newHealthcheckMetricContextWithVersion(\"get\", computeAlphaVersion)\n\tv, err := g.c.AlphaHealthChecks().Get(ctx, meta.GlobalKey(name))\n\treturn v, mc.Observe(err)\n}","line":{"from":173,"to":181}} {"id":100034202,"name":"GetBetaHealthCheck","signature":"func (g *Cloud) GetBetaHealthCheck(name string) (*computebeta.HealthCheck, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"// GetBetaHealthCheck returns the given beta HealthCheck by name.\nfunc (g *Cloud) GetBetaHealthCheck(name string) (*computebeta.HealthCheck, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newHealthcheckMetricContextWithVersion(\"get\", computeBetaVersion)\n\tv, err := g.c.BetaHealthChecks().Get(ctx, meta.GlobalKey(name))\n\treturn v, mc.Observe(err)\n}","line":{"from":183,"to":191}} {"id":100034203,"name":"UpdateHealthCheck","signature":"func (g *Cloud) UpdateHealthCheck(hc *compute.HealthCheck) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"// UpdateHealthCheck applies the given HealthCheck as an update.\nfunc (g *Cloud) UpdateHealthCheck(hc *compute.HealthCheck) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newHealthcheckMetricContext(\"update\")\n\treturn mc.Observe(g.c.HealthChecks().Update(ctx, meta.GlobalKey(hc.Name), hc))\n}","line":{"from":193,"to":200}} {"id":100034204,"name":"UpdateAlphaHealthCheck","signature":"func (g *Cloud) UpdateAlphaHealthCheck(hc *computealpha.HealthCheck) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"// UpdateAlphaHealthCheck applies the given alpha HealthCheck as an update.\nfunc (g *Cloud) UpdateAlphaHealthCheck(hc *computealpha.HealthCheck) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newHealthcheckMetricContextWithVersion(\"update\", computeAlphaVersion)\n\treturn mc.Observe(g.c.AlphaHealthChecks().Update(ctx, meta.GlobalKey(hc.Name), hc))\n}","line":{"from":202,"to":209}} {"id":100034205,"name":"UpdateBetaHealthCheck","signature":"func (g *Cloud) UpdateBetaHealthCheck(hc *computebeta.HealthCheck) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"// UpdateBetaHealthCheck applies the given beta HealthCheck as an update.\nfunc (g *Cloud) UpdateBetaHealthCheck(hc *computebeta.HealthCheck) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newHealthcheckMetricContextWithVersion(\"update\", computeBetaVersion)\n\treturn mc.Observe(g.c.BetaHealthChecks().Update(ctx, meta.GlobalKey(hc.Name), hc))\n}","line":{"from":211,"to":218}} {"id":100034206,"name":"DeleteHealthCheck","signature":"func (g *Cloud) DeleteHealthCheck(name string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"// DeleteHealthCheck deletes the given HealthCheck by name.\nfunc (g *Cloud) DeleteHealthCheck(name string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newHealthcheckMetricContext(\"delete\")\n\treturn mc.Observe(g.c.HealthChecks().Delete(ctx, meta.GlobalKey(name)))\n}","line":{"from":220,"to":227}} {"id":100034207,"name":"CreateHealthCheck","signature":"func (g *Cloud) CreateHealthCheck(hc *compute.HealthCheck) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"// CreateHealthCheck creates the given HealthCheck.\nfunc (g *Cloud) CreateHealthCheck(hc *compute.HealthCheck) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newHealthcheckMetricContext(\"create\")\n\treturn mc.Observe(g.c.HealthChecks().Insert(ctx, meta.GlobalKey(hc.Name), hc))\n}","line":{"from":229,"to":236}} {"id":100034208,"name":"CreateAlphaHealthCheck","signature":"func (g *Cloud) CreateAlphaHealthCheck(hc *computealpha.HealthCheck) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"// CreateAlphaHealthCheck creates the given alpha HealthCheck.\nfunc (g *Cloud) CreateAlphaHealthCheck(hc *computealpha.HealthCheck) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newHealthcheckMetricContextWithVersion(\"create\", computeAlphaVersion)\n\treturn mc.Observe(g.c.AlphaHealthChecks().Insert(ctx, meta.GlobalKey(hc.Name), hc))\n}","line":{"from":238,"to":245}} {"id":100034209,"name":"CreateBetaHealthCheck","signature":"func (g *Cloud) CreateBetaHealthCheck(hc *computebeta.HealthCheck) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"// CreateBetaHealthCheck creates the given beta HealthCheck.\nfunc (g *Cloud) CreateBetaHealthCheck(hc *computebeta.HealthCheck) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newHealthcheckMetricContextWithVersion(\"create\", computeBetaVersion)\n\treturn mc.Observe(g.c.BetaHealthChecks().Insert(ctx, meta.GlobalKey(hc.Name), hc))\n}","line":{"from":247,"to":254}} {"id":100034210,"name":"ListHealthChecks","signature":"func (g *Cloud) ListHealthChecks() ([]*compute.HealthCheck, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"// ListHealthChecks lists all HealthCheck in the project.\nfunc (g *Cloud) ListHealthChecks() ([]*compute.HealthCheck, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newHealthcheckMetricContext(\"list\")\n\tv, err := g.c.HealthChecks().List(ctx, filter.None)\n\treturn v, mc.Observe(err)\n}","line":{"from":256,"to":264}} {"id":100034211,"name":"GetNodesHealthCheckPort","signature":"func GetNodesHealthCheckPort() int32","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"// GetNodesHealthCheckPort returns the health check port used by the GCE load\n// balancers (l4) for performing health checks on nodes.\nfunc GetNodesHealthCheckPort() int32 {\n\treturn lbNodesHealthCheckPort\n}","line":{"from":266,"to":270}} {"id":100034212,"name":"GetNodesHealthCheckPath","signature":"func GetNodesHealthCheckPath() string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"// GetNodesHealthCheckPath returns the health check path used by the GCE load\n// balancers (l4) for performing health checks on nodes.\nfunc GetNodesHealthCheckPath() string {\n\treturn nodesHealthCheckPath\n}","line":{"from":272,"to":276}} {"id":100034213,"name":"isAtLeastMinNodesHealthCheckVersion","signature":"func isAtLeastMinNodesHealthCheckVersion(vstring string) bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"// isAtLeastMinNodesHealthCheckVersion checks if a version is higher than\n// `minNodesHealthCheckVersion`.\nfunc isAtLeastMinNodesHealthCheckVersion(vstring string) bool {\n\tversion, err := utilversion.ParseGeneric(vstring)\n\tif err != nil {\n\t\tklog.Errorf(\"vstring (%s) is not a valid version string: %v\", vstring, err)\n\t\treturn false\n\t}\n\treturn version.AtLeast(minNodesHealthCheckVersion)\n}","line":{"from":278,"to":287}} {"id":100034214,"name":"supportsNodesHealthCheck","signature":"func supportsNodesHealthCheck(nodes []*v1.Node) bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_healthchecks.go","code":"// supportsNodesHealthCheck returns false if anyone of the nodes has version\n// lower than `minNodesHealthCheckVersion`.\nfunc supportsNodesHealthCheck(nodes []*v1.Node) bool {\n\tfor _, node := range nodes {\n\t\tif !isAtLeastMinNodesHealthCheckVersion(node.Status.NodeInfo.KubeProxyVersion) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":289,"to":298}} {"id":100034215,"name":"newInstanceGroupMetricContext","signature":"func newInstanceGroupMetricContext(request string, zone string) *metricContext","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instancegroup.go","code":"func newInstanceGroupMetricContext(request string, zone string) *metricContext {\n\treturn newGenericMetricContext(\"instancegroup\", request, unusedMetricLabel, zone, computeV1Version)\n}","line":{"from":30,"to":32}} {"id":100034216,"name":"CreateInstanceGroup","signature":"func (g *Cloud) CreateInstanceGroup(ig *compute.InstanceGroup, zone string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instancegroup.go","code":"// CreateInstanceGroup creates an instance group with the given\n// instances. It is the callers responsibility to add named ports.\nfunc (g *Cloud) CreateInstanceGroup(ig *compute.InstanceGroup, zone string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newInstanceGroupMetricContext(\"create\", zone)\n\treturn mc.Observe(g.c.InstanceGroups().Insert(ctx, meta.ZonalKey(ig.Name, zone), ig))\n}","line":{"from":34,"to":42}} {"id":100034217,"name":"DeleteInstanceGroup","signature":"func (g *Cloud) DeleteInstanceGroup(name string, zone string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instancegroup.go","code":"// DeleteInstanceGroup deletes an instance group.\nfunc (g *Cloud) DeleteInstanceGroup(name string, zone string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newInstanceGroupMetricContext(\"delete\", zone)\n\treturn mc.Observe(g.c.InstanceGroups().Delete(ctx, meta.ZonalKey(name, zone)))\n}","line":{"from":44,"to":51}} {"id":100034218,"name":"FilterInstanceGroupsByNamePrefix","signature":"func (g *Cloud) FilterInstanceGroupsByNamePrefix(namePrefix, zone string) ([]*compute.InstanceGroup, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instancegroup.go","code":"// FilterInstanceGroupsByName lists all InstanceGroups in the project and\n// zone that match the name regexp.\nfunc (g *Cloud) FilterInstanceGroupsByNamePrefix(namePrefix, zone string) ([]*compute.InstanceGroup, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\tmc := newInstanceGroupMetricContext(\"filter\", zone)\n\tv, err := g.c.InstanceGroups().List(ctx, zone, filter.Regexp(\"name\", namePrefix+\".*\"))\n\treturn v, mc.Observe(err)\n}","line":{"from":53,"to":61}} {"id":100034219,"name":"ListInstanceGroups","signature":"func (g *Cloud) ListInstanceGroups(zone string) ([]*compute.InstanceGroup, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instancegroup.go","code":"// ListInstanceGroups lists all InstanceGroups in the project and\n// zone.\nfunc (g *Cloud) ListInstanceGroups(zone string) ([]*compute.InstanceGroup, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newInstanceGroupMetricContext(\"list\", zone)\n\tv, err := g.c.InstanceGroups().List(ctx, zone, filter.None)\n\treturn v, mc.Observe(err)\n}","line":{"from":63,"to":72}} {"id":100034220,"name":"ListInstancesInInstanceGroup","signature":"func (g *Cloud) ListInstancesInInstanceGroup(name string, zone string, state string) ([]*compute.InstanceWithNamedPorts, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instancegroup.go","code":"// ListInstancesInInstanceGroup lists all the instances in a given\n// instance group and state.\nfunc (g *Cloud) ListInstancesInInstanceGroup(name string, zone string, state string) ([]*compute.InstanceWithNamedPorts, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newInstanceGroupMetricContext(\"list_instances\", zone)\n\treq := \u0026compute.InstanceGroupsListInstancesRequest{InstanceState: state}\n\tv, err := g.c.InstanceGroups().ListInstances(ctx, meta.ZonalKey(name, zone), req, filter.None)\n\treturn v, mc.Observe(err)\n}","line":{"from":74,"to":84}} {"id":100034221,"name":"AddInstancesToInstanceGroup","signature":"func (g *Cloud) AddInstancesToInstanceGroup(name string, zone string, instanceRefs []*compute.InstanceReference) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instancegroup.go","code":"// AddInstancesToInstanceGroup adds the given instances to the given\n// instance group.\nfunc (g *Cloud) AddInstancesToInstanceGroup(name string, zone string, instanceRefs []*compute.InstanceReference) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newInstanceGroupMetricContext(\"add_instances\", zone)\n\t// TODO: should cull operation above this layer.\n\tif len(instanceRefs) == 0 {\n\t\treturn nil\n\t}\n\treq := \u0026compute.InstanceGroupsAddInstancesRequest{\n\t\tInstances: instanceRefs,\n\t}\n\treturn mc.Observe(g.c.InstanceGroups().AddInstances(ctx, meta.ZonalKey(name, zone), req))\n}","line":{"from":86,"to":101}} {"id":100034222,"name":"RemoveInstancesFromInstanceGroup","signature":"func (g *Cloud) RemoveInstancesFromInstanceGroup(name string, zone string, instanceRefs []*compute.InstanceReference) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instancegroup.go","code":"// RemoveInstancesFromInstanceGroup removes the given instances from\n// the instance group.\nfunc (g *Cloud) RemoveInstancesFromInstanceGroup(name string, zone string, instanceRefs []*compute.InstanceReference) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newInstanceGroupMetricContext(\"remove_instances\", zone)\n\t// TODO: should cull operation above this layer.\n\tif len(instanceRefs) == 0 {\n\t\treturn nil\n\t}\n\treq := \u0026compute.InstanceGroupsRemoveInstancesRequest{\n\t\tInstances: instanceRefs,\n\t}\n\treturn mc.Observe(g.c.InstanceGroups().RemoveInstances(ctx, meta.ZonalKey(name, zone), req))\n}","line":{"from":103,"to":118}} {"id":100034223,"name":"SetNamedPortsOfInstanceGroup","signature":"func (g *Cloud) SetNamedPortsOfInstanceGroup(igName, zone string, namedPorts []*compute.NamedPort) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instancegroup.go","code":"// SetNamedPortsOfInstanceGroup sets the list of named ports on a given instance group\nfunc (g *Cloud) SetNamedPortsOfInstanceGroup(igName, zone string, namedPorts []*compute.NamedPort) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newInstanceGroupMetricContext(\"set_namedports\", zone)\n\treq := \u0026compute.InstanceGroupsSetNamedPortsRequest{NamedPorts: namedPorts}\n\treturn mc.Observe(g.c.InstanceGroups().SetNamedPorts(ctx, meta.ZonalKey(igName, zone), req))\n}","line":{"from":120,"to":128}} {"id":100034224,"name":"GetInstanceGroup","signature":"func (g *Cloud) GetInstanceGroup(name string, zone string) (*compute.InstanceGroup, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instancegroup.go","code":"// GetInstanceGroup returns an instance group by name.\nfunc (g *Cloud) GetInstanceGroup(name string, zone string) (*compute.InstanceGroup, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newInstanceGroupMetricContext(\"get\", zone)\n\tv, err := g.c.InstanceGroups().Get(ctx, meta.ZonalKey(name, zone))\n\treturn v, mc.Observe(err)\n}","line":{"from":130,"to":138}} {"id":100034225,"name":"newInstancesMetricContext","signature":"func newInstancesMetricContext(request, zone string) *metricContext","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"func newInstancesMetricContext(request, zone string) *metricContext {\n\treturn newGenericMetricContext(\"instances\", request, unusedMetricLabel, zone, computeV1Version)\n}","line":{"from":52,"to":54}} {"id":100034226,"name":"splitNodesByZone","signature":"func splitNodesByZone(nodes []*v1.Node) map[string][]*v1.Node","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"func splitNodesByZone(nodes []*v1.Node) map[string][]*v1.Node {\n\tzones := make(map[string][]*v1.Node)\n\tfor _, n := range nodes {\n\t\tz := getZone(n)\n\t\tif z != defaultZone {\n\t\t\tzones[z] = append(zones[z], n)\n\t\t}\n\t}\n\treturn zones\n}","line":{"from":56,"to":65}} {"id":100034227,"name":"getZone","signature":"func getZone(n *v1.Node) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"func getZone(n *v1.Node) string {\n\tzone, ok := n.Labels[v1.LabelFailureDomainBetaZone]\n\tif !ok {\n\t\treturn defaultZone\n\t}\n\treturn zone\n}","line":{"from":67,"to":73}} {"id":100034228,"name":"makeHostURL","signature":"func makeHostURL(projectsAPIEndpoint, projectID, zone, host string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"func makeHostURL(projectsAPIEndpoint, projectID, zone, host string) string {\n\thost = canonicalizeInstanceName(host)\n\treturn projectsAPIEndpoint + strings.Join([]string{projectID, \"zones\", zone, \"instances\", host}, \"/\")\n}","line":{"from":75,"to":78}} {"id":100034229,"name":"ToInstanceReferences","signature":"func (g *Cloud) ToInstanceReferences(zone string, instanceNames []string) (refs []*compute.InstanceReference)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// ToInstanceReferences returns instance references by links\nfunc (g *Cloud) ToInstanceReferences(zone string, instanceNames []string) (refs []*compute.InstanceReference) {\n\tfor _, ins := range instanceNames {\n\t\tinstanceLink := makeHostURL(g.projectsBasePath, g.projectID, zone, ins)\n\t\trefs = append(refs, \u0026compute.InstanceReference{Instance: instanceLink})\n\t}\n\treturn refs\n}","line":{"from":80,"to":87}} {"id":100034230,"name":"NodeAddresses","signature":"func (g *Cloud) NodeAddresses(ctx context.Context, nodeName types.NodeName) ([]v1.NodeAddress, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// NodeAddresses is an implementation of Instances.NodeAddresses.\nfunc (g *Cloud) NodeAddresses(ctx context.Context, nodeName types.NodeName) ([]v1.NodeAddress, error) {\n\ttimeoutCtx, cancel := context.WithTimeout(ctx, 1*time.Hour)\n\tdefer cancel()\n\n\tinstanceName := string(nodeName)\n\n\tif g.useMetadataServer {\n\t\t// Use metadata server if possible\n\t\tif g.isCurrentInstance(instanceName) {\n\n\t\t\tnics, err := metadata.Get(\"instance/network-interfaces/\")\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"couldn't get network interfaces: %v\", err)\n\t\t\t}\n\n\t\t\tnicsArr := strings.Split(nics, \"/\\n\")\n\t\t\tnodeAddresses := []v1.NodeAddress{}\n\n\t\t\tfor _, nic := range nicsArr {\n\n\t\t\t\tif nic == \"\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tinternalIP, err := metadata.Get(fmt.Sprintf(networkInterfaceIP, nic))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"couldn't get internal IP: %v\", err)\n\t\t\t\t}\n\t\t\t\tnodeAddresses = append(nodeAddresses, v1.NodeAddress{Type: v1.NodeInternalIP, Address: internalIP})\n\n\t\t\t\tacs, err := metadata.Get(fmt.Sprintf(networkInterfaceAccessConfigs, nic))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"couldn't get access configs: %v\", err)\n\t\t\t\t}\n\n\t\t\t\tacsArr := strings.Split(acs, \"/\\n\")\n\n\t\t\t\tfor _, ac := range acsArr {\n\n\t\t\t\t\tif ac == \"\" {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\texternalIP, err := metadata.Get(fmt.Sprintf(networkInterfaceExternalIP, nic, ac))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, fmt.Errorf(\"couldn't get external IP: %v\", err)\n\t\t\t\t\t}\n\n\t\t\t\t\tif externalIP != \"\" {\n\t\t\t\t\t\tnodeAddresses = append(nodeAddresses, v1.NodeAddress{Type: v1.NodeExternalIP, Address: externalIP})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tinternalDNSFull, err := metadata.Get(\"instance/hostname\")\n\t\t\tif err != nil {\n\t\t\t\tklog.Warningf(\"couldn't get full internal DNS name: %v\", err)\n\t\t\t} else {\n\t\t\t\tnodeAddresses = append(nodeAddresses,\n\t\t\t\t\tv1.NodeAddress{Type: v1.NodeInternalDNS, Address: internalDNSFull},\n\t\t\t\t\tv1.NodeAddress{Type: v1.NodeHostName, Address: internalDNSFull},\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn nodeAddresses, nil\n\t\t}\n\t}\n\n\t// Use GCE API\n\tinstanceObj, err := g.getInstanceByName(instanceName)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"couldn't get instance details: %v\", err)\n\t}\n\n\tinstance, err := g.c.Instances().Get(timeoutCtx, meta.ZonalKey(canonicalizeInstanceName(instanceObj.Name), instanceObj.Zone))\n\tif err != nil {\n\t\treturn []v1.NodeAddress{}, fmt.Errorf(\"error while querying for instance: %v\", err)\n\t}\n\n\treturn nodeAddressesFromInstance(instance)\n}","line":{"from":89,"to":169}} {"id":100034231,"name":"NodeAddressesByProviderID","signature":"func (g *Cloud) NodeAddressesByProviderID(ctx context.Context, providerID string) ([]v1.NodeAddress, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// NodeAddressesByProviderID will not be called from the node that is requesting this ID.\n// i.e. metadata service and other local methods cannot be used here\nfunc (g *Cloud) NodeAddressesByProviderID(ctx context.Context, providerID string) ([]v1.NodeAddress, error) {\n\ttimeoutCtx, cancel := context.WithTimeout(ctx, 1*time.Hour)\n\tdefer cancel()\n\n\t_, zone, name, err := splitProviderID(providerID)\n\tif err != nil {\n\t\treturn []v1.NodeAddress{}, err\n\t}\n\n\tinstance, err := g.c.Instances().Get(timeoutCtx, meta.ZonalKey(canonicalizeInstanceName(name), zone))\n\tif err != nil {\n\t\treturn []v1.NodeAddress{}, fmt.Errorf(\"error while querying for providerID %q: %v\", providerID, err)\n\t}\n\n\treturn nodeAddressesFromInstance(instance)\n}","line":{"from":171,"to":188}} {"id":100034232,"name":"instanceByProviderID","signature":"func (g *Cloud) instanceByProviderID(providerID string) (*gceInstance, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// instanceByProviderID returns the cloudprovider instance of the node\n// with the specified unique providerID\nfunc (g *Cloud) instanceByProviderID(providerID string) (*gceInstance, error) {\n\tproject, zone, name, err := splitProviderID(providerID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinstance, err := g.getInstanceFromProjectInZoneByName(project, zone, name)\n\tif err != nil {\n\t\tif isHTTPErrorCode(err, http.StatusNotFound) {\n\t\t\treturn nil, cloudprovider.InstanceNotFound\n\t\t}\n\t\treturn nil, err\n\t}\n\n\treturn instance, nil\n}","line":{"from":190,"to":207}} {"id":100034233,"name":"InstanceShutdownByProviderID","signature":"func (g *Cloud) InstanceShutdownByProviderID(ctx context.Context, providerID string) (bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// InstanceShutdownByProviderID returns true if the instance is in safe state to detach volumes\nfunc (g *Cloud) InstanceShutdownByProviderID(ctx context.Context, providerID string) (bool, error) {\n\treturn false, cloudprovider.NotImplemented\n}","line":{"from":209,"to":212}} {"id":100034234,"name":"InstanceShutdown","signature":"func (g *Cloud) InstanceShutdown(ctx context.Context, node *v1.Node) (bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// InstanceShutdown returns true if the instance is in safe state to detach volumes\nfunc (g *Cloud) InstanceShutdown(ctx context.Context, node *v1.Node) (bool, error) {\n\treturn false, cloudprovider.NotImplemented\n}","line":{"from":214,"to":217}} {"id":100034235,"name":"nodeAddressesFromInstance","signature":"func nodeAddressesFromInstance(instance *compute.Instance) ([]v1.NodeAddress, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"func nodeAddressesFromInstance(instance *compute.Instance) ([]v1.NodeAddress, error) {\n\tif len(instance.NetworkInterfaces) \u003c 1 {\n\t\treturn nil, fmt.Errorf(\"could not find network interfaces for instanceID %q\", instance.Id)\n\t}\n\tnodeAddresses := []v1.NodeAddress{}\n\n\tfor _, nic := range instance.NetworkInterfaces {\n\t\tnodeAddresses = append(nodeAddresses, v1.NodeAddress{Type: v1.NodeInternalIP, Address: nic.NetworkIP})\n\t\tfor _, config := range nic.AccessConfigs {\n\t\t\tnodeAddresses = append(nodeAddresses, v1.NodeAddress{Type: v1.NodeExternalIP, Address: config.NatIP})\n\t\t}\n\t}\n\n\treturn nodeAddresses, nil\n}","line":{"from":219,"to":233}} {"id":100034236,"name":"InstanceTypeByProviderID","signature":"func (g *Cloud) InstanceTypeByProviderID(ctx context.Context, providerID string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// InstanceTypeByProviderID returns the cloudprovider instance type of the node\n// with the specified unique providerID This method will not be called from the\n// node that is requesting this ID. i.e. metadata service and other local\n// methods cannot be used here\nfunc (g *Cloud) InstanceTypeByProviderID(ctx context.Context, providerID string) (string, error) {\n\tinstance, err := g.instanceByProviderID(providerID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn instance.Type, nil\n}","line":{"from":235,"to":246}} {"id":100034237,"name":"InstanceExistsByProviderID","signature":"func (g *Cloud) InstanceExistsByProviderID(ctx context.Context, providerID string) (bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// InstanceExistsByProviderID returns true if the instance with the given provider id still exists and is running.\n// If false is returned with no error, the instance will be immediately deleted by the cloud controller manager.\nfunc (g *Cloud) InstanceExistsByProviderID(ctx context.Context, providerID string) (bool, error) {\n\t_, err := g.instanceByProviderID(providerID)\n\tif err != nil {\n\t\tif err == cloudprovider.InstanceNotFound {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn false, err\n\t}\n\n\treturn true, nil\n}","line":{"from":248,"to":260}} {"id":100034238,"name":"InstanceExists","signature":"func (g *Cloud) InstanceExists(ctx context.Context, node *v1.Node) (bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// InstanceExists returns true if the instance with the given provider id still exists and is running.\n// If false is returned with no error, the instance will be immediately deleted by the cloud controller manager.\nfunc (g *Cloud) InstanceExists(ctx context.Context, node *v1.Node) (bool, error) {\n\tproviderID := node.Spec.ProviderID\n\tif providerID == \"\" {\n\t\tvar err error\n\t\tif providerID, err = cloudprovider.GetInstanceProviderID(ctx, g, types.NodeName(node.Name)); err != nil {\n\t\t\tif err == cloudprovider.InstanceNotFound {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn false, err\n\t\t}\n\t}\n\treturn g.InstanceExistsByProviderID(ctx, providerID)\n}","line":{"from":262,"to":276}} {"id":100034239,"name":"InstanceMetadata","signature":"func (g *Cloud) InstanceMetadata(ctx context.Context, node *v1.Node) (*cloudprovider.InstanceMetadata, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// InstanceMetadata returns metadata of the specified instance.\nfunc (g *Cloud) InstanceMetadata(ctx context.Context, node *v1.Node) (*cloudprovider.InstanceMetadata, error) {\n\ttimeoutCtx, cancel := context.WithTimeout(ctx, 1*time.Hour)\n\tdefer cancel()\n\n\tproviderID := node.Spec.ProviderID\n\tif providerID == \"\" {\n\t\tvar err error\n\t\tif providerID, err = cloudprovider.GetInstanceProviderID(ctx, g, types.NodeName(node.Name)); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t_, zone, name, err := splitProviderID(providerID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tregion, err := GetGCERegion(zone)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinstance, err := g.c.Instances().Get(timeoutCtx, meta.ZonalKey(canonicalizeInstanceName(name), zone))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while querying for providerID %q: %v\", providerID, err)\n\t}\n\n\taddresses, err := nodeAddressesFromInstance(instance)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026cloudprovider.InstanceMetadata{\n\t\tProviderID: providerID,\n\t\tInstanceType: lastComponent(instance.MachineType),\n\t\tNodeAddresses: addresses,\n\t\tZone: zone,\n\t\tRegion: region,\n\t}, nil\n}","line":{"from":278,"to":318}} {"id":100034240,"name":"InstanceID","signature":"func (g *Cloud) InstanceID(ctx context.Context, nodeName types.NodeName) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// InstanceID returns the cloud provider ID of the node with the specified NodeName.\nfunc (g *Cloud) InstanceID(ctx context.Context, nodeName types.NodeName) (string, error) {\n\tinstanceName := mapNodeNameToInstanceName(nodeName)\n\tif g.useMetadataServer {\n\t\t// Use metadata, if possible, to fetch ID. See issue #12000\n\t\tif g.isCurrentInstance(instanceName) {\n\t\t\tprojectID, zone, err := getProjectAndZone()\n\t\t\tif err == nil {\n\t\t\t\treturn projectID + \"/\" + zone + \"/\" + canonicalizeInstanceName(instanceName), nil\n\t\t\t}\n\t\t}\n\t}\n\tinstance, err := g.getInstanceByName(instanceName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn g.projectID + \"/\" + instance.Zone + \"/\" + instance.Name, nil\n}","line":{"from":320,"to":337}} {"id":100034241,"name":"InstanceType","signature":"func (g *Cloud) InstanceType(ctx context.Context, nodeName types.NodeName) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// InstanceType returns the type of the specified node with the specified NodeName.\nfunc (g *Cloud) InstanceType(ctx context.Context, nodeName types.NodeName) (string, error) {\n\tinstanceName := mapNodeNameToInstanceName(nodeName)\n\tif g.useMetadataServer {\n\t\t// Use metadata, if possible, to fetch ID. See issue #12000\n\t\tif g.isCurrentInstance(instanceName) {\n\t\t\tmType, err := getCurrentMachineTypeViaMetadata()\n\t\t\tif err == nil {\n\t\t\t\treturn mType, nil\n\t\t\t}\n\t\t}\n\t}\n\tinstance, err := g.getInstanceByName(instanceName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn instance.Type, nil\n}","line":{"from":339,"to":356}} {"id":100034242,"name":"AddSSHKeyToAllInstances","signature":"func (g *Cloud) AddSSHKeyToAllInstances(ctx context.Context, user string, keyData []byte) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// AddSSHKeyToAllInstances adds an SSH public key as a legal identity for all instances\n// expected format for the key is standard ssh-keygen format: \u003cprotocol\u003e \u003cblob\u003e\nfunc (g *Cloud) AddSSHKeyToAllInstances(ctx context.Context, user string, keyData []byte) error {\n\tctx, cancel := context.WithTimeout(ctx, 1*time.Hour)\n\tdefer cancel()\n\n\treturn wait.Poll(2*time.Second, 30*time.Second, func() (bool, error) {\n\t\tproject, err := g.c.Projects().Get(ctx, g.projectID)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Could not get project: %v\", err)\n\t\t\treturn false, nil\n\t\t}\n\t\tkeyString := fmt.Sprintf(\"%s:%s %s@%s\", user, strings.TrimSpace(string(keyData)), user, user)\n\t\tfound := false\n\t\tfor _, item := range project.CommonInstanceMetadata.Items {\n\t\t\tif item.Key == \"sshKeys\" {\n\t\t\t\tif strings.Contains(*item.Value, keyString) {\n\t\t\t\t\t// We've already added the key\n\t\t\t\t\tklog.Info(\"SSHKey already in project metadata\")\n\t\t\t\t\treturn true, nil\n\t\t\t\t}\n\t\t\t\tvalue := *item.Value + \"\\n\" + keyString\n\t\t\t\titem.Value = \u0026value\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\t// This is super unlikely, so log.\n\t\t\tklog.Infof(\"Failed to find sshKeys metadata, creating a new item\")\n\t\t\tproject.CommonInstanceMetadata.Items = append(project.CommonInstanceMetadata.Items,\n\t\t\t\t\u0026compute.MetadataItems{\n\t\t\t\t\tKey: \"sshKeys\",\n\t\t\t\t\tValue: \u0026keyString,\n\t\t\t\t})\n\t\t}\n\n\t\tmc := newInstancesMetricContext(\"add_ssh_key\", \"\")\n\t\terr = g.c.Projects().SetCommonInstanceMetadata(ctx, g.projectID, project.CommonInstanceMetadata)\n\t\tmc.Observe(err)\n\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Could not Set Metadata: %v\", err)\n\t\t\treturn false, nil\n\t\t}\n\t\tklog.Infof(\"Successfully added sshKey to project metadata\")\n\t\treturn true, nil\n\t})\n}","line":{"from":358,"to":406}} {"id":100034243,"name":"GetAllCurrentZones","signature":"func (g *Cloud) GetAllCurrentZones() (sets.String, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// GetAllCurrentZones returns all the zones in which k8s nodes are currently running\nfunc (g *Cloud) GetAllCurrentZones() (sets.String, error) {\n\tif g.nodeInformerSynced == nil {\n\t\tklog.Warning(\"Cloud object does not have informers set, should only happen in E2E binary.\")\n\t\treturn g.GetAllZonesFromCloudProvider()\n\t}\n\tg.nodeZonesLock.Lock()\n\tdefer g.nodeZonesLock.Unlock()\n\tif !g.nodeInformerSynced() {\n\t\treturn nil, fmt.Errorf(\"node informer is not synced when trying to GetAllCurrentZones\")\n\t}\n\tzones := sets.NewString()\n\tfor zone, nodes := range g.nodeZones {\n\t\tif len(nodes) \u003e 0 {\n\t\t\tzones.Insert(zone)\n\t\t}\n\t}\n\treturn zones, nil\n}","line":{"from":408,"to":426}} {"id":100034244,"name":"GetAllZonesFromCloudProvider","signature":"func (g *Cloud) GetAllZonesFromCloudProvider() (sets.String, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// GetAllZonesFromCloudProvider returns all the zones in which nodes are running\n// Only use this in E2E tests to get zones, on real clusters this will\n// get all zones with compute instances in them even if not k8s instances!!!\n// ex. I have k8s nodes in us-central1-c and us-central1-b. I also have\n// a non-k8s compute in us-central1-a. This func will return a,b, and c.\n//\n// TODO: this should be removed from the cloud provider.\nfunc (g *Cloud) GetAllZonesFromCloudProvider() (sets.String, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tzones := sets.NewString()\n\tfor _, zone := range g.managedZones {\n\t\tinstances, err := g.c.Instances().List(ctx, zone, filter.None)\n\t\tif err != nil {\n\t\t\treturn sets.NewString(), err\n\t\t}\n\t\tif len(instances) \u003e 0 {\n\t\t\tzones.Insert(zone)\n\t\t}\n\t}\n\treturn zones, nil\n}","line":{"from":428,"to":450}} {"id":100034245,"name":"InsertInstance","signature":"func (g *Cloud) InsertInstance(project string, zone string, i *compute.Instance) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// InsertInstance creates a new instance on GCP\nfunc (g *Cloud) InsertInstance(project string, zone string, i *compute.Instance) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newInstancesMetricContext(\"create\", zone)\n\treturn mc.Observe(g.c.Instances().Insert(ctx, meta.ZonalKey(i.Name, zone), i))\n}","line":{"from":452,"to":459}} {"id":100034246,"name":"ListInstanceNames","signature":"func (g *Cloud) ListInstanceNames(project, zone string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// ListInstanceNames returns a string of instance names separated by spaces.\n// This method should only be used for e2e testing.\n// TODO: remove this method.\nfunc (g *Cloud) ListInstanceNames(project, zone string) (string, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tl, err := g.c.Instances().List(ctx, zone, filter.None)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tvar names []string\n\tfor _, i := range l {\n\t\tnames = append(names, i.Name)\n\t}\n\treturn strings.Join(names, \" \"), nil\n}","line":{"from":461,"to":477}} {"id":100034247,"name":"DeleteInstance","signature":"func (g *Cloud) DeleteInstance(project, zone, name string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// DeleteInstance deletes an instance specified by project, zone, and name\nfunc (g *Cloud) DeleteInstance(project, zone, name string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\treturn g.c.Instances().Delete(ctx, meta.ZonalKey(name, zone))\n}","line":{"from":479,"to":485}} {"id":100034248,"name":"CurrentNodeName","signature":"func (g *Cloud) CurrentNodeName(ctx context.Context, hostname string) (types.NodeName, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// CurrentNodeName returns the name of the node we are currently running on\n// On most clouds (e.g. GCE) this is the hostname, so we provide the hostname\nfunc (g *Cloud) CurrentNodeName(ctx context.Context, hostname string) (types.NodeName, error) {\n\treturn types.NodeName(hostname), nil\n}","line":{"from":487,"to":491}} {"id":100034249,"name":"AliasRangesByProviderID","signature":"func (g *Cloud) AliasRangesByProviderID(providerID string) (cidrs []string, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// AliasRangesByProviderID returns a list of CIDR ranges that are assigned to the\n// `node` for allocation to pods. Returns a list of the form\n// \"\u003cip\u003e/\u003cnetmask\u003e\".\nfunc (g *Cloud) AliasRangesByProviderID(providerID string) (cidrs []string, err error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\t_, zone, name, err := splitProviderID(providerID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar res *computebeta.Instance\n\tres, err = g.c.BetaInstances().Get(ctx, meta.ZonalKey(canonicalizeInstanceName(name), zone))\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor _, networkInterface := range res.NetworkInterfaces {\n\t\tfor _, r := range networkInterface.AliasIpRanges {\n\t\t\tcidrs = append(cidrs, r.IpCidrRange)\n\t\t}\n\t}\n\treturn\n}","line":{"from":493,"to":517}} {"id":100034250,"name":"AddAliasToInstanceByProviderID","signature":"func (g *Cloud) AddAliasToInstanceByProviderID(providerID string, alias *net.IPNet) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// AddAliasToInstanceByProviderID adds an alias to the given instance from the named\n// secondary range.\nfunc (g *Cloud) AddAliasToInstanceByProviderID(providerID string, alias *net.IPNet) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\t_, zone, name, err := splitProviderID(providerID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tinstance, err := g.c.BetaInstances().Get(ctx, meta.ZonalKey(canonicalizeInstanceName(name), zone))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch len(instance.NetworkInterfaces) {\n\tcase 0:\n\t\treturn fmt.Errorf(\"instance %q has no network interfaces\", providerID)\n\tcase 1:\n\tdefault:\n\t\tklog.Warningf(\"Instance %q has more than one network interface, using only the first (%v)\",\n\t\t\tproviderID, instance.NetworkInterfaces)\n\t}\n\n\tiface := \u0026computebeta.NetworkInterface{}\n\tiface.Name = instance.NetworkInterfaces[0].Name\n\tiface.Fingerprint = instance.NetworkInterfaces[0].Fingerprint\n\tiface.AliasIpRanges = append(iface.AliasIpRanges, \u0026computebeta.AliasIpRange{\n\t\tIpCidrRange: alias.String(),\n\t\tSubnetworkRangeName: g.secondaryRangeName,\n\t})\n\n\tmc := newInstancesMetricContext(\"add_alias\", zone)\n\terr = g.c.BetaInstances().UpdateNetworkInterface(ctx, meta.ZonalKey(instance.Name, lastComponent(instance.Zone)), iface.Name, iface)\n\treturn mc.Observe(err)\n}","line":{"from":519,"to":555}} {"id":100034251,"name":"getInstancesByNames","signature":"func (g *Cloud) getInstancesByNames(names []string) ([]*gceInstance, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// Gets the named instances, returning cloudprovider.InstanceNotFound if any\n// instance is not found\nfunc (g *Cloud) getInstancesByNames(names []string) ([]*gceInstance, error) {\n\tfoundInstances, err := g.getFoundInstanceByNames(names)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(foundInstances) != len(names) {\n\t\tif len(foundInstances) == 0 {\n\t\t\t// return error so the TargetPool nodecount does not drop to 0 unexpectedly.\n\t\t\treturn nil, cloudprovider.InstanceNotFound\n\t\t}\n\t\tklog.Warningf(\"getFoundInstanceByNames - input instances %d, found %d. Continuing LoadBalancer Update\", len(names), len(foundInstances))\n\t}\n\treturn foundInstances, nil\n}","line":{"from":557,"to":572}} {"id":100034252,"name":"getFoundInstanceByNames","signature":"func (g *Cloud) getFoundInstanceByNames(names []string) ([]*gceInstance, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// Gets the named instances, returning a list of gceInstances it was able to find from the provided\n// list of names.\nfunc (g *Cloud) getFoundInstanceByNames(names []string) ([]*gceInstance, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tfound := map[string]*gceInstance{}\n\tremaining := len(names)\n\n\tnodeInstancePrefix := g.nodeInstancePrefix\n\tfor _, name := range names {\n\t\tname = canonicalizeInstanceName(name)\n\t\tif !strings.HasPrefix(name, g.nodeInstancePrefix) {\n\t\t\tklog.Warningf(\"Instance %q does not conform to prefix %q, removing filter\", name, g.nodeInstancePrefix)\n\t\t\tnodeInstancePrefix = \"\"\n\t\t}\n\t\tfound[name] = nil\n\t}\n\n\tfor _, zone := range g.managedZones {\n\t\tif remaining == 0 {\n\t\t\tbreak\n\t\t}\n\t\tinstances, err := g.c.Instances().List(ctx, zone, filter.Regexp(\"name\", nodeInstancePrefix+\".*\"))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, inst := range instances {\n\t\t\tif remaining == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif _, ok := found[inst.Name]; !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif found[inst.Name] != nil {\n\t\t\t\tklog.Errorf(\"Instance name %q was duplicated (in zone %q and %q)\", inst.Name, zone, found[inst.Name].Zone)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfound[inst.Name] = \u0026gceInstance{\n\t\t\t\tZone: zone,\n\t\t\t\tName: inst.Name,\n\t\t\t\tID: inst.Id,\n\t\t\t\tDisks: inst.Disks,\n\t\t\t\tType: lastComponent(inst.MachineType),\n\t\t\t}\n\t\t\tremaining--\n\t\t}\n\t}\n\n\tvar ret []*gceInstance\n\tvar failed []string\n\tfor name, instance := range found {\n\t\tif instance != nil {\n\t\t\tret = append(ret, instance)\n\t\t} else {\n\t\t\tfailed = append(failed, name)\n\t\t}\n\t}\n\tif len(failed) \u003e 0 {\n\t\tklog.Errorf(\"Failed to retrieve instances: %v\", failed)\n\t}\n\n\treturn ret, nil\n}","line":{"from":574,"to":637}} {"id":100034253,"name":"getInstanceByName","signature":"func (g *Cloud) getInstanceByName(name string) (*gceInstance, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// Gets the named instance, returning cloudprovider.InstanceNotFound if the instance is not found\nfunc (g *Cloud) getInstanceByName(name string) (*gceInstance, error) {\n\t// Avoid changing behaviour when not managing multiple zones\n\tfor _, zone := range g.managedZones {\n\t\tinstance, err := g.getInstanceFromProjectInZoneByName(g.projectID, zone, name)\n\t\tif err != nil {\n\t\t\tif isHTTPErrorCode(err, http.StatusNotFound) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tklog.Errorf(\"getInstanceByName: failed to get instance %s in zone %s; err: %v\", name, zone, err)\n\t\t\treturn nil, err\n\t\t}\n\t\treturn instance, nil\n\t}\n\n\treturn nil, cloudprovider.InstanceNotFound\n}","line":{"from":639,"to":655}} {"id":100034254,"name":"getInstanceFromProjectInZoneByName","signature":"func (g *Cloud) getInstanceFromProjectInZoneByName(project, zone, name string) (*gceInstance, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"func (g *Cloud) getInstanceFromProjectInZoneByName(project, zone, name string) (*gceInstance, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tname = canonicalizeInstanceName(name)\n\tmc := newInstancesMetricContext(\"get\", zone)\n\tres, err := g.c.Instances().Get(ctx, meta.ZonalKey(name, zone))\n\tmc.Observe(err)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026gceInstance{\n\t\tZone: lastComponent(res.Zone),\n\t\tName: res.Name,\n\t\tID: res.Id,\n\t\tDisks: res.Disks,\n\t\tType: lastComponent(res.MachineType),\n\t}, nil\n}","line":{"from":657,"to":675}} {"id":100034255,"name":"getInstanceIDViaMetadata","signature":"func getInstanceIDViaMetadata() (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"func getInstanceIDViaMetadata() (string, error) {\n\tresult, err := metadata.Get(\"instance/hostname\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tparts := strings.Split(result, \".\")\n\tif len(parts) == 0 {\n\t\treturn \"\", fmt.Errorf(\"unexpected response: %s\", result)\n\t}\n\treturn parts[0], nil\n}","line":{"from":677,"to":687}} {"id":100034256,"name":"getCurrentMachineTypeViaMetadata","signature":"func getCurrentMachineTypeViaMetadata() (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"func getCurrentMachineTypeViaMetadata() (string, error) {\n\tmType, err := metadata.Get(\"instance/machine-type\")\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"couldn't get machine type: %v\", err)\n\t}\n\tparts := strings.Split(mType, \"/\")\n\tif len(parts) != 4 {\n\t\treturn \"\", fmt.Errorf(\"unexpected response for machine type: %s\", mType)\n\t}\n\n\treturn parts[3], nil\n}","line":{"from":689,"to":700}} {"id":100034257,"name":"isCurrentInstance","signature":"func (g *Cloud) isCurrentInstance(instanceID string) bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// isCurrentInstance uses metadata server to check if specified\n// instanceID matches current machine's instanceID\nfunc (g *Cloud) isCurrentInstance(instanceID string) bool {\n\tcurrentInstanceID, err := getInstanceIDViaMetadata()\n\tif err != nil {\n\t\t// Log and swallow error\n\t\tklog.Errorf(\"Failed to fetch instanceID via Metadata: %v\", err)\n\t\treturn false\n\t}\n\n\treturn currentInstanceID == canonicalizeInstanceName(instanceID)\n}","line":{"from":702,"to":713}} {"id":100034258,"name":"computeHostTags","signature":"func (g *Cloud) computeHostTags(hosts []*gceInstance) ([]string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// ComputeHostTags grabs all tags from all instances being added to the pool.\n// * The longest tag that is a prefix of the instance name is used\n// * If any instance has no matching prefix tag, return error\n// Invoking this method to get host tags is risky since it depends on the\n// format of the host names in the cluster. Only use it as a fallback if\n// gce.nodeTags is unspecified\nfunc (g *Cloud) computeHostTags(hosts []*gceInstance) ([]string, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\t// TODO: We could store the tags in gceInstance, so we could have already fetched it\n\thostNamesByZone := make(map[string]map[string]bool) // map of zones -\u003e map of names -\u003e bool (for easy lookup)\n\tnodeInstancePrefix := g.nodeInstancePrefix\n\tfor _, host := range hosts {\n\t\tif !strings.HasPrefix(host.Name, g.nodeInstancePrefix) {\n\t\t\tklog.Warningf(\"instance %v does not conform to prefix '%s', ignoring filter\", host, g.nodeInstancePrefix)\n\t\t\tnodeInstancePrefix = \"\"\n\t\t}\n\n\t\tz, ok := hostNamesByZone[host.Zone]\n\t\tif !ok {\n\t\t\tz = make(map[string]bool)\n\t\t\thostNamesByZone[host.Zone] = z\n\t\t}\n\t\tz[host.Name] = true\n\t}\n\n\ttags := sets.NewString()\n\n\tfilt := filter.None\n\tif nodeInstancePrefix != \"\" {\n\t\tfilt = filter.Regexp(\"name\", nodeInstancePrefix+\".*\")\n\t}\n\tfor zone, hostNames := range hostNamesByZone {\n\t\tinstances, err := g.c.Instances().List(ctx, zone, filt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, instance := range instances {\n\t\t\tif !hostNames[instance.Name] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlongestTag := \"\"\n\t\t\tfor _, tag := range instance.Tags.Items {\n\t\t\t\tif strings.HasPrefix(instance.Name, tag) \u0026\u0026 len(tag) \u003e len(longestTag) {\n\t\t\t\t\tlongestTag = tag\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(longestTag) \u003e 0 {\n\t\t\t\ttags.Insert(longestTag)\n\t\t\t} else {\n\t\t\t\treturn nil, fmt.Errorf(\"could not find any tag that is a prefix of instance name for instance %s\", instance.Name)\n\t\t\t}\n\t\t}\n\t}\n\tif len(tags) == 0 {\n\t\treturn nil, fmt.Errorf(\"no instances found\")\n\t}\n\treturn tags.List(), nil\n}","line":{"from":715,"to":774}} {"id":100034259,"name":"GetNodeTags","signature":"func (g *Cloud) GetNodeTags(nodeNames []string) ([]string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_instances.go","code":"// GetNodeTags will first try returning the list of tags specified in GCE cloud Configuration.\n// If they weren't provided, it'll compute the host tags with the given hostnames. If the list\n// of hostnames has not changed, a cached set of nodetags are returned.\nfunc (g *Cloud) GetNodeTags(nodeNames []string) ([]string, error) {\n\t// If nodeTags were specified through configuration, use them\n\tif len(g.nodeTags) \u003e 0 {\n\t\treturn g.nodeTags, nil\n\t}\n\n\tg.computeNodeTagLock.Lock()\n\tdefer g.computeNodeTagLock.Unlock()\n\n\t// Early return if hosts have not changed\n\thosts := sets.NewString(nodeNames...)\n\tif hosts.Equal(g.lastKnownNodeNames) {\n\t\treturn g.lastComputedNodeTags, nil\n\t}\n\n\t// Get GCE instance data by hostname\n\tinstances, err := g.getInstancesByNames(nodeNames)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Determine list of host tags\n\ttags, err := g.computeHostTags(instances)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Save the list of tags\n\tg.lastKnownNodeNames = hosts\n\tg.lastComputedNodeTags = tags\n\treturn tags, nil\n}","line":{"from":776,"to":810}} {"id":100034260,"name":"init","signature":"func init()","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer.go","code":"func init() {\n\tvar err error\n\t// L3/4 health checkers have client addresses within these known CIDRs.\n\tl4LbSrcRngsFlag.ipn, err = netutils.ParseIPNets([]string{\"130.211.0.0/22\", \"35.191.0.0/16\", \"209.85.152.0/22\", \"209.85.204.0/22\"}...)\n\tif err != nil {\n\t\tpanic(\"Incorrect default GCE L3/4 source ranges\")\n\t}\n\t// L7 health checkers have client addresses within these known CIDRs.\n\tl7lbSrcRngsFlag.ipn, err = netutils.ParseIPNets([]string{\"130.211.0.0/22\", \"35.191.0.0/16\"}...)\n\tif err != nil {\n\t\tpanic(\"Incorrect default GCE L7 source ranges\")\n\t}\n\n\tflag.Var(\u0026l4LbSrcRngsFlag, \"cloud-provider-gce-lb-src-cidrs\", \"CIDRs opened in GCE firewall for L4 LB traffic proxy \u0026 health checks\")\n\tflag.Var(\u0026l7lbSrcRngsFlag, \"cloud-provider-gce-l7lb-src-cidrs\", \"CIDRs opened in GCE firewall for L7 LB traffic proxy \u0026 health checks\")\n}","line":{"from":50,"to":65}} {"id":100034261,"name":"String","signature":"func (c *cidrs) String() string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer.go","code":"// String is the method to format the flag's value, part of the flag.Value interface.\nfunc (c *cidrs) String() string {\n\ts := c.ipn.StringSlice()\n\tsort.Strings(s)\n\treturn strings.Join(s, \",\")\n}","line":{"from":67,"to":72}} {"id":100034262,"name":"Set","signature":"func (c *cidrs) Set(value string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer.go","code":"// Set supports a value of CSV or the flag repeated multiple times\nfunc (c *cidrs) Set(value string) error {\n\t// On first Set(), clear the original defaults\n\tif !c.isSet {\n\t\tc.isSet = true\n\t\tc.ipn = make(netutils.IPNetSet)\n\t} else {\n\t\treturn fmt.Errorf(\"GCE LB CIDRs have already been set\")\n\t}\n\n\tfor _, cidr := range strings.Split(value, \",\") {\n\t\t_, ipnet, err := netutils.ParseCIDRSloppy(cidr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.ipn.Insert(ipnet)\n\t}\n\treturn nil\n}","line":{"from":74,"to":93}} {"id":100034263,"name":"L4LoadBalancerSrcRanges","signature":"func L4LoadBalancerSrcRanges() []string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer.go","code":"// L4LoadBalancerSrcRanges contains the ranges of ips used by the L3/L4 GCE load balancers\n// for proxying client requests and performing health checks.\nfunc L4LoadBalancerSrcRanges() []string {\n\treturn l4LbSrcRngsFlag.ipn.StringSlice()\n}","line":{"from":95,"to":99}} {"id":100034264,"name":"L7LoadBalancerSrcRanges","signature":"func L7LoadBalancerSrcRanges() []string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer.go","code":"// L7LoadBalancerSrcRanges contains the ranges of ips used by the GCE load balancers L7\n// for proxying client requests and performing health checks.\nfunc L7LoadBalancerSrcRanges() []string {\n\treturn l7lbSrcRngsFlag.ipn.StringSlice()\n}","line":{"from":101,"to":105}} {"id":100034265,"name":"GetLoadBalancer","signature":"func (g *Cloud) GetLoadBalancer(ctx context.Context, clusterName string, svc *v1.Service) (*v1.LoadBalancerStatus, bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer.go","code":"// GetLoadBalancer is an implementation of LoadBalancer.GetLoadBalancer\nfunc (g *Cloud) GetLoadBalancer(ctx context.Context, clusterName string, svc *v1.Service) (*v1.LoadBalancerStatus, bool, error) {\n\tloadBalancerName := g.GetLoadBalancerName(ctx, clusterName, svc)\n\tfwd, err := g.GetRegionForwardingRule(loadBalancerName, g.region)\n\tif err == nil {\n\t\tstatus := \u0026v1.LoadBalancerStatus{}\n\t\tstatus.Ingress = []v1.LoadBalancerIngress{{IP: fwd.IPAddress}}\n\n\t\treturn status, true, nil\n\t}\n\t// Checking for finalizer is more accurate because controller restart could happen in the middle of resource\n\t// deletion. So even though forwarding rule was deleted, cleanup might not have been complete.\n\tif hasFinalizer(svc, ILBFinalizerV1) {\n\t\treturn \u0026v1.LoadBalancerStatus{}, true, nil\n\t}\n\treturn nil, false, ignoreNotFound(err)\n}","line":{"from":107,"to":123}} {"id":100034266,"name":"GetLoadBalancerName","signature":"func (g *Cloud) GetLoadBalancerName(ctx context.Context, clusterName string, svc *v1.Service) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer.go","code":"// GetLoadBalancerName is an implementation of LoadBalancer.GetLoadBalancerName.\nfunc (g *Cloud) GetLoadBalancerName(ctx context.Context, clusterName string, svc *v1.Service) string {\n\t// TODO: replace DefaultLoadBalancerName to generate more meaningful loadbalancer names.\n\treturn cloudprovider.DefaultLoadBalancerName(svc)\n}","line":{"from":125,"to":129}} {"id":100034267,"name":"EnsureLoadBalancer","signature":"func (g *Cloud) EnsureLoadBalancer(ctx context.Context, clusterName string, svc *v1.Service, nodes []*v1.Node) (*v1.LoadBalancerStatus, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer.go","code":"// EnsureLoadBalancer is an implementation of LoadBalancer.EnsureLoadBalancer.\nfunc (g *Cloud) EnsureLoadBalancer(ctx context.Context, clusterName string, svc *v1.Service, nodes []*v1.Node) (*v1.LoadBalancerStatus, error) {\n\tloadBalancerName := g.GetLoadBalancerName(ctx, clusterName, svc)\n\tdesiredScheme := getSvcScheme(svc)\n\tclusterID, err := g.ClusterID.GetID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Services with multiples protocols are not supported by this controller, warn the users and sets\n\t// the corresponding Service Status Condition.\n\t// https://github.com/kubernetes/enhancements/tree/master/keps/sig-network/1435-mixed-protocol-lb\n\tif err := checkMixedProtocol(svc.Spec.Ports); err != nil {\n\t\tif hasLoadBalancerPortsError(svc) {\n\t\t\treturn nil, err\n\t\t}\n\t\tklog.Warningf(\"Ignoring service %s/%s using different ports protocols\", svc.Namespace, svc.Name)\n\t\tg.eventRecorder.Event(svc, v1.EventTypeWarning, v1.LoadBalancerPortsErrorReason, \"LoadBalancers with multiple protocols are not supported.\")\n\t\tsvcApplyStatus := corev1apply.ServiceStatus().WithConditions(\n\t\t\tmetav1apply.Condition().\n\t\t\t\tWithType(v1.LoadBalancerPortsError).\n\t\t\t\tWithStatus(metav1.ConditionTrue).\n\t\t\t\tWithReason(v1.LoadBalancerPortsErrorReason).\n\t\t\t\tWithMessage(\"LoadBalancer with multiple protocols are not supported\"))\n\t\tsvcApply := corev1apply.Service(svc.Name, svc.Namespace).WithStatus(svcApplyStatus)\n\t\tif _, errApply := g.client.CoreV1().Services(svc.Namespace).ApplyStatus(ctx, svcApply, metav1.ApplyOptions{FieldManager: \"gce-legacy-cloud-controller\", Force: true}); errApply != nil {\n\t\t\treturn nil, errApply\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tklog.V(4).Infof(\"EnsureLoadBalancer(%v, %v, %v, %v, %v): ensure %v loadbalancer\", clusterName, svc.Namespace, svc.Name, loadBalancerName, g.region, desiredScheme)\n\n\texistingFwdRule, err := g.GetRegionForwardingRule(loadBalancerName, g.region)\n\tif err != nil \u0026\u0026 !isNotFound(err) {\n\t\treturn nil, err\n\t}\n\n\tif existingFwdRule != nil {\n\t\texistingScheme := cloud.LbScheme(strings.ToUpper(existingFwdRule.LoadBalancingScheme))\n\n\t\t// If the loadbalancer type changes between INTERNAL and EXTERNAL, the old load balancer should be deleted.\n\t\tif existingScheme != desiredScheme {\n\t\t\tklog.V(4).Infof(\"EnsureLoadBalancer(%v, %v, %v, %v, %v): deleting existing %v loadbalancer\", clusterName, svc.Namespace, svc.Name, loadBalancerName, g.region, existingScheme)\n\t\t\tswitch existingScheme {\n\t\t\tcase cloud.SchemeInternal:\n\t\t\t\terr = g.ensureInternalLoadBalancerDeleted(clusterName, clusterID, svc)\n\t\t\tdefault:\n\t\t\t\terr = g.ensureExternalLoadBalancerDeleted(clusterName, clusterID, svc)\n\t\t\t}\n\t\t\tklog.V(4).Infof(\"EnsureLoadBalancer(%v, %v, %v, %v, %v): done deleting existing %v loadbalancer. err: %v\", clusterName, svc.Namespace, svc.Name, loadBalancerName, g.region, existingScheme, err)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t// Assume the ensureDeleted function successfully deleted the forwarding rule.\n\t\t\texistingFwdRule = nil\n\t\t}\n\t}\n\n\tvar status *v1.LoadBalancerStatus\n\tswitch desiredScheme {\n\tcase cloud.SchemeInternal:\n\t\tstatus, err = g.ensureInternalLoadBalancer(clusterName, clusterID, svc, existingFwdRule, nodes)\n\tdefault:\n\t\tstatus, err = g.ensureExternalLoadBalancer(clusterName, clusterID, svc, existingFwdRule, nodes)\n\t}\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to EnsureLoadBalancer(%s, %s, %s, %s, %s), err: %v\", clusterName, svc.Namespace, svc.Name, loadBalancerName, g.region, err)\n\t\treturn status, err\n\t}\n\tklog.V(4).Infof(\"EnsureLoadBalancer(%s, %s, %s, %s, %s): done ensuring loadbalancer.\", clusterName, svc.Namespace, svc.Name, loadBalancerName, g.region)\n\treturn status, err\n}","line":{"from":131,"to":204}} {"id":100034268,"name":"UpdateLoadBalancer","signature":"func (g *Cloud) UpdateLoadBalancer(ctx context.Context, clusterName string, svc *v1.Service, nodes []*v1.Node) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer.go","code":"// UpdateLoadBalancer is an implementation of LoadBalancer.UpdateLoadBalancer.\nfunc (g *Cloud) UpdateLoadBalancer(ctx context.Context, clusterName string, svc *v1.Service, nodes []*v1.Node) error {\n\tloadBalancerName := g.GetLoadBalancerName(ctx, clusterName, svc)\n\tscheme := getSvcScheme(svc)\n\tclusterID, err := g.ClusterID.GetID()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Services with multiples protocols are not supported by this controller, warn the users and sets\n\t// the corresponding Service Status Condition, but keep processing the Update to not break upgrades.\n\t// https://github.com/kubernetes/enhancements/tree/master/keps/sig-network/1435-mixed-protocol-lb\n\tif err := checkMixedProtocol(svc.Spec.Ports); err != nil \u0026\u0026 !hasLoadBalancerPortsError(svc) {\n\t\tklog.Warningf(\"Ignoring update for service %s/%s using different ports protocols\", svc.Namespace, svc.Name)\n\t\tg.eventRecorder.Event(svc, v1.EventTypeWarning, v1.LoadBalancerPortsErrorReason, \"LoadBalancer with multiple protocols are not supported.\")\n\t\tsvcApplyStatus := corev1apply.ServiceStatus().WithConditions(\n\t\t\tmetav1apply.Condition().\n\t\t\t\tWithType(v1.LoadBalancerPortsError).\n\t\t\t\tWithStatus(metav1.ConditionTrue).\n\t\t\t\tWithReason(v1.LoadBalancerPortsErrorReason).\n\t\t\t\tWithMessage(\"LoadBalancer with multiple protocols are not supported\"))\n\t\tsvcApply := corev1apply.Service(svc.Name, svc.Namespace).WithStatus(svcApplyStatus)\n\t\tif _, errApply := g.client.CoreV1().Services(svc.Namespace).ApplyStatus(ctx, svcApply, metav1.ApplyOptions{FieldManager: \"gce-legacy-cloud-controller\", Force: true}); errApply != nil {\n\t\t\t// the error is retried by the controller loop\n\t\t\treturn errApply\n\t\t}\n\t}\n\n\tklog.V(4).Infof(\"UpdateLoadBalancer(%v, %v, %v, %v, %v): updating with %d nodes\", clusterName, svc.Namespace, svc.Name, loadBalancerName, g.region, len(nodes))\n\n\tswitch scheme {\n\tcase cloud.SchemeInternal:\n\t\terr = g.updateInternalLoadBalancer(clusterName, clusterID, svc, nodes)\n\tdefault:\n\t\terr = g.updateExternalLoadBalancer(clusterName, svc, nodes)\n\t}\n\tklog.V(4).Infof(\"UpdateLoadBalancer(%v, %v, %v, %v, %v): done updating. err: %v\", clusterName, svc.Namespace, svc.Name, loadBalancerName, g.region, err)\n\treturn err\n}","line":{"from":206,"to":244}} {"id":100034269,"name":"EnsureLoadBalancerDeleted","signature":"func (g *Cloud) EnsureLoadBalancerDeleted(ctx context.Context, clusterName string, svc *v1.Service) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer.go","code":"// EnsureLoadBalancerDeleted is an implementation of LoadBalancer.EnsureLoadBalancerDeleted.\nfunc (g *Cloud) EnsureLoadBalancerDeleted(ctx context.Context, clusterName string, svc *v1.Service) error {\n\tloadBalancerName := g.GetLoadBalancerName(ctx, clusterName, svc)\n\tscheme := getSvcScheme(svc)\n\tclusterID, err := g.ClusterID.GetID()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tklog.V(4).Infof(\"EnsureLoadBalancerDeleted(%v, %v, %v, %v, %v): deleting loadbalancer\", clusterName, svc.Namespace, svc.Name, loadBalancerName, g.region)\n\n\tswitch scheme {\n\tcase cloud.SchemeInternal:\n\t\terr = g.ensureInternalLoadBalancerDeleted(clusterName, clusterID, svc)\n\tdefault:\n\t\terr = g.ensureExternalLoadBalancerDeleted(clusterName, clusterID, svc)\n\t}\n\tklog.V(4).Infof(\"EnsureLoadBalancerDeleted(%v, %v, %v, %v, %v): done deleting loadbalancer. err: %v\", clusterName, svc.Namespace, svc.Name, loadBalancerName, g.region, err)\n\treturn err\n}","line":{"from":246,"to":265}} {"id":100034270,"name":"getSvcScheme","signature":"func getSvcScheme(svc *v1.Service) cloud.LbScheme","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer.go","code":"func getSvcScheme(svc *v1.Service) cloud.LbScheme {\n\tif t := GetLoadBalancerAnnotationType(svc); t == LBTypeInternal {\n\t\treturn cloud.SchemeInternal\n\t}\n\treturn cloud.SchemeExternal\n}","line":{"from":267,"to":272}} {"id":100034271,"name":"checkMixedProtocol","signature":"func checkMixedProtocol(ports []v1.ServicePort) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer.go","code":"// checkMixedProtocol checks if the Service Ports uses different protocols,\n// per examples, TCP and UDP.\nfunc checkMixedProtocol(ports []v1.ServicePort) error {\n\tif len(ports) == 0 {\n\t\treturn nil\n\t}\n\n\tfirstProtocol := ports[0].Protocol\n\tfor _, port := range ports[1:] {\n\t\tif port.Protocol != firstProtocol {\n\t\t\treturn fmt.Errorf(\"mixed protocol is not supported for LoadBalancer\")\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":274,"to":288}} {"id":100034272,"name":"hasLoadBalancerPortsError","signature":"func hasLoadBalancerPortsError(service *v1.Service) bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer.go","code":"// hasLoadBalancerPortsError checks if the Service has the LoadBalancerPortsError set to True\nfunc hasLoadBalancerPortsError(service *v1.Service) bool {\n\tif service == nil {\n\t\treturn false\n\t}\n\n\tfor _, cond := range service.Status.Conditions {\n\t\tif cond.Type == v1.LoadBalancerPortsError {\n\t\t\treturn cond.Status == metav1.ConditionTrue\n\t\t}\n\t}\n\treturn false\n}","line":{"from":290,"to":302}} {"id":100034273,"name":"ensureExternalLoadBalancer","signature":"func (g *Cloud) ensureExternalLoadBalancer(clusterName string, clusterID string, apiService *v1.Service, existingFwdRule *compute.ForwardingRule, nodes []*v1.Node) (*v1.LoadBalancerStatus, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"// ensureExternalLoadBalancer is the external implementation of LoadBalancer.EnsureLoadBalancer.\n// Our load balancers in GCE consist of four separate GCE resources - a static\n// IP address, a firewall rule, a target pool, and a forwarding rule. This\n// function has to manage all of them.\n//\n// Due to an interesting series of design decisions, this handles both creating\n// new load balancers and updating existing load balancers, recognizing when\n// each is needed.\nfunc (g *Cloud) ensureExternalLoadBalancer(clusterName string, clusterID string, apiService *v1.Service, existingFwdRule *compute.ForwardingRule, nodes []*v1.Node) (*v1.LoadBalancerStatus, error) {\n\t// Skip service handling if it uses Regional Backend Services and handled by other controllers\n\tif usesL4RBS(apiService, existingFwdRule) {\n\t\treturn nil, cloudprovider.ImplementedElsewhere\n\t}\n\n\tif len(nodes) == 0 {\n\t\treturn nil, fmt.Errorf(errStrLbNoHosts)\n\t}\n\n\thostNames := nodeNames(nodes)\n\tsupportsNodesHealthCheck := supportsNodesHealthCheck(nodes)\n\thosts, err := g.getInstancesByNames(hostNames)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tloadBalancerName := g.GetLoadBalancerName(context.TODO(), clusterName, apiService)\n\trequestedIP := apiService.Spec.LoadBalancerIP\n\tports := apiService.Spec.Ports\n\tportStr := []string{}\n\tfor _, p := range apiService.Spec.Ports {\n\t\tportStr = append(portStr, fmt.Sprintf(\"%s/%d\", p.Protocol, p.Port))\n\t}\n\n\tserviceName := types.NamespacedName{Namespace: apiService.Namespace, Name: apiService.Name}\n\tlbRefStr := fmt.Sprintf(\"%v(%v)\", loadBalancerName, serviceName)\n\tklog.V(2).Infof(\"ensureExternalLoadBalancer(%s, %v, %v, %v, %v, %v)\", lbRefStr, g.region, requestedIP, portStr, hostNames, apiService.Annotations)\n\n\t// Check the current and the desired network tiers. If they do not match,\n\t// tear down the existing resources with the wrong tier.\n\tnetTier, err := g.getServiceNetworkTier(apiService)\n\tif err != nil {\n\t\tklog.Errorf(\"ensureExternalLoadBalancer(%s): Failed to get the desired network tier: %v.\", lbRefStr, err)\n\t\treturn nil, err\n\t}\n\tklog.V(4).Infof(\"ensureExternalLoadBalancer(%s): Desired network tier %q.\", lbRefStr, netTier)\n\t// TODO: distinguish between unspecified and specified network tiers annotation properly in forwardingrule creation\n\t// Only delete ForwardingRule when network tier annotation is specified, otherwise leave it only to avoid wrongful\n\t// deletion against user intention when network tier annotation is not specified.\n\tif _, ok := apiService.Annotations[NetworkTierAnnotationKey]; ok {\n\t\tg.deleteWrongNetworkTieredResources(loadBalancerName, lbRefStr, netTier)\n\t}\n\n\t// Check if the forwarding rule exists, and if so, what its IP is.\n\tfwdRuleExists, fwdRuleNeedsUpdate, fwdRuleIP, err := g.forwardingRuleNeedsUpdate(loadBalancerName, g.region, requestedIP, ports)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !fwdRuleExists {\n\t\tklog.V(2).Infof(\"ensureExternalLoadBalancer(%s): Forwarding rule %v doesn't exist.\", lbRefStr, loadBalancerName)\n\t}\n\n\t// Make sure we know which IP address will be used and have properly reserved\n\t// it as static before moving forward with the rest of our operations.\n\t//\n\t// We use static IP addresses when updating a load balancer to ensure that we\n\t// can replace the load balancer's other components without changing the\n\t// address its service is reachable on. We do it this way rather than always\n\t// keeping the static IP around even though this is more complicated because\n\t// it makes it less likely that we'll run into quota issues. Only 7 static\n\t// IP addresses are allowed per region by default.\n\t//\n\t// We could let an IP be allocated for us when the forwarding rule is created,\n\t// but we need the IP to set up the firewall rule, and we want to keep the\n\t// forwarding rule creation as the last thing that needs to be done in this\n\t// function in order to maintain the invariant that \"if the forwarding rule\n\t// exists, the LB has been fully created\".\n\tipAddressToUse := \"\"\n\n\t// Through this process we try to keep track of whether it is safe to\n\t// release the IP that was allocated. If the user specifically asked for\n\t// an IP, we assume they are managing it themselves. Otherwise, we will\n\t// release the IP in case of early-terminating failure or upon successful\n\t// creating of the LB.\n\t// TODO(#36535): boil this logic down into a set of component functions\n\t// and key the flag values off of errors returned.\n\tisUserOwnedIP := false // if this is set, we never release the IP\n\tisSafeToReleaseIP := false\n\tdefer func() {\n\t\tif isUserOwnedIP {\n\t\t\treturn\n\t\t}\n\t\tif isSafeToReleaseIP {\n\t\t\tif err := g.DeleteRegionAddress(loadBalancerName, g.region); err != nil \u0026\u0026 !isNotFound(err) {\n\t\t\t\tklog.Errorf(\"ensureExternalLoadBalancer(%s): Failed to release static IP %s in region %v: %v.\", lbRefStr, ipAddressToUse, g.region, err)\n\t\t\t} else if isNotFound(err) {\n\t\t\t\tklog.V(2).Infof(\"ensureExternalLoadBalancer(%s): IP address %s is not reserved.\", lbRefStr, ipAddressToUse)\n\t\t\t} else {\n\t\t\t\tklog.Infof(\"ensureExternalLoadBalancer(%s): Released static IP %s.\", lbRefStr, ipAddressToUse)\n\t\t\t}\n\t\t} else {\n\t\t\tklog.Warningf(\"ensureExternalLoadBalancer(%s): Orphaning static IP %s in region %v: %v.\", lbRefStr, ipAddressToUse, g.region, err)\n\t\t}\n\t}()\n\n\tif requestedIP != \"\" {\n\t\t// If user requests a specific IP address, verify first. No mutation to\n\t\t// the GCE resources will be performed in the verification process.\n\t\tisUserOwnedIP, err = verifyUserRequestedIP(g, g.region, requestedIP, fwdRuleIP, lbRefStr, netTier)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tipAddressToUse = requestedIP\n\t}\n\n\tif !isUserOwnedIP {\n\t\t// If we are not using the user-owned IP, either promote the\n\t\t// emphemeral IP used by the fwd rule, or create a new static IP.\n\t\tipAddr, existed, err := ensureStaticIP(g, loadBalancerName, serviceName.String(), g.region, fwdRuleIP, netTier)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to ensure a static IP for load balancer (%s): %v\", lbRefStr, err)\n\t\t}\n\t\tklog.Infof(\"ensureExternalLoadBalancer(%s): Ensured IP address %s (tier: %s).\", lbRefStr, ipAddr, netTier)\n\t\t// If the IP was not owned by the user, but it already existed, it\n\t\t// could indicate that the previous update cycle failed. We can use\n\t\t// this IP and try to run through the process again, but we should\n\t\t// not release the IP unless it is explicitly flagged as OK.\n\t\tisSafeToReleaseIP = !existed\n\t\tipAddressToUse = ipAddr\n\t}\n\n\t// Deal with the firewall next. The reason we do this here rather than last\n\t// is because the forwarding rule is used as the indicator that the load\n\t// balancer is fully created - it's what getLoadBalancer checks for.\n\t// Check if user specified the allow source range\n\tsourceRanges, err := servicehelpers.GetLoadBalancerSourceRanges(apiService)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfirewallExists, firewallNeedsUpdate, err := g.firewallNeedsUpdate(loadBalancerName, serviceName.String(), ipAddressToUse, ports, sourceRanges)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif firewallNeedsUpdate {\n\t\tdesc := makeFirewallDescription(serviceName.String(), ipAddressToUse)\n\t\t// Unlike forwarding rules and target pools, firewalls can be updated\n\t\t// without needing to be deleted and recreated.\n\t\tif firewallExists {\n\t\t\tklog.Infof(\"ensureExternalLoadBalancer(%s): Updating firewall.\", lbRefStr)\n\t\t\tif err := g.updateFirewall(apiService, MakeFirewallName(loadBalancerName), desc, ipAddressToUse, sourceRanges, ports, hosts); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tklog.Infof(\"ensureExternalLoadBalancer(%s): Updated firewall.\", lbRefStr)\n\t\t} else {\n\t\t\tklog.Infof(\"ensureExternalLoadBalancer(%s): Creating firewall.\", lbRefStr)\n\t\t\tif err := g.createFirewall(apiService, MakeFirewallName(loadBalancerName), desc, ipAddressToUse, sourceRanges, ports, hosts); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tklog.Infof(\"ensureExternalLoadBalancer(%s): Created firewall.\", lbRefStr)\n\t\t}\n\t}\n\n\ttpExists, tpNeedsRecreation, err := g.targetPoolNeedsRecreation(loadBalancerName, g.region, apiService.Spec.SessionAffinity)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !tpExists {\n\t\tklog.Infof(\"ensureExternalLoadBalancer(%s): Target pool for service doesn't exist.\", lbRefStr)\n\t}\n\n\t// Check which health check needs to create and which health check needs to delete.\n\t// Health check management is coupled with target pool operation to prevent leaking.\n\tvar hcToCreate, hcToDelete *compute.HttpHealthCheck\n\thcLocalTrafficExisting, err := g.GetHTTPHealthCheck(loadBalancerName)\n\tif err != nil \u0026\u0026 !isHTTPErrorCode(err, http.StatusNotFound) {\n\t\treturn nil, fmt.Errorf(\"error checking HTTP health check for load balancer (%s): %v\", lbRefStr, err)\n\t}\n\tif path, healthCheckNodePort := servicehelpers.GetServiceHealthCheckPathPort(apiService); path != \"\" {\n\t\tklog.V(4).Infof(\"ensureExternalLoadBalancer(%s): Service needs local traffic health checks on: %d%s.\", lbRefStr, healthCheckNodePort, path)\n\t\tif hcLocalTrafficExisting == nil {\n\t\t\t// This logic exists to detect a transition for non-OnlyLocal to OnlyLocal service\n\t\t\t// turn on the tpNeedsRecreation flag to delete/recreate fwdrule/tpool updating the\n\t\t\t// target pool to use local traffic health check.\n\t\t\tklog.V(2).Infof(\"ensureExternalLoadBalancer(%s): Updating from nodes health checks to local traffic health checks.\", lbRefStr)\n\t\t\tif supportsNodesHealthCheck {\n\t\t\t\thcToDelete = makeHTTPHealthCheck(MakeNodesHealthCheckName(clusterID), GetNodesHealthCheckPath(), GetNodesHealthCheckPort())\n\t\t\t}\n\t\t\ttpNeedsRecreation = true\n\t\t}\n\t\thcToCreate = makeHTTPHealthCheck(loadBalancerName, path, healthCheckNodePort)\n\t} else {\n\t\tklog.V(4).Infof(\"ensureExternalLoadBalancer(%s): Service needs nodes health checks.\", lbRefStr)\n\t\tif hcLocalTrafficExisting != nil {\n\t\t\t// This logic exists to detect a transition from OnlyLocal to non-OnlyLocal service\n\t\t\t// and turn on the tpNeedsRecreation flag to delete/recreate fwdrule/tpool updating the\n\t\t\t// target pool to use nodes health check.\n\t\t\tklog.V(2).Infof(\"ensureExternalLoadBalancer(%s): Updating from local traffic health checks to nodes health checks.\", lbRefStr)\n\t\t\thcToDelete = hcLocalTrafficExisting\n\t\t\ttpNeedsRecreation = true\n\t\t}\n\t\tif supportsNodesHealthCheck {\n\t\t\thcToCreate = makeHTTPHealthCheck(MakeNodesHealthCheckName(clusterID), GetNodesHealthCheckPath(), GetNodesHealthCheckPort())\n\t\t}\n\t}\n\t// Now we get to some slightly more interesting logic.\n\t// First, neither target pools nor forwarding rules can be updated in place -\n\t// they have to be deleted and recreated.\n\t// Second, forwarding rules are layered on top of target pools in that you\n\t// can't delete a target pool that's currently in use by a forwarding rule.\n\t// Thus, we have to tear down the forwarding rule if either it or the target\n\t// pool needs to be updated.\n\tif fwdRuleExists \u0026\u0026 (fwdRuleNeedsUpdate || tpNeedsRecreation) {\n\t\t// Begin critical section. If we have to delete the forwarding rule,\n\t\t// and something should fail before we recreate it, don't release the\n\t\t// IP. That way we can come back to it later.\n\t\tisSafeToReleaseIP = false\n\t\tif err := g.DeleteRegionForwardingRule(loadBalancerName, g.region); err != nil \u0026\u0026 !isNotFound(err) {\n\t\t\treturn nil, fmt.Errorf(\"failed to delete existing forwarding rule for load balancer (%s) update: %v\", lbRefStr, err)\n\t\t}\n\t\tklog.Infof(\"ensureExternalLoadBalancer(%s): Deleted forwarding rule.\", lbRefStr)\n\t}\n\n\tif err := g.ensureTargetPoolAndHealthCheck(tpExists, tpNeedsRecreation, apiService, loadBalancerName, clusterID, ipAddressToUse, hosts, hcToCreate, hcToDelete); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tpNeedsRecreation || fwdRuleNeedsUpdate {\n\t\tklog.Infof(\"ensureExternalLoadBalancer(%s): Creating forwarding rule, IP %s (tier: %s).\", lbRefStr, ipAddressToUse, netTier)\n\t\tif err := createForwardingRule(g, loadBalancerName, serviceName.String(), g.region, ipAddressToUse, g.targetPoolURL(loadBalancerName), ports, netTier); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to create forwarding rule for load balancer (%s): %v\", lbRefStr, err)\n\t\t}\n\t\t// End critical section. It is safe to release the static IP (which\n\t\t// just demotes it to ephemeral) now that it is attached. In the case\n\t\t// of a user-requested IP, the \"is user-owned\" flag will be set,\n\t\t// preventing it from actually being released.\n\t\tisSafeToReleaseIP = true\n\t\tklog.Infof(\"ensureExternalLoadBalancer(%s): Created forwarding rule, IP %s.\", lbRefStr, ipAddressToUse)\n\t}\n\n\tstatus := \u0026v1.LoadBalancerStatus{}\n\tstatus.Ingress = []v1.LoadBalancerIngress{{IP: ipAddressToUse}}\n\n\treturn status, nil\n}","line":{"from":47,"to":291}} {"id":100034274,"name":"updateExternalLoadBalancer","signature":"func (g *Cloud) updateExternalLoadBalancer(clusterName string, service *v1.Service, nodes []*v1.Node) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"// updateExternalLoadBalancer is the external implementation of LoadBalancer.UpdateLoadBalancer.\nfunc (g *Cloud) updateExternalLoadBalancer(clusterName string, service *v1.Service, nodes []*v1.Node) error {\n\t// Skip service update if it uses Regional Backend Services and handled by other controllers\n\tif usesL4RBS(service, nil) {\n\t\treturn cloudprovider.ImplementedElsewhere\n\t}\n\n\thosts, err := g.getInstancesByNames(nodeNames(nodes))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tloadBalancerName := g.GetLoadBalancerName(context.TODO(), clusterName, service)\n\treturn g.updateTargetPool(loadBalancerName, hosts)\n}","line":{"from":293,"to":307}} {"id":100034275,"name":"ensureExternalLoadBalancerDeleted","signature":"func (g *Cloud) ensureExternalLoadBalancerDeleted(clusterName, clusterID string, service *v1.Service) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"// ensureExternalLoadBalancerDeleted is the external implementation of LoadBalancer.EnsureLoadBalancerDeleted\nfunc (g *Cloud) ensureExternalLoadBalancerDeleted(clusterName, clusterID string, service *v1.Service) error {\n\t// Skip service deletion if it uses Regional Backend Services and handled by other controllers\n\tif usesL4RBS(service, nil) {\n\t\treturn cloudprovider.ImplementedElsewhere\n\t}\n\n\tloadBalancerName := g.GetLoadBalancerName(context.TODO(), clusterName, service)\n\tserviceName := types.NamespacedName{Namespace: service.Namespace, Name: service.Name}\n\tlbRefStr := fmt.Sprintf(\"%v(%v)\", loadBalancerName, serviceName)\n\n\tvar hcNames []string\n\tif path, _ := servicehelpers.GetServiceHealthCheckPathPort(service); path != \"\" {\n\t\thcToDelete, err := g.GetHTTPHealthCheck(loadBalancerName)\n\t\tif err != nil \u0026\u0026 !isHTTPErrorCode(err, http.StatusNotFound) {\n\t\t\tklog.Infof(\"ensureExternalLoadBalancerDeleted(%s): Failed to retrieve health check:%v.\", lbRefStr, err)\n\t\t\treturn err\n\t\t}\n\t\t// If we got 'StatusNotFound' LB was already deleted and it's safe to ignore.\n\t\tif err == nil {\n\t\t\thcNames = append(hcNames, hcToDelete.Name)\n\t\t}\n\t} else {\n\t\t// EnsureLoadBalancerDeleted() could be triggered by changing service from\n\t\t// LoadBalancer type to others. In this case we have no idea whether it was\n\t\t// using local traffic health check or nodes health check. Attempt to delete\n\t\t// both to prevent leaking.\n\t\thcNames = append(hcNames, loadBalancerName)\n\t\thcNames = append(hcNames, MakeNodesHealthCheckName(clusterID))\n\t}\n\n\terrs := utilerrors.AggregateGoroutines(\n\t\tfunc() error {\n\t\t\tklog.Infof(\"ensureExternalLoadBalancerDeleted(%s): Deleting firewall rule.\", lbRefStr)\n\t\t\tfwName := MakeFirewallName(loadBalancerName)\n\t\t\terr := ignoreNotFound(g.DeleteFirewall(fwName))\n\t\t\tif isForbidden(err) \u0026\u0026 g.OnXPN() {\n\t\t\t\tklog.V(4).Infof(\"ensureExternalLoadBalancerDeleted(%s): Do not have permission to delete firewall rule %v (on XPN). Raising event.\", lbRefStr, fwName)\n\t\t\t\tg.raiseFirewallChangeNeededEvent(service, FirewallToGCloudDeleteCmd(fwName, g.NetworkProjectID()))\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t},\n\t\t// Even though we don't hold on to static IPs for load balancers, it's\n\t\t// possible that EnsureLoadBalancer left one around in a failed\n\t\t// creation/update attempt, so make sure we clean it up here just in case.\n\t\tfunc() error {\n\t\t\tklog.Infof(\"ensureExternalLoadBalancerDeleted(%s): Deleting IP address.\", lbRefStr)\n\t\t\treturn ignoreNotFound(g.DeleteRegionAddress(loadBalancerName, g.region))\n\t\t},\n\t\tfunc() error {\n\t\t\tklog.Infof(\"ensureExternalLoadBalancerDeleted(%s): Deleting forwarding rule.\", lbRefStr)\n\t\t\t// The forwarding rule must be deleted before either the target pool can,\n\t\t\t// unfortunately, so we have to do these two serially.\n\t\t\tif err := ignoreNotFound(g.DeleteRegionForwardingRule(loadBalancerName, g.region)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tklog.Infof(\"ensureExternalLoadBalancerDeleted(%s): Deleting target pool.\", lbRefStr)\n\t\t\tif err := g.DeleteExternalTargetPoolAndChecks(service, loadBalancerName, g.region, clusterID, hcNames...); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t)\n\tif errs != nil {\n\t\treturn utilerrors.Flatten(errs)\n\t}\n\treturn nil\n}","line":{"from":309,"to":377}} {"id":100034276,"name":"DeleteExternalTargetPoolAndChecks","signature":"func (g *Cloud) DeleteExternalTargetPoolAndChecks(service *v1.Service, name, region, clusterID string, hcNames ...string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"// DeleteExternalTargetPoolAndChecks Deletes an external load balancer pool and verifies the operation\nfunc (g *Cloud) DeleteExternalTargetPoolAndChecks(service *v1.Service, name, region, clusterID string, hcNames ...string) error {\n\tserviceName := types.NamespacedName{Namespace: service.Namespace, Name: service.Name}\n\tlbRefStr := fmt.Sprintf(\"%v(%v)\", name, serviceName)\n\n\tif err := g.DeleteTargetPool(name, region); err != nil \u0026\u0026 isHTTPErrorCode(err, http.StatusNotFound) {\n\t\tklog.Infof(\"DeleteExternalTargetPoolAndChecks(%v): Target pool already deleted. Continuing to delete other resources.\", lbRefStr)\n\t} else if err != nil {\n\t\tklog.Warningf(\"DeleteExternalTargetPoolAndChecks(%v): Failed to delete target pool, got error %s.\", lbRefStr, err.Error())\n\t\treturn err\n\t}\n\n\t// Deletion of health checks is allowed only after the TargetPool reference is deleted\n\tfor _, hcName := range hcNames {\n\t\tif err := func() error {\n\t\t\t// Check whether it is nodes health check, which has different name from the load-balancer.\n\t\t\tisNodesHealthCheck := hcName != name\n\t\t\tif isNodesHealthCheck {\n\t\t\t\t// Lock to prevent deleting necessary nodes health check before it gets attached\n\t\t\t\t// to target pool.\n\t\t\t\tg.sharedResourceLock.Lock()\n\t\t\t\tdefer g.sharedResourceLock.Unlock()\n\t\t\t}\n\t\t\tklog.Infof(\"DeleteExternalTargetPoolAndChecks(%v): Deleting health check %v.\", lbRefStr, hcName)\n\t\t\tif err := g.DeleteHTTPHealthCheck(hcName); err != nil {\n\t\t\t\t// Delete nodes health checks will fail if any other target pool is using it.\n\t\t\t\tif isInUsedByError(err) {\n\t\t\t\t\tklog.V(4).Infof(\"DeleteExternalTargetPoolAndChecks(%v): Health check %v is in used: %v.\", lbRefStr, hcName, err)\n\t\t\t\t\treturn nil\n\t\t\t\t} else if !isHTTPErrorCode(err, http.StatusNotFound) {\n\t\t\t\t\tklog.Warningf(\"DeleteExternalTargetPoolAndChecks(%v): Failed to delete health check %v: %v.\", lbRefStr, hcName, err)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t// StatusNotFound could happen when:\n\t\t\t\t// - This is the first attempt but we pass in a healthcheck that is already deleted\n\t\t\t\t// to prevent leaking.\n\t\t\t\t// - This is the first attempt but user manually deleted the heathcheck.\n\t\t\t\t// - This is a retry and in previous round we failed to delete the healthcheck firewall\n\t\t\t\t// after deleted the healthcheck.\n\t\t\t\t// We continue to delete the healthcheck firewall to prevent leaking.\n\t\t\t\tklog.V(4).Infof(\"DeleteExternalTargetPoolAndChecks(%v): Health check %v is already deleted.\", lbRefStr, hcName)\n\t\t\t}\n\t\t\t// If health check is deleted without error, it means no load-balancer is using it.\n\t\t\t// So we should delete the health check firewall as well.\n\t\t\tfwName := MakeHealthCheckFirewallName(clusterID, hcName, isNodesHealthCheck)\n\t\t\tklog.Infof(\"DeleteExternalTargetPoolAndChecks(%v): Deleting health check firewall %v.\", lbRefStr, fwName)\n\t\t\tif err := ignoreNotFound(g.DeleteFirewall(fwName)); err != nil {\n\t\t\t\tif isForbidden(err) \u0026\u0026 g.OnXPN() {\n\t\t\t\t\tklog.V(4).Infof(\"DeleteExternalTargetPoolAndChecks(%v): Do not have permission to delete firewall rule %v (on XPN). Raising event.\", lbRefStr, fwName)\n\t\t\t\t\tg.raiseFirewallChangeNeededEvent(service, FirewallToGCloudDeleteCmd(fwName, g.NetworkProjectID()))\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t}(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}","line":{"from":379,"to":440}} {"id":100034277,"name":"verifyUserRequestedIP","signature":"func verifyUserRequestedIP(s CloudAddressService, region, requestedIP, fwdRuleIP, lbRef string, desiredNetTier cloud.NetworkTier) (isUserOwnedIP bool, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"// verifyUserRequestedIP checks the user-provided IP to see whether it meets\n// all the expected attributes for the load balancer, and returns an error if\n// the verification failed. It also returns a boolean to indicate whether the\n// IP address is considered owned by the user (i.e., not managed by the\n// controller.\nfunc verifyUserRequestedIP(s CloudAddressService, region, requestedIP, fwdRuleIP, lbRef string, desiredNetTier cloud.NetworkTier) (isUserOwnedIP bool, err error) {\n\tif requestedIP == \"\" {\n\t\treturn false, nil\n\t}\n\t// If a specific IP address has been requested, we have to respect the\n\t// user's request and use that IP. If the forwarding rule was already using\n\t// a different IP, it will be harmlessly abandoned because it was only an\n\t// ephemeral IP (or it was a different static IP owned by the user, in which\n\t// case we shouldn't delete it anyway).\n\texistingAddress, err := s.GetRegionAddressByIP(region, requestedIP)\n\tif err != nil \u0026\u0026 !isNotFound(err) {\n\t\tklog.Errorf(\"verifyUserRequestedIP: failed to check whether the requested IP %q for LB %s exists: %v\", requestedIP, lbRef, err)\n\t\treturn false, err\n\t}\n\tif err == nil {\n\t\t// The requested IP is a static IP, owned and managed by the user.\n\n\t\t// Check if the network tier of the static IP matches the desired\n\t\t// network tier.\n\t\tnetTierStr, err := s.getNetworkTierFromAddress(existingAddress.Name, region)\n\t\tif err != nil {\n\t\t\treturn false, fmt.Errorf(\"failed to check the network tier of the IP %q: %v\", requestedIP, err)\n\t\t}\n\t\tnetTier := cloud.NetworkTierGCEValueToType(netTierStr)\n\t\tif netTier != desiredNetTier {\n\t\t\tklog.Errorf(\"verifyUserRequestedIP: requested static IP %q (name: %s) for LB %s has network tier %s, need %s.\", requestedIP, existingAddress.Name, lbRef, netTier, desiredNetTier)\n\t\t\treturn false, fmt.Errorf(\"requested IP %q belongs to the %s network tier; expected %s\", requestedIP, netTier, desiredNetTier)\n\t\t}\n\t\tklog.V(4).Infof(\"verifyUserRequestedIP: the requested static IP %q (name: %s, tier: %s) for LB %s exists.\", requestedIP, existingAddress.Name, netTier, lbRef)\n\t\treturn true, nil\n\t}\n\tif requestedIP == fwdRuleIP {\n\t\t// The requested IP is not a static IP, but is currently assigned\n\t\t// to this forwarding rule, so we can just use it.\n\t\tklog.V(4).Infof(\"verifyUserRequestedIP: the requested IP %q is not static, but is currently in use by for LB %s\", requestedIP, lbRef)\n\t\treturn false, nil\n\t}\n\t// The requested IP is not static and it is not assigned to the\n\t// current forwarding rule. It might be attached to a different\n\t// rule or it might not be part of this project at all. Either\n\t// way, we can't use it.\n\tklog.Errorf(\"verifyUserRequestedIP: requested IP %q for LB %s is neither static nor assigned to the LB\", requestedIP, lbRef)\n\treturn false, fmt.Errorf(\"requested ip %q is neither static nor assigned to the LB\", requestedIP)\n}","line":{"from":442,"to":490}} {"id":100034278,"name":"ensureTargetPoolAndHealthCheck","signature":"func (g *Cloud) ensureTargetPoolAndHealthCheck(tpExists, tpNeedsRecreation bool, svc *v1.Service, loadBalancerName, clusterID, ipAddressToUse string, hosts []*gceInstance, hcToCreate, hcToDelete *compute.HttpHealthCheck) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"func (g *Cloud) ensureTargetPoolAndHealthCheck(tpExists, tpNeedsRecreation bool, svc *v1.Service, loadBalancerName, clusterID, ipAddressToUse string, hosts []*gceInstance, hcToCreate, hcToDelete *compute.HttpHealthCheck) error {\n\tserviceName := types.NamespacedName{Namespace: svc.Namespace, Name: svc.Name}\n\tlbRefStr := fmt.Sprintf(\"%v(%v)\", loadBalancerName, serviceName)\n\n\tif tpExists \u0026\u0026 tpNeedsRecreation {\n\t\t// Pass healthchecks to DeleteExternalTargetPoolAndChecks to cleanup health checks after cleaning up the target pool itself.\n\t\tvar hcNames []string\n\t\tif hcToDelete != nil {\n\t\t\thcNames = append(hcNames, hcToDelete.Name)\n\t\t}\n\t\tif err := g.DeleteExternalTargetPoolAndChecks(svc, loadBalancerName, g.region, clusterID, hcNames...); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to delete existing target pool for load balancer (%s) update: %v\", lbRefStr, err)\n\t\t}\n\t\tklog.Infof(\"ensureTargetPoolAndHealthCheck(%s): Deleted target pool.\", lbRefStr)\n\t}\n\t// Once we've deleted the resources (if necessary), build them back up (or for\n\t// the first time if they're new).\n\tif tpNeedsRecreation {\n\t\tcreateInstances := hosts\n\t\tif len(hosts) \u003e maxTargetPoolCreateInstances {\n\t\t\tcreateInstances = createInstances[:maxTargetPoolCreateInstances]\n\t\t}\n\t\tif err := g.createTargetPoolAndHealthCheck(svc, loadBalancerName, serviceName.String(), ipAddressToUse, g.region, clusterID, createInstances, hcToCreate); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create target pool for load balancer (%s): %v\", lbRefStr, err)\n\t\t}\n\t\tif hcToCreate != nil {\n\t\t\tklog.Infof(\"ensureTargetPoolAndHealthCheck(%s): Created health checks %v.\", lbRefStr, hcToCreate.Name)\n\t\t}\n\t\tif len(hosts) \u003c= maxTargetPoolCreateInstances {\n\t\t\tklog.Infof(\"ensureTargetPoolAndHealthCheck(%s): Created target pool.\", lbRefStr)\n\t\t} else {\n\t\t\tklog.Infof(\"ensureTargetPoolAndHealthCheck(%s): Created initial target pool (now updating the remaining %d hosts).\", lbRefStr, len(hosts)-maxTargetPoolCreateInstances)\n\t\t\tif err := g.updateTargetPool(loadBalancerName, hosts); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to update target pool for load balancer (%s): %v\", lbRefStr, err)\n\t\t\t}\n\t\t\tklog.Infof(\"ensureTargetPoolAndHealthCheck(%s): Updated target pool (with %d hosts).\", lbRefStr, len(hosts)-maxTargetPoolCreateInstances)\n\t\t}\n\t} else if tpExists {\n\t\t// Ensure hosts are updated even if there is no other changes required on target pool.\n\t\tif err := g.updateTargetPool(loadBalancerName, hosts); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to update target pool for load balancer (%s): %v\", lbRefStr, err)\n\t\t}\n\t\tklog.Infof(\"ensureTargetPoolAndHealthCheck(%s): Updated target pool (with %d hosts).\", lbRefStr, len(hosts))\n\t\tif hcToCreate != nil {\n\t\t\tif hc, err := g.ensureHTTPHealthCheck(hcToCreate.Name, hcToCreate.RequestPath, int32(hcToCreate.Port)); err != nil || hc == nil {\n\t\t\t\treturn fmt.Errorf(\"failed to ensure health check for %v port %d path %v: %v\", loadBalancerName, hcToCreate.Port, hcToCreate.RequestPath, err)\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Panic worthy.\n\t\tklog.Errorf(\"ensureTargetPoolAndHealthCheck(%s): target pool not exists and doesn't need to be created.\", lbRefStr)\n\t}\n\treturn nil\n}","line":{"from":492,"to":545}} {"id":100034279,"name":"createTargetPoolAndHealthCheck","signature":"func (g *Cloud) createTargetPoolAndHealthCheck(svc *v1.Service, name, serviceName, ipAddress, region, clusterID string, hosts []*gceInstance, hc *compute.HttpHealthCheck) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"func (g *Cloud) createTargetPoolAndHealthCheck(svc *v1.Service, name, serviceName, ipAddress, region, clusterID string, hosts []*gceInstance, hc *compute.HttpHealthCheck) error {\n\t// health check management is coupled with targetPools to prevent leaks. A\n\t// target pool is the only thing that requires a health check, so we delete\n\t// associated checks on teardown, and ensure checks on setup.\n\thcLinks := []string{}\n\tif hc != nil {\n\t\t// Check whether it is nodes health check, which has different name from the load-balancer.\n\t\tisNodesHealthCheck := hc.Name != name\n\t\tif isNodesHealthCheck {\n\t\t\t// Lock to prevent necessary nodes health check / firewall gets deleted.\n\t\t\tg.sharedResourceLock.Lock()\n\t\t\tdefer g.sharedResourceLock.Unlock()\n\t\t}\n\n\t\tif err := g.ensureHTTPHealthCheckFirewall(svc, serviceName, ipAddress, region, clusterID, hosts, hc.Name, int32(hc.Port), isNodesHealthCheck); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar err error\n\t\thcRequestPath, hcPort := hc.RequestPath, hc.Port\n\t\tif hc, err = g.ensureHTTPHealthCheck(hc.Name, hc.RequestPath, int32(hc.Port)); err != nil || hc == nil {\n\t\t\treturn fmt.Errorf(\"failed to ensure health check for %v port %d path %v: %v\", name, hcPort, hcRequestPath, err)\n\t\t}\n\t\thcLinks = append(hcLinks, hc.SelfLink)\n\t}\n\n\tvar instances []string\n\tfor _, host := range hosts {\n\t\tinstances = append(instances, host.makeComparableHostPath())\n\t}\n\tklog.Infof(\"Creating targetpool %v with %d healthchecks\", name, len(hcLinks))\n\tpool := \u0026compute.TargetPool{\n\t\tName: name,\n\t\tDescription: fmt.Sprintf(`{\"kubernetes.io/service-name\":\"%s\"}`, serviceName),\n\t\tInstances: instances,\n\t\tSessionAffinity: translateAffinityType(svc.Spec.SessionAffinity),\n\t\tHealthChecks: hcLinks,\n\t}\n\n\tif err := g.CreateTargetPool(pool, region); err != nil \u0026\u0026 !isHTTPErrorCode(err, http.StatusConflict) {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":547,"to":589}} {"id":100034280,"name":"updateTargetPool","signature":"func (g *Cloud) updateTargetPool(loadBalancerName string, hosts []*gceInstance) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"func (g *Cloud) updateTargetPool(loadBalancerName string, hosts []*gceInstance) error {\n\tpool, err := g.GetTargetPool(loadBalancerName, g.region)\n\tif err != nil {\n\t\treturn err\n\t}\n\texisting := sets.NewString()\n\tfor _, instance := range pool.Instances {\n\t\texisting.Insert(hostURLToComparablePath(instance))\n\t}\n\n\tvar toAdd []*compute.InstanceReference\n\tvar toRemove []*compute.InstanceReference\n\tfor _, host := range hosts {\n\t\tlink := host.makeComparableHostPath()\n\t\tif !existing.Has(link) {\n\t\t\ttoAdd = append(toAdd, \u0026compute.InstanceReference{Instance: link})\n\t\t}\n\t\texisting.Delete(link)\n\t}\n\tfor link := range existing {\n\t\ttoRemove = append(toRemove, \u0026compute.InstanceReference{Instance: link})\n\t}\n\n\tfor len(toAdd) \u003e 0 {\n\t\t// Do not remove more than maxInstancesPerTargetPoolUpdate in a single call.\n\t\tinstancesCount := len(toAdd)\n\t\tif instancesCount \u003e maxInstancesPerTargetPoolUpdate {\n\t\t\tinstancesCount = maxInstancesPerTargetPoolUpdate\n\t\t}\n\t\t// The operation to add 1000 instances is fairly long (may take minutes), so\n\t\t// we don't need to worry about saturating QPS limits.\n\t\tif err := g.AddInstancesToTargetPool(loadBalancerName, g.region, toAdd[:instancesCount]); err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttoAdd = toAdd[instancesCount:]\n\t}\n\n\tfor len(toRemove) \u003e 0 {\n\t\t// Do not remove more than maxInstancesPerTargetPoolUpdate in a single call.\n\t\tinstancesCount := len(toRemove)\n\t\tif instancesCount \u003e maxInstancesPerTargetPoolUpdate {\n\t\t\tinstancesCount = maxInstancesPerTargetPoolUpdate\n\t\t}\n\t\t// The operation to remove 1000 instances is fairly long (may take minutes), so\n\t\t// we don't need to worry about saturating QPS limits.\n\t\tif err := g.RemoveInstancesFromTargetPool(loadBalancerName, g.region, toRemove[:instancesCount]); err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttoRemove = toRemove[instancesCount:]\n\t}\n\n\t// Try to verify that the correct number of nodes are now in the target pool.\n\t// We've been bitten by a bug here before (#11327) where all nodes were\n\t// accidentally removed and want to make similar problems easier to notice.\n\tupdatedPool, err := g.GetTargetPool(loadBalancerName, g.region)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(updatedPool.Instances) != len(hosts) {\n\t\tklog.Errorf(\"Unexpected number of instances (%d) in target pool %s after updating (expected %d). Instances in updated pool: %s\",\n\t\t\tlen(updatedPool.Instances), loadBalancerName, len(hosts), strings.Join(updatedPool.Instances, \",\"))\n\t\treturn fmt.Errorf(\"unexpected number of instances (%d) in target pool %s after update (expected %d)\", len(updatedPool.Instances), loadBalancerName, len(hosts))\n\t}\n\treturn nil\n}","line":{"from":591,"to":655}} {"id":100034281,"name":"targetPoolURL","signature":"func (g *Cloud) targetPoolURL(name string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"func (g *Cloud) targetPoolURL(name string) string {\n\treturn g.projectsBasePath + strings.Join([]string{g.projectID, \"regions\", g.region, \"targetPools\", name}, \"/\")\n}","line":{"from":657,"to":659}} {"id":100034282,"name":"makeHTTPHealthCheck","signature":"func makeHTTPHealthCheck(name, path string, port int32) *compute.HttpHealthCheck","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"func makeHTTPHealthCheck(name, path string, port int32) *compute.HttpHealthCheck {\n\treturn \u0026compute.HttpHealthCheck{\n\t\tName: name,\n\t\tPort: int64(port),\n\t\tRequestPath: path,\n\t\tHost: \"\",\n\t\tDescription: makeHealthCheckDescription(name),\n\t\tCheckIntervalSec: gceHcCheckIntervalSeconds,\n\t\tTimeoutSec: gceHcTimeoutSeconds,\n\t\tHealthyThreshold: gceHcHealthyThreshold,\n\t\tUnhealthyThreshold: gceHcUnhealthyThreshold,\n\t}\n}","line":{"from":661,"to":673}} {"id":100034283,"name":"mergeHTTPHealthChecks","signature":"func mergeHTTPHealthChecks(hc, newHC *compute.HttpHealthCheck)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"// mergeHTTPHealthChecks reconciles HttpHealthCheck configures to be no smaller\n// than the default values.\n// E.g. old health check interval is 2s, new default is 8.\n// The HC interval will be reconciled to 8 seconds.\n// If the existing health check is larger than the default interval,\n// the configuration will be kept.\nfunc mergeHTTPHealthChecks(hc, newHC *compute.HttpHealthCheck) {\n\tif hc.CheckIntervalSec \u003e newHC.CheckIntervalSec {\n\t\tnewHC.CheckIntervalSec = hc.CheckIntervalSec\n\t}\n\tif hc.TimeoutSec \u003e newHC.TimeoutSec {\n\t\tnewHC.TimeoutSec = hc.TimeoutSec\n\t}\n\tif hc.UnhealthyThreshold \u003e newHC.UnhealthyThreshold {\n\t\tnewHC.UnhealthyThreshold = hc.UnhealthyThreshold\n\t}\n\tif hc.HealthyThreshold \u003e newHC.HealthyThreshold {\n\t\tnewHC.HealthyThreshold = hc.HealthyThreshold\n\t}\n}","line":{"from":675,"to":694}} {"id":100034284,"name":"needToUpdateHTTPHealthChecks","signature":"func needToUpdateHTTPHealthChecks(hc, newHC *compute.HttpHealthCheck) bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"// needToUpdateHTTPHealthChecks checks whether the http healthcheck needs to be\n// updated.\nfunc needToUpdateHTTPHealthChecks(hc, newHC *compute.HttpHealthCheck) bool {\n\tswitch {\n\tcase\n\t\thc.Port != newHC.Port,\n\t\thc.RequestPath != newHC.RequestPath,\n\t\thc.Description != newHC.Description,\n\t\thc.CheckIntervalSec \u003c newHC.CheckIntervalSec,\n\t\thc.TimeoutSec \u003c newHC.TimeoutSec,\n\t\thc.UnhealthyThreshold \u003c newHC.UnhealthyThreshold,\n\t\thc.HealthyThreshold \u003c newHC.HealthyThreshold:\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":696,"to":711}} {"id":100034285,"name":"ensureHTTPHealthCheck","signature":"func (g *Cloud) ensureHTTPHealthCheck(name, path string, port int32) (hc *compute.HttpHealthCheck, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"func (g *Cloud) ensureHTTPHealthCheck(name, path string, port int32) (hc *compute.HttpHealthCheck, err error) {\n\tnewHC := makeHTTPHealthCheck(name, path, port)\n\thc, err = g.GetHTTPHealthCheck(name)\n\tif hc == nil || err != nil \u0026\u0026 isHTTPErrorCode(err, http.StatusNotFound) {\n\t\tklog.Infof(\"Did not find health check %v, creating port %v path %v\", name, port, path)\n\t\tif err = g.CreateHTTPHealthCheck(newHC); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\thc, err = g.GetHTTPHealthCheck(name)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to get http health check %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tklog.Infof(\"Created HTTP health check %v healthCheckNodePort: %d\", name, port)\n\t\treturn hc, nil\n\t}\n\t// Validate health check fields\n\tklog.V(4).Infof(\"Checking http health check params %s\", name)\n\tif needToUpdateHTTPHealthChecks(hc, newHC) {\n\t\tklog.Warningf(\"Health check %v exists but parameters have drifted - updating...\", name)\n\t\tmergeHTTPHealthChecks(hc, newHC)\n\t\tif err := g.UpdateHTTPHealthCheck(newHC); err != nil {\n\t\t\tklog.Warningf(\"Failed to reconcile http health check %v parameters\", name)\n\t\t\treturn nil, err\n\t\t}\n\t\tklog.V(4).Infof(\"Corrected health check %v parameters successful\", name)\n\t\thc, err = g.GetHTTPHealthCheck(name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn hc, nil\n}","line":{"from":713,"to":745}} {"id":100034286,"name":"forwardingRuleNeedsUpdate","signature":"func (g *Cloud) forwardingRuleNeedsUpdate(name, region string, loadBalancerIP string, ports []v1.ServicePort) (exists bool, needsUpdate bool, ipAddress string, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"// Passing nil for requested IP is perfectly fine - it just means that no specific\n// IP is being requested.\n// Returns whether the forwarding rule exists, whether it needs to be updated,\n// what its IP address is (if it exists), and any error we encountered.\nfunc (g *Cloud) forwardingRuleNeedsUpdate(name, region string, loadBalancerIP string, ports []v1.ServicePort) (exists bool, needsUpdate bool, ipAddress string, err error) {\n\tfwd, err := g.GetRegionForwardingRule(name, region)\n\tif err != nil {\n\t\tif isHTTPErrorCode(err, http.StatusNotFound) {\n\t\t\treturn false, true, \"\", nil\n\t\t}\n\t\t// Err on the side of caution in case of errors. Caller should notice the error and retry.\n\t\t// We never want to end up recreating resources because g api flaked.\n\t\treturn true, false, \"\", fmt.Errorf(\"error getting load balancer's forwarding rule: %v\", err)\n\t}\n\t// If the user asks for a specific static ip through the Service spec,\n\t// check that we're actually using it.\n\t// TODO: we report loadbalancer IP through status, so we want to verify if\n\t// that matches the forwarding rule as well.\n\tif loadBalancerIP != \"\" \u0026\u0026 loadBalancerIP != fwd.IPAddress {\n\t\tklog.Infof(\"LoadBalancer ip for forwarding rule %v was expected to be %v, but was actually %v\", fwd.Name, fwd.IPAddress, loadBalancerIP)\n\t\treturn true, true, fwd.IPAddress, nil\n\t}\n\tportRange, err := loadBalancerPortRange(ports)\n\tif err != nil {\n\t\t// Err on the side of caution in case of errors. Caller should notice the error and retry.\n\t\t// We never want to end up recreating resources because g api flaked.\n\t\treturn true, false, \"\", err\n\t}\n\tif portRange != fwd.PortRange {\n\t\tklog.Infof(\"LoadBalancer port range for forwarding rule %v was expected to be %v, but was actually %v\", fwd.Name, fwd.PortRange, portRange)\n\t\treturn true, true, fwd.IPAddress, nil\n\t}\n\t// The service controller verified all the protocols match on the ports, just check the first one\n\tif string(ports[0].Protocol) != fwd.IPProtocol {\n\t\tklog.Infof(\"LoadBalancer protocol for forwarding rule %v was expected to be %v, but was actually %v\", fwd.Name, fwd.IPProtocol, string(ports[0].Protocol))\n\t\treturn true, true, fwd.IPAddress, nil\n\t}\n\n\treturn true, false, fwd.IPAddress, nil\n}","line":{"from":747,"to":786}} {"id":100034287,"name":"targetPoolNeedsRecreation","signature":"func (g *Cloud) targetPoolNeedsRecreation(name, region string, affinityType v1.ServiceAffinity) (exists bool, needsRecreation bool, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"// Doesn't check whether the hosts have changed, since host updating is handled\n// separately.\nfunc (g *Cloud) targetPoolNeedsRecreation(name, region string, affinityType v1.ServiceAffinity) (exists bool, needsRecreation bool, err error) {\n\ttp, err := g.GetTargetPool(name, region)\n\tif err != nil {\n\t\tif isHTTPErrorCode(err, http.StatusNotFound) {\n\t\t\treturn false, true, nil\n\t\t}\n\t\t// Err on the side of caution in case of errors. Caller should notice the error and retry.\n\t\t// We never want to end up recreating resources because g api flaked.\n\t\treturn true, false, fmt.Errorf(\"error getting load balancer's target pool: %v\", err)\n\t}\n\t// TODO: If the user modifies their Service's session affinity, it *should*\n\t// reflect in the associated target pool. However, currently not setting the\n\t// session affinity on a target pool defaults it to the empty string while\n\t// not setting in on a Service defaults it to None. There is a lack of\n\t// documentation around the default setting for the target pool, so if we\n\t// find it's the undocumented empty string, don't blindly recreate the\n\t// target pool (which results in downtime). Fix this when we have formally\n\t// defined the defaults on either side.\n\tif tp.SessionAffinity != \"\" \u0026\u0026 translateAffinityType(affinityType) != tp.SessionAffinity {\n\t\tklog.Infof(\"LoadBalancer target pool %v changed affinity from %v to %v\", name, tp.SessionAffinity, affinityType)\n\t\treturn true, true, nil\n\t}\n\treturn true, false, nil\n}","line":{"from":788,"to":813}} {"id":100034288,"name":"makeComparableHostPath","signature":"func (h *gceInstance) makeComparableHostPath() string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"func (h *gceInstance) makeComparableHostPath() string {\n\treturn fmt.Sprintf(\"/zones/%s/instances/%s\", h.Zone, h.Name)\n}","line":{"from":815,"to":817}} {"id":100034289,"name":"nodeNames","signature":"func nodeNames(nodes []*v1.Node) []string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"func nodeNames(nodes []*v1.Node) []string {\n\tret := make([]string, len(nodes))\n\tfor i, node := range nodes {\n\t\tret[i] = node.Name\n\t}\n\treturn ret\n}","line":{"from":819,"to":825}} {"id":100034290,"name":"hostURLToComparablePath","signature":"func hostURLToComparablePath(hostURL string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"func hostURLToComparablePath(hostURL string) string {\n\tidx := strings.Index(hostURL, \"/zones/\")\n\tif idx \u003c 0 {\n\t\treturn \"\"\n\t}\n\treturn hostURL[idx:]\n}","line":{"from":827,"to":833}} {"id":100034291,"name":"loadBalancerPortRange","signature":"func loadBalancerPortRange(ports []v1.ServicePort) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"func loadBalancerPortRange(ports []v1.ServicePort) (string, error) {\n\tif len(ports) == 0 {\n\t\treturn \"\", fmt.Errorf(\"no ports specified for GCE load balancer\")\n\t}\n\n\t// The service controller verified all the protocols match on the ports, just check and use the first one\n\tif ports[0].Protocol != v1.ProtocolTCP \u0026\u0026 ports[0].Protocol != v1.ProtocolUDP {\n\t\treturn \"\", fmt.Errorf(\"invalid protocol %s, only TCP and UDP are supported\", string(ports[0].Protocol))\n\t}\n\n\tminPort := int32(65536)\n\tmaxPort := int32(0)\n\tfor i := range ports {\n\t\tif ports[i].Port \u003c minPort {\n\t\t\tminPort = ports[i].Port\n\t\t}\n\t\tif ports[i].Port \u003e maxPort {\n\t\t\tmaxPort = ports[i].Port\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"%d-%d\", minPort, maxPort), nil\n}","line":{"from":835,"to":856}} {"id":100034292,"name":"translateAffinityType","signature":"func translateAffinityType(affinityType v1.ServiceAffinity) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"// translate from what K8s supports to what the cloud provider supports for session affinity.\nfunc translateAffinityType(affinityType v1.ServiceAffinity) string {\n\tswitch affinityType {\n\tcase v1.ServiceAffinityClientIP:\n\t\treturn gceAffinityTypeClientIP\n\tcase v1.ServiceAffinityNone:\n\t\treturn gceAffinityTypeNone\n\tdefault:\n\t\tklog.Errorf(\"Unexpected affinity type: %v\", affinityType)\n\t\treturn gceAffinityTypeNone\n\t}\n}","line":{"from":858,"to":869}} {"id":100034293,"name":"firewallNeedsUpdate","signature":"func (g *Cloud) firewallNeedsUpdate(name, serviceName, ipAddress string, ports []v1.ServicePort, sourceRanges utilnet.IPNetSet) (exists bool, needsUpdate bool, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"func (g *Cloud) firewallNeedsUpdate(name, serviceName, ipAddress string, ports []v1.ServicePort, sourceRanges utilnet.IPNetSet) (exists bool, needsUpdate bool, err error) {\n\tfw, err := g.GetFirewall(MakeFirewallName(name))\n\tif err != nil {\n\t\tif isHTTPErrorCode(err, http.StatusNotFound) {\n\t\t\treturn false, true, nil\n\t\t}\n\t\treturn false, false, fmt.Errorf(\"error getting load balancer's firewall: %v\", err)\n\t}\n\tif fw.Description != makeFirewallDescription(serviceName, ipAddress) {\n\t\treturn true, true, nil\n\t}\n\tif len(fw.Allowed) != 1 || (fw.Allowed[0].IPProtocol != \"tcp\" \u0026\u0026 fw.Allowed[0].IPProtocol != \"udp\") {\n\t\treturn true, true, nil\n\t}\n\t// Make sure the allowed ports match.\n\tportNums, portRanges, _ := getPortsAndProtocol(ports)\n\t// This logic checks if the existing firewall rules contains either enumerated service ports or port ranges.\n\t// This is to prevent unnecessary noop updates to the firewall rule when the existing firewall rule is\n\t// set up via the previous pattern using enumerated ports instead of port ranges.\n\tif !equalStringSets(portNums, fw.Allowed[0].Ports) \u0026\u0026 !equalStringSets(portRanges, fw.Allowed[0].Ports) {\n\t\treturn true, true, nil\n\t}\n\n\t// The service controller already verified that the protocol matches on all ports, no need to check.\n\tactualSourceRanges, err := utilnet.ParseIPNets(fw.SourceRanges...)\n\tif err != nil {\n\t\t// This really shouldn't happen... GCE has returned something unexpected\n\t\tklog.Warningf(\"Error parsing firewall SourceRanges: %v\", fw.SourceRanges)\n\t\t// We don't return the error, because we can hopefully recover from this by reconfiguring the firewall\n\t\treturn true, true, nil\n\t}\n\n\tif !sourceRanges.Equal(actualSourceRanges) {\n\t\treturn true, true, nil\n\t}\n\n\tdestinationRanges := []string{ipAddress}\n\n\tif !reflect.DeepEqual(destinationRanges, fw.DestinationRanges) {\n\t\treturn true, true, nil\n\t}\n\n\treturn true, false, nil\n}","line":{"from":871,"to":914}} {"id":100034294,"name":"ensureHTTPHealthCheckFirewall","signature":"func (g *Cloud) ensureHTTPHealthCheckFirewall(svc *v1.Service, serviceName, ipAddress, region, clusterID string, hosts []*gceInstance, hcName string, hcPort int32, isNodesHealthCheck bool) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"func (g *Cloud) ensureHTTPHealthCheckFirewall(svc *v1.Service, serviceName, ipAddress, region, clusterID string, hosts []*gceInstance, hcName string, hcPort int32, isNodesHealthCheck bool) error {\n\t// Prepare the firewall params for creating / checking.\n\tdesc := fmt.Sprintf(`{\"kubernetes.io/cluster-id\":\"%s\"}`, clusterID)\n\tif !isNodesHealthCheck {\n\t\tdesc = makeFirewallDescription(serviceName, ipAddress)\n\t}\n\tsourceRanges := l4LbSrcRngsFlag.ipn\n\tports := []v1.ServicePort{{Protocol: \"tcp\", Port: hcPort}}\n\n\tfwName := MakeHealthCheckFirewallName(clusterID, hcName, isNodesHealthCheck)\n\tfw, err := g.GetFirewall(fwName)\n\tif err != nil {\n\t\tif !isHTTPErrorCode(err, http.StatusNotFound) {\n\t\t\treturn fmt.Errorf(\"error getting firewall for health checks: %v\", err)\n\t\t}\n\t\tklog.Infof(\"Creating firewall %v for health checks.\", fwName)\n\t\tif err := g.createFirewall(svc, fwName, desc, ipAddress, sourceRanges, ports, hosts); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tklog.Infof(\"Created firewall %v for health checks.\", fwName)\n\t\treturn nil\n\t}\n\t// Validate firewall fields.\n\tif fw.Description != desc ||\n\t\tlen(fw.Allowed) != 1 ||\n\t\tfw.Allowed[0].IPProtocol != string(ports[0].Protocol) ||\n\t\t!equalStringSets(fw.Allowed[0].Ports, []string{strconv.Itoa(int(ports[0].Port))}) ||\n\t\t!equalStringSets(fw.SourceRanges, sourceRanges.StringSlice()) {\n\t\tklog.Warningf(\"Firewall %v exists but parameters have drifted - updating...\", fwName)\n\t\tif err := g.updateFirewall(svc, fwName, desc, ipAddress, sourceRanges, ports, hosts); err != nil {\n\t\t\tklog.Warningf(\"Failed to reconcile firewall %v parameters.\", fwName)\n\t\t\treturn err\n\t\t}\n\t\tklog.V(4).Infof(\"Corrected firewall %v parameters successful\", fwName)\n\t}\n\treturn nil\n}","line":{"from":916,"to":952}} {"id":100034295,"name":"createForwardingRule","signature":"func createForwardingRule(s CloudForwardingRuleService, name, serviceName, region, ipAddress, target string, ports []v1.ServicePort, netTier cloud.NetworkTier) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"func createForwardingRule(s CloudForwardingRuleService, name, serviceName, region, ipAddress, target string, ports []v1.ServicePort, netTier cloud.NetworkTier) error {\n\tportRange, err := loadBalancerPortRange(ports)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdesc := makeServiceDescription(serviceName)\n\tipProtocol := string(ports[0].Protocol)\n\n\trule := \u0026compute.ForwardingRule{\n\t\tName: name,\n\t\tDescription: desc,\n\t\tIPAddress: ipAddress,\n\t\tIPProtocol: ipProtocol,\n\t\tPortRange: portRange,\n\t\tTarget: target,\n\t\tNetworkTier: netTier.ToGCEValue(),\n\t}\n\n\terr = s.CreateRegionForwardingRule(rule, region)\n\n\tif err != nil \u0026\u0026 !isHTTPErrorCode(err, http.StatusConflict) {\n\t\treturn err\n\t}\n\n\treturn nil\n}","line":{"from":954,"to":979}} {"id":100034296,"name":"createFirewall","signature":"func (g *Cloud) createFirewall(svc *v1.Service, name, desc, destinationIP string, sourceRanges utilnet.IPNetSet, ports []v1.ServicePort, hosts []*gceInstance) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"func (g *Cloud) createFirewall(svc *v1.Service, name, desc, destinationIP string, sourceRanges utilnet.IPNetSet, ports []v1.ServicePort, hosts []*gceInstance) error {\n\tfirewall, err := g.firewallObject(name, desc, destinationIP, sourceRanges, ports, hosts)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = g.CreateFirewall(firewall); err != nil {\n\t\tif isHTTPErrorCode(err, http.StatusConflict) {\n\t\t\treturn nil\n\t\t} else if isForbidden(err) \u0026\u0026 g.OnXPN() {\n\t\t\tklog.V(4).Infof(\"createFirewall(%v): do not have permission to create firewall rule (on XPN). Raising event.\", firewall.Name)\n\t\t\tg.raiseFirewallChangeNeededEvent(svc, FirewallToGCloudCreateCmd(firewall, g.NetworkProjectID()))\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":981,"to":997}} {"id":100034297,"name":"updateFirewall","signature":"func (g *Cloud) updateFirewall(svc *v1.Service, name, desc, destinationIP string, sourceRanges utilnet.IPNetSet, ports []v1.ServicePort, hosts []*gceInstance) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"func (g *Cloud) updateFirewall(svc *v1.Service, name, desc, destinationIP string, sourceRanges utilnet.IPNetSet, ports []v1.ServicePort, hosts []*gceInstance) error {\n\tfirewall, err := g.firewallObject(name, desc, destinationIP, sourceRanges, ports, hosts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = g.PatchFirewall(firewall); err != nil {\n\t\tif isHTTPErrorCode(err, http.StatusConflict) {\n\t\t\treturn nil\n\t\t} else if isForbidden(err) \u0026\u0026 g.OnXPN() {\n\t\t\tklog.V(4).Infof(\"updateFirewall(%v): do not have permission to update firewall rule (on XPN). Raising event.\", firewall.Name)\n\t\t\tg.raiseFirewallChangeNeededEvent(svc, FirewallToGCloudUpdateCmd(firewall, g.NetworkProjectID()))\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":999,"to":1016}} {"id":100034298,"name":"firewallObject","signature":"func (g *Cloud) firewallObject(name, desc, destinationIP string, sourceRanges utilnet.IPNetSet, ports []v1.ServicePort, hosts []*gceInstance) (*compute.Firewall, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"func (g *Cloud) firewallObject(name, desc, destinationIP string, sourceRanges utilnet.IPNetSet, ports []v1.ServicePort, hosts []*gceInstance) (*compute.Firewall, error) {\n\t// destinationIP can be empty string \"\" and this means that it is not set.\n\t// GCE considers empty destinationRanges as \"all\" for ingress firewall-rules.\n\t// Concatenate service ports into port ranges. This help to workaround the gce firewall limitation where only\n\t// 100 ports or port ranges can be used in a firewall rule.\n\t_, portRanges, _ := getPortsAndProtocol(ports)\n\n\t// If the node tags to be used for this cluster have been predefined in the\n\t// provider config, just use them. Otherwise, invoke computeHostTags method to get the tags.\n\thostTags := g.nodeTags\n\tif len(hostTags) == 0 {\n\t\tvar err error\n\t\tif hostTags, err = g.computeHostTags(hosts); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"no node tags supplied and also failed to parse the given lists of hosts for tags. Abort creating firewall rule\")\n\t\t}\n\t}\n\n\tfirewall := \u0026compute.Firewall{\n\t\tName: name,\n\t\tDescription: desc,\n\t\tNetwork: g.networkURL,\n\t\tSourceRanges: sourceRanges.StringSlice(),\n\t\tTargetTags: hostTags,\n\t\tAllowed: []*compute.FirewallAllowed{\n\t\t\t{\n\t\t\t\t// TODO: Make this more generic. Currently this method is only\n\t\t\t\t// used to create firewall rules for loadbalancers, which have\n\t\t\t\t// exactly one protocol, so we can never end up with a list of\n\t\t\t\t// mixed TCP and UDP ports. It should be possible to use a\n\t\t\t\t// single firewall rule for both a TCP and UDP lb.\n\t\t\t\tIPProtocol: strings.ToLower(string(ports[0].Protocol)),\n\t\t\t\tPorts: portRanges,\n\t\t\t},\n\t\t},\n\t}\n\tif destinationIP != \"\" {\n\t\tfirewall.DestinationRanges = []string{destinationIP}\n\t}\n\treturn firewall, nil\n}","line":{"from":1018,"to":1057}} {"id":100034299,"name":"ensureStaticIP","signature":"func ensureStaticIP(s CloudAddressService, name, serviceName, region, existingIP string, netTier cloud.NetworkTier) (ipAddress string, existing bool, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"func ensureStaticIP(s CloudAddressService, name, serviceName, region, existingIP string, netTier cloud.NetworkTier) (ipAddress string, existing bool, err error) {\n\t// If the address doesn't exist, this will create it.\n\t// If the existingIP exists but is ephemeral, this will promote it to static.\n\t// If the address already exists, this will harmlessly return a StatusConflict\n\t// and we'll grab the IP before returning.\n\texisted := false\n\tdesc := makeServiceDescription(serviceName)\n\n\tvar creationErr error\n\taddressObj := \u0026compute.Address{\n\t\tName: name,\n\t\tDescription: desc,\n\t\tNetworkTier: netTier.ToGCEValue(),\n\t}\n\tif existingIP != \"\" {\n\t\taddressObj.Address = existingIP\n\t}\n\tcreationErr = s.ReserveRegionAddress(addressObj, region)\n\n\tif creationErr != nil {\n\t\t// GCE returns StatusConflict if the name conflicts; it returns\n\t\t// StatusBadRequest if the IP conflicts.\n\t\tif !isHTTPErrorCode(creationErr, http.StatusConflict) \u0026\u0026 !isHTTPErrorCode(creationErr, http.StatusBadRequest) {\n\t\t\treturn \"\", false, fmt.Errorf(\"error creating gce static IP address: %v\", creationErr)\n\t\t}\n\t\texisted = true\n\t}\n\n\t// If address exists, get it by IP, because name might be different.\n\t// This can specifically happen if the IP was changed from ephemeral to static,\n\t// which results in a new name for the IP.\n\tif existingIP != \"\" {\n\t\taddr, err := s.GetRegionAddressByIP(region, existingIP)\n\t\tif err != nil {\n\t\t\treturn \"\", false, fmt.Errorf(\"error getting static IP address: %v\", err)\n\t\t}\n\t\treturn addr.Address, existed, nil\n\t}\n\n\t// Otherwise, get address by name\n\taddr, err := s.GetRegionAddress(name, region)\n\tif err != nil {\n\t\treturn \"\", false, fmt.Errorf(\"error getting static IP address: %v\", err)\n\t}\n\n\treturn addr.Address, existed, nil\n}","line":{"from":1059,"to":1105}} {"id":100034300,"name":"getServiceNetworkTier","signature":"func (g *Cloud) getServiceNetworkTier(svc *v1.Service) (cloud.NetworkTier, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"func (g *Cloud) getServiceNetworkTier(svc *v1.Service) (cloud.NetworkTier, error) {\n\ttier, err := GetServiceNetworkTier(svc)\n\tif err != nil {\n\t\t// Returns an error if the annotation is invalid.\n\t\treturn cloud.NetworkTier(\"\"), err\n\t}\n\treturn tier, nil\n}","line":{"from":1107,"to":1114}} {"id":100034301,"name":"deleteWrongNetworkTieredResources","signature":"func (g *Cloud) deleteWrongNetworkTieredResources(lbName, lbRef string, desiredNetTier cloud.NetworkTier) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"func (g *Cloud) deleteWrongNetworkTieredResources(lbName, lbRef string, desiredNetTier cloud.NetworkTier) error {\n\tlogPrefix := fmt.Sprintf(\"deleteWrongNetworkTieredResources:(%s)\", lbRef)\n\tif err := deleteFWDRuleWithWrongTier(g, g.region, lbName, logPrefix, desiredNetTier); err != nil {\n\t\treturn err\n\t}\n\tif err := deleteAddressWithWrongTier(g, g.region, lbName, logPrefix, desiredNetTier); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":1116,"to":1125}} {"id":100034302,"name":"deleteFWDRuleWithWrongTier","signature":"func deleteFWDRuleWithWrongTier(s CloudForwardingRuleService, region, name, logPrefix string, desiredNetTier cloud.NetworkTier) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"// deleteFWDRuleWithWrongTier checks the network tier of existing forwarding\n// rule and delete the rule if the tier does not matched the desired tier.\nfunc deleteFWDRuleWithWrongTier(s CloudForwardingRuleService, region, name, logPrefix string, desiredNetTier cloud.NetworkTier) error {\n\ttierStr, err := s.getNetworkTierFromForwardingRule(name, region)\n\tif isNotFound(err) {\n\t\treturn nil\n\t} else if err != nil {\n\t\treturn err\n\t}\n\texistingTier := cloud.NetworkTierGCEValueToType(tierStr)\n\tif existingTier == desiredNetTier {\n\t\treturn nil\n\t}\n\tklog.V(2).Infof(\"%s: Network tiers do not match; existing forwarding rule: %q, desired: %q. Deleting the forwarding rule\",\n\t\tlogPrefix, existingTier, desiredNetTier)\n\terr = s.DeleteRegionForwardingRule(name, region)\n\treturn ignoreNotFound(err)\n}","line":{"from":1127,"to":1144}} {"id":100034303,"name":"deleteAddressWithWrongTier","signature":"func deleteAddressWithWrongTier(s CloudAddressService, region, name, logPrefix string, desiredNetTier cloud.NetworkTier) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_external.go","code":"// deleteAddressWithWrongTier checks the network tier of existing address\n// and delete the address if the tier does not matched the desired tier.\nfunc deleteAddressWithWrongTier(s CloudAddressService, region, name, logPrefix string, desiredNetTier cloud.NetworkTier) error {\n\t// We only check the IP address matching the reserved name that the\n\t// controller assigned to the LB. We make the assumption that an address of\n\t// such name is owned by the controller and is safe to release. Whether an\n\t// IP is owned by the user is not clearly defined in the current code, and\n\t// this assumption may not match some of the existing logic in the code.\n\t// However, this is okay since network tiering is still Alpha and will be\n\t// properly gated.\n\t// TODO(#51665): Re-evaluate the \"ownership\" of the IP address to ensure\n\t// we don't release IP unintentionally.\n\ttierStr, err := s.getNetworkTierFromAddress(name, region)\n\tif isNotFound(err) {\n\t\treturn nil\n\t} else if err != nil {\n\t\treturn err\n\t}\n\texistingTier := cloud.NetworkTierGCEValueToType(tierStr)\n\tif existingTier == desiredNetTier {\n\t\treturn nil\n\t}\n\tklog.V(2).Infof(\"%s: Network tiers do not match; existing address: %q, desired: %q. Deleting the address\",\n\t\tlogPrefix, existingTier, desiredNetTier)\n\terr = s.DeleteRegionAddress(name, region)\n\treturn ignoreNotFound(err)\n}","line":{"from":1146,"to":1172}} {"id":100034304,"name":"ensureInternalLoadBalancer","signature":"func (g *Cloud) ensureInternalLoadBalancer(clusterName, clusterID string, svc *v1.Service, existingFwdRule *compute.ForwardingRule, nodes []*v1.Node) (*v1.LoadBalancerStatus, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"func (g *Cloud) ensureInternalLoadBalancer(clusterName, clusterID string, svc *v1.Service, existingFwdRule *compute.ForwardingRule, nodes []*v1.Node) (*v1.LoadBalancerStatus, error) {\n\tif existingFwdRule == nil \u0026\u0026 !hasFinalizer(svc, ILBFinalizerV1) {\n\t\t// Neither the forwarding rule nor the V1 finalizer exists. This is most likely a new service.\n\t\tif g.AlphaFeatureGate.Enabled(AlphaFeatureILBSubsets) {\n\t\t\t// When ILBSubsets is enabled, new ILB services will not be processed here.\n\t\t\t// Services that have existing GCE resources created by this controller or the v1 finalizer\n\t\t\t// will continue to update.\n\t\t\tklog.V(2).Infof(\"Skipped ensureInternalLoadBalancer for service %s/%s, since %s feature is enabled.\", svc.Namespace, svc.Name, AlphaFeatureILBSubsets)\n\t\t\treturn nil, cloudprovider.ImplementedElsewhere\n\t\t}\n\t\tif hasFinalizer(svc, ILBFinalizerV2) {\n\t\t\t// No V1 resources present - Another controller is handling the resources for this service.\n\t\t\tklog.V(2).Infof(\"Skipped ensureInternalLoadBalancer for service %s/%s, as service contains %q finalizer.\", svc.Namespace, svc.Name, ILBFinalizerV2)\n\t\t\treturn nil, cloudprovider.ImplementedElsewhere\n\t\t}\n\t}\n\n\tnm := types.NamespacedName{Name: svc.Name, Namespace: svc.Namespace}\n\n\tvar serviceState L4ILBServiceState\n\t// Mark the service InSuccess state as false to begin with.\n\t// This will be updated to true if the VIP is configured successfully.\n\tserviceState.InSuccess = false\n\tdefer func() {\n\t\tg.metricsCollector.SetL4ILBService(nm.String(), serviceState)\n\t}()\n\n\tloadBalancerName := g.GetLoadBalancerName(context.TODO(), clusterName, svc)\n\tklog.V(2).Infof(\"ensureInternalLoadBalancer(%v): Attaching %q finalizer\", loadBalancerName, ILBFinalizerV1)\n\tif err := addFinalizer(svc, g.client.CoreV1(), ILBFinalizerV1); err != nil {\n\t\tklog.Errorf(\"Failed to attach finalizer '%s' on service %s/%s - %v\", ILBFinalizerV1, svc.Namespace, svc.Name, err)\n\t\treturn nil, err\n\t}\n\n\tports, _, protocol := getPortsAndProtocol(svc.Spec.Ports)\n\tif protocol != v1.ProtocolTCP \u0026\u0026 protocol != v1.ProtocolUDP {\n\t\treturn nil, fmt.Errorf(\"Invalid protocol %s, only TCP and UDP are supported\", string(protocol))\n\t}\n\tscheme := cloud.SchemeInternal\n\toptions := getILBOptions(svc)\n\tif g.IsLegacyNetwork() {\n\t\tg.eventRecorder.Event(svc, v1.EventTypeWarning, \"ILBOptionsIgnored\", \"Internal LoadBalancer options are not supported with Legacy Networks.\")\n\t\toptions = ILBOptions{}\n\t}\n\n\tsharedBackend := shareBackendService(svc)\n\tbackendServiceName := makeBackendServiceName(loadBalancerName, clusterID, sharedBackend, scheme, protocol, svc.Spec.SessionAffinity)\n\tbackendServiceLink := g.getBackendServiceLink(backendServiceName)\n\n\t// Ensure instance groups exist and nodes are assigned to groups\n\tigName := makeInstanceGroupName(clusterID)\n\tigLinks, err := g.ensureInternalInstanceGroups(igName, nodes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Get existing backend service (if exists)\n\tvar existingBackendService *compute.BackendService\n\tif existingFwdRule != nil \u0026\u0026 existingFwdRule.BackendService != \"\" {\n\t\texistingBSName := getNameFromLink(existingFwdRule.BackendService)\n\t\tif existingBackendService, err = g.GetRegionBackendService(existingBSName, g.region); err != nil \u0026\u0026 !isNotFound(err) {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Lock the sharedResourceLock to prevent any deletions of shared resources while assembling shared resources here\n\tg.sharedResourceLock.Lock()\n\tdefer g.sharedResourceLock.Unlock()\n\n\t// Ensure health check exists before creating the backend service. The health check is shared\n\t// if externalTrafficPolicy=Cluster.\n\tsharedHealthCheck := !servicehelpers.RequestsOnlyLocalTraffic(svc)\n\thcName := makeHealthCheckName(loadBalancerName, clusterID, sharedHealthCheck)\n\thcPath, hcPort := GetNodesHealthCheckPath(), GetNodesHealthCheckPort()\n\tif !sharedHealthCheck {\n\t\t// Service requires a special health check, retrieve the OnlyLocal port \u0026 path\n\t\thcPath, hcPort = servicehelpers.GetServiceHealthCheckPathPort(svc)\n\t}\n\thc, err := g.ensureInternalHealthCheck(hcName, nm, sharedHealthCheck, hcPath, hcPort)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsubnetworkURL := g.SubnetworkURL()\n\t// Any subnet specified using the subnet annotation will be picked up and reflected in the forwarding rule.\n\t// Removing the annotation will set the forwarding rule to use the default subnet and result in a VIP change.\n\t// In order to support existing ILBs that were setup using the wrong subnet - https://github.com/kubernetes/kubernetes/pull/57861,\n\t// users will need to specify that subnet with the annotation.\n\tif options.SubnetName != \"\" {\n\t\tsubnetworkURL = gceSubnetworkURL(\"\", g.networkProjectID, g.region, options.SubnetName)\n\t}\n\t// Determine IP which will be used for this LB. If no forwarding rule has been established\n\t// or specified in the Service spec, then requestedIP = \"\".\n\tipToUse := ilbIPToUse(svc, existingFwdRule, subnetworkURL)\n\n\tklog.V(2).Infof(\"ensureInternalLoadBalancer(%v): Using subnet %s for LoadBalancer IP %s\", loadBalancerName, options.SubnetName, ipToUse)\n\n\tvar addrMgr *addressManager\n\t// If the network is not a legacy network, use the address manager\n\tif !g.IsLegacyNetwork() {\n\t\taddrMgr = newAddressManager(g, nm.String(), g.Region(), subnetworkURL, loadBalancerName, ipToUse, cloud.SchemeInternal)\n\t\tipToUse, err = addrMgr.HoldAddress()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tklog.V(2).Infof(\"ensureInternalLoadBalancer(%v): reserved IP %q for the forwarding rule\", loadBalancerName, ipToUse)\n\t\tdefer func() {\n\t\t\t// Release the address if all resources were created successfully, or if we error out.\n\t\t\tif err := addrMgr.ReleaseAddress(); err != nil {\n\t\t\t\tklog.Errorf(\"ensureInternalLoadBalancer: failed to release address reservation, possibly causing an orphan: %v\", err)\n\t\t\t}\n\t\t}()\n\t}\n\n\tfwdRuleDescription := \u0026forwardingRuleDescription{ServiceName: nm.String()}\n\tfwdRuleDescriptionString, err := fwdRuleDescription.marshal()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnewFwdRule := \u0026compute.ForwardingRule{\n\t\tName: loadBalancerName,\n\t\tDescription: fwdRuleDescriptionString,\n\t\tIPAddress: ipToUse,\n\t\tBackendService: backendServiceLink,\n\t\tPorts: ports,\n\t\tIPProtocol: string(protocol),\n\t\tLoadBalancingScheme: string(scheme),\n\t\t// Given that CreateGCECloud will attempt to determine the subnet based off the network,\n\t\t// the subnetwork should rarely be unknown.\n\t\tSubnetwork: subnetworkURL,\n\t\tNetwork: g.networkURL,\n\t}\n\tif options.AllowGlobalAccess {\n\t\tnewFwdRule.AllowGlobalAccess = options.AllowGlobalAccess\n\t}\n\tif len(ports) \u003e maxL4ILBPorts {\n\t\tnewFwdRule.Ports = nil\n\t\tnewFwdRule.AllPorts = true\n\t}\n\n\tfwdRuleDeleted := false\n\tif existingFwdRule != nil \u0026\u0026 !forwardingRulesEqual(existingFwdRule, newFwdRule) {\n\t\t// Delete existing forwarding rule before making changes to the backend service. For example - changing protocol\n\t\t// of backend service without first deleting forwarding rule will throw an error since the linked forwarding\n\t\t// rule would show the old protocol.\n\t\tif klogV := klog.V(2); klogV.Enabled() {\n\t\t\tfrDiff := cmp.Diff(existingFwdRule, newFwdRule)\n\t\t\tklogV.Infof(\"ensureInternalLoadBalancer(%v): forwarding rule changed - Existing - %+v\\n, New - %+v\\n, Diff(-existing, +new) - %s\\n. Deleting existing forwarding rule.\", loadBalancerName, existingFwdRule, newFwdRule, frDiff)\n\t\t}\n\t\tif err = ignoreNotFound(g.DeleteRegionForwardingRule(loadBalancerName, g.region)); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfwdRuleDeleted = true\n\t}\n\n\tbsDescription := makeBackendServiceDescription(nm, sharedBackend)\n\terr = g.ensureInternalBackendService(backendServiceName, bsDescription, svc.Spec.SessionAffinity, scheme, protocol, igLinks, hc.SelfLink)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif fwdRuleDeleted || existingFwdRule == nil {\n\t\t// existing rule has been deleted, pass in nil\n\t\tif err := g.ensureInternalForwardingRule(nil, newFwdRule); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Get the most recent forwarding rule for the address.\n\tupdatedFwdRule, err := g.GetRegionForwardingRule(loadBalancerName, g.region)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tipToUse = updatedFwdRule.IPAddress\n\t// Ensure firewall rules if necessary\n\tif err = g.ensureInternalFirewalls(loadBalancerName, ipToUse, clusterID, nm, svc, strconv.Itoa(int(hcPort)), sharedHealthCheck, nodes); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Delete the previous internal load balancer resources if necessary\n\tif existingBackendService != nil {\n\t\tg.clearPreviousInternalResources(svc, loadBalancerName, existingBackendService, backendServiceName, hcName)\n\t}\n\n\tserviceState.InSuccess = true\n\tif options.AllowGlobalAccess {\n\t\tserviceState.EnabledGlobalAccess = true\n\t}\n\t// SubnetName is overridden to nil value if Alpha feature gate for custom subnet\n\t// is not enabled. So, a non empty subnet name at this point implies that the\n\t// feature is in use.\n\tif options.SubnetName != \"\" {\n\t\tserviceState.EnabledCustomSubnet = true\n\t}\n\tklog.V(6).Infof(\"Internal Loadbalancer for Service %s ensured, updating its state %v in metrics cache\", nm, serviceState)\n\n\tstatus := \u0026v1.LoadBalancerStatus{}\n\tstatus.Ingress = []v1.LoadBalancerIngress{{IP: updatedFwdRule.IPAddress}}\n\treturn status, nil\n}","line":{"from":55,"to":255}} {"id":100034305,"name":"clearPreviousInternalResources","signature":"func (g *Cloud) clearPreviousInternalResources(svc *v1.Service, loadBalancerName string, existingBackendService *compute.BackendService, expectedBSName, expectedHCName string)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"func (g *Cloud) clearPreviousInternalResources(svc *v1.Service, loadBalancerName string, existingBackendService *compute.BackendService, expectedBSName, expectedHCName string) {\n\t// If a new backend service was created, delete the old one.\n\tif existingBackendService.Name != expectedBSName {\n\t\tklog.V(2).Infof(\"clearPreviousInternalResources(%v): expected backend service %q does not match previous %q - deleting backend service\", loadBalancerName, expectedBSName, existingBackendService.Name)\n\t\tif err := g.teardownInternalBackendService(existingBackendService.Name); err != nil \u0026\u0026 !isNotFound(err) {\n\t\t\tklog.Warningf(\"clearPreviousInternalResources: could not delete old backend service: %v, err: %v\", existingBackendService.Name, err)\n\t\t}\n\t}\n\n\t// If a new health check was created, delete the old one.\n\tif len(existingBackendService.HealthChecks) == 1 {\n\t\texistingHCName := getNameFromLink(existingBackendService.HealthChecks[0])\n\t\tif existingHCName != expectedHCName {\n\t\t\tklog.V(2).Infof(\"clearPreviousInternalResources(%v): expected health check %q does not match previous %q - deleting health check\", loadBalancerName, expectedHCName, existingHCName)\n\t\t\tif err := g.teardownInternalHealthCheckAndFirewall(svc, existingHCName); err != nil {\n\t\t\t\tklog.Warningf(\"clearPreviousInternalResources: could not delete existing healthcheck: %v, err: %v\", existingHCName, err)\n\t\t\t}\n\t\t}\n\t} else if len(existingBackendService.HealthChecks) \u003e 1 {\n\t\tklog.Warningf(\"clearPreviousInternalResources(%v): more than one health check on the backend service %v, %v\", loadBalancerName, existingBackendService.Name, existingBackendService.HealthChecks)\n\t}\n}","line":{"from":257,"to":278}} {"id":100034306,"name":"updateInternalLoadBalancer","signature":"func (g *Cloud) updateInternalLoadBalancer(clusterName, clusterID string, svc *v1.Service, nodes []*v1.Node) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"// updateInternalLoadBalancer is called when the list of nodes has changed. Therefore, only the instance groups\n// and possibly the backend service need to be updated.\nfunc (g *Cloud) updateInternalLoadBalancer(clusterName, clusterID string, svc *v1.Service, nodes []*v1.Node) error {\n\tif g.AlphaFeatureGate.Enabled(AlphaFeatureILBSubsets) \u0026\u0026 !hasFinalizer(svc, ILBFinalizerV1) {\n\t\tklog.V(2).Infof(\"Skipped updateInternalLoadBalancer for service %s/%s since it does not contain %q finalizer.\", svc.Namespace, svc.Name, ILBFinalizerV1)\n\t\treturn cloudprovider.ImplementedElsewhere\n\t}\n\tg.sharedResourceLock.Lock()\n\tdefer g.sharedResourceLock.Unlock()\n\n\tigName := makeInstanceGroupName(clusterID)\n\tigLinks, err := g.ensureInternalInstanceGroups(igName, nodes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Generate the backend service name\n\t_, _, protocol := getPortsAndProtocol(svc.Spec.Ports)\n\tscheme := cloud.SchemeInternal\n\tloadBalancerName := g.GetLoadBalancerName(context.TODO(), clusterName, svc)\n\tbackendServiceName := makeBackendServiceName(loadBalancerName, clusterID, shareBackendService(svc), scheme, protocol, svc.Spec.SessionAffinity)\n\t// Ensure the backend service has the proper backend/instance-group links\n\treturn g.ensureInternalBackendServiceGroups(backendServiceName, igLinks)\n}","line":{"from":280,"to":303}} {"id":100034307,"name":"ensureInternalLoadBalancerDeleted","signature":"func (g *Cloud) ensureInternalLoadBalancerDeleted(clusterName, clusterID string, svc *v1.Service) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"func (g *Cloud) ensureInternalLoadBalancerDeleted(clusterName, clusterID string, svc *v1.Service) error {\n\tloadBalancerName := g.GetLoadBalancerName(context.TODO(), clusterName, svc)\n\tsvcNamespacedName := types.NamespacedName{Name: svc.Name, Namespace: svc.Namespace}\n\t_, _, protocol := getPortsAndProtocol(svc.Spec.Ports)\n\tscheme := cloud.SchemeInternal\n\tsharedBackend := shareBackendService(svc)\n\tsharedHealthCheck := !servicehelpers.RequestsOnlyLocalTraffic(svc)\n\n\tg.sharedResourceLock.Lock()\n\tdefer g.sharedResourceLock.Unlock()\n\n\tklog.V(2).Infof(\"ensureInternalLoadBalancerDeleted(%v): attempting delete of region internal address\", loadBalancerName)\n\tensureAddressDeleted(g, loadBalancerName, g.region)\n\n\tklog.V(2).Infof(\"ensureInternalLoadBalancerDeleted(%v): deleting region internal forwarding rule\", loadBalancerName)\n\tif err := ignoreNotFound(g.DeleteRegionForwardingRule(loadBalancerName, g.region)); err != nil {\n\t\treturn err\n\t}\n\n\tbackendServiceName := makeBackendServiceName(loadBalancerName, clusterID, sharedBackend, scheme, protocol, svc.Spec.SessionAffinity)\n\tklog.V(2).Infof(\"ensureInternalLoadBalancerDeleted(%v): deleting region backend service %v\", loadBalancerName, backendServiceName)\n\tif err := g.teardownInternalBackendService(backendServiceName); err != nil {\n\t\treturn err\n\t}\n\n\tdeleteFunc := func(fwName string) error {\n\t\tif err := ignoreNotFound(g.DeleteFirewall(fwName)); err != nil {\n\t\t\tif isForbidden(err) \u0026\u0026 g.OnXPN() {\n\t\t\t\tklog.V(2).Infof(\"ensureInternalLoadBalancerDeleted(%v): could not delete traffic firewall on XPN cluster. Raising event.\", loadBalancerName)\n\t\t\t\tg.raiseFirewallChangeNeededEvent(svc, FirewallToGCloudDeleteCmd(fwName, g.NetworkProjectID()))\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\tfwName := MakeFirewallName(loadBalancerName)\n\tklog.V(2).Infof(\"ensureInternalLoadBalancerDeleted(%v): deleting firewall %s for traffic\",\n\t\tloadBalancerName, fwName)\n\tif err := deleteFunc(fwName); err != nil {\n\t\treturn err\n\t}\n\tklog.V(2).Infof(\"ensureInternalLoadBalancerDeleted(%v): deleting legacy name firewall for traffic\", loadBalancerName)\n\tif err := deleteFunc(loadBalancerName); err != nil {\n\t\treturn err\n\t}\n\n\thcName := makeHealthCheckName(loadBalancerName, clusterID, sharedHealthCheck)\n\tklog.V(2).Infof(\"ensureInternalLoadBalancerDeleted(%v): deleting health check %v and its firewall\", loadBalancerName, hcName)\n\tif err := g.teardownInternalHealthCheckAndFirewall(svc, hcName); err != nil {\n\t\treturn err\n\t}\n\n\t// Try deleting instance groups - expect ResourceInuse error if needed by other LBs\n\tigName := makeInstanceGroupName(clusterID)\n\tklog.V(2).Infof(\"ensureInternalLoadBalancerDeleted(%v): Attempting delete of instanceGroup %v\", loadBalancerName, igName)\n\tif err := g.ensureInternalInstanceGroupsDeleted(igName); err != nil \u0026\u0026 !isInUsedByError(err) {\n\t\treturn err\n\t}\n\n\tklog.V(2).Infof(\"ensureInternalLoadBalancerDeleted(%v): Removing %q finalizer\", loadBalancerName, ILBFinalizerV1)\n\tif err := removeFinalizer(svc, g.client.CoreV1(), ILBFinalizerV1); err != nil {\n\t\tklog.Errorf(\"Failed to remove finalizer '%s' on service %s - %v\", ILBFinalizerV1, svcNamespacedName, err)\n\t\treturn err\n\t}\n\n\tklog.V(6).Infof(\"Internal Loadbalancer for Service %s deleted, removing its state from metrics cache\", svcNamespacedName)\n\tg.metricsCollector.DeleteL4ILBService(svcNamespacedName.String())\n\treturn nil\n}","line":{"from":305,"to":374}} {"id":100034308,"name":"teardownInternalBackendService","signature":"func (g *Cloud) teardownInternalBackendService(bsName string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"func (g *Cloud) teardownInternalBackendService(bsName string) error {\n\tif err := g.DeleteRegionBackendService(bsName, g.region); err != nil {\n\t\tif isNotFound(err) {\n\t\t\tklog.V(2).Infof(\"teardownInternalBackendService(%v): backend service already deleted. err: %v\", bsName, err)\n\t\t\treturn nil\n\t\t} else if isInUsedByError(err) {\n\t\t\tklog.V(2).Infof(\"teardownInternalBackendService(%v): backend service in use.\", bsName)\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"failed to delete backend service: %v, err: %v\", bsName, err)\n\t\t}\n\t}\n\tklog.V(2).Infof(\"teardownInternalBackendService(%v): backend service deleted\", bsName)\n\treturn nil\n}","line":{"from":376,"to":390}} {"id":100034309,"name":"teardownInternalHealthCheckAndFirewall","signature":"func (g *Cloud) teardownInternalHealthCheckAndFirewall(svc *v1.Service, hcName string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"func (g *Cloud) teardownInternalHealthCheckAndFirewall(svc *v1.Service, hcName string) error {\n\tif err := g.DeleteHealthCheck(hcName); err != nil {\n\t\tif isNotFound(err) {\n\t\t\tklog.V(2).Infof(\"teardownInternalHealthCheckAndFirewall(%v): health check does not exist.\", hcName)\n\t\t\t// Purposely do not early return - double check the firewall does not exist\n\t\t} else if isInUsedByError(err) {\n\t\t\tklog.V(2).Infof(\"teardownInternalHealthCheckAndFirewall(%v): health check in use.\", hcName)\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"failed to delete health check: %v, err: %v\", hcName, err)\n\t\t}\n\t}\n\tklog.V(2).Infof(\"teardownInternalHealthCheckAndFirewall(%v): health check deleted\", hcName)\n\n\thcFirewallName := makeHealthCheckFirewallNameFromHC(hcName)\n\tif err := ignoreNotFound(g.DeleteFirewall(hcFirewallName)); err != nil {\n\t\tif isForbidden(err) \u0026\u0026 g.OnXPN() {\n\t\t\tklog.V(2).Infof(\"teardownInternalHealthCheckAndFirewall(%v): could not delete health check traffic firewall on XPN cluster. Raising Event.\", hcName)\n\t\t\tg.raiseFirewallChangeNeededEvent(svc, FirewallToGCloudDeleteCmd(hcFirewallName, g.NetworkProjectID()))\n\t\t\treturn nil\n\t\t}\n\n\t\treturn fmt.Errorf(\"failed to delete health check firewall: %v, err: %v\", hcFirewallName, err)\n\t}\n\tklog.V(2).Infof(\"teardownInternalHealthCheckAndFirewall(%v): health check firewall deleted\", hcFirewallName)\n\treturn nil\n}","line":{"from":392,"to":418}} {"id":100034310,"name":"ensureInternalFirewall","signature":"func (g *Cloud) ensureInternalFirewall(svc *v1.Service, fwName, fwDesc, destinationIP string, sourceRanges []string, portRanges []string, protocol v1.Protocol, nodes []*v1.Node, legacyFwName string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"func (g *Cloud) ensureInternalFirewall(svc *v1.Service, fwName, fwDesc, destinationIP string, sourceRanges []string, portRanges []string, protocol v1.Protocol, nodes []*v1.Node, legacyFwName string) error {\n\tklog.V(2).Infof(\"ensureInternalFirewall(%v): checking existing firewall\", fwName)\n\ttargetTags, err := g.GetNodeTags(nodeNames(nodes))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\texistingFirewall, err := g.GetFirewall(fwName)\n\tif err != nil \u0026\u0026 !isNotFound(err) {\n\t\treturn err\n\t}\n\t// TODO(84821) Remove legacyFwName logic after 3 releases, so there would have been atleast 2 master upgrades that would\n\t// have triggered service sync and deletion of the legacy rules.\n\tif legacyFwName != \"\" {\n\t\t// Check for firewall named with the legacy naming scheme and delete if found.\n\t\tlegacyFirewall, err := g.GetFirewall(legacyFwName)\n\t\tif err != nil \u0026\u0026 !isNotFound(err) {\n\t\t\treturn err\n\t\t}\n\t\tif legacyFirewall != nil \u0026\u0026 existingFirewall != nil {\n\t\t\t// Delete the legacyFirewall rule if the new one was already created. If not, it will be deleted in the\n\t\t\t// next sync or when the service is deleted.\n\t\t\tdefer func() {\n\t\t\t\terr = g.DeleteFirewall(legacyFwName)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Errorf(\"Failed to delete legacy firewall %s for service %s/%s, err %v\",\n\t\t\t\t\t\tlegacyFwName, svc.Namespace, svc.Name, err)\n\t\t\t\t} else {\n\t\t\t\t\tklog.V(2).Infof(\"Successfully deleted legacy firewall %s for service %s/%s\",\n\t\t\t\t\t\tlegacyFwName, svc.Namespace, svc.Name)\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t}\n\n\texpectedFirewall := \u0026compute.Firewall{\n\t\tName: fwName,\n\t\tDescription: fwDesc,\n\t\tNetwork: g.networkURL,\n\t\tSourceRanges: sourceRanges,\n\t\tTargetTags: targetTags,\n\t\tAllowed: []*compute.FirewallAllowed{\n\t\t\t{\n\t\t\t\tIPProtocol: strings.ToLower(string(protocol)),\n\t\t\t\tPorts: portRanges,\n\t\t\t},\n\t\t},\n\t}\n\n\tif destinationIP != \"\" {\n\t\texpectedFirewall.DestinationRanges = []string{destinationIP}\n\t}\n\n\tif existingFirewall == nil {\n\t\tklog.V(2).Infof(\"ensureInternalFirewall(%v): creating firewall\", fwName)\n\t\terr = g.CreateFirewall(expectedFirewall)\n\t\tif err != nil \u0026\u0026 isForbidden(err) \u0026\u0026 g.OnXPN() {\n\t\t\tklog.V(2).Infof(\"ensureInternalFirewall(%v): do not have permission to create firewall rule (on XPN). Raising event.\", fwName)\n\t\t\tg.raiseFirewallChangeNeededEvent(svc, FirewallToGCloudCreateCmd(expectedFirewall, g.NetworkProjectID()))\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\tif firewallRuleEqual(expectedFirewall, existingFirewall) {\n\t\treturn nil\n\t}\n\n\tklog.V(2).Infof(\"ensureInternalFirewall(%v): updating firewall\", fwName)\n\terr = g.PatchFirewall(expectedFirewall)\n\tif err != nil \u0026\u0026 isForbidden(err) \u0026\u0026 g.OnXPN() {\n\t\tklog.V(2).Infof(\"ensureInternalFirewall(%v): do not have permission to update firewall rule (on XPN). Raising event.\", fwName)\n\t\tg.raiseFirewallChangeNeededEvent(svc, FirewallToGCloudUpdateCmd(expectedFirewall, g.NetworkProjectID()))\n\t\treturn nil\n\t}\n\treturn err\n}","line":{"from":420,"to":496}} {"id":100034311,"name":"ensureInternalFirewalls","signature":"func (g *Cloud) ensureInternalFirewalls(loadBalancerName, ipAddress, clusterID string, nm types.NamespacedName, svc *v1.Service, healthCheckPort string, sharedHealthCheck bool, nodes []*v1.Node) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"func (g *Cloud) ensureInternalFirewalls(loadBalancerName, ipAddress, clusterID string, nm types.NamespacedName, svc *v1.Service, healthCheckPort string, sharedHealthCheck bool, nodes []*v1.Node) error {\n\t// First firewall is for ingress traffic\n\tfwDesc := makeFirewallDescription(nm.String(), ipAddress)\n\t_, portRanges, protocol := getPortsAndProtocol(svc.Spec.Ports)\n\tsourceRanges, err := servicehelpers.GetLoadBalancerSourceRanges(svc)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = g.ensureInternalFirewall(svc, MakeFirewallName(loadBalancerName), fwDesc, ipAddress, sourceRanges.StringSlice(), portRanges, protocol, nodes, loadBalancerName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Second firewall is for health checking nodes / services\n\tfwHCName := makeHealthCheckFirewallName(loadBalancerName, clusterID, sharedHealthCheck)\n\thcSrcRanges := L4LoadBalancerSrcRanges()\n\treturn g.ensureInternalFirewall(svc, fwHCName, \"\", \"\", hcSrcRanges, []string{healthCheckPort}, v1.ProtocolTCP, nodes, \"\")\n}","line":{"from":498,"to":515}} {"id":100034312,"name":"ensureInternalHealthCheck","signature":"func (g *Cloud) ensureInternalHealthCheck(name string, svcName types.NamespacedName, shared bool, path string, port int32) (*compute.HealthCheck, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"func (g *Cloud) ensureInternalHealthCheck(name string, svcName types.NamespacedName, shared bool, path string, port int32) (*compute.HealthCheck, error) {\n\tklog.V(2).Infof(\"ensureInternalHealthCheck(%v, %v, %v): checking existing health check\", name, path, port)\n\texpectedHC := newInternalLBHealthCheck(name, svcName, shared, path, port)\n\n\thc, err := g.GetHealthCheck(name)\n\tif err != nil \u0026\u0026 !isNotFound(err) {\n\t\treturn nil, err\n\t}\n\n\tif hc == nil {\n\t\tklog.V(2).Infof(\"ensureInternalHealthCheck: did not find health check %v, creating one with port %v path %v\", name, port, path)\n\t\tif err = g.CreateHealthCheck(expectedHC); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\thc, err = g.GetHealthCheck(name)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to get http health check %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tklog.V(2).Infof(\"ensureInternalHealthCheck: created health check %v\", name)\n\t\treturn hc, nil\n\t}\n\n\tif needToUpdateHealthChecks(hc, expectedHC) {\n\t\tklog.V(2).Infof(\"ensureInternalHealthCheck: health check %v exists but parameters have drifted - updating...\", name)\n\t\tmergeHealthChecks(hc, expectedHC)\n\t\tif err := g.UpdateHealthCheck(expectedHC); err != nil {\n\t\t\tklog.Warningf(\"Failed to reconcile http health check %v parameters\", name)\n\t\t\treturn nil, err\n\t\t}\n\t\tklog.V(2).Infof(\"ensureInternalHealthCheck: corrected health check %v parameters successful\", name)\n\t\thc, err = g.GetHealthCheck(name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn hc, nil\n}","line":{"from":517,"to":554}} {"id":100034313,"name":"ensureInternalInstanceGroup","signature":"func (g *Cloud) ensureInternalInstanceGroup(name, zone string, nodes []*v1.Node) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"func (g *Cloud) ensureInternalInstanceGroup(name, zone string, nodes []*v1.Node) (string, error) {\n\tklog.V(2).Infof(\"ensureInternalInstanceGroup(%v, %v): checking group that it contains %v nodes\", name, zone, len(nodes))\n\tig, err := g.GetInstanceGroup(name, zone)\n\tif err != nil \u0026\u0026 !isNotFound(err) {\n\t\treturn \"\", err\n\t}\n\n\tkubeNodes := sets.NewString()\n\tfor _, n := range nodes {\n\t\tkubeNodes.Insert(n.Name)\n\t}\n\n\t// Individual InstanceGroup has a limit for 1000 instances in it.\n\t// As a result, it's not possible to add more to it.\n\t// Given that the long-term fix (AlphaFeatureILBSubsets) is already in-progress,\n\t// to stop the bleeding we now simply cut down the contents to first 1000\n\t// instances in the alphabetical order. Since there is a limitation for\n\t// 250 backend VMs for ILB, this isn't making things worse.\n\tif len(kubeNodes) \u003e maxInstancesPerInstanceGroup {\n\t\tklog.Warningf(\"Limiting number of VMs for InstanceGroup %s to %d\", name, maxInstancesPerInstanceGroup)\n\t\tkubeNodes = sets.NewString(kubeNodes.List()[:maxInstancesPerInstanceGroup]...)\n\t}\n\n\tgceNodes := sets.NewString()\n\tif ig == nil {\n\t\tklog.V(2).Infof(\"ensureInternalInstanceGroup(%v, %v): creating instance group\", name, zone)\n\t\tnewIG := \u0026compute.InstanceGroup{Name: name}\n\t\tif err = g.CreateInstanceGroup(newIG, zone); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tig, err = g.GetInstanceGroup(name, zone)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t} else {\n\t\tinstances, err := g.ListInstancesInInstanceGroup(name, zone, allInstances)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tfor _, ins := range instances {\n\t\t\tparts := strings.Split(ins.Instance, \"/\")\n\t\t\tgceNodes.Insert(parts[len(parts)-1])\n\t\t}\n\t}\n\n\tremoveNodes := gceNodes.Difference(kubeNodes).List()\n\taddNodes := kubeNodes.Difference(gceNodes).List()\n\n\tif len(removeNodes) != 0 {\n\t\tklog.V(2).Infof(\"ensureInternalInstanceGroup(%v, %v): removing nodes: %v\", name, zone, removeNodes)\n\t\tinstanceRefs := g.ToInstanceReferences(zone, removeNodes)\n\t\t// Possible we'll receive 404's here if the instance was deleted before getting to this point.\n\t\tif err = g.RemoveInstancesFromInstanceGroup(name, zone, instanceRefs); err != nil \u0026\u0026 !isNotFound(err) {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tif len(addNodes) != 0 {\n\t\tklog.V(2).Infof(\"ensureInternalInstanceGroup(%v, %v): adding nodes: %v\", name, zone, addNodes)\n\t\tinstanceRefs := g.ToInstanceReferences(zone, addNodes)\n\t\tif err = g.AddInstancesToInstanceGroup(name, zone, instanceRefs); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\treturn ig.SelfLink, nil\n}","line":{"from":556,"to":624}} {"id":100034314,"name":"ensureInternalInstanceGroups","signature":"func (g *Cloud) ensureInternalInstanceGroups(name string, nodes []*v1.Node) ([]string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"// ensureInternalInstanceGroups generates an unmanaged instance group for every zone\n// where a K8s node exists. It also ensures that each node belongs to an instance group\nfunc (g *Cloud) ensureInternalInstanceGroups(name string, nodes []*v1.Node) ([]string, error) {\n\tzonedNodes := splitNodesByZone(nodes)\n\tklog.V(2).Infof(\"ensureInternalInstanceGroups(%v): %d nodes over %d zones in region %v\", name, len(nodes), len(zonedNodes), g.region)\n\tvar igLinks []string\n\tfor zone, nodes := range zonedNodes {\n\t\tif g.AlphaFeatureGate.Enabled(AlphaFeatureSkipIGsManagement) {\n\t\t\tigs, err := g.FilterInstanceGroupsByNamePrefix(name, zone)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfor _, ig := range igs {\n\t\t\t\tigLinks = append(igLinks, ig.SelfLink)\n\t\t\t}\n\t\t} else {\n\t\t\tigLink, err := g.ensureInternalInstanceGroup(name, zone, nodes)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tigLinks = append(igLinks, igLink)\n\t\t}\n\t}\n\n\treturn igLinks, nil\n}","line":{"from":626,"to":651}} {"id":100034315,"name":"ensureInternalInstanceGroupsDeleted","signature":"func (g *Cloud) ensureInternalInstanceGroupsDeleted(name string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"func (g *Cloud) ensureInternalInstanceGroupsDeleted(name string) error {\n\t// List of nodes isn't available here - fetch all zones in region and try deleting this cluster's ig\n\tzones, err := g.ListZonesInRegion(g.region)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Skip Instance Group deletion if IG management was moved out of k/k code\n\tif !g.AlphaFeatureGate.Enabled(AlphaFeatureSkipIGsManagement) {\n\t\tklog.V(2).Infof(\"ensureInternalInstanceGroupsDeleted(%v): attempting delete instance group in all %d zones\", name, len(zones))\n\t\tfor _, z := range zones {\n\t\t\tif err := g.DeleteInstanceGroup(name, z.Name); err != nil \u0026\u0026 !isNotFoundOrInUse(err) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":653,"to":670}} {"id":100034316,"name":"ensureInternalBackendService","signature":"func (g *Cloud) ensureInternalBackendService(name, description string, affinityType v1.ServiceAffinity, scheme cloud.LbScheme, protocol v1.Protocol, igLinks []string, hcLink string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"func (g *Cloud) ensureInternalBackendService(name, description string, affinityType v1.ServiceAffinity, scheme cloud.LbScheme, protocol v1.Protocol, igLinks []string, hcLink string) error {\n\tklog.V(2).Infof(\"ensureInternalBackendService(%v, %v, %v): checking existing backend service with %d groups\", name, scheme, protocol, len(igLinks))\n\tbs, err := g.GetRegionBackendService(name, g.region)\n\tif err != nil \u0026\u0026 !isNotFound(err) {\n\t\treturn err\n\t}\n\n\tbackends := backendsFromGroupLinks(igLinks)\n\texpectedBS := \u0026compute.BackendService{\n\t\tName: name,\n\t\tProtocol: string(protocol),\n\t\tDescription: description,\n\t\tHealthChecks: []string{hcLink},\n\t\tBackends: backends,\n\t\tSessionAffinity: translateAffinityType(affinityType),\n\t\tLoadBalancingScheme: string(scheme),\n\t}\n\n\t// Create backend service if none was found\n\tif bs == nil {\n\t\tklog.V(2).Infof(\"ensureInternalBackendService: creating backend service %v\", name)\n\t\terr := g.CreateRegionBackendService(expectedBS, g.region)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tklog.V(2).Infof(\"ensureInternalBackendService: created backend service %v successfully\", name)\n\t\treturn nil\n\t}\n\n\tif backendSvcEqual(expectedBS, bs) {\n\t\treturn nil\n\t}\n\n\tklog.V(2).Infof(\"ensureInternalBackendService: updating backend service %v\", name)\n\t// Set fingerprint for optimistic locking\n\texpectedBS.Fingerprint = bs.Fingerprint\n\tif err := g.UpdateRegionBackendService(expectedBS, g.region); err != nil {\n\t\treturn err\n\t}\n\tklog.V(2).Infof(\"ensureInternalBackendService: updated backend service %v successfully\", name)\n\treturn nil\n}","line":{"from":672,"to":713}} {"id":100034317,"name":"ensureInternalBackendServiceGroups","signature":"func (g *Cloud) ensureInternalBackendServiceGroups(name string, igLinks []string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"// ensureInternalBackendServiceGroups updates backend services if their list of backend instance groups is incorrect.\nfunc (g *Cloud) ensureInternalBackendServiceGroups(name string, igLinks []string) error {\n\tklog.V(2).Infof(\"ensureInternalBackendServiceGroups(%v): checking existing backend service's groups\", name)\n\tbs, err := g.GetRegionBackendService(name, g.region)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbackends := backendsFromGroupLinks(igLinks)\n\tif backendsListEqual(bs.Backends, backends) {\n\t\treturn nil\n\t}\n\n\t// Set the backend service's backends to the updated list.\n\tbs.Backends = backends\n\n\tklog.V(2).Infof(\"ensureInternalBackendServiceGroups: updating backend service %v\", name)\n\tif err := g.UpdateRegionBackendService(bs, g.region); err != nil {\n\t\treturn err\n\t}\n\tklog.V(2).Infof(\"ensureInternalBackendServiceGroups: updated backend service %v successfully\", name)\n\treturn nil\n}","line":{"from":715,"to":737}} {"id":100034318,"name":"shareBackendService","signature":"func shareBackendService(svc *v1.Service) bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"func shareBackendService(svc *v1.Service) bool {\n\treturn GetLoadBalancerAnnotationBackendShare(svc) \u0026\u0026 !servicehelpers.RequestsOnlyLocalTraffic(svc)\n}","line":{"from":739,"to":741}} {"id":100034319,"name":"backendsFromGroupLinks","signature":"func backendsFromGroupLinks(igLinks []string) (backends []*compute.Backend)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"func backendsFromGroupLinks(igLinks []string) (backends []*compute.Backend) {\n\tfor _, igLink := range igLinks {\n\t\tbackends = append(backends, \u0026compute.Backend{\n\t\t\tGroup: igLink,\n\t\t})\n\t}\n\treturn backends\n}","line":{"from":743,"to":750}} {"id":100034320,"name":"newInternalLBHealthCheck","signature":"func newInternalLBHealthCheck(name string, svcName types.NamespacedName, shared bool, path string, port int32) *compute.HealthCheck","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"func newInternalLBHealthCheck(name string, svcName types.NamespacedName, shared bool, path string, port int32) *compute.HealthCheck {\n\thttpSettings := compute.HTTPHealthCheck{\n\t\tPort: int64(port),\n\t\tRequestPath: path,\n\t}\n\tdesc := \"\"\n\tif !shared {\n\t\tdesc = makeHealthCheckDescription(svcName.String())\n\t}\n\treturn \u0026compute.HealthCheck{\n\t\tName: name,\n\t\tCheckIntervalSec: gceHcCheckIntervalSeconds,\n\t\tTimeoutSec: gceHcTimeoutSeconds,\n\t\tHealthyThreshold: gceHcHealthyThreshold,\n\t\tUnhealthyThreshold: gceHcUnhealthyThreshold,\n\t\tHttpHealthCheck: \u0026httpSettings,\n\t\tType: \"HTTP\",\n\t\tDescription: desc,\n\t}\n}","line":{"from":752,"to":771}} {"id":100034321,"name":"firewallRuleEqual","signature":"func firewallRuleEqual(a, b *compute.Firewall) bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"func firewallRuleEqual(a, b *compute.Firewall) bool {\n\treturn a.Description == b.Description \u0026\u0026\n\t\tlen(a.Allowed) == 1 \u0026\u0026 len(a.Allowed) == len(b.Allowed) \u0026\u0026\n\t\ta.Allowed[0].IPProtocol == b.Allowed[0].IPProtocol \u0026\u0026\n\t\tequalStringSets(a.Allowed[0].Ports, b.Allowed[0].Ports) \u0026\u0026\n\t\tequalStringSets(a.SourceRanges, b.SourceRanges) \u0026\u0026\n\t\tequalStringSets(a.DestinationRanges, b.DestinationRanges) \u0026\u0026\n\t\tequalStringSets(a.TargetTags, b.TargetTags)\n}","line":{"from":773,"to":781}} {"id":100034322,"name":"mergeHealthChecks","signature":"func mergeHealthChecks(hc, newHC *compute.HealthCheck)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"// mergeHealthChecks reconciles HealthCheck configures to be no smaller than\n// the default values.\n// E.g. old health check interval is 2s, new default is 8.\n// The HC interval will be reconciled to 8 seconds.\n// If the existing health check is larger than the default interval,\n// the configuration will be kept.\nfunc mergeHealthChecks(hc, newHC *compute.HealthCheck) {\n\tif hc.CheckIntervalSec \u003e newHC.CheckIntervalSec {\n\t\tnewHC.CheckIntervalSec = hc.CheckIntervalSec\n\t}\n\tif hc.TimeoutSec \u003e newHC.TimeoutSec {\n\t\tnewHC.TimeoutSec = hc.TimeoutSec\n\t}\n\tif hc.UnhealthyThreshold \u003e newHC.UnhealthyThreshold {\n\t\tnewHC.UnhealthyThreshold = hc.UnhealthyThreshold\n\t}\n\tif hc.HealthyThreshold \u003e newHC.HealthyThreshold {\n\t\tnewHC.HealthyThreshold = hc.HealthyThreshold\n\t}\n}","line":{"from":783,"to":802}} {"id":100034323,"name":"needToUpdateHealthChecks","signature":"func needToUpdateHealthChecks(hc, newHC *compute.HealthCheck) bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"// needToUpdateHealthChecks checks whether the healthcheck needs to be updated.\nfunc needToUpdateHealthChecks(hc, newHC *compute.HealthCheck) bool {\n\tswitch {\n\tcase\n\t\thc.HttpHealthCheck == nil,\n\t\tnewHC.HttpHealthCheck == nil,\n\t\thc.HttpHealthCheck.Port != newHC.HttpHealthCheck.Port,\n\t\thc.HttpHealthCheck.RequestPath != newHC.HttpHealthCheck.RequestPath,\n\t\thc.Description != newHC.Description,\n\t\thc.CheckIntervalSec \u003c newHC.CheckIntervalSec,\n\t\thc.TimeoutSec \u003c newHC.TimeoutSec,\n\t\thc.UnhealthyThreshold \u003c newHC.UnhealthyThreshold,\n\t\thc.HealthyThreshold \u003c newHC.HealthyThreshold:\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":804,"to":820}} {"id":100034324,"name":"backendsListEqual","signature":"func backendsListEqual(a, b []*compute.Backend) bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"// backendsListEqual asserts that backend lists are equal by instance group link only\nfunc backendsListEqual(a, b []*compute.Backend) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tif len(a) == 0 {\n\t\treturn true\n\t}\n\n\taSet := sets.NewString()\n\tfor _, v := range a {\n\t\taSet.Insert(v.Group)\n\t}\n\tbSet := sets.NewString()\n\tfor _, v := range b {\n\t\tbSet.Insert(v.Group)\n\t}\n\n\treturn aSet.Equal(bSet)\n}","line":{"from":822,"to":841}} {"id":100034325,"name":"backendSvcEqual","signature":"func backendSvcEqual(a, b *compute.BackendService) bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"func backendSvcEqual(a, b *compute.BackendService) bool {\n\treturn a.Protocol == b.Protocol \u0026\u0026\n\t\ta.Description == b.Description \u0026\u0026\n\t\ta.SessionAffinity == b.SessionAffinity \u0026\u0026\n\t\ta.LoadBalancingScheme == b.LoadBalancingScheme \u0026\u0026\n\t\tequalStringSets(a.HealthChecks, b.HealthChecks) \u0026\u0026\n\t\tbackendsListEqual(a.Backends, b.Backends)\n}","line":{"from":843,"to":850}} {"id":100034326,"name":"getPortsAndProtocol","signature":"func getPortsAndProtocol(svcPorts []v1.ServicePort) (ports []string, portRanges []string, protocol v1.Protocol)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"func getPortsAndProtocol(svcPorts []v1.ServicePort) (ports []string, portRanges []string, protocol v1.Protocol) {\n\tif len(svcPorts) == 0 {\n\t\treturn []string{}, []string{}, v1.ProtocolUDP\n\t}\n\n\t// GCP doesn't support multiple protocols for a single load balancer\n\tprotocol = svcPorts[0].Protocol\n\tportInts := []int{}\n\tfor _, p := range svcPorts {\n\t\tports = append(ports, strconv.Itoa(int(p.Port)))\n\t\tportInts = append(portInts, int(p.Port))\n\t}\n\n\treturn ports, getPortRanges(portInts), protocol\n}","line":{"from":852,"to":866}} {"id":100034327,"name":"getPortRanges","signature":"func getPortRanges(ports []int) (ranges []string)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"func getPortRanges(ports []int) (ranges []string) {\n\tif len(ports) \u003c 1 {\n\t\treturn ranges\n\t}\n\tsort.Ints(ports)\n\n\tstart := ports[0]\n\tprev := ports[0]\n\tfor ix, current := range ports {\n\t\tswitch {\n\t\tcase current == prev:\n\t\t\t// Loop over duplicates, except if the end of list is reached.\n\t\t\tif ix == len(ports)-1 {\n\t\t\t\tif start == current {\n\t\t\t\t\tranges = append(ranges, fmt.Sprintf(\"%d\", current))\n\t\t\t\t} else {\n\t\t\t\t\tranges = append(ranges, fmt.Sprintf(\"%d-%d\", start, current))\n\t\t\t\t}\n\t\t\t}\n\t\tcase current == prev+1:\n\t\t\t// continue the streak, create the range if this is the last element in the list.\n\t\t\tif ix == len(ports)-1 {\n\t\t\t\tranges = append(ranges, fmt.Sprintf(\"%d-%d\", start, current))\n\t\t\t}\n\t\tdefault:\n\t\t\t// current is not prev + 1, streak is broken. Construct the range and handle last element case.\n\t\t\tif start == prev {\n\t\t\t\tranges = append(ranges, fmt.Sprintf(\"%d\", prev))\n\t\t\t} else {\n\t\t\t\tranges = append(ranges, fmt.Sprintf(\"%d-%d\", start, prev))\n\t\t\t}\n\t\t\tif ix == len(ports)-1 {\n\t\t\t\tranges = append(ranges, fmt.Sprintf(\"%d\", current))\n\t\t\t}\n\t\t\t// reset start element\n\t\t\tstart = current\n\t\t}\n\t\tprev = current\n\t}\n\treturn ranges\n}","line":{"from":868,"to":908}} {"id":100034328,"name":"getBackendServiceLink","signature":"func (g *Cloud) getBackendServiceLink(name string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"func (g *Cloud) getBackendServiceLink(name string) string {\n\treturn g.projectsBasePath + strings.Join([]string{g.projectID, \"regions\", g.region, \"backendServices\", name}, \"/\")\n}","line":{"from":910,"to":912}} {"id":100034329,"name":"getNameFromLink","signature":"func getNameFromLink(link string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"func getNameFromLink(link string) string {\n\tif link == \"\" {\n\t\treturn \"\"\n\t}\n\n\tfields := strings.Split(link, \"/\")\n\treturn fields[len(fields)-1]\n}","line":{"from":914,"to":921}} {"id":100034330,"name":"ilbIPToUse","signature":"func ilbIPToUse(svc *v1.Service, fwdRule *compute.ForwardingRule, requestedSubnet string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"// ilbIPToUse determines which IP address needs to be used in the ForwardingRule. If an IP has been\n// specified by the user, that is used. If there is an existing ForwardingRule, the ip address from\n// that is reused. In case a subnetwork change is requested, the existing ForwardingRule IP is ignored.\nfunc ilbIPToUse(svc *v1.Service, fwdRule *compute.ForwardingRule, requestedSubnet string) string {\n\tif svc.Spec.LoadBalancerIP != \"\" {\n\t\treturn svc.Spec.LoadBalancerIP\n\t}\n\tif fwdRule == nil {\n\t\treturn \"\"\n\t}\n\tif requestedSubnet != fwdRule.Subnetwork {\n\t\t// reset ip address since subnet is being changed.\n\t\treturn \"\"\n\t}\n\treturn fwdRule.IPAddress\n}","line":{"from":923,"to":938}} {"id":100034331,"name":"getILBOptions","signature":"func getILBOptions(svc *v1.Service) ILBOptions","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"func getILBOptions(svc *v1.Service) ILBOptions {\n\treturn ILBOptions{AllowGlobalAccess: GetLoadBalancerAnnotationAllowGlobalAccess(svc),\n\t\tSubnetName: GetLoadBalancerAnnotationSubnet(svc),\n\t}\n}","line":{"from":940,"to":944}} {"id":100034332,"name":"marshal","signature":"func (d *forwardingRuleDescription) marshal() (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"// marshal the description as a JSON-encoded string.\nfunc (d *forwardingRuleDescription) marshal() (string, error) {\n\tout, err := json.Marshal(d)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(out), err\n}","line":{"from":951,"to":958}} {"id":100034333,"name":"unmarshal","signature":"func (d *forwardingRuleDescription) unmarshal(desc string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"// unmarshal desc JSON-encoded string into this structure.\nfunc (d *forwardingRuleDescription) unmarshal(desc string) error {\n\treturn json.Unmarshal([]byte(desc), d)\n}","line":{"from":960,"to":963}} {"id":100034334,"name":"getFwdRuleAPIVersion","signature":"func getFwdRuleAPIVersion(rule *compute.ForwardingRule) (meta.Version, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"func getFwdRuleAPIVersion(rule *compute.ForwardingRule) (meta.Version, error) {\n\td := \u0026forwardingRuleDescription{}\n\tif rule.Description == \"\" {\n\t\treturn meta.VersionGA, nil\n\t}\n\tif err := d.unmarshal(rule.Description); err != nil {\n\t\treturn meta.VersionGA, fmt.Errorf(\"Failed to get APIVersion from Forwarding rule %s - %v\", rule.Name, err)\n\t}\n\tif d.APIVersion == \"\" {\n\t\td.APIVersion = meta.VersionGA\n\t}\n\treturn d.APIVersion, nil\n}","line":{"from":965,"to":977}} {"id":100034335,"name":"ensureInternalForwardingRule","signature":"func (g *Cloud) ensureInternalForwardingRule(existingFwdRule, newFwdRule *compute.ForwardingRule) (err error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"func (g *Cloud) ensureInternalForwardingRule(existingFwdRule, newFwdRule *compute.ForwardingRule) (err error) {\n\tif existingFwdRule != nil {\n\t\tif forwardingRulesEqual(existingFwdRule, newFwdRule) {\n\t\t\tklog.V(4).Infof(\"existingFwdRule == newFwdRule, no updates needed (existingFwdRule == %+v)\", existingFwdRule)\n\t\t\treturn nil\n\t\t}\n\t\tklog.V(2).Infof(\"ensureInternalLoadBalancer(%v): deleting existing forwarding rule with IP address %v\", existingFwdRule.Name, existingFwdRule.IPAddress)\n\t\tif err = ignoreNotFound(g.DeleteRegionForwardingRule(existingFwdRule.Name, g.region)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// At this point, the existing rule has been deleted if required.\n\t// Create the rule based on the api version determined\n\tklog.V(2).Infof(\"ensureInternalLoadBalancer(%v): creating forwarding rule\", newFwdRule.Name)\n\tif err = g.CreateRegionForwardingRule(newFwdRule, g.region); err != nil {\n\t\treturn err\n\t}\n\tklog.V(2).Infof(\"ensureInternalLoadBalancer(%v): created forwarding rule\", newFwdRule.Name)\n\treturn nil\n}","line":{"from":979,"to":998}} {"id":100034336,"name":"forwardingRulesEqual","signature":"func forwardingRulesEqual(old, new *compute.ForwardingRule) bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_internal.go","code":"func forwardingRulesEqual(old, new *compute.ForwardingRule) bool {\n\t// basepath could have differences like compute.googleapis.com vs www.googleapis.com, compare resourceIDs\n\toldResourceID, err := cloud.ParseResourceURL(old.BackendService)\n\tif err != nil {\n\t\tklog.Errorf(\"forwardingRulesEqual(): failed to parse backend resource URL from existing FR, err - %v\", err)\n\t}\n\tnewResourceID, err := cloud.ParseResourceURL(new.BackendService)\n\tif err != nil {\n\t\tklog.Errorf(\"forwardingRulesEqual(): failed to parse resource URL from new FR, err - %v\", err)\n\t}\n\treturn (old.IPAddress == \"\" || new.IPAddress == \"\" || old.IPAddress == new.IPAddress) \u0026\u0026\n\t\told.IPProtocol == new.IPProtocol \u0026\u0026\n\t\told.LoadBalancingScheme == new.LoadBalancingScheme \u0026\u0026\n\t\tequalStringSets(old.Ports, new.Ports) \u0026\u0026\n\t\told.AllPorts == new.AllPorts \u0026\u0026\n\t\toldResourceID.Equal(newResourceID) \u0026\u0026\n\t\told.AllowGlobalAccess == new.AllowGlobalAccess \u0026\u0026\n\t\told.Subnetwork == new.Subnetwork\n}","line":{"from":1000,"to":1018}} {"id":100034337,"name":"init","signature":"func init()","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_metrics.go","code":"// init registers L4 internal loadbalancer usage metrics.\nfunc init() {\n\tklog.V(3).Infof(\"Registering Service Controller loadbalancer usage metrics %v\", l4ILBCount)\n\tlegacyregistry.MustRegister(l4ILBCount)\n}","line":{"from":48,"to":52}} {"id":100034338,"name":"String","signature":"func (f feature) String() string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_metrics.go","code":"func (f feature) String() string {\n\treturn string(f)\n}","line":{"from":65,"to":67}} {"id":100034339,"name":"newLoadBalancerMetrics","signature":"func newLoadBalancerMetrics() loadbalancerMetricsCollector","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_metrics.go","code":"// newLoadBalancerMetrics initializes LoadBalancerMetrics and starts a goroutine\n// to compute and export metrics periodically.\nfunc newLoadBalancerMetrics() loadbalancerMetricsCollector {\n\treturn \u0026LoadBalancerMetrics{\n\t\tl4ILBServiceMap: make(map[string]L4ILBServiceState),\n\t}\n}","line":{"from":102,"to":108}} {"id":100034340,"name":"Run","signature":"func (lm *LoadBalancerMetrics) Run(stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_metrics.go","code":"// Run implements loadbalancerMetricsCollector.\nfunc (lm *LoadBalancerMetrics) Run(stopCh \u003c-chan struct{}) {\n\tklog.V(3).Infof(\"Loadbalancer Metrics initialized. Metrics will be exported at an interval of %v\", metricsInterval)\n\t// Compute and export metrics periodically.\n\tgo func() {\n\t\t// Wait for service states to be populated in the cache before computing metrics.\n\t\ttime.Sleep(metricsInterval)\n\t\twait.Until(lm.export, metricsInterval, stopCh)\n\t}()\n\t\u003c-stopCh\n}","line":{"from":110,"to":120}} {"id":100034341,"name":"SetL4ILBService","signature":"func (lm *LoadBalancerMetrics) SetL4ILBService(svcKey string, state L4ILBServiceState)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_metrics.go","code":"// SetL4ILBService implements loadbalancerMetricsCollector.\nfunc (lm *LoadBalancerMetrics) SetL4ILBService(svcKey string, state L4ILBServiceState) {\n\tlm.Lock()\n\tdefer lm.Unlock()\n\n\tif lm.l4ILBServiceMap == nil {\n\t\tklog.Fatalf(\"Loadbalancer Metrics failed to initialize correctly.\")\n\t}\n\tlm.l4ILBServiceMap[svcKey] = state\n}","line":{"from":122,"to":131}} {"id":100034342,"name":"DeleteL4ILBService","signature":"func (lm *LoadBalancerMetrics) DeleteL4ILBService(svcKey string)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_metrics.go","code":"// DeleteL4ILBService implements loadbalancerMetricsCollector.\nfunc (lm *LoadBalancerMetrics) DeleteL4ILBService(svcKey string) {\n\tlm.Lock()\n\tdefer lm.Unlock()\n\n\tdelete(lm.l4ILBServiceMap, svcKey)\n}","line":{"from":133,"to":139}} {"id":100034343,"name":"export","signature":"func (lm *LoadBalancerMetrics) export()","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_metrics.go","code":"// export computes and exports loadbalancer usage metrics.\nfunc (lm *LoadBalancerMetrics) export() {\n\tilbCount := lm.computeL4ILBMetrics()\n\tklog.V(5).Infof(\"Exporting L4 ILB usage metrics: %#v\", ilbCount)\n\tfor feature, count := range ilbCount {\n\t\tl4ILBCount.With(map[string]string{label: feature.String()}).Set(float64(count))\n\t}\n\tklog.V(5).Infof(\"L4 ILB usage metrics exported.\")\n}","line":{"from":141,"to":149}} {"id":100034344,"name":"computeL4ILBMetrics","signature":"func (lm *LoadBalancerMetrics) computeL4ILBMetrics() map[feature]int","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_metrics.go","code":"// computeL4ILBMetrics aggregates L4 ILB metrics in the cache.\nfunc (lm *LoadBalancerMetrics) computeL4ILBMetrics() map[feature]int {\n\tlm.Lock()\n\tdefer lm.Unlock()\n\tklog.V(4).Infof(\"Computing L4 ILB usage metrics from service state map: %#v\", lm.l4ILBServiceMap)\n\tcounts := map[feature]int{\n\t\tl4ILBService: 0,\n\t\tl4ILBGlobalAccess: 0,\n\t\tl4ILBCustomSubnet: 0,\n\t\tl4ILBInSuccess: 0,\n\t\tl4ILBInError: 0,\n\t}\n\n\tfor key, state := range lm.l4ILBServiceMap {\n\t\tklog.V(6).Infof(\"ILB Service %s has EnabledGlobalAccess: %t, EnabledCustomSubnet: %t, InSuccess: %t\", key, state.EnabledGlobalAccess, state.EnabledCustomSubnet, state.InSuccess)\n\t\tcounts[l4ILBService]++\n\t\tif !state.InSuccess {\n\t\t\tcounts[l4ILBInError]++\n\t\t\t// Skip counting other features if the service is in error state.\n\t\t\tcontinue\n\t\t}\n\t\tcounts[l4ILBInSuccess]++\n\t\tif state.EnabledGlobalAccess {\n\t\t\tcounts[l4ILBGlobalAccess]++\n\t\t}\n\t\tif state.EnabledCustomSubnet {\n\t\t\tcounts[l4ILBCustomSubnet]++\n\t\t}\n\t}\n\tklog.V(4).Info(\"L4 ILB usage metrics computed.\")\n\treturn counts\n}","line":{"from":151,"to":182}} {"id":100034345,"name":"makeInstanceGroupName","signature":"func makeInstanceGroupName(clusterID string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_naming.go","code":"// Instance groups remain legacy named to stay consistent with ingress\nfunc makeInstanceGroupName(clusterID string) string {\n\tprefix := \"k8s-ig\"\n\t// clusterID might be empty for legacy clusters\n\tif clusterID == \"\" {\n\t\treturn prefix\n\t}\n\treturn fmt.Sprintf(\"%s--%s\", prefix, clusterID)\n}","line":{"from":35,"to":43}} {"id":100034346,"name":"makeBackendServiceName","signature":"func makeBackendServiceName(loadBalancerName, clusterID string, shared bool, scheme cloud.LbScheme, protocol v1.Protocol, svcAffinity v1.ServiceAffinity) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_naming.go","code":"func makeBackendServiceName(loadBalancerName, clusterID string, shared bool, scheme cloud.LbScheme, protocol v1.Protocol, svcAffinity v1.ServiceAffinity) string {\n\tif shared {\n\t\thash := sha1.New()\n\n\t\t// For every non-nil option, hash its value. Currently, only service affinity is relevant.\n\t\thash.Write([]byte(string(svcAffinity)))\n\n\t\thashed := hex.EncodeToString(hash.Sum(nil))\n\t\thashed = hashed[:16]\n\n\t\t// k8s- 4\n\t\t// {clusterid}- 17\n\t\t// {scheme}- 9 (internal/external)\n\t\t// {protocol}- 4 (tcp/udp)\n\t\t// nmv1- 5 (naming convention version)\n\t\t// {suffix} 16 (hash of settings)\n\t\t// -----------------\n\t\t// 55 characters used\n\t\treturn fmt.Sprintf(\"k8s-%s-%s-%s-nmv1-%s\", clusterID, strings.ToLower(string(scheme)), strings.ToLower(string(protocol)), hashed)\n\t}\n\treturn loadBalancerName\n}","line":{"from":45,"to":66}} {"id":100034347,"name":"makeHealthCheckName","signature":"func makeHealthCheckName(loadBalancerName, clusterID string, shared bool) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_naming.go","code":"func makeHealthCheckName(loadBalancerName, clusterID string, shared bool) string {\n\tif shared {\n\t\treturn fmt.Sprintf(\"k8s-%s-node\", clusterID)\n\t}\n\n\treturn loadBalancerName\n}","line":{"from":68,"to":74}} {"id":100034348,"name":"makeHealthCheckFirewallNameFromHC","signature":"func makeHealthCheckFirewallNameFromHC(healthCheckName string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_naming.go","code":"func makeHealthCheckFirewallNameFromHC(healthCheckName string) string {\n\treturn healthCheckName + \"-hc\"\n}","line":{"from":76,"to":78}} {"id":100034349,"name":"makeHealthCheckFirewallName","signature":"func makeHealthCheckFirewallName(loadBalancerName, clusterID string, shared bool) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_naming.go","code":"func makeHealthCheckFirewallName(loadBalancerName, clusterID string, shared bool) string {\n\tif shared {\n\t\treturn fmt.Sprintf(\"k8s-%s-node-hc\", clusterID)\n\t}\n\treturn loadBalancerName + \"-hc\"\n}","line":{"from":80,"to":85}} {"id":100034350,"name":"makeBackendServiceDescription","signature":"func makeBackendServiceDescription(nm types.NamespacedName, shared bool) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_naming.go","code":"func makeBackendServiceDescription(nm types.NamespacedName, shared bool) string {\n\tif shared {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(`{\"kubernetes.io/service-name\":\"%s\"}`, nm.String())\n}","line":{"from":87,"to":92}} {"id":100034351,"name":"makeServiceDescription","signature":"func makeServiceDescription(serviceName string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_naming.go","code":"// makeServiceDescription is used to generate descriptions for forwarding rules and addresses.\nfunc makeServiceDescription(serviceName string) string {\n\treturn fmt.Sprintf(`{\"kubernetes.io/service-name\":\"%s\"}`, serviceName)\n}","line":{"from":96,"to":99}} {"id":100034352,"name":"MakeNodesHealthCheckName","signature":"func MakeNodesHealthCheckName(clusterID string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_naming.go","code":"// MakeNodesHealthCheckName returns name of the health check resource used by\n// the GCE load balancers (l4) for performing health checks on nodes.\nfunc MakeNodesHealthCheckName(clusterID string) string {\n\treturn fmt.Sprintf(\"k8s-%v-node\", clusterID)\n}","line":{"from":101,"to":105}} {"id":100034353,"name":"makeHealthCheckDescription","signature":"func makeHealthCheckDescription(serviceName string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_naming.go","code":"func makeHealthCheckDescription(serviceName string) string {\n\treturn fmt.Sprintf(`{\"kubernetes.io/service-name\":\"%s\"}`, serviceName)\n}","line":{"from":107,"to":109}} {"id":100034354,"name":"MakeHealthCheckFirewallName","signature":"func MakeHealthCheckFirewallName(clusterID, hcName string, isNodesHealthCheck bool) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_naming.go","code":"// MakeHealthCheckFirewallName returns the firewall name used by the GCE load\n// balancers (l4) for performing health checks.\nfunc MakeHealthCheckFirewallName(clusterID, hcName string, isNodesHealthCheck bool) string {\n\tif isNodesHealthCheck {\n\t\treturn MakeNodesHealthCheckName(clusterID) + \"-http-hc\"\n\t}\n\treturn \"k8s-\" + hcName + \"-http-hc\"\n}","line":{"from":111,"to":118}} {"id":100034355,"name":"MakeFirewallName","signature":"func MakeFirewallName(name string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_naming.go","code":"// MakeFirewallName returns the firewall name used by the GCE load\n// balancers (l4) for serving traffic.\nfunc MakeFirewallName(name string) string {\n\treturn fmt.Sprintf(\"k8s-fw-%s\", name)\n}","line":{"from":120,"to":124}} {"id":100034356,"name":"makeFirewallDescription","signature":"func makeFirewallDescription(serviceName, ipAddress string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_loadbalancer_naming.go","code":"func makeFirewallDescription(serviceName, ipAddress string) string {\n\treturn fmt.Sprintf(`{\"kubernetes.io/service-name\":\"%s\", \"kubernetes.io/service-ip\":\"%s\"}`,\n\t\tserviceName, ipAddress)\n}","line":{"from":126,"to":129}} {"id":100034357,"name":"newNetworkEndpointGroupMetricContext","signature":"func newNetworkEndpointGroupMetricContext(request string, zone string) *metricContext","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_networkendpointgroup.go","code":"func newNetworkEndpointGroupMetricContext(request string, zone string) *metricContext {\n\treturn newGenericMetricContext(\"networkendpointgroup_\", request, unusedMetricLabel, zone, computeBetaVersion)\n}","line":{"from":33,"to":35}} {"id":100034358,"name":"GetNetworkEndpointGroup","signature":"func (g *Cloud) GetNetworkEndpointGroup(name string, zone string) (*computebeta.NetworkEndpointGroup, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_networkendpointgroup.go","code":"// GetNetworkEndpointGroup returns the collection of network endpoints for the name in zone\nfunc (g *Cloud) GetNetworkEndpointGroup(name string, zone string) (*computebeta.NetworkEndpointGroup, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newNetworkEndpointGroupMetricContext(\"get\", zone)\n\tv, err := g.c.BetaNetworkEndpointGroups().Get(ctx, meta.ZonalKey(name, zone))\n\treturn v, mc.Observe(err)\n}","line":{"from":37,"to":45}} {"id":100034359,"name":"ListNetworkEndpointGroup","signature":"func (g *Cloud) ListNetworkEndpointGroup(zone string) ([]*computebeta.NetworkEndpointGroup, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_networkendpointgroup.go","code":"// ListNetworkEndpointGroup returns the collection of network endpoints for the zone\nfunc (g *Cloud) ListNetworkEndpointGroup(zone string) ([]*computebeta.NetworkEndpointGroup, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newNetworkEndpointGroupMetricContext(\"list\", zone)\n\tnegs, err := g.c.BetaNetworkEndpointGroups().List(ctx, zone, filter.None)\n\treturn negs, mc.Observe(err)\n}","line":{"from":47,"to":55}} {"id":100034360,"name":"AggregatedListNetworkEndpointGroup","signature":"func (g *Cloud) AggregatedListNetworkEndpointGroup() (map[string][]*computebeta.NetworkEndpointGroup, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_networkendpointgroup.go","code":"// AggregatedListNetworkEndpointGroup returns a map of zone -\u003e endpoint group.\nfunc (g *Cloud) AggregatedListNetworkEndpointGroup() (map[string][]*computebeta.NetworkEndpointGroup, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newNetworkEndpointGroupMetricContext(\"aggregated_list\", \"\")\n\t// TODO: filter for the region the cluster is in.\n\tall, err := g.c.BetaNetworkEndpointGroups().AggregatedList(ctx, filter.None)\n\tif err != nil {\n\t\treturn nil, mc.Observe(err)\n\t}\n\tret := map[string][]*computebeta.NetworkEndpointGroup{}\n\tfor key, byZone := range all {\n\t\t// key is \"zones/\u003czone name\u003e\"\n\t\tparts := strings.Split(key, \"/\")\n\t\tif len(parts) != 2 {\n\t\t\treturn nil, mc.Observe(fmt.Errorf(\"invalid key for AggregatedListNetworkEndpointGroup: %q\", key))\n\t\t}\n\t\tzone := parts[1]\n\t\tret[zone] = append(ret[zone], byZone...)\n\t}\n\treturn ret, mc.Observe(nil)\n}","line":{"from":57,"to":79}} {"id":100034361,"name":"CreateNetworkEndpointGroup","signature":"func (g *Cloud) CreateNetworkEndpointGroup(neg *computebeta.NetworkEndpointGroup, zone string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_networkendpointgroup.go","code":"// CreateNetworkEndpointGroup creates an endpoint group in the zone\nfunc (g *Cloud) CreateNetworkEndpointGroup(neg *computebeta.NetworkEndpointGroup, zone string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newNetworkEndpointGroupMetricContext(\"create\", zone)\n\treturn mc.Observe(g.c.BetaNetworkEndpointGroups().Insert(ctx, meta.ZonalKey(neg.Name, zone), neg))\n}","line":{"from":81,"to":88}} {"id":100034362,"name":"DeleteNetworkEndpointGroup","signature":"func (g *Cloud) DeleteNetworkEndpointGroup(name string, zone string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_networkendpointgroup.go","code":"// DeleteNetworkEndpointGroup deletes the name endpoint group from the zone\nfunc (g *Cloud) DeleteNetworkEndpointGroup(name string, zone string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newNetworkEndpointGroupMetricContext(\"delete\", zone)\n\treturn mc.Observe(g.c.BetaNetworkEndpointGroups().Delete(ctx, meta.ZonalKey(name, zone)))\n}","line":{"from":90,"to":97}} {"id":100034363,"name":"AttachNetworkEndpoints","signature":"func (g *Cloud) AttachNetworkEndpoints(name, zone string, endpoints []*computebeta.NetworkEndpoint) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_networkendpointgroup.go","code":"// AttachNetworkEndpoints associates the referenced endpoints with the named endpoint group in the zone\nfunc (g *Cloud) AttachNetworkEndpoints(name, zone string, endpoints []*computebeta.NetworkEndpoint) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newNetworkEndpointGroupMetricContext(\"attach\", zone)\n\treq := \u0026computebeta.NetworkEndpointGroupsAttachEndpointsRequest{\n\t\tNetworkEndpoints: endpoints,\n\t}\n\treturn mc.Observe(g.c.BetaNetworkEndpointGroups().AttachNetworkEndpoints(ctx, meta.ZonalKey(name, zone), req))\n}","line":{"from":99,"to":109}} {"id":100034364,"name":"DetachNetworkEndpoints","signature":"func (g *Cloud) DetachNetworkEndpoints(name, zone string, endpoints []*computebeta.NetworkEndpoint) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_networkendpointgroup.go","code":"// DetachNetworkEndpoints breaks the association between the referenced endpoints and the named endpoint group in the zone\nfunc (g *Cloud) DetachNetworkEndpoints(name, zone string, endpoints []*computebeta.NetworkEndpoint) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newNetworkEndpointGroupMetricContext(\"detach\", zone)\n\treq := \u0026computebeta.NetworkEndpointGroupsDetachEndpointsRequest{\n\t\tNetworkEndpoints: endpoints,\n\t}\n\treturn mc.Observe(g.c.BetaNetworkEndpointGroups().DetachNetworkEndpoints(ctx, meta.ZonalKey(name, zone), req))\n}","line":{"from":111,"to":121}} {"id":100034365,"name":"ListNetworkEndpoints","signature":"func (g *Cloud) ListNetworkEndpoints(name, zone string, showHealthStatus bool) ([]*computebeta.NetworkEndpointWithHealthStatus, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_networkendpointgroup.go","code":"// ListNetworkEndpoints returns all the endpoints associated with the endpoint group in zone and optionally their status.\nfunc (g *Cloud) ListNetworkEndpoints(name, zone string, showHealthStatus bool) ([]*computebeta.NetworkEndpointWithHealthStatus, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newNetworkEndpointGroupMetricContext(\"list_networkendpoints\", zone)\n\thealthStatus := \"SKIP\"\n\tif showHealthStatus {\n\t\thealthStatus = \"SHOW\"\n\t}\n\treq := \u0026computebeta.NetworkEndpointGroupsListEndpointsRequest{\n\t\tHealthStatus: healthStatus,\n\t}\n\tl, err := g.c.BetaNetworkEndpointGroups().ListNetworkEndpoints(ctx, meta.ZonalKey(name, zone), req, filter.None)\n\treturn l, mc.Observe(err)\n}","line":{"from":123,"to":138}} {"id":100034366,"name":"newRoutesMetricContext","signature":"func newRoutesMetricContext(request string) *metricContext","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_routes.go","code":"func newRoutesMetricContext(request string) *metricContext {\n\treturn newGenericMetricContext(\"routes\", request, unusedMetricLabel, unusedMetricLabel, computeV1Version)\n}","line":{"from":38,"to":40}} {"id":100034367,"name":"ListRoutes","signature":"func (g *Cloud) ListRoutes(ctx context.Context, clusterName string) ([]*cloudprovider.Route, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_routes.go","code":"// ListRoutes in the cloud environment.\nfunc (g *Cloud) ListRoutes(ctx context.Context, clusterName string) ([]*cloudprovider.Route, error) {\n\ttimeoutCtx, cancel := context.WithTimeout(ctx, 1*time.Hour)\n\tdefer cancel()\n\n\tmc := newRoutesMetricContext(\"list\")\n\tprefix := truncateClusterName(clusterName)\n\tf := filter.Regexp(\"name\", prefix+\"-.*\").AndRegexp(\"network\", g.NetworkURL()).AndRegexp(\"description\", k8sNodeRouteTag)\n\troutes, err := g.c.Routes().List(timeoutCtx, f)\n\tif err != nil {\n\t\treturn nil, mc.Observe(err)\n\t}\n\tvar croutes []*cloudprovider.Route\n\tfor _, r := range routes {\n\t\ttarget := path.Base(r.NextHopInstance)\n\t\t// TODO: Should we lastComponent(target) this?\n\t\ttargetNodeName := types.NodeName(target) // NodeName == Instance Name on GCE\n\t\tcroutes = append(croutes, \u0026cloudprovider.Route{\n\t\t\tName: r.Name,\n\t\t\tTargetNode: targetNodeName,\n\t\t\tDestinationCIDR: r.DestRange,\n\t\t})\n\t}\n\treturn croutes, mc.Observe(nil)\n}","line":{"from":42,"to":66}} {"id":100034368,"name":"CreateRoute","signature":"func (g *Cloud) CreateRoute(ctx context.Context, clusterName string, nameHint string, route *cloudprovider.Route) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_routes.go","code":"// CreateRoute in the cloud environment.\nfunc (g *Cloud) CreateRoute(ctx context.Context, clusterName string, nameHint string, route *cloudprovider.Route) error {\n\ttimeoutCtx, cancel := context.WithTimeout(ctx, 1*time.Hour)\n\tdefer cancel()\n\n\tmc := newRoutesMetricContext(\"create\")\n\n\ttargetInstance, err := g.getInstanceByName(mapNodeNameToInstanceName(route.TargetNode))\n\tif err != nil {\n\t\treturn mc.Observe(err)\n\t}\n\tcr := \u0026compute.Route{\n\t\t// TODO(thockin): generate a unique name for node + route cidr. Don't depend on name hints.\n\t\tName: truncateClusterName(clusterName) + \"-\" + nameHint,\n\t\tDestRange: route.DestinationCIDR,\n\t\tNextHopInstance: fmt.Sprintf(\"zones/%s/instances/%s\", targetInstance.Zone, targetInstance.Name),\n\t\tNetwork: g.NetworkURL(),\n\t\tPriority: 1000,\n\t\tDescription: k8sNodeRouteTag,\n\t}\n\terr = g.c.Routes().Insert(timeoutCtx, meta.GlobalKey(cr.Name), cr)\n\tif isHTTPErrorCode(err, http.StatusConflict) {\n\t\tklog.Infof(\"Route %q already exists.\", cr.Name)\n\t\terr = nil\n\t}\n\treturn mc.Observe(err)\n}","line":{"from":68,"to":94}} {"id":100034369,"name":"DeleteRoute","signature":"func (g *Cloud) DeleteRoute(ctx context.Context, clusterName string, route *cloudprovider.Route) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_routes.go","code":"// DeleteRoute from the cloud environment.\nfunc (g *Cloud) DeleteRoute(ctx context.Context, clusterName string, route *cloudprovider.Route) error {\n\ttimeoutCtx, cancel := context.WithTimeout(ctx, 1*time.Hour)\n\tdefer cancel()\n\n\tmc := newRoutesMetricContext(\"delete\")\n\treturn mc.Observe(g.c.Routes().Delete(timeoutCtx, meta.GlobalKey(route.Name)))\n}","line":{"from":96,"to":103}} {"id":100034370,"name":"truncateClusterName","signature":"func truncateClusterName(clusterName string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_routes.go","code":"func truncateClusterName(clusterName string) string {\n\tif len(clusterName) \u003e 26 {\n\t\treturn clusterName[:26]\n\t}\n\treturn clusterName\n}","line":{"from":105,"to":110}} {"id":100034371,"name":"newSecurityPolicyMetricContextWithVersion","signature":"func newSecurityPolicyMetricContextWithVersion(request, version string) *metricContext","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_securitypolicy.go","code":"func newSecurityPolicyMetricContextWithVersion(request, version string) *metricContext {\n\treturn newGenericMetricContext(\"securitypolicy\", request, \"\", unusedMetricLabel, version)\n}","line":{"from":30,"to":32}} {"id":100034372,"name":"GetBetaSecurityPolicy","signature":"func (g *Cloud) GetBetaSecurityPolicy(name string) (*computebeta.SecurityPolicy, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_securitypolicy.go","code":"// GetBetaSecurityPolicy retrieves a security policy.\nfunc (g *Cloud) GetBetaSecurityPolicy(name string) (*computebeta.SecurityPolicy, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newSecurityPolicyMetricContextWithVersion(\"get\", computeBetaVersion)\n\tv, err := g.c.BetaSecurityPolicies().Get(ctx, meta.GlobalKey(name))\n\treturn v, mc.Observe(err)\n}","line":{"from":34,"to":42}} {"id":100034373,"name":"ListBetaSecurityPolicy","signature":"func (g *Cloud) ListBetaSecurityPolicy() ([]*computebeta.SecurityPolicy, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_securitypolicy.go","code":"// ListBetaSecurityPolicy lists all security policies in the project.\nfunc (g *Cloud) ListBetaSecurityPolicy() ([]*computebeta.SecurityPolicy, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newSecurityPolicyMetricContextWithVersion(\"list\", computeBetaVersion)\n\tv, err := g.c.BetaSecurityPolicies().List(ctx, filter.None)\n\treturn v, mc.Observe(err)\n}","line":{"from":44,"to":52}} {"id":100034374,"name":"CreateBetaSecurityPolicy","signature":"func (g *Cloud) CreateBetaSecurityPolicy(sp *computebeta.SecurityPolicy) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_securitypolicy.go","code":"// CreateBetaSecurityPolicy creates the given security policy.\nfunc (g *Cloud) CreateBetaSecurityPolicy(sp *computebeta.SecurityPolicy) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newSecurityPolicyMetricContextWithVersion(\"create\", computeBetaVersion)\n\treturn mc.Observe(g.c.BetaSecurityPolicies().Insert(ctx, meta.GlobalKey(sp.Name), sp))\n}","line":{"from":54,"to":61}} {"id":100034375,"name":"DeleteBetaSecurityPolicy","signature":"func (g *Cloud) DeleteBetaSecurityPolicy(name string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_securitypolicy.go","code":"// DeleteBetaSecurityPolicy deletes the given security policy.\nfunc (g *Cloud) DeleteBetaSecurityPolicy(name string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newSecurityPolicyMetricContextWithVersion(\"delete\", computeBetaVersion)\n\treturn mc.Observe(g.c.BetaSecurityPolicies().Delete(ctx, meta.GlobalKey(name)))\n}","line":{"from":63,"to":70}} {"id":100034376,"name":"PatchBetaSecurityPolicy","signature":"func (g *Cloud) PatchBetaSecurityPolicy(sp *computebeta.SecurityPolicy) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_securitypolicy.go","code":"// PatchBetaSecurityPolicy applies the given security policy as a\n// patch to an existing security policy.\nfunc (g *Cloud) PatchBetaSecurityPolicy(sp *computebeta.SecurityPolicy) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newSecurityPolicyMetricContextWithVersion(\"patch\", computeBetaVersion)\n\treturn mc.Observe(g.c.BetaSecurityPolicies().Patch(ctx, meta.GlobalKey(sp.Name), sp))\n}","line":{"from":72,"to":80}} {"id":100034377,"name":"GetRuleForBetaSecurityPolicy","signature":"func (g *Cloud) GetRuleForBetaSecurityPolicy(name string) (*computebeta.SecurityPolicyRule, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_securitypolicy.go","code":"// GetRuleForBetaSecurityPolicy gets rule from a security policy.\nfunc (g *Cloud) GetRuleForBetaSecurityPolicy(name string) (*computebeta.SecurityPolicyRule, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newSecurityPolicyMetricContextWithVersion(\"get_rule\", computeBetaVersion)\n\tv, err := g.c.BetaSecurityPolicies().GetRule(ctx, meta.GlobalKey(name))\n\treturn v, mc.Observe(err)\n}","line":{"from":82,"to":90}} {"id":100034378,"name":"AddRuletoBetaSecurityPolicy","signature":"func (g *Cloud) AddRuletoBetaSecurityPolicy(name string, spr *computebeta.SecurityPolicyRule) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_securitypolicy.go","code":"// AddRuletoBetaSecurityPolicy adds the given security policy rule to\n// a security policy.\nfunc (g *Cloud) AddRuletoBetaSecurityPolicy(name string, spr *computebeta.SecurityPolicyRule) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newSecurityPolicyMetricContextWithVersion(\"add_rule\", computeBetaVersion)\n\treturn mc.Observe(g.c.BetaSecurityPolicies().AddRule(ctx, meta.GlobalKey(name), spr))\n}","line":{"from":92,"to":100}} {"id":100034379,"name":"PatchRuleForBetaSecurityPolicy","signature":"func (g *Cloud) PatchRuleForBetaSecurityPolicy(name string, spr *computebeta.SecurityPolicyRule) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_securitypolicy.go","code":"// PatchRuleForBetaSecurityPolicy patches the given security policy\n// rule to a security policy.\nfunc (g *Cloud) PatchRuleForBetaSecurityPolicy(name string, spr *computebeta.SecurityPolicyRule) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newSecurityPolicyMetricContextWithVersion(\"patch_rule\", computeBetaVersion)\n\treturn mc.Observe(g.c.BetaSecurityPolicies().PatchRule(ctx, meta.GlobalKey(name), spr))\n}","line":{"from":102,"to":110}} {"id":100034380,"name":"RemoveRuleFromBetaSecurityPolicy","signature":"func (g *Cloud) RemoveRuleFromBetaSecurityPolicy(name string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_securitypolicy.go","code":"// RemoveRuleFromBetaSecurityPolicy removes rule from a security policy.\nfunc (g *Cloud) RemoveRuleFromBetaSecurityPolicy(name string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newSecurityPolicyMetricContextWithVersion(\"remove_rule\", computeBetaVersion)\n\treturn mc.Observe(g.c.BetaSecurityPolicies().RemoveRule(ctx, meta.GlobalKey(name)))\n}","line":{"from":112,"to":119}} {"id":100034381,"name":"newTargetPoolMetricContext","signature":"func newTargetPoolMetricContext(request, region string) *metricContext","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_targetpool.go","code":"func newTargetPoolMetricContext(request, region string) *metricContext {\n\treturn newGenericMetricContext(\"targetpool\", request, region, unusedMetricLabel, computeV1Version)\n}","line":{"from":29,"to":31}} {"id":100034382,"name":"GetTargetPool","signature":"func (g *Cloud) GetTargetPool(name, region string) (*compute.TargetPool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_targetpool.go","code":"// GetTargetPool returns the TargetPool by name.\nfunc (g *Cloud) GetTargetPool(name, region string) (*compute.TargetPool, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newTargetPoolMetricContext(\"get\", region)\n\tv, err := g.c.TargetPools().Get(ctx, meta.RegionalKey(name, region))\n\treturn v, mc.Observe(err)\n}","line":{"from":33,"to":41}} {"id":100034383,"name":"CreateTargetPool","signature":"func (g *Cloud) CreateTargetPool(tp *compute.TargetPool, region string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_targetpool.go","code":"// CreateTargetPool creates the passed TargetPool\nfunc (g *Cloud) CreateTargetPool(tp *compute.TargetPool, region string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newTargetPoolMetricContext(\"create\", region)\n\treturn mc.Observe(g.c.TargetPools().Insert(ctx, meta.RegionalKey(tp.Name, region), tp))\n}","line":{"from":43,"to":50}} {"id":100034384,"name":"DeleteTargetPool","signature":"func (g *Cloud) DeleteTargetPool(name, region string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_targetpool.go","code":"// DeleteTargetPool deletes TargetPool by name.\nfunc (g *Cloud) DeleteTargetPool(name, region string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newTargetPoolMetricContext(\"delete\", region)\n\treturn mc.Observe(g.c.TargetPools().Delete(ctx, meta.RegionalKey(name, region)))\n}","line":{"from":52,"to":59}} {"id":100034385,"name":"AddInstancesToTargetPool","signature":"func (g *Cloud) AddInstancesToTargetPool(name, region string, instanceRefs []*compute.InstanceReference) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_targetpool.go","code":"// AddInstancesToTargetPool adds instances by link to the TargetPool\nfunc (g *Cloud) AddInstancesToTargetPool(name, region string, instanceRefs []*compute.InstanceReference) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\treq := \u0026compute.TargetPoolsAddInstanceRequest{\n\t\tInstances: instanceRefs,\n\t}\n\tmc := newTargetPoolMetricContext(\"add_instances\", region)\n\treturn mc.Observe(g.c.TargetPools().AddInstance(ctx, meta.RegionalKey(name, region), req))\n}","line":{"from":61,"to":71}} {"id":100034386,"name":"RemoveInstancesFromTargetPool","signature":"func (g *Cloud) RemoveInstancesFromTargetPool(name, region string, instanceRefs []*compute.InstanceReference) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_targetpool.go","code":"// RemoveInstancesFromTargetPool removes instances by link to the TargetPool\nfunc (g *Cloud) RemoveInstancesFromTargetPool(name, region string, instanceRefs []*compute.InstanceReference) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\treq := \u0026compute.TargetPoolsRemoveInstanceRequest{\n\t\tInstances: instanceRefs,\n\t}\n\tmc := newTargetPoolMetricContext(\"remove_instances\", region)\n\treturn mc.Observe(g.c.TargetPools().RemoveInstance(ctx, meta.RegionalKey(name, region), req))\n}","line":{"from":73,"to":83}} {"id":100034387,"name":"newTargetProxyMetricContext","signature":"func newTargetProxyMetricContext(request string) *metricContext","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_targetproxy.go","code":"func newTargetProxyMetricContext(request string) *metricContext {\n\treturn newGenericMetricContext(\"targetproxy\", request, unusedMetricLabel, unusedMetricLabel, computeV1Version)\n}","line":{"from":30,"to":32}} {"id":100034388,"name":"GetTargetHTTPProxy","signature":"func (g *Cloud) GetTargetHTTPProxy(name string) (*compute.TargetHttpProxy, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_targetproxy.go","code":"// GetTargetHTTPProxy returns the UrlMap by name.\nfunc (g *Cloud) GetTargetHTTPProxy(name string) (*compute.TargetHttpProxy, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newTargetProxyMetricContext(\"get\")\n\tv, err := g.c.TargetHttpProxies().Get(ctx, meta.GlobalKey(name))\n\treturn v, mc.Observe(err)\n}","line":{"from":34,"to":42}} {"id":100034389,"name":"CreateTargetHTTPProxy","signature":"func (g *Cloud) CreateTargetHTTPProxy(proxy *compute.TargetHttpProxy) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_targetproxy.go","code":"// CreateTargetHTTPProxy creates a TargetHttpProxy\nfunc (g *Cloud) CreateTargetHTTPProxy(proxy *compute.TargetHttpProxy) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newTargetProxyMetricContext(\"create\")\n\treturn mc.Observe(g.c.TargetHttpProxies().Insert(ctx, meta.GlobalKey(proxy.Name), proxy))\n}","line":{"from":44,"to":51}} {"id":100034390,"name":"SetURLMapForTargetHTTPProxy","signature":"func (g *Cloud) SetURLMapForTargetHTTPProxy(proxy *compute.TargetHttpProxy, urlMapLink string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_targetproxy.go","code":"// SetURLMapForTargetHTTPProxy sets the given UrlMap for the given TargetHttpProxy.\nfunc (g *Cloud) SetURLMapForTargetHTTPProxy(proxy *compute.TargetHttpProxy, urlMapLink string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tref := \u0026compute.UrlMapReference{UrlMap: urlMapLink}\n\tmc := newTargetProxyMetricContext(\"set_url_map\")\n\treturn mc.Observe(g.c.TargetHttpProxies().SetUrlMap(ctx, meta.GlobalKey(proxy.Name), ref))\n}","line":{"from":53,"to":61}} {"id":100034391,"name":"DeleteTargetHTTPProxy","signature":"func (g *Cloud) DeleteTargetHTTPProxy(name string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_targetproxy.go","code":"// DeleteTargetHTTPProxy deletes the TargetHttpProxy by name.\nfunc (g *Cloud) DeleteTargetHTTPProxy(name string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newTargetProxyMetricContext(\"delete\")\n\treturn mc.Observe(g.c.TargetHttpProxies().Delete(ctx, meta.GlobalKey(name)))\n}","line":{"from":63,"to":70}} {"id":100034392,"name":"ListTargetHTTPProxies","signature":"func (g *Cloud) ListTargetHTTPProxies() ([]*compute.TargetHttpProxy, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_targetproxy.go","code":"// ListTargetHTTPProxies lists all TargetHttpProxies in the project.\nfunc (g *Cloud) ListTargetHTTPProxies() ([]*compute.TargetHttpProxy, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newTargetProxyMetricContext(\"list\")\n\tv, err := g.c.TargetHttpProxies().List(ctx, filter.None)\n\treturn v, mc.Observe(err)\n}","line":{"from":72,"to":80}} {"id":100034393,"name":"GetTargetHTTPSProxy","signature":"func (g *Cloud) GetTargetHTTPSProxy(name string) (*compute.TargetHttpsProxy, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_targetproxy.go","code":"// GetTargetHTTPSProxy returns the UrlMap by name.\nfunc (g *Cloud) GetTargetHTTPSProxy(name string) (*compute.TargetHttpsProxy, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newTargetProxyMetricContext(\"get\")\n\tv, err := g.c.TargetHttpsProxies().Get(ctx, meta.GlobalKey(name))\n\treturn v, mc.Observe(err)\n}","line":{"from":84,"to":92}} {"id":100034394,"name":"CreateTargetHTTPSProxy","signature":"func (g *Cloud) CreateTargetHTTPSProxy(proxy *compute.TargetHttpsProxy) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_targetproxy.go","code":"// CreateTargetHTTPSProxy creates a TargetHttpsProxy\nfunc (g *Cloud) CreateTargetHTTPSProxy(proxy *compute.TargetHttpsProxy) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newTargetProxyMetricContext(\"create\")\n\treturn mc.Observe(g.c.TargetHttpsProxies().Insert(ctx, meta.GlobalKey(proxy.Name), proxy))\n}","line":{"from":94,"to":101}} {"id":100034395,"name":"SetURLMapForTargetHTTPSProxy","signature":"func (g *Cloud) SetURLMapForTargetHTTPSProxy(proxy *compute.TargetHttpsProxy, urlMapLink string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_targetproxy.go","code":"// SetURLMapForTargetHTTPSProxy sets the given UrlMap for the given TargetHttpsProxy.\nfunc (g *Cloud) SetURLMapForTargetHTTPSProxy(proxy *compute.TargetHttpsProxy, urlMapLink string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newTargetProxyMetricContext(\"set_url_map\")\n\tref := \u0026compute.UrlMapReference{UrlMap: urlMapLink}\n\treturn mc.Observe(g.c.TargetHttpsProxies().SetUrlMap(ctx, meta.GlobalKey(proxy.Name), ref))\n}","line":{"from":103,"to":111}} {"id":100034396,"name":"SetSslCertificateForTargetHTTPSProxy","signature":"func (g *Cloud) SetSslCertificateForTargetHTTPSProxy(proxy *compute.TargetHttpsProxy, sslCertURLs []string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_targetproxy.go","code":"// SetSslCertificateForTargetHTTPSProxy sets the given SslCertificate for the given TargetHttpsProxy.\nfunc (g *Cloud) SetSslCertificateForTargetHTTPSProxy(proxy *compute.TargetHttpsProxy, sslCertURLs []string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newTargetProxyMetricContext(\"set_ssl_cert\")\n\treq := \u0026compute.TargetHttpsProxiesSetSslCertificatesRequest{\n\t\tSslCertificates: sslCertURLs,\n\t}\n\treturn mc.Observe(g.c.TargetHttpsProxies().SetSslCertificates(ctx, meta.GlobalKey(proxy.Name), req))\n}","line":{"from":113,"to":123}} {"id":100034397,"name":"DeleteTargetHTTPSProxy","signature":"func (g *Cloud) DeleteTargetHTTPSProxy(name string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_targetproxy.go","code":"// DeleteTargetHTTPSProxy deletes the TargetHttpsProxy by name.\nfunc (g *Cloud) DeleteTargetHTTPSProxy(name string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newTargetProxyMetricContext(\"delete\")\n\treturn mc.Observe(g.c.TargetHttpsProxies().Delete(ctx, meta.GlobalKey(name)))\n}","line":{"from":125,"to":132}} {"id":100034398,"name":"ListTargetHTTPSProxies","signature":"func (g *Cloud) ListTargetHTTPSProxies() ([]*compute.TargetHttpsProxy, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_targetproxy.go","code":"// ListTargetHTTPSProxies lists all TargetHttpsProxies in the project.\nfunc (g *Cloud) ListTargetHTTPSProxies() ([]*compute.TargetHttpsProxy, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newTargetProxyMetricContext(\"list\")\n\tv, err := g.c.TargetHttpsProxies().List(ctx, filter.None)\n\treturn v, mc.Observe(err)\n}","line":{"from":134,"to":142}} {"id":100034399,"name":"newTPUService","signature":"func newTPUService(client *http.Client) (*tpuService, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_tpu.go","code":"// newTPUService returns a new tpuService using the client to communicate with\n// the Cloud TPU APIs.\nfunc newTPUService(client *http.Client) (*tpuService, error) {\n\ts, err := tpuapi.NewService(context.Background())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026tpuService{\n\t\tprojects: tpuapi.NewProjectsService(s),\n\t}, nil\n}","line":{"from":36,"to":46}} {"id":100034400,"name":"CreateTPU","signature":"func (g *Cloud) CreateTPU(ctx context.Context, name, zone string, node *tpuapi.Node) (*tpuapi.Node, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_tpu.go","code":"// CreateTPU creates the Cloud TPU node with the specified name in the\n// specified zone.\nfunc (g *Cloud) CreateTPU(ctx context.Context, name, zone string, node *tpuapi.Node) (*tpuapi.Node, error) {\n\tvar err error\n\tmc := newTPUMetricContext(\"create\", zone)\n\tdefer mc.Observe(err)\n\n\tvar op *tpuapi.Operation\n\tparent := getTPUParentName(g.projectID, zone)\n\top, err = g.tpuService.projects.Locations.Nodes.Create(parent, node).NodeId(name).Do()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tklog.V(2).Infof(\"Creating Cloud TPU %q in zone %q with operation %q\", name, zone, op.Name)\n\n\top, err = g.waitForTPUOp(ctx, op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = getErrorFromTPUOp(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\toutput := new(tpuapi.Node)\n\terr = json.Unmarshal(op.Response, output)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"failed to unmarshal response from operation %q: response = %v, err = %v\", op.Name, op.Response, err)\n\t\treturn nil, err\n\t}\n\treturn output, nil\n}","line":{"from":54,"to":85}} {"id":100034401,"name":"DeleteTPU","signature":"func (g *Cloud) DeleteTPU(ctx context.Context, name, zone string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_tpu.go","code":"// DeleteTPU deletes the Cloud TPU with the specified name in the specified\n// zone.\nfunc (g *Cloud) DeleteTPU(ctx context.Context, name, zone string) error {\n\tvar err error\n\tmc := newTPUMetricContext(\"delete\", zone)\n\tdefer mc.Observe(err)\n\n\tvar op *tpuapi.Operation\n\tname = getTPUName(g.projectID, zone, name)\n\top, err = g.tpuService.projects.Locations.Nodes.Delete(name).Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\tklog.V(2).Infof(\"Deleting Cloud TPU %q in zone %q with operation %q\", name, zone, op.Name)\n\n\top, err = g.waitForTPUOp(ctx, op)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = getErrorFromTPUOp(op)\n\treturn err\n}","line":{"from":87,"to":108}} {"id":100034402,"name":"GetTPU","signature":"func (g *Cloud) GetTPU(ctx context.Context, name, zone string) (*tpuapi.Node, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_tpu.go","code":"// GetTPU returns the Cloud TPU with the specified name in the specified zone.\nfunc (g *Cloud) GetTPU(ctx context.Context, name, zone string) (*tpuapi.Node, error) {\n\tmc := newTPUMetricContext(\"get\", zone)\n\n\tname = getTPUName(g.projectID, zone, name)\n\tnode, err := g.tpuService.projects.Locations.Nodes.Get(name).Do()\n\tif err != nil {\n\t\treturn nil, mc.Observe(err)\n\t}\n\treturn node, mc.Observe(nil)\n}","line":{"from":110,"to":120}} {"id":100034403,"name":"ListTPUs","signature":"func (g *Cloud) ListTPUs(ctx context.Context, zone string) ([]*tpuapi.Node, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_tpu.go","code":"// ListTPUs returns Cloud TPUs in the specified zone.\nfunc (g *Cloud) ListTPUs(ctx context.Context, zone string) ([]*tpuapi.Node, error) {\n\tmc := newTPUMetricContext(\"list\", zone)\n\n\tparent := getTPUParentName(g.projectID, zone)\n\tvar nodes []*tpuapi.Node\n\tvar accumulator = func(response *tpuapi.ListNodesResponse) error {\n\t\tnodes = append(nodes, response.Nodes...)\n\t\treturn nil\n\t}\n\terr := g.tpuService.projects.Locations.Nodes.List(parent).Pages(ctx, accumulator)\n\tif err != nil {\n\t\treturn nil, mc.Observe(err)\n\t}\n\treturn nodes, mc.Observe(nil)\n}","line":{"from":122,"to":137}} {"id":100034404,"name":"ListLocations","signature":"func (g *Cloud) ListLocations(ctx context.Context) ([]*tpuapi.Location, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_tpu.go","code":"// ListLocations returns the zones where Cloud TPUs are available.\nfunc (g *Cloud) ListLocations(ctx context.Context) ([]*tpuapi.Location, error) {\n\tmc := newTPUMetricContext(\"list_locations\", \"\")\n\tparent := getTPUProjectURL(g.projectID)\n\tvar locations []*tpuapi.Location\n\tvar accumulator = func(response *tpuapi.ListLocationsResponse) error {\n\t\tlocations = append(locations, response.Locations...)\n\t\treturn nil\n\t}\n\terr := g.tpuService.projects.Locations.List(parent).Pages(ctx, accumulator)\n\tif err != nil {\n\t\treturn nil, mc.Observe(err)\n\t}\n\treturn locations, mc.Observe(nil)\n}","line":{"from":139,"to":153}} {"id":100034405,"name":"waitForTPUOp","signature":"func (g *Cloud) waitForTPUOp(ctx context.Context, op *tpuapi.Operation) (*tpuapi.Operation, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_tpu.go","code":"// waitForTPUOp checks whether the op is done every 30 seconds before the ctx\n// is cancelled.\nfunc (g *Cloud) waitForTPUOp(ctx context.Context, op *tpuapi.Operation) (*tpuapi.Operation, error) {\n\tif err := wait.PollInfinite(30*time.Second, func() (bool, error) {\n\t\t// Check if context has been cancelled.\n\t\tselect {\n\t\tcase \u003c-ctx.Done():\n\t\t\tklog.V(3).Infof(\"Context for operation %q has been cancelled: %s\", op.Name, ctx.Err())\n\t\t\treturn true, ctx.Err()\n\t\tdefault:\n\t\t}\n\n\t\tklog.V(3).Infof(\"Waiting for operation %q to complete...\", op.Name)\n\n\t\tstart := time.Now()\n\t\tg.operationPollRateLimiter.Accept()\n\t\tduration := time.Since(start)\n\t\tif duration \u003e 5*time.Second {\n\t\t\tklog.V(2).Infof(\"Getting operation %q throttled for %v\", op.Name, duration)\n\t\t}\n\n\t\tvar err error\n\t\top, err = g.tpuService.projects.Locations.Operations.Get(op.Name).Do()\n\t\tif err != nil {\n\t\t\treturn true, err\n\t\t}\n\t\tif op.Done {\n\t\t\tklog.V(3).Infof(\"Operation %q has completed\", op.Name)\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t}); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to wait for operation %q: %s\", op.Name, err)\n\t}\n\treturn op, nil\n}","line":{"from":155,"to":190}} {"id":100034406,"name":"newTPUMetricContext","signature":"func newTPUMetricContext(request, zone string) *metricContext","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_tpu.go","code":"// newTPUMetricContext returns a new metricContext used for recording metrics\n// of Cloud TPU API calls.\nfunc newTPUMetricContext(request, zone string) *metricContext {\n\treturn newGenericMetricContext(\"tpus\", request, unusedMetricLabel, zone, \"v1\")\n}","line":{"from":192,"to":196}} {"id":100034407,"name":"getErrorFromTPUOp","signature":"func getErrorFromTPUOp(op *tpuapi.Operation) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_tpu.go","code":"// getErrorFromTPUOp returns the error in the failed op, or nil if the op\n// succeed.\nfunc getErrorFromTPUOp(op *tpuapi.Operation) error {\n\tif op != nil \u0026\u0026 op.Error != nil {\n\t\treturn \u0026googleapi.Error{\n\t\t\tCode: op.ServerResponse.HTTPStatusCode,\n\t\t\tMessage: op.Error.Message,\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":198,"to":208}} {"id":100034408,"name":"getTPUProjectURL","signature":"func getTPUProjectURL(project string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_tpu.go","code":"func getTPUProjectURL(project string) string {\n\treturn fmt.Sprintf(\"projects/%s\", project)\n}","line":{"from":210,"to":212}} {"id":100034409,"name":"getTPUParentName","signature":"func getTPUParentName(project, zone string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_tpu.go","code":"func getTPUParentName(project, zone string) string {\n\treturn fmt.Sprintf(\"projects/%s/locations/%s\", project, zone)\n}","line":{"from":214,"to":216}} {"id":100034410,"name":"getTPUName","signature":"func getTPUName(project, zone, name string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_tpu.go","code":"func getTPUName(project, zone, name string) string {\n\treturn fmt.Sprintf(\"projects/%s/locations/%s/nodes/%s\", project, zone, name)\n}","line":{"from":218,"to":220}} {"id":100034411,"name":"newURLMapMetricContext","signature":"func newURLMapMetricContext(request string) *metricContext","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_urlmap.go","code":"func newURLMapMetricContext(request string) *metricContext {\n\treturn newGenericMetricContext(\"urlmap\", request, unusedMetricLabel, unusedMetricLabel, computeV1Version)\n}","line":{"from":30,"to":32}} {"id":100034412,"name":"GetURLMap","signature":"func (g *Cloud) GetURLMap(name string) (*compute.UrlMap, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_urlmap.go","code":"// GetURLMap returns the UrlMap by name.\nfunc (g *Cloud) GetURLMap(name string) (*compute.UrlMap, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newURLMapMetricContext(\"get\")\n\tv, err := g.c.UrlMaps().Get(ctx, meta.GlobalKey(name))\n\treturn v, mc.Observe(err)\n}","line":{"from":34,"to":42}} {"id":100034413,"name":"CreateURLMap","signature":"func (g *Cloud) CreateURLMap(urlMap *compute.UrlMap) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_urlmap.go","code":"// CreateURLMap creates a url map\nfunc (g *Cloud) CreateURLMap(urlMap *compute.UrlMap) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newURLMapMetricContext(\"create\")\n\treturn mc.Observe(g.c.UrlMaps().Insert(ctx, meta.GlobalKey(urlMap.Name), urlMap))\n}","line":{"from":44,"to":51}} {"id":100034414,"name":"UpdateURLMap","signature":"func (g *Cloud) UpdateURLMap(urlMap *compute.UrlMap) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_urlmap.go","code":"// UpdateURLMap applies the given UrlMap as an update\nfunc (g *Cloud) UpdateURLMap(urlMap *compute.UrlMap) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newURLMapMetricContext(\"update\")\n\treturn mc.Observe(g.c.UrlMaps().Update(ctx, meta.GlobalKey(urlMap.Name), urlMap))\n}","line":{"from":53,"to":60}} {"id":100034415,"name":"DeleteURLMap","signature":"func (g *Cloud) DeleteURLMap(name string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_urlmap.go","code":"// DeleteURLMap deletes a url map by name.\nfunc (g *Cloud) DeleteURLMap(name string) error {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newURLMapMetricContext(\"delete\")\n\treturn mc.Observe(g.c.UrlMaps().Delete(ctx, meta.GlobalKey(name)))\n}","line":{"from":62,"to":69}} {"id":100034416,"name":"ListURLMaps","signature":"func (g *Cloud) ListURLMaps() ([]*compute.UrlMap, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_urlmap.go","code":"// ListURLMaps lists all UrlMaps in the project.\nfunc (g *Cloud) ListURLMaps() ([]*compute.UrlMap, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newURLMapMetricContext(\"list\")\n\tv, err := g.c.UrlMaps().List(ctx, filter.None)\n\treturn v, mc.Observe(err)\n}","line":{"from":71,"to":79}} {"id":100034417,"name":"fakeGCECloud","signature":"func fakeGCECloud(vals TestClusterValues) (*Cloud, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"func fakeGCECloud(vals TestClusterValues) (*Cloud, error) {\n\tgce := NewFakeGCECloud(vals)\n\n\tgce.AlphaFeatureGate = NewAlphaFeatureGate([]string{})\n\tgce.nodeInformerSynced = func() bool { return true }\n\tgce.client = fake.NewSimpleClientset()\n\tgce.eventRecorder = \u0026record.FakeRecorder{}\n\n\tmockGCE := gce.c.(*cloud.MockGCE)\n\tmockGCE.MockTargetPools.AddInstanceHook = mock.AddInstanceHook\n\tmockGCE.MockTargetPools.RemoveInstanceHook = mock.RemoveInstanceHook\n\tmockGCE.MockForwardingRules.InsertHook = mock.InsertFwdRuleHook\n\tmockGCE.MockAddresses.InsertHook = mock.InsertAddressHook\n\tmockGCE.MockAlphaAddresses.InsertHook = mock.InsertAlphaAddressHook\n\tmockGCE.MockAlphaAddresses.X = mock.AddressAttributes{}\n\tmockGCE.MockAddresses.X = mock.AddressAttributes{}\n\n\tmockGCE.MockInstanceGroups.X = mock.InstanceGroupAttributes{\n\t\tInstanceMap: make(map[meta.Key]map[string]*compute.InstanceWithNamedPorts),\n\t\tLock: \u0026sync.Mutex{},\n\t}\n\tmockGCE.MockInstanceGroups.AddInstancesHook = mock.AddInstancesHook\n\tmockGCE.MockInstanceGroups.RemoveInstancesHook = mock.RemoveInstancesHook\n\tmockGCE.MockInstanceGroups.ListInstancesHook = mock.ListInstancesHook\n\n\tmockGCE.MockRegionBackendServices.UpdateHook = mock.UpdateRegionBackendServiceHook\n\tmockGCE.MockHealthChecks.UpdateHook = mock.UpdateHealthCheckHook\n\tmockGCE.MockFirewalls.UpdateHook = mock.UpdateFirewallHook\n\tmockGCE.MockFirewalls.PatchHook = mock.UpdateFirewallHook\n\n\tkeyGA := meta.GlobalKey(\"key-ga\")\n\tmockGCE.MockZones.Objects[*keyGA] = \u0026cloud.MockZonesObj{\n\t\tObj: \u0026compute.Zone{Name: vals.ZoneName, Region: gce.getRegionLink(vals.Region)},\n\t}\n\n\treturn gce, nil\n}","line":{"from":55,"to":91}} {"id":100034418,"name":"registerTargetPoolAddInstanceHook","signature":"func registerTargetPoolAddInstanceHook(gce *Cloud, callback func(*compute.TargetPoolsAddInstanceRequest)) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"func registerTargetPoolAddInstanceHook(gce *Cloud, callback func(*compute.TargetPoolsAddInstanceRequest)) error {\n\tmockGCE, ok := gce.c.(*cloud.MockGCE)\n\tif !ok {\n\t\treturn fmt.Errorf(\"couldn't cast cloud to mockGCE: %#v\", gce)\n\t}\n\texistingHandler := mockGCE.MockTargetPools.AddInstanceHook\n\thook := func(ctx context.Context, key *meta.Key, req *compute.TargetPoolsAddInstanceRequest, m *cloud.MockTargetPools) error {\n\t\tcallback(req)\n\t\treturn existingHandler(ctx, key, req, m)\n\t}\n\tmockGCE.MockTargetPools.AddInstanceHook = hook\n\treturn nil\n}","line":{"from":93,"to":105}} {"id":100034419,"name":"registerTargetPoolRemoveInstanceHook","signature":"func registerTargetPoolRemoveInstanceHook(gce *Cloud, callback func(*compute.TargetPoolsRemoveInstanceRequest)) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"func registerTargetPoolRemoveInstanceHook(gce *Cloud, callback func(*compute.TargetPoolsRemoveInstanceRequest)) error {\n\tmockGCE, ok := gce.c.(*cloud.MockGCE)\n\tif !ok {\n\t\treturn fmt.Errorf(\"couldn't cast cloud to mockGCE: %#v\", gce)\n\t}\n\texistingHandler := mockGCE.MockTargetPools.RemoveInstanceHook\n\thook := func(ctx context.Context, key *meta.Key, req *compute.TargetPoolsRemoveInstanceRequest, m *cloud.MockTargetPools) error {\n\t\tcallback(req)\n\t\treturn existingHandler(ctx, key, req, m)\n\t}\n\tmockGCE.MockTargetPools.RemoveInstanceHook = hook\n\treturn nil\n}","line":{"from":107,"to":119}} {"id":100034420,"name":"getProjectAndZone","signature":"func getProjectAndZone() (string, string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"func getProjectAndZone() (string, string, error) {\n\tresult, err := metadata.Get(\"instance/zone\")\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tparts := strings.Split(result, \"/\")\n\tif len(parts) != 4 {\n\t\treturn \"\", \"\", fmt.Errorf(\"unexpected response: %s\", result)\n\t}\n\tzone := parts[3]\n\tprojectID, err := metadata.ProjectID()\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\treturn projectID, zone, nil\n}","line":{"from":138,"to":153}} {"id":100034421,"name":"raiseFirewallChangeNeededEvent","signature":"func (g *Cloud) raiseFirewallChangeNeededEvent(svc *v1.Service, cmd string)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"func (g *Cloud) raiseFirewallChangeNeededEvent(svc *v1.Service, cmd string) {\n\tmsg := fmt.Sprintf(\"Firewall change required by security admin: `%v`\", cmd)\n\tif g.eventRecorder != nil \u0026\u0026 svc != nil {\n\t\tg.eventRecorder.Event(svc, v1.EventTypeNormal, \"LoadBalancerManualChange\", msg)\n\t}\n}","line":{"from":155,"to":160}} {"id":100034422,"name":"FirewallToGCloudCreateCmd","signature":"func FirewallToGCloudCreateCmd(fw *compute.Firewall, projectID string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"// FirewallToGCloudCreateCmd generates a gcloud command to create a firewall with specified params\nfunc FirewallToGCloudCreateCmd(fw *compute.Firewall, projectID string) string {\n\targs := firewallToGcloudArgs(fw, projectID)\n\treturn fmt.Sprintf(\"gcloud compute firewall-rules create %v --network %v %v\", fw.Name, getNameFromLink(fw.Network), args)\n}","line":{"from":162,"to":166}} {"id":100034423,"name":"FirewallToGCloudUpdateCmd","signature":"func FirewallToGCloudUpdateCmd(fw *compute.Firewall, projectID string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"// FirewallToGCloudUpdateCmd generates a gcloud command to update a firewall to specified params\nfunc FirewallToGCloudUpdateCmd(fw *compute.Firewall, projectID string) string {\n\targs := firewallToGcloudArgs(fw, projectID)\n\treturn fmt.Sprintf(\"gcloud compute firewall-rules update %v %v\", fw.Name, args)\n}","line":{"from":168,"to":172}} {"id":100034424,"name":"FirewallToGCloudDeleteCmd","signature":"func FirewallToGCloudDeleteCmd(fwName, projectID string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"// FirewallToGCloudDeleteCmd generates a gcloud command to delete a firewall to specified params\nfunc FirewallToGCloudDeleteCmd(fwName, projectID string) string {\n\treturn fmt.Sprintf(\"gcloud compute firewall-rules delete %v --project %v\", fwName, projectID)\n}","line":{"from":174,"to":177}} {"id":100034425,"name":"firewallToGcloudArgs","signature":"func firewallToGcloudArgs(fw *compute.Firewall, projectID string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"func firewallToGcloudArgs(fw *compute.Firewall, projectID string) string {\n\tvar allPorts []string\n\tfor _, a := range fw.Allowed {\n\t\tfor _, p := range a.Ports {\n\t\t\tallPorts = append(allPorts, fmt.Sprintf(\"%v:%v\", a.IPProtocol, p))\n\t\t}\n\t}\n\n\t// Sort all slices to prevent the event from being duped\n\tsort.Strings(allPorts)\n\tallow := strings.Join(allPorts, \",\")\n\tsort.Strings(fw.SourceRanges)\n\tsrcRngs := strings.Join(fw.SourceRanges, \",\")\n\tsort.Strings(fw.TargetTags)\n\ttargets := strings.Join(fw.TargetTags, \",\")\n\treturn fmt.Sprintf(\"--description %q --allow %v --source-ranges %v --target-tags %v --project %v\", fw.Description, allow, srcRngs, targets, projectID)\n}","line":{"from":179,"to":195}} {"id":100034426,"name":"canonicalizeInstanceName","signature":"func canonicalizeInstanceName(name string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"// Take a GCE instance 'hostname' and break it down to something that can be fed\n// to the GCE API client library. Basically this means reducing 'kubernetes-\n// node-2.c.my-proj.internal' to 'kubernetes-node-2' if necessary.\nfunc canonicalizeInstanceName(name string) string {\n\tix := strings.Index(name, \".\")\n\tif ix != -1 {\n\t\tname = name[:ix]\n\t}\n\treturn name\n}","line":{"from":197,"to":206}} {"id":100034427,"name":"lastComponent","signature":"func lastComponent(s string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"// Returns the last component of a URL, i.e. anything after the last slash\n// If there is no slash, returns the whole string\nfunc lastComponent(s string) string {\n\tlastSlash := strings.LastIndex(s, \"/\")\n\tif lastSlash != -1 {\n\t\ts = s[lastSlash+1:]\n\t}\n\treturn s\n}","line":{"from":208,"to":216}} {"id":100034428,"name":"mapNodeNameToInstanceName","signature":"func mapNodeNameToInstanceName(nodeName types.NodeName) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"// mapNodeNameToInstanceName maps a k8s NodeName to a GCE Instance Name\n// This is a simple string cast.\nfunc mapNodeNameToInstanceName(nodeName types.NodeName) string {\n\treturn string(nodeName)\n}","line":{"from":218,"to":222}} {"id":100034429,"name":"GetGCERegion","signature":"func GetGCERegion(zone string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"// GetGCERegion returns region of the gce zone. Zone names\n// are of the form: ${region-name}-${ix}.\n// For example, \"us-central1-b\" has a region of \"us-central1\".\n// So we look for the last '-' and trim to just before that.\nfunc GetGCERegion(zone string) (string, error) {\n\tix := strings.LastIndex(zone, \"-\")\n\tif ix == -1 {\n\t\treturn \"\", fmt.Errorf(\"unexpected zone: %s\", zone)\n\t}\n\treturn zone[:ix], nil\n}","line":{"from":224,"to":234}} {"id":100034430,"name":"isHTTPErrorCode","signature":"func isHTTPErrorCode(err error, code int) bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"func isHTTPErrorCode(err error, code int) bool {\n\tapiErr, ok := err.(*googleapi.Error)\n\treturn ok \u0026\u0026 apiErr.Code == code\n}","line":{"from":236,"to":239}} {"id":100034431,"name":"isInUsedByError","signature":"func isInUsedByError(err error) bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"func isInUsedByError(err error) bool {\n\tapiErr, ok := err.(*googleapi.Error)\n\tif !ok || apiErr.Code != http.StatusBadRequest {\n\t\treturn false\n\t}\n\treturn strings.Contains(apiErr.Message, \"being used by\")\n}","line":{"from":241,"to":247}} {"id":100034432,"name":"splitProviderID","signature":"func splitProviderID(providerID string) (project, zone, instance string, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"// splitProviderID splits a provider's id into core components.\n// A providerID is build out of '${ProviderName}://${project-id}/${zone}/${instance-name}'\n// See cloudprovider.GetInstanceProviderID.\nfunc splitProviderID(providerID string) (project, zone, instance string, err error) {\n\tmatches := providerIDRE.FindStringSubmatch(providerID)\n\tif len(matches) != 4 {\n\t\treturn \"\", \"\", \"\", errors.New(\"error splitting providerID\")\n\t}\n\treturn matches[1], matches[2], matches[3], nil\n}","line":{"from":249,"to":258}} {"id":100034433,"name":"equalStringSets","signature":"func equalStringSets(x, y []string) bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"func equalStringSets(x, y []string) bool {\n\tif len(x) != len(y) {\n\t\treturn false\n\t}\n\txString := sets.NewString(x...)\n\tyString := sets.NewString(y...)\n\treturn xString.Equal(yString)\n}","line":{"from":260,"to":267}} {"id":100034434,"name":"isNotFound","signature":"func isNotFound(err error) bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"func isNotFound(err error) bool {\n\treturn isHTTPErrorCode(err, http.StatusNotFound)\n}","line":{"from":269,"to":271}} {"id":100034435,"name":"ignoreNotFound","signature":"func ignoreNotFound(err error) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"func ignoreNotFound(err error) error {\n\tif err == nil || isNotFound(err) {\n\t\treturn nil\n\t}\n\treturn err\n}","line":{"from":273,"to":278}} {"id":100034436,"name":"isNotFoundOrInUse","signature":"func isNotFoundOrInUse(err error) bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"func isNotFoundOrInUse(err error) bool {\n\treturn isNotFound(err) || isInUsedByError(err)\n}","line":{"from":280,"to":282}} {"id":100034437,"name":"isForbidden","signature":"func isForbidden(err error) bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"func isForbidden(err error) bool {\n\treturn isHTTPErrorCode(err, http.StatusForbidden)\n}","line":{"from":284,"to":286}} {"id":100034438,"name":"makeGoogleAPINotFoundError","signature":"func makeGoogleAPINotFoundError(message string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"func makeGoogleAPINotFoundError(message string) error {\n\treturn \u0026googleapi.Error{Code: http.StatusNotFound, Message: message}\n}","line":{"from":288,"to":290}} {"id":100034439,"name":"containsCIDR","signature":"func containsCIDR(outer, inner *net.IPNet) bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"// containsCIDR returns true if outer contains inner.\nfunc containsCIDR(outer, inner *net.IPNet) bool {\n\treturn outer.Contains(firstIPInRange(inner)) \u0026\u0026 outer.Contains(lastIPInRange(inner))\n}","line":{"from":292,"to":295}} {"id":100034440,"name":"firstIPInRange","signature":"func firstIPInRange(ipNet *net.IPNet) net.IP","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"// firstIPInRange returns the first IP in a given IP range.\nfunc firstIPInRange(ipNet *net.IPNet) net.IP {\n\treturn ipNet.IP.Mask(ipNet.Mask)\n}","line":{"from":297,"to":300}} {"id":100034441,"name":"lastIPInRange","signature":"func lastIPInRange(cidr *net.IPNet) net.IP","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"// lastIPInRange returns the last IP in a given IP range.\nfunc lastIPInRange(cidr *net.IPNet) net.IP {\n\tip := append([]byte{}, cidr.IP...)\n\tfor i, b := range cidr.Mask {\n\t\tip[i] |= ^b\n\t}\n\treturn ip\n}","line":{"from":302,"to":309}} {"id":100034442,"name":"subnetsInCIDR","signature":"func subnetsInCIDR(subnets []*compute.Subnetwork, cidr *net.IPNet) ([]*compute.Subnetwork, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"// subnetsInCIDR takes a list of subnets for a single region and\n// returns subnets which exists in the specified CIDR range.\nfunc subnetsInCIDR(subnets []*compute.Subnetwork, cidr *net.IPNet) ([]*compute.Subnetwork, error) {\n\tvar res []*compute.Subnetwork\n\tfor _, subnet := range subnets {\n\t\t_, subnetRange, err := netutils.ParseCIDRSloppy(subnet.IpCidrRange)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to parse CIDR %q for subnet %q: %v\", subnet.IpCidrRange, subnet.Name, err)\n\t\t}\n\t\tif containsCIDR(cidr, subnetRange) {\n\t\t\tres = append(res, subnet)\n\t\t}\n\t}\n\treturn res, nil\n}","line":{"from":311,"to":325}} {"id":100034443,"name":"typeOfNetwork","signature":"func typeOfNetwork(network *compute.Network) netType","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"func typeOfNetwork(network *compute.Network) netType {\n\tif network.IPv4Range != \"\" {\n\t\treturn netTypeLegacy\n\t}\n\n\tif network.AutoCreateSubnetworks {\n\t\treturn netTypeAuto\n\t}\n\n\treturn netTypeCustom\n}","line":{"from":335,"to":345}} {"id":100034444,"name":"getLocationName","signature":"func getLocationName(project, zoneOrRegion string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"func getLocationName(project, zoneOrRegion string) string {\n\treturn fmt.Sprintf(\"projects/%s/locations/%s\", project, zoneOrRegion)\n}","line":{"from":347,"to":349}} {"id":100034445,"name":"addFinalizer","signature":"func addFinalizer(service *v1.Service, kubeClient v1core.CoreV1Interface, key string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"func addFinalizer(service *v1.Service, kubeClient v1core.CoreV1Interface, key string) error {\n\tif hasFinalizer(service, key) {\n\t\treturn nil\n\t}\n\n\t// Make a copy so we don't mutate the shared informer cache.\n\tupdated := service.DeepCopy()\n\tupdated.ObjectMeta.Finalizers = append(updated.ObjectMeta.Finalizers, key)\n\n\t_, err := servicehelper.PatchService(kubeClient, service, updated)\n\treturn err\n}","line":{"from":351,"to":362}} {"id":100034446,"name":"removeFinalizer","signature":"func removeFinalizer(service *v1.Service, kubeClient v1core.CoreV1Interface, key string) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"// removeFinalizer patches the service to remove finalizer.\nfunc removeFinalizer(service *v1.Service, kubeClient v1core.CoreV1Interface, key string) error {\n\tif !hasFinalizer(service, key) {\n\t\treturn nil\n\t}\n\n\t// Make a copy so we don't mutate the shared informer cache.\n\tupdated := service.DeepCopy()\n\tupdated.ObjectMeta.Finalizers = removeString(updated.ObjectMeta.Finalizers, key)\n\n\t_, err := servicehelper.PatchService(kubeClient, service, updated)\n\treturn err\n}","line":{"from":364,"to":376}} {"id":100034447,"name":"hasFinalizer","signature":"func hasFinalizer(service *v1.Service, key string) bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"// hasFinalizer returns if the given service has the specified key in its list of finalizers.\nfunc hasFinalizer(service *v1.Service, key string) bool {\n\tfor _, finalizer := range service.ObjectMeta.Finalizers {\n\t\tif finalizer == key {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":378,"to":386}} {"id":100034448,"name":"removeString","signature":"func removeString(slice []string, s string) []string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"// removeString returns a newly created []string that contains all items from slice that\n// are not equal to s.\nfunc removeString(slice []string, s string) []string {\n\tvar newSlice []string\n\tfor _, item := range slice {\n\t\tif item != s {\n\t\t\tnewSlice = append(newSlice, item)\n\t\t}\n\t}\n\treturn newSlice\n}","line":{"from":388,"to":398}} {"id":100034449,"name":"usesL4RBS","signature":"func usesL4RBS(service *v1.Service, forwardingRule *compute.ForwardingRule) bool","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_util.go","code":"// usesL4RBS checks if service uses Regional Backend Service as a Backend.\n// Such services implemented in other controllers and\n// should not be handled by Service Controller.\nfunc usesL4RBS(service *v1.Service, forwardingRule *compute.ForwardingRule) bool {\n\t// Detect RBS by annotation\n\tif val, ok := service.Annotations[RBSAnnotationKey]; ok \u0026\u0026 val == RBSEnabled {\n\t\treturn true\n\t}\n\t// Detect RBS by finalizer\n\tif hasFinalizer(service, NetLBFinalizerV2) {\n\t\treturn true\n\t}\n\t// Detect RBS by existing forwarding rule with Backend Service attached\n\tif forwardingRule != nil \u0026\u0026 forwardingRule.BackendService != \"\" {\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":400,"to":418}} {"id":100034450,"name":"newZonesMetricContext","signature":"func newZonesMetricContext(request, region string) *metricContext","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_zones.go","code":"func newZonesMetricContext(request, region string) *metricContext {\n\treturn newGenericMetricContext(\"zones\", request, region, unusedMetricLabel, computeV1Version)\n}","line":{"from":35,"to":37}} {"id":100034451,"name":"GetZone","signature":"func (g *Cloud) GetZone(ctx context.Context) (cloudprovider.Zone, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_zones.go","code":"// GetZone creates a cloudprovider.Zone of the current zone and region\nfunc (g *Cloud) GetZone(ctx context.Context) (cloudprovider.Zone, error) {\n\treturn cloudprovider.Zone{\n\t\tFailureDomain: g.localZone,\n\t\tRegion: g.region,\n\t}, nil\n}","line":{"from":39,"to":45}} {"id":100034452,"name":"GetZoneByProviderID","signature":"func (g *Cloud) GetZoneByProviderID(ctx context.Context, providerID string) (cloudprovider.Zone, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_zones.go","code":"// GetZoneByProviderID implements Zones.GetZoneByProviderID\n// This is particularly useful in external cloud providers where the kubelet\n// does not initialize node data.\nfunc (g *Cloud) GetZoneByProviderID(ctx context.Context, providerID string) (cloudprovider.Zone, error) {\n\t_, zone, _, err := splitProviderID(providerID)\n\tif err != nil {\n\t\treturn cloudprovider.Zone{}, err\n\t}\n\tregion, err := GetGCERegion(zone)\n\tif err != nil {\n\t\treturn cloudprovider.Zone{}, err\n\t}\n\treturn cloudprovider.Zone{FailureDomain: zone, Region: region}, nil\n}","line":{"from":47,"to":60}} {"id":100034453,"name":"GetZoneByNodeName","signature":"func (g *Cloud) GetZoneByNodeName(ctx context.Context, nodeName types.NodeName) (cloudprovider.Zone, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_zones.go","code":"// GetZoneByNodeName implements Zones.GetZoneByNodeName\n// This is particularly useful in external cloud providers where the kubelet\n// does not initialize node data.\nfunc (g *Cloud) GetZoneByNodeName(ctx context.Context, nodeName types.NodeName) (cloudprovider.Zone, error) {\n\tinstanceName := mapNodeNameToInstanceName(nodeName)\n\tinstance, err := g.getInstanceByName(instanceName)\n\tif err != nil {\n\t\treturn cloudprovider.Zone{}, err\n\t}\n\tregion, err := GetGCERegion(instance.Zone)\n\tif err != nil {\n\t\treturn cloudprovider.Zone{}, err\n\t}\n\treturn cloudprovider.Zone{FailureDomain: instance.Zone, Region: region}, nil\n}","line":{"from":62,"to":76}} {"id":100034454,"name":"ListZonesInRegion","signature":"func (g *Cloud) ListZonesInRegion(region string) ([]*compute.Zone, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_zones.go","code":"// ListZonesInRegion returns all zones in a GCP region\nfunc (g *Cloud) ListZonesInRegion(region string) ([]*compute.Zone, error) {\n\tctx, cancel := cloud.ContextWithCallTimeout()\n\tdefer cancel()\n\n\tmc := newZonesMetricContext(\"list\", region)\n\t// Use regex match instead of an exact regional link constructed from getRegionalLink below.\n\t// See comments in issue kubernetes/kubernetes#87905\n\tlist, err := g.c.Zones().List(ctx, filter.Regexp(\"region\", fmt.Sprintf(\".*/regions/%s\", region)))\n\tif err != nil {\n\t\treturn nil, mc.Observe(err)\n\t}\n\treturn list, mc.Observe(err)\n}","line":{"from":78,"to":91}} {"id":100034455,"name":"getRegionLink","signature":"func (g *Cloud) getRegionLink(region string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gce_zones.go","code":"func (g *Cloud) getRegionLink(region string) string {\n\treturn g.projectsBasePath + strings.Join([]string{g.projectID, \"regions\", region}, \"/\")\n}","line":{"from":93,"to":95}} {"id":100034456,"name":"Error","signature":"func (he *HTTPError) Error() string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gcpcredential/credentialutil.go","code":"// Error implements error\nfunc (he *HTTPError) Error() string {\n\treturn fmt.Sprintf(\"http status code: %d while fetching url %s\",\n\t\the.StatusCode, he.URL)\n}","line":{"from":41,"to":45}} {"id":100034457,"name":"ReadURL","signature":"func ReadURL(url string, client *http.Client, header *http.Header) (body []byte, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gcpcredential/credentialutil.go","code":"// ReadURL read contents from given url\nfunc ReadURL(url string, client *http.Client, header *http.Header) (body []byte, err error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif header != nil {\n\t\treq.Header = *header\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tklog.V(2).InfoS(\"Failed to read URL\", \"statusCode\", resp.StatusCode, \"URL\", url)\n\t\treturn nil, \u0026HTTPError{\n\t\t\tStatusCode: resp.StatusCode,\n\t\t\tURL: url,\n\t\t}\n\t}\n\n\tlimitedReader := \u0026io.LimitedReader{R: resp.Body, N: maxReadLength}\n\tcontents, err := ioutil.ReadAll(limitedReader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif limitedReader.N \u003c= 0 {\n\t\treturn nil, errors.New(\"the read limit is reached\")\n\t}\n\n\treturn contents, nil\n}","line":{"from":47,"to":81}} {"id":100034458,"name":"ReadDockerConfigFileFromURL","signature":"func ReadDockerConfigFileFromURL(url string, client *http.Client, header *http.Header) (cfg credentialconfig.RegistryConfig, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gcpcredential/credentialutil.go","code":"// ReadDockerConfigFileFromURL read a docker config file from the given url\nfunc ReadDockerConfigFileFromURL(url string, client *http.Client, header *http.Header) (cfg credentialconfig.RegistryConfig, err error) {\n\tif contents, err := ReadURL(url, client, header); err == nil {\n\t\treturn ReadDockerConfigFileFromBytes(contents)\n\t}\n\n\treturn nil, err\n}","line":{"from":83,"to":90}} {"id":100034459,"name":"ReadDockerConfigFileFromBytes","signature":"func ReadDockerConfigFileFromBytes(contents []byte) (cfg credentialconfig.RegistryConfig, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gcpcredential/credentialutil.go","code":"// ReadDockerConfigFileFromBytes read a docker config file from the given bytes\nfunc ReadDockerConfigFileFromBytes(contents []byte) (cfg credentialconfig.RegistryConfig, err error) {\n\tserializableCfg := internalRegistryConfig{}\n\tif err = json.Unmarshal(contents, \u0026serializableCfg); err != nil {\n\t\treturn nil, errors.New(\"error occurred while trying to unmarshal json\")\n\t}\n\treturn convertToExternalConfig(serializableCfg), nil\n}","line":{"from":94,"to":101}} {"id":100034460,"name":"convertToExternalConfig","signature":"func convertToExternalConfig(in internalRegistryConfig) (cfg credentialconfig.RegistryConfig)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gcpcredential/credentialutil.go","code":"func convertToExternalConfig(in internalRegistryConfig) (cfg credentialconfig.RegistryConfig) {\n\tconfigMap := credentialconfig.RegistryConfig{}\n\tfor k, v := range in {\n\t\tconfigMap[k] = credentialconfig.RegistryConfigEntry{\n\t\t\tUsername: v.Username,\n\t\t\tPassword: v.Password,\n\t\t\tEmail: v.Email,\n\t\t}\n\t}\n\treturn configMap\n}","line":{"from":103,"to":113}} {"id":100034461,"name":"ProvideConfigKey","signature":"func ProvideConfigKey(client *http.Client, image string) credentialconfig.RegistryConfig","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gcpcredential/gcpcredential.go","code":"// ProvideConfigKey implements a dockercfg-based authentication flow.\nfunc ProvideConfigKey(client *http.Client, image string) credentialconfig.RegistryConfig {\n\t// Read the contents of the google-dockercfg metadata key and\n\t// parse them as an alternate .dockercfg\n\tif cfg, err := ReadDockerConfigFileFromURL(DockerConfigKey, client, metadataHeader); err != nil {\n\t\tklog.Errorf(\"while reading 'google-dockercfg' metadata: %v\", err)\n\t} else {\n\t\treturn cfg\n\t}\n\n\treturn credentialconfig.RegistryConfig{}\n}","line":{"from":57,"to":68}} {"id":100034462,"name":"ProvideURLKey","signature":"func ProvideURLKey(client *http.Client, image string) credentialconfig.RegistryConfig","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gcpcredential/gcpcredential.go","code":"// ProvideURLKey implements a dockercfg-url-based authentication flow.\nfunc ProvideURLKey(client *http.Client, image string) credentialconfig.RegistryConfig {\n\t// Read the contents of the google-dockercfg-url key and load a .dockercfg from there\n\tif url, err := ReadURL(DockerConfigURLKey, client, metadataHeader); err != nil {\n\t\tklog.Errorf(\"while reading 'google-dockercfg-url' metadata: %v\", err)\n\t} else {\n\t\tif strings.HasPrefix(string(url), \"http\") {\n\t\t\tif cfg, err := ReadDockerConfigFileFromURL(string(url), client, nil); err != nil {\n\t\t\t\tklog.Errorf(\"while reading 'google-dockercfg-url'-specified url: %s, %v\", string(url), err)\n\t\t\t} else {\n\t\t\t\treturn cfg\n\t\t\t}\n\t\t} else {\n\t\t\t// TODO(mattmoor): support reading alternate scheme URLs (e.g. gs:// or s3://)\n\t\t\tklog.Errorf(\"Unsupported URL scheme: %s\", string(url))\n\t\t}\n\t}\n\n\treturn credentialconfig.RegistryConfig{}\n}","line":{"from":70,"to":89}} {"id":100034463,"name":"ProvideContainerRegistry","signature":"func ProvideContainerRegistry(client *http.Client, image string) credentialconfig.RegistryConfig","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gcpcredential/gcpcredential.go","code":"// ProvideContainerRegistry implements a gcr.io-based authentication flow.\nfunc ProvideContainerRegistry(client *http.Client, image string) credentialconfig.RegistryConfig {\n\tcfg := credentialconfig.RegistryConfig{}\n\n\ttokenJSONBlob, err := ReadURL(metadataToken, client, metadataHeader)\n\tif err != nil {\n\t\tklog.Errorf(\"while reading access token endpoint: %v\", err)\n\t\treturn cfg\n\t}\n\n\temail, err := ReadURL(metadataEmail, client, metadataHeader)\n\tif err != nil {\n\t\tklog.Errorf(\"while reading email endpoint: %v\", err)\n\t\treturn cfg\n\t}\n\n\tvar parsedBlob TokenBlob\n\tif err := json.Unmarshal([]byte(tokenJSONBlob), \u0026parsedBlob); err != nil {\n\t\tklog.Errorf(\"error while parsing json blob of length %d\", len(tokenJSONBlob))\n\t\treturn cfg\n\t}\n\n\tentry := credentialconfig.RegistryConfigEntry{\n\t\tUsername: \"_token\",\n\t\tPassword: parsedBlob.AccessToken,\n\t\tEmail: string(email),\n\t}\n\n\t// Add our entry for each of the supported container registry URLs\n\tfor _, k := range containerRegistryUrls {\n\t\tcfg[k] = entry\n\t}\n\treturn cfg\n}","line":{"from":97,"to":130}} {"id":100034464,"name":"UnmarshalJSON","signature":"func (ident *RegistryConfigEntry) UnmarshalJSON(data []byte) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gcpcredential/registry_marshal.go","code":"// UnmarshalJSON implements the json.Unmarshaler interface.\nfunc (ident *RegistryConfigEntry) UnmarshalJSON(data []byte) error {\n\tvar tmp registryConfigEntryWithAuth\n\terr := json.Unmarshal(data, \u0026tmp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tident.Username = tmp.Username\n\tident.Password = tmp.Password\n\tident.Email = tmp.Email\n\n\tif len(tmp.Auth) == 0 {\n\t\treturn nil\n\t}\n\n\tident.Username, ident.Password, err = decodeRegistryConfigFieldAuth(tmp.Auth)\n\treturn err\n}","line":{"from":46,"to":64}} {"id":100034465,"name":"MarshalJSON","signature":"func (ident RegistryConfigEntry) MarshalJSON() ([]byte, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gcpcredential/registry_marshal.go","code":"// MarshalJSON implements the json.Marshaler interface.\nfunc (ident RegistryConfigEntry) MarshalJSON() ([]byte, error) {\n\ttoEncode := registryConfigEntryWithAuth{ident.Username, ident.Password, ident.Email, \"\"}\n\ttoEncode.Auth = encodeRegistryConfigFieldAuth(ident.Username, ident.Password)\n\n\treturn json.Marshal(toEncode)\n}","line":{"from":66,"to":72}} {"id":100034466,"name":"decodeRegistryConfigFieldAuth","signature":"func decodeRegistryConfigFieldAuth(field string) (username, password string, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gcpcredential/registry_marshal.go","code":"// decodeRegistryConfigFieldAuth deserializes the \"auth\" field from dockercfg into a\n// username and a password. The format of the auth field is base64(\u003cusername\u003e:\u003cpassword\u003e).\nfunc decodeRegistryConfigFieldAuth(field string) (username, password string, err error) {\n\n\tvar decoded []byte\n\n\t// StdEncoding can only decode padded string\n\t// RawStdEncoding can only decode unpadded string\n\tif strings.HasSuffix(strings.TrimSpace(field), \"=\") {\n\t\t// decode padded data\n\t\tdecoded, err = base64.StdEncoding.DecodeString(field)\n\t} else {\n\t\t// decode unpadded data\n\t\tdecoded, err = base64.RawStdEncoding.DecodeString(field)\n\t}\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tparts := strings.SplitN(string(decoded), \":\", 2)\n\tif len(parts) != 2 {\n\t\terr = fmt.Errorf(\"unable to parse auth field, must be formatted as base64(username:password)\")\n\t\treturn\n\t}\n\n\tusername = parts[0]\n\tpassword = parts[1]\n\n\treturn\n}","line":{"from":74,"to":104}} {"id":100034467,"name":"encodeRegistryConfigFieldAuth","signature":"func encodeRegistryConfigFieldAuth(username, password string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/gcpcredential/registry_marshal.go","code":"func encodeRegistryConfigFieldAuth(username, password string) string {\n\tfieldValue := username + \":\" + password\n\n\treturn base64.StdEncoding.EncodeToString([]byte(fieldValue))\n}","line":{"from":106,"to":110}} {"id":100034468,"name":"Observe","signature":"func (mc *metricContext) Observe(err error) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/metrics.go","code":"// Observe the result of a API call.\nfunc (mc *metricContext) Observe(err error) error {\n\tapiMetrics.latency.WithLabelValues(mc.attributes...).Observe(\n\t\ttime.Since(mc.start).Seconds())\n\tif err != nil {\n\t\tapiMetrics.errors.WithLabelValues(mc.attributes...).Inc()\n\t}\n\n\treturn err\n}","line":{"from":62,"to":71}} {"id":100034469,"name":"newGenericMetricContext","signature":"func newGenericMetricContext(prefix, request, region, zone, version string) *metricContext","file":"staging/src/k8s.io/legacy-cloud-providers/gce/metrics.go","code":"func newGenericMetricContext(prefix, request, region, zone, version string) *metricContext {\n\tif len(zone) == 0 {\n\t\tzone = unusedMetricLabel\n\t}\n\tif len(region) == 0 {\n\t\tregion = unusedMetricLabel\n\t}\n\treturn \u0026metricContext{\n\t\tstart: time.Now(),\n\t\tattributes: []string{prefix + \"_\" + request, region, zone, version},\n\t}\n}","line":{"from":73,"to":84}} {"id":100034470,"name":"registerAPIMetrics","signature":"func registerAPIMetrics() *apiCallMetrics","file":"staging/src/k8s.io/legacy-cloud-providers/gce/metrics.go","code":"// registerApiMetrics adds metrics definitions for a category of API calls.\nfunc registerAPIMetrics() *apiCallMetrics {\n\tmetrics := \u0026apiCallMetrics{\n\t\tlatency: metrics.NewHistogramVec(\n\t\t\t\u0026metrics.HistogramOpts{\n\t\t\t\tName: \"cloudprovider_gce_api_request_duration_seconds\",\n\t\t\t\tHelp: \"Latency of a GCE API call\",\n\t\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t\t},\n\t\t\tmetricLabels,\n\t\t),\n\t\terrors: metrics.NewCounterVec(\n\t\t\t\u0026metrics.CounterOpts{\n\t\t\t\tName: \"cloudprovider_gce_api_request_errors\",\n\t\t\t\tHelp: \"Number of errors for an API call\",\n\t\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t\t},\n\t\t\tmetricLabels,\n\t\t),\n\t}\n\n\tlegacyregistry.MustRegister(metrics.latency)\n\tlegacyregistry.MustRegister(metrics.errors)\n\n\treturn metrics\n}","line":{"from":86,"to":111}} {"id":100034471,"name":"ProjectID","signature":"func (r *gceProjectRouter) ProjectID(ctx context.Context, version meta.Version, service string) string","file":"staging/src/k8s.io/legacy-cloud-providers/gce/support.go","code":"// ProjectID returns the project ID to be used for the given operation.\nfunc (r *gceProjectRouter) ProjectID(ctx context.Context, version meta.Version, service string) string {\n\tswitch service {\n\tcase \"Firewalls\", \"Routes\":\n\t\treturn r.gce.NetworkProjectID()\n\tdefault:\n\t\treturn r.gce.projectID\n\t}\n}","line":{"from":34,"to":42}} {"id":100034472,"name":"Accept","signature":"func (l *gceRateLimiter) Accept(ctx context.Context, key *cloud.RateLimitKey) error","file":"staging/src/k8s.io/legacy-cloud-providers/gce/support.go","code":"// Accept blocks until the operation can be performed.\n//\n// TODO: the current cloud provider policy doesn't seem to be correct as it\n// only rate limits the polling operations, but not the /submission/ of\n// operations.\nfunc (l *gceRateLimiter) Accept(ctx context.Context, key *cloud.RateLimitKey) error {\n\tif key.Operation == \"Get\" \u0026\u0026 key.Service == \"Operations\" {\n\t\t// Wait a minimum amount of time regardless of rate limiter.\n\t\trl := \u0026cloud.MinimumRateLimiter{\n\t\t\t// Convert flowcontrol.RateLimiter into cloud.RateLimiter\n\t\t\tRateLimiter: \u0026cloud.AcceptRateLimiter{\n\t\t\t\tAcceptor: l.gce.operationPollRateLimiter,\n\t\t\t},\n\t\t\tMinimum: operationPollInterval,\n\t\t}\n\t\treturn rl.Accept(ctx, key)\n\t}\n\treturn nil\n}","line":{"from":49,"to":67}} {"id":100034473,"name":"CreateGCECloudWithCloud","signature":"func CreateGCECloudWithCloud(config *CloudConfig, c cloud.Cloud) (*Cloud, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/support.go","code":"// CreateGCECloudWithCloud is a helper function to create an instance of Cloud with the\n// given Cloud interface implementation. Typical usage is to use cloud.NewMockGCE to get a\n// handle to a mock Cloud instance and then use that for testing.\nfunc CreateGCECloudWithCloud(config *CloudConfig, c cloud.Cloud) (*Cloud, error) {\n\tgceCloud, err := CreateGCECloud(config)\n\tif err == nil {\n\t\tgceCloud.c = c\n\t}\n\treturn gceCloud, err\n}","line":{"from":69,"to":78}} {"id":100034474,"name":"init","signature":"func init()","file":"staging/src/k8s.io/legacy-cloud-providers/gce/token_source.go","code":"func init() {\n\tlegacyregistry.MustRegister(getTokenCounter)\n\tlegacyregistry.MustRegister(getTokenFailCounter)\n}","line":{"from":70,"to":73}} {"id":100034475,"name":"Token","signature":"func (a *AltTokenSource) Token() (*oauth2.Token, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/token_source.go","code":"// Token returns a token which may be used for authentication\nfunc (a *AltTokenSource) Token() (*oauth2.Token, error) {\n\ta.throttle.Accept()\n\tgetTokenCounter.Inc()\n\tt, err := a.token()\n\tif err != nil {\n\t\tgetTokenFailCounter.Inc()\n\t}\n\treturn t, err\n}","line":{"from":83,"to":92}} {"id":100034476,"name":"token","signature":"func (a *AltTokenSource) token() (*oauth2.Token, error)","file":"staging/src/k8s.io/legacy-cloud-providers/gce/token_source.go","code":"func (a *AltTokenSource) token() (*oauth2.Token, error) {\n\treq, err := http.NewRequest(\"POST\", a.tokenURL, strings.NewReader(a.tokenBody))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tres, err := a.oauthClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer res.Body.Close()\n\tif err := googleapi.CheckResponse(res); err != nil {\n\t\treturn nil, err\n\t}\n\tvar tok struct {\n\t\tAccessToken string `json:\"accessToken\" datapolicy:\"token\"`\n\t\tExpireTime time.Time `json:\"expireTime\"`\n\t}\n\tif err := json.NewDecoder(res.Body).Decode(\u0026tok); err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026oauth2.Token{\n\t\tAccessToken: tok.AccessToken,\n\t\tExpiry: tok.ExpireTime,\n\t}, nil\n}","line":{"from":94,"to":118}} {"id":100034477,"name":"NewAltTokenSource","signature":"func NewAltTokenSource(tokenURL, tokenBody string) oauth2.TokenSource","file":"staging/src/k8s.io/legacy-cloud-providers/gce/token_source.go","code":"// NewAltTokenSource constructs a new alternate token source for generating tokens.\nfunc NewAltTokenSource(tokenURL, tokenBody string) oauth2.TokenSource {\n\tclient := oauth2.NewClient(context.Background(), google.ComputeTokenSource(\"\"))\n\ta := \u0026AltTokenSource{\n\t\toauthClient: client,\n\t\ttokenURL: tokenURL,\n\t\ttokenBody: tokenBody,\n\t\tthrottle: flowcontrol.NewTokenBucketRateLimiter(tokenURLQPS, tokenURLBurst),\n\t}\n\treturn oauth2.ReuseTokenSource(nil, a)\n}","line":{"from":120,"to":130}} {"id":100034478,"name":"GetCredential","signature":"func (secretCredentialManager *SecretCredentialManager) GetCredential(server string) (*Credential, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/credentialmanager.go","code":"// GetCredential returns credentials for the given vCenter Server.\n// GetCredential returns error if Secret is not added.\n// GetCredential return error is the secret doesn't contain any credentials.\nfunc (secretCredentialManager *SecretCredentialManager) GetCredential(server string) (*Credential, error) {\n\terr := secretCredentialManager.updateCredentialsMap()\n\tif err != nil {\n\t\tstatusErr, ok := err.(*apierrors.StatusError)\n\t\tif (ok \u0026\u0026 statusErr.ErrStatus.Code != http.StatusNotFound) || !ok {\n\t\t\treturn nil, err\n\t\t}\n\t\t// Handle secrets deletion by finding credentials from cache\n\t\tklog.Warningf(\"secret %q not found in namespace %q\", secretCredentialManager.SecretName, secretCredentialManager.SecretNamespace)\n\t}\n\n\t// Converting server FQIN to lowercase to consolidate with config parsing approach\n\tserver = strings.ToLower(server)\n\tcredential, found := secretCredentialManager.Cache.GetCredential(server)\n\tif !found {\n\t\tklog.Errorf(\"credentials not found for server %q\", server)\n\t\treturn nil, ErrCredentialsNotFound\n\t}\n\treturn \u0026credential, nil\n}","line":{"from":67,"to":89}} {"id":100034479,"name":"updateCredentialsMap","signature":"func (secretCredentialManager *SecretCredentialManager) updateCredentialsMap() error","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/credentialmanager.go","code":"func (secretCredentialManager *SecretCredentialManager) updateCredentialsMap() error {\n\tif secretCredentialManager.SecretLister == nil {\n\t\treturn fmt.Errorf(\"secretLister is not initialized\")\n\t}\n\tsecret, err := secretCredentialManager.SecretLister.Secrets(secretCredentialManager.SecretNamespace).Get(secretCredentialManager.SecretName)\n\tif err != nil {\n\t\tklog.Errorf(\"Cannot get secret %s in namespace %s. error: %q\", secretCredentialManager.SecretName, secretCredentialManager.SecretNamespace, err)\n\t\treturn err\n\t}\n\tcacheSecret := secretCredentialManager.Cache.GetSecret()\n\tif cacheSecret != nil \u0026\u0026\n\t\tcacheSecret.GetResourceVersion() == secret.GetResourceVersion() {\n\t\tklog.V(4).Infof(\"VCP SecretCredentialManager: Secret %q will not be updated in cache. Since, secrets have same resource version %q\", secretCredentialManager.SecretName, cacheSecret.GetResourceVersion())\n\t\treturn nil\n\t}\n\tsecretCredentialManager.Cache.UpdateSecret(secret)\n\treturn secretCredentialManager.Cache.parseSecret()\n}","line":{"from":91,"to":108}} {"id":100034480,"name":"GetSecret","signature":"func (cache *SecretCache) GetSecret() *corev1.Secret","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/credentialmanager.go","code":"func (cache *SecretCache) GetSecret() *corev1.Secret {\n\tcache.cacheLock.Lock()\n\tdefer cache.cacheLock.Unlock()\n\treturn cache.Secret\n}","line":{"from":110,"to":114}} {"id":100034481,"name":"UpdateSecret","signature":"func (cache *SecretCache) UpdateSecret(secret *corev1.Secret)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/credentialmanager.go","code":"func (cache *SecretCache) UpdateSecret(secret *corev1.Secret) {\n\tcache.cacheLock.Lock()\n\tdefer cache.cacheLock.Unlock()\n\tcache.Secret = secret\n}","line":{"from":116,"to":120}} {"id":100034482,"name":"GetCredential","signature":"func (cache *SecretCache) GetCredential(server string) (Credential, bool)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/credentialmanager.go","code":"func (cache *SecretCache) GetCredential(server string) (Credential, bool) {\n\tcache.cacheLock.Lock()\n\tdefer cache.cacheLock.Unlock()\n\tcredential, found := cache.VirtualCenter[server]\n\tif !found {\n\t\treturn Credential{}, found\n\t}\n\treturn *credential, found\n}","line":{"from":122,"to":130}} {"id":100034483,"name":"parseSecret","signature":"func (cache *SecretCache) parseSecret() error","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/credentialmanager.go","code":"func (cache *SecretCache) parseSecret() error {\n\tcache.cacheLock.Lock()\n\tdefer cache.cacheLock.Unlock()\n\treturn parseConfig(cache.Secret.Data, cache.VirtualCenter)\n}","line":{"from":132,"to":136}} {"id":100034484,"name":"parseConfig","signature":"func parseConfig(data map[string][]byte, config map[string]*Credential) error","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/credentialmanager.go","code":"// parseConfig returns vCenter ip/fdqn mapping to its credentials viz. Username and Password.\nfunc parseConfig(data map[string][]byte, config map[string]*Credential) error {\n\tif len(data) == 0 {\n\t\treturn ErrCredentialMissing\n\t}\n\tfor credentialKey, credentialValue := range data {\n\t\tcredentialKey = strings.ToLower(credentialKey)\n\t\tvcServer := \"\"\n\t\tif strings.HasSuffix(credentialKey, \"password\") {\n\t\t\tvcServer = strings.Split(credentialKey, \".password\")[0]\n\t\t\tif _, ok := config[vcServer]; !ok {\n\t\t\t\tconfig[vcServer] = \u0026Credential{}\n\t\t\t}\n\t\t\tconfig[vcServer].Password = string(credentialValue)\n\t\t} else if strings.HasSuffix(credentialKey, \"username\") {\n\t\t\tvcServer = strings.Split(credentialKey, \".username\")[0]\n\t\t\tif _, ok := config[vcServer]; !ok {\n\t\t\t\tconfig[vcServer] = \u0026Credential{}\n\t\t\t}\n\t\t\tconfig[vcServer].User = string(credentialValue)\n\t\t} else {\n\t\t\tklog.Errorf(\"Unknown secret key %s\", credentialKey)\n\t\t\treturn ErrUnknownSecretKey\n\t\t}\n\t}\n\tfor vcServer, credential := range config {\n\t\tif credential.User == \"\" || credential.Password == \"\" {\n\t\t\tklog.Errorf(\"Username/Password is missing for server %s\", vcServer)\n\t\t\treturn ErrCredentialMissing\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":138,"to":170}} {"id":100034485,"name":"String","signature":"func (n NodeInfo) String() string","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go","code":"func (n NodeInfo) String() string {\n\treturn fmt.Sprintf(\"{datacenter: %v, vm: %v, vcServer: %s, vmUUID: %s, zone: %v}\",\n\t\t*n.dataCenter, n.vm.Reference(), n.vcServer, n.vmUUID, *n.zone)\n}","line":{"from":50,"to":53}} {"id":100034486,"name":"DiscoverNode","signature":"func (nm *NodeManager) DiscoverNode(node *v1.Node) error","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go","code":"func (nm *NodeManager) DiscoverNode(node *v1.Node) error {\n\ttype VmSearch struct {\n\t\tvc string\n\t\tdatacenter *vclib.Datacenter\n\t}\n\n\tvar mutex = \u0026sync.Mutex{}\n\tvar globalErrMutex = \u0026sync.Mutex{}\n\tvar queueChannel chan *VmSearch\n\tvar wg sync.WaitGroup\n\tvar globalErr *error\n\n\tqueueChannel = make(chan *VmSearch, QUEUE_SIZE)\n\tnodeUUID, err := GetNodeUUID(node)\n\tif err != nil {\n\t\tklog.Errorf(\"Node Discovery failed to get node uuid for node %s with error: %v\", node.Name, err)\n\t\treturn err\n\t}\n\n\tklog.V(4).Infof(\"Discovering node %s with uuid %s\", node.ObjectMeta.Name, nodeUUID)\n\n\tvmFound := false\n\tglobalErr = nil\n\n\tsetGlobalErr := func(err error) {\n\t\tglobalErrMutex.Lock()\n\t\tglobalErr = \u0026err\n\t\tglobalErrMutex.Unlock()\n\t}\n\n\tsetVMFound := func(found bool) {\n\t\tmutex.Lock()\n\t\tvmFound = found\n\t\tmutex.Unlock()\n\t}\n\n\tgetVMFound := func() bool {\n\t\tmutex.Lock()\n\t\tfound := vmFound\n\t\tmutex.Unlock()\n\t\treturn found\n\t}\n\n\tgo func() {\n\t\tvar datacenterObjs []*vclib.Datacenter\n\t\tfor vc, vsi := range nm.vsphereInstanceMap {\n\n\t\t\tfound := getVMFound()\n\t\t\tif found == true {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// Create context\n\t\t\tctx, cancel := context.WithCancel(context.Background())\n\t\t\tdefer cancel()\n\n\t\t\terr := nm.vcConnect(ctx, vsi)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Info(\"Discovering node error vc:\", err)\n\t\t\t\tsetGlobalErr(err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif vsi.cfg.Datacenters == \"\" {\n\t\t\t\tdatacenterObjs, err = vclib.GetAllDatacenter(ctx, vsi.conn)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.V(4).Info(\"Discovering node error dc:\", err)\n\t\t\t\t\tsetGlobalErr(err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdatacenters := strings.Split(vsi.cfg.Datacenters, \",\")\n\t\t\t\tfor _, dc := range datacenters {\n\t\t\t\t\tdc = strings.TrimSpace(dc)\n\t\t\t\t\tif dc == \"\" {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tdatacenterObj, err := vclib.GetDatacenter(ctx, vsi.conn, dc)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tklog.V(4).Info(\"Discovering node error dc:\", err)\n\t\t\t\t\t\tsetGlobalErr(err)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tdatacenterObjs = append(datacenterObjs, datacenterObj)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor _, datacenterObj := range datacenterObjs {\n\t\t\t\tfound := getVMFound()\n\t\t\t\tif found == true {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tklog.V(4).Infof(\"Finding node %s in vc=%s and datacenter=%s\", node.Name, vc, datacenterObj.Name())\n\t\t\t\tqueueChannel \u003c- \u0026VmSearch{\n\t\t\t\t\tvc: vc,\n\t\t\t\t\tdatacenter: datacenterObj,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tclose(queueChannel)\n\t}()\n\n\tfor i := 0; i \u003c POOL_SIZE; i++ {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tfor res := range queueChannel {\n\t\t\t\tctx, cancel := context.WithCancel(context.Background())\n\t\t\t\tvm, err := res.datacenter.GetVMByUUID(ctx, nodeUUID)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.V(4).Infof(\"Error while looking for vm=%+v in vc=%s and datacenter=%s: %v\",\n\t\t\t\t\t\tvm, res.vc, res.datacenter.Name(), err)\n\t\t\t\t\tif err != vclib.ErrNoVMFound {\n\t\t\t\t\t\tsetGlobalErr(err)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tklog.V(4).Infof(\"Did not find node %s in vc=%s and datacenter=%s\",\n\t\t\t\t\t\t\tnode.Name, res.vc, res.datacenter.Name())\n\t\t\t\t\t}\n\t\t\t\t\tcancel()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif vm != nil {\n\t\t\t\t\tklog.V(4).Infof(\"Found node %s as vm=%+v in vc=%s and datacenter=%s\",\n\t\t\t\t\t\tnode.Name, vm, res.vc, res.datacenter.Name())\n\t\t\t\t\tvar vmObj mo.VirtualMachine\n\t\t\t\t\terr := vm.Properties(ctx, vm.Reference(), []string{\"config\"}, \u0026vmObj)\n\t\t\t\t\tif err != nil || vmObj.Config == nil {\n\t\t\t\t\t\tklog.Errorf(\"failed to retrieve guest vmconfig for node: %s Err: %v\", node.Name, err)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tklog.V(4).Infof(\"vm hardware version for node:%s is %s\", node.Name, vmObj.Config.Version)\n\t\t\t\t\t\t// vmconfig.Version returns vm hardware version as vmx-11, vmx-13, vmx-14, vmx-15 etc.\n\t\t\t\t\t\tvmhardwaredeprecated, err := isGuestHardwareVersionDeprecated(vmObj.Config.Version)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tklog.Errorf(\"failed to check if vm hardware version is deprecated. VM Hardware Version: %s Err: %v\", vmObj.Config.Version, err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif vmhardwaredeprecated {\n\t\t\t\t\t\t\tklog.Warningf(\"VM Hardware version: %s from node: %s is deprecated. Please consider upgrading virtual machine hardware version to vmx-15 or higher\", vmObj.Config.Version, node.Name)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// Get the node zone information\n\t\t\t\t\tnodeFd := node.ObjectMeta.Labels[v1.LabelTopologyZone]\n\t\t\t\t\tnodeRegion := node.ObjectMeta.Labels[v1.LabelTopologyRegion]\n\t\t\t\t\tnodeZone := \u0026cloudprovider.Zone{FailureDomain: nodeFd, Region: nodeRegion}\n\t\t\t\t\tnodeInfo := \u0026NodeInfo{dataCenter: res.datacenter, vm: vm, vcServer: res.vc, vmUUID: nodeUUID, zone: nodeZone}\n\t\t\t\t\tnm.addNodeInfo(node.ObjectMeta.Name, nodeInfo)\n\t\t\t\t\tfor range queueChannel {\n\t\t\t\t\t}\n\t\t\t\t\tsetVMFound(true)\n\t\t\t\t\tcancel()\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcancel()\n\t\t\t}\n\t\t\twg.Done()\n\t\t}()\n\t}\n\twg.Wait()\n\tif vmFound {\n\t\treturn nil\n\t}\n\tif globalErr != nil {\n\t\treturn *globalErr\n\t}\n\n\tklog.V(4).Infof(\"Discovery Node: %q vm not found\", node.Name)\n\treturn vclib.ErrNoVMFound\n}","line":{"from":89,"to":255}} {"id":100034487,"name":"RegisterNode","signature":"func (nm *NodeManager) RegisterNode(node *v1.Node) error","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go","code":"func (nm *NodeManager) RegisterNode(node *v1.Node) error {\n\tnm.addNode(node)\n\treturn nm.DiscoverNode(node)\n}","line":{"from":257,"to":260}} {"id":100034488,"name":"UnRegisterNode","signature":"func (nm *NodeManager) UnRegisterNode(node *v1.Node) error","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go","code":"func (nm *NodeManager) UnRegisterNode(node *v1.Node) error {\n\tnm.removeNode(node)\n\treturn nil\n}","line":{"from":262,"to":265}} {"id":100034489,"name":"RediscoverNode","signature":"func (nm *NodeManager) RediscoverNode(nodeName k8stypes.NodeName) error","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go","code":"func (nm *NodeManager) RediscoverNode(nodeName k8stypes.NodeName) error {\n\tnode, err := nm.GetNode(nodeName)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nm.DiscoverNode(\u0026node)\n}","line":{"from":267,"to":274}} {"id":100034490,"name":"GetNode","signature":"func (nm *NodeManager) GetNode(nodeName k8stypes.NodeName) (v1.Node, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go","code":"func (nm *NodeManager) GetNode(nodeName k8stypes.NodeName) (v1.Node, error) {\n\tnm.registeredNodesLock.RLock()\n\tnode := nm.registeredNodes[convertToString(nodeName)]\n\tnm.registeredNodesLock.RUnlock()\n\tif node != nil {\n\t\tklog.V(4).Infof(\"Node %s found in vSphere cloud provider cache\", nodeName)\n\t\treturn *node, nil\n\t}\n\n\tif nm.nodeLister != nil {\n\t\tklog.V(4).Infof(\"Node %s missing in vSphere cloud provider cache, trying node informer\")\n\t\tnode, err := nm.nodeLister.Get(convertToString(nodeName))\n\t\tif err != nil {\n\t\t\tif !errors.IsNotFound(err) {\n\t\t\t\treturn v1.Node{}, err\n\t\t\t}\n\t\t\t// Fall through with IsNotFound error and try to get the node from the API server\n\t\t} else {\n\t\t\tnode := node.DeepCopy()\n\t\t\tnm.addNode(node)\n\t\t\tklog.V(4).Infof(\"Node %s found in vSphere cloud provider node informer\", nodeName)\n\t\t\treturn *node, nil\n\t\t}\n\t}\n\n\tif nm.nodeGetter != nil {\n\t\tklog.V(4).Infof(\"Node %s missing in vSphere cloud provider caches, trying the API server\")\n\t\tnode, err := nm.nodeGetter.Nodes().Get(context.TODO(), convertToString(nodeName), metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\tif !errors.IsNotFound(err) {\n\t\t\t\treturn v1.Node{}, err\n\t\t\t}\n\t\t\t// Fall through with IsNotFound error to keep the code consistent with the above\n\t\t} else {\n\t\t\tnm.addNode(node)\n\t\t\tklog.V(4).Infof(\"Node %s found in the API server\", nodeName)\n\t\t\treturn *node, nil\n\t\t}\n\t}\n\tklog.V(4).Infof(\"Node %s not found in vSphere cloud provider\", nodeName)\n\treturn v1.Node{}, vclib.ErrNoVMFound\n}","line":{"from":276,"to":317}} {"id":100034491,"name":"getNodes","signature":"func (nm *NodeManager) getNodes() map[string]*v1.Node","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go","code":"func (nm *NodeManager) getNodes() map[string]*v1.Node {\n\tnm.registeredNodesLock.RLock()\n\tdefer nm.registeredNodesLock.RUnlock()\n\tregisteredNodes := make(map[string]*v1.Node, len(nm.registeredNodes))\n\tfor nodeName, node := range nm.registeredNodes {\n\t\tregisteredNodes[nodeName] = node\n\t}\n\treturn registeredNodes\n}","line":{"from":319,"to":327}} {"id":100034492,"name":"addNode","signature":"func (nm *NodeManager) addNode(node *v1.Node)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go","code":"func (nm *NodeManager) addNode(node *v1.Node) {\n\tnm.registeredNodesLock.Lock()\n\tnm.registeredNodes[node.ObjectMeta.Name] = node\n\tnm.registeredNodesLock.Unlock()\n}","line":{"from":329,"to":333}} {"id":100034493,"name":"removeNode","signature":"func (nm *NodeManager) removeNode(node *v1.Node)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go","code":"func (nm *NodeManager) removeNode(node *v1.Node) {\n\tnm.registeredNodesLock.Lock()\n\tdelete(nm.registeredNodes, node.ObjectMeta.Name)\n\tnm.registeredNodesLock.Unlock()\n\n\tnm.nodeInfoLock.Lock()\n\tdelete(nm.nodeInfoMap, node.ObjectMeta.Name)\n\tnm.nodeInfoLock.Unlock()\n}","line":{"from":335,"to":343}} {"id":100034494,"name":"GetNodeInfo","signature":"func (nm *NodeManager) GetNodeInfo(nodeName k8stypes.NodeName) (NodeInfo, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go","code":"// GetNodeInfo returns a NodeInfo which datacenter, vm and vc server ip address.\n// This method returns an error if it is unable find node VCs and DCs listed in vSphere.conf\n// NodeInfo returned may not be updated to reflect current VM location.\n//\n// This method is a getter but it can cause side-effect of updating NodeInfo object.\nfunc (nm *NodeManager) GetNodeInfo(nodeName k8stypes.NodeName) (NodeInfo, error) {\n\treturn nm.getRefreshedNodeInfo(nodeName)\n}","line":{"from":345,"to":352}} {"id":100034495,"name":"GetNodeDetails","signature":"func (nm *NodeManager) GetNodeDetails() ([]NodeDetails, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go","code":"// GetNodeDetails returns NodeDetails for all the discovered nodes.\n//\n// This method is a getter but it can cause side-effect of updating NodeInfo objects.\nfunc (nm *NodeManager) GetNodeDetails() ([]NodeDetails, error) {\n\tvar nodeDetails []NodeDetails\n\n\tfor nodeName, nodeObj := range nm.getNodes() {\n\t\tnodeInfo, err := nm.GetNodeInfoWithNodeObject(nodeObj)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tklog.V(4).Infof(\"Updated NodeInfo %v for node %q.\", nodeInfo, nodeName)\n\t\tnodeDetails = append(nodeDetails, NodeDetails{nodeName, nodeInfo.vm, nodeInfo.vmUUID, nodeInfo.zone})\n\t}\n\treturn nodeDetails, nil\n}","line":{"from":354,"to":369}} {"id":100034496,"name":"GetNodeNames","signature":"func (nm *NodeManager) GetNodeNames() []k8stypes.NodeName","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go","code":"// GetNodeNames returns list of nodes that are known to vsphere cloudprovider.\n// These are typically nodes that make up k8s cluster.\nfunc (nm *NodeManager) GetNodeNames() []k8stypes.NodeName {\n\tnodes := nm.getNodes()\n\tvar nodeNameList []k8stypes.NodeName\n\tfor _, node := range nodes {\n\t\tnodeNameList = append(nodeNameList, k8stypes.NodeName(node.Name))\n\t}\n\treturn nodeNameList\n}","line":{"from":371,"to":380}} {"id":100034497,"name":"refreshNodes","signature":"func (nm *NodeManager) refreshNodes() (errList []error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go","code":"func (nm *NodeManager) refreshNodes() (errList []error) {\n\tfor nodeName := range nm.getNodes() {\n\t\tnodeInfo, err := nm.getRefreshedNodeInfo(convertToK8sType(nodeName))\n\t\tif err != nil {\n\t\t\terrList = append(errList, err)\n\t\t\tcontinue\n\t\t}\n\t\tklog.V(4).Infof(\"Updated NodeInfo %v for node %q.\", nodeInfo, nodeName)\n\t}\n\treturn errList\n}","line":{"from":382,"to":392}} {"id":100034498,"name":"getRefreshedNodeInfo","signature":"func (nm *NodeManager) getRefreshedNodeInfo(nodeName k8stypes.NodeName) (NodeInfo, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go","code":"func (nm *NodeManager) getRefreshedNodeInfo(nodeName k8stypes.NodeName) (NodeInfo, error) {\n\tnodeInfo := nm.getNodeInfo(nodeName)\n\tvar err error\n\tif nodeInfo == nil {\n\t\t// Rediscover node if no NodeInfo found.\n\t\tklog.V(4).Infof(\"No VM found for node %q. Initiating rediscovery.\", convertToString(nodeName))\n\t\terr = nm.RediscoverNode(nodeName)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Error %q node info for node %q not found\", err, convertToString(nodeName))\n\t\t\treturn NodeInfo{}, err\n\t\t}\n\t\tnodeInfo = nm.getNodeInfo(nodeName)\n\t} else {\n\t\t// Renew the found NodeInfo to avoid stale vSphere connection.\n\t\tklog.V(4).Infof(\"Renewing NodeInfo %+v for node %q\", nodeInfo, convertToString(nodeName))\n\t\tnodeInfo, err = nm.renewNodeInfo(nodeInfo, true)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Error %q occurred while renewing NodeInfo for %q\", err, convertToString(nodeName))\n\t\t\treturn NodeInfo{}, err\n\t\t}\n\t\tnm.addNodeInfo(convertToString(nodeName), nodeInfo)\n\t}\n\treturn *nodeInfo, nil\n}","line":{"from":394,"to":417}} {"id":100034499,"name":"addNodeInfo","signature":"func (nm *NodeManager) addNodeInfo(nodeName string, nodeInfo *NodeInfo)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go","code":"func (nm *NodeManager) addNodeInfo(nodeName string, nodeInfo *NodeInfo) {\n\tnm.nodeInfoLock.Lock()\n\tnm.nodeInfoMap[nodeName] = nodeInfo\n\tnm.nodeInfoLock.Unlock()\n}","line":{"from":419,"to":423}} {"id":100034500,"name":"getNodeInfo","signature":"func (nm *NodeManager) getNodeInfo(nodeName k8stypes.NodeName) *NodeInfo","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go","code":"func (nm *NodeManager) getNodeInfo(nodeName k8stypes.NodeName) *NodeInfo {\n\tnm.nodeInfoLock.RLock()\n\tnodeInfo := nm.nodeInfoMap[convertToString(nodeName)]\n\tnm.nodeInfoLock.RUnlock()\n\treturn nodeInfo\n}","line":{"from":425,"to":430}} {"id":100034501,"name":"GetVSphereInstance","signature":"func (nm *NodeManager) GetVSphereInstance(nodeName k8stypes.NodeName) (VSphereInstance, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go","code":"func (nm *NodeManager) GetVSphereInstance(nodeName k8stypes.NodeName) (VSphereInstance, error) {\n\tnodeInfo, err := nm.GetNodeInfo(nodeName)\n\tif err != nil {\n\t\tklog.V(4).Infof(\"node info for node %q not found\", convertToString(nodeName))\n\t\treturn VSphereInstance{}, err\n\t}\n\tvsphereInstance := nm.vsphereInstanceMap[nodeInfo.vcServer]\n\tif vsphereInstance == nil {\n\t\treturn VSphereInstance{}, fmt.Errorf(\"vSphereInstance for vc server %q not found while looking for node %q\", nodeInfo.vcServer, convertToString(nodeName))\n\t}\n\treturn *vsphereInstance, nil\n}","line":{"from":432,"to":443}} {"id":100034502,"name":"renewNodeInfo","signature":"func (nm *NodeManager) renewNodeInfo(nodeInfo *NodeInfo, reconnect bool) (*NodeInfo, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go","code":"// renewNodeInfo renews vSphere connection, VirtualMachine and Datacenter for NodeInfo instance.\nfunc (nm *NodeManager) renewNodeInfo(nodeInfo *NodeInfo, reconnect bool) (*NodeInfo, error) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tvsphereInstance := nm.vsphereInstanceMap[nodeInfo.vcServer]\n\tif vsphereInstance == nil {\n\t\terr := fmt.Errorf(\"vSphereInstance for vSphere %q not found while refershing NodeInfo for VM %q\", nodeInfo.vcServer, nodeInfo.vm)\n\t\treturn nil, err\n\t}\n\tif reconnect {\n\t\terr := nm.vcConnect(ctx, vsphereInstance)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tvm := nodeInfo.vm.RenewVM(vsphereInstance.conn.Client)\n\treturn \u0026NodeInfo{\n\t\tvm: \u0026vm,\n\t\tdataCenter: vm.Datacenter,\n\t\tvcServer: nodeInfo.vcServer,\n\t\tvmUUID: nodeInfo.vmUUID,\n\t\tzone: nodeInfo.zone,\n\t}, nil\n}","line":{"from":445,"to":469}} {"id":100034503,"name":"VM","signature":"func (nodeInfo *NodeInfo) VM() *vclib.VirtualMachine","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go","code":"func (nodeInfo *NodeInfo) VM() *vclib.VirtualMachine {\n\tif nodeInfo == nil {\n\t\treturn nil\n\t}\n\treturn nodeInfo.vm\n}","line":{"from":471,"to":476}} {"id":100034504,"name":"vcConnect","signature":"func (nm *NodeManager) vcConnect(ctx context.Context, vsphereInstance *VSphereInstance) error","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go","code":"// vcConnect connects to vCenter with existing credentials\n// If credentials are invalid:\n// 1. It will fetch credentials from credentialManager\n// 2. Update the credentials\n// 3. Connects again to vCenter with fetched credentials\nfunc (nm *NodeManager) vcConnect(ctx context.Context, vsphereInstance *VSphereInstance) error {\n\terr := vsphereInstance.conn.Connect(ctx)\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\tcredentialManager := nm.CredentialManager()\n\tif !vclib.IsInvalidCredentialsError(err) || credentialManager == nil {\n\t\tklog.Errorf(\"Cannot connect to vCenter with err: %v\", err)\n\t\treturn err\n\t}\n\n\tklog.V(4).Infof(\"Invalid credentials. Cannot connect to server %q. Fetching credentials from secrets.\", vsphereInstance.conn.Hostname)\n\n\t// Get latest credentials from SecretCredentialManager\n\tcredentials, err := credentialManager.GetCredential(vsphereInstance.conn.Hostname)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get credentials from Secret Credential Manager with err: %v\", err)\n\t\treturn err\n\t}\n\tvsphereInstance.conn.UpdateCredentials(credentials.User, credentials.Password)\n\treturn vsphereInstance.conn.Connect(ctx)\n}","line":{"from":478,"to":505}} {"id":100034505,"name":"GetNodeInfoWithNodeObject","signature":"func (nm *NodeManager) GetNodeInfoWithNodeObject(node *v1.Node) (NodeInfo, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go","code":"// GetNodeInfoWithNodeObject returns a NodeInfo which datacenter, vm and vc server ip address.\n// This method returns an error if it is unable find node VCs and DCs listed in vSphere.conf\n// NodeInfo returned may not be updated to reflect current VM location.\n//\n// This method is a getter but it can cause side-effect of updating NodeInfo object.\nfunc (nm *NodeManager) GetNodeInfoWithNodeObject(node *v1.Node) (NodeInfo, error) {\n\treturn nm.getRefreshedNodeInfo(convertToK8sType(node.Name))\n}","line":{"from":507,"to":514}} {"id":100034506,"name":"CredentialManager","signature":"func (nm *NodeManager) CredentialManager() *SecretCredentialManager","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go","code":"func (nm *NodeManager) CredentialManager() *SecretCredentialManager {\n\tnm.credentialManagerLock.Lock()\n\tdefer nm.credentialManagerLock.Unlock()\n\treturn nm.credentialManager\n}","line":{"from":516,"to":520}} {"id":100034507,"name":"UpdateCredentialManager","signature":"func (nm *NodeManager) UpdateCredentialManager(credentialManager *SecretCredentialManager)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go","code":"func (nm *NodeManager) UpdateCredentialManager(credentialManager *SecretCredentialManager) {\n\tnm.credentialManagerLock.Lock()\n\tdefer nm.credentialManagerLock.Unlock()\n\tnm.credentialManager = credentialManager\n}","line":{"from":522,"to":526}} {"id":100034508,"name":"GetHostsInZone","signature":"func (nm *NodeManager) GetHostsInZone(ctx context.Context, zoneFailureDomain string) ([]*object.HostSystem, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go","code":"func (nm *NodeManager) GetHostsInZone(ctx context.Context, zoneFailureDomain string) ([]*object.HostSystem, error) {\n\tklog.V(9).Infof(\"GetHostsInZone called with registeredNodes: %v\", nm.registeredNodes)\n\tnodeDetails, err := nm.GetNodeDetails()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tklog.V(4).Infof(\"Node Details: %v\", nodeDetails)\n\t// Build a map of Host moRef to HostSystem\n\thostMap := make(map[string]*object.HostSystem)\n\tfor _, n := range nodeDetails {\n\t\t// Match the provided zone failure domain with the node.\n\t\tklog.V(9).Infof(\"Matching provided zone %s with node %s zone %s\", zoneFailureDomain, n.NodeName, n.Zone.FailureDomain)\n\t\tif zoneFailureDomain == n.Zone.FailureDomain {\n\t\t\thost, err := n.vm.HostSystem(ctx)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"Failed to get host system for VM %s. err: %+v\", n.vm, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\thostMap[host.Reference().Value] = host\n\t\t}\n\t}\n\t// Build the unique list of hosts.\n\thosts := make([]*object.HostSystem, 0)\n\tfor _, value := range hostMap {\n\t\thosts = append(hosts, value)\n\t}\n\tklog.V(4).Infof(\"GetHostsInZone %v returning: %v\", zoneFailureDomain, hosts)\n\treturn hosts, nil\n}","line":{"from":528,"to":556}} {"id":100034509,"name":"SetNodeLister","signature":"func (nm *NodeManager) SetNodeLister(nodeLister corelisters.NodeLister)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go","code":"func (nm *NodeManager) SetNodeLister(nodeLister corelisters.NodeLister) {\n\tnm.nodeLister = nodeLister\n}","line":{"from":558,"to":560}} {"id":100034510,"name":"SetNodeGetter","signature":"func (nm *NodeManager) SetNodeGetter(nodeGetter coreclients.NodesGetter)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go","code":"func (nm *NodeManager) SetNodeGetter(nodeGetter coreclients.NodesGetter) {\n\tnm.nodeGetter = nodeGetter\n}","line":{"from":562,"to":564}} {"id":100034511,"name":"getSharedDatastore","signature":"func (shared *sharedDatastore) getSharedDatastore(ctcx context.Context) (*vclib.DatastoreInfo, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/shared_datastore.go","code":"func (shared *sharedDatastore) getSharedDatastore(ctcx context.Context) (*vclib.DatastoreInfo, error) {\n\tnodes := shared.nodeManager.getNodes()\n\n\t// Segregate nodes according to VC-DC\n\tdcNodes := make(map[string][]NodeInfo)\n\tnodeHosts := make(map[string]hostInfo)\n\n\tfor nodeName, node := range nodes {\n\t\tnodeInfo, err := shared.nodeManager.GetNodeInfoWithNodeObject(node)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to find node %s: %v\", nodeName, err)\n\t\t}\n\t\tvcDC := nodeInfo.vcServer + nodeInfo.dataCenter.String()\n\t\tdcNodes[vcDC] = append(dcNodes[vcDC], nodeInfo)\n\t}\n\n\tfor vcDC, nodes := range dcNodes {\n\t\tvar hostInfos []hostInfo\n\t\tvar err error\n\t\thostInfos, err = shared.getNodeHosts(ctcx, nodes, vcDC)\n\t\tif err != nil {\n\t\t\tif vclib.IsManagedObjectNotFoundError(err) {\n\t\t\t\tklog.Warningf(\"SharedHost.getSharedDatastore: batch fetching of hosts failed - switching to fetching them individually.\")\n\t\t\t\thostInfos, err = shared.getEachNodeHost(ctcx, nodes, vcDC)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Errorf(\"SharedHost.getSharedDatastore: error fetching node hosts individually: %v\", err)\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\tfor _, host := range hostInfos {\n\t\t\thostDCName := fmt.Sprintf(\"%s/%s\", host.datacenter, host.hostMOID)\n\t\t\tnodeHosts[hostDCName] = host\n\t\t}\n\t}\n\n\tif len(nodeHosts) \u003c 1 {\n\t\tmsg := fmt.Sprintf(\"SharedHost.getSharedDatastore unable to find hosts associated with nodes\")\n\t\tklog.Error(msg)\n\t\treturn nil, fmt.Errorf(\"\")\n\t}\n\n\tfor _, datastoreInfo := range shared.candidateDatastores {\n\t\tdataStoreHosts, err := shared.getAttachedHosts(ctcx, datastoreInfo.Datastore)\n\t\tif err != nil {\n\t\t\tmsg := fmt.Sprintf(\"error finding attached hosts to datastore %s: %v\", datastoreInfo.Name(), err)\n\t\t\tklog.Error(msg)\n\t\t\treturn nil, fmt.Errorf(msg)\n\t\t}\n\t\tif shared.isIncluded(dataStoreHosts, nodeHosts) {\n\t\t\treturn datastoreInfo, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"SharedHost.getSharedDatastore: unable to find any shared datastores\")\n}","line":{"from":51,"to":107}} {"id":100034512,"name":"isIncluded","signature":"func (shared *sharedDatastore) isIncluded(dataStoreHosts []hostInfo, nodeHosts map[string]hostInfo) bool","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/shared_datastore.go","code":"// check if all of the nodeHosts are included in the dataStoreHosts\nfunc (shared *sharedDatastore) isIncluded(dataStoreHosts []hostInfo, nodeHosts map[string]hostInfo) bool {\n\tresult := true\n\tfor _, host := range nodeHosts {\n\t\thostFound := false\n\t\tfor _, targetHost := range dataStoreHosts {\n\t\t\tif host.hostUUID == targetHost.hostUUID \u0026\u0026 host.hostMOID == targetHost.hostMOID {\n\t\t\t\thostFound = true\n\t\t\t}\n\t\t}\n\t\tif !hostFound {\n\t\t\tresult = false\n\t\t}\n\t}\n\treturn result\n}","line":{"from":109,"to":124}} {"id":100034513,"name":"getEachNodeHost","signature":"func (shared *sharedDatastore) getEachNodeHost(ctx context.Context, nodes []NodeInfo, dcVC string) ([]hostInfo, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/shared_datastore.go","code":"func (shared *sharedDatastore) getEachNodeHost(ctx context.Context, nodes []NodeInfo, dcVC string) ([]hostInfo, error) {\n\tvar hosts []hostInfo\n\tfor _, node := range nodes {\n\t\thost, err := node.vm.GetHost(ctx)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"SharedHost.getEachNodeHost: unable to find host for vm %s: %v\", node.vm.InventoryPath, err)\n\t\t\treturn nil, err\n\t\t}\n\t\thosts = append(hosts, hostInfo{\n\t\t\thostUUID: host.Summary.Hardware.Uuid,\n\t\t\thostMOID: host.Summary.Host.String(),\n\t\t\tdatacenter: node.dataCenter.String(),\n\t\t})\n\t}\n\treturn hosts, nil\n}","line":{"from":126,"to":141}} {"id":100034514,"name":"getNodeHosts","signature":"func (shared *sharedDatastore) getNodeHosts(ctx context.Context, nodes []NodeInfo, dcVC string) ([]hostInfo, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/shared_datastore.go","code":"func (shared *sharedDatastore) getNodeHosts(ctx context.Context, nodes []NodeInfo, dcVC string) ([]hostInfo, error) {\n\tvar vmRefs []types.ManagedObjectReference\n\tif len(nodes) \u003c 1 {\n\t\treturn nil, fmt.Errorf(\"no nodes found for dc-vc: %s\", dcVC)\n\t}\n\tvar nodeInfo NodeInfo\n\tfor _, n := range nodes {\n\t\tnodeInfo = n\n\t\tvmRefs = append(vmRefs, n.vm.Reference())\n\t}\n\tpc := property.DefaultCollector(nodeInfo.dataCenter.Client())\n\tvar vmoList []mo.VirtualMachine\n\terr := pc.Retrieve(ctx, vmRefs, []string{nameProperty, runtimeHost}, \u0026vmoList)\n\tif err != nil {\n\t\tklog.Errorf(\"SharedHost.getNodeHosts: unable to fetch vms from datacenter %s: %v\", nodeInfo.dataCenter.String(), err)\n\t\treturn nil, err\n\t}\n\tvar hostMoList []mo.HostSystem\n\tvar hostRefs []types.ManagedObjectReference\n\tfor _, vmo := range vmoList {\n\t\tif vmo.Summary.Runtime.Host == nil {\n\t\t\tmsg := fmt.Sprintf(\"SharedHost.getNodeHosts: no host associated with vm %s\", vmo.Name)\n\t\t\tklog.Error(msg)\n\t\t\treturn nil, fmt.Errorf(msg)\n\t\t}\n\t\thostRefs = append(hostRefs, vmo.Summary.Runtime.Host.Reference())\n\t}\n\tpc = property.DefaultCollector(nodeInfo.dataCenter.Client())\n\terr = pc.Retrieve(ctx, hostRefs, []string{summary}, \u0026hostMoList)\n\tif err != nil {\n\t\tklog.Errorf(\"SharedHost.getNodeHosts: unable to fetch hosts from datacenter %s: %v\", nodeInfo.dataCenter.String(), err)\n\t\treturn nil, err\n\t}\n\tvar hosts []hostInfo\n\tfor _, host := range hostMoList {\n\t\thosts = append(hosts, hostInfo{hostMOID: host.Summary.Host.String(), hostUUID: host.Summary.Hardware.Uuid, datacenter: nodeInfo.dataCenter.String()})\n\t}\n\treturn hosts, nil\n}","line":{"from":143,"to":181}} {"id":100034515,"name":"getAttachedHosts","signature":"func (shared *sharedDatastore) getAttachedHosts(ctx context.Context, datastore *vclib.Datastore) ([]hostInfo, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/shared_datastore.go","code":"func (shared *sharedDatastore) getAttachedHosts(ctx context.Context, datastore *vclib.Datastore) ([]hostInfo, error) {\n\tvar ds mo.Datastore\n\n\tpc := property.DefaultCollector(datastore.Client())\n\terr := pc.RetrieveOne(ctx, datastore.Reference(), []string{hostsProperty}, \u0026ds)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmounts := make(map[types.ManagedObjectReference]types.DatastoreHostMount)\n\tvar refs []types.ManagedObjectReference\n\tfor _, host := range ds.Host {\n\t\trefs = append(refs, host.Key)\n\t\tmounts[host.Key] = host\n\t}\n\n\tvar hs []mo.HostSystem\n\terr = pc.Retrieve(ctx, refs, []string{summary}, \u0026hs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar hosts []hostInfo\n\tfor _, h := range hs {\n\t\thosts = append(hosts, hostInfo{hostUUID: h.Summary.Hardware.Uuid, hostMOID: h.Summary.Host.String()})\n\t}\n\treturn hosts, nil\n\n}","line":{"from":183,"to":210}} {"id":100034516,"name":"Connect","signature":"func (connection *VSphereConnection) Connect(ctx context.Context) error","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/connection.go","code":"// Connect makes connection to vCenter and sets VSphereConnection.Client.\n// If connection.Client is already set, it obtains the existing user session.\n// if user session is not valid, connection.Client will be set to the new client.\nfunc (connection *VSphereConnection) Connect(ctx context.Context) error {\n\tvar err error\n\tclientLock.Lock()\n\tdefer clientLock.Unlock()\n\n\tif connection.Client == nil {\n\t\tconnection.Client, err = connection.NewClient(ctx)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to create govmomi client. err: %+v\", err)\n\t\t\treturn err\n\t\t}\n\t\tsetVCenterInfoMetric(connection)\n\t\treturn nil\n\t}\n\tm := session.NewManager(connection.Client)\n\tuserSession, err := m.UserSession(ctx)\n\tif err != nil {\n\t\tklog.Errorf(\"Error while obtaining user session. err: %+v\", err)\n\t\treturn err\n\t}\n\tif userSession != nil {\n\t\treturn nil\n\t}\n\tklog.Warningf(\"Creating new client session since the existing session is not valid or not authenticated\")\n\n\tconnection.Client, err = connection.NewClient(ctx)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to create govmomi client. err: %+v\", err)\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":54,"to":88}} {"id":100034517,"name":"Signer","signature":"func (connection *VSphereConnection) Signer(ctx context.Context, client *vim25.Client) (*sts.Signer, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/connection.go","code":"// Signer returns an sts.Signer for use with SAML token auth if connection is configured for such.\n// Returns nil if username/password auth is configured for the connection.\nfunc (connection *VSphereConnection) Signer(ctx context.Context, client *vim25.Client) (*sts.Signer, error) {\n\t// TODO: Add separate fields for certificate and private-key.\n\t// For now we can leave the config structs and validation as-is and\n\t// decide to use LoginByToken if the username value is PEM encoded.\n\tb, _ := pem.Decode([]byte(connection.Username))\n\tif b == nil {\n\t\treturn nil, nil\n\t}\n\n\tcert, err := tls.X509KeyPair([]byte(connection.Username), []byte(connection.Password))\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to load X509 key pair. err: %+v\", err)\n\t\treturn nil, err\n\t}\n\n\ttokens, err := sts.NewClient(ctx, client)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to create STS client. err: %+v\", err)\n\t\treturn nil, err\n\t}\n\n\treq := sts.TokenRequest{\n\t\tCertificate: \u0026cert,\n\t\tDelegatable: true,\n\t}\n\n\tsigner, err := tokens.Issue(ctx, req)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to issue SAML token. err: %+v\", err)\n\t\treturn nil, err\n\t}\n\n\treturn signer, nil\n}","line":{"from":90,"to":125}} {"id":100034518,"name":"login","signature":"func (connection *VSphereConnection) login(ctx context.Context, client *vim25.Client) error","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/connection.go","code":"// login calls SessionManager.LoginByToken if certificate and private key are configured,\n// otherwise calls SessionManager.Login with user and password.\nfunc (connection *VSphereConnection) login(ctx context.Context, client *vim25.Client) error {\n\tm := session.NewManager(client)\n\tconnection.credentialsLock.Lock()\n\tdefer connection.credentialsLock.Unlock()\n\n\tsigner, err := connection.Signer(ctx, client)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif signer == nil {\n\t\tklog.V(3).Infof(\"SessionManager.Login with username %q\", connection.Username)\n\t\treturn m.Login(ctx, neturl.UserPassword(connection.Username, connection.Password))\n\t}\n\n\tklog.V(3).Infof(\"SessionManager.LoginByToken with certificate %q\", connection.Username)\n\n\theader := soap.Header{Security: signer}\n\n\treturn m.LoginByToken(client.WithHeader(ctx, header))\n}","line":{"from":127,"to":149}} {"id":100034519,"name":"Logout","signature":"func (connection *VSphereConnection) Logout(ctx context.Context)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/connection.go","code":"// Logout calls SessionManager.Logout for the given connection.\nfunc (connection *VSphereConnection) Logout(ctx context.Context) {\n\tclientLock.Lock()\n\tc := connection.Client\n\tclientLock.Unlock()\n\tif c == nil {\n\t\treturn\n\t}\n\n\tm := session.NewManager(c)\n\n\thasActiveSession, err := m.SessionIsActive(ctx)\n\tif err != nil {\n\t\tklog.Errorf(\"Logout failed: %s\", err)\n\t\treturn\n\t}\n\tif !hasActiveSession {\n\t\tklog.Errorf(\"No active session, cannot logout\")\n\t\treturn\n\t}\n\tif err := m.Logout(ctx); err != nil {\n\t\tklog.Errorf(\"Logout failed: %s\", err)\n\t}\n}","line":{"from":151,"to":174}} {"id":100034520,"name":"NewClient","signature":"func (connection *VSphereConnection) NewClient(ctx context.Context) (*vim25.Client, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/connection.go","code":"// NewClient creates a new govmomi client for the VSphereConnection obj\nfunc (connection *VSphereConnection) NewClient(ctx context.Context) (*vim25.Client, error) {\n\turl, err := soap.ParseURL(net.JoinHostPort(connection.Hostname, connection.Port))\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to parse URL: %s. err: %+v\", url, err)\n\t\treturn nil, err\n\t}\n\n\tsc := soap.NewClient(url, connection.Insecure)\n\n\tif ca := connection.CACert; ca != \"\" {\n\t\tif err := sc.SetRootCAs(ca); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\ttpHost := connection.Hostname + \":\" + connection.Port\n\tsc.SetThumbprint(tpHost, connection.Thumbprint)\n\n\tclient, err := vim25.NewClient(ctx, sc)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to create new client. err: %+v\", err)\n\t\treturn nil, err\n\t}\n\n\tk8sVersion := version.Get().GitVersion\n\tclient.UserAgent = fmt.Sprintf(\"kubernetes-cloudprovider/%s\", k8sVersion)\n\n\terr = connection.login(ctx, client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tklogV := klog.V(3)\n\tif klogV.Enabled() {\n\t\ts, err := session.NewManager(client).UserSession(ctx)\n\t\tif err == nil {\n\t\t\tklogV.Infof(\"New session ID for '%s' = %s\", s.UserName, s.Key)\n\t\t}\n\t}\n\n\tif connection.RoundTripperCount == 0 {\n\t\tconnection.RoundTripperCount = RoundTripperDefaultCount\n\t}\n\tclient.RoundTripper = vim25.Retry(client.RoundTripper, vim25.TemporaryNetworkError(int(connection.RoundTripperCount)))\n\tvcNotSupported, err := isvCenterNotSupported(client.ServiceContent.About.Version, client.ServiceContent.About.ApiVersion)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to check if vCenter version:%v and api version: %s is supported or not. Error: %v\", client.ServiceContent.About.Version, client.ServiceContent.About.ApiVersion, err)\n\t}\n\tif vcNotSupported {\n\t\tklog.Warningf(\"vCenter version (version: %q, api verson: %q) is not supported for CSI Migration. Please consider upgrading vCenter and ESXi servers to 7.0u2 or higher for migrating vSphere volumes to CSI.\", client.ServiceContent.About.Version, client.ServiceContent.About.ApiVersion)\n\t}\n\treturn client, nil\n}","line":{"from":176,"to":228}} {"id":100034521,"name":"UpdateCredentials","signature":"func (connection *VSphereConnection) UpdateCredentials(username string, password string)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/connection.go","code":"// UpdateCredentials updates username and password.\n// Note: Updated username and password will be used when there is no session active\nfunc (connection *VSphereConnection) UpdateCredentials(username string, password string) {\n\tconnection.credentialsLock.Lock()\n\tdefer connection.credentialsLock.Unlock()\n\tconnection.Username = username\n\tconnection.Password = password\n}","line":{"from":230,"to":237}} {"id":100034522,"name":"GetDatacenter","signature":"func GetDatacenter(ctx context.Context, connection *VSphereConnection, datacenterPath string) (*Datacenter, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/datacenter.go","code":"// GetDatacenter returns the DataCenter Object for the given datacenterPath\n// If datacenter is located in a folder, include full path to datacenter else just provide the datacenter name\nfunc GetDatacenter(ctx context.Context, connection *VSphereConnection, datacenterPath string) (*Datacenter, error) {\n\tfinder := find.NewFinder(connection.Client, false)\n\tdatacenter, err := finder.Datacenter(ctx, datacenterPath)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to find the datacenter: %s. err: %+v\", datacenterPath, err)\n\t\treturn nil, err\n\t}\n\tdc := Datacenter{datacenter}\n\treturn \u0026dc, nil\n}","line":{"from":39,"to":50}} {"id":100034523,"name":"GetAllDatacenter","signature":"func GetAllDatacenter(ctx context.Context, connection *VSphereConnection) ([]*Datacenter, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/datacenter.go","code":"// GetAllDatacenter returns all the DataCenter Objects\nfunc GetAllDatacenter(ctx context.Context, connection *VSphereConnection) ([]*Datacenter, error) {\n\tvar dc []*Datacenter\n\tfinder := find.NewFinder(connection.Client, false)\n\tdatacenters, err := finder.DatacenterList(ctx, \"*\")\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to find the datacenter. err: %+v\", err)\n\t\treturn nil, err\n\t}\n\tfor _, datacenter := range datacenters {\n\t\tdc = append(dc, \u0026(Datacenter{datacenter}))\n\t}\n\n\treturn dc, nil\n}","line":{"from":52,"to":66}} {"id":100034524,"name":"GetVMByUUID","signature":"func (dc *Datacenter) GetVMByUUID(ctx context.Context, vmUUID string) (*VirtualMachine, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/datacenter.go","code":"// GetVMByUUID gets the VM object from the given vmUUID\nfunc (dc *Datacenter) GetVMByUUID(ctx context.Context, vmUUID string) (*VirtualMachine, error) {\n\ts := object.NewSearchIndex(dc.Client())\n\tvmUUID = strings.ToLower(strings.TrimSpace(vmUUID))\n\tsvm, err := s.FindByUuid(ctx, dc.Datacenter, vmUUID, true, nil)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to find VM by UUID. VM UUID: %s, err: %+v\", vmUUID, err)\n\t\treturn nil, err\n\t}\n\tif svm == nil {\n\t\tklog.Errorf(\"Unable to find VM by UUID. VM UUID: %s\", vmUUID)\n\t\treturn nil, ErrNoVMFound\n\t}\n\tvirtualMachine := VirtualMachine{object.NewVirtualMachine(dc.Client(), svm.Reference()), dc}\n\treturn \u0026virtualMachine, nil\n}","line":{"from":68,"to":83}} {"id":100034525,"name":"GetHostByVMUUID","signature":"func (dc *Datacenter) GetHostByVMUUID(ctx context.Context, vmUUID string) (*types.ManagedObjectReference, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/datacenter.go","code":"// GetHostByVMUUID gets the host object from the given vmUUID\nfunc (dc *Datacenter) GetHostByVMUUID(ctx context.Context, vmUUID string) (*types.ManagedObjectReference, error) {\n\tvirtualMachine, err := dc.GetVMByUUID(ctx, vmUUID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar vmMo mo.VirtualMachine\n\tpc := property.DefaultCollector(virtualMachine.Client())\n\terr = pc.RetrieveOne(ctx, virtualMachine.Reference(), []string{\"summary.runtime.host\"}, \u0026vmMo)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to retrieve VM runtime host, err: %v\", err)\n\t\treturn nil, err\n\t}\n\thost := vmMo.Summary.Runtime.Host\n\tklog.Infof(\"%s host is %s\", virtualMachine.Reference(), host)\n\treturn host, nil\n}","line":{"from":85,"to":101}} {"id":100034526,"name":"GetVMByPath","signature":"func (dc *Datacenter) GetVMByPath(ctx context.Context, vmPath string) (*VirtualMachine, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/datacenter.go","code":"// GetVMByPath gets the VM object from the given vmPath\n// vmPath should be the full path to VM and not just the name\nfunc (dc *Datacenter) GetVMByPath(ctx context.Context, vmPath string) (*VirtualMachine, error) {\n\tfinder := getFinder(dc)\n\tvm, err := finder.VirtualMachine(ctx, vmPath)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to find VM by Path. VM Path: %s, err: %+v\", vmPath, err)\n\t\treturn nil, err\n\t}\n\tvirtualMachine := VirtualMachine{vm, dc}\n\treturn \u0026virtualMachine, nil\n}","line":{"from":103,"to":114}} {"id":100034527,"name":"GetAllDatastores","signature":"func (dc *Datacenter) GetAllDatastores(ctx context.Context) (map[string]*DatastoreInfo, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/datacenter.go","code":"// GetAllDatastores gets the datastore URL to DatastoreInfo map for all the datastores in\n// the datacenter.\nfunc (dc *Datacenter) GetAllDatastores(ctx context.Context) (map[string]*DatastoreInfo, error) {\n\tfinder := getFinder(dc)\n\tdatastores, err := finder.DatastoreList(ctx, \"*\")\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get all the datastores. err: %+v\", err)\n\t\treturn nil, err\n\t}\n\tvar dsList []types.ManagedObjectReference\n\tfor _, ds := range datastores {\n\t\tdsList = append(dsList, ds.Reference())\n\t}\n\n\tvar dsMoList []mo.Datastore\n\tpc := property.DefaultCollector(dc.Client())\n\tproperties := []string{DatastoreInfoProperty}\n\terr = pc.Retrieve(ctx, dsList, properties, \u0026dsMoList)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get Datastore managed objects from datastore objects.\"+\n\t\t\t\" dsObjList: %+v, properties: %+v, err: %v\", dsList, properties, err)\n\t\treturn nil, err\n\t}\n\n\tdsURLInfoMap := make(map[string]*DatastoreInfo)\n\tfor _, dsMo := range dsMoList {\n\t\tdsURLInfoMap[dsMo.Info.GetDatastoreInfo().Url] = \u0026DatastoreInfo{\n\t\t\t\u0026Datastore{object.NewDatastore(dc.Client(), dsMo.Reference()),\n\t\t\t\tdc},\n\t\t\tdsMo.Info.GetDatastoreInfo()}\n\t}\n\tklog.V(9).Infof(\"dsURLInfoMap : %+v\", dsURLInfoMap)\n\treturn dsURLInfoMap, nil\n}","line":{"from":116,"to":149}} {"id":100034528,"name":"GetAllHosts","signature":"func (dc *Datacenter) GetAllHosts(ctx context.Context) ([]types.ManagedObjectReference, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/datacenter.go","code":"// GetAllHosts returns all the host objects in this datacenter of VC\nfunc (dc *Datacenter) GetAllHosts(ctx context.Context) ([]types.ManagedObjectReference, error) {\n\tfinder := getFinder(dc)\n\thostSystems, err := finder.HostSystemList(ctx, \"*\")\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get all hostSystems. err: %+v\", err)\n\t\treturn nil, err\n\t}\n\tvar hostMors []types.ManagedObjectReference\n\tfor _, hs := range hostSystems {\n\t\thostMors = append(hostMors, hs.Reference())\n\t}\n\treturn hostMors, nil\n}","line":{"from":151,"to":164}} {"id":100034529,"name":"GetDatastoreByPath","signature":"func (dc *Datacenter) GetDatastoreByPath(ctx context.Context, vmDiskPath string) (*Datastore, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/datacenter.go","code":"// GetDatastoreByPath gets the Datastore object from the given vmDiskPath\nfunc (dc *Datacenter) GetDatastoreByPath(ctx context.Context, vmDiskPath string) (*Datastore, error) {\n\tdatastorePathObj := new(object.DatastorePath)\n\tisSuccess := datastorePathObj.FromString(vmDiskPath)\n\tif !isSuccess {\n\t\tklog.Errorf(\"Failed to parse vmDiskPath: %s\", vmDiskPath)\n\t\treturn nil, errors.New(\"Failed to parse vmDiskPath\")\n\t}\n\n\treturn dc.GetDatastoreByName(ctx, datastorePathObj.Datastore)\n}","line":{"from":166,"to":176}} {"id":100034530,"name":"GetDatastoreByName","signature":"func (dc *Datacenter) GetDatastoreByName(ctx context.Context, name string) (*Datastore, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/datacenter.go","code":"// GetDatastoreByName gets the Datastore object for the given datastore name\nfunc (dc *Datacenter) GetDatastoreByName(ctx context.Context, name string) (*Datastore, error) {\n\tfinder := getFinder(dc)\n\tds, err := finder.Datastore(ctx, name)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed while searching for datastore: %s. err: %+v\", name, err)\n\t\treturn nil, err\n\t}\n\tdatastore := Datastore{ds, dc}\n\treturn \u0026datastore, nil\n}","line":{"from":178,"to":188}} {"id":100034531,"name":"GetDatastoreInfoByName","signature":"func (dc *Datacenter) GetDatastoreInfoByName(ctx context.Context, name string) (*DatastoreInfo, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/datacenter.go","code":"// GetDatastoreInfoByName gets the Datastore object for the given datastore name\nfunc (dc *Datacenter) GetDatastoreInfoByName(ctx context.Context, name string) (*DatastoreInfo, error) {\n\tfinder := getFinder(dc)\n\tds, err := finder.Datastore(ctx, name)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed while searching for datastore: %s. err: %+v\", name, err)\n\t\treturn nil, err\n\t}\n\tdatastore := Datastore{ds, dc}\n\tvar dsMo mo.Datastore\n\tpc := property.DefaultCollector(dc.Client())\n\tproperties := []string{DatastoreInfoProperty}\n\terr = pc.RetrieveOne(ctx, ds.Reference(), properties, \u0026dsMo)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get Datastore managed objects from datastore reference.\"+\n\t\t\t\" dsRef: %+v, err: %+v\", ds.Reference(), err)\n\t\treturn nil, err\n\t}\n\tklog.V(9).Infof(\"Result dsMo: %+v\", dsMo)\n\treturn \u0026DatastoreInfo{Datastore: \u0026datastore, Info: dsMo.Info.GetDatastoreInfo()}, nil\n}","line":{"from":190,"to":210}} {"id":100034532,"name":"GetResourcePool","signature":"func (dc *Datacenter) GetResourcePool(ctx context.Context, resourcePoolPath string) (*object.ResourcePool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/datacenter.go","code":"// GetResourcePool gets the resource pool for the given path\nfunc (dc *Datacenter) GetResourcePool(ctx context.Context, resourcePoolPath string) (*object.ResourcePool, error) {\n\tfinder := getFinder(dc)\n\tvar resourcePool *object.ResourcePool\n\tvar err error\n\tresourcePool, err = finder.ResourcePoolOrDefault(ctx, resourcePoolPath)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get the ResourcePool for path '%s'. err: %+v\", resourcePoolPath, err)\n\t\treturn nil, err\n\t}\n\treturn resourcePool, nil\n}","line":{"from":212,"to":223}} {"id":100034533,"name":"GetFolderByPath","signature":"func (dc *Datacenter) GetFolderByPath(ctx context.Context, folderPath string) (*Folder, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/datacenter.go","code":"// GetFolderByPath gets the Folder Object from the given folder path\n// folderPath should be the full path to folder\nfunc (dc *Datacenter) GetFolderByPath(ctx context.Context, folderPath string) (*Folder, error) {\n\tfinder := getFinder(dc)\n\tvmFolder, err := finder.Folder(ctx, folderPath)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get the folder reference for %s. err: %+v\", folderPath, err)\n\t\treturn nil, err\n\t}\n\tfolder := Folder{vmFolder, dc}\n\treturn \u0026folder, nil\n}","line":{"from":225,"to":236}} {"id":100034534,"name":"GetVMMoList","signature":"func (dc *Datacenter) GetVMMoList(ctx context.Context, vmObjList []*VirtualMachine, properties []string) ([]mo.VirtualMachine, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/datacenter.go","code":"// GetVMMoList gets the VM Managed Objects with the given properties from the VM object\nfunc (dc *Datacenter) GetVMMoList(ctx context.Context, vmObjList []*VirtualMachine, properties []string) ([]mo.VirtualMachine, error) {\n\tvar vmMoList []mo.VirtualMachine\n\tvar vmRefs []types.ManagedObjectReference\n\tif len(vmObjList) \u003c 1 {\n\t\tklog.Errorf(\"VirtualMachine Object list is empty\")\n\t\treturn nil, fmt.Errorf(\"VirtualMachine Object list is empty\")\n\t}\n\n\tfor _, vmObj := range vmObjList {\n\t\tvmRefs = append(vmRefs, vmObj.Reference())\n\t}\n\tpc := property.DefaultCollector(dc.Client())\n\terr := pc.Retrieve(ctx, vmRefs, properties, \u0026vmMoList)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get VM managed objects from VM objects. vmObjList: %+v, properties: %+v, err: %v\", vmObjList, properties, err)\n\t\treturn nil, err\n\t}\n\treturn vmMoList, nil\n}","line":{"from":238,"to":257}} {"id":100034535,"name":"GetVirtualDiskPage83Data","signature":"func (dc *Datacenter) GetVirtualDiskPage83Data(ctx context.Context, diskPath string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/datacenter.go","code":"// GetVirtualDiskPage83Data gets the virtual disk UUID by diskPath\nfunc (dc *Datacenter) GetVirtualDiskPage83Data(ctx context.Context, diskPath string) (string, error) {\n\tif len(diskPath) \u003e 0 \u0026\u0026 filepath.Ext(diskPath) != \".vmdk\" {\n\t\tdiskPath += \".vmdk\"\n\t}\n\tvdm := object.NewVirtualDiskManager(dc.Client())\n\t// Returns uuid of vmdk virtual disk\n\tdiskUUID, err := vdm.QueryVirtualDiskUuid(ctx, diskPath, dc.Datacenter)\n\n\tif err != nil {\n\t\tklog.Warningf(\"QueryVirtualDiskUuid failed for diskPath: %q. err: %+v\", diskPath, err)\n\t\treturn \"\", err\n\t}\n\tdiskUUID = formatVirtualDiskUUID(diskUUID)\n\treturn diskUUID, nil\n}","line":{"from":259,"to":274}} {"id":100034536,"name":"GetDatastoreMoList","signature":"func (dc *Datacenter) GetDatastoreMoList(ctx context.Context, dsObjList []*Datastore, properties []string) ([]mo.Datastore, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/datacenter.go","code":"// GetDatastoreMoList gets the Datastore Managed Objects with the given properties from the datastore objects\nfunc (dc *Datacenter) GetDatastoreMoList(ctx context.Context, dsObjList []*Datastore, properties []string) ([]mo.Datastore, error) {\n\tvar dsMoList []mo.Datastore\n\tvar dsRefs []types.ManagedObjectReference\n\tif len(dsObjList) \u003c 1 {\n\t\tklog.Errorf(\"Datastore Object list is empty\")\n\t\treturn nil, fmt.Errorf(\"Datastore Object list is empty\")\n\t}\n\n\tfor _, dsObj := range dsObjList {\n\t\tdsRefs = append(dsRefs, dsObj.Reference())\n\t}\n\tpc := property.DefaultCollector(dc.Client())\n\terr := pc.Retrieve(ctx, dsRefs, properties, \u0026dsMoList)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get Datastore managed objects from datastore objects. dsObjList: %+v, properties: %+v, err: %v\", dsObjList, properties, err)\n\t\treturn nil, err\n\t}\n\treturn dsMoList, nil\n}","line":{"from":276,"to":295}} {"id":100034537,"name":"CheckDisksAttached","signature":"func (dc *Datacenter) CheckDisksAttached(ctx context.Context, nodeVolumes map[string][]string) (map[string]map[string]bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/datacenter.go","code":"// CheckDisksAttached checks if the disk is attached to node.\n// This is done by comparing the volume path with the backing.FilePath on the VM Virtual disk devices.\nfunc (dc *Datacenter) CheckDisksAttached(ctx context.Context, nodeVolumes map[string][]string) (map[string]map[string]bool, error) {\n\tattached := make(map[string]map[string]bool)\n\tvar vmList []*VirtualMachine\n\tfor nodeName, volPaths := range nodeVolumes {\n\t\tfor _, volPath := range volPaths {\n\t\t\tsetNodeVolumeMap(attached, volPath, nodeName, false)\n\t\t}\n\t\tvm, err := dc.GetVMByPath(ctx, nodeName)\n\t\tif err != nil {\n\t\t\tif IsNotFound(err) {\n\t\t\t\tklog.Warningf(\"Node %q does not exist, vSphere CP will assume disks %v are not attached to it.\", nodeName, volPaths)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tvmList = append(vmList, vm)\n\t}\n\tif len(vmList) == 0 {\n\t\tklog.V(2).Infof(\"vSphere CP will assume no disks are attached to any node.\")\n\t\treturn attached, nil\n\t}\n\tvmMoList, err := dc.GetVMMoList(ctx, vmList, []string{\"config.hardware.device\", \"name\"})\n\tif err != nil {\n\t\t// When there is an error fetching instance information\n\t\t// it is safer to return nil and let volume information not be touched.\n\t\tklog.Errorf(\"Failed to get VM Managed object for nodes: %+v. err: +%v\", vmList, err)\n\t\treturn nil, err\n\t}\n\n\tfor _, vmMo := range vmMoList {\n\t\tif vmMo.Config == nil {\n\t\t\tklog.Errorf(\"Config is not available for VM: %q\", vmMo.Name)\n\t\t\tcontinue\n\t\t}\n\t\tfor nodeName, volPaths := range nodeVolumes {\n\t\t\tif nodeName == vmMo.Name {\n\t\t\t\tverifyVolumePathsForVM(vmMo, volPaths, attached)\n\t\t\t}\n\t\t}\n\t}\n\treturn attached, nil\n}","line":{"from":297,"to":339}} {"id":100034538,"name":"verifyVolumePathsForVM","signature":"func verifyVolumePathsForVM(vmMo mo.VirtualMachine, volPaths []string, nodeVolumeMap map[string]map[string]bool)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/datacenter.go","code":"// VerifyVolumePathsForVM verifies if the volume paths (volPaths) are attached to VM.\nfunc verifyVolumePathsForVM(vmMo mo.VirtualMachine, volPaths []string, nodeVolumeMap map[string]map[string]bool) {\n\t// Verify if the volume paths are present on the VM backing virtual disk devices\n\tfor _, volPath := range volPaths {\n\t\tvmDevices := object.VirtualDeviceList(vmMo.Config.Hardware.Device)\n\t\tfor _, device := range vmDevices {\n\t\t\tif vmDevices.TypeName(device) == \"VirtualDisk\" {\n\t\t\t\tvirtualDevice := device.GetVirtualDevice()\n\t\t\t\tif backing, ok := virtualDevice.Backing.(*types.VirtualDiskFlatVer2BackingInfo); ok {\n\t\t\t\t\tif backing.FileName == volPath {\n\t\t\t\t\t\tsetNodeVolumeMap(nodeVolumeMap, volPath, vmMo.Name, true)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":341,"to":357}} {"id":100034539,"name":"setNodeVolumeMap","signature":"func setNodeVolumeMap(","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/datacenter.go","code":"func setNodeVolumeMap(\n\tnodeVolumeMap map[string]map[string]bool,\n\tvolumePath string,\n\tnodeName string,\n\tcheck bool) {\n\tvolumeMap := nodeVolumeMap[nodeName]\n\tif volumeMap == nil {\n\t\tvolumeMap = make(map[string]bool)\n\t\tnodeVolumeMap[nodeName] = volumeMap\n\t}\n\tvolumeMap[volumePath] = check\n}","line":{"from":359,"to":370}} {"id":100034540,"name":"String","signature":"func (di DatastoreInfo) String() string","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/datastore.go","code":"func (di DatastoreInfo) String() string {\n\treturn fmt.Sprintf(\"Datastore: %+v, datastore URL: %s\", di.Datastore, di.Info.Url)\n}","line":{"from":43,"to":45}} {"id":100034541,"name":"CreateDirectory","signature":"func (ds *Datastore) CreateDirectory(ctx context.Context, directoryPath string, createParents bool) error","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/datastore.go","code":"// CreateDirectory creates the directory at location specified by directoryPath.\n// If the intermediate level folders do not exist, and the parameter createParents is true, all the non-existent folders are created.\n// directoryPath must be in the format \"[vsanDatastore] kubevols\"\nfunc (ds *Datastore) CreateDirectory(ctx context.Context, directoryPath string, createParents bool) error {\n\tfileManager := object.NewFileManager(ds.Client())\n\terr := fileManager.MakeDirectory(ctx, directoryPath, ds.Datacenter.Datacenter, createParents)\n\tif err != nil {\n\t\tif soap.IsSoapFault(err) {\n\t\t\tsoapFault := soap.ToSoapFault(err)\n\t\t\tif _, ok := soapFault.VimFault().(types.FileAlreadyExists); ok {\n\t\t\t\treturn ErrFileAlreadyExist\n\t\t\t}\n\t\t}\n\t\treturn err\n\t}\n\tklog.V(LogLevel).Infof(\"Created dir with path as %+q\", directoryPath)\n\treturn nil\n}","line":{"from":47,"to":64}} {"id":100034542,"name":"GetType","signature":"func (ds *Datastore) GetType(ctx context.Context) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/datastore.go","code":"// GetType returns the type of datastore\nfunc (ds *Datastore) GetType(ctx context.Context) (string, error) {\n\tvar dsMo mo.Datastore\n\tpc := property.DefaultCollector(ds.Client())\n\terr := pc.RetrieveOne(ctx, ds.Datastore.Reference(), []string{\"summary\"}, \u0026dsMo)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to retrieve datastore summary property. err: %v\", err)\n\t\treturn \"\", err\n\t}\n\treturn dsMo.Summary.Type, nil\n}","line":{"from":66,"to":76}} {"id":100034543,"name":"IsCompatibleWithStoragePolicy","signature":"func (ds *Datastore) IsCompatibleWithStoragePolicy(ctx context.Context, storagePolicyID string) (bool, string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/datastore.go","code":"// IsCompatibleWithStoragePolicy returns true if datastore is compatible with given storage policy else return false\n// for not compatible datastore, fault message is also returned\nfunc (ds *Datastore) IsCompatibleWithStoragePolicy(ctx context.Context, storagePolicyID string) (bool, string, error) {\n\tpbmClient, err := NewPbmClient(ctx, ds.Client())\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get new PbmClient Object. err: %v\", err)\n\t\treturn false, \"\", err\n\t}\n\treturn pbmClient.IsDatastoreCompatible(ctx, storagePolicyID, ds)\n}","line":{"from":78,"to":87}} {"id":100034544,"name":"GetDatastoreHostMounts","signature":"func (ds *Datastore) GetDatastoreHostMounts(ctx context.Context) ([]types.ManagedObjectReference, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/datastore.go","code":"// GetDatastoreHostMounts gets the host names mounted on given datastore\nfunc (ds *Datastore) GetDatastoreHostMounts(ctx context.Context) ([]types.ManagedObjectReference, error) {\n\tvar dsMo mo.Datastore\n\tpc := property.DefaultCollector(ds.Client())\n\terr := pc.RetrieveOne(ctx, ds.Datastore.Reference(), []string{\"host\"}, \u0026dsMo)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to retrieve datastore host mount property. err: %v\", err)\n\t\treturn nil, err\n\t}\n\thosts := make([]types.ManagedObjectReference, len(dsMo.Host))\n\tfor i, dsHostMount := range dsMo.Host {\n\t\thosts[i] = dsHostMount.Key\n\t}\n\treturn hosts, nil\n}","line":{"from":89,"to":103}} {"id":100034545,"name":"Exists","signature":"func (ds *Datastore) Exists(ctx context.Context, file string) bool","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/datastore.go","code":"// Exists returns whether the given file exists in this datastore\nfunc (ds *Datastore) Exists(ctx context.Context, file string) bool {\n\t_, err := ds.Datastore.Stat(ctx, file)\n\treturn err == nil\n}","line":{"from":105,"to":109}} {"id":100034546,"name":"Create","signature":"func (diskManager virtualDiskManager) Create(ctx context.Context, datastore *vclib.Datastore) (canonicalDiskPath string, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/diskmanagers/vdm.go","code":"// Create implements Disk's Create interface\n// Contains implementation of virtualDiskManager based Provisioning\nfunc (diskManager virtualDiskManager) Create(ctx context.Context, datastore *vclib.Datastore) (canonicalDiskPath string, err error) {\n\tif diskManager.volumeOptions.SCSIControllerType == \"\" {\n\t\tdiskManager.volumeOptions.SCSIControllerType = vclib.LSILogicControllerType\n\t}\n\n\t// Check for existing VMDK before attempting create. Because a name collision\n\t// is unlikely, \"VMDK already exists\" is likely from a previous attempt to\n\t// create this volume.\n\tif dsPath := vclib.GetPathFromVMDiskPath(diskManager.diskPath); datastore.Exists(ctx, dsPath) {\n\t\tklog.V(2).Infof(\"Create: VirtualDisk already exists, returning success. Name=%q\", diskManager.diskPath)\n\t\treturn diskManager.diskPath, nil\n\t}\n\n\t// Create specification for new virtual disk\n\tdiskFormat := vclib.DiskFormatValidType[diskManager.volumeOptions.DiskFormat]\n\tvmDiskSpec := \u0026types.FileBackedVirtualDiskSpec{\n\t\tVirtualDiskSpec: types.VirtualDiskSpec{\n\t\t\tAdapterType: diskManager.volumeOptions.SCSIControllerType,\n\t\t\tDiskType: diskFormat,\n\t\t},\n\t\tCapacityKb: int64(diskManager.volumeOptions.CapacityKB),\n\t}\n\n\tvdm := object.NewVirtualDiskManager(datastore.Client())\n\trequestTime := time.Now()\n\t// Create virtual disk\n\ttask, err := vdm.CreateVirtualDisk(ctx, diskManager.diskPath, datastore.Datacenter.Datacenter, vmDiskSpec)\n\tif err != nil {\n\t\tvclib.RecordvSphereMetric(vclib.APICreateVolume, requestTime, err)\n\t\tklog.Errorf(\"Failed to create virtual disk: %s. err: %+v\", diskManager.diskPath, err)\n\t\treturn \"\", err\n\t}\n\ttaskInfo, err := task.WaitForResult(ctx, nil)\n\tvclib.RecordvSphereMetric(vclib.APICreateVolume, requestTime, err)\n\tif err != nil {\n\t\tif isAlreadyExists(diskManager.diskPath, err) {\n\t\t\t// The disk already exists, log info message and return success\n\t\t\tklog.V(vclib.LogLevel).Infof(\"File: %v already exists\", diskManager.diskPath)\n\t\t\treturn diskManager.diskPath, nil\n\t\t}\n\t\tklog.Errorf(\"Failed to complete virtual disk creation: %s. err: %+v\", diskManager.diskPath, err)\n\t\treturn \"\", err\n\t}\n\tcanonicalDiskPath = taskInfo.Result.(string)\n\treturn canonicalDiskPath, nil\n}","line":{"from":36,"to":83}} {"id":100034547,"name":"Delete","signature":"func (diskManager virtualDiskManager) Delete(ctx context.Context, datacenter *vclib.Datacenter) error","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/diskmanagers/vdm.go","code":"// Delete implements Disk's Delete interface\nfunc (diskManager virtualDiskManager) Delete(ctx context.Context, datacenter *vclib.Datacenter) error {\n\t// Create a virtual disk manager\n\tvirtualDiskManager := object.NewVirtualDiskManager(datacenter.Client())\n\tdiskPath := vclib.RemoveStorageClusterORFolderNameFromVDiskPath(diskManager.diskPath)\n\trequestTime := time.Now()\n\t// Delete virtual disk\n\ttask, err := virtualDiskManager.DeleteVirtualDisk(ctx, diskPath, datacenter.Datacenter)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to delete virtual disk. err: %v\", err)\n\t\tvclib.RecordvSphereMetric(vclib.APIDeleteVolume, requestTime, err)\n\t\treturn err\n\t}\n\terr = task.Wait(ctx)\n\tvclib.RecordvSphereMetric(vclib.APIDeleteVolume, requestTime, err)\n\tif err != nil \u0026\u0026 !types.IsFileNotFound(err) {\n\t\tklog.Errorf(\"Failed to delete virtual disk. err: %v\", err)\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":85,"to":105}} {"id":100034548,"name":"getDiskManager","signature":"func getDiskManager(disk *VirtualDisk, diskOperation string) VirtualDiskProvider","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/diskmanagers/virtualdisk.go","code":"// getDiskManager returns vmDiskManager or vdmDiskManager based on given volumeoptions\nfunc getDiskManager(disk *VirtualDisk, diskOperation string) VirtualDiskProvider {\n\tvar diskProvider VirtualDiskProvider\n\tswitch diskOperation {\n\tcase VirtualDiskDeleteOperation:\n\t\tdiskProvider = virtualDiskManager{disk.DiskPath, disk.VolumeOptions}\n\tcase VirtualDiskCreateOperation:\n\t\tif disk.VolumeOptions.StoragePolicyName != \"\" || disk.VolumeOptions.VSANStorageProfileData != \"\" || disk.VolumeOptions.StoragePolicyID != \"\" {\n\t\t\tdiskProvider = vmDiskManager{disk.DiskPath, disk.VolumeOptions, disk.VMOptions}\n\t\t} else {\n\t\t\tdiskProvider = virtualDiskManager{disk.DiskPath, disk.VolumeOptions}\n\t\t}\n\t}\n\treturn diskProvider\n}","line":{"from":46,"to":60}} {"id":100034549,"name":"Create","signature":"func (virtualDisk *VirtualDisk) Create(ctx context.Context, datastore *vclib.Datastore) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/diskmanagers/virtualdisk.go","code":"// Create gets appropriate disk manager and calls respective create method\nfunc (virtualDisk *VirtualDisk) Create(ctx context.Context, datastore *vclib.Datastore) (string, error) {\n\tif virtualDisk.VolumeOptions.DiskFormat == \"\" {\n\t\tvirtualDisk.VolumeOptions.DiskFormat = vclib.ThinDiskType\n\t}\n\tif err := virtualDisk.VolumeOptions.VerifyVolumeOptions(); err != nil {\n\t\tklog.Errorf(\"VolumeOptions verification failed: %s (options: %+v)\", err, virtualDisk.VolumeOptions)\n\t\treturn \"\", fmt.Errorf(\"validation of parameters failed: %s\", err)\n\t}\n\tif virtualDisk.VolumeOptions.StoragePolicyID != \"\" \u0026\u0026 virtualDisk.VolumeOptions.StoragePolicyName != \"\" {\n\t\treturn \"\", fmt.Errorf(\"Storage Policy ID and Storage Policy Name both set, Please set only one parameter\")\n\t}\n\treturn getDiskManager(virtualDisk, VirtualDiskCreateOperation).Create(ctx, datastore)\n}","line":{"from":62,"to":75}} {"id":100034550,"name":"Delete","signature":"func (virtualDisk *VirtualDisk) Delete(ctx context.Context, datacenter *vclib.Datacenter) error","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/diskmanagers/virtualdisk.go","code":"// Delete gets appropriate disk manager and calls respective delete method\nfunc (virtualDisk *VirtualDisk) Delete(ctx context.Context, datacenter *vclib.Datacenter) error {\n\treturn getDiskManager(virtualDisk, VirtualDiskDeleteOperation).Delete(ctx, datacenter)\n}","line":{"from":77,"to":80}} {"id":100034551,"name":"Create","signature":"func (vmdisk vmDiskManager) Create(ctx context.Context, datastore *vclib.Datastore) (canonicalDiskPath string, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/diskmanagers/vmdm.go","code":"// Create implements Disk's Create interface\n// Contains implementation of VM based Provisioning to provision disk with SPBM Policy or VSANStorageProfileData\nfunc (vmdisk vmDiskManager) Create(ctx context.Context, datastore *vclib.Datastore) (canonicalDiskPath string, err error) {\n\tif vmdisk.volumeOptions.SCSIControllerType == \"\" {\n\t\tvmdisk.volumeOptions.SCSIControllerType = vclib.PVSCSIControllerType\n\t}\n\tpbmClient, err := vclib.NewPbmClient(ctx, datastore.Client())\n\tif err != nil {\n\t\tklog.Errorf(\"error occurred while creating new pbmClient, err: %+v\", err)\n\t\treturn \"\", err\n\t}\n\n\tif vmdisk.volumeOptions.StoragePolicyID == \"\" \u0026\u0026 vmdisk.volumeOptions.StoragePolicyName != \"\" {\n\t\tvmdisk.volumeOptions.StoragePolicyID, err = pbmClient.ProfileIDByName(ctx, vmdisk.volumeOptions.StoragePolicyName)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"error occurred while getting Profile Id from Profile Name: %s, err: %+v\", vmdisk.volumeOptions.StoragePolicyName, err)\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\tif vmdisk.volumeOptions.StoragePolicyID != \"\" {\n\t\tcompatible, faultMessage, err := datastore.IsCompatibleWithStoragePolicy(ctx, vmdisk.volumeOptions.StoragePolicyID)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"error occurred while checking datastore compatibility with storage policy id: %s, err: %+v\", vmdisk.volumeOptions.StoragePolicyID, err)\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tif !compatible {\n\t\t\tklog.Errorf(\"Datastore: %s is not compatible with Policy: %s\", datastore.Name(), vmdisk.volumeOptions.StoragePolicyName)\n\t\t\treturn \"\", fmt.Errorf(\"user specified datastore is not compatible with the storagePolicy: %q. Failed with faults: %+q\", vmdisk.volumeOptions.StoragePolicyName, faultMessage)\n\t\t}\n\t}\n\n\tstorageProfileSpec := \u0026types.VirtualMachineDefinedProfileSpec{}\n\t// Is PBM storage policy ID is present, set the storage spec profile ID,\n\t// else, set raw the VSAN policy string.\n\tif vmdisk.volumeOptions.StoragePolicyID != \"\" {\n\t\tstorageProfileSpec.ProfileId = vmdisk.volumeOptions.StoragePolicyID\n\t} else if vmdisk.volumeOptions.VSANStorageProfileData != \"\" {\n\t\t// Check Datastore type - VSANStorageProfileData is only applicable to vSAN Datastore\n\t\tdsType, err := datastore.GetType(ctx)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif dsType != vclib.VSANDatastoreType {\n\t\t\tklog.Errorf(\"The specified datastore: %q is not a VSAN datastore\", datastore.Name())\n\t\t\treturn \"\", fmt.Errorf(\"the specified datastore: %q is not a VSAN datastore.\"+\n\t\t\t\t\" the policy parameters will work only with VSAN Datastore.\"+\n\t\t\t\t\" so, please specify a valid VSAN datastore in Storage class definition\", datastore.Name())\n\t\t}\n\t\tstorageProfileSpec.ProfileId = \"\"\n\t\tstorageProfileSpec.ProfileData = \u0026types.VirtualMachineProfileRawData{\n\t\t\tExtensionKey: \"com.vmware.vim.sps\",\n\t\t\tObjectData: vmdisk.volumeOptions.VSANStorageProfileData,\n\t\t}\n\t} else {\n\t\tklog.Errorf(\"Both volumeOptions.StoragePolicyID and volumeOptions.VSANStorageProfileData are not set. One of them should be set\")\n\t\treturn \"\", fmt.Errorf(\"both volumeOptions.StoragePolicyID and volumeOptions.VSANStorageProfileData are not set. One of them should be set\")\n\t}\n\tvar dummyVM *vclib.VirtualMachine\n\t// Check if VM already exist in the folder.\n\t// If VM is already present, use it, else create a new dummy VM.\n\tfnvHash := fnv.New32a()\n\tfnvHash.Write([]byte(vmdisk.volumeOptions.Name))\n\tdummyVMFullName := vclib.DummyVMPrefixName + \"-\" + fmt.Sprint(fnvHash.Sum32())\n\tdummyVM, err = datastore.Datacenter.GetVMByPath(ctx, vmdisk.vmOptions.VMFolder.InventoryPath+\"/\"+dummyVMFullName)\n\tif err != nil {\n\t\t// Create a dummy VM\n\t\tklog.V(1).Infof(\"Creating Dummy VM: %q\", dummyVMFullName)\n\t\tdummyVM, err = vmdisk.createDummyVM(ctx, datastore.Datacenter, dummyVMFullName)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"failed to create Dummy VM. err: %v\", err)\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\t// Reconfigure the VM to attach the disk with the VSAN policy configured\n\tvirtualMachineConfigSpec := types.VirtualMachineConfigSpec{}\n\tdisk, _, err := dummyVM.CreateDiskSpec(ctx, vmdisk.diskPath, datastore, vmdisk.volumeOptions)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to create Disk Spec. err: %v\", err)\n\t\treturn \"\", err\n\t}\n\tdeviceConfigSpec := \u0026types.VirtualDeviceConfigSpec{\n\t\tDevice: disk,\n\t\tOperation: types.VirtualDeviceConfigSpecOperationAdd,\n\t\tFileOperation: types.VirtualDeviceConfigSpecFileOperationCreate,\n\t}\n\n\tdeviceConfigSpec.Profile = append(deviceConfigSpec.Profile, storageProfileSpec)\n\tvirtualMachineConfigSpec.DeviceChange = append(virtualMachineConfigSpec.DeviceChange, deviceConfigSpec)\n\tfileAlreadyExist := false\n\ttask, err := dummyVM.Reconfigure(ctx, virtualMachineConfigSpec)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to reconfig. err: %v\", err)\n\t\treturn \"\", err\n\t}\n\terr = task.Wait(ctx)\n\tif err != nil {\n\t\tfileAlreadyExist = isAlreadyExists(vmdisk.diskPath, err)\n\t\tif fileAlreadyExist {\n\t\t\t//Skip error and continue to detach the disk as the disk was already created on the datastore.\n\t\t\tklog.V(vclib.LogLevel).Infof(\"File: %v already exists\", vmdisk.diskPath)\n\t\t} else {\n\t\t\tklog.Errorf(\"Failed to attach the disk to VM: %q with err: %+v\", dummyVMFullName, err)\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\t// Detach the disk from the dummy VM.\n\terr = dummyVM.DetachDisk(ctx, vmdisk.diskPath)\n\tif err != nil {\n\t\tif vclib.DiskNotFoundErrMsg == err.Error() \u0026\u0026 fileAlreadyExist {\n\t\t\t// Skip error if disk was already detached from the dummy VM but still present on the datastore.\n\t\t\tklog.V(vclib.LogLevel).Infof(\"File: %v is already detached\", vmdisk.diskPath)\n\t\t} else {\n\t\t\tklog.Errorf(\"Failed to detach the disk: %q from VM: %q with err: %+v\", vmdisk.diskPath, dummyVMFullName, err)\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\t// Delete the dummy VM\n\terr = dummyVM.DeleteVM(ctx)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to destroy the vm: %q with err: %+v\", dummyVMFullName, err)\n\t}\n\treturn vmdisk.diskPath, nil\n}","line":{"from":39,"to":163}} {"id":100034552,"name":"Delete","signature":"func (vmdisk vmDiskManager) Delete(ctx context.Context, datacenter *vclib.Datacenter) error","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/diskmanagers/vmdm.go","code":"func (vmdisk vmDiskManager) Delete(ctx context.Context, datacenter *vclib.Datacenter) error {\n\treturn fmt.Errorf(\"vmDiskManager.Delete is not supported\")\n}","line":{"from":165,"to":167}} {"id":100034553,"name":"createDummyVM","signature":"func (vmdisk vmDiskManager) createDummyVM(ctx context.Context, datacenter *vclib.Datacenter, vmName string) (*vclib.VirtualMachine, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/diskmanagers/vmdm.go","code":"// CreateDummyVM create a Dummy VM at specified location with given name.\nfunc (vmdisk vmDiskManager) createDummyVM(ctx context.Context, datacenter *vclib.Datacenter, vmName string) (*vclib.VirtualMachine, error) {\n\t// Create a virtual machine config spec with 1 SCSI adapter.\n\tvirtualMachineConfigSpec := types.VirtualMachineConfigSpec{\n\t\tName: vmName,\n\t\tFiles: \u0026types.VirtualMachineFileInfo{\n\t\t\tVmPathName: \"[\" + vmdisk.volumeOptions.Datastore + \"]\",\n\t\t},\n\t\tNumCPUs: 1,\n\t\tMemoryMB: 4,\n\t\tDeviceChange: []types.BaseVirtualDeviceConfigSpec{\n\t\t\t\u0026types.VirtualDeviceConfigSpec{\n\t\t\t\tOperation: types.VirtualDeviceConfigSpecOperationAdd,\n\t\t\t\tDevice: \u0026types.ParaVirtualSCSIController{\n\t\t\t\t\tVirtualSCSIController: types.VirtualSCSIController{\n\t\t\t\t\t\tSharedBus: types.VirtualSCSISharingNoSharing,\n\t\t\t\t\t\tVirtualController: types.VirtualController{\n\t\t\t\t\t\t\tBusNumber: 0,\n\t\t\t\t\t\t\tVirtualDevice: types.VirtualDevice{\n\t\t\t\t\t\t\t\tKey: 1000,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\ttask, err := vmdisk.vmOptions.VMFolder.CreateVM(ctx, virtualMachineConfigSpec, vmdisk.vmOptions.VMResourcePool, nil)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to create VM. err: %+v\", err)\n\t\treturn nil, err\n\t}\n\n\tdummyVMTaskInfo, err := task.WaitForResult(ctx, nil)\n\tif err != nil {\n\t\tklog.Errorf(\"Error occurred while waiting for create VM task result. err: %+v\", err)\n\t\treturn nil, err\n\t}\n\n\tvmRef := dummyVMTaskInfo.Result.(object.Reference)\n\tdummyVM := object.NewVirtualMachine(datacenter.Client(), vmRef.Reference())\n\treturn \u0026vclib.VirtualMachine{VirtualMachine: dummyVM, Datacenter: datacenter}, nil\n}","line":{"from":169,"to":212}} {"id":100034554,"name":"CleanUpDummyVMs","signature":"func CleanUpDummyVMs(ctx context.Context, folder *vclib.Folder) error","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/diskmanagers/vmdm.go","code":"// CleanUpDummyVMs deletes stale dummyVM's\nfunc CleanUpDummyVMs(ctx context.Context, folder *vclib.Folder) error {\n\tvmList, err := folder.GetVirtualMachines(ctx)\n\tif err != nil {\n\t\tklog.V(4).Infof(\"Failed to get virtual machines in the kubernetes cluster: %s, err: %+v\", folder.InventoryPath, err)\n\t\treturn err\n\t}\n\tif vmList == nil || len(vmList) == 0 {\n\t\tklog.Errorf(\"No virtual machines found in the kubernetes cluster: %s\", folder.InventoryPath)\n\t\treturn fmt.Errorf(\"no virtual machines found in the kubernetes cluster: %s\", folder.InventoryPath)\n\t}\n\tvar dummyVMList []*vclib.VirtualMachine\n\t// Loop through VM's in the Kubernetes cluster to find dummy VM's\n\tfor _, vm := range vmList {\n\t\tvmName, err := vm.ObjectName(ctx)\n\t\tif err != nil {\n\t\t\tklog.V(4).Infof(\"Unable to get name from VM with err: %+v\", err)\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasPrefix(vmName, vclib.DummyVMPrefixName) {\n\t\t\tvmObj := vclib.VirtualMachine{VirtualMachine: object.NewVirtualMachine(folder.Client(), vm.Reference())}\n\t\t\tdummyVMList = append(dummyVMList, \u0026vmObj)\n\t\t}\n\t}\n\tfor _, vm := range dummyVMList {\n\t\terr = vm.DeleteVM(ctx)\n\t\tif err != nil {\n\t\t\tklog.V(4).Infof(\"Unable to delete dummy VM with err: %+v\", err)\n\t\t\tcontinue\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":214,"to":246}} {"id":100034555,"name":"isAlreadyExists","signature":"func isAlreadyExists(path string, err error) bool","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/diskmanagers/vmdm.go","code":"func isAlreadyExists(path string, err error) bool {\n\terrorMessage := fmt.Sprintf(\"Cannot complete the operation because the file or folder %s already exists\", path)\n\tif errorMessage == err.Error() {\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":248,"to":254}} {"id":100034556,"name":"GetVirtualMachines","signature":"func (folder *Folder) GetVirtualMachines(ctx context.Context) ([]*VirtualMachine, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/folder.go","code":"// GetVirtualMachines returns list of VirtualMachine inside a folder.\nfunc (folder *Folder) GetVirtualMachines(ctx context.Context) ([]*VirtualMachine, error) {\n\tvmFolders, err := folder.Children(ctx)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get children from Folder: %s. err: %+v\", folder.InventoryPath, err)\n\t\treturn nil, err\n\t}\n\tvar vmObjList []*VirtualMachine\n\tfor _, vmFolder := range vmFolders {\n\t\tif vmFolder.Reference().Type == VirtualMachineType {\n\t\t\tvmObj := VirtualMachine{object.NewVirtualMachine(folder.Client(), vmFolder.Reference()), folder.Datacenter}\n\t\t\tvmObjList = append(vmObjList, \u0026vmObj)\n\t\t}\n\t}\n\treturn vmObjList, nil\n}","line":{"from":32,"to":47}} {"id":100034557,"name":"NewPbmClient","signature":"func NewPbmClient(ctx context.Context, client *vim25.Client) (*PbmClient, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/pbm.go","code":"// NewPbmClient returns a new PBM Client object\nfunc NewPbmClient(ctx context.Context, client *vim25.Client) (*PbmClient, error) {\n\tpbmClient, err := pbm.NewClient(ctx, client)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to create new Pbm Client. err: %+v\", err)\n\t\treturn nil, err\n\t}\n\treturn \u0026PbmClient{pbmClient}, nil\n}","line":{"from":35,"to":43}} {"id":100034558,"name":"IsDatastoreCompatible","signature":"func (pbmClient *PbmClient) IsDatastoreCompatible(ctx context.Context, storagePolicyID string, datastore *Datastore) (bool, string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/pbm.go","code":"// IsDatastoreCompatible check if the datastores is compatible for given storage policy id\n// if datastore is not compatible with policy, fault message with the Datastore Name is returned\nfunc (pbmClient *PbmClient) IsDatastoreCompatible(ctx context.Context, storagePolicyID string, datastore *Datastore) (bool, string, error) {\n\tfaultMessage := \"\"\n\tplacementHub := pbmtypes.PbmPlacementHub{\n\t\tHubType: datastore.Reference().Type,\n\t\tHubId: datastore.Reference().Value,\n\t}\n\thubs := []pbmtypes.PbmPlacementHub{placementHub}\n\treq := []pbmtypes.BasePbmPlacementRequirement{\n\t\t\u0026pbmtypes.PbmPlacementCapabilityProfileRequirement{\n\t\t\tProfileId: pbmtypes.PbmProfileId{\n\t\t\t\tUniqueId: storagePolicyID,\n\t\t\t},\n\t\t},\n\t}\n\tcompatibilityResult, err := pbmClient.CheckRequirements(ctx, hubs, nil, req)\n\tif err != nil {\n\t\tklog.Errorf(\"Error occurred for CheckRequirements call. err %+v\", err)\n\t\treturn false, \"\", err\n\t}\n\tif compatibilityResult != nil \u0026\u0026 len(compatibilityResult) \u003e 0 {\n\t\tcompatibleHubs := compatibilityResult.CompatibleDatastores()\n\t\tif compatibleHubs != nil \u0026\u0026 len(compatibleHubs) \u003e 0 {\n\t\t\treturn true, \"\", nil\n\t\t}\n\t\tdsName, err := datastore.ObjectName(ctx)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to get datastore ObjectName\")\n\t\t\treturn false, \"\", err\n\t\t}\n\t\tif compatibilityResult[0].Error[0].LocalizedMessage == \"\" {\n\t\t\tfaultMessage = \"Datastore: \" + dsName + \" is not compatible with the storage policy.\"\n\t\t} else {\n\t\t\tfaultMessage = \"Datastore: \" + dsName + \" is not compatible with the storage policy. LocalizedMessage: \" + compatibilityResult[0].Error[0].LocalizedMessage + \"\\n\"\n\t\t}\n\t\treturn false, faultMessage, nil\n\t}\n\treturn false, \"\", fmt.Errorf(\"compatibilityResult is nil or empty\")\n}","line":{"from":45,"to":84}} {"id":100034559,"name":"GetCompatibleDatastores","signature":"func (pbmClient *PbmClient) GetCompatibleDatastores(ctx context.Context, storagePolicyID string, datastores []*DatastoreInfo) ([]*DatastoreInfo, string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/pbm.go","code":"// GetCompatibleDatastores filters and returns compatible list of datastores for given storage policy id\n// For Non Compatible Datastores, fault message with the Datastore Name is also returned\nfunc (pbmClient *PbmClient) GetCompatibleDatastores(ctx context.Context, storagePolicyID string, datastores []*DatastoreInfo) ([]*DatastoreInfo, string, error) {\n\tvar (\n\t\tdsMorNameMap = getDsMorNameMap(ctx, datastores)\n\t\tlocalizedMessagesForNotCompatibleDatastores = \"\"\n\t)\n\tcompatibilityResult, err := pbmClient.GetPlacementCompatibilityResult(ctx, storagePolicyID, datastores)\n\tif err != nil {\n\t\tklog.Errorf(\"Error occurred while retrieving placement compatibility result for datastores: %+v with storagePolicyID: %s. err: %+v\", datastores, storagePolicyID, err)\n\t\treturn nil, \"\", err\n\t}\n\tcompatibleHubs := compatibilityResult.CompatibleDatastores()\n\tvar compatibleDatastoreList []*DatastoreInfo\n\tfor _, hub := range compatibleHubs {\n\t\tcompatibleDatastoreList = append(compatibleDatastoreList, getDatastoreFromPlacementHub(datastores, hub))\n\t}\n\tfor _, res := range compatibilityResult {\n\t\tfor _, err := range res.Error {\n\t\t\tdsName := dsMorNameMap[res.Hub.HubId]\n\t\t\tlocalizedMessage := \"\"\n\t\t\tif err.LocalizedMessage != \"\" {\n\t\t\t\tlocalizedMessage = \"Datastore: \" + dsName + \" not compatible with the storage policy. LocalizedMessage: \" + err.LocalizedMessage + \"\\n\"\n\t\t\t} else {\n\t\t\t\tlocalizedMessage = \"Datastore: \" + dsName + \" not compatible with the storage policy. \\n\"\n\t\t\t}\n\t\t\tlocalizedMessagesForNotCompatibleDatastores += localizedMessage\n\t\t}\n\t}\n\t// Return an error if there are no compatible datastores.\n\tif len(compatibleHubs) \u003c 1 {\n\t\tklog.Errorf(\"No compatible datastores found that satisfy the storage policy requirements: %s\", storagePolicyID)\n\t\treturn nil, localizedMessagesForNotCompatibleDatastores, fmt.Errorf(\"No compatible datastores found that satisfy the storage policy requirements\")\n\t}\n\treturn compatibleDatastoreList, localizedMessagesForNotCompatibleDatastores, nil\n}","line":{"from":86,"to":121}} {"id":100034560,"name":"GetPlacementCompatibilityResult","signature":"func (pbmClient *PbmClient) GetPlacementCompatibilityResult(ctx context.Context, storagePolicyID string, datastore []*DatastoreInfo) (pbm.PlacementCompatibilityResult, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/pbm.go","code":"// GetPlacementCompatibilityResult gets placement compatibility result based on storage policy requirements.\nfunc (pbmClient *PbmClient) GetPlacementCompatibilityResult(ctx context.Context, storagePolicyID string, datastore []*DatastoreInfo) (pbm.PlacementCompatibilityResult, error) {\n\tvar hubs []pbmtypes.PbmPlacementHub\n\tfor _, ds := range datastore {\n\t\thubs = append(hubs, pbmtypes.PbmPlacementHub{\n\t\t\tHubType: ds.Reference().Type,\n\t\t\tHubId: ds.Reference().Value,\n\t\t})\n\t}\n\treq := []pbmtypes.BasePbmPlacementRequirement{\n\t\t\u0026pbmtypes.PbmPlacementCapabilityProfileRequirement{\n\t\t\tProfileId: pbmtypes.PbmProfileId{\n\t\t\t\tUniqueId: storagePolicyID,\n\t\t\t},\n\t\t},\n\t}\n\tres, err := pbmClient.CheckRequirements(ctx, hubs, nil, req)\n\tif err != nil {\n\t\tklog.Errorf(\"Error occurred for CheckRequirements call. err: %+v\", err)\n\t\treturn nil, err\n\t}\n\treturn res, nil\n}","line":{"from":123,"to":145}} {"id":100034561,"name":"getDatastoreFromPlacementHub","signature":"func getDatastoreFromPlacementHub(datastore []*DatastoreInfo, pbmPlacementHub pbmtypes.PbmPlacementHub) *DatastoreInfo","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/pbm.go","code":"// getDataStoreForPlacementHub returns matching datastore associated with given pbmPlacementHub\nfunc getDatastoreFromPlacementHub(datastore []*DatastoreInfo, pbmPlacementHub pbmtypes.PbmPlacementHub) *DatastoreInfo {\n\tfor _, ds := range datastore {\n\t\tif ds.Reference().Type == pbmPlacementHub.HubType \u0026\u0026 ds.Reference().Value == pbmPlacementHub.HubId {\n\t\t\treturn ds\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":147,"to":155}} {"id":100034562,"name":"getDsMorNameMap","signature":"func getDsMorNameMap(ctx context.Context, datastores []*DatastoreInfo) map[string]string","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/pbm.go","code":"// getDsMorNameMap returns map of ds Mor and Datastore Object Name\nfunc getDsMorNameMap(ctx context.Context, datastores []*DatastoreInfo) map[string]string {\n\tdsMorNameMap := make(map[string]string)\n\tfor _, ds := range datastores {\n\t\tdsObjectName, err := ds.ObjectName(ctx)\n\t\tif err == nil {\n\t\t\tdsMorNameMap[ds.Reference().Value] = dsObjectName\n\t\t} else {\n\t\t\tklog.Errorf(\"Error occurred while getting datastore object name. err: %+v\", err)\n\t\t}\n\t}\n\treturn dsMorNameMap\n}","line":{"from":157,"to":169}} {"id":100034563,"name":"IsNotFound","signature":"func IsNotFound(err error) bool","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/utils.go","code":"// IsNotFound return true if err is NotFoundError or DefaultNotFoundError\nfunc IsNotFound(err error) bool {\n\t_, ok := err.(*find.NotFoundError)\n\tif ok {\n\t\treturn true\n\t}\n\n\t_, ok = err.(*find.DefaultNotFoundError)\n\tif ok {\n\t\treturn true\n\t}\n\n\treturn false\n}","line":{"from":33,"to":46}} {"id":100034564,"name":"getFinder","signature":"func getFinder(dc *Datacenter) *find.Finder","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/utils.go","code":"func getFinder(dc *Datacenter) *find.Finder {\n\tfinder := find.NewFinder(dc.Client(), false)\n\tfinder.SetDatacenter(dc.Datacenter)\n\treturn finder\n}","line":{"from":48,"to":52}} {"id":100034565,"name":"formatVirtualDiskUUID","signature":"func formatVirtualDiskUUID(uuid string) string","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/utils.go","code":"// formatVirtualDiskUUID removes any spaces and hyphens in UUID\n// Example UUID input is 42375390-71f9-43a3-a770-56803bcd7baa and output after format is 4237539071f943a3a77056803bcd7baa\nfunc formatVirtualDiskUUID(uuid string) string {\n\tuuidwithNoSpace := strings.Replace(uuid, \" \", \"\", -1)\n\tuuidWithNoHypens := strings.Replace(uuidwithNoSpace, \"-\", \"\", -1)\n\treturn strings.ToLower(uuidWithNoHypens)\n}","line":{"from":54,"to":60}} {"id":100034566,"name":"getSCSIControllersOfType","signature":"func getSCSIControllersOfType(vmDevices object.VirtualDeviceList, scsiType string) []*types.VirtualController","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/utils.go","code":"// getSCSIControllersOfType filters specific type of Controller device from given list of Virtual Machine Devices\nfunc getSCSIControllersOfType(vmDevices object.VirtualDeviceList, scsiType string) []*types.VirtualController {\n\t// get virtual scsi controllers of passed argument type\n\tvar scsiControllers []*types.VirtualController\n\tfor _, device := range vmDevices {\n\t\tdevType := vmDevices.Type(device)\n\t\tif devType == scsiType {\n\t\t\tif c, ok := device.(types.BaseVirtualController); ok {\n\t\t\t\tscsiControllers = append(scsiControllers, c.GetVirtualController())\n\t\t\t}\n\t\t}\n\t}\n\treturn scsiControllers\n}","line":{"from":62,"to":75}} {"id":100034567,"name":"getAvailableSCSIController","signature":"func getAvailableSCSIController(scsiControllers []*types.VirtualController) *types.VirtualController","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/utils.go","code":"// getAvailableSCSIController gets available SCSI Controller from list of given controllers, which has less than 15 disk devices.\nfunc getAvailableSCSIController(scsiControllers []*types.VirtualController) *types.VirtualController {\n\t// get SCSI controller which has space for adding more devices\n\tfor _, controller := range scsiControllers {\n\t\tif len(controller.Device) \u003c SCSIControllerDeviceLimit {\n\t\t\treturn controller\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":77,"to":86}} {"id":100034568,"name":"getNextUnitNumber","signature":"func getNextUnitNumber(devices object.VirtualDeviceList, c types.BaseVirtualController) (int32, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/utils.go","code":"// getNextUnitNumber gets the next available SCSI controller unit number from given list of Controller Device List\nfunc getNextUnitNumber(devices object.VirtualDeviceList, c types.BaseVirtualController) (int32, error) {\n\tvar takenUnitNumbers [SCSIDeviceSlots]bool\n\ttakenUnitNumbers[SCSIReservedSlot] = true\n\tkey := c.GetVirtualController().Key\n\n\tfor _, device := range devices {\n\t\td := device.GetVirtualDevice()\n\t\tif d.ControllerKey == key {\n\t\t\tif d.UnitNumber != nil \u0026\u0026 *d.UnitNumber \u003c SCSIDeviceSlots {\n\t\t\t\ttakenUnitNumbers[*d.UnitNumber] = true\n\t\t\t}\n\t\t}\n\t}\n\tfor unitNumber, takenUnitNumber := range takenUnitNumbers {\n\t\tif !takenUnitNumber {\n\t\t\treturn int32(unitNumber), nil\n\t\t}\n\t}\n\treturn -1, fmt.Errorf(\"SCSI Controller with key=%d does not have any available slots\", key)\n}","line":{"from":88,"to":108}} {"id":100034569,"name":"getSCSIControllers","signature":"func getSCSIControllers(vmDevices object.VirtualDeviceList) []*types.VirtualController","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/utils.go","code":"// getSCSIControllers filters and return list of Controller Devices from given list of Virtual Machine Devices.\nfunc getSCSIControllers(vmDevices object.VirtualDeviceList) []*types.VirtualController {\n\t// get all virtual scsi controllers\n\tvar scsiControllers []*types.VirtualController\n\tfor _, device := range vmDevices {\n\t\tdevType := vmDevices.Type(device)\n\t\tswitch devType {\n\t\tcase SCSIControllerType, strings.ToLower(LSILogicControllerType), strings.ToLower(BusLogicControllerType), PVSCSIControllerType, strings.ToLower(LSILogicSASControllerType):\n\t\t\tif c, ok := device.(types.BaseVirtualController); ok {\n\t\t\t\tscsiControllers = append(scsiControllers, c.GetVirtualController())\n\t\t\t}\n\t\t}\n\t}\n\treturn scsiControllers\n}","line":{"from":110,"to":124}} {"id":100034570,"name":"RemoveStorageClusterORFolderNameFromVDiskPath","signature":"func RemoveStorageClusterORFolderNameFromVDiskPath(vDiskPath string) string","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/utils.go","code":"// RemoveStorageClusterORFolderNameFromVDiskPath removes the cluster or folder path from the vDiskPath\n// for vDiskPath [DatastoreCluster/sharedVmfs-0] kubevols/e2e-vmdk-1234.vmdk, return value is [sharedVmfs-0] kubevols/e2e-vmdk-1234.vmdk\n// for vDiskPath [sharedVmfs-0] kubevols/e2e-vmdk-1234.vmdk, return value remains same [sharedVmfs-0] kubevols/e2e-vmdk-1234.vmdk\nfunc RemoveStorageClusterORFolderNameFromVDiskPath(vDiskPath string) string {\n\tdatastore := regexp.MustCompile(\"\\\\[(.*?)\\\\]\").FindStringSubmatch(vDiskPath)[1]\n\tif filepath.Base(datastore) != datastore {\n\t\tvDiskPath = strings.Replace(vDiskPath, datastore, filepath.Base(datastore), 1)\n\t}\n\treturn vDiskPath\n}","line":{"from":126,"to":135}} {"id":100034571,"name":"GetPathFromVMDiskPath","signature":"func GetPathFromVMDiskPath(vmDiskPath string) string","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/utils.go","code":"// GetPathFromVMDiskPath retrieves the path from VM Disk Path.\n// Example: For vmDiskPath - [vsanDatastore] kubevols/volume.vmdk, the path is kubevols/volume.vmdk\nfunc GetPathFromVMDiskPath(vmDiskPath string) string {\n\tdatastorePathObj := new(object.DatastorePath)\n\tisSuccess := datastorePathObj.FromString(vmDiskPath)\n\tif !isSuccess {\n\t\tklog.Errorf(\"Failed to parse vmDiskPath: %s\", vmDiskPath)\n\t\treturn \"\"\n\t}\n\treturn datastorePathObj.Path\n}","line":{"from":137,"to":147}} {"id":100034572,"name":"GetDatastorePathObjFromVMDiskPath","signature":"func GetDatastorePathObjFromVMDiskPath(vmDiskPath string) (*object.DatastorePath, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/utils.go","code":"// GetDatastorePathObjFromVMDiskPath gets the datastorePathObj from VM disk path.\nfunc GetDatastorePathObjFromVMDiskPath(vmDiskPath string) (*object.DatastorePath, error) {\n\tdatastorePathObj := new(object.DatastorePath)\n\tisSuccess := datastorePathObj.FromString(vmDiskPath)\n\tif !isSuccess {\n\t\tklog.Errorf(\"Failed to parse volPath: %s\", vmDiskPath)\n\t\treturn nil, fmt.Errorf(\"failed to parse volPath: %s\", vmDiskPath)\n\t}\n\treturn datastorePathObj, nil\n}","line":{"from":149,"to":158}} {"id":100034573,"name":"IsValidUUID","signature":"func IsValidUUID(uuid string) bool","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/utils.go","code":"// IsValidUUID checks if the string is a valid UUID.\nfunc IsValidUUID(uuid string) bool {\n\tr := regexp.MustCompile(\"^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$\")\n\treturn r.MatchString(uuid)\n}","line":{"from":160,"to":164}} {"id":100034574,"name":"IsManagedObjectNotFoundError","signature":"func IsManagedObjectNotFoundError(err error) bool","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/utils.go","code":"// IsManagedObjectNotFoundError returns true if error is of type ManagedObjectNotFound\nfunc IsManagedObjectNotFoundError(err error) bool {\n\tisManagedObjectNotFoundError := false\n\tif soap.IsSoapFault(err) {\n\t\t_, isManagedObjectNotFoundError = soap.ToSoapFault(err).VimFault().(types.ManagedObjectNotFound)\n\t}\n\treturn isManagedObjectNotFoundError\n}","line":{"from":166,"to":173}} {"id":100034575,"name":"IsInvalidCredentialsError","signature":"func IsInvalidCredentialsError(err error) bool","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/utils.go","code":"// IsInvalidCredentialsError returns true if error is of type InvalidLogin\nfunc IsInvalidCredentialsError(err error) bool {\n\tisInvalidCredentialsError := false\n\tif soap.IsSoapFault(err) {\n\t\t_, isInvalidCredentialsError = soap.ToSoapFault(err).VimFault().(types.InvalidLogin)\n\t}\n\treturn isInvalidCredentialsError\n}","line":{"from":175,"to":182}} {"id":100034576,"name":"VerifyVolumePathsForVMDevices","signature":"func VerifyVolumePathsForVMDevices(vmDevices object.VirtualDeviceList, volPaths []string, nodeName string, nodeVolumeMap map[string]map[string]bool)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/utils.go","code":"// VerifyVolumePathsForVMDevices verifies if the volume paths (volPaths) are attached to VM.\nfunc VerifyVolumePathsForVMDevices(vmDevices object.VirtualDeviceList, volPaths []string, nodeName string, nodeVolumeMap map[string]map[string]bool) {\n\tvolPathsMap := make(map[string]bool)\n\tfor _, volPath := range volPaths {\n\t\tvolPathsMap[volPath] = true\n\t}\n\t// Verify if the volume paths are present on the VM backing virtual disk devices\n\tfor _, device := range vmDevices {\n\t\tif vmDevices.TypeName(device) == \"VirtualDisk\" {\n\t\t\tvirtualDevice := device.GetVirtualDevice()\n\t\t\tif backing, ok := virtualDevice.Backing.(*types.VirtualDiskFlatVer2BackingInfo); ok {\n\t\t\t\tif volPathsMap[backing.FileName] {\n\t\t\t\t\tsetNodeVolumeMap(nodeVolumeMap, backing.FileName, nodeName, true)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n}","line":{"from":184,"to":202}} {"id":100034577,"name":"isvCenterNotSupported","signature":"func isvCenterNotSupported(vCenterVersion string, vCenterAPIVersion string) (bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/utils.go","code":"// isvCenterNotSupported takes vCenter version and vCenter API version as input and return true if vCenter is no longer\n// supported by VMware for in-tree vSphere volume plugin\nfunc isvCenterNotSupported(vCenterVersion string, vCenterAPIVersion string) (bool, error) {\n\tvar vcversion, vcapiversion, minvcversion vcVersion\n\tvar err error\n\terr = vcversion.parse(vCenterVersion)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"failed to parse vCenter version: %s. err: %+v\", vCenterVersion, err)\n\t}\n\terr = vcapiversion.parse(vCenterAPIVersion)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"failed to parse vCenter API version: %s. err: %+v\", vCenterAPIVersion, err)\n\t}\n\terr = minvcversion.parse(MinvCenterVersion)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"failed to parse minimum vCenter version: %s. err: %+v\", MinvCenterVersion, err)\n\t}\n\tif vcversion.isLessThan(minvcversion) \u0026\u0026 vcapiversion.isLessThan(minvcversion) {\n\t\treturn true, nil\n\t}\n\treturn false, nil\n}","line":{"from":204,"to":225}} {"id":100034578,"name":"parse","signature":"func (v *vcVersion) parse(version string) error","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/utils.go","code":"// parse helps parse version string to VCVersion\n// returns error when parse fail\nfunc (v *vcVersion) parse(version string) error {\n\tfor index, value := range strings.Split(version, \".\") {\n\t\tvar err error\n\t\tif index == 0 {\n\t\t\tv.Major, err = strconv.ParseInt(value, 10, 64)\n\t\t} else if index == 1 {\n\t\t\tv.Minor, err = strconv.ParseInt(value, 10, 64)\n\t\t} else if index == 2 {\n\t\t\tv.Revision, err = strconv.ParseInt(value, 10, 64)\n\t\t} else if index == 3 {\n\t\t\tv.Build, err = strconv.ParseInt(value, 10, 64)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to parse version: %q, err: %v\", version, err)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":235,"to":254}} {"id":100034579,"name":"isLessThan","signature":"func (v *vcVersion) isLessThan(o vcVersion) bool","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/utils.go","code":"// isLessThan compares VCVersion v to o and returns\n// true if v is less than o\nfunc (v *vcVersion) isLessThan(o vcVersion) bool {\n\tif v.Major != o.Major {\n\t\tif v.Major \u003e o.Major {\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t}\n\tif v.Minor != o.Minor {\n\t\tif v.Minor \u003e o.Minor {\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t}\n\tif v.Revision != o.Revision {\n\t\tif v.Revision \u003e o.Revision {\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t}\n\tif v.Build != o.Build {\n\t\tif v.Build \u003e o.Build {\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}","line":{"from":256,"to":284}} {"id":100034580,"name":"IsDiskAttached","signature":"func (vm *VirtualMachine) IsDiskAttached(ctx context.Context, diskPath string) (bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/virtualmachine.go","code":"// IsDiskAttached checks if disk is attached to the VM.\nfunc (vm *VirtualMachine) IsDiskAttached(ctx context.Context, diskPath string) (bool, error) {\n\tdevice, err := vm.getVirtualDeviceByPath(ctx, diskPath)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif device != nil {\n\t\treturn true, nil\n\t}\n\treturn false, nil\n}","line":{"from":39,"to":49}} {"id":100034581,"name":"DeleteVM","signature":"func (vm *VirtualMachine) DeleteVM(ctx context.Context) error","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/virtualmachine.go","code":"// DeleteVM deletes the VM.\nfunc (vm *VirtualMachine) DeleteVM(ctx context.Context) error {\n\tdestroyTask, err := vm.Destroy(ctx)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to delete the VM: %q. err: %+v\", vm.InventoryPath, err)\n\t\treturn err\n\t}\n\treturn destroyTask.Wait(ctx)\n}","line":{"from":51,"to":59}} {"id":100034582,"name":"AttachDisk","signature":"func (vm *VirtualMachine) AttachDisk(ctx context.Context, vmDiskPath string, volumeOptions *VolumeOptions) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/virtualmachine.go","code":"// AttachDisk attaches the disk at location - vmDiskPath from Datastore - dsObj to the Virtual Machine\n// Additionally the disk can be configured with SPBM policy if volumeOptions.StoragePolicyID is non-empty.\nfunc (vm *VirtualMachine) AttachDisk(ctx context.Context, vmDiskPath string, volumeOptions *VolumeOptions) (string, error) {\n\t// Check if the diskControllerType is valid\n\tif !CheckControllerSupported(volumeOptions.SCSIControllerType) {\n\t\treturn \"\", fmt.Errorf(\"Not a valid SCSI Controller Type. Valid options are %q\", SCSIControllerTypeValidOptions())\n\t}\n\tvmDiskPathCopy := vmDiskPath\n\tvmDiskPath = RemoveStorageClusterORFolderNameFromVDiskPath(vmDiskPath)\n\tattached, err := vm.IsDiskAttached(ctx, vmDiskPath)\n\tif err != nil {\n\t\tklog.Errorf(\"Error occurred while checking if disk is attached on VM: %q. vmDiskPath: %q, err: %+v\", vm.InventoryPath, vmDiskPath, err)\n\t\treturn \"\", err\n\t}\n\t// If disk is already attached, return the disk UUID\n\tif attached {\n\t\tdiskUUID, _ := vm.Datacenter.GetVirtualDiskPage83Data(ctx, vmDiskPath)\n\t\treturn diskUUID, nil\n\t}\n\n\tif volumeOptions.StoragePolicyName != \"\" {\n\t\tpbmClient, err := NewPbmClient(ctx, vm.Client())\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Error occurred while creating new pbmClient. err: %+v\", err)\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tvolumeOptions.StoragePolicyID, err = pbmClient.ProfileIDByName(ctx, volumeOptions.StoragePolicyName)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to get Profile ID by name: %s. err: %+v\", volumeOptions.StoragePolicyName, err)\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tdsObj, err := vm.Datacenter.GetDatastoreByPath(ctx, vmDiskPathCopy)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get datastore from vmDiskPath: %q. err: %+v\", vmDiskPath, err)\n\t\treturn \"\", err\n\t}\n\t// If disk is not attached, create a disk spec for disk to be attached to the VM.\n\tdisk, newSCSIController, err := vm.CreateDiskSpec(ctx, vmDiskPath, dsObj, volumeOptions)\n\tif err != nil {\n\t\tklog.Errorf(\"Error occurred while creating disk spec. err: %+v\", err)\n\t\treturn \"\", err\n\t}\n\tvmDevices, err := vm.Device(ctx)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to retrieve VM devices for VM: %q. err: %+v\", vm.InventoryPath, err)\n\t\treturn \"\", err\n\t}\n\tvirtualMachineConfigSpec := types.VirtualMachineConfigSpec{}\n\tdeviceConfigSpec := \u0026types.VirtualDeviceConfigSpec{\n\t\tDevice: disk,\n\t\tOperation: types.VirtualDeviceConfigSpecOperationAdd,\n\t}\n\t// Configure the disk with the SPBM profile only if ProfileID is not empty.\n\tif volumeOptions.StoragePolicyID != \"\" {\n\t\tprofileSpec := \u0026types.VirtualMachineDefinedProfileSpec{\n\t\t\tProfileId: volumeOptions.StoragePolicyID,\n\t\t}\n\t\tdeviceConfigSpec.Profile = append(deviceConfigSpec.Profile, profileSpec)\n\t}\n\tvirtualMachineConfigSpec.DeviceChange = append(virtualMachineConfigSpec.DeviceChange, deviceConfigSpec)\n\trequestTime := time.Now()\n\ttask, err := vm.Reconfigure(ctx, virtualMachineConfigSpec)\n\tif err != nil {\n\t\tRecordvSphereMetric(APIAttachVolume, requestTime, err)\n\t\tklog.Errorf(\"Failed to attach the disk with storagePolicy: %q on VM: %q. err - %+v\", volumeOptions.StoragePolicyID, vm.InventoryPath, err)\n\t\tif newSCSIController != nil {\n\t\t\tnestedErr := vm.deleteController(ctx, newSCSIController, vmDevices)\n\t\t\tif nestedErr != nil {\n\t\t\t\treturn \"\", fmt.Errorf(\"failed to delete SCSI Controller after reconfiguration failed with err=%v: %v\", err, nestedErr)\n\t\t\t}\n\t\t}\n\t\treturn \"\", err\n\t}\n\terr = task.Wait(ctx)\n\tRecordvSphereMetric(APIAttachVolume, requestTime, err)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to attach the disk with storagePolicy: %+q on VM: %q. err - %+v\", volumeOptions.StoragePolicyID, vm.InventoryPath, err)\n\t\tif newSCSIController != nil {\n\t\t\tnestedErr := vm.deleteController(ctx, newSCSIController, vmDevices)\n\t\t\tif nestedErr != nil {\n\t\t\t\treturn \"\", fmt.Errorf(\"failed to delete SCSI Controller after waiting for reconfiguration failed with err='%v': %v\", err, nestedErr)\n\t\t\t}\n\t\t}\n\t\treturn \"\", err\n\t}\n\n\t// Once disk is attached, get the disk UUID.\n\tdiskUUID, err := vm.Datacenter.GetVirtualDiskPage83Data(ctx, vmDiskPath)\n\tif err != nil {\n\t\tklog.Errorf(\"Error occurred while getting Disk Info from VM: %q. err: %v\", vm.InventoryPath, err)\n\t\tnestedErr := vm.DetachDisk(ctx, vmDiskPath)\n\t\tif nestedErr != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to detach disk after getting VM UUID failed with err='%v': %v\", err, nestedErr)\n\t\t}\n\t\tif newSCSIController != nil {\n\t\t\tnestedErr = vm.deleteController(ctx, newSCSIController, vmDevices)\n\t\t\tif nestedErr != nil {\n\t\t\t\treturn \"\", fmt.Errorf(\"failed to delete SCSI Controller after getting VM UUID failed with err='%v': %v\", err, nestedErr)\n\t\t\t}\n\t\t}\n\t\treturn \"\", err\n\t}\n\treturn diskUUID, nil\n}","line":{"from":61,"to":167}} {"id":100034583,"name":"GetHost","signature":"func (vm *VirtualMachine) GetHost(ctx context.Context) (mo.HostSystem, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/virtualmachine.go","code":"// GetHost returns host of the virtual machine\nfunc (vm *VirtualMachine) GetHost(ctx context.Context) (mo.HostSystem, error) {\n\thost, err := vm.HostSystem(ctx)\n\tvar hostSystemMo mo.HostSystem\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get host system for VM: %q. err: %+v\", vm.InventoryPath, err)\n\t\treturn hostSystemMo, err\n\t}\n\n\ts := object.NewSearchIndex(vm.Client())\n\terr = s.Properties(ctx, host.Reference(), []string{\"summary\"}, \u0026hostSystemMo)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to retrieve datastores for host: %+v. err: %+v\", host, err)\n\t\treturn hostSystemMo, err\n\t}\n\treturn hostSystemMo, nil\n}","line":{"from":169,"to":185}} {"id":100034584,"name":"DetachDisk","signature":"func (vm *VirtualMachine) DetachDisk(ctx context.Context, vmDiskPath string) error","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/virtualmachine.go","code":"// DetachDisk detaches the disk specified by vmDiskPath\nfunc (vm *VirtualMachine) DetachDisk(ctx context.Context, vmDiskPath string) error {\n\tdevice, err := vm.getVirtualDeviceByPath(ctx, vmDiskPath)\n\tif err != nil {\n\t\tklog.Errorf(\"Disk ID not found for VM: %q with diskPath: %q\", vm.InventoryPath, vmDiskPath)\n\t\treturn err\n\t}\n\tif device == nil {\n\t\tklog.Errorf(\"No virtual device found with diskPath: %q on VM: %q\", vmDiskPath, vm.InventoryPath)\n\t\treturn fmt.Errorf(\"No virtual device found with diskPath: %q on VM: %q\", vmDiskPath, vm.InventoryPath)\n\t}\n\t// Detach disk from VM\n\trequestTime := time.Now()\n\terr = vm.RemoveDevice(ctx, true, device)\n\tRecordvSphereMetric(APIDetachVolume, requestTime, err)\n\tif err != nil {\n\t\tklog.Errorf(\"Error occurred while removing disk device for VM: %q. err: %v\", vm.InventoryPath, err)\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":187,"to":207}} {"id":100034585,"name":"GetResourcePool","signature":"func (vm *VirtualMachine) GetResourcePool(ctx context.Context) (*object.ResourcePool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/virtualmachine.go","code":"// GetResourcePool gets the resource pool for VM.\nfunc (vm *VirtualMachine) GetResourcePool(ctx context.Context) (*object.ResourcePool, error) {\n\tvmMoList, err := vm.Datacenter.GetVMMoList(ctx, []*VirtualMachine{vm}, []string{\"resourcePool\"})\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get resource pool from VM: %q. err: %+v\", vm.InventoryPath, err)\n\t\treturn nil, err\n\t}\n\treturn object.NewResourcePool(vm.Client(), vmMoList[0].ResourcePool.Reference()), nil\n}","line":{"from":209,"to":217}} {"id":100034586,"name":"IsActive","signature":"func (vm *VirtualMachine) IsActive(ctx context.Context) (bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/virtualmachine.go","code":"// IsActive checks if the VM is active.\n// Returns true if VM is in poweredOn state.\nfunc (vm *VirtualMachine) IsActive(ctx context.Context) (bool, error) {\n\tvmMoList, err := vm.Datacenter.GetVMMoList(ctx, []*VirtualMachine{vm}, []string{\"summary\"})\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get VM Managed object with property summary. err: +%v\", err)\n\t\treturn false, err\n\t}\n\tif vmMoList[0].Summary.Runtime.PowerState == ActivePowerState {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}","line":{"from":219,"to":232}} {"id":100034587,"name":"Exists","signature":"func (vm *VirtualMachine) Exists(ctx context.Context) (bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/virtualmachine.go","code":"// Exists checks if VM exists and is not terminated\nfunc (vm *VirtualMachine) Exists(ctx context.Context) (bool, error) {\n\tvmMoList, err := vm.Datacenter.GetVMMoList(ctx, []*VirtualMachine{vm}, []string{\"summary.runtime.powerState\"})\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get VM Managed object with property summary. err: +%v\", err)\n\t\treturn false, err\n\t}\n\t// We check for VMs which are still available in vcenter and has not been terminated/removed from\n\t// disk and hence we consider PoweredOn,PoweredOff and Suspended as alive states.\n\taliveStates := []types.VirtualMachinePowerState{\n\t\ttypes.VirtualMachinePowerStatePoweredOff,\n\t\ttypes.VirtualMachinePowerStatePoweredOn,\n\t\ttypes.VirtualMachinePowerStateSuspended,\n\t}\n\tcurrentState := vmMoList[0].Summary.Runtime.PowerState\n\tfor _, state := range aliveStates {\n\t\tif state == currentState {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}","line":{"from":234,"to":255}} {"id":100034588,"name":"GetAllAccessibleDatastores","signature":"func (vm *VirtualMachine) GetAllAccessibleDatastores(ctx context.Context) ([]*DatastoreInfo, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/virtualmachine.go","code":"// GetAllAccessibleDatastores gets the list of accessible Datastores for the given Virtual Machine\nfunc (vm *VirtualMachine) GetAllAccessibleDatastores(ctx context.Context) ([]*DatastoreInfo, error) {\n\thost, err := vm.HostSystem(ctx)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get host system for VM: %q. err: %+v\", vm.InventoryPath, err)\n\t\treturn nil, err\n\t}\n\tvar hostSystemMo mo.HostSystem\n\ts := object.NewSearchIndex(vm.Client())\n\terr = s.Properties(ctx, host.Reference(), []string{DatastoreProperty}, \u0026hostSystemMo)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to retrieve datastores for host: %+v. err: %+v\", host, err)\n\t\treturn nil, err\n\t}\n\tvar dsRefList []types.ManagedObjectReference\n\tdsRefList = append(dsRefList, hostSystemMo.Datastore...)\n\n\tvar dsMoList []mo.Datastore\n\tpc := property.DefaultCollector(vm.Client())\n\tproperties := []string{DatastoreInfoProperty, NameProperty}\n\terr = pc.Retrieve(ctx, dsRefList, properties, \u0026dsMoList)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get Datastore managed objects from datastore objects.\"+\n\t\t\t\" dsObjList: %+v, properties: %+v, err: %v\", dsRefList, properties, err)\n\t\treturn nil, err\n\t}\n\tklog.V(9).Infof(\"Result dsMoList: %+v\", dsMoList)\n\tfinder := getFinder(vm.Datacenter)\n\tvar dsObjList []*DatastoreInfo\n\tfor _, dsMo := range dsMoList {\n\t\t// use the finder so that InventoryPath is set correctly in ds\n\t\tds, err := finder.Datastore(ctx, dsMo.Name)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed finding datastore: %s. err: %+v\", dsMo.Name, err)\n\t\t\treturn nil, err\n\t\t}\n\t\tdatastore := Datastore{ds, vm.Datacenter}\n\t\tdsObjList = append(dsObjList,\n\t\t\t\u0026DatastoreInfo{\n\t\t\t\t\u0026datastore,\n\t\t\t\tdsMo.Info.GetDatastoreInfo()})\n\t}\n\treturn dsObjList, nil\n}","line":{"from":257,"to":300}} {"id":100034589,"name":"CreateDiskSpec","signature":"func (vm *VirtualMachine) CreateDiskSpec(ctx context.Context, diskPath string, dsObj *Datastore, volumeOptions *VolumeOptions) (*types.VirtualDisk, types.BaseVirtualDevice, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/virtualmachine.go","code":"// CreateDiskSpec creates a disk spec for disk\nfunc (vm *VirtualMachine) CreateDiskSpec(ctx context.Context, diskPath string, dsObj *Datastore, volumeOptions *VolumeOptions) (*types.VirtualDisk, types.BaseVirtualDevice, error) {\n\tvar newSCSIController types.BaseVirtualDevice\n\tvmDevices, err := vm.Device(ctx)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to retrieve VM devices. err: %+v\", err)\n\t\treturn nil, nil, err\n\t}\n\t// find SCSI controller of particular type from VM devices\n\tscsiControllersOfRequiredType := getSCSIControllersOfType(vmDevices, volumeOptions.SCSIControllerType)\n\tscsiController := getAvailableSCSIController(scsiControllersOfRequiredType)\n\tif scsiController == nil {\n\t\tnewSCSIController, err = vm.createAndAttachSCSIController(ctx, volumeOptions.SCSIControllerType)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to create SCSI controller for VM :%q with err: %+v\", vm.InventoryPath, err)\n\t\t\treturn nil, nil, err\n\t\t}\n\t\t// Get VM device list\n\t\tvmDevices, err := vm.Device(ctx)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to retrieve VM devices. err: %v\", err)\n\t\t\treturn nil, nil, err\n\t\t}\n\t\t// verify scsi controller in virtual machine\n\t\tscsiControllersOfRequiredType := getSCSIControllersOfType(vmDevices, volumeOptions.SCSIControllerType)\n\t\tscsiController = getAvailableSCSIController(scsiControllersOfRequiredType)\n\t\tif scsiController == nil {\n\t\t\tklog.Errorf(\"Cannot find SCSI controller of type: %q in VM\", volumeOptions.SCSIControllerType)\n\t\t\t// attempt clean up of scsi controller\n\t\t\tif err := vm.deleteController(ctx, newSCSIController, vmDevices); err != nil {\n\t\t\t\treturn nil, nil, fmt.Errorf(\"failed to delete SCSI controller after failing to find it on VM: %v\", err)\n\t\t\t}\n\t\t\treturn nil, nil, fmt.Errorf(\"cannot find SCSI controller of type: %q in VM\", volumeOptions.SCSIControllerType)\n\t\t}\n\t}\n\tdisk := vmDevices.CreateDisk(scsiController, dsObj.Reference(), diskPath)\n\tunitNumber, err := getNextUnitNumber(vmDevices, scsiController)\n\tif err != nil {\n\t\tklog.Errorf(\"Cannot attach disk to VM, unitNumber limit reached - %+v.\", err)\n\t\treturn nil, nil, err\n\t}\n\t*disk.UnitNumber = unitNumber\n\tbacking := disk.Backing.(*types.VirtualDiskFlatVer2BackingInfo)\n\tbacking.DiskMode = string(types.VirtualDiskModeIndependent_persistent)\n\n\tif volumeOptions.CapacityKB != 0 {\n\t\tdisk.CapacityInKB = int64(volumeOptions.CapacityKB)\n\t}\n\tif volumeOptions.DiskFormat != \"\" {\n\t\tvar diskFormat string\n\t\tdiskFormat = DiskFormatValidType[volumeOptions.DiskFormat]\n\t\tswitch diskFormat {\n\t\tcase ThinDiskType:\n\t\t\tbacking.ThinProvisioned = types.NewBool(true)\n\t\tcase EagerZeroedThickDiskType:\n\t\t\tbacking.EagerlyScrub = types.NewBool(true)\n\t\tdefault:\n\t\t\tbacking.ThinProvisioned = types.NewBool(false)\n\t\t}\n\t}\n\treturn disk, newSCSIController, nil\n}","line":{"from":302,"to":363}} {"id":100034590,"name":"GetVirtualDiskPath","signature":"func (vm *VirtualMachine) GetVirtualDiskPath(ctx context.Context) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/virtualmachine.go","code":"// GetVirtualDiskPath gets the first available virtual disk devicePath from the VM\nfunc (vm *VirtualMachine) GetVirtualDiskPath(ctx context.Context) (string, error) {\n\tvmDevices, err := vm.Device(ctx)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get the devices for VM: %q. err: %+v\", vm.InventoryPath, err)\n\t\treturn \"\", err\n\t}\n\t// filter vm devices to retrieve device for the given vmdk file identified by disk path\n\tfor _, device := range vmDevices {\n\t\tif vmDevices.TypeName(device) == \"VirtualDisk\" {\n\t\t\tvirtualDevice := device.GetVirtualDevice()\n\t\t\tif backing, ok := virtualDevice.Backing.(*types.VirtualDiskFlatVer2BackingInfo); ok {\n\t\t\t\treturn backing.FileName, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", nil\n}","line":{"from":365,"to":382}} {"id":100034591,"name":"createAndAttachSCSIController","signature":"func (vm *VirtualMachine) createAndAttachSCSIController(ctx context.Context, diskControllerType string) (types.BaseVirtualDevice, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/virtualmachine.go","code":"// createAndAttachSCSIController creates and attachs the SCSI controller to the VM.\nfunc (vm *VirtualMachine) createAndAttachSCSIController(ctx context.Context, diskControllerType string) (types.BaseVirtualDevice, error) {\n\t// Get VM device list\n\tvmDevices, err := vm.Device(ctx)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to retrieve VM devices for VM: %q. err: %+v\", vm.InventoryPath, err)\n\t\treturn nil, err\n\t}\n\tallSCSIControllers := getSCSIControllers(vmDevices)\n\tif len(allSCSIControllers) \u003e= SCSIControllerLimit {\n\t\t// we reached the maximum number of controllers we can attach\n\t\tklog.Errorf(\"SCSI Controller Limit of %d has been reached, cannot create another SCSI controller\", SCSIControllerLimit)\n\t\treturn nil, fmt.Errorf(\"SCSI Controller Limit of %d has been reached, cannot create another SCSI controller\", SCSIControllerLimit)\n\t}\n\tnewSCSIController, err := vmDevices.CreateSCSIController(diskControllerType)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to create new SCSI controller on VM: %q. err: %+v\", vm.InventoryPath, err)\n\t\treturn nil, err\n\t}\n\tconfigNewSCSIController := newSCSIController.(types.BaseVirtualSCSIController).GetVirtualSCSIController()\n\thotAndRemove := true\n\tconfigNewSCSIController.HotAddRemove = \u0026hotAndRemove\n\tconfigNewSCSIController.SharedBus = types.VirtualSCSISharing(types.VirtualSCSISharingNoSharing)\n\n\t// add the scsi controller to virtual machine\n\terr = vm.AddDevice(context.TODO(), newSCSIController)\n\tif err != nil {\n\t\tklog.V(LogLevel).Infof(\"Cannot add SCSI controller to VM: %q. err: %+v\", vm.InventoryPath, err)\n\t\t// attempt clean up of scsi controller\n\t\tnestedErr := vm.deleteController(ctx, newSCSIController, vmDevices)\n\t\tif nestedErr != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to delete SCSI controller after failing to add it to vm with err='%v': %v\", err, nestedErr)\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn newSCSIController, nil\n}","line":{"from":384,"to":420}} {"id":100034592,"name":"getVirtualDeviceByPath","signature":"func (vm *VirtualMachine) getVirtualDeviceByPath(ctx context.Context, diskPath string) (types.BaseVirtualDevice, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/virtualmachine.go","code":"// getVirtualDeviceByPath gets the virtual device by path\nfunc (vm *VirtualMachine) getVirtualDeviceByPath(ctx context.Context, diskPath string) (types.BaseVirtualDevice, error) {\n\tvmDevices, err := vm.Device(ctx)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get the devices for VM: %q. err: %+v\", vm.InventoryPath, err)\n\t\treturn nil, err\n\t}\n\n\t// filter vm devices to retrieve device for the given vmdk file identified by disk path\n\tfor _, device := range vmDevices {\n\t\tif vmDevices.TypeName(device) == \"VirtualDisk\" {\n\t\t\tvirtualDevice := device.GetVirtualDevice()\n\t\t\tif backing, ok := virtualDevice.Backing.(*types.VirtualDiskFlatVer2BackingInfo); ok {\n\t\t\t\tif matchVirtualDiskAndVolPath(backing.FileName, diskPath) {\n\t\t\t\t\tklog.V(LogLevel).Infof(\"Found VirtualDisk backing with filename %q for diskPath %q\", backing.FileName, diskPath)\n\t\t\t\t\treturn device, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, nil\n}","line":{"from":422,"to":443}} {"id":100034593,"name":"matchVirtualDiskAndVolPath","signature":"func matchVirtualDiskAndVolPath(diskPath, volPath string) bool","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/virtualmachine.go","code":"func matchVirtualDiskAndVolPath(diskPath, volPath string) bool {\n\tfileExt := \".vmdk\"\n\tdiskPath = strings.TrimSuffix(diskPath, fileExt)\n\tvolPath = strings.TrimSuffix(volPath, fileExt)\n\treturn diskPath == volPath\n}","line":{"from":445,"to":450}} {"id":100034594,"name":"deleteController","signature":"func (vm *VirtualMachine) deleteController(ctx context.Context, controllerDevice types.BaseVirtualDevice, vmDevices object.VirtualDeviceList) error","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/virtualmachine.go","code":"// deleteController removes latest added SCSI controller from VM.\nfunc (vm *VirtualMachine) deleteController(ctx context.Context, controllerDevice types.BaseVirtualDevice, vmDevices object.VirtualDeviceList) error {\n\tcontrollerDeviceList := vmDevices.SelectByType(controllerDevice)\n\tif len(controllerDeviceList) \u003c 1 {\n\t\treturn ErrNoDevicesFound\n\t}\n\tdevice := controllerDeviceList[len(controllerDeviceList)-1]\n\terr := vm.RemoveDevice(ctx, true, device)\n\tif err != nil {\n\t\tklog.Errorf(\"Error occurred while removing device on VM: %q. err: %+v\", vm.InventoryPath, err)\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":452,"to":465}} {"id":100034595,"name":"RenewVM","signature":"func (vm *VirtualMachine) RenewVM(client *vim25.Client) VirtualMachine","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/virtualmachine.go","code":"// RenewVM renews this virtual machine with new client connection.\nfunc (vm *VirtualMachine) RenewVM(client *vim25.Client) VirtualMachine {\n\tdc := Datacenter{Datacenter: object.NewDatacenter(client, vm.Datacenter.Reference())}\n\tnewVM := object.NewVirtualMachine(client, vm.VirtualMachine.Reference())\n\treturn VirtualMachine{VirtualMachine: newVM, Datacenter: \u0026dc}\n}","line":{"from":467,"to":472}} {"id":100034596,"name":"DiskformatValidOptions","signature":"func DiskformatValidOptions() string","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/volumeoptions.go","code":"// DiskformatValidOptions generates Valid Options for Diskformat\nfunc DiskformatValidOptions() string {\n\tvalidopts := \"\"\n\tfor diskformat := range DiskFormatValidType {\n\t\tvalidopts += diskformat + \", \"\n\t}\n\tvalidopts = strings.TrimSuffix(validopts, \", \")\n\treturn validopts\n}","line":{"from":53,"to":61}} {"id":100034597,"name":"CheckDiskFormatSupported","signature":"func CheckDiskFormatSupported(diskFormat string) bool","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/volumeoptions.go","code":"// CheckDiskFormatSupported checks if the diskFormat is valid\nfunc CheckDiskFormatSupported(diskFormat string) bool {\n\tif DiskFormatValidType[diskFormat] == \"\" {\n\t\tklog.Errorf(\"Not a valid Disk Format. Valid options are %+q\", DiskformatValidOptions())\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":63,"to":70}} {"id":100034598,"name":"SCSIControllerTypeValidOptions","signature":"func SCSIControllerTypeValidOptions() string","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/volumeoptions.go","code":"// SCSIControllerTypeValidOptions generates valid options for SCSIControllerType\nfunc SCSIControllerTypeValidOptions() string {\n\tvalidopts := \"\"\n\tfor _, controllerType := range SCSIControllerValidType {\n\t\tvalidopts += (controllerType + \", \")\n\t}\n\tvalidopts = strings.TrimSuffix(validopts, \", \")\n\treturn validopts\n}","line":{"from":72,"to":80}} {"id":100034599,"name":"CheckControllerSupported","signature":"func CheckControllerSupported(ctrlType string) bool","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/volumeoptions.go","code":"// CheckControllerSupported checks if the given controller type is valid\nfunc CheckControllerSupported(ctrlType string) bool {\n\tfor _, c := range SCSIControllerValidType {\n\t\tif ctrlType == c {\n\t\t\treturn true\n\t\t}\n\t}\n\tklog.Errorf(\"Not a valid SCSI Controller Type. Valid options are %q\", SCSIControllerTypeValidOptions())\n\treturn false\n}","line":{"from":82,"to":91}} {"id":100034600,"name":"VerifyVolumeOptions","signature":"func (volumeOptions VolumeOptions) VerifyVolumeOptions() error","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/volumeoptions.go","code":"// VerifyVolumeOptions checks if volumeOptions.SCIControllerType is valid controller type\nfunc (volumeOptions VolumeOptions) VerifyVolumeOptions() error {\n\t// Validate only if SCSIControllerType is set by user.\n\t// Default value is set later in virtualDiskManager.Create and vmDiskManager.Create\n\tif volumeOptions.SCSIControllerType != \"\" {\n\t\tisValid := CheckControllerSupported(volumeOptions.SCSIControllerType)\n\t\tif !isValid {\n\t\t\treturn fmt.Errorf(\"invalid scsiControllerType: %s\", volumeOptions.SCSIControllerType)\n\t\t}\n\t}\n\t// ThinDiskType is the default, so skip the validation.\n\tif volumeOptions.DiskFormat != ThinDiskType {\n\t\tisValid := CheckDiskFormatSupported(volumeOptions.DiskFormat)\n\t\tif !isValid {\n\t\t\treturn fmt.Errorf(\"invalid diskFormat: %s\", volumeOptions.DiskFormat)\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":93,"to":111}} {"id":100034601,"name":"init","signature":"func init()","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/vsphere_metrics.go","code":"func init() {\n\tvCenterMetric = \u0026vcenterMetric{\n\t\tvCenterInfos: make(map[string]types.AboutInfo),\n\t\tmux: sync.Mutex{},\n\t}\n}","line":{"from":50,"to":55}} {"id":100034602,"name":"RegisterMetrics","signature":"func RegisterMetrics()","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/vsphere_metrics.go","code":"// RegisterMetrics registers all the API and Operation metrics\nfunc RegisterMetrics() {\n\tlegacyregistry.MustRegister(vsphereAPIMetric)\n\tlegacyregistry.MustRegister(vsphereAPIErrorMetric)\n\tlegacyregistry.MustRegister(vsphereOperationMetric)\n\tlegacyregistry.MustRegister(vsphereOperationErrorMetric)\n\tlegacyregistry.CustomMustRegister(vCenterMetric)\n}","line":{"from":101,"to":108}} {"id":100034603,"name":"DescribeWithStability","signature":"func (collector *vcenterMetric) DescribeWithStability(ch chan\u003c- *metrics.Desc)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/vsphere_metrics.go","code":"func (collector *vcenterMetric) DescribeWithStability(ch chan\u003c- *metrics.Desc) {\n\tch \u003c- vsphereVersion\n}","line":{"from":117,"to":119}} {"id":100034604,"name":"CollectWithStability","signature":"func (collector *vcenterMetric) CollectWithStability(ch chan\u003c- metrics.Metric)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/vsphere_metrics.go","code":"func (collector *vcenterMetric) CollectWithStability(ch chan\u003c- metrics.Metric) {\n\tcollector.mux.Lock()\n\tdefer collector.mux.Unlock()\n\n\tfor vCenter, info := range collector.vCenterInfos {\n\t\tch \u003c- metrics.NewLazyMetricWithTimestamp(time.Now(),\n\t\t\tmetrics.NewLazyConstMetric(vsphereVersion,\n\t\t\t\tmetrics.GaugeValue,\n\t\t\t\tfloat64(1),\n\t\t\t\tvCenter,\n\t\t\t\tinfo.Version,\n\t\t\t\tinfo.Build))\n\t}\n}","line":{"from":121,"to":134}} {"id":100034605,"name":"setAbout","signature":"func (collector *vcenterMetric) setAbout(server string, info types.AboutInfo)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/vsphere_metrics.go","code":"func (collector *vcenterMetric) setAbout(server string, info types.AboutInfo) {\n\tcollector.mux.Lock()\n\tdefer collector.mux.Unlock()\n\tcollector.vCenterInfos[server] = info\n}","line":{"from":136,"to":140}} {"id":100034606,"name":"setVCenterInfoMetric","signature":"func setVCenterInfoMetric(connection *VSphereConnection)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/vsphere_metrics.go","code":"func setVCenterInfoMetric(connection *VSphereConnection) {\n\tvCenterMetric.setAbout(connection.Hostname, connection.Client.ServiceContent.About)\n}","line":{"from":142,"to":144}} {"id":100034607,"name":"RecordvSphereMetric","signature":"func RecordvSphereMetric(actionName string, requestTime time.Time, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/vsphere_metrics.go","code":"// RecordvSphereMetric records the vSphere API and Operation metrics\nfunc RecordvSphereMetric(actionName string, requestTime time.Time, err error) {\n\tswitch actionName {\n\tcase APICreateVolume, APIDeleteVolume, APIAttachVolume, APIDetachVolume:\n\t\trecordvSphereAPIMetric(actionName, requestTime, err)\n\tdefault:\n\t\trecordvSphereOperationMetric(actionName, requestTime, err)\n\t}\n}","line":{"from":146,"to":154}} {"id":100034608,"name":"recordvSphereAPIMetric","signature":"func recordvSphereAPIMetric(actionName string, requestTime time.Time, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/vsphere_metrics.go","code":"func recordvSphereAPIMetric(actionName string, requestTime time.Time, err error) {\n\tif err != nil {\n\t\tvsphereAPIErrorMetric.With(metrics.Labels{\"request\": actionName}).Inc()\n\t} else {\n\t\tvsphereAPIMetric.With(metrics.Labels{\"request\": actionName}).Observe(calculateTimeTaken(requestTime))\n\t}\n}","line":{"from":156,"to":162}} {"id":100034609,"name":"recordvSphereOperationMetric","signature":"func recordvSphereOperationMetric(actionName string, requestTime time.Time, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/vsphere_metrics.go","code":"func recordvSphereOperationMetric(actionName string, requestTime time.Time, err error) {\n\tif err != nil {\n\t\tvsphereOperationErrorMetric.With(metrics.Labels{\"operation\": actionName}).Inc()\n\t} else {\n\t\tvsphereOperationMetric.With(metrics.Labels{\"operation\": actionName}).Observe(calculateTimeTaken(requestTime))\n\t}\n}","line":{"from":164,"to":170}} {"id":100034610,"name":"RecordCreateVolumeMetric","signature":"func RecordCreateVolumeMetric(volumeOptions *VolumeOptions, requestTime time.Time, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/vsphere_metrics.go","code":"// RecordCreateVolumeMetric records the Create Volume metric\nfunc RecordCreateVolumeMetric(volumeOptions *VolumeOptions, requestTime time.Time, err error) {\n\tvar actionName string\n\tif volumeOptions.StoragePolicyName != \"\" {\n\t\tactionName = OperationCreateVolumeWithPolicy\n\t} else if volumeOptions.VSANStorageProfileData != \"\" {\n\t\tactionName = OperationCreateVolumeWithRawVSANPolicy\n\t} else {\n\t\tactionName = OperationCreateVolume\n\t}\n\tRecordvSphereMetric(actionName, requestTime, err)\n}","line":{"from":172,"to":183}} {"id":100034611,"name":"calculateTimeTaken","signature":"func calculateTimeTaken(requestBeginTime time.Time) (timeTaken float64)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vclib/vsphere_metrics.go","code":"func calculateTimeTaken(requestBeginTime time.Time) (timeTaken float64) {\n\tif !requestBeginTime.IsZero() {\n\t\ttimeTaken = time.Since(requestBeginTime).Seconds()\n\t} else {\n\t\ttimeTaken = 0\n\t}\n\treturn timeTaken\n}","line":{"from":185,"to":192}} {"id":100034612,"name":"readConfig","signature":"func readConfig(config io.Reader) (VSphereConfig, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// Parses vSphere cloud config file and stores it into VSphereConfig.\nfunc readConfig(config io.Reader) (VSphereConfig, error) {\n\tif config == nil {\n\t\terr := fmt.Errorf(\"no vSphere cloud provider config file given\")\n\t\treturn VSphereConfig{}, err\n\t}\n\n\tvar cfg VSphereConfig\n\terr := gcfg.ReadInto(\u0026cfg, config)\n\treturn cfg, err\n}","line":{"from":249,"to":259}} {"id":100034613,"name":"init","signature":"func init()","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"func init() {\n\tvclib.RegisterMetrics()\n\tcloudprovider.RegisterCloudProvider(ProviderName, func(config io.Reader) (cloudprovider.Interface, error) {\n\t\t// If vSphere.conf file is not present then it is worker node.\n\t\tif config == nil {\n\t\t\treturn newWorkerNode()\n\t\t}\n\t\tcfg, err := readConfig(config)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn newControllerNode(cfg)\n\t})\n}","line":{"from":261,"to":274}} {"id":100034614,"name":"Initialize","signature":"func (vs *VSphere) Initialize(clientBuilder cloudprovider.ControllerClientBuilder, stop \u003c-chan struct{})","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// Initialize passes a Kubernetes clientBuilder interface to the cloud provider\nfunc (vs *VSphere) Initialize(clientBuilder cloudprovider.ControllerClientBuilder, stop \u003c-chan struct{}) {\n\tvs.kubeClient = clientBuilder.ClientOrDie(\"vsphere-legacy-cloud-provider\")\n\tvs.nodeManager.SetNodeGetter(vs.kubeClient.CoreV1())\n}","line":{"from":276,"to":280}} {"id":100034615,"name":"SetInformers","signature":"func (vs *VSphere) SetInformers(informerFactory informers.SharedInformerFactory)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// Initialize Node Informers\nfunc (vs *VSphere) SetInformers(informerFactory informers.SharedInformerFactory) {\n\tif vs.cfg == nil {\n\t\treturn\n\t}\n\n\tif vs.isSecretInfoProvided {\n\t\tsecretCredentialManager := \u0026SecretCredentialManager{\n\t\t\tSecretName: vs.cfg.Global.SecretName,\n\t\t\tSecretNamespace: vs.cfg.Global.SecretNamespace,\n\t\t\tSecretLister: informerFactory.Core().V1().Secrets().Lister(),\n\t\t\tCache: \u0026SecretCache{\n\t\t\t\tVirtualCenter: make(map[string]*Credential),\n\t\t\t},\n\t\t}\n\t\tif vs.isSecretManaged {\n\t\t\tklog.V(4).Infof(\"Setting up secret informers for vSphere Cloud Provider\")\n\t\t\tsecretInformer := informerFactory.Core().V1().Secrets().Informer()\n\t\t\tsecretInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\t\t\tAddFunc: vs.SecretAdded,\n\t\t\t\tUpdateFunc: vs.SecretUpdated,\n\t\t\t})\n\t\t\tklog.V(4).Infof(\"Secret informers in vSphere cloud provider initialized\")\n\t\t}\n\t\tvs.nodeManager.UpdateCredentialManager(secretCredentialManager)\n\t}\n\n\t// Only on controller node it is required to register listeners.\n\t// Register callbacks for node updates\n\tklog.V(4).Infof(\"Setting up node informers for vSphere Cloud Provider\")\n\tnodeInformer := informerFactory.Core().V1().Nodes().Informer()\n\tnodeInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: vs.NodeAdded,\n\t\tDeleteFunc: vs.NodeDeleted,\n\t})\n\t// Register sync function for node zone/region labels\n\tnodeInformer.AddEventHandlerWithResyncPeriod(\n\t\tcache.ResourceEventHandlerFuncs{UpdateFunc: vs.syncNodeZoneLabels},\n\t\tzoneLabelsResyncPeriod,\n\t)\n\n\tnodeLister := informerFactory.Core().V1().Nodes().Lister()\n\tvs.nodeManager.SetNodeLister(nodeLister)\n\tklog.V(4).Infof(\"Node informers in vSphere cloud provider initialized\")\n\n}","line":{"from":282,"to":327}} {"id":100034616,"name":"newWorkerNode","signature":"func newWorkerNode() (*VSphere, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// Creates new worker node interface and returns\nfunc newWorkerNode() (*VSphere, error) {\n\tvar err error\n\tvs := VSphere{}\n\tvs.hostName, err = os.Hostname()\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get hostname. err: %+v\", err)\n\t\treturn nil, err\n\t}\n\tvs.vmUUID, err = GetVMUUID()\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get uuid. err: %+v\", err)\n\t\treturn nil, err\n\t}\n\treturn \u0026vs, nil\n}","line":{"from":329,"to":344}} {"id":100034617,"name":"populateVsphereInstanceMap","signature":"func populateVsphereInstanceMap(cfg *VSphereConfig) (map[string]*VSphereInstance, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"func populateVsphereInstanceMap(cfg *VSphereConfig) (map[string]*VSphereInstance, error) {\n\tvsphereInstanceMap := make(map[string]*VSphereInstance)\n\tisSecretInfoProvided := true\n\n\tif cfg.Global.SecretName == \"\" || cfg.Global.SecretNamespace == \"\" {\n\t\tklog.Warningf(\"SecretName and/or SecretNamespace is not provided. \" +\n\t\t\t\"VCP will use username and password from config file\")\n\t\tisSecretInfoProvided = false\n\t}\n\n\tif isSecretInfoProvided {\n\t\tif cfg.Global.User != \"\" {\n\t\t\tklog.Warning(\"Global.User and Secret info provided. VCP will use secret to get credentials\")\n\t\t\tcfg.Global.User = \"\"\n\t\t}\n\t\tif cfg.Global.Password != \"\" {\n\t\t\tklog.Warning(\"Global.Password and Secret info provided. VCP will use secret to get credentials\")\n\t\t\tcfg.Global.Password = \"\"\n\t\t}\n\t}\n\n\t// Check if the vsphere.conf is in old format. In this\n\t// format the cfg.VirtualCenter will be nil or empty.\n\tif cfg.VirtualCenter == nil || len(cfg.VirtualCenter) == 0 {\n\t\tklog.V(4).Infof(\"Config is not per virtual center and is in old format.\")\n\t\tif !isSecretInfoProvided {\n\t\t\tif cfg.Global.User == \"\" {\n\t\t\t\tklog.Error(\"Global.User is empty!\")\n\t\t\t\treturn nil, ErrUsernameMissing\n\t\t\t}\n\t\t\tif cfg.Global.Password == \"\" {\n\t\t\t\tklog.Error(\"Global.Password is empty!\")\n\t\t\t\treturn nil, ErrPasswordMissing\n\t\t\t}\n\t\t}\n\n\t\tif cfg.Global.WorkingDir == \"\" {\n\t\t\tklog.Error(\"Global.WorkingDir is empty!\")\n\t\t\treturn nil, errors.New(\"Global.WorkingDir is empty!\")\n\t\t}\n\t\tif cfg.Global.VCenterIP == \"\" {\n\t\t\tklog.Error(\"Global.VCenterIP is empty!\")\n\t\t\treturn nil, errors.New(\"Global.VCenterIP is empty!\")\n\t\t}\n\t\tif cfg.Global.Datacenter == \"\" {\n\t\t\tklog.Error(\"Global.Datacenter is empty!\")\n\t\t\treturn nil, errors.New(\"Global.Datacenter is empty!\")\n\t\t}\n\t\tcfg.Workspace.VCenterIP = cfg.Global.VCenterIP\n\t\tcfg.Workspace.Datacenter = cfg.Global.Datacenter\n\t\tcfg.Workspace.Folder = cfg.Global.WorkingDir\n\t\tcfg.Workspace.DefaultDatastore = cfg.Global.DefaultDatastore\n\n\t\tvcConfig := VirtualCenterConfig{\n\t\t\tUser: cfg.Global.User,\n\t\t\tPassword: cfg.Global.Password,\n\t\t\tVCenterPort: cfg.Global.VCenterPort,\n\t\t\tDatacenters: cfg.Global.Datacenter,\n\t\t\tRoundTripperCount: cfg.Global.RoundTripperCount,\n\t\t\tThumbprint: cfg.Global.Thumbprint,\n\t\t}\n\n\t\t// Note: If secrets info is provided username and password will be populated\n\t\t// once secret is created.\n\t\tvSphereConn := vclib.VSphereConnection{\n\t\t\tUsername: vcConfig.User,\n\t\t\tPassword: vcConfig.Password,\n\t\t\tHostname: cfg.Global.VCenterIP,\n\t\t\tInsecure: cfg.Global.InsecureFlag,\n\t\t\tRoundTripperCount: vcConfig.RoundTripperCount,\n\t\t\tPort: vcConfig.VCenterPort,\n\t\t\tCACert: cfg.Global.CAFile,\n\t\t\tThumbprint: cfg.Global.Thumbprint,\n\t\t}\n\n\t\tvsphereIns := VSphereInstance{\n\t\t\tconn: \u0026vSphereConn,\n\t\t\tcfg: \u0026vcConfig,\n\t\t}\n\t\tvsphereInstanceMap[cfg.Global.VCenterIP] = \u0026vsphereIns\n\t} else {\n\t\tif cfg.Workspace.VCenterIP == \"\" || cfg.Workspace.Folder == \"\" || cfg.Workspace.Datacenter == \"\" {\n\t\t\tmsg := fmt.Sprintf(\"All fields in workspace are mandatory.\"+\n\t\t\t\t\" vsphere.conf does not have the workspace specified correctly. cfg.Workspace: %+v\", cfg.Workspace)\n\t\t\tklog.Error(msg)\n\t\t\treturn nil, errors.New(msg)\n\t\t}\n\t\tif len(cfg.VirtualCenter) \u003e 1 {\n\t\t\tklog.Warning(\"Multi vCenter support is deprecated. vSphere CSI Driver does not support Kubernetes nodes spread across multiple vCenter servers. Please consider moving all Kubernetes nodes to single vCenter server\")\n\t\t}\n\n\t\tfor vcServer, vcConfig := range cfg.VirtualCenter {\n\t\t\tklog.V(4).Infof(\"Initializing vc server %s\", vcServer)\n\t\t\tif vcServer == \"\" {\n\t\t\t\tklog.Error(\"vsphere.conf does not have the VirtualCenter IP address specified\")\n\t\t\t\treturn nil, errors.New(\"vsphere.conf does not have the VirtualCenter IP address specified\")\n\t\t\t}\n\n\t\t\tif !isSecretInfoProvided {\n\t\t\t\tif vcConfig.User == \"\" {\n\t\t\t\t\tvcConfig.User = cfg.Global.User\n\t\t\t\t\tif vcConfig.User == \"\" {\n\t\t\t\t\t\tklog.Errorf(\"vcConfig.User is empty for vc %s!\", vcServer)\n\t\t\t\t\t\treturn nil, ErrUsernameMissing\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif vcConfig.Password == \"\" {\n\t\t\t\t\tvcConfig.Password = cfg.Global.Password\n\t\t\t\t\tif vcConfig.Password == \"\" {\n\t\t\t\t\t\tklog.Errorf(\"vcConfig.Password is empty for vc %s!\", vcServer)\n\t\t\t\t\t\treturn nil, ErrPasswordMissing\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif vcConfig.User != \"\" {\n\t\t\t\t\tklog.Warningf(\"vcConfig.User for server %s and Secret info provided. VCP will use secret to get credentials\", vcServer)\n\t\t\t\t\tvcConfig.User = \"\"\n\t\t\t\t}\n\t\t\t\tif vcConfig.Password != \"\" {\n\t\t\t\t\tklog.Warningf(\"vcConfig.Password for server %s and Secret info provided. VCP will use secret to get credentials\", vcServer)\n\t\t\t\t\tvcConfig.Password = \"\"\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif vcConfig.VCenterPort == \"\" {\n\t\t\t\tvcConfig.VCenterPort = cfg.Global.VCenterPort\n\t\t\t}\n\n\t\t\tif vcConfig.Datacenters == \"\" {\n\t\t\t\tif cfg.Global.Datacenters != \"\" {\n\t\t\t\t\tvcConfig.Datacenters = cfg.Global.Datacenters\n\t\t\t\t} else {\n\t\t\t\t\t// cfg.Global.Datacenter is deprecated, so giving it the last preference.\n\t\t\t\t\tvcConfig.Datacenters = cfg.Global.Datacenter\n\t\t\t\t}\n\t\t\t}\n\t\t\tif vcConfig.RoundTripperCount == 0 {\n\t\t\t\tvcConfig.RoundTripperCount = cfg.Global.RoundTripperCount\n\t\t\t}\n\n\t\t\t// Note: If secrets info is provided username and password will be populated\n\t\t\t// once secret is created.\n\t\t\tvSphereConn := vclib.VSphereConnection{\n\t\t\t\tUsername: vcConfig.User,\n\t\t\t\tPassword: vcConfig.Password,\n\t\t\t\tHostname: vcServer,\n\t\t\t\tInsecure: cfg.Global.InsecureFlag,\n\t\t\t\tRoundTripperCount: vcConfig.RoundTripperCount,\n\t\t\t\tPort: vcConfig.VCenterPort,\n\t\t\t\tCACert: cfg.Global.CAFile,\n\t\t\t\tThumbprint: vcConfig.Thumbprint,\n\t\t\t}\n\t\t\tvsphereIns := VSphereInstance{\n\t\t\t\tconn: \u0026vSphereConn,\n\t\t\t\tcfg: vcConfig,\n\t\t\t}\n\t\t\tvsphereInstanceMap[vcServer] = \u0026vsphereIns\n\t\t}\n\t}\n\treturn vsphereInstanceMap, nil\n}","line":{"from":346,"to":506}} {"id":100034618,"name":"newControllerNode","signature":"func newControllerNode(cfg VSphereConfig) (*VSphere, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// Creates new Controller node interface and returns\nfunc newControllerNode(cfg VSphereConfig) (*VSphere, error) {\n\tvs, err := buildVSphereFromConfig(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvs.hostName, err = os.Hostname()\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get hostname. err: %+v\", err)\n\t\treturn nil, err\n\t}\n\tif cfg.Global.VMUUID != \"\" {\n\t\tvs.vmUUID = cfg.Global.VMUUID\n\t} else {\n\t\tvs.vmUUID, err = getVMUUID()\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to get uuid. err: %+v\", err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\truntime.SetFinalizer(vs, logout)\n\treturn vs, nil\n}","line":{"from":511,"to":533}} {"id":100034619,"name":"buildVSphereFromConfig","signature":"func buildVSphereFromConfig(cfg VSphereConfig) (*VSphere, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// Initializes vSphere from vSphere CloudProvider Configuration\nfunc buildVSphereFromConfig(cfg VSphereConfig) (*VSphere, error) {\n\tisSecretInfoProvided := false\n\tif cfg.Global.SecretName != \"\" \u0026\u0026 cfg.Global.SecretNamespace != \"\" {\n\t\tisSecretInfoProvided = true\n\t}\n\n\tif cfg.Disk.SCSIControllerType == \"\" {\n\t\tcfg.Disk.SCSIControllerType = vclib.PVSCSIControllerType\n\t} else if !vclib.CheckControllerSupported(cfg.Disk.SCSIControllerType) {\n\t\tklog.Errorf(\"%v is not a supported SCSI Controller type. Please configure 'lsilogic-sas' OR 'pvscsi'\", cfg.Disk.SCSIControllerType)\n\t\treturn nil, errors.New(\"Controller type not supported. Please configure 'lsilogic-sas' OR 'pvscsi'\")\n\t}\n\tif cfg.Global.WorkingDir != \"\" {\n\t\tcfg.Global.WorkingDir = path.Clean(cfg.Global.WorkingDir)\n\t}\n\tif cfg.Global.RoundTripperCount == 0 {\n\t\tcfg.Global.RoundTripperCount = RoundTripperDefaultCount\n\t}\n\tif cfg.Global.VCenterPort == \"\" {\n\t\tcfg.Global.VCenterPort = \"443\"\n\t}\n\n\tvsphereInstanceMap, err := populateVsphereInstanceMap(\u0026cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvs := VSphere{\n\t\tvsphereInstanceMap: vsphereInstanceMap,\n\t\tnodeManager: \u0026NodeManager{\n\t\t\tvsphereInstanceMap: vsphereInstanceMap,\n\t\t\tnodeInfoMap: make(map[string]*NodeInfo),\n\t\t\tregisteredNodes: make(map[string]*v1.Node),\n\t\t},\n\t\tvsphereVolumeMap: NewVsphereVolumeMap(),\n\t\tisSecretInfoProvided: isSecretInfoProvided,\n\t\tisSecretManaged: !cfg.Global.SecretNotManaged,\n\t\tcfg: \u0026cfg,\n\t}\n\treturn \u0026vs, nil\n}","line":{"from":535,"to":576}} {"id":100034620,"name":"logout","signature":"func logout(vs *VSphere)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"func logout(vs *VSphere) {\n\tfor _, vsphereIns := range vs.vsphereInstanceMap {\n\t\tvsphereIns.conn.Logout(context.TODO())\n\t}\n}","line":{"from":578,"to":582}} {"id":100034621,"name":"Instances","signature":"func (vs *VSphere) Instances() (cloudprovider.Instances, bool)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// Instances returns an implementation of Instances for vSphere.\nfunc (vs *VSphere) Instances() (cloudprovider.Instances, bool) {\n\treturn vs, true\n}","line":{"from":584,"to":587}} {"id":100034622,"name":"InstancesV2","signature":"func (vs *VSphere) InstancesV2() (cloudprovider.InstancesV2, bool)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// InstancesV2 returns an implementation of InstancesV2 for vSphere.\n// TODO: implement ONLY for external cloud provider\nfunc (vs *VSphere) InstancesV2() (cloudprovider.InstancesV2, bool) {\n\treturn nil, false\n}","line":{"from":589,"to":593}} {"id":100034623,"name":"getLocalIP","signature":"func getLocalIP() ([]v1.NodeAddress, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"func getLocalIP() ([]v1.NodeAddress, error) {\n\t// hashtable with VMware-allocated OUIs for MAC filtering\n\t// List of official OUIs: http://standards-oui.ieee.org/oui.txt\n\tvmwareOUI := map[string]bool{\n\t\t\"00:05:69\": true,\n\t\t\"00:0c:29\": true,\n\t\t\"00:1c:14\": true,\n\t\t\"00:50:56\": true,\n\t}\n\n\taddrs := []v1.NodeAddress{}\n\tifaces, err := net.Interfaces()\n\tif err != nil {\n\t\tklog.Errorf(\"net.Interfaces() failed for NodeAddresses - %v\", err)\n\t\treturn nil, err\n\t}\n\tfor _, i := range ifaces {\n\t\tif i.Flags\u0026net.FlagLoopback != 0 {\n\t\t\tcontinue\n\t\t}\n\t\tlocalAddrs, err := i.Addrs()\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"Failed to extract addresses for NodeAddresses - %v\", err)\n\t\t} else {\n\t\t\tfor _, addr := range localAddrs {\n\t\t\t\tif ipnet, ok := addr.(*net.IPNet); ok {\n\t\t\t\t\tif !ipnet.IP.IsLinkLocalUnicast() {\n\t\t\t\t\t\t// Filter external IP by MAC address OUIs from vCenter and from ESX\n\t\t\t\t\t\tvmMACAddr := strings.ToLower(i.HardwareAddr.String())\n\t\t\t\t\t\t// Making sure that the MAC address is long enough\n\t\t\t\t\t\tif len(vmMACAddr) \u003c 17 {\n\t\t\t\t\t\t\tklog.V(4).Infof(\"Skipping invalid MAC address: %q\", vmMACAddr)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif vmwareOUI[vmMACAddr[:8]] {\n\t\t\t\t\t\t\tnodehelpers.AddToNodeAddresses(\u0026addrs,\n\t\t\t\t\t\t\t\tv1.NodeAddress{\n\t\t\t\t\t\t\t\t\tType: v1.NodeExternalIP,\n\t\t\t\t\t\t\t\t\tAddress: ipnet.IP.String(),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tv1.NodeAddress{\n\t\t\t\t\t\t\t\t\tType: v1.NodeInternalIP,\n\t\t\t\t\t\t\t\t\tAddress: ipnet.IP.String(),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tklog.V(4).Infof(\"Detected local IP address as %q\", ipnet.IP.String())\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tklog.V(4).Infof(\"Failed to patch IP for interface %q as MAC address %q does not belong to a VMware platform\", i.Name, vmMACAddr)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn addrs, nil\n}","line":{"from":595,"to":650}} {"id":100034624,"name":"getVSphereInstance","signature":"func (vs *VSphere) getVSphereInstance(nodeName k8stypes.NodeName) (*VSphereInstance, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"func (vs *VSphere) getVSphereInstance(nodeName k8stypes.NodeName) (*VSphereInstance, error) {\n\tvsphereIns, err := vs.nodeManager.GetVSphereInstance(nodeName)\n\tif err != nil {\n\t\tklog.Errorf(\"Cannot find node %q in cache. Node not found!!!\", nodeName)\n\t\treturn nil, err\n\t}\n\treturn \u0026vsphereIns, nil\n}","line":{"from":652,"to":659}} {"id":100034625,"name":"getVSphereInstanceForServer","signature":"func (vs *VSphere) getVSphereInstanceForServer(vcServer string, ctx context.Context) (*VSphereInstance, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"func (vs *VSphere) getVSphereInstanceForServer(vcServer string, ctx context.Context) (*VSphereInstance, error) {\n\tvsphereIns, ok := vs.vsphereInstanceMap[vcServer]\n\tif !ok {\n\t\tklog.Errorf(\"cannot find vcServer %q in cache. VC not found!!!\", vcServer)\n\t\treturn nil, fmt.Errorf(\"cannot find node %q in vsphere configuration map\", vcServer)\n\t}\n\t// Ensure client is logged in and session is valid\n\terr := vs.nodeManager.vcConnect(ctx, vsphereIns)\n\tif err != nil {\n\t\tklog.Errorf(\"failed connecting to vcServer %q with error %+v\", vcServer, err)\n\t\treturn nil, err\n\t}\n\n\treturn vsphereIns, nil\n}","line":{"from":661,"to":675}} {"id":100034626,"name":"getVMFromNodeName","signature":"func (vs *VSphere) getVMFromNodeName(ctx context.Context, nodeName k8stypes.NodeName) (*vclib.VirtualMachine, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// Get the VM Managed Object instance by from the node\nfunc (vs *VSphere) getVMFromNodeName(ctx context.Context, nodeName k8stypes.NodeName) (*vclib.VirtualMachine, error) {\n\tnodeInfo, err := vs.nodeManager.GetNodeInfo(nodeName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn nodeInfo.vm, nil\n}","line":{"from":677,"to":684}} {"id":100034627,"name":"NodeAddresses","signature":"func (vs *VSphere) NodeAddresses(ctx context.Context, nodeName k8stypes.NodeName) ([]v1.NodeAddress, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// NodeAddresses is an implementation of Instances.NodeAddresses.\nfunc (vs *VSphere) NodeAddresses(ctx context.Context, nodeName k8stypes.NodeName) ([]v1.NodeAddress, error) {\n\tif vs.hostName == convertToString(nodeName) {\n\t\treturn vs.getNodeAddressesFromLocalIP()\n\t}\n\treturn vs.getNodeAddressesFromVM(ctx, nodeName)\n}","line":{"from":686,"to":692}} {"id":100034628,"name":"getNodeAddressesFromLocalIP","signature":"func (vs *VSphere) getNodeAddressesFromLocalIP() ([]v1.NodeAddress, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// getNodeAddressesFromLocalIP get local IP addresses if node is local node.\nfunc (vs *VSphere) getNodeAddressesFromLocalIP() ([]v1.NodeAddress, error) {\n\taddrs, err := getLocalIP()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// add the hostname address\n\tnodehelpers.AddToNodeAddresses(\u0026addrs, v1.NodeAddress{Type: v1.NodeHostName, Address: vs.hostName})\n\treturn addrs, nil\n}","line":{"from":694,"to":703}} {"id":100034629,"name":"getNodeAddressesFromVM","signature":"func (vs *VSphere) getNodeAddressesFromVM(ctx context.Context, nodeName k8stypes.NodeName) ([]v1.NodeAddress, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// getNodeAddressesFromVM get vm IP addresses if node is vm.\nfunc (vs *VSphere) getNodeAddressesFromVM(ctx context.Context, nodeName k8stypes.NodeName) ([]v1.NodeAddress, error) {\n\tif vs.cfg == nil {\n\t\treturn nil, cloudprovider.InstanceNotFound\n\t}\n\n\t// Below logic can be executed only on master as VC details are present.\n\taddrs := []v1.NodeAddress{}\n\t// Create context\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\tvsi, err := vs.getVSphereInstance(nodeName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Ensure client is logged in and session is valid\n\terr = vs.nodeManager.vcConnect(ctx, vsi)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvm, err := vs.getVMFromNodeName(ctx, nodeName)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get VM object for node: %q. err: +%v\", convertToString(nodeName), err)\n\t\treturn nil, err\n\t}\n\tvmMoList, err := vm.Datacenter.GetVMMoList(ctx, []*vclib.VirtualMachine{vm}, []string{\"guest.net\"})\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get VM Managed object with property guest.net for node: %q. err: +%v\", convertToString(nodeName), err)\n\t\treturn nil, err\n\t}\n\t// retrieve VM's ip(s)\n\tfor _, v := range vmMoList[0].Guest.Net {\n\t\tif vs.cfg.Network.PublicNetwork == v.Network {\n\t\t\tfor _, ip := range v.IpAddress {\n\t\t\t\tif !netutils.ParseIPSloppy(ip).IsLinkLocalUnicast() {\n\t\t\t\t\tnodehelpers.AddToNodeAddresses(\u0026addrs,\n\t\t\t\t\t\tv1.NodeAddress{\n\t\t\t\t\t\t\tType: v1.NodeExternalIP,\n\t\t\t\t\t\t\tAddress: ip,\n\t\t\t\t\t\t}, v1.NodeAddress{\n\t\t\t\t\t\t\tType: v1.NodeInternalIP,\n\t\t\t\t\t\t\tAddress: ip,\n\t\t\t\t\t\t},\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn addrs, nil\n}","line":{"from":705,"to":755}} {"id":100034630,"name":"NodeAddressesByProviderID","signature":"func (vs *VSphere) NodeAddressesByProviderID(ctx context.Context, providerID string) ([]v1.NodeAddress, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// NodeAddressesByProviderID returns the node addresses of an instances with the specified unique providerID\n// This method will not be called from the node that is requesting this ID. i.e. metadata service\n// and other local methods cannot be used here\nfunc (vs *VSphere) NodeAddressesByProviderID(ctx context.Context, providerID string) ([]v1.NodeAddress, error) {\n\treturn vs.NodeAddresses(ctx, convertToK8sType(providerID))\n}","line":{"from":757,"to":762}} {"id":100034631,"name":"AddSSHKeyToAllInstances","signature":"func (vs *VSphere) AddSSHKeyToAllInstances(ctx context.Context, user string, keyData []byte) error","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// AddSSHKeyToAllInstances add SSH key to all instances\nfunc (vs *VSphere) AddSSHKeyToAllInstances(ctx context.Context, user string, keyData []byte) error {\n\treturn cloudprovider.NotImplemented\n}","line":{"from":764,"to":767}} {"id":100034632,"name":"CurrentNodeName","signature":"func (vs *VSphere) CurrentNodeName(ctx context.Context, hostname string) (k8stypes.NodeName, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// CurrentNodeName gives the current node name\nfunc (vs *VSphere) CurrentNodeName(ctx context.Context, hostname string) (k8stypes.NodeName, error) {\n\treturn convertToK8sType(vs.hostName), nil\n}","line":{"from":769,"to":772}} {"id":100034633,"name":"convertToString","signature":"func convertToString(nodeName k8stypes.NodeName) string","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"func convertToString(nodeName k8stypes.NodeName) string {\n\treturn string(nodeName)\n}","line":{"from":774,"to":776}} {"id":100034634,"name":"convertToK8sType","signature":"func convertToK8sType(vmName string) k8stypes.NodeName","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"func convertToK8sType(vmName string) k8stypes.NodeName {\n\treturn k8stypes.NodeName(vmName)\n}","line":{"from":778,"to":780}} {"id":100034635,"name":"InstanceExistsByProviderID","signature":"func (vs *VSphere) InstanceExistsByProviderID(ctx context.Context, providerID string) (bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// InstanceExistsByProviderID returns true if the instance with the given provider id still exists and is running.\n// If false is returned with no error, the instance will be immediately deleted by the cloud controller manager.\nfunc (vs *VSphere) InstanceExistsByProviderID(ctx context.Context, providerID string) (bool, error) {\n\tnodeName, err := vs.GetNodeNameFromProviderID(providerID)\n\tif err != nil {\n\t\tklog.Errorf(\"Error while getting nodename for providerID %s\", providerID)\n\t\treturn false, err\n\t}\n\t_, err = vs.InstanceID(ctx, convertToK8sType(nodeName))\n\tif err != nil {\n\t\tif err == cloudprovider.InstanceNotFound {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn false, err\n\t}\n\n\treturn true, nil\n}","line":{"from":782,"to":799}} {"id":100034636,"name":"InstanceShutdownByProviderID","signature":"func (vs *VSphere) InstanceShutdownByProviderID(ctx context.Context, providerID string) (bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// InstanceShutdownByProviderID returns true if the instance is in safe state to detach volumes\nfunc (vs *VSphere) InstanceShutdownByProviderID(ctx context.Context, providerID string) (bool, error) {\n\tnodeName, err := vs.GetNodeNameFromProviderID(providerID)\n\tif err != nil {\n\t\tklog.Errorf(\"Error while getting nodename for providerID %s\", providerID)\n\t\treturn false, err\n\t}\n\n\tvsi, err := vs.getVSphereInstance(convertToK8sType(nodeName))\n\tif err != nil {\n\t\treturn false, err\n\t}\n\t// Ensure client is logged in and session is valid\n\tif err := vs.nodeManager.vcConnect(ctx, vsi); err != nil {\n\t\treturn false, err\n\t}\n\tvm, err := vs.getVMFromNodeName(ctx, convertToK8sType(nodeName))\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get VM object for node: %q. err: +%v\", nodeName, err)\n\t\treturn false, err\n\t}\n\tisActive, err := vm.IsActive(ctx)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to check whether node %q is active. err: %+v.\", nodeName, err)\n\t\treturn false, err\n\t}\n\treturn !isActive, nil\n}","line":{"from":801,"to":828}} {"id":100034637,"name":"InstanceID","signature":"func (vs *VSphere) InstanceID(ctx context.Context, nodeName k8stypes.NodeName) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// InstanceID returns the cloud provider ID of the node with the specified Name.\nfunc (vs *VSphere) InstanceID(ctx context.Context, nodeName k8stypes.NodeName) (string, error) {\n\n\tinstanceIDInternal := func() (string, error) {\n\t\tif vs.hostName == convertToString(nodeName) {\n\t\t\treturn vs.vmUUID, nil\n\t\t}\n\n\t\t// Below logic can be performed only on master node where VC details are preset.\n\t\tif vs.cfg == nil {\n\t\t\treturn \"\", fmt.Errorf(\"The current node can't determine InstanceID for %q\", convertToString(nodeName))\n\t\t}\n\n\t\t// Create context\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tdefer cancel()\n\t\tvsi, err := vs.getVSphereInstance(nodeName)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\t// Ensure client is logged in and session is valid\n\t\terr = vs.nodeManager.vcConnect(ctx, vsi)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tvm, err := vs.getVMFromNodeName(ctx, nodeName)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to get VM object for node: %q. err: +%v\", convertToString(nodeName), err)\n\t\t\treturn \"\", err\n\t\t}\n\n\t\texists, err := vm.Exists(ctx)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to check whether node %q still exists. err: %+v.\", convertToString(nodeName), err)\n\t\t\treturn \"\", err\n\t\t}\n\t\tif exists {\n\t\t\treturn vs.vmUUID, nil\n\t\t}\n\n\t\tklog.Warningf(\"The VM: %s doesn't exist\", convertToString(nodeName))\n\t\treturn \"\", cloudprovider.InstanceNotFound\n\t}\n\n\tinstanceID, err := instanceIDInternal()\n\tif err != nil {\n\t\tif vclib.IsManagedObjectNotFoundError(err) {\n\t\t\terr = vs.nodeManager.RediscoverNode(nodeName)\n\t\t\tif err == nil {\n\t\t\t\tklog.V(4).Infof(\"InstanceID: Found node %q\", convertToString(nodeName))\n\t\t\t\tinstanceID, err = instanceIDInternal()\n\t\t\t} else if err == vclib.ErrNoVMFound {\n\t\t\t\treturn \"\", cloudprovider.InstanceNotFound\n\t\t\t}\n\t\t}\n\t}\n\n\treturn instanceID, err\n}","line":{"from":830,"to":888}} {"id":100034638,"name":"InstanceTypeByProviderID","signature":"func (vs *VSphere) InstanceTypeByProviderID(ctx context.Context, providerID string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// InstanceTypeByProviderID returns the cloudprovider instance type of the node with the specified unique providerID\n// This method will not be called from the node that is requesting this ID. i.e. metadata service\n// and other local methods cannot be used here\nfunc (vs *VSphere) InstanceTypeByProviderID(ctx context.Context, providerID string) (string, error) {\n\treturn \"\", nil\n}","line":{"from":890,"to":895}} {"id":100034639,"name":"InstanceType","signature":"func (vs *VSphere) InstanceType(ctx context.Context, name k8stypes.NodeName) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"func (vs *VSphere) InstanceType(ctx context.Context, name k8stypes.NodeName) (string, error) {\n\treturn \"\", nil\n}","line":{"from":897,"to":899}} {"id":100034640,"name":"Clusters","signature":"func (vs *VSphere) Clusters() (cloudprovider.Clusters, bool)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"func (vs *VSphere) Clusters() (cloudprovider.Clusters, bool) {\n\treturn nil, true\n}","line":{"from":901,"to":903}} {"id":100034641,"name":"ProviderName","signature":"func (vs *VSphere) ProviderName() string","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// ProviderName returns the cloud provider ID.\nfunc (vs *VSphere) ProviderName() string {\n\treturn ProviderName\n}","line":{"from":905,"to":908}} {"id":100034642,"name":"LoadBalancer","signature":"func (vs *VSphere) LoadBalancer() (cloudprovider.LoadBalancer, bool)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// LoadBalancer returns an implementation of LoadBalancer for vSphere.\nfunc (vs *VSphere) LoadBalancer() (cloudprovider.LoadBalancer, bool) {\n\treturn nil, false\n}","line":{"from":910,"to":913}} {"id":100034643,"name":"isZoneEnabled","signature":"func (vs *VSphere) isZoneEnabled() bool","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"func (vs *VSphere) isZoneEnabled() bool {\n\tisEnabled := vs.cfg != nil \u0026\u0026 vs.cfg.Labels.Zone != \"\" \u0026\u0026 vs.cfg.Labels.Region != \"\"\n\t// Return false within kubelet in case of credentials stored in secret.\n\t// Otherwise kubelet will not be able to obtain zone labels from vSphere and create initial node\n\t// due to no credentials at this step.\n\t// See https://github.com/kubernetes/kubernetes/blob/b960f7a0e04687c17e0b0801e17e7cab89f273cc/pkg/kubelet/kubelet_node_status.go#L384-L386\n\tif isEnabled \u0026\u0026 vs.isSecretInfoProvided \u0026\u0026 vs.nodeManager.credentialManager == nil {\n\t\tklog.V(1).Info(\"Zones can not be populated now due to credentials in Secret, skip.\")\n\t\treturn false\n\t}\n\treturn isEnabled\n}","line":{"from":915,"to":926}} {"id":100034644,"name":"Zones","signature":"func (vs *VSphere) Zones() (cloudprovider.Zones, bool)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// Zones returns an implementation of Zones for vSphere.\nfunc (vs *VSphere) Zones() (cloudprovider.Zones, bool) {\n\tif vs.isZoneEnabled() {\n\t\treturn vs, true\n\t}\n\tklog.V(1).Info(\"The vSphere cloud provider does not support zones\")\n\treturn nil, false\n}","line":{"from":928,"to":935}} {"id":100034645,"name":"Routes","signature":"func (vs *VSphere) Routes() (cloudprovider.Routes, bool)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// Routes returns a false since the interface is not supported for vSphere.\nfunc (vs *VSphere) Routes() (cloudprovider.Routes, bool) {\n\treturn nil, false\n}","line":{"from":937,"to":940}} {"id":100034646,"name":"AttachDisk","signature":"func (vs *VSphere) AttachDisk(vmDiskPath string, storagePolicyName string, nodeName k8stypes.NodeName) (diskUUID string, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// AttachDisk attaches given virtual disk volume to the compute running kubelet.\nfunc (vs *VSphere) AttachDisk(vmDiskPath string, storagePolicyName string, nodeName k8stypes.NodeName) (diskUUID string, err error) {\n\tattachDiskInternal := func(vmDiskPath string, storagePolicyName string, nodeName k8stypes.NodeName) (diskUUID string, err error) {\n\t\tif nodeName == \"\" {\n\t\t\tnodeName = convertToK8sType(vs.hostName)\n\t\t}\n\t\t// Create context\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tdefer cancel()\n\t\tvsi, err := vs.getVSphereInstance(nodeName)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\t// Ensure client is logged in and session is valid\n\t\terr = vs.nodeManager.vcConnect(ctx, vsi)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tvm, err := vs.getVMFromNodeName(ctx, nodeName)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to get VM object for node: %q. err: +%v\", convertToString(nodeName), err)\n\t\t\treturn \"\", err\n\t\t}\n\n\t\t// try and get canonical path for disk and if we can't use provided vmDiskPath\n\t\tcanonicalPath, pathFetchErr := getcanonicalVolumePath(ctx, vm.Datacenter, vmDiskPath)\n\t\tif canonicalPath != \"\" \u0026\u0026 pathFetchErr == nil {\n\t\t\tvmDiskPath = canonicalPath\n\t\t}\n\n\t\tdiskUUID, err = vm.AttachDisk(ctx, vmDiskPath, \u0026vclib.VolumeOptions{SCSIControllerType: vclib.PVSCSIControllerType, StoragePolicyName: storagePolicyName})\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to attach disk: %s for node: %s. err: +%v\", vmDiskPath, convertToString(nodeName), err)\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn diskUUID, nil\n\t}\n\trequestTime := time.Now()\n\tdiskUUID, err = attachDiskInternal(vmDiskPath, storagePolicyName, nodeName)\n\tif err != nil {\n\t\tif vclib.IsManagedObjectNotFoundError(err) {\n\t\t\terr = vs.nodeManager.RediscoverNode(nodeName)\n\t\t\tif err == nil {\n\t\t\t\tklog.V(4).Infof(\"AttachDisk: Found node %q\", convertToString(nodeName))\n\t\t\t\tdiskUUID, err = attachDiskInternal(vmDiskPath, storagePolicyName, nodeName)\n\t\t\t\tklog.V(4).Infof(\"AttachDisk: Retry: diskUUID %s, err +%v\", diskUUID, err)\n\t\t\t}\n\t\t}\n\t}\n\tklog.V(4).Infof(\"AttachDisk executed for node %s and volume %s with diskUUID %s. Err: %s\", convertToString(nodeName), vmDiskPath, diskUUID, err)\n\tif err != nil {\n\t\t// if attach failed, we should check if disk is attached somewhere else. This can happen for several reasons\n\t\t// and throwing a dangling volume error here will allow attach-detach controller to detach disk from a node\n\t\t// where it is not needed.\n\t\texistingNode, ok := vs.vsphereVolumeMap.CheckForVolume(vmDiskPath)\n\t\tif ok {\n\t\t\tattached, newVolumePath, diskAttachedError := vs.DiskIsAttached(vmDiskPath, existingNode)\n\t\t\t// if disk is attached somewhere else then we can throw a dangling error\n\t\t\tif diskAttachedError == nil \u0026\u0026 attached \u0026\u0026 (nodeName != existingNode) {\n\t\t\t\tklog.V(3).Infof(\"found dangling volume %s to node %s\", vmDiskPath, existingNode)\n\t\t\t\treturn \"\", volerr.NewDanglingError(err.Error(), existingNode, newVolumePath)\n\t\t\t}\n\t\t}\n\t}\n\tvclib.RecordvSphereMetric(vclib.OperationAttachVolume, requestTime, err)\n\treturn diskUUID, err\n}","line":{"from":942,"to":1009}} {"id":100034647,"name":"DetachDisk","signature":"func (vs *VSphere) DetachDisk(volPath string, nodeName k8stypes.NodeName) error","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// DetachDisk detaches given virtual disk volume from the compute running kubelet.\nfunc (vs *VSphere) DetachDisk(volPath string, nodeName k8stypes.NodeName) error {\n\tdetachDiskInternal := func(volPath string, nodeName k8stypes.NodeName) error {\n\t\tif nodeName == \"\" {\n\t\t\tnodeName = convertToK8sType(vs.hostName)\n\t\t}\n\t\t// Create context\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tdefer cancel()\n\t\tvsi, err := vs.getVSphereInstance(nodeName)\n\t\tif err != nil {\n\t\t\t// If node doesn't exist, disk is already detached from node.\n\t\t\tif err == vclib.ErrNoVMFound {\n\t\t\t\tklog.Infof(\"Node %q does not exist, disk %s is already detached from node.\", convertToString(nodeName), volPath)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\t// Ensure client is logged in and session is valid\n\t\terr = vs.nodeManager.vcConnect(ctx, vsi)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvm, err := vs.getVMFromNodeName(ctx, nodeName)\n\t\tif err != nil {\n\t\t\t// If node doesn't exist, disk is already detached from node.\n\t\t\tif err == vclib.ErrNoVMFound {\n\t\t\t\tklog.Infof(\"Node %q does not exist, disk %s is already detached from node.\", convertToString(nodeName), volPath)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tklog.Errorf(\"Failed to get VM object for node: %q. err: +%v\", convertToString(nodeName), err)\n\t\t\treturn err\n\t\t}\n\t\terr = vm.DetachDisk(ctx, volPath)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to detach disk: %s for node: %s. err: +%v\", volPath, convertToString(nodeName), err)\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\trequestTime := time.Now()\n\terr := detachDiskInternal(volPath, nodeName)\n\tif err != nil {\n\t\tif vclib.IsManagedObjectNotFoundError(err) {\n\t\t\terr = vs.nodeManager.RediscoverNode(nodeName)\n\t\t\tif err == nil {\n\t\t\t\terr = detachDiskInternal(volPath, nodeName)\n\t\t\t}\n\t\t}\n\t}\n\tvclib.RecordvSphereMetric(vclib.OperationDetachVolume, requestTime, err)\n\treturn err\n}","line":{"from":1011,"to":1064}} {"id":100034648,"name":"DiskIsAttached","signature":"func (vs *VSphere) DiskIsAttached(volPath string, nodeName k8stypes.NodeName) (bool, string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// DiskIsAttached returns if disk is attached to the VM using controllers supported by the plugin.\nfunc (vs *VSphere) DiskIsAttached(volPath string, nodeName k8stypes.NodeName) (bool, string, error) {\n\tdiskIsAttachedInternal := func(volPath string, nodeName k8stypes.NodeName) (bool, string, error) {\n\t\tvar vSphereInstance string\n\t\tif nodeName == \"\" {\n\t\t\tvSphereInstance = vs.hostName\n\t\t\tnodeName = convertToK8sType(vSphereInstance)\n\t\t} else {\n\t\t\tvSphereInstance = convertToString(nodeName)\n\t\t}\n\t\t// Create context\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tdefer cancel()\n\t\tvsi, err := vs.getVSphereInstance(nodeName)\n\t\tif err != nil {\n\t\t\treturn false, volPath, err\n\t\t}\n\t\t// Ensure client is logged in and session is valid\n\t\terr = vs.nodeManager.vcConnect(ctx, vsi)\n\t\tif err != nil {\n\t\t\treturn false, volPath, err\n\t\t}\n\t\tvm, err := vs.getVMFromNodeName(ctx, nodeName)\n\t\tif err != nil {\n\t\t\tif err == vclib.ErrNoVMFound {\n\t\t\t\tklog.Warningf(\"Node %q does not exist, vsphere CP will assume disk %v is not attached to it.\", nodeName, volPath)\n\t\t\t\t// make the disk as detached and return false without error.\n\t\t\t\treturn false, volPath, nil\n\t\t\t}\n\t\t\tklog.Errorf(\"Failed to get VM object for node: %q. err: +%v\", vSphereInstance, err)\n\t\t\treturn false, volPath, err\n\t\t}\n\n\t\tvolPath = vclib.RemoveStorageClusterORFolderNameFromVDiskPath(volPath)\n\t\tcanonicalPath, pathFetchErr := getcanonicalVolumePath(ctx, vm.Datacenter, volPath)\n\t\t// if canonicalPath is not empty string and pathFetchErr is nil then we can use canonical path to perform detach\n\t\tif canonicalPath != \"\" \u0026\u0026 pathFetchErr == nil {\n\t\t\tvolPath = canonicalPath\n\t\t}\n\t\tattached, err := vm.IsDiskAttached(ctx, volPath)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"DiskIsAttached failed to determine whether disk %q is still attached on node %q\",\n\t\t\t\tvolPath,\n\t\t\t\tvSphereInstance)\n\t\t}\n\t\tklog.V(4).Infof(\"DiskIsAttached result: %v and error: %q, for volume: %q\", attached, err, volPath)\n\t\treturn attached, volPath, err\n\t}\n\trequestTime := time.Now()\n\tisAttached, newVolumePath, err := diskIsAttachedInternal(volPath, nodeName)\n\tif err != nil {\n\t\tif vclib.IsManagedObjectNotFoundError(err) {\n\t\t\terr = vs.nodeManager.RediscoverNode(nodeName)\n\t\t\tif err == vclib.ErrNoVMFound {\n\t\t\t\tisAttached, err = false, nil\n\t\t\t} else if err == nil {\n\t\t\t\tisAttached, newVolumePath, err = diskIsAttachedInternal(volPath, nodeName)\n\t\t\t}\n\t\t}\n\t}\n\tvclib.RecordvSphereMetric(vclib.OperationDiskIsAttached, requestTime, err)\n\treturn isAttached, newVolumePath, err\n}","line":{"from":1066,"to":1128}} {"id":100034649,"name":"DisksAreAttached","signature":"func (vs *VSphere) DisksAreAttached(nodeVolumes map[k8stypes.NodeName][]string) (map[k8stypes.NodeName]map[string]bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// DisksAreAttached returns if disks are attached to the VM using controllers supported by the plugin.\n// 1. Converts volPaths into canonical form so that it can be compared with the VM device path.\n// 2. Segregates nodes by vCenter and Datacenter they are present in. This reduces calls to VC.\n// 3. Creates go routines per VC-DC to find whether disks are attached to the nodes.\n// 4. If the some of the VMs are not found or migrated then they are added to a list.\n// 5. After successful execution of goroutines,\n// 5a. If there are any VMs which needs to be retried, they are rediscovered and the whole operation is initiated again for only rediscovered VMs.\n// 5b. If VMs are removed from vSphere inventory they are ignored.\nfunc (vs *VSphere) DisksAreAttached(nodeVolumes map[k8stypes.NodeName][]string) (map[k8stypes.NodeName]map[string]bool, error) {\n\tdisksAreAttachedInternal := func(nodeVolumes map[k8stypes.NodeName][]string) (map[k8stypes.NodeName]map[string]bool, error) {\n\t\tvs.vsphereVolumeMap.StartDiskVerification()\n\n\t\t// disksAreAttach checks whether disks are attached to the nodes.\n\t\t// Returns nodes that need to be retried if retry is true\n\t\t// Segregates nodes per VC and DC\n\t\t// Creates go routines per VC-DC to find whether disks are attached to the nodes.\n\t\tdisksAreAttach := func(ctx context.Context, nodeVolumes map[k8stypes.NodeName][]string, attached map[string]map[string]bool, retry bool) ([]k8stypes.NodeName, error) {\n\n\t\t\tvar wg sync.WaitGroup\n\t\t\tvar localAttachedMaps []map[string]map[string]bool\n\t\t\tvar nodesToRetry []k8stypes.NodeName\n\t\t\tvar globalErr error\n\t\t\tglobalErr = nil\n\t\t\tglobalErrMutex := \u0026sync.Mutex{}\n\t\t\tnodesToRetryMutex := \u0026sync.Mutex{}\n\n\t\t\t// Segregate nodes according to VC-DC\n\t\t\tdcNodes := make(map[string][]k8stypes.NodeName)\n\t\t\tfor nodeName := range nodeVolumes {\n\t\t\t\tnodeInfo, err := vs.nodeManager.GetNodeInfo(nodeName)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Errorf(\"Failed to get node info: %+v. err: %+v\", nodeInfo.vm, err)\n\t\t\t\t\treturn nodesToRetry, err\n\t\t\t\t}\n\t\t\t\tVC_DC := nodeInfo.vcServer + nodeInfo.dataCenter.String()\n\t\t\t\tdcNodes[VC_DC] = append(dcNodes[VC_DC], nodeName)\n\t\t\t}\n\n\t\t\tfor _, nodeNames := range dcNodes {\n\t\t\t\tlocalAttachedMap := make(map[string]map[string]bool)\n\t\t\t\tlocalAttachedMaps = append(localAttachedMaps, localAttachedMap)\n\t\t\t\t// Start go routines per VC-DC to check disks are attached\n\t\t\t\tgo func(nodes []k8stypes.NodeName) {\n\t\t\t\t\tnodesToRetryLocal, err := vs.checkDiskAttached(ctx, nodes, nodeVolumes, localAttachedMap, retry)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tif !vclib.IsManagedObjectNotFoundError(err) {\n\t\t\t\t\t\t\tglobalErrMutex.Lock()\n\t\t\t\t\t\t\tglobalErr = err\n\t\t\t\t\t\t\tglobalErrMutex.Unlock()\n\t\t\t\t\t\t\tklog.Errorf(\"Failed to check disk attached for nodes: %+v. err: %+v\", nodes, err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tnodesToRetryMutex.Lock()\n\t\t\t\t\tnodesToRetry = append(nodesToRetry, nodesToRetryLocal...)\n\t\t\t\t\tnodesToRetryMutex.Unlock()\n\t\t\t\t\twg.Done()\n\t\t\t\t}(nodeNames)\n\t\t\t\twg.Add(1)\n\t\t\t}\n\t\t\twg.Wait()\n\t\t\tif globalErr != nil {\n\t\t\t\treturn nodesToRetry, globalErr\n\t\t\t}\n\t\t\tfor _, localAttachedMap := range localAttachedMaps {\n\t\t\t\tfor key, value := range localAttachedMap {\n\t\t\t\t\tattached[key] = value\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nodesToRetry, nil\n\t\t}\n\n\t\tklog.V(4).Infof(\"Starting DisksAreAttached API for vSphere with nodeVolumes: %+v\", nodeVolumes)\n\t\t// Create context\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tdefer cancel()\n\n\t\tdisksAttached := make(map[k8stypes.NodeName]map[string]bool)\n\t\tif len(nodeVolumes) == 0 {\n\t\t\treturn disksAttached, nil\n\t\t}\n\n\t\t// Convert VolPaths into canonical form so that it can be compared with the VM device path.\n\t\tvmVolumes, err := vs.convertVolPathsToDevicePaths(ctx, nodeVolumes)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to convert volPaths to devicePaths: %+v. err: %+v\", nodeVolumes, err)\n\t\t\treturn nil, err\n\t\t}\n\t\tattached := make(map[string]map[string]bool)\n\t\tnodesToRetry, err := disksAreAttach(ctx, vmVolumes, attached, false)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif len(nodesToRetry) != 0 {\n\t\t\t// Rediscover nodes which are need to be retried\n\t\t\tremainingNodesVolumes := make(map[k8stypes.NodeName][]string)\n\t\t\tfor _, nodeName := range nodesToRetry {\n\t\t\t\terr = vs.nodeManager.RediscoverNode(nodeName)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif err == vclib.ErrNoVMFound {\n\t\t\t\t\t\tklog.V(4).Infof(\"node %s not found. err: %+v\", nodeName, err)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tklog.Errorf(\"Failed to rediscover node %s. err: %+v\", nodeName, err)\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tremainingNodesVolumes[nodeName] = nodeVolumes[nodeName]\n\t\t\t}\n\n\t\t\t// If some remaining nodes are still registered\n\t\t\tif len(remainingNodesVolumes) != 0 {\n\t\t\t\tnodesToRetry, err = disksAreAttach(ctx, remainingNodesVolumes, attached, true)\n\t\t\t\tif err != nil || len(nodesToRetry) != 0 {\n\t\t\t\t\tklog.Errorf(\"Failed to retry disksAreAttach for nodes %+v. err: %+v\", remainingNodesVolumes, err)\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor nodeName, volPaths := range attached {\n\t\t\t\tdisksAttached[convertToK8sType(nodeName)] = volPaths\n\t\t\t}\n\n\t\t}\n\t\tklog.V(4).Infof(\"DisksAreAttached successfully executed. result: %+v\", attached)\n\t\t// There could be nodes in cluster which do not have any pods with vsphere volumes running on them\n\t\t// such nodes won't be part of nodeVolumes map because attach-detach controller does not keep track\n\t\t// such nodes. But such nodes may still have dangling volumes on them and hence we need to scan all the\n\t\t// remaining nodes which weren't scanned by code previously.\n\t\tvs.BuildMissingVolumeNodeMap(ctx)\n\t\t// any volume which we could not verify will be removed from the map.\n\t\tvs.vsphereVolumeMap.RemoveUnverified()\n\t\tklog.V(4).Infof(\"current node volume map is: %+v\", vs.vsphereVolumeMap.volumeNodeMap)\n\t\treturn disksAttached, nil\n\t}\n\trequestTime := time.Now()\n\tattached, err := disksAreAttachedInternal(nodeVolumes)\n\tvclib.RecordvSphereMetric(vclib.OperationDisksAreAttached, requestTime, err)\n\treturn attached, err\n}","line":{"from":1130,"to":1269}} {"id":100034650,"name":"CreateVolume","signature":"func (vs *VSphere) CreateVolume(volumeOptions *vclib.VolumeOptions) (canonicalVolumePath string, err error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// CreateVolume creates a volume of given size (in KiB) and return the volume path.\n// If the volumeOptions.Datastore is part of datastore cluster for example - [DatastoreCluster/sharedVmfs-0] then\n// return value will be [DatastoreCluster/sharedVmfs-0] kubevols/\u003cvolume-name\u003e.vmdk\n// else return value will be [sharedVmfs-0] kubevols/\u003cvolume-name\u003e.vmdk\nfunc (vs *VSphere) CreateVolume(volumeOptions *vclib.VolumeOptions) (canonicalVolumePath string, err error) {\n\tklog.V(1).Infof(\"Starting to create a vSphere volume with volumeOptions: %+v\", volumeOptions)\n\tcreateVolumeInternal := func(volumeOptions *vclib.VolumeOptions) (canonicalVolumePath string, err error) {\n\t\tvar datastoreInfo *vclib.DatastoreInfo\n\t\tvar dsList []*vclib.DatastoreInfo\n\n\t\t// Create context\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tdefer cancel()\n\t\tvsi, err := vs.getVSphereInstanceForServer(vs.cfg.Workspace.VCenterIP, ctx)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\t// If datastore not specified, then use default datastore\n\t\tdatastoreName := strings.TrimSpace(volumeOptions.Datastore)\n\t\tif datastoreName == \"\" {\n\t\t\tdatastoreName = strings.TrimSpace(vs.cfg.Workspace.DefaultDatastore)\n\t\t}\n\t\t// The given datastoreName may be present in more than one datacenter\n\t\tcandidateDatastoreInfos, err := vs.FindDatastoreByName(ctx, datastoreName)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\t// Each of the datastores found is a candidate for Volume creation.\n\t\t// One of these will be selected based on given policy and/or zone.\n\t\tcandidateDatastores := make(map[string]*vclib.DatastoreInfo)\n\t\tfor _, dsInfo := range candidateDatastoreInfos {\n\t\t\tcandidateDatastores[dsInfo.Info.Url] = dsInfo\n\t\t}\n\n\t\tvar vmOptions *vclib.VMOptions\n\t\tvar zonesToSearch []string\n\n\t\tif volumeOptions.SelectedNode != nil {\n\t\t\tif len(volumeOptions.Zone) \u003e 1 {\n\t\t\t\t// In waitForFirstConsumer mode, if more than one allowedTopologies is specified, the volume should satisfy all these.\n\t\t\t\tzonesToSearch = volumeOptions.Zone\n\t\t\t} else {\n\t\t\t\t// Pick the selectedNode's zone, if available.\n\t\t\t\tnodeInfo, err := vs.nodeManager.GetNodeInfoWithNodeObject(volumeOptions.SelectedNode)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Errorf(\"Unable to get node information for %s. err: %+v\", volumeOptions.SelectedNode.Name, err)\n\t\t\t\t\treturn \"\", err\n\t\t\t\t}\n\t\t\t\tklog.V(4).Infof(\"selectedNode info : %s\", nodeInfo)\n\t\t\t\tif nodeInfo.zone != nil \u0026\u0026 nodeInfo.zone.FailureDomain != \"\" {\n\t\t\t\t\tzonesToSearch = append(zonesToSearch, nodeInfo.zone.FailureDomain)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// If no selectedNode, pick allowedTopologies, if provided.\n\t\t\tzonesToSearch = volumeOptions.Zone\n\t\t}\n\t\tklog.V(1).Infof(\"Volume topology : %s\", zonesToSearch)\n\n\t\tif volumeOptions.VSANStorageProfileData != \"\" || volumeOptions.StoragePolicyName != \"\" {\n\t\t\t// If datastore and zone are specified, first validate if the datastore is in the provided zone.\n\t\t\tif len(zonesToSearch) != 0 \u0026\u0026 volumeOptions.Datastore != \"\" {\n\t\t\t\tklog.V(4).Infof(\"Specified zone : %s, datastore : %s\", zonesToSearch, volumeOptions.Datastore)\n\t\t\t\tdsList, err = getDatastoresForZone(ctx, vs.nodeManager, zonesToSearch)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Errorf(\"Failed to find a shared datastore matching zone %s. err: %+v\", zonesToSearch, err)\n\t\t\t\t\treturn \"\", err\n\t\t\t\t}\n\n\t\t\t\t// Validate if the datastore provided belongs to the zone. If not, fail the operation.\n\t\t\t\tfound := false\n\t\t\t\tfor _, ds := range dsList {\n\t\t\t\t\tif datastoreInfo, found = candidateDatastores[ds.Info.Url]; found {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !found {\n\t\t\t\t\terr := fmt.Errorf(\"The specified datastore %s does not match the provided zones : %s\", volumeOptions.Datastore, zonesToSearch)\n\t\t\t\t\tklog.Error(err)\n\t\t\t\t\treturn \"\", err\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Acquire a read lock to ensure multiple PVC requests can be processed simultaneously.\n\t\t\tcleanUpDummyVMLock.RLock()\n\t\t\tdefer cleanUpDummyVMLock.RUnlock()\n\t\t\t// Create a new background routine that will delete any dummy VM's that are left stale.\n\t\t\t// This routine will get executed for every 5 minutes and gets initiated only once in its entire lifetime.\n\t\t\tcleanUpRoutineInitLock.Lock()\n\t\t\tif !cleanUpRoutineInitialized {\n\t\t\t\tklog.V(1).Infof(\"Starting a clean up routine to remove stale dummy VM's\")\n\t\t\t\tgo vs.cleanUpDummyVMs(DummyVMPrefixName)\n\t\t\t\tcleanUpRoutineInitialized = true\n\t\t\t}\n\t\t\tcleanUpRoutineInitLock.Unlock()\n\t\t}\n\t\tif volumeOptions.StoragePolicyName != \"\" \u0026\u0026 volumeOptions.Datastore == \"\" {\n\t\t\tif len(zonesToSearch) == 0 {\n\t\t\t\tklog.V(4).Infof(\"Selecting a shared datastore as per the storage policy %s\", volumeOptions.StoragePolicyName)\n\t\t\t\tdatastoreInfo, err = getPbmCompatibleDatastore(ctx, vsi.conn.Client, volumeOptions.StoragePolicyName, vs.nodeManager)\n\t\t\t} else {\n\t\t\t\t// If zone is specified, first get the datastores in the zone.\n\t\t\t\tdsList, err = getDatastoresForZone(ctx, vs.nodeManager, zonesToSearch)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Errorf(\"Failed to find a shared datastore matching zone %s. err: %+v\", zonesToSearch, err)\n\t\t\t\t\treturn \"\", err\n\t\t\t\t}\n\n\t\t\t\tklog.V(4).Infof(\"Specified zone : %s. Picking a datastore as per the storage policy %s among the zoned datastores : %s\", zonesToSearch,\n\t\t\t\t\tvolumeOptions.StoragePolicyName, dsList)\n\t\t\t\t// Among the compatible datastores, select the one based on the maximum free space.\n\t\t\t\tdatastoreInfo, err = getPbmCompatibleZonedDatastore(ctx, vsi.conn.Client, volumeOptions.StoragePolicyName, dsList)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"Failed to get pbm compatible datastore with storagePolicy: %s. err: %+v\", volumeOptions.StoragePolicyName, err)\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\tklog.V(1).Infof(\"Datastore selected as per policy : %s\", datastoreInfo.Info.Name)\n\t\t} else {\n\t\t\t// If zone is specified, pick the datastore in the zone with maximum free space within the zone.\n\t\t\tif volumeOptions.Datastore == \"\" \u0026\u0026 len(zonesToSearch) != 0 {\n\t\t\t\tklog.V(4).Infof(\"Specified zone : %s\", zonesToSearch)\n\t\t\t\tdsList, err = getDatastoresForZone(ctx, vs.nodeManager, zonesToSearch)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Errorf(\"Failed to find a shared datastore matching zone %s. err: %+v\", zonesToSearch, err)\n\t\t\t\t\treturn \"\", err\n\t\t\t\t}\n\t\t\t\t// If unable to get any datastore, fail the operation\n\t\t\t\tif len(dsList) == 0 {\n\t\t\t\t\terr := fmt.Errorf(\"Failed to find a shared datastore matching zone %s\", zonesToSearch)\n\t\t\t\t\tklog.Error(err)\n\t\t\t\t\treturn \"\", err\n\t\t\t\t}\n\n\t\t\t\tdatastoreInfo, err = getMostFreeDatastore(ctx, nil, dsList)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Errorf(\"Failed to get shared datastore: %+v\", err)\n\t\t\t\t\treturn \"\", err\n\t\t\t\t}\n\t\t\t\tklog.V(1).Infof(\"Specified zone : %s. Selected datastore : %s\", zonesToSearch, datastoreInfo.Info.Name)\n\t\t\t} else {\n\t\t\t\tvar sharedDsList []*vclib.DatastoreInfo\n\t\t\t\tvar err error\n\t\t\t\tif len(zonesToSearch) == 0 {\n\t\t\t\t\t// If zone is not provided, get the shared datastore across all node VMs.\n\t\t\t\t\tklog.V(4).Infof(\"Validating if datastore %s is shared across all node VMs\", datastoreName)\n\t\t\t\t\tsharedDSFinder := \u0026sharedDatastore{\n\t\t\t\t\t\tnodeManager: vs.nodeManager,\n\t\t\t\t\t\tcandidateDatastores: candidateDatastoreInfos,\n\t\t\t\t\t}\n\t\t\t\t\tdatastoreInfo, err = sharedDSFinder.getSharedDatastore(ctx)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tklog.Errorf(\"Failed to get shared datastore: %+v\", err)\n\t\t\t\t\t\treturn \"\", err\n\t\t\t\t\t}\n\t\t\t\t\tif datastoreInfo == nil {\n\t\t\t\t\t\terr = fmt.Errorf(\"The specified datastore %s is not a shared datastore across node VMs\", datastoreName)\n\t\t\t\t\t\tklog.Error(err)\n\t\t\t\t\t\treturn \"\", err\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// If zone is provided, get the shared datastores in that zone.\n\t\t\t\t\tklog.V(4).Infof(\"Validating if datastore %s is in zone %s \", datastoreName, zonesToSearch)\n\t\t\t\t\tsharedDsList, err = getDatastoresForZone(ctx, vs.nodeManager, zonesToSearch)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tklog.Errorf(\"Failed to find a shared datastore matching zone %s. err: %+v\", zonesToSearch, err)\n\t\t\t\t\t\treturn \"\", err\n\t\t\t\t\t}\n\t\t\t\t\tfound := false\n\t\t\t\t\tfor _, sharedDs := range sharedDsList {\n\t\t\t\t\t\tif datastoreInfo, found = candidateDatastores[sharedDs.Info.Url]; found {\n\t\t\t\t\t\t\tklog.V(4).Infof(\"Datastore validation succeeded\")\n\t\t\t\t\t\t\tfound = true\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif !found {\n\t\t\t\t\t\terr = fmt.Errorf(\"The specified datastore %s does not match the provided zones : %s\", datastoreName, zonesToSearch)\n\t\t\t\t\t\tklog.Error(err)\n\t\t\t\t\t\treturn \"\", err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// if datastoreInfo is still not determined, it is an error condition\n\t\tif datastoreInfo == nil {\n\t\t\tklog.Errorf(\"ambiguous datastore name %s, cannot be found among: %v\", datastoreName, candidateDatastoreInfos)\n\t\t\treturn \"\", fmt.Errorf(\"ambiguous datastore name %s\", datastoreName)\n\t\t}\n\t\tds := datastoreInfo.Datastore\n\t\tvolumeOptions.Datastore = datastoreInfo.Info.Name\n\t\tvmOptions, err = vs.setVMOptions(ctx, vsi.conn, ds)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"failed to set VM options required to create a vsphere volume. err: %+v\", err)\n\t\t\treturn \"\", err\n\t\t}\n\t\tkubeVolsPath := filepath.Clean(ds.Path(VolDir)) + \"/\"\n\t\terr = ds.CreateDirectory(ctx, kubeVolsPath, false)\n\t\tif err != nil \u0026\u0026 err != vclib.ErrFileAlreadyExist {\n\t\t\tklog.Errorf(\"Cannot create dir %#v. err %s\", kubeVolsPath, err)\n\t\t\treturn \"\", err\n\t\t}\n\t\tvolumePath := kubeVolsPath + volumeOptions.Name + \".vmdk\"\n\t\tdisk := diskmanagers.VirtualDisk{\n\t\t\tDiskPath: volumePath,\n\t\t\tVolumeOptions: volumeOptions,\n\t\t\tVMOptions: vmOptions,\n\t\t}\n\t\tvolumePath, err = disk.Create(ctx, ds)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to create a vsphere volume with volumeOptions: %+v on datastore: %s. err: %+v\", volumeOptions, ds, err)\n\t\t\treturn \"\", err\n\t\t}\n\t\t// Get the canonical path for the volume path.\n\t\tcanonicalVolumePath, err = getcanonicalVolumePath(ctx, datastoreInfo.Datacenter, volumePath)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to get canonical vsphere volume path for volume: %s with volumeOptions: %+v on datastore: %s. err: %+v\", volumePath, volumeOptions, ds, err)\n\t\t\treturn \"\", err\n\t\t}\n\t\tif filepath.Base(datastoreName) != datastoreName {\n\t\t\t// If datastore is within cluster, add cluster path to the volumePath\n\t\t\tcanonicalVolumePath = strings.Replace(canonicalVolumePath, filepath.Base(datastoreName), datastoreName, 1)\n\t\t}\n\t\treturn canonicalVolumePath, nil\n\t}\n\trequestTime := time.Now()\n\tcanonicalVolumePath, err = createVolumeInternal(volumeOptions)\n\tvclib.RecordCreateVolumeMetric(volumeOptions, requestTime, err)\n\tklog.V(4).Infof(\"The canonical volume path for the newly created vSphere volume is %q\", canonicalVolumePath)\n\treturn canonicalVolumePath, err\n}","line":{"from":1271,"to":1503}} {"id":100034651,"name":"DeleteVolume","signature":"func (vs *VSphere) DeleteVolume(vmDiskPath string) error","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// DeleteVolume deletes a volume given volume name.\nfunc (vs *VSphere) DeleteVolume(vmDiskPath string) error {\n\tklog.V(1).Infof(\"Starting to delete vSphere volume with vmDiskPath: %s\", vmDiskPath)\n\tdeleteVolumeInternal := func(vmDiskPath string) error {\n\t\t// Create context\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tdefer cancel()\n\t\tvsi, err := vs.getVSphereInstanceForServer(vs.cfg.Workspace.VCenterIP, ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdc, err := vclib.GetDatacenter(ctx, vsi.conn, vs.cfg.Workspace.Datacenter)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdisk := diskmanagers.VirtualDisk{\n\t\t\tDiskPath: vmDiskPath,\n\t\t\tVolumeOptions: \u0026vclib.VolumeOptions{},\n\t\t\tVMOptions: \u0026vclib.VMOptions{},\n\t\t}\n\t\terr = disk.Delete(ctx, dc)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Failed to delete vsphere volume with vmDiskPath: %s. err: %+v\", vmDiskPath, err)\n\t\t}\n\t\treturn err\n\t}\n\trequestTime := time.Now()\n\terr := deleteVolumeInternal(vmDiskPath)\n\tvclib.RecordvSphereMetric(vclib.OperationDeleteVolume, requestTime, err)\n\treturn err\n}","line":{"from":1505,"to":1535}} {"id":100034652,"name":"HasClusterID","signature":"func (vs *VSphere) HasClusterID() bool","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// HasClusterID returns true if the cluster has a clusterID\nfunc (vs *VSphere) HasClusterID() bool {\n\treturn true\n}","line":{"from":1537,"to":1540}} {"id":100034653,"name":"NodeAdded","signature":"func (vs *VSphere) NodeAdded(obj interface{})","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// Notification handler when node is added into k8s cluster.\nfunc (vs *VSphere) NodeAdded(obj interface{}) {\n\tnode, ok := obj.(*v1.Node)\n\tif node == nil || !ok {\n\t\tklog.Warningf(\"NodeAdded: unrecognized object %+v\", obj)\n\t\treturn\n\t}\n\n\tklog.V(4).Infof(\"Node added: %+v\", node)\n\tif err := vs.nodeManager.RegisterNode(node); err != nil {\n\t\tklog.Errorf(\"failed to add node %+v: %v\", node, err)\n\t}\n\tvs.setNodeZoneLabels(node)\n}","line":{"from":1542,"to":1555}} {"id":100034654,"name":"syncNodeZoneLabels","signature":"func (vs *VSphere) syncNodeZoneLabels(_ interface{}, newObj interface{})","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// Node zone labels sync function, intended to be called periodically within kube-controller-manager.\nfunc (vs *VSphere) syncNodeZoneLabels(_ interface{}, newObj interface{}) {\n\tnode, ok := newObj.(*v1.Node)\n\tif node == nil || !ok {\n\t\tklog.Warningf(\"NodeUpdated: unrecognized object %+v\", newObj)\n\t\treturn\n\t}\n\n\t// Populate zone and region labels if needed.\n\t// This logic engages only if credentials provided via secret.\n\t// Returns early if topology labels are already presented.\n\t// https://github.com/kubernetes/kubernetes/issues/75175\n\tif vs.isSecretInfoProvided \u0026\u0026 vs.isZoneEnabled() {\n\t\tlabels := node.GetLabels()\n\t\t_, zoneOk := labels[v1.LabelTopologyZone]\n\t\t_, regionOk := labels[v1.LabelTopologyRegion]\n\t\tif zoneOk \u0026\u0026 regionOk {\n\t\t\tklog.V(6).Infof(\"Node topology labels are already populated\")\n\t\t\treturn\n\t\t}\n\t\tklog.V(4).Infof(\"Topology labels was not found, trying to populate for node %s\", node.Name)\n\t\tvs.setNodeZoneLabels(node)\n\t}\n}","line":{"from":1557,"to":1580}} {"id":100034655,"name":"setNodeZoneLabels","signature":"func (vs *VSphere) setNodeZoneLabels(node *v1.Node)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"func (vs *VSphere) setNodeZoneLabels(node *v1.Node) {\n\tnodeZone := node.ObjectMeta.Labels[v1.LabelTopologyZone]\n\tnodeRegion := node.ObjectMeta.Labels[v1.LabelTopologyRegion]\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tif vs.isSecretInfoProvided \u0026\u0026 vs.isZoneEnabled() {\n\t\tzone, err := vs.GetZoneByProviderID(ctx, node.Spec.ProviderID)\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"Can not get Zones from vCenter: %v\", err)\n\t\t}\n\n\t\tif zone.FailureDomain != nodeZone || zone.Region != nodeRegion {\n\t\t\tupdatedNode := node.DeepCopy()\n\t\t\tlabels := updatedNode.ObjectMeta.Labels\n\t\t\tif labels == nil {\n\t\t\t\tlabels = make(map[string]string)\n\t\t\t}\n\t\t\tlabels[v1.LabelTopologyZone] = zone.FailureDomain\n\t\t\tlabels[v1.LabelTopologyRegion] = zone.Region\n\n\t\t\terr = tryUpdateNode(ctx, vs.kubeClient, updatedNode)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"vSphere cloud provider can not update node with zones info: %v\", err)\n\t\t\t} else {\n\t\t\t\tklog.V(4).Infof(\"Node %s updated with zone and region labels\", updatedNode.Name)\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":1582,"to":1610}} {"id":100034656,"name":"tryUpdateNode","signature":"func tryUpdateNode(ctx context.Context, client clientset.Interface, updatedNode *v1.Node) error","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"func tryUpdateNode(ctx context.Context, client clientset.Interface, updatedNode *v1.Node) error {\n\tfor i := 0; i \u003c updateNodeRetryCount; i++ {\n\t\t_, err := client.CoreV1().Nodes().Update(ctx, updatedNode, metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\tif !apierrors.IsConflict(err) {\n\t\t\t\treturn fmt.Errorf(\"vSphere cloud provider can not update node with zones info: %v\", err)\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"update node exceeds retry count\")\n}","line":{"from":1612,"to":1624}} {"id":100034657,"name":"NodeDeleted","signature":"func (vs *VSphere) NodeDeleted(obj interface{})","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// Notification handler when node is removed from k8s cluster.\nfunc (vs *VSphere) NodeDeleted(obj interface{}) {\n\tnode, ok := obj.(*v1.Node)\n\tif node == nil || !ok {\n\t\tklog.Warningf(\"NodeDeleted: unrecognized object %+v\", obj)\n\t\treturn\n\t}\n\n\tklog.V(4).Infof(\"Node deleted: %+v\", node)\n\tif err := vs.nodeManager.UnRegisterNode(node); err != nil {\n\t\tklog.Errorf(\"failed to delete node %s: %v\", node.Name, err)\n\t}\n}","line":{"from":1626,"to":1638}} {"id":100034658,"name":"SecretAdded","signature":"func (vs *VSphere) SecretAdded(obj interface{})","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// Notification handler when credentials secret is added.\nfunc (vs *VSphere) SecretAdded(obj interface{}) {\n\tsecret, ok := obj.(*v1.Secret)\n\tif secret == nil || !ok {\n\t\tklog.Warningf(\"Unrecognized secret object %T\", obj)\n\t\treturn\n\t}\n\n\tif secret.Name != vs.cfg.Global.SecretName ||\n\t\tsecret.Namespace != vs.cfg.Global.SecretNamespace {\n\t\treturn\n\t}\n\n\tklog.V(4).Infof(\"refreshing node cache for secret: %s/%s\", secret.Namespace, secret.Name)\n\tvs.refreshNodesForSecretChange()\n}","line":{"from":1640,"to":1655}} {"id":100034659,"name":"SecretUpdated","signature":"func (vs *VSphere) SecretUpdated(obj interface{}, newObj interface{})","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// Notification handler when credentials secret is updated.\nfunc (vs *VSphere) SecretUpdated(obj interface{}, newObj interface{}) {\n\toldSecret, ok := obj.(*v1.Secret)\n\tif oldSecret == nil || !ok {\n\t\tklog.Warningf(\"Unrecognized secret object %T\", obj)\n\t\treturn\n\t}\n\n\tsecret, ok := newObj.(*v1.Secret)\n\tif secret == nil || !ok {\n\t\tklog.Warningf(\"Unrecognized secret object %T\", newObj)\n\t\treturn\n\t}\n\n\tif secret.Name != vs.cfg.Global.SecretName ||\n\t\tsecret.Namespace != vs.cfg.Global.SecretNamespace ||\n\t\treflect.DeepEqual(secret.Data, oldSecret.Data) {\n\t\treturn\n\t}\n\n\tklog.V(4).Infof(\"refreshing node cache for secret: %s/%s\", secret.Namespace, secret.Name)\n\tvs.refreshNodesForSecretChange()\n}","line":{"from":1657,"to":1679}} {"id":100034660,"name":"refreshNodesForSecretChange","signature":"func (vs *VSphere) refreshNodesForSecretChange()","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"func (vs *VSphere) refreshNodesForSecretChange() {\n\terr := vs.nodeManager.refreshNodes()\n\tif err != nil {\n\t\tklog.Errorf(\"failed to rediscover nodes: %v\", err)\n\t}\n}","line":{"from":1681,"to":1686}} {"id":100034661,"name":"NodeManager","signature":"func (vs *VSphere) NodeManager() (nodeManager *NodeManager)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"func (vs *VSphere) NodeManager() (nodeManager *NodeManager) {\n\tif vs == nil {\n\t\treturn nil\n\t}\n\treturn vs.nodeManager\n}","line":{"from":1688,"to":1693}} {"id":100034662,"name":"withTagsClient","signature":"func withTagsClient(ctx context.Context, connection *vclib.VSphereConnection, f func(c *rest.Client) error) error","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"func withTagsClient(ctx context.Context, connection *vclib.VSphereConnection, f func(c *rest.Client) error) error {\n\tc := rest.NewClient(connection.Client)\n\tsigner, err := connection.Signer(ctx, connection.Client)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif signer == nil {\n\t\tuser := url.UserPassword(connection.Username, connection.Password)\n\t\terr = c.Login(ctx, user)\n\t} else {\n\t\terr = c.LoginByToken(c.WithSigner(ctx, signer))\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\tif err := c.Logout(ctx); err != nil {\n\t\t\tklog.Errorf(\"failed to logout: %v\", err)\n\t\t}\n\t}()\n\treturn f(c)\n}","line":{"from":1695,"to":1717}} {"id":100034663,"name":"getZoneByVmUUIDAndNodeName","signature":"func (vs *VSphere) getZoneByVmUUIDAndNodeName(ctx context.Context, vmUUID string, nodeName k8stypes.NodeName) (cloudprovider.Zone, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"func (vs *VSphere) getZoneByVmUUIDAndNodeName(ctx context.Context, vmUUID string, nodeName k8stypes.NodeName) (cloudprovider.Zone, error) {\n\tzone := cloudprovider.Zone{}\n\n\tvsi, err := vs.getVSphereInstanceForServer(vs.cfg.Workspace.VCenterIP, ctx)\n\tif err != nil {\n\t\tklog.Errorf(\"Cannot connect to vsphere. Get zone for node %s error\", nodeName)\n\t\treturn cloudprovider.Zone{}, err\n\t}\n\tdc, err := vclib.GetDatacenter(ctx, vsi.conn, vs.cfg.Workspace.Datacenter)\n\tif err != nil {\n\t\tklog.Errorf(\"Cannot connect to datacenter. Get zone for node %s error\", nodeName)\n\t\treturn cloudprovider.Zone{}, err\n\t}\n\tvmHost, err := dc.GetHostByVMUUID(ctx, vmUUID)\n\tif err != nil {\n\t\tklog.Errorf(\"Cannot find VM runtime host. Get zone for node %s error\", nodeName)\n\t\treturn cloudprovider.Zone{}, err\n\t}\n\n\tpc := vsi.conn.Client.ServiceContent.PropertyCollector\n\terr = withTagsClient(ctx, vsi.conn, func(c *rest.Client) error {\n\t\tclient := tags.NewManager(c)\n\t\t// example result: [\"Folder\", \"Datacenter\", \"Cluster\", \"Host\"]\n\t\tobjects, err := mo.Ancestors(ctx, vsi.conn.Client, pc, *vmHost)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// search the hierarchy, example order: [\"Host\", \"Cluster\", \"Datacenter\", \"Folder\"]\n\t\tfor i := range objects {\n\t\t\tobj := objects[len(objects)-1-i]\n\t\t\tattachedTags, err := client.ListAttachedTags(ctx, obj)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"Cannot list attached tags. Get zone for node %s: %s\", nodeName, err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfor _, value := range attachedTags {\n\t\t\t\ttag, err := client.GetTag(ctx, value)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Errorf(\"Get tag %s: %s\", value, err)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tcategory, err := client.GetCategory(ctx, tag.CategoryID)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Errorf(\"Get category %s error\", value)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tfound := func() {\n\t\t\t\t\tklog.Errorf(\"Found %q tag (%s) for %s attached to %s\", category.Name, tag.Name, vmUUID, obj.Reference())\n\t\t\t\t}\n\t\t\t\tswitch {\n\t\t\t\tcase category.Name == vs.cfg.Labels.Zone:\n\t\t\t\t\tzone.FailureDomain = tag.Name\n\t\t\t\t\tfound()\n\t\t\t\tcase category.Name == vs.cfg.Labels.Region:\n\t\t\t\t\tzone.Region = tag.Name\n\t\t\t\t\tfound()\n\t\t\t\t}\n\n\t\t\t\tif zone.FailureDomain != \"\" \u0026\u0026 zone.Region != \"\" {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif zone.Region == \"\" {\n\t\t\treturn fmt.Errorf(\"vSphere region category %q does not match any tags for node %s [%s]\", vs.cfg.Labels.Region, nodeName, vmUUID)\n\t\t}\n\t\tif zone.FailureDomain == \"\" {\n\t\t\treturn fmt.Errorf(\"vSphere zone category %q does not match any tags for node %s [%s]\", vs.cfg.Labels.Zone, nodeName, vmUUID)\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tklog.Errorf(\"Get zone for node %s: %s\", nodeName, err)\n\t\treturn cloudprovider.Zone{}, err\n\t}\n\treturn zone, nil\n}","line":{"from":1719,"to":1799}} {"id":100034664,"name":"GetZone","signature":"func (vs *VSphere) GetZone(ctx context.Context) (cloudprovider.Zone, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// GetZone implements Zones.GetZone\nfunc (vs *VSphere) GetZone(ctx context.Context) (cloudprovider.Zone, error) {\n\tnodeName, err := vs.CurrentNodeName(ctx, vs.hostName)\n\tif err != nil {\n\t\tklog.Errorf(\"Cannot get node name.\")\n\t\treturn cloudprovider.Zone{}, err\n\t}\n\treturn vs.getZoneByVmUUIDAndNodeName(ctx, vs.vmUUID, nodeName)\n}","line":{"from":1801,"to":1809}} {"id":100034665,"name":"GetZoneByNodeName","signature":"func (vs *VSphere) GetZoneByNodeName(ctx context.Context, nodeName k8stypes.NodeName) (cloudprovider.Zone, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"func (vs *VSphere) GetZoneByNodeName(ctx context.Context, nodeName k8stypes.NodeName) (cloudprovider.Zone, error) {\n\treturn cloudprovider.Zone{}, cloudprovider.NotImplemented\n}","line":{"from":1811,"to":1813}} {"id":100034666,"name":"GetZoneByProviderID","signature":"func (vs *VSphere) GetZoneByProviderID(ctx context.Context, providerID string) (cloudprovider.Zone, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"func (vs *VSphere) GetZoneByProviderID(ctx context.Context, providerID string) (cloudprovider.Zone, error) {\n\tvar nodeName k8stypes.NodeName\n\tvmUUID := strings.Replace(providerID, providerIDPrefix, \"\", 1)\n\n\tfor nName, nInfo := range vs.nodeManager.nodeInfoMap {\n\t\tif nInfo.vmUUID == vmUUID {\n\t\t\tnodeName = convertToK8sType(nName)\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn vs.getZoneByVmUUIDAndNodeName(ctx, vmUUID, nodeName)\n}","line":{"from":1815,"to":1827}} {"id":100034667,"name":"GetLabelsForVolume","signature":"func (vs *VSphere) GetLabelsForVolume(ctx context.Context, pv *v1.PersistentVolume) (map[string]string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// GetLabelsForVolume implements the PVLabeler interface for VSphere\n// since this interface is used by the PV label admission controller.\nfunc (vs *VSphere) GetLabelsForVolume(ctx context.Context, pv *v1.PersistentVolume) (map[string]string, error) {\n\t// ignore if zones not enabled\n\tif !vs.isZoneEnabled() {\n\t\tklog.V(4).Infof(\"Zone labels for volume is not enabled in vsphere.conf\")\n\t\treturn nil, nil\n\t}\n\t// ignore if not vSphere volume\n\tif pv.Spec.VsphereVolume == nil {\n\t\treturn nil, nil\n\t}\n\treturn vs.GetVolumeLabels(pv.Spec.VsphereVolume.VolumePath)\n}","line":{"from":1829,"to":1842}} {"id":100034668,"name":"GetVolumeLabels","signature":"func (vs *VSphere) GetVolumeLabels(volumePath string) (map[string]string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// GetVolumeLabels returns the well known zone and region labels for given volume\nfunc (vs *VSphere) GetVolumeLabels(volumePath string) (map[string]string, error) {\n\t// Create context\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\t// if zones is not enabled return no labels\n\tif !vs.isZoneEnabled() {\n\t\tklog.V(4).Infof(\"Volume zone labels is not enabled in vsphere.conf\")\n\t\treturn nil, nil\n\t}\n\n\t// Find the datastore on which this volume resides\n\tdatastorePathObj, err := vclib.GetDatastorePathObjFromVMDiskPath(volumePath)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get datastore for volume: %v: %+v\", volumePath, err)\n\t\treturn nil, err\n\t}\n\tdsInfos, err := vs.FindDatastoreByName(ctx, datastorePathObj.Datastore)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get datastore by name: %v: %+v\", datastorePathObj.Datastore, err)\n\t\treturn nil, err\n\t}\n\tvar datastore *vclib.Datastore\n\tfor _, dsInfo := range dsInfos {\n\t\tif dsInfo.Datastore.Exists(ctx, datastorePathObj.Path) {\n\t\t\tdatastore = dsInfo.Datastore\n\t\t}\n\t}\n\tif datastore == nil {\n\t\tklog.Errorf(\"Could not find %s among %v\", volumePath, dsInfos)\n\t\treturn nil, fmt.Errorf(\"could not find the datastore for volume: %s\", volumePath)\n\t}\n\n\tdsZones, err := vs.GetZonesForDatastore(ctx, datastore)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get zones for datastore %v: %+v\", datastorePathObj.Datastore, err)\n\t\treturn nil, err\n\t}\n\tdsZones, err = vs.collapseZonesInRegion(ctx, dsZones)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to collapse zones. %v\", err)\n\t\treturn nil, err\n\t}\n\t// FIXME: For now, pick the first zone of datastore as the zone of volume\n\tlabels := make(map[string]string)\n\tif len(dsZones) \u003e 0 {\n\t\tlabels[v1.LabelTopologyRegion] = dsZones[0].Region\n\t\tlabels[v1.LabelTopologyZone] = dsZones[0].FailureDomain\n\t}\n\treturn labels, nil\n}","line":{"from":1844,"to":1895}} {"id":100034669,"name":"collapseZonesInRegion","signature":"func (vs *VSphere) collapseZonesInRegion(ctx context.Context, zones []cloudprovider.Zone) ([]cloudprovider.Zone, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// collapse all zones in same region. Join FailureDomain with well known separator\nfunc (vs *VSphere) collapseZonesInRegion(ctx context.Context, zones []cloudprovider.Zone) ([]cloudprovider.Zone, error) {\n\t// first create a map of region -\u003e list of zones in that region\n\tregionToZones := make(map[string][]string)\n\tfor _, zone := range zones {\n\t\tfds, exists := regionToZones[zone.Region]\n\t\tif !exists {\n\t\t\tfds = make([]string, 0)\n\t\t}\n\t\tregionToZones[zone.Region] = append(fds, zone.FailureDomain)\n\t}\n\n\t// Join all fds in same region and return Zone instances\n\tcollapsedZones := make([]cloudprovider.Zone, 0)\n\tfor region, fds := range regionToZones {\n\t\tfdSet := sets.NewString(fds...)\n\t\tappendedZone := volumehelpers.ZonesSetToLabelValue(fdSet)\n\t\tcollapsedZones = append(collapsedZones, cloudprovider.Zone{FailureDomain: appendedZone, Region: region})\n\t}\n\treturn collapsedZones, nil\n}","line":{"from":1897,"to":1917}} {"id":100034670,"name":"GetZonesForDatastore","signature":"func (vs *VSphere) GetZonesForDatastore(ctx context.Context, datastore *vclib.Datastore) ([]cloudprovider.Zone, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// GetZonesForDatastore returns all the zones from which this datastore is visible\nfunc (vs *VSphere) GetZonesForDatastore(ctx context.Context, datastore *vclib.Datastore) ([]cloudprovider.Zone, error) {\n\tvsi, err := vs.getVSphereInstanceForServer(vs.cfg.Workspace.VCenterIP, ctx)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get vSphere instance: %+v\", err)\n\t\treturn nil, err\n\t}\n\n\t// get the hosts mounted on this datastore\n\t// datastore -\u003e [\"host-1\", \"host-2\", \"host-3\", ...]\n\tdsHosts, err := datastore.GetDatastoreHostMounts(ctx)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get datastore host mounts for %v: %+v\", datastore, err)\n\t\treturn nil, err\n\t}\n\tklog.V(4).Infof(\"Got host mounts for datastore: %v: %v\", datastore, dsHosts)\n\n\t// compute map of zone to list of hosts in that zone across all hosts in vsphere\n\t// zone -\u003e [\"host-i\", \"host-j\", \"host-k\", ...]\n\tzoneToHosts, err := vs.GetZoneToHosts(ctx, vsi)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get zones for hosts: %+v\", err)\n\t\treturn nil, err\n\t}\n\tklog.V(4).Infof(\"Got zone to hosts: %v\", zoneToHosts)\n\n\t// datastore belongs to a zone if all hosts in that zone mount that datastore\n\tdsZones := make([]cloudprovider.Zone, 0)\n\tfor zone, zoneHosts := range zoneToHosts {\n\t\t// if zone is valid and zoneHosts is a subset of dsHosts, then add zone\n\t\tif zone.Region != \"\" \u0026\u0026 containsAll(dsHosts, zoneHosts) {\n\t\t\tdsZones = append(dsZones, zone)\n\t\t}\n\t}\n\tklog.V(4).Infof(\"Datastore %s belongs to zones: %v\", datastore, dsZones)\n\treturn dsZones, nil\n}","line":{"from":1919,"to":1955}} {"id":100034671,"name":"GetZoneToHosts","signature":"func (vs *VSphere) GetZoneToHosts(ctx context.Context, vsi *VSphereInstance) (map[cloudprovider.Zone][]vmwaretypes.ManagedObjectReference, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// GetZoneToHosts returns a map of 'zone' -\u003e 'list of hosts in that zone' in given VC\nfunc (vs *VSphere) GetZoneToHosts(ctx context.Context, vsi *VSphereInstance) (map[cloudprovider.Zone][]vmwaretypes.ManagedObjectReference, error) {\n\t// Approach is to find tags with the category of 'vs.cfg.Labels.Zone'\n\tzoneToHosts := make(map[cloudprovider.Zone][]vmwaretypes.ManagedObjectReference)\n\n\tgetHostsInTagCategory := func(ctx context.Context, tagCategoryName string) (map[vmwaretypes.ManagedObjectReference]string, error) {\n\n\t\thostToTag := make(map[vmwaretypes.ManagedObjectReference]string)\n\t\terr := withTagsClient(ctx, vsi.conn, func(c *rest.Client) error {\n\t\t\t// Look whether the zone/region tag is defined in VC\n\t\t\ttagManager := tags.NewManager(c)\n\t\t\ttagsForCat, err := tagManager.GetTagsForCategory(ctx, tagCategoryName)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"No tags with category %s exists in VC. So ignoring.\", tagCategoryName)\n\t\t\t\t// return a special error so that tag unavailability can be ignored\n\t\t\t\treturn ErrNoZoneTagInVC\n\t\t\t}\n\t\t\tklog.V(4).Infof(\"List of tags under category %s: %v\", tagCategoryName, tagsForCat)\n\n\t\t\t// Each such tag is a different 'zone' marked in vCenter.\n\t\t\t// Query for objects associated with each tag. Consider Host, Cluster and Datacenter kind of objects.\n\t\t\ttagToObjects := make(map[string][]mo.Reference)\n\t\t\tfor _, tag := range tagsForCat {\n\t\t\t\tklog.V(4).Infof(\"Getting objects associated with tag %s\", tag.Name)\n\t\t\t\tobjects, err := tagManager.ListAttachedObjects(ctx, tag.Name)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Errorf(\"Error fetching objects associated with zone tag %s: %+v\", tag.Name, err)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\ttagToObjects[tag.Name] = objects\n\t\t\t}\n\t\t\tklog.V(4).Infof(\"Map of tag to objects: %v\", tagToObjects)\n\n\t\t\t// Infer zone for hosts within Datacenter, hosts within clusters and hosts - in this order of increasing priority\n\t\t\t// The below nested for-loops goes over all the objects in tagToObjects three times over.\n\t\t\tfor _, moType := range []string{vclib.DatacenterType, vclib.ClusterComputeResourceType, vclib.HostSystemType} {\n\t\t\t\tfor tagName, objects := range tagToObjects {\n\t\t\t\t\tfor _, obj := range objects {\n\t\t\t\t\t\tif obj.Reference().Type == moType {\n\t\t\t\t\t\t\tklog.V(4).Infof(\"Found zone tag %s associated with %s of type %T: %s\", tagName, obj, obj, obj.Reference().Value)\n\t\t\t\t\t\t\tswitch moType {\n\t\t\t\t\t\t\tcase \"Datacenter\":\n\t\t\t\t\t\t\t\t// mark that all hosts in this datacenter has tag applied\n\t\t\t\t\t\t\t\tdcObjRef := object.NewReference(vsi.conn.Client, obj.Reference())\n\t\t\t\t\t\t\t\tklog.V(4).Infof(\"Converted mo obj %v to govmomi object ref %v\", obj, dcObjRef)\n\t\t\t\t\t\t\t\tdcObj, ok := dcObjRef.(*object.Datacenter)\n\t\t\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\t\t\terrMsg := fmt.Sprintf(\"Not able to convert object to Datacenter %v\", obj)\n\t\t\t\t\t\t\t\t\tklog.Errorf(errMsg)\n\t\t\t\t\t\t\t\t\treturn errors.New(errMsg)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tklog.V(4).Infof(\"Converted to object Datacenter %v\", dcObj)\n\t\t\t\t\t\t\t\tdc := vclib.Datacenter{Datacenter: dcObj}\n\t\t\t\t\t\t\t\thosts, err := dc.GetAllHosts(ctx)\n\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\tklog.Errorf(\"Could not get hosts from datacenter %v: %+v\", dc, err)\n\t\t\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tfor _, host := range hosts {\n\t\t\t\t\t\t\t\t\thostToTag[host] = tagName\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcase \"ClusterComputeResource\":\n\t\t\t\t\t\t\t\t// mark that all hosts in this cluster has tag applied\n\t\t\t\t\t\t\t\tclusterObjRef := object.NewReference(vsi.conn.Client, obj.Reference())\n\t\t\t\t\t\t\t\tclusterObj, ok := clusterObjRef.(*object.ClusterComputeResource)\n\t\t\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\t\t\terrMsg := fmt.Sprintf(\"Not able to convert object ClusterComputeResource %v\", obj)\n\t\t\t\t\t\t\t\t\tklog.Errorf(errMsg)\n\t\t\t\t\t\t\t\t\treturn errors.New(errMsg)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\thostSystemList, err := clusterObj.Hosts(ctx)\n\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\tklog.Errorf(\"Not able to get hosts in cluster %v: %+v\", clusterObj, err)\n\t\t\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tfor _, host := range hostSystemList {\n\t\t\t\t\t\t\t\t\thostToTag[host.Reference()] = tagName\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcase \"HostSystem\":\n\t\t\t\t\t\t\t\t// mark that this host has tag applied\n\t\t\t\t\t\t\t\thostToTag[obj.Reference()] = tagName\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil // no error\n\t\t})\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Error processing tag category %s: %+v\", tagCategoryName, err)\n\t\t\treturn nil, err\n\t\t}\n\t\tklog.V(6).Infof(\"Computed hostToTag: %v\", hostToTag)\n\t\treturn hostToTag, nil\n\t}\n\n\thostToZone, err := getHostsInTagCategory(ctx, vs.cfg.Labels.Zone)\n\tif err != nil {\n\t\tif err == ErrNoZoneTagInVC {\n\t\t\treturn zoneToHosts, nil\n\t\t}\n\t\tklog.Errorf(\"Get hosts in tag category %s failed: %+v\", vs.cfg.Labels.Zone, err)\n\t\treturn nil, err\n\t}\n\n\thostToRegion, err := getHostsInTagCategory(ctx, vs.cfg.Labels.Region)\n\tif err != nil {\n\t\tif err == ErrNoZoneTagInVC {\n\t\t\treturn zoneToHosts, nil\n\t\t}\n\t\tklog.Errorf(\"Get hosts in tag category %s failed: %+v\", vs.cfg.Labels.Region, err)\n\t\treturn nil, err\n\t}\n\n\t// populate zoneToHosts based on hostToZone and hostToRegion\n\tklog.V(6).Infof(\"hostToZone: %v\", hostToZone)\n\tklog.V(6).Infof(\"hostToRegion: %v\", hostToRegion)\n\tfor host, zone := range hostToZone {\n\t\tregion, regionExists := hostToRegion[host]\n\t\tif !regionExists {\n\t\t\tklog.Errorf(\"Host %s has a zone, but no region. So ignoring.\", host)\n\t\t\tcontinue\n\t\t}\n\t\tcpZone := cloudprovider.Zone{FailureDomain: zone, Region: region}\n\t\thosts, exists := zoneToHosts[cpZone]\n\t\tif !exists {\n\t\t\thosts = make([]vmwaretypes.ManagedObjectReference, 0)\n\t\t}\n\t\tzoneToHosts[cpZone] = append(hosts, host)\n\t}\n\tklog.V(4).Infof(\"Final zoneToHosts: %v\", zoneToHosts)\n\treturn zoneToHosts, nil\n}","line":{"from":1957,"to":2089}} {"id":100034672,"name":"containsAll","signature":"func containsAll(s1 []vmwaretypes.ManagedObjectReference, s2 []vmwaretypes.ManagedObjectReference) bool","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere.go","code":"// returns true if s1 contains all elements from s2; false otherwise\nfunc containsAll(s1 []vmwaretypes.ManagedObjectReference, s2 []vmwaretypes.ManagedObjectReference) bool {\n\t// put all elements of s1 into a map\n\ts1Map := make(map[vmwaretypes.ManagedObjectReference]bool)\n\tfor _, mor := range s1 {\n\t\ts1Map[mor] = true\n\t}\n\t// verify if all elements of s2 are present in s1Map\n\tfor _, mor := range s2 {\n\t\tif _, found := s1Map[mor]; !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}","line":{"from":2091,"to":2105}} {"id":100034673,"name":"GetVSphere","signature":"func GetVSphere() (*VSphere, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"// GetVSphere reads vSphere configuration from system environment and construct vSphere object\nfunc GetVSphere() (*VSphere, error) {\n\tcfg, err := getVSphereConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvs, err := newControllerNode(*cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn vs, nil\n}","line":{"from":62,"to":73}} {"id":100034674,"name":"getVSphereConfig","signature":"func getVSphereConfig() (*VSphereConfig, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"func getVSphereConfig() (*VSphereConfig, error) {\n\tconfFileLocation := os.Getenv(vSphereConfFileEnvVar)\n\tif confFileLocation == \"\" {\n\t\treturn nil, fmt.Errorf(\"Env variable 'VSPHERE_CONF_FILE' is not set.\")\n\t}\n\tconfFile, err := os.Open(confFileLocation)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\tif err := confFile.Close(); err != nil {\n\t\t\tklog.Errorf(\"failed to close config file: %v\", err)\n\t\t}\n\t}()\n\n\tcfg, err := readConfig(confFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026cfg, nil\n}","line":{"from":75,"to":95}} {"id":100034675,"name":"getAccessibleDatastores","signature":"func getAccessibleDatastores(ctx context.Context, nodeVmDetail *NodeDetails, nodeManager *NodeManager) ([]*vclib.DatastoreInfo, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"// Returns the accessible datastores for the given node VM.\nfunc getAccessibleDatastores(ctx context.Context, nodeVmDetail *NodeDetails, nodeManager *NodeManager) ([]*vclib.DatastoreInfo, error) {\n\taccessibleDatastores, err := nodeVmDetail.vm.GetAllAccessibleDatastores(ctx)\n\tif err != nil {\n\t\t// Check if the node VM is not found which indicates that the node info in the node manager is stale.\n\t\t// If so, rediscover the node and retry.\n\t\tif vclib.IsManagedObjectNotFoundError(err) {\n\t\t\tklog.V(4).Infof(\"error %q ManagedObjectNotFound for node %q. Rediscovering...\", err, nodeVmDetail.NodeName)\n\t\t\terr = nodeManager.RediscoverNode(convertToK8sType(nodeVmDetail.NodeName))\n\t\t\tif err == nil {\n\t\t\t\tklog.V(4).Infof(\"Discovered node %s successfully\", nodeVmDetail.NodeName)\n\t\t\t\tnodeInfo, err := nodeManager.GetNodeInfo(convertToK8sType(nodeVmDetail.NodeName))\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.V(4).Infof(\"error %q getting node info for node %+v\", err, nodeVmDetail)\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\taccessibleDatastores, err = nodeInfo.vm.GetAllAccessibleDatastores(ctx)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.V(4).Infof(\"error %q getting accessible datastores for node %+v\", err, nodeVmDetail)\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tklog.V(4).Infof(\"error %q rediscovering node %+v\", err, nodeVmDetail)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\tklog.V(4).Infof(\"error %q getting accessible datastores for node %+v\", err, nodeVmDetail)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn accessibleDatastores, nil\n}","line":{"from":97,"to":129}} {"id":100034676,"name":"getSharedDatastoresInK8SCluster","signature":"func getSharedDatastoresInK8SCluster(ctx context.Context, nodeManager *NodeManager) ([]*vclib.DatastoreInfo, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"// Get all datastores accessible for the virtual machine object.\nfunc getSharedDatastoresInK8SCluster(ctx context.Context, nodeManager *NodeManager) ([]*vclib.DatastoreInfo, error) {\n\tnodeVmDetails, err := nodeManager.GetNodeDetails()\n\tif err != nil {\n\t\tklog.Errorf(\"Error while obtaining Kubernetes node nodeVmDetail details. error : %+v\", err)\n\t\treturn nil, err\n\t}\n\n\tif len(nodeVmDetails) == 0 {\n\t\tmsg := fmt.Sprintf(\"Kubernetes node nodeVmDetail details is empty. nodeVmDetails : %+v\", nodeVmDetails)\n\t\tklog.Error(msg)\n\t\treturn nil, fmt.Errorf(msg)\n\t}\n\tvar sharedDatastores []*vclib.DatastoreInfo\n\tfor _, nodeVmDetail := range nodeVmDetails {\n\t\tklog.V(9).Infof(\"Getting accessible datastores for node %s\", nodeVmDetail.NodeName)\n\t\taccessibleDatastores, err := getAccessibleDatastores(ctx, \u0026nodeVmDetail, nodeManager)\n\t\tif err != nil {\n\t\t\tif err == vclib.ErrNoVMFound {\n\t\t\t\tklog.V(9).Infof(\"Got NoVMFound error for node %s\", nodeVmDetail.NodeName)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif len(sharedDatastores) == 0 {\n\t\t\tsharedDatastores = accessibleDatastores\n\t\t} else {\n\t\t\tsharedDatastores = intersect(sharedDatastores, accessibleDatastores)\n\t\t\tif len(sharedDatastores) == 0 {\n\t\t\t\treturn nil, fmt.Errorf(\"No shared datastores found in the Kubernetes cluster for nodeVmDetails: %+v\", nodeVmDetails)\n\t\t\t}\n\t\t}\n\t}\n\tklog.V(9).Infof(\"sharedDatastores : %+v\", sharedDatastores)\n\treturn sharedDatastores, nil\n}","line":{"from":131,"to":167}} {"id":100034677,"name":"intersect","signature":"func intersect(list1 []*vclib.DatastoreInfo, list2 []*vclib.DatastoreInfo) []*vclib.DatastoreInfo","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"func intersect(list1 []*vclib.DatastoreInfo, list2 []*vclib.DatastoreInfo) []*vclib.DatastoreInfo {\n\tklog.V(9).Infof(\"list1: %+v\", list1)\n\tklog.V(9).Infof(\"list2: %+v\", list2)\n\tvar sharedDs []*vclib.DatastoreInfo\n\tfor _, val1 := range list1 {\n\t\t// Check if val1 is found in list2\n\t\tfor _, val2 := range list2 {\n\t\t\t// Intersection is performed based on the datastoreUrl as this uniquely identifies the datastore.\n\t\t\tif val1.Info.Url == val2.Info.Url {\n\t\t\t\tsharedDs = append(sharedDs, val1)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn sharedDs\n}","line":{"from":169,"to":184}} {"id":100034678,"name":"getMostFreeDatastore","signature":"func getMostFreeDatastore(ctx context.Context, client *vim25.Client, dsInfoList []*vclib.DatastoreInfo) (*vclib.DatastoreInfo, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"// getMostFreeDatastore gets the best fit compatible datastore by free space.\nfunc getMostFreeDatastore(ctx context.Context, client *vim25.Client, dsInfoList []*vclib.DatastoreInfo) (*vclib.DatastoreInfo, error) {\n\tvar curMax int64\n\tcurMax = -1\n\tvar index int\n\tfor i, dsInfo := range dsInfoList {\n\t\tdsFreeSpace := dsInfo.Info.GetDatastoreInfo().FreeSpace\n\t\tif dsFreeSpace \u003e curMax {\n\t\t\tcurMax = dsFreeSpace\n\t\t\tindex = i\n\t\t}\n\t}\n\treturn dsInfoList[index], nil\n}","line":{"from":186,"to":199}} {"id":100034679,"name":"getPbmCompatibleDatastore","signature":"func getPbmCompatibleDatastore(ctx context.Context, vcClient *vim25.Client, storagePolicyName string, nodeManager *NodeManager) (*vclib.DatastoreInfo, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"func getPbmCompatibleDatastore(ctx context.Context, vcClient *vim25.Client, storagePolicyName string, nodeManager *NodeManager) (*vclib.DatastoreInfo, error) {\n\tpbmClient, err := vclib.NewPbmClient(ctx, vcClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstoragePolicyID, err := pbmClient.ProfileIDByName(ctx, storagePolicyName)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get Profile ID by name: %s. err: %+v\", storagePolicyName, err)\n\t\treturn nil, err\n\t}\n\tsharedDs, err := getSharedDatastoresInK8SCluster(ctx, nodeManager)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get shared datastores. err: %+v\", err)\n\t\treturn nil, err\n\t}\n\tif len(sharedDs) == 0 {\n\t\tmsg := \"No shared datastores found in the endpoint virtual center\"\n\t\tklog.Errorf(msg)\n\t\treturn nil, errors.New(msg)\n\t}\n\tcompatibleDatastores, _, err := pbmClient.GetCompatibleDatastores(ctx, storagePolicyID, sharedDs)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get compatible datastores from datastores : %+v with storagePolicy: %s. err: %+v\",\n\t\t\tsharedDs, storagePolicyID, err)\n\t\treturn nil, err\n\t}\n\tklog.V(9).Infof(\"compatibleDatastores : %+v\", compatibleDatastores)\n\tdatastore, err := getMostFreeDatastore(ctx, vcClient, compatibleDatastores)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get most free datastore from compatible datastores: %+v. err: %+v\", compatibleDatastores, err)\n\t\treturn nil, err\n\t}\n\tklog.V(4).Infof(\"Most free datastore : %+s\", datastore.Info.Name)\n\treturn datastore, err\n}","line":{"from":201,"to":235}} {"id":100034680,"name":"getDatastoresForZone","signature":"func getDatastoresForZone(ctx context.Context, nodeManager *NodeManager, selectedZones []string) ([]*vclib.DatastoreInfo, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"func getDatastoresForZone(ctx context.Context, nodeManager *NodeManager, selectedZones []string) ([]*vclib.DatastoreInfo, error) {\n\n\tvar sharedDatastores []*vclib.DatastoreInfo\n\n\tfor _, zone := range selectedZones {\n\t\tvar sharedDatastoresPerZone []*vclib.DatastoreInfo\n\t\thosts, err := nodeManager.GetHostsInZone(ctx, zone)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tklog.V(4).Infof(\"Hosts in zone %s : %s\", zone, hosts)\n\n\t\tfor _, host := range hosts {\n\t\t\tvar hostSystemMo mo.HostSystem\n\t\t\terr = host.Properties(ctx, host.Reference(), []string{\"datastore\"}, \u0026hostSystemMo)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"Failed to get datastore property for host %s. err : %+v\", host, err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tklog.V(4).Infof(\"Datastores mounted on host %s : %s\", host, hostSystemMo.Datastore)\n\t\t\tvar dsRefList []types.ManagedObjectReference\n\t\t\tfor _, dsRef := range hostSystemMo.Datastore {\n\t\t\t\tdsRefList = append(dsRefList, dsRef)\n\t\t\t}\n\n\t\t\tvar dsMoList []mo.Datastore\n\t\t\tpc := property.DefaultCollector(host.Client())\n\t\t\tproperties := []string{DatastoreInfoProperty, DatastoreNameProperty}\n\t\t\terr = pc.Retrieve(ctx, dsRefList, properties, \u0026dsMoList)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"Failed to get Datastore managed objects from datastore objects.\"+\n\t\t\t\t\t\" dsObjList: %+v, properties: %+v, err: %+v\", dsRefList, properties, err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tklog.V(9).Infof(\"Datastore mo details: %+v\", dsMoList)\n\n\t\t\t// find the Datacenter parent for this host\n\t\t\tmes, err := mo.Ancestors(ctx, host.Client(), pc.Reference(), host.Reference())\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tvar dcMoref *types.ManagedObjectReference\n\t\t\tfor i := len(mes) - 1; i \u003e 0; i-- {\n\t\t\t\tif mes[i].Self.Type == \"Datacenter\" {\n\t\t\t\t\tdcMoref = \u0026mes[i].Self\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif dcMoref == nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to find the Datacenter of host %s\", host)\n\t\t\t}\n\n\t\t\tdc := object.NewDatacenter(host.Client(), *dcMoref)\n\t\t\tfinder := find.NewFinder(host.Client(), false)\n\t\t\tfinder.SetDatacenter(dc)\n\t\t\tvar dsObjList []*vclib.DatastoreInfo\n\t\t\tfor _, dsMo := range dsMoList {\n\t\t\t\t// use the finder so that InventoryPath is set correctly in dsObj\n\t\t\t\tdsObj, err := finder.Datastore(ctx, dsMo.Name)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Errorf(\"Failed to find datastore named %s in datacenter %s\", dsMo.Name, dc)\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tdsObjList = append(dsObjList,\n\t\t\t\t\t\u0026vclib.DatastoreInfo{\n\t\t\t\t\t\tDatastore: \u0026vclib.Datastore{Datastore: dsObj,\n\t\t\t\t\t\t\tDatacenter: \u0026vclib.Datacenter{Datacenter: dc}},\n\t\t\t\t\t\tInfo: dsMo.Info.GetDatastoreInfo()})\n\t\t\t}\n\n\t\t\tklog.V(9).Infof(\"DatastoreInfo details : %s\", dsObjList)\n\n\t\t\tif len(sharedDatastoresPerZone) == 0 {\n\t\t\t\tsharedDatastoresPerZone = dsObjList\n\t\t\t} else {\n\t\t\t\tsharedDatastoresPerZone = intersect(sharedDatastoresPerZone, dsObjList)\n\t\t\t\tif len(sharedDatastoresPerZone) == 0 {\n\t\t\t\t\tklog.V(4).Infof(\"No shared datastores found among hosts %s\", hosts)\n\t\t\t\t\treturn nil, fmt.Errorf(\"No matching datastores found in the kubernetes cluster for zone %s\", zone)\n\t\t\t\t}\n\t\t\t}\n\t\t\tklog.V(9).Infof(\"Shared datastore list after processing host %s : %s\", host, sharedDatastoresPerZone)\n\t\t}\n\t\tklog.V(4).Infof(\"Shared datastore per zone %s is %s\", zone, sharedDatastoresPerZone)\n\t\tif len(sharedDatastores) == 0 {\n\t\t\tsharedDatastores = sharedDatastoresPerZone\n\t\t} else {\n\t\t\tsharedDatastores = intersect(sharedDatastores, sharedDatastoresPerZone)\n\t\t\tif len(sharedDatastores) == 0 {\n\t\t\t\treturn nil, fmt.Errorf(\"No matching datastores found in the kubernetes cluster across zones %s\", selectedZones)\n\t\t\t}\n\t\t}\n\t}\n\tklog.V(1).Infof(\"Returning selected datastores : %s\", sharedDatastores)\n\treturn sharedDatastores, nil\n}","line":{"from":237,"to":333}} {"id":100034681,"name":"getPbmCompatibleZonedDatastore","signature":"func getPbmCompatibleZonedDatastore(ctx context.Context, vcClient *vim25.Client, storagePolicyName string, zonedDatastores []*vclib.DatastoreInfo) (*vclib.DatastoreInfo, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"func getPbmCompatibleZonedDatastore(ctx context.Context, vcClient *vim25.Client, storagePolicyName string, zonedDatastores []*vclib.DatastoreInfo) (*vclib.DatastoreInfo, error) {\n\tpbmClient, err := vclib.NewPbmClient(ctx, vcClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstoragePolicyID, err := pbmClient.ProfileIDByName(ctx, storagePolicyName)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get Profile ID by name: %s. err: %+v\", storagePolicyName, err)\n\t\treturn nil, err\n\t}\n\tcompatibleDatastores, _, err := pbmClient.GetCompatibleDatastores(ctx, storagePolicyID, zonedDatastores)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get compatible datastores from datastores : %+v with storagePolicy: %s. err: %+v\",\n\t\t\tzonedDatastores, storagePolicyID, err)\n\t\treturn nil, err\n\t}\n\tklog.V(9).Infof(\"compatibleDatastores : %+v\", compatibleDatastores)\n\tdatastore, err := getMostFreeDatastore(ctx, vcClient, compatibleDatastores)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get most free datastore from compatible datastores: %+v. err: %+v\", compatibleDatastores, err)\n\t\treturn nil, err\n\t}\n\tklog.V(4).Infof(\"Most free datastore : %+s\", datastore.Info.Name)\n\treturn datastore, err\n}","line":{"from":335,"to":359}} {"id":100034682,"name":"setVMOptions","signature":"func (vs *VSphere) setVMOptions(ctx context.Context, connection *vclib.VSphereConnection, ds *vclib.Datastore) (*vclib.VMOptions, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"func (vs *VSphere) setVMOptions(ctx context.Context, connection *vclib.VSphereConnection, ds *vclib.Datastore) (*vclib.VMOptions, error) {\n\tvar vmOptions vclib.VMOptions\n\tdsHosts, err := ds.GetDatastoreHostMounts(ctx)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get datastore host mounts for %v: %+v\", ds, err)\n\t\treturn nil, err\n\t}\n\t// pick a host at random to use for Volume creation\n\tdsHostMoref := dsHosts[rand.New(rand.NewSource(time.Now().UnixNano())).Intn(len(dsHosts))]\n\tdummyVMHost := object.NewHostSystem(connection.Client, dsHostMoref)\n\tresourcePool, err := dummyVMHost.ResourcePool(ctx)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get resource pool from host %v\", dummyVMHost)\n\t\treturn nil, err\n\t}\n\tfolder, err := ds.Datacenter.GetFolderByPath(ctx, vs.cfg.Workspace.Folder)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvmOptions.VMFolder = folder\n\tvmOptions.VMResourcePool = resourcePool\n\treturn \u0026vmOptions, nil\n}","line":{"from":361,"to":383}} {"id":100034683,"name":"cleanUpDummyVMs","signature":"func (vs *VSphere) cleanUpDummyVMs(dummyVMPrefix string)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"// A background routine which will be responsible for deleting stale dummy VM's.\nfunc (vs *VSphere) cleanUpDummyVMs(dummyVMPrefix string) {\n\t// Create context\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tfor {\n\t\ttime.Sleep(CleanUpDummyVMRoutineInterval * time.Minute)\n\t\tdatacenters, err := vs.GetWorkspaceDatacenters(ctx)\n\t\tif err != nil {\n\t\t\tklog.V(4).Infof(\"Failed to get datacenters from VC. err: %+v\", err)\n\t\t\tcontinue\n\t\t}\n\t\t// Clean up dummy VMs in each datacenter\n\t\tfor _, dc := range datacenters {\n\t\t\t// Get the folder reference for global working directory where the dummy VM needs to be created.\n\t\t\tvmFolder, err := dc.GetFolderByPath(ctx, vs.cfg.Workspace.Folder)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Unable to get the kubernetes folder: %q reference. err: %+v\", vs.cfg.Workspace.Folder, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// A write lock is acquired to make sure the cleanUp routine doesn't delete any VM's created by ongoing PVC requests.\n\t\t\tcleanUpDummyVMs := func() {\n\t\t\t\tcleanUpDummyVMLock.Lock()\n\t\t\t\tdefer cleanUpDummyVMLock.Unlock()\n\t\t\t\terr = diskmanagers.CleanUpDummyVMs(ctx, vmFolder)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.V(4).Infof(\"Unable to clean up dummy VM's in the kubernetes cluster: %q. err: %+v\", vs.cfg.Workspace.Folder, err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tcleanUpDummyVMs()\n\t\t}\n\t}\n}","line":{"from":385,"to":417}} {"id":100034684,"name":"getcanonicalVolumePath","signature":"func getcanonicalVolumePath(ctx context.Context, dc *vclib.Datacenter, volumePath string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"// Get canonical volume path for volume Path.\n// Example1: The canonical path for volume path - [vsanDatastore] kubevols/volume.vmdk will be [vsanDatastore] 25d8b159-948c-4b73-e499-02001ad1b044/volume.vmdk\n// Example2: The canonical path for volume path - [vsanDatastore] 25d8b159-948c-4b73-e499-02001ad1b044/volume.vmdk will be same as volume Path.\nfunc getcanonicalVolumePath(ctx context.Context, dc *vclib.Datacenter, volumePath string) (string, error) {\n\tvar folderID string\n\tvar folderExists bool\n\tcanonicalVolumePath := volumePath\n\tdsPathObj, err := vclib.GetDatastorePathObjFromVMDiskPath(volumePath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdsPath := strings.Split(strings.TrimSpace(dsPathObj.Path), \"/\")\n\tif len(dsPath) \u003c= 1 {\n\t\treturn canonicalVolumePath, nil\n\t}\n\tdatastore := dsPathObj.Datastore\n\tdsFolder := dsPath[0]\n\tfolderNameIDMap, datastoreExists := datastoreFolderIDMap[datastore]\n\tif datastoreExists {\n\t\tfolderID, folderExists = folderNameIDMap[dsFolder]\n\t}\n\t// Get the datastore folder ID if datastore or folder doesn't exist in datastoreFolderIDMap\n\tif !datastoreExists || !folderExists {\n\t\tif !vclib.IsValidUUID(dsFolder) {\n\t\t\tdummyDiskVolPath := \"[\" + datastore + \"] \" + dsFolder + \"/\" + DummyDiskName\n\t\t\t// Querying a non-existent dummy disk on the datastore folder.\n\t\t\t// It would fail and return an folder ID in the error message.\n\t\t\t_, err := dc.GetVirtualDiskPage83Data(ctx, dummyDiskVolPath)\n\t\t\tcanonicalVolumePath, err = getPathFromFileNotFound(err)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", fmt.Errorf(\"failed to get path from dummy request: %v\", err)\n\t\t\t}\n\t\t}\n\t\tdiskPath := vclib.GetPathFromVMDiskPath(canonicalVolumePath)\n\t\tif diskPath == \"\" {\n\t\t\treturn \"\", fmt.Errorf(\"Failed to parse canonicalVolumePath: %s in getcanonicalVolumePath method\", canonicalVolumePath)\n\t\t}\n\t\tfolderID = strings.Split(strings.TrimSpace(diskPath), \"/\")[0]\n\t\tsetdatastoreFolderIDMap(datastoreFolderIDMap, datastore, dsFolder, folderID)\n\t}\n\tcanonicalVolumePath = strings.Replace(volumePath, dsFolder, folderID, 1)\n\treturn canonicalVolumePath, nil\n}","line":{"from":419,"to":461}} {"id":100034685,"name":"getPathFromFileNotFound","signature":"func getPathFromFileNotFound(err error) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"// getPathFromFileNotFound returns the path from a fileNotFound error\nfunc getPathFromFileNotFound(err error) (string, error) {\n\tif soap.IsSoapFault(err) {\n\t\tfault := soap.ToSoapFault(err)\n\t\tf, ok := fault.VimFault().(types.FileNotFound)\n\t\tif !ok {\n\t\t\treturn \"\", fmt.Errorf(\"%v is not a FileNotFound error\", err)\n\t\t}\n\t\treturn f.File, nil\n\t}\n\treturn \"\", fmt.Errorf(\"%v is not a soap fault\", err)\n}","line":{"from":463,"to":474}} {"id":100034686,"name":"setdatastoreFolderIDMap","signature":"func setdatastoreFolderIDMap(","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"func setdatastoreFolderIDMap(\n\tdatastoreFolderIDMap map[string]map[string]string,\n\tdatastore string,\n\tfolderName string,\n\tfolderID string) {\n\tfolderNameIDMap := datastoreFolderIDMap[datastore]\n\tif folderNameIDMap == nil {\n\t\tfolderNameIDMap = make(map[string]string)\n\t\tdatastoreFolderIDMap[datastore] = folderNameIDMap\n\t}\n\tfolderNameIDMap[folderName] = folderID\n}","line":{"from":476,"to":487}} {"id":100034687,"name":"convertVolPathToDevicePath","signature":"func convertVolPathToDevicePath(ctx context.Context, dc *vclib.Datacenter, volPath string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"func convertVolPathToDevicePath(ctx context.Context, dc *vclib.Datacenter, volPath string) (string, error) {\n\tvolPath = vclib.RemoveStorageClusterORFolderNameFromVDiskPath(volPath)\n\t// Get the canonical volume path for volPath.\n\tcanonicalVolumePath, err := getcanonicalVolumePath(ctx, dc, volPath)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get canonical vsphere volume path for volume: %s. err: %+v\", volPath, err)\n\t\treturn \"\", err\n\t}\n\t// Check if the volume path contains .vmdk extension. If not, add the extension and update the nodeVolumes Map\n\tif len(canonicalVolumePath) \u003e 0 \u0026\u0026 filepath.Ext(canonicalVolumePath) != \".vmdk\" {\n\t\tcanonicalVolumePath += \".vmdk\"\n\t}\n\treturn canonicalVolumePath, nil\n}","line":{"from":489,"to":502}} {"id":100034688,"name":"convertVolPathsToDevicePaths","signature":"func (vs *VSphere) convertVolPathsToDevicePaths(ctx context.Context, nodeVolumes map[k8stypes.NodeName][]string) (map[k8stypes.NodeName][]string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"// convertVolPathsToDevicePaths removes cluster or folder path from volPaths and convert to canonicalPath\nfunc (vs *VSphere) convertVolPathsToDevicePaths(ctx context.Context, nodeVolumes map[k8stypes.NodeName][]string) (map[k8stypes.NodeName][]string, error) {\n\tvmVolumes := make(map[k8stypes.NodeName][]string)\n\tfor nodeName, volPaths := range nodeVolumes {\n\t\tnodeInfo, err := vs.nodeManager.GetNodeInfo(nodeName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t_, err = vs.getVSphereInstanceForServer(nodeInfo.vcServer, ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor i, volPath := range volPaths {\n\t\t\tdeviceVolPath, err := convertVolPathToDevicePath(ctx, nodeInfo.dataCenter, volPath)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"Failed to convert vsphere volume path %s to device path for volume %s. err: %+v\", volPath, deviceVolPath, err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tvolPaths[i] = deviceVolPath\n\t\t}\n\t\tvmVolumes[nodeName] = volPaths\n\t}\n\treturn vmVolumes, nil\n}","line":{"from":504,"to":529}} {"id":100034689,"name":"checkDiskAttached","signature":"func (vs *VSphere) checkDiskAttached(ctx context.Context, nodes []k8stypes.NodeName, nodeVolumes map[k8stypes.NodeName][]string, attached map[string]map[string]bool, retry bool) ([]k8stypes.NodeName, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"// checkDiskAttached verifies volumes are attached to the VMs which are in same vCenter and Datacenter\n// Returns nodes if exist any for which VM is not found in that vCenter and Datacenter\nfunc (vs *VSphere) checkDiskAttached(ctx context.Context, nodes []k8stypes.NodeName, nodeVolumes map[k8stypes.NodeName][]string, attached map[string]map[string]bool, retry bool) ([]k8stypes.NodeName, error) {\n\tvar nodesToRetry []k8stypes.NodeName\n\tvar vmList []*vclib.VirtualMachine\n\tvar nodeInfo NodeInfo\n\tvar err error\n\n\tfor _, nodeName := range nodes {\n\t\tnodeInfo, err = vs.nodeManager.GetNodeInfo(nodeName)\n\t\tif err != nil {\n\t\t\treturn nodesToRetry, err\n\t\t}\n\t\tvmList = append(vmList, nodeInfo.vm)\n\t}\n\n\t// Making sure session is valid\n\t_, err = vs.getVSphereInstanceForServer(nodeInfo.vcServer, ctx)\n\tif err != nil {\n\t\treturn nodesToRetry, err\n\t}\n\n\t// If any of the nodes are not present property collector query will fail for entire operation\n\tvmMoList, err := nodeInfo.dataCenter.GetVMMoList(ctx, vmList, []string{\"config.hardware.device\", \"name\", \"config.uuid\"})\n\tif err != nil {\n\t\tif vclib.IsManagedObjectNotFoundError(err) \u0026\u0026 !retry {\n\t\t\tklog.V(4).Infof(\"checkDiskAttached: ManagedObjectNotFound for property collector query for nodes: %+v vms: %+v\", nodes, vmList)\n\t\t\t// Property Collector Query failed\n\t\t\t// VerifyVolumePaths per VM\n\t\t\tfor _, nodeName := range nodes {\n\t\t\t\tnodeInfo, err := vs.nodeManager.GetNodeInfo(nodeName)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nodesToRetry, err\n\t\t\t\t}\n\t\t\t\tdevices, err := nodeInfo.vm.VirtualMachine.Device(ctx)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif vclib.IsManagedObjectNotFoundError(err) {\n\t\t\t\t\t\tklog.V(4).Infof(\"checkDiskAttached: ManagedObjectNotFound for Kubernetes node: %s with vSphere Virtual Machine reference: %v\", nodeName, nodeInfo.vm)\n\t\t\t\t\t\tnodesToRetry = append(nodesToRetry, nodeName)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\treturn nodesToRetry, err\n\t\t\t\t}\n\t\t\t\tklog.V(4).Infof(\"Verifying Volume Paths by devices for node %s and VM %s\", nodeName, nodeInfo.vm)\n\t\t\t\tvs.vsphereVolumeMap.Add(nodeName, devices)\n\t\t\t\tvclib.VerifyVolumePathsForVMDevices(devices, nodeVolumes[nodeName], convertToString(nodeName), attached)\n\t\t\t}\n\t\t}\n\t\treturn nodesToRetry, err\n\t}\n\n\tvmMoMap := make(map[string]mo.VirtualMachine)\n\tfor _, vmMo := range vmMoList {\n\t\tif vmMo.Config == nil {\n\t\t\tklog.Errorf(\"Config is not available for VM: %q\", vmMo.Name)\n\t\t\tcontinue\n\t\t}\n\t\tklog.V(9).Infof(\"vmMoMap vmname: %q vmuuid: %s\", vmMo.Name, strings.ToLower(vmMo.Config.Uuid))\n\t\tvmMoMap[strings.ToLower(vmMo.Config.Uuid)] = vmMo\n\t}\n\n\tklog.V(9).Infof(\"vmMoMap: +%v\", vmMoMap)\n\n\tfor _, nodeName := range nodes {\n\t\tnode, err := vs.nodeManager.GetNode(nodeName)\n\t\tif err != nil {\n\t\t\treturn nodesToRetry, err\n\t\t}\n\t\tnodeUUID, err := GetNodeUUID(\u0026node)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Node Discovery failed to get node uuid for node %s with error: %v\", node.Name, err)\n\t\t\treturn nodesToRetry, err\n\t\t}\n\t\tnodeUUID = strings.ToLower(nodeUUID)\n\t\tklog.V(9).Infof(\"Verifying volume for node %s with nodeuuid %q: %v\", nodeName, nodeUUID, vmMoMap)\n\t\tvmMo := vmMoMap[nodeUUID]\n\t\tvmDevices := object.VirtualDeviceList(vmMo.Config.Hardware.Device)\n\t\tvs.vsphereVolumeMap.Add(nodeName, vmDevices)\n\t\tvclib.VerifyVolumePathsForVMDevices(vmDevices, nodeVolumes[nodeName], convertToString(nodeName), attached)\n\t}\n\treturn nodesToRetry, nil\n}","line":{"from":531,"to":612}} {"id":100034690,"name":"BuildMissingVolumeNodeMap","signature":"func (vs *VSphere) BuildMissingVolumeNodeMap(ctx context.Context)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"// BuildMissingVolumeNodeMap builds a map of volumes and nodes which are not known to attach detach controller.\n// There could be nodes in cluster which do not have any pods with vsphere volumes running on them\n// such nodes won't be part of disk verification check because attach-detach controller does not keep track\n// such nodes. But such nodes may still have dangling volumes on them and hence we need to scan all the\n// remaining nodes which weren't scanned by code previously.\nfunc (vs *VSphere) BuildMissingVolumeNodeMap(ctx context.Context) {\n\tnodeNames := vs.nodeManager.GetNodeNames()\n\t// Segregate nodes according to VC-DC\n\tdcNodes := make(map[string][]k8stypes.NodeName)\n\n\tfor _, nodeName := range nodeNames {\n\t\t// if given node is not in node volume map\n\t\tif !vs.vsphereVolumeMap.CheckForNode(nodeName) {\n\t\t\tnodeInfo, err := vs.nodeManager.GetNodeInfo(nodeName)\n\t\t\tif err != nil {\n\t\t\t\tklog.V(4).Infof(\"Failed to get node info: %+v. err: %+v\", nodeInfo.vm, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvcDC := nodeInfo.vcServer + nodeInfo.dataCenter.String()\n\t\t\tdcNodes[vcDC] = append(dcNodes[vcDC], nodeName)\n\t\t}\n\t}\n\n\tvar wg sync.WaitGroup\n\n\tfor _, nodeNames := range dcNodes {\n\t\t// Start go routines per VC-DC to check disks are attached\n\t\twg.Add(1)\n\t\tgo func(nodes []k8stypes.NodeName) {\n\t\t\terr := vs.checkNodeDisks(ctx, nodes)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"Failed to check disk attached for nodes: %+v. err: %+v\", nodes, err)\n\t\t\t}\n\t\t\twg.Done()\n\t\t}(nodeNames)\n\t}\n\twg.Wait()\n}","line":{"from":614,"to":651}} {"id":100034691,"name":"checkNodeDisks","signature":"func (vs *VSphere) checkNodeDisks(ctx context.Context, nodeNames []k8stypes.NodeName) error","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"func (vs *VSphere) checkNodeDisks(ctx context.Context, nodeNames []k8stypes.NodeName) error {\n\tvar vmList []*vclib.VirtualMachine\n\tvar nodeInfo NodeInfo\n\tvar err error\n\n\tfor _, nodeName := range nodeNames {\n\t\tnodeInfo, err = vs.nodeManager.GetNodeInfo(nodeName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvmList = append(vmList, nodeInfo.vm)\n\t}\n\n\t// Making sure session is valid\n\t_, err = vs.getVSphereInstanceForServer(nodeInfo.vcServer, ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// If any of the nodes are not present property collector query will fail for entire operation\n\tvmMoList, err := nodeInfo.dataCenter.GetVMMoList(ctx, vmList, []string{\"config.hardware.device\", \"name\", \"config.uuid\"})\n\tif err != nil {\n\t\tif vclib.IsManagedObjectNotFoundError(err) {\n\t\t\tklog.V(4).Infof(\"checkNodeDisks: ManagedObjectNotFound for property collector query for nodes: %+v vms: %+v\", nodeNames, vmList)\n\t\t\t// Property Collector Query failed\n\t\t\t// VerifyVolumePaths per VM\n\t\t\tfor _, nodeName := range nodeNames {\n\t\t\t\tnodeInfo, err := vs.nodeManager.GetNodeInfo(nodeName)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tdevices, err := nodeInfo.vm.VirtualMachine.Device(ctx)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif vclib.IsManagedObjectNotFoundError(err) {\n\t\t\t\t\t\tklog.V(4).Infof(\"checkNodeDisks: ManagedObjectNotFound for Kubernetes node: %s with vSphere Virtual Machine reference: %v\", nodeName, nodeInfo.vm)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tklog.V(4).Infof(\"Verifying Volume Paths by devices for node %s and VM %s\", nodeName, nodeInfo.vm)\n\t\t\t\tvs.vsphereVolumeMap.Add(nodeName, devices)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\tvmMoMap := make(map[string]mo.VirtualMachine)\n\tfor _, vmMo := range vmMoList {\n\t\tif vmMo.Config == nil {\n\t\t\tklog.Errorf(\"Config is not available for VM: %q\", vmMo.Name)\n\t\t\tcontinue\n\t\t}\n\t\tklog.V(9).Infof(\"vmMoMap vmname: %q vmuuid: %s\", vmMo.Name, strings.ToLower(vmMo.Config.Uuid))\n\t\tvmMoMap[strings.ToLower(vmMo.Config.Uuid)] = vmMo\n\t}\n\n\tklog.V(9).Infof(\"vmMoMap: +%v\", vmMoMap)\n\n\tfor _, nodeName := range nodeNames {\n\t\tnode, err := vs.nodeManager.GetNode(nodeName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnodeUUID, err := GetNodeUUID(\u0026node)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Node Discovery failed to get node uuid for node %s with error: %v\", node.Name, err)\n\t\t\treturn err\n\t\t}\n\t\tnodeUUID = strings.ToLower(nodeUUID)\n\t\tklog.V(9).Infof(\"Verifying volume for node %s with nodeuuid %q: %v\", nodeName, nodeUUID, vmMoMap)\n\t\tvmMo := vmMoMap[nodeUUID]\n\t\tvmDevices := object.VirtualDeviceList(vmMo.Config.Hardware.Device)\n\t\tvs.vsphereVolumeMap.Add(nodeName, vmDevices)\n\t}\n\treturn nil\n}","line":{"from":653,"to":729}} {"id":100034692,"name":"GetNodeNameFromProviderID","signature":"func (vs *VSphere) GetNodeNameFromProviderID(providerID string) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"func (vs *VSphere) GetNodeNameFromProviderID(providerID string) (string, error) {\n\tvar nodeName string\n\tnodes, err := vs.nodeManager.GetNodeDetails()\n\tif err != nil {\n\t\tklog.Errorf(\"Error while obtaining Kubernetes node nodeVmDetail details. error : %+v\", err)\n\t\treturn \"\", err\n\t}\n\tfor _, node := range nodes {\n\t\t// ProviderID is UUID for nodes v1.9.3+\n\t\tif node.VMUUID == GetUUIDFromProviderID(providerID) || node.NodeName == providerID {\n\t\t\tnodeName = node.NodeName\n\t\t\tbreak\n\t\t}\n\t}\n\tif nodeName == \"\" {\n\t\tmsg := fmt.Sprintf(\"Error while obtaining Kubernetes nodename for providerID %s.\", providerID)\n\t\treturn \"\", errors.New(msg)\n\t}\n\treturn nodeName, nil\n}","line":{"from":731,"to":750}} {"id":100034693,"name":"GetUUIDFromProviderID","signature":"func GetUUIDFromProviderID(providerID string) string","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"func GetUUIDFromProviderID(providerID string) string {\n\treturn strings.TrimPrefix(providerID, ProviderPrefix)\n}","line":{"from":752,"to":754}} {"id":100034694,"name":"IsUUIDSupportedNode","signature":"func IsUUIDSupportedNode(node *v1.Node) (bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"func IsUUIDSupportedNode(node *v1.Node) (bool, error) {\n\tnewVersion, err := version.ParseSemantic(\"v1.9.4\")\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to determine whether node %+v is old with error %v\", node, err)\n\t\treturn false, err\n\t}\n\tnodeVersion, err := version.ParseSemantic(node.Status.NodeInfo.KubeletVersion)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to determine whether node %+v is old with error %v\", node, err)\n\t\treturn false, err\n\t}\n\tif nodeVersion.LessThan(newVersion) {\n\t\treturn true, nil\n\t}\n\treturn false, nil\n}","line":{"from":756,"to":771}} {"id":100034695,"name":"isGuestHardwareVersionDeprecated","signature":"func isGuestHardwareVersionDeprecated(vmHardwareversion string) (bool, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"func isGuestHardwareVersionDeprecated(vmHardwareversion string) (bool, error) {\n\tvmHardwareDeprecated := false\n\t// vmconfig.Version returns vm hardware version as vmx-11, vmx-13, vmx-14, vmx-15 etc.\n\tversion := strings.Trim(vmHardwareversion, \"vmx-\")\n\tvalue, err := strconv.ParseInt(version, 0, 64)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"failed to parse vm hardware version: %v Err: %v\", version, err)\n\t} else {\n\t\tif value \u003c 15 {\n\t\t\tvmHardwareDeprecated = true\n\t\t}\n\t}\n\treturn vmHardwareDeprecated, nil\n}","line":{"from":773,"to":786}} {"id":100034696,"name":"GetNodeUUID","signature":"func GetNodeUUID(node *v1.Node) (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"func GetNodeUUID(node *v1.Node) (string, error) {\n\toldNode, err := IsUUIDSupportedNode(node)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to get node UUID for node %+v with error %v\", node, err)\n\t\treturn \"\", err\n\t}\n\tif oldNode {\n\t\treturn node.Status.NodeInfo.SystemUUID, nil\n\t}\n\treturn GetUUIDFromProviderID(node.Spec.ProviderID), nil\n}","line":{"from":788,"to":798}} {"id":100034697,"name":"GetVMUUID","signature":"func GetVMUUID() (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"func GetVMUUID() (string, error) {\n\tuuidFromFile, err := getRawUUID()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error retrieving vm uuid: %s\", err)\n\t}\n\t//strip leading and trailing white space and new line char\n\tuuid := strings.TrimSpace(uuidFromFile)\n\t// check the uuid starts with \"VMware-\"\n\tif !strings.HasPrefix(uuid, UUIDPrefix) {\n\t\treturn \"\", fmt.Errorf(\"failed to match Prefix, UUID read from the file is %v\", uuidFromFile)\n\t}\n\t// Strip the prefix and white spaces and -\n\tuuid = strings.Replace(uuid[len(UUIDPrefix):(len(uuid))], \" \", \"\", -1)\n\tuuid = strings.Replace(uuid, \"-\", \"\", -1)\n\tif len(uuid) != 32 {\n\t\treturn \"\", fmt.Errorf(\"length check failed, UUID read from the file is %v\", uuidFromFile)\n\t}\n\t// need to add dashes, e.g. \"564d395e-d807-e18a-cb25-b79f65eb2b9f\"\n\tuuid = fmt.Sprintf(\"%s-%s-%s-%s-%s\", uuid[0:8], uuid[8:12], uuid[12:16], uuid[16:20], uuid[20:32])\n\treturn uuid, nil\n}","line":{"from":800,"to":820}} {"id":100034698,"name":"GetWorkspaceDatacenters","signature":"func (vs *VSphere) GetWorkspaceDatacenters(ctx context.Context) ([]*vclib.Datacenter, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"// GetWorkspaceDatacenters returns the Datacenter objects that VCP has access to.\n// User can configure the list of datacenters in vsphere.conf. Otherwise all the\n// Datacenters in the configured list of VCs are returned.\nfunc (vs *VSphere) GetWorkspaceDatacenters(ctx context.Context) ([]*vclib.Datacenter, error) {\n\tvar datacenterObjs []*vclib.Datacenter\n\tfor vc, vsi := range vs.vsphereInstanceMap {\n\t\t// ensure connection to VC\n\t\terr := vs.nodeManager.vcConnect(ctx, vsi)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif vsi.cfg.Datacenters == \"\" {\n\t\t\tvcDatacenterObjs, err := vclib.GetAllDatacenter(ctx, vsi.conn)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"Error fetching list of datacenters from VC %s: %+v\", vc, err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdatacenterObjs = append(datacenterObjs, vcDatacenterObjs...)\n\t\t} else {\n\t\t\tdatacenters := strings.Split(vsi.cfg.Datacenters, \",\")\n\t\t\tfor _, dc := range datacenters {\n\t\t\t\tdc = strings.TrimSpace(dc)\n\t\t\t\tif dc == \"\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tdatacenterObj, err := vclib.GetDatacenter(ctx, vsi.conn, dc)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Errorf(\"Error fetching datacenter %s from VC %s: %+v\", dc, vc, err)\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tdatacenterObjs = append(datacenterObjs, datacenterObj)\n\t\t\t}\n\t\t}\n\t}\n\treturn datacenterObjs, nil\n}","line":{"from":822,"to":857}} {"id":100034699,"name":"FindDatastoreByName","signature":"func (vs *VSphere) FindDatastoreByName(ctx context.Context, datastoreName string) ([]*vclib.DatastoreInfo, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util.go","code":"// FindDatastoreByName looks for the given datastore by name across all available datacenters.\n// If more than one Datacenter has a Datastore with the given name, then returns reference to all of them.\nfunc (vs *VSphere) FindDatastoreByName(ctx context.Context, datastoreName string) ([]*vclib.DatastoreInfo, error) {\n\tdatacenters, err := vs.GetWorkspaceDatacenters(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar datastoreInfos []*vclib.DatastoreInfo\n\tfor _, dc := range datacenters {\n\t\tdatastoreInfo, err := dc.GetDatastoreInfoByName(ctx, datastoreName)\n\t\tif err != nil {\n\t\t\tklog.V(9).Infof(\"Did not find datastore %s in datacenter %s, still looking.\", datastoreName, dc.Name())\n\t\t\tcontinue\n\t\t}\n\t\tdatastoreInfos = append(datastoreInfos, datastoreInfo)\n\t}\n\tif len(datastoreInfos) == 0 {\n\t\treturn nil, fmt.Errorf(\"Datastore '%s' not found\", datastoreName)\n\t}\n\tklog.V(4).Infof(\"Found datastore infos %v for datastore %s\", datastoreInfos, datastoreName)\n\treturn datastoreInfos, nil\n}","line":{"from":859,"to":880}} {"id":100034700,"name":"getRawUUID","signature":"func getRawUUID() (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util_linux.go","code":"func getRawUUID() (string, error) {\n\tid, err := ioutil.ReadFile(UUIDPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(id), nil\n}","line":{"from":28,"to":34}} {"id":100034701,"name":"getRawUUID","signature":"func getRawUUID() (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util_unsupported.go","code":"func getRawUUID() (string, error) {\n\treturn \"\", fmt.Errorf(\"Retrieving VM UUID on this build is not implemented.\")\n}","line":{"from":24,"to":26}} {"id":100034702,"name":"getRawUUID","signature":"func getRawUUID() (string, error)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_util_windows.go","code":"func getRawUUID() (string, error) {\n\tresult, err := exec.Command(\"wmic\", \"bios\", \"get\", \"serialnumber\").Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tlines := strings.FieldsFunc(string(result), func(r rune) bool {\n\t\tswitch r {\n\t\tcase '\\n', '\\r':\n\t\t\treturn true\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t})\n\tif len(lines) != 2 {\n\t\treturn \"\", fmt.Errorf(\"received unexpected value retrieving vm uuid: %q\", string(result))\n\t}\n\treturn lines[1], nil\n}","line":{"from":28,"to":45}} {"id":100034703,"name":"NewVsphereVolumeMap","signature":"func NewVsphereVolumeMap() *VsphereVolumeMap","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_volume_map.go","code":"func NewVsphereVolumeMap() *VsphereVolumeMap {\n\treturn \u0026VsphereVolumeMap{\n\t\tvolumeNodeMap: map[volumePath]nodeVolumeStatus{},\n\t\tnodeMap: map[k8stypes.NodeName]bool{},\n\t}\n}","line":{"from":44,"to":49}} {"id":100034704,"name":"StartDiskVerification","signature":"func (vsphereVolume *VsphereVolumeMap) StartDiskVerification()","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_volume_map.go","code":"// StartDiskVerification marks all known volumes as unverified so as\n// disks which aren't verified can be removed at the end of verification process\nfunc (vsphereVolume *VsphereVolumeMap) StartDiskVerification() {\n\tvsphereVolume.lock.Lock()\n\tdefer vsphereVolume.lock.Unlock()\n\tfor k, v := range vsphereVolume.volumeNodeMap {\n\t\tv.verified = false\n\t\tvsphereVolume.volumeNodeMap[k] = v\n\t}\n\t// reset nodeMap to empty so that any node we could not verify via usual verification process\n\t// can still be verified.\n\tvsphereVolume.nodeMap = map[k8stypes.NodeName]bool{}\n}","line":{"from":51,"to":63}} {"id":100034705,"name":"CheckForVolume","signature":"func (vsphereVolume *VsphereVolumeMap) CheckForVolume(path string) (k8stypes.NodeName, bool)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_volume_map.go","code":"// CheckForVolume verifies if disk is attached to some node in the cluster.\n// This check is not definitive and should be followed up by separate verification.\nfunc (vsphereVolume *VsphereVolumeMap) CheckForVolume(path string) (k8stypes.NodeName, bool) {\n\tvsphereVolume.lock.RLock()\n\tdefer vsphereVolume.lock.RUnlock()\n\tvPath := volumePath(path)\n\tns, ok := vsphereVolume.volumeNodeMap[vPath]\n\tif ok {\n\t\treturn ns.nodeName, true\n\t}\n\treturn \"\", false\n}","line":{"from":65,"to":76}} {"id":100034706,"name":"CheckForNode","signature":"func (vsphereVolume *VsphereVolumeMap) CheckForNode(nodeName k8stypes.NodeName) bool","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_volume_map.go","code":"// CheckForNode returns true if given node has already been processed by volume\n// verification mechanism. This is used to skip verifying attached disks on nodes\n// which were previously verified.\nfunc (vsphereVolume *VsphereVolumeMap) CheckForNode(nodeName k8stypes.NodeName) bool {\n\tvsphereVolume.lock.RLock()\n\tdefer vsphereVolume.lock.RUnlock()\n\t_, ok := vsphereVolume.nodeMap[nodeName]\n\treturn ok\n}","line":{"from":78,"to":86}} {"id":100034707,"name":"Add","signature":"func (vsphereVolume *VsphereVolumeMap) Add(node k8stypes.NodeName, vmDevices object.VirtualDeviceList)","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_volume_map.go","code":"// Add all devices found on a node to the device map\nfunc (vsphereVolume *VsphereVolumeMap) Add(node k8stypes.NodeName, vmDevices object.VirtualDeviceList) {\n\tvsphereVolume.lock.Lock()\n\tdefer vsphereVolume.lock.Unlock()\n\tfor _, device := range vmDevices {\n\t\tif vmDevices.TypeName(device) == \"VirtualDisk\" {\n\t\t\tvirtualDevice := device.GetVirtualDevice()\n\t\t\tif backing, ok := virtualDevice.Backing.(*types.VirtualDiskFlatVer2BackingInfo); ok {\n\t\t\t\tfilename := volumePath(backing.FileName)\n\t\t\t\tvsphereVolume.volumeNodeMap[filename] = nodeVolumeStatus{node, true}\n\t\t\t\tvsphereVolume.nodeMap[node] = true\n\t\t\t}\n\t\t}\n\t}\n}","line":{"from":88,"to":102}} {"id":100034708,"name":"RemoveUnverified","signature":"func (vsphereVolume *VsphereVolumeMap) RemoveUnverified()","file":"staging/src/k8s.io/legacy-cloud-providers/vsphere/vsphere_volume_map.go","code":"// RemoveUnverified will remove any device which we could not verify to be attached to a node.\nfunc (vsphereVolume *VsphereVolumeMap) RemoveUnverified() {\n\tvsphereVolume.lock.Lock()\n\tdefer vsphereVolume.lock.Unlock()\n\tfor k, v := range vsphereVolume.volumeNodeMap {\n\t\tif !v.verified {\n\t\t\tdelete(vsphereVolume.volumeNodeMap, k)\n\t\t\tdelete(vsphereVolume.nodeMap, v.nodeName)\n\t\t}\n\t}\n}","line":{"from":104,"to":114}} {"id":100034709,"name":"Convert_v1_ObjectReference_To_custom_metrics_ObjectReference","signature":"func Convert_v1_ObjectReference_To_custom_metrics_ObjectReference(in *v1.ObjectReference, out *ObjectReference, s conversion.Scope) error","file":"staging/src/k8s.io/metrics/pkg/apis/custom_metrics/conversion.go","code":"func Convert_v1_ObjectReference_To_custom_metrics_ObjectReference(in *v1.ObjectReference, out *ObjectReference, s conversion.Scope) error {\n\tout.APIVersion = in.APIVersion\n\n\tout.Kind = in.Kind\n\tout.Namespace = in.Namespace\n\tout.Name = in.Name\n\tout.UID = in.UID\n\tout.ResourceVersion = in.ResourceVersion\n\tout.FieldPath = in.FieldPath\n\treturn nil\n}","line":{"from":24,"to":34}} {"id":100034710,"name":"Convert_custom_metrics_ObjectReference_To_v1_ObjectReference","signature":"func Convert_custom_metrics_ObjectReference_To_v1_ObjectReference(in *ObjectReference, out *v1.ObjectReference, s conversion.Scope) error","file":"staging/src/k8s.io/metrics/pkg/apis/custom_metrics/conversion.go","code":"func Convert_custom_metrics_ObjectReference_To_v1_ObjectReference(in *ObjectReference, out *v1.ObjectReference, s conversion.Scope) error {\n\tout.APIVersion = in.APIVersion\n\n\tout.Kind = in.Kind\n\tout.Namespace = in.Namespace\n\tout.Name = in.Name\n\tout.UID = in.UID\n\tout.ResourceVersion = in.ResourceVersion\n\tout.FieldPath = in.FieldPath\n\treturn nil\n}","line":{"from":36,"to":46}} {"id":100034711,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"staging/src/k8s.io/metrics/pkg/apis/custom_metrics/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(custom_metrics.AddToScheme(scheme))\n\tutilruntime.Must(v1beta2.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1beta1.SchemeGroupVersion, v1beta2.SchemeGroupVersion))\n}","line":{"from":29,"to":35}} {"id":100034712,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/metrics/pkg/apis/custom_metrics/register.go","code":"// Kind takes an unqualified kind and returns back a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100034713,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/metrics/pkg/apis/custom_metrics/register.go","code":"// Resource takes an unqualified resource and returns back a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100034714,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/metrics/pkg/apis/custom_metrics/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026MetricValue{},\n\t\t\u0026MetricValueList{},\n\t\t\u0026MetricListOptions{},\n\t)\n\treturn nil\n}","line":{"from":45,"to":52}} {"id":100034715,"name":"Convert_v1beta1_MetricValue_To_custom_metrics_MetricValue","signature":"func Convert_v1beta1_MetricValue_To_custom_metrics_MetricValue(in *MetricValue, out *custom_metrics.MetricValue, s conversion.Scope) error","file":"staging/src/k8s.io/metrics/pkg/apis/custom_metrics/v1beta1/conversion.go","code":"func Convert_v1beta1_MetricValue_To_custom_metrics_MetricValue(in *MetricValue, out *custom_metrics.MetricValue, s conversion.Scope) error {\n\tif err := autoConvert_v1beta1_MetricValue_To_custom_metrics_MetricValue(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tout.Metric.Name = in.MetricName\n\tout.Metric.Selector = in.Selector\n\treturn nil\n}","line":{"from":24,"to":31}} {"id":100034716,"name":"Convert_custom_metrics_MetricValue_To_v1beta1_MetricValue","signature":"func Convert_custom_metrics_MetricValue_To_v1beta1_MetricValue(in *custom_metrics.MetricValue, out *MetricValue, s conversion.Scope) error","file":"staging/src/k8s.io/metrics/pkg/apis/custom_metrics/v1beta1/conversion.go","code":"func Convert_custom_metrics_MetricValue_To_v1beta1_MetricValue(in *custom_metrics.MetricValue, out *MetricValue, s conversion.Scope) error {\n\tif err := autoConvert_custom_metrics_MetricValue_To_v1beta1_MetricValue(in, out, s); err != nil {\n\t\treturn err\n\t}\n\tout.MetricName = in.Metric.Name\n\tout.Selector = in.Metric.Selector\n\treturn nil\n}","line":{"from":33,"to":40}} {"id":100034717,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/metrics/pkg/apis/custom_metrics/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100034718,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/metrics/pkg/apis/custom_metrics/v1beta1/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026MetricValue{},\n\t\t\u0026MetricValueList{},\n\t\t\u0026MetricListOptions{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":52}} {"id":100034719,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/metrics/pkg/apis/custom_metrics/v1beta2/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100034720,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/metrics/pkg/apis/custom_metrics/v1beta2/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026MetricValue{},\n\t\t\u0026MetricValueList{},\n\t\t\u0026MetricListOptions{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":52}} {"id":100034721,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"staging/src/k8s.io/metrics/pkg/apis/external_metrics/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(external_metrics.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1beta1.SchemeGroupVersion))\n}","line":{"from":28,"to":33}} {"id":100034722,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/metrics/pkg/apis/external_metrics/register.go","code":"// Kind takes an unqualified kind and returns back a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100034723,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/metrics/pkg/apis/external_metrics/register.go","code":"// Resource takes an unqualified resource and returns back a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100034724,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/metrics/pkg/apis/external_metrics/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026ExternalMetricValue{},\n\t\t\u0026ExternalMetricValueList{},\n\t)\n\treturn nil\n}","line":{"from":45,"to":51}} {"id":100034725,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/metrics/pkg/apis/external_metrics/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100034726,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/metrics/pkg/apis/external_metrics/v1beta1/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026ExternalMetricValue{},\n\t\t\u0026ExternalMetricValueList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":51}} {"id":100034727,"name":"Install","signature":"func Install(scheme *runtime.Scheme)","file":"staging/src/k8s.io/metrics/pkg/apis/metrics/install/install.go","code":"// Install registers the API group and adds types to a scheme\nfunc Install(scheme *runtime.Scheme) {\n\tutilruntime.Must(metrics.AddToScheme(scheme))\n\tutilruntime.Must(v1beta1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(v1beta1.SchemeGroupVersion))\n}","line":{"from":28,"to":33}} {"id":100034728,"name":"Kind","signature":"func Kind(kind string) schema.GroupKind","file":"staging/src/k8s.io/metrics/pkg/apis/metrics/register.go","code":"// Kind takes an unqualified kind and returns back a Group qualified GroupKind\nfunc Kind(kind string) schema.GroupKind {\n\treturn SchemeGroupVersion.WithKind(kind).GroupKind()\n}","line":{"from":30,"to":33}} {"id":100034729,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/metrics/pkg/apis/metrics/register.go","code":"// Resource takes an unqualified resource and returns back a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":35,"to":38}} {"id":100034730,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/metrics/pkg/apis/metrics/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026NodeMetrics{},\n\t\t\u0026NodeMetricsList{},\n\t\t\u0026PodMetrics{},\n\t\t\u0026PodMetricsList{},\n\t)\n\treturn nil\n}","line":{"from":47,"to":55}} {"id":100034731,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/metrics/pkg/apis/metrics/v1alpha1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100034732,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/metrics/pkg/apis/metrics/v1alpha1/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026NodeMetrics{},\n\t\t\u0026NodeMetricsList{},\n\t\t\u0026PodMetrics{},\n\t\t\u0026PodMetricsList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":53}} {"id":100034733,"name":"Resource","signature":"func Resource(resource string) schema.GroupResource","file":"staging/src/k8s.io/metrics/pkg/apis/metrics/v1beta1/register.go","code":"// Resource takes an unqualified resource and returns a Group qualified GroupResource\nfunc Resource(resource string) schema.GroupResource {\n\treturn SchemeGroupVersion.WithResource(resource).GroupResource()\n}","line":{"from":31,"to":34}} {"id":100034734,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/metrics/pkg/apis/metrics/v1beta1/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026NodeMetrics{},\n\t\t\u0026NodeMetricsList{},\n\t\t\u0026PodMetrics{},\n\t\t\u0026PodMetricsList{},\n\t)\n\tmetav1.AddToGroupVersion(scheme, SchemeGroupVersion)\n\treturn nil\n}","line":{"from":44,"to":53}} {"id":100034735,"name":"MetricsV1alpha1","signature":"func (c *Clientset) MetricsV1alpha1() metricsv1alpha1.MetricsV1alpha1Interface","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/clientset.go","code":"// MetricsV1alpha1 retrieves the MetricsV1alpha1Client\nfunc (c *Clientset) MetricsV1alpha1() metricsv1alpha1.MetricsV1alpha1Interface {\n\treturn c.metricsV1alpha1\n}","line":{"from":45,"to":48}} {"id":100034736,"name":"MetricsV1beta1","signature":"func (c *Clientset) MetricsV1beta1() metricsv1beta1.MetricsV1beta1Interface","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/clientset.go","code":"// MetricsV1beta1 retrieves the MetricsV1beta1Client\nfunc (c *Clientset) MetricsV1beta1() metricsv1beta1.MetricsV1beta1Interface {\n\treturn c.metricsV1beta1\n}","line":{"from":50,"to":53}} {"id":100034737,"name":"Discovery","signature":"func (c *Clientset) Discovery() discovery.DiscoveryInterface","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/clientset.go","code":"// Discovery retrieves the DiscoveryClient\nfunc (c *Clientset) Discovery() discovery.DiscoveryInterface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.DiscoveryClient\n}","line":{"from":55,"to":61}} {"id":100034738,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*Clientset, error)","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/clientset.go","code":"// NewForConfig creates a new Clientset for the given config.\n// If config's RateLimiter is not set and QPS and Burst are acceptable,\n// NewForConfig will generate a rate-limiter in configShallowCopy.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*Clientset, error) {\n\tconfigShallowCopy := *c\n\n\tif configShallowCopy.UserAgent == \"\" {\n\t\tconfigShallowCopy.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\t// share the transport between all clients\n\thttpClient, err := rest.HTTPClientFor(\u0026configShallowCopy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n}","line":{"from":63,"to":82}} {"id":100034739,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, httpClient *http.Client) (*Clientset, error)","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/clientset.go","code":"// NewForConfigAndClient creates a new Clientset for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\n// If config's RateLimiter is not set and QPS and Burst are acceptable,\n// NewForConfigAndClient will generate a rate-limiter in configShallowCopy.\nfunc NewForConfigAndClient(c *rest.Config, httpClient *http.Client) (*Clientset, error) {\n\tconfigShallowCopy := *c\n\tif configShallowCopy.RateLimiter == nil \u0026\u0026 configShallowCopy.QPS \u003e 0 {\n\t\tif configShallowCopy.Burst \u003c= 0 {\n\t\t\treturn nil, fmt.Errorf(\"burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0\")\n\t\t}\n\t\tconfigShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst)\n\t}\n\n\tvar cs Clientset\n\tvar err error\n\tcs.metricsV1alpha1, err = metricsv1alpha1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.metricsV1beta1, err = metricsv1beta1.NewForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfigAndClient(\u0026configShallowCopy, httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026cs, nil\n}","line":{"from":84,"to":113}} {"id":100034740,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *Clientset","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/clientset.go","code":"// NewForConfigOrDie creates a new Clientset for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *Clientset {\n\tcs, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn cs\n}","line":{"from":115,"to":123}} {"id":100034741,"name":"New","signature":"func New(c rest.Interface) *Clientset","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/clientset.go","code":"// New creates a new Clientset for the given RESTClient.\nfunc New(c rest.Interface) *Clientset {\n\tvar cs Clientset\n\tcs.metricsV1alpha1 = metricsv1alpha1.New(c)\n\tcs.metricsV1beta1 = metricsv1beta1.New(c)\n\n\tcs.DiscoveryClient = discovery.NewDiscoveryClient(c)\n\treturn \u0026cs\n}","line":{"from":125,"to":133}} {"id":100034742,"name":"init","signature":"func init()","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/scheme/register.go","code":"func init() {\n\tv1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: \"v1\"})\n\tutilruntime.Must(AddToScheme(Scheme))\n}","line":{"from":55,"to":58}} {"id":100034743,"name":"NodeMetricses","signature":"func (c *MetricsV1alpha1Client) NodeMetricses() NodeMetricsInterface","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1alpha1/metrics_client.go","code":"func (c *MetricsV1alpha1Client) NodeMetricses() NodeMetricsInterface {\n\treturn newNodeMetricses(c)\n}","line":{"from":40,"to":42}} {"id":100034744,"name":"PodMetricses","signature":"func (c *MetricsV1alpha1Client) PodMetricses(namespace string) PodMetricsInterface","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1alpha1/metrics_client.go","code":"func (c *MetricsV1alpha1Client) PodMetricses(namespace string) PodMetricsInterface {\n\treturn newPodMetricses(c, namespace)\n}","line":{"from":44,"to":46}} {"id":100034745,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*MetricsV1alpha1Client, error)","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1alpha1/metrics_client.go","code":"// NewForConfig creates a new MetricsV1alpha1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*MetricsV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":48,"to":61}} {"id":100034746,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*MetricsV1alpha1Client, error)","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1alpha1/metrics_client.go","code":"// NewForConfigAndClient creates a new MetricsV1alpha1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*MetricsV1alpha1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026MetricsV1alpha1Client{client}, nil\n}","line":{"from":63,"to":75}} {"id":100034747,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *MetricsV1alpha1Client","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1alpha1/metrics_client.go","code":"// NewForConfigOrDie creates a new MetricsV1alpha1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *MetricsV1alpha1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":77,"to":85}} {"id":100034748,"name":"New","signature":"func New(c rest.Interface) *MetricsV1alpha1Client","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1alpha1/metrics_client.go","code":"// New creates a new MetricsV1alpha1Client for the given RESTClient.\nfunc New(c rest.Interface) *MetricsV1alpha1Client {\n\treturn \u0026MetricsV1alpha1Client{c}\n}","line":{"from":87,"to":90}} {"id":100034749,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1alpha1/metrics_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1alpha1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":92,"to":103}} {"id":100034750,"name":"RESTClient","signature":"func (c *MetricsV1alpha1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1alpha1/metrics_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *MetricsV1alpha1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":105,"to":112}} {"id":100034751,"name":"newNodeMetricses","signature":"func newNodeMetricses(c *MetricsV1alpha1Client) *nodeMetricses","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1alpha1/nodemetrics.go","code":"// newNodeMetricses returns a NodeMetricses\nfunc newNodeMetricses(c *MetricsV1alpha1Client) *nodeMetricses {\n\treturn \u0026nodeMetricses{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":51,"to":56}} {"id":100034752,"name":"Get","signature":"func (c *nodeMetricses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.NodeMetrics, err error)","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1alpha1/nodemetrics.go","code":"// Get takes name of the nodeMetrics, and returns the corresponding nodeMetrics object, and an error if there is any.\nfunc (c *nodeMetricses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.NodeMetrics, err error) {\n\tresult = \u0026v1alpha1.NodeMetrics{}\n\terr = c.client.Get().\n\t\tResource(\"nodes\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":58,"to":68}} {"id":100034753,"name":"List","signature":"func (c *nodeMetricses) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.NodeMetricsList, err error)","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1alpha1/nodemetrics.go","code":"// List takes label and field selectors, and returns the list of NodeMetricses that match those selectors.\nfunc (c *nodeMetricses) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.NodeMetricsList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1alpha1.NodeMetricsList{}\n\terr = c.client.Get().\n\t\tResource(\"nodes\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":84}} {"id":100034754,"name":"Watch","signature":"func (c *nodeMetricses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1alpha1/nodemetrics.go","code":"// Watch returns a watch.Interface that watches the requested nodeMetricses.\nfunc (c *nodeMetricses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"nodes\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":86,"to":98}} {"id":100034755,"name":"newPodMetricses","signature":"func newPodMetricses(c *MetricsV1alpha1Client, namespace string) *podMetricses","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1alpha1/podmetrics.go","code":"// newPodMetricses returns a PodMetricses\nfunc newPodMetricses(c *MetricsV1alpha1Client, namespace string) *podMetricses {\n\treturn \u0026podMetricses{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":52,"to":58}} {"id":100034756,"name":"Get","signature":"func (c *podMetricses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.PodMetrics, err error)","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1alpha1/podmetrics.go","code":"// Get takes name of the podMetrics, and returns the corresponding podMetrics object, and an error if there is any.\nfunc (c *podMetricses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.PodMetrics, err error) {\n\tresult = \u0026v1alpha1.PodMetrics{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"pods\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":60,"to":71}} {"id":100034757,"name":"List","signature":"func (c *podMetricses) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.PodMetricsList, err error)","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1alpha1/podmetrics.go","code":"// List takes label and field selectors, and returns the list of PodMetricses that match those selectors.\nfunc (c *podMetricses) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.PodMetricsList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1alpha1.PodMetricsList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"pods\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":73,"to":88}} {"id":100034758,"name":"Watch","signature":"func (c *podMetricses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1alpha1/podmetrics.go","code":"// Watch returns a watch.Interface that watches the requested podMetricses.\nfunc (c *podMetricses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"pods\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":90,"to":103}} {"id":100034759,"name":"NodeMetricses","signature":"func (c *MetricsV1beta1Client) NodeMetricses() NodeMetricsInterface","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1beta1/metrics_client.go","code":"func (c *MetricsV1beta1Client) NodeMetricses() NodeMetricsInterface {\n\treturn newNodeMetricses(c)\n}","line":{"from":40,"to":42}} {"id":100034760,"name":"PodMetricses","signature":"func (c *MetricsV1beta1Client) PodMetricses(namespace string) PodMetricsInterface","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1beta1/metrics_client.go","code":"func (c *MetricsV1beta1Client) PodMetricses(namespace string) PodMetricsInterface {\n\treturn newPodMetricses(c, namespace)\n}","line":{"from":44,"to":46}} {"id":100034761,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (*MetricsV1beta1Client, error)","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1beta1/metrics_client.go","code":"// NewForConfig creates a new MetricsV1beta1Client for the given config.\n// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n// where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(c *rest.Config) (*MetricsV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := rest.HTTPClientFor(\u0026config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(\u0026config, httpClient)\n}","line":{"from":48,"to":61}} {"id":100034762,"name":"NewForConfigAndClient","signature":"func NewForConfigAndClient(c *rest.Config, h *http.Client) (*MetricsV1beta1Client, error)","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1beta1/metrics_client.go","code":"// NewForConfigAndClient creates a new MetricsV1beta1Client for the given config and http client.\n// Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(c *rest.Config, h *http.Client) (*MetricsV1beta1Client, error) {\n\tconfig := *c\n\tif err := setConfigDefaults(\u0026config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := rest.RESTClientForConfigAndClient(\u0026config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \u0026MetricsV1beta1Client{client}, nil\n}","line":{"from":63,"to":75}} {"id":100034763,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) *MetricsV1beta1Client","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1beta1/metrics_client.go","code":"// NewForConfigOrDie creates a new MetricsV1beta1Client for the given config and\n// panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) *MetricsV1beta1Client {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":77,"to":85}} {"id":100034764,"name":"New","signature":"func New(c rest.Interface) *MetricsV1beta1Client","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1beta1/metrics_client.go","code":"// New creates a new MetricsV1beta1Client for the given RESTClient.\nfunc New(c rest.Interface) *MetricsV1beta1Client {\n\treturn \u0026MetricsV1beta1Client{c}\n}","line":{"from":87,"to":90}} {"id":100034765,"name":"setConfigDefaults","signature":"func setConfigDefaults(config *rest.Config) error","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1beta1/metrics_client.go","code":"func setConfigDefaults(config *rest.Config) error {\n\tgv := v1beta1.SchemeGroupVersion\n\tconfig.GroupVersion = \u0026gv\n\tconfig.APIPath = \"/apis\"\n\tconfig.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\treturn nil\n}","line":{"from":92,"to":103}} {"id":100034766,"name":"RESTClient","signature":"func (c *MetricsV1beta1Client) RESTClient() rest.Interface","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1beta1/metrics_client.go","code":"// RESTClient returns a RESTClient that is used to communicate\n// with API server by this client implementation.\nfunc (c *MetricsV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}","line":{"from":105,"to":112}} {"id":100034767,"name":"newNodeMetricses","signature":"func newNodeMetricses(c *MetricsV1beta1Client) *nodeMetricses","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1beta1/nodemetrics.go","code":"// newNodeMetricses returns a NodeMetricses\nfunc newNodeMetricses(c *MetricsV1beta1Client) *nodeMetricses {\n\treturn \u0026nodeMetricses{\n\t\tclient: c.RESTClient(),\n\t}\n}","line":{"from":51,"to":56}} {"id":100034768,"name":"Get","signature":"func (c *nodeMetricses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.NodeMetrics, err error)","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1beta1/nodemetrics.go","code":"// Get takes name of the nodeMetrics, and returns the corresponding nodeMetrics object, and an error if there is any.\nfunc (c *nodeMetricses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.NodeMetrics, err error) {\n\tresult = \u0026v1beta1.NodeMetrics{}\n\terr = c.client.Get().\n\t\tResource(\"nodes\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":58,"to":68}} {"id":100034769,"name":"List","signature":"func (c *nodeMetricses) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.NodeMetricsList, err error)","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1beta1/nodemetrics.go","code":"// List takes label and field selectors, and returns the list of NodeMetricses that match those selectors.\nfunc (c *nodeMetricses) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.NodeMetricsList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.NodeMetricsList{}\n\terr = c.client.Get().\n\t\tResource(\"nodes\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":70,"to":84}} {"id":100034770,"name":"Watch","signature":"func (c *nodeMetricses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1beta1/nodemetrics.go","code":"// Watch returns a watch.Interface that watches the requested nodeMetricses.\nfunc (c *nodeMetricses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tResource(\"nodes\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":86,"to":98}} {"id":100034771,"name":"newPodMetricses","signature":"func newPodMetricses(c *MetricsV1beta1Client, namespace string) *podMetricses","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1beta1/podmetrics.go","code":"// newPodMetricses returns a PodMetricses\nfunc newPodMetricses(c *MetricsV1beta1Client, namespace string) *podMetricses {\n\treturn \u0026podMetricses{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}","line":{"from":52,"to":58}} {"id":100034772,"name":"Get","signature":"func (c *podMetricses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.PodMetrics, err error)","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1beta1/podmetrics.go","code":"// Get takes name of the podMetrics, and returns the corresponding podMetrics object, and an error if there is any.\nfunc (c *podMetricses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.PodMetrics, err error) {\n\tresult = \u0026v1beta1.PodMetrics{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"pods\").\n\t\tName(name).\n\t\tVersionedParams(\u0026options, scheme.ParameterCodec).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":60,"to":71}} {"id":100034773,"name":"List","signature":"func (c *podMetricses) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.PodMetricsList, err error)","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1beta1/podmetrics.go","code":"// List takes label and field selectors, and returns the list of PodMetricses that match those selectors.\nfunc (c *podMetricses) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.PodMetricsList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = \u0026v1beta1.PodMetricsList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"pods\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}","line":{"from":73,"to":88}} {"id":100034774,"name":"Watch","signature":"func (c *podMetricses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)","file":"staging/src/k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1beta1/podmetrics.go","code":"// Watch returns a watch.Interface that watches the requested podMetricses.\nfunc (c *podMetricses) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\topts.Watch = true\n\treturn c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"pods\").\n\t\tVersionedParams(\u0026opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tWatch(ctx)\n}","line":{"from":90,"to":103}} {"id":100034775,"name":"NewMetricConverter","signature":"func NewMetricConverter() *MetricConverter","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/converter.go","code":"// NewMetricConverter creates a MetricConverter which knows how to convert objects\n// between different versions of the custom metrics api.\nfunc NewMetricConverter() *MetricConverter {\n\treturn \u0026MetricConverter{\n\t\tscheme: scheme.Scheme,\n\t\tcodecs: serializer.NewCodecFactory(scheme.Scheme),\n\t\tinternalVersioner: runtime.NewMultiGroupVersioner(\n\t\t\tscheme.SchemeGroupVersion,\n\t\t\tschema.GroupKind{Group: cmint.GroupName, Kind: \"\"},\n\t\t\tschema.GroupKind{Group: cmv1beta1.GroupName, Kind: \"\"},\n\t\t\tschema.GroupKind{Group: cmv1beta2.GroupName, Kind: \"\"},\n\t\t),\n\t}\n}","line":{"from":49,"to":62}} {"id":100034776,"name":"Scheme","signature":"func (c *MetricConverter) Scheme() *runtime.Scheme","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/converter.go","code":"// Scheme returns the scheme used by this metric converter.\nfunc (c *MetricConverter) Scheme() *runtime.Scheme {\n\treturn c.scheme\n}","line":{"from":64,"to":67}} {"id":100034777,"name":"Codecs","signature":"func (c *MetricConverter) Codecs() serializer.CodecFactory","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/converter.go","code":"// Codecs returns the codecs used by this metric converter\nfunc (c *MetricConverter) Codecs() serializer.CodecFactory {\n\treturn c.codecs\n}","line":{"from":69,"to":72}} {"id":100034778,"name":"ConvertListOptionsToVersion","signature":"func (c *MetricConverter) ConvertListOptionsToVersion(opts *cmint.MetricListOptions, version schema.GroupVersion) (runtime.Object, error)","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/converter.go","code":"// ConvertListOptionsToVersion converts converts a set of MetricListOptions\n// to the provided GroupVersion.\nfunc (c *MetricConverter) ConvertListOptionsToVersion(opts *cmint.MetricListOptions, version schema.GroupVersion) (runtime.Object, error) {\n\tparamObj, err := c.UnsafeConvertToVersionVia(opts, version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn paramObj, nil\n}","line":{"from":74,"to":82}} {"id":100034779,"name":"ConvertResultToVersion","signature":"func (c *MetricConverter) ConvertResultToVersion(res rest.Result, gv schema.GroupVersion) (runtime.Object, error)","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/converter.go","code":"// ConvertResultToVersion converts a Result to the provided GroupVersion\nfunc (c *MetricConverter) ConvertResultToVersion(res rest.Result, gv schema.GroupVersion) (runtime.Object, error) {\n\tif err := res.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmetricBytes, err := res.Raw()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdecoder := c.codecs.UniversalDecoder(MetricVersions...)\n\trawMetricObj, err := runtime.Decode(decoder, metricBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmetricObj, err := c.UnsafeConvertToVersionVia(rawMetricObj, gv)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn metricObj, nil\n}","line":{"from":84,"to":106}} {"id":100034780,"name":"UnsafeConvertToVersionVia","signature":"func (c *MetricConverter) UnsafeConvertToVersionVia(obj runtime.Object, externalVersion schema.GroupVersion) (runtime.Object, error)","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/converter.go","code":"// UnsafeConvertToVersionVia is like Scheme.UnsafeConvertToVersion, but it does so via an internal version first.\n// We use it here to work with the v1beta2 client internally, while preserving backwards compatibility for existing custom metrics adapters\nfunc (c *MetricConverter) UnsafeConvertToVersionVia(obj runtime.Object, externalVersion schema.GroupVersion) (runtime.Object, error) {\n\tobjInt, err := c.scheme.UnsafeConvertToVersion(obj, schema.GroupVersion{Group: externalVersion.Group, Version: runtime.APIVersionInternal})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to convert the given object to the internal version: %v\", err)\n\t}\n\n\tobjExt, err := c.scheme.UnsafeConvertToVersion(objInt, externalVersion)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to convert the given object back to the external version: %v\", err)\n\t}\n\n\treturn objExt, err\n}","line":{"from":108,"to":122}} {"id":100034781,"name":"init","signature":"func init()","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/discovery.go","code":"func init() {\n\tmetricVersionsToGV = make(map[string]schema.GroupVersion)\n\tfor _, ver := range MetricVersions {\n\t\tmetricVersionsToGV[ver.String()] = ver\n\t}\n}","line":{"from":37,"to":42}} {"id":100034782,"name":"NewAvailableAPIsGetter","signature":"func NewAvailableAPIsGetter(client discovery.DiscoveryInterface) AvailableAPIsGetter","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/discovery.go","code":"// NewAvailableAPIsGetter creates an AvailableAPIsGetter that checks discovery\n// to find the available versions of the custom metrics api.\nfunc NewAvailableAPIsGetter(client discovery.DiscoveryInterface) AvailableAPIsGetter {\n\treturn \u0026apiVersionsFromDiscovery{\n\t\tclient: client,\n\t}\n}","line":{"from":44,"to":50}} {"id":100034783,"name":"fetchVersions","signature":"func (d *apiVersionsFromDiscovery) fetchVersions() (*metav1.APIGroup, error)","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/discovery.go","code":"// fetchVersions fetches the versions, but doesn't try to invalidate on cache misses.\nfunc (d *apiVersionsFromDiscovery) fetchVersions() (*metav1.APIGroup, error) {\n\t// TODO(directxman12): amend the discovery interface to ask for a particular group (/apis/foo)\n\tgroups, err := d.client.ServerGroups()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Determine the preferred version on the server by first finding the custom metrics group\n\tvar apiGroup *metav1.APIGroup\n\tfor _, group := range groups.Groups {\n\t\tif group.Name == cmint.GroupName {\n\t\t\tapiGroup = \u0026group\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif apiGroup == nil {\n\t\treturn nil, fmt.Errorf(\"no custom metrics API (%s) registered\", cmint.GroupName)\n\t}\n\n\treturn apiGroup, nil\n}","line":{"from":62,"to":84}} {"id":100034784,"name":"chooseVersion","signature":"func (d *apiVersionsFromDiscovery) chooseVersion(apiGroup *metav1.APIGroup) (schema.GroupVersion, error)","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/discovery.go","code":"// chooseVersion sets a preferred version of the custom metrics api based on available versions.\nfunc (d *apiVersionsFromDiscovery) chooseVersion(apiGroup *metav1.APIGroup) (schema.GroupVersion, error) {\n\tvar preferredVersion *schema.GroupVersion\n\tif gv, present := metricVersionsToGV[apiGroup.PreferredVersion.GroupVersion]; present \u0026\u0026 len(apiGroup.PreferredVersion.GroupVersion) != 0 {\n\t\tpreferredVersion = \u0026gv\n\t} else {\n\t\tfor _, version := range apiGroup.Versions {\n\t\t\tif gv, present := metricVersionsToGV[version.GroupVersion]; present {\n\t\t\t\tpreferredVersion = \u0026gv\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif preferredVersion == nil {\n\t\treturn schema.GroupVersion{}, fmt.Errorf(\"no known available metric versions found\")\n\t}\n\treturn *preferredVersion, nil\n}","line":{"from":86,"to":104}} {"id":100034785,"name":"PreferredVersion","signature":"func (d *apiVersionsFromDiscovery) PreferredVersion() (schema.GroupVersion, error)","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/discovery.go","code":"// PreferredVersion returns the current preferred version of the custom metrics api.\n// If none is specified, it will use the first known one.\nfunc (d *apiVersionsFromDiscovery) PreferredVersion() (schema.GroupVersion, error) {\n\td.mu.RLock()\n\tif d.prefVersion != nil {\n\t\t// if we've already got one, proceed with that\n\t\tdefer d.mu.RUnlock()\n\t\treturn *d.prefVersion, nil\n\t}\n\td.mu.RUnlock()\n\n\td.mu.Lock()\n\tdefer d.mu.Unlock()\n\n\t// double check, someone might have beaten us to it\n\tif d.prefVersion != nil {\n\t\treturn *d.prefVersion, nil\n\t}\n\n\t// populate our cache\n\tgroupInfo, err := d.fetchVersions()\n\tif err != nil {\n\t\treturn schema.GroupVersion{}, err\n\t}\n\tprefVersion, err := d.chooseVersion(groupInfo)\n\tif err != nil {\n\t\treturn schema.GroupVersion{}, err\n\t}\n\n\td.prefVersion = \u0026prefVersion\n\treturn *d.prefVersion, nil\n}","line":{"from":106,"to":137}} {"id":100034786,"name":"Invalidate","signature":"func (d *apiVersionsFromDiscovery) Invalidate()","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/discovery.go","code":"// Invalidate refreshes the preferred version information.\nfunc (d *apiVersionsFromDiscovery) Invalidate() {\n\td.mu.Lock()\n\tdefer d.mu.Unlock()\n\n\td.prefVersion = nil\n}","line":{"from":139,"to":145}} {"id":100034787,"name":"PeriodicallyInvalidate","signature":"func PeriodicallyInvalidate(cache AvailableAPIsGetter, interval time.Duration, stopCh \u003c-chan struct{})","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/multi_client.go","code":"// PeriodicallyInvalidate periodically invalidates the preferred version cache until\n// told to stop.\nfunc PeriodicallyInvalidate(cache AvailableAPIsGetter, interval time.Duration, stopCh \u003c-chan struct{}) {\n\tticker := time.NewTicker(interval)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase \u003c-ticker.C:\n\t\t\tcache.Invalidate()\n\t\tcase \u003c-stopCh:\n\t\t\treturn\n\t\t}\n\t}\n}","line":{"from":38,"to":52}} {"id":100034788,"name":"NewForConfig","signature":"func NewForConfig(baseConfig *rest.Config, mapper meta.RESTMapper, availableAPIs AvailableAPIsGetter) CustomMetricsClient","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/multi_client.go","code":"// NewForConfig creates a new custom metrics client which delegates to a client which\n// uses the preferred api version.\nfunc NewForConfig(baseConfig *rest.Config, mapper meta.RESTMapper, availableAPIs AvailableAPIsGetter) CustomMetricsClient {\n\treturn \u0026multiClient{\n\t\tclients: make(map[schema.GroupVersion]CustomMetricsClient),\n\t\tavailableAPIs: availableAPIs,\n\n\t\tnewClient: func(ver schema.GroupVersion) (CustomMetricsClient, error) {\n\t\t\treturn NewForVersionForConfig(rest.CopyConfig(baseConfig), mapper, ver)\n\t\t},\n\t}\n}","line":{"from":54,"to":65}} {"id":100034789,"name":"getPreferredClient","signature":"func (c *multiClient) getPreferredClient() (CustomMetricsClient, error)","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/multi_client.go","code":"// getPreferredClient returns a custom metrics client of the preferred api version.\nfunc (c *multiClient) getPreferredClient() (CustomMetricsClient, error) {\n\tpref, err := c.availableAPIs.PreferredVersion()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.mu.RLock()\n\tclient, present := c.clients[pref]\n\tc.mu.RUnlock()\n\tif present {\n\t\treturn client, nil\n\t}\n\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tclient, err = c.newClient(pref)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.clients[pref] = client\n\n\treturn client, nil\n}","line":{"from":75,"to":98}} {"id":100034790,"name":"RootScopedMetrics","signature":"func (c *multiClient) RootScopedMetrics() MetricsInterface","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/multi_client.go","code":"func (c *multiClient) RootScopedMetrics() MetricsInterface {\n\treturn \u0026multiClientInterface{clients: c}\n}","line":{"from":100,"to":102}} {"id":100034791,"name":"NamespacedMetrics","signature":"func (c *multiClient) NamespacedMetrics(namespace string) MetricsInterface","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/multi_client.go","code":"func (c *multiClient) NamespacedMetrics(namespace string) MetricsInterface {\n\treturn \u0026multiClientInterface{\n\t\tclients: c,\n\t\tnamespace: \u0026namespace,\n\t}\n}","line":{"from":104,"to":109}} {"id":100034792,"name":"GetForObject","signature":"func (m *multiClientInterface) GetForObject(groupKind schema.GroupKind, name string, metricName string, metricSelector labels.Selector) (*v1beta2.MetricValue, error)","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/multi_client.go","code":"func (m *multiClientInterface) GetForObject(groupKind schema.GroupKind, name string, metricName string, metricSelector labels.Selector) (*v1beta2.MetricValue, error) {\n\tclient, err := m.clients.getPreferredClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif m.namespace == nil {\n\t\treturn client.RootScopedMetrics().GetForObject(groupKind, name, metricName, metricSelector)\n\t} else {\n\t\treturn client.NamespacedMetrics(*m.namespace).GetForObject(groupKind, name, metricName, metricSelector)\n\t}\n}","line":{"from":116,"to":126}} {"id":100034793,"name":"GetForObjects","signature":"func (m *multiClientInterface) GetForObjects(groupKind schema.GroupKind, selector labels.Selector, metricName string, metricSelector labels.Selector) (*v1beta2.MetricValueList, error)","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/multi_client.go","code":"func (m *multiClientInterface) GetForObjects(groupKind schema.GroupKind, selector labels.Selector, metricName string, metricSelector labels.Selector) (*v1beta2.MetricValueList, error) {\n\tclient, err := m.clients.getPreferredClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif m.namespace == nil {\n\t\treturn client.RootScopedMetrics().GetForObjects(groupKind, selector, metricName, metricSelector)\n\t} else {\n\t\treturn client.NamespacedMetrics(*m.namespace).GetForObjects(groupKind, selector, metricName, metricSelector)\n\t}\n}","line":{"from":128,"to":138}} {"id":100034794,"name":"init","signature":"func init()","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/scheme/register.go","code":"func init() {\n\tmetav1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: \"v1\"})\n\tAddToScheme(Scheme)\n}","line":{"from":44,"to":47}} {"id":100034795,"name":"AddToScheme","signature":"func AddToScheme(scheme *runtime.Scheme)","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/scheme/register.go","code":"// AddToScheme adds all types of this clientset into the given scheme. This allows composition\n// of clientsets, like in:\n//\n//\timport (\n//\t \"k8s.io/client-go/kubernetes\"\n//\t clientsetscheme \"k8s.io/client-go/kubernetes/scheme\"\n//\t aggregatorclientsetscheme \"k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme\"\n//\t)\n//\n//\tkclientset, _ := kubernetes.NewForConfig(c)\n//\taggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme)\n//\n// After this, RawExtensions in Kubernetes types will serialize kube-aggregator types\n// correctly.\nfunc AddToScheme(scheme *runtime.Scheme) {\n\tcmint.AddToScheme(scheme)\n\tcmv1beta1.AddToScheme(scheme)\n\tcmv1beta2.AddToScheme(scheme)\n}","line":{"from":49,"to":67}} {"id":100034796,"name":"NewForVersion","signature":"func NewForVersion(client rest.Interface, mapper meta.RESTMapper, version schema.GroupVersion) CustomMetricsClient","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/versioned_client.go","code":"// NewForVersion returns a new CustomMetricsClient for a particular api version.\nfunc NewForVersion(client rest.Interface, mapper meta.RESTMapper, version schema.GroupVersion) CustomMetricsClient {\n\treturn \u0026customMetricsClient{\n\t\tclient: client,\n\t\tversion: version,\n\t\tmapper: mapper,\n\t}\n}","line":{"from":44,"to":51}} {"id":100034797,"name":"NewForVersionForConfig","signature":"func NewForVersionForConfig(c *rest.Config, mapper meta.RESTMapper, version schema.GroupVersion) (CustomMetricsClient, error)","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/versioned_client.go","code":"// NewForVersionForConfig returns a new CustomMetricsClient for a particular api version and base configuration.\nfunc NewForVersionForConfig(c *rest.Config, mapper meta.RESTMapper, version schema.GroupVersion) (CustomMetricsClient, error) {\n\tconfigShallowCopy := *c\n\tif configShallowCopy.RateLimiter == nil \u0026\u0026 configShallowCopy.QPS \u003e 0 {\n\t\tif configShallowCopy.Burst \u003c= 0 {\n\t\t\treturn nil, fmt.Errorf(\"burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0\")\n\t\t}\n\t\tconfigShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst)\n\t}\n\tconfigShallowCopy.APIPath = \"/apis\"\n\tif configShallowCopy.UserAgent == \"\" {\n\t\tconfigShallowCopy.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\tconfigShallowCopy.GroupVersion = \u0026version\n\tconfigShallowCopy.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tclient, err := rest.RESTClientFor(\u0026configShallowCopy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewForVersion(client, mapper, version), nil\n}","line":{"from":53,"to":75}} {"id":100034798,"name":"RootScopedMetrics","signature":"func (c *customMetricsClient) RootScopedMetrics() MetricsInterface","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/versioned_client.go","code":"func (c *customMetricsClient) RootScopedMetrics() MetricsInterface {\n\treturn \u0026rootScopedMetrics{c}\n}","line":{"from":77,"to":79}} {"id":100034799,"name":"NamespacedMetrics","signature":"func (c *customMetricsClient) NamespacedMetrics(namespace string) MetricsInterface","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/versioned_client.go","code":"func (c *customMetricsClient) NamespacedMetrics(namespace string) MetricsInterface {\n\treturn \u0026namespacedMetrics{\n\t\tclient: c,\n\t\tnamespace: namespace,\n\t}\n}","line":{"from":81,"to":86}} {"id":100034800,"name":"qualResourceForKind","signature":"func (c *customMetricsClient) qualResourceForKind(groupKind schema.GroupKind) (string, error)","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/versioned_client.go","code":"// qualResourceForKind returns the string format of a qualified group resource for the specified GroupKind\nfunc (c *customMetricsClient) qualResourceForKind(groupKind schema.GroupKind) (string, error) {\n\tmapping, err := c.mapper.RESTMapping(groupKind)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to map kind %s to resource: %v\", groupKind.String(), err)\n\t}\n\n\tgr := mapping.Resource.GroupResource()\n\treturn gr.String(), nil\n}","line":{"from":88,"to":97}} {"id":100034801,"name":"getForNamespace","signature":"func (m *rootScopedMetrics) getForNamespace(namespace string, metricName string, metricSelector labels.Selector) (*v1beta2.MetricValue, error)","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/versioned_client.go","code":"func (m *rootScopedMetrics) getForNamespace(namespace string, metricName string, metricSelector labels.Selector) (*v1beta2.MetricValue, error) {\n\tparams, err := versionConverter.ConvertListOptionsToVersion(\u0026cmint.MetricListOptions{\n\t\tMetricLabelSelector: metricSelector.String(),\n\t}, m.client.version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := m.client.client.Get().\n\t\tResource(\"metrics\").\n\t\tNamespace(namespace).\n\t\tName(metricName).\n\t\tVersionedParams(params, scheme.ParameterCodec).\n\t\tDo(context.TODO())\n\n\tmetricObj, err := versionConverter.ConvertResultToVersion(result, v1beta2.SchemeGroupVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar res *v1beta2.MetricValueList\n\tvar ok bool\n\tif res, ok = metricObj.(*v1beta2.MetricValueList); !ok {\n\t\treturn nil, fmt.Errorf(\"the custom metrics API server didn't return MetricValueList, the type is %v\", reflect.TypeOf(metricObj))\n\t}\n\tif len(res.Items) != 1 {\n\t\treturn nil, fmt.Errorf(\"the custom metrics API server returned %v results when we asked for exactly one\", len(res.Items))\n\t}\n\n\treturn \u0026res.Items[0], nil\n}","line":{"from":103,"to":133}} {"id":100034802,"name":"GetForObject","signature":"func (m *rootScopedMetrics) GetForObject(groupKind schema.GroupKind, name string, metricName string, metricSelector labels.Selector) (*v1beta2.MetricValue, error)","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/versioned_client.go","code":"func (m *rootScopedMetrics) GetForObject(groupKind schema.GroupKind, name string, metricName string, metricSelector labels.Selector) (*v1beta2.MetricValue, error) {\n\t// handle namespace separately\n\tif groupKind.Kind == \"Namespace\" \u0026\u0026 groupKind.Group == \"\" {\n\t\treturn m.getForNamespace(name, metricName, metricSelector)\n\t}\n\n\tresourceName, err := m.client.qualResourceForKind(groupKind)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparams, err := versionConverter.ConvertListOptionsToVersion(\u0026cmint.MetricListOptions{\n\t\tMetricLabelSelector: metricSelector.String(),\n\t}, m.client.version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := m.client.client.Get().\n\t\tResource(resourceName).\n\t\tName(name).\n\t\tSubResource(metricName).\n\t\tVersionedParams(params, scheme.ParameterCodec).\n\t\tDo(context.TODO())\n\n\tmetricObj, err := versionConverter.ConvertResultToVersion(result, v1beta2.SchemeGroupVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar res *v1beta2.MetricValueList\n\tvar ok bool\n\tif res, ok = metricObj.(*v1beta2.MetricValueList); !ok {\n\t\treturn nil, fmt.Errorf(\"the custom metrics API server didn't return MetricValueList, the type is %v\", reflect.TypeOf(metricObj))\n\t}\n\tif len(res.Items) != 1 {\n\t\treturn nil, fmt.Errorf(\"the custom metrics API server returned %v results when we asked for exactly one\", len(res.Items))\n\t}\n\n\treturn \u0026res.Items[0], nil\n}","line":{"from":135,"to":175}} {"id":100034803,"name":"GetForObjects","signature":"func (m *rootScopedMetrics) GetForObjects(groupKind schema.GroupKind, selector labels.Selector, metricName string, metricSelector labels.Selector) (*v1beta2.MetricValueList, error)","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/versioned_client.go","code":"func (m *rootScopedMetrics) GetForObjects(groupKind schema.GroupKind, selector labels.Selector, metricName string, metricSelector labels.Selector) (*v1beta2.MetricValueList, error) {\n\t// we can't wildcard-fetch for namespaces\n\tif groupKind.Kind == \"Namespace\" \u0026\u0026 groupKind.Group == \"\" {\n\t\treturn nil, fmt.Errorf(\"cannot fetch metrics for multiple namespaces at once\")\n\t}\n\n\tresourceName, err := m.client.qualResourceForKind(groupKind)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparams, err := versionConverter.ConvertListOptionsToVersion(\u0026cmint.MetricListOptions{\n\t\tLabelSelector: selector.String(),\n\t\tMetricLabelSelector: metricSelector.String(),\n\t}, m.client.version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := m.client.client.Get().\n\t\tResource(resourceName).\n\t\tName(v1beta1.AllObjects).\n\t\tSubResource(metricName).\n\t\tVersionedParams(params, scheme.ParameterCodec).\n\t\tDo(context.TODO())\n\n\tmetricObj, err := versionConverter.ConvertResultToVersion(result, v1beta2.SchemeGroupVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar res *v1beta2.MetricValueList\n\tvar ok bool\n\tif res, ok = metricObj.(*v1beta2.MetricValueList); !ok {\n\t\treturn nil, fmt.Errorf(\"the custom metrics API server didn't return MetricValueList, the type is %v\", reflect.TypeOf(metricObj))\n\t}\n\treturn res, nil\n}","line":{"from":177,"to":214}} {"id":100034804,"name":"GetForObject","signature":"func (m *namespacedMetrics) GetForObject(groupKind schema.GroupKind, name string, metricName string, metricSelector labels.Selector) (*v1beta2.MetricValue, error)","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/versioned_client.go","code":"func (m *namespacedMetrics) GetForObject(groupKind schema.GroupKind, name string, metricName string, metricSelector labels.Selector) (*v1beta2.MetricValue, error) {\n\tresourceName, err := m.client.qualResourceForKind(groupKind)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparams, err := versionConverter.ConvertListOptionsToVersion(\u0026cmint.MetricListOptions{\n\t\tMetricLabelSelector: metricSelector.String(),\n\t}, m.client.version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := m.client.client.Get().\n\t\tResource(resourceName).\n\t\tNamespace(m.namespace).\n\t\tName(name).\n\t\tSubResource(metricName).\n\t\tVersionedParams(params, scheme.ParameterCodec).\n\t\tDo(context.TODO())\n\n\tmetricObj, err := versionConverter.ConvertResultToVersion(result, v1beta2.SchemeGroupVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar res *v1beta2.MetricValueList\n\tvar ok bool\n\tif res, ok = metricObj.(*v1beta2.MetricValueList); !ok {\n\t\treturn nil, fmt.Errorf(\"the custom metrics API server didn't return MetricValueList, the type is %v\", reflect.TypeOf(metricObj))\n\t}\n\tif len(res.Items) != 1 {\n\t\treturn nil, fmt.Errorf(\"the custom metrics API server returned %v results when we asked for exactly one\", len(res.Items))\n\t}\n\n\treturn \u0026res.Items[0], nil\n}","line":{"from":221,"to":257}} {"id":100034805,"name":"GetForObjects","signature":"func (m *namespacedMetrics) GetForObjects(groupKind schema.GroupKind, selector labels.Selector, metricName string, metricSelector labels.Selector) (*v1beta2.MetricValueList, error)","file":"staging/src/k8s.io/metrics/pkg/client/custom_metrics/versioned_client.go","code":"func (m *namespacedMetrics) GetForObjects(groupKind schema.GroupKind, selector labels.Selector, metricName string, metricSelector labels.Selector) (*v1beta2.MetricValueList, error) {\n\tresourceName, err := m.client.qualResourceForKind(groupKind)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparams, err := versionConverter.ConvertListOptionsToVersion(\u0026cmint.MetricListOptions{\n\t\tLabelSelector: selector.String(),\n\t\tMetricLabelSelector: metricSelector.String(),\n\t}, m.client.version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := m.client.client.Get().\n\t\tResource(resourceName).\n\t\tNamespace(m.namespace).\n\t\tName(v1beta1.AllObjects).\n\t\tSubResource(metricName).\n\t\tVersionedParams(params, scheme.ParameterCodec).\n\t\tDo(context.TODO())\n\n\tmetricObj, err := versionConverter.ConvertResultToVersion(result, v1beta2.SchemeGroupVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar res *v1beta2.MetricValueList\n\tvar ok bool\n\tif res, ok = metricObj.(*v1beta2.MetricValueList); !ok {\n\t\treturn nil, fmt.Errorf(\"the custom metrics API server didn't return MetricValueList, the type is %v\", reflect.TypeOf(metricObj))\n\t}\n\treturn res, nil\n}","line":{"from":259,"to":292}} {"id":100034806,"name":"New","signature":"func New(client rest.Interface) ExternalMetricsClient","file":"staging/src/k8s.io/metrics/pkg/client/external_metrics/client.go","code":"func New(client rest.Interface) ExternalMetricsClient {\n\treturn \u0026externalMetricsClient{\n\t\tclient: client,\n\t}\n}","line":{"from":35,"to":39}} {"id":100034807,"name":"NewForConfig","signature":"func NewForConfig(c *rest.Config) (ExternalMetricsClient, error)","file":"staging/src/k8s.io/metrics/pkg/client/external_metrics/client.go","code":"func NewForConfig(c *rest.Config) (ExternalMetricsClient, error) {\n\tconfigShallowCopy := *c\n\tif configShallowCopy.RateLimiter == nil \u0026\u0026 configShallowCopy.QPS \u003e 0 {\n\t\tif configShallowCopy.Burst \u003c= 0 {\n\t\t\treturn nil, fmt.Errorf(\"burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0\")\n\t\t}\n\t\tconfigShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst)\n\t}\n\tconfigShallowCopy.APIPath = \"/apis\"\n\tif configShallowCopy.UserAgent == \"\" {\n\t\tconfigShallowCopy.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\tconfigShallowCopy.GroupVersion = \u0026v1beta1.SchemeGroupVersion\n\tconfigShallowCopy.NegotiatedSerializer = scheme.Codecs.WithoutConversion()\n\n\tclient, err := rest.RESTClientFor(\u0026configShallowCopy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn New(client), nil\n}","line":{"from":41,"to":62}} {"id":100034808,"name":"NewForConfigOrDie","signature":"func NewForConfigOrDie(c *rest.Config) ExternalMetricsClient","file":"staging/src/k8s.io/metrics/pkg/client/external_metrics/client.go","code":"func NewForConfigOrDie(c *rest.Config) ExternalMetricsClient {\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}","line":{"from":64,"to":70}} {"id":100034809,"name":"NamespacedMetrics","signature":"func (c *externalMetricsClient) NamespacedMetrics(namespace string) MetricsInterface","file":"staging/src/k8s.io/metrics/pkg/client/external_metrics/client.go","code":"func (c *externalMetricsClient) NamespacedMetrics(namespace string) MetricsInterface {\n\treturn \u0026namespacedMetrics{\n\t\tclient: c,\n\t\tnamespace: namespace,\n\t}\n}","line":{"from":72,"to":77}} {"id":100034810,"name":"List","signature":"func (m *namespacedMetrics) List(metricName string, metricSelector labels.Selector) (*v1beta1.ExternalMetricValueList, error)","file":"staging/src/k8s.io/metrics/pkg/client/external_metrics/client.go","code":"func (m *namespacedMetrics) List(metricName string, metricSelector labels.Selector) (*v1beta1.ExternalMetricValueList, error) {\n\tres := \u0026v1beta1.ExternalMetricValueList{}\n\terr := m.client.client.Get().\n\t\tNamespace(m.namespace).\n\t\tResource(metricName).\n\t\tVersionedParams(\u0026metav1.ListOptions{\n\t\t\tLabelSelector: metricSelector.String(),\n\t\t}, metav1.ParameterCodec).\n\t\tDo(context.TODO()).\n\t\tInto(res)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res, nil\n}","line":{"from":84,"to":100}} {"id":100034811,"name":"String","signature":"func (mountError MountError) String() string","file":"staging/src/k8s.io/mount-utils/mount.go","code":"func (mountError MountError) String() string {\n\treturn mountError.Message\n}","line":{"from":128,"to":130}} {"id":100034812,"name":"Error","signature":"func (mountError MountError) Error() string","file":"staging/src/k8s.io/mount-utils/mount.go","code":"func (mountError MountError) Error() string {\n\treturn mountError.Message\n}","line":{"from":132,"to":134}} {"id":100034813,"name":"NewMountError","signature":"func NewMountError(mountErrorValue MountErrorType, format string, args ...interface{}) error","file":"staging/src/k8s.io/mount-utils/mount.go","code":"func NewMountError(mountErrorValue MountErrorType, format string, args ...interface{}) error {\n\tmountError := MountError{\n\t\tType: mountErrorValue,\n\t\tMessage: fmt.Sprintf(format, args...),\n\t}\n\treturn mountError\n}","line":{"from":136,"to":142}} {"id":100034814,"name":"NewSafeFormatAndMount","signature":"func NewSafeFormatAndMount(mounter Interface, exec utilexec.Interface, opts ...Option) *SafeFormatAndMount","file":"staging/src/k8s.io/mount-utils/mount.go","code":"func NewSafeFormatAndMount(mounter Interface, exec utilexec.Interface, opts ...Option) *SafeFormatAndMount {\n\tres := \u0026SafeFormatAndMount{\n\t\tInterface: mounter,\n\t\tExec: exec,\n\t}\n\tfor _, opt := range opts {\n\t\topt(res)\n\t}\n\treturn res\n}","line":{"from":155,"to":164}} {"id":100034815,"name":"WithMaxConcurrentFormat","signature":"func WithMaxConcurrentFormat(n int, timeout time.Duration) Option","file":"staging/src/k8s.io/mount-utils/mount.go","code":"// WithMaxConcurrentFormat sets the maximum number of concurrent format\n// operations executed by the mounter. The timeout controls the maximum\n// duration of a format operation before its concurrency token is released.\n// Once a token is released, it can be acquired by another concurrent format\n// operation. The original operation is allowed to complete.\n// If n \u003c 1, concurrency is set to unlimited.\nfunc WithMaxConcurrentFormat(n int, timeout time.Duration) Option {\n\treturn func(mounter *SafeFormatAndMount) {\n\t\tif n \u003e 0 {\n\t\t\tmounter.formatSem = make(chan any, n)\n\t\t\tmounter.formatTimeout = timeout\n\t\t}\n\t}\n}","line":{"from":168,"to":181}} {"id":100034816,"name":"FormatAndMount","signature":"func (mounter *SafeFormatAndMount) FormatAndMount(source string, target string, fstype string, options []string) error","file":"staging/src/k8s.io/mount-utils/mount.go","code":"// FormatAndMount formats the given disk, if needed, and mounts it.\n// That is if the disk is not formatted and it is not being mounted as\n// read-only it will format it first then mount it. Otherwise, if the\n// disk is already formatted or it is being mounted as read-only, it\n// will be mounted without formatting.\n// options MUST not contain sensitive material (like passwords).\nfunc (mounter *SafeFormatAndMount) FormatAndMount(source string, target string, fstype string, options []string) error {\n\treturn mounter.FormatAndMountSensitive(source, target, fstype, options, nil /* sensitiveOptions */)\n}","line":{"from":183,"to":191}} {"id":100034817,"name":"FormatAndMountSensitive","signature":"func (mounter *SafeFormatAndMount) FormatAndMountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string) error","file":"staging/src/k8s.io/mount-utils/mount.go","code":"// FormatAndMountSensitive is the same as FormatAndMount but this method allows\n// sensitiveOptions to be passed in a separate parameter from the normal mount\n// options and ensures the sensitiveOptions are never logged. This method should\n// be used by callers that pass sensitive material (like passwords) as mount\n// options.\nfunc (mounter *SafeFormatAndMount) FormatAndMountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string) error {\n\treturn mounter.FormatAndMountSensitiveWithFormatOptions(source, target, fstype, options, sensitiveOptions, nil /* formatOptions */)\n}","line":{"from":193,"to":200}} {"id":100034818,"name":"FormatAndMountSensitiveWithFormatOptions","signature":"func (mounter *SafeFormatAndMount) FormatAndMountSensitiveWithFormatOptions(source string, target string, fstype string, options []string, sensitiveOptions []string, formatOptions []string) error","file":"staging/src/k8s.io/mount-utils/mount.go","code":"// FormatAndMountSensitiveWithFormatOptions behaves exactly the same as\n// FormatAndMountSensitive, but allows for options to be passed when the disk\n// is formatted. These options are NOT validated in any way and should never\n// come directly from untrusted user input as that would be an injection risk.\nfunc (mounter *SafeFormatAndMount) FormatAndMountSensitiveWithFormatOptions(source string, target string, fstype string, options []string, sensitiveOptions []string, formatOptions []string) error {\n\treturn mounter.formatAndMountSensitive(source, target, fstype, options, sensitiveOptions, formatOptions)\n}","line":{"from":202,"to":208}} {"id":100034819,"name":"getMountRefsByDev","signature":"func getMountRefsByDev(mounter Interface, mountPath string) ([]string, error)","file":"staging/src/k8s.io/mount-utils/mount.go","code":"// getMountRefsByDev finds all references to the device provided\n// by mountPath; returns a list of paths.\n// Note that mountPath should be path after the evaluation of any symblolic links.\nfunc getMountRefsByDev(mounter Interface, mountPath string) ([]string, error) {\n\tmps, err := mounter.List()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Finding the device mounted to mountPath.\n\tdiskDev := \"\"\n\tfor i := range mps {\n\t\tif mountPath == mps[i].Path {\n\t\t\tdiskDev = mps[i].Device\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Find all references to the device.\n\tvar refs []string\n\tfor i := range mps {\n\t\tif mps[i].Device == diskDev || mps[i].Device == mountPath {\n\t\t\tif mps[i].Path != mountPath {\n\t\t\t\trefs = append(refs, mps[i].Path)\n\t\t\t}\n\t\t}\n\t}\n\treturn refs, nil\n}","line":{"from":210,"to":238}} {"id":100034820,"name":"IsNotMountPoint","signature":"func IsNotMountPoint(mounter Interface, file string) (bool, error)","file":"staging/src/k8s.io/mount-utils/mount.go","code":"// IsNotMountPoint determines if a directory is a mountpoint.\n// It should return ErrNotExist when the directory does not exist.\n// IsNotMountPoint is more expensive than IsLikelyNotMountPoint\n// and depends on IsMountPoint.\n//\n// If an error occurs, it returns true (assuming it is not a mountpoint)\n// when ErrNotExist is returned for callers similar to IsLikelyNotMountPoint.\n//\n// Deprecated: This function is kept to keep changes backward compatible with\n// previous library version. Callers should prefer mounter.IsMountPoint.\nfunc IsNotMountPoint(mounter Interface, file string) (bool, error) {\n\tisMnt, err := mounter.IsMountPoint(file)\n\tif err != nil {\n\t\treturn true, err\n\t}\n\treturn !isMnt, nil\n}","line":{"from":240,"to":256}} {"id":100034821,"name":"GetDeviceNameFromMount","signature":"func GetDeviceNameFromMount(mounter Interface, mountPath string) (string, int, error)","file":"staging/src/k8s.io/mount-utils/mount.go","code":"// GetDeviceNameFromMount given a mnt point, find the device from /proc/mounts\n// returns the device name, reference count, and error code.\nfunc GetDeviceNameFromMount(mounter Interface, mountPath string) (string, int, error) {\n\tmps, err := mounter.List()\n\tif err != nil {\n\t\treturn \"\", 0, err\n\t}\n\n\t// Find the device name.\n\t// FIXME if multiple devices mounted on the same mount path, only the first one is returned.\n\tdevice := \"\"\n\t// If mountPath is symlink, need get its target path.\n\tslTarget, err := filepath.EvalSymlinks(mountPath)\n\tif err != nil {\n\t\tslTarget = mountPath\n\t}\n\tfor i := range mps {\n\t\tif mps[i].Path == slTarget {\n\t\t\tdevice = mps[i].Device\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Find all references to the device.\n\trefCount := 0\n\tfor i := range mps {\n\t\tif mps[i].Device == device {\n\t\t\trefCount++\n\t\t}\n\t}\n\treturn device, refCount, nil\n}","line":{"from":258,"to":289}} {"id":100034822,"name":"MakeBindOpts","signature":"func MakeBindOpts(options []string) (bool, []string, []string)","file":"staging/src/k8s.io/mount-utils/mount.go","code":"// MakeBindOpts detects whether a bind mount is being requested and makes the remount options to\n// use in case of bind mount, due to the fact that bind mount doesn't respect mount options.\n// The list equals:\n//\n//\toptions - 'bind' + 'remount' (no duplicate)\nfunc MakeBindOpts(options []string) (bool, []string, []string) {\n\tbind, bindOpts, bindRemountOpts, _ := MakeBindOptsSensitive(options, nil /* sensitiveOptions */)\n\treturn bind, bindOpts, bindRemountOpts\n}","line":{"from":291,"to":299}} {"id":100034823,"name":"MakeBindOptsSensitive","signature":"func MakeBindOptsSensitive(options []string, sensitiveOptions []string) (bool, []string, []string, []string)","file":"staging/src/k8s.io/mount-utils/mount.go","code":"// MakeBindOptsSensitive is the same as MakeBindOpts but this method allows\n// sensitiveOptions to be passed in a separate parameter from the normal mount\n// options and ensures the sensitiveOptions are never logged. This method should\n// be used by callers that pass sensitive material (like passwords) as mount\n// options.\nfunc MakeBindOptsSensitive(options []string, sensitiveOptions []string) (bool, []string, []string, []string) {\n\t// Because we have an FD opened on the subpath bind mount, the \"bind\" option\n\t// needs to be included, otherwise the mount target will error as busy if you\n\t// remount as readonly.\n\t//\n\t// As a consequence, all read only bind mounts will no longer change the underlying\n\t// volume mount to be read only.\n\tbindRemountOpts := []string{\"bind\", \"remount\"}\n\tbindRemountSensitiveOpts := []string{}\n\tbind := false\n\tbindOpts := []string{\"bind\"}\n\n\t// _netdev is a userspace mount option and does not automatically get added when\n\t// bind mount is created and hence we must carry it over.\n\tif checkForNetDev(options, sensitiveOptions) {\n\t\tbindOpts = append(bindOpts, \"_netdev\")\n\t}\n\n\tfor _, option := range options {\n\t\tswitch option {\n\t\tcase \"bind\":\n\t\t\tbind = true\n\t\tcase \"remount\":\n\t\tdefault:\n\t\t\tbindRemountOpts = append(bindRemountOpts, option)\n\t\t}\n\t}\n\n\tfor _, sensitiveOption := range sensitiveOptions {\n\t\tswitch sensitiveOption {\n\t\tcase \"bind\":\n\t\t\tbind = true\n\t\tcase \"remount\":\n\t\tdefault:\n\t\t\tbindRemountSensitiveOpts = append(bindRemountSensitiveOpts, sensitiveOption)\n\t\t}\n\t}\n\n\treturn bind, bindOpts, bindRemountOpts, bindRemountSensitiveOpts\n}","line":{"from":301,"to":345}} {"id":100034824,"name":"checkForNetDev","signature":"func checkForNetDev(options []string, sensitiveOptions []string) bool","file":"staging/src/k8s.io/mount-utils/mount.go","code":"func checkForNetDev(options []string, sensitiveOptions []string) bool {\n\tfor _, option := range options {\n\t\tif option == \"_netdev\" {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor _, sensitiveOption := range sensitiveOptions {\n\t\tif sensitiveOption == \"_netdev\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":347,"to":359}} {"id":100034825,"name":"PathWithinBase","signature":"func PathWithinBase(fullPath, basePath string) bool","file":"staging/src/k8s.io/mount-utils/mount.go","code":"// PathWithinBase checks if give path is within given base directory.\nfunc PathWithinBase(fullPath, basePath string) bool {\n\trel, err := filepath.Rel(basePath, fullPath)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif StartsWithBackstep(rel) {\n\t\t// Needed to escape the base path.\n\t\treturn false\n\t}\n\treturn true\n}","line":{"from":361,"to":372}} {"id":100034826,"name":"StartsWithBackstep","signature":"func StartsWithBackstep(rel string) bool","file":"staging/src/k8s.io/mount-utils/mount.go","code":"// StartsWithBackstep checks if the given path starts with a backstep segment.\nfunc StartsWithBackstep(rel string) bool {\n\t// normalize to / and check for ../\n\treturn rel == \"..\" || strings.HasPrefix(filepath.ToSlash(rel), \"../\")\n}","line":{"from":374,"to":378}} {"id":100034827,"name":"sanitizedOptionsForLogging","signature":"func sanitizedOptionsForLogging(options []string, sensitiveOptions []string) string","file":"staging/src/k8s.io/mount-utils/mount.go","code":"// sanitizedOptionsForLogging will return a comma separated string containing\n// options and sensitiveOptions. Each entry in sensitiveOptions will be\n// replaced with the string sensitiveOptionsRemoved\n// e.g. o1,o2,\u003cmasked\u003e,\u003cmasked\u003e\nfunc sanitizedOptionsForLogging(options []string, sensitiveOptions []string) string {\n\tseparator := \"\"\n\tif len(options) \u003e 0 \u0026\u0026 len(sensitiveOptions) \u003e 0 {\n\t\tseparator = \",\"\n\t}\n\n\tsensitiveOptionsStart := \"\"\n\tsensitiveOptionsEnd := \"\"\n\tif len(sensitiveOptions) \u003e 0 {\n\t\tsensitiveOptionsStart = strings.Repeat(sensitiveOptionsRemoved+\",\", len(sensitiveOptions)-1)\n\t\tsensitiveOptionsEnd = sensitiveOptionsRemoved\n\t}\n\n\treturn strings.Join(options, \",\") +\n\t\tseparator +\n\t\tsensitiveOptionsStart +\n\t\tsensitiveOptionsEnd\n}","line":{"from":380,"to":401}} {"id":100034828,"name":"CleanupMountPoint","signature":"func CleanupMountPoint(mountPath string, mounter Interface, extensiveMountPointCheck bool) error","file":"staging/src/k8s.io/mount-utils/mount_helper_common.go","code":"// CleanupMountPoint unmounts the given path and deletes the remaining directory\n// if successful. If extensiveMountPointCheck is true IsNotMountPoint will be\n// called instead of IsLikelyNotMountPoint. IsNotMountPoint is more expensive\n// but properly handles bind mounts within the same fs.\nfunc CleanupMountPoint(mountPath string, mounter Interface, extensiveMountPointCheck bool) error {\n\tpathExists, pathErr := PathExists(mountPath)\n\tif !pathExists \u0026\u0026 pathErr == nil {\n\t\tklog.Warningf(\"Warning: mount cleanup skipped because path does not exist: %v\", mountPath)\n\t\treturn nil\n\t}\n\tcorruptedMnt := IsCorruptedMnt(pathErr)\n\tif pathErr != nil \u0026\u0026 !corruptedMnt {\n\t\treturn fmt.Errorf(\"Error checking path: %v\", pathErr)\n\t}\n\treturn doCleanupMountPoint(mountPath, mounter, extensiveMountPointCheck, corruptedMnt)\n}","line":{"from":27,"to":42}} {"id":100034829,"name":"CleanupMountWithForce","signature":"func CleanupMountWithForce(mountPath string, mounter MounterForceUnmounter, extensiveMountPointCheck bool, umountTimeout time.Duration) error","file":"staging/src/k8s.io/mount-utils/mount_helper_common.go","code":"func CleanupMountWithForce(mountPath string, mounter MounterForceUnmounter, extensiveMountPointCheck bool, umountTimeout time.Duration) error {\n\tpathExists, pathErr := PathExists(mountPath)\n\tif !pathExists \u0026\u0026 pathErr == nil {\n\t\tklog.Warningf(\"Warning: mount cleanup skipped because path does not exist: %v\", mountPath)\n\t\treturn nil\n\t}\n\tcorruptedMnt := IsCorruptedMnt(pathErr)\n\tif pathErr != nil \u0026\u0026 !corruptedMnt {\n\t\treturn fmt.Errorf(\"Error checking path: %v\", pathErr)\n\t}\n\n\tif corruptedMnt || mounter.CanSafelySkipMountPointCheck() {\n\t\tklog.V(4).Infof(\"unmounting %q (corruptedMount: %t, mounterCanSkipMountPointChecks: %t)\",\n\t\t\tmountPath, corruptedMnt, mounter.CanSafelySkipMountPointCheck())\n\t\tif err := mounter.UnmountWithForce(mountPath, umountTimeout); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn removePath(mountPath)\n\t}\n\n\tnotMnt, err := removePathIfNotMountPoint(mountPath, mounter, extensiveMountPointCheck)\n\t// if mountPath is not a mount point, it's just been removed or there was an error\n\tif err != nil || notMnt {\n\t\treturn err\n\t}\n\n\tklog.V(4).Infof(\"%q is a mountpoint, unmounting\", mountPath)\n\tif err := mounter.UnmountWithForce(mountPath, umountTimeout); err != nil {\n\t\treturn err\n\t}\n\n\tnotMnt, err = removePathIfNotMountPoint(mountPath, mounter, extensiveMountPointCheck)\n\t// if mountPath is not a mount point, it's either just been removed or there was an error\n\tif notMnt {\n\t\treturn err\n\t}\n\t// mountPath is still a mount point\n\treturn fmt.Errorf(\"failed to cleanup mount point %v\", mountPath)\n}","line":{"from":44,"to":82}} {"id":100034830,"name":"doCleanupMountPoint","signature":"func doCleanupMountPoint(mountPath string, mounter Interface, extensiveMountPointCheck bool, corruptedMnt bool) error","file":"staging/src/k8s.io/mount-utils/mount_helper_common.go","code":"// doCleanupMountPoint unmounts the given path and\n// deletes the remaining directory if successful.\n// if extensiveMountPointCheck is true\n// IsNotMountPoint will be called instead of IsLikelyNotMountPoint.\n// IsNotMountPoint is more expensive but properly handles bind mounts within the same fs.\n// if corruptedMnt is true, it means that the mountPath is a corrupted mountpoint, and the mount point check\n// will be skipped. The mount point check will also be skipped if the mounter supports it.\nfunc doCleanupMountPoint(mountPath string, mounter Interface, extensiveMountPointCheck bool, corruptedMnt bool) error {\n\tif corruptedMnt || mounter.CanSafelySkipMountPointCheck() {\n\t\tklog.V(4).Infof(\"unmounting %q (corruptedMount: %t, mounterCanSkipMountPointChecks: %t)\",\n\t\t\tmountPath, corruptedMnt, mounter.CanSafelySkipMountPointCheck())\n\t\tif err := mounter.Unmount(mountPath); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn removePath(mountPath)\n\t}\n\n\tnotMnt, err := removePathIfNotMountPoint(mountPath, mounter, extensiveMountPointCheck)\n\t// if mountPath is not a mount point, it's just been removed or there was an error\n\tif err != nil || notMnt {\n\t\treturn err\n\t}\n\n\tklog.V(4).Infof(\"%q is a mountpoint, unmounting\", mountPath)\n\tif err := mounter.Unmount(mountPath); err != nil {\n\t\treturn err\n\t}\n\n\tnotMnt, err = removePathIfNotMountPoint(mountPath, mounter, extensiveMountPointCheck)\n\t// if mountPath is not a mount point, it's either just been removed or there was an error\n\tif notMnt {\n\t\treturn err\n\t}\n\t// mountPath is still a mount point\n\treturn fmt.Errorf(\"failed to cleanup mount point %v\", mountPath)\n}","line":{"from":84,"to":119}} {"id":100034831,"name":"removePathIfNotMountPoint","signature":"func removePathIfNotMountPoint(mountPath string, mounter Interface, extensiveMountPointCheck bool) (bool, error)","file":"staging/src/k8s.io/mount-utils/mount_helper_common.go","code":"// removePathIfNotMountPoint verifies if given mountPath is a mount point if not it attempts\n// to remove the directory. Returns true and nil if directory was not a mount point and removed.\nfunc removePathIfNotMountPoint(mountPath string, mounter Interface, extensiveMountPointCheck bool) (bool, error) {\n\tvar notMnt bool\n\tvar err error\n\n\tif extensiveMountPointCheck {\n\t\tnotMnt, err = IsNotMountPoint(mounter, mountPath)\n\t} else {\n\t\tnotMnt, err = mounter.IsLikelyNotMountPoint(mountPath)\n\t}\n\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tklog.V(4).Infof(\"%q does not exist\", mountPath)\n\t\t\treturn true, nil\n\t\t}\n\t\treturn notMnt, err\n\t}\n\n\tif notMnt {\n\t\tklog.Warningf(\"Warning: %q is not a mountpoint, deleting\", mountPath)\n\t\treturn notMnt, os.Remove(mountPath)\n\t}\n\treturn notMnt, nil\n}","line":{"from":121,"to":146}} {"id":100034832,"name":"removePath","signature":"func removePath(mountPath string) error","file":"staging/src/k8s.io/mount-utils/mount_helper_common.go","code":"// removePath attempts to remove the directory. Returns nil if the directory was removed or does not exist.\nfunc removePath(mountPath string) error {\n\tklog.V(4).Infof(\"Warning: deleting path %q\", mountPath)\n\terr := os.Remove(mountPath)\n\tif os.IsNotExist(err) {\n\t\tklog.V(4).Infof(\"%q does not exist\", mountPath)\n\t\treturn nil\n\t}\n\treturn err\n}","line":{"from":148,"to":157}} {"id":100034833,"name":"IsCorruptedMnt","signature":"func IsCorruptedMnt(err error) bool","file":"staging/src/k8s.io/mount-utils/mount_helper_unix.go","code":"// IsCorruptedMnt return true if err is about corrupted mount point\nfunc IsCorruptedMnt(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\tvar underlyingError error\n\tswitch pe := err.(type) {\n\tcase nil:\n\t\treturn false\n\tcase *os.PathError:\n\t\tunderlyingError = pe.Err\n\tcase *os.LinkError:\n\t\tunderlyingError = pe.Err\n\tcase *os.SyscallError:\n\t\tunderlyingError = pe.Err\n\tcase syscall.Errno:\n\t\tunderlyingError = err\n\t}\n\n\treturn underlyingError == syscall.ENOTCONN || underlyingError == syscall.ESTALE || underlyingError == syscall.EIO || underlyingError == syscall.EACCES || underlyingError == syscall.EHOSTDOWN\n}","line":{"from":42,"to":62}} {"id":100034834,"name":"ParseMountInfo","signature":"func ParseMountInfo(filename string) ([]MountInfo, error)","file":"staging/src/k8s.io/mount-utils/mount_helper_unix.go","code":"// ParseMountInfo parses /proc/xxx/mountinfo.\nfunc ParseMountInfo(filename string) ([]MountInfo, error) {\n\tcontent, err := utilio.ConsistentRead(filename, maxListTries)\n\tif err != nil {\n\t\treturn []MountInfo{}, err\n\t}\n\tcontentStr := string(content)\n\tinfos := []MountInfo{}\n\n\tfor _, line := range strings.Split(contentStr, \"\\n\") {\n\t\tif line == \"\" {\n\t\t\t// the last split() item is empty string following the last \\n\n\t\t\tcontinue\n\t\t}\n\t\t// See `man proc` for authoritative description of format of the file.\n\t\tfields := strings.Fields(line)\n\t\tif len(fields) \u003c expectedAtLeastNumFieldsPerMountInfo {\n\t\t\treturn nil, fmt.Errorf(\"wrong number of fields in (expected at least %d, got %d): %s\", expectedAtLeastNumFieldsPerMountInfo, len(fields), line)\n\t\t}\n\t\tid, err := strconv.Atoi(fields[0])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tparentID, err := strconv.Atoi(fields[1])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmm := strings.Split(fields[2], \":\")\n\t\tif len(mm) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"parsing '%s' failed: unexpected minor:major pair %s\", line, mm)\n\t\t}\n\t\tmajor, err := strconv.Atoi(mm[0])\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"parsing '%s' failed: unable to parse major device id, err:%v\", mm[0], err)\n\t\t}\n\t\tminor, err := strconv.Atoi(mm[1])\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"parsing '%s' failed: unable to parse minor device id, err:%v\", mm[1], err)\n\t\t}\n\n\t\tinfo := MountInfo{\n\t\t\tID: id,\n\t\t\tParentID: parentID,\n\t\t\tMajor: major,\n\t\t\tMinor: minor,\n\t\t\tRoot: fields[3],\n\t\t\tMountPoint: fields[4],\n\t\t\tMountOptions: splitMountOptions(fields[5]),\n\t\t}\n\t\t// All fields until \"-\" are \"optional fields\".\n\t\ti := 6\n\t\tfor ; i \u003c len(fields) \u0026\u0026 fields[i] != \"-\"; i++ {\n\t\t\tinfo.OptionalFields = append(info.OptionalFields, fields[i])\n\t\t}\n\t\t// Parse the rest 3 fields.\n\t\ti++\n\t\tif len(fields)-i \u003c 3 {\n\t\t\treturn nil, fmt.Errorf(\"expect 3 fields in %s, got %d\", line, len(fields)-i)\n\t\t}\n\t\tinfo.FsType = fields[i]\n\t\tinfo.Source = fields[i+1]\n\t\tinfo.SuperOptions = splitMountOptions(fields[i+2])\n\t\tinfos = append(infos, info)\n\t}\n\treturn infos, nil\n}","line":{"from":92,"to":157}} {"id":100034835,"name":"splitMountOptions","signature":"func splitMountOptions(s string) []string","file":"staging/src/k8s.io/mount-utils/mount_helper_unix.go","code":"// splitMountOptions parses comma-separated list of mount options into an array.\n// It respects double quotes - commas in them are not considered as the option separator.\nfunc splitMountOptions(s string) []string {\n\tinQuotes := false\n\tlist := strings.FieldsFunc(s, func(r rune) bool {\n\t\tif r == '\"' {\n\t\t\tinQuotes = !inQuotes\n\t\t}\n\t\t// Report a new field only when outside of double quotes.\n\t\treturn r == ',' \u0026\u0026 !inQuotes\n\t})\n\treturn list\n}","line":{"from":159,"to":171}} {"id":100034836,"name":"isMountPointMatch","signature":"func isMountPointMatch(mp MountPoint, dir string) bool","file":"staging/src/k8s.io/mount-utils/mount_helper_unix.go","code":"// isMountPointMatch returns true if the path in mp is the same as dir.\n// Handles case where mountpoint dir has been renamed due to stale NFS mount.\nfunc isMountPointMatch(mp MountPoint, dir string) bool {\n\tdeletedDir := fmt.Sprintf(\"%s\\\\040(deleted)\", dir)\n\treturn ((mp.Path == dir) || (mp.Path == deletedDir))\n}","line":{"from":173,"to":178}} {"id":100034837,"name":"PathExists","signature":"func PathExists(path string) (bool, error)","file":"staging/src/k8s.io/mount-utils/mount_helper_unix.go","code":"// PathExists returns true if the specified path exists.\n// TODO: clean this up to use pkg/util/file/FileExists\nfunc PathExists(path string) (bool, error) {\n\t_, err := os.Stat(path)\n\tif err == nil {\n\t\treturn true, nil\n\t} else if errors.Is(err, fs.ErrNotExist) {\n\t\terr = syscall.Access(path, syscall.F_OK)\n\t\tif err == nil {\n\t\t\t// The access syscall says the file exists, the stat syscall says it\n\t\t\t// doesn't. This was observed on CIFS when the path was removed at\n\t\t\t// the server somehow. POSIX calls this a stale file handle, let's fake\n\t\t\t// that error and treat the path as existing but corrupted.\n\t\t\tklog.Warningf(\"Potential stale file handle detected: %s\", path)\n\t\t\treturn true, syscall.ESTALE\n\t\t}\n\t\treturn false, nil\n\t} else if IsCorruptedMnt(err) {\n\t\treturn true, err\n\t}\n\treturn false, err\n}","line":{"from":180,"to":201}} {"id":100034838,"name":"IsCorruptedMnt","signature":"func IsCorruptedMnt(err error) bool","file":"staging/src/k8s.io/mount-utils/mount_helper_windows.go","code":"// IsCorruptedMnt return true if err is about corrupted mount point\nfunc IsCorruptedMnt(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\n\tvar underlyingError error\n\tswitch pe := err.(type) {\n\tcase nil:\n\t\treturn false\n\tcase *os.PathError:\n\t\tunderlyingError = pe.Err\n\tcase *os.LinkError:\n\t\tunderlyingError = pe.Err\n\tcase *os.SyscallError:\n\t\tunderlyingError = pe.Err\n\t}\n\n\tif ee, ok := underlyingError.(syscall.Errno); ok {\n\t\tfor _, errno := range errorNoList {\n\t\t\tif int(ee) == errno {\n\t\t\t\tklog.Warningf(\"IsCorruptedMnt failed with error: %v, error code: %v\", err, errno)\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}","line":{"from":45,"to":73}} {"id":100034839,"name":"NormalizeWindowsPath","signature":"func NormalizeWindowsPath(path string) string","file":"staging/src/k8s.io/mount-utils/mount_helper_windows.go","code":"// NormalizeWindowsPath makes sure the given path is a valid path on Windows\n// systems by making sure all instances of `/` are replaced with `\\\\`, and the\n// path beings with `c:`\nfunc NormalizeWindowsPath(path string) string {\n\tnormalizedPath := strings.Replace(path, \"/\", \"\\\\\", -1)\n\tif strings.HasPrefix(normalizedPath, \"\\\\\") {\n\t\tnormalizedPath = \"c:\" + normalizedPath\n\t}\n\treturn normalizedPath\n}","line":{"from":75,"to":84}} {"id":100034840,"name":"ValidateDiskNumber","signature":"func ValidateDiskNumber(disk string) error","file":"staging/src/k8s.io/mount-utils/mount_helper_windows.go","code":"// ValidateDiskNumber : disk number should be a number in [0, 99]\nfunc ValidateDiskNumber(disk string) error {\n\tif _, err := strconv.Atoi(disk); err != nil {\n\t\treturn fmt.Errorf(\"wrong disk number format: %q, err: %v\", disk, err)\n\t}\n\treturn nil\n}","line":{"from":86,"to":92}} {"id":100034841,"name":"isMountPointMatch","signature":"func isMountPointMatch(mp MountPoint, dir string) bool","file":"staging/src/k8s.io/mount-utils/mount_helper_windows.go","code":"// isMountPointMatch determines if the mountpoint matches the dir\nfunc isMountPointMatch(mp MountPoint, dir string) bool {\n\treturn mp.Path == dir\n}","line":{"from":94,"to":97}} {"id":100034842,"name":"PathExists","signature":"func PathExists(path string) (bool, error)","file":"staging/src/k8s.io/mount-utils/mount_helper_windows.go","code":"// PathExists returns true if the specified path exists.\n// TODO: clean this up to use pkg/util/file/FileExists\nfunc PathExists(path string) (bool, error) {\n\t_, err := os.Stat(path)\n\tif err == nil {\n\t\treturn true, nil\n\t} else if os.IsNotExist(err) {\n\t\treturn false, nil\n\t} else if IsCorruptedMnt(err) {\n\t\treturn true, err\n\t}\n\treturn false, err\n}","line":{"from":99,"to":111}} {"id":100034843,"name":"New","signature":"func New(mounterPath string) Interface","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// New returns a mount.Interface for the current system.\n// It provides options to override the default mounter behavior.\n// mounterPath allows using an alternative to `/bin/mount` for mounting.\nfunc New(mounterPath string) Interface {\n\treturn \u0026Mounter{\n\t\tmounterPath: mounterPath,\n\t\ttrySystemd: true,\n\t\twithSafeNotMountedBehavior: detectSafeNotMountedBehavior(),\n\t}\n}","line":{"from":72,"to":81}} {"id":100034844,"name":"NewWithoutSystemd","signature":"func NewWithoutSystemd(mounterPath string) Interface","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// NewWithoutSystemd returns a Linux specific mount.Interface for the current\n// system. It provides options to override the default mounter behavior.\n// mounterPath allows using an alternative to `/bin/mount` for mounting. Any\n// detection for systemd functionality is disabled with this Mounter.\nfunc NewWithoutSystemd(mounterPath string) Interface {\n\treturn \u0026Mounter{\n\t\tmounterPath: mounterPath,\n\t\ttrySystemd: false,\n\t\twithSafeNotMountedBehavior: detectSafeNotMountedBehavior(),\n\t}\n}","line":{"from":83,"to":93}} {"id":100034845,"name":"hasSystemd","signature":"func (mounter *Mounter) hasSystemd() bool","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// hasSystemd validates that the withSystemd bool is set, if it is not,\n// detectSystemd will be called once for this Mounter instance.\nfunc (mounter *Mounter) hasSystemd() bool {\n\tif !mounter.trySystemd {\n\t\tmounter.withSystemd = \u0026mounter.trySystemd\n\t}\n\n\tif mounter.withSystemd == nil {\n\t\twithSystemd := detectSystemd()\n\t\tmounter.withSystemd = \u0026withSystemd\n\t}\n\n\treturn *mounter.withSystemd\n}","line":{"from":95,"to":108}} {"id":100034846,"name":"Mount","signature":"func (mounter *Mounter) Mount(source string, target string, fstype string, options []string) error","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// Mount mounts source to target as fstype with given options. 'source' and 'fstype' must\n// be an empty string in case it's not required, e.g. for remount, or for auto filesystem\n// type, where kernel handles fstype for you. The mount 'options' is a list of options,\n// currently come from mount(8), e.g. \"ro\", \"remount\", \"bind\", etc. If no more option is\n// required, call Mount with an empty string list or nil.\nfunc (mounter *Mounter) Mount(source string, target string, fstype string, options []string) error {\n\treturn mounter.MountSensitive(source, target, fstype, options, nil)\n}","line":{"from":110,"to":117}} {"id":100034847,"name":"MountSensitive","signature":"func (mounter *Mounter) MountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string) error","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// MountSensitive is the same as Mount() but this method allows\n// sensitiveOptions to be passed in a separate parameter from the normal\n// mount options and ensures the sensitiveOptions are never logged. This\n// method should be used by callers that pass sensitive material (like\n// passwords) as mount options.\nfunc (mounter *Mounter) MountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string) error {\n\t// Path to mounter binary if containerized mounter is needed. Otherwise, it is set to empty.\n\t// All Linux distros are expected to be shipped with a mount utility that a support bind mounts.\n\tmounterPath := \"\"\n\tbind, bindOpts, bindRemountOpts, bindRemountOptsSensitive := MakeBindOptsSensitive(options, sensitiveOptions)\n\tif bind {\n\t\terr := mounter.doMount(mounterPath, defaultMountCommand, source, target, fstype, bindOpts, bindRemountOptsSensitive, nil /* mountFlags */, mounter.trySystemd)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn mounter.doMount(mounterPath, defaultMountCommand, source, target, fstype, bindRemountOpts, bindRemountOptsSensitive, nil /* mountFlags */, mounter.trySystemd)\n\t}\n\t// The list of filesystems that require containerized mounter on GCI image cluster\n\tfsTypesNeedMounter := map[string]struct{}{\n\t\t\"nfs\": {},\n\t\t\"glusterfs\": {},\n\t\t\"ceph\": {},\n\t\t\"cifs\": {},\n\t}\n\tif _, ok := fsTypesNeedMounter[fstype]; ok {\n\t\tmounterPath = mounter.mounterPath\n\t}\n\treturn mounter.doMount(mounterPath, defaultMountCommand, source, target, fstype, options, sensitiveOptions, nil /* mountFlags */, mounter.trySystemd)\n}","line":{"from":119,"to":147}} {"id":100034848,"name":"MountSensitiveWithoutSystemd","signature":"func (mounter *Mounter) MountSensitiveWithoutSystemd(source string, target string, fstype string, options []string, sensitiveOptions []string) error","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// MountSensitiveWithoutSystemd is the same as MountSensitive() but disable using systemd mount.\nfunc (mounter *Mounter) MountSensitiveWithoutSystemd(source string, target string, fstype string, options []string, sensitiveOptions []string) error {\n\treturn mounter.MountSensitiveWithoutSystemdWithMountFlags(source, target, fstype, options, sensitiveOptions, nil /* mountFlags */)\n}","line":{"from":149,"to":152}} {"id":100034849,"name":"MountSensitiveWithoutSystemdWithMountFlags","signature":"func (mounter *Mounter) MountSensitiveWithoutSystemdWithMountFlags(source string, target string, fstype string, options []string, sensitiveOptions []string, mountFlags []string) error","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// MountSensitiveWithoutSystemdWithMountFlags is the same as MountSensitiveWithoutSystemd with additional mount flags.\nfunc (mounter *Mounter) MountSensitiveWithoutSystemdWithMountFlags(source string, target string, fstype string, options []string, sensitiveOptions []string, mountFlags []string) error {\n\tmounterPath := \"\"\n\tbind, bindOpts, bindRemountOpts, bindRemountOptsSensitive := MakeBindOptsSensitive(options, sensitiveOptions)\n\tif bind {\n\t\terr := mounter.doMount(mounterPath, defaultMountCommand, source, target, fstype, bindOpts, bindRemountOptsSensitive, mountFlags, false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn mounter.doMount(mounterPath, defaultMountCommand, source, target, fstype, bindRemountOpts, bindRemountOptsSensitive, mountFlags, false)\n\t}\n\t// The list of filesystems that require containerized mounter on GCI image cluster\n\tfsTypesNeedMounter := map[string]struct{}{\n\t\t\"nfs\": {},\n\t\t\"glusterfs\": {},\n\t\t\"ceph\": {},\n\t\t\"cifs\": {},\n\t}\n\tif _, ok := fsTypesNeedMounter[fstype]; ok {\n\t\tmounterPath = mounter.mounterPath\n\t}\n\treturn mounter.doMount(mounterPath, defaultMountCommand, source, target, fstype, options, sensitiveOptions, mountFlags, false)\n}","line":{"from":154,"to":176}} {"id":100034850,"name":"doMount","signature":"func (mounter *Mounter) doMount(mounterPath string, mountCmd string, source string, target string, fstype string, options []string, sensitiveOptions []string, mountFlags []string, systemdMountRequired bool) error","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// doMount runs the mount command. mounterPath is the path to mounter binary if containerized mounter is used.\n// sensitiveOptions is an extension of options except they will not be logged (because they may contain sensitive material)\n// systemdMountRequired is an extension of option to decide whether uses systemd mount.\nfunc (mounter *Mounter) doMount(mounterPath string, mountCmd string, source string, target string, fstype string, options []string, sensitiveOptions []string, mountFlags []string, systemdMountRequired bool) error {\n\tmountArgs, mountArgsLogStr := MakeMountArgsSensitiveWithMountFlags(source, target, fstype, options, sensitiveOptions, mountFlags)\n\tif len(mounterPath) \u003e 0 {\n\t\tmountArgs = append([]string{mountCmd}, mountArgs...)\n\t\tmountArgsLogStr = mountCmd + \" \" + mountArgsLogStr\n\t\tmountCmd = mounterPath\n\t}\n\n\tif systemdMountRequired \u0026\u0026 mounter.hasSystemd() {\n\t\t// Try to run mount via systemd-run --scope. This will escape the\n\t\t// service where kubelet runs and any fuse daemons will be started in a\n\t\t// specific scope. kubelet service than can be restarted without killing\n\t\t// these fuse daemons.\n\t\t//\n\t\t// Complete command line (when mounterPath is not used):\n\t\t// systemd-run --description=... --scope -- mount -t \u003ctype\u003e \u003cwhat\u003e \u003cwhere\u003e\n\t\t//\n\t\t// Expected flow:\n\t\t// * systemd-run creates a transient scope (=~ cgroup) and executes its\n\t\t// argument (/bin/mount) there.\n\t\t// * mount does its job, forks a fuse daemon if necessary and finishes.\n\t\t// (systemd-run --scope finishes at this point, returning mount's exit\n\t\t// code and stdout/stderr - thats one of --scope benefits).\n\t\t// * systemd keeps the fuse daemon running in the scope (i.e. in its own\n\t\t// cgroup) until the fuse daemon dies (another --scope benefit).\n\t\t// Kubelet service can be restarted and the fuse daemon survives.\n\t\t// * When the fuse daemon dies (e.g. during unmount) systemd removes the\n\t\t// scope automatically.\n\t\t//\n\t\t// systemd-mount is not used because it's too new for older distros\n\t\t// (CentOS 7, Debian Jessie).\n\t\tmountCmd, mountArgs, mountArgsLogStr = AddSystemdScopeSensitive(\"systemd-run\", target, mountCmd, mountArgs, mountArgsLogStr)\n\t\t// } else {\n\t\t// No systemd-run on the host (or we failed to check it), assume kubelet\n\t\t// does not run as a systemd service.\n\t\t// No code here, mountCmd and mountArgs are already populated.\n\t}\n\n\t// Logging with sensitive mount options removed.\n\tklog.V(4).Infof(\"Mounting cmd (%s) with arguments (%s)\", mountCmd, mountArgsLogStr)\n\tcommand := exec.Command(mountCmd, mountArgs...)\n\toutput, err := command.CombinedOutput()\n\tif err != nil {\n\t\tif err.Error() == errNoChildProcesses {\n\t\t\tif command.ProcessState.Success() {\n\t\t\t\t// We don't consider errNoChildProcesses an error if the process itself succeeded (see - k/k issue #103753).\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t// Rewrite err with the actual exit error of the process.\n\t\t\terr = \u0026exec.ExitError{ProcessState: command.ProcessState}\n\t\t}\n\t\tklog.Errorf(\"Mount failed: %v\\nMounting command: %s\\nMounting arguments: %s\\nOutput: %s\\n\", err, mountCmd, mountArgsLogStr, string(output))\n\t\treturn fmt.Errorf(\"mount failed: %v\\nMounting command: %s\\nMounting arguments: %s\\nOutput: %s\",\n\t\t\terr, mountCmd, mountArgsLogStr, string(output))\n\t}\n\treturn err\n}","line":{"from":178,"to":237}} {"id":100034851,"name":"detectSystemd","signature":"func detectSystemd() bool","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// detectSystemd returns true if OS runs with systemd as init. When not sure\n// (permission errors, ...), it returns false.\n// There may be different ways how to detect systemd, this one makes sure that\n// systemd-runs (needed by Mount()) works.\nfunc detectSystemd() bool {\n\tif _, err := exec.LookPath(\"systemd-run\"); err != nil {\n\t\tklog.V(2).Infof(\"Detected OS without systemd\")\n\t\treturn false\n\t}\n\t// Try to run systemd-run --scope /bin/true, that should be enough\n\t// to make sure that systemd is really running and not just installed,\n\t// which happens when running in a container with a systemd-based image\n\t// but with different pid 1.\n\tcmd := exec.Command(\"systemd-run\", \"--description=Kubernetes systemd probe\", \"--scope\", \"true\")\n\toutput, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tklog.V(2).Infof(\"Cannot run systemd-run, assuming non-systemd OS\")\n\t\tklog.V(4).Infof(\"systemd-run output: %s, failed with: %v\", string(output), err)\n\t\treturn false\n\t}\n\tklog.V(2).Infof(\"Detected OS with systemd\")\n\treturn true\n}","line":{"from":239,"to":261}} {"id":100034852,"name":"detectSafeNotMountedBehavior","signature":"func detectSafeNotMountedBehavior() bool","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// detectSafeNotMountedBehavior returns true if the umount implementation replies \"not mounted\"\n// when the specified path is not mounted. When not sure (permission errors, ...), it returns false.\n// When possible, we will trust umount's message and avoid doing our own mount point checks.\n// More info: https://github.com/util-linux/util-linux/blob/v2.2/mount/umount.c#L179\nfunc detectSafeNotMountedBehavior() bool {\n\treturn detectSafeNotMountedBehaviorWithExec(utilexec.New())\n}","line":{"from":263,"to":269}} {"id":100034853,"name":"detectSafeNotMountedBehaviorWithExec","signature":"func detectSafeNotMountedBehaviorWithExec(exec utilexec.Interface) bool","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// detectSafeNotMountedBehaviorWithExec is for testing with FakeExec.\nfunc detectSafeNotMountedBehaviorWithExec(exec utilexec.Interface) bool {\n\t// create a temp dir and try to umount it\n\tpath, err := ioutil.TempDir(\"\", \"kubelet-detect-safe-umount\")\n\tif err != nil {\n\t\tklog.V(4).Infof(\"Cannot create temp dir to detect safe 'not mounted' behavior: %v\", err)\n\t\treturn false\n\t}\n\tdefer os.RemoveAll(path)\n\tcmd := exec.Command(\"umount\", path)\n\toutput, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tif strings.Contains(string(output), errNotMounted) {\n\t\t\tklog.V(4).Infof(\"Detected umount with safe 'not mounted' behavior\")\n\t\t\treturn true\n\t\t}\n\t\tklog.V(4).Infof(\"'umount %s' failed with: %v, output: %s\", path, err, string(output))\n\t}\n\tklog.V(4).Infof(\"Detected umount with unsafe 'not mounted' behavior\")\n\treturn false\n}","line":{"from":271,"to":291}} {"id":100034854,"name":"MakeMountArgs","signature":"func MakeMountArgs(source, target, fstype string, options []string) (mountArgs []string)","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// MakeMountArgs makes the arguments to the mount(8) command.\n// options MUST not contain sensitive material (like passwords).\nfunc MakeMountArgs(source, target, fstype string, options []string) (mountArgs []string) {\n\tmountArgs, _ = MakeMountArgsSensitive(source, target, fstype, options, nil /* sensitiveOptions */)\n\treturn mountArgs\n}","line":{"from":293,"to":298}} {"id":100034855,"name":"MakeMountArgsSensitive","signature":"func MakeMountArgsSensitive(source, target, fstype string, options []string, sensitiveOptions []string) (mountArgs []string, mountArgsLogStr string)","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// MakeMountArgsSensitive makes the arguments to the mount(8) command.\n// sensitiveOptions is an extension of options except they will not be logged (because they may contain sensitive material)\nfunc MakeMountArgsSensitive(source, target, fstype string, options []string, sensitiveOptions []string) (mountArgs []string, mountArgsLogStr string) {\n\treturn MakeMountArgsSensitiveWithMountFlags(source, target, fstype, options, sensitiveOptions, nil /* mountFlags */)\n}","line":{"from":300,"to":304}} {"id":100034856,"name":"MakeMountArgsSensitiveWithMountFlags","signature":"func MakeMountArgsSensitiveWithMountFlags(source, target, fstype string, options []string, sensitiveOptions []string, mountFlags []string) (mountArgs []string, mountArgsLogStr string)","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// MakeMountArgsSensitiveWithMountFlags makes the arguments to the mount(8) command.\n// sensitiveOptions is an extension of options except they will not be logged (because they may contain sensitive material)\n// mountFlags are additional mount flags that are not related with the fstype\n// and mount options\nfunc MakeMountArgsSensitiveWithMountFlags(source, target, fstype string, options []string, sensitiveOptions []string, mountFlags []string) (mountArgs []string, mountArgsLogStr string) {\n\t// Build mount command as follows:\n\t// mount [$mountFlags] [-t $fstype] [-o $options] [$source] $target\n\tmountArgs = []string{}\n\tmountArgsLogStr = \"\"\n\n\tmountArgs = append(mountArgs, mountFlags...)\n\tmountArgsLogStr += strings.Join(mountFlags, \" \")\n\n\tif len(fstype) \u003e 0 {\n\t\tmountArgs = append(mountArgs, \"-t\", fstype)\n\t\tmountArgsLogStr += strings.Join(mountArgs, \" \")\n\t}\n\tif len(options) \u003e 0 || len(sensitiveOptions) \u003e 0 {\n\t\tcombinedOptions := []string{}\n\t\tcombinedOptions = append(combinedOptions, options...)\n\t\tcombinedOptions = append(combinedOptions, sensitiveOptions...)\n\t\tmountArgs = append(mountArgs, \"-o\", strings.Join(combinedOptions, \",\"))\n\t\t// exclude sensitiveOptions from log string\n\t\tmountArgsLogStr += \" -o \" + sanitizedOptionsForLogging(options, sensitiveOptions)\n\t}\n\tif len(source) \u003e 0 {\n\t\tmountArgs = append(mountArgs, source)\n\t\tmountArgsLogStr += \" \" + source\n\t}\n\tmountArgs = append(mountArgs, target)\n\tmountArgsLogStr += \" \" + target\n\n\treturn mountArgs, mountArgsLogStr\n}","line":{"from":306,"to":339}} {"id":100034857,"name":"AddSystemdScope","signature":"func AddSystemdScope(systemdRunPath, mountName, command string, args []string) (string, []string)","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// AddSystemdScope adds \"system-run --scope\" to given command line\n// If args contains sensitive material, use AddSystemdScopeSensitive to construct\n// a safe to log string.\nfunc AddSystemdScope(systemdRunPath, mountName, command string, args []string) (string, []string) {\n\tdescriptionArg := fmt.Sprintf(\"--description=Kubernetes transient mount for %s\", mountName)\n\tsystemdRunArgs := []string{descriptionArg, \"--scope\", \"--\", command}\n\treturn systemdRunPath, append(systemdRunArgs, args...)\n}","line":{"from":341,"to":348}} {"id":100034858,"name":"AddSystemdScopeSensitive","signature":"func AddSystemdScopeSensitive(systemdRunPath, mountName, command string, args []string, mountArgsLogStr string) (string, []string, string)","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// AddSystemdScopeSensitive adds \"system-run --scope\" to given command line\n// It also accepts takes a sanitized string containing mount arguments, mountArgsLogStr,\n// and returns the string appended to the systemd command for logging.\nfunc AddSystemdScopeSensitive(systemdRunPath, mountName, command string, args []string, mountArgsLogStr string) (string, []string, string) {\n\tdescriptionArg := fmt.Sprintf(\"--description=Kubernetes transient mount for %s\", mountName)\n\tsystemdRunArgs := []string{descriptionArg, \"--scope\", \"--\", command}\n\treturn systemdRunPath, append(systemdRunArgs, args...), strings.Join(systemdRunArgs, \" \") + \" \" + mountArgsLogStr\n}","line":{"from":350,"to":357}} {"id":100034859,"name":"Unmount","signature":"func (mounter *Mounter) Unmount(target string) error","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// Unmount unmounts the target.\n// If the mounter has safe \"not mounted\" behavior, no error will be returned when the target is not a mount point.\nfunc (mounter *Mounter) Unmount(target string) error {\n\tklog.V(4).Infof(\"Unmounting %s\", target)\n\tcommand := exec.Command(\"umount\", target)\n\toutput, err := command.CombinedOutput()\n\tif err != nil {\n\t\treturn checkUmountError(target, command, output, err, mounter.withSafeNotMountedBehavior)\n\t}\n\treturn nil\n}","line":{"from":359,"to":369}} {"id":100034860,"name":"UnmountWithForce","signature":"func (mounter *Mounter) UnmountWithForce(target string, umountTimeout time.Duration) error","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// UnmountWithForce unmounts given target but will retry unmounting with force option\n// after given timeout.\nfunc (mounter *Mounter) UnmountWithForce(target string, umountTimeout time.Duration) error {\n\terr := tryUnmount(target, mounter.withSafeNotMountedBehavior, umountTimeout)\n\tif err != nil {\n\t\tif err == context.DeadlineExceeded {\n\t\t\tklog.V(2).Infof(\"Timed out waiting for unmount of %s, trying with -f\", target)\n\t\t\terr = forceUmount(target, mounter.withSafeNotMountedBehavior)\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":371,"to":383}} {"id":100034861,"name":"List","signature":"func (*Mounter) List() ([]MountPoint, error)","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// List returns a list of all mounted filesystems.\nfunc (*Mounter) List() ([]MountPoint, error) {\n\treturn ListProcMounts(procMountsPath)\n}","line":{"from":385,"to":388}} {"id":100034862,"name":"IsLikelyNotMountPoint","signature":"func (mounter *Mounter) IsLikelyNotMountPoint(file string) (bool, error)","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// IsLikelyNotMountPoint determines if a directory is not a mountpoint.\n// It is fast but not necessarily ALWAYS correct. If the path is in fact\n// a bind mount from one part of a mount to another it will not be detected.\n// It also can not distinguish between mountpoints and symbolic links.\n// mkdir /tmp/a /tmp/b; mount --bind /tmp/a /tmp/b; IsLikelyNotMountPoint(\"/tmp/b\")\n// will return true. When in fact /tmp/b is a mount point. If this situation\n// is of interest to you, don't use this function...\nfunc (mounter *Mounter) IsLikelyNotMountPoint(file string) (bool, error) {\n\tstat, err := os.Stat(file)\n\tif err != nil {\n\t\treturn true, err\n\t}\n\trootStat, err := os.Stat(filepath.Dir(strings.TrimSuffix(file, \"/\")))\n\tif err != nil {\n\t\treturn true, err\n\t}\n\t// If the directory has a different device as parent, then it is a mountpoint.\n\tif stat.Sys().(*syscall.Stat_t).Dev != rootStat.Sys().(*syscall.Stat_t).Dev {\n\t\treturn false, nil\n\t}\n\n\treturn true, nil\n}","line":{"from":390,"to":412}} {"id":100034863,"name":"CanSafelySkipMountPointCheck","signature":"func (mounter *Mounter) CanSafelySkipMountPointCheck() bool","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// CanSafelySkipMountPointCheck relies on the detected behavior of umount when given a target that is not a mount point.\nfunc (mounter *Mounter) CanSafelySkipMountPointCheck() bool {\n\treturn mounter.withSafeNotMountedBehavior\n}","line":{"from":414,"to":417}} {"id":100034864,"name":"GetMountRefs","signature":"func (mounter *Mounter) GetMountRefs(pathname string) ([]string, error)","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// GetMountRefs finds all mount references to pathname, returns a\n// list of paths. Path could be a mountpoint or a normal\n// directory (for bind mount).\nfunc (mounter *Mounter) GetMountRefs(pathname string) ([]string, error) {\n\tpathExists, pathErr := PathExists(pathname)\n\tif !pathExists {\n\t\treturn []string{}, nil\n\t} else if IsCorruptedMnt(pathErr) {\n\t\tklog.Warningf(\"GetMountRefs found corrupted mount at %s, treating as unmounted path\", pathname)\n\t\treturn []string{}, nil\n\t} else if pathErr != nil {\n\t\treturn nil, fmt.Errorf(\"error checking path %s: %v\", pathname, pathErr)\n\t}\n\trealpath, err := filepath.EvalSymlinks(pathname)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn SearchMountPoints(realpath, procMountInfoPath)\n}","line":{"from":419,"to":437}} {"id":100034865,"name":"checkAndRepairFilesystem","signature":"func (mounter *SafeFormatAndMount) checkAndRepairFilesystem(source string) error","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// checkAndRepairFileSystem checks and repairs filesystems using command fsck.\nfunc (mounter *SafeFormatAndMount) checkAndRepairFilesystem(source string) error {\n\tklog.V(4).Infof(\"Checking for issues with fsck on disk: %s\", source)\n\targs := []string{\"-a\", source}\n\tout, err := mounter.Exec.Command(\"fsck\", args...).CombinedOutput()\n\tif err != nil {\n\t\tee, isExitError := err.(utilexec.ExitError)\n\t\tswitch {\n\t\tcase err == utilexec.ErrExecutableNotFound:\n\t\t\tklog.Warningf(\"'fsck' not found on system; continuing mount without running 'fsck'.\")\n\t\tcase isExitError \u0026\u0026 ee.ExitStatus() == fsckErrorsCorrected:\n\t\t\tklog.Infof(\"Device %s has errors which were corrected by fsck.\", source)\n\t\tcase isExitError \u0026\u0026 ee.ExitStatus() == fsckErrorsUncorrected:\n\t\t\treturn NewMountError(HasFilesystemErrors, \"'fsck' found errors on device %s but could not correct them: %s\", source, string(out))\n\t\tcase isExitError \u0026\u0026 ee.ExitStatus() \u003e fsckErrorsUncorrected:\n\t\t\tklog.Infof(\"`fsck` error %s\", string(out))\n\t\tdefault:\n\t\t\tklog.Warningf(\"fsck on device %s failed with error %v, output: %v\", source, err, string(out))\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":439,"to":460}} {"id":100034866,"name":"formatAndMountSensitive","signature":"func (mounter *SafeFormatAndMount) formatAndMountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string, formatOptions []string) error","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// formatAndMount uses unix utils to format and mount the given disk\nfunc (mounter *SafeFormatAndMount) formatAndMountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string, formatOptions []string) error {\n\treadOnly := false\n\tfor _, option := range options {\n\t\tif option == \"ro\" {\n\t\t\treadOnly = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !readOnly {\n\t\t// Check sensitiveOptions for ro\n\t\tfor _, option := range sensitiveOptions {\n\t\t\tif option == \"ro\" {\n\t\t\t\treadOnly = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\toptions = append(options, \"defaults\")\n\tmountErrorValue := UnknownMountError\n\n\t// Check if the disk is already formatted\n\texistingFormat, err := mounter.GetDiskFormat(source)\n\tif err != nil {\n\t\treturn NewMountError(GetDiskFormatFailed, \"failed to get disk format of disk %s: %v\", source, err)\n\t}\n\n\t// Use 'ext4' as the default\n\tif len(fstype) == 0 {\n\t\tfstype = \"ext4\"\n\t}\n\n\tif existingFormat == \"\" {\n\t\t// Do not attempt to format the disk if mounting as readonly, return an error to reflect this.\n\t\tif readOnly {\n\t\t\treturn NewMountError(UnformattedReadOnly, \"cannot mount unformatted disk %s as we are manipulating it in read-only mode\", source)\n\t\t}\n\n\t\t// Disk is unformatted so format it.\n\t\targs := []string{source}\n\t\tif fstype == \"ext4\" || fstype == \"ext3\" {\n\t\t\targs = []string{\n\t\t\t\t\"-F\", // Force flag\n\t\t\t\t\"-m0\", // Zero blocks reserved for super-user\n\t\t\t\tsource,\n\t\t\t}\n\t\t} else if fstype == \"xfs\" {\n\t\t\targs = []string{\n\t\t\t\t\"-f\", // force flag\n\t\t\t\tsource,\n\t\t\t}\n\t\t}\n\t\targs = append(formatOptions, args...)\n\n\t\tklog.Infof(\"Disk %q appears to be unformatted, attempting to format as type: %q with options: %v\", source, fstype, args)\n\n\t\toutput, err := mounter.format(fstype, args)\n\t\tif err != nil {\n\t\t\t// Do not log sensitiveOptions only options\n\t\t\tsensitiveOptionsLog := sanitizedOptionsForLogging(options, sensitiveOptions)\n\t\t\tdetailedErr := fmt.Sprintf(\"format of disk %q failed: type:(%q) target:(%q) options:(%q) errcode:(%v) output:(%v) \", source, fstype, target, sensitiveOptionsLog, err, string(output))\n\t\t\tklog.Error(detailedErr)\n\t\t\treturn NewMountError(FormatFailed, detailedErr)\n\t\t}\n\n\t\tklog.Infof(\"Disk successfully formatted (mkfs): %s - %s %s\", fstype, source, target)\n\t} else {\n\t\tif fstype != existingFormat {\n\t\t\t// Verify that the disk is formatted with filesystem type we are expecting\n\t\t\tmountErrorValue = FilesystemMismatch\n\t\t\tklog.Warningf(\"Configured to mount disk %s as %s but current format is %s, things might break\", source, existingFormat, fstype)\n\t\t}\n\n\t\tif !readOnly {\n\t\t\t// Run check tools on the disk to fix repairable issues, only do this for formatted volumes requested as rw.\n\t\t\terr := mounter.checkAndRepairFilesystem(source)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// Mount the disk\n\tklog.V(4).Infof(\"Attempting to mount disk %s in %s format at %s\", source, fstype, target)\n\tif err := mounter.MountSensitive(source, target, fstype, options, sensitiveOptions); err != nil {\n\t\treturn NewMountError(mountErrorValue, err.Error())\n\t}\n\n\treturn nil\n}","line":{"from":462,"to":552}} {"id":100034867,"name":"format","signature":"func (mounter *SafeFormatAndMount) format(fstype string, args []string) ([]byte, error)","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"func (mounter *SafeFormatAndMount) format(fstype string, args []string) ([]byte, error) {\n\tif mounter.formatSem != nil {\n\t\tdone := make(chan struct{})\n\t\tdefer close(done)\n\n\t\tmounter.formatSem \u003c- struct{}{}\n\n\t\tgo func() {\n\t\t\tdefer func() { \u003c-mounter.formatSem }()\n\n\t\t\ttimeout := time.NewTimer(mounter.formatTimeout)\n\t\t\tdefer timeout.Stop()\n\n\t\t\tselect {\n\t\t\tcase \u003c-done:\n\t\t\tcase \u003c-timeout.C:\n\t\t\t}\n\t\t}()\n\t}\n\n\treturn mounter.Exec.Command(\"mkfs.\"+fstype, args...).CombinedOutput()\n}","line":{"from":554,"to":575}} {"id":100034868,"name":"getDiskFormat","signature":"func getDiskFormat(exec utilexec.Interface, disk string) (string, error)","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"func getDiskFormat(exec utilexec.Interface, disk string) (string, error) {\n\targs := []string{\"-p\", \"-s\", \"TYPE\", \"-s\", \"PTTYPE\", \"-o\", \"export\", disk}\n\tklog.V(4).Infof(\"Attempting to determine if disk %q is formatted using blkid with args: (%v)\", disk, args)\n\tdataOut, err := exec.Command(\"blkid\", args...).CombinedOutput()\n\toutput := string(dataOut)\n\tklog.V(4).Infof(\"Output: %q\", output)\n\n\tif err != nil {\n\t\tif exit, ok := err.(utilexec.ExitError); ok {\n\t\t\tif exit.ExitStatus() == 2 {\n\t\t\t\t// Disk device is unformatted.\n\t\t\t\t// For `blkid`, if the specified token (TYPE/PTTYPE, etc) was\n\t\t\t\t// not found, or no (specified) devices could be identified, an\n\t\t\t\t// exit code of 2 is returned.\n\t\t\t\treturn \"\", nil\n\t\t\t}\n\t\t}\n\t\tklog.Errorf(\"Could not determine if disk %q is formatted (%v)\", disk, err)\n\t\treturn \"\", err\n\t}\n\n\tvar fstype, pttype string\n\n\tlines := strings.Split(output, \"\\n\")\n\tfor _, l := range lines {\n\t\tif len(l) \u003c= 0 {\n\t\t\t// Ignore empty line.\n\t\t\tcontinue\n\t\t}\n\t\tcs := strings.Split(l, \"=\")\n\t\tif len(cs) != 2 {\n\t\t\treturn \"\", fmt.Errorf(\"blkid returns invalid output: %s\", output)\n\t\t}\n\t\t// TYPE is filesystem type, and PTTYPE is partition table type, according\n\t\t// to https://www.kernel.org/pub/linux/utils/util-linux/v2.21/libblkid-docs/.\n\t\tif cs[0] == \"TYPE\" {\n\t\t\tfstype = cs[1]\n\t\t} else if cs[0] == \"PTTYPE\" {\n\t\t\tpttype = cs[1]\n\t\t}\n\t}\n\n\tif len(pttype) \u003e 0 {\n\t\tklog.V(4).Infof(\"Disk %s detected partition table type: %s\", disk, pttype)\n\t\t// Returns a special non-empty string as filesystem type, then kubelet\n\t\t// will not format it.\n\t\treturn \"unknown data, probably partitions\", nil\n\t}\n\n\treturn fstype, nil\n}","line":{"from":577,"to":627}} {"id":100034869,"name":"GetDiskFormat","signature":"func (mounter *SafeFormatAndMount) GetDiskFormat(disk string) (string, error)","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// GetDiskFormat uses 'blkid' to see if the given disk is unformatted\nfunc (mounter *SafeFormatAndMount) GetDiskFormat(disk string) (string, error) {\n\treturn getDiskFormat(mounter.Exec, disk)\n}","line":{"from":629,"to":632}} {"id":100034870,"name":"ListProcMounts","signature":"func ListProcMounts(mountFilePath string) ([]MountPoint, error)","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// ListProcMounts is shared with NsEnterMounter\nfunc ListProcMounts(mountFilePath string) ([]MountPoint, error) {\n\tcontent, err := utilio.ConsistentRead(mountFilePath, maxListTries)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn parseProcMounts(content)\n}","line":{"from":634,"to":641}} {"id":100034871,"name":"parseProcMounts","signature":"func parseProcMounts(content []byte) ([]MountPoint, error)","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"func parseProcMounts(content []byte) ([]MountPoint, error) {\n\tout := []MountPoint{}\n\tlines := strings.Split(string(content), \"\\n\")\n\tfor _, line := range lines {\n\t\tif line == \"\" {\n\t\t\t// the last split() item is empty string following the last \\n\n\t\t\tcontinue\n\t\t}\n\t\tfields := strings.Fields(line)\n\t\tif len(fields) != expectedNumFieldsPerLine {\n\t\t\t// Do not log line in case it contains sensitive Mount options\n\t\t\treturn nil, fmt.Errorf(\"wrong number of fields (expected %d, got %d)\", expectedNumFieldsPerLine, len(fields))\n\t\t}\n\n\t\tmp := MountPoint{\n\t\t\tDevice: fields[0],\n\t\t\tPath: fields[1],\n\t\t\tType: fields[2],\n\t\t\tOpts: strings.Split(fields[3], \",\"),\n\t\t}\n\n\t\tfreq, err := strconv.Atoi(fields[4])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmp.Freq = freq\n\n\t\tpass, err := strconv.Atoi(fields[5])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmp.Pass = pass\n\n\t\tout = append(out, mp)\n\t}\n\treturn out, nil\n}","line":{"from":643,"to":679}} {"id":100034872,"name":"SearchMountPoints","signature":"func SearchMountPoints(hostSource, mountInfoPath string) ([]string, error)","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// SearchMountPoints finds all mount references to the source, returns a list of\n// mountpoints.\n// The source can be a mount point or a normal directory (bind mount). We\n// didn't support device because there is no use case by now.\n// Some filesystems may share a source name, e.g. tmpfs. And for bind mounting,\n// it's possible to mount a non-root path of a filesystem, so we need to use\n// root path and major:minor to represent mount source uniquely.\n// This implementation is shared between Linux and NsEnterMounter\nfunc SearchMountPoints(hostSource, mountInfoPath string) ([]string, error) {\n\tmis, err := ParseMountInfo(mountInfoPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmountID := 0\n\trootPath := \"\"\n\tmajor := -1\n\tminor := -1\n\n\t// Finding the underlying root path and major:minor if possible.\n\t// We need search in backward order because it's possible for later mounts\n\t// to overlap earlier mounts.\n\tfor i := len(mis) - 1; i \u003e= 0; i-- {\n\t\tif hostSource == mis[i].MountPoint || PathWithinBase(hostSource, mis[i].MountPoint) {\n\t\t\t// If it's a mount point or path under a mount point.\n\t\t\tmountID = mis[i].ID\n\t\t\trootPath = filepath.Join(mis[i].Root, strings.TrimPrefix(hostSource, mis[i].MountPoint))\n\t\t\tmajor = mis[i].Major\n\t\t\tminor = mis[i].Minor\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif rootPath == \"\" || major == -1 || minor == -1 {\n\t\treturn nil, fmt.Errorf(\"failed to get root path and major:minor for %s\", hostSource)\n\t}\n\n\tvar refs []string\n\tfor i := range mis {\n\t\tif mis[i].ID == mountID {\n\t\t\t// Ignore mount entry for mount source itself.\n\t\t\tcontinue\n\t\t}\n\t\tif mis[i].Root == rootPath \u0026\u0026 mis[i].Major == major \u0026\u0026 mis[i].Minor == minor {\n\t\t\trefs = append(refs, mis[i].MountPoint)\n\t\t}\n\t}\n\n\treturn refs, nil\n}","line":{"from":681,"to":730}} {"id":100034873,"name":"IsMountPoint","signature":"func (mounter *Mounter) IsMountPoint(file string) (bool, error)","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// IsMountPoint determines if a file is a mountpoint.\n// It first detects bind \u0026 any other mountpoints using\n// MountedFast function. If the MountedFast function returns\n// sure as true and err as nil, then a mountpoint is detected\n// successfully. When an error is returned by MountedFast, the\n// following is true:\n// 1. All errors are returned with IsMountPoint as false\n// except os.IsPermission.\n// 2. When os.IsPermission is returned by MountedFast, List()\n// is called to confirm if the given file is a mountpoint are not.\n//\n// os.ErrNotExist should always be returned if a file does not exist\n// as callers have in past relied on this error and not fallback.\n//\n// When MountedFast returns sure as false and err as nil (eg: in\n// case of bindmounts on kernel version 5.10- ); mounter.List()\n// endpoint is called to enumerate all the mountpoints and check if\n// it is mountpoint match or not.\nfunc (mounter *Mounter) IsMountPoint(file string) (bool, error) {\n\tisMnt, sure, isMntErr := mountinfo.MountedFast(file)\n\tif sure \u0026\u0026 isMntErr == nil {\n\t\treturn isMnt, nil\n\t}\n\tif isMntErr != nil {\n\t\tif errors.Is(isMntErr, fs.ErrNotExist) {\n\t\t\treturn false, fs.ErrNotExist\n\t\t}\n\t\t// We were not allowed to do the simple stat() check, e.g. on NFS with\n\t\t// root_squash. Fall back to /proc/mounts check below when\n\t\t// fs.ErrPermission is returned.\n\t\tif !errors.Is(isMntErr, fs.ErrPermission) {\n\t\t\treturn false, isMntErr\n\t\t}\n\t}\n\t// Resolve any symlinks in file, kernel would do the same and use the resolved path in /proc/mounts.\n\tresolvedFile, err := filepath.EvalSymlinks(file)\n\tif err != nil {\n\t\tif errors.Is(isMntErr, fs.ErrNotExist) {\n\t\t\treturn false, fs.ErrNotExist\n\t\t}\n\t\treturn false, err\n\t}\n\n\t// check all mountpoints since MountedFast is not sure.\n\t// is not reliable for some mountpoint types.\n\tmountPoints, mountPointsErr := mounter.List()\n\tif mountPointsErr != nil {\n\t\treturn false, mountPointsErr\n\t}\n\tfor _, mp := range mountPoints {\n\t\tif isMountPointMatch(mp, resolvedFile) {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}","line":{"from":732,"to":787}} {"id":100034874,"name":"tryUnmount","signature":"func tryUnmount(target string, withSafeNotMountedBehavior bool, unmountTimeout time.Duration) error","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// tryUnmount calls plain \"umount\" and waits for unmountTimeout for it to finish.\nfunc tryUnmount(target string, withSafeNotMountedBehavior bool, unmountTimeout time.Duration) error {\n\tklog.V(4).Infof(\"Unmounting %s\", target)\n\tctx, cancel := context.WithTimeout(context.Background(), unmountTimeout)\n\tdefer cancel()\n\n\tcommand := exec.CommandContext(ctx, \"umount\", target)\n\toutput, err := command.CombinedOutput()\n\n\t// CombinedOutput() does not return DeadlineExceeded, make sure it's\n\t// propagated on timeout.\n\tif ctx.Err() != nil {\n\t\treturn ctx.Err()\n\t}\n\n\tif err != nil {\n\t\treturn checkUmountError(target, command, output, err, withSafeNotMountedBehavior)\n\t}\n\treturn nil\n}","line":{"from":789,"to":808}} {"id":100034875,"name":"forceUmount","signature":"func forceUmount(target string, withSafeNotMountedBehavior bool) error","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"func forceUmount(target string, withSafeNotMountedBehavior bool) error {\n\tcommand := exec.Command(\"umount\", \"-f\", target)\n\toutput, err := command.CombinedOutput()\n\n\tif err != nil {\n\t\treturn checkUmountError(target, command, output, err, withSafeNotMountedBehavior)\n\t}\n\treturn nil\n}","line":{"from":810,"to":818}} {"id":100034876,"name":"checkUmountError","signature":"func checkUmountError(target string, command *exec.Cmd, output []byte, err error, withSafeNotMountedBehavior bool) error","file":"staging/src/k8s.io/mount-utils/mount_linux.go","code":"// checkUmountError checks a result of umount command and determine a return value.\nfunc checkUmountError(target string, command *exec.Cmd, output []byte, err error, withSafeNotMountedBehavior bool) error {\n\tif err.Error() == errNoChildProcesses {\n\t\tif command.ProcessState.Success() {\n\t\t\t// We don't consider errNoChildProcesses an error if the process itself succeeded (see - k/k issue #103753).\n\t\t\treturn nil\n\t\t}\n\t\t// Rewrite err with the actual exit error of the process.\n\t\terr = \u0026exec.ExitError{ProcessState: command.ProcessState}\n\t}\n\tif withSafeNotMountedBehavior \u0026\u0026 strings.Contains(string(output), errNotMounted) {\n\t\tklog.V(4).Infof(\"ignoring 'not mounted' error for %s\", target)\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"unmount failed: %v\\nUnmounting arguments: %s\\nOutput: %s\", err, target, string(output))\n}","line":{"from":820,"to":835}} {"id":100034877,"name":"New","signature":"func New(mounterPath string) Interface","file":"staging/src/k8s.io/mount-utils/mount_unsupported.go","code":"// New returns a mount.Interface for the current system.\n// It provides options to override the default mounter behavior.\n// mounterPath allows using an alternative to `/bin/mount` for mounting.\nfunc New(mounterPath string) Interface {\n\treturn \u0026Mounter{\n\t\tmounterPath: mounterPath,\n\t}\n}","line":{"from":33,"to":40}} {"id":100034878,"name":"Mount","signature":"func (mounter *Mounter) Mount(source string, target string, fstype string, options []string) error","file":"staging/src/k8s.io/mount-utils/mount_unsupported.go","code":"// Mount always returns an error on unsupported platforms\nfunc (mounter *Mounter) Mount(source string, target string, fstype string, options []string) error {\n\treturn errUnsupported\n}","line":{"from":42,"to":45}} {"id":100034879,"name":"MountSensitive","signature":"func (mounter *Mounter) MountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string) error","file":"staging/src/k8s.io/mount-utils/mount_unsupported.go","code":"// MountSensitive always returns an error on unsupported platforms\nfunc (mounter *Mounter) MountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string) error {\n\treturn errUnsupported\n}","line":{"from":47,"to":50}} {"id":100034880,"name":"MountSensitiveWithoutSystemd","signature":"func (mounter *Mounter) MountSensitiveWithoutSystemd(source string, target string, fstype string, options []string, sensitiveOptions []string) error","file":"staging/src/k8s.io/mount-utils/mount_unsupported.go","code":"// MountSensitiveWithoutSystemd always returns an error on unsupported platforms\nfunc (mounter *Mounter) MountSensitiveWithoutSystemd(source string, target string, fstype string, options []string, sensitiveOptions []string) error {\n\treturn errUnsupported\n}","line":{"from":52,"to":55}} {"id":100034881,"name":"MountSensitiveWithoutSystemdWithMountFlags","signature":"func (mounter *Mounter) MountSensitiveWithoutSystemdWithMountFlags(source string, target string, fstype string, options []string, sensitiveOptions []string, mountFlags []string) error","file":"staging/src/k8s.io/mount-utils/mount_unsupported.go","code":"// MountSensitiveWithoutSystemdWithMountFlags always returns an error on unsupported platforms\nfunc (mounter *Mounter) MountSensitiveWithoutSystemdWithMountFlags(source string, target string, fstype string, options []string, sensitiveOptions []string, mountFlags []string) error {\n\treturn errUnsupported\n}","line":{"from":57,"to":60}} {"id":100034882,"name":"Unmount","signature":"func (mounter *Mounter) Unmount(target string) error","file":"staging/src/k8s.io/mount-utils/mount_unsupported.go","code":"// Unmount always returns an error on unsupported platforms\nfunc (mounter *Mounter) Unmount(target string) error {\n\treturn errUnsupported\n}","line":{"from":62,"to":65}} {"id":100034883,"name":"List","signature":"func (mounter *Mounter) List() ([]MountPoint, error)","file":"staging/src/k8s.io/mount-utils/mount_unsupported.go","code":"// List always returns an error on unsupported platforms\nfunc (mounter *Mounter) List() ([]MountPoint, error) {\n\treturn []MountPoint{}, errUnsupported\n}","line":{"from":67,"to":70}} {"id":100034884,"name":"IsLikelyNotMountPoint","signature":"func (mounter *Mounter) IsLikelyNotMountPoint(file string) (bool, error)","file":"staging/src/k8s.io/mount-utils/mount_unsupported.go","code":"// IsLikelyNotMountPoint always returns an error on unsupported platforms\nfunc (mounter *Mounter) IsLikelyNotMountPoint(file string) (bool, error) {\n\treturn true, errUnsupported\n}","line":{"from":72,"to":75}} {"id":100034885,"name":"CanSafelySkipMountPointCheck","signature":"func (mounter *Mounter) CanSafelySkipMountPointCheck() bool","file":"staging/src/k8s.io/mount-utils/mount_unsupported.go","code":"// CanSafelySkipMountPointCheck always returns false on unsupported platforms\nfunc (mounter *Mounter) CanSafelySkipMountPointCheck() bool {\n\treturn false\n}","line":{"from":77,"to":80}} {"id":100034886,"name":"IsMountPoint","signature":"func (mounter *Mounter) IsMountPoint(file string) (bool, error)","file":"staging/src/k8s.io/mount-utils/mount_unsupported.go","code":"// IsMountPoint determines if a directory is a mountpoint.\n// It always returns an error on unsupported platforms.\nfunc (mounter *Mounter) IsMountPoint(file string) (bool, error) {\n\treturn false, errUnsupported\n}","line":{"from":82,"to":86}} {"id":100034887,"name":"GetMountRefs","signature":"func (mounter *Mounter) GetMountRefs(pathname string) ([]string, error)","file":"staging/src/k8s.io/mount-utils/mount_unsupported.go","code":"// GetMountRefs always returns an error on unsupported platforms\nfunc (mounter *Mounter) GetMountRefs(pathname string) ([]string, error) {\n\treturn nil, errUnsupported\n}","line":{"from":88,"to":91}} {"id":100034888,"name":"formatAndMountSensitive","signature":"func (mounter *SafeFormatAndMount) formatAndMountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string, formatOptions []string) error","file":"staging/src/k8s.io/mount-utils/mount_unsupported.go","code":"func (mounter *SafeFormatAndMount) formatAndMountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string, formatOptions []string) error {\n\treturn mounter.Interface.Mount(source, target, fstype, options)\n}","line":{"from":93,"to":95}} {"id":100034889,"name":"diskLooksUnformatted","signature":"func (mounter *SafeFormatAndMount) diskLooksUnformatted(disk string) (bool, error)","file":"staging/src/k8s.io/mount-utils/mount_unsupported.go","code":"func (mounter *SafeFormatAndMount) diskLooksUnformatted(disk string) (bool, error) {\n\treturn true, errUnsupported\n}","line":{"from":97,"to":99}} {"id":100034890,"name":"IsMountPoint","signature":"func (mounter *SafeFormatAndMount) IsMountPoint(file string) (bool, error)","file":"staging/src/k8s.io/mount-utils/mount_unsupported.go","code":"// IsMountPoint determines if a directory is a mountpoint.\n// It always returns an error on unsupported platforms.\nfunc (mounter *SafeFormatAndMount) IsMountPoint(file string) (bool, error) {\n\treturn false, errUnsupported\n}","line":{"from":101,"to":105}} {"id":100034891,"name":"New","signature":"func New(mounterPath string) Interface","file":"staging/src/k8s.io/mount-utils/mount_windows.go","code":"// New returns a mount.Interface for the current system.\n// It provides options to override the default mounter behavior.\n// mounterPath allows using an alternative to `/bin/mount` for mounting.\nfunc New(mounterPath string) Interface {\n\treturn \u0026Mounter{\n\t\tmounterPath: mounterPath,\n\t}\n}","line":{"from":44,"to":51}} {"id":100034892,"name":"Mount","signature":"func (mounter *Mounter) Mount(source string, target string, fstype string, options []string) error","file":"staging/src/k8s.io/mount-utils/mount_windows.go","code":"// Mount : mounts source to target with given options.\n// currently only supports cifs(smb), bind mount(for disk)\nfunc (mounter *Mounter) Mount(source string, target string, fstype string, options []string) error {\n\treturn mounter.MountSensitive(source, target, fstype, options, nil /* sensitiveOptions */)\n}","line":{"from":56,"to":60}} {"id":100034893,"name":"MountSensitiveWithoutSystemd","signature":"func (mounter *Mounter) MountSensitiveWithoutSystemd(source string, target string, fstype string, options []string, sensitiveOptions []string) error","file":"staging/src/k8s.io/mount-utils/mount_windows.go","code":"// MountSensitiveWithoutSystemd is the same as MountSensitive() but disable using ssytemd mount.\n// Windows not supported systemd mount, this function degrades to MountSensitive().\nfunc (mounter *Mounter) MountSensitiveWithoutSystemd(source string, target string, fstype string, options []string, sensitiveOptions []string) error {\n\treturn mounter.MountSensitive(source, target, fstype, options, sensitiveOptions /* sensitiveOptions */)\n}","line":{"from":62,"to":66}} {"id":100034894,"name":"MountSensitiveWithoutSystemdWithMountFlags","signature":"func (mounter *Mounter) MountSensitiveWithoutSystemdWithMountFlags(source string, target string, fstype string, options []string, sensitiveOptions []string, mountFlags []string) error","file":"staging/src/k8s.io/mount-utils/mount_windows.go","code":"// MountSensitiveWithoutSystemdWithMountFlags is the same as MountSensitiveWithoutSystemd with additional mount flags\n// Windows not supported systemd mount, this function degrades to MountSensitive().\nfunc (mounter *Mounter) MountSensitiveWithoutSystemdWithMountFlags(source string, target string, fstype string, options []string, sensitiveOptions []string, mountFlags []string) error {\n\treturn mounter.MountSensitive(source, target, fstype, options, sensitiveOptions /* sensitiveOptions */)\n}","line":{"from":68,"to":72}} {"id":100034895,"name":"MountSensitive","signature":"func (mounter *Mounter) MountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string) error","file":"staging/src/k8s.io/mount-utils/mount_windows.go","code":"// MountSensitive is the same as Mount() but this method allows\n// sensitiveOptions to be passed in a separate parameter from the normal\n// mount options and ensures the sensitiveOptions are never logged. This\n// method should be used by callers that pass sensitive material (like\n// passwords) as mount options.\nfunc (mounter *Mounter) MountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string) error {\n\ttarget = NormalizeWindowsPath(target)\n\tsanitizedOptionsForLogging := sanitizedOptionsForLogging(options, sensitiveOptions)\n\n\tif source == \"tmpfs\" {\n\t\tklog.V(3).Infof(\"mounting source (%q), target (%q), with options (%q)\", source, target, sanitizedOptionsForLogging)\n\t\treturn os.MkdirAll(target, 0755)\n\t}\n\n\tparentDir := filepath.Dir(target)\n\tif err := os.MkdirAll(parentDir, 0755); err != nil {\n\t\treturn err\n\t}\n\n\tklog.V(4).Infof(\"mount options(%q) source:%q, target:%q, fstype:%q, begin to mount\",\n\t\tsanitizedOptionsForLogging, source, target, fstype)\n\tbindSource := source\n\n\tif bind, _, _, _ := MakeBindOptsSensitive(options, sensitiveOptions); bind {\n\t\tbindSource = NormalizeWindowsPath(source)\n\t} else {\n\t\tallOptions := []string{}\n\t\tallOptions = append(allOptions, options...)\n\t\tallOptions = append(allOptions, sensitiveOptions...)\n\t\tif len(allOptions) \u003c 2 {\n\t\t\treturn fmt.Errorf(\"mount options(%q) should have at least 2 options, current number:%d, source:%q, target:%q\",\n\t\t\t\tsanitizedOptionsForLogging, len(allOptions), source, target)\n\t\t}\n\n\t\t// currently only cifs mount is supported\n\t\tif strings.ToLower(fstype) != \"cifs\" {\n\t\t\treturn fmt.Errorf(\"only cifs mount is supported now, fstype: %q, mounting source (%q), target (%q), with options (%q)\", fstype, source, target, sanitizedOptionsForLogging)\n\t\t}\n\n\t\t// lock smb mount for the same source\n\t\tgetSMBMountMutex.LockKey(source)\n\t\tdefer getSMBMountMutex.UnlockKey(source)\n\n\t\tusername := allOptions[0]\n\t\tpassword := allOptions[1]\n\t\tif output, err := newSMBMapping(username, password, source); err != nil {\n\t\t\tklog.Warningf(\"SMB Mapping(%s) returned with error(%v), output(%s)\", source, err, string(output))\n\t\t\tif isSMBMappingExist(source) {\n\t\t\t\tvalid, err := isValidPath(source)\n\t\t\t\tif !valid {\n\t\t\t\t\tif err == nil || isAccessDeniedError(err) {\n\t\t\t\t\t\tklog.V(2).Infof(\"SMB Mapping(%s) already exists while it's not valid, return error: %v, now begin to remove and remount\", source, err)\n\t\t\t\t\t\tif output, err = removeSMBMapping(source); err != nil {\n\t\t\t\t\t\t\treturn fmt.Errorf(\"Remove-SmbGlobalMapping failed: %v, output: %q\", err, output)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif output, err := newSMBMapping(username, password, source); err != nil {\n\t\t\t\t\t\t\treturn fmt.Errorf(\"New-SmbGlobalMapping(%s) failed: %v, output: %q\", source, err, output)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tklog.V(2).Infof(\"SMB Mapping(%s) already exists and is still valid, skip error(%v)\", source, err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn fmt.Errorf(\"New-SmbGlobalMapping(%s) failed: %v, output: %q\", source, err, output)\n\t\t\t}\n\t\t}\n\t}\n\n\t// There is an issue in golang where EvalSymlinks fails on Windows when passed a\n\t// UNC share root path without a trailing backslash.\n\t// Ex: \\\\SERVER\\share will fail to resolve but \\\\SERVER\\share\\ will resolve\n\t// containerD on Windows calls EvalSymlinks so we'll add the backslash when making the symlink if it is missing.\n\t// https://github.com/golang/go/pull/42096 fixes this issue in golang but a fix will not be available until\n\t// golang v1.16\n\tmklinkSource := bindSource\n\tif !strings.HasSuffix(mklinkSource, \"\\\\\") {\n\t\tmklinkSource = mklinkSource + \"\\\\\"\n\t}\n\n\toutput, err := exec.Command(\"cmd\", \"/c\", \"mklink\", \"/D\", target, mklinkSource).CombinedOutput()\n\tif err != nil {\n\t\tklog.Errorf(\"mklink failed: %v, source(%q) target(%q) output: %q\", err, mklinkSource, target, string(output))\n\t\treturn err\n\t}\n\tklog.V(2).Infof(\"mklink source(%q) on target(%q) successfully, output: %q\", mklinkSource, target, string(output))\n\n\treturn nil\n}","line":{"from":74,"to":161}} {"id":100034896,"name":"newSMBMapping","signature":"func newSMBMapping(username, password, remotepath string) (string, error)","file":"staging/src/k8s.io/mount-utils/mount_windows.go","code":"// do the SMB mount with username, password, remotepath\n// return (output, error)\nfunc newSMBMapping(username, password, remotepath string) (string, error) {\n\tif username == \"\" || password == \"\" || remotepath == \"\" {\n\t\treturn \"\", fmt.Errorf(\"invalid parameter(username: %s, password: %s, remoteapth: %s)\", username, sensitiveOptionsRemoved, remotepath)\n\t}\n\n\t// use PowerShell Environment Variables to store user input string to prevent command line injection\n\t// https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_environment_variables?view=powershell-5.1\n\tcmdLine := `$PWord = ConvertTo-SecureString -String $Env:smbpassword -AsPlainText -Force` +\n\t\t`;$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Env:smbuser, $PWord` +\n\t\t`;New-SmbGlobalMapping -RemotePath $Env:smbremotepath -Credential $Credential -RequirePrivacy $true`\n\tcmd := exec.Command(\"powershell\", \"/c\", cmdLine)\n\tcmd.Env = append(os.Environ(),\n\t\tfmt.Sprintf(\"smbuser=%s\", username),\n\t\tfmt.Sprintf(\"smbpassword=%s\", password),\n\t\tfmt.Sprintf(\"smbremotepath=%s\", remotepath))\n\n\toutput, err := cmd.CombinedOutput()\n\treturn string(output), err\n}","line":{"from":163,"to":183}} {"id":100034897,"name":"isSMBMappingExist","signature":"func isSMBMappingExist(remotepath string) bool","file":"staging/src/k8s.io/mount-utils/mount_windows.go","code":"// check whether remotepath is already mounted\nfunc isSMBMappingExist(remotepath string) bool {\n\tcmd := exec.Command(\"powershell\", \"/c\", `Get-SmbGlobalMapping -RemotePath $Env:smbremotepath`)\n\tcmd.Env = append(os.Environ(), fmt.Sprintf(\"smbremotepath=%s\", remotepath))\n\t_, err := cmd.CombinedOutput()\n\treturn err == nil\n}","line":{"from":185,"to":191}} {"id":100034898,"name":"isValidPath","signature":"func isValidPath(remotepath string) (bool, error)","file":"staging/src/k8s.io/mount-utils/mount_windows.go","code":"// check whether remotepath is valid\n// return (true, nil) if remotepath is valid\nfunc isValidPath(remotepath string) (bool, error) {\n\tcmd := exec.Command(\"powershell\", \"/c\", `Test-Path $Env:remoteapth`)\n\tcmd.Env = append(os.Environ(), fmt.Sprintf(\"remoteapth=%s\", remotepath))\n\toutput, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"returned output: %s, error: %v\", string(output), err)\n\t}\n\n\treturn strings.HasPrefix(strings.ToLower(string(output)), \"true\"), nil\n}","line":{"from":193,"to":204}} {"id":100034899,"name":"isAccessDeniedError","signature":"func isAccessDeniedError(err error) bool","file":"staging/src/k8s.io/mount-utils/mount_windows.go","code":"func isAccessDeniedError(err error) bool {\n\treturn err != nil \u0026\u0026 strings.Contains(strings.ToLower(err.Error()), accessDenied)\n}","line":{"from":206,"to":208}} {"id":100034900,"name":"removeSMBMapping","signature":"func removeSMBMapping(remotepath string) (string, error)","file":"staging/src/k8s.io/mount-utils/mount_windows.go","code":"// remove SMB mapping\nfunc removeSMBMapping(remotepath string) (string, error) {\n\tcmd := exec.Command(\"powershell\", \"/c\", `Remove-SmbGlobalMapping -RemotePath $Env:smbremotepath -Force`)\n\tcmd.Env = append(os.Environ(), fmt.Sprintf(\"smbremotepath=%s\", remotepath))\n\toutput, err := cmd.CombinedOutput()\n\treturn string(output), err\n}","line":{"from":210,"to":216}} {"id":100034901,"name":"Unmount","signature":"func (mounter *Mounter) Unmount(target string) error","file":"staging/src/k8s.io/mount-utils/mount_windows.go","code":"// Unmount unmounts the target.\nfunc (mounter *Mounter) Unmount(target string) error {\n\tklog.V(4).Infof(\"Unmount target (%q)\", target)\n\ttarget = NormalizeWindowsPath(target)\n\tif output, err := exec.Command(\"cmd\", \"/c\", \"rmdir\", target).CombinedOutput(); err != nil {\n\t\tklog.Errorf(\"rmdir failed: %v, output: %q\", err, string(output))\n\t\treturn err\n\t}\n\treturn nil\n}","line":{"from":218,"to":227}} {"id":100034902,"name":"List","signature":"func (mounter *Mounter) List() ([]MountPoint, error)","file":"staging/src/k8s.io/mount-utils/mount_windows.go","code":"// List returns a list of all mounted filesystems. todo\nfunc (mounter *Mounter) List() ([]MountPoint, error) {\n\treturn []MountPoint{}, nil\n}","line":{"from":229,"to":232}} {"id":100034903,"name":"IsLikelyNotMountPoint","signature":"func (mounter *Mounter) IsLikelyNotMountPoint(file string) (bool, error)","file":"staging/src/k8s.io/mount-utils/mount_windows.go","code":"// IsLikelyNotMountPoint determines if a directory is not a mountpoint.\nfunc (mounter *Mounter) IsLikelyNotMountPoint(file string) (bool, error) {\n\tstat, err := os.Lstat(file)\n\tif err != nil {\n\t\treturn true, err\n\t}\n\n\tif stat.Mode()\u0026os.ModeSymlink != 0 {\n\t\treturn false, err\n\t}\n\treturn true, nil\n}","line":{"from":234,"to":245}} {"id":100034904,"name":"CanSafelySkipMountPointCheck","signature":"func (mounter *Mounter) CanSafelySkipMountPointCheck() bool","file":"staging/src/k8s.io/mount-utils/mount_windows.go","code":"// CanSafelySkipMountPointCheck always returns false on Windows\nfunc (mounter *Mounter) CanSafelySkipMountPointCheck() bool {\n\treturn false\n}","line":{"from":247,"to":250}} {"id":100034905,"name":"IsMountPoint","signature":"func (mounter *Mounter) IsMountPoint(file string) (bool, error)","file":"staging/src/k8s.io/mount-utils/mount_windows.go","code":"// IsMountPoint: determines if a directory is a mountpoint.\nfunc (mounter *Mounter) IsMountPoint(file string) (bool, error) {\n\tisNotMnt, err := mounter.IsLikelyNotMountPoint(file)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn !isNotMnt, nil\n}","line":{"from":252,"to":259}} {"id":100034906,"name":"GetMountRefs","signature":"func (mounter *Mounter) GetMountRefs(pathname string) ([]string, error)","file":"staging/src/k8s.io/mount-utils/mount_windows.go","code":"// GetMountRefs : empty implementation here since there is no place to query all mount points on Windows\nfunc (mounter *Mounter) GetMountRefs(pathname string) ([]string, error) {\n\twindowsPath := NormalizeWindowsPath(pathname)\n\tpathExists, pathErr := PathExists(windowsPath)\n\tif !pathExists {\n\t\treturn []string{}, nil\n\t} else if IsCorruptedMnt(pathErr) {\n\t\tklog.Warningf(\"GetMountRefs found corrupted mount at %s, treating as unmounted path\", windowsPath)\n\t\treturn []string{}, nil\n\t} else if pathErr != nil {\n\t\treturn nil, fmt.Errorf(\"error checking path %s: %v\", windowsPath, pathErr)\n\t}\n\treturn []string{pathname}, nil\n}","line":{"from":261,"to":274}} {"id":100034907,"name":"formatAndMountSensitive","signature":"func (mounter *SafeFormatAndMount) formatAndMountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string, formatOptions []string) error","file":"staging/src/k8s.io/mount-utils/mount_windows.go","code":"func (mounter *SafeFormatAndMount) formatAndMountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string, formatOptions []string) error {\n\t// Try to mount the disk\n\tklog.V(4).Infof(\"Attempting to formatAndMount disk: %s %s %s\", fstype, source, target)\n\n\tif err := ValidateDiskNumber(source); err != nil {\n\t\tklog.Errorf(\"diskMount: formatAndMount failed, err: %v\", err)\n\t\treturn err\n\t}\n\n\tif len(fstype) == 0 {\n\t\t// Use 'NTFS' as the default\n\t\tfstype = \"NTFS\"\n\t}\n\n\t// format disk if it is unformatted(raw)\n\tformatOptionsUnwrapped := \"\"\n\tif len(formatOptions) \u003e 0 {\n\t\tformatOptionsUnwrapped = \" \" + strings.Join(formatOptions, \" \")\n\t}\n\tcmd := fmt.Sprintf(\"Get-Disk -Number %s | Where partitionstyle -eq 'raw' | Initialize-Disk -PartitionStyle GPT -PassThru\"+\n\t\t\" | New-Partition -UseMaximumSize | Format-Volume -FileSystem %s -Confirm:$false%s\", source, fstype, formatOptionsUnwrapped)\n\tif output, err := mounter.Exec.Command(\"powershell\", \"/c\", cmd).CombinedOutput(); err != nil {\n\t\treturn fmt.Errorf(\"diskMount: format disk failed, error: %v, output: %q\", err, string(output))\n\t}\n\tklog.V(4).Infof(\"diskMount: Disk successfully formatted, disk: %q, fstype: %q\", source, fstype)\n\n\tvolumeIds, err := listVolumesOnDisk(source)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdriverPath := volumeIds[0]\n\ttarget = NormalizeWindowsPath(target)\n\toutput, err := mounter.Exec.Command(\"cmd\", \"/c\", \"mklink\", \"/D\", target, driverPath).CombinedOutput()\n\tif err != nil {\n\t\tklog.Errorf(\"mklink(%s, %s) failed: %v, output: %q\", target, driverPath, err, string(output))\n\t\treturn err\n\t}\n\tklog.V(2).Infof(\"formatAndMount disk(%s) fstype(%s) on(%s) with output(%s) successfully\", driverPath, fstype, target, string(output))\n\treturn nil\n}","line":{"from":276,"to":315}} {"id":100034908,"name":"listVolumesOnDisk","signature":"func listVolumesOnDisk(diskID string) (volumeIDs []string, err error)","file":"staging/src/k8s.io/mount-utils/mount_windows.go","code":"// ListVolumesOnDisk - returns back list of volumes(volumeIDs) in the disk (requested in diskID).\nfunc listVolumesOnDisk(diskID string) (volumeIDs []string, err error) {\n\tcmd := fmt.Sprintf(\"(Get-Disk -DeviceId %s | Get-Partition | Get-Volume).UniqueId\", diskID)\n\toutput, err := exec.Command(\"powershell\", \"/c\", cmd).CombinedOutput()\n\tklog.V(4).Infof(\"listVolumesOnDisk id from %s: %s\", diskID, string(output))\n\tif err != nil {\n\t\treturn []string{}, fmt.Errorf(\"error list volumes on disk. cmd: %s, output: %s, error: %v\", cmd, string(output), err)\n\t}\n\n\tvolumeIds := strings.Split(strings.TrimSpace(string(output)), \"\\r\\n\")\n\treturn volumeIds, nil\n}","line":{"from":317,"to":328}} {"id":100034909,"name":"getAllParentLinks","signature":"func getAllParentLinks(path string) ([]string, error)","file":"staging/src/k8s.io/mount-utils/mount_windows.go","code":"// getAllParentLinks walks all symbolic links and return all the parent targets recursively\nfunc getAllParentLinks(path string) ([]string, error) {\n\tconst maxIter = 255\n\tlinks := []string{}\n\tfor {\n\t\tlinks = append(links, path)\n\t\tif len(links) \u003e maxIter {\n\t\t\treturn links, fmt.Errorf(\"unexpected length of parent links: %v\", links)\n\t\t}\n\n\t\tfi, err := os.Lstat(path)\n\t\tif err != nil {\n\t\t\treturn links, fmt.Errorf(\"Lstat: %v\", err)\n\t\t}\n\t\tif fi.Mode()\u0026os.ModeSymlink == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\tpath, err = os.Readlink(path)\n\t\tif err != nil {\n\t\t\treturn links, fmt.Errorf(\"Readlink error: %v\", err)\n\t\t}\n\t}\n\n\treturn links, nil\n}","line":{"from":330,"to":355}} {"id":100034910,"name":"NewResizeFs","signature":"func NewResizeFs(exec utilexec.Interface) *ResizeFs","file":"staging/src/k8s.io/mount-utils/resizefs_linux.go","code":"// NewResizeFs returns new instance of resizer\nfunc NewResizeFs(exec utilexec.Interface) *ResizeFs {\n\treturn \u0026ResizeFs{exec: exec}\n}","line":{"from":40,"to":43}} {"id":100034911,"name":"Resize","signature":"func (resizefs *ResizeFs) Resize(devicePath string, deviceMountPath string) (bool, error)","file":"staging/src/k8s.io/mount-utils/resizefs_linux.go","code":"// Resize perform resize of file system\nfunc (resizefs *ResizeFs) Resize(devicePath string, deviceMountPath string) (bool, error) {\n\tformat, err := getDiskFormat(resizefs.exec, devicePath)\n\n\tif err != nil {\n\t\tformatErr := fmt.Errorf(\"ResizeFS.Resize - error checking format for device %s: %v\", devicePath, err)\n\t\treturn false, formatErr\n\t}\n\n\t// If disk has no format, there is no need to resize the disk because mkfs.*\n\t// by default will use whole disk anyways.\n\tif format == \"\" {\n\t\treturn false, nil\n\t}\n\n\tklog.V(3).Infof(\"ResizeFS.Resize - Expanding mounted volume %s\", devicePath)\n\tswitch format {\n\tcase \"ext3\", \"ext4\":\n\t\treturn resizefs.extResize(devicePath)\n\tcase \"xfs\":\n\t\treturn resizefs.xfsResize(deviceMountPath)\n\tcase \"btrfs\":\n\t\treturn resizefs.btrfsResize(deviceMountPath)\n\t}\n\treturn false, fmt.Errorf(\"ResizeFS.Resize - resize of format %s is not supported for device %s mounted at %s\", format, devicePath, deviceMountPath)\n}","line":{"from":45,"to":70}} {"id":100034912,"name":"extResize","signature":"func (resizefs *ResizeFs) extResize(devicePath string) (bool, error)","file":"staging/src/k8s.io/mount-utils/resizefs_linux.go","code":"func (resizefs *ResizeFs) extResize(devicePath string) (bool, error) {\n\toutput, err := resizefs.exec.Command(\"resize2fs\", devicePath).CombinedOutput()\n\tif err == nil {\n\t\tklog.V(2).Infof(\"Device %s resized successfully\", devicePath)\n\t\treturn true, nil\n\t}\n\n\tresizeError := fmt.Errorf(\"resize of device %s failed: %v. resize2fs output: %s\", devicePath, err, string(output))\n\treturn false, resizeError\n\n}","line":{"from":72,"to":82}} {"id":100034913,"name":"xfsResize","signature":"func (resizefs *ResizeFs) xfsResize(deviceMountPath string) (bool, error)","file":"staging/src/k8s.io/mount-utils/resizefs_linux.go","code":"func (resizefs *ResizeFs) xfsResize(deviceMountPath string) (bool, error) {\n\targs := []string{\"-d\", deviceMountPath}\n\toutput, err := resizefs.exec.Command(\"xfs_growfs\", args...).CombinedOutput()\n\n\tif err == nil {\n\t\tklog.V(2).Infof(\"Device %s resized successfully\", deviceMountPath)\n\t\treturn true, nil\n\t}\n\n\tresizeError := fmt.Errorf(\"resize of device %s failed: %v. xfs_growfs output: %s\", deviceMountPath, err, string(output))\n\treturn false, resizeError\n}","line":{"from":84,"to":95}} {"id":100034914,"name":"btrfsResize","signature":"func (resizefs *ResizeFs) btrfsResize(deviceMountPath string) (bool, error)","file":"staging/src/k8s.io/mount-utils/resizefs_linux.go","code":"func (resizefs *ResizeFs) btrfsResize(deviceMountPath string) (bool, error) {\n\targs := []string{\"filesystem\", \"resize\", \"max\", deviceMountPath}\n\toutput, err := resizefs.exec.Command(\"btrfs\", args...).CombinedOutput()\n\n\tif err == nil {\n\t\tklog.V(2).Infof(\"Device %s resized successfully\", deviceMountPath)\n\t\treturn true, nil\n\t}\n\n\tresizeError := fmt.Errorf(\"resize of device %s failed: %v. btrfs output: %s\", deviceMountPath, err, string(output))\n\treturn false, resizeError\n}","line":{"from":97,"to":108}} {"id":100034915,"name":"NeedResize","signature":"func (resizefs *ResizeFs) NeedResize(devicePath string, deviceMountPath string) (bool, error)","file":"staging/src/k8s.io/mount-utils/resizefs_linux.go","code":"func (resizefs *ResizeFs) NeedResize(devicePath string, deviceMountPath string) (bool, error) {\n\t// Do nothing if device is mounted as readonly\n\treadonly, err := resizefs.getDeviceRO(devicePath)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif readonly {\n\t\tklog.V(3).Infof(\"ResizeFs.needResize - no resize possible since filesystem %s is readonly\", devicePath)\n\t\treturn false, nil\n\t}\n\n\tdeviceSize, err := resizefs.getDeviceSize(devicePath)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tvar fsSize, blockSize uint64\n\tformat, err := getDiskFormat(resizefs.exec, devicePath)\n\tif err != nil {\n\t\tformatErr := fmt.Errorf(\"ResizeFS.Resize - error checking format for device %s: %v\", devicePath, err)\n\t\treturn false, formatErr\n\t}\n\n\t// If disk has no format, there is no need to resize the disk because mkfs.*\n\t// by default will use whole disk anyways.\n\tif format == \"\" {\n\t\treturn false, nil\n\t}\n\n\tklog.V(3).Infof(\"ResizeFs.needResize - checking mounted volume %s\", devicePath)\n\tswitch format {\n\tcase \"ext3\", \"ext4\":\n\t\tblockSize, fsSize, err = resizefs.getExtSize(devicePath)\n\t\tklog.V(5).Infof(\"Ext size: filesystem size=%d, block size=%d\", fsSize, blockSize)\n\tcase \"xfs\":\n\t\tblockSize, fsSize, err = resizefs.getXFSSize(deviceMountPath)\n\t\tklog.V(5).Infof(\"Xfs size: filesystem size=%d, block size=%d, err=%v\", fsSize, blockSize, err)\n\tcase \"btrfs\":\n\t\tblockSize, fsSize, err = resizefs.getBtrfsSize(devicePath)\n\t\tklog.V(5).Infof(\"Btrfs size: filesystem size=%d, block size=%d, err=%v\", fsSize, blockSize, err)\n\tdefault:\n\t\tklog.Errorf(\"Not able to parse given filesystem info. fsType: %s, will not resize\", format)\n\t\treturn false, fmt.Errorf(\"Could not parse fs info on given filesystem format: %s. Supported fs types are: xfs, ext3, ext4\", format)\n\t}\n\tif err != nil {\n\t\treturn false, err\n\t}\n\t// Tolerate one block difference, just in case of rounding errors somewhere.\n\tklog.V(5).Infof(\"Volume %s: device size=%d, filesystem size=%d, block size=%d\", devicePath, deviceSize, fsSize, blockSize)\n\tif deviceSize \u003c= fsSize+blockSize {\n\t\treturn false, nil\n\t}\n\treturn true, nil\n}","line":{"from":110,"to":163}} {"id":100034916,"name":"getDeviceSize","signature":"func (resizefs *ResizeFs) getDeviceSize(devicePath string) (uint64, error)","file":"staging/src/k8s.io/mount-utils/resizefs_linux.go","code":"func (resizefs *ResizeFs) getDeviceSize(devicePath string) (uint64, error) {\n\toutput, err := resizefs.exec.Command(blockDev, \"--getsize64\", devicePath).CombinedOutput()\n\toutStr := strings.TrimSpace(string(output))\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"failed to read size of device %s: %s: %s\", devicePath, err, outStr)\n\t}\n\tsize, err := strconv.ParseUint(outStr, 10, 64)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"failed to parse size of device %s %s: %s\", devicePath, outStr, err)\n\t}\n\treturn size, nil\n}","line":{"from":164,"to":175}} {"id":100034917,"name":"getDeviceRO","signature":"func (resizefs *ResizeFs) getDeviceRO(devicePath string) (bool, error)","file":"staging/src/k8s.io/mount-utils/resizefs_linux.go","code":"func (resizefs *ResizeFs) getDeviceRO(devicePath string) (bool, error) {\n\toutput, err := resizefs.exec.Command(blockDev, \"--getro\", devicePath).CombinedOutput()\n\toutStr := strings.TrimSpace(string(output))\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"failed to get readonly bit from device %s: %s: %s\", devicePath, err, outStr)\n\t}\n\tswitch outStr {\n\tcase \"0\":\n\t\treturn false, nil\n\tcase \"1\":\n\t\treturn true, nil\n\tdefault:\n\t\treturn false, fmt.Errorf(\"Failed readonly device check. Expected 1 or 0, got '%s'\", outStr)\n\t}\n}","line":{"from":177,"to":191}} {"id":100034918,"name":"getExtSize","signature":"func (resizefs *ResizeFs) getExtSize(devicePath string) (uint64, uint64, error)","file":"staging/src/k8s.io/mount-utils/resizefs_linux.go","code":"func (resizefs *ResizeFs) getExtSize(devicePath string) (uint64, uint64, error) {\n\toutput, err := resizefs.exec.Command(\"dumpe2fs\", \"-h\", devicePath).CombinedOutput()\n\tif err != nil {\n\t\treturn 0, 0, fmt.Errorf(\"failed to read size of filesystem on %s: %s: %s\", devicePath, err, string(output))\n\t}\n\n\tblockSize, blockCount, _ := resizefs.parseFsInfoOutput(string(output), \":\", \"block size\", \"block count\")\n\n\tif blockSize == 0 {\n\t\treturn 0, 0, fmt.Errorf(\"could not find block size of device %s\", devicePath)\n\t}\n\tif blockCount == 0 {\n\t\treturn 0, 0, fmt.Errorf(\"could not find block count of device %s\", devicePath)\n\t}\n\treturn blockSize, blockSize * blockCount, nil\n}","line":{"from":193,"to":208}} {"id":100034919,"name":"getXFSSize","signature":"func (resizefs *ResizeFs) getXFSSize(devicePath string) (uint64, uint64, error)","file":"staging/src/k8s.io/mount-utils/resizefs_linux.go","code":"func (resizefs *ResizeFs) getXFSSize(devicePath string) (uint64, uint64, error) {\n\toutput, err := resizefs.exec.Command(\"xfs_io\", \"-c\", \"statfs\", devicePath).CombinedOutput()\n\tif err != nil {\n\t\treturn 0, 0, fmt.Errorf(\"failed to read size of filesystem on %s: %s: %s\", devicePath, err, string(output))\n\t}\n\n\tblockSize, blockCount, _ := resizefs.parseFsInfoOutput(string(output), \"=\", \"geom.bsize\", \"geom.datablocks\")\n\n\tif blockSize == 0 {\n\t\treturn 0, 0, fmt.Errorf(\"could not find block size of device %s\", devicePath)\n\t}\n\tif blockCount == 0 {\n\t\treturn 0, 0, fmt.Errorf(\"could not find block count of device %s\", devicePath)\n\t}\n\treturn blockSize, blockSize * blockCount, nil\n}","line":{"from":210,"to":225}} {"id":100034920,"name":"getBtrfsSize","signature":"func (resizefs *ResizeFs) getBtrfsSize(devicePath string) (uint64, uint64, error)","file":"staging/src/k8s.io/mount-utils/resizefs_linux.go","code":"func (resizefs *ResizeFs) getBtrfsSize(devicePath string) (uint64, uint64, error) {\n\toutput, err := resizefs.exec.Command(\"btrfs\", \"inspect-internal\", \"dump-super\", \"-f\", devicePath).CombinedOutput()\n\tif err != nil {\n\t\treturn 0, 0, fmt.Errorf(\"failed to read size of filesystem on %s: %s: %s\", devicePath, err, string(output))\n\t}\n\n\tblockSize, totalBytes, _ := resizefs.parseBtrfsInfoOutput(string(output), \"sectorsize\", \"total_bytes\")\n\n\tif blockSize == 0 {\n\t\treturn 0, 0, fmt.Errorf(\"could not find block size of device %s\", devicePath)\n\t}\n\tif totalBytes == 0 {\n\t\treturn 0, 0, fmt.Errorf(\"could not find total size of device %s\", devicePath)\n\t}\n\treturn blockSize, totalBytes, nil\n}","line":{"from":227,"to":242}} {"id":100034921,"name":"parseBtrfsInfoOutput","signature":"func (resizefs *ResizeFs) parseBtrfsInfoOutput(cmdOutput string, blockSizeKey string, totalBytesKey string) (uint64, uint64, error)","file":"staging/src/k8s.io/mount-utils/resizefs_linux.go","code":"func (resizefs *ResizeFs) parseBtrfsInfoOutput(cmdOutput string, blockSizeKey string, totalBytesKey string) (uint64, uint64, error) {\n\tlines := strings.Split(cmdOutput, \"\\n\")\n\tvar blockSize, blockCount uint64\n\tvar err error\n\n\tfor _, line := range lines {\n\t\ttokens := strings.Fields(line)\n\t\tif len(tokens) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\tkey, value := strings.ToLower(strings.TrimSpace(tokens[0])), strings.ToLower(strings.TrimSpace(tokens[1]))\n\n\t\tif key == blockSizeKey {\n\t\t\tblockSize, err = strconv.ParseUint(value, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, 0, fmt.Errorf(\"failed to parse block size %s: %s\", value, err)\n\t\t\t}\n\t\t}\n\t\tif key == totalBytesKey {\n\t\t\tblockCount, err = strconv.ParseUint(value, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, 0, fmt.Errorf(\"failed to parse total size %s: %s\", value, err)\n\t\t\t}\n\t\t}\n\t}\n\treturn blockSize, blockCount, err\n}","line":{"from":244,"to":270}} {"id":100034922,"name":"parseFsInfoOutput","signature":"func (resizefs *ResizeFs) parseFsInfoOutput(cmdOutput string, spliter string, blockSizeKey string, blockCountKey string) (uint64, uint64, error)","file":"staging/src/k8s.io/mount-utils/resizefs_linux.go","code":"func (resizefs *ResizeFs) parseFsInfoOutput(cmdOutput string, spliter string, blockSizeKey string, blockCountKey string) (uint64, uint64, error) {\n\tlines := strings.Split(cmdOutput, \"\\n\")\n\tvar blockSize, blockCount uint64\n\tvar err error\n\n\tfor _, line := range lines {\n\t\ttokens := strings.Split(line, spliter)\n\t\tif len(tokens) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\tkey, value := strings.ToLower(strings.TrimSpace(tokens[0])), strings.ToLower(strings.TrimSpace(tokens[1]))\n\t\tif key == blockSizeKey {\n\t\t\tblockSize, err = strconv.ParseUint(value, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, 0, fmt.Errorf(\"failed to parse block size %s: %s\", value, err)\n\t\t\t}\n\t\t}\n\t\tif key == blockCountKey {\n\t\t\tblockCount, err = strconv.ParseUint(value, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, 0, fmt.Errorf(\"failed to parse block count %s: %s\", value, err)\n\t\t\t}\n\t\t}\n\t}\n\treturn blockSize, blockCount, err\n}","line":{"from":272,"to":297}} {"id":100034923,"name":"NewResizeFs","signature":"func NewResizeFs(exec utilexec.Interface) *ResizeFs","file":"staging/src/k8s.io/mount-utils/resizefs_unsupported.go","code":"// NewResizeFs returns new instance of resizer\nfunc NewResizeFs(exec utilexec.Interface) *ResizeFs {\n\treturn \u0026ResizeFs{exec: exec}\n}","line":{"from":33,"to":36}} {"id":100034924,"name":"Resize","signature":"func (resizefs *ResizeFs) Resize(devicePath string, deviceMountPath string) (bool, error)","file":"staging/src/k8s.io/mount-utils/resizefs_unsupported.go","code":"// Resize perform resize of file system\nfunc (resizefs *ResizeFs) Resize(devicePath string, deviceMountPath string) (bool, error) {\n\treturn false, fmt.Errorf(\"Resize is not supported for this build\")\n}","line":{"from":38,"to":41}} {"id":100034925,"name":"NeedResize","signature":"func (resizefs *ResizeFs) NeedResize(devicePath string, deviceMountPath string) (bool, error)","file":"staging/src/k8s.io/mount-utils/resizefs_unsupported.go","code":"// NeedResize check whether mounted volume needs resize\nfunc (resizefs *ResizeFs) NeedResize(devicePath string, deviceMountPath string) (bool, error) {\n\treturn false, fmt.Errorf(\"NeedResize is not supported for this build\")\n}","line":{"from":43,"to":46}} {"id":100034926,"name":"HasPodSpec","signature":"func (DefaultPodSpecExtractor) HasPodSpec(gr schema.GroupResource) bool","file":"staging/src/k8s.io/pod-security-admission/admission/admission.go","code":"func (DefaultPodSpecExtractor) HasPodSpec(gr schema.GroupResource) bool {\n\treturn defaultPodSpecResources[gr]\n}","line":{"from":108,"to":110}} {"id":100034927,"name":"ExtractPodSpec","signature":"func (DefaultPodSpecExtractor) ExtractPodSpec(obj runtime.Object) (*metav1.ObjectMeta, *corev1.PodSpec, error)","file":"staging/src/k8s.io/pod-security-admission/admission/admission.go","code":"func (DefaultPodSpecExtractor) ExtractPodSpec(obj runtime.Object) (*metav1.ObjectMeta, *corev1.PodSpec, error) {\n\tswitch o := obj.(type) {\n\tcase *corev1.Pod:\n\t\treturn \u0026o.ObjectMeta, \u0026o.Spec, nil\n\tcase *corev1.PodTemplate:\n\t\treturn extractPodSpecFromTemplate(\u0026o.Template)\n\tcase *corev1.ReplicationController:\n\t\treturn extractPodSpecFromTemplate(o.Spec.Template)\n\tcase *appsv1.ReplicaSet:\n\t\treturn extractPodSpecFromTemplate(\u0026o.Spec.Template)\n\tcase *appsv1.Deployment:\n\t\treturn extractPodSpecFromTemplate(\u0026o.Spec.Template)\n\tcase *appsv1.DaemonSet:\n\t\treturn extractPodSpecFromTemplate(\u0026o.Spec.Template)\n\tcase *appsv1.StatefulSet:\n\t\treturn extractPodSpecFromTemplate(\u0026o.Spec.Template)\n\tcase *batchv1.Job:\n\t\treturn extractPodSpecFromTemplate(\u0026o.Spec.Template)\n\tcase *batchv1.CronJob:\n\t\treturn extractPodSpecFromTemplate(\u0026o.Spec.JobTemplate.Spec.Template)\n\tdefault:\n\t\treturn nil, nil, fmt.Errorf(\"unexpected object type: %s\", obj.GetObjectKind().GroupVersionKind().String())\n\t}\n}","line":{"from":112,"to":135}} {"id":100034928,"name":"PodSpecResources","signature":"func (DefaultPodSpecExtractor) PodSpecResources() []schema.GroupResource","file":"staging/src/k8s.io/pod-security-admission/admission/admission.go","code":"func (DefaultPodSpecExtractor) PodSpecResources() []schema.GroupResource {\n\tretval := make([]schema.GroupResource, 0, len(defaultPodSpecResources))\n\tfor r := range defaultPodSpecResources {\n\t\tretval = append(retval, r)\n\t}\n\treturn retval\n}","line":{"from":137,"to":143}} {"id":100034929,"name":"extractPodSpecFromTemplate","signature":"func extractPodSpecFromTemplate(template *corev1.PodTemplateSpec) (*metav1.ObjectMeta, *corev1.PodSpec, error)","file":"staging/src/k8s.io/pod-security-admission/admission/admission.go","code":"func extractPodSpecFromTemplate(template *corev1.PodTemplateSpec) (*metav1.ObjectMeta, *corev1.PodSpec, error) {\n\tif template == nil {\n\t\treturn nil, nil, nil\n\t}\n\treturn \u0026template.ObjectMeta, \u0026template.Spec, nil\n}","line":{"from":145,"to":150}} {"id":100034930,"name":"CompleteConfiguration","signature":"func (a *Admission) CompleteConfiguration() error","file":"staging/src/k8s.io/pod-security-admission/admission/admission.go","code":"// CompleteConfiguration sets up default or derived configuration.\nfunc (a *Admission) CompleteConfiguration() error {\n\tif a.Configuration != nil {\n\t\tif p, err := admissionapi.ToPolicy(a.Configuration.Defaults); err != nil {\n\t\t\treturn err\n\t\t} else {\n\t\t\ta.defaultPolicy = p\n\t\t}\n\t}\n\ta.namespaceMaxPodsToCheck = defaultNamespaceMaxPodsToCheck\n\ta.namespacePodCheckTimeout = defaultNamespacePodCheckTimeout\n\n\tif a.PodSpecExtractor == nil {\n\t\ta.PodSpecExtractor = \u0026DefaultPodSpecExtractor{}\n\t}\n\n\treturn nil\n}","line":{"from":152,"to":169}} {"id":100034931,"name":"ValidateConfiguration","signature":"func (a *Admission) ValidateConfiguration() error","file":"staging/src/k8s.io/pod-security-admission/admission/admission.go","code":"// ValidateConfiguration ensures all required fields are set with valid values.\nfunc (a *Admission) ValidateConfiguration() error {\n\tif a.Configuration == nil {\n\t\treturn fmt.Errorf(\"configuration required\")\n\t} else if errs := validation.ValidatePodSecurityConfiguration(a.Configuration); len(errs) \u003e 0 {\n\t\treturn errs.ToAggregate()\n\t} else {\n\t\tif p, err := admissionapi.ToPolicy(a.Configuration.Defaults); err != nil {\n\t\t\treturn err\n\t\t} else if !reflect.DeepEqual(p, a.defaultPolicy) {\n\t\t\treturn fmt.Errorf(\"default policy does not match; CompleteConfiguration() was not called before ValidateConfiguration()\")\n\t\t}\n\t}\n\tif a.namespaceMaxPodsToCheck == 0 || a.namespacePodCheckTimeout == 0 {\n\t\treturn fmt.Errorf(\"namespace configuration not set; CompleteConfiguration() was not called before ValidateConfiguration()\")\n\t}\n\tif a.Metrics == nil {\n\t\treturn fmt.Errorf(\"Metrics recorder required\")\n\t}\n\tif a.PodSpecExtractor == nil {\n\t\treturn fmt.Errorf(\"PodSpecExtractor required\")\n\t}\n\tif a.Evaluator == nil {\n\t\treturn fmt.Errorf(\"Evaluator required\")\n\t}\n\tif a.NamespaceGetter == nil {\n\t\treturn fmt.Errorf(\"NamespaceGetter required\")\n\t}\n\tif a.PodLister == nil {\n\t\treturn fmt.Errorf(\"PodLister required\")\n\t}\n\treturn nil\n}","line":{"from":171,"to":203}} {"id":100034932,"name":"Validate","signature":"func (a *Admission) Validate(ctx context.Context, attrs api.Attributes) *admissionv1.AdmissionResponse","file":"staging/src/k8s.io/pod-security-admission/admission/admission.go","code":"// Validate admits an API request.\n// The objects in admission attributes are expected to be external v1 objects that we care about.\n// The returned response may be shared and must not be mutated.\nfunc (a *Admission) Validate(ctx context.Context, attrs api.Attributes) *admissionv1.AdmissionResponse {\n\tvar response *admissionv1.AdmissionResponse\n\tswitch attrs.GetResource().GroupResource() {\n\tcase namespacesResource:\n\t\tresponse = a.ValidateNamespace(ctx, attrs)\n\tcase podsResource:\n\t\tresponse = a.ValidatePod(ctx, attrs)\n\tdefault:\n\t\tresponse = a.ValidatePodController(ctx, attrs)\n\t}\n\treturn response\n}","line":{"from":210,"to":224}} {"id":100034933,"name":"ValidateNamespace","signature":"func (a *Admission) ValidateNamespace(ctx context.Context, attrs api.Attributes) *admissionv1.AdmissionResponse","file":"staging/src/k8s.io/pod-security-admission/admission/admission.go","code":"// ValidateNamespace evaluates a namespace create or update request to ensure the pod security labels are valid,\n// and checks existing pods in the namespace for violations of the new policy when updating the enforce level on a namespace.\n// The returned response may be shared between evaluations and must not be mutated.\nfunc (a *Admission) ValidateNamespace(ctx context.Context, attrs api.Attributes) *admissionv1.AdmissionResponse {\n\t// short-circuit on subresources\n\tif attrs.GetSubresource() != \"\" {\n\t\treturn sharedAllowedResponse\n\t}\n\tobj, err := attrs.GetObject()\n\tif err != nil {\n\t\tklog.ErrorS(err, \"failed to decode object\")\n\t\treturn errorResponse(err, \u0026apierrors.NewBadRequest(\"failed to decode object\").ErrStatus)\n\t}\n\tnamespace, ok := obj.(*corev1.Namespace)\n\tif !ok {\n\t\tklog.InfoS(\"failed to assert namespace type\", \"type\", reflect.TypeOf(obj))\n\t\treturn errorResponse(nil, \u0026apierrors.NewBadRequest(\"failed to decode namespace\").ErrStatus)\n\t}\n\n\tnewPolicy, newErrs := a.PolicyToEvaluate(namespace.Labels)\n\n\tswitch attrs.GetOperation() {\n\tcase admissionv1.Create:\n\t\t// require valid labels on create\n\t\tif len(newErrs) \u003e 0 {\n\t\t\treturn invalidResponse(attrs, newErrs)\n\t\t}\n\t\tif a.exemptNamespace(attrs.GetNamespace()) {\n\t\t\tif warning := a.exemptNamespaceWarning(namespace.Name, newPolicy, namespace.Labels); warning != \"\" {\n\t\t\t\tresponse := allowedResponse()\n\t\t\t\tresponse.Warnings = append(response.Warnings, warning)\n\t\t\t\treturn response\n\t\t\t}\n\t\t}\n\t\treturn sharedAllowedResponse\n\n\tcase admissionv1.Update:\n\t\t// if update, check if policy labels changed\n\t\toldObj, err := attrs.GetOldObject()\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"failed to decode old object\")\n\t\t\treturn errorResponse(err, \u0026apierrors.NewBadRequest(\"failed to decode old object\").ErrStatus)\n\t\t}\n\t\toldNamespace, ok := oldObj.(*corev1.Namespace)\n\t\tif !ok {\n\t\t\tklog.InfoS(\"failed to assert old namespace type\", \"type\", reflect.TypeOf(oldObj))\n\t\t\treturn errorResponse(nil, \u0026apierrors.NewBadRequest(\"failed to decode old namespace\").ErrStatus)\n\t\t}\n\t\toldPolicy, oldErrs := a.PolicyToEvaluate(oldNamespace.Labels)\n\n\t\t// require valid labels on update if they have changed\n\t\tif len(newErrs) \u003e 0 \u0026\u0026 (len(oldErrs) == 0 || !reflect.DeepEqual(newErrs, oldErrs)) {\n\t\t\treturn invalidResponse(attrs, newErrs)\n\t\t}\n\n\t\t// Skip dry-running pods:\n\t\t// * if the enforce policy is unchanged\n\t\t// * if the new enforce policy is privileged\n\t\t// * if the new enforce is the same version and level was relaxed\n\t\t// * for exempt namespaces\n\t\tif newPolicy.Enforce == oldPolicy.Enforce {\n\t\t\treturn sharedAllowedResponse\n\t\t}\n\t\tif newPolicy.Enforce.Level == api.LevelPrivileged {\n\t\t\treturn sharedAllowedResponse\n\t\t}\n\t\tif newPolicy.Enforce.Version == oldPolicy.Enforce.Version \u0026\u0026\n\t\t\tapi.CompareLevels(newPolicy.Enforce.Level, oldPolicy.Enforce.Level) \u003c 1 {\n\t\t\treturn sharedAllowedResponse\n\t\t}\n\t\tif a.exemptNamespace(attrs.GetNamespace()) {\n\t\t\tif warning := a.exemptNamespaceWarning(namespace.Name, newPolicy, namespace.Labels); warning != \"\" {\n\t\t\t\tresponse := allowedResponse()\n\t\t\t\tresponse.Warnings = append(response.Warnings, warning)\n\t\t\t\treturn response\n\t\t\t}\n\t\t\treturn sharedAllowedResponse\n\t\t}\n\t\tresponse := allowedResponse()\n\t\tresponse.Warnings = a.EvaluatePodsInNamespace(ctx, namespace.Name, newPolicy.Enforce)\n\t\treturn response\n\n\tdefault:\n\t\treturn sharedAllowedResponse\n\t}\n}","line":{"from":226,"to":311}} {"id":100034934,"name":"ValidatePod","signature":"func (a *Admission) ValidatePod(ctx context.Context, attrs api.Attributes) *admissionv1.AdmissionResponse","file":"staging/src/k8s.io/pod-security-admission/admission/admission.go","code":"// ValidatePod evaluates a pod create or update request against the effective policy for the namespace.\n// The returned response may be shared between evaluations and must not be mutated.\nfunc (a *Admission) ValidatePod(ctx context.Context, attrs api.Attributes) *admissionv1.AdmissionResponse {\n\t// short-circuit on ignored subresources\n\tif ignoredPodSubresources[attrs.GetSubresource()] {\n\t\treturn sharedAllowedResponse\n\t}\n\t// short-circuit on exempt namespaces and users\n\tif a.exemptNamespace(attrs.GetNamespace()) {\n\t\ta.Metrics.RecordExemption(attrs)\n\t\treturn sharedAllowedByNamespaceExemptionResponse\n\t}\n\n\tif a.exemptUser(attrs.GetUserName()) {\n\t\ta.Metrics.RecordExemption(attrs)\n\t\treturn sharedAllowedByUserExemptionResponse\n\t}\n\n\t// short-circuit on privileged enforce+audit+warn namespaces\n\tnamespace, err := a.NamespaceGetter.GetNamespace(ctx, attrs.GetNamespace())\n\tif err != nil {\n\t\tklog.ErrorS(err, \"failed to fetch pod namespace\", \"namespace\", attrs.GetNamespace())\n\t\ta.Metrics.RecordError(true, attrs)\n\t\treturn errorResponse(err, \u0026apierrors.NewInternalError(fmt.Errorf(\"failed to lookup namespace %q\", attrs.GetNamespace())).ErrStatus)\n\t}\n\tnsPolicy, nsPolicyErrs := a.PolicyToEvaluate(namespace.Labels)\n\tif len(nsPolicyErrs) == 0 \u0026\u0026 nsPolicy.FullyPrivileged() {\n\t\ta.Metrics.RecordEvaluation(metrics.DecisionAllow, nsPolicy.Enforce, metrics.ModeEnforce, attrs)\n\t\treturn sharedAllowedPrivilegedResponse\n\t}\n\n\tobj, err := attrs.GetObject()\n\tif err != nil {\n\t\tklog.ErrorS(err, \"failed to decode object\")\n\t\ta.Metrics.RecordError(true, attrs)\n\t\treturn errorResponse(err, \u0026apierrors.NewBadRequest(\"failed to decode object\").ErrStatus)\n\t}\n\tpod, ok := obj.(*corev1.Pod)\n\tif !ok {\n\t\tklog.InfoS(\"failed to assert pod type\", \"type\", reflect.TypeOf(obj))\n\t\ta.Metrics.RecordError(true, attrs)\n\t\treturn errorResponse(nil, \u0026apierrors.NewBadRequest(\"failed to decode pod\").ErrStatus)\n\t}\n\tif attrs.GetOperation() == admissionv1.Update {\n\t\toldObj, err := attrs.GetOldObject()\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"failed to decode old object\")\n\t\t\ta.Metrics.RecordError(true, attrs)\n\t\t\treturn errorResponse(err, \u0026apierrors.NewBadRequest(\"failed to decode old object\").ErrStatus)\n\t\t}\n\t\toldPod, ok := oldObj.(*corev1.Pod)\n\t\tif !ok {\n\t\t\tklog.InfoS(\"Failed to assert old pod type\", \"type\", reflect.TypeOf(oldObj))\n\t\t\ta.Metrics.RecordError(true, attrs)\n\t\t\treturn errorResponse(nil, \u0026apierrors.NewBadRequest(\"failed to decode old pod\").ErrStatus)\n\t\t}\n\t\tif !isSignificantPodUpdate(pod, oldPod) {\n\t\t\t// Nothing we care about changed, so always allow the update.\n\t\t\treturn sharedAllowedResponse\n\t\t}\n\t}\n\treturn a.EvaluatePod(ctx, nsPolicy, nsPolicyErrs.ToAggregate(), \u0026pod.ObjectMeta, \u0026pod.Spec, attrs, true)\n}","line":{"from":327,"to":389}} {"id":100034935,"name":"ValidatePodController","signature":"func (a *Admission) ValidatePodController(ctx context.Context, attrs api.Attributes) *admissionv1.AdmissionResponse","file":"staging/src/k8s.io/pod-security-admission/admission/admission.go","code":"// ValidatePodController evaluates a pod controller create or update request against the effective policy for the namespace.\n// The returned response may be shared between evaluations and must not be mutated.\nfunc (a *Admission) ValidatePodController(ctx context.Context, attrs api.Attributes) *admissionv1.AdmissionResponse {\n\t// short-circuit on subresources\n\tif attrs.GetSubresource() != \"\" {\n\t\treturn sharedAllowedResponse\n\t}\n\t// short-circuit on exempt namespaces and users\n\tif a.exemptNamespace(attrs.GetNamespace()) {\n\t\ta.Metrics.RecordExemption(attrs)\n\t\treturn sharedAllowedByNamespaceExemptionResponse\n\t}\n\n\tif a.exemptUser(attrs.GetUserName()) {\n\t\ta.Metrics.RecordExemption(attrs)\n\t\treturn sharedAllowedByUserExemptionResponse\n\t}\n\n\t// short-circuit on privileged audit+warn namespaces\n\tnamespace, err := a.NamespaceGetter.GetNamespace(ctx, attrs.GetNamespace())\n\tif err != nil {\n\t\tklog.ErrorS(err, \"failed to fetch pod namespace\", \"namespace\", attrs.GetNamespace())\n\t\ta.Metrics.RecordError(true, attrs)\n\t\tresponse := allowedResponse()\n\t\tresponse.AuditAnnotations = map[string]string{\n\t\t\t\"error\": fmt.Sprintf(\"failed to lookup namespace %q: %v\", attrs.GetNamespace(), err),\n\t\t}\n\t\treturn response\n\t}\n\tnsPolicy, nsPolicyErrs := a.PolicyToEvaluate(namespace.Labels)\n\tif len(nsPolicyErrs) == 0 \u0026\u0026 nsPolicy.Warn.Level == api.LevelPrivileged \u0026\u0026 nsPolicy.Audit.Level == api.LevelPrivileged {\n\t\treturn sharedAllowedResponse\n\t}\n\n\tobj, err := attrs.GetObject()\n\tif err != nil {\n\t\tklog.ErrorS(err, \"failed to decode object\")\n\t\ta.Metrics.RecordError(true, attrs)\n\t\tresponse := allowedResponse()\n\t\tresponse.AuditAnnotations = map[string]string{\n\t\t\t\"error\": fmt.Sprintf(\"failed to decode object: %v\", err),\n\t\t}\n\t\treturn response\n\t}\n\tpodMetadata, podSpec, err := a.PodSpecExtractor.ExtractPodSpec(obj)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"failed to extract pod spec\")\n\t\ta.Metrics.RecordError(true, attrs)\n\t\tresponse := allowedResponse()\n\t\tresponse.AuditAnnotations = map[string]string{\n\t\t\t\"error\": fmt.Sprintf(\"failed to extract pod template: %v\", err),\n\t\t}\n\t\treturn response\n\t}\n\tif podMetadata == nil \u0026\u0026 podSpec == nil {\n\t\t// if a controller with an optional pod spec does not contain a pod spec, skip validation\n\t\treturn sharedAllowedResponse\n\t}\n\treturn a.EvaluatePod(ctx, nsPolicy, nsPolicyErrs.ToAggregate(), podMetadata, podSpec, attrs, false)\n}","line":{"from":391,"to":450}} {"id":100034936,"name":"EvaluatePod","signature":"func (a *Admission) EvaluatePod(ctx context.Context, nsPolicy api.Policy, nsPolicyErr error, podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec, attrs api.Attributes, enforce bool) *admissionv1.AdmissionResponse","file":"staging/src/k8s.io/pod-security-admission/admission/admission.go","code":"// EvaluatePod evaluates the given policy against the given pod(-like) object.\n// The enforce policy is only checked if enforce=true.\n// The returned response may be shared between evaluations and must not be mutated.\nfunc (a *Admission) EvaluatePod(ctx context.Context, nsPolicy api.Policy, nsPolicyErr error, podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec, attrs api.Attributes, enforce bool) *admissionv1.AdmissionResponse {\n\t// short-circuit on exempt runtimeclass\n\tif a.exemptRuntimeClass(podSpec.RuntimeClassName) {\n\t\ta.Metrics.RecordExemption(attrs)\n\t\treturn sharedAllowedByRuntimeClassExemptionResponse\n\t}\n\n\tauditAnnotations := map[string]string{}\n\tif nsPolicyErr != nil {\n\t\tklog.V(2).InfoS(\"failed to parse PodSecurity namespace labels\", \"err\", nsPolicyErr)\n\t\tauditAnnotations[\"error\"] = fmt.Sprintf(\"Failed to parse policy: %v\", nsPolicyErr)\n\t\ta.Metrics.RecordError(false, attrs)\n\t}\n\n\tklogV := klog.V(5)\n\tif klogV.Enabled() {\n\t\tklogV.InfoS(\"PodSecurity evaluation\", \"policy\", fmt.Sprintf(\"%v\", nsPolicy), \"op\", attrs.GetOperation(), \"resource\", attrs.GetResource(), \"namespace\", attrs.GetNamespace(), \"name\", attrs.GetName())\n\t}\n\tcachedResults := make(map[api.LevelVersion]policy.AggregateCheckResult)\n\tresponse := allowedResponse()\n\tif enforce {\n\t\tauditAnnotations[api.EnforcedPolicyAnnotationKey] = nsPolicy.Enforce.String()\n\n\t\tresult := policy.AggregateCheckResults(a.Evaluator.EvaluatePod(nsPolicy.Enforce, podMetadata, podSpec))\n\t\tif !result.Allowed {\n\t\t\tresponse = forbiddenResponse(attrs, fmt.Errorf(\n\t\t\t\t\"violates PodSecurity %q: %s\",\n\t\t\t\tnsPolicy.Enforce.String(),\n\t\t\t\tresult.ForbiddenDetail(),\n\t\t\t))\n\t\t\ta.Metrics.RecordEvaluation(metrics.DecisionDeny, nsPolicy.Enforce, metrics.ModeEnforce, attrs)\n\t\t} else {\n\t\t\ta.Metrics.RecordEvaluation(metrics.DecisionAllow, nsPolicy.Enforce, metrics.ModeEnforce, attrs)\n\t\t}\n\t\tcachedResults[nsPolicy.Enforce] = result\n\t}\n\n\t// reuse previous evaluation if audit level+version is the same as enforce level+version\n\n\tauditResult, ok := cachedResults[nsPolicy.Audit]\n\tif !ok {\n\t\tauditResult = policy.AggregateCheckResults(a.Evaluator.EvaluatePod(nsPolicy.Audit, podMetadata, podSpec))\n\t\tcachedResults[nsPolicy.Audit] = auditResult\n\t}\n\tif !auditResult.Allowed {\n\t\tauditAnnotations[api.AuditViolationsAnnotationKey] = fmt.Sprintf(\n\t\t\t\"would violate PodSecurity %q: %s\",\n\t\t\tnsPolicy.Audit.String(),\n\t\t\tauditResult.ForbiddenDetail(),\n\t\t)\n\t\ta.Metrics.RecordEvaluation(metrics.DecisionDeny, nsPolicy.Audit, metrics.ModeAudit, attrs)\n\t}\n\n\t// avoid adding warnings to a request we're already going to reject with an error\n\tif response.Allowed {\n\t\t// reuse previous evaluation if warn level+version is the same as audit or enforce level+version\n\t\twarnResult, ok := cachedResults[nsPolicy.Warn]\n\t\tif !ok {\n\t\t\twarnResult = policy.AggregateCheckResults(a.Evaluator.EvaluatePod(nsPolicy.Warn, podMetadata, podSpec))\n\t\t}\n\t\tif !warnResult.Allowed {\n\t\t\t// TODO: Craft a better user-facing warning message\n\t\t\tresponse.Warnings = append(response.Warnings, fmt.Sprintf(\n\t\t\t\t\"would violate PodSecurity %q: %s\",\n\t\t\t\tnsPolicy.Warn.String(),\n\t\t\t\twarnResult.ForbiddenDetail(),\n\t\t\t))\n\t\t\ta.Metrics.RecordEvaluation(metrics.DecisionDeny, nsPolicy.Warn, metrics.ModeWarn, attrs)\n\t\t}\n\t}\n\n\tresponse.AuditAnnotations = auditAnnotations\n\treturn response\n}","line":{"from":452,"to":528}} {"id":100034937,"name":"EvaluatePodsInNamespace","signature":"func (a *Admission) EvaluatePodsInNamespace(ctx context.Context, namespace string, enforce api.LevelVersion) []string","file":"staging/src/k8s.io/pod-security-admission/admission/admission.go","code":"func (a *Admission) EvaluatePodsInNamespace(ctx context.Context, namespace string, enforce api.LevelVersion) []string {\n\t// start with the default timeout\n\ttimeout := a.namespacePodCheckTimeout\n\tif deadline, ok := ctx.Deadline(); ok {\n\t\ttimeRemaining := time.Until(deadline) / 2 // don't take more than half the remaining time\n\t\tif timeout \u003e timeRemaining {\n\t\t\ttimeout = timeRemaining\n\t\t}\n\t}\n\tdeadline := time.Now().Add(timeout)\n\tctx, cancel := context.WithDeadline(ctx, deadline)\n\tdefer cancel()\n\n\tpods, err := a.PodLister.ListPods(ctx, namespace)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"failed to list pods\", \"namespace\", namespace)\n\t\treturn []string{\"failed to list pods while checking new PodSecurity enforce level\"}\n\t}\n\n\tvar (\n\t\twarnings []string\n\n\t\tpodWarnings []string\n\t\tpodWarningsToCount = make(map[string]podCount)\n\t\tprioritizedPods = a.prioritizePods(pods)\n\t)\n\n\ttotalPods := len(prioritizedPods)\n\tif len(prioritizedPods) \u003e a.namespaceMaxPodsToCheck {\n\t\tprioritizedPods = prioritizedPods[0:a.namespaceMaxPodsToCheck]\n\t}\n\n\tcheckedPods := len(prioritizedPods)\n\tfor i, pod := range prioritizedPods {\n\t\tr := policy.AggregateCheckResults(a.Evaluator.EvaluatePod(enforce, \u0026pod.ObjectMeta, \u0026pod.Spec))\n\t\tif !r.Allowed {\n\t\t\twarning := r.ForbiddenReason()\n\t\t\tc, seen := podWarningsToCount[warning]\n\t\t\tif !seen {\n\t\t\t\tc.podName = pod.Name\n\t\t\t\tpodWarnings = append(podWarnings, warning)\n\t\t\t} else if pod.Name \u003c c.podName {\n\t\t\t\tc.podName = pod.Name\n\t\t\t}\n\t\t\tc.podCount++\n\t\t\tpodWarningsToCount[warning] = c\n\t\t}\n\t\tif err := ctx.Err(); err != nil { // deadline exceeded or context was cancelled\n\t\t\tcheckedPods = i + 1\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif checkedPods \u003c totalPods {\n\t\twarnings = append(warnings, fmt.Sprintf(\"new PodSecurity enforce level only checked against the first %d of %d existing pods\", checkedPods, totalPods))\n\t}\n\n\tif len(podWarnings) \u003e 0 {\n\t\twarnings = append(warnings, fmt.Sprintf(\"existing pods in namespace %q violate the new PodSecurity enforce level %q\", namespace, enforce.String()))\n\t}\n\n\t// prepend pod names to warnings\n\tdecoratePodWarnings(podWarningsToCount, podWarnings)\n\t// put warnings in a deterministic order\n\tsort.Strings(podWarnings)\n\n\treturn append(warnings, podWarnings...)\n}","line":{"from":539,"to":606}} {"id":100034938,"name":"decoratePodWarnings","signature":"func decoratePodWarnings(podWarningsToCount map[string]podCount, warnings []string)","file":"staging/src/k8s.io/pod-security-admission/admission/admission.go","code":"// prefixes warnings with the pod names related to that warning\nfunc decoratePodWarnings(podWarningsToCount map[string]podCount, warnings []string) {\n\tfor i, warning := range warnings {\n\t\tc := podWarningsToCount[warning]\n\t\tswitch c.podCount {\n\t\tcase 0:\n\t\t\t// unexpected, just leave the warning alone\n\t\tcase 1:\n\t\t\twarnings[i] = fmt.Sprintf(\"%s: %s\", c.podName, warning)\n\t\tcase 2:\n\t\t\twarnings[i] = fmt.Sprintf(\"%s (and 1 other pod): %s\", c.podName, warning)\n\t\tdefault:\n\t\t\twarnings[i] = fmt.Sprintf(\"%s (and %d other pods): %s\", c.podName, c.podCount-1, warning)\n\t\t}\n\t}\n}","line":{"from":608,"to":623}} {"id":100034939,"name":"PolicyToEvaluate","signature":"func (a *Admission) PolicyToEvaluate(labels map[string]string) (api.Policy, field.ErrorList)","file":"staging/src/k8s.io/pod-security-admission/admission/admission.go","code":"func (a *Admission) PolicyToEvaluate(labels map[string]string) (api.Policy, field.ErrorList) {\n\treturn api.PolicyToEvaluate(labels, a.defaultPolicy)\n}","line":{"from":625,"to":627}} {"id":100034940,"name":"isSignificantPodUpdate","signature":"func isSignificantPodUpdate(pod, oldPod *corev1.Pod) bool","file":"staging/src/k8s.io/pod-security-admission/admission/admission.go","code":"// isSignificantPodUpdate determines whether a pod update should trigger a policy evaluation.\n// Relevant mutable pod fields as of 1.21 are image annotations:\n// * https://github.com/kubernetes/kubernetes/blob/release-1.21/pkg/apis/core/validation/validation.go#L3947-L3949\nfunc isSignificantPodUpdate(pod, oldPod *corev1.Pod) bool {\n\t// TODO: invert this logic to only allow specific update types.\n\tif len(pod.Spec.Containers) != len(oldPod.Spec.Containers) {\n\t\treturn true\n\t}\n\tif len(pod.Spec.InitContainers) != len(oldPod.Spec.InitContainers) {\n\t\treturn true\n\t}\n\tfor i := 0; i \u003c len(pod.Spec.Containers); i++ {\n\t\tif isSignificantContainerUpdate(\u0026pod.Spec.Containers[i], \u0026oldPod.Spec.Containers[i]) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor i := 0; i \u003c len(pod.Spec.InitContainers); i++ {\n\t\tif isSignificantContainerUpdate(\u0026pod.Spec.InitContainers[i], \u0026oldPod.Spec.InitContainers[i]) {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor _, c := range pod.Spec.EphemeralContainers {\n\t\tvar oldC *corev1.Container\n\t\tfor i, oc := range oldPod.Spec.EphemeralContainers {\n\t\t\tif oc.Name == c.Name {\n\t\t\t\toldC = (*corev1.Container)(\u0026oldPod.Spec.EphemeralContainers[i].EphemeralContainerCommon)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif oldC == nil {\n\t\t\treturn true // EphemeralContainer added\n\t\t}\n\t\tif isSignificantContainerUpdate((*corev1.Container)(\u0026c.EphemeralContainerCommon), oldC) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":629,"to":666}} {"id":100034941,"name":"isSignificantContainerUpdate","signature":"func isSignificantContainerUpdate(container, oldContainer *corev1.Container) bool","file":"staging/src/k8s.io/pod-security-admission/admission/admission.go","code":"// isSignificantContainerUpdate determines whether a container update should trigger a policy evaluation.\nfunc isSignificantContainerUpdate(container, oldContainer *corev1.Container) bool {\n\treturn container.Image != oldContainer.Image\n}","line":{"from":668,"to":671}} {"id":100034942,"name":"exemptNamespace","signature":"func (a *Admission) exemptNamespace(namespace string) bool","file":"staging/src/k8s.io/pod-security-admission/admission/admission.go","code":"func (a *Admission) exemptNamespace(namespace string) bool {\n\tif len(namespace) == 0 {\n\t\treturn false\n\t}\n\t// TODO: consider optimizing to O(1) lookup\n\treturn containsString(namespace, a.Configuration.Exemptions.Namespaces)\n}","line":{"from":673,"to":679}} {"id":100034943,"name":"exemptUser","signature":"func (a *Admission) exemptUser(username string) bool","file":"staging/src/k8s.io/pod-security-admission/admission/admission.go","code":"func (a *Admission) exemptUser(username string) bool {\n\tif len(username) == 0 {\n\t\treturn false\n\t}\n\t// TODO: consider optimizing to O(1) lookup\n\treturn containsString(username, a.Configuration.Exemptions.Usernames)\n}","line":{"from":680,"to":686}} {"id":100034944,"name":"exemptRuntimeClass","signature":"func (a *Admission) exemptRuntimeClass(runtimeClass *string) bool","file":"staging/src/k8s.io/pod-security-admission/admission/admission.go","code":"func (a *Admission) exemptRuntimeClass(runtimeClass *string) bool {\n\tif runtimeClass == nil || len(*runtimeClass) == 0 {\n\t\treturn false\n\t}\n\t// TODO: consider optimizing to O(1) lookup\n\treturn containsString(*runtimeClass, a.Configuration.Exemptions.RuntimeClasses)\n}","line":{"from":687,"to":693}} {"id":100034945,"name":"prioritizePods","signature":"func (a *Admission) prioritizePods(pods []*corev1.Pod) []*corev1.Pod","file":"staging/src/k8s.io/pod-security-admission/admission/admission.go","code":"// Filter and prioritize pods based on runtimeclass and uniqueness of the controller respectively for evaluation.\n// The input slice is modified in place and should not be reused.\nfunc (a *Admission) prioritizePods(pods []*corev1.Pod) []*corev1.Pod {\n\t// accumulate the list of prioritized pods in-place to avoid double-allocating\n\tprioritizedPods := pods[:0]\n\t// accumulate any additional replicated pods after the first one encountered for a given controller uid\n\tvar duplicateReplicatedPods []*corev1.Pod\n\tevaluatedControllers := make(map[types.UID]bool)\n\tfor _, pod := range pods {\n\t\t// short-circuit on exempt runtimeclass\n\t\tif a.exemptRuntimeClass(pod.Spec.RuntimeClassName) {\n\t\t\tcontinue\n\t\t}\n\t\t// short-circuit if pod from the same controller is evaluated\n\t\tpodOwnerControllerRef := metav1.GetControllerOfNoCopy(pod)\n\t\tif podOwnerControllerRef == nil {\n\t\t\tprioritizedPods = append(prioritizedPods, pod)\n\t\t\tcontinue\n\t\t}\n\t\tif evaluatedControllers[podOwnerControllerRef.UID] {\n\t\t\tduplicateReplicatedPods = append(duplicateReplicatedPods, pod)\n\t\t\tcontinue\n\t\t}\n\t\tprioritizedPods = append(prioritizedPods, pod)\n\t\tevaluatedControllers[podOwnerControllerRef.UID] = true\n\t}\n\treturn append(prioritizedPods, duplicateReplicatedPods...)\n}","line":{"from":695,"to":722}} {"id":100034946,"name":"containsString","signature":"func containsString(needle string, haystack []string) bool","file":"staging/src/k8s.io/pod-security-admission/admission/admission.go","code":"func containsString(needle string, haystack []string) bool {\n\tfor _, s := range haystack {\n\t\tif s == needle {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}","line":{"from":724,"to":731}} {"id":100034947,"name":"exemptNamespaceWarning","signature":"func (a *Admission) exemptNamespaceWarning(exemptNamespace string, policy api.Policy, nsLabels map[string]string) string","file":"staging/src/k8s.io/pod-security-admission/admission/admission.go","code":"// exemptNamespaceWarning returns a non-empty warning message if the exempt namespace has a\n// non-privileged policy and sets pod security labels.\nfunc (a *Admission) exemptNamespaceWarning(exemptNamespace string, policy api.Policy, nsLabels map[string]string) string {\n\tif policy.FullyPrivileged() || policy.Equivalent(\u0026a.defaultPolicy) {\n\t\treturn \"\"\n\t}\n\n\t// Build a compact representation of the policy, only printing non-privileged modes that have\n\t// been explicitly set.\n\tsb := strings.Builder{}\n\t_, hasEnforceLevel := nsLabels[api.EnforceLevelLabel]\n\t_, hasEnforceVersion := nsLabels[api.EnforceVersionLabel]\n\tif policy.Enforce.Level != api.LevelPrivileged \u0026\u0026 (hasEnforceLevel || hasEnforceVersion) {\n\t\tsb.WriteString(\"enforce=\")\n\t\tsb.WriteString(policy.Enforce.String())\n\t}\n\t_, hasAuditLevel := nsLabels[api.AuditLevelLabel]\n\t_, hasAuditVersion := nsLabels[api.AuditVersionLabel]\n\tif policy.Audit.Level != api.LevelPrivileged \u0026\u0026 (hasAuditLevel || hasAuditVersion) {\n\t\tif sb.Len() \u003e 0 {\n\t\t\tsb.WriteString(\", \")\n\t\t}\n\t\tsb.WriteString(\"audit=\")\n\t\tsb.WriteString(policy.Audit.String())\n\t}\n\t_, hasWarnLevel := nsLabels[api.WarnLevelLabel]\n\t_, hasWarnVersion := nsLabels[api.WarnVersionLabel]\n\tif policy.Warn.Level != api.LevelPrivileged \u0026\u0026 (hasWarnLevel || hasWarnVersion) {\n\t\tif sb.Len() \u003e 0 {\n\t\t\tsb.WriteString(\", \")\n\t\t}\n\t\tsb.WriteString(\"warn=\")\n\t\tsb.WriteString(policy.Warn.String())\n\t}\n\n\treturn fmt.Sprintf(\"namespace %q is exempt from Pod Security, and the policy (%s) will be ignored\",\n\t\texemptNamespace, sb.String())\n}","line":{"from":733,"to":770}} {"id":100034948,"name":"ToPolicy","signature":"func ToPolicy(defaults PodSecurityDefaults) (policyapi.Policy, error)","file":"staging/src/k8s.io/pod-security-admission/admission/api/helpers.go","code":"// TODO: deduplicate against PolicyToEvaluate\nfunc ToPolicy(defaults PodSecurityDefaults) (policyapi.Policy, error) {\n\tvar (\n\t\terr error\n\t\terrs []error\n\t\tp policyapi.Policy\n\t)\n\n\tif len(defaults.Enforce) == 0 {\n\t\terrs = appendErr(errs, requiredErr, \"enforce\")\n\t} else {\n\t\tp.Enforce.Level, err = policyapi.ParseLevel(defaults.Enforce)\n\t\terrs = appendErr(errs, err, \"enforce\")\n\t}\n\n\tif len(defaults.EnforceVersion) == 0 {\n\t\terrs = appendErr(errs, requiredErr, \"enforce-version\")\n\t} else {\n\t\tp.Enforce.Version, err = policyapi.ParseVersion(defaults.EnforceVersion)\n\t\terrs = appendErr(errs, err, \"enforce-version\")\n\t}\n\n\tif len(defaults.Audit) == 0 {\n\t\terrs = appendErr(errs, requiredErr, \"audit\")\n\t} else {\n\t\tp.Audit.Level, err = policyapi.ParseLevel(defaults.Audit)\n\t\terrs = appendErr(errs, err, \"audit\")\n\t}\n\n\tif len(defaults.AuditVersion) == 0 {\n\t\terrs = appendErr(errs, requiredErr, \"audit-version\")\n\t} else {\n\t\tp.Audit.Version, err = policyapi.ParseVersion(defaults.AuditVersion)\n\t\terrs = appendErr(errs, err, \"audit-version\")\n\t}\n\n\tif len(defaults.Warn) == 0 {\n\t\terrs = appendErr(errs, requiredErr, \"warn\")\n\t} else {\n\t\tp.Warn.Level, err = policyapi.ParseLevel(defaults.Warn)\n\t\terrs = appendErr(errs, err, \"warn\")\n\t}\n\n\tif len(defaults.WarnVersion) == 0 {\n\t\terrs = appendErr(errs, requiredErr, \"warn-version\")\n\t} else {\n\t\tp.Warn.Version, err = policyapi.ParseVersion(defaults.WarnVersion)\n\t\terrs = appendErr(errs, err, \"warn-version\")\n\t}\n\n\treturn p, errors.NewAggregate(errs)\n}","line":{"from":28,"to":79}} {"id":100034949,"name":"appendErr","signature":"func appendErr(errs []error, err error, field string) []error","file":"staging/src/k8s.io/pod-security-admission/admission/api/helpers.go","code":"// appendErr is a helper function to collect field-specific errors.\nfunc appendErr(errs []error, err error, field string) []error {\n\tif err != nil {\n\t\treturn append(errs, fmt.Errorf(\"%s: %s\", field, err.Error()))\n\t}\n\treturn errs\n}","line":{"from":81,"to":87}} {"id":100034950,"name":"LoadFromFile","signature":"func LoadFromFile(file string) (*api.PodSecurityConfiguration, error)","file":"staging/src/k8s.io/pod-security-admission/admission/api/load/load.go","code":"func LoadFromFile(file string) (*api.PodSecurityConfiguration, error) {\n\tif len(file) == 0 {\n\t\t// no file specified, use default config\n\t\treturn LoadFromData(nil)\n\t}\n\n\t// read from file\n\tdata, err := os.ReadFile(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn LoadFromData(data)\n}","line":{"from":30,"to":42}} {"id":100034951,"name":"LoadFromReader","signature":"func LoadFromReader(reader io.Reader) (*api.PodSecurityConfiguration, error)","file":"staging/src/k8s.io/pod-security-admission/admission/api/load/load.go","code":"func LoadFromReader(reader io.Reader) (*api.PodSecurityConfiguration, error) {\n\tif reader == nil {\n\t\t// no reader specified, use default config\n\t\treturn LoadFromData(nil)\n\t}\n\n\tdata, err := io.ReadAll(reader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn LoadFromData(data)\n}","line":{"from":44,"to":55}} {"id":100034952,"name":"LoadFromData","signature":"func LoadFromData(data []byte) (*api.PodSecurityConfiguration, error)","file":"staging/src/k8s.io/pod-security-admission/admission/api/load/load.go","code":"func LoadFromData(data []byte) (*api.PodSecurityConfiguration, error) {\n\tif len(data) == 0 {\n\t\t// no config provided, return default\n\t\texternalConfig := \u0026apiv1.PodSecurityConfiguration{}\n\t\tscheme.Scheme.Default(externalConfig)\n\t\tinternalConfig := \u0026api.PodSecurityConfiguration{}\n\t\tif err := scheme.Scheme.Convert(externalConfig, internalConfig, nil); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn internalConfig, nil\n\t}\n\n\tdecodedObj, err := runtime.Decode(scheme.Codecs.UniversalDecoder(), data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfiguration, ok := decodedObj.(*api.PodSecurityConfiguration)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"expected PodSecurityConfiguration, got %T\", decodedObj)\n\t}\n\treturn configuration, nil\n}","line":{"from":57,"to":78}} {"id":100034953,"name":"init","signature":"func init()","file":"staging/src/k8s.io/pod-security-admission/admission/api/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addKnownTypes)\n}","line":{"from":38,"to":43}} {"id":100034954,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/pod-security-admission/admission/api/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026PodSecurityConfiguration{},\n\t)\n\treturn nil\n}","line":{"from":45,"to":50}} {"id":100034955,"name":"init","signature":"func init()","file":"staging/src/k8s.io/pod-security-admission/admission/api/scheme/scheme.go","code":"func init() {\n\tAddToScheme(Scheme)\n}","line":{"from":37,"to":39}} {"id":100034956,"name":"AddToScheme","signature":"func AddToScheme(scheme *runtime.Scheme)","file":"staging/src/k8s.io/pod-security-admission/admission/api/scheme/scheme.go","code":"// AddToScheme builds the podsecurity scheme using all known versions of the podsecurity api.\nfunc AddToScheme(scheme *runtime.Scheme) {\n\tutilruntime.Must(podsecurityapi.AddToScheme(scheme))\n\tutilruntime.Must(podsecurityv1alpha1.AddToScheme(scheme))\n\tutilruntime.Must(podsecurityv1beta1.AddToScheme(scheme))\n\tutilruntime.Must(podsecurityv1.AddToScheme(scheme))\n\tutilruntime.Must(scheme.SetVersionPriority(podsecurityv1.SchemeGroupVersion, podsecurityv1beta1.SchemeGroupVersion, podsecurityv1alpha1.SchemeGroupVersion))\n}","line":{"from":41,"to":48}} {"id":100034957,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/pod-security-admission/admission/api/v1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":24,"to":26}} {"id":100034958,"name":"SetDefaults_PodSecurityDefaults","signature":"func SetDefaults_PodSecurityDefaults(obj *PodSecurityDefaults)","file":"staging/src/k8s.io/pod-security-admission/admission/api/v1/defaults.go","code":"func SetDefaults_PodSecurityDefaults(obj *PodSecurityDefaults) {\n\tif len(obj.Enforce) == 0 {\n\t\tobj.Enforce = string(api.LevelPrivileged)\n\t}\n\tif len(obj.Warn) == 0 {\n\t\tobj.Warn = string(api.LevelPrivileged)\n\t}\n\tif len(obj.Audit) == 0 {\n\t\tobj.Audit = string(api.LevelPrivileged)\n\t}\n\n\tif len(obj.EnforceVersion) == 0 {\n\t\tobj.EnforceVersion = string(api.VersionLatest)\n\t}\n\tif len(obj.WarnVersion) == 0 {\n\t\tobj.WarnVersion = string(api.VersionLatest)\n\t}\n\tif len(obj.AuditVersion) == 0 {\n\t\tobj.AuditVersion = string(api.VersionLatest)\n\t}\n}","line":{"from":28,"to":48}} {"id":100034959,"name":"init","signature":"func init()","file":"staging/src/k8s.io/pod-security-admission/admission/api/v1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addKnownTypes, addDefaultingFuncs)\n}","line":{"from":38,"to":43}} {"id":100034960,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/pod-security-admission/admission/api/v1/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026PodSecurityConfiguration{},\n\t)\n\treturn nil\n}","line":{"from":45,"to":50}} {"id":100034961,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/pod-security-admission/admission/api/v1alpha1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":24,"to":26}} {"id":100034962,"name":"SetDefaults_PodSecurityDefaults","signature":"func SetDefaults_PodSecurityDefaults(obj *PodSecurityDefaults)","file":"staging/src/k8s.io/pod-security-admission/admission/api/v1alpha1/defaults.go","code":"func SetDefaults_PodSecurityDefaults(obj *PodSecurityDefaults) {\n\tif len(obj.Enforce) == 0 {\n\t\tobj.Enforce = string(api.LevelPrivileged)\n\t}\n\tif len(obj.Warn) == 0 {\n\t\tobj.Warn = string(api.LevelPrivileged)\n\t}\n\tif len(obj.Audit) == 0 {\n\t\tobj.Audit = string(api.LevelPrivileged)\n\t}\n\n\tif len(obj.EnforceVersion) == 0 {\n\t\tobj.EnforceVersion = string(api.VersionLatest)\n\t}\n\tif len(obj.WarnVersion) == 0 {\n\t\tobj.WarnVersion = string(api.VersionLatest)\n\t}\n\tif len(obj.AuditVersion) == 0 {\n\t\tobj.AuditVersion = string(api.VersionLatest)\n\t}\n}","line":{"from":28,"to":48}} {"id":100034963,"name":"init","signature":"func init()","file":"staging/src/k8s.io/pod-security-admission/admission/api/v1alpha1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addKnownTypes, addDefaultingFuncs)\n}","line":{"from":38,"to":43}} {"id":100034964,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/pod-security-admission/admission/api/v1alpha1/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026PodSecurityConfiguration{},\n\t)\n\treturn nil\n}","line":{"from":45,"to":50}} {"id":100034965,"name":"addDefaultingFuncs","signature":"func addDefaultingFuncs(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/pod-security-admission/admission/api/v1beta1/defaults.go","code":"func addDefaultingFuncs(scheme *runtime.Scheme) error {\n\treturn RegisterDefaults(scheme)\n}","line":{"from":24,"to":26}} {"id":100034966,"name":"SetDefaults_PodSecurityDefaults","signature":"func SetDefaults_PodSecurityDefaults(obj *PodSecurityDefaults)","file":"staging/src/k8s.io/pod-security-admission/admission/api/v1beta1/defaults.go","code":"func SetDefaults_PodSecurityDefaults(obj *PodSecurityDefaults) {\n\tif len(obj.Enforce) == 0 {\n\t\tobj.Enforce = string(api.LevelPrivileged)\n\t}\n\tif len(obj.Warn) == 0 {\n\t\tobj.Warn = string(api.LevelPrivileged)\n\t}\n\tif len(obj.Audit) == 0 {\n\t\tobj.Audit = string(api.LevelPrivileged)\n\t}\n\n\tif len(obj.EnforceVersion) == 0 {\n\t\tobj.EnforceVersion = string(api.VersionLatest)\n\t}\n\tif len(obj.WarnVersion) == 0 {\n\t\tobj.WarnVersion = string(api.VersionLatest)\n\t}\n\tif len(obj.AuditVersion) == 0 {\n\t\tobj.AuditVersion = string(api.VersionLatest)\n\t}\n}","line":{"from":28,"to":48}} {"id":100034967,"name":"init","signature":"func init()","file":"staging/src/k8s.io/pod-security-admission/admission/api/v1beta1/register.go","code":"func init() {\n\t// We only register manually written functions here. The registration of the\n\t// generated functions takes place in the generated files. The separation\n\t// makes the code compile even when the generated files are missing.\n\tlocalSchemeBuilder.Register(addKnownTypes, addDefaultingFuncs)\n}","line":{"from":38,"to":43}} {"id":100034968,"name":"addKnownTypes","signature":"func addKnownTypes(scheme *runtime.Scheme) error","file":"staging/src/k8s.io/pod-security-admission/admission/api/v1beta1/register.go","code":"func addKnownTypes(scheme *runtime.Scheme) error {\n\tscheme.AddKnownTypes(SchemeGroupVersion,\n\t\t\u0026PodSecurityConfiguration{},\n\t)\n\treturn nil\n}","line":{"from":45,"to":50}} {"id":100034969,"name":"ValidatePodSecurityConfiguration","signature":"func ValidatePodSecurityConfiguration(configuration *admissionapi.PodSecurityConfiguration) field.ErrorList","file":"staging/src/k8s.io/pod-security-admission/admission/api/validation/validation.go","code":"// ValidatePodSecurityConfiguration validates a given PodSecurityConfiguration.\nfunc ValidatePodSecurityConfiguration(configuration *admissionapi.PodSecurityConfiguration) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\t// validate defaults\n\tallErrs = append(allErrs, validateLevel(field.NewPath(\"defaults\", \"enforce\"), configuration.Defaults.Enforce)...)\n\tallErrs = append(allErrs, validateVersion(field.NewPath(\"defaults\", \"enforce-version\"), configuration.Defaults.EnforceVersion)...)\n\tallErrs = append(allErrs, validateLevel(field.NewPath(\"defaults\", \"warn\"), configuration.Defaults.Warn)...)\n\tallErrs = append(allErrs, validateVersion(field.NewPath(\"defaults\", \"warn-version\"), configuration.Defaults.WarnVersion)...)\n\tallErrs = append(allErrs, validateLevel(field.NewPath(\"defaults\", \"audit\"), configuration.Defaults.Audit)...)\n\tallErrs = append(allErrs, validateVersion(field.NewPath(\"defaults\", \"audit-version\"), configuration.Defaults.AuditVersion)...)\n\n\t// validate exemptions\n\tallErrs = append(allErrs, validateNamespaces(configuration)...)\n\tallErrs = append(allErrs, validateRuntimeClasses(configuration)...)\n\tallErrs = append(allErrs, validateUsernames(configuration)...)\n\n\treturn allErrs\n}","line":{"from":29,"to":47}} {"id":100034970,"name":"validateLevel","signature":"func validateLevel(p *field.Path, value string) field.ErrorList","file":"staging/src/k8s.io/pod-security-admission/admission/api/validation/validation.go","code":"// validateLevel validates a level\nfunc validateLevel(p *field.Path, value string) field.ErrorList {\n\terrs := field.ErrorList{}\n\t_, err := api.ParseLevel(value)\n\tif err != nil {\n\t\terrs = append(errs, field.Invalid(p, value, err.Error()))\n\t}\n\treturn errs\n}","line":{"from":49,"to":57}} {"id":100034971,"name":"validateVersion","signature":"func validateVersion(p *field.Path, value string) field.ErrorList","file":"staging/src/k8s.io/pod-security-admission/admission/api/validation/validation.go","code":"// validateVersion validates a version\nfunc validateVersion(p *field.Path, value string) field.ErrorList {\n\terrs := field.ErrorList{}\n\t_, err := api.ParseVersion(value)\n\tif err != nil {\n\t\terrs = append(errs, field.Invalid(p, value, err.Error()))\n\t}\n\treturn errs\n}","line":{"from":59,"to":67}} {"id":100034972,"name":"validateNamespaces","signature":"func validateNamespaces(configuration *admissionapi.PodSecurityConfiguration) field.ErrorList","file":"staging/src/k8s.io/pod-security-admission/admission/api/validation/validation.go","code":"func validateNamespaces(configuration *admissionapi.PodSecurityConfiguration) field.ErrorList {\n\terrs := field.ErrorList{}\n\tvalidSet := sets.NewString()\n\tfor i, ns := range configuration.Exemptions.Namespaces {\n\t\terr := machinery.ValidateNamespaceName(ns, false)\n\t\tif len(err) \u003e 0 {\n\t\t\tpath := field.NewPath(\"exemptions\", \"namespaces\").Index(i)\n\t\t\terrs = append(errs, field.Invalid(path, ns, strings.Join(err, \", \")))\n\t\t\tcontinue\n\t\t}\n\t\tif validSet.Has(ns) {\n\t\t\tpath := field.NewPath(\"exemptions\", \"namespaces\").Index(i)\n\t\t\terrs = append(errs, field.Duplicate(path, ns))\n\t\t\tcontinue\n\t\t}\n\t\tvalidSet.Insert(ns)\n\t}\n\treturn errs\n}","line":{"from":69,"to":87}} {"id":100034973,"name":"validateRuntimeClasses","signature":"func validateRuntimeClasses(configuration *admissionapi.PodSecurityConfiguration) field.ErrorList","file":"staging/src/k8s.io/pod-security-admission/admission/api/validation/validation.go","code":"func validateRuntimeClasses(configuration *admissionapi.PodSecurityConfiguration) field.ErrorList {\n\terrs := field.ErrorList{}\n\tvalidSet := sets.NewString()\n\tfor i, rc := range configuration.Exemptions.RuntimeClasses {\n\t\terr := machinery.NameIsDNSSubdomain(rc, false)\n\t\tif len(err) \u003e 0 {\n\t\t\tpath := field.NewPath(\"exemptions\", \"runtimeClasses\").Index(i)\n\t\t\terrs = append(errs, field.Invalid(path, rc, strings.Join(err, \", \")))\n\t\t\tcontinue\n\t\t}\n\t\tif validSet.Has(rc) {\n\t\t\tpath := field.NewPath(\"exemptions\", \"runtimeClasses\").Index(i)\n\t\t\terrs = append(errs, field.Duplicate(path, rc))\n\t\t\tcontinue\n\t\t}\n\t\tvalidSet.Insert(rc)\n\t}\n\treturn errs\n}","line":{"from":89,"to":107}} {"id":100034974,"name":"validateUsernames","signature":"func validateUsernames(configuration *admissionapi.PodSecurityConfiguration) field.ErrorList","file":"staging/src/k8s.io/pod-security-admission/admission/api/validation/validation.go","code":"func validateUsernames(configuration *admissionapi.PodSecurityConfiguration) field.ErrorList {\n\terrs := field.ErrorList{}\n\tvalidSet := sets.NewString()\n\tfor i, uname := range configuration.Exemptions.Usernames {\n\t\tif uname == \"\" {\n\t\t\tpath := field.NewPath(\"exemptions\", \"usernames\").Index(i)\n\t\t\terrs = append(errs, field.Invalid(path, uname, \"username must not be empty\"))\n\t\t\tcontinue\n\t\t}\n\t\tif validSet.Has(uname) {\n\t\t\tpath := field.NewPath(\"exemptions\", \"usernames\").Index(i)\n\t\t\terrs = append(errs, field.Duplicate(path, uname))\n\t\t\tcontinue\n\t\t}\n\t\tvalidSet.Insert(uname)\n\t}\n\n\treturn errs\n}","line":{"from":109,"to":127}} {"id":100034975,"name":"NamespaceGetterFromClient","signature":"func NamespaceGetterFromClient(client kubernetes.Interface) NamespaceGetter","file":"staging/src/k8s.io/pod-security-admission/admission/namespace.go","code":"func NamespaceGetterFromClient(client kubernetes.Interface) NamespaceGetter {\n\treturn \u0026namespaceGetter{client: client}\n}","line":{"from":29,"to":31}} {"id":100034976,"name":"NamespaceGetterFromListerAndClient","signature":"func NamespaceGetterFromListerAndClient(lister corev1listers.NamespaceLister, client kubernetes.Interface) NamespaceGetter","file":"staging/src/k8s.io/pod-security-admission/admission/namespace.go","code":"func NamespaceGetterFromListerAndClient(lister corev1listers.NamespaceLister, client kubernetes.Interface) NamespaceGetter {\n\treturn \u0026namespaceGetter{lister: lister, client: client}\n}","line":{"from":33,"to":35}} {"id":100034977,"name":"GetNamespace","signature":"func (n *namespaceGetter) GetNamespace(ctx context.Context, name string) (namespace *corev1.Namespace, err error)","file":"staging/src/k8s.io/pod-security-admission/admission/namespace.go","code":"func (n *namespaceGetter) GetNamespace(ctx context.Context, name string) (namespace *corev1.Namespace, err error) {\n\tif n.lister != nil {\n\t\tnamespace, err := n.lister.Get(name)\n\t\tif err == nil || !apierrors.IsNotFound(err) {\n\t\t\treturn namespace, err\n\t\t}\n\t}\n\treturn n.client.CoreV1().Namespaces().Get(ctx, name, metav1.GetOptions{})\n}","line":{"from":42,"to":50}} {"id":100034978,"name":"PodListerFromClient","signature":"func PodListerFromClient(client kubernetes.Interface) PodLister","file":"staging/src/k8s.io/pod-security-admission/admission/pods.go","code":"// PodListerFromClient returns a PodLister that does live lists using the provided client.\nfunc PodListerFromClient(client kubernetes.Interface) PodLister {\n\treturn \u0026clientPodLister{client}\n}","line":{"from":29,"to":32}} {"id":100034979,"name":"ListPods","signature":"func (p *clientPodLister) ListPods(ctx context.Context, namespace string) ([]*corev1.Pod, error)","file":"staging/src/k8s.io/pod-security-admission/admission/pods.go","code":"func (p *clientPodLister) ListPods(ctx context.Context, namespace string) ([]*corev1.Pod, error) {\n\tlist, err := p.client.CoreV1().Pods(namespace).List(ctx, metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpods := make([]*corev1.Pod, len(list.Items))\n\tfor i := range list.Items {\n\t\tpods[i] = \u0026list.Items[i]\n\t}\n\treturn pods, nil\n}","line":{"from":38,"to":48}} {"id":100034980,"name":"PodListerFromInformer","signature":"func PodListerFromInformer(lister corev1listers.PodLister) PodLister","file":"staging/src/k8s.io/pod-security-admission/admission/pods.go","code":"// PodListerFromInformer returns a PodLister that does cached lists using the provided lister.\nfunc PodListerFromInformer(lister corev1listers.PodLister) PodLister {\n\treturn \u0026informerPodLister{lister}\n}","line":{"from":50,"to":53}} {"id":100034981,"name":"ListPods","signature":"func (p *informerPodLister) ListPods(ctx context.Context, namespace string) ([]*corev1.Pod, error)","file":"staging/src/k8s.io/pod-security-admission/admission/pods.go","code":"func (p *informerPodLister) ListPods(ctx context.Context, namespace string) ([]*corev1.Pod, error) {\n\treturn p.lister.Pods(namespace).List(labels.Everything())\n}","line":{"from":59,"to":61}} {"id":100034982,"name":"init","signature":"func init()","file":"staging/src/k8s.io/pod-security-admission/admission/response.go","code":"func init() {\n\tsharedAllowedPrivilegedResponse.AuditAnnotations = map[string]string{\n\t\tapi.EnforcedPolicyAnnotationKey: api.LevelVersion{Level: api.LevelPrivileged, Version: api.LatestVersion()}.String(),\n\t}\n\tsharedAllowedByUserExemptionResponse.AuditAnnotations = map[string]string{api.ExemptionReasonAnnotationKey: \"user\"}\n\tsharedAllowedByNamespaceExemptionResponse.AuditAnnotations = map[string]string{api.ExemptionReasonAnnotationKey: \"namespace\"}\n\tsharedAllowedByRuntimeClassExemptionResponse.AuditAnnotations = map[string]string{api.ExemptionReasonAnnotationKey: \"runtimeClass\"}\n}","line":{"from":37,"to":44}} {"id":100034983,"name":"allowedResponse","signature":"func allowedResponse() *admissionv1.AdmissionResponse","file":"staging/src/k8s.io/pod-security-admission/admission/response.go","code":"// allowedResponse is the response used when the admission decision is allow.\nfunc allowedResponse() *admissionv1.AdmissionResponse {\n\treturn \u0026admissionv1.AdmissionResponse{Allowed: true}\n}","line":{"from":46,"to":49}} {"id":100034984,"name":"forbiddenResponse","signature":"func forbiddenResponse(attrs api.Attributes, err error) *admissionv1.AdmissionResponse","file":"staging/src/k8s.io/pod-security-admission/admission/response.go","code":"// forbiddenResponse is the response used when the admission decision is deny for policy violations.\nfunc forbiddenResponse(attrs api.Attributes, err error) *admissionv1.AdmissionResponse {\n\treturn \u0026admissionv1.AdmissionResponse{\n\t\tAllowed: false,\n\t\tResult: \u0026apierrors.NewForbidden(attrs.GetResource().GroupResource(), attrs.GetName(), err).ErrStatus,\n\t}\n}","line":{"from":51,"to":57}} {"id":100034985,"name":"invalidResponse","signature":"func invalidResponse(attrs api.Attributes, fieldErrors field.ErrorList) *admissionv1.AdmissionResponse","file":"staging/src/k8s.io/pod-security-admission/admission/response.go","code":"// invalidResponse is the response used for namespace requests when namespace labels are invalid.\nfunc invalidResponse(attrs api.Attributes, fieldErrors field.ErrorList) *admissionv1.AdmissionResponse {\n\treturn \u0026admissionv1.AdmissionResponse{\n\t\tAllowed: false,\n\t\tResult: \u0026apierrors.NewInvalid(attrs.GetKind().GroupKind(), attrs.GetName(), fieldErrors).ErrStatus,\n\t}\n}","line":{"from":59,"to":65}} {"id":100034986,"name":"errorResponse","signature":"func errorResponse(err error, status *metav1.Status) *admissionv1.AdmissionResponse","file":"staging/src/k8s.io/pod-security-admission/admission/response.go","code":"// errorResponse is the response used to capture generic errors.\nfunc errorResponse(err error, status *metav1.Status) *admissionv1.AdmissionResponse {\n\tvar errDetail string\n\tif err != nil {\n\t\terrDetail = fmt.Sprintf(\"%s: %v\", status.Message, err)\n\t} else {\n\t\terrDetail = status.Message\n\t}\n\treturn \u0026admissionv1.AdmissionResponse{\n\t\tAllowed: false,\n\t\tResult: status,\n\t\tAuditAnnotations: map[string]string{\"error\": errDetail},\n\t}\n}","line":{"from":67,"to":80}} {"id":100034987,"name":"GetName","signature":"func (a *AttributesRecord) GetName() string","file":"staging/src/k8s.io/pod-security-admission/api/attributes.go","code":"func (a *AttributesRecord) GetName() string {\n\treturn a.Name\n}","line":{"from":65,"to":67}} {"id":100034988,"name":"GetNamespace","signature":"func (a *AttributesRecord) GetNamespace() string","file":"staging/src/k8s.io/pod-security-admission/api/attributes.go","code":"func (a *AttributesRecord) GetNamespace() string {\n\treturn a.Namespace\n}","line":{"from":68,"to":70}} {"id":100034989,"name":"GetKind","signature":"func (a *AttributesRecord) GetKind() schema.GroupVersionKind","file":"staging/src/k8s.io/pod-security-admission/api/attributes.go","code":"func (a *AttributesRecord) GetKind() schema.GroupVersionKind {\n\treturn a.Kind\n}","line":{"from":71,"to":73}} {"id":100034990,"name":"GetResource","signature":"func (a *AttributesRecord) GetResource() schema.GroupVersionResource","file":"staging/src/k8s.io/pod-security-admission/api/attributes.go","code":"func (a *AttributesRecord) GetResource() schema.GroupVersionResource {\n\treturn a.Resource\n}","line":{"from":74,"to":76}} {"id":100034991,"name":"GetSubresource","signature":"func (a *AttributesRecord) GetSubresource() string","file":"staging/src/k8s.io/pod-security-admission/api/attributes.go","code":"func (a *AttributesRecord) GetSubresource() string {\n\treturn a.Subresource\n}","line":{"from":77,"to":79}} {"id":100034992,"name":"GetOperation","signature":"func (a *AttributesRecord) GetOperation() admissionv1.Operation","file":"staging/src/k8s.io/pod-security-admission/api/attributes.go","code":"func (a *AttributesRecord) GetOperation() admissionv1.Operation {\n\treturn a.Operation\n}","line":{"from":80,"to":82}} {"id":100034993,"name":"GetUserName","signature":"func (a *AttributesRecord) GetUserName() string","file":"staging/src/k8s.io/pod-security-admission/api/attributes.go","code":"func (a *AttributesRecord) GetUserName() string {\n\treturn a.Username\n}","line":{"from":83,"to":85}} {"id":100034994,"name":"GetObject","signature":"func (a *AttributesRecord) GetObject() (runtime.Object, error)","file":"staging/src/k8s.io/pod-security-admission/api/attributes.go","code":"func (a *AttributesRecord) GetObject() (runtime.Object, error) {\n\treturn a.Object, nil\n}","line":{"from":86,"to":88}} {"id":100034995,"name":"GetOldObject","signature":"func (a *AttributesRecord) GetOldObject() (runtime.Object, error)","file":"staging/src/k8s.io/pod-security-admission/api/attributes.go","code":"func (a *AttributesRecord) GetOldObject() (runtime.Object, error) {\n\treturn a.OldObject, nil\n}","line":{"from":89,"to":91}} {"id":100034996,"name":"RequestAttributes","signature":"func RequestAttributes(request *admissionv1.AdmissionRequest, decoder runtime.Decoder) Attributes","file":"staging/src/k8s.io/pod-security-admission/api/attributes.go","code":"// RequestAttributes adapts an admission.Request to the Attributes interface.\nfunc RequestAttributes(request *admissionv1.AdmissionRequest, decoder runtime.Decoder) Attributes {\n\treturn \u0026attributes{\n\t\tr: request,\n\t\tdecoder: decoder,\n\t}\n}","line":{"from":95,"to":101}} {"id":100034997,"name":"GetName","signature":"func (a *attributes) GetName() string","file":"staging/src/k8s.io/pod-security-admission/api/attributes.go","code":"func (a *attributes) GetName() string {\n\treturn a.r.Name\n}","line":{"from":110,"to":112}} {"id":100034998,"name":"GetNamespace","signature":"func (a *attributes) GetNamespace() string","file":"staging/src/k8s.io/pod-security-admission/api/attributes.go","code":"func (a *attributes) GetNamespace() string {\n\treturn a.r.Namespace\n}","line":{"from":113,"to":115}} {"id":100034999,"name":"GetKind","signature":"func (a *attributes) GetKind() schema.GroupVersionKind","file":"staging/src/k8s.io/pod-security-admission/api/attributes.go","code":"func (a *attributes) GetKind() schema.GroupVersionKind {\n\treturn schema.GroupVersionKind(a.r.Kind)\n}","line":{"from":116,"to":118}} {"id":100035000,"name":"GetResource","signature":"func (a *attributes) GetResource() schema.GroupVersionResource","file":"staging/src/k8s.io/pod-security-admission/api/attributes.go","code":"func (a *attributes) GetResource() schema.GroupVersionResource {\n\treturn schema.GroupVersionResource(a.r.Resource)\n}","line":{"from":119,"to":121}} {"id":100035001,"name":"GetSubresource","signature":"func (a *attributes) GetSubresource() string","file":"staging/src/k8s.io/pod-security-admission/api/attributes.go","code":"func (a *attributes) GetSubresource() string {\n\treturn a.r.RequestSubResource\n}","line":{"from":122,"to":124}} {"id":100035002,"name":"GetOperation","signature":"func (a *attributes) GetOperation() admissionv1.Operation","file":"staging/src/k8s.io/pod-security-admission/api/attributes.go","code":"func (a *attributes) GetOperation() admissionv1.Operation {\n\treturn a.r.Operation\n}","line":{"from":125,"to":127}} {"id":100035003,"name":"GetUserName","signature":"func (a *attributes) GetUserName() string","file":"staging/src/k8s.io/pod-security-admission/api/attributes.go","code":"func (a *attributes) GetUserName() string {\n\treturn a.r.UserInfo.Username\n}","line":{"from":128,"to":130}} {"id":100035004,"name":"GetObject","signature":"func (a *attributes) GetObject() (runtime.Object, error)","file":"staging/src/k8s.io/pod-security-admission/api/attributes.go","code":"func (a *attributes) GetObject() (runtime.Object, error) {\n\treturn a.decode(a.r.Object)\n}","line":{"from":131,"to":133}} {"id":100035005,"name":"GetOldObject","signature":"func (a *attributes) GetOldObject() (runtime.Object, error)","file":"staging/src/k8s.io/pod-security-admission/api/attributes.go","code":"func (a *attributes) GetOldObject() (runtime.Object, error) {\n\treturn a.decode(a.r.OldObject)\n}","line":{"from":134,"to":136}} {"id":100035006,"name":"decode","signature":"func (a *attributes) decode(in runtime.RawExtension) (runtime.Object, error)","file":"staging/src/k8s.io/pod-security-admission/api/attributes.go","code":"func (a *attributes) decode(in runtime.RawExtension) (runtime.Object, error) {\n\tif in.Raw == nil {\n\t\treturn nil, nil\n\t}\n\tgvk := schema.GroupVersionKind(a.r.Kind)\n\tout, _, err := a.decoder.Decode(in.Raw, \u0026gvk, nil)\n\treturn out, err\n}","line":{"from":137,"to":144}} {"id":100035007,"name":"String","signature":"func (v Version) String() string","file":"staging/src/k8s.io/pod-security-admission/api/helpers.go","code":"func (v Version) String() string {\n\tif v.latest {\n\t\treturn \"latest\"\n\t}\n\treturn fmt.Sprintf(\"v%d.%d\", v.major, v.minor)\n}","line":{"from":36,"to":41}} {"id":100035008,"name":"Older","signature":"func (v *Version) Older(other Version) bool","file":"staging/src/k8s.io/pod-security-admission/api/helpers.go","code":"// Older returns true if this version v is older than the other.\nfunc (v *Version) Older(other Version) bool {\n\tif v.latest { // Latest is always consider newer, even than future versions.\n\t\treturn false\n\t}\n\tif other.latest {\n\t\treturn true\n\t}\n\tif v.major != other.major {\n\t\treturn v.major \u003c other.major\n\t}\n\treturn v.minor \u003c other.minor\n}","line":{"from":43,"to":55}} {"id":100035009,"name":"Major","signature":"func (v *Version) Major() int","file":"staging/src/k8s.io/pod-security-admission/api/helpers.go","code":"func (v *Version) Major() int {\n\treturn v.major\n}","line":{"from":57,"to":59}} {"id":100035010,"name":"Minor","signature":"func (v *Version) Minor() int","file":"staging/src/k8s.io/pod-security-admission/api/helpers.go","code":"func (v *Version) Minor() int {\n\treturn v.minor\n}","line":{"from":60,"to":62}} {"id":100035011,"name":"Latest","signature":"func (v *Version) Latest() bool","file":"staging/src/k8s.io/pod-security-admission/api/helpers.go","code":"func (v *Version) Latest() bool {\n\treturn v.latest\n}","line":{"from":63,"to":65}} {"id":100035012,"name":"MajorMinorVersion","signature":"func MajorMinorVersion(major, minor int) Version","file":"staging/src/k8s.io/pod-security-admission/api/helpers.go","code":"func MajorMinorVersion(major, minor int) Version {\n\treturn Version{major: major, minor: minor}\n}","line":{"from":67,"to":69}} {"id":100035013,"name":"GetAPIVersion","signature":"func GetAPIVersion() Version","file":"staging/src/k8s.io/pod-security-admission/api/helpers.go","code":"// GetAPIVersion get the version of apiServer and return the version major and minor\nfunc GetAPIVersion() Version {\n\tvar err error\n\tv := Version{}\n\tapiVersion := version.Get()\n\tmajor, err := strconv.Atoi(apiVersion.Major)\n\tif err != nil {\n\t\treturn v\n\t}\n\t// split the \"normal\" + and - for semver stuff to get the leading minor number\n\tminorString := strings.FieldsFunc(apiVersion.Minor, func(r rune) bool {\n\t\treturn !unicode.IsDigit(r)\n\t})[0]\n\tminor, err := strconv.Atoi(minorString)\n\tif err != nil {\n\t\treturn v\n\t}\n\tv = MajorMinorVersion(major, minor)\n\treturn v\n}","line":{"from":71,"to":90}} {"id":100035014,"name":"LatestVersion","signature":"func LatestVersion() Version","file":"staging/src/k8s.io/pod-security-admission/api/helpers.go","code":"func LatestVersion() Version {\n\treturn Version{latest: true}\n}","line":{"from":92,"to":94}} {"id":100035015,"name":"ParseLevel","signature":"func ParseLevel(level string) (Level, error)","file":"staging/src/k8s.io/pod-security-admission/api/helpers.go","code":"// ParseLevel returns the level that should be evaluated.\n// level must be \"privileged\", \"baseline\", or \"restricted\".\n// if level does not match one of those strings, \"restricted\" and an error is returned.\nfunc ParseLevel(level string) (Level, error) {\n\tswitch Level(level) {\n\tcase LevelPrivileged, LevelBaseline, LevelRestricted:\n\t\treturn Level(level), nil\n\tdefault:\n\t\treturn LevelRestricted, fmt.Errorf(`must be one of %s`, strings.Join(validLevels, \", \"))\n\t}\n}","line":{"from":96,"to":106}} {"id":100035016,"name":"Valid","signature":"func (l *Level) Valid() bool","file":"staging/src/k8s.io/pod-security-admission/api/helpers.go","code":"// Valid checks whether the level l is a valid level.\nfunc (l *Level) Valid() bool {\n\tswitch *l {\n\tcase LevelPrivileged, LevelBaseline, LevelRestricted:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}","line":{"from":108,"to":116}} {"id":100035017,"name":"ParseVersion","signature":"func ParseVersion(version string) (Version, error)","file":"staging/src/k8s.io/pod-security-admission/api/helpers.go","code":"// ParseVersion returns the policy version that should be evaluated.\n// version must be \"latest\" or \"v1.x\".\n// If version does not match one of those patterns, the latest version and an error is returned.\nfunc ParseVersion(version string) (Version, error) {\n\tif version == \"latest\" {\n\t\treturn Version{latest: true}, nil\n\t}\n\tmatch := versionRegexp.FindStringSubmatch(version)\n\tif len(match) != 2 {\n\t\treturn Version{latest: true}, fmt.Errorf(`must be \"latest\" or \"v1.x\"`)\n\t}\n\tversionNumber, err := strconv.Atoi(match[1])\n\tif err != nil || versionNumber \u003c 0 {\n\t\treturn Version{latest: true}, fmt.Errorf(`must be \"latest\" or \"v1.x\"`)\n\t}\n\treturn Version{major: 1, minor: versionNumber}, nil\n}","line":{"from":120,"to":136}} {"id":100035018,"name":"String","signature":"func (lv LevelVersion) String() string","file":"staging/src/k8s.io/pod-security-admission/api/helpers.go","code":"func (lv LevelVersion) String() string {\n\treturn fmt.Sprintf(\"%s:%s\", lv.Level, lv.Version)\n}","line":{"from":143,"to":145}} {"id":100035019,"name":"Equivalent","signature":"func (lv *LevelVersion) Equivalent(other *LevelVersion) bool","file":"staging/src/k8s.io/pod-security-admission/api/helpers.go","code":"// Equivalent determines whether two LevelVersions are functionally equivalent. LevelVersions are\n// considered equivalent if both are privileged, or both levels \u0026 versions are equal.\nfunc (lv *LevelVersion) Equivalent(other *LevelVersion) bool {\n\treturn (lv.Level == LevelPrivileged \u0026\u0026 other.Level == LevelPrivileged) ||\n\t\t(lv.Level == other.Level \u0026\u0026 lv.Version == other.Version)\n}","line":{"from":147,"to":152}} {"id":100035020,"name":"String","signature":"func (p *Policy) String() string","file":"staging/src/k8s.io/pod-security-admission/api/helpers.go","code":"func (p *Policy) String() string {\n\treturn fmt.Sprintf(\"enforce=%#v, audit=%#v, warn=%#v\", p.Enforce, p.Audit, p.Warn)\n}","line":{"from":160,"to":162}} {"id":100035021,"name":"Equivalent","signature":"func (p *Policy) Equivalent(other *Policy) bool","file":"staging/src/k8s.io/pod-security-admission/api/helpers.go","code":"// Equivalent determines whether two policies are functionally equivalent. Policies are considered\n// equivalent if all 3 modes are considered equivalent.\nfunc (p *Policy) Equivalent(other *Policy) bool {\n\treturn p.Enforce.Equivalent(\u0026other.Enforce) \u0026\u0026 p.Audit.Equivalent(\u0026other.Audit) \u0026\u0026 p.Warn.Equivalent(\u0026other.Warn)\n}","line":{"from":164,"to":168}} {"id":100035022,"name":"FullyPrivileged","signature":"func (p *Policy) FullyPrivileged() bool","file":"staging/src/k8s.io/pod-security-admission/api/helpers.go","code":"// FullyPrivileged returns true if all 3 policy modes are privileged.\nfunc (p *Policy) FullyPrivileged() bool {\n\treturn p.Enforce.Level == LevelPrivileged \u0026\u0026\n\t\tp.Audit.Level == LevelPrivileged \u0026\u0026\n\t\tp.Warn.Level == LevelPrivileged\n}","line":{"from":170,"to":175}} {"id":100035023,"name":"PolicyToEvaluate","signature":"func PolicyToEvaluate(labels map[string]string, defaults Policy) (Policy, field.ErrorList)","file":"staging/src/k8s.io/pod-security-admission/api/helpers.go","code":"// PolicyToEvaluate resolves the PodSecurity namespace labels to the policy for that namespace,\n// falling back to the provided defaults when a label is unspecified. A valid policy is always\n// returned, even when an error is returned. If labels cannot be parsed correctly, the values of\n// \"restricted\" and \"latest\" are used for level and version respectively.\nfunc PolicyToEvaluate(labels map[string]string, defaults Policy) (Policy, field.ErrorList) {\n\tvar (\n\t\terr error\n\t\terrs field.ErrorList\n\n\t\tp = defaults\n\n\t\thasEnforceLevel bool\n\t\thasWarnLevel, hasWarnVersion bool\n\t)\n\tif len(labels) == 0 {\n\t\treturn p, nil\n\t}\n\tif level, ok := labels[EnforceLevelLabel]; ok {\n\t\tp.Enforce.Level, err = ParseLevel(level)\n\t\thasEnforceLevel = (err == nil) // Don't default warn in case of error\n\t\terrs = appendErr(errs, err, EnforceLevelLabel, level)\n\t}\n\tif version, ok := labels[EnforceVersionLabel]; ok {\n\t\tp.Enforce.Version, err = ParseVersion(version)\n\t\terrs = appendErr(errs, err, EnforceVersionLabel, version)\n\t}\n\tif level, ok := labels[AuditLevelLabel]; ok {\n\t\tp.Audit.Level, err = ParseLevel(level)\n\t\terrs = appendErr(errs, err, AuditLevelLabel, level)\n\t\tif err != nil {\n\t\t\tp.Audit.Level = LevelPrivileged // Fail open for audit.\n\t\t}\n\t}\n\tif version, ok := labels[AuditVersionLabel]; ok {\n\t\tp.Audit.Version, err = ParseVersion(version)\n\t\terrs = appendErr(errs, err, AuditVersionLabel, version)\n\t}\n\tif level, ok := labels[WarnLevelLabel]; ok {\n\t\thasWarnLevel = true\n\t\tp.Warn.Level, err = ParseLevel(level)\n\t\terrs = appendErr(errs, err, WarnLevelLabel, level)\n\t\tif err != nil {\n\t\t\tp.Warn.Level = LevelPrivileged // Fail open for warn.\n\t\t}\n\t}\n\tif version, ok := labels[WarnVersionLabel]; ok {\n\t\thasWarnVersion = true\n\t\tp.Warn.Version, err = ParseVersion(version)\n\t\terrs = appendErr(errs, err, WarnVersionLabel, version)\n\t}\n\n\t// Default warn to the enforce level when explicitly set to a more restrictive level.\n\tif !hasWarnLevel \u0026\u0026 hasEnforceLevel \u0026\u0026 CompareLevels(p.Enforce.Level, p.Warn.Level) \u003e 0 {\n\t\tp.Warn.Level = p.Enforce.Level\n\t\tif !hasWarnVersion {\n\t\t\tp.Warn.Version = p.Enforce.Version\n\t\t}\n\t}\n\n\treturn p, errs\n}","line":{"from":177,"to":237}} {"id":100035024,"name":"CompareLevels","signature":"func CompareLevels(a, b Level) int","file":"staging/src/k8s.io/pod-security-admission/api/helpers.go","code":"// CompareLevels returns an integer comparing two levels by strictness. The result will be 0 if\n// a==b, -1 if a is less strict than b, and +1 if a is more strict than b.\nfunc CompareLevels(a, b Level) int {\n\tif a == b {\n\t\treturn 0\n\t}\n\tswitch a {\n\tcase LevelPrivileged:\n\t\treturn -1\n\tcase LevelRestricted:\n\t\treturn 1\n\tdefault:\n\t\tif b == LevelPrivileged {\n\t\t\treturn 1\n\t\t} else if b == LevelRestricted {\n\t\t\treturn -1\n\t\t}\n\t}\n\t// This should only happen if both a \u0026 b are invalid levels.\n\treturn 0\n}","line":{"from":239,"to":259}} {"id":100035025,"name":"appendErr","signature":"func appendErr(errs field.ErrorList, err error, label, value string) field.ErrorList","file":"staging/src/k8s.io/pod-security-admission/api/helpers.go","code":"// appendErr is a helper function to collect label-specific errors.\nfunc appendErr(errs field.ErrorList, err error, label, value string) field.ErrorList {\n\tif err != nil {\n\t\treturn append(errs, field.Invalid(labelsPath.Key(label), value, err.Error()))\n\t}\n\treturn errs\n}","line":{"from":263,"to":269}} {"id":100035026,"name":"NewOptions","signature":"func NewOptions() *Options","file":"staging/src/k8s.io/pod-security-admission/cmd/webhook/server/options/options.go","code":"func NewOptions() *Options {\n\tsecureServing := apiserveroptions.NewSecureServingOptions()\n\tsecureServing.ServerCert.PairName = \"webhook\"\n\to := \u0026Options{\n\t\tSecureServing: *secureServing,\n\t\tInsecureServing: apiserveroptions.DeprecatedInsecureServingOptions{},\n\t\tClientQPSLimit: DefaultClientQPSLimit,\n\t\tClientQPSBurst: DefaultClientQPSBurst,\n\t}\n\to.SecureServing.BindPort = DefaultPort\n\to.InsecureServing.BindPort = DefaultInsecurePort\n\treturn o\n}","line":{"from":47,"to":59}} {"id":100035027,"name":"AddFlags","signature":"func (o *Options) AddFlags(fs *pflag.FlagSet)","file":"staging/src/k8s.io/pod-security-admission/cmd/webhook/server/options/options.go","code":"func (o *Options) AddFlags(fs *pflag.FlagSet) {\n\tfs.StringVar(\u0026o.Kubeconfig, \"kubeconfig\", o.Kubeconfig, \"Path to the kubeconfig file specifying how to connect to the API server. Leave empty to use an in-cluster config.\")\n\tfs.StringVar(\u0026o.Config, \"config\", o.Config, \"The path to the PodSecurity configuration file.\")\n\tfs.Float32Var(\u0026o.ClientQPSLimit, \"client-qps-limit\", o.ClientQPSLimit, \"Client QPS limit for throttling requests to the API server.\")\n\tfs.IntVar(\u0026o.ClientQPSBurst, \"client-qps-burst\", o.ClientQPSBurst, \"Client QPS burst limit for throttling requests to the API server.\")\n\n\to.SecureServing.AddFlags(fs)\n\to.InsecureServing.AddFlags(fs)\n}","line":{"from":61,"to":69}} {"id":100035028,"name":"Validate","signature":"func (o *Options) Validate() []error","file":"staging/src/k8s.io/pod-security-admission/cmd/webhook/server/options/options.go","code":"// Validate validates all the required options.\nfunc (o *Options) Validate() []error {\n\tvar errs []error\n\n\terrs = append(errs, o.SecureServing.Validate()...)\n\terrs = append(errs, o.InsecureServing.Validate()...)\n\n\treturn errs\n}","line":{"from":71,"to":79}} {"id":100035029,"name":"init","signature":"func init()","file":"staging/src/k8s.io/pod-security-admission/cmd/webhook/server/scheme.go","code":"func init() {\n\taddToScheme(scheme)\n}","line":{"from":32,"to":34}} {"id":100035030,"name":"addToScheme","signature":"func addToScheme(scheme *runtime.Scheme)","file":"staging/src/k8s.io/pod-security-admission/cmd/webhook/server/scheme.go","code":"func addToScheme(scheme *runtime.Scheme) {\n\tutilruntime.Must(corev1.AddToScheme(scheme))\n\tutilruntime.Must(appsv1.AddToScheme(scheme))\n\tutilruntime.Must(batchv1.AddToScheme(scheme))\n\tutilruntime.Must(admissionv1.AddToScheme(scheme))\n}","line":{"from":36,"to":41}} {"id":100035031,"name":"NewServerCommand","signature":"func NewServerCommand() *cobra.Command","file":"staging/src/k8s.io/pod-security-admission/cmd/webhook/server/server.go","code":"// NewSchedulerCommand creates a *cobra.Command object with default parameters and registryOptions\nfunc NewServerCommand() *cobra.Command {\n\topts := options.NewOptions()\n\n\tcmdName := \"podsecurity-webhook\"\n\tif executable, err := os.Executable(); err == nil {\n\t\tcmdName = filepath.Base(executable)\n\t}\n\tcmd := \u0026cobra.Command{\n\t\tUse: cmdName,\n\t\tLong: `The PodSecurity webhook is a standalone webhook server implementing the Pod\nSecurity Standards.`,\n\t\tRunE: func(cmd *cobra.Command, _ []string) error {\n\t\t\tverflag.PrintAndExitIfRequested()\n\t\t\treturn runServer(cmd.Context(), opts)\n\t\t},\n\t\tArgs: cobra.NoArgs,\n\t}\n\topts.AddFlags(cmd.Flags())\n\tverflag.AddFlags(cmd.Flags())\n\n\treturn cmd\n}","line":{"from":57,"to":79}} {"id":100035032,"name":"runServer","signature":"func runServer(ctx context.Context, opts *options.Options) error","file":"staging/src/k8s.io/pod-security-admission/cmd/webhook/server/server.go","code":"func runServer(ctx context.Context, opts *options.Options) error {\n\tconfig, err := LoadConfig(opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\tserver, err := Setup(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\tgo func() {\n\t\tstopCh := apiserver.SetupSignalHandler()\n\t\t\u003c-stopCh\n\t\tcancel()\n\t}()\n\n\treturn server.Start(ctx)\n}","line":{"from":81,"to":100}} {"id":100035033,"name":"Start","signature":"func (s *Server) Start(ctx context.Context) error","file":"staging/src/k8s.io/pod-security-admission/cmd/webhook/server/server.go","code":"func (s *Server) Start(ctx context.Context) error {\n\ts.informerFactory.Start(ctx.Done())\n\n\tmux := http.NewServeMux()\n\thealthz.InstallHandler(mux, healthz.PingHealthz)\n\thealthz.InstallReadyzHandler(mux, healthz.NewInformerSyncHealthz(s.informerFactory))\n\t// The webhook is stateless, so it's safe to expose everything on the insecure port for\n\t// debugging or proxy purposes. The API server will not connect to an http webhook.\n\tmux.HandleFunc(\"/\", s.HandleValidate)\n\n\t// Serve the metrics.\n\tmux.Handle(\"/metrics\",\n\t\tcompbasemetrics.HandlerFor(s.metricsRegistry, compbasemetrics.HandlerOpts{ErrorHandling: compbasemetrics.ContinueOnError}))\n\n\tif s.insecureServing != nil {\n\t\tif err := s.insecureServing.Serve(mux, 0, ctx.Done()); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to start insecure server: %w\", err)\n\t\t}\n\t}\n\n\tvar shutdownCh \u003c-chan struct{}\n\tvar listenerStoppedCh \u003c-chan struct{}\n\tif s.secureServing != nil {\n\t\tvar err error\n\t\tshutdownCh, listenerStoppedCh, err = s.secureServing.Serve(mux, 0, ctx.Done())\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to start secure server: %w\", err)\n\t\t}\n\t}\n\n\t\u003c-listenerStoppedCh\n\tklog.V(1).InfoS(\"[graceful-termination] HTTP Server has stopped listening\")\n\n\t// Wait for graceful shutdown.\n\t\u003c-shutdownCh\n\tklog.V(1).Info(\"[graceful-termination] HTTP Server is exiting\")\n\n\treturn nil\n}","line":{"from":113,"to":151}} {"id":100035034,"name":"HandleValidate","signature":"func (s *Server) HandleValidate(w http.ResponseWriter, r *http.Request)","file":"staging/src/k8s.io/pod-security-admission/cmd/webhook/server/server.go","code":"func (s *Server) HandleValidate(w http.ResponseWriter, r *http.Request) {\n\tdefer utilruntime.HandleCrash(func(_ interface{}) {\n\t\t// Assume the crash happened before the response was written.\n\t\thttp.Error(w, \"internal server error\", http.StatusInternalServerError)\n\t})\n\n\tvar (\n\t\tbody []byte\n\t\terr error\n\t\tctx = r.Context()\n\t)\n\n\tif timeout, ok, err := parseTimeout(r); err != nil {\n\t\t// Ignore an invalid timeout.\n\t\tklog.V(2).InfoS(\"Invalid timeout\", \"error\", err)\n\t} else if ok {\n\t\tvar cancel context.CancelFunc\n\t\tctx, cancel = context.WithTimeout(ctx, timeout)\n\t\tdefer cancel()\n\t}\n\n\tif r.Body == nil || r.Body == http.NoBody {\n\t\terr = errors.New(\"request body is empty\")\n\t\tklog.ErrorS(err, \"bad request\")\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdefer r.Body.Close()\n\tlimitedReader := \u0026io.LimitedReader{R: r.Body, N: maxRequestSize}\n\tif body, err = ioutil.ReadAll(limitedReader); err != nil {\n\t\tklog.ErrorS(err, \"unable to read the body from the incoming request\")\n\t\thttp.Error(w, \"unable to read the body from the incoming request\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tif limitedReader.N \u003c= 0 {\n\t\tklog.ErrorS(err, \"unable to read the body from the incoming request; limit reached\")\n\t\thttp.Error(w, fmt.Sprintf(\"request entity is too large; limit is %d bytes\", maxRequestSize), http.StatusRequestEntityTooLarge)\n\t\treturn\n\t}\n\n\t// verify the content type is accurate\n\tif contentType := r.Header.Get(\"Content-Type\"); contentType != \"application/json\" {\n\t\terr = fmt.Errorf(\"contentType=%s, expected application/json\", contentType)\n\t\tklog.ErrorS(err, \"unable to process a request with an unknown content type\", \"contentType\", contentType)\n\t\thttp.Error(w, \"unable to process a request with a non-json content type\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tv1AdmissionReviewKind := admissionv1.SchemeGroupVersion.WithKind(\"AdmissionReview\")\n\treviewObject, gvk, err := codecs.UniversalDeserializer().Decode(body, \u0026v1AdmissionReviewKind, nil)\n\tif err != nil {\n\t\tklog.ErrorS(err, \"unable to decode the request\")\n\t\thttp.Error(w, \"unable to decode the request\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tif *gvk != v1AdmissionReviewKind {\n\t\tklog.InfoS(\"Unexpected AdmissionReview kind\", \"kind\", gvk.String())\n\t\thttp.Error(w, fmt.Sprintf(\"unexpected AdmissionReview kind: %s\", gvk.String()), http.StatusBadRequest)\n\t\treturn\n\t}\n\treview, ok := reviewObject.(*admissionv1.AdmissionReview)\n\tif !ok {\n\t\tklog.InfoS(\"Failed admissionv1.AdmissionReview type assertion\")\n\t\thttp.Error(w, \"unexpected AdmissionReview type\", http.StatusBadRequest)\n\t}\n\tklog.V(1).InfoS(\"received request\", \"UID\", review.Request.UID, \"kind\", review.Request.Kind, \"resource\", review.Request.Resource)\n\n\tattributes := api.RequestAttributes(review.Request, codecs.UniversalDeserializer())\n\tresponse := s.delegate.Validate(ctx, attributes)\n\tresponse.UID = review.Request.UID // Response UID must match request UID\n\treview.Response = response\n\twriteResponse(w, review)\n}","line":{"from":153,"to":226}} {"id":100035035,"name":"LoadConfig","signature":"func LoadConfig(opts *options.Options) (*Config, error)","file":"staging/src/k8s.io/pod-security-admission/cmd/webhook/server/server.go","code":"// LoadConfig loads the Config from the Options.\nfunc LoadConfig(opts *options.Options) (*Config, error) {\n\tif errs := opts.Validate(); len(errs) \u003e 0 {\n\t\treturn nil, utilerrors.NewAggregate(errs)\n\t}\n\n\tvar c Config\n\topts.SecureServing.ApplyTo(\u0026c.SecureServing)\n\topts.InsecureServing.ApplyTo(\u0026c.InsecureServing)\n\n\t// Load Kube Client\n\tkubeConfig, err := clientcmd.BuildConfigFromFlags(\"\", opts.Kubeconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkubeConfig.QPS = opts.ClientQPSLimit\n\tkubeConfig.Burst = opts.ClientQPSBurst\n\tc.KubeConfig = restclient.AddUserAgent(kubeConfig, \"podsecurity-webhook\")\n\n\t// Load PodSecurity config\n\tc.PodSecurityConfig, err = podsecurityconfigloader.LoadFromFile(opts.Config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn \u0026c, nil\n}","line":{"from":236,"to":262}} {"id":100035036,"name":"Setup","signature":"func Setup(c *Config) (*Server, error)","file":"staging/src/k8s.io/pod-security-admission/cmd/webhook/server/server.go","code":"// Setup creates an Admission object to handle the admission logic.\nfunc Setup(c *Config) (*Server, error) {\n\ts := \u0026Server{\n\t\tsecureServing: c.SecureServing,\n\t\tinsecureServing: c.InsecureServing,\n\t}\n\n\tif s.secureServing == nil \u0026\u0026 s.insecureServing == nil {\n\t\treturn nil, errors.New(\"no serving info configured\")\n\t}\n\n\tclient, err := clientset.NewForConfig(c.KubeConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.informerFactory = kubeinformers.NewSharedInformerFactory(client, 0 /* no resync */)\n\tnamespaceInformer := s.informerFactory.Core().V1().Namespaces()\n\tnamespaceLister := namespaceInformer.Lister()\n\n\tevaluator, err := policy.NewEvaluator(policy.DefaultChecks())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not create PodSecurityRegistry: %w\", err)\n\t}\n\tmetrics := metrics.NewPrometheusRecorder(api.GetAPIVersion())\n\ts.metricsRegistry = compbasemetrics.NewKubeRegistry()\n\tmetrics.MustRegister(s.metricsRegistry.MustRegister)\n\n\ts.delegate = \u0026admission.Admission{\n\t\tConfiguration: c.PodSecurityConfig,\n\t\tEvaluator: evaluator,\n\t\tMetrics: metrics,\n\t\tPodSpecExtractor: admission.DefaultPodSpecExtractor{},\n\t\tPodLister: admission.PodListerFromClient(client),\n\t\tNamespaceGetter: admission.NamespaceGetterFromListerAndClient(namespaceLister, client),\n\t}\n\n\tif err := s.delegate.CompleteConfiguration(); err != nil {\n\t\treturn nil, fmt.Errorf(\"configuration error: %w\", err)\n\t}\n\tif err := s.delegate.ValidateConfiguration(); err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid configuration: %w\", err)\n\t}\n\n\treturn s, nil\n}","line":{"from":264,"to":308}} {"id":100035037,"name":"writeResponse","signature":"func writeResponse(w http.ResponseWriter, review *admissionv1.AdmissionReview)","file":"staging/src/k8s.io/pod-security-admission/cmd/webhook/server/server.go","code":"func writeResponse(w http.ResponseWriter, review *admissionv1.AdmissionReview) {\n\t// Webhooks should always respond with a 200 HTTP status code when an AdmissionResponse can be sent.\n\t// In an error case, the true status code is captured in the response.result.code\n\tif err := json.NewEncoder(w).Encode(review); err != nil {\n\t\tklog.ErrorS(err, \"Failed to encode response\")\n\t\t// Unable to send an AdmissionResponse, fall back to an HTTP error.\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}","line":{"from":310,"to":318}} {"id":100035038,"name":"parseTimeout","signature":"func parseTimeout(req *http.Request) (time.Duration, bool, error)","file":"staging/src/k8s.io/pod-security-admission/cmd/webhook/server/server.go","code":"// parseTimeout parses the given HTTP request URL and extracts the timeout query parameter\n// value if specified by the user.\n// If a timeout is not specified the function returns false and err is set to nil\n// If the value specified is malformed then the function returns false and err is set\nfunc parseTimeout(req *http.Request) (time.Duration, bool, error) {\n\tvalue := req.URL.Query().Get(\"timeout\")\n\tif value == \"\" {\n\t\treturn 0, false, nil\n\t}\n\n\ttimeout, err := time.ParseDuration(value)\n\tif err != nil {\n\t\treturn 0, false, fmt.Errorf(\"invalid timeout query: %w\", err)\n\t}\n\n\treturn timeout, true, nil\n}","line":{"from":320,"to":336}} {"id":100035039,"name":"main","signature":"func main()","file":"staging/src/k8s.io/pod-security-admission/cmd/webhook/webhook.go","code":"func main() {\n\tcommand := server.NewServerCommand()\n\tcode := cli.Run(command)\n\tos.Exit(code)\n}","line":{"from":27,"to":31}} {"id":100035040,"name":"NewPrometheusRecorder","signature":"func NewPrometheusRecorder(version api.Version) *PrometheusRecorder","file":"staging/src/k8s.io/pod-security-admission/metrics/metrics.go","code":"func NewPrometheusRecorder(version api.Version) *PrometheusRecorder {\n\terrorsCounter := metrics.NewCounterVec(\n\t\t\u0026metrics.CounterOpts{\n\t\t\tName: \"pod_security_errors_total\",\n\t\t\tHelp: \"Number of errors preventing normal evaluation. Non-fatal errors may result in the latest restricted profile being used for evaluation.\",\n\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t},\n\t\t[]string{\"fatal\", \"request_operation\", \"resource\", \"subresource\"},\n\t)\n\n\treturn \u0026PrometheusRecorder{\n\t\tapiVersion: version,\n\t\tevaluationsCounter: newEvaluationsCounter(),\n\t\texemptionsCounter: newExemptionsCounter(),\n\t\terrorsCounter: errorsCounter,\n\t}\n}","line":{"from":59,"to":75}} {"id":100035041,"name":"MustRegister","signature":"func (r *PrometheusRecorder) MustRegister(registerFunc func(...metrics.Registerable))","file":"staging/src/k8s.io/pod-security-admission/metrics/metrics.go","code":"func (r *PrometheusRecorder) MustRegister(registerFunc func(...metrics.Registerable)) {\n\tregisterFunc(r.evaluationsCounter)\n\tregisterFunc(r.exemptionsCounter)\n\tregisterFunc(r.errorsCounter)\n}","line":{"from":77,"to":81}} {"id":100035042,"name":"Reset","signature":"func (r *PrometheusRecorder) Reset()","file":"staging/src/k8s.io/pod-security-admission/metrics/metrics.go","code":"func (r *PrometheusRecorder) Reset() {\n\tr.evaluationsCounter.Reset()\n\tr.exemptionsCounter.Reset()\n\tr.errorsCounter.Reset()\n}","line":{"from":83,"to":87}} {"id":100035043,"name":"RecordEvaluation","signature":"func (r *PrometheusRecorder) RecordEvaluation(decision Decision, policy api.LevelVersion, evalMode Mode, attrs api.Attributes)","file":"staging/src/k8s.io/pod-security-admission/metrics/metrics.go","code":"func (r *PrometheusRecorder) RecordEvaluation(decision Decision, policy api.LevelVersion, evalMode Mode, attrs api.Attributes) {\n\tvar version string\n\tif policy.Version.Latest() || policy.Level == api.LevelPrivileged { // Privileged is always effectively latest.\n\t\tversion = \"latest\"\n\t} else {\n\t\tif !r.apiVersion.Older(policy.Version) {\n\t\t\tversion = policy.Version.String()\n\t\t} else {\n\t\t\tversion = \"future\"\n\t\t}\n\t}\n\n\tr.evaluationsCounter.CachedInc(evaluationsLabels{\n\t\tdecision: string(decision),\n\t\tlevel: string(policy.Level),\n\t\tversion: version,\n\t\tmode: string(evalMode),\n\t\toperation: operationLabel(attrs.GetOperation()),\n\t\tresource: resourceLabel(attrs.GetResource()),\n\t\tsubresource: attrs.GetSubresource(),\n\t})\n}","line":{"from":89,"to":110}} {"id":100035044,"name":"RecordExemption","signature":"func (r *PrometheusRecorder) RecordExemption(attrs api.Attributes)","file":"staging/src/k8s.io/pod-security-admission/metrics/metrics.go","code":"func (r *PrometheusRecorder) RecordExemption(attrs api.Attributes) {\n\tr.exemptionsCounter.CachedInc(exemptionsLabels{\n\t\toperation: operationLabel(attrs.GetOperation()),\n\t\tresource: resourceLabel(attrs.GetResource()),\n\t\tsubresource: attrs.GetSubresource(),\n\t})\n}","line":{"from":112,"to":118}} {"id":100035045,"name":"RecordError","signature":"func (r *PrometheusRecorder) RecordError(fatal bool, attrs api.Attributes)","file":"staging/src/k8s.io/pod-security-admission/metrics/metrics.go","code":"func (r *PrometheusRecorder) RecordError(fatal bool, attrs api.Attributes) {\n\tr.errorsCounter.WithLabelValues(\n\t\tstrconv.FormatBool(fatal),\n\t\toperationLabel(attrs.GetOperation()),\n\t\tresourceLabel(attrs.GetResource()),\n\t\tattrs.GetSubresource(),\n\t).Inc()\n}","line":{"from":120,"to":127}} {"id":100035046,"name":"resourceLabel","signature":"func resourceLabel(resource schema.GroupVersionResource) string","file":"staging/src/k8s.io/pod-security-admission/metrics/metrics.go","code":"func resourceLabel(resource schema.GroupVersionResource) string {\n\tswitch resource.GroupResource() {\n\tcase podResource:\n\t\treturn \"pod\"\n\tcase namespaceResource:\n\t\treturn \"namespace\"\n\tdefault:\n\t\t// Assume any other resource is a valid input to pod-security, and therefore a controller.\n\t\treturn \"controller\"\n\t}\n}","line":{"from":134,"to":144}} {"id":100035047,"name":"operationLabel","signature":"func operationLabel(op admissionv1.Operation) string","file":"staging/src/k8s.io/pod-security-admission/metrics/metrics.go","code":"func operationLabel(op admissionv1.Operation) string {\n\tswitch op {\n\tcase admissionv1.Create:\n\t\treturn \"create\"\n\tcase admissionv1.Update:\n\t\treturn \"update\"\n\tdefault:\n\t\t// This is a slower operation, but never used in the default implementation.\n\t\treturn strings.ToLower(string(op))\n\t}\n}","line":{"from":146,"to":156}} {"id":100035048,"name":"labels","signature":"func (l *evaluationsLabels) labels() []string","file":"staging/src/k8s.io/pod-security-admission/metrics/metrics.go","code":"func (l *evaluationsLabels) labels() []string {\n\treturn []string{l.decision, l.level, l.version, l.mode, l.operation, l.resource, l.subresource}\n}","line":{"from":168,"to":170}} {"id":100035049,"name":"labels","signature":"func (l *exemptionsLabels) labels() []string","file":"staging/src/k8s.io/pod-security-admission/metrics/metrics.go","code":"func (l *exemptionsLabels) labels() []string {\n\treturn []string{l.operation, l.resource, l.subresource}\n}","line":{"from":178,"to":180}} {"id":100035050,"name":"newEvaluationsCounter","signature":"func newEvaluationsCounter() *evaluationsCounter","file":"staging/src/k8s.io/pod-security-admission/metrics/metrics.go","code":"func newEvaluationsCounter() *evaluationsCounter {\n\treturn \u0026evaluationsCounter{\n\t\tCounterVec: metrics.NewCounterVec(\n\t\t\t\u0026metrics.CounterOpts{\n\t\t\t\tName: \"pod_security_evaluations_total\",\n\t\t\t\tHelp: \"Number of policy evaluations that occurred, not counting ignored or exempt requests.\",\n\t\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t\t},\n\t\t\t[]string{\"decision\", \"policy_level\", \"policy_version\", \"mode\", \"request_operation\", \"resource\", \"subresource\"},\n\t\t),\n\t\tcache: make(map[evaluationsLabels]metrics.CounterMetric),\n\t}\n}","line":{"from":189,"to":201}} {"id":100035051,"name":"CachedInc","signature":"func (c *evaluationsCounter) CachedInc(l evaluationsLabels)","file":"staging/src/k8s.io/pod-security-admission/metrics/metrics.go","code":"func (c *evaluationsCounter) CachedInc(l evaluationsLabels) {\n\tc.cacheLock.RLock()\n\tdefer c.cacheLock.RUnlock()\n\n\tif cachedCounter, ok := c.cache[l]; ok {\n\t\tcachedCounter.Inc()\n\t} else {\n\t\tc.CounterVec.WithLabelValues(l.labels()...).Inc()\n\t}\n}","line":{"from":203,"to":212}} {"id":100035052,"name":"Create","signature":"func (c *evaluationsCounter) Create(version *semver.Version) bool","file":"staging/src/k8s.io/pod-security-admission/metrics/metrics.go","code":"func (c *evaluationsCounter) Create(version *semver.Version) bool {\n\tc.cacheLock.Lock()\n\tdefer c.cacheLock.Unlock()\n\tif c.CounterVec.Create(version) {\n\t\tc.populateCache()\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}","line":{"from":214,"to":223}} {"id":100035053,"name":"Reset","signature":"func (c *evaluationsCounter) Reset()","file":"staging/src/k8s.io/pod-security-admission/metrics/metrics.go","code":"func (c *evaluationsCounter) Reset() {\n\tc.cacheLock.Lock()\n\tdefer c.cacheLock.Unlock()\n\tc.CounterVec.Reset()\n\tc.populateCache()\n}","line":{"from":225,"to":230}} {"id":100035054,"name":"populateCache","signature":"func (c *evaluationsCounter) populateCache()","file":"staging/src/k8s.io/pod-security-admission/metrics/metrics.go","code":"func (c *evaluationsCounter) populateCache() {\n\tlabelsToCache := []evaluationsLabels{\n\t\t{decision: \"allow\", level: \"privileged\", version: \"latest\", mode: \"enforce\", operation: \"create\", resource: \"pod\", subresource: \"\"},\n\t\t{decision: \"allow\", level: \"privileged\", version: \"latest\", mode: \"enforce\", operation: \"update\", resource: \"pod\", subresource: \"\"},\n\t}\n\tfor _, l := range labelsToCache {\n\t\tc.cache[l] = c.CounterVec.WithLabelValues(l.labels()...)\n\t}\n}","line":{"from":232,"to":240}} {"id":100035055,"name":"newExemptionsCounter","signature":"func newExemptionsCounter() *exemptionsCounter","file":"staging/src/k8s.io/pod-security-admission/metrics/metrics.go","code":"func newExemptionsCounter() *exemptionsCounter {\n\treturn \u0026exemptionsCounter{\n\t\tCounterVec: metrics.NewCounterVec(\n\t\t\t\u0026metrics.CounterOpts{\n\t\t\t\tName: \"pod_security_exemptions_total\",\n\t\t\t\tHelp: \"Number of exempt requests, not counting ignored or out of scope requests.\",\n\t\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t\t},\n\t\t\t[]string{\"request_operation\", \"resource\", \"subresource\"},\n\t\t),\n\t\tcache: make(map[exemptionsLabels]metrics.CounterMetric),\n\t}\n}","line":{"from":249,"to":261}} {"id":100035056,"name":"CachedInc","signature":"func (c *exemptionsCounter) CachedInc(l exemptionsLabels)","file":"staging/src/k8s.io/pod-security-admission/metrics/metrics.go","code":"func (c *exemptionsCounter) CachedInc(l exemptionsLabels) {\n\tc.cacheLock.RLock()\n\tdefer c.cacheLock.RUnlock()\n\n\tif cachedCounter, ok := c.cache[l]; ok {\n\t\tcachedCounter.Inc()\n\t} else {\n\t\tc.CounterVec.WithLabelValues(l.labels()...).Inc()\n\t}\n}","line":{"from":263,"to":272}} {"id":100035057,"name":"Create","signature":"func (c *exemptionsCounter) Create(version *semver.Version) bool","file":"staging/src/k8s.io/pod-security-admission/metrics/metrics.go","code":"func (c *exemptionsCounter) Create(version *semver.Version) bool {\n\tc.cacheLock.Lock()\n\tdefer c.cacheLock.Unlock()\n\tif c.CounterVec.Create(version) {\n\t\tc.populateCache()\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}","line":{"from":274,"to":283}} {"id":100035058,"name":"Reset","signature":"func (c *exemptionsCounter) Reset()","file":"staging/src/k8s.io/pod-security-admission/metrics/metrics.go","code":"func (c *exemptionsCounter) Reset() {\n\tc.cacheLock.Lock()\n\tdefer c.cacheLock.Unlock()\n\tc.CounterVec.Reset()\n\tc.populateCache()\n}","line":{"from":285,"to":290}} {"id":100035059,"name":"populateCache","signature":"func (c *exemptionsCounter) populateCache()","file":"staging/src/k8s.io/pod-security-admission/metrics/metrics.go","code":"func (c *exemptionsCounter) populateCache() {\n\tlabelsToCache := []exemptionsLabels{\n\t\t{operation: \"create\", resource: \"pod\", subresource: \"\"},\n\t\t{operation: \"update\", resource: \"pod\", subresource: \"\"},\n\t\t{operation: \"create\", resource: \"controller\", subresource: \"\"},\n\t\t{operation: \"update\", resource: \"controller\", subresource: \"\"},\n\t}\n\tfor _, l := range labelsToCache {\n\t\tc.cache[l] = c.CounterVec.WithLabelValues(l.labels()...)\n\t}\n}","line":{"from":292,"to":302}} {"id":100035060,"name":"init","signature":"func init()","file":"staging/src/k8s.io/pod-security-admission/policy/check_allowPrivilegeEscalation.go","code":"func init() {\n\taddCheck(CheckAllowPrivilegeEscalation)\n}","line":{"from":38,"to":40}} {"id":100035061,"name":"CheckAllowPrivilegeEscalation","signature":"func CheckAllowPrivilegeEscalation() Check","file":"staging/src/k8s.io/pod-security-admission/policy/check_allowPrivilegeEscalation.go","code":"// CheckAllowPrivilegeEscalation returns a restricted level check\n// that requires allowPrivilegeEscalation=false in 1.8+\nfunc CheckAllowPrivilegeEscalation() Check {\n\treturn Check{\n\t\tID: \"allowPrivilegeEscalation\",\n\t\tLevel: api.LevelRestricted,\n\t\tVersions: []VersionedCheck{\n\t\t\t{\n\t\t\t\t// Field added in 1.8:\n\t\t\t\t// https://github.com/kubernetes/kubernetes/blob/v1.8.0/staging/src/k8s.io/api/core/v1/types.go#L4797-L4804\n\t\t\t\tMinimumVersion: api.MajorMinorVersion(1, 8),\n\t\t\t\tCheckPod: allowPrivilegeEscalation_1_8,\n\t\t\t},\n\t\t\t{\n\t\t\t\t// Starting 1.25, windows pods would be exempted from this check using pod.spec.os field when set to windows.\n\t\t\t\tMinimumVersion: api.MajorMinorVersion(1, 25),\n\t\t\t\tCheckPod: allowPrivilegeEscalation_1_25,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":42,"to":62}} {"id":100035062,"name":"allowPrivilegeEscalation_1_8","signature":"func allowPrivilegeEscalation_1_8(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult","file":"staging/src/k8s.io/pod-security-admission/policy/check_allowPrivilegeEscalation.go","code":"func allowPrivilegeEscalation_1_8(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {\n\tvar badContainers []string\n\tvisitContainers(podSpec, func(container *corev1.Container) {\n\t\tif container.SecurityContext == nil || container.SecurityContext.AllowPrivilegeEscalation == nil || *container.SecurityContext.AllowPrivilegeEscalation {\n\t\t\tbadContainers = append(badContainers, container.Name)\n\t\t}\n\t})\n\n\tif len(badContainers) \u003e 0 {\n\t\treturn CheckResult{\n\t\t\tAllowed: false,\n\t\t\tForbiddenReason: \"allowPrivilegeEscalation != false\",\n\t\t\tForbiddenDetail: fmt.Sprintf(\n\t\t\t\t\"%s %s must set securityContext.allowPrivilegeEscalation=false\",\n\t\t\t\tpluralize(\"container\", \"containers\", len(badContainers)),\n\t\t\t\tjoinQuote(badContainers),\n\t\t\t),\n\t\t}\n\t}\n\treturn CheckResult{Allowed: true}\n}","line":{"from":64,"to":84}} {"id":100035063,"name":"allowPrivilegeEscalation_1_25","signature":"func allowPrivilegeEscalation_1_25(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult","file":"staging/src/k8s.io/pod-security-admission/policy/check_allowPrivilegeEscalation.go","code":"func allowPrivilegeEscalation_1_25(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {\n\t// Pod API validation would have failed if podOS == Windows and if privilegeEscalation has been set.\n\t// We can admit the Windows pod even if privilegeEscalation has not been set.\n\tif podSpec.OS != nil \u0026\u0026 podSpec.OS.Name == corev1.Windows {\n\t\treturn CheckResult{Allowed: true}\n\t}\n\treturn allowPrivilegeEscalation_1_8(podMetadata, podSpec)\n}","line":{"from":86,"to":93}} {"id":100035064,"name":"init","signature":"func init()","file":"staging/src/k8s.io/pod-security-admission/policy/check_appArmorProfile.go","code":"/*\nOn supported hosts, the 'runtime/default' AppArmor profile is applied by default.\nThe baseline policy should prevent overriding or disabling the default AppArmor\nprofile, or restrict overrides to an allowed set of profiles.\n\n**Restricted Fields:**\nmetadata.annotations['container.apparmor.security.beta.kubernetes.io/*']\n\n**Allowed Values:** 'runtime/default', 'localhost/*', empty, undefined\n*/\nfunc init() {\n\taddCheck(CheckAppArmorProfile)\n}","line":{"from":29,"to":41}} {"id":100035065,"name":"CheckAppArmorProfile","signature":"func CheckAppArmorProfile() Check","file":"staging/src/k8s.io/pod-security-admission/policy/check_appArmorProfile.go","code":"// CheckAppArmorProfile returns a baseline level check\n// that limits the value of AppArmor profiles in 1.0+\nfunc CheckAppArmorProfile() Check {\n\treturn Check{\n\t\tID: \"appArmorProfile\",\n\t\tLevel: api.LevelBaseline,\n\t\tVersions: []VersionedCheck{\n\t\t\t{\n\t\t\t\tMinimumVersion: api.MajorMinorVersion(1, 0),\n\t\t\t\tCheckPod: appArmorProfile_1_0,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":43,"to":56}} {"id":100035066,"name":"allowedProfile","signature":"func allowedProfile(profile string) bool","file":"staging/src/k8s.io/pod-security-admission/policy/check_appArmorProfile.go","code":"func allowedProfile(profile string) bool {\n\treturn len(profile) == 0 ||\n\t\tprofile == corev1.AppArmorBetaProfileRuntimeDefault ||\n\t\tstrings.HasPrefix(profile, corev1.AppArmorBetaProfileNamePrefix)\n}","line":{"from":58,"to":62}} {"id":100035067,"name":"appArmorProfile_1_0","signature":"func appArmorProfile_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult","file":"staging/src/k8s.io/pod-security-admission/policy/check_appArmorProfile.go","code":"func appArmorProfile_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {\n\tvar forbiddenValues []string\n\tfor k, v := range podMetadata.Annotations {\n\t\tif strings.HasPrefix(k, corev1.AppArmorBetaContainerAnnotationKeyPrefix) \u0026\u0026 !allowedProfile(v) {\n\t\t\tforbiddenValues = append(forbiddenValues, fmt.Sprintf(\"%s=%q\", k, v))\n\t\t}\n\t}\n\tif len(forbiddenValues) \u003e 0 {\n\t\tsort.Strings(forbiddenValues)\n\t\treturn CheckResult{\n\t\t\tAllowed: false,\n\t\t\tForbiddenReason: pluralize(\"forbidden AppArmor profile\", \"forbidden AppArmor profiles\", len(forbiddenValues)),\n\t\t\tForbiddenDetail: strings.Join(forbiddenValues, \", \"),\n\t\t}\n\t}\n\n\treturn CheckResult{Allowed: true}\n}","line":{"from":64,"to":81}} {"id":100035068,"name":"init","signature":"func init()","file":"staging/src/k8s.io/pod-security-admission/policy/check_capabilities_baseline.go","code":"func init() {\n\taddCheck(CheckCapabilitiesBaseline)\n}","line":{"from":40,"to":42}} {"id":100035069,"name":"CheckCapabilitiesBaseline","signature":"func CheckCapabilitiesBaseline() Check","file":"staging/src/k8s.io/pod-security-admission/policy/check_capabilities_baseline.go","code":"// CheckCapabilitiesBaseline returns a baseline level check\n// that limits the capabilities that can be added in 1.0+\nfunc CheckCapabilitiesBaseline() Check {\n\treturn Check{\n\t\tID: checkCapabilitiesBaselineID,\n\t\tLevel: api.LevelBaseline,\n\t\tVersions: []VersionedCheck{\n\t\t\t{\n\t\t\t\tMinimumVersion: api.MajorMinorVersion(1, 0),\n\t\t\t\tCheckPod: capabilitiesBaseline_1_0,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":46,"to":59}} {"id":100035070,"name":"capabilitiesBaseline_1_0","signature":"func capabilitiesBaseline_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult","file":"staging/src/k8s.io/pod-security-admission/policy/check_capabilities_baseline.go","code":"func capabilitiesBaseline_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {\n\tvar badContainers []string\n\tnonDefaultCapabilities := sets.NewString()\n\tvisitContainers(podSpec, func(container *corev1.Container) {\n\t\tif container.SecurityContext != nil \u0026\u0026 container.SecurityContext.Capabilities != nil {\n\t\t\tvalid := true\n\t\t\tfor _, c := range container.SecurityContext.Capabilities.Add {\n\t\t\t\tif !capabilities_allowed_1_0.Has(string(c)) {\n\t\t\t\t\tvalid = false\n\t\t\t\t\tnonDefaultCapabilities.Insert(string(c))\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !valid {\n\t\t\t\tbadContainers = append(badContainers, container.Name)\n\t\t\t}\n\t\t}\n\t})\n\n\tif len(badContainers) \u003e 0 {\n\t\treturn CheckResult{\n\t\t\tAllowed: false,\n\t\t\tForbiddenReason: \"non-default capabilities\",\n\t\t\tForbiddenDetail: fmt.Sprintf(\n\t\t\t\t\"%s %s must not include %s in securityContext.capabilities.add\",\n\t\t\t\tpluralize(\"container\", \"containers\", len(badContainers)),\n\t\t\t\tjoinQuote(badContainers),\n\t\t\t\tjoinQuote(nonDefaultCapabilities.List()),\n\t\t\t),\n\t\t}\n\t}\n\treturn CheckResult{Allowed: true}\n}","line":{"from":79,"to":110}} {"id":100035071,"name":"init","signature":"func init()","file":"staging/src/k8s.io/pod-security-admission/policy/check_capabilities_restricted.go","code":"func init() {\n\taddCheck(CheckCapabilitiesRestricted)\n}","line":{"from":53,"to":55}} {"id":100035072,"name":"CheckCapabilitiesRestricted","signature":"func CheckCapabilitiesRestricted() Check","file":"staging/src/k8s.io/pod-security-admission/policy/check_capabilities_restricted.go","code":"// CheckCapabilitiesRestricted returns a restricted level check\n// that ensures ALL capabilities are dropped in 1.22+\nfunc CheckCapabilitiesRestricted() Check {\n\treturn Check{\n\t\tID: \"capabilities_restricted\",\n\t\tLevel: api.LevelRestricted,\n\t\tVersions: []VersionedCheck{\n\t\t\t{\n\t\t\t\tMinimumVersion: api.MajorMinorVersion(1, 22),\n\t\t\t\tCheckPod: capabilitiesRestricted_1_22,\n\t\t\t\tOverrideCheckIDs: []CheckID{checkCapabilitiesBaselineID},\n\t\t\t},\n\t\t\t// Starting 1.25, windows pods would be exempted from this check using pod.spec.os field when set to windows.\n\t\t\t{\n\t\t\t\tMinimumVersion: api.MajorMinorVersion(1, 25),\n\t\t\t\tCheckPod: capabilitiesRestricted_1_25,\n\t\t\t\tOverrideCheckIDs: []CheckID{checkCapabilitiesBaselineID},\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":57,"to":77}} {"id":100035073,"name":"capabilitiesRestricted_1_22","signature":"func capabilitiesRestricted_1_22(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult","file":"staging/src/k8s.io/pod-security-admission/policy/check_capabilities_restricted.go","code":"func capabilitiesRestricted_1_22(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {\n\tvar (\n\t\tcontainersMissingDropAll []string\n\t\tcontainersAddingForbidden []string\n\t\tforbiddenCapabilities = sets.NewString()\n\t)\n\n\tvisitContainers(podSpec, func(container *corev1.Container) {\n\t\tif container.SecurityContext == nil || container.SecurityContext.Capabilities == nil {\n\t\t\tcontainersMissingDropAll = append(containersMissingDropAll, container.Name)\n\t\t\treturn\n\t\t}\n\n\t\tdroppedAll := false\n\t\tfor _, c := range container.SecurityContext.Capabilities.Drop {\n\t\t\tif c == capabilityAll {\n\t\t\t\tdroppedAll = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !droppedAll {\n\t\t\tcontainersMissingDropAll = append(containersMissingDropAll, container.Name)\n\t\t}\n\n\t\taddedForbidden := false\n\t\tfor _, c := range container.SecurityContext.Capabilities.Add {\n\t\t\tif c != capabilityNetBindService {\n\t\t\t\taddedForbidden = true\n\t\t\t\tforbiddenCapabilities.Insert(string(c))\n\t\t\t}\n\t\t}\n\t\tif addedForbidden {\n\t\t\tcontainersAddingForbidden = append(containersAddingForbidden, container.Name)\n\t\t}\n\t})\n\tvar forbiddenDetails []string\n\tif len(containersMissingDropAll) \u003e 0 {\n\t\tforbiddenDetails = append(forbiddenDetails, fmt.Sprintf(\n\t\t\t`%s %s must set securityContext.capabilities.drop=[\"ALL\"]`,\n\t\t\tpluralize(\"container\", \"containers\", len(containersMissingDropAll)),\n\t\t\tjoinQuote(containersMissingDropAll)))\n\t}\n\tif len(containersAddingForbidden) \u003e 0 {\n\t\tforbiddenDetails = append(forbiddenDetails, fmt.Sprintf(\n\t\t\t`%s %s must not include %s in securityContext.capabilities.add`,\n\t\t\tpluralize(\"container\", \"containers\", len(containersAddingForbidden)),\n\t\t\tjoinQuote(containersAddingForbidden),\n\t\t\tjoinQuote(forbiddenCapabilities.List())))\n\t}\n\tif len(forbiddenDetails) \u003e 0 {\n\t\treturn CheckResult{\n\t\t\tAllowed: false,\n\t\t\tForbiddenReason: \"unrestricted capabilities\",\n\t\t\tForbiddenDetail: strings.Join(forbiddenDetails, \"; \"),\n\t\t}\n\t}\n\treturn CheckResult{Allowed: true}\n}","line":{"from":79,"to":136}} {"id":100035074,"name":"capabilitiesRestricted_1_25","signature":"func capabilitiesRestricted_1_25(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult","file":"staging/src/k8s.io/pod-security-admission/policy/check_capabilities_restricted.go","code":"func capabilitiesRestricted_1_25(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {\n\t// Pod API validation would have failed if podOS == Windows and if capabilities have been set.\n\t// We can admit the Windows pod even if capabilities has not been set.\n\tif podSpec.OS != nil \u0026\u0026 podSpec.OS.Name == corev1.Windows {\n\t\treturn CheckResult{Allowed: true}\n\t}\n\treturn capabilitiesRestricted_1_22(podMetadata, podSpec)\n}","line":{"from":138,"to":145}} {"id":100035075,"name":"init","signature":"func init()","file":"staging/src/k8s.io/pod-security-admission/policy/check_hostNamespaces.go","code":"func init() {\n\taddCheck(CheckHostNamespaces)\n}","line":{"from":39,"to":41}} {"id":100035076,"name":"CheckHostNamespaces","signature":"func CheckHostNamespaces() Check","file":"staging/src/k8s.io/pod-security-admission/policy/check_hostNamespaces.go","code":"// CheckHostNamespaces returns a baseline level check\n// that prohibits host namespaces in 1.0+\nfunc CheckHostNamespaces() Check {\n\treturn Check{\n\t\tID: \"hostNamespaces\",\n\t\tLevel: api.LevelBaseline,\n\t\tVersions: []VersionedCheck{\n\t\t\t{\n\t\t\t\tMinimumVersion: api.MajorMinorVersion(1, 0),\n\t\t\t\tCheckPod: hostNamespaces_1_0,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":43,"to":56}} {"id":100035077,"name":"hostNamespaces_1_0","signature":"func hostNamespaces_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult","file":"staging/src/k8s.io/pod-security-admission/policy/check_hostNamespaces.go","code":"func hostNamespaces_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {\n\tvar hostNamespaces []string\n\n\tif podSpec.HostNetwork {\n\t\thostNamespaces = append(hostNamespaces, \"hostNetwork=true\")\n\t}\n\n\tif podSpec.HostPID {\n\t\thostNamespaces = append(hostNamespaces, \"hostPID=true\")\n\t}\n\n\tif podSpec.HostIPC {\n\t\thostNamespaces = append(hostNamespaces, \"hostIPC=true\")\n\t}\n\n\tif len(hostNamespaces) \u003e 0 {\n\t\treturn CheckResult{\n\t\t\tAllowed: false,\n\t\t\tForbiddenReason: \"host namespaces\",\n\t\t\tForbiddenDetail: strings.Join(hostNamespaces, \", \"),\n\t\t}\n\t}\n\n\treturn CheckResult{Allowed: true}\n}","line":{"from":58,"to":82}} {"id":100035078,"name":"init","signature":"func init()","file":"staging/src/k8s.io/pod-security-admission/policy/check_hostPathVolumes.go","code":"func init() {\n\taddCheck(CheckHostPathVolumes)\n}","line":{"from":37,"to":39}} {"id":100035079,"name":"CheckHostPathVolumes","signature":"func CheckHostPathVolumes() Check","file":"staging/src/k8s.io/pod-security-admission/policy/check_hostPathVolumes.go","code":"// CheckHostPathVolumes returns a baseline level check\n// that requires hostPath=undefined/null in 1.0+\nfunc CheckHostPathVolumes() Check {\n\treturn Check{\n\t\tID: checkHostPathVolumesID,\n\t\tLevel: api.LevelBaseline,\n\t\tVersions: []VersionedCheck{\n\t\t\t{\n\t\t\t\tMinimumVersion: api.MajorMinorVersion(1, 0),\n\t\t\t\tCheckPod: hostPathVolumes_1_0,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":43,"to":56}} {"id":100035080,"name":"hostPathVolumes_1_0","signature":"func hostPathVolumes_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult","file":"staging/src/k8s.io/pod-security-admission/policy/check_hostPathVolumes.go","code":"func hostPathVolumes_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {\n\tvar hostVolumes []string\n\n\tfor _, volume := range podSpec.Volumes {\n\t\tif volume.HostPath != nil {\n\t\t\thostVolumes = append(hostVolumes, volume.Name)\n\t\t}\n\t}\n\n\tif len(hostVolumes) \u003e 0 {\n\t\treturn CheckResult{\n\t\t\tAllowed: false,\n\t\t\tForbiddenReason: \"hostPath volumes\",\n\t\t\tForbiddenDetail: fmt.Sprintf(\"%s %s\", pluralize(\"volume\", \"volumes\", len(hostVolumes)), joinQuote(hostVolumes)),\n\t\t}\n\t}\n\n\treturn CheckResult{Allowed: true}\n}","line":{"from":58,"to":76}} {"id":100035081,"name":"init","signature":"func init()","file":"staging/src/k8s.io/pod-security-admission/policy/check_hostPorts.go","code":"func init() {\n\taddCheck(CheckHostPorts)\n}","line":{"from":41,"to":43}} {"id":100035082,"name":"CheckHostPorts","signature":"func CheckHostPorts() Check","file":"staging/src/k8s.io/pod-security-admission/policy/check_hostPorts.go","code":"// CheckHostPorts returns a baseline level check\n// that forbids any host ports in 1.0+\nfunc CheckHostPorts() Check {\n\treturn Check{\n\t\tID: \"hostPorts\",\n\t\tLevel: api.LevelBaseline,\n\t\tVersions: []VersionedCheck{\n\t\t\t{\n\t\t\t\tMinimumVersion: api.MajorMinorVersion(1, 0),\n\t\t\t\tCheckPod: hostPorts_1_0,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":45,"to":58}} {"id":100035083,"name":"hostPorts_1_0","signature":"func hostPorts_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult","file":"staging/src/k8s.io/pod-security-admission/policy/check_hostPorts.go","code":"func hostPorts_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {\n\tvar badContainers []string\n\tforbiddenHostPorts := sets.NewString()\n\tvisitContainers(podSpec, func(container *corev1.Container) {\n\t\tvalid := true\n\t\tfor _, c := range container.Ports {\n\t\t\tif c.HostPort != 0 {\n\t\t\t\tvalid = false\n\t\t\t\tforbiddenHostPorts.Insert(strconv.Itoa(int(c.HostPort)))\n\t\t\t}\n\t\t}\n\t\tif !valid {\n\t\t\tbadContainers = append(badContainers, container.Name)\n\t\t}\n\t})\n\n\tif len(badContainers) \u003e 0 {\n\t\treturn CheckResult{\n\t\t\tAllowed: false,\n\t\t\tForbiddenReason: \"hostPort\",\n\t\t\tForbiddenDetail: fmt.Sprintf(\n\t\t\t\t\"%s %s %s %s %s\",\n\t\t\t\tpluralize(\"container\", \"containers\", len(badContainers)),\n\t\t\t\tjoinQuote(badContainers),\n\t\t\t\tpluralize(\"uses\", \"use\", len(badContainers)),\n\t\t\t\tpluralize(\"hostPort\", \"hostPorts\", len(forbiddenHostPorts)),\n\t\t\t\tstrings.Join(forbiddenHostPorts.List(), \", \"),\n\t\t\t),\n\t\t}\n\t}\n\treturn CheckResult{Allowed: true}\n}","line":{"from":60,"to":91}} {"id":100035084,"name":"init","signature":"func init()","file":"staging/src/k8s.io/pod-security-admission/policy/check_privileged.go","code":"func init() {\n\taddCheck(CheckPrivileged)\n}","line":{"from":37,"to":39}} {"id":100035085,"name":"CheckPrivileged","signature":"func CheckPrivileged() Check","file":"staging/src/k8s.io/pod-security-admission/policy/check_privileged.go","code":"// CheckPrivileged returns a baseline level check\n// that forbids privileged=true in 1.0+\nfunc CheckPrivileged() Check {\n\treturn Check{\n\t\tID: \"privileged\",\n\t\tLevel: api.LevelBaseline,\n\t\tVersions: []VersionedCheck{\n\t\t\t{\n\t\t\t\tMinimumVersion: api.MajorMinorVersion(1, 0),\n\t\t\t\tCheckPod: privileged_1_0,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":41,"to":54}} {"id":100035086,"name":"privileged_1_0","signature":"func privileged_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult","file":"staging/src/k8s.io/pod-security-admission/policy/check_privileged.go","code":"func privileged_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {\n\tvar badContainers []string\n\tvisitContainers(podSpec, func(container *corev1.Container) {\n\t\tif container.SecurityContext != nil \u0026\u0026 container.SecurityContext.Privileged != nil \u0026\u0026 *container.SecurityContext.Privileged {\n\t\t\tbadContainers = append(badContainers, container.Name)\n\t\t}\n\t})\n\tif len(badContainers) \u003e 0 {\n\t\treturn CheckResult{\n\t\t\tAllowed: false,\n\t\t\tForbiddenReason: \"privileged\",\n\t\t\tForbiddenDetail: fmt.Sprintf(\n\t\t\t\t`%s %s must not set securityContext.privileged=true`,\n\t\t\t\tpluralize(\"container\", \"containers\", len(badContainers)),\n\t\t\t\tjoinQuote(badContainers),\n\t\t\t),\n\t\t}\n\t}\n\treturn CheckResult{Allowed: true}\n}","line":{"from":56,"to":75}} {"id":100035087,"name":"init","signature":"func init()","file":"staging/src/k8s.io/pod-security-admission/policy/check_procMount.go","code":"func init() {\n\taddCheck(CheckProcMount)\n}","line":{"from":40,"to":42}} {"id":100035088,"name":"CheckProcMount","signature":"func CheckProcMount() Check","file":"staging/src/k8s.io/pod-security-admission/policy/check_procMount.go","code":"// CheckProcMount returns a baseline level check that restricts\n// setting the value of securityContext.procMount to DefaultProcMount\n// in 1.0+\nfunc CheckProcMount() Check {\n\treturn Check{\n\t\tID: \"procMount\",\n\t\tLevel: api.LevelBaseline,\n\t\tVersions: []VersionedCheck{\n\t\t\t{\n\t\t\t\tMinimumVersion: api.MajorMinorVersion(1, 0),\n\t\t\t\tCheckPod: procMount_1_0,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":44,"to":58}} {"id":100035089,"name":"procMount_1_0","signature":"func procMount_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult","file":"staging/src/k8s.io/pod-security-admission/policy/check_procMount.go","code":"func procMount_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {\n\tvar badContainers []string\n\tforbiddenProcMountTypes := sets.NewString()\n\tvisitContainers(podSpec, func(container *corev1.Container) {\n\t\t// allow if the security context is nil.\n\t\tif container.SecurityContext == nil {\n\t\t\treturn\n\t\t}\n\t\t// allow if proc mount is not set.\n\t\tif container.SecurityContext.ProcMount == nil {\n\t\t\treturn\n\t\t}\n\t\t// check if the value of the proc mount type is valid.\n\t\tif *container.SecurityContext.ProcMount != corev1.DefaultProcMount {\n\t\t\tbadContainers = append(badContainers, container.Name)\n\t\t\tforbiddenProcMountTypes.Insert(string(*container.SecurityContext.ProcMount))\n\t\t}\n\t})\n\tif len(badContainers) \u003e 0 {\n\t\treturn CheckResult{\n\t\t\tAllowed: false,\n\t\t\tForbiddenReason: \"procMount\",\n\t\t\tForbiddenDetail: fmt.Sprintf(\n\t\t\t\t\"%s %s must not set securityContext.procMount to %s\",\n\t\t\t\tpluralize(\"container\", \"containers\", len(badContainers)),\n\t\t\t\tjoinQuote(badContainers),\n\t\t\t\tjoinQuote(forbiddenProcMountTypes.List()),\n\t\t\t),\n\t\t}\n\t}\n\treturn CheckResult{Allowed: true}\n}","line":{"from":60,"to":91}} {"id":100035090,"name":"init","signature":"func init()","file":"staging/src/k8s.io/pod-security-admission/policy/check_restrictedVolumes.go","code":"func init() {\n\taddCheck(CheckRestrictedVolumes)\n}","line":{"from":67,"to":69}} {"id":100035091,"name":"CheckRestrictedVolumes","signature":"func CheckRestrictedVolumes() Check","file":"staging/src/k8s.io/pod-security-admission/policy/check_restrictedVolumes.go","code":"// CheckRestrictedVolumes returns a restricted level check\n// that limits usage of specific volume types in 1.0+\nfunc CheckRestrictedVolumes() Check {\n\treturn Check{\n\t\tID: \"restrictedVolumes\",\n\t\tLevel: api.LevelRestricted,\n\t\tVersions: []VersionedCheck{\n\t\t\t{\n\t\t\t\tMinimumVersion: api.MajorMinorVersion(1, 0),\n\t\t\t\tCheckPod: restrictedVolumes_1_0,\n\t\t\t\tOverrideCheckIDs: []CheckID{checkHostPathVolumesID},\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":71,"to":85}} {"id":100035092,"name":"restrictedVolumes_1_0","signature":"func restrictedVolumes_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult","file":"staging/src/k8s.io/pod-security-admission/policy/check_restrictedVolumes.go","code":"func restrictedVolumes_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {\n\tvar badVolumes []string\n\tbadVolumeTypes := sets.NewString()\n\n\tfor _, volume := range podSpec.Volumes {\n\t\tswitch {\n\t\tcase volume.ConfigMap != nil,\n\t\t\tvolume.CSI != nil,\n\t\t\tvolume.DownwardAPI != nil,\n\t\t\tvolume.EmptyDir != nil,\n\t\t\tvolume.Ephemeral != nil,\n\t\t\tvolume.PersistentVolumeClaim != nil,\n\t\t\tvolume.Projected != nil,\n\t\t\tvolume.Secret != nil:\n\t\t\tcontinue\n\n\t\tdefault:\n\t\t\tbadVolumes = append(badVolumes, volume.Name)\n\n\t\t\tswitch {\n\t\t\tcase volume.HostPath != nil:\n\t\t\t\tbadVolumeTypes.Insert(\"hostPath\")\n\t\t\tcase volume.GCEPersistentDisk != nil:\n\t\t\t\tbadVolumeTypes.Insert(\"gcePersistentDisk\")\n\t\t\tcase volume.AWSElasticBlockStore != nil:\n\t\t\t\tbadVolumeTypes.Insert(\"awsElasticBlockStore\")\n\t\t\tcase volume.GitRepo != nil:\n\t\t\t\tbadVolumeTypes.Insert(\"gitRepo\")\n\t\t\tcase volume.NFS != nil:\n\t\t\t\tbadVolumeTypes.Insert(\"nfs\")\n\t\t\tcase volume.ISCSI != nil:\n\t\t\t\tbadVolumeTypes.Insert(\"iscsi\")\n\t\t\tcase volume.Glusterfs != nil:\n\t\t\t\tbadVolumeTypes.Insert(\"glusterfs\")\n\t\t\tcase volume.RBD != nil:\n\t\t\t\tbadVolumeTypes.Insert(\"rbd\")\n\t\t\tcase volume.FlexVolume != nil:\n\t\t\t\tbadVolumeTypes.Insert(\"flexVolume\")\n\t\t\tcase volume.Cinder != nil:\n\t\t\t\tbadVolumeTypes.Insert(\"cinder\")\n\t\t\tcase volume.CephFS != nil:\n\t\t\t\tbadVolumeTypes.Insert(\"cephfs\")\n\t\t\tcase volume.Flocker != nil:\n\t\t\t\tbadVolumeTypes.Insert(\"flocker\")\n\t\t\tcase volume.FC != nil:\n\t\t\t\tbadVolumeTypes.Insert(\"fc\")\n\t\t\tcase volume.AzureFile != nil:\n\t\t\t\tbadVolumeTypes.Insert(\"azureFile\")\n\t\t\tcase volume.VsphereVolume != nil:\n\t\t\t\tbadVolumeTypes.Insert(\"vsphereVolume\")\n\t\t\tcase volume.Quobyte != nil:\n\t\t\t\tbadVolumeTypes.Insert(\"quobyte\")\n\t\t\tcase volume.AzureDisk != nil:\n\t\t\t\tbadVolumeTypes.Insert(\"azureDisk\")\n\t\t\tcase volume.PhotonPersistentDisk != nil:\n\t\t\t\tbadVolumeTypes.Insert(\"photonPersistentDisk\")\n\t\t\tcase volume.PortworxVolume != nil:\n\t\t\t\tbadVolumeTypes.Insert(\"portworxVolume\")\n\t\t\tcase volume.ScaleIO != nil:\n\t\t\t\tbadVolumeTypes.Insert(\"scaleIO\")\n\t\t\tcase volume.StorageOS != nil:\n\t\t\t\tbadVolumeTypes.Insert(\"storageos\")\n\t\t\tdefault:\n\t\t\t\tbadVolumeTypes.Insert(\"unknown\")\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(badVolumes) \u003e 0 {\n\t\treturn CheckResult{\n\t\t\tAllowed: false,\n\t\t\tForbiddenReason: \"restricted volume types\",\n\t\t\tForbiddenDetail: fmt.Sprintf(\n\t\t\t\t\"%s %s %s %s %s\",\n\t\t\t\tpluralize(\"volume\", \"volumes\", len(badVolumes)),\n\t\t\t\tjoinQuote(badVolumes),\n\t\t\t\tpluralize(\"uses\", \"use\", len(badVolumes)),\n\t\t\t\tpluralize(\"restricted volume type\", \"restricted volume types\", len(badVolumeTypes)),\n\t\t\t\tjoinQuote(badVolumeTypes.List()),\n\t\t\t),\n\t\t}\n\t}\n\n\treturn CheckResult{Allowed: true}\n}","line":{"from":87,"to":171}} {"id":100035093,"name":"init","signature":"func init()","file":"staging/src/k8s.io/pod-security-admission/policy/check_runAsNonRoot.go","code":"func init() {\n\taddCheck(CheckRunAsNonRoot)\n}","line":{"from":42,"to":44}} {"id":100035094,"name":"CheckRunAsNonRoot","signature":"func CheckRunAsNonRoot() Check","file":"staging/src/k8s.io/pod-security-admission/policy/check_runAsNonRoot.go","code":"// CheckRunAsNonRoot returns a restricted level check\n// that requires runAsNonRoot=true in 1.0+\nfunc CheckRunAsNonRoot() Check {\n\treturn Check{\n\t\tID: \"runAsNonRoot\",\n\t\tLevel: api.LevelRestricted,\n\t\tVersions: []VersionedCheck{\n\t\t\t{\n\t\t\t\tMinimumVersion: api.MajorMinorVersion(1, 0),\n\t\t\t\tCheckPod: runAsNonRoot_1_0,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":46,"to":59}} {"id":100035095,"name":"runAsNonRoot_1_0","signature":"func runAsNonRoot_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult","file":"staging/src/k8s.io/pod-security-admission/policy/check_runAsNonRoot.go","code":"func runAsNonRoot_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {\n\t// things that explicitly set runAsNonRoot=false\n\tvar badSetters []string\n\n\tpodRunAsNonRoot := false\n\tif podSpec.SecurityContext != nil \u0026\u0026 podSpec.SecurityContext.RunAsNonRoot != nil {\n\t\tif !*podSpec.SecurityContext.RunAsNonRoot {\n\t\t\tbadSetters = append(badSetters, \"pod\")\n\t\t} else {\n\t\t\tpodRunAsNonRoot = true\n\t\t}\n\t}\n\n\t// containers that explicitly set runAsNonRoot=false\n\tvar explicitlyBadContainers []string\n\t// containers that didn't set runAsNonRoot and aren't caught by a pod-level runAsNonRoot=true\n\tvar implicitlyBadContainers []string\n\n\tvisitContainers(podSpec, func(container *corev1.Container) {\n\t\tif container.SecurityContext != nil \u0026\u0026 container.SecurityContext.RunAsNonRoot != nil {\n\t\t\t// container explicitly set runAsNonRoot\n\t\t\tif !*container.SecurityContext.RunAsNonRoot {\n\t\t\t\t// container explicitly set runAsNonRoot to a bad value\n\t\t\t\texplicitlyBadContainers = append(explicitlyBadContainers, container.Name)\n\t\t\t}\n\t\t} else {\n\t\t\t// container did not explicitly set runAsNonRoot\n\t\t\tif !podRunAsNonRoot {\n\t\t\t\t// no pod-level runAsNonRoot=true, so this container implicitly has a bad value\n\t\t\t\timplicitlyBadContainers = append(implicitlyBadContainers, container.Name)\n\t\t\t}\n\t\t}\n\t})\n\n\tif len(explicitlyBadContainers) \u003e 0 {\n\t\tbadSetters = append(\n\t\t\tbadSetters,\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"%s %s\",\n\t\t\t\tpluralize(\"container\", \"containers\", len(explicitlyBadContainers)),\n\t\t\t\tjoinQuote(explicitlyBadContainers),\n\t\t\t),\n\t\t)\n\t}\n\t// pod or containers explicitly set runAsNonRoot=false\n\tif len(badSetters) \u003e 0 {\n\t\treturn CheckResult{\n\t\t\tAllowed: false,\n\t\t\tForbiddenReason: \"runAsNonRoot != true\",\n\t\t\tForbiddenDetail: fmt.Sprintf(\"%s must not set securityContext.runAsNonRoot=false\", strings.Join(badSetters, \" and \")),\n\t\t}\n\t}\n\n\t// pod didn't set runAsNonRoot and not all containers opted into runAsNonRoot\n\tif len(implicitlyBadContainers) \u003e 0 {\n\t\treturn CheckResult{\n\t\t\tAllowed: false,\n\t\t\tForbiddenReason: \"runAsNonRoot != true\",\n\t\t\tForbiddenDetail: fmt.Sprintf(\n\t\t\t\t\"pod or %s %s must set securityContext.runAsNonRoot=true\",\n\t\t\t\tpluralize(\"container\", \"containers\", len(implicitlyBadContainers)),\n\t\t\t\tjoinQuote(implicitlyBadContainers),\n\t\t\t),\n\t\t}\n\t}\n\n\treturn CheckResult{Allowed: true}\n}","line":{"from":61,"to":128}} {"id":100035096,"name":"init","signature":"func init()","file":"staging/src/k8s.io/pod-security-admission/policy/check_runAsUser.go","code":"func init() {\n\taddCheck(CheckRunAsUser)\n}","line":{"from":43,"to":45}} {"id":100035097,"name":"CheckRunAsUser","signature":"func CheckRunAsUser() Check","file":"staging/src/k8s.io/pod-security-admission/policy/check_runAsUser.go","code":"// CheckRunAsUser returns a restricted level check\n// that forbides runAsUser=0 in 1.23+\nfunc CheckRunAsUser() Check {\n\treturn Check{\n\t\tID: \"runAsUser\",\n\t\tLevel: api.LevelRestricted,\n\t\tVersions: []VersionedCheck{\n\t\t\t{\n\t\t\t\tMinimumVersion: api.MajorMinorVersion(1, 23),\n\t\t\t\tCheckPod: runAsUser_1_23,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":47,"to":60}} {"id":100035098,"name":"runAsUser_1_23","signature":"func runAsUser_1_23(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult","file":"staging/src/k8s.io/pod-security-admission/policy/check_runAsUser.go","code":"func runAsUser_1_23(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {\n\t// things that explicitly set runAsUser=0\n\tvar badSetters []string\n\n\tif podSpec.SecurityContext != nil \u0026\u0026 podSpec.SecurityContext.RunAsUser != nil \u0026\u0026 *podSpec.SecurityContext.RunAsUser == 0 {\n\t\tbadSetters = append(badSetters, \"pod\")\n\t}\n\n\t// containers that explicitly set runAsUser=0\n\tvar explicitlyBadContainers []string\n\n\tvisitContainers(podSpec, func(container *corev1.Container) {\n\t\tif container.SecurityContext != nil \u0026\u0026 container.SecurityContext.RunAsUser != nil \u0026\u0026 *container.SecurityContext.RunAsUser == 0 {\n\t\t\texplicitlyBadContainers = append(explicitlyBadContainers, container.Name)\n\t\t}\n\t})\n\n\tif len(explicitlyBadContainers) \u003e 0 {\n\t\tbadSetters = append(\n\t\t\tbadSetters,\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"%s %s\",\n\t\t\t\tpluralize(\"container\", \"containers\", len(explicitlyBadContainers)),\n\t\t\t\tjoinQuote(explicitlyBadContainers),\n\t\t\t),\n\t\t)\n\t}\n\t// pod or containers explicitly set runAsUser=0\n\tif len(badSetters) \u003e 0 {\n\t\treturn CheckResult{\n\t\t\tAllowed: false,\n\t\t\tForbiddenReason: \"runAsUser=0\",\n\t\t\tForbiddenDetail: fmt.Sprintf(\"%s must not set runAsUser=0\", strings.Join(badSetters, \" and \")),\n\t\t}\n\t}\n\n\treturn CheckResult{Allowed: true}\n}","line":{"from":62,"to":99}} {"id":100035099,"name":"init","signature":"func init()","file":"staging/src/k8s.io/pod-security-admission/policy/check_seLinuxOptions.go","code":"func init() {\n\taddCheck(CheckSELinuxOptions)\n}","line":{"from":54,"to":56}} {"id":100035100,"name":"CheckSELinuxOptions","signature":"func CheckSELinuxOptions() Check","file":"staging/src/k8s.io/pod-security-admission/policy/check_seLinuxOptions.go","code":"// CheckSELinuxOptions returns a baseline level check\n// that limits seLinuxOptions type, user, and role values in 1.0+\nfunc CheckSELinuxOptions() Check {\n\treturn Check{\n\t\tID: \"seLinuxOptions\",\n\t\tLevel: api.LevelBaseline,\n\t\tVersions: []VersionedCheck{\n\t\t\t{\n\t\t\t\tMinimumVersion: api.MajorMinorVersion(1, 0),\n\t\t\t\tCheckPod: seLinuxOptions_1_0,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":58,"to":71}} {"id":100035101,"name":"seLinuxOptions_1_0","signature":"func seLinuxOptions_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult","file":"staging/src/k8s.io/pod-security-admission/policy/check_seLinuxOptions.go","code":"func seLinuxOptions_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {\n\tvar (\n\t\t// sources that set bad seLinuxOptions\n\t\tbadSetters []string\n\n\t\t// invalid type values set\n\t\tbadTypes = sets.NewString()\n\t\t// was user set?\n\t\tsetUser = false\n\t\t// was role set?\n\t\tsetRole = false\n\t)\n\n\tvalidSELinuxOptions := func(opts *corev1.SELinuxOptions) bool {\n\t\tvalid := true\n\t\tif !selinux_allowed_types_1_0.Has(opts.Type) {\n\t\t\tvalid = false\n\t\t\tbadTypes.Insert(opts.Type)\n\t\t}\n\t\tif len(opts.User) \u003e 0 {\n\t\t\tvalid = false\n\t\t\tsetUser = true\n\t\t}\n\t\tif len(opts.Role) \u003e 0 {\n\t\t\tvalid = false\n\t\t\tsetRole = true\n\t\t}\n\t\treturn valid\n\t}\n\n\tif podSpec.SecurityContext != nil \u0026\u0026 podSpec.SecurityContext.SELinuxOptions != nil {\n\t\tif !validSELinuxOptions(podSpec.SecurityContext.SELinuxOptions) {\n\t\t\tbadSetters = append(badSetters, \"pod\")\n\t\t}\n\t}\n\n\tvar badContainers []string\n\tvisitContainers(podSpec, func(container *corev1.Container) {\n\t\tif container.SecurityContext != nil \u0026\u0026 container.SecurityContext.SELinuxOptions != nil {\n\t\t\tif !validSELinuxOptions(container.SecurityContext.SELinuxOptions) {\n\t\t\t\tbadContainers = append(badContainers, container.Name)\n\t\t\t}\n\t\t}\n\t})\n\tif len(badContainers) \u003e 0 {\n\t\tbadSetters = append(\n\t\t\tbadSetters,\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"%s %s\",\n\t\t\t\tpluralize(\"container\", \"containers\", len(badContainers)),\n\t\t\t\tjoinQuote(badContainers),\n\t\t\t),\n\t\t)\n\t}\n\n\tif len(badSetters) \u003e 0 {\n\t\tvar badData []string\n\t\tif len(badTypes) \u003e 0 {\n\t\t\tbadData = append(badData, fmt.Sprintf(\n\t\t\t\t\"%s %s\",\n\t\t\t\tpluralize(\"type\", \"types\", len(badTypes)),\n\t\t\t\tjoinQuote(badTypes.List()),\n\t\t\t))\n\t\t}\n\t\tif setUser {\n\t\t\tbadData = append(badData, \"user may not be set\")\n\t\t}\n\t\tif setRole {\n\t\t\tbadData = append(badData, \"role may not be set\")\n\t\t}\n\n\t\treturn CheckResult{\n\t\t\tAllowed: false,\n\t\t\tForbiddenReason: \"seLinuxOptions\",\n\t\t\tForbiddenDetail: fmt.Sprintf(\n\t\t\t\t`%s set forbidden securityContext.seLinuxOptions: %s`,\n\t\t\t\tstrings.Join(badSetters, \" and \"),\n\t\t\t\tstrings.Join(badData, \"; \"),\n\t\t\t),\n\t\t}\n\t}\n\treturn CheckResult{Allowed: true}\n}","line":{"from":77,"to":159}} {"id":100035102,"name":"init","signature":"func init()","file":"staging/src/k8s.io/pod-security-admission/policy/check_seccompProfile_baseline.go","code":"func init() {\n\taddCheck(CheckSeccompBaseline)\n}","line":{"from":54,"to":56}} {"id":100035103,"name":"CheckSeccompBaseline","signature":"func CheckSeccompBaseline() Check","file":"staging/src/k8s.io/pod-security-admission/policy/check_seccompProfile_baseline.go","code":"func CheckSeccompBaseline() Check {\n\treturn Check{\n\t\tID: checkSeccompBaselineID,\n\t\tLevel: api.LevelBaseline,\n\t\tVersions: []VersionedCheck{\n\t\t\t{\n\t\t\t\tMinimumVersion: api.MajorMinorVersion(1, 0),\n\t\t\t\tCheckPod: seccompProfileBaseline_1_0,\n\t\t\t},\n\t\t\t{\n\t\t\t\tMinimumVersion: api.MajorMinorVersion(1, 19),\n\t\t\t\tCheckPod: seccompProfileBaseline_1_19,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":58,"to":73}} {"id":100035104,"name":"validSeccomp","signature":"func validSeccomp(t corev1.SeccompProfileType) bool","file":"staging/src/k8s.io/pod-security-admission/policy/check_seccompProfile_baseline.go","code":"func validSeccomp(t corev1.SeccompProfileType) bool {\n\treturn t == corev1.SeccompProfileTypeLocalhost ||\n\t\tt == corev1.SeccompProfileTypeRuntimeDefault\n}","line":{"from":75,"to":78}} {"id":100035105,"name":"validSeccompAnnotationValue","signature":"func validSeccompAnnotationValue(v string) bool","file":"staging/src/k8s.io/pod-security-admission/policy/check_seccompProfile_baseline.go","code":"func validSeccompAnnotationValue(v string) bool {\n\treturn v == corev1.SeccompProfileRuntimeDefault ||\n\t\tv == corev1.DeprecatedSeccompProfileDockerDefault ||\n\t\tstrings.HasPrefix(v, corev1.SeccompLocalhostProfileNamePrefix)\n}","line":{"from":80,"to":84}} {"id":100035106,"name":"seccompProfileBaseline_1_0","signature":"func seccompProfileBaseline_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult","file":"staging/src/k8s.io/pod-security-admission/policy/check_seccompProfile_baseline.go","code":"// seccompProfileBaseline_1_0 checks baseline policy on seccomp alpha annotation\nfunc seccompProfileBaseline_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {\n\tforbidden := sets.NewString()\n\n\tif val, ok := podMetadata.Annotations[annotationKeyPod]; ok {\n\t\tif !validSeccompAnnotationValue(val) {\n\t\t\tforbidden.Insert(fmt.Sprintf(\"%s=%q\", annotationKeyPod, val))\n\t\t}\n\t}\n\n\tvisitContainers(podSpec, func(c *corev1.Container) {\n\t\tannotation := annotationKeyContainerPrefix + c.Name\n\t\tif val, ok := podMetadata.Annotations[annotation]; ok {\n\t\t\tif !validSeccompAnnotationValue(val) {\n\t\t\t\tforbidden.Insert(fmt.Sprintf(\"%s=%q\", annotation, val))\n\t\t\t}\n\t\t}\n\t})\n\n\tif len(forbidden) \u003e 0 {\n\t\treturn CheckResult{\n\t\t\tAllowed: false,\n\t\t\tForbiddenReason: \"seccompProfile\",\n\t\t\tForbiddenDetail: fmt.Sprintf(\n\t\t\t\t\"forbidden %s %s\",\n\t\t\t\tpluralize(\"annotation\", \"annotations\", len(forbidden)),\n\t\t\t\tstrings.Join(forbidden.List(), \", \"),\n\t\t\t),\n\t\t}\n\t}\n\n\treturn CheckResult{Allowed: true}\n}","line":{"from":86,"to":118}} {"id":100035107,"name":"seccompProfileBaseline_1_19","signature":"func seccompProfileBaseline_1_19(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult","file":"staging/src/k8s.io/pod-security-admission/policy/check_seccompProfile_baseline.go","code":"// seccompProfileBaseline_1_19 checks baseline policy on securityContext.seccompProfile field\nfunc seccompProfileBaseline_1_19(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {\n\t// things that explicitly set seccompProfile.type to a bad value\n\tvar badSetters []string\n\tbadValues := sets.NewString()\n\n\tif podSpec.SecurityContext != nil \u0026\u0026 podSpec.SecurityContext.SeccompProfile != nil {\n\t\tif !validSeccomp(podSpec.SecurityContext.SeccompProfile.Type) {\n\t\t\tbadSetters = append(badSetters, \"pod\")\n\t\t\tbadValues.Insert(string(podSpec.SecurityContext.SeccompProfile.Type))\n\t\t}\n\t}\n\n\t// containers that explicitly set seccompProfile.type to a bad value\n\tvar explicitlyBadContainers []string\n\n\tvisitContainers(podSpec, func(c *corev1.Container) {\n\t\tif c.SecurityContext != nil \u0026\u0026 c.SecurityContext.SeccompProfile != nil {\n\t\t\t// container explicitly set seccompProfile\n\t\t\tif !validSeccomp(c.SecurityContext.SeccompProfile.Type) {\n\t\t\t\t// container explicitly set seccompProfile to a bad value\n\t\t\t\texplicitlyBadContainers = append(explicitlyBadContainers, c.Name)\n\t\t\t\tbadValues.Insert(string(c.SecurityContext.SeccompProfile.Type))\n\t\t\t}\n\t\t}\n\t})\n\n\tif len(explicitlyBadContainers) \u003e 0 {\n\t\tbadSetters = append(\n\t\t\tbadSetters,\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"%s %s\",\n\t\t\t\tpluralize(\"container\", \"containers\", len(explicitlyBadContainers)),\n\t\t\t\tjoinQuote(explicitlyBadContainers),\n\t\t\t),\n\t\t)\n\t}\n\t// pod or containers explicitly set bad seccompProfiles\n\tif len(badSetters) \u003e 0 {\n\t\treturn CheckResult{\n\t\t\tAllowed: false,\n\t\t\tForbiddenReason: \"seccompProfile\",\n\t\t\tForbiddenDetail: fmt.Sprintf(\n\t\t\t\t\"%s must not set securityContext.seccompProfile.type to %s\",\n\t\t\t\tstrings.Join(badSetters, \" and \"),\n\t\t\t\tjoinQuote(badValues.List()),\n\t\t\t),\n\t\t}\n\t}\n\n\treturn CheckResult{Allowed: true}\n}","line":{"from":120,"to":171}} {"id":100035108,"name":"init","signature":"func init()","file":"staging/src/k8s.io/pod-security-admission/policy/check_seccompProfile_restricted.go","code":"func init() {\n\taddCheck(CheckSeccompProfileRestricted)\n}","line":{"from":44,"to":46}} {"id":100035109,"name":"CheckSeccompProfileRestricted","signature":"func CheckSeccompProfileRestricted() Check","file":"staging/src/k8s.io/pod-security-admission/policy/check_seccompProfile_restricted.go","code":"func CheckSeccompProfileRestricted() Check {\n\treturn Check{\n\t\tID: \"seccompProfile_restricted\",\n\t\tLevel: api.LevelRestricted,\n\t\tVersions: []VersionedCheck{\n\t\t\t{\n\t\t\t\tMinimumVersion: api.MajorMinorVersion(1, 19),\n\t\t\t\tCheckPod: seccompProfileRestricted_1_19,\n\t\t\t\tOverrideCheckIDs: []CheckID{checkSeccompBaselineID},\n\t\t\t},\n\t\t\t// Starting 1.25, windows pods would be exempted from this check using pod.spec.os field when set to windows.\n\t\t\t{\n\t\t\t\tMinimumVersion: api.MajorMinorVersion(1, 25),\n\t\t\t\tCheckPod: seccompProfileRestricted_1_25,\n\t\t\t\tOverrideCheckIDs: []CheckID{checkSeccompBaselineID},\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":48,"to":66}} {"id":100035110,"name":"seccompProfileRestricted_1_19","signature":"func seccompProfileRestricted_1_19(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult","file":"staging/src/k8s.io/pod-security-admission/policy/check_seccompProfile_restricted.go","code":"// seccompProfileRestricted_1_19 checks restricted policy on securityContext.seccompProfile field\nfunc seccompProfileRestricted_1_19(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {\n\t// things that explicitly set seccompProfile.type to a bad value\n\tvar badSetters []string\n\tbadValues := sets.NewString()\n\n\tpodSeccompSet := false\n\n\tif podSpec.SecurityContext != nil \u0026\u0026 podSpec.SecurityContext.SeccompProfile != nil {\n\t\tif !validSeccomp(podSpec.SecurityContext.SeccompProfile.Type) {\n\t\t\tbadSetters = append(badSetters, \"pod\")\n\t\t\tbadValues.Insert(string(podSpec.SecurityContext.SeccompProfile.Type))\n\t\t} else {\n\t\t\tpodSeccompSet = true\n\t\t}\n\t}\n\n\t// containers that explicitly set seccompProfile.type to a bad value\n\tvar explicitlyBadContainers []string\n\t// containers that didn't set seccompProfile and aren't caught by a pod-level seccompProfile\n\tvar implicitlyBadContainers []string\n\n\tvisitContainers(podSpec, func(c *corev1.Container) {\n\t\tif c.SecurityContext != nil \u0026\u0026 c.SecurityContext.SeccompProfile != nil {\n\t\t\t// container explicitly set seccompProfile\n\t\t\tif !validSeccomp(c.SecurityContext.SeccompProfile.Type) {\n\t\t\t\t// container explicitly set seccompProfile to a bad value\n\t\t\t\texplicitlyBadContainers = append(explicitlyBadContainers, c.Name)\n\t\t\t\tbadValues.Insert(string(c.SecurityContext.SeccompProfile.Type))\n\t\t\t}\n\t\t} else {\n\t\t\t// container did not explicitly set seccompProfile\n\t\t\tif !podSeccompSet {\n\t\t\t\t// no valid pod-level seccompProfile, so this container implicitly has a bad value\n\t\t\t\timplicitlyBadContainers = append(implicitlyBadContainers, c.Name)\n\t\t\t}\n\t\t}\n\t})\n\n\tif len(explicitlyBadContainers) \u003e 0 {\n\t\tbadSetters = append(\n\t\t\tbadSetters,\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"%s %s\",\n\t\t\t\tpluralize(\"container\", \"containers\", len(explicitlyBadContainers)),\n\t\t\t\tjoinQuote(explicitlyBadContainers),\n\t\t\t),\n\t\t)\n\t}\n\t// pod or containers explicitly set bad seccompProfiles\n\tif len(badSetters) \u003e 0 {\n\t\treturn CheckResult{\n\t\t\tAllowed: false,\n\t\t\tForbiddenReason: \"seccompProfile\",\n\t\t\tForbiddenDetail: fmt.Sprintf(\n\t\t\t\t\"%s must not set securityContext.seccompProfile.type to %s\",\n\t\t\t\tstrings.Join(badSetters, \" and \"),\n\t\t\t\tjoinQuote(badValues.List()),\n\t\t\t),\n\t\t}\n\t}\n\n\t// pod didn't set seccompProfile and not all containers opted into seccompProfile\n\tif len(implicitlyBadContainers) \u003e 0 {\n\t\treturn CheckResult{\n\t\t\tAllowed: false,\n\t\t\tForbiddenReason: \"seccompProfile\",\n\t\t\tForbiddenDetail: fmt.Sprintf(\n\t\t\t\t`pod or %s %s must set securityContext.seccompProfile.type to \"RuntimeDefault\" or \"Localhost\"`,\n\t\t\t\tpluralize(\"container\", \"containers\", len(implicitlyBadContainers)),\n\t\t\t\tjoinQuote(implicitlyBadContainers),\n\t\t\t),\n\t\t}\n\t}\n\n\treturn CheckResult{Allowed: true}\n}","line":{"from":68,"to":144}} {"id":100035111,"name":"seccompProfileRestricted_1_25","signature":"func seccompProfileRestricted_1_25(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult","file":"staging/src/k8s.io/pod-security-admission/policy/check_seccompProfile_restricted.go","code":"// seccompProfileRestricted_1_25 checks restricted policy on securityContext.seccompProfile field for kubernetes\n// version 1.25 and above\nfunc seccompProfileRestricted_1_25(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {\n\t// Pod API validation would have failed if podOS == Windows and if secCompProfile has been set.\n\t// We can admit the Windows pod even if seccompProfile has not been set.\n\tif podSpec.OS != nil \u0026\u0026 podSpec.OS.Name == corev1.Windows {\n\t\treturn CheckResult{Allowed: true}\n\t}\n\treturn seccompProfileRestricted_1_19(podMetadata, podSpec)\n}","line":{"from":146,"to":155}} {"id":100035112,"name":"init","signature":"func init()","file":"staging/src/k8s.io/pod-security-admission/policy/check_sysctls.go","code":"func init() {\n\taddCheck(CheckSysctls)\n}","line":{"from":49,"to":51}} {"id":100035113,"name":"CheckSysctls","signature":"func CheckSysctls() Check","file":"staging/src/k8s.io/pod-security-admission/policy/check_sysctls.go","code":"// CheckSysctls returns a baseline level check\n// that limits the value of sysctls in 1.0+\nfunc CheckSysctls() Check {\n\treturn Check{\n\t\tID: \"sysctls\",\n\t\tLevel: api.LevelBaseline,\n\t\tVersions: []VersionedCheck{\n\t\t\t{\n\t\t\t\tMinimumVersion: api.MajorMinorVersion(1, 0),\n\t\t\t\tCheckPod: sysctls_1_0,\n\t\t\t},\n\t\t\t{\n\t\t\t\tMinimumVersion: api.MajorMinorVersion(1, 27),\n\t\t\t\tCheckPod: sysctls_1_27,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":53,"to":70}} {"id":100035114,"name":"sysctls_1_0","signature":"func sysctls_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult","file":"staging/src/k8s.io/pod-security-admission/policy/check_sysctls.go","code":"func sysctls_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {\n\treturn sysctls(podMetadata, podSpec, sysctls_allowed_1_0)\n}","line":{"from":90,"to":92}} {"id":100035115,"name":"sysctls_1_27","signature":"func sysctls_1_27(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult","file":"staging/src/k8s.io/pod-security-admission/policy/check_sysctls.go","code":"func sysctls_1_27(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {\n\treturn sysctls(podMetadata, podSpec, sysctls_allowed_1_27)\n}","line":{"from":94,"to":96}} {"id":100035116,"name":"sysctls","signature":"func sysctls(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec, sysctls_allowed_set sets.String) CheckResult","file":"staging/src/k8s.io/pod-security-admission/policy/check_sysctls.go","code":"func sysctls(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec, sysctls_allowed_set sets.String) CheckResult {\n\tvar forbiddenSysctls []string\n\n\tif podSpec.SecurityContext != nil {\n\t\tfor _, sysctl := range podSpec.SecurityContext.Sysctls {\n\t\t\tif !sysctls_allowed_set.Has(sysctl.Name) {\n\t\t\t\tforbiddenSysctls = append(forbiddenSysctls, sysctl.Name)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(forbiddenSysctls) \u003e 0 {\n\t\treturn CheckResult{\n\t\t\tAllowed: false,\n\t\t\tForbiddenReason: \"forbidden sysctls\",\n\t\t\tForbiddenDetail: strings.Join(forbiddenSysctls, \", \"),\n\t\t}\n\t}\n\treturn CheckResult{Allowed: true}\n}","line":{"from":98,"to":117}} {"id":100035117,"name":"init","signature":"func init()","file":"staging/src/k8s.io/pod-security-admission/policy/check_windowsHostProcess.go","code":"func init() {\n\taddCheck(CheckWindowsHostProcess)\n}","line":{"from":40,"to":42}} {"id":100035118,"name":"CheckWindowsHostProcess","signature":"func CheckWindowsHostProcess() Check","file":"staging/src/k8s.io/pod-security-admission/policy/check_windowsHostProcess.go","code":"// CheckWindowsHostProcess returns a baseline level check\n// that forbids hostProcess=true in 1.0+\nfunc CheckWindowsHostProcess() Check {\n\treturn Check{\n\t\tID: \"windowsHostProcess\",\n\t\tLevel: api.LevelBaseline,\n\t\tVersions: []VersionedCheck{\n\t\t\t{\n\t\t\t\tMinimumVersion: api.MajorMinorVersion(1, 0),\n\t\t\t\tCheckPod: windowsHostProcess_1_0,\n\t\t\t},\n\t\t},\n\t}\n}","line":{"from":44,"to":57}} {"id":100035119,"name":"windowsHostProcess_1_0","signature":"func windowsHostProcess_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult","file":"staging/src/k8s.io/pod-security-admission/policy/check_windowsHostProcess.go","code":"func windowsHostProcess_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {\n\tvar badContainers []string\n\tvisitContainers(podSpec, func(container *corev1.Container) {\n\t\tif container.SecurityContext != nil \u0026\u0026\n\t\t\tcontainer.SecurityContext.WindowsOptions != nil \u0026\u0026\n\t\t\tcontainer.SecurityContext.WindowsOptions.HostProcess != nil \u0026\u0026\n\t\t\t*container.SecurityContext.WindowsOptions.HostProcess {\n\t\t\tbadContainers = append(badContainers, container.Name)\n\t\t}\n\t})\n\n\tpodSpecForbidden := false\n\tif podSpec.SecurityContext != nil \u0026\u0026\n\t\tpodSpec.SecurityContext.WindowsOptions != nil \u0026\u0026\n\t\tpodSpec.SecurityContext.WindowsOptions.HostProcess != nil \u0026\u0026\n\t\t*podSpec.SecurityContext.WindowsOptions.HostProcess {\n\t\tpodSpecForbidden = true\n\t}\n\n\t// pod or containers explicitly set hostProcess=true\n\tvar forbiddenSetters []string\n\tif podSpecForbidden {\n\t\tforbiddenSetters = append(forbiddenSetters, \"pod\")\n\t}\n\tif len(badContainers) \u003e 0 {\n\t\tforbiddenSetters = append(\n\t\t\tforbiddenSetters,\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"%s %s\",\n\t\t\t\tpluralize(\"container\", \"containers\", len(badContainers)),\n\t\t\t\tjoinQuote(badContainers),\n\t\t\t),\n\t\t)\n\t}\n\tif len(forbiddenSetters) \u003e 0 {\n\t\treturn CheckResult{\n\t\t\tAllowed: false,\n\t\t\tForbiddenReason: \"hostProcess\",\n\t\t\tForbiddenDetail: fmt.Sprintf(\"%s must not set securityContext.windowsOptions.hostProcess=true\", strings.Join(forbiddenSetters, \" and \")),\n\t\t}\n\t}\n\n\treturn CheckResult{Allowed: true}\n}","line":{"from":59,"to":102}} {"id":100035120,"name":"ForbiddenReason","signature":"func (a *AggregateCheckResult) ForbiddenReason() string","file":"staging/src/k8s.io/pod-security-admission/policy/checks.go","code":"// ForbiddenReason returns a comma-separated string of of the forbidden reasons.\n// Example: host ports, privileged containers, non-default capabilities\nfunc (a *AggregateCheckResult) ForbiddenReason() string {\n\treturn strings.Join(a.ForbiddenReasons, \", \")\n}","line":{"from":97,"to":101}} {"id":100035121,"name":"ForbiddenDetail","signature":"func (a *AggregateCheckResult) ForbiddenDetail() string","file":"staging/src/k8s.io/pod-security-admission/policy/checks.go","code":"// ForbiddenDetail returns a detailed forbidden message, with non-empty details formatted in\n// parentheses with the associated reason.\n// Example: host ports (8080, 9090), privileged containers, non-default capabilities (NET_RAW)\nfunc (a *AggregateCheckResult) ForbiddenDetail() string {\n\tvar b strings.Builder\n\tfor i := 0; i \u003c len(a.ForbiddenReasons); i++ {\n\t\tb.WriteString(a.ForbiddenReasons[i])\n\t\tif a.ForbiddenDetails[i] != \"\" {\n\t\t\tb.WriteString(\" (\")\n\t\t\tb.WriteString(a.ForbiddenDetails[i])\n\t\t\tb.WriteString(\")\")\n\t\t}\n\t\tif i != len(a.ForbiddenReasons)-1 {\n\t\t\tb.WriteString(\", \")\n\t\t}\n\t}\n\treturn b.String()\n}","line":{"from":103,"to":120}} {"id":100035122,"name":"AggregateCheckResults","signature":"func AggregateCheckResults(results []CheckResult) AggregateCheckResult","file":"staging/src/k8s.io/pod-security-admission/policy/checks.go","code":"// AggregateCheckPod runs all the checks and aggregates the forbidden results into a single CheckResult.\n// The aggregated reason is a comma-separated\nfunc AggregateCheckResults(results []CheckResult) AggregateCheckResult {\n\tvar (\n\t\treasons []string\n\t\tdetails []string\n\t)\n\tfor _, result := range results {\n\t\tif !result.Allowed {\n\t\t\tif len(result.ForbiddenReason) == 0 {\n\t\t\t\treasons = append(reasons, UnknownForbiddenReason)\n\t\t\t} else {\n\t\t\t\treasons = append(reasons, result.ForbiddenReason)\n\t\t\t}\n\t\t\tdetails = append(details, result.ForbiddenDetail)\n\t\t}\n\t}\n\treturn AggregateCheckResult{\n\t\tAllowed: len(reasons) == 0,\n\t\tForbiddenReasons: reasons,\n\t\tForbiddenDetails: details,\n\t}\n}","line":{"from":125,"to":147}} {"id":100035123,"name":"addCheck","signature":"func addCheck(f func() Check)","file":"staging/src/k8s.io/pod-security-admission/policy/checks.go","code":"func addCheck(f func() Check) {\n\t// add to experimental or versioned list\n\tc := f()\n\tif len(c.Versions) == 1 \u0026\u0026 c.Versions[0].MinimumVersion == (api.Version{}) {\n\t\texperimentalChecks = append(experimentalChecks, f)\n\t} else {\n\t\tdefaultChecks = append(defaultChecks, f)\n\t}\n}","line":{"from":154,"to":162}} {"id":100035124,"name":"DefaultChecks","signature":"func DefaultChecks() []Check","file":"staging/src/k8s.io/pod-security-admission/policy/checks.go","code":"// DefaultChecks returns checks that are expected to be enabled by default.\n// The results are mutually exclusive with ExperimentalChecks.\n// It returns a new copy of checks on each invocation and is expected to be called once at setup time.\nfunc DefaultChecks() []Check {\n\tretval := make([]Check, 0, len(defaultChecks))\n\tfor _, f := range defaultChecks {\n\t\tretval = append(retval, f())\n\t}\n\treturn retval\n}","line":{"from":164,"to":173}} {"id":100035125,"name":"ExperimentalChecks","signature":"func ExperimentalChecks() []Check","file":"staging/src/k8s.io/pod-security-admission/policy/checks.go","code":"// ExperimentalChecks returns checks that have not yet been assigned to policy versions.\n// The results are mutually exclusive with DefaultChecks.\n// It returns a new copy of checks on each invocation and is expected to be called once at setup time.\nfunc ExperimentalChecks() []Check {\n\tretval := make([]Check, 0, len(experimentalChecks))\n\tfor _, f := range experimentalChecks {\n\t\tretval = append(retval, f())\n\t}\n\treturn retval\n}","line":{"from":175,"to":184}} {"id":100035126,"name":"joinQuote","signature":"func joinQuote(items []string) string","file":"staging/src/k8s.io/pod-security-admission/policy/helpers.go","code":"func joinQuote(items []string) string {\n\tif len(items) == 0 {\n\t\treturn \"\"\n\t}\n\treturn `\"` + strings.Join(items, `\", \"`) + `\"`\n}","line":{"from":21,"to":26}} {"id":100035127,"name":"pluralize","signature":"func pluralize(singular, plural string, count int) string","file":"staging/src/k8s.io/pod-security-admission/policy/helpers.go","code":"func pluralize(singular, plural string, count int) string {\n\tif count == 1 {\n\t\treturn singular\n\t}\n\treturn plural\n}","line":{"from":28,"to":33}} {"id":100035128,"name":"NewEvaluator","signature":"func NewEvaluator(checks []Check) (Evaluator, error)","file":"staging/src/k8s.io/pod-security-admission/policy/registry.go","code":"// NewEvaluator constructs a new Evaluator instance from the list of checks. If the provided checks are invalid,\n// an error is returned. A valid list of checks must meet the following requirements:\n// 1. Check.ID is unique in the list\n// 2. Check.Level must be either Baseline or Restricted\n// 3. Checks must have a non-empty set of versions, sorted in a strictly increasing order\n// 4. Check.Versions cannot include 'latest'\nfunc NewEvaluator(checks []Check) (Evaluator, error) {\n\tif err := validateChecks(checks); err != nil {\n\t\treturn nil, err\n\t}\n\tr := \u0026checkRegistry{\n\t\tbaselineChecks: map[api.Version][]CheckPodFn{},\n\t\trestrictedChecks: map[api.Version][]CheckPodFn{},\n\t}\n\tpopulate(r, checks)\n\treturn r, nil\n}","line":{"from":43,"to":59}} {"id":100035129,"name":"EvaluatePod","signature":"func (r *checkRegistry) EvaluatePod(lv api.LevelVersion, podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) []CheckResult","file":"staging/src/k8s.io/pod-security-admission/policy/registry.go","code":"func (r *checkRegistry) EvaluatePod(lv api.LevelVersion, podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) []CheckResult {\n\tif lv.Level == api.LevelPrivileged {\n\t\treturn nil\n\t}\n\tif r.maxVersion.Older(lv.Version) {\n\t\tlv.Version = r.maxVersion\n\t}\n\n\tvar checks []CheckPodFn\n\tif lv.Level == api.LevelBaseline {\n\t\tchecks = r.baselineChecks[lv.Version]\n\t} else {\n\t\t// includes non-overridden baseline checks\n\t\tchecks = r.restrictedChecks[lv.Version]\n\t}\n\n\tvar results []CheckResult\n\tfor _, check := range checks {\n\t\tresults = append(results, check(podMetadata, podSpec))\n\t}\n\treturn results\n}","line":{"from":61,"to":82}} {"id":100035130,"name":"validateChecks","signature":"func validateChecks(checks []Check) error","file":"staging/src/k8s.io/pod-security-admission/policy/registry.go","code":"func validateChecks(checks []Check) error {\n\tids := map[CheckID]api.Level{}\n\tfor _, check := range checks {\n\t\tif _, ok := ids[check.ID]; ok {\n\t\t\treturn fmt.Errorf(\"multiple checks registered for ID %s\", check.ID)\n\t\t}\n\t\tids[check.ID] = check.Level\n\t\tif check.Level != api.LevelBaseline \u0026\u0026 check.Level != api.LevelRestricted {\n\t\t\treturn fmt.Errorf(\"check %s: invalid level %s\", check.ID, check.Level)\n\t\t}\n\t\tif len(check.Versions) == 0 {\n\t\t\treturn fmt.Errorf(\"check %s: empty\", check.ID)\n\t\t}\n\t\tmaxVersion := api.Version{}\n\t\tfor _, c := range check.Versions {\n\t\t\tif c.MinimumVersion == (api.Version{}) {\n\t\t\t\treturn fmt.Errorf(\"check %s: undefined version found\", check.ID)\n\t\t\t}\n\t\t\tif c.MinimumVersion.Latest() {\n\t\t\t\treturn fmt.Errorf(\"check %s: version cannot be 'latest'\", check.ID)\n\t\t\t}\n\t\t\tif maxVersion == c.MinimumVersion {\n\t\t\t\treturn fmt.Errorf(\"check %s: duplicate version %s\", check.ID, c.MinimumVersion)\n\t\t\t}\n\t\t\tif !maxVersion.Older(c.MinimumVersion) {\n\t\t\t\treturn fmt.Errorf(\"check %s: versions must be strictly increasing\", check.ID)\n\t\t\t}\n\t\t\tmaxVersion = c.MinimumVersion\n\t\t}\n\t}\n\t// Second pass to validate overrides.\n\tfor _, check := range checks {\n\t\tfor _, c := range check.Versions {\n\t\t\tif len(c.OverrideCheckIDs) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif check.Level != api.LevelRestricted {\n\t\t\t\treturn fmt.Errorf(\"check %s: only restricted checks may set overrides\", check.ID)\n\t\t\t}\n\t\t\tfor _, override := range c.OverrideCheckIDs {\n\t\t\t\tif overriddenLevel, ok := ids[override]; ok \u0026\u0026 overriddenLevel != api.LevelBaseline {\n\t\t\t\t\treturn fmt.Errorf(\"check %s: overrides %s check %s\", check.ID, overriddenLevel, override)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}","line":{"from":84,"to":132}} {"id":100035131,"name":"populate","signature":"func populate(r *checkRegistry, validChecks []Check)","file":"staging/src/k8s.io/pod-security-admission/policy/registry.go","code":"func populate(r *checkRegistry, validChecks []Check) {\n\t// Find the max(MinimumVersion) across all checks.\n\tfor _, c := range validChecks {\n\t\tlastVersion := c.Versions[len(c.Versions)-1].MinimumVersion\n\t\tif r.maxVersion.Older(lastVersion) {\n\t\t\tr.maxVersion = lastVersion\n\t\t}\n\t}\n\n\tvar (\n\t\trestrictedVersionedChecks = map[api.Version]map[CheckID]VersionedCheck{}\n\t\tbaselineVersionedChecks = map[api.Version]map[CheckID]VersionedCheck{}\n\n\t\tbaselineIDs, restrictedIDs []CheckID\n\t)\n\tfor _, c := range validChecks {\n\t\tif c.Level == api.LevelRestricted {\n\t\t\trestrictedIDs = append(restrictedIDs, c.ID)\n\t\t\tinflateVersions(c, restrictedVersionedChecks, r.maxVersion)\n\t\t} else {\n\t\t\tbaselineIDs = append(baselineIDs, c.ID)\n\t\t\tinflateVersions(c, baselineVersionedChecks, r.maxVersion)\n\t\t}\n\t}\n\n\t// Sort the IDs to maintain consistent error messages.\n\tsort.Slice(restrictedIDs, func(i, j int) bool { return restrictedIDs[i] \u003c restrictedIDs[j] })\n\tsort.Slice(baselineIDs, func(i, j int) bool { return baselineIDs[i] \u003c baselineIDs[j] })\n\torderedIDs := append(baselineIDs, restrictedIDs...) // Baseline checks first, then restricted.\n\n\tfor v := api.MajorMinorVersion(1, 0); v.Older(nextMinor(r.maxVersion)); v = nextMinor(v) {\n\t\t// Aggregate all the overridden baseline check ids.\n\t\toverrides := map[CheckID]bool{}\n\t\tfor _, c := range restrictedVersionedChecks[v] {\n\t\t\tfor _, override := range c.OverrideCheckIDs {\n\t\t\t\toverrides[override] = true\n\t\t\t}\n\t\t}\n\t\t// Add the filtered baseline checks to restricted.\n\t\tfor id, c := range baselineVersionedChecks[v] {\n\t\t\tif overrides[id] {\n\t\t\t\tcontinue // Overridden check: skip it.\n\t\t\t}\n\t\t\tif restrictedVersionedChecks[v] == nil {\n\t\t\t\trestrictedVersionedChecks[v] = map[CheckID]VersionedCheck{}\n\t\t\t}\n\t\t\trestrictedVersionedChecks[v][id] = c\n\t\t}\n\n\t\tr.restrictedChecks[v] = mapCheckPodFns(restrictedVersionedChecks[v], orderedIDs)\n\t\tr.baselineChecks[v] = mapCheckPodFns(baselineVersionedChecks[v], orderedIDs)\n\t}\n}","line":{"from":134,"to":186}} {"id":100035132,"name":"inflateVersions","signature":"func inflateVersions(check Check, versions map[api.Version]map[CheckID]VersionedCheck, maxVersion api.Version)","file":"staging/src/k8s.io/pod-security-admission/policy/registry.go","code":"func inflateVersions(check Check, versions map[api.Version]map[CheckID]VersionedCheck, maxVersion api.Version) {\n\tfor i, c := range check.Versions {\n\t\tvar nextVersion api.Version\n\t\tif i+1 \u003c len(check.Versions) {\n\t\t\tnextVersion = check.Versions[i+1].MinimumVersion\n\t\t} else {\n\t\t\t// Assumes only 1 Major version.\n\t\t\tnextVersion = nextMinor(maxVersion)\n\t\t}\n\t\t// Iterate over all versions from the minimum of the current check, to the minimum of the\n\t\t// next check, or the maxVersion++.\n\t\tfor v := c.MinimumVersion; v.Older(nextVersion); v = nextMinor(v) {\n\t\t\tif versions[v] == nil {\n\t\t\t\tversions[v] = map[CheckID]VersionedCheck{}\n\t\t\t}\n\t\t\tversions[v][check.ID] = check.Versions[i]\n\t\t}\n\t}\n}","line":{"from":188,"to":206}} {"id":100035133,"name":"mapCheckPodFns","signature":"func mapCheckPodFns(checks map[CheckID]VersionedCheck, orderedIDs []CheckID) []CheckPodFn","file":"staging/src/k8s.io/pod-security-admission/policy/registry.go","code":"// mapCheckPodFns converts the versioned check map to an ordered slice of CheckPodFn,\n// using the order specified by orderedIDs. All checks must have a corresponding ID in orderedIDs.\nfunc mapCheckPodFns(checks map[CheckID]VersionedCheck, orderedIDs []CheckID) []CheckPodFn {\n\tfns := make([]CheckPodFn, 0, len(checks))\n\tfor _, id := range orderedIDs {\n\t\tif check, ok := checks[id]; ok {\n\t\t\tfns = append(fns, check.CheckPod)\n\t\t}\n\t}\n\treturn fns\n}","line":{"from":208,"to":218}} {"id":100035134,"name":"nextMinor","signature":"func nextMinor(v api.Version) api.Version","file":"staging/src/k8s.io/pod-security-admission/policy/registry.go","code":"// nextMinor increments the minor version\nfunc nextMinor(v api.Version) api.Version {\n\tif v.Latest() {\n\t\treturn v\n\t}\n\treturn api.MajorMinorVersion(v.Major(), v.Minor()+1)\n}","line":{"from":220,"to":226}} {"id":100035135,"name":"visitContainers","signature":"func visitContainers(podSpec *corev1.PodSpec, visitor ContainerVisitor)","file":"staging/src/k8s.io/pod-security-admission/policy/visitor.go","code":"// visitContainers invokes the visitor function for every container in the given pod spec\nfunc visitContainers(podSpec *corev1.PodSpec, visitor ContainerVisitor) {\n\tfor i := range podSpec.InitContainers {\n\t\tvisitor(\u0026podSpec.InitContainers[i])\n\t}\n\tfor i := range podSpec.Containers {\n\t\tvisitor(\u0026podSpec.Containers[i])\n\t}\n\tfor i := range podSpec.EphemeralContainers {\n\t\tvisitor((*corev1.Container)(\u0026podSpec.EphemeralContainers[i].EphemeralContainerCommon))\n\t}\n}","line":{"from":26,"to":37}}